AR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool extF80_lt_quiet( extFloat80_t a, extFloat80_t b )
{
    union { struct extFloat80M s; extFloat80_t f; } uA;
    uint_fast16_t uiA64;
    uint_fast64_t uiA0;
    union { struct extFloat80M s; extFloat80_t f; } uB;
    uint_fast16_t uiB64;
    uint_fast64_t uiB0;
    bool signA, signB;

    uA.f = a;
    uiA64 = uA.s.signExp;
    uiA0  = uA.s.signif;
    uB.f = b;
    uiB64 = uB.s.signExp;
    uiB0  = uB.s.signif;
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNExtF80UI( uiA64, uiA0 )
            || softfloat_isSigNaNExtF80UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    signA = signExtF80UI64( uiA64 );
    signB = signExtF80UI64( uiB64 );
    return
        (signA != signB)
            ? signA && (((uiA64 | uiB64) & 0x7FFF) | uiA0 | uiB0)
            : ((uiA64 != uiB64) || (uiA0 != uiB0))
                  && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 ));

}

/**** ended inlining ../../source/extF80_lt_quiet.c ****/
/**** start inlining ../../source/extF80_isSignalingNaN.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool extF80_isSignalingNaN( extFloat80_t a )
{
    union { struct extFloat80M s; extFloat80_t f; } uA;

    uA.f = a;
    return softfloat_isSigNaNExtF80UI( uA.s.signExp, uA.s.signif );

}

/**** ended inlining ../../source/extF80_isSignalingNaN.c ****/
/**** start inlining ../../source/extF80M_to_ui32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast32_t
 extF80M_to_ui32(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return extF80_to_ui32( *aPtr, roundingMode, exact );

}

#else

uint_fast32_t
 extF80M_to_ui32(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x4032 - exp;
    if ( shiftDist <= 0 ) {
        if ( sig>>32 ) goto invalid;
        if ( -32 < shiftDist ) {
            sig <<= -shiftDist;
        } else {
            if ( (uint32_t) sig ) goto invalid;
        }
    } else {
        sig = softfloat_shiftRightJam64( sig, shiftDist );
    }
    return softfloat_roundToUI32( sign, sig, roundingMode, exact );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
            ? ui32_fromNaN
            : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_ui32.c ****/
/**** start inlining ../../source/extF80M_to_ui64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast64_t
 extF80M_to_ui64(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return extF80_to_ui64( *aPtr, roundingMode, exact );

}

#else

uint_fast64_t
 extF80M_to_ui64(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    uint32_t extSig[3];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x403E - exp;
    if ( shiftDist < 0 ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                ? ui64_fromNaN
                : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    extSig[indexWord( 3, 2 )] = sig>>32;
    extSig[indexWord( 3, 1 )] = sig;
    extSig[indexWord( 3, 0 )] = 0;
    if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig );
    return softfloat_roundMToUI64( sign, extSig, roundingMode, exact );

}

#endif

/**** ended inlining ../../source/extF80M_to_ui64.c ****/
/**** start inlining ../../source/extF80M_to_i32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast32_t
 extF80M_to_i32(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return extF80_to_i32( *aPtr, roundingMode, exact );

}

#else

int_fast32_t
 extF80M_to_i32(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x4032 - exp;
    if ( shiftDist <= 0 ) {
        if ( sig>>32 ) goto invalid;
        if ( -32 < shiftDist ) {
            sig <<= -shiftDist;
        } else {
            if ( (uint32_t) sig ) goto invalid;
        }
    } else {
        sig = softfloat_shiftRightJam64( sig, shiftDist );
    }
    return softfloat_roundToI32( sign, sig, roundingMode, exact );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ? i32_fromNaN
            : sign ? i32_fromNegOverflow : i32_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_i32.c ****/
/**** start inlining ../../source/extF80M_to_i64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast64_t
 extF80M_to_i64(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return extF80_to_i64( *aPtr, roundingMode, exact );

}

#else

int_fast64_t
 extF80M_to_i64(
     const extFloat80_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    uint32_t extSig[3];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x403E - exp;
    if ( shiftDist < 0 ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                ? i64_fromNaN
                : sign ? i64_fromNegOverflow : i64_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    extSig[indexWord( 3, 2 )] = sig>>32;
    extSig[indexWord( 3, 1 )] = sig;
    extSig[indexWord( 3, 0 )] = 0;
    if ( shiftDist ) softfloat_shiftRightJam96M( extSig, shiftDist, extSig );
    return softfloat_roundMToI64( sign, extSig, roundingMode, exact );

}

#endif

/**** ended inlining ../../source/extF80M_to_i64.c ****/
/**** start inlining ../../source/extF80M_to_ui32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast32_t extF80M_to_ui32_r_minMag( const extFloat80_t *aPtr, bool exact )
{

    return extF80_to_ui32_r_minMag( *aPtr, exact );

}

#else

uint_fast32_t extF80M_to_ui32_r_minMag( const extFloat80_t *aPtr, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    bool sign;
    uint64_t shiftedSig;
    uint32_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    exp = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! sig && (exp != 0x7FFF) ) return 0;
    shiftDist = 0x403E - exp;
    if ( 64 <= shiftDist ) {
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sign = signExtF80UI64( uiA64 );
    if ( shiftDist < 0 ) {
        if ( sign || sig>>32 || (shiftDist <= -31) ) goto invalid;
        shiftedSig = (uint64_t) (uint32_t) sig<<-shiftDist;
        if ( shiftedSig>>32 ) goto invalid;
        z = shiftedSig;
    } else {
        shiftedSig = sig;
        if ( shiftDist ) shiftedSig >>= shiftDist;
        if ( shiftedSig>>32 ) goto invalid;
        z = shiftedSig;
        if ( sign && z ) goto invalid;
        if ( exact && shiftDist && ((uint64_t) z<<shiftDist != sig) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    }
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
            ? ui32_fromNaN
            : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_ui32_r_minMag.c ****/
/**** start inlining ../../source/extF80M_to_ui64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast64_t extF80M_to_ui64_r_minMag( const extFloat80_t *aPtr, bool exact )
{

    return extF80_to_ui64_r_minMag( *aPtr, exact );

}

#else

uint_fast64_t extF80M_to_ui64_r_minMag( const extFloat80_t *aPtr, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    bool sign;
    uint64_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    exp = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! sig && (exp != 0x7FFF) ) return 0;
    shiftDist = 0x403E - exp;
    if ( 64 <= shiftDist ) {
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sign = signExtF80UI64( uiA64 );
    if ( shiftDist < 0 ) {
        if ( sign || (shiftDist <= -63) ) goto invalid;
        shiftDist = -shiftDist;
        z = sig<<shiftDist;
        if ( z>>shiftDist != sig ) goto invalid;
    } else {
        z = sig;
        if ( shiftDist ) z >>= shiftDist;
        if ( sign && z ) goto invalid;
        if ( exact && shiftDist && (z<<shiftDist != sig) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    }
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
            ? ui64_fromNaN
            : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_ui64_r_minMag.c ****/
/**** start inlining ../../source/extF80M_to_i32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast32_t extF80M_to_i32_r_minMag( const extFloat80_t *aPtr, bool exact )
{

    return extF80_to_i32_r_minMag( *aPtr, exact );

}

#else

int_fast32_t extF80M_to_i32_r_minMag( const extFloat80_t *aPtr, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    bool sign, raiseInexact;
    int32_t z;
    uint64_t shiftedSig;
    uint32_t absZ;
    union { uint32_t ui; int32_t i; } u;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    exp = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! sig && (exp != 0x7FFF) ) return 0;
    shiftDist = 0x403E - exp;
    if ( 64 <= shiftDist ) {
        raiseInexact = exact;
        z = 0;
    } else {
        sign = signExtF80UI64( uiA64 );
        raiseInexact = false;
        if ( shiftDist < 0 ) {
            if ( sig>>32 || (shiftDist <= -31) ) goto invalid;
            shiftedSig = (uint64_t) (uint32_t) sig<<-shiftDist;
            if ( shiftedSig>>32 ) goto invalid;
            absZ = shiftedSig;
        } else {
            shiftedSig = sig;
            if ( shiftDist ) shiftedSig >>= shiftDist;
            if ( shiftedSig>>32 ) goto invalid;
            absZ = shiftedSig;
            if ( exact && shiftDist ) {
                raiseInexact = ((uint64_t) absZ<<shiftDist != sig);
            }
        }
        if ( sign ) {
            if ( 0x80000000 < absZ ) goto invalid;
            u.ui = -absZ;
            z = u.i;
        } else {
            if ( 0x80000000 <= absZ ) goto invalid;
            z = absZ;
        }
    }
    if ( raiseInexact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ? i32_fromNaN
            : sign ? i32_fromNegOverflow : i32_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_i32_r_minMag.c ****/
/**** start inlining ../../source/extF80M_to_i64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast64_t extF80M_to_i64_r_minMag( const extFloat80_t *aPtr, bool exact )
{

    return extF80_to_i64_r_minMag( *aPtr, exact );

}

#else

int_fast64_t extF80M_to_i64_r_minMag( const extFloat80_t *aPtr, bool exact )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    int32_t exp;
    uint64_t sig;
    int32_t shiftDist;
    bool sign, raiseInexact;
    int64_t z;
    uint64_t absZ;
    union { uint64_t ui; int64_t i; } u;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    uiA64 = aSPtr->signExp;
    exp = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! sig && (exp != 0x7FFF) ) return 0;
    shiftDist = 0x403E - exp;
    if ( 64 <= shiftDist ) {
        raiseInexact = exact;
        z = 0;
    } else {
        sign = signExtF80UI64( uiA64 );
        raiseInexact = false;
        if ( shiftDist < 0 ) {
            if ( shiftDist <= -63 ) goto invalid;
            shiftDist = -shiftDist;
            absZ = sig<<shiftDist;
            if ( absZ>>shiftDist != sig ) goto invalid;
        } else {
            absZ = sig;
            if ( shiftDist ) absZ >>= shiftDist;
            if ( exact && shiftDist ) raiseInexact = (absZ<<shiftDist != sig);
        }
        if ( sign ) {
            if ( UINT64_C( 0x8000000000000000 ) < absZ ) goto invalid;
            u.ui = -absZ;
            z = u.i;
        } else {
            if ( UINT64_C( 0x8000000000000000 ) <= absZ ) goto invalid;
            z = absZ;
        }
    }
    if ( raiseInexact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ? i64_fromNaN
            : sign ? i64_fromNegOverflow : i64_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/extF80M_to_i64_r_minMag.c ****/
/**** start inlining ../../source/extF80M_to_f16.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float16_t extF80M_to_f16( const extFloat80_t *aPtr )
{

    return extF80_to_f16( *aPtr );

}

#else

float16_t extF80M_to_f16( const extFloat80_t *aPtr )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    struct commonNaN commonNaN;
    uint16_t uiZ, sig16;
    union ui16_f16 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
            softfloat_extF80MToCommonNaN( aSPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF16UI( &commonNaN );
        } else {
            uiZ = packToF16UI( sign, 0x1F, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sig ) {
            uiZ = packToF16UI( sign, 0, 0 );
            goto uiZ;
        }
        exp += softfloat_normExtF80SigM( &sig );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig16 = softfloat_shortShiftRightJam64( sig, 49 );
    exp -= 0x3FF1;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x40 ) exp = -0x40;
    }
    return softfloat_roundPackToF16( sign, exp, sig16 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/extF80M_to_f16.c ****/
/**** start inlining ../../source/extF80M_to_f32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float32_t extF80M_to_f32( const extFloat80_t *aPtr )
{

    return extF80_to_f32( *aPtr );

}

#else

float32_t extF80M_to_f32( const extFloat80_t *aPtr )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    struct commonNaN commonNaN;
    uint32_t uiZ, sig32;
    union ui32_f32 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
            softfloat_extF80MToCommonNaN( aSPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF32UI( &commonNaN );
        } else {
            uiZ = packToF32UI( sign, 0xFF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sig ) {
            uiZ = packToF32UI( sign, 0, 0 );
            goto uiZ;
        }
        exp += softfloat_normExtF80SigM( &sig );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig32 = softfloat_shortShiftRightJam64( sig, 33 );
    exp -= 0x3F81;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return softfloat_roundPackToF32( sign, exp, sig32 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/extF80M_to_f32.c ****/
/**** start inlining ../../source/extF80M_to_f64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float64_t extF80M_to_f64( const extFloat80_t *aPtr )
{

    return extF80_to_f64( *aPtr );

}

#else

float64_t extF80M_to_f64( const extFloat80_t *aPtr )
{
    const struct extFloat80M *aSPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    struct commonNaN commonNaN;
    uint64_t uiZ;
    union ui64_f64 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
            softfloat_extF80MToCommonNaN( aSPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF64UI( &commonNaN );
        } else {
            uiZ = packToF64UI( sign, 0x7FF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sig ) {
            uiZ = packToF64UI( sign, 0, 0 );
            goto uiZ;
        }
        exp += softfloat_normExtF80SigM( &sig );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig = softfloat_shortShiftRightJam64( sig, 1 );
    exp -= 0x3C01;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return softfloat_roundPackToF64( sign, exp, sig );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/extF80M_to_f64.c ****/
/**** start inlining ../../source/extF80M_to_f128M.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void extF80M_to_f128M( const extFloat80_t *aPtr, float128_t *zPtr )
{

    *zPtr = extF80_to_f128( *aPtr );

}

#else

void extF80M_to_f128M( const extFloat80_t *aPtr, float128_t *zPtr )
{
    const struct extFloat80M *aSPtr;
    uint32_t *zWPtr;
    uint_fast16_t uiA64;
    bool sign;
    int32_t exp;
    uint64_t sig;
    struct commonNaN commonNaN;
    uint32_t uiZ96;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    sign = signExtF80UI64( uiA64 );
    exp  = expExtF80UI64( uiA64 );
    sig = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    zWPtr[indexWord( 4, 0 )] = 0;
    if ( exp == 0x7FFF ) {
        if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
            softfloat_extF80MToCommonNaN( aSPtr, &commonNaN );
            softfloat_commonNaNToF128M( &commonNaN, zWPtr );
            return;
        }
        uiZ96 = packToF128UI96( sign, 0x7FFF, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) --exp;
    if ( ! (sig & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sig ) {
            uiZ96 = packToF128UI96( sign, 0, 0 );
            goto uiZ;
        }
        exp += softfloat_normExtF80SigM( &sig );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    zWPtr[indexWord( 4, 1 )] = (uint32_t) sig<<17;
    sig >>= 15;
    zWPtr[indexWord( 4, 2 )] = sig;
    if ( exp < 0 ) {
        zWPtr[indexWordHi( 4 )] = sig>>32;
        softfloat_shiftRight96M(
            &zWPtr[indexMultiwordHi( 4, 3 )],
            -exp,
            &zWPtr[indexMultiwordHi( 4, 3 )]
        );
        exp = 0;
        sig = (uint64_t) zWPtr[indexWordHi( 4 )]<<32;
    }
    zWPtr[indexWordHi( 4 )] = packToF128UI96( sign, exp, sig>>32 );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    zWPtr[indexWord( 4, 3 )] = uiZ96;
    zWPtr[indexWord( 4, 2 )] = 0;
    zWPtr[indexWord( 4, 1 )] = 0;

}

#endif

/**** ended inlining ../../source/extF80M_to_f128M.c ****/
/**** start inlining ../../source/extF80M_roundToInt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_roundToInt(
     const extFloat80_t *aPtr,
     uint_fast8_t roundingMode,
     bool exact,
     extFloat80_t *zPtr
 )
{

    *zPtr = extF80_roundToInt( *aPtr, roundingMode, exact );

}

#else

void
 extF80M_roundToInt(
     const extFloat80_t *aPtr,
     uint_fast8_t roundingMode,
     bool exact,
     extFloat80_t *zPtr
 )
{
    const struct extFloat80M *aSPtr;
    struct extFloat80M *zSPtr;
    uint_fast16_t uiA64, signUI64;
    int32_t exp;
    uint64_t sigA;
    uint_fast16_t uiZ64;
    uint64_t sigZ, lastBitMask, roundBitsMask;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    signUI64 = uiA64 & packToExtF80UI64( 1, 0 );
    exp = expExtF80UI64( uiA64 );
    sigA = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( !(sigA & UINT64_C( 0x8000000000000000 )) && (exp != 0x7FFF) ) {
        if ( !sigA ) {
            uiZ64 = signUI64;
            sigZ = 0;
            goto uiZ;
        }
        exp += softfloat_normExtF80SigM( &sigA );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp <= 0x3FFE ) {
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
        switch ( roundingMode ) {
         case softfloat_round_near_even:
            if ( !(sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF )) ) break;
         case softfloat_round_near_maxMag:
            if ( exp == 0x3FFE ) goto mag1;
            break;
         case softfloat_round_min:
            if ( signUI64 ) goto mag1;
            break;
         case softfloat_round_max:
            if ( !signUI64 ) goto mag1;
            break;
#ifdef SOFTFLOAT_ROUND_ODD
         case softfloat_round_odd:
            goto mag1;
#endif
        }
        uiZ64 = signUI64;
        sigZ = 0;
        goto uiZ;
     mag1:
        uiZ64 = signUI64 | 0x3FFF;
        sigZ = UINT64_C( 0x8000000000000000 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( 0x403E <= exp ) {
        if ( exp == 0x7FFF ) {
            if ( sigA & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
                softfloat_propagateNaNExtF80M( aSPtr, 0, zSPtr );
                return;
            }
            sigZ = UINT64_C( 0x8000000000000000 );
        } else {
            sigZ = sigA;
        }
        uiZ64 = signUI64 | exp;
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiZ64 = signUI64 | exp;
    lastBitMask = (uint64_t) 1<<(0x403E - exp);
    roundBitsMask = lastBitMask - 1;
    sigZ = sigA;
    if ( roundingMode == softfloat_round_near_maxMag ) {
        sigZ += lastBitMask>>1;
    } else if ( roundingMode == softfloat_round_near_even ) {
        sigZ += lastBitMask>>1;
        if ( !(sigZ & roundBitsMask) ) sigZ &= ~lastBitMask;
    } else if (
        roundingMode == (signUI64 ? softfloat_round_min : softfloat_round_max)
    ) {
        sigZ += roundBitsMask;
    }
    sigZ &= ~roundBitsMask;
    if ( !sigZ ) {
        ++uiZ64;
        sigZ = UINT64_C( 0x8000000000000000 );
    }
    if ( sigZ != sigA ) {
#ifdef SOFTFLOAT_ROUND_ODD
        if ( roundingMode == softfloat_round_odd ) sigZ |= lastBitMask;
#endif
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
 uiZ:
    zSPtr->signExp = uiZ64;
    zSPtr->signif = sigZ;
    return;

}

#endif

/**** ended inlining ../../source/extF80M_roundToInt.c ****/
/**** start inlining ../../source/extF80M_add.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_add(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint_fast64_t uiA0;
    bool signA;
    uint_fast16_t uiB64;
    uint_fast64_t uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    extFloat80_t
        (*magsFuncPtr)(
            uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool );
#endif

    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    signA = signExtF80UI64( uiA64 );
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    signB = signExtF80UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        *zPtr = softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        *zPtr = softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_addMagsExtF80 : softfloat_subMagsExtF80;
    *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

#else

void
 extF80M_add(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{

    softfloat_addExtF80M(
        (const struct extFloat80M *) aPtr,
        (const struct extFloat80M *) bPtr,
        (struct extFloat80M *) zPtr,
        false
    );

}

#endif

/**** ended inlining ../../source/extF80M_add.c ****/
/**** start inlining ../../source/extF80M_sub.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_sub(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint_fast64_t uiA0;
    bool signA;
    uint_fast16_t uiB64;
    uint_fast64_t uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    extFloat80_t
        (*magsFuncPtr)(
            uint_fast16_t, uint_fast64_t, uint_fast16_t, uint_fast64_t, bool );
#endif

    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    signA = signExtF80UI64( uiA64 );
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    signB = signExtF80UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        *zPtr = softfloat_subMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        *zPtr = softfloat_addMagsExtF80( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_subMagsExtF80 : softfloat_addMagsExtF80;
    *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

#else

void
 extF80M_sub(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{

    softfloat_addExtF80M(
        (const struct extFloat80M *) aPtr,
        (const struct extFloat80M *) bPtr,
        (struct extFloat80M *) zPtr,
        true
    );

}

#endif

/**** ended inlining ../../source/extF80M_sub.c ****/
/**** start inlining ../../source/extF80M_mul.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_mul(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{

    *zPtr = extF80_mul( *aPtr, *bPtr );

}

#else

void
 extF80M_mul(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    struct extFloat80M *zSPtr;
    uint_fast16_t uiA64;
    int32_t expA;
    uint_fast16_t uiB64;
    int32_t expB;
    bool signZ;
    uint_fast16_t exp, uiZ64;
    uint64_t uiZ0, sigA, sigB;
    int32_t expZ;
    uint32_t sigProd[4], *extSigZPtr;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    expA = expExtF80UI64( uiA64 );
    uiB64 = bSPtr->signExp;
    expB = expExtF80UI64( uiB64 );
    signZ = signExtF80UI64( uiA64 ) ^ signExtF80UI64( uiB64 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return;
        if (
               (! aSPtr->signif && (expA != 0x7FFF))
            || (! bSPtr->signif && (expB != 0x7FFF))
        ) {
            softfloat_invalidExtF80M( zSPtr );
            return;
        }
        uiZ64 = packToExtF80UI64( signZ, 0x7FFF );
        uiZ0  = UINT64_C( 0x8000000000000000 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expA ) expA = 1;
    sigA = aSPtr->signif;
    if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sigA ) goto zero;
        expA += softfloat_normExtF80SigM( &sigA );
    }
    if ( ! expB ) expB = 1;
    sigB = bSPtr->signif;
    if ( ! (sigB & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sigB ) goto zero;
        expB += softfloat_normExtF80SigM( &sigB );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA + expB - 0x3FFE;
    softfloat_mul64To128M( sigA, sigB, sigProd );
    if ( sigProd[indexWordLo( 4 )] ) sigProd[indexWord( 4, 1 )] |= 1;
    extSigZPtr = &sigProd[indexMultiwordHi( 4, 3 )];
    if ( sigProd[indexWordHi( 4 )] < 0x80000000 ) {
        --expZ;
        softfloat_add96M( extSigZPtr, extSigZPtr, extSigZPtr );
    }
    softfloat_roundPackMToExtF80M(
        signZ, expZ, extSigZPtr, extF80_roundingPrecision, zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 zero:
    uiZ64 = packToExtF80UI64( signZ, 0 );
    uiZ0  = 0;
 uiZ:
    zSPtr->signExp = uiZ64;
    zSPtr->signif  = uiZ0;

}

#endif

/**** ended inlining ../../source/extF80M_mul.c ****/
/**** start inlining ../../source/extF80M_div.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_div(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{

    *zPtr = extF80_div( *aPtr, *bPtr );

}

#else

void
 extF80M_div(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    struct extFloat80M *zSPtr;
    uint_fast16_t uiA64;
    int32_t expA;
    uint_fast16_t uiB64;
    int32_t expB;
    bool signZ;
    uint64_t sigA, x64;
    int32_t expZ;
    int shiftDist;
    uint32_t y[3], recip32, sigB[3];
    int ix;
    uint32_t q, qs[2];
    uint_fast16_t uiZ64;
    uint64_t uiZ0;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    expA = expExtF80UI64( uiA64 );
    uiB64 = bSPtr->signExp;
    expB = expExtF80UI64( uiB64 );
    signZ = signExtF80UI64( uiA64 ) ^ signExtF80UI64( uiB64 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return;
        if ( expA == 0x7FFF ) {
            if ( expB == 0x7FFF ) goto invalid;
            goto infinity;
        }
        goto zero;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sigA = aSPtr->signif;
    x64 = bSPtr->signif;
    if ( ! expB ) expB = 1;
    if ( ! (x64 & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! x64 ) {
            if ( ! sigA ) goto invalid;
            softfloat_raiseFlags( softfloat_flag_infinite );
            goto infinity;
        }
        expB += softfloat_normExtF80SigM( &x64 );
    }
    if ( ! expA ) expA = 1;
    if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sigA ) goto zero;
        expA += softfloat_normExtF80SigM( &sigA );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA - expB + 0x3FFF;
    shiftDist = 29;
    if ( sigA < x64 ) {
        --expZ;
        shiftDist = 30;
    }
    softfloat_shortShiftLeft64To96M( sigA, shiftDist, y );
    recip32 = softfloat_approxRecip32_1( x64>>32 );
    sigB[indexWord( 3, 0 )] = (uint32_t) x64<<30;
    x64 >>= 2;
    sigB[indexWord( 3, 2 )] = x64>>32;
    sigB[indexWord( 3, 1 )] = x64;
    ix = 2;
    for (;;) {
        x64 = (uint64_t) y[indexWordHi( 3 )] * recip32;
        q = (x64 + 0x80000000)>>32;
        --ix;
        if ( ix < 0 ) break;
        softfloat_remStep96MBy32( y, 29, sigB, q, y );
        if ( y[indexWordHi( 3 )] & 0x80000000 ) {
            --q;
            softfloat_add96M( y, sigB, y );
        }
        qs[ix] = q;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ((q + 1) & 0x3FFFFF) < 2 ) {
        softfloat_remStep96MBy32( y, 29, sigB, q, y );
        if ( y[indexWordHi( 3 )] & 0x80000000 ) {
            --q;
            softfloat_add96M( y, sigB, y );
        } else if ( softfloat_compare96M( sigB, y ) <= 0 ) {
            ++q;
            softfloat_sub96M( y, sigB, y );
        }
        if (
            y[indexWordLo( 3 )] || y[indexWord( 3, 1 )] || y[indexWord( 3, 2 )]
        ) {
            q |= 1;
        }
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    x64 = (uint64_t) q<<9;
    y[indexWord( 3, 0 )] = x64;
    x64 = ((uint64_t) qs[0]<<6) + (x64>>32);
    y[indexWord( 3, 1 )] = x64;
    y[indexWord( 3, 2 )] = (qs[1]<<3) + (x64>>32);
    softfloat_roundPackMToExtF80M(
        signZ, expZ, y, extF80_roundingPrecision, zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidExtF80M( zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 infinity:
    uiZ64 = packToExtF80UI64( signZ, 0x7FFF );
    uiZ0  = UINT64_C( 0x8000000000000000 );
    goto uiZ;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 zero:
    uiZ64 = packToExtF80UI64( signZ, 0 );
    uiZ0  = 0;
 uiZ:
    zSPtr->signExp = uiZ64;
    zSPtr->signif  = uiZ0;

}

#endif

/**** ended inlining ../../source/extF80M_div.c ****/
/**** start inlining ../../source/extF80M_rem.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 extF80M_rem(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{

    *zPtr = extF80_rem( *aPtr, *bPtr );

}

#else

void
 extF80M_rem(
     const extFloat80_t *aPtr, const extFloat80_t *bPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    struct extFloat80M *zSPtr;
    uint_fast16_t uiA64;
    int32_t expA, expB;
    uint64_t x64;
    bool signRem;
    uint64_t sigA;
    int32_t expDiff;
    uint32_t rem[3], x[3], sig32B, q, recip32, rem2[3], *remPtr, *altRemPtr;
    uint32_t *newRemPtr, wordMeanRem;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    expA = expExtF80UI64( uiA64 );
    expB = expExtF80UI64( bSPtr->signExp );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNExtF80M( aSPtr, bSPtr, zSPtr ) ) return;
        if ( expA == 0x7FFF ) goto invalid;
        /*--------------------------------------------------------------------
        | If we get here, then argument b is an infinity and `expB' is 0x7FFF;
        | Doubling `expB' is an easy way to ensure that `expDiff' later is
        | less than -1, which will result in returning a canonicalized version
        | of argument a.
        *--------------------------------------------------------------------*/
        expB += expB;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expB ) expB = 1;
    x64 = bSPtr->signif;
    if ( ! (x64 & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! x64 ) goto invalid;
        expB += softfloat_normExtF80SigM( &x64 );
    }
    signRem = signExtF80UI64( uiA64 );
    if ( ! expA ) expA = 1;
    sigA = aSPtr->signif;
    if ( ! (sigA & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! sigA ) {
            expA = 0;
            goto copyA;
        }
        expA += softfloat_normExtF80SigM( &sigA );
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expDiff = expA - expB;
    if ( expDiff < -1 ) goto copyA;
    rem[indexWord( 3, 2 )] = sigA>>34;
    rem[indexWord( 3, 1 )] = sigA>>2;
    rem[indexWord( 3, 0 )] = (uint32_t) sigA<<30;
    x[indexWord( 3, 0 )] = (uint32_t) x64<<30;
    sig32B = x64>>32;
    x64 >>= 2;
    x[indexWord( 3, 2 )] = x64>>32;
    x[indexWord( 3, 1 )] = x64;
    if ( expDiff < 1 ) {
        if ( expDiff ) {
            --expB;
            softfloat_add96M( x, x, x );
            q = 0;
        } else {
            q = (softfloat_compare96M( x, rem ) <= 0);
            if ( q ) softfloat_sub96M( rem, x, rem );
        }
    } else {
        recip32 = softfloat_approxRecip32_1( sig32B );
        expDiff -= 30;
        for (;;) {
            x64 = (uint64_t) rem[indexWordHi( 3 )] * recip32;
            if ( expDiff < 0 ) break;
            q = (x64 + 0x80000000)>>32;
            softfloat_remStep96MBy32( rem, 29, x, q, rem );
            if ( rem[indexWordHi( 3 )] & 0x80000000 ) {
                softfloat_add96M( rem, x, rem );
            }
            expDiff -= 29;
        }
        /*--------------------------------------------------------------------
        | (`expDiff' cannot be less than -29 here.)
        *--------------------------------------------------------------------*/
        q = (uint32_t) (x64>>32)>>(~expDiff & 31);
        softfloat_remStep96MBy32( rem, expDiff + 30, x, q, rem );
        if ( rem[indexWordHi( 3 )] & 0x80000000 ) {
            remPtr = rem;
            altRemPtr = rem2;
            softfloat_add96M( remPtr, x, altRemPtr );
            goto selectRem;
        }
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    remPtr = rem;
    altRemPtr = rem2;
    do {
        ++q;
        newRemPtr = altRemPtr;
        softfloat_sub96M( remPtr, x, newRemPtr );
        altRemPtr = remPtr;
        remPtr = newRemPtr;
    } while ( ! (remPtr[indexWordHi( 3 )] & 0x80000000) );
 selectRem:
    softfloat_add96M( remPtr, altRemPtr, x );
    wordMeanRem = x[indexWordHi( 3 )];
    if (
        (wordMeanRem & 0x80000000)
            || (! wordMeanRem && (q & 1) && ! x[indexWord( 3, 0 )]
                    && ! x[indexWord( 3, 1 )])
    ) {
        remPtr = altRemPtr;
    }
    if ( remPtr[indexWordHi( 3 )] & 0x80000000 ) {
        signRem = ! signRem;
        softfloat_negX96M( remPtr );
    }
    softfloat_normRoundPackMToExtF80M( signRem, expB + 2, remPtr, 80, zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidExtF80M( zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 copyA:
    if ( expA < 1 ) {
        sigA >>= 1 - expA;
        expA = 0;
    }
    zSPtr->signExp = packToExtF80UI64( signRem, expA );
    zSPtr->signif = sigA;

}

#endif

/**** ended inlining ../../source/extF80M_rem.c ****/
/**** start inlining ../../source/extF80M_sqrt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2017 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void extF80M_sqrt( const extFloat80_t *aPtr, extFloat80_t *zPtr )
{

    *zPtr = extF80_sqrt( *aPtr );

}

#else

void extF80M_sqrt( const extFloat80_t *aPtr, extFloat80_t *zPtr )
{
    const struct extFloat80M *aSPtr;
    struct extFloat80M *zSPtr;
    uint_fast16_t uiA64, signUI64;
    int32_t expA;
    uint64_t rem64;
    int32_t expZ;
    uint32_t rem96[3], sig32A, recipSqrt32, sig32Z, q;
    uint64_t sig64Z, x64;
    uint32_t rem32, term[4], rem[4], extSigZ[3];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    signUI64 = uiA64 & packToExtF80UI64( 1, 0 );
    expA = expExtF80UI64( uiA64 );
    rem64 = aSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA == 0x7FFF ) {
        if ( rem64 & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) {
            softfloat_propagateNaNExtF80M( aSPtr, 0, zSPtr );
            return;
        }
        if ( signUI64 ) goto invalid;
        rem64 = UINT64_C( 0x8000000000000000 );
        goto copyA;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expA ) expA = 1;
    if ( ! (rem64 & UINT64_C( 0x8000000000000000 )) ) {
        if ( ! rem64 ) {
            uiA64 = signUI64;
            goto copyA;
        }
        expA += softfloat_normExtF80SigM( &rem64 );
    }
    if ( signUI64 ) goto invalid;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = ((expA - 0x3FFF)>>1) + 0x3FFF;
    expA &= 1;
    softfloat_shortShiftLeft64To96M( rem64, 30 - expA, rem96 );
    sig32A = rem64>>32;
    recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A );
    sig32Z = ((uint64_t) sig32A * recipSqrt32)>>32;
    if ( expA ) sig32Z >>= 1;
    rem64 =
        ((uint64_t) rem96[indexWord( 3, 2 )]<<32 | rem96[indexWord( 3, 1 )])
            - (uint64_t) sig32Z * sig32Z;
    rem96[indexWord( 3, 2 )] = rem64>>32;
    rem96[indexWord( 3, 1 )] = rem64;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32;
    sig64Z = ((uint64_t) sig32Z<<32) + ((uint64_t) q<<3);
    term[indexWord( 3, 2 )] = 0;
    /*------------------------------------------------------------------------
    | (Repeating this loop is a rare occurrence.)
    *------------------------------------------------------------------------*/
    for (;;) {
        x64 = ((uint64_t) sig32Z<<32) + sig64Z;
        term[indexWord( 3, 1 )] = x64>>32;
        term[indexWord( 3, 0 )] = x64;
        softfloat_remStep96MBy32(
            rem96, 29, term, q, &rem[indexMultiwordHi( 4, 3 )] );
        rem32 = rem[indexWord( 4, 3 )];
        if ( ! (rem32 & 0x80000000) ) break;
        --q;
        sig64Z -= 1<<3;
    }
    rem64 = (uint64_t) rem32<<32 | rem[indexWord( 4, 2 )];
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = (((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32) + 2;
    if ( rem64>>34 ) q += recipSqrt32;
    x64 = (uint64_t) q<<7;
    extSigZ[indexWord( 3, 0 )] = x64;
    x64 = (sig64Z<<1) + (x64>>32);
    extSigZ[indexWord( 3, 2 )] = x64>>32;
    extSigZ[indexWord( 3, 1 )] = x64;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (q & 0xFFFFFF) <= 2 ) {
        q &= ~(uint32_t) 0xFFFF;
        extSigZ[indexWordLo( 3 )] = q<<7;
        x64 = sig64Z + (q>>27);
        term[indexWord( 4, 3 )] = 0;
        term[indexWord( 4, 2 )] = x64>>32;
        term[indexWord( 4, 1 )] = x64;
        term[indexWord( 4, 0 )] = q<<5;
        rem[indexWord( 4, 0 )] = 0;
        softfloat_remStep128MBy32( rem, 28, term, q, rem );
        q = rem[indexWordHi( 4 )];
        if ( q & 0x80000000 ) {
            softfloat_sub1X96M( extSigZ );
        } else {
            if ( q || rem[indexWord( 4, 1 )] || rem[indexWord( 4, 2 )] ) {
                extSigZ[indexWordLo( 3 )] |= 1;
            }
        }
    }
    softfloat_roundPackMToExtF80M(
        0, expZ, extSigZ, extF80_roundingPrecision, zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidExtF80M( zSPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 copyA:
    zSPtr->signExp = uiA64;
    zSPtr->signif  = rem64;

}

#endif

/**** ended inlining ../../source/extF80M_sqrt.c ****/
/**** start inlining ../../source/extF80M_eq.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_eq( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_eq( *aPtr, *bPtr );

}

#else

bool extF80M_eq( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNExtF80UI( uiA64, uiA0 )
            || softfloat_isSigNaNExtF80UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( uiA0 == uiB0 ) {
        return (uiA64 == uiB64) || ! uiA0;
    } else {
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return ! softfloat_compareNonnormExtF80M( aSPtr, bSPtr );
        }
        return false;
    }

}

#endif

/**** ended inlining ../../source/extF80M_eq.c ****/
/**** start inlining ../../source/extF80M_le.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_le( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_le( *aPtr, *bPtr );

}

#else

bool extF80M_le( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;
    bool signA, ltMags;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    signA = signExtF80UI64( uiA64 );
    if ( (uiA64 ^ uiB64) & 0x8000 ) {
        /*--------------------------------------------------------------------
        | Signs are different.
        *--------------------------------------------------------------------*/
        return signA || ! (uiA0 | uiB0);
    } else {
        /*--------------------------------------------------------------------
        | Signs are the same.
        *--------------------------------------------------------------------*/
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) <= 0);
        }
        if ( uiA64 == uiB64 ) {
            if ( uiA0 == uiB0 ) return true;
            ltMags = (uiA0 < uiB0);
        } else {
            ltMags = (uiA64 < uiB64);
        }
        return signA ^ ltMags;
    }

}

#endif

/**** ended inlining ../../source/extF80M_le.c ****/
/**** start inlining ../../source/extF80M_lt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_lt( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_lt( *aPtr, *bPtr );

}

#else

bool extF80M_lt( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;
    bool signA, ltMags;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    signA = signExtF80UI64( uiA64 );
    if ( (uiA64 ^ uiB64) & 0x8000 ) {
        /*--------------------------------------------------------------------
        | Signs are different.
        *--------------------------------------------------------------------*/
        return signA && ((uiA0 | uiB0) != 0);
    } else {
        /*--------------------------------------------------------------------
        | Signs are the same.
        *--------------------------------------------------------------------*/
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) < 0);
        }
        if ( uiA64 == uiB64 ) {
            if ( uiA0 == uiB0 ) return false;
            ltMags = (uiA0 < uiB0);
        } else {
            ltMags = (uiA64 < uiB64);
        }
        return signA ^ ltMags;
    }

}

#endif

/**** ended inlining ../../source/extF80M_lt.c ****/
/**** start inlining ../../source/extF80M_eq_signaling.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_eq_signaling( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_eq_signaling( *aPtr, *bPtr );

}

#else

bool extF80M_eq_signaling( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( uiA0 == uiB0 ) {
        return (uiA64 == uiB64) || ! uiA0;
    } else {
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return ! softfloat_compareNonnormExtF80M( aSPtr, bSPtr );
        }
        return false;
    }

}

#endif

/**** ended inlining ../../source/extF80M_eq_signaling.c ****/
/**** start inlining ../../source/extF80M_le_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_le_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_le_quiet( *aPtr, *bPtr );

}

#else

bool extF80M_le_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;
    bool signA, ltMags;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNExtF80UI( uiA64, uiA0 )
            || softfloat_isSigNaNExtF80UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    signA = signExtF80UI64( uiA64 );
    if ( (uiA64 ^ uiB64) & 0x8000 ) {
        /*--------------------------------------------------------------------
        | Signs are different.
        *--------------------------------------------------------------------*/
        return signA || ! (uiA0 | uiB0);
    } else {
        /*--------------------------------------------------------------------
        | Signs are the same.
        *--------------------------------------------------------------------*/
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) <= 0);
        }
        if ( uiA64 == uiB64 ) {
            if ( uiA0 == uiB0 ) return true;
            ltMags = (uiA0 < uiB0);
        } else {
            ltMags = (uiA64 < uiB64);
        }
        return signA ^ ltMags;
    }

}

#endif

/**** ended inlining ../../source/extF80M_le_quiet.c ****/
/**** start inlining ../../source/extF80M_lt_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool extF80M_lt_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{

    return extF80_lt_quiet( *aPtr, *bPtr );

}

#else

bool extF80M_lt_quiet( const extFloat80_t *aPtr, const extFloat80_t *bPtr )
{
    const struct extFloat80M *aSPtr, *bSPtr;
    uint_fast16_t uiA64;
    uint64_t uiA0;
    uint_fast16_t uiB64;
    uint64_t uiB0;
    bool signA, ltMags;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aSPtr = (const struct extFloat80M *) aPtr;
    bSPtr = (const struct extFloat80M *) bPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA64 = aSPtr->signExp;
    uiA0  = aSPtr->signif;
    uiB64 = bSPtr->signExp;
    uiB0  = bSPtr->signif;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNExtF80UI( uiA64, uiA0 )
            || softfloat_isSigNaNExtF80UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    signA = signExtF80UI64( uiA64 );
    if ( (uiA64 ^ uiB64) & 0x8000 ) {
        /*--------------------------------------------------------------------
        | Signs are different.
        *--------------------------------------------------------------------*/
        return signA && ((uiA0 | uiB0) != 0);
    } else {
        /*--------------------------------------------------------------------
        | Signs are the same.
        *--------------------------------------------------------------------*/
        if ( ! ((uiA0 & uiB0) & UINT64_C( 0x8000000000000000 )) ) {
            return (softfloat_compareNonnormExtF80M( aSPtr, bSPtr ) < 0);
        }
        if ( uiA64 == uiB64 ) {
            if ( uiA0 == uiB0 ) return false;
            ltMags = (uiA0 < uiB0);
        } else {
            ltMags = (uiA64 < uiB64);
        }
        return signA ^ ltMags;
    }

}

#endif

/**** ended inlining ../../source/extF80M_lt_quiet.c ****/
/**** start inlining ../../source/f128_to_ui32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

uint_fast32_t
 f128_to_ui32( float128_t a, uint_fast8_t roundingMode, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64;
    int_fast32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow)
    if ( (exp == 0x7FFF) && sig64 ) {
#if (ui32_fromNaN == ui32_fromPosOverflow)
        sign = 0;
#elif (ui32_fromNaN == ui32_fromNegOverflow)
        sign = 1;
#else
        softfloat_raiseFlags( softfloat_flag_invalid );
        return ui32_fromNaN;
#endif
    }
#endif
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
    shiftDist = 0x4023 - exp;
    if ( 0 < shiftDist ) {
        sig64 = softfloat_shiftRightJam64( sig64, shiftDist );
    }
    return softfloat_roundToUI32( sign, sig64, roundingMode, exact );

}

/**** ended inlining ../../source/f128_to_ui32.c ****/
/**** start inlining ../../source/f128_to_ui64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

uint_fast64_t
 f128_to_ui64( float128_t a, uint_fast8_t roundingMode, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64, sig0;
    int_fast32_t shiftDist;
    struct uint128 sig128;
    struct uint64_extra sigExtra;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 );
    sig0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( shiftDist <= 0 ) {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( shiftDist < -15 ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
            return
                (exp == 0x7FFF) && (sig64 | sig0) ? ui64_fromNaN
                    : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        sig64 |= UINT64_C( 0x0001000000000000 );
        if ( shiftDist ) {
            sig128 = softfloat_shortShiftLeft128( sig64, sig0, -shiftDist );
            sig64 = sig128.v64;
            sig0  = sig128.v0;
        }
    } else {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
        sigExtra = softfloat_shiftRightJam64Extra( sig64, sig0, shiftDist );
        sig64 = sigExtra.v;
        sig0  = sigExtra.extra;
    }
    return softfloat_roundToUI64( sign, sig64, sig0, roundingMode, exact );

}

/**** ended inlining ../../source/f128_to_ui64.c ****/
/**** start inlining ../../source/f128_to_i32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

int_fast32_t f128_to_i32( float128_t a, uint_fast8_t roundingMode, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64, sig0;
    int_fast32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 );
    sig0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow)
    if ( (exp == 0x7FFF) && (sig64 | sig0) ) {
#if (i32_fromNaN == i32_fromPosOverflow)
        sign = 0;
#elif (i32_fromNaN == i32_fromNegOverflow)
        sign = 1;
#else
        softfloat_raiseFlags( softfloat_flag_invalid );
        return i32_fromNaN;
#endif
    }
#endif
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
    sig64 |= (sig0 != 0);
    shiftDist = 0x4023 - exp;
    if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist );
    return softfloat_roundToI32( sign, sig64, roundingMode, exact );

}

/**** ended inlining ../../source/f128_to_i32.c ****/
/**** start inlining ../../source/f128_to_i64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

int_fast64_t f128_to_i64( float128_t a, uint_fast8_t roundingMode, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64, sig0;
    int_fast32_t shiftDist;
    struct uint128 sig128;
    struct uint64_extra sigExtra;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 );
    sig0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( shiftDist <= 0 ) {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( shiftDist < -15 ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
            return
                (exp == 0x7FFF) && (sig64 | sig0) ? i64_fromNaN
                    : sign ? i64_fromNegOverflow : i64_fromPosOverflow;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        sig64 |= UINT64_C( 0x0001000000000000 );
        if ( shiftDist ) {
            sig128 = softfloat_shortShiftLeft128( sig64, sig0, -shiftDist );
            sig64 = sig128.v64;
            sig0  = sig128.v0;
        }
    } else {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
        sigExtra = softfloat_shiftRightJam64Extra( sig64, sig0, shiftDist );
        sig64 = sigExtra.v;
        sig0  = sigExtra.extra;
    }
    return softfloat_roundToI64( sign, sig64, sig0, roundingMode, exact );

}

/**** ended inlining ../../source/f128_to_i64.c ****/
/**** start inlining ../../source/f128_to_ui32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

uint_fast32_t f128_to_ui32_r_minMag( float128_t a, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    int_fast32_t exp;
    uint_fast64_t sig64;
    int_fast32_t shiftDist;
    bool sign;
    uint_fast32_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( 49 <= shiftDist ) {
        if ( exact && (exp | sig64) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sign = signF128UI64( uiA64 );
    if ( sign || (shiftDist < 17) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF) && sig64 ? ui32_fromNaN
                : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig64 |= UINT64_C( 0x0001000000000000 );
    z = sig64>>shiftDist;
    if ( exact && ((uint_fast64_t) z<<shiftDist != sig64) ) {
        softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
    return z;

}

/**** ended inlining ../../source/f128_to_ui32_r_minMag.c ****/
/**** start inlining ../../source/f128_to_ui64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

uint_fast64_t f128_to_ui64_r_minMag( float128_t a, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64, sig0;
    int_fast32_t shiftDist;
    int_fast8_t negShiftDist;
    uint_fast64_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 );
    sig0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( shiftDist < 0 ) {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( sign || (shiftDist < -15) ) goto invalid;
        sig64 |= UINT64_C( 0x0001000000000000 );
        negShiftDist = -shiftDist;
        z = sig64<<negShiftDist | sig0>>(shiftDist & 63);
        if ( exact && (uint64_t) (sig0<<negShiftDist) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    } else {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( 49 <= shiftDist ) {
            if ( exact && (exp | sig64 | sig0) ) {
                softfloat_exceptionFlags |= softfloat_flag_inexact;
            }
            return 0;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( sign ) goto invalid;
        sig64 |= UINT64_C( 0x0001000000000000 );
        z = sig64>>shiftDist;
        if ( exact && (sig0 || (z<<shiftDist != sig64)) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    }
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && (sig64 | sig0) ? ui64_fromNaN
            : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;

}

/**** ended inlining ../../source/f128_to_ui64_r_minMag.c ****/
/**** start inlining ../../source/f128_to_i32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

int_fast32_t f128_to_i32_r_minMag( float128_t a, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    int_fast32_t exp;
    uint_fast64_t sig64;
    int_fast32_t shiftDist;
    bool sign;
    int_fast32_t absZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 ) | (uiA0 != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( 49 <= shiftDist ) {
        if ( exact && (exp | sig64) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sign = signF128UI64( uiA64 );
    if ( shiftDist < 18 ) {
        if (
            sign && (shiftDist == 17)
                && (sig64 < UINT64_C( 0x0000000000020000 ))
        ) {
            if ( exact && sig64 ) {
                softfloat_exceptionFlags |= softfloat_flag_inexact;
            }
            return -0x7FFFFFFF - 1;
        }
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF) && sig64 ? i32_fromNaN
                : sign ? i32_fromNegOverflow : i32_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig64 |= UINT64_C( 0x0001000000000000 );
    absZ = sig64>>shiftDist;
    if (
        exact && ((uint_fast64_t) (uint_fast32_t) absZ<<shiftDist != sig64)
    ) {
        softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
    return sign ? -absZ : absZ;

}

/**** ended inlining ../../source/f128_to_i32_r_minMag.c ****/
/**** start inlining ../../source/f128_to_i64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

int_fast64_t f128_to_i64_r_minMag( float128_t a, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t sig64, sig0;
    int_fast32_t shiftDist;
    int_fast8_t negShiftDist;
    int_fast64_t absZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    sig64 = fracF128UI64( uiA64 );
    sig0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( shiftDist < 0 ) {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( shiftDist < -14 ) {
            if (
                   (uiA64 == UINT64_C( 0xC03E000000000000 ))
                && (sig0 < UINT64_C( 0x0002000000000000 ))
            ) {
                if ( exact && sig0 ) {
                    softfloat_exceptionFlags |= softfloat_flag_inexact;
                }
                return -INT64_C( 0x7FFFFFFFFFFFFFFF ) - 1;
            }
            softfloat_raiseFlags( softfloat_flag_invalid );
            return
                (exp == 0x7FFF) && (sig64 | sig0) ? i64_fromNaN
                    : sign ? i64_fromNegOverflow : i64_fromPosOverflow;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        sig64 |= UINT64_C( 0x0001000000000000 );
        negShiftDist = -shiftDist;
        absZ = sig64<<negShiftDist | sig0>>(shiftDist & 63);
        if ( exact && (uint64_t) (sig0<<negShiftDist) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    } else {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( 49 <= shiftDist ) {
            if ( exact && (exp | sig64 | sig0) ) {
                softfloat_exceptionFlags |= softfloat_flag_inexact;
            }
            return 0;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        sig64 |= UINT64_C( 0x0001000000000000 );
        absZ = sig64>>shiftDist;
        if ( exact && (sig0 || (absZ<<shiftDist != sig64)) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    }
    return sign ? -absZ : absZ;

}

/**** ended inlining ../../source/f128_to_i64_r_minMag.c ****/
/**** start inlining ../../source/f128_to_f16.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float16_t f128_to_f16( float128_t a )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t frac64;
    struct commonNaN commonNaN;
    uint_fast16_t uiZ, frac16;
    union ui16_f16 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    frac64 = fracF128UI64( uiA64 ) | (uiA0 != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 ) {
            softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN );
            uiZ = softfloat_commonNaNToF16UI( &commonNaN );
        } else {
            uiZ = packToF16UI( sign, 0x1F, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac16 = softfloat_shortShiftRightJam64( frac64, 34 );
    if ( ! (exp | frac16) ) {
        uiZ = packToF16UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3FF1;
    if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) {
        if ( exp < -0x40 ) exp = -0x40;
    }
    return softfloat_roundPackToF16( sign, exp, frac16 | 0x4000 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_to_f16.c ****/
/**** start inlining ../../source/f128_to_f32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float32_t f128_to_f32( float128_t a )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t frac64;
    struct commonNaN commonNaN;
    uint_fast32_t uiZ, frac32;
    union ui32_f32 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    frac64 = fracF128UI64( uiA64 ) | (uiA0 != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 ) {
            softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN );
            uiZ = softfloat_commonNaNToF32UI( &commonNaN );
        } else {
            uiZ = packToF32UI( sign, 0xFF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac32 = softfloat_shortShiftRightJam64( frac64, 18 );
    if ( ! (exp | frac32) ) {
        uiZ = packToF32UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3F81;
    if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return softfloat_roundPackToF32( sign, exp, frac32 | 0x40000000 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_to_f32.c ****/
/**** start inlining ../../source/f128_to_extF80.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

extFloat80_t f128_to_extF80( float128_t a )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t frac64, frac0;
    struct commonNaN commonNaN;
    struct uint128 uiZ;
    uint_fast16_t uiZ64;
    uint_fast64_t uiZ0;
    struct exp32_sig128 normExpSig;
    struct uint128 sig128;
    union { struct extFloat80M s; extFloat80_t f; } uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign   = signF128UI64( uiA64 );
    exp    = expF128UI64( uiA64 );
    frac64 = fracF128UI64( uiA64 );
    frac0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 | frac0 ) {
            softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN );
            uiZ = softfloat_commonNaNToExtF80UI( &commonNaN );
            uiZ64 = uiZ.v64;
            uiZ0  = uiZ.v0;
        } else {
            uiZ64 = packToExtF80UI64( sign, 0x7FFF );
            uiZ0  = UINT64_C( 0x8000000000000000 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! exp ) {
        if ( ! (frac64 | frac0) ) {
            uiZ64 = packToExtF80UI64( sign, 0 );
            uiZ0  = 0;
            goto uiZ;
        }
        normExpSig = softfloat_normSubnormalF128Sig( frac64, frac0 );
        exp   = normExpSig.exp;
        frac64 = normExpSig.sig.v64;
        frac0  = normExpSig.sig.v0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig128 =
        softfloat_shortShiftLeft128(
            frac64 | UINT64_C( 0x0001000000000000 ), frac0, 15 );
    return softfloat_roundPackToExtF80( sign, exp, sig128.v64, sig128.v0, 80 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.s.signExp = uiZ64;
    uZ.s.signif  = uiZ0;
    return uZ.f;

}

/**** ended inlining ../../source/f128_to_extF80.c ****/
/**** start inlining ../../source/f128_to_f64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float64_t f128_to_f64( float128_t a )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool sign;
    int_fast32_t exp;
    uint_fast64_t frac64, frac0;
    struct commonNaN commonNaN;
    uint_fast64_t uiZ;
    struct uint128 frac128;
    union ui64_f64 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    sign  = signF128UI64( uiA64 );
    exp   = expF128UI64( uiA64 );
    frac64 = fracF128UI64( uiA64 );
    frac0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 | frac0 ) {
            softfloat_f128UIToCommonNaN( uiA64, uiA0, &commonNaN );
            uiZ = softfloat_commonNaNToF64UI( &commonNaN );
        } else {
            uiZ = packToF64UI( sign, 0x7FF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac128 = softfloat_shortShiftLeft128( frac64, frac0, 14 );
    frac64 = frac128.v64 | (frac128.v0 != 0);
    if ( ! (exp | frac64) ) {
        uiZ = packToF64UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3C01;
    if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return
        softfloat_roundPackToF64(
            sign, exp, frac64 | UINT64_C( 0x4000000000000000 ) );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_to_f64.c ****/
/**** start inlining ../../source/f128_roundToInt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float128_t
 f128_roundToInt( float128_t a, uint_fast8_t roundingMode, bool exact )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    int_fast32_t exp;
    struct uint128 uiZ;
    uint_fast64_t lastBitMask0, roundBitsMask;
    bool roundNearEven;
    uint_fast64_t lastBitMask64;
    union ui128_f128 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    exp = expF128UI64( uiA64 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( 0x402F <= exp ) {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( 0x406F <= exp ) {
            if ( (exp == 0x7FFF) && (fracF128UI64( uiA64 ) | uiA0) ) {
                uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, 0, 0 );
                goto uiZ;
            }
            return a;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        lastBitMask0 = (uint_fast64_t) 2<<(0x406E - exp);
        roundBitsMask = lastBitMask0 - 1;
        uiZ.v64 = uiA64;
        uiZ.v0  = uiA0;
        roundNearEven = (roundingMode == softfloat_round_near_even);
        if ( roundNearEven || (roundingMode == softfloat_round_near_maxMag) ) {
            if ( exp == 0x402F ) {
                if ( UINT64_C( 0x8000000000000000 ) <= uiZ.v0 ) {
                    ++uiZ.v64;
                    if (
                        roundNearEven
                            && (uiZ.v0 == UINT64_C( 0x8000000000000000 ))
                    ) {
                        uiZ.v64 &= ~1;
                    }
                }
            } else {
                uiZ = softfloat_add128( uiZ.v64, uiZ.v0, 0, lastBitMask0>>1 );
                if ( roundNearEven && !(uiZ.v0 & roundBitsMask) ) {
                    uiZ.v0 &= ~lastBitMask0;
                }
            }
        } else if (
            roundingMode
                == (signF128UI64( uiZ.v64 ) ? softfloat_round_min
                        : softfloat_round_max)
        ) {
            uiZ = softfloat_add128( uiZ.v64, uiZ.v0, 0, roundBitsMask );
        }
        uiZ.v0 &= ~roundBitsMask;
        lastBitMask64 = !lastBitMask0;
    } else {
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        if ( exp < 0x3FFF ) {
            if ( !((uiA64 & UINT64_C( 0x7FFFFFFFFFFFFFFF )) | uiA0) ) return a;
            if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
            uiZ.v64 = uiA64 & packToF128UI64( 1, 0, 0 );
            uiZ.v0  = 0;
            switch ( roundingMode ) {
             case softfloat_round_near_even:
                if ( !(fracF128UI64( uiA64 ) | uiA0) ) break;
             case softfloat_round_near_maxMag:
                if ( exp == 0x3FFE ) uiZ.v64 |= packToF128UI64( 0, 0x3FFF, 0 );
                break;
             case softfloat_round_min:
                if ( uiZ.v64 ) uiZ.v64 = packToF128UI64( 1, 0x3FFF, 0 );
                break;
             case softfloat_round_max:
                if ( !uiZ.v64 ) uiZ.v64 = packToF128UI64( 0, 0x3FFF, 0 );
                break;
#ifdef SOFTFLOAT_ROUND_ODD
             case softfloat_round_odd:
                uiZ.v64 |= packToF128UI64( 0, 0x3FFF, 0 );
                break;
#endif
            }
            goto uiZ;
        }
        /*--------------------------------------------------------------------
        *--------------------------------------------------------------------*/
        uiZ.v64 = uiA64;
        uiZ.v0  = 0;
        lastBitMask64 = (uint_fast64_t) 1<<(0x402F - exp);
        roundBitsMask = lastBitMask64 - 1;
        if ( roundingMode == softfloat_round_near_maxMag ) {
            uiZ.v64 += lastBitMask64>>1;
        } else if ( roundingMode == softfloat_round_near_even ) {
            uiZ.v64 += lastBitMask64>>1;
            if ( !((uiZ.v64 & roundBitsMask) | uiA0) ) {
                uiZ.v64 &= ~lastBitMask64;
            }
        } else if (
            roundingMode
                == (signF128UI64( uiZ.v64 ) ? softfloat_round_min
                        : softfloat_round_max)
        ) {
            uiZ.v64 = (uiZ.v64 | (uiA0 != 0)) + roundBitsMask;
        }
        uiZ.v64 &= ~roundBitsMask;
        lastBitMask0 = 0;
    }
    if ( (uiZ.v64 != uiA64) || (uiZ.v0 != uiA0) ) {
#ifdef SOFTFLOAT_ROUND_ODD
        if ( roundingMode == softfloat_round_odd ) {
            uiZ.v64 |= lastBitMask64;
            uiZ.v0  |= lastBitMask0;
        }
#endif
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_roundToInt.c ****/
/**** start inlining ../../source/f128_add.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_add( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    float128_t
        (*magsFuncPtr)(
            uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool );
#endif

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    signB = signF128UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        return softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        return softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_addMagsF128 : softfloat_subMagsF128;
    return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

/**** ended inlining ../../source/f128_add.c ****/
/**** start inlining ../../source/f128_sub.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_sub( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    float128_t
        (*magsFuncPtr)(
            uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool );
#endif

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    signB = signF128UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        return softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        return softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_subMagsF128 : softfloat_addMagsF128;
    return (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

/**** ended inlining ../../source/f128_sub.c ****/
/**** start inlining ../../source/f128_mul.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_mul( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    int_fast32_t expA;
    struct uint128 sigA;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signB;
    int_fast32_t expB;
    struct uint128 sigB;
    bool signZ;
    uint_fast64_t magBits;
    struct exp32_sig128 normExpSig;
    int_fast32_t expZ;
    uint64_t sig256Z[4];
    uint_fast64_t sigZExtra;
    struct uint128 sigZ;
    struct uint128_extra sig128Extra;
    struct uint128 uiZ;
    union ui128_f128 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    expA  = expF128UI64( uiA64 );
    sigA.v64 = fracF128UI64( uiA64 );
    sigA.v0  = uiA0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    signB = signF128UI64( uiB64 );
    expB  = expF128UI64( uiB64 );
    sigB.v64 = fracF128UI64( uiB64 );
    sigB.v0  = uiB0;
    signZ = signA ^ signB;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA == 0x7FFF ) {
        if (
            (sigA.v64 | sigA.v0) || ((expB == 0x7FFF) && (sigB.v64 | sigB.v0))
        ) {
            goto propagateNaN;
        }
        magBits = expB | sigB.v64 | sigB.v0;
        goto infArg;
    }
    if ( expB == 0x7FFF ) {
        if ( sigB.v64 | sigB.v0 ) goto propagateNaN;
        magBits = expA | sigA.v64 | sigA.v0;
        goto infArg;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expA ) {
        if ( ! (sigA.v64 | sigA.v0) ) goto zero;
        normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 );
        expA = normExpSig.exp;
        sigA = normExpSig.sig;
    }
    if ( ! expB ) {
        if ( ! (sigB.v64 | sigB.v0) ) goto zero;
        normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 );
        expB = normExpSig.exp;
        sigB = normExpSig.sig;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA + expB - 0x4000;
    sigA.v64 |= UINT64_C( 0x0001000000000000 );
    sigB = softfloat_shortShiftLeft128( sigB.v64, sigB.v0, 16 );
    softfloat_mul128To256M( sigA.v64, sigA.v0, sigB.v64, sigB.v0, sig256Z );
    sigZExtra = sig256Z[indexWord( 4, 1 )] | (sig256Z[indexWord( 4, 0 )] != 0);
    sigZ =
        softfloat_add128(
            sig256Z[indexWord( 4, 3 )], sig256Z[indexWord( 4, 2 )],
            sigA.v64, sigA.v0
        );
    if ( UINT64_C( 0x0002000000000000 ) <= sigZ.v64 ) {
        ++expZ;
        sig128Extra =
            softfloat_shortShiftRightJam128Extra(
                sigZ.v64, sigZ.v0, sigZExtra, 1 );
        sigZ = sig128Extra.v;
        sigZExtra = sig128Extra.extra;
    }
    return
        softfloat_roundPackToF128( signZ, expZ, sigZ.v64, sigZ.v0, sigZExtra );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 propagateNaN:
    uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 );
    goto uiZ;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 infArg:
    if ( ! magBits ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        uiZ.v64 = defaultNaNF128UI64;
        uiZ.v0  = defaultNaNF128UI0;
        goto uiZ;
    }
    uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 );
    goto uiZ0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 zero:
    uiZ.v64 = packToF128UI64( signZ, 0, 0 );
 uiZ0:
    uiZ.v0 = 0;
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_mul.c ****/
/**** start inlining ../../source/f128_mulAdd.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_mulAdd( float128_t a, float128_t b, float128_t c )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    union ui128_f128 uC;
    uint_fast64_t uiC64, uiC0;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    uC.f = c;
    uiC64 = uC.ui.v64;
    uiC0  = uC.ui.v0;
    return softfloat_mulAddF128( uiA64, uiA0, uiB64, uiB0, uiC64, uiC0, 0 );

}

/**** ended inlining ../../source/f128_mulAdd.c ****/
/**** start inlining ../../source/f128_div.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_div( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    int_fast32_t expA;
    struct uint128 sigA;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signB;
    int_fast32_t expB;
    struct uint128 sigB;
    bool signZ;
    struct exp32_sig128 normExpSig;
    int_fast32_t expZ;
    struct uint128 rem;
    uint_fast32_t recip32;
    int ix;
    uint_fast64_t q64;
    uint_fast32_t q;
    struct uint128 term;
    uint_fast32_t qs[3];
    uint_fast64_t sigZExtra;
    struct uint128 sigZ, uiZ;
    union ui128_f128 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    expA  = expF128UI64( uiA64 );
    sigA.v64 = fracF128UI64( uiA64 );
    sigA.v0  = uiA0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    signB = signF128UI64( uiB64 );
    expB  = expF128UI64( uiB64 );
    sigB.v64 = fracF128UI64( uiB64 );
    sigB.v0  = uiB0;
    signZ = signA ^ signB;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA == 0x7FFF ) {
        if ( sigA.v64 | sigA.v0 ) goto propagateNaN;
        if ( expB == 0x7FFF ) {
            if ( sigB.v64 | sigB.v0 ) goto propagateNaN;
            goto invalid;
        }
        goto infinity;
    }
    if ( expB == 0x7FFF ) {
        if ( sigB.v64 | sigB.v0 ) goto propagateNaN;
        goto zero;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expB ) {
        if ( ! (sigB.v64 | sigB.v0) ) {
            if ( ! (expA | sigA.v64 | sigA.v0) ) goto invalid;
            softfloat_raiseFlags( softfloat_flag_infinite );
            goto infinity;
        }
        normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 );
        expB = normExpSig.exp;
        sigB = normExpSig.sig;
    }
    if ( ! expA ) {
        if ( ! (sigA.v64 | sigA.v0) ) goto zero;
        normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 );
        expA = normExpSig.exp;
        sigA = normExpSig.sig;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA - expB + 0x3FFE;
    sigA.v64 |= UINT64_C( 0x0001000000000000 );
    sigB.v64 |= UINT64_C( 0x0001000000000000 );
    rem = sigA;
    if ( softfloat_lt128( sigA.v64, sigA.v0, sigB.v64, sigB.v0 ) ) {
        --expZ;
        rem = softfloat_add128( sigA.v64, sigA.v0, sigA.v64, sigA.v0 );
    }
    recip32 = softfloat_approxRecip32_1( sigB.v64>>17 );
    ix = 3;
    for (;;) {
        q64 = (uint_fast64_t) (uint32_t) (rem.v64>>19) * recip32;
        q = (q64 + 0x80000000)>>32;
        --ix;
        if ( ix < 0 ) break;
        rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
        term = softfloat_mul128By32( sigB.v64, sigB.v0, q );
        rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
        if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
            --q;
            rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
        }
        qs[ix] = q;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ((q + 1) & 7) < 2 ) {
        rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
        term = softfloat_mul128By32( sigB.v64, sigB.v0, q );
        rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
        if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
            --q;
            rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
        } else if ( softfloat_le128( sigB.v64, sigB.v0, rem.v64, rem.v0 ) ) {
            ++q;
            rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
        }
        if ( rem.v64 | rem.v0 ) q |= 1;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sigZExtra = (uint64_t) ((uint_fast64_t) q<<60);
    term = softfloat_shortShiftLeft128( 0, qs[1], 54 );
    sigZ =
        softfloat_add128(
            (uint_fast64_t) qs[2]<<19, ((uint_fast64_t) qs[0]<<25) + (q>>4),
            term.v64, term.v0
        );
    return
        softfloat_roundPackToF128( signZ, expZ, sigZ.v64, sigZ.v0, sigZExtra );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 propagateNaN:
    uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 );
    goto uiZ;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    uiZ.v64 = defaultNaNF128UI64;
    uiZ.v0  = defaultNaNF128UI0;
    goto uiZ;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 infinity:
    uiZ.v64 = packToF128UI64( signZ, 0x7FFF, 0 );
    goto uiZ0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 zero:
    uiZ.v64 = packToF128UI64( signZ, 0, 0 );
 uiZ0:
    uiZ.v0 = 0;
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_div.c ****/
/**** start inlining ../../source/f128_rem.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_rem( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    int_fast32_t expA;
    struct uint128 sigA;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    int_fast32_t expB;
    struct uint128 sigB;
    struct exp32_sig128 normExpSig;
    struct uint128 rem;
    int_fast32_t expDiff;
    uint_fast32_t q, recip32;
    uint_fast64_t q64;
    struct uint128 term, altRem, meanRem;
    bool signRem;
    struct uint128 uiZ;
    union ui128_f128 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    expA  = expF128UI64( uiA64 );
    sigA.v64 = fracF128UI64( uiA64 );
    sigA.v0  = uiA0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    expB  = expF128UI64( uiB64 );
    sigB.v64 = fracF128UI64( uiB64 );
    sigB.v0  = uiB0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA == 0x7FFF ) {
        if (
            (sigA.v64 | sigA.v0) || ((expB == 0x7FFF) && (sigB.v64 | sigB.v0))
        ) {
            goto propagateNaN;
        }
        goto invalid;
    }
    if ( expB == 0x7FFF ) {
        if ( sigB.v64 | sigB.v0 ) goto propagateNaN;
        return a;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expB ) {
        if ( ! (sigB.v64 | sigB.v0) ) goto invalid;
        normExpSig = softfloat_normSubnormalF128Sig( sigB.v64, sigB.v0 );
        expB = normExpSig.exp;
        sigB = normExpSig.sig;
    }
    if ( ! expA ) {
        if ( ! (sigA.v64 | sigA.v0) ) return a;
        normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 );
        expA = normExpSig.exp;
        sigA = normExpSig.sig;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sigA.v64 |= UINT64_C( 0x0001000000000000 );
    sigB.v64 |= UINT64_C( 0x0001000000000000 );
    rem = sigA;
    expDiff = expA - expB;
    if ( expDiff < 1 ) {
        if ( expDiff < -1 ) return a;
        if ( expDiff ) {
            --expB;
            sigB = softfloat_add128( sigB.v64, sigB.v0, sigB.v64, sigB.v0 );
            q = 0;
        } else {
            q = softfloat_le128( sigB.v64, sigB.v0, rem.v64, rem.v0 );
            if ( q ) {
                rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
            }
        }
    } else {
        recip32 = softfloat_approxRecip32_1( sigB.v64>>17 );
        expDiff -= 30;
        for (;;) {
            q64 = (uint_fast64_t) (uint32_t) (rem.v64>>19) * recip32;
            if ( expDiff < 0 ) break;
            q = (q64 + 0x80000000)>>32;
            rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
            term = softfloat_mul128By32( sigB.v64, sigB.v0, q );
            rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
            if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
                rem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
            }
            expDiff -= 29;
        }
        /*--------------------------------------------------------------------
        | (`expDiff' cannot be less than -29 here.)
        *--------------------------------------------------------------------*/
        q = (uint32_t) (q64>>32)>>(~expDiff & 31);
        rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, expDiff + 30 );
        term = softfloat_mul128By32( sigB.v64, sigB.v0, q );
        rem = softfloat_sub128( rem.v64, rem.v0, term.v64, term.v0 );
        if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
            altRem = softfloat_add128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
            goto selectRem;
        }
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    do {
        altRem = rem;
        ++q;
        rem = softfloat_sub128( rem.v64, rem.v0, sigB.v64, sigB.v0 );
    } while ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) );
 selectRem:
    meanRem = softfloat_add128( rem.v64, rem.v0, altRem.v64, altRem.v0 );
    if (
        (meanRem.v64 & UINT64_C( 0x8000000000000000 ))
            || (! (meanRem.v64 | meanRem.v0) && (q & 1))
    ) {
        rem = altRem;
    }
    signRem = signA;
    if ( rem.v64 & UINT64_C( 0x8000000000000000 ) ) {
        signRem = ! signRem;
        rem = softfloat_sub128( 0, 0, rem.v64, rem.v0 );
    }
    return softfloat_normRoundPackToF128( signRem, expB - 1, rem.v64, rem.v0 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 propagateNaN:
    uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, uiB64, uiB0 );
    goto uiZ;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    uiZ.v64 = defaultNaNF128UI64;
    uiZ.v0  = defaultNaNF128UI0;
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_rem.c ****/
/**** start inlining ../../source/f128_sqrt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

float128_t f128_sqrt( float128_t a )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    int_fast32_t expA;
    struct uint128 sigA, uiZ;
    struct exp32_sig128 normExpSig;
    int_fast32_t expZ;
    uint_fast32_t sig32A, recipSqrt32, sig32Z;
    struct uint128 rem;
    uint32_t qs[3];
    uint_fast32_t q;
    uint_fast64_t x64, sig64Z;
    struct uint128 y, term;
    uint_fast64_t sigZExtra;
    struct uint128 sigZ;
    union ui128_f128 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    signA = signF128UI64( uiA64 );
    expA  = expF128UI64( uiA64 );
    sigA.v64 = fracF128UI64( uiA64 );
    sigA.v0  = uiA0;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA == 0x7FFF ) {
        if ( sigA.v64 | sigA.v0 ) {
            uiZ = softfloat_propagateNaNF128UI( uiA64, uiA0, 0, 0 );
            goto uiZ;
        }
        if ( ! signA ) return a;
        goto invalid;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( signA ) {
        if ( ! (expA | sigA.v64 | sigA.v0) ) return a;
        goto invalid;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ! expA ) {
        if ( ! (sigA.v64 | sigA.v0) ) return a;
        normExpSig = softfloat_normSubnormalF128Sig( sigA.v64, sigA.v0 );
        expA = normExpSig.exp;
        sigA = normExpSig.sig;
    }
    /*------------------------------------------------------------------------
    | (`sig32Z' is guaranteed to be a lower bound on the square root of
    | `sig32A', which makes `sig32Z' also a lower bound on the square root of
    | `sigA'.)
    *------------------------------------------------------------------------*/
    expZ = ((expA - 0x3FFF)>>1) + 0x3FFE;
    expA &= 1;
    sigA.v64 |= UINT64_C( 0x0001000000000000 );
    sig32A = sigA.v64>>17;
    recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A );
    sig32Z = ((uint_fast64_t) sig32A * recipSqrt32)>>32;
    if ( expA ) {
        sig32Z >>= 1;
        rem = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 12 );
    } else {
        rem = softfloat_shortShiftLeft128( sigA.v64, sigA.v0, 13 );
    }
    qs[2] = sig32Z;
    rem.v64 -= (uint_fast64_t) sig32Z * sig32Z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = ((uint32_t) (rem.v64>>2) * (uint_fast64_t) recipSqrt32)>>32;
    x64 = (uint_fast64_t) sig32Z<<32;
    sig64Z = x64 + ((uint_fast64_t) q<<3);
    y = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
    /*------------------------------------------------------------------------
    | (Repeating this loop is a rare occurrence.)
    *------------------------------------------------------------------------*/
    for (;;) {
        term = softfloat_mul64ByShifted32To128( x64 + sig64Z, q );
        rem = softfloat_sub128( y.v64, y.v0, term.v64, term.v0 );
        if ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ) break;
        --q;
        sig64Z -= 1<<3;
    }
    qs[1] = q;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = ((rem.v64>>2) * recipSqrt32)>>32;
    y = softfloat_shortShiftLeft128( rem.v64, rem.v0, 29 );
    sig64Z <<= 1;
    /*------------------------------------------------------------------------
    | (Repeating this loop is a rare occurrence.)
    *------------------------------------------------------------------------*/
    for (;;) {
        term = softfloat_shortShiftLeft128( 0, sig64Z, 32 );
        term = softfloat_add128( term.v64, term.v0, 0, (uint_fast64_t) q<<6 );
        term = softfloat_mul128By32( term.v64, term.v0, q );
        rem = softfloat_sub128( y.v64, y.v0, term.v64, term.v0 );
        if ( ! (rem.v64 & UINT64_C( 0x8000000000000000 )) ) break;
        --q;
    }
    qs[0] = q;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = (((rem.v64>>2) * recipSqrt32)>>32) + 2;
    sigZExtra = (uint64_t) ((uint_fast64_t) q<<59);
    term = softfloat_shortShiftLeft128( 0, qs[1], 53 );
    sigZ =
        softfloat_add128(
            (uint_fast64_t) qs[2]<<18, ((uint_fast64_t) qs[0]<<24) + (q>>5),
            term.v64, term.v0
        );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (q & 0xF) <= 2 ) {
        q &= ~3;
        sigZExtra = (uint64_t) ((uint_fast64_t) q<<59);
        y = softfloat_shortShiftLeft128( sigZ.v64, sigZ.v0, 6 );
        y.v0 |= sigZExtra>>58;
        term = softfloat_sub128( y.v64, y.v0, 0, q );
        y    = softfloat_mul64ByShifted32To128( term.v0,  q );
        term = softfloat_mul64ByShifted32To128( term.v64, q );
        term = softfloat_add128( term.v64, term.v0, 0, y.v64 );
        rem = softfloat_shortShiftLeft128( rem.v64, rem.v0, 20 );
        term = softfloat_sub128( term.v64, term.v0, rem.v64, rem.v0 );
        /*--------------------------------------------------------------------
        | The concatenation of `term' and `y.v0' is now the negative remainder
        | (3 words altogether).
        *--------------------------------------------------------------------*/
        if ( term.v64 & UINT64_C( 0x8000000000000000 ) ) {
            sigZExtra |= 1;
        } else {
            if ( term.v64 | term.v0 | y.v0 ) {
                if ( sigZExtra ) {
                    --sigZExtra;
                } else {
                    sigZ = softfloat_sub128( sigZ.v64, sigZ.v0, 0, 1 );
                    sigZExtra = ~0;
                }
            }
        }
    }
    return softfloat_roundPackToF128( 0, expZ, sigZ.v64, sigZ.v0, sigZExtra );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    uiZ.v64 = defaultNaNF128UI64;
    uiZ.v0  = defaultNaNF128UI0;
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

/**** ended inlining ../../source/f128_sqrt.c ****/
/**** start inlining ../../source/f128_eq.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool f128_eq( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNF128UI( uiA64, uiA0 )
            || softfloat_isSigNaNF128UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    return
           (uiA0 == uiB0)
        && (   (uiA64 == uiB64)
            || (! uiA0 && ! ((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )))
           );

}

/**** ended inlining ../../source/f128_eq.c ****/
/**** start inlining ../../source/f128_le.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

bool f128_le( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signA, signB;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    signA = signF128UI64( uiA64 );
    signB = signF128UI64( uiB64 );
    return
        (signA != signB)
            ? signA
                  || ! (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                            | uiA0 | uiB0)
            : ((uiA64 == uiB64) && (uiA0 == uiB0))
                  || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 ));

}

/**** ended inlining ../../source/f128_le.c ****/
/**** start inlining ../../source/f128_lt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

bool f128_lt( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signA, signB;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    signA = signF128UI64( uiA64 );
    signB = signF128UI64( uiB64 );
    return
        (signA != signB)
            ? signA
                  && (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                          | uiA0 | uiB0)
            : ((uiA64 != uiB64) || (uiA0 != uiB0))
                  && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 ));

}

/**** ended inlining ../../source/f128_lt.c ****/
/**** start inlining ../../source/f128_eq_signaling.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

bool f128_eq_signaling( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    return
           (uiA0 == uiB0)
        && (   (uiA64 == uiB64)
            || (! uiA0 && ! ((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF )))
           );

}

/**** ended inlining ../../source/f128_eq_signaling.c ****/
/**** start inlining ../../source/f128_le_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool f128_le_quiet( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signA, signB;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNF128UI( uiA64, uiA0 )
            || softfloat_isSigNaNF128UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    signA = signF128UI64( uiA64 );
    signB = signF128UI64( uiB64 );
    return
        (signA != signB)
            ? signA
                  || ! (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                            | uiA0 | uiB0)
            : ((uiA64 == uiB64) && (uiA0 == uiB0))
                  || (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 ));

}

/**** ended inlining ../../source/f128_le_quiet.c ****/
/**** start inlining ../../source/f128_lt_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool f128_lt_quiet( float128_t a, float128_t b )
{
    union ui128_f128 uA;
    uint_fast64_t uiA64, uiA0;
    union ui128_f128 uB;
    uint_fast64_t uiB64, uiB0;
    bool signA, signB;

    uA.f = a;
    uiA64 = uA.ui.v64;
    uiA0  = uA.ui.v0;
    uB.f = b;
    uiB64 = uB.ui.v64;
    uiB0  = uB.ui.v0;
    if ( isNaNF128UI( uiA64, uiA0 ) || isNaNF128UI( uiB64, uiB0 ) ) {
        if (
               softfloat_isSigNaNF128UI( uiA64, uiA0 )
            || softfloat_isSigNaNF128UI( uiB64, uiB0 )
        ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    signA = signF128UI64( uiA64 );
    signB = signF128UI64( uiB64 );
    return
        (signA != signB)
            ? signA
                  && (((uiA64 | uiB64) & UINT64_C( 0x7FFFFFFFFFFFFFFF ))
                          | uiA0 | uiB0)
            : ((uiA64 != uiB64) || (uiA0 != uiB0))
                  && (signA ^ softfloat_lt128( uiA64, uiA0, uiB64, uiB0 ));

}

/**** ended inlining ../../source/f128_lt_quiet.c ****/
/**** start inlining ../../source/f128_isSignalingNaN.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

bool f128_isSignalingNaN( float128_t a )
{
    union ui128_f128 uA;

    uA.f = a;
    return softfloat_isSigNaNF128UI( uA.ui.v64, uA.ui.v0 );

}

/**** ended inlining ../../source/f128_isSignalingNaN.c ****/
/**** start inlining ../../source/f128M_to_ui32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast32_t
 f128M_to_ui32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return f128_to_ui32( *aPtr, roundingMode, exact );

}

#else

uint_fast32_t
 f128M_to_ui32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint64_t sig64;
    int32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )];
    if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
#if (ui32_fromNaN != ui32_fromPosOverflow) || (ui32_fromNaN != ui32_fromNegOverflow)
    if ( (exp == 0x7FFF) && sig64 ) {
#if (ui32_fromNaN == ui32_fromPosOverflow)
        sign = 0;
#elif (ui32_fromNaN == ui32_fromNegOverflow)
        sign = 1;
#else
        softfloat_raiseFlags( softfloat_flag_invalid );
        return ui32_fromNaN;
#endif
    }
#endif
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
    shiftDist = 0x4023 - exp;
    if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist );
    return softfloat_roundToUI32( sign, sig64, roundingMode, exact );

}

#endif

/**** ended inlining ../../source/f128M_to_ui32.c ****/
/**** start inlining ../../source/f128M_to_ui64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast64_t
 f128M_to_ui64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return f128_to_ui64( *aPtr, roundingMode, exact );

}

#else

uint_fast64_t
 f128M_to_ui64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint32_t sig96;
    int32_t shiftDist;
    uint32_t sig[4];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign  = signF128UI96( uiA96 );
    exp   = expF128UI96( uiA96 );
    sig96 = fracF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x404F - exp;
    if ( shiftDist < 17 ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF)
                && (sig96
                        || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                                | aWPtr[indexWord( 4, 0 )]))
                ? ui64_fromNaN
                : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig96 |= 0x00010000;
    sig[indexWord( 4, 3 )] = sig96;
    sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
    sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
    sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
    softfloat_shiftRightJam128M( sig, shiftDist, sig );
    return
        softfloat_roundMToUI64(
            sign, sig + indexMultiwordLo( 4, 3 ), roundingMode, exact );

}

#endif

/**** ended inlining ../../source/f128M_to_ui64.c ****/
/**** start inlining ../../source/f128M_to_i32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast32_t
 f128M_to_i32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return f128_to_i32( *aPtr, roundingMode, exact );

}

#else

int_fast32_t
 f128M_to_i32( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint64_t sig64;
    int32_t shiftDist;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )];
    if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
#if (i32_fromNaN != i32_fromPosOverflow) || (i32_fromNaN != i32_fromNegOverflow)
    if ( (exp == 0x7FFF) && sig64 ) {
#if (i32_fromNaN == i32_fromPosOverflow)
        sign = 0;
#elif (i32_fromNaN == i32_fromNegOverflow)
        sign = 1;
#else
        softfloat_raiseFlags( softfloat_flag_invalid );
        return i32_fromNaN;
#endif
    }
#endif
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig64 |= UINT64_C( 0x0001000000000000 );
    shiftDist = 0x4023 - exp;
    if ( 0 < shiftDist ) sig64 = softfloat_shiftRightJam64( sig64, shiftDist );
    return softfloat_roundToI32( sign, sig64, roundingMode, exact );

}

#endif

/**** ended inlining ../../source/f128M_to_i32.c ****/
/**** start inlining ../../source/f128M_to_i64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the
University of California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast64_t
 f128M_to_i64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{

    return f128_to_i64( *aPtr, roundingMode, exact );

}

#else

int_fast64_t
 f128M_to_i64( const float128_t *aPtr, uint_fast8_t roundingMode, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint32_t sig96;
    int32_t shiftDist;
    uint32_t sig[4];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign  = signF128UI96( uiA96 );
    exp   = expF128UI96( uiA96 );
    sig96 = fracF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x404F - exp;
    if ( shiftDist < 17 ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF)
                && (sig96
                        || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                                | aWPtr[indexWord( 4, 0 )]))
                ? i64_fromNaN
                : sign ? i64_fromNegOverflow : i64_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp ) sig96 |= 0x00010000;
    sig[indexWord( 4, 3 )] = sig96;
    sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
    sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
    sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
    softfloat_shiftRightJam128M( sig, shiftDist, sig );
    return
        softfloat_roundMToI64(
            sign, sig + indexMultiwordLo( 4, 3 ), roundingMode, exact );

}

#endif

/**** ended inlining ../../source/f128M_to_i64.c ****/
/**** start inlining ../../source/f128M_to_ui32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast32_t f128M_to_ui32_r_minMag( const float128_t *aPtr, bool exact )
{

    return f128_to_ui32_r_minMag( *aPtr, exact );

}

#else

uint_fast32_t f128M_to_ui32_r_minMag( const float128_t *aPtr, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    int32_t exp;
    uint64_t sig64;
    int32_t shiftDist;
    bool sign;
    uint32_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    exp = expF128UI96( uiA96 );
    sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )];
    if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x402F - exp;
    if ( 49 <= shiftDist ) {
        if ( exact && (exp | sig64) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sign = signF128UI96( uiA96 );
    if ( sign || (shiftDist < 17) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return
            (exp == 0x7FFF) && sig64 ? ui32_fromNaN
                : sign ? ui32_fromNegOverflow : ui32_fromPosOverflow;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    sig64 |= UINT64_C( 0x0001000000000000 );
    z = sig64>>shiftDist;
    if ( exact && ((uint64_t) z<<shiftDist != sig64) ) {
        softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
    return z;

}

#endif

/**** ended inlining ../../source/f128M_to_ui32_r_minMag.c ****/
/**** start inlining ../../source/f128M_to_ui64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact )
{

    return f128_to_ui64_r_minMag( *aPtr, exact );

}

#else

uint_fast64_t f128M_to_ui64_r_minMag( const float128_t *aPtr, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint32_t sig96;
    int32_t shiftDist;
    uint32_t sig[4];
    uint64_t z;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign  = signF128UI96( uiA96 );
    exp   = expF128UI96( uiA96 );
    sig96 = fracF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x403E - exp;
    if ( shiftDist < 0 ) goto invalid;
    if ( exact ) {
        if ( exp ) sig96 |= 0x00010000;
        sig[indexWord( 4, 3 )] = sig96;
        sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
        sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
        sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
        softfloat_shiftRightJam128M( sig, shiftDist + 17, sig );
        z = (uint64_t) sig[indexWord( 4, 2 )]<<32 | sig[indexWord( 4, 1 )];
        if ( sign && z ) goto invalid;
        if ( sig[indexWordLo( 4 )] ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    } else {
        if ( 64 <= shiftDist ) return 0;
        if ( sign ) goto invalid;
        z =   UINT64_C( 0x8000000000000000 )
            | (uint64_t) sig96<<47
            | (uint64_t) aWPtr[indexWord( 4, 2 )]<<15
            | aWPtr[indexWord( 4, 1 )]>>17;
        z >>= shiftDist;
    }
    return z;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF)
            && (sig96
                    || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                            | aWPtr[indexWord( 4, 0 )]))
            ? ui64_fromNaN
            : sign ? ui64_fromNegOverflow : ui64_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/f128M_to_ui64_r_minMag.c ****/
/**** start inlining ../../source/f128M_to_i32_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast32_t f128M_to_i32_r_minMag( const float128_t *aPtr, bool exact )
{

    return f128_to_i32_r_minMag( *aPtr, exact );

}

#else

int_fast32_t f128M_to_i32_r_minMag( const float128_t *aPtr, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint64_t sig64;
    int32_t shiftDist;
    uint32_t absZ, uiZ;
    union { uint32_t ui; int32_t i; } uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    sig64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )];
    if ( aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) sig64 |= 1;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp < 0x3FFF ) {
        if ( exact && (exp | sig64) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
        return 0;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( 0x401F <= exp ) goto invalid;
    shiftDist = 0x402F - exp;
    sig64 |= UINT64_C( 0x0001000000000000 );
    absZ = sig64>>shiftDist;
    uiZ = sign ? -absZ : absZ;
    if ( uiZ>>31 != sign ) goto invalid;
    if ( exact && ((uint64_t) absZ<<shiftDist != sig64) ) {
        softfloat_exceptionFlags |= softfloat_flag_inexact;
    }
    uZ.ui = uiZ;
    return uZ.i;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF) && sig64 ? i32_fromNaN
            : sign ? i32_fromNegOverflow : i32_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/f128M_to_i32_r_minMag.c ****/
/**** start inlining ../../source/f128M_to_i64_r_minMag.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

int_fast64_t f128M_to_i64_r_minMag( const float128_t *aPtr, bool exact )
{

    return f128_to_i64_r_minMag( *aPtr, exact );

}

#else

int_fast64_t f128M_to_i64_r_minMag( const float128_t *aPtr, bool exact )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint32_t sig96;
    int32_t shiftDist;
    uint32_t sig[4];
    uint64_t uiZ;
    union { uint64_t ui; int64_t i; } uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign  = signF128UI96( uiA96 );
    exp   = expF128UI96( uiA96 );
    sig96 = fracF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    shiftDist = 0x403E - exp;
    if ( shiftDist < 0 ) goto invalid;
    if ( exact ) {
        if ( exp ) sig96 |= 0x00010000;
        sig[indexWord( 4, 3 )] = sig96;
        sig[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
        sig[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
        sig[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
        softfloat_shiftRightJam128M( sig, shiftDist + 17, sig );
        uiZ = (uint64_t) sig[indexWord( 4, 2 )]<<32 | sig[indexWord( 4, 1 )];
        if ( uiZ>>63 && (! sign || (uiZ != UINT64_C( 0x8000000000000000 ))) ) {
            goto invalid;
        }
        if ( sig[indexWordLo( 4 )] ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
    } else {
        if ( 64 <= shiftDist ) return 0;
        uiZ =
              (uint64_t) sig96<<47
            | (uint64_t) aWPtr[indexWord( 4, 2 )]<<15
            | aWPtr[indexWord( 4, 1 )]>>17;
        if ( shiftDist ) {
            uiZ |= UINT64_C( 0x8000000000000000 );
            uiZ >>= shiftDist;
        } else {
            if ( uiZ || ! sign ) goto invalid;
            uiZ |= UINT64_C( 0x8000000000000000 );
        }
    }
    if ( sign ) uiZ = -uiZ;
    uZ.ui = uiZ;
    return uZ.i;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_raiseFlags( softfloat_flag_invalid );
    return
        (exp == 0x7FFF)
            && (sig96
                    || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                            | aWPtr[indexWord( 4, 0 )]))
            ? i64_fromNaN
            : sign ? i64_fromNegOverflow : i64_fromPosOverflow;

}

#endif

/**** ended inlining ../../source/f128M_to_i64_r_minMag.c ****/
/**** start inlining ../../source/f128M_to_f16.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float16_t f128M_to_f16( const float128_t *aPtr )
{

    return f128_to_f16( *aPtr );

}

#else

float16_t f128M_to_f16( const float128_t *aPtr )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint32_t frac32;
    struct commonNaN commonNaN;
    uint16_t uiZ, frac16;
    union ui16_f16 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    frac32 =
        fracF128UI96( uiA96 )
            | ((aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                    | aWPtr[indexWord( 4, 0 )])
                   != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac32 ) {
            softfloat_f128MToCommonNaN( aWPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF16UI( &commonNaN );
        } else {
            uiZ = packToF16UI( sign, 0x1F, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac16 = frac32>>2 | (frac32 & 3);
    if ( ! (exp | frac16) ) {
        uiZ = packToF16UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3FF1;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x40 ) exp = -0x40;
    }
    return softfloat_roundPackToF16( sign, exp, frac16 | 0x4000 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/f128M_to_f16.c ****/
/**** start inlining ../../source/f128M_to_f32.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float32_t f128M_to_f32( const float128_t *aPtr )
{

    return f128_to_f32( *aPtr );

}

#else

float32_t f128M_to_f32( const float128_t *aPtr )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint64_t frac64;
    struct commonNaN commonNaN;
    uint32_t uiZ, frac32;
    union ui32_f32 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    frac64 =
        (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )]
            | ((aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )]) != 0);
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 ) {
            softfloat_f128MToCommonNaN( aWPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF32UI( &commonNaN );
        } else {
            uiZ = packToF32UI( sign, 0xFF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac32 = softfloat_shortShiftRightJam64( frac64, 18 );
    if ( ! (exp | frac32) ) {
        uiZ = packToF32UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3F81;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return softfloat_roundPackToF32( sign, exp, frac32 | 0x40000000 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/f128M_to_f32.c ****/
/**** start inlining ../../source/f128M_to_extF80M.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr )
{

    *zPtr = f128_to_extF80( *aPtr );

}

#else

void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr )
{
    const uint32_t *aWPtr;
    struct extFloat80M *zSPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    struct commonNaN commonNaN;
    uint32_t sig[4];

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    zSPtr = (struct extFloat80M *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( softfloat_isNaNF128M( aWPtr ) ) {
            softfloat_f128MToCommonNaN( aWPtr, &commonNaN );
            softfloat_commonNaNToExtF80M( &commonNaN, zSPtr );
            return;
        }
        zSPtr->signExp = packToExtF80UI64( sign, 0x7FFF );
        zSPtr->signif = UINT64_C( 0x8000000000000000 );
        return;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp = softfloat_shiftNormSigF128M( aWPtr, 15, sig );
    if ( exp == -128 ) {
        zSPtr->signExp = packToExtF80UI64( sign, 0 );
        zSPtr->signif = 0;
        return;
    }
    if ( sig[indexWord( 4, 0 )] ) sig[indexWord( 4, 1 )] |= 1;
    softfloat_roundPackMToExtF80M(
        sign, exp, &sig[indexMultiwordHi( 4, 3 )], 80, zSPtr );

}

#endif

/**** ended inlining ../../source/f128M_to_extF80M.c ****/
/**** start inlining ../../source/f128M_to_f64.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

float64_t f128M_to_f64( const float128_t *aPtr )
{

    return f128_to_f64( *aPtr );

}

#else

float64_t f128M_to_f64( const float128_t *aPtr )
{
    const uint32_t *aWPtr;
    uint32_t uiA96;
    bool sign;
    int32_t exp;
    uint64_t frac64;
    struct commonNaN commonNaN;
    uint64_t uiZ;
    uint32_t frac32;
    union ui64_f64 uZ;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    uiA96 = aWPtr[indexWordHi( 4 )];
    sign = signF128UI96( uiA96 );
    exp  = expF128UI96( uiA96 );
    frac64 = (uint64_t) fracF128UI96( uiA96 )<<32 | aWPtr[indexWord( 4, 2 )];
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp == 0x7FFF ) {
        if ( frac64 || aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )] ) {
            softfloat_f128MToCommonNaN( aWPtr, &commonNaN );
            uiZ = softfloat_commonNaNToF64UI( &commonNaN );
        } else {
            uiZ = packToF64UI( sign, 0x7FF, 0 );
        }
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    frac32 = aWPtr[indexWord( 4, 1 )];
    frac64 = frac64<<14 | frac32>>18;
    if ( (frac32 & 0x0003FFFF) || aWPtr[indexWord( 4, 0 )] ) frac64 |= 1;
    if ( ! (exp | frac64) ) {
        uiZ = packToF64UI( sign, 0, 0 );
        goto uiZ;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    exp -= 0x3C01;
    if ( sizeof (int_fast16_t) < sizeof (int32_t) ) {
        if ( exp < -0x1000 ) exp = -0x1000;
    }
    return
        softfloat_roundPackToF64(
            sign, exp, frac64 | UINT64_C( 0x4000000000000000 ) );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 uiZ:
    uZ.ui = uiZ;
    return uZ.f;

}

#endif

/**** ended inlining ../../source/f128M_to_f64.c ****/
/**** start inlining ../../source/f128M_roundToInt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_roundToInt(
     const float128_t *aPtr,
     uint_fast8_t roundingMode,
     bool exact,
     float128_t *zPtr
 )
{

    *zPtr = f128_roundToInt( *aPtr, roundingMode, exact );

}

#else

void
 f128M_roundToInt(
     const float128_t *aPtr,
     uint_fast8_t roundingMode,
     bool exact,
     float128_t *zPtr
 )
{
    const uint32_t *aWPtr;
    uint32_t *zWPtr;
    uint32_t ui96;
    int32_t exp;
    uint32_t sigExtra;
    bool sign;
    uint_fast8_t bitPos;
    bool roundNear;
    unsigned int index, lastIndex;
    bool extra;
    uint32_t wordA, bit, wordZ;
    uint_fast8_t carry;
    uint32_t extrasMask;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    ui96 = aWPtr[indexWordHi( 4 )];
    exp = expF128UI96( ui96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( exp < 0x3FFF ) {
        zWPtr[indexWord( 4, 2 )] = 0;
        zWPtr[indexWord( 4, 1 )] = 0;
        zWPtr[indexWord( 4, 0 )] = 0;
        sigExtra = aWPtr[indexWord( 4, 2 )];
        if ( !sigExtra ) {
            sigExtra = aWPtr[indexWord( 4, 1 )] | aWPtr[indexWord( 4, 0 )];
        }
        if ( !sigExtra && !(ui96 & 0x7FFFFFFF) ) goto ui96;
        if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
        sign = signF128UI96( ui96 );
        switch ( roundingMode ) {
         case softfloat_round_near_even:
            if ( !fracF128UI96( ui96 ) && !sigExtra ) break;
         case softfloat_round_near_maxMag:
            if ( exp == 0x3FFE ) goto mag1;
            break;
         case softfloat_round_min:
            if ( sign ) goto mag1;
            break;
         case softfloat_round_max:
            if ( !sign ) goto mag1;
            break;
#ifdef SOFTFLOAT_ROUND_ODD
         case softfloat_round_odd:
            goto mag1;
#endif
        }
        ui96 = packToF128UI96( sign, 0, 0 );
        goto ui96;
     mag1:
        ui96 = packToF128UI96( sign, 0x3FFF, 0 );
        goto ui96;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( 0x406F <= exp ) {
        if (
            (exp == 0x7FFF)
                && (fracF128UI96( ui96 )
                        || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                                | aWPtr[indexWord( 4, 0 )]))
        ) {
            softfloat_propagateNaNF128M( aWPtr, 0, zWPtr );
            return;
        }
        zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
        zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
        zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
        goto ui96;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    bitPos = 0x406F - exp;
    roundNear =
           (roundingMode == softfloat_round_near_maxMag)
        || (roundingMode == softfloat_round_near_even);
    bitPos -= roundNear;
    index = indexWordLo( 4 );
    lastIndex = indexWordHi( 4 );
    extra = 0;
    for (;;) {
        wordA = aWPtr[index];
        if ( bitPos < 32 ) break;
        if ( wordA ) extra = 1;
        zWPtr[index] = 0;
        index += wordIncr;
        bitPos -= 32;
    }
    bit = (uint32_t) 1<<bitPos;
    if ( roundNear ) {
        wordZ = wordA + bit;
        carry = (wordZ < wordA);
        bit <<= 1;
        extrasMask = bit - 1;
        if ( exact && (extra || (wordA & extrasMask)) ) {
            softfloat_exceptionFlags |= softfloat_flag_inexact;
        }
        if (
            (roundingMode == softfloat_round_near_even)
                && !extra && !(wordZ & extrasMask)
        ) {
            if ( !bit ) {
                zWPtr[index] = wordZ;
                index += wordIncr;
                wordZ = aWPtr[index] + carry;
                carry &= !wordZ;
                zWPtr[index] = wordZ & ~1;
                goto propagateCarry;
            }
            wordZ &= ~bit;
        }
    } else {
        wordZ = wordA;
        carry = 0;
        extrasMask = bit - 1;
        if ( extra || (wordA & extrasMask) ) {
            if ( exact ) softfloat_exceptionFlags |= softfloat_flag_inexact;
            if (
                roundingMode
                    == (signF128UI96( ui96 ) ? softfloat_round_min
                            : softfloat_round_max)
            ) {
                wordZ += bit;
                carry = (wordZ < wordA);
#ifdef SOFTFLOAT_ROUND_ODD
            } else if ( roundingMode == softfloat_round_odd ) {
                wordZ |= bit;
#endif
            }
        }
    }
    wordZ &= ~extrasMask;
    zWPtr[index] = wordZ;
 propagateCarry:
    while ( index != lastIndex ) {
        index += wordIncr;
        wordZ = aWPtr[index] + carry;
        zWPtr[index] = wordZ;
        carry &= !wordZ;
    }
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 ui96:
    zWPtr[indexWordHi( 4 )] = ui96;

}

#endif

/**** ended inlining ../../source/f128M_roundToInt.c ****/
/**** start inlining ../../source/f128M_add.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_add( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{
    const uint64_t *aWPtr, *bWPtr;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    uint_fast64_t uiB64, uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    float128_t
        (*magsFuncPtr)(
            uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool );
#endif

    aWPtr = (const uint64_t *) aPtr;
    bWPtr = (const uint64_t *) bPtr;
    uiA64 = aWPtr[indexWord( 2, 1 )];
    uiA0  = aWPtr[indexWord( 2, 0 )];
    signA = signF128UI64( uiA64 );
    uiB64 = bWPtr[indexWord( 2, 1 )];
    uiB0  = bWPtr[indexWord( 2, 0 )];
    signB = signF128UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        *zPtr = softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        *zPtr = softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_addMagsF128 : softfloat_subMagsF128;
    *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

#else

void
 f128M_add( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{

    softfloat_addF128M(
        (const uint32_t *) aPtr,
        (const uint32_t *) bPtr,
        (uint32_t *) zPtr,
        false
    );

}

#endif

/**** ended inlining ../../source/f128M_add.c ****/
/**** start inlining ../../source/f128M_sub.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_sub( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{
    const uint64_t *aWPtr, *bWPtr;
    uint_fast64_t uiA64, uiA0;
    bool signA;
    uint_fast64_t uiB64, uiB0;
    bool signB;
#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2)
    float128_t
        (*magsFuncPtr)(
            uint_fast64_t, uint_fast64_t, uint_fast64_t, uint_fast64_t, bool );
#endif

    aWPtr = (const uint64_t *) aPtr;
    bWPtr = (const uint64_t *) bPtr;
    uiA64 = aWPtr[indexWord( 2, 1 )];
    uiA0  = aWPtr[indexWord( 2, 0 )];
    signA = signF128UI64( uiA64 );
    uiB64 = bWPtr[indexWord( 2, 1 )];
    uiB0  = bWPtr[indexWord( 2, 0 )];
    signB = signF128UI64( uiB64 );
#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL)
    if ( signA == signB ) {
        *zPtr = softfloat_subMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    } else {
        *zPtr = softfloat_addMagsF128( uiA64, uiA0, uiB64, uiB0, signA );
    }
#else
    magsFuncPtr =
        (signA == signB) ? softfloat_subMagsF128 : softfloat_addMagsF128;
    *zPtr = (*magsFuncPtr)( uiA64, uiA0, uiB64, uiB0, signA );
#endif

}

#else

void
 f128M_sub( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{

    softfloat_addF128M(
        (const uint32_t *) aPtr,
        (const uint32_t *) bPtr,
        (uint32_t *) zPtr,
        true
    );

}

#endif

/**** ended inlining ../../source/f128M_sub.c ****/
/**** start inlining ../../source/f128M_mul.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_mul( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{

    *zPtr = f128_mul( *aPtr, *bPtr );

}

#else

void
 f128M_mul( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t *zWPtr;
    uint32_t uiA96;
    int32_t expA;
    uint32_t uiB96;
    int32_t expB;
    bool signZ;
    const uint32_t *ptr;
    uint32_t uiZ96, sigA[4];
    uint_fast8_t shiftDist;
    uint32_t sigB[4];
    int32_t expZ;
    uint32_t sigProd[8], *extSigZPtr;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    expA = expF128UI96( uiA96 );
    uiB96 = bWPtr[indexWordHi( 4 )];
    expB = expF128UI96( uiB96 );
    signZ = signF128UI96( uiA96 ) ^ signF128UI96( uiB96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return;
        ptr = aWPtr;
        if ( ! expA ) goto possiblyInvalid;
        if ( ! expB ) {
            ptr = bWPtr;
     possiblyInvalid:
            if (
                ! fracF128UI96( ptr[indexWordHi( 4 )] )
                    && ! (ptr[indexWord( 4, 2 )] | ptr[indexWord( 4, 1 )]
                              | ptr[indexWord( 4, 0 )])
            ) {
                softfloat_invalidF128M( zWPtr );
                return;
            }
        }
        uiZ96 = packToF128UI96( signZ, 0x7FFF, 0 );
        goto uiZ96;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA ) {
        sigA[indexWordHi( 4 )] = fracF128UI96( uiA96 ) | 0x00010000;
        sigA[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
        sigA[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
        sigA[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];
    } else {
        expA = softfloat_shiftNormSigF128M( aWPtr, 0, sigA );
        if ( expA == -128 ) goto zero;
    }
    if ( expB ) {
        sigB[indexWordHi( 4 )] = fracF128UI96( uiB96 ) | 0x00010000;
        sigB[indexWord( 4, 2 )] = bWPtr[indexWord( 4, 2 )];
        sigB[indexWord( 4, 1 )] = bWPtr[indexWord( 4, 1 )];
        sigB[indexWord( 4, 0 )] = bWPtr[indexWord( 4, 0 )];
    } else {
        expB = softfloat_shiftNormSigF128M( bWPtr, 0, sigB );
        if ( expB == -128 ) goto zero;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA + expB - 0x4000;
    softfloat_mul128MTo256M( sigA, sigB, sigProd );
    if (
        sigProd[indexWord( 8, 2 )]
            || (sigProd[indexWord( 8, 1 )] | sigProd[indexWord( 8, 0 )])
    ) {
        sigProd[indexWord( 8, 3 )] |= 1;
    }
    extSigZPtr = &sigProd[indexMultiwordHi( 8, 5 )];
    shiftDist = 16;
    if ( extSigZPtr[indexWordHi( 5 )] & 2 ) {
        ++expZ;
        shiftDist = 15;
    }
    softfloat_shortShiftLeft160M( extSigZPtr, shiftDist, extSigZPtr );
    softfloat_roundPackMToF128M( signZ, expZ, extSigZPtr, zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 zero:
    uiZ96 = packToF128UI96( signZ, 0, 0 );
 uiZ96:
    zWPtr[indexWordHi( 4 )] = uiZ96;
    zWPtr[indexWord( 4, 2 )] = 0;
    zWPtr[indexWord( 4, 1 )] = 0;
    zWPtr[indexWord( 4, 0 )] = 0;

}

#endif

/**** ended inlining ../../source/f128M_mul.c ****/
/**** start inlining ../../source/f128M_mulAdd.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_mulAdd(
     const float128_t *aPtr,
     const float128_t *bPtr,
     const float128_t *cPtr,
     float128_t *zPtr
 )
{
    const uint64_t *aWPtr, *bWPtr, *cWPtr;
    uint_fast64_t uiA64, uiA0;
    uint_fast64_t uiB64, uiB0;
    uint_fast64_t uiC64, uiC0;

    aWPtr = (const uint64_t *) aPtr;
    bWPtr = (const uint64_t *) bPtr;
    cWPtr = (const uint64_t *) cPtr;
    uiA64 = aWPtr[indexWord( 2, 1 )];
    uiA0  = aWPtr[indexWord( 2, 0 )];
    uiB64 = bWPtr[indexWord( 2, 1 )];
    uiB0  = bWPtr[indexWord( 2, 0 )];
    uiC64 = cWPtr[indexWord( 2, 1 )];
    uiC0  = cWPtr[indexWord( 2, 0 )];
    *zPtr = softfloat_mulAddF128( uiA64, uiA0, uiB64, uiB0, uiC64, uiC0, 0 );

}

#else

void
 f128M_mulAdd(
     const float128_t *aPtr,
     const float128_t *bPtr,
     const float128_t *cPtr,
     float128_t *zPtr
 )
{

    softfloat_mulAddF128M(
        (const uint32_t *) aPtr,
        (const uint32_t *) bPtr,
        (const uint32_t *) cPtr,
        (uint32_t *) zPtr,
        0
    );

}

#endif

/**** ended inlining ../../source/f128M_mulAdd.c ****/
/**** start inlining ../../source/f128M_div.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_div( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{

    *zPtr = f128_div( *aPtr, *bPtr );

}

#else

void
 f128M_div( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t *zWPtr, uiA96;
    bool signA;
    int32_t expA;
    uint32_t uiB96;
    bool signB;
    int32_t expB;
    bool signZ;
    uint32_t y[5], sigB[4];
    int32_t expZ;
    uint32_t recip32;
    int ix;
    uint64_t q64;
    uint32_t q, qs[3], uiZ96;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    expA  = expF128UI96( uiA96 );
    uiB96 = bWPtr[indexWordHi( 4 )];
    signB = signF128UI96( uiB96 );
    expB  = expF128UI96( uiB96 );
    signZ = signA ^ signB;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return;
        if ( expA == 0x7FFF ) {
            if ( expB == 0x7FFF ) goto invalid;
            goto infinity;
        }
        goto zero;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expA = softfloat_shiftNormSigF128M( aWPtr, 13, y );
    expB = softfloat_shiftNormSigF128M( bWPtr, 13, sigB );
    if ( expA == -128 ) {
        if ( expB == -128 ) goto invalid;
        goto zero;
    }
    if ( expB == -128 ) {
        softfloat_raiseFlags( softfloat_flag_infinite );
        goto infinity;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expZ = expA - expB + 0x3FFE;
    if ( softfloat_compare128M( y, sigB ) < 0 ) {
        --expZ;
        softfloat_add128M( y, y, y );
    }
    recip32 =
        softfloat_approxRecip32_1(
            ((uint64_t) sigB[indexWord( 4, 3 )]<<32 | sigB[indexWord( 4, 2 )])
                >>30
        );
    ix = 3;
    for (;;) {
        q64 = (uint64_t) y[indexWordHi( 4 )] * recip32;
        q = (q64 + 0x80000000)>>32;
        --ix;
        if ( ix < 0 ) break;
        softfloat_remStep128MBy32( y, 29, sigB, q, y );
        if ( y[indexWordHi( 4 )] & 0x80000000 ) {
            --q;
            softfloat_add128M( y, sigB, y );
        }
        qs[ix] = q;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( ((q + 1) & 7) < 2 ) {
        softfloat_remStep128MBy32( y, 29, sigB, q, y );
        if ( y[indexWordHi( 4 )] & 0x80000000 ) {
            --q;
            softfloat_add128M( y, sigB, y );
        } else if ( softfloat_compare128M( sigB, y ) <= 0 ) {
            ++q;
            softfloat_sub128M( y, sigB, y );
        }
        if (
            y[indexWordLo( 4 )] || y[indexWord( 4, 1 )]
                || (y[indexWord( 4, 2 )] | y[indexWord( 4, 3 )])
        ) {
            q |= 1;
        }
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q64 = (uint64_t) q<<28;
    y[indexWord( 5, 0 )] = q64;
    q64 = ((uint64_t) qs[0]<<25) + (q64>>32);
    y[indexWord( 5, 1 )] = q64;
    q64 = ((uint64_t) qs[1]<<22) + (q64>>32);
    y[indexWord( 5, 2 )] = q64;
    q64 = ((uint64_t) qs[2]<<19) + (q64>>32);
    y[indexWord( 5, 3 )] = q64;
    y[indexWord( 5, 4 )] = q64>>32;
    softfloat_roundPackMToF128M( signZ, expZ, y, zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidF128M( zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 infinity:
    uiZ96 = packToF128UI96( signZ, 0x7FFF, 0 );
    goto uiZ96;
 zero:
    uiZ96 = packToF128UI96( signZ, 0, 0 );
 uiZ96:
    zWPtr[indexWordHi( 4 )] = uiZ96;
    zWPtr[indexWord( 4, 2 )] = 0;
    zWPtr[indexWord( 4, 1 )] = 0;
    zWPtr[indexWord( 4, 0 )] = 0;

}

#endif

/**** ended inlining ../../source/f128M_div.c ****/
/**** start inlining ../../source/f128M_rem.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void
 f128M_rem( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{

    *zPtr = f128_rem( *aPtr, *bPtr );

}

#else

void
 f128M_rem( const float128_t *aPtr, const float128_t *bPtr, float128_t *zPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t *zWPtr, uiA96;
    int32_t expA, expB;
    uint32_t x[4], rem1[5], *remPtr;
    bool signRem;
    int32_t expDiff;
    uint32_t q, recip32;
    uint64_t q64;
    uint32_t rem2[5], *altRemPtr, *newRemPtr, wordMeanRem;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    expA = expF128UI96( uiA96 );
    expB = expF128UI96( bWPtr[indexWordHi( 4 )] );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (expA == 0x7FFF) || (expB == 0x7FFF) ) {
        if ( softfloat_tryPropagateNaNF128M( aWPtr, bWPtr, zWPtr ) ) return;
        if ( expA == 0x7FFF ) goto invalid;
        goto copyA;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( expA < expB - 1 ) goto copyA;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expB = softfloat_shiftNormSigF128M( bWPtr, 13, x );
    if ( expB == -128 ) goto invalid;
    remPtr = &rem1[indexMultiwordLo( 5, 4 )];
    expA = softfloat_shiftNormSigF128M( aWPtr, 13, remPtr );
    if ( expA == -128 ) goto copyA;
    signRem = signF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expDiff = expA - expB;
    if ( expDiff < 1 ) {
        if ( expDiff < -1 ) goto copyA;
        if ( expDiff ) {
            --expB;
            softfloat_add128M( x, x, x );
            q = 0;
        } else {
            q = (softfloat_compare128M( x, remPtr ) <= 0);
            if ( q ) softfloat_sub128M( remPtr, x, remPtr );
        }
    } else {
        recip32 =
            softfloat_approxRecip32_1(
                ((uint64_t) x[indexWord( 4, 3 )]<<32 | x[indexWord( 4, 2 )])
                    >>30
            );
        expDiff -= 30;
        for (;;) {
            q64 = (uint64_t) remPtr[indexWordHi( 4 )] * recip32;
            if ( expDiff < 0 ) break;
            q = (q64 + 0x80000000)>>32;
            softfloat_remStep128MBy32( remPtr, 29, x, q, remPtr );
            if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) {
                softfloat_add128M( remPtr, x, remPtr );
            }
            expDiff -= 29;
        }
        /*--------------------------------------------------------------------
        | (`expDiff' cannot be less than -29 here.)
        *--------------------------------------------------------------------*/
        q = (uint32_t) (q64>>32)>>(~expDiff & 31);
        softfloat_remStep128MBy32( remPtr, expDiff + 30, x, q, remPtr );
        if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) {
            altRemPtr = &rem2[indexMultiwordLo( 5, 4 )];
            softfloat_add128M( remPtr, x, altRemPtr );
            goto selectRem;
        }
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    altRemPtr = &rem2[indexMultiwordLo( 5, 4 )];
    do {
        ++q;
        newRemPtr = altRemPtr;
        softfloat_sub128M( remPtr, x, newRemPtr );
        altRemPtr = remPtr;
        remPtr = newRemPtr;
    } while ( ! (remPtr[indexWordHi( 4 )] & 0x80000000) );
 selectRem:
    softfloat_add128M( remPtr, altRemPtr, x );
    wordMeanRem = x[indexWordHi( 4 )];
    if (
        (wordMeanRem & 0x80000000)
            || (! wordMeanRem && (q & 1) && ! x[indexWord( 4, 0 )]
                    && ! (x[indexWord( 4, 2 )] | x[indexWord( 4, 1 )]))
    ) {
        remPtr = altRemPtr;
    }
    if ( remPtr[indexWordHi( 4 )] & 0x80000000 ) {
        signRem = ! signRem;
        softfloat_negX128M( remPtr );
    }
    remPtr -= indexMultiwordLo( 5, 4 );
    remPtr[indexWordHi( 5 )] = 0;
    softfloat_normRoundPackMToF128M( signRem, expB + 18, remPtr, zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidF128M( zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 copyA:
    zWPtr[indexWordHi( 4 )] = uiA96;
    zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
    zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
    zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];

}

#endif

/**** ended inlining ../../source/f128M_rem.c ****/
/**** start inlining ../../source/f128M_sqrt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014, 2017 The Regents of the University of
California.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

void f128M_sqrt( const float128_t *aPtr, float128_t *zPtr )
{

    *zPtr = f128_sqrt( *aPtr );

}

#else

void f128M_sqrt( const float128_t *aPtr, float128_t *zPtr )
{
    const uint32_t *aWPtr;
    uint32_t *zWPtr;
    uint32_t uiA96;
    bool signA;
    int32_t rawExpA;
    uint32_t rem[6];
    int32_t expA, expZ;
    uint64_t rem64;
    uint32_t sig32A, recipSqrt32, sig32Z, qs[3], q;
    uint64_t sig64Z;
    uint32_t term[5];
    uint64_t x64;
    uint32_t y[5], rem32;

    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    aWPtr = (const uint32_t *) aPtr;
    zWPtr = (uint32_t *) zPtr;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    uiA96 = aWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    rawExpA  = expF128UI96( uiA96 );
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( rawExpA == 0x7FFF ) {
        if (
            fracF128UI96( uiA96 )
                || (aWPtr[indexWord( 4, 2 )] | aWPtr[indexWord( 4, 1 )]
                        | aWPtr[indexWord( 4, 0 )])
        ) {
            softfloat_propagateNaNF128M( aWPtr, 0, zWPtr );
            return;
        }
        if ( ! signA ) goto copyA;
        goto invalid;
    }
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    expA = softfloat_shiftNormSigF128M( aWPtr, 13 - (rawExpA & 1), rem );
    if ( expA == -128 ) goto copyA;
    if ( signA ) goto invalid;
    /*------------------------------------------------------------------------
    | (`sig32Z' is guaranteed to be a lower bound on the square root of
    | `sig32A', which makes `sig32Z' also a lower bound on the square root of
    | `sigA'.)
    *------------------------------------------------------------------------*/
    expZ = ((expA - 0x3FFF)>>1) + 0x3FFE;
    expA &= 1;
    rem64 = (uint64_t) rem[indexWord( 4, 3 )]<<32 | rem[indexWord( 4, 2 )];
    if ( expA ) {
        if ( ! rawExpA ) {
            softfloat_shortShiftRight128M( rem, 1, rem );
            rem64 >>= 1;
        }
        sig32A = rem64>>29;
    } else {
        sig32A = rem64>>30;
    }
    recipSqrt32 = softfloat_approxRecipSqrt32_1( expA, sig32A );
    sig32Z = ((uint64_t) sig32A * recipSqrt32)>>32;
    if ( expA ) sig32Z >>= 1;
    qs[2] = sig32Z;
    rem64 -= (uint64_t) sig32Z * sig32Z;
    rem[indexWord( 4, 3 )] = rem64>>32;
    rem[indexWord( 4, 2 )] = rem64;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32;
    sig64Z = ((uint64_t) sig32Z<<32) + ((uint64_t) q<<3);
    term[indexWord( 4, 3 )] = 0;
    term[indexWord( 4, 0 )] = 0;
    /*------------------------------------------------------------------------
    | (Repeating this loop is a rare occurrence.)
    *------------------------------------------------------------------------*/
    for (;;) {
        x64 = ((uint64_t) sig32Z<<32) + sig64Z;
        term[indexWord( 4, 2 )] = x64>>32;
        term[indexWord( 4, 1 )] = x64;
        softfloat_remStep128MBy32( rem, 29, term, q, y );
        rem32 = y[indexWord( 4, 3 )];
        if ( ! (rem32 & 0x80000000) ) break;
        --q;
        sig64Z -= 1<<3;
    }
    qs[1] = q;
    rem64 = (uint64_t) rem32<<32 | y[indexWord( 4, 2 )];
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = ((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32;
    if ( rem64>>34 ) q += recipSqrt32;
    sig64Z <<= 1;
    /*------------------------------------------------------------------------
    | (Repeating this loop is a rare occurrence.)
    *------------------------------------------------------------------------*/
    for (;;) {
        x64 = sig64Z + (q>>26);
        term[indexWord( 4, 2 )] = x64>>32;
        term[indexWord( 4, 1 )] = x64;
        term[indexWord( 4, 0 )] = q<<6;
        softfloat_remStep128MBy32(
            y, 29, term, q, &rem[indexMultiwordHi( 6, 4 )] );
        rem32 = rem[indexWordHi( 6 )];
        if ( ! (rem32 & 0x80000000) ) break;
        --q;
    }
    qs[0] = q;
    rem64 = (uint64_t) rem32<<32 | rem[indexWord( 6, 4 )];
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    q = (((uint32_t) (rem64>>2) * (uint64_t) recipSqrt32)>>32) + 2;
    if ( rem64>>34 ) q += recipSqrt32;
    x64 = (uint64_t) q<<27;
    y[indexWord( 5, 0 )] = x64;
    x64 = ((uint64_t) qs[0]<<24) + (x64>>32);
    y[indexWord( 5, 1 )] = x64;
    x64 = ((uint64_t) qs[1]<<21) + (x64>>32);
    y[indexWord( 5, 2 )] = x64;
    x64 = ((uint64_t) qs[2]<<18) + (x64>>32);
    y[indexWord( 5, 3 )] = x64;
    y[indexWord( 5, 4 )] = x64>>32;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
    if ( (q & 0xF) <= 2 ) {
        q &= ~3;
        y[indexWordLo( 5 )] = q<<27;
        term[indexWord( 5, 4 )] = 0;
        term[indexWord( 5, 3 )] = 0;
        term[indexWord( 5, 2 )] = 0;
        term[indexWord( 5, 1 )] = q>>6;
        term[indexWord( 5, 0 )] = q<<26;
        softfloat_sub160M( y, term, term );
        rem[indexWord( 6, 1 )] = 0;
        rem[indexWord( 6, 0 )] = 0;
        softfloat_remStep160MBy32(
            &rem[indexMultiwordLo( 6, 5 )],
            14,
            term,
            q,
            &rem[indexMultiwordLo( 6, 5 )]
        );
        rem32 = rem[indexWord( 6, 4 )];
        if ( rem32 & 0x80000000 ) {
            softfloat_sub1X160M( y );
        } else {
            if (
                rem32 || rem[indexWord( 6, 0 )] || rem[indexWord( 6, 1 )]
                    || (rem[indexWord( 6, 3 )] | rem[indexWord( 6, 2 )])
            ) {
                y[indexWordLo( 5 )] |= 1;
            }
        }
    }
    softfloat_roundPackMToF128M( 0, expZ, y, zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 invalid:
    softfloat_invalidF128M( zWPtr );
    return;
    /*------------------------------------------------------------------------
    *------------------------------------------------------------------------*/
 copyA:
    zWPtr[indexWordHi( 4 )] = uiA96;
    zWPtr[indexWord( 4, 2 )] = aWPtr[indexWord( 4, 2 )];
    zWPtr[indexWord( 4, 1 )] = aWPtr[indexWord( 4, 1 )];
    zWPtr[indexWord( 4, 0 )] = aWPtr[indexWord( 4, 0 )];

}

#endif

/**** ended inlining ../../source/f128M_sqrt.c ****/
/**** start inlining ../../source/f128M_eq.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_eq( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_eq( *aPtr, *bPtr );

}

#else

bool f128M_eq( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t wordA, wordB, uiA96, uiB96;
    bool possibleOppositeZeros;
    uint32_t mashWord;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    wordA = aWPtr[indexWord( 4, 2 )];
    wordB = bWPtr[indexWord( 4, 2 )];
    if ( wordA != wordB ) goto false_checkSigNaNs;
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    possibleOppositeZeros = false;
    if ( uiA96 != uiB96 ) {
        possibleOppositeZeros = (((uiA96 | uiB96) & 0x7FFFFFFF) == 0);
        if ( ! possibleOppositeZeros ) goto false_checkSigNaNs;
    }
    mashWord = wordA | wordB;
    wordA = aWPtr[indexWord( 4, 1 )];
    wordB = bWPtr[indexWord( 4, 1 )];
    if ( wordA != wordB ) goto false_checkSigNaNs;
    mashWord |= wordA | wordB;
    wordA = aWPtr[indexWord( 4, 0 )];
    wordB = bWPtr[indexWord( 4, 0 )];
    if ( wordA != wordB ) goto false_checkSigNaNs;
    if ( possibleOppositeZeros && ((mashWord | wordA | wordB) != 0) ) {
        goto false_checkSigNaNs;
    }
    if ( ! softfloat_isNaNF128M( aWPtr ) && ! softfloat_isNaNF128M( bWPtr ) ) {
        return true;
    }
 false_checkSigNaNs:
    if (
           f128M_isSignalingNaN( (const float128_t *) aWPtr )
        || f128M_isSignalingNaN( (const float128_t *) bWPtr )
    ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
    }
    return false;

}

#endif

/**** ended inlining ../../source/f128M_eq.c ****/
/**** start inlining ../../source/f128M_le.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_le( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_le( *aPtr, *bPtr );

}

#else

bool f128M_le( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t uiA96, uiB96;
    bool signA, signB;
    uint32_t wordA, wordB;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    signB = signF128UI96( uiB96 );
    if ( signA != signB ) {
        if ( signA ) return true;
        if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return false;
        wordA = aWPtr[indexWord( 4, 2 )];
        wordB = bWPtr[indexWord( 4, 2 )];
        if ( wordA | wordB ) return false;
        wordA = aWPtr[indexWord( 4, 1 )];
        wordB = bWPtr[indexWord( 4, 1 )];
        if ( wordA | wordB ) return false;
        wordA = aWPtr[indexWord( 4, 0 )];
        wordB = bWPtr[indexWord( 4, 0 )];
        return ((wordA | wordB) == 0);
    }
    if ( signA ) {
        aWPtr = (const uint32_t *) bPtr;
        bWPtr = (const uint32_t *) aPtr;
    }
    return (softfloat_compare128M( aWPtr, bWPtr ) <= 0);

}

#endif

/**** ended inlining ../../source/f128M_le.c ****/
/**** start inlining ../../source/f128M_lt.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_lt( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_lt( *aPtr, *bPtr );

}

#else

bool f128M_lt( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t uiA96, uiB96;
    bool signA, signB;
    uint32_t wordA, wordB;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    signB = signF128UI96( uiB96 );
    if ( signA != signB ) {
        if ( signB ) return false;
        if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return true;
        wordA = aWPtr[indexWord( 4, 2 )];
        wordB = bWPtr[indexWord( 4, 2 )];
        if ( wordA | wordB ) return true;
        wordA = aWPtr[indexWord( 4, 1 )];
        wordB = bWPtr[indexWord( 4, 1 )];
        if ( wordA | wordB ) return true;
        wordA = aWPtr[indexWord( 4, 0 )];
        wordB = bWPtr[indexWord( 4, 0 )];
        return ((wordA | wordB) != 0);
    }
    if ( signA ) {
        aWPtr = (const uint32_t *) bPtr;
        bWPtr = (const uint32_t *) aPtr;
    }
    return (softfloat_compare128M( aWPtr, bWPtr ) < 0);

}

#endif

/**** ended inlining ../../source/f128M_lt.c ****/
/**** start inlining ../../source/f128M_eq_signaling.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_eq_signaling( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_eq_signaling( *aPtr, *bPtr );

}

#else

bool f128M_eq_signaling( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t wordA, wordB, uiA96, uiB96;
    bool possibleOppositeZeros;
    uint32_t mashWord;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) {
        softfloat_raiseFlags( softfloat_flag_invalid );
        return false;
    }
    wordA = aWPtr[indexWord( 4, 2 )];
    wordB = bWPtr[indexWord( 4, 2 )];
    if ( wordA != wordB ) return false;
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    possibleOppositeZeros = false;
    if ( uiA96 != uiB96 ) {
        possibleOppositeZeros = (((uiA96 | uiB96) & 0x7FFFFFFF) == 0);
        if ( ! possibleOppositeZeros ) return false;
    }
    mashWord = wordA | wordB;
    wordA = aWPtr[indexWord( 4, 1 )];
    wordB = bWPtr[indexWord( 4, 1 )];
    if ( wordA != wordB ) return false;
    mashWord |= wordA | wordB;
    wordA = aWPtr[indexWord( 4, 0 )];
    wordB = bWPtr[indexWord( 4, 0 )];
    return
        (wordA == wordB)
            && (! possibleOppositeZeros || ((mashWord | wordA | wordB) == 0));

}

#endif

/**** ended inlining ../../source/f128M_eq_signaling.c ****/
/**** start inlining ../../source/f128M_le_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_le_quiet( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_le_quiet( *aPtr, *bPtr );

}

#else

bool f128M_le_quiet( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t uiA96, uiB96;
    bool signA, signB;
    uint32_t wordA, wordB;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) {
        if ( f128M_isSignalingNaN( aPtr ) || f128M_isSignalingNaN( bPtr ) ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    signB = signF128UI96( uiB96 );
    if ( signA != signB ) {
        if ( signA ) return true;
        if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return false;
        wordA = aWPtr[indexWord( 4, 2 )];
        wordB = bWPtr[indexWord( 4, 2 )];
        if ( wordA | wordB ) return false;
        wordA = aWPtr[indexWord( 4, 1 )];
        wordB = bWPtr[indexWord( 4, 1 )];
        if ( wordA | wordB ) return false;
        wordA = aWPtr[indexWord( 4, 0 )];
        wordB = bWPtr[indexWord( 4, 0 )];
        return ((wordA | wordB) == 0);
    }
    if ( signA ) {
        aWPtr = (const uint32_t *) bPtr;
        bWPtr = (const uint32_t *) aPtr;
    }
    return (softfloat_compare128M( aWPtr, bWPtr ) <= 0);

}

#endif

/**** ended inlining ../../source/f128M_le_quiet.c ****/
/**** start inlining ../../source/f128M_lt_quiet.c ****/

/*============================================================================

This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic
Package, Release 3e, by John R. Hauser.

Copyright 2011, 2012, 2013, 2014 The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 1. Redistributions of source code must retain the above copyright notice,
    this list of conditions, and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions, and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

 3. Neither the name of the University nor the names of its contributors may
    be used to endorse or promote products derived from this software without
    specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE
DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=============================================================================*/

#include <stdbool.h>
#include <stdint.h>
/**** skipping file: platform.h ****/
/**** skipping file: internals.h ****/
/**** skipping file: specialize.h ****/
/**** skipping file: softfloat.h ****/

#ifdef SOFTFLOAT_FAST_INT64

bool f128M_lt_quiet( const float128_t *aPtr, const float128_t *bPtr )
{

    return f128_lt_quiet( *aPtr, *bPtr );

}

#else

bool f128M_lt_quiet( const float128_t *aPtr, const float128_t *bPtr )
{
    const uint32_t *aWPtr, *bWPtr;
    uint32_t uiA96, uiB96;
    bool signA, signB;
    uint32_t wordA, wordB;

    aWPtr = (const uint32_t *) aPtr;
    bWPtr = (const uint32_t *) bPtr;
    if ( softfloat_isNaNF128M( aWPtr ) || softfloat_isNaNF128M( bWPtr ) ) {
        if ( f128M_isSignalingNaN( aPtr ) || f128M_isSignalingNaN( bPtr ) ) {
            softfloat_raiseFlags( softfloat_flag_invalid );
        }
        return false;
    }
    uiA96 = aWPtr[indexWordHi( 4 )];
    uiB96 = bWPtr[indexWordHi( 4 )];
    signA = signF128UI96( uiA96 );
    signB = signF128UI96( uiB96 );
    if ( signA != signB ) {
        if ( signB ) return false;
        if ( (uiA96 | uiB96) & 0x7FFFFFFF ) return true;
        wordA = aWPtr[indexWord( 4, 2 )];
        wordB = bWPtr[indexWord( 4, 2 )];
        if ( wordA | wordB ) return true;
        wordA = aWPtr[indexWord( 4, 1 )];
        wordB = bWPtr[indexWord( 4, 1 )];
        if ( wordA | wordB ) return true;
        wordA = aWPtr[indexWord( 4, 0 )];
        wordB = bWPtr[indexWord( 4, 0 )];
        return ((wordA | wordB) != 0);
    }
    if ( signA ) {
        aWPtr = (const uint32_t *) bPtr;
        bWPtr = (const uint32_t *) aPtr;
    }
    return (softfloat_compare128M( aWPtr, bWPtr ) < 0);

}

#endif

/**** ended inlining ../../source/f128M_lt_quiet.c ****/
                                                                                          source/v64/lib/zstd/zstddeclib.c                                                                    0000644 0000000 0000000 00002151557 00000000000 013731  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #define malloc v86_malloc
#define free v86_free
#include <stddef.h>
void *calloc(size_t nmemb, size_t size);
void *memset(void *s, int c, size_t n);
void *memcpy(void *dest, const void *src, size_t n);
void *memmove(void *dest, const void *src, size_t n);
void *malloc(size_t size);
void free(void *ptr);
/**
 * \file zstddeclib.c
 * Single-file Zstandard decompressor.
 *
 * Generate using:
 * \code
 *	combine.sh -r ../../lib -o zstddeclib.c zstddeclib-in.c
 * \endcode
 */
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */
/*
 * Settings to bake for the standalone decompressor.
 *
 * Note: It's important that none of these affects 'zstd.h' (only the
 * implementation files we're amalgamating).
 *
 * Note: MEM_MODULE stops xxhash redefining BYTE, U16, etc., which are also
 * defined in mem.h (breaking C99 compatibility).
 *
 * Note: the undefs for xxHash allow Zstd's implementation to coinside with with
 * standalone xxHash usage (with global defines).
 */
#define DEBUGLEVEL 0
#define MEM_MODULE
#undef  XXH_NAMESPACE
#define XXH_NAMESPACE ZSTD_
#undef  XXH_PRIVATE_API
#define XXH_PRIVATE_API
#undef  XXH_INLINE_ALL
#define XXH_INLINE_ALL
#define ZSTD_LEGACY_SUPPORT 0
#define ZSTD_LIB_COMPRESSION 0
#define ZSTD_LIB_DEPRECATED 0
#define ZSTD_NOBENCH
#define ZSTD_STRIP_ERROR_STRINGS

/**** start inlining common/debug.c ****/
/* ******************************************************************
 * debug
 * Part of FSE library
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */


/*
 * This module only hosts one global variable
 * which can be used to dynamically influence the verbosity of traces,
 * such as DEBUGLOG and RAWLOG
 */

/**** start inlining debug.h ****/
/* ******************************************************************
 * debug
 * Part of FSE library
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */


/*
 * The purpose of this header is to enable debug functions.
 * They regroup assert(), DEBUGLOG() and RAWLOG() for run-time,
 * and DEBUG_STATIC_ASSERT() for compile-time.
 *
 * By default, DEBUGLEVEL==0, which means run-time debug is disabled.
 *
 * Level 1 enables assert() only.
 * Starting level 2, traces can be generated and pushed to stderr.
 * The higher the level, the more verbose the traces.
 *
 * It's possible to dynamically adjust level using variable g_debug_level,
 * which is only declared if DEBUGLEVEL>=2,
 * and is a global variable, not multi-thread protected (use with care)
 */

#ifndef DEBUG_H_12987983217
#define DEBUG_H_12987983217

#if defined (__cplusplus)
extern "C" {
#endif


/* static assert is triggered at compile time, leaving no runtime artefact.
 * static assert only works with compile-time constants.
 * Also, this variant can only be used inside a function. */
#define DEBUG_STATIC_ASSERT(c) (void)sizeof(char[(c) ? 1 : -1])


/* DEBUGLEVEL is expected to be defined externally,
 * typically through compiler command line.
 * Value must be a number. */
#ifndef DEBUGLEVEL
#  define DEBUGLEVEL 0
#endif


/* DEBUGFILE can be defined externally,
 * typically through compiler command line.
 * note : currently useless.
 * Value must be stderr or stdout */
#ifndef DEBUGFILE
#  define DEBUGFILE stderr
#endif


/* recommended values for DEBUGLEVEL :
 * 0 : release mode, no debug, all run-time checks disabled
 * 1 : enables assert() only, no display
 * 2 : reserved, for currently active debug path
 * 3 : events once per object lifetime (CCtx, CDict, etc.)
 * 4 : events once per frame
 * 5 : events once per block
 * 6 : events once per sequence (verbose)
 * 7+: events at every position (*very* verbose)
 *
 * It's generally inconvenient to output traces > 5.
 * In which case, it's possible to selectively trigger high verbosity levels
 * by modifying g_debug_level.
 */

#if (DEBUGLEVEL>=1)
#  include <assert.h>
#else
#  ifndef assert   /* assert may be already defined, due to prior #include <assert.h> */
#    define assert(condition) ((void)0)   /* disable assert (default) */
#  endif
#endif

#if (DEBUGLEVEL>=2)
#  include <stdio.h>
extern int g_debuglevel; /* the variable is only declared,
                            it actually lives in debug.c,
                            and is shared by the whole process.
                            It's not thread-safe.
                            It's useful when enabling very verbose levels
                            on selective conditions (such as position in src) */

#  define RAWLOG(l, ...) {                                      \
                if (l<=g_debuglevel) {                          \
                    fprintf(stderr, __VA_ARGS__);               \
            }   }
#  define DEBUGLOG(l, ...) {                                    \
                if (l<=g_debuglevel) {                          \
                    fprintf(stderr, __FILE__ ": " __VA_ARGS__); \
                    fprintf(stderr, " \n");                     \
            }   }
#else
#  define RAWLOG(l, ...)      {}    /* disabled */
#  define DEBUGLOG(l, ...)    {}    /* disabled */
#endif


#if defined (__cplusplus)
}
#endif

#endif /* DEBUG_H_12987983217 */
/**** ended inlining debug.h ****/

int g_debuglevel = DEBUGLEVEL;
/**** ended inlining common/debug.c ****/
/**** start inlining common/entropy_common.c ****/
/* ******************************************************************
 * Common functions of New Generation Entropy library
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 *
 *  You can contact the author at :
 *  - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */

/* *************************************
*  Dependencies
***************************************/
/**** start inlining mem.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef MEM_H_MODULE
#define MEM_H_MODULE

#if defined (__cplusplus)
extern "C" {
#endif

/*-****************************************
*  Dependencies
******************************************/
#include <stddef.h>     /* size_t, ptrdiff_t */


/*-****************************************
*  Compiler specifics
******************************************/
#if defined(_MSC_VER)   /* Visual Studio */
#   include <intrin.h>  /* _byteswap_* */
#endif
#if defined(__GNUC__)
#  define MEM_STATIC static __inline __attribute__((unused))
#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
#  define MEM_STATIC static inline
#elif defined(_MSC_VER)
#  define MEM_STATIC static __inline
#else
#  define MEM_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
#endif

#ifndef __has_builtin
#  define __has_builtin(x) 0  /* compat. with non-clang compilers */
#endif

/* code only tested on 32 and 64 bits systems */
#define MEM_STATIC_ASSERT(c)   { enum { MEM_static_assert = 1/(int)(!!(c)) }; }
MEM_STATIC void MEM_check(void) { MEM_STATIC_ASSERT((sizeof(size_t)==4) || (sizeof(size_t)==8)); }

/* detects whether we are being compiled under msan */
#if defined (__has_feature)
#  if __has_feature(memory_sanitizer)
#    define MEMORY_SANITIZER 1
#  endif
#endif

#if defined (MEMORY_SANITIZER)
/* Not all platforms that support msan provide sanitizers/msan_interface.h.
 * We therefore declare the functions we need ourselves, rather than trying to
 * include the header file... */

#include <stdint.h> /* intptr_t */

/* Make memory region fully initialized (without changing its contents). */
void __msan_unpoison(const volatile void *a, size_t size);

/* Make memory region fully uninitialized (without changing its contents).
   This is a legacy interface that does not update origin information. Use
   __msan_allocated_memory() instead. */
void __msan_poison(const volatile void *a, size_t size);

/* Returns the offset of the first (at least partially) poisoned byte in the
   memory range, or -1 if the whole range is good. */
intptr_t __msan_test_shadow(const volatile void *x, size_t size);
#endif

/* detects whether we are being compiled under asan */
#if defined (__has_feature)
#  if __has_feature(address_sanitizer)
#    define ADDRESS_SANITIZER 1
#  endif
#elif defined(__SANITIZE_ADDRESS__)
#  define ADDRESS_SANITIZER 1
#endif

#if defined (ADDRESS_SANITIZER)
/* Not all platforms that support asan provide sanitizers/asan_interface.h.
 * We therefore declare the functions we need ourselves, rather than trying to
 * include the header file... */

/**
 * Marks a memory region (<c>[addr, addr+size)</c>) as unaddressable.
 *
 * This memory must be previously allocated by your program. Instrumented
 * code is forbidden from accessing addresses in this region until it is
 * unpoisoned. This function is not guaranteed to poison the entire region -
 * it could poison only a subregion of <c>[addr, addr+size)</c> due to ASan
 * alignment restrictions.
 *
 * \note This function is not thread-safe because no two threads can poison or
 * unpoison memory in the same memory region simultaneously.
 *
 * \param addr Start of memory region.
 * \param size Size of memory region. */
void __asan_poison_memory_region(void const volatile *addr, size_t size);

/**
 * Marks a memory region (<c>[addr, addr+size)</c>) as addressable.
 *
 * This memory must be previously allocated by your program. Accessing
 * addresses in this region is allowed until this region is poisoned again.
 * This function could unpoison a super-region of <c>[addr, addr+size)</c> due
 * to ASan alignment restrictions.
 *
 * \note This function is not thread-safe because no two threads can
 * poison or unpoison memory in the same memory region simultaneously.
 *
 * \param addr Start of memory region.
 * \param size Size of memory region. */
void __asan_unpoison_memory_region(void const volatile *addr, size_t size);
#endif


/*-**************************************************************
*  Basic Types
*****************************************************************/
#if  !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
# include <stdint.h>
  typedef   uint8_t BYTE;
  typedef  uint16_t U16;
  typedef   int16_t S16;
  typedef  uint32_t U32;
  typedef   int32_t S32;
  typedef  uint64_t U64;
  typedef   int64_t S64;
#else
# include <limits.h>
#if CHAR_BIT != 8
#  error "this implementation requires char to be exactly 8-bit type"
#endif
  typedef unsigned char      BYTE;
#if USHRT_MAX != 65535
#  error "this implementation requires short to be exactly 16-bit type"
#endif
  typedef unsigned short      U16;
  typedef   signed short      S16;
#if UINT_MAX != 4294967295
#  error "this implementation requires int to be exactly 32-bit type"
#endif
  typedef unsigned int        U32;
  typedef   signed int        S32;
/* note : there are no limits defined for long long type in C90.
 * limits exist in C99, however, in such case, <stdint.h> is preferred */
  typedef unsigned long long  U64;
  typedef   signed long long  S64;
#endif


/*-**************************************************************
*  Memory I/O
*****************************************************************/
/* MEM_FORCE_MEMORY_ACCESS :
 * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
 * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
 * The below switch allow to select different access method for improved performance.
 * Method 0 (default) : use `memcpy()`. Safe and portable.
 * Method 1 : `__packed` statement. It depends on compiler extension (i.e., not portable).
 *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
 * Method 2 : direct access. This method is portable but violate C standard.
 *            It can generate buggy code on targets depending on alignment.
 *            In some circumstances, it's the only known way to get the most performance (i.e. GCC + ARMv6)
 * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
 * Prefer these methods in priority order (0 > 1 > 2)
 */
#ifndef MEM_FORCE_MEMORY_ACCESS   /* can be defined externally, on command line for example */
#  if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
#    define MEM_FORCE_MEMORY_ACCESS 2
#  elif defined(__INTEL_COMPILER) || defined(__GNUC__) || defined(__ICCARM__)
#    define MEM_FORCE_MEMORY_ACCESS 1
#  endif
#endif

MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; }
MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; }

MEM_STATIC unsigned MEM_isLittleEndian(void)
{
    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */
    return one.c[0];
}

#if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2)

/* violates C standard, by lying on structure alignment.
Only use if no other choice to achieve best performance on target platform */
MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; }
MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; }
MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; }
MEM_STATIC size_t MEM_readST(const void* memPtr) { return *(const size_t*) memPtr; }

MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; }

#elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1)

/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
/* currently only defined for gcc and icc */
#if defined(_MSC_VER) || (defined(__INTEL_COMPILER) && defined(WIN32))
    __pragma( pack(push, 1) )
    typedef struct { U16 v; } unalign16;
    typedef struct { U32 v; } unalign32;
    typedef struct { U64 v; } unalign64;
    typedef struct { size_t v; } unalignArch;
    __pragma( pack(pop) )
#else
    typedef struct { U16 v; } __attribute__((packed)) unalign16;
    typedef struct { U32 v; } __attribute__((packed)) unalign32;
    typedef struct { U64 v; } __attribute__((packed)) unalign64;
    typedef struct { size_t v; } __attribute__((packed)) unalignArch;
#endif

MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign16*)ptr)->v; }
MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign32*)ptr)->v; }
MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign64*)ptr)->v; }
MEM_STATIC size_t MEM_readST(const void* ptr) { return ((const unalignArch*)ptr)->v; }

MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign16*)memPtr)->v = value; }
MEM_STATIC void MEM_write32(void* memPtr, U32 value) { ((unalign32*)memPtr)->v = value; }
MEM_STATIC void MEM_write64(void* memPtr, U64 value) { ((unalign64*)memPtr)->v = value; }

#else

/* default method, safe and standard.
   can sometimes prove slower */

MEM_STATIC U16 MEM_read16(const void* memPtr)
{
    U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
}

MEM_STATIC U32 MEM_read32(const void* memPtr)
{
    U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
}

MEM_STATIC U64 MEM_read64(const void* memPtr)
{
    U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
}

MEM_STATIC size_t MEM_readST(const void* memPtr)
{
    size_t val; memcpy(&val, memPtr, sizeof(val)); return val;
}

MEM_STATIC void MEM_write16(void* memPtr, U16 value)
{
    memcpy(memPtr, &value, sizeof(value));
}

MEM_STATIC void MEM_write32(void* memPtr, U32 value)
{
    memcpy(memPtr, &value, sizeof(value));
}

MEM_STATIC void MEM_write64(void* memPtr, U64 value)
{
    memcpy(memPtr, &value, sizeof(value));
}

#endif /* MEM_FORCE_MEMORY_ACCESS */

MEM_STATIC U32 MEM_swap32(U32 in)
{
#if defined(_MSC_VER)     /* Visual Studio */
    return _byteswap_ulong(in);
#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \
  || (defined(__clang__) && __has_builtin(__builtin_bswap32))
    return __builtin_bswap32(in);
#else
    return  ((in << 24) & 0xff000000 ) |
            ((in <<  8) & 0x00ff0000 ) |
            ((in >>  8) & 0x0000ff00 ) |
            ((in >> 24) & 0x000000ff );
#endif
}

MEM_STATIC U64 MEM_swap64(U64 in)
{
#if defined(_MSC_VER)     /* Visual Studio */
    return _byteswap_uint64(in);
#elif (defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) \
  || (defined(__clang__) && __has_builtin(__builtin_bswap64))
    return __builtin_bswap64(in);
#else
    return  ((in << 56) & 0xff00000000000000ULL) |
            ((in << 40) & 0x00ff000000000000ULL) |
            ((in << 24) & 0x0000ff0000000000ULL) |
            ((in << 8)  & 0x000000ff00000000ULL) |
            ((in >> 8)  & 0x00000000ff000000ULL) |
            ((in >> 24) & 0x0000000000ff0000ULL) |
            ((in >> 40) & 0x000000000000ff00ULL) |
            ((in >> 56) & 0x00000000000000ffULL);
#endif
}

MEM_STATIC size_t MEM_swapST(size_t in)
{
    if (MEM_32bits())
        return (size_t)MEM_swap32((U32)in);
    else
        return (size_t)MEM_swap64((U64)in);
}

/*=== Little endian r/w ===*/

MEM_STATIC U16 MEM_readLE16(const void* memPtr)
{
    if (MEM_isLittleEndian())
        return MEM_read16(memPtr);
    else {
        const BYTE* p = (const BYTE*)memPtr;
        return (U16)(p[0] + (p[1]<<8));
    }
}

MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
{
    if (MEM_isLittleEndian()) {
        MEM_write16(memPtr, val);
    } else {
        BYTE* p = (BYTE*)memPtr;
        p[0] = (BYTE)val;
        p[1] = (BYTE)(val>>8);
    }
}

MEM_STATIC U32 MEM_readLE24(const void* memPtr)
{
    return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
}

MEM_STATIC void MEM_writeLE24(void* memPtr, U32 val)
{
    MEM_writeLE16(memPtr, (U16)val);
    ((BYTE*)memPtr)[2] = (BYTE)(val>>16);
}

MEM_STATIC U32 MEM_readLE32(const void* memPtr)
{
    if (MEM_isLittleEndian())
        return MEM_read32(memPtr);
    else
        return MEM_swap32(MEM_read32(memPtr));
}

MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32)
{
    if (MEM_isLittleEndian())
        MEM_write32(memPtr, val32);
    else
        MEM_write32(memPtr, MEM_swap32(val32));
}

MEM_STATIC U64 MEM_readLE64(const void* memPtr)
{
    if (MEM_isLittleEndian())
        return MEM_read64(memPtr);
    else
        return MEM_swap64(MEM_read64(memPtr));
}

MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64)
{
    if (MEM_isLittleEndian())
        MEM_write64(memPtr, val64);
    else
        MEM_write64(memPtr, MEM_swap64(val64));
}

MEM_STATIC size_t MEM_readLEST(const void* memPtr)
{
    if (MEM_32bits())
        return (size_t)MEM_readLE32(memPtr);
    else
        return (size_t)MEM_readLE64(memPtr);
}

MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val)
{
    if (MEM_32bits())
        MEM_writeLE32(memPtr, (U32)val);
    else
        MEM_writeLE64(memPtr, (U64)val);
}

/*=== Big endian r/w ===*/

MEM_STATIC U32 MEM_readBE32(const void* memPtr)
{
    if (MEM_isLittleEndian())
        return MEM_swap32(MEM_read32(memPtr));
    else
        return MEM_read32(memPtr);
}

MEM_STATIC void MEM_writeBE32(void* memPtr, U32 val32)
{
    if (MEM_isLittleEndian())
        MEM_write32(memPtr, MEM_swap32(val32));
    else
        MEM_write32(memPtr, val32);
}

MEM_STATIC U64 MEM_readBE64(const void* memPtr)
{
    if (MEM_isLittleEndian())
        return MEM_swap64(MEM_read64(memPtr));
    else
        return MEM_read64(memPtr);
}

MEM_STATIC void MEM_writeBE64(void* memPtr, U64 val64)
{
    if (MEM_isLittleEndian())
        MEM_write64(memPtr, MEM_swap64(val64));
    else
        MEM_write64(memPtr, val64);
}

MEM_STATIC size_t MEM_readBEST(const void* memPtr)
{
    if (MEM_32bits())
        return (size_t)MEM_readBE32(memPtr);
    else
        return (size_t)MEM_readBE64(memPtr);
}

MEM_STATIC void MEM_writeBEST(void* memPtr, size_t val)
{
    if (MEM_32bits())
        MEM_writeBE32(memPtr, (U32)val);
    else
        MEM_writeBE64(memPtr, (U64)val);
}


#if defined (__cplusplus)
}
#endif

#endif /* MEM_H_MODULE */
/**** ended inlining mem.h ****/
/**** start inlining error_private.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

/* Note : this module is expected to remain private, do not expose it */

#ifndef ERROR_H_MODULE
#define ERROR_H_MODULE

#if defined (__cplusplus)
extern "C" {
#endif


/* ****************************************
*  Dependencies
******************************************/
#include <stddef.h>        /* size_t */
/**** start inlining zstd_errors.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_ERRORS_H_398273423
#define ZSTD_ERRORS_H_398273423

#if defined (__cplusplus)
extern "C" {
#endif

/*===== dependency =====*/
#include <stddef.h>   /* size_t */


/* =====   ZSTDERRORLIB_API : control library symbols visibility   ===== */
#ifndef ZSTDERRORLIB_VISIBILITY
#  if defined(__GNUC__) && (__GNUC__ >= 4)
#    define ZSTDERRORLIB_VISIBILITY __attribute__ ((visibility ("default")))
#  else
#    define ZSTDERRORLIB_VISIBILITY
#  endif
#endif
#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
#  define ZSTDERRORLIB_API __declspec(dllexport) ZSTDERRORLIB_VISIBILITY
#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
#  define ZSTDERRORLIB_API __declspec(dllimport) ZSTDERRORLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
#else
#  define ZSTDERRORLIB_API ZSTDERRORLIB_VISIBILITY
#endif

/*-*********************************************
 *  Error codes list
 *-*********************************************
 *  Error codes _values_ are pinned down since v1.3.1 only.
 *  Therefore, don't rely on values if you may link to any version < v1.3.1.
 *
 *  Only values < 100 are considered stable.
 *
 *  note 1 : this API shall be used with static linking only.
 *           dynamic linking is not yet officially supported.
 *  note 2 : Prefer relying on the enum than on its value whenever possible
 *           This is the only supported way to use the error list < v1.3.1
 *  note 3 : ZSTD_isError() is always correct, whatever the library version.
 **********************************************/
typedef enum {
  ZSTD_error_no_error = 0,
  ZSTD_error_GENERIC  = 1,
  ZSTD_error_prefix_unknown                = 10,
  ZSTD_error_version_unsupported           = 12,
  ZSTD_error_frameParameter_unsupported    = 14,
  ZSTD_error_frameParameter_windowTooLarge = 16,
  ZSTD_error_corruption_detected = 20,
  ZSTD_error_checksum_wrong      = 22,
  ZSTD_error_dictionary_corrupted      = 30,
  ZSTD_error_dictionary_wrong          = 32,
  ZSTD_error_dictionaryCreation_failed = 34,
  ZSTD_error_parameter_unsupported   = 40,
  ZSTD_error_parameter_outOfBound    = 42,
  ZSTD_error_tableLog_tooLarge       = 44,
  ZSTD_error_maxSymbolValue_tooLarge = 46,
  ZSTD_error_maxSymbolValue_tooSmall = 48,
  ZSTD_error_stage_wrong       = 60,
  ZSTD_error_init_missing      = 62,
  ZSTD_error_memory_allocation = 64,
  ZSTD_error_workSpace_tooSmall= 66,
  ZSTD_error_dstSize_tooSmall = 70,
  ZSTD_error_srcSize_wrong    = 72,
  ZSTD_error_dstBuffer_null   = 74,
  /* following error codes are __NOT STABLE__, they can be removed or changed in future versions */
  ZSTD_error_frameIndex_tooLarge = 100,
  ZSTD_error_seekableIO          = 102,
  ZSTD_error_dstBuffer_wrong     = 104,
  ZSTD_error_maxCode = 120  /* never EVER use this value directly, it can change in future versions! Use ZSTD_isError() instead */
} ZSTD_ErrorCode;

/*! ZSTD_getErrorCode() :
    convert a `size_t` function result into a `ZSTD_ErrorCode` enum type,
    which can be used to compare with enum list published above */
ZSTDERRORLIB_API ZSTD_ErrorCode ZSTD_getErrorCode(size_t functionResult);
ZSTDERRORLIB_API const char* ZSTD_getErrorString(ZSTD_ErrorCode code);   /**< Same as ZSTD_getErrorName, but using a `ZSTD_ErrorCode` enum argument */


#if defined (__cplusplus)
}
#endif

#endif /* ZSTD_ERRORS_H_398273423 */
/**** ended inlining zstd_errors.h ****/


/* ****************************************
*  Compiler-specific
******************************************/
#if defined(__GNUC__)
#  define ERR_STATIC static __attribute__((unused))
#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
#  define ERR_STATIC static inline
#elif defined(_MSC_VER)
#  define ERR_STATIC static __inline
#else
#  define ERR_STATIC static  /* this version may generate warnings for unused static functions; disable the relevant warning */
#endif


/*-****************************************
*  Customization (error_public.h)
******************************************/
typedef ZSTD_ErrorCode ERR_enum;
#define PREFIX(name) ZSTD_error_##name


/*-****************************************
*  Error codes handling
******************************************/
#undef ERROR   /* already defined on Visual Studio */
#define ERROR(name) ZSTD_ERROR(name)
#define ZSTD_ERROR(name) ((size_t)-PREFIX(name))

ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); }

ERR_STATIC ERR_enum ERR_getErrorCode(size_t code) { if (!ERR_isError(code)) return (ERR_enum)0; return (ERR_enum) (0-code); }

/* check and forward error code */
#define CHECK_V_F(e, f) size_t const e = f; if (ERR_isError(e)) return e
#define CHECK_F(f)   { CHECK_V_F(_var_err__, f); }


/*-****************************************
*  Error Strings
******************************************/

const char* ERR_getErrorString(ERR_enum code);   /* error_private.c */

ERR_STATIC const char* ERR_getErrorName(size_t code)
{
    return ERR_getErrorString(ERR_getErrorCode(code));
}

#if defined (__cplusplus)
}
#endif

#endif /* ERROR_H_MODULE */
/**** ended inlining error_private.h ****/
#define FSE_STATIC_LINKING_ONLY  /* FSE_MIN_TABLELOG */
/**** start inlining fse.h ****/
/* ******************************************************************
 * FSE : Finite State Entropy codec
 * Public Prototypes declaration
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */

#if defined (__cplusplus)
extern "C" {
#endif

#ifndef FSE_H
#define FSE_H


/*-*****************************************
*  Dependencies
******************************************/
#include <stddef.h>    /* size_t, ptrdiff_t */


/*-*****************************************
*  FSE_PUBLIC_API : control library symbols visibility
******************************************/
#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
#  define FSE_PUBLIC_API __attribute__ ((visibility ("default")))
#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1)   /* Visual expected */
#  define FSE_PUBLIC_API __declspec(dllexport)
#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
#  define FSE_PUBLIC_API __declspec(dllimport) /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
#else
#  define FSE_PUBLIC_API
#endif

/*------   Version   ------*/
#define FSE_VERSION_MAJOR    0
#define FSE_VERSION_MINOR    9
#define FSE_VERSION_RELEASE  0

#define FSE_LIB_VERSION FSE_VERSION_MAJOR.FSE_VERSION_MINOR.FSE_VERSION_RELEASE
#define FSE_QUOTE(str) #str
#define FSE_EXPAND_AND_QUOTE(str) FSE_QUOTE(str)
#define FSE_VERSION_STRING FSE_EXPAND_AND_QUOTE(FSE_LIB_VERSION)

#define FSE_VERSION_NUMBER  (FSE_VERSION_MAJOR *100*100 + FSE_VERSION_MINOR *100 + FSE_VERSION_RELEASE)
FSE_PUBLIC_API unsigned FSE_versionNumber(void);   /**< library version number; to be used when checking dll version */


/*-****************************************
*  FSE simple functions
******************************************/
/*! FSE_compress() :
    Compress content of buffer 'src', of size 'srcSize', into destination buffer 'dst'.
    'dst' buffer must be already allocated. Compression runs faster is dstCapacity >= FSE_compressBound(srcSize).
    @return : size of compressed data (<= dstCapacity).
    Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
                     if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression instead.
                     if FSE_isError(return), compression failed (more details using FSE_getErrorName())
*/
FSE_PUBLIC_API size_t FSE_compress(void* dst, size_t dstCapacity,
                             const void* src, size_t srcSize);

/*! FSE_decompress():
    Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
    into already allocated destination buffer 'dst', of size 'dstCapacity'.
    @return : size of regenerated data (<= maxDstSize),
              or an error code, which can be tested using FSE_isError() .

    ** Important ** : FSE_decompress() does not decompress non-compressible nor RLE data !!!
    Why ? : making this distinction requires a header.
    Header management is intentionally delegated to the user layer, which can better manage special cases.
*/
FSE_PUBLIC_API size_t FSE_decompress(void* dst,  size_t dstCapacity,
                               const void* cSrc, size_t cSrcSize);


/*-*****************************************
*  Tool functions
******************************************/
FSE_PUBLIC_API size_t FSE_compressBound(size_t size);       /* maximum compressed size */

/* Error Management */
FSE_PUBLIC_API unsigned    FSE_isError(size_t code);        /* tells if a return value is an error code */
FSE_PUBLIC_API const char* FSE_getErrorName(size_t code);   /* provides error code string (useful for debugging) */


/*-*****************************************
*  FSE advanced functions
******************************************/
/*! FSE_compress2() :
    Same as FSE_compress(), but allows the selection of 'maxSymbolValue' and 'tableLog'
    Both parameters can be defined as '0' to mean : use default value
    @return : size of compressed data
    Special values : if return == 0, srcData is not compressible => Nothing is stored within cSrc !!!
                     if return == 1, srcData is a single byte symbol * srcSize times. Use RLE compression.
                     if FSE_isError(return), it's an error code.
*/
FSE_PUBLIC_API size_t FSE_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);


/*-*****************************************
*  FSE detailed API
******************************************/
/*!
FSE_compress() does the following:
1. count symbol occurrence from source[] into table count[] (see hist.h)
2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
3. save normalized counters to memory buffer using writeNCount()
4. build encoding table 'CTable' from normalized counters
5. encode the data stream using encoding table 'CTable'

FSE_decompress() does the following:
1. read normalized counters with readNCount()
2. build decoding table 'DTable' from normalized counters
3. decode the data stream using decoding table 'DTable'

The following API allows targeting specific sub-functions for advanced tasks.
For example, it's possible to compress several blocks using the same 'CTable',
or to save and provide normalized distribution using external method.
*/

/* *** COMPRESSION *** */

/*! FSE_optimalTableLog():
    dynamically downsize 'tableLog' when conditions are met.
    It saves CPU time, by using smaller tables, while preserving or even improving compression ratio.
    @return : recommended tableLog (necessarily <= 'maxTableLog') */
FSE_PUBLIC_API unsigned FSE_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);

/*! FSE_normalizeCount():
    normalize counts so that sum(count[]) == Power_of_2 (2^tableLog)
    'normalizedCounter' is a table of short, of minimum size (maxSymbolValue+1).
    @return : tableLog,
              or an errorCode, which can be tested using FSE_isError() */
FSE_PUBLIC_API size_t FSE_normalizeCount(short* normalizedCounter, unsigned tableLog,
                    const unsigned* count, size_t srcSize, unsigned maxSymbolValue);

/*! FSE_NCountWriteBound():
    Provides the maximum possible size of an FSE normalized table, given 'maxSymbolValue' and 'tableLog'.
    Typically useful for allocation purpose. */
FSE_PUBLIC_API size_t FSE_NCountWriteBound(unsigned maxSymbolValue, unsigned tableLog);

/*! FSE_writeNCount():
    Compactly save 'normalizedCounter' into 'buffer'.
    @return : size of the compressed table,
              or an errorCode, which can be tested using FSE_isError(). */
FSE_PUBLIC_API size_t FSE_writeNCount (void* buffer, size_t bufferSize,
                                 const short* normalizedCounter,
                                 unsigned maxSymbolValue, unsigned tableLog);

/*! Constructor and Destructor of FSE_CTable.
    Note that FSE_CTable size depends on 'tableLog' and 'maxSymbolValue' */
typedef unsigned FSE_CTable;   /* don't allocate that. It's only meant to be more restrictive than void* */
FSE_PUBLIC_API FSE_CTable* FSE_createCTable (unsigned maxSymbolValue, unsigned tableLog);
FSE_PUBLIC_API void        FSE_freeCTable (FSE_CTable* ct);

/*! FSE_buildCTable():
    Builds `ct`, which must be already allocated, using FSE_createCTable().
    @return : 0, or an errorCode, which can be tested using FSE_isError() */
FSE_PUBLIC_API size_t FSE_buildCTable(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);

/*! FSE_compress_usingCTable():
    Compress `src` using `ct` into `dst` which must be already allocated.
    @return : size of compressed data (<= `dstCapacity`),
              or 0 if compressed data could not fit into `dst`,
              or an errorCode, which can be tested using FSE_isError() */
FSE_PUBLIC_API size_t FSE_compress_usingCTable (void* dst, size_t dstCapacity, const void* src, size_t srcSize, const FSE_CTable* ct);

/*!
Tutorial :
----------
The first step is to count all symbols. FSE_count() does this job very fast.
Result will be saved into 'count', a table of unsigned int, which must be already allocated, and have 'maxSymbolValuePtr[0]+1' cells.
'src' is a table of bytes of size 'srcSize'. All values within 'src' MUST be <= maxSymbolValuePtr[0]
maxSymbolValuePtr[0] will be updated, with its real value (necessarily <= original value)
FSE_count() will return the number of occurrence of the most frequent symbol.
This can be used to know if there is a single symbol within 'src', and to quickly evaluate its compressibility.
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).

The next step is to normalize the frequencies.
FSE_normalizeCount() will ensure that sum of frequencies is == 2 ^'tableLog'.
It also guarantees a minimum of 1 to any Symbol with frequency >= 1.
You can use 'tableLog'==0 to mean "use default tableLog value".
If you are unsure of which tableLog value to use, you can ask FSE_optimalTableLog(),
which will provide the optimal valid tableLog given sourceSize, maxSymbolValue, and a user-defined maximum (0 means "default").

The result of FSE_normalizeCount() will be saved into a table,
called 'normalizedCounter', which is a table of signed short.
'normalizedCounter' must be already allocated, and have at least 'maxSymbolValue+1' cells.
The return value is tableLog if everything proceeded as expected.
It is 0 if there is a single symbol within distribution.
If there is an error (ex: invalid tableLog value), the function will return an ErrorCode (which can be tested using FSE_isError()).

'normalizedCounter' can be saved in a compact manner to a memory area using FSE_writeNCount().
'buffer' must be already allocated.
For guaranteed success, buffer size must be at least FSE_headerBound().
The result of the function is the number of bytes written into 'buffer'.
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError(); ex : buffer size too small).

'normalizedCounter' can then be used to create the compression table 'CTable'.
The space required by 'CTable' must be already allocated, using FSE_createCTable().
You can then use FSE_buildCTable() to fill 'CTable'.
If there is an error, both functions will return an ErrorCode (which can be tested using FSE_isError()).

'CTable' can then be used to compress 'src', with FSE_compress_usingCTable().
Similar to FSE_count(), the convention is that 'src' is assumed to be a table of char of size 'srcSize'
The function returns the size of compressed data (without header), necessarily <= `dstCapacity`.
If it returns '0', compressed data could not fit into 'dst'.
If there is an error, the function will return an ErrorCode (which can be tested using FSE_isError()).
*/


/* *** DECOMPRESSION *** */

/*! FSE_readNCount():
    Read compactly saved 'normalizedCounter' from 'rBuffer'.
    @return : size read from 'rBuffer',
              or an errorCode, which can be tested using FSE_isError().
              maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
FSE_PUBLIC_API size_t FSE_readNCount (short* normalizedCounter,
                           unsigned* maxSymbolValuePtr, unsigned* tableLogPtr,
                           const void* rBuffer, size_t rBuffSize);

/*! Constructor and Destructor of FSE_DTable.
    Note that its size depends on 'tableLog' */
typedef unsigned FSE_DTable;   /* don't allocate that. It's just a way to be more restrictive than void* */
FSE_PUBLIC_API FSE_DTable* FSE_createDTable(unsigned tableLog);
FSE_PUBLIC_API void        FSE_freeDTable(FSE_DTable* dt);

/*! FSE_buildDTable():
    Builds 'dt', which must be already allocated, using FSE_createDTable().
    return : 0, or an errorCode, which can be tested using FSE_isError() */
FSE_PUBLIC_API size_t FSE_buildDTable (FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);

/*! FSE_decompress_usingDTable():
    Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
    into `dst` which must be already allocated.
    @return : size of regenerated data (necessarily <= `dstCapacity`),
              or an errorCode, which can be tested using FSE_isError() */
FSE_PUBLIC_API size_t FSE_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt);

/*!
Tutorial :
----------
(Note : these functions only decompress FSE-compressed blocks.
 If block is uncompressed, use memcpy() instead
 If block is a single repeated byte, use memset() instead )

The first step is to obtain the normalized frequencies of symbols.
This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
or size the table to handle worst case situations (typically 256).
FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
If there is an error, the function will return an error code, which can be tested using FSE_isError().

The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
This is performed by the function FSE_buildDTable().
The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
If there is an error, the function will return an error code, which can be tested using FSE_isError().

`FSE_DTable` can then be used to decompress `cSrc`, with FSE_decompress_usingDTable().
`cSrcSize` must be strictly correct, otherwise decompression will fail.
FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
*/

#endif  /* FSE_H */

#if defined(FSE_STATIC_LINKING_ONLY) && !defined(FSE_H_FSE_STATIC_LINKING_ONLY)
#define FSE_H_FSE_STATIC_LINKING_ONLY

/* *** Dependency *** */
/**** start inlining bitstream.h ****/
/* ******************************************************************
 * bitstream
 * Part of FSE library
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */
#ifndef BITSTREAM_H_MODULE
#define BITSTREAM_H_MODULE

#if defined (__cplusplus)
extern "C" {
#endif

/*
*  This API consists of small unitary functions, which must be inlined for best performance.
*  Since link-time-optimization is not available for all compilers,
*  these functions are defined into a .h to be included.
*/

/*-****************************************
*  Dependencies
******************************************/
/**** skipping file: mem.h ****/
/**** start inlining compiler.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_COMPILER_H
#define ZSTD_COMPILER_H

/*-*******************************************************
*  Compiler specifics
*********************************************************/
/* force inlining */

#if !defined(ZSTD_NO_INLINE)
#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
#  define INLINE_KEYWORD inline
#else
#  define INLINE_KEYWORD
#endif

#if defined(__GNUC__) || defined(__ICCARM__)
#  define FORCE_INLINE_ATTR __attribute__((always_inline))
#elif defined(_MSC_VER)
#  define FORCE_INLINE_ATTR __forceinline
#else
#  define FORCE_INLINE_ATTR
#endif

#else

#define INLINE_KEYWORD
#define FORCE_INLINE_ATTR

#endif

/**
  On MSVC qsort requires that functions passed into it use the __cdecl calling conversion(CC). 
  This explictly marks such functions as __cdecl so that the code will still compile 
  if a CC other than __cdecl has been made the default.
*/
#if  defined(_MSC_VER)
#  define WIN_CDECL __cdecl
#else
#  define WIN_CDECL 
#endif

/**
 * FORCE_INLINE_TEMPLATE is used to define C "templates", which take constant
 * parameters. They must be inlined for the compiler to eliminate the constant
 * branches.
 */
#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR
/**
 * HINT_INLINE is used to help the compiler generate better code. It is *not*
 * used for "templates", so it can be tweaked based on the compilers
 * performance.
 *
 * gcc-4.8 and gcc-4.9 have been shown to benefit from leaving off the
 * always_inline attribute.
 *
 * clang up to 5.0.0 (trunk) benefit tremendously from the always_inline
 * attribute.
 */
#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 8 && __GNUC__ < 5
#  define HINT_INLINE static INLINE_KEYWORD
#else
#  define HINT_INLINE static INLINE_KEYWORD FORCE_INLINE_ATTR
#endif

/* UNUSED_ATTR tells the compiler it is okay if the function is unused. */
#if defined(__GNUC__)
#  define UNUSED_ATTR __attribute__((unused))
#else
#  define UNUSED_ATTR
#endif

/* force no inlining */
#ifdef _MSC_VER
#  define FORCE_NOINLINE static __declspec(noinline)
#else
#  if defined(__GNUC__) || defined(__ICCARM__)
#    define FORCE_NOINLINE static __attribute__((__noinline__))
#  else
#    define FORCE_NOINLINE static
#  endif
#endif

/* target attribute */
#ifndef __has_attribute
  #define __has_attribute(x) 0  /* Compatibility with non-clang compilers. */
#endif
#if defined(__GNUC__) || defined(__ICCARM__)
#  define TARGET_ATTRIBUTE(target) __attribute__((__target__(target)))
#else
#  define TARGET_ATTRIBUTE(target)
#endif

/* Enable runtime BMI2 dispatch based on the CPU.
 * Enabled for clang & gcc >=4.8 on x86 when BMI2 isn't enabled by default.
 */
#ifndef DYNAMIC_BMI2
  #if ((defined(__clang__) && __has_attribute(__target__)) \
      || (defined(__GNUC__) \
          && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))) \
      && (defined(__x86_64__) || defined(_M_X86)) \
      && !defined(__BMI2__)
  #  define DYNAMIC_BMI2 1
  #else
  #  define DYNAMIC_BMI2 0
  #endif
#endif

/* prefetch
 * can be disabled, by declaring NO_PREFETCH build macro */
#if defined(NO_PREFETCH)
#  define PREFETCH_L1(ptr)  (void)(ptr)  /* disabled */
#  define PREFETCH_L2(ptr)  (void)(ptr)  /* disabled */
#else
#  if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_I86))  /* _mm_prefetch() is not defined outside of x86/x64 */
#    include <mmintrin.h>   /* https://msdn.microsoft.com/fr-fr/library/84szxsww(v=vs.90).aspx */
#    define PREFETCH_L1(ptr)  _mm_prefetch((const char*)(ptr), _MM_HINT_T0)
#    define PREFETCH_L2(ptr)  _mm_prefetch((const char*)(ptr), _MM_HINT_T1)
#    elif defined(__aarch64__)
#     define PREFETCH_L1(ptr)  __asm__ __volatile__("prfm pldl1keep, %0" ::"Q"(*(ptr)))
#     define PREFETCH_L2(ptr)  __asm__ __volatile__("prfm pldl2keep, %0" ::"Q"(*(ptr)))
#  elif defined(__GNUC__) && ( (__GNUC__ >= 4) || ( (__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) ) )
#    define PREFETCH_L1(ptr)  __builtin_prefetch((ptr), 0 /* rw==read */, 3 /* locality */)
#    define PREFETCH_L2(ptr)  __builtin_prefetch((ptr), 0 /* rw==read */, 2 /* locality */)
#  else
#    define PREFETCH_L1(ptr) (void)(ptr)  /* disabled */
#    define PREFETCH_L2(ptr) (void)(ptr)  /* disabled */
#  endif
#endif  /* NO_PREFETCH */

#define CACHELINE_SIZE 64

#define PREFETCH_AREA(p, s)  {            \
    const char* const _ptr = (const char*)(p);  \
    size_t const _size = (size_t)(s);     \
    size_t _pos;                          \
    for (_pos=0; _pos<_size; _pos+=CACHELINE_SIZE) {  \
        PREFETCH_L2(_ptr + _pos);         \
    }                                     \
}

/* vectorization
 * older GCC (pre gcc-4.3 picked as the cutoff) uses a different syntax */
#if !defined(__INTEL_COMPILER) && !defined(__clang__) && defined(__GNUC__)
#  if (__GNUC__ == 4 && __GNUC_MINOR__ > 3) || (__GNUC__ >= 5)
#    define DONT_VECTORIZE __attribute__((optimize("no-tree-vectorize")))
#  else
#    define DONT_VECTORIZE _Pragma("GCC optimize(\"no-tree-vectorize\")")
#  endif
#else
#  define DONT_VECTORIZE
#endif

/* Tell the compiler that a branch is likely or unlikely.
 * Only use these macros if it causes the compiler to generate better code.
 * If you can remove a LIKELY/UNLIKELY annotation without speed changes in gcc
 * and clang, please do.
 */
#if defined(__GNUC__)
#define LIKELY(x) (__builtin_expect((x), 1))
#define UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif

/* disable warnings */
#ifdef _MSC_VER    /* Visual Studio */
#  include <intrin.h>                    /* For Visual 2005 */
#  pragma warning(disable : 4100)        /* disable: C4100: unreferenced formal parameter */
#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
#  pragma warning(disable : 4204)        /* disable: C4204: non-constant aggregate initializer */
#  pragma warning(disable : 4214)        /* disable: C4214: non-int bitfields */
#  pragma warning(disable : 4324)        /* disable: C4324: padded structure */
#endif

#endif /* ZSTD_COMPILER_H */
/**** ended inlining compiler.h ****/
/**** skipping file: debug.h ****/
/**** skipping file: error_private.h ****/


/*=========================================
*  Target specific
=========================================*/
#if defined(__BMI__) && defined(__GNUC__)
#  include <immintrin.h>   /* support for bextr (experimental) */
#elif defined(__ICCARM__)
#  include <intrinsics.h>
#endif

#define STREAM_ACCUMULATOR_MIN_32  25
#define STREAM_ACCUMULATOR_MIN_64  57
#define STREAM_ACCUMULATOR_MIN    ((U32)(MEM_32bits() ? STREAM_ACCUMULATOR_MIN_32 : STREAM_ACCUMULATOR_MIN_64))


/*-******************************************
*  bitStream encoding API (write forward)
********************************************/
/* bitStream can mix input from multiple sources.
 * A critical property of these streams is that they encode and decode in **reverse** direction.
 * So the first bit sequence you add will be the last to be read, like a LIFO stack.
 */
typedef struct {
    size_t bitContainer;
    unsigned bitPos;
    char*  startPtr;
    char*  ptr;
    char*  endPtr;
} BIT_CStream_t;

MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC, void* dstBuffer, size_t dstCapacity);
MEM_STATIC void   BIT_addBits(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
MEM_STATIC void   BIT_flushBits(BIT_CStream_t* bitC);
MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC);

/* Start with initCStream, providing the size of buffer to write into.
*  bitStream will never write outside of this buffer.
*  `dstCapacity` must be >= sizeof(bitD->bitContainer), otherwise @return will be an error code.
*
*  bits are first added to a local register.
*  Local register is size_t, hence 64-bits on 64-bits systems, or 32-bits on 32-bits systems.
*  Writing data into memory is an explicit operation, performed by the flushBits function.
*  Hence keep track how many bits are potentially stored into local register to avoid register overflow.
*  After a flushBits, a maximum of 7 bits might still be stored into local register.
*
*  Avoid storing elements of more than 24 bits if you want compatibility with 32-bits bitstream readers.
*
*  Last operation is to close the bitStream.
*  The function returns the final size of CStream in bytes.
*  If data couldn't fit into `dstBuffer`, it will return a 0 ( == not storable)
*/


/*-********************************************
*  bitStream decoding API (read backward)
**********************************************/
typedef struct {
    size_t   bitContainer;
    unsigned bitsConsumed;
    const char* ptr;
    const char* start;
    const char* limitPtr;
} BIT_DStream_t;

typedef enum { BIT_DStream_unfinished = 0,
               BIT_DStream_endOfBuffer = 1,
               BIT_DStream_completed = 2,
               BIT_DStream_overflow = 3 } BIT_DStream_status;  /* result of BIT_reloadDStream() */
               /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */

MEM_STATIC size_t   BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
MEM_STATIC size_t   BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);


/* Start by invoking BIT_initDStream().
*  A chunk of the bitStream is then stored into a local register.
*  Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
*  You can then retrieve bitFields stored into the local register, **in reverse order**.
*  Local register is explicitly reloaded from memory by the BIT_reloadDStream() method.
*  A reload guarantee a minimum of ((8*sizeof(bitD->bitContainer))-7) bits when its result is BIT_DStream_unfinished.
*  Otherwise, it can be less than that, so proceed accordingly.
*  Checking if DStream has reached its end can be performed with BIT_endOfDStream().
*/


/*-****************************************
*  unsafe API
******************************************/
MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC, size_t value, unsigned nbBits);
/* faster, but works only if value is "clean", meaning all high bits above nbBits are 0 */

MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC);
/* unsafe version; does not check buffer overflow */

MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
/* faster, but works only if nbBits >= 1 */



/*-**************************************************************
*  Internal functions
****************************************************************/
MEM_STATIC unsigned BIT_highbit32 (U32 val)
{
    assert(val != 0);
    {
#   if defined(_MSC_VER)   /* Visual */
        unsigned long r=0;
        return _BitScanReverse ( &r, val ) ? (unsigned)r : 0;
#   elif defined(__GNUC__) && (__GNUC__ >= 3)   /* Use GCC Intrinsic */
        return __builtin_clz (val) ^ 31;
#   elif defined(__ICCARM__)    /* IAR Intrinsic */
        return 31 - __CLZ(val);
#   else   /* Software version */
        static const unsigned DeBruijnClz[32] = { 0,  9,  1, 10, 13, 21,  2, 29,
                                                 11, 14, 16, 18, 22, 25,  3, 30,
                                                  8, 12, 20, 28, 15, 17, 24,  7,
                                                 19, 27, 23,  6, 26,  5,  4, 31 };
        U32 v = val;
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
#   endif
    }
}

/*=====    Local Constants   =====*/
static const unsigned BIT_mask[] = {
    0,          1,         3,         7,         0xF,       0x1F,
    0x3F,       0x7F,      0xFF,      0x1FF,     0x3FF,     0x7FF,
    0xFFF,      0x1FFF,    0x3FFF,    0x7FFF,    0xFFFF,    0x1FFFF,
    0x3FFFF,    0x7FFFF,   0xFFFFF,   0x1FFFFF,  0x3FFFFF,  0x7FFFFF,
    0xFFFFFF,   0x1FFFFFF, 0x3FFFFFF, 0x7FFFFFF, 0xFFFFFFF, 0x1FFFFFFF,
    0x3FFFFFFF, 0x7FFFFFFF}; /* up to 31 bits */
#define BIT_MASK_SIZE (sizeof(BIT_mask) / sizeof(BIT_mask[0]))

/*-**************************************************************
*  bitStream encoding
****************************************************************/
/*! BIT_initCStream() :
 *  `dstCapacity` must be > sizeof(size_t)
 *  @return : 0 if success,
 *            otherwise an error code (can be tested using ERR_isError()) */
MEM_STATIC size_t BIT_initCStream(BIT_CStream_t* bitC,
                                  void* startPtr, size_t dstCapacity)
{
    bitC->bitContainer = 0;
    bitC->bitPos = 0;
    bitC->startPtr = (char*)startPtr;
    bitC->ptr = bitC->startPtr;
    bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer);
    if (dstCapacity <= sizeof(bitC->bitContainer)) return ERROR(dstSize_tooSmall);
    return 0;
}

/*! BIT_addBits() :
 *  can add up to 31 bits into `bitC`.
 *  Note : does not check for register overflow ! */
MEM_STATIC void BIT_addBits(BIT_CStream_t* bitC,
                            size_t value, unsigned nbBits)
{
    MEM_STATIC_ASSERT(BIT_MASK_SIZE == 32);
    assert(nbBits < BIT_MASK_SIZE);
    assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
    bitC->bitContainer |= (value & BIT_mask[nbBits]) << bitC->bitPos;
    bitC->bitPos += nbBits;
}

/*! BIT_addBitsFast() :
 *  works only if `value` is _clean_,
 *  meaning all high bits above nbBits are 0 */
MEM_STATIC void BIT_addBitsFast(BIT_CStream_t* bitC,
                                size_t value, unsigned nbBits)
{
    assert((value>>nbBits) == 0);
    assert(nbBits + bitC->bitPos < sizeof(bitC->bitContainer) * 8);
    bitC->bitContainer |= value << bitC->bitPos;
    bitC->bitPos += nbBits;
}

/*! BIT_flushBitsFast() :
 *  assumption : bitContainer has not overflowed
 *  unsafe version; does not check buffer overflow */
MEM_STATIC void BIT_flushBitsFast(BIT_CStream_t* bitC)
{
    size_t const nbBytes = bitC->bitPos >> 3;
    assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
    assert(bitC->ptr <= bitC->endPtr);
    MEM_writeLEST(bitC->ptr, bitC->bitContainer);
    bitC->ptr += nbBytes;
    bitC->bitPos &= 7;
    bitC->bitContainer >>= nbBytes*8;
}

/*! BIT_flushBits() :
 *  assumption : bitContainer has not overflowed
 *  safe version; check for buffer overflow, and prevents it.
 *  note : does not signal buffer overflow.
 *  overflow will be revealed later on using BIT_closeCStream() */
MEM_STATIC void BIT_flushBits(BIT_CStream_t* bitC)
{
    size_t const nbBytes = bitC->bitPos >> 3;
    assert(bitC->bitPos < sizeof(bitC->bitContainer) * 8);
    assert(bitC->ptr <= bitC->endPtr);
    MEM_writeLEST(bitC->ptr, bitC->bitContainer);
    bitC->ptr += nbBytes;
    if (bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
    bitC->bitPos &= 7;
    bitC->bitContainer >>= nbBytes*8;
}

/*! BIT_closeCStream() :
 *  @return : size of CStream, in bytes,
 *            or 0 if it could not fit into dstBuffer */
MEM_STATIC size_t BIT_closeCStream(BIT_CStream_t* bitC)
{
    BIT_addBitsFast(bitC, 1, 1);   /* endMark */
    BIT_flushBits(bitC);
    if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
    return (bitC->ptr - bitC->startPtr) + (bitC->bitPos > 0);
}


/*-********************************************************
*  bitStream decoding
**********************************************************/
/*! BIT_initDStream() :
 *  Initialize a BIT_DStream_t.
 * `bitD` : a pointer to an already allocated BIT_DStream_t structure.
 * `srcSize` must be the *exact* size of the bitStream, in bytes.
 * @return : size of stream (== srcSize), or an errorCode if a problem is detected
 */
MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
{
    if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }

    bitD->start = (const char*)srcBuffer;
    bitD->limitPtr = bitD->start + sizeof(bitD->bitContainer);

    if (srcSize >=  sizeof(bitD->bitContainer)) {  /* normal case */
        bitD->ptr   = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
        bitD->bitContainer = MEM_readLEST(bitD->ptr);
        { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
          bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0;  /* ensures bitsConsumed is always set */
          if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
    } else {
        bitD->ptr   = bitD->start;
        bitD->bitContainer = *(const BYTE*)(bitD->start);
        switch(srcSize)
        {
        case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);
                /* fall-through */

        case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);
                /* fall-through */

        case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);
                /* fall-through */

        case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24;
                /* fall-through */

        case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16;
                /* fall-through */

        case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) <<  8;
                /* fall-through */

        default: break;
        }
        {   BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
            bitD->bitsConsumed = lastByte ? 8 - BIT_highbit32(lastByte) : 0;
            if (lastByte == 0) return ERROR(corruption_detected);  /* endMark not present */
        }
        bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
    }

    return srcSize;
}

MEM_STATIC size_t BIT_getUpperBits(size_t bitContainer, U32 const start)
{
    return bitContainer >> start;
}

MEM_STATIC size_t BIT_getMiddleBits(size_t bitContainer, U32 const start, U32 const nbBits)
{
    U32 const regMask = sizeof(bitContainer)*8 - 1;
    /* if start > regMask, bitstream is corrupted, and result is undefined */
    assert(nbBits < BIT_MASK_SIZE);
    return (bitContainer >> (start & regMask)) & BIT_mask[nbBits];
}

MEM_STATIC size_t BIT_getLowerBits(size_t bitContainer, U32 const nbBits)
{
    assert(nbBits < BIT_MASK_SIZE);
    return bitContainer & BIT_mask[nbBits];
}

/*! BIT_lookBits() :
 *  Provides next n bits from local register.
 *  local register is not modified.
 *  On 32-bits, maxNbBits==24.
 *  On 64-bits, maxNbBits==56.
 * @return : value extracted */
MEM_STATIC size_t BIT_lookBits(const BIT_DStream_t* bitD, U32 nbBits)
{
    /* arbitrate between double-shift and shift+mask */
#if 1
    /* if bitD->bitsConsumed + nbBits > sizeof(bitD->bitContainer)*8,
     * bitstream is likely corrupted, and result is undefined */
    return BIT_getMiddleBits(bitD->bitContainer, (sizeof(bitD->bitContainer)*8) - bitD->bitsConsumed - nbBits, nbBits);
#else
    /* this code path is slower on my os-x laptop */
    U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
    return ((bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> 1) >> ((regMask-nbBits) & regMask);
#endif
}

/*! BIT_lookBitsFast() :
 *  unsafe version; only works if nbBits >= 1 */
MEM_STATIC size_t BIT_lookBitsFast(const BIT_DStream_t* bitD, U32 nbBits)
{
    U32 const regMask = sizeof(bitD->bitContainer)*8 - 1;
    assert(nbBits >= 1);
    return (bitD->bitContainer << (bitD->bitsConsumed & regMask)) >> (((regMask+1)-nbBits) & regMask);
}

MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
{
    bitD->bitsConsumed += nbBits;
}

/*! BIT_readBits() :
 *  Read (consume) next n bits from local register and update.
 *  Pay attention to not read more than nbBits contained into local register.
 * @return : extracted value. */
MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits)
{
    size_t const value = BIT_lookBits(bitD, nbBits);
    BIT_skipBits(bitD, nbBits);
    return value;
}

/*! BIT_readBitsFast() :
 *  unsafe version; only works only if nbBits >= 1 */
MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits)
{
    size_t const value = BIT_lookBitsFast(bitD, nbBits);
    assert(nbBits >= 1);
    BIT_skipBits(bitD, nbBits);
    return value;
}

/*! BIT_reloadDStreamFast() :
 *  Similar to BIT_reloadDStream(), but with two differences:
 *  1. bitsConsumed <= sizeof(bitD->bitContainer)*8 must hold!
 *  2. Returns BIT_DStream_overflow when bitD->ptr < bitD->limitPtr, at this
 *     point you must use BIT_reloadDStream() to reload.
 */
MEM_STATIC BIT_DStream_status BIT_reloadDStreamFast(BIT_DStream_t* bitD)
{
    if (UNLIKELY(bitD->ptr < bitD->limitPtr))
        return BIT_DStream_overflow;
    assert(bitD->bitsConsumed <= sizeof(bitD->bitContainer)*8);
    bitD->ptr -= bitD->bitsConsumed >> 3;
    bitD->bitsConsumed &= 7;
    bitD->bitContainer = MEM_readLEST(bitD->ptr);
    return BIT_DStream_unfinished;
}

/*! BIT_reloadDStream() :
 *  Refill `bitD` from buffer previously set in BIT_initDStream() .
 *  This function is safe, it guarantees it will not read beyond src buffer.
 * @return : status of `BIT_DStream_t` internal register.
 *           when status == BIT_DStream_unfinished, internal register is filled with at least 25 or 57 bits */
MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
{
    if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8))  /* overflow detected, like end of stream */
        return BIT_DStream_overflow;

    if (bitD->ptr >= bitD->limitPtr) {
        return BIT_reloadDStreamFast(bitD);
    }
    if (bitD->ptr == bitD->start) {
        if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
        return BIT_DStream_completed;
    }
    /* start < ptr < limitPtr */
    {   U32 nbBytes = bitD->bitsConsumed >> 3;
        BIT_DStream_status result = BIT_DStream_unfinished;
        if (bitD->ptr - nbBytes < bitD->start) {
            nbBytes = (U32)(bitD->ptr - bitD->start);  /* ptr > start */
            result = BIT_DStream_endOfBuffer;
        }
        bitD->ptr -= nbBytes;
        bitD->bitsConsumed -= nbBytes*8;
        bitD->bitContainer = MEM_readLEST(bitD->ptr);   /* reminder : srcSize > sizeof(bitD->bitContainer), otherwise bitD->ptr == bitD->start */
        return result;
    }
}

/*! BIT_endOfDStream() :
 * @return : 1 if DStream has _exactly_ reached its end (all bits consumed).
 */
MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
{
    return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
}

#if defined (__cplusplus)
}
#endif

#endif /* BITSTREAM_H_MODULE */
/**** ended inlining bitstream.h ****/


/* *****************************************
*  Static allocation
*******************************************/
/* FSE buffer bounds */
#define FSE_NCOUNTBOUND 512
#define FSE_BLOCKBOUND(size) (size + (size>>7) + 4 /* fse states */ + sizeof(size_t) /* bitContainer */)
#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size))   /* Macro version, useful for static allocation */

/* It is possible to statically allocate FSE CTable/DTable as a table of FSE_CTable/FSE_DTable using below macros */
#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue)   (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
#define FSE_DTABLE_SIZE_U32(maxTableLog)                   (1 + (1<<maxTableLog))

/* or use the size to malloc() space directly. Pay attention to alignment restrictions though */
#define FSE_CTABLE_SIZE(maxTableLog, maxSymbolValue)   (FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) * sizeof(FSE_CTable))
#define FSE_DTABLE_SIZE(maxTableLog)                   (FSE_DTABLE_SIZE_U32(maxTableLog) * sizeof(FSE_DTable))


/* *****************************************
 *  FSE advanced API
 ***************************************** */

unsigned FSE_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
/**< same as FSE_optimalTableLog(), which used `minus==2` */

/* FSE_compress_wksp() :
 * Same as FSE_compress2(), but using an externally allocated scratch buffer (`workSpace`).
 * FSE_WKSP_SIZE_U32() provides the minimum size required for `workSpace` as a table of FSE_CTable.
 */
#define FSE_WKSP_SIZE_U32(maxTableLog, maxSymbolValue)   ( FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) + ((maxTableLog > 12) ? (1 << (maxTableLog - 2)) : 1024) )
size_t FSE_compress_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);

size_t FSE_buildCTable_raw (FSE_CTable* ct, unsigned nbBits);
/**< build a fake FSE_CTable, designed for a flat distribution, where each symbol uses nbBits */

size_t FSE_buildCTable_rle (FSE_CTable* ct, unsigned char symbolValue);
/**< build a fake FSE_CTable, designed to compress always the same symbolValue */

/* FSE_buildCTable_wksp() :
 * Same as FSE_buildCTable(), but using an externally allocated scratch buffer (`workSpace`).
 * `wkspSize` must be >= `(1<<tableLog)`.
 */
size_t FSE_buildCTable_wksp(FSE_CTable* ct, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);

size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
/**< build a fake FSE_DTable, designed to read a flat distribution where each symbol uses nbBits */

size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
/**< build a fake FSE_DTable, designed to always generate the same symbolValue */

size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog);
/**< same as FSE_decompress(), using an externally allocated `workSpace` produced with `FSE_DTABLE_SIZE_U32(maxLog)` */

typedef enum {
   FSE_repeat_none,  /**< Cannot use the previous table */
   FSE_repeat_check, /**< Can use the previous table but it must be checked */
   FSE_repeat_valid  /**< Can use the previous table and it is assumed to be valid */
 } FSE_repeat;

/* *****************************************
*  FSE symbol compression API
*******************************************/
/*!
   This API consists of small unitary functions, which highly benefit from being inlined.
   Hence their body are included in next section.
*/
typedef struct {
    ptrdiff_t   value;
    const void* stateTable;
    const void* symbolTT;
    unsigned    stateLog;
} FSE_CState_t;

static void FSE_initCState(FSE_CState_t* CStatePtr, const FSE_CTable* ct);

static void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* CStatePtr, unsigned symbol);

static void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* CStatePtr);

/**<
These functions are inner components of FSE_compress_usingCTable().
They allow the creation of custom streams, mixing multiple tables and bit sources.

A key property to keep in mind is that encoding and decoding are done **in reverse direction**.
So the first symbol you will encode is the last you will decode, like a LIFO stack.

You will need a few variables to track your CStream. They are :

FSE_CTable    ct;         // Provided by FSE_buildCTable()
BIT_CStream_t bitStream;  // bitStream tracking structure
FSE_CState_t  state;      // State tracking structure (can have several)


The first thing to do is to init bitStream and state.
    size_t errorCode = BIT_initCStream(&bitStream, dstBuffer, maxDstSize);
    FSE_initCState(&state, ct);

Note that BIT_initCStream() can produce an error code, so its result should be tested, using FSE_isError();
You can then encode your input data, byte after byte.
FSE_encodeSymbol() outputs a maximum of 'tableLog' bits at a time.
Remember decoding will be done in reverse direction.
    FSE_encodeByte(&bitStream, &state, symbol);

At any time, you can also add any bit sequence.
Note : maximum allowed nbBits is 25, for compatibility with 32-bits decoders
    BIT_addBits(&bitStream, bitField, nbBits);

The above methods don't commit data to memory, they just store it into local register, for speed.
Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t).
Writing data to memory is a manual operation, performed by the flushBits function.
    BIT_flushBits(&bitStream);

Your last FSE encoding operation shall be to flush your last state value(s).
    FSE_flushState(&bitStream, &state);

Finally, you must close the bitStream.
The function returns the size of CStream in bytes.
If data couldn't fit into dstBuffer, it will return a 0 ( == not compressible)
If there is an error, it returns an errorCode (which can be tested using FSE_isError()).
    size_t size = BIT_closeCStream(&bitStream);
*/


/* *****************************************
*  FSE symbol decompression API
*******************************************/
typedef struct {
    size_t      state;
    const void* table;   /* precise table may vary, depending on U16 */
} FSE_DState_t;


static void     FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);

static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);

static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);

/**<
Let's now decompose FSE_decompress_usingDTable() into its unitary components.
You will decode FSE-encoded symbols from the bitStream,
and also any other bitFields you put in, **in reverse order**.

You will need a few variables to track your bitStream. They are :

BIT_DStream_t DStream;    // Stream context
FSE_DState_t  DState;     // State context. Multiple ones are possible
FSE_DTable*   DTablePtr;  // Decoding table, provided by FSE_buildDTable()

The first thing to do is to init the bitStream.
    errorCode = BIT_initDStream(&DStream, srcBuffer, srcSize);

You should then retrieve your initial state(s)
(in reverse flushing order if you have several ones) :
    errorCode = FSE_initDState(&DState, &DStream, DTablePtr);

You can then decode your data, symbol after symbol.
For information the maximum number of bits read by FSE_decodeSymbol() is 'tableLog'.
Keep in mind that symbols are decoded in reverse order, like a LIFO stack (last in, first out).
    unsigned char symbol = FSE_decodeSymbol(&DState, &DStream);

You can retrieve any bitfield you eventually stored into the bitStream (in reverse order)
Note : maximum allowed nbBits is 25, for 32-bits compatibility
    size_t bitField = BIT_readBits(&DStream, nbBits);

All above operations only read from local register (which size depends on size_t).
Refueling the register from memory is manually performed by the reload method.
    endSignal = FSE_reloadDStream(&DStream);

BIT_reloadDStream() result tells if there is still some more data to read from DStream.
BIT_DStream_unfinished : there is still some data left into the DStream.
BIT_DStream_endOfBuffer : Dstream reached end of buffer. Its container may no longer be completely filled.
BIT_DStream_completed : Dstream reached its exact end, corresponding in general to decompression completed.
BIT_DStream_tooFar : Dstream went too far. Decompression result is corrupted.

When reaching end of buffer (BIT_DStream_endOfBuffer), progress slowly, notably if you decode multiple symbols per loop,
to properly detect the exact end of stream.
After each decoded symbol, check if DStream is fully consumed using this simple test :
    BIT_reloadDStream(&DStream) >= BIT_DStream_completed

When it's done, verify decompression is fully completed, by checking both DStream and the relevant states.
Checking if DStream has reached its end is performed by :
    BIT_endOfDStream(&DStream);
Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible.
    FSE_endOfDState(&DState);
*/


/* *****************************************
*  FSE unsafe API
*******************************************/
static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */


/* *****************************************
*  Implementation of inlined functions
*******************************************/
typedef struct {
    int deltaFindState;
    U32 deltaNbBits;
} FSE_symbolCompressionTransform; /* total 8 bytes */

MEM_STATIC void FSE_initCState(FSE_CState_t* statePtr, const FSE_CTable* ct)
{
    const void* ptr = ct;
    const U16* u16ptr = (const U16*) ptr;
    const U32 tableLog = MEM_read16(ptr);
    statePtr->value = (ptrdiff_t)1<<tableLog;
    statePtr->stateTable = u16ptr+2;
    statePtr->symbolTT = ct + 1 + (tableLog ? (1<<(tableLog-1)) : 1);
    statePtr->stateLog = tableLog;
}


/*! FSE_initCState2() :
*   Same as FSE_initCState(), but the first symbol to include (which will be the last to be read)
*   uses the smallest state value possible, saving the cost of this symbol */
MEM_STATIC void FSE_initCState2(FSE_CState_t* statePtr, const FSE_CTable* ct, U32 symbol)
{
    FSE_initCState(statePtr, ct);
    {   const FSE_symbolCompressionTransform symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
        const U16* stateTable = (const U16*)(statePtr->stateTable);
        U32 nbBitsOut  = (U32)((symbolTT.deltaNbBits + (1<<15)) >> 16);
        statePtr->value = (nbBitsOut << 16) - symbolTT.deltaNbBits;
        statePtr->value = stateTable[(statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
    }
}

MEM_STATIC void FSE_encodeSymbol(BIT_CStream_t* bitC, FSE_CState_t* statePtr, unsigned symbol)
{
    FSE_symbolCompressionTransform const symbolTT = ((const FSE_symbolCompressionTransform*)(statePtr->symbolTT))[symbol];
    const U16* const stateTable = (const U16*)(statePtr->stateTable);
    U32 const nbBitsOut  = (U32)((statePtr->value + symbolTT.deltaNbBits) >> 16);
    BIT_addBits(bitC, statePtr->value, nbBitsOut);
    statePtr->value = stateTable[ (statePtr->value >> nbBitsOut) + symbolTT.deltaFindState];
}

MEM_STATIC void FSE_flushCState(BIT_CStream_t* bitC, const FSE_CState_t* statePtr)
{
    BIT_addBits(bitC, statePtr->value, statePtr->stateLog);
    BIT_flushBits(bitC);
}


/* FSE_getMaxNbBits() :
 * Approximate maximum cost of a symbol, in bits.
 * Fractional get rounded up (i.e : a symbol with a normalized frequency of 3 gives the same result as a frequency of 2)
 * note 1 : assume symbolValue is valid (<= maxSymbolValue)
 * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
MEM_STATIC U32 FSE_getMaxNbBits(const void* symbolTTPtr, U32 symbolValue)
{
    const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
    return (symbolTT[symbolValue].deltaNbBits + ((1<<16)-1)) >> 16;
}

/* FSE_bitCost() :
 * Approximate symbol cost, as fractional value, using fixed-point format (accuracyLog fractional bits)
 * note 1 : assume symbolValue is valid (<= maxSymbolValue)
 * note 2 : if freq[symbolValue]==0, @return a fake cost of tableLog+1 bits */
MEM_STATIC U32 FSE_bitCost(const void* symbolTTPtr, U32 tableLog, U32 symbolValue, U32 accuracyLog)
{
    const FSE_symbolCompressionTransform* symbolTT = (const FSE_symbolCompressionTransform*) symbolTTPtr;
    U32 const minNbBits = symbolTT[symbolValue].deltaNbBits >> 16;
    U32 const threshold = (minNbBits+1) << 16;
    assert(tableLog < 16);
    assert(accuracyLog < 31-tableLog);  /* ensure enough room for renormalization double shift */
    {   U32 const tableSize = 1 << tableLog;
        U32 const deltaFromThreshold = threshold - (symbolTT[symbolValue].deltaNbBits + tableSize);
        U32 const normalizedDeltaFromThreshold = (deltaFromThreshold << accuracyLog) >> tableLog;   /* linear interpolation (very approximate) */
        U32 const bitMultiplier = 1 << accuracyLog;
        assert(symbolTT[symbolValue].deltaNbBits + tableSize <= threshold);
        assert(normalizedDeltaFromThreshold <= bitMultiplier);
        return (minNbBits+1)*bitMultiplier - normalizedDeltaFromThreshold;
    }
}


/* ======    Decompression    ====== */

typedef struct {
    U16 tableLog;
    U16 fastMode;
} FSE_DTableHeader;   /* sizeof U32 */

typedef struct
{
    unsigned short newState;
    unsigned char  symbol;
    unsigned char  nbBits;
} FSE_decode_t;   /* size == U32 */

MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
{
    const void* ptr = dt;
    const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)ptr;
    DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
    BIT_reloadDStream(bitD);
    DStatePtr->table = dt + 1;
}

MEM_STATIC BYTE FSE_peekSymbol(const FSE_DState_t* DStatePtr)
{
    FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
    return DInfo.symbol;
}

MEM_STATIC void FSE_updateState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
{
    FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
    U32 const nbBits = DInfo.nbBits;
    size_t const lowBits = BIT_readBits(bitD, nbBits);
    DStatePtr->state = DInfo.newState + lowBits;
}

MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
{
    FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
    U32 const nbBits = DInfo.nbBits;
    BYTE const symbol = DInfo.symbol;
    size_t const lowBits = BIT_readBits(bitD, nbBits);

    DStatePtr->state = DInfo.newState + lowBits;
    return symbol;
}

/*! FSE_decodeSymbolFast() :
    unsafe, only works if no symbol has a probability > 50% */
MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
{
    FSE_decode_t const DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
    U32 const nbBits = DInfo.nbBits;
    BYTE const symbol = DInfo.symbol;
    size_t const lowBits = BIT_readBitsFast(bitD, nbBits);

    DStatePtr->state = DInfo.newState + lowBits;
    return symbol;
}

MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
{
    return DStatePtr->state == 0;
}



#ifndef FSE_COMMONDEFS_ONLY

/* **************************************************************
*  Tuning parameters
****************************************************************/
/*!MEMORY_USAGE :
*  Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
*  Increasing memory usage improves compression ratio
*  Reduced memory usage can improve speed, due to cache effect
*  Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
#ifndef FSE_MAX_MEMORY_USAGE
#  define FSE_MAX_MEMORY_USAGE 14
#endif
#ifndef FSE_DEFAULT_MEMORY_USAGE
#  define FSE_DEFAULT_MEMORY_USAGE 13
#endif

/*!FSE_MAX_SYMBOL_VALUE :
*  Maximum symbol value authorized.
*  Required for proper stack allocation */
#ifndef FSE_MAX_SYMBOL_VALUE
#  define FSE_MAX_SYMBOL_VALUE 255
#endif

/* **************************************************************
*  template functions type & suffix
****************************************************************/
#define FSE_FUNCTION_TYPE BYTE
#define FSE_FUNCTION_EXTENSION
#define FSE_DECODE_TYPE FSE_decode_t


#endif   /* !FSE_COMMONDEFS_ONLY */


/* ***************************************************************
*  Constants
*****************************************************************/
#define FSE_MAX_TABLELOG  (FSE_MAX_MEMORY_USAGE-2)
#define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
#define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
#define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
#define FSE_MIN_TABLELOG 5

#define FSE_TABLELOG_ABSOLUTE_MAX 15
#if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
#  error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
#endif

#define FSE_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3)


#endif /* FSE_STATIC_LINKING_ONLY */


#if defined (__cplusplus)
}
#endif
/**** ended inlining fse.h ****/
#define HUF_STATIC_LINKING_ONLY  /* HUF_TABLELOG_ABSOLUTEMAX */
/**** start inlining huf.h ****/
/* ******************************************************************
 * huff0 huffman codec,
 * part of Finite State Entropy library
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */

#if defined (__cplusplus)
extern "C" {
#endif

#ifndef HUF_H_298734234
#define HUF_H_298734234

/* *** Dependencies *** */
#include <stddef.h>    /* size_t */


/* *** library symbols visibility *** */
/* Note : when linking with -fvisibility=hidden on gcc, or by default on Visual,
 *        HUF symbols remain "private" (internal symbols for library only).
 *        Set macro FSE_DLL_EXPORT to 1 if you want HUF symbols visible on DLL interface */
#if defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1) && defined(__GNUC__) && (__GNUC__ >= 4)
#  define HUF_PUBLIC_API __attribute__ ((visibility ("default")))
#elif defined(FSE_DLL_EXPORT) && (FSE_DLL_EXPORT==1)   /* Visual expected */
#  define HUF_PUBLIC_API __declspec(dllexport)
#elif defined(FSE_DLL_IMPORT) && (FSE_DLL_IMPORT==1)
#  define HUF_PUBLIC_API __declspec(dllimport)  /* not required, just to generate faster code (saves a function pointer load from IAT and an indirect jump) */
#else
#  define HUF_PUBLIC_API
#endif


/* ========================== */
/* ***  simple functions  *** */
/* ========================== */

/** HUF_compress() :
 *  Compress content from buffer 'src', of size 'srcSize', into buffer 'dst'.
 * 'dst' buffer must be already allocated.
 *  Compression runs faster if `dstCapacity` >= HUF_compressBound(srcSize).
 * `srcSize` must be <= `HUF_BLOCKSIZE_MAX` == 128 KB.
 * @return : size of compressed data (<= `dstCapacity`).
 *  Special values : if return == 0, srcData is not compressible => Nothing is stored within dst !!!
 *                   if HUF_isError(return), compression failed (more details using HUF_getErrorName())
 */
HUF_PUBLIC_API size_t HUF_compress(void* dst, size_t dstCapacity,
                             const void* src, size_t srcSize);

/** HUF_decompress() :
 *  Decompress HUF data from buffer 'cSrc', of size 'cSrcSize',
 *  into already allocated buffer 'dst', of minimum size 'dstSize'.
 * `originalSize` : **must** be the ***exact*** size of original (uncompressed) data.
 *  Note : in contrast with FSE, HUF_decompress can regenerate
 *         RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data,
 *         because it knows size to regenerate (originalSize).
 * @return : size of regenerated data (== originalSize),
 *           or an error code, which can be tested using HUF_isError()
 */
HUF_PUBLIC_API size_t HUF_decompress(void* dst,  size_t originalSize,
                               const void* cSrc, size_t cSrcSize);


/* ***   Tool functions *** */
#define HUF_BLOCKSIZE_MAX (128 * 1024)                  /**< maximum input size for a single block compressed with HUF_compress */
HUF_PUBLIC_API size_t HUF_compressBound(size_t size);   /**< maximum compressed size (worst case) */

/* Error Management */
HUF_PUBLIC_API unsigned    HUF_isError(size_t code);       /**< tells if a return value is an error code */
HUF_PUBLIC_API const char* HUF_getErrorName(size_t code);  /**< provides error code string (useful for debugging) */


/* ***   Advanced function   *** */

/** HUF_compress2() :
 *  Same as HUF_compress(), but offers control over `maxSymbolValue` and `tableLog`.
 * `maxSymbolValue` must be <= HUF_SYMBOLVALUE_MAX .
 * `tableLog` must be `<= HUF_TABLELOG_MAX` . */
HUF_PUBLIC_API size_t HUF_compress2 (void* dst, size_t dstCapacity,
                               const void* src, size_t srcSize,
                               unsigned maxSymbolValue, unsigned tableLog);

/** HUF_compress4X_wksp() :
 *  Same as HUF_compress2(), but uses externally allocated `workSpace`.
 * `workspace` must have minimum alignment of 4, and be at least as large as HUF_WORKSPACE_SIZE */
#define HUF_WORKSPACE_SIZE ((6 << 10) + 256)
#define HUF_WORKSPACE_SIZE_U32 (HUF_WORKSPACE_SIZE / sizeof(U32))
HUF_PUBLIC_API size_t HUF_compress4X_wksp (void* dst, size_t dstCapacity,
                                     const void* src, size_t srcSize,
                                     unsigned maxSymbolValue, unsigned tableLog,
                                     void* workSpace, size_t wkspSize);

#endif   /* HUF_H_298734234 */

/* ******************************************************************
 *  WARNING !!
 *  The following section contains advanced and experimental definitions
 *  which shall never be used in the context of a dynamic library,
 *  because they are not guaranteed to remain stable in the future.
 *  Only consider them in association with static linking.
 * *****************************************************************/
#if defined(HUF_STATIC_LINKING_ONLY) && !defined(HUF_H_HUF_STATIC_LINKING_ONLY)
#define HUF_H_HUF_STATIC_LINKING_ONLY

/* *** Dependencies *** */
/**** skipping file: mem.h ****/


/* *** Constants *** */
#define HUF_TABLELOG_MAX      12      /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
#define HUF_TABLELOG_DEFAULT  11      /* default tableLog value when none specified */
#define HUF_SYMBOLVALUE_MAX  255

#define HUF_TABLELOG_ABSOLUTEMAX  15  /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
#if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX)
#  error "HUF_TABLELOG_MAX is too large !"
#endif


/* ****************************************
*  Static allocation
******************************************/
/* HUF buffer bounds */
#define HUF_CTABLEBOUND 129
#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8)   /* only true when incompressible is pre-filtered with fast heuristic */
#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size))   /* Macro version, useful for static allocation */

/* static allocation of HUF's Compression Table */
#define HUF_CTABLE_SIZE_U32(maxSymbolValue)   ((maxSymbolValue)+1)   /* Use tables of U32, for proper alignment */
#define HUF_CTABLE_SIZE(maxSymbolValue)       (HUF_CTABLE_SIZE_U32(maxSymbolValue) * sizeof(U32))
#define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \
    U32 name##hb[HUF_CTABLE_SIZE_U32(maxSymbolValue)]; \
    void* name##hv = &(name##hb); \
    HUF_CElt* name = (HUF_CElt*)(name##hv)   /* no final ; */

/* static allocation of HUF's DTable */
typedef U32 HUF_DTable;
#define HUF_DTABLE_SIZE(maxTableLog)   (1 + (1<<(maxTableLog)))
#define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \
        HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) }
#define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
        HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) }


/* ****************************************
*  Advanced decompression functions
******************************************/
size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< single-symbol decoder */
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< double-symbols decoder */
#endif

size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< decodes RLE and uncompressed */
size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< considers RLE and uncompressed as errors */
size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize); /**< considers RLE and uncompressed as errors */
size_t HUF_decompress4X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< single-symbol decoder */
size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);   /**< single-symbol decoder */
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< double-symbols decoder */
size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);   /**< double-symbols decoder */
#endif


/* ****************************************
 *  HUF detailed API
 * ****************************************/

/*! HUF_compress() does the following:
 *  1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h")
 *  2. (optional) refine tableLog using HUF_optimalTableLog()
 *  3. build Huffman table from count using HUF_buildCTable()
 *  4. save Huffman table to memory buffer using HUF_writeCTable()
 *  5. encode the data stream using HUF_compress4X_usingCTable()
 *
 *  The following API allows targeting specific sub-functions for advanced tasks.
 *  For example, it's possible to compress several blocks using the same 'CTable',
 *  or to save and regenerate 'CTable' using external methods.
 */
unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue);
typedef struct HUF_CElt_s HUF_CElt;   /* incomplete type */
size_t HUF_buildCTable (HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits);   /* @return : maxNbBits; CTable and count can overlap. In which case, CTable will overwrite count content */
size_t HUF_writeCTable (void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog);
size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable);
size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);
int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);

typedef enum {
   HUF_repeat_none,  /**< Cannot use the previous table */
   HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */
   HUF_repeat_valid  /**< Can use the previous table and it is assumed to be valid */
 } HUF_repeat;
/** HUF_compress4X_repeat() :
 *  Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
 *  If it uses hufTable it does not modify hufTable or repeat.
 *  If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
 *  If preferRepeat then the old table will always be used if valid. */
size_t HUF_compress4X_repeat(void* dst, size_t dstSize,
                       const void* src, size_t srcSize,
                       unsigned maxSymbolValue, unsigned tableLog,
                       void* workSpace, size_t wkspSize,    /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
                       HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2);

/** HUF_buildCTable_wksp() :
 *  Same as HUF_buildCTable(), but using externally allocated scratch buffer.
 * `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE.
 */
#define HUF_CTABLE_WORKSPACE_SIZE_U32 (2*HUF_SYMBOLVALUE_MAX +1 +1)
#define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned))
size_t HUF_buildCTable_wksp (HUF_CElt* tree,
                       const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,
                             void* workSpace, size_t wkspSize);

/*! HUF_readStats() :
 *  Read compact Huffman tree, saved by HUF_writeCTable().
 * `huffWeight` is destination buffer.
 * @return : size read from `src` , or an error Code .
 *  Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */
size_t HUF_readStats(BYTE* huffWeight, size_t hwSize,
                     U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,
                     const void* src, size_t srcSize);

/** HUF_readCTable() :
 *  Loading a CTable saved with HUF_writeCTable() */
size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned *hasZeroWeights);

/** HUF_getNbBits() :
 *  Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX
 *  Note 1 : is not inlined, as HUF_CElt definition is private
 *  Note 2 : const void* used, so that it can provide a statically allocated table as argument (which uses type U32) */
U32 HUF_getNbBits(const void* symbolTable, U32 symbolValue);

/*
 * HUF_decompress() does the following:
 * 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics
 * 2. build Huffman table from save, using HUF_readDTableX?()
 * 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable()
 */

/** HUF_selectDecoder() :
 *  Tells which decoder is likely to decode faster,
 *  based on a set of pre-computed metrics.
 * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
 *  Assumption : 0 < dstSize <= 128 KB */
U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize);

/**
 *  The minimum workspace size for the `workSpace` used in
 *  HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp().
 *
 *  The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when
 *  HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15.
 *  Buffer overflow errors may potentially occur if code modifications result in
 *  a required workspace size greater than that specified in the following
 *  macro.
 */
#define HUF_DECOMPRESS_WORKSPACE_SIZE (2 << 10)
#define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32))

#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_readDTableX1 (HUF_DTable* DTable, const void* src, size_t srcSize);
size_t HUF_readDTableX1_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize);
#endif
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_readDTableX2 (HUF_DTable* DTable, const void* src, size_t srcSize);
size_t HUF_readDTableX2_wksp (HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize);
#endif

size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_decompress4X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
#endif
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
#endif


/* ====================== */
/* single stream variants */
/* ====================== */

size_t HUF_compress1X (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog);
size_t HUF_compress1X_wksp (void* dst, size_t dstSize, const void* src, size_t srcSize, unsigned maxSymbolValue, unsigned tableLog, void* workSpace, size_t wkspSize);  /**< `workSpace` must be a table of at least HUF_WORKSPACE_SIZE_U32 unsigned */
size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable);
/** HUF_compress1X_repeat() :
 *  Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.
 *  If it uses hufTable it does not modify hufTable or repeat.
 *  If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.
 *  If preferRepeat then the old table will always be used if valid. */
size_t HUF_compress1X_repeat(void* dst, size_t dstSize,
                       const void* src, size_t srcSize,
                       unsigned maxSymbolValue, unsigned tableLog,
                       void* workSpace, size_t wkspSize,   /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */
                       HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2);

size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* single-symbol decoder */
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /* double-symbol decoder */
#endif

size_t HUF_decompress1X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
size_t HUF_decompress1X_DCtx_wksp (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);
#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_decompress1X1_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< single-symbol decoder */
size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);   /**< single-symbol decoder */
#endif
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress1X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);   /**< double-symbols decoder */
size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize);   /**< double-symbols decoder */
#endif

size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);   /**< automatic selection of sing or double symbol decoder, based on DTable */
#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_decompress1X1_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
#endif
#ifndef HUF_FORCE_DECOMPRESS_X1
size_t HUF_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable);
#endif

/* BMI2 variants.
 * If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.
 */
size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2);
#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2);
#endif
size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2);
size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2);

#endif /* HUF_STATIC_LINKING_ONLY */

#if defined (__cplusplus)
}
#endif
/**** ended inlining huf.h ****/


/*===   Version   ===*/
unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }


/*===   Error Management   ===*/
unsigned FSE_isError(size_t code) { return ERR_isError(code); }
const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }

unsigned HUF_isError(size_t code) { return ERR_isError(code); }
const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }


/*-**************************************************************
*  FSE NCount encoding-decoding
****************************************************************/
size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
                 const void* headerBuffer, size_t hbSize)
{
    const BYTE* const istart = (const BYTE*) headerBuffer;
    const BYTE* const iend = istart + hbSize;
    const BYTE* ip = istart;
    int nbBits;
    int remaining;
    int threshold;
    U32 bitStream;
    int bitCount;
    unsigned charnum = 0;
    int previous0 = 0;

    if (hbSize < 4) {
        /* This function only works when hbSize >= 4 */
        char buffer[4];
        memset(buffer, 0, sizeof(buffer));
        memcpy(buffer, headerBuffer, hbSize);
        {   size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
                                                    buffer, sizeof(buffer));
            if (FSE_isError(countSize)) return countSize;
            if (countSize > hbSize) return ERROR(corruption_detected);
            return countSize;
    }   }
    assert(hbSize >= 4);

    /* init */
    memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0]));   /* all symbols not present in NCount have a frequency of 0 */
    bitStream = MEM_readLE32(ip);
    nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG;   /* extract tableLog */
    if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
    bitStream >>= 4;
    bitCount = 4;
    *tableLogPtr = nbBits;
    remaining = (1<<nbBits)+1;
    threshold = 1<<nbBits;
    nbBits++;

    while ((remaining>1) & (charnum<=*maxSVPtr)) {
        if (previous0) {
            unsigned n0 = charnum;
            while ((bitStream & 0xFFFF) == 0xFFFF) {
                n0 += 24;
                if (ip < iend-5) {
                    ip += 2;
                    bitStream = MEM_readLE32(ip) >> bitCount;
                } else {
                    bitStream >>= 16;
                    bitCount   += 16;
            }   }
            while ((bitStream & 3) == 3) {
                n0 += 3;
                bitStream >>= 2;
                bitCount += 2;
            }
            n0 += bitStream & 3;
            bitCount += 2;
            if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
            while (charnum < n0) normalizedCounter[charnum++] = 0;
            if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
                assert((bitCount >> 3) <= 3); /* For first condition to work */
                ip += bitCount>>3;
                bitCount &= 7;
                bitStream = MEM_readLE32(ip) >> bitCount;
            } else {
                bitStream >>= 2;
        }   }
        {   int const max = (2*threshold-1) - remaining;
            int count;

            if ((bitStream & (threshold-1)) < (U32)max) {
                count = bitStream & (threshold-1);
                bitCount += nbBits-1;
            } else {
                count = bitStream & (2*threshold-1);
                if (count >= threshold) count -= max;
                bitCount += nbBits;
            }

            count--;   /* extra accuracy */
            remaining -= count < 0 ? -count : count;   /* -1 means +1 */
            normalizedCounter[charnum++] = (short)count;
            previous0 = !count;
            while (remaining < threshold) {
                nbBits--;
                threshold >>= 1;
            }

            if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
                ip += bitCount>>3;
                bitCount &= 7;
            } else {
                bitCount -= (int)(8 * (iend - 4 - ip));
                ip = iend - 4;
            }
            bitStream = MEM_readLE32(ip) >> (bitCount & 31);
    }   }   /* while ((remaining>1) & (charnum<=*maxSVPtr)) */
    if (remaining != 1) return ERROR(corruption_detected);
    if (bitCount > 32) return ERROR(corruption_detected);
    *maxSVPtr = charnum-1;

    ip += (bitCount+7)>>3;
    return ip-istart;
}


/*! HUF_readStats() :
    Read compact Huffman tree, saved by HUF_writeCTable().
    `huffWeight` is destination buffer.
    `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
    @return : size read from `src` , or an error Code .
    Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
*/
size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
                     U32* nbSymbolsPtr, U32* tableLogPtr,
                     const void* src, size_t srcSize)
{
    U32 weightTotal;
    const BYTE* ip = (const BYTE*) src;
    size_t iSize;
    size_t oSize;

    if (!srcSize) return ERROR(srcSize_wrong);
    iSize = ip[0];
    /* memset(huffWeight, 0, hwSize);   *//* is not necessary, even though some analyzer complain ... */

    if (iSize >= 128) {  /* special header */
        oSize = iSize - 127;
        iSize = ((oSize+1)/2);
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
        if (oSize >= hwSize) return ERROR(corruption_detected);
        ip += 1;
        {   U32 n;
            for (n=0; n<oSize; n+=2) {
                huffWeight[n]   = ip[n/2] >> 4;
                huffWeight[n+1] = ip[n/2] & 15;
    }   }   }
    else  {   /* header compressed with FSE (normal case) */
        FSE_DTable fseWorkspace[FSE_DTABLE_SIZE_U32(6)];  /* 6 is max possible tableLog for HUF header (maybe even 5, to be tested) */
        if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
        oSize = FSE_decompress_wksp(huffWeight, hwSize-1, ip+1, iSize, fseWorkspace, 6);   /* max (hwSize-1) values decoded, as last one is implied */
        if (FSE_isError(oSize)) return oSize;
    }

    /* collect weight stats */
    memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
    weightTotal = 0;
    {   U32 n; for (n=0; n<oSize; n++) {
            if (huffWeight[n] >= HUF_TABLELOG_MAX) return ERROR(corruption_detected);
            rankStats[huffWeight[n]]++;
            weightTotal += (1 << huffWeight[n]) >> 1;
    }   }
    if (weightTotal == 0) return ERROR(corruption_detected);

    /* get last non-null symbol weight (implied, total must be 2^n) */
    {   U32 const tableLog = BIT_highbit32(weightTotal) + 1;
        if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
        *tableLogPtr = tableLog;
        /* determine last weight */
        {   U32 const total = 1 << tableLog;
            U32 const rest = total - weightTotal;
            U32 const verif = 1 << BIT_highbit32(rest);
            U32 const lastWeight = BIT_highbit32(rest) + 1;
            if (verif != rest) return ERROR(corruption_detected);    /* last value must be a clean power of 2 */
            huffWeight[oSize] = (BYTE)lastWeight;
            rankStats[lastWeight]++;
    }   }

    /* check tree construction validity */
    if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected);   /* by construction : at least 2 elts of rank 1, must be even */

    /* results */
    *nbSymbolsPtr = (U32)(oSize+1);
    return iSize+1;
}
/**** ended inlining common/entropy_common.c ****/
/**** start inlining common/error_private.c ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

/* The purpose of this file is to have a single list of error strings embedded in binary */

/**** skipping file: error_private.h ****/

const char* ERR_getErrorString(ERR_enum code)
{
#ifdef ZSTD_STRIP_ERROR_STRINGS
    (void)code;
    return "Error strings stripped";
#else
    static const char* const notErrorCode = "Unspecified error code";
    switch( code )
    {
    case PREFIX(no_error): return "No error detected";
    case PREFIX(GENERIC):  return "Error (generic)";
    case PREFIX(prefix_unknown): return "Unknown frame descriptor";
    case PREFIX(version_unsupported): return "Version not supported";
    case PREFIX(frameParameter_unsupported): return "Unsupported frame parameter";
    case PREFIX(frameParameter_windowTooLarge): return "Frame requires too much memory for decoding";
    case PREFIX(corruption_detected): return "Corrupted block detected";
    case PREFIX(checksum_wrong): return "Restored data doesn't match checksum";
    case PREFIX(parameter_unsupported): return "Unsupported parameter";
    case PREFIX(parameter_outOfBound): return "Parameter is out of bound";
    case PREFIX(init_missing): return "Context should be init first";
    case PREFIX(memory_allocation): return "Allocation error : not enough memory";
    case PREFIX(workSpace_tooSmall): return "workSpace buffer is not large enough";
    case PREFIX(stage_wrong): return "Operation not authorized at current processing stage";
    case PREFIX(tableLog_tooLarge): return "tableLog requires too much memory : unsupported";
    case PREFIX(maxSymbolValue_tooLarge): return "Unsupported max Symbol Value : too large";
    case PREFIX(maxSymbolValue_tooSmall): return "Specified maxSymbolValue is too small";
    case PREFIX(dictionary_corrupted): return "Dictionary is corrupted";
    case PREFIX(dictionary_wrong): return "Dictionary mismatch";
    case PREFIX(dictionaryCreation_failed): return "Cannot create Dictionary from provided samples";
    case PREFIX(dstSize_tooSmall): return "Destination buffer is too small";
    case PREFIX(srcSize_wrong): return "Src size is incorrect";
    case PREFIX(dstBuffer_null): return "Operation on NULL destination buffer";
        /* following error codes are not stable and may be removed or changed in a future version */
    case PREFIX(frameIndex_tooLarge): return "Frame index is too large";
    case PREFIX(seekableIO): return "An I/O error occurred when reading/seeking";
    case PREFIX(dstBuffer_wrong): return "Destination buffer is wrong";
    case PREFIX(maxCode):
    default: return notErrorCode;
    }
#endif
}
/**** ended inlining common/error_private.c ****/
/**** start inlining common/fse_decompress.c ****/
/* ******************************************************************
 * FSE : Finite State Entropy decoder
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 *  You can contact the author at :
 *  - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */


/* **************************************************************
*  Includes
****************************************************************/
/**** skipping file: bitstream.h ****/
/**** skipping file: compiler.h ****/
#define FSE_STATIC_LINKING_ONLY
/**** skipping file: fse.h ****/
/**** skipping file: error_private.h ****/


/* **************************************************************
*  Error Management
****************************************************************/
#define FSE_isError ERR_isError
#define FSE_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)   /* use only *after* variable declarations */


/* **************************************************************
*  Templates
****************************************************************/
/*
  designed to be included
  for type-specific functions (template emulation in C)
  Objective is to write these functions only once, for improved maintenance
*/

/* safety checks */
#ifndef FSE_FUNCTION_EXTENSION
#  error "FSE_FUNCTION_EXTENSION must be defined"
#endif
#ifndef FSE_FUNCTION_TYPE
#  error "FSE_FUNCTION_TYPE must be defined"
#endif

/* Function names */
#define FSE_CAT(X,Y) X##Y
#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)


/* Function templates */
FSE_DTable* FSE_createDTable (unsigned tableLog)
{
    if (tableLog > FSE_TABLELOG_ABSOLUTE_MAX) tableLog = FSE_TABLELOG_ABSOLUTE_MAX;
    return (FSE_DTable*)malloc( FSE_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
}

void FSE_freeDTable (FSE_DTable* dt)
{
    free(dt);
}

size_t FSE_buildDTable(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
{
    void* const tdPtr = dt+1;   /* because *dt is unsigned, 32-bits aligned on 32-bits */
    FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
    U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];

    U32 const maxSV1 = maxSymbolValue + 1;
    U32 const tableSize = 1 << tableLog;
    U32 highThreshold = tableSize-1;

    /* Sanity Checks */
    if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
    if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);

    /* Init, lay down lowprob symbols */
    {   FSE_DTableHeader DTableH;
        DTableH.tableLog = (U16)tableLog;
        DTableH.fastMode = 1;
        {   S16 const largeLimit= (S16)(1 << (tableLog-1));
            U32 s;
            for (s=0; s<maxSV1; s++) {
                if (normalizedCounter[s]==-1) {
                    tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
                    symbolNext[s] = 1;
                } else {
                    if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
                    symbolNext[s] = normalizedCounter[s];
        }   }   }
        memcpy(dt, &DTableH, sizeof(DTableH));
    }

    /* Spread symbols */
    {   U32 const tableMask = tableSize-1;
        U32 const step = FSE_TABLESTEP(tableSize);
        U32 s, position = 0;
        for (s=0; s<maxSV1; s++) {
            int i;
            for (i=0; i<normalizedCounter[s]; i++) {
                tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
                position = (position + step) & tableMask;
                while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
        }   }
        if (position!=0) return ERROR(GENERIC);   /* position must reach all cells once, otherwise normalizedCounter is incorrect */
    }

    /* Build Decoding table */
    {   U32 u;
        for (u=0; u<tableSize; u++) {
            FSE_FUNCTION_TYPE const symbol = (FSE_FUNCTION_TYPE)(tableDecode[u].symbol);
            U32 const nextState = symbolNext[symbol]++;
            tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
            tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
    }   }

    return 0;
}


#ifndef FSE_COMMONDEFS_ONLY

/*-*******************************************************
*  Decompression (Byte symbols)
*********************************************************/
size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
{
    void* ptr = dt;
    FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
    void* dPtr = dt + 1;
    FSE_decode_t* const cell = (FSE_decode_t*)dPtr;

    DTableH->tableLog = 0;
    DTableH->fastMode = 0;

    cell->newState = 0;
    cell->symbol = symbolValue;
    cell->nbBits = 0;

    return 0;
}


size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
{
    void* ptr = dt;
    FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
    void* dPtr = dt + 1;
    FSE_decode_t* const dinfo = (FSE_decode_t*)dPtr;
    const unsigned tableSize = 1 << nbBits;
    const unsigned tableMask = tableSize - 1;
    const unsigned maxSV1 = tableMask+1;
    unsigned s;

    /* Sanity checks */
    if (nbBits < 1) return ERROR(GENERIC);         /* min size */

    /* Build Decoding Table */
    DTableH->tableLog = (U16)nbBits;
    DTableH->fastMode = 1;
    for (s=0; s<maxSV1; s++) {
        dinfo[s].newState = 0;
        dinfo[s].symbol = (BYTE)s;
        dinfo[s].nbBits = (BYTE)nbBits;
    }

    return 0;
}

FORCE_INLINE_TEMPLATE size_t FSE_decompress_usingDTable_generic(
          void* dst, size_t maxDstSize,
    const void* cSrc, size_t cSrcSize,
    const FSE_DTable* dt, const unsigned fast)
{
    BYTE* const ostart = (BYTE*) dst;
    BYTE* op = ostart;
    BYTE* const omax = op + maxDstSize;
    BYTE* const olimit = omax-3;

    BIT_DStream_t bitD;
    FSE_DState_t state1;
    FSE_DState_t state2;

    /* Init */
    CHECK_F(BIT_initDStream(&bitD, cSrc, cSrcSize));

    FSE_initDState(&state1, &bitD, dt);
    FSE_initDState(&state2, &bitD, dt);

#define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)

    /* 4 symbols per loop */
    for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) & (op<olimit) ; op+=4) {
        op[0] = FSE_GETSYMBOL(&state1);

        if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
            BIT_reloadDStream(&bitD);

        op[1] = FSE_GETSYMBOL(&state2);

        if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
            { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }

        op[2] = FSE_GETSYMBOL(&state1);

        if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8)    /* This test must be static */
            BIT_reloadDStream(&bitD);

        op[3] = FSE_GETSYMBOL(&state2);
    }

    /* tail */
    /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
    while (1) {
        if (op>(omax-2)) return ERROR(dstSize_tooSmall);
        *op++ = FSE_GETSYMBOL(&state1);
        if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
            *op++ = FSE_GETSYMBOL(&state2);
            break;
        }

        if (op>(omax-2)) return ERROR(dstSize_tooSmall);
        *op++ = FSE_GETSYMBOL(&state2);
        if (BIT_reloadDStream(&bitD)==BIT_DStream_overflow) {
            *op++ = FSE_GETSYMBOL(&state1);
            break;
    }   }

    return op-ostart;
}


size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
                            const void* cSrc, size_t cSrcSize,
                            const FSE_DTable* dt)
{
    const void* ptr = dt;
    const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)ptr;
    const U32 fastMode = DTableH->fastMode;

    /* select fast mode (static) */
    if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
    return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
}


size_t FSE_decompress_wksp(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, FSE_DTable* workSpace, unsigned maxLog)
{
    const BYTE* const istart = (const BYTE*)cSrc;
    const BYTE* ip = istart;
    short counting[FSE_MAX_SYMBOL_VALUE+1];
    unsigned tableLog;
    unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;

    /* normal FSE decoding mode */
    size_t const NCountLength = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
    if (FSE_isError(NCountLength)) return NCountLength;
    /* if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong); */  /* too small input size; supposed to be already checked in NCountLength, only remaining case : NCountLength==cSrcSize */
    if (tableLog > maxLog) return ERROR(tableLog_tooLarge);
    ip += NCountLength;
    cSrcSize -= NCountLength;

    CHECK_F( FSE_buildDTable (workSpace, counting, maxSymbolValue, tableLog) );

    return FSE_decompress_usingDTable (dst, dstCapacity, ip, cSrcSize, workSpace);   /* always return, even if it is an error code */
}


typedef FSE_DTable DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];

size_t FSE_decompress(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize)
{
    DTable_max_t dt;   /* Static analyzer seems unable to understand this table will be properly initialized later */
    return FSE_decompress_wksp(dst, dstCapacity, cSrc, cSrcSize, dt, FSE_MAX_TABLELOG);
}



#endif   /* FSE_COMMONDEFS_ONLY */
/**** ended inlining common/fse_decompress.c ****/
/**** start inlining common/zstd_common.c ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */



/*-*************************************
*  Dependencies
***************************************/
/**** skipping file: error_private.h ****/
/**** start inlining zstd_internal.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_CCOMMON_H_MODULE
#define ZSTD_CCOMMON_H_MODULE

/* this module contains definitions which must be identical
 * across compression, decompression and dictBuilder.
 * It also contains a few functions useful to at least 2 of them
 * and which benefit from being inlined */

/*-*************************************
*  Dependencies
***************************************/
#ifdef __aarch64__
#include <arm_neon.h>
#endif
/**** skipping file: compiler.h ****/
/**** skipping file: mem.h ****/
/**** skipping file: debug.h ****/
/**** skipping file: error_private.h ****/
#define ZSTD_STATIC_LINKING_ONLY
/**** start inlining ../zstd.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */
#if defined (__cplusplus)
extern "C" {
#endif

#ifndef ZSTD_H_235446
#define ZSTD_H_235446

/* ======   Dependency   ======*/
#include <limits.h>   /* INT_MAX */
#include <stddef.h>   /* size_t */


/* =====   ZSTDLIB_API : control library symbols visibility   ===== */
#ifndef ZSTDLIB_VISIBILITY
#  if defined(__GNUC__) && (__GNUC__ >= 4)
#    define ZSTDLIB_VISIBILITY __attribute__ ((visibility ("default")))
#  else
#    define ZSTDLIB_VISIBILITY
#  endif
#endif
#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
#  define ZSTDLIB_API __declspec(dllexport) ZSTDLIB_VISIBILITY
#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
#  define ZSTDLIB_API __declspec(dllimport) ZSTDLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
#else
#  define ZSTDLIB_API ZSTDLIB_VISIBILITY
#endif


/*******************************************************************************
  Introduction

  zstd, short for Zstandard, is a fast lossless compression algorithm, targeting
  real-time compression scenarios at zlib-level and better compression ratios.
  The zstd compression library provides in-memory compression and decompression
  functions.

  The library supports regular compression levels from 1 up to ZSTD_maxCLevel(),
  which is currently 22. Levels >= 20, labeled `--ultra`, should be used with
  caution, as they require more memory. The library also offers negative
  compression levels, which extend the range of speed vs. ratio preferences.
  The lower the level, the faster the speed (at the cost of compression).

  Compression can be done in:
    - a single step (described as Simple API)
    - a single step, reusing a context (described as Explicit context)
    - unbounded multiple steps (described as Streaming compression)

  The compression ratio achievable on small data can be highly improved using
  a dictionary. Dictionary compression can be performed in:
    - a single step (described as Simple dictionary API)
    - a single step, reusing a dictionary (described as Bulk-processing
      dictionary API)

  Advanced experimental functions can be accessed using
  `#define ZSTD_STATIC_LINKING_ONLY` before including zstd.h.

  Advanced experimental APIs should never be used with a dynamically-linked
  library. They are not "stable"; their definitions or signatures may change in
  the future. Only static linking is allowed.
*******************************************************************************/

/*------   Version   ------*/
#define ZSTD_VERSION_MAJOR    1
#define ZSTD_VERSION_MINOR    4
#define ZSTD_VERSION_RELEASE  5

#define ZSTD_VERSION_NUMBER  (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE)
ZSTDLIB_API unsigned ZSTD_versionNumber(void);   /**< to check runtime library version */

#define ZSTD_LIB_VERSION ZSTD_VERSION_MAJOR.ZSTD_VERSION_MINOR.ZSTD_VERSION_RELEASE
#define ZSTD_QUOTE(str) #str
#define ZSTD_EXPAND_AND_QUOTE(str) ZSTD_QUOTE(str)
#define ZSTD_VERSION_STRING ZSTD_EXPAND_AND_QUOTE(ZSTD_LIB_VERSION)
ZSTDLIB_API const char* ZSTD_versionString(void);   /* requires v1.3.0+ */

/* *************************************
 *  Default constant
 ***************************************/
#ifndef ZSTD_CLEVEL_DEFAULT
#  define ZSTD_CLEVEL_DEFAULT 3
#endif

/* *************************************
 *  Constants
 ***************************************/

/* All magic numbers are supposed read/written to/from files/memory using little-endian convention */
#define ZSTD_MAGICNUMBER            0xFD2FB528    /* valid since v0.8.0 */
#define ZSTD_MAGIC_DICTIONARY       0xEC30A437    /* valid since v0.7.0 */
#define ZSTD_MAGIC_SKIPPABLE_START  0x184D2A50    /* all 16 values, from 0x184D2A50 to 0x184D2A5F, signal the beginning of a skippable frame */
#define ZSTD_MAGIC_SKIPPABLE_MASK   0xFFFFFFF0

#define ZSTD_BLOCKSIZELOG_MAX  17
#define ZSTD_BLOCKSIZE_MAX     (1<<ZSTD_BLOCKSIZELOG_MAX)



/***************************************
*  Simple API
***************************************/
/*! ZSTD_compress() :
 *  Compresses `src` content as a single zstd compressed frame into already allocated `dst`.
 *  Hint : compression runs faster if `dstCapacity` >=  `ZSTD_compressBound(srcSize)`.
 *  @return : compressed size written into `dst` (<= `dstCapacity),
 *            or an error code if it fails (which can be tested using ZSTD_isError()). */
ZSTDLIB_API size_t ZSTD_compress( void* dst, size_t dstCapacity,
                            const void* src, size_t srcSize,
                                  int compressionLevel);

/*! ZSTD_decompress() :
 *  `compressedSize` : must be the _exact_ size of some number of compressed and/or skippable frames.
 *  `dstCapacity` is an upper bound of originalSize to regenerate.
 *  If user cannot imply a maximum upper bound, it's better to use streaming mode to decompress data.
 *  @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
 *            or an errorCode if it fails (which can be tested using ZSTD_isError()). */
ZSTDLIB_API size_t ZSTD_decompress( void* dst, size_t dstCapacity,
                              const void* src, size_t compressedSize);

/*! ZSTD_getFrameContentSize() : requires v1.3.0+
 *  `src` should point to the start of a ZSTD encoded frame.
 *  `srcSize` must be at least as large as the frame header.
 *            hint : any size >= `ZSTD_frameHeaderSize_max` is large enough.
 *  @return : - decompressed size of `src` frame content, if known
 *            - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
 *            - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small)
 *   note 1 : a 0 return value means the frame is valid but "empty".
 *   note 2 : decompressed size is an optional field, it may not be present, typically in streaming mode.
 *            When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
 *            In which case, it's necessary to use streaming mode to decompress data.
 *            Optionally, application can rely on some implicit limit,
 *            as ZSTD_decompress() only needs an upper bound of decompressed size.
 *            (For example, data could be necessarily cut into blocks <= 16 KB).
 *   note 3 : decompressed size is always present when compression is completed using single-pass functions,
 *            such as ZSTD_compress(), ZSTD_compressCCtx() ZSTD_compress_usingDict() or ZSTD_compress_usingCDict().
 *   note 4 : decompressed size can be very large (64-bits value),
 *            potentially larger than what local system can handle as a single memory segment.
 *            In which case, it's necessary to use streaming mode to decompress data.
 *   note 5 : If source is untrusted, decompressed size could be wrong or intentionally modified.
 *            Always ensure return value fits within application's authorized limits.
 *            Each application can set its own limits.
 *   note 6 : This function replaces ZSTD_getDecompressedSize() */
#define ZSTD_CONTENTSIZE_UNKNOWN (0ULL - 1)
#define ZSTD_CONTENTSIZE_ERROR   (0ULL - 2)
ZSTDLIB_API unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize);

/*! ZSTD_getDecompressedSize() :
 *  NOTE: This function is now obsolete, in favor of ZSTD_getFrameContentSize().
 *  Both functions work the same way, but ZSTD_getDecompressedSize() blends
 *  "empty", "unknown" and "error" results to the same return value (0),
 *  while ZSTD_getFrameContentSize() gives them separate return values.
 * @return : decompressed size of `src` frame content _if known and not empty_, 0 otherwise. */
ZSTDLIB_API unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize);

/*! ZSTD_findFrameCompressedSize() :
 * `src` should point to the start of a ZSTD frame or skippable frame.
 * `srcSize` must be >= first frame size
 * @return : the compressed size of the first frame starting at `src`,
 *           suitable to pass as `srcSize` to `ZSTD_decompress` or similar,
 *        or an error code if input is invalid */
ZSTDLIB_API size_t ZSTD_findFrameCompressedSize(const void* src, size_t srcSize);


/*======  Helper functions  ======*/
#define ZSTD_COMPRESSBOUND(srcSize)   ((srcSize) + ((srcSize)>>8) + (((srcSize) < (128<<10)) ? (((128<<10) - (srcSize)) >> 11) /* margin, from 64 to 0 */ : 0))  /* this formula ensures that bound(A) + bound(B) <= bound(A+B) as long as A and B >= 128 KB */
ZSTDLIB_API size_t      ZSTD_compressBound(size_t srcSize); /*!< maximum compressed size in worst case single-pass scenario */
ZSTDLIB_API unsigned    ZSTD_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
ZSTDLIB_API const char* ZSTD_getErrorName(size_t code);     /*!< provides readable string from an error code */
ZSTDLIB_API int         ZSTD_minCLevel(void);               /*!< minimum negative compression level allowed */
ZSTDLIB_API int         ZSTD_maxCLevel(void);               /*!< maximum compression level available */


/***************************************
*  Explicit context
***************************************/
/*= Compression context
 *  When compressing many times,
 *  it is recommended to allocate a context just once,
 *  and re-use it for each successive compression operation.
 *  This will make workload friendlier for system's memory.
 *  Note : re-using context is just a speed / resource optimization.
 *         It doesn't change the compression ratio, which remains identical.
 *  Note 2 : In multi-threaded environments,
 *         use one different context per thread for parallel execution.
 */
typedef struct ZSTD_CCtx_s ZSTD_CCtx;
ZSTDLIB_API ZSTD_CCtx* ZSTD_createCCtx(void);
ZSTDLIB_API size_t     ZSTD_freeCCtx(ZSTD_CCtx* cctx);

/*! ZSTD_compressCCtx() :
 *  Same as ZSTD_compress(), using an explicit ZSTD_CCtx.
 *  Important : in order to behave similarly to `ZSTD_compress()`,
 *  this function compresses at requested compression level,
 *  __ignoring any other parameter__ .
 *  If any advanced parameter was set using the advanced API,
 *  they will all be reset. Only `compressionLevel` remains.
 */
ZSTDLIB_API size_t ZSTD_compressCCtx(ZSTD_CCtx* cctx,
                                     void* dst, size_t dstCapacity,
                               const void* src, size_t srcSize,
                                     int compressionLevel);

/*= Decompression context
 *  When decompressing many times,
 *  it is recommended to allocate a context only once,
 *  and re-use it for each successive compression operation.
 *  This will make workload friendlier for system's memory.
 *  Use one context per thread for parallel execution. */
typedef struct ZSTD_DCtx_s ZSTD_DCtx;
ZSTDLIB_API ZSTD_DCtx* ZSTD_createDCtx(void);
ZSTDLIB_API size_t     ZSTD_freeDCtx(ZSTD_DCtx* dctx);

/*! ZSTD_decompressDCtx() :
 *  Same as ZSTD_decompress(),
 *  requires an allocated ZSTD_DCtx.
 *  Compatible with sticky parameters.
 */
ZSTDLIB_API size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx,
                                       void* dst, size_t dstCapacity,
                                 const void* src, size_t srcSize);


/***************************************
*  Advanced compression API
***************************************/

/* API design :
 *   Parameters are pushed one by one into an existing context,
 *   using ZSTD_CCtx_set*() functions.
 *   Pushed parameters are sticky : they are valid for next compressed frame, and any subsequent frame.
 *   "sticky" parameters are applicable to `ZSTD_compress2()` and `ZSTD_compressStream*()` !
 *   __They do not apply to "simple" one-shot variants such as ZSTD_compressCCtx()__ .
 *
 *   It's possible to reset all parameters to "default" using ZSTD_CCtx_reset().
 *
 *   This API supercedes all other "advanced" API entry points in the experimental section.
 *   In the future, we expect to remove from experimental API entry points which are redundant with this API.
 */


/* Compression strategies, listed from fastest to strongest */
typedef enum { ZSTD_fast=1,
               ZSTD_dfast=2,
               ZSTD_greedy=3,
               ZSTD_lazy=4,
               ZSTD_lazy2=5,
               ZSTD_btlazy2=6,
               ZSTD_btopt=7,
               ZSTD_btultra=8,
               ZSTD_btultra2=9
               /* note : new strategies _might_ be added in the future.
                         Only the order (from fast to strong) is guaranteed */
} ZSTD_strategy;


typedef enum {

    /* compression parameters
     * Note: When compressing with a ZSTD_CDict these parameters are superseded
     * by the parameters used to construct the ZSTD_CDict.
     * See ZSTD_CCtx_refCDict() for more info (superseded-by-cdict). */
    ZSTD_c_compressionLevel=100, /* Set compression parameters according to pre-defined cLevel table.
                              * Note that exact compression parameters are dynamically determined,
                              * depending on both compression level and srcSize (when known).
                              * Default level is ZSTD_CLEVEL_DEFAULT==3.
                              * Special: value 0 means default, which is controlled by ZSTD_CLEVEL_DEFAULT.
                              * Note 1 : it's possible to pass a negative compression level.
                              * Note 2 : setting a level does not automatically set all other compression parameters
                              *   to default. Setting this will however eventually dynamically impact the compression
                              *   parameters which have not been manually set. The manually set
                              *   ones will 'stick'. */
    /* Advanced compression parameters :
     * It's possible to pin down compression parameters to some specific values.
     * In which case, these values are no longer dynamically selected by the compressor */
    ZSTD_c_windowLog=101,    /* Maximum allowed back-reference distance, expressed as power of 2.
                              * This will set a memory budget for streaming decompression,
                              * with larger values requiring more memory
                              * and typically compressing more.
                              * Must be clamped between ZSTD_WINDOWLOG_MIN and ZSTD_WINDOWLOG_MAX.
                              * Special: value 0 means "use default windowLog".
                              * Note: Using a windowLog greater than ZSTD_WINDOWLOG_LIMIT_DEFAULT
                              *       requires explicitly allowing such size at streaming decompression stage. */
    ZSTD_c_hashLog=102,      /* Size of the initial probe table, as a power of 2.
                              * Resulting memory usage is (1 << (hashLog+2)).
                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX.
                              * Larger tables improve compression ratio of strategies <= dFast,
                              * and improve speed of strategies > dFast.
                              * Special: value 0 means "use default hashLog". */
    ZSTD_c_chainLog=103,     /* Size of the multi-probe search table, as a power of 2.
                              * Resulting memory usage is (1 << (chainLog+2)).
                              * Must be clamped between ZSTD_CHAINLOG_MIN and ZSTD_CHAINLOG_MAX.
                              * Larger tables result in better and slower compression.
                              * This parameter is useless for "fast" strategy.
                              * It's still useful when using "dfast" strategy,
                              * in which case it defines a secondary probe table.
                              * Special: value 0 means "use default chainLog". */
    ZSTD_c_searchLog=104,    /* Number of search attempts, as a power of 2.
                              * More attempts result in better and slower compression.
                              * This parameter is useless for "fast" and "dFast" strategies.
                              * Special: value 0 means "use default searchLog". */
    ZSTD_c_minMatch=105,     /* Minimum size of searched matches.
                              * Note that Zstandard can still find matches of smaller size,
                              * it just tweaks its search algorithm to look for this size and larger.
                              * Larger values increase compression and decompression speed, but decrease ratio.
                              * Must be clamped between ZSTD_MINMATCH_MIN and ZSTD_MINMATCH_MAX.
                              * Note that currently, for all strategies < btopt, effective minimum is 4.
                              *                    , for all strategies > fast, effective maximum is 6.
                              * Special: value 0 means "use default minMatchLength". */
    ZSTD_c_targetLength=106, /* Impact of this field depends on strategy.
                              * For strategies btopt, btultra & btultra2:
                              *     Length of Match considered "good enough" to stop search.
                              *     Larger values make compression stronger, and slower.
                              * For strategy fast:
                              *     Distance between match sampling.
                              *     Larger values make compression faster, and weaker.
                              * Special: value 0 means "use default targetLength". */
    ZSTD_c_strategy=107,     /* See ZSTD_strategy enum definition.
                              * The higher the value of selected strategy, the more complex it is,
                              * resulting in stronger and slower compression.
                              * Special: value 0 means "use default strategy". */

    /* LDM mode parameters */
    ZSTD_c_enableLongDistanceMatching=160, /* Enable long distance matching.
                                     * This parameter is designed to improve compression ratio
                                     * for large inputs, by finding large matches at long distance.
                                     * It increases memory usage and window size.
                                     * Note: enabling this parameter increases default ZSTD_c_windowLog to 128 MB
                                     * except when expressly set to a different value. */
    ZSTD_c_ldmHashLog=161,   /* Size of the table for long distance matching, as a power of 2.
                              * Larger values increase memory usage and compression ratio,
                              * but decrease compression speed.
                              * Must be clamped between ZSTD_HASHLOG_MIN and ZSTD_HASHLOG_MAX
                              * default: windowlog - 7.
                              * Special: value 0 means "automatically determine hashlog". */
    ZSTD_c_ldmMinMatch=162,  /* Minimum match size for long distance matcher.
                              * Larger/too small values usually decrease compression ratio.
                              * Must be clamped between ZSTD_LDM_MINMATCH_MIN and ZSTD_LDM_MINMATCH_MAX.
                              * Special: value 0 means "use default value" (default: 64). */
    ZSTD_c_ldmBucketSizeLog=163, /* Log size of each bucket in the LDM hash table for collision resolution.
                              * Larger values improve collision resolution but decrease compression speed.
                              * The maximum value is ZSTD_LDM_BUCKETSIZELOG_MAX.
                              * Special: value 0 means "use default value" (default: 3). */
    ZSTD_c_ldmHashRateLog=164, /* Frequency of inserting/looking up entries into the LDM hash table.
                              * Must be clamped between 0 and (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN).
                              * Default is MAX(0, (windowLog - ldmHashLog)), optimizing hash table usage.
                              * Larger values improve compression speed.
                              * Deviating far from default value will likely result in a compression ratio decrease.
                              * Special: value 0 means "automatically determine hashRateLog". */

    /* frame parameters */
    ZSTD_c_contentSizeFlag=200, /* Content size will be written into frame header _whenever known_ (default:1)
                              * Content size must be known at the beginning of compression.
                              * This is automatically the case when using ZSTD_compress2(),
                              * For streaming scenarios, content size must be provided with ZSTD_CCtx_setPledgedSrcSize() */
    ZSTD_c_checksumFlag=201, /* A 32-bits checksum of content is written at end of frame (default:0) */
    ZSTD_c_dictIDFlag=202,   /* When applicable, dictionary's ID is written into frame header (default:1) */

    /* multi-threading parameters */
    /* These parameters are only useful if multi-threading is enabled (compiled with build macro ZSTD_MULTITHREAD).
     * They return an error otherwise. */
    ZSTD_c_nbWorkers=400,    /* Select how many threads will be spawned to compress in parallel.
                              * When nbWorkers >= 1, triggers asynchronous mode when used with ZSTD_compressStream*() :
                              * ZSTD_compressStream*() consumes input and flush output if possible, but immediately gives back control to caller,
                              * while compression work is performed in parallel, within worker threads.
                              * (note : a strong exception to this rule is when first invocation of ZSTD_compressStream2() sets ZSTD_e_end :
                              *  in which case, ZSTD_compressStream2() delegates to ZSTD_compress2(), which is always a blocking call).
                              * More workers improve speed, but also increase memory usage.
                              * Default value is `0`, aka "single-threaded mode" : no worker is spawned, compression is performed inside Caller's thread, all invocations are blocking */
    ZSTD_c_jobSize=401,      /* Size of a compression job. This value is enforced only when nbWorkers >= 1.
                              * Each compression job is completed in parallel, so this value can indirectly impact the nb of active threads.
                              * 0 means default, which is dynamically determined based on compression parameters.
                              * Job size must be a minimum of overlap size, or 1 MB, whichever is largest.
                              * The minimum size is automatically and transparently enforced. */
    ZSTD_c_overlapLog=402,   /* Control the overlap size, as a fraction of window size.
                              * The overlap size is an amount of data reloaded from previous job at the beginning of a new job.
                              * It helps preserve compression ratio, while each job is compressed in parallel.
                              * This value is enforced only when nbWorkers >= 1.
                              * Larger values increase compression ratio, but decrease speed.
                              * Possible values range from 0 to 9 :
                              * - 0 means "default" : value will be determined by the library, depending on strategy
                              * - 1 means "no overlap"
                              * - 9 means "full overlap", using a full window size.
                              * Each intermediate rank increases/decreases load size by a factor 2 :
                              * 9: full window;  8: w/2;  7: w/4;  6: w/8;  5:w/16;  4: w/32;  3:w/64;  2:w/128;  1:no overlap;  0:default
                              * default value varies between 6 and 9, depending on strategy */

    /* note : additional experimental parameters are also available
     * within the experimental section of the API.
     * At the time of this writing, they include :
     * ZSTD_c_rsyncable
     * ZSTD_c_format
     * ZSTD_c_forceMaxWindow
     * ZSTD_c_forceAttachDict
     * ZSTD_c_literalCompressionMode
     * ZSTD_c_targetCBlockSize
     * ZSTD_c_srcSizeHint
     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
     * note : never ever use experimentalParam? names directly;
     *        also, the enums values themselves are unstable and can still change.
     */
     ZSTD_c_experimentalParam1=500,
     ZSTD_c_experimentalParam2=10,
     ZSTD_c_experimentalParam3=1000,
     ZSTD_c_experimentalParam4=1001,
     ZSTD_c_experimentalParam5=1002,
     ZSTD_c_experimentalParam6=1003,
     ZSTD_c_experimentalParam7=1004
} ZSTD_cParameter;

typedef struct {
    size_t error;
    int lowerBound;
    int upperBound;
} ZSTD_bounds;

/*! ZSTD_cParam_getBounds() :
 *  All parameters must belong to an interval with lower and upper bounds,
 *  otherwise they will either trigger an error or be automatically clamped.
 * @return : a structure, ZSTD_bounds, which contains
 *         - an error status field, which must be tested using ZSTD_isError()
 *         - lower and upper bounds, both inclusive
 */
ZSTDLIB_API ZSTD_bounds ZSTD_cParam_getBounds(ZSTD_cParameter cParam);

/*! ZSTD_CCtx_setParameter() :
 *  Set one compression parameter, selected by enum ZSTD_cParameter.
 *  All parameters have valid bounds. Bounds can be queried using ZSTD_cParam_getBounds().
 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
 *  Setting a parameter is generally only possible during frame initialization (before starting compression).
 *  Exception : when using multi-threading mode (nbWorkers >= 1),
 *              the following parameters can be updated _during_ compression (within same frame):
 *              => compressionLevel, hashLog, chainLog, searchLog, minMatch, targetLength and strategy.
 *              new parameters will be active for next job only (after a flush()).
 * @return : an error code (which can be tested using ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_CCtx_setParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int value);

/*! ZSTD_CCtx_setPledgedSrcSize() :
 *  Total input data size to be compressed as a single frame.
 *  Value will be written in frame header, unless if explicitly forbidden using ZSTD_c_contentSizeFlag.
 *  This value will also be controlled at end of frame, and trigger an error if not respected.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Note 1 : pledgedSrcSize==0 actually means zero, aka an empty frame.
 *           In order to mean "unknown content size", pass constant ZSTD_CONTENTSIZE_UNKNOWN.
 *           ZSTD_CONTENTSIZE_UNKNOWN is default value for any new frame.
 *  Note 2 : pledgedSrcSize is only valid once, for the next frame.
 *           It's discarded at the end of the frame, and replaced by ZSTD_CONTENTSIZE_UNKNOWN.
 *  Note 3 : Whenever all input data is provided and consumed in a single round,
 *           for example with ZSTD_compress2(),
 *           or invoking immediately ZSTD_compressStream2(,,,ZSTD_e_end),
 *           this value is automatically overridden by srcSize instead.
 */
ZSTDLIB_API size_t ZSTD_CCtx_setPledgedSrcSize(ZSTD_CCtx* cctx, unsigned long long pledgedSrcSize);

typedef enum {
    ZSTD_reset_session_only = 1,
    ZSTD_reset_parameters = 2,
    ZSTD_reset_session_and_parameters = 3
} ZSTD_ResetDirective;

/*! ZSTD_CCtx_reset() :
 *  There are 2 different things that can be reset, independently or jointly :
 *  - The session : will stop compressing current frame, and make CCtx ready to start a new one.
 *                  Useful after an error, or to interrupt any ongoing compression.
 *                  Any internal data not yet flushed is cancelled.
 *                  Compression parameters and dictionary remain unchanged.
 *                  They will be used to compress next frame.
 *                  Resetting session never fails.
 *  - The parameters : changes all parameters back to "default".
 *                  This removes any reference to any dictionary too.
 *                  Parameters can only be changed between 2 sessions (i.e. no compression is currently ongoing)
 *                  otherwise the reset fails, and function returns an error value (which can be tested using ZSTD_isError())
 *  - Both : similar to resetting the session, followed by resetting parameters.
 */
ZSTDLIB_API size_t ZSTD_CCtx_reset(ZSTD_CCtx* cctx, ZSTD_ResetDirective reset);

/*! ZSTD_compress2() :
 *  Behave the same as ZSTD_compressCCtx(), but compression parameters are set using the advanced API.
 *  ZSTD_compress2() always starts a new frame.
 *  Should cctx hold data from a previously unfinished frame, everything about it is forgotten.
 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
 *  - The function is always blocking, returns when compression is completed.
 *  Hint : compression runs faster if `dstCapacity` >=  `ZSTD_compressBound(srcSize)`.
 * @return : compressed size written into `dst` (<= `dstCapacity),
 *           or an error code if it fails (which can be tested using ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_compress2( ZSTD_CCtx* cctx,
                                   void* dst, size_t dstCapacity,
                             const void* src, size_t srcSize);


/***************************************
*  Advanced decompression API
***************************************/

/* The advanced API pushes parameters one by one into an existing DCtx context.
 * Parameters are sticky, and remain valid for all following frames
 * using the same DCtx context.
 * It's possible to reset parameters to default values using ZSTD_DCtx_reset().
 * Note : This API is compatible with existing ZSTD_decompressDCtx() and ZSTD_decompressStream().
 *        Therefore, no new decompression function is necessary.
 */

typedef enum {

    ZSTD_d_windowLogMax=100, /* Select a size limit (in power of 2) beyond which
                              * the streaming API will refuse to allocate memory buffer
                              * in order to protect the host from unreasonable memory requirements.
                              * This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
                              * By default, a decompression context accepts window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT).
                              * Special: value 0 means "use default maximum windowLog". */

    /* note : additional experimental parameters are also available
     * within the experimental section of the API.
     * At the time of this writing, they include :
     * ZSTD_d_format
     * ZSTD_d_stableOutBuffer
     * Because they are not stable, it's necessary to define ZSTD_STATIC_LINKING_ONLY to access them.
     * note : never ever use experimentalParam? names directly
     */
     ZSTD_d_experimentalParam1=1000,
     ZSTD_d_experimentalParam2=1001

} ZSTD_dParameter;

/*! ZSTD_dParam_getBounds() :
 *  All parameters must belong to an interval with lower and upper bounds,
 *  otherwise they will either trigger an error or be automatically clamped.
 * @return : a structure, ZSTD_bounds, which contains
 *         - an error status field, which must be tested using ZSTD_isError()
 *         - both lower and upper bounds, inclusive
 */
ZSTDLIB_API ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam);

/*! ZSTD_DCtx_setParameter() :
 *  Set one compression parameter, selected by enum ZSTD_dParameter.
 *  All parameters have valid bounds. Bounds can be queried using ZSTD_dParam_getBounds().
 *  Providing a value beyond bound will either clamp it, or trigger an error (depending on parameter).
 *  Setting a parameter is only possible during frame initialization (before starting decompression).
 * @return : 0, or an error code (which can be tested using ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter param, int value);

/*! ZSTD_DCtx_reset() :
 *  Return a DCtx to clean state.
 *  Session and parameters can be reset jointly or separately.
 *  Parameters can only be reset when no active frame is being decompressed.
 * @return : 0, or an error code, which can be tested with ZSTD_isError()
 */
ZSTDLIB_API size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset);


/****************************
*  Streaming
****************************/

typedef struct ZSTD_inBuffer_s {
  const void* src;    /**< start of input buffer */
  size_t size;        /**< size of input buffer */
  size_t pos;         /**< position where reading stopped. Will be updated. Necessarily 0 <= pos <= size */
} ZSTD_inBuffer;

typedef struct ZSTD_outBuffer_s {
  void*  dst;         /**< start of output buffer */
  size_t size;        /**< size of output buffer */
  size_t pos;         /**< position where writing stopped. Will be updated. Necessarily 0 <= pos <= size */
} ZSTD_outBuffer;



/*-***********************************************************************
*  Streaming compression - HowTo
*
*  A ZSTD_CStream object is required to track streaming operation.
*  Use ZSTD_createCStream() and ZSTD_freeCStream() to create/release resources.
*  ZSTD_CStream objects can be reused multiple times on consecutive compression operations.
*  It is recommended to re-use ZSTD_CStream since it will play nicer with system's memory, by re-using already allocated memory.
*
*  For parallel execution, use one separate ZSTD_CStream per thread.
*
*  note : since v1.3.0, ZSTD_CStream and ZSTD_CCtx are the same thing.
*
*  Parameters are sticky : when starting a new compression on the same context,
*  it will re-use the same sticky parameters as previous compression session.
*  When in doubt, it's recommended to fully initialize the context before usage.
*  Use ZSTD_CCtx_reset() to reset the context and ZSTD_CCtx_setParameter(),
*  ZSTD_CCtx_setPledgedSrcSize(), or ZSTD_CCtx_loadDictionary() and friends to
*  set more specific parameters, the pledged source size, or load a dictionary.
*
*  Use ZSTD_compressStream2() with ZSTD_e_continue as many times as necessary to
*  consume input stream. The function will automatically update both `pos`
*  fields within `input` and `output`.
*  Note that the function may not consume the entire input, for example, because
*  the output buffer is already full, in which case `input.pos < input.size`.
*  The caller must check if input has been entirely consumed.
*  If not, the caller must make some room to receive more compressed data,
*  and then present again remaining input data.
*  note: ZSTD_e_continue is guaranteed to make some forward progress when called,
*        but doesn't guarantee maximal forward progress. This is especially relevant
*        when compressing with multiple threads. The call won't block if it can
*        consume some input, but if it can't it will wait for some, but not all,
*        output to be flushed.
* @return : provides a minimum amount of data remaining to be flushed from internal buffers
*           or an error code, which can be tested using ZSTD_isError().
*
*  At any moment, it's possible to flush whatever data might remain stuck within internal buffer,
*  using ZSTD_compressStream2() with ZSTD_e_flush. `output->pos` will be updated.
*  Note that, if `output->size` is too small, a single invocation with ZSTD_e_flush might not be enough (return code > 0).
*  In which case, make some room to receive more compressed data, and call again ZSTD_compressStream2() with ZSTD_e_flush.
*  You must continue calling ZSTD_compressStream2() with ZSTD_e_flush until it returns 0, at which point you can change the
*  operation.
*  note: ZSTD_e_flush will flush as much output as possible, meaning when compressing with multiple threads, it will
*        block until the flush is complete or the output buffer is full.
*  @return : 0 if internal buffers are entirely flushed,
*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
*            or an error code, which can be tested using ZSTD_isError().
*
*  Calling ZSTD_compressStream2() with ZSTD_e_end instructs to finish a frame.
*  It will perform a flush and write frame epilogue.
*  The epilogue is required for decoders to consider a frame completed.
*  flush operation is the same, and follows same rules as calling ZSTD_compressStream2() with ZSTD_e_flush.
*  You must continue calling ZSTD_compressStream2() with ZSTD_e_end until it returns 0, at which point you are free to
*  start a new frame.
*  note: ZSTD_e_end will flush as much output as possible, meaning when compressing with multiple threads, it will
*        block until the flush is complete or the output buffer is full.
*  @return : 0 if frame fully completed and fully flushed,
*            >0 if some data still present within internal buffer (the value is minimal estimation of remaining size),
*            or an error code, which can be tested using ZSTD_isError().
*
* *******************************************************************/

typedef ZSTD_CCtx ZSTD_CStream;  /**< CCtx and CStream are now effectively same object (>= v1.3.0) */
                                 /* Continue to distinguish them for compatibility with older versions <= v1.2.0 */
/*===== ZSTD_CStream management functions =====*/
ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream(void);
ZSTDLIB_API size_t ZSTD_freeCStream(ZSTD_CStream* zcs);

/*===== Streaming compression functions =====*/
typedef enum {
    ZSTD_e_continue=0, /* collect more data, encoder decides when to output compressed result, for optimal compression ratio */
    ZSTD_e_flush=1,    /* flush any data provided so far,
                        * it creates (at least) one new block, that can be decoded immediately on reception;
                        * frame will continue: any future data can still reference previously compressed data, improving compression.
                        * note : multithreaded compression will block to flush as much output as possible. */
    ZSTD_e_end=2       /* flush any remaining data _and_ close current frame.
                        * note that frame is only closed after compressed data is fully flushed (return value == 0).
                        * After that point, any additional data starts a new frame.
                        * note : each frame is independent (does not reference any content from previous frame).
                        : note : multithreaded compression will block to flush as much output as possible. */
} ZSTD_EndDirective;

/*! ZSTD_compressStream2() :
 *  Behaves about the same as ZSTD_compressStream, with additional control on end directive.
 *  - Compression parameters are pushed into CCtx before starting compression, using ZSTD_CCtx_set*()
 *  - Compression parameters cannot be changed once compression is started (save a list of exceptions in multi-threading mode)
 *  - output->pos must be <= dstCapacity, input->pos must be <= srcSize
 *  - output->pos and input->pos will be updated. They are guaranteed to remain below their respective limit.
 *  - When nbWorkers==0 (default), function is blocking : it completes its job before returning to caller.
 *  - When nbWorkers>=1, function is non-blocking : it just acquires a copy of input, and distributes jobs to internal worker threads, flush whatever is available,
 *                                                  and then immediately returns, just indicating that there is some data remaining to be flushed.
 *                                                  The function nonetheless guarantees forward progress : it will return only after it reads or write at least 1+ byte.
 *  - Exception : if the first call requests a ZSTD_e_end directive and provides enough dstCapacity, the function delegates to ZSTD_compress2() which is always blocking.
 *  - @return provides a minimum amount of data remaining to be flushed from internal buffers
 *            or an error code, which can be tested using ZSTD_isError().
 *            if @return != 0, flush is not fully completed, there is still some data left within internal buffers.
 *            This is useful for ZSTD_e_flush, since in this case more flushes are necessary to empty all buffers.
 *            For ZSTD_e_end, @return == 0 when internal buffers are fully flushed and frame is completed.
 *  - after a ZSTD_e_end directive, if internal buffer is not fully flushed (@return != 0),
 *            only ZSTD_e_end or ZSTD_e_flush operations are allowed.
 *            Before starting a new compression job, or changing compression parameters,
 *            it is required to fully flush internal buffers.
 */
ZSTDLIB_API size_t ZSTD_compressStream2( ZSTD_CCtx* cctx,
                                         ZSTD_outBuffer* output,
                                         ZSTD_inBuffer* input,
                                         ZSTD_EndDirective endOp);


/* These buffer sizes are softly recommended.
 * They are not required : ZSTD_compressStream*() happily accepts any buffer size, for both input and output.
 * Respecting the recommended size just makes it a bit easier for ZSTD_compressStream*(),
 * reducing the amount of memory shuffling and buffering, resulting in minor performance savings.
 *
 * However, note that these recommendations are from the perspective of a C caller program.
 * If the streaming interface is invoked from some other language,
 * especially managed ones such as Java or Go, through a foreign function interface such as jni or cgo,
 * a major performance rule is to reduce crossing such interface to an absolute minimum.
 * It's not rare that performance ends being spent more into the interface, rather than compression itself.
 * In which cases, prefer using large buffers, as large as practical,
 * for both input and output, to reduce the nb of roundtrips.
 */
ZSTDLIB_API size_t ZSTD_CStreamInSize(void);    /**< recommended size for input buffer */
ZSTDLIB_API size_t ZSTD_CStreamOutSize(void);   /**< recommended size for output buffer. Guarantee to successfully flush at least one complete compressed block. */


/* *****************************************************************************
 * This following is a legacy streaming API.
 * It can be replaced by ZSTD_CCtx_reset() and ZSTD_compressStream2().
 * It is redundant, but remains fully supported.
 * Advanced parameters and dictionary compression can only be used through the
 * new API.
 ******************************************************************************/

/*!
 * Equivalent to:
 *
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
 */
ZSTDLIB_API size_t ZSTD_initCStream(ZSTD_CStream* zcs, int compressionLevel);
/*!
 * Alternative for ZSTD_compressStream2(zcs, output, input, ZSTD_e_continue).
 * NOTE: The return value is different. ZSTD_compressStream() returns a hint for
 * the next read size (if non-zero and not an error). ZSTD_compressStream2()
 * returns the minimum nb of bytes left to flush (if non-zero and not an error).
 */
ZSTDLIB_API size_t ZSTD_compressStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output, ZSTD_inBuffer* input);
/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_flush). */
ZSTDLIB_API size_t ZSTD_flushStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);
/*! Equivalent to ZSTD_compressStream2(zcs, output, &emptyInput, ZSTD_e_end). */
ZSTDLIB_API size_t ZSTD_endStream(ZSTD_CStream* zcs, ZSTD_outBuffer* output);


/*-***************************************************************************
*  Streaming decompression - HowTo
*
*  A ZSTD_DStream object is required to track streaming operations.
*  Use ZSTD_createDStream() and ZSTD_freeDStream() to create/release resources.
*  ZSTD_DStream objects can be re-used multiple times.
*
*  Use ZSTD_initDStream() to start a new decompression operation.
* @return : recommended first input size
*  Alternatively, use advanced API to set specific properties.
*
*  Use ZSTD_decompressStream() repetitively to consume your input.
*  The function will update both `pos` fields.
*  If `input.pos < input.size`, some input has not been consumed.
*  It's up to the caller to present again remaining data.
*  The function tries to flush all data decoded immediately, respecting output buffer size.
*  If `output.pos < output.size`, decoder has flushed everything it could.
*  But if `output.pos == output.size`, there might be some data left within internal buffers.,
*  In which case, call ZSTD_decompressStream() again to flush whatever remains in the buffer.
*  Note : with no additional input provided, amount of data flushed is necessarily <= ZSTD_BLOCKSIZE_MAX.
* @return : 0 when a frame is completely decoded and fully flushed,
*        or an error code, which can be tested using ZSTD_isError(),
*        or any other value > 0, which means there is still some decoding or flushing to do to complete current frame :
*                                the return value is a suggested next input size (just a hint for better latency)
*                                that will never request more than the remaining frame size.
* *******************************************************************************/

typedef ZSTD_DCtx ZSTD_DStream;  /**< DCtx and DStream are now effectively same object (>= v1.3.0) */
                                 /* For compatibility with versions <= v1.2.0, prefer differentiating them. */
/*===== ZSTD_DStream management functions =====*/
ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream(void);
ZSTDLIB_API size_t ZSTD_freeDStream(ZSTD_DStream* zds);

/*===== Streaming decompression functions =====*/

/* This function is redundant with the advanced API and equivalent to:
 *
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
 *     ZSTD_DCtx_refDDict(zds, NULL);
 */
ZSTDLIB_API size_t ZSTD_initDStream(ZSTD_DStream* zds);

ZSTDLIB_API size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input);

ZSTDLIB_API size_t ZSTD_DStreamInSize(void);    /*!< recommended size for input buffer */
ZSTDLIB_API size_t ZSTD_DStreamOutSize(void);   /*!< recommended size for output buffer. Guarantee to successfully flush at least one complete block in all circumstances. */


/**************************
*  Simple dictionary API
***************************/
/*! ZSTD_compress_usingDict() :
 *  Compression at an explicit compression level using a Dictionary.
 *  A dictionary can be any arbitrary data segment (also called a prefix),
 *  or a buffer with specified information (see dictBuilder/zdict.h).
 *  Note : This function loads the dictionary, resulting in significant startup delay.
 *         It's intended for a dictionary used only once.
 *  Note 2 : When `dict == NULL || dictSize < 8` no dictionary is used. */
ZSTDLIB_API size_t ZSTD_compress_usingDict(ZSTD_CCtx* ctx,
                                           void* dst, size_t dstCapacity,
                                     const void* src, size_t srcSize,
                                     const void* dict,size_t dictSize,
                                           int compressionLevel);

/*! ZSTD_decompress_usingDict() :
 *  Decompression using a known Dictionary.
 *  Dictionary must be identical to the one used during compression.
 *  Note : This function loads the dictionary, resulting in significant startup delay.
 *         It's intended for a dictionary used only once.
 *  Note : When `dict == NULL || dictSize < 8` no dictionary is used. */
ZSTDLIB_API size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
                                             void* dst, size_t dstCapacity,
                                       const void* src, size_t srcSize,
                                       const void* dict,size_t dictSize);


/***********************************
 *  Bulk processing dictionary API
 **********************************/
typedef struct ZSTD_CDict_s ZSTD_CDict;

/*! ZSTD_createCDict() :
 *  When compressing multiple messages or blocks using the same dictionary,
 *  it's recommended to digest the dictionary only once, since it's a costly operation.
 *  ZSTD_createCDict() will create a state from digesting a dictionary.
 *  The resulting state can be used for future compression operations with very limited startup cost.
 *  ZSTD_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
 * @dictBuffer can be released after ZSTD_CDict creation, because its content is copied within CDict.
 *  Note 1 : Consider experimental function `ZSTD_createCDict_byReference()` if you prefer to not duplicate @dictBuffer content.
 *  Note 2 : A ZSTD_CDict can be created from an empty @dictBuffer,
 *      in which case the only thing that it transports is the @compressionLevel.
 *      This can be useful in a pipeline featuring ZSTD_compress_usingCDict() exclusively,
 *      expecting a ZSTD_CDict parameter with any data, including those without a known dictionary. */
ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict(const void* dictBuffer, size_t dictSize,
                                         int compressionLevel);

/*! ZSTD_freeCDict() :
 *  Function frees memory allocated by ZSTD_createCDict(). */
ZSTDLIB_API size_t      ZSTD_freeCDict(ZSTD_CDict* CDict);

/*! ZSTD_compress_usingCDict() :
 *  Compression using a digested Dictionary.
 *  Recommended when same dictionary is used multiple times.
 *  Note : compression level is _decided at dictionary creation time_,
 *     and frame parameters are hardcoded (dictID=yes, contentSize=yes, checksum=no) */
ZSTDLIB_API size_t ZSTD_compress_usingCDict(ZSTD_CCtx* cctx,
                                            void* dst, size_t dstCapacity,
                                      const void* src, size_t srcSize,
                                      const ZSTD_CDict* cdict);


typedef struct ZSTD_DDict_s ZSTD_DDict;

/*! ZSTD_createDDict() :
 *  Create a digested dictionary, ready to start decompression operation without startup delay.
 *  dictBuffer can be released after DDict creation, as its content is copied inside DDict. */
ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict(const void* dictBuffer, size_t dictSize);

/*! ZSTD_freeDDict() :
 *  Function frees memory allocated with ZSTD_createDDict() */
ZSTDLIB_API size_t      ZSTD_freeDDict(ZSTD_DDict* ddict);

/*! ZSTD_decompress_usingDDict() :
 *  Decompression using a digested Dictionary.
 *  Recommended when same dictionary is used multiple times. */
ZSTDLIB_API size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
                                              void* dst, size_t dstCapacity,
                                        const void* src, size_t srcSize,
                                        const ZSTD_DDict* ddict);


/********************************
 *  Dictionary helper functions
 *******************************/

/*! ZSTD_getDictID_fromDict() :
 *  Provides the dictID stored within dictionary.
 *  if @return == 0, the dictionary is not conformant with Zstandard specification.
 *  It can still be loaded, but as a content-only dictionary. */
ZSTDLIB_API unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize);

/*! ZSTD_getDictID_fromDDict() :
 *  Provides the dictID of the dictionary loaded into `ddict`.
 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
ZSTDLIB_API unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict);

/*! ZSTD_getDictID_fromFrame() :
 *  Provides the dictID required to decompressed the frame stored within `src`.
 *  If @return == 0, the dictID could not be decoded.
 *  This could for one of the following reasons :
 *  - The frame does not require a dictionary to be decoded (most common case).
 *  - The frame was built with dictID intentionally removed. Whatever dictionary is necessary is a hidden information.
 *    Note : this use case also happens when using a non-conformant dictionary.
 *  - `srcSize` is too small, and as a result, the frame header could not be decoded (only possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`).
 *  - This is not a Zstandard frame.
 *  When identifying the exact failure cause, it's possible to use ZSTD_getFrameHeader(), which will provide a more precise error code. */
ZSTDLIB_API unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize);


/*******************************************************************************
 * Advanced dictionary and prefix API
 *
 * This API allows dictionaries to be used with ZSTD_compress2(),
 * ZSTD_compressStream2(), and ZSTD_decompress(). Dictionaries are sticky, and
 * only reset with the context is reset with ZSTD_reset_parameters or
 * ZSTD_reset_session_and_parameters. Prefixes are single-use.
 ******************************************************************************/


/*! ZSTD_CCtx_loadDictionary() :
 *  Create an internal CDict from `dict` buffer.
 *  Decompression will have to use same dictionary.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Special: Loading a NULL (or 0-size) dictionary invalidates previous dictionary,
 *           meaning "return to no-dictionary mode".
 *  Note 1 : Dictionary is sticky, it will be used for all future compressed frames.
 *           To return to "no-dictionary" situation, load a NULL dictionary (or reset parameters).
 *  Note 2 : Loading a dictionary involves building tables.
 *           It's also a CPU consuming operation, with non-negligible impact on latency.
 *           Tables are dependent on compression parameters, and for this reason,
 *           compression parameters can no longer be changed after loading a dictionary.
 *  Note 3 :`dict` content will be copied internally.
 *           Use experimental ZSTD_CCtx_loadDictionary_byReference() to reference content instead.
 *           In such a case, dictionary buffer must outlive its users.
 *  Note 4 : Use ZSTD_CCtx_loadDictionary_advanced()
 *           to precisely select how dictionary content must be interpreted. */
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);

/*! ZSTD_CCtx_refCDict() :
 *  Reference a prepared dictionary, to be used for all next compressed frames.
 *  Note that compression parameters are enforced from within CDict,
 *  and supersede any compression parameter previously set within CCtx.
 *  The parameters ignored are labled as "superseded-by-cdict" in the ZSTD_cParameter enum docs.
 *  The ignored parameters will be used again if the CCtx is returned to no-dictionary mode.
 *  The dictionary will remain valid for future compressed frames using same CCtx.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Special : Referencing a NULL CDict means "return to no-dictionary mode".
 *  Note 1 : Currently, only one dictionary can be managed.
 *           Referencing a new dictionary effectively "discards" any previous one.
 *  Note 2 : CDict is just referenced, its lifetime must outlive its usage within CCtx. */
ZSTDLIB_API size_t ZSTD_CCtx_refCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict);

/*! ZSTD_CCtx_refPrefix() :
 *  Reference a prefix (single-usage dictionary) for next compressed frame.
 *  A prefix is **only used once**. Tables are discarded at end of frame (ZSTD_e_end).
 *  Decompression will need same prefix to properly regenerate data.
 *  Compressing with a prefix is similar in outcome as performing a diff and compressing it,
 *  but performs much faster, especially during decompression (compression speed is tunable with compression level).
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Special: Adding any prefix (including NULL) invalidates any previous prefix or dictionary
 *  Note 1 : Prefix buffer is referenced. It **must** outlive compression.
 *           Its content must remain unmodified during compression.
 *  Note 2 : If the intention is to diff some large src data blob with some prior version of itself,
 *           ensure that the window size is large enough to contain the entire source.
 *           See ZSTD_c_windowLog.
 *  Note 3 : Referencing a prefix involves building tables, which are dependent on compression parameters.
 *           It's a CPU consuming operation, with non-negligible impact on latency.
 *           If there is a need to use the same prefix multiple times, consider loadDictionary instead.
 *  Note 4 : By default, the prefix is interpreted as raw content (ZSTD_dct_rawContent).
 *           Use experimental ZSTD_CCtx_refPrefix_advanced() to alter dictionary interpretation. */
ZSTDLIB_API size_t ZSTD_CCtx_refPrefix(ZSTD_CCtx* cctx,
                                 const void* prefix, size_t prefixSize);

/*! ZSTD_DCtx_loadDictionary() :
 *  Create an internal DDict from dict buffer,
 *  to be used to decompress next frames.
 *  The dictionary remains valid for all future frames, until explicitly invalidated.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Special : Adding a NULL (or 0-size) dictionary invalidates any previous dictionary,
 *            meaning "return to no-dictionary mode".
 *  Note 1 : Loading a dictionary involves building tables,
 *           which has a non-negligible impact on CPU usage and latency.
 *           It's recommended to "load once, use many times", to amortize the cost
 *  Note 2 :`dict` content will be copied internally, so `dict` can be released after loading.
 *           Use ZSTD_DCtx_loadDictionary_byReference() to reference dictionary content instead.
 *  Note 3 : Use ZSTD_DCtx_loadDictionary_advanced() to take control of
 *           how dictionary content is loaded and interpreted.
 */
ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);

/*! ZSTD_DCtx_refDDict() :
 *  Reference a prepared dictionary, to be used to decompress next frames.
 *  The dictionary remains active for decompression of future frames using same DCtx.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Note 1 : Currently, only one dictionary can be managed.
 *           Referencing a new dictionary effectively "discards" any previous one.
 *  Special: referencing a NULL DDict means "return to no-dictionary mode".
 *  Note 2 : DDict is just referenced, its lifetime must outlive its usage from DCtx.
 */
ZSTDLIB_API size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);

/*! ZSTD_DCtx_refPrefix() :
 *  Reference a prefix (single-usage dictionary) to decompress next frame.
 *  This is the reverse operation of ZSTD_CCtx_refPrefix(),
 *  and must use the same prefix as the one used during compression.
 *  Prefix is **only used once**. Reference is discarded at end of frame.
 *  End of frame is reached when ZSTD_decompressStream() returns 0.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 *  Note 1 : Adding any prefix (including NULL) invalidates any previously set prefix or dictionary
 *  Note 2 : Prefix buffer is referenced. It **must** outlive decompression.
 *           Prefix buffer must remain unmodified up to the end of frame,
 *           reached when ZSTD_decompressStream() returns 0.
 *  Note 3 : By default, the prefix is treated as raw content (ZSTD_dct_rawContent).
 *           Use ZSTD_CCtx_refPrefix_advanced() to alter dictMode (Experimental section)
 *  Note 4 : Referencing a raw content prefix has almost no cpu nor memory cost.
 *           A full dictionary is more costly, as it requires building tables.
 */
ZSTDLIB_API size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx,
                                 const void* prefix, size_t prefixSize);

/* ===   Memory management   === */

/*! ZSTD_sizeof_*() :
 *  These functions give the _current_ memory usage of selected object.
 *  Note that object memory usage can evolve (increase or decrease) over time. */
ZSTDLIB_API size_t ZSTD_sizeof_CCtx(const ZSTD_CCtx* cctx);
ZSTDLIB_API size_t ZSTD_sizeof_DCtx(const ZSTD_DCtx* dctx);
ZSTDLIB_API size_t ZSTD_sizeof_CStream(const ZSTD_CStream* zcs);
ZSTDLIB_API size_t ZSTD_sizeof_DStream(const ZSTD_DStream* zds);
ZSTDLIB_API size_t ZSTD_sizeof_CDict(const ZSTD_CDict* cdict);
ZSTDLIB_API size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict);

#endif  /* ZSTD_H_235446 */


/* **************************************************************************************
 *   ADVANCED AND EXPERIMENTAL FUNCTIONS
 ****************************************************************************************
 * The definitions in the following section are considered experimental.
 * They are provided for advanced scenarios.
 * They should never be used with a dynamic library, as prototypes may change in the future.
 * Use them only in association with static linking.
 * ***************************************************************************************/

#if defined(ZSTD_STATIC_LINKING_ONLY) && !defined(ZSTD_H_ZSTD_STATIC_LINKING_ONLY)
#define ZSTD_H_ZSTD_STATIC_LINKING_ONLY

/****************************************************************************************
 *   experimental API (static linking only)
 ****************************************************************************************
 * The following symbols and constants
 * are not planned to join "stable API" status in the near future.
 * They can still change in future versions.
 * Some of them are planned to remain in the static_only section indefinitely.
 * Some of them might be removed in the future (especially when redundant with existing stable functions)
 * ***************************************************************************************/

#define ZSTD_FRAMEHEADERSIZE_PREFIX(format) ((format) == ZSTD_f_zstd1 ? 5 : 1)   /* minimum input size required to query frame header size */
#define ZSTD_FRAMEHEADERSIZE_MIN(format)    ((format) == ZSTD_f_zstd1 ? 6 : 2)
#define ZSTD_FRAMEHEADERSIZE_MAX   18   /* can be useful for static allocation */
#define ZSTD_SKIPPABLEHEADERSIZE    8

/* compression parameter bounds */
#define ZSTD_WINDOWLOG_MAX_32    30
#define ZSTD_WINDOWLOG_MAX_64    31
#define ZSTD_WINDOWLOG_MAX     ((int)(sizeof(size_t) == 4 ? ZSTD_WINDOWLOG_MAX_32 : ZSTD_WINDOWLOG_MAX_64))
#define ZSTD_WINDOWLOG_MIN       10
#define ZSTD_HASHLOG_MAX       ((ZSTD_WINDOWLOG_MAX < 30) ? ZSTD_WINDOWLOG_MAX : 30)
#define ZSTD_HASHLOG_MIN          6
#define ZSTD_CHAINLOG_MAX_32     29
#define ZSTD_CHAINLOG_MAX_64     30
#define ZSTD_CHAINLOG_MAX      ((int)(sizeof(size_t) == 4 ? ZSTD_CHAINLOG_MAX_32 : ZSTD_CHAINLOG_MAX_64))
#define ZSTD_CHAINLOG_MIN        ZSTD_HASHLOG_MIN
#define ZSTD_SEARCHLOG_MAX      (ZSTD_WINDOWLOG_MAX-1)
#define ZSTD_SEARCHLOG_MIN        1
#define ZSTD_MINMATCH_MAX         7   /* only for ZSTD_fast, other strategies are limited to 6 */
#define ZSTD_MINMATCH_MIN         3   /* only for ZSTD_btopt+, faster strategies are limited to 4 */
#define ZSTD_TARGETLENGTH_MAX    ZSTD_BLOCKSIZE_MAX
#define ZSTD_TARGETLENGTH_MIN     0   /* note : comparing this constant to an unsigned results in a tautological test */
#define ZSTD_STRATEGY_MIN        ZSTD_fast
#define ZSTD_STRATEGY_MAX        ZSTD_btultra2


#define ZSTD_OVERLAPLOG_MIN       0
#define ZSTD_OVERLAPLOG_MAX       9

#define ZSTD_WINDOWLOG_LIMIT_DEFAULT 27   /* by default, the streaming decoder will refuse any frame
                                           * requiring larger than (1<<ZSTD_WINDOWLOG_LIMIT_DEFAULT) window size,
                                           * to preserve host's memory from unreasonable requirements.
                                           * This limit can be overridden using ZSTD_DCtx_setParameter(,ZSTD_d_windowLogMax,).
                                           * The limit does not apply for one-pass decoders (such as ZSTD_decompress()), since no additional memory is allocated */


/* LDM parameter bounds */
#define ZSTD_LDM_HASHLOG_MIN      ZSTD_HASHLOG_MIN
#define ZSTD_LDM_HASHLOG_MAX      ZSTD_HASHLOG_MAX
#define ZSTD_LDM_MINMATCH_MIN        4
#define ZSTD_LDM_MINMATCH_MAX     4096
#define ZSTD_LDM_BUCKETSIZELOG_MIN   1
#define ZSTD_LDM_BUCKETSIZELOG_MAX   8
#define ZSTD_LDM_HASHRATELOG_MIN     0
#define ZSTD_LDM_HASHRATELOG_MAX (ZSTD_WINDOWLOG_MAX - ZSTD_HASHLOG_MIN)

/* Advanced parameter bounds */
#define ZSTD_TARGETCBLOCKSIZE_MIN   64
#define ZSTD_TARGETCBLOCKSIZE_MAX   ZSTD_BLOCKSIZE_MAX
#define ZSTD_SRCSIZEHINT_MIN        0
#define ZSTD_SRCSIZEHINT_MAX        INT_MAX

/* internal */
#define ZSTD_HASHLOG3_MAX           17


/* ---  Advanced types  --- */

typedef struct ZSTD_CCtx_params_s ZSTD_CCtx_params;

typedef struct {
    unsigned int matchPos; /* Match pos in dst */
    /* If seqDef.offset > 3, then this is seqDef.offset - 3
     * If seqDef.offset < 3, then this is the corresponding repeat offset
     * But if seqDef.offset < 3 and litLength == 0, this is the
     *   repeat offset before the corresponding repeat offset
     * And if seqDef.offset == 3 and litLength == 0, this is the
     *   most recent repeat offset - 1
     */
    unsigned int offset;
    unsigned int litLength; /* Literal length */
    unsigned int matchLength; /* Match length */
    /* 0 when seq not rep and seqDef.offset otherwise
     * when litLength == 0 this will be <= 4, otherwise <= 3 like normal
     */
    unsigned int rep;
} ZSTD_Sequence;

typedef struct {
    unsigned windowLog;       /**< largest match distance : larger == more compression, more memory needed during decompression */
    unsigned chainLog;        /**< fully searched segment : larger == more compression, slower, more memory (useless for fast) */
    unsigned hashLog;         /**< dispatch table : larger == faster, more memory */
    unsigned searchLog;       /**< nb of searches : larger == more compression, slower */
    unsigned minMatch;        /**< match length searched : larger == faster decompression, sometimes less compression */
    unsigned targetLength;    /**< acceptable match size for optimal parser (only) : larger == more compression, slower */
    ZSTD_strategy strategy;   /**< see ZSTD_strategy definition above */
} ZSTD_compressionParameters;

typedef struct {
    int contentSizeFlag; /**< 1: content size will be in frame header (when known) */
    int checksumFlag;    /**< 1: generate a 32-bits checksum using XXH64 algorithm at end of frame, for error detection */
    int noDictIDFlag;    /**< 1: no dictID will be saved into frame header (dictID is only useful for dictionary compression) */
} ZSTD_frameParameters;

typedef struct {
    ZSTD_compressionParameters cParams;
    ZSTD_frameParameters fParams;
} ZSTD_parameters;

typedef enum {
    ZSTD_dct_auto = 0,       /* dictionary is "full" when starting with ZSTD_MAGIC_DICTIONARY, otherwise it is "rawContent" */
    ZSTD_dct_rawContent = 1, /* ensures dictionary is always loaded as rawContent, even if it starts with ZSTD_MAGIC_DICTIONARY */
    ZSTD_dct_fullDict = 2    /* refuses to load a dictionary if it does not respect Zstandard's specification, starting with ZSTD_MAGIC_DICTIONARY */
} ZSTD_dictContentType_e;

typedef enum {
    ZSTD_dlm_byCopy = 0,  /**< Copy dictionary content internally */
    ZSTD_dlm_byRef = 1    /**< Reference dictionary content -- the dictionary buffer must outlive its users. */
} ZSTD_dictLoadMethod_e;

typedef enum {
    ZSTD_f_zstd1 = 0,           /* zstd frame format, specified in zstd_compression_format.md (default) */
    ZSTD_f_zstd1_magicless = 1  /* Variant of zstd frame format, without initial 4-bytes magic number.
                                 * Useful to save 4 bytes per generated frame.
                                 * Decoder cannot recognise automatically this format, requiring this instruction. */
} ZSTD_format_e;

typedef enum {
    /* Note: this enum and the behavior it controls are effectively internal
     * implementation details of the compressor. They are expected to continue
     * to evolve and should be considered only in the context of extremely
     * advanced performance tuning.
     *
     * Zstd currently supports the use of a CDict in three ways:
     *
     * - The contents of the CDict can be copied into the working context. This
     *   means that the compression can search both the dictionary and input
     *   while operating on a single set of internal tables. This makes
     *   the compression faster per-byte of input. However, the initial copy of
     *   the CDict's tables incurs a fixed cost at the beginning of the
     *   compression. For small compressions (< 8 KB), that copy can dominate
     *   the cost of the compression.
     *
     * - The CDict's tables can be used in-place. In this model, compression is
     *   slower per input byte, because the compressor has to search two sets of
     *   tables. However, this model incurs no start-up cost (as long as the
     *   working context's tables can be reused). For small inputs, this can be
     *   faster than copying the CDict's tables.
     *
     * - The CDict's tables are not used at all, and instead we use the working
     *   context alone to reload the dictionary and use params based on the source
     *   size. See ZSTD_compress_insertDictionary() and ZSTD_compress_usingDict().
     *   This method is effective when the dictionary sizes are very small relative
     *   to the input size, and the input size is fairly large to begin with.
     *
     * Zstd has a simple internal heuristic that selects which strategy to use
     * at the beginning of a compression. However, if experimentation shows that
     * Zstd is making poor choices, it is possible to override that choice with
     * this enum.
     */
    ZSTD_dictDefaultAttach = 0, /* Use the default heuristic. */
    ZSTD_dictForceAttach   = 1, /* Never copy the dictionary. */
    ZSTD_dictForceCopy     = 2, /* Always copy the dictionary. */
    ZSTD_dictForceLoad     = 3  /* Always reload the dictionary */
} ZSTD_dictAttachPref_e;

typedef enum {
  ZSTD_lcm_auto = 0,          /**< Automatically determine the compression mode based on the compression level.
                               *   Negative compression levels will be uncompressed, and positive compression
                               *   levels will be compressed. */
  ZSTD_lcm_huffman = 1,       /**< Always attempt Huffman compression. Uncompressed literals will still be
                               *   emitted if Huffman compression is not profitable. */
  ZSTD_lcm_uncompressed = 2   /**< Always emit uncompressed literals. */
} ZSTD_literalCompressionMode_e;


/***************************************
*  Frame size functions
***************************************/

/*! ZSTD_findDecompressedSize() :
 *  `src` should point to the start of a series of ZSTD encoded and/or skippable frames
 *  `srcSize` must be the _exact_ size of this series
 *       (i.e. there should be a frame boundary at `src + srcSize`)
 *  @return : - decompressed size of all data in all successive frames
 *            - if the decompressed size cannot be determined: ZSTD_CONTENTSIZE_UNKNOWN
 *            - if an error occurred: ZSTD_CONTENTSIZE_ERROR
 *
 *   note 1 : decompressed size is an optional field, that may not be present, especially in streaming mode.
 *            When `return==ZSTD_CONTENTSIZE_UNKNOWN`, data to decompress could be any size.
 *            In which case, it's necessary to use streaming mode to decompress data.
 *   note 2 : decompressed size is always present when compression is done with ZSTD_compress()
 *   note 3 : decompressed size can be very large (64-bits value),
 *            potentially larger than what local system can handle as a single memory segment.
 *            In which case, it's necessary to use streaming mode to decompress data.
 *   note 4 : If source is untrusted, decompressed size could be wrong or intentionally modified.
 *            Always ensure result fits within application's authorized limits.
 *            Each application can set its own limits.
 *   note 5 : ZSTD_findDecompressedSize handles multiple frames, and so it must traverse the input to
 *            read each contained frame header.  This is fast as most of the data is skipped,
 *            however it does mean that all frame data must be present and valid. */
ZSTDLIB_API unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize);

/*! ZSTD_decompressBound() :
 *  `src` should point to the start of a series of ZSTD encoded and/or skippable frames
 *  `srcSize` must be the _exact_ size of this series
 *       (i.e. there should be a frame boundary at `src + srcSize`)
 *  @return : - upper-bound for the decompressed size of all data in all successive frames
 *            - if an error occured: ZSTD_CONTENTSIZE_ERROR
 *
 *  note 1  : an error can occur if `src` contains an invalid or incorrectly formatted frame.
 *  note 2  : the upper-bound is exact when the decompressed size field is available in every ZSTD encoded frame of `src`.
 *            in this case, `ZSTD_findDecompressedSize` and `ZSTD_decompressBound` return the same value.
 *  note 3  : when the decompressed size field isn't available, the upper-bound for that frame is calculated by:
 *              upper-bound = # blocks * min(128 KB, Window_Size)
 */
ZSTDLIB_API unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize);

/*! ZSTD_frameHeaderSize() :
 *  srcSize must be >= ZSTD_FRAMEHEADERSIZE_PREFIX.
 * @return : size of the Frame Header,
 *           or an error code (if srcSize is too small) */
ZSTDLIB_API size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize);

/*! ZSTD_getSequences() :
 * Extract sequences from the sequence store
 * zc can be used to insert custom compression params.
 * This function invokes ZSTD_compress2
 * @return : number of sequences extracted
 */
ZSTDLIB_API size_t ZSTD_getSequences(ZSTD_CCtx* zc, ZSTD_Sequence* outSeqs,
    size_t outSeqsSize, const void* src, size_t srcSize);


/***************************************
*  Memory management
***************************************/

/*! ZSTD_estimate*() :
 *  These functions make it possible to estimate memory usage
 *  of a future {D,C}Ctx, before its creation.
 *
 *  ZSTD_estimateCCtxSize() will provide a memory budget large enough
 *  for any compression level up to selected one.
 *  Note : Unlike ZSTD_estimateCStreamSize*(), this estimate
 *         does not include space for a window buffer.
 *         Therefore, the estimation is only guaranteed for single-shot compressions, not streaming.
 *  The estimate will assume the input may be arbitrarily large,
 *  which is the worst case.
 *
 *  When srcSize can be bound by a known and rather "small" value,
 *  this fact can be used to provide a tighter estimation
 *  because the CCtx compression context will need less memory.
 *  This tighter estimation can be provided by more advanced functions
 *  ZSTD_estimateCCtxSize_usingCParams(), which can be used in tandem with ZSTD_getCParams(),
 *  and ZSTD_estimateCCtxSize_usingCCtxParams(), which can be used in tandem with ZSTD_CCtxParams_setParameter().
 *  Both can be used to estimate memory using custom compression parameters and arbitrary srcSize limits.
 *
 *  Note 2 : only single-threaded compression is supported.
 *  ZSTD_estimateCCtxSize_usingCCtxParams() will return an error code if ZSTD_c_nbWorkers is >= 1.
 */
ZSTDLIB_API size_t ZSTD_estimateCCtxSize(int compressionLevel);
ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCParams(ZSTD_compressionParameters cParams);
ZSTDLIB_API size_t ZSTD_estimateCCtxSize_usingCCtxParams(const ZSTD_CCtx_params* params);
ZSTDLIB_API size_t ZSTD_estimateDCtxSize(void);

/*! ZSTD_estimateCStreamSize() :
 *  ZSTD_estimateCStreamSize() will provide a budget large enough for any compression level up to selected one.
 *  It will also consider src size to be arbitrarily "large", which is worst case.
 *  If srcSize is known to always be small, ZSTD_estimateCStreamSize_usingCParams() can provide a tighter estimation.
 *  ZSTD_estimateCStreamSize_usingCParams() can be used in tandem with ZSTD_getCParams() to create cParams from compressionLevel.
 *  ZSTD_estimateCStreamSize_usingCCtxParams() can be used in tandem with ZSTD_CCtxParams_setParameter(). Only single-threaded compression is supported. This function will return an error code if ZSTD_c_nbWorkers is >= 1.
 *  Note : CStream size estimation is only correct for single-threaded compression.
 *  ZSTD_DStream memory budget depends on window Size.
 *  This information can be passed manually, using ZSTD_estimateDStreamSize,
 *  or deducted from a valid frame Header, using ZSTD_estimateDStreamSize_fromFrame();
 *  Note : if streaming is init with function ZSTD_init?Stream_usingDict(),
 *         an internal ?Dict will be created, which additional size is not estimated here.
 *         In this case, get total size by adding ZSTD_estimate?DictSize */
ZSTDLIB_API size_t ZSTD_estimateCStreamSize(int compressionLevel);
ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCParams(ZSTD_compressionParameters cParams);
ZSTDLIB_API size_t ZSTD_estimateCStreamSize_usingCCtxParams(const ZSTD_CCtx_params* params);
ZSTDLIB_API size_t ZSTD_estimateDStreamSize(size_t windowSize);
ZSTDLIB_API size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize);

/*! ZSTD_estimate?DictSize() :
 *  ZSTD_estimateCDictSize() will bet that src size is relatively "small", and content is copied, like ZSTD_createCDict().
 *  ZSTD_estimateCDictSize_advanced() makes it possible to control compression parameters precisely, like ZSTD_createCDict_advanced().
 *  Note : dictionaries created by reference (`ZSTD_dlm_byRef`) are logically smaller.
 */
ZSTDLIB_API size_t ZSTD_estimateCDictSize(size_t dictSize, int compressionLevel);
ZSTDLIB_API size_t ZSTD_estimateCDictSize_advanced(size_t dictSize, ZSTD_compressionParameters cParams, ZSTD_dictLoadMethod_e dictLoadMethod);
ZSTDLIB_API size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod);

/*! ZSTD_initStatic*() :
 *  Initialize an object using a pre-allocated fixed-size buffer.
 *  workspace: The memory area to emplace the object into.
 *             Provided pointer *must be 8-bytes aligned*.
 *             Buffer must outlive object.
 *  workspaceSize: Use ZSTD_estimate*Size() to determine
 *                 how large workspace must be to support target scenario.
 * @return : pointer to object (same address as workspace, just different type),
 *           or NULL if error (size too small, incorrect alignment, etc.)
 *  Note : zstd will never resize nor malloc() when using a static buffer.
 *         If the object requires more memory than available,
 *         zstd will just error out (typically ZSTD_error_memory_allocation).
 *  Note 2 : there is no corresponding "free" function.
 *           Since workspace is allocated externally, it must be freed externally too.
 *  Note 3 : cParams : use ZSTD_getCParams() to convert a compression level
 *           into its associated cParams.
 *  Limitation 1 : currently not compatible with internal dictionary creation, triggered by
 *                 ZSTD_CCtx_loadDictionary(), ZSTD_initCStream_usingDict() or ZSTD_initDStream_usingDict().
 *  Limitation 2 : static cctx currently not compatible with multi-threading.
 *  Limitation 3 : static dctx is incompatible with legacy support.
 */
ZSTDLIB_API ZSTD_CCtx*    ZSTD_initStaticCCtx(void* workspace, size_t workspaceSize);
ZSTDLIB_API ZSTD_CStream* ZSTD_initStaticCStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticCCtx() */

ZSTDLIB_API ZSTD_DCtx*    ZSTD_initStaticDCtx(void* workspace, size_t workspaceSize);
ZSTDLIB_API ZSTD_DStream* ZSTD_initStaticDStream(void* workspace, size_t workspaceSize);    /**< same as ZSTD_initStaticDCtx() */

ZSTDLIB_API const ZSTD_CDict* ZSTD_initStaticCDict(
                                        void* workspace, size_t workspaceSize,
                                        const void* dict, size_t dictSize,
                                        ZSTD_dictLoadMethod_e dictLoadMethod,
                                        ZSTD_dictContentType_e dictContentType,
                                        ZSTD_compressionParameters cParams);

ZSTDLIB_API const ZSTD_DDict* ZSTD_initStaticDDict(
                                        void* workspace, size_t workspaceSize,
                                        const void* dict, size_t dictSize,
                                        ZSTD_dictLoadMethod_e dictLoadMethod,
                                        ZSTD_dictContentType_e dictContentType);


/*! Custom memory allocation :
 *  These prototypes make it possible to pass your own allocation/free functions.
 *  ZSTD_customMem is provided at creation time, using ZSTD_create*_advanced() variants listed below.
 *  All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.
 */
typedef void* (*ZSTD_allocFunction) (void* opaque, size_t size);
typedef void  (*ZSTD_freeFunction) (void* opaque, void* address);
typedef struct { ZSTD_allocFunction customAlloc; ZSTD_freeFunction customFree; void* opaque; } ZSTD_customMem;
static ZSTD_customMem const ZSTD_defaultCMem = { NULL, NULL, NULL };  /**< this constant defers to stdlib's functions */

ZSTDLIB_API ZSTD_CCtx*    ZSTD_createCCtx_advanced(ZSTD_customMem customMem);
ZSTDLIB_API ZSTD_CStream* ZSTD_createCStream_advanced(ZSTD_customMem customMem);
ZSTDLIB_API ZSTD_DCtx*    ZSTD_createDCtx_advanced(ZSTD_customMem customMem);
ZSTDLIB_API ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem);

ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_advanced(const void* dict, size_t dictSize,
                                                  ZSTD_dictLoadMethod_e dictLoadMethod,
                                                  ZSTD_dictContentType_e dictContentType,
                                                  ZSTD_compressionParameters cParams,
                                                  ZSTD_customMem customMem);

ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
                                                  ZSTD_dictLoadMethod_e dictLoadMethod,
                                                  ZSTD_dictContentType_e dictContentType,
                                                  ZSTD_customMem customMem);



/***************************************
*  Advanced compression functions
***************************************/

/*! ZSTD_createCDict_byReference() :
 *  Create a digested dictionary for compression
 *  Dictionary content is just referenced, not duplicated.
 *  As a consequence, `dictBuffer` **must** outlive CDict,
 *  and its content must remain unmodified throughout the lifetime of CDict.
 *  note: equivalent to ZSTD_createCDict_advanced(), with dictLoadMethod==ZSTD_dlm_byRef */
ZSTDLIB_API ZSTD_CDict* ZSTD_createCDict_byReference(const void* dictBuffer, size_t dictSize, int compressionLevel);

/*! ZSTD_getCParams() :
 * @return ZSTD_compressionParameters structure for a selected compression level and estimated srcSize.
 * `estimatedSrcSize` value is optional, select 0 if not known */
ZSTDLIB_API ZSTD_compressionParameters ZSTD_getCParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);

/*! ZSTD_getParams() :
 *  same as ZSTD_getCParams(), but @return a full `ZSTD_parameters` object instead of sub-component `ZSTD_compressionParameters`.
 *  All fields of `ZSTD_frameParameters` are set to default : contentSize=1, checksum=0, noDictID=0 */
ZSTDLIB_API ZSTD_parameters ZSTD_getParams(int compressionLevel, unsigned long long estimatedSrcSize, size_t dictSize);

/*! ZSTD_checkCParams() :
 *  Ensure param values remain within authorized range.
 * @return 0 on success, or an error code (can be checked with ZSTD_isError()) */
ZSTDLIB_API size_t ZSTD_checkCParams(ZSTD_compressionParameters params);

/*! ZSTD_adjustCParams() :
 *  optimize params for a given `srcSize` and `dictSize`.
 * `srcSize` can be unknown, in which case use ZSTD_CONTENTSIZE_UNKNOWN.
 * `dictSize` must be `0` when there is no dictionary.
 *  cPar can be invalid : all parameters will be clamped within valid range in the @return struct.
 *  This function never fails (wide contract) */
ZSTDLIB_API ZSTD_compressionParameters ZSTD_adjustCParams(ZSTD_compressionParameters cPar, unsigned long long srcSize, size_t dictSize);

/*! ZSTD_compress_advanced() :
 *  Note : this function is now DEPRECATED.
 *         It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_setParameter() and other parameter setters.
 *  This prototype will be marked as deprecated and generate compilation warning on reaching v1.5.x */
ZSTDLIB_API size_t ZSTD_compress_advanced(ZSTD_CCtx* cctx,
                                          void* dst, size_t dstCapacity,
                                    const void* src, size_t srcSize,
                                    const void* dict,size_t dictSize,
                                          ZSTD_parameters params);

/*! ZSTD_compress_usingCDict_advanced() :
 *  Note : this function is now REDUNDANT.
 *         It can be replaced by ZSTD_compress2(), in combination with ZSTD_CCtx_loadDictionary() and other parameter setters.
 *  This prototype will be marked as deprecated and generate compilation warning in some future version */
ZSTDLIB_API size_t ZSTD_compress_usingCDict_advanced(ZSTD_CCtx* cctx,
                                              void* dst, size_t dstCapacity,
                                        const void* src, size_t srcSize,
                                        const ZSTD_CDict* cdict,
                                              ZSTD_frameParameters fParams);


/*! ZSTD_CCtx_loadDictionary_byReference() :
 *  Same as ZSTD_CCtx_loadDictionary(), but dictionary content is referenced, instead of being copied into CCtx.
 *  It saves some memory, but also requires that `dict` outlives its usage within `cctx` */
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_byReference(ZSTD_CCtx* cctx, const void* dict, size_t dictSize);

/*! ZSTD_CCtx_loadDictionary_advanced() :
 *  Same as ZSTD_CCtx_loadDictionary(), but gives finer control over
 *  how to load the dictionary (by copy ? by reference ?)
 *  and how to interpret it (automatic ? force raw mode ? full mode only ?) */
ZSTDLIB_API size_t ZSTD_CCtx_loadDictionary_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);

/*! ZSTD_CCtx_refPrefix_advanced() :
 *  Same as ZSTD_CCtx_refPrefix(), but gives finer control over
 *  how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
ZSTDLIB_API size_t ZSTD_CCtx_refPrefix_advanced(ZSTD_CCtx* cctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);

/* ===   experimental parameters   === */
/* these parameters can be used with ZSTD_setParameter()
 * they are not guaranteed to remain supported in the future */

 /* Enables rsyncable mode,
  * which makes compressed files more rsync friendly
  * by adding periodic synchronization points to the compressed data.
  * The target average block size is ZSTD_c_jobSize / 2.
  * It's possible to modify the job size to increase or decrease
  * the granularity of the synchronization point.
  * Once the jobSize is smaller than the window size,
  * it will result in compression ratio degradation.
  * NOTE 1: rsyncable mode only works when multithreading is enabled.
  * NOTE 2: rsyncable performs poorly in combination with long range mode,
  * since it will decrease the effectiveness of synchronization points,
  * though mileage may vary.
  * NOTE 3: Rsyncable mode limits maximum compression speed to ~400 MB/s.
  * If the selected compression level is already running significantly slower,
  * the overall speed won't be significantly impacted.
  */
 #define ZSTD_c_rsyncable ZSTD_c_experimentalParam1

/* Select a compression format.
 * The value must be of type ZSTD_format_e.
 * See ZSTD_format_e enum definition for details */
#define ZSTD_c_format ZSTD_c_experimentalParam2

/* Force back-reference distances to remain < windowSize,
 * even when referencing into Dictionary content (default:0) */
#define ZSTD_c_forceMaxWindow ZSTD_c_experimentalParam3

/* Controls whether the contents of a CDict
 * are used in place, or copied into the working context.
 * Accepts values from the ZSTD_dictAttachPref_e enum.
 * See the comments on that enum for an explanation of the feature. */
#define ZSTD_c_forceAttachDict ZSTD_c_experimentalParam4

/* Controls how the literals are compressed (default is auto).
 * The value must be of type ZSTD_literalCompressionMode_e.
 * See ZSTD_literalCompressionMode_t enum definition for details.
 */
#define ZSTD_c_literalCompressionMode ZSTD_c_experimentalParam5

/* Tries to fit compressed block size to be around targetCBlockSize.
 * No target when targetCBlockSize == 0.
 * There is no guarantee on compressed block size (default:0) */
#define ZSTD_c_targetCBlockSize ZSTD_c_experimentalParam6

/* User's best guess of source size.
 * Hint is not valid when srcSizeHint == 0.
 * There is no guarantee that hint is close to actual source size,
 * but compression ratio may regress significantly if guess considerably underestimates */
#define ZSTD_c_srcSizeHint ZSTD_c_experimentalParam7

/*! ZSTD_CCtx_getParameter() :
 *  Get the requested compression parameter value, selected by enum ZSTD_cParameter,
 *  and store it into int* value.
 * @return : 0, or an error code (which can be tested with ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_CCtx_getParameter(ZSTD_CCtx* cctx, ZSTD_cParameter param, int* value);


/*! ZSTD_CCtx_params :
 *  Quick howto :
 *  - ZSTD_createCCtxParams() : Create a ZSTD_CCtx_params structure
 *  - ZSTD_CCtxParams_setParameter() : Push parameters one by one into
 *                                     an existing ZSTD_CCtx_params structure.
 *                                     This is similar to
 *                                     ZSTD_CCtx_setParameter().
 *  - ZSTD_CCtx_setParametersUsingCCtxParams() : Apply parameters to
 *                                    an existing CCtx.
 *                                    These parameters will be applied to
 *                                    all subsequent frames.
 *  - ZSTD_compressStream2() : Do compression using the CCtx.
 *  - ZSTD_freeCCtxParams() : Free the memory.
 *
 *  This can be used with ZSTD_estimateCCtxSize_advanced_usingCCtxParams()
 *  for static allocation of CCtx for single-threaded compression.
 */
ZSTDLIB_API ZSTD_CCtx_params* ZSTD_createCCtxParams(void);
ZSTDLIB_API size_t ZSTD_freeCCtxParams(ZSTD_CCtx_params* params);

/*! ZSTD_CCtxParams_reset() :
 *  Reset params to default values.
 */
ZSTDLIB_API size_t ZSTD_CCtxParams_reset(ZSTD_CCtx_params* params);

/*! ZSTD_CCtxParams_init() :
 *  Initializes the compression parameters of cctxParams according to
 *  compression level. All other parameters are reset to their default values.
 */
ZSTDLIB_API size_t ZSTD_CCtxParams_init(ZSTD_CCtx_params* cctxParams, int compressionLevel);

/*! ZSTD_CCtxParams_init_advanced() :
 *  Initializes the compression and frame parameters of cctxParams according to
 *  params. All other parameters are reset to their default values.
 */
ZSTDLIB_API size_t ZSTD_CCtxParams_init_advanced(ZSTD_CCtx_params* cctxParams, ZSTD_parameters params);

/*! ZSTD_CCtxParams_setParameter() :
 *  Similar to ZSTD_CCtx_setParameter.
 *  Set one compression parameter, selected by enum ZSTD_cParameter.
 *  Parameters must be applied to a ZSTD_CCtx using ZSTD_CCtx_setParametersUsingCCtxParams().
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_CCtxParams_setParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int value);

/*! ZSTD_CCtxParams_getParameter() :
 * Similar to ZSTD_CCtx_getParameter.
 * Get the requested value of one compression parameter, selected by enum ZSTD_cParameter.
 * @result : 0, or an error code (which can be tested with ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_CCtxParams_getParameter(ZSTD_CCtx_params* params, ZSTD_cParameter param, int* value);

/*! ZSTD_CCtx_setParametersUsingCCtxParams() :
 *  Apply a set of ZSTD_CCtx_params to the compression context.
 *  This can be done even after compression is started,
 *    if nbWorkers==0, this will have no impact until a new compression is started.
 *    if nbWorkers>=1, new parameters will be picked up at next job,
 *       with a few restrictions (windowLog, pledgedSrcSize, nbWorkers, jobSize, and overlapLog are not updated).
 */
ZSTDLIB_API size_t ZSTD_CCtx_setParametersUsingCCtxParams(
        ZSTD_CCtx* cctx, const ZSTD_CCtx_params* params);

/*! ZSTD_compressStream2_simpleArgs() :
 *  Same as ZSTD_compressStream2(),
 *  but using only integral types as arguments.
 *  This variant might be helpful for binders from dynamic languages
 *  which have troubles handling structures containing memory pointers.
 */
ZSTDLIB_API size_t ZSTD_compressStream2_simpleArgs (
                            ZSTD_CCtx* cctx,
                            void* dst, size_t dstCapacity, size_t* dstPos,
                      const void* src, size_t srcSize, size_t* srcPos,
                            ZSTD_EndDirective endOp);


/***************************************
*  Advanced decompression functions
***************************************/

/*! ZSTD_isFrame() :
 *  Tells if the content of `buffer` starts with a valid Frame Identifier.
 *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
 *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
 *  Note 3 : Skippable Frame Identifiers are considered valid. */
ZSTDLIB_API unsigned ZSTD_isFrame(const void* buffer, size_t size);

/*! ZSTD_createDDict_byReference() :
 *  Create a digested dictionary, ready to start decompression operation without startup delay.
 *  Dictionary content is referenced, and therefore stays in dictBuffer.
 *  It is important that dictBuffer outlives DDict,
 *  it must remain read accessible throughout the lifetime of DDict */
ZSTDLIB_API ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize);

/*! ZSTD_DCtx_loadDictionary_byReference() :
 *  Same as ZSTD_DCtx_loadDictionary(),
 *  but references `dict` content instead of copying it into `dctx`.
 *  This saves memory if `dict` remains around.,
 *  However, it's imperative that `dict` remains accessible (and unmodified) while being used, so it must outlive decompression. */
ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);

/*! ZSTD_DCtx_loadDictionary_advanced() :
 *  Same as ZSTD_DCtx_loadDictionary(),
 *  but gives direct control over
 *  how to load the dictionary (by copy ? by reference ?)
 *  and how to interpret it (automatic ? force raw mode ? full mode only ?). */
ZSTDLIB_API size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx, const void* dict, size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod, ZSTD_dictContentType_e dictContentType);

/*! ZSTD_DCtx_refPrefix_advanced() :
 *  Same as ZSTD_DCtx_refPrefix(), but gives finer control over
 *  how to interpret prefix content (automatic ? force raw mode (default) ? full mode only ?) */
ZSTDLIB_API size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType);

/*! ZSTD_DCtx_setMaxWindowSize() :
 *  Refuses allocating internal buffers for frames requiring a window size larger than provided limit.
 *  This protects a decoder context from reserving too much memory for itself (potential attack scenario).
 *  This parameter is only useful in streaming mode, since no internal buffer is allocated in single-pass mode.
 *  By default, a decompression context accepts all window sizes <= (1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT)
 * @return : 0, or an error code (which can be tested using ZSTD_isError()).
 */
ZSTDLIB_API size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize);

/* ZSTD_d_format
 * experimental parameter,
 * allowing selection between ZSTD_format_e input compression formats
 */
#define ZSTD_d_format ZSTD_d_experimentalParam1
/* ZSTD_d_stableOutBuffer
 * Experimental parameter.
 * Default is 0 == disabled. Set to 1 to enable.
 *
 * Tells the decompressor that the ZSTD_outBuffer will ALWAYS be the same
 * between calls, except for the modifications that zstd makes to pos (the
 * caller must not modify pos). This is checked by the decompressor, and
 * decompression will fail if it ever changes. Therefore the ZSTD_outBuffer
 * MUST be large enough to fit the entire decompressed frame. This will be
 * checked when the frame content size is known. The data in the ZSTD_outBuffer
 * in the range [dst, dst + pos) MUST not be modified during decompression
 * or you will get data corruption.
 *
 * When this flags is enabled zstd won't allocate an output buffer, because
 * it can write directly to the ZSTD_outBuffer, but it will still allocate
 * an input buffer large enough to fit any compressed block. This will also
 * avoid the memcpy() from the internal output buffer to the ZSTD_outBuffer.
 * If you need to avoid the input buffer allocation use the buffer-less
 * streaming API.
 *
 * NOTE: So long as the ZSTD_outBuffer always points to valid memory, using
 * this flag is ALWAYS memory safe, and will never access out-of-bounds
 * memory. However, decompression WILL fail if you violate the preconditions.
 *
 * WARNING: The data in the ZSTD_outBuffer in the range [dst, dst + pos) MUST
 * not be modified during decompression or you will get data corruption. This
 * is because zstd needs to reference data in the ZSTD_outBuffer to regenerate
 * matches. Normally zstd maintains its own buffer for this purpose, but passing
 * this flag tells zstd to use the user provided buffer.
 */
#define ZSTD_d_stableOutBuffer ZSTD_d_experimentalParam2

/*! ZSTD_DCtx_setFormat() :
 *  Instruct the decoder context about what kind of data to decode next.
 *  This instruction is mandatory to decode data without a fully-formed header,
 *  such ZSTD_f_zstd1_magicless for example.
 * @return : 0, or an error code (which can be tested using ZSTD_isError()). */
ZSTDLIB_API size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format);

/*! ZSTD_decompressStream_simpleArgs() :
 *  Same as ZSTD_decompressStream(),
 *  but using only integral types as arguments.
 *  This can be helpful for binders from dynamic languages
 *  which have troubles handling structures containing memory pointers.
 */
ZSTDLIB_API size_t ZSTD_decompressStream_simpleArgs (
                            ZSTD_DCtx* dctx,
                            void* dst, size_t dstCapacity, size_t* dstPos,
                      const void* src, size_t srcSize, size_t* srcPos);


/********************************************************************
*  Advanced streaming functions
*  Warning : most of these functions are now redundant with the Advanced API.
*  Once Advanced API reaches "stable" status,
*  redundant functions will be deprecated, and then at some point removed.
********************************************************************/

/*=====   Advanced Streaming compression functions  =====*/
/**! ZSTD_initCStream_srcSize() :
 * This function is deprecated, and equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     ZSTD_CCtx_refCDict(zcs, NULL); // clear the dictionary (if any)
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
 *
 * pledgedSrcSize must be correct. If it is not known at init time, use
 * ZSTD_CONTENTSIZE_UNKNOWN. Note that, for compatibility with older programs,
 * "0" also disables frame content size field. It may be enabled in the future.
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t
ZSTD_initCStream_srcSize(ZSTD_CStream* zcs,
                         int compressionLevel,
                         unsigned long long pledgedSrcSize);

/**! ZSTD_initCStream_usingDict() :
 * This function is deprecated, and is equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     ZSTD_CCtx_setParameter(zcs, ZSTD_c_compressionLevel, compressionLevel);
 *     ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
 *
 * Creates of an internal CDict (incompatible with static CCtx), except if
 * dict == NULL or dictSize < 8, in which case no dict is used.
 * Note: dict is loaded with ZSTD_dct_auto (treated as a full zstd dictionary if
 * it begins with ZSTD_MAGIC_DICTIONARY, else as raw content) and ZSTD_dlm_byCopy.
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t
ZSTD_initCStream_usingDict(ZSTD_CStream* zcs,
                     const void* dict, size_t dictSize,
                           int compressionLevel);

/**! ZSTD_initCStream_advanced() :
 * This function is deprecated, and is approximately equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     // Pseudocode: Set each zstd parameter and leave the rest as-is.
 *     for ((param, value) : params) {
 *         ZSTD_CCtx_setParameter(zcs, param, value);
 *     }
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
 *     ZSTD_CCtx_loadDictionary(zcs, dict, dictSize);
 *
 * dict is loaded with ZSTD_dct_auto and ZSTD_dlm_byCopy.
 * pledgedSrcSize must be correct.
 * If srcSize is not known at init time, use value ZSTD_CONTENTSIZE_UNKNOWN.
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t
ZSTD_initCStream_advanced(ZSTD_CStream* zcs,
                    const void* dict, size_t dictSize,
                          ZSTD_parameters params,
                          unsigned long long pledgedSrcSize);

/**! ZSTD_initCStream_usingCDict() :
 * This function is deprecated, and equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     ZSTD_CCtx_refCDict(zcs, cdict);
 *
 * note : cdict will just be referenced, and must outlive compression session
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t ZSTD_initCStream_usingCDict(ZSTD_CStream* zcs, const ZSTD_CDict* cdict);

/**! ZSTD_initCStream_usingCDict_advanced() :
 *   This function is DEPRECATED, and is approximately equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     // Pseudocode: Set each zstd frame parameter and leave the rest as-is.
 *     for ((fParam, value) : fParams) {
 *         ZSTD_CCtx_setParameter(zcs, fParam, value);
 *     }
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
 *     ZSTD_CCtx_refCDict(zcs, cdict);
 *
 * same as ZSTD_initCStream_usingCDict(), with control over frame parameters.
 * pledgedSrcSize must be correct. If srcSize is not known at init time, use
 * value ZSTD_CONTENTSIZE_UNKNOWN.
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t
ZSTD_initCStream_usingCDict_advanced(ZSTD_CStream* zcs,
                               const ZSTD_CDict* cdict,
                                     ZSTD_frameParameters fParams,
                                     unsigned long long pledgedSrcSize);

/*! ZSTD_resetCStream() :
 * This function is deprecated, and is equivalent to:
 *     ZSTD_CCtx_reset(zcs, ZSTD_reset_session_only);
 *     ZSTD_CCtx_setPledgedSrcSize(zcs, pledgedSrcSize);
 *
 *  start a new frame, using same parameters from previous frame.
 *  This is typically useful to skip dictionary loading stage, since it will re-use it in-place.
 *  Note that zcs must be init at least once before using ZSTD_resetCStream().
 *  If pledgedSrcSize is not known at reset time, use macro ZSTD_CONTENTSIZE_UNKNOWN.
 *  If pledgedSrcSize > 0, its value must be correct, as it will be written in header, and controlled at the end.
 *  For the time being, pledgedSrcSize==0 is interpreted as "srcSize unknown" for compatibility with older programs,
 *  but it will change to mean "empty" in future version, so use macro ZSTD_CONTENTSIZE_UNKNOWN instead.
 * @return : 0, or an error code (which can be tested using ZSTD_isError())
 *  Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t ZSTD_resetCStream(ZSTD_CStream* zcs, unsigned long long pledgedSrcSize);


typedef struct {
    unsigned long long ingested;   /* nb input bytes read and buffered */
    unsigned long long consumed;   /* nb input bytes actually compressed */
    unsigned long long produced;   /* nb of compressed bytes generated and buffered */
    unsigned long long flushed;    /* nb of compressed bytes flushed : not provided; can be tracked from caller side */
    unsigned currentJobID;         /* MT only : latest started job nb */
    unsigned nbActiveWorkers;      /* MT only : nb of workers actively compressing at probe time */
} ZSTD_frameProgression;

/* ZSTD_getFrameProgression() :
 * tells how much data has been ingested (read from input)
 * consumed (input actually compressed) and produced (output) for current frame.
 * Note : (ingested - consumed) is amount of input data buffered internally, not yet compressed.
 * Aggregates progression inside active worker threads.
 */
ZSTDLIB_API ZSTD_frameProgression ZSTD_getFrameProgression(const ZSTD_CCtx* cctx);

/*! ZSTD_toFlushNow() :
 *  Tell how many bytes are ready to be flushed immediately.
 *  Useful for multithreading scenarios (nbWorkers >= 1).
 *  Probe the oldest active job, defined as oldest job not yet entirely flushed,
 *  and check its output buffer.
 * @return : amount of data stored in oldest job and ready to be flushed immediately.
 *  if @return == 0, it means either :
 *  + there is no active job (could be checked with ZSTD_frameProgression()), or
 *  + oldest job is still actively compressing data,
 *    but everything it has produced has also been flushed so far,
 *    therefore flush speed is limited by production speed of oldest job
 *    irrespective of the speed of concurrent (and newer) jobs.
 */
ZSTDLIB_API size_t ZSTD_toFlushNow(ZSTD_CCtx* cctx);


/*=====   Advanced Streaming decompression functions  =====*/
/**
 * This function is deprecated, and is equivalent to:
 *
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
 *     ZSTD_DCtx_loadDictionary(zds, dict, dictSize);
 *
 * note: no dictionary will be used if dict == NULL or dictSize < 8
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize);

/**
 * This function is deprecated, and is equivalent to:
 *
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
 *     ZSTD_DCtx_refDDict(zds, ddict);
 *
 * note : ddict is referenced, it must outlive decompression session
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* zds, const ZSTD_DDict* ddict);

/**
 * This function is deprecated, and is equivalent to:
 *
 *     ZSTD_DCtx_reset(zds, ZSTD_reset_session_only);
 *
 * re-use decompression parameters from previous init; saves dictionary loading
 * Note : this prototype will be marked as deprecated and generate compilation warnings on reaching v1.5.x
 */
ZSTDLIB_API size_t ZSTD_resetDStream(ZSTD_DStream* zds);


/*********************************************************************
*  Buffer-less and synchronous inner streaming functions
*
*  This is an advanced API, giving full control over buffer management, for users which need direct control over memory.
*  But it's also a complex one, with several restrictions, documented below.
*  Prefer normal streaming API for an easier experience.
********************************************************************* */

/**
  Buffer-less streaming compression (synchronous mode)

  A ZSTD_CCtx object is required to track streaming operations.
  Use ZSTD_createCCtx() / ZSTD_freeCCtx() to manage resource.
  ZSTD_CCtx object can be re-used multiple times within successive compression operations.

  Start by initializing a context.
  Use ZSTD_compressBegin(), or ZSTD_compressBegin_usingDict() for dictionary compression,
  or ZSTD_compressBegin_advanced(), for finer parameter control.
  It's also possible to duplicate a reference context which has already been initialized, using ZSTD_copyCCtx()

  Then, consume your input using ZSTD_compressContinue().
  There are some important considerations to keep in mind when using this advanced function :
  - ZSTD_compressContinue() has no internal buffer. It uses externally provided buffers only.
  - Interface is synchronous : input is consumed entirely and produces 1+ compressed blocks.
  - Caller must ensure there is enough space in `dst` to store compressed data under worst case scenario.
    Worst case evaluation is provided by ZSTD_compressBound().
    ZSTD_compressContinue() doesn't guarantee recover after a failed compression.
  - ZSTD_compressContinue() presumes prior input ***is still accessible and unmodified*** (up to maximum distance size, see WindowLog).
    It remembers all previous contiguous blocks, plus one separated memory segment (which can itself consists of multiple contiguous blocks)
  - ZSTD_compressContinue() detects that prior input has been overwritten when `src` buffer overlaps.
    In which case, it will "discard" the relevant memory section from its history.

  Finish a frame with ZSTD_compressEnd(), which will write the last block(s) and optional checksum.
  It's possible to use srcSize==0, in which case, it will write a final empty block to end the frame.
  Without last block mark, frames are considered unfinished (hence corrupted) by compliant decoders.

  `ZSTD_CCtx` object can be re-used (ZSTD_compressBegin()) to compress again.
*/

/*=====   Buffer-less streaming compression functions  =====*/
ZSTDLIB_API size_t ZSTD_compressBegin(ZSTD_CCtx* cctx, int compressionLevel);
ZSTDLIB_API size_t ZSTD_compressBegin_usingDict(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, int compressionLevel);
ZSTDLIB_API size_t ZSTD_compressBegin_advanced(ZSTD_CCtx* cctx, const void* dict, size_t dictSize, ZSTD_parameters params, unsigned long long pledgedSrcSize); /**< pledgedSrcSize : If srcSize is not known at init time, use ZSTD_CONTENTSIZE_UNKNOWN */
ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict(ZSTD_CCtx* cctx, const ZSTD_CDict* cdict); /**< note: fails if cdict==NULL */
ZSTDLIB_API size_t ZSTD_compressBegin_usingCDict_advanced(ZSTD_CCtx* const cctx, const ZSTD_CDict* const cdict, ZSTD_frameParameters const fParams, unsigned long long const pledgedSrcSize);   /* compression parameters are already set within cdict. pledgedSrcSize must be correct. If srcSize is not known, use macro ZSTD_CONTENTSIZE_UNKNOWN */
ZSTDLIB_API size_t ZSTD_copyCCtx(ZSTD_CCtx* cctx, const ZSTD_CCtx* preparedCCtx, unsigned long long pledgedSrcSize); /**<  note: if pledgedSrcSize is not known, use ZSTD_CONTENTSIZE_UNKNOWN */

ZSTDLIB_API size_t ZSTD_compressContinue(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
ZSTDLIB_API size_t ZSTD_compressEnd(ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);


/*-
  Buffer-less streaming decompression (synchronous mode)

  A ZSTD_DCtx object is required to track streaming operations.
  Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
  A ZSTD_DCtx object can be re-used multiple times.

  First typical operation is to retrieve frame parameters, using ZSTD_getFrameHeader().
  Frame header is extracted from the beginning of compressed frame, so providing only the frame's beginning is enough.
  Data fragment must be large enough to ensure successful decoding.
 `ZSTD_frameHeaderSize_max` bytes is guaranteed to always be large enough.
  @result : 0 : successful decoding, the `ZSTD_frameHeader` structure is correctly filled.
           >0 : `srcSize` is too small, please provide at least @result bytes on next attempt.
           errorCode, which can be tested using ZSTD_isError().

  It fills a ZSTD_frameHeader structure with important information to correctly decode the frame,
  such as the dictionary ID, content size, or maximum back-reference distance (`windowSize`).
  Note that these values could be wrong, either because of data corruption, or because a 3rd party deliberately spoofs false information.
  As a consequence, check that values remain within valid application range.
  For example, do not allocate memory blindly, check that `windowSize` is within expectation.
  Each application can set its own limits, depending on local restrictions.
  For extended interoperability, it is recommended to support `windowSize` of at least 8 MB.

  ZSTD_decompressContinue() needs previous data blocks during decompression, up to `windowSize` bytes.
  ZSTD_decompressContinue() is very sensitive to contiguity,
  if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
  or that previous contiguous segment is large enough to properly handle maximum back-reference distance.
  There are multiple ways to guarantee this condition.

  The most memory efficient way is to use a round buffer of sufficient size.
  Sufficient size is determined by invoking ZSTD_decodingBufferSize_min(),
  which can @return an error code if required value is too large for current system (in 32-bits mode).
  In a round buffer methodology, ZSTD_decompressContinue() decompresses each block next to previous one,
  up to the moment there is not enough room left in the buffer to guarantee decoding another full block,
  which maximum size is provided in `ZSTD_frameHeader` structure, field `blockSizeMax`.
  At which point, decoding can resume from the beginning of the buffer.
  Note that already decoded data stored in the buffer should be flushed before being overwritten.

  There are alternatives possible, for example using two or more buffers of size `windowSize` each, though they consume more memory.

  Finally, if you control the compression process, you can also ignore all buffer size rules,
  as long as the encoder and decoder progress in "lock-step",
  aka use exactly the same buffer sizes, break contiguity at the same place, etc.

  Once buffers are setup, start decompression, with ZSTD_decompressBegin().
  If decompression requires a dictionary, use ZSTD_decompressBegin_usingDict() or ZSTD_decompressBegin_usingDDict().

  Then use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
  ZSTD_nextSrcSizeToDecompress() tells how many bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  ZSTD_decompressContinue() requires this _exact_ amount of bytes, or it will fail.

 @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
  It can be zero : it just means ZSTD_decompressContinue() has decoded some metadata item.
  It can also be an error code, which can be tested with ZSTD_isError().

  A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
  Context can then be reset to start a new decompression.

  Note : it's possible to know if next input to present is a header or a block, using ZSTD_nextInputType().
  This information is not required to properly decode a frame.

  == Special case : skippable frames ==

  Skippable frames allow integration of user-defined data into a flow of concatenated frames.
  Skippable frames will be ignored (skipped) by decompressor.
  The format of skippable frames is as follows :
  a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
  b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
  c) Frame Content - any content (User Data) of length equal to Frame Size
  For skippable frames ZSTD_getFrameHeader() returns zfhPtr->frameType==ZSTD_skippableFrame.
  For skippable frames ZSTD_decompressContinue() always returns 0 : it only skips the content.
*/

/*=====   Buffer-less streaming decompression functions  =====*/
typedef enum { ZSTD_frame, ZSTD_skippableFrame } ZSTD_frameType_e;
typedef struct {
    unsigned long long frameContentSize; /* if == ZSTD_CONTENTSIZE_UNKNOWN, it means this field is not available. 0 means "empty" */
    unsigned long long windowSize;       /* can be very large, up to <= frameContentSize */
    unsigned blockSizeMax;
    ZSTD_frameType_e frameType;          /* if == ZSTD_skippableFrame, frameContentSize is the size of skippable content */
    unsigned headerSize;
    unsigned dictID;
    unsigned checksumFlag;
} ZSTD_frameHeader;

/*! ZSTD_getFrameHeader() :
 *  decode Frame Header, or requires larger `srcSize`.
 * @return : 0, `zfhPtr` is correctly filled,
 *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
 *           or an error code, which can be tested using ZSTD_isError() */
ZSTDLIB_API size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
/*! ZSTD_getFrameHeader_advanced() :
 *  same as ZSTD_getFrameHeader(),
 *  with added capability to select a format (like ZSTD_f_zstd1_magicless) */
ZSTDLIB_API size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format);
ZSTDLIB_API size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize);  /**< when frame content size is not known, pass in frameContentSize == ZSTD_CONTENTSIZE_UNKNOWN */

ZSTDLIB_API size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx);
ZSTDLIB_API size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize);
ZSTDLIB_API size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);

ZSTDLIB_API size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
ZSTDLIB_API size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);

/* misc */
ZSTDLIB_API void   ZSTD_copyDCtx(ZSTD_DCtx* dctx, const ZSTD_DCtx* preparedDCtx);
typedef enum { ZSTDnit_frameHeader, ZSTDnit_blockHeader, ZSTDnit_block, ZSTDnit_lastBlock, ZSTDnit_checksum, ZSTDnit_skippableFrame } ZSTD_nextInputType_e;
ZSTDLIB_API ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx);




/* ============================ */
/**       Block level API       */
/* ============================ */

/*!
    Block functions produce and decode raw zstd blocks, without frame metadata.
    Frame metadata cost is typically ~12 bytes, which can be non-negligible for very small blocks (< 100 bytes).
    But users will have to take in charge needed metadata to regenerate data, such as compressed and content sizes.

    A few rules to respect :
    - Compressing and decompressing require a context structure
      + Use ZSTD_createCCtx() and ZSTD_createDCtx()
    - It is necessary to init context before starting
      + compression : any ZSTD_compressBegin*() variant, including with dictionary
      + decompression : any ZSTD_decompressBegin*() variant, including with dictionary
      + copyCCtx() and copyDCtx() can be used too
    - Block size is limited, it must be <= ZSTD_getBlockSize() <= ZSTD_BLOCKSIZE_MAX == 128 KB
      + If input is larger than a block size, it's necessary to split input data into multiple blocks
      + For inputs larger than a single block, consider using regular ZSTD_compress() instead.
        Frame metadata is not that costly, and quickly becomes negligible as source size grows larger than a block.
    - When a block is considered not compressible enough, ZSTD_compressBlock() result will be 0 (zero) !
      ===> In which case, nothing is produced into `dst` !
      + User __must__ test for such outcome and deal directly with uncompressed data
      + A block cannot be declared incompressible if ZSTD_compressBlock() return value was != 0.
        Doing so would mess up with statistics history, leading to potential data corruption.
      + ZSTD_decompressBlock() _doesn't accept uncompressed data as input_ !!
      + In case of multiple successive blocks, should some of them be uncompressed,
        decoder must be informed of their existence in order to follow proper history.
        Use ZSTD_insertBlock() for such a case.
*/

/*=====   Raw zstd block functions  =====*/
ZSTDLIB_API size_t ZSTD_getBlockSize   (const ZSTD_CCtx* cctx);
ZSTDLIB_API size_t ZSTD_compressBlock  (ZSTD_CCtx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
ZSTDLIB_API size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
ZSTDLIB_API size_t ZSTD_insertBlock    (ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize);  /**< insert uncompressed block into `dctx` history. Useful for multi-blocks decompression. */


#endif   /* ZSTD_H_ZSTD_STATIC_LINKING_ONLY */

#if defined (__cplusplus)
}
#endif
/**** ended inlining ../zstd.h ****/
#define FSE_STATIC_LINKING_ONLY
/**** skipping file: fse.h ****/
#define HUF_STATIC_LINKING_ONLY
/**** skipping file: huf.h ****/
#ifndef XXH_STATIC_LINKING_ONLY
#  define XXH_STATIC_LINKING_ONLY  /* XXH64_state_t */
#endif
/**** start inlining xxhash.h ****/
/*
 * xxHash - Extremely Fast Hash algorithm
 * Header File
 * Copyright (c) 2012-2020, Yann Collet, Facebook, Inc.
 *
 * You can contact the author at :
 * - xxHash source repository : https://github.com/Cyan4973/xxHash
 * 
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
*/

/* Notice extracted from xxHash homepage :

xxHash is an extremely fast Hash algorithm, running at RAM speed limits.
It also successfully passes all tests from the SMHasher suite.

Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)

Name            Speed       Q.Score   Author
xxHash          5.4 GB/s     10
CrapWow         3.2 GB/s      2       Andrew
MumurHash 3a    2.7 GB/s     10       Austin Appleby
SpookyHash      2.0 GB/s     10       Bob Jenkins
SBox            1.4 GB/s      9       Bret Mulvey
Lookup3         1.2 GB/s      9       Bob Jenkins
SuperFastHash   1.2 GB/s      1       Paul Hsieh
CityHash64      1.05 GB/s    10       Pike & Alakuijala
FNV             0.55 GB/s     5       Fowler, Noll, Vo
CRC32           0.43 GB/s     9
MD5-32          0.33 GB/s    10       Ronald L. Rivest
SHA1-32         0.28 GB/s    10

Q.Score is a measure of quality of the hash function.
It depends on successfully passing SMHasher test set.
10 is a perfect score.

A 64-bits version, named XXH64, is available since r35.
It offers much better speed, but for 64-bits applications only.
Name     Speed on 64 bits    Speed on 32 bits
XXH64       13.8 GB/s            1.9 GB/s
XXH32        6.8 GB/s            6.0 GB/s
*/

#if defined (__cplusplus)
extern "C" {
#endif

#ifndef XXHASH_H_5627135585666179
#define XXHASH_H_5627135585666179 1


/* ****************************
*  Definitions
******************************/
#include <stddef.h>   /* size_t */
typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;


/* ****************************
*  API modifier
******************************/
/** XXH_PRIVATE_API
*   This is useful if you want to include xxhash functions in `static` mode
*   in order to inline them, and remove their symbol from the public list.
*   Methodology :
*     #define XXH_PRIVATE_API
*     #include "xxhash.h"
*   `xxhash.c` is automatically included.
*   It's not useful to compile and link it as a separate module anymore.
*/
#ifdef XXH_PRIVATE_API
#  ifndef XXH_STATIC_LINKING_ONLY
#    define XXH_STATIC_LINKING_ONLY
#  endif
#  if defined(__GNUC__)
#    define XXH_PUBLIC_API static __inline __attribute__((unused))
#  elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
#    define XXH_PUBLIC_API static inline
#  elif defined(_MSC_VER)
#    define XXH_PUBLIC_API static __inline
#  else
#    define XXH_PUBLIC_API static   /* this version may generate warnings for unused static functions; disable the relevant warning */
#  endif
#else
#  define XXH_PUBLIC_API   /* do nothing */
#endif /* XXH_PRIVATE_API */

/*!XXH_NAMESPACE, aka Namespace Emulation :

If you want to include _and expose_ xxHash functions from within your own library,
but also want to avoid symbol collisions with another library which also includes xxHash,

you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library
with the value of XXH_NAMESPACE (so avoid to keep it NULL and avoid numeric values).

Note that no change is required within the calling program as long as it includes `xxhash.h` :
regular symbol name will be automatically translated by this header.
*/
#ifdef XXH_NAMESPACE
#  define XXH_CAT(A,B) A##B
#  define XXH_NAME2(A,B) XXH_CAT(A,B)
#  define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32)
#  define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64)
#  define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber)
#  define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState)
#  define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState)
#  define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState)
#  define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState)
#  define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset)
#  define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset)
#  define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update)
#  define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update)
#  define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest)
#  define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest)
#  define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState)
#  define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState)
#  define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash)
#  define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash)
#  define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical)
#  define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical)
#endif


/* *************************************
*  Version
***************************************/
#define XXH_VERSION_MAJOR    0
#define XXH_VERSION_MINOR    6
#define XXH_VERSION_RELEASE  2
#define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)
XXH_PUBLIC_API unsigned XXH_versionNumber (void);


/* ****************************
*  Simple Hash Functions
******************************/
typedef unsigned int       XXH32_hash_t;
typedef unsigned long long XXH64_hash_t;

XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed);
XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed);

/*!
XXH32() :
    Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input".
    The memory between input & input+length must be valid (allocated and read-accessible).
    "seed" can be used to alter the result predictably.
    Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s
XXH64() :
    Calculate the 64-bits hash of sequence of length "len" stored at memory address "input".
    "seed" can be used to alter the result predictably.
    This function runs 2x faster on 64-bits systems, but slower on 32-bits systems (see benchmark).
*/


/* ****************************
*  Streaming Hash Functions
******************************/
typedef struct XXH32_state_s XXH32_state_t;   /* incomplete type */
typedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */

/*! State allocation, compatible with dynamic libraries */

XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void);
XXH_PUBLIC_API XXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);

XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void);
XXH_PUBLIC_API XXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);


/* hash streaming */

XXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, unsigned int seed);
XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);
XXH_PUBLIC_API XXH32_hash_t  XXH32_digest (const XXH32_state_t* statePtr);

XXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH64_state_t* statePtr, unsigned long long seed);
XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);
XXH_PUBLIC_API XXH64_hash_t  XXH64_digest (const XXH64_state_t* statePtr);

/*
These functions generate the xxHash of an input provided in multiple segments.
Note that, for small input, they are slower than single-call functions, due to state management.
For small input, prefer `XXH32()` and `XXH64()` .

XXH state must first be allocated, using XXH*_createState() .

Start a new hash by initializing state with a seed, using XXH*_reset().

Then, feed the hash state by calling XXH*_update() as many times as necessary.
Obviously, input must be allocated and read accessible.
The function returns an error code, with 0 meaning OK, and any other value meaning there is an error.

Finally, a hash value can be produced anytime, by using XXH*_digest().
This function returns the nn-bits hash as an int or long long.

It's still possible to continue inserting input into the hash state after a digest,
and generate some new hashes later on, by calling again XXH*_digest().

When done, free XXH state space if it was allocated dynamically.
*/


/* **************************
*  Utils
****************************/
#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L))   /* ! C99 */
#  define restrict   /* disable restrict */
#endif

XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dst_state, const XXH32_state_t* restrict src_state);
XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dst_state, const XXH64_state_t* restrict src_state);


/* **************************
*  Canonical representation
****************************/
/* Default result type for XXH functions are primitive unsigned 32 and 64 bits.
*  The canonical representation uses human-readable write convention, aka big-endian (large digits first).
*  These functions allow transformation of hash result into and from its canonical format.
*  This way, hash values can be written into a file / memory, and remain comparable on different systems and programs.
*/
typedef struct { unsigned char digest[4]; } XXH32_canonical_t;
typedef struct { unsigned char digest[8]; } XXH64_canonical_t;

XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash);
XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash);

XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);
XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src);

#endif /* XXHASH_H_5627135585666179 */



/* ================================================================================================
   This section contains definitions which are not guaranteed to remain stable.
   They may change in future versions, becoming incompatible with a different version of the library.
   They shall only be used with static linking.
   Never use these definitions in association with dynamic linking !
=================================================================================================== */
#if defined(XXH_STATIC_LINKING_ONLY) && !defined(XXH_STATIC_H_3543687687345)
#define XXH_STATIC_H_3543687687345

/* These definitions are only meant to allow allocation of XXH state
   statically, on stack, or in a struct for example.
   Do not use members directly. */

   struct XXH32_state_s {
       unsigned total_len_32;
       unsigned large_len;
       unsigned v1;
       unsigned v2;
       unsigned v3;
       unsigned v4;
       unsigned mem32[4];   /* buffer defined as U32 for alignment */
       unsigned memsize;
       unsigned reserved;   /* never read nor write, will be removed in a future version */
   };   /* typedef'd to XXH32_state_t */

   struct XXH64_state_s {
       unsigned long long total_len;
       unsigned long long v1;
       unsigned long long v2;
       unsigned long long v3;
       unsigned long long v4;
       unsigned long long mem64[4];   /* buffer defined as U64 for alignment */
       unsigned memsize;
       unsigned reserved[2];          /* never read nor write, will be removed in a future version */
   };   /* typedef'd to XXH64_state_t */


#  ifdef XXH_PRIVATE_API
/**** start inlining xxhash.c ****/
/*
 *  xxHash - Fast Hash algorithm
 *  Copyright (c) 2012-2020, Yann Collet, Facebook, Inc.
 *
 *  You can contact the author at :
 *  - xxHash homepage: http://www.xxhash.com
 *  - xxHash source repository : https://github.com/Cyan4973/xxHash
 * 
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
*/


/* *************************************
*  Tuning parameters
***************************************/
/*!XXH_FORCE_MEMORY_ACCESS :
 * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
 * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
 * The below switch allow to select different access method for improved performance.
 * Method 0 (default) : use `memcpy()`. Safe and portable.
 * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
 *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
 * Method 2 : direct access. This method doesn't depend on compiler but violate C standard.
 *            It can generate buggy code on targets which do not support unaligned memory accesses.
 *            But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
 * See http://stackoverflow.com/a/32095106/646947 for details.
 * Prefer these methods in priority order (0 > 1 > 2)
 */
#ifndef XXH_FORCE_MEMORY_ACCESS   /* can be defined externally, on command line for example */
#  if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
#    define XXH_FORCE_MEMORY_ACCESS 2
#  elif (defined(__INTEL_COMPILER) && !defined(WIN32)) || \
  (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) )) || \
  defined(__ICCARM__)
#    define XXH_FORCE_MEMORY_ACCESS 1
#  endif
#endif

/*!XXH_ACCEPT_NULL_INPUT_POINTER :
 * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.
 * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.
 * By default, this option is disabled. To enable it, uncomment below define :
 */
/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */

/*!XXH_FORCE_NATIVE_FORMAT :
 * By default, xxHash library provides endian-independent Hash values, based on little-endian convention.
 * Results are therefore identical for little-endian and big-endian CPU.
 * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.
 * Should endian-independence be of no importance for your application, you may set the #define below to 1,
 * to improve speed for Big-endian CPU.
 * This option has no impact on Little_Endian CPU.
 */
#ifndef XXH_FORCE_NATIVE_FORMAT   /* can be defined externally */
#  define XXH_FORCE_NATIVE_FORMAT 0
#endif

/*!XXH_FORCE_ALIGN_CHECK :
 * This is a minor performance trick, only useful with lots of very small keys.
 * It means : check for aligned/unaligned input.
 * The check costs one initial branch per hash; set to 0 when the input data
 * is guaranteed to be aligned.
 */
#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */
#  if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
#    define XXH_FORCE_ALIGN_CHECK 0
#  else
#    define XXH_FORCE_ALIGN_CHECK 1
#  endif
#endif


/* *************************************
*  Includes & Memory related functions
***************************************/
/* Modify the local functions below should you wish to use some other memory routines */
/* for malloc(), free() */
#include <stddef.h>     /* size_t */
static void* XXH_malloc(size_t s) { return malloc(s); }
static void  XXH_free  (void* p)  { free(p); }
/* for memcpy() */
static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); }

#ifndef XXH_STATIC_LINKING_ONLY
#  define XXH_STATIC_LINKING_ONLY
#endif
/**** skipping file: xxhash.h ****/


/* *************************************
*  Compiler Specific Options
***************************************/
#if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || defined(__cplusplus) || defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
#  define INLINE_KEYWORD inline
#else
#  define INLINE_KEYWORD
#endif

#if defined(__GNUC__) || defined(__ICCARM__)
#  define FORCE_INLINE_ATTR __attribute__((always_inline))
#elif defined(_MSC_VER)
#  define FORCE_INLINE_ATTR __forceinline
#else
#  define FORCE_INLINE_ATTR
#endif

#define FORCE_INLINE_TEMPLATE static INLINE_KEYWORD FORCE_INLINE_ATTR


#ifdef _MSC_VER
#  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */
#endif


/* *************************************
*  Basic Types
***************************************/
#ifndef MEM_MODULE
# define MEM_MODULE
# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
#   include <stdint.h>
    typedef uint8_t  BYTE;
    typedef uint16_t U16;
    typedef uint32_t U32;
    typedef  int32_t S32;
    typedef uint64_t U64;
#  else
    typedef unsigned char      BYTE;
    typedef unsigned short     U16;
    typedef unsigned int       U32;
    typedef   signed int       S32;
    typedef unsigned long long U64;   /* if your compiler doesn't support unsigned long long, replace by another 64-bit type here. Note that xxhash.h will also need to be updated. */
#  endif
#endif


#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))

/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */
static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; }
static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; }

#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))

/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
/* currently only defined for gcc and icc */
typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign;

static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
static U64 XXH_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }

#else

/* portable and safe solution. Generally efficient.
 * see : http://stackoverflow.com/a/32095106/646947
 */

static U32 XXH_read32(const void* memPtr)
{
    U32 val;
    memcpy(&val, memPtr, sizeof(val));
    return val;
}

static U64 XXH_read64(const void* memPtr)
{
    U64 val;
    memcpy(&val, memPtr, sizeof(val));
    return val;
}

#endif   /* XXH_FORCE_DIRECT_MEMORY_ACCESS */


/* ****************************************
*  Compiler-specific Functions and Macros
******************************************/
#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)

/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */
#if defined(_MSC_VER)
#  define XXH_rotl32(x,r) _rotl(x,r)
#  define XXH_rotl64(x,r) _rotl64(x,r)
#else
#if defined(__ICCARM__)
#  include <intrinsics.h>
#  define XXH_rotl32(x,r) __ROR(x,(32 - r))
#else
#  define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))
#endif
#  define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))
#endif

#if defined(_MSC_VER)     /* Visual Studio */
#  define XXH_swap32 _byteswap_ulong
#  define XXH_swap64 _byteswap_uint64
#elif GCC_VERSION >= 403
#  define XXH_swap32 __builtin_bswap32
#  define XXH_swap64 __builtin_bswap64
#else
static U32 XXH_swap32 (U32 x)
{
    return  ((x << 24) & 0xff000000 ) |
            ((x <<  8) & 0x00ff0000 ) |
            ((x >>  8) & 0x0000ff00 ) |
            ((x >> 24) & 0x000000ff );
}
static U64 XXH_swap64 (U64 x)
{
    return  ((x << 56) & 0xff00000000000000ULL) |
            ((x << 40) & 0x00ff000000000000ULL) |
            ((x << 24) & 0x0000ff0000000000ULL) |
            ((x << 8)  & 0x000000ff00000000ULL) |
            ((x >> 8)  & 0x00000000ff000000ULL) |
            ((x >> 24) & 0x0000000000ff0000ULL) |
            ((x >> 40) & 0x000000000000ff00ULL) |
            ((x >> 56) & 0x00000000000000ffULL);
}
#endif


/* *************************************
*  Architecture Macros
***************************************/
typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;

/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */
#ifndef XXH_CPU_LITTLE_ENDIAN
    static const int g_one = 1;
#   define XXH_CPU_LITTLE_ENDIAN   (*(const char*)(&g_one))
#endif


/* ***************************
*  Memory reads
*****************************/
typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;

FORCE_INLINE_TEMPLATE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
{
    if (align==XXH_unaligned)
        return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
    else
        return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr);
}

FORCE_INLINE_TEMPLATE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)
{
    return XXH_readLE32_align(ptr, endian, XXH_unaligned);
}

static U32 XXH_readBE32(const void* ptr)
{
    return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr);
}

FORCE_INLINE_TEMPLATE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
{
    if (align==XXH_unaligned)
        return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
    else
        return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr);
}

FORCE_INLINE_TEMPLATE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)
{
    return XXH_readLE64_align(ptr, endian, XXH_unaligned);
}

static U64 XXH_readBE64(const void* ptr)
{
    return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr);
}


/* *************************************
*  Macros
***************************************/
#define XXH_STATIC_ASSERT(c)   { enum { XXH_static_assert = 1/(int)(!!(c)) }; }    /* use only *after* variable declarations */


/* *************************************
*  Constants
***************************************/
static const U32 PRIME32_1 = 2654435761U;
static const U32 PRIME32_2 = 2246822519U;
static const U32 PRIME32_3 = 3266489917U;
static const U32 PRIME32_4 =  668265263U;
static const U32 PRIME32_5 =  374761393U;

static const U64 PRIME64_1 = 11400714785074694791ULL;
static const U64 PRIME64_2 = 14029467366897019727ULL;
static const U64 PRIME64_3 =  1609587929392839161ULL;
static const U64 PRIME64_4 =  9650029242287828579ULL;
static const U64 PRIME64_5 =  2870177450012600261ULL;

XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; }


/* **************************
*  Utils
****************************/
XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* restrict dstState, const XXH32_state_t* restrict srcState)
{
    memcpy(dstState, srcState, sizeof(*dstState));
}

XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* restrict dstState, const XXH64_state_t* restrict srcState)
{
    memcpy(dstState, srcState, sizeof(*dstState));
}


/* ***************************
*  Simple Hash Functions
*****************************/

static U32 XXH32_round(U32 seed, U32 input)
{
    seed += input * PRIME32_2;
    seed  = XXH_rotl32(seed, 13);
    seed *= PRIME32_1;
    return seed;
}

FORCE_INLINE_TEMPLATE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)
{
    const BYTE* p = (const BYTE*)input;
    const BYTE* bEnd = p + len;
    U32 h32;
#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align)

#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
    if (p==NULL) {
        len=0;
        bEnd=p=(const BYTE*)(size_t)16;
    }
#endif

    if (len>=16) {
        const BYTE* const limit = bEnd - 16;
        U32 v1 = seed + PRIME32_1 + PRIME32_2;
        U32 v2 = seed + PRIME32_2;
        U32 v3 = seed + 0;
        U32 v4 = seed - PRIME32_1;

        do {
            v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4;
            v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4;
            v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4;
            v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4;
        } while (p<=limit);

        h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);
    } else {
        h32  = seed + PRIME32_5;
    }

    h32 += (U32) len;

    while (p+4<=bEnd) {
        h32 += XXH_get32bits(p) * PRIME32_3;
        h32  = XXH_rotl32(h32, 17) * PRIME32_4 ;
        p+=4;
    }

    while (p<bEnd) {
        h32 += (*p) * PRIME32_5;
        h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;
        p++;
    }

    h32 ^= h32 >> 15;
    h32 *= PRIME32_2;
    h32 ^= h32 >> 13;
    h32 *= PRIME32_3;
    h32 ^= h32 >> 16;

    return h32;
}


XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed)
{
#if 0
    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
    XXH32_CREATESTATE_STATIC(state);
    XXH32_reset(state, seed);
    XXH32_update(state, input, len);
    return XXH32_digest(state);
#else
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if (XXH_FORCE_ALIGN_CHECK) {
        if ((((size_t)input) & 3) == 0) {   /* Input is 4-bytes aligned, leverage the speed benefit */
            if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
                return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
            else
                return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
    }   }

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
    else
        return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
#endif
}


static U64 XXH64_round(U64 acc, U64 input)
{
    acc += input * PRIME64_2;
    acc  = XXH_rotl64(acc, 31);
    acc *= PRIME64_1;
    return acc;
}

static U64 XXH64_mergeRound(U64 acc, U64 val)
{
    val  = XXH64_round(0, val);
    acc ^= val;
    acc  = acc * PRIME64_1 + PRIME64_4;
    return acc;
}

FORCE_INLINE_TEMPLATE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)
{
    const BYTE* p = (const BYTE*)input;
    const BYTE* const bEnd = p + len;
    U64 h64;
#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align)

#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
    if (p==NULL) {
        len=0;
        bEnd=p=(const BYTE*)(size_t)32;
    }
#endif

    if (len>=32) {
        const BYTE* const limit = bEnd - 32;
        U64 v1 = seed + PRIME64_1 + PRIME64_2;
        U64 v2 = seed + PRIME64_2;
        U64 v3 = seed + 0;
        U64 v4 = seed - PRIME64_1;

        do {
            v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8;
            v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8;
            v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8;
            v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8;
        } while (p<=limit);

        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
        h64 = XXH64_mergeRound(h64, v1);
        h64 = XXH64_mergeRound(h64, v2);
        h64 = XXH64_mergeRound(h64, v3);
        h64 = XXH64_mergeRound(h64, v4);

    } else {
        h64  = seed + PRIME64_5;
    }

    h64 += (U64) len;

    while (p+8<=bEnd) {
        U64 const k1 = XXH64_round(0, XXH_get64bits(p));
        h64 ^= k1;
        h64  = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
        p+=8;
    }

    if (p+4<=bEnd) {
        h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1;
        h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
        p+=4;
    }

    while (p<bEnd) {
        h64 ^= (*p) * PRIME64_5;
        h64 = XXH_rotl64(h64, 11) * PRIME64_1;
        p++;
    }

    h64 ^= h64 >> 33;
    h64 *= PRIME64_2;
    h64 ^= h64 >> 29;
    h64 *= PRIME64_3;
    h64 ^= h64 >> 32;

    return h64;
}


XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)
{
#if 0
    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */
    XXH64_CREATESTATE_STATIC(state);
    XXH64_reset(state, seed);
    XXH64_update(state, input, len);
    return XXH64_digest(state);
#else
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if (XXH_FORCE_ALIGN_CHECK) {
        if ((((size_t)input) & 7)==0) {  /* Input is aligned, let's leverage the speed advantage */
            if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
                return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);
            else
                return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);
    }   }

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);
    else
        return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);
#endif
}


/* **************************************************
*  Advanced Hash Functions
****************************************************/

XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void)
{
    return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));
}
XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)
{
    XXH_free(statePtr);
    return XXH_OK;
}

XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void)
{
    return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));
}
XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)
{
    XXH_free(statePtr);
    return XXH_OK;
}


/*** Hash feed ***/

XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed)
{
    XXH32_state_t state;   /* using a local state to memcpy() in order to avoid strict-aliasing warnings */
    memset(&state, 0, sizeof(state)-4);   /* do not write into reserved, for future removal */
    state.v1 = seed + PRIME32_1 + PRIME32_2;
    state.v2 = seed + PRIME32_2;
    state.v3 = seed + 0;
    state.v4 = seed - PRIME32_1;
    memcpy(statePtr, &state, sizeof(state));
    return XXH_OK;
}


XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed)
{
    XXH64_state_t state;   /* using a local state to memcpy() in order to avoid strict-aliasing warnings */
    memset(&state, 0, sizeof(state)-8);   /* do not write into reserved, for future removal */
    state.v1 = seed + PRIME64_1 + PRIME64_2;
    state.v2 = seed + PRIME64_2;
    state.v3 = seed + 0;
    state.v4 = seed - PRIME64_1;
    memcpy(statePtr, &state, sizeof(state));
    return XXH_OK;
}


FORCE_INLINE_TEMPLATE XXH_errorcode XXH32_update_endian (XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian)
{
    const BYTE* p = (const BYTE*)input;
    const BYTE* const bEnd = p + len;

#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
    if (input==NULL) return XXH_ERROR;
#endif

    state->total_len_32 += (unsigned)len;
    state->large_len |= (len>=16) | (state->total_len_32>=16);

    if (state->memsize + len < 16)  {   /* fill in tmp buffer */
        XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len);
        state->memsize += (unsigned)len;
        return XXH_OK;
    }

    if (state->memsize) {   /* some data left from previous update */
        XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize);
        {   const U32* p32 = state->mem32;
            state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++;
            state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++;
            state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++;
            state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++;
        }
        p += 16-state->memsize;
        state->memsize = 0;
    }

    if (p <= bEnd-16) {
        const BYTE* const limit = bEnd - 16;
        U32 v1 = state->v1;
        U32 v2 = state->v2;
        U32 v3 = state->v3;
        U32 v4 = state->v4;

        do {
            v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4;
            v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4;
            v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4;
            v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4;
        } while (p<=limit);

        state->v1 = v1;
        state->v2 = v2;
        state->v3 = v3;
        state->v4 = v4;
    }

    if (p < bEnd) {
        XXH_memcpy(state->mem32, p, (size_t)(bEnd-p));
        state->memsize = (unsigned)(bEnd-p);
    }

    return XXH_OK;
}

XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
{
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
    else
        return XXH32_update_endian(state_in, input, len, XXH_bigEndian);
}



FORCE_INLINE_TEMPLATE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)
{
    const BYTE * p = (const BYTE*)state->mem32;
    const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize;
    U32 h32;

    if (state->large_len) {
        h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);
    } else {
        h32 = state->v3 /* == seed */ + PRIME32_5;
    }

    h32 += state->total_len_32;

    while (p+4<=bEnd) {
        h32 += XXH_readLE32(p, endian) * PRIME32_3;
        h32  = XXH_rotl32(h32, 17) * PRIME32_4;
        p+=4;
    }

    while (p<bEnd) {
        h32 += (*p) * PRIME32_5;
        h32  = XXH_rotl32(h32, 11) * PRIME32_1;
        p++;
    }

    h32 ^= h32 >> 15;
    h32 *= PRIME32_2;
    h32 ^= h32 >> 13;
    h32 *= PRIME32_3;
    h32 ^= h32 >> 16;

    return h32;
}


XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in)
{
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH32_digest_endian(state_in, XXH_littleEndian);
    else
        return XXH32_digest_endian(state_in, XXH_bigEndian);
}



/* **** XXH64 **** */

FORCE_INLINE_TEMPLATE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian)
{
    const BYTE* p = (const BYTE*)input;
    const BYTE* const bEnd = p + len;

#ifdef XXH_ACCEPT_NULL_INPUT_POINTER
    if (input==NULL) return XXH_ERROR;
#endif

    state->total_len += len;

    if (state->memsize + len < 32) {  /* fill in tmp buffer */
        if (input != NULL) {
            XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len);
        }
        state->memsize += (U32)len;
        return XXH_OK;
    }

    if (state->memsize) {   /* tmp buffer is full */
        XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize);
        state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian));
        state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian));
        state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian));
        state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian));
        p += 32-state->memsize;
        state->memsize = 0;
    }

    if (p+32 <= bEnd) {
        const BYTE* const limit = bEnd - 32;
        U64 v1 = state->v1;
        U64 v2 = state->v2;
        U64 v3 = state->v3;
        U64 v4 = state->v4;

        do {
            v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8;
            v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8;
            v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8;
            v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8;
        } while (p<=limit);

        state->v1 = v1;
        state->v2 = v2;
        state->v3 = v3;
        state->v4 = v4;
    }

    if (p < bEnd) {
        XXH_memcpy(state->mem64, p, (size_t)(bEnd-p));
        state->memsize = (unsigned)(bEnd-p);
    }

    return XXH_OK;
}

XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
{
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
    else
        return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
}



FORCE_INLINE_TEMPLATE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian)
{
    const BYTE * p = (const BYTE*)state->mem64;
    const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize;
    U64 h64;

    if (state->total_len >= 32) {
        U64 const v1 = state->v1;
        U64 const v2 = state->v2;
        U64 const v3 = state->v3;
        U64 const v4 = state->v4;

        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);
        h64 = XXH64_mergeRound(h64, v1);
        h64 = XXH64_mergeRound(h64, v2);
        h64 = XXH64_mergeRound(h64, v3);
        h64 = XXH64_mergeRound(h64, v4);
    } else {
        h64  = state->v3 + PRIME64_5;
    }

    h64 += (U64) state->total_len;

    while (p+8<=bEnd) {
        U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian));
        h64 ^= k1;
        h64  = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;
        p+=8;
    }

    if (p+4<=bEnd) {
        h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1;
        h64  = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;
        p+=4;
    }

    while (p<bEnd) {
        h64 ^= (*p) * PRIME64_5;
        h64  = XXH_rotl64(h64, 11) * PRIME64_1;
        p++;
    }

    h64 ^= h64 >> 33;
    h64 *= PRIME64_2;
    h64 ^= h64 >> 29;
    h64 *= PRIME64_3;
    h64 ^= h64 >> 32;

    return h64;
}


XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in)
{
    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;

    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
        return XXH64_digest_endian(state_in, XXH_littleEndian);
    else
        return XXH64_digest_endian(state_in, XXH_bigEndian);
}


/* **************************
*  Canonical representation
****************************/

/*! Default XXH result types are basic unsigned 32 and 64 bits.
*   The canonical representation follows human-readable write convention, aka big-endian (large digits first).
*   These functions allow transformation of hash result into and from its canonical format.
*   This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs.
*/

XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash)
{
    XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));
    if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash);
    memcpy(dst, &hash, sizeof(*dst));
}

XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash)
{
    XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));
    if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash);
    memcpy(dst, &hash, sizeof(*dst));
}

XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src)
{
    return XXH_readBE32(src);
}

XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src)
{
    return XXH_readBE64(src);
}
/**** ended inlining xxhash.c ****/
#  endif

#endif /* XXH_STATIC_LINKING_ONLY && XXH_STATIC_H_3543687687345 */


#if defined (__cplusplus)
}
#endif
/**** ended inlining xxhash.h ****/

#if defined (__cplusplus)
extern "C" {
#endif

/* ---- static assert (debug) --- */
#define ZSTD_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)
#define ZSTD_isError ERR_isError   /* for inlining */
#define FSE_isError  ERR_isError
#define HUF_isError  ERR_isError


/*-*************************************
*  shared macros
***************************************/
#undef MIN
#undef MAX
#define MIN(a,b) ((a)<(b) ? (a) : (b))
#define MAX(a,b) ((a)>(b) ? (a) : (b))

/**
 * Ignore: this is an internal helper.
 *
 * This is a helper function to help force C99-correctness during compilation.
 * Under strict compilation modes, variadic macro arguments can't be empty.
 * However, variadic function arguments can be. Using a function therefore lets
 * us statically check that at least one (string) argument was passed,
 * independent of the compilation flags.
 */
static INLINE_KEYWORD UNUSED_ATTR
void _force_has_format_string(const char *format, ...) {
  (void)format;
}

/**
 * Ignore: this is an internal helper.
 *
 * We want to force this function invocation to be syntactically correct, but
 * we don't want to force runtime evaluation of its arguments.
 */
#define _FORCE_HAS_FORMAT_STRING(...) \
  if (0) { \
    _force_has_format_string(__VA_ARGS__); \
  }

/**
 * Return the specified error if the condition evaluates to true.
 *
 * In debug modes, prints additional information.
 * In order to do that (particularly, printing the conditional that failed),
 * this can't just wrap RETURN_ERROR().
 */
#define RETURN_ERROR_IF(cond, err, ...) \
  if (cond) { \
    RAWLOG(3, "%s:%d: ERROR!: check %s failed, returning %s", \
           __FILE__, __LINE__, ZSTD_QUOTE(cond), ZSTD_QUOTE(ERROR(err))); \
    _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
    RAWLOG(3, ": " __VA_ARGS__); \
    RAWLOG(3, "\n"); \
    return ERROR(err); \
  }

/**
 * Unconditionally return the specified error.
 *
 * In debug modes, prints additional information.
 */
#define RETURN_ERROR(err, ...) \
  do { \
    RAWLOG(3, "%s:%d: ERROR!: unconditional check failed, returning %s", \
           __FILE__, __LINE__, ZSTD_QUOTE(ERROR(err))); \
    _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
    RAWLOG(3, ": " __VA_ARGS__); \
    RAWLOG(3, "\n"); \
    return ERROR(err); \
  } while(0);

/**
 * If the provided expression evaluates to an error code, returns that error code.
 *
 * In debug modes, prints additional information.
 */
#define FORWARD_IF_ERROR(err, ...) \
  do { \
    size_t const err_code = (err); \
    if (ERR_isError(err_code)) { \
      RAWLOG(3, "%s:%d: ERROR!: forwarding error in %s: %s", \
             __FILE__, __LINE__, ZSTD_QUOTE(err), ERR_getErrorName(err_code)); \
      _FORCE_HAS_FORMAT_STRING(__VA_ARGS__); \
      RAWLOG(3, ": " __VA_ARGS__); \
      RAWLOG(3, "\n"); \
      return err_code; \
    } \
  } while(0);


/*-*************************************
*  Common constants
***************************************/
#define ZSTD_OPT_NUM    (1<<12)

#define ZSTD_REP_NUM      3                 /* number of repcodes */
#define ZSTD_REP_MOVE     (ZSTD_REP_NUM-1)
static const U32 repStartValue[ZSTD_REP_NUM] = { 1, 4, 8 };

#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)

#define BIT7 128
#define BIT6  64
#define BIT5  32
#define BIT4  16
#define BIT1   2
#define BIT0   1

#define ZSTD_WINDOWLOG_ABSOLUTEMIN 10
static const size_t ZSTD_fcs_fieldSize[4] = { 0, 2, 4, 8 };
static const size_t ZSTD_did_fieldSize[4] = { 0, 1, 2, 4 };

#define ZSTD_FRAMEIDSIZE 4   /* magic number size */

#define ZSTD_BLOCKHEADERSIZE 3   /* C standard doesn't allow `static const` variable to be init using another `static const` variable */
static const size_t ZSTD_blockHeaderSize = ZSTD_BLOCKHEADERSIZE;
typedef enum { bt_raw, bt_rle, bt_compressed, bt_reserved } blockType_e;

#define ZSTD_FRAMECHECKSUMSIZE 4

#define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
#define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */)   /* for a non-null block */

#define HufLog 12
typedef enum { set_basic, set_rle, set_compressed, set_repeat } symbolEncodingType_e;

#define LONGNBSEQ 0x7F00

#define MINMATCH 3

#define Litbits  8
#define MaxLit ((1<<Litbits) - 1)
#define MaxML   52
#define MaxLL   35
#define DefaultMaxOff 28
#define MaxOff  31
#define MaxSeq MAX(MaxLL, MaxML)   /* Assumption : MaxOff < MaxLL,MaxML */
#define MLFSELog    9
#define LLFSELog    9
#define OffFSELog   8
#define MaxFSELog  MAX(MAX(MLFSELog, LLFSELog), OffFSELog)

static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0,
                                      1, 1, 1, 1, 2, 2, 3, 3,
                                      4, 6, 7, 8, 9,10,11,12,
                                     13,14,15,16 };
static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2,
                                             2, 2, 2, 2, 2, 1, 1, 1,
                                             2, 2, 2, 2, 2, 2, 2, 2,
                                             2, 3, 2, 1, 1, 1, 1, 1,
                                            -1,-1,-1,-1 };
#define LL_DEFAULTNORMLOG 6  /* for static allocation */
static const U32 LL_defaultNormLog = LL_DEFAULTNORMLOG;

static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0,
                                      0, 0, 0, 0, 0, 0, 0, 0,
                                      1, 1, 1, 1, 2, 2, 3, 3,
                                      4, 4, 5, 7, 8, 9,10,11,
                                     12,13,14,15,16 };
static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2,
                                             2, 1, 1, 1, 1, 1, 1, 1,
                                             1, 1, 1, 1, 1, 1, 1, 1,
                                             1, 1, 1, 1, 1, 1, 1, 1,
                                             1, 1, 1, 1, 1, 1, 1, 1,
                                             1, 1, 1, 1, 1, 1,-1,-1,
                                            -1,-1,-1,-1,-1 };
#define ML_DEFAULTNORMLOG 6  /* for static allocation */
static const U32 ML_defaultNormLog = ML_DEFAULTNORMLOG;

static const S16 OF_defaultNorm[DefaultMaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2,
                                                     2, 1, 1, 1, 1, 1, 1, 1,
                                                     1, 1, 1, 1, 1, 1, 1, 1,
                                                    -1,-1,-1,-1,-1 };
#define OF_DEFAULTNORMLOG 5  /* for static allocation */
static const U32 OF_defaultNormLog = OF_DEFAULTNORMLOG;


/*-*******************************************
*  Shared functions to include for inlining
*********************************************/
static void ZSTD_copy8(void* dst, const void* src) {
#ifdef __aarch64__
    vst1_u8((uint8_t*)dst, vld1_u8((const uint8_t*)src));
#else
    memcpy(dst, src, 8);
#endif
}

#define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
static void ZSTD_copy16(void* dst, const void* src) {
#ifdef __aarch64__
    vst1q_u8((uint8_t*)dst, vld1q_u8((const uint8_t*)src));
#else
    memcpy(dst, src, 16);
#endif
}
#define COPY16(d,s) { ZSTD_copy16(d,s); d+=16; s+=16; }

#define WILDCOPY_OVERLENGTH 32
#define WILDCOPY_VECLEN 16

typedef enum {
    ZSTD_no_overlap,
    ZSTD_overlap_src_before_dst
    /*  ZSTD_overlap_dst_before_src, */
} ZSTD_overlap_e;

/*! ZSTD_wildcopy() :
 *  Custom version of memcpy(), can over read/write up to WILDCOPY_OVERLENGTH bytes (if length==0)
 *  @param ovtype controls the overlap detection
 *         - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
 *         - ZSTD_overlap_src_before_dst: The src and dst may overlap, but they MUST be at least 8 bytes apart.
 *           The src buffer must be before the dst buffer.
 */
MEM_STATIC FORCE_INLINE_ATTR 
void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length, ZSTD_overlap_e const ovtype)
{
    ptrdiff_t diff = (BYTE*)dst - (const BYTE*)src;
    const BYTE* ip = (const BYTE*)src;
    BYTE* op = (BYTE*)dst;
    BYTE* const oend = op + length;

    assert(diff >= 8 || (ovtype == ZSTD_no_overlap && diff <= -WILDCOPY_VECLEN));

    if (ovtype == ZSTD_overlap_src_before_dst && diff < WILDCOPY_VECLEN) {
        /* Handle short offset copies. */
        do {
            COPY8(op, ip)
        } while (op < oend);
    } else {
        assert(diff >= WILDCOPY_VECLEN || diff <= -WILDCOPY_VECLEN);
        /* Separate out the first COPY16() call because the copy length is
         * almost certain to be short, so the branches have different
         * probabilities. Since it is almost certain to be short, only do
         * one COPY16() in the first call. Then, do two calls per loop since
         * at that point it is more likely to have a high trip count.
         */
#ifndef __aarch64__
        do {
            COPY16(op, ip);
        }
        while (op < oend);
#else
        COPY16(op, ip);
        if (op >= oend) return;
        do {
            COPY16(op, ip);
            COPY16(op, ip);
        }
        while (op < oend);
#endif
    }
}

MEM_STATIC size_t ZSTD_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
{
    size_t const length = MIN(dstCapacity, srcSize);
    if (length > 0) {
        memcpy(dst, src, length);
    }
    return length;
}

/* define "workspace is too large" as this number of times larger than needed */
#define ZSTD_WORKSPACETOOLARGE_FACTOR 3

/* when workspace is continuously too large
 * during at least this number of times,
 * context's memory usage is considered wasteful,
 * because it's sized to handle a worst case scenario which rarely happens.
 * In which case, resize it down to free some memory */
#define ZSTD_WORKSPACETOOLARGE_MAXDURATION 128


/*-*******************************************
*  Private declarations
*********************************************/
typedef struct seqDef_s {
    U32 offset;
    U16 litLength;
    U16 matchLength;
} seqDef;

typedef struct {
    seqDef* sequencesStart;
    seqDef* sequences;
    BYTE* litStart;
    BYTE* lit;
    BYTE* llCode;
    BYTE* mlCode;
    BYTE* ofCode;
    size_t maxNbSeq;
    size_t maxNbLit;
    U32   longLengthID;   /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */
    U32   longLengthPos;
} seqStore_t;

typedef struct {
    U32 litLength;
    U32 matchLength;
} ZSTD_sequenceLength;

/**
 * Returns the ZSTD_sequenceLength for the given sequences. It handles the decoding of long sequences
 * indicated by longLengthPos and longLengthID, and adds MINMATCH back to matchLength.
 */
MEM_STATIC ZSTD_sequenceLength ZSTD_getSequenceLength(seqStore_t const* seqStore, seqDef const* seq)
{
    ZSTD_sequenceLength seqLen;
    seqLen.litLength = seq->litLength;
    seqLen.matchLength = seq->matchLength + MINMATCH;
    if (seqStore->longLengthPos == (U32)(seq - seqStore->sequencesStart)) {
        if (seqStore->longLengthID == 1) {
            seqLen.litLength += 0xFFFF;
        }
        if (seqStore->longLengthID == 2) {
            seqLen.matchLength += 0xFFFF;
        }
    }
    return seqLen;
}

/**
 * Contains the compressed frame size and an upper-bound for the decompressed frame size.
 * Note: before using `compressedSize`, check for errors using ZSTD_isError().
 *       similarly, before using `decompressedBound`, check for errors using:
 *          `decompressedBound != ZSTD_CONTENTSIZE_ERROR`
 */
typedef struct {
    size_t compressedSize;
    unsigned long long decompressedBound;
} ZSTD_frameSizeInfo;   /* decompress & legacy */

const seqStore_t* ZSTD_getSeqStore(const ZSTD_CCtx* ctx);   /* compress & dictBuilder */
void ZSTD_seqToCodes(const seqStore_t* seqStorePtr);   /* compress, dictBuilder, decodeCorpus (shouldn't get its definition from here) */

/* custom memory allocation functions */
void* ZSTD_malloc(size_t size, ZSTD_customMem customMem);
void* ZSTD_calloc(size_t size, ZSTD_customMem customMem);
void ZSTD_free(void* ptr, ZSTD_customMem customMem);


MEM_STATIC U32 ZSTD_highbit32(U32 val)   /* compress, dictBuilder, decodeCorpus */
{
    assert(val != 0);
    {
#   if defined(_MSC_VER)   /* Visual */
        unsigned long r=0;
        return _BitScanReverse(&r, val) ? (unsigned)r : 0;
#   elif defined(__GNUC__) && (__GNUC__ >= 3)   /* GCC Intrinsic */
        return __builtin_clz (val) ^ 31;
#   elif defined(__ICCARM__)    /* IAR Intrinsic */
        return 31 - __CLZ(val);
#   else   /* Software version */
        static const U32 DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
        U32 v = val;
        v |= v >> 1;
        v |= v >> 2;
        v |= v >> 4;
        v |= v >> 8;
        v |= v >> 16;
        return DeBruijnClz[(v * 0x07C4ACDDU) >> 27];
#   endif
    }
}


/* ZSTD_invalidateRepCodes() :
 * ensures next compression will not use repcodes from previous block.
 * Note : only works with regular variant;
 *        do not use with extDict variant ! */
void ZSTD_invalidateRepCodes(ZSTD_CCtx* cctx);   /* zstdmt, adaptive_compression (shouldn't get this definition from here) */


typedef struct {
    blockType_e blockType;
    U32 lastBlock;
    U32 origSize;
} blockProperties_t;   /* declared here for decompress and fullbench */

/*! ZSTD_getcBlockSize() :
 *  Provides the size of compressed block from block header `src` */
/* Used by: decompress, fullbench (does not get its definition from here) */
size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
                          blockProperties_t* bpPtr);

/*! ZSTD_decodeSeqHeaders() :
 *  decode sequence header from src */
/* Used by: decompress, fullbench (does not get its definition from here) */
size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
                       const void* src, size_t srcSize);


#if defined (__cplusplus)
}
#endif

#endif   /* ZSTD_CCOMMON_H_MODULE */
/**** ended inlining zstd_internal.h ****/


/*-****************************************
*  Version
******************************************/
unsigned ZSTD_versionNumber(void) { return ZSTD_VERSION_NUMBER; }

const char* ZSTD_versionString(void) { return ZSTD_VERSION_STRING; }


/*-****************************************
*  ZSTD Error Management
******************************************/
#undef ZSTD_isError   /* defined within zstd_internal.h */
/*! ZSTD_isError() :
 *  tells if a return value is an error code
 *  symbol is required for external callers */
unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }

/*! ZSTD_getErrorName() :
 *  provides error code string from function result (useful for debugging) */
const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); }

/*! ZSTD_getError() :
 *  convert a `size_t` function result into a proper ZSTD_errorCode enum */
ZSTD_ErrorCode ZSTD_getErrorCode(size_t code) { return ERR_getErrorCode(code); }

/*! ZSTD_getErrorString() :
 *  provides error code string from enum */
const char* ZSTD_getErrorString(ZSTD_ErrorCode code) { return ERR_getErrorString(code); }



/*=**************************************************************
*  Custom allocator
****************************************************************/
void* ZSTD_malloc(size_t size, ZSTD_customMem customMem)
{
    if (customMem.customAlloc)
        return customMem.customAlloc(customMem.opaque, size);
    return malloc(size);
}

void* ZSTD_calloc(size_t size, ZSTD_customMem customMem)
{
    if (customMem.customAlloc) {
        /* calloc implemented as malloc+memset;
         * not as efficient as calloc, but next best guess for custom malloc */
        void* const ptr = customMem.customAlloc(customMem.opaque, size);
        memset(ptr, 0, size);
        return ptr;
    }
    return calloc(1, size);
}

void ZSTD_free(void* ptr, ZSTD_customMem customMem)
{
    if (ptr!=NULL) {
        if (customMem.customFree)
            customMem.customFree(customMem.opaque, ptr);
        else
            free(ptr);
    }
}
/**** ended inlining common/zstd_common.c ****/

/**** start inlining decompress/huf_decompress.c ****/
/* ******************************************************************
 * huff0 huffman decoder,
 * part of Finite State Entropy library
 * Copyright (c) 2013-2020, Yann Collet, Facebook, Inc.
 *
 *  You can contact the author at :
 *  - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
****************************************************************** */

/* **************************************************************
*  Dependencies
****************************************************************/
/**** skipping file: ../common/compiler.h ****/
/**** skipping file: ../common/bitstream.h ****/
/**** skipping file: ../common/fse.h ****/
#define HUF_STATIC_LINKING_ONLY
/**** skipping file: ../common/huf.h ****/
/**** skipping file: ../common/error_private.h ****/

/* **************************************************************
*  Macros
****************************************************************/

/* These two optional macros force the use one way or another of the two
 * Huffman decompression implementations. You can't force in both directions
 * at the same time.
 */
#if defined(HUF_FORCE_DECOMPRESS_X1) && \
    defined(HUF_FORCE_DECOMPRESS_X2)
#error "Cannot force the use of the X1 and X2 decoders at the same time!"
#endif


/* **************************************************************
*  Error Management
****************************************************************/
#define HUF_isError ERR_isError


/* **************************************************************
*  Byte alignment for workSpace management
****************************************************************/
#define HUF_ALIGN(x, a)         HUF_ALIGN_MASK((x), (a) - 1)
#define HUF_ALIGN_MASK(x, mask) (((x) + (mask)) & ~(mask))


/* **************************************************************
*  BMI2 Variant Wrappers
****************************************************************/
#if DYNAMIC_BMI2

#define HUF_DGEN(fn)                                                        \
                                                                            \
    static size_t fn##_default(                                             \
                  void* dst,  size_t dstSize,                               \
            const void* cSrc, size_t cSrcSize,                              \
            const HUF_DTable* DTable)                                       \
    {                                                                       \
        return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable);             \
    }                                                                       \
                                                                            \
    static TARGET_ATTRIBUTE("bmi2") size_t fn##_bmi2(                       \
                  void* dst,  size_t dstSize,                               \
            const void* cSrc, size_t cSrcSize,                              \
            const HUF_DTable* DTable)                                       \
    {                                                                       \
        return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable);             \
    }                                                                       \
                                                                            \
    static size_t fn(void* dst, size_t dstSize, void const* cSrc,           \
                     size_t cSrcSize, HUF_DTable const* DTable, int bmi2)   \
    {                                                                       \
        if (bmi2) {                                                         \
            return fn##_bmi2(dst, dstSize, cSrc, cSrcSize, DTable);         \
        }                                                                   \
        return fn##_default(dst, dstSize, cSrc, cSrcSize, DTable);          \
    }

#else

#define HUF_DGEN(fn)                                                        \
    static size_t fn(void* dst, size_t dstSize, void const* cSrc,           \
                     size_t cSrcSize, HUF_DTable const* DTable, int bmi2)   \
    {                                                                       \
        (void)bmi2;                                                         \
        return fn##_body(dst, dstSize, cSrc, cSrcSize, DTable);             \
    }

#endif


/*-***************************/
/*  generic DTableDesc       */
/*-***************************/
typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc;

static DTableDesc HUF_getDTableDesc(const HUF_DTable* table)
{
    DTableDesc dtd;
    memcpy(&dtd, table, sizeof(dtd));
    return dtd;
}


#ifndef HUF_FORCE_DECOMPRESS_X2

/*-***************************/
/*  single-symbol decoding   */
/*-***************************/
typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX1;   /* single-symbol decoding */

size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize)
{
    U32 tableLog = 0;
    U32 nbSymbols = 0;
    size_t iSize;
    void* const dtPtr = DTable + 1;
    HUF_DEltX1* const dt = (HUF_DEltX1*)dtPtr;

    U32* rankVal;
    BYTE* huffWeight;
    size_t spaceUsed32 = 0;

    rankVal = (U32 *)workSpace + spaceUsed32;
    spaceUsed32 += HUF_TABLELOG_ABSOLUTEMAX + 1;
    huffWeight = (BYTE *)((U32 *)workSpace + spaceUsed32);
    spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2;

    if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge);

    DEBUG_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUF_DTable));
    /* memset(huffWeight, 0, sizeof(huffWeight)); */   /* is not necessary, even though some analyzer complain ... */

    iSize = HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
    if (HUF_isError(iSize)) return iSize;

    /* Table header */
    {   DTableDesc dtd = HUF_getDTableDesc(DTable);
        if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge);   /* DTable too small, Huffman tree cannot fit in */
        dtd.tableType = 0;
        dtd.tableLog = (BYTE)tableLog;
        memcpy(DTable, &dtd, sizeof(dtd));
    }

    /* Calculate starting value for each rank */
    {   U32 n, nextRankStart = 0;
        for (n=1; n<tableLog+1; n++) {
            U32 const current = nextRankStart;
            nextRankStart += (rankVal[n] << (n-1));
            rankVal[n] = current;
    }   }

    /* fill DTable */
    {   U32 n;
        size_t const nEnd = nbSymbols;
        for (n=0; n<nEnd; n++) {
            size_t const w = huffWeight[n];
            size_t const length = (1 << w) >> 1;
            size_t const uStart = rankVal[w];
            size_t const uEnd = uStart + length;
            size_t u;
            HUF_DEltX1 D;
            D.byte = (BYTE)n;
            D.nbBits = (BYTE)(tableLog + 1 - w);
            rankVal[w] = (U32)uEnd;
            if (length < 4) {
                /* Use length in the loop bound so the compiler knows it is short. */
                for (u = 0; u < length; ++u)
                    dt[uStart + u] = D;
            } else {
                /* Unroll the loop 4 times, we know it is a power of 2. */
                for (u = uStart; u < uEnd; u += 4) {
                    dt[u + 0] = D;
                    dt[u + 1] = D;
                    dt[u + 2] = D;
                    dt[u + 3] = D;
    }   }   }   }
    return iSize;
}

size_t HUF_readDTableX1(HUF_DTable* DTable, const void* src, size_t srcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_readDTableX1_wksp(DTable, src, srcSize,
                                 workSpace, sizeof(workSpace));
}

FORCE_INLINE_TEMPLATE BYTE
HUF_decodeSymbolX1(BIT_DStream_t* Dstream, const HUF_DEltX1* dt, const U32 dtLog)
{
    size_t const val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
    BYTE const c = dt[val].byte;
    BIT_skipBits(Dstream, dt[val].nbBits);
    return c;
}

#define HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr) \
    *ptr++ = HUF_decodeSymbolX1(DStreamPtr, dt, dtLog)

#define HUF_DECODE_SYMBOLX1_1(ptr, DStreamPtr)  \
    if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
        HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)

#define HUF_DECODE_SYMBOLX1_2(ptr, DStreamPtr) \
    if (MEM_64bits()) \
        HUF_DECODE_SYMBOLX1_0(ptr, DStreamPtr)

HINT_INLINE size_t
HUF_decodeStreamX1(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX1* const dt, const U32 dtLog)
{
    BYTE* const pStart = p;

    /* up to 4 symbols at a time */
    while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-3)) {
        HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
        HUF_DECODE_SYMBOLX1_1(p, bitDPtr);
        HUF_DECODE_SYMBOLX1_2(p, bitDPtr);
        HUF_DECODE_SYMBOLX1_0(p, bitDPtr);
    }

    /* [0-3] symbols remaining */
    if (MEM_32bits())
        while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd))
            HUF_DECODE_SYMBOLX1_0(p, bitDPtr);

    /* no more data to retrieve from bitstream, no need to reload */
    while (p < pEnd)
        HUF_DECODE_SYMBOLX1_0(p, bitDPtr);

    return pEnd-pStart;
}

FORCE_INLINE_TEMPLATE size_t
HUF_decompress1X1_usingDTable_internal_body(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    BYTE* op = (BYTE*)dst;
    BYTE* const oend = op + dstSize;
    const void* dtPtr = DTable + 1;
    const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;
    BIT_DStream_t bitD;
    DTableDesc const dtd = HUF_getDTableDesc(DTable);
    U32 const dtLog = dtd.tableLog;

    CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );

    HUF_decodeStreamX1(op, &bitD, oend, dt, dtLog);

    if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);

    return dstSize;
}

FORCE_INLINE_TEMPLATE size_t
HUF_decompress4X1_usingDTable_internal_body(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    /* Check */
    if (cSrcSize < 10) return ERROR(corruption_detected);  /* strict minimum : jump table + 1 byte per stream */

    {   const BYTE* const istart = (const BYTE*) cSrc;
        BYTE* const ostart = (BYTE*) dst;
        BYTE* const oend = ostart + dstSize;
        BYTE* const olimit = oend - 3;
        const void* const dtPtr = DTable + 1;
        const HUF_DEltX1* const dt = (const HUF_DEltX1*)dtPtr;

        /* Init */
        BIT_DStream_t bitD1;
        BIT_DStream_t bitD2;
        BIT_DStream_t bitD3;
        BIT_DStream_t bitD4;
        size_t const length1 = MEM_readLE16(istart);
        size_t const length2 = MEM_readLE16(istart+2);
        size_t const length3 = MEM_readLE16(istart+4);
        size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
        const BYTE* const istart1 = istart + 6;  /* jumpTable */
        const BYTE* const istart2 = istart1 + length1;
        const BYTE* const istart3 = istart2 + length2;
        const BYTE* const istart4 = istart3 + length3;
        const size_t segmentSize = (dstSize+3) / 4;
        BYTE* const opStart2 = ostart + segmentSize;
        BYTE* const opStart3 = opStart2 + segmentSize;
        BYTE* const opStart4 = opStart3 + segmentSize;
        BYTE* op1 = ostart;
        BYTE* op2 = opStart2;
        BYTE* op3 = opStart3;
        BYTE* op4 = opStart4;
        DTableDesc const dtd = HUF_getDTableDesc(DTable);
        U32 const dtLog = dtd.tableLog;
        U32 endSignal = 1;

        if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
        CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
        CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
        CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
        CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );

        /* up to 16 symbols per loop (4 symbols per stream) in 64-bit mode */
        for ( ; (endSignal) & (op4 < olimit) ; ) {
            HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX1_1(op1, &bitD1);
            HUF_DECODE_SYMBOLX1_1(op2, &bitD2);
            HUF_DECODE_SYMBOLX1_1(op3, &bitD3);
            HUF_DECODE_SYMBOLX1_1(op4, &bitD4);
            HUF_DECODE_SYMBOLX1_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX1_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX1_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX1_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX1_0(op1, &bitD1);
            HUF_DECODE_SYMBOLX1_0(op2, &bitD2);
            HUF_DECODE_SYMBOLX1_0(op3, &bitD3);
            HUF_DECODE_SYMBOLX1_0(op4, &bitD4);
            endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
            endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
            endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
            endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
        }

        /* check corruption */
        /* note : should not be necessary : op# advance in lock step, and we control op4.
         *        but curiously, binary generated by gcc 7.2 & 7.3 with -mbmi2 runs faster when >=1 test is present */
        if (op1 > opStart2) return ERROR(corruption_detected);
        if (op2 > opStart3) return ERROR(corruption_detected);
        if (op3 > opStart4) return ERROR(corruption_detected);
        /* note : op4 supposed already verified within main loop */

        /* finish bitStreams one by one */
        HUF_decodeStreamX1(op1, &bitD1, opStart2, dt, dtLog);
        HUF_decodeStreamX1(op2, &bitD2, opStart3, dt, dtLog);
        HUF_decodeStreamX1(op3, &bitD3, opStart4, dt, dtLog);
        HUF_decodeStreamX1(op4, &bitD4, oend,     dt, dtLog);

        /* check */
        { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
          if (!endCheck) return ERROR(corruption_detected); }

        /* decoded size */
        return dstSize;
    }
}


typedef size_t (*HUF_decompress_usingDTable_t)(void *dst, size_t dstSize,
                                               const void *cSrc,
                                               size_t cSrcSize,
                                               const HUF_DTable *DTable);

HUF_DGEN(HUF_decompress1X1_usingDTable_internal)
HUF_DGEN(HUF_decompress4X1_usingDTable_internal)



size_t HUF_decompress1X1_usingDTable(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    DTableDesc dtd = HUF_getDTableDesc(DTable);
    if (dtd.tableType != 0) return ERROR(GENERIC);
    return HUF_decompress1X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
}

size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize)
{
    const BYTE* ip = (const BYTE*) cSrc;

    size_t const hSize = HUF_readDTableX1_wksp(DCtx, cSrc, cSrcSize, workSpace, wkspSize);
    if (HUF_isError(hSize)) return hSize;
    if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
    ip += hSize; cSrcSize -= hSize;

    return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0);
}


size_t HUF_decompress1X1_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize,
                              const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress1X1_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize,
                                       workSpace, sizeof(workSpace));
}

size_t HUF_decompress1X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX);
    return HUF_decompress1X1_DCtx (DTable, dst, dstSize, cSrc, cSrcSize);
}

size_t HUF_decompress4X1_usingDTable(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    DTableDesc dtd = HUF_getDTableDesc(DTable);
    if (dtd.tableType != 0) return ERROR(GENERIC);
    return HUF_decompress4X1_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
}

static size_t HUF_decompress4X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize, int bmi2)
{
    const BYTE* ip = (const BYTE*) cSrc;

    size_t const hSize = HUF_readDTableX1_wksp (dctx, cSrc, cSrcSize,
                                                workSpace, wkspSize);
    if (HUF_isError(hSize)) return hSize;
    if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
    ip += hSize; cSrcSize -= hSize;

    return HUF_decompress4X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
}

size_t HUF_decompress4X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize)
{
    return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, 0);
}


size_t HUF_decompress4X1_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
                                       workSpace, sizeof(workSpace));
}
size_t HUF_decompress4X1 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    HUF_CREATE_STATIC_DTABLEX1(DTable, HUF_TABLELOG_MAX);
    return HUF_decompress4X1_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
}

#endif /* HUF_FORCE_DECOMPRESS_X2 */


#ifndef HUF_FORCE_DECOMPRESS_X1

/* *************************/
/* double-symbols decoding */
/* *************************/

typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX2;  /* double-symbols decoding */
typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
typedef U32 rankValCol_t[HUF_TABLELOG_MAX + 1];
typedef rankValCol_t rankVal_t[HUF_TABLELOG_MAX];


/* HUF_fillDTableX2Level2() :
 * `rankValOrigin` must be a table of at least (HUF_TABLELOG_MAX + 1) U32 */
static void HUF_fillDTableX2Level2(HUF_DEltX2* DTable, U32 sizeLog, const U32 consumed,
                           const U32* rankValOrigin, const int minWeight,
                           const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
                           U32 nbBitsBaseline, U16 baseSeq)
{
    HUF_DEltX2 DElt;
    U32 rankVal[HUF_TABLELOG_MAX + 1];

    /* get pre-calculated rankVal */
    memcpy(rankVal, rankValOrigin, sizeof(rankVal));

    /* fill skipped values */
    if (minWeight>1) {
        U32 i, skipSize = rankVal[minWeight];
        MEM_writeLE16(&(DElt.sequence), baseSeq);
        DElt.nbBits   = (BYTE)(consumed);
        DElt.length   = 1;
        for (i = 0; i < skipSize; i++)
            DTable[i] = DElt;
    }

    /* fill DTable */
    {   U32 s; for (s=0; s<sortedListSize; s++) {   /* note : sortedSymbols already skipped */
            const U32 symbol = sortedSymbols[s].symbol;
            const U32 weight = sortedSymbols[s].weight;
            const U32 nbBits = nbBitsBaseline - weight;
            const U32 length = 1 << (sizeLog-nbBits);
            const U32 start = rankVal[weight];
            U32 i = start;
            const U32 end = start + length;

            MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
            DElt.nbBits = (BYTE)(nbBits + consumed);
            DElt.length = 2;
            do { DTable[i++] = DElt; } while (i<end);   /* since length >= 1 */

            rankVal[weight] += length;
    }   }
}


static void HUF_fillDTableX2(HUF_DEltX2* DTable, const U32 targetLog,
                           const sortedSymbol_t* sortedList, const U32 sortedListSize,
                           const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
                           const U32 nbBitsBaseline)
{
    U32 rankVal[HUF_TABLELOG_MAX + 1];
    const int scaleLog = nbBitsBaseline - targetLog;   /* note : targetLog >= srcLog, hence scaleLog <= 1 */
    const U32 minBits  = nbBitsBaseline - maxWeight;
    U32 s;

    memcpy(rankVal, rankValOrigin, sizeof(rankVal));

    /* fill DTable */
    for (s=0; s<sortedListSize; s++) {
        const U16 symbol = sortedList[s].symbol;
        const U32 weight = sortedList[s].weight;
        const U32 nbBits = nbBitsBaseline - weight;
        const U32 start = rankVal[weight];
        const U32 length = 1 << (targetLog-nbBits);

        if (targetLog-nbBits >= minBits) {   /* enough room for a second symbol */
            U32 sortedRank;
            int minWeight = nbBits + scaleLog;
            if (minWeight < 1) minWeight = 1;
            sortedRank = rankStart[minWeight];
            HUF_fillDTableX2Level2(DTable+start, targetLog-nbBits, nbBits,
                           rankValOrigin[nbBits], minWeight,
                           sortedList+sortedRank, sortedListSize-sortedRank,
                           nbBitsBaseline, symbol);
        } else {
            HUF_DEltX2 DElt;
            MEM_writeLE16(&(DElt.sequence), symbol);
            DElt.nbBits = (BYTE)(nbBits);
            DElt.length = 1;
            {   U32 const end = start + length;
                U32 u;
                for (u = start; u < end; u++) DTable[u] = DElt;
        }   }
        rankVal[weight] += length;
    }
}

size_t HUF_readDTableX2_wksp(HUF_DTable* DTable,
                       const void* src, size_t srcSize,
                             void* workSpace, size_t wkspSize)
{
    U32 tableLog, maxW, sizeOfSort, nbSymbols;
    DTableDesc dtd = HUF_getDTableDesc(DTable);
    U32 const maxTableLog = dtd.maxTableLog;
    size_t iSize;
    void* dtPtr = DTable+1;   /* force compiler to avoid strict-aliasing */
    HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr;
    U32 *rankStart;

    rankValCol_t* rankVal;
    U32* rankStats;
    U32* rankStart0;
    sortedSymbol_t* sortedSymbol;
    BYTE* weightList;
    size_t spaceUsed32 = 0;

    rankVal = (rankValCol_t *)((U32 *)workSpace + spaceUsed32);
    spaceUsed32 += (sizeof(rankValCol_t) * HUF_TABLELOG_MAX) >> 2;
    rankStats = (U32 *)workSpace + spaceUsed32;
    spaceUsed32 += HUF_TABLELOG_MAX + 1;
    rankStart0 = (U32 *)workSpace + spaceUsed32;
    spaceUsed32 += HUF_TABLELOG_MAX + 2;
    sortedSymbol = (sortedSymbol_t *)workSpace + (spaceUsed32 * sizeof(U32)) / sizeof(sortedSymbol_t);
    spaceUsed32 += HUF_ALIGN(sizeof(sortedSymbol_t) * (HUF_SYMBOLVALUE_MAX + 1), sizeof(U32)) >> 2;
    weightList = (BYTE *)((U32 *)workSpace + spaceUsed32);
    spaceUsed32 += HUF_ALIGN(HUF_SYMBOLVALUE_MAX + 1, sizeof(U32)) >> 2;

    if ((spaceUsed32 << 2) > wkspSize) return ERROR(tableLog_tooLarge);

    rankStart = rankStart0 + 1;
    memset(rankStats, 0, sizeof(U32) * (2 * HUF_TABLELOG_MAX + 2 + 1));

    DEBUG_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(HUF_DTable));   /* if compiler fails here, assertion is wrong */
    if (maxTableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
    /* memset(weightList, 0, sizeof(weightList)); */  /* is not necessary, even though some analyzer complain ... */

    iSize = HUF_readStats(weightList, HUF_SYMBOLVALUE_MAX + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
    if (HUF_isError(iSize)) return iSize;

    /* check result */
    if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge);   /* DTable can't fit code depth */

    /* find maxWeight */
    for (maxW = tableLog; rankStats[maxW]==0; maxW--) {}  /* necessarily finds a solution before 0 */

    /* Get start index of each weight */
    {   U32 w, nextRankStart = 0;
        for (w=1; w<maxW+1; w++) {
            U32 current = nextRankStart;
            nextRankStart += rankStats[w];
            rankStart[w] = current;
        }
        rankStart[0] = nextRankStart;   /* put all 0w symbols at the end of sorted list*/
        sizeOfSort = nextRankStart;
    }

    /* sort symbols by weight */
    {   U32 s;
        for (s=0; s<nbSymbols; s++) {
            U32 const w = weightList[s];
            U32 const r = rankStart[w]++;
            sortedSymbol[r].symbol = (BYTE)s;
            sortedSymbol[r].weight = (BYTE)w;
        }
        rankStart[0] = 0;   /* forget 0w symbols; this is beginning of weight(1) */
    }

    /* Build rankVal */
    {   U32* const rankVal0 = rankVal[0];
        {   int const rescale = (maxTableLog-tableLog) - 1;   /* tableLog <= maxTableLog */
            U32 nextRankVal = 0;
            U32 w;
            for (w=1; w<maxW+1; w++) {
                U32 current = nextRankVal;
                nextRankVal += rankStats[w] << (w+rescale);
                rankVal0[w] = current;
        }   }
        {   U32 const minBits = tableLog+1 - maxW;
            U32 consumed;
            for (consumed = minBits; consumed < maxTableLog - minBits + 1; consumed++) {
                U32* const rankValPtr = rankVal[consumed];
                U32 w;
                for (w = 1; w < maxW+1; w++) {
                    rankValPtr[w] = rankVal0[w] >> consumed;
    }   }   }   }

    HUF_fillDTableX2(dt, maxTableLog,
                   sortedSymbol, sizeOfSort,
                   rankStart0, rankVal, maxW,
                   tableLog+1);

    dtd.tableLog = (BYTE)maxTableLog;
    dtd.tableType = 1;
    memcpy(DTable, &dtd, sizeof(dtd));
    return iSize;
}

size_t HUF_readDTableX2(HUF_DTable* DTable, const void* src, size_t srcSize)
{
  U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
  return HUF_readDTableX2_wksp(DTable, src, srcSize,
                               workSpace, sizeof(workSpace));
}


FORCE_INLINE_TEMPLATE U32
HUF_decodeSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
{
    size_t const val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
    memcpy(op, dt+val, 2);
    BIT_skipBits(DStream, dt[val].nbBits);
    return dt[val].length;
}

FORCE_INLINE_TEMPLATE U32
HUF_decodeLastSymbolX2(void* op, BIT_DStream_t* DStream, const HUF_DEltX2* dt, const U32 dtLog)
{
    size_t const val = BIT_lookBitsFast(DStream, dtLog);   /* note : dtLog >= 1 */
    memcpy(op, dt+val, 1);
    if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
    else {
        if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
            BIT_skipBits(DStream, dt[val].nbBits);
            if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
                /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
                DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8);
    }   }
    return 1;
}

#define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
    ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)

#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
    if (MEM_64bits() || (HUF_TABLELOG_MAX<=12)) \
        ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)

#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
    if (MEM_64bits()) \
        ptr += HUF_decodeSymbolX2(ptr, DStreamPtr, dt, dtLog)

HINT_INLINE size_t
HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd,
                const HUF_DEltX2* const dt, const U32 dtLog)
{
    BYTE* const pStart = p;

    /* up to 8 symbols at a time */
    while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p < pEnd-(sizeof(bitDPtr->bitContainer)-1))) {
        HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
        HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
        HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
        HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
    }

    /* closer to end : up to 2 symbols at a time */
    while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) & (p <= pEnd-2))
        HUF_DECODE_SYMBOLX2_0(p, bitDPtr);

    while (p <= pEnd-2)
        HUF_DECODE_SYMBOLX2_0(p, bitDPtr);   /* no need to reload : reached the end of DStream */

    if (p < pEnd)
        p += HUF_decodeLastSymbolX2(p, bitDPtr, dt, dtLog);

    return p-pStart;
}

FORCE_INLINE_TEMPLATE size_t
HUF_decompress1X2_usingDTable_internal_body(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    BIT_DStream_t bitD;

    /* Init */
    CHECK_F( BIT_initDStream(&bitD, cSrc, cSrcSize) );

    /* decode */
    {   BYTE* const ostart = (BYTE*) dst;
        BYTE* const oend = ostart + dstSize;
        const void* const dtPtr = DTable+1;   /* force compiler to not use strict-aliasing */
        const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;
        DTableDesc const dtd = HUF_getDTableDesc(DTable);
        HUF_decodeStreamX2(ostart, &bitD, oend, dt, dtd.tableLog);
    }

    /* check */
    if (!BIT_endOfDStream(&bitD)) return ERROR(corruption_detected);

    /* decoded size */
    return dstSize;
}

FORCE_INLINE_TEMPLATE size_t
HUF_decompress4X2_usingDTable_internal_body(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    if (cSrcSize < 10) return ERROR(corruption_detected);   /* strict minimum : jump table + 1 byte per stream */

    {   const BYTE* const istart = (const BYTE*) cSrc;
        BYTE* const ostart = (BYTE*) dst;
        BYTE* const oend = ostart + dstSize;
        BYTE* const olimit = oend - (sizeof(size_t)-1);
        const void* const dtPtr = DTable+1;
        const HUF_DEltX2* const dt = (const HUF_DEltX2*)dtPtr;

        /* Init */
        BIT_DStream_t bitD1;
        BIT_DStream_t bitD2;
        BIT_DStream_t bitD3;
        BIT_DStream_t bitD4;
        size_t const length1 = MEM_readLE16(istart);
        size_t const length2 = MEM_readLE16(istart+2);
        size_t const length3 = MEM_readLE16(istart+4);
        size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
        const BYTE* const istart1 = istart + 6;  /* jumpTable */
        const BYTE* const istart2 = istart1 + length1;
        const BYTE* const istart3 = istart2 + length2;
        const BYTE* const istart4 = istart3 + length3;
        size_t const segmentSize = (dstSize+3) / 4;
        BYTE* const opStart2 = ostart + segmentSize;
        BYTE* const opStart3 = opStart2 + segmentSize;
        BYTE* const opStart4 = opStart3 + segmentSize;
        BYTE* op1 = ostart;
        BYTE* op2 = opStart2;
        BYTE* op3 = opStart3;
        BYTE* op4 = opStart4;
        U32 endSignal = 1;
        DTableDesc const dtd = HUF_getDTableDesc(DTable);
        U32 const dtLog = dtd.tableLog;

        if (length4 > cSrcSize) return ERROR(corruption_detected);   /* overflow */
        CHECK_F( BIT_initDStream(&bitD1, istart1, length1) );
        CHECK_F( BIT_initDStream(&bitD2, istart2, length2) );
        CHECK_F( BIT_initDStream(&bitD3, istart3, length3) );
        CHECK_F( BIT_initDStream(&bitD4, istart4, length4) );

        /* 16-32 symbols per loop (4-8 symbols per stream) */
        for ( ; (endSignal) & (op4 < olimit); ) {
#if defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
            HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
            endSignal &= BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished;
            endSignal &= BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished;
            HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
            endSignal &= BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished;
            endSignal &= BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished;
#else
            HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
            HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
            HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
            HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
            HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
            endSignal = (U32)LIKELY(
                        (BIT_reloadDStreamFast(&bitD1) == BIT_DStream_unfinished)
                      & (BIT_reloadDStreamFast(&bitD2) == BIT_DStream_unfinished)
                      & (BIT_reloadDStreamFast(&bitD3) == BIT_DStream_unfinished)
                      & (BIT_reloadDStreamFast(&bitD4) == BIT_DStream_unfinished));
#endif
        }

        /* check corruption */
        if (op1 > opStart2) return ERROR(corruption_detected);
        if (op2 > opStart3) return ERROR(corruption_detected);
        if (op3 > opStart4) return ERROR(corruption_detected);
        /* note : op4 already verified within main loop */

        /* finish bitStreams one by one */
        HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
        HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
        HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
        HUF_decodeStreamX2(op4, &bitD4, oend,     dt, dtLog);

        /* check */
        { U32 const endCheck = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
          if (!endCheck) return ERROR(corruption_detected); }

        /* decoded size */
        return dstSize;
    }
}

HUF_DGEN(HUF_decompress1X2_usingDTable_internal)
HUF_DGEN(HUF_decompress4X2_usingDTable_internal)

size_t HUF_decompress1X2_usingDTable(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    DTableDesc dtd = HUF_getDTableDesc(DTable);
    if (dtd.tableType != 1) return ERROR(GENERIC);
    return HUF_decompress1X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
}

size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* DCtx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize)
{
    const BYTE* ip = (const BYTE*) cSrc;

    size_t const hSize = HUF_readDTableX2_wksp(DCtx, cSrc, cSrcSize,
                                               workSpace, wkspSize);
    if (HUF_isError(hSize)) return hSize;
    if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
    ip += hSize; cSrcSize -= hSize;

    return HUF_decompress1X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, DCtx, /* bmi2 */ 0);
}


size_t HUF_decompress1X2_DCtx(HUF_DTable* DCtx, void* dst, size_t dstSize,
                              const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress1X2_DCtx_wksp(DCtx, dst, dstSize, cSrc, cSrcSize,
                                       workSpace, sizeof(workSpace));
}

size_t HUF_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX);
    return HUF_decompress1X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
}

size_t HUF_decompress4X2_usingDTable(
          void* dst,  size_t dstSize,
    const void* cSrc, size_t cSrcSize,
    const HUF_DTable* DTable)
{
    DTableDesc dtd = HUF_getDTableDesc(DTable);
    if (dtd.tableType != 1) return ERROR(GENERIC);
    return HUF_decompress4X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
}

static size_t HUF_decompress4X2_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize, int bmi2)
{
    const BYTE* ip = (const BYTE*) cSrc;

    size_t hSize = HUF_readDTableX2_wksp(dctx, cSrc, cSrcSize,
                                         workSpace, wkspSize);
    if (HUF_isError(hSize)) return hSize;
    if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
    ip += hSize; cSrcSize -= hSize;

    return HUF_decompress4X2_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
}

size_t HUF_decompress4X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
                                   const void* cSrc, size_t cSrcSize,
                                   void* workSpace, size_t wkspSize)
{
    return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, /* bmi2 */ 0);
}


size_t HUF_decompress4X2_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize,
                              const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
                                       workSpace, sizeof(workSpace));
}

size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_TABLELOG_MAX);
    return HUF_decompress4X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
}

#endif /* HUF_FORCE_DECOMPRESS_X1 */


/* ***********************************/
/* Universal decompression selectors */
/* ***********************************/

size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize,
                                    const void* cSrc, size_t cSrcSize,
                                    const HUF_DTable* DTable)
{
    DTableDesc const dtd = HUF_getDTableDesc(DTable);
#if defined(HUF_FORCE_DECOMPRESS_X1)
    (void)dtd;
    assert(dtd.tableType == 0);
    return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
    (void)dtd;
    assert(dtd.tableType == 1);
    return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#else
    return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) :
                           HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#endif
}

size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize,
                                    const void* cSrc, size_t cSrcSize,
                                    const HUF_DTable* DTable)
{
    DTableDesc const dtd = HUF_getDTableDesc(DTable);
#if defined(HUF_FORCE_DECOMPRESS_X1)
    (void)dtd;
    assert(dtd.tableType == 0);
    return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
    (void)dtd;
    assert(dtd.tableType == 1);
    return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#else
    return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0) :
                           HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, /* bmi2 */ 0);
#endif
}


#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2)
typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
{
    /* single, double, quad */
    {{0,0}, {1,1}, {2,2}},  /* Q==0 : impossible */
    {{0,0}, {1,1}, {2,2}},  /* Q==1 : impossible */
    {{  38,130}, {1313, 74}, {2151, 38}},   /* Q == 2 : 12-18% */
    {{ 448,128}, {1353, 74}, {2238, 41}},   /* Q == 3 : 18-25% */
    {{ 556,128}, {1353, 74}, {2238, 47}},   /* Q == 4 : 25-32% */
    {{ 714,128}, {1418, 74}, {2436, 53}},   /* Q == 5 : 32-38% */
    {{ 883,128}, {1437, 74}, {2464, 61}},   /* Q == 6 : 38-44% */
    {{ 897,128}, {1515, 75}, {2622, 68}},   /* Q == 7 : 44-50% */
    {{ 926,128}, {1613, 75}, {2730, 75}},   /* Q == 8 : 50-56% */
    {{ 947,128}, {1729, 77}, {3359, 77}},   /* Q == 9 : 56-62% */
    {{1107,128}, {2083, 81}, {4006, 84}},   /* Q ==10 : 62-69% */
    {{1177,128}, {2379, 87}, {4785, 88}},   /* Q ==11 : 69-75% */
    {{1242,128}, {2415, 93}, {5155, 84}},   /* Q ==12 : 75-81% */
    {{1349,128}, {2644,106}, {5260,106}},   /* Q ==13 : 81-87% */
    {{1455,128}, {2422,124}, {4174,124}},   /* Q ==14 : 87-93% */
    {{ 722,128}, {1891,145}, {1936,146}},   /* Q ==15 : 93-99% */
};
#endif

/** HUF_selectDecoder() :
 *  Tells which decoder is likely to decode faster,
 *  based on a set of pre-computed metrics.
 * @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .
 *  Assumption : 0 < dstSize <= 128 KB */
U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize)
{
    assert(dstSize > 0);
    assert(dstSize <= 128*1024);
#if defined(HUF_FORCE_DECOMPRESS_X1)
    (void)dstSize;
    (void)cSrcSize;
    return 0;
#elif defined(HUF_FORCE_DECOMPRESS_X2)
    (void)dstSize;
    (void)cSrcSize;
    return 1;
#else
    /* decoder timing evaluation */
    {   U32 const Q = (cSrcSize >= dstSize) ? 15 : (U32)(cSrcSize * 16 / dstSize);   /* Q < 16 */
        U32 const D256 = (U32)(dstSize >> 8);
        U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256);
        U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256);
        DTime1 += DTime1 >> 3;  /* advantage to algorithm using less memory, to reduce cache eviction */
        return DTime1 < DTime0;
    }
#endif
}


typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);

size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
#if !defined(HUF_FORCE_DECOMPRESS_X1) && !defined(HUF_FORCE_DECOMPRESS_X2)
    static const decompressionAlgo decompress[2] = { HUF_decompress4X1, HUF_decompress4X2 };
#endif

    /* validation checks */
    if (dstSize == 0) return ERROR(dstSize_tooSmall);
    if (cSrcSize > dstSize) return ERROR(corruption_detected);   /* invalid */
    if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; }   /* not compressed */
    if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; }   /* RLE */

    {   U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
#if defined(HUF_FORCE_DECOMPRESS_X1)
        (void)algoNb;
        assert(algoNb == 0);
        return HUF_decompress4X1(dst, dstSize, cSrc, cSrcSize);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
        (void)algoNb;
        assert(algoNb == 1);
        return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize);
#else
        return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
#endif
    }
}

size_t HUF_decompress4X_DCtx (HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    /* validation checks */
    if (dstSize == 0) return ERROR(dstSize_tooSmall);
    if (cSrcSize > dstSize) return ERROR(corruption_detected);   /* invalid */
    if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; }   /* not compressed */
    if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; }   /* RLE */

    {   U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
#if defined(HUF_FORCE_DECOMPRESS_X1)
        (void)algoNb;
        assert(algoNb == 0);
        return HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
        (void)algoNb;
        assert(algoNb == 1);
        return HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize);
#else
        return algoNb ? HUF_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) :
                        HUF_decompress4X1_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ;
#endif
    }
}

size_t HUF_decompress4X_hufOnly(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress4X_hufOnly_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
                                         workSpace, sizeof(workSpace));
}


size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst,
                                     size_t dstSize, const void* cSrc,
                                     size_t cSrcSize, void* workSpace,
                                     size_t wkspSize)
{
    /* validation checks */
    if (dstSize == 0) return ERROR(dstSize_tooSmall);
    if (cSrcSize == 0) return ERROR(corruption_detected);

    {   U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
#if defined(HUF_FORCE_DECOMPRESS_X1)
        (void)algoNb;
        assert(algoNb == 0);
        return HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
        (void)algoNb;
        assert(algoNb == 1);
        return HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
#else
        return algoNb ? HUF_decompress4X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
                            cSrcSize, workSpace, wkspSize):
                        HUF_decompress4X1_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize);
#endif
    }
}

size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize,
                                  const void* cSrc, size_t cSrcSize,
                                  void* workSpace, size_t wkspSize)
{
    /* validation checks */
    if (dstSize == 0) return ERROR(dstSize_tooSmall);
    if (cSrcSize > dstSize) return ERROR(corruption_detected);   /* invalid */
    if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; }   /* not compressed */
    if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; }   /* RLE */

    {   U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
#if defined(HUF_FORCE_DECOMPRESS_X1)
        (void)algoNb;
        assert(algoNb == 0);
        return HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
                                cSrcSize, workSpace, wkspSize);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
        (void)algoNb;
        assert(algoNb == 1);
        return HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
                                cSrcSize, workSpace, wkspSize);
#else
        return algoNb ? HUF_decompress1X2_DCtx_wksp(dctx, dst, dstSize, cSrc,
                                cSrcSize, workSpace, wkspSize):
                        HUF_decompress1X1_DCtx_wksp(dctx, dst, dstSize, cSrc,
                                cSrcSize, workSpace, wkspSize);
#endif
    }
}

size_t HUF_decompress1X_DCtx(HUF_DTable* dctx, void* dst, size_t dstSize,
                             const void* cSrc, size_t cSrcSize)
{
    U32 workSpace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];
    return HUF_decompress1X_DCtx_wksp(dctx, dst, dstSize, cSrc, cSrcSize,
                                      workSpace, sizeof(workSpace));
}


size_t HUF_decompress1X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2)
{
    DTableDesc const dtd = HUF_getDTableDesc(DTable);
#if defined(HUF_FORCE_DECOMPRESS_X1)
    (void)dtd;
    assert(dtd.tableType == 0);
    return HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
    (void)dtd;
    assert(dtd.tableType == 1);
    return HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#else
    return dtd.tableType ? HUF_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) :
                           HUF_decompress1X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#endif
}

#ifndef HUF_FORCE_DECOMPRESS_X2
size_t HUF_decompress1X1_DCtx_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2)
{
    const BYTE* ip = (const BYTE*) cSrc;

    size_t const hSize = HUF_readDTableX1_wksp(dctx, cSrc, cSrcSize, workSpace, wkspSize);
    if (HUF_isError(hSize)) return hSize;
    if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
    ip += hSize; cSrcSize -= hSize;

    return HUF_decompress1X1_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx, bmi2);
}
#endif

size_t HUF_decompress4X_usingDTable_bmi2(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int bmi2)
{
    DTableDesc const dtd = HUF_getDTableDesc(DTable);
#if defined(HUF_FORCE_DECOMPRESS_X1)
    (void)dtd;
    assert(dtd.tableType == 0);
    return HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
    (void)dtd;
    assert(dtd.tableType == 1);
    return HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#else
    return dtd.tableType ? HUF_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2) :
                           HUF_decompress4X1_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable, bmi2);
#endif
}

size_t HUF_decompress4X_hufOnly_wksp_bmi2(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int bmi2)
{
    /* validation checks */
    if (dstSize == 0) return ERROR(dstSize_tooSmall);
    if (cSrcSize == 0) return ERROR(corruption_detected);

    {   U32 const algoNb = HUF_selectDecoder(dstSize, cSrcSize);
#if defined(HUF_FORCE_DECOMPRESS_X1)
        (void)algoNb;
        assert(algoNb == 0);
        return HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
#elif defined(HUF_FORCE_DECOMPRESS_X2)
        (void)algoNb;
        assert(algoNb == 1);
        return HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
#else
        return algoNb ? HUF_decompress4X2_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2) :
                        HUF_decompress4X1_DCtx_wksp_bmi2(dctx, dst, dstSize, cSrc, cSrcSize, workSpace, wkspSize, bmi2);
#endif
    }
}
/**** ended inlining decompress/huf_decompress.c ****/
/**** start inlining decompress/zstd_ddict.c ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

/* zstd_ddict.c :
 * concentrates all logic that needs to know the internals of ZSTD_DDict object */

/*-*******************************************************
*  Dependencies
*********************************************************/
/**** start inlining ../common/cpu.h ****/
/*
 * Copyright (c) 2018-2020, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_COMMON_CPU_H
#define ZSTD_COMMON_CPU_H

/**
 * Implementation taken from folly/CpuId.h
 * https://github.com/facebook/folly/blob/master/folly/CpuId.h
 */


/**** skipping file: mem.h ****/

#ifdef _MSC_VER
#include <intrin.h>
#endif

typedef struct {
    U32 f1c;
    U32 f1d;
    U32 f7b;
    U32 f7c;
} ZSTD_cpuid_t;

MEM_STATIC ZSTD_cpuid_t ZSTD_cpuid(void) {
    U32 f1c = 0;
    U32 f1d = 0;
    U32 f7b = 0;
    U32 f7c = 0;
#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
    int reg[4];
    __cpuid((int*)reg, 0);
    {
        int const n = reg[0];
        if (n >= 1) {
            __cpuid((int*)reg, 1);
            f1c = (U32)reg[2];
            f1d = (U32)reg[3];
        }
        if (n >= 7) {
            __cpuidex((int*)reg, 7, 0);
            f7b = (U32)reg[1];
            f7c = (U32)reg[2];
        }
    }
#elif defined(__i386__) && defined(__PIC__) && !defined(__clang__) && defined(__GNUC__)
    /* The following block like the normal cpuid branch below, but gcc
     * reserves ebx for use of its pic register so we must specially
     * handle the save and restore to avoid clobbering the register
     */
    U32 n;
    __asm__(
        "pushl %%ebx\n\t"
        "cpuid\n\t"
        "popl %%ebx\n\t"
        : "=a"(n)
        : "a"(0)
        : "ecx", "edx");
    if (n >= 1) {
      U32 f1a;
      __asm__(
          "pushl %%ebx\n\t"
          "cpuid\n\t"
          "popl %%ebx\n\t"
          : "=a"(f1a), "=c"(f1c), "=d"(f1d)
          : "a"(1));
    }
    if (n >= 7) {
      __asm__(
          "pushl %%ebx\n\t"
          "cpuid\n\t"
          "movl %%ebx, %%eax\n\t"
          "popl %%ebx"
          : "=a"(f7b), "=c"(f7c)
          : "a"(7), "c"(0)
          : "edx");
    }
#elif defined(__x86_64__) || defined(_M_X64) || defined(__i386__)
    U32 n;
    __asm__("cpuid" : "=a"(n) : "a"(0) : "ebx", "ecx", "edx");
    if (n >= 1) {
      U32 f1a;
      __asm__("cpuid" : "=a"(f1a), "=c"(f1c), "=d"(f1d) : "a"(1) : "ebx");
    }
    if (n >= 7) {
      U32 f7a;
      __asm__("cpuid"
              : "=a"(f7a), "=b"(f7b), "=c"(f7c)
              : "a"(7), "c"(0)
              : "edx");
    }
#endif
    {
        ZSTD_cpuid_t cpuid;
        cpuid.f1c = f1c;
        cpuid.f1d = f1d;
        cpuid.f7b = f7b;
        cpuid.f7c = f7c;
        return cpuid;
    }
}

#define X(name, r, bit)                                                        \
  MEM_STATIC int ZSTD_cpuid_##name(ZSTD_cpuid_t const cpuid) {                 \
    return ((cpuid.r) & (1U << bit)) != 0;                                     \
  }

/* cpuid(1): Processor Info and Feature Bits. */
#define C(name, bit) X(name, f1c, bit)
  C(sse3, 0)
  C(pclmuldq, 1)
  C(dtes64, 2)
  C(monitor, 3)
  C(dscpl, 4)
  C(vmx, 5)
  C(smx, 6)
  C(eist, 7)
  C(tm2, 8)
  C(ssse3, 9)
  C(cnxtid, 10)
  C(fma, 12)
  C(cx16, 13)
  C(xtpr, 14)
  C(pdcm, 15)
  C(pcid, 17)
  C(dca, 18)
  C(sse41, 19)
  C(sse42, 20)
  C(x2apic, 21)
  C(movbe, 22)
  C(popcnt, 23)
  C(tscdeadline, 24)
  C(aes, 25)
  C(xsave, 26)
  C(osxsave, 27)
  C(avx, 28)
  C(f16c, 29)
  C(rdrand, 30)
#undef C
#define D(name, bit) X(name, f1d, bit)
  D(fpu, 0)
  D(vme, 1)
  D(de, 2)
  D(pse, 3)
  D(tsc, 4)
  D(msr, 5)
  D(pae, 6)
  D(mce, 7)
  D(cx8, 8)
  D(apic, 9)
  D(sep, 11)
  D(mtrr, 12)
  D(pge, 13)
  D(mca, 14)
  D(cmov, 15)
  D(pat, 16)
  D(pse36, 17)
  D(psn, 18)
  D(clfsh, 19)
  D(ds, 21)
  D(acpi, 22)
  D(mmx, 23)
  D(fxsr, 24)
  D(sse, 25)
  D(sse2, 26)
  D(ss, 27)
  D(htt, 28)
  D(tm, 29)
  D(pbe, 31)
#undef D

/* cpuid(7): Extended Features. */
#define B(name, bit) X(name, f7b, bit)
  B(bmi1, 3)
  B(hle, 4)
  B(avx2, 5)
  B(smep, 7)
  B(bmi2, 8)
  B(erms, 9)
  B(invpcid, 10)
  B(rtm, 11)
  B(mpx, 14)
  B(avx512f, 16)
  B(avx512dq, 17)
  B(rdseed, 18)
  B(adx, 19)
  B(smap, 20)
  B(avx512ifma, 21)
  B(pcommit, 22)
  B(clflushopt, 23)
  B(clwb, 24)
  B(avx512pf, 26)
  B(avx512er, 27)
  B(avx512cd, 28)
  B(sha, 29)
  B(avx512bw, 30)
  B(avx512vl, 31)
#undef B
#define C(name, bit) X(name, f7c, bit)
  C(prefetchwt1, 0)
  C(avx512vbmi, 1)
#undef C

#undef X

#endif /* ZSTD_COMMON_CPU_H */
/**** ended inlining ../common/cpu.h ****/
/**** skipping file: ../common/mem.h ****/
#define FSE_STATIC_LINKING_ONLY
/**** skipping file: ../common/fse.h ****/
#define HUF_STATIC_LINKING_ONLY
/**** skipping file: ../common/huf.h ****/
/**** start inlining zstd_decompress_internal.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */


/* zstd_decompress_internal:
 * objects and definitions shared within lib/decompress modules */

 #ifndef ZSTD_DECOMPRESS_INTERNAL_H
 #define ZSTD_DECOMPRESS_INTERNAL_H


/*-*******************************************************
 *  Dependencies
 *********************************************************/
/**** skipping file: ../common/mem.h ****/
/**** skipping file: ../common/zstd_internal.h ****/



/*-*******************************************************
 *  Constants
 *********************************************************/
static const U32 LL_base[MaxLL+1] = {
                 0,    1,    2,     3,     4,     5,     6,      7,
                 8,    9,   10,    11,    12,    13,    14,     15,
                16,   18,   20,    22,    24,    28,    32,     40,
                48,   64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
                0x2000, 0x4000, 0x8000, 0x10000 };

static const U32 OF_base[MaxOff+1] = {
                 0,        1,       1,       5,     0xD,     0x1D,     0x3D,     0x7D,
                 0xFD,   0x1FD,   0x3FD,   0x7FD,   0xFFD,   0x1FFD,   0x3FFD,   0x7FFD,
                 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
                 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD, 0x1FFFFFFD, 0x3FFFFFFD, 0x7FFFFFFD };

static const U32 OF_bits[MaxOff+1] = {
                     0,  1,  2,  3,  4,  5,  6,  7,
                     8,  9, 10, 11, 12, 13, 14, 15,
                    16, 17, 18, 19, 20, 21, 22, 23,
                    24, 25, 26, 27, 28, 29, 30, 31 };

static const U32 ML_base[MaxML+1] = {
                     3,  4,  5,    6,     7,     8,     9,    10,
                    11, 12, 13,   14,    15,    16,    17,    18,
                    19, 20, 21,   22,    23,    24,    25,    26,
                    27, 28, 29,   30,    31,    32,    33,    34,
                    35, 37, 39,   41,    43,    47,    51,    59,
                    67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
                    0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };


/*-*******************************************************
 *  Decompression types
 *********************************************************/
 typedef struct {
     U32 fastMode;
     U32 tableLog;
 } ZSTD_seqSymbol_header;

 typedef struct {
     U16  nextState;
     BYTE nbAdditionalBits;
     BYTE nbBits;
     U32  baseValue;
 } ZSTD_seqSymbol;

 #define SEQSYMBOL_TABLE_SIZE(log)   (1 + (1 << (log)))

typedef struct {
    ZSTD_seqSymbol LLTable[SEQSYMBOL_TABLE_SIZE(LLFSELog)];    /* Note : Space reserved for FSE Tables */
    ZSTD_seqSymbol OFTable[SEQSYMBOL_TABLE_SIZE(OffFSELog)];   /* is also used as temporary workspace while building hufTable during DDict creation */
    ZSTD_seqSymbol MLTable[SEQSYMBOL_TABLE_SIZE(MLFSELog)];    /* and therefore must be at least HUF_DECOMPRESS_WORKSPACE_SIZE large */
    HUF_DTable hufTable[HUF_DTABLE_SIZE(HufLog)];  /* can accommodate HUF_decompress4X */
    U32 rep[ZSTD_REP_NUM];
} ZSTD_entropyDTables_t;

typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
               ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock,
               ZSTDds_decompressLastBlock, ZSTDds_checkChecksum,
               ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTD_dStage;

typedef enum { zdss_init=0, zdss_loadHeader,
               zdss_read, zdss_load, zdss_flush } ZSTD_dStreamStage;

typedef enum {
    ZSTD_use_indefinitely = -1,  /* Use the dictionary indefinitely */
    ZSTD_dont_use = 0,           /* Do not use the dictionary (if one exists free it) */
    ZSTD_use_once = 1            /* Use the dictionary once and set to ZSTD_dont_use */
} ZSTD_dictUses_e;

typedef enum {
    ZSTD_obm_buffered = 0,  /* Buffer the output */
    ZSTD_obm_stable = 1     /* ZSTD_outBuffer is stable */
} ZSTD_outBufferMode_e;

struct ZSTD_DCtx_s
{
    const ZSTD_seqSymbol* LLTptr;
    const ZSTD_seqSymbol* MLTptr;
    const ZSTD_seqSymbol* OFTptr;
    const HUF_DTable* HUFptr;
    ZSTD_entropyDTables_t entropy;
    U32 workspace[HUF_DECOMPRESS_WORKSPACE_SIZE_U32];   /* space needed when building huffman tables */
    const void* previousDstEnd;   /* detect continuity */
    const void* prefixStart;      /* start of current segment */
    const void* virtualStart;     /* virtual start of previous segment if it was just before current one */
    const void* dictEnd;          /* end of previous segment */
    size_t expected;
    ZSTD_frameHeader fParams;
    U64 decodedSize;
    blockType_e bType;            /* used in ZSTD_decompressContinue(), store blockType between block header decoding and block decompression stages */
    ZSTD_dStage stage;
    U32 litEntropy;
    U32 fseEntropy;
    XXH64_state_t xxhState;
    size_t headerSize;
    ZSTD_format_e format;
    const BYTE* litPtr;
    ZSTD_customMem customMem;
    size_t litSize;
    size_t rleSize;
    size_t staticSize;
    int bmi2;                     /* == 1 if the CPU supports BMI2 and 0 otherwise. CPU support is determined dynamically once per context lifetime. */

    /* dictionary */
    ZSTD_DDict* ddictLocal;
    const ZSTD_DDict* ddict;     /* set by ZSTD_initDStream_usingDDict(), or ZSTD_DCtx_refDDict() */
    U32 dictID;
    int ddictIsCold;             /* if == 1 : dictionary is "new" for working context, and presumed "cold" (not in cpu cache) */
    ZSTD_dictUses_e dictUses;

    /* streaming */
    ZSTD_dStreamStage streamStage;
    char*  inBuff;
    size_t inBuffSize;
    size_t inPos;
    size_t maxWindowSize;
    char*  outBuff;
    size_t outBuffSize;
    size_t outStart;
    size_t outEnd;
    size_t lhSize;
    void* legacyContext;
    U32 previousLegacyVersion;
    U32 legacyVersion;
    U32 hostageByte;
    int noForwardProgress;
    ZSTD_outBufferMode_e outBufferMode;
    ZSTD_outBuffer expectedOutBuffer;

    /* workspace */
    BYTE litBuffer[ZSTD_BLOCKSIZE_MAX + WILDCOPY_OVERLENGTH];
    BYTE headerBuffer[ZSTD_FRAMEHEADERSIZE_MAX];

    size_t oversizedDuration;

#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    void const* dictContentBeginForFuzzing;
    void const* dictContentEndForFuzzing;
#endif
};  /* typedef'd to ZSTD_DCtx within "zstd.h" */


/*-*******************************************************
 *  Shared internal functions
 *********************************************************/

/*! ZSTD_loadDEntropy() :
 *  dict : must point at beginning of a valid zstd dictionary.
 * @return : size of dictionary header (size of magic number + dict ID + entropy tables) */
size_t ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
                   const void* const dict, size_t const dictSize);

/*! ZSTD_checkContinuity() :
 *  check if next `dst` follows previous position, where decompression ended.
 *  If yes, do nothing (continue on current segment).
 *  If not, classify previous segment as "external dictionary", and start a new segment.
 *  This function cannot fail. */
void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst);


#endif /* ZSTD_DECOMPRESS_INTERNAL_H */
/**** ended inlining zstd_decompress_internal.h ****/
/**** start inlining zstd_ddict.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */


#ifndef ZSTD_DDICT_H
#define ZSTD_DDICT_H

/*-*******************************************************
 *  Dependencies
 *********************************************************/
#include <stddef.h>   /* size_t */
/**** skipping file: ../zstd.h ****/


/*-*******************************************************
 *  Interface
 *********************************************************/

/* note: several prototypes are already published in `zstd.h` :
 * ZSTD_createDDict()
 * ZSTD_createDDict_byReference()
 * ZSTD_createDDict_advanced()
 * ZSTD_freeDDict()
 * ZSTD_initStaticDDict()
 * ZSTD_sizeof_DDict()
 * ZSTD_estimateDDictSize()
 * ZSTD_getDictID_fromDict()
 */

const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict);
size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict);

void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict);



#endif /* ZSTD_DDICT_H */
/**** ended inlining zstd_ddict.h ****/

#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
/**** start inlining ../legacy/zstd_legacy.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_LEGACY_H
#define ZSTD_LEGACY_H

#if defined (__cplusplus)
extern "C" {
#endif

/* *************************************
*  Includes
***************************************/
/**** skipping file: ../common/mem.h ****/
/**** skipping file: ../common/error_private.h ****/
/**** skipping file: ../common/zstd_internal.h ****/

#if !defined (ZSTD_LEGACY_SUPPORT) || (ZSTD_LEGACY_SUPPORT == 0)
#  undef ZSTD_LEGACY_SUPPORT
#  define ZSTD_LEGACY_SUPPORT 8
#endif

#if (ZSTD_LEGACY_SUPPORT <= 1)
/**** start inlining zstd_v01.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_V01_H_28739879432
#define ZSTD_V01_H_28739879432

#if defined (__cplusplus)
extern "C" {
#endif

/* *************************************
*  Includes
***************************************/
#include <stddef.h>   /* size_t */


/* *************************************
*  Simple one-step function
***************************************/
/**
ZSTDv01_decompress() : decompress ZSTD frames compliant with v0.1.x format
    compressedSize : is the exact source size
    maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated.
                      It must be equal or larger than originalSize, otherwise decompression will fail.
    return : the number of bytes decompressed into destination buffer (originalSize)
             or an errorCode if it fails (which can be tested using ZSTDv01_isError())
*/
size_t ZSTDv01_decompress( void* dst, size_t maxOriginalSize,
                     const void* src, size_t compressedSize);

 /**
 ZSTDv01_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.1.x format
     srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
     cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                 or an error code if it fails (which can be tested using ZSTDv01_isError())
     dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                 or ZSTD_CONTENTSIZE_ERROR if an error occurs

     note : assumes `cSize` and `dBound` are _not_ NULL.
 */
void ZSTDv01_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                     size_t* cSize, unsigned long long* dBound);

/**
ZSTDv01_isError() : tells if the result of ZSTDv01_decompress() is an error
*/
unsigned ZSTDv01_isError(size_t code);


/* *************************************
*  Advanced functions
***************************************/
typedef struct ZSTDv01_Dctx_s ZSTDv01_Dctx;
ZSTDv01_Dctx* ZSTDv01_createDCtx(void);
size_t ZSTDv01_freeDCtx(ZSTDv01_Dctx* dctx);

size_t ZSTDv01_decompressDCtx(void* ctx,
                              void* dst, size_t maxOriginalSize,
                        const void* src, size_t compressedSize);

/* *************************************
*  Streaming functions
***************************************/
size_t ZSTDv01_resetDCtx(ZSTDv01_Dctx* dctx);

size_t ZSTDv01_nextSrcSizeToDecompress(ZSTDv01_Dctx* dctx);
size_t ZSTDv01_decompressContinue(ZSTDv01_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize);
/**
  Use above functions alternatively.
  ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  Result is the number of bytes regenerated within 'dst'.
  It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
*/

/* *************************************
*  Prefix - version detection
***************************************/
#define ZSTDv01_magicNumber   0xFD2FB51E   /* Big Endian version */
#define ZSTDv01_magicNumberLE 0x1EB52FFD   /* Little Endian version */


#if defined (__cplusplus)
}
#endif

#endif /* ZSTD_V01_H_28739879432 */
/**** ended inlining zstd_v01.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 2)
/**** start inlining zstd_v02.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_V02_H_4174539423
#define ZSTD_V02_H_4174539423

#if defined (__cplusplus)
extern "C" {
#endif

/* *************************************
*  Includes
***************************************/
#include <stddef.h>   /* size_t */


/* *************************************
*  Simple one-step function
***************************************/
/**
ZSTDv02_decompress() : decompress ZSTD frames compliant with v0.2.x format
    compressedSize : is the exact source size
    maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated.
                      It must be equal or larger than originalSize, otherwise decompression will fail.
    return : the number of bytes decompressed into destination buffer (originalSize)
             or an errorCode if it fails (which can be tested using ZSTDv01_isError())
*/
size_t ZSTDv02_decompress( void* dst, size_t maxOriginalSize,
                     const void* src, size_t compressedSize);

 /**
 ZSTDv02_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.2.x format
     srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
     cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                 or an error code if it fails (which can be tested using ZSTDv01_isError())
     dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                 or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
 */
void ZSTDv02_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                     size_t* cSize, unsigned long long* dBound);

/**
ZSTDv02_isError() : tells if the result of ZSTDv02_decompress() is an error
*/
unsigned ZSTDv02_isError(size_t code);


/* *************************************
*  Advanced functions
***************************************/
typedef struct ZSTDv02_Dctx_s ZSTDv02_Dctx;
ZSTDv02_Dctx* ZSTDv02_createDCtx(void);
size_t ZSTDv02_freeDCtx(ZSTDv02_Dctx* dctx);

size_t ZSTDv02_decompressDCtx(void* ctx,
                              void* dst, size_t maxOriginalSize,
                        const void* src, size_t compressedSize);

/* *************************************
*  Streaming functions
***************************************/
size_t ZSTDv02_resetDCtx(ZSTDv02_Dctx* dctx);

size_t ZSTDv02_nextSrcSizeToDecompress(ZSTDv02_Dctx* dctx);
size_t ZSTDv02_decompressContinue(ZSTDv02_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize);
/**
  Use above functions alternatively.
  ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  Result is the number of bytes regenerated within 'dst'.
  It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
*/

/* *************************************
*  Prefix - version detection
***************************************/
#define ZSTDv02_magicNumber 0xFD2FB522   /* v0.2 */


#if defined (__cplusplus)
}
#endif

#endif /* ZSTD_V02_H_4174539423 */
/**** ended inlining zstd_v02.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 3)
/**** start inlining zstd_v03.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_V03_H_298734209782
#define ZSTD_V03_H_298734209782

#if defined (__cplusplus)
extern "C" {
#endif

/* *************************************
*  Includes
***************************************/
#include <stddef.h>   /* size_t */


/* *************************************
*  Simple one-step function
***************************************/
/**
ZSTDv03_decompress() : decompress ZSTD frames compliant with v0.3.x format
    compressedSize : is the exact source size
    maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated.
                      It must be equal or larger than originalSize, otherwise decompression will fail.
    return : the number of bytes decompressed into destination buffer (originalSize)
             or an errorCode if it fails (which can be tested using ZSTDv01_isError())
*/
size_t ZSTDv03_decompress( void* dst, size_t maxOriginalSize,
                     const void* src, size_t compressedSize);

 /**
 ZSTDv03_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.3.x format
     srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
     cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                 or an error code if it fails (which can be tested using ZSTDv01_isError())
     dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                 or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
 */
 void ZSTDv03_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                      size_t* cSize, unsigned long long* dBound);

    /**
ZSTDv03_isError() : tells if the result of ZSTDv03_decompress() is an error
*/
unsigned ZSTDv03_isError(size_t code);


/* *************************************
*  Advanced functions
***************************************/
typedef struct ZSTDv03_Dctx_s ZSTDv03_Dctx;
ZSTDv03_Dctx* ZSTDv03_createDCtx(void);
size_t ZSTDv03_freeDCtx(ZSTDv03_Dctx* dctx);

size_t ZSTDv03_decompressDCtx(void* ctx,
                              void* dst, size_t maxOriginalSize,
                        const void* src, size_t compressedSize);

/* *************************************
*  Streaming functions
***************************************/
size_t ZSTDv03_resetDCtx(ZSTDv03_Dctx* dctx);

size_t ZSTDv03_nextSrcSizeToDecompress(ZSTDv03_Dctx* dctx);
size_t ZSTDv03_decompressContinue(ZSTDv03_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize);
/**
  Use above functions alternatively.
  ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  Result is the number of bytes regenerated within 'dst'.
  It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
*/

/* *************************************
*  Prefix - version detection
***************************************/
#define ZSTDv03_magicNumber 0xFD2FB523   /* v0.3 */


#if defined (__cplusplus)
}
#endif

#endif /* ZSTD_V03_H_298734209782 */
/**** ended inlining zstd_v03.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 4)
/**** start inlining zstd_v04.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTD_V04_H_91868324769238
#define ZSTD_V04_H_91868324769238

#if defined (__cplusplus)
extern "C" {
#endif

/* *************************************
*  Includes
***************************************/
#include <stddef.h>   /* size_t */


/* *************************************
*  Simple one-step function
***************************************/
/**
ZSTDv04_decompress() : decompress ZSTD frames compliant with v0.4.x format
    compressedSize : is the exact source size
    maxOriginalSize : is the size of the 'dst' buffer, which must be already allocated.
                      It must be equal or larger than originalSize, otherwise decompression will fail.
    return : the number of bytes decompressed into destination buffer (originalSize)
             or an errorCode if it fails (which can be tested using ZSTDv01_isError())
*/
size_t ZSTDv04_decompress( void* dst, size_t maxOriginalSize,
                     const void* src, size_t compressedSize);

 /**
 ZSTDv04_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.4.x format
     srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
     cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                 or an error code if it fails (which can be tested using ZSTDv01_isError())
     dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                 or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
 */
 void ZSTDv04_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                      size_t* cSize, unsigned long long* dBound);

/**
ZSTDv04_isError() : tells if the result of ZSTDv04_decompress() is an error
*/
unsigned ZSTDv04_isError(size_t code);


/* *************************************
*  Advanced functions
***************************************/
typedef struct ZSTDv04_Dctx_s ZSTDv04_Dctx;
ZSTDv04_Dctx* ZSTDv04_createDCtx(void);
size_t ZSTDv04_freeDCtx(ZSTDv04_Dctx* dctx);

size_t ZSTDv04_decompressDCtx(ZSTDv04_Dctx* dctx,
                              void* dst, size_t maxOriginalSize,
                        const void* src, size_t compressedSize);


/* *************************************
*  Direct Streaming
***************************************/
size_t ZSTDv04_resetDCtx(ZSTDv04_Dctx* dctx);

size_t ZSTDv04_nextSrcSizeToDecompress(ZSTDv04_Dctx* dctx);
size_t ZSTDv04_decompressContinue(ZSTDv04_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize);
/**
  Use above functions alternatively.
  ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block.
  Result is the number of bytes regenerated within 'dst'.
  It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
*/


/* *************************************
*  Buffered Streaming
***************************************/
typedef struct ZBUFFv04_DCtx_s ZBUFFv04_DCtx;
ZBUFFv04_DCtx* ZBUFFv04_createDCtx(void);
size_t         ZBUFFv04_freeDCtx(ZBUFFv04_DCtx* dctx);

size_t ZBUFFv04_decompressInit(ZBUFFv04_DCtx* dctx);
size_t ZBUFFv04_decompressWithDictionary(ZBUFFv04_DCtx* dctx, const void* dict, size_t dictSize);

size_t ZBUFFv04_decompressContinue(ZBUFFv04_DCtx* dctx, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr);

/** ************************************************
*  Streaming decompression
*
*  A ZBUFF_DCtx object is required to track streaming operation.
*  Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources.
*  Use ZBUFF_decompressInit() to start a new decompression operation.
*  ZBUFF_DCtx objects can be reused multiple times.
*
*  Optionally, a reference to a static dictionary can be set, using ZBUFF_decompressWithDictionary()
*  It must be the same content as the one set during compression phase.
*  Dictionary content must remain accessible during the decompression process.
*
*  Use ZBUFF_decompressContinue() repetitively to consume your input.
*  *srcSizePtr and *maxDstSizePtr can be any size.
*  The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr.
*  Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
*  The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst.
*  @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency)
*            or 0 when a frame is completely decoded
*            or an error code, which can be tested using ZBUFF_isError().
*
*  Hint : recommended buffer sizes (not compulsory) : ZBUFF_recommendedDInSize / ZBUFF_recommendedDOutSize
*  output : ZBUFF_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded.
*  input : ZBUFF_recommendedDInSize==128Kb+3; just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
* **************************************************/
unsigned ZBUFFv04_isError(size_t errorCode);
const char* ZBUFFv04_getErrorName(size_t errorCode);


/** The below functions provide recommended buffer sizes for Compression or Decompression operations.
*   These sizes are not compulsory, they just tend to offer better latency */
size_t ZBUFFv04_recommendedDInSize(void);
size_t ZBUFFv04_recommendedDOutSize(void);


/* *************************************
*  Prefix - version detection
***************************************/
#define ZSTDv04_magicNumber 0xFD2FB524   /* v0.4 */


#if defined (__cplusplus)
}
#endif

#endif /* ZSTD_V04_H_91868324769238 */
/**** ended inlining zstd_v04.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
/**** start inlining zstd_v05.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTDv05_H
#define ZSTDv05_H

#if defined (__cplusplus)
extern "C" {
#endif

/*-*************************************
*  Dependencies
***************************************/
#include <stddef.h>   /* size_t */
/**** skipping file: ../common/mem.h ****/


/* *************************************
*  Simple functions
***************************************/
/*! ZSTDv05_decompress() :
    `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail.
    `dstCapacity` must be large enough, equal or larger than originalSize.
    @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
              or an errorCode if it fails (which can be tested using ZSTDv05_isError()) */
size_t ZSTDv05_decompress( void* dst, size_t dstCapacity,
                     const void* src, size_t compressedSize);

 /**
 ZSTDv05_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.5.x format
     srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
     cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                 or an error code if it fails (which can be tested using ZSTDv01_isError())
     dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                 or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
 */
void ZSTDv05_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                     size_t* cSize, unsigned long long* dBound);

/* *************************************
*  Helper functions
***************************************/
/* Error Management */
unsigned    ZSTDv05_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
const char* ZSTDv05_getErrorName(size_t code);     /*!< provides readable string for an error code */


/* *************************************
*  Explicit memory management
***************************************/
/** Decompression context */
typedef struct ZSTDv05_DCtx_s ZSTDv05_DCtx;
ZSTDv05_DCtx* ZSTDv05_createDCtx(void);
size_t ZSTDv05_freeDCtx(ZSTDv05_DCtx* dctx);      /*!< @return : errorCode */

/** ZSTDv05_decompressDCtx() :
*   Same as ZSTDv05_decompress(), but requires an already allocated ZSTDv05_DCtx (see ZSTDv05_createDCtx()) */
size_t ZSTDv05_decompressDCtx(ZSTDv05_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);


/*-***********************
*  Simple Dictionary API
*************************/
/*! ZSTDv05_decompress_usingDict() :
*   Decompression using a pre-defined Dictionary content (see dictBuilder).
*   Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted.
*   Note : dict can be NULL, in which case, it's equivalent to ZSTDv05_decompressDCtx() */
size_t ZSTDv05_decompress_usingDict(ZSTDv05_DCtx* dctx,
                                            void* dst, size_t dstCapacity,
                                      const void* src, size_t srcSize,
                                      const void* dict,size_t dictSize);

/*-************************
*  Advanced Streaming API
***************************/
typedef enum { ZSTDv05_fast, ZSTDv05_greedy, ZSTDv05_lazy, ZSTDv05_lazy2, ZSTDv05_btlazy2, ZSTDv05_opt, ZSTDv05_btopt } ZSTDv05_strategy;
typedef struct {
    U64 srcSize;
    U32 windowLog;     /* the only useful information to retrieve */
    U32 contentLog; U32 hashLog; U32 searchLog; U32 searchLength; U32 targetLength; ZSTDv05_strategy strategy;
} ZSTDv05_parameters;
size_t ZSTDv05_getFrameParams(ZSTDv05_parameters* params, const void* src, size_t srcSize);

size_t ZSTDv05_decompressBegin_usingDict(ZSTDv05_DCtx* dctx, const void* dict, size_t dictSize);
void   ZSTDv05_copyDCtx(ZSTDv05_DCtx* dstDCtx, const ZSTDv05_DCtx* srcDCtx);
size_t ZSTDv05_nextSrcSizeToDecompress(ZSTDv05_DCtx* dctx);
size_t ZSTDv05_decompressContinue(ZSTDv05_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);


/*-***********************
*  ZBUFF API
*************************/
typedef struct ZBUFFv05_DCtx_s ZBUFFv05_DCtx;
ZBUFFv05_DCtx* ZBUFFv05_createDCtx(void);
size_t         ZBUFFv05_freeDCtx(ZBUFFv05_DCtx* dctx);

size_t ZBUFFv05_decompressInit(ZBUFFv05_DCtx* dctx);
size_t ZBUFFv05_decompressInitDictionary(ZBUFFv05_DCtx* dctx, const void* dict, size_t dictSize);

size_t ZBUFFv05_decompressContinue(ZBUFFv05_DCtx* dctx,
                                            void* dst, size_t* dstCapacityPtr,
                                      const void* src, size_t* srcSizePtr);

/*-***************************************************************************
*  Streaming decompression
*
*  A ZBUFFv05_DCtx object is required to track streaming operations.
*  Use ZBUFFv05_createDCtx() and ZBUFFv05_freeDCtx() to create/release resources.
*  Use ZBUFFv05_decompressInit() to start a new decompression operation,
*   or ZBUFFv05_decompressInitDictionary() if decompression requires a dictionary.
*  Note that ZBUFFv05_DCtx objects can be reused multiple times.
*
*  Use ZBUFFv05_decompressContinue() repetitively to consume your input.
*  *srcSizePtr and *dstCapacityPtr can be any size.
*  The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
*  Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
*  The content of @dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters or change @dst.
*  @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency)
*            or 0 when a frame is completely decoded
*            or an error code, which can be tested using ZBUFFv05_isError().
*
*  Hint : recommended buffer sizes (not compulsory) : ZBUFFv05_recommendedDInSize() / ZBUFFv05_recommendedDOutSize()
*  output : ZBUFFv05_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
*  input  : ZBUFFv05_recommendedDInSize==128Kb+3; just follow indications from ZBUFFv05_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
* *******************************************************************************/


/* *************************************
*  Tool functions
***************************************/
unsigned ZBUFFv05_isError(size_t errorCode);
const char* ZBUFFv05_getErrorName(size_t errorCode);

/** Functions below provide recommended buffer sizes for Compression or Decompression operations.
*   These sizes are just hints, and tend to offer better latency */
size_t ZBUFFv05_recommendedDInSize(void);
size_t ZBUFFv05_recommendedDOutSize(void);



/*-*************************************
*  Constants
***************************************/
#define ZSTDv05_MAGICNUMBER 0xFD2FB525   /* v0.5 */




#if defined (__cplusplus)
}
#endif

#endif  /* ZSTDv0505_H */
/**** ended inlining zstd_v05.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
/**** start inlining zstd_v06.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTDv06_H
#define ZSTDv06_H

#if defined (__cplusplus)
extern "C" {
#endif

/*======  Dependency  ======*/
#include <stddef.h>   /* size_t */


/*======  Export for Windows  ======*/
/*!
*  ZSTDv06_DLL_EXPORT :
*  Enable exporting of functions when building a Windows DLL
*/
#if defined(_WIN32) && defined(ZSTDv06_DLL_EXPORT) && (ZSTDv06_DLL_EXPORT==1)
#  define ZSTDLIBv06_API __declspec(dllexport)
#else
#  define ZSTDLIBv06_API
#endif


/* *************************************
*  Simple functions
***************************************/
/*! ZSTDv06_decompress() :
    `compressedSize` : is the _exact_ size of the compressed blob, otherwise decompression will fail.
    `dstCapacity` must be large enough, equal or larger than originalSize.
    @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
              or an errorCode if it fails (which can be tested using ZSTDv06_isError()) */
ZSTDLIBv06_API size_t ZSTDv06_decompress( void* dst, size_t dstCapacity,
                                    const void* src, size_t compressedSize);

/**
ZSTDv06_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.6.x format
    srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
    cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                or an error code if it fails (which can be tested using ZSTDv01_isError())
    dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
*/
void ZSTDv06_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                     size_t* cSize, unsigned long long* dBound);

/* *************************************
*  Helper functions
***************************************/
ZSTDLIBv06_API size_t      ZSTDv06_compressBound(size_t srcSize); /*!< maximum compressed size (worst case scenario) */

/* Error Management */
ZSTDLIBv06_API unsigned    ZSTDv06_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
ZSTDLIBv06_API const char* ZSTDv06_getErrorName(size_t code);     /*!< provides readable string for an error code */


/* *************************************
*  Explicit memory management
***************************************/
/** Decompression context */
typedef struct ZSTDv06_DCtx_s ZSTDv06_DCtx;
ZSTDLIBv06_API ZSTDv06_DCtx* ZSTDv06_createDCtx(void);
ZSTDLIBv06_API size_t     ZSTDv06_freeDCtx(ZSTDv06_DCtx* dctx);      /*!< @return : errorCode */

/** ZSTDv06_decompressDCtx() :
*   Same as ZSTDv06_decompress(), but requires an already allocated ZSTDv06_DCtx (see ZSTDv06_createDCtx()) */
ZSTDLIBv06_API size_t ZSTDv06_decompressDCtx(ZSTDv06_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);


/*-***********************
*  Dictionary API
*************************/
/*! ZSTDv06_decompress_usingDict() :
*   Decompression using a pre-defined Dictionary content (see dictBuilder).
*   Dictionary must be identical to the one used during compression, otherwise regenerated data will be corrupted.
*   Note : dict can be NULL, in which case, it's equivalent to ZSTDv06_decompressDCtx() */
ZSTDLIBv06_API size_t ZSTDv06_decompress_usingDict(ZSTDv06_DCtx* dctx,
                                                   void* dst, size_t dstCapacity,
                                             const void* src, size_t srcSize,
                                             const void* dict,size_t dictSize);


/*-************************
*  Advanced Streaming API
***************************/
struct ZSTDv06_frameParams_s { unsigned long long frameContentSize; unsigned windowLog; };
typedef struct ZSTDv06_frameParams_s ZSTDv06_frameParams;

ZSTDLIBv06_API size_t ZSTDv06_getFrameParams(ZSTDv06_frameParams* fparamsPtr, const void* src, size_t srcSize);   /**< doesn't consume input */
ZSTDLIBv06_API size_t ZSTDv06_decompressBegin_usingDict(ZSTDv06_DCtx* dctx, const void* dict, size_t dictSize);
ZSTDLIBv06_API void   ZSTDv06_copyDCtx(ZSTDv06_DCtx* dctx, const ZSTDv06_DCtx* preparedDCtx);

ZSTDLIBv06_API size_t ZSTDv06_nextSrcSizeToDecompress(ZSTDv06_DCtx* dctx);
ZSTDLIBv06_API size_t ZSTDv06_decompressContinue(ZSTDv06_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);



/* *************************************
*  ZBUFF API
***************************************/

typedef struct ZBUFFv06_DCtx_s ZBUFFv06_DCtx;
ZSTDLIBv06_API ZBUFFv06_DCtx* ZBUFFv06_createDCtx(void);
ZSTDLIBv06_API size_t         ZBUFFv06_freeDCtx(ZBUFFv06_DCtx* dctx);

ZSTDLIBv06_API size_t ZBUFFv06_decompressInit(ZBUFFv06_DCtx* dctx);
ZSTDLIBv06_API size_t ZBUFFv06_decompressInitDictionary(ZBUFFv06_DCtx* dctx, const void* dict, size_t dictSize);

ZSTDLIBv06_API size_t ZBUFFv06_decompressContinue(ZBUFFv06_DCtx* dctx,
                                                  void* dst, size_t* dstCapacityPtr,
                                            const void* src, size_t* srcSizePtr);

/*-***************************************************************************
*  Streaming decompression howto
*
*  A ZBUFFv06_DCtx object is required to track streaming operations.
*  Use ZBUFFv06_createDCtx() and ZBUFFv06_freeDCtx() to create/release resources.
*  Use ZBUFFv06_decompressInit() to start a new decompression operation,
*   or ZBUFFv06_decompressInitDictionary() if decompression requires a dictionary.
*  Note that ZBUFFv06_DCtx objects can be re-init multiple times.
*
*  Use ZBUFFv06_decompressContinue() repetitively to consume your input.
*  *srcSizePtr and *dstCapacityPtr can be any size.
*  The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
*  Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
*  The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`.
*  @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency),
*            or 0 when a frame is completely decoded,
*            or an error code, which can be tested using ZBUFFv06_isError().
*
*  Hint : recommended buffer sizes (not compulsory) : ZBUFFv06_recommendedDInSize() and ZBUFFv06_recommendedDOutSize()
*  output : ZBUFFv06_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
*  input  : ZBUFFv06_recommendedDInSize == 128KB + 3;
*           just follow indications from ZBUFFv06_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
* *******************************************************************************/


/* *************************************
*  Tool functions
***************************************/
ZSTDLIBv06_API unsigned ZBUFFv06_isError(size_t errorCode);
ZSTDLIBv06_API const char* ZBUFFv06_getErrorName(size_t errorCode);

/** Functions below provide recommended buffer sizes for Compression or Decompression operations.
*   These sizes are just hints, they tend to offer better latency */
ZSTDLIBv06_API size_t ZBUFFv06_recommendedDInSize(void);
ZSTDLIBv06_API size_t ZBUFFv06_recommendedDOutSize(void);


/*-*************************************
*  Constants
***************************************/
#define ZSTDv06_MAGICNUMBER 0xFD2FB526   /* v0.6 */



#if defined (__cplusplus)
}
#endif

#endif  /* ZSTDv06_BUFFERED_H */
/**** ended inlining zstd_v06.h ****/
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
/**** start inlining zstd_v07.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

#ifndef ZSTDv07_H_235446
#define ZSTDv07_H_235446

#if defined (__cplusplus)
extern "C" {
#endif

/*======  Dependency  ======*/
#include <stddef.h>   /* size_t */


/*======  Export for Windows  ======*/
/*!
*  ZSTDv07_DLL_EXPORT :
*  Enable exporting of functions when building a Windows DLL
*/
#if defined(_WIN32) && defined(ZSTDv07_DLL_EXPORT) && (ZSTDv07_DLL_EXPORT==1)
#  define ZSTDLIBv07_API __declspec(dllexport)
#else
#  define ZSTDLIBv07_API
#endif


/* *************************************
*  Simple API
***************************************/
/*! ZSTDv07_getDecompressedSize() :
*   @return : decompressed size if known, 0 otherwise.
       note 1 : if `0`, follow up with ZSTDv07_getFrameParams() to know precise failure cause.
       note 2 : decompressed size could be wrong or intentionally modified !
                always ensure results fit within application's authorized limits */
unsigned long long ZSTDv07_getDecompressedSize(const void* src, size_t srcSize);

/*! ZSTDv07_decompress() :
    `compressedSize` : must be _exact_ size of compressed input, otherwise decompression will fail.
    `dstCapacity` must be equal or larger than originalSize.
    @return : the number of bytes decompressed into `dst` (<= `dstCapacity`),
              or an errorCode if it fails (which can be tested using ZSTDv07_isError()) */
ZSTDLIBv07_API size_t ZSTDv07_decompress( void* dst, size_t dstCapacity,
                                    const void* src, size_t compressedSize);

/**
ZSTDv07_findFrameSizeInfoLegacy() : get the source length and decompressed bound of a ZSTD frame compliant with v0.7.x format
    srcSize : The size of the 'src' buffer, at least as large as the frame pointed to by 'src'
    cSize (output parameter)  : the number of bytes that would be read to decompress this frame
                                or an error code if it fails (which can be tested using ZSTDv01_isError())
    dBound (output parameter) : an upper-bound for the decompressed size of the data in the frame
                                or ZSTD_CONTENTSIZE_ERROR if an error occurs

    note : assumes `cSize` and `dBound` are _not_ NULL.
*/
void ZSTDv07_findFrameSizeInfoLegacy(const void *src, size_t srcSize,
                                     size_t* cSize, unsigned long long* dBound);

/*======  Helper functions  ======*/
ZSTDLIBv07_API unsigned    ZSTDv07_isError(size_t code);          /*!< tells if a `size_t` function result is an error code */
ZSTDLIBv07_API const char* ZSTDv07_getErrorName(size_t code);     /*!< provides readable string from an error code */


/*-*************************************
*  Explicit memory management
***************************************/
/** Decompression context */
typedef struct ZSTDv07_DCtx_s ZSTDv07_DCtx;
ZSTDLIBv07_API ZSTDv07_DCtx* ZSTDv07_createDCtx(void);
ZSTDLIBv07_API size_t     ZSTDv07_freeDCtx(ZSTDv07_DCtx* dctx);      /*!< @return : errorCode */

/** ZSTDv07_decompressDCtx() :
*   Same as ZSTDv07_decompress(), requires an allocated ZSTDv07_DCtx (see ZSTDv07_createDCtx()) */
ZSTDLIBv07_API size_t ZSTDv07_decompressDCtx(ZSTDv07_DCtx* ctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);


/*-************************
*  Simple dictionary API
***************************/
/*! ZSTDv07_decompress_usingDict() :
*   Decompression using a pre-defined Dictionary content (see dictBuilder).
*   Dictionary must be identical to the one used during compression.
*   Note : This function load the dictionary, resulting in a significant startup time */
ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDict(ZSTDv07_DCtx* dctx,
                                                   void* dst, size_t dstCapacity,
                                             const void* src, size_t srcSize,
                                             const void* dict,size_t dictSize);


/*-**************************
*  Advanced Dictionary API
****************************/
/*! ZSTDv07_createDDict() :
*   Create a digested dictionary, ready to start decompression operation without startup delay.
*   `dict` can be released after creation */
typedef struct ZSTDv07_DDict_s ZSTDv07_DDict;
ZSTDLIBv07_API ZSTDv07_DDict* ZSTDv07_createDDict(const void* dict, size_t dictSize);
ZSTDLIBv07_API size_t      ZSTDv07_freeDDict(ZSTDv07_DDict* ddict);

/*! ZSTDv07_decompress_usingDDict() :
*   Decompression using a pre-digested Dictionary
*   Faster startup than ZSTDv07_decompress_usingDict(), recommended when same dictionary is used multiple times. */
ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDDict(ZSTDv07_DCtx* dctx,
                                                    void* dst, size_t dstCapacity,
                                              const void* src, size_t srcSize,
                                              const ZSTDv07_DDict* ddict);

typedef struct {
    unsigned long long frameContentSize;
    unsigned windowSize;
    unsigned dictID;
    unsigned checksumFlag;
} ZSTDv07_frameParams;

ZSTDLIBv07_API size_t ZSTDv07_getFrameParams(ZSTDv07_frameParams* fparamsPtr, const void* src, size_t srcSize);   /**< doesn't consume input */




/* *************************************
*  Streaming functions
***************************************/
typedef struct ZBUFFv07_DCtx_s ZBUFFv07_DCtx;
ZSTDLIBv07_API ZBUFFv07_DCtx* ZBUFFv07_createDCtx(void);
ZSTDLIBv07_API size_t      ZBUFFv07_freeDCtx(ZBUFFv07_DCtx* dctx);

ZSTDLIBv07_API size_t ZBUFFv07_decompressInit(ZBUFFv07_DCtx* dctx);
ZSTDLIBv07_API size_t ZBUFFv07_decompressInitDictionary(ZBUFFv07_DCtx* dctx, const void* dict, size_t dictSize);

ZSTDLIBv07_API size_t ZBUFFv07_decompressContinue(ZBUFFv07_DCtx* dctx,
                                            void* dst, size_t* dstCapacityPtr,
                                      const void* src, size_t* srcSizePtr);

/*-***************************************************************************
*  Streaming decompression howto
*
*  A ZBUFFv07_DCtx object is required to track streaming operations.
*  Use ZBUFFv07_createDCtx() and ZBUFFv07_freeDCtx() to create/release resources.
*  Use ZBUFFv07_decompressInit() to start a new decompression operation,
*   or ZBUFFv07_decompressInitDictionary() if decompression requires a dictionary.
*  Note that ZBUFFv07_DCtx objects can be re-init multiple times.
*
*  Use ZBUFFv07_decompressContinue() repetitively to consume your input.
*  *srcSizePtr and *dstCapacityPtr can be any size.
*  The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
*  Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
*  The content of `dst` will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change `dst`.
*  @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency),
*            or 0 when a frame is completely decoded,
*            or an error code, which can be tested using ZBUFFv07_isError().
*
*  Hint : recommended buffer sizes (not compulsory) : ZBUFFv07_recommendedDInSize() and ZBUFFv07_recommendedDOutSize()
*  output : ZBUFFv07_recommendedDOutSize== 128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
*  input  : ZBUFFv07_recommendedDInSize == 128KB + 3;
*           just follow indications from ZBUFFv07_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
* *******************************************************************************/


/* *************************************
*  Tool functions
***************************************/
ZSTDLIBv07_API unsigned ZBUFFv07_isError(size_t errorCode);
ZSTDLIBv07_API const char* ZBUFFv07_getErrorName(size_t errorCode);

/** Functions below provide recommended buffer sizes for Compression or Decompression operations.
*   These sizes are just hints, they tend to offer better latency */
ZSTDLIBv07_API size_t ZBUFFv07_recommendedDInSize(void);
ZSTDLIBv07_API size_t ZBUFFv07_recommendedDOutSize(void);


/*-*************************************
*  Constants
***************************************/
#define ZSTDv07_MAGICNUMBER            0xFD2FB527   /* v0.7 */


#if defined (__cplusplus)
}
#endif

#endif  /* ZSTDv07_H_235446 */
/**** ended inlining zstd_v07.h ****/
#endif

/** ZSTD_isLegacy() :
    @return : > 0 if supported by legacy decoder. 0 otherwise.
              return value is the version.
*/
MEM_STATIC unsigned ZSTD_isLegacy(const void* src, size_t srcSize)
{
    U32 magicNumberLE;
    if (srcSize<4) return 0;
    magicNumberLE = MEM_readLE32(src);
    switch(magicNumberLE)
    {
#if (ZSTD_LEGACY_SUPPORT <= 1)
        case ZSTDv01_magicNumberLE:return 1;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 2)
        case ZSTDv02_magicNumber : return 2;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 3)
        case ZSTDv03_magicNumber : return 3;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case ZSTDv04_magicNumber : return 4;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case ZSTDv05_MAGICNUMBER : return 5;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case ZSTDv06_MAGICNUMBER : return 6;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case ZSTDv07_MAGICNUMBER : return 7;
#endif
        default : return 0;
    }
}


MEM_STATIC unsigned long long ZSTD_getDecompressedSize_legacy(const void* src, size_t srcSize)
{
    U32 const version = ZSTD_isLegacy(src, srcSize);
    if (version < 5) return 0;  /* no decompressed size in frame header, or not a legacy format */
#if (ZSTD_LEGACY_SUPPORT <= 5)
    if (version==5) {
        ZSTDv05_parameters fParams;
        size_t const frResult = ZSTDv05_getFrameParams(&fParams, src, srcSize);
        if (frResult != 0) return 0;
        return fParams.srcSize;
    }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
    if (version==6) {
        ZSTDv06_frameParams fParams;
        size_t const frResult = ZSTDv06_getFrameParams(&fParams, src, srcSize);
        if (frResult != 0) return 0;
        return fParams.frameContentSize;
    }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
    if (version==7) {
        ZSTDv07_frameParams fParams;
        size_t const frResult = ZSTDv07_getFrameParams(&fParams, src, srcSize);
        if (frResult != 0) return 0;
        return fParams.frameContentSize;
    }
#endif
    return 0;   /* should not be possible */
}


MEM_STATIC size_t ZSTD_decompressLegacy(
                     void* dst, size_t dstCapacity,
               const void* src, size_t compressedSize,
               const void* dict,size_t dictSize)
{
    U32 const version = ZSTD_isLegacy(src, compressedSize);
    (void)dst; (void)dstCapacity; (void)dict; (void)dictSize;  /* unused when ZSTD_LEGACY_SUPPORT >= 8 */
    switch(version)
    {
#if (ZSTD_LEGACY_SUPPORT <= 1)
        case 1 :
            return ZSTDv01_decompress(dst, dstCapacity, src, compressedSize);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 2)
        case 2 :
            return ZSTDv02_decompress(dst, dstCapacity, src, compressedSize);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 3)
        case 3 :
            return ZSTDv03_decompress(dst, dstCapacity, src, compressedSize);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case 4 :
            return ZSTDv04_decompress(dst, dstCapacity, src, compressedSize);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case 5 :
            {   size_t result;
                ZSTDv05_DCtx* const zd = ZSTDv05_createDCtx();
                if (zd==NULL) return ERROR(memory_allocation);
                result = ZSTDv05_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize);
                ZSTDv05_freeDCtx(zd);
                return result;
            }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case 6 :
            {   size_t result;
                ZSTDv06_DCtx* const zd = ZSTDv06_createDCtx();
                if (zd==NULL) return ERROR(memory_allocation);
                result = ZSTDv06_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize);
                ZSTDv06_freeDCtx(zd);
                return result;
            }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case 7 :
            {   size_t result;
                ZSTDv07_DCtx* const zd = ZSTDv07_createDCtx();
                if (zd==NULL) return ERROR(memory_allocation);
                result = ZSTDv07_decompress_usingDict(zd, dst, dstCapacity, src, compressedSize, dict, dictSize);
                ZSTDv07_freeDCtx(zd);
                return result;
            }
#endif
        default :
            return ERROR(prefix_unknown);
    }
}

MEM_STATIC ZSTD_frameSizeInfo ZSTD_findFrameSizeInfoLegacy(const void *src, size_t srcSize)
{
    ZSTD_frameSizeInfo frameSizeInfo;
    U32 const version = ZSTD_isLegacy(src, srcSize);
    switch(version)
    {
#if (ZSTD_LEGACY_SUPPORT <= 1)
        case 1 :
            ZSTDv01_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 2)
        case 2 :
            ZSTDv02_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 3)
        case 3 :
            ZSTDv03_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case 4 :
            ZSTDv04_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case 5 :
            ZSTDv05_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case 6 :
            ZSTDv06_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case 7 :
            ZSTDv07_findFrameSizeInfoLegacy(src, srcSize,
                &frameSizeInfo.compressedSize,
                &frameSizeInfo.decompressedBound);
            break;
#endif
        default :
            frameSizeInfo.compressedSize = ERROR(prefix_unknown);
            frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
            break;
    }
    if (!ZSTD_isError(frameSizeInfo.compressedSize) && frameSizeInfo.compressedSize > srcSize) {
        frameSizeInfo.compressedSize = ERROR(srcSize_wrong);
        frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
    }
    return frameSizeInfo;
}

MEM_STATIC size_t ZSTD_findFrameCompressedSizeLegacy(const void *src, size_t srcSize)
{
    ZSTD_frameSizeInfo frameSizeInfo = ZSTD_findFrameSizeInfoLegacy(src, srcSize);
    return frameSizeInfo.compressedSize;
}

MEM_STATIC size_t ZSTD_freeLegacyStreamContext(void* legacyContext, U32 version)
{
    switch(version)
    {
        default :
        case 1 :
        case 2 :
        case 3 :
            (void)legacyContext;
            return ERROR(version_unsupported);
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case 4 : return ZBUFFv04_freeDCtx((ZBUFFv04_DCtx*)legacyContext);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case 5 : return ZBUFFv05_freeDCtx((ZBUFFv05_DCtx*)legacyContext);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case 6 : return ZBUFFv06_freeDCtx((ZBUFFv06_DCtx*)legacyContext);
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case 7 : return ZBUFFv07_freeDCtx((ZBUFFv07_DCtx*)legacyContext);
#endif
    }
}


MEM_STATIC size_t ZSTD_initLegacyStream(void** legacyContext, U32 prevVersion, U32 newVersion,
                                        const void* dict, size_t dictSize)
{
    DEBUGLOG(5, "ZSTD_initLegacyStream for v0.%u", newVersion);
    if (prevVersion != newVersion) ZSTD_freeLegacyStreamContext(*legacyContext, prevVersion);
    switch(newVersion)
    {
        default :
        case 1 :
        case 2 :
        case 3 :
            (void)dict; (void)dictSize;
            return 0;
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case 4 :
        {
            ZBUFFv04_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv04_createDCtx() : (ZBUFFv04_DCtx*)*legacyContext;
            if (dctx==NULL) return ERROR(memory_allocation);
            ZBUFFv04_decompressInit(dctx);
            ZBUFFv04_decompressWithDictionary(dctx, dict, dictSize);
            *legacyContext = dctx;
            return 0;
        }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case 5 :
        {
            ZBUFFv05_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv05_createDCtx() : (ZBUFFv05_DCtx*)*legacyContext;
            if (dctx==NULL) return ERROR(memory_allocation);
            ZBUFFv05_decompressInitDictionary(dctx, dict, dictSize);
            *legacyContext = dctx;
            return 0;
        }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case 6 :
        {
            ZBUFFv06_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv06_createDCtx() : (ZBUFFv06_DCtx*)*legacyContext;
            if (dctx==NULL) return ERROR(memory_allocation);
            ZBUFFv06_decompressInitDictionary(dctx, dict, dictSize);
            *legacyContext = dctx;
            return 0;
        }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case 7 :
        {
            ZBUFFv07_DCtx* dctx = (prevVersion != newVersion) ? ZBUFFv07_createDCtx() : (ZBUFFv07_DCtx*)*legacyContext;
            if (dctx==NULL) return ERROR(memory_allocation);
            ZBUFFv07_decompressInitDictionary(dctx, dict, dictSize);
            *legacyContext = dctx;
            return 0;
        }
#endif
    }
}



MEM_STATIC size_t ZSTD_decompressLegacyStream(void* legacyContext, U32 version,
                                              ZSTD_outBuffer* output, ZSTD_inBuffer* input)
{
    DEBUGLOG(5, "ZSTD_decompressLegacyStream for v0.%u", version);
    switch(version)
    {
        default :
        case 1 :
        case 2 :
        case 3 :
            (void)legacyContext; (void)output; (void)input;
            return ERROR(version_unsupported);
#if (ZSTD_LEGACY_SUPPORT <= 4)
        case 4 :
            {
                ZBUFFv04_DCtx* dctx = (ZBUFFv04_DCtx*) legacyContext;
                const void* src = (const char*)input->src + input->pos;
                size_t readSize = input->size - input->pos;
                void* dst = (char*)output->dst + output->pos;
                size_t decodedSize = output->size - output->pos;
                size_t const hintSize = ZBUFFv04_decompressContinue(dctx, dst, &decodedSize, src, &readSize);
                output->pos += decodedSize;
                input->pos += readSize;
                return hintSize;
            }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 5)
        case 5 :
            {
                ZBUFFv05_DCtx* dctx = (ZBUFFv05_DCtx*) legacyContext;
                const void* src = (const char*)input->src + input->pos;
                size_t readSize = input->size - input->pos;
                void* dst = (char*)output->dst + output->pos;
                size_t decodedSize = output->size - output->pos;
                size_t const hintSize = ZBUFFv05_decompressContinue(dctx, dst, &decodedSize, src, &readSize);
                output->pos += decodedSize;
                input->pos += readSize;
                return hintSize;
            }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 6)
        case 6 :
            {
                ZBUFFv06_DCtx* dctx = (ZBUFFv06_DCtx*) legacyContext;
                const void* src = (const char*)input->src + input->pos;
                size_t readSize = input->size - input->pos;
                void* dst = (char*)output->dst + output->pos;
                size_t decodedSize = output->size - output->pos;
                size_t const hintSize = ZBUFFv06_decompressContinue(dctx, dst, &decodedSize, src, &readSize);
                output->pos += decodedSize;
                input->pos += readSize;
                return hintSize;
            }
#endif
#if (ZSTD_LEGACY_SUPPORT <= 7)
        case 7 :
            {
                ZBUFFv07_DCtx* dctx = (ZBUFFv07_DCtx*) legacyContext;
                const void* src = (const char*)input->src + input->pos;
                size_t readSize = input->size - input->pos;
                void* dst = (char*)output->dst + output->pos;
                size_t decodedSize = output->size - output->pos;
                size_t const hintSize = ZBUFFv07_decompressContinue(dctx, dst, &decodedSize, src, &readSize);
                output->pos += decodedSize;
                input->pos += readSize;
                return hintSize;
            }
#endif
    }
}


#if defined (__cplusplus)
}
#endif

#endif   /* ZSTD_LEGACY_H */
/**** ended inlining ../legacy/zstd_legacy.h ****/
#endif



/*-*******************************************************
*  Types
*********************************************************/
struct ZSTD_DDict_s {
    void* dictBuffer;
    const void* dictContent;
    size_t dictSize;
    ZSTD_entropyDTables_t entropy;
    U32 dictID;
    U32 entropyPresent;
    ZSTD_customMem cMem;
};  /* typedef'd to ZSTD_DDict within "zstd.h" */

const void* ZSTD_DDict_dictContent(const ZSTD_DDict* ddict)
{
    assert(ddict != NULL);
    return ddict->dictContent;
}

size_t ZSTD_DDict_dictSize(const ZSTD_DDict* ddict)
{
    assert(ddict != NULL);
    return ddict->dictSize;
}

void ZSTD_copyDDictParameters(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
{
    DEBUGLOG(4, "ZSTD_copyDDictParameters");
    assert(dctx != NULL);
    assert(ddict != NULL);
    dctx->dictID = ddict->dictID;
    dctx->prefixStart = ddict->dictContent;
    dctx->virtualStart = ddict->dictContent;
    dctx->dictEnd = (const BYTE*)ddict->dictContent + ddict->dictSize;
    dctx->previousDstEnd = dctx->dictEnd;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    dctx->dictContentBeginForFuzzing = dctx->prefixStart;
    dctx->dictContentEndForFuzzing = dctx->previousDstEnd;
#endif
    if (ddict->entropyPresent) {
        dctx->litEntropy = 1;
        dctx->fseEntropy = 1;
        dctx->LLTptr = ddict->entropy.LLTable;
        dctx->MLTptr = ddict->entropy.MLTable;
        dctx->OFTptr = ddict->entropy.OFTable;
        dctx->HUFptr = ddict->entropy.hufTable;
        dctx->entropy.rep[0] = ddict->entropy.rep[0];
        dctx->entropy.rep[1] = ddict->entropy.rep[1];
        dctx->entropy.rep[2] = ddict->entropy.rep[2];
    } else {
        dctx->litEntropy = 0;
        dctx->fseEntropy = 0;
    }
}


static size_t
ZSTD_loadEntropy_intoDDict(ZSTD_DDict* ddict,
                           ZSTD_dictContentType_e dictContentType)
{
    ddict->dictID = 0;
    ddict->entropyPresent = 0;
    if (dictContentType == ZSTD_dct_rawContent) return 0;

    if (ddict->dictSize < 8) {
        if (dictContentType == ZSTD_dct_fullDict)
            return ERROR(dictionary_corrupted);   /* only accept specified dictionaries */
        return 0;   /* pure content mode */
    }
    {   U32 const magic = MEM_readLE32(ddict->dictContent);
        if (magic != ZSTD_MAGIC_DICTIONARY) {
            if (dictContentType == ZSTD_dct_fullDict)
                return ERROR(dictionary_corrupted);   /* only accept specified dictionaries */
            return 0;   /* pure content mode */
        }
    }
    ddict->dictID = MEM_readLE32((const char*)ddict->dictContent + ZSTD_FRAMEIDSIZE);

    /* load entropy tables */
    RETURN_ERROR_IF(ZSTD_isError(ZSTD_loadDEntropy(
            &ddict->entropy, ddict->dictContent, ddict->dictSize)),
        dictionary_corrupted, "");
    ddict->entropyPresent = 1;
    return 0;
}


static size_t ZSTD_initDDict_internal(ZSTD_DDict* ddict,
                                      const void* dict, size_t dictSize,
                                      ZSTD_dictLoadMethod_e dictLoadMethod,
                                      ZSTD_dictContentType_e dictContentType)
{
    if ((dictLoadMethod == ZSTD_dlm_byRef) || (!dict) || (!dictSize)) {
        ddict->dictBuffer = NULL;
        ddict->dictContent = dict;
        if (!dict) dictSize = 0;
    } else {
        void* const internalBuffer = ZSTD_malloc(dictSize, ddict->cMem);
        ddict->dictBuffer = internalBuffer;
        ddict->dictContent = internalBuffer;
        if (!internalBuffer) return ERROR(memory_allocation);
        memcpy(internalBuffer, dict, dictSize);
    }
    ddict->dictSize = dictSize;
    ddict->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001);  /* cover both little and big endian */

    /* parse dictionary content */
    FORWARD_IF_ERROR( ZSTD_loadEntropy_intoDDict(ddict, dictContentType) , "");

    return 0;
}

ZSTD_DDict* ZSTD_createDDict_advanced(const void* dict, size_t dictSize,
                                      ZSTD_dictLoadMethod_e dictLoadMethod,
                                      ZSTD_dictContentType_e dictContentType,
                                      ZSTD_customMem customMem)
{
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;

    {   ZSTD_DDict* const ddict = (ZSTD_DDict*) ZSTD_malloc(sizeof(ZSTD_DDict), customMem);
        if (ddict == NULL) return NULL;
        ddict->cMem = customMem;
        {   size_t const initResult = ZSTD_initDDict_internal(ddict,
                                            dict, dictSize,
                                            dictLoadMethod, dictContentType);
            if (ZSTD_isError(initResult)) {
                ZSTD_freeDDict(ddict);
                return NULL;
        }   }
        return ddict;
    }
}

/*! ZSTD_createDDict() :
*   Create a digested dictionary, to start decompression without startup delay.
*   `dict` content is copied inside DDict.
*   Consequently, `dict` can be released after `ZSTD_DDict` creation */
ZSTD_DDict* ZSTD_createDDict(const void* dict, size_t dictSize)
{
    ZSTD_customMem const allocator = { NULL, NULL, NULL };
    return ZSTD_createDDict_advanced(dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto, allocator);
}

/*! ZSTD_createDDict_byReference() :
 *  Create a digested dictionary, to start decompression without startup delay.
 *  Dictionary content is simply referenced, it will be accessed during decompression.
 *  Warning : dictBuffer must outlive DDict (DDict must be freed before dictBuffer) */
ZSTD_DDict* ZSTD_createDDict_byReference(const void* dictBuffer, size_t dictSize)
{
    ZSTD_customMem const allocator = { NULL, NULL, NULL };
    return ZSTD_createDDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, allocator);
}


const ZSTD_DDict* ZSTD_initStaticDDict(
                                void* sBuffer, size_t sBufferSize,
                                const void* dict, size_t dictSize,
                                ZSTD_dictLoadMethod_e dictLoadMethod,
                                ZSTD_dictContentType_e dictContentType)
{
    size_t const neededSpace = sizeof(ZSTD_DDict)
                             + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
    ZSTD_DDict* const ddict = (ZSTD_DDict*)sBuffer;
    assert(sBuffer != NULL);
    assert(dict != NULL);
    if ((size_t)sBuffer & 7) return NULL;   /* 8-aligned */
    if (sBufferSize < neededSpace) return NULL;
    if (dictLoadMethod == ZSTD_dlm_byCopy) {
        memcpy(ddict+1, dict, dictSize);  /* local copy */
        dict = ddict+1;
    }
    if (ZSTD_isError( ZSTD_initDDict_internal(ddict,
                                              dict, dictSize,
                                              ZSTD_dlm_byRef, dictContentType) ))
        return NULL;
    return ddict;
}


size_t ZSTD_freeDDict(ZSTD_DDict* ddict)
{
    if (ddict==NULL) return 0;   /* support free on NULL */
    {   ZSTD_customMem const cMem = ddict->cMem;
        ZSTD_free(ddict->dictBuffer, cMem);
        ZSTD_free(ddict, cMem);
        return 0;
    }
}

/*! ZSTD_estimateDDictSize() :
 *  Estimate amount of memory that will be needed to create a dictionary for decompression.
 *  Note : dictionary created by reference using ZSTD_dlm_byRef are smaller */
size_t ZSTD_estimateDDictSize(size_t dictSize, ZSTD_dictLoadMethod_e dictLoadMethod)
{
    return sizeof(ZSTD_DDict) + (dictLoadMethod == ZSTD_dlm_byRef ? 0 : dictSize);
}

size_t ZSTD_sizeof_DDict(const ZSTD_DDict* ddict)
{
    if (ddict==NULL) return 0;   /* support sizeof on NULL */
    return sizeof(*ddict) + (ddict->dictBuffer ? ddict->dictSize : 0) ;
}

/*! ZSTD_getDictID_fromDDict() :
 *  Provides the dictID of the dictionary loaded into `ddict`.
 *  If @return == 0, the dictionary is not conformant to Zstandard specification, or empty.
 *  Non-conformant dictionaries can still be loaded, but as content-only dictionaries. */
unsigned ZSTD_getDictID_fromDDict(const ZSTD_DDict* ddict)
{
    if (ddict==NULL) return 0;
    return ZSTD_getDictID_fromDict(ddict->dictContent, ddict->dictSize);
}
/**** ended inlining decompress/zstd_ddict.c ****/
/**** start inlining decompress/zstd_decompress.c ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */


/* ***************************************************************
*  Tuning parameters
*****************************************************************/
/*!
 * HEAPMODE :
 * Select how default decompression function ZSTD_decompress() allocates its context,
 * on stack (0), or into heap (1, default; requires malloc()).
 * Note that functions with explicit context such as ZSTD_decompressDCtx() are unaffected.
 */
#ifndef ZSTD_HEAPMODE
#  define ZSTD_HEAPMODE 1
#endif

/*!
*  LEGACY_SUPPORT :
*  if set to 1+, ZSTD_decompress() can decode older formats (v0.1+)
*/
#ifndef ZSTD_LEGACY_SUPPORT
#  define ZSTD_LEGACY_SUPPORT 0
#endif

/*!
 *  MAXWINDOWSIZE_DEFAULT :
 *  maximum window size accepted by DStream __by default__.
 *  Frames requiring more memory will be rejected.
 *  It's possible to set a different limit using ZSTD_DCtx_setMaxWindowSize().
 */
#ifndef ZSTD_MAXWINDOWSIZE_DEFAULT
#  define ZSTD_MAXWINDOWSIZE_DEFAULT (((U32)1 << ZSTD_WINDOWLOG_LIMIT_DEFAULT) + 1)
#endif

/*!
 *  NO_FORWARD_PROGRESS_MAX :
 *  maximum allowed nb of calls to ZSTD_decompressStream()
 *  without any forward progress
 *  (defined as: no byte read from input, and no byte flushed to output)
 *  before triggering an error.
 */
#ifndef ZSTD_NO_FORWARD_PROGRESS_MAX
#  define ZSTD_NO_FORWARD_PROGRESS_MAX 16
#endif


/*-*******************************************************
*  Dependencies
*********************************************************/
/**** skipping file: ../common/cpu.h ****/
/**** skipping file: ../common/mem.h ****/
#define FSE_STATIC_LINKING_ONLY
/**** skipping file: ../common/fse.h ****/
#define HUF_STATIC_LINKING_ONLY
/**** skipping file: ../common/huf.h ****/
/**** skipping file: ../common/zstd_internal.h ****/
/**** skipping file: zstd_decompress_internal.h ****/
/**** skipping file: zstd_ddict.h ****/
/**** start inlining zstd_decompress_block.h ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */


#ifndef ZSTD_DEC_BLOCK_H
#define ZSTD_DEC_BLOCK_H

/*-*******************************************************
 *  Dependencies
 *********************************************************/
#include <stddef.h>   /* size_t */
/**** skipping file: ../zstd.h ****/
/**** skipping file: ../common/zstd_internal.h ****/
/**** skipping file: zstd_decompress_internal.h ****/


/* ===   Prototypes   === */

/* note: prototypes already published within `zstd.h` :
 * ZSTD_decompressBlock()
 */

/* note: prototypes already published within `zstd_internal.h` :
 * ZSTD_getcBlockSize()
 * ZSTD_decodeSeqHeaders()
 */


/* ZSTD_decompressBlock_internal() :
 * decompress block, starting at `src`,
 * into destination buffer `dst`.
 * @return : decompressed block size,
 *           or an error code (which can be tested using ZSTD_isError())
 */
size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
                               void* dst, size_t dstCapacity,
                         const void* src, size_t srcSize, const int frame);

/* ZSTD_buildFSETable() :
 * generate FSE decoding table for one symbol (ll, ml or off)
 * this function must be called with valid parameters only
 * (dt is large enough, normalizedCounter distribution total is a power of 2, max is within range, etc.)
 * in which case it cannot fail.
 * Internal use only.
 */
void ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
             const short* normalizedCounter, unsigned maxSymbolValue,
             const U32* baseValue, const U32* nbAdditionalBits,
                   unsigned tableLog);


#endif /* ZSTD_DEC_BLOCK_H */
/**** ended inlining zstd_decompress_block.h ****/

#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
/**** skipping file: ../legacy/zstd_legacy.h ****/
#endif


/*-*************************************************************
*   Context management
***************************************************************/
size_t ZSTD_sizeof_DCtx (const ZSTD_DCtx* dctx)
{
    if (dctx==NULL) return 0;   /* support sizeof NULL */
    return sizeof(*dctx)
           + ZSTD_sizeof_DDict(dctx->ddictLocal)
           + dctx->inBuffSize + dctx->outBuffSize;
}

size_t ZSTD_estimateDCtxSize(void) { return sizeof(ZSTD_DCtx); }


static size_t ZSTD_startingInputLength(ZSTD_format_e format)
{
    size_t const startingInputLength = ZSTD_FRAMEHEADERSIZE_PREFIX(format);
    /* only supports formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless */
    assert( (format == ZSTD_f_zstd1) || (format == ZSTD_f_zstd1_magicless) );
    return startingInputLength;
}

static void ZSTD_initDCtx_internal(ZSTD_DCtx* dctx)
{
    dctx->format = ZSTD_f_zstd1;  /* ZSTD_decompressBegin() invokes ZSTD_startingInputLength() with argument dctx->format */
    dctx->staticSize  = 0;
    dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
    dctx->ddict       = NULL;
    dctx->ddictLocal  = NULL;
    dctx->dictEnd     = NULL;
    dctx->ddictIsCold = 0;
    dctx->dictUses = ZSTD_dont_use;
    dctx->inBuff      = NULL;
    dctx->inBuffSize  = 0;
    dctx->outBuffSize = 0;
    dctx->streamStage = zdss_init;
    dctx->legacyContext = NULL;
    dctx->previousLegacyVersion = 0;
    dctx->noForwardProgress = 0;
    dctx->oversizedDuration = 0;
    dctx->bmi2 = ZSTD_cpuid_bmi2(ZSTD_cpuid());
    dctx->outBufferMode = ZSTD_obm_buffered;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    dctx->dictContentEndForFuzzing = NULL;
#endif
}

ZSTD_DCtx* ZSTD_initStaticDCtx(void *workspace, size_t workspaceSize)
{
    ZSTD_DCtx* const dctx = (ZSTD_DCtx*) workspace;

    if ((size_t)workspace & 7) return NULL;  /* 8-aligned */
    if (workspaceSize < sizeof(ZSTD_DCtx)) return NULL;  /* minimum size */

    ZSTD_initDCtx_internal(dctx);
    dctx->staticSize = workspaceSize;
    dctx->inBuff = (char*)(dctx+1);
    return dctx;
}

ZSTD_DCtx* ZSTD_createDCtx_advanced(ZSTD_customMem customMem)
{
    if (!customMem.customAlloc ^ !customMem.customFree) return NULL;

    {   ZSTD_DCtx* const dctx = (ZSTD_DCtx*)ZSTD_malloc(sizeof(*dctx), customMem);
        if (!dctx) return NULL;
        dctx->customMem = customMem;
        ZSTD_initDCtx_internal(dctx);
        return dctx;
    }
}

ZSTD_DCtx* ZSTD_createDCtx(void)
{
    DEBUGLOG(3, "ZSTD_createDCtx");
    return ZSTD_createDCtx_advanced(ZSTD_defaultCMem);
}

static void ZSTD_clearDict(ZSTD_DCtx* dctx)
{
    ZSTD_freeDDict(dctx->ddictLocal);
    dctx->ddictLocal = NULL;
    dctx->ddict = NULL;
    dctx->dictUses = ZSTD_dont_use;
}

size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
{
    if (dctx==NULL) return 0;   /* support free on NULL */
    RETURN_ERROR_IF(dctx->staticSize, memory_allocation, "not compatible with static DCtx");
    {   ZSTD_customMem const cMem = dctx->customMem;
        ZSTD_clearDict(dctx);
        ZSTD_free(dctx->inBuff, cMem);
        dctx->inBuff = NULL;
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
        if (dctx->legacyContext)
            ZSTD_freeLegacyStreamContext(dctx->legacyContext, dctx->previousLegacyVersion);
#endif
        ZSTD_free(dctx, cMem);
        return 0;
    }
}

/* no longer useful */
void ZSTD_copyDCtx(ZSTD_DCtx* dstDCtx, const ZSTD_DCtx* srcDCtx)
{
    size_t const toCopy = (size_t)((char*)(&dstDCtx->inBuff) - (char*)dstDCtx);
    memcpy(dstDCtx, srcDCtx, toCopy);  /* no need to copy workspace */
}


/*-*************************************************************
 *   Frame header decoding
 ***************************************************************/

/*! ZSTD_isFrame() :
 *  Tells if the content of `buffer` starts with a valid Frame Identifier.
 *  Note : Frame Identifier is 4 bytes. If `size < 4`, @return will always be 0.
 *  Note 2 : Legacy Frame Identifiers are considered valid only if Legacy Support is enabled.
 *  Note 3 : Skippable Frame Identifiers are considered valid. */
unsigned ZSTD_isFrame(const void* buffer, size_t size)
{
    if (size < ZSTD_FRAMEIDSIZE) return 0;
    {   U32 const magic = MEM_readLE32(buffer);
        if (magic == ZSTD_MAGICNUMBER) return 1;
        if ((magic & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) return 1;
    }
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
    if (ZSTD_isLegacy(buffer, size)) return 1;
#endif
    return 0;
}

/** ZSTD_frameHeaderSize_internal() :
 *  srcSize must be large enough to reach header size fields.
 *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless.
 * @return : size of the Frame Header
 *           or an error code, which can be tested with ZSTD_isError() */
static size_t ZSTD_frameHeaderSize_internal(const void* src, size_t srcSize, ZSTD_format_e format)
{
    size_t const minInputSize = ZSTD_startingInputLength(format);
    RETURN_ERROR_IF(srcSize < minInputSize, srcSize_wrong, "");

    {   BYTE const fhd = ((const BYTE*)src)[minInputSize-1];
        U32 const dictID= fhd & 3;
        U32 const singleSegment = (fhd >> 5) & 1;
        U32 const fcsId = fhd >> 6;
        return minInputSize + !singleSegment
             + ZSTD_did_fieldSize[dictID] + ZSTD_fcs_fieldSize[fcsId]
             + (singleSegment && !fcsId);
    }
}

/** ZSTD_frameHeaderSize() :
 *  srcSize must be >= ZSTD_frameHeaderSize_prefix.
 * @return : size of the Frame Header,
 *           or an error code (if srcSize is too small) */
size_t ZSTD_frameHeaderSize(const void* src, size_t srcSize)
{
    return ZSTD_frameHeaderSize_internal(src, srcSize, ZSTD_f_zstd1);
}


/** ZSTD_getFrameHeader_advanced() :
 *  decode Frame Header, or require larger `srcSize`.
 *  note : only works for formats ZSTD_f_zstd1 and ZSTD_f_zstd1_magicless
 * @return : 0, `zfhPtr` is correctly filled,
 *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
 *           or an error code, which can be tested using ZSTD_isError() */
size_t ZSTD_getFrameHeader_advanced(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize, ZSTD_format_e format)
{
    const BYTE* ip = (const BYTE*)src;
    size_t const minInputSize = ZSTD_startingInputLength(format);

    memset(zfhPtr, 0, sizeof(*zfhPtr));   /* not strictly necessary, but static analyzer do not understand that zfhPtr is only going to be read only if return value is zero, since they are 2 different signals */
    if (srcSize < minInputSize) return minInputSize;
    RETURN_ERROR_IF(src==NULL, GENERIC, "invalid parameter");

    if ( (format != ZSTD_f_zstd1_magicless)
      && (MEM_readLE32(src) != ZSTD_MAGICNUMBER) ) {
        if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
            /* skippable frame */
            if (srcSize < ZSTD_SKIPPABLEHEADERSIZE)
                return ZSTD_SKIPPABLEHEADERSIZE; /* magic number + frame length */
            memset(zfhPtr, 0, sizeof(*zfhPtr));
            zfhPtr->frameContentSize = MEM_readLE32((const char *)src + ZSTD_FRAMEIDSIZE);
            zfhPtr->frameType = ZSTD_skippableFrame;
            return 0;
        }
        RETURN_ERROR(prefix_unknown, "");
    }

    /* ensure there is enough `srcSize` to fully read/decode frame header */
    {   size_t const fhsize = ZSTD_frameHeaderSize_internal(src, srcSize, format);
        if (srcSize < fhsize) return fhsize;
        zfhPtr->headerSize = (U32)fhsize;
    }

    {   BYTE const fhdByte = ip[minInputSize-1];
        size_t pos = minInputSize;
        U32 const dictIDSizeCode = fhdByte&3;
        U32 const checksumFlag = (fhdByte>>2)&1;
        U32 const singleSegment = (fhdByte>>5)&1;
        U32 const fcsID = fhdByte>>6;
        U64 windowSize = 0;
        U32 dictID = 0;
        U64 frameContentSize = ZSTD_CONTENTSIZE_UNKNOWN;
        RETURN_ERROR_IF((fhdByte & 0x08) != 0, frameParameter_unsupported,
                        "reserved bits, must be zero");

        if (!singleSegment) {
            BYTE const wlByte = ip[pos++];
            U32 const windowLog = (wlByte >> 3) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
            RETURN_ERROR_IF(windowLog > ZSTD_WINDOWLOG_MAX, frameParameter_windowTooLarge, "");
            windowSize = (1ULL << windowLog);
            windowSize += (windowSize >> 3) * (wlByte&7);
        }
        switch(dictIDSizeCode)
        {
            default: assert(0);  /* impossible */
            case 0 : break;
            case 1 : dictID = ip[pos]; pos++; break;
            case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
            case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
        }
        switch(fcsID)
        {
            default: assert(0);  /* impossible */
            case 0 : if (singleSegment) frameContentSize = ip[pos]; break;
            case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
            case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
            case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
        }
        if (singleSegment) windowSize = frameContentSize;

        zfhPtr->frameType = ZSTD_frame;
        zfhPtr->frameContentSize = frameContentSize;
        zfhPtr->windowSize = windowSize;
        zfhPtr->blockSizeMax = (unsigned) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
        zfhPtr->dictID = dictID;
        zfhPtr->checksumFlag = checksumFlag;
    }
    return 0;
}

/** ZSTD_getFrameHeader() :
 *  decode Frame Header, or require larger `srcSize`.
 *  note : this function does not consume input, it only reads it.
 * @return : 0, `zfhPtr` is correctly filled,
 *          >0, `srcSize` is too small, value is wanted `srcSize` amount,
 *           or an error code, which can be tested using ZSTD_isError() */
size_t ZSTD_getFrameHeader(ZSTD_frameHeader* zfhPtr, const void* src, size_t srcSize)
{
    return ZSTD_getFrameHeader_advanced(zfhPtr, src, srcSize, ZSTD_f_zstd1);
}


/** ZSTD_getFrameContentSize() :
 *  compatible with legacy mode
 * @return : decompressed size of the single frame pointed to be `src` if known, otherwise
 *         - ZSTD_CONTENTSIZE_UNKNOWN if the size cannot be determined
 *         - ZSTD_CONTENTSIZE_ERROR if an error occurred (e.g. invalid magic number, srcSize too small) */
unsigned long long ZSTD_getFrameContentSize(const void *src, size_t srcSize)
{
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
    if (ZSTD_isLegacy(src, srcSize)) {
        unsigned long long const ret = ZSTD_getDecompressedSize_legacy(src, srcSize);
        return ret == 0 ? ZSTD_CONTENTSIZE_UNKNOWN : ret;
    }
#endif
    {   ZSTD_frameHeader zfh;
        if (ZSTD_getFrameHeader(&zfh, src, srcSize) != 0)
            return ZSTD_CONTENTSIZE_ERROR;
        if (zfh.frameType == ZSTD_skippableFrame) {
            return 0;
        } else {
            return zfh.frameContentSize;
    }   }
}

static size_t readSkippableFrameSize(void const* src, size_t srcSize)
{
    size_t const skippableHeaderSize = ZSTD_SKIPPABLEHEADERSIZE;
    U32 sizeU32;

    RETURN_ERROR_IF(srcSize < ZSTD_SKIPPABLEHEADERSIZE, srcSize_wrong, "");

    sizeU32 = MEM_readLE32((BYTE const*)src + ZSTD_FRAMEIDSIZE);
    RETURN_ERROR_IF((U32)(sizeU32 + ZSTD_SKIPPABLEHEADERSIZE) < sizeU32,
                    frameParameter_unsupported, "");
    {
        size_t const skippableSize = skippableHeaderSize + sizeU32;
        RETURN_ERROR_IF(skippableSize > srcSize, srcSize_wrong, "");
        return skippableSize;
    }
}

/** ZSTD_findDecompressedSize() :
 *  compatible with legacy mode
 *  `srcSize` must be the exact length of some number of ZSTD compressed and/or
 *      skippable frames
 *  @return : decompressed size of the frames contained */
unsigned long long ZSTD_findDecompressedSize(const void* src, size_t srcSize)
{
    unsigned long long totalDstSize = 0;

    while (srcSize >= ZSTD_startingInputLength(ZSTD_f_zstd1)) {
        U32 const magicNumber = MEM_readLE32(src);

        if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
            size_t const skippableSize = readSkippableFrameSize(src, srcSize);
            if (ZSTD_isError(skippableSize)) {
                return ZSTD_CONTENTSIZE_ERROR;
            }
            assert(skippableSize <= srcSize);

            src = (const BYTE *)src + skippableSize;
            srcSize -= skippableSize;
            continue;
        }

        {   unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
            if (ret >= ZSTD_CONTENTSIZE_ERROR) return ret;

            /* check for overflow */
            if (totalDstSize + ret < totalDstSize) return ZSTD_CONTENTSIZE_ERROR;
            totalDstSize += ret;
        }
        {   size_t const frameSrcSize = ZSTD_findFrameCompressedSize(src, srcSize);
            if (ZSTD_isError(frameSrcSize)) {
                return ZSTD_CONTENTSIZE_ERROR;
            }

            src = (const BYTE *)src + frameSrcSize;
            srcSize -= frameSrcSize;
        }
    }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */

    if (srcSize) return ZSTD_CONTENTSIZE_ERROR;

    return totalDstSize;
}

/** ZSTD_getDecompressedSize() :
 *  compatible with legacy mode
 * @return : decompressed size if known, 0 otherwise
             note : 0 can mean any of the following :
                   - frame content is empty
                   - decompressed size field is not present in frame header
                   - frame header unknown / not supported
                   - frame header not complete (`srcSize` too small) */
unsigned long long ZSTD_getDecompressedSize(const void* src, size_t srcSize)
{
    unsigned long long const ret = ZSTD_getFrameContentSize(src, srcSize);
    ZSTD_STATIC_ASSERT(ZSTD_CONTENTSIZE_ERROR < ZSTD_CONTENTSIZE_UNKNOWN);
    return (ret >= ZSTD_CONTENTSIZE_ERROR) ? 0 : ret;
}


/** ZSTD_decodeFrameHeader() :
 * `headerSize` must be the size provided by ZSTD_frameHeaderSize().
 * @return : 0 if success, or an error code, which can be tested using ZSTD_isError() */
static size_t ZSTD_decodeFrameHeader(ZSTD_DCtx* dctx, const void* src, size_t headerSize)
{
    size_t const result = ZSTD_getFrameHeader_advanced(&(dctx->fParams), src, headerSize, dctx->format);
    if (ZSTD_isError(result)) return result;    /* invalid header */
    RETURN_ERROR_IF(result>0, srcSize_wrong, "headerSize too small");
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    /* Skip the dictID check in fuzzing mode, because it makes the search
     * harder.
     */
    RETURN_ERROR_IF(dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID),
                    dictionary_wrong, "");
#endif
    if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
    return 0;
}

static ZSTD_frameSizeInfo ZSTD_errorFrameSizeInfo(size_t ret)
{
    ZSTD_frameSizeInfo frameSizeInfo;
    frameSizeInfo.compressedSize = ret;
    frameSizeInfo.decompressedBound = ZSTD_CONTENTSIZE_ERROR;
    return frameSizeInfo;
}

static ZSTD_frameSizeInfo ZSTD_findFrameSizeInfo(const void* src, size_t srcSize)
{
    ZSTD_frameSizeInfo frameSizeInfo;
    memset(&frameSizeInfo, 0, sizeof(ZSTD_frameSizeInfo));

#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
    if (ZSTD_isLegacy(src, srcSize))
        return ZSTD_findFrameSizeInfoLegacy(src, srcSize);
#endif

    if ((srcSize >= ZSTD_SKIPPABLEHEADERSIZE)
        && (MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
        frameSizeInfo.compressedSize = readSkippableFrameSize(src, srcSize);
        assert(ZSTD_isError(frameSizeInfo.compressedSize) ||
               frameSizeInfo.compressedSize <= srcSize);
        return frameSizeInfo;
    } else {
        const BYTE* ip = (const BYTE*)src;
        const BYTE* const ipstart = ip;
        size_t remainingSize = srcSize;
        size_t nbBlocks = 0;
        ZSTD_frameHeader zfh;

        /* Extract Frame Header */
        {   size_t const ret = ZSTD_getFrameHeader(&zfh, src, srcSize);
            if (ZSTD_isError(ret))
                return ZSTD_errorFrameSizeInfo(ret);
            if (ret > 0)
                return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
        }

        ip += zfh.headerSize;
        remainingSize -= zfh.headerSize;

        /* Iterate over each block */
        while (1) {
            blockProperties_t blockProperties;
            size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
            if (ZSTD_isError(cBlockSize))
                return ZSTD_errorFrameSizeInfo(cBlockSize);

            if (ZSTD_blockHeaderSize + cBlockSize > remainingSize)
                return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));

            ip += ZSTD_blockHeaderSize + cBlockSize;
            remainingSize -= ZSTD_blockHeaderSize + cBlockSize;
            nbBlocks++;

            if (blockProperties.lastBlock) break;
        }

        /* Final frame content checksum */
        if (zfh.checksumFlag) {
            if (remainingSize < 4)
                return ZSTD_errorFrameSizeInfo(ERROR(srcSize_wrong));
            ip += 4;
        }

        frameSizeInfo.compressedSize = ip - ipstart;
        frameSizeInfo.decompressedBound = (zfh.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN)
                                        ? zfh.frameContentSize
                                        : nbBlocks * zfh.blockSizeMax;
        return frameSizeInfo;
    }
}

/** ZSTD_findFrameCompressedSize() :
 *  compatible with legacy mode
 *  `src` must point to the start of a ZSTD frame, ZSTD legacy frame, or skippable frame
 *  `srcSize` must be at least as large as the frame contained
 *  @return : the compressed size of the frame starting at `src` */
size_t ZSTD_findFrameCompressedSize(const void *src, size_t srcSize)
{
    ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize);
    return frameSizeInfo.compressedSize;
}

/** ZSTD_decompressBound() :
 *  compatible with legacy mode
 *  `src` must point to the start of a ZSTD frame or a skippeable frame
 *  `srcSize` must be at least as large as the frame contained
 *  @return : the maximum decompressed size of the compressed source
 */
unsigned long long ZSTD_decompressBound(const void* src, size_t srcSize)
{
    unsigned long long bound = 0;
    /* Iterate over each frame */
    while (srcSize > 0) {
        ZSTD_frameSizeInfo const frameSizeInfo = ZSTD_findFrameSizeInfo(src, srcSize);
        size_t const compressedSize = frameSizeInfo.compressedSize;
        unsigned long long const decompressedBound = frameSizeInfo.decompressedBound;
        if (ZSTD_isError(compressedSize) || decompressedBound == ZSTD_CONTENTSIZE_ERROR)
            return ZSTD_CONTENTSIZE_ERROR;
        assert(srcSize >= compressedSize);
        src = (const BYTE*)src + compressedSize;
        srcSize -= compressedSize;
        bound += decompressedBound;
    }
    return bound;
}


/*-*************************************************************
 *   Frame decoding
 ***************************************************************/

/** ZSTD_insertBlock() :
 *  insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
size_t ZSTD_insertBlock(ZSTD_DCtx* dctx, const void* blockStart, size_t blockSize)
{
    DEBUGLOG(5, "ZSTD_insertBlock: %u bytes", (unsigned)blockSize);
    ZSTD_checkContinuity(dctx, blockStart);
    dctx->previousDstEnd = (const char*)blockStart + blockSize;
    return blockSize;
}


static size_t ZSTD_copyRawBlock(void* dst, size_t dstCapacity,
                          const void* src, size_t srcSize)
{
    DEBUGLOG(5, "ZSTD_copyRawBlock");
    if (dst == NULL) {
        if (srcSize == 0) return 0;
        RETURN_ERROR(dstBuffer_null, "");
    }
    RETURN_ERROR_IF(srcSize > dstCapacity, dstSize_tooSmall, "");
    memcpy(dst, src, srcSize);
    return srcSize;
}

static size_t ZSTD_setRleBlock(void* dst, size_t dstCapacity,
                               BYTE b,
                               size_t regenSize)
{
    if (dst == NULL) {
        if (regenSize == 0) return 0;
        RETURN_ERROR(dstBuffer_null, "");
    }
    RETURN_ERROR_IF(regenSize > dstCapacity, dstSize_tooSmall, "");
    memset(dst, b, regenSize);
    return regenSize;
}


/*! ZSTD_decompressFrame() :
 * @dctx must be properly initialized
 *  will update *srcPtr and *srcSizePtr,
 *  to make *srcPtr progress by one frame. */
static size_t ZSTD_decompressFrame(ZSTD_DCtx* dctx,
                                   void* dst, size_t dstCapacity,
                             const void** srcPtr, size_t *srcSizePtr)
{
    const BYTE* ip = (const BYTE*)(*srcPtr);
    BYTE* const ostart = (BYTE* const)dst;
    BYTE* const oend = dstCapacity != 0 ? ostart + dstCapacity : ostart;
    BYTE* op = ostart;
    size_t remainingSrcSize = *srcSizePtr;

    DEBUGLOG(4, "ZSTD_decompressFrame (srcSize:%i)", (int)*srcSizePtr);

    /* check */
    RETURN_ERROR_IF(
        remainingSrcSize < ZSTD_FRAMEHEADERSIZE_MIN(dctx->format)+ZSTD_blockHeaderSize,
        srcSize_wrong, "");

    /* Frame Header */
    {   size_t const frameHeaderSize = ZSTD_frameHeaderSize_internal(
                ip, ZSTD_FRAMEHEADERSIZE_PREFIX(dctx->format), dctx->format);
        if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
        RETURN_ERROR_IF(remainingSrcSize < frameHeaderSize+ZSTD_blockHeaderSize,
                        srcSize_wrong, "");
        FORWARD_IF_ERROR( ZSTD_decodeFrameHeader(dctx, ip, frameHeaderSize) , "");
        ip += frameHeaderSize; remainingSrcSize -= frameHeaderSize;
    }

    /* Loop on each block */
    while (1) {
        size_t decodedSize;
        blockProperties_t blockProperties;
        size_t const cBlockSize = ZSTD_getcBlockSize(ip, remainingSrcSize, &blockProperties);
        if (ZSTD_isError(cBlockSize)) return cBlockSize;

        ip += ZSTD_blockHeaderSize;
        remainingSrcSize -= ZSTD_blockHeaderSize;
        RETURN_ERROR_IF(cBlockSize > remainingSrcSize, srcSize_wrong, "");

        switch(blockProperties.blockType)
        {
        case bt_compressed:
            decodedSize = ZSTD_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize, /* frame */ 1);
            break;
        case bt_raw :
            decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
            break;
        case bt_rle :
            decodedSize = ZSTD_setRleBlock(op, oend-op, *ip, blockProperties.origSize);
            break;
        case bt_reserved :
        default:
            RETURN_ERROR(corruption_detected, "invalid block type");
        }

        if (ZSTD_isError(decodedSize)) return decodedSize;
        if (dctx->fParams.checksumFlag)
            XXH64_update(&dctx->xxhState, op, decodedSize);
        if (decodedSize != 0)
            op += decodedSize;
        assert(ip != NULL);
        ip += cBlockSize;
        remainingSrcSize -= cBlockSize;
        if (blockProperties.lastBlock) break;
    }

    if (dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN) {
        RETURN_ERROR_IF((U64)(op-ostart) != dctx->fParams.frameContentSize,
                        corruption_detected, "");
    }
    if (dctx->fParams.checksumFlag) { /* Frame content checksum verification */
        U32 const checkCalc = (U32)XXH64_digest(&dctx->xxhState);
        U32 checkRead;
        RETURN_ERROR_IF(remainingSrcSize<4, checksum_wrong, "");
        checkRead = MEM_readLE32(ip);
        RETURN_ERROR_IF(checkRead != checkCalc, checksum_wrong, "");
        ip += 4;
        remainingSrcSize -= 4;
    }

    /* Allow caller to get size read */
    *srcPtr = ip;
    *srcSizePtr = remainingSrcSize;
    return op-ostart;
}

static size_t ZSTD_decompressMultiFrame(ZSTD_DCtx* dctx,
                                        void* dst, size_t dstCapacity,
                                  const void* src, size_t srcSize,
                                  const void* dict, size_t dictSize,
                                  const ZSTD_DDict* ddict)
{
    void* const dststart = dst;
    int moreThan1Frame = 0;

    DEBUGLOG(5, "ZSTD_decompressMultiFrame");
    assert(dict==NULL || ddict==NULL);  /* either dict or ddict set, not both */

    if (ddict) {
        dict = ZSTD_DDict_dictContent(ddict);
        dictSize = ZSTD_DDict_dictSize(ddict);
    }

    while (srcSize >= ZSTD_startingInputLength(dctx->format)) {

#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT >= 1)
        if (ZSTD_isLegacy(src, srcSize)) {
            size_t decodedSize;
            size_t const frameSize = ZSTD_findFrameCompressedSizeLegacy(src, srcSize);
            if (ZSTD_isError(frameSize)) return frameSize;
            RETURN_ERROR_IF(dctx->staticSize, memory_allocation,
                "legacy support is not compatible with static dctx");

            decodedSize = ZSTD_decompressLegacy(dst, dstCapacity, src, frameSize, dict, dictSize);
            if (ZSTD_isError(decodedSize)) return decodedSize;

            assert(decodedSize <=- dstCapacity);
            dst = (BYTE*)dst + decodedSize;
            dstCapacity -= decodedSize;

            src = (const BYTE*)src + frameSize;
            srcSize -= frameSize;

            continue;
        }
#endif

        {   U32 const magicNumber = MEM_readLE32(src);
            DEBUGLOG(4, "reading magic number %08X (expecting %08X)",
                        (unsigned)magicNumber, ZSTD_MAGICNUMBER);
            if ((magicNumber & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {
                size_t const skippableSize = readSkippableFrameSize(src, srcSize);
                FORWARD_IF_ERROR(skippableSize, "readSkippableFrameSize failed");
                assert(skippableSize <= srcSize);

                src = (const BYTE *)src + skippableSize;
                srcSize -= skippableSize;
                continue;
        }   }

        if (ddict) {
            /* we were called from ZSTD_decompress_usingDDict */
            FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(dctx, ddict), "");
        } else {
            /* this will initialize correctly with no dict if dict == NULL, so
             * use this in all cases but ddict */
            FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDict(dctx, dict, dictSize), "");
        }
        ZSTD_checkContinuity(dctx, dst);

        {   const size_t res = ZSTD_decompressFrame(dctx, dst, dstCapacity,
                                                    &src, &srcSize);
            RETURN_ERROR_IF(
                (ZSTD_getErrorCode(res) == ZSTD_error_prefix_unknown)
             && (moreThan1Frame==1),
                srcSize_wrong,
                "at least one frame successfully completed, but following "
                "bytes are garbage: it's more likely to be a srcSize error, "
                "specifying more bytes than compressed size of frame(s). This "
                "error message replaces ERROR(prefix_unknown), which would be "
                "confusing, as the first header is actually correct. Note that "
                "one could be unlucky, it might be a corruption error instead, "
                "happening right at the place where we expect zstd magic "
                "bytes. But this is _much_ less likely than a srcSize field "
                "error.");
            if (ZSTD_isError(res)) return res;
            assert(res <= dstCapacity);
            if (res != 0)
                dst = (BYTE*)dst + res;
            dstCapacity -= res;
        }
        moreThan1Frame = 1;
    }  /* while (srcSize >= ZSTD_frameHeaderSize_prefix) */

    RETURN_ERROR_IF(srcSize, srcSize_wrong, "input not entirely consumed");

    return (BYTE*)dst - (BYTE*)dststart;
}

size_t ZSTD_decompress_usingDict(ZSTD_DCtx* dctx,
                                 void* dst, size_t dstCapacity,
                           const void* src, size_t srcSize,
                           const void* dict, size_t dictSize)
{
    return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize, dict, dictSize, NULL);
}


static ZSTD_DDict const* ZSTD_getDDict(ZSTD_DCtx* dctx)
{
    switch (dctx->dictUses) {
    default:
        assert(0 /* Impossible */);
        /* fall-through */
    case ZSTD_dont_use:
        ZSTD_clearDict(dctx);
        return NULL;
    case ZSTD_use_indefinitely:
        return dctx->ddict;
    case ZSTD_use_once:
        dctx->dictUses = ZSTD_dont_use;
        return dctx->ddict;
    }
}

size_t ZSTD_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
{
    return ZSTD_decompress_usingDDict(dctx, dst, dstCapacity, src, srcSize, ZSTD_getDDict(dctx));
}


size_t ZSTD_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
{
#if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE>=1)
    size_t regenSize;
    ZSTD_DCtx* const dctx = ZSTD_createDCtx();
    RETURN_ERROR_IF(dctx==NULL, memory_allocation, "NULL pointer!");
    regenSize = ZSTD_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
    ZSTD_freeDCtx(dctx);
    return regenSize;
#else   /* stack mode */
    ZSTD_DCtx dctx;
    ZSTD_initDCtx_internal(&dctx);
    return ZSTD_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
#endif
}


/*-**************************************
*   Advanced Streaming Decompression API
*   Bufferless and synchronous
****************************************/
size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx) { return dctx->expected; }

/**
 * Similar to ZSTD_nextSrcSizeToDecompress(), but when when a block input can be streamed,
 * we allow taking a partial block as the input. Currently only raw uncompressed blocks can
 * be streamed.
 *
 * For blocks that can be streamed, this allows us to reduce the latency until we produce
 * output, and avoid copying the input.
 *
 * @param inputSize - The total amount of input that the caller currently has.
 */
static size_t ZSTD_nextSrcSizeToDecompressWithInputSize(ZSTD_DCtx* dctx, size_t inputSize) {
    if (!(dctx->stage == ZSTDds_decompressBlock || dctx->stage == ZSTDds_decompressLastBlock))
        return dctx->expected;
    if (dctx->bType != bt_raw)
        return dctx->expected;
    return MIN(MAX(inputSize, 1), dctx->expected);
}

ZSTD_nextInputType_e ZSTD_nextInputType(ZSTD_DCtx* dctx) {
    switch(dctx->stage)
    {
    default:   /* should not happen */
        assert(0);
    case ZSTDds_getFrameHeaderSize:
    case ZSTDds_decodeFrameHeader:
        return ZSTDnit_frameHeader;
    case ZSTDds_decodeBlockHeader:
        return ZSTDnit_blockHeader;
    case ZSTDds_decompressBlock:
        return ZSTDnit_block;
    case ZSTDds_decompressLastBlock:
        return ZSTDnit_lastBlock;
    case ZSTDds_checkChecksum:
        return ZSTDnit_checksum;
    case ZSTDds_decodeSkippableHeader:
    case ZSTDds_skipFrame:
        return ZSTDnit_skippableFrame;
    }
}

static int ZSTD_isSkipFrame(ZSTD_DCtx* dctx) { return dctx->stage == ZSTDds_skipFrame; }

/** ZSTD_decompressContinue() :
 *  srcSize : must be the exact nb of bytes expected (see ZSTD_nextSrcSizeToDecompress())
 *  @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
 *            or an error code, which can be tested using ZSTD_isError() */
size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
{
    DEBUGLOG(5, "ZSTD_decompressContinue (srcSize:%u)", (unsigned)srcSize);
    /* Sanity check */
    RETURN_ERROR_IF(srcSize != ZSTD_nextSrcSizeToDecompressWithInputSize(dctx, srcSize), srcSize_wrong, "not allowed");
    if (dstCapacity) ZSTD_checkContinuity(dctx, dst);

    switch (dctx->stage)
    {
    case ZSTDds_getFrameHeaderSize :
        assert(src != NULL);
        if (dctx->format == ZSTD_f_zstd1) {  /* allows header */
            assert(srcSize >= ZSTD_FRAMEIDSIZE);  /* to read skippable magic number */
            if ((MEM_readLE32(src) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {        /* skippable frame */
                memcpy(dctx->headerBuffer, src, srcSize);
                dctx->expected = ZSTD_SKIPPABLEHEADERSIZE - srcSize;  /* remaining to load to get full skippable frame header */
                dctx->stage = ZSTDds_decodeSkippableHeader;
                return 0;
        }   }
        dctx->headerSize = ZSTD_frameHeaderSize_internal(src, srcSize, dctx->format);
        if (ZSTD_isError(dctx->headerSize)) return dctx->headerSize;
        memcpy(dctx->headerBuffer, src, srcSize);
        dctx->expected = dctx->headerSize - srcSize;
        dctx->stage = ZSTDds_decodeFrameHeader;
        return 0;

    case ZSTDds_decodeFrameHeader:
        assert(src != NULL);
        memcpy(dctx->headerBuffer + (dctx->headerSize - srcSize), src, srcSize);
        FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize), "");
        dctx->expected = ZSTD_blockHeaderSize;
        dctx->stage = ZSTDds_decodeBlockHeader;
        return 0;

    case ZSTDds_decodeBlockHeader:
        {   blockProperties_t bp;
            size_t const cBlockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
            if (ZSTD_isError(cBlockSize)) return cBlockSize;
            RETURN_ERROR_IF(cBlockSize > dctx->fParams.blockSizeMax, corruption_detected, "Block Size Exceeds Maximum");
            dctx->expected = cBlockSize;
            dctx->bType = bp.blockType;
            dctx->rleSize = bp.origSize;
            if (cBlockSize) {
                dctx->stage = bp.lastBlock ? ZSTDds_decompressLastBlock : ZSTDds_decompressBlock;
                return 0;
            }
            /* empty block */
            if (bp.lastBlock) {
                if (dctx->fParams.checksumFlag) {
                    dctx->expected = 4;
                    dctx->stage = ZSTDds_checkChecksum;
                } else {
                    dctx->expected = 0; /* end of frame */
                    dctx->stage = ZSTDds_getFrameHeaderSize;
                }
            } else {
                dctx->expected = ZSTD_blockHeaderSize;  /* jump to next header */
                dctx->stage = ZSTDds_decodeBlockHeader;
            }
            return 0;
        }

    case ZSTDds_decompressLastBlock:
    case ZSTDds_decompressBlock:
        DEBUGLOG(5, "ZSTD_decompressContinue: case ZSTDds_decompressBlock");
        {   size_t rSize;
            switch(dctx->bType)
            {
            case bt_compressed:
                DEBUGLOG(5, "ZSTD_decompressContinue: case bt_compressed");
                rSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 1);
                dctx->expected = 0;  /* Streaming not supported */
                break;
            case bt_raw :
                assert(srcSize <= dctx->expected);
                rSize = ZSTD_copyRawBlock(dst, dstCapacity, src, srcSize);
                FORWARD_IF_ERROR(rSize, "ZSTD_copyRawBlock failed");
                assert(rSize == srcSize);
                dctx->expected -= rSize;
                break;
            case bt_rle :
                rSize = ZSTD_setRleBlock(dst, dstCapacity, *(const BYTE*)src, dctx->rleSize);
                dctx->expected = 0;  /* Streaming not supported */
                break;
            case bt_reserved :   /* should never happen */
            default:
                RETURN_ERROR(corruption_detected, "invalid block type");
            }
            FORWARD_IF_ERROR(rSize, "");
            RETURN_ERROR_IF(rSize > dctx->fParams.blockSizeMax, corruption_detected, "Decompressed Block Size Exceeds Maximum");
            DEBUGLOG(5, "ZSTD_decompressContinue: decoded size from block : %u", (unsigned)rSize);
            dctx->decodedSize += rSize;
            if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
            dctx->previousDstEnd = (char*)dst + rSize;

            /* Stay on the same stage until we are finished streaming the block. */
            if (dctx->expected > 0) {
                return rSize;
            }

            if (dctx->stage == ZSTDds_decompressLastBlock) {   /* end of frame */
                DEBUGLOG(4, "ZSTD_decompressContinue: decoded size from frame : %u", (unsigned)dctx->decodedSize);
                RETURN_ERROR_IF(
                    dctx->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
                 && dctx->decodedSize != dctx->fParams.frameContentSize,
                    corruption_detected, "");
                if (dctx->fParams.checksumFlag) {  /* another round for frame checksum */
                    dctx->expected = 4;
                    dctx->stage = ZSTDds_checkChecksum;
                } else {
                    dctx->expected = 0;   /* ends here */
                    dctx->stage = ZSTDds_getFrameHeaderSize;
                }
            } else {
                dctx->stage = ZSTDds_decodeBlockHeader;
                dctx->expected = ZSTD_blockHeaderSize;
            }
            return rSize;
        }

    case ZSTDds_checkChecksum:
        assert(srcSize == 4);  /* guaranteed by dctx->expected */
        {   U32 const h32 = (U32)XXH64_digest(&dctx->xxhState);
            U32 const check32 = MEM_readLE32(src);
            DEBUGLOG(4, "ZSTD_decompressContinue: checksum : calculated %08X :: %08X read", (unsigned)h32, (unsigned)check32);
            RETURN_ERROR_IF(check32 != h32, checksum_wrong, "");
            dctx->expected = 0;
            dctx->stage = ZSTDds_getFrameHeaderSize;
            return 0;
        }

    case ZSTDds_decodeSkippableHeader:
        assert(src != NULL);
        assert(srcSize <= ZSTD_SKIPPABLEHEADERSIZE);
        memcpy(dctx->headerBuffer + (ZSTD_SKIPPABLEHEADERSIZE - srcSize), src, srcSize);   /* complete skippable header */
        dctx->expected = MEM_readLE32(dctx->headerBuffer + ZSTD_FRAMEIDSIZE);   /* note : dctx->expected can grow seriously large, beyond local buffer size */
        dctx->stage = ZSTDds_skipFrame;
        return 0;

    case ZSTDds_skipFrame:
        dctx->expected = 0;
        dctx->stage = ZSTDds_getFrameHeaderSize;
        return 0;

    default:
        assert(0);   /* impossible */
        RETURN_ERROR(GENERIC, "impossible to reach");   /* some compiler require default to do something */
    }
}


static size_t ZSTD_refDictContent(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
{
    dctx->dictEnd = dctx->previousDstEnd;
    dctx->virtualStart = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
    dctx->prefixStart = dict;
    dctx->previousDstEnd = (const char*)dict + dictSize;
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
    dctx->dictContentBeginForFuzzing = dctx->prefixStart;
    dctx->dictContentEndForFuzzing = dctx->previousDstEnd;
#endif
    return 0;
}

/*! ZSTD_loadDEntropy() :
 *  dict : must point at beginning of a valid zstd dictionary.
 * @return : size of entropy tables read */
size_t
ZSTD_loadDEntropy(ZSTD_entropyDTables_t* entropy,
                  const void* const dict, size_t const dictSize)
{
    const BYTE* dictPtr = (const BYTE*)dict;
    const BYTE* const dictEnd = dictPtr + dictSize;

    RETURN_ERROR_IF(dictSize <= 8, dictionary_corrupted, "dict is too small");
    assert(MEM_readLE32(dict) == ZSTD_MAGIC_DICTIONARY);   /* dict must be valid */
    dictPtr += 8;   /* skip header = magic + dictID */

    ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, OFTable) == offsetof(ZSTD_entropyDTables_t, LLTable) + sizeof(entropy->LLTable));
    ZSTD_STATIC_ASSERT(offsetof(ZSTD_entropyDTables_t, MLTable) == offsetof(ZSTD_entropyDTables_t, OFTable) + sizeof(entropy->OFTable));
    ZSTD_STATIC_ASSERT(sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable) >= HUF_DECOMPRESS_WORKSPACE_SIZE);
    {   void* const workspace = &entropy->LLTable;   /* use fse tables as temporary workspace; implies fse tables are grouped together */
        size_t const workspaceSize = sizeof(entropy->LLTable) + sizeof(entropy->OFTable) + sizeof(entropy->MLTable);
#ifdef HUF_FORCE_DECOMPRESS_X1
        /* in minimal huffman, we always use X1 variants */
        size_t const hSize = HUF_readDTableX1_wksp(entropy->hufTable,
                                                dictPtr, dictEnd - dictPtr,
                                                workspace, workspaceSize);
#else
        size_t const hSize = HUF_readDTableX2_wksp(entropy->hufTable,
                                                dictPtr, dictEnd - dictPtr,
                                                workspace, workspaceSize);
#endif
        RETURN_ERROR_IF(HUF_isError(hSize), dictionary_corrupted, "");
        dictPtr += hSize;
    }

    {   short offcodeNCount[MaxOff+1];
        unsigned offcodeMaxValue = MaxOff, offcodeLog;
        size_t const offcodeHeaderSize = FSE_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
        RETURN_ERROR_IF(FSE_isError(offcodeHeaderSize), dictionary_corrupted, "");
        RETURN_ERROR_IF(offcodeMaxValue > MaxOff, dictionary_corrupted, "");
        RETURN_ERROR_IF(offcodeLog > OffFSELog, dictionary_corrupted, "");
        ZSTD_buildFSETable( entropy->OFTable,
                            offcodeNCount, offcodeMaxValue,
                            OF_base, OF_bits,
                            offcodeLog);
        dictPtr += offcodeHeaderSize;
    }

    {   short matchlengthNCount[MaxML+1];
        unsigned matchlengthMaxValue = MaxML, matchlengthLog;
        size_t const matchlengthHeaderSize = FSE_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
        RETURN_ERROR_IF(FSE_isError(matchlengthHeaderSize), dictionary_corrupted, "");
        RETURN_ERROR_IF(matchlengthMaxValue > MaxML, dictionary_corrupted, "");
        RETURN_ERROR_IF(matchlengthLog > MLFSELog, dictionary_corrupted, "");
        ZSTD_buildFSETable( entropy->MLTable,
                            matchlengthNCount, matchlengthMaxValue,
                            ML_base, ML_bits,
                            matchlengthLog);
        dictPtr += matchlengthHeaderSize;
    }

    {   short litlengthNCount[MaxLL+1];
        unsigned litlengthMaxValue = MaxLL, litlengthLog;
        size_t const litlengthHeaderSize = FSE_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
        RETURN_ERROR_IF(FSE_isError(litlengthHeaderSize), dictionary_corrupted, "");
        RETURN_ERROR_IF(litlengthMaxValue > MaxLL, dictionary_corrupted, "");
        RETURN_ERROR_IF(litlengthLog > LLFSELog, dictionary_corrupted, "");
        ZSTD_buildFSETable( entropy->LLTable,
                            litlengthNCount, litlengthMaxValue,
                            LL_base, LL_bits,
                            litlengthLog);
        dictPtr += litlengthHeaderSize;
    }

    RETURN_ERROR_IF(dictPtr+12 > dictEnd, dictionary_corrupted, "");
    {   int i;
        size_t const dictContentSize = (size_t)(dictEnd - (dictPtr+12));
        for (i=0; i<3; i++) {
            U32 const rep = MEM_readLE32(dictPtr); dictPtr += 4;
            RETURN_ERROR_IF(rep==0 || rep > dictContentSize,
                            dictionary_corrupted, "");
            entropy->rep[i] = rep;
    }   }

    return dictPtr - (const BYTE*)dict;
}

static size_t ZSTD_decompress_insertDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
{
    if (dictSize < 8) return ZSTD_refDictContent(dctx, dict, dictSize);
    {   U32 const magic = MEM_readLE32(dict);
        if (magic != ZSTD_MAGIC_DICTIONARY) {
            return ZSTD_refDictContent(dctx, dict, dictSize);   /* pure content mode */
    }   }
    dctx->dictID = MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);

    /* load entropy tables */
    {   size_t const eSize = ZSTD_loadDEntropy(&dctx->entropy, dict, dictSize);
        RETURN_ERROR_IF(ZSTD_isError(eSize), dictionary_corrupted, "");
        dict = (const char*)dict + eSize;
        dictSize -= eSize;
    }
    dctx->litEntropy = dctx->fseEntropy = 1;

    /* reference dictionary content */
    return ZSTD_refDictContent(dctx, dict, dictSize);
}

size_t ZSTD_decompressBegin(ZSTD_DCtx* dctx)
{
    assert(dctx != NULL);
    dctx->expected = ZSTD_startingInputLength(dctx->format);  /* dctx->format must be properly set */
    dctx->stage = ZSTDds_getFrameHeaderSize;
    dctx->decodedSize = 0;
    dctx->previousDstEnd = NULL;
    dctx->prefixStart = NULL;
    dctx->virtualStart = NULL;
    dctx->dictEnd = NULL;
    dctx->entropy.hufTable[0] = (HUF_DTable)((HufLog)*0x1000001);  /* cover both little and big endian */
    dctx->litEntropy = dctx->fseEntropy = 0;
    dctx->dictID = 0;
    dctx->bType = bt_reserved;
    ZSTD_STATIC_ASSERT(sizeof(dctx->entropy.rep) == sizeof(repStartValue));
    memcpy(dctx->entropy.rep, repStartValue, sizeof(repStartValue));  /* initial repcodes */
    dctx->LLTptr = dctx->entropy.LLTable;
    dctx->MLTptr = dctx->entropy.MLTable;
    dctx->OFTptr = dctx->entropy.OFTable;
    dctx->HUFptr = dctx->entropy.hufTable;
    return 0;
}

size_t ZSTD_decompressBegin_usingDict(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
{
    FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");
    if (dict && dictSize)
        RETURN_ERROR_IF(
            ZSTD_isError(ZSTD_decompress_insertDictionary(dctx, dict, dictSize)),
            dictionary_corrupted, "");
    return 0;
}


/* ======   ZSTD_DDict   ====== */

size_t ZSTD_decompressBegin_usingDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
{
    DEBUGLOG(4, "ZSTD_decompressBegin_usingDDict");
    assert(dctx != NULL);
    if (ddict) {
        const char* const dictStart = (const char*)ZSTD_DDict_dictContent(ddict);
        size_t const dictSize = ZSTD_DDict_dictSize(ddict);
        const void* const dictEnd = dictStart + dictSize;
        dctx->ddictIsCold = (dctx->dictEnd != dictEnd);
        DEBUGLOG(4, "DDict is %s",
                    dctx->ddictIsCold ? "~cold~" : "hot!");
    }
    FORWARD_IF_ERROR( ZSTD_decompressBegin(dctx) , "");
    if (ddict) {   /* NULL ddict is equivalent to no dictionary */
        ZSTD_copyDDictParameters(dctx, ddict);
    }
    return 0;
}

/*! ZSTD_getDictID_fromDict() :
 *  Provides the dictID stored within dictionary.
 *  if @return == 0, the dictionary is not conformant with Zstandard specification.
 *  It can still be loaded, but as a content-only dictionary. */
unsigned ZSTD_getDictID_fromDict(const void* dict, size_t dictSize)
{
    if (dictSize < 8) return 0;
    if (MEM_readLE32(dict) != ZSTD_MAGIC_DICTIONARY) return 0;
    return MEM_readLE32((const char*)dict + ZSTD_FRAMEIDSIZE);
}

/*! ZSTD_getDictID_fromFrame() :
 *  Provides the dictID required to decompress frame stored within `src`.
 *  If @return == 0, the dictID could not be decoded.
 *  This could for one of the following reasons :
 *  - The frame does not require a dictionary (most common case).
 *  - The frame was built with dictID intentionally removed.
 *    Needed dictionary is a hidden information.
 *    Note : this use case also happens when using a non-conformant dictionary.
 *  - `srcSize` is too small, and as a result, frame header could not be decoded.
 *    Note : possible if `srcSize < ZSTD_FRAMEHEADERSIZE_MAX`.
 *  - This is not a Zstandard frame.
 *  When identifying the exact failure cause, it's possible to use
 *  ZSTD_getFrameHeader(), which will provide a more precise error code. */
unsigned ZSTD_getDictID_fromFrame(const void* src, size_t srcSize)
{
    ZSTD_frameHeader zfp = { 0, 0, 0, ZSTD_frame, 0, 0, 0 };
    size_t const hError = ZSTD_getFrameHeader(&zfp, src, srcSize);
    if (ZSTD_isError(hError)) return 0;
    return zfp.dictID;
}


/*! ZSTD_decompress_usingDDict() :
*   Decompression using a pre-digested Dictionary
*   Use dictionary without significant overhead. */
size_t ZSTD_decompress_usingDDict(ZSTD_DCtx* dctx,
                                  void* dst, size_t dstCapacity,
                            const void* src, size_t srcSize,
                            const ZSTD_DDict* ddict)
{
    /* pass content and size in case legacy frames are encountered */
    return ZSTD_decompressMultiFrame(dctx, dst, dstCapacity, src, srcSize,
                                     NULL, 0,
                                     ddict);
}


/*=====================================
*   Streaming decompression
*====================================*/

ZSTD_DStream* ZSTD_createDStream(void)
{
    DEBUGLOG(3, "ZSTD_createDStream");
    return ZSTD_createDStream_advanced(ZSTD_defaultCMem);
}

ZSTD_DStream* ZSTD_initStaticDStream(void *workspace, size_t workspaceSize)
{
    return ZSTD_initStaticDCtx(workspace, workspaceSize);
}

ZSTD_DStream* ZSTD_createDStream_advanced(ZSTD_customMem customMem)
{
    return ZSTD_createDCtx_advanced(customMem);
}

size_t ZSTD_freeDStream(ZSTD_DStream* zds)
{
    return ZSTD_freeDCtx(zds);
}


/* ***  Initialization  *** */

size_t ZSTD_DStreamInSize(void)  { return ZSTD_BLOCKSIZE_MAX + ZSTD_blockHeaderSize; }
size_t ZSTD_DStreamOutSize(void) { return ZSTD_BLOCKSIZE_MAX; }

size_t ZSTD_DCtx_loadDictionary_advanced(ZSTD_DCtx* dctx,
                                   const void* dict, size_t dictSize,
                                         ZSTD_dictLoadMethod_e dictLoadMethod,
                                         ZSTD_dictContentType_e dictContentType)
{
    RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
    ZSTD_clearDict(dctx);
    if (dict && dictSize != 0) {
        dctx->ddictLocal = ZSTD_createDDict_advanced(dict, dictSize, dictLoadMethod, dictContentType, dctx->customMem);
        RETURN_ERROR_IF(dctx->ddictLocal == NULL, memory_allocation, "NULL pointer!");
        dctx->ddict = dctx->ddictLocal;
        dctx->dictUses = ZSTD_use_indefinitely;
    }
    return 0;
}

size_t ZSTD_DCtx_loadDictionary_byReference(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
{
    return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto);
}

size_t ZSTD_DCtx_loadDictionary(ZSTD_DCtx* dctx, const void* dict, size_t dictSize)
{
    return ZSTD_DCtx_loadDictionary_advanced(dctx, dict, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
}

size_t ZSTD_DCtx_refPrefix_advanced(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize, ZSTD_dictContentType_e dictContentType)
{
    FORWARD_IF_ERROR(ZSTD_DCtx_loadDictionary_advanced(dctx, prefix, prefixSize, ZSTD_dlm_byRef, dictContentType), "");
    dctx->dictUses = ZSTD_use_once;
    return 0;
}

size_t ZSTD_DCtx_refPrefix(ZSTD_DCtx* dctx, const void* prefix, size_t prefixSize)
{
    return ZSTD_DCtx_refPrefix_advanced(dctx, prefix, prefixSize, ZSTD_dct_rawContent);
}


/* ZSTD_initDStream_usingDict() :
 * return : expected size, aka ZSTD_startingInputLength().
 * this function cannot fail */
size_t ZSTD_initDStream_usingDict(ZSTD_DStream* zds, const void* dict, size_t dictSize)
{
    DEBUGLOG(4, "ZSTD_initDStream_usingDict");
    FORWARD_IF_ERROR( ZSTD_DCtx_reset(zds, ZSTD_reset_session_only) , "");
    FORWARD_IF_ERROR( ZSTD_DCtx_loadDictionary(zds, dict, dictSize) , "");
    return ZSTD_startingInputLength(zds->format);
}

/* note : this variant can't fail */
size_t ZSTD_initDStream(ZSTD_DStream* zds)
{
    DEBUGLOG(4, "ZSTD_initDStream");
    return ZSTD_initDStream_usingDDict(zds, NULL);
}

/* ZSTD_initDStream_usingDDict() :
 * ddict will just be referenced, and must outlive decompression session
 * this function cannot fail */
size_t ZSTD_initDStream_usingDDict(ZSTD_DStream* dctx, const ZSTD_DDict* ddict)
{
    FORWARD_IF_ERROR( ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only) , "");
    FORWARD_IF_ERROR( ZSTD_DCtx_refDDict(dctx, ddict) , "");
    return ZSTD_startingInputLength(dctx->format);
}

/* ZSTD_resetDStream() :
 * return : expected size, aka ZSTD_startingInputLength().
 * this function cannot fail */
size_t ZSTD_resetDStream(ZSTD_DStream* dctx)
{
    FORWARD_IF_ERROR(ZSTD_DCtx_reset(dctx, ZSTD_reset_session_only), "");
    return ZSTD_startingInputLength(dctx->format);
}


size_t ZSTD_DCtx_refDDict(ZSTD_DCtx* dctx, const ZSTD_DDict* ddict)
{
    RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
    ZSTD_clearDict(dctx);
    if (ddict) {
        dctx->ddict = ddict;
        dctx->dictUses = ZSTD_use_indefinitely;
    }
    return 0;
}

/* ZSTD_DCtx_setMaxWindowSize() :
 * note : no direct equivalence in ZSTD_DCtx_setParameter,
 * since this version sets windowSize, and the other sets windowLog */
size_t ZSTD_DCtx_setMaxWindowSize(ZSTD_DCtx* dctx, size_t maxWindowSize)
{
    ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
    size_t const min = (size_t)1 << bounds.lowerBound;
    size_t const max = (size_t)1 << bounds.upperBound;
    RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
    RETURN_ERROR_IF(maxWindowSize < min, parameter_outOfBound, "");
    RETURN_ERROR_IF(maxWindowSize > max, parameter_outOfBound, "");
    dctx->maxWindowSize = maxWindowSize;
    return 0;
}

size_t ZSTD_DCtx_setFormat(ZSTD_DCtx* dctx, ZSTD_format_e format)
{
    return ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, format);
}

ZSTD_bounds ZSTD_dParam_getBounds(ZSTD_dParameter dParam)
{
    ZSTD_bounds bounds = { 0, 0, 0 };
    switch(dParam) {
        case ZSTD_d_windowLogMax:
            bounds.lowerBound = ZSTD_WINDOWLOG_ABSOLUTEMIN;
            bounds.upperBound = ZSTD_WINDOWLOG_MAX;
            return bounds;
        case ZSTD_d_format:
            bounds.lowerBound = (int)ZSTD_f_zstd1;
            bounds.upperBound = (int)ZSTD_f_zstd1_magicless;
            ZSTD_STATIC_ASSERT(ZSTD_f_zstd1 < ZSTD_f_zstd1_magicless);
            return bounds;
        case ZSTD_d_stableOutBuffer:
            bounds.lowerBound = (int)ZSTD_obm_buffered;
            bounds.upperBound = (int)ZSTD_obm_stable;
            return bounds;
        default:;
    }
    bounds.error = ERROR(parameter_unsupported);
    return bounds;
}

/* ZSTD_dParam_withinBounds:
 * @return 1 if value is within dParam bounds,
 * 0 otherwise */
static int ZSTD_dParam_withinBounds(ZSTD_dParameter dParam, int value)
{
    ZSTD_bounds const bounds = ZSTD_dParam_getBounds(dParam);
    if (ZSTD_isError(bounds.error)) return 0;
    if (value < bounds.lowerBound) return 0;
    if (value > bounds.upperBound) return 0;
    return 1;
}

#define CHECK_DBOUNDS(p,v) {                \
    RETURN_ERROR_IF(!ZSTD_dParam_withinBounds(p, v), parameter_outOfBound, ""); \
}

size_t ZSTD_DCtx_setParameter(ZSTD_DCtx* dctx, ZSTD_dParameter dParam, int value)
{
    RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
    switch(dParam) {
        case ZSTD_d_windowLogMax:
            if (value == 0) value = ZSTD_WINDOWLOG_LIMIT_DEFAULT;
            CHECK_DBOUNDS(ZSTD_d_windowLogMax, value);
            dctx->maxWindowSize = ((size_t)1) << value;
            return 0;
        case ZSTD_d_format:
            CHECK_DBOUNDS(ZSTD_d_format, value);
            dctx->format = (ZSTD_format_e)value;
            return 0;
        case ZSTD_d_stableOutBuffer:
            CHECK_DBOUNDS(ZSTD_d_stableOutBuffer, value);
            dctx->outBufferMode = (ZSTD_outBufferMode_e)value;
            return 0;
        default:;
    }
    RETURN_ERROR(parameter_unsupported, "");
}

size_t ZSTD_DCtx_reset(ZSTD_DCtx* dctx, ZSTD_ResetDirective reset)
{
    if ( (reset == ZSTD_reset_session_only)
      || (reset == ZSTD_reset_session_and_parameters) ) {
        dctx->streamStage = zdss_init;
        dctx->noForwardProgress = 0;
    }
    if ( (reset == ZSTD_reset_parameters)
      || (reset == ZSTD_reset_session_and_parameters) ) {
        RETURN_ERROR_IF(dctx->streamStage != zdss_init, stage_wrong, "");
        ZSTD_clearDict(dctx);
        dctx->format = ZSTD_f_zstd1;
        dctx->maxWindowSize = ZSTD_MAXWINDOWSIZE_DEFAULT;
    }
    return 0;
}


size_t ZSTD_sizeof_DStream(const ZSTD_DStream* dctx)
{
    return ZSTD_sizeof_DCtx(dctx);
}

size_t ZSTD_decodingBufferSize_min(unsigned long long windowSize, unsigned long long frameContentSize)
{
    size_t const blockSize = (size_t) MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
    unsigned long long const neededRBSize = windowSize + blockSize + (WILDCOPY_OVERLENGTH * 2);
    unsigned long long const neededSize = MIN(frameContentSize, neededRBSize);
    size_t const minRBSize = (size_t) neededSize;
    RETURN_ERROR_IF((unsigned long long)minRBSize != neededSize,
                    frameParameter_windowTooLarge, "");
    return minRBSize;
}

size_t ZSTD_estimateDStreamSize(size_t windowSize)
{
    size_t const blockSize = MIN(windowSize, ZSTD_BLOCKSIZE_MAX);
    size_t const inBuffSize = blockSize;  /* no block can be larger */
    size_t const outBuffSize = ZSTD_decodingBufferSize_min(windowSize, ZSTD_CONTENTSIZE_UNKNOWN);
    return ZSTD_estimateDCtxSize() + inBuffSize + outBuffSize;
}

size_t ZSTD_estimateDStreamSize_fromFrame(const void* src, size_t srcSize)
{
    U32 const windowSizeMax = 1U << ZSTD_WINDOWLOG_MAX;   /* note : should be user-selectable, but requires an additional parameter (or a dctx) */
    ZSTD_frameHeader zfh;
    size_t const err = ZSTD_getFrameHeader(&zfh, src, srcSize);
    if (ZSTD_isError(err)) return err;
    RETURN_ERROR_IF(err>0, srcSize_wrong, "");
    RETURN_ERROR_IF(zfh.windowSize > windowSizeMax,
                    frameParameter_windowTooLarge, "");
    return ZSTD_estimateDStreamSize((size_t)zfh.windowSize);
}


/* *****   Decompression   ***** */

static int ZSTD_DCtx_isOverflow(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
{
    return (zds->inBuffSize + zds->outBuffSize) >= (neededInBuffSize + neededOutBuffSize) * ZSTD_WORKSPACETOOLARGE_FACTOR;
}

static void ZSTD_DCtx_updateOversizedDuration(ZSTD_DStream* zds, size_t const neededInBuffSize, size_t const neededOutBuffSize)
{
    if (ZSTD_DCtx_isOverflow(zds, neededInBuffSize, neededOutBuffSize))
        zds->oversizedDuration++;
    else 
        zds->oversizedDuration = 0;
}

static int ZSTD_DCtx_isOversizedTooLong(ZSTD_DStream* zds)
{
    return zds->oversizedDuration >= ZSTD_WORKSPACETOOLARGE_MAXDURATION;
}

/* Checks that the output buffer hasn't changed if ZSTD_obm_stable is used. */
static size_t ZSTD_checkOutBuffer(ZSTD_DStream const* zds, ZSTD_outBuffer const* output)
{
    ZSTD_outBuffer const expect = zds->expectedOutBuffer;
    /* No requirement when ZSTD_obm_stable is not enabled. */
    if (zds->outBufferMode != ZSTD_obm_stable)
        return 0;
    /* Any buffer is allowed in zdss_init, this must be the same for every other call until
     * the context is reset.
     */
    if (zds->streamStage == zdss_init)
        return 0;
    /* The buffer must match our expectation exactly. */
    if (expect.dst == output->dst && expect.pos == output->pos && expect.size == output->size)
        return 0;
    RETURN_ERROR(dstBuffer_wrong, "ZSTD_obm_stable enabled but output differs!");
}

/* Calls ZSTD_decompressContinue() with the right parameters for ZSTD_decompressStream()
 * and updates the stage and the output buffer state. This call is extracted so it can be
 * used both when reading directly from the ZSTD_inBuffer, and in buffered input mode.
 * NOTE: You must break after calling this function since the streamStage is modified.
 */
static size_t ZSTD_decompressContinueStream(
            ZSTD_DStream* zds, char** op, char* oend,
            void const* src, size_t srcSize) {
    int const isSkipFrame = ZSTD_isSkipFrame(zds);
    if (zds->outBufferMode == ZSTD_obm_buffered) {
        size_t const dstSize = isSkipFrame ? 0 : zds->outBuffSize - zds->outStart;
        size_t const decodedSize = ZSTD_decompressContinue(zds,
                zds->outBuff + zds->outStart, dstSize, src, srcSize);
        FORWARD_IF_ERROR(decodedSize, "");
        if (!decodedSize && !isSkipFrame) {
            zds->streamStage = zdss_read;
        } else {
            zds->outEnd = zds->outStart + decodedSize;
            zds->streamStage = zdss_flush;
        }
    } else {
        /* Write directly into the output buffer */
        size_t const dstSize = isSkipFrame ? 0 : oend - *op;
        size_t const decodedSize = ZSTD_decompressContinue(zds, *op, dstSize, src, srcSize);
        FORWARD_IF_ERROR(decodedSize, "");
        *op += decodedSize;
        /* Flushing is not needed. */
        zds->streamStage = zdss_read;
        assert(*op <= oend);
        assert(zds->outBufferMode == ZSTD_obm_stable);
    }
    return 0;
}

size_t ZSTD_decompressStream(ZSTD_DStream* zds, ZSTD_outBuffer* output, ZSTD_inBuffer* input)
{
    const char* const src = (const char*)input->src;
    const char* const istart = input->pos != 0 ? src + input->pos : src;
    const char* const iend = input->size != 0 ? src + input->size : src;
    const char* ip = istart;
    char* const dst = (char*)output->dst;
    char* const ostart = output->pos != 0 ? dst + output->pos : dst;
    char* const oend = output->size != 0 ? dst + output->size : dst;
    char* op = ostart;
    U32 someMoreWork = 1;

    DEBUGLOG(5, "ZSTD_decompressStream");
    RETURN_ERROR_IF(
        input->pos > input->size,
        srcSize_wrong,
        "forbidden. in: pos: %u   vs size: %u",
        (U32)input->pos, (U32)input->size);
    RETURN_ERROR_IF(
        output->pos > output->size,
        dstSize_tooSmall,
        "forbidden. out: pos: %u   vs size: %u",
        (U32)output->pos, (U32)output->size);
    DEBUGLOG(5, "input size : %u", (U32)(input->size - input->pos));
    FORWARD_IF_ERROR(ZSTD_checkOutBuffer(zds, output), "");

    while (someMoreWork) {
        switch(zds->streamStage)
        {
        case zdss_init :
            DEBUGLOG(5, "stage zdss_init => transparent reset ");
            zds->streamStage = zdss_loadHeader;
            zds->lhSize = zds->inPos = zds->outStart = zds->outEnd = 0;
            zds->legacyVersion = 0;
            zds->hostageByte = 0;
            zds->expectedOutBuffer = *output;
            /* fall-through */

        case zdss_loadHeader :
            DEBUGLOG(5, "stage zdss_loadHeader (srcSize : %u)", (U32)(iend - ip));
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
            if (zds->legacyVersion) {
                RETURN_ERROR_IF(zds->staticSize, memory_allocation,
                    "legacy support is incompatible with static dctx");
                {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, zds->legacyVersion, output, input);
                    if (hint==0) zds->streamStage = zdss_init;
                    return hint;
            }   }
#endif
            {   size_t const hSize = ZSTD_getFrameHeader_advanced(&zds->fParams, zds->headerBuffer, zds->lhSize, zds->format);
                DEBUGLOG(5, "header size : %u", (U32)hSize);
                if (ZSTD_isError(hSize)) {
#if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>=1)
                    U32 const legacyVersion = ZSTD_isLegacy(istart, iend-istart);
                    if (legacyVersion) {
                        ZSTD_DDict const* const ddict = ZSTD_getDDict(zds);
                        const void* const dict = ddict ? ZSTD_DDict_dictContent(ddict) : NULL;
                        size_t const dictSize = ddict ? ZSTD_DDict_dictSize(ddict) : 0;
                        DEBUGLOG(5, "ZSTD_decompressStream: detected legacy version v0.%u", legacyVersion);
                        RETURN_ERROR_IF(zds->staticSize, memory_allocation,
                            "legacy support is incompatible with static dctx");
                        FORWARD_IF_ERROR(ZSTD_initLegacyStream(&zds->legacyContext,
                                    zds->previousLegacyVersion, legacyVersion,
                                    dict, dictSize), "");
                        zds->legacyVersion = zds->previousLegacyVersion = legacyVersion;
                        {   size_t const hint = ZSTD_decompressLegacyStream(zds->legacyContext, legacyVersion, output, input);
                            if (hint==0) zds->streamStage = zdss_init;   /* or stay in stage zdss_loadHeader */
                            return hint;
                    }   }
#endif
                    return hSize;   /* error */
                }
                if (hSize != 0) {   /* need more input */
                    size_t const toLoad = hSize - zds->lhSize;   /* if hSize!=0, hSize > zds->lhSize */
                    size_t const remainingInput = (size_t)(iend-ip);
                    assert(iend >= ip);
                    if (toLoad > remainingInput) {   /* not enough input to load full header */
                        if (remainingInput > 0) {
                            memcpy(zds->headerBuffer + zds->lhSize, ip, remainingInput);
                            zds->lhSize += remainingInput;
                        }
                        input->pos = input->size;
                        return (MAX((size_t)ZSTD_FRAMEHEADERSIZE_MIN(zds->format), hSize) - zds->lhSize) + ZSTD_blockHeaderSize;   /* remaining header bytes + next block header */
                    }
                    assert(ip != NULL);
                    memcpy(zds->headerBuffer + zds->lhSize, ip, toLoad); zds->lhSize = hSize; ip += toLoad;
                    break;
            }   }

            /* check for single-pass mode opportunity */
            if (zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
                && zds->fParams.frameType != ZSTD_skippableFrame
                && (U64)(size_t)(oend-op) >= zds->fParams.frameContentSize) {
                size_t const cSize = ZSTD_findFrameCompressedSize(istart, iend-istart);
                if (cSize <= (size_t)(iend-istart)) {
                    /* shortcut : using single-pass mode */
                    size_t const decompressedSize = ZSTD_decompress_usingDDict(zds, op, oend-op, istart, cSize, ZSTD_getDDict(zds));
                    if (ZSTD_isError(decompressedSize)) return decompressedSize;
                    DEBUGLOG(4, "shortcut to single-pass ZSTD_decompress_usingDDict()")
                    ip = istart + cSize;
                    op += decompressedSize;
                    zds->expected = 0;
                    zds->streamStage = zdss_init;
                    someMoreWork = 0;
                    break;
            }   }

            /* Check output buffer is large enough for ZSTD_odm_stable. */
            if (zds->outBufferMode == ZSTD_obm_stable
                && zds->fParams.frameType != ZSTD_skippableFrame
                && zds->fParams.frameContentSize != ZSTD_CONTENTSIZE_UNKNOWN
                && (U64)(size_t)(oend-op) < zds->fParams.frameContentSize) {
                RETURN_ERROR(dstSize_tooSmall, "ZSTD_obm_stable passed but ZSTD_outBuffer is too small");
            }

            /* Consume header (see ZSTDds_decodeFrameHeader) */
            DEBUGLOG(4, "Consume header");
            FORWARD_IF_ERROR(ZSTD_decompressBegin_usingDDict(zds, ZSTD_getDDict(zds)), "");

            if ((MEM_readLE32(zds->headerBuffer) & ZSTD_MAGIC_SKIPPABLE_MASK) == ZSTD_MAGIC_SKIPPABLE_START) {  /* skippable frame */
                zds->expected = MEM_readLE32(zds->headerBuffer + ZSTD_FRAMEIDSIZE);
                zds->stage = ZSTDds_skipFrame;
            } else {
                FORWARD_IF_ERROR(ZSTD_decodeFrameHeader(zds, zds->headerBuffer, zds->lhSize), "");
                zds->expected = ZSTD_blockHeaderSize;
                zds->stage = ZSTDds_decodeBlockHeader;
            }

            /* control buffer memory usage */
            DEBUGLOG(4, "Control max memory usage (%u KB <= max %u KB)",
                        (U32)(zds->fParams.windowSize >>10),
                        (U32)(zds->maxWindowSize >> 10) );
            zds->fParams.windowSize = MAX(zds->fParams.windowSize, 1U << ZSTD_WINDOWLOG_ABSOLUTEMIN);
            RETURN_ERROR_IF(zds->fParams.windowSize > zds->maxWindowSize,
                            frameParameter_windowTooLarge, "");

            /* Adapt buffer sizes to frame header instructions */
            {   size_t const neededInBuffSize = MAX(zds->fParams.blockSizeMax, 4 /* frame checksum */);
                size_t const neededOutBuffSize = zds->outBufferMode == ZSTD_obm_buffered
                        ? ZSTD_decodingBufferSize_min(zds->fParams.windowSize, zds->fParams.frameContentSize)
                        : 0;

                ZSTD_DCtx_updateOversizedDuration(zds, neededInBuffSize, neededOutBuffSize);

                {   int const tooSmall = (zds->inBuffSize < neededInBuffSize) || (zds->outBuffSize < neededOutBuffSize);
                    int const tooLarge = ZSTD_DCtx_isOversizedTooLong(zds);
                    
                    if (tooSmall || tooLarge) {
                        size_t const bufferSize = neededInBuffSize + neededOutBuffSize;
                        DEBUGLOG(4, "inBuff  : from %u to %u",
                                    (U32)zds->inBuffSize, (U32)neededInBuffSize);
                        DEBUGLOG(4, "outBuff : from %u to %u",
                                    (U32)zds->outBuffSize, (U32)neededOutBuffSize);
                        if (zds->staticSize) {  /* static DCtx */
                            DEBUGLOG(4, "staticSize : %u", (U32)zds->staticSize);
                            assert(zds->staticSize >= sizeof(ZSTD_DCtx));  /* controlled at init */
                            RETURN_ERROR_IF(
                                bufferSize > zds->staticSize - sizeof(ZSTD_DCtx),
                                memory_allocation, "");
                        } else {
                            ZSTD_free(zds->inBuff, zds->customMem);
                            zds->inBuffSize = 0;
                            zds->outBuffSize = 0;
                            zds->inBuff = (char*)ZSTD_malloc(bufferSize, zds->customMem);
                            RETURN_ERROR_IF(zds->inBuff == NULL, memory_allocation, "");
                        }
                        zds->inBuffSize = neededInBuffSize;
                        zds->outBuff = zds->inBuff + zds->inBuffSize;
                        zds->outBuffSize = neededOutBuffSize;
            }   }   }
            zds->streamStage = zdss_read;
            /* fall-through */

        case zdss_read:
            DEBUGLOG(5, "stage zdss_read");
            {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip);
                DEBUGLOG(5, "neededInSize = %u", (U32)neededInSize);
                if (neededInSize==0) {  /* end of frame */
                    zds->streamStage = zdss_init;
                    someMoreWork = 0;
                    break;
                }
                if ((size_t)(iend-ip) >= neededInSize) {  /* decode directly from src */
                    FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, ip, neededInSize), "");
                    ip += neededInSize;
                    /* Function modifies the stage so we must break */
                    break;
            }   }
            if (ip==iend) { someMoreWork = 0; break; }   /* no more input */
            zds->streamStage = zdss_load;
            /* fall-through */

        case zdss_load:
            {   size_t const neededInSize = ZSTD_nextSrcSizeToDecompress(zds);
                size_t const toLoad = neededInSize - zds->inPos;
                int const isSkipFrame = ZSTD_isSkipFrame(zds);
                size_t loadedSize;
                /* At this point we shouldn't be decompressing a block that we can stream. */
                assert(neededInSize == ZSTD_nextSrcSizeToDecompressWithInputSize(zds, iend - ip));
                if (isSkipFrame) {
                    loadedSize = MIN(toLoad, (size_t)(iend-ip));
                } else {
                    RETURN_ERROR_IF(toLoad > zds->inBuffSize - zds->inPos,
                                    corruption_detected,
                                    "should never happen");
                    loadedSize = ZSTD_limitCopy(zds->inBuff + zds->inPos, toLoad, ip, iend-ip);
                }
                ip += loadedSize;
                zds->inPos += loadedSize;
                if (loadedSize < toLoad) { someMoreWork = 0; break; }   /* not enough input, wait for more */

                /* decode loaded input */
                zds->inPos = 0;   /* input is consumed */
                FORWARD_IF_ERROR(ZSTD_decompressContinueStream(zds, &op, oend, zds->inBuff, neededInSize), "");
                /* Function modifies the stage so we must break */
                break;
            }
        case zdss_flush:
            {   size_t const toFlushSize = zds->outEnd - zds->outStart;
                size_t const flushedSize = ZSTD_limitCopy(op, oend-op, zds->outBuff + zds->outStart, toFlushSize);
                op += flushedSize;
                zds->outStart += flushedSize;
                if (flushedSize == toFlushSize) {  /* flush completed */
                    zds->streamStage = zdss_read;
                    if ( (zds->outBuffSize < zds->fParams.frameContentSize)
                      && (zds->outStart + zds->fParams.blockSizeMax > zds->outBuffSize) ) {
                        DEBUGLOG(5, "restart filling outBuff from beginning (left:%i, needed:%u)",
                                (int)(zds->outBuffSize - zds->outStart),
                                (U32)zds->fParams.blockSizeMax);
                        zds->outStart = zds->outEnd = 0;
                    }
                    break;
            }   }
            /* cannot complete flush */
            someMoreWork = 0;
            break;

        default:
            assert(0);    /* impossible */
            RETURN_ERROR(GENERIC, "impossible to reach");   /* some compiler require default to do something */
    }   }

    /* result */
    input->pos = (size_t)(ip - (const char*)(input->src));
    output->pos = (size_t)(op - (char*)(output->dst));

    /* Update the expected output buffer for ZSTD_obm_stable. */
    zds->expectedOutBuffer = *output;

    if ((ip==istart) && (op==ostart)) {  /* no forward progress */
        zds->noForwardProgress ++;
        if (zds->noForwardProgress >= ZSTD_NO_FORWARD_PROGRESS_MAX) {
            RETURN_ERROR_IF(op==oend, dstSize_tooSmall, "");
            RETURN_ERROR_IF(ip==iend, srcSize_wrong, "");
            assert(0);
        }
    } else {
        zds->noForwardProgress = 0;
    }
    {   size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zds);
        if (!nextSrcSizeHint) {   /* frame fully decoded */
            if (zds->outEnd == zds->outStart) {  /* output fully flushed */
                if (zds->hostageByte) {
                    if (input->pos >= input->size) {
                        /* can't release hostage (not present) */
                        zds->streamStage = zdss_read;
                        return 1;
                    }
                    input->pos++;  /* release hostage */
                }   /* zds->hostageByte */
                return 0;
            }  /* zds->outEnd == zds->outStart */
            if (!zds->hostageByte) { /* output not fully flushed; keep last byte as hostage; will be released when all output is flushed */
                input->pos--;   /* note : pos > 0, otherwise, impossible to finish reading last block */
                zds->hostageByte=1;
            }
            return 1;
        }  /* nextSrcSizeHint==0 */
        nextSrcSizeHint += ZSTD_blockHeaderSize * (ZSTD_nextInputType(zds) == ZSTDnit_block);   /* preload header of next block */
        assert(zds->inPos <= nextSrcSizeHint);
        nextSrcSizeHint -= zds->inPos;   /* part already loaded*/
        return nextSrcSizeHint;
    }
}

size_t ZSTD_decompressStream_simpleArgs (
                            ZSTD_DCtx* dctx,
                            void* dst, size_t dstCapacity, size_t* dstPos,
                      const void* src, size_t srcSize, size_t* srcPos)
{
    ZSTD_outBuffer output = { dst, dstCapacity, *dstPos };
    ZSTD_inBuffer  input  = { src, srcSize, *srcPos };
    /* ZSTD_compress_generic() will check validity of dstPos and srcPos */
    size_t const cErr = ZSTD_decompressStream(dctx, &output, &input);
    *dstPos = output.pos;
    *srcPos = input.pos;
    return cErr;
}
/**** ended inlining decompress/zstd_decompress.c ****/
/**** start inlining decompress/zstd_decompress_block.c ****/
/*
 * Copyright (c) 2016-2020, Yann Collet, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under both the BSD-style license (found in the
 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
 * in the COPYING file in the root directory of this source tree).
 * You may select, at your option, one of the above-listed licenses.
 */

/* zstd_decompress_block :
 * this module takes care of decompressing _compressed_ block */

/*-*******************************************************
*  Dependencies
*********************************************************/
/**** skipping file: ../common/compiler.h ****/
/**** skipping file: ../common/cpu.h ****/
/**** skipping file: ../common/mem.h ****/
#define FSE_STATIC_LINKING_ONLY
/**** skipping file: ../common/fse.h ****/
#define HUF_STATIC_LINKING_ONLY
/**** skipping file: ../common/huf.h ****/
/**** skipping file: ../common/zstd_internal.h ****/
/**** skipping file: zstd_decompress_internal.h ****/
/**** skipping file: zstd_ddict.h ****/
/**** skipping file: zstd_decompress_block.h ****/

/*_*******************************************************
*  Macros
**********************************************************/

/* These two optional macros force the use one way or another of the two
 * ZSTD_decompressSequences implementations. You can't force in both directions
 * at the same time.
 */
#if defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
    defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
#error "Cannot force the use of the short and the long ZSTD_decompressSequences variants!"
#endif


/*_*******************************************************
*  Memory operations
**********************************************************/
static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }


/*-*************************************************************
 *   Block decoding
 ***************************************************************/

/*! ZSTD_getcBlockSize() :
 *  Provides the size of compressed block from block header `src` */
size_t ZSTD_getcBlockSize(const void* src, size_t srcSize,
                          blockProperties_t* bpPtr)
{
    RETURN_ERROR_IF(srcSize < ZSTD_blockHeaderSize, srcSize_wrong, "");

    {   U32 const cBlockHeader = MEM_readLE24(src);
        U32 const cSize = cBlockHeader >> 3;
        bpPtr->lastBlock = cBlockHeader & 1;
        bpPtr->blockType = (blockType_e)((cBlockHeader >> 1) & 3);
        bpPtr->origSize = cSize;   /* only useful for RLE */
        if (bpPtr->blockType == bt_rle) return 1;
        RETURN_ERROR_IF(bpPtr->blockType == bt_reserved, corruption_detected, "");
        return cSize;
    }
}


/* Hidden declaration for fullbench */
size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
                          const void* src, size_t srcSize);
/*! ZSTD_decodeLiteralsBlock() :
 * @return : nb of bytes read from src (< srcSize )
 *  note : symbol not declared but exposed for fullbench */
size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
                          const void* src, size_t srcSize)   /* note : srcSize < BLOCKSIZE */
{
    DEBUGLOG(5, "ZSTD_decodeLiteralsBlock");
    RETURN_ERROR_IF(srcSize < MIN_CBLOCK_SIZE, corruption_detected, "");

    {   const BYTE* const istart = (const BYTE*) src;
        symbolEncodingType_e const litEncType = (symbolEncodingType_e)(istart[0] & 3);

        switch(litEncType)
        {
        case set_repeat:
            DEBUGLOG(5, "set_repeat flag : re-using stats from previous compressed literals block");
            RETURN_ERROR_IF(dctx->litEntropy==0, dictionary_corrupted, "");
            /* fall-through */

        case set_compressed:
            RETURN_ERROR_IF(srcSize < 5, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for case 3");
            {   size_t lhSize, litSize, litCSize;
                U32 singleStream=0;
                U32 const lhlCode = (istart[0] >> 2) & 3;
                U32 const lhc = MEM_readLE32(istart);
                size_t hufSuccess;
                switch(lhlCode)
                {
                case 0: case 1: default:   /* note : default is impossible, since lhlCode into [0..3] */
                    /* 2 - 2 - 10 - 10 */
                    singleStream = !lhlCode;
                    lhSize = 3;
                    litSize  = (lhc >> 4) & 0x3FF;
                    litCSize = (lhc >> 14) & 0x3FF;
                    break;
                case 2:
                    /* 2 - 2 - 14 - 14 */
                    lhSize = 4;
                    litSize  = (lhc >> 4) & 0x3FFF;
                    litCSize = lhc >> 18;
                    break;
                case 3:
                    /* 2 - 2 - 18 - 18 */
                    lhSize = 5;
                    litSize  = (lhc >> 4) & 0x3FFFF;
                    litCSize = (lhc >> 22) + ((size_t)istart[4] << 10);
                    break;
                }
                RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
                RETURN_ERROR_IF(litCSize + lhSize > srcSize, corruption_detected, "");

                /* prefetch huffman table if cold */
                if (dctx->ddictIsCold && (litSize > 768 /* heuristic */)) {
                    PREFETCH_AREA(dctx->HUFptr, sizeof(dctx->entropy.hufTable));
                }

                if (litEncType==set_repeat) {
                    if (singleStream) {
                        hufSuccess = HUF_decompress1X_usingDTable_bmi2(
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
                            dctx->HUFptr, dctx->bmi2);
                    } else {
                        hufSuccess = HUF_decompress4X_usingDTable_bmi2(
                            dctx->litBuffer, litSize, istart+lhSize, litCSize,
                            dctx->HUFptr, dctx->bmi2);
                    }
                } else {
                    if (singleStream) {
#if defined(HUF_FORCE_DECOMPRESS_X2)
                        hufSuccess = HUF_decompress1X_DCtx_wksp(
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
                            istart+lhSize, litCSize, dctx->workspace,
                            sizeof(dctx->workspace));
#else
                        hufSuccess = HUF_decompress1X1_DCtx_wksp_bmi2(
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
                            istart+lhSize, litCSize, dctx->workspace,
                            sizeof(dctx->workspace), dctx->bmi2);
#endif
                    } else {
                        hufSuccess = HUF_decompress4X_hufOnly_wksp_bmi2(
                            dctx->entropy.hufTable, dctx->litBuffer, litSize,
                            istart+lhSize, litCSize, dctx->workspace,
                            sizeof(dctx->workspace), dctx->bmi2);
                    }
                }

                RETURN_ERROR_IF(HUF_isError(hufSuccess), corruption_detected, "");

                dctx->litPtr = dctx->litBuffer;
                dctx->litSize = litSize;
                dctx->litEntropy = 1;
                if (litEncType==set_compressed) dctx->HUFptr = dctx->entropy.hufTable;
                memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
                return litCSize + lhSize;
            }

        case set_basic:
            {   size_t litSize, lhSize;
                U32 const lhlCode = ((istart[0]) >> 2) & 3;
                switch(lhlCode)
                {
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
                    lhSize = 1;
                    litSize = istart[0] >> 3;
                    break;
                case 1:
                    lhSize = 2;
                    litSize = MEM_readLE16(istart) >> 4;
                    break;
                case 3:
                    lhSize = 3;
                    litSize = MEM_readLE24(istart) >> 4;
                    break;
                }

                if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) {  /* risk reading beyond src buffer with wildcopy */
                    RETURN_ERROR_IF(litSize+lhSize > srcSize, corruption_detected, "");
                    memcpy(dctx->litBuffer, istart+lhSize, litSize);
                    dctx->litPtr = dctx->litBuffer;
                    dctx->litSize = litSize;
                    memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
                    return lhSize+litSize;
                }
                /* direct reference into compressed stream */
                dctx->litPtr = istart+lhSize;
                dctx->litSize = litSize;
                return lhSize+litSize;
            }

        case set_rle:
            {   U32 const lhlCode = ((istart[0]) >> 2) & 3;
                size_t litSize, lhSize;
                switch(lhlCode)
                {
                case 0: case 2: default:   /* note : default is impossible, since lhlCode into [0..3] */
                    lhSize = 1;
                    litSize = istart[0] >> 3;
                    break;
                case 1:
                    lhSize = 2;
                    litSize = MEM_readLE16(istart) >> 4;
                    break;
                case 3:
                    lhSize = 3;
                    litSize = MEM_readLE24(istart) >> 4;
                    RETURN_ERROR_IF(srcSize<4, corruption_detected, "srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4");
                    break;
                }
                RETURN_ERROR_IF(litSize > ZSTD_BLOCKSIZE_MAX, corruption_detected, "");
                memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
                dctx->litPtr = dctx->litBuffer;
                dctx->litSize = litSize;
                return lhSize+1;
            }
        default:
            RETURN_ERROR(corruption_detected, "impossible");
        }
    }
}

/* Default FSE distribution tables.
 * These are pre-calculated FSE decoding tables using default distributions as defined in specification :
 * https://github.com/facebook/zstd/blob/master/doc/zstd_compression_format.md#default-distributions
 * They were generated programmatically with following method :
 * - start from default distributions, present in /lib/common/zstd_internal.h
 * - generate tables normally, using ZSTD_buildFSETable()
 * - printout the content of tables
 * - pretify output, report below, test with fuzzer to ensure it's correct */

/* Default FSE distribution table for Literal Lengths */
static const ZSTD_seqSymbol LL_defaultDTable[(1<<LL_DEFAULTNORMLOG)+1] = {
     {  1,  1,  1, LL_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
     /* nextState, nbAddBits, nbBits, baseVal */
     {  0,  0,  4,    0},  { 16,  0,  4,    0},
     { 32,  0,  5,    1},  {  0,  0,  5,    3},
     {  0,  0,  5,    4},  {  0,  0,  5,    6},
     {  0,  0,  5,    7},  {  0,  0,  5,    9},
     {  0,  0,  5,   10},  {  0,  0,  5,   12},
     {  0,  0,  6,   14},  {  0,  1,  5,   16},
     {  0,  1,  5,   20},  {  0,  1,  5,   22},
     {  0,  2,  5,   28},  {  0,  3,  5,   32},
     {  0,  4,  5,   48},  { 32,  6,  5,   64},
     {  0,  7,  5,  128},  {  0,  8,  6,  256},
     {  0, 10,  6, 1024},  {  0, 12,  6, 4096},
     { 32,  0,  4,    0},  {  0,  0,  4,    1},
     {  0,  0,  5,    2},  { 32,  0,  5,    4},
     {  0,  0,  5,    5},  { 32,  0,  5,    7},
     {  0,  0,  5,    8},  { 32,  0,  5,   10},
     {  0,  0,  5,   11},  {  0,  0,  6,   13},
     { 32,  1,  5,   16},  {  0,  1,  5,   18},
     { 32,  1,  5,   22},  {  0,  2,  5,   24},
     { 32,  3,  5,   32},  {  0,  3,  5,   40},
     {  0,  6,  4,   64},  { 16,  6,  4,   64},
     { 32,  7,  5,  128},  {  0,  9,  6,  512},
     {  0, 11,  6, 2048},  { 48,  0,  4,    0},
     { 16,  0,  4,    1},  { 32,  0,  5,    2},
     { 32,  0,  5,    3},  { 32,  0,  5,    5},
     { 32,  0,  5,    6},  { 32,  0,  5,    8},
     { 32,  0,  5,    9},  { 32,  0,  5,   11},
     { 32,  0,  5,   12},  {  0,  0,  6,   15},
     { 32,  1,  5,   18},  { 32,  1,  5,   20},
     { 32,  2,  5,   24},  { 32,  2,  5,   28},
     { 32,  3,  5,   40},  { 32,  4,  5,   48},
     {  0, 16,  6,65536},  {  0, 15,  6,32768},
     {  0, 14,  6,16384},  {  0, 13,  6, 8192},
};   /* LL_defaultDTable */

/* Default FSE distribution table for Offset Codes */
static const ZSTD_seqSymbol OF_defaultDTable[(1<<OF_DEFAULTNORMLOG)+1] = {
    {  1,  1,  1, OF_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
    /* nextState, nbAddBits, nbBits, baseVal */
    {  0,  0,  5,    0},     {  0,  6,  4,   61},
    {  0,  9,  5,  509},     {  0, 15,  5,32765},
    {  0, 21,  5,2097149},   {  0,  3,  5,    5},
    {  0,  7,  4,  125},     {  0, 12,  5, 4093},
    {  0, 18,  5,262141},    {  0, 23,  5,8388605},
    {  0,  5,  5,   29},     {  0,  8,  4,  253},
    {  0, 14,  5,16381},     {  0, 20,  5,1048573},
    {  0,  2,  5,    1},     { 16,  7,  4,  125},
    {  0, 11,  5, 2045},     {  0, 17,  5,131069},
    {  0, 22,  5,4194301},   {  0,  4,  5,   13},
    { 16,  8,  4,  253},     {  0, 13,  5, 8189},
    {  0, 19,  5,524285},    {  0,  1,  5,    1},
    { 16,  6,  4,   61},     {  0, 10,  5, 1021},
    {  0, 16,  5,65533},     {  0, 28,  5,268435453},
    {  0, 27,  5,134217725}, {  0, 26,  5,67108861},
    {  0, 25,  5,33554429},  {  0, 24,  5,16777213},
};   /* OF_defaultDTable */


/* Default FSE distribution table for Match Lengths */
static const ZSTD_seqSymbol ML_defaultDTable[(1<<ML_DEFAULTNORMLOG)+1] = {
    {  1,  1,  1, ML_DEFAULTNORMLOG},  /* header : fastMode, tableLog */
    /* nextState, nbAddBits, nbBits, baseVal */
    {  0,  0,  6,    3},  {  0,  0,  4,    4},
    { 32,  0,  5,    5},  {  0,  0,  5,    6},
    {  0,  0,  5,    8},  {  0,  0,  5,    9},
    {  0,  0,  5,   11},  {  0,  0,  6,   13},
    {  0,  0,  6,   16},  {  0,  0,  6,   19},
    {  0,  0,  6,   22},  {  0,  0,  6,   25},
    {  0,  0,  6,   28},  {  0,  0,  6,   31},
    {  0,  0,  6,   34},  {  0,  1,  6,   37},
    {  0,  1,  6,   41},  {  0,  2,  6,   47},
    {  0,  3,  6,   59},  {  0,  4,  6,   83},
    {  0,  7,  6,  131},  {  0,  9,  6,  515},
    { 16,  0,  4,    4},  {  0,  0,  4,    5},
    { 32,  0,  5,    6},  {  0,  0,  5,    7},
    { 32,  0,  5,    9},  {  0,  0,  5,   10},
    {  0,  0,  6,   12},  {  0,  0,  6,   15},
    {  0,  0,  6,   18},  {  0,  0,  6,   21},
    {  0,  0,  6,   24},  {  0,  0,  6,   27},
    {  0,  0,  6,   30},  {  0,  0,  6,   33},
    {  0,  1,  6,   35},  {  0,  1,  6,   39},
    {  0,  2,  6,   43},  {  0,  3,  6,   51},
    {  0,  4,  6,   67},  {  0,  5,  6,   99},
    {  0,  8,  6,  259},  { 32,  0,  4,    4},
    { 48,  0,  4,    4},  { 16,  0,  4,    5},
    { 32,  0,  5,    7},  { 32,  0,  5,    8},
    { 32,  0,  5,   10},  { 32,  0,  5,   11},
    {  0,  0,  6,   14},  {  0,  0,  6,   17},
    {  0,  0,  6,   20},  {  0,  0,  6,   23},
    {  0,  0,  6,   26},  {  0,  0,  6,   29},
    {  0,  0,  6,   32},  {  0, 16,  6,65539},
    {  0, 15,  6,32771},  {  0, 14,  6,16387},
    {  0, 13,  6, 8195},  {  0, 12,  6, 4099},
    {  0, 11,  6, 2051},  {  0, 10,  6, 1027},
};   /* ML_defaultDTable */


static void ZSTD_buildSeqTable_rle(ZSTD_seqSymbol* dt, U32 baseValue, U32 nbAddBits)
{
    void* ptr = dt;
    ZSTD_seqSymbol_header* const DTableH = (ZSTD_seqSymbol_header*)ptr;
    ZSTD_seqSymbol* const cell = dt + 1;

    DTableH->tableLog = 0;
    DTableH->fastMode = 0;

    cell->nbBits = 0;
    cell->nextState = 0;
    assert(nbAddBits < 255);
    cell->nbAdditionalBits = (BYTE)nbAddBits;
    cell->baseValue = baseValue;
}


/* ZSTD_buildFSETable() :
 * generate FSE decoding table for one symbol (ll, ml or off)
 * cannot fail if input is valid =>
 * all inputs are presumed validated at this stage */
void
ZSTD_buildFSETable(ZSTD_seqSymbol* dt,
            const short* normalizedCounter, unsigned maxSymbolValue,
            const U32* baseValue, const U32* nbAdditionalBits,
            unsigned tableLog)
{
    ZSTD_seqSymbol* const tableDecode = dt+1;
    U16 symbolNext[MaxSeq+1];

    U32 const maxSV1 = maxSymbolValue + 1;
    U32 const tableSize = 1 << tableLog;
    U32 highThreshold = tableSize-1;

    /* Sanity Checks */
    assert(maxSymbolValue <= MaxSeq);
    assert(tableLog <= MaxFSELog);

    /* Init, lay down lowprob symbols */
    {   ZSTD_seqSymbol_header DTableH;
        DTableH.tableLog = tableLog;
        DTableH.fastMode = 1;
        {   S16 const largeLimit= (S16)(1 << (tableLog-1));
            U32 s;
            for (s=0; s<maxSV1; s++) {
                if (normalizedCounter[s]==-1) {
                    tableDecode[highThreshold--].baseValue = s;
                    symbolNext[s] = 1;
                } else {
                    if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
                    assert(normalizedCounter[s]>=0);
                    symbolNext[s] = (U16)normalizedCounter[s];
        }   }   }
        memcpy(dt, &DTableH, sizeof(DTableH));
    }

    /* Spread symbols */
    {   U32 const tableMask = tableSize-1;
        U32 const step = FSE_TABLESTEP(tableSize);
        U32 s, position = 0;
        for (s=0; s<maxSV1; s++) {
            int i;
            for (i=0; i<normalizedCounter[s]; i++) {
                tableDecode[position].baseValue = s;
                position = (position + step) & tableMask;
                while (position > highThreshold) position = (position + step) & tableMask;   /* lowprob area */
        }   }
        assert(position == 0); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
    }

    /* Build Decoding table */
    {   U32 u;
        for (u=0; u<tableSize; u++) {
            U32 const symbol = tableDecode[u].baseValue;
            U32 const nextState = symbolNext[symbol]++;
            tableDecode[u].nbBits = (BYTE) (tableLog - BIT_highbit32(nextState) );
            tableDecode[u].nextState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
            assert(nbAdditionalBits[symbol] < 255);
            tableDecode[u].nbAdditionalBits = (BYTE)nbAdditionalBits[symbol];
            tableDecode[u].baseValue = baseValue[symbol];
    }   }
}


/*! ZSTD_buildSeqTable() :
 * @return : nb bytes read from src,
 *           or an error code if it fails */
static size_t ZSTD_buildSeqTable(ZSTD_seqSymbol* DTableSpace, const ZSTD_seqSymbol** DTablePtr,
                                 symbolEncodingType_e type, unsigned max, U32 maxLog,
                                 const void* src, size_t srcSize,
                                 const U32* baseValue, const U32* nbAdditionalBits,
                                 const ZSTD_seqSymbol* defaultTable, U32 flagRepeatTable,
                                 int ddictIsCold, int nbSeq)
{
    switch(type)
    {
    case set_rle :
        RETURN_ERROR_IF(!srcSize, srcSize_wrong, "");
        RETURN_ERROR_IF((*(const BYTE*)src) > max, corruption_detected, "");
        {   U32 const symbol = *(const BYTE*)src;
            U32 const baseline = baseValue[symbol];
            U32 const nbBits = nbAdditionalBits[symbol];
            ZSTD_buildSeqTable_rle(DTableSpace, baseline, nbBits);
        }
        *DTablePtr = DTableSpace;
        return 1;
    case set_basic :
        *DTablePtr = defaultTable;
        return 0;
    case set_repeat:
        RETURN_ERROR_IF(!flagRepeatTable, corruption_detected, "");
        /* prefetch FSE table if used */
        if (ddictIsCold && (nbSeq > 24 /* heuristic */)) {
            const void* const pStart = *DTablePtr;
            size_t const pSize = sizeof(ZSTD_seqSymbol) * (SEQSYMBOL_TABLE_SIZE(maxLog));
            PREFETCH_AREA(pStart, pSize);
        }
        return 0;
    case set_compressed :
        {   unsigned tableLog;
            S16 norm[MaxSeq+1];
            size_t const headerSize = FSE_readNCount(norm, &max, &tableLog, src, srcSize);
            RETURN_ERROR_IF(FSE_isError(headerSize), corruption_detected, "");
            RETURN_ERROR_IF(tableLog > maxLog, corruption_detected, "");
            ZSTD_buildFSETable(DTableSpace, norm, max, baseValue, nbAdditionalBits, tableLog);
            *DTablePtr = DTableSpace;
            return headerSize;
        }
    default :
        assert(0);
        RETURN_ERROR(GENERIC, "impossible");
    }
}

size_t ZSTD_decodeSeqHeaders(ZSTD_DCtx* dctx, int* nbSeqPtr,
                             const void* src, size_t srcSize)
{
    const BYTE* const istart = (const BYTE* const)src;
    const BYTE* const iend = istart + srcSize;
    const BYTE* ip = istart;
    int nbSeq;
    DEBUGLOG(5, "ZSTD_decodeSeqHeaders");

    /* check */
    RETURN_ERROR_IF(srcSize < MIN_SEQUENCES_SIZE, srcSize_wrong, "");

    /* SeqHead */
    nbSeq = *ip++;
    if (!nbSeq) {
        *nbSeqPtr=0;
        RETURN_ERROR_IF(srcSize != 1, srcSize_wrong, "");
        return 1;
    }
    if (nbSeq > 0x7F) {
        if (nbSeq == 0xFF) {
            RETURN_ERROR_IF(ip+2 > iend, srcSize_wrong, "");
            nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
        } else {
            RETURN_ERROR_IF(ip >= iend, srcSize_wrong, "");
            nbSeq = ((nbSeq-0x80)<<8) + *ip++;
        }
    }
    *nbSeqPtr = nbSeq;

    /* FSE table descriptors */
    RETURN_ERROR_IF(ip+1 > iend, srcSize_wrong, ""); /* minimum possible size: 1 byte for symbol encoding types */
    {   symbolEncodingType_e const LLtype = (symbolEncodingType_e)(*ip >> 6);
        symbolEncodingType_e const OFtype = (symbolEncodingType_e)((*ip >> 4) & 3);
        symbolEncodingType_e const MLtype = (symbolEncodingType_e)((*ip >> 2) & 3);
        ip++;

        /* Build DTables */
        {   size_t const llhSize = ZSTD_buildSeqTable(dctx->entropy.LLTable, &dctx->LLTptr,
                                                      LLtype, MaxLL, LLFSELog,
                                                      ip, iend-ip,
                                                      LL_base, LL_bits,
                                                      LL_defaultDTable, dctx->fseEntropy,
                                                      dctx->ddictIsCold, nbSeq);
            RETURN_ERROR_IF(ZSTD_isError(llhSize), corruption_detected, "ZSTD_buildSeqTable failed");
            ip += llhSize;
        }

        {   size_t const ofhSize = ZSTD_buildSeqTable(dctx->entropy.OFTable, &dctx->OFTptr,
                                                      OFtype, MaxOff, OffFSELog,
                                                      ip, iend-ip,
                                                      OF_base, OF_bits,
                                                      OF_defaultDTable, dctx->fseEntropy,
                                                      dctx->ddictIsCold, nbSeq);
            RETURN_ERROR_IF(ZSTD_isError(ofhSize), corruption_detected, "ZSTD_buildSeqTable failed");
            ip += ofhSize;
        }

        {   size_t const mlhSize = ZSTD_buildSeqTable(dctx->entropy.MLTable, &dctx->MLTptr,
                                                      MLtype, MaxML, MLFSELog,
                                                      ip, iend-ip,
                                                      ML_base, ML_bits,
                                                      ML_defaultDTable, dctx->fseEntropy,
                                                      dctx->ddictIsCold, nbSeq);
            RETURN_ERROR_IF(ZSTD_isError(mlhSize), corruption_detected, "ZSTD_buildSeqTable failed");
            ip += mlhSize;
        }
    }

    return ip-istart;
}


typedef struct {
    size_t litLength;
    size_t matchLength;
    size_t offset;
    const BYTE* match;
} seq_t;

typedef struct {
    size_t state;
    const ZSTD_seqSymbol* table;
} ZSTD_fseState;

typedef struct {
    BIT_DStream_t DStream;
    ZSTD_fseState stateLL;
    ZSTD_fseState stateOffb;
    ZSTD_fseState stateML;
    size_t prevOffset[ZSTD_REP_NUM];
    const BYTE* prefixStart;
    const BYTE* dictEnd;
    size_t pos;
} seqState_t;

/*! ZSTD_overlapCopy8() :
 *  Copies 8 bytes from ip to op and updates op and ip where ip <= op.
 *  If the offset is < 8 then the offset is spread to at least 8 bytes.
 *
 *  Precondition: *ip <= *op
 *  Postcondition: *op - *op >= 8
 */
HINT_INLINE void ZSTD_overlapCopy8(BYTE** op, BYTE const** ip, size_t offset) {
    assert(*ip <= *op);
    if (offset < 8) {
        /* close range match, overlap */
        static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 };   /* added */
        static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 };   /* subtracted */
        int const sub2 = dec64table[offset];
        (*op)[0] = (*ip)[0];
        (*op)[1] = (*ip)[1];
        (*op)[2] = (*ip)[2];
        (*op)[3] = (*ip)[3];
        *ip += dec32table[offset];
        ZSTD_copy4(*op+4, *ip);
        *ip -= sub2;
    } else {
        ZSTD_copy8(*op, *ip);
    }
    *ip += 8;
    *op += 8;
    assert(*op - *ip >= 8);
}

/*! ZSTD_safecopy() :
 *  Specialized version of memcpy() that is allowed to READ up to WILDCOPY_OVERLENGTH past the input buffer
 *  and write up to 16 bytes past oend_w (op >= oend_w is allowed).
 *  This function is only called in the uncommon case where the sequence is near the end of the block. It
 *  should be fast for a single long sequence, but can be slow for several short sequences.
 *
 *  @param ovtype controls the overlap detection
 *         - ZSTD_no_overlap: The source and destination are guaranteed to be at least WILDCOPY_VECLEN bytes apart.
 *         - ZSTD_overlap_src_before_dst: The src and dst may overlap and may be any distance apart.
 *           The src buffer must be before the dst buffer.
 */
static void ZSTD_safecopy(BYTE* op, BYTE* const oend_w, BYTE const* ip, ptrdiff_t length, ZSTD_overlap_e ovtype) {
    ptrdiff_t const diff = op - ip;
    BYTE* const oend = op + length;

    assert((ovtype == ZSTD_no_overlap && (diff <= -8 || diff >= 8 || op >= oend_w)) ||
           (ovtype == ZSTD_overlap_src_before_dst && diff >= 0));

    if (length < 8) {
        /* Handle short lengths. */
        while (op < oend) *op++ = *ip++;
        return;
    }
    if (ovtype == ZSTD_overlap_src_before_dst) {
        /* Copy 8 bytes and ensure the offset >= 8 when there can be overlap. */
        assert(length >= 8);
        ZSTD_overlapCopy8(&op, &ip, diff);
        assert(op - ip >= 8);
        assert(op <= oend);
    }

    if (oend <= oend_w) {
        /* No risk of overwrite. */
        ZSTD_wildcopy(op, ip, length, ovtype);
        return;
    }
    if (op <= oend_w) {
        /* Wildcopy until we get close to the end. */
        assert(oend > oend_w);
        ZSTD_wildcopy(op, ip, oend_w - op, ovtype);
        ip += oend_w - op;
        op = oend_w;
    }
    /* Handle the leftovers. */
    while (op < oend) *op++ = *ip++;
}

/* ZSTD_execSequenceEnd():
 * This version handles cases that are near the end of the output buffer. It requires
 * more careful checks to make sure there is no overflow. By separating out these hard
 * and unlikely cases, we can speed up the common cases.
 *
 * NOTE: This function needs to be fast for a single long sequence, but doesn't need
 * to be optimized for many small sequences, since those fall into ZSTD_execSequence().
 */
FORCE_NOINLINE
size_t ZSTD_execSequenceEnd(BYTE* op,
                            BYTE* const oend, seq_t sequence,
                            const BYTE** litPtr, const BYTE* const litLimit,
                            const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
{
    BYTE* const oLitEnd = op + sequence.litLength;
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
    const BYTE* match = oLitEnd - sequence.offset;
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;

    /* bounds checks : careful of address space overflow in 32-bit mode */
    RETURN_ERROR_IF(sequenceLength > (size_t)(oend - op), dstSize_tooSmall, "last match must fit within dstBuffer");
    RETURN_ERROR_IF(sequence.litLength > (size_t)(litLimit - *litPtr), corruption_detected, "try to read beyond literal buffer");
    assert(op < op + sequenceLength);
    assert(oLitEnd < op + sequenceLength);

    /* copy literals */
    ZSTD_safecopy(op, oend_w, *litPtr, sequence.litLength, ZSTD_no_overlap);
    op = oLitEnd;
    *litPtr = iLitEnd;

    /* copy Match */
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
        /* offset beyond prefix */
        RETURN_ERROR_IF(sequence.offset > (size_t)(oLitEnd - virtualStart), corruption_detected, "");
        match = dictEnd - (prefixStart-match);
        if (match + sequence.matchLength <= dictEnd) {
            memmove(oLitEnd, match, sequence.matchLength);
            return sequenceLength;
        }
        /* span extDict & currentPrefixSegment */
        {   size_t const length1 = dictEnd - match;
            memmove(oLitEnd, match, length1);
            op = oLitEnd + length1;
            sequence.matchLength -= length1;
            match = prefixStart;
    }   }
    ZSTD_safecopy(op, oend_w, match, sequence.matchLength, ZSTD_overlap_src_before_dst);
    return sequenceLength;
}

HINT_INLINE
size_t ZSTD_execSequence(BYTE* op,
                         BYTE* const oend, seq_t sequence,
                         const BYTE** litPtr, const BYTE* const litLimit,
                         const BYTE* const prefixStart, const BYTE* const virtualStart, const BYTE* const dictEnd)
{
    BYTE* const oLitEnd = op + sequence.litLength;
    size_t const sequenceLength = sequence.litLength + sequence.matchLength;
    BYTE* const oMatchEnd = op + sequenceLength;   /* risk : address space overflow (32-bits) */
    BYTE* const oend_w = oend - WILDCOPY_OVERLENGTH;   /* risk : address space underflow on oend=NULL */
    const BYTE* const iLitEnd = *litPtr + sequence.litLength;
    const BYTE* match = oLitEnd - sequence.offset;

    assert(op != NULL /* Precondition */);
    assert(oend_w < oend /* No underflow */);
    /* Handle edge cases in a slow path:
     *   - Read beyond end of literals
     *   - Match end is within WILDCOPY_OVERLIMIT of oend
     *   - 32-bit mode and the match length overflows
     */
    if (UNLIKELY(
            iLitEnd > litLimit ||
            oMatchEnd > oend_w ||
            (MEM_32bits() && (size_t)(oend - op) < sequenceLength + WILDCOPY_OVERLENGTH)))
        return ZSTD_execSequenceEnd(op, oend, sequence, litPtr, litLimit, prefixStart, virtualStart, dictEnd);

    /* Assumptions (everything else goes into ZSTD_execSequenceEnd()) */
    assert(op <= oLitEnd /* No overflow */);
    assert(oLitEnd < oMatchEnd /* Non-zero match & no overflow */);
    assert(oMatchEnd <= oend /* No underflow */);
    assert(iLitEnd <= litLimit /* Literal length is in bounds */);
    assert(oLitEnd <= oend_w /* Can wildcopy literals */);
    assert(oMatchEnd <= oend_w /* Can wildcopy matches */);

    /* Copy Literals:
     * Split out litLength <= 16 since it is nearly always true. +1.6% on gcc-9.
     * We likely don't need the full 32-byte wildcopy.
     */
    assert(WILDCOPY_OVERLENGTH >= 16);
    ZSTD_copy16(op, (*litPtr));
    if (UNLIKELY(sequence.litLength > 16)) {
        ZSTD_wildcopy(op+16, (*litPtr)+16, sequence.litLength-16, ZSTD_no_overlap);
    }
    op = oLitEnd;
    *litPtr = iLitEnd;   /* update for next sequence */

    /* Copy Match */
    if (sequence.offset > (size_t)(oLitEnd - prefixStart)) {
        /* offset beyond prefix -> go into extDict */
        RETURN_ERROR_IF(UNLIKELY(sequence.offset > (size_t)(oLitEnd - virtualStart)), corruption_detected, "");
        match = dictEnd + (match - prefixStart);
        if (match + sequence.matchLength <= dictEnd) {
            memmove(oLitEnd, match, sequence.matchLength);
            return sequenceLength;
        }
        /* span extDict & currentPrefixSegment */
        {   size_t const length1 = dictEnd - match;
            memmove(oLitEnd, match, length1);
            op = oLitEnd + length1;
            sequence.matchLength -= length1;
            match = prefixStart;
    }   }
    /* Match within prefix of 1 or more bytes */
    assert(op <= oMatchEnd);
    assert(oMatchEnd <= oend_w);
    assert(match >= prefixStart);
    assert(sequence.matchLength >= 1);

    /* Nearly all offsets are >= WILDCOPY_VECLEN bytes, which means we can use wildcopy
     * without overlap checking.
     */
    if (LIKELY(sequence.offset >= WILDCOPY_VECLEN)) {
        /* We bet on a full wildcopy for matches, since we expect matches to be
         * longer than literals (in general). In silesia, ~10% of matches are longer
         * than 16 bytes.
         */
        ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength, ZSTD_no_overlap);
        return sequenceLength;
    }
    assert(sequence.offset < WILDCOPY_VECLEN);

    /* Copy 8 bytes and spread the offset to be >= 8. */
    ZSTD_overlapCopy8(&op, &match, sequence.offset);

    /* If the match length is > 8 bytes, then continue with the wildcopy. */
    if (sequence.matchLength > 8) {
        assert(op < oMatchEnd);
        ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8, ZSTD_overlap_src_before_dst);
    }
    return sequenceLength;
}

static void
ZSTD_initFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, const ZSTD_seqSymbol* dt)
{
    const void* ptr = dt;
    const ZSTD_seqSymbol_header* const DTableH = (const ZSTD_seqSymbol_header*)ptr;
    DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog);
    DEBUGLOG(6, "ZSTD_initFseState : val=%u using %u bits",
                (U32)DStatePtr->state, DTableH->tableLog);
    BIT_reloadDStream(bitD);
    DStatePtr->table = dt + 1;
}

FORCE_INLINE_TEMPLATE void
ZSTD_updateFseState(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD)
{
    ZSTD_seqSymbol const DInfo = DStatePtr->table[DStatePtr->state];
    U32 const nbBits = DInfo.nbBits;
    size_t const lowBits = BIT_readBits(bitD, nbBits);
    DStatePtr->state = DInfo.nextState + lowBits;
}

FORCE_INLINE_TEMPLATE void
ZSTD_updateFseStateWithDInfo(ZSTD_fseState* DStatePtr, BIT_DStream_t* bitD, ZSTD_seqSymbol const DInfo)
{
    U32 const nbBits = DInfo.nbBits;
    size_t const lowBits = BIT_readBits(bitD, nbBits);
    DStatePtr->state = DInfo.nextState + lowBits;
}

/* We need to add at most (ZSTD_WINDOWLOG_MAX_32 - 1) bits to read the maximum
 * offset bits. But we can only read at most (STREAM_ACCUMULATOR_MIN_32 - 1)
 * bits before reloading. This value is the maximum number of bytes we read
 * after reloading when we are decoding long offsets.
 */
#define LONG_OFFSETS_MAX_EXTRA_BITS_32                       \
    (ZSTD_WINDOWLOG_MAX_32 > STREAM_ACCUMULATOR_MIN_32       \
        ? ZSTD_WINDOWLOG_MAX_32 - STREAM_ACCUMULATOR_MIN_32  \
        : 0)

typedef enum { ZSTD_lo_isRegularOffset, ZSTD_lo_isLongOffset=1 } ZSTD_longOffset_e;
typedef enum { ZSTD_p_noPrefetch=0, ZSTD_p_prefetch=1 } ZSTD_prefetch_e;

FORCE_INLINE_TEMPLATE seq_t
ZSTD_decodeSequence(seqState_t* seqState, const ZSTD_longOffset_e longOffsets, const ZSTD_prefetch_e prefetch)
{
    seq_t seq;
    ZSTD_seqSymbol const llDInfo = seqState->stateLL.table[seqState->stateLL.state];
    ZSTD_seqSymbol const mlDInfo = seqState->stateML.table[seqState->stateML.state];
    ZSTD_seqSymbol const ofDInfo = seqState->stateOffb.table[seqState->stateOffb.state];
    U32 const llBase = llDInfo.baseValue;
    U32 const mlBase = mlDInfo.baseValue;
    U32 const ofBase = ofDInfo.baseValue;
    BYTE const llBits = llDInfo.nbAdditionalBits;
    BYTE const mlBits = mlDInfo.nbAdditionalBits;
    BYTE const ofBits = ofDInfo.nbAdditionalBits;
    BYTE const totalBits = llBits+mlBits+ofBits;

    /* sequence */
    {   size_t offset;
        if (ofBits > 1) {
            ZSTD_STATIC_ASSERT(ZSTD_lo_isLongOffset == 1);
            ZSTD_STATIC_ASSERT(LONG_OFFSETS_MAX_EXTRA_BITS_32 == 5);
            assert(ofBits <= MaxOff);
            if (MEM_32bits() && longOffsets && (ofBits >= STREAM_ACCUMULATOR_MIN_32)) {
                U32 const extraBits = ofBits - MIN(ofBits, 32 - seqState->DStream.bitsConsumed);
                offset = ofBase + (BIT_readBitsFast(&seqState->DStream, ofBits - extraBits) << extraBits);
                BIT_reloadDStream(&seqState->DStream);
                if (extraBits) offset += BIT_readBitsFast(&seqState->DStream, extraBits);
                assert(extraBits <= LONG_OFFSETS_MAX_EXTRA_BITS_32);   /* to avoid another reload */
            } else {
                offset = ofBase + BIT_readBitsFast(&seqState->DStream, ofBits/*>0*/);   /* <=  (ZSTD_WINDOWLOG_MAX-1) bits */
                if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);
            }
            seqState->prevOffset[2] = seqState->prevOffset[1];
            seqState->prevOffset[1] = seqState->prevOffset[0];
            seqState->prevOffset[0] = offset;
        } else {
            U32 const ll0 = (llBase == 0);
            if (LIKELY((ofBits == 0))) {
                if (LIKELY(!ll0))
                    offset = seqState->prevOffset[0];
                else {
                    offset = seqState->prevOffset[1];
                    seqState->prevOffset[1] = seqState->prevOffset[0];
                    seqState->prevOffset[0] = offset;
                }
            } else {
                offset = ofBase + ll0 + BIT_readBitsFast(&seqState->DStream, 1);
                {   size_t temp = (offset==3) ? seqState->prevOffset[0] - 1 : seqState->prevOffset[offset];
                    temp += !temp;   /* 0 is not valid; input is corrupted; force offset to 1 */
                    if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
                    seqState->prevOffset[1] = seqState->prevOffset[0];
                    seqState->prevOffset[0] = offset = temp;
        }   }   }
        seq.offset = offset;
    }

    seq.matchLength = mlBase;
    if (mlBits > 0)
        seq.matchLength += BIT_readBitsFast(&seqState->DStream, mlBits/*>0*/);

    if (MEM_32bits() && (mlBits+llBits >= STREAM_ACCUMULATOR_MIN_32-LONG_OFFSETS_MAX_EXTRA_BITS_32))
        BIT_reloadDStream(&seqState->DStream);
    if (MEM_64bits() && UNLIKELY(totalBits >= STREAM_ACCUMULATOR_MIN_64-(LLFSELog+MLFSELog+OffFSELog)))
        BIT_reloadDStream(&seqState->DStream);
    /* Ensure there are enough bits to read the rest of data in 64-bit mode. */
    ZSTD_STATIC_ASSERT(16+LLFSELog+MLFSELog+OffFSELog < STREAM_ACCUMULATOR_MIN_64);

    seq.litLength = llBase;
    if (llBits > 0)
        seq.litLength += BIT_readBitsFast(&seqState->DStream, llBits/*>0*/);

    if (MEM_32bits())
        BIT_reloadDStream(&seqState->DStream);

    DEBUGLOG(6, "seq: litL=%u, matchL=%u, offset=%u",
                (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);

    if (prefetch == ZSTD_p_prefetch) {
        size_t const pos = seqState->pos + seq.litLength;
        const BYTE* const matchBase = (seq.offset > pos) ? seqState->dictEnd : seqState->prefixStart;
        seq.match = matchBase + pos - seq.offset;  /* note : this operation can overflow when seq.offset is really too large, which can only happen when input is corrupted.
                                                    * No consequence though : no memory access will occur, offset is only used for prefetching */
        seqState->pos = pos + seq.matchLength;
    }

    /* ANS state update
     * gcc-9.0.0 does 2.5% worse with ZSTD_updateFseStateWithDInfo().
     * clang-9.2.0 does 7% worse with ZSTD_updateFseState().
     * Naturally it seems like ZSTD_updateFseStateWithDInfo() should be the
     * better option, so it is the default for other compilers. But, if you
     * measure that it is worse, please put up a pull request.
     */
    {
#if defined(__GNUC__) && !defined(__clang__)
        const int kUseUpdateFseState = 1;
#else
        const int kUseUpdateFseState = 0;
#endif
        if (kUseUpdateFseState) {
            ZSTD_updateFseState(&seqState->stateLL, &seqState->DStream);    /* <=  9 bits */
            ZSTD_updateFseState(&seqState->stateML, &seqState->DStream);    /* <=  9 bits */
            if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
            ZSTD_updateFseState(&seqState->stateOffb, &seqState->DStream);  /* <=  8 bits */
        } else {
            ZSTD_updateFseStateWithDInfo(&seqState->stateLL, &seqState->DStream, llDInfo);    /* <=  9 bits */
            ZSTD_updateFseStateWithDInfo(&seqState->stateML, &seqState->DStream, mlDInfo);    /* <=  9 bits */
            if (MEM_32bits()) BIT_reloadDStream(&seqState->DStream);    /* <= 18 bits */
            ZSTD_updateFseStateWithDInfo(&seqState->stateOffb, &seqState->DStream, ofDInfo);  /* <=  8 bits */
        }
    }

    return seq;
}

#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
MEM_STATIC int ZSTD_dictionaryIsActive(ZSTD_DCtx const* dctx, BYTE const* prefixStart, BYTE const* oLitEnd)
{
    size_t const windowSize = dctx->fParams.windowSize;
    /* No dictionary used. */
    if (dctx->dictContentEndForFuzzing == NULL) return 0;
    /* Dictionary is our prefix. */
    if (prefixStart == dctx->dictContentBeginForFuzzing) return 1;
    /* Dictionary is not our ext-dict. */
    if (dctx->dictEnd != dctx->dictContentEndForFuzzing) return 0;
    /* Dictionary is not within our window size. */
    if ((size_t)(oLitEnd - prefixStart) >= windowSize) return 0;
    /* Dictionary is active. */
    return 1;
}

MEM_STATIC void ZSTD_assertValidSequence(
        ZSTD_DCtx const* dctx,
        BYTE const* op, BYTE const* oend,
        seq_t const seq,
        BYTE const* prefixStart, BYTE const* virtualStart)
{
#if DEBUGLEVEL >= 1
    size_t const windowSize = dctx->fParams.windowSize;
    size_t const sequenceSize = seq.litLength + seq.matchLength;
    BYTE const* const oLitEnd = op + seq.litLength;
    DEBUGLOG(6, "Checking sequence: litL=%u matchL=%u offset=%u",
            (U32)seq.litLength, (U32)seq.matchLength, (U32)seq.offset);
    assert(op <= oend);
    assert((size_t)(oend - op) >= sequenceSize);
    assert(sequenceSize <= ZSTD_BLOCKSIZE_MAX);
    if (ZSTD_dictionaryIsActive(dctx, prefixStart, oLitEnd)) {
        size_t const dictSize = (size_t)((char const*)dctx->dictContentEndForFuzzing - (char const*)dctx->dictContentBeginForFuzzing);
        /* Offset must be within the dictionary. */
        assert(seq.offset <= (size_t)(oLitEnd - virtualStart));
        assert(seq.offset <= windowSize + dictSize);
    } else {
        /* Offset must be within our window. */
        assert(seq.offset <= windowSize);
    }
#else
    (void)dctx, (void)op, (void)oend, (void)seq, (void)prefixStart, (void)virtualStart;
#endif
}
#endif

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
FORCE_INLINE_TEMPLATE size_t
DONT_VECTORIZE
ZSTD_decompressSequences_body( ZSTD_DCtx* dctx,
                               void* dst, size_t maxDstSize,
                         const void* seqStart, size_t seqSize, int nbSeq,
                         const ZSTD_longOffset_e isLongOffset,
                         const int frame)
{
    const BYTE* ip = (const BYTE*)seqStart;
    const BYTE* const iend = ip + seqSize;
    BYTE* const ostart = (BYTE* const)dst;
    BYTE* const oend = ostart + maxDstSize;
    BYTE* op = ostart;
    const BYTE* litPtr = dctx->litPtr;
    const BYTE* const litEnd = litPtr + dctx->litSize;
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
    const BYTE* const vBase = (const BYTE*) (dctx->virtualStart);
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
    DEBUGLOG(5, "ZSTD_decompressSequences_body");
    (void)frame;

    /* Regen sequences */
    if (nbSeq) {
        seqState_t seqState;
        size_t error = 0;
        dctx->fseEntropy = 1;
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
        RETURN_ERROR_IF(
            ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
            corruption_detected, "");
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);
        assert(dst != NULL);

        ZSTD_STATIC_ASSERT(
                BIT_DStream_unfinished < BIT_DStream_completed &&
                BIT_DStream_endOfBuffer < BIT_DStream_completed &&
                BIT_DStream_completed < BIT_DStream_overflow);

#if defined(__GNUC__) && defined(__x86_64__)
        /* Align the decompression loop to 32 + 16 bytes.
         *
         * zstd compiled with gcc-9 on an Intel i9-9900k shows 10% decompression
         * speed swings based on the alignment of the decompression loop. This
         * performance swing is caused by parts of the decompression loop falling
         * out of the DSB. The entire decompression loop should fit in the DSB,
         * when it can't we get much worse performance. You can measure if you've
         * hit the good case or the bad case with this perf command for some
         * compressed file test.zst:
         *
         *   perf stat -e cycles -e instructions -e idq.all_dsb_cycles_any_uops \
         *             -e idq.all_mite_cycles_any_uops -- ./zstd -tq test.zst
         *
         * If you see most cycles served out of the MITE you've hit the bad case.
         * If you see most cycles served out of the DSB you've hit the good case.
         * If it is pretty even then you may be in an okay case.
         *
         * I've been able to reproduce this issue on the following CPUs:
         *   - Kabylake: Macbook Pro (15-inch, 2019) 2.4 GHz Intel Core i9
         *               Use Instruments->Counters to get DSB/MITE cycles.
         *               I never got performance swings, but I was able to
         *               go from the good case of mostly DSB to half of the
         *               cycles served from MITE.
         *   - Coffeelake: Intel i9-9900k
         *
         * I haven't been able to reproduce the instability or DSB misses on any
         * of the following CPUS:
         *   - Haswell
         *   - Broadwell: Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GH
         *   - Skylake
         *
         * If you are seeing performance stability this script can help test.
         * It tests on 4 commits in zstd where I saw performance change.
         *
         *   https://gist.github.com/terrelln/9889fc06a423fd5ca6e99351564473f4
         */
        __asm__(".p2align 5");
        __asm__("nop");
        __asm__(".p2align 4");
#endif
        for ( ; ; ) {
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_noPrefetch);
            size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, prefixStart, vBase, dictEnd);
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
            assert(!ZSTD_isError(oneSeqSize));
            if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequence, prefixStart, vBase);
#endif
            DEBUGLOG(6, "regenerated sequence size : %u", (U32)oneSeqSize);
            BIT_reloadDStream(&(seqState.DStream));
            /* gcc and clang both don't like early returns in this loop.
             * gcc doesn't like early breaks either.
             * Instead save an error and report it at the end.
             * When there is an error, don't increment op, so we don't
             * overwrite.
             */
            if (UNLIKELY(ZSTD_isError(oneSeqSize))) error = oneSeqSize;
            else op += oneSeqSize;
            if (UNLIKELY(!--nbSeq)) break;
        }

        /* check if reached exact end */
        DEBUGLOG(5, "ZSTD_decompressSequences_body: after decode loop, remaining nbSeq : %i", nbSeq);
        if (ZSTD_isError(error)) return error;
        RETURN_ERROR_IF(nbSeq, corruption_detected, "");
        RETURN_ERROR_IF(BIT_reloadDStream(&seqState.DStream) < BIT_DStream_completed, corruption_detected, "");
        /* save reps for next block */
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
    }

    /* last literal segment */
    {   size_t const lastLLSize = litEnd - litPtr;
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
        if (op != NULL) {
            memcpy(op, litPtr, lastLLSize);
            op += lastLLSize;
        }
    }

    return op-ostart;
}

static size_t
ZSTD_decompressSequences_default(ZSTD_DCtx* dctx,
                                 void* dst, size_t maxDstSize,
                           const void* seqStart, size_t seqSize, int nbSeq,
                           const ZSTD_longOffset_e isLongOffset,
                           const int frame)
{
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
FORCE_INLINE_TEMPLATE size_t
ZSTD_decompressSequencesLong_body(
                               ZSTD_DCtx* dctx,
                               void* dst, size_t maxDstSize,
                         const void* seqStart, size_t seqSize, int nbSeq,
                         const ZSTD_longOffset_e isLongOffset,
                         const int frame)
{
    const BYTE* ip = (const BYTE*)seqStart;
    const BYTE* const iend = ip + seqSize;
    BYTE* const ostart = (BYTE* const)dst;
    BYTE* const oend = ostart + maxDstSize;
    BYTE* op = ostart;
    const BYTE* litPtr = dctx->litPtr;
    const BYTE* const litEnd = litPtr + dctx->litSize;
    const BYTE* const prefixStart = (const BYTE*) (dctx->prefixStart);
    const BYTE* const dictStart = (const BYTE*) (dctx->virtualStart);
    const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
    (void)frame;

    /* Regen sequences */
    if (nbSeq) {
#define STORED_SEQS 4
#define STORED_SEQS_MASK (STORED_SEQS-1)
#define ADVANCED_SEQS 4
        seq_t sequences[STORED_SEQS];
        int const seqAdvance = MIN(nbSeq, ADVANCED_SEQS);
        seqState_t seqState;
        int seqNb;
        dctx->fseEntropy = 1;
        { int i; for (i=0; i<ZSTD_REP_NUM; i++) seqState.prevOffset[i] = dctx->entropy.rep[i]; }
        seqState.prefixStart = prefixStart;
        seqState.pos = (size_t)(op-prefixStart);
        seqState.dictEnd = dictEnd;
        assert(dst != NULL);
        assert(iend >= ip);
        RETURN_ERROR_IF(
            ERR_isError(BIT_initDStream(&seqState.DStream, ip, iend-ip)),
            corruption_detected, "");
        ZSTD_initFseState(&seqState.stateLL, &seqState.DStream, dctx->LLTptr);
        ZSTD_initFseState(&seqState.stateOffb, &seqState.DStream, dctx->OFTptr);
        ZSTD_initFseState(&seqState.stateML, &seqState.DStream, dctx->MLTptr);

        /* prepare in advance */
        for (seqNb=0; (BIT_reloadDStream(&seqState.DStream) <= BIT_DStream_completed) && (seqNb<seqAdvance); seqNb++) {
            sequences[seqNb] = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
            PREFETCH_L1(sequences[seqNb].match); PREFETCH_L1(sequences[seqNb].match + sequences[seqNb].matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
        }
        RETURN_ERROR_IF(seqNb<seqAdvance, corruption_detected, "");

        /* decode and decompress */
        for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && (seqNb<nbSeq) ; seqNb++) {
            seq_t const sequence = ZSTD_decodeSequence(&seqState, isLongOffset, ZSTD_p_prefetch);
            size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
            assert(!ZSTD_isError(oneSeqSize));
            if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[(seqNb-ADVANCED_SEQS) & STORED_SEQS_MASK], prefixStart, dictStart);
#endif
            if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
            PREFETCH_L1(sequence.match); PREFETCH_L1(sequence.match + sequence.matchLength - 1); /* note : it's safe to invoke PREFETCH() on any memory address, including invalid ones */
            sequences[seqNb & STORED_SEQS_MASK] = sequence;
            op += oneSeqSize;
        }
        RETURN_ERROR_IF(seqNb<nbSeq, corruption_detected, "");

        /* finish queue */
        seqNb -= seqAdvance;
        for ( ; seqNb<nbSeq ; seqNb++) {
            size_t const oneSeqSize = ZSTD_execSequence(op, oend, sequences[seqNb&STORED_SEQS_MASK], &litPtr, litEnd, prefixStart, dictStart, dictEnd);
#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && defined(FUZZING_ASSERT_VALID_SEQUENCE)
            assert(!ZSTD_isError(oneSeqSize));
            if (frame) ZSTD_assertValidSequence(dctx, op, oend, sequences[seqNb&STORED_SEQS_MASK], prefixStart, dictStart);
#endif
            if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
            op += oneSeqSize;
        }

        /* save reps for next block */
        { U32 i; for (i=0; i<ZSTD_REP_NUM; i++) dctx->entropy.rep[i] = (U32)(seqState.prevOffset[i]); }
    }

    /* last literal segment */
    {   size_t const lastLLSize = litEnd - litPtr;
        RETURN_ERROR_IF(lastLLSize > (size_t)(oend-op), dstSize_tooSmall, "");
        if (op != NULL) {
            memcpy(op, litPtr, lastLLSize);
            op += lastLLSize;
        }
    }

    return op-ostart;
}

static size_t
ZSTD_decompressSequencesLong_default(ZSTD_DCtx* dctx,
                                 void* dst, size_t maxDstSize,
                           const void* seqStart, size_t seqSize, int nbSeq,
                           const ZSTD_longOffset_e isLongOffset,
                           const int frame)
{
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */



#if DYNAMIC_BMI2

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
static TARGET_ATTRIBUTE("bmi2") size_t
DONT_VECTORIZE
ZSTD_decompressSequences_bmi2(ZSTD_DCtx* dctx,
                                 void* dst, size_t maxDstSize,
                           const void* seqStart, size_t seqSize, int nbSeq,
                           const ZSTD_longOffset_e isLongOffset,
                           const int frame)
{
    return ZSTD_decompressSequences_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
static TARGET_ATTRIBUTE("bmi2") size_t
ZSTD_decompressSequencesLong_bmi2(ZSTD_DCtx* dctx,
                                 void* dst, size_t maxDstSize,
                           const void* seqStart, size_t seqSize, int nbSeq,
                           const ZSTD_longOffset_e isLongOffset,
                           const int frame)
{
    return ZSTD_decompressSequencesLong_body(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */

#endif /* DYNAMIC_BMI2 */

typedef size_t (*ZSTD_decompressSequences_t)(
                            ZSTD_DCtx* dctx,
                            void* dst, size_t maxDstSize,
                            const void* seqStart, size_t seqSize, int nbSeq,
                            const ZSTD_longOffset_e isLongOffset,
                            const int frame);

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
static size_t
ZSTD_decompressSequences(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize,
                   const void* seqStart, size_t seqSize, int nbSeq,
                   const ZSTD_longOffset_e isLongOffset,
                   const int frame)
{
    DEBUGLOG(5, "ZSTD_decompressSequences");
#if DYNAMIC_BMI2
    if (dctx->bmi2) {
        return ZSTD_decompressSequences_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
    }
#endif
  return ZSTD_decompressSequences_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG */


#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
/* ZSTD_decompressSequencesLong() :
 * decompression function triggered when a minimum share of offsets is considered "long",
 * aka out of cache.
 * note : "long" definition seems overloaded here, sometimes meaning "wider than bitstream register", and sometimes meaning "farther than memory cache distance".
 * This function will try to mitigate main memory latency through the use of prefetching */
static size_t
ZSTD_decompressSequencesLong(ZSTD_DCtx* dctx,
                             void* dst, size_t maxDstSize,
                             const void* seqStart, size_t seqSize, int nbSeq,
                             const ZSTD_longOffset_e isLongOffset,
                             const int frame)
{
    DEBUGLOG(5, "ZSTD_decompressSequencesLong");
#if DYNAMIC_BMI2
    if (dctx->bmi2) {
        return ZSTD_decompressSequencesLong_bmi2(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
    }
#endif
  return ZSTD_decompressSequencesLong_default(dctx, dst, maxDstSize, seqStart, seqSize, nbSeq, isLongOffset, frame);
}
#endif /* ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT */



#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
/* ZSTD_getLongOffsetsShare() :
 * condition : offTable must be valid
 * @return : "share" of long offsets (arbitrarily defined as > (1<<23))
 *           compared to maximum possible of (1<<OffFSELog) */
static unsigned
ZSTD_getLongOffsetsShare(const ZSTD_seqSymbol* offTable)
{
    const void* ptr = offTable;
    U32 const tableLog = ((const ZSTD_seqSymbol_header*)ptr)[0].tableLog;
    const ZSTD_seqSymbol* table = offTable + 1;
    U32 const max = 1 << tableLog;
    U32 u, total = 0;
    DEBUGLOG(5, "ZSTD_getLongOffsetsShare: (tableLog=%u)", tableLog);

    assert(max <= (1 << OffFSELog));  /* max not too large */
    for (u=0; u<max; u++) {
        if (table[u].nbAdditionalBits > 22) total += 1;
    }

    assert(tableLog <= OffFSELog);
    total <<= (OffFSELog - tableLog);  /* scale to OffFSELog */

    return total;
}
#endif

size_t
ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
                              void* dst, size_t dstCapacity,
                        const void* src, size_t srcSize, const int frame)
{   /* blockType == blockCompressed */
    const BYTE* ip = (const BYTE*)src;
    /* isLongOffset must be true if there are long offsets.
     * Offsets are long if they are larger than 2^STREAM_ACCUMULATOR_MIN.
     * We don't expect that to be the case in 64-bit mode.
     * In block mode, window size is not known, so we have to be conservative.
     * (note: but it could be evaluated from current-lowLimit)
     */
    ZSTD_longOffset_e const isLongOffset = (ZSTD_longOffset_e)(MEM_32bits() && (!frame || (dctx->fParams.windowSize > (1ULL << STREAM_ACCUMULATOR_MIN))));
    DEBUGLOG(5, "ZSTD_decompressBlock_internal (size : %u)", (U32)srcSize);

    RETURN_ERROR_IF(srcSize >= ZSTD_BLOCKSIZE_MAX, srcSize_wrong, "");

    /* Decode literals section */
    {   size_t const litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
        DEBUGLOG(5, "ZSTD_decodeLiteralsBlock : %u", (U32)litCSize);
        if (ZSTD_isError(litCSize)) return litCSize;
        ip += litCSize;
        srcSize -= litCSize;
    }

    /* Build Decoding Tables */
    {
        /* These macros control at build-time which decompressor implementation
         * we use. If neither is defined, we do some inspection and dispatch at
         * runtime.
         */
#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
        int usePrefetchDecoder = dctx->ddictIsCold;
#endif
        int nbSeq;
        size_t const seqHSize = ZSTD_decodeSeqHeaders(dctx, &nbSeq, ip, srcSize);
        if (ZSTD_isError(seqHSize)) return seqHSize;
        ip += seqHSize;
        srcSize -= seqHSize;

        RETURN_ERROR_IF(dst == NULL && nbSeq > 0, dstSize_tooSmall, "NULL not handled");

#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
        if ( !usePrefetchDecoder
          && (!frame || (dctx->fParams.windowSize > (1<<24)))
          && (nbSeq>ADVANCED_SEQS) ) {  /* could probably use a larger nbSeq limit */
            U32 const shareLongOffsets = ZSTD_getLongOffsetsShare(dctx->OFTptr);
            U32 const minShare = MEM_64bits() ? 7 : 20; /* heuristic values, correspond to 2.73% and 7.81% */
            usePrefetchDecoder = (shareLongOffsets >= minShare);
        }
#endif

        dctx->ddictIsCold = 0;

#if !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT) && \
    !defined(ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG)
        if (usePrefetchDecoder)
#endif
#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT
            return ZSTD_decompressSequencesLong(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
#endif

#ifndef ZSTD_FORCE_DECOMPRESS_SEQUENCES_LONG
        /* else */
        return ZSTD_decompressSequences(dctx, dst, dstCapacity, ip, srcSize, nbSeq, isLongOffset, frame);
#endif
    }
}


void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
{
    if (dst != dctx->previousDstEnd) {   /* not contiguous */
        dctx->dictEnd = dctx->previousDstEnd;
        dctx->virtualStart = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->prefixStart));
        dctx->prefixStart = dst;
        dctx->previousDstEnd = dst;
    }
}


size_t ZSTD_decompressBlock(ZSTD_DCtx* dctx,
                            void* dst, size_t dstCapacity,
                      const void* src, size_t srcSize)
{
    size_t dSize;
    ZSTD_checkContinuity(dctx, dst);
    dSize = ZSTD_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize, /* frame */ 0);
    dctx->previousDstEnd = (char*)dst + dSize;
    return dSize;
}
/**** ended inlining decompress/zstd_decompress_block.c ****/
                                                                                                                                                 source/v64/manifest.json                                                                            0000644 0000000 0000000 00000000353 00000000000 012366  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
    "name": "v86",
    "short_name": "v86",
    "start_url": "./",
    "display": "standalone",
    "icons": [
        {
            "src": "192.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ]
}
                                                                                                                                                                                                                                                                                     source/v64/package-lock.json                                                                        0000644 0000000 0000000 00000035165 00000000000 013112  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
  "name": "v86",
  "version": "0.5",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "v86",
      "version": "0.5",
      "license": "BSD-2-Clause",
      "devDependencies": {
        "esbuild": "0.28.2",
        "typescript": "6.0.3"
      }
    },
    "node_modules/@esbuild/aix-ppc64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
      "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
      "cpu": [
        "ppc64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "aix"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/android-arm": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
      "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
      "cpu": [
        "arm"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "android"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/android-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
      "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "android"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/android-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
      "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "android"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/darwin-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
      "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/darwin-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
      "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/freebsd-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
      "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/freebsd-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
      "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-arm": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
      "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
      "cpu": [
        "arm"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
      "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-ia32": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
      "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
      "cpu": [
        "ia32"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-loong64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
      "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
      "cpu": [
        "loong64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-mips64el": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
      "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
      "cpu": [
        "mips64el"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-ppc64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
      "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
      "cpu": [
        "ppc64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-riscv64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
      "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
      "cpu": [
        "riscv64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-s390x": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
      "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
      "cpu": [
        "s390x"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/linux-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
      "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/netbsd-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
      "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/netbsd-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
      "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/openbsd-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
      "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/openbsd-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
      "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/openharmony-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
      "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "openharmony"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/sunos-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
      "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "sunos"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/win32-arm64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
      "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
      "cpu": [
        "arm64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/win32-ia32": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
      "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
      "cpu": [
        "ia32"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/@esbuild/win32-x64": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
      "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
      "cpu": [
        "x64"
      ],
      "dev": true,
      "license": "MIT",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/esbuild": {
      "version": "0.28.2",
      "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
      "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
      "dev": true,
      "hasInstallScript": true,
      "license": "MIT",
      "bin": {
        "esbuild": "bin/esbuild"
      },
      "engines": {
        "node": ">=18"
      },
      "optionalDependencies": {
        "@esbuild/aix-ppc64": "0.28.2",
        "@esbuild/android-arm": "0.28.2",
        "@esbuild/android-arm64": "0.28.2",
        "@esbuild/android-x64": "0.28.2",
        "@esbuild/darwin-arm64": "0.28.2",
        "@esbuild/darwin-x64": "0.28.2",
        "@esbuild/freebsd-arm64": "0.28.2",
        "@esbuild/freebsd-x64": "0.28.2",
        "@esbuild/linux-arm": "0.28.2",
        "@esbuild/linux-arm64": "0.28.2",
        "@esbuild/linux-ia32": "0.28.2",
        "@esbuild/linux-loong64": "0.28.2",
        "@esbuild/linux-mips64el": "0.28.2",
        "@esbuild/linux-ppc64": "0.28.2",
        "@esbuild/linux-riscv64": "0.28.2",
        "@esbuild/linux-s390x": "0.28.2",
        "@esbuild/linux-x64": "0.28.2",
        "@esbuild/netbsd-arm64": "0.28.2",
        "@esbuild/netbsd-x64": "0.28.2",
        "@esbuild/openbsd-arm64": "0.28.2",
        "@esbuild/openbsd-x64": "0.28.2",
        "@esbuild/openharmony-arm64": "0.28.2",
        "@esbuild/sunos-x64": "0.28.2",
        "@esbuild/win32-arm64": "0.28.2",
        "@esbuild/win32-ia32": "0.28.2",
        "@esbuild/win32-x64": "0.28.2"
      }
    },
    "node_modules/typescript": {
      "version": "6.0.3",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
      "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
      "dev": true,
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc",
        "tsserver": "bin/tsserver"
      },
      "engines": {
        "node": ">=14.17"
      }
    }
  }
}
                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/package.json                                                                             0000644 0000000 0000000 00000001215 00000000000 012151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
  "name": "v86",
  "version": "0.5",
  "license": "BSD-2-Clause",
  "description": "x86 PC emulator and x86-to-wasm JIT, running in the browser",
  "homepage": "https://v64-2ys.pages.dev/",
  "files": [
    "Readme.md",
    "LICENSE",
    "v86.d.ts",
    "build/libv86*.js",
    "build/cpu-worker.js",
    "build/vcpu-worker.js",
    "build/libv86*.js.map",
    "build/*.mjs",
    "build/glbridge/",
    "build/v86*.wasm",
    "build/v86-*.js"
  ],
  "main": "build/libv86.mjs",
  "types": "v86.d.ts",
  "repository": "github:speedyHKjournalist/v64",
  "type": "module",
  "devDependencies": {
    "esbuild": "0.28.2",
    "typescript": "6.0.3"
  }
}
                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/acpi.js                                                                              0000644 0000000 0000000 00000071500 00000000000 011730  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // ACPI fixed hardware: the PIIX4 power management function (PCI 00:07.0) of
// the i440FX machine, or the power management of the ICH9 LPC (Q35).
//
// PIIX4: the PM I/O block (PM1 event and control registers, PM timer) is
// decoded at the base the firmware writes to PMBA (PCI config 0x40) once
// PMREGMISC (0x80) enables it; with v86's own ACPI tables SeaBIOS uses 0x600.
// The GPE0 block is fixed at 0xAFE0 (as in QEMU), SMI_CMD is 0xB2 with
// ACPI_ENABLE = 0xF1 and ACPI_DISABLE = 0xF0.
// ICH9: the LPC function (src/q35.js) decodes the 128-byte block at PMBASE
// (LPC config 0x40) once ACPI_EN (config 0x44 bit 7) is set and tells this
// device (set_pm_decode). GPE0 is part of the block (+0x20, 16 bytes), SMI_EN
// is at +0x30, SMI_CMD values are QEMU's 0x02/0x03. The SCI is IRQ 9 on both
// (src/platform.js describes the layouts).
//
// Register semantics: ACPI 6.6, section 4.8 (fixed hardware registers)
// https://uefi.org/specs/ACPI/6.6/04_ACPI_Hardware_Specification.html

import { LOG_ACPI } from "../src/const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";
import { ICH9_PM_TCO, ICH9_TCO_LENGTH, SMI_TCO, TCO } from "./ich9_tco.js";
import {
    ACPI_SCI_IRQ, ACPI_SMI_CMD_PORT, QEMU_PCI_SUBSYSTEM, pci_functions,
} from "./platform.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";
import { Platform } from "./platform.js";

/** Source id of the SCI on its (possibly shared) IRQ line; PCI functions use their pci_id */
export const ACPI_SCI_SOURCE = 0x100;

// PIIX4 PM function configuration registers
const PCI_PMBA = 0x40; // PM base address, bits 15:6; bit 0 reads as 1 (I/O space)
const PCI_PMREGMISC = 0x80; // bit 0: PM I/O space enable

export const PM_TIMER_TICKS_PER_MS = 3579545 / 1000;
// TMR_STS is set whenever bit 23 of the 24-bit timer changes
const PM_TIMER_STATUS_PERIOD = 1 << 23;

// PM1_STS and PM1_EN bits
const TMR = 1 << 0;
const BM = 1 << 4;
const GBL = 1 << 5;
const PWRBTN = 1 << 8;
const SLPBTN = 1 << 9;
const RTC = 1 << 10;
const WAK = 1 << 15;

const PM1_STS_MASK = TMR | BM | GBL | PWRBTN | SLPBTN | RTC | WAK;
const PM1_EN_MASK = TMR | GBL | PWRBTN | SLPBTN | RTC;

// PM1_CNT bits
const SCI_EN = 1 << 0;
const BM_RLS = 1 << 1;
const SLP_TYP_SHIFT = 10;
const SLP_TYP = 7 << SLP_TYP_SHIFT;
const SLP_EN = 1 << 13;

// SCI_EN belongs to the hardware (changed through SMI_CMD, preserved by
// OSPM); GBL_RLS and SLP_EN are write-only and read as zero
const PM1_CNT_WRITABLE = BM_RLS | SLP_TYP;

// PIIX4 GLBCTL: SeaBIOS sets SMI_EN in it. Without SMM it is plain storage.
const PM_GLBCTL = 0x28;
// ICH9 SMI_EN and SMI_STS: SeaBIOS reads SMI_EN to decide whether to set up
// SMM and then sets APMC_EN/GLB_SMI_EN. Without SMM they are plain storage.
const ICH9_PM_SMI_EN = 0x30;
const ICH9_PM_SMI_STS = 0x34;
/** SMI_EN.APMC_EN and SMI_STS.APM_STS: SMIs from writes to the APM control port */
const ICH9_SMI_APM = 1 << 5;
const APM_STS_PORT = 0xB3;

const STATE_FORMAT = 3;

// CMOS shutdown status byte: 0xFE tells SeaBIOS to resume from S3
const CMOS_SHUTDOWN_STATUS = 0x0F;
const CMOS_SHUTDOWN_S3_RESUME = 0xFE;

/**
 * Contents of the fw_cfg file etc/system-states, read by SeaBIOS's ACPI
 * builder: indexed by sleep state, bit 7 = advertised, bits 0-6 = SLP_TYP.
 * @param {Platform} platform
 * @return {!Uint8Array}
 */
export function acpi_system_states_file(platform)
{
    const states = new Uint8Array(6);
    states[0] = 0x80;
    for(const { state, slp_typ, supported } of platform.sleep_states)
    {
        states[state] = (supported ? 0x80 : 0) | slp_typ;
    }
    return states;
}

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 */
export function ACPI(cpu, bus)
{
    /** @type {CPU} */
    this.cpu = cpu;

    /** @const */
    this.bus = bus;

    /**
     * Time in milliseconds for port reads and snapshots. timer() gets the
     * same time from the main loop. Tests may replace it.
     * @type {function():number}
     */
    this.clock = () => this.cpu.clock.now();

    /** @const @type {Platform} */
    this.platform = /** @type {Platform} */ (cpu.platform);

    /** PIIX4 (with its own PCI function) or ICH9 (decoded by the LPC) */
    this.ich9 = this.platform.machine === "q35";

    /** @const */
    this.pm_length = this.platform.pm.length;

    /** @type {Int32Array} PIIX4: the PM function's configuration space */
    this.pci_config = null;

    if(!this.ich9)
    {
        // (QEMU's: revision 3 and its subsystem)
        const qemu = cpu.platform.qemu_compatible;
        const acpi = {
            pci_id: pci_functions(cpu.platform).acpi_pm,
            pci_space: [
                0x86, 0x80, 0x13, 0x71, 0x07, 0x00, 0x80, 0x02, qemu ? 0x03 : 0x08, 0x00, 0x80, 0x06, 0x00, 0x00, 0x80, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ...qemu ? QEMU_PCI_SUBSYSTEM : [0x00, 0x00, 0x00, 0x00],
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x00, 0x00,
            ],
            pci_bars: [],
            name: "acpi",
            on_config_write: offset => {
                if(offset >> 2 === PCI_PMBA >> 2 || offset >> 2 === PCI_PMREGMISC >> 2)
                {
                    this.update_pm_decode();
                }
            },
            on_config_restore: () => this.update_pm_decode(),
        };

        // 00:07.0 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 08)
        this.pci_config = cpu.devices.pci.register_device(acpi);
    }

    /** Base of the decoded PM I/O block, -1 while not decoded */
    this.pm_base = -1;

    this.pm1_sts = 0;
    this.pm1_en = 0;
    this.pm1_cnt = 0;
    this.gpe_sts = 0;
    this.gpe_en = 0;
    this.smi_cmd = 0;
    this.glbctl = 0;
    /** ICH9 SMI_EN and SMI_STS */
    this.smi_en = 0;
    this.smi_sts = 0;
    /** ICH9: the TCO watchdog, at PMBASE + 0x60, with SMIs if SMI_EN.TCO_EN */
    // (as in QEMU, TCO SMIs go to the bootstrap processor)
    this.tco = this.ich9 ? new TCO(cpu, () => this.raise_smi(SMI_TCO, 0)) : null;
    /** ICH9: APM status port (0xB3), a scratch register (SeaBIOS's SMM handshake) */
    this.apm_sts = 0;

    /**
     * 0 while the machine is on, otherwise the sleeping state (4 or 5) the
     * guest used to turn it off
     */
    this.soft_off = 0;

    /** 3 while the machine is suspended to RAM (S3), otherwise 0 */
    this.sleeping = 0;

    /** Level this device currently drives on the SCI line */
    this.sci_level = false;

    // The PM timer counts from 0 at power-on. timer_last keeps it monotonic,
    // timer_offset keeps it continuous across snapshots (like the TSC).
    this.timer_last = 0;
    this.timer_offset = -Math.floor(this.clock() * PM_TIMER_TICKS_PER_MS);
    this.timer_period = 0;

    /**
     * Where vCPU workers read the PM timer themselves (src/parallel):
     * the PM base, the timer offset and the timer's maximum so far, shared
     * by every thread (share_timer)
     * @type {Int32Array}
     */
    this.shared_base = null;
    /** @type {Float64Array} */
    this.shared_offset = null;
    /** @type {BigInt64Array} */
    this.shared_last = null;

    const io = cpu.io;
    this.reset_pm_config();
    if(!this.ich9)
    {
        // (ICH9's GPE0 block is part of the PM block)
        this.register_block(io, this.platform.pm.gpe0_base, this.platform.pm.gpe0_length, this.gpe_read, this.gpe_write);
    }

    io.register_read(ACPI_SMI_CMD_PORT, this,
        () => this.smi_cmd,
        () => this.smi_cmd,
        () => this.smi_cmd);
    io.register_write(ACPI_SMI_CMD_PORT, this,
        value => this.smi_cmd_write(value & 0xFF),
        value => this.smi_cmd_write(value & 0xFF),
        value => this.smi_cmd_write(value & 0xFF));
    if(this.ich9)
    {
        io.register_read(APM_STS_PORT, this, () => this.apm_sts);
        io.register_write(APM_STS_PORT, this, value => { this.apm_sts = value & 0xFF; });
    }
}

/**
 * Registers every access width on every port of a register block. Accesses
 * wider than a byte are handled as one access, so a register read cannot tear.
 * @param {Object} io
 * @param {number} base
 * @param {number} length
 * @param {function(this:ACPI, number, number):number} read
 * @param {function(this:ACPI, number, number, number)} write
 */
ACPI.prototype.register_block = function(io, base, length, read, write)
{
    for(let offset = 0; offset < length; offset++)
    {
        io.register_read(base + offset, this,
            () => read.call(this, offset, 1),
            () => read.call(this, offset, 2),
            () => read.call(this, offset, 4));
        io.register_write(base + offset, this,
            value => write.call(this, offset, 1, value),
            value => write.call(this, offset, 2, value),
            value => write.call(this, offset, 4, value));
    }
};

/**
 * PMBA and PMREGMISC after PCIRST#: PM I/O space disabled (PIIX4; the ICH9
 * LPC resets PMBASE and ACPI_CNTL itself)
 */
ACPI.prototype.reset_pm_config = function()
{
    if(this.ich9)
    {
        return;
    }
    this.pci_config[PCI_PMBA >> 2] = 1;
    this.pci_config[PCI_PMREGMISC >> 2] &= ~0xFF;
    this.update_pm_decode();
};

/** PIIX4: move the PM I/O block to the base in PMBA, or stop decoding it */
ACPI.prototype.update_pm_decode = function()
{
    // bits 31:16 and 5:1 are reserved (zero), bit 0 is hardwired to 1
    const pmba = this.pci_config[PCI_PMBA >> 2] & 0xFFC0;
    this.pci_config[PCI_PMBA >> 2] = pmba | 1;

    const enabled = (this.pci_config[PCI_PMREGMISC >> 2] & 1) !== 0;
    this.set_pm_decode(enabled && pmba !== 0 ? pmba : -1);
};

/**
 * Decode the PM I/O block at base, or nowhere (-1). PIIX4 derives the base
 * from its configuration; on Q35 the ICH9 LPC calls this.
 * @param {number} base
 */
ACPI.prototype.set_pm_decode = function(base)
{
    if(base === this.pm_base)
    {
        return;
    }

    const io = this.cpu.io;
    if(this.pm_base !== -1)
    {
        io.unregister_range(this.pm_base, this.pm_length, this);
    }

    dbg_log("ACPI PM block " + (base === -1 ? "disabled" : "at " + h(base, 4)), LOG_ACPI);
    this.pm_base = base;
    this.publish_timer();

    if(base !== -1)
    {
        for(let port = base; port < base + this.pm_length; port++)
        {
            if(io.ports[port].device)
            {
                dbg_log("Warning: ACPI PM block at " + h(base, 4) + " overlaps " + io.ports[port].device.name, LOG_ACPI);
                break;
            }
        }
        this.register_block(io, base, this.pm_length, this.pm_read, this.pm_write);
    }
};

ACPI.prototype.pm_read = function(offset, size)
{
    let timer = 0;
    if(offset === 8)
    {
        // (the step profile's PM timer reads, docs/jit-unification-plan.md P4.0)
        const note = this.cpu.wm?.exports["step_profile_note_event"];
        if(note) note(11, 0); // step_profile::event::PM_TIMER_READ
    }
    if(offset < 12 && offset + size > 8 || offset < 2)
    {
        const ticks = this.timer_ticks(this.clock());
        timer = ticks & 0xFFFFFF;
        this.update_timer_status(ticks);
    }

    let value = 0;
    for(let i = 0; i < size; i++)
    {
        value |= this.pm_read_byte(offset + i, timer) << (i << 3);
    }
    return value;
};

ACPI.prototype.pm_read_byte = function(offset, timer)
{
    if(this.ich9)
    {
        const gpe0 = this.platform.pm.gpe0_offset;
        if(offset >= gpe0 && offset < gpe0 + this.platform.pm.gpe0_length)
        {
            return this.gpe_read(offset - gpe0, 1);
        }
        if(offset >= ICH9_PM_SMI_EN && offset < ICH9_PM_SMI_EN + 4)
        {
            return this.smi_en >>> ((offset - ICH9_PM_SMI_EN) << 3) & 0xFF;
        }
        if(offset >= ICH9_PM_SMI_STS && offset < ICH9_PM_SMI_STS + 4)
        {
            return this.smi_sts >>> ((offset - ICH9_PM_SMI_STS) << 3) & 0xFF;
        }
        if(offset >= PM_GLBCTL && offset < PM_GLBCTL + 4)
        {
            // (ICH9 has no GLBCTL here)
            return 0;
        }
        if(offset >= ICH9_PM_TCO && offset < ICH9_PM_TCO + ICH9_TCO_LENGTH)
        {
            return this.tco.read_byte(offset - ICH9_PM_TCO);
        }
    }
    switch(offset)
    {
        case 0: return this.pm1_sts & 0xFF;
        case 1: return this.pm1_sts >> 8;
        case 2: return this.pm1_en & 0xFF;
        case 3: return this.pm1_en >> 8;
        case 4: return this.pm1_cnt & 0xFF;
        case 5: return this.pm1_cnt >> 8;
        case 8: return timer & 0xFF;
        case 9: return timer >> 8 & 0xFF;
        case 10: return timer >> 16 & 0xFF;
        case PM_GLBCTL: case PM_GLBCTL + 1: case PM_GLBCTL + 2: case PM_GLBCTL + 3:
            return this.glbctl >>> ((offset - PM_GLBCTL) << 3) & 0xFF;
        default:
            // reserved, and the upper byte of the 24-bit timer
            return 0;
    }
};

ACPI.prototype.pm_write = function(offset, size, value)
{
    dbg_log("ACPI PM write" + (size << 3) + " offset=" + h(offset, 2) + " value=" + h(value >>> 0), LOG_ACPI);

    let sleep = false;

    for(let i = 0; i < size; i++)
    {
        const o = offset + i;
        const shift = (o & 1) << 3;
        const byte = value >>> (i << 3) & 0xFF;
        const bits = byte << shift;
        const byte_mask = 0xFF << shift;

        switch(o)
        {
            case 0: case 1:
                // write one to clear
                this.pm1_sts &= ~(bits & PM1_STS_MASK);
                break;
            case 2: case 3:
                this.pm1_en = (this.pm1_en & ~byte_mask | bits) & PM1_EN_MASK;
                break;
            case 4: case 5:
                this.pm1_cnt = this.pm1_cnt & ~(byte_mask & PM1_CNT_WRITABLE) | bits & PM1_CNT_WRITABLE;
                sleep = sleep || (bits & SLP_EN) !== 0;
                break;
            case PM_GLBCTL: case PM_GLBCTL + 1: case PM_GLBCTL + 2: case PM_GLBCTL + 3:
            {
                if(this.ich9)
                {
                    // (ICH9: part of GPE0)
                    this.pm_write_ich9(o, byte);
                    break;
                }
                const glbctl_shift = (o - PM_GLBCTL) << 3;
                this.glbctl = this.glbctl & ~(0xFF << glbctl_shift) | byte << glbctl_shift;
                break;
            }
            default:
                // the timer is read-only; everything else is reserved
                if(this.ich9)
                {
                    this.pm_write_ich9(o, byte);
                }
                break;
        }
    }

    this.update_sci();

    if(sleep)
    {
        this.enter_sleep_state((this.pm1_cnt & SLP_TYP) >> SLP_TYP_SHIFT);
    }
};

/**
 * ICH9 PM registers that PIIX4 doesn't have (GPE0 inside the block, SMI_EN,
 * SMI_STS); one byte
 * @param {number} offset
 * @param {number} byte
 */
ACPI.prototype.pm_write_ich9 = function(offset, byte)
{
    const gpe0 = this.platform.pm.gpe0_offset;
    if(offset >= gpe0 && offset < gpe0 + this.platform.pm.gpe0_length)
    {
        this.gpe_write(offset - gpe0, 1, byte);
    }
    else if(offset >= ICH9_PM_SMI_EN && offset < ICH9_PM_SMI_EN + 4)
    {
        const shift = (offset - ICH9_PM_SMI_EN) << 3;
        // (GEN_PMCON_1.SMI_LOCK: GBL_SMI_EN, bit 0, keeps its value)
        const q35 = this.cpu.devices.q35;
        if(shift === 0 && q35 && q35.smi_lock) byte = byte & ~1 | this.smi_en & 1;
        this.smi_en = (this.smi_en & ~(0xFF << shift) | byte << shift) >>> 0;
    }
    else if(offset >= ICH9_PM_SMI_STS && offset < ICH9_PM_SMI_STS + 4)
    {
        // write one to clear
        this.smi_sts = (this.smi_sts & ~(byte << ((offset - ICH9_PM_SMI_STS) << 3))) >>> 0;
    }
    else if(offset >= ICH9_PM_TCO && offset < ICH9_PM_TCO + ICH9_TCO_LENGTH)
    {
        this.tco.write_byte(offset - ICH9_PM_TCO, byte);
    }
};

/**
 * GPE0: the status bytes (write one to clear), then as many enable bytes.
 * PIIX4 has 2 + 2 bytes, ICH9 8 + 8; gpe_sts and gpe_en hold the first 32
 * bits (no GPE source above them is implemented)
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
ACPI.prototype.gpe_read = function(offset, size)
{
    const half = this.platform.pm.gpe0_length >> 1;
    let value = 0;
    for(let i = 0; i < size; i++)
    {
        const o = offset + i;
        const register = o < half ? this.gpe_sts : this.gpe_en;
        const index = o < half ? o : o - half;
        const byte = index < 4 ? register >>> (index << 3) & 0xFF : 0;
        value |= byte << (i << 3);
    }
    return size === 4 ? value | 0 : value;
};

ACPI.prototype.gpe_write = function(offset, size, value)
{
    dbg_log("ACPI GPE write" + (size << 3) + " offset=" + offset + " value=" + h(value >>> 0), LOG_ACPI);

    const half = this.platform.pm.gpe0_length >> 1;
    const bits_mask = half >= 4 ? -1 : (1 << (half << 3)) - 1;

    for(let i = 0; i < size && offset + i < this.platform.pm.gpe0_length; i++)
    {
        const o = offset + i;
        const index = o < half ? o : o - half;
        if(index >= 4)
        {
            continue;
        }
        const shift = index << 3;
        const bits = (value >>> (i << 3) & 0xFF) << shift;

        if(o < half)
        {
            // GPE0_STS: write one to clear
            this.gpe_sts = (this.gpe_sts & ~bits) & bits_mask;
        }
        else
        {
            this.gpe_en = (this.gpe_en & ~(0xFF << shift) | bits) & bits_mask;
        }
    }

    this.update_sci();
};

/**
 * Port 0xB2 (APM control). The FADT names it SMI_CMD: OSPM writes
 * ACPI_ENABLE/ACPI_DISABLE to switch SCI_EN. On real hardware this goes
 * through an SMI handler; here the device switches it (as QEMU's does). On
 * ICH9 every other value raises an SMI if SMI_EN.APMC_EN is set (SeaBIOS's
 * SMM: the SMBASE relocation, call32_smm).
 */
ACPI.prototype.smi_cmd_write = function(value)
{
    this.smi_cmd = value;

    if(value === this.platform.pm.acpi_enable)
    {
        dbg_log("ACPI enable", LOG_ACPI);
        this.pm1_cnt |= SCI_EN;
        this.update_sci();
    }
    else if(value === this.platform.pm.acpi_disable)
    {
        dbg_log("ACPI disable", LOG_ACPI);
        this.pm1_cnt &= ~SCI_EN;
        this.update_sci();
    }
    else if(this.ich9)
    {
        this.raise_smi(ICH9_SMI_APM);
    }
};

/**
 * ICH9: an SMI source fired; with its enable bit in SMI_EN, its status bit
 * in SMI_STS is set and a core enters SMM: by default the one whose port
 * access raised it (the APM control port's). (Like QEMU, SMI_EN.GBL_SMI_EN is
 * not needed: SeaBIOS does not set it.)
 * @param {number} bit
 * @param {number=} core
 */
ACPI.prototype.raise_smi = function(bit, core)
{
    if(!(this.smi_en & bit))
    {
        return;
    }
    dbg_log("SMI (SMI_STS " + h(bit, 8) + ")", LOG_ACPI);
    this.smi_sts = (this.smi_sts | bit) >>> 0;
    this.cpu.smi(core);
};

/**
 * The SCI is a level-triggered interrupt: it stays asserted while an
 * enabled fixed event or GPE is pending and SCI_EN is set.
 */
ACPI.prototype.update_sci = function()
{
    const level = (this.pm1_cnt & SCI_EN) !== 0 &&
        ((this.pm1_sts & this.pm1_en & PM1_EN_MASK) !== 0 || (this.gpe_sts & this.gpe_en) !== 0);

    if(level !== this.sci_level)
    {
        dbg_log("ACPI SCI " + (level ? "raise" : "lower"), LOG_ACPI);
        this.sci_level = level;
        this.cpu.set_shared_irq_level(ACPI_SCI_IRQ, ACPI_SCI_SOURCE, level);
    }
};

/**
 * Re-derive the SCI after the interrupt controllers were restored from a
 * snapshot: sci_level must describe the restored line, not the pre-restore one.
 */
ACPI.prototype.sync_sci = function()
{
    this.sci_level = this.cpu.shared_irq_sources[ACPI_SCI_IRQ].has(ACPI_SCI_SOURCE);
    this.update_sci();
};

ACPI.prototype.enter_sleep_state = function(slp_typ)
{
    const sleep_state = this.platform.sleep_states.find(s => s.slp_typ === slp_typ);

    if(sleep_state && sleep_state.state >= 4 && sleep_state.supported)
    {
        // S4 and S5 turn the machine off; for S4 the guest resumes from disk
        // at the next power-on
        this.power_off(sleep_state.state);
    }
    else if(sleep_state && sleep_state.state === 3 && sleep_state.supported)
    {
        this.suspend();
    }
    else
    {
        // Sleeping states that are not implemented: behave as if a wake event
        // arrived immediately, so that the guest does not wait forever
        dbg_log("ACPI: sleep type " + slp_typ + " not supported, waking up", LOG_ACPI);
        this.pm1_sts |= WAK;
    }
};

ACPI.prototype.power_off = function(sleep_state)
{
    if(this.soft_off)
    {
        return;
    }

    dbg_log("ACPI: soft off (S" + sleep_state + ")", LOG_ACPI);
    this.soft_off = sleep_state;
    // The disks are complete when the host hears of it: writes still in flight
    // (only with an embedder's asynchronous disk buffer) land first
    const cpu = this.cpu, bus = this.bus, deadline = Date.now() + 30000;
    const announce = () => {
        if(cpu["snapshot_io_pending"] && Date.now() < deadline)
        {
            setTimeout(announce, 1);
            return;
        }
        bus.send("acpi-power-off", "S" + sleep_state);
    };
    announce();
};

/**
 * S3: every core stops at the end of its current instruction and RAM is
 * kept. The device timers keep running, so an RTC alarm can wake the
 * machine; so can the power button.
 */
ACPI.prototype.suspend = function()
{
    if(this.sleeping || this.soft_off)
    {
        return;
    }
    dbg_log("ACPI: suspend to RAM (S3)", LOG_ACPI);
    this.sleeping = 3;
    this.cpu.devices.rtc.cmos_write(CMOS_SHUTDOWN_STATUS, CMOS_SHUTDOWN_S3_RESUME);
    this.cpu.enter_sleep();
    this.bus.send("acpi-sleep", "S3");
};

/**
 * Leave S3 because of a wake event (fixed event status bits, e.g. PWRBTN or
 * RTC). The CPUs and devices are reset without reloading the BIOS, so
 * SeaBIOS sees that POST already ran and resumes through the FACS waking
 * vector. WAK_STS and the cause are set after the reset.
 * @param {number} status
 * @return {boolean}
 */
ACPI.prototype.wake = function(status)
{
    if(this.sleeping !== 3)
    {
        return false;
    }
    dbg_log("ACPI: wake from S3, status " + h(status), LOG_ACPI);
    this.sleeping = 0;
    this.cpu.resume_from_sleep();
    this.pm1_sts |= WAK | status;
    this.update_sci();
    this.bus.send("acpi-wake", status & PWRBTN ? "power-button" : status & RTC ? "rtc" : "other");
    return true;
};

/** The RTC alarm fired: RTC_STS, and a wake from S3 if RTC_EN is set */
ACPI.prototype.rtc_alarm = function()
{
    if(this.sleeping)
    {
        if(this.pm1_en & RTC)
        {
            this.wake(RTC);
        }
        return;
    }
    this.pm1_sts |= RTC;
    this.update_sci();
};

/**
 * Press the power button of a running machine. The guest sees a fixed
 * power button event; with SCI_EN clear (no ACPI OS) nothing happens.
 * A suspended (S3) machine wakes up.
 */
ACPI.prototype.press_power_button = function()
{
    if(this.sleeping)
    {
        this.wake(PWRBTN);
        return;
    }
    this.pm1_sts |= PWRBTN;
    this.update_sci();
};

/** Hardware reset: the registers return to their power-on values; the PM timer keeps running */
ACPI.prototype.reset = function()
{
    this.pm1_sts = 0;
    this.pm1_en = 0;
    this.pm1_cnt = 0;
    this.gpe_sts = 0;
    this.gpe_en = 0;
    this.smi_cmd = 0;
    this.glbctl = 0;
    this.smi_en = 0;
    this.smi_sts = 0;
    this.apm_sts = 0;
    this.tco && this.tco.reset();
    this.soft_off = 0;
    this.sleeping = 0;
    this.update_sci();
    this.reset_pm_config();
};

/**
 * PM timer ticks since power-on (not truncated to 24 bits). Monotonic; it
 * advances with time only, not with the number of reads.
 * @param {number} now
 * @return {number}
 */
ACPI.prototype.timer_ticks = function(now)
{
    const ticks = Math.floor(now * PM_TIMER_TICKS_PER_MS) + this.timer_offset;

    if(this.shared_last)
    {
        // vCPU workers read the timer too: one maximum for every thread
        this.timer_last = pm_timer_shared_max(this.shared_last, ticks);
    }
    else if(ticks > this.timer_last)
    {
        this.timer_last = ticks;
    }

    return this.timer_last;
};

/**
 * Let vCPU workers read the PM timer (port PM base + 8, 32 bits) without
 * asking this thread: where the block is, the timer offset and a maximum
 * all threads share (src/parallel/vcpu.js computes the same ticks from the
 * shared machine clock). Status bits and every other register stay here.
 * @param {!Int32Array} base one word: the PM base, or -1
 * @param {!Float64Array} offset one number: timer_offset
 * @param {!BigInt64Array} last one number: the largest value read
 */
ACPI.prototype.share_timer = function(base, offset, last)
{
    this.shared_base = base;
    this.shared_offset = offset;
    this.shared_last = last;
    Atomics.store(last, 0, /** @type {?} */ (BigInt(this.timer_last)));
    this.publish_timer();
};

ACPI.prototype.publish_timer = function()
{
    if(!this.shared_base) return;
    this.shared_offset[0] = this.timer_offset;
    Atomics.store(this.shared_base, 0, this.pm_base);
};

/**
 * Raise the shared maximum to `ticks` unless it is larger already
 * @param {!BigInt64Array} last
 * @param {number} ticks
 * @return {number} the maximum
 */
export function pm_timer_shared_max(last, ticks)
{
    const value = BigInt(ticks);
    let seen = Atomics.load(last, 0);
    while(value > seen)
    {
        const previous = Atomics.compareExchange(last, 0, seen, /** @type {?} */ (value));
        if(previous === seen) return ticks;
        seen = previous;
    }
    return Number(seen);
}

ACPI.prototype.update_timer_status = function(ticks)
{
    const period = Math.floor(ticks / PM_TIMER_STATUS_PERIOD);

    if(period !== this.timer_period)
    {
        this.timer_period = period;
        this.pm1_sts |= TMR;
        this.update_sci();
    }
};

/**
 * Called from the main loop
 * @param {number} now
 * @return {number} milliseconds until this device needs to be called again
 */
ACPI.prototype.timer = function(now)
{
    const ticks = this.timer_ticks(now);
    this.update_timer_status(ticks);
    const tco = this.tco ? this.tco.timer(now) : 100;

    if((this.pm1_en & TMR) && (this.pm1_cnt & SCI_EN))
    {
        const next = (this.timer_period + 1) * PM_TIMER_STATUS_PERIOD;
        return Math.min(100, tco, (next - ticks) / PM_TIMER_TICKS_PER_MS);
    }

    return tco;
};

ACPI.prototype.get_state = function()
{
    const state = [];
    state[0] = this.pm1_cnt;
    state[1] = this.pm1_sts;
    state[2] = this.pm1_en;
    // GPE0 status bytes, then enable bytes (PIIX4: 2 + 2, ICH9: 8 + 8)
    const half = this.platform.pm.gpe0_length >> 1;
    state[3] = new Uint8Array(half << 1);
    for(let i = 0; i < Math.min(half, 4); i++)
    {
        state[3][i] = this.gpe_sts >>> (i << 3) & 0xFF;
        state[3][half + i] = this.gpe_en >>> (i << 3) & 0xFF;
    }
    state[4] = STATE_FORMAT;
    state[5] = this.timer_ticks(this.clock());
    state[6] = this.timer_period;
    state[7] = this.smi_cmd;
    state[8] = this.glbctl;
    state[9] = this.soft_off;
    state[10] = this.sleeping;
    state[11] = this.smi_en;
    state[12] = this.smi_sts;
    state[13] = this.tco ? this.tco.get_state() : null;
    state[14] = this.apm_sts;
    return state;
};

ACPI.prototype.set_state = function(state)
{
    const gpe = state[3];
    const gpe_half = gpe.length >> 1;
    const gpe_bytes = (start) => {
        let value = 0;
        for(let i = 0; i < Math.min(gpe_half, 4); i++) value |= gpe[start + i] << (i << 3);
        return value >>> 0;
    };
    this.pm1_sts = state[1] & PM1_STS_MASK;
    this.pm1_en = state[2] & PM1_EN_MASK;
    this.gpe_en = gpe_bytes(gpe_half);
    this.smi_en = state[11] || 0;
    this.smi_sts = state[12] || 0;
    if(this.tco && state[13])
    {
        this.tco.set_state(state[13]);
    }
    this.apm_sts = state[14] || 0;

    let ticks = 0;

    if(state[4] === undefined)
    {
        // Before STATE_FORMAT 2, PM1_CNT was stored as last written (including
        // SLP_EN), the GPE bytes were raw storage (status bits the guest had
        // cleared read back as set) and the timer phase was not saved.
        this.pm1_cnt = state[0] & (SCI_EN | PM1_CNT_WRITABLE);
        this.gpe_sts = 0;
        this.smi_cmd = 0;
        this.glbctl = 0;
        this.soft_off = 0;
        this.sleeping = 0;
    }
    else
    {
        this.pm1_cnt = state[0] & (SCI_EN | PM1_CNT_WRITABLE);
        this.gpe_sts = gpe_bytes(0);
        ticks = state[5];
        this.timer_period = state[6];
        this.smi_cmd = state[7];
        this.glbctl = state[8];
        this.soft_off = state[9];
        // (format 3) suspended to RAM
        this.sleeping = state[4] >= 3 ? state[10] : 0;
    }

    this.timer_offset = ticks - Math.floor(this.clock() * PM_TIMER_TICKS_PER_MS);
    this.timer_last = ticks;
    if(this.shared_last) Atomics.store(this.shared_last, 0, /** @type {?} */ (BigInt(ticks)));
    this.publish_timer();
    if(state[4] === undefined)
    {
        this.timer_period = Math.floor(ticks / PM_TIMER_STATUS_PERIOD);
    }
    // PCI restores PMBA/PMREGMISC after this device, then on_config_restore
    // rebuilds the PM I/O mapping from the restored configuration.
    // sci_level is re-derived by sync_sci once the interrupt controllers are restored
};
                                                                                                                                                                                                source/v64/src/acpi_tables.js                                                                       0000644 0000000 0000000 00000115761 00000000000 013272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // ACPI tables of the v86 platform, installed by SeaBIOS through the fw_cfg
// files etc/table-loader, etc/acpi/tables and etc/acpi/rsdp (the QEMU
// "linker/loader" interface, SeaBIOS src/fw/romfile_loader.h).
//
// Everything here is derived from src/platform.js and describes hardware that
// v86 implements. AML encoding: ACPI 6.6, chapter 20
// https://uefi.org/specs/ACPI/6.6/20_AML_Specification.html
// Table layouts: ACPI 6.6, chapter 5; the FADT is revision 3 (ACPI 2.0) and
// the DSDT uses 32-bit integers (revision 1), which Windows 2000/XP accept.

import { dbg_assert } from "./log.js";
import {
    ACPI_SCI_IRQ, ACPI_SMI_CMD_PORT, FW_CFG_PORT, ICH9_RCBA_ADDRESS, ICH9_RCBA_SIZE,
    IOAPIC_ADDRESS, IOAPIC_ID, LAPIC_ADDRESS, PCI_LINK_IRQS, RESET_PORT, RESET_VALUE, TPM_CRB_BASE, TPM_CRB_SIZE,
    gpe0_block, pci_memory_windows,
} from "./platform.js";
import { CMOS_CENTURY } from "./rtc.js";
import { HPET_ADDRESS, HPET_BLOCK_ID, HPET_SIZE } from "./hpet.js";

// For Types Only
import { Platform } from "./platform.js";

const OEM_ID = "V86   ";
const CREATOR_ID = "V86 ";

export const ACPI_TABLES_FILE = "etc/acpi/tables";
export const ACPI_RSDP_FILE = "etc/acpi/rsdp";
export const ACPI_LOADER_FILE = "etc/table-loader";
/** The TPM's event log area (QEMU's name and size): the TPM2 table points to it */
export const TPM_LOG_FILE = "etc/tpm/log";
const TPM_LOG_SIZE = 0x10000;
/** The TPM2 table's log area address (LASA), which the table loader fills in */
const TPM2_LASA = 68;

// ---------------------------------------------------------------------------
// AML encoding. Every helper returns an array of bytes.

const ZERO_OP = 0x00;
const ONE_OP = 0x01;
const NAME_OP = 0x08;
const BYTE_PREFIX = 0x0A;
const WORD_PREFIX = 0x0B;
const DWORD_PREFIX = 0x0C;
const SCOPE_OP = 0x10;
const BUFFER_OP = 0x11;
const PACKAGE_OP = 0x12;
const METHOD_OP = 0x14;
const DUAL_NAME_PREFIX = 0x2E;
const MULTI_NAME_PREFIX = 0x2F;
const EXT_OP = 0x5B;
const OP_REGION_OP = 0x80;
const FIELD_OP = 0x81;
const DEVICE_OP = 0x82;
const PROCESSOR_OP = 0x83;
const LOCAL0_OP = 0x60;
const ARG0_OP = 0x68;
const STORE_OP = 0x70;
const AND_OP = 0x7B;
const OR_OP = 0x7D;
const CREATE_DWORD_FIELD_OP = 0x8A;
const LNOT_OP = 0x92;
const LEQUAL_OP = 0x93;
const LLESS_OP = 0x95;
const IF_OP = 0xA0;
const ELSE_OP = 0xA1;
const RETURN_OP = 0xA4;
const NOOP_OP = 0xA3;

const REGION_SYSTEM_IO = 0x01;
const REGION_PCI_CONFIG = 0x02;

/**
 * A length as encoded in PkgLength and in field lists (not including itself)
 * @param {number} value
 * @return {!Array<number>}
 */
function aml_length(value)
{
    if(value < 0x40)
    {
        return [value];
    }
    const follow = value < 1 << 12 ? 1 : value < 1 << 20 ? 2 : 3;
    dbg_assert(value < 1 << 28);
    const bytes = [follow << 6 | value & 0xF];
    for(let i = 0; i < follow; i++)
    {
        bytes.push(value >>> (4 + 8 * i) & 0xFF);
    }
    return bytes;
}

/**
 * PkgLength followed by the contents; PkgLength counts its own bytes
 * @param {!Array<number>} contents
 * @return {!Array<number>}
 */
function with_pkg_length(contents)
{
    for(let size = 1; size <= 4; size++)
    {
        const encoded = aml_length(contents.length + size);
        if(encoded.length === size)
        {
            return encoded.concat(contents);
        }
    }
    throw new Error("AML package too large");
}

/** @param {!Array<!Array<number>>} terms */
const flat = terms => [].concat(...terms);

/**
 * @param {string} seg
 * @return {!Array<number>}
 */
function name_seg(seg)
{
    dbg_assert(seg.length >= 1 && seg.length <= 4 && /^[A-Z_][A-Z0-9_]*$/.test(seg), "bad name segment " + seg);
    seg = seg.padEnd(4, "_");
    return Array.from(seg, c => c.charCodeAt(0));
}

/**
 * NameString: "\\_SB.PCI0", "^PRQ0", "_HID"
 * @param {string} path
 * @return {!Array<number>}
 */
function aml_name(path)
{
    const prefix = [];
    while(path[0] === "\\" || path[0] === "^")
    {
        prefix.push(path.charCodeAt(0));
        path = path.slice(1);
    }
    const segments = path === "" ? [] : path.split(".");
    let body;
    if(segments.length === 0)
    {
        body = [0x00];
    }
    else if(segments.length === 1)
    {
        body = name_seg(segments[0]);
    }
    else if(segments.length === 2)
    {
        body = [DUAL_NAME_PREFIX].concat(name_seg(segments[0]), name_seg(segments[1]));
    }
    else
    {
        body = [MULTI_NAME_PREFIX, segments.length].concat(flat(segments.map(name_seg)));
    }
    return prefix.concat(body);
}

/**
 * @param {number} value unsigned, at most 32 bits (DSDT revision 1)
 * @return {!Array<number>}
 */
function aml_int(value)
{
    dbg_assert(value >= 0 && value <= 0xFFFFFFFF && Number.isInteger(value));
    if(value === 0) return [ZERO_OP];
    if(value === 1) return [ONE_OP];
    if(value <= 0xFF) return [BYTE_PREFIX, value];
    if(value <= 0xFFFF) return [WORD_PREFIX, value & 0xFF, value >> 8];
    return [DWORD_PREFIX].concat(le(value, 4));
}

/**
 * Compressed EISA id, e.g. "PNP0A03"
 * @param {string} id
 * @return {!Array<number>}
 */
function aml_eisa_id(id)
{
    dbg_assert(/^[A-Z]{3}[0-9A-F]{4}$/.test(id));
    const c = i => id.charCodeAt(i) - 0x40;
    const product = parseInt(id.slice(3), 16);
    const bytes = [c(0) << 2 | c(1) >> 3, (c(1) & 7) << 5 | c(2), product >> 8, product & 0xFF];
    return aml_int((bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) >>> 0);
}

const aml_arg = n => [ARG0_OP + n];
const aml_local = n => [LOCAL0_OP + n];
const aml_name_decl = (path, value) => [NAME_OP].concat(aml_name(path), value);
const aml_scope = (path, ...terms) => [SCOPE_OP].concat(with_pkg_length(aml_name(path).concat(flat(terms))));
const aml_device = (path, ...terms) => [EXT_OP, DEVICE_OP].concat(with_pkg_length(aml_name(path).concat(flat(terms))));
const aml_package = (...elements) => [PACKAGE_OP].concat(with_pkg_length([elements.length].concat(flat(elements))));
const aml_buffer = bytes => [BUFFER_OP].concat(with_pkg_length(aml_int(bytes.length).concat(bytes)));
const aml_return = value => [RETURN_OP].concat(value);
const aml_store = (source, target) => [STORE_OP].concat(source, target);
const aml_and = (a, b, target = [0]) => [AND_OP].concat(a, b, target);
const aml_or = (a, b, target = [0]) => [OR_OP].concat(a, b, target);
const aml_lless = (a, b) => [LLESS_OP].concat(a, b);
const aml_lequal = (a, b) => [LEQUAL_OP].concat(a, b);
const aml_lnot = a => [LNOT_OP].concat(a);
const aml_if = (predicate, ...terms) => [IF_OP].concat(with_pkg_length(predicate.concat(flat(terms))));
/** (right after the aml_if it belongs to) */
const aml_else = (...terms) => [ELSE_OP].concat(with_pkg_length(flat(terms)));
const aml_create_dword_field = (buffer, index, name) => [CREATE_DWORD_FIELD_OP].concat(buffer, aml_int(index), aml_name(name));

/**
 * @param {string} path
 * @param {number} arg_count
 * @param {boolean} serialized
 * @param {...!Array<number>} terms
 */
function aml_method(path, arg_count, serialized, ...terms)
{
    return [METHOD_OP].concat(with_pkg_length(aml_name(path).concat([arg_count | (serialized ? 8 : 0)], flat(terms))));
}

/**
 * Processor object. Deprecated since ACPI 6.0 in favour of Device(ACPI0007),
 * which Windows 2000/XP don't understand; every OS in the target list
 * accepts Processor().
 * @param {string} path
 * @param {number} id
 * @param {...!Array<number>} terms
 */
function aml_processor(path, id, ...terms)
{
    // no P_BLK: C2/C3 are not supported
    return [EXT_OP, PROCESSOR_OP].concat(with_pkg_length(aml_name(path).concat([id], le(0, 4), [0], flat(terms))));
}

const aml_op_region = (path, space, offset, length) =>
    [EXT_OP, OP_REGION_OP].concat(aml_name(path), [space], aml_int(offset), aml_int(length));

/**
 * @param {string} region
 * @param {number} flags access type | lock rule | update rule
 * @param {!Array<{name: (string|undefined), bits: number}>} fields unnamed entries are reserved space
 */
function aml_field(region, flags, fields)
{
    const list = flat(fields.map(({ name, bits }) => (name ? name_seg(name) : [0x00]).concat(aml_length(bits))));
    return [EXT_OP, FIELD_OP].concat(with_pkg_length(aml_name(region).concat([flags], list)));
}

const FIELD_BYTE_ACC = 0x01;
const FIELD_PRESERVE = 0x00;

// Resource descriptors (ACPI 6.6, section 6.4)

/** Fixed 16-bit decoded I/O range */
const res_io = (base, length) => [0x47, 0x01, base & 0xFF, base >> 8, base & 0xFF, base >> 8, 0x01, length];
/** @param {!Array<number>} irqs */
const res_irq_noflags = irqs => { const mask = irqs.reduce((m, irq) => m | 1 << irq, 0); return [0x22, mask & 0xFF, mask >> 8]; };
/** 8-bit ISA compatibility DMA, not a bus master */
const res_dma = channels => [0x2A, channels.reduce((m, c) => m | 1 << c, 0), 0x00];
/**
 * Level-triggered, active-high, shared interrupt consumer; the first IRQ is at byte 5
 * @param {!Array<number>} irqs
 */
const res_interrupt_shared_level = irqs => [0x89].concat(le(2 + 4 * irqs.length, 2), [0x09, irqs.length], flat(irqs.map(irq => le(irq, 4))));

/** Word address space producer with fixed min/max; type 1 = I/O, 2 = bus numbers */
function res_word_space(type, type_flags, min, max)
{
    return [0x88, 13, 0, type, 0x0C, type_flags].concat(le(0, 2), le(min, 2), le(max, 2), le(0, 2), le(max - min + 1, 2));
}
const res_word_bus = (min, max) => res_word_space(2, 0, min, max);
const res_word_io = (min, max) => res_word_space(1, 0x03, min, max);
/** 32-bit fixed memory range, read/write (reserved by a motherboard device) */
const res_memory32_fixed = (base, length) => [0x86, 9, 0, 1].concat(le(base, 4), le(length, 4));
/** A string: StringPrefix, ASCII, NUL */
const aml_string = text => [0x0D, ...Array.from(text, c => c.charCodeAt(0)), 0];
/** Cacheable read/write memory window */
const res_dword_memory = (min, max) =>
    [0x87, 23, 0, 0, 0x0C, 0x03].concat(le(0, 4), le(min, 4), le(max, 4), le(0, 4), le(max - min + 1 >>> 0, 4));

/** @param {...!Array<number>} descriptors */
const aml_resources = (...descriptors) => aml_buffer(flat(descriptors).concat([0x79, 0x00]));

/**
 * @param {number} value
 * @param {number} size
 * @return {!Array<number>}
 */
function le(value, size)
{
    const bytes = [];
    for(let i = 0; i < size; i++)
    {
        // Numbers up to 2**53 (8-byte fields hold at most 32-bit values here)
        bytes.push(i < 4 ? value >>> (8 * i) & 0xFF : Math.floor(value / 2 ** (8 * i)) & 0xFF);
    }
    return bytes;
}

// ---------------------------------------------------------------------------
// DSDT

/**
 * @param {string} name
 * @param {string} hid
 * @param {!Array<number>} resources
 * @param {number=} uid
 * @return {!Array<number>}
 */
const isa_device = (name, hid, resources, uid) => aml_device(name,
    aml_name_decl("_HID", aml_eisa_id(hid)),
    uid === undefined ? [] : aml_name_decl("_UID", aml_int(uid)),
    aml_name_decl("_CRS", resources));

/**
 * The devices behind the ISA (PIIX3) or LPC (ICH9) bridge
 * @param {Platform} platform
 * @return {!Array<!Array<number>>}
 */
function isa_devices_of(platform)
{
    const isa_devices = [
        isa_device("RTC", "PNP0B00", aml_resources(res_io(0x70, 2), res_irq_noflags([8]))),
        // SeaBIOS looks for PNP0303 to enable its PS/2 support
        isa_device("KBD", "PNP0303", aml_resources(res_io(0x60, 1), res_io(0x64, 1), res_irq_noflags([1]))),
        isa_device("MOU", "PNP0F13", aml_resources(res_irq_noflags([12]))),
        isa_device("FDC0", "PNP0700", aml_resources(res_io(0x3F2, 4), res_io(0x3F7, 1), res_irq_noflags([6]), res_dma([2]))),
        // (QEMU's PC does not describe these: with platform.qemu_compatible
        // a guest installed there sees no new devices)
        ...platform.qemu_compatible ? [] : [
            isa_device("PIC", "PNP0000", aml_resources(res_io(0x20, 2), res_io(0xA0, 2), res_io(0x4D0, 2), res_irq_noflags([2]))),
            isa_device("TMR", "PNP0100", aml_resources(res_io(0x40, 4), res_irq_noflags([0]))),
            isa_device("DMAC", "PNP0200", aml_resources(res_io(0x00, 0x10), res_io(0x80, 0x10), res_io(0xC0, 0x20), res_dma([4]))),
            isa_device("SPKR", "PNP0800", aml_resources(res_io(0x61, 1))),
            isa_device("FPU", "PNP0C04", aml_resources(res_io(0xF0, 0x10), res_irq_noflags([13]))),
        ],
    ];
    for(const { index, port, irq } of platform.uarts)
    {
        isa_devices.push(isa_device("COM" + (index + 1), "PNP0501", aml_resources(res_io(port, 8), res_irq_noflags([irq])), index + 1));
    }
    for(const { index, port, irq } of platform.parallel_ports)
    {
        isa_devices.push(isa_device(index === 0 ? "LPT" : "LPT" + (index + 1), "PNP0400", aml_resources(res_io(port, 8), res_irq_noflags([irq])), index + 1));
    }
    return isa_devices;
}

/**
 * The TPM's device, when the machine has one (docs/tpm.md)
 * @param {Platform} platform
 * @return {!Array<!Array<number>>}
 */
function tpm_devices(platform)
{
    // (TCG ACPI Specification: MSFT0101, which Windows' tpm.inf and Linux's
    // tpm_crb bind; the TPM2 table tells the interface, CRB)
    return platform.tpm ? [aml_device("TPM",
        aml_name_decl("_HID", aml_string("MSFT0101")),
        aml_name_decl("_STA", aml_int(0x0F)),
        aml_name_decl("_CRS", aml_resources(res_memory32_fixed(TPM_CRB_BASE, TPM_CRB_SIZE))))] : [];
}

/**
 * \_Sx packages of the sleep states the machine advertises
 * @param {Platform} platform
 * @return {!Array<!Array<number>>}
 */
function sleep_state_packages(platform)
{
    return platform.sleep_states.filter(s => s.supported).map(({ state, slp_typ }) =>
        aml_name_decl("\\_S" + state, aml_package(aml_int(slp_typ), aml_int(slp_typ), aml_int(0), aml_int(0))));
}

/**
 * @param {Platform} platform
 * @param {number} pm_base
 * @return {!Array<number>} the DSDT body (after the table header)
 */
function build_dsdt_body(platform, pm_base)
{
    if(platform.machine === "q35")
    {
        return build_q35_dsdt_body(platform, pm_base);
    }

    const LINKS = ["LNKA", "LNKB", "LNKC", "LNKD"];
    const PIRQ_FIELDS = ["PRQ0", "PRQ1", "PRQ2", "PRQ3"];

    // Interrupt pin p (0 = INTA) of slot s reaches PIRQ (s + p - 1) & 3; the same
    // swizzle as PCI.prototype.get_irq_line
    const prt = [];
    for(let slot = 0; slot < 32; slot++)
    {
        for(let pin = 0; pin < 4; pin++)
        {
            prt.push(aml_package(aml_int((slot << 16 | 0xFFFF) >>> 0), aml_int(pin), aml_name(LINKS[slot + pin - 1 & 3]), aml_int(0)));
        }
    }

    const links = LINKS.map((link, i) => aml_device(link,
        aml_name_decl("_HID", aml_eisa_id("PNP0C0F")),
        aml_name_decl("_UID", aml_int(i)),
        aml_name_decl("_PRS", aml_resources(res_interrupt_shared_level(PCI_LINK_IRQS))),
        // IQST and IQCR are defined before the links: a method call can only be
        // parsed once the method (and its argument count) is known
        aml_method("_STA", 0, false, aml_return(aml_name("IQST").concat(aml_name(PIRQ_FIELDS[i])))),
        aml_method("_DIS", 0, false, aml_or(aml_name(PIRQ_FIELDS[i]), aml_int(0x80), aml_name(PIRQ_FIELDS[i]))),
        aml_method("_CRS", 0, false, aml_return(aml_name("IQCR").concat(aml_name(PIRQ_FIELDS[i])))),
        aml_method("_SRS", 1, false,
            aml_create_dword_field(aml_arg(0), 5, "PRRI"),
            aml_store(aml_name("PRRI"), aml_name(PIRQ_FIELDS[i])))));

    const isa_devices = isa_devices_of(platform);
    const gpe0 = gpe0_block(platform, pm_base);

    // Ports that belong to the chipset but no device above: ACPI PM and GPE
    // blocks, SMI_CMD/APM, fw_cfg, port 0x92 and the PIIX reset register
    const motherboard = aml_device("MBRS",
        aml_name_decl("_HID", aml_eisa_id("PNP0C02")),
        aml_name_decl("_UID", aml_int(1)),
        aml_name_decl("_CRS", aml_resources(
            res_io(pm_base, platform.pm.length),
            res_io(gpe0.base, gpe0.length),
            res_io(ACPI_SMI_CMD_PORT, 2),
            res_io(FW_CFG_PORT, 2),
            res_io(0x92, 1))));

    const pci_crs = aml_resources(
        res_word_bus(0x00, 0xFF),
        res_io(0xCF8, 8),
        res_word_io(0x0000, 0x0CF7),
        res_word_io(0x0D00, 0xFFFF),
        res_dword_memory(0xA0000, 0xBFFFF),
        ...pci_memory_windows(platform).map(([first, last]) => res_dword_memory(first, last)));

    const sleep_states = sleep_state_packages(platform);

    // ProcID i matches the ACPI processor id of the i-th MADT entry
    const processors = platform.apic_ids.map((_, i) => aml_processor("CP" + i.toString(16).toUpperCase().padStart(2, "0"), i));

    return flat([
        aml_scope("\\_SB",
            // a device has either _HID or _ADR; the root bridge is identified by _HID
            aml_device("PCI0",
                aml_name_decl("_HID", aml_eisa_id("PNP0A03")),
                // (QEMU's PC: 0; the instance ids of all devices below derive from it)
                aml_name_decl("_UID", aml_int(platform.qemu_compatible ? 0 : 1)),
                aml_name_decl("_CRS", pci_crs),
                aml_name_decl("_PRT", aml_package(...prt)),
                aml_device("ISA",
                    aml_name_decl("_ADR", aml_int(0x00010000)),
                    // PIIX PIRQ route control registers
                    aml_op_region("P40C", REGION_PCI_CONFIG, 0x60, 4),
                    ...isa_devices,
                    motherboard)),
            aml_field("PCI0.ISA.P40C", FIELD_BYTE_ACC | FIELD_PRESERVE, PIRQ_FIELDS.map(name => ({ name, bits: 8 }))),
            // _STA of a link: disabled (bit 7 set) or enabled
            aml_method("IQST", 1, false,
                aml_if(aml_and(aml_int(0x80), aml_arg(0)), aml_return(aml_int(0x09))),
                aml_return(aml_int(0x0B))),
            // _CRS of a link: its current IRQ, or none
            aml_method("IQCR", 1, true,
                aml_name_decl("PRR0", aml_resources(res_interrupt_shared_level([0]))),
                aml_create_dword_field(aml_name("PRR0"), 5, "PRRI"),
                aml_if(aml_lless(aml_arg(0), aml_int(0x80)), aml_store(aml_arg(0), aml_name("PRRI"))),
                aml_return(aml_name("PRR0"))),
            ...links,
            ...tpm_devices(platform),
            ...processors),
        ...sleep_states,
    ]);
}

/**
 * Q35: the PCI Express root bridge with the devices of the ICH9 LPC bridge,
 * the eight PIRQ links in PIC mode and their GSIs 16-23 in APIC mode (the
 * wiring of src/q35.js, which is QEMU's)
 * @param {Platform} platform
 * @param {number} pm_base
 * @return {!Array<number>} the DSDT body (after the table header)
 */
function build_q35_dsdt_body(platform, pm_base)
{
    const PIRQS = ["A", "B", "C", "D", "E", "F", "G", "H"];
    const PIRQ_FIELDS = PIRQS.map(p => "PRQ" + p);

    // PIRQ of interrupt pin p (0 = INTA) of device d on bus 0; the defaults of
    // the device 25-31 route registers (INTA..D -> PIRQA..D)
    const pirq_of = (d, p) => d <= 24 ? 4 + (d + p) % 4 : d === 30 ? 4 + p : p;
    const routing_table = prefix => {
        const entries = [];
        for(let d = 0; d < 32; d++)
        {
            for(let p = 0; p < 4; p++)
            {
                entries.push(aml_package(aml_int((d << 16 | 0xFFFF) >>> 0), aml_int(p), aml_name(prefix + PIRQS[pirq_of(d, p)]), aml_int(0)));
            }
        }
        return aml_package(...entries);
    };

    // PIC mode: link devices over the LPC's PIRQ route registers
    const links = PIRQS.map((pirq, i) => aml_device("LNK" + pirq,
        aml_name_decl("_HID", aml_eisa_id("PNP0C0F")),
        aml_name_decl("_UID", aml_int(i)),
        aml_name_decl("_PRS", aml_resources(res_interrupt_shared_level(PCI_LINK_IRQS))),
        aml_method("_STA", 0, false, aml_return(aml_name("IQST").concat(aml_name(PIRQ_FIELDS[i])))),
        aml_method("_DIS", 0, false, aml_or(aml_name(PIRQ_FIELDS[i]), aml_int(0x80), aml_name(PIRQ_FIELDS[i]))),
        aml_method("_CRS", 0, false, aml_return(aml_name("IQCR").concat(aml_name(PIRQ_FIELDS[i])))),
        aml_method("_SRS", 1, false,
            aml_create_dword_field(aml_arg(0), 5, "PRRI"),
            aml_store(aml_name("PRRI"), aml_name(PIRQ_FIELDS[i])))));

    // APIC mode: PIRQx is IOAPIC input 16 + x, always connected
    const gsi_links = PIRQS.map((pirq, i) => {
        const resources = aml_resources(res_interrupt_shared_level([16 + i]));
        return aml_device("GSI" + pirq,
            aml_name_decl("_HID", aml_eisa_id("PNP0C0F")),
            aml_name_decl("_UID", aml_int(8 + i)),
            aml_name_decl("_PRS", resources),
            aml_name_decl("_CRS", resources),
            aml_method("_STA", 0, false, aml_return(aml_int(0x0B))),
            aml_method("_DIS", 0, false, [NOOP_OP]),
            aml_method("_SRS", 1, false, [NOOP_OP]));
    });

    // Chipset resources no device above claims: the PM block (GPE0 is part of
    // it), SMI_CMD/APM, fw_cfg, port 0x92, and the root complex register block
    const motherboard = aml_device("MBRS",
        aml_name_decl("_HID", aml_eisa_id("PNP0C02")),
        aml_name_decl("_UID", aml_int(1)),
        aml_name_decl("_CRS", aml_resources(
            res_io(pm_base, platform.pm.length),
            res_io(ACPI_SMI_CMD_PORT, 2),
            res_io(FW_CFG_PORT, 2),
            res_io(0x92, 1),
            res_memory32_fixed(ICH9_RCBA_ADDRESS, ICH9_RCBA_SIZE))));

    const pci_crs = aml_resources(
        res_word_bus(0x00, platform.ecam.size / 0x100000 - 1),
        res_io(0xCF8, 8),
        res_word_io(0x0000, 0x0CF7),
        res_word_io(0x0D00, 0xFFFF),
        res_dword_memory(0xA0000, 0xBFFFF),
        // (without the ECAM window: above it with SeaBIOS, around it with OVMF)
        ...pci_memory_windows(platform).map(([first, last]) => res_dword_memory(first, last)));

    const processors = platform.apic_ids.map((_, i) => aml_processor("CP" + i.toString(16).toUpperCase().padStart(2, "0"), i));

    return flat([
        // OSPM tells the interrupt model through \_PIC: 0 PIC, 1 APIC
        aml_name_decl("\\PICF", aml_int(0)),
        aml_method("\\_PIC", 1, false, aml_store(aml_arg(0), aml_name("\\PICF"))),
        aml_scope("\\_SB",
            aml_device("PCI0",
                aml_name_decl("_HID", aml_eisa_id("PNP0A08")),
                aml_name_decl("_CID", aml_eisa_id("PNP0A03")),
                // (a device has either _HID or _ADR; the root bridge is identified by _HID)
                aml_name_decl("_UID", aml_int(0)),
                aml_name_decl("_SEG", aml_int(0)),
                aml_name_decl("_BBN", aml_int(0)),
                aml_name_decl("_CRS", pci_crs),
                aml_name_decl("PRTP", routing_table("LNK")),
                aml_name_decl("PRTA", routing_table("GSI")),
                aml_method("_PRT", 0, false,
                    aml_if(aml_name("\\PICF"), aml_return(aml_name("PRTA"))),
                    aml_return(aml_name("PRTP"))),
                pci_host_bridge_osc(),
                aml_device("ISA",
                    aml_name_decl("_ADR", aml_int(0x001F0000)),
                    // ICH9 PIRQ route control registers (PIRQA..D, SIRQ_CNTL and reserved, PIRQE..H)
                    aml_op_region("PIRQ", REGION_PCI_CONFIG, 0x60, 0x0C),
                    ...isa_devices_of(platform),
                    ...platform.hpet ? [aml_device("HPET",
                        aml_name_decl("_HID", aml_eisa_id("PNP0103")),
                        aml_name_decl("_UID", aml_int(0)),
                        aml_name_decl("_CRS", aml_resources(res_memory32_fixed(HPET_ADDRESS, HPET_SIZE))))] : [],
                    motherboard)),
            aml_field("PCI0.ISA.PIRQ", FIELD_BYTE_ACC | FIELD_PRESERVE, [
                ...PIRQ_FIELDS.slice(0, 4).map(name => ({ name, bits: 8 })),
                { name: undefined, bits: 32 },
                ...PIRQ_FIELDS.slice(4).map(name => ({ name, bits: 8 })),
            ]),
            // _STA of a link: disabled (bit 7 set) or enabled
            aml_method("IQST", 1, false,
                aml_if(aml_and(aml_int(0x80), aml_arg(0)), aml_return(aml_int(0x09))),
                aml_return(aml_int(0x0B))),
            // _CRS of a link: its current IRQ, or none
            aml_method("IQCR", 1, true,
                aml_name_decl("PRR0", aml_resources(res_interrupt_shared_level([0]))),
                aml_create_dword_field(aml_name("PRR0"), 5, "PRRI"),
                aml_if(aml_lless(aml_arg(0), aml_int(0x80)), aml_store(aml_arg(0), aml_name("PRRI"))),
                aml_return(aml_name("PRR0"))),
            ...links,
            ...gsi_links,
            // the ECAM window, which the root bridge's _CRS leaves out (PCI
            // Firmware 3.3, 4.1.2: reserved by a motherboard resource; QEMU's DRAC)
            aml_device("DRAC",
                aml_name_decl("_HID", aml_eisa_id("PNP0C01")),
                aml_name_decl("_UID", aml_int(2)),
                aml_name_decl("_CRS", aml_resources(res_memory32_fixed(platform.ecam.base, platform.ecam.size)))),
            ...tpm_devices(platform),
            ...processors),
        ...sleep_state_packages(platform),
    ]);
}

// ---------------------------------------------------------------------------
// Tables

/**
 * @param {string} signature
 * @param {number} revision
 * @param {string} table_id
 * @param {!Array<number>} body
 * @return {!Uint8Array} table with length set and checksum 0
 */
function table(signature, revision, table_id, body)
{
    const length = 36 + body.length;
    const header = Array.from(signature, c => c.charCodeAt(0)).concat(
        le(length, 4), [revision, 0],
        Array.from(OEM_ID, c => c.charCodeAt(0)),
        Array.from(table_id.padEnd(8, " "), c => c.charCodeAt(0)),
        le(1, 4),
        Array.from(CREATOR_ID, c => c.charCodeAt(0)),
        le(1, 4));
    return Uint8Array.from(header.concat(body));
}

/** Generic address structure (12 bytes); space 1 = system I/O */
const gas_io = (address, bits) => [REGION_SYSTEM_IO, bits, 0, 0].concat(le(address, 8));
const GAS_NONE = new Array(12).fill(0);

function build_facs()
{
    const facs = new Uint8Array(64);
    facs.set([0x46, 0x41, 0x43, 0x53]); // "FACS"
    facs.set(le(64, 4), 4);
    facs[32] = 1; // version
    return facs;
}

// FADT field offsets (ACPI 6.6, table 5.9)
const FADT_FIRMWARE_CTRL = 36;
const FADT_DSDT = 40;
const FADT_X_FIRMWARE_CTRL = 132;
const FADT_X_DSDT = 140;
const FADT_LENGTH = 244;

// FADT flags
const WBINVD = 1 << 0;
const PROC_C1 = 1 << 2;
const SLP_BUTTON = 1 << 5; // no sleep button
const FIX_RTC = 1 << 6; // RTC wake status is not in the fixed registers
const RESET_REG_SUP = 1 << 10;
const USE_PLATFORM_CLOCK = 1 << 15;

// IAPC_BOOT_ARCH
const LEGACY_DEVICES = 1 << 0;
const HAS_8042 = 1 << 1;

/**
 * @param {Platform} platform
 * @param {number} pm_base
 */
function build_fadt(platform, pm_base)
{
    const gpe0 = gpe0_block(platform, pm_base);
    const body = [].concat(
        le(0, 4), // FIRMWARE_CTRL (patched by the loader)
        le(0, 4), // DSDT (patched by the loader)
        [0], // reserved (INT_MODEL in ACPI 1.0)
        [0], // Preferred_PM_Profile: unspecified
        le(ACPI_SCI_IRQ, 2),
        le(ACPI_SMI_CMD_PORT, 4),
        [platform.pm.acpi_enable, platform.pm.acpi_disable, 0, 0], // S4BIOS_REQ, PSTATE_CNT
        le(pm_base, 4), le(0, 4), // PM1a/b_EVT_BLK
        le(pm_base + 4, 4), le(0, 4), // PM1a/b_CNT_BLK
        le(0, 4), // PM2_CNT_BLK
        le(pm_base + 8, 4), // PM_TMR_BLK
        le(gpe0.base, 4), le(0, 4), // GPE0/1_BLK
        [4, 2, 0, 4, gpe0.length, 0, 0, 0], // lengths, GPE1_BASE, CST_CNT
        le(101, 2), // P_LVL2_LAT > 100: no C2
        le(1001, 2), // P_LVL3_LAT > 1000: no C3
        le(0, 4), // FLUSH_SIZE, FLUSH_STRIDE
        [0, 0], // DUTY_OFFSET, DUTY_WIDTH
        [0, 0, CMOS_CENTURY], // DAY_ALRM, MON_ALRM (not supported), CENTURY
        le(LEGACY_DEVICES | HAS_8042, 2),
        [0], // reserved
        le(WBINVD | PROC_C1 | SLP_BUTTON | FIX_RTC | RESET_REG_SUP | USE_PLATFORM_CLOCK, 4),
        gas_io(RESET_PORT, 8), [RESET_VALUE, 0, 0, 0],
        le(0, 8), // X_FIRMWARE_CTRL (patched)
        le(0, 8), // X_DSDT (patched)
        gas_io(pm_base, 32), GAS_NONE, // X_PM1a/b_EVT_BLK
        gas_io(pm_base + 4, 16), GAS_NONE, // X_PM1a/b_CNT_BLK
        GAS_NONE, // X_PM2_CNT_BLK
        gas_io(pm_base + 8, 32), // X_PM_TMR_BLK
        gas_io(gpe0.base, gpe0.length * 8), GAS_NONE); // X_GPE0/1_BLK

    const fadt = table("FACP", 3, "V86FACP", body);
    dbg_assert(fadt.length === FADT_LENGTH);
    return fadt;
}

/**
 * _OSC of the PCI Express host bridge (PCI Firmware Specification 3.0, 4.5),
 * as QEMU's Q35 has it with native hot plug: the OS gets the control it asks
 * for among native PCI Express hot plug (the root ports' slots,
 * pcie_root_port.js), SHPC hot plug, PME, AER and the PCI Express capability
 * structure; other control bits are masked (and reported so). An unknown
 * UUID or revision is reported in the first dword too.
 * @return {!Array<number>}
 */
function pci_host_bridge_osc()
{
    // ToUUID ("33db4d5b-1ff7-401c-9657-7441c03dd766"), the PCI host bridge
    const PCI_HOST_BRIDGE_UUID = [0x5B, 0x4D, 0xDB, 0x33, 0xF7, 0x1F, 0x1C, 0x40, 0x96, 0x57, 0x74, 0x41, 0xC0, 0x3D, 0xD7, 0x66];
    const OSC_UNRECOGNIZED_UUID = 0x04;
    const OSC_UNRECOGNIZED_REVISION = 0x08;
    const OSC_CAPABILITIES_MASKED = 0x10;
    const GRANTED = 0x1F;
    const cdw1 = aml_name("CDW1"), cdw3 = aml_name("CDW3"), local0 = aml_local(0);
    return aml_method("_OSC", 4, false,
        aml_create_dword_field(aml_arg(3), 0, "CDW1"),
        aml_if(aml_lequal(aml_arg(0), aml_buffer(PCI_HOST_BRIDGE_UUID)),
            aml_create_dword_field(aml_arg(3), 4, "CDW2"),
            aml_create_dword_field(aml_arg(3), 8, "CDW3"),
            aml_store(cdw3, local0),
            aml_and(local0, aml_int(GRANTED), local0),
            aml_if(aml_lnot(aml_lequal(aml_arg(1), aml_int(1))),
                aml_or(cdw1, aml_int(OSC_UNRECOGNIZED_REVISION), cdw1)),
            aml_if(aml_lnot(aml_lequal(cdw3, local0)),
                aml_or(cdw1, aml_int(OSC_CAPABILITIES_MASKED), cdw1)),
            aml_store(local0, cdw3)),
        aml_else(
            aml_or(cdw1, aml_int(OSC_UNRECOGNIZED_UUID), cdw1)),
        aml_return(aml_arg(3)));
}

/** @param {Platform} platform */
function build_madt(platform)
{
    const PCAT_COMPAT = 1;
    const LEVEL_ACTIVE_HIGH = 0x0D; // polarity active high (1), trigger level (3 << 2)

    const entries = [];
    platform.apic_ids.forEach((apic_id, i) => {
        entries.push([0, 8, i, apic_id].concat(le(1, 4))); // processor local APIC, enabled
    });
    entries.push([1, 12, IOAPIC_ID, 0].concat(le(IOAPIC_ADDRESS, 4), le(0, 4)));
    // The SCI and the PCI interrupt links are level-triggered, active high.
    // Other ISA IRQs keep the default (edge, active high, GSI = IRQ).
    for(const irq of [ACPI_SCI_IRQ].concat(PCI_LINK_IRQS))
    {
        entries.push([2, 10, 0, irq].concat(le(irq, 4), le(LEVEL_ACTIVE_HIGH, 2)));
    }
    entries.push([4, 6, 0xFF, 0, 0, 1]); // local APIC NMI on LINT1 of every processor

    return table("APIC", 1, "V86APIC", le(LAPIC_ADDRESS, 4).concat(le(PCAT_COMPAT, 4), flat(entries)));
}

/**
 * The HPET description table (IA-PC HPET 1.0a, 3.2.4): the event timer
 * block's ID, its address (system memory), HPET number 0, no minimum clock
 * tick, no page protection (QEMU's values)
 */
function build_hpet()
{
    return table("HPET", 1, "V86HPET", le(HPET_BLOCK_ID, 4).concat(
        [0, 0, 0, 0], le(HPET_ADDRESS, 8), [0], le(0, 2), [0]));
}

/**
 * TPM2 (TCG ACPI Specification 1.3, revision 4): a client platform's TPM 2.0
 * started through its CRB (start method 7), the control area's address; no
 * start method parameters; the log area (etc/tpm/log, its address filled in
 * by the table loader), where SeaBIOS logs what it measures (and without
 * which it leaves the TPM alone)
 */
function build_tpm2()
{
    const body = [].concat(le(0, 2), le(0, 2), le(TPM_CRB_BASE + 0x40, 8), le(7, 4),
        new Array(12).fill(0), le(TPM_LOG_SIZE, 4), le(0, 8));
    dbg_assert(36 + body.length === TPM2_LASA + 8);
    return table("TPM2", 4, "V86TPM2", body);
}

/**
 * PCI Express memory-mapped configuration space (PCI Firmware 3.3, 4.1.2):
 * one allocation, segment 0, buses 0 to the last one of the ECAM window
 * @param {Platform} platform
 */
function build_mcfg(platform)
{
    const ecam = platform.ecam;
    return table("MCFG", 1, "V86MCFG", le(0, 8).concat(
        le(ecam.base, 8), le(0, 2), [0, ecam.size / 0x100000 - 1], le(0, 4)));
}

// ---------------------------------------------------------------------------
// Linker/loader script (SeaBIOS src/fw/romfile_loader.h)

const LOADER_ENTRY_SIZE = 128;
const LOADER_FILE_NAME_SIZE = 56;
const COMMAND_ALLOCATE = 1;
const COMMAND_ADD_POINTER = 2;
const COMMAND_ADD_CHECKSUM = 3;
export const ZONE_HIGH = 1;
export const ZONE_FSEG = 2;

function loader_name(name)
{
    dbg_assert(name.length < LOADER_FILE_NAME_SIZE);
    const bytes = new Array(LOADER_FILE_NAME_SIZE).fill(0);
    for(let i = 0; i < name.length; i++) bytes[i] = name.charCodeAt(i);
    return bytes;
}

function loader_entry(bytes)
{
    const entry = new Array(LOADER_ENTRY_SIZE).fill(0);
    bytes.forEach((b, i) => entry[i] = b);
    return entry;
}

const loader_allocate = (file, align, zone) =>
    loader_entry(le(COMMAND_ALLOCATE, 4).concat(loader_name(file), le(align, 4), [zone]));
const loader_add_pointer = (dest_file, src_file, offset, size) =>
    loader_entry(le(COMMAND_ADD_POINTER, 4).concat(loader_name(dest_file), loader_name(src_file), le(offset, 4), [size]));
const loader_add_checksum = (file, offset, start, length) =>
    loader_entry(le(COMMAND_ADD_CHECKSUM, 4).concat(loader_name(file), le(offset, 4), le(start, 4), le(length, 4)));

/**
 * Build all tables. Pointers inside the files hold offsets into
 * etc/acpi/tables; the loader script turns them into addresses and fills in
 * the checksums.
 * @param {Platform} platform
 * @param {number} pm_base PM I/O base as programmed in PMBA
 * @return {{ tables: !Uint8Array, rsdp: !Uint8Array, loader: !Uint8Array, tpm_log: ?Uint8Array,
 *            layout: !Object<string, {offset: number, length: number}> }}
 */
export function build_acpi_tables(platform, pm_base)
{
    const parts = [
        ["FACS", build_facs()],
        ["DSDT", table("DSDT", 1, "V86DSDT", build_dsdt_body(platform, pm_base))],
        ["FACP", build_fadt(platform, pm_base)],
        ["APIC", build_madt(platform)],
        ...platform.ecam ? [["MCFG", build_mcfg(platform)]] : [],
        ...platform.hpet ? [["HPET", build_hpet()]] : [],
        ...platform.tpm ? [["TPM2", build_tpm2()]] : [],
    ];

    // RSDT and XSDT list every table except FACS and DSDT (the FADT points to those)
    const listed = parts.filter(([name]) => name !== "FACS" && name !== "DSDT").map(([name]) => name);

    const layout = {};
    let offset = 0;
    for(const [name, data] of parts)
    {
        layout[name] = { offset, length: data.length };
        offset += data.length;
    }
    const rsdt_offset = offset;
    const rsdt = table("RSDT", 1, "V86RSDT", flat(listed.map(name => le(layout[name].offset, 4))));
    layout["RSDT"] = { offset: rsdt_offset, length: rsdt.length };
    const xsdt_offset = rsdt_offset + rsdt.length;
    const xsdt = table("XSDT", 1, "V86XSDT", flat(listed.map(name => le(layout[name].offset, 8))));
    layout["XSDT"] = { offset: xsdt_offset, length: xsdt.length };
    parts.push(["RSDT", rsdt], ["XSDT", xsdt]);

    const tables = new Uint8Array(xsdt_offset + xsdt.length);
    for(const [name, data] of parts)
    {
        tables.set(data, layout[name].offset);
    }

    // FADT pointers to FACS and DSDT (32 and 64 bit)
    const fadt = layout["FACP"].offset;
    tables.set(le(layout["FACS"].offset, 4), fadt + FADT_FIRMWARE_CTRL);
    tables.set(le(layout["DSDT"].offset, 4), fadt + FADT_DSDT);
    tables.set(le(layout["FACS"].offset, 8), fadt + FADT_X_FIRMWARE_CTRL);
    tables.set(le(layout["DSDT"].offset, 8), fadt + FADT_X_DSDT);

    const rsdp = Uint8Array.from([].concat(
        Array.from("RSD PTR ", c => c.charCodeAt(0)), [0],
        Array.from(OEM_ID, c => c.charCodeAt(0)), [2],
        le(rsdt_offset, 4), le(36, 4), le(xsdt_offset, 8), [0, 0, 0, 0]));
    dbg_assert(rsdp.length === 36);

    const T = ACPI_TABLES_FILE;
    const commands = [
        loader_allocate(ACPI_RSDP_FILE, 16, ZONE_FSEG),
        // 64-byte alignment is required by the FACS at offset 0
        loader_allocate(T, 64, ZONE_HIGH),
        loader_add_pointer(T, T, fadt + FADT_FIRMWARE_CTRL, 4),
        loader_add_pointer(T, T, fadt + FADT_DSDT, 4),
        loader_add_pointer(T, T, fadt + FADT_X_FIRMWARE_CTRL, 8),
        loader_add_pointer(T, T, fadt + FADT_X_DSDT, 8),
        ...listed.map((_, i) => loader_add_pointer(T, T, rsdt_offset + 36 + 4 * i, 4)),
        ...listed.map((_, i) => loader_add_pointer(T, T, xsdt_offset + 36 + 8 * i, 8)),
        loader_add_pointer(ACPI_RSDP_FILE, T, 16, 4),
        loader_add_pointer(ACPI_RSDP_FILE, T, 24, 8),
        // (the TPM's log area, in reserved memory as the tables are)
        ...platform.tpm ? [
            loader_allocate(TPM_LOG_FILE, 64, ZONE_HIGH),
            loader_add_pointer(T, TPM_LOG_FILE, layout["TPM2"].offset + TPM2_LASA, 8),
        ] : [],
        // Checksums last: they cover the patched pointers
        ...parts.filter(([name]) => name !== "FACS").map(([name]) =>
            loader_add_checksum(T, layout[name].offset + 9, layout[name].offset, layout[name].length)),
        loader_add_checksum(ACPI_RSDP_FILE, 8, 0, 20),
        loader_add_checksum(ACPI_RSDP_FILE, 32, 0, 36),
    ];

    return { tables, rsdp, loader: Uint8Array.from(flat(commands)), tpm_log: platform.tpm ? new Uint8Array(TPM_LOG_SIZE) : null, layout };
}

/**
 * Find the ACPI tables in guest memory the way an OS does (RSDP in the BIOS
 * area, then XSDT or RSDT), for diagnostics and tests
 * @param {!Uint8Array} mem8
 * @return {?{rsdp: number, revision: number, oem_id: string,
 *            tables: !Array<{signature: string, address: number, length: number, checksum_ok: boolean}>}}
 */
export function locate_acpi_tables(mem8)
{
    const u32 = a => (mem8[a] | mem8[a + 1] << 8 | mem8[a + 2] << 16 | mem8[a + 3] << 24) >>> 0;
    const text = (a, n) => String.fromCharCode(...mem8.subarray(a, a + n));
    const sum = (a, n) => mem8.subarray(a, a + n).reduce((x, y) => x + y, 0) & 0xFF;
    const in_ram = (a, n) => a + n <= mem8.length;

    let rsdp = -1;
    for(let a = 0xE0000; a < 0x100000; a += 16)
    {
        if(text(a, 8) === "RSD PTR " && sum(a, 20) === 0)
        {
            rsdp = a;
            break;
        }
    }
    if(rsdp === -1)
    {
        return null;
    }

    const revision = mem8[rsdp + 15];
    const table = address => {
        if(!in_ram(address, 36)) return { signature: "????", address, length: 0, checksum_ok: false };
        const length = u32(address + 4);
        const signature = text(address, 4);
        const checksum_ok = signature === "FACS" || in_ram(address, length) && sum(address, length) === 0;
        return { signature, address, length, checksum_ok };
    };

    // XSDT entries above 4 GiB can't be in v86's RAM; use the low half
    const use_xsdt = revision >= 2 && u32(rsdp + 28) === 0 && u32(rsdp + 24) !== 0;
    const root = table(use_xsdt ? u32(rsdp + 24) : u32(rsdp + 16));
    const entry_size = use_xsdt ? 8 : 4;
    const tables = [root];
    for(let p = root.address + 36; p + entry_size <= root.address + root.length && in_ram(p, entry_size); p += entry_size)
    {
        const t = table(u32(p));
        tables.push(t);
        if(t.signature === "FACP" && t.length >= 44)
        {
            tables.push(table(u32(t.address + 36)), table(u32(t.address + 40))); // FACS, DSDT
        }
    }

    return { rsdp, revision, oem_id: text(rsdp + 9, 6), tables };
}
               source/v64/src/ahci.js                                                                              0000644 0000000 0000000 00000157163 00000000000 011732  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AHCI host bus adapter with SATA ports: the ICH9 AHCI function (00:1f.2) of
// the Q35 machine. Each port with a drive hosts an ATA or ATAPI device of
// src/ide.js, for which the port is the transport (IDEInterface's channel):
// the command FIS is loaded into the device's task file registers, data
// phases go through the command's PRDT, and completions become received FISes
// and interrupt status bits.
//
// Drives can be attached to and detached from the ports at runtime (hot
// plug): the guest sees the link change (PxSERR.DIAG.X/N, the PCS and PRCS
// interrupts) and finds out what is there by resetting the port.
//
// Serial ATA AHCI 1.3.1 specification:
// https://www.intel.com/content/dam/www/public/us/en/documents/technical-specifications/serial-ata-ahci-spec-rev1-3-1.pdf
// Behaviour the guests depend on (SeaBIOS rel-1.16.2 src/hw/ahci.c, Linux
// drivers/ata/libahci.c, QEMU hw/ide/ahci.c) is listed in docs/ahci.md; the
// ports, links and devices are described in docs/sata.md.

import { LOG_DISK } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";
import { IDEInterface } from "./ide.js";
import { QEMU_PCI_SUBSYSTEM, pci_functions } from "./platform.js";
import { msi_capability } from "./pci.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

const PORT_COUNT = 6;
const COMMAND_SLOTS = 32;
const ABAR_SIZE = 0x1000;
const PORT_REGISTERS = 0x100;
const PORT_REGISTERS_SIZE = 0x80;

// Generic host control
const HOST_CAP = 0x00;
const HOST_GHC = 0x04;
const HOST_IS = 0x08;
const HOST_PI = 0x0C;
const HOST_VS = 0x10;

const CAP_PSC = 1 << 13;            // partial state capable
const CAP_SSC = 1 << 14;            // slumber state capable
const CAP_SAM = 1 << 18;            // supports AHCI mode only
const CAP_ISS_GEN1 = 1 << 20;       // interface speed: Gen 1 (1.5 Gbps)
const CAP_SALP = 1 << 26;           // aggressive link power management
const CAP_SNCQ = 1 << 30;           // native command queuing
const CAP_S64A = 1 << 31;           // 64-bit addressing

const GHC_HR = 1 << 0;              // HBA reset
const GHC_IE = 1 << 1;              // interrupt enable
const GHC_AE = 1 << 31;             // AHCI enable (read-only 1: CAP.SAM)

/** AHCI 1.0, as QEMU reports it (CAP2 and BOHC exist from AHCI 1.2) */
const AHCI_VERSION = 0x00010000;

// Port registers
const PX_CLB = 0x00;
const PX_CLBU = 0x04;
const PX_FB = 0x08;
const PX_FBU = 0x0C;
const PX_IS = 0x10;
const PX_IE = 0x14;
const PX_CMD = 0x18;
const PX_TFD = 0x20;
const PX_SIG = 0x24;
const PX_SSTS = 0x28;
const PX_SCTL = 0x2C;
const PX_SERR = 0x30;
const PX_SACT = 0x34;
const PX_CI = 0x38;

// PxIS / PxIE
const IS_DHRS = 1 << 0;             // D2H register FIS received (with I)
const IS_PSS = 1 << 1;              // PIO setup FIS received (with I)
const IS_SDBS = 1 << 3;             // set device bits FIS
const IS_DPS = 1 << 5;              // descriptor processed
const IS_PCS = 1 << 6;              // port connect change (PxSERR.DIAG.X)
const IS_PRCS = 1 << 22;            // PhyRdy change (PxSERR.DIAG.N)
const IS_OFS = 1 << 24;             // overflow
const IS_IFS = 1 << 27;             // interface fatal error
const IS_HBFS = 1 << 29;            // host bus fatal error
const IS_TFES = 1 << 30;            // task file error
/** PxIS bits software can clear and PxIE bits it can set */
const IS_IMPLEMENTED = 0xFDC000FF;

// PxCMD
const CMD_ST = 1 << 0;
const CMD_SUD = 1 << 1;
const CMD_POD = 1 << 2;
const CMD_CLO = 1 << 3;
const CMD_FRE = 1 << 4;
const CMD_FR = 1 << 14;
const CMD_CR = 1 << 15;
const CMD_HPCP = 1 << 18;           // hot plug capable port
const CMD_ALPE = 1 << 26;           // aggressive link power management enable
const CMD_ASP = 1 << 27;            // aggressive slumber (else partial)
const CMD_ICC_SHIFT = 28;           // interface communication control (a request; reads 0)
/** Software-writable bits: ST, FRE, ATAPI, DLAE, ALPE, ASP (ICC is not implemented) */
const CMD_WRITABLE = CMD_ST | CMD_FRE | 1 << 24 | 1 << 25 | 1 << 26 | 1 << 27;

// PxSSTS: device present, communication established, Gen 1, active
const SSTS_DEVICE = 0x113;
// Interface power management states (PxSSTS.IPM, and the PxCMD.ICC requests)
const IPM_ACTIVE = 1;
const IPM_PARTIAL = 2;
const IPM_SLUMBER = 6;
// PxSCTL.IPM: transitions software does not allow
const SCTL_IPM_NO_PARTIAL = 1 << 8;
const SCTL_IPM_NO_SLUMBER = 2 << 8;
const SERR_DIAG_N = 1 << 16;        // PhyRdy change
const SERR_DIAG_X = 1 << 26;        // exchanged

// Command header (32 bytes) DW0
const HEADER_CFL = 0x1F;            // command FIS length in dwords
const HEADER_WRITE = 1 << 6;

// FIS types
const FIS_REG_H2D = 0x27;
const FIS_REG_D2H = 0x34;
const FIS_PIO_SETUP = 0x5F;
const FIS_SET_DEVICE_BITS = 0xA1;
const FIS_H2D_COMMAND = 0x80;       // C: command register update (else device control)

// Received FIS area
const RFIS_PIO_SETUP = 0x20;
const RFIS_D2H = 0x40;
const RFIS_SDB = 0x58;

// ATA/ATAPI
const ATA_SR_ERR = 0x01;
const ATA_SR_DRQ = 0x08;
const ATA_SR_DSC = 0x10;
const ATA_SR_DRDY = 0x40;
const ATA_SR_BSY = 0x80;
const ATA_ER_ABRT = 0x04;
const ATA_CR_SRST = 0x04;
const ATA_CMD_PACKET = 0xA0;
const ATA_CMD_READ_FPDMA_QUEUED = 0x60;
const ATA_CMD_WRITE_FPDMA_QUEUED = 0x61;
const ATA_CMD_READ_LOG_EXT = 0x2F;
const ATA_ER_IDNF = 0x10;
/** READ/WRITE DMA (EXT): their data moves by DMA once the command is set up */
const ATA_DMA_COMMANDS = new Set([0xC8, 0x25, 0xCA, 0x35]);
const ATA_READ_DMA = new Set([0xC8, 0x25]);
/** PIO commands whose data goes from the host to the device */
const ATA_PIO_OUT_COMMANDS = new Set([0x30, 0x34, 0x39, 0xC5]);

/** The MSI capability (where ICH9's is) */
const MSI_CAP = 0x80;

const STATE_FORMAT = 1;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 * @param {!Array<({buffer: ?, is_cdrom: (boolean|undefined)}|undefined)>} drives by port
 * @param {number=} pci_id the function (ICH9's 00:1f.2 by default)
 */
export function AHCIController(cpu, bus, drives, pci_id)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    /** @const @type {BusConnector} */
    this.bus = bus;
    this.name = "ahci";

    this.pci_id = pci_id === undefined ? pci_functions(cpu.platform).ahci : pci_id;
    dbg_assert(this.pci_id >= 0);

    const qemu = cpu.platform.qemu_compatible;
    // 00:1f.2 SATA controller: Intel Corporation 82801IR/IO/IH (ICH9R/DO/DH) 6 port SATA Controller [AHCI mode] (rev 02)
    const space = new Array(256).fill(0);
    space.splice(0, 16, 0x86, 0x80, 0x22, 0x29, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, 0x06, 0x01, 0x00, 0x00, 0x00, 0x00);
    space.splice(0x2C, 4, ...qemu ? QEMU_PCI_SUBSYSTEM : [0x86, 0x80, 0x22, 0x29]);
    space[0x06] = 0x10; // status: capabilities list
    space[0x34] = MSI_CAP;
    space.splice(MSI_CAP, 14, ...msi_capability(0));
    space[0x3D] = 1;    // INTA
    space[0x90] = 0x40; // MAP: SATA mode select = AHCI
    this.pci_space = space;
    this.pci_bars = [undefined, undefined, undefined, undefined, undefined,
        { size: ABAR_SIZE, on_move: base => this.update_decode() }];
    this.on_command_change = () => {
        this.update_decode();
        // (bus mastering was off: commands wait for it)
        this.ports.forEach(port => port.check_commands());
    };
    this.on_config_restore = () => this.update_decode();
    // (behind a bridge: its decode and bus mastering changed)
    this.on_upstream_change = () => {
        this.update_decode();
        this.ports.forEach(port => port.check_commands());
    };
    this.on_config_write = (offset, size) => {
        if(offset < MSI_CAP + 14 && offset + size > MSI_CAP)
        {
            this.cpu.devices.pci.msi_config_written(this.pci_id, MSI_CAP, 0);
            // (enabling MSI releases INTA; disabling it may need INTA)
            this.update_irq();
        }
    };

    /** @type {!Array<AHCIPort>} */
    this.ports = [];
    for(let i = 0; i < PORT_COUNT; i++)
    {
        this.ports.push(new AHCIPort(this, i, drives[i]));
    }

    this.ghc = GHC_AE;
    /** Where ABAR is decoded, or -1 */
    this.abar = -1;
    /** The level this function drives on INTA */
    this.irq_level = false;
    /** With MSI: whether an interrupt is pending (a message was sent for it) */
    this.msi_pending = false;
    /** A port set status bits since the last interrupt decision */
    this.new_event = false;

    /** @const @type {!Int32Array} */
    this.pci_config = cpu.devices.pci.register_device(this);

    this.update_decode();
}

/**
 * HBA capabilities: six ports, 32 command slots, AHCI only, Gen 1, 64-bit
 * addressing (limited by the 36-bit physical address space), native command
 * queuing, link power management (partial, slumber, aggressive).
 * @return {number}
 */
AHCIController.prototype.capabilities = function()
{
    return (PORT_COUNT - 1 | COMMAND_SLOTS - 1 << 8 | CAP_SAM | CAP_ISS_GEN1 |
        CAP_PSC | CAP_SSC | CAP_SALP |
        (this.ports[0].ncq_depth ? CAP_SNCQ : 0) | (this.s64a ? CAP_S64A : 0)) >>> 0;
};

/**
 * 64-bit addressing: the upper halves of the list, FIS, command table and data
 * addresses are used (CLBU, FBU, CTBAU, DBAU); addresses beyond guest RAM
 * fail like any address outside it
 */
AHCIController.prototype.s64a = true;

/**
 * The drive configured as hda, hdb or cdrom: a hard disk on port 0 or 1, the
 * CD drive on port 2
 * @param {string} name
 * @return {IDEInterface|undefined}
 */
AHCIController.prototype.disk_device = function(name)
{
    const port = { "hda": 0, "hdb": 1, "cdrom": 2 }[name];
    const device = port === undefined ? null : this.ports[port].device;
    return device && device.is_atapi === (name === "cdrom") ? device : undefined;
};

/** @return {!Array<!Array<?>>} [name, device] of every port with a drive */
AHCIController.prototype.disk_devices = function()
{
    return this.ports.filter(port => port.device).map(port => {
        const name = ["hda", "hdb", "cdrom"][port.number];
        return [name && this.disk_device(name) === port.device ? name : "sata" + port.number, port.device];
    });
};

/** The machine's CD drive (cpu.devices.cdrom) is the ATAPI drive on port 2 */
AHCIController.prototype.update_cdrom = function()
{
    if(this.cpu.devices.ahci === this)
    {
        this.cpu.devices.cdrom = this.disk_device("cdrom");
    }
};

/**
 * Hot plug: attach a drive to a free port. The device signals its presence
 * (COMINIT): PxSERR.DIAG.X and DIAG.N are set (PCS, PRCS), the link comes up
 * unless software holds it in reset or disabled, and the device sends its
 * signature once FIS reception is on.
 * @param {number} number the port
 * @param {{buffer: ?, is_cdrom: (boolean|undefined)}} drive
 * @return {IDEInterface}
 */
AHCIController.prototype.attach = function(number, drive)
{
    const port = this.ports[number];
    if(!port || port.device)
    {
        throw new Error("AHCI: port " + number + (port ? " already has a drive" : " does not exist"));
    }
    port.attach(drive);
    this.update_cdrom();
    this.update_irq();
    return port.device;
};

/**
 * Hot plug: remove the drive of a port (a surprise removal). The link goes
 * down, PxSERR.DIAG.N is set (PRCS); commands issued stay issued until
 * software stops the port. Disk I/O in flight completes nowhere; writes
 * already handed to the disk image land.
 * @param {number} number the port
 */
AHCIController.prototype.detach = function(number)
{
    const port = this.ports[number];
    if(!port || !port.device)
    {
        throw new Error("AHCI: port " + number + " has no drive");
    }
    port.detach();
    this.update_cdrom();
    this.update_irq();
};

/**
 * Decode ABAR (BAR5) where the guest put it while memory space is enabled
 * (and, behind a bridge, the bridges forward it)
 */
AHCIController.prototype.update_decode = function()
{
    const pci = this.cpu.devices.pci;
    const bar = this.pci_bars[5];
    const base = bar.base && pci.memory_decoded(this.pci_id, bar.base, ABAR_SIZE) ? bar.base : -1;

    if(base === this.abar)
    {
        return;
    }

    const io = this.cpu.io;
    if(this.abar !== -1)
    {
        io.mmap_unregister_range(this.abar, ABAR_SIZE, this);
    }
    dbg_log("AHCI: ABAR " + (base === -1 ? "not decoded" : "at " + h(base >>> 0, 8)), LOG_DISK);
    this.abar = base;
    if(base !== -1)
    {
        io.mmap_register_range(base, ABAR_SIZE, this,
            addr => this.read32(addr - this.abar & ~3) >>> ((addr & 3) << 3) & 0xFF,
            (addr, value) => this.write32(addr - this.abar & ~3, value << ((addr & 3) << 3), 0xFF << ((addr & 3) << 3)),
            addr => this.read32(addr - this.abar),
            (addr, value) => this.write32(addr - this.abar, value, -1));
    }
};

/** Whether the function may access memory (PCI bus mastering) */
AHCIController.prototype.can_dma = function()
{
    return this.cpu.devices.pci.is_bus_master(this.pci_id);
};

/**
 * @param {number} offset
 * @return {number}
 */
AHCIController.prototype.read32 = function(offset)
{
    offset >>>= 0;
    let value = 0;
    if(offset >= PORT_REGISTERS && offset < PORT_REGISTERS + PORT_COUNT * PORT_REGISTERS_SIZE)
    {
        const port = this.ports[offset - PORT_REGISTERS >> 7];
        value = port.read32(offset & PORT_REGISTERS_SIZE - 1);
    }
    else
    {
        switch(offset)
        {
            case HOST_CAP: value = this.capabilities(); break;
            case HOST_GHC: value = this.ghc; break;
            case HOST_IS: value = this.interrupt_status(); break;
            case HOST_PI: value = (1 << PORT_COUNT) - 1; break;
            case HOST_VS: value = AHCI_VERSION; break;
            // CCC, enclosure management, vendor specific: not implemented
        }
    }
    dbg_log("AHCI read " + h(offset, 3) + " -> " + h(value >>> 0, 8), LOG_DISK);
    return value | 0;
};

/**
 * @param {number} offset
 * @param {number} value
 * @param {number} mask the bytes written (a byte access writes one)
 */
AHCIController.prototype.write32 = function(offset, value, mask)
{
    offset >>>= 0;
    dbg_log("AHCI write " + h(offset, 3) + " <- " + h(value >>> 0, 8) + (mask === -1 ? "" : " mask " + h(mask >>> 0, 8)), LOG_DISK);
    if(offset >= PORT_REGISTERS && offset < PORT_REGISTERS + PORT_COUNT * PORT_REGISTERS_SIZE)
    {
        this.ports[offset - PORT_REGISTERS >> 7].write32(offset & PORT_REGISTERS_SIZE - 1, value & mask, mask);
        return;
    }
    switch(offset)
    {
        case HOST_GHC:
            if(value & mask & GHC_HR)
            {
                this.hba_reset();
            }
            else
            {
                this.ghc = GHC_AE | (this.ghc & ~mask | value & mask) & GHC_IE;
                this.update_irq();
            }
            break;
        case HOST_IS:
            // write one to clear: the bits follow the ports' status, as in QEMU
            this.update_irq();
            break;
    }
};

/** IS: the ports with an enabled interrupt pending */
AHCIController.prototype.interrupt_status = function()
{
    let status = 0;
    this.ports.forEach((port, i) => {
        if(port.interrupt_bits() & port.ie)
        {
            status |= 1 << i;
        }
    });
    return status;
};

/**
 * Interrupts from the ports' enabled status and GHC.IE: INTA follows the
 * level; with MSI enabled, a message is sent when an interrupt becomes
 * pending and for every new event while it is (QEMU sends one per check)
 */
AHCIController.prototype.update_irq = function()
{
    const pci = this.cpu.devices.pci;
    const pending = (this.ghc & GHC_IE) !== 0 && this.interrupt_status() !== 0;
    const msi = pci.msi_enabled(this.pci_id, MSI_CAP);
    const level = pending && !msi;
    if(level !== this.irq_level)
    {
        this.irq_level = level;
        level ? pci.raise_irq(this.pci_id) : pci.lower_irq(this.pci_id);
    }
    if(msi && pending && (!this.msi_pending || this.new_event))
    {
        pci.msi_notify(this.pci_id, MSI_CAP);
    }
    this.msi_pending = msi && pending;
    this.new_event = false;
};

/** GHC.HR: the HBA and every port return to their reset state, each link is reset (COMRESET) */
AHCIController.prototype.hba_reset = function()
{
    dbg_log("AHCI: HBA reset", LOG_DISK);
    this.ghc = GHC_AE;
    this.ports.forEach(port => port.reset(false));
    this.update_irq();
};

/** PCIRST#: as GHC.HR, and the list and FIS base addresses are cleared too */
AHCIController.prototype.reset = function()
{
    this.ghc = GHC_AE;
    this.ports.forEach(port => port.reset(true));
    this.update_irq();
};

AHCIController.prototype.get_state = function()
{
    const state = [];
    state[0] = STATE_FORMAT;
    state[1] = this.ghc;
    state[2] = this.irq_level;
    state[3] = this.ports.map(port => port.get_state());
    state[4] = this.msi_pending;
    return state;
};

AHCIController.prototype.set_state = function(state)
{
    dbg_assert(state[0] === STATE_FORMAT);
    this.ghc = state[1];
    this.irq_level = state[2];
    this.new_event = false;
    // (a drive present on one side only becomes a hot plug event, signalled
    // by update_irq once the whole machine is restored)
    this.ports.forEach((port, i) => port.set_state(state[3][i]));
    this.msi_pending = !!state[4];
    this.update_cdrom();
};

/**
 * A SATA port and the transport of its device
 * @constructor
 * @param {AHCIController} controller
 * @param {number} number
 * @param {({buffer: ?, is_cdrom: (boolean|undefined)}|undefined)} drive
 */
function AHCIPort(controller, number, drive)
{
    this.controller = controller;
    this.number = number;
    /** @const @type {CPU} */
    this.cpu = controller.cpu;
    this.bus = controller.bus;
    this.name = "ahci" + number;

    // The transport as IDEInterface sees it. channel_nr and the device's
    // interface_nr give the drive the IDE position of the same name
    // (hda: 0.0, hdb: 0.1, cdrom: 1.0) for names, serial numbers and the
    // disk activity events.
    this.channel_nr = number >> 1;
    this.cmos_geometry = false;
    this.sata = true;
    /** Native command queuing, 32 deep */
    this.ncq_depth = COMMAND_SLOTS;
    /** bit 0: the current command's DMA may run (IDEInterface checks it) */
    this.dma_status = 0;
    this.slave = null;

    /** @type {IDEInterface|null} */
    this.device = null;
    this.device = drive && (drive.buffer || drive.is_cdrom) ?
        new IDEInterface(this, number & 1, drive.buffer, !!drive.is_cdrom) : null;
    this.master = this.device;
    /**
     * PxCMD.HPCP, set by the platform: the ports without a drive at power-on
     * are the hot plug capable ones (every port supports hot plug; Windows
     * offers to eject the drives on such ports)
     * @const
     */
    this.hot_plug_capable = !this.device;

    this.clb = 0;
    this.clbu = 0;
    this.fb = 0;
    this.fbu = 0;
    this.is = 0;
    this.ie = 0;
    this.cmd = 0;
    this.tfd = 0x7F;
    this.sig = -1;
    this.ssts = 0;
    this.sctl = 0;
    this.serr = 0;
    this.sact = 0;
    this.ci = 0;

    /** The device's first D2H register FIS after a reset, sent once FIS reception is on */
    this.init_d2h_pending = false;
    /** A command failed (PxIS.TFES): nothing is issued until software clears ST */
    this.halted = false;
    /** The slot being executed, or -1 */
    this.busy_slot = -1;
    /**
     * The command being executed
     * @type {?{slot: number, header: number, table: number, prdtl: number, dma: boolean,
     *          dma_started: boolean, packet_sent: boolean, bytes: number, first_drq: boolean}}
     */
    this.command = null;
    /** Device control: SRST was set by a control FIS */
    this.srst = false;

    // Native command queuing: the tags in flight, a generation that stops
    // their completions after a stop or reset, the failed command for the
    // NCQ command error log
    this.ncq_active = 0;
    this.ncq_epoch = 0;
    /** @type {?{tag: number, error: number, lba: number, count: number}} */
    this.ncq_error = null;

    // re-entrancy of the command state machine
    this.advancing = false;
    this.advance_again = false;
    this.in_device = false;

    this.reset(true);
}

/**
 * Reset the port and its link (COMRESET): with a device, the link comes up
 * and the device sends its signature once FIS reception is on
 * @param {boolean} power_on also clear the list and FIS base addresses
 */
AHCIPort.prototype.reset = function(power_on)
{
    if(power_on)
    {
        this.clb = this.clbu = this.fb = this.fbu = 0;
    }
    this.is = 0;
    this.ie = 0;
    this.cmd = CMD_SUD | CMD_POD;
    this.sctl = 0;
    this.serr = 0;
    this.sact = 0;
    this.ci = 0;
    this.halted = false;
    this.abort_command();
    this.link_reset();
};

/** COMRESET: the device resets, the link comes up again if there is one */
AHCIPort.prototype.link_reset = function()
{
    this.tfd = 0x7F;
    this.sig = -1;
    this.srst = false;
    this.abort_command();
    if(this.device)
    {
        this.device_reset();
        this.ssts = SSTS_DEVICE;
        this.init_d2h_pending = true;
        this.send_init_d2h();
    }
    else
    {
        this.ssts = 0;
        this.init_d2h_pending = false;
    }
};

/** The device's own reset: its signature in the task file, no command */
AHCIPort.prototype.device_reset = function()
{
    const device = this.device;
    this.ncq_error = null;
    device.device_reset();
    device.current_command = -1;
    device.data_pointer = device.data_end = device.data_length = 0;
    // ready: an ATA device reports DRDY, an ATAPI device 0 ([ATA8-ACS] 9.12)
    device.status_reg = device.is_atapi ? 0 : ATA_SR_DRDY | ATA_SR_DSC;
    device.error_reg = 1; // diagnostic code: no error
};

/** The first D2H register FIS after a reset: signature and status */
AHCIPort.prototype.send_init_d2h = function()
{
    if(!this.init_d2h_pending || !(this.cmd & CMD_FRE))
    {
        return;
    }
    this.init_d2h_pending = false;
    const device = this.device;
    this.sig = (device.lba_high_reg & 0xFF) << 24 | (device.lba_mid_reg & 0xFF) << 16 |
        (device.lba_low_reg & 0xFF) << 8 | device.sector_count_reg & 0xFF;
    this.post_d2h(true);
    this.controller.update_irq();
};

/**
 * PxIS: the status bits, and PCS and PRCS, which reflect PxSERR.DIAG.X and
 * DIAG.N (they clear when those are cleared)
 * @return {number}
 */
AHCIPort.prototype.interrupt_bits = function()
{
    return (this.is | (this.serr & SERR_DIAG_X ? IS_PCS : 0) | (this.serr & SERR_DIAG_N ? IS_PRCS : 0)) >>> 0;
};

/**
 * @param {{buffer: ?, is_cdrom: (boolean|undefined)}} drive
 */
AHCIPort.prototype.attach = function(drive)
{
    this.attach_device(new IDEInterface(this, this.number & 1, drive.buffer, !!drive.is_cdrom));
};

/**
 * @param {!IDEInterface} device
 */
AHCIPort.prototype.attach_device = function(device)
{
    dbg_log("AHCI port " + this.number + ": " + (device.is_atapi ? "CD drive" : "disk") + " attached", LOG_DISK);
    this.device = device;
    this.master = device;
    // COMINIT from the device (exchanged), the PhyRdy change
    this.serr = (this.serr | SERR_DIAG_X | SERR_DIAG_N) >>> 0;
    this.controller.new_event = true;
    const det = this.sctl & 0xF;
    if(det === 4)
    {
        // the interface is disabled: offline
        this.ssts = 4;
    }
    else if(det !== 1)
    {
        // (with COMRESET asserted the link comes up when software releases it)
        this.link_reset();
    }
};

AHCIPort.prototype.detach = function()
{
    dbg_log("AHCI port " + this.number + ": drive detached", LOG_DISK);
    const device = this.device;
    // its disk I/O in flight is dropped (and the requests held after an
    // I/O error: src/block_backend.js)
    device.cancel_io_operations();
    device.drop_held_requests();
    device.reset_epoch++;
    this.device = this.master = null;
    // PhyRdy lost; no device: no link, PxTFD 7Fh, no signature
    this.serr = (this.serr | SERR_DIAG_N) >>> 0;
    this.controller.new_event = true;
    this.link_reset();
};

/**
 * Interrupt status bits the port sets (PxIS)
 * @param {number} bits
 */
AHCIPort.prototype.set_status = function(bits)
{
    this.is = (this.is | bits) >>> 0;
    this.controller.new_event = true;
};

/** Stop the command being executed; its completion, if it comes, is ignored */
AHCIPort.prototype.abort_command = function()
{
    this.command = null;
    this.busy_slot = -1;
    this.dma_status = 0;
    this.ncq_active = 0;
    this.ncq_epoch++;
};

/**
 * @param {number} offset
 * @return {number}
 */
AHCIPort.prototype.read32 = function(offset)
{
    switch(offset)
    {
        case PX_CLB: return this.clb;
        case PX_CLBU: return this.clbu;
        case PX_FB: return this.fb;
        case PX_FBU: return this.fbu;
        case PX_IS: return this.interrupt_bits();
        case PX_IE: return this.ie;
        case PX_CMD:
            return this.cmd | (this.cmd & CMD_ST ? CMD_CR : 0) | (this.cmd & CMD_FRE ? CMD_FR : 0) |
                (this.hot_plug_capable ? CMD_HPCP : 0) | (this.busy_slot === -1 ? 0 : this.busy_slot << 8);
        case PX_TFD: return this.tfd;
        case PX_SIG: return this.sig;
        case PX_SSTS: return this.ssts;
        case PX_SCTL: return this.sctl;
        case PX_SERR: return this.serr;
        case PX_SACT: return this.sact;
        case PX_CI: return this.ci;
    }
    return 0;
};

/**
 * @param {number} offset
 * @param {number} value (only the bytes in mask)
 * @param {number} mask
 */
AHCIPort.prototype.write32 = function(offset, value, mask)
{
    const merge = old => (old & ~mask | value) >>> 0;
    switch(offset)
    {
        case PX_CLB:
            // 1 KiB aligned
            this.clb = merge(this.clb) & ~0x3FF;
            break;
        case PX_CLBU:
            if(this.controller.s64a) this.clbu = merge(this.clbu);
            break;
        case PX_FB:
            // 256 bytes aligned
            this.fb = merge(this.fb) & ~0xFF;
            break;
        case PX_FBU:
            if(this.controller.s64a) this.fbu = merge(this.fbu);
            break;
        case PX_IS:
            this.is &= ~value;
            this.controller.update_irq();
            break;
        case PX_IE:
            this.ie = merge(this.ie) & IS_IMPLEMENTED;
            this.controller.update_irq();
            break;
        case PX_CMD:
            this.write_command(merge(this.cmd));
            break;
        case PX_SCTL:
        {
            const old = this.sctl;
            this.sctl = merge(this.sctl) & 0xFFF;
            const det = this.sctl & 0xF;
            if(det === 1)
            {
                // COMRESET asserted: no communication until it is released
                this.ssts = 0;
                this.abort_command();
            }
            else if((old & 0xF) === 1 && det === 0)
            {
                dbg_log("AHCI port " + this.number + ": COMRESET", LOG_DISK);
                this.link_reset();
            }
            else if(det === 4)
            {
                // the interface is disabled
                this.ssts = this.device ? 4 : 0;
            }
            break;
        }
        case PX_SERR:
            // (clearing DIAG.X and DIAG.N clears PCS and PRCS)
            this.serr &= ~value;
            this.controller.update_irq();
            break;
        case PX_SACT:
            if(this.cmd & CMD_ST) this.sact = (this.sact | value) >>> 0;
            break;
        case PX_CI:
            if(this.cmd & CMD_ST)
            {
                // (a command for the device wakes a sleeping link)
                this.ci = (this.ci | value) >>> 0;
                this.check_commands();
            }
            break;
    }
};

/**
 * PxCMD: start/stop the command list (ST) and FIS reception (FRE)
 * @param {number} value
 */
AHCIPort.prototype.write_command = function(value)
{
    const old = this.cmd;
    this.cmd = value & CMD_WRITABLE | CMD_SUD | CMD_POD;

    // ICC: move the link to active, partial or slumber (done at once: the
    // field reads as idle); not while the device has work
    const icc = value >>> CMD_ICC_SHIFT;
    if(icc === IPM_ACTIVE)
    {
        this.set_link_power(IPM_ACTIVE);
    }
    else if((icc === IPM_PARTIAL || icc === IPM_SLUMBER) && this.busy_slot === -1 && !this.ncq_active)
    {
        this.set_link_power(icc);
    }

    if(old & CMD_ST && !(value & CMD_ST))
    {
        // the command list stops: commands issued are dropped (CR clears at once)
        this.ci = 0;
        this.sact = 0;
        this.halted = false;
        this.abort_command();
    }
    if(value & CMD_FRE && !(old & CMD_FRE))
    {
        this.send_init_d2h();
    }
    if(value & CMD_ST && !(old & CMD_ST))
    {
        this.halted = false;
        this.check_commands();
    }
    // (ALPE set on an idle port)
    this.idle_link_power();
};

/** Execute the next command issued, if the port can */
AHCIPort.prototype.check_commands = function()
{
    if(this.ci && this.cmd & CMD_ST)
    {
        // commands wake the link from partial or slumber
        this.set_link_power(IPM_ACTIVE);
    }
    // (the lowest slot first, as QEMU does; non-queued commands run one at a
    // time, queued ones are handed to the device as long as it takes them)
    while(this.busy_slot === -1 && !this.halted && this.cmd & CMD_ST && this.ci &&
        this.link_up() && !this.init_d2h_pending && this.controller.can_dma())
    {
        const before = this.ci;
        this.start_command(31 - Math.clz32(this.ci & -this.ci));
        if(this.ci === before && this.busy_slot === -1)
        {
            // a non-queued command waits for the queued ones in flight
            break;
        }
    }
    this.idle_link_power();
};

/** PxSSTS.DET: a device is present and communication established */
AHCIPort.prototype.link_up = function()
{
    return (this.ssts & 0xF) === 3;
};

/**
 * Interface power management: the link goes to state (IPM_ACTIVE,
 * IPM_PARTIAL, IPM_SLUMBER) if it is up and PxSCTL.IPM allows the low power
 * states. There is no real link: the transitions take no time and change no
 * PhyRdy (no PxSERR.DIAG.N).
 * @param {number} state
 */
AHCIPort.prototype.set_link_power = function(state)
{
    if(!this.link_up() || (this.ssts >> 8 & 0xF) === state ||
        state === IPM_PARTIAL && this.sctl & SCTL_IPM_NO_PARTIAL ||
        state === IPM_SLUMBER && this.sctl & SCTL_IPM_NO_SLUMBER)
    {
        return;
    }
    dbg_log("AHCI port " + this.number + ": link " + (state === IPM_ACTIVE ? "active" : state === IPM_PARTIAL ? "partial" : "slumber"), LOG_DISK);
    this.ssts = this.ssts & ~0xF00 | state << 8;
};

/** PxCMD.ALPE: an idle port (nothing issued or queued) puts its link to partial, or slumber with ASP */
AHCIPort.prototype.idle_link_power = function()
{
    if(this.cmd & CMD_ALPE && this.cmd & CMD_ST && !this.ci && !this.sact &&
        this.busy_slot === -1 && !this.ncq_active)
    {
        this.set_link_power(this.cmd & CMD_ASP ? IPM_SLUMBER : IPM_PARTIAL);
    }
};

/**
 * @param {number} slot
 */
AHCIPort.prototype.start_command = function(slot)
{
    const cpu = this.cpu;
    const header = this.list_base() + slot * 32;

    let dw0, table, fis;
    try
    {
        cpu.validate_physical_range(header, 32);
        const head = cpu.read_blob_physical(header, 16);
        dw0 = (head[0] | head[1] << 8 | head[2] << 16 | head[3] << 24) >>> 0;
        // CTBA (128-byte aligned) and CTBAU
        table = ((head[8] | head[9] << 8 | head[10] << 16 | head[11] << 24) & ~0x7F) >>> 0;
        if(this.controller.s64a)
        {
            table += (head[12] | head[13] << 8 | head[14] << 16 | head[15] << 24) * 0x100000000;
        }
        // PRDBC: nothing transferred yet
        cpu.write_blob_physical(new Uint8Array(4), header + 4);
        const fis_length = Math.max(5, dw0 & HEADER_CFL) * 4;
        fis = cpu.read_blob_physical(table, Math.min(fis_length, 64));
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.host_bus_error();
        return;
    }

    dbg_log("AHCI port " + this.number + " slot " + slot + ": FIS " + h(fis[0], 2) + " C=" + (fis[1] >> 7) +
        " command " + h(fis[2], 2) + " header " + h(dw0, 8), LOG_DISK);

    if(fis[0] !== FIS_REG_H2D)
    {
        // only register FISes are sent from a command list
        this.complete_slot(slot);
        this.set_status(IS_IFS);
        this.halted = true;
        this.controller.update_irq();
        return;
    }

    if(!(fis[1] & FIS_H2D_COMMAND))
    {
        this.device_control(slot, fis[15]);
        return;
    }

    const device = this.device;
    const command = fis[2];

    if(command === ATA_CMD_READ_FPDMA_QUEUED || command === ATA_CMD_WRITE_FPDMA_QUEUED)
    {
        this.start_queued(slot, header, table, dw0 >>> 16, fis);
        return;
    }
    if(this.ncq_active)
    {
        // non-queued commands wait until the queued ones are done
        return;
    }

    // the task file registers: the high order byte of each is the previous write
    device.features_reg = fis[11] << 8 | fis[3];
    device.lba_low_reg = fis[8] << 8 | fis[4];
    device.lba_mid_reg = fis[9] << 8 | fis[5];
    device.lba_high_reg = fis[10] << 8 | fis[6];
    device.device_reg = fis[7];
    device.is_lba = fis[7] >> 6 & 1;
    device.head = fis[7] & 0xF;
    device.sector_count_reg = fis[13] << 8 | fis[12];

    const dma = ATA_DMA_COMMANDS.has(command) || command === ATA_CMD_PACKET && (fis[3] & 1) !== 0;
    this.busy_slot = slot;
    this.command = {
        slot, header, table, prdtl: dw0 >>> 16, dma, dma_started: false,
        packet_sent: false, bytes: 0, first_drq: true,
    };
    this.dma_status = dma ? 1 : 0;
    // (the HBA shows the device busy once it has sent the command)
    this.tfd = this.tfd & ~0xFF | ATA_SR_BSY;

    device.status_reg &= ~(ATA_SR_ERR | 0x20);
    if(command === ATA_CMD_READ_LOG_EXT && !device.is_atapi)
    {
        this.read_log(fis[4], fis[5], (fis[12] | fis[13] << 8) || 0x10000);
    }
    else
    {
        this.call_device(() => device.ata_command(command));
    }
    this.advance();
};

/**
 * READ FPDMA QUEUED / WRITE FPDMA QUEUED: the device takes the command at
 * once (PxCI clears, BSY is not set), moves the data whenever the disk image
 * has it, and reports completion with a set device bits FIS for its tag
 * (PxSACT clears, SDBS); several are in flight at a time. Native command
 * queuing: Serial ATA 2.6, 13.6; AHCI 1.3.1, 5.6.4.
 * @param {number} slot
 * @param {number} header
 * @param {number} table
 * @param {number} prdtl
 * @param {!Uint8Array} fis
 */
AHCIPort.prototype.start_queued = function(slot, header, table, prdtl, fis)
{
    const device = this.device;
    const tag = fis[12] >> 3;
    const count = (fis[3] | fis[11] << 8) || 0x10000;
    const lba = fis[4] + fis[5] * 0x100 + fis[6] * 0x10000 + fis[8] * 0x1000000 + fis[9] * 0x100000000 + fis[10] * 0x10000000000;
    const write = fis[2] === ATA_CMD_WRITE_FPDMA_QUEUED;
    const job = { slot, tag, header, table, prdtl, bytes: 0, epoch: this.ncq_epoch, lba, count, write };

    // accepted: the slot is free again, and the device releases the bus with
    // a register FIS without the interrupt bit (BSY clear: ready for more)
    this.ci &= ~(1 << slot);
    device.status_reg = ATA_SR_DRDY | ATA_SR_DSC;
    device.error_reg = 0;
    this.post_d2h(false);

    dbg_log("AHCI port " + this.number + " NCQ " + (write ? "write" : "read") + " tag " + tag + " lba " + h(lba) + " count " + count, LOG_DISK);

    if(!this.ncq_depth || device.is_atapi || !device.buffer || this.ncq_error || this.ncq_active & 1 << tag)
    {
        this.ncq_failed(job, ATA_ER_ABRT);
        return;
    }
    // (in the disk's logical sectors: 512 or 4096 bytes)
    const start = lba * device.sector_size, length = count * device.sector_size;
    if(start + length > device.buffer.byteLength)
    {
        this.ncq_failed(job, ATA_ER_IDNF);
        return;
    }

    this.ncq_active |= 1 << tag;
    if(write)
    {
        let data;
        try
        {
            data = new Uint8Array(length);
            for(const segment of this.prdt_segments(job, 0, length))
            {
                data.set(this.cpu.read_blob_physical(segment.address, segment.length), segment.offset);
            }
        }
        catch(error)
        {
            if(!(error instanceof RangeError)) throw error;
            this.ncq_active &= ~(1 << tag);
            this.set_status(IS_OFS);
            this.ncq_failed(job, ATA_ER_ABRT);
            return;
        }
        // (FUA, the device register's bit 7: durable before it completes)
        device.write_to_backend(start, data, () => this.queued_done(job), () => this.queued_failed(job), !!(fis[7] & 0x80));
        device.report_write(length);
    }
    else
    {
        device.report_read_start();
        device.read_buffer(start, length, data =>
        {
            device.report_read_end(length);
            if(job.epoch !== this.ncq_epoch)
            {
                return;
            }
            try
            {
                for(const segment of this.prdt_segments(job, 0, length))
                {
                    this.cpu.write_blob_physical(data.subarray(segment.offset, segment.offset + segment.length), segment.address);
                }
            }
            catch(error)
            {
                if(!(error instanceof RangeError)) throw error;
                this.ncq_active &= ~(1 << tag);
                this.set_status(IS_OFS);
                this.ncq_failed(job, ATA_ER_ABRT);
                return;
            }
            this.queued_done(job);
        }, () =>
        {
            device.report_read_end(0);
            this.queued_failed(job);
        });
    }
};

/**
 * A queued command completed: a set device bits FIS with its tag
 * @param {!Object} job
 */
AHCIPort.prototype.queued_done = function(job)
{
    if(job.epoch !== this.ncq_epoch || !(this.ncq_active & 1 << job.tag))
    {
        // (the list was stopped or the port reset meanwhile)
        return;
    }
    this.ncq_active &= ~(1 << job.tag);
    this.post_sdb(ATA_SR_DRDY | ATA_SR_DSC, 0, 1 << job.tag);
    this.controller.update_irq();
    this.check_commands();
};

/**
 * The disk image failed a queued command's read or write
 * (docs/disk-image-formats-plan.md P0): it ends with ABRT, as QEMU's
 * ncq_err
 * @param {!Object} job
 */
AHCIPort.prototype.queued_failed = function(job)
{
    if(job.epoch !== this.ncq_epoch || !(this.ncq_active & 1 << job.tag))
    {
        return;
    }
    this.ncq_active &= ~(1 << job.tag);
    this.ncq_failed(job, ATA_ER_ABRT);
};

/**
 * A queued command failed: the device reports the error with a set device
 * bits FIS without its tag, keeps it for the NCQ command error log (READ LOG
 * EXT 10h) and rejects queued commands until the log is read; the HBA stops
 * (TFES) until software clears ST
 * @param {!Object} job
 * @param {number} error
 */
AHCIPort.prototype.ncq_failed = function(job, error)
{
    dbg_log("AHCI port " + this.number + " NCQ tag " + job.tag + " failed, error " + h(error, 2), LOG_DISK);
    if(!this.ncq_error)
    {
        this.ncq_error = { tag: job.tag, error, lba: job.lba, count: job.count };
    }
    // the device aborts every queued command it has: none of them completes
    // (writes already handed to the disk image still land)
    this.ncq_active = 0;
    this.ncq_epoch++;
    this.post_sdb(ATA_SR_DRDY | ATA_SR_ERR, error, 0);
    this.halted = true;
    this.controller.update_irq();
};

/**
 * A set device bits FIS: PxSACT loses the completed tags, PxTFD takes the
 * status and error, SDBS (the interrupt bit is always set), TFES with ERR
 * @param {number} status
 * @param {number} error
 * @param {number} completed
 */
AHCIPort.prototype.post_sdb = function(status, error, completed)
{
    this.post_fis(RFIS_SDB, [FIS_SET_DEVICE_BITS, 1 << 6, status & 0x77, error,
        completed & 0xFF, completed >> 8 & 0xFF, completed >> 16 & 0xFF, completed >>> 24]);
    this.sact = (this.sact & ~completed) >>> 0;
    this.tfd = error << 8 | this.tfd & 0x88 | status & 0x77;
    this.set_status(IS_SDBS);
    if(status & ATA_SR_ERR)
    {
        this.set_status(IS_TFES);
    }
};

/**
 * READ LOG EXT for the logs native command queuing needs: the directory
 * (00h) and the NCQ command error log (10h, whose read clears the error),
 * one page each; other logs and pages are aborted. The data goes out like
 * any PIO data-in command.
 * @param {number} log
 * @param {number} page
 * @param {number} pages
 */
AHCIPort.prototype.read_log = function(log, page, pages)
{
    const device = this.device;
    device.current_command = ATA_CMD_READ_LOG_EXT;
    device.error_reg = 0;

    const data = new Uint8Array(512);
    if(page + pages > 1)
    {
        log = -1;
    }
    if(log === 0x00 && this.ncq_depth)
    {
        // version 1; log 10h has one page
        data[0] = 1;
        data[0x10 * 2] = 1;
    }
    else if(log === 0x10 && this.ncq_depth && page === 0)
    {
        const e = this.ncq_error;
        if(e)
        {
            data[0] = e.tag;
            data[2] = ATA_SR_DRDY | ATA_SR_ERR;
            data[3] = e.error;
            data[4] = e.lba & 0xFF;
            data[5] = e.lba >> 8 & 0xFF;
            data[6] = e.lba >> 16 & 0xFF;
            data[7] = 0x40;
            data[8] = Math.floor(e.lba / 0x1000000) & 0xFF;
            data[9] = Math.floor(e.lba / 0x100000000) & 0xFF;
            data[10] = Math.floor(e.lba / 0x10000000000) & 0xFF;
            data[12] = e.count & 0xFF;
            data[13] = e.count >> 8 & 0xFF;
        }
        else
        {
            data[0] = 0x80; // NQ: no queued command failed
        }
        data[511] = -data.subarray(0, 511).reduce((a, b) => a + b, 0) & 0xFF;
        this.ncq_error = null;
    }
    else
    {
        device.current_command = -1;
        device.error_reg = ATA_ER_ABRT;
        device.status_reg = ATA_SR_DRDY | ATA_SR_ERR;
        return;
    }
    device.data_set(data);
    device.data_end = data.length;
    device.status_reg = ATA_SR_DRDY | ATA_SR_DSC | ATA_SR_DRQ;
};

/**
 * A register FIS without the C bit: an update of the device control
 * register. SRST set and then cleared resets the device (software reset).
 * @param {number} slot
 * @param {number} control
 */
AHCIPort.prototype.device_control = function(slot, control)
{
    dbg_log("AHCI port " + this.number + ": device control " + h(control, 2), LOG_DISK);
    this.complete_slot(slot);

    if(control & ATA_CR_SRST)
    {
        this.srst = true;
        this.tfd = this.tfd & ~0xFF | ATA_SR_BSY;
    }
    else if(this.srst)
    {
        this.srst = false;
        this.device_reset();
        this.sig = (this.device.lba_high_reg & 0xFF) << 24 | (this.device.lba_mid_reg & 0xFF) << 16 |
            (this.device.lba_low_reg & 0xFF) << 8 | this.device.sector_count_reg & 0xFF;
        this.post_d2h(true);
    }
    this.controller.update_irq();
    this.check_commands();
};

/**
 * Run a device method; interrupts it signals (push_irq) are looked at
 * afterwards by advance, not in the middle of it
 * @param {function()} f
 */
AHCIPort.prototype.call_device = function(f)
{
    const was = this.in_device;
    this.in_device = true;
    try
    {
        f();
    }
    finally
    {
        this.in_device = was;
    }
};

/** IDEInterface: the device signals an interrupt or a new phase */
AHCIPort.prototype.push_irq = function()
{
    if(!this.device || this.in_device)
    {
        return;
    }
    this.advance();
};

/** Drive the current command through its phases until it waits for the backend or is done */
AHCIPort.prototype.advance = function()
{
    if(this.advancing)
    {
        this.advance_again = true;
        return;
    }
    this.advancing = true;
    try
    {
        do
        {
            this.advance_again = false;
            this.advance_once();
        }
        while(this.advance_again);
    }
    finally
    {
        this.advancing = false;
    }
};

AHCIPort.prototype.advance_once = function()
{
    const command = this.command;
    if(!command)
    {
        return;
    }
    const device = this.device;
    const status = device.status_reg;

    if(status & ATA_SR_BSY)
    {
        // waiting for the disk image; push_irq continues
        return;
    }

    if(status & ATA_SR_DRQ)
    {
        if(device.current_command === ATA_CMD_PACKET && !command.packet_sent)
        {
            // the command packet (ACMD), then the device executes it
            command.packet_sent = true;
            let packet;
            try
            {
                packet = this.cpu.read_blob_physical(command.table + 0x40, 16);
            }
            catch(error)
            {
                if(!(error instanceof RangeError)) throw error;
                this.host_bus_error();
                return;
            }
            device.data.set(packet.subarray(0, 12));
            device.data_pointer = 12;
            this.call_device(() => device.write_end());
            this.advance_again = true;
            return;
        }

        if(command.dma && ATA_DMA_COMMANDS.has(device.current_command))
        {
            if(!command.dma_started)
            {
                // what the bus master start bit does for IDE
                command.dma_started = true;
                this.call_device(() => ATA_READ_DMA.has(device.current_command) ?
                    device.do_ata_read_sectors_dma() : device.do_ata_write_sectors_dma());
                this.advance_again = true;
            }
            return;
        }

        this.transfer_block(command);
        return;
    }

    this.complete_command();
};

/**
 * One data block of a command whose device has it ready (DRQ): from the
 * device's buffer to the PRDT or the reverse. ATAPI commands with DMA move
 * their data here too (the device prepared it like for PIO).
 * @param {!Object} command
 */
AHCIPort.prototype.transfer_block = function(command)
{
    const device = this.device;
    const start = device.data_pointer;
    const end = device.data_end;
    const length = end - start;
    const to_device = ATA_PIO_OUT_COMMANDS.has(device.current_command);
    const pio = !command.dma;
    const status_before = device.status_reg;

    try
    {
        if(length > 0)
        {
            const segments = this.prdt_segments(command, command.bytes, length);
            for(const segment of segments)
            {
                if(to_device)
                {
                    device.data.set(this.cpu.read_blob_physical(segment.address, segment.length), start + segment.offset);
                }
                else
                {
                    this.cpu.write_blob_physical(device.data.subarray(start + segment.offset, start + segment.offset + segment.length), segment.address);
                }
            }
            command.bytes += length;
            this.write_prdbc(command);
        }
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        // the PRDT doesn't hold the transfer
        dbg_log("AHCI port " + this.number + ": " + error.message, LOG_DISK);
        this.set_status(IS_OFS);
        device.data_pointer = device.data_end = device.data_length = 0;
        device.current_command = -1;
        device.error_reg = ATA_ER_ABRT;
        device.status_reg = ATA_SR_DRDY | ATA_SR_ERR;
        this.advance_again = true;
        return;
    }

    device.data_pointer = end;
    this.call_device(() => to_device ? device.write_end() : device.read_end());

    if(pio)
    {
        // The PIO setup FIS of the block: its interrupt bit is set for data
        // from the device, and for data to it after the first block; never
        // for the command packet of an ATAPI command (QEMU's rule, which
        // SeaBIOS depends on: it takes the status from this FIS)
        const interrupt = !to_device || !command.first_drq;
        this.post_pio_setup(status_before, device.status_reg, length, !to_device, interrupt);
    }
    command.first_drq = false;
    this.advance_again = true;
};

/** The command is done (the device is neither busy nor has data): D2H FIS and status */
AHCIPort.prototype.complete_command = function()
{
    const command = this.command;
    const device = this.device;
    if(!command)
    {
        return;
    }
    this.command = null;
    this.busy_slot = -1;
    this.dma_status = 0;
    this.write_prdbc(command);

    // with the interrupt bit: DHRS, and TFES when the device reports an error
    this.post_d2h(true);

    if(device.status_reg & ATA_SR_ERR)
    {
        // the slot stays issued and the list stops until software clears ST
        dbg_log("AHCI port " + this.number + " slot " + command.slot + ": error " + h(device.error_reg & 0xFF, 2), LOG_DISK);
        this.halted = true;
    }
    else
    {
        this.ci &= ~(1 << command.slot);
    }
    this.controller.update_irq();
    this.check_commands();
};

/**
 * Clear a slot that completed without a D2H FIS
 * @param {number} slot
 */
AHCIPort.prototype.complete_slot = function(slot)
{
    this.ci &= ~(1 << slot);
};

/** The HBA could not read or write a command structure */
AHCIPort.prototype.host_bus_error = function()
{
    dbg_log("AHCI port " + this.number + ": host bus fatal error", LOG_DISK);
    this.abort_command();
    this.set_status(IS_HBFS);
    this.halted = true;
    this.controller.update_irq();
};

/**
 * The guest memory of bytes [offset, offset + length) of the command's
 * PRDT. Throws a RangeError when the PRDT is shorter or not in RAM.
 * @param {!Object} command
 * @param {number} offset
 * @param {number} length
 * @return {!Array<{address: number, offset: number, length: number}>}
 */
AHCIPort.prototype.prdt_segments = function(command, offset, length)
{
    const cpu = this.cpu;
    const segments = [];
    let position = 0;
    const end = offset + length;

    for(let i = 0; i < command.prdtl && position < end; i++)
    {
        const entry = command.table + 0x80 + i * 16;
        cpu.validate_physical_range(entry, 16);
        const bytes = cpu.read_blob_physical(entry, 16);
        // DBA: word aligned (bit 0 reserved); DBAU only with 64-bit addressing
        let address = (bytes[0] & ~1 | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) >>> 0;
        if(this.controller.s64a)
        {
            address += (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) * 0x100000000;
        }
        const count = ((bytes[12] | bytes[13] << 8 | bytes[14] << 16) & 0x3FFFFF) + 1;

        const from = Math.max(position, offset);
        const to = Math.min(position + count, end);
        if(from < to)
        {
            const part = to - from;
            const at = address + (from - position);
            cpu.validate_physical_range(at, part);
            segments.push({ address: at, offset: from - offset, length: part });
        }
        position += count;
    }

    if(position < end)
    {
        throw new RangeError("AHCI PRDT ends before the transfer (" + position + " < " + end + ")");
    }
    return segments;
};

/**
 * IDEInterface: the memory of a DMA transfer of the current command
 * @param {number} byte_count
 * @return {!Array<{address: number, offset: number, length: number}>}
 */
AHCIPort.prototype.dma_segments = function(byte_count)
{
    const command = this.command;
    if(!command)
    {
        throw new RangeError("AHCI: DMA without a command");
    }
    const segments = this.prdt_segments(command, 0, byte_count);
    command.bytes = byte_count;
    return segments;
};

/**
 * PRDBC of the command header: the bytes transferred
 * @param {!Object} command
 */
AHCIPort.prototype.write_prdbc = function(command)
{
    const bytes = command.bytes;
    try
    {
        this.cpu.write_blob_physical(new Uint8Array([bytes & 0xFF, bytes >> 8 & 0xFF, bytes >> 16 & 0xFF, bytes >>> 24]), command.header + 4);
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
    }
};

/** The command list's address (CLB, and CLBU with 64-bit addressing) */
AHCIPort.prototype.list_base = function()
{
    return this.clb + (this.controller.s64a ? this.clbu * 0x100000000 : 0);
};

/** The received FIS area's address (FB, FBU) */
AHCIPort.prototype.fis_base = function()
{
    return this.fb + (this.controller.s64a ? this.fbu * 0x100000000 : 0);
};

/**
 * Write a received FIS (when FIS reception is on)
 * @param {number} offset in the received FIS area
 * @param {!Array<number>} fis
 */
AHCIPort.prototype.post_fis = function(offset, fis)
{
    if(!(this.cmd & CMD_FRE))
    {
        return;
    }
    try
    {
        this.cpu.write_blob_physical(new Uint8Array(fis), this.fis_base() + offset);
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.set_status(IS_HBFS);
    }
};

/**
 * The task file registers in FIS byte order (bytes 4-13)
 * @return {!Array<number>}
 */
AHCIPort.prototype.task_file = function()
{
    const d = this.device;
    return [
        d.lba_low_reg & 0xFF, d.lba_mid_reg & 0xFF, d.lba_high_reg & 0xFF, d.device_reg & 0xF0 | d.head & 0x0F,
        d.lba_low_reg >> 8 & 0xFF, d.lba_mid_reg >> 8 & 0xFF, d.lba_high_reg >> 8 & 0xFF, 0,
        d.sector_count_reg & 0xFF, d.sector_count_reg >> 8 & 0xFF,
    ];
};

/**
 * The device's register FIS: PxTFD follows it; DHRS with the interrupt bit,
 * TFES with an error
 * @param {boolean} interrupt
 */
AHCIPort.prototype.post_d2h = function(interrupt)
{
    const d = this.device;
    const status = d.status_reg & 0xFF;
    const error = d.error_reg & 0xFF;
    this.post_fis(RFIS_D2H, [FIS_REG_D2H, interrupt ? 1 << 6 : 0, status, error,
        ...this.task_file(), 0, 0, 0, 0, 0, 0]);
    this.tfd = error << 8 | status;
    if(interrupt)
    {
        this.set_status(IS_DHRS);
    }
    if(status & ATA_SR_ERR)
    {
        this.set_status(IS_TFES);
    }
};

/**
 * A PIO setup FIS: the status while the block is transferred, the ending
 * status (E_Status) after it, and the transfer count
 * @param {number} status
 * @param {number} end_status
 * @param {number} count
 * @param {boolean} from_device
 * @param {boolean} interrupt
 */
AHCIPort.prototype.post_pio_setup = function(status, end_status, count, from_device, interrupt)
{
    const d = this.device;
    this.post_fis(RFIS_PIO_SETUP, [FIS_PIO_SETUP, (interrupt ? 1 << 6 : 0) | (from_device ? 1 << 5 : 0),
        status & 0xFF, d.error_reg & 0xFF, ...this.task_file(), 0, end_status & 0xFF,
        count & 0xFF, count >> 8 & 0xFF, 0, 0]);
    this.tfd = (d.error_reg & 0xFF) << 8 | end_status & 0xFF;
    if(interrupt)
    {
        this.set_status(IS_PSS);
    }
};

AHCIPort.prototype.get_state = function()
{
    const state = [];
    state[0] = this.clb;
    state[1] = this.clbu;
    state[2] = this.fb;
    state[3] = this.fbu;
    state[4] = this.is;
    state[5] = this.ie;
    state[6] = this.cmd;
    state[7] = this.tfd;
    state[8] = this.sig;
    state[9] = this.ssts;
    state[10] = this.sctl;
    state[11] = this.serr;
    state[12] = this.sact;
    state[13] = this.ci;
    state[14] = this.init_d2h_pending;
    state[15] = this.halted;
    state[16] = this.srst;
    state[17] = this.device;
    const e = this.ncq_error;
    state[18] = e ? [e.tag, e.error, e.lba, e.count] : null;
    // (a snapshot waits for the disk I/O in flight: no command is running)
    dbg_assert(!this.command && !this.ncq_active);
    return state;
};

AHCIPort.prototype.set_state = function(state)
{
    this.clb = state[0];
    this.clbu = state[1];
    this.fb = state[2];
    this.fbu = state[3];
    this.is = state[4];
    this.ie = state[5];
    this.cmd = state[6];
    this.tfd = state[7];
    this.sig = state[8];
    this.ssts = state[9];
    this.sctl = state[10];
    this.serr = state[11];
    this.sact = state[12];
    this.ci = state[13];
    this.init_d2h_pending = state[14];
    this.halted = state[15];
    this.srst = state[16];
    const e = state[18];
    this.ncq_error = e ? { tag: e[0], error: e[1], lba: e[2], count: e[3] } : null;
    this.abort_command();
    if(this.device && state[17])
    {
        this.device.set_state(state[17]);
    }
    else if(this.device)
    {
        // a drive attached after the snapshot was taken: for the restored
        // guest, it was plugged in just now
        const device = this.device;
        this.device = this.master = null;
        this.attach_device(device);
    }
    else if(state[17])
    {
        // the snapshot's port had a drive this machine does not have (one
        // that was hot plugged): for the restored guest, it was removed
        dbg_log("AHCI port " + this.number + ": the snapshot has a drive here, this machine does not", LOG_DISK);
        this.serr = (this.serr | SERR_DIAG_N) >>> 0;
        this.link_reset();
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/android/assemble.js                                                                  0000644 0000000 0000000 00000041364 00000000000 014234  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Android image packages made into a disk (docs/android-images-plan.md I3):
// what a package is, the disk it gives (the device model's partitions, super
// shrunk to its partitions, userdata blank of the chosen size) and the disk
// written as the zip's members inflate, through write(offset, bytes) (an
// OPFS file's sync handle in a worker, a node file, a disk service's
// session). The images are written as they are: nothing in them changes but
// super's size in its metadata.

import { latin1, u16, u32 } from "./bytes.js";
import { zip_entries, zip_stream, zip_read } from "./zip.js";
import { sparse_decoder } from "./sparse.js";
import { lp_metadata, lp_end, lp_resize, lp_place } from "./lp.js";
import { gpt_layout, gpt_writes, SECTOR } from "./gpt.js";
import { vbmeta_struct, AVB_FLAG_VERIFICATION_DISABLED } from "./avb.js";
import { parse_vendor_boot_image } from "./bootimg.js";
import { lz4_legacy_decompress } from "./lz4.js";
import { cpio_files } from "./cpio.js";
import { CF_ARM64_ONLY_PHONE, RANCHU_DEVICES, device_partitions } from "./devices.js";
import { ext4_writes } from "./ext4.js";

/** super's room after its partitions once shrunk */
export const SUPER_SLACK = 64 << 20;
/** the bytes of super inflated before its metadata is read: its geometry and
 * every copy (liblp: 4 KiB reserved, two geometries, the copies) are near its
 * start, in the sparse image's first chunks */
const SUPER_HEAD = 4 << 20;

/**
 * What a package is, from its members (zip_entries')
 * @param {!Array<!Object>} entries
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @return {!Promise<{kind: string, device: (string|undefined), text: string}|null>}
 *     kind: cuttlefish (a whole device), gsi (a system), emulator (the SDK's)
 */
export async function identify_package(entries, read)
{
    const names = new Set(entries.map(e => e.name));
    if(names.has("fastboot-info.txt") && names.has("super.img") && names.has("vendor_boot.img") && names.has("boot.img"))
    {
        const info = latin1(await zip_read(read, entries.find(e => e.name === "fastboot-info.txt")));
        if(!/^#\s*cuttlefish/m.test(info)) return null;
        // (the kernel's architecture: arm64's Image has "ARMd" at 56)
        const boot = await zip_read(read, entries.find(e => e.name === "boot.img"), 4096 + 64);
        const arm64 = latin1(boot, 4096 + 56, 4096 + 60) === "ARMd";
        return arm64 ? { kind: "cuttlefish", device: CF_ARM64_ONLY_PHONE.id, text: "a Cuttlefish arm64 device (its images zip)" } :
            { kind: "unsupported", device: undefined, text: "a Cuttlefish device, not arm64" };
    }
    if(names.has("system.img") && !names.has("vendor_boot.img") && !names.has("super.img"))
    {
        return { kind: "gsi", device: undefined, text: "a Generic System Image (a system for a device's vendor: docs/android-images-plan.md I5)" };
    }
    if([...names].some(n => /(^|\/)kernel-ranchu(-64)?$/.test(n)))
    {
        return { kind: "emulator", device: undefined, text: "an Android Emulator system image (the ranchu board: docs/android-images-plan.md I6)" };
    }
    return null;
}

/**
 * key=value lines as a Map
 * @param {string} text
 * @return {!Map<string, string>}
 */
function properties(text)
{
    const map = new Map();
    for(const line of text.split("\n"))
    {
        const m = /^([^#=\s][^=]*)=(.*)$/.exec(line.trim());
        if(m) map.set(m[1], m[2]);
    }
    return map;
}

/**
 * A version as sdk_full ("36.1") in numbers to compare
 * @param {string|undefined} text
 * @return {number}
 */
function sdk_full(text)
{
    const m = /^(\d+)(?:\.(\d+))?$/.exec(text || "");
    return m ? +m[1] * 1000 + +(m[2] || 0) : NaN;
}

/**
 * A Generic System Image's zip: its system.img (raw ext4 or erofs, or
 * sparse), vbmeta.img (which must disable verification) and build.prop's
 * version and ABIs (docs/android-images-plan.md I5)
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Array<!Object>} entries
 */
export async function gsi_package(read, entries)
{
    const member = name => entries.find(e => e.name === name) || (() => { throw new Error("the GSI has no " + name); })();
    const system = member("system.img"), vbmeta = await zip_read(read, member("vbmeta.img"));
    if(!(vbmeta_struct(vbmeta).flags & AVB_FLAG_VERIFICATION_DISABLED)) throw new Error("the GSI's vbmeta.img does not disable verification");
    const head = await zip_read(read, system, 1082);
    const sparse = u32(head, 0) === 0xED26FF3A;
    if(!sparse && u16(head, 1080) !== 0xEF53 && u32(head, 1024) !== 0xE0F5E1E2) throw new Error("the GSI's system.img is not ext4, erofs or a sparse image");
    let size = system.size;
    if(sparse)
    {
        const h = await zip_read(read, system, 28);
        size = u32(h, 12) * u32(h, 16);
    }
    if(size % SECTOR) throw new Error("the GSI's system.img is not whole sectors");
    const prop = entries.find(e => e.name === "build.prop");
    const props = prop ? properties(latin1(await zip_read(read, prop))) : new Map();
    return { system, sparse, size, vbmeta, props,
        sdk_full: props.get("ro.system.build.version.sdk_full") || props.get("ro.build.version.sdk_full") || "",
        release: props.get("ro.system.build.version.release") || props.get("ro.build.version.release") || "",
        fingerprint: props.get("ro.system.build.fingerprint") || props.get("ro.build.fingerprint") || "",
        abilist32: props.get("ro.system.product.cpu.abilist32") || props.get("ro.product.cpu.abilist32") || "" };
}

/**
 * The disk a Cuttlefish images zip gives: the device's partitions in order,
 * each image as it is, super shrunk (its metadata's block device size) and
 * userdata blank (formatted at first boot). With a GSI (gsi_package's, and
 * the reads of its zip): its system.img as system_a in free space in super
 * (the old system_a's data not written), its vbmeta.img as vbmeta_a and
 * vbmeta_b (nothing verified, as flashing a GSI needs); refused when it is
 * older than the device's vendor (I0.2: init's SELinux policy does not compile)
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Array<!Object>} entries
 * @param {{userdata_bytes: number, gsi: (Object|undefined), gsi_read: (Function|undefined)}} options
 * @return {!Promise<{device: !Object, partitions: !Array<{name: string, start: number, size: number, member: (Object|undefined), blank: (boolean|undefined)}>,
 *     disk_size: number, super_head: !Uint8Array, super_writes: !Array<{offset: number, bytes: !Uint8Array}>, super_size: number, data_bytes: number,
 *     vendor_sdk_full: string, gsi: Object}>}
 *     data_bytes: what is written (no blank space), for progress; vendor_sdk_full: the vendor's version ("" unknown)
 */
export async function cuttlefish_disk(read, entries, options)
{
    const device = CF_ARM64_ONLY_PHONE;
    const member = name =>
    {
        const e = entries.find(e => e.name === name);
        if(!e) throw new Error(`the package has no ${name}`);
        return e;
    };
    // super's metadata, from the start of its sparse image as it inflates
    const head = new Uint8Array(SUPER_HEAD);
    const decoder = sparse_decoder((at, bytes) =>
    {
        if(at < SUPER_HEAD) head.set(bytes.subarray(0, Math.min(bytes.length, SUPER_HEAD - at)), at);
    });
    let pushed = 0;
    await zip_stream(read, member("super.img"), bytes => { decoder.push(bytes); pushed += bytes.length; }, { limit: SUPER_HEAD + (1 << 20) });
    if(decoder.size() < 0) throw new Error("super.img is not a sparse image");
    const lp = lp_metadata((offset, length) =>
    {
        if(offset + length > SUPER_HEAD) throw new Error("super's metadata is beyond its first " + SUPER_HEAD + " bytes");
        return head.subarray(offset, offset + length);
    });
    // (the vendor's version: vendor_boot's ramdisk's prop.default, "" when it has none)
    let vendor_sdk_full = "";
    try
    {
        const vendor_boot = parse_vendor_boot_image(await zip_read(read, member("vendor_boot.img")));
        const prop_default = cpio_files(lz4_legacy_decompress(vendor_boot.ramdisk)).get("prop.default");
        if(prop_default) vendor_sdk_full = properties(latin1(prop_default)).get("ro.vendor.build.version.sdk_full") || "";
    }
    catch(e)
    {
        vendor_sdk_full = "";
    }
    const gsi = options.gsi;
    let skip = null, gsi_at = 0;
    if(gsi)
    {
        // (checked when both say their version)
        if(sdk_full(gsi.sdk_full) < sdk_full(vendor_sdk_full))
        {
            throw new Error(`the GSI (Android ${gsi.release}, sdk_full ${gsi.sdk_full || "?"}) is older than the device's vendor (sdk_full ${vendor_sdk_full || "?"}): ` +
                "it does not boot (init's SELinux policy does not compile); choose a GSI of the same release or newer");
        }
        const old = lp.copies[0].partitions.find(p => p.name === "system_a");
        if(!old) throw new Error("super has no system_a");
        skip = old.extents.map(e => [e.sector * SECTOR, (e.sector + e.sectors) * SECTOR]);
        const align = lp.alignment / SECTOR, sector = Math.ceil(lp_end(lp) / align) * align;
        lp_place(lp, "system_a", sector, gsi.size / SECTOR);
        gsi_at = sector * SECTOR;
    }
    lp_resize(lp, lp_end(lp) * SECTOR + SUPER_SLACK);
    const super_writes = lp.copies.map(c => ({ offset: c.offset, bytes: c.bytes }));
    const list = device_partitions(device).map(({ name, base, blank }) =>
    {
        if(blank) return { name, size: blank, blank: true };
        if(base === "super") return { name, size: lp.size, member: member("super.img"), sparse: true, skip };
        if(base === "userdata") return { name, size: options.userdata_bytes, blank: true };
        if(base === "vbmeta" && gsi) return { name, size: gsi.vbmeta.length, bytes: gsi.vbmeta };
        const m = member(base + ".img");
        return { name, size: m.size, member: m };
    });
    const { partitions, disk_size } = gpt_layout(list);
    const data_bytes = partitions.reduce((n, p) => n + (p.member ? p.member.size : 0), 0) + (gsi ? gsi.system.size : 0);
    return { device, partitions, disk_size, super_head: head, super_writes, super_size: lp.size, data_bytes, vendor_sdk_full,
        gsi: gsi ? { read: options.gsi_read, system: gsi.system, sparse: gsi.sparse, at: gsi_at } : null };
}

/**
 * The disk written: the GPT, each partition's image (super's sparse image
 * as it inflates, its writes past its shrunk size left out: zeros), super's
 * new metadata. Blank space is not written (a new file reads as zeros).
 * progress(done, total) in data bytes
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Object} disk cuttlefish_disk's
 * @param {function(number, !Uint8Array): (Promise|undefined)} write
 * @param {function(number, number)=} progress
 */
export async function write_disk(read, disk, write, progress = () => {})
{
    for(const w of gpt_writes(disk.disk_size, disk.partitions)) await write(w.offset, w.bytes);
    let done = 0;
    for(const p of disk.partitions)
    {
        if(p.bytes) { await write(p.start, p.bytes); continue; }
        // (a filesystem made here: its metadata's writes)
        if(p.writes) { for(const w of p.writes) await write(p.start + w.offset, w.bytes); continue; }
        if(!p.member) continue;
        if(!p.sparse)
        {
            let at = p.start;
            await zip_stream(read, p.member, async bytes => { await write(at, bytes); at += bytes.length; done += bytes.length; progress(done, disk.data_bytes); });
            continue;
        }
        // (a sparse image: its writes collected as a piece inflates, then written)
        let pending = [];
        const keep = (at, bytes) =>
        {
            const n = Math.max(0, Math.min(bytes.length, p.size - at));
            if(n < bytes.length && bytes.subarray(n).some(b => b)) throw new Error(`${p.member.name}: data at ${at + n}, past its partition's ${p.size} bytes`);
            if(n) pending.push([p.start + at, bytes.slice(0, n)]);
        };
        const decoder = sparse_decoder((at, bytes) =>
        {
            // (the replaced system_a's data left out: a piece cut at its edges)
            let pieces = [[at, bytes]];
            for(const [from, to] of p.skip || [])
            {
                pieces = pieces.flatMap(([a, b]) => a >= to || a + b.length <= from ? [[a, b]] :
                    [[a, b.subarray(0, Math.max(0, from - a))], [to, b.subarray(Math.min(b.length, to - a))]].filter(([, x]) => x.length));
            }
            for(const [a, b] of pieces) keep(a, b);
        });
        await zip_stream(read, p.member, async bytes =>
        {
            decoder.push(bytes);
            for(const [offset, data] of pending) await write(offset, data);
            pending = [];
            done += bytes.length;
            progress(done, disk.data_bytes);
        });
        decoder.end();
        if(p.name !== "super") continue;
        for(const w of disk.super_writes) await write(p.start + w.offset, w.bytes);
        // the GSI's system.img at its extent, raw or sparse
        const g = disk.gsi;
        if(!g) continue;
        if(g.sparse)
        {
            let queue = [];
            const system = sparse_decoder((at, bytes) => { queue.push([p.start + g.at + at, bytes.slice()]); });
            await zip_stream(g.read, g.system, async bytes =>
            {
                system.push(bytes);
                for(const [offset, data] of queue) await write(offset, data);
                queue = [];
                done += bytes.length;
                progress(done, disk.data_bytes);
            });
            system.end();
        }
        else
        {
            let at = p.start + g.at;
            await zip_stream(g.read, g.system, async bytes => { await write(at, bytes); at += bytes.length; done += bytes.length; progress(done, disk.data_bytes); });
        }
    }
}

/**
 * The disk an Android Emulator system image zip (the SDK's
 * system-images/android-<api>/<tag>/<abi> package) gives
 * (docs/android-images-plan.md I6): the device model of its API level and
 * ABI (source.properties), its partitions in order, each image as it is
 * (system.img raw or sparse), an empty ext4 where the emulator makes one
 * (only its metadata written: the rest of a new disk reads as zeros)
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Array<!Object>} entries
 * @return {!Promise<{device: !Object, partitions: !Array<Object>, disk_size: number, data_bytes: number,
 *     api: number, abi: string, tag: string, release: string}>}
 */
export async function emulator_disk(read, entries)
{
    const source = entries.find(e => /(^|\/)source\.properties$/.test(e.name));
    if(!source) throw new Error("the emulator image has no source.properties");
    const directory = source.name.slice(0, source.name.length - "source.properties".length);
    const member = name => entries.find(e => e.name === directory + name) || (() => { throw new Error("the emulator image has no " + name); })();
    const props = properties(latin1(await zip_read(read, source)));
    const api = +(props.get("AndroidVersion.ApiLevel") || NaN), abi = props.get("SystemImage.Abi") || "";
    const device = RANCHU_DEVICES.find(d => d.api === api && d.abi === abi);
    if(!device)
    {
        throw new Error(`an emulator image of API ${api} for ${abi || "an unknown ABI"}: v64 boots ` +
            RANCHU_DEVICES.map(d => `API ${d.api} ${d.abi}`).join(", "));
    }
    const build = entries.find(e => e.name === directory + "build.prop");
    const release = build ? properties(latin1(await zip_read(read, build))).get("ro.build.version.release") || "" : "";
    const list = [];
    for(const p of device.partitions)
    {
        if(p.ext4)
        {
            // (only the file system's metadata written: zeros elsewhere)
            list.push({ name: p.name, size: p.ext4, writes: ext4_writes(p.ext4, p.name, 0) });
            continue;
        }
        const m = member(p.member);
        const head = await zip_read(read, m, 28);
        if(u32(head, 0) === 0xED26FF3A) list.push({ name: p.name, size: u32(head, 12) * u32(head, 16), member: m, sparse: true });
        else list.push({ name: p.name, size: m.size, member: m });
    }
    const { partitions, disk_size } = gpt_layout(list);
    const data_bytes = partitions.reduce((n, p) => n + (p.member ? p.member.size : 0), 0);
    return { device, partitions, disk_size, data_bytes, api, abi, tag: props.get("SystemImage.TagId") || "", release };
}

/**
 * A package's members from a file (a File, or bytes) by its size:
 * zip_entries over read
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {number} size
 */
export async function package_entries(read, size)
{
    const head = await read(0, 4);
    if(head.length < 4 || u32(head, 0) !== 0x04034B50) throw new Error("not a zip archive (an Android image package is a .zip)");
    return zip_entries(read, size);
}
                                                                                                                                                                                                                                                                            source/v64/src/android/avb.js                                                                       0000644 0000000 0000000 00000014111 00000000000 013177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Android Verified Boot (external/avb/libavb): vbmeta structs and their
// descriptors, the digest a bootloader passes to the kernel, and dm-verity
// hash trees (docs/android-images-plan.md I1). Big-endian structures.

import { u32be, u64be, put32be, put64be, latin1, c_string, concat, sha256, sha256_hex } from "./bytes.js";

const AVB_HEADER_SIZE = 256;
/** vbmeta's flags: hash trees off, verification off (avbtool --disable-verity, --disable-verification) */
export const AVB_FLAG_HASHTREE_DISABLED = 1;
export const AVB_FLAG_VERIFICATION_DISABLED = 2;

/**
 * A vbmeta struct (header, authentication and auxiliary blocks) at offset
 * @param {!Uint8Array} bytes
 * @param {number=} offset
 * @return {{struct: !Uint8Array, descriptors: !Array<{tag: number, partition: (string|undefined)}>, flags: number}}
 */
export function vbmeta_struct(bytes, offset = 0)
{
    if(latin1(bytes, offset, offset + 4) !== "AVB0") throw new Error("no vbmeta");
    const auth = u64be(bytes, offset + 12), aux = u64be(bytes, offset + 20);
    const struct = bytes.subarray(offset, offset + AVB_HEADER_SIZE + auth + aux);
    const descriptors = [];
    const start = AVB_HEADER_SIZE + auth + u64be(struct, 96), end = start + u64be(struct, 104);
    for(let at = start; at < end;)
    {
        const tag = u64be(struct, at), following = u64be(struct, at + 8);
        if(tag === 4)
        {
            // chain partition: rollback_index_location, partition_name_len, public_key_len, flags, reserved[60]
            const name_length = u32be(struct, at + 20);
            descriptors.push({ tag, partition: latin1(struct, at + 92, at + 92 + name_length) });
        }
        else if(tag === 1 || tag === 2)
        {
            // hashtree (1) / hash (2): the partition name follows the fixed part
            const fixed = tag === 1 ? 180 : 132, name_length = u32be(struct, at + (tag === 1 ? 104 : 56));
            descriptors.push({ tag, partition: latin1(struct, at + fixed, at + fixed + name_length) });
        }
        else descriptors.push({ tag });
        at += 16 + following;
    }
    return { struct, descriptors, flags: u32be(struct, 120) };
}

/**
 * A partition image's vbmeta: through its footer, else at its start
 * @param {!Uint8Array} bytes
 */
export function partition_vbmeta(bytes)
{
    const footer = bytes.length - 64;
    if(footer >= 0 && latin1(bytes, footer, footer + 4) === "AVBf")
    {
        return vbmeta_struct(bytes, u64be(bytes, footer + 20));
    }
    return vbmeta_struct(bytes);
}

/**
 * The digest a bootloader passes as androidboot.vbmeta.digest: sha256 of
 * the vbmeta structs in libavb's load order (depth first). With
 * verification disabled in vbmeta's flags libavb loads vbmeta alone.
 * @param {function(string): !Uint8Array} read_partition
 * @return {{digest: string, size: number, chained: !Array<string>}}
 */
export function vbmeta_digest(read_partition)
{
    const structs = [];
    const root = vbmeta_struct(read_partition("vbmeta"));
    const verify = !(root.flags & AVB_FLAG_VERIFICATION_DISABLED);
    const visit = vbmeta =>
    {
        structs.push(vbmeta.struct);
        if(!verify) return;
        for(const d of vbmeta.descriptors)
        {
            if(d.tag === 4) visit(partition_vbmeta(read_partition(/** @type {string} */ (d.partition))));
        }
    };
    visit(root);
    const all = concat(structs);
    return { digest: sha256_hex(all), size: all.length,
        chained: verify ? root.descriptors.filter(d => d.tag === 4).map(d => /** @type {string} */ (d.partition)) : [] };
}

/**
 * A hashtree descriptor's fields in a vbmeta struct (offsets into bytes)
 * @param {!Uint8Array} bytes
 * @param {string} partition
 */
export function hashtree_descriptor(bytes, partition)
{
    const auth = u64be(bytes, 12);
    const start = AVB_HEADER_SIZE + auth + u64be(bytes, 96), end = start + u64be(bytes, 104);
    for(let at = start; at < end; at += 16 + u64be(bytes, at + 8))
    {
        if(u64be(bytes, at) !== 1) continue;
        const name_length = u32be(bytes, at + 104), salt_length = u32be(bytes, at + 108);
        if(latin1(bytes, at + 180, at + 180 + name_length) !== partition) continue;
        const salt = at + 180 + name_length;
        return { at, image_size: u64be(bytes, at + 20), data_block: u32be(bytes, at + 44),
            hash_block: u32be(bytes, at + 48), algorithm: c_string(bytes, at + 72, 32),
            salt: bytes.subarray(salt, salt + salt_length), digest: salt + salt_length, digest_length: u32be(bytes, at + 112) };
    }
    throw new Error("vbmeta: no hashtree descriptor for " + partition);
}

/**
 * dm-verity's hash tree of image as avbtool makes it (the top level first)
 * and its root digest
 * @param {!Uint8Array} image
 * @param {!Uint8Array} salt
 * @param {number=} block
 * @return {{root: !Uint8Array, tree: !Uint8Array}}
 */
export function avb_hashtree(image, salt, block = 4096)
{
    const levels = [];
    let level = image;
    while(level.length > block)
    {
        const count = Math.ceil(level.length / block);
        const next = new Uint8Array(Math.ceil(count * 32 / block) * block);
        const data = new Uint8Array(block);
        for(let i = 0; i < count; i++)
        {
            data.fill(0);
            data.set(level.subarray(i * block, Math.min(level.length, (i + 1) * block)));
            next.set(sha256(salt, data), i * 32);
        }
        levels.unshift(next);
        level = next;
    }
    return { root: sha256(salt, level), tree: concat(levels) };
}

/**
 * A hashtree descriptor (in vbmeta bytes, changed in place) set to image's
 * size and a tree's size and root digest, without FEC
 * @param {!Uint8Array} bytes
 * @param {!Object} descriptor hashtree_descriptor's
 * @param {number} image_size
 * @param {number} tree_size
 * @param {!Uint8Array} root
 */
export function set_hashtree(bytes, descriptor, image_size, tree_size, root)
{
    const d = descriptor.at;
    put64be(bytes, d + 20, image_size);
    put64be(bytes, d + 28, image_size);
    put64be(bytes, d + 36, tree_size);
    // (no FEC)
    put32be(bytes, d + 52, 0);
    put64be(bytes, d + 56, 0);
    put64be(bytes, d + 64, 0);
    bytes.set(root, descriptor.digest);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/android/boot.js                                                                      0000644 0000000 0000000 00000004565 00000000000 013406  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What an Android device's bootloader hands the kernel
// (docs/android-images-plan.md I2): the kernel of boot, the vendor ramdisk,
// init_boot's generic ramdisk and bootconfig (the vendor_boot's own and the
// device model's) as the initrd, and the kernel command line. The same for
// tools/a64_android.mjs and for v64's bootloader reading the disk.

import { concat } from "./bytes.js";
import { parse_boot_image, parse_vendor_boot_image } from "./bootimg.js";
import { parse_bootconfig, append_bootconfig } from "./bootconfig.js";
import { vbmeta_digest } from "./avb.js";
import { device_bootconfig } from "./devices.js";

/**
 * @param {function(string): !Uint8Array} read_partition a partition by
 *     its name without the slot (boot, vbmeta, vbmeta_system, ...), the
 *     device's slot's
 * @param {!Object} device devices.js's
 * @param {{memory_mb: number, selinux: (string|undefined), page_size: (number|undefined), gpu_mode: (string|undefined),
 *     vendor_ramdisk: (Uint8Array|undefined), extra_ramdisk: (Uint8Array|undefined)}} options
 *     vendor_ramdisk: in place of the vendor_boot's (Cuttlefish's debug
 *     one); extra_ramdisk: after it (the 16K modules)
 * @return {{kernel: !Uint8Array, initrd: !Uint8Array, cmdline: string, bootconfig: !Map<string, string>,
 *     vbmeta: {digest: string, size: number, chained: !Array<string>}, boot: !Object, vendor_boot: !Object}}
 */
export function android_boot(read_partition, device, options)
{
    const boot = parse_boot_image(read_partition("boot"));
    const init_boot = parse_boot_image(read_partition("init_boot"));
    const vendor_boot = parse_vendor_boot_image(read_partition("vendor_boot"));
    const vbmeta = vbmeta_digest(read_partition);
    const bootconfig = parse_bootconfig(vendor_boot.bootconfig);
    const launcher = device_bootconfig(device, { vbmeta, memory_mb: options.memory_mb, selinux: options.selinux, page_size: options.page_size,
        gpu_mode: options.gpu_mode });
    for(const [key, value] of launcher) bootconfig.set(key, value);
    const ramdisk = concat([options.vendor_ramdisk || vendor_boot.ramdisk, options.extra_ramdisk || new Uint8Array(0), init_boot.ramdisk]);
    const cmdline = [vendor_boot.cmdline, boot.cmdline, device.cmdline_tail].filter(Boolean).join(" ");
    return { kernel: boot.kernel, initrd: append_bootconfig(ramdisk, bootconfig), cmdline, bootconfig, vbmeta, boot, vendor_boot };
}
                                                                                                                                           source/v64/src/android/bootconfig.js                                                                0000644 0000000 0000000 00000002501 00000000000 014560  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // bootconfig (Documentation/admin-guide/bootconfig.rst) as Android's
// bootloaders append it to the initrd (docs/android-images-plan.md I1)

import { put32, bytes_of, utf8, concat } from "./bytes.js";

/**
 * key=value lines (bootconfig as the vendor_boot carries it) as a Map
 * @param {string} text
 * @return {!Map<string, string>}
 */
export function parse_bootconfig(text)
{
    const map = new Map();
    for(const line of text.split("\n"))
    {
        const m = /^\s*([^#=\s][^=\s]*)\s*=\s*(.*?)\s*$/.exec(line);
        if(m) map.set(m[1], m[2].replace(/^"(.*)"$/, "$1"));
    }
    return map;
}

/**
 * bootconfig appended to an initrd: the text, padded so the whole stays
 * 4-aligned, its size and checksum (the sum of its bytes), "#BOOTCONFIG\n"
 * @param {!Uint8Array} initrd
 * @param {!Map<string, string>} map
 * @return {!Uint8Array}
 */
export function append_bootconfig(initrd, map)
{
    const text = utf8([...map].map(([key, value]) => `${key} = "${value}"\n`).join("") + "\0");
    const pad = (4 - (initrd.length + text.length + 8 + 12) % 4) % 4;
    const data = concat([text, new Uint8Array(pad)]);
    const footer = new Uint8Array(8);
    put32(footer, 0, data.length);
    put32(footer, 4, data.reduce((sum, byte) => sum + byte, 0) >>> 0);
    return concat([initrd, data, footer, bytes_of("#BOOTCONFIG\n")]);
}
                                                                                                                                                                                               source/v64/src/android/bootimg.js                                                                   0000644 0000000 0000000 00000005412 00000000000 014073  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Android boot images (system/tools/mkbootimg's boot_image.h): boot.img and
// init_boot.img (header version 3 or 4) and vendor_boot.img (version 4), as
// a bootloader reads them (docs/android-images-plan.md I1, I2).

import { u32, latin1, c_string } from "./bytes.js";

/**
 * boot.img and init_boot.img, header version 3 or 4: kernel and ramdisk
 * (pages of 4096)
 * @param {!Uint8Array} bytes
 * @return {{version: number, kernel: !Uint8Array, ramdisk: !Uint8Array, os_version: number, cmdline: string}}
 */
export function parse_boot_image(bytes)
{
    if(latin1(bytes, 0, 8) !== "ANDROID!") throw new Error("not a boot image");
    const version = u32(bytes, 40);
    if(version < 3) throw new Error("boot image header version " + version);
    const kernel_size = u32(bytes, 8), ramdisk_size = u32(bytes, 12);
    const page = 4096, align = x => Math.ceil(x / page) * page;
    const kernel = bytes.subarray(page, page + kernel_size);
    const ramdisk_offset = page + align(kernel_size);
    return { version, kernel, ramdisk: bytes.subarray(ramdisk_offset, ramdisk_offset + ramdisk_size),
        os_version: u32(bytes, 16), cmdline: c_string(bytes, 44, 1536) };
}

/**
 * vendor_boot.img, header version 4: vendor ramdisks, cmdline, bootconfig
 * @param {!Uint8Array} bytes
 * @return {{cmdline: string, ramdisks: !Array<{type: number, name: string, bytes: !Uint8Array}>, ramdisk: !Uint8Array, bootconfig: string}}
 */
export function parse_vendor_boot_image(bytes)
{
    if(latin1(bytes, 0, 8) !== "VNDRBOOT") throw new Error("not a vendor boot image");
    const version = u32(bytes, 8);
    if(version !== 4) throw new Error("vendor boot image header version " + version);
    const page = u32(bytes, 12), align = x => Math.ceil(x / page) * page;
    const header_size = u32(bytes, 2096), ramdisk_size = u32(bytes, 24), dtb_size = u32(bytes, 2100);
    const table_size = u32(bytes, 2112), table_entries = u32(bytes, 2116), entry_size = u32(bytes, 2120);
    const bootconfig_size = u32(bytes, 2124);
    const ramdisk_offset = align(header_size);
    const table_offset = ramdisk_offset + align(ramdisk_size) + align(dtb_size);
    const bootconfig_offset = table_offset + align(table_size);
    const ramdisks = [];
    for(let i = 0; i < table_entries; i++)
    {
        const entry = table_offset + i * entry_size;
        const size = u32(bytes, entry), offset = u32(bytes, entry + 4);
        ramdisks.push({ type: u32(bytes, entry + 8), name: c_string(bytes, entry + 12, 32),
            bytes: bytes.subarray(ramdisk_offset + offset, ramdisk_offset + offset + size) });
    }
    return { cmdline: c_string(bytes, 28, 2048), ramdisks, ramdisk: bytes.subarray(ramdisk_offset, ramdisk_offset + ramdisk_size),
        bootconfig: latin1(bytes, bootconfig_offset, bootconfig_offset + bootconfig_size) };
}
                                                                                                                                                                                                                                                      source/v64/src/android/bootloader.js                                                                0000644 0000000 0000000 00000012416 00000000000 014567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // v64's Android bootloader (docs/android-images-plan.md I2): from the
// first disk's GPT, the slot's boot, init_boot, vendor_boot and vbmeta
// partitions (and those vbmeta chains), what the device's bootloader hands
// the kernel (boot.js): the kernel, the initrd with bootconfig, the command
// line. An emulator image's device (the ranchu machine's, I6): its kernel
// and ramdisk partitions as they are, the emulator's command line, and the
// partitions that are the emulator's disks. The disk is read through
// read(offset, length), a promise of the bytes (a disk buffer's get).

import { gpt_partitions } from "./gpt.js";
import { vbmeta_struct, AVB_FLAG_VERIFICATION_DISABLED } from "./avb.js";
import { android_boot } from "./boot.js";
import { CF_ARM64_ONLY_PHONE, RANCHU_DEVICES, ranchu_gpu_mode } from "./devices.js";
import { ranchu_cmdline } from "../virt/ranchu.js";
import { ramdisk_overlay } from "./ramdisk_overlay.js";

/** the device models by id (the VM config's android.device) */
export const ANDROID_DEVICES = Object.fromEntries([CF_ARM64_ONLY_PHONE, ...RANCHU_DEVICES].map(d => [d.id, d]));

/**
 * @param {function(number, number): !Promise<!Uint8Array>} read
 * @param {number} disk_size
 * @param {{device: (string|undefined), gpu_mode: (string|undefined), selinux: (string|undefined), memory_mb: number,
 *     vendor_ramdisk: (Uint8Array|undefined)}} options vendor_ramdisk: in
 *     place of the vendor_boot's (Cuttlefish's debug one)
 * @return {!Promise<{kernel: !Uint8Array, initrd: !Uint8Array, cmdline: string, bootconfig: ?Map<string, string>, vbmeta: ?Object,
 *     disks: (!Array<{name: string, start: number, size: number, readonly: boolean}>|undefined), ranchu_gpu: (string|undefined)}>}
 *     disks: (an emulator image's) the partitions that are the machine's virtio disks, in order;
 *     ranchu_gpu: (an emulator image's) its GPU mode's ranchu_gpu
 */
export async function android_bootloader(read, disk_size, options)
{
    const device = ANDROID_DEVICES[options.device || CF_ARM64_ONLY_PHONE.id];
    if(!device) throw new Error("android: no device model " + options.device);
    // the GPT: both ends of the disk read first (the primary's entries
    // follow it, the backup's precede it)
    const span = Math.min(disk_size, 1 << 16);
    const head = await read(0, span), tail = await read(disk_size - span, span);
    const partitions = gpt_partitions((offset, length) =>
    {
        if(offset + length <= head.length) return head.subarray(offset, offset + length);
        if(offset >= disk_size - span) return tail.subarray(offset - (disk_size - span), offset - (disk_size - span) + length);
        throw new Error("android: the GPT's entries are not at an end of the disk");
    }, disk_size);
    const by_name = new Map(partitions.map(p => [p.name, p]));
    if(device.machine === "ranchu")
    {
        const part = name =>
        {
            const p = by_name.get(name);
            if(!p) throw new Error(`android: the disk has no ${name} partition (${partitions.map(p => p.name).join(", ")})`);
            if(p.start + p.size > disk_size) throw new Error(`android: ${p.name} is beyond the disk`);
            return p;
        };
        const load = async name => { const p = part(name); return new Uint8Array(await read(p.start, p.size)); };
        const gpu = ranchu_gpu_mode(device, options.gpu_mode, options.gles_version);
        // (a partition is whole sectors: the kernel's and ramdisk's bytes run to their ends, which the kernel ignores)
        return { kernel: await load("kernel"), initrd: await ramdisk_overlay(await load("ramdisk"), device),
            cmdline: ranchu_cmdline({ arm32: device.cmdline.arm32, bootanim: device.cmdline.bootanim, gles: gpu.gles }),
            bootconfig: null, vbmeta: null,
            properties: Object.assign({}, device.properties, gpu.properties), clock_rate: device.clock_rate || null,
            ranchu_gpu: gpu.ranchu_gpu, gles_version: gpu.gles_version,
            disks: device.partitions.filter(p => p.disk).map(p => ({ name: p.name, start: part(p.name).start, size: part(p.name).size,
                readonly: p.disk === "read_only" })) };
    }
    const loaded = new Map();
    const load = async name =>
    {
        if(loaded.has(name)) return loaded.get(name);
        const p = by_name.get(name + device.slot) || by_name.get(name);
        if(!p) throw new Error(`android: the disk has no ${name}${device.slot} partition (${partitions.map(p => p.name).join(", ")})`);
        if(p.start + p.size > disk_size) throw new Error(`android: ${p.name} is beyond the disk`);
        // (a copy: the disk's buffer may hand out its cache)
        const bytes = new Uint8Array(await read(p.start, p.size));
        loaded.set(name, bytes);
        return bytes;
    };
    for(const name of ["vbmeta", "boot", "init_boot", "vendor_boot"]) await load(name);
    // (the partitions vbmeta chains, which libavb loads unless it disables verification)
    const top = vbmeta_struct(loaded.get("vbmeta"));
    if(!(top.flags & AVB_FLAG_VERIFICATION_DISABLED))
    {
        for(const d of top.descriptors) if(d.tag === 4) await load(/** @type {string} */ (d.partition));
    }
    return android_boot(name =>
    {
        if(!loaded.has(name)) throw new Error("android: " + name + " was not loaded");
        return loaded.get(name);
    }, device, options);
}
                                                                                                                                                                                                                                                  source/v64/src/android/bytes.js                                                                     0000644 0000000 0000000 00000014647 00000000000 013573  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Android image library's byte helpers (docs/android-images-plan.md
// I1): fields, text, checksums and hashes over Uint8Array, so that the same
// code runs in node (tools/a64_android.mjs) and in browsers. Offsets and
// 64-bit fields are numbers (images stay far below 2^53 bytes).

import { SHA256 } from "../image/sha256.js";

/** @param {!Uint8Array} b @param {number} at @return {number} */
export function u16(b, at) { return b[at] | b[at + 1] << 8; }
/** @param {!Uint8Array} b @param {number} at @return {number} */
export function u32(b, at) { return (b[at] | b[at + 1] << 8 | b[at + 2] << 16 | b[at + 3] << 24) >>> 0; }
/** @param {!Uint8Array} b @param {number} at @return {number} */
export function u64(b, at) { return u32(b, at) + u32(b, at + 4) * 0x100000000; }
/** @param {!Uint8Array} b @param {number} at @return {number} */
export function u32be(b, at) { return (b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]) >>> 0; }
/** @param {!Uint8Array} b @param {number} at @return {number} */
export function u64be(b, at) { return u32be(b, at) * 0x100000000 + u32be(b, at + 4); }

/** @param {!Uint8Array} b @param {number} at @param {number} v */
export function put16(b, at, v) { b[at] = v; b[at + 1] = v >>> 8; }
/** @param {!Uint8Array} b @param {number} at @param {number} v */
export function put32(b, at, v) { b[at] = v; b[at + 1] = v >>> 8; b[at + 2] = v >>> 16; b[at + 3] = v >>> 24; }
/** @param {!Uint8Array} b @param {number} at @param {number} v */
export function put64(b, at, v) { put32(b, at, v >>> 0); put32(b, at + 4, Math.floor(v / 0x100000000)); }
/** @param {!Uint8Array} b @param {number} at @param {number} v */
export function put32be(b, at, v) { b[at] = v >>> 24; b[at + 1] = v >>> 16; b[at + 2] = v >>> 8; b[at + 3] = v; }
/** @param {!Uint8Array} b @param {number} at @param {number} v */
export function put64be(b, at, v) { put32be(b, at, Math.floor(v / 0x100000000)); put32be(b, at + 4, v >>> 0); }

/**
 * Bytes as latin1 text (one character per byte)
 * @param {!Uint8Array} b
 * @param {number=} start
 * @param {number=} end
 * @return {string}
 */
export function latin1(b, start = 0, end = b.length)
{
    let text = "";
    for(let at = start; at < end; at += 0x8000)
    {
        text += String.fromCharCode.apply(null, Array.from(b.subarray(at, Math.min(end, at + 0x8000))));
    }
    return text;
}

/**
 * latin1 text as bytes (each character's low byte)
 * @param {string} text
 * @return {!Uint8Array}
 */
export function bytes_of(text)
{
    const out = new Uint8Array(text.length);
    for(let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i);
    return out;
}

/**
 * UTF-8 text as bytes
 * @param {string} text
 * @return {!Uint8Array}
 */
export function utf8(text) { return new TextEncoder().encode(text); }

/**
 * UTF-16LE text as bytes (GPT's names)
 * @param {string} text
 * @return {!Uint8Array}
 */
export function utf16le(text)
{
    const out = new Uint8Array(text.length * 2);
    for(let i = 0; i < text.length; i++) put16(out, 2 * i, text.charCodeAt(i));
    return out;
}

/**
 * A NUL-terminated string of at most length bytes at offset
 * @param {!Uint8Array} b
 * @param {number} at
 * @param {number} length
 * @return {string}
 */
export function c_string(b, at, length)
{
    const field = b.subarray(at, at + length);
    const end = field.indexOf(0);
    return latin1(field, 0, end < 0 ? field.length : end);
}

/**
 * A copy of bytes of its own (b.slice() is a view when b is node's Buffer)
 * @param {!Uint8Array} b
 * @param {number=} start
 * @param {number=} end
 * @return {!Uint8Array}
 */
export function copy(b, start = 0, end = b.length)
{
    return new Uint8Array(b.subarray(start, end));
}

/**
 * @param {!Array<!Uint8Array>} parts
 * @return {!Uint8Array}
 */
export function concat(parts)
{
    const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
    let at = 0;
    for(const p of parts) { out.set(p, at); at += p.length; }
    return out;
}

/** @param {!Uint8Array} a @param {!Uint8Array} b @return {boolean} */
export function equals(a, b)
{
    if(a.length !== b.length) return false;
    for(let i = 0; i < a.length; i++) if(a[i] !== b[i]) return false;
    return true;
}

/**
 * Byte order, as Buffer.compare
 * @param {!Uint8Array} a
 * @param {!Uint8Array} b
 * @return {number}
 */
export function compare(a, b)
{
    const n = Math.min(a.length, b.length);
    for(let i = 0; i < n; i++) if(a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
    return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
}

/**
 * Where needle starts in hay, or -1
 * @param {!Uint8Array} hay
 * @param {!Uint8Array} needle
 * @param {number=} from
 * @return {number}
 */
export function index_of(hay, needle, from = 0)
{
    if(!needle.length) return from;
    for(let i = hay.indexOf(needle[0], from); i >= 0 && i + needle.length <= hay.length; i = hay.indexOf(needle[0], i + 1))
    {
        let j = 1;
        while(j < needle.length && hay[i + j] === needle[j]) j++;
        if(j === needle.length) return i;
    }
    return -1;
}

/** @param {!Uint8Array} b @return {string} */
export function hex(b) { return Array.from(b, x => x.toString(16).padStart(2, "0")).join(""); }

/**
 * @param {...!Uint8Array} parts
 * @return {!Uint8Array}
 */
export function sha256(...parts)
{
    const hash = new SHA256();
    for(const part of parts) hash.update(part);
    return hash.digest();
}

/**
 * @param {...!Uint8Array} parts
 * @return {string}
 */
export function sha256_hex(...parts)
{
    const hash = new SHA256();
    for(const part of parts) hash.update(part);
    return hash.hex();
}

const CRC32 = new Int32Array(256);
const CRC32C = new Int32Array(256);
for(let n = 0; n < 256; n++)
{
    let c = n, k = n;
    for(let i = 0; i < 8; i++)
    {
        c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
        k = k & 1 ? 0x82F63B78 ^ k >>> 1 : k >>> 1;
    }
    CRC32[n] = c;
    CRC32C[n] = k;
}

/**
 * CRC-32 (zlib's)
 * @param {!Uint8Array} bytes
 * @param {number=} crc a running value
 * @return {number}
 */
export function crc32(bytes, crc = 0)
{
    let c = ~crc;
    for(let i = 0; i < bytes.length; i++) c = CRC32[(c ^ bytes[i]) & 0xFF] ^ c >>> 8;
    return ~c >>> 0;
}

/**
 * CRC-32C over bytes from crc as is (erofs's: initial 0xFFFFFFFF, no final
 * inversion)
 * @param {number} crc
 * @param {!Uint8Array} bytes
 * @return {number}
 */
export function crc32c(crc, bytes)
{
    let c = crc;
    for(let i = 0; i < bytes.length; i++) c = CRC32C[(c ^ bytes[i]) & 0xFF] ^ c >>> 8;
    return c >>> 0;
}
                                                                                         source/v64/src/android/cpio.js                                                                      0000644 0000000 0000000 00000003247 00000000000 013371  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // newc cpio archives, Android's ramdisks (docs/android-images-plan.md I1)

import { latin1, bytes_of, concat } from "./bytes.js";

/**
 * The regular files of newc cpio archives
 * @param {!Uint8Array} bytes
 * @return {!Map<string, !Uint8Array>} name -> data
 */
export function cpio_files(bytes)
{
    const files = new Map();
    for(let at = 0; at + 110 <= bytes.length;)
    {
        if(latin1(bytes, at, at + 6) !== "070701") { at += 4; continue; }
        const field = i => parseInt(latin1(bytes, at + 6 + i * 8, at + 14 + i * 8), 16);
        const mode = field(1), size = field(6), name_size = field(11);
        const name = latin1(bytes, at + 110, at + 110 + name_size - 1);
        const data_at = Math.ceil((at + 110 + name_size) / 4) * 4;
        if((mode & 0o170000) === 0o100000) files.set(name, bytes.subarray(data_at, data_at + size));
        at = Math.ceil((data_at + size) / 4) * 4;
    }
    return files;
}

/**
 * A newc cpio archive of regular files [name, data] (mode 0644)
 * @param {!Array<!Array>} files
 * @return {!Uint8Array}
 */
export function cpio_newc(files)
{
    const parts = [];
    let ino = 0x7000;
    const entry = (name, data, mode, nlink) =>
    {
        const fields = [ino++, mode, 0, 0, nlink, 0, data.length, 0, 0, 0, 0, name.length + 1, 0];
        const header = bytes_of("070701" + fields.map(f => f.toString(16).toUpperCase().padStart(8, "0")).join("") + name + "\0");
        parts.push(header, new Uint8Array((4 - header.length % 4) % 4), data, new Uint8Array((4 - data.length % 4) % 4));
    };
    for(const [name, data] of files) entry(name, data, 0o100644, 1);
    entry("TRAILER!!!", new Uint8Array(0), 0, 1);
    return concat(parts);
}
                                                                                                                                                                                                                                                                                                                                                         source/v64/src/android/devices.js                                                                   0000644 0000000 0000000 00000035054 00000000000 014062  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Android device models (docs/android-images-plan.md I2.1): how a build for
// a device boots on the virt machine, as that device's bootloader and
// launcher would boot it: the disk's partitions, the kernel command line's
// tail and what goes into bootconfig.

/**
 * Cuttlefish's arm64-only phone (aosp_cf_arm64_only_phone): what its
 * launcher puts into bootconfig (host/commands/assemble_cvd/
 * bootconfig_args.cpp, QEMU, no host services) and its bootloader (slot,
 * normal boot, verified boot state). The host services Cuttlefish provides
 * through virtio-console ports are replaced by the guest's own: KeyMint and
 * Gatekeeper from the vendor's nonsecure APEXes.
 */
export const CF_ARM64_ONLY_PHONE = {
    id: "cf_arm64_only_phone",
    cpu: "arm64",
    machine: "virt",
    /** its display (Cuttlefish's phone: 720x1280 at androidboot.lcd_density
     * 320); the VM manager gives virtio-gpu this size and zooms the screen
     * to the window, rather than a display the window's size */
    display: { width: 720, height: 1280 },
    /** the virt machine's PCIe host bridge (high ECAM), under which first
     * stage init looks for the partitions */
    boot_devices: "4010000000.pcie",
    /** the disk: Cuttlefish's partition order (host/commands/assemble_cvd/
     * disk_flags.cc); slotted ones twice (_a, _b); blank ones with their
     * size. frp is from Cuttlefish's second, persistent disk:
     * PersistentDataBlockService's, without which system_server dies at
     * boot phase 500 */
    partitions: [
        { name: "misc", blank: 1 << 20 },
        { name: "boot", slots: true },
        { name: "init_boot", slots: true },
        { name: "vendor_boot", slots: true },
        { name: "vbmeta", slots: true },
        { name: "vbmeta_system", slots: true },
        { name: "vbmeta_vendor_dlkm", slots: true },
        { name: "vbmeta_system_dlkm", slots: true },
        { name: "super" },
        { name: "userdata" },
        { name: "metadata", blank: 64 << 20 },
        { name: "frp", blank: 1 << 20 },
    ],
    slot: "_a",
    /** the kernel's console is hvc0 (the first virtio-console port, as
     * Cuttlefish's) after earlycon on the PL011 */
    cmdline_tail: "console=hvc0 earlycon=pl011,mmio32,0x9000000",
    /** the GPU modes' bootconfig: SwiftShader's (gpu_mode guest_swiftshader:
     * VK_API_VERSION_1_2, OpenGL ES 3.1), and what Venus changes (as
     * Cuttlefish's drm_virgl: SurfaceFlinger composes on the GPU, the ranchu
     * HWC only scans out; ANGLE on Venus gives OpenGL ES 3.0) */
    gpu_modes: {
        swiftshader: [
            ["androidboot.cpuvulkan.version", String((1 << 22) | (2 << 12))],
            ["androidboot.hardware.gralloc", "minigbm"],
            ["androidboot.hardware.hwcomposer", "ranchu"],
            ["androidboot.hardware.hwcomposer.display_finder_mode", "drm"],
            ["androidboot.hardware.hwcomposer.display_framebuffer_format", "rgba"],
            ["androidboot.hardware.egl", "angle"],
            ["androidboot.hardware.vulkan", "pastel"],
            ["androidboot.opengles.version", "196609"],
        ],
        venus: [
            ["androidboot.hardware.vulkan", "virtio"],
            ["androidboot.hardware.hwcomposer.mode", "client"],
            ["androidboot.opengles.version", "196608"],
        ],
        // gpu_mode gfxstream_guest_angle as the launcher writes it
        // (host/libs/vm_manager/qemu_manager.cpp; docs/gfxstream-protocol.md):
        // the guest's Vulkan driver gfxstream's (vulkan.ranchu), GLES ANGLE on
        // it, the transport ASG rings in virtio-gpu blobs; for v64's
        // gfxstream device (docs/gfxstream-plan.md G1-G5). Composition as
        // Venus's: SurfaceFlinger on the GPU, the HWC scanning out through
        // KMS (the launcher's HWC composes on the host, renderControl's
        // rcCompose); ANGLE gets OpenGL ES 3.0 of VX
        gfxstream: [
            ["androidboot.cpuvulkan.version", "0"],
            ["androidboot.hardware.vulkan", "ranchu"],
            ["androidboot.hardware.gltransport", "virtio-gpu-asg"],
            ["androidboot.hardware.hwcomposer.mode", "client"],
            ["androidboot.opengles.version", "196608"],
        ],
    },
};

/**
 * Cuttlefish's arm64 phone of Android 14 (aosp_cf_arm64_phone from the
 * aosp-android14-gsi branch, vsoc_arm64): a 32-bit second architecture
 * (zygote64_32), for 32-bit apps on arm64 (docs/aarch32-plan.md Q5.2);
 * otherwise as the arm64-only phone, tools/a64_android.mjs --build a14
 */
export const CF_ARM64_PHONE_A14 = /** @type {!Object} */ (Object.assign({}, CF_ARM64_ONLY_PHONE, {
    id: "cf_arm64_phone_a14",
    // (no vbmeta_system_dlkm: the build has no such image, system_dlkm is
    // in vbmeta's chain)
    partitions: CF_ARM64_ONLY_PHONE.partitions.filter(p => p.name !== "vbmeta_system_dlkm"),
}));

/**
 * The partitions of a device's disk in order, each slotted one per slot
 * @param {!Object} device
 * @return {!Array<{name: string, base: string, blank: (number|undefined)}>}
 */
export function device_partitions(device)
{
    return device.partitions.flatMap(p => p.slots ? ["_a", "_b"].map(slot => ({ name: p.name + slot, base: p.name })) :
        [{ name: p.name, base: p.name, blank: p.blank }]);
}

/**
 * The launcher's and bootloader's bootconfig (key order as Cuttlefish
 * writes it), with the GPU mode's keys
 * @param {!Object} device
 * @param {{vbmeta: {size: number, digest: string}, memory_mb: number, selinux: (string|undefined), page_size: (number|undefined), gpu_mode: (string|undefined)}} options
 * @return {!Map<string, string>}
 */
export function device_bootconfig(device, options)
{
    const map = new Map([
        ["androidboot.slot_suffix", device.slot],
        ["androidboot.force_normal_boot", "1"],
        ["androidboot.verifiedbootstate", "orange"],
        ["androidboot.vbmeta.device_state", "unlocked"],
        ["androidboot.vbmeta.hash_alg", "sha256"],
        ["androidboot.vbmeta.size", String(options.vbmeta.size)],
        ["androidboot.vbmeta.digest", options.vbmeta.digest],
        ["androidboot.vbmeta.avb_version", "1.3"],
        ["androidboot.vbmeta.invalidate_on_error", "yes"],
        ["androidboot.veritymode", "enforcing"],
        ["androidboot.boot_devices", device.boot_devices],
        ["androidboot.serialno", "V86A64ANDROID01"],
        ["androidboot.ddr_size", options.memory_mb + "MB"],
        ["androidboot.console", "ttyAMA0"],
        ["androidboot.serialconsole", "1"],
        ["androidboot.lcd_density", "320"],
        ["androidboot.setupwizard_mode", "DISABLED"],
        ["androidboot.enable_bootanimation", "1"],
        ...(options.selinux === "permissive" ? [["androidboot.selinux", "permissive"]] : []),
        ["androidboot.enable_confirmationui", "0"],
        // (the audio HAL's primary output is tinyalsa's card 0 device 0:
        // the guest's virtio-snd card, v86's virtio_sound, QEMU's
        // virtio-sound-pci; P12.5)
        ["androidboot.audio.tinyalsa.ignore_output", "false"],
        ["androidboot.audio.tinyalsa.simulate_input", "true"],
        // (16 KiB pages: f2fs's block is the page, the image's userdata is
        // f2fs in 4 KiB blocks; ext4 takes 4 KiB blocks under 16K pages)
        ["androidboot.fstab_suffix", (options.page_size || 4096) === 4096 ? "cf.f2fs.hctr2" : "cf.ext4.hctr2"],
        ["androidboot.wifi_mac_prefix", "5554"],
        ["androidboot.hw_timeout_multiplier", "50"],
        ["androidboot.hypervisor.vm.supported", "0"],
        ["androidboot.hypervisor.protected_vm.supported", "0"],
        ["androidboot.vendor.apex.com.android.hardware.keymint", "com.android.hardware.keymint.rust_nonsecure"],
        ["androidboot.vendor.apex.com.android.hardware.gatekeeper", "com.android.hardware.gatekeeper.nonsecure"],
        ["androidboot.vendor.apex.com.android.hardware.secure_element", "com.android.hardware.secure_element"],
        ["androidboot.vendor.apex.com.android.hardware.strongbox", "none"],
        ["androidboot.vendor.apex.com.android.hardware.graphics.composer", "com.android.hardware.graphics.composer.ranchu"],
        ["androidboot.wifi_impl", "virt_wifi"],
        // the lights HAL listens on this vsock port (a privileged port 0
        // without it: EACCES, and system_server waits for the HAL forever);
        // the Thread network HAL needs a node id above 0
        ["androidboot.vsock_lights_port", "6900"],
        ["androidboot.vsock_lights_cid", "3"],
        ["androidboot.openthread_node_id", "1"],
        ...device.gpu_modes.swiftshader,
    ]);
    const mode = options.gpu_mode || "swiftshader";
    if(!device.gpu_modes[mode]) throw new Error(`${device.id}: no GPU mode ${mode}`);
    if(mode !== "swiftshader") for(const [key, value] of device.gpu_modes[mode]) map.set(key, value);
    return map;
}

/**
 * The Android Emulator's system images on the ranchu machine
 * (docs/android-images-plan.md I6, docs/aarch32-plan.md R6): how the
 * emulator boots an SDK image of one API level and ABI: its kernel
 * (kernel-ranchu) and ramdisk, its disks in the emulator's order (the
 * virtio disks vda, vdb, ...: the ramdisk's fstab.ranchu names them) and
 * the kernel command line (src/virt/ranchu.js). On v64's disk each is a
 * partition: `member` the zip's file (in its ABI's directory), `ext4` an
 * empty file system of that size (the emulator's own, made at its start:
 * src/android/ext4.js); the bootloader (bootloader.js) makes each `disk`
 * partition a virtio disk, read-only or not
 */
export const RANCHU_25_ARMEABI_V7A = {
    id: "ranchu_25_armeabi_v7a",
    name: "Android 7.1 emulator image (armeabi-v7a)",
    cpu: "arm32",
    machine: "ranchu",
    api: 25,
    abi: "armeabi-v7a",
    partitions: [
        { name: "kernel", member: "kernel-ranchu" },
        { name: "ramdisk", member: "ramdisk.img" },
        // (fstab.ranchu: vda /system, vdb /cache, vdc /data)
        { name: "system", member: "system.img", disk: "read_only" },
        { name: "cache", ext4: 64 << 20, disk: "read_write" },
        { name: "userdata", member: "userdata.img", disk: "read_write" },
    ],
    // (no boot animation: the CPU draws it, which slows the first boot down)
    cmdline: { arm32: true, bootanim: false },
    // the GPU modes (docs/gles-proxy-plan.md "Android 传输"): "guest" the
    // CPU renders (qemu.gles=0); "host" the emulator's GL libraries send
    // GLES to v64's GLES host (ranchu_gpu "host": qemu.gles=1, and
    // ro.opengles.version the GLES version the host announces,
    // ranchu_gpu_mode's). The low-RAM setting, the boot animation and the
    // clock rate stay as "guest" has them until E3 measures them with host GLES.
    gpu_modes: {
        guest: { ranchu_gpu: "guest", gles: false, properties: {} },
        host: { ranchu_gpu: "host", gles: true, properties: {} },
    },
    // qemud's boot properties (src/virt/goldfish.js), beyond the machine's:
    // a low-RAM device (ActivityManager.isHighEndGfx false), so that
    // system_server draws its own windows with the CPU. Its GL would be the
    // guest's SwiftShader (without a host GPU the EGL loader takes the
    // vendor's SwiftShader: qemu.gles 2), whose JIT the image's SELinux
    // policy denies system_server (execmem): its first GL frame killed it.
    // No ANR stack traces (an empty dalvik.vm.stack-trace-file: AMS's
    // dumpStackTraces returns at once): on a CPU this slow an ANR's dumps of
    // every process held ActivityManager's lock past the Watchdog's 60 s,
    // which killed system_server
    properties: { "ro.config.low_ram": "true", "dalvik.vm.stack-trace-file": "" },
    // the machine's clock at a tenth of the host's (cpu_clock.rate, with
    // cooperative cores): Android 7.1's timeouts are a real phone's (a
    // service's start 20 s, the Watchdog 60 s); on this CPU SystemUI's start
    // took longer, ActivityManager killed it again and again (a background
    // ANR) and the keyguard's black scrim never went away
    clock_rate: 0.1,
    // init's additions (src/android/ramdisk_overlay.js): background ANRs
    // shown, not killed (Settings.Secure.ANR_SHOW_BACKGROUND, set by the
    // shell's settings command when the boot completes), so that a slow
    // service start (on a slower host) does not kill SystemUI for good
    // (init of Android 7.1 takes no quoted arguments; the shell's domain
    // is entered by /system/bin/sh only)
    init: {
        rc: [
            "# v64 (src/android/devices.js): background ANRs shown, not killed",
            "service v64_anr /system/bin/sh /system/bin/settings put secure anr_show_background 1",
            "    user shell",
            "    group shell",
            "    seclabel u:r:shell:s0",
            "    disabled",
            "    oneshot",
            "",
            "on property:sys.boot_completed=1",
            "    start v64_anr",
            "",
        ].join("\n"),
    },
};

/** The emulator images v64 boots, by API level and ABI */
export const RANCHU_DEVICES = [RANCHU_25_ARMEABI_V7A];

/** GLES versions as Android's ro.opengles.version (the major version << 16 | the minor) */
export const GLES_VERSIONS = { "2.0": "131072", "3.0": "196608", "3.1": "196609", "3.2": "196610" };

/**
 * The GLES version a GLES host announces where nothing says: 3.1, the
 * highest Android 7.1's library goes (3.2 is offered, of which the
 * library passes on part: gpu-deviations.md G-68; docs/gles3-plan.md)
 */
export const DEFAULT_GLES_VERSION = "3.1";

/**
 * An emulator image's GPU mode: the VM config's android.gpu_mode, "guest"
 * when it names none (or "swiftshader", the VM config's default, which is
 * the guest's own rendering here as well); with the GLES host, the GLES
 * version it announces (android.gles_version) as ro.opengles.version
 * @param {!Object} device
 * @param {string|undefined} gpu_mode
 * @param {string=} gles_version GLES_VERSIONS', DEFAULT_GLES_VERSION unless given
 * @return {{ranchu_gpu: string, gles: boolean, gles_version: (string|undefined), properties: !Object<string, string>}}
 */
export function ranchu_gpu_mode(device, gpu_mode, gles_version)
{
    const mode = !gpu_mode || gpu_mode === "swiftshader" ? "guest" : gpu_mode;
    const m = device.gpu_modes[mode];
    if(!m) throw new Error(`${device.id}: no GPU mode ${gpu_mode} (${Object.keys(device.gpu_modes).join(", ")})`);
    if(!m.gles) return m;
    const version = gles_version || DEFAULT_GLES_VERSION;
    if(!GLES_VERSIONS[version]) throw new Error(`${device.id}: no GLES version ${version} (${Object.keys(GLES_VERSIONS).join(", ")})`);
    return /** @type {{ranchu_gpu: string, gles: boolean, gles_version: (string|undefined), properties: !Object<string, string>}} */ (
        Object.assign({}, m, { gles_version: version, properties: Object.assign({}, m.properties, { "ro.opengles.version": GLES_VERSIONS[version] }) }));
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/src/android/erofs.js                                                                     0000644 0000000 0000000 00000026067 00000000000 013562  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // erofs (fs/erofs/erofs_fs.h), little-endian: reading flat inodes and
// directories of 4 KiB images, and adding or replacing files as
// uncompressed data after the image (docs/android-images-plan.md I1)

import { u16, u32, u64, put16, put32, put64, latin1, bytes_of, concat, compare, crc32c } from "./bytes.js";

const EROFS_SUPER_OFFSET = 1024, EROFS_MAGIC = 0xE0F5E1E2;
const B = 4096;
const EROFS_FT_REG_FILE = 1, EROFS_FT_DIR = 2;

/**
 * An inode of a 4 KiB erofs image
 * @param {!Uint8Array} image
 * @param {number} nid
 */
export function erofs_inode(image, nid)
{
    const sb = EROFS_SUPER_OFFSET;
    if(u32(image, sb) !== EROFS_MAGIC || image[sb + 12] !== 12) throw new Error("erofs: not a 4 KiB erofs image");
    const at = u32(image, sb + 40) * B + nid * 32, extended = u16(image, at) & 1, xattr_count = u16(image, at + 2);
    return { at, extended, layout: u16(image, at) >> 1 & 7, mode: u16(image, at + 4),
        size: extended ? u64(image, at + 8) : u32(image, at + 8),
        block: u32(image, at + 16), xattrs: at + (extended ? 64 : 32), xattr_size: xattr_count ? 12 + 4 * (xattr_count - 1) : 0 };
}

/**
 * The root directory's inode
 * @param {!Uint8Array} image
 */
export function erofs_root(image)
{
    return erofs_inode(image, u16(image, EROFS_SUPER_OFFSET + 14));
}

/**
 * An uncompressed (flat) inode's data, its last block inline or not
 * @param {!Uint8Array} image
 * @param {!Object} inode
 * @return {!Uint8Array}
 */
export function erofs_data(image, inode)
{
    if(inode.layout !== 0 && inode.layout !== 2) throw new Error("erofs: not a flat inode");
    const inline = inode.layout === 2 ? inode.size % B : 0, blocks = inode.size - inline;
    return concat([image.subarray(inode.block * B, inode.block * B + blocks),
        image.subarray(inode.xattrs + inode.xattr_size, inode.xattrs + inode.xattr_size + inline)]);
}

/**
 * Where offset into a flat inode's data is in the image
 * @param {!Object} inode
 * @param {number} offset
 * @return {number}
 */
function erofs_data_at(inode, offset)
{
    const blocks = inode.size - (inode.layout === 2 ? inode.size % B : 0);
    return offset < blocks ? inode.block * B + offset : inode.xattrs + inode.xattr_size + offset - blocks;
}

/**
 * A flat directory's entries (at: where each entry is in the image)
 * @param {!Uint8Array} image
 * @param {!Object} inode
 * @return {!Array<{nid: number, type: number, name: string, at: number}>}
 */
export function erofs_entries(image, inode)
{
    const data = erofs_data(image, inode), entries = [];
    for(let base = 0; base < data.length; base += B)
    {
        const length = Math.min(B, data.length - base), count = u16(data, base + 8) / 12;
        for(let i = 0; i < count; i++)
        {
            const end = base + (i + 1 < count ? u16(data, base + (i + 1) * 12 + 8) : length);
            entries.push({ nid: u64(data, base + i * 12), type: data[base + i * 12 + 10],
                name: latin1(data, base + u16(data, base + i * 12 + 8), end).replace(/\0.*$/s, ""), at: erofs_data_at(inode, base + i * 12) });
        }
    }
    return entries;
}

/**
 * Every path under a flat directory (the root by default), depth first,
 * with its inode
 * @param {!Uint8Array} image
 * @param {Object=} inode
 * @param {string=} prefix
 * @return {!Array<{path: string, type: number, inode: !Object}>}
 */
export function erofs_list(image, inode = erofs_root(image), prefix = "")
{
    const out = [];
    for(const e of erofs_entries(image, inode))
    {
        if(e.name === "." || e.name === "..") continue;
        const child = erofs_inode(image, e.nid);
        out.push({ path: prefix + e.name, type: e.type, inode: child });
        if(e.type === EROFS_FT_DIR) out.push(...erofs_list(image, child, prefix + e.name + "/"));
    }
    return out;
}

/**
 * The inode at path, through flat directories
 * @param {!Uint8Array} image
 * @param {string} file_path
 */
export function erofs_lookup(image, file_path)
{
    let inode = erofs_root(image);
    for(const name of file_path.split("/"))
    {
        const entry = erofs_entries(image, inode).find(e => e.name === name);
        if(!entry) return null;
        inode = erofs_inode(image, entry.nid);
    }
    return inode;
}

/** the superblock's checksum, when its feature flag asks for one */
function erofs_super_checksum(out)
{
    const sb = EROFS_SUPER_OFFSET;
    if(u32(out, sb + 8) & 1)
    {
        put32(out, sb + 4, 0);
        put32(out, sb + 4, crc32c(0xFFFFFFFF, out.subarray(sb, B)));
    }
}

/**
 * image (mkfs.erofs's) with a file at file_path, its directories new under
 * the root: the new inodes, directories and the file's data (uncompressed)
 * in blocks after the image's; the root's entries move into a block of
 * their own. labels: the SELinux label of the directories and of the file
 * @param {!Uint8Array} image
 * @param {string} file_path
 * @param {!Uint8Array} data
 * @param {{dir: string, file: string}} labels
 * @return {!Uint8Array}
 */
export function erofs_add_file(image, file_path, data, labels)
{
    const sb = EROFS_SUPER_OFFSET;
    const blocks = u32(image, sb + 36), meta = u32(image, sb + 40) * B;
    const root_nid = u16(image, sb + 14), inos = u64(image, sb + 16);
    const root = erofs_inode(image, root_nid);
    const entries = erofs_entries(image, root);
    const names = file_path.split("/");
    if(entries.some(e => e.name === names[0])) throw new Error(`erofs: /${names[0]} exists`);
    // (the name filter of the root's xattrs, with security.selinux as ours)
    if(!root.xattr_size) throw new Error("erofs: the root has no xattrs");
    const filter = u32(image, root.xattrs);
    const xattrs = label =>
    {
        const entry = concat([new Uint8Array([7, 6, label.length & 0xFF, label.length >> 8]), bytes_of("selinux" + label)]);
        const body = new Uint8Array(12 + Math.ceil(entry.length / 4) * 4);
        put32(body, 0, filter);
        body.set(entry, 12);
        return body;
    };
    const dirent_block = list =>
    {
        list.sort((a, b) => compare(bytes_of(a.name), bytes_of(b.name)));
        const block = new Uint8Array(B);
        let name_at = list.length * 12;
        list.forEach((e, i) =>
        {
            put64(block, i * 12, e.nid);
            put16(block, i * 12 + 8, name_at);
            block[i * 12 + 10] = e.type;
            if(name_at + e.name.length > B) throw new Error("erofs: a directory beyond one block");
            block.set(bytes_of(e.name), name_at);
            name_at += e.name.length;
        });
        return { block, size: name_at };
    };
    // the layout after the image: one block of inodes, the directories' blocks, the data
    const new_dirs = names.length - 1;
    const inode_block = blocks, dir_block = blocks + 1, data_block = dir_block + 1 + new_dirs;
    const total = data_block + Math.ceil(data.length / B);
    const out = new Uint8Array(total * B);
    out.set(image.subarray(0, blocks * B));
    const nids = [];
    let at = inode_block * B;
    for(let i = 0; i < names.length; i++)
    {
        nids.push((at - meta) / 32);
        at += Math.ceil((32 + xattrs(labels[i + 1 === names.length ? "file" : "dir"]).length) / 32) * 32;
    }
    if(at > dir_block * B) throw new Error("erofs: the inodes beyond one block");
    const write_inode = (index, mode, nlink, size, block, label) =>
    {
        const i = (nids[index] * 32) + meta, x = xattrs(label);
        put16(out, i, 0); // compact, flat plain
        put16(out, i + 2, (x.length - 12) / 4 + 1);
        put16(out, i + 4, mode);
        put16(out, i + 6, nlink);
        put32(out, i + 8, size);
        put32(out, i + 16, block);
        put32(out, i + 20, inos + 1 + index);
        out.set(x, i + 32);
    };
    for(let d = 0; d < new_dirs; d++)
    {
        const parent = d ? nids[d - 1] : root_nid;
        const child = { nid: nids[d + 1], type: d + 1 < new_dirs ? EROFS_FT_DIR : EROFS_FT_REG_FILE, name: names[d + 1] };
        const { block, size } = dirent_block([{ nid: nids[d], type: EROFS_FT_DIR, name: "." }, { nid: parent, type: EROFS_FT_DIR, name: ".." }, child]);
        out.set(block, (dir_block + 1 + d) * B);
        write_inode(d, 0o40755, d + 1 < new_dirs ? 3 : 2, size, dir_block + 1 + d, labels.dir);
    }
    write_inode(new_dirs, 0o100644, 1, data.length, data_block, labels.file);
    out.set(data, data_block * B);
    // the root: its entries and the new directory in a block of its own
    const { block, size } = dirent_block([...entries, { nid: nids[0], type: EROFS_FT_DIR, name: names[0] }]);
    out.set(block, dir_block * B);
    put16(out, root.at, u16(out, root.at) & ~0xE);
    if(root.extended)
    {
        put64(out, root.at + 8, size);
        put32(out, root.at + 44, u32(out, root.at + 44) + 1);
    }
    else
    {
        put32(out, root.at + 8, size);
        put16(out, root.at + 6, u16(out, root.at + 6) + 1);
    }
    put32(out, root.at + 16, dir_block);
    // the superblock: its counts and checksum
    put64(out, sb + 16, inos + names.length);
    put32(out, sb + 36, total);
    erofs_super_checksum(out);
    return out;
}

/**
 * image with files (path -> data) replaced: each file a new inode (the
 * old one's fields and xattrs, its layout flat plain, no inode across a
 * block) and its data uncompressed, in blocks after the image's; the
 * directory entry points at the new inode, the old inode and blocks stay
 * unused
 * @param {!Uint8Array} image
 * @param {!Iterable<!Array>} files [path, data]
 * @return {!Uint8Array}
 */
export function erofs_replace_files(image, files)
{
    const sb = EROFS_SUPER_OFFSET;
    const blocks = u32(image, sb + 36), meta = u32(image, sb + 40) * B;
    const root = erofs_root(image);
    const changes = [];
    for(const [file_path, data] of files)
    {
        const names = file_path.split("/"), name = names.pop();
        const dir = names.length ? erofs_lookup(image, names.join("/")) : root;
        const entry = dir && erofs_entries(image, dir).find(e => e.name === name);
        if(!entry) throw new Error(`erofs: no /${file_path}`);
        const inode = erofs_inode(image, entry.nid);
        if((inode.mode & 0o170000) !== 0o100000) throw new Error(`erofs: /${file_path} is not a regular file`);
        changes.push({ entry, inode, data, head: (inode.extended ? 64 : 32) + inode.xattr_size, at: 0, block: 0 });
    }
    let end = blocks * B;
    for(const c of changes)
    {
        const size = Math.ceil(c.head / 32) * 32;
        if(end % B + size > B) end = Math.ceil(end / B) * B;
        c.at = end;
        end += size;
    }
    let block = Math.ceil(end / B);
    for(const c of changes)
    {
        c.block = block;
        block += Math.ceil(c.data.length / B);
    }
    const out = new Uint8Array(block * B);
    out.set(image.subarray(0, blocks * B));
    for(const c of changes)
    {
        out.set(image.subarray(c.inode.at, c.inode.at + c.head), c.at);
        put16(out, c.at, u16(out, c.at) & ~0xE);
        if(c.inode.extended) put64(out, c.at + 8, c.data.length);
        else put32(out, c.at + 8, c.data.length);
        put32(out, c.at + 16, c.block);
        out.set(c.data, c.block * B);
        put64(out, c.entry.at, (c.at - meta) / 32);
    }
    put32(out, sb + 36, block);
    erofs_super_checksum(out);
    return out;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/android/ext4.js                                                                      0000644 0000000 0000000 00000020441 00000000000 013316  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // An empty filesystem for an Android partition that the system expects
// formatted but whose image the SDK does not ship, or ships too small (the
// ranchu machine's /cache, docs/aarch32-plan.md R6.3; API 28's userdata,
// whose userdata.img is 1 MiB that the emulator grows): the ext2 layout
// (revision 1, 4 KiB blocks, 256-byte inodes, file types in directories,
// sparse superblocks), which Linux's ext4 driver mounts as ext4 (fstab's
// type) with neither a journal nor extents. Block groups of 128 MiB, each
// with its bitmaps and inode table (and in groups 0, 1 and the powers of 3,
// 5 and 7 a copy of the superblock and the group descriptors); the root
// directory and lost+found in group 0.

const BLOCK = 4096;
const INODE_SIZE = 256;
const BLOCKS_PER_GROUP = 8 * BLOCK;
const FIRST_INODE = 11;
const DESCRIPTOR_SIZE = 32;

/**
 * Whether group `g` keeps a copy of the superblock (sparse_super)
 * @param {number} g
 */
function has_super(g)
{
    if(g <= 1) return true;
    for(const base of [3, 5, 7])
    {
        let n = base;
        while(n < g) n *= base;
        if(n === g) return true;
    }
    return false;
}

/**
 * The filesystem as the writes of its metadata (everything else zeros: a
 * new disk's blocks), so that a large one is never in memory whole
 * @param {number} size bytes (a multiple of 4 KiB, at least 256 KiB, below 16 TiB)
 * @param {string=} label the volume's name
 * @param {number=} time seconds since the epoch, the inodes' and the superblock's times
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function ext4_writes(size, label = "", time = 0)
{
    const blocks = Math.floor(size / BLOCK);
    if(blocks < 64 || size % BLOCK || blocks >= 2 ** 32)
    {
        throw new Error("make_empty_ext4: " + size + " bytes: a multiple of 4 KiB from 256 KiB to below 16 TiB");
    }
    let groups = Math.ceil(blocks / BLOCKS_PER_GROUP);
    // (a last group too small for its metadata is left out of the filesystem)
    const inodes_per_group = Math.min(8192, Math.max(2048, Math.floor(blocks / groups / 4) & ~7));
    const table_blocks = inodes_per_group * INODE_SIZE / BLOCK;
    const gdt_blocks = Math.ceil(groups * DESCRIPTOR_SIZE / BLOCK);
    const metadata = g => (has_super(g) ? 1 + gdt_blocks : 0) + 2 + table_blocks;
    let total = blocks;
    if(groups > 1 && total - (groups - 1) * BLOCKS_PER_GROUP < metadata(groups - 1) + 16)
    {
        groups--;
        total = groups * BLOCKS_PER_GROUP;
    }
    const inodes = groups * inodes_per_group;
    const writes = [];
    const view_of = bytes => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);

    // the groups' layout and what they use
    const layout = [];
    for(let g = 0; g < groups; g++)
    {
        const start = g * BLOCKS_PER_GROUP;
        const length = Math.min(BLOCKS_PER_GROUP, total - start);
        const first = start + (has_super(g) ? 1 + gdt_blocks : 0);
        layout.push({ start, length, block_bitmap: first, inode_bitmap: first + 1, inode_table: first + 2, used: metadata(g) });
    }
    // (group 0: the root directory's block and lost+found's after its table)
    const ROOT_BLOCK = layout[0].inode_table + table_blocks, LOST_BLOCK = ROOT_BLOCK + 1;
    layout[0].used += 2;
    const free_blocks = layout.reduce((n, l) => n + l.length - l.used, 0);

    // the superblock (and its copies: the same but their group number)
    const superblock = g =>
    {
        const sb = new Uint8Array(1024), view = view_of(sb);
        const u32 = (at, v) => view.setUint32(at, v >>> 0, true);
        const u16 = (at, v) => view.setUint16(at, v, true);
        u32(0, inodes);
        u32(4, total);
        u32(12, free_blocks);
        u32(16, inodes - FIRST_INODE);
        u32(20, 0);
        u32(24, 2);
        u32(28, 2);
        u32(32, BLOCKS_PER_GROUP);
        u32(36, BLOCKS_PER_GROUP);
        u32(40, inodes_per_group);
        u32(44, time);
        u32(48, time);
        u16(54, 0xFFFF);
        u16(56, 0xEF53);
        u16(58, 1);
        u16(60, 1);
        u32(64, time);
        u32(76, 1);
        u32(84, FIRST_INODE);
        u16(88, INODE_SIZE);
        u16(90, g);
        // (features: FILETYPE; SPARSE_SUPER and LARGE_FILE)
        u32(96, 0x0002);
        u32(100, 0x0003);
        // (the volume's UUID: a deterministic one from the size and time)
        let seed = (size / BLOCK ^ time ^ 0x5EED) >>> 0;
        for(let i = 0; i < 16; i++)
        {
            seed = Math.imul(seed ^ seed >>> 15, 0x2C1B3C6D) + 0x297A2D39 >>> 0;
            sb[104 + i] = seed >>> 24;
        }
        sb.set(new TextEncoder().encode(label).subarray(0, 16), 120);
        u32(264, time);
        return sb;
    };
    const descriptors = new Uint8Array(gdt_blocks * BLOCK);
    {
        const view = view_of(descriptors);
        layout.forEach((l, g) =>
        {
            const at = g * DESCRIPTOR_SIZE;
            view.setUint32(at + 0, l.block_bitmap, true);
            view.setUint32(at + 4, l.inode_bitmap, true);
            view.setUint32(at + 8, l.inode_table, true);
            view.setUint16(at + 12, l.length - l.used, true);
            view.setUint16(at + 14, g === 0 ? inodes_per_group - FIRST_INODE : inodes_per_group, true);
            view.setUint16(at + 16, g === 0 ? 2 : 0, true);
        });
    }
    layout.forEach((l, g) =>
    {
        if(has_super(g))
        {
            writes.push({ offset: g === 0 ? 1024 : l.start * BLOCK, bytes: superblock(g) });
            writes.push({ offset: (l.start + 1) * BLOCK, bytes: descriptors });
        }
        // the bitmaps: what is used, and the bits past the group's end
        const block_bitmap = new Uint8Array(BLOCK), inode_bitmap = new Uint8Array(BLOCK);
        const set_bits = (bitmap, from, to) => { for(let b = from; b < to; b++) bitmap[b >> 3] |= 1 << (b & 7); };
        set_bits(block_bitmap, 0, l.used);
        set_bits(block_bitmap, l.length, BLOCKS_PER_GROUP);
        set_bits(inode_bitmap, 0, g === 0 ? FIRST_INODE : 0);
        set_bits(inode_bitmap, inodes_per_group, 8 * BLOCK);
        writes.push({ offset: l.block_bitmap * BLOCK, bytes: block_bitmap });
        writes.push({ offset: l.inode_bitmap * BLOCK, bytes: inode_bitmap });
    });

    // the root (inode 2) and lost+found (11): directories of one block each
    const table = new Uint8Array(FIRST_INODE * INODE_SIZE), table_view = view_of(table);
    const inode = (n, mode, links, block) =>
    {
        const at = (n - 1) * INODE_SIZE;
        table_view.setUint16(at + 0, mode, true);
        table_view.setUint32(at + 4, BLOCK, true);
        table_view.setUint32(at + 8, time, true);
        table_view.setUint32(at + 12, time, true);
        table_view.setUint32(at + 16, time, true);
        table_view.setUint16(at + 26, links, true);
        table_view.setUint32(at + 28, BLOCK / 512, true);
        table_view.setUint32(at + 40, block, true);
    };
    inode(2, 0x41ED, 3, ROOT_BLOCK);
    inode(FIRST_INODE, 0x41C0, 2, LOST_BLOCK);
    writes.push({ offset: layout[0].inode_table * BLOCK, bytes: table });
    const directory = entries =>
    {
        const bytes = new Uint8Array(BLOCK), view = view_of(bytes);
        let at = 0;
        entries.forEach(([ino, name], i) =>
        {
            const encoded = new TextEncoder().encode(name);
            const rec_len = i === entries.length - 1 ? BLOCK - at : 12;
            view.setUint32(at, ino, true);
            view.setUint16(at + 4, rec_len, true);
            bytes[at + 6] = encoded.length;
            // (the file type: a directory)
            bytes[at + 7] = 2;
            bytes.set(encoded, at + 8);
            at += rec_len;
        });
        return bytes;
    };
    writes.push({ offset: ROOT_BLOCK * BLOCK, bytes: directory([[2, "."], [2, ".."], [FIRST_INODE, "lost+found"]]) });
    writes.push({ offset: LOST_BLOCK * BLOCK, bytes: directory([[FIRST_INODE, "."], [2, ".."]]) });
    return writes;
}

/**
 * The filesystem whole (a small one: it is in memory)
 * @param {number} size bytes (a multiple of 4 KiB, at least 256 KiB)
 * @param {string=} label the volume's name
 * @param {number=} time seconds since the epoch, the inodes' and the superblock's times
 * @return {!Uint8Array}
 */
export function make_empty_ext4(size, label = "", time = 0)
{
    const writes = ext4_writes(size, label, time);
    const image = new Uint8Array(size);
    for(const w of writes) image.set(w.bytes, w.offset);
    return image;
}
                                                                                                                                                                                                                               source/v64/src/android/gpt.js                                                                       0000644 0000000 0000000 00000014625 00000000000 013233  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GPT disks (UEFI 2.10 §5.3) as Android's partitions need them: a layout
// of named partitions, the protective MBR and both GPTs as writes, and a
// reader (docs/android-images-plan.md I1, I2)

import { u32, u64, put16, put32, put64, latin1, bytes_of, utf8, copy, crc32, sha256_hex } from "./bytes.js";

export const SECTOR = 512;
const LINUX_FILESYSTEM = "0FC63DAF-8483-4772-8E79-3D69D8477DE4";
const ENTRIES = 128, ENTRY_SIZE = 128;

/**
 * A GUID's bytes (the first three fields little-endian)
 * @param {string} text
 * @return {!Uint8Array}
 */
export function guid_bytes(text)
{
    const h = text.replace(/-/g, "");
    const b = new Uint8Array(16);
    for(let i = 0; i < 16; i++) b[i] = parseInt(h.substr(2 * i, 2), 16);
    return new Uint8Array([b[3], b[2], b[1], b[0], b[5], b[4], b[7], b[6], ...b.subarray(8)]);
}

/**
 * A GUID's text from its bytes
 * @param {!Uint8Array} b
 * @return {string}
 */
export function guid_text(b)
{
    const h = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15].map(i => b[i].toString(16).padStart(2, "0")).join("");
    return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`.toUpperCase();
}

/**
 * A stable GUID from a name (version 4 layout, from sha256)
 * @param {string} name
 * @return {string}
 */
export function name_guid(name)
{
    const h = sha256_hex(utf8("v86-a64-android:" + name));
    const v = h.slice(0, 12) + "4" + h.slice(13, 16) + "8" + h.slice(17, 32);
    return `${v.slice(0, 8)}-${v.slice(8, 12)}-${v.slice(12, 16)}-${v.slice(16, 20)}-${v.slice(20, 32)}`.toUpperCase();
}

/**
 * Partitions placed one after another from align, each start aligned, and
 * the disk's size (one more align at its end, for the backup GPT)
 * @param {!Array<{name: string, size: number}>} list
 * @param {number=} align
 * @return {{partitions: !Array<{name: string, start: number, size: number}>, disk_size: number}}
 */
export function gpt_layout(list, align = 1 << 20)
{
    const partitions = [];
    let at = align;
    for(const p of list)
    {
        partitions.push({ ...p, start: at });
        at += Math.ceil(p.size / align) * align;
    }
    return { partitions, disk_size: at + align };
}

/**
 * The protective MBR, primary and backup GPT for partitions [{ name,
 * start, size }] (bytes) as writes; a partition's type is Linux filesystem
 * data unless it has its own (an EFI System Partition's, for docs/uefi.md)
 * @param {number} disk_size
 * @param {!Array<{name: string, start: number, size: number, type: (string|undefined)}>} partitions
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function gpt_writes(disk_size, partitions)
{
    if(partitions.length > ENTRIES) throw new Error("GPT: more than 128 partitions");
    const entries = new Uint8Array(ENTRIES * ENTRY_SIZE);
    partitions.forEach((p, i) =>
    {
        const e = i * ENTRY_SIZE;
        entries.set(guid_bytes(p.type || LINUX_FILESYSTEM), e);
        entries.set(guid_bytes(name_guid(p.name)), e + 16);
        // (whole sectors: a size that is not ends in its last sector)
        if(p.start % SECTOR) throw new Error("GPT: " + p.name + " starts within a sector");
        put64(entries, e + 32, p.start / SECTOR);
        put64(entries, e + 40, Math.ceil((p.start + p.size) / SECTOR) - 1);
        if(p.name.length > 36) throw new Error("GPT: a name beyond 36 characters: " + p.name);
        for(let c = 0; c < p.name.length; c++) put16(entries, e + 56 + 2 * c, p.name.charCodeAt(c));
    });
    const sectors = disk_size / SECTOR;
    const header = (current, backup, entries_lba) =>
    {
        const h = new Uint8Array(SECTOR);
        h.set(bytes_of("EFI PART"), 0);
        put32(h, 8, 0x10000);
        put32(h, 12, 92);
        put64(h, 24, current);
        put64(h, 32, backup);
        put64(h, 40, 34);
        put64(h, 48, sectors - 34);
        h.set(guid_bytes(name_guid("disk")), 56);
        put64(h, 72, entries_lba);
        put32(h, 80, ENTRIES);
        put32(h, 84, ENTRY_SIZE);
        put32(h, 88, crc32(entries));
        put32(h, 16, crc32(h.subarray(0, 92)));
        return h;
    };
    const mbr = new Uint8Array(SECTOR);
    mbr[446 + 4] = 0xEE;
    put32(mbr, 446 + 8, 1);
    put32(mbr, 446 + 12, Math.min(sectors - 1, 0xFFFFFFFF));
    mbr[446 + 1] = 0; mbr[446 + 2] = 2; // CHS of LBA 1
    mbr[446 + 5] = 0xFF; mbr[446 + 6] = 0xFF; mbr[446 + 7] = 0xFF;
    put16(mbr, 510, 0xAA55);
    return [
        { offset: 0, bytes: mbr },
        { offset: SECTOR, bytes: header(1, sectors - 1, 2) },
        { offset: 2 * SECTOR, bytes: entries },
        { offset: (sectors - 33) * SECTOR, bytes: entries },
        { offset: (sectors - 1) * SECTOR, bytes: header(sectors - 1, 1, sectors - 33) },
    ];
}

/**
 * A disk's GPT partitions, from the primary GPT (else the backup), through
 * read(offset, length)
 * @param {function(number, number): !Uint8Array} read
 * @param {number=} disk_size for the backup
 * @return {!Array<{name: string, start: number, size: number, type: string, guid: string}>}
 */
export function gpt_partitions(read, disk_size = 0)
{
    const valid = h =>
    {
        if(h.length < 92 || latin1(h, 0, 8) !== "EFI PART") return false;
        const size = u32(h, 12);
        if(size < 92 || size > SECTOR) return false;
        const header = copy(h, 0, size);
        put32(header, 16, 0);
        return crc32(header) === u32(h, 16);
    };
    let h = read(SECTOR, SECTOR);
    if(!valid(h) && disk_size) h = read(disk_size - SECTOR, SECTOR);
    if(!valid(h)) throw new Error("GPT: no valid header");
    const count = u32(h, 80), size = u32(h, 84);
    if(size < 128 || count * size > 1 << 20) throw new Error("GPT: entries of " + size + " bytes");
    const entries = read(u64(h, 72) * SECTOR, count * size);
    if(crc32(entries) !== u32(h, 88)) throw new Error("GPT: the entries' CRC differs");
    const partitions = [];
    for(let i = 0; i < count; i++)
    {
        const e = entries.subarray(i * size, (i + 1) * size);
        if(e.subarray(0, 16).every(b => b === 0)) continue;
        let name = "";
        for(let c = 56; c + 1 < 128; c += 2)
        {
            const code = e[c] | e[c + 1] << 8;
            if(!code) break;
            name += String.fromCharCode(code);
        }
        const first = u64(e, 32), last = u64(e, 40);
        partitions.push({ name, start: first * SECTOR, size: (last - first + 1) * SECTOR,
            type: guid_text(e.subarray(0, 16)), guid: guid_text(e.subarray(16, 32)) });
    }
    return partitions;
}
                                                                                                           source/v64/src/android/lp.js                                                                        0000644 0000000 0000000 00000035766 00000000000 013065  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The super partition (system/core/fs_mgr/liblp/include/liblp/
// metadata_format.h): its geometry and metadata, little-endian, and its
// logical partitions replaced with their hash trees and vbmeta descriptors
// (docs/android-images-plan.md I1)

import { u32, u64, u64be, put32, put64, put32be, put64be, c_string, latin1, bytes_of, copy, concat, equals, hex, sha256 } from "./bytes.js";
import { vbmeta_struct, hashtree_descriptor, avb_hashtree, set_hashtree } from "./avb.js";

const LP_RESERVED_BYTES = 4096, LP_GEOMETRY_SIZE = 4096;
const LP_GEOMETRY_MAGIC = 0x616C4467, LP_HEADER_MAGIC = 0x414C5030;
const SECTOR = 512;
/** the tables' entry sizes (LpMetadataPartition, LpMetadataExtent,
 * LpMetadataPartitionGroup, LpMetadataBlockDevice) and where the header
 * describes each table */
const PARTITION_SIZE = 52, EXTENT_SIZE = 24, GROUP_SIZE = 48, DEVICE_SIZE = 64;
const TABLES = [80, 92, 104, 116];

/**
 * A metadata copy's partitions with their extents (at: where each extent is
 * in bytes)
 * @param {!Uint8Array} bytes
 * @return {!Array<{name: string, extents: !Array<{at: number, sectors: number, type: number, sector: number}>}>}
 */
function copy_partitions(bytes)
{
    const header_size = u32(bytes, 8);
    const table = at => ({ offset: header_size + u32(bytes, at), count: u32(bytes, at + 4), size: u32(bytes, at + 8) });
    const partitions = [], extents = table(92);
    const t = table(80);
    for(let p = 0; p < t.count; p++)
    {
        const at = t.offset + p * t.size;
        const first = u32(bytes, at + 40), count = u32(bytes, at + 44);
        partitions.push({ name: c_string(bytes, at, 36), extents: Array.from({ length: count }, (_, e) =>
        {
            const x = extents.offset + (first + e) * extents.size;
            return { at: x, sectors: u64(bytes, x), type: u32(bytes, x + 8), sector: u64(bytes, x + 12) };
        }) });
    }
    return partitions;
}

/**
 * Every copy of super's metadata (each slot's primary and backup), read
 * through read(offset, length); max: the room of each copy
 * @param {function(number, number): !Uint8Array} read
 * @return {{copies: !Array<{offset: number, bytes: !Uint8Array, partitions: !Array<{name: string, extents: !Array<{at: number, sectors: number, type: number, sector: number}>}>}>, alignment: number, size: number, max: number, slots: number}}
 */
export function lp_metadata(read)
{
    const geometry = read(LP_RESERVED_BYTES, 52);
    if(u32(geometry, 0) !== LP_GEOMETRY_MAGIC) throw new Error("super: no liblp geometry");
    const max = u32(geometry, 40), slots = u32(geometry, 44);
    const copies = [];
    for(let i = 0; i < 2 * slots; i++)
    {
        const offset = LP_RESERVED_BYTES + 2 * LP_GEOMETRY_SIZE + max * i;
        const head = read(offset, 48);
        if(u32(head, 0) !== LP_HEADER_MAGIC) throw new Error(`super: no metadata at ${offset}`);
        // (a copy of its own: changed in place)
        const bytes = new Uint8Array(read(offset, u32(head, 8) + u32(head, 44)));
        copies.push({ offset, bytes, partitions: copy_partitions(bytes) });
    }
    // (the block device: super itself)
    const bytes = copies[0].bytes, device = u32(bytes, 8) + u32(bytes, 116);
    return { copies, alignment: u32(bytes, device + 8), size: u64(bytes, device + 16), max, slots };
}

/**
 * A metadata copy as tables: partitions (their extents in them), groups
 * and block devices; header: the header's bytes (its other fields kept)
 * @param {!Uint8Array} bytes
 */
export function lp_parse(bytes)
{
    const header_size = u32(bytes, 8);
    const t = TABLES.map(at => ({ offset: header_size + u32(bytes, at), count: u32(bytes, at + 4), size: u32(bytes, at + 8) }));
    [PARTITION_SIZE, EXTENT_SIZE, GROUP_SIZE, DEVICE_SIZE].forEach((size, i) =>
    {
        if(t[i].size !== size) throw new Error(`super: table ${i}'s entries are ${t[i].size} bytes`);
    });
    const entries = (i, f) => Array.from({ length: t[i].count }, (_, k) => f(bytes.subarray(t[i].offset + k * t[i].size, t[i].offset + (k + 1) * t[i].size)));
    const extents = entries(1, e => ({ sectors: u64(e, 0), type: u32(e, 8), target: u64(e, 12), source: u32(e, 20) }));
    return {
        header: copy(bytes, 0, header_size),
        partitions: entries(0, e => ({ name: c_string(e, 0, 36), attributes: u32(e, 36), group: u32(e, 48),
            extents: extents.slice(u32(e, 40), u32(e, 40) + u32(e, 44)) })),
        groups: entries(2, e => ({ name: c_string(e, 0, 36), flags: u32(e, 36), maximum_size: u64(e, 40) })),
        block_devices: entries(3, e => ({ first_logical_sector: u64(e, 0), alignment: u32(e, 8), alignment_offset: u32(e, 12),
            size: u64(e, 16), name: c_string(e, 24, 36), flags: u32(e, 60) })),
    };
}

/**
 * lp_parse's tables as a metadata copy (extents in partition order), its
 * checksums new
 * @param {!Object} model
 * @return {!Uint8Array}
 */
export function lp_serialize(model)
{
    const name = (e, text) =>
    {
        if(text.length > 36) throw new Error("super: a name beyond 36 bytes: " + text);
        e.set(bytes_of(text), 0);
    };
    const extents = [], partitions = model.partitions.map(p =>
    {
        const e = new Uint8Array(PARTITION_SIZE);
        name(e, p.name);
        put32(e, 36, p.attributes);
        put32(e, 40, extents.length);
        put32(e, 44, p.extents.length);
        put32(e, 48, p.group);
        for(const x of p.extents)
        {
            const b = new Uint8Array(EXTENT_SIZE);
            put64(b, 0, x.sectors);
            put32(b, 8, x.type);
            put64(b, 12, x.target);
            put32(b, 20, x.source);
            extents.push(b);
        }
        return e;
    });
    const groups = model.groups.map(g =>
    {
        const e = new Uint8Array(GROUP_SIZE);
        name(e, g.name);
        put32(e, 36, g.flags);
        put64(e, 40, g.maximum_size);
        return e;
    });
    const devices = model.block_devices.map(d =>
    {
        const e = new Uint8Array(DEVICE_SIZE);
        put64(e, 0, d.first_logical_sector);
        put32(e, 8, d.alignment);
        put32(e, 12, d.alignment_offset);
        put64(e, 16, d.size);
        e.subarray(24).set(bytes_of(d.name).subarray(0, 36));
        put32(e, 60, d.flags);
        return e;
    });
    const header = new Uint8Array(model.header);
    let offset = 0;
    [[partitions, PARTITION_SIZE], [extents, EXTENT_SIZE], [groups, GROUP_SIZE], [devices, DEVICE_SIZE]].forEach(([list, size], i) =>
    {
        put32(header, TABLES[i], offset);
        put32(header, TABLES[i] + 4, list.length);
        put32(header, TABLES[i] + 8, size);
        offset += list.length * size;
    });
    put32(header, 44, offset);
    const bytes = concat([header, ...partitions, ...extents, ...groups, ...devices]);
    lp_checksum(bytes);
    return bytes;
}

/**
 * Every metadata copy of lp changed by change(model, index) (lp_parse's,
 * changed in place) and written again, lp's copies replaced; returns the
 * writes into super
 * @param {!Object} lp
 * @param {function(!Object, number)} change
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function lp_rewrite(lp, change)
{
    return lp.copies.map((copy, i) =>
    {
        const model = lp_parse(copy.bytes);
        change(model, i);
        const bytes = lp_serialize(model);
        if(bytes.length > lp.max) throw new Error(`super: metadata of ${bytes.length} bytes, room for ${lp.max}`);
        copy.bytes = bytes;
        copy.partitions = copy_partitions(bytes);
        if(i === 0)
        {
            const device = model.block_devices[0];
            lp.alignment = device.alignment;
            lp.size = device.size;
        }
        return { offset: copy.offset, bytes };
    });
}

/**
 * Super shrunk (or grown) to size (aligned up, past every extent): its
 * block device's size in every copy
 * @param {!Object} lp
 * @param {number} size bytes
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function lp_resize(lp, size)
{
    const aligned = Math.ceil(size / lp.alignment) * lp.alignment;
    if(aligned < lp_end(lp) * SECTOR) throw new Error(`super: ${aligned} bytes leave out its partitions (up to ${lp_end(lp) * SECTOR})`);
    return lp_rewrite(lp, model => { model.block_devices[0].size = aligned; });
}

/**
 * Super's logical partition name gone from every copy (its extents with it)
 * @param {!Object} lp
 * @param {string} name
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function lp_remove(lp, name)
{
    return lp_rewrite(lp, model =>
    {
        const i = model.partitions.findIndex(p => p.name === name);
        if(i < 0) throw new Error(`super: no ${name}`);
        model.partitions.splice(i, 1);
    });
}

/**
 * Super's logical partition name given one linear extent of sectors at
 * sector (on super itself) in every copy
 * @param {!Object} lp
 * @param {string} name
 * @param {number} sector
 * @param {number} sectors
 * @return {!Array<{offset: number, bytes: !Uint8Array}>}
 */
export function lp_place(lp, name, sector, sectors)
{
    if(sector % (lp.alignment / SECTOR)) throw new Error(`super: ${name} at an unaligned sector ${sector}`);
    if((sector + sectors) * SECTOR > lp.size) throw new Error(`super: no room for ${name}`);
    return lp_rewrite(lp, model =>
    {
        const p = model.partitions.find(p => p.name === name);
        if(!p) throw new Error(`super: no ${name}`);
        p.extents = [{ sectors, type: 0, target: sector, source: 0 }];
    });
}

/**
 * A metadata copy's checksums (sha256 of the tables, then of the header
 * with its own checksum zero), set in place
 * @param {!Uint8Array} bytes
 */
export function lp_checksum(bytes)
{
    const header_size = u32(bytes, 8);
    bytes.set(sha256(bytes.subarray(header_size)), 48);
    bytes.fill(0, 12, 44);
    bytes.set(sha256(bytes.subarray(0, header_size)), 12);
}

/**
 * The first sector after every extent of super's partitions
 * @param {!Object} lp lp_metadata's
 * @return {number}
 */
export function lp_end(lp)
{
    return Math.max(...lp.copies.flatMap(c => c.partitions.flatMap(p => p.extents.map(e => e.sector + e.sectors))));
}

/**
 * Super's partition name (slot a) replaced by image: its hash tree (as
 * the descriptor's: sha256 over 4 KiB blocks, its salt; no FEC), vbmeta
 * (the image holding name's hashtree descriptor) with the descriptor's sizes
 * and root digest, and the partition's one linear extent moved to free
 * space, space.sector onwards, in every metadata copy of lp (lp_metadata's,
 * changed in place). With `footer` (the partition's own vbmeta struct, as
 * the old one's AVB footer held it) the partition gets a footer again: that
 * struct with the same descriptor changes after the tree, the footer in the
 * extent's last 64 bytes (fs_mgr reads the "offline" vbmeta there). Returns
 * the new vbmeta, the bytes to write into super and a record
 * @param {!Object} lp
 * @param {!Uint8Array} vbmeta
 * @param {string} name
 * @param {!Uint8Array} image
 * @param {{sector: number}} space
 * @param {Uint8Array=} footer
 */
export function super_replace(lp, vbmeta, name, image, space, footer = null)
{
    const descriptor = hashtree_descriptor(vbmeta, name);
    if(descriptor.algorithm !== "sha256" || descriptor.data_block !== 4096 || descriptor.hash_block !== 4096) throw new Error(`vbmeta: ${name}'s hash tree is not sha256 over 4 KiB blocks`);
    const { root, tree } = avb_hashtree(image, descriptor.salt);
    const new_vbmeta = new Uint8Array(vbmeta);
    set_hashtree(new_vbmeta, descriptor, image.length, tree.length, root);
    let struct = null;
    if(footer)
    {
        // (the same changes in the partition's own struct: unsigned, avbtool's add_hashtree_footer)
        struct = new Uint8Array(footer);
        const own = hashtree_descriptor(struct, name);
        if(!equals(own.salt, descriptor.salt)) throw new Error(`vbmeta: ${name}'s footer has another salt`);
        set_hashtree(struct, own, image.length, tree.length, root);
    }
    const page = n => Math.ceil(n / 4096) * 4096;
    const vbmeta_offset = page(image.length + tree.length);
    const used = struct ? vbmeta_offset + page(struct.length) + 4096 : image.length + tree.length;
    const align = lp.alignment / SECTOR;
    const sector = Math.ceil(space.sector / align) * align, sectors = Math.ceil(used / lp.alignment) * align;
    if((sector + sectors) * SECTOR > lp.size) throw new Error(`super: no room for ${name}_a`);
    const old = lp.copies[0].partitions.find(p => p.name === name + "_a")?.extents;
    if(!old || old.length !== 1 || old[0].type !== 0) throw new Error(`super: ${name}_a is not one linear extent`);
    for(const copy of lp.copies)
    {
        const p = copy.partitions.find(p => p.name === name + "_a");
        if(!p || p.extents.length !== 1 || p.extents[0].sector !== old[0].sector) throw new Error(`super: the metadata copies differ in ${name}_a`);
        put64(copy.bytes, p.extents[0].at, sectors);
        put64(copy.bytes, p.extents[0].at + 12, sector);
        lp_checksum(copy.bytes);
        copy.partitions = copy_partitions(copy.bytes);
    }
    space.sector = sector + sectors;
    let bytes = concat([image, tree]);
    if(struct)
    {
        // AvbFooter: magic, version 1.0, original_image_size, vbmeta_offset, vbmeta_size, reserved[28]
        bytes = new Uint8Array(sectors * SECTOR);
        bytes.set(image, 0);
        bytes.set(tree, image.length);
        bytes.set(struct, vbmeta_offset);
        const f = bytes.length - 64;
        bytes.set(bytes_of("AVBf"), f);
        put32be(bytes, f + 4, 1);
        put32be(bytes, f + 8, 0);
        put64be(bytes, f + 12, image.length);
        put64be(bytes, f + 20, vbmeta_offset);
        put64be(bytes, f + 28, struct.length);
    }
    return { vbmeta: new_vbmeta, data: { offset: sector * SECTOR, bytes },
        record: { sector, sectors, image_blocks: image.length / 4096, root_digest: hex(root), footer: !!struct } };
}

/**
 * The vbmeta struct of super's partition name (slot a) as its AVB footer
 * holds it, or null
 * @param {function(number, number): !Uint8Array} super_read
 * @param {!Object} lp
 * @param {string} name
 * @return {Uint8Array}
 */
export function super_footer_struct(super_read, lp, name)
{
    const p = lp.copies[0].partitions.find(p => p.name === name + "_a");
    if(!p || p.extents.length !== 1) return null;
    const end = (p.extents[0].sector + p.extents[0].sectors) * SECTOR;
    const footer = super_read(end - 64, 64);
    if(latin1(footer, 0, 4) !== "AVBf") return null;
    const offset = u64be(footer, 20), size = u64be(footer, 28);
    return vbmeta_struct(super_read(p.extents[0].sector * SECTOR + offset, size)).struct;
}

/**
 * Super's partition name (slot a) as its hashtree descriptor in vbmeta sizes it
 * @param {function(number, number): !Uint8Array} super_read
 * @param {!Object} lp
 * @param {!Uint8Array} vbmeta
 * @param {string} name
 * @return {!Uint8Array}
 */
export function super_partition(super_read, lp, vbmeta, name)
{
    const p = lp.copies[0].partitions.find(p => p.name === name + "_a");
    if(!p || p.extents.length !== 1 || p.extents[0].type !== 0) throw new Error(`super: ${name}_a is not one linear extent`);
    return super_read(p.extents[0].sector * SECTOR, hashtree_descriptor(vbmeta, name).image_size);
}
          source/v64/src/android/lz4.js                                                                       0000644 0000000 0000000 00000004622 00000000000 013146  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // LZ4's legacy frame, Android's ramdisks (docs/android-images-plan.md I1)

import { u32, put32, concat } from "./bytes.js";

const LZ4_LEGACY_MAGIC = 0x184C2102;

/**
 * LZ4's legacy frame (Android's ramdisks): its blocks, one after another
 * @param {!Uint8Array} input
 * @return {!Uint8Array}
 */
export function lz4_legacy_decompress(input)
{
    if(u32(input, 0) !== LZ4_LEGACY_MAGIC) throw new Error("not an LZ4 legacy frame");
    const chunks = [];
    for(let at = 4; at + 4 <= input.length;)
    {
        const size = u32(input, at);
        // (another frame's magic: concatenated archives)
        if(size === LZ4_LEGACY_MAGIC) { at += 4; continue; }
        const src = input.subarray(at + 4, at + 4 + size);
        at += 4 + size;
        const out = new Uint8Array(8 << 20);
        let ip = 0, op = 0;
        while(ip < src.length)
        {
            const token = src[ip++];
            let literals = token >> 4;
            if(literals === 15) for(let b = 255; b === 255;) literals += b = src[ip++];
            out.set(src.subarray(ip, ip + literals), op);
            ip += literals; op += literals;
            if(ip >= src.length) break;
            const offset = src[ip] | src[ip + 1] << 8;
            ip += 2;
            let length = token & 15;
            if(length === 15) for(let b = 255; b === 255;) length += b = src[ip++];
            length += 4;
            for(let i = 0; i < length; i++, op++) out[op] = out[op - offset];
        }
        chunks.push(out.subarray(0, op));
    }
    return concat(chunks);
}

/**
 * LZ4's legacy frame with blocks of literals only (no compression), which
 * the kernel's unlz4 takes after another ramdisk's frame
 * @param {!Uint8Array} data
 * @return {!Uint8Array}
 */
export function lz4_legacy_store(data)
{
    const parts = [new Uint8Array([0x02, 0x21, 0x4C, 0x18])];
    for(let at = 0; at < data.length; at += 8 << 20)
    {
        const chunk = data.subarray(at, Math.min(data.length, at + (8 << 20)));
        const length = [];
        for(let rest = chunk.length - 15; rest >= 0; rest -= 255) length.push(Math.min(rest, 255));
        if(chunk.length >= 15 && length[length.length - 1] === 255) length.push(0);
        const block = concat([new Uint8Array([Math.min(chunk.length, 15) << 4, ...length]), chunk]);
        const size = new Uint8Array(4);
        put32(size, 0, block.length);
        parts.push(size, block);
    }
    return concat(parts);
}
                                                                                                              source/v64/src/android/partition_buffer.js                                                          0000644 0000000 0000000 00000003515 00000000000 015777  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A partition of a disk as a disk of its own (the ranchu machine's virtio
// disks on an emulator image's GPT disk, docs/android-images-plan.md I6):
// the disk buffer's reads, writes and flushes moved by the partition's
// start, its size the partition's. A snapshot keeps the disk's state once,
// with the partition that owns it (the first written one); the others keep
// none.

import { check_disk_state, restore_disk_state } from "../disk_writeback.js";

/**
 * @constructor
 * @param {?} disk the disk's buffer (src/buffer.js, a write-back backend)
 * @param {{name: string, start: number, size: number}} partition
 * @param {boolean} owner whether this partition's snapshot state is the disk's
 */
export function PartitionBuffer(disk, partition, owner)
{
    this.disk = disk;
    this.start = partition.start;
    this.byteLength = partition.size;
    this.owner = owner;
    this.disk_name = (disk.disk_name ? disk.disk_name + ":" : "") + partition.name;
    this.disk_error = disk.disk_error;
    this.logical_sector_size = disk.logical_sector_size;
}

PartitionBuffer.prototype.get = function(start, length, callback)
{
    this.disk.get(this.start + start, length, callback);
};

PartitionBuffer.prototype.set = function(start, data, callback)
{
    this.disk.set(this.start + start, data, callback);
};

PartitionBuffer.prototype.flush = function(callback)
{
    if(this.disk.flush) return this.disk.flush(callback);
    callback && callback();
};

PartitionBuffer.prototype.get_state = function()
{
    return this.owner ? [this.disk] : [];
};

PartitionBuffer.prototype.check_state = function(state)
{
    if(this.owner && state[0] !== undefined) check_disk_state(this.disk_name, this.disk, state[0]);
};

PartitionBuffer.prototype.set_state = function(state)
{
    if(this.owner && state[0] !== undefined) restore_disk_state(this.disk, state[0]);
};
                                                                                                                                                                                   source/v64/src/android/ramdisk_overlay.js                                                           0000644 0000000 0000000 00000003465 00000000000 015634  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What v64 adds to an emulator image's ramdisk (an Android Emulator system
// image's, docs/aarch32-plan.md R7.1): a second cpio archive after the
// image's own, which the kernel unpacks over it (a later file of the same
// name replaces the earlier one): the device's init file (init.ranchu.rc)
// with the device model's lines after its own, and the device model's
// files. The image's ramdisk is gzip-compressed; the archive added is not.

import { concat, bytes_of, latin1 } from "./bytes.js";
import { cpio_files, cpio_newc } from "./cpio.js";
// (the deflate stream decoded to its end: a partition's zeros after it are
// ignored; DecompressionStream calls them junk, and Chrome's then dropped the
// archive's last part, init.ranchu.rc with it)
import { gunzip } from "../virt/inflate.js";

/**
 * The ramdisk with the device model's additions (`device.init`: `{ rc:
 * string, files: Object<string, string> }`, the rc lines for `rc_file`),
 * or the ramdisk itself when it has none
 * @param {!Uint8Array} ramdisk the image's (gzip-compressed cpio)
 * @param {!Object} device src/android/devices.js's
 * @return {!Promise<!Uint8Array>}
 */
export async function ramdisk_overlay(ramdisk, device)
{
    const init = device.init;
    if(!init) return ramdisk;
    const files = cpio_files(gunzip(ramdisk));
    const rc_file = init.rc_file || "init.ranchu.rc";
    const rc = files.get(rc_file);
    if(!rc) throw new Error(`android: the ramdisk has no ${rc_file}`);
    const added = [[rc_file, bytes_of(latin1(rc) + "\n" + init.rc)],
        ...Object.entries(init.files || {}).map(([name, text]) => [name, bytes_of(text)])];
    // (the image's archive ends where its gzip stream does; the next one starts 4-aligned)
    const pad = new Uint8Array((4 - ramdisk.length % 4) % 4);
    return concat([ramdisk, pad, cpio_newc(added)]);
}
                                                                                                                                                                                                           source/v64/src/android/service_writer.js                                                            0000644 0000000 0000000 00000006140 00000000000 015466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A disk service's image written by the Android importer
// (docs/android-images-plan.md I3.2, tools/disk-service.mjs): a write
// session (open, write, close), the importer's writes gathered into runs
// of whole sectors (4 MiB a request). The image is new (zeros): a run's
// last partial sector is sent padded with zeros.

const SECTOR = 512;
const CHUNK = 4 << 20;

/**
 * @param {string} url the image's
 * @param {string=} token the service's, if it needs one
 * @return {!Promise<{write: function(number, !Uint8Array): !Promise, close: function(): !Promise}>}
 */
export async function service_writer(url, token)
{
    const post = async (op, headers = {}, body = undefined) =>
    {
        const all = Object.assign({ "X-V86-Disk-Op": op }, headers);
        if(token) all["Authorization"] = "Bearer " + token;
        const response = await fetch(url, { method: "POST", headers: all, body, cache: "no-store" });
        const answer = await response.json().catch(() => ({}));
        if(!response.ok) throw new Error("the disk service refused " + op + ": " + (answer.error || response.status));
        return answer;
    };
    const open = await post("open");
    const session = { "X-V86-Disk-Session": String(open.session), "X-V86-Disk-Epoch": String(open.epoch) };
    let sequence = 0;
    // the run gathered: its start (whole sectors) and bytes
    let start = -1, buffer = new Uint8Array(CHUNK + SECTOR), length = 0;
    const send = async (offset, bytes) =>
    {
        await post("write", Object.assign({ "X-V86-Disk-Sequence": String(++sequence), "X-V86-Disk-Offset": String(offset) }, session), bytes);
    };
    // (whole sectors sent; the rest kept, or with end padded and sent)
    const flush = async end =>
    {
        if(start < 0) return;
        const whole = end ? Math.ceil(length / SECTOR) * SECTOR : Math.floor(length / SECTOR) * SECTOR;
        if(whole)
        {
            if(whole > length) buffer.fill(0, length, whole);
            await send(start, buffer.slice(0, whole));
        }
        if(end || whole >= length)
        {
            start = -1;
            length = 0;
            return;
        }
        buffer.copyWithin(0, whole, length);
        start += whole;
        length -= whole;
    };
    return {
        async write(offset, bytes)
        {
            for(let at = 0; at < bytes.length;)
            {
                if(start < 0 || offset + at !== start + length)
                {
                    await flush(true);
                    // (a run begins on a sector: the importer's partitions do)
                    if((offset + at) % SECTOR) throw new Error("the disk service: a write at " + (offset + at) + ", within a sector");
                    start = offset + at;
                }
                const n = Math.min(bytes.length - at, CHUNK - length);
                buffer.set(bytes.subarray(at, at + n), length);
                length += n;
                at += n;
                if(length >= CHUNK) await flush(false);
            }
        },
        async close()
        {
            await flush(true);
            await post("close", session);
        },
    };
}
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/android/sparse.js                                                                    0000644 0000000 0000000 00000021422 00000000000 013727  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Android sparse images (system/core/libsparse: sparse_format.h)
// (docs/android-images-plan.md I1). The image is read through
// read(offset, length), which returns the bytes (fewer at its end).

import { u16, u32, copy, concat } from "./bytes.js";

const SPARSE_MAGIC = 0xED26FF3A;
const CHUNK_RAW = 0xCAC1, CHUNK_FILL = 0xCAC2, CHUNK_DONT_CARE = 0xCAC3, CHUNK_CRC32 = 0xCAC4;

/**
 * @param {function(number, number): !Uint8Array} read
 * @return {boolean}
 */
export function is_sparse(read)
{
    const head = read(0, 4);
    return head.length === 4 && u32(head, 0) === SPARSE_MAGIC;
}

/**
 * The sparse header
 * @param {function(number, number): !Uint8Array} read
 * @return {{file_header_size: number, chunk_header_size: number, block_size: number, total_blocks: number, total_chunks: number}}
 */
export function sparse_header(read)
{
    const header = read(0, 28);
    if(u32(header, 0) !== SPARSE_MAGIC) throw new Error("not a sparse image");
    return { file_header_size: u16(header, 8), chunk_header_size: u16(header, 10), block_size: u32(header, 12),
        total_blocks: u32(header, 16), total_chunks: u32(header, 20) };
}

/**
 * The raw size of a sparse image
 * @param {function(number, number): !Uint8Array} read
 * @return {number}
 */
export function sparse_size(read)
{
    const h = sparse_header(read);
    return h.block_size * h.total_blocks;
}

/**
 * A sparse image's raw contents as writes: write(offset, bytes) for data
 * and non-zero fills (zero fills and "don't care" are left out: the target
 * reads as zero there); returns the raw size
 * @param {function(number, number): !Uint8Array} read
 * @param {function(number, !Uint8Array)} write
 * @param {number=} piece the largest write
 * @return {number}
 */
export function unsparse(read, write, piece = 64 << 20)
{
    const h = sparse_header(read);
    let position = h.file_header_size, block = 0;
    for(let i = 0; i < h.total_chunks; i++)
    {
        const chunk_header = read(position, h.chunk_header_size);
        const type = u16(chunk_header, 0), blocks = u32(chunk_header, 4), total = u32(chunk_header, 8);
        const data_position = position + h.chunk_header_size, bytes = blocks * h.block_size;
        const at = block * h.block_size;
        if(type === CHUNK_RAW)
        {
            for(let done = 0; done < bytes;)
            {
                const n = Math.min(piece, bytes - done);
                write(at + done, read(data_position + done, n));
                done += n;
            }
        }
        else if(type === CHUNK_FILL)
        {
            const fill = read(data_position, 4);
            if(u32(fill, 0) !== 0)
            {
                const pattern = new Uint8Array(Math.min(piece, bytes));
                for(let j = 0; j < pattern.length; j += 4) pattern.set(fill, j);
                for(let done = 0; done < bytes; done += pattern.length) write(at + done, pattern.subarray(0, Math.min(pattern.length, bytes - done)));
            }
        }
        else if(type !== CHUNK_DONT_CARE && type !== CHUNK_CRC32) throw new Error(`sparse image: chunk type ${type.toString(16)}`);
        block += type === CHUNK_CRC32 ? 0 : blocks;
        position += total;
    }
    if(block !== h.total_blocks) throw new Error(`sparse image: ${block} of ${h.total_blocks} blocks`);
    return h.total_blocks * h.block_size;
}

/**
 * Bytes [offset, offset + length) of a sparse image's raw contents
 * @param {function(number, number): !Uint8Array} read
 * @param {number} offset
 * @param {number} length
 * @return {!Uint8Array}
 */
export function sparse_read(read, offset, length)
{
    const out = new Uint8Array(length);
    const h = sparse_header(read);
    for(let i = 0, position = h.file_header_size, at = 0; i < h.total_chunks && at < offset + length; i++)
    {
        const chunk_header = read(position, h.chunk_header_size);
        const type = u16(chunk_header, 0), bytes = type === CHUNK_CRC32 ? 0 : u32(chunk_header, 4) * h.block_size;
        const data = position + h.chunk_header_size, from = Math.max(at, offset), to = Math.min(at + bytes, offset + length);
        if(from < to && type === CHUNK_RAW) out.set(read(data + from - at, to - from), from - offset);
        else if(from < to && type === CHUNK_FILL)
        {
            const fill = read(data, 4);
            for(let j = from; j < to; j++) out[j - offset] = fill[(j - at) % 4];
        }
        at += bytes;
        position += u32(chunk_header, 8);
    }
    return out;
}

/**
 * A sparse image's raw contents from its bytes in order (a stream: a zip
 * member as it inflates): push(bytes) as they come, end() when they are all
 * there (returns the raw size). As unsparse, write(offset, bytes) for data
 * and non-zero fills, synchronously (bytes may be a view of push's);
 * size(): the raw size once the header is in (else -1)
 * @param {function(number, !Uint8Array)} write
 * @param {number=} piece the largest fill write
 * @return {{push: function(!Uint8Array), end: function(): number, size: function(): number}}
 */
export function sparse_decoder(write, piece = 16 << 20)
{
    // states: "file" (the header), "skip" (bytes to pass over), "chunk" (a
    // chunk's header), "raw" (its data), "fill" (its pattern), "done"
    let state = "file", need = 28, held = [], held_length = 0, left = 0;
    let h = null, chunks_left = 0, block = 0, type = 0, blocks = 0, data_size = 0;
    const next_chunk = () =>
    {
        if(chunks_left) { state = "chunk"; need = h.chunk_header_size; }
        else state = "done";
    };
    const skip = n =>
    {
        if(n) { state = "skip"; left = n; }
        else next_chunk();
    };
    const header = b =>
    {
        if(state === "file")
        {
            if(u32(b, 0) !== SPARSE_MAGIC) throw new Error("not a sparse image");
            h = { file_header_size: u16(b, 8), chunk_header_size: u16(b, 10), block_size: u32(b, 12),
                total_blocks: u32(b, 16), total_chunks: u32(b, 20) };
            if(h.file_header_size < 28 || h.chunk_header_size < 12) throw new Error("sparse image: header sizes");
            chunks_left = h.total_chunks;
            skip(h.file_header_size - 28);
        }
        else if(state === "chunk")
        {
            type = u16(b, 0); blocks = u32(b, 4); data_size = u32(b, 8) - h.chunk_header_size;
            chunks_left--;
            if(type === CHUNK_RAW)
            {
                if(data_size !== blocks * h.block_size) throw new Error("sparse image: a raw chunk's size");
                left = data_size;
                if(left) state = "raw";
                else next_chunk();
            }
            else if(type === CHUNK_FILL)
            {
                if(data_size < 4) throw new Error("sparse image: a fill chunk's size");
                state = "fill"; need = 4;
            }
            else if(type === CHUNK_DONT_CARE)
            {
                block += blocks;
                skip(data_size);
            }
            else if(type === CHUNK_CRC32) skip(data_size);
            else throw new Error(`sparse image: chunk type ${type.toString(16)}`);
        }
        else if(state === "fill")
        {
            const bytes = blocks * h.block_size, at = block * h.block_size;
            if(u32(b, 0) !== 0)
            {
                const pattern = new Uint8Array(Math.min(piece, bytes));
                for(let j = 0; j < pattern.length; j += 4) pattern.set(b, j);
                for(let done = 0; done < bytes; done += pattern.length) write(at + done, pattern.subarray(0, Math.min(pattern.length, bytes - done)));
            }
            block += blocks;
            skip(data_size - 4);
        }
    };
    const push = data =>
    {
        for(let i = 0; i < data.length;)
        {
            if(state === "done") throw new Error("sparse image: bytes after its last chunk");
            if(state === "raw" || state === "skip")
            {
                const n = Math.min(left, data.length - i);
                if(state === "raw")
                {
                    write(block * h.block_size + data_size - left, data.subarray(i, i + n));
                    if(n === left) block += blocks;
                }
                left -= n; i += n;
                if(!left) next_chunk();
                continue;
            }
            const n = Math.min(need - held_length, data.length - i);
            held.push(copy(data, i, i + n));
            held_length += n; i += n;
            if(held_length < need) continue;
            const b = held.length === 1 ? held[0] : concat(held);
            held = []; held_length = 0;
            header(b);
        }
    };
    const end = () =>
    {
        if(state !== "done" || block !== h.total_blocks) throw new Error(`sparse image: cut short (${block} of ${h ? h.total_blocks : "?"} blocks)`);
        return h.total_blocks * h.block_size;
    };
    return { push, end, size: () => h ? h.total_blocks * h.block_size : -1 };
}
                                                                                                                                                                                                                                              source/v64/src/android/zip.js                                                                       0000644 0000000 0000000 00000017451 00000000000 013243  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // zip archives (APPNOTE.TXT 6.3.10) as Android's images come: the central
// directory (zip64 too), members stored or deflated, inflated as a stream
// (DecompressionStream "deflate-raw") with their CRC-32 checked
// (docs/android-images-plan.md I1, I3). The archive is read through
// read(offset, length), which returns the bytes or a promise of them: a
// File's slices, an OPFS file's or a URL's ranges.

import { u16, u32, u64, latin1, copy, concat, crc32 } from "./bytes.js";

const EOCD = 0x06054B50, EOCD64 = 0x06064B50, EOCD64_LOCATOR = 0x07064B50, CENTRAL = 0x02014B50, LOCAL = 0x04034B50;
const STORED = 0, DEFLATED = 8;

/**
 * The archive's members, in the central directory's order
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {number} size the archive's
 * @return {!Promise<!Array<{name: string, method: number, flags: number, crc32: number, compressed_size: number, size: number, offset: number}>>}
 */
export async function zip_entries(read, size)
{
    const tail_length = Math.min(size, 22 + 0xFFFF);
    const tail = await read(size - tail_length, tail_length);
    let e = -1;
    for(let i = tail.length - 22; i >= 0; i--) if(u32(tail, i) === EOCD) { e = i; break; }
    if(e < 0) throw new Error("zip: no end of central directory");
    let count = u16(tail, e + 10), directory_size = u32(tail, e + 12), directory = u32(tail, e + 16);
    if(count === 0xFFFF || directory_size === 0xFFFFFFFF || directory === 0xFFFFFFFF)
    {
        const at = size - tail_length + e - 20;
        const locator = at >= 0 ? await read(at, 20) : new Uint8Array(20);
        if(u32(locator, 0) !== EOCD64_LOCATOR) throw new Error("zip: no zip64 end of central directory locator");
        const z = await read(u64(locator, 8), 56);
        if(u32(z, 0) !== EOCD64) throw new Error("zip: no zip64 end of central directory");
        count = u64(z, 32); directory_size = u64(z, 40); directory = u64(z, 48);
    }
    if(directory + directory_size > size) throw new Error("zip: the central directory is beyond the archive");
    const cd = await read(directory, directory_size);
    const entries = [];
    for(let at = 0, i = 0; i < count; i++)
    {
        if(at + 46 > cd.length || u32(cd, at) !== CENTRAL) throw new Error("zip: a broken central directory");
        const flags = u16(cd, at + 8), method = u16(cd, at + 10), crc = u32(cd, at + 16);
        let compressed_size = u32(cd, at + 20), uncompressed_size = u32(cd, at + 24), offset = u32(cd, at + 42);
        const name_length = u16(cd, at + 28), extra_length = u16(cd, at + 30), comment_length = u16(cd, at + 32);
        const name_bytes = cd.subarray(at + 46, at + 46 + name_length);
        const name = flags & 0x800 ? new TextDecoder().decode(name_bytes) : latin1(name_bytes);
        // (zip64's extra field: the fields at their maximum, in this order)
        for(let p = at + 46 + name_length, end = p + extra_length; p + 4 <= end;)
        {
            const id = u16(cd, p), length = u16(cd, p + 2);
            if(id === 1)
            {
                let q = p + 4;
                if(uncompressed_size === 0xFFFFFFFF) { uncompressed_size = u64(cd, q); q += 8; }
                if(compressed_size === 0xFFFFFFFF) { compressed_size = u64(cd, q); q += 8; }
                if(offset === 0xFFFFFFFF) { offset = u64(cd, q); q += 8; }
            }
            p += 4 + length;
        }
        entries.push({ name, method, flags, crc32: crc, compressed_size, size: uncompressed_size, offset });
        at += 46 + name_length + extra_length + comment_length;
    }
    return entries;
}

/**
 * A member's data: where it starts after its local header
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Object} entry zip_entries'
 * @return {!Promise<number>}
 */
async function data_offset(read, entry)
{
    const h = await read(entry.offset, 30);
    if(u32(h, 0) !== LOCAL) throw new Error(`zip: no local header for ${entry.name}`);
    return entry.offset + 30 + u16(h, 26) + u16(h, 28);
}

/**
 * A member's contents in order: sink(bytes) for each piece (awaited); its
 * size and CRC-32 checked against the central directory's. With limit,
 * stops once that many bytes are out (unchecked then). Returns the bytes
 * given to sink
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Object} entry
 * @param {function(!Uint8Array): (Promise|undefined)} sink
 * @param {{chunk: (number|undefined), limit: (number|undefined)}=} options
 * @return {!Promise<number>}
 */
export async function zip_stream(read, entry, sink, options = {})
{
    const chunk = options.chunk || 4 << 20, limit = options.limit === undefined ? Infinity : options.limit;
    if(entry.flags & 1) throw new Error(`zip: ${entry.name} is encrypted`);
    if(entry.method !== STORED && entry.method !== DEFLATED) throw new Error(`zip: ${entry.name}'s method ${entry.method}`);
    const start = await data_offset(read, entry);
    let crc = 0, produced = 0;
    const emit = async bytes =>
    {
        crc = crc32(bytes, crc);
        produced += bytes.length;
        await sink(bytes);
    };
    if(entry.method === STORED)
    {
        for(let done = 0; done < entry.compressed_size && produced < limit;)
        {
            const n = Math.min(chunk, entry.compressed_size - done);
            const bytes = await read(start + done, n);
            if(bytes.length !== n) throw new Error(`zip: ${entry.name} is cut short`);
            await emit(bytes);
            done += n;
        }
    }
    else
    {
        const inflate = new DecompressionStream("deflate-raw");
        const writer = inflate.writable.getWriter(), reader = inflate.readable.getReader();
        let stopped = false, feed_error = null;
        const feeding = (async () =>
        {
            for(let done = 0; done < entry.compressed_size && !stopped;)
            {
                const n = Math.min(chunk, entry.compressed_size - done);
                const bytes = await read(start + done, n);
                if(bytes.length !== n) throw new Error(`zip: ${entry.name} is cut short`);
                await writer.write(bytes);
                done += n;
            }
            if(!stopped) await writer.close();
        })().catch(e =>
        {
            if(!stopped) feed_error = e;
            return writer.abort(e).catch(() => {});
        });
        try
        {
            for(;;)
            {
                const { value, done } = await reader.read();
                if(done) break;
                await emit(value);
                if(produced >= limit)
                {
                    stopped = true;
                    await reader.cancel();
                    break;
                }
            }
        }
        catch(e)
        {
            // (a broken stream, a failed read (the writer aborted with it)
            // or sink's error: the feeding stops at its next write)
            stopped = true;
            await reader.cancel(e).catch(() => {});
            await feeding;
            throw e;
        }
        await feeding;
        if(feed_error) throw feed_error;
    }
    if(limit === Infinity)
    {
        if(produced !== entry.size) throw new Error(`zip: ${entry.name} is ${produced} bytes, the directory says ${entry.size}`);
        if(crc !== entry.crc32) throw new Error(`zip: ${entry.name}'s CRC-32 differs`);
    }
    return produced;
}

/**
 * A member's contents whole (a small one), or its first limit bytes
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {!Object} entry
 * @param {number=} limit
 * @return {!Promise<!Uint8Array>}
 */
export async function zip_read(read, entry, limit)
{
    const parts = [];
    await zip_stream(read, entry, bytes => { parts.push(copy(bytes)); }, { limit });
    const all = concat(parts);
    return limit === undefined ? all : all.subarray(0, limit);
}
                                                                                                                                                                                                                       source/v64/src/app/android_catalog.js                                                               0000644 0000000 0000000 00000012355 00000000000 014711  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The Android catalog (docs/android-images-plan.md I7): systems verified on
// v64 or its reference (QEMU) with the files each needs, where to download them
// (the official pages: the site hosts none, the owner's 2026-10-23
// decision), their sizes and SHA-256. The wizard lists them; dropped files
// are matched to their parts by size and SHA-256. tools/android_catalog.mjs
// checks the entries against local copies or the servers.

/**
 * @typedef {{name: string, role: "device" | "gsi" | "debug_ramdisk", page: string, url: string, size: number, sha256: string,
 *     optional?: boolean}} CatalogPart
 * @typedef {{id: string, title: string, android: string, api: number, abi: string, kind: "cuttlefish" | "gsi" | "emulator", device: string,
 *     parts: CatalogPart[], gpu: string, verified: string, license: string, notes: string}} CatalogEntry
 */

const CF_BUILD = "15581820";
const CF_PAGE = `https://ci.android.com/builds/submitted/${CF_BUILD}/aosp_cf_arm64_only_phone-userdebug/latest`;
const GSI_PAGE = "https://developer.android.com/topic/generic-system-image/releases";

/** @type {CatalogPart} the Cuttlefish arm64-only phone's images */
const CF_DEVICE = { name: `aosp_cf_arm64_only_phone-img-${CF_BUILD}.zip`, role: "device", page: CF_PAGE,
    url: CF_PAGE + `/raw/aosp_cf_arm64_only_phone-img-${CF_BUILD}.zip`, size: 1046288463,
    sha256: "d56b75f00cd4a0005d54175fdf9bafb48c4b4f8c1a20ee4ac062b019080ef506" };
/** @type {CatalogPart} its debug vendor ramdisk (the settings' Vendor ramdisk: debug) */
const CF_DEBUG_RAMDISK = { name: "vendor_ramdisk-debug.img", role: "debug_ramdisk", page: CF_PAGE, url: CF_PAGE + "/raw/vendor_ramdisk-debug.img",
    size: 18797343, sha256: "b9a00cd701d93acdb7fe3787d6674741e5373e0137777e0b3b68e5812ba65665", optional: true };

const AOSP_LICENSE = "Android Open Source Project builds (Apache 2.0 and the licenses of their parts: the build's NOTICE)";

const SDK_REPOSITORY = "https://dl.google.com/android/repository/sys-img/google_apis/";
const SDK_PAGE = "https://developer.android.com/studio/run/managing-avds";

/**
 * One entry per Android version that boots on v64, newest first (the
 * owner's 2026-10-27 choice: no list of every release). A GSI runs only on
 * a vendor of its Android version or older, and v64's one device is the
 * Android 16 Cuttlefish phone; Android 8.0 to 15 have no image that boots
 * here (their emulator images draw only through the emulator's host GLES,
 * docs/android-images-plan.md I6.3), Android 1 to 6 none either (the old
 * goldfish board).
 * @type {{version: number, entries: CatalogEntry[], default_entry: string}}
 */
export const ANDROID_CATALOG = {
    version: 2,
    default_entry: "android16-cuttlefish",
    entries: [
        {
            id: "android17-gsi-cp3a", title: "Android 17", android: "17 QPR1", api: 37,
            abi: "arm64-v8a", kind: "gsi", device: "cf_arm64_only_phone", gpu: "swiftshader",
            parts: [{ name: "aosp_arm64-exp-CP3A.260905.010-16176746-4a869a69.zip", role: "gsi", page: GSI_PAGE,
                url: "https://dl.google.com/developers/android/cinnamonbun/images/gsi/aosp_arm64-exp-CP3A.260905.010-16176746-4a869a69.zip", size: 1166864309,
                sha256: "4a869a6959a50fee15ff871ce378853ced4485f2aa456eb64dbdbf7a2c0408aa" }, CF_DEVICE],
            verified: "QEMU (HVF): boot_completed in 22 s (docs/android-images-plan.md I0.2)", license: AOSP_LICENSE + "; the GSI under the terms on its release page",
            notes: "Google's Generic System Image (QPR1, CP3A.260905.010) on the Android 16 phone: both files. 64-bit apps.",
        },
        {
            id: "android16-cuttlefish", title: "Android 16", android: "16 QPR2", api: 36, abi: "arm64-v8a",
            kind: "cuttlefish", device: "cf_arm64_only_phone", parts: [CF_DEVICE, CF_DEBUG_RAMDISK], gpu: "swiftshader",
            verified: "QEMU (HVF): boot_completed in 19-29 s; v64: docs/android-images-plan.md I3", license: AOSP_LICENSE,
            notes: "AOSP's phone for virtual machines (QPR2, build " + CF_BUILD + "). 64-bit apps.",
        },
        {
            id: "android7-emulator", title: "Android 7.1 (32-bit)", android: "7.1.1", api: 25, abi: "armeabi-v7a",
            kind: "emulator", device: "ranchu_25_armeabi_v7a", gpu: "guest",
            parts: [{ name: "armeabi-v7a-25_r18.zip", role: "device", page: SDK_PAGE, url: SDK_REPOSITORY + "armeabi-v7a-25_r18.zip",
                size: 952973150, sha256: "0e888e3141ec4bf55494cbbb268e91fab60de7bf5163f85a40a4bab7e31032ff" }],
            verified: "v64: boot_completed (docs/aarch32-plan.md R7.1)", license: "Android SDK system image (Google APIs): the Android SDK License Agreement",
            notes: "The Android Emulator's system image (Google APIs). The guest draws with the CPU.",
        },
    ],
};

/**
 * The catalog's part a file is, by its size and SHA-256 (the hash only
 * when a size matches)
 * @param {{size: number}} file
 * @param {string} [sha256] the file's, when known
 * @return {CatalogPart[]} the parts of that size (and hash, given one)
 */
export function catalog_parts_of(file, sha256)
{
    const parts = ANDROID_CATALOG.entries.flatMap(e => e.parts).filter(p => p.size === file.size && (!sha256 || p.sha256 === sha256));
    return parts.filter((p, i) => parts.findIndex(q => q.sha256 === p.sha256) === i);
}
                                                                                                                                                                                                                                                                                   source/v64/src/app/android_import.js                                                                0000644 0000000 0000000 00000024231 00000000000 014605  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// Android image packages in the VM manager (docs/android-images-plan.md
// I3): what a chosen file is (read on the page: the zip's directory, the
// start of its boot image and super's metadata) and the browser disk made
// from it in a worker (android_import_worker.js, build/android-import-worker.js).

import { package_entries, identify_package, cuttlefish_disk, emulator_disk, gsi_package } from "../android/assemble.js";
import { reserve_disk, finish_disk, delete_disk } from "./browser_disks.js";
import { create_image, list_images, new_image_name } from "./disk_service_client.js";
import { query_append } from "./emulator_bridge.js";
import { catalog_parts_of } from "./android_catalog.js";

/** The userdata sizes offered (GiB) and the default (the owner's, 2026-10-23); first boot formats it */
export const USERDATA_GIB = [2, 4, 8, 16];
export const DEFAULT_USERDATA_GIB = 4;
const GIB = 1024 * 1024 * 1024;

/**
 * @typedef {{kind: string, text: string, device: string | undefined, disk_size: (userdata_gib: number) => number,
 *     data_bytes: number, super_size: number, vendor_sdk_full: string,
 *     gsi: {name: string, release: string, sdk_full: string, fingerprint: string, abilist32: string} | null,
 *     emulator: {api: number, abi: string, tag: string, release: string, cpu: string} | null}} PackageInfo
 *     disk_size: the disk's with that userdata (an emulator image's: its own userdata.img, whatever the size);
 *     gsi: the system the device runs in place of its own; emulator: an Android Emulator image's (I6)
 */

/**
 * @param {Blob} file
 * @return {(offset: number, length: number) => Promise<Uint8Array>}
 */
function file_reader(file)
{
    return async (offset, length) => new Uint8Array(await file.slice(offset, offset + length).arrayBuffer());
}

/**
 * The chosen files sorted: the device's package (a Cuttlefish images zip)
 * and a GSI (docs/android-images-plan.md I5), each read on the page
 * @param {File[]} files
 * @return {Promise<{device: File | null, gsi: File | null, debug_ramdisk: File | null}>}
 */
export async function sort_android_files(files)
{
    /** @type {{device: any, gsi: any, debug_ramdisk: any}} */
    const sorted = { device: null, gsi: null, debug_ramdisk: null };
    for(const file of files)
    {
        // (the catalog's debug vendor ramdisk, by its size: not a zip)
        if(catalog_parts_of(file).some(p => p.role === "debug_ramdisk")) { sorted.debug_ramdisk = file; continue; }
        const read = file_reader(file);
        const kind = await identify_package(await package_entries(read, file.size), read);
        const name = file.name || "the file";
        if(!kind) throw new Error(name + " is not an Android image package v64 knows (a Cuttlefish images zip, aosp_cf_arm64_only_phone-img-<build>.zip, " +
            "a GSI zip, or an Android Emulator image zip)");
        if(kind.kind === "cuttlefish" || kind.kind === "emulator") sorted.device = file;
        else if(kind.kind === "gsi") sorted.gsi = file;
        else throw new Error(name + " is " + kind.text + ": v64 does not import it yet");
    }
    return sorted;
}

/**
 * What the package (and a GSI with it) gives: the device, the disk
 * @param {Blob} file the device's package
 * @param {(Blob & {name?: string}) | null} [gsi_file]
 * @return {Promise<PackageInfo>}
 */
export async function inspect_android_package(file, gsi_file = null)
{
    const read = file_reader(file);
    const entries = await package_entries(read, file.size);
    const kind = await identify_package(entries, read);
    if(!kind) throw new Error("Not an Android image package v64 knows (a Cuttlefish images zip, aosp_cf_arm64_only_phone-img-<build>.zip, " +
        "an Android Emulator image zip)");
    if(kind.kind === "gsi") throw new Error("This is a GSI: a system for a device; add the device's package (a Cuttlefish images zip) with it");
    if(kind.kind === "emulator")
    {
        if(gsi_file) throw new Error("A GSI goes with a Cuttlefish images zip, not with an emulator image");
        const disk = await emulator_disk(read, entries);
        return { kind: kind.kind, text: kind.text, device: disk.device.id, disk_size: () => disk.disk_size, data_bytes: disk.data_bytes,
            super_size: 0, vendor_sdk_full: "", gsi: null,
            emulator: { api: disk.api, abi: disk.abi, tag: disk.tag, release: disk.release, cpu: disk.device.cpu } };
    }
    if(kind.kind !== "cuttlefish") throw new Error("This is " + kind.text + ": v64 does not import it yet");
    let gsi = null, gsi_read;
    if(gsi_file)
    {
        gsi_read = file_reader(gsi_file);
        gsi = await gsi_package(gsi_read, await package_entries(gsi_read, gsi_file.size));
    }
    const disk = await cuttlefish_disk(read, entries, { userdata_bytes: GIB, gsi: gsi || undefined, gsi_read });
    return { kind: kind.kind, text: kind.text, device: kind.device, disk_size: userdata_gib => disk.disk_size - GIB + userdata_gib * GIB,
        data_bytes: disk.data_bytes, super_size: disk.super_size, vendor_sdk_full: disk.vendor_sdk_full,
        gsi: gsi && { name: gsi_file && gsi_file.name || "", release: gsi.release, sdk_full: gsi.sdk_full, fingerprint: gsi.fingerprint, abilist32: gsi.abilist32 },
        emulator: null };
}

/**
 * The importer's worker on a message: its progress, then its answer;
 * signal aborts it (the worker ended at once)
 * @param {any} message
 * @param {{progress?: (done: number, total: number) => void, signal?: AbortSignal}} options
 * @return {Promise<any>}
 */
function run_worker(message, options)
{
    const worker = new Worker("build/android-import-worker.js" + query_append(), { type: "module" });
    return new Promise((resolve, reject) =>
    {
        const end = () => { worker.terminate(); options.signal && options.signal.removeEventListener("abort", abort); };
        const abort = () => { end(); reject(new Error("Cancelled")); };
        if(options.signal && options.signal.aborted) { abort(); return; }
        options.signal && options.signal.addEventListener("abort", abort);
        worker.onmessage = e =>
        {
            if(e.data.progress) { options.progress && options.progress(e.data.progress[0], e.data.progress[1]); return; }
            end();
            if(e.data.error) reject(new Error(e.data.error));
            else resolve(e.data);
        };
        // (a worker that does not load says nothing more: on a development server, build/android-import-worker.js not built)
        worker.onerror = e => { end(); reject(new Error("The importer's worker failed: " +
            (e.message || "it did not start (build/android-import-worker.js: make app builds it)"))); };
        worker.postMessage(message);
    });
}

/**
 * The browser disk of a package (with a GSI), made in a worker; cancelled
 * by signal (the disk made so far deleted)
 * @param {Blob & {name?: string}} file
 * @param {string} label
 * @param {{userdata_gib: number, gsi?: (Blob & {name?: string}) | null, prefs?: any, progress?: (done: number, total: number) => void,
 *     signal?: AbortSignal}} options
 * @return {Promise<import("./browser_disks.js").BrowserDisk>}
 */
export async function import_android_package(file, label, options)
{
    const info = await inspect_android_package(file, options.gsi || null);
    const userdata_bytes = options.userdata_gib * GIB;
    const { id } = await reserve_disk(info.disk_size(options.userdata_gib), options.prefs);
    /** @type {any} */
    let result;
    try
    {
        result = (await run_worker({ file, gsi_file: options.gsi || null, id, userdata_bytes }, options)).done;
    }
    catch(e)
    {
        // (the worker's handle on the file goes with it: the disk deleted once it can be)
        for(let i = 0; i < 20; i++)
        {
            try { await delete_disk(id); break; }
            catch(_) { await new Promise(resolve => setTimeout(resolve, 250)); }
        }
        throw e;
    }
    return await finish_disk(id, label, { source: file.name || "", android: { kind: result.kind, device: result.device, userdata_gib: options.userdata_gib,
        gsi: options.gsi ? options.gsi.name || "" : undefined } });
}

/**
 * A browser disk's Android user data wiped: the start of its userdata and
 * metadata partitions zeroed (their file systems' superblocks), which
 * Android formats again at its next boot (fs_mgr's formattable). In the
 * importer's worker, through the file's sync access handle: not while the
 * machine runs (its CPU holds the disk open)
 * @param {string} id the browser disk's
 * @return {Promise<string[]>} the partitions wiped
 */
export async function wipe_android_data(id)
{
    return (await run_worker({ op: "wipe", id }, {})).wiped;
}

/**
 * A file's SHA-256, in the importer's worker
 * @param {Blob} file
 * @param {(done: number, total: number) => void} [progress]
 * @return {Promise<string>}
 */
export async function hash_file(file, progress)
{
    return (await run_worker({ op: "hash", file }, { progress })).sha256;
}

/**
 * A package (with a GSI) made into a new image of the disk service
 * (docs/android-images-plan.md I3.2): the image created, then written by
 * the importer's worker through a write session
 * @param {Blob & {name?: string}} file
 * @param {string} machine the machine's name (the image's)
 * @param {import("./disk_service_client.js").Service} service
 * @param {{userdata_gib: number, gsi?: (Blob & {name?: string}) | null, progress?: (done: number, total: number) => void, signal?: AbortSignal}} options
 *     signal: cancelled (the image created stays: the service has no delete; its name said)
 * @return {Promise<{url: string, size: number}>}
 */
export async function import_android_package_to_service(file, machine, service, options)
{
    const info = await inspect_android_package(file, options.gsi || null);
    const size = info.disk_size(options.userdata_gib);
    const image = await create_image(service, new_image_name(machine, (await list_images(service)).images), size);
    try
    {
        await run_worker({ file, gsi_file: options.gsi || null, id: "", userdata_bytes: options.userdata_gib * GIB,
            service: { url: image.url, token: service.token } }, options);
    }
    catch(e)
    {
        throw new Error(e.message + " (the disk service keeps the image made so far, " + image.name + ")");
    }
    return { url: image.url, size };
}
                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/app/android_import_worker.js                                                         0000644 0000000 0000000 00000014220 00000000000 016173  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Android importer's worker (docs/android-images-plan.md I3.1): an
// image package (a File) made into a browser disk, v86/disks/<id>.img,
// through the file's sync access handle (dedicated workers only), as
// src/android/assemble.js lays it out. Bundled into
// build/android-import-worker.js; src/app/android_import.js starts it.
//
// in:  { file: File, gsi_file: File | null, id: string, userdata_bytes: number, service?: { url, token } }
//      (service: the disk service's new image written, I3.2, in place of the browser disk id)
// out: { progress: [done, total] }..., then { done: { size, kind, partitions } } or { error: string }
// in:  { op: "wipe", id }: the disk's userdata and metadata wiped (their first MiB zeroed)
// out: { wiped: [names] } or { error: string }
// in:  { op: "hash", file }: the file's SHA-256 (the catalog's check, I7.2)
// out: { progress: [done, total] }..., then { sha256 } or { error: string }

import { package_entries, identify_package, cuttlefish_disk, emulator_disk, write_disk, gsi_package } from "../android/assemble.js";
import { gpt_partitions } from "../android/gpt.js";
import { SHA256 } from "../image/sha256.js";
import { service_writer } from "../android/service_writer.js";

/** the browser disks' directory */
async function disks_directory()
{
    let dir = await navigator.storage.getDirectory();
    for(const name of ["v86", "disks"]) dir = await dir.getDirectoryHandle(name, { create: true });
    return dir;
}

/** a browser disk's userdata and metadata: their first MiB zeroed */
async function wipe(id)
{
    const handle = await (await disks_directory()).getFileHandle(id + ".img");
    let access;
    try
    {
        access = await handle.createSyncAccessHandle();
    }
    catch(e)
    {
        throw new Error("the disk is in use: power the machine off first (" + e.message + ")");
    }
    try
    {
        const size = access.getSize();
        const read = (offset, length) =>
        {
            const bytes = new Uint8Array(length);
            return bytes.subarray(0, access.read(bytes, { at: offset }));
        };
        const wiped = [];
        for(const p of gpt_partitions(read, size))
        {
            if(p.name !== "userdata" && p.name !== "metadata") continue;
            access.write(new Uint8Array(Math.min(p.size, 1 << 20)), { at: p.start });
            wiped.push(p.name);
        }
        if(!wiped.length) throw new Error("the disk has no userdata or metadata partition");
        access.flush();
        return wiped;
    }
    finally
    {
        access.close();
    }
}

/** a file's SHA-256, read in pieces */
async function hash(file)
{
    const sha = new SHA256(), piece = 8 << 20;
    for(let at = 0; at < file.size; at += piece)
    {
        sha.update(new Uint8Array(await file.slice(at, at + piece).arrayBuffer()));
        postMessage({ progress: [Math.min(file.size, at + piece), file.size] });
    }
    return sha.hex();
}

globalThis.onmessage = async event =>
{
    if(event.data.op === "hash")
    {
        try { postMessage({ sha256: await hash(event.data.file) }); }
        catch(e) { postMessage({ error: e && e.message || String(e) }); }
        return;
    }
    if(event.data.op === "wipe")
    {
        try { postMessage({ wiped: await wipe(event.data.id) }); }
        catch(e) { postMessage({ error: e && e.message || String(e) }); }
        return;
    }
    const { file, gsi_file, id, userdata_bytes, service } = event.data;
    /** @type {any} */
    let dir = null, access = null;
    try
    {
        const reader = blob => async (offset, length) => new Uint8Array(await blob.slice(offset, offset + length).arrayBuffer());
        const read = reader(file);
        const entries = await package_entries(read, file.size);
        const kind = await identify_package(entries, read);
        if(!kind) throw new Error(file.name + " is not an Android image package v64 knows (a Cuttlefish images zip, an emulator image zip)");
        if(kind.kind !== "cuttlefish" && kind.kind !== "emulator") throw new Error(file.name + " is " + kind.text + ": not imported yet");
        /** @type {any} */
        let disk;
        if(kind.kind === "emulator")
        {
            // (an emulator image, I6: its device model is its API level's and ABI's)
            disk = await emulator_disk(read, entries);
            kind.device = disk.device.id;
        }
        else
        {
            const gsi_read = gsi_file ? reader(gsi_file) : undefined;
            const gsi = gsi_file ? await gsi_package(gsi_read, await package_entries(gsi_read, gsi_file.size)) : undefined;
            disk = await cuttlefish_disk(read, entries, { userdata_bytes, gsi, gsi_read });
        }
        let shown = 0;
        const progress = (done, total) =>
        {
            // (at most every 1/200th)
            if(done - shown >= total / 200 || done === total)
            {
                shown = done;
                postMessage({ progress: [done, total] });
            }
        };
        const done = () => postMessage({ done: { size: disk.disk_size, kind: kind.kind, device: kind.device,
            partitions: disk.partitions.map(p => ({ name: p.name, start: p.start, size: p.size })) } });
        if(service)
        {
            const writer = await service_writer(service.url, service.token);
            await write_disk(read, disk, (offset, bytes) => writer.write(offset, bytes), progress);
            await writer.close();
            done();
            return;
        }
        dir = await disks_directory();
        const handle = await dir.getFileHandle(id + ".img", { create: true });
        access = await handle.createSyncAccessHandle();
        access.truncate(disk.disk_size);
        await write_disk(read, disk, (offset, bytes) =>
        {
            if(access.write(bytes, { at: offset }) !== bytes.length) throw new Error("a short write into the browser disk (no room?)");
        }, progress);
        access.flush();
        access.close();
        access = null;
        done();
    }
    catch(e)
    {
        try { access && access.close(); } catch(_) { /* closed */ }
        if(dir) await dir.removeEntry(id + ".img").catch(() => {});
        postMessage({ error: e && e.message || String(e) });
    }
};
                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/app/app.css                                                                          0000644 0000000 0000000 00000025755 00000000000 012543  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The VM manager's page (docs/vm-manager-plan.md); v86.css stays the old page's */
:root {
    --bg: #111;
    --panel: #1a1a1a;
    --panel-2: #222;
    --line: #333;
    --text: #e6e6e6;
    --muted: #a0a0a0;
    --accent: #3d7bd9;
    --accent-text: #fff;
    --selected: #24344d;
    --danger: #ff8a80;
    --error: #ffb4a9;
    color-scheme: dark;
}
* { box-sizing: border-box; }
/* (the hidden attribute wins over the display of buttons and panels) */
[hidden] { display: none !important; }
html, body { margin: 0; }
body {
    background: var(--bg);
    color: var(--text);
    font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}
#app { flex: 1; display: flex; flex-direction: column; }
a { color: #8ab4f8; }
h1 { font-size: 1.5em; margin: 0 0 0.5em; font-weight: 600; }
h2 { font-size: 1.15em; margin: 0 0 0.75em; font-weight: 600; }

button, a.button {
    font: inherit;
    color: var(--text);
    background: var(--panel-2);
    border: 1px solid #444;
    border-radius: 4px;
    padding: 5px 12px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
}
button:hover:not(:disabled), a.button:hover { border-color: #666; }
button:focus-visible, a.button:focus-visible, [tabindex]:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
button:disabled { opacity: 0.5; cursor: default; }
button.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
button.danger { color: var(--danger); border-color: #6b3a36; }
input[type=text], input[type=number], select {
    font: inherit;
    color: var(--text);
    background: #0c0c0c;
    border: 1px solid #444;
    border-radius: 4px;
    padding: 4px 6px;
}

/* the library */
.library { flex: 1; display: grid; grid-template-columns: 280px 1fr; }
.library-list { background: var(--panel); border-right: 1px solid var(--line); padding: 12px; }
.library-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 12px; }
.vm-list { list-style: none; margin: 0; padding: 0; }
.vm-list li {
    display: flex;
    flex-direction: column;
    padding: 7px 10px;
    border-radius: 4px;
    cursor: pointer;
}
.vm-list li:hover { background: #202020; }
.vm-list li.selected { background: var(--selected); }
.vm-name { font-weight: 500; overflow-wrap: anywhere; }
.vm-state { color: var(--muted); font-size: 0.9em; }
.library-summary { padding: 20px 28px; min-width: 0; }
.summary-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 16px; }
.hardware { border-collapse: collapse; max-width: 100%; }
.hardware th, .hardware td { text-align: left; vertical-align: top; padding: 4px 16px 4px 0; border-bottom: 1px solid #262626; }
.hardware th { color: var(--muted); font-weight: normal; white-space: nowrap; }
.hardware td { overflow-wrap: anywhere; }
.notes { white-space: pre-wrap; }
.note, .empty { color: var(--muted); }
.intro { max-width: 40em; }

/* dialogs */
dialog.dialog {
    background: var(--panel);
    color: var(--text);
    border: 1px solid #444;
    border-radius: 6px;
    padding: 18px 20px;
    max-width: min(560px, calc(100vw - 32px));
}
dialog.dialog::backdrop { background: rgba(0, 0, 0, 0.6); }
.dialog-body { margin-bottom: 16px; }
.dialog-buttons { display: flex; justify-content: flex-end; gap: 8px; }
.field { display: flex; flex-direction: column; gap: 4px; }
.field input { width: 100%; }
pre.problems { white-space: pre-wrap; margin: 0; font-size: 0.95em; }

/* the settings dialog and the wizard */
dialog.settings-dialog, dialog.wizard-dialog {
    background: var(--panel);
    color: var(--text);
    border: 1px solid #444;
    border-radius: 6px;
    padding: 0;
    width: min(980px, calc(100vw - 32px));
    height: min(720px, calc(100vh - 32px));
}
dialog.settings-dialog::backdrop, dialog.wizard-dialog::backdrop { background: rgba(0, 0, 0, 0.6); }
.settings {
    display: grid;
    grid-template-columns: 260px 1fr;
    grid-template-rows: auto 1fr auto;
    height: 100%;
}
.settings-header, .wizard header { grid-column: 1 / -1; padding: 14px 18px 0; }
.settings-list { border-right: 1px solid var(--line); overflow: auto; padding: 8px; display: flex; flex-direction: column; }
.hardware-list { list-style: none; margin: 0; padding: 0; flex: 1; }
.hardware-list li { display: flex; flex-direction: column; padding: 6px 10px; border-radius: 4px; cursor: pointer; }
.hardware-list li:hover { background: #202020; }
.hardware-list li.selected { background: var(--selected); }
.hardware-list li.has-problem .item-label::after { content: " ⚠"; color: var(--error); }
.item-summary { color: var(--muted); font-size: 0.88em; overflow-wrap: anywhere; }
.settings-list-actions { display: flex; gap: 6px; padding-top: 8px; }
.settings-panel { overflow: auto; padding: 4px 20px 16px; display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }
.settings-panel h3 { margin: 6px 0 4px; }
.settings-panel .field { max-width: 100%; }
.settings-panel textarea { width: min(520px, 100%); }
.settings-footer, .wizard-footer {
    grid-column: 1 / -1;
    display: flex;
    gap: 8px;
    align-items: center;
    padding: 10px 18px;
    border-top: 1px solid var(--line);
}
.settings-notes, .wizard-status { flex: 1; color: var(--muted); font-size: 0.92em; }
.wizard-status.error { color: var(--error); }
ul.problems { color: var(--error); margin: 0; padding-left: 1.2em; }
small.reason { color: var(--muted); }
label.check { display: flex; gap: 4px; align-items: baseline; }
.image-picker { display: flex; flex-direction: column; gap: 6px; border-left: 2px solid #2c2c2c; padding-left: 10px; }
.service-images { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; }
.wizard { display: flex; flex-direction: column; height: 100%; }
.wizard-steps { display: flex; flex-wrap: wrap; gap: 4px 16px; list-style: none; padding: 0; margin: 4px 0 8px; color: var(--muted); }
.wizard-steps li.current { color: var(--text); font-weight: 600; }
.wizard-steps li.done::after { content: " ✓"; }
.wizard-body { flex: 1; overflow: auto; padding: 8px 18px; display: flex; flex-direction: column; gap: 10px; }
.wizard-body fieldset { border: 1px solid var(--line); border-radius: 4px; display: flex; flex-direction: column; gap: 6px; }
.preset-pane { display: grid; grid-template-columns: 230px 1fr; gap: 16px; min-height: 0; }
.preset-list { list-style: none; margin: 0; padding: 0; overflow: auto; }
.preset-list li { padding: 6px 10px; border-radius: 4px; cursor: pointer; display: flex; justify-content: space-between; gap: 6px; }
.preset-list li:hover { background: #202020; }
.preset-list li.selected { background: var(--selected); }
.badge { font-size: 0.78em; color: #ffcc80; border: 1px solid #6b5a36; border-radius: 3px; padding: 0 4px; white-space: nowrap; }
.preset-detail h4 { margin: 10px 0 4px; }
.indent { margin-left: 22px; display: flex; flex-direction: column; gap: 8px; }
details.checklist { margin: 10px 0; }

/* the console */
.console { padding: 8px 12px; }
.console-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-bottom: 8px; }
.toolbar-gap { flex: 1; }
.console-name { color: var(--muted); margin-left: 8px; }
.console-notice:empty { display: none; }
.console-notice { margin-bottom: 8px; }
.console-main { display: flex; gap: 10px; align-items: flex-start; }
.console-screen { overflow: auto; min-width: 0; }
.console-drawer {
    flex: 0 0 360px;
    max-width: 100%;
    background: var(--panel);
    border: 1px solid var(--line);
    border-radius: 4px;
    padding: 8px 10px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: calc(100vh - 150px);
    overflow: auto;
}
.console-drawer header { display: flex; justify-content: space-between; align-items: center; }
.console-drawer h2 { margin: 0; font-size: 1em; }
.terminal { min-height: 300px; }
.console-status { color: var(--muted); margin-top: 6px; min-height: 1.45em; display: flex; flex-wrap: wrap; gap: 4px 18px; font-size: 0.92em; }
.console-status span:empty { display: none; }
.status-state { color: var(--text); }
button.pressed { background: var(--selected); border-color: #4a6a9a; }
.error { color: var(--error); }

/* menus */
.menu { position: relative; display: inline-block; }
.menu-list {
    position: absolute;
    top: calc(100% + 2px);
    left: 0;
    z-index: 100;
    min-width: 240px;
    background: var(--panel);
    border: 1px solid #444;
    border-radius: 4px;
    padding: 4px 0;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
}
.menu-list[hidden] { display: none; }
.menu-item { text-align: left; border: 0; border-radius: 0; background: none; padding: 5px 14px; white-space: pre; }
.menu-item:hover:not(:disabled), .menu-item:focus-visible { background: var(--selected); outline: none; }
.menu-separator { border-top: 1px solid var(--line); margin: 4px 0; }

/* theatre mode: the screen alone, as large as fits */
body.theatre-body { overflow: hidden; }
body.theatre-body footer { display: none; }
.console.theatre { position: fixed; inset: 0; z-index: 50; background: #000; padding: 0; display: flex; align-items: center; justify-content: center; }
.console.theatre .console-toolbar, .console.theatre .console-status, .console.theatre .console-notice, .console.theatre .console-drawer { display: none; }
.theatre-show-ui { position: fixed; top: 8px; right: 8px; z-index: 60; opacity: 0.6; }
.theatre-show-ui:hover { opacity: 1; }
#screen_container { position: relative; display: inline-block; outline: 1px solid #555; background: #000; }
#screen {
    white-space: pre;
    position: relative;
    font-family: Liberation Mono, DejaVu Sans Mono, Courier New, monospace;
    font-weight: bold;
    font-size: 15px;
    line-height: normal;
    color: #fff;
    transform-origin: top left;
}
#vga { background-color: #000; touch-action: none; transform-origin: top left; }
#screen_container:fullscreen { display: flex !important; align-items: center; justify-content: center; }
#screen_container:fullscreen #vga { width: auto !important; height: 100% !important; }
.phone_keyboard { position: absolute; opacity: 0; width: 0; height: 0; resize: none; left: -9999em; top: 0; z-index: -10; }

footer { color: var(--muted); padding: 10px 16px; border-top: 1px solid var(--line); font-size: 0.9em; }

@media (max-width: 700px) {
    .settings { grid-template-columns: 1fr; grid-template-rows: auto auto 1fr auto; }
    .settings-list { border-right: 0; border-bottom: 1px solid var(--line); max-height: 34vh; }
    .preset-pane { grid-template-columns: 1fr; }
    .library { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
    .library-list { border-right: 0; border-bottom: 1px solid var(--line); }
    .library-summary { padding: 16px; }
    .console { padding: 8px 16px; }
    .console-main { flex-direction: column; }
    .console-drawer { flex-basis: auto; width: 100%; }
}

/* the wizard's Android image package (docs/android-images-plan.md I3) */
.drop-zone { border: 2px dashed var(--line); border-radius: 6px; padding: 8px 12px; margin: 8px 0; }
.drop-zone.over { border-color: var(--accent); background: var(--selected); }
                   source/v64/src/app/browser_disks.js                                                                 0000644 0000000 0000000 00000027437 00000000000 014466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// Browser disks, managed (docs/vm-manager-plan.md "浏览器磁盘（OPFS）", "管理",
// U6): images in the browser's private file system (v86/disks/<id>.img, its
// record <id>.json beside it, src/opfs_disk.js), made empty, imported from a
// URL or a file (a copy: the source stays as it is; checked with SHA-256),
// exported, deleted; the space they take. A machine names one with the url
// "opfs:v86/disks/<id>.img" (an image of kind "browser").

import { SHA256 } from "../image/sha256.js";
import { new_id } from "./vm_config.js";

/** @typedef {{id: string, path: string, size: number, label: string, created: string, generation: number}} BrowserDisk */

const DISKS = ["v86", "disks"];
/** The prefix of a browser disk's path (an image's `path`) */
export const DISK_PATH = DISKS.join("/") + "/";

/**
 * The directory of the browser disks (made when missing)
 * @return {Promise<FileSystemDirectoryHandle>}
 */
async function disks_directory()
{
    let dir = await navigator.storage.getDirectory();
    for(const name of DISKS) dir = await dir.getDirectoryHandle(name, { create: true });
    return dir;
}

/**
 * A disk's path of its id
 * @param {string} id
 */
export function disk_path(id)
{
    return DISK_PATH + id + ".img";
}

/**
 * The id of a disk's path, or "" for another path
 * @param {string} path
 */
export function disk_id(path)
{
    const match = /^v86\/disks\/([A-Za-z0-9_-]+)\.img$/.exec(path);
    return match ? match[1] : "";
}

/**
 * @param {FileSystemDirectoryHandle} dir
 * @param {string} id
 * @return {Promise<any>}
 */
async function read_record(dir, id)
{
    try
    {
        return JSON.parse(await (await (await dir.getFileHandle(id + ".json")).getFile()).text());
    }
    catch(e)
    {
        return {};
    }
}

/**
 * @param {FileSystemDirectoryHandle} dir
 * @param {string} id
 * @param {any} record
 */
async function write_record(dir, id, record)
{
    const writable = await (await dir.getFileHandle(id + ".json", { create: true })).createWritable();
    await writable.write(JSON.stringify(record));
    await writable.close();
}

/**
 * The browser disks
 * @return {Promise<BrowserDisk[]>}
 */
export async function list_disks()
{
    const dir = await disks_directory();
    const disks = [];
    for await (const [name, handle] of /** @type {any} */ (dir).entries())
    {
        const match = /^([A-Za-z0-9_-]+)\.img$/.exec(name);
        if(!match || handle.kind !== "file") continue;
        const file = await handle.getFile();
        const record = await read_record(dir, match[1]);
        disks.push({ id: match[1], path: disk_path(match[1]), size: file.size, label: record.label || match[1],
            created: record.created || new Date(file.lastModified).toISOString(), generation: record.generation || 1 });
    }
    return disks.sort((a, b) => a.label.localeCompare(b.label));
}

/**
 * The browser's room for a new disk: refused (thrown) when there is not
 * enough; persistent storage asked for (once, with the first disk)
 * @param {number} size
 * @param {{get_pref: (name: string) => Promise<any>, put_pref: (name: string, value: any) => Promise<void>}} [prefs]
 */
export async function make_room(size, prefs)
{
    const estimate = await navigator.storage.estimate();
    const free = (estimate.quota || 0) - (estimate.usage || 0);
    if(estimate.quota && free < size)
    {
        throw new Error("The browser gives this site " + Math.floor(free / 1048576) + " MB more, the disk needs " + Math.ceil(size / 1048576) + " MB");
    }
    if(prefs && !await prefs.get_pref("persist_asked"))
    {
        await prefs.put_pref("persist_asked", true);
        await navigator.storage.persist?.().catch(() => false);
    }
}

/**
 * A new empty browser disk (zeros; sparse where the browser keeps it so)
 * @param {number} size bytes, a multiple of 512
 * @param {string} label
 * @param {Parameters<typeof make_room>[1]} [prefs]
 * @return {Promise<BrowserDisk>}
 */
export async function create_disk(size, label, prefs)
{
    if(!Number.isSafeInteger(size) || size <= 0 || size % 512) throw new Error("A disk's size is a positive multiple of 512 bytes");
    await make_room(size, prefs);
    const dir = await disks_directory();
    const id = new_id();
    const writable = await (await dir.getFileHandle(id + ".img", { create: true })).createWritable();
    await writable.truncate(size);
    await writable.close();
    const created = new Date().toISOString();
    await write_record(dir, id, { uuid: new_id(), generation: 1, size, label, created });
    return { id, path: disk_path(id), size, label, created, generation: 1 };
}

/**
 * A copy of an image as a new browser disk: its bytes streamed in, hashed
 * (SHA-256) on the way, the copy read back and hashed again
 * @param {File | string} source a file of the user's, or a URL
 * @param {string} label
 * @param {{prefs?: Parameters<typeof make_room>[1], progress?: (done: number, total: number) => void}} [options]
 * @return {Promise<BrowserDisk & {sha256: string}>}
 */
export async function import_disk(source, label, options = {})
{
    let stream, total;
    if(typeof source === "string")
    {
        const response = await fetch(source);
        if(!response.ok || !response.body) throw new Error("The image at " + source + " cannot be read (" + response.status + ")");
        total = Number(response.headers.get("Content-Length")) || 0;
        stream = response.body;
    }
    else
    {
        total = source.size;
        stream = source.stream();
    }
    if(total) await make_room(total, options.prefs);
    const dir = await disks_directory();
    const id = new_id();
    const handle = await dir.getFileHandle(id + ".img", { create: true });
    const writable = await handle.createWritable();
    const hash = new SHA256();
    let done = 0;
    try
    {
        const reader = stream.getReader();
        for(;;)
        {
            const { done: end, value } = await reader.read();
            if(end) break;
            hash.update(value);
            await writable.write(value);
            done += value.length;
            options.progress && options.progress(done, total);
        }
        if(total && done !== total) throw new Error("The image has " + done + " bytes, " + total + " were announced");
        if(done % 512) throw new Error("The image has " + done + " bytes, not a whole number of 512-byte sectors");
        await writable.close();
    }
    catch(e)
    {
        await writable.abort().catch(() => {});
        await dir.removeEntry(id + ".img").catch(() => {});
        throw e;
    }
    const sha256 = hash.hex();
    // (the copy read back: the same bytes)
    const check = new SHA256();
    const copy = await handle.getFile();
    const reader = copy.stream().getReader();
    for(;;)
    {
        const { done: end, value } = await reader.read();
        if(end) break;
        check.update(value);
    }
    if(copy.size !== done || check.hex() !== sha256)
    {
        await dir.removeEntry(id + ".img").catch(() => {});
        throw new Error("The copy differs from the image (SHA-256)");
    }
    const created = new Date().toISOString();
    await write_record(dir, id, { uuid: new_id(), generation: 1, size: done, label, created, sha256,
        source: typeof source === "string" ? source : source.name });
    return { id, path: disk_path(id), size: done, label, created, generation: 1, sha256 };
}

/**
 * A new browser disk that a worker writes (src/app/android_import.js): its
 * id and path, the room made; then finish_disk, or delete_disk
 * @param {number} size
 * @param {Parameters<typeof make_room>[1]} [prefs]
 * @return {Promise<{id: string, path: string}>}
 */
export async function reserve_disk(size, prefs)
{
    await make_room(size, prefs);
    await disks_directory();
    const id = new_id();
    return { id, path: disk_path(id) };
}

/**
 * A disk reserve_disk gave, written: its record
 * @param {string} id
 * @param {string} label
 * @param {Object} fields more of the record (source, the package's kind)
 * @return {Promise<BrowserDisk>}
 */
export async function finish_disk(id, label, fields = {})
{
    const dir = await disks_directory();
    const size = (await (await dir.getFileHandle(id + ".img")).getFile()).size;
    const created = new Date().toISOString();
    await write_record(dir, id, Object.assign({ uuid: new_id(), generation: 1, size, label, created }, fields));
    return { id, path: disk_path(id), size, label, created, generation: 1 };
}

/**
 * A browser disk's contents replaced by an image's (a UEFI machine's variable
 * store reset to the template, docs/uefi.md; a TPM's state cleared to zeros,
 * docs/tpm.md): written in place, its generation moved on (snapshots of it
 * before no longer fit). Not while a machine has it open: the browser
 * refuses the write then.
 * @param {string} id
 * @param {string | Uint8Array<ArrayBuffer>} source a URL, or the bytes
 * @return {Promise<undefined>}
 */
export async function reset_disk(id, source)
{
    /** @type {Uint8Array<ArrayBuffer>} */
    let bytes;
    if(typeof source === "string")
    {
        const response = await fetch(source);
        if(!response.ok) throw new Error("The image at " + source + " cannot be read (" + response.status + ")");
        bytes = new Uint8Array(await response.arrayBuffer());
    }
    else
    {
        bytes = source;
    }
    if(bytes.length % 512) throw new Error("The image has " + bytes.length + " bytes, not a whole number of 512-byte sectors");
    const dir = await disks_directory();
    let writable;
    try
    {
        writable = await (await dir.getFileHandle(id + ".img")).createWritable();
    }
    catch(e)
    {
        throw new Error("The disk is in use (" + e.message + "): power the machine off first");
    }
    await writable.write(bytes);
    await writable.truncate(bytes.length);
    await writable.close();
    const record = await read_record(dir, id);
    record.generation = (record.generation || 1) + 1;
    record.size = bytes.length;
    await write_record(dir, id, record);
}

/**
 * A browser disk's image as a File (to export it, or read it)
 * @param {string} id
 * @return {Promise<File>}
 */
export async function disk_file(id)
{
    return (await (await disks_directory()).getFileHandle(id + ".img")).getFile();
}

/**
 * Save a browser disk as a file of the user's: streamed into the file where
 * the browser lets the page write one (Chromium), else downloaded as it is
 * (the browser reads the file as it saves it, not into memory)
 * @param {string} id
 * @param {string} name
 * @param {(parts: BlobPart[], name: string) => void} download
 */
export async function export_disk(id, name, download)
{
    const file = await disk_file(id);
    const picker = /** @type {any} */ (window).showSaveFilePicker;
    if(typeof picker === "function")
    {
        let handle;
        try { handle = await picker({ suggestedName: name }); }
        catch(e) { if(e.name === "AbortError") return; throw e; }
        const writable = await handle.createWritable();
        await file.stream().pipeTo(writable);
        return;
    }
    download([file], name);
}

/**
 * Delete a browser disk and its record; refused while a machine uses it (another tab's)
 * @param {string} id
 */
export async function delete_disk(id)
{
    const dir = await disks_directory();
    try
    {
        await dir.removeEntry(id + ".img");
    }
    catch(e)
    {
        if(e.name === "NotFoundError") return;
        if(e.name === "NoModificationAllowedError" || e.name === "InvalidModificationError") throw new Error("The disk is in use: power its machine off first");
        throw e;
    }
    await dir.removeEntry(id + ".json").catch(() => {});
}

/**
 * Rename a browser disk (its label)
 * @param {string} id
 * @param {string} label
 */
export async function rename_disk(id, label)
{
    const dir = await disks_directory();
    const record = await read_record(dir, id);
    record.label = label;
    await write_record(dir, id, record);
}
                                                                                                                                                                                                                                 source/v64/src/app/disk_service_client.js                                                           0000644 0000000 0000000 00000010524 00000000000 015603  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The VM manager's side of a disk service (docs/vm-manager-plan.md "磁盘服务
// 的创建与列出", tools/disk-service.mjs): its images (list), a new image
// (create), and whether a URL is a disk service at all (probe). Its images
// are a configuration's images of kind "url" with disk_option "read_write".

/** The local disk service of make run (tools/dev-server.py) */
export const LOCAL_SERVICE = "http://127.0.0.1:8471/";

/**
 * @typedef {{url: string, token?: string}} Service a disk service's URL and its token (if it needs one)
 * @typedef {{name: string, size: number, modified: string, writer: boolean}} ServiceImage
 * @typedef {{images: ServiceImage[], create: boolean, max_size: number}} ServiceList
 */

/** A disk service's refusal: its code (create, name, size, exists, no_space, token, origin, ...) and status */
export class ServiceError extends Error
{
    /**
     * @param {string} message
     * @param {string} code
     * @param {number} status
     */
    constructor(message, code, status)
    {
        super(message);
        this.code = code;
        this.status = status;
    }
}

/**
 * The service's URL, ending in /
 * @param {string} url
 * @return {string}
 */
export function service_base(url)
{
    return url.endsWith("/") ? url : url + "/";
}

/**
 * The URL of an image of the service
 * @param {Service} service
 * @param {string} name
 * @return {string}
 */
export function image_url(service, name)
{
    return service_base(service.url) + encodeURIComponent(name);
}

/**
 * @param {Service} service
 * @param {string} name "" for the service itself
 * @param {Object<string, string>} headers
 * @return {Promise<any>}
 */
async function operate(service, name, headers)
{
    const all = Object.assign({}, headers);
    if(service.token) all["Authorization"] = "Bearer " + service.token;
    let response;
    try
    {
        response = await fetch(service_base(service.url) + (name ? encodeURIComponent(name) : ""), { method: "POST", headers: all, cache: "no-store" });
    }
    catch(e)
    {
        throw new ServiceError("The disk service at " + service.url + " cannot be reached, or does not accept this page " +
            "(start it with --origin " + globalThis.location?.origin + ")", "unreachable", 0);
    }
    if(!response.headers.get("X-V86-Disk-Protocol"))
    {
        throw new ServiceError(service.url + " is not a disk service that lists and creates images (an older version answers " +
            response.status + ")", "not_a_service", response.status);
    }
    const body = await response.json().catch(() => ({}));
    if(!response.ok) throw new ServiceError(body.error || "The disk service refused (" + response.status + ")", body.code || "refused", response.status);
    return body;
}

/**
 * The service's images, and whether it creates new ones
 * @param {Service} service
 * @return {Promise<ServiceList>}
 */
export async function list_images(service)
{
    return operate(service, "", { "X-V86-Disk-Op": "list" });
}

/**
 * A new image of zeros in the service's directory
 * @param {Service} service
 * @param {string} name a name ending in .img
 * @param {number} size bytes, a multiple of 512
 * @return {Promise<{name: string, size: number, url: string}>}
 */
export async function create_image(service, name, size)
{
    return operate(service, name, { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": String(size) });
}

/**
 * Whether a disk service answers at the URL, and what it has
 * @param {Service} service
 * @return {Promise<{ok: true, list: ServiceList} | {ok: false, reason: string, code: string}>}
 */
export async function probe(service)
{
    try
    {
        return { ok: true, list: await list_images(service) };
    }
    catch(e)
    {
        return { ok: false, reason: e.message, code: e.code || "error" };
    }
}

/**
 * A name for a new image of the service: the machine's name in letters,
 * digits and dashes, not taken yet
 * @param {string} machine
 * @param {ServiceImage[]} images
 * @return {string}
 */
export function new_image_name(machine, images)
{
    const base = machine.normalize("NFKD").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase().slice(0, 100) || "disk";
    const taken = new Set(images.map(image => image.name));
    for(let i = 1; ; i++)
    {
        const name = base + (i === 1 ? "" : "-" + i) + ".img";
        if(!taken.has(name)) return name;
    }
}
                                                                                                                                                                            source/v64/src/app/emulator_bridge.js                                                               0000644 0000000 0000000 00000006743 00000000000 014747  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The VM manager's only way to the emulator (docs/vm-manager-plan.md G1):
// new V86() and its public methods and events (v86.d.ts), as build/libv86.mjs
// gives them; the page's options of a start (src/browser/vm_options.js); the
// graphics proxy's bundle.

import { V86 } from "v86";

/** app_debug.html: the library's debug build and the firmware's (its <html data-debug>) */
export const DEBUG_PAGE = document.documentElement.hasAttribute("data-debug");

/** The page is served from this computer (on debug pages: the local network relay) */
export const ON_LOCALHOST = ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname);

/**
 * The files' version (?<commit>, for the browser's cache): the page's #version
 * @return {string}
 */
export function query_append()
{
    const version = document.getElementById("version");
    return version ? "?" + version.textContent : "";
}

/**
 * The page's part of the options (settings_to_options's env): its builds,
 * the files' version, the graphics proxy's option, the screen
 * @param {HTMLElement} screen_container
 * @param {boolean} graphics_proxy
 * @param {(message: string) => void} on_proxy_error
 */
export function page_env(screen_container, graphics_proxy, on_proxy_error)
{
    return {
        debug: DEBUG_PAGE,
        query_append: query_append(),
        graphics_proxy: graphics_proxy && {
            "onError": error =>
            {
                console.error("Graphics proxy initialization failed", error);
                on_proxy_error("Graphics proxy failed; VGA remains available: " + error.message);
            },
        },
        screen_container,
    };
}

/**
 * The WebGPU graphics proxy's bundle (build/glbridge), loaded once
 * @return {Promise<void>}
 */
export async function load_graphics_proxy()
{
    if(!(/** @type {any} */ (navigator).gpu))
    {
        throw new Error("WebGPU is unavailable. Use a WebGPU-capable browser over HTTPS or localhost.");
    }
    if(typeof (/** @type {any} */ (window)).V86GraphicsProxy === "function") return;

    // Fetch the current revision so the bundle and shader workers use matching assets.
    const response = await fetch("build/glbridge/manifest.json", { cache: "no-store" });
    if(!response.ok) throw new Error("Graphics bundle is missing. Run make glbridge and reload.");
    const manifest = await response.json();
    await new Promise((resolve, reject) =>
    {
        const script = document.createElement("script");
        script.src = "build/glbridge/libv86-webgpu.js?v=" + encodeURIComponent(manifest["revision"]);
        script.onload = () => resolve(undefined);
        script.onerror = () =>
        {
            script.remove();
            reject(new Error("Could not load the graphics bundle. Run make glbridge and reload."));
        };
        document.head.appendChild(script);
    });
    if(typeof (/** @type {any} */ (window)).V86GraphicsProxy !== "function")
    {
        throw new Error("Graphics bundle did not initialize. Check the browser console and rebuild with make glbridge.");
    }
}

/**
 * Start the emulator with the options; null when a test records the options
 * instead (window.v86_record_options, as the old page's start_emulation)
 * @param {Object} options
 * @return {V86 | null}
 */
export function create_emulator(options)
{
    const record = /** @type {any} */ (window).v86_record_options;
    if(typeof record === "function")
    {
        record(options);
        return null;
    }
    return new V86(/** @type {any} */ (options));
}
                             source/v64/src/app/guest_presets.js                                                                 0000644 0000000 0000000 00000042766 00000000000 014504  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The new machine wizard's guest presets (docs/vm-manager-plan.md "客户机预设",
// U3): for each system, the whole hardware (a configuration's defaults),
// whether a document or test of the repository verified it, how it is
// installed, the steps after the installation and the known problems, from
// the systems' documents (docs/dos.md, windows-31x.md, windows-9x.md,
// windows-nt.md, multicore.md, x86-64.md, gpu-devices.md, aarch64.md).

import { new_config } from "./vm_config.js";
import { DEFAULT_GLES_VERSION } from "../android/devices.js";
import { fitted } from "./vm_model.js";

/** @typedef {import("./vm_config.js").VMConfig} VMConfig */

/**
 * @typedef {Object} Preset
 * @property {string} id
 * @property {string} name
 * @property {string} guest the configuration's guest (its family)
 * @property {boolean} verified
 * @property {string} basis the document or test it rests on; for one not verified, the closest verified one
 * @property {Array<"cdrom" | "floppy" | "disk" | "direct" | "android">} install the ways to install it, the usual first:
 *     from a CD or a floppy, an existing hard disk image (Android's: its GPT disk, which its bootloader boots),
 *     a kernel and initrd (and its CD as a read-only disk), an Android image package (made into a disk)
 * @property {string} install_text
 * @property {number} disk_mb the new empty disk's default size
 * @property {"memory" | "browser" | "service"} disk_location where its new disk goes by default
 * @property {string[]} checklist the steps after the installation
 * @property {string[]} issues the known problems
 * @property {(c: any) => void} hardware its hardware on a new configuration
 */

const MB = 1;
const GB = 1024;

/**
 * A PC's hardware
 * @param {{cpu?: string, memory: number, cores?: number, adapter?: string, vram?: number, nic?: string, sound?: string,
 *     acpi?: boolean, cpuid_level?: number, tablet?: boolean, usb?: string, q35?: boolean, uefi?: boolean,
 *     secure_boot?: boolean, tpm?: boolean}} h
 */
function pc(h)
{
    return c =>
    {
        c.cpu.type = h.cpu || "x86";
        c.cpu.cores = h.cores || 1;
        c.memory.mb = h.memory;
        c.machine.type = "i440fx";
        c.machine.acpi = !!h.acpi;
        c.display.adapter = h.adapter || "bochs_vga";
        c.display.vram_mb = h.vram || 8;
        c.network[0].device = h.nic || "ne2k";
        if(c.network[0].device === "none") { c.network[0].backend = "none"; c.network[0].relay_url = ""; }
        c.sound.device = h.sound || "sb16";
        if(h.cpuid_level) c.advanced.cpuid_level = h.cpuid_level;
        // (the USB tablet: an absolute pointer for the systems that have its
        // drivers; xHCI for the systems with its driver, EHCI for XP to 7)
        c.usb = h.tablet ? { controller: h.usb || "uhci", tablet: true, disks: [] } : null;
        // (Windows 11's machine: Q35 with AHCI, UEFI with Secure Boot and
        // Microsoft's keys, a TPM 2.0: docs/uefi.md, docs/tpm.md)
        if(h.q35) c.machine.type = "q35";
        if(h.uefi) c.machine.firmware = "uefi";
        if(h.secure_boot) Object.assign(c.machine, { secure_boot: true, secure_boot_keys: "microsoft" });
        if(h.tpm) c.tpm = { state: null };
    };
}

const WINDOWS_81 = {
    cpu: "x86_64", memory: 2048 * MB, cores: 2, adapter: "vmware_svga", vram: 16, nic: "e1000", sound: "hd_audio", acpi: true, tablet: true, usb: "xhci",
};
const WINDOWS_81_CHECKLIST = [
    "Display driver, one of: VMware Tools 13.1.5's vm3d (install KB2919355 first), or the test-signed viogpudo 0.1.240 (2D only)",
    "Set the display driver's TDR timeout to 60 seconds",
    "Before moving the disk from IDE to Q35 (AHCI), enable storahci",
];
const WINDOWS_81_ISSUES = [
    "Too slow without the JIT (do not turn it off)",
];

/** @type {Preset[]} */
export const PRESETS = [
    {
        id: "dos", name: "DOS (MS-DOS 6.22, FreeDOS)", guest: "dos", verified: true, basis: "docs/dos.md, tests/full/run.js",
        install: ["floppy", "cdrom"], install_text: "MS-DOS from its floppies, FreeDOS from its CD (or its boot floppy)",
        disk_mb: 128 * MB, disk_location: "memory", checklist: [], issues: [],
        hardware: pc({ memory: 64 * MB }),
    },
    {
        id: "windows3x", name: "Windows 3.x", guest: "windows3x", verified: true, basis: "docs/windows-31x.md",
        install: ["floppy"], install_text: "Install MS-DOS 6.22 first, then Windows from its floppies",
        disk_mb: 128 * MB, disk_location: "memory",
        checklist: ["Windows for Workgroups 3.11: the keyboard fix (vkda.386)", "The Sound Blaster 16 driver", "The vbesvga display driver"],
        issues: ["Windows 3.1 has no usable network card driver: use the modem and PPP"],
        hardware: pc({ memory: 64 * MB }),
    },
    ...[["windows95", "Windows 95", 64], ["windows98", "Windows 98", 256], ["windowsme", "Windows ME", 256]].map(([id, name, memory]) => ({
        id: /** @type {string} */ (id), name: /** @type {string} */ (name), guest: "windows9x", verified: true,
        basis: "tests/r1/windows9x.mjs (the site's Windows 98 state), docs/windows-9x.md",
        install: /** @type {Array<"cdrom">} */ (["cdrom"]), install_text: "From the CD, with the Patcher9x floppy",
        disk_mb: 2 * GB, disk_location: /** @type {"memory"} */ ("memory"), checklist: [],
        issues: ["Retail CDs need FIX95CPU or Patcher9x (#1556)", "The floppy drive works in MS-DOS compatibility mode only",
            "No ACPI: the images have no ACPI HAL"],
        hardware: pc({ memory: /** @type {number} */ (memory) * MB, vram: 16 }),
    })),
    {
        id: "windowsnt4", name: "Windows NT 4", guest: "windowsnt", verified: true, basis: "docs/windows-nt.md",
        install: ["cdrom"], install_text: "From the CD", disk_mb: 2 * GB, disk_location: "memory", checklist: [], issues: [],
        hardware: pc({ memory: 512 * MB, vram: 16, cpuid_level: 2 }),
    },
    {
        id: "windows2000", name: "Windows 2000", guest: "windowsnt", verified: true, basis: "docs/windows-nt.md, tests/full/run.js",
        install: ["cdrom"], install_text: "From the CD", disk_mb: 2 * GB, disk_location: "memory",
        checklist: ["Switch the HAL to \"Standard PC\"", "The Sound Blaster 16 driver"], issues: [],
        hardware: pc({ memory: 512 * MB, vram: 16 }),
    },
    {
        id: "windowsxp", name: "Windows XP", guest: "windowsnt", verified: true, basis: "the owner's XP performance gate (tests/ir/performance/xp_boot.mjs)",
        install: ["cdrom"], install_text: "From the CD", disk_mb: 4 * GB, disk_location: "memory",
        checklist: ["D3D programs such as 3DMark06: d3d9.dll from driver.iso"],
        issues: ["Keep the x86 CPU: x86_64 makes XP use its PAE kernel", "XP's and 2000's ACPI HAL is not verified: one core only"],
        hardware: pc({ memory: 2048 * MB, vram: 16, tablet: true, usb: "ehci" }),
    },
    {
        id: "windows81", name: "Windows 8.1 (x64)", guest: "windows", verified: true,
        basis: "tests/x64/windows_boot.mjs, docs/windows-nt.md (from an existing image; installing from the CD in v86 is not verified)",
        install: ["disk", "cdrom"], install_text: "An existing hard disk image", disk_mb: 32 * GB, disk_location: "service",
        checklist: WINDOWS_81_CHECKLIST, issues: WINDOWS_81_ISSUES, hardware: pc(WINDOWS_81),
    },
    {
        id: "windows11", name: "Windows 11 (x64)", guest: "windows", verified: false,
        basis: "Windows 8.1's devices (tests/x64/windows_boot.mjs), its Setup under Secure Boot with Microsoft's keys " +
            "(tests/uefi/windows_setup.mjs), the TPM 2.0 (docs/tpm.md); Windows 11 itself was never tried here",
        install: ["cdrom", "disk"], install_text: "From the CD", disk_mb: 64 * GB, disk_location: "service",
        checklist: WINDOWS_81_CHECKLIST.slice(0, 2), issues: WINDOWS_81_ISSUES.concat([
            "Windows 11 asks for a supported processor model: v86's is not on Microsoft's list",
            "No DirectX 12 / WDDM 2.0 display driver",
        ]),
        hardware: pc(Object.assign({}, WINDOWS_81, { memory: 4096 * MB, q35: true, uefi: true, secure_boot: true, tpm: true })),
    },
    {
        id: "windows7", name: "Windows Vista / 7 / 10", guest: "windows", verified: false,
        basis: "Windows 8.1's settings; Vista's installation CD only starts, 7 and 10 were never tried",
        install: ["cdrom"], install_text: "From the CD", disk_mb: 32 * GB, disk_location: "service",
        checklist: WINDOWS_81_CHECKLIST, issues: WINDOWS_81_ISSUES, hardware: pc(Object.assign({}, WINDOWS_81, { usb: "ehci" })),
    },
    {
        id: "linux", name: "Linux (32-bit)", guest: "linux", verified: true, basis: "Linux 4.16, 6.8, 6.18: docs/multicore.md, docs/acpi.md, docs/q35.md",
        install: ["cdrom"], install_text: "From a live or installation CD", disk_mb: 8 * GB, disk_location: "memory", checklist: [], issues: [],
        hardware: pc({ memory: 512 * MB, acpi: true, tablet: true, usb: "xhci" }),
    },
    {
        id: "linux64", name: "Linux (x86_64)", guest: "linux", verified: true, basis: "Alpine 3.24: docs/x86-64.md, docs/gpu-devices.md",
        install: ["cdrom"], install_text: "From a live or installation CD", disk_mb: 8 * GB, disk_location: "memory", checklist: [], issues: [],
        hardware: pc({ cpu: "x86_64", memory: 1024 * MB, cores: 2, adapter: "virtio_gpu", nic: "virtio", acpi: true, tablet: true, usb: "xhci" }),
    },
    {
        id: "linux_arm64", name: "Linux (arm64)", guest: "linux", verified: true, basis: "Alpine 3.24 aarch64: docs/aarch64.md, tests/a64/linux_boot.mjs",
        install: ["direct"], install_text: "The kernel and initrd of the ISO's boot/ directory, the ISO as a read-only virtio disk",
        disk_mb: 8 * GB, disk_location: "browser", checklist: [],
        issues: ["Only with the page tier (the JIT on), in the CPU Worker"],
        hardware: c =>
        {
            c.cpu.type = "arm64";
            // (Alpine's kernel has COMPAT: armhf programs run too)
            c.cpu.profile = "generic-arm64-compat32";
            c.machine.type = "virt";
            c.machine.acpi = false;
            c.cpu.cores = 4;
            c.memory.mb = 1024 * MB;
            c.display.adapter = "virtio_gpu";
            c.network[0].device = "virtio";
            c.sound.device = "none";
        },
    },
    {
        id: "linux_arm32", name: "Linux (ARM 32-bit)", guest: "linux", verified: true,
        basis: "Alpine 3.24 armv7 (netboot): docs/aarch32-plan.md R5, tests/a32/linux_boot.mjs",
        install: ["direct"], install_text: "The netboot kernel and initramfs (vmlinuz-lts, initramfs-lts), its modloop and packages from a disk or the network",
        disk_mb: 4 * GB, disk_location: "browser", checklist: [],
        issues: ["Only with the page tier (the JIT on)", "The serial console only: the 32-bit virt machine's display is not verified"],
        hardware: c =>
        {
            c.cpu.type = "arm32";
            c.machine.type = "virt";
            c.machine.acpi = false;
            c.cpu.cores = 2;
            c.memory.mb = 512 * MB;
            c.display.adapter = "none";
            c.network[0].device = "virtio";
            c.sound.device = "none";
            c.kernel = { bzimage: null, initrd: null, cmdline: "console=ttyAMA0", multiboot: null, from_filesystem: false };
        },
    },
    {
        id: "android16", name: "Android (arm64)", guest: "android", verified: true,
        basis: "boot_completed and the A9 scenario on gfxstream with the official images: docs/aarch64.md, docs/gfxstream-plan.md G5",
        install: ["android", "disk"], install_text: "Android 16, and 17 as a GSI on that phone: an Android image package (Cuttlefish's images zip, " +
            "and a GSI's, made into a disk: the image's own GPU " +
            "drivers on gfxstream), or tools/a64_android.mjs's disk.img: v64's bootloader reads the kernel and initrd from the disk's boot " +
            "partitions (docs/android-images-plan.md I2, I3)",

        disk_mb: 8 * GB, disk_location: "browser", checklist: [],
        issues: ["Only with the page tier, in the CPU Worker", "The first boot takes about 20 minutes on 4 cores", "See docs/aarch64.md"],
        hardware: c =>
        {
            c.cpu.type = "arm64";
            c.machine.type = "virt";
            c.machine.acpi = false;
            c.cpu.cores = 4;
            c.memory.mb = 1536 * MB;
            c.display.adapter = "virtio_gpu";
            // (gfxstream: the official images' own drivers, vulkan.ranchu and ANGLE; Venus needs
            // initrd-venus.img's libvulkan; SwiftShader's desktop takes too long to draw)
            c.display.proxy = true;
            c.display.vulkan = "gfxstream";
            c.sound.device = "virtio";
            // (three virtio-net cards, as Cuttlefish's: its Wi-Fi, the third, on the fetch backend)
            c.network = [0, 1, 2].map(i => ({ device: "virtio", backend: i === 2 ? "fetch" : "none", relay_url: "", mtu: 1500, mac_address_translation: false }));
            c.virt = { transport: "pci", input: ["keyboard", "multitouch"], console_ports: 18, vsock: true, gpu_pci_slot: 2 };
            // (the bootloader: the disk's kernel and initrd, bootconfig with Venus's keys)
            c.android = { device: "cf_arm64_only_phone", gpu_mode: "gfxstream", vendor_ramdisk: "release", debug_ramdisk: null, selinux: "enforcing", display: "device",
                gles_version: DEFAULT_GLES_VERSION };
        },
    },
    {
        id: "android7_arm32", name: "Android (ARM 32-bit)", guest: "android", verified: true,
        basis: "the SDK's armeabi-v7a-25_r18 image to boot_completed: docs/aarch32-plan.md R7.1, tests/a32/android_boot.mjs",
        install: ["android"], install_text: "Android 7.1: the Android Emulator's system image zip (system-images/android-25/google_apis/armeabi-v7a, " +
            "armeabi-v7a-25_r18.zip), made into a disk: its kernel, ramdisk, system, cache and userdata (docs/android-images-plan.md I6)",
        disk_mb: 4 * GB, disk_location: "browser", checklist: [],
        issues: ["Only with the page tier, in the CPU Worker", "The first boot takes about 7 minutes on 2 cores",
            "The host's GPU draws through WebGPU (docs/gles-proxy-plan.md); without WebGPU the guest's CPU draws, slowly",
            "The guest's clock runs at a tenth of the host's, so that Android's timeouts suit this CPU", "No sound"],
        hardware: c =>
        {
            c.cpu.type = "arm32";
            c.machine.type = "ranchu";
            c.machine.acpi = false;
            c.cpu.cores = 2;
            c.memory.mb = 1024 * MB;
            c.display.adapter = "none";
            c.sound.device = "none";
            c.network = [{ device: "virtio", backend: "fetch", relay_url: "", mtu: 1500, mac_address_translation: false }];
            // (the host's GPU draws its GLES: the CPU when the page has no WebGPU, src/app/ui/console.js)
            c.android = { device: "ranchu_25_armeabi_v7a", gpu_mode: "host", vendor_ramdisk: "release", debug_ramdisk: null, selinux: "enforcing", display: "device",
                gles_version: DEFAULT_GLES_VERSION };
        },
    },
    {
        id: "android_x86_64", name: "Android (x86_64)", guest: "android", verified: false,
        basis: "Linux (x86_64)'s hardware (Alpine 3.24: docs/x86-64.md, docs/gpu-devices.md); Android-x86 was never tried here",
        install: ["cdrom"], install_text: "From Android-x86's 64-bit ISO (android-x86.org, up to Android 9.0): its installer puts it on the hard disk. " +
            "Google's x86_64 emulator images do not boot (from Android 8.0 they draw only through the emulator's host GLES)",
        disk_mb: 8 * GB, disk_location: "browser", checklist: ["Install to the hard disk from the ISO's menu (ext4, with GRUB)"],
        issues: ["Not tried on v64", "Graphics: virtio-gpu's 3D (virgl) or the guest's own software rendering"],
        hardware: pc({ cpu: "x86_64", memory: 2048 * MB, cores: 2, adapter: "virtio_gpu", nic: "virtio", sound: "hd_audio", acpi: true, tablet: true, usb: "xhci" }),
    },
    {
        id: "android_x86", name: "Android (x86)", guest: "android", verified: false,
        basis: "Linux (32-bit)'s hardware (docs/multicore.md, docs/acpi.md); Android-x86 was never tried here",
        install: ["cdrom"], install_text: "From Android-x86's 32-bit ISO (android-x86.org, up to Android 9.0): its installer puts it on the hard disk. " +
            "Google's x86 emulator images do not boot (from Android 8.0 they draw only through the emulator's host GLES)",
        disk_mb: 8 * GB, disk_location: "browser", checklist: ["Install to the hard disk from the ISO's menu (ext4, with GRUB)"],
        issues: ["Not tried on v64", "Graphics: virtio-gpu's 3D (virgl) or the guest's own software rendering"],
        hardware: pc({ memory: 2048 * MB, cores: 2, adapter: "virtio_gpu", nic: "virtio", sound: "hd_audio", acpi: true, tablet: true, usb: "xhci" }),
    },
    {
        id: "other", name: "Other", guest: "other", verified: false, basis: "the old page's machine without changes",
        install: ["cdrom", "floppy", "disk", "direct"], install_text: "Any", disk_mb: 512 * MB, disk_location: "memory", checklist: [], issues: [],
        hardware: () => {},
    },
];

/**
 * A preset by its id
 * @param {string | null} id
 * @return {Preset | undefined}
 */
export function preset(id)
{
    return PRESETS.find(p => p.id === id);
}

/**
 * A new configuration of a preset: its hardware on the defaults, fitted to its machine
 * @param {Preset} p
 * @param {Partial<VMConfig>} [fields] name and the rest
 * @return {VMConfig}
 */
export function preset_config(p, fields = {})
{
    const config = new_config(Object.assign({ name: p.name, guest: p.guest, template: p.id }, fields));
    p.hardware(config);
    return fitted(config).config;
}
          source/v64/src/app/keys.js                                                                          0000644 0000000 0000000 00000005160 00000000000 012546  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// Key combinations for the console's "Send keys" menu (docs/vm-manager-plan.md
// "控制台"): "Ctrl+Alt+Del", "Alt+Tab", "Ctrl+Alt+F2", "Win+R" as PC
// scancodes (set 1, what keyboard_send_scancodes takes): the keys pressed
// in order, released in the reverse order.

/** Make codes; 0xE0xx: an extended key (its E0 prefix) */
const KEYS = {
    esc: 0x01, "1": 0x02, "2": 0x03, "3": 0x04, "4": 0x05, "5": 0x06, "6": 0x07, "7": 0x08, "8": 0x09, "9": 0x0A, "0": 0x0B,
    "-": 0x0C, "=": 0x0D, backspace: 0x0E, tab: 0x0F,
    q: 0x10, w: 0x11, e: 0x12, r: 0x13, t: 0x14, y: 0x15, u: 0x16, i: 0x17, o: 0x18, p: 0x19, "[": 0x1A, "]": 0x1B, enter: 0x1C,
    ctrl: 0x1D, a: 0x1E, s: 0x1F, d: 0x20, f: 0x21, g: 0x22, h: 0x23, j: 0x24, k: 0x25, l: 0x26, ";": 0x27, "'": 0x28, "`": 0x29,
    shift: 0x2A, "\\": 0x2B, z: 0x2C, x: 0x2D, c: 0x2E, v: 0x2F, b: 0x30, n: 0x31, m: 0x32, ",": 0x33, ".": 0x34, "/": 0x35,
    alt: 0x38, space: 0x39, capslock: 0x3A,
    f1: 0x3B, f2: 0x3C, f3: 0x3D, f4: 0x3E, f5: 0x3F, f6: 0x40, f7: 0x41, f8: 0x42, f9: 0x43, f10: 0x44, f11: 0x57, f12: 0x58,
    numlock: 0x45, scrolllock: 0x46,
    home: 0xE047, up: 0xE048, pageup: 0xE049, left: 0xE04B, right: 0xE04D, end: 0xE04F, down: 0xE050, pagedown: 0xE051,
    // (Del: the keypad's code, as the old page sends Ctrl+Alt+Del, which every BIOS takes)
    insert: 0xE052, del: 0x53, win: 0xE05B, menu: 0xE05D, printscreen: 0xE037,
};
/** Other names of the keys */
const ALIASES = { control: "ctrl", delete: "del", escape: "esc", return: "enter", meta: "win", super: "win", cmd: "win", ins: "insert",
    pgup: "pageup", pgdn: "pagedown", " ": "space" };

/** The combinations of the menu */
export const COMBINATIONS = ["Ctrl+Alt+Del", "Alt+Tab", "Alt+F4", "Ctrl+Esc", "Win", "Win+R", "Ctrl+Alt+F1", "Ctrl+Alt+F2", "Ctrl+Alt+Backspace", "PrintScreen"];

/**
 * The scancodes of a combination, its presses and its releases (sent 100 ms
 * later, as the old page sends Alt+Tab); throws for a key it does not know
 * @param {string} text "Ctrl+Alt+Del"
 * @return {{press: number[], release: number[]}}
 */
export function combination_scancodes(text)
{
    const keys = text.split("+").map(k => k.trim().toLowerCase()).filter(Boolean).map(k => ALIASES[k] || k);
    if(!keys.length) throw new Error("No keys");
    const codes = keys.map(k =>
    {
        if(!(k in KEYS)) throw new Error("Unknown key: " + k);
        return KEYS[k];
    });
    const scancodes = (list, release) => list.flatMap(code => (code > 0xFF ? [0xE0] : []).concat([(code & 0xFF) | (release ? 0x80 : 0)]));
    return { press: scancodes(codes, false), release: scancodes(codes.slice().reverse(), true) };
}
                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/app/main.js                                                                          0000644 0000000 0000000 00000001733 00000000000 012521  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The VM manager (docs/vm-manager-plan.md): index.html's page. The address
// decides: ?vm=<id> is a library machine's console, ?profile=custom with an
// image (hda.url, cdrom.url or fda.url, and the old page's other query
// arguments) a console as the old page starts it, anything else the library.

import { open_library } from "./ui/library.js";
import { open_console } from "./ui/console.js";

const args = new URLSearchParams(location.search);
const root = /** @type {HTMLElement} */ (document.getElementById("app"));

if(!globalThis.WebAssembly)
{
    root.textContent = "Your browser is not supported because it doesn't support WebAssembly";
}
else if(args.has("vm"))
{
    open_console(root, { vm: /** @type {string} */ (args.get("vm")) });
}
else if(args.has("profile") && !(args.get("profile") === "custom" && !["hda.url", "cdrom.url", "fda.url"].some(name => args.has(name))))
{
    open_console(root, { query_args: args });
}
else
{
    open_library(root);
}
                                     source/v64/src/app/ui/console.js                                                                    0000644 0000000 0000000 00000162202 00000000000 013653  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The console (docs/vm-manager-plan.md "控制台", U2 and U4): one virtual
// machine in this tab, started from the library (?vm=<id>) or from an old
// page's address (?profile=custom with its images and query arguments, as
// the old page starts it). The toolbar's menus (power, keys, removable devices, view,
// input, sound, tools), the status bar (time, speed, disk, network, display,
// mouse), the drawers (serial terminal, shared folder, details), the disk
// error dialog, and the warning before closing a page with disks written back.
// A library machine runs in one tab at a time (its lock), and suspends into
// a state file of the browser's private storage, resumed when it starts again (U5).

import { h, replace, confirm, inform, dialog, download, pick_file, ask_text, menu_button, format_size } from "./dom.js";
import { VMStore } from "../vm_store.js";
import { read_state, delete_state, write_state, storage_space, state_estimate, machine_digest, hold_machine } from "../vm_state.js";
import { config_to_options, android_display, uefi_vars_template, TPM_STATE_SIZE } from "../vm_config.js";
import { import_disk, create_disk } from "../browser_disks.js";
import { combination_scancodes, COMBINATIONS } from "../keys.js";
import { DEFAULT_FORM, DEFAULT_GRAPHICS_ADAPTER, settings_to_options } from "../../browser/vm_options.js";
import { bool_arg, start_settings } from "../../browser/query_compat.js";
import { DEBUG_PAGE, ON_LOCALHOST, page_env, load_graphics_proxy, create_emulator, query_append } from "../emulator_bridge.js";
import { NIC_LABELS, SOUND_LABELS } from "./panels/devices.js";
import { USB_PORTS } from "../../machine_options.js";

/** @typedef {import("../vm_config.js").VMConfig} VMConfig */
/** @typedef {import("../vm_config.js").Image} Image */

/** The old page's profiles that start themselves after a key press (main.js's hack) */
/** RAM and video memory from which states are saved as V7 streams (the old page's STREAMED_STATE_MEMORY) */
const STREAMED_STATE_MEMORY = 1024 * 1024 * 1024;

/** The screen's scales of the View menu */
const SCALES = [0.5, 1, 1.5, 2, 3];

/**
 * @param {string} text
 */
function set_title(text)
{
    document.title = text + " - v86" + (DEBUG_PAGE ? " - debug" : "");
}

/**
 * 75s, 3m 05s, 1h 02m 05s
 * @param {number} time seconds
 */
export function format_time(time)
{
    const two = n => String(n).padStart(2, "0");
    if(time < 60) return time + "s";
    if(time < 3600) return (time / 60 | 0) + "m " + two(time % 60) + "s";
    return (time / 3600 | 0) + "h " + two((time / 60 | 0) % 60) + "m " + two(time % 60) + "s";
}

/**
 * A packet as Wireshark imports it ("File, Import from Hex Dump": offsets and
 * bytes, 16 to a line; the old page's hex_dump)
 * @param {Uint8Array} data
 * @return {string}
 */
export function hex_dump(data)
{
    const hex = (n, length) => n.toString(16).toUpperCase().padStart(length, "0");
    const lines = [];
    for(let offset = 0; offset < data.length; offset += 16)
    {
        const row = Array.from(data.subarray(offset, offset + 16));
        lines.push(hex(offset, 5) + "   " + row.map(b => hex(b, 2) + " ").join("") + "   ".repeat(16 - row.length) + "  " +
            row.map(x => x >= 33 && x !== 34 && x !== 92 && x <= 126 ? String.fromCharCode(x) : ".").join(""));
    }
    return "\n" + lines.join("\n") + "\n";
}

/**
 * The console's frame: a toolbar, a notice line, the screen and a drawer, a status bar
 */
function console_layout()
{
    const phone_keyboard = /** @type {HTMLTextAreaElement} */ (h("textarea.phone_keyboard", { "aria-label": "Keyboard", autocorrect: "off",
        autocapitalize: "off", spellcheck: "false", tabindex: "0" }));
    const screen_container = h("div#screen_container", null,
        h("div#screen"),
        h("canvas#vga"),
        h("div", { style: { position: "absolute", top: "0", zIndex: "10" } }, phone_keyboard));
    const status = h("div.console-status", { role: "status" });
    const toolbar = h("div.console-toolbar", { role: "toolbar", "aria-label": "Console" });
    const notice = h("div.console-notice");
    const drawer = h("aside.console-drawer", { hidden: true });
    const root = h("div.console", null, toolbar, notice, h("div.console-main", null, h("div.console-screen", null, screen_container), drawer), status);
    return { root, screen_container, status, toolbar, notice, drawer, phone_keyboard };
}

/**
 * The start of an old page's address (?profile=custom with an image: hda.url,
 * cdrom.url or fda.url) and the settings the old page makes of it
 * @param {URLSearchParams} query_args
 * @return {Promise<{error: string} | {profile: any, start: ReturnType<typeof start_settings>, graphics_proxy: boolean}>}
 */
async function address_start(query_args)
{
    const id = query_args.get("profile");
    // (the old page's list of systems with images on its host is not part of this page)
    const profile = null;
    if(!(id === "custom" && ["hda.url", "cdrom.url", "fda.url"].some(name => query_args.has(name))))
    {
        return { error: id === "custom" ? "The address names no image (hda.url, cdrom.url or fda.url)." :
            "There is no system " + JSON.stringify(id) + ": an address names its images, ?profile=custom&hda.url=… (or cdrom.url, fda.url)." };
    }
    // (the old page's form as it is before anyone changes it; on debug.html at localhost, its relay)
    const form = DEBUG_PAGE && ON_LOCALHOST ? Object.assign({}, DEFAULT_FORM, { relay_url: "ws://localhost:8080/" }) : DEFAULT_FORM;
    const graphics_proxy = query_args.has("graphics_proxy") && bool_arg(query_args.get("graphics_proxy"));
    const start = start_settings(profile, query_args, form, { location_args: query_args, origin: location.origin, debug: DEBUG_PAGE, graphics_proxy });
    return { profile, start, graphics_proxy };
}

/**
 * The files a configuration names, picked again or read through their kept
 * handles (the browser asks for permission on a click)
 * @param {VMConfig} config
 * @param {VMStore} store
 * @param {HTMLElement} notice where to ask
 * @return {Promise<Map<Image, File>>}
 */
async function resolve_files(config, store, notice)
{
    /** @type {Map<Image, File>} */
    const files = new Map();
    const images = [config.machine.bios, config.machine.vga_bios, ...config.disks.map(d => d.image), ...(config.usb ? config.usb.disks.map(d => d.image) : []),
        config.cdrom.image,
        ...config.floppies.map(f => f.image), config.kernel?.bzimage, config.kernel?.initrd, config.kernel?.multiboot, config.initial_state];
    for(const image of images)
    {
        if(!image || image.kind !== "file") continue;
        const handle = image.handle ? await store.get_handle(image.handle) : undefined;
        if(handle)
        {
            const access = /** @type {any} */ (handle);
            if(await access.queryPermission?.({ mode: "read" }) !== "granted")
            {
                await new Promise(resolve => replace(notice, h("p", null, "The virtual machine reads " + image.name + " on this computer. ",
                    h("button.primary", { onclick: async () => { if(await access.requestPermission({ mode: "read" }) === "granted") resolve(undefined); } },
                        "Allow access to " + image.name))));
            }
            files.set(image, await handle.getFile());
            continue;
        }
        // (no handle: this browser does not keep them, or the configuration was imported)
        const file = await new Promise(resolve =>
        {
            const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", onchange: () => resolve(input.files?.[0]) }));
            replace(notice, h("p", null, "Choose " + image.name + " (" + image.size + " bytes) on this computer: ", input));
        });
        if(file.size !== image.size)
        {
            throw new Error(file.name + " has " + file.size + " bytes, the virtual machine's " + image.name + " had " + image.size);
        }
        if((file.name !== image.name || file.lastModified !== image.last_modified) &&
            !await confirm("Another file?", file.name + " is not the file the virtual machine was made with (" + image.name +
                ", changed " + new Date(image.last_modified).toLocaleString() + "). Use it anyway?", "Use it"))
        {
            throw new Error("No file for " + image.name);
        }
        files.set(image, file);
    }
    replace(notice);
    return files;
}

/**
 * Save a state as a file of the user's: in one buffer for smaller machines,
 * else a V7 stream written as it is made (straight into a file where the
 * browser lets the page write one)
 * @param {any} emulator
 * @param {any} options the machine's
 * @param {string} name
 */
async function save_state_to_file(emulator, options, name)
{
    let result = null;
    if(!options.extended_memory_size && options.memory_size + (options.vram_size || 0) < STREAMED_STATE_MEMORY)
    {
        try
        {
            result = await emulator.save_state();
        }
        catch(error)
        {
            if(!/RangeError|save_state_stream/.test(String(error && (error.stack || error.message)))) throw error;
        }
    }
    if(result)
    {
        download([result], name);
        return;
    }
    const save_picker = /** @type {any} */ (window).showSaveFilePicker;
    if(typeof save_picker === "function")
    {
        let handle;
        try { handle = await save_picker({ suggestedName: name }); }
        catch(e) { if(e.name === "AbortError") return; throw e; }
        const writable = await handle.createWritable();
        try
        {
            await emulator.save_state_stream(chunk => writable.write(chunk.slice()));
            await writable.close();
        }
        catch(e)
        {
            await writable.abort().catch(() => {});
            throw e;
        }
        return;
    }
    const parts = [];
    await emulator.save_state_stream(chunk => { parts.push(chunk.slice()); });
    download(parts, name);
}

/**
 * Open the console in `root`
 * @param {HTMLElement} root
 * @param {{vm?: string, query_args?: URLSearchParams}} target
 */
export async function open_console(root, target)
{
    const layout = console_layout();
    replace(root, layout.root);
    const set_status = text => { layout.status.dataset.state = text; render_status(); };
    let render_status = () => { layout.status.textContent = layout.status.dataset.state || ""; };
    const fail = text =>
    {
        replace(layout.notice, h("p.error", null, text, " ", h("a", { href: location.pathname }, "Back to the library")));
        set_status("");
    };

    /** @type {any} */
    let options, profile = null, config = null, store = null, lock = null, resume = null;
    const on_proxy_error = text => set_status(text);
    try
    {
        if(target.vm)
        {
            store = await VMStore.open();
            config = await store.get(target.vm);
            if(!config)
            {
                fail("There is no such virtual machine in this browser's library.");
                return;
            }
            set_title(config.name);
            // (one tab at a time: its lock, held until it powers off or the tab closes)
            lock = await hold_machine(config.id);
            if(!lock)
            {
                fail(config.name + " runs in another tab. Close it there first (a machine runs in one tab at a time).");
                return;
            }
            if(config.suspended)
            {
                resume = await resume_choice(config, store, layout.notice);
                if(resume === "cancel")
                {
                    lock.release();
                    location.href = location.pathname;
                    return;
                }
                if(resume !== "resume") config = await store.get(config.id);
            }
            const files = await resolve_files(config, store, layout.notice);
            // (a UEFI machine's variable store, docs/uefi.md: a browser disk
            // made from the template at its first power-on, written back;
            // with Secure Boot and Microsoft's keys, the template with them)
            if(config.machine.firmware === "uefi" && !config.machine.uefi_vars && config.advanced.cpu_worker)
            {
                set_status("Making the UEFI variable store...");
                try
                {
                    const disk = await import_disk(uefi_vars_template(config.machine), config.name + ": UEFI variables");
                    config.machine.uefi_vars = { kind: "browser", path: disk.path, size: disk.size };
                    await store.put(config);
                }
                catch(e)
                {
                    console.warn("The UEFI variable store could not be made (" + e.message + "): the variables stay in memory this time");
                }
            }
            // (a TPM's state, docs/tpm.md: a browser disk of zeros at the first
            // power-on, a new TPM; written back from then on)
            if(config.tpm && !config.tpm.state && config.advanced.cpu_worker)
            {
                set_status("Making the TPM's state store...");
                try
                {
                    const disk = await create_disk(TPM_STATE_SIZE, config.name + ": TPM");
                    config.tpm.state = { kind: "browser", path: disk.path, size: disk.size };
                    await store.put(config);
                }
                catch(e)
                {
                    console.warn("The TPM's state store could not be made (" + e.message + "): the TPM's state stays in memory this time");
                }
            }
            if(config.display.proxy) await load_graphics_proxy();
            // (an emulator image's GLES on the host's GPU, docs/gles-proxy-plan.md
            // E5: the WebGPU renderer's bundle; without WebGPU the guest's CPU
            // draws, this start only: a suspended machine resumes with its own)
            let android_gpu = null;
            if(config.android && config.android.gpu_mode === "host" && !config.display.proxy)
            {
                try
                {
                    await load_graphics_proxy();
                }
                catch(e)
                {
                    if(resume === "resume") throw e;
                    android_gpu = "guest";
                    set_status("The guest's CPU draws Android (" + e.message + ")");
                }
            }
            options = config_to_options(config, Object.assign(page_env(layout.screen_container, config.display.proxy, on_proxy_error),
                { file: image => files.get(image) }));
            if(android_gpu) options.android.gpu_mode = android_gpu;
        }
        else
        {
            const query_args = /** @type {URLSearchParams} */ (target.query_args);
            const result = await address_start(query_args);
            if("error" in result)
            {
                fail(result.error);
                return;
            }
            profile = result.profile;
            if(profile) set_title(profile.name);
            if(result.graphics_proxy)
            {
                set_status("Loading graphics proxy...");
                await load_graphics_proxy();
            }
            options = settings_to_options(result.start.settings,
                Object.assign({ cpu_worker: result.start.cpu_worker }, page_env(layout.screen_container, result.graphics_proxy, on_proxy_error)));
        }
    }
    catch(e)
    {
        fail(e.message);
        return;
    }

    if(resume === "resume") options.autostart = false;
    const emulator = create_emulator(options);
    if(!emulator) return;
    const name = config ? config.name : profile ? profile.name : "Custom";
    /** @type {any} */ (window).v86_console = { emulator, config, profile, options };
    console_ui(layout, emulator, { options, config, profile, query_args: target.query_args, name, fail, set_status, set_renderer: f => { render_status = f; },
        store, release: () => lock && lock.release() });
    if(resume === "resume")
    {
        // (the machine loaded, not started: its state, then it runs on; the state file is used up)
        emulator.add_listener("emulator-loaded", async () =>
        {
            set_status("Resuming ...");
            try
            {
                await emulator.restore_state_stream(await read_state(config.id));
                emulator.run();
                await delete_state(config.id);
                await store.put(Object.assign({}, config, { suspended: null }));
                replace(layout.notice);
            }
            catch(error)
            {
                replace(layout.notice, h("p.error", null, "The suspended state could not be resumed: " + error.message + " ",
                    h("button", { type: "button", onclick: async () => { await delete_state(config.id); await store.put(Object.assign({}, config, { suspended: null }));
                        location.reload(); } }, "Discard it and power on"), " ", h("a", { href: location.pathname }, "Back to the library")));
                set_status("Not resumed");
            }
        });
    }
}

/**
 * How a suspended machine starts: from its state ("resume"), afresh with the
 * state discarded ("discard"), or not ("cancel"); asked when its settings
 * changed after it was suspended, or its state is gone
 * @param {VMConfig} config
 * @param {VMStore} store
 * @param {HTMLElement} notice
 * @return {Promise<"resume" | "discard" | "cancel">}
 */
async function resume_choice(config, store, notice)
{
    const discard = async () =>
    {
        await delete_state(config.id);
        await store.put(Object.assign({}, config, { suspended: null }));
        return /** @type {"discard"} */ ("discard");
    };
    const file = await read_state(config.id);
    if(!file)
    {
        await discard();
        replace(notice, h("p", null, "The suspended state is gone (the browser's storage was cleared?): the machine starts afresh."));
        return "discard";
    }
    if(await machine_digest(config) === /** @type {any} */ (config.suspended).digest) return "resume";
    const answer = await new Promise(resolve => replace(notice, h("div.resume-choice", { role: "alert" },
        h("p", null, "The settings of " + config.name + " changed after it was suspended: its state may not fit them any more."),
        h("button.primary", { type: "button", id: "resume_anyway", onclick: () => resolve("resume") }, "Resume anyway"), " ",
        h("button", { type: "button", id: "resume_discard", onclick: () => resolve("discard") }, "Discard the state and power on"), " ",
        h("button", { type: "button", id: "resume_cancel", onclick: () => resolve("cancel") }, "Cancel"))));
    replace(notice);
    if(answer === "discard") return discard();
    return answer;
}

/**
 * What a console printed (the serial port, a virtio console), kept from power
 * on so that its drawer shows all of it when it opens: the last `limit`
 * bytes until then, everything after
 * @param {number} limit
 */
function console_output(limit)
{
    /** @type {Uint8Array[]} */
    let parts = [];
    let current = new Uint8Array(4096), used = 0, size = 0;
    /** @type {((bytes: Uint8Array) => void) | null} */
    let sink = null;
    const flush = () =>
    {
        if(!used) return;
        parts.push(current.subarray(0, used));
        size += used;
        current = new Uint8Array(4096);
        used = 0;
        while(size > limit && parts.length > 1) size -= /** @type {Uint8Array} */ (parts.shift()).length;
    };
    return {
        /** @param {Uint8Array} bytes */
        push(bytes)
        {
            if(sink) { sink(bytes); return; }
            for(let i = 0; i < bytes.length;)
            {
                const n = Math.min(bytes.length - i, current.length - used);
                current.set(bytes.subarray(i, i + n), used);
                used += n;
                i += n;
                if(used === current.length) flush();
            }
        },
        /** @param {(bytes: Uint8Array) => void} write what was kept, then what comes */
        attach(write)
        {
            flush();
            for(const part of parts) write(part);
            parts = [];
            size = 0;
            sink = write;
        },
    };
}

/**
 * The running console's controls
 * @param {ReturnType<typeof console_layout>} layout
 * @param {any} emulator
 * @param {{options: any, config: VMConfig | null, profile: any, query_args?: URLSearchParams, name: string,
 *     fail: (text: string) => void, set_status: (text: string) => void, set_renderer: (f: () => void) => void,
 *     store: VMStore | null, release: () => void}} ctx
 */
function console_ui(layout, emulator, ctx)
{
    const options = ctx.options;
    const tag = ctx.profile?.id || (ctx.config ? ctx.config.name.replace(/[^\w.-]+/g, "_") : "v86");
    const virt = options.cpu_type === "arm64";
    const written_back = [options.hda, options.hdb, options.fda, options.fdb, ...(options.virtio_disks || [])].some(d => d && d.disk_option === "read_write");
    let powered_off = false;
    let running = false;

    // ---- the status bar
    const stats = { started: 0, running_ms: 0, last_tick: 0, last_counter: 0, total: 0, ips: 0,
        disk_read: 0, disk_written: 0, disk_busy: false, net_in: 0, net_out: 0, fs_read: 0, fs_written: 0, fs_file: "",
        mode: "", resolution: "", guest_mouse: false, absolute_mouse: false, usb_tablet: false, pointer_locked: false, mouse_enabled: true };
    const status_parts = {
        state: h("span.status-state"), time: h("span"), speed: h("span"), disk: h("span"), network: h("span"), display: h("span"), mouse: h("span"),
    };
    replace(layout.status, Object.values(status_parts));
    const render = () =>
    {
        status_parts.state.textContent = layout.status.dataset.state || "";
        status_parts.time.textContent = stats.running_ms ? format_time(stats.running_ms / 1000 | 0) : "";
        status_parts.speed.textContent = stats.running_ms ? (stats.ips / 1000).toFixed(1) + " MIPS (average " + (stats.total / 1000 / stats.running_ms).toFixed(1) + ")" : "";
        status_parts.disk.textContent = stats.disk_read || stats.disk_written ? "Disk " + (stats.disk_busy ? "busy, " : "") +
            format_size(stats.disk_read) + " read, " + format_size(stats.disk_written) + " written" : "";
        status_parts.network.textContent = stats.net_in || stats.net_out ? "Network " + format_size(stats.net_in) + " in, " + format_size(stats.net_out) + " out" : "";
        status_parts.display.textContent = stats.mode ? stats.mode + " " + stats.resolution : "";
        status_parts.mouse.textContent = !stats.mouse_enabled ? "Mouse off" :
            stats.usb_tablet && !stats.pointer_locked ? "Mouse: USB tablet (absolute)" :
            stats.guest_mouse ? "Mouse: the guest's" + (stats.pointer_locked ? " (PS/2, locked)" : stats.absolute_mouse ? " (absolute)" : "") : "";
        if(details_open()) render_details();
    };
    ctx.set_renderer(render);
    const tick = () =>
    {
        const now = Date.now();
        let counter = emulator.get_instruction_counter();
        if(counter < stats.last_counter) stats.last_counter -= 0x100000000;
        const instructions = counter - stats.last_counter;
        stats.last_counter = counter;
        stats.total += instructions;
        const delta = now - stats.last_tick;
        if(delta)
        {
            stats.running_ms += delta;
            stats.last_tick = now;
            stats.ips = instructions / delta * 1000 / 1000;
        }
        render();
    };
    let interval = 0;
    emulator.add_listener("emulator-started", () =>
    {
        running = true;
        stats.last_tick = Date.now();
        clearInterval(interval);
        interval = window.setInterval(tick, 1000);
        ctx.set_status("Running");
    });
    emulator.add_listener("emulator-stopped", () =>
    {
        running = false;
        tick();
        clearInterval(interval);
        if(!powered_off) ctx.set_status("Paused");
    });
    emulator.add_listener("ide-read-start", () => { stats.disk_busy = true; });
    emulator.add_listener("ide-read-end", args => { stats.disk_busy = false; stats.disk_read += args[1]; });
    emulator.add_listener("ide-write-end", args => { stats.disk_written += args[1]; });
    emulator.add_listener("eth-receive-end", args => { stats.net_in += args[0]; });
    emulator.add_listener("eth-transmit-end", args => { stats.net_out += args[0]; });
    emulator.add_listener("9p-read-start", args => { stats.fs_file = args[0]; show_files_tab(); });
    emulator.add_listener("9p-read-end", args => { stats.fs_read += args[1]; });
    emulator.add_listener("9p-write-end", args => { stats.fs_written += args[1]; stats.fs_file = args[0]; });
    emulator.add_listener("mouse-enable", enabled => { stats.guest_mouse = enabled; render(); });
    emulator.add_listener("vmware-absolute-mouse", enabled => { stats.absolute_mouse = enabled; });
    // (the ARM machines' virtio tablet and touch screens: [active, the guest's cursor])
    emulator.add_listener("absolute-pointer", state => { stats.absolute_mouse = state[0]; render(); });
    // (the USB tablet: the pointer absolute while the guest uses it; locked, the PS/2 mouse's)
    emulator.add_listener("usb-tablet-active", active => { stats.usb_tablet = active; render(); });
    document.addEventListener("pointerlockchange", () => { stats.pointer_locked = !!document.pointerLockElement; render(); });
    emulator.add_listener("screen-set-size", args =>
    {
        const [width, height, bpp] = args;
        stats.mode = bpp ? "Graphics" : "Text";
        stats.resolution = width + "×" + height + (bpp ? "×" + bpp : "");
        render();
        if(zoom_to_fit) fit();
    });

    // ---- start and errors
    emulator.add_listener("download-progress", e =>
    {
        const file = String(e.file_name).split("?", 1)[0].split("/").pop();
        ctx.set_status(e.total ? "Downloading " + file + " " + Math.floor(e.loaded / e.total * 100) + "%" : "Downloading " + file + " ...");
    });
    emulator.add_listener("download-error", e => ctx.fail("Loading " + e.file_name + " failed. Check your connection and reload the page to try again."));
    emulator.add_listener("emulator-error", error => ctx.fail("Emulator failed: " + error.message));
    emulator.add_listener("emulator-ready", () =>
    {
        ctx.set_status("Running");
        if(ctx.query_args?.has("c")) setTimeout(() => emulator.keyboard_send_text(ctx.query_args.get("c") + "\n"), 25);
        if(ctx.query_args?.has("s")) setTimeout(() => emulator.serial0_send(ctx.query_args.get("s") + "\n"), 25);
        if(ctx.query_args?.has("theatre") && bool_arg(ctx.query_args.get("theatre"))) set_theatre(true);
        if(ctx.profile?.mouse_disabled_default || ctx.config?.advanced.mouse_disabled) set_mouse(false);
    });

    // virtio_gpu: the guest's display follows the window; Android's is its
    // device model's (a phone's, unless its settings say the window's), the
    // screen zoomed to the window: a display of a large window's size made
    // Android draw every frame of its boot at 2325x1690
    const fixed_display = ctx.config ? android_display(ctx.config) : null;
    if(fixed_display)
    {
        emulator.add_listener("emulator-ready", () =>
        {
            emulator.set_display_size(fixed_display.width, fixed_display.height);
            set_zoom_to_fit(true);
        });
    }
    else if((options.graphics_adapter || DEFAULT_GRAPHICS_ADAPTER) === "virtio_gpu")
    {
        let timer = 0;
        const displays = options.graphics_adapter_test?.scanouts || 1;
        const report = () =>
        {
            clearTimeout(timer);
            timer = window.setTimeout(() =>
            {
                for(let i = 0; i < displays; i++) emulator.set_display_size(Math.floor(window.innerWidth / displays), window.innerHeight, i);
            }, 250);
        };
        window.addEventListener("resize", report);
        emulator.add_listener("emulator-ready", report);
    }

    // ---- power
    const power_off = async (ask = true) =>
    {
        if(ask && !await confirm("Power off?", "The virtual machine stops as if its power were cut. What is only in its memory is lost." +
            (written_back ? " Its disks written back keep what they completed." : ""), "Power off", true)) return;
        powered_off = true;
        clearInterval(interval);
        await emulator.destroy();
        ctx.release();
        replace(layout.toolbar, h("a.button", { href: location.pathname }, "Library"), h("span.console-name", null, ctx.name));
        replace(layout.notice, h("p", null, "Powered off. ", h("a", { href: location.href }, "Power on again"), " or go back to the ",
            h("a", { href: location.pathname }, "library"), "."));
        ctx.set_status("Powered off");
    };
    const save_and_power_off = async () =>
    {
        try
        {
            const parts = [];
            await emulator.save_state_stream(chunk => { parts.push(chunk.slice()); });
            download(parts, tag + "-state.bin");
            await power_off(false);
            replace(layout.notice, h("p", null, "Saved the state (" + tag + "-state.bin, " + format_size(parts.reduce((n, p) => n + p.length, 0)) +
                ") and powered off: the disks written back are flushed and closed. Load the state with the same disks to go on. ",
                h("a", { href: location.pathname }, "Back to the library")));
        }
        catch(error)
        {
            await inform("The state was not saved", error.message);
        }
    };
    const suspend = async () =>
    {
        const config = /** @type {VMConfig} */ (ctx.config), store = /** @type {VMStore} */ (ctx.store);
        const space = await storage_space();
        const need = state_estimate(options);
        if(space.quota && space.free < need)
        {
            await inform("Not enough space to suspend", "The state needs about " + format_size(need) + "; the browser gives this site " +
                format_size(space.free) + " more. Free some (delete other machines' states or disks), or power off.");
            return;
        }
        // (once: ask the browser to keep this site's storage when it runs short)
        if(!space.persisted && !await store.get_pref("persist_asked"))
        {
            await store.put_pref("persist_asked", true);
            await navigator.storage.persist?.().catch(() => false);
        }
        ctx.set_status("Suspending ...");
        try
        {
            const size = await write_state(config.id, write => emulator.save_state_stream(write));
            await store.put(Object.assign({}, config, { suspended: { size, time: new Date().toISOString(), digest: await machine_digest(config) } }));
            await power_off(false);
            replace(layout.notice, h("p", null, "Suspended (" + format_size(size) + " in this browser's storage). Power it on from the ",
                h("a", { href: location.pathname }, "library"), " to resume it."));
            ctx.set_status("Suspended");
        }
        catch(error)
        {
            await delete_state(config.id).catch(() => {});
            await inform("The machine was not suspended", error.message);
            ctx.set_status(emulator.is_running() ? "Running" : "Paused");
        }
    };
    const save_state = async () =>
    {
        ctx.set_status("Saving the state ...");
        try { await save_state_to_file(emulator, options, tag + "-state.bin"); }
        catch(error) { await inform("The state was not saved", error.message); }
        ctx.set_status(running ? "Running" : "Paused");
    };
    const load_state = async () =>
    {
        const file = await pick_file("");
        if(!file) return;
        ctx.set_status("Loading the state ...");
        try
        {
            // (streams, large machines', are read from the file as needed:
            // odd versions, 7 and 9; src/state.js)
            const header = new DataView(await file.slice(0, 8).arrayBuffer());
            const stream = header.byteLength === 8 && header.getUint32(0, true) === 0x86768676 && header.getUint32(4, true) % 2 === 1;
            const was_running = emulator.is_running();
            if(was_running) await emulator.stop();
            if(stream) await emulator.restore_state_stream(file);
            else await emulator.restore_state(await file.arrayBuffer());
            if(was_running) emulator.run();
        }
        catch(error)
        {
            await inform("The state was not loaded", String(error.message || error) + " (the machine's configuration must be the one the state was saved with)");
        }
        ctx.set_status(emulator.is_running() ? "Running" : "Paused");
    };

    // ---- keys
    const send_keys = text =>
    {
        const { press, release } = combination_scancodes(text);
        emulator.keyboard_send_scancodes(press);
        setTimeout(() => emulator.keyboard_send_scancodes(release), 100);
    };
    const other_keys = async () =>
    {
        const text = await ask_text("Send keys", "Keys joined by + (Ctrl, Alt, Shift, Win, F1-F12, Del, Tab, Esc, Enter, letters)", "Ctrl+Alt+F1");
        if(!text) return;
        try { send_keys(text); }
        catch(error) { await inform("Send keys", error.message); }
    };

    // ---- removable devices and disk images
    const disks = ["hda", "hdb", "cdrom"].filter(name => options[name]).concat((options.virtio_disks || []).map((_, i) => "virtio_disk" + i));
    const floppy_inserted = async drive => !!(await (drive === "fda" ? emulator.get_disk_fda() : emulator.get_disk_fdb()));
    const insert_floppy = async drive =>
    {
        const file = await pick_file("");
        if(!file) return;
        await (drive === "fda" ? emulator.set_fda({ buffer: file }) : emulator.set_fdb({ buffer: file }));
    };
    const insert_cdrom = async () =>
    {
        const files = await new Promise(resolve =>
        {
            const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", multiple: true, style: { display: "none" } }));
            input.addEventListener("change", () => { resolve(Array.from(input.files || [])); input.remove(); });
            input.addEventListener("cancel", () => { resolve([]); input.remove(); });
            document.body.append(input);
            input.click();
        });
        if(!files.length) return;
        if(files.length === 1 && /\.(iso(9660|img)?|cdr)$/i.test(files[0].name)) await emulator.set_cdrom({ buffer: files[0] });
        else await emulator.set_cdrom_files(await Promise.all(files.map(async file => ({ name: file.name, contents: new Uint8Array(await file.arrayBuffer()) }))));
    };
    // USB disks: the configuration's and those plugged in since (their ids);
    // the guest's eject tells that one can be unplugged
    const usb_disks = options.usb ? (options.usb.mass_storage || []).map(disk => disk.id) : [];
    const usb_free = () => options.usb ? (USB_PORTS[options.usb.controller] || 0) - (options.usb.tablet ? 1 : 0) - usb_disks.length : 0;
    const usb_ejected = new Set();
    emulator.add_listener("usb-disk-ejected", id =>
    {
        usb_ejected.add(id);
        ctx.set_status("The guest ejected the USB disk " + id + ": it can be unplugged");
    });
    const insert_usb_disk = async () =>
    {
        const file = await pick_file("");
        if(!file) return;
        let n = 0;
        while(usb_disks.includes("usb" + n)) n++;
        const id = "usb" + n;
        try
        {
            await emulator.usb_attach_disk(id, { buffer: file });
            usb_disks.push(id);
        }
        catch(error) { await inform("The USB disk was not plugged in", error.message); }
    };
    const unplug_usb_disk = async id =>
    {
        if(!usb_ejected.has(id) && !await confirm("Unplug the USB disk " + id + "?", "The guest has not ejected it: what it has not written to it " +
            "yet is lost, and its file system may need a check. (Eject it in the guest first: \"Safely Remove Hardware\", eject.)", "Unplug", true))
        {
            return;
        }
        try
        {
            await emulator.usb_detach_disk(id);
            usb_disks.splice(usb_disks.indexOf(id), 1);
            usb_ejected.delete(id);
        }
        catch(error) { await inform("The USB disk was not unplugged", error.message); }
    };
    const get_disk_image = async name =>
    {
        ctx.set_status("Reading " + name + " ...");
        try
        {
            if(name === "fda" || name === "fdb")
            {
                const data = await (name === "fda" ? emulator.get_disk_fda() : emulator.get_disk_fdb());
                if(data) download([data], tag + "-" + name + ".img");
            }
            else
            {
                const parts = [];
                await emulator.export_disk_image(name, { write: chunk => { parts.push(chunk.slice()); } });
                download(parts, tag + "-" + name.replace(":", "-") + (name === "cdrom" ? ".iso" : ".img"));
            }
        }
        catch(error)
        {
            await inform("The disk image was not read", error.message);
        }
        ctx.set_status(emulator.is_running() ? "Running" : "Paused");
    };

    // ---- view
    let zoom_to_fit = false, theatre = false, scale = 1;
    const fit = () =>
    {
        emulator.screen_set_scale(1, 1);
        const box = layout.screen_container.getBoundingClientRect();
        const room = theatre ? { width: window.innerWidth, height: window.innerHeight } :
            { width: layout.screen_container.parentElement.clientWidth || window.innerWidth, height: window.innerHeight - 120 };
        const n = Math.max(0.1, Math.min(room.width / box.width, room.height / box.height));
        emulator.screen_set_scale(n, n);
    };
    const set_zoom_to_fit = enabled =>
    {
        zoom_to_fit = enabled;
        if(enabled)
        {
            window.addEventListener("resize", fit);
            fit();
        }
        else
        {
            window.removeEventListener("resize", fit);
            emulator.screen_set_scale(scale, scale);
        }
    };
    const set_scale = n =>
    {
        scale = n;
        if(zoom_to_fit) set_zoom_to_fit(false);
        emulator.screen_set_scale(n, n);
    };
    const show_ui = h("button.theatre-show-ui", { type: "button", hidden: true, onclick: () => set_theatre(false) }, "Leave theatre mode");
    layout.root.append(show_ui);
    const set_theatre = enabled =>
    {
        theatre = enabled;
        layout.root.classList.toggle("theatre", enabled);
        document.body.classList.toggle("theatre-body", enabled);
        show_ui.hidden = !enabled;
        if(zoom_to_fit) fit();
    };
    const screenshot = () =>
    {
        const image = /** @type {any} */ (emulator.screen_make_screenshot());
        const src = image && (image.src || (image.toDataURL && image.toDataURL("image/png")));
        if(!src) return;
        const link = h("a", { href: src, download: tag + "-screenshot.png", style: { display: "none" } });
        document.body.append(link);
        link.click();
        link.remove();
    };

    // ---- input
    let mouse_enabled = true;
    const set_mouse = enabled =>
    {
        mouse_enabled = enabled;
        stats.mouse_enabled = enabled;
        emulator.mouse_set_enabled(enabled);
        render();
    };
    const lock_mouse = () =>
    {
        if(!mouse_enabled) set_mouse(true);
        emulator.lock_mouse();
    };
    layout.screen_container.addEventListener("click", e =>
    {
        // (a guest that follows the host's cursor needs no lock; the menu's Lock mouse is still there for games)
        if(mouse_enabled && stats.guest_mouse && !stats.absolute_mouse && !stats.usb_tablet) emulator.lock_mouse();
        if(window.getSelection()?.isCollapsed)
        {
            layout.phone_keyboard.style.top = window.scrollY + e.clientY + 20 + "px";
            layout.phone_keyboard.style.left = window.scrollX + e.clientX + "px";
            layout.phone_keyboard.value = "";
            layout.phone_keyboard.focus();
        }
    });

    // ---- sound
    let muted = false;
    const has_speaker = !options.disable_speaker && emulator.set_speaker_volume(1);
    const mute = h("button#mute", { type: "button", hidden: !has_speaker, "aria-pressed": "false", onclick: () =>
    {
        muted = !muted;
        emulator.set_speaker_volume(muted ? 0 : 1);
        mute.textContent = muted ? "Unmute" : "Mute";
        mute.setAttribute("aria-pressed", String(muted));
    } }, "Mute");

    // ---- tools
    const memory_dump = async () =>
    {
        const size = (options.memory_size || 0) + (options.extended_memory_size || 0);
        const parts = [];
        ctx.set_status("Reading the memory ...");
        try
        {
            for await (const chunk of emulator.read_memory_chunks(0, Math.min(size, options.memory_size))) parts.push(chunk.slice());
            download(parts, tag + "-memory.bin");
        }
        catch(error)
        {
            await inform("The memory was not read", error.message);
        }
        ctx.set_status(emulator.is_running() ? "Running" : "Paused");
    };
    let capture = null, stop_capture = null;
    const capture_network = () =>
    {
        if(!capture)
        {
            capture = [];
            stop_capture = emulator.capture_network_traffic((direction, data) =>
            {
                capture.push({ direction, time: performance.now() / 1000, hex_dump: hex_dump(data) });
                ctx.set_status("Capturing network traffic: " + capture.length + " packets");
            });
            ctx.set_status("Capturing network traffic: 0 packets");
            return;
        }
        // (Wireshark: File, Import from Hex Dump, direction indication, timestamp %s.%f)
        download([capture.map(p => p.direction + " " + p.time.toFixed(6) + p.hex_dump + "\n").join("")], tag + "-traffic.hex", "text/plain");
        capture = [];
    };
    const end_capture = () =>
    {
        if(stop_capture) stop_capture();
        capture = null;
        stop_capture = null;
        ctx.set_status(emulator.is_running() ? "Running" : "Paused");
    };

    // ---- drawers: the serial terminal, the kernel console (the first virtio
    // console: hvc0 of the virt machine's Linux and Android), the shared
    // folder, the details. The consoles' output is kept from power on (the
    // last MiB), so a drawer opened later shows the boot from its start.
    let drawer = "";
    let files_tab = !!(ctx.config ? ctx.config.filesystem : ctx.options.filesystem && Object.keys(ctx.options.filesystem).length);
    const details_open = () => drawer === "details";
    const kernel_console = !!options.virtio_console;
    const serial_output = console_output(1 << 20), kernel_output = console_output(1 << 20);
    emulator.add_listener("serial0-output-byte", /** @param {number} byte */ byte => serial_output.push(Uint8Array.of(byte)));
    if(kernel_console) emulator.add_listener("virtio-console0-output-bytes", /** @param {Uint8Array} bytes */ bytes => kernel_output.push(bytes));
    const terminal = h("div.terminal"), kernel = h("div.terminal");
    /** @type {Promise<void> | null} */
    let xterm_loaded = null;
    /** @type {Set<HTMLElement>} */
    const terminals = new Set();
    /**
     * An xterm in `element` (once): what the console printed so far, then
     * what it prints; the keys typed go to `send`
     * @param {HTMLElement} element
     * @param {ReturnType<typeof console_output>} output
     * @param {(text: string) => void} send
     */
    const open_terminal = (element, output, send) =>
    {
        if(terminals.has(element)) return;
        terminals.add(element);
        xterm_loaded = xterm_loaded || new Promise((resolve, reject) =>
        {
            const script = document.createElement("script");
            script.src = "build/xterm.js" + query_append();
            script.onload = () => resolve(undefined);
            script.onerror = () => reject(new Error("build/xterm.js did not load"));
            document.head.append(script);
        });
        xterm_loaded.then(() =>
        {
            // (a boot's log runs to thousands of lines: xterm keeps 1000 by default)
            const term = new (/** @type {any} */ (window)).Terminal({ logLevel: "off", convertEol: true, scrollback: 10000 });
            term.open(element);
            output.attach(bytes => term.write(bytes));
            term.onData(/** @param {string} data */ data => send(data));
        }, error => ctx.set_status(error.message));
    };
    const details = h("div.details");
    // (the cards of the options: the library's defaults where they name none)
    const network_card = options.net_device && options.net_device.type || (virt ? "virtio" : "ne2k");
    const sound_card = virt ? (options.virtio_sound ? "virtio" : "none") : options.audio_device || "sb16";
    const render_details = () =>
    {
        const rows = [
            ["Machine", (options.machine_type || "i440fx") + ", " + options.cpu_type + ", " + options.cpu_cores + (options.cpu_cores === 1 ? " core" : " cores")],
            ["Memory", format_size((options.memory_size || 0) + (options.extended_memory_size || 0))],
            ["Running", stats.running_ms ? format_time(stats.running_ms / 1000 | 0) : "-"],
            ["Speed", stats.running_ms ? (stats.ips / 1000).toFixed(1) + " MIPS now, " + (stats.total / 1000 / stats.running_ms).toFixed(1) + " on average" : "-"],
            ["Instructions", String(stats.total)],
            ["Storage (" + (virt ? "virtio-blk" : options.machine_type === "q35" ? "AHCI" : "IDE") + ")", format_size(stats.disk_read) + " read, " +
                format_size(stats.disk_written) + " written" + (stats.disk_busy ? ", busy" : "")],
            ["Network", (NIC_LABELS[network_card] || network_card) + (network_card === "none" ? "" :
                ": " + format_size(stats.net_in) + " received, " + format_size(stats.net_out) + " sent")],
            ["Sound", (SOUND_LABELS[sound_card] || sound_card) + (options.disable_speaker ? ", muted" : "")],
            ["Shared folder", stats.fs_file ? format_size(stats.fs_read) + " read, " + format_size(stats.fs_written) + " written, last " + stats.fs_file : "-"],
            ["Display", stats.mode ? stats.mode + ", " + stats.resolution : "-"],
            ["Mouse", stats.usb_tablet ? "the USB tablet (absolute)" + (stats.pointer_locked ? "; locked: PS/2" : "") :
                stats.guest_mouse ? "used by the guest" + (stats.absolute_mouse ? " (absolute)" : "") : "not used by the guest"],
            ["USB", options.usb ? options.usb.controller.toUpperCase() + (options.usb.tablet ? ", tablet" : "") : "none"],
        ];
        replace(details, h("table.hardware", null, h("tbody", null, rows.map(([k, v]) => h("tr", null, h("th", null, k), h("td", null, v))))),
            h("p.note#usb_devices"), h("p.note#execution"));
        // (each USB device's controller and speed: EHCI's companions have the full-speed ones)
        if(options.usb) emulator.usb_devices().then(list =>
        {
            const element = details.querySelector("#usb_devices");
            if(element) element.textContent = "USB devices: " + (list.map(d => d.id + " (port " + (d.port + 1) + ", " +
                (d.plugged ? (d.controller === "ehci" ? "EHCI" : options.usb.controller === "ehci" ? "UHCI companion" : "UHCI") + ", " + d.speed + " Mbit/s" :
                    "out of its port") + ")").join("; ") || "none");
        }, () => {});
        emulator.get_diagnostics().then(diagnostics =>
        {
            const execution = diagnostics && diagnostics.execution;
            const fallback = execution && execution.fallback;
            const text = options.cpu_cores === 1 ? "1 core" : execution && execution.mode === "parallel" ? options.cpu_cores + " cores, each in a host thread" :
                options.cpu_cores + " cores taking turns on one thread" + (fallback && fallback !== "not requested" ? " (parallel unavailable: " + fallback + ")" : "");
            const element = details.querySelector("#execution");
            if(element) element.textContent = "Execution: " + text;
        }).catch(() => {});
    };
    const files_panel = () =>
    {
        const send = /** @type {HTMLInputElement} */ (h("input", { type: "file", multiple: true, "aria-label": "Send files" }));
        send.addEventListener("change", async () =>
        {
            for(const file of Array.from(send.files || []))
            {
                await emulator.create_file("/" + file.name, new Uint8Array(await file.arrayBuffer()));
            }
            send.value = "";
            ctx.set_status("Sent to the shared folder");
        });
        const path = /** @type {HTMLInputElement} */ (h("input", { type: "text", placeholder: "/file.txt", "aria-label": "File to get" }));
        const get = async () =>
        {
            try
            {
                const data = await emulator.read_file(path.value.trim());
                download([data], path.value.trim().split("/").pop() || "file");
            }
            catch(error)
            {
                await inform("The file was not read", "Can't read " + path.value + ": " + (error.message || error));
            }
        };
        path.addEventListener("keydown", e => { if(e.key === "Enter") get(); });
        return [
            h("p.note", null, "The shared folder (9p): in the guest, mount it (Linux: mount -t 9p host9p /mnt)."),
            h("label.field", null, h("span", null, "Send files into it"), send),
            h("label.field", null, h("span", null, "Get a file from it"), path), h("button", { type: "button", onclick: get }, "Get"),
        ];
    };
    const open_drawer = name =>
    {
        drawer = drawer === name ? "" : name;
        layout.drawer.hidden = !drawer;
        layout.root.classList.toggle("with-drawer", !!drawer);
        if(!drawer) { update_toolbar(); return; }
        const title = { terminal: "Serial terminal", kernel: "Kernel console", files: "Shared folder", details: "Details" }[drawer];
        replace(layout.drawer, h("header", null, h("h2", null, title), h("button", { type: "button", "aria-label": "Close", onclick: () => open_drawer("") }, "×")),
            drawer === "terminal" ? terminal : drawer === "kernel" ? kernel : drawer === "files" ? files_panel() : details);
        // (the serial port takes bytes: the keys' UTF-8 as characters 0-255)
        if(drawer === "terminal") open_terminal(terminal, serial_output, data => emulator.serial0_send(String.fromCharCode(...new TextEncoder().encode(data))));
        if(drawer === "kernel") open_terminal(kernel, kernel_output, data => emulator.virtio_console_send(data));
        if(drawer === "details") render_details();
        update_toolbar();
    };
    const show_files_tab = () =>
    {
        if(files_tab) return;
        files_tab = true;
        update_toolbar();
    };
    emulator.add_listener("9p-attach", show_files_tab);

    // ---- the disk error dialog (disk_error "stop": retry or power off; "report": the guest was told)
    emulator.add_listener("disk-error", async event =>
    {
        const stop = event.policy === "stop";
        const text = "Disk " + event.disk + ": the " + event.operation + " of " + event.length + " bytes at " + event.offset + " failed: " + event.reason + ". " +
            (!stop ? "The guest was told." : event.retryable ? "The machine is stopped: retry once the disk can be reached again, or power off." :
                "The machine is stopped: this cannot be retried; continue (the guest is told), or power off.");
        const answer = await dialog({
            title: "Disk error",
            body: h("p#disk_error_text", null, text),
            buttons: stop ? [{ label: "Power off", value: "off", danger: true }, { label: event.retryable ? "Retry" : "Continue", value: "run", primary: true }] :
                [{ label: "OK", value: "ok", primary: true }],
        });
        if(answer === "run" || answer === undefined && stop) emulator.run();
        if(answer === "off")
        {
            await power_off(false);
            replace(layout.notice, h("p", null, "Powered off: the requests still waiting for the disk are dropped, as by a power loss. ",
                h("a", { href: location.pathname }, "Back to the library")));
        }
    });

    // ---- leaving the page: disks written back, and Ctrl+W (which the guest cannot get)
    let ctrl = false;
    const ctrl_state = e => { ctrl = !!e.ctrlKey; };
    window.addEventListener("keydown", ctrl_state, true);
    window.addEventListener("keyup", ctrl_state, true);
    window.addEventListener("blur", () => { ctrl = false; });
    window.addEventListener("beforeunload", e =>
    {
        if(powered_off) return;
        if(written_back || ctrl)
        {
            e.preventDefault();
            e.returnValue = "";
        }
    });

    // ---- the toolbar
    /** @type {Object<string, () => Array<import("./dom.js").MenuItem | "-">>} */
    const items = {
        power: () => [
            { label: running ? "Pause" : "Run", id: "menu_run", action: () => running ? emulator.stop() : emulator.run() },
            { label: "Reset", id: "menu_reset", disabled: !!options.initial_state, title: options.initial_state ? "Started from a saved state" : "", action: () => emulator.restart() },
            { label: "Power off…", id: "menu_power_off", action: () => power_off() },
            ...(ctx.config ? [{ label: "Suspend", id: "menu_suspend", action: suspend }] : []),
            ...(written_back ? [{ label: "Save and power off", id: "menu_save_and_power_off", action: save_and_power_off }] : []),
            "-",
            { label: "Save the state to a file", id: "menu_save_state", action: save_state },
            { label: "Load a state from a file…", id: "menu_load_state", action: load_state },
        ],
        keys: () => [
            ...COMBINATIONS.map(c => ({ label: c, id: "keys_" + c.replace(/\W+/g, "_"), action: () => send_keys(c) })),
            "-",
            { label: "Other keys…", id: "keys_other", action: other_keys },
        ],
        devices: () => [
            ...(options.cdrom || !virt ? [{ label: "CD/DVD: insert an image or files…", id: "devices_insert_cdrom", action: insert_cdrom },
                { label: "CD/DVD: eject", id: "devices_eject_cdrom", action: () => emulator.eject_cdrom() }] : []),
            ...(!virt ? [
                { label: "Floppy A: insert…", id: "devices_insert_fda", action: () => insert_floppy("fda") },
                { label: "Floppy A: eject", id: "devices_eject_fda", action: () => emulator.eject_fda() },
                { label: "Floppy B: insert…", id: "devices_insert_fdb", action: () => insert_floppy("fdb") },
                { label: "Floppy B: eject", id: "devices_eject_fdb", action: () => emulator.eject_fdb() },
            ] : []),
            ...(options.usb && !virt ? [
                "-",
                ...(usb_free() > 0 ? [{ label: "USB disk: plug in an image…", id: "devices_usb_insert", action: insert_usb_disk }] : []),
                ...usb_disks.map(id => ({ label: "USB disk " + id + ": unplug" + (usb_ejected.has(id) ? " (ejected)" : "…"), id: "devices_usb_unplug_" + id,
                    action: () => unplug_usb_disk(id) })),
            ] : []),
            "-",
            ...disks.concat(usb_disks.map(id => "usb:" + id), virt ? [] : ["fda", "fdb"]).map(name => ({ label: "Download the " + name + " image",
                id: "devices_get_" + name.replace(":", "_"), action: () => get_disk_image(name) })),
        ],
        view: () => [
            { label: "Full screen", id: "view_fullscreen", action: () => emulator.screen_go_fullscreen() },
            { label: "Zoom to fit", id: "view_zoom_to_fit", checked: zoom_to_fit, action: () => set_zoom_to_fit(!zoom_to_fit) },
            ...SCALES.map(n => ({ label: "Scale " + n * 100 + "%", id: "view_scale_" + n * 100, checked: !zoom_to_fit && scale === n, action: () => set_scale(n) })),
            { label: "Theatre mode", id: "view_theatre", checked: theatre, action: () => set_theatre(!theatre) },
            "-",
            { label: "Screenshot", id: "view_screenshot", action: screenshot },
        ],
        input: () => [
            { label: "Mouse", id: "input_mouse", checked: mouse_enabled, action: () => set_mouse(!mouse_enabled) },
            { label: "Lock the mouse", id: "input_lock_mouse", action: lock_mouse },
        ],
        tools: () => [
            { label: "Memory dump", id: "tools_memory_dump", action: memory_dump },
            { label: capture ? "Save the " + capture.length + " packets captured" : "Capture network traffic", id: "tools_capture", action: capture_network },
            ...(capture ? [{ label: "Stop capturing", id: "tools_stop_capture", action: end_capture }] : []),
        ],
    };
    const drawer_button = (name, label) => h("button", { type: "button", id: "drawer_" + name, "aria-pressed": String(drawer === name),
        class: drawer === name ? "pressed" : "", onclick: () => open_drawer(name) }, label);
    const update_toolbar = () =>
    {
        if(powered_off) return;
        replace(layout.toolbar,
            h("a.button", { href: location.pathname }, "Library"),
            menu_button("Power", items.power, "menu_power"),
            menu_button("Keys", items.keys, "menu_keys"),
            menu_button("Devices", items.devices, "menu_devices"),
            menu_button("View", items.view, "menu_view"),
            menu_button("Input", items.input, "menu_input"),
            mute,
            menu_button("Tools", items.tools, "menu_tools"),
            h("span.toolbar-gap"),
            drawer_button("terminal", "Terminal"),
            kernel_console ? drawer_button("kernel", "Kernel console") : null,
            files_tab ? drawer_button("files", "Files") : null,
            drawer_button("details", "Details"),
            h("span.console-name", null, ctx.name));
    };
    update_toolbar();
    ctx.set_status("Starting ...");
}
                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/app/ui/describe.js                                                                   0000644 0000000 0000000 00000012305 00000000000 013767  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// A configuration for people (docs/vm-manager-plan.md): where an image is,
// and the hardware table of the library's summary and the settings list.

import { format_size } from "./dom.js";
import { NIC_LABELS, SOUND_LABELS } from "./panels/devices.js";

/** @typedef {import("../vm_config.js").VMConfig} VMConfig */
/** @typedef {import("../vm_config.js").Image} Image */

const MACHINES = { i440fx: "i440FX (IDE)", q35: "Q35 (AHCI, PCI Express)", virt: "virt (arm64)" };
const ADAPTERS = { bochs_vga: "Bochs VGA", vmware_svga: "VMware SVGA II", virtio_gpu: "virtio-gpu", none: "None (serial console only)" };
const BACKENDS = { none: "no network", inbrowser: "in the browser", relay: "relay", wisp: "wisp", fetch: "fetch" };

/**
 * Where an image is, for people
 * @param {Image | null} image
 * @return {string}
 */
export function describe_image(image)
{
    if(!image) return "none";
    switch(image.kind)
    {
        case "url": return image.url + (image.size ? " (" + format_size(image.size) + ")" : "");
        case "file": return "file on this computer: " + image.name + " (" + format_size(image.size) + ")" + (image.handle ? "" : ", to be chosen again");
        case "empty": return "empty disk in memory, " + format_size(image.size) + " (lost at power off)";
        case "browser": return "browser disk, " + format_size(image.size);
    }
    return "?";
}

/**
 * The hardware of a configuration, a row each (the settings dialog's list in U3)
 * @param {VMConfig} c
 * @return {Array<[string, string]>}
 */
export function hardware_rows(c)
{
    /** @type {Array<[string, string]>} */
    const rows = [
        ["Memory", c.memory.mb + " MB"],
        ["Processor", c.cpu.type + ", " + c.cpu.cores + (c.cpu.cores === 1 ? " core" : " cores") + (c.cpu.cores > 1 && c.cpu.parallel ? " in parallel" : "") +
            (c.cpu.jit ? "" : ", no JIT")],
        ["Machine", (MACHINES[c.machine.type] || c.machine.type) + (c.machine.acpi ? ", ACPI" : "") + (c.machine.firmware === "uefi" ? ", UEFI" : "") +
            (c.machine.firmware === "uefi" && c.machine.secure_boot ? ", Secure Boot" : "")],
    ];
    for(const disk of c.disks)
    {
        rows.push(["Hard disk (" + disk.slot + ")", describe_image(disk.image) + (disk.disk_option === "read_write" ? ", read write" : ", read only")]);
    }
    if(c.cdrom.image) rows.push(["CD/DVD", describe_image(c.cdrom.image)]);
    for(const floppy of c.floppies) if(floppy.image) rows.push(["Floppy (" + floppy.slot + ")", describe_image(floppy.image)]);
    if(c.kernel)
    {
        rows.push(["Direct boot", [c.kernel.bzimage && "kernel " + describe_image(c.kernel.bzimage), c.kernel.initrd && "initrd " + describe_image(c.kernel.initrd),
            c.kernel.multiboot && "multiboot " + describe_image(c.kernel.multiboot), c.kernel.cmdline && "command line " + c.kernel.cmdline,
            c.kernel.from_filesystem && "kernel and initrd from the shared folder"].filter(Boolean).join("; ")]);
    }
    if(c.android)
    {
        // (docs/android-images-plan.md I2: the kernel and initrd from the disk's boot partitions)
        // (an emulator image's: its GLES drawn by the host's GPU, or the guest draws)
        rows.push(["Android boot", "from the first disk (" + c.android.device + "), " + (/^ranchu_/.test(c.android.device) ?
            "the emulator's disks, " + (c.android.gpu_mode === "host" ? "the host's GPU draws GLES " + c.android.gles_version : "the guest draws") :
            { venus: "Venus", gfxstream: "gfxstream" }[c.android.gpu_mode] || "SwiftShader") +
            (c.android.vendor_ramdisk === "debug" ? ", debug vendor ramdisk " + (c.android.debug_ramdisk ? describe_image(c.android.debug_ramdisk) : "(not chosen)") : "") +
            (c.android.selinux === "permissive" ? ", SELinux permissive" : "")]);
    }
    if(c.initial_state) rows.push(["Starts from a state", describe_image(c.initial_state)]);
    rows.push(["Display", (ADAPTERS[c.display.adapter] || c.display.adapter) + (c.display.vram_mb ? ", " + c.display.vram_mb + " MB" : "") +
        (c.display.displays > 1 ? ", " + c.display.displays + " displays" : "") + ({ venus: ", Vulkan (Venus)", gfxstream: ", Vulkan (gfxstream)" }[c.display.vulkan] || "")]);
    for(const network of c.network)
    {
        rows.push(["Network", network.device === "none" ? "none" : (NIC_LABELS[network.device] || network.device) + ", " + (BACKENDS[network.backend] || network.backend) +
            (network.relay_url ? " " + network.relay_url : "")]);
    }
    rows.push(["Sound", (c.sound.device === "none" ? "none" : SOUND_LABELS[c.sound.device] || c.sound.device) + (c.sound.mute ? ", muted" : "")]);
    if(c.usb) rows.push(["USB", c.usb.controller.toUpperCase() + (c.usb.tablet ? ", tablet" : "")]);
    if(c.tpm) rows.push(["TPM", "TPM 2.0 (CRB)"]);
    for(const disk of c.usb ? c.usb.disks : [])
    {
        rows.push(["USB disk (" + disk.id + ")", describe_image(disk.image) + (disk.disk_option === "read_write" ? ", read write" : ", read only") +
            (disk.write_protected ? ", write protected" : "")]);
    }
    for(const serial of c.serial) if(serial.attach !== "none") rows.push(["UART" + serial.port, serial.attach]);
    if(c.filesystem) rows.push(["Shared folder", c.filesystem.baseurl || "in the browser"]);
    return rows;
}
                                                                                                                                                                                                                                                                                                                           source/v64/src/app/ui/dom.js                                                                        0000644 0000000 0000000 00000022255 00000000000 012773  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The VM manager's DOM helpers (docs/vm-manager-plan.md G6: no UI framework):
// h() for elements, modal dialogs, and downloads.

/**
 * An element: h("div.summary#vm", { onclick, title, dataset: {...}, style: {...} }, child, ...)
 * Children are nodes, strings, or arrays of them; null, undefined and false are left out.
 * @param {string} spec a tag, then .class and #id parts
 * @param {Object<string, any> | null} [props]
 * @param {...any} children
 * @return {HTMLElement}
 */
export function h(spec, props, ...children)
{
    const [, tag, rest] = /^([a-z0-9-]+)(.*)$/i.exec(spec) || [];
    const element = document.createElement(tag || "div");
    for(const part of (rest || "").match(/[.#][^.#]+/g) || [])
    {
        if(part[0] === ".") element.classList.add(part.slice(1));
        else element.id = part.slice(1);
    }
    for(const [name, value] of Object.entries(props || {}))
    {
        if(value === undefined || value === null || value === false) continue;
        if(name.startsWith("on") && typeof value === "function") element.addEventListener(name.slice(2), value);
        // (added to the spec's classes, not in their place)
        else if(name === "class") element.classList.add(...String(value).split(/\s+/).filter(Boolean));
        else if(name === "style" && typeof value === "object") Object.assign(element.style, value);
        else if(name === "dataset") Object.assign(element.dataset, value);
        else if(name in element && typeof value !== "string") /** @type {any} */ (element)[name] = value;
        else element.setAttribute(name, value === true ? "" : String(value));
    }
    append(element, children);
    return element;
}

/**
 * @param {Element} parent
 * @param {any[]} children
 */
function append(parent, children)
{
    for(const child of children)
    {
        if(child === null || child === undefined || child === false) continue;
        if(Array.isArray(child)) append(parent, child);
        else parent.append(child instanceof globalThis.Node ? child : String(child));
    }
}

/**
 * Replace an element's children
 * @param {Element} element
 * @param {...any} children
 */
export function replace(element, ...children)
{
    element.replaceChildren();
    append(element, children);
}

/**
 * A modal dialog; resolves with the value of the button pressed (Escape: undefined)
 * @param {{title: string, body?: any, buttons: Array<{label: string, value: any, primary?: boolean, danger?: boolean}>,
 *     focus?: HTMLElement, on_submit?: () => any}} options on_submit: the value of pressing Enter in a field
 * @return {Promise<any>}
 */
export function dialog(options)
{
    return new Promise(resolve =>
    {
        /** @type {HTMLDialogElement} */
        const element = /** @type {HTMLDialogElement} */ (h("dialog.dialog"));
        const close = value =>
        {
            element.close();
            element.remove();
            resolve(value);
        };
        const form = h("form", { method: "dialog", onsubmit: e => { e.preventDefault(); if(options.on_submit) close(options.on_submit()); } },
            h("h2", null, options.title),
            options.body ? h("div.dialog-body", null, options.body) : null,
            h("div.dialog-buttons", null, options.buttons.map(b => h("button" + (b.primary ? ".primary" : "") + (b.danger ? ".danger" : ""), {
                type: "button",
                onclick: () => close(b.value),
            }, b.label))));
        element.append(form);
        element.addEventListener("cancel", e => { e.preventDefault(); close(undefined); });
        document.body.append(element);
        element.showModal();
        (options.focus || element.querySelector("button.primary") || element.querySelector("button"))?.focus();
    });
}

/**
 * Ask for a line of text; undefined when cancelled
 * @param {string} title
 * @param {string} label
 * @param {string} value
 * @return {Promise<string | undefined>}
 */
export async function ask_text(title, label, value)
{
    const input = /** @type {HTMLInputElement} */ (h("input", { type: "text", value, "aria-label": label, size: 40 }));
    const answer = await dialog({
        title,
        body: h("label.field", null, h("span", null, label), input),
        focus: input,
        on_submit: () => input.value,
        buttons: [{ label: "Cancel", value: undefined }, { label: "OK", value: "ok", primary: true }],
    });
    return answer === undefined ? undefined : input.value;
}

/**
 * Ask a yes or no question
 * @param {string} title
 * @param {any} body
 * @param {string} yes the label of the button that says yes
 * @param {boolean} [danger]
 * @return {Promise<boolean>}
 */
export async function confirm(title, body, yes, danger = false)
{
    return await dialog({ title, body, buttons: [{ label: "Cancel", value: false }, { label: yes, value: true, primary: !danger, danger }] }) === true;
}

/**
 * Tell something; resolves when it is closed
 * @param {string} title
 * @param {any} body
 * @return {Promise<void>}
 */
export async function inform(title, body)
{
    await dialog({ title, body, buttons: [{ label: "OK", value: true, primary: true }] });
}

/**
 * Save data as a file of the user's
 * @param {BlobPart[]} parts
 * @param {string} name
 * @param {string} [type]
 */
export function download(parts, name, type = "application/octet-stream")
{
    const url = URL.createObjectURL(new Blob(parts, { type }));
    const link = h("a", { href: url, download: name, style: { display: "none" } });
    document.body.append(link);
    link.click();
    link.remove();
    setTimeout(() => URL.revokeObjectURL(url), 60000);
}

/**
 * A file the user picks (undefined: none picked)
 * @param {string} accept
 * @return {Promise<File | undefined>}
 */
export function pick_file(accept)
{
    return new Promise(resolve =>
    {
        const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", accept, style: { display: "none" } }));
        input.addEventListener("change", () => { resolve(input.files?.[0]); input.remove(); });
        input.addEventListener("cancel", () => { resolve(undefined); input.remove(); });
        document.body.append(input);
        input.click();
    });
}

/**
 * A size for people: 1.4 MB, 512 MB, 2 GB
 * @param {number} bytes
 * @return {string}
 */
export function format_size(bytes)
{
    const units = ["bytes", "KB", "MB", "GB", "TB"];
    let unit = 0;
    let value = bytes;
    while(value >= 1024 && unit < units.length - 1)
    {
        value /= 1024;
        unit++;
    }
    return (unit === 0 || value >= 100 || Number.isInteger(value) ? Math.round(value) : value.toFixed(1)) + " " + units[unit];
}

/**
 * @typedef {{label: string, action?: () => any, disabled?: boolean, checked?: boolean, title?: string, id?: string}} MenuItem
 */

/**
 * A menu button; its items are made each time it opens (their labels and
 * states follow the machine). Arrow keys move, Escape and a click elsewhere close it.
 * @param {string} label
 * @param {() => Array<MenuItem | "-">} items "-" separates
 * @param {string} [id] the button's id
 * @return {HTMLElement}
 */
export function menu_button(label, items, id)
{
    const list = h("div.menu-list", { role: "menu", hidden: true });
    const button = h("button.menu-button", { type: "button", "aria-haspopup": "menu", "aria-expanded": "false", id });
    button.textContent = label;
    const wrapper = h("div.menu", null, button, list);
    const outside = e => { if(!wrapper.contains(/** @type {Node} */ (e.target))) close(); };
    const close = () =>
    {
        list.hidden = true;
        button.setAttribute("aria-expanded", "false");
        document.removeEventListener("pointerdown", outside, true);
    };
    const open = () =>
    {
        replace(list, items().map(item => item === "-" ? h("div.menu-separator", { role: "separator" }) :
            h("button.menu-item", {
                type: "button",
                role: item.checked === undefined ? "menuitem" : "menuitemcheckbox",
                "aria-checked": item.checked === undefined ? undefined : String(item.checked),
                disabled: !!item.disabled,
                title: item.title || "",
                id: item.id,
                onclick: () => { close(); if(item.action) item.action(); },
            }, (item.checked === undefined ? "" : item.checked ? "✓ " : "   ") + item.label)));
        list.hidden = false;
        button.setAttribute("aria-expanded", "true");
        document.addEventListener("pointerdown", outside, true);
        /** @type {HTMLElement | null} */ (list.querySelector("button:not(:disabled)"))?.focus();
    };
    button.addEventListener("click", () => { if(list.hidden) open(); else close(); });
    wrapper.addEventListener("keydown", e =>
    {
        if(e.key === "Escape" && !list.hidden) { e.preventDefault(); close(); button.focus(); return; }
        if(e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
        if(list.hidden) { e.preventDefault(); open(); return; }
        const buttons = /** @type {HTMLElement[]} */ (Array.from(list.querySelectorAll("button:not(:disabled)")));
        const at = buttons.indexOf(/** @type {HTMLElement} */ (document.activeElement));
        e.preventDefault();
        buttons[(at + (e.key === "ArrowDown" ? 1 : buttons.length - 1)) % buttons.length]?.focus();
    });
    return wrapper;
}
                                                                                                                                                                                                                                                                                                                                                   source/v64/src/app/ui/image_picker.js                                                               0000644 0000000 0000000 00000033162 00000000000 014632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// Where an image comes from (docs/vm-manager-plan.md "虚拟机配置格式", the
// image's kinds; "磁盘的存放位置"): a URL, a file on this computer (its
// handle kept where the browser allows it), an empty disk in memory, an
// image of the disk service (listed, or created there), a browser disk (in
// the browser's private storage: chosen, made empty, or imported, U6).
// The settings dialog and the wizard use it.

import { h, ask_text, inform, format_size } from "./dom.js";
import { FLOPPY_SIZES } from "../vm_config.js";
import { list_images, create_image, image_url, new_image_name } from "../disk_service_client.js";
import { list_disks, create_disk, import_disk } from "../browser_disks.js";

/** @typedef {import("../vm_config.js").Image} Image */
/** @typedef {import("../disk_service_client.js").Service} Service */

/**
 * @typedef {Object} PickerOptions
 * @property {Image | null} image the image now
 * @property {"disk" | "cdrom" | "floppy" | "file"} role a hard disk's choices (empty disks, the service, browser
 *     disks), a CD's, a floppy's (empty floppies), or any other image's (a kernel, a BIOS: URL or file)
 * @property {boolean} [optional] "none" is a choice
 * @property {(image: Image | null, extra?: {read_write?: boolean}) => void} on_change extra.read_write: an image
 *     the service created, to be written back
 * @property {{put_handle: (handle: any) => Promise<string>, get_pref?: (name: string) => Promise<any>,
 *     put_pref?: (name: string, value: any) => Promise<void>}} store where a picked file's handle is kept (and the
 *     preferences: persistent storage asked for once)
 * @property {Service | null} [service] the disk service, if there is one
 * @property {string} [machine_name] for the name of a new image of the service
 * @property {string} label
 */

/**
 * A file the user picks, with its handle where the browser gives one (Chromium's showOpenFilePicker)
 * @param {{put_handle: (handle: any) => Promise<string>}} store
 * @return {Promise<Image | null>}
 */
async function pick_local_file(store)
{
    const picker = /** @type {any} */ (window).showOpenFilePicker;
    if(typeof picker === "function")
    {
        let handles;
        try
        {
            handles = await picker({ multiple: false });
        }
        catch(e)
        {
            if(e.name === "AbortError") return null;
            throw e;
        }
        const file = await handles[0].getFile();
        return { kind: "file", name: file.name, size: file.size, last_modified: file.lastModified, handle: await store.put_handle(handles[0]) };
    }
    // (other browsers keep no handle: the console asks for the file again)
    const file = await new Promise(resolve =>
    {
        const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", style: { display: "none" } }));
        input.addEventListener("change", () => { resolve(input.files?.[0]); input.remove(); });
        input.addEventListener("cancel", () => { resolve(undefined); input.remove(); });
        document.body.append(input);
        input.click();
    });
    return file ? { kind: "file", name: file.name, size: file.size, last_modified: file.lastModified } : null;
}

/**
 * The image's kind as the picker names it ("service" for a URL of the service)
 * @param {Image | null} image
 * @param {Service | null | undefined} service
 */
function picker_kind(image, service)
{
    if(!image) return "none";
    if(image.kind === "url" && service && image.url.startsWith(image_url(service, ""))) return "service";
    return image.kind;
}

/**
 * The picker's element
 * @param {PickerOptions} o
 * @return {HTMLElement}
 */
export function image_picker(o)
{
    const kinds = [];
    if(o.optional) kinds.push(["none", "None"]);
    kinds.push(["url", "An image on the web (URL)"], ["file", "A file on this computer"]);
    if(o.role === "disk") kinds.push(["empty", "A new empty disk in memory (lost at power off)"]);
    if(o.role === "floppy") kinds.push(["empty", "An empty floppy"]);
    if((o.role === "disk" || o.role === "cdrom" || o.role === "floppy") && o.service) kinds.push(["service", "An image of the disk service"]);
    if(o.role === "disk" || o.role === "floppy") kinds.push(["browser", "A browser disk (kept in this browser)"]);
    // (without "none" among the choices, an empty URL to begin with)
    /** @type {any} (its kind is the picker's) */
    const image = o.image || (o.optional ? null : { kind: "url", url: "", async: true });
    const kind = picker_kind(image, o.service);

    const select = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": o.label + ": source" },
        kinds.map(([value, text]) => h("option", { value, selected: value === kind }, text))));
    select.addEventListener("change", () =>
    {
        const value = select.value;
        if(value === "none") o.on_change(null);
        else if(value === "url") o.on_change({ kind: "url", url: "", async: true });
        else if(value === "empty") o.on_change({ kind: "empty", size: o.role === "floppy" ? 1474560 : 512 << 20 });
        else if(value === "file") pick_local_file(o.store).then(picked => { if(picked) o.on_change(picked); else select.value = kind; });
        else if(value === "service") o.on_change({ kind: "url", url: image_url(/** @type {Service} */ (o.service), ""), async: true });
        else if(value === "browser") o.on_change({ kind: "browser", path: "", size: 0 });
    });

    const detail = [];
    if(image && kind === "url")
    {
        const url = /** @type {HTMLInputElement} */ (h("input", { type: "text", value: image.url, size: 50, placeholder: "https://…/disk.img",
            "aria-label": o.label + ": URL" }));
        url.addEventListener("change", () => o.on_change(Object.assign({}, image, { url: url.value.trim() })));
        const size = /** @type {HTMLInputElement} */ (h("input", { type: "number", min: "0", step: "512", value: image.size || "",
            placeholder: "optional", "aria-label": o.label + ": size in bytes" }));
        size.addEventListener("change", () =>
        {
            const next = Object.assign({}, image);
            if(+size.value > 0) next.size = +size.value;
            else delete next.size;
            o.on_change(next);
        });
        detail.push(h("label.field", null, h("span", null, "URL"), url), h("label.field", null, h("span", null, "Size in bytes"), size));
    }
    else if(image && kind === "file")
    {
        detail.push(h("p", null, image.name + ", " + format_size(image.size) + (image.handle ? "" : " (to be chosen again when the machine starts)"), " ",
            h("button", { type: "button", onclick: () => pick_local_file(o.store).then(picked => { if(picked) o.on_change(picked); }) }, "Choose another…")));
    }
    else if(image && kind === "empty" && o.role === "floppy")
    {
        const sizes = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": o.label + ": floppy size" },
            FLOPPY_SIZES.map(bytes => h("option", { value: bytes, selected: bytes === image.size }, format_size(bytes)))));
        sizes.addEventListener("change", () => o.on_change({ kind: "empty", size: +sizes.value }));
        detail.push(h("label.field", null, h("span", null, "Size"), sizes));
    }
    else if(image && kind === "empty")
    {
        const mb = /** @type {HTMLInputElement} */ (h("input", { type: "number", min: "1", max: "2000", value: Math.round(image.size / 1048576),
            "aria-label": o.label + ": size in MB" }));
        mb.addEventListener("change", () => o.on_change({ kind: "empty", size: Math.max(1, Math.min(2000, Math.round(+mb.value || 1))) * 1048576 }));
        detail.push(h("label.field", null, h("span", null, "Size in MB (at most 2000)"), mb));
    }
    else if(image && image.kind === "url" && kind === "service")
    {
        const service = /** @type {Service} */ (o.service);
        const list = h("div.service-images", null, "Listing the disk service's images…");
        detail.push(list);
        list_images(service).then(found =>
        {
            const current = decodeURIComponent(image.url.slice(image_url(service, "").length));
            const choose = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": o.label + ": the service's image" },
                h("option", { value: "", selected: !current }, "Choose an image…"),
                found.images.map(i => h("option", { value: i.name, selected: i.name === current },
                    i.name + " (" + format_size(i.size) + (i.writer ? ", in use" : "") + ")"))));
            choose.addEventListener("change", () =>
            {
                const chosen = found.images.find(i => i.name === choose.value);
                if(chosen) o.on_change({ kind: "url", url: image_url(service, chosen.name), size: chosen.size, async: true }, { read_write: true });
            });
            const create = h("button", {
                type: "button", disabled: !found.create, title: found.create ? "" : "The disk service does not create images (start it with --allow-create)",
                onclick: async () =>
                {
                    const name = await ask_text("New image", "Name (ending in .img)", new_image_name(o.machine_name || "disk", found.images));
                    if(!name) return;
                    const size = await ask_text("New image", "Size in MB", "8192");
                    if(!size || !(+size > 0)) return;
                    try
                    {
                        const made = await create_image(service, name.trim(), Math.round(+size) * 1048576);
                        o.on_change({ kind: "url", url: made.url, size: made.size, async: true }, { read_write: true });
                    }
                    catch(e)
                    {
                        await inform("The image was not created", e.message);
                    }
                },
            }, "Create a new image…");
            list.replaceChildren(h("label.field", null, h("span", null, "Image"), choose), create);
        }, e => list.replaceChildren(h("p.error", null, e.message)));
    }
    else if(image && kind === "browser")
    {
        detail.push(browser_disk_choice(o, image));
    }
    return h("div.image-picker", null, h("label.field", null, h("span", null, o.label), select), detail);
}

/**
 * The browser disks to choose from, and making or importing one
 * @param {PickerOptions} o
 * @param {any} image
 */
function browser_disk_choice(o, image)
{
    const element = h("div.service-images", null, "Listing the browser disks…");
    const prefs = o.store.get_pref && o.store.put_pref ? /** @type {any} */ (o.store) : undefined;
    const chosen = disk => o.on_change({ kind: "browser", path: disk.path, size: disk.size }, { read_write: true });
    const status = h("small.reason", { role: "status" });
    list_disks().then(disks =>
    {
        const choose = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": o.label + ": the browser disk" },
            h("option", { value: "", selected: !image.path }, "Choose a disk…"),
            disks.map(d => h("option", { value: d.path, selected: d.path === image.path }, d.label + " (" + format_size(d.size) + ")"))));
        choose.addEventListener("change", () => { const d = disks.find(x => x.path === choose.value); if(d) chosen(d); });
        const make = h("button", { type: "button", onclick: async () =>
        {
            const size = await ask_text("New browser disk", "Size in MB", o.role === "floppy" ? "1.44" : "1024");
            if(!size || !(+size > 0)) return;
            try
            {
                status.textContent = "Making the disk …";
                chosen(await create_disk(o.role === "floppy" ? 1474560 : Math.round(+size) * 1048576, o.machine_name || "disk", prefs));
            }
            catch(e) { status.textContent = ""; await inform("The disk was not made", e.message); }
        } }, "New empty disk…");
        const bring = h("button", { type: "button", onclick: async () =>
        {
            const from = await ask_text("Import into a browser disk", "The image's URL (empty: a file on this computer)", "");
            if(from === undefined) return;
            /** @type {string | File} */
            let source = from.trim();
            if(!source)
            {
                const file = await new Promise(resolve =>
                {
                    const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", style: { display: "none" } }));
                    input.addEventListener("change", () => { resolve(input.files?.[0]); input.remove(); });
                    input.addEventListener("cancel", () => { resolve(undefined); input.remove(); });
                    document.body.append(input);
                    input.click();
                });
                if(!file) return;
                source = file;
            }
            try
            {
                const label = typeof source === "string" ? source.split("/").pop() || "disk" : source.name;
                const disk = await import_disk(source, label, { prefs, progress: (done, total) =>
                {
                    status.textContent = "Copying " + format_size(done) + (total ? " of " + format_size(total) : "") + " …";
                } });
                status.textContent = "Copied, the copy checked (SHA-256)";
                chosen(disk);
            }
            catch(e) { status.textContent = ""; await inform("The image was not imported", e.message); }
        } }, "Import an image…");
        element.replaceChildren(h("label.field", null, h("span", null, "Disk"), choose), make, bring, status,
            h("small.reason", null, "An import is a copy: the original stays as it is."));
    }, e => element.replaceChildren(h("p.error", null, e.message)));
    return element;
}
                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/app/ui/library.js                                                                    0000644 0000000 0000000 00000037150 00000000000 013660  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The library (docs/vm-manager-plan.md "虚拟机库"): the virtual machines of
// this browser on the left, the chosen one's summary on the right: new (the
// wizard), import, edit settings (the settings dialog), rename, export,
// delete (with its own browser disks), power on in a new tab, resume; the
// preferences (the disk service); the browser disks (U6).

import { h, replace, ask_text, confirm, inform, download, pick_file, dialog, format_size } from "./dom.js";
import { hardware_rows } from "./describe.js";
import { open_wizard } from "./wizard.js";
import { open_settings } from "./settings.js";
import { VMStore, export_config, export_file_name, import_config, files_to_choose, config_images } from "../vm_store.js";
import { list_disks, create_disk, import_disk, export_disk, delete_disk, disk_id } from "../browser_disks.js";
import { preset } from "../guest_presets.js";
import { probe, LOCAL_SERVICE } from "../disk_service_client.js";
import { delete_state, running_machines, storage_space } from "../vm_state.js";

/** @typedef {import("../vm_config.js").VMConfig} VMConfig */
/** @typedef {import("../vm_config.js").Image} Image */

/**
 * The browser disks a configuration uses
 * @param {VMConfig} config
 * @return {string[]} their paths
 */
function browser_disk_paths(config)
{
    return config_images(config).filter(image => image.kind === "browser").map(image => /** @type {any} */ (image).path);
}

/**
 * The browser disks dialog: each disk's size and machines, export, delete,
 * import, a new one; their total
 * @param {VMStore} store
 * @param {VMConfig[]} configs
 */
async function browser_disks_dialog(store, configs)
{
    for(;;)
    {
        const disks = await list_disks();
        const users = path => configs.filter(c => browser_disk_paths(c).includes(path)).map(c => c.name);
        /** @type {null | (() => any)} */
        let action = null;
        const act = fn => () => { action = fn; /** @type {HTMLElement | null} */ (document.querySelector("dialog[open] .dialog-buttons button"))?.click(); };
        const total = disks.reduce((n, d) => n + d.size, 0);
        await dialog({
            title: "Browser disks",
            body: [
                h("p.note", null, "Disks kept in this browser's private storage for this site: " + disks.length + ", " + format_size(total) +
                    ". Clearing the site's data deletes them: export the ones you want to keep."),
                disks.length ? h("table.hardware.browser-disks", null, h("tbody", null, disks.map(d => h("tr", { dataset: { disk: d.id } },
                    h("th", null, d.label), h("td", null, format_size(d.size)), h("td", null, users(d.path).join(", ") || "not used"),
                    h("td", null,
                        h("button", { type: "button", onclick: act(() => export_disk(d.id, d.label.replace(/[^\w.-]+/g, "_") + ".img", download)) }, "Export"), " ",
                        h("button.danger", { type: "button", onclick: act(async () =>
                        {
                            const used = users(d.path);
                            if(!await confirm("Delete " + d.label + "?", used.length ? "It is the disk of " + used.join(", ") + ": they will not start without it." :
                                "Its data is gone for good.", "Delete", true)) return;
                            await delete_disk(d.id);
                        }) }, "Delete")))))) : h("p.empty", null, "No browser disks."),
                h("div.summary-actions", null,
                    h("button", { type: "button", id: "browser_disk_new", onclick: act(async () =>
                    {
                        const size = await ask_text("New browser disk", "Size in MB", "1024");
                        if(size && +size > 0) await create_disk(Math.round(+size) * 1048576, "disk", store);
                    }) }, "New empty disk…"),
                    h("button", { type: "button", id: "browser_disk_import", onclick: act(async () =>
                    {
                        const file = await pick_file("");
                        if(file) await import_disk(file, file.name, { prefs: store });
                    }) }, "Import a file…")),
            ],
            buttons: [{ label: "Close", value: true, primary: true }],
        });
        if(!action) return;
        try { await action(); }
        catch(e) { await inform("Browser disks", e.message); }
    }
}

/** The page is served from this computer (the local disk service is looked for there) */
const PAGE_ON_THIS_COMPUTER = ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname);

/**
 * The disk service the manager uses: the preference's, or on a page served
 * from this computer the local one of make run when it answers
 * @param {VMStore} store
 * @return {Promise<import("../disk_service_client.js").Service | null>}
 */
export async function current_service(store)
{
    const pref = await store.get_pref("disk_service");
    if(pref && pref.url) return (await probe(pref)).ok ? pref : null;
    if(pref && pref.off) return null;
    if(!PAGE_ON_THIS_COMPUTER) return null;
    const local = { url: LOCAL_SERVICE };
    return (await probe(local)).ok ? local : null;
}

/**
 * The preferences dialog: the disk service's URL and token
 * @param {VMStore} store
 */
async function preferences(store)
{
    const pref = await store.get_pref("disk_service") || {};
    const url = /** @type {HTMLInputElement} */ (h("input", { type: "text", value: pref.url || "", size: 40, placeholder: PAGE_ON_THIS_COMPUTER ? LOCAL_SERVICE + " (looked for by default)" : "https://…/",
        "aria-label": "Disk service URL" }));
    const token = /** @type {HTMLInputElement} */ (h("input", { type: "password", value: pref.token || "", size: 40, autocomplete: "off", "aria-label": "Token" }));
    const off = /** @type {HTMLInputElement} */ (h("input", { type: "checkbox", checked: !!pref.off }));
    const result = h("p.note", { role: "status" });
    const test = h("button", { type: "button", onclick: async () =>
    {
        result.textContent = "Asking …";
        /** @type {any} */
        const found = await probe({ url: url.value.trim() || LOCAL_SERVICE, token: token.value || undefined });
        result.textContent = found.ok ? "A disk service: " + found.list.images.length + " images" + (found.list.create ? ", creates new ones" : ", does not create images") :
            found.reason;
    } }, "Test");
    const answer = await dialog({
        title: "Preferences",
        body: [
            h("p", null, "A disk service keeps hard disks in image files and writes the guests' changes back (tools/disk-service.mjs; make run starts one)."),
            h("label.field", null, h("span", null, "Disk service URL"), url),
            h("label.field", null, h("span", null, "Token (if it needs one)"), token),
            h("label.check", null, off, " Use no disk service"),
            h("div", null, test, result),
        ],
        buttons: [{ label: "Cancel", value: false }, { label: "Save", value: true, primary: true }],
    });
    if(!answer) return;
    await store.put_pref("disk_service", off.checked ? { off: true } : url.value.trim() ? { url: url.value.trim(), token: token.value || undefined } : undefined);
}

/**
 * Open the library in `root`
 * @param {HTMLElement} root
 */
export async function open_library(root)
{
    document.title = "Virtual machines - v86";
    const store = await VMStore.open();
    let configs = await store.list();
    let service = await current_service(store);
    /** @type {Set<string>} the machines running in a tab now */
    let running = await running_machines();
    let space = await storage_space().catch(() => null);
    /** @type {string | undefined} */
    let selected = configs[0]?.id;

    const reload = async id =>
    {
        configs = await store.list();
        running = await running_machines();
        space = await storage_space().catch(() => null);
        selected = id && configs.some(c => c.id === id) ? id : configs[0]?.id;
        render();
    };

    const create = async () =>
    {
        const config = await open_wizard({ store, service, names: configs.map(c => c.name) });
        if(!config) return;
        await reload((await store.put(config)).id);
    };

    const edit = async config =>
    {
        const edited = await open_settings(config, { store, service });
        if(!edited) return;
        await reload((await store.put(edited)).id);
    };

    const import_file = async () =>
    {
        const file = await pick_file(".json,.v86vm.json,application/json");
        if(!file) return;
        let config;
        try
        {
            config = await store.put(import_config(await file.text(), new Set(configs.map(c => c.id))));
        }
        catch(e)
        {
            await inform("Import failed", h("pre.problems", null, e.message));
            return;
        }
        await reload(config.id);
        if(files_to_choose(config).length)
        {
            await inform("Imported " + config.name, "Its files on your computer are not part of the export: the console asks for them when it starts.");
        }
    };

    function render()
    {
        const list = h("ul.vm-list", { role: "listbox", "aria-label": "Virtual machines" }, configs.map(c => h("li", {
            role: "option",
            "aria-selected": c.id === selected ? "true" : "false",
            class: c.id === selected ? "selected" : "",
            dataset: { id: c.id },
            tabindex: "0",
            onclick: () => { selected = c.id; render(); },
            onkeydown: e => { if(e.key === "Enter" || e.key === " ") { selected = c.id; render(); } },
        }, h("span.vm-name", null, c.name), h("span.vm-state", null, running.has(c.id) ? "Running in another tab" :
            c.suspended ? "Suspended" : "Powered off"))));
        const sidebar = h("aside.library-list", null,
            h("div.library-actions", null,
                h("button.primary#new_vm", { onclick: create }, "New virtual machine…"),
                h("button#import_vm", { onclick: import_file }, "Import…"),
                h("button#preferences", { onclick: async () => { await preferences(store); service = await current_service(store); render(); } }, "Preferences…"),
                h("button#browser_disks", { onclick: async () => { await browser_disks_dialog(store, configs); await reload(selected); } }, "Browser disks…")),
            h("p.note#service_status", null, service ? "Disk service: " + service.url : "No disk service"),
            configs.length ? list : h("p.empty", null, "No virtual machines yet. Make a new one, or import a .v86vm.json file."),
            space && space.quota ? h("p.note#storage_status", null, "Browser storage: " + format_size(space.usage) + " used of " + format_size(space.quota) +
                (space.persisted ? " (kept)" : "")) : null);
        const config = configs.find(c => c.id === selected);
        replace(root, h("div.library", null, sidebar, h("main.library-summary", null, config ? summary(config) : intro())));
    }

    function intro()
    {
        return h("div.intro", null,
            h("h1", null, "v86"),
            h("p", null, "Make a virtual machine, give it a disk and an installation CD or floppy, and start it. Its settings stay in this browser."),
            h("p.note", null, "The library lives in this browser's storage for this site: clearing the site's data deletes it. Export your machines now and then."));
    }

    /**
     * @param {VMConfig} config
     */
    function summary(config)
    {
        const power_on = () => window.open(location.pathname + "?vm=" + encodeURIComponent(config.id), "_blank");
        const rename = async () =>
        {
            const name = await ask_text("Rename", "Name", config.name);
            if(name === undefined || !name.trim() || name === config.name) return;
            await store.put(Object.assign({}, config, { name: name.trim() }));
            await reload(config.id);
        };
        const remove = async () =>
        {
            if(running.has(config.id))
            {
                await inform("It runs", config.name + " runs in another tab: power it off there first.");
                return;
            }
            // (its own browser disks go with it; those other machines use stay)
            const own = browser_disk_paths(config).filter(path => !configs.some(c => c.id !== config.id && browser_disk_paths(c).includes(path)));
            if(!await confirm("Delete " + config.name + "?", "Its settings" + (config.suspended ? ", its suspended state" : "") +
                (own.length ? " and its browser disk" + (own.length > 1 ? "s" : "") : "") + " are deleted from this browser. " +
                "Images on web sites, on your computer or on a disk service stay where they are.", "Delete", true)) return;
            try
            {
                for(const path of own) await delete_disk(disk_id(path));
            }
            catch(e)
            {
                await inform("Not deleted", e.message);
                return;
            }
            await delete_state(config.id);
            await store.delete(config.id);
            await reload(undefined);
        };
        const discard = async () =>
        {
            if(!await confirm("Discard the suspended state?", "The next power on starts " + config.name + " afresh: what it had in its memory is lost.",
                "Discard", true)) return;
            await delete_state(config.id);
            await store.put(Object.assign({}, config, { suspended: null }));
            await reload(config.id);
        };
        const p = config.template ? preset(config.template) : undefined;
        return h("div.summary", null,
            h("h1", null, config.name),
            config.notes ? h("p.notes", null, config.notes) : null,
            p && !p.verified ? h("p.error", null, "Its system's settings are not verified: " + p.basis) : null,
            config.suspended ? h("p.note#suspended_note", null, "Suspended " + new Date(config.suspended.time).toLocaleString() + " (" +
                format_size(config.suspended.size) + " in this browser's storage)") : null,
            running.has(config.id) ? h("p.note", null, "Running in another tab.") : null,
            h("div.summary-actions", null,
                h("button.primary#power_on", { onclick: power_on }, config.suspended ? "Resume" : "Power on"),
                config.suspended ? h("button#discard_state", { onclick: discard }, "Discard the suspended state…") : null,
                h("button#edit_vm", { onclick: () => edit(config) }, "Edit settings…"),
                h("button#rename_vm", { onclick: rename }, "Rename…"),
                h("button#export_vm", { onclick: () => download([export_config(config)], export_file_name(config), "application/json") }, "Export"),
                h("button.danger#delete_vm", { onclick: remove }, "Delete…")),
            h("table.hardware", null, h("tbody", null, hardware_rows(config).map(([name, value]) => h("tr", null, h("th", null, name), h("td", null, value))))),
            p && (p.checklist.length || p.issues.length) ? h("details.checklist", null, h("summary", null, "After the installation, known problems"),
                p.checklist.length ? h("ul", null, p.checklist.map(c => h("li", null, h("label.check", null, h("input", { type: "checkbox" }), " " + c)))) : null,
                p.issues.length ? h("ul", null, p.issues.map(c => h("li", null, c))) : null) : null,
            h("p.note", null, "Changed " + new Date(config.modified).toLocaleString()));
    }

    // (another tab powered a machine on or off, or suspended it)
    window.addEventListener("focus", () => reload(selected));
    document.addEventListener("visibilitychange", () => { if(!document.hidden) reload(selected); });
    render();
}
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/app/ui/panels/android.js                                                             0000644 0000000 0000000 00000015346 00000000000 015121  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog's Android panel (docs/android-images-plan.md I4.2):
// v64's bootloader (the device model, the GPU mode, the GLES version an
// emulator image gets on the host's GPU, the vendor ramdisk and
// the debug one's file, SELinux), the display's size, and wiping the user data of the machine's
// browser disk (Android formats userdata and metadata again at its next boot).

import { h, confirm } from "../dom.js";
import { image_picker } from "../image_picker.js";
import { select_field } from "./system.js";
import { ANDROID_DEVICES, ANDROID_GPU_MODES, RANCHU_GPU_MODES, ANDROID_VENDOR_RAMDISKS, ANDROID_SELINUX, ANDROID_DISPLAYS, ANDROID_GLES_VERSIONS } from "../../vm_config.js";
import { ANDROID_DEVICES as MODELS } from "../../../android/bootloader.js";
import { wipe_android_data } from "../../android_import.js";
import { disk_id } from "../../browser_disks.js";

/** @typedef {import("../settings.js").PanelContext} PanelContext */

const DEVICES = { cf_arm64_only_phone: "Cuttlefish arm64-only phone (aosp_cf_arm64_only_phone)",
    ranchu_25_armeabi_v7a: "Android Emulator image: Android 7.1 (API 25, armeabi-v7a)" };
const GPU = {
    swiftshader: "SwiftShader: the CPU draws (Android starts; its desktop needs a GPU)",
    venus: "Venus: the disk's own Venus driver (tools/a64_android.mjs puts it in odm), drawn by the graphics proxy",
    gfxstream: "gfxstream: the image's own drivers (official images), drawn by the graphics proxy",
    host: "The host's GPU: the emulator's GLES drawn with this page's WebGPU (the CPU draws without WebGPU)",
    guest: "The guest's CPU: Android draws its windows itself (slow)",
};
const GLES = {
    "2.0": "GLES 2.0",
    "3.0": "GLES 3.0",
    "3.1": "GLES 3.1 (compute, storage buffers, images; the default)",
    "3.2": "GLES 3.2 (advanced blending, border clamping; Android 7.1's GLES library refuses geometry and tessellation shaders)",
};
const RAMDISKS = {
    release: "The device's own (release: adb asks on the screen)",
    debug: "Cuttlefish's debug ramdisk (adb without asking, root; only with a system of the same release)",
};

/** @param {PanelContext} ctx */
export function android_panel(ctx)
{
    const a = /** @type {import("../../vm_config.js").Android} */ (ctx.config.android);
    const set = (name, value) => ctx.edit(next => { /** @type {any} */ (next.android)[name] = value; });
    const disk = ctx.config.disks.find(d => d.slot === "hda");
    const browser_disk = disk && disk.image.kind === "browser" ? disk.image.path : "";
    // (an emulator image: the ranchu machine's; its disk's partitions are the emulator's disks)
    const emulator = MODELS[a.device] && MODELS[a.device].machine === "ranchu";
    const models = ANDROID_DEVICES.filter(id => MODELS[id].machine === ctx.config.machine.type && MODELS[id].cpu === ctx.config.cpu.type);
    const status = h("small.reason", { role: "status" });
    const wipe = /** @type {HTMLButtonElement} */ (h("button", { type: "button", disabled: !browser_disk || emulator,
        title: emulator ? "An emulator image's user data is its userdata.img: import the image again" :
            browser_disk ? "" : "Only a browser disk's user data can be wiped here" }, "Wipe user data…"));
    wipe.addEventListener("click", async () =>
    {
        if(!await confirm("Wipe user data?", "This machine's apps, settings and files are deleted; Android sets itself up again at its next boot.", "Wipe", true)) return;
        wipe.disabled = true;
        status.textContent = "Wiping…";
        try
        {
            const wiped = await wipe_android_data(disk_id(browser_disk));
            status.textContent = "Wiped: " + wiped.join(", ") + ". Android formats them at its next boot.";
        }
        catch(e)
        {
            status.textContent = "Not wiped: " + e.message;
        }
        wipe.disabled = false;
    });
    if(emulator)
    {
        return [
            h("p.note", null, "v64 boots the emulator image from the first hard disk: its kernel and ramdisk partitions, the emulator's command line; " +
                "its system, cache and userdata partitions are the machine's virtio disks."),
            select_field("Device model", models, a.device, value => set("device", value), v => DEVICES[v] || v),
            // (the GPU mode, read at the boot: a suspended machine resumes with its own)
            select_field("GPU", RANCHU_GPU_MODES, a.gpu_mode === "swiftshader" ? "guest" : a.gpu_mode, value => set("gpu_mode", value), v => GPU[v] || v),
            // (the version the host's GPU announces: read at the boot, as the GPU mode)
            select_field("GLES version", ANDROID_GLES_VERSIONS, a.gles_version, value => set("gles_version", value), v => GLES[v] || v,
                a.gpu_mode === "host" ? {} : { disabled: true, title: "The host's GPU's: the guest's CPU draws GLES 2.0" }),
            h("div.field", null, wipe, " ", status),
        ];
    }
    return [
        h("p.note", null, "v64 boots Android from the first hard disk: the kernel, initrd and command line come from its boot partitions."),
        select_field("Device model", models, a.device, value => set("device", value), v => DEVICES[v] || v),
        // (a GPU mode other than SwiftShader is the display's Vulkan: chosen there)
        select_field("GPU", ANDROID_GPU_MODES.filter(v => v === "swiftshader" || v === ctx.config.display.vulkan || v === a.gpu_mode), a.gpu_mode,
            value => set("gpu_mode", value), v => GPU[v] || v,
            ctx.config.display.vulkan !== "none" ? {} : { disabled: a.gpu_mode === "swiftshader", title: "Venus and gfxstream need the display's Vulkan (Display: Vulkan)" }),
        select_field("Vendor ramdisk", ANDROID_VENDOR_RAMDISKS, a.vendor_ramdisk, value => set("vendor_ramdisk", value), v => RAMDISKS[v] || v),
        a.vendor_ramdisk === "debug" ? image_picker({ label: "Debug vendor ramdisk (vendor_ramdisk-debug.img, from the build's artifacts on ci.android.com)",
            role: "file", image: a.debug_ramdisk, store: ctx.store, on_change: image => set("debug_ramdisk", image) }) : null,
        select_field("SELinux", ANDROID_SELINUX, a.selinux, value => set("selinux", value),
            v => v === "enforcing" ? "Enforcing" : "Permissive (for debugging; a user build ignores it)"),
        // (the size Android takes at its boot: a phone's, or the window's, which a large window makes slow to draw)
        select_field("Display", ANDROID_DISPLAYS, a.display, value => set("display", value), v => v === "device" ?
            "The device's (" + (MODELS[a.device] && MODELS[a.device].display ? MODELS[a.device].display.width + " × " + MODELS[a.device].display.height : "its own") +
                "), zoomed to the window" : "The window's size, following it (a large window draws slowly)"),
        h("div.field", null, wipe, " ", status),
    ];
}
                                                                                                                                                                                                                                                                                          source/v64/src/app/ui/panels/devices.js                                                             0000644 0000000 0000000 00000025036 00000000000 015120  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog's panels of the devices (docs/vm-manager-plan.md "设置
// 对话框"): network adapters, sound, display, serial ports, the shared
// folder, the virt machine's devices.

import { confirm, h } from "../dom.js";
import { select_field, check_field, number_field, text_field } from "./system.js";
import { VIRT_INPUTS } from "../../vm_model.js";
import { DISPLAY_VULKAN } from "../../vm_config.js";
import { disk_id, reset_disk } from "../../browser_disks.js";

/** @typedef {import("../settings.js").PanelContext} PanelContext */

const ADAPTER_LABELS = { bochs_vga: "Bochs VGA", vmware_svga: "VMware SVGA II", virtio_gpu: "virtio-gpu", none: "None (serial console only)" };
const VULKAN_LABELS = {
    none: "None",
    venus: "Venus (through the graphics proxy; Android's initrd-venus.img, Linux's Mesa)",
    gfxstream: "gfxstream (through the graphics proxy; Android's official images)",
};
/** The cards' names, also in the hardware list and the summary (describe.js) */
export const NIC_LABELS = { ne2k: "NE2000 (ne2k)", e1000: "Intel PRO/1000 MT (e1000)", virtio: "virtio-net", none: "None" };
const BACKEND_LABELS = { none: "Not connected", inbrowser: "A network in the browser", relay: "A relay (WebSocket)", wisp: "A wisp server", fetch: "fetch (HTTP only)" };
export const SOUND_LABELS = { sb16: "Sound Blaster 16", hd_audio: "HD Audio (Intel)", virtio: "virtio-snd", none: "None" };

/**
 * @param {PanelContext} ctx
 * @param {number} index
 */
export function network_panel(ctx, index)
{
    const n = ctx.config.network[index];
    const at = "network." + index + ".";
    return [
        select_field("Card", ctx.choices.net_devices, n.device, value => ctx.set(at + "device", value), v => NIC_LABELS[v] || v),
        n.device === "none" ? null : [
            select_field("Connected to", ["none", "inbrowser", "relay", "wisp", "fetch"], n.backend, value => ctx.set(at + "backend", value), v => BACKEND_LABELS[v]),
            n.backend === "relay" || n.backend === "wisp" || n.backend === "fetch" ?
                text_field(n.backend === "fetch" ? "CORS proxy (optional)" : n.backend === "wisp" ? "Wisp server" : "Relay", n.relay_url,
                    value => ctx.set(at + "relay_url", value.trim()), { placeholder: n.backend === "fetch" ? "https://…" : n.backend === "wisp" ? "wisps://…" : "wss://…" }) : null,
            n.device === "virtio" ? number_field("MTU", n.mtu, { min: 68, max: 65535 }, value => ctx.set(at + "mtu", value)) : null,
            check_field("Translate MAC addresses (some relays need it)", n.mac_address_translation, value => ctx.set(at + "mac_address_translation", value)),
        ],
        ctx.config.network.length > 1 ? h("p.note", null, "Card " + (index + 1) + " of " + ctx.config.network.length + ": one card reaches the network.") : null,
    ];
}

const USB_LABELS = { uhci: "UHCI (USB 1.1)", ehci: "EHCI (USB 2.0, with UHCI companions)", xhci: "xHCI (USB 3)" };

/** @param {PanelContext} ctx */
export function usb_panel(ctx)
{
    const u = /** @type {{controller: string, tablet: boolean}} */ (ctx.config.usb);
    // (Windows 7 and earlier: no xHCI driver of their own)
    const old_windows = ["windows3x", "windows9x", "windowsnt"].includes(ctx.config.guest) || ctx.config.template === "windows7";
    return [
        select_field("Controller", ctx.choices.usb_controllers, u.controller, value => ctx.set("usb.controller", value), v => USB_LABELS[v] || v),
        u.controller === "xhci" && old_windows ?
            h("p.note", null, "Windows 7 and earlier have no driver of their own for xHCI (Windows 8 and later have): EHCI works with them.") : null,
        check_field("Tablet (an absolute pointer: the guest's cursor follows the page's, no mouse lock)", u.tablet, value => ctx.set("usb.tablet", value)),
        h("p.note", null, "Lock the mouse (Input menu) for relative movement through the PS/2 mouse, as games need."),
    ];
}

/**
 * The TPM 2.0 (docs/tpm.md): what it is, and clearing it
 * @param {PanelContext} ctx
 */
export function tpm_panel(ctx)
{
    const t = /** @type {{state: any}} */ (ctx.config.tpm);
    const state = t.state;
    const status = h("small.reason", { role: "status" });
    const clear = /** @type {HTMLButtonElement} */ (h("button", { type: "button", disabled: !state || state.kind !== "browser",
        title: state ? "" : "The TPM's state is made at the first power-on" }, "Clear TPM…"));
    clear.addEventListener("click", async () =>
    {
        if(!state || state.kind !== "browser") return;
        if(!await confirm("Clear the TPM?", "Its seeds, keys and stored data are deleted, and a new TPM is made at the next power-on: " +
            "keys sealed to this one (BitLocker's among them) can no longer be unsealed. Have their recovery keys first.", "Clear", true)) return;
        clear.disabled = true;
        status.textContent = "Clearing…";
        try
        {
            await reset_disk(disk_id(state.path), new Uint8Array(state.size));
            status.textContent = "Cleared: a new TPM at the next power-on.";
        }
        catch(e)
        {
            status.textContent = "Not cleared: " + e.message;
        }
        clear.disabled = false;
    });
    return [
        h("p.note", null, "A TPM 2.0 (libtpms in WebAssembly) behind the CRB interface, which Windows 8 and later and Linux drive. " +
            "Its state (keys, stored data) is kept in a browser disk of the machine's, made at the first power-on (with the CPU in a Worker; " +
            "otherwise there is a new TPM at each power-on). It is a TPM for software that needs one, not a hardware root of trust."),
        h("div.field", null, clear, " ", status),
    ];
}

/** @param {PanelContext} ctx */
export function sound_panel(ctx)
{
    return [
        select_field("Sound card", ctx.choices.sound_devices, ctx.config.sound.device, value => ctx.set("sound.device", value), v => SOUND_LABELS[v] || v),
        // (None: the guest has no sound card; Mute: it has one, the page plays nothing)
        check_field("Mute (the page plays nothing; the guest keeps its sound card)", ctx.config.sound.mute, value => ctx.set("sound.mute", value)),
    ];
}

/** @param {PanelContext} ctx */
export function display_panel(ctx)
{
    const d = ctx.config.display;
    const sizes = [1, 2, 4, 8, 16, 32, 64, 128, 256].filter(mb => mb <= ctx.choices.max_vram);
    return [
        select_field("Display adapter", ctx.choices.graphics_adapters, d.adapter, value => ctx.set("display.adapter", value), v => ADAPTER_LABELS[v] || v),
        d.vram_mb === null ? h("p.note", null, "Video memory: the saved state's") :
            select_field("Video memory", sizes, d.vram_mb, value => ctx.set("display.vram_mb", value), v => v + " MB"),
        check_field("Graphics proxy (WebGPU: Direct3D and OpenGL of the guest)", d.proxy, value => ctx.set("display.proxy", value)),
        select_field("Vulkan", DISPLAY_VULKAN, d.vulkan, value => ctx.set("display.vulkan", value), v => VULKAN_LABELS[v] || v,
            d.adapter === "virtio_gpu" ? {} : { disabled: true, title: "only virtio-gpu has Vulkan" }),
        select_field("Displays", [1, 2, 3, 4], d.displays, value => ctx.set("display.displays", value), String,
            d.adapter === "virtio_gpu" ? {} : { disabled: true, title: "only virtio-gpu has more than one display" }),
    ];
}

/** @param {PanelContext} ctx */
export function serial_panel(ctx)
{
    const virt = ctx.config.machine.type === "virt" || ctx.config.machine.type === "ranchu";
    const attach = virt ? ["none", "terminal"] : ["none", "terminal", "modem"];
    return [0, 1, 2, 3].map(port =>
    {
        const entry = ctx.config.serial.find(s => s.port === port);
        const value = entry ? entry.attach : "none";
        return select_field("UART" + port + (port === 0 ? " (COM1)" : " (COM" + (port + 1) + ")"), attach, value, next_value => ctx.edit(next =>
        {
            next.serial = next.serial.filter(s => s.port !== port);
            if(next_value === "modem") for(const s of next.serial) if(s.attach === "modem") s.attach = "none";
            if(next_value !== "none") next.serial.push({ port, attach: next_value });
            next.serial.sort((a, b) => a.port - b.port);
        }), v => ({ none: "Not connected", terminal: "The serial terminal", modem: "A modem (Hayes AT commands)" })[v]);
    });
}

/** @param {PanelContext} ctx */
export function shared_folder_panel(ctx)
{
    const fs = /** @type {{baseurl?: string, basefs?: {url: string}}} */ (ctx.config.filesystem);
    return [
        h("p.note", null, "A 9p file system: files sent in and out while the machine runs, or files served from a URL."),
        text_field("Files' base URL (optional)", fs.baseurl || "", value => ctx.edit(next =>
        {
            const f = /** @type {any} */ (next.filesystem);
            if(value.trim()) f.baseurl = value.trim(); else delete f.baseurl;
        })),
        text_field("Its description, fs.json (optional)", fs.basefs ? fs.basefs.url : "", value => ctx.edit(next =>
        {
            const f = /** @type {any} */ (next.filesystem);
            if(value.trim()) f.basefs = { url: value.trim() }; else delete f.basefs;
        })),
    ];
}

/** @param {PanelContext} ctx */
export function virt_panel(ctx)
{
    const v = ctx.config.virt;
    const automatic = v.input === null;
    return [
        select_field("virtio transport", ["mmio", "pci"], v.transport, value => ctx.edit(next =>
        {
            next.virt.transport = value;
            if(value !== "pci") next.virt.gpu_pci_slot = null;
        }), t => t === "mmio" ? "MMIO (the default)" : "PCI Express"),
        check_field("Input devices as the display has them (virtio-gpu: keyboard, tablet, touch screen)", automatic,
            value => ctx.edit(next => { next.virt.input = value ? null : VIRT_INPUTS.slice(); })),
        automatic ? null : VIRT_INPUTS.map(kind => check_field(kind, /** @type {string[]} */ (v.input).includes(kind), value => ctx.edit(next =>
        {
            const list = /** @type {string[]} */ (next.virt.input).filter(k => k !== kind);
            if(value) list.push(kind);
            next.virt.input = VIRT_INPUTS.filter(k => list.includes(k));
        }))),
        number_field("virtio console ports (0: none)", v.console_ports, { min: 0, max: 30 }, value => ctx.set("virt.console_ports", value)),
        check_field("vsock", v.vsock, value => ctx.set("virt.vsock", value)),
        v.transport === "pci" && ctx.config.display.adapter === "virtio_gpu" ?
            select_field("virtio-gpu's PCI slot", [null, 1, 2, 3, 4], v.gpu_pci_slot, value => ctx.set("virt.gpu_pci_slot", value), s => s === null ? "Any" : "00:0" + s + ".0") : null,
    ];
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/app/ui/panels/storage.js                                                             0000644 0000000 0000000 00000020076 00000000000 015141  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog's panels of the drives (docs/vm-manager-plan.md "设置
// 对话框"): hard disks (their source, disk_option, disk_error, bus), USB
// disks, the CD/DVD drive, floppy drives, direct boot (kernel, initrd,
// multiboot).

import { h } from "../dom.js";
import { image_picker } from "../image_picker.js";
import { select_field, check_field, text_field } from "./system.js";

/** @typedef {import("../settings.js").PanelContext} PanelContext */

/**
 * The bus a hard disk is on
 * @param {string} machine
 */
function bus(machine)
{
    return machine === "q35" ? "AHCI (SATA)" : machine === "virt" || machine === "ranchu" ? "virtio-blk" : "IDE";
}

/**
 * Why a disk cannot be written back, or ""
 * @param {import("../../vm_config.js").Image | null} image
 */
function read_write_problem(image)
{
    if(!image) return "no image";
    if(image.kind === "file") return "a file chosen on this computer can only be read: use the disk service to write one back";
    if(image.kind === "empty") return "an empty disk in memory has nothing to write back to";
    if(image.kind === "url" && (image.use_parts || /\.zst$/.test(image.url))) return "an image in parts can only be read";
    return "";
}

/**
 * @param {PanelContext} ctx
 * @param {number} index
 */
export function disk_panel(ctx, index)
{
    const disk = ctx.config.disks[index];
    const problem = read_write_problem(disk.image);
    const where = disk.image && disk.image.kind === "url" ? (ctx.service && disk.image.url.startsWith(ctx.service.url) ? "the disk service's image" : "the image at its URL") :
        disk.image && disk.image.kind === "browser" ? "the browser disk" : "nowhere: the disk's source cannot be written";
    return [
        select_field("Drive", ["hda", "hdb"], disk.slot, value => ctx.edit(next => { next.disks[index].slot = value; }),
            v => v === "hda" ? "First hard disk (hda)" : "Second hard disk (hdb)"),
        h("p.note", null, "Bus: " + bus(ctx.config.machine.type)),
        image_picker({ label: "Source", role: "disk", image: disk.image, store: ctx.store, service: ctx.service, machine_name: ctx.config.name,
            on_change: (image, extra) => ctx.edit(next =>
            {
                next.disks[index].image = image;
                if(extra && extra.read_write) next.disks[index].disk_option = "read_write";
                if(read_write_problem(image)) next.disks[index].disk_option = "read_only";
            }) }),
        select_field("The guest's changes", ["read_only", "read_write"], disk.disk_option, value => ctx.set("disks." + index + ".disk_option", value),
            v => v === "read_only" ? "Kept in memory, the image unchanged (read only)" : "Written back to " + where + " (read write)",
            problem ? { disabled: true, title: problem } : {}),
        select_field("When a read or write fails", ["stop", "report"], disk.disk_error, value => ctx.set("disks." + index + ".disk_error", value),
            v => v === "stop" ? "Pause the machine and ask (retry or power off)" : "Report it to the guest"),
    ];
}

/**
 * A USB disk (usb.disks[index]): a disk image as a USB stick, its source as
 * a hard disk's
 * @param {PanelContext} ctx
 * @param {number} index
 */
export function usb_disk_panel(ctx, index)
{
    const usb = /** @type {{tablet: boolean, disks: import("../../vm_config.js").UsbDisk[]}} */ (ctx.config.usb);
    const disk = usb.disks[index];
    const path = "usb.disks." + index;
    const problem = read_write_problem(disk.image);
    return [
        h("p.note", null, "A disk image as a USB stick (mass storage, in a port of the USB controller): the guest mounts it as a removable disk. " +
            "While the machine runs, the Devices menu unplugs it or plugs in another."),
        image_picker({ label: "Source", role: "disk", image: disk.image, store: ctx.store, service: ctx.service, machine_name: ctx.config.name,
            on_change: (image, extra) => ctx.edit(next =>
            {
                const d = /** @type {any} */ (next.usb).disks[index];
                d.image = image;
                if(extra && extra.read_write) d.disk_option = "read_write";
                if(read_write_problem(image)) d.disk_option = "read_only";
            }) }),
        select_field("The guest's changes", ["read_only", "read_write"], disk.disk_option, value => ctx.set(path + ".disk_option", value),
            v => v === "read_only" ? "Kept in memory, the image unchanged (read only)" : "Written back to the image (read write)",
            problem ? { disabled: true, title: problem } : {}),
        check_field("Write protected (the guest can only read it)", disk.write_protected, value => ctx.set(path + ".write_protected", value)),
        select_field("When a read or write fails", ["stop", "report"], disk.disk_error, value => ctx.set(path + ".disk_error", value),
            v => v === "stop" ? "Pause the machine and ask (retry or power off)" : "Report it to the guest"),
    ];
}

/** @param {PanelContext} ctx */
export function cdrom_panel(ctx)
{
    const virt = ctx.config.machine.type === "virt" || ctx.config.machine.type === "ranchu";
    return [
        image_picker({ label: "Disc", role: "cdrom", optional: true, image: ctx.config.cdrom.image, store: ctx.store, service: ctx.service,
            on_change: image => ctx.set("cdrom.image", image) }),
        virt ? h("p.note", null, "On the " + ctx.config.machine.type + " machine the disc is a read-only virtio disk.") : null,
        select_field("When a read fails", ["stop", "report"], ctx.config.cdrom.disk_error, value => ctx.set("cdrom.disk_error", value),
            v => v === "stop" ? "Pause the machine and ask" : "Report it to the guest"),
    ];
}

/**
 * @param {PanelContext} ctx
 * @param {number} index
 */
export function floppy_panel(ctx, index)
{
    const floppy = ctx.config.floppies[index];
    const problem = floppy.image ? read_write_problem(floppy.image) : "no image";
    return [
        select_field("Drive", ["fda", "fdb"], floppy.slot, value => ctx.edit(next => { next.floppies[index].slot = value; }),
            v => v === "fda" ? "A:" : "B:"),
        image_picker({ label: "Floppy", role: "floppy", optional: true, image: floppy.image, store: ctx.store, service: ctx.service,
            on_change: (image, extra) => ctx.edit(next =>
            {
                next.floppies[index].image = image;
                if(extra && extra.read_write) next.floppies[index].disk_option = "read_write";
                if(!image || read_write_problem(image)) next.floppies[index].disk_option = "read_only";
            }) }),
        select_field("The guest's changes", ["read_only", "read_write"], floppy.disk_option, value => ctx.set("floppies." + index + ".disk_option", value),
            v => v === "read_only" ? "Kept in memory (read only)" : "Written back (read write)", problem ? { disabled: true, title: problem } : {}),
    ];
}

/** @param {PanelContext} ctx */
export function direct_boot_panel(ctx)
{
    const k = /** @type {NonNullable<import("../../vm_config.js").VMConfig["kernel"]>} */ (ctx.config.kernel);
    const virt = ctx.config.machine.type === "virt" || ctx.config.machine.type === "ranchu";
    const set = (name, value) => ctx.edit(next => { /** @type {any} */ (next.kernel)[name] = value; });
    return [
        image_picker({ label: virt ? "Kernel (Image, or a gzipped vmlinuz)" : "Kernel (bzImage)", role: "file", optional: true, image: k.bzimage, store: ctx.store,
            on_change: image => set("bzimage", image) }),
        image_picker({ label: "Initrd", role: "file", optional: true, image: k.initrd, store: ctx.store, on_change: image => set("initrd", image) }),
        text_field("Command line", k.cmdline || "", value => set("cmdline", value.trim() || null),
            { placeholder: virt ? "console=ttyAMA0 console=tty0 … (the default)" : "" }),
        virt ? null : image_picker({ label: "Multiboot kernel", role: "file", optional: true, image: k.multiboot, store: ctx.store,
            on_change: image => set("multiboot", image) }),
        check_field("The kernel and initrd from the shared folder (/boot)", k.from_filesystem, value => set("from_filesystem", value)),
    ];
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/app/ui/panels/system.js                                                              0000644 0000000 0000000 00000034541 00000000000 015023  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog's panels of the machine itself (docs/vm-manager-plan.md
// "设置对话框"): general, memory, processor, machine and firmware, advanced.

import { confirm, h } from "../dom.js";
import { image_picker } from "../image_picker.js";
import { ARM_MACHINE_TYPES, DEFAULT_CPU_PROFILES } from "../../../machine_options.js";
import { disk_id, reset_disk } from "../../browser_disks.js";
import { uefi_vars_template } from "../../vm_config.js";

/** @typedef {import("../settings.js").PanelContext} PanelContext */

export const CPU_LABELS = { x86: "x86 (32-bit, up to SSE3)", x86_64: "x86_64 (64-bit, every instruction set)", arm64: "arm64 (64-bit ARM)",
    arm32: "ARM (32-bit, ARMv7-A)" };
/**
 * The CPU models (cpu.profile; docs/iphone4-plan.md "CPU 型号"): the name the
 * panel shows, and what the model is for
 */
export const CPU_PROFILE_LABELS = {
    "generic-x86": ["Generic 32-bit x86 (recommended)", "DOS, Windows 3.x to XP, 32-bit Linux"],
    "generic-x86-64": ["Generic 64-bit x86 (recommended)", "64-bit Windows 8.1 to 11, 64-bit Linux"],
    "generic-arm64": ["Generic 64-bit ARM (recommended)", "64-bit Linux, Android 16"],
    "generic-arm64-compat32": ["Generic 64-bit ARM that runs 32-bit programs",
        "A 64-bit system that runs 32-bit programs too (armhf, armeabi-v7a); their code is interpreted, slower than 64-bit code"],
    "cortex-a15": ["ARM Cortex-A15 (2011)", "32-bit Linux, Android 7.1"],
};
export const MACHINE_LABELS = { i440fx: "i440FX (IDE, PCI)", q35: "Q35 (AHCI, PCI Express)", virt: "virt (ARM, virtio devices)",
    ranchu: "ranchu (the Android Emulator's board)" };
const FIRMWARE_LABELS = { seabios: "SeaBIOS (the default)", bochs: "Bochs BIOS", custom: "An image of your own", uefi: "UEFI (OVMF)" };
const BOOT_ORDER_LABELS = { 0: "Automatic (floppy, then hard disk, then CD)", 0x213: "CD, floppy, hard disk", 0x123: "CD, hard disk, floppy",
    0x231: "Floppy, CD, hard disk", 0x321: "Floppy, hard disk, CD", 0x312: "Hard disk, floppy, CD", 0x132: "Hard disk, CD, floppy" };

/**
 * A select of values
 * @param {string} label
 * @param {Array<any>} values
 * @param {any} value
 * @param {(value: any) => void} on_change
 * @param {(value: any) => string} [text]
 * @param {{disabled?: boolean, title?: string}} [options]
 */
export function select_field(label, values, value, on_change, text = String, options = {})
{
    const select = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": label, disabled: !!options.disabled, title: options.title || "" },
        values.map((v, i) => h("option", { value: String(i), selected: v === value }, text(v)))));
    select.addEventListener("change", () => on_change(values[+select.value]));
    return h("label.field", null, h("span", null, label), select, options.disabled && options.title ? h("small.reason", null, options.title) : null);
}

/**
 * A checkbox; disabled with its reason when the value is fixed
 * @param {string} label
 * @param {boolean} value
 * @param {(value: boolean) => void} on_change
 * @param {string} [fixed_reason]
 */
export function check_field(label, value, on_change, fixed_reason)
{
    const box = /** @type {HTMLInputElement} */ (h("input", { type: "checkbox", checked: value, disabled: !!fixed_reason }));
    box.addEventListener("change", () => on_change(box.checked));
    return h("label.check", { title: fixed_reason || "" }, box, " " + label, fixed_reason ? h("small.reason", null, " (" + fixed_reason + ")") : null);
}

/**
 * A number field, applied when it is left or Enter is pressed
 * @param {string} label
 * @param {number} value
 * @param {{min: number, max: number, step?: number}} range
 * @param {(value: number) => void} on_change
 */
export function number_field(label, value, range, on_change)
{
    const input = /** @type {HTMLInputElement} */ (h("input", { type: "number", value, min: range.min, max: range.max, step: range.step || 1, "aria-label": label }));
    input.addEventListener("change", () =>
    {
        const n = Math.round(+input.value);
        on_change(Number.isFinite(n) ? Math.min(range.max, Math.max(range.min, n)) : value);
    });
    return h("label.field", null, h("span", null, label), input);
}

/**
 * A text field, applied when it is left or Enter is pressed
 * @param {string} label
 * @param {string} value
 * @param {(value: string) => void} on_change
 * @param {{multiline?: boolean, placeholder?: string}} [options]
 */
export function text_field(label, value, on_change, options = {})
{
    const input = /** @type {HTMLInputElement} */ (h(options.multiline ? "textarea" : "input",
        { type: "text", value, placeholder: options.placeholder || "", "aria-label": label, rows: 4 }));
    if(options.multiline) input.value = value;
    input.addEventListener("change", () => on_change(input.value));
    return h("label.field", null, h("span", null, label), input);
}

/** @param {PanelContext} ctx */
export function general_panel(ctx)
{
    return [
        text_field("Name", ctx.config.name, value => ctx.set("name", value.trim())),
        text_field("Notes", ctx.config.notes, value => ctx.set("notes", value), { multiline: true }),
    ];
}

/** @param {PanelContext} ctx */
export function memory_panel(ctx)
{
    const c = ctx.config;
    return [
        number_field("Memory in MB", c.memory.mb, { min: 16, max: ctx.choices.max_memory, step: 16 }, mb => ctx.set("memory.mb", mb)),
        h("p.note", null, c.cpu.type === "x86" ? "The 32-bit CPU reaches 2048 MB; more chooses x86_64." :
            c.cpu.type === "arm32" ? "The 32-bit ARM CPU reaches 2048 MB (its kernels' high memory above 768 MB)." :
            "Up to 2048 MB live in the WebAssembly heap, the rest in extended RAM above 4 GiB (64-bit guests only)."),
    ];
}

/** @param {PanelContext} ctx */
export function processor_panel(ctx)
{
    const c = ctx.config;
    const cores = Array.from({ length: ctx.choices.max_cores }, (_, i) => i + 1);
    return [
        select_field("CPU", ctx.choices.cpu_types, c.cpu.type, value => ctx.set("cpu.type", value), v => CPU_LABELS[v] || v),
        select_field("Cores", cores, c.cpu.cores, value => ctx.set("cpu.cores", value)),
        check_field("Run the cores in host threads where the page allows it (otherwise they take turns)", c.cpu.parallel, value => ctx.set("cpu.parallel", value),
            c.cpu.cores === 1 ? "one core" : undefined),
        check_field("JIT compiler", c.cpu.jit, value => ctx.set("cpu.jit", value)),
        // (the CPU model: automatic is the CPU type's default; a real chip only where software checks which CPU it is)
        select_field("CPU model", ctx.choices.cpu_profiles, c.cpu.profile, value => ctx.set("cpu.profile", value),
            v => v === null ? "Automatic (the system decides)" : CPU_PROFILE_LABELS[v]?.[0] || v),
        h("p.note", null, CPU_PROFILE_LABELS[c.cpu.profile || DEFAULT_CPU_PROFILES[c.cpu.type]]?.[1] || ""),
    ];
}

/** @param {PanelContext} ctx */
export function machine_panel(ctx)
{
    const c = ctx.config, ch = ctx.choices;
    // (an ARM board, virt or ranchu: no PC firmware)
    const arm = ARM_MACHINE_TYPES.includes(c.machine.type);
    const q35 = c.machine.type === "q35";
    const bochs = !!(c.machine.bios && c.machine.bios.kind === "url" && c.machine.bios.url === "bios/bochs-bios.bin");
    const firmware = c.machine.firmware === "uefi" ? "uefi" : c.machine.bios === null ? "seabios" : bochs ? "bochs" : "custom";
    const firmware_field = select_field("Firmware", ["seabios", "bochs", "custom", "uefi"], firmware, value =>
    {
        ctx.edit(next =>
        {
            next.machine.firmware = value === "uefi" ? "uefi" : "seabios";
            next.machine.bios = value === "seabios" || value === "uefi" ? null : value === "bochs" ? { kind: "url", url: "bios/bochs-bios.bin" } :
                { kind: "url", url: "", async: false };
            next.machine.vga_bios = value === "bochs" ? { kind: "url", url: "bios/bochs-vgabios.bin" } : value === "seabios" || value === "uefi" ? null :
                next.machine.vga_bios;
            // (OVMF is the X64 build: the 64-bit CPU, with ACPI)
            if(value === "uefi")
            {
                next.cpu.type = "x86_64";
                next.machine.acpi = true;
            }
        });
    }, v => FIRMWARE_LABELS[v], arm ? { disabled: true, title: ch.unavailable["bios"] } : {});
    return [
        select_field("Machine", ch.machine_types, c.machine.type, value => ctx.set("machine.type", value), v => MACHINE_LABELS[v] || v),
        firmware_field,
        !arm && firmware === "uefi" ? uefi_fields(ctx) : null,
        !arm && firmware === "custom" ? [
            image_picker({ label: "BIOS image", role: "file", image: c.machine.bios, store: ctx.store, on_change: image => ctx.set("machine.bios", image) }),
            image_picker({ label: "VGA BIOS image", role: "file", optional: true, image: c.machine.vga_bios, store: ctx.store,
                on_change: image => ctx.set("machine.vga_bios", image) }),
        ] : null,
        check_field("ACPI", c.machine.acpi, value => ctx.set("machine.acpi", value), ch.acpi_fixed ? ch.acpi_fixed.reason : undefined),
        check_field("HPET (high precision event timer)", c.machine.hpet, value => ctx.set("machine.hpet", value), q35 ? undefined : ch.unavailable["hpet"]),
        check_field("SMBus controller", c.machine.smbus, value => ctx.set("machine.smbus", value), q35 ? undefined : ch.unavailable["smbus"]),
        q35 ? number_field("PCI Express root ports", c.machine.pcie_root_ports, { min: 0, max: 6 }, value => ctx.set("machine.pcie_root_ports", value)) :
            h("p.note", null, "PCI Express root ports: " + ch.unavailable["pcie_root_ports"]),
        select_field("Boot order", ch.boot_orders, c.machine.boot_order, value => ctx.set("machine.boot_order", value), v => BOOT_ORDER_LABELS[v],
            arm ? { disabled: true, title: "the " + c.machine.type + " machine boots its kernel" } : {}),
        check_field("Fast boot (no boot menu delay)", c.machine.fastboot, value => ctx.set("machine.fastboot", value), arm ? "no PC firmware" : undefined),
        check_field("Boot menu", c.machine.bootmenu, value => ctx.set("machine.bootmenu", value), arm ? "no PC firmware" : undefined),
    ];
}

const SECURE_BOOT_KEY_LABELS = {
    microsoft: "Microsoft's (Windows; Linux through shim)",
    none: "None: Setup Mode (enroll your own)",
};

/**
 * The UEFI firmware's note, Secure Boot and the variable store's reset
 * @param {PanelContext} ctx
 */
function uefi_fields(ctx)
{
    const c = ctx.config;
    const vars = c.machine.uefi_vars;
    const q35 = c.machine.type === "q35";
    const status = h("small.reason", { role: "status" });
    const reset = /** @type {HTMLButtonElement} */ (h("button", { type: "button", disabled: !vars || vars.kind !== "browser",
        title: vars ? "" : "The variable store is made at the first power-on" }, "Reset UEFI variables…"));
    reset.addEventListener("click", async () =>
    {
        if(!vars || vars.kind !== "browser") return;
        const keys = c.machine.secure_boot && c.machine.secure_boot_keys === "microsoft" ? "Microsoft's Secure Boot keys" : "no Secure Boot keys";
        if(!await confirm("Reset UEFI variables?", "The firmware's variables (its boot entries, its settings) go back to the template's, " +
            "with " + keys + "; the firmware makes its boot entries again at the next power-on.", "Reset", true)) return;
        reset.disabled = true;
        status.textContent = "Resetting…";
        try
        {
            await reset_disk(disk_id(vars.path), uefi_vars_template(c.machine));
            status.textContent = "Reset: the template's variables, " + keys + ".";
        }
        catch(e)
        {
            status.textContent = "Not reset: " + e.message;
        }
        reset.disabled = false;
    });
    return [
        h("p.note", null, "UEFI is OVMF (edk2-stable202408, as QEMU ships it) on the x86_64 CPU; on i440FX the devices take QEMU's places. " +
            "Its variables (boot entries, settings) are kept in a browser disk of the machine's, made at the first power-on " +
            "(with the CPU in a Worker; otherwise they last until the machine is turned off)."),
        check_field("Secure Boot", c.machine.secure_boot, value => ctx.set("machine.secure_boot", value),
            q35 ? undefined : "Secure Boot needs the Q35 machine (its firmware runs in SMM)"),
        c.machine.secure_boot ? [
            select_field("Secure Boot keys", Object.keys(SECURE_BOOT_KEY_LABELS), c.machine.secure_boot_keys,
                value => ctx.set("machine.secure_boot_keys", value), v => SECURE_BOOT_KEY_LABELS[v]),
            h("p.note", null, "The firmware loads only what the keys allow, and only its own code in SMM changes them. " +
                "The keys are enrolled when the variable store is made (the first power-on) or reset: after changing Secure Boot " +
                "or its keys, Reset UEFI variables… enrolls them."),
        ] : null,
        h("div.field", null, reset, " ", status),
    ];
}

/** @param {PanelContext} ctx */
export function advanced_panel(ctx)
{
    const c = ctx.config, a = c.advanced;
    const virt = ARM_MACHINE_TYPES.includes(c.machine.type);
    return [
        check_field("Run the CPU in a Worker (the page stays responsive)", a.cpu_worker, value => ctx.set("advanced.cpu_worker", value)),
        check_field("Compile 32-bit code in the x64 page tier (ir_tier0)", a.ir_tier0, value => ctx.set("advanced.ir_tier0", value), virt ? "x86 only" : undefined),
        check_field("x87: fast arithmetic in 64-bit floats", a.x87_fast_math, value => ctx.set("advanced.x87_fast_math", value), virt ? "x86 only" : undefined),
        check_field("x87: cached compiled regions", a.x87_jit_cache, value => ctx.set("advanced.x87_jit_cache", value), virt ? "x86 only" : undefined),
        virt ? h("p.note", null, "CPUID level: " + ctx.choices.unavailable["cpuid_level"]) :
            select_field("CPUID level", [null, 1, 2, 4, 7, 0xd], a.cpuid_level, value => ctx.set("advanced.cpuid_level", value),
                v => v === null ? "The CPU's own" : "Level " + v + (v === 2 ? " (Windows NT 4)" : "")),
        check_field("Mouse off at the start", a.mouse_disabled, value => ctx.set("advanced.mouse_disabled", value)),
        image_picker({ label: "Start from a saved state", role: "file", optional: true, image: c.initial_state, store: ctx.store,
            on_change: image => ctx.edit(next => { next.initial_state = image; if(image === null && next.display.vram_mb === null) next.display.vram_mb = 8; }) }),
    ];
}
                                                                                                                                                               source/v64/src/app/ui/settings.js                                                                   0000644 0000000 0000000 00000035670 00000000000 014061  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog (docs/vm-manager-plan.md "设置对话框", U3): the
// hardware list on the left, the chosen item's panel on the right, Add and
// Remove under the list. Every control offers only what the machine allows
// (src/app/vm_model.js) and a change says what else it changed; before
// saving, the whole configuration is checked (check_config) and each
// problem shows on its item's panel.

import { h, replace } from "./dom.js";
import { choices, change, fitted } from "../vm_model.js";
import { check_config } from "../vm_config.js";
import { describe_image } from "./describe.js";
import { general_panel, memory_panel, processor_panel, machine_panel, advanced_panel, CPU_LABELS, MACHINE_LABELS } from "./panels/system.js";
import { disk_panel, usb_disk_panel, cdrom_panel, floppy_panel, direct_boot_panel } from "./panels/storage.js";
import { network_panel, sound_panel, usb_panel, tpm_panel, display_panel, serial_panel, shared_folder_panel, virt_panel, NIC_LABELS, SOUND_LABELS } from "./panels/devices.js";
import { android_panel } from "./panels/android.js";
import { ANDROID_DEFAULTS } from "../vm_config.js";
import { RANCHU_DEVICES } from "../../android/devices.js";
import { USB_PORTS } from "../../machine_options.js";

/** @typedef {import("../vm_config.js").VMConfig} VMConfig */
/** @typedef {import("../vm_config.js").Problem} Problem */

/**
 * @typedef {Object} PanelContext
 * @property {VMConfig} config the configuration being edited
 * @property {ReturnType<typeof choices>} choices what its controls may hold
 * @property {(path: string, value: any) => void} set a field changed (vm_model's change: what it implies too)
 * @property {(fn: (next: VMConfig) => void) => void} edit a change of several fields, then fitted to the machine
 * @property {{put_handle: (handle: any) => Promise<string>}} store where picked files' handles go
 * @property {import("../disk_service_client.js").Service | null} service the disk service, if there is one
 */

/**
 * @typedef {Object} Item
 * @property {string} id
 * @property {string} label
 * @property {string} summary
 * @property {(ctx: PanelContext) => any} panel
 * @property {((next: VMConfig) => void) | null} remove
 */

/**
 * The hardware list of a configuration
 * @param {VMConfig} c
 * @return {Item[]}
 */
export function hardware_items(c)
{
    const virt = c.machine.type === "virt";
    /** @type {Item[]} */
    const items = [
        { id: "general", label: "General", summary: c.name, panel: general_panel, remove: null },
        { id: "memory", label: "Memory", summary: c.memory.mb + " MB", panel: memory_panel, remove: null },
        { id: "processor", label: "Processor", summary: c.cpu.type + ", " + c.cpu.cores + (c.cpu.cores === 1 ? " core" : " cores"), panel: processor_panel, remove: null },
        { id: "machine", label: "Machine and firmware", summary: MACHINE_LABELS[c.machine.type] || c.machine.type, panel: machine_panel, remove: null },
    ];
    c.disks.forEach((disk, i) => items.push({
        id: "disk-" + i, label: "Hard disk (" + disk.slot + ")", summary: describe_image(disk.image), panel: ctx => disk_panel(ctx, i),
        remove: next => { next.disks.splice(i, 1); },
    }));
    items.push({ id: "cdrom", label: "CD/DVD", summary: describe_image(c.cdrom.image), panel: cdrom_panel, remove: null });
    c.floppies.forEach((floppy, i) => items.push({
        id: "floppy-" + i, label: "Floppy (" + floppy.slot + ")", summary: describe_image(floppy.image), panel: ctx => floppy_panel(ctx, i),
        remove: next => { next.floppies.splice(i, 1); },
    }));
    c.network.forEach((n, i) => items.push({
        id: "network-" + i, label: "Network adapter" + (c.network.length > 1 ? " " + (i + 1) : ""), summary: n.device === "none" ? "none" : (NIC_LABELS[n.device] || n.device) + ", " + n.backend,
        panel: ctx => network_panel(ctx, i), remove: c.network.length > 1 ? next => { next.network.splice(i, 1); } : null,
    }));
    items.push({ id: "sound", label: "Sound card", summary: (c.sound.device === "none" ? "none" : SOUND_LABELS[c.sound.device] || c.sound.device) +
        (c.sound.mute ? ", muted" : ""),
        panel: sound_panel, remove: null });
    if(c.usb) items.push({ id: "usb", label: "USB", summary: c.usb.controller.toUpperCase() + (c.usb.tablet ? ", tablet" : ""), panel: usb_panel,
        remove: next => { next.usb = null; } });
    (c.usb ? c.usb.disks : []).forEach((disk, i) => items.push({
        id: "usb-disk-" + i, label: "USB disk (" + disk.id + ")", summary: describe_image(disk.image), panel: ctx => usb_disk_panel(ctx, i),
        remove: next => { /** @type {any} */ (next.usb).disks.splice(i, 1); },
    }));
    if(c.tpm) items.push({ id: "tpm", label: "TPM", summary: "TPM 2.0 (CRB)", panel: tpm_panel, remove: next => { next.tpm = null; } });
    items.push({ id: "display", label: "Display", summary: c.display.adapter + (c.display.vram_mb ? ", " + c.display.vram_mb + " MB" : ""), panel: display_panel, remove: null });
    items.push({ id: "serial", label: "Serial ports", summary: c.serial.filter(s => s.attach !== "none").map(s => "UART" + s.port + " " + s.attach).join(", ") || "none",
        panel: serial_panel, remove: null });
    if(c.filesystem) items.push({ id: "filesystem", label: "Shared folder", summary: c.filesystem.baseurl || "in the browser", panel: shared_folder_panel,
        remove: next => { next.filesystem = null; } });
    if(c.kernel) items.push({ id: "kernel", label: "Direct boot", summary: c.kernel.bzimage ? describe_image(c.kernel.bzimage) : "kernel not chosen", panel: direct_boot_panel,
        remove: next => { next.kernel = null; } });
    if(c.android) items.push({ id: "android", label: "Android", summary: ({ venus: "Venus", gfxstream: "gfxstream", host: "host GPU", guest: "CPU" }[c.android.gpu_mode] ||
        (/^ranchu_/.test(c.android.device) ? "CPU" : "SwiftShader")) +
        (c.android.vendor_ramdisk === "debug" ? ", debug ramdisk" : ""), panel: android_panel, remove: next => { next.android = null; } });
    if(virt) items.push({ id: "virt", label: "virt devices", summary: c.virt.transport + (c.virt.vsock ? ", vsock" : ""), panel: virt_panel, remove: null });
    items.push({ id: "advanced", label: "Advanced", summary: c.advanced.cpu_worker ? "CPU in a Worker" : "CPU in the page", panel: advanced_panel, remove: null });
    return items;
}

/**
 * The item a problem belongs to
 * @param {string} path
 * @return {string}
 */
export function item_of(path)
{
    const [head, index] = path.split(".");
    // (a USB disk's: usb.disks.<i>)
    if(head === "usb" && index === "disks" && /^\d+$/.test(path.split(".")[2] || "")) return "usb-disk-" + path.split(".")[2];
    switch(head)
    {
        case "disks": return "disk-" + (index || 0);
        case "floppies": return "floppy-" + (index || 0);
        case "network": return "network-" + (index || 0);
        case "cpu": return "processor";
        case "memory": case "machine": case "cdrom": case "sound": case "usb": case "tpm": case "display": case "serial": case "filesystem": case "virt": case "advanced": return head;
        case "kernel": return "kernel";
        case "android": return "android";
        case "initial_state": return "advanced";
    }
    return "general";
}

/**
 * What can be added to a configuration
 * @param {VMConfig} c
 * @return {Array<[string, (next: VMConfig) => void]>}
 */
function additions(c)
{
    const virt = c.machine.type === "virt", arm = virt || c.machine.type === "ranchu";
    /** @type {Array<[string, (next: VMConfig) => void]>} */
    const list = [];
    if(c.disks.length < 2)
    {
        list.push(["Hard disk", next => { next.disks.push({ slot: next.disks.some(d => d.slot === "hda") ? "hdb" : "hda", image: { kind: "empty", size: 512 << 20 },
            disk_option: "read_only", disk_error: "stop" }); }]);
    }
    if(!arm && c.floppies.length < 2)
    {
        list.push(["Floppy drive", next => { next.floppies.push({ slot: next.floppies.some(f => f.slot === "fda") ? "fdb" : "fda", image: null, disk_option: "read_only" }); }]);
    }
    if(virt && c.network.length < 4)
    {
        list.push(["Network adapter", next => { next.network.push({ device: "virtio", backend: "none", relay_url: "", mtu: 1500, mac_address_translation: false }); }]);
    }
    if(!arm && !c.usb) list.push(["USB", next => { next.usb = { controller: "uhci", tablet: true, disks: [] }; }]);
    // (a TPM 2.0: with ACPI, which describes it)
    if(!arm && !c.tpm) list.push(["TPM", next => { next.tpm = { state: null }; next.machine.acpi = true; }]);
    // (a USB disk in a free port: with USB, or with it added for the disk)
    if(!arm && (!c.usb || c.usb.disks.length + (c.usb.tablet ? 1 : 0) < (USB_PORTS[c.usb.controller] || 0)))
    {
        list.push(["USB disk", next =>
        {
            if(!next.usb) next.usb = { controller: "uhci", tablet: false, disks: [] };
            const ids = next.usb.disks.map(d => d.id);
            let n = 0;
            while(ids.includes("usb" + n)) n++;
            next.usb.disks.push({ id: "usb" + n, image: { kind: "empty", size: 64 << 20 }, disk_option: "read_only", disk_error: "stop", write_protected: false });
        }]);
    }
    if(!c.filesystem) list.push(["Shared folder", next => { next.filesystem = {}; }]);
    if(!c.kernel) list.push(["Direct boot", next => { next.kernel = { bzimage: null, initrd: null, cmdline: null, multiboot: null, from_filesystem: false }; }]);
    // (Cuttlefish's on the arm64 virt machine, an emulator image's on ranchu)
    if(virt && c.cpu.type === "arm64" && !c.android) list.push(["Android boot", next => { next.android = Object.assign({}, ANDROID_DEFAULTS); }]);
    if(c.machine.type === "ranchu" && !c.android)
    {
        const model = RANCHU_DEVICES.find(d => d.cpu === c.cpu.type);
        if(model) list.push(["Android boot", next => { next.android = Object.assign({}, ANDROID_DEFAULTS, { device: model.id }); }]);
    }
    return list;
}

/**
 * Edit a configuration in the dialog; resolves with the saved configuration
 * (checked) or null when cancelled
 * @param {VMConfig} config
 * @param {{store: PanelContext["store"], service?: PanelContext["service"], title?: string, save_label?: string, item?: string}} options
 * @return {Promise<VMConfig | null>}
 */
export function open_settings(config, options)
{
    return new Promise(resolve =>
    {
        let working = fitted(config).config;
        let notes = fitted(config).notes;
        let selected = options.item || "general";
        /** @type {Problem[]} */
        let problems = [];
        const element = /** @type {HTMLDialogElement} */ (h("dialog.settings-dialog", { "aria-label": options.title || "Settings" }));
        const close = value =>
        {
            element.close();
            element.remove();
            resolve(value);
        };
        element.addEventListener("cancel", e => { e.preventDefault(); close(null); });

        /** @type {PanelContext} */
        const ctx = {
            get config() { return working; },
            get choices() { return choices(working); },
            set(path, value)
            {
                const result = change(working, path, value);
                working = result.config;
                notes = result.notes;
                problems = [];
                render();
            },
            edit(fn)
            {
                const next = JSON.parse(JSON.stringify(working));
                fn(next);
                const result = fitted(next);
                working = result.config;
                notes = result.notes;
                problems = [];
                render();
            },
            store: options.store,
            service: options.service || null,
        };

        const save = () =>
        {
            problems = check_config(working);
            if(problems.length)
            {
                selected = item_of(problems[0].path);
                render();
                return;
            }
            close(working);
        };

        function render()
        {
            const items = hardware_items(working);
            if(!items.some(item => item.id === selected)) selected = "general";
            const item = /** @type {Item} */ (items.find(i => i.id === selected));
            const with_problems = new Set(problems.map(p => item_of(p.path)));
            const list = h("ul.hardware-list", { role: "listbox", "aria-label": "Hardware" }, items.map(i => h("li", {
                role: "option",
                tabindex: "0",
                class: (i.id === selected ? "selected" : "") + (with_problems.has(i.id) ? " has-problem" : ""),
                "aria-selected": i.id === selected ? "true" : "false",
                dataset: { item: i.id },
                onclick: () => { selected = i.id; render(); },
                onkeydown: e => { if(e.key === "Enter" || e.key === " ") { e.preventDefault(); selected = i.id; render(); } },
            }, h("span.item-label", null, i.label), h("span.item-summary", null, i.summary))));
            const add = /** @type {HTMLSelectElement} */ (h("select", { "aria-label": "Add hardware" }, h("option", { value: "" }, "Add…"),
                additions(working).map(([label], index) => h("option", { value: String(index) }, label))));
            add.addEventListener("change", () =>
            {
                const chosen = additions(working)[+add.value];
                if(!chosen) return;
                const before = new Set(hardware_items(working).map(i => i.id));
                ctx.edit(chosen[1]);
                const added = hardware_items(working).find(i => !before.has(i.id));
                if(added) { selected = added.id; render(); }
            });
            const remove = h("button", { type: "button", disabled: !item.remove, onclick: () => { if(item.remove) ctx.edit(item.remove); } }, "Remove");
            const own_problems = problems.filter(p => item_of(p.path) === selected);
            replace(element,
                h("div.settings", null,
                    h("header.settings-header", null, h("h2", null, options.title || "Settings: " + working.name)),
                    h("aside.settings-list", null, list, h("div.settings-list-actions", null, add, remove)),
                    h("section.settings-panel", { "aria-label": item.label }, h("h3", null, item.label),
                        own_problems.length ? h("ul.problems", { role: "alert" }, own_problems.map(p => h("li", null, p.message))) : null,
                        item.panel(ctx)),
                    h("footer.settings-footer", null,
                        h("div.settings-notes", { role: "status" }, notes.length ? "Also changed: " + notes.join("; ") : problems.length ?
                            problems.length + (problems.length === 1 ? " problem" : " problems") + " to fix before saving" : ""),
                        h("button", { type: "button", onclick: () => close(null) }, "Cancel"),
                        h("button.primary", { type: "button", onclick: save }, options.save_label || "Save"))));
        }

        document.body.append(element);
        render();
        element.showModal();
    });
}

export { CPU_LABELS };
                                                                        source/v64/src/app/ui/wizard.js                                                                     0000644 0000000 0000000 00000104460 00000000000 013513  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The new machine wizard (docs/vm-manager-plan.md "新建虚拟机向导", U3):
// 1 where the system comes from (a CD, a floppy, an installed hard disk, a
// kernel and initrd, an Android image package, or later), 2 the system (a preset of
// src/app/guest_presets.js: all the hardware), 3 the name, 4 the hard disk
// (a new empty one and where it goes: a browser disk, the disk service,
// memory), 5 the summary: finish, or customize the hardware in the settings
// dialog first. The browser disk and the disk service's image are made only
// when the wizard finishes. An Android image package (docs/android-images-plan.md
// I3) becomes a browser disk then, in a worker (src/app/android_import.js):
// its images as they are, booted by v64's bootloader with SwiftShader.

import { h, replace, format_size } from "./dom.js";
import { image_picker } from "./image_picker.js";
import { hardware_rows } from "./describe.js";
import { open_settings } from "./settings.js";
import { PRESETS, preset, preset_config } from "../guest_presets.js";
import { create_image, list_images, new_image_name } from "../disk_service_client.js";
import { create_disk } from "../browser_disks.js";
import { inspect_android_package, import_android_package, import_android_package_to_service, sort_android_files, hash_file, USERDATA_GIB,
    DEFAULT_USERDATA_GIB } from "../android_import.js";
import { ANDROID_CATALOG } from "../android_catalog.js";
import { MAX_ARRAY_BUFFER_SIZE_MB } from "../../browser/vm_options.js";

/** @typedef {import("../vm_config.js").VMConfig} VMConfig */
/** @typedef {import("../vm_config.js").Image} Image */
/** @typedef {import("../disk_service_client.js").Service} Service */

const SOURCES = [
    ["cdrom", "A CD or DVD image (an installation or live CD)"],
    ["floppy", "A floppy image"],
    ["disk", "A hard disk image with the system installed"],
    ["direct", "A kernel and initrd (and the system's CD as a read-only disk)"],
    ["android", "An Android image package (.zip)"],
    ["later", "Install the system later"],
];

/**
 * The wizard; resolves with the new configuration (stored by the caller) or null when cancelled
 * @param {{store: {put_handle: (handle: any) => Promise<string>, get_pref?: any, put_pref?: any}, service: Service | null, names: string[]}} options
 *     names: the library's
 * @return {Promise<VMConfig | null>}
 */
export function open_wizard(options)
{
    return new Promise(resolve =>
    {
        const state = {
            step: 0,
            source: "cdrom",
            /** @type {Image | null} */
            image: null,
            /** @type {{bzimage: Image | null, initrd: Image | null, cmdline: string}} */
            direct: { bzimage: null, initrd: null, cmdline: "" },
            preset: "other",
            name: "",
            notes: "",
            disk: "new",
            disk_mb: 512,
            location: "browser",
            read_write: false,
            error: "",
            /** @type {{file: File | null, gsi: File | null, debug_ramdisk: File | null, info: import("../android_import.js").PackageInfo | null, error: string,
             *     userdata_gib: number, entry: string, checks: Object<string, string>, room?: number | null}} entry: the catalog's (I7), "" for another
             *     package; checks: each dropped part's against it (ok, checking…, or what differs); room: the site's storage left (null: unknown) */
            android: { file: null, gsi: null, debug_ramdisk: null, info: null, error: "", userdata_gib: DEFAULT_USERDATA_GIB,
                entry: ANDROID_CATALOG.default_entry, checks: {} },
            progress: "",
            /** @type {AbortController | null} the import going on (its Cancel) */
            importing: null,
        };
        const element = /** @type {HTMLDialogElement} */ (h("dialog.wizard-dialog", { "aria-label": "New virtual machine" }));
        const close = value => { element.close(); element.remove(); resolve(value); };
        element.addEventListener("cancel", e => { e.preventDefault(); if(state.importing) state.importing.abort(); else close(null); });
        const steps = ["Source", "System", "Name", "Hard disk", "Summary"];

        const unique = name =>
        {
            for(let i = 1; ; i++)
            {
                const candidate = i === 1 ? name : name + " " + i;
                if(!options.names.includes(candidate)) return candidate;
            }
        };
        const choose_preset = id =>
        {
            const p = /** @type {import("../guest_presets.js").Preset} */ (preset(id));
            state.preset = id;
            state.disk_mb = p.disk_mb;
            state.location = p.disk_location === "service" && options.service ? "service" :
                p.disk_location === "memory" && p.disk_mb <= MAX_ARRAY_BUFFER_SIZE_MB ? "memory" : "browser";
            if(!state.name || PRESETS.some(q => unique(q.name) === state.name)) state.name = unique(p.name);
        };
        choose_preset("other");

        /**
         * The configuration of the choices (the new disk: the disk service's image's URL, or the browser disk's path, made when finished)
         * @param {string} [made]
         * @return {VMConfig}
         */
        const build = made =>
        {
            const p = /** @type {import("../guest_presets.js").Preset} */ (preset(state.preset));
            const config = preset_config(p, { name: state.name.trim() || p.name, notes: state.notes });
            if(state.source === "cdrom" && state.image) config.cdrom.image = state.image;
            if(state.source === "floppy" && state.image) config.floppies = [{ slot: "fda", image: state.image, disk_option: "read_only" }];
            if(state.source === "direct")
            {
                config.kernel = { bzimage: state.direct.bzimage, initrd: state.direct.initrd, cmdline: state.direct.cmdline.trim() || null,
                    multiboot: null, from_filesystem: false };
                if(state.image) config.cdrom.image = state.image;
            }
            if(state.source === "disk" && state.image)
            {
                config.disks = [{ slot: "hda", image: state.image, disk_option: state.read_write ? "read_write" : "read_only", disk_error: "stop" }];
            }
            else if(state.source === "android" && state.android.info)
            {
                // (its images as they are: their own GPU drivers on gfxstream, the preset's (I8.1); the disk kept and
                // written; an emulator image's device model its own, the guest drawing)
                if(config.android && state.android.info.emulator) config.android.device = /** @type {string} */ (state.android.info.device);
                const size = state.android.info.disk_size(state.android.userdata_gib);
                config.disks = [{ slot: "hda", image: state.location === "service" ? { kind: "url", url: made || "(created when finished)", size, async: true } :
                    { kind: "browser", path: made || "(made when finished)", size }, disk_option: "read_write", disk_error: "stop" }];
            }
            else if(state.disk === "new")
            {
                const size = state.disk_mb * 1048576;
                config.disks = [{ slot: "hda", image: state.location === "service" ? { kind: "url", url: made || "(created when finished)", size, async: true } :
                    state.location === "browser" ? { kind: "browser", path: made || "(made when finished)", size } : { kind: "empty", size },
                disk_option: state.location === "memory" ? "read_only" : "read_write", disk_error: "stop" }];
            }
            return config;
        };

        const finish = async customize =>
        {
            state.error = "";
            let url;
            const new_disk = state.source !== "disk" && state.source !== "android" && state.disk === "new";
            if(state.source === "android")
            {
                const file = /** @type {File} */ (state.android.file);
                try
                {
                    state.progress = "Importing " + file.name + "…";
                    render();
                    const started = Date.now();
                    const progress = (done, total) =>
                    {
                        const seconds = (Date.now() - started) / 1000;
                        const left = done ? seconds * (total - done) / done : 0;
                        state.progress = "Importing " + file.name + ": " + Math.floor(done / total * 100) + "% (" + format_size(done) + " of " + format_size(total) +
                            (done && done < total ? ", about " + Math.ceil(left) + " s left" : "") + ")";
                        const status = element.querySelector(".wizard-status");
                        if(status) status.textContent = state.progress;
                    };
                    state.importing = new AbortController();
                    render();
                    const imported = { userdata_gib: state.android.userdata_gib, gsi: state.android.gsi, progress, signal: state.importing.signal };
                    url = state.location === "service" ?
                        (await import_android_package_to_service(file, state.name || "android", /** @type {Service} */ (options.service), imported)).url :
                        (await import_android_package(file, state.name || "Android", Object.assign({ prefs: options.store }, imported))).path;
                    state.progress = "";
                    state.importing = null;
                }
                catch(e)
                {
                    state.progress = "";
                    state.importing = null;
                    state.error = e.message === "Cancelled" ? "The import was cancelled" : "The package was not imported: " + e.message;
                    render();
                    return;
                }
            }
            if(new_disk && state.location === "browser")
            {
                try
                {
                    url = (await create_disk(state.disk_mb * 1048576, state.name || "disk", /** @type {any} */ (options.store))).path;
                }
                catch(e)
                {
                    state.error = "The browser disk was not made: " + e.message;
                    render();
                    return;
                }
            }
            if(new_disk && state.location === "service")
            {
                const service = /** @type {Service} */ (options.service);
                try
                {
                    const name = new_image_name(state.name || "disk", (await list_images(service)).images);
                    url = (await create_image(service, name, state.disk_mb * 1048576)).url;
                }
                catch(e)
                {
                    state.error = "The disk service did not create the disk: " + e.message;
                    render();
                    return;
                }
            }
            let config = build(url);
            if(customize)
            {
                element.close();
                const edited = await open_settings(config, { store: options.store, service: options.service, title: "Customize: " + config.name, save_label: "Finish" });
                if(!edited)
                {
                    element.showModal();
                    return;
                }
                config = edited;
            }
            close(config);
        };

        const source_step = () =>
        {
            const radios = SOURCES.map(([value, text]) => h("label.check", null,
                h("input", { type: "radio", name: "source", value, checked: state.source === value, onchange: () => { state.source = value; state.image = null; render(); } }),
                " " + text));
            const pickers = [];
            if(state.source === "cdrom" || state.source === "floppy" || state.source === "disk")
            {
                pickers.push(image_picker({ label: state.source === "cdrom" ? "CD image" : state.source === "floppy" ? "Floppy image" : "Hard disk image",
                    role: state.source === "disk" ? "disk" : state.source, image: state.image, store: options.store, service: options.service,
                    machine_name: state.name, on_change: (image, extra) =>
                    {
                        state.image = image && image.kind === "empty" && state.source === "disk" ? null : image;
                        state.read_write = !!(extra && extra.read_write);
                        render();
                    } }));
            }
            if(state.source === "android") pickers.push(android_picker());
            if(state.source === "direct")
            {
                pickers.push(
                    image_picker({ label: "Kernel", role: "file", image: state.direct.bzimage, store: options.store, on_change: image => { state.direct.bzimage = image; render(); } }),
                    image_picker({ label: "Initrd", role: "file", optional: true, image: state.direct.initrd, store: options.store, on_change: image => { state.direct.initrd = image; render(); } }),
                    h("label.field", null, h("span", null, "Command line (optional)"), (() =>
                    {
                        const input = /** @type {HTMLInputElement} */ (h("input", { type: "text", value: state.direct.cmdline, size: 50 }));
                        input.addEventListener("change", () => { state.direct.cmdline = input.value; });
                        return input;
                    })()),
                    image_picker({ label: "The system's CD (optional)", role: "cdrom", optional: true, image: state.image, store: options.store,
                        on_change: image => { state.image = image; render(); } }));
            }
            return [h("fieldset", null, h("legend", null, "Where does the system come from?"), radios), pickers];
        };

        // (the files: chosen or dropped, the device's package and a GSI (in
        // one go or one after the other), then read: what they are, the disk)
        // (the dropped parts against the catalog's entry: size, then SHA-256 in
        // the importer's worker, each file hashed once)
        const hashes = new WeakMap();
        const check_parts = async () =>
        {
            const a = state.android;
            const entry = ANDROID_CATALOG.entries.find(e => e.id === a.entry);
            a.checks = {};
            if(!entry) return;
            for(const [role, file] of /** @type {Array<[string, File | null]>} */ ([["device", a.file], ["gsi", a.gsi], ["debug_ramdisk", a.debug_ramdisk]]))
            {
                if(!file) continue;
                const part = entry.parts.find(p => p.role === role);
                if(!part) { a.checks[role] = "not one of this entry's files"; continue; }
                if(file.size !== part.size) { a.checks[role] = "differs: " + format_size(file.size) + ", the catalog's " + part.name + " is " + format_size(part.size); continue; }
                if(!hashes.has(file))
                {
                    a.checks[role] = "checking…";
                    render();
                    try
                    {
                        hashes.set(file, await hash_file(file, (done, total) =>
                        {
                            const status = element.querySelector(".drop-zone [data-role=" + role + "]");
                            if(status) status.textContent = "checking " + Math.floor(done / total * 100) + "%";
                        }));
                    }
                    catch(e)
                    {
                        // (the importer's worker did not run: said, not "checking…" for ever)
                        a.checks[role] = "could not be checked: " + e.message;
                        continue;
                    }
                }
                a.checks[role] = hashes.get(file) === part.sha256 ? "ok" : "differs: its SHA-256 is not the catalog's (another build, or a damaged download)";
            }
            render();
        };
        const take_files = async files =>
        {
            const a = state.android;
            Object.assign(a, { info: null, error: "" });
            render();
            try
            {
                const sorted = await sort_android_files(files);
                if(sorted.device) a.file = sorted.device;
                if(sorted.gsi) a.gsi = sorted.gsi;
                if(sorted.debug_ramdisk) a.debug_ramdisk = sorted.debug_ramdisk;
                if(!a.file) throw new Error(a.gsi ? "A GSI is a system for a device: add the device's package (a Cuttlefish images zip) too" :
                    "Add the device's package (a Cuttlefish images zip, or an Android Emulator image zip)");
                a.info = await inspect_android_package(a.file, a.gsi);
                // (an emulator image: the preset of its device model, I6)
                const device = a.info.device;
                const model = a.info.emulator ? PRESETS.find(p => preset_config(p).android?.device === device) : undefined;
                choose_preset(model ? model.id : "android16");
            }
            catch(e)
            {
                a.error = e.message;
            }
            render();
            await check_parts();
        };
        /** the catalog (I7): one entry per Android version that boots, the chosen one's files and their downloads */
        const catalog = () =>
        {
            const a = state.android;
            const entry = ANDROID_CATALOG.entries.find(e => e.id === a.entry);
            const ROLES = { device: entry && entry.kind === "emulator" ? "System image" : "Phone images", gsi: "GSI",
                debug_ramdisk: "Debug vendor ramdisk (optional)" };
            const radios = [...ANDROID_CATALOG.entries.map(e => [e.id, e.title]), ["", "Another package"]].map(([id, title]) =>
                h("label.check", null, h("input", { type: "radio", name: "catalog", value: id, checked: a.entry === id,
                    onchange: () => { a.entry = id; check_parts(); render(); } }), " " + title));
            return h("fieldset", null, h("legend", null, "Android version"), radios, entry ? [
                h("p", null, h("small.reason", null, entry.notes)),
                h("table.hardware.catalog-parts", null, h("tbody", null, entry.parts.map(p => h("tr", null,
                    h("th", null, ROLES[p.role]),
                    h("td", null, h("a", { href: p.url, target: "_blank", rel: "noopener" }, p.name), " ", format_size(p.size)),
                    h("td", { "data-role": p.role }, a.checks[p.role] || (p.optional ? "" : "needed"))))))] : null);
        };
        const android_picker = () =>
        {
            const input = /** @type {HTMLInputElement} */ (h("input", { type: "file", accept: ".zip,application/zip", multiple: true, "aria-label": "Android image package" }));
            input.addEventListener("change", () => { if(input.files && input.files.length) take_files(Array.from(input.files)); });
            const a = state.android;
            const gsi = a.info && a.info.gsi;
            const zone = h("div.drop-zone", { tabindex: "0" }, catalog(),
                h("p", null, "Drop the files here, or choose them: ", input),
                h("p", null, h("small.reason", null, "Download them with the links above; v64 reads them here, nothing is uploaded.")),
                a.file || a.gsi ? h("p", { role: "status" }, [a.file, a.gsi].filter(Boolean).map(f => f.name + " (" + format_size(f.size) + ")").join(" and ") + ": " +
                    (a.error ? "" : a.info ? a.info.text + (gsi ? ", running the GSI's Android " + gsi.release + " (" + gsi.fingerprint + ")" : "") +
                        "; its disk: " + format_size(a.info.disk_size(a.userdata_gib)) : "reading…")) : null,
                gsi && gsi.abilist32 ? h("p", null, h("small.reason", null, "The GSI lists 32-bit ABIs (" + gsi.abilist32 + "), but this device runs " +
                    "only the 64-bit zygote: Android starts, 32-bit apps do not run (they need AArch32 and a device with a 32-bit zygote: " +
                    "docs/aarch32-plan.md).")) : null,
                a.error ? h("p.error", null, a.error) : null,
                a.gsi ? h("button", { type: "button", onclick: () => { a.gsi = null; take_files([]); } }, "Without the GSI") : null);
            zone.addEventListener("dragover", e => { e.preventDefault(); zone.classList.add("over"); });
            zone.addEventListener("dragleave", () => zone.classList.remove("over"));
            zone.addEventListener("drop", e =>
            {
                e.preventDefault();
                zone.classList.remove("over");
                const files = e.dataTransfer ? Array.from(e.dataTransfer.files) : [];
                if(files.length) take_files(files);
            });
            return zone;
        };

        const system_step = () =>
        {
            const p = /** @type {import("../guest_presets.js").Preset} */ (preset(state.preset));
            const list = h("ul.preset-list", { role: "listbox", "aria-label": "Systems" }, PRESETS.map(q => h("li", {
                role: "option", tabindex: "0", "aria-selected": q.id === state.preset ? "true" : "false", class: q.id === state.preset ? "selected" : "",
                dataset: { preset: q.id },
                onclick: () => { choose_preset(q.id); render(); },
                onkeydown: e => { if(e.key === "Enter" || e.key === " ") { e.preventDefault(); choose_preset(q.id); render(); } },
            }, h("span", null, q.name), q.verified ? null : h("span.badge", null, "not verified"))));
            const fits = state.source === "later" || p.install.includes(/** @type {any} */ (state.source));
            return h("div.preset-pane", null, list, h("div.preset-detail", null,
                h("h3", null, p.name),
                h("p", null, p.verified ? "Verified: " + p.basis : h("strong", null, "Not verified: "), p.verified ? null : p.basis),
                h("p", null, "Installation: " + p.install_text),
                fits ? null : h("p.error", null, "This system is usually installed another way: " + p.install_text),
                h("table.hardware", null, h("tbody", null, hardware_rows(preset_config(p, { name: "x" })).filter(([name]) => !/^(Hard disk|CD|Floppy|UART)/.test(name))
                    .map(([name, value]) => h("tr", null, h("th", null, name), h("td", null, value))))),
                p.checklist.length ? [h("h4", null, "After the installation"), h("ul", null, p.checklist.map(c => h("li", null, c)))] : null,
                p.issues.length ? [h("h4", null, "Known problems"), h("ul", null, p.issues.map(c => h("li", null, c)))] : null));
        };

        const name_step = () =>
        {
            const name = /** @type {HTMLInputElement} */ (h("input", { type: "text", value: state.name, size: 40, "aria-label": "Name" }));
            name.addEventListener("input", () => { state.name = name.value; });
            const notes = /** @type {HTMLTextAreaElement} */ (h("textarea", { rows: 4, cols: 40, "aria-label": "Notes" }));
            notes.value = state.notes;
            notes.addEventListener("input", () => { state.notes = notes.value; });
            return [h("label.field", null, h("span", null, "Name"), name), h("label.field", null, h("span", null, "Notes"), notes)];
        };

        const disk_step = () =>
        {
            if(state.source === "android")
            {
                const info = /** @type {import("../android_import.js").PackageInfo} */ (state.android.info);
                // (a browser disk takes its whole size at once: the sizes past the site's room are not offered, I4.3)
                if(state.android.room === undefined)
                {
                    state.android.room = null;
                    navigator.storage?.estimate?.().then(e => { state.android.room = e.quota ? Math.max(0, e.quota - (e.usage || 0)) : null; render(); }).catch(() => {});
                }
                const room = state.location === "browser" ? state.android.room : null;
                const fits = gib => room === null || room === undefined || info.disk_size(gib) <= room;
                if(!fits(state.android.userdata_gib)) state.android.userdata_gib = USERDATA_GIB.filter(fits).pop() || USERDATA_GIB[0];
                const sizes = USERDATA_GIB.map(gib => h("label.check", { title: fits(gib) ? "" : "the disk would be " + format_size(info.disk_size(gib)) + ", the site has " +
                    format_size(/** @type {number} */ (room)) + " more" }, h("input", { type: "radio", name: "userdata", value: String(gib),
                    checked: state.android.userdata_gib === gib, disabled: !fits(gib), onchange: () => { state.android.userdata_gib = gib; render(); } }),
                " " + gib + " GiB" + (gib === DEFAULT_USERDATA_GIB ? " (the usual)" : "") + (fits(gib) ? "" : " (no room)")));
                if(state.location === "memory" || state.location === "service" && !options.service) state.location = "browser";
                const where = [["browser", "A browser disk: kept in this browser (until its site data is cleared)", false, ""],
                    ["service", "The disk service: an image file on " + (options.service ? options.service.url : "a disk service") + " (kept)", !options.service,
                        options.service ? "" : "No disk service: start one (make run starts one), or set it in Preferences"]].map(([value, text, disabled, title]) =>
                    h("label.check", { title }, h("input", { type: "radio", name: "location", value, checked: state.location === value, disabled,
                        onchange: () => { state.location = /** @type {string} */ (value); render(); } }), " " + text));
                if(info.emulator)
                {
                    const e = info.emulator;
                    return [
                        h("p", null, "A disk made from the Android Emulator's image (Android " + (e.release || "?") + ", API " + e.api + ", " + e.abi +
                            (e.tag ? ", " + e.tag : "") + "): its kernel, ramdisk, system and userdata as they are, an empty cache. " +
                            format_size(info.disk_size(0)) + " in all, about " + format_size(info.data_bytes) + " of it written now."),
                        h("fieldset", null, h("legend", null, "Where it is kept"), where),
                        state.location === "browser" ? quota_note() : null,
                        h("p", null, h("small.reason", null, "The " + (e.cpu === "arm32" ? "32-bit ARM CPU" : "arm64 CPU") + " on the ranchu machine boots it; " +
                            "the guest draws (no host GPU).")),
                    ];
                }
                return [
                    h("p", null, "A disk made from the package: its images as they are, super shrunk to its partitions (" + format_size(info.super_size) + "), " +
                        "userdata blank (Android formats it at first boot). " + format_size(info.disk_size(state.android.userdata_gib)) + " in all, about " +
                        format_size(info.data_bytes) + " of it written now."),
                    h("fieldset", null, h("legend", null, "Space for apps and data (userdata)"), sizes),
                    h("fieldset", null, h("legend", null, "Where it is kept"), where),
                    state.location === "browser" ? quota_note() : null,
                    h("p", null, h("small.reason", null, "The package boots with its own GPU drivers on gfxstream: the graphics proxy's WebGPU " +
                        "renderer draws (Settings, Display; without WebGPU choose SwiftShader in Settings, Android: Android starts, its desktop is slow).")),
                ];
            }
            if(state.source === "disk")
            {
                return h("p", null, "The machine starts from the chosen hard disk image" + (state.read_write ? ", written back to the disk service." : ": its changes stay in memory."));
            }
            const choice = (value, text, disabled = false, title = "") => h("label.check", { title }, h("input", { type: "radio", name: "disk", value,
                checked: state.disk === value, disabled, onchange: () => { state.disk = value; render(); } }), " " + text);
            /** @type {Array<[string, string, boolean, string]>} */
            const locations = [
                ["browser", "A browser disk: kept in this browser (until its site data is cleared)", false, ""],
                ["service", "The disk service: an image file on " + (options.service ? options.service.url : "a disk service") + " (kept)", !options.service,
                    options.service ? "" : "No disk service: start one (make run starts one), or set it in Preferences"],
                ["memory", "Memory: lost at power off (at most " + MAX_ARRAY_BUFFER_SIZE_MB + " MB)", state.disk_mb > MAX_ARRAY_BUFFER_SIZE_MB, "too large for memory"],
            ];
            const size = /** @type {HTMLInputElement} */ (h("input", { type: "number", min: "1", value: state.disk_mb, "aria-label": "Disk size in MB" }));
            size.addEventListener("change", () =>
            {
                state.disk_mb = Math.max(1, Math.round(+size.value || 1));
                if(state.location === "memory" && state.disk_mb > MAX_ARRAY_BUFFER_SIZE_MB) state.location = "browser";
                render();
            });
            return [
                choice("new", "A new empty disk"),
                state.disk === "new" ? h("div.indent", null,
                    h("label.field", null, h("span", null, "Size in MB"), size, h("small.reason", null, format_size(state.disk_mb * 1048576))),
                    h("fieldset", null, h("legend", null, "Where it is kept"), locations.map(([value, text, disabled, title]) => h("label.check", { title },
                        h("input", { type: "radio", name: "location", value, checked: state.location === value, disabled,
                            onchange: () => { state.location = value; render(); } }), " " + text))),
                    state.location === "browser" ? quota_note() : null) : null,
                choice("none", "No hard disk"),
            ];
        };

        // (a browser disk counts its whole size against the site's storage at once: measured in Chrome, docs/vm-manager-plan.md U6)
        const quota_note = () =>
        {
            const note = h("small.reason", { role: "status" }, "A browser disk takes its whole size of the browser's storage for this site at once.");
            navigator.storage?.estimate?.().then(e =>
            {
                if(e.quota) note.textContent += " This site has " + format_size(Math.max(0, e.quota - (e.usage || 0))) + " more.";
            }).catch(() => {});
            return note;
        };

        const summary_step = () =>
        {
            const config = build();
            const p = /** @type {import("../guest_presets.js").Preset} */ (preset(state.preset));
            return [
                h("h3", null, config.name),
                p.verified ? null : h("p.error", null, "This system's settings are not verified: " + p.basis),
                h("table.hardware", null, h("tbody", null, hardware_rows(config).map(([name, value]) => h("tr", null, h("th", null, name), h("td", null, value))))),
                p.checklist.length ? [h("h4", null, "After the installation"), h("ul", null, p.checklist.map(c => h("li", null, c)))] : null,
            ];
        };

        const ready = () =>
        {
            if(state.step === 0)
            {
                if(state.source === "direct") return state.direct.bzimage ? "" : "Choose the kernel";
                if(state.source === "android")
                {
                    const a = state.android;
                    if(!a.info) return a.file && !a.error ? "Reading the package…" : "Choose the package";
                    const entry = ANDROID_CATALOG.entries.find(e => e.id === a.entry);
                    if(entry)
                    {
                        const missing = entry.parts.filter(p => !p.optional && !{ device: a.file, gsi: a.gsi }[p.role]);
                        if(missing.length) return "Still needed: " + missing.map(p => p.name).join(", ");
                        const bad = Object.entries(a.checks).find(([, c]) => c !== "ok");
                        if(bad) return bad[1] === "checking…" ? "Checking the files…" :
                            bad[1].startsWith("could not") ? "A file " + bad[1] : "A file is not the catalog's: " + bad[1];
                    }
                    return "";
                }
                if(state.source !== "later" && !state.image) return "Choose the image";
                if(state.image && state.image.kind === "url" && !state.image.url) return "Give the image's URL";
            }
            if(state.step === 2 && !state.name.trim()) return "Give the machine a name";
            if(state.step === 3 && state.disk === "new" && state.location === "memory" && state.disk_mb > MAX_ARRAY_BUFFER_SIZE_MB) return "Too large for memory";
            return "";
        };

        function render()
        {
            const body = [source_step, system_step, name_step, disk_step, summary_step][state.step]();
            const blocked = ready();
            const last = state.step === steps.length - 1;
            replace(element, h("div.wizard", null,
                h("header", null, h("h2", null, "New virtual machine"),
                    h("ol.wizard-steps", null, steps.map((s, i) => h("li", { class: i === state.step ? "current" : i < state.step ? "done" : "" }, s)))),
                h("section.wizard-body", { "aria-label": steps[state.step] }, body),
                h("footer.wizard-footer", null,
                    h("span.wizard-status", { role: "status", class: state.error ? "error" : "" }, state.error || state.progress || blocked),
                    // (while a package is imported: only its Cancel)
                    state.importing ? h("button", { type: "button", onclick: () => state.importing && state.importing.abort() }, "Cancel import") : [
                        h("button", { type: "button", onclick: () => close(null) }, "Cancel"),
                        h("button", { type: "button", disabled: state.step === 0, onclick: () => { state.step--; render(); } }, "Back"),
                        last ? [h("button", { type: "button", onclick: () => finish(true) }, "Customize hardware…"),
                            h("button.primary", { type: "button", onclick: () => finish(false) }, "Finish")] :
                            h("button.primary", { type: "button", disabled: !!blocked, onclick: () => { state.step++; render(); } }, "Next")])));
        }

        document.body.append(element);
        render();
        element.showModal();
    });
}
                                                                                                                                                                                                                source/v64/src/app/vm_config.js                                                                     0000644 0000000 0000000 00000145300 00000000000 013543  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// A virtual machine's configuration in the VM manager (docs/vm-manager-plan.md,
// "虚拟机配置格式", U1): the format and its version, the defaults, the
// migration of older versions, the checks, the V86 options of a
// configuration (config_to_options, with the old page's rules of
// src/browser/vm_options.js).

import { CPU_PROFILES, MACHINE_CPU_PROFILES, ARM_MACHINE_TYPES, CPU_TYPES, FIRMWARE_TYPES, MACHINE_TYPES, MAX_VRAM_SIZE, Q35_ROOT_PORTS_MAX, USB_PORTS, allowed_options,
    check_machine_options } from "../machine_options.js";
import { ANDROID_DEVICES as ANDROID_DEVICE_MODELS } from "../android/bootloader.js";
import { DEFAULT_GLES_VERSION, GLES_VERSIONS } from "../android/devices.js";
import { DISK_OPTIONS, DISK_ERRORS, check_disk_options } from "../disk_options.js";
import { DEFAULT_FORM, DEFAULT_MEMORY_SIZE, MAX_MEMORY_SIZE, MAX_HEAP_MEMORY_SIZE, MAX_ARRAY_BUFFER_SIZE_MB, DEFAULT_VGA_MEMORY_SIZE,
    DEFAULT_MTU, apply_form, settings_to_options } from "../browser/vm_options.js";

export const FORMAT = "v86-vm";
export const VERSION = 4;

/** The UEFI firmware's images (machine.firmware "uefi"; bios/fetch-ovmf.sh) */
export const UEFI_CODE_URL = "bios/ovmf-code.fd";
export const UEFI_VARS_URL = "bios/ovmf-vars.fd";
/** With Secure Boot (machine.secure_boot, docs/uefi.md): the build whose variables are SMM's; Microsoft's keys enrolled */
export const UEFI_SECURE_CODE_URL = "bios/ovmf-secure-code.fd";
export const UEFI_MS_VARS_URL = "bios/ovmf-vars-ms.fd";
/** machine.secure_boot_keys: the keys a new variable store has */
export const SECURE_BOOT_KEYS = ["microsoft", "none"];

/**
 * The variable store's template for a machine: Microsoft's keys with Secure
 * Boot and those keys, else none (Setup Mode)
 * @param {{secure_boot: boolean, secure_boot_keys: string}} machine
 */
export const uefi_vars_template = machine => machine.secure_boot && machine.secure_boot_keys === "microsoft" ? UEFI_MS_VARS_URL : UEFI_VARS_URL;
/** The TPM's state store (docs/tpm.md, src/tpm/store.js): two slots of 256 KiB */
export const TPM_STATE_SIZE = 512 * 1024;

/**
 * Where an image is (the plan's 镜像来源): a URL (or a disk service's), a
 * file on this computer (its handle in the store, src/app/vm_store.js), an
 * empty disk in memory, or a browser disk (OPFS)
 * @typedef {{kind: "url", url: string, size?: number, async?: boolean, fixed_chunk_size?: number, use_parts?: boolean}
 *     | {kind: "file", name: string, size: number, last_modified: number, handle?: string}
 *     | {kind: "empty", size: number}
 *     | {kind: "browser", path: string, size: number}} Image
 */

/**
 * @typedef {Object} Disk
 * @property {"hda" | "hdb"} slot
 * @property {Image} image
 * @property {"read_only" | "read_write"} disk_option
 * @property {"stop" | "report"} disk_error
 */

/**
 * @typedef {Object} Floppy
 * @property {"fda" | "fdb"} slot
 * @property {Image | null} image
 * @property {"read_only" | "read_write"} disk_option
 */

/**
 * @typedef {Object} UsbDisk a disk image as a USB disk (usb.mass_storage)
 * @property {string} id its name (V86's usb_attach_disk id; "usb:" + id for its image)
 * @property {Image} image
 * @property {"read_only" | "read_write"} disk_option the source's policy, as a hard disk's
 * @property {"stop" | "report"} disk_error
 * @property {boolean} write_protected the guest sees it read only
 */

/**
 * @typedef {Object} Network
 * @property {string} device ne2k, virtio or none
 * @property {"none" | "inbrowser" | "relay" | "wisp" | "fetch"} backend
 * @property {string} relay_url the relay's or wisp's URL; fetch: the CORS proxy, or ""
 * @property {number} mtu
 * @property {boolean} mac_address_translation
 */

/**
 * @typedef {Object} VMConfig
 * @property {"v86-vm"} format
 * @property {number} version
 * @property {string} id
 * @property {string} name
 * @property {string} notes
 * @property {string} guest the preset's family (src/app/guest_presets.js), or "other"
 * @property {string | null} template the preset it was made from
 * @property {string} created
 * @property {string} modified
 * @property {{type: string, acpi: boolean, hpet: boolean, smbus: boolean, pcie_root_ports: number, boot_order: number,
 *     fastboot: boolean, bootmenu: boolean, bios: Image | null, vga_bios: Image | null, firmware: string,
 *     uefi_vars: Image | null, secure_boot: boolean, secure_boot_keys: string}} machine
 *     (firmware: "seabios", the BIOS images' or SeaBIOS, or "uefi", OVMF: docs/uefi.md; uefi_vars: its variable
 *     store, a browser disk made from the template at the first power-on, null before and after a reset to it;
 *     secure_boot: the Secure Boot firmware (Q35); secure_boot_keys: "microsoft" or "none", the keys a store gets
 *     when it is made or reset)
 * @property {{state: Image | null} | null} tpm a TPM 2.0 (docs/tpm.md); its state a browser disk made at the first
 *     power-on (null before)
 * @property {{type: string, cores: number, parallel: boolean, jit: boolean, profile: (string|null)}} cpu (profile: the CPU model, cpu_profile; null the CPU type's default)
 * @property {{mb: number}} memory
 * @property {Disk[]} disks
 * @property {{image: Image | null, disk_error: "stop" | "report"}} cdrom
 * @property {Floppy[]} floppies
 * @property {{bzimage: Image | null, initrd: Image | null, cmdline: string | null, multiboot: Image | null, from_filesystem: boolean} | null} kernel
 * @property {Android | null} android Android booted from its disk: the kernel and initrd from its boot partitions
 *     (kernel's cmdline, if any, after the device's)
 * @property {{adapter: string, vram_mb: number | null, proxy: boolean, vulkan: "none" | "venus" | "gfxstream", displays: number}} display
 *     vram_mb: null with an initial_state, whose video memory it is; vulkan: virtio-gpu's Vulkan, drawn by the graphics
 *     proxy's WebGPU renderer: Venus contexts, or gfxstream's (its contexts only: Android's official images)
 * @property {Network[]} network one on the PC machines; up to four virtio-net cards on virt (Android's
 *     three), at most one of them with a backend
 * @property {{device: "sb16" | "hd_audio" | "virtio" | "none", mute: boolean}} sound the sound card (virtio: virt's
 *     virtio-snd; none: no card, the PC speaker stays) and whether the page plays nothing
 * @property {{controller: "uhci", tablet: boolean, disks: UsbDisk[]} | null} usb a USB controller and its devices (the PC
 *     machines'): the tablet, USB disks; each in a port of its own
 * @property {{transport: "mmio" | "pci", input: string[] | null, console_ports: number, vsock: boolean,
 *     gpu_pci_slot: number | null}} virt the virt machine's devices: input null as the display has them
 *     (keyboard, tablet and touch screen with virtio-gpu); console_ports 0: no virtio console
 * @property {{port: number, attach: "none" | "terminal" | "modem"}[]} serial
 * @property {{baseurl?: string, basefs?: {url: string}} | null} filesystem the 9p file system: its files' base URL, its description (fs.json)
 * @property {Image | null} initial_state a state to start from (an old page's profile with a state)
 * @property {{cpu_worker: boolean, ir_tier0: boolean, x87_fast_math: boolean, x87_jit_cache: boolean,
 *     cpuid_level: number | null, mouse_disabled: boolean}} advanced
 * @property {{size: number, time: string, digest: string} | null} suspended the suspended state (U5)
 */

/**
 * Android's bootloader (docs/android-images-plan.md I2): the device
 * models of src/android/devices.js, its GPU modes (venus: Android's own
 * Venus driver, as tools/a64_android.mjs puts it in odm, with display.vulkan
 * "venus"; gfxstream: the image's own drivers, with display.vulkan
 * "gfxstream"; an emulator image's own two, docs/gles-proxy-plan.md E5:
 * host, its GLES drawn by the page's WebGPU, and guest, the CPU draws, as
 * swiftshader does there), the vendor ramdisks (debug: Cuttlefish's
 * vendor_ramdisk-debug.img, a file of its own), SELinux's modes and the
 * display (device: the device model's, the screen zoomed to the window;
 * window: a display of the window's size, following it)
 * @typedef {{device: string, gpu_mode: "swiftshader" | "venus" | "gfxstream" | "host" | "guest", vendor_ramdisk: "release" | "debug",
 *     debug_ramdisk: Image | null, selinux: "enforcing" | "permissive", display: "device" | "window", gles_version: string}} Android
 */
/** the device models (src/android/devices.js): Cuttlefish's phone (arm64 on virt), the emulator images (ranchu) */
export const ANDROID_DEVICES = Object.keys(ANDROID_DEVICE_MODELS);
export const ANDROID_GPU_MODES = ["swiftshader", "venus", "gfxstream"];
/** an emulator image's (the ranchu machine's): the host's GPU, the guest's CPU ("swiftshader" is "guest" there) */
export const RANCHU_GPU_MODES = ["host", "guest"];
/** display.vulkan: none, Venus contexts, gfxstream's */
export const DISPLAY_VULKAN = ["none", "venus", "gfxstream"];
export const ANDROID_VENDOR_RAMDISKS = ["release", "debug"];
export const ANDROID_SELINUX = ["enforcing", "permissive"];
export const ANDROID_DISPLAYS = ["device", "window"];
/** the GLES version an emulator image announces on the host's GPU (docs/gles3-plan.md) */
export const ANDROID_GLES_VERSIONS = Object.keys(GLES_VERSIONS);
/** an android section's defaults
 * @type {Android} */
export const ANDROID_DEFAULTS = { device: "cf_arm64_only_phone", gpu_mode: "swiftshader", vendor_ramdisk: "release", debug_ramdisk: null, selinux: "enforcing",
    display: "device", gles_version: DEFAULT_GLES_VERSION };

/**
 * The display an Android machine's virtio-gpu gets: its device model's
 * (android.display "device"), or null when the display follows the window
 * @param {VMConfig} config
 * @return {{width: number, height: number} | null}
 */
export function android_display(config)
{
    const a = config.android;
    if(!a || a.display === "window") return null;
    const model = /** @type {any} */ (ANDROID_DEVICE_MODELS)[a.device];
    return model && model.display || null;
}

/** The network backends and the old page's relay_url of each */
export const NETWORK_BACKENDS = ["none", "inbrowser", "relay", "wisp", "fetch"];
/** The boot orders the old page offers (index.html's boot_order) */
export const BOOT_ORDERS = [0, 0x213, 0x123, 0x231, 0x321, 0x312, 0x132];
/** The sound devices of the PC machines (virt: virtio, none; ranchu: none, its goldfish audio is not played) */
export const SOUND_DEVICES = ["sb16", "hd_audio", "none"];
const VIRT_SOUND_DEVICES = ["virtio", "none"];
const RANCHU_SOUND_DEVICES = ["none"];
/** The virt machine's input devices (virtio_input) */
const VIRT_INPUTS = ["keyboard", "tablet", "multitouch"];
/** The virt section of a PC machine, and virt's defaults */
export const VIRT_DEFAULTS = { transport: "mmio", input: null, console_ports: 0, vsock: false, gpu_pci_slot: null };
export const SERIAL_ATTACH = ["none", "terminal", "modem"];
/** The floppy images' sizes (as the old page's empty floppies, src/floppy.js) */
export const FLOPPY_SIZES = [320, 360, 400, 640, 720, 800, 1440, 2400, 2880, 3444, 5760, 7680].map(sectors => sectors * 512);

/**
 * A new identifier
 * @return {string}
 */
export function new_id()
{
    return globalThis.crypto.randomUUID();
}

/**
 * A new configuration with the defaults: the old page's machine before
 * anyone changes its form (DEFAULT_FORM)
 * @param {Partial<VMConfig>} [fields]
 * @return {VMConfig}
 */
export function new_config(fields = {})
{
    const now = new Date().toISOString();
    return with_defaults(Object.assign({ format: FORMAT, version: VERSION, id: new_id(), created: now, modified: now }, fields));
}

/** @param {*} value */
const is_object = value => !!value && typeof value === "object" && !Array.isArray(value);

/**
 * A configuration with each field it lacks set to its default (the fields
 * it has stay, the checks are validate_config's)
 * @param {Object} config
 * @return {VMConfig}
 */
export function with_defaults(config)
{
    /** @type {any} */
    const c = Object.assign({}, config);
    const section = (name, defaults) => { c[name] = Object.assign(defaults, is_object(c[name]) ? c[name] : {}); };
    c.format = c.format ?? FORMAT;
    c.version = c.version ?? VERSION;
    c.name = c.name ?? "New virtual machine";
    c.notes = c.notes ?? "";
    c.guest = c.guest ?? "other";
    c.template = c.template ?? null;
    c.created = c.created ?? new Date().toISOString();
    c.modified = c.modified ?? c.created;
    section("machine", { type: DEFAULT_FORM.machine_type, acpi: DEFAULT_FORM.acpi, hpet: false, smbus: false, pcie_root_ports: 0,
        boot_order: 0, fastboot: false, bootmenu: false, bios: null, vga_bios: null, firmware: "seabios", uefi_vars: null,
        secure_boot: false, secure_boot_keys: "microsoft" });
    // (profile: the CPU model, cpu_profile; null the CPU type's default)
    section("cpu", { type: DEFAULT_FORM.cpu_type, cores: 1, parallel: DEFAULT_FORM.parallel, jit: true, profile: null });
    section("memory", { mb: DEFAULT_MEMORY_SIZE });
    c.disks = Array.isArray(c.disks) ? c.disks.map(d => Object.assign({ disk_option: "read_only", disk_error: "stop" }, d)) : [];
    section("cdrom", { image: null, disk_error: "stop" });
    c.floppies = Array.isArray(c.floppies) ? c.floppies.map(f => Object.assign({ image: null, disk_option: "read_only" }, f)) : [];
    c.kernel = is_object(c.kernel) ? Object.assign({ bzimage: null, initrd: null, cmdline: null, multiboot: null, from_filesystem: false }, c.kernel) : null;
    c.android = is_object(c.android) ? Object.assign({}, ANDROID_DEFAULTS, c.android) : null;
    section("display", { adapter: DEFAULT_FORM.graphics_adapter, vram_mb: DEFAULT_VGA_MEMORY_SIZE, proxy: false, vulkan: "none", displays: 1 });
    c.network = Array.isArray(c.network) ? c.network.map(n => Object.assign(default_network(), n)) : [default_network()];
    section("sound", { device: "sb16", mute: false });
    c.usb = is_object(c.usb) ? Object.assign({ controller: "uhci", tablet: true, disks: [] }, c.usb) : null;
    c.tpm = is_object(c.tpm) ? Object.assign({ state: null }, c.tpm) : null;
    if(c.usb && Array.isArray(c.usb.disks))
    {
        c.usb.disks = c.usb.disks.map(d => Object.assign({ disk_option: "read_only", disk_error: "stop", write_protected: false }, d));
    }
    section("virt", Object.assign({}, VIRT_DEFAULTS));
    c.serial = Array.isArray(c.serial) ? c.serial : [{ port: 0, attach: "terminal" }];
    c.filesystem = is_object(c.filesystem) ? c.filesystem : null;
    c.initial_state = is_object(c.initial_state) ? c.initial_state : null;
    section("advanced", { cpu_worker: true, ir_tier0: true, x87_fast_math: true, x87_jit_cache: true, cpuid_level: null, mouse_disabled: false });
    c.suspended = is_object(c.suspended) ? c.suspended : null;
    return c;
}

/**
 * The old page's network: its card and relay
 * @return {Network}
 */
function default_network()
{
    return { device: DEFAULT_FORM.net_device_type, backend: "relay", relay_url: DEFAULT_FORM.relay_url, mtu: DEFAULT_MTU, mac_address_translation: false };
}

/**
 * Each version's change to the next
 * @type {Object<number, function(any): any>}
 */
const MIGRATIONS = {
    // 2 (2026-10-24, docs/gfxstream-plan.md G5): display.vulkan names the kind, Venus or gfxstream
    1: config => {
        if(is_object(config.display) && typeof config.display.vulkan === "boolean")
        {
            config = Object.assign({}, config, { display: Object.assign({}, config.display, { vulkan: config.display.vulkan ? "venus" : "none" }) });
        }
        return config;
    },
    // 3 (2026-10-26, docs/modern-pc-devices-plan.md H1): a PC's sound "none"
    // was the Sound Blaster muted (the guest had one); it stays so, as
    // sound.mute, and "none" is no sound card from now on
    2: config => {
        const sound = is_object(config.sound) ? config.sound : {};
        const virt = is_object(config.machine) && ARM_MACHINE_TYPES.includes(config.machine.type);
        const changed = !virt && sound.device === "none" ? { device: "sb16", mute: true } : { mute: false };
        return Object.assign({}, config, { sound: Object.assign({}, sound, changed) });
    },
    // 4 (2026-10-26, U1): the usb section (none before)
    3: config => Object.assign({}, config, { usb: null }),
};

/**
 * A stored or imported configuration in the current version: older versions
 * changed step by step, missing fields set to their defaults
 * @param {*} raw
 * @return {VMConfig}
 */
export function migrate(raw)
{
    if(!is_object(raw) || raw.format !== FORMAT)
    {
        throw new Error("This is not a v86 virtual machine (" + JSON.stringify(FORMAT) + " format)");
    }
    let config = raw;
    let version = config.version;
    if(!Number.isInteger(version) || version < 1)
    {
        throw new Error("The virtual machine's format version " + JSON.stringify(version) + " is not valid");
    }
    if(version > VERSION)
    {
        throw new Error("The virtual machine was made by a newer v86 (format version " + version + "; this one reads up to " + VERSION + ")");
    }
    while(version < VERSION)
    {
        config = MIGRATIONS[version](config);
        version++;
        config.version = version;
    }
    return with_defaults(config);
}

/**
 * @typedef {{path: string, message: string}} Problem a field (as "machine.type", "disks.0.image") and what is wrong
 */

/**
 * The problems of an image's description
 * @param {*} image
 * @param {string} path
 * @param {Problem[]} problems
 */
function check_image(image, path, problems)
{
    const problem = message => problems.push({ path, message });
    if(!is_object(image))
    {
        problem("an image is an object with a kind");
        return;
    }
    const size_ok = size => Number.isSafeInteger(size) && size > 0;
    switch(image.kind)
    {
        case "url":
            if(typeof image.url !== "string" || !image.url) problem("the image's URL is missing");
            else if(image.url.endsWith("/")) problem("the URL names a directory, not an image (choose the disk service's image)");
            if(image.size !== undefined && !size_ok(image.size)) problem("the image's size must be a positive integer");
            break;
        case "file":
            if(typeof image.name !== "string" || !image.name) problem("the file's name is missing");
            if(!Number.isSafeInteger(image.size) || image.size < 0) problem("the file's size must be a non-negative integer");
            break;
        case "empty":
            if(!size_ok(image.size)) problem("an empty disk's size must be a positive integer");
            break;
        case "browser":
            if(typeof image.path !== "string" || !/^v86\/disks\/[A-Za-z0-9_-]+\.img$/.test(image.path))
            {
                problem("a browser disk's path is v86/disks/<id>.img");
            }
            if(!size_ok(image.size)) problem("the browser disk's size must be a positive integer");
            break;
        default:
            problem("the image's kind is url, file, empty or browser, not " + JSON.stringify(image.kind));
    }
}

/**
 * The problems of a configuration: each field's values and the combinations
 * the machines allow (allowed_options); none for a configuration that
 * config_to_options can start
 * @param {VMConfig} config
 * @return {Problem[]}
 */
export function validate_config(config)
{
    /** @type {Problem[]} */
    const problems = [];
    const problem = (path, message) => problems.push({ path, message });
    const bool = (value, path) => { if(typeof value !== "boolean") problem(path, "must be true or false"); };
    const int = (value, path, min, max) =>
    {
        if(!Number.isInteger(value) || value < min || value > max) problem(path, "must be an integer from " + min + " to " + max);
    };

    if(config.format !== FORMAT) problem("format", "must be " + JSON.stringify(FORMAT));
    if(config.version !== VERSION) problem("version", "must be " + VERSION);
    if(typeof config.id !== "string" || !config.id) problem("id", "is missing");
    if(typeof config.name !== "string" || !config.name.trim()) problem("name", "a virtual machine needs a name");
    else if(config.name.length > 200) problem("name", "is longer than 200 characters");
    if(typeof config.notes !== "string") problem("notes", "must be text");

    const machine = config.machine, cpu = config.cpu;
    // (the rest depends on the CPU and the machine)
    if(!CPU_TYPES.includes(cpu.type) || !MACHINE_TYPES.includes(machine.type))
    {
        if(!CPU_TYPES.includes(cpu.type)) problem("cpu.type", "must be one of " + CPU_TYPES.join(", "));
        if(!MACHINE_TYPES.includes(machine.type)) problem("machine.type", "must be one of " + MACHINE_TYPES.join(", "));
        return problems;
    }

    const allowed = allowed_options(cpu.type, machine.type);
    // (arm: an ARM board, virt or ranchu; virt: the virt machine's own devices)
    const arm = ARM_MACHINE_TYPES.includes(machine.type);
    const virt = machine.type === "virt", ranchu = machine.type === "ranchu";
    if(!allowed.machine_types.includes(machine.type))
    {
        problem("machine.type", arm ? "the " + machine.type + " machine needs an ARM CPU (arm64 or arm32)" :
            "the " + cpu.type + " CPU runs on " + allowed.machine_types.join(" or "));
        return problems;
    }

    int(cpu.cores, "cpu.cores", 1, allowed.max_cores);
    bool(cpu.parallel, "cpu.parallel");
    bool(cpu.jit, "cpu.jit");
    if(cpu.profile !== null && cpu.profile !== undefined)
    {
        const model = Object.prototype.hasOwnProperty.call(CPU_PROFILES, cpu.profile) ? CPU_PROFILES[cpu.profile] : null;
        const only = MACHINE_CPU_PROFILES[machine.type]?.[cpu.type];
        if(!model) problem("cpu.profile", "must be one of " + Object.keys(CPU_PROFILES).join(", "));
        else if(model.cpu_type !== cpu.type) problem("cpu.profile", "is a CPU of type " + model.cpu_type + ", not " + cpu.type);
        else if(only && !only.includes(cpu.profile)) problem("cpu.profile", "the " + machine.type + " machine takes " + only.join(", "));
    }

    int(config.memory.mb, "memory.mb", 16, MAX_MEMORY_SIZE);
    if(config.memory.mb > MAX_HEAP_MEMORY_SIZE && cpu.type === "x86")
    {
        problem("memory.mb", "more than " + MAX_HEAP_MEMORY_SIZE + " MB needs a 64-bit CPU (x86_64)");
    }

    bool(machine.acpi, "machine.acpi");
    if(arm && machine.acpi) problem("machine.acpi", allowed.unavailable["acpi"]);
    if(allowed.acpi === "required" && !machine.acpi) problem("machine.acpi", "the Q35 machine always has ACPI");
    if(allowed.acpi === "with_cores" && cpu.cores > 1 && !machine.acpi) problem("machine.acpi", "more than one core needs ACPI");
    for(const name of ["hpet", "smbus"])
    {
        bool(machine[name], "machine." + name);
        if(machine[name] && allowed.unavailable[name]) problem("machine." + name, allowed.unavailable[name]);
    }
    int(machine.pcie_root_ports, "machine.pcie_root_ports", 0, Q35_ROOT_PORTS_MAX);
    if(machine.pcie_root_ports && allowed.unavailable["pcie_root_ports"]) problem("machine.pcie_root_ports", allowed.unavailable["pcie_root_ports"]);
    if(!BOOT_ORDERS.includes(machine.boot_order)) problem("machine.boot_order", "must be one of the boot orders (0 for automatic)");
    bool(machine.fastboot, "machine.fastboot");
    bool(machine.bootmenu, "machine.bootmenu");
    for(const name of ["bios", "vga_bios"])
    {
        if(machine[name] === null) continue;
        if(arm) problem("machine." + name, allowed.unavailable[name]);
        else if(machine.firmware === "uefi") problem("machine." + name, "UEFI takes the place of the BIOS images");
        else check_image(machine[name], "machine." + name, problems);
    }
    if(machine.uefi_vars !== null)
    {
        check_image(machine.uefi_vars, "machine.uefi_vars", problems);
        if(machine.uefi_vars.kind !== "browser") problem("machine.uefi_vars", "is a browser disk");
    }
    if(!FIRMWARE_TYPES.includes(machine.firmware)) problem("machine.firmware", "must be one of " + FIRMWARE_TYPES.join(", "));
    else if(machine.firmware === "uefi")
    {
        if(arm) problem("machine.firmware", allowed.unavailable["firmware"]);
        else if(cpu.type !== "x86_64") problem("machine.firmware", "UEFI (OVMF) needs the x86_64 CPU");
        else if(!machine.acpi) problem("machine.firmware", "UEFI needs ACPI");
    }
    bool(machine.secure_boot, "machine.secure_boot");
    if(machine.secure_boot === true)
    {
        // (the Secure Boot firmware keeps its variables in SMM: Q35's)
        if(machine.firmware !== "uefi") problem("machine.secure_boot", "Secure Boot needs UEFI");
        else if(machine.type !== "q35") problem("machine.secure_boot", "Secure Boot needs the Q35 machine (its firmware runs in SMM)");
    }
    if(!SECURE_BOOT_KEYS.includes(machine.secure_boot_keys)) problem("machine.secure_boot_keys", "must be one of " + SECURE_BOOT_KEYS.join(", "));

    // the disks (docs/disk-persistence-plan.md: read write needs a source that can be written back)
    const slots = new Set();
    config.disks.forEach((disk, i) =>
    {
        const path = "disks." + i;
        if(disk.slot !== "hda" && disk.slot !== "hdb") problem(path + ".slot", "must be hda or hdb");
        else if(slots.has(disk.slot)) problem(path + ".slot", disk.slot + " is given twice");
        slots.add(disk.slot);
        check_image(disk.image, path + ".image", problems);
        if(!DISK_OPTIONS.includes(disk.disk_option)) problem(path + ".disk_option", "must be read_only or read_write");
        if(!DISK_ERRORS.includes(disk.disk_error)) problem(path + ".disk_error", "must be stop or report");
        if(disk.disk_option === "read_write" && disk.image && (disk.image.kind === "file" || disk.image.kind === "empty"))
        {
            problem(path + ".disk_option", disk.image.kind === "file" ?
                "a file chosen on this computer can only be read: its changes stay in memory (read write needs a disk service or a browser disk)" :
                "an empty disk in memory has nothing to write back to: use a browser disk or a disk service");
        }
        if(disk.image && disk.image.kind === "empty" && disk.image.size > MAX_ARRAY_BUFFER_SIZE_MB * 1024 * 1024)
        {
            problem(path + ".image", "an empty disk in memory has at most " + MAX_ARRAY_BUFFER_SIZE_MB + " MB");
        }
    });
    if(config.cdrom.image !== null) check_image(config.cdrom.image, "cdrom.image", problems);
    if(config.cdrom.image && config.cdrom.image.kind === "empty") problem("cdrom.image", "a CD-ROM is not empty");
    if(!DISK_ERRORS.includes(config.cdrom.disk_error)) problem("cdrom.disk_error", "must be stop or report");
    const floppies = new Set();
    config.floppies.forEach((floppy, i) =>
    {
        const path = "floppies." + i;
        if(arm) problem(path, allowed.unavailable["fda"]);
        if(floppy.slot !== "fda" && floppy.slot !== "fdb") problem(path + ".slot", "must be fda or fdb");
        else if(floppies.has(floppy.slot)) problem(path + ".slot", floppy.slot + " is given twice");
        floppies.add(floppy.slot);
        if(floppy.image !== null) check_image(floppy.image, path + ".image", problems);
        if(floppy.image && floppy.image.kind === "empty" && !FLOPPY_SIZES.includes(floppy.image.size))
        {
            problem(path + ".image", "an empty floppy has one of the floppy sizes");
        }
        if(!DISK_OPTIONS.includes(floppy.disk_option)) problem(path + ".disk_option", "must be read_only or read_write");
    });

    if(config.kernel !== null)
    {
        for(const name of ["bzimage", "initrd", "multiboot"])
        {
            if(config.kernel[name] !== null) check_image(config.kernel[name], "kernel." + name, problems);
        }
        if(arm && config.kernel.multiboot) problem("kernel.multiboot", allowed.unavailable["multiboot"]);
        if(config.kernel.cmdline !== null && typeof config.kernel.cmdline !== "string") problem("kernel.cmdline", "must be text");
        bool(config.kernel.from_filesystem, "kernel.from_filesystem");
    }

    if(config.android !== null)
    {
        const a = config.android;
        const one_of = (value, list, path) => { if(!list.includes(value)) problem(path, "must be one of " + list.join(", ")); };
        one_of(a.device, ANDROID_DEVICES, "android.device");
        const model = ANDROID_DEVICE_MODELS[a.device];
        if(model && (model.machine !== machine.type || model.cpu !== cpu.type))
        {
            problem("android", model.id + " boots on the " + model.machine + " machine with the " + model.cpu + " CPU");
        }
        one_of(a.gpu_mode, model && model.machine === "ranchu" ? RANCHU_GPU_MODES.concat("swiftshader") : ANDROID_GPU_MODES, "android.gpu_mode");
        if(a.gpu_mode === "venus" && config.display.vulkan !== "venus") problem("android.gpu_mode", "Venus needs virtio-gpu's Venus (display.vulkan)");
        if(a.gpu_mode === "gfxstream" && config.display.vulkan !== "gfxstream") problem("android.gpu_mode", "gfxstream needs virtio-gpu's gfxstream (display.vulkan)");
        one_of(a.vendor_ramdisk, ANDROID_VENDOR_RAMDISKS, "android.vendor_ramdisk");
        if(a.vendor_ramdisk === "debug" && a.debug_ramdisk === null) problem("android.debug_ramdisk", "the debug vendor ramdisk (vendor_ramdisk-debug.img) is a file of its own: choose it");
        if(a.debug_ramdisk !== null) check_image(a.debug_ramdisk, "android.debug_ramdisk", problems);
        one_of(a.selinux, ANDROID_SELINUX, "android.selinux");
        one_of(a.display, ANDROID_DISPLAYS, "android.display");
        one_of(a.gles_version, ANDROID_GLES_VERSIONS, "android.gles_version");
        if(config.kernel && (config.kernel.bzimage || config.kernel.initrd || config.kernel.multiboot))
        {
            problem("kernel", "Android's kernel and initrd come from its disk's boot partitions: leave them out");
        }
        // (its disk, the first hard disk, may come later: without it the start says so, src/browser/starter.js)
        if(config.cdrom.image !== null) problem("cdrom.image", "Android's disk is the first virtio disk: no CD-ROM");
    }

    const display = config.display;
    if(!allowed.graphics_adapters.includes(display.adapter))
    {
        problem("display.adapter", ranchu ? "the ranchu machine has the emulator's framebuffer: none" :
            virt ? "the virt machine has no VGA: virtio-gpu or none" : "must be one of " + allowed.graphics_adapters.join(", "));
    }
    if(display.vram_mb === null)
    {
        if(config.initial_state === null) problem("display.vram_mb", "only a state image has the video memory it was saved with");
    }
    else if(!Number.isInteger(display.vram_mb) || display.vram_mb < 1 || display.vram_mb > MAX_VRAM_SIZE >> 20 || (display.vram_mb & display.vram_mb - 1))
    {
        problem("display.vram_mb", "must be a power of two from 1 to " + (MAX_VRAM_SIZE >> 20) + " MB");
    }
    bool(display.proxy, "display.proxy");
    if(!DISPLAY_VULKAN.includes(display.vulkan)) problem("display.vulkan", "must be one of " + DISPLAY_VULKAN.join(", "));
    else if(display.vulkan !== "none" && display.adapter !== "virtio_gpu") problem("display.vulkan", "only virtio-gpu has Vulkan");
    else if(display.vulkan !== "none" && display.proxy !== true) problem("display.vulkan", "needs the graphics proxy, whose WebGPU renderer draws it");
    int(display.displays, "display.displays", 1, 4);
    if(display.displays > 1 && display.adapter !== "virtio_gpu") problem("display.displays", "only virtio-gpu has more than one display");

    if(config.network.length > (virt ? 4 : 1)) problem("network", virt ? "the virt machine has four network cards at most" : "a PC machine has one network card");
    if(config.network.filter(n => n.backend !== "none").length > 1) problem("network", "one network card reaches the network, the others stay unconnected");
    if(virt && config.network.length > 1 && config.network.some(n => n.device !== "virtio")) problem("network", "the virt machine's cards are virtio-net");
    config.network.forEach((network, i) =>
    {
        const path = "network." + i;
        if(!allowed.net_device_types.includes(network.device))
        {
            problem(path + ".device", virt ? "the virt machine has virtio-net" : "must be one of " + allowed.net_device_types.join(", "));
        }
        if(!NETWORK_BACKENDS.includes(network.backend)) problem(path + ".backend", "must be one of " + NETWORK_BACKENDS.join(", "));
        const url = network.relay_url;
        if(network.backend === "relay" && !/^wss?:\/\//.test(url)) problem(path + ".relay_url", "a relay's URL starts with ws:// or wss://");
        if(network.backend === "wisp" && !/^wisps?:\/\//.test(url)) problem(path + ".relay_url", "a wisp server's URL starts with wisp:// or wisps://");
        if(network.backend === "fetch" && url && !/^https?:\/\//.test(url)) problem(path + ".relay_url", "the CORS proxy's URL starts with http:// or https://");
        int(network.mtu, path + ".mtu", 68, 65535);
        bool(network.mac_address_translation, path + ".mac_address_translation");
    });

    if(!(ranchu ? RANCHU_SOUND_DEVICES : virt ? VIRT_SOUND_DEVICES : SOUND_DEVICES).includes(config.sound.device))
    {
        problem("sound.device", ranchu ? "the ranchu machine's sound is not played: none" :
            virt ? "the virt machine has virtio-snd or none (no Sound Blaster)" : "must be sb16, hd_audio or none (virtio-snd is the virt machine's)");
    }
    bool(config.sound.mute, "sound.mute");
    if(config.tpm !== null)
    {
        if(!is_object(config.tpm)) problem("tpm", "an object or null");
        else if(arm) problem("tpm", allowed.unavailable["tpm"]);
        else
        {
            if(!machine.acpi) problem("tpm", "the TPM needs ACPI");
            if(config.tpm.state !== null)
            {
                check_image(config.tpm.state, "tpm.state", problems);
                if(config.tpm.state.kind !== "browser") problem("tpm.state", "is a browser disk");
            }
        }
    }
    if(config.usb !== null)
    {
        if(!is_object(config.usb)) problem("usb", "an object or null");
        else
        {
            if(!allowed.usb_controllers.includes(config.usb.controller))
            {
                problem("usb.controller", virt ? "the virt machine has no USB (its input is virtio-input)" : "must be one of " + allowed.usb_controllers.join(", "));
            }
            bool(config.usb.tablet, "usb.tablet");
            // USB disks: a port each (the tablet takes one), their images as hard disks'
            const disks = config.usb.disks === undefined ? [] : config.usb.disks;
            if(!Array.isArray(disks)) problem("usb.disks", "a list");
            else
            {
                const ids = new Set();
                disks.forEach((disk, i) =>
                {
                    const path = "usb.disks." + i;
                    if(typeof disk.id !== "string" || !/^[A-Za-z0-9_-]+$/.test(disk.id) || disk.id === "tablet") problem(path + ".id", "letters, digits, - and _");
                    else if(ids.has(disk.id)) problem(path + ".id", disk.id + " is given twice");
                    ids.add(disk.id);
                    check_image(disk.image, path + ".image", problems);
                    if(!DISK_OPTIONS.includes(disk.disk_option)) problem(path + ".disk_option", "must be read_only or read_write");
                    if(!DISK_ERRORS.includes(disk.disk_error)) problem(path + ".disk_error", "must be stop or report");
                    if(disk.disk_option === "read_write" && disk.image && (disk.image.kind === "file" || disk.image.kind === "empty"))
                    {
                        problem(path + ".disk_option", disk.image.kind === "file" ?
                            "a file chosen on this computer can only be read: its changes stay in memory (read write needs a disk service or a browser disk)" :
                            "an empty disk in memory has nothing to write back to: use a browser disk or a disk service");
                    }
                    if(disk.image && disk.image.kind === "empty" && disk.image.size > MAX_ARRAY_BUFFER_SIZE_MB * 1024 * 1024)
                    {
                        problem(path + ".image", "an empty disk in memory has at most " + MAX_ARRAY_BUFFER_SIZE_MB + " MB");
                    }
                    bool(disk.write_protected, path + ".write_protected");
                });
                const ports = USB_PORTS[config.usb.controller];
                if(ports && disks.length + (config.usb.tablet ? 1 : 0) > ports)
                {
                    problem("usb.disks", "the " + config.usb.controller.toUpperCase() + " controller has " + ports + " ports" +
                        (config.usb.tablet ? ", one of them the tablet's" : ""));
                }
            }
        }
    }

    const v = config.virt;
    if(!virt)
    {
        if(v.transport !== "mmio" || v.input !== null || v.console_ports || v.vsock || v.gpu_pci_slot !== null)
        {
            problem("virt", "the virtio transport, input devices, console ports, vsock and GPU slot are the virt machine's");
        }
    }
    else
    {
        if(v.transport !== "mmio" && v.transport !== "pci") problem("virt.transport", "must be mmio or pci");
        if(v.input !== null && !(Array.isArray(v.input) && v.input.every(kind => VIRT_INPUTS.includes(kind)) && new Set(v.input).size === v.input.length))
        {
            problem("virt.input", "is null (as the display has them) or a list of " + VIRT_INPUTS.join(", "));
        }
        int(v.console_ports, "virt.console_ports", 0, 30);
        bool(v.vsock, "virt.vsock");
        if(v.gpu_pci_slot !== null)
        {
            int(v.gpu_pci_slot, "virt.gpu_pci_slot", 1, 31);
            if(v.transport !== "pci" || display.adapter !== "virtio_gpu") problem("virt.gpu_pci_slot", "a PCI slot for virtio-gpu needs the pci transport and virtio-gpu");
        }
    }

    const ports = new Set();
    let modems = 0;
    config.serial.forEach((serial, i) =>
    {
        const path = "serial." + i;
        int(serial.port, path + ".port", 0, 3);
        if(ports.has(serial.port)) problem(path + ".port", "UART" + serial.port + " is given twice");
        ports.add(serial.port);
        if(!SERIAL_ATTACH.includes(serial.attach)) problem(path + ".attach", "must be none, terminal or modem");
        if(serial.attach === "modem") modems++;
        if(serial.attach === "modem" && arm) problem(path + ".attach", allowed.unavailable["modem"]);
    });
    if(modems > 1) problem("serial", "one modem at most");

    if(config.filesystem !== null)
    {
        const { baseurl, basefs } = config.filesystem;
        if(baseurl !== undefined && typeof baseurl !== "string") problem("filesystem.baseurl", "must be a URL");
        // (the file system's description, fs.json: as a file of the library, { url })
        if(basefs !== undefined && !(is_object(basefs) && typeof basefs.url === "string")) problem("filesystem.basefs", "must be { url }");
    }
    if(config.initial_state !== null)
    {
        check_image(config.initial_state, "initial_state", problems);
        if(config.initial_state.kind === "empty") problem("initial_state", "a state is not empty");
    }

    const advanced = config.advanced;
    for(const name of ["cpu_worker", "ir_tier0", "x87_fast_math", "x87_jit_cache", "mouse_disabled"])
    {
        bool(advanced[name], "advanced." + name);
    }
    if(advanced.cpuid_level !== null) int(advanced.cpuid_level, "advanced.cpuid_level", 1, 0x20);
    if(arm && advanced.cpuid_level !== null) problem("advanced.cpuid_level", allowed.unavailable["cpuid_level"]);
    return problems;
}

/**
 * Every problem of a configuration, the library's checks of its options
 * included (check_machine_options, check_disk_options): the settings dialog's
 * check before saving
 * @param {VMConfig} config
 * @return {Problem[]}
 */
export function check_config(config)
{
    const problems = validate_config(config);
    if(problems.length) return problems;
    // (a picked file stands in as an empty Blob: the checks look at the kind of source)
    const options = config_to_options(config, { debug: false, query_append: "", graphics_proxy: false, screen_container: undefined, file: () => new Blob([]) });
    /** @type {Array<[string, (options: any) => any]>} */
    const checks = [["machine", check_machine_options], ["disks", check_disk_options]];
    for(const [path, check] of checks)
    {
        try
        {
            check(options);
        }
        catch(e)
        {
            problems.push({ path, message: e.message });
        }
    }
    return problems;
}

/**
 * An image of a configuration as a
 * V86 image option: a URL as given, a file (env.file finds the picked File
 * for it), an empty disk in memory, a browser disk (OPFS: "opfs:<path>")
 * @param {Image | null} image
 * @param {(image: Image) => (Blob | undefined)} file
 * @return {any}
 */
function image_option(image, file)
{
    if(!image) return undefined;
    switch(image.kind)
    {
        case "url":
        {
            /** @type {any} */
            const option = { url: image.url };
            for(const name of ["size", "async", "fixed_chunk_size", "use_parts"])
            {
                if(image[name] !== undefined) option[name] = image[name];
            }
            return option;
        }
        case "file":
        {
            const buffer = file(image);
            if(!buffer) throw new Error("The file " + image.name + " needs to be chosen again");
            return { buffer };
        }
        case "empty":
            return { buffer: new ArrayBuffer(image.size) };
        case "browser":
            return { url: "opfs:" + image.path, size: image.size };
    }
    throw new Error("Unknown image kind " + JSON.stringify(/** @type {any} */ (image).kind));
}

/**
 * The old page's relay_url of a configuration's network backend
 * @param {Network | undefined} network
 * @return {string}
 */
function relay_url_of(network)
{
    if(!network) return "";
    switch(network.backend)
    {
        case "inbrowser": return "inbrowser";
        case "fetch": return network.relay_url ? "fetch:" + network.relay_url : "fetch";
        case "relay": case "wisp": return network.relay_url;
    }
    return "";
}

/**
 * The V86 options of a configuration (checked by validate_config): its
 * fields as the settings of a profile and of the address, the form filled
 * in with them, both made consistent by apply_form as the old page does
 * (src/browser/vm_options.js), then settings_to_options
 * @param {VMConfig} config
 * @param {{debug: boolean, query_append: string, graphics_proxy: (Object | boolean), screen_container: any,
 *     file: (image: Image) => (Blob | undefined)}} env the page (as settings_to_options's), and the
 *     picked File of an image of kind "file"
 * @return {any}
 */
export function config_to_options(config, env)
{
    const MB = 1024 * 1024;
    const image = value => image_option(value, env.file);
    const machine = config.machine, cpu = config.cpu, display = config.display, advanced = config.advanced;
    // (the card the backend serves: the virt machine's net<id>; else the first)
    const served = Math.max(0, config.network.findIndex(n => n.backend !== "none"));
    const network = config.network[served];
    const modem = config.serial.find(serial => serial.attach === "modem");
    /** @type {any} */
    const settings = {};
    settings["ir_tier0"] = advanced.ir_tier0;
    settings["x87_fast_math"] = advanced.x87_fast_math;
    settings["x87_jit_cache"] = advanced.x87_jit_cache;

    // (as a profile's: profile_settings)
    settings.initial_state = image(config.initial_state);
    settings.filesystem = config.filesystem || undefined;
    for(const disk of config.disks)
    {
        const option = image(disk.image);
        if(disk.disk_option === "read_write") option.disk_option = "read_write";
        if(disk.disk_error !== "stop") option.disk_error = disk.disk_error;
        settings[disk.slot] = option;
    }
    settings.cdrom = image(config.cdrom.image);
    if(settings.cdrom && config.cdrom.disk_error !== "stop") settings.cdrom.disk_error = config.cdrom.disk_error;
    for(const floppy of config.floppies)
    {
        const option = image(floppy.image);
        if(option && floppy.disk_option === "read_write") option.disk_option = "read_write";
        settings[floppy.slot] = option;
    }
    if(config.kernel)
    {
        settings.bzimage = image(config.kernel.bzimage);
        settings.initrd = image(config.kernel.initrd);
        settings.multiboot = image(config.kernel.multiboot);
        settings.cmdline = config.kernel.cmdline ?? undefined;
        if(config.kernel.from_filesystem) settings.bzimage_initrd_from_filesystem = true;
    }
    settings.bios = image(machine.bios);
    settings.vga_bios = image(machine.vga_bios);
    if(network && network.mac_address_translation) settings.mac_address_translation = true;
    settings.cpuid_level = advanced.cpuid_level ?? undefined;
    settings.acpi = machine.acpi;
    settings.memory_size = config.memory.mb * MB;
    settings.graphics_adapter = display.adapter;
    settings.vram_size = display.vram_mb === null ? undefined : display.vram_mb * MB;
    settings.boot_order = machine.boot_order || undefined;
    settings.net_device_type = network ? network.device : "none";
    if(!ARM_MACHINE_TYPES.includes(machine.type)) settings.audio_device = config.sound.device;
    if(modem) settings.modem = { uart: modem.port };

    // (as the address's: apply_query_args; a state image has its own machine)
    if(!settings.initial_state)
    {
        settings.cpu_cores = cpu.cores;
        settings.parallel = cpu.parallel;
        settings.cpu_type = cpu.type;
        if(cpu.profile) settings.cpu_profile = cpu.profile;
        settings.machine_type = machine.type;
        if(machine.type === "q35")
        {
            settings.hpet = machine.hpet;
            settings.smbus = machine.smbus;
            settings.pcie_root_ports = machine.pcie_root_ports;
        }
        if(display.displays > 1) settings.displays = display.displays;
        // (the device's level, chosen at power-on: a state image has its own)
        if(display.vulkan !== "none") settings.virtio_gpu_level = display.vulkan;
        settings.mtu = network ? network.mtu : DEFAULT_MTU;
    }
    settings.relay_url = relay_url_of(network);
    if(!cpu.jit) settings.disable_jit = true;
    // (muted; a virt machine without virtio-snd has nothing to play either; a
    // PC without a sound card still has its speaker)
    const quiet = config.sound.mute || ARM_MACHINE_TYPES.includes(machine.type) && config.sound.device === "none";
    if(quiet) settings.disable_audio = true;

    // (the form, filled in with the configuration's values)
    const form = Object.assign({}, DEFAULT_FORM, {
        relay_url: settings.relay_url,
        disable_audio: quiet,
        audio_device: settings.audio_device || DEFAULT_FORM.audio_device,
        files: {},
        empty_sizes: {},
        urls: {},
        disk_options: {},
        memory_size: String(config.memory.mb),
        vga_memory_size: String(display.vram_mb ?? DEFAULT_VGA_MEMORY_SIZE),
        graphics_adapter: display.adapter,
        boot_order: machine.boot_order.toString(16),
        cpu_cores: String(cpu.cores),
        parallel: cpu.parallel,
        cpu_type: cpu.type,
        machine_type: machine.type,
        acpi: machine.acpi,
        net_device_type: settings.net_device_type,
        mtu: String(network ? network.mtu : DEFAULT_MTU),
        modem: "none",
    });
    apply_form(settings, form, new Map(), { location_args: new URLSearchParams(), origin: "", debug: env.debug });

    const options = settings_to_options(settings, {
        cpu_worker: advanced.cpu_worker,
        debug: env.debug,
        query_append: env.query_append,
        graphics_proxy: env.graphics_proxy,
        screen_container: env.screen_container,
    });
    // (the firmware's boot options, which the old page does not have)
    if(machine.fastboot) options.fastboot = true;
    // (UEFI, likewise: OVMF in place of the BIOS images; on i440FX with
    // QEMU's device layout, which OVMF expects)
    // (the variable store: the machine's browser disk written back, which
    // needs the CPU Worker; else the template, its changes in memory)
    if(machine.firmware === "uefi")
    {
        delete options.bios;
        delete options.vga_bios;
        const vars = machine.uefi_vars && advanced.cpu_worker ? Object.assign(image(machine.uefi_vars), { disk_option: "read_write" }) :
            { url: uefi_vars_template(machine) };
        options.firmware = machine.secure_boot ? { type: "uefi", secure_boot: true, code: { url: UEFI_SECURE_CODE_URL }, vars } :
            { type: "uefi", code: { url: UEFI_CODE_URL }, vars };
        if(machine.type === "i440fx") options.qemu_compatible = true;
    }
    // (USB, likewise)
    if(config.usb && !ARM_MACHINE_TYPES.includes(machine.type))
    {
        options.usb = { controller: config.usb.controller, tablet: config.usb.tablet };
        if(config.usb.disks && config.usb.disks.length)
        {
            options.usb.mass_storage = config.usb.disks.map(disk =>
            {
                const option = image(disk.image);
                if(disk.disk_option === "read_write") option.disk_option = "read_write";
                if(disk.disk_error !== "stop") option.disk_error = disk.disk_error;
                return { id: disk.id, image: option, read_only: disk.write_protected };
            });
        }
    }
    // (the TPM, likewise, on the PC machines: its state the machine's browser disk written back, which
    // needs the CPU Worker; else in memory, a new TPM at each power-on)
    if(config.tpm && !ARM_MACHINE_TYPES.includes(machine.type))
    {
        options.tpm = { version: "2.0" };
        if(config.tpm.state && advanced.cpu_worker) options.tpm.state = Object.assign(image(config.tpm.state), { disk_option: "read_write" });
    }
    if(machine.bootmenu) options.bootmenu = true;
    // (the virt machine's devices, which the old page does not have either)
    if(machine.type === "virt")
    {
        const v = config.virt;
        if(v.transport === "pci") options.virtio_transport = "pci";
        if(v.input !== null) options.virtio_input = v.input.length ? v.input.slice() : undefined;
        if(v.console_ports)
        {
            options.virtio_console = true;
            options.virtio_console_ports = v.console_ports;
        }
        if(v.vsock) options.virtio_vsock = true;
        if(v.gpu_pci_slot !== null) options.virtio_gpu_pci_slot = v.gpu_pci_slot;
        if(config.sound.device === "virtio") options.virtio_sound = true;
        if(config.network.length > 1)
        {
            options.net_device.count = config.network.length;
            options.net_device.id = served;
        }
    }
    // (Android: its bootloader gives the kernel, initrd and command line;
    // the kernel section's cmdline goes after the device's)
    if(config.android)
    {
        const a = config.android;
        options.android = { device: a.device, gpu_mode: a.gpu_mode, selinux: a.selinux,
            vendor_ramdisk: a.vendor_ramdisk === "debug" ? image(a.debug_ramdisk) : undefined,
            // (an emulator image on the host's GPU: the GLES version its host announces)
            gles_version: a.gpu_mode === "host" ? a.gles_version : undefined };
        delete options.kernel;
        delete options.initrd;
        options.cmdline = config.kernel && config.kernel.cmdline || undefined;
    }
    return options;
}
                                                                                                                                                                                                                                                                                                                                source/v64/src/app/vm_model.js                                                                      0000644 0000000 0000000 00000037572 00000000000 013411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The settings dialog's rules (docs/vm-manager-plan.md "设置对话框", U3): what
// each control may hold for a configuration (from allowed_options in
// src/machine_options.js, the one place of the machines' rules) and a change
// with what it implies (another CPU picks its machine, Q35 has ACPI, a
// second core needs ACPI, more than 2048 MB needs x86_64, the virt machine
// drops what it does not have), each implication told. A configuration made
// only through change() passes check_config.

import { ARM_MACHINE_TYPES, CPU_PROFILES, CPU_TYPES, MACHINE_CPU_PROFILES, MAX_VRAM_SIZE, allowed_options, is_arm } from "../machine_options.js";
import { ANDROID_DEVICES as ANDROID_DEVICE_MODELS } from "../android/bootloader.js";
import { MAX_MEMORY_SIZE, MAX_HEAP_MEMORY_SIZE, Q35_PAGE_DEVICES } from "../browser/vm_options.js";
import { SOUND_DEVICES, BOOT_ORDERS } from "./vm_config.js";

/** Android's GPU modes and display.vulkan's kinds, as the notes name them */
const GPU_NAMES = { swiftshader: "SwiftShader", venus: "Venus", gfxstream: "gfxstream", host: "the host's GPU", guest: "the guest's CPU", none: "none" };

/** @typedef {import("./vm_config.js").VMConfig} VMConfig */

/** The sound devices of the virt machine (virtio-snd); ranchu's (its goldfish audio is not played) */
export const VIRT_SOUND_DEVICES = ["virtio", "none"];
export const RANCHU_SOUND_DEVICES = ["none"];

/** The input devices a virt machine may have (virtio_input) */
export const VIRT_INPUTS = ["keyboard", "tablet", "multitouch"];

/**
 * A network backend's URL by default (the old page's buttons: its relay, a
 * public wisp server; fetch without a CORS proxy), and whether a URL fits it
 */
export const BACKEND_URLS = {
    none: { default: "", fits: url => url === "" },
    inbrowser: { default: "", fits: url => url === "" },
    relay: { default: "wss://relay.widgetry.org/", fits: url => /^wss?:\/\//.test(url) },
    wisp: { default: "wisps://wisp.mercurywork.shop/v86/", fits: url => /^wisps?:\/\//.test(url) },
    fetch: { default: "", fits: url => url === "" || /^https?:\/\//.test(url) },
};

/**
 * What the controls may hold for a configuration
 * @param {VMConfig} config
 */
export function choices(config)
{
    const allowed = allowed_options(config.cpu.type, config.machine.type);
    const arm = ARM_MACHINE_TYPES.includes(config.machine.type);
    const virt = config.machine.type === "virt", ranchu = config.machine.type === "ranchu";
    // (the Wasm heap for the 32-bit CPUs: arm32's RAM is below 4 GiB, its 32-bit kernels' reach)
    const sixty_four = config.cpu.type === "x86_64" || config.cpu.type === "arm64";
    return {
        cpu_types: CPU_TYPES.slice(),
        /** the CPU models to offer (cpu.profile), null (automatic) first */
        cpu_profiles: [null, ...allowed.cpu_profiles],
        machine_types: allowed.machine_types,
        graphics_adapters: allowed.graphics_adapters,
        net_devices: allowed.net_device_types,
        sound_devices: ranchu ? RANCHU_SOUND_DEVICES : virt ? VIRT_SOUND_DEVICES : SOUND_DEVICES,
        usb_controllers: allowed.usb_controllers,
        boot_orders: arm ? [0] : BOOT_ORDERS,
        max_cores: allowed.max_cores,
        /** the most memory in MB: the Wasm heap for the 32-bit CPUs, extended RAM above it for the 64-bit ones */
        max_memory: sixty_four ? MAX_MEMORY_SIZE : MAX_HEAP_MEMORY_SIZE,
        max_vram: MAX_VRAM_SIZE >> 20,
        /** ACPI: set by the machine (Q35: always, virt: never), or by more than one core; null when free */
        acpi_fixed: allowed.acpi === "required" ? { value: true, reason: "the Q35 machine always has ACPI" } :
            allowed.acpi === "none" ? { value: false, reason: allowed.unavailable["acpi"] } :
            config.cpu.cores > 1 ? { value: true, reason: "more than one core needs ACPI" } : null,
        /** the most network cards (virt: virtio-net functions, Android's three) */
        max_network: virt ? 4 : 1,
        /** an option's reason when it does not apply (allowed_options's names) */
        unavailable: allowed.unavailable,
    };
}

/**
 * A copy to change
 * @param {VMConfig} config
 * @return {VMConfig}
 */
function copy(config)
{
    return JSON.parse(JSON.stringify(config));
}

/**
 * The fields that depend on the CPU, machine, cores and display, made to fit them; the notes say what changed
 * @param {VMConfig} c
 * @param {string[]} notes
 */
function fit(c, notes)
{
    const allowed = allowed_options(c.cpu.type, c.machine.type);
    // (arm: an ARM board, virt or ranchu; virt and ranchu: their own devices)
    const arm = ARM_MACHINE_TYPES.includes(c.machine.type);
    const virt = c.machine.type === "virt", ranchu = c.machine.type === "ranchu";
    const note = text => { if(!notes.includes(text)) notes.push(text); };

    if(!allowed.machine_types.includes(c.machine.type))
    {
        c.machine.type = allowed.machine_types[0];
        note("Machine: " + c.machine.type + " (the " + c.cpu.type + " CPU's)");
        return fit(c, notes);
    }
    if(c.cpu.cores > allowed.max_cores) c.cpu.cores = allowed.max_cores;
    if(c.cpu.type === "x86" && c.memory.mb > MAX_HEAP_MEMORY_SIZE)
    {
        c.cpu.type = "x86_64";
        note("Processor: x86_64 (more than " + MAX_HEAP_MEMORY_SIZE + " MB needs a 64-bit CPU)");
        return fit(c, notes);
    }
    if(c.cpu.type === "arm32" && c.memory.mb > MAX_HEAP_MEMORY_SIZE)
    {
        c.memory.mb = MAX_HEAP_MEMORY_SIZE;
        note("Memory: " + MAX_HEAP_MEMORY_SIZE + " MB (the most of the 32-bit ARM CPU)");
    }
    if(c.cpu.profile)
    {
        // (a CPU model of another CPU, one the machine does not take, or no model at all: the default)
        const model = Object.prototype.hasOwnProperty.call(CPU_PROFILES, c.cpu.profile) ? CPU_PROFILES[c.cpu.profile] : null;
        const only = MACHINE_CPU_PROFILES[c.machine.type]?.[c.cpu.type];
        const reason = !model ? "there is no CPU model " + c.cpu.profile : model.cpu_type !== c.cpu.type ? c.cpu.profile + " is not a " + c.cpu.type + " CPU" :
            only && !only.includes(c.cpu.profile) ? "the " + c.machine.type + " machine takes " + only.join(", ") : "";
        if(reason) { c.cpu.profile = null; note("CPU model: automatic (" + reason + ")"); }
    }

    // ACPI and the Q35 machine's devices
    if(allowed.acpi === "none" && c.machine.acpi) { c.machine.acpi = false; note("ACPI off: " + allowed.unavailable["acpi"]); }
    if(allowed.acpi === "required" && !c.machine.acpi) { c.machine.acpi = true; note("ACPI on: the Q35 machine always has it"); }
    if(allowed.acpi === "with_cores" && c.cpu.cores > 1 && !c.machine.acpi) { c.machine.acpi = true; note("ACPI on: more than one core needs it"); }
    // the TPM: on a PC machine, with ACPI (docs/tpm.md)
    if(c.tpm)
    {
        if(arm)
        {
            c.tpm = null;
            note("TPM removed: " + allowed.unavailable["tpm"]);
        }
        else if(!c.machine.acpi)
        {
            c.machine.acpi = true;
            note("ACPI on: the TPM needs it");
        }
    }
    // UEFI: OVMF runs on the x86_64 CPU with ACPI (docs/uefi.md)
    if(c.machine.firmware === "uefi")
    {
        if(arm || c.cpu.type !== "x86_64")
        {
            c.machine.firmware = "seabios";
            note("Firmware: SeaBIOS (UEFI needs the x86_64 CPU on a PC machine)");
        }
        else if(!c.machine.acpi)
        {
            c.machine.acpi = true;
            note("ACPI on: UEFI needs it");
        }
    }
    // Secure Boot: the Secure Boot firmware runs in SMM, on Q35 (docs/uefi.md)
    if(c.machine.secure_boot && (c.machine.firmware !== "uefi" || c.machine.type !== "q35"))
    {
        c.machine.secure_boot = false;
        note("Secure Boot off: it needs UEFI on the Q35 machine");
    }
    if(c.machine.type === "q35") { /* (kept: the Q35 devices are the user's) */ }
    else
    {
        if(c.machine.hpet || c.machine.smbus || c.machine.pcie_root_ports) note("HPET, SMBus and root ports off: only the Q35 machine has them");
        c.machine.hpet = false;
        c.machine.smbus = false;
        c.machine.pcie_root_ports = 0;
    }

    // the PC's firmware, floppies, modem, Sound Blaster and CPUID level: not on the ARM boards
    if(arm)
    {
        if(c.machine.bios || c.machine.vga_bios) { c.machine.bios = c.machine.vga_bios = null; note("BIOS removed: " + allowed.unavailable["bios"]); }
        if(c.machine.boot_order) { c.machine.boot_order = 0; note("Boot order: automatic (the " + c.machine.type + " machine boots its kernel)"); }
        if(c.floppies.length) { c.floppies = []; note("Floppy drives removed: " + allowed.unavailable["fda"]); }
        if(c.kernel && c.kernel.multiboot) { c.kernel.multiboot = null; note("Multiboot image removed: " + allowed.unavailable["multiboot"]); }
        for(const serial of c.serial) if(serial.attach === "modem") { serial.attach = "terminal"; note("Modem removed: " + allowed.unavailable["modem"]); }
        if(c.advanced.cpuid_level !== null) { c.advanced.cpuid_level = null; note("CPUID level: the CPU's own"); }
    }
    if(!virt)
    {
        const v = c.virt;
        if(v && (v.transport !== "mmio" || v.input !== null || v.console_ports || v.vsock || v.gpu_pci_slot !== null))
        {
            c.virt = { transport: "mmio", input: null, console_ports: 0, vsock: false, gpu_pci_slot: null };
            note("The virt machine's devices removed (virtio transport, input, console ports, vsock)");
        }
    }

    // display, network, sound
    if(!allowed.graphics_adapters.includes(c.display.adapter))
    {
        c.display.adapter = ranchu ? "none" : virt ? "virtio_gpu" : "bochs_vga";
        note("Display: " + c.display.adapter + (ranchu ? " (the ranchu machine has the emulator's framebuffer)" : virt ? " (the virt machine has no VGA)" : ""));
    }
    if(c.display.adapter !== "virtio_gpu" && c.display.displays > 1) { c.display.displays = 1; note("One display: only virtio-gpu has more"); }
    if(c.display.adapter !== "virtio_gpu" && c.display.vulkan !== "none") { c.display.vulkan = "none"; note("No Vulkan: only virtio-gpu has it"); }
    // (Android: its device model's machine and CPU, Cuttlefish's the arm64
    // virt machine, an emulator image's ranchu; Venus and gfxstream with theirs)
    const model = c.android && ANDROID_DEVICE_MODELS[c.android.device];
    if(model && (model.machine !== c.machine.type || model.cpu !== c.cpu.type))
    {
        c.android = null;
        note("Android's bootloader off: " + model.id + " boots on the " + model.machine + " machine with the " + model.cpu + " CPU");
    }
    // (the device kind's GPU modes: an emulator image draws with the
    // host's GPU or the guest's CPU, Cuttlefish with SwiftShader, Venus or gfxstream)
    const ranchu_gpu = ["host", "guest", "swiftshader"];
    if(c.android && model && (model.machine === "ranchu") !== ranchu_gpu.includes(c.android.gpu_mode) && c.android.gpu_mode !== "swiftshader")
    {
        const was = c.android.gpu_mode;
        c.android.gpu_mode = model.machine === "ranchu" ? "guest" : "swiftshader";
        note("Android's GPU: " + GPU_NAMES[c.android.gpu_mode] + " (" + model.id + " has no " + GPU_NAMES[was] + ")");
    }
    // (an emulator image's GPU modes are its own: the display's Vulkan is not theirs)
    if(c.android && model && model.machine !== "ranchu" && c.android.gpu_mode !== "swiftshader" && c.display.vulkan !== c.android.gpu_mode)
    {
        const was = c.android.gpu_mode;
        c.android.gpu_mode = c.display.vulkan === "none" ? "swiftshader" : c.display.vulkan;
        note("Android's GPU: " + GPU_NAMES[c.android.gpu_mode] + " (" + GPU_NAMES[was] + " needs the display's " + GPU_NAMES[was] + ")");
    }
    const max_network = virt ? 4 : 1;
    if(c.network.length > max_network)
    {
        c.network = c.network.slice(0, max_network);
        note("Network: one card (the PC machines have one)");
    }
    for(const n of c.network)
    {
        if(!allowed.net_device_types.includes(n.device))
        {
            n.device = arm ? "virtio" : "ne2k";
            note("Network card: " + n.device + (arm ? " (the " + c.machine.type + " machine has virtio-net)" : ""));
        }
    }
    // (one card with a backend: the virt machine's NICs share one)
    let served = false;
    for(const n of c.network)
    {
        if(n.backend === "none") continue;
        if(served) { n.backend = "none"; n.relay_url = ""; note("Network: one card reaches the network, the others stay unconnected"); }
        served = true;
    }
    const sound = ranchu ? RANCHU_SOUND_DEVICES : virt ? VIRT_SOUND_DEVICES : SOUND_DEVICES;
    if(!sound.includes(c.sound.device))
    {
        c.sound.device = "none";
        note("Sound: none" + (ranchu ? " (the ranchu machine's sound is not played)" : virt ? " (the virt machine has no Sound Blaster)" : ""));
    }
    if(c.usb && (virt || ranchu))
    {
        c.usb = null;
        note("USB: none (the " + c.machine.type + " machine's input is virtio-input)");
    }
    return c;
}

/**
 * A change of one field and what it implies
 * @param {VMConfig} config
 * @param {string} path "cpu.type", "machine.acpi", "memory.mb", "display.adapter", "network.0.device", ...
 * @param {any} value
 * @return {{config: VMConfig, notes: string[]}} notes: what else changed, for people
 */
export function change(config, path, value)
{
    const c = copy(config);
    const notes = [];
    const keys = path.split(".");
    /** @type {any} */
    let target = c;
    for(const key of keys.slice(0, -1)) target = target[key];
    const last = keys[keys.length - 1];
    const before = target[last];
    target[last] = value;

    const backend = /^network\.(\d+)\.backend$/.exec(path);
    if(backend && BACKEND_URLS[value] && !BACKEND_URLS[value].fits(c.network[+backend[1]].relay_url))
    {
        c.network[+backend[1]].relay_url = BACKEND_URLS[value].default;
    }
    if(path === "machine.type" && value === "q35" && before !== "q35")
    {
        // (the page's Q35: an HPET and an SMBus controller, as a real board has them)
        c.machine.hpet = Q35_PAGE_DEVICES.hpet;
        c.machine.smbus = Q35_PAGE_DEVICES.smbus;
        c.machine.pcie_root_ports = Q35_PAGE_DEVICES.pcie_root_ports;
    }
    if(path === "display.vulkan" && value !== "none" && !c.display.proxy)
    {
        c.display.proxy = true;
        notes.push("Graphics proxy: on (its WebGPU renderer draws Vulkan)");
    }
    if(path === "display.proxy" && !value && c.display.vulkan !== "none")
    {
        c.display.vulkan = "none";
        notes.push("Vulkan: off (it needs the graphics proxy)");
    }
    const arm_machine = ARM_MACHINE_TYPES.includes(c.machine.type);
    if(path === "cpu.type" && is_arm(value) && !arm_machine)
    {
        c.machine.type = "virt";
        notes.push("Machine: virt (the " + value + " CPU's)");
    }
    if(path === "cpu.type" && !is_arm(value) && arm_machine)
    {
        c.machine.type = "i440fx";
        notes.push("Machine: i440fx (the " + value + " CPU's)");
    }
    if(path === "cpu.type" && c.cpu.profile && CPU_PROFILES[c.cpu.profile]?.cpu_type !== value)
    {
        c.cpu.profile = null;
        notes.push("CPU model: automatic (the " + value + " CPU's default)");
    }
    if(path === "cpu.type" && value === "x86" && c.memory.mb > MAX_HEAP_MEMORY_SIZE)
    {
        c.memory.mb = MAX_HEAP_MEMORY_SIZE;
        notes.push("Memory: " + MAX_HEAP_MEMORY_SIZE + " MB (the most of the 32-bit CPU)");
    }
    if(path === "machine.type" && ARM_MACHINE_TYPES.includes(value) && !is_arm(c.cpu.type))
    {
        c.cpu.type = "arm64";
        notes.push("Processor: arm64 (the " + value + " machine's)");
    }
    if(path === "machine.type" && !ARM_MACHINE_TYPES.includes(value) && is_arm(c.cpu.type))
    {
        c.cpu.type = "x86";
        notes.push("Processor: x86 (the PC machines')");
    }
    return { config: fit(c, notes), notes };
}

/**
 * A configuration made to fit its CPU and machine (a preset's, an imported one's)
 * @param {VMConfig} config
 * @return {{config: VMConfig, notes: string[]}}
 */
export function fitted(config)
{
    const notes = [];
    return { config: fit(copy(config), notes), notes };
}
                                                                                                                                      source/v64/src/app/vm_state.js                                                                      0000644 0000000 0000000 00000012526 00000000000 013421  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// Suspended machines (docs/vm-manager-plan.md "存储与持久化", U5): a
// machine's state saved as a V7 stream into the browser's private file
// system (OPFS, v86/states/<id>.bin), the space it needs checked first,
// persistent storage asked for once; the configuration's digest, to tell
// whether its settings changed after it was suspended; the lock that keeps
// a machine in one tab (navigator.locks).

/** @typedef {import("./vm_config.js").VMConfig} VMConfig */

const STATES = ["v86", "states"];

/**
 * The directory of the states (made when missing)
 * @return {Promise<FileSystemDirectoryHandle>}
 */
async function states_directory()
{
    let dir = await navigator.storage.getDirectory();
    for(const name of STATES) dir = await dir.getDirectoryHandle(name, { create: true });
    return dir;
}

/**
 * @param {string} id
 */
function state_name(id)
{
    return id.replace(/[^A-Za-z0-9_-]/g, "_") + ".bin";
}

/**
 * The suspended state's file of a machine, or undefined
 * @param {string} id
 * @return {Promise<File | undefined>}
 */
export async function read_state(id)
{
    try
    {
        return await (await (await states_directory()).getFileHandle(state_name(id))).getFile();
    }
    catch(e)
    {
        if(e.name === "NotFoundError") return undefined;
        throw e;
    }
}

/**
 * Remove a machine's suspended state (none: nothing to do)
 * @param {string} id
 */
export async function delete_state(id)
{
    try
    {
        await (await states_directory()).removeEntry(state_name(id));
    }
    catch(e)
    {
        if(e.name !== "NotFoundError") throw e;
    }
}

/**
 * Save a machine's state into its file, as a V7 stream written as it is
 * made; the file is replaced only when the whole state is written
 * @param {string} id
 * @param {(write: (chunk: Uint8Array) => any) => Promise<any>} save the emulator's save_state_stream
 * @return {Promise<number>} its size
 */
export async function write_state(id, save)
{
    const dir = await states_directory();
    const handle = await dir.getFileHandle(state_name(id), { create: true });
    const writable = await handle.createWritable();
    let size = 0;
    try
    {
        await save(chunk => { size += chunk.length; return writable.write(chunk.slice()); });
        await writable.close();
    }
    catch(e)
    {
        await writable.abort().catch(() => {});
        throw e;
    }
    return size;
}

/**
 * The browser's space for this site: what is free, and whether it is kept
 * when the browser runs short (persistent)
 * @return {Promise<{free: number, usage: number, quota: number, persisted: boolean}>}
 */
export async function storage_space()
{
    const estimate = await navigator.storage.estimate();
    const persisted = navigator.storage.persisted ? await navigator.storage.persisted() : false;
    return { free: Math.max(0, (estimate.quota || 0) - (estimate.usage || 0)), usage: estimate.usage || 0, quota: estimate.quota || 0, persisted };
}

/**
 * About how much a machine's state takes: its RAM and video memory (the
 * stream holds them whole), and a margin for the devices
 * @param {any} options the machine's V86 options
 */
export function state_estimate(options)
{
    return (options.memory_size || 0) + (options.extended_memory_size || 0) + (options.vram_size || 0) + (16 << 20);
}

/**
 * The digest of a configuration's machine: its settings without the name,
 * notes, times and the suspension itself (a change of them does not matter
 * to a saved state)
 * @param {VMConfig} config
 * @return {Promise<string>}
 */
export async function machine_digest(config)
{
    /** @type {any} */
    const machine = JSON.parse(JSON.stringify(config));
    for(const name of ["id", "name", "notes", "guest", "template", "created", "modified", "suspended"]) delete machine[name];
    const canonical = value => Array.isArray(value) ? value.map(canonical) :
        value && typeof value === "object" ? Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])) : value;
    const bytes = new TextEncoder().encode(JSON.stringify(canonical(machine)));
    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
    return Array.from(digest, b => b.toString(16).padStart(2, "0")).join("");
}

/** A machine's lock's name */
export function lock_name(id)
{
    return "v86-vm-" + id;
}

/**
 * Hold a machine's lock while it runs in this tab: null when another tab holds it
 * @param {string} id
 * @return {Promise<{release: () => void} | null>}
 */
export function hold_machine(id)
{
    if(!navigator.locks) return Promise.resolve({ release: () => {} });
    return new Promise(resolve =>
    {
        navigator.locks.request(lock_name(id), { ifAvailable: true }, lock =>
        {
            if(!lock)
            {
                resolve(null);
                return undefined;
            }
            // (held until released: the tab closes, or the machine powers off)
            return new Promise(release => resolve({ release: () => release(undefined) }));
        });
    });
}

/**
 * The machines that run in a tab now (their locks are held)
 * @return {Promise<Set<string>>}
 */
export async function running_machines()
{
    if(!navigator.locks) return new Set();
    const state = await navigator.locks.query();
    return new Set((state.held || []).map(lock => lock.name || "").filter(name => name.startsWith("v86-vm-")).map(name => name.slice(7)));
}
                                                                                                                                                                          source/v64/src/app/vm_store.js                                                                      0000644 0000000 0000000 00000023112 00000000000 013426  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // @ts-check
// The VM manager's library (docs/vm-manager-plan.md, "存储与持久化", U1):
// the configurations in IndexedDB (the database v86-vm-manager: the store
// vms by id, handles, the FileSystemFileHandles of the files the
// configurations name, and prefs, the manager's preferences such as its disk
// service, U3), and a configuration's export to a .v86vm.json file and
// import from one. The suspended states and the browser disks in OPFS come
// with U5 and U6.

import { migrate, validate_config, new_id } from "./vm_config.js";
import { machine_digest } from "./vm_state.js";

/** @typedef {import("./vm_config.js").VMConfig} VMConfig */
/** @typedef {import("./vm_config.js").Image} Image */

export const DB_NAME = "v86-vm-manager";
/** 1: vms, handles; 2: prefs */
const DB_VERSION = 2;
const VMS = "vms";
const HANDLES = "handles";
const PREFS = "prefs";

/**
 * A request's result
 * @template T
 * @param {IDBRequest<T>} request
 * @return {Promise<T>}
 */
function done(request)
{
    return new Promise((resolve, reject) =>
    {
        request.onsuccess = () => resolve(request.result);
        request.onerror = () => reject(request.error);
    });
}

/**
 * A transaction's end
 * @param {IDBTransaction} transaction
 * @return {Promise<void>}
 */
function complete(transaction)
{
    return new Promise((resolve, reject) =>
    {
        transaction.oncomplete = () => resolve();
        transaction.onerror = () => reject(transaction.error);
        transaction.onabort = () => reject(transaction.error || new Error("The transaction was aborted"));
    });
}

/**
 * The images a configuration names, wherever they are
 * @param {VMConfig} config
 * @return {Image[]}
 */
export function config_images(config)
{
    return [config.machine.bios, config.machine.vga_bios, config.machine.uefi_vars, config.tpm && config.tpm.state,
        ...config.disks.map(d => d.image), ...(config.usb ? config.usb.disks.map(d => d.image) : []),
        config.cdrom.image,
        ...config.floppies.map(f => f.image), config.kernel && config.kernel.bzimage, config.kernel && config.kernel.initrd,
        config.kernel && config.kernel.multiboot, config.initial_state].filter(image => !!image);
}

/**
 * Why a configuration cannot be stored: its problems (validate_config), one per line
 * @param {import("./vm_config.js").Problem[]} problems
 * @return {Error}
 */
function invalid(problems)
{
    const error = new Error("The virtual machine's settings are not valid:\n" + problems.map(p => p.path + ": " + p.message).join("\n"));
    /** @type {any} */ (error).problems = problems;
    return error;
}

export class VMStore
{
    /**
     * @param {IDBDatabase} db
     */
    constructor(db)
    {
        this.db = db;
    }

    /**
     * Open (and on the first use create) the library
     * @param {string} [name] the database's name (tests use their own)
     * @return {Promise<VMStore>}
     */
    static async open(name = DB_NAME)
    {
        const request = globalThis.indexedDB.open(name, DB_VERSION);
        request.onupgradeneeded = () =>
        {
            const db = request.result;
            if(!db.objectStoreNames.contains(VMS)) db.createObjectStore(VMS, { keyPath: "id" });
            if(!db.objectStoreNames.contains(HANDLES)) db.createObjectStore(HANDLES);
            if(!db.objectStoreNames.contains(PREFS)) db.createObjectStore(PREFS);
        };
        return new VMStore(await done(request));
    }

    close()
    {
        this.db.close();
    }

    /**
     * Every configuration, in the current version, by name
     * @return {Promise<VMConfig[]>}
     */
    async list()
    {
        const transaction = this.db.transaction(VMS, "readonly");
        const all = await done(transaction.objectStore(VMS).getAll());
        const configs = await Promise.all(all.map(raw => this.current(raw)));
        return configs.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
    }

    /**
     * @param {string} id
     * @return {Promise<VMConfig | undefined>}
     */
    async get(id)
    {
        const raw = await done(this.db.transaction(VMS, "readonly").objectStore(VMS).get(id));
        return raw === undefined ? undefined : this.current(raw);
    }

    /**
     * A stored configuration in the current version (migrate). A suspended
     * machine's digest (src/app/vm_state.js) is of the configuration as it
     * was stored; a migration changes the form, not the guest's hardware
     * (version 3: a PC's sound "none" was a muted Sound Blaster and becomes
     * one), so where the digest was still right the new form's replaces it,
     * and the configuration is stored in the new form: otherwise every
     * suspended machine would say its settings changed
     * @param {any} raw
     * @return {Promise<VMConfig>}
     */
    async current(raw)
    {
        const config = migrate(raw);
        if(raw.version === config.version || !config.suspended) return config;
        if(config.suspended.digest !== await machine_digest(raw)) return config;
        config.suspended = Object.assign({}, config.suspended, { digest: await machine_digest(config) });
        const transaction = this.db.transaction(VMS, "readwrite");
        transaction.objectStore(VMS).put(config);
        await complete(transaction);
        return config;
    }

    /**
     * Store a configuration (new or changed): checked first, its time of change set
     * @param {VMConfig} config
     * @return {Promise<VMConfig>} what was stored
     */
    async put(config)
    {
        const problems = validate_config(config);
        if(problems.length) throw invalid(problems);
        const stored = Object.assign({}, config, { modified: new Date().toISOString() });
        const transaction = this.db.transaction(VMS, "readwrite");
        transaction.objectStore(VMS).put(stored);
        await complete(transaction);
        return stored;
    }

    /**
     * Delete a configuration and the handles of its files (its browser disks
     * and suspended state: U5, U6)
     * @param {string} id
     */
    async delete(id)
    {
        const config = await this.get(id);
        const transaction = this.db.transaction([VMS, HANDLES], "readwrite");
        transaction.objectStore(VMS).delete(id);
        for(const image of config ? config_images(config) : [])
        {
            if(image.kind === "file" && image.handle) transaction.objectStore(HANDLES).delete(image.handle);
        }
        await complete(transaction);
    }

    /**
     * Keep a file's handle (Chrome and Edge keep a FileSystemFileHandle in
     * IndexedDB; the page asks for its permission again when it starts the machine)
     * @param {FileSystemFileHandle} handle
     * @return {Promise<string>} the handle's id, for the image's `handle`
     */
    async put_handle(handle)
    {
        const id = new_id();
        const transaction = this.db.transaction(HANDLES, "readwrite");
        transaction.objectStore(HANDLES).put(handle, id);
        await complete(transaction);
        return id;
    }

    /**
     * @param {string} id
     * @return {Promise<FileSystemFileHandle | undefined>}
     */
    async get_handle(id)
    {
        return done(this.db.transaction(HANDLES, "readonly").objectStore(HANDLES).get(id));
    }

    /**
     * A preference (undefined when not set)
     * @param {string} name
     * @return {Promise<any>}
     */
    async get_pref(name)
    {
        return done(this.db.transaction(PREFS, "readonly").objectStore(PREFS).get(name));
    }

    /**
     * Set a preference (undefined: back to its default)
     * @param {string} name
     * @param {any} value
     */
    async put_pref(name, value)
    {
        const transaction = this.db.transaction(PREFS, "readwrite");
        if(value === undefined) transaction.objectStore(PREFS).delete(name);
        else transaction.objectStore(PREFS).put(value, name);
        await complete(transaction);
    }
}

/**
 * A configuration as a .v86vm.json file's text: the files' handles stay in
 * this browser (an imported configuration's files need to be chosen again)
 * @param {VMConfig} config
 * @return {string}
 */
export function export_config(config)
{
    /** @type {any} */
    const copy = JSON.parse(JSON.stringify(config));
    for(const image of config_images(copy))
    {
        if(image.kind === "file") delete image.handle;
    }
    return JSON.stringify(copy, null, 4) + "\n";
}

/**
 * The file name to export a configuration to
 * @param {VMConfig} config
 * @return {string}
 */
export function export_file_name(config)
{
    return (config.name.replace(/[^\p{L}\p{N} ._-]+/gu, "_").trim() || "virtual machine") + ".v86vm.json";
}

/**
 * A configuration of a .v86vm.json file's text, in the current version and
 * checked; a new id when it has none or the library has one with its id already
 * @param {string} text
 * @param {Set<string>} [ids] the library's configurations' ids
 * @return {VMConfig}
 */
export function import_config(text, ids = new Set())
{
    let raw;
    try
    {
        raw = JSON.parse(text);
    }
    catch(e)
    {
        throw new Error("The file is not a v86 virtual machine (not JSON: " + e.message + ")");
    }
    const config = migrate(raw);
    if(typeof config.id !== "string" || !config.id || ids.has(config.id)) config.id = new_id();
    const problems = validate_config(config);
    if(problems.length) throw invalid(problems);
    return config;
}

/**
 * The images that need their file chosen again: files without a handle (imported, or from a browser
 * that does not keep handles)
 * @param {VMConfig} config
 * @return {Image[]}
 */
export function files_to_choose(config)
{
    return config_images(config).filter(image => image.kind === "file" && !image.handle);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/apple/devicetree.js                                                                  0000644 0000000 0000000 00000012104 00000000000 014227  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Apple's flattened device tree (docs/iphone4-plan.md S0, S1): a node is
// its property count and child count (u32 each, little-endian), its
// properties (a 32-byte NUL-padded name, a u32 length, the value padded to
// 4 bytes) and its children. The length's top bit marks a placeholder that
// iBoot replaces (with a value of the same size) while it fills the tree:
// v86 does that filling itself (src/apple/boot.js).

const PLACEHOLDER = 0x80000000;

/**
 * @typedef {{name: string, value: !Uint8Array, placeholder: boolean}}
 */
export let DTProperty;

/**
 * @typedef {{properties: !Array<!DTProperty>, children: !Array<!Object>}}
 */
export let DTNode;

/**
 * @param {!Uint8Array} bytes
 * @return {!DTNode} the root
 */
export function dt_parse(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    let at = 0;
    const node = () =>
    {
        if(at + 8 > bytes.length) throw new Error("device tree: cut short");
        const property_count = view.getUint32(at, true), child_count = view.getUint32(at + 4, true);
        at += 8;
        const properties = [], children = [];
        for(let i = 0; i < property_count; i++)
        {
            if(at + 36 > bytes.length) throw new Error("device tree: a property cut short");
            const raw = bytes.subarray(at, at + 32);
            const end = raw.indexOf(0);
            const name = String.fromCharCode(...raw.subarray(0, end < 0 ? 32 : end));
            const word = view.getUint32(at + 32, true), length = word & ~PLACEHOLDER;
            if(at + 36 + length > bytes.length) throw new Error(`device tree: property ${name} cut short`);
            properties.push({ name, value: bytes.slice(at + 36, at + 36 + length), placeholder: !!(word & PLACEHOLDER) });
            at += 36 + (length + 3 & ~3);
        }
        for(let i = 0; i < child_count; i++) children.push(node());
        return { properties, children };
    };
    const root = node();
    return root;
}

/**
 * @param {!DTNode} root
 * @return {!Uint8Array}
 */
export function dt_serialize(root)
{
    const size = n => 8 + n.properties.reduce((s, p) => s + 36 + (p.value.length + 3 & ~3), 0) + n.children.reduce((s, c) => s + size(c), 0);
    const out = new Uint8Array(size(root)), view = new DataView(out.buffer);
    let at = 0;
    const write = n =>
    {
        view.setUint32(at, n.properties.length, true);
        view.setUint32(at + 4, n.children.length, true);
        at += 8;
        for(const p of n.properties)
        {
            if(p.name.length > 31) throw new Error(`device tree: property name ${p.name} is too long`);
            for(let i = 0; i < p.name.length; i++) out[at + i] = p.name.charCodeAt(i);
            view.setUint32(at + 32, (p.value.length | (p.placeholder ? PLACEHOLDER : 0)) >>> 0, true);
            out.set(p.value, at + 36);
            at += 36 + (p.value.length + 3 & ~3);
        }
        for(const c of n.children) write(c);
    };
    write(root);
    return out;
}

/** @param {!DTNode} node @param {string} name @return {?DTProperty} */
export function dt_property(node, name)
{
    return node.properties.find(p => p.name === name) || null;
}

/** @param {!DTNode} node @return {string} its name property */
export function dt_name(node)
{
    const p = dt_property(node, "name");
    return p ? dt_string(p.value) : "";
}

/** @param {!Uint8Array} value @return {string} up to the first NUL */
export function dt_string(value)
{
    const end = value.indexOf(0);
    return String.fromCharCode(...value.subarray(0, end < 0 ? value.length : end));
}

/** @param {!Uint8Array} value @return {!Array<string>} a list of NUL-terminated strings */
export function dt_strings(value)
{
    return String.fromCharCode(...value).split("\0").filter(Boolean);
}

/** @param {!Uint8Array} value @return {!Array<number>} little-endian u32 cells */
export function dt_cells(value)
{
    const view = new DataView(value.buffer, value.byteOffset, value.byteLength);
    return Array.from({ length: value.length >> 2 }, (_, i) => view.getUint32(4 * i, true));
}

/**
 * The node at a path of names ("/arm-io/uart0"; the root is "/" or "")
 * @param {!DTNode} root
 * @param {string} path
 * @return {?DTNode}
 */
export function dt_find(root, path)
{
    let node = root;
    for(const part of path.split("/").filter(Boolean))
    {
        node = node.children.find(c => dt_name(c) === part);
        if(!node) return null;
    }
    return node;
}

/**
 * Sets (or adds) a property; placeholder cleared
 * @param {!DTNode} node
 * @param {string} name
 * @param {!Uint8Array} value
 */
export function dt_set(node, name, value)
{
    const p = dt_property(node, name);
    if(p) { p.value = value; p.placeholder = false; }
    else node.properties.push({ name, value, placeholder: false });
}

/**
 * Every node with its path, depth first: visit(path, node)
 * @param {!DTNode} root
 * @param {function(string, !DTNode)} visit
 */
export function dt_walk(root, visit)
{
    const recurse = (prefix, node) =>
    {
        visit(prefix || "/", node);
        for(const c of node.children) recurse(prefix + "/" + dt_name(c), c);
    };
    recurse("", root);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/apple/macho.js                                                                       0000644 0000000 0000000 00000014572 00000000000 013212  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Mach-O, the format of XNU's kernelcache and of iOS's binaries
// (docs/iphone4-plan.md S0, S1): the header, the load commands v86 needs
// (segments and their sections, the symbol table, LC_UNIXTHREAD's entry
// point, the UUID, the dylibs) and the symbols. 32- and 64-bit, little-endian.

const LC_SEGMENT = 0x1, LC_SYMTAB = 0x2, LC_UNIXTHREAD = 0x5, LC_LOAD_DYLIB = 0xC, LC_ID_DYLIB = 0xD,
    LC_SEGMENT_64 = 0x19, LC_UUID = 0x1B, LC_VERSION_MIN_IPHONEOS = 0x25, LC_LOAD_WEAK_DYLIB = 0x80000018,
    LC_REEXPORT_DYLIB = 0x8000001F;

export const CPU_TYPE_ARM = 12;

/** @param {!Uint8Array} b @param {number} at @param {number} n @return {string} */
function fixed_string(b, at, n)
{
    const raw = b.subarray(at, at + n), end = raw.indexOf(0);
    return String.fromCharCode(...raw.subarray(0, end < 0 ? n : end));
}

/** @param {!Uint8Array} b @param {number} at @return {string} */
function c_string(b, at)
{
    let end = at;
    while(end < b.length && b[end]) end++;
    return String.fromCharCode(...b.subarray(at, end));
}

/**
 * @param {!Uint8Array} bytes
 * @return {Object}
 */
export function macho_parse(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const magic = view.getUint32(0, true);
    const is64 = magic === 0xFEEDFACF;
    if(magic !== 0xFEEDFACE && !is64) throw new Error(`Mach-O: magic 0x${magic.toString(16)}`);
    const result = {
        is64, cputype: view.getUint32(4, true), cpusubtype: view.getUint32(8, true), filetype: view.getUint32(12, true),
        flags: view.getUint32(24, true), segments: [], dylibs: [], entry: null, thread: null, symtab: null, uuid: null, id: null,
        min_ios: null,
    };
    const count = view.getUint32(16, true);
    let at = is64 ? 32 : 28;
    for(let i = 0; i < count; i++)
    {
        const cmd = view.getUint32(at, true), size = view.getUint32(at + 4, true);
        if(size < 8 || at + size > bytes.length) throw new Error(`Mach-O: load command ${i} is broken`);
        if(cmd === LC_SEGMENT || cmd === LC_SEGMENT_64)
        {
            const w = cmd === LC_SEGMENT_64 ? 8 : 4;
            const get = off => w === 8 ? Number(view.getBigUint64(off, true)) : view.getUint32(off, true);
            const segment = {
                name: fixed_string(bytes, at + 8, 16), vmaddr: get(at + 24), vmsize: get(at + 24 + w),
                fileoff: get(at + 24 + 2 * w), filesize: get(at + 24 + 3 * w),
                maxprot: view.getUint32(at + 24 + 4 * w, true), initprot: view.getUint32(at + 28 + 4 * w, true),
                flags: view.getUint32(at + 36 + 4 * w, true), sections: [],
            };
            const nsects = view.getUint32(at + 32 + 4 * w, true);
            for(let s = 0, p = at + 40 + 4 * w; s < nsects; s++, p += w === 8 ? 80 : 68)
            {
                segment.sections.push({
                    name: fixed_string(bytes, p, 16), segment: fixed_string(bytes, p + 16, 16),
                    addr: get(p + 32), size: get(p + 32 + w), offset: view.getUint32(p + 32 + 2 * w, true),
                    align: view.getUint32(p + 36 + 2 * w, true), flags: view.getUint32(p + 48 + 2 * w, true),
                });
            }
            result.segments.push(segment);
        }
        else if(cmd === LC_SYMTAB)
        {
            result.symtab = { symoff: view.getUint32(at + 8, true), nsyms: view.getUint32(at + 12, true),
                stroff: view.getUint32(at + 16, true), strsize: view.getUint32(at + 20, true) };
        }
        else if(cmd === LC_UNIXTHREAD)
        {
            const flavor = view.getUint32(at + 8, true), words = view.getUint32(at + 12, true);
            const state = Array.from({ length: words }, (_, k) => view.getUint32(at + 16 + 4 * k, true));
            result.thread = { flavor, state };
            // (ARM_THREAD_STATE: r0–r12, sp, lr, pc, cpsr)
            if(result.cputype === CPU_TYPE_ARM && flavor === 1) result.entry = state[15];
        }
        else if(cmd === LC_UUID)
        {
            result.uuid = Array.from(bytes.subarray(at + 8, at + 24), x => x.toString(16).padStart(2, "0")).join("");
        }
        else if(cmd === LC_LOAD_DYLIB || cmd === LC_LOAD_WEAK_DYLIB || cmd === LC_REEXPORT_DYLIB || cmd === LC_ID_DYLIB)
        {
            const name = c_string(bytes, at + view.getUint32(at + 8, true));
            if(cmd === LC_ID_DYLIB) result.id = name;
            else result.dylibs.push(name);
        }
        else if(cmd === LC_VERSION_MIN_IPHONEOS)
        {
            const v = view.getUint32(at + 8, true);
            result.min_ios = `${v >>> 16}.${v >> 8 & 0xFF}.${v & 0xFF}`;
        }
        at += size;
    }
    return result;
}

/**
 * The symbol table's entries (file offsets as given: for a binary on its
 * own, offsets in it)
 * @param {!Uint8Array} bytes
 * @param {Object} parsed macho_parse's
 * @return {!Array<{name: string, value: number, type: number, sect: number, desc: number}>}
 */
export function macho_symbols(bytes, parsed)
{
    const t = parsed.symtab;
    if(!t) return [];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const size = parsed.is64 ? 16 : 12, out = [];
    for(let i = 0; i < t.nsyms; i++)
    {
        const at = t.symoff + i * size;
        const strx = view.getUint32(at, true);
        out.push({
            name: strx ? c_string(bytes, t.stroff + strx) : "", type: bytes[at + 4], sect: bytes[at + 5], desc: view.getUint16(at + 6, true),
            value: parsed.is64 ? Number(view.getBigUint64(at + 8, true)) : view.getUint32(at + 8, true),
        });
    }
    return out;
}

/**
 * A section's bytes, by segment and section name
 * @param {!Uint8Array} bytes
 * @param {Object} parsed
 * @param {string} segment
 * @param {string} section
 * @return {?Uint8Array}
 */
export function macho_section(bytes, parsed, segment, section)
{
    for(const s of parsed.segments)
    {
        if(s.name !== segment) continue;
        const sect = s.sections.find(x => x.name === section);
        if(sect) return bytes.subarray(sect.offset, sect.offset + sect.size);
    }
    return null;
}

/**
 * The file offset of a virtual address (in a segment's file-backed part)
 * @param {Object} parsed
 * @param {number} address
 * @return {number} -1 when none
 */
export function macho_offset(parsed, address)
{
    for(const s of parsed.segments)
    {
        if(address >= s.vmaddr && address < s.vmaddr + s.filesize) return s.fileoff + (address - s.vmaddr);
    }
    return -1;
}
                                                                                                                                      source/v64/src/arm/backdoor_a32.js                                                                  0000644 0000000 0000000 00000015641 00000000000 014030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GLES backdoor device of arm32 user code (docs/gles-proxy-plan.md
// "iOS 传输", E6; the core's side: src/rust/aarch64/backdoor.rs): a process
// without a driver reaches the GLES host's services ("opengles",
// "GLProcessPipe", as Android's goldfish pipe does) with UDF #0x8664.
//
// A call: r0 = 0x8664 << 16 | command, r1 a user address, r2 a length,
// r3 a connection; the answer in r0:
//   PROBE    the backdoor's version (1)
//   OPEN     r1, r2 the service's name: a connection (1 up)
//   WRITE    r3's service gets r2 bytes at r1: r2
//   READ     at most r2 of r3's bytes for the guest into r1: how many;
//            AGAIN when it has none yet (the guest library polls, yielding)
//   POLL     whether r3 has bytes for the guest: 1 or 0
//   CLOSE    r3 closed: 0
// Errors: FAULT (a page of the buffer is not mapped for the access: the
// library touches its pages and calls again; nothing happened), AGAIN,
// INVALID (a command, connection or service this does not know), CLOSED.
//
// Buffers are translated page by page through the calling core's tables
// (env.a32_backdoor_translate) and read or written in guest memory; a call
// checks every page before it does anything. The guest's library writes a
// connection's commands as the pipe's clients do (a u32 of flags, then the
// commands) and reads the replies it waits for: the services cannot tell the
// two transports apart.
//
// A snapshot keeps each connection with its service's state, as the pipe's
// channels (src/virt/goldfish.js).

/** r0's top half for a call */
export const BACKDOOR_CALL = 0x8664;
export const BACKDOOR_VERSION = 1;
export const BACKDOOR = { PROBE: 0, OPEN: 1, WRITE: 2, READ: 3, POLL: 4, CLOSE: 5 };
export const BACKDOOR_ERROR = { FAULT: -1, AGAIN: -2, INVALID: -3, CLOSED: -4 };
/** The core's "not a call": the UDF is the undefined instruction it was (src/rust/aarch64/backdoor.rs) */
export const BACKDOOR_NOT_HANDLED = -0x80000000;

/** A service name or a single call's buffer at most this long (a 4096 by 4096 RGBA texture, with room) */
const MAX_BUFFER = 80 << 20;

/**
 * @constructor
 * @param {?} cpu the ARM CPU: read_blob_physical, write_blob_physical, and
 *     its core's translate(va, write) (a physical address, or -1)
 * @param {function(string, function(), *=): ?Object} services a name (and
 *     at a restore the service's state) to its service, or null
 */
export function BackdoorA32(cpu, services)
{
    this.cpu = cpu;
    this.services = services;
    /** @type {!Map<number, {name: string, service: !Object}>} */
    this.connections = new Map();
    this.next = 1;
    this.calls = 0;
}

BackdoorA32.prototype.reset = function()
{
    for(const conn of this.connections.values()) conn.service.close();
    this.connections.clear();
    this.next = 1;
};

/**
 * The physical ranges of a user buffer, page by page, or null at a fault
 * @param {number} address
 * @param {number} length
 * @param {boolean} write
 * @return {?Array<!Array<number>>} [physical address, bytes]
 */
BackdoorA32.prototype.ranges = function(address, length, write)
{
    const ranges = [];
    for(let at = address >>> 0, end = (address >>> 0) + length; at < end;)
    {
        const n = Math.min(end - at, 0x1000 - (at & 0xFFF));
        const physical = this.cpu.translate_user(at, write);
        if(physical < 0) return null;
        const last = ranges[ranges.length - 1];
        if(last && last[0] + last[1] === physical) last[1] += n;
        else ranges.push([physical, n]);
        at += n;
    }
    return ranges;
};

/** @return {?Uint8Array} the user buffer's bytes, or null at a fault */
BackdoorA32.prototype.read_user = function(address, length)
{
    const ranges = this.ranges(address, length, false);
    if(!ranges) return null;
    if(ranges.length === 1) return this.cpu.read_blob_physical(ranges[0][0], ranges[0][1]).slice();
    const bytes = new Uint8Array(length);
    let at = 0;
    for(const [physical, n] of ranges)
    {
        bytes.set(this.cpu.read_blob_physical(physical, n), at);
        at += n;
    }
    return bytes;
};

/**
 * r0 to r3 of a call: the answer for r0
 * @return {number}
 */
BackdoorA32.prototype.call = function(r0, r1, r2, r3)
{
    this.calls++;
    const command = r0 & 0xFFFF, address = r1 >>> 0, length = r2 >>> 0;
    if(length > MAX_BUFFER) return BACKDOOR_ERROR.INVALID;
    if(command === BACKDOOR.PROBE) return BACKDOOR_VERSION;
    if(command === BACKDOOR.OPEN)
    {
        if(length === 0 || length > 256) return BACKDOOR_ERROR.INVALID;
        const bytes = this.read_user(address, length);
        if(!bytes) return BACKDOOR_ERROR.FAULT;
        const end = bytes.indexOf(0);
        const name = new TextDecoder().decode(end < 0 ? bytes : bytes.subarray(0, end));
        const id = this.next;
        const service = this.services(name, () => {});
        if(!service) return BACKDOOR_ERROR.INVALID;
        this.next = this.next % 0x7FFFFFFF + 1;
        this.connections.set(id, { name, service });
        return id;
    }
    const conn = this.connections.get(r3 >>> 0);
    if(!conn) return BACKDOOR_ERROR.INVALID;
    switch(command)
    {
        case BACKDOOR.WRITE:
        {
            const bytes = this.read_user(address, length);
            if(!bytes) return BACKDOOR_ERROR.FAULT;
            conn.service.write(bytes);
            return length;
        }
        case BACKDOOR.READ:
        {
            if(!conn.service.available()) return BACKDOOR_ERROR.AGAIN;
            // (every page writable first: a fault takes nothing from the service)
            const ranges = this.ranges(address, length, true);
            if(!ranges) return BACKDOOR_ERROR.FAULT;
            const bytes = conn.service.read(length);
            if(!bytes || !bytes.length) return BACKDOOR_ERROR.AGAIN;
            let at = 0;
            for(const [physical, n] of ranges)
            {
                if(at >= bytes.length) break;
                const part = bytes.subarray(at, at + n);
                this.cpu.write_blob_physical(part, physical);
                at += part.length;
            }
            return bytes.length;
        }
        case BACKDOOR.POLL: return conn.service.available() ? 1 : 0;
        case BACKDOOR.CLOSE:
            conn.service.close();
            this.connections.delete(r3 >>> 0);
            return 0;
    }
    return BACKDOOR_ERROR.INVALID;
};

/** A snapshot's: the next connection, each connection with its service's state */
BackdoorA32.prototype.get_state = function()
{
    return [this.next, [...this.connections].map(([id, conn]) => [id, conn.name, conn.service.get_state ? conn.service.get_state() : null])];
};

BackdoorA32.prototype.set_state = function(state)
{
    this.reset();
    this.next = state[0];
    for(const [id, name, saved] of state[1])
    {
        // (a service that keeps no state: its connection is gone, the guest's calls get INVALID)
        const service = saved === null ? null : this.services(name, () => {}, saved);
        if(service) this.connections.set(id, { name, service });
    }
};
                                                                                               source/v64/src/arm/cpu.js                                                                           0000644 0000000 0000000 00000201040 00000000000 012354  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The arm64 CPU of the virt machine (docs/arm64-virt-android16-plan.md P1.2):
// the JavaScript side of the ARM core (build/v86-arm64.wasm), with the
// interface src/main.js, src/browser/starter.js and src/state.js use of a CPU
// (init, run_cores, the clock, devices, snapshots, guest memory). Cores in
// vCPU workers (parallel) come with P8.2; until then the parallel members are
// empty. The x86 CPU is src/cpu.js.

import { dbg_assert, dbg_log } from "../log.js";
import { LOG_CPU, WASM_TABLE_OFFSET } from "../const.js";
import { set_jit_switches } from "../jit_switches.js";
import { relaxed_fma_fused } from "../cpu.js";
import { view, Bitmap } from "../lib.js";
import { v86 } from "../main.js";
import { MachineClock } from "../machine_clock.js";
import { check_machine_options } from "../machine_options.js";
import { CORE_STATE_RANGES, STATE_OFFSETS } from "./state_layout.js";
import { VirtDeviceSpace } from "../virt/io.js";
import {
    A64_PROFILES, ARM32_PROFILES, VIRT_LAYOUT_VERSION, VIRT_MMIO, VIRT_MMIO_COUNT, VIRT_MMIO_SIZE, VIRT_PCIE_ECAM_HIGH, VIRT_PCIE_ECAM_SIZE,
    VIRT_PCIE_MMIO, VIRT_PCIE_MMIO_HIGH, VIRT_PCIE_MMIO_HIGH_SIZE, VIRT_PCIE_MMIO_SIZE, VIRT_RAM_BASE, virt_machine,
    VIRT_EXTENDED_RAM_BASE, VIRT_EXTENDED_RAM_END,
} from "../virt/platform.js";
import { PCI } from "../pci.js";
import { ExtendedStore } from "../extended_memory.js";
import { PL011 } from "../virt/pl011.js";
import { PL031 } from "../virt/pl031.js";
import { GoldfishFb, GoldfishEvents, GoldfishBattery, GoldfishAudio, GoldfishPipe } from "../virt/goldfish.js";
import { BackdoorA32, BACKDOOR_NOT_HANDLED } from "./backdoor_a32.js";
import {
    RANCHU_DISPLAY, RANCHU_GOLDFISH_AUDIO, RANCHU_GOLDFISH_BATTERY, RANCHU_GOLDFISH_EVENTS, RANCHU_GOLDFISH_FB, RANCHU_GOLDFISH_PIPE,
    RANCHU_LAYOUT_VERSION, RANCHU_RTC, RANCHU_SPI, ranchu_framebuffer,
} from "../virt/ranchu.js";
import { load_linux } from "../virt/loader.js";
import { VirtioMmio } from "../virtio_mmio.js";
import { VirtioBlk } from "../virtio_blk.js";
import { drop_disk_holds } from "../block_backend.js";
import { VirtioRng } from "../virtio_rng.js";
import { VirtioNet } from "../virtio_net.js";
import { VirtioConsole } from "../virtio_console.js";
import { VirtioInput } from "../virtio_input.js";
import { VirtioVsock } from "../virtio_vsock.js";
import { VirtioSnd } from "../virtio_snd.js";
import { DisplayHub } from "../display.js";
import { GraphicsAdapter, graphics_adapter_of_state } from "../graphics_adapter.js";
import { GLES_PLUGINS, PluginDevice, plugin_of_state } from "../device_plugin.js";
import { ParallelMachine } from "../parallel/machine.js";
import { COMMAND_RELOAD, COMMAND_RESET } from "../parallel/control.js";

/** The devices in a snapshot's state[4], in this order */
const DEVICE_ORDER = ["pl011", "pl031", "goldfish_fb", "goldfish_events", "goldfish_battery", "goldfish_audio", "goldfish_pipe"];

/** (src/state.js: one buffer holds at most 2 GiB) */
const STATE_MAX_SINGLE_BUFFER = 0x7FFFFFFF;

/**
 * Device memory after RAM, with a display adapter (virtio-gpu's host
 * visible memory, P7.1: 128 MiB, Venus's; more when the adapter's level
 * asks for it, its descriptor's device_memory_size: gfxstream's 256 MiB)
 */
const DEVICE_MEMORY_SIZE = 128 << 20;
/** Device memory regions start at multiples of this (src/rust/aarch64/bus.rs, a64_device_take_dirty) */
const DEVICE_MEMORY_ALIGN = 256 << 10;

/**
 * @constructor
 * @param {Object} bus
 * @param {Object} wm the ARM core: {exports, wasm_table}
 * @param {function()} stop_idling
 */
export function A64CPU(bus, wm, stop_idling)
{
    dbg_assert(wm.exports["isa_aarch64"], "A64CPU needs the ARM core (v86-arm64.wasm)");
    this.stop_idling = stop_idling;
    this.wm = wm;
    this.bus = bus;
    this.clock = new MachineClock({ now: v86.microtick });
    this.in_cpu = false;
    this.cpu_type = "arm64";
    this.machine_type = "virt";

    const memory = this.wm.exports.memory;
    this.wasm_memory = memory;
    const state_base = this.state_base = this.wm.exports["state_base"]() >>> 0;
    this.instruction_counter = view(Uint32Array, memory, state_base + STATE_OFFSETS.instruction_counter, 1);

    /** cores in vCPU workers: P8.2 */
    this.parallel = null;
    this.parallel_fallback = "";
    // extended RAM (configure_extended_memory)
    this.extended_pages = 0;
    this.extended_base = 0;
    /** @type {ExtendedStore} */
    this.extended_store = null;

    // (src/state.js reads memory_size[0])
    this.memory_size = new Uint32Array(1);
    this.mem8 = new Uint8Array(0);
    this.cores = 1;

    /** @type {!Object} */
    this.devices = {};
    /** @type {?VirtioSnd} the sound device (virtio_sound), its timer the machine's */
    this.virtio_sound = null;
    // (src/main.js: a snapshot waits while host I/O a device started is in
    // flight, the virtio disks' reads and writes; src/state_io.js counts it)
    this["snapshot_io_pending"] = 0;
    /** the device registers (src/virt/io.js) */
    this.io = new VirtDeviceSpace(this.wm.exports);
    /** (the A64 page tier, docs/jit-unification-plan.md J2) publications of an older machine are dropped */
    this.execution_epoch = 0;
    this.ir_sync_publication = false;
    this.create_jit_imports();
}

/** What generated page functions import (module "e"): the core's exports, its memory and, with tail calls, its table */
A64CPU.prototype.create_jit_imports = function()
{
    const jit_imports = Object.create(null);
    jit_imports["m"] = this.wm.exports["memory"];
    for(const name of Object.keys(this.wm.exports))
    {
        if(name.startsWith("_") || name.startsWith("zstd") || name.endsWith("_js")) continue;
        jit_imports[name] = this.wm.exports[name];
    }
    const table = this.wm.wasm_table;
    if(table && this.wm.exports["a64_page_set_chaining"])
    {
        // (module (func (return_call 0)))
        const probe = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4, 0, 18, 0, 11]);
        const supported = WebAssembly.validate(probe);
        if(supported) jit_imports["t"] = table;
        this.wm.exports["a64_page_set_chaining"](supported ? 1 : 0);
    }
    // (the multiply-adds through relaxed SIMD where they fuse: a64_relaxed_fma)
    this.wm.exports["a64_page_set_relaxed_fma_fused"]?.(relaxed_fma_fused() ? 1 : 0);
    this.jit_imports = jit_imports;
};

/**
 * (env.jit_publish, jitrt::publish) the module of a page function: instantiated
 * (at once with ir_sync_publication), then its table slot set if the core still wants it
 */
A64CPU.prototype.jit_publish = function(client, id, slot, pointer, length)
{
    const wasm = this.wm, exports = wasm.exports, table = wasm.wasm_table;
    const epoch = this.execution_epoch;
    const code = new Uint8Array(exports["memory"].buffer, pointer >>> 0, length >>> 0).slice();
    const current = () => this.execution_epoch === epoch && this.wm === wasm;
    const cancel = () => exports["jit_cancel"](client, id, slot);
    const set = instance => {
        if(!current()) return false;
        const f = instance.exports["f"];
        if(typeof f !== "function" || !exports["jit_install"](client, id, slot))
        {
            cancel();
            return false;
        }
        table.set(slot + WASM_TABLE_OFFSET, f);
        exports["jit_ready"](client, id, slot);
        return true;
    };
    if(this.ir_sync_publication)
    {
        try
        {
            return Promise.resolve(set(new WebAssembly.Instance(new WebAssembly.Module(code), { "e": this.jit_imports })));
        }
        catch(error)
        {
            if(error instanceof WebAssembly.CompileError || error instanceof WebAssembly.LinkError)
            {
                dbg_log("page function rejected: " + error, LOG_CPU);
                if(current()) cancel();
                return Promise.resolve(false);
            }
            this.ir_sync_publication = false;
        }
    }
    return WebAssembly.instantiate(code, { "e": this.jit_imports }).then(result => set(result.instance), error => {
        dbg_log("page function rejected: " + error, LOG_CPU);
        if(current()) cancel();
        return false;
    });
};

/** (env.jit_clear_func) a slot of a retired function */
A64CPU.prototype.jit_clear_func = function(index)
{
    this.wm.wasm_table.set(index + WASM_TABLE_OFFSET, null);
};

/** The shared imports the ARM core needs besides those of src/browser/starter.js */
A64CPU.prototype.imports = function()
{
    return {
        "a64_mmio_read": (owner, offset, width) => this.io.mmio_read(owner, offset, width),
        "a64_mmio_write": (owner, offset, width, value) => this.io.mmio_write(owner, offset, width, value),
        "a32_backdoor": (r0, r1, r2, r3) => this.backdoor_call(r0, r1, r2, r3),
    };
};

/**
 * (env.a32_backdoor) A GLES backdoor call of user code (src/arm/backdoor_a32.js):
 * r0's answer, or BACKDOOR_NOT_HANDLED without the backdoor
 * @return {number}
 */
A64CPU.prototype.backdoor_call = function(r0, r1, r2, r3)
{
    return this.devices.backdoor ? this.devices.backdoor.call(r0 >>> 0, r1 >>> 0, r2 >>> 0, r3 >>> 0) : BACKDOOR_NOT_HANDLED;
};

/**
 * The physical address of a user address for a read or a write, as the
 * running core translates it; -1: not mapped for that access
 * @param {number} address
 * @param {boolean} write
 * @return {number}
 */
A64CPU.prototype.translate_user = function(address, write)
{
    return this.wm.exports["a32_backdoor_translate"](address >>> 0, write);
};

A64CPU.prototype.init = function(settings, device_bus)
{
    const { machine_type, cpu_profile } = check_machine_options(settings);
    if(machine_type !== "virt" && machine_type !== "ranchu")
    {
        throw new Error("The ARM CPU runs machine_type \"virt\" or \"ranchu\"");
    }
    /** "virt", or "ranchu": the Android emulator's board (src/virt/ranchu.js) */
    this.machine_type = machine_type;
    const ranchu = machine_type === "ranchu";
    const { cores, memory_size } = virt_machine(settings);
    this.cores = cores;
    // (cpu_type "arm32": AArch32 throughout, docs/aarch32-plan.md part 2)
    this.cpu_type = settings["cpu_type"] === "arm32" ? "arm32" : "arm64";
    // the CPU model's profile (cpu_profile; docs/arm64-virt-android16-plan.md,
    // "CPU profile"): generic-arm64 is v2 (v1.1 and FEAT_PAN, the default
    // since 2026-10-20), -v1.1 the 4, 16 and 64 KiB granules (P8.6), -v1
    // 4 KiB only, -compat32 v3 (AArch32 at EL0); arm32's own
    this.set_profile((this.cpu_type === "arm32" ? ARM32_PROFILES : A64_PROFILES)[cpu_profile][0]);
    // the A64 page tier (J2): synchronous publication (tests), the JIT switches by name
    this.ir_sync_publication = settings["ir_sync_publication"] === true;
    set_jit_switches(this.wm.exports, this.wasm_memory, settings["jit_switches"]);
    // (the GIC's distributor and redistributors: decoded in the core, P4.2;
    // ranchu's with a 32-bit kernel a GICv2's distributor and CPU interface)
    /** whether the GIC is a GICv2 (ranchu with a 32-bit kernel) */
    this.gic_v2 = ranchu && this.cpu_type === "arm32";
    this.wm.exports["a64_gic_set_version"]?.(this.gic_v2 ? 2 : 3);
    if(!this.wm.exports["a64_set_cores"](cores)) throw new Error("the GIC's frames overlap a device");
    if(settings.cpu_clock) this.clock = new MachineClock(Object.assign({ now: v86.microtick }, settings.cpu_clock));
    // The display adapter's plugin descriptor (P7.1: virtio-gpu without VGA); none with graphics_adapter: "none"
    this.graphics_adapter_descriptor = settings.graphics_adapter;
    const adapter = this.graphics_adapter_descriptor;
    this.create_memory(memory_size, adapter ? Math.max(DEVICE_MEMORY_SIZE,
        adapter["device_memory_size"]?.({ "test": settings.graphics_adapter_test }) || 0) : 0);
    this.configure_extended_memory(settings.extended_memory_size || 0, settings.extended_memory_cache);
    this.device_bus = device_bus;
    this.devices = {
        "pl011": new PL011(this, device_bus),
        "pl031": ranchu ? new PL031(this, RANCHU_RTC, 32 + RANCHU_SPI.rtc) : new PL031(this),
    };
    // The generic PCIe host bridge (P5.6, P5.10): its configuration through
    // the high ECAM, the BARs in its 32- and 64-bit windows (where no BAR
    // is, reads are all ones, as on the reference); INTx are SPIs that the
    // functions share (set_shared_gsi_level)
    /** @type {!Map<number, !Set<number>>} the functions asserting each shared SPI, by INTID */
    this.shared_spi_sources = new Map();
    // (ranchu: no PCIe host)
    /** @type {!Array<{base: number, size: number, owners: !Array<number>}>} */
    this.pcie_windows = [];
    if(!ranchu)
    {
        const pci = new PCI(/** @type {?} */ (this), { generic: true });
        this.devices["pci"] = pci;
        this.io.register_mmio(VIRT_PCIE_ECAM_HIGH, VIRT_PCIE_ECAM_SIZE, pci.ecam_handler());
        // (the windows: around device memory mapped into them, update_windows)
        this.pcie_windows = [
            { base: VIRT_PCIE_MMIO, size: VIRT_PCIE_MMIO_SIZE, owners: [] },
            { base: VIRT_PCIE_MMIO_HIGH[1] * 0x100000000 + VIRT_PCIE_MMIO_HIGH[0], size: VIRT_PCIE_MMIO_HIGH_SIZE, owners: [] },
        ];
        this.update_windows();
    }
    // The virtio-mmio slots (P5.3): a slot without a device reads as the
    // reference's empty one ("virt", version 2, device ID 0, "QEMU"), which
    // Linux skips; devices take the slots from the last one down, in the
    // order of the reference's -device options: the disks, then net, rng,
    // console (tests/a64/linux_boot.mjs)
    /** @type {!Array<VirtioMmio>} by slot */
    this.virtio_mmio = new Array(VIRT_MMIO_COUNT).fill(null);
    /** @type {!Array<number>} the slots' owners (src/virt/io.js) */
    this.virtio_mmio_slots = [];
    for(let n = 0; n < VIRT_MMIO_COUNT; n++)
    {
        const slot = n;
        this.virtio_mmio_slots.push(this.io.register_mmio(VIRT_MMIO + n * VIRT_MMIO_SIZE, VIRT_MMIO_SIZE, {
            name: "virtio-mmio",
            read: (offset, width) => this.virtio_mmio[slot] ? this.virtio_mmio[slot].read(offset, width) :
                width === 4 ? [0x74726976, ranchu ? 1 : 2, 0, 0x554D4551][offset >> 2] ?? 0 : 0,
            write: (offset, width, value) => { this.virtio_mmio[slot]?.write(offset, width, value); },
        }));
    }
    // The virtio devices' transport (P5.7): virtio-mmio, or virtio-pci on the
    // PCIe host, where they take slot 1 on (00:01.0, 00:02.0, ...) in the same
    // order, as the reference's -device virtio-*-pci options do
    /** @type {string} */
    this.virtio_transport = settings.virtio_transport || "mmio";
    /** @type {!Array<{slot: number, name: string, device: !Object}>} in order: from the last virtio-mmio slot, or from PCI slot 1 */
    this.virtio_devices = [];
    // (on the PCIe host the display adapter may take a slot of its own, which
    // the others skip: Cuttlefish's sepolicy expects its GPU at 00:02.0, P10.7)
    const gpu_slot = this.virtio_transport === "pci" && this.graphics_adapter_descriptor && settings.virtio_gpu_pci_slot || 0;
    const pci_slot = n => 1 + n + (gpu_slot && 1 + n >= gpu_slot ? 1 : 0);
    const add = (name, create) =>
    {
        let device, slot;
        if(this.virtio_transport === "pci")
        {
            slot = pci_slot(this.virtio_devices.length);
            device = create(null, slot << 3);
        }
        else
        {
            slot = VIRT_MMIO_COUNT - 1 - this.virtio_devices.length;
            // (SPI 16 + slot, as the reference's)
            const transport = new VirtioMmio(this, slot, 32 + 16 + slot, ranchu);
            this.virtio_mmio[slot] = transport;
            device = create(transport, undefined);
        }
        this.virtio_devices.push({ slot, name, device });
        return device;
    };
    // (hda and hdb, given instead, are the first two; the disks' names, as
    // export_disk_image takes them: virtio_disk<n>, or hda and hdb)
    const disks = settings.virtio_disks && settings.virtio_disks.length ?
        settings.virtio_disks.map((disk, i) => ({ buffer: disk.buffer, id: disk.id, readonly: disk.readonly, name: "virtio_disk" + i })) :
        [["hda", settings.hda], ["hdb", settings.hdb]].filter(([, buffer]) => buffer)
            .map(([name, buffer]) => ({ buffer, id: undefined, readonly: false, name }));
    for(const disk of disks)
    {
        add("virtio-blk", (transport, pci_id) => new VirtioBlk(this, disk.buffer, disk, transport, pci_id));
    }
    if(settings.net_device && settings.net_device.type === "virtio")
    {
        // (the PC's devices take a CPU: what they use of it, the ARM CPU has)
        // (net_device.count: that many functions, net0, net1, ... on the bus:
        // Android's three, as Cuttlefish's, P11.2; the relay takes net_device.id's)
        for(let id = 0; id < (settings.net_device.count || 1); id++)
        {
            add("virtio-net", (transport, pci_id) => new VirtioNet(/** @type {?} */ (this), device_bus, settings.preserve_mac_from_state_image,
                settings.net_device.mtu, pci_id, transport || undefined, id));
        }
    }
    if(settings.virtio_rng) add("virtio-rng", (transport, pci_id) => new VirtioRng(this, transport, pci_id));
    if(settings.virtio_console)
    {
        // (ports 1-3 generic: the host service channels, P9.1; or
        // virtio_console_ports consoles, P10.7)
        const ports = settings.virtio_console_ports;
        add("virtio-console", (transport, pci_id) => new VirtioConsole(/** @type {?} */ (this), device_bus, pci_id, transport || undefined,
            !ports, ports || undefined));
    }
    // (P5.8, P7.4: a keyboard and a tablet, or the kinds listed, as the
    // reference's virtio-keyboard, virtio-tablet and virtio-multitouch)
    if(settings.virtio_input)
    {
        const kinds = Array.isArray(settings.virtio_input) ? settings.virtio_input : ["keyboard", "tablet"];
        // (a touch screen without a tablet beside it takes the mouse as a finger: Android's preset has no tablet)
        const mouse_as_touch = !kinds.includes("tablet");
        for(const kind of kinds)
        {
            add("virtio-" + kind, (transport, pci_id) => new VirtioInput(this, device_bus, kind, transport, pci_id, mouse_as_touch));
        }
    }
    // (P10.7: stream sockets to the guest, its adbd's vsock:5555)
    if(settings.virtio_vsock) add("virtio-vsock", (transport, pci_id) => new VirtioVsock(this, device_bus, transport, pci_id));
    // (P7.5, P12.5: sound, one output stream, played on the machine's clock)
    this.virtio_sound = settings.virtio_sound ? add("virtio-snd", (transport, pci_id) => new VirtioSnd(this, device_bus, transport, pci_id)) : null;
    // The display adapter (P7.1): virtio-gpu without VGA, after the virtio
    // devices (the next PCI slot, or virtio-mmio slot), on the display hub
    if(this.graphics_adapter_descriptor)
    {
        this.devices.display = new DisplayHub(device_bus, settings.screen);
        const slot = this.virtio_transport === "pci" ? gpu_slot || pci_slot(this.virtio_devices.length) :
            VIRT_MMIO_COUNT - 1 - this.virtio_devices.length;
        const transport = this.virtio_transport === "pci" ? null : new VirtioMmio(this, slot, 32 + 16 + slot, ranchu);
        if(transport) this.virtio_mmio[slot] = transport;
        this.graphics_adapter_slot = slot;
        this.devices.graphics_adapter = new GraphicsAdapter(/** @type {?} */ (this), this.graphics_adapter_descriptor, {
            vram_size: settings.vram_size, test: settings.graphics_adapter_test, renderer: settings.graphics_adapter_renderer,
            pci_id: transport ? undefined : slot << 3, transport,
        });
        if(transport)
        {
            // (on virtio-mmio its memory has no BAR: at the top of the 64-bit
            // window, which nothing else uses then; the SHM registers say where)
            const virtio = this.devices.graphics_adapter.pci_device;
            const window = this.pcie_windows[1];
            let top = window.base + window.size;
            const bases = [];
            virtio.pci_bars.forEach((bar, i) => {
                if(!bar || !bar.on_move) return;
                top = Math.floor((top - bar.size) / bar.size) * bar.size;
                bases[i] = top;
                bar.on_move(top);
            });
            for(const region of transport.shared_memory_regions())
            {
                transport.set_shared_memory_base(region.id, bases[region.bar] + region.offset);
            }
        }
    }
    // The ranchu machine's goldfish devices (src/virt/goldfish.js): the
    // framebuffer on a display hub of its own, the events, the battery, the
    // audio output and the pipe with the boot properties, and with
    // ranchu_gpu "host" the GLES host's services (src/gles/plugin.js)
    if(ranchu)
    {
        this.devices.display = new DisplayHub(device_bus, settings.screen);
        const display = /** @type {{width: number, height: number, dpi: number}} */ (Object.assign({}, RANCHU_DISPLAY, settings.ranchu_display));
        // (arm32: a simple-framebuffer, src/virt/goldfish.js)
        /** @type {?{base: number, size: number, width: number, height: number}} */
        this.ranchu_framebuffer = this.cpu_type === "arm32" ? ranchu_framebuffer(memory_size, display) : null;
        this.devices["goldfish_fb"] = new GoldfishFb(this, RANCHU_GOLDFISH_FB, 32 + RANCHU_SPI.fb, display,
            this.ranchu_framebuffer ? this.ranchu_framebuffer.base : 0);
        this.devices["goldfish_events"] = new GoldfishEvents(this, device_bus, RANCHU_GOLDFISH_EVENTS, 32 + RANCHU_SPI.events);
        this.devices["goldfish_battery"] = new GoldfishBattery(this, RANCHU_GOLDFISH_BATTERY);
        this.devices["goldfish_audio"] = new GoldfishAudio(this, RANCHU_GOLDFISH_AUDIO, 32 + RANCHU_SPI.audio);
        if(settings.gles_plugin)
        {
            this.devices.gles = new PluginDevice(/** @type {?} */ (this), GLES_PLUGINS, settings.gles_plugin, -1, {}, {
                "display": { "width": display.width, "height": display.height, "dpi": display.dpi },
                // (the page's renderer: graphics_adapter is "none" on ranchu, so the channel is the GLES host's)
                "renderer": settings.graphics_adapter_renderer || null,
                // (the posted frames the page read back: the framebuffer device shows them)
                "present": (rgba, width, height) => this.devices["goldfish_fb"].present(rgba, width, height),
                // (its plugin's prepare: glslang, docs/gles3-plan.md)
                "prepared": settings.gles_prepared || null,
                "max_version": settings.ranchu_gles_version || "2.0",
            });
        }
        const gles = this.devices.gles;
        this.devices["goldfish_pipe"] = new GoldfishPipe(this, RANCHU_GOLDFISH_PIPE, 32 + RANCHU_SPI.pipe, Object.assign({
            "qemu.sf.lcd_density": String(display.dpi), "qemu.hw.mainkeys": "0",
        }, settings.ranchu_properties), gles ? (name, wake, ...saved) => gles.device["service"](name, wake, ...saved) : undefined);
    }
    // arm32's GLES backdoor (gles_backdoor: docs/gles-proxy-plan.md "iOS 传输"):
    // the GLES host's services for user code, no screen of its own (its
    // posts are not shown; the test reads its pixels back)
    if(settings.gles_backdoor && settings.gles_plugin)
    {
        this.devices.gles = this.devices.gles || new PluginDevice(/** @type {?} */ (this), GLES_PLUGINS, settings.gles_plugin, -1, {}, {
            "display": { "width": 800, "height": 600, "dpi": 160 },
            "renderer": settings.graphics_adapter_renderer || null,
            "present": () => {},
            "prepared": settings.gles_prepared || null,
            "max_version": settings.ranchu_gles_version || "2.0",
        });
        const gles = this.devices.gles;
        this.devices.backdoor = new BackdoorA32(this, (name, wake, ...saved) => gles.device["service"](name, wake, ...saved));
    }
    // the boot core starts at the kernel (P4.6: the device tree in x0, P4.2)
    this.booted = false;
    /** @type {Object} what the machine boots, loaded again at a reset */
    this.boot_files = null;
    if(settings.kernel)
    {
        // (kept: a reset loads them again, P4.6)
        this.boot_files = { kernel: settings.kernel, initrd: settings.initrd, cmdline: settings.cmdline, dtb: settings.dtb, cores };
        const { entry, x0 } = load_linux(this, this.boot_files);
        this.boot(entry, x0);
    }
};

/**
 * Reset the cores; core 0 starts at `entry` with x0 = `x0`
 * @param {number} entry
 * @param {number} x0
 */
A64CPU.prototype.boot = function(entry, x0)
{
    if(this.cpu_type === "arm32")
    {
        // (a 32-bit kernel: SVC mode, r0 0, r1 ~0 (a device tree, not a board), r2 the device tree)
        this.wm.exports["a32_boot"](entry >>> 0, x0 >>> 0);
    }
    else
    {
        this.wm.exports["a64_boot"](entry >>> 0, Math.floor(entry / 0x100000000), x0 >>> 0, Math.floor(x0 / 0x100000000));
    }
    this.boot_entry = entry;
    this.boot_x0 = x0;
    this.booted = true;
};

/**
 * Guest RAM of `size` bytes at 0x4000_0000, and after it in guest memory
 * `device_size` bytes of device memory (mmio_ram_allocate)
 * @param {number} size
 * @param {number=} device_size
 */
A64CPU.prototype.create_memory = function(size, device_size = 0)
{
    const exports = this.wm.exports;
    // (one allocation in the 32-bit Wasm memory: below 2 GiB; more RAM is
    // docs/arm64-virt-android16-plan.md P8)
    if(size + device_size >= 0x80000000)
    {
        throw new Error("memory_size: the arm64 core takes less than 2 GiB of RAM (" + size + " bytes" +
            (device_size ? ", and " + device_size + " bytes of the display adapter's device memory" : "") + ")");
    }
    const pointer = exports["a64_allocate_memory"](size + device_size) >>> 0;
    if(!exports["a64_bus_set_ram"](size)) throw new Error("create_memory: RAM of " + size + " bytes does not fit");
    this.mem8 = view(Uint8Array, this.wasm_memory, pointer, size);
    this.memory_size[0] = size;
    /** device memory: [start, end) in guest memory's backing, and its regions */
    this.device_memory = { start: size, end: size + device_size, next: size };
    /** @type {!Array<{backing: number, size: number, base: number}>} */
    this.device_regions = [];
    if(device_size && !exports["a64_device_memory"](size)) throw new Error("create_memory: no device memory");
};

// ---- device memory (P7.1): the interface of the x86 core's mmio_ram (src/rust/cpu/mmio_ram.rs)

/**
 * A region of device memory (virtio-gpu's host visible memory)
 * @param {number} size
 * @return {number} the region, or -1
 */
A64CPU.prototype.mmio_ram_allocate = function(size)
{
    const memory = this.device_memory;
    const at = Math.ceil(memory.next / DEVICE_MEMORY_ALIGN) * DEVICE_MEMORY_ALIGN;
    size = Math.ceil(size / 4096) * 4096;
    if(!size || at + size > memory.end) return -1;
    memory.next = at + size;
    this.device_regions.push({ backing: at, size, base: -1 });
    return this.device_regions.length - 1;
};

/** @return {number} the address of the region's memory in the Wasm memory */
A64CPU.prototype.mmio_ram_backing = function(region)
{
    return this.mem8.byteOffset + this.device_regions[region].backing;
};

/**
 * Decode the region at `address` (a BAR's), when all of it is in one of the
 * PCIe host's windows; elsewhere (an unassigned BAR) nowhere
 * @param {number} region
 * @param {number} address
 */
A64CPU.prototype.mmio_ram_map = function(region, address)
{
    const r = this.device_regions[region];
    const inside = this.pcie_windows.some(w => address >= w.base && address + r.size <= w.base + w.size);
    const base = inside ? address : -1;
    if(base === r.base) return;
    if(r.base !== -1) this.wm.exports["a64_bus_unmap"](r.base >>> 0, Math.floor(r.base / 0x100000000));
    r.base = base;
    this.update_windows();
    if(base !== -1 && !this.wm.exports["a64_bus_map_device"](base >>> 0, Math.floor(base / 0x100000000), r.size >>> 0, 0, r.backing))
    {
        dbg_log("device memory at 0x" + base.toString(16) + " overlaps a region", LOG_CPU);
        r.base = -1;
        this.update_windows();
    }
};

A64CPU.prototype.mmio_ram_unmap = function(region)
{
    this.mmio_ram_map(region, -1);
};

/** @return {number} the address of the words marking the pages the cores wrote (0: none) */
A64CPU.prototype.mmio_ram_take_dirty = function(region)
{
    const r = this.device_regions[region];
    return this.wm.exports["a64_device_take_dirty"](r.backing, r.size);
};

A64CPU.prototype.mmio_ram_mark_dirty = function(region)
{
    const r = this.device_regions[region];
    this.wm.exports["a64_device_mark_dirty"](r.backing, r.size);
};

A64CPU.prototype.mmio_ram_read8 = function(region, offset)
{
    return new Uint8Array(this.wasm_memory.buffer)[this.mmio_ram_backing(region) + offset];
};

A64CPU.prototype.mmio_ram_write8 = function(region, offset, value)
{
    new Uint8Array(this.wasm_memory.buffer)[this.mmio_ram_backing(region) + offset] = value;
};

/**
 * The PCIe host's windows as ranges of the core's address space: each one
 * around the device memory mapped into it (window_handler, src/pci.js)
 */
A64CPU.prototype.update_windows = function()
{
    const pci = this.devices["pci"];
    for(const window of this.pcie_windows)
    {
        for(const owner of window.owners) this.io.unregister_mmio(owner);
        window.owners = [];
        const holes = this.device_regions.filter(r => r.base !== -1 && r.base >= window.base && r.base < window.base + window.size)
            .sort((a, b) => a.base - b.base);
        let at = window.base;
        for(const hole of [...holes, { base: window.base + window.size, size: 0 }])
        {
            if(hole.base > at) window.owners.push(this.io.register_mmio(at, hole.base - at, pci.window_handler(at)));
            at = hole.base + hole.size;
        }
    }
};

/**
 * One turn of the machine: the cores' slices and the timers. Returns the
 * milliseconds until something is due (0: run again at once).
 * @return {number}
 */
A64CPU.prototype.run_cores = function()
{
    if(this.parallel) return this.run_parallel();
    return this.run_machine_core();
};

/** One slice of the cores this instance runs (all, or with cores in workers core 0): milliseconds until it needs to run again */
A64CPU.prototype.run_machine_core = function()
{
    const run = this.wm.exports["a64_run_slice"];
    if(!run || !this.booted) return 100;
    this.in_cpu = true;
    try
    {
        const devices = this.run_hardware_timers(null, this.clock.now());
        const next = Math.min(run(this.clock.now()), devices);
        // (PSCI SYSTEM_RESET: the machine resets and boots again, P4.8)
        if(this.wm.exports["a64_take_reset_request"]()) this.reboot_internal("restart");
        return next;
    }
    finally
    {
        this.in_cpu = false;
    }
};

// ---- cores in vCPU workers (P8.2: src/parallel/machine.js, src/parallel/vcpu_arm.js)

/**
 * Cores 1 and up run in vCPU workers; this thread runs core 0 and the
 * devices, serves the workers' device accesses and stops them at safe
 * points for snapshots, resets and pauses
 * @param {{bytes: Uint8Array, settings: Object, worker_url: (string|URL)}} options
 */
A64CPU.prototype.start_parallel = async function(options)
{
    dbg_assert(this.cores > 1);
    this.parallel = new ParallelMachine(this, options);
    await this.parallel.start();
};

/** @return {number} milliseconds until the machine needs to run again */
A64CPU.prototype.run_parallel = function()
{
    const machine = this.parallel, exports = this.wm.exports;
    // (a failed vCPU stops the machine: v86.prototype.do_tick)
    if(machine.check_failure()) return 0;
    machine.service();
    if(machine.pending_reset)
    {
        machine.request_stop();
        if(!machine.all_parked()) return 0;
        const { reason } = machine.pending_reset;
        machine.pending_reset = null;
        this.reboot_internal(reason);
        return 0;
    }
    if(machine.stopping()) machine.resume();
    // (core 0 takes the other cores' code writes and TLB maintenance; while it
    // waits it counts as idle, crate::parallel::code, crate::aarch64::tlb)
    exports["parallel_idle"](false);
    const t = this.run_machine_core();
    machine.service();
    if(t > 0) exports["parallel_idle"](true);
    return t;
};

/** (src/main.js) the parked workers' cores are read where they are (save_core_state) */
A64CPU.prototype.parallel_capture = function()
{
    dbg_assert(this.parallel.all_parked());
};

/** (src/main.js) after a restore into the workers' state blocks: they drop what derived from the old state */
A64CPU.prototype.parallel_install = function()
{
    dbg_assert(this.parallel.all_parked());
    this.parallel.schedule(COMMAND_RELOAD);
};

/** The state block of core `core`: the running core's, or with cores in workers a worker's (parked) */
A64CPU.prototype.state_block_of = function(core)
{
    const base = this.parallel && core !== 0 ? this.parallel.state_base(core) : this.state_base;
    return new Uint8Array(this.wasm_memory.buffer, base, 4096);
};

/** (env.run_hardware_timers) the virt machine's device timers (the PL031's alarm, the display's); the cores' timers are their own */
A64CPU.prototype.run_hardware_timers = function(acpi, now)
{
    const display = this.devices.display ? this.devices.display.timer(now) : 100;
    const sound = this.virtio_sound ? this.virtio_sound.timer(now) : 100;
    const audio = this.devices["goldfish_audio"] ? this.devices["goldfish_audio"].timer(now) : 100;
    return Math.min(100, display, sound, audio, this.devices["pl031"] ? this.devices["pl031"].timer() : 100);
};

/**
 * A device's interrupt line, an SPI of the GIC (P4.2)
 * @param {number} intid
 * @param {boolean} level
 */
A64CPU.prototype.set_irq = function(intid, level)
{
    this.wm.exports["a64_gic_set_spi"](intid, level);
};

/**
 * A function on the PCIe host drives the SPI its INTx pin is routed to
 * (src/pci.js): the line is high while any function asserts it
 * @param {number} intid
 * @param {number} source the function's pci_id
 * @param {boolean} level
 */
A64CPU.prototype.set_shared_gsi_level = function(intid, source, level)
{
    let sources = this.shared_spi_sources.get(intid);
    if(!sources)
    {
        sources = new Set();
        this.shared_spi_sources.set(intid, sources);
    }
    if(level) sources.add(source);
    else sources.delete(source);
    this.set_irq(intid, sources.size > 0);
};

/**
 * (snapshots) a view of the machine state `which` the core keeps (0 the GIC, 1 PSCI)
 * @param {number} which
 * @return {!Uint8Array}
 */
A64CPU.prototype.machine_state_bytes = function(which)
{
    const exports = this.wm.exports;
    return new Uint8Array(this.wasm_memory.buffer, exports["a64_machine_state"](which, false) >>> 0, exports["a64_machine_state"](which, true));
};

/** Whether the guest turned the machine off (PSCI SYSTEM_OFF, P4.4) */
A64CPU.prototype.powered_off = function()
{
    return !!this.wm.exports["a64_powered_off"]?.();
};

/**
 * A reset (PSCI SYSTEM_RESET, V86.restart), or with reason "power-on" the
 * machine powered on again after SYSTEM_OFF (V86.power_button)
 * @param {string=} reason
 */
A64CPU.prototype.reboot_internal = function(reason)
{
    if(!this.booted) return;
    // (cores in workers: they stop first, run_parallel resets then, and they wait for CPU_ON again)
    if(this.parallel && !this.parallel.all_parked())
    {
        this.parallel.pending_reset = { reason };
        this.parallel.request_stop();
        return;
    }
    if(this.parallel) this.parallel.schedule(COMMAND_RESET);
    if(reason === "power-on")
    {
        // (after PSCI SYSTEM_OFF, P8.1: RAM and device memory do not keep their contents)
        this.mem8.fill(0);
        this.wm.exports["a64_bus_written"](0, this.memory_size[0]);
        new Uint8Array(this.wasm_memory.buffer, this.mem8.byteOffset + this.device_memory.start,
            this.device_memory.end - this.device_memory.start).fill(0);
        this.clear_extended_memory();
    }
    for(const device of Object.values(this.devices)) device.reset?.();
    for(const { device } of this.virtio_devices) device.reset();
    if(this.boot_files)
    {
        const { entry, x0 } = load_linux(this, this.boot_files);
        this.boot(entry, x0);
    }
    else
    {
        this.boot(this.boot_entry, this.boot_x0);
    }
};

// ---- guest memory (P1.6: the machine's DMA facade)

/** @return {boolean} whether [offset, offset + length) of guest memory is zero */
A64CPU.prototype.is_memory_zeroed = function(offset, length)
{
    dbg_assert((offset & 3) === 0 && (length & 3) === 0);
    const words = new Int32Array(this.mem8.buffer, this.mem8.byteOffset + offset, length >> 2);
    for(let i = 0; i < words.length; i++)
    {
        if(words[i] !== 0) return false;
    }
    return true;
};

A64CPU.prototype.zero_memory = function(offset, length)
{
    this.mem8.fill(0, offset, offset + length);
    this.wm.exports["a64_bus_written"](offset, length);
};

/**
 * The guest-memory offset of the physical range [address, address + length)
 * of RAM, or -1 when it is not all RAM
 * @param {number} address a physical address below 2^53
 * @param {number} length
 */
A64CPU.prototype.ram_offset = function(address, length)
{
    const offset = address - VIRT_RAM_BASE;
    return offset >= 0 && offset + length <= this.memory_size[0] ? offset : -1;
};

/** The end of the physical address space: profile v1's 40 bits */
A64CPU.prototype.physical_limit = 0x10000000000;

/** Whether the physical range [address, address + length) is all extended RAM (P8.5) */
A64CPU.prototype.is_extended = function(address, length)
{
    const offset = address - this.extended_base;
    return this.extended_pages !== 0 && offset >= 0 && offset + length <= this.extended_pages * 4096;
};

/**
 * Where a device's DMA to [address, address + length) goes (the machine's
 * DMA facade, P1.6): RAM is one contiguous backing, extended RAM is copied
 * a page at a time
 * @param {number} address
 * @param {number} length
 * @return {number} the offset in guest memory, -1 for extended RAM, or -2 when it is not all RAM
 */
A64CPU.prototype.dma_classify = function(address, length)
{
    if(!Number.isSafeInteger(address) || !Number.isSafeInteger(length) || length <= 0) return -2;
    const offset = this.ram_offset(address, length);
    return offset >= 0 ? offset : this.is_extended(address, length) ? -1 : -2;
};

/**
 * Read guest RAM at a physical address (V86.read_memory)
 * @param {number} address
 * @param {number} length
 * @return {!Uint8Array}
 */
A64CPU.prototype.read_blob_physical = function(address, length)
{
    const offset = this.ram_offset(address, length);
    if(offset >= 0) return this.mem8.slice(offset, offset + length);
    if(!this.is_extended(address, length))
    {
        throw new RangeError("read_blob_physical: [0x" + address.toString(16) + ", +" + length + ") is not RAM");
    }
    const result = new Uint8Array(length);
    for(let done = 0; done < length;)
    {
        const count = Math.min(length - done, 4096 - (address + done) % 4096);
        result.set(this.extended_page_bytes(address + done, count, false), done);
        done += count;
    }
    return result;
};

/**
 * Write guest RAM at a physical address (V86.write_memory, the loaders,
 * devices' DMA): code compiled from it retires
 * @param {!Uint8Array|!Array<number>} blob
 * @param {number} address
 */
A64CPU.prototype.write_blob_physical = function(blob, address)
{
    const offset = this.ram_offset(address, blob.length);
    if(offset >= 0)
    {
        this.mem8.set(blob, offset);
        this.wm.exports["a64_bus_written"](offset, blob.length);
        return;
    }
    if(!this.is_extended(address, blob.length))
    {
        throw new RangeError("write_blob_physical: [0x" + address.toString(16) + ", +" + blob.length + ") is not RAM");
    }
    const bytes = blob instanceof Uint8Array ? blob : new Uint8Array(blob);
    for(let done = 0; done < bytes.length;)
    {
        const count = Math.min(bytes.length - done, 4096 - (address + done) % 4096);
        this.extended_page_bytes(address + done, count, bytes.subarray(done, done + count));
        done += count;
    }
};

/**
 * Copy bytes of one page of extended RAM (DMA, debugging): its frame is
 * pinned meanwhile; a write retires code compiled from the page and clears
 * every core's reservations in it (src/rust/aarch64/extended.rs)
 * @param {number} address guest physical, in extended RAM
 * @param {number} count bytes within the page
 * @param {Uint8Array|boolean} write the bytes to write, or false to read
 * @return {!Uint8Array} the bytes read
 */
A64CPU.prototype.extended_page_bytes = function(address, count, write)
{
    const page = Math.floor((address - this.extended_base) / 4096);
    // (an i32: the frame pool may lie above 2 GiB)
    const frame = this.wm.exports["a64_ext_pin"](page, !!write) >>> 0;
    dbg_assert(frame !== 0 && address % 4096 + count <= 4096);
    const bytes = new Uint8Array(this.wasm_memory.buffer, frame + address % 4096, count);
    let result = bytes;
    if(write) bytes.set(/** @type {!Uint8Array} */ (write));
    else result = bytes.slice();
    this.wm.exports["a64_ext_unpin"](page);
    return result;
};

/** @throws {RangeError} unless [address, address + length) is all RAM (VirtQueue) */
A64CPU.prototype.validate_physical_range = function(address, length)
{
    // (RAM or extended RAM, which the facade copies a page at a time: a
    // virtqueue or a buffer above 4 GiB with 4 GiB of RAM)
    if(length && this.dma_classify(address, length) === -2)
    {
        throw new RangeError("[0x" + address.toString(16) + ", +" + length + ") is not RAM");
    }
};

/** The guest-memory offset of a scalar's RAM, -1 in extended RAM, or a RangeError (devices' DMA) */
A64CPU.prototype.scalar_offset = function(address, bytes)
{
    const offset = this.dma_classify(address, bytes);
    if(offset === -2) throw new RangeError("0x" + address.toString(16) + " is not RAM");
    return offset;
};
/** A scalar of `bytes` bytes at `address` (devices' DMA) */
A64CPU.prototype.read_scalar_physical = function(address, bytes)
{
    const o = this.scalar_offset(address, bytes);
    const b = o >= 0 ? this.mem8.subarray(o, o + bytes) : this.read_blob_physical(address, bytes);
    let value = 0;
    for(let i = 0; i < bytes; i++) value |= b[i] << 8 * i;
    return value >>> 0;
};
A64CPU.prototype.read8_physical = function(address) { return this.read_scalar_physical(address, 1); };
A64CPU.prototype.read16_physical = function(address) { return this.read_scalar_physical(address, 2); };
A64CPU.prototype.read32_physical = function(address) { return this.read_scalar_physical(address, 4); };
/** A scalar's bytes at `address`: code compiled from them retires, other cores' reservations clear */
A64CPU.prototype.write_scalar_physical = function(address, value, bytes)
{
    const o = this.scalar_offset(address, bytes);
    const b = new Uint8Array(bytes);
    for(let i = 0; i < bytes; i++) b[i] = value >>> 8 * i & 0xFF;
    if(o < 0)
    {
        this.write_blob_physical(b, address);
        return;
    }
    this.mem8.set(b, o);
    this.wm.exports["a64_bus_written"](o, bytes);
};
A64CPU.prototype.write8_physical = function(address, value) { this.write_scalar_physical(address, value, 1); };
A64CPU.prototype.write16_physical = function(address, value) { this.write_scalar_physical(address, value, 2); };
A64CPU.prototype.write32_physical = function(address, value) { this.write_scalar_physical(address, value, 4); };

// ---- extended RAM (P8.5)

/**
 * RAM beyond guest memory (extended RAM): `size` bytes at guest physical
 * 4 GiB (the device tree's second memory range), kept in an ExtendedStore
 * (src/extended_memory.js) and cached in `cache_size` bytes of frames
 * (src/rust/aarch64/extended.rs)
 * @param {number} size
 * @param {number=} cache_size
 */
A64CPU.prototype.configure_extended_memory = function(size, cache_size)
{
    this.extended_pages = 0;
    this.extended_base = 0;
    this.extended_store = null;
    if(!size) return;
    if(!Number.isSafeInteger(size) || size < 0 || size % (2 << 20))
    {
        throw new Error("extended_memory_size must be a multiple of 2 MiB");
    }
    const base = VIRT_EXTENDED_RAM_BASE;
    if(base + size > VIRT_EXTENDED_RAM_END)
    {
        throw new Error("extended_memory_size: the virt machine's RAM ends at 256 GiB (at most " + (VIRT_EXTENDED_RAM_END - base) + " bytes)");
    }
    const cache = Math.min(size, cache_size || 512 << 20);
    if(!Number.isSafeInteger(cache) || cache < 1 << 20 || cache % 4096)
    {
        throw new Error("extended_memory_cache must be a multiple of 4 KiB and at least 1 MiB");
    }
    let store;
    try
    {
        store = new ExtendedStore(size / 4096);
    }
    catch(e)
    {
        throw new Error("extended_memory_size: the host cannot allocate " + size + " bytes (" + e.message + ")");
    }
    // (before the first access: extended_load reads the store)
    this.extended_store = store;
    if(!this.wm.exports["a64_ext_configure"](base >>> 0, Math.floor(base / 0x100000000), size / 4096, cache / 4096))
    {
        this.extended_store = null;
        throw new Error("extended_memory_size: cannot allocate the frame cache");
    }
    this.extended_pages = size / 4096;
    this.extended_base = base;
};

/** Extended RAM reads as zero again (power-on, a restore); every core is stopped */
A64CPU.prototype.clear_extended_memory = function()
{
    if(!this.extended_store) return;
    this.wm.exports["a64_ext_discard"]();
    this.extended_store.clear();
    // (code compiled from it)
    this.wm.exports["jit_clear_cache_js"]();
};

/** Every dirty frame back into the store (src/state.js: a snapshot stream) */
A64CPU.prototype.flush_extended_memory = function()
{
    this.wm.exports["a64_ext_flush"]();
};

// ---- snapshots (P1.9): ["virt", VIRT_LAYOUT_VERSION, profile] in state[103]

/** The ARM core's state block of the current core, its per-core ranges */
/** @param {number=} core with cores in workers, a parked worker's core */
A64CPU.prototype.save_core_state = function(core = 0)
{
    const block = this.parallel ? this.state_block_of(core) : new Uint8Array(this.wasm_memory.buffer, this.state_base, 4096);
    const saved = new Uint8Array(CORE_STATE_RANGES.reduce((n, [a, b]) => n + b - a, 0));
    let at = 0;
    for(const [a, b] of CORE_STATE_RANGES)
    {
        saved.set(block.subarray(a, b), at);
        at += b - a;
    }
    return saved;
};

/** @param {!Uint8Array} saved @param {number=} core with cores in workers, a parked worker's core */
A64CPU.prototype.load_core_state = function(saved, core = 0)
{
    const block = this.parallel ? this.state_block_of(core) : new Uint8Array(this.wasm_memory.buffer, this.state_base, 4096);
    let at = 0;
    for(const [a, b] of CORE_STATE_RANGES)
    {
        block.set(saved.subarray(at, at + b - a), a);
        at += b - a;
    }
};

/**
 * Run `f` with each core (or only `only`) switched in, between slices; the
 * running core is the same afterwards
 * @param {function(number):*} f
 * @param {number=} only
 * @return {!Array<*>}
 */
A64CPU.prototype.each_core = function(f, only)
{
    const exports = this.wm.exports;
    // (cores in workers: each core's state is in its own block, state_block_of)
    if(this.parallel)
    {
        const results = [];
        for(let core = 0; core < this.cores; core++)
        {
            if(only === undefined || core === only) results.push(f(core));
        }
        return results;
    }
    const running = exports["a64_current_core"]();
    const results = [];
    for(let core = 0; core < this.cores; core++)
    {
        if(only !== undefined && core !== only) continue;
        exports["a64_switch_core"](core);
        results.push(f(core));
    }
    exports["a64_switch_core"](running);
    return results;
};

A64CPU.prototype.get_state = function(skip_memory = false)
{
    const state = [];
    state[0] = this.memory_size[0];
    state[1] = this.cores;
    // (every core's state block, P3.9: each switched in for a moment; then the running one again)
    state[2] = this.each_core(core => this.save_core_state(core));
    state[3] = this.wm.exports["a64_current_core"]();
    // the machine (P3.10): the devices, the GIC and the cores' power states (bytes of the core), the boot
    state[4] = DEVICE_ORDER.map(name => this.devices[name] ? this.devices[name].get_state() : null);
    state[5] = this.machine_state_bytes(0).slice();
    state[6] = this.machine_state_bytes(1).slice();
    state[7] = [this.booted, this.boot_entry || 0, this.boot_x0 || 0];
    // the virtio devices (P5.9): slot, kind, state; their transport
    state[8] = this.virtio_devices.map(({ slot, name, device }) => [slot, name, device]);
    state[9] = this.virtio_transport;
    // the PCIe host (P5.6): its functions' configuration, the shared SPIs' sources
    state[10] = this.devices["pci"] ? this.devices["pci"].get_state() : null;
    state[11] = Array.from(this.shared_spi_sources, ([intid, sources]) => [intid, Array.from(sources)]);
    // the display adapter (P7.1; nothing with graphics_adapter: "none")
    state[12] = this.devices.graphics_adapter;
    // (a GICv2's own state: ranchu with arm32)
    state[13] = this.gic_v2 ? this.machine_state_bytes(2).slice() : null;
    // the GLES host (ranchu_gpu "host"; a plugin's slot)
    state[14] = this.devices.gles ? this.devices.gles.get_state() : null;
    // the GLES backdoor's connections (gles_backdoor)
    state[15] = this.devices.backdoor ? this.devices.backdoor.get_state() : null;
    // (the machine clock: the system counter goes on from where it was, as on x86, src/cpu.js)
    state[95] = this.clock.get_state();
    // extended RAM's pages (P8.5: its contents are records of the snapshot stream)
    state[98] = this.extended_pages;
    if(skip_memory)
    {
        state[77] = null;
        state[78] = null;
    }
    else
    {
        // (a single-buffer snapshot does not hold extended RAM: the stream does)
        if(this.extended_store)
        {
            this.flush_extended_memory();
            if(this.extended_store.touched.some(byte => byte !== 0))
            {
                throw new Error("A snapshot of extended RAM needs save_state_stream");
            }
        }
        const { packed_memory, bitmap } = this.pack_memory();
        state[77] = packed_memory;
        state[78] = new Uint8Array(bitmap.get_buffer());
    }
    state[99] = null;
    state[103] = [this.machine_type, this.machine_type === "ranchu" ? RANCHU_LAYOUT_VERSION : VIRT_LAYOUT_VERSION, this.profile];
    return state;
};

/**
 * Take on a CPU profile by its name (A64_PROFILES): its granules and optional
 * features; a restore takes the snapshot's
 * @param {string} name
 */
A64CPU.prototype.set_profile = function(name)
{
    const entry = [...Object.values(A64_PROFILES), ...Object.values(ARM32_PROFILES)].find(p => p[0] === name);
    dbg_assert(!!entry, "unknown profile " + name);
    this.profile = name;
    this.wm.exports["a64_set_granules"](entry[1]);
    this.wm.exports["a64_set_features"](entry[2]);
};

/** Refuse a snapshot of another machine (an x86 one in either direction) or layout */
A64CPU.prototype.validate_state = function(state)
{
    const identity = state[103];
    const machine = identity ? identity[0] : "i440fx";
    if(machine !== this.machine_type)
    {
        throw new Error("The snapshot is from a machine with machine_type: \"" + machine + "\", this one has \"" + this.machine_type + "\"");
    }
    // (a snapshot of another profile restores as that profile, set_state)
    // (arm32's and arm64's profiles are of different CPUs)
    const profiles = Object.values(this.cpu_type === "arm32" ? ARM32_PROFILES : A64_PROFILES);
    const layout = this.machine_type === "ranchu" ? RANCHU_LAYOUT_VERSION : VIRT_LAYOUT_VERSION;
    if(identity[1] !== layout || !profiles.some(p => p[0] === identity[2]))
    {
        throw new Error("The snapshot is from " + machine + " layout " + identity[1] + " with CPU profile " + identity[2] +
            "; this machine is layout " + layout + ", " + this.profile);
    }
    if(state[0] !== this.memory_size[0])
    {
        throw new Error("The snapshot has " + state[0] + " bytes of RAM, this machine " + this.memory_size[0]);
    }
    if(state[1] !== this.cores)
    {
        throw new Error("The snapshot has " + state[1] + " cores, this machine " + this.cores);
    }
    if((state[98] || 0) !== this.extended_pages)
    {
        throw new Error("The snapshot has " + (state[98] || 0) * 4096 + " bytes of extended RAM, this machine " + this.extended_pages * 4096);
    }
    // (a disk's changes only onto the same image: docs/disk-image-formats-plan.md
    // P1; a different layout of the devices is refused in set_state)
    (state[8] || []).forEach(([, name, device_state], i) =>
    {
        const own = this.virtio_devices[i];
        if(own && name === "virtio-blk" && own.name === name && device_state) own.device.check_state(device_state);
    });
    if(this.devices.graphics_adapter)
    {
        this.devices.graphics_adapter.check_state(state[12]);
    }
    else if(graphics_adapter_of_state(state[12]) !== "none")
    {
        throw new Error("The snapshot is from a machine with graphics_adapter: \"" + graphics_adapter_of_state(state[12]) + "\", this one has \"none\"");
    }
    if(this.devices.gles)
    {
        this.devices.gles.check_state(state[14]);
    }
    else if(plugin_of_state(GLES_PLUGINS, state[14]) !== null)
    {
        throw new Error("The snapshot is from a machine with ranchu_gpu \"host\", this one has \"guest\"");
    }
};

A64CPU.prototype.set_state = function(state, skip_memory = false)
{
    this.validate_state(state);
    if(state[103][2] !== this.profile) this.set_profile(state[103][2]);
    // (disk requests held after an I/O error belong to the machine left behind)
    drop_disk_holds(this);
    if(state[95]) this.clock.set_state(state[95]);
    state[2].forEach((saved, core) => this.each_core(() => this.load_core_state(saved, core), core));
    if(!this.parallel) this.wm.exports["a64_switch_core"](state[3] || 0);
    (state[4] || []).forEach((device_state, i) => { if(device_state && this.devices[DEVICE_ORDER[i]]) this.devices[DEVICE_ORDER[i]].set_state(device_state); });
    if(state[5]) this.machine_state_bytes(0).set(state[5]);
    if(state[6]) { this.machine_state_bytes(1).set(state[6]); this.wm.exports["a64_psci_restored"](); }
    if(state[7]) [this.booted, this.boot_entry, this.boot_x0] = state[7];
    // (the same devices in the same slots, or the snapshot is refused)
    const devices = state[8] || [];
    const layout = list => list.map(([slot, name]) => slot + ":" + name).join(",");
    const own = layout(this.virtio_devices.map(({ slot, name }) => [slot, name]));
    if(layout(devices) !== own || state[9] !== this.virtio_transport)
    {
        throw new Error("The snapshot has the virtio devices [" + layout(devices) + "] on " + state[9] +
            ", this machine [" + own + "] on " + this.virtio_transport);
    }
    devices.forEach(([, , device_state], i) => this.virtio_devices[i].device.set_state(device_state));
    if(this.devices["pci"]) this.devices["pci"].set_state(state[10]);
    if(this.gic_v2 && state[13]) this.machine_state_bytes(2).set(state[13]);
    this.shared_spi_sources = new Map((state[11] || []).map(([intid, sources]) => [intid, new Set(sources)]));
    this.devices.graphics_adapter && this.devices.graphics_adapter.set_state(state[12]);
    // (the backdoor's connections before the GLES host's state, as the pipe's channels)
    if(this.devices.backdoor) this.devices.backdoor.set_state(state[15] || [1, []]);
    this.devices.gles && this.devices.gles.set_state(state[14]);
    this.wm.exports["a64_restored"]();
    if(!skip_memory && state[77])
    {
        this.unpack_memory(new Bitmap(state[78].buffer), state[77]);
    }
    // (cached translations and compiled code knew the old memory)
    this.wm.exports["jit_clear_cache_js"]?.();
};

/**
 * The disks by name, as CPU.prototype.disk_devices (export_disk_image,
 * disk_image_info): the virtio-blk disks, each with its image as `buffer`
 * @return {!Array<!Array<?>>}
 */
A64CPU.prototype.disk_devices = function()
{
    return this.virtio_devices.filter(({ name }) => name === "virtio-blk")
        .map(({ device }) => [device.name, { buffer: device.backend.buffer }]);
};

A64CPU.prototype.pack_memory = function()
{
    const page_count = this.memory_size[0] >>> 12;
    const nonzero = [];
    for(let page = 0; page < page_count; page++)
    {
        if(!this.is_memory_zeroed(page << 12, 0x1000)) nonzero.push(page);
    }
    if(nonzero.length * 0x1000 > STATE_MAX_SINGLE_BUFFER)
    {
        throw new RangeError("The state is larger than a single-buffer snapshot can be (2 GiB): use save_state_stream");
    }
    const bitmap = new Bitmap(page_count);
    const packed_memory = new Uint8Array(nonzero.length * 0x1000);
    for(const [i, page] of nonzero.entries())
    {
        bitmap.set(page, 1);
        packed_memory.set(this.mem8.subarray(page << 12, (page << 12) + 0x1000), i << 12);
    }
    return { bitmap, packed_memory };
};

A64CPU.prototype.unpack_memory = function(bitmap, packed_memory)
{
    this.mem8.fill(0);
    const page_count = this.memory_size[0] >>> 12;
    let packed = 0;
    for(let page = 0; page < page_count; page++)
    {
        if(bitmap.get(page))
        {
            this.mem8.set(packed_memory.subarray(packed << 12, (packed << 12) + 0x1000), page << 12);
            packed++;
        }
    }
    this.wm.exports["a64_bus_written"](0, this.memory_size[0]);
};

// ---- zstd for snapshots (src/state.js), the shared module's exports

A64CPU.prototype.zstd_create_ctx = function(n) { return this.wm.exports["zstd_create_ctx"](n); };
A64CPU.prototype.zstd_get_src_ptr = function(ctx) { return this.wm.exports["zstd_get_src_ptr"](ctx); };
A64CPU.prototype.zstd_free_ctx = function(ctx) { return this.wm.exports["zstd_free_ctx"](ctx); };
A64CPU.prototype.zstd_read = function(ctx, length) { return this.wm.exports["zstd_read"](ctx, length); };
A64CPU.prototype.zstd_read_free = function(ptr, length) { return this.wm.exports["zstd_read_free"](ptr, length); };

A64CPU.prototype.get_diagnostics = function()
{
    const exports = this.wm.exports;
    const power = ["on", "off", "on-pending"];
    const psci = this.machine_state_bytes(1);
    const cores = this.each_core(core => {
        const block = this.parallel ? this.state_block_of(core) : new Uint8Array(this.wasm_memory.buffer, this.state_base, 4096);
        const word = offset => new Int32Array(block.buffer, block.byteOffset + offset, 1)[0];
        const waiting = word(STATE_OFFSETS.waiting);
        const worker = this.parallel && core !== 0;
        return {
            "pc": worker ? "0x" + (new BigUint64Array(block.buffer, block.byteOffset + STATE_OFFSETS.pc, 1)[0]).toString(16) : this.read_pc(),
            "state": power[psci[core]] === "on" ? ["runnable", "wfi", "wfe", "off"][waiting] : power[psci[core]],
            // (AArch32's modes: User is EL0, the others PL1)
            "el": word(STATE_OFFSETS.pstate) & 0x10 ? +((word(STATE_OFFSETS.pstate) & 0xF) !== 0) : word(STATE_OFFSETS.pstate) >> 2 & 3,
            "retired_instructions": this.retired_instructions(core),
            "halt_count": worker ? this.parallel.core_counters(core).waits :
                exports["core_statistics_get"] ? exports["core_statistics_get"](core, 3) : 0,
        };
    });
    return {
        "cpu_type": this.cpu_type,
        "machine_type": this.machine_type,
        "active_core": exports["a64_current_core"](),
        "parallel": this.parallel ? Object.assign(this.parallel.status(), { "machine_core": {
            "tlbi_posted": exports["a64_tlb_ring_stat"](0), "dsb_waits": exports["a64_tlb_ring_stat"](1),
            "tlbi_taken": exports["a64_tlb_ring_stat"](2), "kicked": exports["a64_kicked"]() } }) : null,
        "execution": { "mode": this.parallel ? "parallel" : "cooperative", "fallback": this.parallel_fallback || null },
        "cores": cores,
        "pc": this.read_pc(),
        "retired": exports["core_statistics_get"] ? exports["core_statistics_get"](0, 0) : 0,
        "undefined": this.undefined_instructions(),
        "page_tier": this.page_tier_stats(),
    };
};

/** The instructions core `core` retired (with cores in workers, as its worker counts them) */
A64CPU.prototype.retired_instructions = function(core)
{
    if(this.parallel && core !== 0) return this.parallel.core_retired(core);
    const get = this.wm.exports["core_statistics_get"];
    return get ? get(core, 0) : 0;
};

/** The A64 page tier's counters (src/rust/aarch64/jit/pages.rs), or null without it */
A64CPU.prototype.page_tier_stats = function()
{
    // (the A64 page tier is jitrt's client 1: jit_stat, src/rust/jitrt/stat.rs)
    const jit_stat = this.wm.exports["jit_stat"];
    if(!jit_stat || Number.isNaN(jit_stat(1, 0))) return null;
    const stat = field => jit_stat(1, field);
    const names = ["compiled", "activations", "retired", "steps", "retries", "unknown", "retired_functions",
        "access_fills", "access_refused", "failed", "chained", "instructions", "templated"];
    const result = { "live": stat(100), "code_page_writes": stat(101), "resets": stat(102), "pages_compiled": stat(103),
        "most_compiles": stat(104), "helpers": stat(106), "evictions": stat(107), "compile_ms": stat(108),
        "asid_tag_switches": stat(109), "asid_tag": stat(110), "live_code_bytes": stat(111),
        "table_free_low": this.wm.exports["jit_wasm_table_free_low"](),
        // (diagnostics: why the access cache refused fills, pages.rs REFUSED_*)
        "refused": { "crossing": stat(120), "translation": stat(121), "not_writable": stat(122), "watched": stat(123),
            "reserved": stat(124), "extended": stat(125), "not_ram": stat(126), "unaligned": stat(127) } };
    names.forEach((name, i) => { result[name] = stat(i); });
    return result;
};

/**
 * The page tier's steps (diagnostics, pages.rs a64_step_stat): the
 * instruction classes (decode.rs Op << 4 | sub & 15) most often stepped, that
 * ended an activation by changing what compiled code depends on, and that ran
 * as helpers, with a word of each; every core's
 * @param {number=} top
 * @return {Object} null without the counters
 */
A64CPU.prototype.step_stats = function(top = 20)
{
    const stat = this.wm.exports["a64_step_stat"];
    if(!stat) return null;
    const result = {};
    // (AArch32's helper calls by instruction word)
    const helper_word = this.wm.exports["a32_helper_word"];
    if(helper_word)
    {
        const words = [];
        for(let i = 0; i < 4096; i++)
        {
            const count = helper_word(i, true);
            if(count) words.push({ "word": "0x" + (helper_word(i, false) >>> 0).toString(16).padStart(8, "0"), "count": count });
        }
        words.sort((a, b) => b["count"] - a["count"]);
        result["helped_words"] = words.slice(0, top);
    }
    ["stepped", "changed_context", "helped"].forEach((name, kind) => {
        const rows = [];
        for(let key = 0; key < 1024; key++)
        {
            const count = stat(kind, key);
            if(count) rows.push({ "op": key >> 4, "sub": key & 15, "word": "0x" + (stat(3, key) >>> 0).toString(16).padStart(8, "0"), "count": count });
        }
        rows.sort((a, b) => b["count"] - a["count"]);
        result[name] = rows.slice(0, top);
        // (MRS and MSR (register) by register: S<op0>_<op1>_C<CRn>_C<CRm>_<op2>)
        const sysreg = this.wm.exports["a64_sysreg_stat"];
        if(!sysreg) return;
        const regs = [];
        for(let reg = 0; reg < 1 << 16; reg++)
        {
            const count = sysreg(kind, reg);
            if(!count) continue;
            const r = reg & 0x7FFF;
            regs.push({ "msr": reg >> 15, "reg": `S${2 + (r >> 14)}_${r >> 11 & 7}_C${r >> 7 & 15}_C${r >> 3 & 15}_${r & 7}`, "count": count });
        }
        regs.sort((a, b) => b["count"] - a["count"]);
        result[name + "_sysregs"] = regs.slice(0, top);
        // (SYS by operation: op1, CRn, CRm, op2, as "SYS #op1, Cn, Cm, #op2")
        const ops = [];
        for(let op = 0; op < 1 << 14; op++)
        {
            const count = sysreg(4 + kind, op);
            if(count) ops.push({ "sys": `#${op >> 11 & 7}, C${op >> 7 & 15}, C${op >> 3 & 15}, #${op & 7}`, "count": count });
        }
        ops.sort((a, b) => b["count"] - a["count"]);
        result[name + "_sys"] = ops.slice(0, top);
    });
    return result;
};

/**
 * UNDEF telemetry (P2.3): counts at EL0 and EL1, and the most recent ones
 * (PC, word, EL)
 */
A64CPU.prototype.undefined_instructions = function()
{
    const exports = this.wm.exports;
    if(!exports["a64_undef_count"]) return null;
    const last = [];
    for(let i = 0; i < 16; i++)
    {
        const word = exports["a64_undef_last"](i, 2) >>> 0;
        const pc = (exports["a64_undef_last"](i, 1) >>> 0) * 0x100000000 + (exports["a64_undef_last"](i, 0) >>> 0);
        if(!pc && !word) break;
        last.push({ "pc": "0x" + pc.toString(16), "word": "0x" + word.toString(16).padStart(8, "0"), "el": exports["a64_undef_last"](i, 3) });
    }
    return { "el0": exports["a64_undef_count"](0, 16), "el1": exports["a64_undef_count"](1, 16), "last": last };
};

/** The current core's PC, as a hexadecimal string */
A64CPU.prototype.read_pc = function()
{
    const words = view(Uint32Array, this.wasm_memory, this.state_base + STATE_OFFSETS.pc, 2);
    return "0x" + (words[1] * 0x100000000 + words[0]).toString(16);
};

A64CPU.prototype.get_jit_info = function()
{
    return { "enabled": false };
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/arm/state_layout.js                                                                  0000644 0000000 0000000 00000004072 00000000000 014310  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by gen/state_layout.js from the CPU state layout; do not edit.

/** Offsets of the CPU state fields in the Wasm memory */
export const STATE_OFFSETS = {
    x: 64,
    pc: 320,
    nzcv: 328,
    pstate: 332,
    fpcr: 336,
    fpsr: 340,
    instruction_counter: 344,
    slice_budget: 348,
    v: 352,
    sp_el: 864,
    elr_el1: 880,
    spsr_el1: 888,
    esr_el1: 896,
    far_el1: 904,
    vbar_el1: 912,
    sctlr_el1: 920,
    cpacr_el1: 928,
    ttbr0_el1: 936,
    ttbr1_el1: 944,
    tcr_el1: 952,
    mair_el1: 960,
    amair_el1: 968,
    contextidr_el1: 976,
    tpidr_el0: 984,
    tpidrro_el0: 992,
    tpidr_el1: 1000,
    par_el1: 1008,
    afsr0_el1: 1016,
    afsr1_el1: 1024,
    actlr_el1: 1032,
    csselr_el1: 1040,
    cntkctl_el1: 1048,
    cntfrq_el0: 1056,
    mdscr_el1: 1064,
    osdlr_el1: 1072,
    oslsr_el1: 1080,
    mdccint_el1: 1088,
    disr_el1: 1096,
    cntv_ctl: 1104,
    cntv_cval: 1112,
    cntp_ctl: 1120,
    cntp_cval: 1128,
    icc_pmr: 1136,
    icc_bpr: 1140,
    icc_igrpen: 1148,
    icc_ctlr: 1156,
    icc_ap0r: 1160,
    icc_ap1r: 1164,
    icc_active: 1168,
    icc_active_count: 1200,
    excl_valid: 1208,
    excl_addr: 1216,
    excl_value: 1232,
    dbgbvr: 1248,
    dbgbcr: 1264,
    dbgwvr: 1280,
    dbgwcr: 1296,
    waiting: 1312,
    event_register: 1316,
    a64_page_exit: 1328,
    a64_page_chain: 1332,
    a64_page_linear: 1336,
    a64_jac_epoch: 1344,
    a64_jac_base: 1352,
    a64_code_base: 1356,
    a32_bank: 1360,
    a32_bank_r8: 1408,
    a32_spsr: 1448,
    a32_ttbcr: 1468,
    a32_dacr: 1472,
    a32_ifsr: 1476,
    a32_fpexc: 1480,
};

/**
 * Byte ranges [start, end) of the per-core state; copied when the active core
 * changes (CPU.prototype.save_core_state/load_core_state)
 */
export const CORE_STATE_RANGES = [
    [64, 344],
    [352, 864],
    [864, 1104],
    [1104, 1136],
    [1136, 1204],
    [1208, 1248],
    [1248, 1312],
    [1312, 1320],
    [1360, 1484],
];

/** [offset, size] of the core state that INIT keeps (the rest takes its reset value) */
export const INIT_PRESERVED = [

];
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/audio_devices/hd_audio/codec.js                                                      0000644 0000000 0000000 00000026477 00000000000 016465  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The HD Audio codec behind the controller (src/audio_devices/hd_audio/
// controller.js): a generic output codec, as QEMU's hda-output
// (hw/audio/hda-codec.c) is, which the drivers that come with Windows
// (hdaudio.inf, HDAUDIO\FUNC_01) and Linux (the generic codec parser)
// accept without codec-specific setup. Its nodes: the root, the audio
// function group, a stereo DAC with an output amplifier (mute and 74 steps
// of 1 dB, a volume control for the guest's mixer) and a line out pin
// connected to it. See the High Definition Audio Specification 1.0a,
// sections 7.3 (verbs and parameters).

// codec IDs (QEMU's: vendor 1AF4, its output codec with a mixer)
const VENDOR_ID = 0x1AF40012;
const REVISION_ID = 0x00100101;

const NID_ROOT = 0, NID_AFG = 1, NID_DAC = 2, NID_PIN = 3;

// parameters (GET_PARAMETERS)
const PAR_VENDOR_ID = 0x00, PAR_SUBSYSTEM_ID = 0x01, PAR_REV_ID = 0x02, PAR_NODE_COUNT = 0x04, PAR_FUNCTION_TYPE = 0x05,
    PAR_AUDIO_FG_CAP = 0x08, PAR_AUDIO_WIDGET_CAP = 0x09, PAR_PCM = 0x0A, PAR_STREAM = 0x0B, PAR_PIN_CAP = 0x0C,
    PAR_AMP_IN_CAP = 0x0D, PAR_CONNLIST_LEN = 0x0E, PAR_POWER_STATE = 0x0F, PAR_PROC_CAP = 0x10, PAR_GPIO_CAP = 0x11,
    PAR_AMP_OUT_CAP = 0x12, PAR_VOL_KNB_CAP = 0x13;

// widget capabilities
const WCAP_STEREO = 1 << 0, WCAP_OUT_AMP = 1 << 2, WCAP_AMP_OVRD = 1 << 3, WCAP_FORMAT_OVRD = 1 << 4, WCAP_CONN_LIST = 1 << 8;
const WID_AUD_OUT = 0, WID_PIN = 4;
const WCAP_TYPE_SHIFT = 20;

/**
 * The formats: 16-bit PCM at 44.1 and 48 kHz (bits 5 and 6), what the
 * controller's streams play (PCM_RATES of controller.js)
 */
export const PCM_FORMATS = 1 << 17 | 1 << 5 | 1 << 6;
const SUPFMT_PCM = 1;
const PINCAP_OUT = 1 << 4;
// the DAC's amplifier: mute, 74 steps of 1 dB (step size 3: (3 + 1) / 4 dB), 0 dB at step 74
export const AMP_STEPS = 0x4A;
const AMP_CAPS = 1 << 31 | 3 << 16 | AMP_STEPS << 8 | AMP_STEPS;
// line out, a jack, green, association 1 (QEMU's)
const PIN_CONFIG = 0x00004010;
const PINCTL_OUT_EN = 1 << 6;

// verbs with 8-bit payloads (12-bit verbs)
const VERB_PARAMETERS = 0xF00, VERB_GET_CONNECT_SEL = 0xF01, VERB_GET_CONNECT_LIST = 0xF02, VERB_GET_POWER_STATE = 0xF05,
    VERB_GET_CONV = 0xF06, VERB_GET_PIN_WIDGET_CONTROL = 0xF07, VERB_GET_UNSOLICITED = 0xF08, VERB_GET_PIN_SENSE = 0xF09,
    VERB_GET_EAPD_BTLENABLE = 0xF0C, VERB_GET_DIGI_CONVERT = 0xF0D, VERB_GET_CONFIG_DEFAULT = 0xF1C,
    VERB_GET_SUBSYSTEM_ID = 0xF20, VERB_GET_CVT_CHAN_COUNT = 0xF2D,
    VERB_SET_CONNECT_SEL = 0x701, VERB_SET_POWER_STATE = 0x705, VERB_SET_CHANNEL_STREAMID = 0x706,
    VERB_SET_PIN_WIDGET_CONTROL = 0x707, VERB_SET_UNSOLICITED = 0x708, VERB_SET_EAPD_BTLENABLE = 0x70C,
    VERB_SET_DIGI_CONVERT_1 = 0x70D, VERB_SET_CONFIG_DEFAULT_0 = 0x71C, VERB_SET_CONFIG_DEFAULT_3 = 0x71F,
    VERB_SET_SUBSYSTEM_ID_0 = 0x720, VERB_SET_SUBSYSTEM_ID_3 = 0x723, VERB_SET_CVT_CHAN_COUNT = 0x72D, VERB_RESET = 0x7FF;
// verbs with 16-bit payloads (4-bit verbs)
const VERB4_SET_STREAM_FORMAT = 0x2, VERB4_SET_AMP_GAIN_MUTE = 0x3, VERB4_GET_STREAM_FORMAT = 0xA, VERB4_GET_AMP_GAIN_MUTE = 0xB;

/**
 * @constructor
 * @param {number} address the codec's address on the link (SDIN), 0
 */
export function HDACodec(address)
{
    this.address = address;
    this.reset();
}

/** Power on, a link reset or the function group's reset verb */
HDACodec.prototype.reset = function()
{
    /** The DAC's stream (tag) and channel; tag 0: not playing */
    this.stream = 0;
    this.channel = 0;
    /** The DAC's format (the stream format register's encoding) */
    this.format = 0x0011;
    /** The DAC's output amplifier: [left, right] gain steps and mute */
    this.gain = [AMP_STEPS, AMP_STEPS];
    this.mute = [false, false];
    this.pin_control = PINCTL_OUT_EN;
    this.pin_config = PIN_CONFIG;
    this.eapd = 0;
    this.unsolicited = 0;
    this.power = [0, 0, 0, 0];
    this.subsystem_id = VENDOR_ID;
    this.digital = 0;
};

/**
 * A node's parameter (GET_PARAMETERS)
 * @param {number} nid
 * @param {number} id
 * @return {number}
 */
HDACodec.prototype.parameter = function(nid, id)
{
    switch(nid)
    {
        case NID_ROOT:
            switch(id)
            {
                case PAR_VENDOR_ID: return VENDOR_ID;
                case PAR_SUBSYSTEM_ID: return this.subsystem_id;
                case PAR_REV_ID: return REVISION_ID;
                // one node from 1: the function group
                case PAR_NODE_COUNT: return 1 << 16 | 1;
            }
            return 0;
        case NID_AFG:
            switch(id)
            {
                case PAR_FUNCTION_TYPE: return 0x01;
                case PAR_SUBSYSTEM_ID: return this.subsystem_id;
                // two widgets from 2: the DAC and the pin
                case PAR_NODE_COUNT: return 2 << 16 | 2;
                case PAR_AUDIO_FG_CAP: return 0x00000808;
                case PAR_PCM: return PCM_FORMATS;
                case PAR_STREAM: return SUPFMT_PCM;
            }
            return 0;
        case NID_DAC:
            switch(id)
            {
                case PAR_AUDIO_WIDGET_CAP:
                    return WID_AUD_OUT << WCAP_TYPE_SHIFT | WCAP_FORMAT_OVRD | WCAP_AMP_OVRD | WCAP_OUT_AMP | WCAP_STEREO;
                case PAR_PCM: return PCM_FORMATS;
                case PAR_STREAM: return SUPFMT_PCM;
                case PAR_AMP_OUT_CAP: return AMP_CAPS;
            }
            return 0;
        case NID_PIN:
            switch(id)
            {
                case PAR_AUDIO_WIDGET_CAP: return WID_PIN << WCAP_TYPE_SHIFT | WCAP_CONN_LIST | WCAP_STEREO;
                case PAR_PIN_CAP: return PINCAP_OUT;
                case PAR_CONNLIST_LEN: return 1;
            }
            return 0;
    }
    return 0;
};

/**
 * A command from the controller (CORB or the immediate command): the
 * response (0 for nodes and verbs it does not have, as QEMU's codec answers)
 * @param {number} command the 32-bit verb
 * @return {number}
 */
HDACodec.prototype.command = function(command)
{
    const nid = command >>> 20 & 0x7F;
    if(nid > NID_PIN) return 0;
    // 4-bit verbs carry a 16-bit payload, 12-bit verbs (7xx, Fxx) an 8-bit one
    if((command >>> 16 & 7) !== 7)
    {
        return this.verb4(nid, command >>> 16 & 0xF, command & 0xFFFF);
    }
    return this.verb12(nid, command >>> 8 & 0xFFF, command & 0xFF);
};

/**
 * @param {number} nid
 * @param {number} verb
 * @param {number} payload
 * @return {number}
 */
HDACodec.prototype.verb4 = function(nid, verb, payload)
{
    if(nid !== NID_DAC) return 0;
    switch(verb)
    {
        case VERB4_SET_STREAM_FORMAT:
            this.format = payload;
            return 0;
        case VERB4_GET_STREAM_FORMAT:
            return this.format;
        case VERB4_SET_AMP_GAIN_MUTE:
            // output amplifier (bit 15), left (13) and right (12)
            if(payload & 1 << 15)
            {
                for(const [bit, side] of [[13, 0], [12, 1]])
                {
                    if(payload & 1 << bit)
                    {
                        this.gain[side] = Math.min(payload & 0x7F, AMP_STEPS);
                        this.mute[side] = !!(payload & 0x80);
                    }
                }
            }
            return 0;
        case VERB4_GET_AMP_GAIN_MUTE:
        {
            if(!(payload & 1 << 15)) return 0;
            const side = payload & 1 << 13 ? 0 : 1;
            return (this.mute[side] ? 0x80 : 0) | this.gain[side];
        }
    }
    return 0;
};

/**
 * @param {number} nid
 * @param {number} verb
 * @param {number} payload
 * @return {number}
 */
HDACodec.prototype.verb12 = function(nid, verb, payload)
{
    switch(verb)
    {
        case VERB_PARAMETERS:
            return this.parameter(nid, payload);
        case VERB_GET_SUBSYSTEM_ID:
            return this.subsystem_id;
        case VERB_GET_CONNECT_LIST:
            // the pin's one entry, the DAC
            return nid === NID_PIN && payload === 0 ? NID_DAC : 0;
        case VERB_GET_CONNECT_SEL:
        case VERB_SET_CONNECT_SEL:
            return 0;
        case VERB_GET_POWER_STATE:
            // (the state set, also as the actual state)
            return this.power[nid] << 4 | this.power[nid];
        case VERB_SET_POWER_STATE:
            this.power[nid] = payload & 0xF;
            return 0;
        case VERB_GET_CONV:
            return nid === NID_DAC ? this.stream << 4 | this.channel : 0;
        case VERB_SET_CHANNEL_STREAMID:
            if(nid === NID_DAC)
            {
                this.stream = payload >> 4;
                this.channel = payload & 0xF;
            }
            return 0;
        case VERB_GET_PIN_WIDGET_CONTROL:
            return nid === NID_PIN ? this.pin_control : 0;
        case VERB_SET_PIN_WIDGET_CONTROL:
            if(nid === NID_PIN) this.pin_control = payload;
            return 0;
        case VERB_GET_UNSOLICITED:
            return this.unsolicited;
        case VERB_SET_UNSOLICITED:
            this.unsolicited = payload;
            return 0;
        case VERB_GET_PIN_SENSE:
            // (nothing to sense: no presence detect in the pin's caps)
            return 0;
        case VERB_GET_EAPD_BTLENABLE:
            return this.eapd;
        case VERB_SET_EAPD_BTLENABLE:
            this.eapd = payload;
            return 0;
        case VERB_GET_DIGI_CONVERT:
            return this.digital;
        case VERB_SET_DIGI_CONVERT_1:
            this.digital = this.digital & ~0xFF | payload;
            return 0;
        case VERB_GET_CONFIG_DEFAULT:
            return nid === NID_PIN ? this.pin_config : 0;
        case VERB_GET_CVT_CHAN_COUNT:
            return nid === NID_DAC ? 1 : 0;
        case VERB_SET_CVT_CHAN_COUNT:
            return 0;
        case VERB_RESET:
            if(nid === NID_AFG) this.reset();
            return 0;
    }
    if(verb >= VERB_SET_CONFIG_DEFAULT_0 && verb <= VERB_SET_CONFIG_DEFAULT_3)
    {
        if(nid === NID_PIN)
        {
            const shift = (verb - VERB_SET_CONFIG_DEFAULT_0) << 3;
            this.pin_config = (this.pin_config & ~(0xFF << shift) | payload << shift) >>> 0;
        }
        return 0;
    }
    if(verb >= VERB_SET_SUBSYSTEM_ID_0 && verb <= VERB_SET_SUBSYSTEM_ID_3)
    {
        const shift = (verb - VERB_SET_SUBSYSTEM_ID_0) << 3;
        this.subsystem_id = (this.subsystem_id & ~(0xFF << shift) | payload << shift) >>> 0;
        return 0;
    }
    // other verbs: no state, the response 0 (as QEMU's codec answers)
    return 0;
};

/**
 * The DAC's output: whether stream `tag` plays through it, and its gains
 * (linear, per channel; 0 when muted or the pin is off)
 * @param {number} tag
 * @return {?Array<number>}
 */
HDACodec.prototype.output_for = function(tag)
{
    if(!tag || this.stream !== tag) return null;
    const on = !!(this.pin_control & PINCTL_OUT_EN);
    return [0, 1].map(side => on && !this.mute[side] ? Math.pow(10, (this.gain[side] - AMP_STEPS) / 20) : 0);
};

HDACodec.prototype.get_state = function()
{
    return [this.stream, this.channel, this.format, this.gain[0], this.gain[1], +this.mute[0], +this.mute[1],
        this.pin_control, this.pin_config, this.eapd, this.unsolicited, this.power.slice(), this.subsystem_id, this.digital];
};

HDACodec.prototype.set_state = function(state)
{
    [this.stream, this.channel, this.format] = state;
    this.gain = [state[3], state[4]];
    this.mute = [!!state[5], !!state[6]];
    [this.pin_control, this.pin_config, this.eapd, this.unsolicited] = state.slice(7, 11);
    this.power = state[11].slice();
    this.subsystem_id = state[12];
    this.digital = state[13];
};
                                                                                                                                                                                                 source/v64/src/audio_devices/hd_audio/controller.js                                                 0000644 0000000 0000000 00000103221 00000000000 017552  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // audio_device "hd_audio": an Intel High Definition Audio controller, ICH6's
// (8086:2668) on i440FX, ICH9's (8086:293E) on Q35, as QEMU's intel-hda and
// ich9-intel-hda; Windows binds hdaudbus.inf by its class (PCI\CC_0403),
// Linux snd-hda-intel by both IDs. One codec (codec.js) and one output
// stream; INTA. See the High Definition Audio Specification 1.0a, chapters 3
// (registers) and 4 (programming model).
//
// The codec's commands go through the CORB and RIRB in guest memory (or the
// immediate command registers) and are answered at once. An output stream
// plays at its format's rate on the machine clock: its buffer descriptor
// list is read as the time to play it comes, LPIB, the DMA position buffer
// and the completion interrupts follow, and the samples go to the speaker
// whether or not the page can play them (docs/modern-pc-devices-plan.md,
// H1).

import { LOG_DMA } from "../../const.js";
import { h } from "../../lib.js";
import { dbg_log } from "../../log.js";
import { AudioMachine } from "../machine.js";
import { HDACodec } from "./codec.js";

const MMIO_SIZE = 0x4000;

/** The controller of each machine: [device, revision] */
const IDENTITY = { "i440fx": [0x2668, 0x01], "q35": [0x293E, 0x03] };
const PCI_VENDOR = 0x8086;
// (QEMU's subsystem, as its intel-hda has)
const PCI_SUBSYSTEM_VENDOR = 0x1AF4, PCI_SUBSYSTEM = 0x1100;
const PM_CAP = 0x50;
const PM_PMC = 0xC842;

const INPUT_STREAMS = 0, OUTPUT_STREAMS = 1;
const STREAMS = INPUT_STREAMS + OUTPUT_STREAMS;
/** GCAP: output and input streams, 64-bit addresses */
const GCAP = OUTPUT_STREAMS << 12 | INPUT_STREAMS << 8 | 1;

// registers (byte offsets in BAR0)
const R_GCAP = 0x00, R_VMIN = 0x02, R_VMAJ = 0x03, R_OUTPAY = 0x04, R_INPAY = 0x06, R_GCTL = 0x08, R_WAKEEN = 0x0C,
    R_STATESTS = 0x0E, R_GSTS = 0x10, R_OUTSTRMPAY = 0x18, R_INSTRMPAY = 0x1A, R_INTCTL = 0x20, R_INTSTS = 0x24,
    R_WALCLK = 0x30, R_SSYNC_OLD = 0x34, R_SSYNC = 0x38,
    R_CORBLBASE = 0x40, R_CORBUBASE = 0x44, R_CORBWP = 0x48, R_CORBRP = 0x4A, R_CORBCTL = 0x4C, R_CORBSTS = 0x4D,
    R_CORBSIZE = 0x4E, R_RIRBLBASE = 0x50, R_RIRBUBASE = 0x54, R_RIRBWP = 0x58, R_RINTCNT = 0x5A, R_RIRBCTL = 0x5C,
    R_RIRBSTS = 0x5D, R_RIRBSIZE = 0x5E, R_ICOI = 0x60, R_ICII = 0x64, R_ICIS = 0x68, R_DPLBASE = 0x70, R_DPUBASE = 0x74,
    R_STREAMS = 0x80, STREAM_SIZE = 0x20, R_WALCLK_ALIAS = 0x2030, R_LPIB_ALIAS = 0x2084;
// a stream descriptor's registers (from its base)
const SD_CTL = 0x00, SD_STS = 0x03, SD_LPIB = 0x04, SD_CBL = 0x08, SD_LVI = 0x0C, SD_FIFOW = 0x0E, SD_FIFOS = 0x10,
    SD_FMT = 0x12, SD_BDPL = 0x18, SD_BDPU = 0x1C;

const GCTL_CRST = 1 << 0, GCTL_FCNTRL = 1 << 1, GCTL_UNSOL = 1 << 8;
const INT_GIE = 1 << 31, INT_CIE = 1 << 30;
const CORBRP_RST = 1 << 15;
const CORBCTL_CMEIE = 1 << 0, CORBCTL_RUN = 1 << 1;
const RIRBWP_RST = 1 << 15;
const RIRBCTL_RINTCTL = 1 << 0, RIRBCTL_DMAEN = 1 << 1;
const RIRBSTS_RINTFL = 1 << 0, RIRBSTS_OIS = 1 << 2;
/** 256 entries (the only size), and that it is the only one */
const RING_SIZE = 0x42;
const ICIS_ICB = 1 << 0, ICIS_IRV = 1 << 1;
const DPLBASE_ENABLE = 1 << 0;

const SD_CTL_SRST = 1 << 0, SD_CTL_RUN = 1 << 1, SD_CTL_IOCE = 1 << 2, SD_CTL_FEIE = 1 << 3, SD_CTL_DEIE = 1 << 4;
const SD_STS_BCIS = 1 << 2, SD_STS_FIFOE = 1 << 3, SD_STS_DESE = 1 << 4, SD_STS_FIFORDY = 1 << 5;
/** The FIFO's size in bytes, less one (SDnFIFOS) */
const FIFO_SIZE = 0xFF;

/** The wall clock: 24 MHz, in ticks per millisecond of the machine clock */
const WALLCLK_PER_MS = 24000;
/** Per round of the timer at most this much is played; the rest when it is due again */
const MAX_PLAY_MS = 100;

/** The formats the codec announces (codec.js PCM_FORMATS): rate and sample size of a stream */
const PCM_RATES = [44100, 48000];

/**
 * A stream's format register (SDnFMT, the codec's converter format)
 * @param {number} fmt
 * @return {{rate: number, bytes: number, channels: number}}
 */
export function decode_format(fmt)
{
    const base = fmt & 1 << 14 ? 44100 : 48000;
    const rate = base * ((fmt >> 11 & 7) + 1) / ((fmt >> 8 & 7) + 1);
    // 8 bits in a byte, 16 in two, 20, 24 and 32 in four
    const bytes = [1, 2, 4, 4, 4, 4, 4, 4][fmt >> 4 & 7];
    return { rate, bytes, channels: (fmt & 0xF) + 1 };
}

/**
 * @constructor
 * @param {!Object} handle the machine handle (src/device_plugin.js)
 */
export function HDAController(handle)
{
    const machine = new AudioMachine(handle);
    /** @const @type {AudioMachine} */
    this.machine = machine;
    this.name = "hd_audio";

    this.codec = new HDACodec(0);
    this.streams = [];
    for(let i = 0; i < STREAMS; i++) this.streams.push(new_stream(i));

    this.bar0 = 0;
    /** Where BAR0 is decoded, or -1 */
    this.mmio = -1;
    this.irq_level = false;
    /** The rate the speaker was last told */
    this.speaker_rate = 0;

    this.reset_controller();
    this.gctl = 0;

    const [device, revision] = IDENTITY[machine.machine_type] || IDENTITY["i440fx"];
    machine.register_pci({
        pci_space: create_pci_space(device, revision),
        pci_bars: [{ size: MMIO_SIZE, on_move: base => { this.bar0 = base; this.update_decode(); } }],
        on_command_change: () => { this.update_decode(); this.update_irq(); },
        on_config_restore: () => this.update_decode(),
        on_upstream_change: () => this.update_decode(),
        on_config_write: (offset, size) => this.config_written(offset, size),
    });
    machine.add_timer(now => this.timer(now));
}

/**
 * @param {number} index
 */
function new_stream(index)
{
    return {
        index,
        output: index >= INPUT_STREAMS,
        ctl: 0, sts: 0, lpib: 0, cbl: 0, lvi: 0, fifow: 0, fmt: 0, bdpl: 0, bdpu: 0,
        // while it runs: the buffer descriptor and the offset in it, and
        // the frames played since `started` (machine time)
        entry: 0, offset: 0, started: 0, played: 0, running: false,
    };
}

/**
 * @param {number} device
 * @param {number} revision
 * @return {!Array<number>}
 */
function create_pci_space(device, revision)
{
    const space = new Array(256).fill(0);
    const put16 = (offset, value) => { space[offset] = value & 0xFF; space[offset + 1] = value >> 8 & 0xFF; };
    put16(0x00, PCI_VENDOR);
    put16(0x02, device);
    // status: a capabilities list
    put16(0x06, 0x0010);
    space[0x08] = revision;
    // class 04/03/00: an HD Audio controller
    space[0x0A] = 0x03;
    space[0x0B] = 0x04;
    put16(0x2C, PCI_SUBSYSTEM_VENDOR);
    put16(0x2E, PCI_SUBSYSTEM);
    space[0x34] = PM_CAP;
    space[0x3D] = 1;
    // HDCTL: HD Audio, not AC '97
    space[0x40] = 0x01;
    space[PM_CAP] = 0x01;
    put16(PM_CAP + 2, PM_PMC);
    return space;
}

/** The power management capability keeps its read-only bytes */
HDAController.prototype.config_written = function(offset, size)
{
    if(offset + size <= PM_CAP || offset >= PM_CAP + 8) return;
    const space = this.machine.pci_config();
    const pmcsr = (space[PM_CAP + 4] | space[PM_CAP + 5] << 8) & 0x0103;
    space.set([0x01, 0x00, PM_PMC & 0xFF, PM_PMC >> 8, pmcsr & 0xFF, pmcsr >> 8, 0, 0], PM_CAP);
};

HDAController.prototype.update_decode = function()
{
    const base = this.bar0 && this.machine.memory_decoded(this.bar0, MMIO_SIZE) ? this.bar0 : -1;
    if(base === this.mmio) return;
    if(this.mmio !== -1) this.machine.mmap_unregister_range(this.mmio, MMIO_SIZE);
    this.mmio = base;
    if(base !== -1)
    {
        this.machine.mmap_register_range(base, MMIO_SIZE,
            address => this.read(address - this.mmio, 1),
            (address, value) => this.write(address - this.mmio, 1, value),
            address => this.read(address - this.mmio, 4),
            (address, value) => this.write(address - this.mmio, 4, value));
    }
};

/** Everything but GCTL to its reset value (GCTL.CRST cleared, or a machine reset) */
HDAController.prototype.reset_controller = function()
{
    for(const stream of this.streams) this.stop(stream);
    this.streams = this.streams.map(stream => new_stream(stream.index));
    this.wakeen = 0;
    this.statests = 0;
    this.gsts = 0;
    this.intctl = 0;
    this.ssync = 0;
    this.corb_base = [0, 0];
    this.corb_wp = 0;
    this.corb_rp = 0;
    this.corb_rp_reset = false;
    this.corbctl = 0;
    this.corbsts = 0;
    this.rirb_base = [0, 0];
    this.rirb_wp = 0;
    this.rintcnt = 0;
    this.rirbctl = 0;
    this.rirbsts = 0;
    /** responses since RINTFL was last set (RINTCNT) */
    this.rirb_count = 0;
    this.icoi = 0;
    this.icii = 0;
    this.icis = 0;
    this.dplbase = 0;
    this.dpubase = 0;
    this.wall_base = this.machine.now();
    this.codec.reset();
    this.update_irq();
};

/** A machine reset (PCIRST#) */
HDAController.prototype.reset = function()
{
    this.reset_controller();
    this.gctl = 0;
    this.update_decode();
};

// registers

/**
 * A register's value
 * @param {number} offset its first byte
 * @return {number}
 */
HDAController.prototype.register = function(offset)
{
    if(offset >= R_STREAMS && offset < R_STREAMS + STREAMS * STREAM_SIZE)
    {
        const stream = this.streams[offset - R_STREAMS >> 5];
        switch(offset - R_STREAMS & 0x1F)
        {
            case SD_CTL: return stream.ctl;
            case SD_STS: return stream.sts | (stream.running ? SD_STS_FIFORDY : 0);
            case SD_LPIB: return stream.lpib;
            case SD_CBL: return stream.cbl;
            case SD_LVI: return stream.lvi;
            case SD_FIFOW: return stream.fifow;
            case SD_FIFOS: return FIFO_SIZE;
            case SD_FMT: return stream.fmt;
            case SD_BDPL: return stream.bdpl;
            case SD_BDPU: return stream.bdpu;
        }
        return 0;
    }
    if(offset >= R_LPIB_ALIAS && offset < R_LPIB_ALIAS + STREAMS * STREAM_SIZE && !(offset - R_LPIB_ALIAS & 0x1F))
    {
        return this.streams[offset - R_LPIB_ALIAS >> 5].lpib;
    }
    switch(offset)
    {
        case R_GCAP: return GCAP;
        case R_VMIN: return 0;
        case R_VMAJ: return 1;
        case R_OUTPAY: return 0x3C;
        case R_INPAY: return 0x1D;
        case R_GCTL: return this.gctl;
        case R_WAKEEN: return this.wakeen;
        case R_STATESTS: return this.statests;
        case R_GSTS: return this.gsts;
        case R_OUTSTRMPAY: return 0x30;
        case R_INSTRMPAY: return 0x18;
        case R_INTCTL: return this.intctl;
        case R_INTSTS: return this.interrupt_status();
        case R_WALCLK: case R_WALCLK_ALIAS: return this.wallclock();
        case R_SSYNC: case R_SSYNC_OLD: return this.ssync;
        case R_CORBLBASE: return this.corb_base[0];
        case R_CORBUBASE: return this.corb_base[1];
        case R_CORBWP: return this.corb_wp;
        case R_CORBRP: return this.corb_rp | (this.corb_rp_reset ? CORBRP_RST : 0);
        case R_CORBCTL: return this.corbctl;
        case R_CORBSTS: return this.corbsts;
        case R_CORBSIZE: return RING_SIZE;
        case R_RIRBLBASE: return this.rirb_base[0];
        case R_RIRBUBASE: return this.rirb_base[1];
        case R_RIRBWP: return this.rirb_wp;
        case R_RINTCNT: return this.rintcnt;
        case R_RIRBCTL: return this.rirbctl;
        case R_RIRBSTS: return this.rirbsts;
        case R_RIRBSIZE: return RING_SIZE;
        case R_ICOI: return this.icoi;
        case R_ICII: return this.icii;
        case R_ICIS: return this.icis;
        case R_DPLBASE: return this.dplbase;
        case R_DPUBASE: return this.dpubase;
    }
    return 0;
};

/** The registers' sizes, by first byte (the rest are a stream's, register_size) */
const SIZES = new Map([
    [R_GCAP, 2], [R_VMIN, 1], [R_VMAJ, 1], [R_OUTPAY, 2], [R_INPAY, 2], [R_GCTL, 4], [R_WAKEEN, 2], [R_STATESTS, 2],
    [R_GSTS, 2], [R_OUTSTRMPAY, 2], [R_INSTRMPAY, 2], [R_INTCTL, 4], [R_INTSTS, 4], [R_WALCLK, 4], [R_SSYNC_OLD, 4],
    [R_SSYNC, 4], [R_CORBLBASE, 4], [R_CORBUBASE, 4], [R_CORBWP, 2], [R_CORBRP, 2], [R_CORBCTL, 1], [R_CORBSTS, 1],
    [R_CORBSIZE, 1], [R_RIRBLBASE, 4], [R_RIRBUBASE, 4], [R_RIRBWP, 2], [R_RINTCNT, 2], [R_RIRBCTL, 1], [R_RIRBSTS, 1],
    [R_RIRBSIZE, 1], [R_ICOI, 4], [R_ICII, 4], [R_ICIS, 2], [R_DPLBASE, 4], [R_DPUBASE, 4], [R_WALCLK_ALIAS, 4],
]);
const STREAM_SIZES = new Map([[SD_CTL, 3], [SD_STS, 1], [SD_LPIB, 4], [SD_CBL, 4], [SD_LVI, 2], [SD_FIFOW, 2], [SD_FIFOS, 2],
    [SD_FMT, 2], [SD_BDPL, 4], [SD_BDPU, 4]]);

/**
 * The register a byte belongs to: [its first byte, its size], or null
 * @param {number} offset
 * @return {Array<number>}
 */
function register_at(offset)
{
    const stream_area = (base, sizes) =>
    {
        const local = offset - base & 0x1F;
        for(const [start, size] of sizes)
        {
            if(local >= start && local < start + size) return [offset - local + start, size];
        }
        return null;
    };
    if(offset >= R_STREAMS && offset < R_STREAMS + STREAMS * STREAM_SIZE) return stream_area(R_STREAMS, STREAM_SIZES);
    if(offset >= R_LPIB_ALIAS && offset < R_LPIB_ALIAS + STREAMS * STREAM_SIZE) return stream_area(R_LPIB_ALIAS, new Map([[0, 4]]));
    for(const [start, size] of SIZES)
    {
        if(offset >= start && offset < start + size) return [start, size];
    }
    return null;
}

/**
 * An access of 1, 2 or 4 bytes: each register it covers, its bytes merged
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
HDAController.prototype.read = function(offset, size)
{
    let value = 0;
    for(let i = 0; i < size;)
    {
        const at = register_at(offset + i);
        if(!at) { i++; continue; }
        const [start, length] = at;
        const register = this.register(start) >>> 0;
        for(; i < size && offset + i < start + length; i++)
        {
            value |= (register >>> ((offset + i - start) << 3) & 0xFF) << (i << 3);
        }
    }
    return value >>> 0;
};

/**
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
HDAController.prototype.write = function(offset, size, value)
{
    for(let i = 0; i < size;)
    {
        const at = register_at(offset + i);
        if(!at) { i++; continue; }
        const [start, length] = at;
        let mask = 0, bits = 0;
        for(; i < size && offset + i < start + length; i++)
        {
            const shift = (offset + i - start) << 3;
            mask |= 0xFF << shift;
            bits |= (value >>> (i << 3) & 0xFF) << shift;
        }
        this.write_register(start, bits >>> 0, mask >>> 0);
    }
};

/**
 * A write of the bytes `mask` covers
 * @param {number} offset the register's first byte
 * @param {number} bits
 * @param {number} mask
 */
HDAController.prototype.write_register = function(offset, bits, mask)
{
    const merge = old => (old & ~mask | bits & mask) >>> 0;
    const clear = old => (old & ~(bits & mask)) >>> 0;
    if(offset === R_GCTL)
    {
        this.write_gctl(merge(this.gctl));
        return;
    }
    // (in reset only GCTL is written)
    if(!(this.gctl & GCTL_CRST)) return;

    if(offset >= R_STREAMS && offset < R_STREAMS + STREAMS * STREAM_SIZE)
    {
        this.write_stream(this.streams[offset - R_STREAMS >> 5], offset - R_STREAMS & 0x1F, bits, mask);
        return;
    }
    switch(offset)
    {
        case R_WAKEEN:
            this.wakeen = merge(this.wakeen) & 0x7FFF;
            this.update_irq();
            break;
        case R_STATESTS:
            this.statests = clear(this.statests);
            this.update_irq();
            break;
        case R_GSTS:
            this.gsts = clear(this.gsts);
            break;
        case R_INTCTL:
            this.intctl = merge(this.intctl);
            this.update_irq();
            break;
        case R_SSYNC:
        case R_SSYNC_OLD:
            this.ssync = merge(this.ssync) & (1 << STREAMS) - 1;
            for(const stream of this.streams) this.update_running(stream);
            break;
        case R_CORBLBASE:
            this.corb_base[0] = merge(this.corb_base[0]) & ~0x7F;
            break;
        case R_CORBUBASE:
            this.corb_base[1] = merge(this.corb_base[1]);
            break;
        case R_CORBWP:
            this.corb_wp = merge(this.corb_wp) & 0xFF;
            this.run_corb();
            break;
        case R_CORBRP:
            if(merge(0) & CORBRP_RST)
            {
                this.corb_rp = 0;
                this.corb_rp_reset = true;
            }
            else
            {
                this.corb_rp_reset = false;
            }
            break;
        case R_CORBCTL:
            this.corbctl = merge(this.corbctl) & (CORBCTL_CMEIE | CORBCTL_RUN);
            this.run_corb();
            break;
        case R_CORBSTS:
            this.corbsts = clear(this.corbsts);
            this.update_irq();
            break;
        case R_RIRBLBASE:
            this.rirb_base[0] = merge(this.rirb_base[0]) & ~0x7F;
            break;
        case R_RIRBUBASE:
            this.rirb_base[1] = merge(this.rirb_base[1]);
            break;
        case R_RIRBWP:
            if(merge(0) & RIRBWP_RST) this.rirb_wp = 0;
            break;
        case R_RINTCNT:
            this.rintcnt = merge(this.rintcnt) & 0xFF;
            break;
        case R_RIRBCTL:
            this.rirbctl = merge(this.rirbctl) & 7;
            this.update_irq();
            this.run_corb();
            break;
        case R_RIRBSTS:
            this.rirbsts = clear(this.rirbsts);
            this.update_irq();
            break;
        case R_ICOI:
            this.icoi = merge(this.icoi);
            break;
        case R_ICIS:
        {
            const written = merge(0);
            if(written & ICIS_IRV) this.icis &= ~ICIS_IRV;
            if(written & ICIS_ICB && !(this.icis & ICIS_ICB))
            {
                // the immediate command: its response at once (without a
                // codec at that address it stays busy, the driver times out)
                this.icis |= ICIS_ICB;
                const response = this.send_command(this.icoi);
                if(response !== null)
                {
                    this.icii = response;
                    this.icis = this.icis & ~ICIS_ICB | ICIS_IRV;
                }
            }
            break;
        }
        case R_DPLBASE:
            this.dplbase = merge(this.dplbase) & ~0x7E;
            this.write_positions();
            break;
        case R_DPUBASE:
            this.dpubase = merge(this.dpubase);
            break;
    }
};

/**
 * GCTL: CRST leaves or enters the reset, the codec then asks for its
 * address (STATESTS)
 * @param {number} value
 */
HDAController.prototype.write_gctl = function(value)
{
    const was = this.gctl & GCTL_CRST;
    if(!(value & GCTL_CRST))
    {
        if(was) dbg_log("hd_audio: controller reset", LOG_DMA);
        this.reset_controller();
        this.gctl = 0;
        return;
    }
    this.gctl = value & (GCTL_CRST | GCTL_UNSOL);
    if(!was)
    {
        this.statests |= 1 << this.codec.address;
        this.update_irq();
    }
};

// commands to the codec

/**
 * @param {number} command
 * @return {?number} the response, null without a codec at that address
 */
HDAController.prototype.send_command = function(command)
{
    if(command >>> 28 !== this.codec.address) return null;
    return this.codec.command(command) >>> 0;
};

/** The CORB's commands up to CORBWP, their responses into the RIRB */
HDAController.prototype.run_corb = function()
{
    while(this.corbctl & CORBCTL_RUN && this.corb_rp !== this.corb_wp)
    {
        if(!this.machine.is_bus_master()) return;
        const rp = this.corb_rp + 1 & 0xFF;
        const command = this.dma_read32(ring_address(this.corb_base) + 4 * rp);
        this.corb_rp = rp;
        const response = command === null ? null : this.send_command(command);
        if(response !== null) this.respond(response);
    }
};

/**
 * A response into the RIRB; RINTFL when RINTCNT responses are there or the
 * CORB is empty
 * @param {number} response
 */
HDAController.prototype.respond = function(response)
{
    if(!(this.rirbctl & RIRBCTL_DMAEN)) return;
    const wp = this.rirb_wp + 1 & 0xFF;
    const address = ring_address(this.rirb_base) + 8 * wp;
    const entry = new Uint8Array(8);
    new DataView(entry.buffer).setUint32(0, response, true);
    // (the extended response: the codec's address, solicited)
    entry[4] = this.codec.address;
    this.dma_write(entry, address);
    this.rirb_wp = wp;
    this.rirb_count++;
    if(this.rirb_count >= (this.rintcnt || 256) || this.corb_rp === this.corb_wp)
    {
        this.rirb_count = 0;
        if(this.rirbctl & RIRBCTL_RINTCTL)
        {
            this.rirbsts |= RIRBSTS_RINTFL;
            this.update_irq();
        }
    }
};

/**
 * @param {!Array<number>} base [low, high]
 * @return {number}
 */
function ring_address(base)
{
    return (base[1] >>> 0) * 0x100000000 + (base[0] >>> 0);
}

// interrupts

/** INTSTS: the streams' bits, the controller's (CIS), and GIS */
HDAController.prototype.interrupt_status = function()
{
    let status = 0;
    if(this.rirbsts & (RIRBSTS_RINTFL | RIRBSTS_OIS) || this.statests & this.wakeen || this.corbsts & this.corbctl & CORBCTL_CMEIE)
    {
        status |= INT_CIE;
    }
    for(const stream of this.streams)
    {
        const enabled = (stream.ctl & SD_CTL_IOCE ? SD_STS_BCIS : 0) | (stream.ctl & SD_CTL_FEIE ? SD_STS_FIFOE : 0) |
            (stream.ctl & SD_CTL_DEIE ? SD_STS_DESE : 0);
        if(stream.sts & enabled) status |= 1 << stream.index;
    }
    if(status & this.intctl) status |= INT_GIE;
    return status >>> 0;
};

HDAController.prototype.update_irq = function()
{
    const level = !!(this.interrupt_status() & INT_GIE && this.intctl & INT_GIE);
    if(level === this.irq_level) return;
    this.irq_level = level;
    if(level) this.machine.raise_irq();
    else this.machine.lower_irq();
};

// streams

/**
 * @param {Object} stream
 * @param {number} local the register's offset in the descriptor
 * @param {number} bits
 * @param {number} mask
 */
HDAController.prototype.write_stream = function(stream, local, bits, mask)
{
    const merge = old => (old & ~mask | bits & mask) >>> 0;
    switch(local)
    {
        case SD_CTL:
        {
            const value = merge(stream.ctl) & 0xFF001F;
            if(value & SD_CTL_SRST)
            {
                // in reset: the descriptor to its defaults, SRST reads 1
                this.stop(stream);
                Object.assign(stream, new_stream(stream.index), { ctl: SD_CTL_SRST });
                this.update_irq();
                return;
            }
            stream.ctl = value;
            this.update_running(stream);
            this.update_irq();
            break;
        }
        case SD_STS:
            stream.sts &= ~(bits & mask & (SD_STS_BCIS | SD_STS_FIFOE | SD_STS_DESE));
            this.update_irq();
            break;
        case SD_CBL:
            if(!stream.running) stream.cbl = merge(stream.cbl);
            break;
        case SD_LVI:
            if(!stream.running) stream.lvi = merge(stream.lvi) & 0xFF;
            break;
        case SD_FIFOW:
            stream.fifow = merge(stream.fifow) & 7;
            break;
        case SD_FMT:
            if(!stream.running) stream.fmt = merge(stream.fmt) & 0x7F7F;
            break;
        case SD_BDPL:
            if(!stream.running) stream.bdpl = merge(stream.bdpl) & ~0x7F;
            break;
        case SD_BDPU:
            if(!stream.running) stream.bdpu = merge(stream.bdpu);
            break;
    }
};

/**
 * The stream runs while RUN is set and SSYNC does not hold it
 * @param {Object} stream
 */
HDAController.prototype.update_running = function(stream)
{
    const run = !!(stream.ctl & SD_CTL_RUN) && !(this.ssync & 1 << stream.index);
    if(run === stream.running) return;
    if(run)
    {
        stream.running = true;
        stream.started = this.machine.now();
        stream.played = 0;
        if(stream.output)
        {
            const { rate } = decode_format(stream.fmt);
            if(rate !== this.speaker_rate)
            {
                this.speaker_rate = rate;
                this.machine.set_sampling_rate(rate);
            }
            this.machine.enable_output();
        }
        dbg_log("hd_audio: stream " + stream.index + " runs: format " + h(stream.fmt, 4) + ", " + stream.cbl + " bytes in " +
            (stream.lvi + 1) + " descriptors", LOG_DMA);
        // (what is due now: nothing yet; the timer plays it)
        this.machine.wake();
    }
    else
    {
        this.play(stream, this.machine.now());
        this.stop(stream);
    }
};

/** @param {Object} stream */
HDAController.prototype.stop = function(stream)
{
    if(!stream.running) return;
    stream.running = false;
    if(stream.output && !this.streams.some(other => other !== stream && other.running && other.output))
    {
        this.machine.disable_output();
    }
};

/**
 * The machine's timers run: each running stream plays what is due
 * @param {number} now
 * @return {number} milliseconds until it needs to run again
 */
HDAController.prototype.timer = function(now)
{
    let next = 100;
    for(const stream of this.streams)
    {
        if(!stream.running) continue;
        this.play(stream, now);
        next = Math.min(next, this.time_to_boundary(stream, now));
    }
    return next;
};

/**
 * Until the current descriptor's end (its completion interrupt), at most
 * 10 ms (the speaker's next samples)
 * @param {Object} stream
 * @param {number} now
 * @return {number}
 */
HDAController.prototype.time_to_boundary = function(stream, now)
{
    const { rate, bytes, channels } = decode_format(stream.fmt);
    const entry = this.descriptor(stream, stream.entry);
    const left = entry ? Math.max(0, entry.length - stream.offset) / (bytes * channels) : 0;
    const due_at = stream.started + (stream.played + left) / rate * 1000;
    return Math.max(0.5, Math.min(10, due_at - now));
};

/**
 * A buffer descriptor: address, length, IOC
 * @param {Object} stream
 * @param {number} index
 * @return {?{address: number, length: number, ioc: boolean}}
 */
HDAController.prototype.descriptor = function(stream, index)
{
    const base = (stream.bdpu >>> 0) * 0x100000000 + (stream.bdpl >>> 0);
    const bytes = this.dma_read(base + 16 * index, 16);
    if(!bytes) return null;
    const view = new DataView(bytes.buffer);
    return {
        address: view.getUint32(4, true) * 0x100000000 + view.getUint32(0, true),
        length: view.getUint32(8, true),
        ioc: !!(view.getUint32(12, true) & 1),
    };
};

/**
 * Read (output) what the stream's time has come for, from its descriptors
 * in order: LPIB, the completion interrupts, the samples to the speaker
 * @param {Object} stream
 * @param {number} now
 */
HDAController.prototype.play = function(stream, now)
{
    if(!stream.running || !stream.output) return;
    if(!this.machine.is_bus_master()) return;
    const { rate, bytes, channels } = decode_format(stream.fmt);
    const frame_bytes = bytes * channels;
    let due = Math.floor((now - stream.started) / 1000 * rate) - stream.played;
    if(due <= 0) return;
    if(due > rate * MAX_PLAY_MS / 1000)
    {
        // (the host stalled: the stream's clock goes on, the samples of the gap are not kept)
        const skip = due - Math.floor(rate * MAX_PLAY_MS / 1000);
        stream.started += skip / rate * 1000;
        due -= skip;
    }
    const chunks = [];
    let interrupt = false, guard = 0;
    while(due > 0 && guard++ < 1024)
    {
        const entry = this.descriptor(stream, stream.entry);
        if(!entry || entry.length < frame_bytes)
        {
            // a bad list: descriptor error, the stream stops
            stream.sts |= SD_STS_DESE;
            stream.ctl &= ~SD_CTL_RUN;
            this.stop(stream);
            interrupt = true;
            break;
        }
        const take = Math.min(due * frame_bytes, entry.length - stream.offset);
        const count = take - take % frame_bytes;
        if(count > 0)
        {
            const data = this.dma_read(entry.address + stream.offset, count);
            chunks.push(data || new Uint8Array(count));
            stream.offset += count;
            stream.played += count / frame_bytes;
            due -= count / frame_bytes;
            stream.lpib += count;
            if(stream.lpib >= stream.cbl) stream.lpib = stream.cbl ? stream.lpib % stream.cbl : 0;
        }
        if(stream.offset + frame_bytes > entry.length)
        {
            // the descriptor is done
            if(entry.ioc)
            {
                stream.sts |= SD_STS_BCIS;
                interrupt = true;
            }
            stream.offset = 0;
            stream.entry = stream.entry >= stream.lvi ? 0 : stream.entry + 1;
        }
    }
    this.write_positions();
    if(chunks.length) this.output(stream, chunks, bytes, channels);
    if(interrupt) this.update_irq();
};

/** The DMA position buffer: each stream's LPIB (DPLBASE.enable) */
HDAController.prototype.write_positions = function()
{
    if(!(this.dplbase & DPLBASE_ENABLE) || !this.machine.is_bus_master()) return;
    const base = (this.dpubase >>> 0) * 0x100000000 + ((this.dplbase & ~0x7F) >>> 0);
    const bytes = new Uint8Array(8 * STREAMS);
    const view = new DataView(bytes.buffer);
    for(const stream of this.streams) view.setUint32(8 * stream.index, stream.lpib, true);
    this.dma_write(bytes, base);
};

/**
 * Samples to the speaker, through the codec's DAC: its stream, gains, the pin
 * @param {Object} stream
 * @param {!Array<!Uint8Array>} chunks
 * @param {number} bytes per sample
 * @param {number} channels
 */
HDAController.prototype.output = function(stream, chunks, bytes, channels)
{
    const tag = stream.ctl >>> 20 & 0xF;
    const gains = this.codec.output_for(tag) || [0, 0];
    let frames = 0;
    for(const chunk of chunks) frames += chunk.length / (bytes * channels);
    const left = new Float32Array(frames), right = new Float32Array(frames);
    // (the DAC's first channel and the next)
    const first = Math.min(this.codec.channel, channels - 1), second = Math.min(this.codec.channel + 1, channels - 1);
    let at = 0;
    for(const chunk of chunks)
    {
        const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
        for(let offset = 0; offset < chunk.length; offset += bytes * channels, at++)
        {
            left[at] = sample(view, offset + first * bytes, bytes) * gains[0];
            right[at] = sample(view, offset + second * bytes, bytes) * gains[1];
        }
    }
    this.machine.output(left, right, { "stream": stream.index, "format": stream.fmt, "tag": tag, "chunks": chunks });
};

/**
 * @param {!DataView} view
 * @param {number} offset
 * @param {number} bytes
 * @return {number} in [-1, 1)
 */
function sample(view, offset, bytes)
{
    if(bytes === 2) return view.getInt16(offset, true) / 32768;
    if(bytes === 4) return view.getInt32(offset, true) / 2147483648;
    return (view.getUint8(offset) - 128) / 128;
}

// DMA

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array}
 */
HDAController.prototype.dma_read = function(address, length)
{
    try
    {
        return this.machine.read_physical(address, length);
    }
    catch(e)
    {
        dbg_log("hd_audio: DMA read outside memory at " + h(address, 9), LOG_DMA);
        return null;
    }
};

/**
 * @param {number} address
 * @return {?number}
 */
HDAController.prototype.dma_read32 = function(address)
{
    const bytes = this.dma_read(address, 4);
    return bytes ? (bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) >>> 0 : null;
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 */
HDAController.prototype.dma_write = function(bytes, address)
{
    try
    {
        this.machine.write_physical(bytes, address);
    }
    catch(e)
    {
        dbg_log("hd_audio: DMA write outside memory at " + h(address, 9), LOG_DMA);
    }
};

/** The wall clock (24 MHz) since the controller's reset */
HDAController.prototype.wallclock = function()
{
    return Math.floor((this.machine.now() - this.wall_base) * WALLCLK_PER_MS) >>> 0;
};

// snapshots

HDAController.prototype.get_state = function()
{
    const now = this.machine.now();
    return [
        new Int32Array([this.gctl, this.wakeen, this.statests, this.gsts, this.intctl, this.ssync,
            this.corb_base[0], this.corb_base[1], this.corb_wp, this.corb_rp, +this.corb_rp_reset, this.corbctl, this.corbsts,
            this.rirb_base[0], this.rirb_base[1], this.rirb_wp, this.rintcnt, this.rirbctl, this.rirbsts, this.rirb_count,
            this.icoi, this.icii, this.icis, this.dplbase, this.dpubase, this.bar0, +this.irq_level, this.speaker_rate]),
        // (times relative to now: the machine clock is restored with the snapshot)
        now - this.wall_base,
        this.streams.map(s => [s.ctl, s.sts, s.lpib, s.cbl, s.lvi, s.fifow, s.fmt, s.bdpl, s.bdpu,
            s.entry, s.offset, now - s.started, s.played, +s.running]),
        this.codec.get_state(),
    ];
};

HDAController.prototype.set_state = function(state)
{
    const r = state[0];
    [this.gctl, this.wakeen, this.statests, this.gsts, this.intctl, this.ssync] = r;
    this.corb_base = [r[6], r[7]];
    [this.corb_wp, this.corb_rp] = [r[8], r[9]];
    this.corb_rp_reset = !!r[10];
    [this.corbctl, this.corbsts] = [r[11], r[12]];
    this.rirb_base = [r[13], r[14]];
    [this.rirb_wp, this.rintcnt, this.rirbctl, this.rirbsts, this.rirb_count] = r.slice(15, 20);
    [this.icoi, this.icii, this.icis, this.dplbase, this.dpubase] = r.slice(20, 25);
    this.bar0 = r[25] >>> 0;
    this.irq_level = !!r[26];
    this.speaker_rate = r[27];
    const now = this.machine.now();
    this.wall_base = now - state[1];
    this.streams = state[2].map((s, index) => Object.assign(new_stream(index), {
        ctl: s[0], sts: s[1], lpib: s[2], cbl: s[3], lvi: s[4], fifow: s[5], fmt: s[6], bdpl: s[7], bdpu: s[8],
        entry: s[9], offset: s[10], started: now - s[11], played: s[12], running: !!s[13],
    }));
    this.codec.set_state(state[3]);
    // (the speaker starts again with the stream's samples from now on)
    if(this.streams.some(s => s.running && s.output))
    {
        this.machine.set_sampling_rate(this.speaker_rate);
        this.machine.enable_output();
    }
    if(this.irq_level) this.machine.raise_irq();
    else this.machine.lower_irq();
    this.update_decode();
};
                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/audio_devices/hd_audio/plugin.js                                                     0000644 0000000 0000000 00000001422 00000000000 016665  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // audio_device "hd_audio" -- an Intel HD Audio controller (ICH6 on i440FX,
// ICH9 on Q35) with a generic output codec, the sound card Windows Vista to
// 11 and Linux have drivers for. Built into build/v86-hd-audio.js; from the
// source tree, src/device_plugin.js imports this file directly.

import { HDAController } from "./controller.js";
import { register_audio_device } from "../machine.js";

register_audio_device({
    "name": "hd_audio",
    "create": (handle, options) =>
    {
        const controller = new HDAController(handle);
        return {
            "controller": controller,
            "reset": () => controller.reset(),
            "get_state": () => controller.get_state(),
            "set_state": state => controller.set_state(state),
        };
    },
});
                                                                                                                                                                                                                                              source/v64/src/audio_devices/machine.js                                                             0000644 0000000 0000000 00000004410 00000000000 015217  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A sound card plugin's view of the machine (audio_device "sb16", "hd_audio"): the
// device handle of src/device_machine.js plus the speaker, the dac-* messages
// of the bus (src/browser/speaker.js; src/cpu.js, create_audio_plugin).
// Built into each card's plugin file.

import { DeviceMachine, register_device_plugin } from "../device_machine.js";

/**
 * Make a card known to v86 (its plugin file calls this when it loads)
 * @param {!Object} descriptor { "name", "create": function(handle, options) }
 */
export function register_audio_device(descriptor)
{
    register_device_plugin("V86AudioDevices", descriptor);
}

/**
 * @constructor
 * @extends {DeviceMachine}
 * @param {!Object} handle
 */
export function AudioMachine(handle)
{
    DeviceMachine.call(this, handle);

    /** @const @type {!Object} */
    this.audio = handle["audio"];
}

AudioMachine.prototype = Object.create(DeviceMachine.prototype);

/**
 * Samples played: to the speaker (two channels in [-1, 1)), and as the
 * stream's own bytes to "hd-audio-pcm" listeners (tests)
 * @param {!Float32Array} left
 * @param {!Float32Array} right
 * @param {!Object} pcm { "stream", "format", "tag", "chunks" }
 */
AudioMachine.prototype.output = function(left, right, pcm)
{
    this.audio["send"](left, right);
    this.audio["pcm"](pcm);
};

/** @param {number} rate the samples' rate from now on */
AudioMachine.prototype.set_sampling_rate = function(rate)
{
    this.audio["set_sampling_rate"](rate);
};

/** A stream plays: the speaker takes samples */
AudioMachine.prototype.enable_output = function()
{
    this.audio["enable"]();
};

/** No stream plays */
AudioMachine.prototype.disable_output = function()
{
    this.audio["disable"]();
};

/**
 * A message to the speaker (src/browser/speaker.js: dac-*, mixer-*), for a
 * card that speaks its protocol itself (the SB16)
 * @param {string} name
 * @param {*=} data
 * @param {!Array=} transfer
 */
AudioMachine.prototype.bus_send = function(name, data, transfer)
{
    this.audio["bus_send"](name, data, transfer);
};

/**
 * The speaker's messages to the card (dac-request-data, speaker-has-initialized)
 * @param {string} name
 * @param {function(*)} handler
 */
AudioMachine.prototype.bus_register = function(name, handler)
{
    this.audio["bus_register"](name, handler);
};
                                                                                                                                                                                                                                                        source/v64/src/audio_devices/sb16/plugin.js                                                         0000644 0000000 0000000 00000001417 00000000000 015670  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // audio_device "sb16" (the default) -- a Sound Blaster 16 on the ISA bus.
// Built into build/v86-sb16.js; from the source tree, src/device_plugin.js
// imports this file directly. Its state is the core SB16's of before (a
// snapshot's untagged state[61] is read as it is: src/device_plugin.js). No
// reset hook: the machine's reset left the SB16 as it was before as well.

import { SB16 } from "./sb16.js";
import { AudioMachine, register_audio_device } from "../machine.js";

register_audio_device({
    "name": "sb16",
    "create": handle =>
    {
        const card = new SB16(new AudioMachine(handle));
        return {
            "card": card,
            "get_state": () => card.get_state(),
            "set_state": state => card.set_state(state),
        };
    },
});
                                                                                                                                                                                                                                                 source/v64/src/audio_devices/sb16/sb16.js                                                           0000644 0000000 0000000 00000153034 00000000000 015150  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // audio_device "sb16" (the default) -- a Sound Blaster 16: the DSP, the
// mixer, the MPU-401 and OPL ports, its 8-bit and 16-bit DMA channels and
// IRQ 5 on the ISA bus. A plugin since M1 (docs/modern-pc-devices-plan.md):
// its machine is an AudioMachine (src/audio_devices/machine.js) with the ISA
// part of the handle (src/device_machine.js); its state is the one the
// core's SB16 had, field for field, so that snapshots from before read as
// they are. It speaks the speaker's protocol itself (src/browser/speaker.js:
// the speaker asks for data, "dac-request-data").

import {
    LOG_SB16,
    MIXER_CHANNEL_BOTH, MIXER_CHANNEL_LEFT, MIXER_CHANNEL_RIGHT,
    MIXER_SRC_PCSPEAKER, MIXER_SRC_DAC, MIXER_SRC_MASTER,
} from "../../const.js";
import { h } from "../../lib.js";
import { dbg_log } from "../../log.js";
import { ByteQueue, FloatQueue } from "../../lib.js";

// For Types Only
import { AudioMachine } from "../machine.js";

// Useful documentation, articles, and source codes for reference:
// ===============================================================
//
// Official Hardware Programming Guide
// -> https://pdos.csail.mit.edu/6.828/2011/readings/hardware/SoundBlaster.pdf
//
// Official Yamaha YMF262 Manual
// -> http://map.grauw.nl/resources/sound/yamaha_ymf262.pdf
//
// OPL3 Programming Guide
// -> http://www.fit.vutbr.cz/~arnost/opl/opl3.html
//
// DOSBox
// -> https://sourceforge.net/p/dosbox/code-0/HEAD/tree/dosbox/branches/mamesound/src/hardware/sblaster.cpp
// -> https://github.com/duganchen/dosbox/blob/master/src/hardware/sblaster.cpp
// -> https://github.com/joncampbell123/dosbox-x/blob/master/src/hardware/sblaster.cpp
//
// QEMU
// -> https://github.com/qemu/qemu/blob/master/hw/audio/sb16.c
// -> https://github.com/hackndev/qemu/blob/master/hw/sb16.c
//
// VirtualBox
// -> https://www.virtualbox.org/svn/vbox/trunk/src/VBox/Devices/Audio/DevSB16.cpp
// -> https://github.com/mdaniel/virtualbox-org-svn-vbox-trunk/blob/master/src/VBox/Devices/Audio/DevSB16.cpp

const
    // Used for drivers to identify device (DSP command 0xE3).
    DSP_COPYRIGHT = "COPYRIGHT (C) CREATIVE TECHNOLOGY LTD, 1992.",

    // Value of the current DSP command that indicates that the
    // next command/data write in port 2xC should be interpreted
    // as a command number.
    DSP_NO_COMMAND = 0,

    // Size (bytes) of the DSP write/read buffers
    DSP_BUFSIZE = 64,

    // Size (bytes) of the buffers containing floating point linear PCM audio.
    DSP_DACSIZE = 65536,

    // Size (bytes) of the buffer in which DMA transfers are temporarily
    // stored before being processed.
    SB_DMA_BUFSIZE = 65536,

    // Number of samples to attempt to retrieve per transfer.
    SB_DMA_BLOCK_SAMPLES = 1024,

    // A host that has not asked for data this long is not listening: the
    // transfer keeps the machine's time on its own (SB16.prototype.timer).
    DAC_HOST_TIMEOUT_MS = 250,

    // At most this many blocks per timer call, as a bound on a transfer that
    // makes no progress (a DMA address outside of memory).
    DAC_CATCH_UP_BLOCKS = 64,

    // Usable DMA channels.
    SB_DMA0 = 0,
    SB_DMA1 = 1,
    SB_DMA3 = 3,
    SB_DMA5 = 5,
    SB_DMA6 = 6,
    SB_DMA7 = 7,

    // Default DMA channels.
    SB_DMA_CHANNEL_8BIT = SB_DMA1,
    SB_DMA_CHANNEL_16BIT = SB_DMA5,

    // Usable IRQ channels.
    SB_IRQ2 = 2,
    SB_IRQ5 = 5,
    SB_IRQ7 = 7,
    SB_IRQ10 = 10,

    // Default IRQ channel.
    SB_IRQ = SB_IRQ5,

    // Indices to the irq_triggered register.
    SB_IRQ_8BIT = 0x1,
    SB_IRQ_16BIT = 0x2,
    SB_IRQ_MIDI = 0x1,
    SB_IRQ_MPU = 0x4;


// Probably less efficient, but it's more maintainable, instead
// of having a single large unorganised and decoupled table.
var DSP_COMMAND_SIZES = new Uint8Array(256);
var DSP_COMMAND_HANDLERS = [];
var MIXER_READ_HANDLERS = [];
var MIXER_WRITE_HANDLERS = [];
var MIXER_REGISTER_IS_LEGACY = new Uint8Array(256);
var FM_HANDLERS = [];


/**
 * Sound Blaster 16 Emulator, or so it seems.
 * @constructor
 * @param {AudioMachine} machine
 */
export function SB16(machine)
{
    /** @const @type {AudioMachine} */
    this.machine = machine;

    // I/O Buffers.
    this.write_buffer = new ByteQueue(DSP_BUFSIZE);
    this.read_buffer = new ByteQueue(DSP_BUFSIZE);
    this.read_buffer_lastvalue = 0;

    // Current DSP command info.
    this.command = DSP_NO_COMMAND;
    this.command_size = 0;

    // Mixer.
    this.mixer_current_address = 0;
    this.mixer_registers = new Uint8Array(256);
    this.mixer_reset();

    // Dummy status and test registers.
    this.dummy_speaker_enabled = false;
    this.test_register = 0;

    // DSP state.
    this.dsp_highspeed = false;
    this.dsp_stereo = false;
    this.dsp_16bit = false;
    this.dsp_signed = false;

    // DAC buffer.
    // The final destination for audio data before being sent off
    // to Web Audio APIs.
    // Format:
    // Floating precision linear PCM, nominal between -1 and 1.
    this.dac_buffers = [
      new FloatQueue(DSP_DACSIZE),
      new FloatQueue(DSP_DACSIZE),
    ];

    // Direct Memory Access transfer info.
    this.dma_sample_count = 0;
    this.dma_bytes_count = 0;
    this.dma_bytes_left = 0;
    this.dma_bytes_block = 0;
    this.dma_irq = 0;
    this.dma_channel = 0;
    this.dma_channel_8bit = SB_DMA_CHANNEL_8BIT;
    this.dma_channel_16bit = SB_DMA_CHANNEL_16BIT;
    this.dma_autoinit = false;
    this.dma_buffer = new ArrayBuffer(SB_DMA_BUFSIZE);
    this.dma_buffer_int8 = new Int8Array(this.dma_buffer);
    this.dma_buffer_uint8 = new Uint8Array(this.dma_buffer);
    this.dma_buffer_int16 = new Int16Array(this.dma_buffer);
    this.dma_buffer_uint16 = new Uint16Array(this.dma_buffer);
    this.dma_waiting_transfer = false;
    this.dma_paused = false;
    // The machine time up to which the transfer has played (-1: none yet),
    // and the time of the host's last request (SB16.prototype.timer)
    this.dma_clock = -1;
    this.dac_request_time = -Infinity;
    this.sampling_rate = 22050;
    machine.bus_send("dac-tell-sampling-rate", this.sampling_rate);
    this.bytes_per_sample = 1;

    // DMA identification data.
    this.e2_value = 0xAA;
    this.e2_count = 0;

    // ASP data: not understood by me.
    this.asp_registers = new Uint8Array(256);

    // MPU.
    this.mpu_read_buffer = new ByteQueue(DSP_BUFSIZE);
    this.mpu_read_buffer_lastvalue = 0;

    // FM Synthesizer.
    this.fm_current_address0 = 0;
    this.fm_current_address1 = 0;
    this.fm_waveform_select_enable = false;

    // Interrupts.
    this.irq = SB_IRQ;
    this.irq_triggered = new Uint8Array(0x10);

    // IO Ports.
    // http://homepages.cae.wisc.edu/~brodskye/sb16doc/sb16doc.html#DSPPorts
    // https://pdos.csail.mit.edu/6.828/2011/readings/hardware/SoundBlaster.pdf

    machine.register_read_consecutive(0x220, this,
        this.port2x0_read, this.port2x1_read, this.port2x2_read, this.port2x3_read);
    machine.register_read_consecutive(0x388, this,
        this.port2x0_read, this.port2x1_read);

    machine.register_read_consecutive(0x224, this,
        this.port2x4_read, this.port2x5_read);

    machine.register_read(0x226, this, this.port2x6_read);
    machine.register_read(0x227, this, this.port2x7_read);
    machine.register_read(0x228, this, this.port2x8_read);
    machine.register_read(0x229, this, this.port2x9_read);

    machine.register_read(0x22A, this, this.port2xA_read);
    machine.register_read(0x22B, this, this.port2xB_read);
    machine.register_read(0x22C, this, this.port2xC_read);
    machine.register_read(0x22D, this, this.port2xD_read);

    machine.register_read_consecutive(0x22E, this,
        this.port2xE_read, this.port2xF_read);

    machine.register_write_consecutive(0x220, this,
        this.port2x0_write, this.port2x1_write, this.port2x2_write, this.port2x3_write);
    machine.register_write_consecutive(0x388, this,
        this.port2x0_write, this.port2x1_write);

    machine.register_write_consecutive(0x224, this,
        this.port2x4_write, this.port2x5_write);

    machine.register_write(0x226, this, this.port2x6_write);
    machine.register_write(0x227, this, this.port2x7_write);

    machine.register_write_consecutive(0x228, this,
        this.port2x8_write, this.port2x9_write);

    machine.register_write(0x22A, this, this.port2xA_write);
    machine.register_write(0x22B, this, this.port2xB_write);
    machine.register_write(0x22C, this, this.port2xC_write);
    machine.register_write(0x22D, this, this.port2xD_write);
    machine.register_write(0x22E, this, this.port2xE_write);
    machine.register_write(0x22F, this, this.port2xF_write);

    machine.register_read_consecutive(0x330, this, this.port3x0_read, this.port3x1_read);
    machine.register_write_consecutive(0x330, this, this.port3x0_write, this.port3x1_write);

    machine.dma_on_unmask(channel => this.dma_on_unmask(channel));

    machine.bus_register("dac-request-data", () => this.dac_handle_request());
    machine.bus_register("speaker-has-initialized", () => this.mixer_reset());
    machine.bus_send("speaker-confirm-initialized");

    // (the transfer's own pace while the host does not ask: SB16.prototype.timer)
    machine.add_timer(now => this.timer(now));

    this.dsp_reset();
}

//
// General
//

SB16.prototype.dsp_reset = function()
{
    this.write_buffer.clear();
    this.read_buffer.clear();

    this.command = DSP_NO_COMMAND;
    this.command_size = 0;

    this.dummy_speaker_enabled = false;
    this.test_register = 0;

    this.dsp_highspeed = false;
    this.dsp_stereo = false;
    this.dsp_16bit = false;
    this.dsp_signed = false;

    this.dac_buffers[0].clear();
    this.dac_buffers[1].clear();

    this.dma_sample_count = 0;
    this.dma_bytes_count = 0;
    this.dma_bytes_left = 0;
    this.dma_bytes_block = 0;
    this.dma_irq = 0;
    this.dma_channel = 0;
    this.dma_autoinit = false;
    this.dma_buffer_uint8.fill(0);
    this.dma_waiting_transfer = false;
    this.dma_paused = false;
    this.dma_clock = -1;

    this.e2_value = 0xAA;
    this.e2_count = 0;

    this.sampling_rate = 22050;
    this.bytes_per_sample = 1;

    this.lower_irq(SB_IRQ_8BIT);
    this.irq_triggered.fill(0);

    this.asp_registers.fill(0);
    this.asp_registers[5] = 0x01;
    this.asp_registers[9] = 0xF8;
};

SB16.prototype.get_state = function()
{
    var state = [];

    // state[0] = this.write_buffer;
    // state[1] = this.read_buffer;
    state[2] = this.read_buffer_lastvalue;

    state[3] = this.command;
    state[4] = this.command_size;

    state[5] = this.mixer_current_address;
    state[6] = this.mixer_registers;

    state[7] = this.dummy_speaker_enabled;
    state[8] = this.test_register;

    state[9] = this.dsp_highspeed;
    state[10] = this.dsp_stereo;
    state[11] = this.dsp_16bit;
    state[12] = this.dsp_signed;

    // state[13] = this.dac_buffers;
    //state[14]

    state[15] = this.dma_sample_count;
    state[16] = this.dma_bytes_count;
    state[17] = this.dma_bytes_left;
    state[18] = this.dma_bytes_block;
    state[19] = this.dma_irq;
    state[20] = this.dma_channel;
    state[21] = this.dma_channel_8bit;
    state[22] = this.dma_channel_16bit;
    state[23] = this.dma_autoinit;
    state[24] = this.dma_buffer_uint8;
    state[25] = this.dma_waiting_transfer;
    state[26] = this.dma_paused;
    state[27] = this.sampling_rate;
    state[28] = this.bytes_per_sample;

    state[29] = this.e2_value;
    state[30] = this.e2_count;

    state[31] = this.asp_registers;

    // state[32] = this.mpu_read_buffer;
    state[33] = this.mpu_read_buffer_last_value;

    state[34] = this.irq;
    state[35] = this.irq_triggered;
    //state[36]

    return state;
};

SB16.prototype.set_state = function(state)
{
    // this.write_buffer = state[0];
    // this.read_buffer = state[1];
    this.read_buffer_lastvalue = state[2];

    this.command = state[3];
    this.command_size = state[4];

    this.mixer_current_address = state[5];
    this.mixer_registers = state[6];
    this.mixer_full_update();

    this.dummy_speaker_enabled = state[7];
    this.test_register = state[8];

    this.dsp_highspeed = state[9];
    this.dsp_stereo = state[10];
    this.dsp_16bit = state[11];
    this.dsp_signed = state[12];

    // Host audio and unsaved DAC samples belong to the discarded timeline.
    this.machine.bus_send("dac-reset");
    this.dac_buffers[0].clear();
    this.dac_buffers[1].clear();
    //state[14]

    this.dma_sample_count = state[15];
    this.dma_bytes_count = state[16];
    this.dma_bytes_left = state[17];
    this.dma_bytes_block = state[18];
    this.dma_irq = state[19];
    this.dma_channel = state[20];
    this.dma_channel_8bit = state[21];
    this.dma_channel_16bit = state[22];
    this.dma_autoinit = state[23];
    this.dma_buffer_uint8 = state[24];
    this.dma_waiting_transfer = state[25];
    this.dma_paused = state[26];
    this.dma_clock = -1;
    this.sampling_rate_change(state[27]);
    this.bytes_per_sample = state[28];

    this.e2_value = state[29];
    this.e2_count = state[30];

    this.asp_registers = state[31];

    // this.mpu_read_buffer = state[32];
    this.mpu_read_buffer_last_value = state[33];

    this.irq = state[34];
    this.irq_triggered = state[35];
    //state[36];

    this.dma_buffer = this.dma_buffer_uint8.buffer;
    this.dma_buffer_int8 = new Int8Array(this.dma_buffer);
    this.dma_buffer_int16 = new Int16Array(this.dma_buffer);
    this.dma_buffer_uint16 = new Uint16Array(this.dma_buffer);

    if(this.dma_paused)
    {
        this.machine.bus_send("dac-disable");
    }
    else
    {
        this.machine.bus_send("dac-enable");
    }
};

//
// I/O handlers
//

SB16.prototype.port2x0_read = function()
{
    dbg_log("220 read: fm music status port (unimplemented)", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x1_read = function()
{
    dbg_log("221 read: fm music data port (write only)", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x2_read = function()
{
    dbg_log("222 read: advanced fm music status port (unimplemented)", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x3_read = function()
{
    dbg_log("223 read: advanced music data port (write only)", LOG_SB16);
    return 0xFF;
};

// Mixer Address Port.
SB16.prototype.port2x4_read = function()
{
    dbg_log("224 read: mixer address port", LOG_SB16);
    return this.mixer_current_address;
};

// Mixer Data Port.
SB16.prototype.port2x5_read = function()
{
    dbg_log("225 read: mixer data port", LOG_SB16);
    return this.mixer_read(this.mixer_current_address);
};

SB16.prototype.port2x6_read = function()
{
    dbg_log("226 read: (write only)", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x7_read = function()
{
    dbg_log("227 read: undocumented", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x8_read = function()
{
    dbg_log("228 read: fm music status port (unimplemented)", LOG_SB16);
    return 0xFF;
};

SB16.prototype.port2x9_read = function()
{
    dbg_log("229 read: fm music data port (write only)", LOG_SB16);
    return 0xFF;
};

// Read Data.
// Used to access in-bound DSP data.
SB16.prototype.port2xA_read = function()
{
    dbg_log("22A read: read data", LOG_SB16);
    if(this.read_buffer.length)
    {
        this.read_buffer_lastvalue = this.read_buffer.shift();
    }
    dbg_log(" <- " + this.read_buffer_lastvalue + " " + h(this.read_buffer_lastvalue) + " '" + String.fromCharCode(this.read_buffer_lastvalue) + "'", LOG_SB16);
    return this.read_buffer_lastvalue;
};

SB16.prototype.port2xB_read = function()
{
    dbg_log("22B read: undocumented", LOG_SB16);
    return 0xFF;
};

// Write-Buffer Status.
// Indicates whether the DSP is ready to accept commands or data.
SB16.prototype.port2xC_read = function()
{
    dbg_log("22C read: write-buffer status", LOG_SB16);
    // Always return ready (bit-7 set to low)
    return 0x7F;
};

SB16.prototype.port2xD_read = function()
{
    dbg_log("22D read: undocumented", LOG_SB16);
    return 0xFF;
};

// Read-Buffer Status.
// Indicates whether there is any in-bound data available for reading.
// Also used to acknowledge DSP 8-bit interrupt.
SB16.prototype.port2xE_read = function()
{
    dbg_log("22E read: read-buffer status / irq 8bit ack.", LOG_SB16);
    if(this.irq_triggered[SB_IRQ_8BIT])
    {
        this.lower_irq(SB_IRQ_8BIT);
    }
    var ready = this.read_buffer.length && !this.dsp_highspeed;
    return (ready << 7) | 0x7F;
};

// DSP 16-bit interrupt acknowledgement.
SB16.prototype.port2xF_read = function()
{
    dbg_log("22F read: irq 16bit ack", LOG_SB16);
    this.lower_irq(SB_IRQ_16BIT);
    return 0;
};


// FM Address Port - primary register.
SB16.prototype.port2x0_write = function(value)
{
    dbg_log("220 write: (unimplemented) fm register 0 address = " + h(value), LOG_SB16);
    this.fm_current_address0 = 0;
};

// FM Data Port - primary register.
SB16.prototype.port2x1_write = function(value)
{
    dbg_log("221 write: (unimplemented) fm register 0 data = " + h(value), LOG_SB16);
    var handler = FM_HANDLERS[this.fm_current_address0];
    if(!handler)
    {
        handler = this.fm_default_write;
    }
    handler.call(this, value, 0, this.fm_current_address0);
};

// FM Address Port - secondary register.
SB16.prototype.port2x2_write = function(value)
{
    dbg_log("222 write: (unimplemented) fm register 1 address = " + h(value), LOG_SB16);
    this.fm_current_address1 = 0;
};

// FM Data Port - secondary register.
SB16.prototype.port2x3_write = function(value)
{
    dbg_log("223 write: (unimplemented) fm register 1 data =" + h(value), LOG_SB16);
    var handler = FM_HANDLERS[this.fm_current_address1];
    if(!handler)
    {
        handler = this.fm_default_write;
    }
    handler.call(this, value, 1, this.fm_current_address1);
};

// Mixer Address Port.
SB16.prototype.port2x4_write = function(value)
{
    dbg_log("224 write: mixer address = " + h(value), LOG_SB16);
    this.mixer_current_address = value;
};

// Mixer Data Port.
SB16.prototype.port2x5_write = function(value)
{
    dbg_log("225 write: mixer data = " + h(value), LOG_SB16);
    this.mixer_write(this.mixer_current_address, value);
};

// Reset.
// Used to reset the DSP to its default state and to exit highspeed mode.
SB16.prototype.port2x6_write = function(yesplease)
{
    dbg_log("226 write: reset = " + h(yesplease), LOG_SB16);

    if(this.dsp_highspeed)
    {
        dbg_log(" -> exit highspeed", LOG_SB16);
        this.dsp_highspeed = false;
    }
    else if(yesplease)
    {
        dbg_log(" -> reset", LOG_SB16);
        this.dsp_reset();
    }

    // Signal completion.
    this.read_buffer.clear();
    this.read_buffer.push(0xAA);
};

SB16.prototype.port2x7_write = function(value)
{
    dbg_log("227 write: undocumented", LOG_SB16);
};

SB16.prototype.port2x8_write = function(value)
{
    dbg_log("228 write: fm music register port (unimplemented)", LOG_SB16);
};

SB16.prototype.port2x9_write = function(value)
{
    dbg_log("229 write: fm music data port (unimplemented)", LOG_SB16);
};

SB16.prototype.port2xA_write = function(value)
{
    dbg_log("22A write: dsp read data port (read only)", LOG_SB16);
};

SB16.prototype.port2xB_write = function(value)
{
    dbg_log("22B write: undocumented", LOG_SB16);
};

// Write Command/Data.
// Used to send commands or data to the DSP.
SB16.prototype.port2xC_write = function(value)
{
    dbg_log("22C write: write command/data", LOG_SB16);

    if(this.command === DSP_NO_COMMAND)
    {
        // New command.
        dbg_log("22C write: command = " + h(value), LOG_SB16);
        this.command = value;
        this.write_buffer.clear();
        this.command_size = DSP_COMMAND_SIZES[value];
    }
    else
    {
        // More data for current command.
        dbg_log("22C write: data: " + h(value), LOG_SB16);
        this.write_buffer.push(value);
    }

    // Perform command when we have all the needed data.
    if(this.write_buffer.length >= this.command_size)
    {
        this.command_do();
    }
};

SB16.prototype.port2xD_write = function(value)
{
    dbg_log("22D write: undocumented", LOG_SB16);
};

SB16.prototype.port2xE_write = function(value)
{
    dbg_log("22E write: dsp read buffer status (read only)", LOG_SB16);
};

SB16.prototype.port2xF_write = function(value)
{
    dbg_log("22F write: undocumented", LOG_SB16);
};


// MPU UART Mode - Data Port
SB16.prototype.port3x0_read = function()
{
    dbg_log("330 read: mpu data", LOG_SB16);

    if(this.mpu_read_buffer.length)
    {
        this.mpu_read_buffer_lastvalue = this.mpu_read_buffer.shift();
    }
    dbg_log(" <- " + h(this.mpu_read_buffer_lastvalue), LOG_SB16);

    return this.mpu_read_buffer_lastvalue;
};
SB16.prototype.port3x0_write = function(value)
{
    dbg_log("330 write: mpu data (unimplemented) : " + h(value), LOG_SB16);
};

// MPU UART Mode - Status Port
SB16.prototype.port3x1_read = function()
{
    dbg_log("331 read: mpu status", LOG_SB16);

    var status = 0;
    status |= 0x40 * 0; // Output Ready
    status |= 0x80 * !this.mpu_read_buffer.length; // Input Ready

    return status;
};

// MPU UART Mode - Command Port
SB16.prototype.port3x1_write = function(value)
{
    dbg_log("331 write: mpu command: " + h(value), LOG_SB16);
    if(value === 0xFF)
    {
        // Command acknowledge.
        this.mpu_read_buffer.clear();
        this.mpu_read_buffer.push(0xFE);
    }
};

//
// DSP command handlers
//

SB16.prototype.command_do = function()
{
    var handler = DSP_COMMAND_HANDLERS[this.command];
    if(!handler)
    {
        handler = this.dsp_default_handler;
    }
    handler.call(this);

    // Reset Inputs.
    this.command = DSP_NO_COMMAND;
    this.command_size = 0;
    this.write_buffer.clear();
};

SB16.prototype.dsp_default_handler = function()
{
    dbg_log("Unhandled command: " + h(this.command), LOG_SB16);
};

/**
 * @param {Array} commands
 * @param {number} size
 * @param {function()=} handler
 */
function register_dsp_command(commands, size, handler)
{
    if(!handler)
    {
        handler = SB16.prototype.dsp_default_handler;
    }
    for(var i = 0; i < commands.length; i++)
    {
        DSP_COMMAND_SIZES[commands[i]] = size;
        DSP_COMMAND_HANDLERS[commands[i]] = handler;
    }
}

function any_first_digit(base)
{
    var commands = [];
    for(var i = 0; i < 16; i++)
    {
        commands.push(base + i);
    }
    return commands;
}

// The CSP/ASP coprocessor is reported absent (as on most real SB16 cards);
// drivers that detect one (e.g. Win9x CSPMAN.DLL) crash programming it.

// ASP set mode register
register_dsp_command([0x04], 1);

// ASP set codec parameter
register_dsp_command([0x05], 2);

// ASP get version
register_dsp_command([0x08], 1, function()
{
    var sub_command = this.write_buffer.shift();
    if(sub_command === 0x03)
    {
        this.read_buffer.clear();
        this.read_buffer.push(0xFF); // no chip installed
    }
});

// ASP set register
register_dsp_command([0x0E], 2);

// ASP get register
register_dsp_command([0x0F], 1, function()
{
    this.read_buffer.clear();
    this.read_buffer.push(this.asp_registers[this.write_buffer.shift()]);
});

// 8-bit direct mode single byte digitized sound output.
register_dsp_command([0x10], 1, function()
{
    var value = audio_normalize(this.write_buffer.shift(), 127.5, -1);

    this.dac_buffers[0].push(value);
    this.dac_buffers[1].push(value);
    this.machine.bus_send("dac-enable");
});

// 8-bit single-cycle DMA mode digitized sound output.
register_dsp_command([0x14, 0x15], 2, function()
{
    this.dma_irq = SB_IRQ_8BIT;
    this.dma_channel = this.dma_channel_8bit;
    this.dma_autoinit = false;
    this.dsp_signed = false;
    this.dsp_16bit = false;
    this.dsp_highspeed = false;
    this.dma_transfer_size_set();
    this.dma_transfer_start();
});

// Creative 8-bit to 2-bit ADPCM single-cycle DMA mode digitized sound output.
register_dsp_command([0x16], 2);

// Creative 8-bit to 2-bit ADPCM single-cycle DMA mode digitzed sound output
// with reference byte.
register_dsp_command([0x17], 2);

// 8-bit auto-init DMA mode digitized sound output.
register_dsp_command([0x1C], 0, function()
{
    this.dma_irq = SB_IRQ_8BIT;
    this.dma_channel = this.dma_channel_8bit;
    this.dma_autoinit = true;
    this.dsp_signed = false;
    this.dsp_16bit = false;
    this.dsp_highspeed = false;
    this.dma_transfer_start();
});

// Creative 8-bit to 2-bit ADPCM auto-init DMA mode digitized sound output
// with reference byte.
register_dsp_command([0x1F], 0);

// 8-bit direct mode single byte digitized sound input.
register_dsp_command([0x20], 0, function()
{
    // Fake silent input.
    this.read_buffer.clear();
    this.read_buffer.push(0x7f);
});

// 8-bit single-cycle DMA mode digitized sound input.
register_dsp_command([0x24], 2);

// 8-bit auto-init DMA mode digitized sound input.
register_dsp_command([0x2C], 0);

// Polling mode MIDI input.
register_dsp_command([0x30], 0);

// Interrupt mode MIDI input.
register_dsp_command([0x31], 0);

// UART polling mode MIDI I/O.
register_dsp_command([0x34], 0);

// UART interrupt mode MIDI I/O.
register_dsp_command([0x35], 0);

// UART polling mode MIDI I/O with time stamping.
register_dsp_command([0x36], 0);

// UART interrupt mode MIDI I/O with time stamping.
register_dsp_command([0x37], 0);

// MIDI output.
register_dsp_command([0x38], 0);

// Set digitized sound transfer Time Constant.
register_dsp_command([0x40], 1, function()
{
    // Note: bTimeConstant = 256 * time constant
    this.sampling_rate_change(
        1000000 / (256 - this.write_buffer.shift()) / this.get_channel_count()
    );
});

// Set digitized sound output sampling rate.
// Set digitized sound input sampling rate.
register_dsp_command([0x41, 0x42], 2, function()
{
    this.sampling_rate_change((this.write_buffer.shift() << 8) | this.write_buffer.shift());
});

// Set DSP block transfer size.
register_dsp_command([0x48], 2, function()
{
    // TODO: should be in bytes, but if this is only used
    // for 8 bit transfers, then this number is the same
    // as number of samples?
    // Wrong: e.g. stereo requires two bytes per sample.
    this.dma_transfer_size_set();
});

// Creative 8-bit to 4-bit ADPCM single-cycle DMA mode digitized sound output.
register_dsp_command([0x74], 2);

// Creative 8-bit to 4-bit ADPCM single-cycle DMA mode digitized sound output
// with referene byte.
register_dsp_command([0x75], 2);

// Creative 8-bit to 3-bit ADPCM single-cycle DMA mode digitized sound output.
register_dsp_command([0x76], 2);

// Creative 8-bit to 3-bit ADPCM single-cycle DMA mode digitized sound output
// with referene byte.
register_dsp_command([0x77], 2);

// Creative 8-bit to 4-bit ADPCM auto-init DMA mode digitized sound output
// with reference byte.
register_dsp_command([0x7D], 0);

// Creative 8-bit to 3-bit ADPCM auto-init DMA mode digitized sound output
// with reference byte.
register_dsp_command([0x7F], 0);

// Pause DAC for a duration.
register_dsp_command([0x80], 2);

// 8-bit high-speed auto-init DMA mode digitized sound output.
register_dsp_command([0x90], 0, function()
{
    this.dma_irq = SB_IRQ_8BIT;
    this.dma_channel = this.dma_channel_8bit;
    this.dma_autoinit = true;
    this.dsp_signed = false;
    this.dsp_highspeed = true;
    this.dsp_16bit = false;
    this.dma_transfer_start();
});

// 8-bit high-speed single-cycle DMA mode digitized sound input.
register_dsp_command([0x91], 0);

// 8-bit high-speed auto-init DMA mode digitized sound input.
register_dsp_command([0x98], 0);

// 8-bit high-speed single-cycle DMA mode digitized sound input.
register_dsp_command([0x99], 0);

// Set input mode to mono.
register_dsp_command([0xA0], 0);

// Set input mode to stereo.
register_dsp_command([0xA8], 0);

// Program 16-bit DMA mode digitized sound I/O.
register_dsp_command(any_first_digit(0xB0), 3, function()
{
    if(this.command & (1 << 3))
    {
        // Analogue to digital not implemented.
        this.dsp_default_handler();
        return;
    }
    var mode = this.write_buffer.shift();
    this.dma_irq = SB_IRQ_16BIT;
    this.dma_channel = this.dma_channel_16bit;
    this.dma_autoinit = !!(this.command & (1 << 2));
    this.dsp_signed = !!(mode & (1 << 4));
    this.dsp_stereo = !!(mode & (1 << 5));
    this.dsp_16bit = true;
    this.dma_transfer_size_set();
    this.dma_transfer_start();
});

// Program 8-bit DMA mode digitized sound I/O.
register_dsp_command(any_first_digit(0xC0), 3, function()
{
    if(this.command & (1 << 3))
    {
        // Analogue to digital not implemented.
        this.dsp_default_handler();
        return;
    }
    var mode = this.write_buffer.shift();
    this.dma_irq = SB_IRQ_8BIT;
    this.dma_channel = this.dma_channel_8bit;
    this.dma_autoinit = !!(this.command & (1 << 2));
    this.dsp_signed = !!(mode & (1 << 4));
    this.dsp_stereo = !!(mode & (1 << 5));
    this.dsp_16bit = false;
    this.dma_transfer_size_set();
    this.dma_transfer_start();
});

// Pause 8-bit DMA mode digitized sound I/O.
register_dsp_command([0xD0], 0, function()
{
    this.dma_paused = true;
    this.machine.bus_send("dac-disable");
});

// Turn on speaker.
// Documented to have no effect on SB16.
register_dsp_command([0xD1], 0, function()
{
    this.dummy_speaker_enabled = true;
});

// Turn off speaker.
// Documented to have no effect on SB16.
register_dsp_command([0xD3], 0, function()
{
    this.dummy_speaker_enabled = false;
});

// Continue 8-bit DMA mode digitized sound I/O.
register_dsp_command([0xD4], 0, function()
{
    this.dma_paused = false;
    this.machine.bus_send("dac-enable");
});

// Pause 16-bit DMA mode digitized sound I/O.
register_dsp_command([0xD5], 0, function()
{
    this.dma_paused = true;
    this.machine.bus_send("dac-disable");
});

// Continue 16-bit DMA mode digitized sound I/O.
register_dsp_command([0xD6], 0, function()
{
    this.dma_paused = false;
    this.machine.bus_send("dac-enable");
});

// Get speaker status.
register_dsp_command([0xD8], 0, function()
{
    this.read_buffer.clear();
    this.read_buffer.push(this.dummy_speaker_enabled * 0xFF);
});

// Exit 16-bit auto-init DMA mode digitized sound I/O.
// Exit 8-bit auto-init mode digitized sound I/O.
register_dsp_command([0xD9, 0xDA], 0, function()
{
    this.dma_autoinit = false;
});

// DSP identification
register_dsp_command([0xE0], 1, function()
{
    this.read_buffer.clear();
    this.read_buffer.push(~this.write_buffer.shift());
});

// Get DSP version number.
register_dsp_command([0xE1], 0, function()
{
    this.read_buffer.clear();
    this.read_buffer.push(4);
    this.read_buffer.push(5);
});

// DMA identification.
register_dsp_command([0xE2], 1);

// Get DSP copyright.
register_dsp_command([0xE3], 0, function()
{
    this.read_buffer.clear();
    for(var i = 0; i < DSP_COPYRIGHT.length; i++)
    {
        this.read_buffer.push(DSP_COPYRIGHT.charCodeAt(i));
    }
    // Null terminator.
    this.read_buffer.push(0);
});

// Write test register.
register_dsp_command([0xE4], 1, function()
{
    this.test_register = this.write_buffer.shift();
});

// Read test register.
register_dsp_command([0xE8], 0, function()
{
    this.read_buffer.clear();
    this.read_buffer.push(this.test_register);
});

// Trigger IRQ - 8-bit
register_dsp_command([0xF2], 0, function()
{
    this.raise_irq(SB_IRQ_8BIT);
});

// Trigger IRQ - 16-bit
register_dsp_command([0xF3], 0, function()
{
    this.raise_irq(SB_IRQ_16BIT);
});

// ASP - unknown function
var SB_F9 = new Uint8Array(256);
SB_F9[0x0E] = 0xFF;
SB_F9[0x0F] = 0x07;
SB_F9[0x37] = 0x38;
register_dsp_command([0xF9], 1, function()
{
    var input = this.write_buffer.shift();
    dbg_log("dsp 0xf9: unknown function. input: " + input, LOG_SB16);

    this.read_buffer.clear();
    this.read_buffer.push(SB_F9[input]);
});

//
// Mixer Handlers (CT1745)
//

SB16.prototype.mixer_read = function(address)
{
    var handler = MIXER_READ_HANDLERS[address];
    var data;
    if(handler)
    {
        data = handler.call(this);
    }
    else
    {
        data = this.mixer_registers[address];
        dbg_log("unhandled mixer register read. addr:" + h(address) + " data:" + h(data), LOG_SB16);
    }
    return data;
};

SB16.prototype.mixer_write = function(address, data)
{
    var handler = MIXER_WRITE_HANDLERS[address];
    if(handler)
    {
        handler.call(this, data);
    }
    else
    {
        dbg_log("unhandled mixer register write. addr:" + h(address) + " data:" + h(data), LOG_SB16);
    }
};

SB16.prototype.mixer_default_read = function()
{
    dbg_log("mixer register read. addr:" + h(this.mixer_current_address), LOG_SB16);
    return this.mixer_registers[this.mixer_current_address];
};

SB16.prototype.mixer_default_write = function(data)
{
    dbg_log("mixer register write. addr:" + h(this.mixer_current_address) + " data:" + h(data), LOG_SB16);
    this.mixer_registers[this.mixer_current_address] = data;
};

SB16.prototype.mixer_reset = function()
{
    // Values intentionally in decimal.
    // Default values available at
    // https://pdos.csail.mit.edu/6.828/2011/readings/hardware/SoundBlaster.pdf
    this.mixer_registers[0x04] = 12 << 4 | 12;
    this.mixer_registers[0x22] = 12 << 4 | 12;
    this.mixer_registers[0x26] = 12 << 4 | 12;
    this.mixer_registers[0x28] = 0;
    this.mixer_registers[0x2E] = 0;
    this.mixer_registers[0x0A] = 0;
    this.mixer_registers[0x30] = 24 << 3;
    this.mixer_registers[0x31] = 24 << 3;
    this.mixer_registers[0x32] = 24 << 3;
    this.mixer_registers[0x33] = 24 << 3;
    this.mixer_registers[0x34] = 24 << 3;
    this.mixer_registers[0x35] = 24 << 3;
    this.mixer_registers[0x36] = 0;
    this.mixer_registers[0x37] = 0;
    this.mixer_registers[0x38] = 0;
    this.mixer_registers[0x39] = 0;
    this.mixer_registers[0x3B] = 0;
    this.mixer_registers[0x3C] = 0x1F;
    this.mixer_registers[0x3D] = 0x15;
    this.mixer_registers[0x3E] = 0x0B;
    this.mixer_registers[0x3F] = 0;
    this.mixer_registers[0x40] = 0;
    this.mixer_registers[0x41] = 0;
    this.mixer_registers[0x42] = 0;
    this.mixer_registers[0x43] = 0;
    this.mixer_registers[0x44] = 8 << 4;
    this.mixer_registers[0x45] = 8 << 4;
    this.mixer_registers[0x46] = 8 << 4;
    this.mixer_registers[0x47] = 8 << 4;

    this.mixer_full_update();
};

SB16.prototype.mixer_full_update = function()
{
    // Start at 1. Don't re-reset.
    for(var i = 1; i < this.mixer_registers.length; i++)
    {
        if(MIXER_REGISTER_IS_LEGACY[i])
        {
            // Legacy registers are actually mapped to other register locations. Update
            // using the new registers rather than the legacy registers.
            continue;
        }
        this.mixer_write(i, this.mixer_registers[i]);
    }
};

/**
 * @param{number} address
 * @param{function():number=} handler
 */
function register_mixer_read(address, handler)
{
    if(!handler)
    {
        handler = SB16.prototype.mixer_default_read;
    }
    MIXER_READ_HANDLERS[address] = handler;
}

/**
 * @param{number} address
 * @param{function(number)=} handler
 */
function register_mixer_write(address, handler)
{
    if(!handler)
    {
        handler = SB16.prototype.mixer_default_write;
    }
    MIXER_WRITE_HANDLERS[address] = handler;
}

// Legacy registers map each nibble to the last 4 bits of the new registers
function register_mixer_legacy(address_old, address_new_left, address_new_right)
{
    MIXER_REGISTER_IS_LEGACY[address_old] = 1;

    /** @this {SB16} */
    MIXER_READ_HANDLERS[address_old] = function()
    {
        var left = this.mixer_registers[address_new_left] & 0xF0;
        var right = this.mixer_registers[address_new_right] >>> 4;
        return left | right;
    };

    /** @this {SB16} */
    MIXER_WRITE_HANDLERS[address_old] = function(data)
    {
        this.mixer_registers[address_old] = data;
        var prev_left = this.mixer_registers[address_new_left];
        var prev_right = this.mixer_registers[address_new_right];
        var left = (data & 0xF0) | (prev_left & 0x0F);
        var right = (data << 4 & 0xF0) | (prev_right & 0x0F);

        this.mixer_write(address_new_left, left);
        this.mixer_write(address_new_right, right);
    };
}

/**
 * @param {number} address
 * @param {number} mixer_source
 * @param {number} channel
 */
function register_mixer_volume(address, mixer_source, channel)
{
    MIXER_READ_HANDLERS[address] = SB16.prototype.mixer_default_read;

    /** @this {SB16} */
    MIXER_WRITE_HANDLERS[address] = function(data)
    {
        this.mixer_registers[address] = data;
        this.machine.bus_send("mixer-volume",
        [
            mixer_source,
            channel,
            (data >>> 2) - 62
        ]);
    };
}

// Reset.
register_mixer_read(0x00, function()
{
    this.mixer_reset();
    return 0;
});
register_mixer_write(0x00);

// Legacy Voice Volume Left/Right.
register_mixer_legacy(0x04, 0x32, 0x33);

// Legacy Mic Volume. TODO.
//register_mixer_read(0x0A);
//register_mixer_write(0x0A, function(data)
//{
//    this.mixer_registers[0x0A] = data;
//    var prev = this.mixer_registers[0x3A];
//    this.mixer_write(0x3A, data << 5 | (prev & 0x0F));
//});

// Legacy Master Volume Left/Right.
register_mixer_legacy(0x22, 0x30, 0x31);
// Legacy Midi Volume Left/Right.
register_mixer_legacy(0x26, 0x34, 0x35);
// Legacy CD Volume Left/Right.
register_mixer_legacy(0x28, 0x36, 0x37);
// Legacy Line Volume Left/Right.
register_mixer_legacy(0x2E, 0x38, 0x39);

// Master Volume Left.
register_mixer_volume(0x30, MIXER_SRC_MASTER, MIXER_CHANNEL_LEFT);
// Master Volume Right.
register_mixer_volume(0x31, MIXER_SRC_MASTER, MIXER_CHANNEL_RIGHT);
// Voice Volume Left.
register_mixer_volume(0x32, MIXER_SRC_DAC, MIXER_CHANNEL_LEFT);
// Voice Volume Right.
register_mixer_volume(0x33, MIXER_SRC_DAC, MIXER_CHANNEL_RIGHT);
// MIDI Volume Left. TODO.
//register_mixer_volume(0x34, MIXER_SRC_SYNTH, MIXER_CHANNEL_LEFT);
// MIDI Volume Right. TODO.
//register_mixer_volume(0x35, MIXER_SRC_SYNTH, MIXER_CHANNEL_RIGHT);
// CD Volume Left. TODO.
//register_mixer_volume(0x36, MIXER_SRC_CD, MIXER_CHANNEL_LEFT);
// CD Volume Right. TODO.
//register_mixer_volume(0x37, MIXER_SRC_CD, MIXER_CHANNEL_RIGHT);
// Line Volume Left. TODO.
//register_mixer_volume(0x38, MIXER_SRC_LINE, MIXER_CHANNEL_LEFT);
// Line Volume Right. TODO.
//register_mixer_volume(0x39, MIXER_SRC_LINE, MIXER_CHANNEL_RIGHT);
// Mic Volume. TODO.
//register_mixer_volume(0x3A, MIXER_SRC_MIC, MIXER_CHANNEL_BOTH);

// PC Speaker Volume.
register_mixer_read(0x3B);
register_mixer_write(0x3B, function(data)
{
    this.mixer_registers[0x3B] = data;
    this.machine.bus_send("mixer-volume", [MIXER_SRC_PCSPEAKER, MIXER_CHANNEL_BOTH, (data >>> 6) * 6 - 18]);
});

// Output Mixer Switches. TODO.
//register_mixer_read(0x3C);
//register_mixer_write(0x3C, function(data)
//{
//    this.mixer_registers[0x3C] = data;
//
//    if(data & 0x01) this.machine.bus_send("mixer-connect", [MIXER_SRC_MIC, MIXER_CHANNEL_BOTH]);
//    else this.machine.bus_send("mixer-disconnect", [MIXER_SRC_MIC, MIXER_CHANNEL_BOTH]);
//
//    if(data & 0x02) this.machine.bus_send("mixer-connect", [MIXER_SRC_CD, MIXER_CHANNEL_RIGHT]);
//    else this.machine.bus_send("mixer-disconnect", [MIXER_SRC_CD, MIXER_CHANNEL_RIGHT]);
//
//    if(data & 0x04) this.machine.bus_send("mixer-connect", [MIXER_SRC_CD, MIXER_CHANNEL_LEFT]);
//    else this.machine.bus_send("mixer-disconnect", [MIXER_SRC_CD, MIXER_CHANNEL_LEFT]);
//
//    if(data & 0x08) this.machine.bus_send("mixer-connect", [MIXER_SRC_LINE, MIXER_CHANNEL_RIGHT]);
//    else this.machine.bus_send("mixer-disconnect", [MIXER_SRC_LINE, MIXER_CHANNEL_RIGHT]);
//
//    if(data & 0x10) this.machine.bus_send("mixer-connect", [MIXER_SRC_LINE, MIXER_CHANNEL_LEFT]);
//    else this.machine.bus_send("mixer-disconnect", [MIXER_SRC_LINE, MIXER_CHANNEL_LEFT]);
//});

// Input Mixer Left Switches. TODO.
//register_mixer_read(0x3D);
//register_mixer_write(0x3D);

// Input Mixer Right Switches. TODO.
//register_mixer_read(0x3E);
//register_mixer_write(0x3E);

// Input Gain Left. TODO.
//register_mixer_read(0x3F);
//register_mixer_write(0x3F);

// Input Gain Right. TODO.
//register_mixer_read(0x40);
//register_mixer_write(0x40);

// Output Gain Left.
register_mixer_read(0x41);
register_mixer_write(0x41, function(data)
{
    this.mixer_registers[0x41] = data;
    this.machine.bus_send("mixer-gain-left", (data >>> 6) * 6);
});

// Output Gain Right.
register_mixer_read(0x42);
register_mixer_write(0x42, function(data)
{
    this.mixer_registers[0x42] = data;
    this.machine.bus_send("mixer-gain-right", (data >>> 6) * 6);
});

// Mic AGC. TODO.
//register_mixer_read(0x43);
//register_mixer_write(0x43);

// Treble Left.
register_mixer_read(0x44);
register_mixer_write(0x44, function(data)
{
    this.mixer_registers[0x44] = data;
    data >>>= 3;
    this.machine.bus_send("mixer-treble-left", data - (data < 16 ? 14 : 16));
});

// Treble Right.
register_mixer_read(0x45);
register_mixer_write(0x45, function(data)
{
    this.mixer_registers[0x45] = data;
    data >>>= 3;
    this.machine.bus_send("mixer-treble-right", data - (data < 16 ? 14 : 16));
});

// Bass Left.
register_mixer_read(0x46);
register_mixer_write(0x46, function(data)
{
    this.mixer_registers[0x46] = data;
    data >>>= 3;
    this.machine.bus_send("mixer-bass-right", data - (data < 16 ? 14 : 16));
});

// Bass Right.
register_mixer_read(0x47);
register_mixer_write(0x47, function(data)
{
    this.mixer_registers[0x47] = data;
    data >>>= 3;
    this.machine.bus_send("mixer-bass-right", data - (data < 16 ? 14 : 16));
});

// IRQ Select.
register_mixer_read(0x80, function()
{
    switch(this.irq)
    {
        case SB_IRQ2: return 0x1;
        case SB_IRQ5: return 0x2;
        case SB_IRQ7: return 0x4;
        case SB_IRQ10: return 0x8;
        default: return 0x0;
    }
});
register_mixer_write(0x80, function(bits)
{
    if(bits & 0x1) this.irq = SB_IRQ2;
    if(bits & 0x2) this.irq = SB_IRQ5;
    if(bits & 0x4) this.irq = SB_IRQ7;
    if(bits & 0x8) this.irq = SB_IRQ10;
});

// DMA Select.
register_mixer_read(0x81, function()
{
    var ret = 0;
    switch(this.dma_channel_8bit)
    {
        case SB_DMA0: ret |= 0x1; break;
        case SB_DMA1: ret |= 0x2; break;
        // Channel 2 is hardwired to floppy disk.
        case SB_DMA3: ret |= 0x8; break;
    }
    switch(this.dma_channel_16bit)
    {
        // Channel 4 cannot be used.
        case SB_DMA5: ret |= 0x20; break;
        case SB_DMA6: ret |= 0x40; break;
        case SB_DMA7: ret |= 0x80; break;
    }
    return ret;
});
register_mixer_write(0x81, function(bits)
{
    if(bits & 0x1) this.dma_channel_8bit = SB_DMA0;
    if(bits & 0x2) this.dma_channel_8bit = SB_DMA1;
    if(bits & 0x8) this.dma_channel_8bit = SB_DMA3;
    if(bits & 0x20) this.dma_channel_16bit = SB_DMA5;
    if(bits & 0x40) this.dma_channel_16bit = SB_DMA6;
    if(bits & 0x80) this.dma_channel_16bit = SB_DMA7;
});

// IRQ Status.
register_mixer_read(0x82, function()
{
    var ret = 0x20;
    for(var i = 0; i < 16; i++)
    {
        ret |= i * this.irq_triggered[i];
    }
    return ret;
});

//
// FM Handlers
//

SB16.prototype.fm_default_write = function(data, register, address)
{
    dbg_log("unhandled fm register write. addr:" + register + "|" + h(address) + " data:" + h(data), LOG_SB16);
    // No need to save into a dummy register as the registers are write-only.
};

/**
 * @param{Array} addresses
 * @param{function(number, number, number)=} handler
 */
function register_fm_write(addresses, handler)
{
    if(!handler)
    {
        handler = SB16.prototype.fm_default_write;
    }
    for(var i = 0; i < addresses.length; i++)
    {
        FM_HANDLERS[addresses[i]] = handler;
    }
}

function between(start, end)
{
    var a = [];
    for(var i = start; i <= end; i++)
    {
        a.push(i);
    }
    return a;
}

const SB_FM_OPERATORS_BY_OFFSET = new Uint8Array(32);
SB_FM_OPERATORS_BY_OFFSET[0x00] = 0;
SB_FM_OPERATORS_BY_OFFSET[0x01] = 1;
SB_FM_OPERATORS_BY_OFFSET[0x02] = 2;
SB_FM_OPERATORS_BY_OFFSET[0x03] = 3;
SB_FM_OPERATORS_BY_OFFSET[0x04] = 4;
SB_FM_OPERATORS_BY_OFFSET[0x05] = 5;
SB_FM_OPERATORS_BY_OFFSET[0x08] = 6;
SB_FM_OPERATORS_BY_OFFSET[0x09] = 7;
SB_FM_OPERATORS_BY_OFFSET[0x0A] = 8;
SB_FM_OPERATORS_BY_OFFSET[0x0B] = 9;
SB_FM_OPERATORS_BY_OFFSET[0x0C] = 10;
SB_FM_OPERATORS_BY_OFFSET[0x0D] = 11;
SB_FM_OPERATORS_BY_OFFSET[0x10] = 12;
SB_FM_OPERATORS_BY_OFFSET[0x11] = 13;
SB_FM_OPERATORS_BY_OFFSET[0x12] = 14;
SB_FM_OPERATORS_BY_OFFSET[0x13] = 15;
SB_FM_OPERATORS_BY_OFFSET[0x14] = 16;
SB_FM_OPERATORS_BY_OFFSET[0x15] = 17;

function get_fm_operator(register, offset)
{
    return register * 18 + SB_FM_OPERATORS_BY_OFFSET[offset];
}

register_fm_write([0x01], function(bits, register, address)
{
    this.fm_waveform_select_enable[register] = bits & 0x20 > 0;
    this.fm_update_waveforms();
});

// Timer 1 Count.
register_fm_write([0x02]);

// Timer 2 Count.
register_fm_write([0x03]);

register_fm_write([0x04], function(bits, register, address)
{
    switch(register)
    {
        case 0:
            // if(bits & 0x80)
            // {
            //     // IQR Reset
            // }
            // else
            // {
            //     // Timer masks and on/off
            // }
            break;
        case 1:
            // Four-operator enable
            break;
    }
});

register_fm_write([0x05], function(bits, register, address)
{
    if(register === 0)
    {
        // No registers documented here.
        this.fm_default_write(bits, register, address);
    }
    else
    {
        // OPL3 Mode Enable
    }
});

register_fm_write([0x08], function(bits, register, address)
{
    // Composite sine wave on/off
    // Note select (keyboard split selection method)
});

register_fm_write(between(0x20, 0x35), function(bits, register, address)
{
    var operator = get_fm_operator(register, address - 0x20);
    // Tremolo
    // Vibrato
    // Sustain
    // KSR Envelope Scaling
    // Frequency Multiplication Factor
});

register_fm_write(between(0x40, 0x55), function(bits, register, address)
{
    var operator = get_fm_operator(register, address - 0x40);
    // Key Scale Level
    // Output Level
});

register_fm_write(between(0x60, 0x75), function(bits, register, address)
{
    var operator = get_fm_operator(register, address - 0x60);
    // Attack Rate
    // Decay Rate
});

register_fm_write(between(0x80, 0x95), function(bits, register, address)
{
    var operator = get_fm_operator(register, address - 0x80);
    // Sustain Level
    // Release Rate
});

register_fm_write(between(0xA0, 0xA8), function(bits, register, address)
{
    var channel = address - 0xA0;
    // Frequency Number (Lower 8 bits)
});

register_fm_write(between(0xB0, 0xB8), function(bits, register, address)
{
    // Key-On
    // Block Number
    // Frequency Number (Higher 2 bits)
});

register_fm_write([0xBD], function(bits, register, address)
{
    // Tremelo Depth
    // Vibrato Depth
    // Percussion Mode
    // Bass Drum Key-On
    // Snare Drum Key-On
    // Tom-Tom Key-On
    // Cymbal Key-On
    // Hi-Hat Key-On
});

register_fm_write(between(0xC0, 0xC8), function(bits, register, address)
{
    // Right Speaker Enable
    // Left Speaker Enable
    // Feedback Modulation Factor
    // Synthesis Type
});

register_fm_write(between(0xE0, 0xF5), function(bits, register, address)
{
    var operator = get_fm_operator(register, address - 0xE0);
    // Waveform Select
});

//
// FM behaviours
//

SB16.prototype.fm_update_waveforms = function()
{
    // To be implemented.
};

//
// General behaviours
//

SB16.prototype.sampling_rate_change = function(rate)
{
    this.sampling_rate = rate;
    this.machine.bus_send("dac-tell-sampling-rate", rate);
};

SB16.prototype.get_channel_count = function()
{
    return this.dsp_stereo ? 2 : 1;
};

SB16.prototype.dma_transfer_size_set = function()
{
    this.dma_sample_count = 1 + (this.write_buffer.shift() << 0) + (this.write_buffer.shift() << 8);
};

SB16.prototype.dma_transfer_start = function()
{
    dbg_log("begin dma transfer", LOG_SB16);

    // (1) Setup appropriate settings.

    this.bytes_per_sample = 1;
    if(this.dsp_16bit) this.bytes_per_sample *= 2;

    // Don't count stereo interleaved bits apparently.
    // Disabling this line is needed for sounds to work correctly,
    // especially double buffering autoinit mode.
    // Learnt the hard way.
    // if(this.dsp_stereo) this.bytes_per_sample *= 2;

    this.dma_bytes_count = this.dma_sample_count * this.bytes_per_sample;
    this.dma_bytes_block = SB_DMA_BLOCK_SAMPLES * this.bytes_per_sample;

    // Ensure block size is small enough but not too small, and is divisible by 4
    var max_bytes_block = Math.max(this.dma_bytes_count >> 2 & ~0x3, 32);
    this.dma_bytes_block = Math.min(max_bytes_block, this.dma_bytes_block);

    // (2) Wait until channel is unmasked (if not already)
    this.dma_waiting_transfer = true;
    if(!this.machine.dma_masked(this.dma_channel))
    {
        this.dma_on_unmask(this.dma_channel);
    }
};

SB16.prototype.dma_on_unmask = function(channel)
{
    if(channel !== this.dma_channel || !this.dma_waiting_transfer)
    {
        return;
    }

    // (3) Configure amount of bytes left to transfer and tell speaker adapter
    // to start requesting transfers
    this.dma_waiting_transfer = false;
    this.dma_bytes_left = this.dma_bytes_count;
    this.dma_paused = false;
    this.machine.bus_send("dac-enable");
};

/**
 * @param {boolean=} silent the samples are dropped (SB16.prototype.timer)
 */
SB16.prototype.dma_transfer_next = function(silent)
{
    dbg_log("dma transfering next block", LOG_SB16);

    var size = Math.min(this.dma_bytes_left, this.dma_bytes_block);
    var samples = Math.floor(size / this.bytes_per_sample);

    this.machine.dma_write(this.dma_channel, this.dma_buffer_uint8, 0, size, (error) =>
    {
        dbg_log("dma block transfer " + (error ? "unsuccessful" : "successful"), LOG_SB16);
        if(error) return;

        if(!silent) this.dma_to_dac(samples);
        if(this.dma_clock >= 0)
        {
            this.dma_clock += samples * 1000 / (this.sampling_rate * (this.dsp_stereo ? 2 : 1));
        }
        this.dma_bytes_left -= size;

        if(!this.dma_bytes_left)
        {
            // Completed requested transfer of given size.
            this.raise_irq(this.dma_irq);

            if(this.dma_autoinit)
            {
                // Restart the transfer.
                this.dma_bytes_left = this.dma_bytes_count;
            }
        }
    });
};

SB16.prototype.dma_to_dac = function(sample_count)
{
    var amplitude = this.dsp_16bit ? 32767.5 : 127.5;
    var offset = this.dsp_signed ? 0 : -1;
    var repeats = this.dsp_stereo ? 1 : 2;

    var buffer;
    if(this.dsp_16bit)
    {
        buffer = this.dsp_signed ? this.dma_buffer_int16 : this.dma_buffer_uint16;
    }
    else
    {
        buffer = this.dsp_signed ? this.dma_buffer_int8 : this.dma_buffer_uint8;
    }

    var channel = 0;
    for(var i = 0; i < sample_count; i++)
    {
        var sample = audio_normalize(buffer[i], amplitude, offset);
        for(var j = 0; j < repeats; j++)
        {
            this.dac_buffers[channel].push(sample);
            channel ^= 1;
        }
    }

    this.dac_send();
};

SB16.prototype.dac_handle_request = function()
{
    this.dac_request_time = this.machine.now();
    // (a masked channel delivers nothing, as the 8237's DREQ is ignored:
    // Windows XP's driver stops a sound with D9, exit auto-init, and masks
    // the channel at once; the DSP's block is 128 KiB around a 16 KiB DMA
    // buffer, so reading on played that buffer again, the sound's last
    // part up to 8 times, until the block's end)
    if(!this.dma_bytes_left || this.dma_paused || this.machine.dma_masked(this.dma_channel))
    {
        // No more data to transfer or is paused. Send whatever is in the buffers.
        this.dac_send();
    }
    else
    {
        this.dma_transfer_next();
    }
};

/**
 * The DMA moves when the host's speaker asks for data ("dac-request-data"),
 * at the pace of the host's audio. A host that stopped asking -- an
 * AudioContext still waiting for the page's first gesture, a stalled or
 * changed audio device, an embedder with no speaker -- froze the guest's play
 * position, which real hardware never does: Need for Speed: Most Wanted's
 * sound engine took a few seconds of that for a broken device and restarted
 * its stream ever after, silent. While the host does not ask, the transfer
 * keeps the machine's time on its own, its samples dropped (nobody listens).
 * @param {number} now
 * @return {number} milliseconds until the next call is needed
 */
SB16.prototype.timer = function(now)
{
    if(!this.dma_bytes_left || this.dma_paused || this.dma_waiting_transfer ||
        this.machine.dma_masked(this.dma_channel) || this.dma_clock < 0)
    {
        // (a transfer that starts gives the host its time to answer dac-enable)
        this.dma_clock = now;
        this.dac_request_time = now;
        return 100;
    }
    // (the host asks: it sets the pace, usually ahead of the clock)
    const asked = now - this.dac_request_time;
    if(asked < DAC_HOST_TIMEOUT_MS)
    {
        return DAC_HOST_TIMEOUT_MS - asked;
    }
    for(let i = 0; i < DAC_CATCH_UP_BLOCKS && this.dma_clock < now; i++)
    {
        const before = this.dma_clock;
        this.dma_transfer_next(true);
        if(this.dma_clock === before || !this.dma_bytes_left || this.dma_paused ||
            this.machine.dma_masked(this.dma_channel))
        {
            break;
        }
    }
    // (far behind, after a transfer that made no progress: from now on)
    if(now - this.dma_clock > 1000) this.dma_clock = now;
    return Math.max(1, this.dma_clock - now);
};

SB16.prototype.dac_send = function()
{
    if(!this.dac_buffers[0].length)
    {
        return;
    }

    var out0 = this.dac_buffers[0].shift_block(this.dac_buffers[0].length);
    var out1 = this.dac_buffers[1].shift_block(this.dac_buffers[1].length);
    this.machine.bus_send("dac-send-data", [out0, out1], [out0.buffer, out1.buffer]);
};

SB16.prototype.raise_irq = function(type)
{
    dbg_log("raise irq", LOG_SB16);
    this.irq_triggered[type] = 1;
    this.machine.isa_raise_irq(this.irq);
};

SB16.prototype.lower_irq = function(type)
{
    dbg_log("lower irq", LOG_SB16);
    this.irq_triggered[type] = 0;
    this.machine.isa_lower_irq(this.irq);
};

//
// Helpers
//

function audio_normalize(value, amplitude, offset)
{
    return audio_clip(value / amplitude + offset, -1, 1);
}

function audio_clip(value, low, high)
{
    return (value < low) * low + (value > high) * high + (low <= value && value <= high) * value;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/src/block_backend.js                                                                     0000644 0000000 0000000 00000032641 00000000000 013560  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A block device's backend (docs/arm64-virt-android16-plan.md P5.4): the
// image buffer (src/buffer.js) behind a disk controller, with what every
// controller needs from it: reads that a reset cancels, writes that a reset
// forgets, FLUSH after the writes issued before it are done, and each host
// operation counted as I/O a snapshot waits for (src/state_io.js). Writes go
// to the buffer, an in-memory overlay of the image: they last the session
// (or a write-back backend's image: docs/disk-persistence-plan.md).
//
// The functions work on an owner with the fields init_block_io sets (and
// `cpu`, `buffer`): BlockBackend (virtio-blk) and IDEInterface (src/ide.js,
// also AHCI's drives) share them.
//
// A backend can fail a request (src/image/, docs/disk-image-formats-plan.md
// P0; docs/disk-persistence-plan.md "错误处理"): a read calls back with
// fn(undefined, error), a write or flush with fn(error). The disk's
// disk_error policy (the buffer's, src/disk_options.js) decides:
// - "report": the failure goes to the caller's on_error, and the controller
//   ends the command with its error status (IDE ERR/ABRT, AHCI NCQ
//   ncq_failed, virtio-blk IOERR);
// - "stop" (the default): the request stays unfinished and is held on the
//   CPU (cpu.disk_holds), the machine stops (cpu.stop_machine, v86's
//   stop()); run() retries the held requests in their order
//   (release_disk_holds), or reports those that cannot be retried;
//   destroy() and a restored snapshot drop them, as a power loss would.
//   The floppy controller's DMA transfers are held the same way
//   (src/floppy.js, block_failed).
// Either way a "disk-error" event tells the host: the disk, the operation,
// offset, length, the reason, whether it can be retried, the policy. A
// cancelled read, or a request a reset overtook, calls neither callback.

import { begin_state_io, track_state_io } from "./state_io.js";
import { LOG_DISK } from "./const.js";
import { dbg_assert, dbg_log } from "./log.js";

/**
 * The fields of an owner's block I/O
 * @param {?} owner
 */
export function init_block_io(owner)
{
    owner.last_io_id = 0;
    /** @type {!Map<number, !AbortController>} reads in progress */
    owner.in_progress = new Map();
    /** @type {!Set<number>} reads cancelled before they completed */
    owner.cancelled = new Set();
    /** a reset moves on: what was started before it does not complete */
    owner.reset_epoch = 0;
    /** writes not finished yet (in flight, or held after an error) */
    owner.writes_in_flight = 0;
    /** the sequence number of the last write issued */
    owner.write_seq = 0;
    /** @type {!Set<number>} the sequence numbers of the writes not finished yet */
    owner.writes_pending = new Set();
    /** @type {!Array<{upto: number, flush: function()}>} FLUSH: each waits for the writes up to its number */
    owner.flush_waiters = [];
}

/**
 * Whether a request that failed with this error can be tried again: an
 * error says so (`retryable`), a disk image's error by its kind (I/O errors
 * only, src/image/source.js), anything else can
 * @param {!Error} error
 * @return {boolean}
 */
export function is_retryable(error)
{
    if(typeof error["retryable"] === "boolean") return error["retryable"];
    const kind = /** @type {?} */ (error).kind;
    if(typeof kind === "string") return kind === "io";
    return true;
}

/**
 * A request the backend failed, by the disk's policy
 * @param {?} owner
 * @param {string} operation "read", "write" or "flush"
 * @param {number} start
 * @param {number} length
 * @param {!Error} error
 * @param {function()} retry starts the request again
 * @param {function(!Error)} report ends it with the error
 * @param {function()} drop forgets it (held, then destroy() or a restore)
 */
export function block_failed(owner, operation, start, length, error, retry, report, drop)
{
    const buffer = owner.buffer;
    const policy = buffer && buffer.disk_error === "report" ? "report" : "stop";
    const retryable = is_retryable(error);
    const name = buffer && buffer.disk_name || owner.name || "disk";
    const cpu = owner.cpu;
    dbg_log(name + ": " + operation + " of " + length + " bytes at " + start + " failed (" + policy + "): " + error.message, LOG_DISK);
    const hold = policy === "stop" && cpu;
    if(hold)
    {
        (cpu.disk_holds || (cpu.disk_holds = [])).push({ owner, operation, retry, report, drop, error, retryable });
    }
    if(cpu && cpu.bus)
    {
        cpu.bus.send("disk-error", {
            "disk": name, "operation": operation, "offset": start, "length": length,
            "reason": error.message, "retryable": retryable, "policy": policy,
        });
    }
    if(hold)
    {
        cpu.stop_machine && cpu.stop_machine();
    }
    else
    {
        report(error);
    }
}

/**
 * Read [start, start + length) of owner.buffer: `callback` gets the bytes (a
 * view the caller copies from), or `on_error` the backend's error, unless
 * the read was cancelled first
 * @param {?} owner
 * @param {number} start
 * @param {number} length
 * @param {function(!Uint8Array)} callback
 * @param {function(!Error)} on_error
 */
export function block_read(owner, start, length, callback, on_error)
{
    const id = owner.last_io_id++;
    const attempt = () =>
    {
        const abort = new AbortController();
        const complete = begin_state_io(owner.cpu);
        abort["snapshot_done"] = complete;
        owner.in_progress.set(id, abort);
        try
        {
            owner.buffer.get(start, length, (data, error) =>
            {
                complete();
                if(owner.cancelled.delete(id))
                {
                    dbg_assert(!owner.in_progress.has(id));
                    return;
                }
                const removed = owner.in_progress.delete(id);
                dbg_assert(removed);
                if(error || !data)
                {
                    block_failed(owner, "read", start, length, error || new Error("the disk image returned no data"),
                        attempt, on_error, () => {});
                    return;
                }
                callback(data);
            }, { signal: abort.signal });
        }
        catch(error)
        {
            complete();
            owner.in_progress.delete(id);
            throw error;
        }
    };
    attempt();
}

/**
 * Write `data` at `start`: `callback` when it is in the buffer, or
 * `on_error` when the backend failed it, unless a reset came first (the
 * write itself still lands). A durable write (the guest turned the write
 * cache off, or FUA: docs/disk-persistence-plan.md "向客户机报告写缓存")
 * completes once the buffer's flush after it is done.
 * @param {?} owner
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function()} callback
 * @param {function(!Error)} on_error
 * @param {boolean=} durable
 */
export function block_write(owner, start, data, callback, on_error, durable)
{
    const epoch = owner.reset_epoch;
    const seq = ++owner.write_seq;
    owner.writes_in_flight++;
    owner.writes_pending.add(seq);
    const finish = () =>
    {
        owner.writes_in_flight--;
        owner.writes_pending.delete(seq);
        run_flush_waiters(owner);
    };
    const buffer = owner.buffer;
    const flush = durable && buffer && typeof buffer.flush === "function";
    const attempt = () =>
    {
        track_state_io(owner.cpu, done => buffer.set(start, data, error =>
        {
            if(error || !flush) done(error);
            else track_state_io(owner.cpu, flushed => buffer.flush(flushed), done);
        }), error =>
        {
            if(error)
            {
                block_failed(owner, "write", start, data.length, error, attempt, error =>
                {
                    if(epoch === owner.reset_epoch) on_error(error);
                    finish();
                }, finish);
                return;
            }
            if(epoch === owner.reset_epoch) callback();
            finish();
        });
    };
    attempt();
}

/**
 * The lowest sequence number of the writes not finished yet
 * @param {?} owner
 * @return {number}
 */
function oldest_pending_write(owner)
{
    let oldest = Infinity;
    for(const seq of owner.writes_pending) if(seq < oldest) oldest = seq;
    return oldest;
}

/** @param {?} owner */
function run_flush_waiters(owner)
{
    if(!owner.flush_waiters.length) return;
    const oldest = oldest_pending_write(owner);
    const ready = owner.flush_waiters.filter(waiter => waiter.upto < oldest);
    if(!ready.length) return;
    owner.flush_waiters = owner.flush_waiters.filter(waiter => waiter.upto >= oldest);
    ready.forEach(waiter => waiter.flush());
}

/**
 * FLUSH: `callback` when the writes issued before are finished and the
 * buffer's own flush (if it has one) is done; `on_error` when the flush
 * failed. Writes issued after it do not hold it up.
 * @param {?} owner
 * @param {function()} callback
 * @param {function(!Error)} on_error
 */
export function block_when_writes_done(owner, callback, on_error)
{
    const epoch = owner.reset_epoch;
    const upto = owner.write_seq;
    const flush = () =>
    {
        const attempt = () =>
        {
            if(owner.buffer && typeof owner.buffer.flush === "function")
            {
                track_state_io(owner.cpu, done => owner.buffer.flush(done), finish);
            }
            else
            {
                finish(undefined);
            }
        };
        const finish = error =>
        {
            if(error)
            {
                block_failed(owner, "flush", 0, 0, error, attempt, error =>
                {
                    if(epoch === owner.reset_epoch) on_error(error);
                }, () => {});
                return;
            }
            if(epoch === owner.reset_epoch) callback();
        };
        attempt();
    };
    if(oldest_pending_write(owner) > upto)
    {
        flush();
    }
    else
    {
        owner.flush_waiters.push({ upto, flush });
    }
}

/**
 * Reads in progress are cancelled (their callbacks never run), and so are
 * the reads and flushes held after an error (a held write still lands when
 * run() retries it, unanswered after a reset)
 * @param {?} owner
 */
export function block_cancel_reads(owner)
{
    for(const [id, abort] of owner.in_progress)
    {
        owner.cancelled.add(id);
        abort.abort();
        abort["snapshot_done"]?.();
    }
    owner.in_progress.clear();
    const cpu = owner.cpu;
    if(cpu && cpu.disk_holds && cpu.disk_holds.length)
    {
        cpu.disk_holds = cpu.disk_holds.filter(hold => hold.owner !== owner || hold.operation === "write");
    }
}

/**
 * The drive is gone (a SATA drive pulled out): its held requests are
 * dropped
 * @param {?} owner
 */
export function block_drop_holds(owner)
{
    const cpu = owner.cpu;
    if(!cpu || !cpu.disk_holds) return;
    const mine = cpu.disk_holds.filter(hold => hold.owner === owner);
    cpu.disk_holds = cpu.disk_holds.filter(hold => hold.owner !== owner);
    mine.forEach(hold => hold.drop());
}

/**
 * run(): the requests held after an error, in their order, are retried, or
 * ended with their error when they cannot be retried
 * @param {?} cpu
 * @return {number} how many there were
 */
export function release_disk_holds(cpu)
{
    const holds = cpu.disk_holds;
    if(!holds || !holds.length) return 0;
    cpu.disk_holds = [];
    for(const hold of holds)
    {
        if(hold.retryable) hold.retry();
        else hold.report(hold.error);
    }
    return holds.length;
}

/**
 * destroy(), or a restored snapshot: the held requests are dropped (as by a
 * power loss)
 * @param {?} cpu
 */
export function drop_disk_holds(cpu)
{
    const holds = cpu.disk_holds;
    if(!holds || !holds.length) return;
    cpu.disk_holds = [];
    holds.forEach(hold => hold.drop());
}

/**
 * A snapshot is refused while requests are held after an error: the state
 * would wait for I/O that does not end
 * @param {?} cpu
 */
export function check_no_disk_holds(cpu)
{
    const holds = cpu.disk_holds;
    if(holds && holds.length)
    {
        const hold = holds[0];
        const name = hold.owner.buffer && hold.owner.buffer.disk_name || hold.owner.name || "disk";
        throw new Error("The state is not saved: the disk " + name + " has " + holds.length + " request(s) held after an I/O error (" +
            hold.error.message + "); run() retries them, destroy() drops them");
    }
}

/**
 * A backend of its own (virtio-blk)
 * @constructor
 * @param {!Object} cpu (snapshot_io_pending)
 * @param {!Object} buffer get(start, length, fn, options), set(start, data, fn), byteLength
 */
export function BlockBackend(cpu, buffer)
{
    this.cpu = cpu;
    this.buffer = buffer;
    this.byte_length = buffer.byteLength;
    init_block_io(this);
}

BlockBackend.prototype.read = function(start, length, callback, on_error) { block_read(this, start, length, callback, on_error); };
/**
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function()} callback
 * @param {function(!Error)} on_error
 * @param {boolean=} durable
 */
BlockBackend.prototype.write = function(start, data, callback, on_error, durable) { block_write(this, start, data, callback, on_error, durable); };
BlockBackend.prototype.when_writes_done = function(callback, on_error) { block_when_writes_done(this, callback, on_error); };
BlockBackend.prototype.cancel_reads = function() { block_cancel_reads(this); };

/** A reset of the controller: nothing started before it completes */
BlockBackend.prototype.reset = function()
{
    this.reset_epoch++;
    this.cancel_reads();
};
                                                                                               source/v64/src/browser/ansi_screen.js                                                               0000644 0000000 0000000 00000003316 00000000000 014770  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { DummyScreenAdapter, DUMMY_SCREEN_CHARACTER, DUMMY_SCREEN_BG_COLOR, DUMMY_SCREEN_FG_COLOR } from "./dummy_screen.js";

const ANSI_RESET = "\x1B[0m";

/**
 * @param {number} color 0xRRGGBB
 * @return {string}
 */
function hex_to_ansi_truecolor(color)
{
    const
        RED   = (color & 0xFF0000) >> 16,
        GREEN = (color & 0x00FF00) >> 8,
        BLUE  = (color & 0x0000FF);

    return `2;${RED};${GREEN};${BLUE}`;
}

/**
 * The text screen as rows of ANSI truecolor escape sequences
 */
export class ANSIScreenAdapter extends DummyScreenAdapter
{
    /** @param {Object=} options */
    constructor(options)
    {
        super(options);
    }

    /** @override */
    get_text_row(y)
    {
        if(!(y >= 0 && y < this.text_height))
        {
            return "";
        }
        let previous_bg = null;
        let previous_fg = null;
        let row = "";
        for(let col = 0; col < this.text_width; col++)
        {
            const chr = this.charmap[this.get_cell(y, col, DUMMY_SCREEN_CHARACTER)];
            const bg_color = this.get_cell(y, col, DUMMY_SCREEN_BG_COLOR);
            const fg_color = this.get_cell(y, col, DUMMY_SCREEN_FG_COLOR);

            let ansi_code = "";
            // combine previous colors with current ones if possible
            if(previous_bg !== bg_color)
            {
                ansi_code += `\x1B[48;${hex_to_ansi_truecolor(bg_color)}m`;
                previous_bg = bg_color;
            }
            if(previous_fg !== fg_color)
            {
                ansi_code += `\x1B[38;${hex_to_ansi_truecolor(fg_color)}m`;
                previous_fg = fg_color;
            }
            row += ansi_code + chr;
        }
        return row + ANSI_RESET;
    }
}
                                                                                                                                                                                                                                                                                                                  source/v64/src/browser/cpu_worker.js                                                                0000644 0000000 0000000 00000064032 00000000000 014661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { state_stream_server } from "./state_stream_transport.js";
// Browser-side ownership boundary. Guest RAM and synchronous devices live only
// in the worker; this side owns DOM adapters and asynchronous GPU execution.
import { DISPLAY_SINK_REPLAY } from "../display.js";
import { default_graphics_adapter_path } from "../graphics_adapter.js";
import { default_glslang_wasm_path, default_plugin_path, default_tpm_wasm_path } from "../device_plugin.js";
import { is_arm, AUDIO_DEVICE_PLUGINS, NET_DEVICE_PLUGINS } from "../machine_options.js";

/**
 * @param {*} f
 * @param {number=} depth (a disk image's parents, backing)
 */
export function encode_worker_file(f, depth = 0)
{
    if(!f) return undefined;
    if(f.get || f.set || f.load) throw new Error("CPU Worker requires a URL, File or buffer disk descriptor");
    // (MAX_CHAIN_DEPTH of src/image/factory.js)
    if(depth > 16) throw new Error("CPU Worker: the backing images of a disk are nested too deeply (or circular)");
    return { "url": f.url && new URL(f.url, location.href).href,
        "buffer": f.buffer, "async": f.async, "size": f.size,
        "fixed_chunk_size": f.fixed_chunk_size, "use_parts": f.use_parts,
        // disk images (docs/disk-image-formats-plan.md): the worker opens them
        "format": f.format, "disk_option": f.disk_option, "image_id": f.image_id,
        // the disk's policy (docs/disk-persistence-plan.md): the worker builds its backend
        "disk_error": f.disk_error, "token": f.token,
        "overlay_limit": f.overlay_limit, "backing": f.backing ? encode_worker_file(f.backing, depth + 1) : undefined,
        "archive_member": f.archive_member, "logical_sector_size": f["logical_sector_size"],
        "files": f.files ? Object.fromEntries(Object.entries(f.files).map(([name, file]) => [name, encode_worker_file(file, depth + 1)])) : undefined };
}

/**
 * @param {!Object} o
 * @param {!Array<!Object>=} plugins device plugins: the worker loads their devices' scripts
 */
export function encode_worker_options(o, plugins = [], adapter_renderer = false)
{
    const file = encode_worker_file;
    const fs = o.filesystem;
    // (a built-in device's place behind a root port)
    const placement = device => device && typeof device === "object" && device.pcie_root_port !== undefined ?
        { "pcie_root_port": device.pcie_root_port, "pcie_plugged": device.pcie_plugged } : {};
    if(o.wasm_fn || fs?.handle9p) throw new Error("CPU Worker cannot transfer wasm_fn or handle9p callbacks");
    if(o["virtio_devices"]?.length) throw new Error("CPU Worker cannot transfer virtio_devices; their descriptors run on the CPU's thread");
    // (the defaults of src/browser/starter.js: an NE2000 and an SB16 on the PC machines)
    const net_type = o.net_device?.type || (is_arm(o["cpu_type"]) ? "virtio" : "ne2k");
    const audio_device = is_arm(o["cpu_type"]) ? o["audio_device"] : o["audio_device"] || "sb16";
    return {
        "device_plugins": plugins.map(plugin => {
            if(!plugin["worker_script"]) throw new Error("CPU Worker: " + plugin["name"] + " has no worker_script for its device");
            return { "name": plugin["name"], "script": new URL(plugin["worker_script"], location.href).href };
        }),
        // (the core of the CPU's family: docs/arm64-virt-android16-plan.md P1.3)
        "wasm_path": new URL(o.wasm_path || (is_arm(o["cpu_type"]) ? "build/v86-arm64.wasm" : "build/v86.wasm"), location.href).href,
        "wasm_fallback_path": o["wasm_fallback_path"] && new URL(o["wasm_fallback_path"], location.href).href,
        // (cores in vCPU workers, which this worker starts: absolute URLs)
        "parallel": o["parallel"],
        "parallel_wasm_path": o["parallel_wasm_path"] && new URL(o["parallel_wasm_path"], location.href).href,
        "vcpu_worker_url": o["vcpu_worker_url"] && new URL(o["vcpu_worker_url"], location.href).href,
        "memory_size": o.memory_size,
        // The worker loads the display adapter's plugin itself, from an absolute URL
        "graphics_adapter": o["graphics_adapter"], "vram_size": o["vram_size"],
        "graphics_adapter_test": o["graphics_adapter_test"],
        // whether the display adapter's 3D renderer is on the page (its channel is "graphics_adapter_renderer")
        "graphics_adapter_renderer": adapter_renderer,
        "graphics_adapter_path": o["graphics_adapter"] === "none" ? undefined :
            new URL(o["graphics_adapter_path"] || default_graphics_adapter_path(o["graphics_adapter"]), location.href).href,
        "extended_memory_size": o.extended_memory_size, "extended_memory_cache": o.extended_memory_cache,
        "high_memory_size": o.high_memory_size,
        "boot_order": o.boot_order, "acpi": o.acpi, "machine_type": o.machine_type, "pcie_root_ports": o.pcie_root_ports, "hpet": o.hpet, "smbus": o.smbus, "cpu_cores": o.cpu_cores,
        "cpu_clock": o.cpu_clock, "cpu_quantum": o.cpu_quantum, "cpu_schedule_seed": o.cpu_schedule_seed,
        "experimental_smp_jit": o.experimental_smp_jit, "disable_jit": o.disable_jit,
        "cpu_type": o["cpu_type"], "cpu_features": o["cpu_features"], "cpu_features_unreleased": o["cpu_features_unreleased"],
        "jit_backend": o["jit_backend"], "ir_tier0": o["ir_tier0"], "jit_switches": o["jit_switches"], "cpu_profile": o["cpu_profile"],
        "x87_fast_math": o["x87_fast_math"],
        "x87_jit_cache": o["x87_jit_cache"],
        "fastboot": o.fastboot, "bootmenu": o.bootmenu, "cmdline": o.cmdline,
        "cpuid_level": o.cpuid_level, "uart1": o.uart1, "uart2": o.uart2, "uart3": o.uart3,
        "parallel1": o.parallel1, "qemu_compatible": o.qemu_compatible,
        "virtio_balloon": o.virtio_balloon && (typeof o.virtio_balloon === "object" ? placement(o.virtio_balloon) : true),
        "virtio_console": o.virtio_console && (typeof o.virtio_console === "object" ? placement(o.virtio_console) : true),
        "modem": o.modem && { "uart": o.modem.uart },
        "preserve_mac_from_state_image": o.preserve_mac_from_state_image,
        "mac_address_translation": o.mac_address_translation,
        "net_device": { "type": net_type, "count": o.net_device?.count,
            // (a plugin card, like the display adapter: the worker loads it
            // from an absolute URL, the default NE2000's too)
            "plugin_path": NET_DEVICE_PLUGINS.includes(net_type) ?
                new URL(o.net_device?.plugin_path || default_plugin_path(net_type), location.href).href : undefined,
            "mtu": o.net_device?.mtu,
            ...placement(o.net_device) },
        // (a plugin card, as the network card's; the default SB16 on the PC machines)
        "audio_device": audio_device,
        "audio_device_path": AUDIO_DEVICE_PLUGINS.includes(audio_device) ?
            new URL(o["audio_device_path"] || default_plugin_path(audio_device), location.href).href : undefined,
        // (USB's plugin, likewise)
        "usb": o["usb"] ? { "controller": o["usb"]["controller"], "tablet": o["usb"]["tablet"],
            "plugin_path": new URL(o["usb"]["plugin_path"] || default_plugin_path("usb"), location.href).href,
            "mass_storage": o["usb"]["mass_storage"] && o["usb"]["mass_storage"].map(disk =>
                ({ "id": disk["id"], "image": file(disk["image"]), "read_only": disk["read_only"] })) } : undefined,
        "bios": file(o.bios), "vga_bios": file(o.vga_bios), "hda": file(o.hda), "hdb": file(o.hdb),
        "firmware": o.firmware && { "type": o.firmware.type, "debug_console": o.firmware.debug_console, "secure_boot": o.firmware.secure_boot,
            "code": file(o.firmware.code), "vars": file(o.firmware.vars) },
        // (the TPM's plugin and module: absolute URLs, as the other plugins')
        "tpm": o.tpm && { "version": o.tpm.version, "interface": o.tpm.interface, "state": file(o.tpm.state),
            "plugin_path": new URL(o.tpm.plugin_path || default_plugin_path("tpm"), location.href).href,
            "wasm_path": new URL(o.tpm.wasm_path || default_tpm_wasm_path(), location.href).href },
        "fda": file(o.fda), "fdb": file(o.fdb), "cdrom": file(o.cdrom),
        "multiboot": file(o.multiboot), "bzimage": file(o.bzimage), "initrd": file(o.initrd),
        // (machine_type "virt": docs/arm64-virt-android16-plan.md P1.1)
        "kernel": file(o.kernel), "dtb": file(o.dtb),
        // (docs/android-images-plan.md I2: the bootloader runs in the worker, beside the disk)
        "android": o.android && { "device": o.android.device, "gpu_mode": o.android.gpu_mode, "selinux": o.android.selinux,
            "vendor_ramdisk": file(o.android.vendor_ramdisk) },
        // (the ranchu machine's GPU mode; the GLES host's plugin by an absolute URL, as the other plugins')
        "ranchu_gpu": o.ranchu_gpu,
        "ranchu_gpu_path": new URL(o.ranchu_gpu_path || default_plugin_path("gles"), location.href).href,
        "gles_glslang_path": new URL(o.gles_glslang_path || default_glslang_wasm_path(), location.href).href,
        "ranchu_gles_version": o.ranchu_gles_version,
        "gles_backdoor": o.gles_backdoor,
        "virtio_disks": o.virtio_disks && o.virtio_disks.map(disk => Object.assign({}, file(disk), { "readonly": disk.readonly, "id": disk.id })),
        "virtio_rng": o.virtio_rng, "virtio_input": o.virtio_input, "virtio_transport": o.virtio_transport,
        "virtio_vsock": o.virtio_vsock, "virtio_sound": o.virtio_sound, "virtio_console_ports": o.virtio_console_ports, "virtio_gpu_pci_slot": o.virtio_gpu_pci_slot,
        "initial_state": file(o.initial_state),
        "filesystem": fs && { "baseurl": fs.baseurl && new URL(fs.baseurl, location.href).href,
            "basefs": typeof fs.basefs === "string" ? new URL(fs.basefs, location.href).href : file(fs.basefs),
            "proxy_url": fs.proxy_url, ...placement(fs) },
        "bzimage_initrd_from_filesystem": o.bzimage_initrd_from_filesystem,
        "disable_keyboard": true, "disable_mouse": true, "disable_speaker": true,
        "autostart": false,
    };
}

export class CPUWorkerController
{
    constructor(emulator, options)
    {
        this.emulator = emulator;
        this.options = options;
        /** whether the display adapter's 3D renderer is on this page (starter.js) */
        this.adapter_renderer = false;
        this.pending = new Map();
        this.next_id = 0;
        this.epoch = 1;
        this.failed = null;
        this.closed = false;
        this.startup_resolve = null;
        this.startup_reject = null;
        this.startup = new Promise((resolve, reject) => {
            this.startup_resolve = resolve;
            this.startup_reject = reject;
        });
        this.startup.catch(() => {});
        this.operations = this.startup;
        this.instructions = 0;
        this.frame_pending = false;
        this.full_frame_wanted = false;
        this.input_queue = [];
        this.ready = false;
        this.screen_queue = [];
        this.device_info = {};
        this.direct_audio = false;
        // Device plugins: the host side here, the device in the worker
        this.device_handlers = new Map();
        // (sent before the worker has made the devices)
        this.device_queue = [];
        this.devices_ready = false;
        const url = options["cpu_worker_url"] || "build/cpu-worker.js";
        this.worker = new Worker(url, { "name": "v86 CPU" });
        this.worker.onmessage = e => this.receive(e.data);
        this.worker.onerror = e => this.fail(new Error(e.message || "CPU Worker failed to start"));
        this.worker.onmessageerror = () => this.fail(new Error("CPU Worker message could not be decoded"));
        emulator.bus.send = (name, value) => {
            if(this.closed || this.failed) return;
            if(!this.ready) this.input_queue.push([name, value]);
            else this.post({ "type": "event", "epoch": this.epoch, "name": name, "value": value });
        };
    }

    post(message, transfer = []) { this.worker.postMessage(message, transfer); }

    /**
     * The host side's end of the channel to a plugin's device in the worker
     * @param {string} name
     */
    device_channel(name)
    {
        return {
            "remote": true,
            "post": (message, transfer) => {
                if(this.closed || this.failed) return;
                if(!this.devices_ready) this.device_queue.push([name, message, transfer]);
                else this.post({ "type": "device", "epoch": this.epoch, "name": name, "message": message }, transfer || []);
            },
            "listen": handler => { this.device_handlers.set(name, handler); },
        };
    }

    rpc(method, args = [], transfer = [])
    {
        if(this.closed || this.failed) return Promise.reject(this.failed || new Error("CPU Worker is closed"));
        const id = ++this.next_id;
        return new Promise((resolve, reject) => {
            this.pending.set(id, { resolve, reject });
            try { this.post({ "type": "rpc", "id": id, "method": method, "args": args }, transfer); }
            catch(error) { this.pending.delete(id); reject(error); }
        });
    }

    /**
     * V86.detach_pcie_device: the worker answers once the removal started
     * (one through the attention button waits for the guest, and the worker
     * does not hold the commands after it back), and reports its end as the
     * result for a second id
     * @param {number} port
     * @param {boolean} surprise
     * @return {!Promise<void>}
     */
    detach_pcie_device(port, surprise)
    {
        if(this.closed || this.failed) return Promise.reject(this.failed || new Error("CPU Worker is closed"));
        const done_id = ++this.next_id;
        const done = new Promise((resolve, reject) => this.pending.set(done_id, { resolve, reject }));
        // (its end may come before the answer)
        done.catch(() => {});
        return this.rpc("detach_pcie_device", [port, { "surprise": surprise }, done_id]).then(() => done, error => {
            this.pending.delete(done_id);
            throw error;
        });
    }

    fail(error)
    {
        if(this.failed || this.closed) return;
        this.failed = error;
        this.startup_reject(error);
        this.emulator.cpu_is_running = false;
        for(const p of this.pending.values()) p.reject(error);
        this.pending.clear();
        this.worker.terminate();
        this.emulator.screen_adapter?.pause();
        this.emulator.speaker_adapter?.pause();
        this.emulator.emulator_bus.send("emulator-error", error);
        console.error("[v86 CPU Worker]", error);
    }

    async start()
    {
        const plugins = this.emulator.device_plugins;
        await Promise.all(this.emulator.plugins_ready);
        const host_states = await this.rpc("init", [encode_worker_options(this.options, plugins, this.adapter_renderer)]);
        this.devices_ready = true;
        for(const [name, message, transfer] of this.device_queue.splice(0))
        {
            this.post({ "type": "device", "epoch": this.epoch, "name": name, "message": message }, transfer || []);
        }
        // initial_state
        for(const plugin of plugins)
        {
            const host_state = host_states[plugin["name"]];
            if(host_state === undefined) continue;
            plugin["before_restore"] && await plugin["before_restore"]();
            plugin["after_restore"] && await plugin["after_restore"](host_state);
        }
        const dac = this.emulator.speaker_adapter?.dac;
        if(dac?.connect_cpu_worker)
        {
            const port = await dac.connect_cpu_worker();
            await this.rpc("audio-attach", [port], [port]);
            this.direct_audio = true;
        }
        this.ready = true;
        for(const [name, value] of this.input_queue) this.emulator.bus.send(name, value);
        this.input_queue = [];
        if(this.options.autostart && !this.emulator.destroyed) await this.rpc("run");
        this.startup_resolve();
        this.emulator.emulator_bus.send("emulator-loaded");
        this.options = null;
    }

    receive(m)
    {
        if(this.closed || this.failed) return;
        if(m["type"] === "result")
        {
            const p = this.pending.get(m["id"]);
            if(!p) return;
            this.pending.delete(m["id"]);
            if(m["error"]) p.reject(new Error(m["error"])); else p.resolve(m["value"]);
            return;
        }
        if(m["type"] === "fatal") { this.fail(new Error(m["error"])); return; }
        if(m["type"] === "epoch")
        {
            this.epoch = m["epoch"];
            this.screen_queue = [];
            this.frame_pending = false;
            if(!this.direct_audio) this.emulator.emulator_bus.send("dac-reset");
            return;
        }
        if(m["epoch"] !== this.epoch) return;
        switch(m["type"])
        {
            case "event":
                if(m["name"] === "download-progress" || m["name"] === "download-error")
                {
                    const v = m["value"];
                    this.emulator.emulator_bus.send(m["name"], { file_name: v["file_name"],
                        file_index: v["file_index"], file_count: v["file_count"],
                        loaded: v["loaded"], total: v["total"], lengthComputable: v["lengthComputable"] });
                }
                else this.emulator.emulator_bus.send(m["name"], m["value"]);
                break;
            case "screen":
                // Guest text redraws can exceed the host's argument limit.
                // Append individually so even large bursts remain lossless.
                for(const command of m["commands"]) this.screen_queue.push(command);
                this.flush_screen();
                break;
            case "frame": this.frame_pending = false; this.draw_frame(m["layers"]); break;
            case "stats":
                this.instructions = m["value"]["instructions"];
                this.device_info = m["value"];
                break;
            case "device": {
                const handler = this.device_handlers.get(m["name"]);
                if(handler) handler(m["message"]);
                break;
            }
        }
    }

    flush_screen()
    {
        const s = this.emulator.screen_adapter;
        const bus = this.emulator.emulator_bus;
        for(const [name, args] of this.screen_queue.splice(0))
        {
            DISPLAY_SINK_REPLAY[name](s, args);
            // (the worker does not send this event: here it comes after the
            // screen has the character, as with the CPU in the page)
            if(name === "put_char") bus.send("screen-put-char", [args[0], args[1], args[2]]);
        }
    }

    request_frame(full)
    {
        if(full) this.full_frame_wanted = true;
        if(!this.ready || this.frame_pending || this.closed || this.failed) return;
        this.frame_pending = true;
        this.post({ "type": "frame", "epoch": this.epoch, "full": !!this.full_frame_wanted });
        this.full_frame_wanted = false;
    }

    draw_frame(layers)
    {
        this.emulator.screen_adapter.update_buffer(layers.map(l => ({
            pixels: { data: l["pixels"], width: l["width"], height: l["height"] },
            screen_x: l["x"], screen_y: l["y"], buffer_x: 0, buffer_y: 0,
            buffer_width: l["width"], buffer_height: l["height"],
        })));
    }

    serialize(operation)
    {
        const next = this.operations.catch(() => {}).then(operation);
        this.operations = next.then(() => {}, () => {});
        return next;
    }

    async stop()
    {
        await this.rpc("stop");
        // Acknowledging a batch can release another pending virtqueue request.
        // Drain to a fixed point, not just the work observed at stop time.
        let pending;
        do {
            await Promise.all(this.emulator.device_plugins.map(plugin => plugin["idle"] && plugin["idle"]()));
            pending = await this.rpc("barrier");
        } while(pending);
        await this.emulator.speaker_adapter?.pause();
    }

    /** @return {!Promise<!Object>} each plugin's host state, by name */
    async prepare_plugins_save()
    {
        const host_states = {};
        for(const plugin of this.emulator.device_plugins)
        {
            if(plugin["prepare_save"]) host_states[plugin["name"]] = await plugin["prepare_save"]();
        }
        return host_states;
    }

    release_plugins_save()
    {
        for(const plugin of this.emulator.device_plugins)
        {
            plugin["release_save"] && plugin["release_save"]();
        }
    }

    async before_plugins_restore()
    {
        for(const plugin of this.emulator.device_plugins)
        {
            plugin["before_restore"] && await plugin["before_restore"]();
        }
    }

    async after_plugins_restore(host_states)
    {
        for(const plugin of this.emulator.device_plugins)
        {
            plugin["after_restore"] && await plugin["after_restore"](host_states[plugin["name"]]);
        }
    }

    cancel_plugins_restore()
    {
        for(const plugin of this.emulator.device_plugins)
        {
            plugin["cancel_restore"] && plugin["cancel_restore"]();
        }
    }

    state(kind, state = null)
    {
        return this.serialize(async () => {
            const running = this.emulator.is_running();
            await this.stop();
            let ok = false;
            try
            {
                if(kind === "save")
                {
                    const result = await this.rpc("save", [await this.prepare_plugins_save()]);
                    ok = true;
                    return result;
                }
                if(kind === "restart")
                {
                    await this.rpc("restart", state ? [state] : []);
                    for(const plugin of this.emulator.device_plugins)
                    {
                        plugin["reset"] && await plugin["reset"]();
                    }
                    ok = true;
                    return;
                }
                await this.before_plugins_restore();
                await this.after_plugins_restore(await this.rpc(kind, state ? [state] : []));
                ok = true;
            }
            catch(error)
            {
                if(kind !== "save") this.cancel_plugins_restore();
                throw error;
            }
            finally
            {
                if(kind === "save") this.release_plugins_save();
                if(running && !this.emulator.destroyed && (ok || kind === "save")) await this.rpc("run");
            }
        });
    }

    state_stream(kind, value)
    {
        return this.serialize(async () => {
            const running = this.emulator.is_running();
            await this.stop();
            const channel = new globalThis.MessageChannel();
            const server = state_stream_server(channel.port1, kind, value);
            let success = false;
            try
            {
                if(kind === "save")
                {
                    await this.rpc("save-stream", [await this.prepare_plugins_save(), channel.port2], [channel.port2]);
                }
                else
                {
                    await this.before_plugins_restore();
                    await this.after_plugins_restore(
                        await this.rpc("restore-stream", [server["size"], channel.port2], [channel.port2]));
                }
                success = true;
            }
            catch(error)
            {
                if(kind !== "save") this.cancel_plugins_restore();
                throw error;
            }
            finally
            {
                server["close"]();
                if(kind === "save") this.release_plugins_save();
                if(running && !this.emulator.destroyed && (success || kind === "save")) await this.rpc("run");
            }
        });
    }

    /**
     * V86.export_disk_image: the worker writes the chunks to a port, one at a
     * time, and each waits for the page's write to finish (backpressure);
     * after the signal aborts, the next chunk's write fails the export
     * @param {string} name
     * @param {!Object} options write, progress, signal
     * @return {!Promise<number>}
     */
    export_disk(name, options)
    {
        return this.serialize(async () => {
            const info = await this.rpc("disk-info", [name]);
            // (a QCOW2 image's size is known once the disk was read)
            const total = options.format === "qcow2" ? undefined : info["size"];
            const channel = new globalThis.MessageChannel();
            let loaded = 0;
            const port = channel.port1;
            const receive = async event => {
                const message = event.data, id = message["id"];
                try
                {
                    if(options.signal && options.signal.aborted) throw new Error("The export was cancelled at " + loaded + " of " + total + " bytes");
                    const bytes = message["bytes"];
                    if(message["kind"] !== "write" || !(bytes instanceof Uint8Array)) throw new Error("Invalid export chunk");
                    await options.write(bytes);
                    loaded += bytes.length;
                    options.progress && options.progress({ loaded, total });
                    port.postMessage({ "id": id });
                }
                catch(error)
                {
                    port.postMessage({ "id": id, "error": String(error && error.message || error) });
                }
            };
            port.onmessage = event => { receive(event); };
            options.progress && options.progress({ loaded: 0, total });
            try
            {
                return await this.rpc("export-disk", [name, channel.port2, { "format": options.format }], [channel.port2]);
            }
            finally
            {
                port.close();
            }
        });
    }

    async destroy()
    {
        if(this.closed) return;
        await this.operations.catch(() => {});
        if(!this.failed)
        {
            try { await this.stop(); await this.rpc("destroy"); }
            finally { this.close(); }
        }
        else this.close();
    }

    close()
    {
        this.closed = true;
        this.startup_reject(new Error("CPU Worker destroyed"));
        this.worker.terminate();
        for(const p of this.pending.values()) p.reject(new Error("CPU Worker destroyed"));
        this.pending.clear();
        this.input_queue = [];
        this.screen_queue = [];
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/browser/cpu_worker_entry.js                                                          0000644 0000000 0000000 00000000120 00000000000 016066  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { start_cpu_worker } from "./cpu_worker_runtime.js";
start_cpu_worker();
                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/browser/cpu_worker_runtime.js                                                        0000644 0000000 0000000 00000042536 00000000000 016431  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { state_stream_client } from "./state_stream_transport.js";
import { wasm_fallback_path } from "./wasm_paths.js";
import { instantiate_v86 } from "../parallel/relocate.js";
// Dedicated-worker entry. Never transfer the WebAssembly.Memory buffer.
import { V86 } from "./starter.js";
import { DisplaySinkRecorder } from "../display.js";

export function start_cpu_worker()
{
    let emulator, epoch = 1;
    let screen_commands = [], screen_scheduled = false, frame_layers = [];
    let timer, command_chain = Promise.resolve();
    let audio_port = null, audio_reset_done = null, audio_enabled = false, audio_rate = 22050;
    let audio_sequence = 0;
    const audio_stats = { "pcm_buffers": 0, "pcm_samples": 0, "pump_requests": 0 };
    const audio_send = (type, value, transfer = []) => audio_port?.postMessage({ "cpu_audio": type, "epoch": epoch, "value": value, "sequence": audio_sequence }, transfer);
    const audio_reset = () => {
        if(!audio_port) return Promise.resolve();
        return new Promise(resolve => { ++audio_sequence; audio_reset_done = resolve; audio_send("reset", null); });
    };
    const send = (type, value = {}, transfer = []) =>
        globalThis.postMessage({ "type": type, "epoch": epoch, ...value }, transfer);
    const fatal = error => {
        if(emulator) emulator.stop();
        send("fatal", { "error": String(error?.stack || error) });
    };
    globalThis.addEventListener("unhandledrejection", e => { e.preventDefault(); fatal(e.reason); });
    const flush_screen = () => {
        screen_scheduled = false;
        if(screen_commands.length) send("screen", { "commands": screen_commands });
        screen_commands = [];
    };
    const screen_call = (name, args) => {
        screen_commands.push([name, args]);
        if(!screen_scheduled) { screen_scheduled = true; globalThis.queueMicrotask(flush_screen); }
    };
    const screen = new DisplaySinkRecorder(screen_call, layers => {
        for(const l of layers)
        {
            const w = l.buffer_width, h = l.buffer_height;
            if(!(w > 0 && h > 0)) continue;
            const pixels = new Uint8ClampedArray(w * h * 4);
            for(let y = 0; y < h; y++)
            {
                const offset = ((l.buffer_y + y) * l.pixels.width + l.buffer_x) * 4;
                pixels.set(l.pixels.data.subarray(offset, offset + w * 4), y * w * 4);
            }
            frame_layers.push({ "pixels": pixels, "width": w, "height": h, "x": l.screen_x, "y": l.screen_y });
        }
    });
    const stats = () => {
        if(!emulator?.v86?.cpu) return;
        const cpu = emulator.v86.cpu;
        send("stats", { "value": { "instructions": emulator.get_instruction_counter(),
            "memory_size": cpu.memory_size[0], "cdrom": !!cpu.devices.cdrom,
            "cdrom_present": !!cpu.devices.cdrom?.has_disk() } });
    };
    // The devices of device plugins (docs/graphics-proxy-plugin-plan.md): each
    // talks to its host side on the page over these messages
    const device_handlers = new Map();
    const device_channel = name => ({
        "remote": true,
        "post": (message, transfer) => send("device", { "name": name, "message": message }, transfer || []),
        "listen": handler => { device_handlers.set(name, handler); },
    });
    const virtio_devices = () => emulator?.v86?.cpu?.devices?.virtio_devices || [];
    // What the devices still wait for from the page; a snapshot needs none
    const busy = () => virtio_devices().reduce((n, device) => n + device.busy(), 0);
    // Host states travel in the snapshot with their devices
    const set_host_states = states => {
        for(const device of virtio_devices()) device.host_state = states ? states[device.name] : undefined;
    };
    const take_host_states = () => {
        const states = {};
        for(const device of virtio_devices())
        {
            if(device.restored_host_state !== undefined) states[device.name] = device.restored_host_state;
            device.restored_host_state = undefined;
        }
        return states;
    };
    const change_epoch = async () => {
        ++epoch;
        screen_commands = [];
        send("epoch");
        await audio_reset();
    };
    const disk = name => {
        const d = emulator.v86.cpu.devices;
        switch(name)
        {
            case "hda": case "hdb": case "cdrom": return emulator.v86.cpu.disk_device(name).buffer;
            case "fda": return d.fdc.drives[0].buffer;
            case "fdb": return d.fdc.drives[1].buffer;
        }
        throw new Error("Unknown disk");
    };
    const methods = {
        "init": async options => {
            if(emulator) throw new Error("CPU Worker already initialized");
            options["screen_adapter"] = screen;
            // Fail a missing/invalid core explicitly. The legacy XHR loader can
            // otherwise leave startup pending indefinitely after a 404.
            options.wasm_fn = async env => {
                const primary = options.wasm_path;
                const fallback = options["wasm_fallback_path"] || wasm_fallback_path(primary);
                // (cores in vCPU workers: the relocatable build; "auto" falls
                // back to the cooperative one, and the emulator says why)
                const parallel = emulator && emulator.parallel_requested && options["parallel_wasm_path"];
                const urls = parallel ? [parallel].concat(emulator.parallel_forced ? [] : [primary, fallback]) : [primary, fallback];
                let last_error;
                for(const url of new Set(urls))
                {
                    try
                    {
                        const response = await fetch(url);
                        if(!response.ok) throw new Error("CPU core fetch failed: HTTP " + response.status);
                        const bytes = await response.arrayBuffer();
                        const result = await instantiate_v86(bytes, env);
                        emulator.wasm_source = bytes;
                        return result.instance.exports;
                    }
                    catch(error) { last_error = error; }
                }
                throw last_error;
            };
            // No network or DOM adapters here. Those connect through the bus.
            options.modem = undefined;
            const plugins = options["device_plugins"] || [];
            for(const plugin of plugins) globalThis.importScripts(plugin["script"]);
            options["virtio_devices"] = plugins.map(plugin => {
                const factories = globalThis["V86VirtioDeviceFactories"];
                const create = factories && factories[plugin["name"]];
                if(typeof create !== "function")
                {
                    throw new Error("CPU Worker: " + plugin["script"] + " defines no device " + plugin["name"]);
                }
                return create(device_channel(plugin["name"]));
            });
            // the display adapter's 3D renderer, on the page
            if(options["graphics_adapter_renderer"]) options["graphics_adapter_renderer_channel"] = device_channel("graphics_adapter_renderer");
            options["worker_bus_setup"] = instance => {
                emulator = instance;
                const original = instance.emulator_bus.send.bind(instance.emulator_bus);
                instance.emulator_bus.send = (name, value, transfer) => {
                    if(name === "emulator-ready") stats();
                    original(name, value, undefined);
                    if(name === "dac-send-data") { ++audio_stats["pcm_buffers"]; audio_stats["pcm_samples"] += value[0].length; }
                    if(name === "dac-tell-sampling-rate") audio_rate = value;
                    if(name === "dac-enable") audio_enabled = true;
                    if(name === "dac-disable") audio_enabled = false;
                    if(audio_port)
                    {
                        if(name === "dac-send-data")
                        {
                            audio_send("queue", value, value.map(channel => channel.buffer));
                            return;
                        }
                        if(name === "dac-tell-sampling-rate") { audio_send("rate", value); return; }
                        if(name === "dac-reset") { audio_send("reset", null); return; }
                        if(name === "emulator-started" || name === "emulator-stopped" || name === "dac-enable" || name === "dac-disable")
                            audio_send("enabled", audio_enabled && emulator.is_running());
                    }
                    if(name === "emulator-loaded") return;
                    // The page sends each character's event itself, once its
                    // screen has the character (CPUWorkerController.flush_screen)
                    if(name === "screen-put-char") return;
                    // The screen's changes before an event reach the page before it
                    if(screen_commands.length) flush_screen();
                    if(name === "download-error") value = { "file_name": value.file_name };
                    // Structured clone snapshots buffers before synchronous guest
                    // execution resumes. PCM buffers are independently owned.
                    if(name === "dac-send-data")
                    {
                        const pcm = value.map(channel => channel.slice());
                        send("event", { "name": name, "value": pcm }, pcm.map(channel => channel.buffer));
                    }
                    else send("event", { "name": name, "value": value });
                };
            };
            await new Promise((resolve, reject) => {
                new V86(options);
                emulator.add_listener("emulator-loaded", resolve);
                emulator.add_listener("emulator-error", reject);
            });
            flush_screen();
            stats();
            timer = setInterval(stats, 250);
            // from initial_state
            return take_host_states();
        },
        "audio-attach": async port => {
            audio_port = port;
            audio_port.onmessage = e => {
                const m = e.data;
                if(m["epoch"] !== epoch) return;
                if(m["cpu_audio"] === "reset-done" && m["sequence"] === audio_sequence && audio_reset_done)
                {
                    const done = audio_reset_done; audio_reset_done = null; done();
                }
                if(m["cpu_audio"] === "pump" && audio_enabled && emulator.is_running())
                {
                    ++audio_stats["pump_requests"];
                    emulator.bus.send("dac-request-data");
                }
            };
            await audio_reset();
            audio_send("rate", audio_rate);
            audio_send("enabled", audio_enabled && emulator.is_running());
        },
        "run": () => emulator.run(),
        // (the page goes away: src/disk_service.js)
        "pagehide": () => emulator.pagehide_disks(),
        "stop": async () => { await emulator.stop(); flush_screen(); stats(); },
        "barrier": () => busy(),
        "save": async host_states => {
            if(emulator.is_running() || busy()) throw new Error("Save requires a drained, stopped CPU");
            set_host_states(host_states);
            try { return await emulator.save_state(); }
            finally { set_host_states(null); }
        },
        "restore": async state => {
            if(emulator.is_running() || busy()) throw new Error("Restore requires a drained, stopped CPU");
            await change_epoch();
            await emulator.restore_state(state);
            await audio_reset();
            flush_screen(); stats();
            return take_host_states();
        },
        "save-stream": async (host_states, port) => {
            if(emulator.is_running() || busy()) throw new Error("Save requires a drained, stopped CPU");
            const stream = state_stream_client(port);
            set_host_states(host_states);
            try { await emulator.save_state_stream(stream["write"]); }
            finally { set_host_states(null); stream["close"](); }
        },
        "restore-stream": async (size, port) => {
            if(emulator.is_running() || busy()) throw new Error("Restore requires a drained, stopped CPU");
            const stream = state_stream_client(port);
            try
            {
                await change_epoch();
                await emulator.restore_state_stream({ "size": size, "read": stream["read"] });
                await audio_reset();
                flush_screen(); stats();
                return take_host_states();
            }
            finally { stream["close"](); }
        },
        "restart": async reason => { await change_epoch(); await emulator.restart(reason); await audio_reset(); flush_screen(); stats(); },
        "power_button": () => emulator.power_button(),
        "power_state": () => emulator.power_state(),
        "get_diagnostics": () => emulator.get_diagnostics(),
        "destroy": async () => { clearInterval(timer); await emulator.destroy(); audio_port?.close(); },
        "read_memory": (offset, length) => emulator.read_memory(offset, length).slice(),
        "write_memory": (bytes, offset) => emulator.write_memory(bytes, offset),
        "memory_dump": () => emulator.v86.cpu.mem8.slice(),
        "disk-info": name => emulator.disk_image_info(name),
        "export-disk": async (name, port, options) => {
            const stream = state_stream_client(port);
            try { return await emulator.export_disk_image(name, { write: stream["write"], format: options && options["format"] }); }
            finally { stream["close"](); }
        },
        "disk": name => {
            const buffer = disk(name);
            // (a local file read in parts, which has no buffer: the file with
            // the blocks written, a File the page gets without a copy)
            if(buffer.get_as_file) return buffer.get_as_file(buffer.file.name);
            return new Promise(resolve => buffer.get_buffer(bytes => resolve(bytes?.slice(0))));
        },
        "set_fda": file => emulator.set_fda(file), "set_fdb": file => emulator.set_fdb(file),
        "set_cdrom": file => emulator.set_cdrom(file),
        "eject_fda": () => emulator.eject_fda(), "eject_fdb": () => emulator.eject_fdb(),
        "eject_cdrom": () => emulator.eject_cdrom(),
        "get_cdrom_state": () => emulator.get_cdrom_state(),
        "attach_sata_drive": (port, file, options) => emulator.attach_sata_drive(port, file || null, options),
        "detach_sata_drive": port => emulator.detach_sata_drive(port),
        "usb_attach_disk": (id, file, options) => emulator.usb_attach_disk(id, file, options),
        "usb_devices": () => emulator.usb_devices(),
        "usb_detach_disk": id => emulator.usb_detach_disk(id),
        "attach_pcie_device": port => emulator.attach_pcie_device(port),
        // (answered once the removal started: one through the attention
        // button waits for the guest, and the commands after it must not;
        // its end comes as the result for done_id)
        "detach_pcie_device": (port, options, done_id) => {
            emulator.detach_pcie_device(port, options).then(
                () => send("result", { "id": done_id, "value": undefined }),
                error => send("result", { "id": done_id, "error": String(error?.stack || error) }));
        },
        "get_disk_fda": () => emulator.get_disk_fda()?.slice() || null, "get_disk_fdb": () => emulator.get_disk_fdb()?.slice() || null,
        "create_file": (name, bytes) => emulator.create_file(name, bytes),
        "read_file": async name => (await emulator.read_file(name))?.slice(),
        "audio-info": () => ({ ...audio_stats, "direct": !!audio_port, "sample_rate": audio_rate }),
        "get_instruction_stats": () => emulator.get_instruction_stats(),
        "get_jit_info": () => emulator.get_jit_info(),
    };
    globalThis.onmessage = e => {
        const m = e.data;
        if(m["type"] === "rpc")
        {
            const work = command_chain.then(async () => {
                const fn = methods[m["method"]];
                if(!fn || !Object.prototype.hasOwnProperty.call(methods, m["method"])) throw new Error("Unknown worker method");
                return fn(...m["args"]);
            });
            command_chain = work.then(value => {
                const transfer = value instanceof ArrayBuffer ? [value] :
                    ArrayBuffer.isView(value) ? [value.buffer] : [];
                send("result", { "id": m["id"], "value": value }, transfer);
            }, error => send("result", { "id": m["id"], "error": String(error?.stack || error) }));
            return;
        }
        if(m["epoch"] !== epoch || !emulator?.v86) return;
        try
        {
            switch(m["type"])
            {
                case "event":
                    if(m["name"] !== "dac-request-data" || !audio_port) emulator.bus.send(m["name"], m["value"]);
                    break;
                case "frame":
                    frame_layers = [];
                    emulator.v86.cpu.devices.display?.request_frame(!!m["full"]);
                    send("frame", { "layers": frame_layers }, frame_layers.map(l => l["pixels"].buffer));
                    frame_layers = [];
                    break;
                case "device": {
                    const handler = device_handlers.get(m["name"]);
                    if(handler) handler(m["message"]);
                    break;
                }
            }
        }
        catch(error) { fatal(error); }
    };
}
                                                                                                                                                                  source/v64/src/browser/dummy_screen.js                                                              0000644 0000000 0000000 00000007453 00000000000 015177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "../log.js";
import { get_charmap } from "../lib.js";

// For Types Only
import { DisplaySink } from "../display.js";

const CHARACTER_INDEX = 0;
const FLAGS_INDEX = 1;
const BG_COLOR_INDEX = 2;
const FG_COLOR_INDEX = 3;
const TEXT_BUF_COMPONENT_SIZE = 4;

/**
 * Shows nothing and remembers the text screen. Used where there is no screen
 * (node), and the base of presenters that only need the text.
 * @implements {DisplaySink}
 */
export class DummyScreenAdapter
{
    /** @param {Object=} options */
    constructor(options)
    {
        /** 8-bit text to Unicode */
        this.charmap = get_charmap(options?.encoding);

        /** @type {!Int32Array} character, flags, background, foreground per cell */
        this.text = new Int32Array(0);
        this.text_width = 0;
        this.text_height = 0;

        this.cursor_row = 0;
        this.cursor_col = 0;

        this.graphical = false;
        this.graphical_width = 0;
        this.graphical_height = 0;

        this.set_size_text(80, 25);
    }

    /** @override */
    put_char(row, col, chr, flags, bg_color, fg_color)
    {
        dbg_assert(row >= 0 && row < this.text_height);
        dbg_assert(col >= 0 && col < this.text_width);
        dbg_assert(chr >= 0 && chr < 0x100);

        const p = TEXT_BUF_COMPONENT_SIZE * (row * this.text_width + col);
        this.text[p + CHARACTER_INDEX] = chr;
        this.text[p + FLAGS_INDEX] = flags;
        this.text[p + BG_COLOR_INDEX] = bg_color;
        this.text[p + FG_COLOR_INDEX] = fg_color;
    }

    /** @override */
    destroy() {}

    /** @override */
    pause() {}

    /** @override */
    continue() {}

    /** @override */
    clear_text_state()
    {
        this.text_width = 0;
        this.text_height = 0;
    }

    /** @override */
    set_mode(graphical)
    {
        this.graphical = graphical;
    }

    /** @override */
    set_font_bitmap(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed) {}

    /** @override */
    set_font_page(page_a, page_b) {}

    /** @override */
    clear_screen() {}

    /** @override */
    set_size_text(cols, rows)
    {
        if(cols === this.text_width && rows === this.text_height)
        {
            return;
        }

        this.text = new Int32Array(cols * rows * TEXT_BUF_COMPONENT_SIZE);
        this.text_width = cols;
        this.text_height = rows;
    }

    /** @override */
    set_size_graphical(width, height, buffer_width, buffer_height)
    {
        this.graphical_width = width;
        this.graphical_height = height;
    }

    /** @override */
    set_scale(s_x, s_y) {}

    /** @override */
    update_cursor_scanline(start, end, enabled) {}

    /** @override */
    update_cursor(row, col)
    {
        this.cursor_row = row;
        this.cursor_col = col;
    }

    /** @override */
    update_buffer(layers) {}

    /** @override */
    get_text_screen()
    {
        const screen = [];

        for(let i = 0; i < this.text_height; i++)
        {
            screen.push(this.get_text_row(i));
        }

        return screen;
    }

    /** @override */
    get_text_row(y)
    {
        if(!(y >= 0 && y < this.text_height))
        {
            return "";
        }
        let row = "";
        for(let col = 0; col < this.text_width; col++)
        {
            row += this.charmap[this.get_cell(y, col, CHARACTER_INDEX)];
        }
        return row;
    }

    /**
     * @param {number} row
     * @param {number} col
     * @param {number} component CHARACTER_INDEX .. FG_COLOR_INDEX
     * @return {number}
     */
    get_cell(row, col, component)
    {
        return this.text[TEXT_BUF_COMPONENT_SIZE * (row * this.text_width + col) + component];
    }
}

export { CHARACTER_INDEX as DUMMY_SCREEN_CHARACTER, BG_COLOR_INDEX as DUMMY_SCREEN_BG_COLOR, FG_COLOR_INDEX as DUMMY_SCREEN_FG_COLOR };
                                                                                                                                                                                                                     source/v64/src/browser/fake_network.js                                                              0000644 0000000 0000000 00000134175 00000000000 015166  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_FETCH } from "../const.js";
import { h } from "../lib.js";
import { dbg_assert, dbg_log } from "../log.js";

// https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml
const ETHERTYPE_IPV4 = 0x0800;
const ETHERTYPE_ARP = 0x0806;
const ETHERTYPE_IPV6 = 0x86DD;

const IPV4_PROTO_ICMP = 1;
const IPV4_PROTO_TCP = 6;
const IPV4_PROTO_UDP = 17;

const UNIX_EPOCH = new Date("1970-01-01T00:00:00Z").getTime();
const NTP_EPOCH = new Date("1900-01-01T00:00:00Z").getTime();
const NTP_EPOC_DIFF = UNIX_EPOCH - NTP_EPOCH;
const TWO_TO_32 = Math.pow(2, 32);

const DHCP_MAGIC_COOKIE = 0x63825363;
const V86_ASCII = [118, 56, 54];

/* For the complete TCP state diagram see:
 *
 *   https://en.wikipedia.org/wiki/File:Tcp_state_diagram_fixed_new.svg
 *
 * State TIME_WAIT is not needed, we can skip it and transition directly to CLOSED instead.
 */
export const TCP_STATE_CLOSED = "closed";
export const TCP_STATE_SYN_RECEIVED = "syn-received";
export const TCP_STATE_SYN_SENT = "syn-sent";
export const TCP_STATE_SYN_PROBE = "syn-probe";
//const TCP_STATE_LISTEN = "listen";
export const TCP_STATE_ESTABLISHED = "established";
export const TCP_STATE_FIN_WAIT_1 = "fin-wait-1";
export const TCP_STATE_CLOSE_WAIT = "close-wait";
export const TCP_STATE_FIN_WAIT_2 = "fin-wait-2";
export const TCP_STATE_LAST_ACK = "last-ack";
export const TCP_STATE_CLOSING = "closing";
//const TCP_STATE_TIME_WAIT = "time-wait";

// source: RFC6335, 6. Port Number Ranges
const TCP_DYNAMIC_PORT_START = 49152;
const TCP_DYNAMIC_PORT_END   = 65535;
const TCP_DYNAMIC_PORT_RANGE = TCP_DYNAMIC_PORT_END - TCP_DYNAMIC_PORT_START;

const ETH_HEADER_SIZE     = 14;
const ETH_PAYLOAD_OFFSET  = ETH_HEADER_SIZE;
const MTU_DEFAULT         = 1500;
const ETH_TRAILER_SIZE    = 4;
const IPV4_HEADER_SIZE    = 20;
const IPV4_PAYLOAD_OFFSET = ETH_PAYLOAD_OFFSET + IPV4_HEADER_SIZE;
const UDP_HEADER_SIZE     = 8;
const UDP_PAYLOAD_OFFSET  = IPV4_PAYLOAD_OFFSET + UDP_HEADER_SIZE;
const TCP_HEADER_SIZE     = 20;
const TCP_PAYLOAD_OFFSET  = IPV4_PAYLOAD_OFFSET + TCP_HEADER_SIZE;
const ICMP_HEADER_SIZE    = 4;

const DEFAULT_DOH_SERVER = "cloudflare-dns.com";

function a2ethaddr(bytes) {
    return [0,1,2,3,4,5].map((i) => bytes[i].toString(16)).map(x => x.length === 1 ? "0" + x : x).join(":");
}

function iptolong(parts) {
    return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3];
}

class GrowableRingbuffer
{
    /**
     * @param {number} initial_capacity
     * @param {number} maximum_capacity
     */
    constructor(initial_capacity, maximum_capacity)
    {
        initial_capacity = Math.min(initial_capacity, 16);
        this.maximum_capacity = maximum_capacity ? Math.max(maximum_capacity, initial_capacity) : 0;
        this.tail = 0;
        this.head = 0;
        this.length = 0;
        this.buffer = new Uint8Array(initial_capacity);
    }

    /**
     * @param {Uint8Array} src_array
     */
    write(src_array)
    {
        const src_length = src_array.length;
        const total_length = this.length + src_length;
        let capacity = this.buffer.length;
        if(capacity < total_length) {
            dbg_assert(capacity > 0);
            while(capacity < total_length) {
                capacity *= 2;
            }
            if(this.maximum_capacity && capacity > this.maximum_capacity) {
                throw new Error("stream capacity overflow in GrowableRingbuffer.write(), package dropped");
            }
            const new_buffer = new Uint8Array(capacity);
            this.peek(new_buffer);
            this.tail = 0;
            this.head = this.length;
            this.buffer = new_buffer;
        }
        const buffer = this.buffer;

        const new_head = this.head + src_length;
        if(new_head > capacity) {
            const i_split = capacity - this.head;
            buffer.set(src_array.subarray(0, i_split), this.head);
            buffer.set(src_array.subarray(i_split));
        }
        else {
            buffer.set(src_array, this.head);
        }
        this.head = new_head % capacity;
        this.length += src_length;
    }

    /**
     * @param {Uint8Array} dst_array
     */
    peek(dst_array)
    {
        const length = Math.min(this.length, dst_array.length);
        if(length) {
            const buffer = this.buffer;
            const capacity = buffer.length;
            const new_tail = this.tail + length;
            if(new_tail > capacity) {
                const buf_len_left = new_tail % capacity;
                const buf_len_right = capacity - this.tail;
                dst_array.set(buffer.subarray(this.tail));
                dst_array.set(buffer.subarray(0, buf_len_left), buf_len_right);
            }
            else {
                dst_array.set(buffer.subarray(this.tail, new_tail));
            }
        }
        return length;
    }

    /**
     * @param {number} length
     */
    remove(length)
    {
        if(length > this.length) {
            length = this.length;
        }
        if(length) {
            this.tail = (this.tail + length) % this.buffer.length;
            this.length -= length;
        }
        return length;
    }
}

export function create_eth_encoder_buf(mtu = MTU_DEFAULT)
{
    const ETH_FRAME_SIZE = ETH_HEADER_SIZE + mtu + ETH_TRAILER_SIZE;
    const IPV4_PAYLOAD_SIZE = mtu - IPV4_HEADER_SIZE;
    const UDP_PAYLOAD_SIZE = IPV4_PAYLOAD_SIZE - UDP_HEADER_SIZE;

    const eth_frame = new Uint8Array(ETH_FRAME_SIZE);
    const buffer = eth_frame.buffer;
    const offset = eth_frame.byteOffset;
    return {
        eth_frame: eth_frame,
        eth_frame_view: new DataView(buffer),
        eth_payload_view: new DataView(buffer, offset + ETH_PAYLOAD_OFFSET, mtu),
        ipv4_payload_view: new DataView(buffer, offset + IPV4_PAYLOAD_OFFSET, IPV4_PAYLOAD_SIZE),
        udp_payload_view: new DataView(buffer, offset + UDP_PAYLOAD_OFFSET, UDP_PAYLOAD_SIZE),
        text_encoder: new TextEncoder()
    };
}

/**
 * Copy given data array into view starting at offset, return number of bytes written.
 *
 * @param {number} offset
 * @param {ArrayBuffer|ArrayBufferView} data
 * @param {DataView} view
 * @param {Object} out
 */
function view_set_array(offset, data, view, out)
{
    out.eth_frame.set(data, view.byteOffset + offset);
    return data.length;
}

/**
 * Write zeros into the view starting at offset
 * @param {number} offset
 * @param {number} length
 * @param {DataView} view
 */
function view_set_zeros(offset, length, view, out)
{
    out.eth_frame.fill(0, view.byteOffset + offset, view.byteOffset + offset + length);
}

/**
 * UTF8-encode given string into view starting at offset, return number of bytes written.
 *
 * @param {number} offset
 * @param {string} str
 * @param {DataView} view
 * @param {Object} out
 */
function view_set_string(offset, str, view, out)
{
    return out.text_encoder.encodeInto(str, out.eth_frame.subarray(view.byteOffset + offset)).written;
}

/**
 * Calculate internet checksum for view[0 : length] and return the 16-bit result.
 * Source: RFC768 and RFC1071 (chapter 4.1).
 *
 * @param {number} length
 * @param {number} checksum
 * @param {DataView} view
 * @param {Object} out
 */
function calc_inet_checksum(length, checksum, view, out)
{
    const uint16_end = view.byteOffset + (length & ~1);
    const eth_frame = out.eth_frame;
    for(let i = view.byteOffset; i < uint16_end; i += 2) {
        checksum += eth_frame[i] << 8 | eth_frame[i+1];
    }
    if(length & 1) {
        checksum += eth_frame[uint16_end] << 8;
    }
    while(checksum >>> 16) {
        checksum = (checksum & 0xffff) + (checksum >>> 16);
    }
    return ~checksum & 0xffff;
}

/**
 * @param {Object} out
 * @param {Object} spec
 */
function make_packet(out, spec)
{
    dbg_assert(spec.eth);
    out.eth_frame.fill(0);
    return out.eth_frame.subarray(0, write_eth(spec, out));
}

function handle_fake_tcp(packet, adapter)
{
    const tuple = `${packet.ipv4.src.join(".")}:${packet.tcp.sport}:${packet.ipv4.dest.join(".")}:${packet.tcp.dport}`;

    if(packet.tcp.syn && !packet.tcp.ack) {
        if(adapter.tcp_conn[tuple]) {
            dbg_log("SYN to already opened port", LOG_FETCH);
            delete adapter.tcp_conn[tuple];
        }

        let conn = new TCPConnection(adapter);
        conn.state = TCP_STATE_SYN_RECEIVED;
        conn.tuple = tuple;
        conn.last = packet;

        // packet.* address fields are subarrays of the NIC TX buffer; copy
        // them so later guest TX doesn't silently retarget our replies.
        conn.hsrc = new Uint8Array(packet.eth.dest);
        conn.psrc = new Uint8Array(packet.ipv4.dest);
        conn.sport = packet.tcp.dport;
        conn.hdest = new Uint8Array(packet.eth.src);
        conn.dport = packet.tcp.sport;
        conn.pdest = new Uint8Array(packet.ipv4.src);

        adapter.bus.pair.send("tcp-connection", conn);

        if(adapter.on_tcp_connection) {
            adapter.on_tcp_connection(conn, packet);
        }
        if(adapter.tcp_conn[tuple]) return;
    }

    if(!adapter.tcp_conn[tuple]) {
        dbg_log(`I dont know about ${tuple}, so resetting`, LOG_FETCH);
        let bop = packet.tcp.ackn;
        if(packet.tcp.fin || packet.tcp.syn) bop += 1;
        let reply = {};
        reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
        reply.ipv4 = {
            proto: IPV4_PROTO_TCP,
            src: packet.ipv4.dest,
            dest: packet.ipv4.src
        };
        reply.tcp = {
            sport: packet.tcp.dport,
            dport: packet.tcp.sport,
            seq: bop,
            ackn: packet.tcp.seq + (packet.tcp.syn ? 1: 0),
            winsize: packet.tcp.winsize,
            rst: true,
            ack: packet.tcp.syn
        };
        adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
        return true;
    }

    adapter.tcp_conn[tuple].process(packet);
}

function handle_fake_dns_static(packet, adapter)
{
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
    reply.ipv4 = {
        proto: IPV4_PROTO_UDP,
        src: adapter.router_ip,
        dest: packet.ipv4.src,
    };
    reply.udp = { sport: 53, dport: packet.udp.sport };

    let answers = [];
    let flags = 0x8000; //Response,
    flags |= 0x0180; // Recursion
    // flags |= 0x0400; Authoritative

    for(let i = 0; i < packet.dns.questions.length; ++i) {
        let q = packet.dns.questions[i];

        switch(q.type){
            case 1: // A record
                answers.push({
                    name: q.name,
                    type: q.type,
                    class: q.class,
                    ttl: 600,
                    data: [192, 168, 87, 1]
                });
                break;
            default:
        }
    }

    reply.dns = {
        id: packet.dns.id,
        flags: flags,
        questions: packet.dns.questions,
        answers: answers
    };
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
    return true;
}

function handle_fake_dns_doh(packet, adapter)
{
    const fetch_url = `https://${adapter.doh_server || DEFAULT_DOH_SERVER}/dns-query`;
    const fetch_opts = {
        method: "POST",
        headers: [["content-type", "application/dns-message"]],
        body: packet.udp.data
    };
    fetch(fetch_url, fetch_opts).then(async (resp) => {
        const reply = {
            eth: {
                ethertype: ETHERTYPE_IPV4,
                src: adapter.router_mac,
                dest: packet.eth.src
            },
            ipv4: {
                proto: IPV4_PROTO_UDP,
                src: adapter.router_ip,
                dest: packet.ipv4.src
            },
            udp: {
                sport: 53,
                dport: packet.udp.sport,
                data: new Uint8Array(await resp.arrayBuffer())
            }
        };
        adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
    });
    return true;
}

function handle_fake_dns(packet, adapter)
{
    if(adapter.dns_method === "static") {
        return handle_fake_dns_static(packet, adapter);
    }
    else {
        return handle_fake_dns_doh(packet, adapter);
    }
}

function handle_fake_ntp(packet, adapter) {
    let now = Date.now(); // - 1000 * 60 * 60 * 24 * 7;
    let now_n = now + NTP_EPOC_DIFF;
    let now_n_f = TWO_TO_32 * ((now_n % 1000) / 1000);

    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
    reply.ipv4 = {
        proto: IPV4_PROTO_UDP,
        src: packet.ipv4.dest,
        dest: packet.ipv4.src,
    };
    reply.udp = { sport: 123, dport: packet.udp.sport };
    let flags = (0 << 6) | (4 << 3) | 4;
    reply.ntp = Object.assign({}, packet.ntp);
    reply.ntp.flags = flags;
    reply.ntp.poll = 10;
    reply.ntp.ori_ts_i = packet.ntp.trans_ts_i;
    reply.ntp.ori_ts_f = packet.ntp.trans_ts_f;

    reply.ntp.rec_ts_i = now_n / 1000;
    reply.ntp.rec_ts_f = now_n_f;

    reply.ntp.trans_ts_i = now_n / 1000;
    reply.ntp.trans_ts_f = now_n_f;

    reply.ntp.stratum = 2;
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
    return true;
}

function handle_fake_dhcp(packet, adapter) {
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
    reply.ipv4 = {
        proto: IPV4_PROTO_UDP,
        src: adapter.router_ip,
        dest: adapter.vm_ip,
    };
    reply.udp = { sport: 67, dport: 68, };
    reply.dhcp = {
        htype: 1,
        hlen: 6,
        hops: 0,
        xid: packet.dhcp.xid,
        secs: 0,
        flags: 0,
        ciaddr: 0,
        yiaddr: iptolong(adapter.vm_ip),
        siaddr: iptolong(adapter.router_ip),
        giaddr: iptolong(adapter.router_ip),
        chaddr: packet.dhcp.chaddr,
    };

    let options = [];

    // idk, it seems like op should be 3, but udhcpc sends 1
    let fix = packet.dhcp.options.find(function(x) { return x[0] === 53; });
    if( fix && fix[2] === 3 ) packet.dhcp.op = 3;

    if(packet.dhcp.op === 1) {
        reply.dhcp.op = 2;
        options.push(new Uint8Array([53, 1, 2]));
    }

    if(packet.dhcp.op === 3) {
        reply.dhcp.op = 2;
        options.push(new Uint8Array([53, 1, 5]));
        options.push(new Uint8Array([51, 4, 8, 0, 0, 0]));  // Lease Time
    }

    let router_ip = [adapter.router_ip[0], adapter.router_ip[1], adapter.router_ip[2], adapter.router_ip[3]];
    options.push(new Uint8Array([1, 4, 255, 255, 255, 0])); // Netmask
    if(adapter.masquerade) {
        options.push(new Uint8Array([3, 4].concat(router_ip))); // Router
        options.push(new Uint8Array([6, 4].concat(router_ip))); // DNS
    }
    options.push(new Uint8Array([54, 4].concat(router_ip))); // DHCP Server
    options.push(new Uint8Array([60, 3].concat(V86_ASCII))); // Vendor
    options.push(new Uint8Array([255, 0]));

    reply.dhcp.options = options;
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
}

export function handle_fake_networking(data, adapter) {
    let packet = {};
    parse_eth(data, packet);

    if(packet.ipv4) {
        if(packet.tcp) {
            handle_fake_tcp(packet, adapter);
        }
        else if(packet.udp) {
            if(packet.dns) {
                handle_fake_dns(packet, adapter);
            }
            else if(packet.dhcp) {
                handle_fake_dhcp(packet, adapter);
            }
            else if(packet.ntp) {
                handle_fake_ntp(packet, adapter);
            }
            else if(packet.udp.dport === 8) {
                handle_udp_echo(packet, adapter);
            }
        }
        else if(packet.icmp && packet.icmp.type === 8) {
            handle_fake_ping(packet, adapter);
        }
    }
    else if(packet.arp && packet.arp.oper === 1 && packet.arp.ptype === ETHERTYPE_IPV4) {
        arp_whohas(packet, adapter);
    }
}

function parse_eth(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);

    let ethertype = view.getUint16(12);
    let eth = {
        ethertype: ethertype,
        dest: data.subarray(0, 6),
        dest_s: a2ethaddr(data.subarray(0, 6)),
        src: data.subarray(6, 12),
        src_s: a2ethaddr(data.subarray(6, 12)),
    };

    o.eth = eth;

    // TODO: Remove CRC from the end of the packet maybe?
    let payload = data.subarray(ETH_HEADER_SIZE, data.length);

    if(ethertype === ETHERTYPE_IPV4) {
        parse_ipv4(payload, o);
    }
    else if(ethertype === ETHERTYPE_ARP) {
        parse_arp(payload, o);
    }
    else if(ethertype === ETHERTYPE_IPV6) {
        dbg_log("Unimplemented: ipv6");
    }
    else {
        dbg_log("Unknown ethertype: " + h(ethertype), LOG_FETCH);
    }
}

function write_eth(spec, out) {
    const view = out.eth_frame_view;
    view_set_array(0, spec.eth.dest, view, out);
    view_set_array(6, spec.eth.src, view, out);
    view.setUint16(12, spec.eth.ethertype);
    let len = ETH_HEADER_SIZE;
    if(spec.arp) {
        len += write_arp(spec, out);
    }
    else if(spec.ipv4) {
        len += write_ipv4(spec, out);
    }
    return len;
}

function parse_arp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let hlen = data[4];
    let plen = data[5];

    let arp = {
        htype: view.getUint16(0),
        ptype: view.getUint16(2),
        oper: view.getUint16(6),
        sha: data.subarray(8, 14),
        spa: data.subarray(14, 18),
        tha: data.subarray(18, 24),
        tpa: data.subarray(24, 28),
    };
    o.arp = arp;
}

function write_arp(spec, out) {
    const view = out.eth_payload_view;
    view.setUint16(0, spec.arp.htype);
    view.setUint16(2, spec.arp.ptype);
    view.setUint8(4, spec.arp.sha.length);
    view.setUint8(5, spec.arp.spa.length);
    view.setUint16(6, spec.arp.oper);
    view_set_array(8, spec.arp.sha, view, out);
    view_set_array(14, spec.arp.spa, view, out);
    view_set_array(18, spec.arp.tha, view, out);
    view_set_array(24, spec.arp.tpa, view, out);
    return 28;
}

function parse_ipv4(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);

    let version = (data[0] >> 4) & 0x0F;
    let ihl = data[0] & 0x0F;

    let tos = view.getUint8(1);
    let len = view.getUint16(2);

    let ttl = view.getUint8(8);
    let proto = view.getUint8(9);
    let ip_checksum = view.getUint16(10);

    let ipv4 = {
        version,
        ihl,
        tos,
        len,
        ttl,
        proto,
        ip_checksum,
        src: data.subarray(12, 12+4),
        dest: data.subarray(16, 16+4),
    };

    // Ethernet minmum packet size.
    if(Math.max(len, 46) !== data.length) {
        dbg_log(`ipv4 Length mismatch: ${len} != ${data.length}`, LOG_FETCH);
    }

    o.ipv4 = ipv4;
    let ipdata = data.subarray(ihl * 4, len);
    if(proto === IPV4_PROTO_ICMP) {
        parse_icmp(ipdata, o);
    }
    else if(proto === IPV4_PROTO_TCP) {
        parse_tcp(ipdata, o);
    }
    else if(proto === IPV4_PROTO_UDP) {
        parse_udp(ipdata, o);
    }
}

function write_ipv4(spec, out) {
    const view = out.eth_payload_view;
    const ihl = IPV4_HEADER_SIZE >> 2; // header length in 32-bit words
    const version = 4;

    let len = IPV4_HEADER_SIZE;
    if(spec.icmp) {
        len += write_icmp(spec, out);
    }
    else if(spec.udp) {
        len += write_udp(spec, out);
    }
    else if(spec.tcp) {
        len += write_tcp(spec, out);
    }

    view.setUint8(0, version << 4 | (ihl & 0x0F));
    view.setUint8(1, spec.ipv4.tos || 0);
    view.setUint16(2, len);
    view.setUint16(4, spec.ipv4.id || 0);
    view.setUint8(6, 2 << 5); // DF Flag
    view.setUint8(8, spec.ipv4.ttl || 32);
    view.setUint8(9, spec.ipv4.proto);
    view.setUint16(10, 0); // checksum initially zero before calculation
    view_set_array(12, spec.ipv4.src, view, out);
    view_set_array(16, spec.ipv4.dest, view, out);
    view.setUint16(10, calc_inet_checksum(IPV4_HEADER_SIZE, 0, view, out));
    return len;
}

function parse_icmp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let icmp = {
        type: view.getUint8(0),
        code: view.getUint8(1),
        checksum: view.getUint16(2),
        data: data.subarray(4)
    };
    o.icmp = icmp;
}

function write_icmp(spec, out) {
    const view = out.ipv4_payload_view;
    view.setUint8(0, spec.icmp.type);
    view.setUint8(1, spec.icmp.code);
    view.setUint16(2, 0); // checksum initially zero before calculation
    const data_length = view_set_array(ICMP_HEADER_SIZE, spec.icmp.data, view, out);
    const total_length = ICMP_HEADER_SIZE + data_length;
    view.setUint16(2, calc_inet_checksum(total_length, 0, view, out));
    return total_length;
}

function parse_udp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let udp = {
        sport: view.getUint16(0),
        dport: view.getUint16(2),
        len: view.getUint16(4),
        checksum: view.getUint16(6),
        data: data.subarray(8),
        data_s: new TextDecoder().decode(data.subarray(8))
    };

    //dbg_assert(udp.data.length + 8 == udp.len);
    if(udp.dport === 67 || udp.sport === 67) { //DHCP
        parse_dhcp(data.subarray(8), o);
    }
    else if(udp.dport === 53 || udp.sport === 53) {
        parse_dns(data.subarray(8), o);
    }
    else if(udp.dport === 123) {
        parse_ntp(data.subarray(8), o);
    }
    o.udp = udp;
}

function write_udp(spec, out) {
    const view = out.ipv4_payload_view;
    let total_length = UDP_HEADER_SIZE;
    if(spec.dhcp) {
        total_length += write_dhcp(spec, out);
    }
    else if(spec.dns) {
        total_length += write_dns(spec, out);
    }
    else if(spec.ntp) {
        total_length += write_ntp(spec, out);
    }
    else {
        total_length += view_set_array(0, spec.udp.data, out.udp_payload_view, out);
    }

    view.setUint16(0, spec.udp.sport);
    view.setUint16(2, spec.udp.dport);
    view.setUint16(4, total_length);
    view.setUint16(6, 0); // checksum initially zero before calculation

    const pseudo_header =
        (spec.ipv4.src[0] << 8 | spec.ipv4.src[1]) +
        (spec.ipv4.src[2] << 8 | spec.ipv4.src[3]) +
        (spec.ipv4.dest[0] << 8 | spec.ipv4.dest[1]) +
        (spec.ipv4.dest[2] << 8 | spec.ipv4.dest[3]) +
        IPV4_PROTO_UDP +
        total_length;
    view.setUint16(6, calc_inet_checksum(total_length, pseudo_header, view, out));
    return total_length;
}

function parse_dns(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let dns = {
        id: view.getUint16(0),
        flags: view.getUint16(2),
        questions: [],
        answers: []
    };

    let qdcount = view.getUint16(4);
    let ancount = view.getUint16(6);
    let nscount = view.getUint16(8);
    let arcount = view.getUint16(10);

    let offset = 12;
    function read_dstr() {
        let o = [];
        let len;
        do {
            len = view.getUint8(offset);
            o.push(new TextDecoder().decode(data.subarray(offset+1, offset+1+len)));
            offset += len + 1;
        } while(len > 0);
        return o;
    }

    for(let i = 0; i < qdcount; i++) {
        dns.questions.push({
            name: read_dstr(),
            type: view.getInt16(offset),
            class: view.getInt16(offset + 2)
        });
        offset += 4;
    }
    for(let i = 0; i < ancount; i++) {
        let ans = {
            name: read_dstr(),
            type: view.getInt16(offset),
            class: view.getUint16(offset + 2),
            ttl: view.getUint32(offset + 4)
        };
        offset += 8;
        let rdlen = view.getUint16(offset);
        offset += 2;
        ans.data = data.subarray(offset, offset+rdlen);
        offset += rdlen;
        dns.answers.push(ans);
    }
    o.dns = dns;
}

function write_dns(spec, out) {
    const view = out.udp_payload_view;
    view.setUint16(0, spec.dns.id);
    view.setUint16(2, spec.dns.flags);
    view.setUint16(4, spec.dns.questions.length);
    view.setUint16(6, spec.dns.answers.length);

    let offset = 12;
    for(let i = 0; i < spec.dns.questions.length; ++i) {
        let q = spec.dns.questions[i];
        for(let s of q.name) {
            const n_written = view_set_string(offset + 1, s, view, out);
            view.setUint8(offset, n_written);
            offset += 1 + n_written;
        }
        view.setUint16(offset, q.type);
        offset += 2;
        view.setUint16(offset, q.class);
        offset += 2;
    }

    function write_reply(a) {
        for(let s of a.name) {
            const n_written = view_set_string(offset + 1, s, view, out);
            view.setUint8(offset, n_written);
            offset += 1 + n_written;
        }
        view.setUint16(offset, a.type);
        offset += 2;
        view.setUint16(offset, a.class);
        offset += 2;
        view.setUint32(offset, a.ttl);
        offset += 4;
        view.setUint16(offset, a.data.length);
        offset += 2;
        offset += view_set_array(offset, a.data, view, out);
    }

    for(let i = 0; i < spec.dns.answers.length; ++i) {
        let a = spec.dns.answers[i];
        write_reply(a);
    }

    return offset;
}

function parse_dhcp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let bootpo  = data.subarray(44,44+192);
    let dhcp = {
        op:  view.getUint8(0),
        htype: view.getUint8(1),
        hlen: view.getUint8(2),
        hops: view.getUint8(3),
        xid: view.getUint32(4),
        secs: view.getUint16(8),
        flags: view.getUint16(10),
        ciaddr: view.getUint32(12),
        yiaddr: view.getUint32(16),
        siaddr: view.getUint32(20),
        giaddr: view.getUint32(24),
        chaddr: data.subarray(28,28+16),
        magic: view.getUint32(236),
        options: [],
    };

    let options = data.subarray(240);
    for(let i = 0; i < options.length; ++i) {
        let start = i;
        let op = options[i];
        if(op === 0) continue;
        ++i;
        let len = options[i];
        i += len;
        dhcp.options.push(options.subarray(start, start + len + 2));
    }

    o.dhcp = dhcp;
    o.dhcp_options = dhcp.options;
}

function write_dhcp(spec, out) {
    const view = out.udp_payload_view;
    view.setUint8(0, spec.dhcp.op);
    view.setUint8(1, spec.dhcp.htype);
    view.setUint8(2, spec.dhcp.hlen);
    view.setUint8(3, spec.dhcp.hops);
    view.setUint32(4, spec.dhcp.xid);
    view.setUint16(8, spec.dhcp.secs);
    view.setUint16(10, spec.dhcp.flags);
    view.setUint32(12, spec.dhcp.ciaddr);
    view.setUint32(16, spec.dhcp.yiaddr);
    view.setUint32(20, spec.dhcp.siaddr);
    view.setUint32(24, spec.dhcp.giaddr);
    view_set_array(28, spec.dhcp.chaddr, view, out);

    view.setUint32(236, DHCP_MAGIC_COOKIE);

    let offset = 240;
    for(let o of spec.dhcp.options) {
        offset += view_set_array(offset, o, view, out);
    }
    return offset;
}

function parse_ntp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    o.ntp = {
        flags: view.getUint8(0),
        stratum: view.getUint8(1),
        poll: view.getUint8(2),
        precision: view.getUint8(3),
        root_delay: view.getUint32(4),
        root_disp: view.getUint32(8),
        ref_id: view.getUint32(12),
        ref_ts_i: view.getUint32(16),
        ref_ts_f: view.getUint32(20),
        ori_ts_i: view.getUint32(24),
        ori_ts_f: view.getUint32(28),
        rec_ts_i: view.getUint32(32),
        rec_ts_f: view.getUint32(36),
        trans_ts_i: view.getUint32(40),
        trans_ts_f: view.getUint32(44),
    };
}

function write_ntp(spec, out) {
    const view = out.udp_payload_view;
    view.setUint8(0, spec.ntp.flags);
    view.setUint8(1, spec.ntp.stratum);
    view.setUint8(2, spec.ntp.poll);
    view.setUint8(3, spec.ntp.precision);
    view.setUint32(4, spec.ntp.root_delay);
    view.setUint32(8, spec.ntp.root_disp);
    view.setUint32(12, spec.ntp.ref_id);
    view.setUint32(16, spec.ntp.ref_ts_i);
    view.setUint32(20, spec.ntp.ref_ts_f);
    view.setUint32(24, spec.ntp.ori_ts_i);
    view.setUint32(28, spec.ntp.ori_ts_f);
    view.setUint32(32, spec.ntp.rec_ts_i);
    view.setUint32(36, spec.ntp.rec_ts_f);
    view.setUint32(40, spec.ntp.trans_ts_i);
    view.setUint32(44, spec.ntp.trans_ts_f);
    return 48;
}

function parse_tcp(data, o) {
    let view = new DataView(data.buffer, data.byteOffset, data.byteLength);

    let tcp = {
        sport: view.getUint16(0),
        dport: view.getUint16(2),
        seq: view.getUint32(4),
        ackn: view.getUint32(8),
        doff: view.getUint8(12) >> 4,
        winsize: view.getUint16(14),
        checksum: view.getUint16(16),
        urgent: view.getUint16(18),
    };

    let flags = view.getUint8(13);

    tcp.fin = !!(flags & 0x01);
    tcp.syn = !!(flags & 0x02);
    tcp.rst = !!(flags & 0x04);
    tcp.psh = !!(flags & 0x08);
    tcp.ack = !!(flags & 0x10);
    tcp.urg = !!(flags & 0x20);
    tcp.ece = !!(flags & 0x40);
    tcp.cwr = !!(flags & 0x80);

    o.tcp = tcp;

    let offset = tcp.doff * 4;
    o.tcp_data = data.subarray(offset);
}

function write_tcp(spec, out) {
    const view = out.ipv4_payload_view;
    let flags = 0;
    let tcp = spec.tcp;

    if(tcp.fin) flags |= 0x01;
    if(tcp.syn) flags |= 0x02;
    if(tcp.rst) flags |= 0x04;
    if(tcp.psh) flags |= 0x08;
    if(tcp.ack) flags |= 0x10;
    if(tcp.urg) flags |= 0x20;
    if(tcp.ece) flags |= 0x40;
    if(tcp.cwr) flags |= 0x80;

    let doff = TCP_HEADER_SIZE;
    if(tcp.options) {
        if(tcp.options.mss) {
            view.setUint8(doff, 0x02); //mss option type
            view.setUint8(doff + 1, 0x04); //option length
            view.setUint16(doff + 2, tcp.options.mss);
            doff += 4;
        }
    }

    let total_length = Math.ceil(doff / 4) * 4; // needs to a multiple of 4 bytes
    if(tcp.options && total_length - doff > 0) {
        view_set_zeros(doff, total_length - doff, view, out); //write zeros into remaining space for options
    }

    view.setUint16(0, tcp.sport);
    view.setUint16(2, tcp.dport);
    view.setUint32(4, tcp.seq);
    view.setUint32(8, tcp.ackn);
    view.setUint8(12, (total_length >> 2) << 4); // header length in 32-bit words
    view.setUint8(13, flags);
    view.setUint16(14, tcp.winsize);
    view.setUint16(16, 0); // checksum initially zero before calculation
    view.setUint16(18, tcp.urgent || 0);

    if(spec.tcp_data) {
        total_length += view_set_array(TCP_HEADER_SIZE, spec.tcp_data, view, out);
    }

    const pseudo_header =
        (spec.ipv4.src[0] << 8 | spec.ipv4.src[1]) +
        (spec.ipv4.src[2] << 8 | spec.ipv4.src[3]) +
        (spec.ipv4.dest[0] << 8 | spec.ipv4.dest[1]) +
        (spec.ipv4.dest[2] << 8 | spec.ipv4.dest[3]) +
        IPV4_PROTO_TCP +
        total_length;
    view.setUint16(16, calc_inet_checksum(total_length, pseudo_header, view, out));
    return total_length;
}

export function fake_tcp_connect(dport, adapter)
{
    const vm_ip_str = adapter.vm_ip.join(".");
    const router_ip_str = adapter.router_ip.join(".");
    const sport_0 = (Math.random() * TCP_DYNAMIC_PORT_RANGE) | 0;
    let sport, tuple, sport_i = 0;
    do {
        sport = TCP_DYNAMIC_PORT_START + ((sport_0 + sport_i) % TCP_DYNAMIC_PORT_RANGE);
        tuple = `${vm_ip_str}:${dport}:${router_ip_str}:${sport}`;
    } while(++sport_i < TCP_DYNAMIC_PORT_RANGE && adapter.tcp_conn[tuple]);
    if(adapter.tcp_conn[tuple]) {
        throw new Error("pool of dynamic TCP port numbers exhausted, connection aborted");
    }

    let conn = new TCPConnection(adapter);

    conn.tuple = tuple;
    conn.hsrc = adapter.router_mac;
    conn.psrc = adapter.router_ip;
    conn.sport = sport;
    conn.hdest = adapter.vm_mac;
    conn.dport = dport;
    conn.pdest = adapter.vm_ip;
    adapter.tcp_conn[tuple] = conn;
    conn.connect();
    return conn;
}

export function fake_tcp_probe(dport, adapter) {
    return new Promise((res, rej) => {
        let handle = fake_tcp_connect(dport, adapter);
        handle.state = TCP_STATE_SYN_PROBE;
        handle.on("probe", res);
    });
}

/**
 * @constructor
 */
export function TCPConnection(adapter)
{
    this.mtu = (adapter.mtu || MTU_DEFAULT);
    const IPV4_PAYLOAD_SIZE = this.mtu - IPV4_HEADER_SIZE;
    const TCP_PAYLOAD_SIZE = IPV4_PAYLOAD_SIZE - TCP_HEADER_SIZE;

    this.state = TCP_STATE_CLOSED;
    this.net = adapter; // The adapter is stored here
    this.send_buffer = new GrowableRingbuffer(2048, 0);
    this.send_chunk_buf = new Uint8Array(TCP_PAYLOAD_SIZE);
    this.in_active_close = false;
    this.delayed_send_fin = false;
    this.delayed_state = undefined;
    this.events_handlers = {};
}

TCPConnection.prototype.on = function(event, handler) {
    this.events_handlers[event] = handler;
};

TCPConnection.prototype.emit = function(event, ...args) {
    if(!this.events_handlers[event]) return;
    this.events_handlers[event].apply(this, args);
};


TCPConnection.prototype.ipv4_reply = function() {
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: this.hsrc, dest: this.hdest };
    reply.ipv4 = {
        proto: IPV4_PROTO_TCP,
        src: this.psrc,
        dest: this.pdest
    };
    reply.tcp = {
        sport: this.sport,
        dport: this.dport,
        winsize: this.winsize,
        ackn: this.ack,
        seq: this.seq,
        ack: true
    };
    return reply;
};

TCPConnection.prototype.packet_reply = function(packet, tcp_options) {
    const reply_tcp = {
        sport: packet.tcp.dport,
        dport: packet.tcp.sport,
        winsize: packet.tcp.winsize,
        ackn: this.ack,
        seq: this.seq
    };
    if(tcp_options) {
        for(const opt in tcp_options) {
            reply_tcp[opt] = tcp_options[opt];
        }
    }
    const reply = this.ipv4_reply();
    reply.tcp = reply_tcp;
    return reply;
};


TCPConnection.prototype.connect = function() {
    // dbg_log(`TCP[${this.tuple}]: connect(): sending SYN+ACK in state "${this.state}", next "${TCP_STATE_SYN_SENT}"`, LOG_FETCH);
    this.seq = 1338;
    this.ack = 1;
    this.start_seq = 0;
    this.winsize = 64240;
    if(this.state !== TCP_STATE_SYN_PROBE) {
        this.state = TCP_STATE_SYN_SENT;
    }

    let reply = this.ipv4_reply();
    reply.ipv4.id = 2345;
    reply.tcp = {
        sport: this.sport,
        dport: this.dport,
        seq: 1337,
        ackn: 0,
        winsize: 0,
        syn: true,
    };
    this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
};


TCPConnection.prototype.accept = function(packet=undefined) {
    packet = packet || this.last;
    this.net.tcp_conn[this.tuple] = this;
    this.seq = 1338;
    this.ack = packet.tcp.seq + 1;
    this.start_seq = packet.tcp.seq;
    this.winsize = packet.tcp.winsize;

    let reply = this.ipv4_reply();
    reply.tcp = {
        sport: this.sport,
        dport: this.dport,
        seq: 1337,
        ackn: this.ack,
        winsize: packet.tcp.winsize,
        syn: true,
        ack: true,
        options: {
            mss: (this.mtu - TCP_HEADER_SIZE - IPV4_HEADER_SIZE)
        }
    };
    // dbg_log(`TCP[${this.tuple}]: accept(): sending SYN+ACK in state "${this.state}", next "${TCP_STATE_ESTABLISHED}"`, LOG_FETCH);
    this.state = TCP_STATE_ESTABLISHED;
    this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
};

TCPConnection.prototype.process = function(packet) {
    this.last = packet;
    if(this.state === TCP_STATE_CLOSED) {
        // dbg_log(`TCP[${this.tuple}]: WARNING: connection already closed, packet dropped`, LOG_FETCH);
        const reply = this.packet_reply(packet, {rst: true});
        this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
        return;
    }
    else if(packet.tcp.rst) {
        if(this.state === TCP_STATE_SYN_PROBE) {
            this.emit("probe", false);
            this.release();
            return;
        }
        // dbg_log(`TCP[${this.tuple}]: received RST in state "${this.state}"`, LOG_FETCH);
        this.on_close();
        this.release();
        return;
    }
    else if(packet.tcp.syn) {
        if(this.state === TCP_STATE_SYN_SENT && packet.tcp.ack) {
            this.ack = packet.tcp.seq + 1;
            this.start_seq = packet.tcp.seq;
            this.last_received_ackn = packet.tcp.ackn;

            const reply = this.ipv4_reply();
            this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
            // dbg_log(`TCP[${this.tuple}]: received SYN+ACK in state "${this.state}", next "${TCP_STATE_ESTABLISHED}"`, LOG_FETCH);
            this.state = TCP_STATE_ESTABLISHED;
            this.emit("connect");
        }
        else if(this.state === TCP_STATE_SYN_PROBE && packet.tcp.ack) {
            this.emit("probe", true);
            const reply = this.packet_reply(packet, {rst: true});
            this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
            this.release();
        }
        else {
            dbg_log(`TCP[${this.tuple}]: WARNING: unexpected SYN packet dropped`, LOG_FETCH);
        }
        if(packet.tcp_data.length) {
            dbg_log(`TCP[${this.tuple}]: WARNING: ${packet.tcp_data.length} bytes of unexpected SYN packet payload dropped`, LOG_FETCH);
        }
        return;
    }

    if(packet.tcp.ack) {
        if(this.state === TCP_STATE_SYN_RECEIVED) {
            // dbg_log(`TCP[${this.tuple}]: received ACK in state "${this.state}", next "${TCP_STATE_ESTABLISHED}"`, LOG_FETCH);
            this.state = TCP_STATE_ESTABLISHED;
        }
        else if(this.state === TCP_STATE_FIN_WAIT_1) {
            if(!packet.tcp.fin) {   // handle FIN+ACK in FIN_WAIT_1 separately further down below
                // dbg_log(`TCP[${this.tuple}]: received ACK in state "${this.state}", next "${TCP_STATE_FIN_WAIT_2}"`, LOG_FETCH);
                this.state = TCP_STATE_FIN_WAIT_2;
            }
        }
        else if(this.state === TCP_STATE_CLOSING || this.state === TCP_STATE_LAST_ACK) {
            // dbg_log(`TCP[${this.tuple}]: received ACK in state "${this.state}"`, LOG_FETCH);
            this.release();
            return;
        }
    }

    if(this.last_received_ackn === undefined) {
        this.last_received_ackn = packet.tcp.ackn;
    }
    else {
        const n_ack = packet.tcp.ackn - this.last_received_ackn;
        //console.log("Read ", n_ack, "(", this.last_received_ackn, ") ", packet.tcp.ackn, packet.tcp.winsize)
        if(n_ack > 0) {
            this.last_received_ackn = packet.tcp.ackn;
            this.send_buffer.remove(n_ack);
            this.seq += n_ack;
            this.pending = false;

            if(this.delayed_send_fin && !this.send_buffer.length) {
                // dbg_log(`TCP[${this.tuple}]: sending delayed FIN from active close in state "${this.state}", next "${this.delayed_state}"`, LOG_FETCH);
                this.delayed_send_fin = false;
                this.state = this.delayed_state;
                const reply = this.ipv4_reply();
                reply.tcp.fin = true;
                this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
                return;
            }
        }
        else if(n_ack < 0) {    // TODO: could this just be a 32-bit sequence number overflow?
            dbg_log(`TCP[${this.tuple}]: ERROR: ack underflow (pkt=${packet.tcp.ackn} last=${this.last_received_ackn}), resetting`, LOG_FETCH);
            const reply = this.packet_reply(packet, {rst: true});
            this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
            this.on_close();
            this.release();
            return;
        }
    }

    if(packet.tcp.fin) {
        if(this.ack !== packet.tcp.seq) {
            dbg_log(`TCP[${this.tuple}]: WARNING: closing connection in state "${this.state}" with invalid seq (${this.ack} != ${packet.tcp.seq})`, LOG_FETCH);
        }
        ++this.ack; // FIN increases seqnr
        const reply = this.packet_reply(packet, {});
        if(this.state === TCP_STATE_ESTABLISHED) {
            // dbg_log(`TCP[${this.tuple}]: received FIN in state "${this.state}, next "${TCP_STATE_CLOSE_WAIT}""`, LOG_FETCH);
            reply.tcp.ack = true;
            this.state = TCP_STATE_CLOSE_WAIT;
            this.on_shutdown();
        }
        else if(this.state === TCP_STATE_FIN_WAIT_1) {
            if(packet.tcp.ack) {
                // dbg_log(`TCP[${this.tuple}]: received ACK+FIN in state "${this.state}"`, LOG_FETCH);
                this.release();
            }
            else {
                // dbg_log(`TCP[${this.tuple}]: received ACK in state "${this.state}", next "${TCP_STATE_CLOSING}"`, LOG_FETCH);
                this.state = TCP_STATE_CLOSING;
            }
            reply.tcp.ack = true;
        }
        else if(this.state === TCP_STATE_FIN_WAIT_2) {
            // dbg_log(`TCP[${this.tuple}]: received FIN in state "${this.state}"`, LOG_FETCH);
            this.release();
            reply.tcp.ack = true;
        }
        else {
            // dbg_log(`TCP[${this.tuple}]: ERROR: received FIN in unexpected TCP state "${this.state}", resetting`, LOG_FETCH);
            this.release();
            this.on_close();
            reply.tcp.rst = true;
        }
        this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
    }
    else if(this.ack !== packet.tcp.seq) {
        // Handle TCP Keep-Alives silently.
        // Excerpt from RFC 9293, 3.8.4. TCP Keep-Alives:
        //   To confirm that an idle connection is still active, these
        //   implementations send a probe segment designed to elicit a response
        //   from the TCP peer.  Such a segment generally contains SEG.SEQ =
        //   SND.NXT-1 and may or may not contain one garbage octet of data.
        if(this.ack !== packet.tcp.seq + 1) {
            dbg_log(`Packet seq was wrong ex: ${this.ack} ~${this.ack - this.start_seq} ` +
                `pk: ${packet.tcp.seq} ~${this.start_seq - packet.tcp.seq} ` +
                `(${this.ack - packet.tcp.seq}) = ${this.name}`, LOG_FETCH);
        }
        const reply = this.packet_reply(packet, {ack: true});
        this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
    }
    else if(packet.tcp.ack && packet.tcp_data.length > 0) {
        this.ack += packet.tcp_data.length;
        const reply = this.ipv4_reply();
        this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
        this.emit("data", packet.tcp_data);
    }

    this.pump();
};

/**
 * @param {Uint8Array} data
 */
TCPConnection.prototype.write = function(data) {
    if(!this.in_active_close) {
        this.send_buffer.write(data);
    }
    this.pump();
};

/**
 * @param {!Array<Uint8Array>} data_array
 */
TCPConnection.prototype.writev = function(data_array) {
    if(!this.in_active_close) {
        for(const data of data_array) {
            this.send_buffer.write(data);
        }
    }
    this.pump();
};

TCPConnection.prototype.close = function() {
    if(!this.in_active_close) {
        this.in_active_close = true;
        let next_state;
        if(this.state === TCP_STATE_ESTABLISHED || this.state === TCP_STATE_SYN_RECEIVED) {
            next_state = TCP_STATE_FIN_WAIT_1;
        }
        else if(this.state === TCP_STATE_CLOSE_WAIT) {
            next_state = TCP_STATE_LAST_ACK;
        }
        else {
            if(this.state !== TCP_STATE_SYN_SENT) {
                dbg_log(`TCP[${this.tuple}]: active close in unexpected state "${this.state}"`, LOG_FETCH);
            }
            this.release();
            return;
        }

        if(this.send_buffer.length || this.pending) {
            // dbg_log(`TCP[${this.tuple}]: active close, delaying FIN in state "${this.state}", delayed next "${next_state}"`, LOG_FETCH);
            this.delayed_send_fin = true;
            this.delayed_state = next_state;
        }
        else {
            // dbg_log(`TCP[${this.tuple}]: active close, sending FIN in state "${this.state}", next "${next_state}"`, LOG_FETCH);
            this.state = next_state;
            const reply = this.ipv4_reply();
            reply.tcp.fin = true;
            this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
        }
    }
    this.pump();
};

TCPConnection.prototype.on_shutdown = function() {
    this.emit("shutdown");
    // forward FIN event from guest device to network adapter
};

TCPConnection.prototype.on_close = function() {
    this.emit("close");
    // forward RST event from guest device to network adapter
};

TCPConnection.prototype.release = function() {
    if(this.net.tcp_conn[this.tuple]) {
        // dbg_log(`TCP[${this.tuple}]: connection closed in state "${this.state}"`, LOG_FETCH);
        this.state = TCP_STATE_CLOSED;
        delete this.net.tcp_conn[this.tuple];
    }
};

TCPConnection.prototype.pump = function() {
    if(this.send_buffer.length && !this.pending) {
        const data = this.send_chunk_buf;
        const n_ready = this.send_buffer.peek(data);
        const reply = this.ipv4_reply();
        reply.tcp.psh = true;
        reply.tcp_data = data.subarray(0, n_ready);
        this.net.receive(make_packet(this.net.eth_encoder_buf, reply));
        this.pending = true;
    }
};


function arp_whohas(packet, adapter) {
    let packet_subnet = iptolong(packet.arp.tpa) & 0xFFFFFF00;
    let router_subnet = iptolong(adapter.router_ip) & 0xFFFFFF00;

    if(!adapter.masquerade) {
        if(packet_subnet !== router_subnet) {
            return;
        }
    }

    if(packet_subnet === router_subnet) {
        // Ignore the DHCP client area
        if(packet.arp.tpa[3] > 99) return;
    }

    // Reply to ARP Whohas
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_ARP, src: adapter.router_mac, dest: packet.eth.src };
    reply.arp = {
        htype: 1,
        ptype: ETHERTYPE_IPV4,
        oper: 2,
        sha: adapter.router_mac,
        spa: packet.arp.tpa,
        tha: packet.eth.src,
        tpa: packet.arp.spa
    };
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
}

function handle_fake_ping(packet, adapter) {
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
    reply.ipv4 = {
        proto: IPV4_PROTO_ICMP,
        src: packet.ipv4.dest,
        dest: packet.ipv4.src,
    };
    reply.icmp = {
        type: 0,
        code: packet.icmp.code,
        data: packet.icmp.data
    };
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
}

function handle_udp_echo(packet, adapter) {
    // UDP Echo Server
    let reply = {};
    reply.eth = { ethertype: ETHERTYPE_IPV4, src: adapter.router_mac, dest: packet.eth.src };
    reply.ipv4 = {
        proto: IPV4_PROTO_UDP,
        src: packet.ipv4.dest,
        dest: packet.ipv4.src,
    };
    reply.udp = {
        sport: packet.udp.dport,
        dport: packet.udp.sport,
        data: new TextEncoder().encode(packet.udp.data_s)
    };
    adapter.receive(make_packet(adapter.eth_encoder_buf, reply));
}
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/fetch_network.js                                                             0000644 0000000 0000000 00000027233 00000000000 015345  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_FETCH } from "../const.js";
import { dbg_log } from "../log.js";

import {
    create_eth_encoder_buf,
    handle_fake_networking,
    TCPConnection,
    TCP_STATE_SYN_RECEIVED,
    fake_tcp_connect,
    fake_tcp_probe
} from "./fake_network.js";

// For Types Only
import { BusConnector } from "../bus.js";


const CR = 0x0D;
const LF = 0x0A;

function find_crlfcrlf(haystack)
{
    for(let i = 0; i + 3 < haystack.length; i++)
    {
        if(haystack[i] === CR && haystack[i + 1] === LF && haystack[i + 2] === CR && haystack[i + 3] === LF)
        {
            return i;
        }
    }
    return -1;
}

/**
 * @constructor
 *
 * @param {BusConnector} bus
 * @param {*=} config
 */
export function FetchNetworkAdapter(bus, config)
{
    config = config || {};
    this.bus = bus;
    this.id = config.id || 0;
    this.router_mac = new Uint8Array((config.router_mac || "52:54:0:1:2:3").split(":").map(function(x) { return parseInt(x, 16); }));
    this.router_ip = new Uint8Array((config.router_ip || "192.168.86.1").split(".").map(function(x) { return parseInt(x, 10); }));
    this.vm_ip = new Uint8Array((config.vm_ip || "192.168.86.100").split(".").map(function(x) { return parseInt(x, 10); }));
    this.masquerade = config.masquerade === undefined || !!config.masquerade;
    this.vm_mac = new Uint8Array(6);
    this.dns_method = config.dns_method || "static";
    this.doh_server = config.doh_server;
    this.tcp_conn = {};
    this.mtu = config.mtu;
    this.eth_encoder_buf = create_eth_encoder_buf(this.mtu);
    this.fetch = (...args) => fetch(...args);

    // Ex: 'https://corsproxy.io/?'
    this.cors_proxy = config.cors_proxy;

    this.bus.register("net" + this.id + "-mac", function(mac) {
        this.vm_mac = new Uint8Array(mac.split(":").map(function(x) { return parseInt(x, 16); }));
    }, this);
    this.bus.register("net" + this.id + "-send", function(data)
    {
        this.send(data);
    }, this);
    this.bus.register("tcp-connection", (conn) => {
        if(conn.sport === 80) {
            conn.on("data", on_data_http);
            conn.accept();
        }
    }, this);
}

FetchNetworkAdapter.prototype.destroy = function()
{
};

FetchNetworkAdapter.prototype.connect = function(port)
{
    return fake_tcp_connect(port, this);
};

FetchNetworkAdapter.prototype.tcp_probe = function(port)
{
    return fake_tcp_probe(port, this);
};

/**
 * HTTP data handler for port-80 TCP connections.
 *
 * Incoming TCP segments are buffered as raw bytes and searched for the
 * \r\n\r\n header/body separator.  Once found the header portion alone is
 * text-decoded and parsed; the body stays as a binary Uint8Array.
 *
 * When a POST/PUT body spans multiple TCP segments the partial body is
 * stored in this.pendingBody and subsequent segments are accumulated there until
 * Content-Length is satisfied, at which point the deferred fetch is fired.
 *
 * NOTE: Transfer-Encoding: chunked is not supported.  Requests using it
 * will not be dispatched.
 *
 * @this {TCPConnection}
 * @param {!ArrayBuffer} data
 */
async function on_data_http(data)
{
    // If we're buffering a partial request body, accumulate chunks until
    // Content-Length is satisfied, then fire the deferred fetch.
    if(this.pendingBody)
    {
        const chunk = data instanceof Uint8Array ? data : new Uint8Array(data);
        const combined = new Uint8Array(this.pendingBody.buf.length + chunk.length);
        combined.set(this.pendingBody.buf);
        combined.set(chunk, this.pendingBody.buf.length);
        this.pendingBody.buf = combined;
        if(this.pendingBody.buf.length >= this.pendingBody.cl)
        {
            const body = this.pendingBody.buf;
            const done = this.pendingBody.done;
            this.pendingBody = null;
            done(body);
        }
        return;
    }

    // Accumulate raw bytes (not text) so binary body data is preserved.
    const chunk = data instanceof Uint8Array ? data : new Uint8Array(data);
    if(this.rawBuffer)
    {
        const combined = new Uint8Array(this.rawBuffer.length + chunk.length);
        combined.set(this.rawBuffer);
        combined.set(chunk, this.rawBuffer.length);
        this.rawBuffer = combined;
    }
    else
    {
        this.rawBuffer = chunk;
    }

    const sep_index = find_crlfcrlf(this.rawBuffer);
    if(sep_index === -1) return;

    // Split into header (text) and body (binary).
    const header_bytes = this.rawBuffer.slice(0, sep_index);
    const body_bytes = this.rawBuffer.slice(sep_index + 4);
    this.rawBuffer = null;

    const header_text = new TextDecoder().decode(header_bytes);
    const header_lines = header_text.split(/\r\n/);

    const first_line = header_lines[0].split(" ");
    let target;
    if(/^https?:/.test(first_line[1]))
    {
        // HTTP proxy
        target = new URL(first_line[1]);
    }
    else
    {
        target = new URL("http://host" + first_line[1]);
    }
    if(typeof window !== "undefined" && target.protocol === "http:" && window.location.protocol === "https:")
    {
        // fix "Mixed Content" errors
        target.protocol = "https:";
    }

    const req_headers = new Headers();
    for(let i = 1; i < header_lines.length; ++i)
    {
        const header = this.net.parse_http_header(header_lines[i]);
        if(!header)
        {
            console.warn('The request contains an invalid header: "%s"', header_lines[i]);
            this.net.respond_text_and_close(this, 400, "Bad Request", `Invalid header in request: ${header_lines[i]}`);
            return;
        }
        if(header.key.toLowerCase() === "host") target.host = header.value;
        else req_headers.append(header.key, header.value);
    }

    if(!this.net.cors_proxy && /^\d+\.external$/.test(target.hostname))
    {
        dbg_log("Request to localhost: " + target.href, LOG_FETCH);
        const localport = parseInt(target.hostname.split(".")[0], 10);
        if(!isNaN(localport) && localport > 0 && localport < 65536)
        {
            target.protocol = "http:";
            target.hostname = "localhost";
            target.port = localport.toString(10);
        }
        else
        {
            console.warn('Unknown port for localhost: "%s"', target.href);
            this.net.respond_text_and_close(this, 400, "Bad Request", `Unknown port for localhost: ${target.href}`);
            return;
        }
    }

    dbg_log("HTTP Dispatch: " + target.href, LOG_FETCH);
    this.name = target.href;

    const opts = {
        method: first_line[0],
        headers: req_headers,
    };

    const fetch_url = this.net.cors_proxy
        ? this.net.cors_proxy + encodeURIComponent(target.href)
        : target.href;

    if(["put", "post"].indexOf(opts.method.toLowerCase()) !== -1)
    {
        // The body may span multiple TCP segments.
        // If Content-Length is present and larger than what we have so far,
        // buffer the partial body and wait for remaining chunks.
        const content_length = parseInt(req_headers.get("content-length") || "0", 10);
        if(content_length > 0 && body_bytes.length < content_length)
        {
            this.pendingBody = {
                buf: body_bytes,
                cl: content_length,
                done: (body) => {
                    opts.body = body;
                    dispatch_fetch(this, fetch_url, opts);
                },
            };
            return;
        }
        opts.body = body_bytes;
    }

    dispatch_fetch(this, fetch_url, opts);
}

/**
 * Execute the HTTP fetch and pipe the response back to the guest.
 *
 * @param {TCPConnection} conn
 * @param {string} fetch_url
 * @param {!Object} opts
 */
function dispatch_fetch(conn, fetch_url, opts)
{
    let response_started = false;
    let handler = (resp) => {
        let resp_headers = new Headers(resp.headers);
        resp_headers.delete("content-encoding");
        resp_headers.delete("keep-alive");
        resp_headers.delete("content-length");
        resp_headers.delete("transfer-encoding");
        resp_headers.set("x-was-fetch-redirected", `${!!resp.redirected}`);
        resp_headers.set("x-fetch-resp-url", resp.url);
        resp_headers.set("connection", "close");

        conn.write(conn.net.form_response_head(resp.status, resp.statusText, resp_headers));
        response_started = true;

        if(resp.body && resp.body.getReader)
        {
            const resp_reader = resp.body.getReader();
            const pump = ({ value, done }) => {
                if(value)
                {
                    conn.write(value);
                }
                if(done)
                {
                    conn.close();
                }
                else
                {
                    return resp_reader.read().then(pump);
                }
            };
            resp_reader.read().then(pump);
        }
        else
        {
            resp.arrayBuffer().then(buffer => {
                conn.write(new Uint8Array(buffer));
                conn.close();
            });
        }
    };

    conn.net.fetch(fetch_url, opts).then(handler)
    .catch((e) => {
        console.warn("Fetch Failed: " + fetch_url + "\n" + e);
        if(!response_started)
        {
            conn.net.respond_text_and_close(conn, 502, "Fetch Error", `Fetch ${fetch_url} failed:\n\n${e.stack || e.message}`);
        }
        conn.close();
    });
}

FetchNetworkAdapter.prototype.fetch = async function(url, options)
{
    if(this.cors_proxy) url = this.cors_proxy + encodeURIComponent(url);

    try
    {
        const resp = await fetch(url, options);
        const ab = await resp.arrayBuffer();
        return [resp, ab];
    }
    catch(e)
    {
        console.warn("Fetch Failed: " + url + "\n" + e);
        return [
            {
                status: 502,
                statusText: "Fetch Error",
                headers: new Headers({ "Content-Type": "text/plain" }),
            },
            new TextEncoder().encode(`Fetch ${url} failed:\n\n${e.stack}`).buffer
        ];
    }
};

FetchNetworkAdapter.prototype.form_response_head = function(status_code, status_text, headers)
{
    let lines = [
        `HTTP/1.1 ${status_code} ${status_text}`
    ];

    for(const [key, value] of headers.entries())
    {
        lines.push(`${key}: ${value}`);
    }

    return new TextEncoder().encode(lines.join("\r\n") + "\r\n\r\n");
};

FetchNetworkAdapter.prototype.respond_text_and_close = function(conn, status_code, status_text, body)
{
    const headers = new Headers({
        "content-type": "text/plain",
        "content-length": body.length.toString(10),
        "connection": "close"
    });
    conn.writev([this.form_response_head(status_code, status_text, headers), new TextEncoder().encode(body)]);
    conn.close();
};

FetchNetworkAdapter.prototype.parse_http_header = function(header)
{
    const parts = header.match(/^([^:]*):(.*)$/);
    if(!parts)
    {
        dbg_log("Unable to parse HTTP header", LOG_FETCH);
        return;
    }

    const key = parts[1];
    const value = parts[2].trim();

    if(key.length === 0)
    {
        dbg_log("Header key is empty, raw header", LOG_FETCH);
        return;
    }
    if(value.length === 0)
    {
        dbg_log("Header value is empty", LOG_FETCH);
        return;
    }
    if(!/^[\w-]+$/.test(key))
    {
        dbg_log("Header key contains forbidden characters", LOG_FETCH);
        return;
    }
    if(!/^[\x20-\x7E]+$/.test(value))
    {
        dbg_log("Header value contains forbidden characters", LOG_FETCH);
        return;
    }

    return { key, value };
};

/**
 * @param {Uint8Array} data
 */
FetchNetworkAdapter.prototype.send = function(data)
{
    handle_fake_networking(data, this);
};

/**
 * @param {Uint8Array} data
 */
FetchNetworkAdapter.prototype.receive = function(data)
{
    this.bus.send("net" + this.id + "-receive", new Uint8Array(data));
};
                                                                                                                                                                                                                                                                                                                                                                     source/v64/src/browser/filestorage.js                                                               0000644 0000000 0000000 00000010021 00000000000 014772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "../log.js";
import { load_file } from "../lib.js";

/** @interface */
export function FileStorageInterface() {}

/**
 * Read a portion of a file.
 * @param {string} sha256sum
 * @param {number} offset
 * @param {number} count
 * @param {number} file_size
 * @return {!Promise<Uint8Array>} null if file does not exist.
 */
FileStorageInterface.prototype.read = function(sha256sum, offset, count, file_size) {};

/**
 * Add a read-only file to the filestorage.
 * @param {string} sha256sum
 * @param {!Uint8Array} data
 * @return {!Promise}
 */
FileStorageInterface.prototype.cache = function(sha256sum, data) {};

/**
 * Call this when the file won't be used soon, e.g. when a file closes or when this immutable
 * version is already out of date. It is used to help prevent accumulation of unused files in
 * memory in the long run for some FileStorage mediums.
 */
FileStorageInterface.prototype.uncache = function(sha256sum) {};

/**
 * @constructor
 * @implements {FileStorageInterface}
 */
export function MemoryFileStorage()
{
    /**
     * From sha256sum to file data.
     * @type {Map<string,Uint8Array>}
     */
    this.filedata = new Map();
}

/**
 * @param {string} sha256sum
 * @param {number} offset
 * @param {number} count
 * @return {!Promise<Uint8Array>} null if file does not exist.
 */
MemoryFileStorage.prototype.read = async function(sha256sum, offset, count)
{
    dbg_assert(sha256sum, "MemoryFileStorage read: sha256sum should be a non-empty string");
    const data = this.filedata.get(sha256sum);

    if(!data)
    {
        return null;
    }

    return data.subarray(offset, offset + count);
};

/**
 * @param {string} sha256sum
 * @param {!Uint8Array} data
 */
MemoryFileStorage.prototype.cache = async function(sha256sum, data)
{
    dbg_assert(sha256sum, "MemoryFileStorage cache: sha256sum should be a non-empty string");
    this.filedata.set(sha256sum, data);
};

/**
 * @param {string} sha256sum
 */
MemoryFileStorage.prototype.uncache = function(sha256sum)
{
    this.filedata.delete(sha256sum);
};

/**
 * @constructor
 * @implements {FileStorageInterface}
 * @param {FileStorageInterface} file_storage
 * @param {string} baseurl
 * @param {function(number,Uint8Array):ArrayBuffer} zstd_decompress
 */
export function ServerFileStorageWrapper(file_storage, baseurl, zstd_decompress)
{
    dbg_assert(baseurl, "ServerMemoryFileStorage: baseurl should not be empty");

    if(!baseurl.endsWith("/"))
    {
        baseurl += "/";
    }

    this.storage = file_storage;
    this.baseurl = baseurl;
    this.zstd_decompress = zstd_decompress;
}

/**
 * @param {string} sha256sum
 * @param {number} file_size
 * @return {!Promise<Uint8Array>}
 */
ServerFileStorageWrapper.prototype.load_from_server = function(sha256sum, file_size)
{
    return new Promise((resolve, reject) =>
    {
        load_file(this.baseurl + sha256sum, { done: async buffer =>
        {
            let data = new Uint8Array(buffer);
            if(sha256sum.endsWith(".zst"))
            {
                data = new Uint8Array(
                    this.zstd_decompress(file_size, data)
                );
            }
            await this.cache(sha256sum, data);
            resolve(data);
        }});
    });
};

/**
 * @param {string} sha256sum
 * @param {number} offset
 * @param {number} count
 * @param {number} file_size
 * @return {!Promise<Uint8Array>}
 */
ServerFileStorageWrapper.prototype.read = async function(sha256sum, offset, count, file_size)
{
    const data = await this.storage.read(sha256sum, offset, count, file_size);
    if(!data)
    {
        const full_file = await this.load_from_server(sha256sum, file_size);
        return full_file.subarray(offset, offset + count);
    }
    return data;
};

/**
 * @param {string} sha256sum
 * @param {!Uint8Array} data
 */
ServerFileStorageWrapper.prototype.cache = async function(sha256sum, data)
{
    return await this.storage.cache(sha256sum, data);
};

/**
 * @param {string} sha256sum
 */
ServerFileStorageWrapper.prototype.uncache = function(sha256sum)
{
    this.storage.uncache(sha256sum);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/glbridge/d3d8-webgpu/d3d8_executor.js                                        0000644 0000000 0000000 00000652032 00000000000 020774  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // D8WG high-level Direct3D 8 command executor.
//
// The guest DLL keeps COM objects, shadow state, Lock/Unlock memory and batching
// inside Windows XP. This host owns only WebGPU resources and immutable cache
// objects. It intentionally starts with the Maple-relevant pre-transformed
// vertex path instead of translating through WineD3D/OpenGL/gl4es.

(function(global) {
    "use strict";

    /*
     * The device and the canvas configuration belong to webgpu_host.js. See the
     * same note in d3d9_executor.js: a GPUCanvasContext belongs to whichever
     * device last configured it, so a backend that brings its own device makes
     * every other backend's swap-chain texture unusable. This path also used to
     * request a device with no optional features at all, which would have left
     * a shared device without BCn had it won the race.
     */
    /*
     * Resolved when an executor is constructed, not when this file is
     * evaluated: the page's script order is not this module's to depend on,
     * and reading global.V86GPUHost at load time silently yields null when
     * webgpu_host.js happens to come later -- which reads downstream as
     * "WebGPU is unavailable" rather than as the load-order mistake it is.
     */
    function resolveGPUHost() {
        if (global.V86GPUHost) return global.V86GPUHost;
        try {
            return typeof require === "function" ?
                require("../webgpu_host.js") : null;
        } catch (error) {
            return null;
        }
    }

    const D8WG_MAGIC = 0x47573844; // "D8WG"
    const D8WG_CHECKPOINT_MAGIC = 0x43533844; // "D8SC"
    const D8WG_CHECKPOINT_VERSION = 1;
    const D8WG_VERSION_MAJOR = 1;
    const D8WG_VERSION_MINOR = 7;
    const D8WG_BATCH_HEADER_BYTES = 32;
    const D8WG_COMMAND_HEADER_BYTES = 16;

    const OP_HELLO = 1;
    const OP_CREATE_DEVICE = 2;
    const OP_RESET = 3;
    const OP_PRESENT = 4;
    const OP_CLEAR = 5;
    const OP_BEGIN_SCENE = 6;
    const OP_END_SCENE = 7;
    const OP_UPDATE_SURFACE = 8;
    const OP_CREATE_BUFFER = 0x100;
    const OP_UPDATE_BUFFER = 0x101;
    const OP_DESTROY_RESOURCE = 0x103;
    const OP_CREATE_TEXTURE = 0x110;
    const OP_UPDATE_TEXTURE = 0x111;
    const OP_CREATE_VERTEX_SHADER = 0x120;
    const OP_CREATE_PIXEL_SHADER = 0x121;
    const OP_SET_RENDER_STATE = 0x200;
    const OP_SET_TEXTURE_STAGE_STATE = 0x201;
    const OP_SET_TEXTURE = 0x202;
    const OP_SET_VIEWPORT = 0x203;
    const OP_SET_TRANSFORM = 0x204;
    const OP_SET_MATERIAL = 0x205;
    const OP_SET_LIGHT = 0x206;
    const OP_LIGHT_ENABLE = 0x207;
    const OP_SET_STREAM_SOURCE = 0x208;
    const OP_SET_INDICES = 0x209;
    const OP_SET_VERTEX_FORMAT = 0x20A;
    const OP_SET_RENDER_TARGET = 0x20B;
    const OP_SET_VERTEX_SHADER = 0x20C;
    const OP_SET_PIXEL_SHADER = 0x20D;
    const OP_SET_VERTEX_SHADER_CONSTANT = 0x20E;
    const OP_SET_PIXEL_SHADER_CONSTANT = 0x20F;
    const OP_DRAW_PRIMITIVE = 0x300;
    const OP_DRAW_INDEXED_PRIMITIVE = 0x301;
    const OP_DRAW_PRIMITIVE_UP = 0x302;
    const OP_DRAW_INDEXED_PRIMITIVE_UP = 0x303;

    const RESOURCE_BUFFER_VERTEX = 1;
    const RESOURCE_BUFFER_INDEX = 2;
    const RESOURCE_TEXTURE_2D = 3;
    const RESOURCE_VERTEX_SHADER = 4;
    const RESOURCE_PIXEL_SHADER = 5;
    const D8WG_MAX_VS_CONSTANTS = 96;
    const D8WG_MAX_PS_CONSTANTS = 8;
    const D3DUSAGE_RENDERTARGET = 0x1;
    const D3DFMT_A8R8G8B8 = 21;
    const D3DFMT_X8R8G8B8 = 22;
    const D3DFMT_R5G6B5 = 23;
    const D3DFMT_X1R5G5B5 = 24;
    const D3DFMT_A1R5G5B5 = 25;
    const D3DFMT_A4R4G4B4 = 26;
    const D3DFMT_A8 = 28;
    const D3DFMT_L8 = 50;
    const D3DFMT_DXT1 = 0x31545844;
    const D3DFMT_DXT3 = 0x33545844;
    const D3DFMT_DXT5 = 0x35545844;
    const D3DFMT_INDEX16 = 101;
    const D3DFMT_INDEX32 = 102;
    const D3DCLEAR_TARGET = 0x1;
    const D3DCLEAR_ZBUFFER = 0x2;
    const D3DCLEAR_STENCIL = 0x4;
    const D3DFVF_POSITION_MASK = 0x00E;
    const D3DFVF_XYZ = 0x002;
    const D3DFVF_XYZRHW = 0x004;
    const D3DFVF_NORMAL = 0x010;
    const D3DFVF_PSIZE = 0x020;
    const D3DFVF_DIFFUSE = 0x040;
    const D3DFVF_SPECULAR = 0x080;
    const D3DFVF_TEXCOUNT_MASK = 0xF00;
    const D3DFVF_TEXCOUNT_SHIFT = 8;

    const D3DRS_ALPHATESTENABLE = 15;
    const D3DRS_SHADEMODE = 9;
    const D3DRS_ZENABLE = 7;
    const D3DRS_ZWRITEENABLE = 14;
    const D3DRS_SRCBLEND = 19;
    const D3DRS_DESTBLEND = 20;
    const D3DRS_CULLMODE = 22;
    const D3DRS_ZFUNC = 23;
    const D3DRS_ALPHAREF = 24;
    const D3DRS_ALPHAFUNC = 25;
    const D3DRS_ALPHABLENDENABLE = 27;
    const D3DRS_FOGENABLE = 28;
    const D3DRS_SPECULARENABLE = 29;
    const D3DRS_FOGCOLOR = 34;
    const D3DRS_FOGTABLEMODE = 35;
    const D3DRS_FOGSTART = 36;
    const D3DRS_FOGEND = 37;
    const D3DRS_FOGDENSITY = 38;
    const D3DRS_ZBIAS = 47;
    const D3DRS_RANGEFOGENABLE = 48;
    const D3DRS_STENCILENABLE = 52;
    const D3DRS_STENCILFAIL = 53;
    const D3DRS_STENCILZFAIL = 54;
    const D3DRS_STENCILPASS = 55;
    const D3DRS_STENCILFUNC = 56;
    const D3DRS_STENCILREF = 57;
    const D3DRS_STENCILMASK = 58;
    const D3DRS_STENCILWRITEMASK = 59;
    const D3DRS_TEXTUREFACTOR = 60;
    const D3DRS_FOGVERTEXMODE = 140;
    const D3DRS_LIGHTING = 137;
    const D3DRS_AMBIENT = 139;
    const D3DRS_COLORVERTEX = 141;
    const D3DRS_LOCALVIEWER = 142;
    const D3DRS_NORMALIZENORMALS = 143;
    const D3DRS_DIFFUSEMATERIALSOURCE = 145;
    const D3DRS_SPECULARMATERIALSOURCE = 146;
    const D3DRS_AMBIENTMATERIALSOURCE = 147;
    const D3DRS_EMISSIVEMATERIALSOURCE = 148;
    const D3DRS_COLORWRITEENABLE = 168;
    const D3DRS_BLENDOP = 171;
    const D3DCULL_NONE = 1;
    const D3DCULL_CCW = 3;

    const D3DTSS_COLOROP = 1;
    const D3DTSS_COLORARG1 = 2;
    const D3DTSS_COLORARG2 = 3;
    const D3DTSS_ALPHAOP = 4;
    const D3DTSS_ALPHAARG1 = 5;
    const D3DTSS_ALPHAARG2 = 6;
    const D3DTSS_TEXCOORDINDEX = 11;
    const D3DTSS_ADDRESSU = 13;
    const D3DTSS_ADDRESSV = 14;
    const D3DTSS_MAGFILTER = 16;
    const D3DTSS_MINFILTER = 17;
    const D3DTSS_MIPFILTER = 18;
    const D3DTSS_MAXMIPLEVEL = 20;
    const D3DTSS_MAXANISOTROPY = 21;
    const D3DTSS_TEXTURETRANSFORMFLAGS = 24;
    const D3DTSS_COLORARG0 = 26;
    const D3DTSS_ALPHAARG0 = 27;
    const D3DTSS_RESULTARG = 28;

    const D3DTOP_DISABLE = 1;
    const D3DTA_SELECTMASK = 0xF;
    const D3DTA_DIFFUSE = 0;
    const D3DTA_CURRENT = 1;
    const D3DTA_TEXTURE = 2;
    const D3DTA_TFACTOR = 3;
    const D3DTA_SPECULAR = 4;
    const D3DTA_TEMP = 5;
    const D3DTA_COMPLEMENT = 0x10;
    const D3DTA_ALPHAREPLICATE = 0x20;

    const BUFFER_USAGE_COPY_SRC = 0x04;
    const BUFFER_USAGE_COPY_DST = 0x08;
    const BUFFER_USAGE_INDEX = 0x10;
    const BUFFER_USAGE_VERTEX = 0x20;
    const BUFFER_USAGE_UNIFORM = 0x40;
    const TEXTURE_USAGE_COPY_SRC = 0x01;
    const TEXTURE_USAGE_COPY_DST = 0x02;
    const TEXTURE_USAGE_TEXTURE_BINDING = 0x04;
    const TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;
    const TRANSIENT_BUFFER_BYTES = 16 * 1024 * 1024;
    const D3DLOCK_DISCARD = 0x2000;

    // Stage 7: uniform ring. Uniform data is suballocated from one persistent
    // ring buffer and bound with a dynamic offset, instead of minting a fresh
    // GPUBuffer per state change. WebGPU requires a dynamic uniform offset to
    // be a multiple of minUniformBufferOffsetAlignment; 256 is the spec's
    // maximum allowed value for that limit, so it is safe on every adapter.
    const UNIFORM_OFFSET_ALIGNMENT = 256;
    const FIXED_UNIFORM_BYTES = 1392;
    const SHADER_UNIFORM_BYTES =
        (D8WG_MAX_VS_CONSTANTS + D8WG_MAX_PS_CONSTANTS) * 16;
    const UNIFORM_RING_BYTES = 4 * 1024 * 1024;

    function alignUniform(value) {
        return (value + (UNIFORM_OFFSET_ALIGNMENT - 1)) &
            ~(UNIFORM_OFFSET_ALIGNMENT - 1);
    }

    // Which render states actually appear in the fixed-function uniform block
    // (see uniformFor / SurfaceUniforms). Everything else is pipeline state and
    // must not invalidate the packed uniform slot. Indexed by D3DRENDERSTATETYPE
    // for an O(1) integer test on the hot command path.
    const UNIFORM_RENDER_STATES = new Uint8Array(256);
    for (const renderState of [
        D3DRS_TEXTUREFACTOR, D3DRS_ALPHAREF, D3DRS_FOGCOLOR, D3DRS_FOGSTART,
        D3DRS_FOGEND, D3DRS_FOGDENSITY, D3DRS_AMBIENT,
    ]) UNIFORM_RENDER_STATES[renderState] = 1;

    // Reused across every setBindGroup so the hot draw path allocates nothing.
    // WebGPU's (data, start, length) overload reads the offsets out of this
    // array synchronously, so a single shared instance is safe.
    const DYNAMIC_OFFSETS = new Uint32Array(1);
    let uniformRingSerial = 0;

    function u16(bytes, offset) {
        return bytes[offset] | bytes[offset + 1] << 8;
    }

    function u32(bytes, offset) {
        return (bytes[offset] | bytes[offset + 1] << 8 |
            bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
    }

    function i32(bytes, offset) {
        return u32(bytes, offset) | 0;
    }

    function f32(bytes, offset) {
        return new DataView(bytes.buffer, bytes.byteOffset + offset, 4)
            .getFloat32(0, true);
    }

    function align4(value) {
        return (value + 3) & ~3;
    }

    function d3dColor(value) {
        return {
            r: ((value >>> 16) & 0xFF) / 255,
            g: ((value >>> 8) & 0xFF) / 255,
            b: (value & 0xFF) / 255,
            a: ((value >>> 24) & 0xFF) / 255,
        };
    }

    function primitiveInfo(type, primitiveCount) {
        switch (type >>> 0) {
        case 1: return { topology: "point-list", vertices: primitiveCount };
        case 2: return { topology: "line-list", vertices: primitiveCount * 2 };
        case 3: return { topology: "line-strip", vertices: primitiveCount + 1 };
        case 4: return { topology: "triangle-list", vertices: primitiveCount * 3 };
        case 5: return { topology: "triangle-strip", vertices: primitiveCount + 2 };
        case 6: return {
            topology: "triangle-list",
            vertices: primitiveCount + 2,
            fan: true,
            convertedIndices: primitiveCount * 3,
        };
        default: return null;
        }
    }

    function indexFormatInfo(format) {
        if ((format >>> 0) === D3DFMT_INDEX16) {
            return { webgpu: "uint16", bytes: 2, ArrayType: Uint16Array };
        }
        if ((format >>> 0) === D3DFMT_INDEX32) {
            return { webgpu: "uint32", bytes: 4, ArrayType: Uint32Array };
        }
        return null;
    }

    function checkedDataRange(bytes, offset, byteCount, label) {
        if (offset > bytes.length || byteCount > bytes.length - offset) {
            throw new Error(label + " range is outside its D8WG batch");
        }
        return bytes.subarray(offset, offset + byteCount);
    }

    function padded4(data) {
        if ((data.byteLength & 3) === 0) return data;
        const result = new Uint8Array(align4(data.byteLength));
        result.set(data);
        return result;
    }

    function textureFormatInfo(format) {
        switch (format >>> 0) {
        case D3DFMT_A8R8G8B8:
        case D3DFMT_X8R8G8B8:
            return { blockWidth: 1, blockHeight: 1, blockBytes: 4 };
        case D3DFMT_R5G6B5:
        case D3DFMT_X1R5G5B5:
        case D3DFMT_A1R5G5B5:
        case D3DFMT_A4R4G4B4:
            return { blockWidth: 1, blockHeight: 1, blockBytes: 2 };
        case D3DFMT_L8:
        case D3DFMT_A8:
            return { blockWidth: 1, blockHeight: 1, blockBytes: 1 };
        case D3DFMT_DXT1:
            return { blockWidth: 4, blockHeight: 4, blockBytes: 8, dxt: 1 };
        case D3DFMT_DXT3:
            return { blockWidth: 4, blockHeight: 4, blockBytes: 16, dxt: 3 };
        case D3DFMT_DXT5:
            return { blockWidth: 4, blockHeight: 4, blockBytes: 16, dxt: 5 };
        default:
            return null;
        }
    }

    function expand5(value) { return value * 255 / 31 | 0; }
    function expand6(value) { return value * 255 / 63 | 0; }

    function dxtColours(source, offset, allowTransparent) {
        const c0 = source[offset] | source[offset + 1] << 8;
        const c1 = source[offset + 2] | source[offset + 3] << 8;
        const first = [expand5(c0 >>> 11), expand6((c0 >>> 5) & 63),
            expand5(c0 & 31), 255];
        const second = [expand5(c1 >>> 11), expand6((c1 >>> 5) & 63),
            expand5(c1 & 31), 255];
        const colours = [first, second];
        if (allowTransparent && c0 <= c1) {
            colours.push(first.map((value, i) => i === 3 ? 255 :
                (value + second[i]) / 2 | 0));
            colours.push([0, 0, 0, 0]);
        } else {
            colours.push(first.map((value, i) => i === 3 ? 255 :
                (2 * value + second[i]) / 3 | 0));
            colours.push(first.map((value, i) => i === 3 ? 255 :
                (value + 2 * second[i]) / 3 | 0));
        }
        return colours;
    }

    function dxt5Alphas(source, offset) {
        const a0 = source[offset];
        const a1 = source[offset + 1];
        const values = [a0, a1];
        if (a0 > a1) {
            for (let i = 1; i <= 6; i++)
                values.push(((7 - i) * a0 + i * a1) / 7 | 0);
        } else {
            for (let i = 1; i <= 4; i++)
                values.push(((5 - i) * a0 + i * a1) / 5 | 0);
            values.push(0, 255);
        }
        return values;
    }

    function decodeDXT(format, source, width, height, rowPitch) {
        const info = textureFormatInfo(format);
        const output = new Uint8Array(width * height * 4);
        const blockColumns = Math.ceil(width / 4);
        const blockRows = Math.ceil(height / 4);
        for (let by = 0; by < blockRows; by++) {
            for (let bx = 0; bx < blockColumns; bx++) {
                const block = by * rowPitch + bx * info.blockBytes;
                const colourOffset = block + (info.dxt === 1 ? 0 : 8);
                const colours = dxtColours(source, colourOffset,
                    info.dxt === 1);
                const colourBits = u32(source, colourOffset + 4);
                const alphaValues = info.dxt === 5 ? dxt5Alphas(source, block) : null;
                for (let py = 0; py < 4; py++) {
                    for (let px = 0; px < 4; px++) {
                        const x = bx * 4 + px;
                        const y = by * 4 + py;
                        if (x >= width || y >= height) continue;
                        const pixel = py * 4 + px;
                        const colour = colours[(colourBits >>> (pixel * 2)) & 3];
                        const destination = (y * width + x) * 4;
                        output[destination] = colour[0];
                        output[destination + 1] = colour[1];
                        output[destination + 2] = colour[2];
                        if (info.dxt === 3) {
                            const packed = source[block + (pixel >>> 1)];
                            const nibble = pixel & 1 ? packed >>> 4 : packed & 15;
                            output[destination + 3] = nibble * 17;
                        } else if (info.dxt === 5) {
                            const bit = pixel * 3;
                            const byte = bit >>> 3;
                            const shift = bit & 7;
                            const packed = source[block + 2 + byte] |
                                (source[block + 3 + byte] || 0) << 8;
                            output[destination + 3] = alphaValues[(packed >>> shift) & 7];
                        } else {
                            output[destination + 3] = colour[3];
                        }
                    }
                }
            }
        }
        return output;
    }

    function decodeTextureUpload(format, source, width, height, rowPitch) {
        const info = textureFormatInfo(format);
        if (!info) throw new Error("unsupported D3D8 texture format " + format);
        if (info.dxt) return decodeDXT(format, source, width, height, rowPitch);
        const output = new Uint8Array(width * height * 4);
        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const sourceOffset = y * rowPitch + x * info.blockBytes;
                const destination = (y * width + x) * 4;
                let r, g, b, a;
                if (format === D3DFMT_A8R8G8B8 || format === D3DFMT_X8R8G8B8) {
                    b = source[sourceOffset];
                    g = source[sourceOffset + 1];
                    r = source[sourceOffset + 2];
                    a = format === D3DFMT_A8R8G8B8 ? source[sourceOffset + 3] : 255;
                } else if (format === D3DFMT_L8) {
                    r = g = b = source[sourceOffset]; a = 255;
                } else if (format === D3DFMT_A8) {
                    r = g = b = 255; a = source[sourceOffset];
                } else {
                    const value = source[sourceOffset] | source[sourceOffset + 1] << 8;
                    if (format === D3DFMT_R5G6B5) {
                        r = expand5(value >>> 11); g = expand6((value >>> 5) & 63);
                        b = expand5(value & 31); a = 255;
                    } else if (format === D3DFMT_A4R4G4B4) {
                        a = (value >>> 12) * 17; r = ((value >>> 8) & 15) * 17;
                        g = ((value >>> 4) & 15) * 17; b = (value & 15) * 17;
                    } else {
                        a = format === D3DFMT_A1R5G5B5 && (value & 0x8000) ? 255 :
                            format === D3DFMT_X1R5G5B5 ? 255 : 0;
                        r = expand5((value >>> 10) & 31);
                        g = expand5((value >>> 5) & 31);
                        b = expand5(value & 31);
                    }
                }
                output[destination] = r;
                output[destination + 1] = g;
                output[destination + 2] = b;
                output[destination + 3] = a;
            }
        }
        return output;
    }

    function parseFVF(fvf, stride) {
        const position = fvf & D3DFVF_POSITION_MASK;
        if (position !== D3DFVF_XYZ && position !== D3DFVF_XYZRHW)
            return null;
        const pretransformed = position === D3DFVF_XYZRHW;
        const attributes = [{ shaderLocation: 0, offset: 0,
            format: pretransformed ? "float32x4" : "float32x3" }];
        let offset = pretransformed ? 16 : 12;
        const result = { attributes, diffuse: false, specular: false,
            normal: false, pointSize: false,
            texDims: [], minimumStride: offset, pretransformed };
        if (fvf & D3DFVF_NORMAL) {
            if (pretransformed) return null;
            attributes.push({ shaderLocation: 5, offset,
                format: "float32x3" });
            result.normal = true;
            offset += 12;
        }
        if (fvf & D3DFVF_PSIZE) {
            attributes.push({ shaderLocation: 6, offset, format: "float32" });
            result.pointSize = true;
            offset += 4;
        }
        if (fvf & D3DFVF_DIFFUSE) {
            attributes.push({ shaderLocation: 1, offset, format: "unorm8x4" });
            result.diffuse = true;
            offset += 4;
        }
        if (fvf & D3DFVF_SPECULAR) {
            attributes.push({ shaderLocation: 2, offset, format: "unorm8x4" });
            result.specular = true;
            offset += 4;
        }
        const textureCount = (fvf & D3DFVF_TEXCOUNT_MASK) >>>
            D3DFVF_TEXCOUNT_SHIFT;
        if (textureCount > 2) return null;
        for (let stage = 0; stage < textureCount; stage++) {
            const code = (fvf >>> (16 + stage * 2)) & 3;
            const dimensions = [2, 3, 4, 1][code];
            result.texDims.push(dimensions);
            attributes.push({ shaderLocation: 3 + stage, offset,
                format: dimensions === 1 ? "float32" : "float32x" + dimensions });
            offset += dimensions * 4;
        }
        result.minimumStride = offset;
        return stride >= offset ? result : null;
    }

    function textureArgument(argument, stage) {
        let expression;
        switch (argument & D3DTA_SELECTMASK) {
        case D3DTA_DIFFUSE: expression = "input.diffuse"; break;
        case D3DTA_CURRENT: expression = "current"; break;
        case D3DTA_TEXTURE: expression = "stage" + stage + "Texture"; break;
        case D3DTA_TFACTOR: expression = "textureFactor"; break;
        case D3DTA_SPECULAR: expression = "input.specular"; break;
        case D3DTA_TEMP: expression = "temporary"; break;
        default: expression = "current"; break;
        }
        if (argument & D3DTA_COMPLEMENT)
            expression = "(vec4<f32>(1.0) - " + expression + ")";
        if (argument & D3DTA_ALPHAREPLICATE)
            expression = "(" + expression + ").aaaa";
        return expression;
    }

    function textureOperation(operation, one, two, zero, stage) {
        const texture = "stage" + stage + "Texture";
        switch (operation >>> 0) {
        case 2: return one;
        case 3: return two;
        case 4: return "(" + one + " * " + two + ")";
        case 5: return "(" + one + " * " + two + " * 2.0)";
        case 6: return "(" + one + " * " + two + " * 4.0)";
        case 7: return "(" + one + " + " + two + ")";
        case 8: return "(" + one + " + " + two + " - vec4<f32>(0.5))";
        case 9: return "((" + one + " + " + two + " - vec4<f32>(0.5)) * 2.0)";
        case 10: return "(" + one + " - " + two + ")";
        case 11: return "(" + one + " + " + two + " * (vec4<f32>(1.0) - " + one + "))";
        case 12: return "mix(" + two + ", " + one + ", input.diffuse.aaaa)";
        case 13: return "mix(" + two + ", " + one + ", " + texture + ".aaaa)";
        case 14: return "mix(" + two + ", " + one + ", textureFactor.aaaa)";
        case 15: return "(" + one + " + " + two + " * (vec4<f32>(1.0) - " + texture + ".aaaa))";
        case 16: return "mix(" + two + ", " + one + ", current.aaaa)";
        case 18: return "vec4<f32>(" + one + ".rgb + " + one + ".aaa * " + two + ".rgb, " + one + ".a)";
        case 19: return "vec4<f32>(" + one + ".rgb * " + two + ".rgb + " + one + ".aaa, " + one + ".a)";
        case 20: return "vec4<f32>(" + one + ".rgb + (vec3<f32>(1.0) - " + one + ".aaa) * " + two + ".rgb, " + one + ".a)";
        case 21: return "vec4<f32>((vec3<f32>(1.0) - " + one + ".rgb) * " + two + ".rgb + " + one + ".aaa, " + one + ".a)";
        case 24: return "vec4<f32>(vec3<f32>(dot((" + one + ".rgb - vec3<f32>(0.5)) * 2.0, (" + two + ".rgb - vec3<f32>(0.5)) * 2.0)), 1.0)";
        case 25: return "(" + one + " * " + two + " + " + zero + ")";
        case 26: return "mix(" + two + ", " + one + ", " + zero + ")";
        default: return one;
        }
    }

    function alphaTestDiscard(func) {
        const alpha = "round(clamp(current.a, 0.0, 1.0) * 255.0)";
        const ref = "surface.alpha_ref";
        switch (func >>> 0) {
        case 1: return "true";
        case 2: return alpha + " >= " + ref;
        case 3: return alpha + " != " + ref;
        case 4: return alpha + " > " + ref;
        case 5: return alpha + " <= " + ref;
        case 6: return alpha + " == " + ref;
        case 7: return alpha + " < " + ref;
        case 8: return "false";
        default: return "false";
        }
    }

    function compareFunction(value) {
        return ({ 1: "never", 2: "less", 3: "equal", 4: "less-equal",
            5: "greater", 6: "not-equal", 7: "greater-equal",
            8: "always" })[value >>> 0] || "always";
    }

    function stencilOperation(value) {
        return ({ 1: "keep", 2: "zero", 3: "replace",
            4: "increment-clamp", 5: "decrement-clamp", 6: "invert",
            7: "increment-wrap", 8: "decrement-wrap" })[value >>> 0] || "keep";
    }

    function dwordFloat(value) {
        const bits = new Uint32Array(1);
        bits[0] = value >>> 0;
        return new Float32Array(bits.buffer)[0];
    }

    function blendFactor(value) {
        return ({ 1: "zero", 2: "one", 3: "src", 4: "one-minus-src",
            5: "src-alpha", 6: "one-minus-src-alpha", 7: "dst-alpha",
            8: "one-minus-dst-alpha", 9: "dst", 10: "one-minus-dst",
            11: "src-alpha-saturated", 12: "src-alpha",
            13: "one-minus-src-alpha" })[value >>> 0] || "one";
    }

    function blendState(state) {
        let source = state.renderStates[D3DRS_SRCBLEND] >>> 0;
        let destination = state.renderStates[D3DRS_DESTBLEND] >>> 0;
        if (source === 12) {
            source = 5;
            destination = 6;
        } else if (source === 13) {
            source = 6;
            destination = 5;
        }
        return {
            color: { operation: blendOperation(
                state.renderStates[D3DRS_BLENDOP]), srcFactor: blendFactor(source),
                dstFactor: blendFactor(destination) },
            alpha: { operation: blendOperation(
                state.renderStates[D3DRS_BLENDOP]), srcFactor: blendFactor(source),
                dstFactor: blendFactor(destination) },
        };
    }

    function blendOperation(value) {
        return ({ 1: "add", 2: "subtract", 3: "reverse-subtract",
            4: "min", 5: "max" })[value >>> 0] || "add";
    }

    function materialSource(state, renderState, uniformName) {
        if (!state.renderStates[D3DRS_COLORVERTEX])
            return "surface." + uniformName;
        switch (state.renderStates[renderState] >>> 0) {
        case 1: return "vertex_diffuse";
        case 2: return "vertex_specular";
        default: return "surface." + uniformName;
        }
    }

    function fixedFunctionShader(state, layout) {
        const inputs = ["    @location(0) position: " +
            (layout.pretransformed ? "vec4<f32>," : "vec3<f32>,")];
        if (layout.normal)
            inputs.push("    @location(5) normal: vec3<f32>,");
        if (layout.diffuse) inputs.push("    @location(1) diffuse_bgra: vec4<f32>,");
        if (layout.specular) inputs.push("    @location(2) specular_bgra: vec4<f32>,");
        for (let stage = 0; stage < layout.texDims.length; stage++) {
            const dimensions = layout.texDims[stage];
            inputs.push("    @location(" + (3 + stage) + ") tex" + stage +
                ": " + (dimensions === 1 ? "f32" : "vec" + dimensions + "<f32>") + ",");
        }
        const vertexAssignments = [
            "    let vertex_diffuse = " + (layout.diffuse ?
                "input.diffuse_bgra.bgra;" : "vec4<f32>(1.0);"),
            "    let vertex_specular = " + (layout.specular ?
                "input.specular_bgra.bgra;" : "vec4<f32>(0.0);"),
            "    output.diffuse = vertex_diffuse;",
            "    output.specular = vertex_specular;",
        ];
        for (let stage = 0; stage < 2; stage++) {
            const texcoordIndex = state.textureStageStates[stage][D3DTSS_TEXCOORDINDEX] >>> 0;
            const coordinateSet = texcoordIndex & 0xFFFF;
            const dimensions = coordinateSet < layout.texDims.length ?
                layout.texDims[coordinateSet] : 0;
            const inputName = "input.tex" + coordinateSet;
            const generated = texcoordIndex & 0xFFFF0000;
            let source = !dimensions ? "vec4<f32>(0.0, 0.0, 0.0, 1.0)" :
                dimensions === 1 ? "vec4<f32>(" + inputName +
                    ", 0.0, 0.0, 1.0)" :
                dimensions === 2 ? "vec4<f32>(" + inputName +
                    ", 0.0, 1.0)" :
                dimensions === 3 ? "vec4<f32>(" + inputName +
                    ", 1.0)" : inputName;
            if (generated === 0x20000 && !layout.pretransformed)
                source = "eye_position";
            else if (generated === 0x10000 && layout.normal)
                source = "vec4<f32>(eye_normal, 1.0)";
            else if (generated === 0x30000 && layout.normal)
                source = "vec4<f32>(reflect(normalize(eye_position.xyz), eye_normal), 1.0)";
            const transformFlags = state.textureStageStates[stage][D3DTSS_TEXTURETRANSFORMFLAGS] >>> 0;
            if (transformFlags & 0xFF) {
                const transformed = "transformed_tex" + stage;
                vertexAssignments.push("    let " + transformed +
                    " = surface.texture_transforms[" + stage + "] * " +
                    source + ";");
                if (transformFlags & 0x100) {
                    const component = (transformFlags & 0xFF) >= 4 ? "w" :
                        (transformFlags & 0xFF) === 3 ? "z" : "y";
                    vertexAssignments.push("    output.tex" + stage + " = " +
                        transformed + ".xy / max(0.000001, abs(" +
                        transformed + "." + component + ")) * sign(" +
                        transformed + "." + component + ");");
                } else {
                    vertexAssignments.push("    output.tex" + stage +
                        " = " + transformed + ".xy;");
                }
            } else {
                vertexAssignments.push("    output.tex" + stage + " = " +
                    source + ".xy;");
            }
        }
        if (state.renderStates[D3DRS_LIGHTING] && layout.normal) {
            const materialDiffuse = materialSource(state,
                D3DRS_DIFFUSEMATERIALSOURCE, "material_diffuse");
            const materialSpecular = materialSource(state,
                D3DRS_SPECULARMATERIALSOURCE, "material_specular");
            const materialAmbient = materialSource(state,
                D3DRS_AMBIENTMATERIALSOURCE, "material_ambient");
            const materialEmissive = materialSource(state,
                D3DRS_EMISSIVEMATERIALSOURCE, "material_emissive");
            const viewer = state.renderStates[D3DRS_LOCALVIEWER] ?
                "normalize(-eye_position.xyz)" : "vec3<f32>(0.0, 0.0, -1.0)";
            vertexAssignments.push(`
    let active_material_diffuse = ${materialDiffuse};
    let active_material_specular = ${materialSpecular};
    let active_material_ambient = ${materialAmbient};
    let active_material_emissive = ${materialEmissive};
    let viewer_direction = ${viewer};
    var lit_diffuse = active_material_emissive +
        active_material_ambient * surface.global_ambient;
    var lit_specular = vec4<f32>(0.0);
    for (var light_index: u32 = 0u; light_index < 8u; light_index++) {
        let light = surface.lights[light_index];
        if (light.spot_angles_enabled.z > 0.5) {
            let eye_light_direction = normalize((surface.view *
                vec4<f32>(light.direction_range.xyz, 0.0)).xyz);
            var to_light = -eye_light_direction;
            var attenuation = 1.0;
            if (light.position_type.w < 2.5) {
                let eye_light_position = (surface.view *
                    vec4<f32>(light.position_type.xyz, 1.0)).xyz;
                let delta = eye_light_position - eye_position.xyz;
                let distance = length(delta);
                to_light = delta / max(distance, 0.000001);
                attenuation = select(0.0, 1.0 / max(0.000001,
                    light.attenuation_falloff.x +
                    light.attenuation_falloff.y * distance +
                    light.attenuation_falloff.z * distance * distance),
                    distance <= light.direction_range.w);
                if (light.position_type.w > 1.5) {
                    let rho = dot(-to_light, eye_light_direction);
                    let outer = cos(light.spot_angles_enabled.y * 0.5);
                    let inner = cos(light.spot_angles_enabled.x * 0.5);
                    attenuation *= pow(clamp((rho - outer) /
                        max(0.000001, inner - outer), 0.0, 1.0),
                        max(0.0, light.attenuation_falloff.w));
                }
            }
            let n_dot_l = max(dot(eye_normal, to_light), 0.0);
            lit_diffuse += attenuation *
                (active_material_ambient * light.ambient +
                 active_material_diffuse * light.diffuse * n_dot_l);
            if (n_dot_l > 0.0 && surface.material_params.x > 0.0) {
                let halfway = normalize(to_light + viewer_direction);
                let specular_factor = pow(max(dot(eye_normal, halfway), 0.0),
                    surface.material_params.x);
                lit_specular += attenuation * active_material_specular *
                    light.specular * specular_factor;
            }
        }
    }
    output.diffuse = vec4<f32>(clamp(lit_diffuse.rgb,
        vec3<f32>(0.0), vec3<f32>(1.0)), active_material_diffuse.a);
    output.specular = clamp(lit_specular, vec4<f32>(0.0), vec4<f32>(1.0));`);
        }
        const fragment = [
            "    let textureFactor = surface.texture_factor;",
            "    var current = input.diffuse;",
            "    var temporary = vec4<f32>(0.0);",
            "    let stage0Texture = textureSample(texture0, sampler0, input.tex0);",
            "    let stage1Texture = textureSample(texture1, sampler1, input.tex1);",
        ];
        for (let stage = 0; stage < 2; stage++) {
            const values = state.textureStageStates[stage];
            const colorOp = values[D3DTSS_COLOROP] >>> 0;
            if (colorOp === D3DTOP_DISABLE) break;
            const color1 = textureArgument(values[D3DTSS_COLORARG1], stage);
            const color2 = textureArgument(values[D3DTSS_COLORARG2], stage);
            const color0 = textureArgument(values[D3DTSS_COLORARG0], stage);
            const alphaOp = values[D3DTSS_ALPHAOP] >>> 0;
            const alpha1 = textureArgument(values[D3DTSS_ALPHAARG1], stage);
            const alpha2 = textureArgument(values[D3DTSS_ALPHAARG2], stage);
            const alpha0 = textureArgument(values[D3DTSS_ALPHAARG0], stage);
            fragment.push("    let stage" + stage + "Color = " +
                textureOperation(colorOp, color1, color2, color0, stage) + ";");
            fragment.push("    let stage" + stage + "Alpha = " +
                (alphaOp === D3DTOP_DISABLE ? "current" :
                    textureOperation(alphaOp, alpha1, alpha2, alpha0, stage)) + ";");
            const destination = (values[D3DTSS_RESULTARG] & D3DTA_SELECTMASK) ===
                D3DTA_TEMP ? "temporary" : "current";
            fragment.push("    " + destination + " = clamp(vec4<f32>(stage" +
                stage + "Color.rgb, stage" + stage + "Alpha.a), " +
                "vec4<f32>(0.0), vec4<f32>(1.0));");
        }
        if (state.renderStates[D3DRS_SPECULARENABLE])
            fragment.push("    current = vec4<f32>(clamp(current.rgb + input.specular.rgb, vec3<f32>(0.0), vec3<f32>(1.0)), current.a);");
        if (state.renderStates[D3DRS_ALPHATESTENABLE])
            fragment.push("    if (" + alphaTestDiscard(
                state.renderStates[D3DRS_ALPHAFUNC]) + ") { discard; }");
        if (state.renderStates[D3DRS_FOGENABLE]) {
            const fogMode = state.renderStates[D3DRS_FOGTABLEMODE] ||
                state.renderStates[D3DRS_FOGVERTEXMODE];
            if (fogMode === 1)
                fragment.push("    let fog_factor = clamp(exp(-surface.fog_params.z * input.fog_depth), 0.0, 1.0);");
            else if (fogMode === 2)
                fragment.push("    let fog_factor = clamp(exp(-pow(surface.fog_params.z * input.fog_depth, 2.0)), 0.0, 1.0);");
            else
                fragment.push("    let fog_factor = clamp((surface.fog_params.y - input.fog_depth) / max(0.000001, surface.fog_params.y - surface.fog_params.x), 0.0, 1.0);");
            fragment.push("    current = vec4<f32>(mix(surface.fog_color.rgb, current.rgb, fog_factor), current.a);");
        }
        fragment.push("    return current;");
        const positionAssignment = layout.pretransformed ? `
    let pixel = input.position.xy - vec2<f32>(0.5, 0.5);
    let rhw = select(1.0, input.position.w, abs(input.position.w) > 0.000001);
    let clipW = 1.0 / rhw;
    output.position = vec4<f32>((pixel.x * surface.inverse_size.x * 2.0 - 1.0) * clipW,
        (1.0 - pixel.y * surface.inverse_size.y * 2.0) * clipW,
        clamp(input.position.z, 0.0, 1.0) * clipW, clipW);` : `
    let world_position = surface.world * vec4<f32>(input.position, 1.0);
    let eye_position = surface.view * world_position;
    output.position = surface.projection * eye_position;
    output.fog_depth = ${state.renderStates[D3DRS_RANGEFOGENABLE] ?
        "length(eye_position.xyz)" : "abs(eye_position.z)"};`;
        const normalAssignment = layout.normal ? `
    let eye_normal_value = (surface.view * surface.world *
        vec4<f32>(input.normal, 0.0)).xyz;
    let eye_normal = ${state.renderStates[D3DRS_NORMALIZENORMALS] ?
        "normalize(eye_normal_value)" : "eye_normal_value"};` : "";
        const interpolation = state.renderStates[D3DRS_SHADEMODE] === 1 ?
            " @interpolate(flat)" : "";
        return `
struct LightUniform {
    diffuse: vec4<f32>, specular: vec4<f32>, ambient: vec4<f32>,
    position_type: vec4<f32>, direction_range: vec4<f32>,
    attenuation_falloff: vec4<f32>, spot_angles_enabled: vec4<f32>,
};
struct SurfaceUniforms {
    size: vec2<f32>, inverse_size: vec2<f32>,
    texture_factor: vec4<f32>, alpha_ref: f32,
    padding0: f32, padding1: f32, padding2: f32,
    world: mat4x4<f32>, view: mat4x4<f32>, projection: mat4x4<f32>,
    fog_color: vec4<f32>, fog_params: vec4<f32>,
    material_diffuse: vec4<f32>, material_ambient: vec4<f32>,
    material_specular: vec4<f32>, material_emissive: vec4<f32>,
    material_params: vec4<f32>, global_ambient: vec4<f32>,
    lights: array<LightUniform, 8>,
    texture_transforms: array<mat4x4<f32>, 2>,
};
@group(0) @binding(0) var<uniform> surface: SurfaceUniforms;
@group(0) @binding(1) var texture0: texture_2d<f32>;
@group(0) @binding(2) var sampler0: sampler;
@group(0) @binding(3) var texture1: texture_2d<f32>;
@group(0) @binding(4) var sampler1: sampler;
struct VSInput {
${inputs.join("\n")}
};
struct VSOutput {
    @builtin(position) position: vec4<f32>,
    @location(0)${interpolation} diffuse: vec4<f32>,
    @location(1)${interpolation} specular: vec4<f32>,
    @location(2) tex0: vec2<f32>,
    @location(3) tex1: vec2<f32>,
    @location(4) fog_depth: f32,
};
@vertex fn vs_main(input: VSInput) -> VSOutput {
    var output: VSOutput;
${positionAssignment}
${layout.pretransformed ? "    output.fog_depth = input.position.z;" : ""}
${normalAssignment}
${vertexAssignments.join("\n")}
    return output;
}
@fragment fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
${fragment.join("\n")}
}
`;
    }

    // ---- Stage 6: D3D8 shader model 1.x bytecode -> WGSL translation ----
    //
    // Token layout constants mirror the real D3D8 SDK bit patterns exactly
    // (see d3d8types.h) since guest-compiled shader bytecode is genuine
    // Microsoft-format SM1.x tokens, not a project-invented encoding. The
    // guest (d3d8_proxy.c: validate_shader_body) enforces the identical
    // supported-instruction table before a shader is ever created, so this
    // translator should never actually see an unsupported opcode from a
    // well-behaved guest build -- but it re-checks independently rather than
    // trusting the wire, per the "host validates before executing" rule.
    const D3DSI_OPCODE_MASK = 0x0000FFFF;
    const D3DSI_COMMENTSIZE_SHIFT = 16;
    const D3DSI_COMMENTSIZE_MASK = 0x7FFF << D3DSI_COMMENTSIZE_SHIFT;
    const D3DSP_REGNUM_MASK = 0x000007FF;
    const D3DSP_DSTMOD_SHIFT = 20;
    const D3DSP_DSTMOD_MASK = 0xF << D3DSP_DSTMOD_SHIFT;
    const D3DSPDM_SATURATE = 1;
    const D3DSP_DSTSHIFT_SHIFT = 24;
    const D3DSP_DSTSHIFT_MASK = 0xF << D3DSP_DSTSHIFT_SHIFT;
    const D3DSP_REGTYPE_SHIFT = 28;
    const D3DSP_REGTYPE_MASK = 0x7 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_TEMP = 0 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_INPUT = 1 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_CONST = 2 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_TEXTURE = 3 << D3DSP_REGTYPE_SHIFT; // == D3DSPR_ADDR
    const D3DSPR_RASTOUT = 4 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_ATTROUT = 5 << D3DSP_REGTYPE_SHIFT;
    const D3DSPR_TEXCRDOUT = 6 << D3DSP_REGTYPE_SHIFT;
    const D3DSP_SWIZZLE_SHIFT = 16;
    const D3DSP_SRCMOD_SHIFT = 24;
    const D3DSP_SRCMOD_MASK = 0xF << D3DSP_SRCMOD_SHIFT;

    const D3DSIO_NOP = 0, D3DSIO_MOV = 1, D3DSIO_ADD = 2, D3DSIO_SUB = 3,
        D3DSIO_MAD = 4, D3DSIO_MUL = 5, D3DSIO_RCP = 6, D3DSIO_RSQ = 7,
        D3DSIO_DP3 = 8, D3DSIO_DP4 = 9, D3DSIO_MIN = 10, D3DSIO_MAX = 11,
        D3DSIO_SLT = 12, D3DSIO_SGE = 13, D3DSIO_EXP = 14, D3DSIO_LOG = 15,
        D3DSIO_LIT = 16, D3DSIO_DST = 17, D3DSIO_LRP = 18, D3DSIO_FRC = 19,
        D3DSIO_TEXCOORD = 64, D3DSIO_TEXKILL = 65, D3DSIO_TEX = 66,
        D3DSIO_EXPP = 78, D3DSIO_LOGP = 79, D3DSIO_CND = 80, D3DSIO_DEF = 81,
        D3DSIO_CMP = 88, D3DSIO_PHASE = 0xFFFD, D3DSIO_COMMENT = 0xFFFE,
        D3DSIO_END = 0xFFFF;

    const D3DVSD_TOKENTYPESHIFT = 29;
    const D3DVSD_TOKEN_STREAMDATA = 2;
    const D3DVSD_TOKEN_END = 7;
    const D3DVSD_DATATYPESHIFT = 16;
    const D3DVSD_VERTEXREGMASK = 0x1F;
    const D3DVSD_SKIPFLAG = 0x10000000;

    // Number of DWORD parameter tokens following the opcode token. DEF's
    // four trailing tokens are raw float32 immediates, not registers,
    // flagged via isDef. Returns null for anything outside the Stage 6
    // supported instruction set for this shader type/version -- matches
    // shader_opcode_supported() in d3d8_proxy.c exactly.
    function shaderOpcodeInfo(opcode, isPixelShader, minor) {
        switch (opcode) {
        case D3DSIO_NOP: return { operandWords: 0 };
        case D3DSIO_MOV: return { operandWords: 2 };
        case D3DSIO_ADD: case D3DSIO_SUB: case D3DSIO_MUL:
        case D3DSIO_MIN: case D3DSIO_MAX: case D3DSIO_DP3: case D3DSIO_DP4:
            return { operandWords: 3 };
        case D3DSIO_MAD: return { operandWords: 4 };
        case D3DSIO_RCP: case D3DSIO_RSQ: case D3DSIO_EXP: case D3DSIO_LOG:
        case D3DSIO_LIT: case D3DSIO_FRC: case D3DSIO_EXPP: case D3DSIO_LOGP:
            return isPixelShader ? null : { operandWords: 2 };
        case D3DSIO_SLT: case D3DSIO_SGE: case D3DSIO_DST:
            return isPixelShader ? null : { operandWords: 3 };
        case D3DSIO_DEF: return { operandWords: 5, isDef: true };
        case D3DSIO_LRP:
            return isPixelShader ? { operandWords: 4 } : null;
        case D3DSIO_CND:
            return (isPixelShader && minor <= 3) ? { operandWords: 4 } : null;
        case D3DSIO_CMP:
            return (isPixelShader && minor >= 2) ? { operandWords: 4 } : null;
        case D3DSIO_TEXCOORD:
            return isPixelShader ? { operandWords: 1 } : null;
        case D3DSIO_TEX:
            return isPixelShader ?
                { operandWords: minor >= 4 ? 2 : 1 } : null;
        case D3DSIO_TEXKILL:
            return isPixelShader ? { operandWords: 1 } : null;
        case D3DSIO_PHASE:
            return (isPixelShader && minor === 4) ? { operandWords: 0 } : null;
        default:
            return null;
        }
    }

    function regType(token) { return (token & D3DSP_REGTYPE_MASK) >>> 0; }
    function regNum(token) { return (token & D3DSP_REGNUM_MASK) >>> 0; }
    function dstWriteMaskBits(token) { return (token >>> 16) & 0xF; }
    function dstSaturates(token) {
        return ((token & D3DSP_DSTMOD_MASK) >>> D3DSP_DSTMOD_SHIFT) ===
            D3DSPDM_SATURATE;
    }
    function dstShiftAmount(token) {
        let shift = (token & D3DSP_DSTSHIFT_MASK) >>> D3DSP_DSTSHIFT_SHIFT;
        if (shift >= 8) shift -= 16; // 4-bit two's-complement nibble
        return shift;
    }
    function srcSwizzleByte(token) { return (token >>> D3DSP_SWIZZLE_SHIFT) & 0xFF; }
    function srcModifierBits(token) {
        return (token & D3DSP_SRCMOD_MASK) >>> D3DSP_SRCMOD_SHIFT;
    }

    function swizzleSuffix(swizzleByte) {
        const letters = "xyzw";
        let suffix = "";
        for (let i = 0; i < 4; i++)
            suffix += letters[(swizzleByte >>> (i * 2)) & 3];
        return suffix;
    }

    function writeMaskSuffix(mask) {
        let suffix = "";
        if (mask & 1) suffix += "x";
        if (mask & 2) suffix += "y";
        if (mask & 4) suffix += "z";
        if (mask & 8) suffix += "w";
        return suffix;
    }

    function applySourceModifier(expr, modifier) {
        switch (modifier) {
        case 0x0: return expr; // D3DSPSM_NONE
        case 0x1: return "(-" + expr + ")"; // D3DSPSM_NEG
        case 0x2: return "(" + expr + " - vec4<f32>(0.5))"; // D3DSPSM_BIAS
        case 0x6: return "(vec4<f32>(1.0) - " + expr + ")"; // D3DSPSM_COMP
        case 0xB: return "abs(" + expr + ")"; // D3DSPSM_ABS
        default:
            throw new Error("unsupported D3D8 source register modifier 0x" +
                modifier.toString(16));
        }
    }

    function applyDestModifiers(resultExpr, dstToken) {
        const shift = dstShiftAmount(dstToken);
        const shiftFactor = { 0: null, 1: 2, 2: 4, 3: 8,
            "-1": 0.5, "-2": 0.25, "-3": 0.125 }[shift];
        if (shift !== 0) {
            if (shiftFactor === undefined)
                throw new Error("unsupported D3D8 destination shift " + shift);
            resultExpr = "(" + resultExpr + " * " + shiftFactor + ")";
        }
        if (dstSaturates(dstToken))
            resultExpr = "clamp(" + resultExpr +
                ", vec4<f32>(0.0), vec4<f32>(1.0))";
        return resultExpr;
    }

    // Walks one D3D8 SM1.x token stream starting right after the version
    // token. `registerExpr(token)` returns the WGSL base expression (before
    // swizzle/modifier) for a register-encoded operand token; throwing from
    // it (e.g. an undeclared vertex input, an out-of-range constant) aborts
    // translation the same way an unsupported opcode does. `emitInstruction`
    // receives (opcode, dstToken, [sourceExprStrings], rawTokens) and pushes
    // WGSL statement(s) for one instruction; DEF is intercepted before this
    // callback runs. Returns nothing; throws on anything outside the Stage 6
    // supported instruction set or a truncated/malformed stream.
    function walkShaderBody(tokens, isPixelShader, minor, registerExpr,
            emitInstruction) {
        const defConstants = new Map();
        // Pre-pass: shader-embedded constants (DEF) override whatever the
        // application sets via Set{Vertex,Pixel}ShaderConstant for that
        // register, per D3D8 semantics, so the main pass needs to know about
        // them before it ever emits a read of a constant register.
        for (let offset = 0; offset < tokens.length;) {
            const token = tokens[offset] >>> 0;
            if (token === D3DSIO_END) break;
            const opcode = token & D3DSI_OPCODE_MASK;
            if (opcode === D3DSIO_COMMENT) {
                offset += 1 + ((token & D3DSI_COMMENTSIZE_MASK) >>>
                    D3DSI_COMMENTSIZE_SHIFT);
                continue;
            }
            const info = shaderOpcodeInfo(opcode, isPixelShader, minor);
            if (!info)
                throw new Error("unsupported D3D8 shader opcode 0x" +
                    opcode.toString(16));
            if (offset + 1 + info.operandWords > tokens.length)
                throw new Error("truncated D3D8 shader instruction 0x" +
                    opcode.toString(16));
            if (opcode === D3DSIO_DEF) {
                const dst = tokens[offset + 1] >>> 0;
                defConstants.set(regNum(dst), [
                    dwordFloat(tokens[offset + 2] >>> 0),
                    dwordFloat(tokens[offset + 3] >>> 0),
                    dwordFloat(tokens[offset + 4] >>> 0),
                    dwordFloat(tokens[offset + 5] >>> 0),
                ]);
            }
            offset += 1 + info.operandWords;
        }

        const constExpr = (token) => {
            if (regType(token) === D3DSPR_CONST) {
                const literal = defConstants.get(regNum(token));
                if (literal)
                    return "vec4<f32>(" + literal.map(v =>
                        Number.isFinite(v) ? v.toExponential() : "0.0")
                        .join(", ") + ")";
            }
            return registerExpr(token);
        };

        for (let offset = 0; offset < tokens.length;) {
            const token = tokens[offset] >>> 0;
            if (token === D3DSIO_END) return;
            const opcode = token & D3DSI_OPCODE_MASK;
            if (opcode === D3DSIO_COMMENT) {
                offset += 1 + ((token & D3DSI_COMMENTSIZE_MASK) >>>
                    D3DSI_COMMENTSIZE_SHIFT);
                continue;
            }
            const info = shaderOpcodeInfo(opcode, isPixelShader, minor);
            if (!info)
                throw new Error("unsupported D3D8 shader opcode 0x" +
                    opcode.toString(16));
            if (offset + 1 + info.operandWords > tokens.length)
                throw new Error("truncated D3D8 shader instruction 0x" +
                    opcode.toString(16));
            if (opcode !== D3DSIO_DEF && opcode !== D3DSIO_NOP &&
                    opcode !== D3DSIO_PHASE) {
                const dstToken = tokens[offset + 1] >>> 0;
                const sourceCount = info.operandWords - 1;
                const sources = [];
                for (let i = 0; i < sourceCount; i++) {
                    const srcToken = tokens[offset + 2 + i] >>> 0;
                    const base = constExpr(srcToken) + "." +
                        swizzleSuffix(srcSwizzleByte(srcToken));
                    sources.push(applySourceModifier(base,
                        srcModifierBits(srcToken)));
                }
                emitInstruction(opcode, dstToken, sources, tokens, offset);
            }
            offset += 1 + info.operandWords;
        }
        // Running off the end of the token array terminates the body just
        // like an explicit D3DSIO_END. The D8WG wire format carries an exact
        // instruction_token_count and the guest strips the trailing END
        // sentinel before sending (see d3d8_proxy.c), so the array bounds --
        // not a sentinel search -- are what actually delimit the stream.
        // Truncation is still caught, by the per-instruction bounds check
        // above.
    }

    function instructionExpression(opcode, sources) {
        const [s0, s1, s2] = sources;
        switch (opcode) {
        case D3DSIO_MOV: return s0;
        case D3DSIO_ADD: return "(" + s0 + " + " + s1 + ")";
        case D3DSIO_SUB: return "(" + s0 + " - " + s1 + ")";
        case D3DSIO_MUL: return "(" + s0 + " * " + s1 + ")";
        case D3DSIO_MAD: return "(" + s0 + " * " + s1 + " + " + s2 + ")";
        case D3DSIO_RCP: return "vec4<f32>(1.0 / (" + s0 + ").x)";
        case D3DSIO_RSQ:
            return "vec4<f32>(inverseSqrt(max(abs((" + s0 + ").x), 1e-12)))";
        case D3DSIO_DP3:
            return "vec4<f32>(dot((" + s0 + ").xyz, (" + s1 + ").xyz))";
        case D3DSIO_DP4: return "vec4<f32>(dot(" + s0 + ", " + s1 + "))";
        case D3DSIO_MIN: return "min(" + s0 + ", " + s1 + ")";
        case D3DSIO_MAX: return "max(" + s0 + ", " + s1 + ")";
        case D3DSIO_SLT:
            return "select(vec4<f32>(0.0), vec4<f32>(1.0), " + s0 + " < " + s1 + ")";
        case D3DSIO_SGE:
            return "select(vec4<f32>(0.0), vec4<f32>(1.0), " + s0 + " >= " + s1 + ")";
        case D3DSIO_EXP: case D3DSIO_EXPP:
            return "vec4<f32>(exp2((" + s0 + ").x))";
        case D3DSIO_LOG: case D3DSIO_LOGP:
            return "vec4<f32>(log2(max(abs((" + s0 + ").x), 1e-12)))";
        case D3DSIO_FRC: return "fract(" + s0 + ")";
        case D3DSIO_DST:
            return "vec4<f32>(1.0, (" + s0 + ").y * (" + s1 + ").y, (" +
                s0 + ").z, (" + s1 + ").w)";
        case D3DSIO_LIT: {
            const n = "(" + s0 + ")";
            return "vec4<f32>(1.0, max(" + n + ".x, 0.0), " +
                "select(0.0, pow(max(" + n + ".y, 0.0), clamp(" + n +
                ".w, -128.0, 128.0)), " + n + ".x > 0.0 && " + n +
                ".y > 0.0), 1.0)";
        }
        case D3DSIO_LRP: return "mix(" + s2 + ", " + s1 + ", " + s0 + ")";
        case D3DSIO_CND:
            return "select(" + s2 + ", " + s1 + ", " + s0 + " > vec4<f32>(0.5))";
        case D3DSIO_CMP:
            return "select(" + s2 + ", " + s1 + ", " + s0 + " >= vec4<f32>(0.0))";
        default:
            throw new Error("no WGSL expression for opcode 0x" +
                opcode.toString(16));
        }
    }

    function emitDestinationWrite(lines, destBaseExpr, dstToken, resultExpr) {
        const mask = dstWriteMaskBits(dstToken);
        if (!mask) return;
        resultExpr = applyDestModifiers(resultExpr, dstToken);
        const suffix = writeMaskSuffix(mask);
        if (suffix === "xyzw") {
            lines.push(destBaseExpr + " = " + resultExpr + ";");
        } else {
            lines.push(destBaseExpr + "." + suffix + " = (" + resultExpr +
                ")." + suffix + ";");
        }
    }

    // Parses a D3DVSD_* vertex declaration into a WebGPU vertex buffer
    // layout keyed by vertex-shader input register number. Per this
    // project's convention (matching the reference d3d8_caps_audit_test.c
    // audit_shader_pipeline() shader, which reads v0/v1 from a declaration
    // whose D3DVSD_REG entries use the D3DVSDE_POSITION=0/D3DVSDE_DIFFUSE=5
    // symbolic slots), a bound vertex shader's input registers are numbered
    // sequentially by the D3DVSD_REG entry's position in the declaration
    // stream, not by the raw D3DVSDE_* register field -- that field is a
    // fixed-function semantic hint the guest also uses for its own shadow
    // bookkeeping, but it is not the shader-visible register index. Only
    // D3DVSD_REG entries in stream 0 are honored -- D3DVSD_SKIP, multiple
    // streams, and the tessellator token type are outside Stage 6's scope
    // and rejected outright rather than silently ignored, so a declaration
    // that needs them fails shader creation instead of producing a shader
    // that reads garbage vertex data.
    function parseVertexDeclaration(tokens) {
        const attributes = [];
        const registers = new Map();
        let cursor = 0;
        let nextRegister = 0;
        for (let i = 0; i < tokens.length; i++) {
            const token = tokens[i] >>> 0;
            const type = (token >>> D3DVSD_TOKENTYPESHIFT) & 0x7;
            if (type !== D3DVSD_TOKEN_STREAMDATA)
                continue;
            if (token & D3DVSD_SKIPFLAG)
                throw new Error("D3DVSD_SKIP is not supported in Stage 6");
            const register = nextRegister++;
            const dataType = (token >>> D3DVSD_DATATYPESHIFT) & 0xF;
            const shapes = {
                0: { format: "float32", size: 4, wgslType: "f32", extend: 3 },
                1: { format: "float32x2", size: 8, wgslType: "vec2<f32>", extend: 2 },
                2: { format: "float32x3", size: 12, wgslType: "vec3<f32>", extend: 1 },
                3: { format: "float32x4", size: 16, wgslType: "vec4<f32>", extend: 0 },
                4: { format: "unorm8x4", size: 4, wgslType: "vec4<f32>", extend: 0 },
            };
            const shape = shapes[dataType];
            if (!shape)
                throw new Error("unsupported D3DVSD data type " + dataType +
                    " in Stage 6 vertex declaration");
            attributes.push({ shaderLocation: register, offset: cursor,
                format: shape.format });
            registers.set(register, shape);
            cursor += shape.size;
        }
        if (!attributes.length)
            throw new Error("vertex declaration has no D3DVSD_REG entries");
        return { attributes, registers, stride: cursor };
    }

    function vertexShaderWgsl(codeTokens, declaration) {
        const minor = codeTokens[0] & 0xFF;
        if (((codeTokens[0] >>> 16) & 0xFFFF) !== 0xFFFE || minor !== 1)
            throw new Error("unsupported vertex shader version token");
        const registerExpr = (token) => {
            const type = regType(token);
            const num = regNum(token);
            switch (type) {
            case D3DSPR_TEMP: return "r" + num;
            case D3DSPR_INPUT: {
                const shape = declaration.registers.get(num);
                if (!shape)
                    throw new Error("vertex shader reads undeclared input v" + num);
                if (shape.extend === 0) return "input.v" + num;
                const pad = ["1.0", "0.0, 1.0", "0.0, 0.0, 1.0"][shape.extend - 1];
                return "vec4<f32>(input.v" + num + ", " + pad + ")";
            }
            case D3DSPR_CONST:
                if (num >= D8WG_MAX_VS_CONSTANTS)
                    throw new Error("vertex shader constant c" + num +
                        " is out of range");
                return "constants.vs[" + num + "]";
            case D3DSPR_RASTOUT:
                if (num !== 0)
                    throw new Error("unsupported vertex shader oRastOut index " + num);
                return "output.position";
            case D3DSPR_ATTROUT:
                if (num > 1)
                    throw new Error("unsupported vertex shader oD index " + num);
                return num === 0 ? "output.diffuse" : "output.specular";
            case D3DSPR_TEXCRDOUT:
                if (num > 7)
                    throw new Error("unsupported vertex shader oT index " + num);
                return "output.texcoord" + num;
            default:
                throw new Error("unsupported vertex shader register type 0x" +
                    type.toString(16));
            }
        };
        const temps = new Set();
        const body = [];
        walkShaderBody(codeTokens.slice(1), false, 1, registerExpr,
            (opcode, dstToken, sources) => {
                if (regType(dstToken) === D3DSPR_TEMP)
                    temps.add("r" + regNum(dstToken));
                const expr = instructionExpression(opcode, sources);
                emitDestinationWrite(body, registerExpr(dstToken), dstToken,
                    expr);
            });
        const inputFields = [...declaration.registers.entries()]
            .sort((a, b) => a[0] - b[0])
            .map(([register, shape]) => "    @location(" + register + ") v" +
                register + ": " + shape.wgslType + ",").join("\n");
        const tempDecls = [...temps].map(name =>
            "    var " + name + ": vec4<f32>;").join("\n");
        return `
struct VSInput {
${inputFields}
};
struct VSOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) diffuse: vec4<f32>,
    @location(1) specular: vec4<f32>,
    @location(2) texcoord0: vec4<f32>,
    @location(3) texcoord1: vec4<f32>,
    @location(4) texcoord2: vec4<f32>,
    @location(5) texcoord3: vec4<f32>,
    @location(6) texcoord4: vec4<f32>,
    @location(7) texcoord5: vec4<f32>,
    @location(8) texcoord6: vec4<f32>,
    @location(9) texcoord7: vec4<f32>,
};
struct D8WGShaderConstants {
    vs: array<vec4<f32>, ${D8WG_MAX_VS_CONSTANTS}>,
    ps: array<vec4<f32>, ${D8WG_MAX_PS_CONSTANTS}>,
};
@group(0) @binding(0) var<uniform> constants: D8WGShaderConstants;
@vertex fn vs_main(input: VSInput) -> VSOutput {
    var output: VSOutput;
    output.position = vec4<f32>(0.0);
    output.diffuse = vec4<f32>(1.0);
    output.specular = vec4<f32>(0.0);
    output.texcoord0 = vec4<f32>(0.0);
    output.texcoord1 = vec4<f32>(0.0);
    output.texcoord2 = vec4<f32>(0.0);
    output.texcoord3 = vec4<f32>(0.0);
    output.texcoord4 = vec4<f32>(0.0);
    output.texcoord5 = vec4<f32>(0.0);
    output.texcoord6 = vec4<f32>(0.0);
    output.texcoord7 = vec4<f32>(0.0);
${tempDecls}
${body.join("\n")}
    return output;
}
`;
    }

    function pixelShaderWgsl(codeTokens) {
        const minor = codeTokens[0] & 0xFF;
        if (((codeTokens[0] >>> 16) & 0xFFFF) !== 0xFFFF || minor < 1 || minor > 4)
            throw new Error("unsupported pixel shader version token");
        const stageOf = (num) => {
            if (num > 1)
                throw new Error("texture stage t" + num +
                    " exceeds this backend's 2-stage binding limit");
            return num;
        };
        const registerExpr = (token) => {
            const type = regType(token);
            const num = regNum(token);
            switch (type) {
            case D3DSPR_TEMP: return "r" + num;
            case D3DSPR_INPUT:
                if (num > 1)
                    throw new Error("unsupported pixel shader v index " + num);
                return num === 0 ? "input.diffuse" : "input.specular";
            case D3DSPR_CONST:
                if (num >= D8WG_MAX_PS_CONSTANTS)
                    throw new Error("pixel shader constant c" + num +
                        " is out of range");
                return "constants.ps[" + num + "]";
            case D3DSPR_TEXTURE:
                stageOf(num);
                return "t" + num;
            default:
                throw new Error("unsupported pixel shader register type 0x" +
                    type.toString(16));
            }
        };
        const temps = new Set();
        const texRegisters = new Set();
        const body = [];
        walkShaderBody(codeTokens.slice(1), true, minor, registerExpr,
            (opcode, dstToken, sources, tokens, offset) => {
                const dstType = regType(dstToken);
                const dstNum = regNum(dstToken);
                if (dstType === D3DSPR_TEMP) temps.add("r" + dstNum);
                if (dstType === D3DSPR_TEXTURE) texRegisters.add(dstNum);
                if (opcode === D3DSIO_TEXCOORD) {
                    const stage = stageOf(dstNum);
                    texRegisters.add(dstNum);
                    body.push("    t" + dstNum + " = vec4<f32>(input.texcoord" +
                        stage + ".xy, 0.0, 1.0);");
                    return;
                }
                if (opcode === D3DSIO_TEX) {
                    texRegisters.add(dstNum);
                    if (minor >= 4) {
                        const srcToken = tokens[offset + 2] >>> 0;
                        const srcStage = stageOf(regNum(srcToken));
                        body.push("    r" + dstNum + " = textureSample(stage" +
                            srcStage + "Texture, stage" + srcStage +
                            "Sampler, t" + srcStage + ".xy);");
                    } else {
                        const stage = stageOf(dstNum);
                        body.push("    t" + dstNum + " = textureSample(stage" +
                            stage + "Texture, stage" + stage +
                            "Sampler, t" + stage + ".xy);");
                    }
                    return;
                }
                if (opcode === D3DSIO_TEXKILL) {
                    const stage = stageOf(dstNum);
                    texRegisters.add(dstNum);
                    body.push("    if (any(vec3<f32>(t" + stage +
                        ".x, t" + stage + ".y, t" + stage +
                        ".z) < vec3<f32>(0.0))) { discard; }");
                    return;
                }
                const expr = instructionExpression(opcode, sources);
                emitDestinationWrite(body, registerExpr(dstToken), dstToken,
                    expr);
            });
        // r0 is always the implicit ps.1.x output register (its final value
        // becomes the fragment color) whether or not the shader body ever
        // names it explicitly, so it must be declared exactly once even for
        // a (degenerate) shader that never writes r0.
        temps.add("r0");
        const tempDecls = [...temps].map(name =>
            "    var " + name + ": vec4<f32>;").join("\n");
        const texDecls = [...texRegisters].sort().map(num =>
            "    var t" + num + ": vec4<f32> = vec4<f32>(input.texcoord" +
            num + ".xy, 0.0, 1.0);").join("\n");
        return `
struct D8WGShaderConstants {
    vs: array<vec4<f32>, ${D8WG_MAX_VS_CONSTANTS}>,
    ps: array<vec4<f32>, ${D8WG_MAX_PS_CONSTANTS}>,
};
@group(0) @binding(0) var<uniform> constants: D8WGShaderConstants;
@group(0) @binding(1) var stage0Texture: texture_2d<f32>;
@group(0) @binding(2) var stage0Sampler: sampler;
@group(0) @binding(3) var stage1Texture: texture_2d<f32>;
@group(0) @binding(4) var stage1Sampler: sampler;
@fragment fn fs_main(input: VSOutput) -> @location(0) vec4<f32> {
${texDecls}
${tempDecls}
${body.join("\n")}
    return r0;
}
`;
    }

    // Combines a translated vertex shader and pixel shader into one WGSL
    // module sharing the VSOutput/D8WGShaderConstants definitions. Either
    // half may be null (no vertex/pixel shader bound uses the fixed-function
    // path instead -- see D3D8WebGPUExecutor.pipelineFor), but Stage 6 only
    // wires the combination where both are real shaders, matching the
    // Maple-relevant usage the doc anticipates (real VS + real PS together).
    function shaderPipelineWgsl(vertexResource, declaration, pixelResource) {
        const vs = vertexShaderWgsl(vertexResource.codeTokens, declaration);
        const ps = pixelShaderWgsl(pixelResource.codeTokens);
        // pixelShaderWgsl's `input: VSOutput` refers to the struct defined
        // in vs; strip its duplicate D8WGShaderConstants block so the
        // combined module only declares each binding once.
        const psBody = ps.replace(
            /struct D8WGShaderConstants[\s\S]*?@binding\(0\) var<uniform> constants: D8WGShaderConstants;\n/,
            "");
        return vs + psBody;
    }

    function identityMatrix() {
        return new Float32Array([
            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1,
        ]);
    }

    function freshDeviceState(handle, surface) {
        const renderStates = new Uint32Array(256);
        const textureStageStates = Array.from({ length: 8 },
            () => new Uint32Array(32));
        renderStates[7] = 1; // D3DRS_ZENABLE = D3DZB_TRUE
        renderStates[14] = 1; // D3DRS_ZWRITEENABLE
        renderStates[D3DRS_ZFUNC] = 4; // D3DCMP_LESSEQUAL
        renderStates[D3DRS_CULLMODE] = D3DCULL_CCW;
        renderStates[137] = 1; // D3DRS_LIGHTING
        renderStates[9] = 2; // D3DRS_SHADEMODE = GOURAUD
        renderStates[D3DRS_ALPHAFUNC] = 8; // ALWAYS
        renderStates[D3DRS_SRCBLEND] = 2; // ONE
        renderStates[D3DRS_DESTBLEND] = 1; // ZERO
        renderStates[D3DRS_BLENDOP] = 1; // ADD
        renderStates[D3DRS_TEXTUREFACTOR] = 0xFFFFFFFF;
        renderStates[D3DRS_COLORWRITEENABLE] = 0xF;
        renderStates[D3DRS_FOGEND] = 0x3F800000;
        renderStates[D3DRS_FOGDENSITY] = 0x3F800000;
        renderStates[D3DRS_STENCILFAIL] = 1; // KEEP
        renderStates[D3DRS_STENCILZFAIL] = 1;
        renderStates[D3DRS_STENCILPASS] = 1;
        renderStates[D3DRS_STENCILFUNC] = 8; // ALWAYS
        renderStates[D3DRS_STENCILMASK] = 0xFFFFFFFF;
        renderStates[D3DRS_STENCILWRITEMASK] = 0xFFFFFFFF;
        renderStates[D3DRS_COLORVERTEX] = 1;
        renderStates[D3DRS_LOCALVIEWER] = 1;
        renderStates[D3DRS_DIFFUSEMATERIALSOURCE] = 1; // COLOR1
        renderStates[D3DRS_SPECULARMATERIALSOURCE] = 2; // COLOR2
        renderStates[D3DRS_AMBIENTMATERIALSOURCE] = 0; // MATERIAL
        renderStates[D3DRS_EMISSIVEMATERIALSOURCE] = 0; // MATERIAL
        for (let stage = 0; stage < 8; stage++) {
            textureStageStates[stage][D3DTSS_COLOROP] =
                stage === 0 ? 4 : D3DTOP_DISABLE; // MODULATE
            textureStageStates[stage][D3DTSS_COLORARG1] = D3DTA_TEXTURE;
            textureStageStates[stage][D3DTSS_COLORARG2] = D3DTA_CURRENT;
            textureStageStates[stage][D3DTSS_ALPHAOP] =
                stage === 0 ? 2 : D3DTOP_DISABLE; // SELECTARG1
            textureStageStates[stage][D3DTSS_ALPHAARG1] = D3DTA_TEXTURE;
            textureStageStates[stage][D3DTSS_ALPHAARG2] = D3DTA_CURRENT;
            textureStageStates[stage][D3DTSS_TEXCOORDINDEX] = stage;
            textureStageStates[stage][D3DTSS_ADDRESSU] = 1; // WRAP
            textureStageStates[stage][D3DTSS_ADDRESSV] = 1;
            textureStageStates[stage][D3DTSS_MAGFILTER] = 1; // POINT
            textureStageStates[stage][D3DTSS_MINFILTER] = 1;
            textureStageStates[stage][D3DTSS_MIPFILTER] = 0;
            textureStageStates[stage][D3DTSS_MAXANISOTROPY] = 1;
            textureStageStates[stage][D3DTSS_RESULTARG] = D3DTA_CURRENT;
        }
        return {
            handle,
            surface,
            renderStates,
            textureStageStates,
            streams: Array.from({ length: 16 }, () => ({ handle: 0, stride: 0 })),
            indices: { handle: 0, baseVertex: 0 },
            textures: new Uint32Array(8),
            viewport: { x: 0, y: 0, width: surface.width,
                height: surface.height, minZ: 0, maxZ: 1 },
            transforms: {
                world: identityMatrix(),
                view: identityMatrix(),
                projection: identityMatrix(),
                textures: Array.from({ length: 8 }, identityMatrix),
            },
            material: {
                diffuse: [1, 1, 1, 1], ambient: [1, 1, 1, 1],
                specular: [0, 0, 0, 0], emissive: [0, 0, 0, 0], power: 0,
            },
            lights: Array.from({ length: 8 }, () => ({
                type: 0,
                diffuse: [0, 0, 0, 0], specular: [0, 0, 0, 0],
                ambient: [0, 0, 0, 0], position: [0, 0, 0],
                direction: [0, 0, 1], range: 0, falloff: 0,
                attenuation: [1, 0, 0], theta: 0, phi: 0, enabled: false,
            })),
            fvf: 0,
            inScene: false,
            renderTarget: { handle: 0, level: 0 },
            depthSurfaceEnabled: surface.autoDepthStencil,
            uniformSerial: 0,
            // Stage 7: the current uniform-ring slot for this device, and the
            // (serial, frame) it was packed for. -1 forces a repack.
            uniformSlotSerial: -1,
            uniformSlotFrame: -1,
            uniformSlotBuffer: null,
            uniformSlotOffset: 0,
            shaderConstantSlotSerial: -1,
            shaderConstantSlotFrame: -1,
            shaderConstantSlotBuffer: null,
            shaderConstantSlotOffset: 0,
            bindGroups: new Map(),
            // Stage 6: D3D8 shader model 1.x. vertexShader/pixelShader are
            // D8WG resource handles (0 = fixed-function / no pixel shader).
            vertexShader: 0,
            pixelShader: 0,
            vsConstants: new Float32Array(D8WG_MAX_VS_CONSTANTS * 4),
            psConstants: new Float32Array(D8WG_MAX_PS_CONSTANTS * 4),
            shaderConstantSerial: 0,
        };
    }

    class D3D8WebGPUExecutor {
        constructor(canvas, options) {
            if (!canvas) {
                throw new Error("D3D8 WebGPU canvas is required");
            }
            this.canvas = canvas;
            this.options = options || {};
            this.gpu = this.options.gpu ||
                (global.navigator && global.navigator.gpu);
            this.adapter = this.options.adapter || null;
            this.device = this.options.device || null;
            this.context = this.options.context || null;
            // Skipped when a device was supplied: that caller configures the
            // canvas itself. See the gpuHost note at the top of this file.
            this.host = this.options.host || (this.device ? null :
                ((host => host ? host.acquire(canvas, {
                    gpu: this.gpu,
                    adapter: this.adapter,
                    context: this.context,
                    format: this.options.format || null,
                    ...(this.options.hostOptions || {}),
                }) : null)(resolveGPUHost())));
            this.format = this.options.format || null;
            this.sessions = new Map();
            this.activeSession = null;
            this.maxSessions = Math.max(16, this.options.maxSessions || 128);
            this.sessionSerial = 0;
            // These aliases always point at the session of the current/most
            // recently executed batch. Keeping them preserves the public test
            // and diagnostics surface while all ownership is session-local.
            this.devices = new Map();
            this.resources = new Map();
            this.retiredDeviceHandles = new Set();
            this.retiredResourceHandles = new Set();
            this.pipelineCache = new Map();
            this.samplerCache = new Map();
            // Stage 6 shader pipelines use an explicit bind group layout
            // rather than layout:"auto" (see shaderBindGroupLayoutFor). Both
            // objects belong to the current GPUDevice and are dropped with the
            // pipeline/sampler caches when a device is lost.
            this.shaderBindGroupLayout = null;
            this.shaderPipelineLayout = null;
            this.maxPipelines = Math.max(32, this.options.maxPipelines || 512);
            this.maxSamplers = Math.max(8, this.options.maxSamplers || 64);
            this.maxBindGroups = Math.max(64,
                this.options.maxBindGroups || 1024);
            this.nextPipelineId = 1;
            this.fallbackTexture = null;
            this.fallbackView = null;
            this.transientBuffer = null;
            this.transientCapacity = Math.max(1024 * 1024,
                this.options.transientBufferBytes || TRANSIENT_BUFFER_BYTES);
            this.transientCursor = 0;
            // Stage 7: one persistent uniform ring per executor, suballocated
            // with dynamic offsets so a state change costs a ring write rather
            // than a new GPUBuffer plus a new bind group.
            this.uniformRing = null;
            this.uniformRingCapacity = Math.max(64 * 1024,
                this.options.uniformRingBytes || UNIFORM_RING_BYTES);
            this.uniformRingCursor = 0;
            // Reused packing scratch: the fixed-function uniform block is
            // rebuilt per distinct state, and allocating it per draw was a
            // measurable GC source.
            this.uniformScratch = new Float32Array(FIXED_UNIFORM_BYTES / 4);
            this.shaderConstantScratch =
                new Float32Array(SHADER_UNIFORM_BYTES / 4);
            this.fixedBindGroupLayout = null;
            this.fixedPipelineLayout = null;
            this.frameSerial = 0;
            this.frame = null;
            this.readyPromise = null;
            this.work = Promise.resolve();
            this.pendingSubmissions = 0;
            this.failed = null;
            this.warned = new Set();
            this.stats = {
                batches: 0,
                commands: 0,
                presents: 0,
                queueSubmits: 0,
                drawCalls: 0,
                indexedDrawCalls: 0,
                upDrawCalls: 0,
                fanConversions: 0,
                uploadBytes: 0,
                transientUploadBytes: 0,
                transientBufferCreations: 0,
                bufferOrphans: 0,
                pipelineCreations: 0,
                pipelineCacheEvictions: 0,
                uniformCacheEvictions: 0,
                // Stage 7 counters (doc 12.2). bindGroupCreations must reach
                // 0/frame in steady state; uniformRingOverflows staying at 0
                // means the ring is large enough for the workload.
                bindGroupCreations: 0,
                bindGroupHits: 0,
                pipelineHits: 0,
                uniformSlotReuses: 0,
                uniformUploadBytes: 0,
                uniformRingOverflows: 0,
                redundantStateWrites: 0,
                malformedBatches: 0,
                unsupportedCommands: 0,
                deviceRecoveries: 0,
                staleCommandsDropped: 0,
                rectangularClears: 0,
                deferredDestroys: 0,
            };
        }

        sessionKey(low, high) {
            return (high >>> 0).toString(16).padStart(8, "0") + ":" +
                (low >>> 0).toString(16).padStart(8, "0");
        }

        setActiveSession(session, finishForeignFrame) {
            if (finishForeignFrame && this.frame &&
                    this.frame.sessionKey !== session.key) {
                this.finishFrame(false);
            }
            this.activeSession = session;
            this.devices = session.devices;
            this.resources = session.resources;
            this.retiredDeviceHandles = session.retiredDeviceHandles;
            this.retiredResourceHandles = session.retiredResourceHandles;
            session.lastUsed = ++this.sessionSerial;
        }

        activateSession(low, high) {
            low >>>= 0;
            high >>>= 0;
            if (!low && !high)
                throw new Error("D8WG batch has an empty process session");
            const key = this.sessionKey(low, high);
            let session = this.sessions.get(key);
            if (!session) {
                session = {
                    key, low, high,
                    devices: new Map(),
                    resources: new Map(),
                    retiredDeviceHandles: new Set(),
                    retiredResourceHandles: new Set(),
                    helloSeen: false,
                    lastUsed: 0,
                };
                this.sessions.set(key, session);
            }
            this.setActiveSession(session, true);
            this.pruneSessions();
            return session;
        }

        pruneSessions() {
            if (this.sessions.size <= this.maxSessions) return;
            for (const [key, session] of this.sessions) {
                if (this.sessions.size <= this.maxSessions) break;
                if (session === this.activeSession || session.devices.size ||
                        session.resources.size) continue;
                this.sessions.delete(key);
            }
        }

        retireHandle(set, handle) {
            if (!handle) return;
            set.add(handle >>> 0);
            if (set.size > 8192)
                set.delete(set.values().next().value);
        }

        warnOnce(key, message, details) {
            if (this.warned.has(key)) return;
            this.warned.add(key);
            console.warn("[d3d8-webgpu] " + message, details || "");
        }

        initialize() {
            if (this.readyPromise) return this.readyPromise;
            this.readyPromise = (async () => {
                if (!this.device) {
                    if (!this.host) throw new Error("WebGPU is unavailable");
                    await this.host.initialize();
                    this.adapter = this.host.adapter;
                    this.device = this.host.device;
                    this.context = this.context || this.host.context;
                    this.format = this.format || this.host.format;
                }
                this.context = this.context ||
                    (this.canvas && typeof this.canvas.getContext === "function" ?
                        this.canvas.getContext("webgpu") : null);
                if (!this.context) throw new Error("could not acquire a WebGPU canvas context");
                this.format = this.format || (this.gpu &&
                    typeof this.gpu.getPreferredCanvasFormat === "function" ?
                    this.gpu.getPreferredCanvasFormat() : "bgra8unorm");
                this.configureContext();
                this.fallbackTexture = this.device.createTexture({
                    label: "D3D8 fallback white texture",
                    size: { width: 1, height: 1, depthOrArrayLayers: 1 },
                    format: "rgba8unorm",
                    usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
                });
                this.fallbackView = this.fallbackTexture.createView();
                this.device.queue.writeTexture({ texture: this.fallbackTexture },
                    new Uint8Array([255, 255, 255, 255]),
                    { bytesPerRow: 4, rowsPerImage: 1 },
                    { width: 1, height: 1, depthOrArrayLayers: 1 });
                this.transientBuffer = this.device.createBuffer({
                    label: "D3D8 transient upload ring",
                    size: this.transientCapacity,
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_INDEX |
                        BUFFER_USAGE_COPY_SRC | BUFFER_USAGE_COPY_DST,
                });
                this.uniformRing = this.device.createBuffer({
                    label: "D3D8 uniform ring",
                    size: this.uniformRingCapacity,
                    usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
                });
                this.uniformRing._d8wgRingId = ++uniformRingSerial;
                this.uniformRingCursor = 0;
                if (this.device.lost && typeof this.device.lost.then === "function") {
                    this.device.lost.then(info => {
                        this.scheduleDeviceRecovery(info);
                    });
                }
                return this;
            })().catch(error => {
                this.failed = error;
                console.error("[d3d8-webgpu] initialization failed", error);
                throw error;
            });
            return this.readyPromise;
        }

        configureContext() {
            // Reconfiguring is how this path has always followed a device
            // reset's new back-buffer size. When the host owns the device it
            // must also own the configuration, or this call would hand the
            // canvas to a device the other backends do not share.
            if (this.host) {
                this.host.configureCanvas();
                return;
            }
            this.context.configure({
                device: this.device,
                format: this.format,
                alphaMode: "opaque",
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_DST,
            });
        }

        submit(bytes, metadata) {
            const owned = bytes instanceof Uint8Array ? bytes.slice() :
                new Uint8Array(bytes || []);
            this.pendingSubmissions++;
            this.work = this.work.then(() => this.initialize())
                .then(() => this.executeBatch(owned, metadata || {}))
                .catch(error => {
                    this.failed = error;
                    console.error("[d3d8-webgpu] batch failed", error, metadata || {});
                }).finally(() => { this.pendingSubmissions--; });
            return this.work;
        }

        idle() {
            return this.work;
        }

        discardFrame() {
            if (!this.frame) return;
            this.endPass();
            for (const buffer of this.frame.transientBuffers)
                buffer.destroy();
            const deferredDestroy = this.frame.deferredDestroy;
            this.frame = null;
            // The discarded encoder no longer references these objects, but
            // an earlier submitted frame still might. Retire them behind the
            // queue completion fence rather than destroying them immediately.
            this.scheduleGPUDestruction(deferredDestroy);
        }

        scheduleGPUDestruction(objects) {
            const pending = Array.from(new Set((objects || []).filter(
                object => object && typeof object.destroy === "function")));
            if (!pending.length) return;
            const destroy = () => {
                for (const object of pending) object.destroy();
            };
            this.stats.deferredDestroys += pending.length;
            if (this.device && this.device.queue &&
                    typeof this.device.queue.onSubmittedWorkDone === "function") {
                this.device.queue.onSubmittedWorkDone().then(destroy, destroy);
            } else {
                destroy();
            }
        }

        retireGPUObjects(...objects) {
            const pending = objects.filter(object => object &&
                typeof object.destroy === "function");
            if (!pending.length) return;
            if (this.frame)
                this.frame.deferredDestroy.push(...pending);
            else
                this.scheduleGPUDestruction(pending);
        }

        async recoverDevice(replacementDevice, info) {
            this.discardFrame();
            const checkpoint = this.serializeState();
            if (this.fallbackTexture) this.fallbackTexture.destroy();
            if (this.transientBuffer) this.transientBuffer.destroy();
            if (this.uniformRing) this.uniformRing.destroy();
            this.fallbackTexture = null;
            this.fallbackView = null;
            this.transientBuffer = null;
            this.uniformRing = null;
            this.uniformRingCursor = 0;
            this.fixedBindGroupLayout = null;
            this.fixedPipelineLayout = null;
            // GPU pipelines and samplers are owned by the lost GPUDevice and
            // must never be reused by the replacement device, even when their
            // logical D3D8 cache keys are identical.
            this.pipelineCache.clear();
            this.samplerCache.clear();
            this.shaderBindGroupLayout = null;
            this.shaderPipelineLayout = null;
            this.device = replacementDevice || null;
            if (!replacementDevice) this.adapter = null;
            this.readyPromise = null;
            this.failed = null;
            await this.initialize();
            this.restoreStateInitialized(checkpoint);
            this.stats.deviceRecoveries++;
            if (typeof this.options.onDeviceRecovered === "function")
                this.options.onDeviceRecovered(info || {});
        }

        scheduleDeviceRecovery(info, replacementDevice) {
            if (this.destroyed || info && info.reason === "destroyed") return Promise.resolve();
            const message = info && info.message || "unknown reason";
            console.warn("[d3d8-webgpu] device lost; rebuilding resources", info);
            this.work = this.work.then(() =>
                this.recoverDevice(replacementDevice, info)).catch(error => {
                this.failed = new Error("WebGPU device recovery failed after " +
                    message + ": " + (error && error.message || error));
                console.error("[d3d8-webgpu] device recovery failed", error);
            });
            return this.work;
        }

        injectDeviceLoss(replacementDevice) {
            if (!replacementDevice)
                throw new Error("device-loss injection requires a replacement device");
            return this.scheduleDeviceRecovery({ reason: "injected",
                message: "test injection" }, replacementDevice);
        }

        parseSurface(bytes, offset) {
            const width = Math.max(1, u32(bytes, offset + 16));
            const height = Math.max(1, u32(bytes, offset + 20));
            return {
                sessionKey: this.activeSession.key,
                sessionIdLow: this.activeSession.low,
                sessionIdHigh: this.activeSession.high,
                hwnd: u32(bytes, offset + 4),
                x: i32(bytes, offset + 8),
                y: i32(bytes, offset + 12),
                width,
                height,
                displayWidth: width,
                displayHeight: height,
                visible: true,
                format: u32(bytes, offset + 24),
                windowed: !!u32(bytes, offset + 28),
                behaviorFlags: u32(bytes, offset + 32),
                autoDepthStencil: !!u32(bytes, offset + 36),
                autoDepthStencilFormat: u32(bytes, offset + 40),
            };
        }

        createSurfaceUniform(state) {
            // Surface size feeds the uniform block, so any cached ring slot is
            // stale. Bind groups do not embed the uniform contents (only the
            // ring buffer identity), but clearing them is cheap and keeps
            // resize behaviour obviously correct.
            state.uniformSlotSerial = -1;
            state.bindGroups.clear();
        }

        createDepthSurface(state) {
            this.retireGPUObjects(state.depthTexture);
            state.depthTexture = null;
            state.depthView = null;
            if (!state.surface.autoDepthStencil) return;
            state.depthTexture = this.device.createTexture({
                label: "D3D8 automatic depth-stencil " +
                    state.handle.toString(16),
                size: { width: state.surface.width,
                    height: state.surface.height, depthOrArrayLayers: 1 },
                sampleCount: 1,
                dimension: "2d",
                format: "depth24plus-stencil8",
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
            });
            state.depthView = state.depthTexture.createView();
        }

        // Suballocate `byteCount` from the uniform ring and return the buffer
        // plus a 256-byte-aligned dynamic offset. The cursor resets at frame
        // start; a frame that outruns the ring falls back to a dedicated
        // buffer retired with that frame, so in-flight data is never
        // overwritten before its command buffer is submitted.
        allocateUniformSlot(byteCount) {
            const size = alignUniform(byteCount);
            const offset = alignUniform(this.uniformRingCursor);
            if (this.uniformRing &&
                    size <= this.uniformRingCapacity - offset) {
                this.uniformRingCursor = offset + size;
                return { buffer: this.uniformRing, offset };
            }
            const overflow = this.device.createBuffer({
                label: "D3D8 uniform ring overflow",
                size,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            overflow._d8wgRingId = ++uniformRingSerial;
            if (this.frame) this.frame.transientBuffers.push(overflow);
            else this.retireGPUObjects(overflow);
            this.stats.uniformRingOverflows++;
            return { buffer: overflow, offset: 0 };
        }

        // Packs the fixed-function uniform block into a reusable scratch array
        // and parks it in the uniform ring. Reuses the previous slot when no
        // state that feeds the block has changed since the last draw of this
        // frame, so a run of draws sharing one state costs a single upload.
        uniformFor(state) {
            if (state.uniformSlotSerial === state.uniformSerial &&
                    state.uniformSlotFrame === this.frameSerial &&
                    state.uniformSlotBuffer) {
                this.stats.uniformSlotReuses++;
                return { buffer: state.uniformSlotBuffer,
                    offset: state.uniformSlotOffset };
            }
            const values = this.uniformScratch;
            const width = Math.max(1, state.surface.width);
            const height = Math.max(1, state.surface.height);
            const factorValue = state.renderStates[D3DRS_TEXTUREFACTOR] >>> 0;
            values[0] = width;
            values[1] = height;
            values[2] = 1 / width;
            values[3] = 1 / height;
            values[4] = ((factorValue >>> 16) & 0xFF) / 255;
            values[5] = ((factorValue >>> 8) & 0xFF) / 255;
            values[6] = (factorValue & 0xFF) / 255;
            values[7] = ((factorValue >>> 24) & 0xFF) / 255;
            values[8] = state.renderStates[D3DRS_ALPHAREF] & 255;
            values[9] = 0; values[10] = 0; values[11] = 0;
            values.set(state.transforms.world, 12);
            values.set(state.transforms.view, 28);
            values.set(state.transforms.projection, 44);
            const fogColorValue = state.renderStates[D3DRS_FOGCOLOR] >>> 0;
            values[60] = ((fogColorValue >>> 16) & 0xFF) / 255;
            values[61] = ((fogColorValue >>> 8) & 0xFF) / 255;
            values[62] = (fogColorValue & 0xFF) / 255;
            values[63] = ((fogColorValue >>> 24) & 0xFF) / 255;
            values[64] = dwordFloat(state.renderStates[D3DRS_FOGSTART]);
            values[65] = dwordFloat(state.renderStates[D3DRS_FOGEND]);
            values[66] = dwordFloat(state.renderStates[D3DRS_FOGDENSITY]);
            values[67] = 0;
            values.set(state.material.diffuse, 68);
            values.set(state.material.ambient, 72);
            values.set(state.material.specular, 76);
            values.set(state.material.emissive, 80);
            values[84] = state.material.power;
            values[85] = 0; values[86] = 0; values[87] = 0;
            const ambientValue = state.renderStates[D3DRS_AMBIENT] >>> 0;
            values[88] = ((ambientValue >>> 16) & 0xFF) / 255;
            values[89] = ((ambientValue >>> 8) & 0xFF) / 255;
            values[90] = (ambientValue & 0xFF) / 255;
            values[91] = ((ambientValue >>> 24) & 0xFF) / 255;
            for (let index = 0; index < 8; index++) {
                const light = state.lights[index];
                const offset = 92 + index * 28;
                values.set(light.diffuse, offset);
                values.set(light.specular, offset + 4);
                values.set(light.ambient, offset + 8);
                values[offset + 12] = light.position[0];
                values[offset + 13] = light.position[1];
                values[offset + 14] = light.position[2];
                values[offset + 15] = light.type;
                values[offset + 16] = light.direction[0];
                values[offset + 17] = light.direction[1];
                values[offset + 18] = light.direction[2];
                values[offset + 19] = light.range;
                values[offset + 20] = light.attenuation[0];
                values[offset + 21] = light.attenuation[1];
                values[offset + 22] = light.attenuation[2];
                values[offset + 23] = light.falloff;
                values[offset + 24] = light.theta;
                values[offset + 25] = light.phi;
                values[offset + 26] = light.enabled ? 1 : 0;
                values[offset + 27] = 0;
            }
            values.set(state.transforms.textures[0], 316);
            values.set(state.transforms.textures[1], 332);
            const slot = this.allocateUniformSlot(FIXED_UNIFORM_BYTES);
            this.device.queue.writeBuffer(slot.buffer, slot.offset, values);
            this.stats.uniformUploadBytes += FIXED_UNIFORM_BYTES;
            state.uniformSlotSerial = state.uniformSerial;
            state.uniformSlotFrame = this.frameSerial;
            state.uniformSlotBuffer = slot.buffer;
            state.uniformSlotOffset = slot.offset;
            return slot;
        }

        createOrResetDevice(bytes, payloadOffset, reset, surfaceReason) {
            const handle = u32(bytes, payloadOffset);
            const surface = this.parseSurface(bytes, payloadOffset);
            let state = this.devices.get(handle);
            if (!state || !reset) {
                if (state) this.retireGPUObjects(state.depthTexture, state.backBuffer);
                state = freshDeviceState(handle, surface);
                this.devices.set(handle, state);
            } else {
                state.surface = surface;
                state.inScene = false;
                state.viewport = { x: 0, y: 0, width: surface.width,
                    height: surface.height, minZ: 0, maxZ: 1 };
            }
            this.canvas.width = surface.width;
            this.canvas.height = surface.height;
            this.configureContext();
            this.createSurfaceUniform(state);
            this.createDepthSurface(state);
            this.retireGPUObjects(state.backBuffer);
            state.backBuffer = this.device.createTexture({
                label: "D3D8 retained back buffer",
                size: { width: surface.width, height: surface.height },
                format: this.format,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            state.backBufferInitialized = false;
            if (typeof this.options.onSurface === "function") {
                this.options.onSurface(surface,
                    surfaceReason || (reset ? "reset" : "create"));
            }
        }

        resetDevice(bytes, payloadOffset) {
            const oldHandle = u32(bytes, payloadOffset);
            const newHandle = u32(bytes, payloadOffset + 4);
            if (!oldHandle || !newHandle || oldHandle === newHandle)
                throw new Error("RESET has an invalid device epoch");
            if (!this.devices.has(oldHandle))
                throw new Error("RESET references an unknown old device");
            this.destroyResource(oldHandle);
            this.createOrResetDevice(bytes, payloadOffset + 4, false, "reset");
        }

        updateSurface(bytes, payloadOffset, state, reason) {
            const width = u32(bytes, payloadOffset + 16);
            const height = u32(bytes, payloadOffset + 20);
            const visible = width !== 0 && height !== 0;
            const hwnd = u32(bytes, payloadOffset + 4);
            const x = i32(bytes, payloadOffset + 8);
            const y = i32(bytes, payloadOffset + 12);
            const changed = state.surface.hwnd !== hwnd ||
                state.surface.x !== x || state.surface.y !== y ||
                state.surface.visible !== visible ||
                (visible && (state.surface.displayWidth !== width ||
                    state.surface.displayHeight !== height));
            state.surface = {
                ...state.surface,
                hwnd,
                x,
                y,
                displayWidth: visible ? width : state.surface.displayWidth,
                displayHeight: visible ? height : state.surface.displayHeight,
                visible,
            };
            if (changed && typeof this.options.onSurface === "function") {
                this.options.onSurface(state.surface, visible ? reason : "hide");
            }
            return visible;
        }

        endPass() {
            if (this.frame && this.frame.pass) {
                this.frame.pass.end();
                this.frame.pass = null;
            }
        }

        mirrorRenderTargetClear(state, color, rectangles) {
            const handle = state.renderTarget.handle >>> 0;
            if (!handle) return;
            const resource = this.resources.get(handle);
            const level = resource && resource.shadowLevels[
                state.renderTarget.level >>> 0];
            if (!resource || resource.kind !== RESOURCE_TEXTURE_2D || !level ||
                    (resource.format !== D3DFMT_A8R8G8B8 &&
                     resource.format !== D3DFMT_X8R8G8B8)) return;
            const b = color & 0xFF;
            const g = (color >>> 8) & 0xFF;
            const r = (color >>> 16) & 0xFF;
            const a = resource.format === D3DFMT_A8R8G8B8 ?
                (color >>> 24) & 0xFF : 0xFF;
            const areas = rectangles && rectangles.length ? rectangles : [{
                x1: 0, y1: 0, x2: level.width, y2: level.height,
            }];
            for (const area of areas) {
                const x1 = Math.max(0, Math.min(level.width, area.x1 | 0));
                const y1 = Math.max(0, Math.min(level.height, area.y1 | 0));
                const x2 = Math.max(x1, Math.min(level.width, area.x2 | 0));
                const y2 = Math.max(y1, Math.min(level.height, area.y2 | 0));
                for (let y = y1; y < y2; y++) {
                    let offset = y * level.rowPitch + x1 * 4;
                    for (let x = x1; x < x2; x++, offset += 4) {
                        level.data[offset] = b;
                        level.data[offset + 1] = g;
                        level.data[offset + 2] = r;
                        level.data[offset + 3] = a;
                    }
                }
            }
        }

        clearPipelineFor(state, flags) {
            const hasDepth = !!(state.depthView && state.depthSurfaceEnabled &&
                !state.renderTarget.handle);
            const targetFormat = state.renderTarget.handle ?
                "rgba8unorm" : this.format;
            const effectiveFlags = (flags & D3DCLEAR_TARGET) |
                (hasDepth ? flags & (D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL) : 0);
            const key = ["rect-clear", targetFormat, hasDepth ? 1 : 0,
                effectiveFlags].join(":");
            let pipeline = this.pipelineCache.get(key);
            if (pipeline) {
                this.pipelineCache.delete(key);
                this.pipelineCache.set(key, pipeline);
                return pipeline;
            }
            const module = this.device.createShaderModule({
                label: "D3D8 rectangular Clear shader",
                code: `
struct ClearData {
    color: vec4<f32>,
    depth: vec4<f32>,
};
@group(0) @binding(0) var<uniform> clearData: ClearData;
struct VertexOutput {
    @builtin(position) position: vec4<f32>,
};
@vertex fn vs_main(@builtin(vertex_index) index: u32) -> VertexOutput {
    var positions = array<vec2<f32>, 3>(
        vec2<f32>(-1.0, -1.0),
        vec2<f32>( 3.0, -1.0),
        vec2<f32>(-1.0,  3.0));
    var output: VertexOutput;
    output.position = vec4<f32>(positions[index], clearData.depth.x, 1.0);
    return output;
}
@fragment fn fs_main() -> @location(0) vec4<f32> {
    return clearData.color;
}`,
            });
            pipeline = this.device.createRenderPipeline({
                label: "D3D8 rectangular Clear pipeline " + key,
                layout: "auto",
                vertex: { module, entryPoint: "vs_main" },
                fragment: {
                    module,
                    entryPoint: "fs_main",
                    targets: [{
                        format: targetFormat,
                        writeMask: effectiveFlags & D3DCLEAR_TARGET ? 0xF : 0,
                    }],
                },
                primitive: { topology: "triangle-list", cullMode: "none" },
                ...(hasDepth ? { depthStencil: {
                    format: "depth24plus-stencil8",
                    depthWriteEnabled: !!(effectiveFlags & D3DCLEAR_ZBUFFER),
                    depthCompare: "always",
                    stencilFront: effectiveFlags & D3DCLEAR_STENCIL ? {
                        compare: "always", failOp: "keep",
                        depthFailOp: "keep", passOp: "replace",
                    } : {},
                    stencilBack: effectiveFlags & D3DCLEAR_STENCIL ? {
                        compare: "always", failOp: "keep",
                        depthFailOp: "keep", passOp: "replace",
                    } : {},
                    stencilReadMask: 0xFF,
                    stencilWriteMask: effectiveFlags & D3DCLEAR_STENCIL ?
                        0xFF : 0,
                } } : {}),
            });
            pipeline._d8wgId = this.nextPipelineId++;
            if (this.pipelineCache.size >= this.maxPipelines) {
                this.pipelineCache.delete(this.pipelineCache.keys().next().value);
                this.stats.pipelineCacheEvictions++;
            }
            this.pipelineCache.set(key, pipeline);
            this.stats.pipelineCreations++;
            return pipeline;
        }

        clearRectangles(state, flags, color, depth, stencil, rectangles) {
            const target = state.renderTarget.handle ?
                this.resources.get(state.renderTarget.handle) : null;
            const level = target ? state.renderTarget.level >>> 0 : 0;
            const width = target ? Math.max(1, target.width >>> level) :
                state.surface.width;
            const height = target ? Math.max(1, target.height >>> level) :
                state.surface.height;
            const hasDepth = !!(state.depthView && state.depthSurfaceEnabled &&
                !state.renderTarget.handle);
            if (!(flags & D3DCLEAR_TARGET) && !hasDepth) return;

            const data = new Uint8Array(32);
            const values = new DataView(data.buffer);
            const clearColor = d3dColor(color);
            values.setFloat32(0, clearColor.r, true);
            values.setFloat32(4, clearColor.g, true);
            values.setFloat32(8, clearColor.b, true);
            values.setFloat32(12, clearColor.a, true);
            values.setFloat32(16, Math.max(0, Math.min(1, depth)), true);
            const pass = this.ensureFrame(state);
            const uniform = this.device.createBuffer({
                label: "D3D8 rectangular Clear uniforms",
                size: data.byteLength,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(uniform, 0, data);
            this.frame.transientBuffers.push(uniform);
            const pipeline = this.clearPipelineFor(state, flags);
            const group = this.device.createBindGroup({
                layout: pipeline.getBindGroupLayout(0),
                entries: [{ binding: 0, resource: {
                    buffer: uniform,
                    offset: 0,
                    size: data.byteLength,
                } }],
            });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, group);
            if (hasDepth && flags & D3DCLEAR_STENCIL)
                pass.setStencilReference(stencil & 0xFF);
            for (const area of rectangles) {
                const x1 = Math.max(0, Math.min(width, area.x1 | 0));
                const y1 = Math.max(0, Math.min(height, area.y1 | 0));
                const x2 = Math.max(x1, Math.min(width, area.x2 | 0));
                const y2 = Math.max(y1, Math.min(height, area.y2 | 0));
                if (x2 === x1 || y2 === y1) continue;
                pass.setScissorRect(x1, y1, x2 - x1, y2 - y1);
                pass.draw(3, 1, 0, 0);
                this.stats.rectangularClears++;
            }
        }

        ensureFrame(state, clearOptions) {
            const targetHandle = state.renderTarget.handle >>> 0;
            if (this.frame && (this.frame.sessionKey !== this.activeSession.key ||
                    this.frame.deviceHandle !== state.handle ||
                    this.frame.targetHandle !== targetHandle)) {
                this.finishFrame(false);
            }
            if (!this.frame) {
                const encoder = this.device.createCommandEncoder({
                    label: "D3D8 frame",
                });
                const target = targetHandle ? this.resources.get(targetHandle) : null;
                if (targetHandle && (!target ||
                        target.kind !== RESOURCE_TEXTURE_2D ||
                        !(target.usage & D3DUSAGE_RENDERTARGET))) {
                    throw new Error("active render target is stale");
                }
                const view = target ? target.gpuTexture.createView({
                    baseMipLevel: state.renderTarget.level,
                    mipLevelCount: 1,
                }) : state.backBuffer.createView();
                this.frame = {
                    sessionKey: this.activeSession.key,
                    deviceHandle: state.handle,
                    targetHandle,
                    state,
                    encoder,
                    view,
                    pass: null,
                    fresh: !target && !state.backBufferInitialized,
                    transientBuffers: [],
                    deferredDestroy: [],
                };
                this.transientCursor = 0;
                // Both rings restart each frame; the previous frame's slots are
                // already encoded into a submitted command buffer.
                this.uniformRingCursor = 0;
                this.frameSerial++;
            }
            if (clearOptions !== undefined) this.endPass();
            if (!this.frame.pass) {
                const clear = clearOptions || {};
                const fresh = this.frame.fresh;
                const descriptor = {
                    label: "D3D8 color pass",
                    colorAttachments: [{
                        view: this.frame.view,
                        clearValue: clear.color || { r: 0, g: 0, b: 0, a: 1 },
                        loadOp: fresh || clear.color ? "clear" : "load",
                        storeOp: "store",
                    }],
                };
                if (state.depthView && state.depthSurfaceEnabled &&
                        !targetHandle) {
                    descriptor.depthStencilAttachment = {
                        view: state.depthView,
                        depthClearValue: clear.depth === undefined ? 1 :
                            Math.max(0, Math.min(1, clear.depth)),
                        depthLoadOp: fresh || clear.depth !== undefined ?
                            "clear" : "load",
                        depthStoreOp: "store",
                        stencilClearValue: clear.stencil === undefined ? 0 :
                            clear.stencil & 0xFF,
                        stencilLoadOp: fresh || clear.stencil !== undefined ?
                            "clear" : "load",
                        stencilStoreOp: "store",
                    };
                }
                this.frame.pass = this.frame.encoder.beginRenderPass(descriptor);
                this.frame.fresh = false;
            }
            return this.frame.pass;
        }

        finishFrame(notify) {
            if (!this.frame) return false;
            const state = this.frame.state;
            const transientBuffers = this.frame.transientBuffers;
            const deferredDestroy = this.frame.deferredDestroy;
            this.endPass();
            if (!this.frame.targetHandle) state.backBufferInitialized = true;
            if (notify) {
                // The canvas texture expires at the browser's frame boundary.
                // Keep partial frames in owned storage, including across save.
                if (this.canvas.width !== state.surface.width) this.canvas.width = state.surface.width;
                if (this.canvas.height !== state.surface.height) this.canvas.height = state.surface.height;
                const target = this.context.getCurrentTexture();
                this.frame.encoder.copyTextureToTexture({ texture: state.backBuffer },
                    { texture: target }, { width: state.surface.width,
                        height: state.surface.height, depthOrArrayLayers: 1 });
            }
            this.device.queue.submit([this.frame.encoder.finish()]);
            this.stats.queueSubmits++;
            this.frame = null;
            this.scheduleGPUDestruction(transientBuffers.concat(
                deferredDestroy));
            if (notify) {
                this.stats.presents++;
                if (typeof this.options.onPresent === "function") {
                    this.options.onPresent(state.surface, this.getStats());
                }
            }
            return true;
        }

        destroyResource(handle) {
            const resource = this.resources.get(handle);
            if (resource) {
                this.retireHandle(this.retiredResourceHandles, handle);
                this.retireGPUObjects(resource.gpuBuffer,
                    resource.gpuTexture);
                this.resources.delete(handle);
                if (resource.kind === RESOURCE_TEXTURE_2D) {
                    for (const device of this.devices.values())
                        device.bindGroups.clear();
                }
            }
            const state = this.devices.get(handle);
            if (state) {
                this.retireHandle(this.retiredDeviceHandles, handle);
                if (this.frame && this.frame.deviceHandle === handle) {
                    this.discardFrame();
                }
                this.retireGPUObjects(state.depthTexture, state.backBuffer);
                for (const [resourceHandle, child] of this.resources) {
                    if (child.deviceHandle !== handle) continue;
                    this.retireHandle(this.retiredResourceHandles,
                        resourceHandle);
                    this.retireGPUObjects(child.gpuBuffer,
                        child.gpuTexture);
                    this.resources.delete(resourceHandle);
                }
                this.devices.delete(handle);
                if (typeof this.options.onDestroy === "function") {
                    this.options.onDestroy(state.surface, "device");
                }
            }
        }

        pipelineFor(state, topology, stride, indexFormat) {
            // A real vertex shader handle always carries bit 0 (see
            // D8WG_SHADER_HANDLE_BASE); state.fvf stays whatever it was last
            // set to (unused) once a real shader is bound.
            if (state.vertexShader & 1)
                return this.shaderPipelineFor(state, topology, stride,
                    indexFormat);
            const vertexLayout = parseFVF(state.fvf >>> 0, stride >>> 0);
            if (!vertexLayout) return null;
            const cull = state.renderStates[D3DRS_CULLMODE] >>> 0;
            const blend = state.renderStates[D3DRS_ALPHABLENDENABLE] >>> 0;
            const stripIndexFormat = topology.endsWith("-strip") ?
                indexFormat : undefined;
            const stageKey = [];
            const shaderStates = [D3DTSS_COLOROP, D3DTSS_COLORARG1,
                D3DTSS_COLORARG2, D3DTSS_ALPHAOP, D3DTSS_ALPHAARG1,
                D3DTSS_ALPHAARG2, D3DTSS_TEXCOORDINDEX,
                D3DTSS_COLORARG0, D3DTSS_ALPHAARG0, D3DTSS_RESULTARG,
                D3DTSS_TEXTURETRANSFORMFLAGS];
            for (let stage = 0; stage < 2; stage++) {
                for (const selector of shaderStates)
                    stageKey.push(state.textureStageStates[stage][selector] >>> 0);
            }
            const targetFormat = state.renderTarget.handle ?
                "rgba8unorm" : this.format;
            const key = [targetFormat, topology, stripIndexFormat || "none",
                state.fvf >>> 0, stride >>> 0,
                cull, blend,
                state.renderStates[D3DRS_SRCBLEND] >>> 0,
                state.renderStates[D3DRS_DESTBLEND] >>> 0,
                state.renderStates[D3DRS_BLENDOP] >>> 0,
                state.renderStates[D3DRS_SHADEMODE] >>> 0,
                state.renderStates[D3DRS_ALPHATESTENABLE] >>> 0,
                state.renderStates[D3DRS_ALPHAFUNC] >>> 0,
                state.renderStates[D3DRS_SPECULARENABLE] >>> 0,
                state.renderStates[D3DRS_FOGENABLE] >>> 0,
                state.renderStates[D3DRS_FOGTABLEMODE] >>> 0,
                state.renderStates[D3DRS_FOGVERTEXMODE] >>> 0,
                state.renderStates[D3DRS_RANGEFOGENABLE] >>> 0,
                state.renderStates[D3DRS_LIGHTING] >>> 0,
                state.renderStates[D3DRS_COLORVERTEX] >>> 0,
                state.renderStates[D3DRS_LOCALVIEWER] >>> 0,
                state.renderStates[D3DRS_NORMALIZENORMALS] >>> 0,
                state.renderStates[D3DRS_DIFFUSEMATERIALSOURCE] >>> 0,
                state.renderStates[D3DRS_SPECULARMATERIALSOURCE] >>> 0,
                state.renderStates[D3DRS_AMBIENTMATERIALSOURCE] >>> 0,
                state.renderStates[D3DRS_EMISSIVEMATERIALSOURCE] >>> 0,
                state.renderStates[D3DRS_COLORWRITEENABLE] >>> 0,
                state.depthView && state.depthSurfaceEnabled &&
                    !state.renderTarget.handle ? 1 : 0,
                state.renderStates[D3DRS_ZENABLE] >>> 0,
                state.renderStates[D3DRS_ZWRITEENABLE] >>> 0,
                state.renderStates[D3DRS_ZFUNC] >>> 0,
                state.renderStates[D3DRS_ZBIAS] >>> 0,
                state.renderStates[D3DRS_STENCILENABLE] >>> 0,
                state.renderStates[D3DRS_STENCILFAIL] >>> 0,
                state.renderStates[D3DRS_STENCILZFAIL] >>> 0,
                state.renderStates[D3DRS_STENCILPASS] >>> 0,
                state.renderStates[D3DRS_STENCILFUNC] >>> 0,
                state.renderStates[D3DRS_STENCILMASK] >>> 0,
                state.renderStates[D3DRS_STENCILWRITEMASK] >>> 0,
                ...stageKey].join(":");
            let pipeline = this.pipelineCache.get(key);
            if (pipeline) {
                this.pipelineCache.delete(key);
                this.pipelineCache.set(key, pipeline);
                return pipeline;
            }
            const shaderModule = this.device.createShaderModule({
                label: "D3D8 fixed-function shader " + this.nextPipelineId,
                code: fixedFunctionShader(state, vertexLayout),
            });
            pipeline = this.device.createRenderPipeline({
                label: "D3D8 fixed pipeline " + key,
                layout: (this.fixedBindGroupLayoutFor(),
                    this.fixedPipelineLayout),
                vertex: {
                    module: shaderModule,
                    entryPoint: "vs_main",
                    buffers: [{
                        arrayStride: stride,
                        stepMode: "vertex",
                        attributes: vertexLayout.attributes,
                    }],
                },
                fragment: {
                    module: shaderModule,
                    entryPoint: "fs_main",
                    targets: [{
                        format: targetFormat,
                        ...(blend ? { blend: blendState(state) } : {}),
                        writeMask: state.renderStates[D3DRS_COLORWRITEENABLE] & 0xF,
                    }],
                },
                primitive: {
                    topology,
                    ...(stripIndexFormat ?
                        { stripIndexFormat } : {}),
                    cullMode: cull === D3DCULL_NONE ? "none" : "back",
                    // The screen-space Y conversion flips winding.
                    frontFace: cull === D3DCULL_CCW ? "cw" : "ccw",
                },
                ...(state.depthView && state.depthSurfaceEnabled &&
                        !state.renderTarget.handle ? { depthStencil: {
                    format: "depth24plus-stencil8",
                    depthWriteEnabled: !!state.renderStates[D3DRS_ZENABLE] &&
                        !!state.renderStates[D3DRS_ZWRITEENABLE],
                    depthCompare: state.renderStates[D3DRS_ZENABLE] ?
                        compareFunction(state.renderStates[D3DRS_ZFUNC]) :
                        "always",
                    stencilFront: state.renderStates[D3DRS_STENCILENABLE] ? {
                        compare: compareFunction(
                            state.renderStates[D3DRS_STENCILFUNC]),
                        failOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILFAIL]),
                        depthFailOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILZFAIL]),
                        passOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILPASS]),
                    } : {},
                    stencilBack: state.renderStates[D3DRS_STENCILENABLE] ? {
                        compare: compareFunction(
                            state.renderStates[D3DRS_STENCILFUNC]),
                        failOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILFAIL]),
                        depthFailOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILZFAIL]),
                        passOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILPASS]),
                    } : {},
                    stencilReadMask: state.renderStates[D3DRS_STENCILENABLE] ?
                        state.renderStates[D3DRS_STENCILMASK] >>> 0 : 0,
                    stencilWriteMask: state.renderStates[D3DRS_STENCILENABLE] ?
                        state.renderStates[D3DRS_STENCILWRITEMASK] >>> 0 : 0,
                    depthBias: -Math.min(16,
                        state.renderStates[D3DRS_ZBIAS] >>> 0),
                } } : {}),
            });
            pipeline._d8wgId = this.nextPipelineId++;
            if (this.pipelineCache.size >= this.maxPipelines) {
                this.pipelineCache.delete(this.pipelineCache.keys().next().value);
                this.stats.pipelineCacheEvictions++;
            }
            this.pipelineCache.set(key, pipeline);
            this.stats.pipelineCreations++;
            return pipeline;
        }

        // Stage 6: D3D8 shader model 1.x pipeline path. Reuses the same
        // pipelineCache Map as the fixed-function path (pipelineFor above) --
        // the key's leading tag keeps the two namespaces from ever
        // colliding -- and the same cull/blend/depth/stencil/color-write
        // render-state fields, since those aren't shader-specific. Only the
        // vertex-layout/fragment-combiner half of the key differs: real
        // shader mode keys on the bound (vertexShader, pixelShader) handle
        // pair instead of (fvf, texture-stage-state). Handles are never
        // reused within a session (see allocate_shader_handle in
        // d3d8_proxy.c), so the raw handle number is already a stable cache
        // key with no separate generation counter needed.
        // Stage 6 shader pipelines cannot use layout:"auto". WebGPU derives an
        // automatic layout from the resources a shader *statically uses*, and
        // a translated SM1.x shader may legitimately use none of them -- a
        // passthrough `mov oPos, v0 / mov oD0, v1` reads no constant bank and
        // samples no texture, so the derived group(0) layout comes back empty
        // and every CreateBindGroup against it fails validation. (The
        // fixed-function shader never hits this because it unconditionally
        // samples both stage textures and reads surface.texture_factor.)
        // Declaring the layout explicitly keeps all five bindings present
        // regardless of shader content; WebGPU permits an explicit layout to
        // contain bindings the shader does not reference.
        // Builds the five-entry layout shared by both draw paths. binding 0 is
        // a dynamic-offset uniform so one persistent ring buffer can back
        // every state variant (Stage 7): the bind group then depends only on
        // the bound textures and samplers, not on the uniform contents, which
        // is what keeps steady-state bind group creation at zero.
        buildBindGroupLayout(label, minBindingSize) {
            const VERTEX = 1;
            const FRAGMENT = 2;
            return this.device.createBindGroupLayout({
                label,
                entries: [
                    { binding: 0, visibility: VERTEX | FRAGMENT,
                        buffer: { type: "uniform", hasDynamicOffset: true,
                            minBindingSize } },
                    { binding: 1, visibility: FRAGMENT,
                        texture: { sampleType: "float", viewDimension: "2d" } },
                    { binding: 2, visibility: FRAGMENT,
                        sampler: { type: "filtering" } },
                    { binding: 3, visibility: FRAGMENT,
                        texture: { sampleType: "float", viewDimension: "2d" } },
                    { binding: 4, visibility: FRAGMENT,
                        sampler: { type: "filtering" } },
                ],
            });
        }

        fixedBindGroupLayoutFor() {
            if (this.fixedBindGroupLayout) return this.fixedBindGroupLayout;
            this.fixedBindGroupLayout = this.buildBindGroupLayout(
                "D3D8 fixed-function bind group layout", FIXED_UNIFORM_BYTES);
            this.fixedPipelineLayout = this.device.createPipelineLayout({
                label: "D3D8 fixed-function pipeline layout",
                bindGroupLayouts: [this.fixedBindGroupLayout],
            });
            return this.fixedBindGroupLayout;
        }

        shaderBindGroupLayoutFor() {
            if (this.shaderBindGroupLayout) return this.shaderBindGroupLayout;
            this.shaderBindGroupLayout = this.buildBindGroupLayout(
                "D3D8 shader bind group layout", SHADER_UNIFORM_BYTES);
            this.shaderPipelineLayout = this.device.createPipelineLayout({
                label: "D3D8 shader pipeline layout",
                bindGroupLayouts: [this.shaderBindGroupLayout],
            });
            return this.shaderBindGroupLayout;
        }

        shaderPipelineFor(state, topology, stride, indexFormat) {
            const vertexResource = this.resources.get(state.vertexShader);
            const pixelResource = state.pixelShader &&
                this.resources.get(state.pixelShader);
            if (!vertexResource || vertexResource.kind !== RESOURCE_VERTEX_SHADER)
                throw new Error("draw with an unresolved vertex shader handle");
            if (!pixelResource || pixelResource.kind !== RESOURCE_PIXEL_SHADER)
                throw new Error("draw with an unresolved pixel shader handle");
            const declaration = vertexResource.declaration;
            if (stride < declaration.stride)
                throw new Error("vertex buffer stride is smaller than the " +
                    "bound vertex shader's declaration requires");
            const cull = state.renderStates[D3DRS_CULLMODE] >>> 0;
            const blend = state.renderStates[D3DRS_ALPHABLENDENABLE] >>> 0;
            const stripIndexFormat = topology.endsWith("-strip") ?
                indexFormat : undefined;
            const targetFormat = state.renderTarget.handle ?
                "rgba8unorm" : this.format;
            const key = ["shader", state.vertexShader, state.pixelShader,
                targetFormat, topology, stripIndexFormat || "none",
                stride >>> 0, cull, blend,
                state.renderStates[D3DRS_SRCBLEND] >>> 0,
                state.renderStates[D3DRS_DESTBLEND] >>> 0,
                state.renderStates[D3DRS_BLENDOP] >>> 0,
                state.renderStates[D3DRS_COLORWRITEENABLE] >>> 0,
                state.depthView && state.depthSurfaceEnabled &&
                    !state.renderTarget.handle ? 1 : 0,
                state.renderStates[D3DRS_ZENABLE] >>> 0,
                state.renderStates[D3DRS_ZWRITEENABLE] >>> 0,
                state.renderStates[D3DRS_ZFUNC] >>> 0,
                state.renderStates[D3DRS_ZBIAS] >>> 0,
                state.renderStates[D3DRS_STENCILENABLE] >>> 0,
                state.renderStates[D3DRS_STENCILFAIL] >>> 0,
                state.renderStates[D3DRS_STENCILZFAIL] >>> 0,
                state.renderStates[D3DRS_STENCILPASS] >>> 0,
                state.renderStates[D3DRS_STENCILFUNC] >>> 0,
                state.renderStates[D3DRS_STENCILMASK] >>> 0,
                state.renderStates[D3DRS_STENCILWRITEMASK] >>> 0].join(":");
            let pipeline = this.pipelineCache.get(key);
            if (pipeline) {
                this.pipelineCache.delete(key);
                this.pipelineCache.set(key, pipeline);
                return pipeline;
            }
            const shaderModule = this.device.createShaderModule({
                label: "D3D8 shader " + state.vertexShader.toString(16) +
                    "/" + state.pixelShader.toString(16),
                code: shaderPipelineWgsl(vertexResource, declaration,
                    pixelResource),
            });
            this.shaderBindGroupLayoutFor();
            pipeline = this.device.createRenderPipeline({
                label: "D3D8 shader pipeline " + key,
                layout: this.shaderPipelineLayout,
                vertex: {
                    module: shaderModule,
                    entryPoint: "vs_main",
                    buffers: [{
                        arrayStride: stride,
                        stepMode: "vertex",
                        attributes: declaration.attributes,
                    }],
                },
                fragment: {
                    module: shaderModule,
                    entryPoint: "fs_main",
                    targets: [{
                        format: targetFormat,
                        ...(blend ? { blend: blendState(state) } : {}),
                        writeMask: state.renderStates[D3DRS_COLORWRITEENABLE] & 0xF,
                    }],
                },
                primitive: {
                    topology,
                    ...(stripIndexFormat ? { stripIndexFormat } : {}),
                    cullMode: cull === D3DCULL_NONE ? "none" : "back",
                    frontFace: cull === D3DCULL_CCW ? "cw" : "ccw",
                },
                ...(state.depthView && state.depthSurfaceEnabled &&
                        !state.renderTarget.handle ? { depthStencil: {
                    format: "depth24plus-stencil8",
                    depthWriteEnabled: !!state.renderStates[D3DRS_ZENABLE] &&
                        !!state.renderStates[D3DRS_ZWRITEENABLE],
                    depthCompare: state.renderStates[D3DRS_ZENABLE] ?
                        compareFunction(state.renderStates[D3DRS_ZFUNC]) :
                        "always",
                    stencilFront: state.renderStates[D3DRS_STENCILENABLE] ? {
                        compare: compareFunction(
                            state.renderStates[D3DRS_STENCILFUNC]),
                        failOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILFAIL]),
                        depthFailOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILZFAIL]),
                        passOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILPASS]),
                    } : {},
                    stencilBack: state.renderStates[D3DRS_STENCILENABLE] ? {
                        compare: compareFunction(
                            state.renderStates[D3DRS_STENCILFUNC]),
                        failOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILFAIL]),
                        depthFailOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILZFAIL]),
                        passOp: stencilOperation(
                            state.renderStates[D3DRS_STENCILPASS]),
                    } : {},
                    stencilReadMask: state.renderStates[D3DRS_STENCILENABLE] ?
                        state.renderStates[D3DRS_STENCILMASK] >>> 0 : 0,
                    stencilWriteMask: state.renderStates[D3DRS_STENCILENABLE] ?
                        state.renderStates[D3DRS_STENCILWRITEMASK] >>> 0 : 0,
                    depthBias: -Math.min(16,
                        state.renderStates[D3DRS_ZBIAS] >>> 0),
                } } : {}),
            });
            pipeline._d8wgId = this.nextPipelineId++;
            if (this.pipelineCache.size >= this.maxPipelines) {
                this.pipelineCache.delete(this.pipelineCache.keys().next().value);
                this.stats.pipelineCacheEvictions++;
            }
            this.pipelineCache.set(key, pipeline);
            this.stats.pipelineCreations++;
            return pipeline;
        }

        // Constant-register uniforms for real-shader-mode draws. Packs both vs
        // and ps banks into one uniform-ring slot matching
        // D8WGShaderConstants' WGSL layout (vs: array<vec4<f32>, 96> then
        // ps: array<vec4<f32>, 8>), reusing the slot while the constants are
        // unchanged within a frame.
        shaderUniformFor(state) {
            if (state.shaderConstantSlotSerial === state.shaderConstantSerial &&
                    state.shaderConstantSlotFrame === this.frameSerial &&
                    state.shaderConstantSlotBuffer) {
                this.stats.uniformSlotReuses++;
                return { buffer: state.shaderConstantSlotBuffer,
                    offset: state.shaderConstantSlotOffset };
            }
            const values = this.shaderConstantScratch;
            values.set(state.vsConstants, 0);
            values.set(state.psConstants, D8WG_MAX_VS_CONSTANTS * 4);
            const slot = this.allocateUniformSlot(SHADER_UNIFORM_BYTES);
            this.device.queue.writeBuffer(slot.buffer, slot.offset, values);
            this.stats.uniformUploadBytes += SHADER_UNIFORM_BYTES;
            state.shaderConstantSlotSerial = state.shaderConstantSerial;
            state.shaderConstantSlotFrame = this.frameSerial;
            state.shaderConstantSlotBuffer = slot.buffer;
            state.shaderConstantSlotOffset = slot.offset;
            return slot;
        }

        shaderBindGroupFor(state, pipeline) {
            const uniforms = this.shaderUniformFor(state);
            const texture0 = this.textureViewFor(state, 0);
            const texture1 = this.textureViewFor(state, 1);
            const sampler0 = this.samplerFor(state, 0);
            const sampler1 = this.samplerFor(state, 1);
            // The uniform slot is addressed by dynamic offset, so it is
            // deliberately NOT part of the bind group identity (doc 9.7).
            // The ring buffer object itself is, because an overflow
            // allocation is a different GPUBuffer.
            const key = "s:" + uniforms.buffer._d8wgRingId + ":" +
                texture0.key + ":" + sampler0._d8wgKey + ":" +
                texture1.key + ":" + sampler1._d8wgKey;
            let group = state.bindGroups.get(key);
            if (group) {
                state.bindGroups.delete(key);
                state.bindGroups.set(key, group);
                this.stats.bindGroupHits++;
                return { group, offset: uniforms.offset };
            }
            group = this.device.createBindGroup({
                label: "D3D8 shader bind group",
                // The explicit layout, not pipeline.getBindGroupLayout(0):
                // see shaderBindGroupLayoutFor for why "auto" cannot work here.
                layout: this.shaderBindGroupLayoutFor(),
                entries: [
                    { binding: 0, resource: { buffer: uniforms.buffer,
                        offset: 0, size: SHADER_UNIFORM_BYTES } },
                    { binding: 1, resource: texture0.view },
                    { binding: 2, resource: sampler0 },
                    { binding: 3, resource: texture1.view },
                    { binding: 4, resource: sampler1 },
                ],
            });
            if (state.bindGroups.size >= this.maxBindGroups)
                state.bindGroups.delete(state.bindGroups.keys().next().value);
            state.bindGroups.set(key, group);
            this.stats.bindGroupCreations++;
            return { group, offset: uniforms.offset };
        }

        samplerFor(state, stage) {
            const values = state.textureStageStates[stage];
            const address = value => value === 1 ? "repeat" :
                value === 2 ? "mirror-repeat" : "clamp-to-edge";
            const min = values[D3DTSS_MINFILTER] === 1 ? "nearest" : "linear";
            const mag = values[D3DTSS_MAGFILTER] === 1 ? "nearest" : "linear";
            const mip = values[D3DTSS_MIPFILTER] === 2 ? "linear" : "nearest";
            let anisotropy = Math.max(1,
                Math.min(16, values[D3DTSS_MAXANISOTROPY] || 1));
            if (min !== "linear" || mag !== "linear" || mip !== "linear")
                anisotropy = 1;
            const key = [address(values[D3DTSS_ADDRESSU]),
                address(values[D3DTSS_ADDRESSV]), min, mag, mip,
                values[D3DTSS_MIPFILTER] === 0 ? 0 : 32,
                anisotropy].join(":");
            let sampler = this.samplerCache.get(key);
            if (!sampler) {
                sampler = this.device.createSampler({
                    addressModeU: address(values[D3DTSS_ADDRESSU]),
                    addressModeV: address(values[D3DTSS_ADDRESSV]),
                    addressModeW: "clamp-to-edge",
                    minFilter: min,
                    magFilter: mag,
                    mipmapFilter: mip,
                    maxLod: values[D3DTSS_MIPFILTER] === 0 ? 0 : 32,
                    maxAnisotropy: anisotropy,
                });
                sampler._d8wgKey = key;
                if (this.samplerCache.size >= this.maxSamplers)
                    this.samplerCache.delete(this.samplerCache.keys().next().value);
                this.samplerCache.set(key, sampler);
            } else {
                this.samplerCache.delete(key);
                this.samplerCache.set(key, sampler);
            }
            return sampler;
        }

        textureViewFor(state, stage) {
            const resource = this.resources.get(state.textures[stage]);
            if (!resource || resource.kind !== RESOURCE_TEXTURE_2D)
                return { resource: null, view: this.fallbackView, key: "fallback" };
            const baseLevel = Math.min(resource.levelCount - 1,
                state.textureStageStates[stage][D3DTSS_MAXMIPLEVEL] >>> 0);
            let view = resource.views.get(baseLevel);
            if (!view) {
                view = resource.gpuTexture.createView({
                    baseMipLevel: baseLevel,
                    mipLevelCount: resource.levelCount - baseLevel,
                });
                resource.views.set(baseLevel, view);
            }
            return { resource, view, key: resource.handle + "@" + baseLevel };
        }

        bindGroupFor(state, pipeline) {
            if (state.vertexShader & 1)
                return this.shaderBindGroupFor(state, pipeline);
            const uniforms = this.uniformFor(state);
            const texture0 = this.textureViewFor(state, 0);
            const texture1 = this.textureViewFor(state, 1);
            const sampler0 = this.samplerFor(state, 0);
            const sampler1 = this.samplerFor(state, 1);
            // Neither the pipeline nor the uniform contents belong in this key:
            // every fixed-function pipeline shares one explicit bind group
            // layout, and the uniform slot is reached by dynamic offset. What
            // remains is the ring buffer identity plus the bound textures and
            // samplers, which is what makes steady-state creation zero.
            const key = "f:" + uniforms.buffer._d8wgRingId + ":" +
                texture0.key + ":" + sampler0._d8wgKey + ":" +
                texture1.key + ":" + sampler1._d8wgKey;
            let group = state.bindGroups.get(key);
            if (group) {
                state.bindGroups.delete(key);
                state.bindGroups.set(key, group);
                this.stats.bindGroupHits++;
                return { group, offset: uniforms.offset };
            }
            group = this.device.createBindGroup({
                label: "D3D8 fixed-function bind group",
                layout: this.fixedBindGroupLayoutFor(),
                entries: [
                    { binding: 0, resource: { buffer: uniforms.buffer,
                        offset: 0, size: FIXED_UNIFORM_BYTES } },
                    { binding: 1, resource: texture0.view },
                    { binding: 2, resource: sampler0 },
                    { binding: 3, resource: texture1.view },
                    { binding: 4, resource: sampler1 },
                ],
            });
            if (state.bindGroups.size >= this.maxBindGroups)
                state.bindGroups.delete(state.bindGroups.keys().next().value);
            state.bindGroups.set(key, group);
            this.stats.bindGroupCreations++;
            return { group, offset: uniforms.offset };
        }

        validateGeometryState(state, stride) {
            if (state.vertexShader & 1) {
                const resource = this.resources.get(state.vertexShader);
                if (!resource || resource.kind !== RESOURCE_VERTEX_SHADER ||
                        stride < resource.declaration.stride) {
                    this.warnOnce("vs-" + state.vertexShader,
                        "draw with an unresolved/incompatible vertex shader",
                        "0x" + state.vertexShader.toString(16));
                    this.stats.unsupportedCommands++;
                    return false;
                }
                return true;
            }
            const layout = parseFVF(state.fvf >>> 0, stride >>> 0);
            if (!layout) {
                this.warnOnce("fvf-" + state.fvf,
                    "unsupported FVF in the WebGPU Maple 2D path",
                    "0x" + state.fvf.toString(16));
                this.stats.unsupportedCommands++;
                return false;
            }
            return true;
        }

        createTransientBuffer(data, usage, label) {
            if (!this.frame) throw new Error("transient buffer created outside a frame");
            const upload = padded4(data);
            let buffer = this.transientBuffer;
            let offset = align4(this.transientCursor);
            if (upload.byteLength > this.transientCapacity - offset) {
                buffer = this.device.createBuffer({
                    label: label + " overflow",
                    size: Math.max(4, upload.byteLength),
                    usage: usage | BUFFER_USAGE_COPY_SRC | BUFFER_USAGE_COPY_DST,
                });
                offset = 0;
                this.frame.transientBuffers.push(buffer);
                this.stats.transientBufferCreations++;
            } else {
                this.transientCursor = offset + upload.byteLength;
            }
            this.device.queue.writeBuffer(buffer, offset, upload);
            this.stats.transientUploadBytes += data.byteLength;
            return { buffer, offset, size: upload.byteLength };
        }

        preparePass(state, pass) {
            const x = Math.min(state.surface.width, state.viewport.x >>> 0);
            const y = Math.min(state.surface.height, state.viewport.y >>> 0);
            const width = Math.min(state.viewport.width >>> 0,
                state.surface.width - x);
            const height = Math.min(state.viewport.height >>> 0,
                state.surface.height - y);
            if (!width || !height) return false;
            if ((state.fvf & D3DFVF_POSITION_MASK) === D3DFVF_XYZ)
                pass.setViewport(x, y, width, height,
                    state.viewport.minZ, state.viewport.maxZ);
            else
                pass.setViewport(0, 0, state.surface.width,
                    state.surface.height, 0, 1);
            if (state.depthView)
                pass.setStencilReference(
                    state.renderStates[D3DRS_STENCILREF] & 0xFF);
            pass.setScissorRect(x, y, width, height);
            return true;
        }

        createTextureResource(bytes, payloadOffset, commandEnd) {
            if (commandEnd - payloadOffset < 32)
                throw new Error("short CREATE_TEXTURE");
            const deviceHandle = u32(bytes, payloadOffset);
            const handle = u32(bytes, payloadOffset + 4);
            const width = u32(bytes, payloadOffset + 8);
            const height = u32(bytes, payloadOffset + 12);
            const levelCount = u32(bytes, payloadOffset + 16);
            const format = u32(bytes, payloadOffset + 20);
            if (!this.devices.has(deviceHandle))
                throw new Error("CREATE_TEXTURE references an unknown device");
            if (!width || !height || !levelCount || !textureFormatInfo(format))
                throw new Error("invalid CREATE_TEXTURE dimensions/format");
            const maximumLevels = 1 + Math.floor(Math.log2(
                Math.max(width, height)));
            if (levelCount > maximumLevels)
                throw new Error("CREATE_TEXTURE has too many mip levels");
            this.destroyResource(handle);
            const gpuTexture = this.device.createTexture({
                label: "D3D8 texture " + handle.toString(16),
                size: { width, height, depthOrArrayLayers: 1 },
                mipLevelCount: levelCount,
                sampleCount: 1,
                dimension: "2d",
                format: "rgba8unorm",
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING |
                    ((u32(bytes, payloadOffset + 24) & D3DUSAGE_RENDERTARGET) ?
                        TEXTURE_USAGE_RENDER_ATTACHMENT : 0),
            });
            const formatInfo = textureFormatInfo(format);
            const shadowLevels = [];
            for (let level = 0; level < levelCount; level++) {
                const levelWidth = Math.max(1, width >>> level);
                const levelHeight = Math.max(1, height >>> level);
                const columns = Math.ceil(levelWidth / formatInfo.blockWidth);
                const rows = Math.ceil(levelHeight / formatInfo.blockHeight);
                const rowPitch = columns * formatInfo.blockBytes;
                shadowLevels.push({
                    width: levelWidth,
                    height: levelHeight,
                    rowPitch,
                    rows,
                    data: new Uint8Array(rowPitch * rows),
                });
            }
            this.resources.set(handle, {
                handle,
                deviceHandle,
                kind: RESOURCE_TEXTURE_2D,
                width,
                height,
                levelCount,
                format,
                usage: u32(bytes, payloadOffset + 24),
                pool: u32(bytes, payloadOffset + 28),
                gpuTexture,
                views: new Map([[0, gpuTexture.createView()]]),
                shadowLevels,
            });
        }

        updateTextureResource(bytes, payloadOffset, commandEnd) {
            if (commandEnd - payloadOffset < 40)
                throw new Error("short UPDATE_TEXTURE");
            const resource = this.resources.get(u32(bytes, payloadOffset));
            if (!resource || resource.kind !== RESOURCE_TEXTURE_2D)
                throw new Error("UPDATE_TEXTURE references an unknown texture");
            const level = u32(bytes, payloadOffset + 4);
            const x = u32(bytes, payloadOffset + 8);
            const y = u32(bytes, payloadOffset + 12);
            const width = u32(bytes, payloadOffset + 16);
            const height = u32(bytes, payloadOffset + 20);
            const rowPitch = u32(bytes, payloadOffset + 24);
            const dataBytes = u32(bytes, payloadOffset + 28);
            const dataOffset = u32(bytes, payloadOffset + 32);
            if (level >= resource.levelCount || !width || !height)
                throw new Error("invalid UPDATE_TEXTURE mip/extent");
            const levelWidth = Math.max(1, resource.width >>> level);
            const levelHeight = Math.max(1, resource.height >>> level);
            if (x > levelWidth || width > levelWidth - x ||
                    y > levelHeight || height > levelHeight - y)
                throw new Error("UPDATE_TEXTURE rectangle exceeds its mip level");
            const format = textureFormatInfo(resource.format);
            const columns = Math.ceil(width / format.blockWidth);
            const rows = Math.ceil(height / format.blockHeight);
            const minimumRow = columns * format.blockBytes;
            const minimumBytes = rowPitch * (rows - 1) + minimumRow;
            if (rowPitch < minimumRow || dataBytes < minimumBytes)
                throw new Error("UPDATE_TEXTURE pitch/data is too small");
            if (format.dxt && ((x & 3) || (y & 3) ||
                    ((width & 3) && x + width !== levelWidth) ||
                    ((height & 3) && y + height !== levelHeight)))
                throw new Error("UPDATE_TEXTURE DXT rectangle is not block aligned");
            const source = checkedDataRange(bytes, dataOffset, dataBytes,
                "UPDATE_TEXTURE data");
            const shadow = resource.shadowLevels[level];
            const blockX = Math.floor(x / format.blockWidth);
            const blockY = Math.floor(y / format.blockHeight);
            for (let row = 0; row < rows; row++) {
                const sourceStart = row * rowPitch;
                const destinationStart = (blockY + row) * shadow.rowPitch +
                    blockX * format.blockBytes;
                shadow.data.set(source.subarray(sourceStart,
                    sourceStart + minimumRow), destinationStart);
            }
            const rgba = decodeTextureUpload(resource.format, source,
                width, height, rowPitch);
            const destination = {
                texture: resource.gpuTexture,
                mipLevel: level,
                origin: { x, y, z: 0 },
            };
            const extent = { width, height, depthOrArrayLayers: 1 };
            if (this.frame) {
                this.endPass();
                const packedPitch = width * 4;
                const uploadPitch = (packedPitch + 255) & ~255;
                const padded = new Uint8Array(uploadPitch * height);
                for (let row = 0; row < height; row++)
                    padded.set(rgba.subarray(row * packedPitch,
                        (row + 1) * packedPitch), row * uploadPitch);
                const staging = this.createTransientBuffer(padded,
                    BUFFER_USAGE_COPY_SRC, "D3D8 ordered texture upload");
                this.frame.encoder.copyBufferToTexture({
                    buffer: staging.buffer,
                    offset: staging.offset,
                    bytesPerRow: uploadPitch,
                    rowsPerImage: height,
                }, destination, extent);
            } else {
                this.device.queue.writeTexture(destination, rgba, {
                    bytesPerRow: width * 4,
                    rowsPerImage: height,
                }, extent);
            }
            this.stats.uploadBytes += dataBytes;
        }

        // Stage 6: D3D8 shader model 1.x. Both creators translate the
        // bytecode eagerly (discarding the WGSL text here; shaderPipelineFor
        // regenerates and caches it per pipeline variant) so a genuinely
        // unsupported/malformed shader fails CreateVertexShader/
        // CreatePixelShader itself rather than surfacing later at the first
        // draw that binds it -- matches the "illegal bytecode is rejected up
        // front" rule the guest-side validator already enforces.
        createVertexShaderResource(bytes, payloadOffset, commandEnd) {
            if (commandEnd - payloadOffset < 24)
                throw new Error("short CREATE_VERTEX_SHADER");
            const deviceHandle = u32(bytes, payloadOffset);
            const handle = u32(bytes, payloadOffset + 4);
            const declCount = u32(bytes, payloadOffset + 8);
            const declOffset = u32(bytes, payloadOffset + 12);
            const codeCount = u32(bytes, payloadOffset + 16);
            const codeOffset = u32(bytes, payloadOffset + 20);
            if (!this.devices.has(deviceHandle))
                throw new Error(
                    "CREATE_VERTEX_SHADER references an unknown device");
            if (!codeCount)
                throw new Error("CREATE_VERTEX_SHADER has an empty code blob");
            const declBytes = checkedDataRange(bytes, declOffset,
                declCount * 4, "CREATE_VERTEX_SHADER declaration");
            const codeBytes = checkedDataRange(bytes, codeOffset,
                codeCount * 4, "CREATE_VERTEX_SHADER code");
            const declTokens = [];
            for (let i = 0; i < declCount; i++)
                declTokens.push(u32(declBytes, i * 4));
            const codeTokens = [];
            for (let i = 0; i < codeCount; i++)
                codeTokens.push(u32(codeBytes, i * 4));
            const declaration = parseVertexDeclaration(declTokens);
            vertexShaderWgsl(codeTokens, declaration);
            this.destroyResource(handle);
            // Reset keeps app-visible shader handles stable (see
            // recreate_device_resources in d3d8_proxy.c), so a handle retired
            // with the previous device epoch is legitimately live again once
            // the guest re-creates it under the new one.
            this.retiredResourceHandles.delete(handle);
            this.resources.set(handle, {
                handle,
                deviceHandle,
                kind: RESOURCE_VERTEX_SHADER,
                codeTokens,
                // Kept verbatim so serializeSession can replay the original
                // CREATE_VERTEX_SHADER after a v86 save/load.
                declTokens,
                declaration,
            });
        }

        createPixelShaderResource(bytes, payloadOffset, commandEnd) {
            if (commandEnd - payloadOffset < 16)
                throw new Error("short CREATE_PIXEL_SHADER");
            const deviceHandle = u32(bytes, payloadOffset);
            const handle = u32(bytes, payloadOffset + 4);
            const codeCount = u32(bytes, payloadOffset + 8);
            const codeOffset = u32(bytes, payloadOffset + 12);
            if (!this.devices.has(deviceHandle))
                throw new Error(
                    "CREATE_PIXEL_SHADER references an unknown device");
            if (!codeCount)
                throw new Error("CREATE_PIXEL_SHADER has an empty code blob");
            const codeBytes = checkedDataRange(bytes, codeOffset,
                codeCount * 4, "CREATE_PIXEL_SHADER code");
            const codeTokens = [];
            for (let i = 0; i < codeCount; i++)
                codeTokens.push(u32(codeBytes, i * 4));
            pixelShaderWgsl(codeTokens);
            this.destroyResource(handle);
            this.retiredResourceHandles.delete(handle);
            this.resources.set(handle, {
                handle,
                deviceHandle,
                kind: RESOURCE_PIXEL_SHADER,
                codeTokens,
            });
        }

        sequentialFanIndices(vertexCount) {
            const use32 = vertexCount > 0xFFFF;
            const values = use32 ? new Uint32Array((vertexCount - 2) * 3) :
                new Uint16Array((vertexCount - 2) * 3);
            let output = 0;
            for (let vertex = 1; vertex + 1 < vertexCount; vertex++) {
                values[output++] = 0;
                values[output++] = vertex;
                values[output++] = vertex + 1;
            }
            this.stats.fanConversions++;
            return { data: new Uint8Array(values.buffer),
                format: use32 ? "uint32" : "uint16", count: values.length };
        }

        convertFanIndices(source, formatInfo, indexCount) {
            const values = new formatInfo.ArrayType((indexCount - 2) * 3);
            const view = new DataView(source.buffer, source.byteOffset,
                source.byteLength);
            const read = formatInfo.bytes === 2 ?
                offset => view.getUint16(offset, true) :
                offset => view.getUint32(offset, true);
            const centre = read(0);
            let output = 0;
            for (let index = 1; index + 1 < indexCount; index++) {
                values[output++] = centre;
                values[output++] = read(index * formatInfo.bytes);
                values[output++] = read((index + 1) * formatInfo.bytes);
            }
            this.stats.fanConversions++;
            return { data: new Uint8Array(values.buffer),
                format: formatInfo.webgpu, count: values.length };
        }

        drawPrimitive(bytes, payloadOffset) {
            const state = this.devices.get(u32(bytes, payloadOffset));
            if (!state) throw new Error("draw references an unknown D3D8 device");
            const primitive = primitiveInfo(u32(bytes, payloadOffset + 4),
                u32(bytes, payloadOffset + 12));
            if (!primitive) {
                this.warnOnce("primitive-" + u32(bytes, payloadOffset + 4),
                    "unsupported primitive topology", u32(bytes, payloadOffset + 4));
                this.stats.unsupportedCommands++;
                return;
            }
            const stream = state.streams[0];
            const resource = this.resources.get(stream.handle);
            if (!resource || resource.kind !== RESOURCE_BUFFER_VERTEX) {
                throw new Error("draw references an unknown vertex buffer");
            }
            if (!this.validateGeometryState(state, stream.stride)) return;
            const startVertex = u32(bytes, payloadOffset + 8);
            const availableVertices = Math.floor(resource.byteCount / stream.stride);
            if (startVertex > availableVertices ||
                primitive.vertices > availableVertices - startVertex) {
                throw new Error("draw vertex range exceeds its buffer");
            }
            const pipeline = this.pipelineFor(state, primitive.topology,
                stream.stride);
            if (!pipeline) return;
            const pass = this.ensureFrame(state);
            if (!this.preparePass(state, pass)) return;
            pass.setPipeline(pipeline);
            const binding = this.bindGroupFor(state, pipeline);
            DYNAMIC_OFFSETS[0] = binding.offset;
            pass.setBindGroup(0, binding.group, DYNAMIC_OFFSETS, 0, 1);
            pass.setVertexBuffer(0, resource.gpuBuffer);
            if (primitive.fan) {
                const fan = this.sequentialFanIndices(primitive.vertices);
                const indexBuffer = this.createTransientBuffer(fan.data,
                    BUFFER_USAGE_INDEX, "D3D8 triangle fan indices");
                pass.setIndexBuffer(indexBuffer.buffer, fan.format,
                    indexBuffer.offset, indexBuffer.size);
                pass.drawIndexed(fan.count, 1, 0, startVertex, 0);
            } else {
                pass.draw(primitive.vertices, 1, startVertex, 0);
            }
            this.stats.drawCalls++;
        }

        drawIndexedPrimitive(bytes, payloadOffset) {
            const state = this.devices.get(u32(bytes, payloadOffset));
            if (!state) throw new Error("indexed draw references an unknown device");
            const primitive = primitiveInfo(u32(bytes, payloadOffset + 4),
                u32(bytes, payloadOffset + 20));
            if (!primitive) throw new Error("invalid indexed primitive topology");
            const stream = state.streams[0];
            const vertexResource = this.resources.get(stream.handle);
            if (!vertexResource || vertexResource.kind !== RESOURCE_BUFFER_VERTEX) {
                throw new Error("indexed draw references an unknown vertex buffer");
            }
            const indexResource = this.resources.get(state.indices.handle);
            if (!indexResource || indexResource.kind !== RESOURCE_BUFFER_INDEX) {
                throw new Error("indexed draw references an unknown index buffer");
            }
            const formatInfo = indexFormatInfo(indexResource.format);
            if (!formatInfo) throw new Error("indexed draw uses an invalid index format");
            if (!this.validateGeometryState(state, stream.stride)) return;
            const startIndex = u32(bytes, payloadOffset + 16);
            const availableIndices = Math.floor(indexResource.byteCount /
                formatInfo.bytes);
            if (startIndex > availableIndices ||
                primitive.vertices > availableIndices - startIndex) {
                throw new Error("indexed draw range exceeds its index buffer");
            }
            const minVertex = u32(bytes, payloadOffset + 8);
            const vertexCount = u32(bytes, payloadOffset + 12);
            const availableVertices = Math.floor(vertexResource.byteCount /
                stream.stride);
            if (state.indices.baseVertex > 0x7FFFFFFF ||
                state.indices.baseVertex + minVertex > availableVertices ||
                vertexCount > availableVertices -
                    (state.indices.baseVertex + minVertex)) {
                throw new Error("indexed draw range exceeds its vertex buffer");
            }
            const pipeline = this.pipelineFor(state, primitive.topology,
                stream.stride, primitive.fan ? undefined : formatInfo.webgpu);
            if (!pipeline) return;
            const pass = this.ensureFrame(state);
            if (!this.preparePass(state, pass)) return;
            pass.setPipeline(pipeline);
            const binding = this.bindGroupFor(state, pipeline);
            DYNAMIC_OFFSETS[0] = binding.offset;
            pass.setBindGroup(0, binding.group, DYNAMIC_OFFSETS, 0, 1);
            pass.setVertexBuffer(0, vertexResource.gpuBuffer);
            if (primitive.fan) {
                const sourceOffset = startIndex * formatInfo.bytes;
                const sourceBytes = primitive.vertices * formatInfo.bytes;
                if (sourceOffset > indexResource.byteCount ||
                    sourceBytes > indexResource.byteCount - sourceOffset) {
                    throw new Error("triangle fan index range exceeds its buffer");
                }
                const fan = this.convertFanIndices(indexResource.shadow.subarray(
                    sourceOffset, sourceOffset + sourceBytes), formatInfo,
                    primitive.vertices);
                const indexBuffer = this.createTransientBuffer(fan.data,
                    BUFFER_USAGE_INDEX, "D3D8 converted indexed fan");
                pass.setIndexBuffer(indexBuffer.buffer, fan.format,
                    indexBuffer.offset, indexBuffer.size);
                pass.drawIndexed(fan.count, 1, 0, state.indices.baseVertex, 0);
            } else {
                pass.setIndexBuffer(indexResource.gpuBuffer, formatInfo.webgpu);
                pass.drawIndexed(primitive.vertices, 1, startIndex,
                    state.indices.baseVertex, 0);
            }
            this.stats.drawCalls++;
            this.stats.indexedDrawCalls++;
        }

        drawPrimitiveUP(bytes, payloadOffset) {
            const state = this.devices.get(u32(bytes, payloadOffset));
            if (!state) throw new Error("UP draw references an unknown device");
            const primitive = primitiveInfo(u32(bytes, payloadOffset + 4),
                u32(bytes, payloadOffset + 8));
            if (!primitive) throw new Error("invalid UP primitive topology");
            const stride = u32(bytes, payloadOffset + 12);
            const vertexCount = u32(bytes, payloadOffset + 16);
            const vertexBytes = u32(bytes, payloadOffset + 20);
            if (!stride || vertexCount !== primitive.vertices ||
                vertexCount > Math.floor(0xFFFFFFFF / stride) ||
                vertexCount * stride !== vertexBytes) {
                throw new Error("DRAW_PRIMITIVE_UP size metadata mismatch");
            }
            if (!this.validateGeometryState(state, stride)) return;
            const data = checkedDataRange(bytes, u32(bytes, payloadOffset + 24),
                vertexBytes, "DRAW_PRIMITIVE_UP vertex data");
            const pipeline = this.pipelineFor(state, primitive.topology, stride);
            if (!pipeline) return;
            const pass = this.ensureFrame(state);
            if (!this.preparePass(state, pass)) return;
            const vertexBuffer = this.createTransientBuffer(data,
                BUFFER_USAGE_VERTEX, "D3D8 DrawPrimitiveUP vertices");
            pass.setPipeline(pipeline);
            const binding = this.bindGroupFor(state, pipeline);
            DYNAMIC_OFFSETS[0] = binding.offset;
            pass.setBindGroup(0, binding.group, DYNAMIC_OFFSETS, 0, 1);
            pass.setVertexBuffer(0, vertexBuffer.buffer, vertexBuffer.offset,
                vertexBuffer.size);
            if (primitive.fan) {
                const fan = this.sequentialFanIndices(vertexCount);
                const indexBuffer = this.createTransientBuffer(fan.data,
                    BUFFER_USAGE_INDEX, "D3D8 UP triangle fan indices");
                pass.setIndexBuffer(indexBuffer.buffer, fan.format,
                    indexBuffer.offset, indexBuffer.size);
                pass.drawIndexed(fan.count, 1, 0, 0, 0);
            } else {
                pass.draw(vertexCount, 1, 0, 0);
            }
            this.stats.drawCalls++;
            this.stats.upDrawCalls++;
            state.streams[0] = { handle: 0, stride: 0 };
        }

        drawIndexedPrimitiveUP(bytes, payloadOffset) {
            const state = this.devices.get(u32(bytes, payloadOffset));
            if (!state) throw new Error("indexed UP draw references an unknown device");
            const primitive = primitiveInfo(u32(bytes, payloadOffset + 4),
                u32(bytes, payloadOffset + 16));
            if (!primitive) throw new Error("invalid indexed UP topology");
            const formatInfo = indexFormatInfo(u32(bytes, payloadOffset + 20));
            if (!formatInfo) throw new Error("invalid indexed UP format");
            const stride = u32(bytes, payloadOffset + 24);
            const indexCount = u32(bytes, payloadOffset + 28);
            const indexBytes = u32(bytes, payloadOffset + 32);
            const vertexBytes = u32(bytes, payloadOffset + 36);
            if (!stride || indexCount !== primitive.vertices ||
                indexCount > Math.floor(0xFFFFFFFF / formatInfo.bytes) ||
                indexCount * formatInfo.bytes !== indexBytes ||
                vertexBytes % stride !== 0) {
                throw new Error("DRAW_INDEXED_PRIMITIVE_UP size metadata mismatch");
            }
            const minVertex = u32(bytes, payloadOffset + 8);
            const vertexCount = u32(bytes, payloadOffset + 12);
            if (minVertex > 0xFFFFFFFF - vertexCount ||
                minVertex + vertexCount > Math.floor(0xFFFFFFFF / stride) ||
                (minVertex + vertexCount) * stride !== vertexBytes) {
                throw new Error("DRAW_INDEXED_PRIMITIVE_UP vertex range mismatch");
            }
            if (!this.validateGeometryState(state, stride)) return;
            let indexData = checkedDataRange(bytes,
                u32(bytes, payloadOffset + 40), indexBytes,
                "DRAW_INDEXED_PRIMITIVE_UP index data");
            const vertexData = checkedDataRange(bytes,
                u32(bytes, payloadOffset + 44), vertexBytes,
                "DRAW_INDEXED_PRIMITIVE_UP vertex data");
            const pipeline = this.pipelineFor(state, primitive.topology, stride,
                primitive.fan ? undefined : formatInfo.webgpu);
            if (!pipeline) return;
            const pass = this.ensureFrame(state);
            if (!this.preparePass(state, pass)) return;
            const vertexBuffer = this.createTransientBuffer(vertexData,
                BUFFER_USAGE_VERTEX, "D3D8 DrawIndexedPrimitiveUP vertices");
            let drawIndexCount = indexCount;
            let webgpuFormat = formatInfo.webgpu;
            if (primitive.fan) {
                const fan = this.convertFanIndices(indexData, formatInfo, indexCount);
                indexData = fan.data;
                drawIndexCount = fan.count;
                webgpuFormat = fan.format;
            }
            const indexBuffer = this.createTransientBuffer(indexData,
                BUFFER_USAGE_INDEX, "D3D8 DrawIndexedPrimitiveUP indices");
            pass.setPipeline(pipeline);
            const binding = this.bindGroupFor(state, pipeline);
            DYNAMIC_OFFSETS[0] = binding.offset;
            pass.setBindGroup(0, binding.group, DYNAMIC_OFFSETS, 0, 1);
            pass.setVertexBuffer(0, vertexBuffer.buffer, vertexBuffer.offset,
                vertexBuffer.size);
            pass.setIndexBuffer(indexBuffer.buffer, webgpuFormat,
                indexBuffer.offset, indexBuffer.size);
            pass.drawIndexed(drawIndexCount, 1, 0, 0, 0);
            this.stats.drawCalls++;
            this.stats.indexedDrawCalls++;
            this.stats.upDrawCalls++;
            state.streams[0] = { handle: 0, stride: 0 };
            state.indices = { handle: 0, baseVertex: 0 };
        }

        executeCommand(bytes, commandOffset, opcode, payloadOffset,
                commandEnd) {
            const firstHandle = commandEnd - payloadOffset >= 4 ?
                u32(bytes, payloadOffset) : 0;
            const resourceOpcode = opcode === OP_UPDATE_BUFFER ||
                opcode === OP_UPDATE_TEXTURE;
            if ((resourceOpcode &&
                    this.retiredResourceHandles.has(firstHandle)) ||
                    (opcode === OP_DESTROY_RESOURCE &&
                        (this.retiredResourceHandles.has(firstHandle) ||
                         this.retiredDeviceHandles.has(firstHandle))) ||
                    (opcode !== OP_CREATE_DEVICE && !resourceOpcode &&
                        opcode !== OP_DESTROY_RESOURCE &&
                        this.retiredDeviceHandles.has(firstHandle))) {
                if ((opcode === OP_CREATE_BUFFER || opcode === OP_CREATE_TEXTURE)
                        && commandEnd - payloadOffset >= 8) {
                    this.retireHandle(this.retiredResourceHandles,
                        u32(bytes, payloadOffset + 4));
                }
                this.stats.staleCommandsDropped++;
                return;
            }
            switch (opcode) {
            case OP_HELLO:
                if (commandEnd - payloadOffset < 16 ||
                        u32(bytes, payloadOffset) !== 32) {
                    throw new Error("only a 32-bit D8WG guest is supported");
                }
                if (u32(bytes, payloadOffset + 8) !== this.activeSession.low ||
                        u32(bytes, payloadOffset + 12) !==
                            this.activeSession.high) {
                    throw new Error("HELLO process session does not match its batch");
                }
                this.activeSession.helloSeen = true;
                break;
            case OP_CREATE_DEVICE:
                if (commandEnd - payloadOffset < 44) throw new Error("short CREATE_DEVICE");
                this.createOrResetDevice(bytes, payloadOffset, false);
                break;
            case OP_RESET:
                if (commandEnd - payloadOffset < 48) throw new Error("short RESET");
                this.resetDevice(bytes, payloadOffset);
                break;
            case OP_UPDATE_SURFACE: {
                if (commandEnd - payloadOffset < 24) {
                    throw new Error("short UPDATE_SURFACE");
                }
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) {
                    throw new Error("UPDATE_SURFACE references an unknown device");
                }
                this.updateSurface(bytes, payloadOffset, state, "move");
                break;
            }
            case OP_PRESENT: {
                if (commandEnd - payloadOffset < 24) throw new Error("short PRESENT");
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("PRESENT references an unknown device");
                this.updateSurface(bytes, payloadOffset, state, "present");
                this.ensureFrame(state);
                this.finishFrame(true);
                break;
            }
            case OP_CLEAR: {
                if (commandEnd - payloadOffset < 24) throw new Error("short CLEAR");
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("CLEAR references an unknown device");
                const flags = u32(bytes, payloadOffset + 4);
                const rectCount = u32(bytes, payloadOffset + 20);
                if (rectCount > Math.floor((commandEnd - payloadOffset - 24) /
                        16)) {
                    throw new Error("CLEAR rectangle array is truncated");
                }
                const rectangles = [];
                for (let index = 0; index < rectCount; index++) {
                    const offset = payloadOffset + 24 + index * 16;
                    rectangles.push({
                        x1: i32(bytes, offset),
                        y1: i32(bytes, offset + 4),
                        x2: i32(bytes, offset + 8),
                        y2: i32(bytes, offset + 12),
                    });
                }
                const color = u32(bytes, payloadOffset + 8);
                const depth = f32(bytes, payloadOffset + 12);
                const stencil = u32(bytes, payloadOffset + 16);
                const clear = {};
                if (flags & D3DCLEAR_TARGET) {
                    clear.color = d3dColor(color);
                    // Keep the canonical save-state shadow coherent for the
                    // supported A8/X8 lockable render-target formats.
                    this.mirrorRenderTargetClear(state, color, rectangles);
                }
                if (flags & D3DCLEAR_ZBUFFER)
                    clear.depth = depth;
                if (flags & D3DCLEAR_STENCIL)
                    clear.stencil = stencil;
                if ((flags & (D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL)) &&
                        !state.depthView) {
                    this.warnOnce("depth-clear-without-surface",
                        "depth/stencil Clear ignored because the device has no automatic depth surface");
                    delete clear.depth;
                    delete clear.stencil;
                }
                if (rectangles.length)
                    this.clearRectangles(state, flags, color, depth,
                        stencil, rectangles);
                else
                    this.ensureFrame(state, clear);
                break;
            }
            case OP_BEGIN_SCENE:
            case OP_END_SCENE: {
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("scene command references an unknown device");
                state.inScene = opcode === OP_BEGIN_SCENE;
                break;
            }
            case OP_CREATE_BUFFER: {
                if (commandEnd - payloadOffset < 32) throw new Error("short CREATE_BUFFER");
                const deviceHandle = u32(bytes, payloadOffset);
                const handle = u32(bytes, payloadOffset + 4);
                const kind = u32(bytes, payloadOffset + 8);
                const byteCount = u32(bytes, payloadOffset + 12);
                if (kind !== RESOURCE_BUFFER_VERTEX &&
                    kind !== RESOURCE_BUFFER_INDEX) {
                    throw new Error("unknown D8WG buffer kind " + kind);
                }
                if (!this.devices.has(deviceHandle))
                    throw new Error("CREATE_BUFFER references an unknown device");
                const format = u32(bytes, payloadOffset + 20);
                if (kind === RESOURCE_BUFFER_INDEX && !indexFormatInfo(format)) {
                    throw new Error("invalid D8WG index buffer format " + format);
                }
                this.destroyResource(handle);
                this.resources.set(handle, {
                    handle,
                    deviceHandle,
                    kind,
                    byteCount,
                    usage: u32(bytes, payloadOffset + 16),
                    pool: u32(bytes, payloadOffset + 24),
                    fvf: kind === RESOURCE_BUFFER_VERTEX ? format : 0,
                    format: kind === RESOURCE_BUFFER_INDEX ? format : 0,
                    shadow: new Uint8Array(align4(byteCount)),
                    gpuBuffer: this.device.createBuffer({
                        label: "D3D8 " + (kind === RESOURCE_BUFFER_VERTEX ?
                            "vertex" : "index") + " buffer " + handle.toString(16),
                        size: Math.max(4, align4(byteCount)),
                        usage: (kind === RESOURCE_BUFFER_VERTEX ?
                            BUFFER_USAGE_VERTEX : BUFFER_USAGE_INDEX) |
                            BUFFER_USAGE_COPY_DST,
                    }),
                });
                break;
            }
            case OP_UPDATE_BUFFER: {
                if (commandEnd - payloadOffset < 24) throw new Error("short UPDATE_BUFFER");
                const resource = this.resources.get(u32(bytes, payloadOffset));
                if (!resource) throw new Error("UPDATE_BUFFER references an unknown resource");
                const destination = u32(bytes, payloadOffset + 4);
                const byteCount = u32(bytes, payloadOffset + 8);
                const dataOffset = u32(bytes, payloadOffset + 12);
                const lockFlags = u32(bytes, payloadOffset + 16);
                if (dataOffset > bytes.length || byteCount > bytes.length - dataOffset ||
                    destination > resource.byteCount ||
                    byteCount > resource.byteCount - destination) {
                    throw new Error("UPDATE_BUFFER range is outside its batch/resource");
                }
                if (lockFlags & D3DLOCK_DISCARD) {
                    const previous = resource.gpuBuffer;
                    resource.shadow.fill(0);
                    resource.gpuBuffer = this.device.createBuffer({
                        label: "D3D8 orphaned " +
                            (resource.kind === RESOURCE_BUFFER_VERTEX ?
                                "vertex" : "index") + " buffer " +
                            resource.handle.toString(16),
                        size: Math.max(4, align4(resource.byteCount)),
                        usage: (resource.kind === RESOURCE_BUFFER_VERTEX ?
                            BUFFER_USAGE_VERTEX : BUFFER_USAGE_INDEX) |
                            BUFFER_USAGE_COPY_DST,
                    });
                    if (this.frame)
                        this.frame.transientBuffers.push(previous);
                    else
                        this.retireGPUObjects(previous);
                    this.stats.bufferOrphans++;
                }
                resource.shadow.set(
                    bytes.subarray(dataOffset, dataOffset + byteCount), destination);
                const alignedStart = destination & ~3;
                const alignedEnd = align4(destination + byteCount);
                const source = resource.shadow.subarray(alignedStart, alignedEnd);
                if (source.byteLength && this.frame) {
                    this.endPass();
                    const staging = this.createTransientBuffer(source,
                        BUFFER_USAGE_COPY_SRC,
                        "D3D8 ordered buffer upload staging");
                    this.frame.encoder.copyBufferToBuffer(staging.buffer,
                        staging.offset,
                        resource.gpuBuffer, alignedStart, source.byteLength);
                } else if (source.byteLength) {
                    this.device.queue.writeBuffer(resource.gpuBuffer,
                        alignedStart, source);
                }
                this.stats.uploadBytes += byteCount;
                break;
            }
            case OP_CREATE_TEXTURE:
                this.createTextureResource(bytes, payloadOffset, commandEnd);
                break;
            case OP_UPDATE_TEXTURE:
                this.updateTextureResource(bytes, payloadOffset, commandEnd);
                break;
            case OP_CREATE_VERTEX_SHADER:
                this.createVertexShaderResource(bytes, payloadOffset,
                    commandEnd);
                break;
            case OP_CREATE_PIXEL_SHADER:
                this.createPixelShaderResource(bytes, payloadOffset,
                    commandEnd);
                break;
            case OP_DESTROY_RESOURCE:
                if (commandEnd - payloadOffset < 8) {
                    throw new Error("short DESTROY_RESOURCE");
                }
                this.destroyResource(u32(bytes, payloadOffset));
                break;
            case OP_SET_RENDER_STATE: {
                const state = this.devices.get(u32(bytes, payloadOffset));
                const index = u32(bytes, payloadOffset + 4);
                if (!state || index >= state.renderStates.length) {
                    throw new Error("invalid SET_RENDER_STATE");
                }
                const value = u32(bytes, payloadOffset + 8);
                if (state.renderStates[index] === value) {
                    // Host-side dead-store elimination. The guest already
                    // suppresses redundant setters, but state-block replay and
                    // Reset restoration legitimately resend whole banks.
                    this.stats.redundantStateWrites++;
                    break;
                }
                state.renderStates[index] = value;
                // Only bump the uniform serial for render states the uniform
                // block actually contains; blend/cull/depth/stencil and the
                // rest are pipeline state and would otherwise force a
                // needless uniform repack and upload on every change.
                if (UNIFORM_RENDER_STATES[index]) state.uniformSerial++;
                break;
            }
            case OP_SET_TEXTURE_STAGE_STATE: {
                const state = this.devices.get(u32(bytes, payloadOffset));
                const stage = u32(bytes, payloadOffset + 4);
                const index = u32(bytes, payloadOffset + 8);
                if (!state || stage >= 8 || index >= 32) {
                    throw new Error("invalid SET_TEXTURE_STAGE_STATE");
                }
                state.textureStageStates[stage][index] = u32(bytes, payloadOffset + 12);
                break;
            }
            case OP_SET_TEXTURE: {
                if (commandEnd - payloadOffset < 16)
                    throw new Error("short SET_TEXTURE");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const stage = u32(bytes, payloadOffset + 4);
                const handle = u32(bytes, payloadOffset + 8);
                const resource = handle ? this.resources.get(handle) : null;
                if (!state || stage >= state.textures.length ||
                        (handle && (!resource ||
                            resource.kind !== RESOURCE_TEXTURE_2D ||
                            resource.deviceHandle !== state.handle)))
                    throw new Error("invalid SET_TEXTURE");
                state.textures[stage] = handle;
                break;
            }
            case OP_SET_VIEWPORT: {
                if (commandEnd - payloadOffset < 32)
                    throw new Error("short SET_VIEWPORT");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const width = u32(bytes, payloadOffset + 12);
                const height = u32(bytes, payloadOffset + 16);
                const minZ = f32(bytes, payloadOffset + 20);
                const maxZ = f32(bytes, payloadOffset + 24);
                if (!state || !width || !height || !Number.isFinite(minZ) ||
                        !Number.isFinite(maxZ) || minZ < 0 || maxZ > 1 ||
                        minZ > maxZ)
                    throw new Error("invalid SET_VIEWPORT");
                state.viewport = {
                    x: u32(bytes, payloadOffset + 4),
                    y: u32(bytes, payloadOffset + 8),
                    width,
                    height,
                    minZ,
                    maxZ,
                };
                break;
            }
            case OP_SET_TRANSFORM: {
                if (commandEnd - payloadOffset < 72)
                    throw new Error("short SET_TRANSFORM");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const transformState = u32(bytes, payloadOffset + 4);
                if (!state) throw new Error("invalid SET_TRANSFORM device");
                const matrix = new Float32Array(16);
                for (let index = 0; index < 16; index++) {
                    const value = f32(bytes, payloadOffset + 8 + index * 4);
                    if (!Number.isFinite(value))
                        throw new Error("SET_TRANSFORM contains a non-finite matrix");
                    matrix[index] = value;
                }
                if (transformState === 2)
                    state.transforms.view = matrix;
                else if (transformState === 3)
                    state.transforms.projection = matrix;
                else if (transformState >= 16 && transformState <= 23)
                    state.transforms.textures[transformState - 16] = matrix;
                else if (transformState >= 256 && transformState < 512) {
                    if (transformState === 256)
                        state.transforms.world = matrix;
                    else
                        this.warnOnce("world-transform-" + transformState,
                            "indexed world transform is stored but vertex blending is not yet enabled",
                            transformState);
                } else {
                    throw new Error("invalid D3D8 transform state " + transformState);
                }
                state.uniformSerial++;
                break;
            }
            case OP_SET_MATERIAL: {
                if (commandEnd - payloadOffset < 72)
                    throw new Error("short SET_MATERIAL");
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("invalid SET_MATERIAL device");
                const read = (offset, count) => Array.from({ length: count },
                    (_, index) => f32(bytes, payloadOffset + offset + index * 4));
                const values = read(4, 17);
                if (!values.every(Number.isFinite))
                    throw new Error("SET_MATERIAL contains a non-finite value");
                state.material = {
                    diffuse: values.slice(0, 4),
                    ambient: values.slice(4, 8),
                    specular: values.slice(8, 12),
                    emissive: values.slice(12, 16),
                    power: values[16],
                };
                state.uniformSerial++;
                break;
            }
            case OP_SET_LIGHT: {
                if (commandEnd - payloadOffset < 112)
                    throw new Error("short SET_LIGHT");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const index = u32(bytes, payloadOffset + 4);
                const type = u32(bytes, payloadOffset + 8);
                if (!state || index >= state.lights.length ||
                        type < 1 || type > 3)
                    throw new Error("invalid SET_LIGHT");
                const read = (offset, count) => Array.from({ length: count },
                    (_, item) => f32(bytes, payloadOffset + offset + item * 4));
                const values = read(12, 25);
                if (!values.every(Number.isFinite))
                    throw new Error("SET_LIGHT contains a non-finite value");
                const enabled = state.lights[index].enabled;
                state.lights[index] = {
                    type,
                    diffuse: values.slice(0, 4),
                    specular: values.slice(4, 8),
                    ambient: values.slice(8, 12),
                    position: values.slice(12, 15),
                    direction: values.slice(15, 18),
                    range: values[18], falloff: values[19],
                    attenuation: values.slice(20, 23),
                    theta: values[23], phi: values[24], enabled,
                };
                state.uniformSerial++;
                break;
            }
            case OP_LIGHT_ENABLE: {
                if (commandEnd - payloadOffset < 16)
                    throw new Error("short LIGHT_ENABLE");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const index = u32(bytes, payloadOffset + 4);
                if (!state || index >= state.lights.length)
                    throw new Error("invalid LIGHT_ENABLE");
                state.lights[index].enabled = !!u32(bytes, payloadOffset + 8);
                state.uniformSerial++;
                break;
            }
            case OP_SET_STREAM_SOURCE: {
                const state = this.devices.get(u32(bytes, payloadOffset));
                const stream = u32(bytes, payloadOffset + 4);
                if (!state || stream >= state.streams.length) {
                    throw new Error("invalid SET_STREAM_SOURCE");
                }
                state.streams[stream] = {
                    handle: u32(bytes, payloadOffset + 8),
                    stride: u32(bytes, payloadOffset + 12),
                };
                break;
            }
            case OP_SET_INDICES: {
                if (commandEnd - payloadOffset < 16) throw new Error("short SET_INDICES");
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("invalid SET_INDICES device");
                state.indices = {
                    handle: u32(bytes, payloadOffset + 4),
                    baseVertex: u32(bytes, payloadOffset + 8),
                };
                break;
            }
            case OP_SET_VERTEX_FORMAT: {
                const state = this.devices.get(u32(bytes, payloadOffset));
                if (!state) throw new Error("invalid SET_VERTEX_FORMAT");
                state.fvf = u32(bytes, payloadOffset + 4);
                break;
            }
            case OP_SET_RENDER_TARGET: {
                if (commandEnd - payloadOffset < 16)
                    throw new Error("short SET_RENDER_TARGET");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const handle = u32(bytes, payloadOffset + 4);
                const level = u32(bytes, payloadOffset + 8);
                const resource = handle ? this.resources.get(handle) : null;
                if (!state || (handle && (!resource ||
                        resource.deviceHandle !== state.handle ||
                        resource.kind !== RESOURCE_TEXTURE_2D ||
                        !(resource.usage & D3DUSAGE_RENDERTARGET) ||
                        level >= resource.levelCount)))
                    throw new Error("invalid SET_RENDER_TARGET");
                if (this.frame) this.finishFrame(false);
                state.renderTarget = { handle, level };
                state.depthSurfaceEnabled = !!u32(bytes, payloadOffset + 12);
                break;
            }
            case OP_SET_VERTEX_SHADER: {
                if (commandEnd - payloadOffset < 8)
                    throw new Error("short SET_VERTEX_SHADER");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const handle = u32(bytes, payloadOffset + 4);
                const resource = handle ? this.resources.get(handle) : null;
                if (!state || (handle && (!resource ||
                        resource.kind !== RESOURCE_VERTEX_SHADER ||
                        resource.deviceHandle !== state.handle)))
                    throw new Error("invalid SET_VERTEX_SHADER");
                state.vertexShader = handle;
                break;
            }
            case OP_SET_PIXEL_SHADER: {
                if (commandEnd - payloadOffset < 8)
                    throw new Error("short SET_PIXEL_SHADER");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const handle = u32(bytes, payloadOffset + 4);
                const resource = handle ? this.resources.get(handle) : null;
                if (!state || (handle && (!resource ||
                        resource.kind !== RESOURCE_PIXEL_SHADER ||
                        resource.deviceHandle !== state.handle)))
                    throw new Error("invalid SET_PIXEL_SHADER");
                state.pixelShader = handle;
                break;
            }
            case OP_SET_VERTEX_SHADER_CONSTANT:
            case OP_SET_PIXEL_SHADER_CONSTANT: {
                if (commandEnd - payloadOffset < 16)
                    throw new Error("short SET_SHADER_CONSTANT");
                const state = this.devices.get(u32(bytes, payloadOffset));
                const startRegister = u32(bytes, payloadOffset + 4);
                const vectorCount = u32(bytes, payloadOffset + 8);
                const dataOffset = u32(bytes, payloadOffset + 12);
                const isVertex = opcode === OP_SET_VERTEX_SHADER_CONSTANT;
                const maxRegisters = isVertex ?
                    D8WG_MAX_VS_CONSTANTS : D8WG_MAX_PS_CONSTANTS;
                if (!state || startRegister > maxRegisters ||
                        vectorCount > maxRegisters - startRegister)
                    throw new Error("invalid SET_SHADER_CONSTANT range");
                const data = checkedDataRange(bytes, dataOffset,
                    vectorCount * 16, "SET_SHADER_CONSTANT data");
                const target = isVertex ? state.vsConstants : state.psConstants;
                for (let i = 0; i < vectorCount * 4; i++)
                    target[startRegister * 4 + i] = f32(data, i * 4);
                state.shaderConstantSerial++;
                break;
            }
            case OP_DRAW_PRIMITIVE:
                if (commandEnd - payloadOffset < 16) throw new Error("short DRAW_PRIMITIVE");
                this.drawPrimitive(bytes, payloadOffset);
                break;
            case OP_DRAW_INDEXED_PRIMITIVE:
                if (commandEnd - payloadOffset < 24) {
                    throw new Error("short DRAW_INDEXED_PRIMITIVE");
                }
                this.drawIndexedPrimitive(bytes, payloadOffset);
                break;
            case OP_DRAW_PRIMITIVE_UP:
                if (commandEnd - payloadOffset < 32) {
                    throw new Error("short DRAW_PRIMITIVE_UP");
                }
                this.drawPrimitiveUP(bytes, payloadOffset);
                break;
            case OP_DRAW_INDEXED_PRIMITIVE_UP:
                if (commandEnd - payloadOffset < 48) {
                    throw new Error("short DRAW_INDEXED_PRIMITIVE_UP");
                }
                this.drawIndexedPrimitiveUP(bytes, payloadOffset);
                break;
            default:
                this.warnOnce("opcode-" + opcode,
                    "unsupported D8WG opcode", "0x" + opcode.toString(16));
                this.stats.unsupportedCommands++;
                break;
            }
            void commandOffset;
        }

        executeBatch(bytes, metadata) {
            if (bytes.length < D8WG_BATCH_HEADER_BYTES) {
                this.stats.malformedBatches++;
                throw new Error("D8WG batch header is truncated");
            }
            if (u32(bytes, 0) !== D8WG_MAGIC) {
                this.stats.malformedBatches++;
                throw new Error("D8WG magic mismatch");
            }
            if (u16(bytes, 4) !== D8WG_VERSION_MAJOR) {
                this.stats.malformedBatches++;
                throw new Error("unsupported D8WG major version " + u16(bytes, 4));
            }
            if (u16(bytes, 6) !== D8WG_VERSION_MINOR) {
                this.stats.malformedBatches++;
                throw new Error("unsupported D8WG minor version " + u16(bytes, 6));
            }
            const session = this.activateSession(u32(bytes, 24),
                u32(bytes, 28));
            const expectedCount = u32(bytes, 16);
            const commandBytes = u32(bytes, 20);
            if (commandBytes > bytes.length - D8WG_BATCH_HEADER_BYTES) {
                this.stats.malformedBatches++;
                throw new Error("D8WG command region is truncated");
            }
            const end = D8WG_BATCH_HEADER_BYTES + commandBytes;
            let offset = D8WG_BATCH_HEADER_BYTES;
            let decoded = 0;
            if (!session.helloSeen && expectedCount &&
                    u16(bytes, offset) !== OP_HELLO) {
                throw new Error("D8WG process session began without HELLO");
            }
            while (offset < end) {
                if (end - offset < D8WG_COMMAND_HEADER_BYTES) {
                    throw new Error("D8WG command header is truncated");
                }
                const opcode = u16(bytes, offset);
                const size = u32(bytes, offset + 4);
                if (size < D8WG_COMMAND_HEADER_BYTES || (size & 7) || size > end - offset) {
                    throw new Error("invalid D8WG command size " + size);
                }
                this.executeCommand(bytes, offset, opcode,
                    offset + D8WG_COMMAND_HEADER_BYTES, offset + size);
                offset += size;
                decoded++;
            }
            if (decoded !== expectedCount) {
                throw new Error("D8WG command count mismatch: expected " +
                    expectedCount + ", decoded " + decoded);
            }
            this.stats.batches++;
            this.stats.commands += decoded;
            if (this.options.trace) {
                console.info("[d3d8-webgpu] batch", {
                    frameId: u32(bytes, 8),
                    session: session.key,
                    flags: u32(bytes, 12),
                    commandCount: decoded,
                    commandBytes,
                    pci: metadata,
                });
            }
            return decoded;
        }

        serializeSession(session) {
            this.setActiveSession(session, false);
            const records = [];
            const makePayload = byteLength => new Uint8Array(byteLength);
            const putU32 = (payload, offset, value) =>
                new DataView(payload.buffer, payload.byteOffset,
                    payload.byteLength).setUint32(offset, value >>> 0, true);
            const putI32 = (payload, offset, value) =>
                new DataView(payload.buffer, payload.byteOffset,
                    payload.byteLength).setInt32(offset, value | 0, true);
            const putF32 = (payload, offset, value) =>
                new DataView(payload.buffer, payload.byteOffset,
                    payload.byteLength).setFloat32(offset, value, true);
            const u32Payload = (...values) => {
                const payload = makePayload(values.length * 4);
                values.forEach((value, index) => putU32(payload,
                    index * 4, value));
                return payload;
            };
            // dataOffsetField is either a single payload offset to patch with
            // the blob's batch-relative address, or an array of
            // {field, delta} for a payload that points at several regions
            // inside one concatenated blob (CREATE_VERTEX_SHADER).
            const add = (opcode, payload, blob, dataOffsetField) => {
                records.push({ opcode, payload, blob: blob || null,
                    dataOffsetField });
            };
            const tokenBlob = tokens => {
                const blob = makePayload(tokens.length * 4);
                tokens.forEach((token, index) =>
                    putU32(blob, index * 4, token));
                return blob;
            };
            const concatBlobs = (first, second) => {
                const blob = makePayload(first.byteLength + second.byteLength);
                blob.set(first, 0);
                blob.set(second, first.byteLength);
                return blob;
            };
            const addTransform = (handle, transformState, matrix) => {
                const payload = makePayload(72);
                putU32(payload, 0, handle);
                putU32(payload, 4, transformState);
                for (let index = 0; index < 16; index++)
                    putF32(payload, 8 + index * 4, matrix[index]);
                add(OP_SET_TRANSFORM, payload);
            };

            add(OP_HELLO, u32Payload(32, 0, session.low, session.high));

            for (const state of this.devices.values()) {
                const surface = state.surface;
                const create = makePayload(44);
                putU32(create, 0, state.handle);
                putU32(create, 4, surface.hwnd);
                putI32(create, 8, surface.x);
                putI32(create, 12, surface.y);
                putU32(create, 16, surface.width);
                putU32(create, 20, surface.height);
                putU32(create, 24, surface.format);
                putU32(create, 28, surface.windowed ? 1 : 0);
                putU32(create, 32, surface.behaviorFlags);
                putU32(create, 36, surface.autoDepthStencil ? 1 : 0);
                putU32(create, 40, surface.autoDepthStencilFormat);
                add(OP_CREATE_DEVICE, create);

                for (const resource of this.resources.values()) {
                    if (resource.deviceHandle !== state.handle) continue;
                    if (resource.kind === RESOURCE_BUFFER_VERTEX ||
                            resource.kind === RESOURCE_BUFFER_INDEX) {
                        add(OP_CREATE_BUFFER, u32Payload(state.handle,
                            resource.handle, resource.kind,
                            resource.byteCount, resource.usage,
                            resource.kind === RESOURCE_BUFFER_VERTEX ?
                                resource.fvf : resource.format,
                            resource.pool, 0));
                        add(OP_UPDATE_BUFFER, u32Payload(resource.handle, 0,
                            resource.byteCount, 0, 0, 0),
                            resource.shadow.subarray(0, resource.byteCount), 12);
                    } else if (resource.kind === RESOURCE_TEXTURE_2D) {
                        add(OP_CREATE_TEXTURE, u32Payload(state.handle,
                            resource.handle, resource.width, resource.height,
                            resource.levelCount, resource.format,
                            resource.usage, resource.pool));
                        resource.shadowLevels.forEach((level, levelIndex) => {
                            add(OP_UPDATE_TEXTURE, u32Payload(resource.handle,
                                levelIndex, 0, 0, level.width, level.height,
                                level.rowPitch, level.data.byteLength, 0, 0),
                                level.data, 32);
                        });
                    } else if (resource.kind === RESOURCE_VERTEX_SHADER) {
                        const declaration = tokenBlob(resource.declTokens);
                        const code = tokenBlob(resource.codeTokens);
                        add(OP_CREATE_VERTEX_SHADER, u32Payload(state.handle,
                            resource.handle, resource.declTokens.length, 0,
                            resource.codeTokens.length, 0),
                            concatBlobs(declaration, code),
                            [{ field: 12, delta: 0 },
                                { field: 20, delta: declaration.byteLength }]);
                    } else if (resource.kind === RESOURCE_PIXEL_SHADER) {
                        add(OP_CREATE_PIXEL_SHADER, u32Payload(state.handle,
                            resource.handle, resource.codeTokens.length, 0),
                            tokenBlob(resource.codeTokens), 12);
                    }
                }

                for (let index = 0; index < state.renderStates.length; index++)
                    add(OP_SET_RENDER_STATE, u32Payload(state.handle, index,
                        state.renderStates[index], 0));
                for (let stage = 0; stage < 8; stage++) {
                    for (let index = 0; index < 32; index++) {
                        add(OP_SET_TEXTURE_STAGE_STATE, u32Payload(state.handle,
                            stage, index,
                            state.textureStageStates[stage][index]));
                    }
                }
                const viewport = makePayload(32);
                putU32(viewport, 0, state.handle);
                putU32(viewport, 4, state.viewport.x);
                putU32(viewport, 8, state.viewport.y);
                putU32(viewport, 12, state.viewport.width);
                putU32(viewport, 16, state.viewport.height);
                putF32(viewport, 20, state.viewport.minZ);
                putF32(viewport, 24, state.viewport.maxZ);
                add(OP_SET_VIEWPORT, viewport);
                addTransform(state.handle, 256, state.transforms.world);
                addTransform(state.handle, 2, state.transforms.view);
                addTransform(state.handle, 3, state.transforms.projection);
                state.transforms.textures.forEach((matrix, index) =>
                    addTransform(state.handle, 16 + index, matrix));

                const material = makePayload(72);
                putU32(material, 0, state.handle);
                [state.material.diffuse, state.material.ambient,
                    state.material.specular, state.material.emissive]
                    .forEach((values, group) => values.forEach((value, index) =>
                        putF32(material, 4 + group * 16 + index * 4, value)));
                putF32(material, 68, state.material.power);
                add(OP_SET_MATERIAL, material);
                state.lights.forEach((light, index) => {
                    if (!light.type) return;
                    const payload = makePayload(112);
                    putU32(payload, 0, state.handle);
                    putU32(payload, 4, index);
                    putU32(payload, 8, light.type);
                    [light.diffuse, light.specular, light.ambient]
                        .forEach((values, group) => values.forEach(
                            (value, item) => putF32(payload,
                                12 + group * 16 + item * 4, value)));
                    light.position.forEach((value, item) =>
                        putF32(payload, 60 + item * 4, value));
                    light.direction.forEach((value, item) =>
                        putF32(payload, 72 + item * 4, value));
                    putF32(payload, 84, light.range);
                    putF32(payload, 88, light.falloff);
                    light.attenuation.forEach((value, item) =>
                        putF32(payload, 92 + item * 4, value));
                    putF32(payload, 104, light.theta);
                    putF32(payload, 108, light.phi);
                    add(OP_SET_LIGHT, payload);
                    if (light.enabled)
                        add(OP_LIGHT_ENABLE, u32Payload(state.handle,
                            index, 1, 0));
                });
                for (let stage = 0; stage < state.textures.length; stage++)
                    add(OP_SET_TEXTURE, u32Payload(state.handle, stage,
                        state.textures[stage], 0));
                state.streams.forEach((stream, index) =>
                    add(OP_SET_STREAM_SOURCE, u32Payload(state.handle, index,
                        stream.handle, stream.stride)));
                add(OP_SET_INDICES, u32Payload(state.handle,
                    state.indices.handle, state.indices.baseVertex, 0));
                add(OP_SET_VERTEX_FORMAT, u32Payload(state.handle, state.fvf));
                // Constant banks first: a restored shader must see the same
                // constants it had at save time before anything draws with it.
                const constantBlob = values => {
                    const blob = makePayload(values.byteLength);
                    values.forEach((value, index) =>
                        putF32(blob, index * 4, value));
                    return blob;
                };
                add(OP_SET_VERTEX_SHADER_CONSTANT, u32Payload(state.handle, 0,
                    D8WG_MAX_VS_CONSTANTS, 0),
                    constantBlob(state.vsConstants), 12);
                add(OP_SET_PIXEL_SHADER_CONSTANT, u32Payload(state.handle, 0,
                    D8WG_MAX_PS_CONSTANTS, 0),
                    constantBlob(state.psConstants), 12);
                if (state.vertexShader)
                    add(OP_SET_VERTEX_SHADER, u32Payload(state.handle,
                        state.vertexShader));
                if (state.pixelShader)
                    add(OP_SET_PIXEL_SHADER, u32Payload(state.handle,
                        state.pixelShader));
                add(OP_SET_RENDER_TARGET, u32Payload(state.handle,
                    state.renderTarget.handle, state.renderTarget.level,
                    state.depthSurfaceEnabled ? 1 : 0));
                if (state.inScene)
                    add(OP_BEGIN_SCENE, u32Payload(state.handle, 0));
            }

            let commandBytes = 0;
            for (const record of records) {
                record.size = (D8WG_COMMAND_HEADER_BYTES +
                    record.payload.byteLength +
                    (record.blob ? record.blob.byteLength : 0) + 7) & ~7;
                record.offset = D8WG_BATCH_HEADER_BYTES + commandBytes;
                commandBytes += record.size;
            }
            const result = new Uint8Array(D8WG_BATCH_HEADER_BYTES +
                commandBytes);
            const view = new DataView(result.buffer);
            view.setUint32(0, D8WG_MAGIC, true);
            view.setUint16(4, D8WG_VERSION_MAJOR, true);
            view.setUint16(6, D8WG_VERSION_MINOR, true);
            view.setUint32(16, records.length, true);
            view.setUint32(20, commandBytes, true);
            view.setUint32(24, session.low, true);
            view.setUint32(28, session.high, true);
            let sequence = 1;
            for (const record of records) {
                if (record.blob && record.dataOffsetField !== undefined) {
                    const blobBase = record.offset + D8WG_COMMAND_HEADER_BYTES +
                        record.payload.byteLength;
                    if (Array.isArray(record.dataOffsetField)) {
                        for (const { field, delta } of record.dataOffsetField)
                            putU32(record.payload, field, blobBase + delta);
                    } else {
                        putU32(record.payload, record.dataOffsetField, blobBase);
                    }
                }
                view.setUint16(record.offset, record.opcode, true);
                view.setUint32(record.offset + 4, record.size, true);
                view.setUint32(record.offset + 8, sequence++, true);
                result.set(record.payload,
                    record.offset + D8WG_COMMAND_HEADER_BYTES);
                if (record.blob) {
                    result.set(record.blob, record.offset +
                        D8WG_COMMAND_HEADER_BYTES + record.payload.byteLength);
                }
            }
            return result;
        }

        serializeState() {
            if (this.pendingSubmissions)
                throw new Error("D3D8 commands are still in flight; retry the save");
            if (this.frame)
                throw new Error("D3D8 has an unfinished frame; retry the save");

            const original = this.activeSession;
            const batches = [];
            for (const session of this.sessions.values()) {
                if (!session.devices.size && !session.resources.size) continue;
                batches.push(this.serializeSession(session));
            }
            if (original) this.setActiveSession(original, false);

            let byteLength = 16;
            for (const batch of batches)
                byteLength += 8 + ((batch.byteLength + 7) & ~7);
            const result = new Uint8Array(byteLength);
            const view = new DataView(result.buffer);
            view.setUint32(0, D8WG_CHECKPOINT_MAGIC, true);
            view.setUint16(4, D8WG_CHECKPOINT_VERSION, true);
            view.setUint32(8, batches.length, true);
            view.setUint32(12, byteLength, true);
            let offset = 16;
            for (const batch of batches) {
                view.setUint32(offset, batch.byteLength, true);
                result.set(batch, offset + 8);
                offset += 8 + ((batch.byteLength + 7) & ~7);
            }
            return result;
        }

        clearAllSessions() {
            this.discardFrame();
            for (const session of Array.from(this.sessions.values())) {
                this.setActiveSession(session, false);
                for (const handle of Array.from(session.devices.keys()))
                    this.destroyResource(handle);
                for (const handle of Array.from(session.resources.keys()))
                    this.destroyResource(handle);
            }
            this.sessions.clear();
            this.activeSession = null;
            this.devices = new Map();
            this.resources = new Map();
            this.retiredDeviceHandles = new Set();
            this.retiredResourceHandles = new Set();
        }

        restoreStateInitialized(checkpoint) {
            this.clearAllSessions();
            const bytes = checkpoint instanceof Uint8Array ? checkpoint :
                new Uint8Array(checkpoint || []);
            if (!bytes.byteLength) return;
            if (bytes.byteLength >= D8WG_BATCH_HEADER_BYTES &&
                    u32(bytes, 0) === D8WG_MAGIC) {
                this.executeBatch(bytes, { stateRestore: true });
                return;
            }
            if (bytes.byteLength < 16 ||
                    u32(bytes, 0) !== D8WG_CHECKPOINT_MAGIC ||
                    u16(bytes, 4) !== D8WG_CHECKPOINT_VERSION ||
                    u32(bytes, 12) !== bytes.byteLength) {
                throw new Error("invalid D3D8 multi-session checkpoint");
            }
            const count = u32(bytes, 8);
            let offset = 16;
            for (let index = 0; index < count; index++) {
                if (offset + 8 > bytes.byteLength)
                    throw new Error("truncated D3D8 checkpoint record");
                const size = u32(bytes, offset);
                if (size < D8WG_BATCH_HEADER_BYTES ||
                        size > bytes.byteLength - offset - 8) {
                    throw new Error("invalid D3D8 checkpoint record size");
                }
                this.executeBatch(bytes.subarray(offset + 8,
                    offset + 8 + size), { stateRestore: true, index });
                offset += 8 + ((size + 7) & ~7);
            }
            if (offset !== bytes.byteLength)
                throw new Error("D3D8 checkpoint has trailing data");
        }

        restoreState(checkpoint) {
            const owned = checkpoint instanceof Uint8Array ? checkpoint.slice() :
                new Uint8Array(checkpoint || []).slice();
            // Serialize restore against already accepted submissions. Callers may
            // invoke this on a brand-new executor, so acquire/configure WebGPU
            // before clearAllSessions() can mutate the live logical namespace.
            // Assign the guarded barrier to `work` immediately: any later submit
            // is forced behind the complete checkpoint replay.
            const operation = this.work.then(async () => {
                if (owned.byteLength) await this.initialize();
                this.restoreStateInitialized(owned);
                this.failed = null;
            });
            this.work = operation.catch(error => {
                this.failed = error;
            });
            return operation;
        }

        getStats() {
            let bindGroupsCached = 0;
            let devicesLive = 0;
            let resourcesLive = 0;
            let sessionsLive = 0;
            for (const session of this.sessions.values()) {
                devicesLive += session.devices.size;
                resourcesLive += session.resources.size;
                if (session.devices.size || session.resources.size)
                    sessionsLive++;
                for (const state of session.devices.values()) {
                    bindGroupsCached += state.bindGroups.size;
                }
            }
            return {
                ...this.stats,
                sessionsLive,
                sessionsTracked: this.sessions.size,
                devicesLive,
                resourcesLive,
                pipelinesCached: this.pipelineCache.size,
                samplersCached: this.samplerCache.size,
                bindGroupsCached,
            };
        }
    }

    global.D3D8WebGPUExecutor = D3D8WebGPUExecutor;
    global.installD3D8WebGPUExecutor = function(canvas, options) {
        return new D3D8WebGPUExecutor(canvas, options);
    };

    if (typeof module !== "undefined" && module.exports) {
        module.exports = {
            D3D8WebGPUExecutor,
            D8WG_MAGIC,
            D8WG_VERSION_MAJOR,
            D8WG_VERSION_MINOR,
            D8WG_BATCH_HEADER_BYTES,
            D8WG_COMMAND_HEADER_BYTES,
            // Stage 6: exposed for direct unit testing of the VS1.1/PS1.1-1.4
            // -> WGSL translator, independent of a real WebGPU device.
            shaderOpcodeInfo,
            parseVertexDeclaration,
            vertexShaderWgsl,
            pixelShaderWgsl,
            shaderPipelineWgsl,
        };
    }
})(typeof window !== "undefined" ? window : globalThis);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/browser/glbridge/d3d9-webgpu/d3d9_executor.js                                        0000644 0000000 0000000 00002437207 00000000000 021005  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // D9WG high-level Direct3D 9 command executor -- M1 skeleton.
//
// The guest DLL (glbridge/d3d9proxy/d3d9_proxy.c) keeps COM objects, shadow
// state, Lock/Unlock memory and batching inside Windows XP. This host owns
// only WebGPU resources and immutable cache objects, mirroring the D3D8
// path's division of responsibility (see ../d3d8-webgpu/d3d8_executor.js)
// but as an independent protocol/implementation: D9WG has its own opcode
// numbering, resource handle namespace and payload shapes (d3d9_protocol.h).
//
// M1 scope: batch decode, a resource table for vertex/index buffers, 2D
// textures and vertex declarations, WebGPU device lifecycle, and the
// fixed-function XYZ/XYZRHW draw path with no programmable shaders.
//
// M2 adds shader model 2.0: CREATE/SET_{VERTEX,PIXEL}_SHADER translated to
// WGSL by d3d9_shader_pipeline.js, the float/int/bool constant register file
// packed into a uniform buffer (plan 9.7), independent sampler state driving
// a GPUSampler cache (plan 4.4/12), and multi-stream vertex declarations.
//
// M3 finishes the fixed-function pipeline, which until then stored a great deal
// of state it never acted on: vertex lighting (SetLight/SetMaterial/
// LightEnable, computed in view space as D3D9 does), the whole D3DTOP_*
// texture-blending cascade across up to eight stages, per-stage coordinate
// selection/generation/transform, cube textures, and the scissor rect. It also
// brings render targets, depth surfaces and MRT forward from M4 -- a 2005-era
// D3D9 game renders most of its frame into textures, so without them it has no
// picture at all -- plus per-process session isolation and device-loss
// recovery, both M1 leftovers.
//
// The fixed-function and programmable paths are one path, not two. Both
// stages are always separate GPUShaderModules meeting over a fixed
// inter-stage varying contract (COLOR0/COLOR1 at locations 0-1, TEXCOORD0..7
// at 2-9, FOG at 10 -- see VARYING_* in d3d9_shader_pipeline.js), with the
// fixed-function stage synthesised into a module that obeys the same
// contract. That is what makes the mixed configurations D3D9 allows work at
// all: fixed-function T&L feeding a real pixel shader, or a vertex shader
// feeding the fixed-function texture pipeline, are both routine in games of
// this era and neither would link if each path had its own varying layout.
//
// Every other D9WG opcode already has a number reserved in d3d9_protocol.h
// for a later milestone, but the guest never emits it yet, so this executor
// does not need a handler for it -- unknown/future opcodes are skipped by
// their `size` field (see decodeCommand) rather than treated as an error,
// matching the parser-safety rule in the implementation plan's section 6.8.
//
// Protocol 1.3's batch header carries a 64-bit process session id. The
// executor switches among per-session device/resource/frame contexts at batch
// boundaries, so launchers and capability helpers may run concurrently with a
// game even though every process starts allocating the same numeric handles.

(function(global) {
    "use strict";

    const shaderPipeline = global.D3D9ShaderPipeline ||
        (typeof require === "function" ? require("./d3d9_shader_pipeline.js") : null);
    if (!shaderPipeline)
        throw new Error("d3d9_executor.js requires d3d9_shader_pipeline.js to " +
            "be loaded first");

    /*
     * The device and the canvas configuration belong to webgpu_host.js, not to
     * this file. A GPUCanvasContext belongs to whichever device last configured
     * it, and getCurrentTexture() then hands out a texture only that device may
     * use -- so when this executor requested its own device and configured the
     * canvas with it, the OpenGL executor's present pass got a swap-chain
     * texture from the wrong device and every frame died in validation. The
     * page loads all three backends whether or not the guest uses them, and
     * DDraw drives the desktop through this one, so the collision was the
     * normal case rather than an edge.
     */
    /*
     * Resolved when an executor is constructed, not when this file is
     * evaluated: the page's script order is not this module's to depend on,
     * and reading global.V86GPUHost at load time silently yields null when
     * webgpu_host.js happens to come later -- which reads downstream as
     * "WebGPU is unavailable" rather than as the load-order mistake it is.
     */
    function resolveGPUHost() {
        if (global.V86GPUHost) return global.V86GPUHost;
        try {
            return typeof require === "function" ?
                require("../webgpu_host.js") : null;
        } catch (error) {
            return null;
        }
    }

    const DEFAULT_SHADER_WORKER_URL = (() => {
        try {
            if (typeof document === "undefined" || !document.currentScript ||
                    !document.currentScript.src)
                return null;
            const executorURL = new URL(document.currentScript.src);
            const workerURL = new URL("d3d9_shader_worker.js", executorURL);
            workerURL.search = global.V86GL_BUILD_REVISION ?
                "?v=" + encodeURIComponent(global.V86GL_BUILD_REVISION) : executorURL.search;
            return workerURL.href;
        } catch (error) { return null; }
    })();

    const D9WG_MAGIC = 0x47573944; // "D9WG"
    const D9WG_VERSION_MAJOR = 1;
    const D9WG_VERSION_MINOR = 7;
    // The oldest guest proxy this host still decodes. 1.3 payloads are simply
    // shorter than 1.4 ones; see the version check in executeBatch().
    const D9WG_VERSION_MIN_MINOR = 3;
    const D9WG_DMA_BYTES = 16 * 1024 * 1024;
    const D9WG_RESPONSE_REGION_BYTES = 4 * 1024 * 1024;
    const D9WG_RESPONSE_REGION_OFFSET =
        D9WG_DMA_BYTES - D9WG_RESPONSE_REGION_BYTES;
    const D9WG_QUERY_REGION_BYTES = 16 * 1024;
    // Liveness counter the guest watches while it spins on a readback; see the
    // comment on D9WG_HEARTBEAT_OFFSET in d3d9_protocol.h.
    const D9WG_HEARTBEAT_BYTES = 16;
    const D9WG_HEARTBEAT_OFFSET =
        D9WG_RESPONSE_REGION_BYTES - D9WG_HEARTBEAT_BYTES;
    const D9WG_RESPONSE_OK = 1;
    const D9WG_RESPONSE_FAILED = 2;
    const D9WG_BATCH_HEADER_BYTES = 32;
    const D9WG_COMMAND_HEADER_BYTES = 16;
    const D9WG_BATCH_FLAG_PRESENT = 1 << 0;
    const D9WG_FEATURE_SHADER_MODEL_2 = 1 << 0;
    const D9WG_FEATURE_SHADER_MODEL_3 = 1 << 1;

    const OP_HELLO = 1;
    const OP_CREATE_DEVICE = 2;
    const OP_RESET = 3;
    const OP_PRESENT = 4;
    const OP_CLEAR = 5;
    const OP_BEGIN_SCENE = 6;
    const OP_END_SCENE = 7;
    const OP_CREATE_BUFFER = 0x100;
    const OP_UPDATE_BUFFER = 0x101;
    const OP_DESTROY_RESOURCE = 0x103;
    const OP_STRETCH_RECT = 8;
    const OP_COLOR_FILL = 9;
    const OP_UPDATE_SURFACE = 10;
    const OP_GUEST_LOG = 11;
    const OP_READBACK_SURFACE = 12;
    const OP_SESSION_END = 13;
    const GUEST_LOG_SEVERITY_INFO = 0;
    const GUEST_LOG_SEVERITY_FAILED = 2;
    const OP_CREATE_TEXTURE_2D = 0x110;
    const OP_CREATE_TEXTURE_CUBE = 0x111;
    const OP_CREATE_TEXTURE_VOLUME = 0x112;
    const OP_UPDATE_TEXTURE = 0x113;
    const OP_SET_SCISSOR_RECT = 0x205;
    const OP_SET_RENDER_TARGET = 0x20F;
    const OP_SET_DEPTH_STENCIL_SURFACE_LEVEL = 0x21E;
    const OP_SET_PALETTE = 0x21F;
    const OP_SET_CURRENT_TEXTURE_PALETTE = 0x220;
    const OP_GENERATE_MIPS = 0x221;
    const OP_SET_TEXTURE_LOD = 0x222;
    const OP_SET_GAMMA_RAMP = 0x223;
    const OP_CREATE_SWAP_CHAIN = 0x224;
    const OP_DESTROY_SWAP_CHAIN = 0x225;
    const OP_PRESENT_SWAP_CHAIN = 0x226;
    // D9WGSetDepthStencilSurface.depth_texture_handle sentinel: the device's own
    // auto depth-stencil surface. It needs a value distinct from 0 because
    // SetDepthStencilSurface(NULL) -- which really does turn depth testing off
    // -- also has no texture handle, and an app that renders to a texture and
    // then restores the back buffer's depth surface must be able to say which
    // of the two it means.
    const D9WG_AUTO_DEPTH_STENCIL_HANDLE = 0xFFFFFFFF;
    const OP_CREATE_VERTEX_DECLARATION = 0x120;
    const OP_CREATE_VERTEX_SHADER = 0x121;
    const OP_CREATE_PIXEL_SHADER = 0x122;
    const OP_CREATE_QUERY = 0x123;
    const OP_SET_RENDER_STATE = 0x200;
    const OP_SET_SAMPLER_STATE = 0x201;
    const OP_SET_TEXTURE_STAGE_STATE = 0x202;
    const OP_SET_TEXTURE = 0x203;
    const OP_SET_VIEWPORT = 0x204;
    const OP_SET_TRANSFORM = 0x206;
    const OP_SET_MATERIAL = 0x207;
    const OP_SET_LIGHT = 0x208;
    const OP_LIGHT_ENABLE = 0x209;
    const OP_SET_STREAM_SOURCE = 0x20A;
    const OP_SET_STREAM_SOURCE_FREQ = 0x20B;
    const OP_SET_INDICES = 0x20C;
    const OP_SET_VERTEX_DECLARATION = 0x20D;
    const OP_SET_FVF = 0x20E;
    const OP_SET_CURSOR_PROPERTIES = 0x21A;
    const OP_SET_CURSOR_POSITION = 0x21B;
    const OP_SHOW_CURSOR = 0x21C;
    const OP_WINDOW_STATE = 0x21D;
    const D9WG_WINDOW_IS_WINDOW = 1 << 0;
    const D9WG_WINDOW_VISIBLE = 1 << 1;
    const D9WG_WINDOW_ICONIC = 1 << 2;
    const D9WG_WINDOW_FOREGROUND = 1 << 3;
    const D9WG_WINDOW_FULLSCREEN = 1 << 4;
    const D9WG_WINDOW_NO_SURFACE = 1 << 5;
    // Other windows cover all of it (d3d9_protocol.h): hidden as far as the
    // picture goes, though the window is up
    const D9WG_WINDOW_OCCLUDED = 1 << 6;
    // Other windows cover part of it: the parts that show follow the record
    // (D9WGWindowRegion in d3d9_protocol.h)
    const D9WG_WINDOW_REGION = 1 << 7;
    const D9WG_WINDOW_STATE_BYTES = 40;
    const D9WG_WINDOW_REGION_MAX_RECTS = 32;
    const OP_SET_VERTEX_SHADER = 0x211;
    const OP_SET_PIXEL_SHADER = 0x212;
    const OP_SET_VERTEX_SHADER_CONSTANT_F = 0x213;
    const OP_SET_VERTEX_SHADER_CONSTANT_I = 0x214;
    const OP_SET_VERTEX_SHADER_CONSTANT_B = 0x215;
    const OP_SET_PIXEL_SHADER_CONSTANT_F = 0x216;
    const OP_SET_PIXEL_SHADER_CONSTANT_I = 0x217;
    const OP_SET_PIXEL_SHADER_CONSTANT_B = 0x218;
    const OP_SET_CLIP_PLANE = 0x219;
    const OP_DRAW_PRIMITIVE = 0x300;
    const OP_DRAW_INDEXED_PRIMITIVE = 0x301;
    const OP_DRAW_PRIMITIVE_UP = 0x302;

    const D3DSTREAMSOURCE_INDEXEDDATA = 0x40000000;
    const D3DSTREAMSOURCE_INSTANCEDATA = 0x80000000;
    const D3DSTREAMSOURCE_FREQUENCY_MASK = 0x3fffffff;
    const OP_DRAW_INDEXED_PRIMITIVE_UP = 0x303;
    const OP_BEGIN_QUERY = 0x400;
    const OP_END_QUERY = 0x401;

    const RESOURCE_BUFFER_VERTEX = 1;
    const RESOURCE_BUFFER_INDEX = 2;
    const RESOURCE_TEXTURE_2D = 3;
    const RESOURCE_TEXTURE_CUBE = 4;
    const RESOURCE_TEXTURE_VOLUME = 5;
    const RESOURCE_VERTEX_DECLARATION = 6;
    const RESOURCE_VERTEX_SHADER = 7;
    const RESOURCE_PIXEL_SHADER = 8;
    const RESOURCE_QUERY = 9;

    const D3DQUERYTYPE_EVENT = 8;
    const D3DQUERYTYPE_OCCLUSION = 9;
    const D3DQUERYTYPE_TIMESTAMP = 10;
    const D3DQUERYTYPE_TIMESTAMPDISJOINT = 11;
    const D3DQUERYTYPE_TIMESTAMPFREQ = 12;

    // Constant register file sizes, matching D9_MAX_* in d3d9_proxy.c.
    const MAX_VS_CONST_F = 256;
    const MAX_PS_CONST_F = 224;
    const MAX_CONST_I = 16;
    const MAX_CONST_B = 16;
    const MAX_SAMPLERS = 16;
    // fill_caps() reports MaxStreams = 16, D3D9's architectural maximum, and
    // the guest keeps 16 binding slots. This is the different, WebGPU-imposed
    // number: how many vertex buffers one *draw* may bind. WebGPU guarantees
    // maxVertexBuffers >= 8 on every implementation, and a layout is built only
    // for the streams a declaration actually references, so the two limits meet
    // only for a declaration that spreads its attributes over more than eight
    // streams -- which is refused and counted rather than silently truncated.
    const MAX_STREAMS = 16;
    const MAX_VERTEX_BUFFERS_PER_DRAW = 8;
    // The pseudo-stream of a layout whose attributes read defaultAttributeBuffer()
    const DEFAULT_ATTRIBUTE_STREAM = -1;
    // fill_caps() reports NumSimultaneousRTs = 4.
    const MAX_RENDER_TARGETS = 4;
    // WebGPU's minUniformBufferOffsetAlignment default. The vertex and pixel
    // constant regions share one buffer, so the pixel region starts here.
    const UNIFORM_OFFSET_ALIGNMENT = 256;
    // Shared so an offset-less bind group does not allocate an array per draw.
    const EMPTY_OFFSETS = Object.freeze([]);
    // M6 keeps per-draw constants in one persistent buffer. 16 MiB covers
    // tens of thousands of ordinary UI/particle draws while remaining small
    // compared with the texture working set of the target games. A frame that
    // exceeds it falls back to a retired one-off buffer rather than wrapping
    // over constants that have already been recorded.
    const UNIFORM_RING_BYTES = 16 * 1024 * 1024;

    const D3DFMT_R8G8B8 = 20;
    const D3DFMT_A8R8G8B8 = 21;
    const D3DFMT_X8R8G8B8 = 22;
    const D3DFMT_R5G6B5 = 23;
    const D3DFMT_X1R5G5B5 = 24;
    const D3DFMT_A1R5G5B5 = 25;
    const D3DFMT_A4R4G4B4 = 26;
    const D3DFMT_R3G3B2 = 27;
    const D3DFMT_A8 = 28;
    const D3DFMT_A8R3G3B2 = 29;
    const D3DFMT_X4R4G4B4 = 30;
    const D3DFMT_A2B10G10R10 = 31;
    const D3DFMT_A8B8G8R8 = 32;
    const D3DFMT_X8B8G8R8 = 33;
    const D3DFMT_G16R16 = 34;
    const D3DFMT_A2R10G10B10 = 35;
    const D3DFMT_A16B16G16R16 = 36;
    const D3DFMT_L8 = 50;
    const D3DFMT_A8L8 = 51;
    const D3DFMT_A4L4 = 52;
    const D3DFMT_V8U8 = 60;
    const D3DFMT_L6V5U5 = 61;
    const D3DFMT_X8L8V8U8 = 62;
    const D3DFMT_Q8W8V8U8 = 63;
    const D3DFMT_V16U16 = 64;
    const D3DFMT_W11V11U10 = 65;
    const D3DFMT_A2W10V10U10 = 67;
    const D3DFMT_L16 = 81;
    const D3DFMT_R16F = 111;
    const D3DFMT_G16R16F = 112;
    const D3DFMT_A16B16G16R16F = 113;
    const D3DFMT_R32F = 114;
    const D3DFMT_G32R32F = 115;
    const D3DFMT_A32B32G32R32F = 116;
    const D3DFMT_CxV8U8 = 117;
    const D3DFMT_P8 = 41;
    const D3DFMT_A8P8 = 40;
    const D3DFMT_Q16W16V16U16 = 110;
    // Packed 4:2:2. One 32-bit block carries two pixels which share their
    // chroma; only the luma (or green) differs between them.
    const D3DFMT_UYVY = 0x59565955;      // 'UYVY'
    const D3DFMT_YUY2 = 0x32595559;      // 'YUY2'
    const D3DFMT_R8G8_B8G8 = 0x47424752; // 'RGBG'
    const D3DFMT_G8R8_G8B8 = 0x42475247; // 'GRGB'
    // ATI's depth-as-texture FOURCCs. Unlike a D24X8 texture, which a D3D9
    // driver samples as a hardware shadow-map comparison, these return the
    // stored depth itself -- an app picks one precisely because it wants the
    // raw value to do its own filtering with.
    const D3DFMT_DF16 = 0x36314644;      // 'DF16'
    const D3DFMT_DF24 = 0x34324644;      // 'DF24'
    const D3DFMT_INTZ = 0x5A544E49;      // 'INTZ'
    // ATI's 3Dc pair, which are BC4 and BC5 under their pre-DX10 names. A
    // normal map keeping only X and Y and reconstructing Z in the shader beats
    // DXT5 for normals by enough that 2005-2007 titles ship art in it. WebGPU
    // exposes exactly these two under texture-compression-bc, so this is a
    // rename rather than a translation.
    const D3DFMT_ATI1N = 0x31495441;     // 'ATI1'
    const D3DFMT_ATI2N = 0x32495441;     // 'ATI2'
    // A render target whose contents nothing ever reads, so a depth-only pass
    // does not have to allocate a colour buffer it will not use.
    const D3DFMT_NULL = 0x4C4C554E;      // 'NULL'
    const D3DFMT_DXT1 = 0x31545844;
    const D3DFMT_DXT2 = 0x32545844;
    const D3DFMT_DXT3 = 0x33545844;
    const D3DFMT_DXT4 = 0x34545844;
    const D3DFMT_DXT5 = 0x35545844;
    const D3DFMT_INDEX16 = 101;
    const D3DFMT_INDEX32 = 102;

    const D3DUSAGE_RENDERTARGET = 0x1;
    const D3DUSAGE_DEPTHSTENCIL = 0x2;
    const D3DUSAGE_AUTOGENMIPMAP = 0x400;
    // Protocol 1.7, and not a D3DUSAGE bit -- see D9WG_USAGE_DDRAW_INDEXED in
    // d3d9_protocol.h. A P8 texture carrying it is stored as r8uint indices
    // resolved through a palette, rather than expanded to RGBA on the CPU,
    // because DirectDraw blits P8 into P8 and a later palette change must
    // still change those pixels' colour.
    const D9WG_USAGE_DDRAW_INDEXED = 0x80000000;
    const D3DMULTISAMPLE_NONE = 0;
    const D3DMULTISAMPLE_4_SAMPLES = 4;

    // The protocol carries D3DMULTISAMPLE_TYPE verbatim.  WebGPU only accepts
    // literal sample counts, and its portable guaranteed multisample count is
    // four.  Quality levels are implementation-specific in D3D9 but do not
    // exist in WebGPU, so the guest advertises exactly quality level zero.
    function sampleCountForD3D(type, quality) {
        if ((quality >>> 0) !== 0) return 0;
        if ((type >>> 0) === D3DMULTISAMPLE_NONE) return 1;
        if ((type >>> 0) === D3DMULTISAMPLE_4_SAMPLES) return 4;
        return 0;
    }

    const D3DCLEAR_TARGET = 0x1;
    const D3DCLEAR_ZBUFFER = 0x2;
    const D3DCLEAR_STENCIL = 0x4;

    // D3DRENDERSTATETYPE values the M1 fixed-function pipeline now honours.
    // Everything else the guest sends is still recorded in the device's
    // renderStates map but has no effect yet.
    const D3DRS_ZENABLE = 7;
    const D3DRS_ZWRITEENABLE = 14;
    const D3DRS_ALPHATESTENABLE = 15;
    const D3DRS_ALPHAREF = 24;
    const D3DRS_ALPHAFUNC = 25;
    const D3DRS_SRCBLEND = 19;
    const D3DRS_DESTBLEND = 20;
    const D3DRS_CULLMODE = 22;
    const D3DRS_ZFUNC = 23;
    const D3DRS_ALPHABLENDENABLE = 27;
    const D3DRS_STENCILENABLE = 52;
    const D3DRS_STENCILFAIL = 53;
    const D3DRS_STENCILZFAIL = 54;
    const D3DRS_STENCILPASS = 55;
    const D3DRS_STENCILFUNC = 56;
    const D3DRS_STENCILREF = 57;
    const D3DRS_STENCILMASK = 58;
    const D3DRS_STENCILWRITEMASK = 59;
    const D3DRS_COLORWRITEENABLE = 168;
    const D3DRS_SLOPESCALEDEPTHBIAS = 175;
    const D3DRS_SCISSORTESTENABLE = 174;
    const D3DRS_TWOSIDEDSTENCILMODE = 185;
    const D3DRS_CCW_STENCILFAIL = 186;
    const D3DRS_CCW_STENCILZFAIL = 187;
    const D3DRS_CCW_STENCILPASS = 188;
    const D3DRS_CCW_STENCILFUNC = 189;
    const D3DRS_SRGBWRITEENABLE = 194;
    const D3DRS_COLORWRITEENABLE1 = 190;
    const D3DRS_COLORWRITEENABLE2 = 191;
    const D3DRS_COLORWRITEENABLE3 = 192;
    const D3DRS_BLENDOP = 171;
    const D3DRS_BLENDFACTOR = 193;
    const D3DRS_DEPTHBIAS = 195;
    const D3DRS_SEPARATEALPHABLENDENABLE = 206;
    const D3DRS_SRCBLENDALPHA = 207;
    const D3DRS_DESTBLENDALPHA = 208;
    const D3DRS_BLENDOPALPHA = 209;
    // Fixed-function fog. fill_caps() in d3d9_proxy.c advertises
    // D3DPRASTERCAPS_FOGVERTEX/FOGTABLE/WFOG, so a game is entitled to expect
    // these to work; ignoring them left Warcraft III's fogged scenery drawn at
    // full texture colour with none of the atmospheric tint.
    const D3DRS_FOGENABLE = 28;
    const D3DRS_FOGCOLOR = 34;
    const D3DRS_FOGTABLEMODE = 35;
    const D3DRS_FOGSTART = 36;
    const D3DRS_FOGEND = 37;
    const D3DRS_FOGDENSITY = 38;
    // Direct3D 7-only texture colour-key states.  The D3D7 guest deliberately
    // sends their legacy numeric ids through SET_RENDER_STATE; D3D9 leaves
    // both holes unused, so they cannot collide with native D3D9 state.
    const D3DRS_COLORKEYENABLE = 41;
    const D3DRS_FOGVERTEXMODE = 140;
    const D3DRS_COLORKEYBLENDENABLE = 144;
    const D3DRS_RANGEFOGENABLE = 48;
    const D3DRS_LIGHTING = 137;
    const D3DRS_AMBIENT = 139;
    // D3DFOGMODE
    const D3DFOG_NONE = 0, D3DFOG_EXP = 1, D3DFOG_EXP2 = 2, D3DFOG_LINEAR = 3;

    // Fixed-function lighting and the texture-blending cascade (M3). The guest
    // has emitted all of these since M1 -- SetMaterial/SetLight/LightEnable and
    // every texture stage state -- and the host recorded them without acting on
    // any, which is why a lit scene came out flat white and every stage past 0
    // was ignored. fill_caps() in d3d9_proxy.c has meanwhile been advertising
    // MaxTextureBlendStages = 8, D3DVTXPCAPS_DIRECTIONALLIGHTS/POSITIONALLIGHTS
    // and a large TextureOpCaps set, so those were caps promises the renderer
    // did not keep; this section is what makes them true.
    const D3DRS_FILLMODE = 8;
    // D3DRS_WRAP0..7 are contiguous at 128..135; WRAP8..15 live at 198..205.
    const D3DRS_WRAP0 = 128, D3DRS_WRAP7 = 135;
    const D3DRS_MULTISAMPLEANTIALIAS = 161;
    // Alpha-to-coverage, which every D3D9 vendor exposed by smuggling a FOURCC
    // through a render state that meant something else -- there was no
    // D3DRS_ALPHATOCOVERAGE to set. ATI wrote 'ATOC' into ADAPTIVETESS_Y;
    // NVIDIA used the same slot with 'ATOC' too (its 'SSAA' spelling asked for
    // supersampling instead, which is not this). Foliage and chain-link fences
    // are what it exists for: alpha-tested edges that alias horribly without it.
    //
    // WebGPU has it natively as multisample.alphaToCoverageEnabled, so unlike
    // most of this family it is an exact mapping rather than a hack.
    const D3DRS_ADAPTIVETESS_Y = 181;
    const D3DFOURCC_ATOC = 0x434F5441; // 'ATOC'
    const D3DRS_MULTISAMPLEMASK = 162;
    const D3DFILL_POINT = 1, D3DFILL_WIREFRAME = 2, D3DFILL_SOLID = 3;
    const D3DRS_SHADEMODE = 9;
    const D3DRS_SPECULARENABLE = 29;
    const D3DRS_TEXTUREFACTOR = 60;
    const D3DRS_COLORVERTEX = 141;
    const D3DRS_LOCALVIEWER = 142;
    const D3DRS_NORMALIZENORMALS = 143;
    const D3DRS_DIFFUSEMATERIALSOURCE = 145;
    const D3DRS_SPECULARMATERIALSOURCE = 146;
    const D3DRS_AMBIENTMATERIALSOURCE = 147;
    const D3DRS_EMISSIVEMATERIALSOURCE = 148;
    // Point primitives/point sprites. WebGPU only exposes one-pixel points,
    // so M6 expands every D3D point to a six-vertex quad in the vertex stage.
    const D3DRS_POINTSIZE = 154;
    const D3DRS_POINTSIZE_MIN = 155;
    const D3DRS_POINTSPRITEENABLE = 156;
    const D3DRS_POINTSCALEENABLE = 157;
    const D3DRS_POINTSCALE_A = 158;
    const D3DRS_POINTSCALE_B = 159;
    const D3DRS_POINTSCALE_C = 160;
    const D3DRS_POINTSIZE_MAX = 166;

    // Fixed-function vertex blending. D3DRS_VERTEXBLEND says how many world
    // matrices pose each vertex; D3DRS_INDEXEDVERTEXBLENDENABLE says whether
    // BLENDINDICES picks them out of the world-matrix palette instead of
    // taking them in order from D3DTS_WORLDMATRIX(0).
    const D3DRS_VERTEXBLEND = 151;
    const D3DRS_CLIPPLANEENABLE = 152;
    const D3DRS_INDEXEDVERTEXBLENDENABLE = 167;
    // D3DVERTEXBLENDFLAGS. The 1/2/3WEIGHTS names count *weights*, and the
    // matrix count is one higher: the last matrix's weight is whatever the
    // others leave over, 1 - sum(the rest). 0WEIGHTS is the indexed-only case
    // of one matrix per vertex chosen by BLENDINDICES.x with weight 1.
    const D3DVBF_DISABLE = 0;
    const D3DVBF_TWEENING = 255;
    const D3DVBF_0WEIGHTS = 256;
    // D3D9's fixed function blends at most four matrices per vertex, which is
    // what fill_caps() reports as MaxVertexBlendMatrices.
    const MAX_BLEND_MATRICES = 4;

    // D3DLIGHTTYPE
    const D3DLIGHT_POINT = 1, D3DLIGHT_SPOT = 2, D3DLIGHT_DIRECTIONAL = 3;
    // D3DMATERIALCOLORSOURCE
    const D3DMCS_MATERIAL = 0, D3DMCS_COLOR1 = 1, D3DMCS_COLOR2 = 2;
    // fill_caps() reports MaxActiveLights = 8.
    const MAX_LIGHTS = 8;

    // D3DTEXTURESTAGESTATETYPE
    const D3DTSS_COLOROP = 1, D3DTSS_COLORARG1 = 2, D3DTSS_COLORARG2 = 3;
    const D3DTSS_ALPHAOP = 4, D3DTSS_ALPHAARG1 = 5, D3DTSS_ALPHAARG2 = 6;
    const D3DTSS_TEXCOORDINDEX = 11;
    // The 2x2 matrix D3DTOP_BUMPENVMAP applies to the (du, dv) it samples,
    // and the luminance scale/offset BUMPENVMAPLUMINANCE adds on top. All six
    // are D3DTSS values holding raw float bits.
    const D3DTSS_BUMPENVMAT00 = 7, D3DTSS_BUMPENVMAT01 = 8;
    const D3DTSS_BUMPENVMAT10 = 9, D3DTSS_BUMPENVMAT11 = 10;
    const D3DTSS_BUMPENVLSCALE = 22, D3DTSS_BUMPENVLOFFSET = 23;
    const D3DTSS_TEXTURETRANSFORMFLAGS = 24;
    const D3DTSS_COLORARG0 = 26, D3DTSS_ALPHAARG0 = 27, D3DTSS_RESULTARG = 28;
    const D3DTSS_CONSTANT = 32;

    // D3DTEXTUREOP. Only the operations fill_caps() advertises in TextureOpCaps
    // are implemented below; a stage asking for one that is absent is counted
    // rather than approximated (an approximated blend renders as
    // wrong-but-plausible shading, which is the failure mode hardest to
    // attribute). D3DTOP_PREMODULATE is the one remaining hole: it modulates
    // this stage's result with the *next* stage's texture, and nothing in the
    // cascade carries a value backwards.
    const D3DTOP_DISABLE = 1, D3DTOP_SELECTARG1 = 2, D3DTOP_SELECTARG2 = 3;
    const D3DTOP_MODULATE = 4, D3DTOP_MODULATE2X = 5, D3DTOP_MODULATE4X = 6;
    const D3DTOP_ADD = 7, D3DTOP_ADDSIGNED = 8, D3DTOP_ADDSIGNED2X = 9;
    const D3DTOP_SUBTRACT = 10, D3DTOP_ADDSMOOTH = 11;
    const D3DTOP_BLENDDIFFUSEALPHA = 12, D3DTOP_BLENDTEXTUREALPHA = 13;
    const D3DTOP_BLENDFACTORALPHA = 14, D3DTOP_BLENDTEXTUREALPHAPM = 15;
    const D3DTOP_BLENDCURRENTALPHA = 16;
    const D3DTOP_PREMODULATE = 17;
    // The four "modulate one channel set, add the other" operations. D3D9
    // documents all four as valid for D3DTSS_COLOROP only -- each one mixes
    // arg1's colour with arg1's *alpha*, which has no scalar analogue -- so the
    // alpha form below returns null and is counted like any other refusal.
    const D3DTOP_MODULATEALPHA_ADDCOLOR = 18;
    const D3DTOP_MODULATECOLOR_ADDALPHA = 19;
    const D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20;
    const D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21;
    const D3DTOP_BUMPENVMAP = 22, D3DTOP_BUMPENVMAPLUMINANCE = 23;
    const D3DTOP_DOTPRODUCT3 = 24, D3DTOP_MULTIPLYADD = 25, D3DTOP_LERP = 26;

    // D3DTA_* argument selectors and their two modifier bits.
    const D3DTA_SELECTMASK = 0x0000000f;
    const D3DTA_COMPLEMENT = 0x00000010;
    const D3DTA_ALPHAREPLICATE = 0x00000020;
    const D3DTA_DIFFUSE = 0, D3DTA_CURRENT = 1, D3DTA_TEXTURE = 2;
    const D3DTA_TFACTOR = 3, D3DTA_SPECULAR = 4, D3DTA_TEMP = 5;
    const D3DTA_CONSTANT = 6;

    // D3DTSS_TEXCOORDINDEX's high bits: automatic coordinate generation.
    const D3DTSS_TCI_MASK = 0xffff0000;
    const D3DTSS_TCI_PASSTHRU = 0x00000000;
    const D3DTSS_TCI_CAMERASPACENORMAL = 0x00010000;
    const D3DTSS_TCI_CAMERASPACEPOSITION = 0x00020000;
    const D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = 0x00030000;
    const D3DTSS_TCI_SPHEREMAP = 0x00040000;

    // D3DTSS_TEXTURETRANSFORMFLAGS
    const D3DTTFF_PROJECTED = 0x100;

    // D3DTSS_RESULTARG picks where a stage writes: the cascade register
    // (D3DTA_CURRENT) or the scratch register (D3DTA_TEMP), which a later stage
    // can read back as an argument.
    const MAX_TEXTURE_STAGES = 8;
    // TEXCOORD0..7 are the only coordinate sets D3D9 has, so this bounds both
    // the vertex attributes and the varyings the cascade can reference.
    const MAX_TEXCOORD_SETS = 8;

    const D3DZB_FALSE = 0;
    const D3DCULL_NONE = 1;
    const D3DCULL_CW = 2;
    const D3DCULL_CCW = 3;

    // D3DCMPFUNC -> GPUCompareFunction
    const COMPARE_FUNCS = [
        undefined, "never", "less", "equal", "less-equal",
        "greater", "not-equal", "greater-equal", "always",
    ];

    // D3DBLEND -> GPUBlendFactor. The BOTH* values are resolved as a source /
    // destination pair in pipelineStateFor(); BLENDFACTOR maps to WebGPU's
    // dynamic blend constant and is installed before each draw.
    const BLEND_FACTORS = [
        undefined,
        "zero",                 // D3DBLEND_ZERO = 1
        "one",                  // D3DBLEND_ONE
        "src",                  // D3DBLEND_SRCCOLOR
        "one-minus-src",        // D3DBLEND_INVSRCCOLOR
        "src-alpha",            // D3DBLEND_SRCALPHA
        "one-minus-src-alpha",  // D3DBLEND_INVSRCALPHA
        "dst-alpha",            // D3DBLEND_DESTALPHA
        "one-minus-dst-alpha",  // D3DBLEND_INVDESTALPHA
        "dst",                  // D3DBLEND_DESTCOLOR
        "one-minus-dst",        // D3DBLEND_INVDESTCOLOR
        "src-alpha-saturated",  // D3DBLEND_SRCALPHASAT
        undefined,              // D3DBLEND_BOTHSRCALPHA (pair alias)
        undefined,              // D3DBLEND_BOTHINVSRCALPHA (pair alias)
        "constant",             // D3DBLEND_BLENDFACTOR
        "one-minus-constant",   // D3DBLEND_INVBLENDFACTOR
    ];

    // D3DBLENDOP -> GPUBlendOperation
    const BLEND_OPS = [
        undefined, "add", "subtract", "reverse-subtract", "min", "max",
    ];

    // D3DSTENCILOP -> GPUStencilOperation.
    const STENCIL_OPS = [
        undefined, "keep", "zero", "replace", "increment-clamp",
        "decrement-clamp", "invert", "increment-wrap", "decrement-wrap",
    ];

    // WebGPU's depth format for the auto depth-stencil surface. D3D9 apps ask
    // for D16/D24S8/D24X8/etc; all of them are satisfied with one real
    // depth24plus-stencil8 target rather than trying to match bit layouts the
    // guest can never observe (it cannot read the depth buffer back in M1).
    const DEPTH_FORMAT = "depth24plus-stencil8";
    const TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;

    // D3DDECLUSAGE / D3DDECLTYPE, the subset d3d9_proxy.c's
    // declaration_element_supported() lets through.
    const DECLUSAGE_POSITION = 0;
    const DECLUSAGE_BLENDWEIGHT = 1;
    const DECLUSAGE_BLENDINDICES = 2;
    const DECLUSAGE_NORMAL = 3;
    const DECLUSAGE_PSIZE = 4;
    const DECLUSAGE_TEXCOORD = 5;
    const DECLUSAGE_POSITIONT = 9;
    const DECLUSAGE_COLOR = 10;
    const DECLTYPE_FLOAT1 = 0;
    const DECLTYPE_FLOAT2 = 1;
    const DECLTYPE_FLOAT3 = 2;
    const DECLTYPE_FLOAT4 = 3;
    const DECLTYPE_D3DCOLOR = 4;

    // D3DDECLTYPE -> [GPUVertexFormat, byte size]. D3DCOLOR is read as raw
    // little-endian BGRA bytes by unorm8x4, so anything consuming it has to
    // swizzle; both shader generators below do that at the point where the
    // attribute is copied into its register, never with a CPU pass over the
    // vertex data.
    const DECLTYPE_FORMATS = {
        [DECLTYPE_FLOAT1]: ["float32", 4],
        [DECLTYPE_FLOAT2]: ["float32x2", 8],
        [DECLTYPE_FLOAT3]: ["float32x3", 12],
        [DECLTYPE_FLOAT4]: ["float32x4", 16],
        [DECLTYPE_D3DCOLOR]: ["unorm8x4", 4],
        5: ["uint8x4", 4],     // D3DDECLTYPE_UBYTE4
        6: ["sint16x2", 4],    // D3DDECLTYPE_SHORT2
        7: ["sint16x4", 8],    // D3DDECLTYPE_SHORT4
        8: ["unorm8x4", 4],    // D3DDECLTYPE_UBYTE4N
        9: ["snorm16x2", 4],   // D3DDECLTYPE_SHORT2N
        10: ["snorm16x4", 8],  // D3DDECLTYPE_SHORT4N
        11: ["unorm16x2", 4],  // D3DDECLTYPE_USHORT2N
        12: ["unorm16x4", 8],  // D3DDECLTYPE_USHORT4N
        13: ["uint32", 4],     // D3DDECLTYPE_UDEC3 (unpacked in WGSL)
        14: ["uint32", 4],     // D3DDECLTYPE_DEC3N (unpacked in WGSL)
        15: ["float16x2", 4],  // D3DDECLTYPE_FLOAT16_2
        16: ["float16x4", 8],  // D3DDECLTYPE_FLOAT16_4
    };

    // D3DSAMPLERSTATETYPE, and the enums its values come from.
    const D3DSAMP_ADDRESSU = 1;
    const D3DSAMP_ADDRESSV = 2;
    const D3DSAMP_ADDRESSW = 3;
    const D3DSAMP_BORDERCOLOR = 4;
    const D3DSAMP_MAGFILTER = 5;
    const D3DSAMP_MINFILTER = 6;
    const D3DSAMP_MIPFILTER = 7;
    // Float bits in a DWORD. WebGPU samplers carry no LOD bias, so this one is
    // applied at the sample call instead -- see lodBiasFor().
    const D3DSAMP_MIPMAPLODBIAS = 8;
    // The floor on which mip level may be sampled, as a level index. WebGPU
    // spells the same restriction as a LOD clamp, so both this and the
    // per-texture SetLOD become lodMinClamp -- see samplerFor().
    const D3DSAMP_MAXMIPLEVEL = 9;
    const D3DSAMP_MAXANISOTROPY = 10;
    // D3D9 decodes an sRGB-tagged texture to linear *on read*. WebGPU has no
    // sampler-level equivalent -- it is a property of the texture format -- so
    // this is honoured by sampling through an "-srgb" view of the same texture
    // rather than by anything in the sampler.
    const D3DSAMP_SRGBTEXTURE = 11;

    // D3DTEXTUREADDRESS -> GPUAddressMode. WebGPU has no BORDER mode and no
    // MIRRORONCE; both fall back to clamp-to-edge, which is the closest
    // available behaviour and is noted once per occurrence rather than
    // silently substituted.
    const ADDRESS_MODES = [
        undefined, "repeat", "mirror-repeat", "clamp-to-edge",
        "clamp-to-edge", "clamp-to-edge",
    ];
    // D3DTEXTUREFILTERTYPE -> GPUFilterMode. ANISOTROPIC becomes linear plus
    // a maxAnisotropy value; PYRAMIDALQUAD/GAUSSIANQUAD have no equivalent.
    const FILTER_MODES = [
        "nearest", "nearest", "linear", "linear",
        "linear", "linear", "linear",
    ];

    // Which states the renderer actually consumes. Kept next to the constants
    // rather than derived from them, because "we read this" is a statement about
    // the code below, not about the enum.
    const CONSUMED_SAMPLER_STATES = new Set([
        D3DSAMP_ADDRESSU, D3DSAMP_ADDRESSV, D3DSAMP_ADDRESSW,
        D3DSAMP_BORDERCOLOR,
        D3DSAMP_MAGFILTER, D3DSAMP_MINFILTER, D3DSAMP_MIPFILTER,
        D3DSAMP_MAXANISOTROPY, D3DSAMP_SRGBTEXTURE,
    ]);

    const CONSUMED_RENDER_STATES = new Set([
        D3DRS_ZENABLE, D3DRS_ZWRITEENABLE, D3DRS_ALPHATESTENABLE, D3DRS_ALPHAREF,
        D3DRS_ALPHAFUNC, D3DRS_SRCBLEND, D3DRS_DESTBLEND, D3DRS_CULLMODE,
        D3DRS_ZFUNC, D3DRS_ALPHABLENDENABLE, D3DRS_COLORWRITEENABLE,
        D3DRS_COLORWRITEENABLE1, D3DRS_COLORWRITEENABLE2, D3DRS_COLORWRITEENABLE3,
        D3DRS_BLENDOP, D3DRS_BLENDFACTOR, D3DRS_SEPARATEALPHABLENDENABLE,
        D3DRS_SRCBLENDALPHA, D3DRS_DESTBLENDALPHA, D3DRS_BLENDOPALPHA,
        D3DRS_STENCILENABLE, D3DRS_STENCILFAIL, D3DRS_STENCILZFAIL,
        D3DRS_STENCILPASS, D3DRS_STENCILFUNC, D3DRS_STENCILREF,
        D3DRS_STENCILMASK, D3DRS_STENCILWRITEMASK,
        D3DRS_TWOSIDEDSTENCILMODE, D3DRS_CCW_STENCILFAIL,
        D3DRS_CCW_STENCILZFAIL, D3DRS_CCW_STENCILPASS,
        D3DRS_CCW_STENCILFUNC, D3DRS_DEPTHBIAS, D3DRS_SLOPESCALEDEPTHBIAS,
        D3DRS_FOGENABLE, D3DRS_FOGCOLOR, D3DRS_FOGTABLEMODE,
        D3DRS_FOGSTART, D3DRS_FOGEND, D3DRS_FOGDENSITY, D3DRS_FOGVERTEXMODE,
        D3DRS_COLORKEYENABLE, D3DRS_COLORKEYBLENDENABLE,
        D3DRS_RANGEFOGENABLE, D3DRS_LIGHTING, D3DRS_AMBIENT,
        D3DRS_SPECULARENABLE, D3DRS_TEXTUREFACTOR, D3DRS_COLORVERTEX,
        D3DRS_LOCALVIEWER, D3DRS_NORMALIZENORMALS, D3DRS_DIFFUSEMATERIALSOURCE,
        D3DRS_SPECULARMATERIALSOURCE, D3DRS_AMBIENTMATERIALSOURCE,
        D3DRS_EMISSIVEMATERIALSOURCE, D3DRS_SCISSORTESTENABLE,
        D3DRS_SRGBWRITEENABLE, D3DRS_POINTSIZE, D3DRS_POINTSIZE_MIN,
        D3DRS_POINTSPRITEENABLE, D3DRS_POINTSCALEENABLE,
        D3DRS_POINTSCALE_A, D3DRS_POINTSCALE_B, D3DRS_POINTSCALE_C,
        D3DRS_POINTSIZE_MAX, D3DRS_VERTEXBLEND,
        D3DRS_INDEXEDVERTEXBLENDENABLE, D3DRS_CLIPPLANEENABLE,
    ]);

    const D3DTS_VIEW = 2;
    const D3DTS_PROJECTION = 3;
    const D3DTS_WORLD = 256;
    // D3DTS_WORLDMATRIX(n) is D3DTS_WORLD + n, and indexed vertex blending can
    // address all 256 of them. The palette actually uploaded per draw is sized
    // from what the guest has set (see maxWorldMatrixIndex), not from this.
    const MAX_WORLD_MATRICES = 256;
    const D3DTS_TEXTURE0 = 16;

    // How many world matrices an indexed blend uploads. Sizing this to exactly
    // the highest index the guest has set would put the count in the shader
    // cache key and mint a fresh module and pipeline every time an engine adds
    // a bone, so it is rounded up through a handful of buckets instead: the
    // key changes a few times per session rather than a few times per frame.
    // The cost of the slack is upload bandwidth on blended draws only.
    function blendPaletteSize(highestIndexSet) {
        const needed = Math.max(1, Math.min(MAX_WORLD_MATRICES,
            (highestIndexSet | 0) + 1));
        let size = 4;
        while (size < needed) size *= 2;
        return size;
    }

    // D3DPRIMITIVETYPE -> WebGPU topology, and element-count helpers mirror
    // d3d9_proxy.c's primitive_element_count() so guest/host agree on how
    // many vertices/indices a given primitive_count consumes. Only list/strip
    // forms map onto a single WebGPU draw call directly; FAN is converted to
    // a triangle list index buffer on upload, same discipline as the D3D8
    // path.
    const D3DPT_POINTLIST = 1;
    const D3DPT_LINELIST = 2;
    const D3DPT_LINESTRIP = 3;
    const D3DPT_TRIANGLELIST = 4;
    const D3DPT_TRIANGLESTRIP = 5;
    const D3DPT_TRIANGLEFAN = 6;

    const BUFFER_USAGE_VERTEX = 0x20;
    const BUFFER_USAGE_INDEX = 0x10;
    const BUFFER_USAGE_UNIFORM = 0x40;
    const BUFFER_USAGE_COPY_SRC = 0x4;
    const BUFFER_USAGE_COPY_DST = 0x8;
    const BUFFER_USAGE_MAP_READ = 0x1;
    const BUFFER_USAGE_QUERY_RESOLVE = 0x200;
    const MAP_MODE_READ = 0x1;
    const TEXTURE_USAGE_COPY_SRC = 0x1;
    const TEXTURE_USAGE_COPY_DST = 0x2;
    const SHADER_STAGE_VERTEX = 0x1;
    const SHADER_STAGE_FRAGMENT = 0x2;
    const TEXTURE_USAGE_TEXTURE_BINDING = 0x4;

    const TEXTURE_FORMAT_NAMES = {
        20: "R8G8B8", 21: "A8R8G8B8", 22: "X8R8G8B8", 23: "R5G6B5",
        24: "X1R5G5B5", 25: "A1R5G5B5", 26: "A4R4G4B4",
        27: "R3G3B2", 28: "A8", 29: "A8R3G3B2", 30: "X4R4G4B4",
        31: "A2B10G10R10", 32: "A8B8G8R8", 33: "X8B8G8R8",
        34: "G16R16", 35: "A2R10G10B10", 36: "A16B16G16R16",
        50: "L8", 51: "A8L8",
        52: "A4L4", 60: "V8U8", 61: "L6V5U5", 62: "X8L8V8U8",
        63: "Q8W8V8U8", 64: "V16U16", 65: "W11V11U10",
        67: "A2W10V10U10", 81: "L16",
        111: "R16F", 112: "G16R16F", 113: "A16B16G16R16F",
        117: "CxV8U8",
        0x31545844: "DXT1", 0x32545844: "DXT2",
        0x33545844: "DXT3", 0x34545844: "DXT4",
        0x35545844: "DXT5",
    };

    // D3D9 stores FOGSTART/FOGEND/FOGDENSITY as float bits inside a DWORD.
    const FLOAT_BITS_BUFFER = new ArrayBuffer(4);
    const FLOAT_BITS_U32 = new Uint32Array(FLOAT_BITS_BUFFER);
    const FLOAT_BITS_F32 = new Float32Array(FLOAT_BITS_BUFFER);

    /*
     * The D9WGWindowRegion after a WINDOW_STATE record: the parts of the
     * client area other guest windows leave showing, as client-area pixels of
     * a client area baseWidth x baseHeight whose top-left corner is at
     * (originX, originY) on the guest's screen. Null when it does not fit the
     * record or says nothing usable.
     */
    function readVisibleRegion(view, offset, bytes, baseWidth, baseHeight, originX, originY) {
        if (bytes < 4 || !baseWidth || !baseHeight) return null;
        const count = view.getUint32(offset, true);
        if (count > D9WG_WINDOW_REGION_MAX_RECTS || bytes < 4 + count * 16) return null;
        const rects = [];
        for (let i = 0; i < count; ++i) {
            const at = offset + 4 + i * 16;
            const left = view.getInt32(at, true), top = view.getInt32(at + 4, true);
            const right = view.getInt32(at + 8, true), bottom = view.getInt32(at + 12, true);
            if (right > left && bottom > top) rects.push({ left, top, right, bottom });
        }
        return { rects, baseWidth, baseHeight, originX, originY };
    }

    function sameVisibleRegion(a, b) {
        if (a === b) return true;
        if (!a || !b || a.rects.length !== b.rects.length || a.baseWidth !== b.baseWidth ||
                a.baseHeight !== b.baseHeight || a.originX !== b.originX || a.originY !== b.originY)
            return false;
        return a.rects.every((r, i) => r.left === b.rects[i].left && r.top === b.rects[i].top &&
            r.right === b.rects[i].right && r.bottom === b.rects[i].bottom);
    }

    function alignUp(value, alignment) {
        return (value + alignment - 1) & ~(alignment - 1);
    }

    function floatFromDWORD(value) {
        FLOAT_BITS_U32[0] = value >>> 0;
        return FLOAT_BITS_F32[0];
    }

    // D3DSAMP_MIPMAPLODBIAS, also float bits in a DWORD.
    //
    // WebGPU samplers have no LOD bias at all, so the only place to apply one
    // is the sample call -- textureSampleBias -- which means the value lands in
    // the shader rather than in the sampler. Baking it as a literal (rather
    // than reading it from a uniform) keeps it out of the per-draw uniform
    // writers on both the fixed-function and translated paths, at the price of
    // one pipeline variant per distinct bias.
    //
    // Quantising to 1/16 of a mip level is what bounds that price: a title that
    // animates the bias continuously would otherwise mint a pipeline per frame,
    // and 1/16 is far finer than the difference is visible at. The range clamp
    // matches D3D9's own, which no hardware exceeded.
    const LOD_BIAS_STEPS = 16;
    const LOD_BIAS_LIMIT = 16;
    function lodBiasFor(dword) {
        const bias = floatFromDWORD(dword);
        if (!Number.isFinite(bias) || bias === 0) return 0;
        return Math.round(Math.max(-LOD_BIAS_LIMIT,
            Math.min(LOD_BIAS_LIMIT, bias)) * LOD_BIAS_STEPS) / LOD_BIAS_STEPS;
    }

    // The "-srgb" sibling of a GPU format, or null when there is none. A view
    // can only use a format listed in the texture's viewFormats at creation, so
    // this has to be known up front rather than at bind time.
    function srgbSiblingOf(gpuFormat) {
        return {
            "bgra8unorm": "bgra8unorm-srgb",
            "rgba8unorm": "rgba8unorm-srgb",
            "bc1-rgba-unorm": "bc1-rgba-unorm-srgb",
            "bc2-rgba-unorm": "bc2-rgba-unorm-srgb",
            "bc3-rgba-unorm": "bc3-rgba-unorm-srgb",
        }[gpuFormat] || null;
    }

    function isCompressedFormat(format) {
        return format === D3DFMT_DXT1 || format === D3DFMT_DXT2 ||
            format === D3DFMT_DXT3 || format === D3DFMT_DXT4 ||
            format === D3DFMT_DXT5 ||
            format === D3DFMT_ATI1N || format === D3DFMT_ATI2N;
    }

    // Bytes per 4x4 block for the block-compressed formats. BC1 and BC4 carry
    // one 8-byte block; everything else here carries two.
    function compressedBlockBytes(format) {
        return (format === D3DFMT_DXT1 || format === D3DFMT_ATI1N) ? 8 : 16;
    }

    // WebGPU measures a block-compressed copy in whole texel blocks: copySize
    // must be a multiple of the BCn 4x4 block, and a mip level's *physical*
    // extent is its logical size rounded up to that grid. So the tail of a DXT
    // mip chain has to be written as a full 4x4 block even though its logical
    // size is 2x2 or 1x1. Passing the logical size makes writeTexture fail
    // validation, and because that failure surfaces as an uncaptured device
    // error rather than an exception, the level silently keeps whatever the
    // texture was created with -- hundreds of "copySize.width (1) is not a
    // multiple of compressed texture format block width (4)" errors while Kart
    // Rider loaded its UI atlases, with no other symptom than the smallest mips
    // sampling as garbage.
    //
    // Callers pass a block-aligned origin, which WebGPU requires independently,
    // so rounding the extent up cannot run past the physical mip extent.
    function blockAlignedCopyExtent(size, compressed) {
        return compressed ? Math.ceil(size / 4) * 4 : size;
    }

    // The pixel rect a draw may touch: the D3D9 viewport (which clips, unlike
    // WebGPU's) intersected with the scissor rect when D3DRS_SCISSORTESTENABLE
    // is on, then clamped into the attachment -- WebGPU rejects a scissor that
    // leaves the render target, and an app is free to set a viewport that does.
    // An empty intersection stays empty (zero width or height), which draws
    // nothing, exactly as D3D9 would.
    function intersectRects(viewport, scissor, targetWidth, targetHeight) {
        let left = viewport.x;
        let top = viewport.y;
        let right = viewport.x + viewport.width;
        let bottom = viewport.y + viewport.height;
        if (scissor) {
            left = Math.max(left, scissor.x);
            top = Math.max(top, scissor.y);
            right = Math.min(right, scissor.x + scissor.width);
            bottom = Math.min(bottom, scissor.y + scissor.height);
        }
        left = Math.max(0, Math.min(left, targetWidth));
        top = Math.max(0, Math.min(top, targetHeight));
        right = Math.max(left, Math.min(right, targetWidth));
        bottom = Math.max(top, Math.min(bottom, targetHeight));
        return { x: left, y: top, width: right - left, height: bottom - top };
    }

    // The FOURCC depth formats. They live in a D3D9 texture like any other
    // format, but their storage is the depth buffer's, so they take the depth
    // path rather than formatToGPU.
    function isFourCCDepthFormat(format) {
        return format === D3DFMT_DF16 || format === D3DFMT_DF24 ||
            format === D3DFMT_INTZ;
    }

    function isPalettizedFormat(format) {
        return format === D3DFMT_P8 || format === D3DFMT_A8P8;
    }

    // Two pixels per 32-bit block, sharing chroma.
    function isPackedPairFormat(format) {
        return format === D3DFMT_UYVY || format === D3DFMT_YUY2 ||
            format === D3DFMT_R8G8_B8G8 || format === D3DFMT_G8R8_G8B8;
    }

    function isHalfFloatExpansionFormat(format) {
        return format === D3DFMT_Q16W16V16U16 ||
            format === D3DFMT_L6V5U5 || format === D3DFMT_X8L8V8U8 ||
            format === D3DFMT_V16U16 || format === D3DFMT_W11V11U10 ||
            format === D3DFMT_A2W10V10U10 ||
            format === D3DFMT_L16 || format === D3DFMT_CxV8U8 ||
            format === D3DFMT_A2B10G10R10 || format === D3DFMT_G16R16 ||
            format === D3DFMT_A2R10G10B10 ||
            format === D3DFMT_A16B16G16R16 || format === D3DFMT_R16F ||
            format === D3DFMT_G16R16F ||
            format === D3DFMT_A16B16G16R16F;
    }

    function gpuBytesPerTexel(format) {
        if (isHalfFloatExpansionFormat(format)) return 8;
        if (format === D3DFMT_G32R32F) return 8;
        if (format === D3DFMT_A32B32G32R32F) return 16;
        return 4;
    }

    // A command whose payload contradicts the batch framing -- a blob that
    // reaches past the end of the record, a length field larger than the bytes
    // behind it. Unlike a command that merely fails, this means the producer
    // and the consumer disagree about the byte layout, so nothing else in the
    // batch can be trusted either and the whole thing is abandoned. Everything
    // that is not one of these is contained to its own command; see the
    // dispatch loop in executeBatch().
    class D9WGStreamError extends Error {}

    // WebGPU wants the level count; D3D9 texture sizes are not always powers of
    // two, and the chain runs until both dimensions reach one.
    function fullMipLevelCount(width, height) {
        let levels = 1;
        let w = width, h = height;
        while (w > 1 || h > 1) {
            if (w > 1) w >>= 1;
            if (h > 1) h >>= 1;
            ++levels;
        }
        return levels;
    }

    function isRenderableGPUFormat(format) {
        return format === "rgba8unorm" || format === "rgba16float" ||
            format === "r32float" || format === "rg32float" ||
            format === "rgba32float" ||
            // The NULL FOURCC target's stand-in. It is renderable by
            // definition -- being a render target nothing reads is its whole
            // purpose -- and r8unorm is the cheapest format that can be one.
            format === "r8unorm" ||
            // Protocol 1.7: the storage a DirectDraw palettised surface uses.
            // It has to be an attachment because a 2D title's whole frame is
            // built by blitting P8 sprites into a P8 back buffer.
            format === "r8uint";
    }

    function isFloat32GPUFormat(format) {
        return format === "r32float" || format === "rg32float" ||
            format === "rgba32float";
    }

    function isBlendableGPUFormat(format, features) {
        return !isFloat32GPUFormat(format) ||
            !!(features && features.float32Blendable);
    }

    function formatToGPU(format) {
        switch (format) {
        case D3DFMT_R8G8B8:
        case D3DFMT_A8R8G8B8:
        case D3DFMT_X8R8G8B8:
        case D3DFMT_X1R5G5B5:
        case D3DFMT_A1R5G5B5:
        case D3DFMT_A4R4G4B4:
        case D3DFMT_R3G3B2:
        case D3DFMT_A8R3G3B2:
        case D3DFMT_X4R4G4B4:
        case D3DFMT_A8B8G8R8:
        case D3DFMT_X8B8G8R8:
        case D3DFMT_R5G6B5:
        case D3DFMT_L8:
        case D3DFMT_A8:
        case D3DFMT_A8L8:
        case D3DFMT_A4L4:
        case D3DFMT_P8:
        case D3DFMT_A8P8:
        case D3DFMT_UYVY:
        case D3DFMT_YUY2:
        case D3DFMT_R8G8_B8G8:
        case D3DFMT_G8R8_G8B8:
        case D3DFMT_INDEX16:
        case D3DFMT_INDEX32:
            // All of these are CPU-expanded to tightly-packed RGBA8 on
            // upload (see expandRowToGPU), matching the D3D8 path's
            // approach: WebGPU has no native 16-bit BGR/BGRA formats.
            return "rgba8unorm";
        case D3DFMT_V8U8:
        case D3DFMT_Q8W8V8U8:
            return "rgba8snorm";
        case D3DFMT_L6V5U5:
        case D3DFMT_X8L8V8U8:
        case D3DFMT_V16U16:
        case D3DFMT_W11V11U10:
        case D3DFMT_A2W10V10U10:
        case D3DFMT_L16:
        case D3DFMT_CxV8U8:
        case D3DFMT_A2B10G10R10:
        case D3DFMT_G16R16:
        case D3DFMT_A2R10G10B10:
        case D3DFMT_A16B16G16R16:
        case D3DFMT_Q16W16V16U16:
        case D3DFMT_R16F:
        case D3DFMT_G16R16F:
        case D3DFMT_A16B16G16R16F:
            // Mixed signed/unsigned bump formats, CxV8U8's reconstructed
            // component, and high-precision L16 cannot be represented by one
            // normalized 8-bit WebGPU format without losing their semantics.
            // Half-float preserves the sampled values closely.
            return "rgba16float";
        case D3DFMT_R32F:
            return "r32float";
        case D3DFMT_G32R32F:
            return "rg32float";
        case D3DFMT_A32B32G32R32F:
            return "rgba32float";
        case D3DFMT_DXT1:
            return "bc1-rgba-unorm";
        case D3DFMT_DXT2:
        case D3DFMT_DXT3:
            return "bc2-rgba-unorm";
        case D3DFMT_DXT4:
        case D3DFMT_DXT5:
            return "bc3-rgba-unorm";
        case D3DFMT_ATI1N:
            return "bc4-r-unorm";
        case D3DFMT_ATI2N:
            return "bc5-rg-unorm";
        case D3DFMT_NULL:
            // Nothing reads it, so the cheapest renderable format is the right
            // one: the size still has to match the depth attachment the pass
            // is really aiming at, but the per-texel cost does not.
            return "r8unorm";
        default:
            return null;
        }
    }

    const HALF_BITS_BUFFER = new ArrayBuffer(4);
    const HALF_BITS_F32 = new Float32Array(HALF_BITS_BUFFER);
    const HALF_BITS_U32 = new Uint32Array(HALF_BITS_BUFFER);

    function floatToHalfBits(value) {
        HALF_BITS_F32[0] = value;
        const bits = HALF_BITS_U32[0];
        const sign = (bits >>> 16) & 0x8000;
        let exponent = (bits >>> 23) & 0xff;
        let mantissa = bits & 0x7fffff;
        if (exponent === 0xff)
            return sign | (mantissa ? 0x7e00 : 0x7c00);
        exponent = exponent - 127 + 15;
        if (exponent >= 31) return sign | 0x7c00;
        if (exponent <= 0) {
            if (exponent < -10) return sign;
            const normalized = mantissa | 0x800000;
            const shift = 14 - exponent;
            let halfMantissa = normalized >>> shift;
            const remainderMask = (1 << shift) - 1;
            const remainder = normalized & remainderMask;
            const halfway = 1 << (shift - 1);
            if (remainder > halfway ||
                    (remainder === halfway && (halfMantissa & 1)))
                ++halfMantissa;
            return sign | halfMantissa;
        }
        let halfMantissa = mantissa >>> 13;
        const remainder = mantissa & 0x1fff;
        if (remainder > 0x1000 ||
                (remainder === 0x1000 && (halfMantissa & 1))) {
            ++halfMantissa;
            if (halfMantissa === 0x400) {
                halfMantissa = 0;
                if (++exponent >= 31) return sign | 0x7c00;
            }
        }
        return sign | (exponent << 10) | halfMantissa;
    }

    function writeHalf(dest, offset, value) {
        const bits = floatToHalfBits(value);
        dest[offset] = bits & 0xff;
        dest[offset + 1] = bits >>> 8;
    }

    function halfBitsToFloat(bits) {
        const sign = (bits & 0x8000) ? -1 : 1;
        const exponent = (bits >>> 10) & 0x1f;
        const mantissa = bits & 0x3ff;
        if (!exponent)
            return mantissa ? sign * Math.pow(2, -14) * mantissa / 1024
                : sign === -1 ? -0 : 0;
        if (exponent === 0x1f)
            return mantissa ? NaN : sign * Infinity;
        return sign * Math.pow(2, exponent - 15) * (1 + mantissa / 1024);
    }

    function d3dBytesPerTexel(format) {
        switch (format) {
        case D3DFMT_R5G6B5:
        case D3DFMT_X1R5G5B5:
        case D3DFMT_A1R5G5B5:
        case D3DFMT_A4R4G4B4:
        case D3DFMT_R16F:
            return 2;
        case D3DFMT_A8R8G8B8:
        case D3DFMT_X8R8G8B8:
        case D3DFMT_A2B10G10R10:
        case D3DFMT_A2R10G10B10:
        case D3DFMT_G16R16F:
        case D3DFMT_R32F:
            return 4;
        case D3DFMT_A16B16G16R16F:
        case D3DFMT_G32R32F:
            return 8;
        case D3DFMT_A32B32G32R32F:
            return 16;
        default:
            return 0;
        }
    }

    function packGPUReadbackRow(format, gpuFormat, source, sourceOffset,
            width, destination, destinationOffset) {
        const sourceView = new DataView(source.buffer,
            source.byteOffset, source.byteLength);
        const destinationView = new DataView(destination.buffer,
            destination.byteOffset, destination.byteLength);
        const sourceBpp = gpuFormat === "rgba16float" ? 8
            : gpuFormat === "rg32float" ? 8
            : gpuFormat === "rgba32float" ? 16 : 4;
        const destinationBpp = d3dBytesPerTexel(format);
        const clamp = value => Math.max(0, Math.min(1,
            Number.isFinite(value) ? value : 0));
        const unorm = (value, maximum) =>
            Math.round(clamp(value) * maximum);
        for (let x = 0; x < width; ++x) {
            const sourceAt = sourceOffset + x * sourceBpp;
            const destinationAt = destinationOffset + x * destinationBpp;
            let r, g, b, a;
            if (gpuFormat === "rgba16float") {
                r = halfBitsToFloat(sourceView.getUint16(sourceAt, true));
                g = halfBitsToFloat(sourceView.getUint16(sourceAt + 2, true));
                b = halfBitsToFloat(sourceView.getUint16(sourceAt + 4, true));
                a = halfBitsToFloat(sourceView.getUint16(sourceAt + 6, true));
            } else if (gpuFormat === "r32float") {
                r = sourceView.getFloat32(sourceAt, true); g = b = 0; a = 1;
            } else if (gpuFormat === "rg32float") {
                r = sourceView.getFloat32(sourceAt, true);
                g = sourceView.getFloat32(sourceAt + 4, true); b = 0; a = 1;
            } else if (gpuFormat === "rgba32float") {
                r = sourceView.getFloat32(sourceAt, true);
                g = sourceView.getFloat32(sourceAt + 4, true);
                b = sourceView.getFloat32(sourceAt + 8, true);
                a = sourceView.getFloat32(sourceAt + 12, true);
            } else if (gpuFormat === "bgra8unorm" ||
                    gpuFormat === "bgra8unorm-srgb") {
                b = source[sourceAt] / 255; g = source[sourceAt + 1] / 255;
                r = source[sourceAt + 2] / 255; a = source[sourceAt + 3] / 255;
            } else {
                r = source[sourceAt] / 255; g = source[sourceAt + 1] / 255;
                b = source[sourceAt + 2] / 255; a = source[sourceAt + 3] / 255;
            }
            switch (format) {
            case D3DFMT_A8R8G8B8:
            case D3DFMT_X8R8G8B8:
                destination[destinationAt] = unorm(b, 255);
                destination[destinationAt + 1] = unorm(g, 255);
                destination[destinationAt + 2] = unorm(r, 255);
                destination[destinationAt + 3] = format === D3DFMT_A8R8G8B8
                    ? unorm(a, 255) : 0xff;
                break;
            case D3DFMT_R5G6B5:
                destinationView.setUint16(destinationAt,
                    (unorm(r, 31) << 11) | (unorm(g, 63) << 5) |
                    unorm(b, 31), true);
                break;
            case D3DFMT_X1R5G5B5:
            case D3DFMT_A1R5G5B5:
                destinationView.setUint16(destinationAt,
                    ((format === D3DFMT_X1R5G5B5 ? 1 : unorm(a, 1)) << 15) |
                    (unorm(r, 31) << 10) | (unorm(g, 31) << 5) |
                    unorm(b, 31), true);
                break;
            case D3DFMT_A4R4G4B4:
                destinationView.setUint16(destinationAt,
                    (unorm(a, 15) << 12) | (unorm(r, 15) << 8) |
                    (unorm(g, 15) << 4) | unorm(b, 15), true);
                break;
            case D3DFMT_A2B10G10R10:
                destinationView.setUint32(destinationAt,
                    (unorm(r, 1023) | (unorm(g, 1023) << 10) |
                    (unorm(b, 1023) << 20) | (unorm(a, 3) << 30)) >>> 0,
                    true);
                break;
            case D3DFMT_A2R10G10B10:
                destinationView.setUint32(destinationAt,
                    (unorm(b, 1023) | (unorm(g, 1023) << 10) |
                    (unorm(r, 1023) << 20) | (unorm(a, 3) << 30)) >>> 0,
                    true);
                break;
            case D3DFMT_R16F:
                destinationView.setUint16(destinationAt,
                    floatToHalfBits(r), true);
                break;
            case D3DFMT_G16R16F:
                destinationView.setUint16(destinationAt,
                    floatToHalfBits(r), true);
                destinationView.setUint16(destinationAt + 2,
                    floatToHalfBits(g), true);
                break;
            case D3DFMT_A16B16G16R16F:
                destinationView.setUint16(destinationAt,
                    floatToHalfBits(r), true);
                destinationView.setUint16(destinationAt + 2,
                    floatToHalfBits(g), true);
                destinationView.setUint16(destinationAt + 4,
                    floatToHalfBits(b), true);
                destinationView.setUint16(destinationAt + 6,
                    floatToHalfBits(a), true);
                break;
            case D3DFMT_R32F:
                destinationView.setFloat32(destinationAt, r, true);
                break;
            case D3DFMT_G32R32F:
                destinationView.setFloat32(destinationAt, r, true);
                destinationView.setFloat32(destinationAt + 4, g, true);
                break;
            case D3DFMT_A32B32G32R32F:
                destinationView.setFloat32(destinationAt, r, true);
                destinationView.setFloat32(destinationAt + 4, g, true);
                destinationView.setFloat32(destinationAt + 8, b, true);
                destinationView.setFloat32(destinationAt + 12, a, true);
                break;
            default:
                throw new Error("unsupported render-target readback format " +
                    format);
            }
        }
    }

    function signedNormalized(value, bitCount) {
        const signBit = 1 << (bitCount - 1);
        const fullRange = 1 << bitCount;
        const signed = value & signBit ? value - fullRange : value;
        return signed === -signBit ? -1 : signed / (signBit - 1);
    }

    // Expands one source row to the WebGPU format returned by formatToGPU().
    // Ordinary colour/luminance formats become RGBA8 UNORM, signed bump maps
    // become RGBA8 SNORM, and mixed/high-precision formats become RGBA16F.
    // BCn formats bypass this routine and stay block-compressed end-to-end.
    // BT.601 studio-swing YCbCr, which is what D3D9's 4:2:2 formats carry --
    // they exist for video frames, and a video decoder writes 16..235 luma.
    // Treating it as full range washes blacks out to dark grey, which is
    // exactly the kind of "close enough to look intentional" error that never
    // gets noticed.
    function yuvToRGB(y, u, v, out) {
        const c = y - 16, d = u - 128, e = v - 128;
        out[0] = Math.min(255, Math.max(0, (298 * c + 409 * e + 128) >> 8));
        out[1] = Math.min(255, Math.max(0,
            (298 * c - 100 * d - 208 * e + 128) >> 8));
        out[2] = Math.min(255, Math.max(0, (298 * c + 516 * d + 128) >> 8));
    }

    const YUV_SCRATCH = new Int32Array(3);

    // The 4:2:2 and RGBG/GRGB formats describe two pixels per 32-bit block, so
    // they cannot be expanded one texel at a time from an index alone: texel i
    // needs the block containing i and its position within it. `palette` is the
    // 256-entry Uint8Array (RGBA) a palettized format indexes into, or null.
    function expandPairedRowToGPU(format, source, sourceOffset, count, dest,
            destOffset) {
        for (let i = 0; i < count; ++i) {
            const block = sourceOffset + (i >> 1) * 4;
            const second = (i & 1) !== 0;
            const out = destOffset + i * 4;
            let r, g, b;
            switch (format) {
            case D3DFMT_YUY2: { // Y0 U Y1 V
                yuvToRGB(source[block + (second ? 2 : 0)], source[block + 1],
                    source[block + 3], YUV_SCRATCH);
                r = YUV_SCRATCH[0]; g = YUV_SCRATCH[1]; b = YUV_SCRATCH[2];
                break;
            }
            case D3DFMT_UYVY: { // U Y0 V Y1
                yuvToRGB(source[block + (second ? 3 : 1)], source[block],
                    source[block + 2], YUV_SCRATCH);
                r = YUV_SCRATCH[0]; g = YUV_SCRATCH[1]; b = YUV_SCRATCH[2];
                break;
            }
            case D3DFMT_R8G8_B8G8: // R G0 B G1: the pair shares R and B
                r = source[block];
                g = source[block + (second ? 3 : 1)];
                b = source[block + 2];
                break;
            default:               // D3DFMT_G8R8_G8B8 -- G0 R G1 B
                r = source[block + 1];
                g = source[block + (second ? 2 : 0)];
                b = source[block + 3];
                break;
            }
            dest[out] = r; dest[out + 1] = g; dest[out + 2] = b;
            dest[out + 3] = 0xff;
        }
    }

    function expandRowToGPU(format, source, sourceOffset, count, dest,
            destOffset, palette) {
        if (format === D3DFMT_R32F || format === D3DFMT_G32R32F ||
                format === D3DFMT_A32B32G32R32F) {
            const bytes = count * gpuBytesPerTexel(format);
            dest.set(source.subarray(sourceOffset, sourceOffset + bytes), destOffset);
            return;
        }
        if (isPackedPairFormat(format)) {
            expandPairedRowToGPU(format, source, sourceOffset, count, dest,
                destOffset);
            return;
        }
        if (isPalettizedFormat(format)) {
            const stride = format === D3DFMT_A8P8 ? 2 : 1;
            for (let i = 0; i < count; ++i) {
                const at = sourceOffset + i * stride;
                // D3DFMT_A8P8 is little-endian [index, alpha]; the palette's
                // own alpha is overridden by the per-texel one.
                const entry = (palette ? source[at] : 0) * 4;
                const out = destOffset + i * 4;
                if (palette) {
                    dest[out] = palette[entry];
                    dest[out + 1] = palette[entry + 1];
                    dest[out + 2] = palette[entry + 2];
                    dest[out + 3] = stride === 2
                        ? source[at + 1] : palette[entry + 3];
                } else {
                    // No palette has been set yet. Opaque white keeps the draw
                    // neutral instead of painting the scene with whatever the
                    // uninitialised entries happened to be.
                    dest[out] = dest[out + 1] = dest[out + 2] = 0xff;
                    dest[out + 3] = stride === 2 ? source[at + 1] : 0xff;
                }
            }
            return;
        }
        for (let i = 0; i < count; ++i) {
            let r, g, b, a;
            if (isHalfFloatExpansionFormat(format)) {
                let u, v, w, q;
                if (format === D3DFMT_CxV8U8) {
                    const at = sourceOffset + i * 2;
                    u = signedNormalized(source[at], 8);
                    v = signedNormalized(source[at + 1], 8);
                    w = Math.sqrt(Math.max(0, 1 - u * u - v * v));
                    q = 1;
                } else if (format === D3DFMT_L16) {
                    const at = sourceOffset + i * 2;
                    const luminance = (source[at] |
                        (source[at + 1] << 8)) / 65535;
                    u = v = w = luminance;
                    q = 1;
                } else if (format === D3DFMT_R16F) {
                    const at = sourceOffset + i * 2;
                    const out = destOffset + i * 8;
                    dest[out] = source[at];
                    dest[out + 1] = source[at + 1];
                    writeHalf(dest, out + 2, 0);
                    writeHalf(dest, out + 4, 0);
                    writeHalf(dest, out + 6, 1);
                    continue;
                } else if (format === D3DFMT_G16R16F) {
                    const at = sourceOffset + i * 4;
                    const out = destOffset + i * 8;
                    dest[out] = source[at];
                    dest[out + 1] = source[at + 1];
                    dest[out + 2] = source[at + 2];
                    dest[out + 3] = source[at + 3];
                    writeHalf(dest, out + 4, 0);
                    writeHalf(dest, out + 6, 1);
                    continue;
                } else if (format === D3DFMT_A16B16G16R16F) {
                    const at = sourceOffset + i * 8;
                    const out = destOffset + i * 8;
                    dest.set(source.subarray(at, at + 8), out);
                    continue;
                } else if (format === D3DFMT_G16R16 ||
                        format === D3DFMT_A16B16G16R16) {
                    const at = sourceOffset + i *
                        (format === D3DFMT_G16R16 ? 4 : 8);
                    const readUNorm16 = offset =>
                        (source[offset] | (source[offset + 1] << 8)) / 65535;
                    u = readUNorm16(at);
                    v = readUNorm16(at + 2);
                    w = format === D3DFMT_A16B16G16R16 ?
                        readUNorm16(at + 4) : 0;
                    q = format === D3DFMT_A16B16G16R16 ?
                        readUNorm16(at + 6) : 1;
                } else if (format === D3DFMT_A2B10G10R10 ||
                        format === D3DFMT_A2R10G10B10) {
                    const at = sourceOffset + i * 4;
                    const value = (source[at] | (source[at + 1] << 8) |
                        (source[at + 2] << 16) |
                        (source[at + 3] << 24)) >>> 0;
                    const c0 = (value & 0x3ff) / 1023;
                    const c1 = ((value >>> 10) & 0x3ff) / 1023;
                    const c2 = ((value >>> 20) & 0x3ff) / 1023;
                    u = format === D3DFMT_A2B10G10R10 ? c0 : c2;
                    v = c1;
                    w = format === D3DFMT_A2B10G10R10 ? c2 : c0;
                    q = (value >>> 30) / 3;
                } else if (format === D3DFMT_L6V5U5) {
                    const value = source[sourceOffset + i * 2] |
                        (source[sourceOffset + i * 2 + 1] << 8);
                    u = signedNormalized(value & 0x1f, 5);
                    v = signedNormalized((value >>> 5) & 0x1f, 5);
                    w = ((value >>> 10) & 0x3f) / 63;
                    q = 1;
                } else if (format === D3DFMT_X8L8V8U8) {
                    const at = sourceOffset + i * 4;
                    u = signedNormalized(source[at], 8);
                    v = signedNormalized(source[at + 1], 8);
                    w = source[at + 2] / 255;
                    q = 1;
                } else if (format === D3DFMT_V16U16) {
                    const at = sourceOffset + i * 4;
                    const rawU = source[at] | (source[at + 1] << 8);
                    const rawV = source[at + 2] | (source[at + 3] << 8);
                    u = signedNormalized(rawU, 16);
                    v = signedNormalized(rawV, 16);
                    w = q = 1;
                } else if (format === D3DFMT_Q16W16V16U16) {
                    const at = sourceOffset + i * 8;
                    const read = offset => signedNormalized(
                        source[offset] | (source[offset + 1] << 8), 16);
                    u = read(at);
                    v = read(at + 2);
                    w = read(at + 4);
                    q = read(at + 6);
                } else if (format === D3DFMT_W11V11U10) {
                    // The one D3D8 bump format whose channels are not a whole
                    // number of bits alike: U is 10 bits at 0-9, V is 11 at
                    // 10-20, W is 11 at 21-31, and all three are signed.
                    const at = sourceOffset + i * 4;
                    const value = (source[at] | (source[at + 1] << 8) |
                        (source[at + 2] << 16) |
                        (source[at + 3] << 24)) >>> 0;
                    u = signedNormalized(value & 0x3ff, 10);
                    v = signedNormalized((value >>> 10) & 0x7ff, 11);
                    w = signedNormalized((value >>> 21) & 0x7ff, 11);
                    q = 1;
                } else {
                    const at = sourceOffset + i * 4;
                    const value = (source[at] | (source[at + 1] << 8) |
                        (source[at + 2] << 16) |
                        (source[at + 3] << 24)) >>> 0;
                    u = signedNormalized(value & 0x3ff, 10);
                    v = signedNormalized((value >>> 10) & 0x3ff, 10);
                    w = signedNormalized((value >>> 20) & 0x3ff, 10);
                    q = (value >>> 30) / 3;
                }
                const out = destOffset + i * 8;
                writeHalf(dest, out, u);
                writeHalf(dest, out + 2, v);
                writeHalf(dest, out + 4, w);
                writeHalf(dest, out + 6, q);
                continue;
            }
            switch (format) {
            case D3DFMT_R8G8B8: {
                const at = sourceOffset + i * 3;
                b = source[at]; g = source[at + 1]; r = source[at + 2];
                a = 0xff;
                break;
            }
            case D3DFMT_A8R8G8B8:
            case D3DFMT_X8R8G8B8: {
                const value = source[sourceOffset + i * 4] |
                    (source[sourceOffset + i * 4 + 1] << 8) |
                    (source[sourceOffset + i * 4 + 2] << 16) |
                    (source[sourceOffset + i * 4 + 3] << 24);
                b = value & 0xff; g = (value >>> 8) & 0xff;
                r = (value >>> 16) & 0xff;
                a = format === D3DFMT_A8R8G8B8 ? (value >>> 24) & 0xff : 0xff;
                break;
            }
            case D3DFMT_R5G6B5: {
                const value = source[sourceOffset + i * 2] |
                    (source[sourceOffset + i * 2 + 1] << 8);
                r = ((value >>> 11) & 0x1f) * 255 / 31;
                g = ((value >>> 5) & 0x3f) * 255 / 63;
                b = (value & 0x1f) * 255 / 31;
                a = 0xff;
                break;
            }
            case D3DFMT_X1R5G5B5:
            case D3DFMT_A1R5G5B5: {
                const value = source[sourceOffset + i * 2] |
                    (source[sourceOffset + i * 2 + 1] << 8);
                r = ((value >>> 10) & 0x1f) * 255 / 31;
                g = ((value >>> 5) & 0x1f) * 255 / 31;
                b = (value & 0x1f) * 255 / 31;
                a = format === D3DFMT_A1R5G5B5 ?
                    ((value >>> 15) & 0x1) * 255 : 0xff;
                break;
            }
            case D3DFMT_A4R4G4B4: {
                const value = source[sourceOffset + i * 2] |
                    (source[sourceOffset + i * 2 + 1] << 8);
                r = ((value >>> 8) & 0xf) * 255 / 15;
                g = ((value >>> 4) & 0xf) * 255 / 15;
                b = (value & 0xf) * 255 / 15;
                a = ((value >>> 12) & 0xf) * 255 / 15;
                break;
            }
            case D3DFMT_R3G3B2: {
                const value = source[sourceOffset + i];
                r = ((value >>> 5) & 0x7) * 255 / 7;
                g = ((value >>> 2) & 0x7) * 255 / 7;
                b = (value & 0x3) * 255 / 3;
                a = 0xff;
                break;
            }
            case D3DFMT_A8R3G3B2: {
                const at = sourceOffset + i * 2;
                const value = source[at];
                r = ((value >>> 5) & 0x7) * 255 / 7;
                g = ((value >>> 2) & 0x7) * 255 / 7;
                b = (value & 0x3) * 255 / 3;
                a = source[at + 1];
                break;
            }
            case D3DFMT_X4R4G4B4: {
                const value = source[sourceOffset + i * 2] |
                    (source[sourceOffset + i * 2 + 1] << 8);
                r = ((value >>> 8) & 0xf) * 17;
                g = ((value >>> 4) & 0xf) * 17;
                b = (value & 0xf) * 17;
                a = 0xff;
                break;
            }
            case D3DFMT_A8B8G8R8:
            case D3DFMT_X8B8G8R8: {
                const at = sourceOffset + i * 4;
                r = source[at]; g = source[at + 1]; b = source[at + 2];
                a = format === D3DFMT_A8B8G8R8 ? source[at + 3] : 0xff;
                break;
            }
            case D3DFMT_L8:
                r = g = b = source[sourceOffset + i];
                a = 0xff;
                break;
            case D3DFMT_A8:
                // A8 is the sole D3D9 format whose missing colour channels
                // default to zero rather than one.
                r = g = b = 0;
                a = source[sourceOffset + i];
                break;
            case D3DFMT_A8L8: {
                const at = sourceOffset + i * 2;
                r = g = b = source[at]; a = source[at + 1];
                break;
            }
            case D3DFMT_A4L4: {
                const value = source[sourceOffset + i];
                r = g = b = (value & 0xf) * 17;
                a = (value >>> 4) * 17;
                break;
            }
            case D3DFMT_V8U8: {
                const at = sourceOffset + i * 2;
                r = source[at]; g = source[at + 1]; b = a = 0x7f;
                break;
            }
            case D3DFMT_Q8W8V8U8: {
                const at = sourceOffset + i * 4;
                r = source[at]; g = source[at + 1];
                b = source[at + 2]; a = source[at + 3];
                break;
            }
            case D3DFMT_INDEX16: {
                /*
                 * INDEX16/32 are buffer formats, not standard D3D colour
                 * formats, but old capability scanners also try them as
                 * textures. Preserve the little-endian index bytes in RGBA
                 * instead of inventing a lossy colour conversion: shaders can
                 * reconstruct the exact value after multiplying by 255.
                 */
                const at = sourceOffset + i * 2;
                r = source[at]; g = source[at + 1]; b = 0; a = 0xff;
                break;
            }
            case D3DFMT_INDEX32: {
                const at = sourceOffset + i * 4;
                r = source[at]; g = source[at + 1];
                b = source[at + 2]; a = source[at + 3];
                break;
            }
            default:
                r = g = b = a = 0;
                break;
            }
            dest[destOffset + i * 4] = r | 0;
            dest[destOffset + i * 4 + 1] = g | 0;
            dest[destOffset + i * 4 + 2] = b | 0;
            dest[destOffset + i * 4 + 3] = a | 0;
        }
    }

    // Row-major multiply: out[row][col] = sum_k a[row][k] * b[k][col]. This is
    // D3D's own convention, so multiply4x4(W, V) chains the way a row vector
    // would travel through them (v * W * V). See uniformBufferFor for why no
    // transpose is needed when handing the result to WGSL.
    function multiply4x4(a, b) {
        const out = new Float32Array(16);
        for (let row = 0; row < 4; ++row) {
            for (let col = 0; col < 4; ++col) {
                let sum = 0;
                for (let k = 0; k < 4; ++k)
                    sum += a[row * 4 + k] * b[k * 4 + col];
                out[row * 4 + col] = sum;
            }
        }
        return out;
    }

    const IDENTITY4x4 = new Float32Array([
        1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1,
    ]);

    // The normal matrix for row-vector maths. A normal n must satisfy
    // n' = n * (M^-1)^T for the transformed geometry to keep its perpendicular
    // relationship, and for a 3x3 that expression reduces to the cofactor
    // matrix divided by the determinant -- no explicit inverse or transpose
    // needed. Only the upper 3x3 participates: a normal has w = 0, so the
    // translation row can never reach it.
    //
    // A singular matrix (a degenerate scale, which engines do produce for
    // collapsed geometry) has no inverse; falling back to identity keeps the
    // draw legal and unlit rather than filling the buffer with NaN, which would
    // propagate into the position and make the whole mesh vanish.
    function inverseTranspose3x3(m) {
        const a = m[0], b = m[1], c = m[2];
        const d = m[4], e = m[5], f = m[6];
        const g = m[8], h = m[9], i = m[10];
        const c00 = e * i - f * h, c01 = f * g - d * i, c02 = d * h - e * g;
        const determinant = a * c00 + b * c01 + c * c02;
        const out = new Float32Array(16);
        out[15] = 1;
        if (!determinant || !isFinite(determinant)) {
            out[0] = out[5] = out[10] = 1;
            return out;
        }
        const scale = 1 / determinant;
        out[0] = c00 * scale;
        out[1] = c01 * scale;
        out[2] = c02 * scale;
        out[4] = (c * h - b * i) * scale;
        out[5] = (a * i - c * g) * scale;
        out[6] = (b * g - a * h) * scale;
        out[8] = (b * f - c * e) * scale;
        out[9] = (c * d - a * f) * scale;
        out[10] = (a * e - b * d) * scale;
        return out;
    }

    // Row-vector transforms, matching multiply4x4's convention: v' = v * M.
    function transformPoint(m, v) {
        return [
            v[0] * m[0] + v[1] * m[4] + v[2] * m[8] + m[12],
            v[0] * m[1] + v[1] * m[5] + v[2] * m[9] + m[13],
            v[0] * m[2] + v[1] * m[6] + v[2] * m[10] + m[14],
        ];
    }

    function transformDirection(m, v) {
        return [
            v[0] * m[0] + v[1] * m[4] + v[2] * m[8],
            v[0] * m[1] + v[1] * m[5] + v[2] * m[9],
            v[0] * m[2] + v[1] * m[6] + v[2] * m[10],
        ];
    }

    function normalize3(v) {
        const length = Math.hypot(v[0], v[1], v[2]);
        return length > 0 ? [v[0] / length, v[1] / length, v[2] / length]
            : [0, 0, 1];
    }

    // What D3D9 lights with when the app never called SetMaterial. Not all
    // zeroes: a zero diffuse would render the mesh black, which looks like a
    // bug in the lighting rather than like missing state.
    const DEFAULT_MATERIAL = {
        diffuse: [1, 1, 1, 1], ambient: [1, 1, 1, 1],
        specular: [0, 0, 0, 0], emissive: [0, 0, 0, 0], power: 0,
    };

    // The inter-stage contract shared with translated shaders. Both stages
    // always agree on it, whichever of the four VS/PS combinations a draw
    // uses (see the file header).
    const VARYING_COUNT = shaderPipeline.VARYING_COUNT;
    const VARYING_COLOR0 = shaderPipeline.VARYING_COLOR0;
    // D3DRS_SHADEMODE. D3DSHADE_FLAT takes the colour of the primitive's first
    // vertex instead of interpolating, which is exactly WGSL's
    // @interpolate(flat) -- whose default sampling is `first`, the same
    // provoking vertex D3D9 uses.
    //
    // It applies to the two colour varyings only. Texture coordinates and fog
    // keep interpolating under flat shading in D3D9, and a title that flat
    // shades a textured surface expects the texture to still follow the
    // surface. D3DSHADE_PHONG is in the enum but no D3D9 device ever
    // implemented it; D3D9 treats it as GOURAUD, and so does this.
    const D3DSHADE_FLAT = 1, D3DSHADE_GOURAUD = 2;
    function varyingDeclaration(slot, flatShading) {
        const flat = flatShading &&
            (slot === VARYING_COLOR0 || slot === shaderPipeline.VARYING_COLOR1);
        return "    @location(" + slot + ")" +
            (flat ? " @interpolate(flat)" : "") +
            " varying" + slot + ": vec4<f32>,";
    }
    const VARYING_TEXCOORD0 = shaderPipeline.VARYING_TEXCOORD0;

    // Vertex attribute locations the fixed-function vertex stage consumes.
    // These are assigned by *semantic*, not by the element's position in the
    // declaration array. M1 assigned them by iteration order and hardcoded
    // position/colour/texcoord as locations 0/1/2 in the WGSL, which agreed
    // only for declarations that happened to list the elements in that
    // order; a declaration with TEXCOORD before COLOR silently fed the
    // texcoord bytes into the colour attribute.
    // M3 widened this from three locations to twelve: fixed-function lighting
    // reads NORMAL, the specular material source can read COLOR1, and a
    // multi-stage cascade can reference all eight coordinate sets rather than
    // only TEXCOORD0.
    const FF_LOCATION_POSITION = 0;
    const FF_LOCATION_COLOR0 = 1;
    const FF_LOCATION_COLOR1 = 2;
    const FF_LOCATION_NORMAL = 3;
    const FF_LOCATION_TEXCOORD0 = 4; // .. 11 for TEXCOORD0..7
    const FF_LOCATION_PSIZE = 12;
    // M7 added two more: fixed-function vertex blending reads the skinning
    // usages the declaration validator has always accepted.
    const FF_LOCATION_BLENDWEIGHT = 13;
    const FF_LOCATION_BLENDINDICES = 14;

    // D3D9's alpha test has no fixed-function equivalent in WebGPU: it has to
    // become a `discard` in the fragment shader, which means the comparison
    // and the reference value are baked into the shader and therefore into
    // the pipeline key. Returns "" when no test is needed.
    //
    // This matters far beyond a subtle shading difference. UI atlases and
    // billboarded foliage lean on alpha test to cut fully transparent texels;
    // without it those texels are drawn opaque, which reads as wrong or
    // missing texture on exactly the panels and edges that should be cut out.
    //
    // D3DCMPFUNC values are 1..8; the expression below is the *discard*
    // condition, i.e. the negation of "the fragment passes".
    function alphaTestDiscard(alphaTest, alphaExpression) {
        if (!alphaTest || !alphaTest.enabled) return "";
        const reference = (alphaTest.reference / 255).toFixed(6);
        const condition = {
            1: "true",                                        // NEVER
            2: "!(" + alphaExpression + " < " + reference + ")",   // LESS
            3: "!(" + alphaExpression + " == " + reference + ")",  // EQUAL
            4: "!(" + alphaExpression + " <= " + reference + ")",  // LESSEQUAL
            5: "!(" + alphaExpression + " > " + reference + ")",   // GREATER
            6: "!(" + alphaExpression + " != " + reference + ")",  // NOTEQUAL
            7: "!(" + alphaExpression + " >= " + reference + ")",  // GREATEREQUAL
        }[alphaTest.func];
        if (!condition) return ""; // ALWAYS (8) and anything unknown: no test
        return "    if (" + condition + ") { discard; }\n";
    }

    // `blend` is the signature's resolved vertexBlend (null when the draw is
    // not blended); it decides whether the skinning attributes are consumed.
    function fixedFunctionLocationFor(element, blend) {
        if (element.usage === DECLUSAGE_POSITION ||
                element.usage === DECLUSAGE_POSITIONT)
            return element.usageIndex === 0 ? FF_LOCATION_POSITION : -1;
        if (element.usage === DECLUSAGE_COLOR)
            return element.usageIndex === 0 ? FF_LOCATION_COLOR0
                : (element.usageIndex === 1 ? FF_LOCATION_COLOR1 : -1);
        if (element.usage === DECLUSAGE_NORMAL)
            return element.usageIndex === 0 ? FF_LOCATION_NORMAL : -1;
        if (element.usage === DECLUSAGE_TEXCOORD &&
                element.usageIndex < MAX_TEXCOORD_SETS)
            return FF_LOCATION_TEXCOORD0 + element.usageIndex;
        if (element.usage === DECLUSAGE_PSIZE)
            return element.usageIndex === 0 ? FF_LOCATION_PSIZE : -1;
        // The skinning usages are read only while vertex blending is actually
        // on. Reporting them unconditionally would put an attribute in the
        // vertex layout that the generated WGSL never declares, for every
        // declaration that carries blend data with D3DRS_VERTEXBLEND disabled
        // -- which is most of them, since engines share one declaration
        // between their skinned and unskinned passes.
        if (element.usage === DECLUSAGE_BLENDWEIGHT)
            return blend && blend.weightCount && element.usageIndex === 0
                ? FF_LOCATION_BLENDWEIGHT : -1;
        if (element.usage === DECLUSAGE_BLENDINDICES)
            return blend && blend.indexed && element.usageIndex === 0
                ? FF_LOCATION_BLENDINDICES : -1;
        return -1;
    }

    // The WGSL declaration for a vertex attribute is always vec4<f32>: WebGPU
    // fills the components a narrower vertex format does not supply with
    // (_, 0, 0, 1), which is exactly D3D9's rule for a FLOAT3 POSITION or a
    // FLOAT2 texcoord. One declared type per location also keeps a shader
    // module independent of which declaration is bound with it.
    // The one exception is an integer vertex format: WebGPU requires the WGSL
    // input's base type to match the format's, so a UBYTE4 BLENDINDICES has to
    // be declared vec4<u32>. `scalar` names that base type; it defaults to the
    // f32 every other fixed-function attribute uses.
    function vertexInputDeclaration(location, scalar) {
        return "@location(" + location + ") in" + location +
            ": vec4<" + (scalar || "f32") + ">";
    }

    // D3DDECLTYPE -> the WGSL base type its WebGPU format must be read as.
    // Only the integer formats need an entry; everything else is f32. UDEC3
    // (13) and DEC3N (14) arrive as a single packed uint32 rather than a
    // four-component vector, so they have no vec4 reading at all and return
    // null -- callers fall back rather than emit WGSL that will not compile.
    function declTypeInputScalar(type) {
        if (type === 13 || type === 14) return null;
        if (type === 5) return "u32";           // UBYTE4  -> uint8x4
        if (type === 6 || type === 7) return "i32"; // SHORT2/4 -> sint16x2/x4
        return "f32";
    }

    // ---- fixed-function uniform blocks ----
    //
    // Both fixed-function stages get a uniform block whose *shape follows the
    // signature*: an unlit untextured draw uploads 80 bytes, one with eight
    // lights and three texture-coordinate transforms uploads over a kilobyte.
    // The shape has to vary because a uniform buffer is built and written per
    // draw (see constantBufferFor), so paying the worst case on every draw
    // would multiply a War3 session's ~100k draws by an order of magnitude of
    // upload traffic for state most of them do not use.
    //
    // One field table drives both the WGSL struct text and the JS writer, so
    // the two cannot drift. That matters more than the usual DRY argument: a
    // mismatched offset here produces a garbage matrix or a black light, not a
    // compile error, which is the class of bug that costs a day to locate.
    //
    // Every field is a vec4, a mat4x4 or an array of a 16-multiple struct, so
    // all of them align to 16 in WGSL's uniform address space and offsets
    // accumulate by plain size with no padding rules to apply. assertAligned
    // holds us to that.
    function uniformBlockLayout(fields) {
        let offset = 0;
        const entries = [];
        for (const field of fields) {
            if (!field) continue;
            if (field.bytes % 16 !== 0 || offset % 16 !== 0)
                throw new Error("fixed-function uniform field " + field.name +
                    " is not 16-byte aligned; WGSL uniform layout would " +
                    "silently disagree with the writer");
            entries.push({ name: field.name, type: field.type,
                bytes: field.bytes, offset, source: field.source });
            offset += field.bytes;
        }
        return { entries, byteLength: Math.max(16, offset),
            byName: new Map(entries.map(entry => [entry.name, entry])) };
    }

    function uniformBlockStruct(structName, layout) {
        // A zero-field block still has to be a legal struct, and every
        // signature that produces one also produces a shader that reads
        // nothing from it, so a dummy vec4 costs one binding slot and no
        // correctness.
        const body = layout.entries.length
            ? layout.entries.map(entry =>
                "    " + entry.name + ": " + entry.type + ",").join("\n")
            : "    _unused: vec4<f32>,";
        return "struct " + structName + " {\n" + body + "\n};";
    }

    // The vertex block. `source` names what fills the field; writeFixedVertex-
    // Uniforms below is the single place that knows how.
    // D3D9 rasterises with the sample point at a pixel's integer corner; WebGPU,
    // like D3D10 and everything after it, samples at the pixel centre -- half a
    // pixel further along both axes. A D3D9 title blitting UI 1:1 has already
    // subtracted that half pixel itself (the "Directly Mapping Texels to Pixels"
    // adjustment every 2000s-era engine carries), so replaying its geometry
    // unchanged puts every sample exactly on a texel boundary and bilinear
    // filtering returns the mean of two texels. 3D art does not care -- nothing
    // in it is pixel-aligned to begin with -- but 12px CJK glyphs turn to mush,
    // which is exactly the split Kart Rider showed: a clean track and an
    // unreadable shop.
    //
    // Adding the half pixel back in clip space, scaled by w so it stays half a
    // pixel at any depth, is what wined3d's posFixup and DXVK's half-pixel
    // offset both do. Screen y grows downward while NDC y grows upward, hence
    // the sign flip on the second component.
    const HALF_PIXEL_OFFSET_BODY =
        "    result.position = vec4<f32>(\n" +
        "        result.position.x + result.position.w / uniforms.viewport.x,\n" +
        "        result.position.y - result.position.w / uniforms.viewport.y,\n" +
        "        result.position.zw);";

    function fixedVertexUniformLayout(signature) {
        // A blended draw cannot pre-multiply the world matrix into anything,
        // because which world matrix applies is a per-vertex question. So the
        // chain splits: the shader poses the vertex into world space from the
        // matrix array, and these carry only what comes after that.
        const blend = signature.vertexBlend;
        const fields = [
            { name: blend ? "view_projection" : "world_view_projection",
                type: "mat4x4<f32>", bytes: 64 },
            { name: "viewport", type: "vec4<f32>", bytes: 16 },
        ];
        if (blend)
            fields.push({ name: "blend_worlds",
                type: "array<mat4x4<f32>, " + blend.matrixSlots + ">",
                bytes: 64 * blend.matrixSlots });
        // D3D9 fixed-function clip-plane equations are in world space. The
        // ordinary position path only needs a pre-multiplied WVP matrix, so
        // retain the world matrix separately when clipping needs that space.
        if (signature.clipPlaneCount && !blend &&
                signature.positionType !== "screen")
            fields.push({ name: "world_matrix",
                type: "mat4x4<f32>", bytes: 64 });
        if (signature.needsViewSpace) {
            fields.push({ name: blend ? "view_matrix" : "world_view",
                type: "mat4x4<f32>", bytes: 64 });
            // Inverse-transpose of the preceding matrix's upper 3x3, widened to
            // a mat4 so it obeys the same 16-byte rule as everything else here.
            fields.push({ name: "normal_matrix", type: "mat4x4<f32>", bytes: 64 });
        }
        if (signature.fogMode)
            fields.push({ name: "fog_params", type: "vec4<f32>", bytes: 16 });
        for (const stage of signature.coordStages) {
            if (stage.transformCount)
                fields.push({ name: "texture_transform" + stage.index,
                    type: "mat4x4<f32>", bytes: 64, source: stage.index });
        }
        if (signature.lighting) {
            fields.push(
                { name: "material_diffuse", type: "vec4<f32>", bytes: 16 },
                { name: "material_ambient", type: "vec4<f32>", bytes: 16 },
                { name: "material_specular", type: "vec4<f32>", bytes: 16 },
                { name: "material_emissive", type: "vec4<f32>", bytes: 16 },
                // xyz = D3DRS_AMBIENT, w = the material's specular power.
                { name: "ambient_power", type: "vec4<f32>", bytes: 16 });
            if (signature.lighting.lights.length)
                fields.push({ name: "lights",
                    type: "array<D9Light, " + signature.lighting.lights.length + ">",
                    bytes: 112 * signature.lighting.lights.length });
        }
        if (signature.clipPlaneCount)
            fields.push({ name: "clip_planes",
                type: "array<vec4<f32>, " + signature.clipPlaneCount + ">",
                bytes: 16 * signature.clipPlaneCount });
        if (signature.pointExpansion) {
            fields.push(
                { name: "point_viewport", type: "vec4<f32>", bytes: 16 },
                // x=size, y=min, z=max, w reserved.
                { name: "point_params", type: "vec4<f32>", bytes: 16 });
            if (signature.pointScale)
                fields.push({ name: "point_scale", type: "vec4<f32>", bytes: 16 });
        }
        return uniformBlockLayout(fields);
    }

    // The pixel block: only what the texture cascade and the fog blend read.
    function fixedPixelUniformLayout(signature) {
        const fields = [];
        if (signature.fogMode)
            fields.push({ name: "fog_color", type: "vec4<f32>", bytes: 16 });
        if (signature.tableFog)
            fields.push({ name: "fog_params", type: "vec4<f32>", bytes: 16 });
        if (signature.usesTextureFactor)
            fields.push({ name: "texture_factor", type: "vec4<f32>", bytes: 16 });
        for (const stage of signature.stages) {
            if (stage.usesConstant)
                fields.push({ name: "stage_constant" + stage.index,
                    type: "vec4<f32>", bytes: 16, source: stage.index });
            // The bump matrix and luminance terms belong to the stage that
            // declared BUMPENVMAP, not to the stage that samples with them.
            if (stage.isBumpSource) {
                fields.push({ name: "stage_bump" + stage.index,
                    type: "vec4<f32>", bytes: 16, bumpSource: stage.index });
                if (stage.colorOp === D3DTOP_BUMPENVMAPLUMINANCE)
                    fields.push({ name: "stage_bump_lum" + stage.index,
                        type: "vec4<f32>", bytes: 16,
                        bumpLuminanceSource: stage.index });
            }
        }
        return uniformBlockLayout(fields);
    }

    function fixedFogFactorExpression(mode, distance) {
        return {
            [D3DFOG_LINEAR]: "clamp((uniforms.fog_params.y - " + distance + ") / " +
                "max(uniforms.fog_params.y - uniforms.fog_params.x, 1e-6), 0.0, 1.0)",
            [D3DFOG_EXP]: "clamp(exp(-(uniforms.fog_params.z * " + distance + ")), " +
                "0.0, 1.0)",
            [D3DFOG_EXP2]: "clamp(exp(-((uniforms.fog_params.z * " + distance + ") * " +
                "(uniforms.fog_params.z * " + distance + "))), 0.0, 1.0)",
        }[mode] || null;
    }

    // ---- D3DTEXTUREOP -> WGSL ----
    //
    // D3D9's texture cascade runs the colour and alpha channels through
    // *separate* operations with separate arguments, so each operation is
    // emitted twice: once over vec3 and once over f32. `blend` names the alpha
    // an op blends with (diffuse/texture/factor/current), which the caller
    // supplies as an already-built scalar expression.
    //
    // Only the operations fill_caps() lists in TextureOpCaps appear here.
    // Returning null makes the caller count the draw and fall back to
    // SELECTARG1 rather than inventing an approximation.
    function textureOpExpression(op, type, args, blend) {
        const one = type === "vec3<f32>" ? "vec3<f32>(1.0)" : "1.0";
        const half = type === "vec3<f32>" ? "vec3<f32>(0.5)" : "0.5";
        const a0 = args[0], a1 = args[1], a2 = args[2];
        switch (op) {
        case D3DTOP_SELECTARG1: return a1;
        case D3DTOP_SELECTARG2: return a2;
        case D3DTOP_MODULATE: return "(" + a1 + " * " + a2 + ")";
        case D3DTOP_MODULATE2X: return "((" + a1 + " * " + a2 + ") * 2.0)";
        case D3DTOP_MODULATE4X: return "((" + a1 + " * " + a2 + ") * 4.0)";
        case D3DTOP_ADD: return "(" + a1 + " + " + a2 + ")";
        case D3DTOP_ADDSIGNED:
            return "(" + a1 + " + " + a2 + " - " + half + ")";
        case D3DTOP_ADDSIGNED2X:
            return "((" + a1 + " + " + a2 + " - " + half + ") * 2.0)";
        case D3DTOP_SUBTRACT: return "(" + a1 + " - " + a2 + ")";
        case D3DTOP_ADDSMOOTH:
            return "(" + a1 + " + " + a2 + " * (" + one + " - " + a1 + "))";
        case D3DTOP_BLENDDIFFUSEALPHA:
        case D3DTOP_BLENDTEXTUREALPHA:
        case D3DTOP_BLENDFACTORALPHA:
        case D3DTOP_BLENDCURRENTALPHA:
            return "mix(" + a2 + ", " + a1 + ", " + blend + ")";
        case D3DTOP_BLENDTEXTUREALPHAPM:
            // Pre-multiplied: arg1 already carries the alpha it was scaled by.
            return "(" + a1 + " + " + a2 + " * (1.0 - " + blend + "))";
        case D3DTOP_DOTPRODUCT3: {
            // Signed-scaled dot product replicated to every channel including
            // alpha, which is why the alpha form is the same expression.
            const dot = "(4.0 * dot(" + args.rgb1 + " - vec3<f32>(0.5), " +
                args.rgb2 + " - vec3<f32>(0.5)))";
            return type === "vec3<f32>" ? "vec3<f32>(" + dot + ")" : dot;
        }
        case D3DTOP_BUMPENVMAP:
        case D3DTOP_BUMPENVMAPLUMINANCE:
            // A bump stage produces no colour of its own: its whole effect is
            // the coordinate perturbation the *next* stage samples with (see
            // the bump handling in buildFixedFunctionPixelShader). D3D leaves
            // the running result untouched, which is arg2 -- D3DTA_CURRENT by
            // default.
            return a2;
        // The four "modulate one channel set, add the other" forms. Each
        // reaches for arg1's alpha alongside arg1's colour, which is why the
        // caller supplies `args.alpha1` separately -- `a1` here is already
        // reduced to the channel being computed. D3D9 defines all four for
        // D3DTSS_COLOROP only, so the f32 form falls through to the null
        // default and is counted rather than invented.
        case D3DTOP_MODULATEALPHA_ADDCOLOR:
            if (type !== "vec3<f32>") return null;
            return "(" + args.rgb1 + " + " + args.alpha1 + " * " + args.rgb2 + ")";
        case D3DTOP_MODULATECOLOR_ADDALPHA:
            if (type !== "vec3<f32>") return null;
            return "(" + args.rgb1 + " * " + args.rgb2 + " + " +
                "vec3<f32>(" + args.alpha1 + "))";
        case D3DTOP_MODULATEINVALPHA_ADDCOLOR:
            if (type !== "vec3<f32>") return null;
            return "((1.0 - " + args.alpha1 + ") * " + args.rgb2 + " + " +
                args.rgb1 + ")";
        case D3DTOP_MODULATEINVCOLOR_ADDALPHA:
            if (type !== "vec3<f32>") return null;
            return "((vec3<f32>(1.0) - " + args.rgb1 + ") * " + args.rgb2 +
                " + vec3<f32>(" + args.alpha1 + "))";
        case D3DTOP_MULTIPLYADD:
            return "(" + a0 + " + " + a1 + " * " + a2 + ")";
        case D3DTOP_LERP:
            return "mix(" + a2 + ", " + a1 + ", " + a0 + ")";
        default:
            return null;
        }
    }

    // Fixed-function vertex stage: position transform, optional lighting,
    // per-stage texture coordinate generation/transform and fog, all written
    // into the shared varying set. `signature` comes from
    // fixedFunctionVertexSignature() plus the state-derived fields
    // programFor() adds.
    function buildFixedFunctionVertexShader(signature) {
        const layout = fixedVertexUniformLayout(signature);
        const lighting = signature.lighting;
        const position = "in" + FF_LOCATION_POSITION;

        const parameters = [vertexInputDeclaration(FF_LOCATION_POSITION)];
        if (signature.hasColor)
            parameters.push(vertexInputDeclaration(FF_LOCATION_COLOR0));
        if (signature.hasColor1)
            parameters.push(vertexInputDeclaration(FF_LOCATION_COLOR1));
        if (signature.hasNormal)
            parameters.push(vertexInputDeclaration(FF_LOCATION_NORMAL));
        if (signature.hasPointSize)
            parameters.push(vertexInputDeclaration(FF_LOCATION_PSIZE));
        const blend = signature.vertexBlend;
        if (blend && blend.weightCount)
            parameters.push(vertexInputDeclaration(FF_LOCATION_BLENDWEIGHT));
        if (blend && blend.indexed)
            parameters.push(vertexInputDeclaration(FF_LOCATION_BLENDINDICES,
                blend.indexScalar));
        for (const set of signature.texCoordSets)
            parameters.push(vertexInputDeclaration(FF_LOCATION_TEXCOORD0 + set));
        if (signature.pointExpansion)
            parameters.push("@builtin(vertex_index) d9_vertex_index: u32");

        const varyings = [];
        for (let slot = 0; slot < VARYING_COUNT; ++slot)
            varyings.push(varyingDeclaration(slot, signature.flatShading));
        const clipVaryings = [];
        let clipBody = "";
        if (signature.clipPlaneCount) {
            const clipPosition = blend ? "d9_blend_position"
                : signature.positionType === "screen" ? position
                : "uniforms.world_matrix * " + position;
            clipBody += "    let d9_clip_position = " + clipPosition + ";\n";
        }
        for (let group = 0; group < Math.ceil(
                (signature.clipPlaneCount || 0) / 4); ++group) {
            clipVaryings.push("    @location(" + (VARYING_COUNT + group) +
                ") clip" + group + ": vec4<f32>,");
            clipBody += "    result.clip" + group +
                " = vec4<f32>(1.0);\n";
        }
        for (let plane = 0; plane < (signature.clipPlaneCount || 0); ++plane)
            clipBody += "    result.clip" + Math.floor(plane / 4) + "." +
                "xyzw"[plane & 3] + " = dot(d9_clip_position, " +
                "uniforms.clip_planes[" + plane + "]);\n";

        // ---- fixed-function vertex blending (D3DRS_VERTEXBLEND) ----
        //
        // D3D9 poses a vertex as sum(w_i * (v * WORLDMATRIX(i))) and applies
        // view and projection only to the result, so a blended draw cannot
        // fold the world matrix into world_view_projection the way every
        // other draw does -- which world matrix applies is a per-vertex
        // question. BLENDWEIGHT carries one fewer weight than there are
        // matrices because D3D9 defines the last as 1 - sum(the rest); that is
        // what keeps the weights a partition of unity even when the exported
        // ones do not quite sum to 1.
        //
        // Normals ride the same blend through the same matrices, with no
        // per-matrix inverse transpose. That is D3D9's behaviour rather than an
        // approximation of it: a blend of two rotations is shorter than either,
        // which is the whole reason D3DRS_NORMALIZENORMALS exists, and it is
        // honoured below where an unblended draw honours it.
        const blendedPosition = blend ? "d9_blend_position" : position;
        let blendBody = "";
        if (blend) {
            const slots = blend.matrixCount;
            const weights = [];
            for (let slot = 0; slot < slots - 1; ++slot)
                weights.push("in" + FF_LOCATION_BLENDWEIGHT + "." + "xyzw"[slot]);
            blendBody = "    var d9_blend_position = vec4<f32>(0.0);\n";
            if (signature.hasNormal)
                blendBody += "    var d9_blend_normal = vec3<f32>(0.0);\n";
            if (weights.length)
                blendBody += "    let d9_blend_last = 1.0 - (" +
                    weights.join(" + ") + ");\n";
            if (blend.indexed) {
                // A palette index out of range is the app's bug, but WGSL gives
                // no defined value for an out-of-bounds uniform read, so clamp:
                // one wrong bone beats an indeterminate matrix.
                const raw = "in" + FF_LOCATION_BLENDINDICES;
                let unsigned;
                if (blend.indexScalar === "u32")
                    unsigned = raw;
                else if (blend.indexScalar === "i32")
                    unsigned = "vec4<u32>(max(" + raw + ", vec4<i32>(0)))";
                else if (blend.indexNormalized)
                    // Rounded, not truncated: 2/255 * 255 does not land exactly
                    // on 2 in f32, and truncating it would select bone 1.
                    unsigned = "vec4<u32>(round(" + raw + " * 255.0))";
                else
                    unsigned = "vec4<u32>(max(" + raw + ", vec4<f32>(0.0)))";
                blendBody += "    let d9_blend_index = min(" + unsigned +
                    ",\n        vec4<u32>(" + (blend.matrixSlots - 1) + "u));\n";
            }
            for (let slot = 0; slot < slots; ++slot) {
                const weight = slot < slots - 1 ? weights[slot]
                    : (weights.length ? "d9_blend_last" : "1.0");
                const index = blend.indexed
                    ? "d9_blend_index." + "xyzw"[slot] : slot + "u";
                blendBody += "    {\n" +
                    "        let d9_bone = uniforms.blend_worlds[" + index + "];\n" +
                    "        let d9_weight = " + weight + ";\n" +
                    "        d9_blend_position = d9_blend_position +\n" +
                    "            (d9_bone * " + position + ") * d9_weight;\n";
                if (signature.hasNormal)
                    blendBody +=
                    "        d9_blend_normal = d9_blend_normal +\n" +
                    "            (d9_bone * vec4<f32>(in" + FF_LOCATION_NORMAL +
                        ".xyz, 0.0)).xyz * d9_weight;\n";
                blendBody += "    }\n";
            }
        }


        // XYZRHW ("screen") vertices arrive already in viewport pixel space and
        // bypass the world/view/projection chain entirely. D3D9 also treats
        // them as already lit, which is why lighting is forced off for them.
        // XYZRHW ("screen") coordinates are absolute render-target pixels, not
        // pixels relative to the viewport -- so the viewport's origin has to
        // come off before normalising, because setViewport puts it back when it
        // maps NDC into the viewport rect. Omitting it made the two cancel only
        // for a viewport at 0,0, which is every full-screen UI pass and hid the
        // bug completely. Kart Rider draws its shop item previews through
        // 110x109 viewports at x=368..636, and pre-transformed geometry there
        // landed several viewport-widths outside the box and was clipped away:
        // the panels whose contents are entirely pre-transformed came out
        // empty, while the one item drawn from world-space geometry rendered
        // perfectly. Same fix as wined3d's transformed-position projection
        // matrix, which carries the -2x/w term for exactly this reason.
        const positionBody = blendBody + (signature.positionType === "screen"
            ? `    let viewport = uniforms.viewport;
    let ndc_x = ((${position}.x - viewport.z) / viewport.x) * 2.0 - 1.0;
    let ndc_y = 1.0 - ((${position}.y - viewport.w) / viewport.y) * 2.0;
    result.position = vec4<f32>(ndc_x, ndc_y, ${position}.z, 1.0);`
            : "    result.position = uniforms." +
                (blend ? "view_projection" : "world_view_projection") +
                " * " + blendedPosition + ";")
            + "\n" + HALF_PIXEL_OFFSET_BODY;

        // View space is where D3D9 lights live and where the camera-space
        // coordinate generation modes are defined, so one block serves both.
        // The light positions/directions themselves arrive already multiplied by
        // the view matrix (see writeFixedVertexUniforms) rather than as a second
        // matrix in the shader.
        let viewSpaceBody = "";
        if (signature.needsViewSpace) {
            // With blending, world_view/normal_matrix hold the view half only
            // -- the world half already happened, per vertex, above.
            viewSpaceBody = "    let position_view = uniforms." +
                (blend ? "view_matrix" : "world_view") + " * " +
                blendedPosition + ";\n";
            if (signature.hasNormal) {
                const normalSource = blend ? "d9_blend_normal"
                    : "in" + FF_LOCATION_NORMAL + ".xyz";
                viewSpaceBody += "    var normal_view = (uniforms.normal_matrix" +
                    " * vec4<f32>(" + normalSource + ", 0.0)).xyz;\n";
                // D3DRS_NORMALIZENORMALS is honoured rather than always
                // normalising: D3D9 genuinely does not renormalise unless asked,
                // so a scaled world matrix produces over- or under-bright
                // lighting, and silently fixing that would make this renderer
                // disagree with the reference for content tuned against it.
                if (signature.normalizeNormals)
                    viewSpaceBody += "    normal_view = normalize(normal_view);\n";
            } else {
                // A declaration with no normal cannot receive directional
                // diffuse/specular light; D3D9 uses (0,0,0), which zeroes every
                // N.L term while leaving ambient + emissive.
                viewSpaceBody += "    let normal_view = vec3<f32>(0.0);\n";
            }
        }

        // Vertex colours, before any material-source selection.
        const vertexDiffuse = signature.hasColor
            ? "in" + FF_LOCATION_COLOR0 + (signature.colorIsBGRA ? ".bgra" : "")
            : "vec4<f32>(1.0, 1.0, 1.0, 1.0)";
        const vertexSpecular = signature.hasColor1
            ? "in" + FF_LOCATION_COLOR1 + (signature.color1IsBGRA ? ".bgra" : "")
            : "vec4<f32>(0.0, 0.0, 0.0, 0.0)";

        let colorBody = "    let vertex_diffuse = " + vertexDiffuse + ";\n" +
            "    let vertex_specular = " + vertexSpecular + ";\n";
        if (lighting) {
            // D3DRS_COLORVERTEX off forces every channel to the material;
            // otherwise D3DRS_*MATERIALSOURCE picks between the material and
            // the two vertex colours. The D3D9 defaults are COLOR1 for diffuse
            // and COLOR2 for specular, which is why a lit mesh with per-vertex
            // colours is tinted by them rather than by the material alone.
            const sourceExpression = (source, materialField) => {
                if (!lighting.colorVertex) return "uniforms." + materialField;
                if (source === D3DMCS_COLOR1) return "vertex_diffuse";
                if (source === D3DMCS_COLOR2) return "vertex_specular";
                return "uniforms." + materialField;
            };
            colorBody +=
                "    let material_diffuse = " +
                    sourceExpression(lighting.diffuseSource, "material_diffuse") + ";\n" +
                "    let material_ambient = " +
                    sourceExpression(lighting.ambientSource, "material_ambient") + ";\n" +
                "    let material_specular = " +
                    sourceExpression(lighting.specularSource, "material_specular") + ";\n" +
                "    let material_emissive = " +
                    sourceExpression(lighting.emissiveSource, "material_emissive") + ";\n" +
                "    var total_diffuse = vec3<f32>(0.0);\n" +
                "    var total_ambient = uniforms.ambient_power.xyz;\n" +
                "    var total_specular = vec3<f32>(0.0);\n" +
                // Without D3DRS_LOCALVIEWER the eye vector is the constant
                // (0,0,-1) of D3D9's left-handed view space, which is the
                // cheaper approximation engines of this era normally leave on.
                "    let eye_direction = " + (lighting.localViewer
                    ? "normalize(-position_view.xyz)"
                    : "vec3<f32>(0.0, 0.0, -1.0)") + ";\n";
            lighting.lights.forEach((light, index) => {
                colorBody += "    {\n" +
                    "        let light = uniforms.lights[" + index + "];\n";
                if (light.type === D3DLIGHT_DIRECTIONAL) {
                    colorBody +=
                        "        let light_direction = -light.direction.xyz;\n" +
                        "        let attenuation = 1.0;\n";
                } else {
                    colorBody +=
                        "        let to_light = light.position.xyz - position_view.xyz;\n" +
                        "        let light_distance = length(to_light);\n" +
                        "        let light_direction = select(vec3<f32>(0.0, 0.0, 1.0),\n" +
                        "            to_light / max(light_distance, 1e-6), light_distance > 0.0);\n" +
                        // D3D9 attenuates by 1/(a0 + a1*d + a2*d^2) and drops
                        // the light entirely past its range.
                        "        var range_attenuation = 1.0 / max(light.attenuation.x +\n" +
                        "            light.attenuation.y * light_distance +\n" +
                        "            light.attenuation.z * light_distance * light_distance, 1e-6);\n" +
                        "        range_attenuation = min(range_attenuation, 1.0);\n" +
                        "        if (light_distance > light.range_falloff.x) {\n" +
                        "            range_attenuation = 0.0;\n" +
                        "        }\n";
                    if (light.type === D3DLIGHT_SPOT) {
                        // range_falloff = (range, falloff, cos(theta/2), cos(phi/2)).
                        colorBody +=
                            "        let rho = dot(light.direction.xyz, -light_direction);\n" +
                            "        var spot = 0.0;\n" +
                            "        if (rho > light.range_falloff.z) {\n" +
                            "            spot = 1.0;\n" +
                            "        } else if (rho > light.range_falloff.w) {\n" +
                            "            spot = pow(max((rho - light.range_falloff.w) /\n" +
                            "                max(light.range_falloff.z - light.range_falloff.w, 1e-6),\n" +
                            "                0.0), max(light.range_falloff.y, 1e-4));\n" +
                            "        }\n" +
                            "        let attenuation = range_attenuation * spot;\n";
                    } else {
                        colorBody += "        let attenuation = range_attenuation;\n";
                    }
                }
                colorBody +=
                    "        let n_dot_l = max(dot(normal_view, light_direction), 0.0);\n" +
                    "        total_diffuse = total_diffuse + light.diffuse.xyz *\n" +
                    "            (n_dot_l * attenuation);\n" +
                    "        total_ambient = total_ambient + light.ambient.xyz * attenuation;\n";
                if (lighting.specularEnable) {
                    colorBody +=
                        "        let half_vector = normalize(light_direction + eye_direction);\n" +
                        "        let n_dot_h = max(dot(normal_view, half_vector), 0.0);\n" +
                        // Back faces contribute no highlight, and pow(0, p) is
                        // only well-defined for p > 0, hence both guards.
                        "        let highlight = select(0.0,\n" +
                        "            pow(n_dot_h, max(uniforms.ambient_power.w, 1e-4)),\n" +
                        "            n_dot_l > 0.0);\n" +
                        "        total_specular = total_specular + light.specular.xyz *\n" +
                        "            (highlight * attenuation);\n";
                }
                colorBody += "    }\n";
            });
            colorBody +=
                "    let lit_rgb = clamp(total_ambient * material_ambient.xyz +\n" +
                "        total_diffuse * material_diffuse.xyz + material_emissive.xyz,\n" +
                "        vec3<f32>(0.0), vec3<f32>(1.0));\n" +
                // D3D9 takes the lit vertex's alpha from the diffuse material
                // channel only -- lighting never affects alpha.
                "    let out_diffuse = vec4<f32>(lit_rgb, clamp(material_diffuse.a, 0.0, 1.0));\n" +
                "    let out_specular = vec4<f32>(clamp(total_specular *\n" +
                "        material_specular.xyz, vec3<f32>(0.0), vec3<f32>(1.0)), 0.0);\n";
        } else {
            colorBody += "    let out_diffuse = vertex_diffuse;\n" +
                "    let out_specular = vertex_specular;\n";
        }

        // Fog distance is the clip-space w, which for a standard projection is
        // the eye-space depth -- exactly D3DPRASTERCAPS_WFOG, which the guest
        // advertises. D3DRS_RANGEFOGENABLE asks for true radial distance
        // instead, which removes the "fog thins towards the screen edges"
        // artefact of depth-based fog.
        const fogDistance = signature.fogRange && signature.needsViewSpace
            ? "length(position_view.xyz)" : "abs(result.position.w)";
        const fogFactor = fixedFogFactorExpression(signature.fogMode,
            "fog_distance");
        const fogBody = fogFactor
            ? "    let fog_distance = " + fogDistance + ";\n" +
              "    result.varying" + shaderPipeline.VARYING_FOG +
              " = vec4<f32>(" + fogFactor + ", 0.0, 0.0, 0.0);\n"
            : "";

        // One texture-coordinate varying per *stage*, not per declared
        // coordinate set: D3DTSS_TEXCOORDINDEX chooses which set (or which
        // generated vector) feeds a stage, and D3DTS_TEXTURE0+n transforms it,
        // so the varying a pixel stage reads for stage n is already the final
        // coordinate. That is also what D3D9 hands a real pixel shader, whose
        // texcoord input n corresponds to texture stage n.
        let coordBody = "";
        for (const stage of signature.coordStages) {
            let raw;
            // XYZRHW vertices have already passed the object/view transform
            // and carry neither an eye-space position nor a normal. A few
            // D3D8 applications leave camera-space TCI bits behind when they
            // switch to a pre-transformed overlay. Native D3D treats the
            // generated value there as undefined; referring to the absent
            // position_view/normal_view locals is worse because it makes the
            // whole WGSL module invalid and poisons the command buffer. Keep a
            // declared coordinate when one exists, otherwise use the same
            // benign (0,0,0,1) value as a missing passthrough coordinate.
            if (signature.positionType === "screen" &&
                    stage.tciMode !== D3DTSS_TCI_PASSTHRU) {
                raw = signature.texCoordSets.includes(stage.texCoordIndex)
                    ? "in" + (FF_LOCATION_TEXCOORD0 + stage.texCoordIndex)
                    : "vec4<f32>(0.0, 0.0, 0.0, 1.0)";
            } else switch (stage.tciMode) {
            case D3DTSS_TCI_CAMERASPACENORMAL:
                raw = "vec4<f32>(normal_view, 1.0)";
                break;
            case D3DTSS_TCI_CAMERASPACEPOSITION:
                raw = "vec4<f32>(position_view.xyz, 1.0)";
                break;
            case D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR:
                raw = "vec4<f32>(reflect(normalize(position_view.xyz), " +
                    "normalize(normal_view)), 1.0)";
                break;
            case D3DTSS_TCI_SPHEREMAP:
                // The classic sphere-map projection of the eye-space
                // reflection vector: the same formula OpenGL's GL_SPHERE_MAP
                // and wined3d use, which is what titles authored their
                // sphere-map art against. m is twice the length of
                // (R.x, R.y, R.z + 1), and the +0.5 recentres the result into
                // the [0,1] texture domain.
                raw = "(func_sphere_map(reflect(normalize(position_view.xyz), " +
                    "normalize(normal_view))))";
                break;
            default:
                raw = signature.texCoordSets.includes(stage.texCoordIndex)
                    ? "in" + (FF_LOCATION_TEXCOORD0 + stage.texCoordIndex)
                    : "vec4<f32>(0.0, 0.0, 0.0, 1.0)";
                break;
            }
            let expression = raw;
            if (stage.transformCount) {
                // The coordinate enters the matrix as a *row* vector padded
                // with ones, which is why a scrolling animation puts its offset
                // in row 3 (_31/_32) for the two-component form. The matrix is
                // uploaded untransposed for the same reason the WVP is: D3D's
                // row-major bytes read back as the transpose in WGSL, and that
                // transpose is exactly the column-vector form of D3D's
                // row-vector multiply.
                const padded = {
                    1: "vec4<f32>(" + raw + ".x, 1.0, 1.0, 1.0)",
                    2: "vec4<f32>(" + raw + ".xy, 1.0, 1.0)",
                    3: "vec4<f32>(" + raw + ".xyz, 1.0)",
                    4: raw,
                }[stage.transformCount] || raw;
                expression = "(uniforms.texture_transform" + stage.index +
                    " * " + padded + ")";
            }
            coordBody += "    result.varying" +
                (VARYING_TEXCOORD0 + stage.index) + " = " + expression + ";\n";
        }

        let pointBody = "";
        if (signature.pointExpansion) {
            const baseSize = signature.hasPointSize
                ? "in" + FF_LOCATION_PSIZE + ".x" : "uniforms.point_params.x";
            pointBody +=
                "    let d9_point_uvs = array<vec2<f32>, 6>(\n" +
                "        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0),\n" +
                "        vec2<f32>(0.0, 1.0), vec2<f32>(0.0, 1.0),\n" +
                "        vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));\n" +
                "    let d9_point_uv = d9_point_uvs[d9_vertex_index % 6u];\n" +
                "    var d9_point_size = " + baseSize + ";\n";
            if (signature.pointScale) {
                pointBody +=
                    "    let d9_point_distance = length(position_view.xyz);\n" +
                    "    let d9_point_denom = max(uniforms.point_scale.x +\n" +
                    "        uniforms.point_scale.y * d9_point_distance +\n" +
                    "        uniforms.point_scale.z * d9_point_distance * d9_point_distance, 1e-6);\n" +
                    "    d9_point_size = d9_point_size * uniforms.point_viewport.y *\n" +
                    "        inverseSqrt(d9_point_denom);\n";
            }
            pointBody +=
                "    d9_point_size = clamp(d9_point_size, uniforms.point_params.y,\n" +
                "        max(uniforms.point_params.y, uniforms.point_params.z));\n" +
                "    let d9_point_ndc = vec2<f32>(\n" +
                "        (d9_point_uv.x * 2.0 - 1.0) * d9_point_size / uniforms.point_viewport.x,\n" +
                "        (1.0 - d9_point_uv.y * 2.0) * d9_point_size / uniforms.point_viewport.y);\n" +
                "    result.position = vec4<f32>(result.position.xy +\n" +
                "        d9_point_ndc * result.position.w, result.position.zw);\n";
            if (signature.pointSprite) {
                for (let stage = 0; stage < MAX_TEXCOORD_SETS; ++stage) {
                    pointBody += "    result.varying" +
                        (VARYING_TEXCOORD0 + stage) +
                        " = vec4<f32>(d9_point_uv, 0.0, 1.0);\n";
                }
            }
        }

        const lightStruct = lighting && lighting.lights.length ? `struct D9Light {
    diffuse: vec4<f32>,
    specular: vec4<f32>,
    ambient: vec4<f32>,
    position: vec4<f32>,
    direction: vec4<f32>,
    range_falloff: vec4<f32>,
    attenuation: vec4<f32>,
};
` : "";

        // Emitted only when a stage asks for it, so the ordinary vertex stage
        // is unchanged.
        const sphereMapHelper = signature.coordStages.some(stage =>
            stage.tciMode === D3DTSS_TCI_SPHEREMAP) ? `
fn func_sphere_map(r: vec3<f32>) -> vec4<f32> {
    // m = 2 * |(R.x, R.y, R.z + 1)|. The guard keeps the division finite for
    // the one reflection vector that degenerates it, R = (0, 0, -1), which is
    // the direction looking straight down the reflected axis.
    let m = 2.0 * sqrt(r.x * r.x + r.y * r.y + (r.z + 1.0) * (r.z + 1.0));
    return vec4<f32>(r.x / max(m, 1e-6) + 0.5, r.y / max(m, 1e-6) + 0.5,
        0.0, 1.0);
}
` : "";

        return `${lightStruct}${uniformBlockStruct("D9FixedUniforms", layout)}
@group(0) @binding(0) var<uniform> uniforms: D9FixedUniforms;
${sphereMapHelper}

struct D9VertexOutput {
    @builtin(position) position: vec4<f32>,
${varyings.join("\n")}
${clipVaryings.join("\n")}
};

@vertex
fn d9_vs_main(${parameters.join(", ")}) -> D9VertexOutput {
    var result: D9VertexOutput;
${positionBody}
${varyings.map((_, slot) =>
        "    result.varying" + slot + " = vec4<f32>(0.0);").join("\n")}
${viewSpaceBody}${colorBody}    result.varying${VARYING_COLOR0} = out_diffuse;
    result.varying${shaderPipeline.VARYING_COLOR1} = out_specular;
${coordBody}${fogBody}${clipBody}${pointBody}    return result;
}
`;
    }

    // Fixed-function pixel stage: D3D9's texture blending cascade.
    //
    // M1/M2 hardcoded one stage of MODULATE(texture, diffuse). This walks the
    // real cascade instead: stages 0..N-1 (N ends at the first D3DTOP_DISABLE),
    // each with its own colour and alpha operation over arguments drawn from
    // diffuse, the running result, the stage's texture, D3DRS_TEXTUREFACTOR,
    // the specular colour, a scratch register and the stage's own constant --
    // which is what terrain splatting, detail texturing and light mapping are
    // actually built from. Every stage saturates its result, as D3D9 does.
    //
    // debugMode (null in normal operation) replaces the output with something
    // unambiguous, so "the screen is black" can be attributed to a specific
    // input rather than guessed at:
    //   "solid"   flat green  -- proves geometry coverage and that fragments land
    //   "color"   vertex colour only, textures ignored
    //   "texture" stage 0's texture sample only, vertex colour ignored
    //   "uv"      stage 0's texcoords as red/green -- shows whether UVs are sane
    //   "missing" flat magenta -- set per draw by debug.highlightMissingTexture
    //             to mark the draws sampling a stage with no live texture
    function buildFixedFunctionPixelShader(signature, debugMode) {
        const layout = fixedPixelUniformLayout(signature);
        const diffuse = "stage_in.varying" + VARYING_COLOR0;
        const specular = "stage_in.varying" + shaderPipeline.VARYING_COLOR1;

        // Per-stage texture declarations. Cube and volume textures reach the
        // fixed-function cascade too (environment mapping, volume fog), so the
        // WGSL texture type and the coordinate arity both come from whatever is
        // actually bound.
        const declarations = [];
        const samples = [];
        for (const stage of signature.stages) {
            if (!stage.samplesTexture) continue;
            const wgslType = { cube: "texture_cube<f32>", "3d": "texture_3d<f32>" }[
                stage.textureType] || "texture_2d<f32>";
            declarations.push("@group(0) @binding(" + (2 + stage.index * 2) +
                ") var d9_tex" + stage.index + ": " + wgslType + ";");
            declarations.push("@group(0) @binding(" + (3 + stage.index * 2) +
                ") var d9_smp" + stage.index + ": sampler;");
            const coord = "stage_in.varying" +
                (VARYING_TEXCOORD0 + stage.coordVarying);
            const components = stage.textureType === "2d" ? 2 : 3;
            let coordExpression = coord +
                (components === 2 ? ".xy" : ".xyz");
            if (stage.projected) {
                // D3DTTFF_PROJECTED divides by the last component of the
                // transformed coordinate, so the divisor follows the transform's
                // component count, not the texture's dimensionality.
                const divisor = coord + "." +
                    ["x", "x", "y", "z", "w"][stage.transformCount || 4];
                // Preserve the sign of q. Clamping a negative divisor with
                // max(q, epsilon) turns every behind-projector coordinate into
                // an enormous positive UV; Warcraft III's projected tree
                // shadows then sample the opaque edge texel over whole terrain
                // triangles, producing the characteristic black wedges.
                const safeDivisor = "select(-max(abs(" + divisor +
                    "), 1e-6), max(abs(" + divisor + "), 1e-6), " +
                    divisor + " >= 0.0)";
                coordExpression = "(" + coordExpression + " / (" +
                    safeDivisor + "))";
            }
            // D3DTOP_BUMPENVMAP: the previous stage sampled a (du, dv) pair,
            // and this stage's coordinate is displaced by it through that
            // stage's 2x2 bump matrix. The bump formats decode signed (see
            // signedNormalized in the upload path), so du/dv are used as
            // sampled rather than being rescaled from unorm here.
            if (stage.bumpFrom !== undefined && stage.textureType === "2d") {
                const bump = "uniforms.stage_bump" + stage.bumpFrom;
                const source = "tex" + stage.bumpFrom;
                coordExpression = "((" + coordExpression + ") + vec2<f32>(" +
                    bump + ".x * " + source + ".r + " + bump + ".z * " +
                    source + ".g, " + bump + ".y * " + source + ".r + " +
                    bump + ".w * " + source + ".g))";
            }
            // D3DTADDRESS_MIRRORONCE: mirror about zero, then clamp. The
            // sampler is already clamp-to-edge for such an axis (see
            // ADDRESS_MODES), so taking the absolute value of the coordinate
            // here completes the mode exactly rather than approximating it --
            // abs() folds the [-1,0] half onto [0,1] and the clamp handles
            // everything beyond. Cube addressing ignores address modes, so it
            // is excluded.
            const mirrorOnceAxes = stage.textureType === "cube" ? [] :
                (stage.textureType === "3d"
                    ? [[stage.addressU, "x"], [stage.addressV, "y"],
                       [stage.addressW, "z"]]
                    : [[stage.addressU, "x"], [stage.addressV, "y"]])
                .filter(axis => axis[0] === 5).map(axis => axis[1]);
            if (mirrorOnceAxes.length) {
                const axes = stage.textureType === "3d"
                    ? ["x", "y", "z"] : ["x", "y"];
                const vector = stage.textureType === "3d"
                    ? "vec3<f32>" : "vec2<f32>";
                coordExpression = vector + "(" + axes.map(axis =>
                    (mirrorOnceAxes.includes(axis)
                        ? "abs((" + coordExpression + ")." + axis + ")"
                        : "(" + coordExpression + ")." + axis)).join(", ") + ")";
            }
            const sampled = stage.lodBias
                ? "textureSampleBias(d9_tex" + stage.index + ", d9_smp" +
                    stage.index + ", " + coordExpression + ", " +
                    stage.lodBias.toFixed(6) + ")"
                : "textureSample(d9_tex" + stage.index +
                    ", d9_smp" + stage.index + ", " + coordExpression + ")";
            const borderAxes = stage.textureType === "cube" ? [] :
                (stage.textureType === "3d"
                    ? [[stage.addressU, "x"], [stage.addressV, "y"],
                       [stage.addressW, "z"]]
                    : [[stage.addressU, "x"], [stage.addressV, "y"]])
                .filter(axis => axis[0] === 4).map(axis => axis[1]);
            let colorKeyInside = null;
            if (borderAxes.length) {
                // WebGPU has no border-colour sampler.  Clamp for the physical
                // sample, then replace every coordinate outside the D3D unit
                // domain on an axis whose addressing mode is BORDER.  This is
                // especially important after projected division: sampling an
                // opaque edge texel outside a shadow/fog projector turns whole
                // terrain triangles into black masks.
                const inside = borderAxes.map(axis => "(" + coordExpression +
                    ")." + axis + " >= 0.0 && (" + coordExpression + ")." +
                    axis + " <= 1.0").join(" && ");
                colorKeyInside = inside;
                const color = stage.borderColor === undefined
                    ? 0 : stage.borderColor >>> 0;
                const component = shift =>
                    (((color >>> shift) & 0xff) / 255).toFixed(8);
                const border = "vec4<f32>(" + component(16) + ", " +
                    component(8) + ", " + component(0) + ", " +
                    component(24) + ")";
                samples.push("    let tex" + stage.index + " = select(" +
                    border + ", " + sampled + ", " + inside + ");");
            } else {
                samples.push("    let tex" + stage.index + " = " + sampled + ";");
            }
            if (stage.colorKey && !stage.colorKey.indexed) {
                const low = stage.colorKey.low >>> 0;
                const high = stage.colorKey.high >>> 0;
                const rgb = value => "vec3<u32>(" +
                    ((value >>> 16) & 0xff) + "u, " +
                    ((value >>> 8) & 0xff) + "u, " +
                    (value & 0xff) + "u)";
                const withinTexture = colorKeyInside
                    ? "(" + colorKeyInside + ") && " : "";
                samples.push("    let d9_key_rgb" + stage.index +
                    " = vec3<u32>(round(clamp(tex" + stage.index +
                    ".rgb, vec3<f32>(0.0), vec3<f32>(1.0)) * 255.0));\n" +
                    "    if (" + withinTexture + "all(d9_key_rgb" +
                    stage.index + " >= " + rgb(low) + ") && all(d9_key_rgb" +
                    stage.index + " <= " + rgb(high) + ")) { discard; }");
            } else if (stage.colorKey && stage.colorKey.indexed) {
                // The indexed companion view was resolved from the original
                // indices and writes alpha zero only for indices in the key
                // range. Comparing palette RGB here would be wrong when two
                // entries contain the same colour.
                samples.push("    if (tex" + stage.index +
                    ".a <= 0.0) { discard; }");
            }
            // D3DTOP_BUMPENVMAPLUMINANCE additionally modulates this stage's
            // colour by the bump texture's luminance channel, scaled and
            // biased by BUMPENVLSCALE/BUMPENVLOFFSET and clamped to [0,1].
            if (stage.bumpLuminanceFrom !== undefined) {
                const lum = "uniforms.stage_bump_lum" + stage.bumpLuminanceFrom;
                const source = "tex" + stage.bumpLuminanceFrom;
                samples.push("    let tex" + stage.index + "_lit = vec4<f32>(" +
                    "tex" + stage.index + ".rgb * clamp(" + lum + ".x * " +
                    source + ".b + " + lum + ".y, 0.0, 1.0), tex" +
                    stage.index + ".a);");
            }
        }

        const luminanceScaledStages = new Set(signature.stages
            .filter(stage => stage.bumpLuminanceFrom !== undefined)
            .map(stage => stage.index));

        // The argument pool. `current` and `temp` are the two mutable registers
        // the cascade threads through, so they are read from variables the
        // stage loop below reassigns.
        function argumentExpression(argument, stageIndex, channel) {
            const selector = argument & D3DTA_SELECTMASK;
            let value;
            switch (selector) {
            case D3DTA_DIFFUSE: value = diffuse; break;
            case D3DTA_CURRENT: value = "current"; break;
            case D3DTA_TEXTURE:
                // A stage sampled under BUMPENVMAPLUMINANCE reads the
                // luminance-modulated copy, which is what the luminance form
                // exists to produce.
                value = "tex" + stageIndex +
                    (luminanceScaledStages.has(stageIndex) ? "_lit" : "");
                break;
            case D3DTA_TFACTOR: value = "uniforms.texture_factor"; break;
            case D3DTA_SPECULAR: value = specular; break;
            case D3DTA_TEMP: value = "temp"; break;
            case D3DTA_CONSTANT: value = "uniforms.stage_constant" + stageIndex; break;
            default: value = diffuse; break;
            }
            // D3DTA_ALPHAREPLICATE broadcasts the argument's alpha over the
            // colour channels; D3DTA_COMPLEMENT inverts whatever came out.
            let expression;
            if (channel === "rgb")
                expression = (argument & D3DTA_ALPHAREPLICATE)
                    ? "vec3<f32>(" + value + ".a)" : value + ".rgb";
            else
                expression = value + ".a";
            if (argument & D3DTA_COMPLEMENT) {
                expression = channel === "rgb"
                    ? "(vec3<f32>(1.0) - " + expression + ")"
                    : "(1.0 - " + expression + ")";
            }
            return expression;
        }

        let cascadeBody = "    var current = " + diffuse + ";\n" +
            // D3D9 leaves the scratch register undefined until written; zero is
            // the one starting value that cannot make an unwritten read look
            // like meaningful data.
            "    var temp = vec4<f32>(0.0);\n";
        for (const stage of signature.stages) {
            const rgb = argument => argumentExpression(argument, stage.index, "rgb");
            const alpha = argument => argumentExpression(argument, stage.index, "a");
            const blendAlpha = {
                [D3DTOP_BLENDDIFFUSEALPHA]: diffuse + ".a",
                [D3DTOP_BLENDTEXTUREALPHA]: "tex" + stage.index + ".a",
                [D3DTOP_BLENDTEXTUREALPHAPM]: "tex" + stage.index + ".a",
                [D3DTOP_BLENDFACTORALPHA]: "uniforms.texture_factor.a",
                [D3DTOP_BLENDCURRENTALPHA]: "current.a",
            };
            const colorArgs = [rgb(stage.colorArg0), rgb(stage.colorArg1),
                rgb(stage.colorArg2)];
            colorArgs.rgb1 = rgb(stage.colorArg1);
            colorArgs.rgb2 = rgb(stage.colorArg2);
            // The MODULATE*_ADD* family reads arg1's alpha while computing the
            // colour channel, so it needs the alpha reduction of the *colour*
            // argument rather than of D3DTSS_ALPHAARG1.
            colorArgs.alpha1 = alpha(stage.colorArg1);
            const alphaArgs = [alpha(stage.alphaArg0), alpha(stage.alphaArg1),
                alpha(stage.alphaArg2)];
            alphaArgs.rgb1 = rgb(stage.colorArg1);
            alphaArgs.rgb2 = rgb(stage.colorArg2);
            alphaArgs.alpha1 = alpha(stage.colorArg1);
            const colorExpression = textureOpExpression(stage.colorOp,
                "vec3<f32>", colorArgs, blendAlpha[stage.colorOp] || "0.0");
            const alphaExpression = stage.alphaOp === D3DTOP_DISABLE ? null
                : textureOpExpression(stage.alphaOp, "f32", alphaArgs,
                    blendAlpha[stage.alphaOp] || "0.0");
            const destination = stage.resultArg === D3DTA_TEMP ? "temp" : "current";
            cascadeBody += "    {\n" +
                "        let stage_rgb = clamp(" +
                    (colorExpression || rgb(stage.colorArg1)) +
                    ", vec3<f32>(0.0), vec3<f32>(1.0));\n" +
                "        let stage_a = clamp(" +
                    (alphaExpression || destination + ".a") + ", 0.0, 1.0);\n" +
                "        " + destination + " = vec4<f32>(stage_rgb, stage_a);\n" +
                "    }\n";
        }

        let value = "current";
        if (debugMode === "solid") value = "vec4<f32>(0.0, 1.0, 0.0, 1.0)";
        else if (debugMode === "missing") value = "vec4<f32>(1.0, 0.0, 1.0, 1.0)";
        else if (debugMode === "orphan") value = "vec4<f32>(0.0, 1.0, 1.0, 1.0)";
        else if (debugMode === "color")
            value = "vec4<f32>(" + diffuse + ".rgb, 1.0)";
        else if (debugMode === "uv")
            value = signature.stages.length
                ? "vec4<f32>(stage_in.varying" +
                    (VARYING_TEXCOORD0 + signature.stages[0].coordVarying) +
                    ".xy, 0.0, 1.0)"
                : "vec4<f32>(0.0, 0.0, 1.0, 1.0)";
        else if (debugMode === "texture")
            value = signature.stages.some(stage => stage.samplesTexture)
                ? "vec4<f32>(tex" + signature.stages.find(
                    stage => stage.samplesTexture).index + ".rgb, 1.0)"
                : "vec4<f32>(1.0, 0.0, 0.0, 1.0)";

        // D3D9 adds the specular colour after the texture cascade, before fog.
        const specularBody = signature.specularEnable && !debugMode
            ? "    result = vec4<f32>(clamp(result.rgb + " + specular +
              ".rgb, vec3<f32>(0.0), vec3<f32>(1.0)), result.a);\n"
            : "";
        let fogBody = "";
        if (signature.fogMode) {
            // Table fog is pixel fog. The device advertises WFOG (and not
            // ZFOG), while fragment position.w is reciprocal clip-space W in
            // WGSL, so recover W here and evaluate the D3D fog equation per
            // fragment. Vertex fog alone consumes the interpolated oFog value.
            const tableFactor = fixedFogFactorExpression(signature.fogMode,
                "fog_distance");
            const factor = signature.tableFog && tableFactor
                ? tableFactor
                : "clamp(stage_in.varying" + shaderPipeline.VARYING_FOG +
                  ".x, 0.0, 1.0)";
            const tableDistance = signature.tableFog && tableFactor
                ? "    let fog_distance = 1.0 / " +
                  "max(abs(stage_in.position.w), 1e-6);\n"
                : "";
            fogBody = tableDistance +
                "    result = vec4<f32>(mix(uniforms.fog_color.rgb, result.rgb,\n" +
                "        " + factor + "), result.a);\n";
        }
        const varyings = [];
        for (let slot = 0; slot < VARYING_COUNT; ++slot)
            varyings.push(varyingDeclaration(slot, signature.flatShading));
        const clipVaryings = [];
        let clipDiscard = "";
        for (let group = 0; group < Math.ceil(
                (signature.clipPlaneCount || 0) / 4); ++group)
            clipVaryings.push("    @location(" + (VARYING_COUNT + group) +
                ") clip" + group + ": vec4<f32>,");
        for (let plane = 0; plane < (signature.clipPlaneCount || 0); ++plane)
            clipDiscard += "    if (stage_in.clip" +
                Math.floor(plane / 4) + "." + "xyzw"[plane & 3] +
                " < 0.0) { discard; }\n";

        return `${layout.entries.length
            ? uniformBlockStruct("D9FixedPixelUniforms", layout) +
              "\n@group(0) @binding(1) var<uniform> uniforms: D9FixedPixelUniforms;"
            : ""}
${declarations.join("\n")}

struct D9PixelInput {
    @builtin(position) position: vec4<f32>,
${varyings.join("\n")}
${clipVaryings.join("\n")}
};

@fragment
fn d9_ps_main(stage_in: D9PixelInput) -> @location(0) vec4<f32> {
${clipDiscard}
${samples.join("\n")}
${cascadeBody}    var result = ${value};
${specularBody}${alphaTestDiscard(signature.alphaTest, "result.a")}${fogBody}    return result;
}
`;
    }

    // A fragment stage that deliberately depends on no varying, constant or
    // texture.  It is used only by the live black-screen probe below.  Keeping
    // it independent of the translated/fixed-function shader is important:
    // "solid" used to rewrite only the fixed-function cascade, so a scene
    // made entirely of programmable draws stayed black and the diagnostic
    // falsely implicated geometry.  This module can be paired with either
    // vertex path while the original program still supplies the bind-group
    // layout expected by the rest of the draw machinery.
    const DIAGNOSTIC_SOLID_PIXEL_SHADER = `
@fragment
fn d9_ps_main() -> @location(0) vec4<f32> {
    return vec4<f32>(0.0, 1.0, 0.0, 1.0);
}
`;

    function createIndexedDBShaderCacheStorage(indexedDB) {
        const databaseName = "d9wg-shader-cache";
        const storeName = "snapshots";
        const open = () => new Promise((resolve, reject) => {
            const request = indexedDB.open(databaseName, 1);
            request.onupgradeneeded = () => {
                const db = request.result;
                if (!db.objectStoreNames.contains(storeName))
                    db.createObjectStore(storeName);
            };
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error ||
                new Error("could not open the shader-cache database"));
            request.onblocked = () => reject(new Error(
                "shader-cache database upgrade is blocked by another page"));
        });
        return {
            async load(key) {
                const db = await open();
                try {
                    return await new Promise((resolve, reject) => {
                        const request = db.transaction(storeName, "readonly")
                            .objectStore(storeName).get(key);
                        request.onsuccess = () => resolve(request.result || null);
                        request.onerror = () => reject(request.error ||
                            new Error("could not read the shader cache"));
                    });
                } finally {
                    db.close();
                }
            },
            async save(key, payload) {
                const db = await open();
                try {
                    await new Promise((resolve, reject) => {
                        const transaction = db.transaction(storeName, "readwrite");
                        transaction.objectStore(storeName).put(payload, key);
                        transaction.oncomplete = () => resolve();
                        transaction.onerror = () => reject(transaction.error ||
                            new Error("could not write the shader cache"));
                        transaction.onabort = () => reject(transaction.error ||
                            new Error("shader-cache transaction was aborted"));
                    });
                } finally {
                    db.close();
                }
            },
        };
    }

    class D3D9WebGPUExecutor {
        constructor(canvas, options) {
            if (!canvas) throw new Error("D3D9 WebGPU canvas is required");
            this.canvas = canvas;
            this.options = options || {};
            this.gpu = this.options.gpu ||
                (global.navigator && global.navigator.gpu);
            this.adapter = this.options.adapter || null;
            this.device = this.options.device || null;
            this.context = this.options.context || null;
            this.format = this.options.format || null;
            // Skipped entirely when a device was supplied -- a caller that
            // brought its own device configures the canvas itself. Otherwise
            // the gpu/adapter/context overrides go to the host, so that a
            // caller injecting a fake WebGPU still gets one device and one
            // canvas configuration rather than two.
            this.host = this.options.host || (this.device ? null :
                ((host => host ? host.acquire(canvas, {
                    gpu: this.gpu,
                    adapter: this.adapter,
                    context: this.context,
                    format: this.format,
                    ...(this.options.hostOptions || {}),
                }) : null)(resolveGPUHost())));
            this.devices = new Map();      // device_handle -> device state
            this.resources = new Map();    // resource_handle -> resource state
            this.pipelineCache = new Map(); // layout signature -> GPURenderPipeline
            this.bindGroupCache = new Map(); // GPU resources -> GPUBindGroup
            this.maxBindGroups = Math.max(256,
                this.options.maxBindGroups || 4096);
            this.uniformRingCapacity = Math.max(64 * 1024,
                this.options.uniformRingBytes || UNIFORM_RING_BYTES);
            // Chunks, not one buffer. A frame's draw count is not bounded by
            // anything -- 3DMark06's batch-size test exists precisely to drive
            // it as high as the driver will go -- and one 16 MiB ring only
            // holds uniformRingCapacity/256 slots, after which the old code
            // fell back to a fresh GPUBuffer *per draw*. Those also defeated
            // the bind-group cache (a transient buffer must not be cached), so
            // past the cliff every draw allocated one buffer plus one bind
            // group and held both until Present. Chunks keep the allocation
            // count proportional to bytes used rather than to draw count, and
            // they are pooled across frames so their object identity -- which
            // is what the bind-group cache keys on -- stays stable.
            // The D3D9 back buffer is an executor-owned texture, not
            // context.getCurrentTexture(). See ensureBackBufferTexture().
            this.backBufferTexture = null;
            this.backBufferView = null;
            this.backBufferSrgbView = null;
            this.backBufferTextureWidth = 0;
            this.backBufferTextureHeight = 0;
            // Palette contents and the DirectDraw GPU palette cache use device
            // handles in their keys. Handles overlap between guest processes,
            // so these are session aliases just like devices/resources and the
            // retained back buffer (see switchSession()).
            this.palettes = new Map();
            this.ddPaletteBuffers = new Map();
            this.ddPaletteSerials = new Map();
            // How many recorded ops may accumulate before the frame is
            // submitted early. A D3D9 frame's cost is otherwise unbounded in
            // its draw count -- 3DMark06's batch-size tests exist to drive that
            // count as high as the driver allows -- and every op is both a live
            // JS object and, at replay, a command in one enormous command
            // buffer. Flushing bounds both. Now that the back buffer is an
            // owned texture (see ensureBackBufferTexture) a partial frame can
            // be submitted without acquiring the swap chain, which is what made
            // this possible at all.
            //
            // Each flush costs one queue.submit(), so the number wants to be
            // large enough that ordinary frames never reach it: a normal scene
            // draws in the hundreds, and even the particle test's 56 draws per
            // frame are three orders of magnitude below this.
            this.flushThreshold = Math.max(1024,
                this.options.flushThreshold || 16384);
            // The guest blocks on a readback, so this is a VM-freeze budget
            // rather than a GPU-latency one.
            this.readbackTimeoutMs = Math.max(250,
                this.options.readbackTimeoutMs || 4000);
            this.heartbeat = 0;
            this.heartbeatBuffer = new Uint8Array(4);
            this.uniformRingChunks = [];
            // A CPU-side mirror of each chunk. Constants are written here and
            // the whole used prefix goes up in one writeBuffer per submit --
            // see uploadUniformStaging().
            this.uniformStaging = [];
            this.uniformRingMaxChunks = Math.max(1,
                this.options.uniformRingChunks || 4);
            this.uniformRingIndex = 0;
            this.uniformRingCursor = 0;
            /*
             * Bumped by every command that is not a draw. D3D9 constants are
             * device state, not a buffer the app manages, so "did the constants
             * change" is answerable the way a real driver answers it: nothing
             * called SetConstant, therefore nothing changed. That is O(1).
             *
             * It replaces hashing the assembled block per draw, which was the
             * same question asked the expensive way -- a 3DMark06 batch-size run
             * hashed 6.8 GB to find that 7% of draws could share a slot. Being
             * bumped by *any* non-draw command makes it conservative: it can
             * only ever miss a reuse, never claim a stale one.
             */
            this.commandSerial = 1;
            this.objectIds = new WeakMap();
            this.nextObjectId = 1;
            // Bytecode hash -> {ok, wgsl, reflection}. Survives device loss:
            // WGSL text is not tied to a GPUDevice (plan 8.5), only the
            // GPUShaderModules in moduleCache are.
            this.shaderCache = new shaderPipeline.D3D9ShaderCache();
            this.shaderCacheStorageKey = "d9wg.shader-cache.sm3-vtf.20260822.v1";
            let indexedDBStorage = null;
            try {
                if (!this.options.shaderCacheStorage && global.window &&
                        global.indexedDB) {
                    indexedDBStorage = createIndexedDBShaderCacheStorage(
                        global.indexedDB);
                }
            } catch (error) { /* persistence is optional for restricted origins */ }
            this.shaderCacheStorage = this.options.shaderCacheStorage ||
                indexedDBStorage;
            this.shaderCacheStorageBackend = this.options.shaderCacheStorage ?
                "injected" : (indexedDBStorage ? "indexeddb" : "memory");
            this.persistentShaderCachePromise = null;
            this.shaderCacheSaveTimer = null;
            this.shaderCacheDirty = false;
            this.shaderWorker = null;
            this.shaderWorkerRequests = new Map();
            this.shaderWorkerSerial = 0;
            this.moduleCache = new Map();  // wgsl -> GPUShaderModule
            this.samplerCache = new Map(); // sampler-state signature -> GPUSampler
            // D3D9 hardware cursor: bitmap, hotspot, position, visibility.
            this.cursor = { texture: null, view: null, width: 0, height: 0,
                hotspotX: 0, hotspotY: 0, x: 0, y: 0, visible: false,
                pipeline: null, sampler: null, uniform: null };
            this.fallbackTexture = null;
            this.defaultAttributes = null;
            this.fallbackView = null;
            this.fallbackDepth = null;
            this.fallbackViews = null;
            this.substituteDepthViews = null;
            // Every protocol-1.3 batch carries its process session id in the
            // batch header. Futuremark launches several D3D9 probe/helper
            // processes alongside the benchmark, and their numeric handles
            // overlap. Keep an independent live context per process and swap
            // these aliases at batch boundaries; one helper's HELLO must never
            // tear down a benchmark process that is still rendering.
            this.sessionStates = new Map();
            this.sessionKey = null;
            this.frame = null;             // { ops, transientBuffers, serial }
            this.frameSerial = 0;
            this.readyPromise = null;
            this.pendingReadbacks = new Set();
            this.work = Promise.resolve();
            this.failed = null;
            // Console-togglable diagnostics, e.g.
            //   v86gl.d3d9Executor.debug.forceClearColor = {r:1,g:0,b:1,a:1}
            // These exist to split "the canvas is not on screen" from "the
            // canvas is on screen but the drawn content is black", which the
            // stats alone cannot distinguish.
            this.debug = {
                forceClearColor: null,  // {r,g,b,a} overrides every Clear
                disableCull: false,     // force cullMode "none"
                disableDepthTest: false,// force depthCompare "always"
                shaderMode: null,       // "solid"|"color"|"texture"|"uv"
                // Replaces *both* fixed-function and translated pixel shaders
                // with an opaque green output. It also disables blend, alpha,
                // depth/stencil rejection and forces RGBA writes, leaving only
                // vertex fetch/transform, viewport and scissor able to hide a
                // draw. This is the definitive geometry-vs-shading probe.
                forceSolidAllDraws: false,
                // Clamps every sampler to the top mip level. If a texture
                // looks wrong because levels below 0 were never uploaded,
                // this makes it correct immediately -- which is the cheapest
                // way to confirm or rule out that cause.
                forceMipLevel0: false,
                // Suspicious-but-valid D3D9 state is counted in getStats()
                // unconditionally. Detailed per-state console warnings are
                // opt-in: real games deliberately reuse declarations and
                // fixed-function state in ways that trip these heuristics,
                // so they are debugging evidence rather than runtime errors.
                warnOnSuspiciousDraws: false,
                // Paints magenta over any fixed-function draw whose cascade
                // samples a stage with no live texture -- the draws that get
                // the 1x1 white fallback. A counter says how many there are;
                // this says *which*, which is the question a flat silhouette
                // actually poses: is the model I am looking at one of them?
                // Everything else keeps rendering normally, so the answer is
                // one screenshot rather than a bisection.
                highlightMissingTexture: false,
                // The same question for the other cause of a flat model:
                // paints cyan over any draw whose stage reads a coordinate
                // set its declaration does not carry. Magenta and cyan
                // together answer "which of the two is this model" in one
                // screenshot, which is the whole difficulty -- both render as
                // one flat colour and neither fails.
                highlightMissingCoordSet: false,
                // Drops every draw that has a translated shader bound on
                // either stage. shaderMode only rewrites the fixed-function
                // pixel cascade, so a model rendered through the programmable
                // path looks *identical* under every debug mode -- which reads
                // as "the debug mode did nothing" rather than as "you are
                // looking at the wrong pipeline". Making those draws vanish
                // answers which path a model is on in one screenshot.
                skipProgrammableDraws: false,
                // Routes fixed-function texture stage n to varying TEXCOORD n
                // (D3D9's rule when a vertex shader is bound) instead of to
                // the varying D3DTSS_TEXCOORDINDEX names. See coordStagePlan
                // for why the two disagree and which one D3D9 documents.
                texcoordFromStageIndex: true,
            };
            this.debug.dumpSmallTextures = o => this.dumpSmallTextures(o);
            this.debug.dumpShaders = o => this.dumpShaders(o);
            this.debug.clearShaderCache = () => this.clearShaderCache();
            this.debug.dumpPipelineStates = () => this.dumpPipelineStates();
            this.debug.blackScreenReport = () => this.blackScreenReport();
            this.lastDraws = { fixed: null, programmable: null };
            this.stats = {
                batches: 0, commands: 0, presents: 0, queueSubmits: 0,
                drawCalls: 0, indexedDrawCalls: 0, upDrawCalls: 0,
                pipelineCreations: 0, pipelineHits: 0,
                bindGroupCreations: 0, bindGroupHits: 0,
                bindGroupCacheEvictions: 0,
                uniformSlotReuses: 0, uniformRingOverflows: 0,
                uniformRingChunksAllocated: 0, uniformRingChunksUsed: 0,
                backBufferAllocations: 0, backBufferPresents: 0,
                redundantStateSkipped: 0, uniformStagingUploads: 0,
                readbackRequests: 0,
                frameFlushes: 0,
                unsupportedCommands: 0, malformedBatches: 0,
                malformedCommands: 0, gammaRampUpdates: 0, fillModeDraws: 0,
                swapChainsCreated: 0, swapChainsDestroyed: 0,
                swapChainsRefused: 0, swapChainPresents: 0,
                swapChainPresentsDropped: 0,
                gammaPresents: 0,
                droppedDraws: 0,
                guestReports: 0,
                texturesCreated: 0, textureUploads: 0, textureBytesUploaded: 0,
                texturePreviewsSkipped: 0,
                drawsWithTexture: 0, drawsWithFallbackTexture: 0,
                shadersTranslated: 0, shaderTranslationFailures: 0,
                shaderVariantsTranslated: 0,
                shaderModulesCreated: 0, shaderCompileErrors: 0,
                shaderCachePersistentLoads: 0,
                shaderCachePersistentSaves: 0,
                shaderCachePersistentFailures: 0,
                shaderWorkerCompiles: 0, shaderWorkerFallbacks: 0,
                samplersCreated: 0, samplerHits: 0,
                // Back-buffer persistence diagnostics. WebGPU does not preserve
                // a canvas texture across Present, while D3D9 applications
                // commonly redraw only changing rectangles. Those frames are
                // counted and restored from the owned post-Present snapshot.
                // A frame with no ops remains useful diagnostic evidence that
                // Present itself did not produce new GPU work.
                framesWithoutColorClear: 0, framesWithNoOps: 0,
                // Dynamic buffers renamed because a draw already recorded in
                // the same frame reads their previous contents (see
                // applyBufferUpdate). Zero means the deferred-draw path never
                // had a write-after-record hazard to begin with.
                bufferRenames: 0, textureUpdateHazards: 0,
                textureRenames: 0, textureFullCopyRenameBytes: 0,
                bufferFullCopyRenames: 0, bufferNoOverwriteWrites: 0,
                emptySurfaceReports: 0, surfaceChanges: 0, sessionChanges: 0,
                sessionsEnded: 0,
                deviceLosses: 0, deviceRecoveries: 0,
                guestFeatureBits: 0, guestShaderModel2: false,
                guestShaderModel3: false,
                windowStateChanges: 0, windowNotForegroundReports: 0, windowOccludedReports: 0,
                windowRegionReports: 0,
                cursorUploads: 0, cursorDraws: 0,
                texturesRejected: 0,
                srgbTextureSamples: 0, srgbViewsCreated: 0,
                srgbTextureUnavailable: 0, srgbWriteRequests: 0,
                srgbWriteUnavailable: 0,
                cubeTexturesCreated: 0, volumeTexturesCreated: 0,
                renderTargetsCreated: 0,
                renderTargetBinds: 0, renderPasses: 0,
                depthTargetSizeMismatches: 0,
                depthTargetSubstitutions: 0,
                depthTargetSubstitutionsUncleared: 0,
                blits: 0, blitsSkipped: 0, blitsThroughBackBuffer: 0,
                colorFills: 0,
                partialClears: 0,
                drawsWithScissor: 0,
                drawsWithIncompleteMipChain: 0,
                // Hardware shadow maps: depth textures sampled through a
                // comparison sampler, and the ways a stage can fail to be one.
                comparisonSamplersCreated: 0,
                depthStageWithoutDepthTexture: 0,
                depthAttachmentSampledInPlace: 0,
                cubeFaceTargetBinds: 0,
                mipChainsGenerated: 0, mipLevelsGenerated: 0,
                explicitMipGenerations: 0,
                palettesSet: 0, paletteSelections: 0, palettizedRepaints: 0,
                depthTextureOnNonDepthStage: 0,
                stagesWithoutSampleableView: 0,
                commandsFailed: 0,
                lastDrawTexture: 0,
                drawsWithUnsupportedTextureOp: 0,
                drawsWithTexCoordIndex: 0, drawsWithTextureTransform: 0,
                drawsWithUnmappedBlend: 0, drawsWithUnappliedFog: 0,
                drawsWithUnappliedLighting: 0,
                drawsWithZeroNormalLighting: 0,
                zeroNormalDrawsWithoutTexture: 0,
                zeroNormalDrawsWithMissingTexture: 0,
                // The two halves of "missing", which are different bugs with
                // the same symptom: the guest bound nothing to the stage
                // (handle 0), or it bound a handle this host has no resource
                // for -- a texture whose creation was refused, or one already
                // destroyed. Both end at the 1x1 white fallback, so the
                // picture cannot tell them apart and the counters must.
                zeroNormalDrawsWithUnboundTexture: 0,
                zeroNormalDrawsWithUnknownTexture: 0,
                zeroNormalDrawsWithLiveTexture: 0,
                // Fixed-function pixel stages routed to a varying the bound
                // translated vertex shader never assigned.
                drawsWithUnwrittenCoordVarying: 0,
                drawsWithDefaultedInputs: 0,
                // The same seam one stage earlier, and entirely inside the
                // fixed-function path: a stage whose D3DTSS_TEXCOORDINDEX names
                // a coordinate set the *declaration* does not carry. The vertex
                // stage substitutes a constant for it, so the model samples one
                // texel and comes out a single flat colour.
                drawsWithMissingCoordSet: 0,
                // Draws posed by more than one world matrix, and draws
                // whose declaration carries skinning data that the
                // render state told us to ignore.
                blendedDraws: 0,
                drawsWithUnappliedVertexBlend: 0,
                programmableDraws: 0, drawsSkippedForBadShader: 0,
                drawsWithCompactVertexInputs: 0,
                constantUploadBytes: 0,
                pointSpriteDraws: 0, pointSpriteInstances: 0,
                indexedPointExpansions: 0,
                instancedDraws: 0, instancesDrawn: 0,
                expandedInstanceStreams: 0,
                queriesCreated: 0, queryBegins: 0, queryEnds: 0,
                occlusionQueriesResolved: 0, timestampQueriesResolved: 0,
                eventQueriesResolved: 0, queryFailures: 0,
                responseWriteFailures: 0,
                renderTargetReadbacks: 0, renderTargetReadbackBytes: 0,
                renderTargetReadbackFailures: 0,
            };
            this.mrtAttachmentDraws = [0, 0, 0, 0, 0];
            this.lastFrameStats = {
                pipelineCreations: 0, bindGroupCreations: 0,
                queueSubmits: 0, renderPasses: 0,
            };
        }

        initialize() {
            if (this.readyPromise) return this.readyPromise;
            this.readyPromise = (async () => {
                // Persistent I/O must not delay adapter/device acquisition.
                // The first submitted batch awaits the same promise before it
                // can create a shader, so starting both jobs here preserves
                // cache hits without putting IndexedDB on the startup path.
                this.restorePersistentShaderCache();
                this.initializeShaderWorker();
                if (!this.device) {
                    if (!this.host) throw new Error("WebGPU is unavailable");
                    // The host asks the adapter for the union of what every
                    // backend needs, BCn included. Without those features every
                    // createTexture for a DXT format throws, which kills the
                    // batch and with it the frame -- and DXT1/3/5 are the
                    // formats a 2002-and-later D3D9 game keeps almost all of
                    // its art in, so that is most of the screen.
                    await this.host.initialize();
                    this.adapter = this.host.adapter;
                    this.device = this.host.device;
                    this.deviceFeatures = this.host.deviceFeatures;
                    this.context = this.context || this.host.context;
                    this.format = this.format || this.host.format;
                }
                // A device supplied by the caller (the fake device in tests, or
                // a shared one) reports its own features.
                if (!this.deviceFeatures) {
                    const features = this.device.features;
                    const has = name => !!(features &&
                        typeof features.has === "function" &&
                        features.has(name));
                    this.deviceFeatures = {
                        bc: has("texture-compression-bc"),
                        float32Filterable: has("float32-filterable"),
                        float32Blendable: has("float32-blendable"),
                        timestampQuery: has("timestamp-query"),
                    };
                }
                // The host configured the canvas with the same usage set this
                // file used to: a context defaults to RENDER_ATTACHMENT alone,
                // but StretchRect to and from the back buffer is how a D3D9
                // game does full-screen post-processing, so COPY_SRC/COPY_DST
                // and TEXTURE_BINDING are not optional. Only a caller that
                // supplied its own device still has to configure for itself.
                this.context = this.context ||
                    (this.canvas && typeof this.canvas.getContext === "function" ?
                        this.canvas.getContext("webgpu") : null);
                if (!this.context) throw new Error("could not acquire a WebGPU canvas context");
                this.format = this.format || (this.gpu &&
                    typeof this.gpu.getPreferredCanvasFormat === "function" ?
                    this.gpu.getPreferredCanvasFormat() : "bgra8unorm");
                this.swapchainSrgbFormat = srgbSiblingOf(this.format);
                if (!this.host && typeof this.context.configure === "function") {
                    this.context.configure({
                        device: this.device, format: this.format,
                        ...(this.swapchainSrgbFormat
                            ? { viewFormats: [this.swapchainSrgbFormat] } : {}),
                        alphaMode: "opaque",
                        usage: TEXTURE_USAGE_RENDER_ATTACHMENT |
                            TEXTURE_USAGE_COPY_SRC | TEXTURE_USAGE_COPY_DST |
                            TEXTURE_USAGE_TEXTURE_BINDING,
                    });
                }
                this.fallbackTexture = this.device.createTexture({
                    label: "D3D9 fallback white texture",
                    size: { width: 1, height: 1, depthOrArrayLayers: 1 },
                    format: "rgba8unorm",
                    usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
                });
                this.fallbackView = this.fallbackTexture.createView();
                this.device.queue.writeTexture({ texture: this.fallbackTexture },
                    new Uint8Array([255, 255, 255, 255]),
                    { bytesPerRow: 4, rowsPerImage: 1 },
                    { width: 1, height: 1, depthOrArrayLayers: 1 });
                this.uniformRingChunks = [];
                this.uniformStaging = [];
                this.uniformRingIndex = 0;
                this.uniformRingCursor = 0;
                this.watchForDeviceLoss();
                return this;
            })().catch(error => {
                this.failed = error;
                console.error("[d3d9-webgpu] initialization failed", error);
                throw error;
            });
            return this.readyPromise;
        }

        async restorePersistentShaderCache() {
            if (this.persistentShaderCachePromise)
                return this.persistentShaderCachePromise;
            this.persistentShaderCachePromise = (async () => {
                try {
                    let payload = null;
                    const storage = this.shaderCacheStorage;
                    if (storage && typeof storage.load === "function") {
                        payload = await storage.load(this.shaderCacheStorageKey);
                    }
                    if (typeof payload === "string") payload = JSON.parse(payload);
                    const restored = this.shaderCache.importEntries(payload);
                    if (restored) this.stats.shaderCachePersistentLoads += restored;
                } catch (error) {
                    ++this.stats.shaderCachePersistentFailures;
                    this.warnOnce("shader-cache-load",
                        "persistent shader cache could not be restored; using the " +
                        "in-memory cache for this session", { message: String(error) });
                }
            })();
            return this.persistentShaderCachePromise;
        }

        initializeShaderWorker() {
            if (this.options.useShaderWorker === false || this.shaderWorker)
                return;
            const WorkerClass = this.options.Worker || global.Worker;
            const url = this.options.shaderWorkerUrl || DEFAULT_SHADER_WORKER_URL;
            if (typeof WorkerClass !== "function" || !url) return;
            try {
                const worker = new WorkerClass(url);
                worker.onmessage = event => {
                    const message = event.data || {};
                    const pending = this.shaderWorkerRequests.get(message.id);
                    if (!pending) return;
                    this.shaderWorkerRequests.delete(message.id);
                    pending.resolve(message.result);
                };
                worker.onerror = event => {
                    const error = new Error("shader compiler worker failed: " +
                        ((event && event.message) || "unknown worker error"));
                    for (const pending of this.shaderWorkerRequests.values())
                        pending.reject(error);
                    this.shaderWorkerRequests.clear();
                    try { worker.terminate(); } catch (ignored) {}
                    if (this.shaderWorker === worker) this.shaderWorker = null;
                };
                this.shaderWorker = worker;
            } catch (error) {
                ++this.stats.shaderWorkerFallbacks;
                this.warnOnce("shader-worker-create",
                    "shader compile Worker is unavailable; compiling on the " +
                    "executor thread", { message: String(error) });
            }
        }

        compileShaderInWorker(tokens) {
            if (!this.shaderWorker) return null;
            const id = ++this.shaderWorkerSerial;
            return new Promise((resolve, reject) => {
                this.shaderWorkerRequests.set(id, { resolve, reject });
                try {
                    this.shaderWorker.postMessage({ id,
                        tokens: Array.from(tokens) });
                } catch (error) {
                    this.shaderWorkerRequests.delete(id);
                    reject(error);
                }
            });
        }

        schedulePersistentShaderCacheSave() {
            const storage = this.shaderCacheStorage;
            if (!storage || typeof storage.save !== "function") return;
            if (this.shaderCacheSaveTimer !== null)
                global.clearTimeout(this.shaderCacheSaveTimer);
            this.shaderCacheSaveTimer = global.setTimeout(() => {
                this.shaderCacheSaveTimer = null;
                this.flushPersistentShaderCache();
            }, 250);
        }

        async flushPersistentShaderCache() {
            if (!this.shaderCacheDirty) return;
            this.shaderCacheDirty = false;
            try {
                const payload = this.shaderCache.exportEntries(2 * 1024 * 1024);
                const storage = this.shaderCacheStorage;
                if (!storage || typeof storage.save !== "function") return;
                await storage.save(this.shaderCacheStorageKey, payload);
                ++this.stats.shaderCachePersistentSaves;
            } catch (error) {
                this.shaderCacheDirty = true;
                ++this.stats.shaderCachePersistentFailures;
                this.warnOnce("shader-cache-save",
                    "persistent shader cache could not be saved; translated " +
                    "WGSL remains cached in memory", { message: String(error) });
            }
        }

        submit(bytes, metadata) {
            const owned = bytes instanceof Uint8Array ? bytes.slice() : new Uint8Array(bytes || []);
            this.work = this.work.then(() => this.initialize())
                .then(() => this.restorePersistentShaderCache())
                .then(() => this.executeBatch(owned, metadata || {}))
                .catch(error => {
                    this.failed = error;
                    console.error("[d3d9-webgpu] batch failed", error, metadata || {});
                    this.discardFrame();
                });
            return this.work;
        }

        trackReadback(operation) {
            this.pendingReadbacks.add(operation);
            operation.then(() => this.pendingReadbacks.delete(operation),
                () => this.pendingReadbacks.delete(operation));
            return operation;
        }

        idle() { return this.work; }

        async checkpointIdle() {
            await this.work;
            while (this.pendingReadbacks.size)
                await Promise.all(Array.from(this.pendingReadbacks));
        }

        flushForCheckpoint() {
            const original = this.sessionKey;
            for (const key of this.sessionStates.keys()) {
                this.switchSession(key);
                this.finishFrame(false);
            }
            if (original !== null) this.switchSession(original);
        }

        async resetForReplay() {
            await this.checkpointIdle();
            for (const key of this.sessionStates.keys()) {
                this.switchSession(key);
                this.releaseActiveSession("state-restore");
            }
            this.sessionStates.clear();
            this.sessionKey = null;
            this.pipelineCache.clear();
            this.bindGroupCache.clear();
            this.moduleCache.clear();
            this.samplerCache.clear();
            this.failed = null;
        }

        // ---- batch decode ----

        async executeBatch(bytes, metadata) {
            const timing = this["performanceTiming"];
            let segmentStart = timing ? timing["now"]() : 0;
            try {
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            if (bytes.byteLength < D9WG_BATCH_HEADER_BYTES) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG batch shorter than its header");
            }
            const magic = view.getUint32(0, true);
            const versionMajor = view.getUint16(4, true);
            const versionMinor = view.getUint16(6, true);
            const commandCount = view.getUint32(16, true);
            const commandBytes = view.getUint32(20, true);
            if (magic !== D9WG_MAGIC) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG batch has the wrong magic");
            }
            // Minor versions are accepted as a range, not an exact match. The
            // guest DLL and this file are deployed separately -- the proxy has
            // to be copied into the VM image, the page reloads on its own -- so
            // insisting they agree exactly turns any protocol addition into a
            // window where nothing renders at all and the only symptom is
            // "unsupported D9WG version".
            //
            // What makes the range safe is that every field added since
            // D9WG_VERSION_MIN_MINOR is length-gated at its decode site: an
            // older payload is short, the field reads as its default, and the
            // default is what that version meant. Adding a field that changes
            // the meaning of existing bytes would need the major version, which
            // is still an exact match.
            if (versionMajor !== D9WG_VERSION_MAJOR ||
                    versionMinor < D9WG_VERSION_MIN_MINOR ||
                    versionMinor > D9WG_VERSION_MINOR) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError(`unsupported D9WG version ${versionMajor}.${versionMinor}`);
            }
            if (commandBytes > bytes.byteLength - D9WG_BATCH_HEADER_BYTES) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError(
                    "D9WG batch command_bytes overruns the record");
            }
            const sessionLow = view.getUint32(24, true);
            const sessionHigh = view.getUint32(28, true);
            const sessionKey = sessionHigh.toString(16).padStart(8, "0") +
                sessionLow.toString(16).padStart(8, "0");
            this.switchSession(sessionKey);
            ++this.stats.batches;

            let offset = D9WG_BATCH_HEADER_BYTES;
            const end = D9WG_BATCH_HEADER_BYTES + commandBytes;
            let decoded = 0;
            while (offset + D9WG_COMMAND_HEADER_BYTES <= end) {
                const opcode = view.getUint16(offset, true);
                const size = view.getUint32(offset + 4, true);
                if (size < D9WG_COMMAND_HEADER_BYTES || offset + size > end) {
                    ++this.stats.malformedBatches;
                    throw new D9WGStreamError("D9WG command size is invalid");
                }
                const payloadOffset = offset + D9WG_COMMAND_HEADER_BYTES;
                const payloadBytes = size - D9WG_COMMAND_HEADER_BYTES;
                // One command's failure must not consume the rest of the
                // batch. A throw used to unwind all the way to submit(), which
                // dropped every command still queued behind it -- render target
                // bindings, resource creations, vertex declarations -- and the
                // guest had no way to know. The frames that followed then drew
                // against state the host had never been told about, and
                // reported it as unknown render targets and missing vertex
                // declarations: symptoms several batches removed from the one
                // command that actually failed.
                //
                // A malformed *stream* still fails the batch: D9WGStreamError
                // is not one bad command but a disagreement about the byte
                // layout, and continuing past it would be executing garbage.
                try {
                    const pending = this.dispatchCommand(opcode, bytes, view,
                        payloadOffset, payloadBytes, metadata);
                    if (pending && typeof pending.then === "function") {
                        if (timing) timing["sync"](timing["now"]() - segmentStart);
                        try { await pending; }
                        finally { if (timing) segmentStart = timing["now"](); }
                    }
                } catch (error) {
                    if (error instanceof D9WGStreamError) throw error;
                    ++this.stats.commandsFailed;
                    this.warnOnce("command-failed-" + opcode,
                        "a command threw and was skipped; the rest of the " +
                        "batch still executes, so this draw or state change " +
                        "is lost but nothing behind it is", {
                            opcode, message: String(error && error.message
                                ? error.message : error) });
                }
                // Any command other than a draw may have moved something the
                // constant block is built from. Draws are excluded because they
                // are the thing being deduplicated; opcodes 0x300..0x303 are the
                // four draw entry points.
                if (opcode < OP_DRAW_PRIMITIVE ||
                        opcode > OP_DRAW_INDEXED_PRIMITIVE_UP)
                    ++this.commandSerial;
                offset += size;
                ++decoded;
                ++this.stats.commands;
                // Mid-batch, because one PCI batch can carry a whole 16 MiB
                // arena's worth of draws -- checking only at the batch boundary
                // would let ~80000 of them pile up first.
                if (this.frame && this.frame.ops.length >= this.flushThreshold)
                    this.finishFrame(false);
            }
            if (decoded !== commandCount) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG command_count does not match the decoded stream");
            }

            const present = (view.getUint32(12, true) & D9WG_BATCH_FLAG_PRESENT) !== 0;
            if (present) this.finishFrame(true);
            else if (this.flushRequested) this.finishFrame(false);
            this.flushRequested = false;
            this.beat(metadata);
            if (this.shaderCacheDirty) this.schedulePersistentShaderCacheSave();
            this.saveActiveSessionState();
            } finally {
                if (timing) timing["sync"](timing["now"]() - segmentStart);
            }
        }

        dispatchCommand(opcode, bytes, view, offset, length, metadata) {
            const handler = this.handlers[opcode];
            if (!handler) {
                // Per plan section 6.8: an unrecognized opcode is skipped by
                // its size (already advanced by the caller), never treated
                // as "executed" -- it simply never produces GPU state.
                ++this.stats.unsupportedCommands;
                return;
            }
            return handler.call(this, bytes, view, offset, length, metadata);
        }

        // ---- device/resource state ----

        deviceState(handle) {
            let state = this.devices.get(handle);
            if (!state) {
                state = this.createDeviceState(handle);
                this.devices.set(handle, state);
            }
            return state;
        }

        createDeviceState(handle) {
            return {
                handle,
                // Where the guest's window is on the guest desktop, resent on
                // every Present so the page can place the overlay canvas.
                // Deliberately NOT the back buffer's size: emit_present_and_flush
                // fills width/height from GetClientRect, and a windowed game's
                // client area is smaller than the back buffer it hosts.
                surface: { hwnd: 0, x: 0, y: 0, width: 0, height: 0,
                    visible: true, noSurface: false, sessionKey: null },
                // What the guest asked for at CreateDevice/Reset, and therefore
                // the real size of the swap-chain colour attachment and of the
                // auto depth target created beside it.
                backBufferWidth: 0,
                backBufferHeight: 0,
                multisampleType: D3DMULTISAMPLE_NONE,
                multisampleQuality: 0,
                sampleCount: 1,
                // WebGPU swap-chain textures are always single-sampled.  A
                // multisampled D3D back buffer therefore renders into this
                // private attachment and resolves into getCurrentTexture() at
                // the end of every render pass.
                backBufferMsaaTexture: null,
                backBufferMsaaView: null,
                backBufferMsaaSrgbView: null,
                viewport: { x: 0, y: 0, width: 1, height: 1,
                    minZ: 0, maxZ: 1 },
                transforms: new Map([
                    [D3DTS_VIEW, IDENTITY4x4], [D3DTS_PROJECTION, IDENTITY4x4],
                    [D3DTS_WORLD, IDENTITY4x4],
                ]),
                // Highest n the guest has ever passed as D3DTS_WORLDMATRIX(n).
                // Indexed vertex blending sizes its palette from this rather
                // than from the 256 D3D9 allows, so an app using eight bones
                // uploads eight matrices per draw and not 256.
                maxWorldMatrixIndex: 0,
                renderStates: new Map(),
                // Auto depth-stencil surface, created on CREATE_DEVICE/RESET
                // when the guest asked for one. hasDepth drives both the
                // render pass attachment and whether pipelines declare a
                // depthStencil block.
                hasDepth: false,
                depthTexture: null,
                // CreateAdditionalSwapChain results, keyed by chain handle.
                // The implicit chain is not in here: it is the canvas.
                swapChains: new Map(),
                depthView: null,
                samplerStates: new Map(), // sampler*64+state -> value, read by samplerFor()
                textureStageStates: new Map(),
                vertexShaderHandle: 0,
                pixelShaderHandle: 0,
                // The D3D9 constant register file. Device state, not shader
                // state: it survives SetVertexShader and Reset, so it lives
                // here and is packed into a uniform buffer per draw by
                // constantBufferFor(). Kept as flat typed arrays because the
                // packing step is a straight subarray copy.
                vsConstF: new Float32Array(MAX_VS_CONST_F * 4),
                vsConstI: new Int32Array(MAX_CONST_I * 4),
                vsConstB: new Uint32Array(MAX_CONST_B),
                psConstF: new Float32Array(MAX_PS_CONST_F * 4),
                psConstI: new Int32Array(MAX_CONST_I * 4),
                psConstB: new Uint32Array(MAX_CONST_B),
                material: null,          // set by SET_MATERIAL; not yet consumed (M2/M3 lighting)
                lights: new Map(),       // light index -> D3DLIGHT9-shaped object; not yet consumed
                lightEnabled: new Map(), // light index -> bool
                // frequency is the raw SetStreamSourceFreq value. D3D9 starts
                // every stream at 1; an absent entry is treated identically.
                streams: new Map(),      // stream -> { handle, stride, offset, frequency }
                indexBufferHandle: 0,
                vertexDeclarationHandle: 0, // also used for the SET_FVF synthesized layout
                fvfLayout: null,         // set by SET_FVF, cleared by SET_VERTEX_DECLARATION
                textures: new Map(),     // stage -> resource handle
                // Explicitly bound colour targets. A slot holding 0 (and slot 0
                // by default) means the swap chain's back buffer, which is the
                // only target whose view cannot be taken until Present.
                renderTargets: [0, 0, 0, 0],
                renderTargetLevels: [0, 0, 0, 0],
                // Which cube face each slot names; 0 for a 2D target.
                renderTargetFaces: [0, 0, 0, 0],
                // D3DFMT_P8/A8P8 sample through this palette; null until
                // SetCurrentTexturePalette names one.
                currentPalette: null,
                // 0 = the device's auto depth-stencil; depthUnbound is
                // SetDepthStencilSurface(NULL), which is not the same thing --
                // it turns depth testing off for the draws that follow.
                depthTargetHandle: 0,
                depthTargetLevel: 0,
                depthUnbound: false,
                scissorRect: null,
                clipPlanes: Array.from({ length: 6 }, () => [0, 0, 0, 1]),
                inScene: false,
            };
        }

        createSessionState(key) {
            return {
                key,
                devices: new Map(),
                resources: new Map(),
                frame: null,
                activeOcclusion: null,
                presentingDevice: null,
                lastSwapTexture: null,
                backBufferTexture: null,
                backBufferView: null,
                backBufferSrgbView: null,
                backBufferTextureWidth: 0,
                backBufferTextureHeight: 0,
                palettes: new Map(),
                ddPaletteBuffers: new Map(),
                ddPaletteSerials: new Map(),
                windowState: null,
                cursor: { texture: null, view: null, width: 0, height: 0,
                    hotspotX: 0, hotspotY: 0, x: 0, y: 0, visible: false,
                    pipeline: null, sampler: null, uniform: null },
                lastDraws: { fixed: null, programmable: null },
                featureBits: 0,
            };
        }

        saveActiveSessionState() {
            if (this.sessionKey === null) return;
            const state = this.sessionStates.get(this.sessionKey);
            if (!state) return;
            state.devices = this.devices;
            state.resources = this.resources;
            state.frame = this.frame;
            state.activeOcclusion = this.activeOcclusion || null;
            state.presentingDevice = this.presentingDevice || null;
            state.lastSwapTexture = this.lastSwapTexture || null;
            state.backBufferTexture = this.backBufferTexture || null;
            state.backBufferView = this.backBufferView || null;
            state.backBufferSrgbView = this.backBufferSrgbView || null;
            state.backBufferTextureWidth = this.backBufferTextureWidth || 0;
            state.backBufferTextureHeight = this.backBufferTextureHeight || 0;
            state.palettes = this.palettes;
            state.ddPaletteBuffers = this.ddPaletteBuffers;
            state.ddPaletteSerials = this.ddPaletteSerials;
            state.windowState = this.windowState || null;
            state.cursor = this.cursor;
            state.lastDraws = this.lastDraws;
        }

        switchSession(key) {
            if (this.sessionKey === key && this.sessionStates.has(key)) return;
            const previousKey = this.sessionKey;
            this.saveActiveSessionState();
            let state = this.sessionStates.get(key);
            if (!state) {
                state = this.createSessionState(key);
                this.sessionStates.set(key, state);
            }
            this.sessionKey = key;
            this.devices = state.devices;
            this.resources = state.resources;
            this.frame = state.frame;
            this.activeOcclusion = state.activeOcclusion;
            this.presentingDevice = state.presentingDevice;
            this.lastSwapTexture = state.lastSwapTexture;
            this.backBufferTexture = state.backBufferTexture;
            this.backBufferView = state.backBufferView;
            this.backBufferSrgbView = state.backBufferSrgbView;
            this.backBufferTextureWidth = state.backBufferTextureWidth;
            this.backBufferTextureHeight = state.backBufferTextureHeight;
            this.palettes = state.palettes;
            this.ddPaletteBuffers = state.ddPaletteBuffers;
            this.ddPaletteSerials = state.ddPaletteSerials;
            this.windowState = state.windowState;
            this.cursor = state.cursor;
            this.lastDraws = state.lastDraws;
            if (previousKey !== null) {
                ++this.stats.sessionChanges;
                if (this.stats.sessionChanges === 1)
                    console.info("[d3d9-webgpu] multiple guest processes are " +
                        "active; D3D9 handles and in-flight frames are now " +
                        "isolated by the batch session id");
                const previous = this.sessionStates.get(previousKey);
                // Capability-only helper processes own no GPU state. Forget
                // them as soon as they go inactive so repeated benchmark runs
                // cannot grow the session table without bound.
                if (previous && !previous.devices.size &&
                        !previous.resources.size && !previous.frame &&
                        !previous.activeOcclusion && !previous.cursor.texture &&
                        !previous.backBufferTexture &&
                        !previous.ddPaletteBuffers.size)
                    this.sessionStates.delete(previousKey);
            }
        }

        // World * View * Projection in D3D's own row-vector order, so that
        // a vertex would be transformed as v * W * V * P. multiply4x4 is a
        // plain row-major multiply, which is exactly that chaining.
        wvp(state) {
            const world = state.transforms.get(D3DTS_WORLD) || IDENTITY4x4;
            const view_ = state.transforms.get(D3DTS_VIEW) || IDENTITY4x4;
            const projection = state.transforms.get(D3DTS_PROJECTION) || IDENTITY4x4;
            return multiply4x4(multiply4x4(world, view_), projection);
        }

        // ---- opcode handlers ----

        get handlers() {
            if (this._handlers) return this._handlers;
            this._handlers = {
                [OP_HELLO]: this.onHello,
                [OP_CREATE_DEVICE]: this.onCreateDevice,
                [OP_RESET]: this.onReset,
                [OP_PRESENT]: this.onPresent,
                [OP_CLEAR]: this.onClear,
                [OP_BEGIN_SCENE]: this.onBeginScene,
                [OP_END_SCENE]: this.onEndScene,
                [OP_CREATE_BUFFER]: this.onCreateBuffer,
                [OP_UPDATE_BUFFER]: this.onUpdateBuffer,
                [OP_DESTROY_RESOURCE]: this.onDestroyResource,
                [OP_CREATE_TEXTURE_2D]: this.onCreateTexture2D,
                [OP_CREATE_TEXTURE_CUBE]: this.onCreateTextureCube,
                [OP_CREATE_TEXTURE_VOLUME]: this.onCreateTextureVolume,
                [OP_UPDATE_TEXTURE]: this.onUpdateTexture,
                [OP_UPDATE_SURFACE]: this.onUpdateSurface,
                [OP_READBACK_SURFACE]: this.onReadbackSurface,
                [OP_SESSION_END]: this.onSessionEnd,
                [OP_SET_SCISSOR_RECT]: this.onSetScissorRect,
                [OP_SET_RENDER_TARGET]: this.onSetRenderTarget,
                [OP_SET_DEPTH_STENCIL_SURFACE_LEVEL]:
                    this.onSetDepthStencilSurfaceLevel,
                [OP_SET_PALETTE]: this.onSetPalette,
                [OP_SET_CURRENT_TEXTURE_PALETTE]:
                    this.onSetCurrentTexturePalette,
                [OP_GENERATE_MIPS]: this.onGenerateMips,
                [OP_SET_TEXTURE_LOD]: this.onSetTextureLOD,
                [OP_SET_GAMMA_RAMP]: this.onSetGammaRamp,
                [OP_CREATE_SWAP_CHAIN]: this.onCreateSwapChain,
                [OP_DESTROY_SWAP_CHAIN]: this.onDestroySwapChain,
                [OP_PRESENT_SWAP_CHAIN]: this.onPresentSwapChain,
                [OP_STRETCH_RECT]: this.onStretchRect,
                [OP_COLOR_FILL]: this.onColorFill,
                [OP_GUEST_LOG]: this.onGuestLog,
                [OP_CREATE_VERTEX_DECLARATION]: this.onCreateVertexDeclaration,
                [OP_CREATE_VERTEX_SHADER]: this.onCreateVertexShader,
                [OP_CREATE_PIXEL_SHADER]: this.onCreatePixelShader,
                [OP_CREATE_QUERY]: this.onCreateQuery,
                [OP_SET_CURSOR_PROPERTIES]: this.onSetCursorProperties,
                [OP_SET_CURSOR_POSITION]: this.onSetCursorPosition,
                [OP_SHOW_CURSOR]: this.onShowCursor,
                [OP_WINDOW_STATE]: this.onWindowState,
                [OP_SET_VERTEX_SHADER]: this.onSetVertexShader,
                [OP_SET_PIXEL_SHADER]: this.onSetPixelShader,
                [OP_SET_VERTEX_SHADER_CONSTANT_F]: this.onSetVertexShaderConstantF,
                [OP_SET_VERTEX_SHADER_CONSTANT_I]: this.onSetVertexShaderConstantI,
                [OP_SET_VERTEX_SHADER_CONSTANT_B]: this.onSetVertexShaderConstantB,
                [OP_SET_PIXEL_SHADER_CONSTANT_F]: this.onSetPixelShaderConstantF,
                [OP_SET_PIXEL_SHADER_CONSTANT_I]: this.onSetPixelShaderConstantI,
                [OP_SET_PIXEL_SHADER_CONSTANT_B]: this.onSetPixelShaderConstantB,
                [OP_SET_CLIP_PLANE]: this.onSetClipPlane,
                [OP_SET_RENDER_STATE]: this.onSetRenderState,
                [OP_SET_SAMPLER_STATE]: this.onSetSamplerState,
                [OP_SET_TEXTURE_STAGE_STATE]: this.onSetTextureStageState,
                [OP_SET_TEXTURE]: this.onSetTexture,
                [OP_SET_VIEWPORT]: this.onSetViewport,
                [OP_SET_TRANSFORM]: this.onSetTransform,
                [OP_SET_MATERIAL]: this.onSetMaterial,
                [OP_SET_LIGHT]: this.onSetLight,
                [OP_LIGHT_ENABLE]: this.onLightEnable,
                [OP_SET_STREAM_SOURCE]: this.onSetStreamSource,
                [OP_SET_STREAM_SOURCE_FREQ]: this.onSetStreamSourceFreq,
                [OP_SET_INDICES]: this.onSetIndices,
                [OP_SET_VERTEX_DECLARATION]: this.onSetVertexDeclaration,
                [OP_SET_FVF]: this.onSetFVF,
                [OP_DRAW_PRIMITIVE]: this.onDrawPrimitive,
                [OP_DRAW_INDEXED_PRIMITIVE]: this.onDrawIndexedPrimitive,
                [OP_DRAW_PRIMITIVE_UP]: this.onDrawPrimitiveUP,
                [OP_DRAW_INDEXED_PRIMITIVE_UP]: this.onDrawIndexedPrimitiveUP,
                [OP_BEGIN_QUERY]: this.onBeginQuery,
                [OP_END_QUERY]: this.onEndQuery,
            };
            // Opcode groups that live in a sibling module -- currently
            // ddraw_ops.js's 0x500 DirectDraw group. Merged here rather than
            // listed above so this file stays the D3D9 command set, and so a
            // page that never loads the sibling simply has those opcodes count
            // as unsupported instead of failing to construct.
            if (D3D9WebGPUExecutor.extensionHandlers)
                Object.assign(this._handlers,
                    D3D9WebGPUExecutor.extensionHandlers);
            return this._handlers;
        }

        onHello(bytes, view, offset) {
            void view.getUint32(offset, true); // guest_pointer_bits
            const featureBits = view.getUint32(offset + 4, true);
            const sessionLow = view.getUint32(offset + 8, true);
            const sessionHigh = view.getUint32(offset + 12, true);
            // Keyed as a string, not `high * 2**32 + low`: a 64-bit id does not
            // survive a float64 above 2**53, and the low bits are exactly the
            // ones that distinguish two processes. The old arithmetic key made
            // the log self-contradictory (created "...576bff", replaced
            // "...576c00" -- the same session, printed exact then rounded) and
            // let two distinct sessions round together into one key, which
            // would keep a dead process's handles alive against a live one.
            const sessionKey = sessionHigh.toString(16).padStart(8, "0") +
                sessionLow.toString(16).padStart(8, "0");
            // HELLO duplicates the batch-header id as a corruption check. The
            // header selected the context before command decoding; changing it
            // here would let one malformed command redirect the rest of its
            // batch into another process's handle namespace.
            if (this.sessionKey !== sessionKey) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG HELLO session does not match its batch");
            }
            const session = this.sessionStates.get(sessionKey);
            if (session) session.featureBits = featureBits;
            this.stats.guestFeatureBits = featureBits;
            // Record the active caps profile so diagnostics can distinguish a
            // fixed-function/SM2 run from a default SM3 run directly.
            this.stats.guestShaderModel2 =
                (featureBits & D9WG_FEATURE_SHADER_MODEL_2) !== 0;
            this.stats.guestShaderModel3 =
                (featureBits & D9WG_FEATURE_SHADER_MODEL_3) !== 0;
        }

        retireResourceState(resource) {
            if (!resource) return;
            this.retireGPUObject(resource.gpuBuffer);
            this.retireGPUObject(resource.gpuTexture);
            this.retireGPUObject(resource.msaaTexture);
            // Installed by ddraw_ops.js on palettised sample resources. A
            // SESSION_END bypasses per-resource opcodes, so its companion
            // textures have to participate in the process-wide teardown too.
            if (resource.ddSampleViews) {
                for (const entry of resource.ddSampleViews.values())
                    this.retireGPUObject(entry && entry.texture);
                resource.ddSampleViews.clear();
            }
            resource.destroyed = true;
        }

        retirePaletteCachesForDevice(handle) {
            const prefix = (handle >>> 0) + ":";
            for (const [key, entry] of this.ddPaletteBuffers) {
                if (!key.startsWith(prefix)) continue;
                this.retireGPUObject(entry && entry.buffer);
                this.ddPaletteBuffers.delete(key);
            }
            for (const key of this.ddPaletteSerials.keys())
                if (key.startsWith(prefix)) this.ddPaletteSerials.delete(key);
            for (const key of this.palettes.keys())
                if (key.startsWith(prefix)) this.palettes.delete(key);
        }

        retireDeviceState(state, reason) {
            if (!state) return;
            state.surface = { ...state.surface, visible: false };
            if (typeof this.options.onDestroy === "function")
                this.options.onDestroy(state.surface, reason || "device");
            if (state.swapChains) {
                for (const chain of state.swapChains.values()) {
                    if (chain.context &&
                            typeof chain.context.unconfigure === "function")
                        chain.context.unconfigure();
                    this.notifySwapChainSurface(
                        { ...chain.surface, visible: false }, "destroy");
                }
                state.swapChains.clear();
            }
            this.retireGPUObject(state.depthTexture);
            this.retireGPUObject(state.backBufferMsaaTexture);
            this.retireGPUObject(state.gammaRampTexture);
            this.retirePaletteCachesForDevice(state.handle);
        }

        retireActiveSessionBackBuffer() {
            this.retireGPUObject(this.backBufferTexture);
            this.backBufferTexture = null;
            this.backBufferView = null;
            this.backBufferSrgbView = null;
            this.backBufferTextureWidth = 0;
            this.backBufferTextureHeight = 0;
            this.lastSwapTexture = null;
        }

        releaseActiveSession(reason) {
            // No queued frame from an ending process may be replayed later
            // after another process has reused the same numeric handles.
            this.discardFrame();
            for (const resource of this.resources.values())
                this.retireResourceState(resource);
            this.resources.clear();
            for (const state of this.devices.values())
                this.retireDeviceState(state, reason || "session-end");
            this.devices.clear();
            for (const entry of this.ddPaletteBuffers.values())
                this.retireGPUObject(entry && entry.buffer);
            this.ddPaletteBuffers.clear();
            this.ddPaletteSerials.clear();
            this.palettes.clear();
            this.retireActiveSessionBackBuffer();
            this.retireGPUObject(this.cursor && this.cursor.texture);
            this.retireGPUObject(this.cursor && this.cursor.uniform);
            this.cursor = { texture: null, view: null, width: 0, height: 0,
                hotspotX: 0, hotspotY: 0, x: 0, y: 0, visible: false,
                pipeline: null, sampler: null, uniform: null };
            this.activeOcclusion = null;
            this.presentingDevice = null;
            this.windowState = null;
            this.lastDraws = { fixed: null, programmable: null };
        }

        onSessionEnd(bytes, view, offset, length) {
            if (length < 8) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG SESSION_END payload is truncated");
            }
            const sessionLow = view.getUint32(offset, true);
            const sessionHigh = view.getUint32(offset + 4, true);
            const sessionKey = sessionHigh.toString(16).padStart(8, "0") +
                sessionLow.toString(16).padStart(8, "0");
            if (this.sessionKey !== sessionKey) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError(
                    "D9WG SESSION_END session does not match its batch");
            }
            const endedKey = this.sessionKey;
            this.releaseActiveSession("session-end");
            this.sessionStates.delete(endedKey);
            // SESSION_END is required to be the final command from a process.
            // Clearing the active key also makes a corrupt trailing command
            // unable to save freshly-created state back under the dead id.
            this.sessionKey = null;
            ++this.stats.sessionsEnded;
        }

        onCreateDevice(bytes, view, offset, length) {
            if (length < 52) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG CREATE_DEVICE payload is not protocol 1.3");
            }
            const handle = view.getUint32(offset, true);
            const hwnd = view.getUint32(offset + 4, true);
            const x = view.getInt32(offset + 8, true);
            const y = view.getInt32(offset + 12, true);
            const width = view.getUint32(offset + 16, true);
            const height = view.getUint32(offset + 20, true);
            const enableAutoDepth = view.getUint32(offset + 36, true);
            const multisampleType = view.getUint32(offset + 44, true);
            const multisampleQuality = view.getUint32(offset + 48, true);
            // A frame left un-presented by a previous device -- typically a
            // process that exited mid-frame -- must not bleed into this one.
            // Its recorded ops reference that device's depth target and
            // back-buffer size, which WebGPU rejects as soon as the sizes
            // differ ("depth stencil attachment size does not match ...").
            this.discardFrame();
            const state = this.deviceState(handle);
            state.viewport = { x: 0, y: 0, width, height, minZ: 0, maxZ: 1 };
            state.surface = { hwnd, x, y, width, height, visible: true,
                noSurface: false, sessionKey: this.sessionKey };
            state.backBufferWidth = width;
            state.backBufferHeight = height;
            this.configureBackBufferMSAA(state, width, height,
                multisampleType, multisampleQuality);
            this.ensureDepthTarget(state, width, height, enableAutoDepth !== 0);
            this.notifySurface(state, "create");
        }

        onReset(bytes, view, offset, length) {
            if (length < 56) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG RESET payload is not protocol 1.3");
            }
            const oldHandle = view.getUint32(offset, true);
            const newHandle = view.getUint32(offset + 4, true);
            const hwnd = view.getUint32(offset + 8, true);
            const x = view.getInt32(offset + 12, true);
            const y = view.getInt32(offset + 16, true);
            const width = view.getUint32(offset + 20, true);
            const height = view.getUint32(offset + 24, true);
            const enableAutoDepth = view.getUint32(offset + 40, true);
            const multisampleType = view.getUint32(offset + 48, true);
            const multisampleQuality = view.getUint32(offset + 52, true);
            const oldState = this.devices.get(oldHandle);
            if (oldState) {
                this.retireGPUObject(oldState.depthTexture);
                this.retireGPUObject(oldState.backBufferMsaaTexture);
            }
            // A D3D9 Reset leaves the back buffer's contents undefined, so the
            // owned texture is dropped rather than carried across; the next
            // frame recreates it, zero-filled, at whatever size Reset asked for.
            this.retireGPUObject(this.backBufferTexture);
            this.backBufferTexture = null;
            this.backBufferView = null;
            this.backBufferSrgbView = null;
            this.backBufferTextureWidth = 0;
            this.backBufferTextureHeight = 0;
            this.devices.delete(oldHandle);
            const state = this.deviceState(newHandle);
            state.viewport = { x: 0, y: 0, width, height, minZ: 0, maxZ: 1 };
            state.surface = { hwnd, x, y, width, height, visible: true,
                noSurface: false, sessionKey: this.sessionKey };
            state.backBufferWidth = width;
            state.backBufferHeight = height;
            this.configureBackBufferMSAA(state, width, height,
                multisampleType, multisampleQuality);
            this.ensureDepthTarget(state, width, height, enableAutoDepth !== 0);
            this.notifySurface(state, "reset");
        }

        resizeCanvasIfNeeded(width, height) {
            if (this.canvas.width !== width) this.canvas.width = width;
            if (this.canvas.height !== height) this.canvas.height = height;
        }

        // The swap-chain colour attachment is context.getCurrentTexture(). The
        // shared canvas is resized only at Present, after that process has won
        // ownership; CREATE/RESET from a helper session must not clear the
        // currently visible owner's canvas.
        // Reading state.surface here instead was a real defect: Present rewrites
        // state.surface with the window's client rect every frame, so a windowed
        // game reported a back buffer 13 rows shorter than the auto depth target
        // created with it (Kart Rider: 800x587 against 800x600). The pass then
        // looked mismatched and dropped depth, which turns off depth testing for
        // the entire game rather than for anything the app actually did.
        /*
         * D3D9 draws into a back buffer that survives Present; WebGPU hands out
         * a different canvas texture every frame, valid only for the task that
         * acquired it. Owning the back buffer resolves both at once.
         *
         * The lifetime is what matters most. A D3D9 frame does not arrive in
         * one task -- d3d9_proxy.c flushes a partial batch whenever the DMA
         * arena fills, and each PCI record is a separate macrotask -- so
         * acquiring the swap-chain texture early and holding it across the
         * frame is the pattern that goes stale ("Destroyed texture ... used in
         * a submit"). Recording into an owned texture instead means nothing
         * before Present touches the swap chain at all, which is what lets
         * finishFrame(false) submit a partial frame (see flushThreshold).
         *
         * It is also less work than the copy pair it replaces: the previous
         * shape copied the retained image *into* the canvas texture at the
         * start of every frame (so loadOp:"load" saw last frame's pixels) and
         * copied it back *out* before Present (so GetRenderTargetData had
         * something to read). Owning it makes the retained image and the render
         * target the same object, leaving one copy at Present.
         */
        ensureBackBufferTexture(width, height) {
            width = Math.max(1, width >>> 0);
            height = Math.max(1, height >>> 0);
            if (this.backBufferTexture &&
                    this.backBufferTextureWidth === width &&
                    this.backBufferTextureHeight === height)
                return this.backBufferTexture;
            // A resize discards the contents, which is what D3D9 does too: the
            // back buffer is undefined across a Reset that changes its size.
            this.retireGPUObject(this.backBufferTexture);
            this.backBufferTexture = this.device.createTexture({
                label: "D3D9 back buffer",
                size: { width, height, depthOrArrayLayers: 1 },
                format: this.format,
                ...(this.swapchainSrgbFormat
                    ? { viewFormats: [this.swapchainSrgbFormat] } : {}),
                mipLevelCount: 1,
                // RENDER_ATTACHMENT to draw into, COPY_SRC to reach the swap
                // chain and GetRenderTargetData, COPY_DST + TEXTURE_BINDING
                // because StretchRect uses the back buffer as both ends of a
                // full-screen post-processing round trip.
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            this.backBufferView = this.backBufferTexture.createView();
            this.backBufferSrgbView = this.swapchainSrgbFormat
                ? this.backBufferTexture.createView(
                    { format: this.swapchainSrgbFormat })
                : this.backBufferView;
            this.backBufferTextureWidth = width;
            this.backBufferTextureHeight = height;
            ++this.stats.backBufferAllocations;
            return this.backBufferTexture;
        }

        backBufferWidthOf(state) {
            return state.backBufferWidth || this.canvas.width ||
                state.surface.width || 1;
        }

        backBufferHeightOf(state) {
            return state.backBufferHeight || this.canvas.height ||
                state.surface.height || 1;
        }

        configureBackBufferMSAA(state, width, height, type, quality) {
            this.retireGPUObject(state.backBufferMsaaTexture);
            state.backBufferMsaaTexture = null;
            state.backBufferMsaaView = null;
            state.backBufferMsaaSrgbView = null;
            const sampleCount = sampleCountForD3D(type, quality);
            if (!sampleCount) {
                this.warnOnce("invalid-backbuffer-msaa-" + type + "-" + quality,
                    "the guest requested an unsupported D3D9 multisample " +
                    "configuration; the host falls back to a single-sampled " +
                    "back buffer instead of creating an invalid WebGPU texture",
                    { type, quality });
            }
            state.multisampleType = sampleCount ? (type >>> 0)
                : D3DMULTISAMPLE_NONE;
            state.multisampleQuality = sampleCount ? (quality >>> 0) : 0;
            state.sampleCount = sampleCount || 1;
            if (state.sampleCount === 1 || !width || !height) return;
            const descriptor = {
                label: "D3D9 multisampled back buffer",
                size: { width, height, depthOrArrayLayers: 1 },
                format: this.format,
                ...(this.swapchainSrgbFormat
                    ? { viewFormats: [this.swapchainSrgbFormat] } : {}),
                mipLevelCount: 1,
                sampleCount: state.sampleCount,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
            };
            state.backBufferMsaaTexture = this.device.createTexture(descriptor);
            state.backBufferMsaaView = state.backBufferMsaaTexture.createView();
            state.backBufferMsaaSrgbView = this.swapchainSrgbFormat
                ? state.backBufferMsaaTexture.createView(
                    { format: this.swapchainSrgbFormat })
                : state.backBufferMsaaView;
        }

        // Creates (or drops) the device's auto depth-stencil target. D3D9
        // reports many depth formats but the guest can never read any of
        // them back in M1, so one depth24plus-stencil8 target satisfies all
        // of them; only whether a depth buffer exists at all is observable.
        ensureDepthTarget(state, width, height, enabled) {
            if (state.depthTexture) {
                // Never destroy it inline: the frame currently being recorded
                // may already have pinned this texture's view (see
                // recordDraw's frame.depthView) and will not submit until
                // Present, so an immediate destroy produces
                // "Destroyed texture ... used in a submit" -- a real crash
                // observed when a device was re-created or Reset mid-frame.
                this.retireGPUObject(state.depthTexture);
                state.depthTexture = null;
                state.depthView = null;
            }
            state.hasDepth = !!enabled;
            if (!enabled || !width || !height) return;
            state.depthTexture = this.device.createTexture({
                label: "D3D9 auto depth-stencil",
                size: { width, height, depthOrArrayLayers: 1 },
                format: DEPTH_FORMAT,
                sampleCount: state.sampleCount || 1,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
            });
            state.depthView = state.depthTexture.createView();
            state.depthWidth = width;
            state.depthHeight = height;
        }

        // One line per distinct condition, so a per-frame problem cannot flood
        // the console while still being reported the first time it happens.
        warnOnce(key, message, details) {
            this.warned = this.warned || new Set();
            if (this.warned.has(key)) return;
            this.warned.add(key);
            console.warn("[d3d9-webgpu] " + message, details || "");
        }

        // Releases a GPU object that the in-flight frame may still reference.
        // If a frame is being recorded, the object rides along with that
        // frame's transient list and is destroyed only once the frame's
        // submit has completed; otherwise it waits on the queue directly.
        retireGPUObject(object) {
            if (!object || typeof object.destroy !== "function") return;
            if (this.frame) {
                this.frame.transientBuffers.push(object);
                return;
            }
            const destroy = () => object.destroy();
            if (this.device.queue
                    && typeof this.device.queue.onSubmittedWorkDone === "function")
                this.device.queue.onSubmittedWorkDone().then(destroy, destroy);
            else
                destroy();
        }

        // WebGPU can take the device away (driver reset, tab backgrounded on
        // some platforms, an unrecoverable validation failure). Before this, the
        // executor logged one error and then failed every subsequent batch
        // forever, which on screen is a frozen canvas with no explanation.
        //
        // What recovery achieves and what it does not, precisely:
        //
        //   It does   bring the host back to a working GPUDevice, canvas context
        //             and cache set, so the page is alive and the next Present
        //             does not throw.
        //   It does   preserve every translation result: WGSL text is not tied
        //             to a GPUDevice (plan 8.5), so the translator does not run
        //             again -- only the GPUShaderModules are rebuilt, lazily.
        //   It does not restore the guest's resources. Their contents live in
        //             the guest's CPU shadows, and the only way to get them back
        //             is for the guest to replay them -- which it does on Reset
        //             (recreate_device_resources in d3d9_proxy.c) but has no
        //             reason to do, because nothing tells it the device was
        //             lost. Until the host->guest notification of plan 6.7
        //             exists, draws after a loss reference handles the new
        //             device never saw and are counted in droppedDraws.
        //
        // So this converts "the page is dead" into "the page is alive and the
        // stats say exactly what happened", which is the honest extent of it.
        watchForDeviceLoss() {
            if (!this.device || !this.device.lost ||
                    typeof this.device.lost.then !== "function")
                return;
            const lostDevice = this.device;
            this.device.lost.then(info => {
                if (this.destroyed || info && info.reason === "destroyed") return;
                if (this.device !== lostDevice) return;
                ++this.stats.deviceLosses;
                console.error("[d3d9-webgpu] WebGPU device lost (" +
                    ((info && info.reason) || "unknown") + "): " +
                    ((info && info.message) || "") +
                    " -- rebuilding; the guest will see D3DERR_DEVICELOST and " +
                    "re-create its resources through its own Reset path");
                this.recoverDevice();
            }, () => {});
        }

        recoverDevice() {
            // Everything below was created by the lost device and cannot be
            // destroyed or reused; dropping the references is all that is
            // possible and all that is needed.
            this.discardFrame();
            this.sessionStates.clear();
            this.devices = new Map();
            this.resources = new Map();
            this.palettes = new Map();
            this.ddPaletteBuffers = new Map();
            this.ddPaletteSerials = new Map();
            this.pipelineCache.clear();
            this.bindGroupCache.clear();
            this.moduleCache.clear();
            this.samplerCache.clear();
            this.cursor = { ...this.cursor, texture: null, view: null,
                pipeline: null, sampler: null, uniform: null,
                bindGroupLayout: null, visible: false };
            this.activeOcclusion = null;
            this.presentingDevice = null;
            this.lastSwapTexture = null;
            this.windowState = null;
            this.fallbackTexture = null;
            this.defaultAttributes = null;
            this.fallbackView = null;
            this.fallbackDepth = null;
            this.fallbackViews = null;
            this.substituteDepthViews = null;
            this.backBufferTexture = null;
            this.backBufferView = null;
            this.backBufferSrgbView = null;
            this.backBufferTextureWidth = 0;
            this.backBufferTextureHeight = 0;
            this.uniformRingChunks = [];
            this.uniformStaging = [];
            this.uniformRingIndex = 0;
            this.uniformRingCursor = 0;
            this.objectIds = new WeakMap();
            this.nextObjectId = 1;
            this.device = null;
            this.context = null;
            this.readyPromise = null;
            this.failed = null;
            this.sessionKey = null;
            if (typeof this.options.onDeviceLost === "function")
                this.options.onDeviceLost();
            // initialize() is idempotent through readyPromise, and submit()
            // already awaits it before every batch, so the next batch after a
            // loss brings the new device up.
            this.work = this.initialize().then(() => {
                ++this.stats.deviceRecoveries;
            }, error => {
                console.error("[d3d9-webgpu] device recovery failed", error);
            });
        }

        notifySurface(state, reason) {
            if (typeof this.options.onSurface === "function")
                this.options.onSurface(state.surface, reason);
        }

        onPresent(bytes, view, offset) {
            // The actual GPU submit happens in finishFrame(), called once
            // per executeBatch() when the outer D9WGBatchHeader carries
            // D9WG_BATCH_FLAG_PRESENT -- see the end of executeBatch(). The
            // guest recomputes the window's current screen position on
            // every Present (d3d9_proxy.c has no window-move subclassing in
            // M1), so this is the live source of truth for canvas placement
            // rather than a separate UPDATE_SURFACE event.
            const handle = view.getUint32(offset, true);
            const state = this.deviceState(handle);
            const hwnd = view.getUint32(offset + 4, true);
            const x = view.getInt32(offset + 8, true);
            const y = view.getInt32(offset + 12, true);
            let width = view.getUint32(offset + 16, true);
            let height = view.getUint32(offset + 20, true);
            // The guest recomputes the client rect on every Present, and
            // GetClientRect is known to return an empty rect in fullscreen
            // (recorded as an open issue at M1). Letting a 0x0 report through
            // makes the host repeatedly resize/reposition the overlay canvas
            // between the real size and nothing, which reads on screen as
            // flicker. The last non-empty size is the better answer: a window
            // that genuinely has no client area has nothing to show anyway.
            if (!width || !height) {
                ++this.stats.emptySurfaceReports;
                width = state.surface.width || width;
                height = state.surface.height || height;
            }
            const changed = state.surface.hwnd !== hwnd || state.surface.x !== x ||
                state.surface.y !== y || state.surface.width !== width ||
                state.surface.height !== height;
            state.surface = { ...state.surface, hwnd, x, y, width, height,
                visible: true, noSurface: false };
            if (changed) {
                ++this.stats.surfaceChanges;
                this.notifySurface(state, "present");
            }
            this.presentingDevice = state;
        }

        onBeginScene(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            this.deviceState(handle).inScene = true;
        }

        onEndScene(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            this.deviceState(handle).inScene = false;
        }

        writeQueryResponse(query, requestId, value, status, metadata) {
            // A released query can have its guest response slot recycled while
            // an older GPU map is still completing. Never let that late map
            // overwrite the new owner's slot.
            if (query.destroyed) return false;
            const writer = metadata && metadata.writeGuestMemory;
            if (typeof writer !== "function") {
                ++this.stats.responseWriteFailures;
                return false;
            }
            try {
                const out = new Uint8Array(16);
                const result = new DataView(out.buffer);
                const numeric = typeof value === "bigint"
                    ? value : BigInt(Math.max(0, Number(value) || 0));
                result.setUint32(0, requestId >>> 0, true);
                result.setUint32(4, Number(numeric & 0xffffffffn), true);
                result.setUint32(8, Number((numeric >> 32n) & 0xffffffffn), true);
                // Last by protocol contract: observing completion means the
                // preceding request/value bytes are visible too.
                result.setUint32(12, status >>> 0, true);
                writer(D9WG_RESPONSE_REGION_OFFSET + query.responseOffset, out);
                return true;
            } catch (error) {
                ++this.stats.responseWriteFailures;
                this.warnOnce("query-response-write",
                    "a completed GPU query could not be written back to guest " +
                    "DMA memory", { message: String(error) });
                return false;
            }
        }

        onCreateQuery(bytes, view, offset, length) {
            if (length < 16) return;
            const handle = view.getUint32(offset + 4, true);
            const type = view.getUint32(offset + 8, true);
            const responseOffset = view.getUint32(offset + 12, true);
            if (responseOffset + 16 > D9WG_QUERY_REGION_BYTES ||
                    (responseOffset & 15) !== 0) {
                ++this.stats.queryFailures;
                return;
            }
            this.resources.set(handle, { kind: RESOURCE_QUERY, type,
                responseOffset, active: false, requestId: 0 });
            ++this.stats.queriesCreated;
        }

        onBeginQuery(bytes, view, offset, length, metadata) {
            if (length < 16) return;
            const query = this.resources.get(view.getUint32(offset + 4, true));
            if (!query || query.kind !== RESOURCE_QUERY) return;
            const responseOffset = view.getUint32(offset + 8, true);
            const requestId = view.getUint32(offset + 12, true);
            if (responseOffset !== query.responseOffset) return;
            query.active = true;
            query.requestId = requestId;
            query.metadata = metadata || {};
            const frame = this.ensureFrame();
            frame.ops.push({ kind: "query-begin", query, requestId,
                metadata: query.metadata });
            ++this.stats.queryBegins;
        }

        onEndQuery(bytes, view, offset, length, metadata) {
            if (length < 16) return;
            const query = this.resources.get(view.getUint32(offset + 4, true));
            if (!query || query.kind !== RESOURCE_QUERY) return;
            const responseOffset = view.getUint32(offset + 8, true);
            const requestId = view.getUint32(offset + 12, true);
            if (responseOffset !== query.responseOffset) return;
            query.requestId = requestId;
            const resultMetadata = metadata || query.metadata || {};
            const frame = this.ensureFrame();
            frame.ops.push({ kind: "query-end", query, requestId,
                metadata: resultMetadata });
            query.active = false;
            ++this.stats.queryEnds;
            /* A GetData call submits the partial guest batch without Present.
             * Ask executeBatch() to submit this frame too so polling can make
             * progress. */
            this.flushRequested = true;
        }

        /*
         * Told to the guest once per finished batch. A readback makes the guest
         * spin until the host answers, and submission has no backpressure, so
         * without this the guest cannot tell a host that is thousands of
         * batches behind from one that has died -- and it gave up on the first,
         * reporting a readback failure for a host that was working correctly.
         */
        beat(metadata) {
            const writer = metadata && metadata.writeGuestMemory;
            if (typeof writer !== "function") {
                this.warnOnce("beat-no-writer",
                    "this batch carried no guest-memory writer, so the guest " +
                    "cannot be told the host is alive and will time out any " +
                    "readback it waits on");
                return;
            }
            this.heartbeat = (this.heartbeat + 1) >>> 0;
            const out = this.heartbeatBuffer;
            out[0] = this.heartbeat & 0xff;
            out[1] = (this.heartbeat >>> 8) & 0xff;
            out[2] = (this.heartbeat >>> 16) & 0xff;
            out[3] = (this.heartbeat >>> 24) & 0xff;
            const at = D9WG_RESPONSE_REGION_OFFSET + D9WG_HEARTBEAT_OFFSET;
            try {
                writer(at, out);
            } catch (error) {
                ++this.stats.responseWriteFailures;
                this.warnOnce("beat-write-failed",
                    "the host cannot write into guest memory at all; every " +
                    "readback and query response is being lost the same way", {
                        dmaOffset: at,
                        message: String(error && error.message
                            ? error.message : error),
                    });
            }
        }

        writeReadbackResponse(responseOffset, requestId, payload, status,
                metadata) {
            const writer = metadata && metadata.writeGuestMemory;
            if (typeof writer !== "function") {
                // The guest is *spinning* on this response, so returning
                // quietly is not a no-op -- it is a hang that ends in the
                // guest's own timeout with nothing to explain it.
                ++this.stats.responseWriteFailures;
                this.warnOnce("readback-no-writer",
                    "a readback response could not be delivered: this batch " +
                    "arrived without a guest-memory writer, so the guest will " +
                    "spin until its own timeout", { responseOffset, requestId });
                return false;
            }
            const data = payload || new Uint8Array(0);
            const out = new Uint8Array(16 + data.byteLength);
            const result = new DataView(out.buffer);
            result.setUint32(0, requestId >>> 0, true);
            result.setUint32(4, data.byteLength, true);
            if (data.byteLength) out.set(data, 16);
            result.setUint32(12, status >>> 0, true);
            writer(D9WG_RESPONSE_REGION_OFFSET + responseOffset, out);
            return true;
        }

        async onReadbackSurface(bytes, view, offset, length, metadata) {
            ++this.stats.readbackRequests;
            if (length < 48) {
                // Same reasoning as above: the guest blocks on the answer, so
                // a malformed request has to be answered, not dropped.
                ++this.stats.renderTargetReadbackFailures;
                this.warnOnce("readback-short-payload",
                    "a readback command was too short to decode; the guest is " +
                    "told it failed rather than left waiting", { length });
                try {
                    this.writeReadbackResponse(
                        view.getUint32(offset + 40, true),
                        view.getUint32(offset + 44, true), null,
                        D9WG_RESPONSE_FAILED, metadata);
                } catch (_) { ++this.stats.responseWriteFailures; }
                return;
            }
            const deviceHandle = view.getUint32(offset, true);
            const textureHandle = view.getUint32(offset + 4, true);
            const level = view.getUint32(offset + 8, true);
            const format = view.getUint32(offset + 12, true);
            const width = view.getUint32(offset + 16, true);
            const height = view.getUint32(offset + 20, true);
            const firstRow = view.getUint32(offset + 24, true);
            const rowCount = view.getUint32(offset + 28, true);
            const destinationPitch = view.getUint32(offset + 32, true);
            const destinationBytes = view.getUint32(offset + 36, true);
            const responseOffset = view.getUint32(offset + 40, true);
            const requestId = view.getUint32(offset + 44, true);
            const face = length >= 52 ? view.getUint32(offset + 48, true) : 0;
            const fail = error => {
                ++this.stats.renderTargetReadbackFailures;
                try {
                    this.writeReadbackResponse(responseOffset, requestId, null,
                        D9WG_RESPONSE_FAILED, metadata);
                } catch (writeError) {
                    ++this.stats.responseWriteFailures;
                    this.warnOnce("readback-response-write-failed",
                        "the failure response could not be written either, so " +
                        "the guest sees silence rather than an error", {
                            message: String(writeError) });
                }
                // Keyed by cause, not just by format: the first failure used
                // to suppress every later one, so a second, different fault in
                // the same session was invisible.
                this.warnOnce("render-target-readback-" + format + "-" +
                        String(error && error.message ? error.message : error),
                    "a GPU render target could not be read back", {
                        format, width, height, message: String(error) });
            };
            let buffer = null;
            let mapped = false;
            try {
                const resource = textureHandle
                    ? this.resources.get(textureHandle) : null;
                const compressed = !!(resource &&
                    isCompressedFormat(format));
                const indexed = !!(resource && resource.ddIndexed);
                const blockBytes = compressed
                    ? compressedBlockBytes(format) : 0;
                const destinationBpp = indexed ? 1 : d3dBytesPerTexel(format);
                const copiedRows = compressed ? Math.ceil(rowCount / 4)
                    : rowCount;
                const minimumPitch = compressed
                    ? Math.ceil(width / 4) * blockBytes
                    : width * destinationBpp;
                if ((!destinationBpp && !compressed) || !width || !height ||
                        !rowCount ||
                        firstRow >= height || rowCount > height - firstRow ||
                        (compressed && (firstRow & 3)) ||
                        destinationPitch < minimumPitch ||
                        destinationBytes !== copiedRows * destinationPitch ||
                        responseOffset < D9WG_QUERY_REGION_BYTES ||
                        responseOffset + 16 + destinationBytes >
                            D9WG_RESPONSE_REGION_BYTES)
                    throw new Error("invalid readback descriptor");

                /* Submit every deferred draw before encoding the copy. Queue
                 * submissions are ordered, so the following copy observes the
                 * resolved render target without a CPU-side GPU wait. */
                if (this.frame) this.finishFrame(false);
                const state = this.devices.get(deviceHandle);
                let sourceTexture = resource && resource.gpuTexture
                    ? resource.gpuTexture : null;
                if (!textureHandle)
                    sourceTexture = this.backBufferTexture ||
                        this.lastSwapTexture || this.context.getCurrentTexture();
                const gpuFormat = resource ? resource.gpuFormat : this.format;
                if (!sourceTexture || !gpuFormat)
                    throw new Error("readback source is unavailable");
                const sourceWidth = resource
                    ? Math.max(1, resource.width >> level) : width;
                const sourceHeight = resource
                    ? Math.max(1, resource.height >> level) : height;
                if (width !== sourceWidth || height !== sourceHeight)
                    throw new Error("readback dimensions do not match source");

                if (compressed && !String(gpuFormat).startsWith("bc"))
                    throw new Error("compressed readback source is not BC storage");
                if (indexed && gpuFormat !== "r8uint")
                    throw new Error("indexed readback source is not index storage");
                const sourceBpp = indexed ? 1
                    : gpuFormat === "rgba16float" ? 8
                    : gpuFormat === "rg32float" ? 8
                    : gpuFormat === "rgba32float" ? 16 : 4;
                const rawRowBytes = compressed
                    ? Math.ceil(width / 4) * blockBytes : width * sourceBpp;
                const gpuRowPitch = alignUp(rawRowBytes, 256);
                buffer = this.device.createBuffer({
                    label: "D3D9 render-target readback",
                    size: gpuRowPitch * copiedRows,
                    usage: BUFFER_USAGE_COPY_DST | BUFFER_USAGE_MAP_READ,
                });
                const encoder = this.device.createCommandEncoder();
                encoder.copyTextureToBuffer({ texture: sourceTexture,
                    mipLevel: level, origin: { x: 0, y: firstRow, z: face } },
                    { buffer, bytesPerRow: gpuRowPitch,
                        rowsPerImage: copiedRows },
                    { width: blockAlignedCopyExtent(width, compressed),
                        height: blockAlignedCopyExtent(rowCount, compressed),
                        depthOrArrayLayers: 1 });
                this.device.queue.submit([encoder.finish()]);
                ++this.stats.queueSubmits;
                /*
                 * Bounded, because the guest is *spinning* on the response --
                 * it cannot make progress until this resolves, so a map that
                 * never completes freezes the whole VM rather than failing.
                 * That is what a lost or errored device looks like from here:
                 * the submit is accepted, the fence never signals, and the only
                 * symptom is a stall. Losing the race is reported as a failure,
                 * which the guest turns into D3DERR_DRIVERINTERNALERROR
                 * immediately instead of thirty seconds later.
                 */
                let mapTimer = null;
                await Promise.race([
                    buffer.mapAsync(MAP_MODE_READ),
                    new Promise((_, reject) => {
                        mapTimer = setTimeout(() => reject(new Error(
                            "readback map did not complete within " +
                            this.readbackTimeoutMs + "ms; the device is " +
                            "probably lost or an earlier submit was rejected")),
                            this.readbackTimeoutMs);
                    }),
                ]).finally(() => { if (mapTimer !== null) clearTimeout(mapTimer); });
                mapped = true;
                const mappedBytes = new Uint8Array(buffer.getMappedRange());
                const packed = new Uint8Array(destinationBytes);
                if (compressed || indexed) {
                    for (let row = 0; row < copiedRows; ++row)
                        packed.set(mappedBytes.subarray(row * gpuRowPitch,
                            row * gpuRowPitch + rawRowBytes),
                            row * destinationPitch);
                } else {
                    for (let row = 0; row < rowCount; ++row)
                        packGPUReadbackRow(format, gpuFormat, mappedBytes,
                            row * gpuRowPitch, width, packed,
                            row * destinationPitch);
                }
                buffer.unmap();
                mapped = false;
                buffer.destroy();
                buffer = null;
                this.writeReadbackResponse(responseOffset, requestId, packed,
                    D9WG_RESPONSE_OK, metadata);
                ++this.stats.renderTargetReadbacks;
                this.stats.renderTargetReadbackBytes += packed.byteLength;
            } catch (error) {
                if (buffer) {
                    if (mapped) {
                        try { buffer.unmap(); } catch (_) {}
                    }
                    try { buffer.destroy(); } catch (_) {}
                }
                fail(error);
            }
        }

        // A "frame" here is pure JS bookkeeping -- a list of pending clear/
        // draw operations -- with no WebGPU objects created yet. This is
        // deliberate: a canvas's context.getCurrentTexture() is only valid
        // for the task that acquired it; once control returns to the
        // browser's event loop, that texture is liable to be presented and
        // invalidated out from under you ("Destroyed texture ... used in a
        // submit"). A single D3D9 frame's Clear/Draw/Present calls do not
        // reliably arrive in one task: d3d9_proxy.c flushes a partial batch
        // over PCI whenever the DMA ring fills up (reserve_command_locked's
        // intermediate submit_batch_locked(FALSE)), and each such PCI record
        // is delivered to this executor as a separate worker postMessage --
        // a separate macrotask. Acquiring the swapchain texture eagerly on
        // the first Clear of a frame and holding it until a much-later
        // Present-carrying submit is exactly the pattern that goes stale.
        // Recording lightweight ops now and only turning them into real
        // WebGPU calls inside finishFrame() -- acquired, recorded, and
        // submitted in one synchronous stretch -- avoids that regardless of
        // how many separate PCI submits contributed to the frame.
        ensureFrame() {
            if (this.frame) return this.frame;
            // `serial` identifies this frame for the write-after-record check in
            // applyBufferUpdate(); it must be unique per frame, never reused.
            // Chunks are retained, only the write position rewinds: WebGPU
            // orders queue.writeBuffer against already-submitted work, so
            // rewinding after the previous frame's Present cannot overwrite
            // bytes a queued draw still has to read.
            this.uniformRingIndex = 0;
            this.uniformRingCursor = 0;
            this.frame = { ops: [], transientBuffers: [],
                serial: ++this.frameSerial,
                statStart: {
                    pipelineCreations: this.stats.pipelineCreations,
                    bindGroupCreations: this.stats.bindGroupCreations,
                    queueSubmits: this.stats.queueSubmits,
                    renderPasses: this.stats.renderPasses,
                } };
            return this.frame;
        }

        // If a command throws partway through a batch (see submit()'s catch
        // handler), this.frame may be left holding recorded-but-unreplayed
        // ops. Since no WebGPU render pass/encoder exists yet at this point
        // (those are only created in finishFrame(), at Present time), there
        // is nothing to end -- just drop the ops and free any transient
        // buffers already created for them so the next frame starts clean.
        discardFrame() {
            const frame = this.frame;
            // A discarded/reset device cannot legally carry an open query
            // into the replacement command stream.
            this.activeOcclusion = null;
            if (!frame) return;
            this.frame = null;
            if (frame.transientBuffers && frame.transientBuffers.length) {
                for (const buffer of frame.transientBuffers) buffer.destroy();
            }
        }

        onClear(bytes, view, offset, length) {
            const deviceHandle = view.getUint32(offset, true);
            const flags = view.getUint32(offset + 4, true);
            const color = view.getUint32(offset + 8, true);
            const depth = view.getFloat32(offset + 12, true);
            const stencil = view.getUint32(offset + 16, true);
            const state = this.deviceState(deviceHandle);
            const clearsColor = (flags & D3DCLEAR_TARGET) !== 0;
            // A depth/stencil clear is only meaningful if the device
            // actually has an auto depth-stencil surface.
            const targets = this.renderTargetsFor(state);
            if (!targets) return;
            const clearsDepth = (flags & D3DCLEAR_ZBUFFER) !== 0 && targets.hasDepth;
            const clearsStencil = (flags & D3DCLEAR_STENCIL) !== 0 && targets.hasDepth;
            // A depth clear is what makes a substituted attachment equivalent
            // to the oversized one it stands in for, so it has to be recorded
            // even when the clear does nothing else.
            this.noteSubstituteDepthUse(targets, clearsDepth);
            if (!clearsColor && !clearsDepth && !clearsStencil) return;
            const a = ((color >>> 24) & 0xff) / 255;
            const r = ((color >>> 16) & 0xff) / 255;
            const g = ((color >>> 8) & 0xff) / 255;
            const b = (color & 0xff) / 255;
            const frame = this.ensureFrame();
            const rectCount = view.getUint32(offset + 20, true);
            if (rectCount) {
                if (24 + rectCount * 16 > length) {
                    ++this.stats.malformedBatches;
                    throw new D9WGStreamError("D9WG Clear rectangles overrun the command");
                }
                const rects = [];
                for (let index = 0; index < rectCount; ++index) {
                    const base = offset + 24 + index * 16;
                    const left = Math.max(0, Math.min(targets.width,
                        view.getInt32(base, true)));
                    const top = Math.max(0, Math.min(targets.height,
                        view.getInt32(base + 4, true)));
                    const right = Math.max(left, Math.min(targets.width,
                        view.getInt32(base + 8, true)));
                    const bottom = Math.max(top, Math.min(targets.height,
                        view.getInt32(base + 12, true)));
                    if (right > left && bottom > top)
                        rects.push({ left, top, right, bottom });
                }
                if (rects.length) {
                    frame.ops.push({ kind: "rect-clear", targets, clearsColor,
                        clearsDepth, clearsStencil, color: { r, g, b, a },
                        depth, stencil, rects });
                    ++this.stats.partialClears;
                }
                return;
            }
            frame.ops.push({
                kind: "clear", targets,
                clearsColor: clearsColor || !!this.debug.forceClearColor,
                clearsDepth, clearsStencil,
                color: this.debug.forceClearColor || { r, g, b, a },
                depth, stencil,
            });
        }

        // Replays every recorded clear/draw op against a freshly-acquired
        // swapchain texture, all synchronously, right before submit -- see
        // the comment on ensureFrame() for why acquisition cannot happen any
        // earlier than this. A "clear" op starts a new render pass (WebGPU
        // has no mid-pass re-clear); a "draw" op opens a loadOp:"load" pass
        // first if none is open yet (a draw with no preceding Clear in this
        // frame means "keep whatever the swapchain texture already has").
        finishFrame(present = true) {
            /*
             * A Present with no frame at all still has work to do. An earlier
             * flush can consume every recorded op, and onPresent() records
             * nothing itself, so `this.frame` is legitimately null here -- but
             * the canvas hands out a fresh, undefined texture each frame, so
             * without the copy below everything already submitted would stay in
             * the owned back buffer and the screen would hold whatever the
             * uninitialised canvas texture contains.
             */
            const frame = this.frame || (present ? this.ensureFrame() : null);
            if (!frame) return;
            this.frame = null;
            // Counted only for a real Present: a partial flush is a fragment
            // of a frame, and "this frame never cleared" is a statement about
            // whole frames.
            if (present) {
                if (!frame.ops.length) ++this.stats.framesWithNoOps;
                else if (!frame.ops.some(op =>
                        op.kind === "clear" && op.clearsColor))
                    ++this.stats.framesWithoutColorClear;
            } else if (frame.ops.length) {
                ++this.stats.frameFlushes;
            }
            /*
             * `|| present` matters once a frame can be flushed early: the last
             * flush may consume every remaining op, leaving a Present with
             * nothing to replay -- and the canvas texture is a *new*, undefined
             * texture each frame, so skipping the work would leave everything
             * already submitted stuck in the owned back buffer, never reaching
             * the screen. A Present always copies, even with no ops of its own.
             */
            if (frame.ops.length || present) {
                const encoder = this.device.createCommandEncoder();
                const carriedOcclusion = this.activeOcclusion || null;
                this.activeOcclusion = null;
                const hasOcclusion = !!carriedOcclusion || frame.ops.some(op =>
                    op.kind === "query-begin" && op.query.type ===
                        D3DQUERYTYPE_OCCLUSION);
                /* Any op can force a render-pass boundary through a target
                 * switch. One slot per recorded op is therefore a safe upper
                 * bound on the number of query segments. */
                const occlusionBudget = hasOcclusion
                    ? Math.min(8192, Math.max(1, frame.ops.length)) : 0;
                const timestampBudget = this.deviceFeatures.timestampQuery
                    ? frame.ops.filter(op => op.kind === "query-end" &&
                        op.query.type === D3DQUERYTYPE_TIMESTAMP).length : 0;
                const occlusionQuerySet = occlusionBudget &&
                        typeof this.device.createQuerySet === "function"
                    ? this.device.createQuerySet({ type: "occlusion",
                        count: Math.max(1, occlusionBudget) }) : null;
                const timestampQuerySet = timestampBudget &&
                        typeof this.device.createQuerySet === "function"
                    ? this.device.createQuerySet({ type: "timestamp",
                        count: Math.max(1, timestampBudget) }) : null;
                let occlusionSlot = 0;
                let timestampSlot = 0;
                let activeOcclusion = carriedOcclusion;
                let activeOcclusionSlots = [];
                let activeOcclusionSlot = -1;
                const occlusionCompletions = [];
                const timestampCompletions = [];
                const fenceCompletions = [];
                // Ops recorded against the implicit back buffer land in the
                // owned texture, so this whole replay is independent of the
                // swap chain; getCurrentTexture() is acquired further down and
                // only when this finish actually presents.
                const backState = this.presentingDevice ||
                    this.devices.values().next().value || null;
                const backWidth = backState
                    ? this.backBufferWidthOf(backState)
                    : (this.backBufferTextureWidth || this.canvas.width || 1);
                const backHeight = backState
                    ? this.backBufferHeightOf(backState)
                    : (this.backBufferTextureHeight || this.canvas.height || 1);
                const backTexture = this.ensureBackBufferTexture(
                    backWidth, backHeight);
                const swapView = this.backBufferView;
                const swapSrgbView = this.backBufferSrgbView;
                // GetRenderTargetData on the implicit back buffer reads the
                // owned texture, which -- unlike a canvas texture -- is still
                // valid in whatever later task the request arrives in.
                this.lastSwapTexture = backTexture;
                // No restore copy: a D3D9 back buffer is routinely reused by
                // applications that redraw only the changing rectangles between
                // Presents (3DMark06's loading renderer does exactly that on
                // 3342 of its first 3343 frames), and the owned texture simply
                // still holds last frame's pixels, so loadOp:"load" is honest.
                // Every op carries the target set it was recorded against (see
                // renderTargetsFor). A pass covers the longest run of ops that
                // share a target set; a Clear always starts a new one, because
                // WebGPU expresses a clear only as a pass's loadOp.
                let pass = null;
                let openKey = null;
                /*
                 * Everything below is *pass* state in WebGPU: a setX persists
                 * until it is changed or the pass ends, so re-issuing an
                 * identical value is a no-op that still costs a full JS->Dawn
                 * crossing. Nine of them were issued per draw regardless of
                 * whether anything moved, which is invisible at the few hundred
                 * draws a scene makes and dominant at the hundred thousand
                 * 3DMark06's batch-size test makes -- there, consecutive draws
                 * differ only in their index range, so eight of the nine calls
                 * are pure overhead.
                 *
                 * `bound` shadows what this pass has actually been told. It is
                 * reset in beginPass() and nowhere else, because beginning a
                 * pass is exactly when WebGPU forgets all of it.
                 */
                let bound = null;
                const resetBoundState = () => {
                    bound = {
                        pipeline: null, bindGroup: null, dynamicOffsets: null,
                        blendR: NaN, blendG: NaN, blendB: NaN, blendA: NaN,
                        stencilReference: -1,
                        vpX: NaN, vpY: NaN, vpW: NaN, vpH: NaN,
                        vpMinZ: NaN, vpMaxZ: NaN,
                        scX: NaN, scY: NaN, scW: NaN, scH: NaN,
                        clipScissor: undefined, clip: null,
                        vertexBuffers: [],
                        indexBuffer: null, indexFormat: null, indexOffset: -1,
                    };
                };
                const sameOffsets = (a, b) => {
                    if (a === b) return true;
                    if (!a || !b || a.length !== b.length) return false;
                    for (let i = 0; i < a.length; ++i)
                        if (a[i] !== b[i]) return false;
                    return true;
                };
                const endOcclusionSegment = () => {
                    if (!pass || activeOcclusionSlot < 0) return;
                    pass.endOcclusionQuery();
                    activeOcclusionSlots.push(activeOcclusionSlot);
                    activeOcclusionSlot = -1;
                };
                const closePass = () => {
                    if (!pass) return;
                    endOcclusionSegment();
                    pass.end();
                    pass = null;
                    openKey = null;
                };
                const beginPass = (targets, clearColor, clearDepthStencil) => {
                    const descriptor = {
                        colorAttachments: targets.colors.map(color => ({
                            view: color.swapchain
                                ? (color.format === this.swapchainSrgbFormat
                                    ? swapSrgbView : swapView)
                                : color.view,
                            loadOp: clearColor ? "clear" : "load",
                            storeOp: "store",
                            ...(clearColor ? { clearValue: clearColor } : {}),
                        })),
                    };
                    if (occlusionQuerySet)
                        descriptor.occlusionQuerySet = occlusionQuerySet;
                    if (targets.depthView) {
                        const clearsDepth = clearDepthStencil &&
                            clearDepthStencil.depth !== undefined;
                        const clearsStencil = clearDepthStencil &&
                            clearDepthStencil.stencil !== undefined;
                        descriptor.depthStencilAttachment = {
                            view: targets.depthView,
                            depthLoadOp: clearsDepth ? "clear" : "load",
                            depthStoreOp: "store",
                            stencilLoadOp: clearsStencil ? "clear" : "load",
                            stencilStoreOp: "store",
                            ...(clearsDepth ? {
                                depthClearValue: clearDepthStencil.depth } : {}),
                            ...(clearsStencil ? {
                                stencilClearValue: clearDepthStencil.stencil } : {}),
                        };
                    }
                    ++this.stats.renderPasses;
                    const created = encoder.beginRenderPass(descriptor);
                    resetBoundState();
                    if (activeOcclusion && occlusionQuerySet &&
                            occlusionSlot < occlusionBudget) {
                        activeOcclusionSlot = occlusionSlot++;
                        created.beginOcclusionQuery(activeOcclusionSlot);
                    }
                    return created;
                };
                // The back buffer and the auto depth-stencil must agree on size
                // or WebGPU rejects the whole command buffer -- and with it
                // every later frame, not just this one.
                // A blit op carries its own attachment views rather than a
                // target set, so it is not part of this check.
                const backBufferOps = frame.ops.filter(op => op.targets &&
                    op.targets.colors.some(color => color.swapchain));
                const mismatched = backBufferOps.find(op => op.targets.depthView &&
                    (op.targets.width !== backWidth ||
                     op.targets.height !== backHeight));
                if (mismatched) {
                    this.warnOnce("depth-size-mismatch",
                        "dropping a frame whose depth target " +
                        mismatched.targets.width + "x" + mismatched.targets.height +
                        " does not match the back buffer " +
                        backWidth + "x" + backHeight);
                    frame.ops.length = 0;
                }
                for (const op of frame.ops) {
                    if (op.kind === "query-begin") {
                        if (op.query.type === D3DQUERYTYPE_OCCLUSION) {
                            closePass();
                            activeOcclusion = { query: op.query,
                                requestId: op.requestId,
                                metadata: op.metadata, value: 0n,
                                failed: false, pending: Promise.resolve() };
                            activeOcclusionSlots = [];
                        }
                        continue;
                    }
                    if (op.kind === "query-end") {
                        if (op.query.type === D3DQUERYTYPE_OCCLUSION) {
                            endOcclusionSegment();
                            const record = activeOcclusion || {
                                query: op.query, requestId: op.requestId,
                                metadata: op.metadata, value: 0n,
                                failed: false, pending: Promise.resolve() };
                            record.requestId = op.requestId;
                            record.metadata = op.metadata;
                            occlusionCompletions.push({ record,
                                query: record.query,
                                requestId: op.requestId,
                                metadata: op.metadata,
                                slots: activeOcclusionSlots.slice(),
                                final: true });
                            activeOcclusion = null;
                            activeOcclusionSlots = [];
                        } else if (op.query.type === D3DQUERYTYPE_TIMESTAMP &&
                                timestampQuerySet &&
                                typeof encoder.writeTimestamp === "function") {
                            closePass();
                            const slot = timestampSlot++;
                            encoder.writeTimestamp(timestampQuerySet, slot);
                            timestampCompletions.push({ ...op, slot });
                        } else {
                            fenceCompletions.push(op);
                        }
                        continue;
                    }
                    if (op.kind === "copy") {
                        closePass();
                        encoder.copyTextureToTexture(op.source, op.destination,
                            op.size);
                        continue;
                    }
                    if (op.kind === "blit") {
                        // A blit is its own pass against its own attachment.
                        closePass();
                        const transient = this.replayBlit(encoder, op, swapView);
                        if (transient) frame.transientBuffers.push(transient);
                        continue;
                    }
                    if (op.kind === "ddblit") {
                        // The DirectDraw blit: the same shape, plus colour
                        // keying, mirroring and index/palette storage, so it is
                        // replayed by ddraw_ops.js.
                        closePass();
                        const transient = this.replayDDBlit(encoder, op,
                            swapView, backTexture);
                        if (transient) frame.transientBuffers.push(transient);
                        continue;
                    }
                    if (op.kind === "present-swap-chain") {
                        // An additional chain's canvas is acquired here, in
                        // the same synchronous stretch as the submit that
                        // consumes it -- the rule getCurrentTexture() imposes
                        // applies per canvas, not just to the implicit one.
                        closePass();
                        let target = null;
                        try {
                            target = op.chain.context.getCurrentTexture();
                        } catch (error) {
                            ++this.stats.swapChainPresentsDropped;
                            this.warnOnce("swap-chain-acquire",
                                "an additional swap chain's canvas could not " +
                                "be acquired; its frame is dropped",
                                { message: String(error) });
                        }
                        if (target) {
                            const width = Math.min(target.width, op.width);
                            const height = Math.min(target.height, op.height);
                            // A blit rather than copyTextureToTexture: the
                            // chain's back buffer is an ordinary D3D texture,
                            // so its format is whatever the guest asked for,
                            // while the canvas is the preferred canvas format.
                            // A copy requires those to be identical and they
                            // routinely are not.
                            if (width && height) {
                                const transient = this.replayBlit(encoder, {
                                    sourceView: op.sourceView,
                                    destinationView: null,
                                    destinationFormat: this.format,
                                    sourceFormat: op.sourceFormat,
                                    sourceRect: [0, 0, 1, 1],
                                    viewport: [0, 0, width, height],
                                    filterPoint: false,
                                }, target.createView());
                                if (transient)
                                    frame.transientBuffers.push(transient);
                            }
                        }
                        continue;
                    }
                    if (op.kind === "generate-mips") {
                        closePass();
                        for (const transient of
                                this.replayGenerateMips(encoder, op))
                            frame.transientBuffers.push(transient);
                        continue;
                    }
                    if (op.kind === "rect-clear") {
                        closePass();
                        const transient = this.replayRectClear(encoder, op,
                            swapView, swapSrgbView);
                        if (transient) frame.transientBuffers.push(transient);
                        continue;
                    }
                    if (op.kind === "color-fill") {
                        closePass();
                        const transient = this.replayColorFill(encoder, op);
                        if (transient) frame.transientBuffers.push(transient);
                        continue;
                    }
                    if (op.kind === "clear") {
                        closePass();
                        // A Clear that only touches depth still has to keep the
                        // colour already drawn this frame, and vice versa --
                        // hence the two independent load ops.
                        pass = beginPass(op.targets,
                            op.clearsColor ? op.color : null,
                            (op.clearsDepth || op.clearsStencil) ? {
                                ...(op.clearsDepth ? { depth: op.depth } : {}),
                                ...(op.clearsStencil ? { stencil: op.stencil } : {}),
                            } : null);
                        openKey = op.targets.key;
                        continue;
                    }
                    if (!pass || openKey !== op.targets.key) {
                        closePass();
                        pass = beginPass(op.targets, null, null);
                        openKey = op.targets.key;
                    }
                    if (bound.pipeline !== op.pipeline) {
                        pass.setPipeline(op.pipeline);
                        bound.pipeline = op.pipeline;
                    } else ++this.stats.redundantStateSkipped;
                    const offsets = op.dynamicOffsets || EMPTY_OFFSETS;
                    if (bound.bindGroup !== op.bindGroup ||
                            !sameOffsets(bound.dynamicOffsets, offsets)) {
                        pass.setBindGroup(0, op.bindGroup, offsets);
                        bound.bindGroup = op.bindGroup;
                        bound.dynamicOffsets = offsets;
                    } else ++this.stats.redundantStateSkipped;
                    const blend = op.blendConstant;
                    if (bound.blendR !== blend.r || bound.blendG !== blend.g ||
                            bound.blendB !== blend.b || bound.blendA !== blend.a) {
                        pass.setBlendConstant(blend);
                        bound.blendR = blend.r; bound.blendG = blend.g;
                        bound.blendB = blend.b; bound.blendA = blend.a;
                    } else ++this.stats.redundantStateSkipped;
                    if (bound.stencilReference !== op.stencilReference) {
                        pass.setStencilReference(op.stencilReference);
                        bound.stencilReference = op.stencilReference;
                    } else ++this.stats.redundantStateSkipped;
                    const vp = op.viewport;
                    const viewportMoved = bound.vpX !== vp.x ||
                        bound.vpY !== vp.y || bound.vpW !== vp.width ||
                        bound.vpH !== vp.height || bound.vpMinZ !== vp.minZ ||
                        bound.vpMaxZ !== vp.maxZ;
                    if (viewportMoved) {
                        pass.setViewport(vp.x, vp.y, vp.width, vp.height,
                                vp.minZ, vp.maxZ);
                        bound.vpX = vp.x; bound.vpY = vp.y;
                        bound.vpW = vp.width; bound.vpH = vp.height;
                        bound.vpMinZ = vp.minZ; bound.vpMaxZ = vp.maxZ;
                    } else ++this.stats.redundantStateSkipped;
                    // A D3D9 viewport clips; a WebGPU one only maps NDC to
                    // pixels. Without a matching scissor, geometry an app
                    // expected the viewport to cut off is drawn across the whole
                    // target instead -- which is why the clip rect is the
                    // viewport intersected with D3DRS_SCISSORTESTENABLE's rect
                    // (D3D9 applies both), not just the latter.
                    //
                    // The intersection is memoised as well as skipped, because
                    // recomputing it allocates a rect per draw. Keyed on the
                    // viewport having *moved* rather than on op.viewport's
                    // identity: every op carries its own copy of the viewport,
                    // so an identity check would miss on every single draw. The
                    // scissor is compared by identity because it is null --
                    // literally the same null -- whenever D3DRS_SCISSORTESTENABLE
                    // is off, which is the case this is here to make fast.
                    let clip = bound.clip;
                    if (!clip || viewportMoved || bound.clipScissor !== op.scissor) {
                        clip = intersectRects(vp, op.scissor,
                                op.targets.width, op.targets.height);
                        bound.clip = clip;
                        bound.clipScissor = op.scissor;
                    }
                    if (bound.scX !== clip.x || bound.scY !== clip.y ||
                            bound.scW !== clip.width || bound.scH !== clip.height) {
                        pass.setScissorRect(clip.x, clip.y, clip.width, clip.height);
                        bound.scX = clip.x; bound.scY = clip.y;
                        bound.scW = clip.width; bound.scH = clip.height;
                    } else ++this.stats.redundantStateSkipped;
                    for (let slot = 0; slot < op.vertexBuffers.length; ++slot) {
                        const binding = op.vertexBuffers[slot];
                        const previous = bound.vertexBuffers[slot];
                        if (previous && previous.buffer === binding.buffer &&
                                previous.offset === binding.offset) {
                            ++this.stats.redundantStateSkipped;
                            continue;
                        }
                        pass.setVertexBuffer(slot, binding.buffer, binding.offset);
                        bound.vertexBuffers[slot] = binding;
                    }
                    if (op.indexInfo) {
                        if (bound.indexBuffer !== op.indexInfo.buffer ||
                                bound.indexFormat !== op.indexInfo.format ||
                                bound.indexOffset !== op.indexInfo.offset) {
                            pass.setIndexBuffer(op.indexInfo.buffer,
                                    op.indexInfo.format, op.indexInfo.offset);
                            bound.indexBuffer = op.indexInfo.buffer;
                            bound.indexFormat = op.indexInfo.format;
                            bound.indexOffset = op.indexInfo.offset;
                        } else ++this.stats.redundantStateSkipped;
                        pass.drawIndexed(op.indexInfo.count, op.instanceCount || 1,
                                op.indexInfo.firstIndex, op.indexInfo.baseVertex);
                    } else {
                        // StartVertex is already folded into each stream's
                        // setVertexBuffer offset (see boundStreams), so
                        // firstVertex stays 0 here.
                        if ((op.instanceCount || 1) === 1)
                            pass.draw(op.vertexCount || 0);
                        else
                            pass.draw(op.vertexCount || 0, op.instanceCount);
                    }
                }
                closePass();
                // D3D9 permits an occlusion query to cross Present. Resolve
                // this frame's segments now, retain the accumulator, and open
                // a fresh WebGPU segment when the next frame starts.
                if (activeOcclusion) {
                    if (activeOcclusionSlots.length)
                        occlusionCompletions.push({ record: activeOcclusion,
                            query: activeOcclusion.query,
                            requestId: activeOcclusion.requestId,
                            metadata: activeOcclusion.metadata,
                            slots: activeOcclusionSlots.slice(),
                            final: false });
                    this.activeOcclusion = activeOcclusion;
                }
                const queryReadbacks = [];
                const encodeQueryReadback = (querySet, count, completions,
                        kind) => {
                    if (!querySet || !count || !completions.length) return;
                    const byteCount = alignUp(count * 8, 256);
                    const resolve = this.device.createBuffer({
                        label: "D3D9 " + kind + " query resolve",
                        size: byteCount,
                        usage: BUFFER_USAGE_QUERY_RESOLVE |
                            BUFFER_USAGE_COPY_SRC,
                    });
                    const read = this.device.createBuffer({
                        label: "D3D9 " + kind + " query readback",
                        size: byteCount,
                        usage: BUFFER_USAGE_COPY_DST | BUFFER_USAGE_MAP_READ,
                    });
                    encoder.resolveQuerySet(querySet, 0, count, resolve, 0);
                    encoder.copyBufferToBuffer(resolve, 0, read, 0,
                        count * 8);
                    queryReadbacks.push({ kind, count, completions, querySet,
                        resolve, read });
                };
                encodeQueryReadback(occlusionQuerySet, occlusionSlot,
                    occlusionCompletions.filter(item => item.slots.length),
                    "occlusion");
                encodeQueryReadback(timestampQuerySet, timestampSlot,
                    timestampCompletions, "timestamp");
                /* A query enclosing no draws still has a real answer: zero
                 * visible samples. It needs only the queue fence, not a query
                 * buffer mapping. */
                for (const completion of occlusionCompletions) {
                    if (!completion.slots.length && completion.final)
                        fenceCompletions.push({ ...completion,
                            query: completion.query, requestId: completion.requestId,
                            metadata: completion.metadata, zeroOcclusion: true });
                }
                // The one place the swap chain is touched, and it happens in
                // the same synchronous stretch as the submit that consumes it,
                // which is the whole rule getCurrentTexture() imposes.
                if (present) {
                    // Canvas width/height are global even though the retained
                    // image is per session. Defer this destructive resize until
                    // the session actually presents, so a capability helper's
                    // CREATE_DEVICE cannot blank the visible process.
                    this.resizeCanvasIfNeeded(this.backBufferTextureWidth,
                        this.backBufferTextureHeight);
                    const swapTexture = this.context.getCurrentTexture();
                    // A canvas resize between recording and here would leave
                    // the two sizes disagreeing; copying the overlap keeps the
                    // submit valid instead of failing the whole command buffer.
                    const copyWidth = Math.min(swapTexture.width,
                        this.backBufferTextureWidth);
                    const copyHeight = Math.min(swapTexture.height,
                        this.backBufferTextureHeight);
                    if (copyWidth && copyHeight) {
                        let presentSource = backTexture;
                        if (typeof this.replayDDOverlays === "function") {
                            const composite = this.replayDDOverlays(encoder,
                                this.presentingDevice, backTexture,
                                copyWidth, copyHeight, frame);
                            if (composite) {
                                presentSource = composite;
                                frame.transientBuffers.push(composite);
                            }
                        }
                        // A gamma ramp is applied here, at the one point every
                        // finished pixel passes through on its way to the
                        // canvas -- which is where the hardware applies it too.
                        // The plain copy stays the path for the overwhelmingly
                        // common identity case, because a lookup pass costs a
                        // full-screen draw the copy does not.
                        const gammaView = this.presentGammaView();
                        if (gammaView) {
                            // The configured canvas format, not
                            // swapTexture.format: the context was configured
                            // with the former and a pipeline target has to
                            // match what the pass writes.
                            const entry = this.gammaBlitPipelineFor(this.format);
                            const pass = encoder.beginRenderPass({
                                colorAttachments: [{
                                    view: swapTexture.createView(),
                                    loadOp: "clear",
                                    clearValue: { r: 0, g: 0, b: 0, a: 1 },
                                    storeOp: "store" }],
                            });
                            ++this.stats.renderPasses;
                            pass.setPipeline(entry.pipeline);
                            pass.setBindGroup(0, this.device.createBindGroup({
                                    layout: entry.bindGroupLayout,
                                    entries: [
                                    { binding: 0,
                                      resource: presentSource.createView() },
                                    { binding: 1, resource: entry.sampler },
                                    { binding: 2, resource: gammaView },
                                ],
                            }));
                            pass.setViewport(0, 0, copyWidth, copyHeight, 0, 1);
                            pass.draw(6);
                            pass.end();
                            ++this.stats.gammaPresents;
                        } else {
                            encoder.copyTextureToTexture(
                                { texture: presentSource },
                                { texture: swapTexture },
                                { width: copyWidth, height: copyHeight,
                                    depthOrArrayLayers: 1 });
                        }
                        ++this.stats.backBufferPresents;
                    }
                    // Drawn onto the canvas copy rather than the back buffer,
                    // so the cursor never accumulates into the image the next
                    // frame loads or GetRenderTargetData reads.
                    this.drawCursor(encoder, swapTexture.createView(),
                        swapTexture.width, swapTexture.height);
                }
                this.uploadUniformStaging();
                this.device.queue.submit([encoder.finish()]);
                ++this.stats.queueSubmits;

                for (const pending of queryReadbacks) {
                    const mapping = pending.read.mapAsync(MAP_MODE_READ).then(() => {
                        const mapped = pending.read.getMappedRange();
                        const source = new DataView(mapped);
                        const values = new Map();
                        for (const completion of pending.completions) {
                            let value = 0n;
                            if (pending.kind === "occlusion") {
                                for (const slot of completion.slots)
                                    value += source.getBigUint64(slot * 8, true);
                            } else {
                                value = source.getBigUint64(completion.slot * 8,
                                    true);
                            }
                            values.set(completion, value);
                        }
                        pending.read.unmap();
                        pending.read.destroy();
                        pending.resolve.destroy();
                        if (typeof pending.querySet.destroy === "function")
                            pending.querySet.destroy();
                        return { values };
                    }).catch(error => {
                        ++this.stats.queryFailures;
                        pending.read.destroy();
                        pending.resolve.destroy();
                        if (typeof pending.querySet.destroy === "function")
                            pending.querySet.destroy();
                        this.warnOnce("query-map-" + pending.kind,
                            "GPU query readback failed", {
                                message: String(error) });
                        return { error };
                    });
                    if (pending.kind === "occlusion") {
                        for (const completion of pending.completions) {
                            const record = completion.record;
                            record.pending = this.trackReadback(record.pending.then(() => mapping)
                                .then(result => {
                                    if (result.error) record.failed = true;
                                    else record.value += result.values.get(completion);
                                    if (!completion.final) return;
                                    ++this.stats.occlusionQueriesResolved;
                                    this.writeQueryResponse(record.query,
                                        completion.requestId, record.value,
                                        record.failed ? D9WG_RESPONSE_FAILED
                                            : D9WG_RESPONSE_OK,
                                        completion.metadata);
                                }));
                        }
                    } else {
                        this.trackReadback(mapping.then(result => {
                            for (const completion of pending.completions) {
                                if (result.error) {
                                    this.writeQueryResponse(completion.query,
                                        completion.requestId, 0,
                                        D9WG_RESPONSE_FAILED,
                                        completion.metadata);
                                    continue;
                                }
                                ++this.stats.timestampQueriesResolved;
                                this.writeQueryResponse(completion.query,
                                    completion.requestId,
                                    result.values.get(completion),
                                    D9WG_RESPONSE_OK, completion.metadata);
                            }
                        }));
                    }
                }
                const fence = this.device.queue &&
                        typeof this.device.queue.onSubmittedWorkDone === "function"
                    ? this.device.queue.onSubmittedWorkDone() : Promise.resolve();
                if (fenceCompletions.length) this.trackReadback(fence.then(() => {
                    for (const completion of fenceCompletions) {
                        if (completion.zeroOcclusion) {
                            const record = completion.record;
                            record.pending = this.trackReadback(record.pending.then(() => {
                                ++this.stats.occlusionQueriesResolved;
                                this.writeQueryResponse(record.query,
                                    completion.requestId, record.value,
                                    record.failed ? D9WG_RESPONSE_FAILED
                                        : D9WG_RESPONSE_OK,
                                    completion.metadata);
                            }));
                            continue;
                        }
                        let value = 0n;
                        switch (completion.query.type) {
                        case D3DQUERYTYPE_EVENT:
                            value = 1n;
                            ++this.stats.eventQueriesResolved;
                            break;
                        case D3DQUERYTYPE_TIMESTAMP:
                            value = BigInt(Math.floor((global.performance &&
                                global.performance.now ?
                                global.performance.now() : Date.now()) * 1000000));
                            ++this.stats.timestampQueriesResolved;
                            break;
                        case D3DQUERYTYPE_TIMESTAMPFREQ:
                            value = 1000000000n;
                            break;
                        case D3DQUERYTYPE_TIMESTAMPDISJOINT:
                        default:
                            value = 0n;
                            break;
                        }
                        this.writeQueryResponse(completion.query,
                            completion.requestId, value, D9WG_RESPONSE_OK,
                            completion.metadata);
                    }
                }, () => {
                    for (const completion of fenceCompletions) {
                        if (completion.zeroOcclusion) {
                            const record = completion.record;
                            record.pending = this.trackReadback(record.pending.then(() => {
                                record.failed = true;
                                ++this.stats.occlusionQueriesResolved;
                                this.writeQueryResponse(record.query,
                                    completion.requestId, record.value,
                                    D9WG_RESPONSE_FAILED,
                                    completion.metadata);
                            }));
                        } else {
                            this.writeQueryResponse(completion.query,
                                completion.requestId, 0,
                                D9WG_RESPONSE_FAILED, completion.metadata);
                        }
                    }
                }));
            }
            if (present) ++this.stats.presents;
            const start = frame.statStart || {};
            this.lastFrameStats = {
                pipelineCreations: this.stats.pipelineCreations -
                    (start.pipelineCreations || 0),
                bindGroupCreations: this.stats.bindGroupCreations -
                    (start.bindGroupCreations || 0),
                queueSubmits: this.stats.queueSubmits -
                    (start.queueSubmits || 0),
                renderPasses: this.stats.renderPasses -
                    (start.renderPasses || 0),
            };
            const transientBuffers = frame.transientBuffers;
            if (transientBuffers && transientBuffers.length) {
                const destroy = () => { for (const b of transientBuffers) b.destroy(); };
                if (this.device.queue && typeof this.device.queue.onSubmittedWorkDone === "function")
                    this.device.queue.onSubmittedWorkDone().then(destroy, destroy);
                else
                    destroy();
            }
            if (present && this.presentingDevice &&
                    typeof this.options.onPresent === "function")
                this.options.onPresent(this.presentingDevice.surface, this.getStats());
            if (present) this.presentingDevice = null;
        }

        // v86gl.d3d9Executor.debug.dumpSmallTextures() -> data: URLs that can
        // be opened straight from the console. Only uncompressed top-level
        // images up to 64x64 are retained (see onUpdateTexture).
        dumpSmallTextures(options) {
            const settings = options || {};
            const out = [];
            for (const [handle, resource] of this.resources) {
                if (!resource.preview) continue;
                if (settings.handle !== undefined && handle !== settings.handle)
                    continue;
                const { width, height, rgba } = resource.preview;
                let url = null;
                let error = null;
                try {
                    // A plain <canvas>, not OffscreenCanvas: only the former
                    // has toDataURL. OffscreenCanvas offers convertToBlob,
                    // which is async and cannot be returned from here -- that
                    // mismatch is why the first version of this helper
                    // reported url: null for every texture.
                    if (typeof document === "undefined")
                        throw new Error("no document to render into");
                    const canvas = document.createElement("canvas");
                    canvas.width = width;
                    canvas.height = height;
                    const context = canvas.getContext("2d");
                    const image = context.createImageData(width, height);
                    image.data.set(rgba.subarray(0, width * height * 4));
                    context.putImageData(image, 0, 0);
                    url = canvas.toDataURL();
                } catch (failure) {
                    error = failure && failure.message ? failure.message
                        : String(failure);
                }
                const entry = { handle, format: resource.format,
                    formatName: TEXTURE_FORMAT_NAMES[resource.format] ||
                        ("0x" + (resource.format >>> 0).toString(16)),
                    size: width + "x" + height,
                    declaredLevels: resource.levelCount,
                    uploadedLevels: resource.uploadedLevels
                        ? [...resource.uploadedLevels].sort((a, b) => a - b) : null,
                    url, error };
                out.push(entry);
                // Rendering them inline is the point of the helper: a data URL
                // in a console row is unreadable, an actual picture answers
                // "is the texture data wrong?" at a glance.
                if (settings.log !== false && url) {
                    const scale = Math.max(1, Math.round(64 / Math.max(width, height)));
                    console.log("%c ", "font-size:0;padding:" +
                        (height * scale / 2) + "px " + (width * scale / 2) +
                        "px;background:url(" + url +
                        ") no-repeat center/contain;image-rendering:pixelated",
                        handle, entry.formatName, entry.size);
                }
            }
            return out;
        }

        // Every distinct pipeline state actually in use, with the raw D3D9
        // render-state values behind it. Reading the real mix beats guessing
        // which blend/depth/cull combination a scene is built from.
        // Prints every translated shader the session has created: its
        // reflection (which declaration semantics it reads, which varyings it
        // writes) and, optionally, the generated WGSL. Reading the shader is
        // the only way to settle questions the pipeline cannot answer -- a
        // varying that is written but written with a constant looks exactly
        // like one that is routed correctly, from the outside.
        // Drops every translated shader, in memory and in storage, so the next
        // draw retranslates from the guest's bytecode. The revision guard in
        // D3D9ShaderCache makes this unnecessary going forward, but a cache
        // written before that guard existed carries no revision to reject it
        // by, and there is no way to age it out other than to throw it away.
        async clearShaderCache() {
            this.shaderCache = new shaderPipeline.D3D9ShaderCache();
            this.moduleCache.clear();
            this.shaderCacheDirty = false;
            const storage = this.shaderCacheStorage;
            if (storage && typeof storage.save === "function") {
                try {
                    await storage.save(this.shaderCacheStorageKey,
                        { version: 1, revision: shaderPipeline.TRANSLATOR_REVISION,
                          entries: [] });
                } catch (error) {
                    return "cleared in memory; storage write failed: " + error;
                }
            }
            return "shader cache cleared -- reload to retranslate";
        }

        dumpShaders(options) {
            options = options || {};
            const rows = [];
            for (const [handle, resource] of this.resources) {
                if (resource.kind !== RESOURCE_VERTEX_SHADER &&
                        resource.kind !== RESOURCE_PIXEL_SHADER) continue;
                const kind = resource.kind === RESOURCE_VERTEX_SHADER
                    ? "vertex" : "pixel";
                const translated = resource.translated;
                const reflection = translated && translated.reflection;
                rows.push({
                    handle, kind,
                    hash: [resource.hashHigh, resource.hashLow]
                        .map(value => (value >>> 0).toString(16)
                            .padStart(8, "0")).join(""),
                    ok: !!(translated && translated.ok),
                    error: translated && translated.error,
                    version: reflection ? reflection.version.major + "." +
                        reflection.version.minor : null,
                    // usage*16+usageIndex is how programFor matches a
                    // declaration element to a shader input, so print the
                    // semantics rather than the raw register numbers.
                    inputs: reflection ? reflection.inputs.map(input =>
                        "v" + input.register + "=usage" + input.usage +
                        "[" + input.usageIndex + "]") : null,
                    writtenVaryings: reflection ? reflection.writtenVaryings : null,
                    samplers: reflection
                        ? reflection.samplers.map(s => s.index) : null,
                    warnings: reflection ? reflection.warnings : null,
                });
            }
            if (options.log !== false) {
                for (const row of rows) console.log("[d3d9-shader]", row);
            }
            if (options.wgsl) {
                for (const [handle, resource] of this.resources) {
                    if (resource.kind !== RESOURCE_VERTEX_SHADER &&
                            resource.kind !== RESOURCE_PIXEL_SHADER) continue;
                    if (options.handle && handle !== options.handle) continue;
                    if (!resource.translated || !resource.translated.ok) continue;
                    console.log("[d3d9-shader] handle " + handle + " WGSL:\n" +
                        resource.translated.wgsl);
                }
            }
            return rows;
        }

        dumpPipelineStates() {
            const out = [];
            for (const [key, pipeline] of this.pipelineCache) {
                const diagnostic = pipeline._d9wgDiagnostic;
                if (diagnostic) {
                    out.push({
                        ...diagnostic,
                        vertexBuffers: diagnostic.vertexBuffers.map(layout => ({
                            ...layout,
                            attributes: layout.attributes.map(attribute =>
                                ({ ...attribute })),
                        })),
                        samplers: diagnostic.samplers.slice(),
                        state: JSON.parse(JSON.stringify(diagnostic.state)),
                        draws: pipeline._d9wgDrawCount || 0,
                    });
                    continue;
                }
                // Compatibility for a pipeline created before structured
                // diagnostics existed. Do not try to split the key: a
                // fixed-function fragment signature legitimately contains
                // "|", so its fields cannot be recovered unambiguously.
                out.push({ key, state: null,
                    draws: pipeline._d9wgDrawCount || 0 });
            }
            return out;
        }

        textureDiagnostic(handle) {
            const resource = handle ? this.resources.get(handle) : null;
            if (!resource) return { handle: handle || 0, live: false };
            const byteSummary = data => {
                const step = Math.max(1, Math.ceil(data.length / 65536));
                let sampled = 0, nonZero = 0, minimum = 255, maximum = 0;
                let hash = 2166136261 >>> 0;
                for (let index = 0; index < data.length; index += step) {
                    const value = data[index];
                    ++sampled;
                    if (value) ++nonZero;
                    minimum = Math.min(minimum, value);
                    maximum = Math.max(maximum, value);
                    hash = Math.imul(hash ^ value, 16777619) >>> 0;
                }
                return { bytes: data.length, sampled, nonZero,
                    minimum: sampled ? minimum : null,
                    maximum: sampled ? maximum : null,
                    hash: "0x" + hash.toString(16).padStart(8, "0") };
            };
            const shadowLevels = [];
            if (resource.textureShadows) {
                for (const [level, shadow] of resource.textureShadows) {
                    shadowLevels.push({ level, width: shadow.width,
                        height: shadow.height, depth: shadow.depth,
                        compressed: !!shadow.compressed,
                        data: byteSummary(shadow.data) });
                }
            }
            return {
                handle, live: true, kind: resource.kind,
                type: resource.textureType || "2d",
                format: resource.format,
                formatName: TEXTURE_FORMAT_NAMES[resource.format] || null,
                gpuFormat: resource.gpuFormat || null,
                width: resource.width, height: resource.height,
                depth: resource.depth || 1,
                levels: resource.levelCount,
                uploadedLevels: resource.uploadedLevels
                    ? [...resource.uploadedLevels].sort((a, b) => a - b) : null,
                shadowLevels,
            };
        }

        drawDiagnostic(reference, path) {
            if (!reference) return null;
            const { which, state, elements, geometry, program, pipelineState,
                targets, pipeline } = reference;
            const viewport = { ...state.viewport };
            const scissorEnabled =
                (state.renderStates.get(D3DRS_SCISSORTESTENABLE) || 0) !== 0 &&
                !!state.scissorRect;
            const scissor = scissorEnabled ? { ...state.scissorRect } : null;
            const clip = intersectRects(viewport, scissor,
                targets.width, targets.height);
            const streams = [];
            for (const [index, binding] of geometry.streams) {
                const resource = binding.resource || null;
                const shadow = resource && resource.shadow;
                const start = Math.max(0, binding.offset || 0);
                const preview = shadow
                    ? shadow.subarray(start,
                        Math.min(shadow.length, start + 64)) : null;
                streams.push({ index, stride: binding.stride || 0,
                    offset: binding.offset || 0,
                    frequency: binding.frequency === undefined
                        ? 1 : binding.frequency,
                    resourceBytes: resource ? resource.byteCount : null,
                    shadowBytes: shadow ? shadow.length : null,
                    availableVertices: shadow && binding.stride
                        ? Math.max(0, Math.floor((shadow.length - start) /
                            binding.stride)) : null,
                    firstBytes: preview ? [...preview].map(value =>
                        value.toString(16).padStart(2, "0")).join("") : null,
                });
            }
            let index = null;
            if (geometry.indexInfo) {
                const info = geometry.indexInfo;
                const resource = geometry.indexResource ||
                    this.resources.get(state.indexBufferHandle);
                const shadow = resource && resource.shadow;
                const bytesPerIndex = info.format === "uint32" ? 4 : 2;
                const scanCount = Math.min(info.count || 0, 4096);
                const samples = [];
                let minimum = Infinity, maximum = -Infinity, scanned = 0;
                if (shadow) {
                    const view = new DataView(shadow.buffer,
                        shadow.byteOffset, shadow.byteLength);
                    for (let item = 0; item < scanCount; ++item) {
                        const byteOffset = (info.offset || 0) +
                            ((info.firstIndex || 0) + item) * bytesPerIndex;
                        if (byteOffset + bytesPerIndex > shadow.length) break;
                        const value = bytesPerIndex === 4
                            ? view.getUint32(byteOffset, true)
                            : view.getUint16(byteOffset, true);
                        ++scanned;
                        if (samples.length < 24) samples.push(value);
                        minimum = Math.min(minimum, value);
                        maximum = Math.max(maximum, value);
                    }
                }
                index = { format: info.format, count: info.count,
                    firstIndex: info.firstIndex, baseVertex: info.baseVertex,
                    bufferOffset: info.offset || 0,
                    resourceBytes: resource ? resource.byteCount : null,
                    scanned,
                    minimum: Number.isFinite(minimum) ? minimum : null,
                    maximum: Number.isFinite(maximum) ? maximum : null,
                    samples };
            }
            const textureHandles = [...new Set(program.samplerIndices.map(
                sampler => state.textures.get(sampler) || 0))];
            return {
                path, which,
                shaders: { vertex: state.vertexShaderHandle || 0,
                    pixel: state.pixelShaderHandle || 0 },
                program: { vertex: program.vertexKey,
                    fragment: program.fragmentKey,
                    fixedPosition: program.fixedFunctionSignature
                        ? program.fixedFunctionSignature.positionType : null,
                    fixedTexCoordSets: program.fixedFunctionSignature
                        ? program.fixedFunctionSignature.texCoordSets.slice() : null,
                    samplers: program.samplerIndices.slice() },
                viewport, scissor, effectiveClip: clip,
                target: { width: targets.width, height: targets.height,
                    formats: targets.formats.slice(),
                    hasDepth: targets.hasDepth },
                pipelineState: JSON.parse(JSON.stringify(pipelineState)),
                pipelineDraws: pipeline._d9wgDrawCount || 0,
                elements: elements.map(element => ({ ...element })),
                streams, index,
                textures: textureHandles.map(handle =>
                    this.textureDiagnostic(handle)),
            };
        }

        blackScreenReport() {
            const device = this.presentingDevice ||
                this.devices.values().next().value || null;
            const report = {
                stats: this.getStats(),
                debug: {
                    forceSolidAllDraws: !!this.debug.forceSolidAllDraws,
                    shaderMode: this.debug.shaderMode,
                    skipProgrammableDraws:
                        !!this.debug.skipProgrammableDraws,
                    disableCull: !!this.debug.disableCull,
                    disableDepthTest: !!this.debug.disableDepthTest,
                },
                device: device ? {
                    handle: device.handle,
                    viewport: { ...device.viewport },
                    scissorRect: device.scissorRect
                        ? { ...device.scissorRect } : null,
                    shaders: { vertex: device.vertexShaderHandle || 0,
                        pixel: device.pixelShaderHandle || 0 },
                    renderStates: Object.fromEntries(device.renderStates),
                    streams: Array.from(device.streams,
                        ([index, stream]) => ({ index, ...stream })),
                    indexBufferHandle: device.indexBufferHandle,
                } : null,
                pipelines: this.dumpPipelineStates(),
                draws: {
                    fixed: this.drawDiagnostic(this.lastDraws.fixed, "fixed"),
                    programmable: this.drawDiagnostic(
                        this.lastDraws.programmable, "programmable"),
                },
                shaders: this.dumpShaders({ log: false }),
                guestReports: (this.guestReports || []).slice(),
            };
            console.log("[d3d9-webgpu] black-screen report", report);
            return report;
        }

        getStats() {
            // The live surface rect is included because it is what positions
            // the overlay canvas, and a wrong rect is invisible in the picture
            // itself: the frame still looks correct, it is just drawn where
            // the guest does not think the window is -- so clicks land on
            // whatever the guest really has at that pixel.
            this.saveActiveSessionState();
            let devicesLive = 0;
            let resourcesLive = 0;
            for (const session of this.sessionStates.values()) {
                devicesLive += session.devices.size;
                resourcesLive += session.resources.size;
            }
            const device = this.presentingDevice ||
                this.devices.values().next().value || null;
            // The fog parameters as this executor decoded them. "Everything
            // is washed out towards one colour" and "fog is not applied at
            // all" look nothing alike in these numbers, and guessing between
            // them from a screenshot has already cost a round.
            let fog = null;
            if (device) {
                const rs = device.renderStates;
                const asFloat = id => {
                    const raw = rs.get(id);
                    if (raw === undefined) return null;
                    FLOAT_BITS_U32[0] = raw >>> 0;
                    return FLOAT_BITS_F32[0];
                };
                const color = rs.get(D3DRS_FOGCOLOR) || 0;
                fog = {
                    enabled: (rs.get(D3DRS_FOGENABLE) || 0) !== 0,
                    tableMode: rs.get(D3DRS_FOGTABLEMODE) || 0,
                    vertexMode: rs.get(D3DRS_FOGVERTEXMODE) || 0,
                    color: "#" + (color & 0xffffff).toString(16).padStart(6, "0"),
                    // null means the game never set it and the D3D9 default
                    // (start 0, end 1) applies -- which fogs everything past
                    // one unit completely, so a null here with LINEAR mode is
                    // itself the explanation for a uniformly washed-out frame.
                    start: asFloat(D3DRS_FOGSTART),
                    end: asFloat(D3DRS_FOGEND),
                    density: asFloat(D3DRS_FOGDENSITY),
                };
            }
            const shaderCache = this.shaderCache.snapshot();
            return { ...this.stats, activeSession: this.sessionKey,
                sessionsLive: this.sessionStates.size,
                devicesLive, resourcesLive,
                pipelinesCached: this.pipelineCache.size,
                bindGroupsCached: this.bindGroupCache.size,
                samplersCached: this.samplerCache.size,
                mrtAttachmentDraws: this.mrtAttachmentDraws.slice(1),
                lastFrame: { ...this.lastFrameStats },
                shaderCache,
                shaderCachePersistentBackend: this.shaderCacheStorageBackend,
                shaderCacheHits: shaderCache.hits,
                shaderCacheMisses: shaderCache.misses,
                shadersCached: shaderCache.cached,
                shaderWGSLBytesCached: shaderCache.totalWGSLBytes,
                shaderCompileLatencyMs: { ...shaderCache.compileLatencyMs },
                occlusionQueries: { mode: "webgpu-query-set",
                    active: this.activeOcclusion ? 1 : 0,
                    perFrameCapacity: 8192,
                    resolved: this.stats.occlusionQueriesResolved },
                surface: device ? { ...device.surface } : null,
                window: this.windowState ? { ...this.windowState } : null,
                fog };
        }

        // ---- resources ----

        onCreateBuffer(bytes, view, offset) {
            const handle = view.getUint32(offset + 4, true);
            const kind = view.getUint32(offset + 8, true);
            const byteCount = view.getUint32(offset + 12, true);
            const format = view.getUint32(offset + 20, true); // index format, for INDEX kind
            const usage = kind === RESOURCE_BUFFER_INDEX
                ? BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST
                : BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST;
            const alignedSize = Math.max(4, alignUp(byteCount, 4));
            const gpuBuffer = this.device.createBuffer({
                size: alignedSize,
                usage,
            });
            this.resources.set(handle, {
                kind, gpuBuffer, byteCount,
                // CPU mirror of the buffer's full (aligned) content. D3D9's
                // Lock/Unlock byte ranges can start and end anywhere, but
                // WebGPU's writeBuffer requires both the destination offset
                // and the size to be a multiple of 4 -- a 16-bit index
                // buffer partially updated starting at an odd index is a
                // routine, common example that is neither. Applying the
                // update to this plain byte array first (no alignment
                // concerns) and re-uploading only the small 4-byte-aligned
                // super-range that covers it keeps every write legal without
                // ever guessing at or corrupting the untouched bytes on
                // either edge (see applyBufferUpdate()).
                shadow: new Uint8Array(alignedSize),
                indexFormat: format === D3DFMT_INDEX32 ? "uint32" : "uint16",
            });
        }

        onUpdateBuffer(bytes, view, offset, length) {
            const handle = view.getUint32(offset, true);
            const destinationOffset = view.getUint32(offset + 4, true);
            const byteCount = view.getUint32(offset + 8, true);
            const dataOffset = view.getUint32(offset + 12, true);
            const lockFlags = view.getUint32(offset + 16, true);
            const resource = this.resources.get(handle);
            if (!resource || !byteCount) return;
            this.applyBufferUpdate(resource, destinationOffset, bytes, dataOffset,
                byteCount, lockFlags);
        }

        applyBufferUpdate(resource, destinationOffset, bytes, sourceOffset,
                byteCount, lockFlags) {
            lockFlags = lockFlags || 0;
            const shadow = resource.shadow;
            if (destinationOffset >= shadow.length) return;
            if (destinationOffset + byteCount > shadow.length)
                byteCount = shadow.length - destinationOffset;
            if (!byteCount) return;
            const source = new Uint8Array(bytes.buffer, bytes.byteOffset + sourceOffset, byteCount);
            shadow.set(source, destinationOffset);

            // Renaming (below) is what keeps deferred draws honest.
            //
            // Draws are not encoded when they arrive: they are recorded and
            // replayed at Present, because a swapchain texture is only valid
            // inside the task that acquired it (see ensureFrame). Buffer
            // writes, by contrast, take effect in queue order -- so every
            // writeBuffer issued during a frame lands *before* that frame's
            // single submit, and therefore before every draw in it.
            //
            // For the single most common dynamic-geometry idiom that is
            // catastrophic:
            //
            //     Lock(DISCARD); write batch A; DrawPrimitive
            //     Lock(DISCARD); write batch B; DrawPrimitive
            //     Present
            //
            // Both draws end up reading batch B. The first renders real
            // indices against the wrong vertices, which on screen is stray
            // geometry stretching across the frame, different every frame,
            // while static/managed resources look perfect.
            //
            // A real D3D9 driver answers this by *renaming*: DISCARD means
            // "I no longer care about the old contents", and the driver hands
            // back fresh storage while in-flight commands keep the old
            // allocation. Do the same here -- but only when this buffer has
            // actually been read by a draw already recorded in this frame, so
            // the ordinary "upload once, draw many" path allocates nothing.
            //
            // The lock flags decide *which* answer is needed, and getting this
            // distinction right is what keeps the cost sane. War3 renamed ~277
            // times per frame when every mid-frame write was treated the same:
            //
            //   NOOVERWRITE  the application has promised it is only writing
            //                bytes no issued draw reads -- that is precisely
            //                the guarantee this hazard needs, and it is how a
            //                game appends batch after batch into one buffer.
            //                Write in place; renaming here is pure waste.
            //   DISCARD      the old contents are dead, so the replacement
            //                only needs the bytes being written now. The rest
            //                is garbage the application has promised not to
            //                read, so there is nothing to copy forward.
            //   neither      a plain lock keeps the old contents readable, so
            //                the replacement has to carry the whole shadow.
            //                Rare, and the only case that costs a full upload.
            const D3DLOCK_NOOVERWRITE = 0x1000;
            const D3DLOCK_DISCARD = 0x2000;
            if (this.frame && resource.frameReferenced === this.frame.serial &&
                    !(lockFlags & D3DLOCK_NOOVERWRITE)) {
                const replacement = this.device.createBuffer({
                    label: "D3D9 renamed buffer",
                    size: resource.gpuBuffer.size,
                    usage: resource.kind === RESOURCE_BUFFER_INDEX
                        ? BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST
                        : BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
                });
                if (lockFlags & D3DLOCK_DISCARD) {
                    const start = destinationOffset & ~3;
                    const end = Math.min(shadow.length,
                        alignUp(destinationOffset + byteCount, 4));
                    if (end > start)
                        this.device.queue.writeBuffer(replacement, start,
                            shadow.buffer, shadow.byteOffset + start, end - start);
                } else {
                    this.device.queue.writeBuffer(replacement, 0, shadow.buffer,
                        shadow.byteOffset, shadow.length);
                    ++this.stats.bufferFullCopyRenames;
                }
                this.retireGPUObject(resource.gpuBuffer);
                resource.gpuBuffer = replacement;
                resource.frameReferenced = 0;
                ++this.stats.bufferRenames;
                return;
            }
            if (this.frame && resource.frameReferenced === this.frame.serial)
                ++this.stats.bufferNoOverwriteWrites;

            const alignedStart = destinationOffset & ~3;
            const alignedEnd = Math.min(shadow.length,
                alignUp(destinationOffset + byteCount, 4));
            if (alignedEnd <= alignedStart) return;
            this.device.queue.writeBuffer(resource.gpuBuffer, alignedStart,
                shadow.buffer, shadow.byteOffset + alignedStart, alignedEnd - alignedStart);
        }

        // WebGPU requires writeBuffer's size (and destination offset) to be a
        // multiple of 4 bytes; D3D9's Lock/Unlock byte ranges carry no such
        // guarantee (a 16-bit index buffer update is a common example that
        // is not). D9WG command records are always padded to an 8-byte
        // boundary (D9WG_ALIGN8 in d3d9_proxy.c), so up to 3 extra
        // zero-padding bytes past `byteCount` are always safely readable
        // from the same batch -- this rounds the write size up into that
        // slack rather than crashing the whole batch on an unaligned
        // Direct3D-legal update.
        writeBufferAligned(gpuBuffer, dstOffset, bytes, sourceOffset, byteCount) {
            if (!byteCount) return;
            if (dstOffset % 4 !== 0) {
                console.warn("[d3d9-webgpu] dropping a buffer update at a " +
                    "non-4-byte-aligned destination offset", { dstOffset, byteCount });
                return;
            }
            let writeCount = alignUp(byteCount, 4);
            const available = gpuBuffer.size - dstOffset;
            if (writeCount > available) writeCount = available - (available % 4);
            if (writeCount <= 0) return;
            this.device.queue.writeBuffer(gpuBuffer, dstOffset,
                new Uint8Array(bytes.buffer, bytes.byteOffset + sourceOffset, writeCount));
        }

        onDestroyResource(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            const kind = view.getUint32(offset + 4, true);
            if (kind === 0) {
                // Matches the D3D8 guest convention: DESTROY_RESOURCE with
                // resource_kind 0 targets the device handle itself, emitted
                // once from device_release() when the app's last reference
                // drops (see d3d9_proxy.c).
                const state = this.devices.get(handle);
                if (state) {
                    const lastDevice = this.devices.size === 1;
                    if (lastDevice) this.discardFrame();
                    this.retireDeviceState(state, "device");
                    this.devices.delete(handle);
                    if (this.presentingDevice === state)
                        this.presentingDevice = null;
                    if (lastDevice) {
                        this.retireActiveSessionBackBuffer();
                        this.retireGPUObject(this.cursor && this.cursor.texture);
                        this.retireGPUObject(this.cursor && this.cursor.uniform);
                        this.cursor = { texture: null, view: null, width: 0,
                            height: 0, hotspotX: 0, hotspotY: 0, x: 0, y: 0,
                            visible: false, pipeline: null, sampler: null,
                            uniform: null };
                    }
                }
                return;
            }
            const resource = this.resources.get(handle);
            if (!resource) return;
            // Never destroy inline. A frame being recorded may already hold a
            // bind group referencing this texture's view or a pending draw
            // referencing this buffer, and none of it is submitted until
            // Present -- destroying now makes WebGPU reject the whole command
            // buffer ("Destroyed texture ... used in a submit"). Releasing a
            // texture in the same frame it was last drawn with is ordinary
            // application behaviour, not an edge case.
            this.retireResourceState(resource);
            this.resources.delete(handle);
        }

        onCreateTexture2D(bytes, view, offset, length) {
            const handle = view.getUint32(offset + 4, true);
            const width = view.getUint32(offset + 8, true);
            const height = view.getUint32(offset + 12, true);
            let levelCount = view.getUint32(offset + 16, true);
            const format = view.getUint32(offset + 20, true);
            const usage = view.getUint32(offset + 24, true);
            const multisampleType = length >= 40
                ? view.getUint32(offset + 32, true) : D3DMULTISAMPLE_NONE;
            const multisampleQuality = length >= 40
                ? view.getUint32(offset + 36, true) : 0;
            // A render target or depth surface arrives as a CREATE_TEXTURE_2D
            // carrying the usage (see d3d9_protocol.h): the host needs a GPU
            // texture either way, and D3D9 reaches a texture's render target
            // through GetSurfaceLevel as often as through CreateRenderTarget, so
            // one opcode covers both without two host paths for one object.
            // A FOURCC depth format is a depth resource whether or not the
            // app spelled out D3DUSAGE_DEPTHSTENCIL: INTZ in particular is
            // routinely created with usage 0 and then bound as the depth
            // surface, which is exactly the trick it exists for.
            const isDepth = (usage & D3DUSAGE_DEPTHSTENCIL) !== 0 ||
                isFourCCDepthFormat(format);
            const isTarget = (usage & D3DUSAGE_RENDERTARGET) !== 0;
            const ddIndexed = (usage & D9WG_USAGE_DDRAW_INDEXED) !== 0 &&
                isPalettizedFormat(format) && !isDepth;
            const sampleCount = sampleCountForD3D(multisampleType,
                multisampleQuality);
            if (!sampleCount) {
                ++this.stats.texturesRejected;
                this.warnOnce("invalid-texture-msaa-" + multisampleType + "-" +
                        multisampleQuality,
                    "a texture requested an unsupported D3D9 multisample " +
                    "configuration and is rejected instead of silently " +
                    "creating a resource with different sampling semantics",
                    { multisampleType, multisampleQuality });
                return;
            }
            if (sampleCount > 1 && (!isTarget && !isDepth)) {
                ++this.stats.texturesRejected;
                this.warnOnce("msaa-non-attachment-texture",
                    "a multisampled D3D9 texture must be a render target or " +
                    "depth-stencil attachment", { usage, sampleCount });
                return;
            }
            if (sampleCount > 1 && levelCount > 1) {
                ++this.stats.texturesRejected;
                this.warnOnce("msaa-mip-chain",
                    "a multisampled D3D9 texture cannot have multiple mip " +
                    "levels; the resource is rejected", { levelCount,
                        sampleCount });
                return;
            }
            // Every D3D9 depth format collapses onto one real depth target: the
            // guest cannot read any of them back, so only "a depth buffer
            // exists" is observable (same argument as ensureDepthTarget).
            // D3DUSAGE_AUTOGENMIPMAP means the app owns level 0 and the driver
            // owns everything under it. The guest therefore reports one level
            // -- which is what D3D9's GetLevelCount says for such a texture --
            // and the full chain is allocated here, where it is filled.
            const autoGenerateMips = (usage & D3DUSAGE_AUTOGENMIPMAP) !== 0 &&
                !isDepth;
            if (autoGenerateMips)
                levelCount = fullMipLevelCount(width, height);
            const gpuFormat = isDepth ? DEPTH_FORMAT
                : (ddIndexed ? "r8uint" : formatToGPU(format));
            if (!gpuFormat) {
                console.warn("[d3d9-webgpu] unsupported texture format", format);
                return;
            }
            if (isTarget && !isDepth && !isRenderableGPUFormat(gpuFormat)) {
                ++this.stats.texturesRejected;
                this.warnOnce("non-renderable-d3d9-target-" + format,
                    "a texture was marked as a D3D9 render target but its " +
                    "WebGPU storage format cannot be a render attachment; " +
                    "the resource is rejected instead of creating an invalid " +
                    "GPU descriptor", { format, gpuFormat });
                return;
            }
            const srgbFormat = isDepth ? null : srgbSiblingOf(gpuFormat);
            const textureDescriptor = {
                label: isDepth ? "D3D9 depth surface"
                    : (isTarget ? "D3D9 render target" : undefined),
                size: { width, height, depthOrArrayLayers: 1 },
                format: gpuFormat,
                ...(srgbFormat ? { viewFormats: [srgbFormat] } : {}),
                mipLevelCount: Math.max(1, levelCount),
                ...(isDepth && sampleCount > 1 ? { sampleCount } : {}),
                usage: (isDepth
                        ? TEXTURE_USAGE_RENDER_ATTACHMENT |
                          // A D3D9 depth *texture* is the standard hardware
                          // shadow map: rendered into as a depth attachment,
                          // then bound to a sampler so the lighting pass can
                          // compare against it. Leaving the binding usage off
                          // made that second half impossible -- see the
                          // `view` field below.
                          (sampleCount > 1 ? 0 : TEXTURE_USAGE_TEXTURE_BINDING)
                        : TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_COPY_SRC |
                          TEXTURE_USAGE_TEXTURE_BINDING) |
                    // A blit writes through a render pass, so anything that can
                    // be a StretchRect destination needs the attachment usage.
                    // BCn cannot be an attachment at all, which is also why a
                    // StretchRect into a compressed texture stays unsupported.
                    ((!isDepth && isRenderableGPUFormat(gpuFormat) &&
                        (isTarget || autoGenerateMips ||
                            !isCompressedFormat(format)))
                        ? TEXTURE_USAGE_RENDER_ATTACHMENT : 0),
            };
            const gpuTexture = this.createTextureOrNull(textureDescriptor, format);
            if (!gpuTexture) return;
            // WebGPU multisampled colour textures cannot be sampled or copied.
            // Keep the ordinary texture as D3D9's resolved surface and render
            // through a transiently persistent multisampled attachment which
            // resolves into it at every pass boundary. Depth has no resolve in
            // either API, so its primary texture itself is multisampled.
            let msaaTexture = null;
            if (sampleCount > 1 && isTarget && !isDepth) {
                const msaaDescriptor = {
                    label: "D3D9 multisampled render target",
                    size: { width, height, depthOrArrayLayers: 1 },
                    format: gpuFormat,
                    ...(srgbFormat ? { viewFormats: [srgbFormat] } : {}),
                    mipLevelCount: 1,
                    sampleCount,
                    usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
                };
                msaaTexture = this.createTextureOrNull(msaaDescriptor, format);
                if (!msaaTexture) {
                    if (typeof gpuTexture.destroy === "function")
                        gpuTexture.destroy();
                    return;
                }
            }
            ++this.stats.texturesCreated;
            if (isTarget) ++this.stats.renderTargetsCreated;
            // No sampler is attached to the texture: since M2, sampling
            // parameters come from the device's per-stage sampler state
            // through samplerFor(), so the same texture bound to two stages
            // with different filtering behaves the way D3D9 says it should.
            this.resources.set(handle, {
                kind: RESOURCE_TEXTURE_2D, textureType: "2d",
                deviceHandle: view.getUint32(offset, true),
                gpuTexture, msaaTexture, gpuFormat, srgbFormat, format, usage,
                width, height, sampleCount,
                multisampleType, multisampleQuality,
                gpuBytesPerTexel: ddIndexed ? 1 : gpuBytesPerTexel(format),
                ddIndexed,
                textureDescriptor,
                levelCount: Math.max(1, levelCount),
                // A subresource the guest never initializes has undefined
                // contents.  Initialization can arrive either as a CPU upload
                // or as a GPU write such as DirectDraw Blt/StretchRect.
                // Sampling one is not "slightly blurry" -- it is whatever was
                // in that memory, which reads as a completely wrong texture.
                // M1 could not hit this the same way because it sampled with
                // one hardcoded sampler; M2 honours D3DSAMP_MIPFILTER, so a
                // game asking for mip filtering now reaches levels that were
                // never written.
                // A render target's or depth surface's levels are written by
                // the GPU, never uploaded, so tracking them would make the
                // incomplete-mip-chain warning fire on every draw that samples
                // a perfectly valid target.
                // A generated chain is written by the GPU, never uploaded, so
                // tracking it would make the incomplete-mip warning fire on
                // every draw that samples a perfectly valid texture.
                uploadedLevels: (isTarget || isDepth || autoGenerateMips)
                    ? null : new Set(),
                autoGenerateMips,
                isDepth,
                // D3D9 has two ways to read a depth texture and they are not
                // interchangeable. A D16/D24X8/D32 texture bound to a sampler
                // is a hardware shadow map: the driver compares and returns
                // filtered visibility. A DF16/DF24/INTZ texture returns the
                // stored depth itself, which is precisely why an app picks one.
                // Sampling either as though it were the other produces an
                // image that looks deliberate and is wrong.
                depthReadsRaw: isDepth && isFourCCDepthFormat(format),
                // A null view here used to be the modelling assumption that a
                // depth surface is only ever an attachment -- nothing can read
                // its pixels back, so "a depth buffer exists" looked like the
                // whole of its observable behaviour. Shadow mapping is the
                // counter-example, and the failure was not a wrong image: the
                // null reached createBindGroup as a binding resource and threw
                // a TypeError out of the batch, taking every command after it
                // in that batch with it.
                //
                // depth24plus-stencil8 can only be sampled one aspect at a
                // time, and the stencil aspect would need its own uint layout
                // entry that no D3D9 shader can ask for.
                view: !isDepth ? gpuTexture.createView()
                    : (sampleCount > 1 ? null
                        : gpuTexture.createView({ aspect: "depth-only" })),
            });
        }

        // Whether the texture bound to a stage is a hardware shadow map: a
        // D3D9 depth-format texture this backend can actually sample. The
        // `view` test is what keeps the multisampled case out -- those are
        // attachment-only and would need a `multisampled: true` layout entry
        // no D3D9 shader can express.
        isDepthSampled(handle) {
            const resource = handle && this.resources.get(handle);
            return !!(resource && resource.isDepth && resource.view);
        }

        // "depth-compare" for a hardware shadow map, "depth-fetch" for the ATI
        // FOURCC formats that hand back the stored value. Both are texture_depth
        // in WGSL and neither is a texture_2d<f32>, but they need different
        // sampler types, so the distinction has to survive all the way into the
        // bind group layout.
        depthSampleModeFor(handle) {
            const resource = handle && this.resources.get(handle);
            if (!resource || !resource.isDepth || !resource.view) return null;
            return resource.depthReadsRaw ? "depth-fetch" : "depth-compare";
        }

        textureShadowFor(resource, level, layer, compressed) {
            if (!resource.textureShadows) resource.textureShadows = new Map();
            const key = level + ":" + (resource.textureType === "3d" ? 0 : layer);
            let shadow = resource.textureShadows.get(key);
            if (shadow) return shadow;
            const width = Math.max(1, resource.width >> level);
            const height = Math.max(1, resource.height >> level);
            const depth = resource.textureType === "3d"
                ? Math.max(1, resource.depth >> level) : 1;
            let bytesPerRow;
            let rowsPerImage;
            if (compressed) {
                const blockBytes = compressedBlockBytes(resource.format);
                bytesPerRow = Math.ceil(width / 4) * blockBytes;
                rowsPerImage = Math.ceil(height / 4);
            } else {
                bytesPerRow = width * resource.gpuBytesPerTexel;
                rowsPerImage = height;
            }
            shadow = { level, layer: resource.textureType === "3d" ? 0 : layer,
                width, height, depth, bytesPerRow, rowsPerImage,
                compressed, data: new Uint8Array(bytesPerRow * rowsPerImage * depth) };
            resource.textureShadows.set(key, shadow);
            return shadow;
        }

        updateTextureShadow(resource, level, layer, x, y, width, height,
                payload, sourceBytesPerRow, compressed, depth = 1,
                sourceSlicePitch = 0) {
            const shadow = this.textureShadowFor(resource, level, layer,
                compressed);
            const blockBytes = compressed
                ? compressedBlockBytes(resource.format)
                : resource.gpuBytesPerTexel;
            const destinationX = compressed ? Math.floor(x / 4) : x;
            const destinationY = compressed ? Math.floor(y / 4) : y;
            const rowBytes = compressed
                ? Math.ceil(width / 4) * blockBytes
                : width * resource.gpuBytesPerTexel;
            const rowCount = compressed ? Math.ceil(height / 4) : height;
            const sourceSlice = sourceSlicePitch || sourceBytesPerRow * rowCount;
            for (let slice = 0; slice < depth; ++slice) {
                for (let row = 0; row < rowCount; ++row) {
                    const destinationOffset = resource.textureType === "3d"
                        ? (layer + slice) * shadow.bytesPerRow *
                            shadow.rowsPerImage +
                            (destinationY + row) * shadow.bytesPerRow +
                            destinationX * blockBytes
                        : (destinationY + row) * shadow.bytesPerRow +
                            destinationX * blockBytes;
                    const sourceOffset = slice * sourceSlice +
                        row * sourceBytesPerRow;
                    const available = Math.max(0,
                        Math.min(rowBytes, shadow.data.length - destinationOffset,
                            payload.length - sourceOffset));
                    if (available)
                        shadow.data.set(payload.subarray(sourceOffset,
                            sourceOffset + available), destinationOffset);
                }
            }
        }

        renameTextureForUpdate(resource) {
            if (!resource.textureDescriptor ||
                    (resource.usage & (D3DUSAGE_RENDERTARGET |
                        D3DUSAGE_DEPTHSTENCIL)) !== 0)
                return false;
            let replacement;
            try {
                replacement = this.device.createTexture({
                    ...resource.textureDescriptor,
                    label: "D3D9 renamed texture",
                });
            } catch (error) {
                this.warnOnce("texture-rename-failed",
                    "a texture updated after an earlier draw could not be " +
                    "renamed; that earlier draw may see the newer pixels", {
                        format: resource.format,
                        size: resource.width + "x" + resource.height,
                        message: error && error.message,
                    });
                return false;
            }
            if (resource.textureShadows) {
                for (const shadow of resource.textureShadows.values()) {
                    this.device.queue.writeTexture({ texture: replacement,
                        mipLevel: shadow.level,
                        origin: { x: 0, y: 0, z: shadow.layer } }, shadow.data,
                        { bytesPerRow: shadow.bytesPerRow,
                            rowsPerImage: shadow.rowsPerImage },
                        { width: blockAlignedCopyExtent(shadow.width,
                                shadow.compressed),
                            height: blockAlignedCopyExtent(shadow.height,
                                shadow.compressed),
                            depthOrArrayLayers: shadow.depth || 1 });
                    this.stats.textureFullCopyRenameBytes += shadow.data.length;
                }
            }
            const oldTexture = resource.gpuTexture;
            resource.gpuTexture = replacement;
            resource.view = replacement.createView({ dimension:
                resource.textureType === "cube" ? "cube"
                    : resource.textureType === "3d" ? "3d" : "2d" });
            resource.srgbView = null;
            resource.blitViews = null;
            resource.targetViews = null;
            resource.frameReferenced = 0;
            this.retireGPUObject(oldTexture);
            ++this.stats.textureRenames;
            return true;
        }

        onUpdateTexture(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            const level = view.getUint32(offset + 4, true);
            const x = view.getUint32(offset + 8, true);
            const y = view.getUint32(offset + 12, true);
            // D9WGUpdateTexture.z is the cube face for a cube texture and the
            // slice for a volume texture; both land on the same WebGPU array
            // layer, which is why one field and one opcode serve both.
            const z = view.getUint32(offset + 16, true);
            const width = view.getUint32(offset + 20, true);
            const height = view.getUint32(offset + 24, true);
            const depth = Math.max(1, view.getUint32(offset + 28, true));
            const rowPitch = view.getUint32(offset + 32, true);
            const slicePitch = view.getUint32(offset + 36, true) ||
                rowPitch * height;
            const dataBytes = view.getUint32(offset + 40, true);
            const dataOffset = view.getUint32(offset + 44, true);
            const resource = this.resources.get(handle);
            if (!resource || !resource.gpuTexture) return;
            const source = new Uint8Array(bytes.buffer, bytes.byteOffset + dataOffset, dataBytes);
            const compressed = isCompressedFormat(resource.format);
            // Bind groups are built eagerly and retain the old view. Renaming
            // here therefore preserves pixels for draws already recorded in
            // this frame while later draws bind the replacement texture.
            if (this.frame && resource.frameReferenced === this.frame.serial) {
                ++this.stats.textureUpdateHazards;
                this.renameTextureForUpdate(resource);
            }
            let payload = source;
            let bytesPerRow = rowPitch;
            if (resource.ddIndexed) {
                // An indexed DirectDraw surface stores what the app wrote: the
                // bytes are the texels, and nothing about them changes when the
                // palette does. Only the row padding comes off, because
                // writeTexture wants the rows tightly packed.
                const packed = new Uint8Array(width * height * depth);
                for (let slice = 0; slice < depth; ++slice) {
                    for (let row = 0; row < height; ++row) {
                        const from = slice * slicePitch + row * rowPitch;
                        packed.set(source.subarray(from, from + width),
                            slice * width * height + row * width);
                    }
                }
                this.updateTextureShadow(resource, level, z, x, y, width,
                    height, packed, width, false, depth, width * height);
                ++this.stats.textureUploads;
                this.stats.textureBytesUploaded += packed.length;
                resource.ddContentSerial = (resource.ddContentSerial || 0) + 1;
                this.markTextureSubresourceWritten(resource, level, z);
                // Keep the primary r8uint texture current for indexed-to-
                // indexed DirectDraw blits.  The RGBA sampling companion is
                // derived lazily from the same shadow by ddIndexedSampleViewFor.
                this.device.queue.writeTexture(
                    { texture: resource.gpuTexture, mipLevel: level,
                        origin: { x, y, z } }, packed,
                    { bytesPerRow: width, rowsPerImage: height },
                    { width, height, depthOrArrayLayers: depth });
                return;
            }
            if (isPalettizedFormat(resource.format)) {
                // The indices, not the colours, are what the app uploaded. A
                // palette swap has to repaint this texture without any new
                // traffic -- that is the whole point of a palettized format --
                // so the source bytes are kept and re-expanded on demand.
                this.rememberPalettizedUpload(resource, {
                    level, z, x, y, width, height, depth, rowPitch, slicePitch,
                    source: source.slice(),
                });
            }
            if (!compressed) {
                const gpuBpp = resource.gpuBytesPerTexel;
                // Expand to the tightly packed WebGPU representation chosen
                // by formatToGPU(): RGBA8 UNORM/SNORM or RGBA16F.
                const expandedSlicePitch = width * height * gpuBpp;
                const expanded = new Uint8Array(expandedSlicePitch * depth);
                const palette = isPalettizedFormat(resource.format)
                    ? this.currentPaletteFor(handle) : null;
                for (let slice = 0; slice < depth; ++slice) {
                    for (let row = 0; row < height; ++row) {
                        expandRowToGPU(resource.format, source,
                            slice * slicePitch + row * rowPitch, width,
                            expanded, slice * expandedSlicePitch +
                                row * width * gpuBpp, palette);
                    }
                }
                payload = expanded;
                bytesPerRow = width * gpuBpp;
            }
            this.updateTextureShadow(resource, level, z, x, y, width, height,
                payload, bytesPerRow, compressed, depth,
                bytesPerRow * (compressed ? Math.ceil(height / 4) : height));
            ++this.stats.textureUploads;
            this.stats.textureBytesUploaded += payload.length;
            // Only level 0 is the app's on an autogen texture, so only level 0
            // can invalidate what the driver generated from it.
            this.markTextureSubresourceWritten(resource, level, z);
            // Retain a CPU copy of small top-level images. This is the one
            // piece of evidence that separates "the texture data we uploaded
            // is wrong" from "the data is right but we sample it wrong", and
            // guessing between those two has already cost several rounds.
            // Bounded to sprite-sized textures so it cannot grow without
            // limit -- cursors and UI glyphs are exactly this size.
            // 64x64 was too small a net: a game's cursor and UI glyphs
            // usually live in a larger atlas, so the one texture worth looking
            // at was the one never captured. 256x256 covers those at a bounded
            // total cost (previewBudget below).
            if (!compressed && resource.gpuFormat === "rgba8unorm" &&
                    resource.textureType !== "3d" && depth === 1 &&
                    level === 0 && z === 0 && width <= 256 &&
                    height <= 256 && x === 0 && y === 0) {
                const previewBytes = width * height * 4;
                if (!resource.preview) {
                    if (this.previewBudget === undefined)
                        this.previewBudget = 16 * 1024 * 1024;
                    if (this.previewBudget >= previewBytes) {
                        this.previewBudget -= previewBytes;
                        resource.preview = {
                            width, height, rgba: payload.slice()
                        };
                    } else {
                        // The preview is diagnostics only. Returning here used
                        // to drop the real queue.writeTexture below once War3
                        // had loaded 16 MiB of menu atlases. Textures first
                        // touched in battle (fog/minimap/command icons/software
                        // cursor) consequently stayed black or transparent.
                        ++this.stats.texturePreviewsSkipped;
                    }
                } else {
                    resource.preview = { width, height, rgba: payload.slice() };
                }
            }
            // rowsPerImage counts *block* rows for a block-compressed format,
            // not pixel rows -- BCn blocks are 4x4, so a DXT upload that
            // passes the pixel height describes an image four times taller
            // than the data actually is.
            this.device.queue.writeTexture(
                { texture: resource.gpuTexture, mipLevel: level, origin: { x, y, z } },
                payload,
                { bytesPerRow, rowsPerImage: compressed ? Math.ceil(height / 4) : height },
                { width: blockAlignedCopyExtent(width, compressed),
                    height: blockAlignedCopyExtent(height, compressed),
                    depthOrArrayLayers: depth });
        }

        // ---- render targets, cube textures and blits (M3/M4) ----

        // A cube texture is a six-layer 2D WebGPU texture viewed as "cube".
        // Both views are kept: bind groups need the cube view, and a blit or an
        // upload addresses a single face, which only the layered 2D form can do.
        onCreateTextureCube(bytes, view, offset) {
            const handle = view.getUint32(offset + 4, true);
            const edge = view.getUint32(offset + 8, true);
            const levelCount = Math.max(1, view.getUint32(offset + 12, true));
            const format = view.getUint32(offset + 16, true);
            const usage = view.getUint32(offset + 20, true);
            const ddIndexed = (usage & D9WG_USAGE_DDRAW_INDEXED) !== 0 &&
                isPalettizedFormat(format);
            const gpuFormat = ddIndexed ? "r8uint" : formatToGPU(format);
            if (!gpuFormat) {
                console.warn("[d3d9-webgpu] unsupported cube texture format", format);
                return;
            }
            const autoGenerateMips = (usage & D3DUSAGE_AUTOGENMIPMAP) !== 0;
            const srgbFormat = srgbSiblingOf(gpuFormat);
            const textureDescriptor = {
                label: "D3D9 cube " + edge,
                size: { width: edge, height: edge, depthOrArrayLayers: 6 },
                format: gpuFormat,
                ...(srgbFormat ? { viewFormats: [srgbFormat] } : {}),
                mipLevelCount: autoGenerateMips
                    ? fullMipLevelCount(edge, edge) : levelCount,
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_TEXTURE_BINDING |
                    // A dynamic environment map is a cube render target: the
                    // app renders the scene six times, once per face, through
                    // the surfaces GetCubeMapSurface hands out.
                    ((((usage & D3DUSAGE_RENDERTARGET) || autoGenerateMips) &&
                        isRenderableGPUFormat(gpuFormat))
                        ? TEXTURE_USAGE_RENDER_ATTACHMENT : 0),
            };
            const gpuTexture = this.createTextureOrNull(textureDescriptor, format);
            if (!gpuTexture) return;
            ++this.stats.texturesCreated;
            ++this.stats.cubeTexturesCreated;
            this.resources.set(handle, {
                kind: RESOURCE_TEXTURE_CUBE, textureType: "cube",
                deviceHandle: view.getUint32(offset, true),
                gpuTexture, gpuFormat, srgbFormat,
                format, usage, width: edge, height: edge, layerCount: 6,
                gpuBytesPerTexel: ddIndexed ? 1 : gpuBytesPerTexel(format),
                ddIndexed,
                textureDescriptor,
                levelCount: textureDescriptor.mipLevelCount,
                // Keyed by level*6+face, so the incomplete-mip warning counts a
                // cube's faces independently -- a game that fills face 0's whole
                // chain and leaves face 5 empty is a real bug this would hide if
                // the levels were tracked per-level only.
                uploadedLevels: autoGenerateMips ? null : new Set(),
                autoGenerateMips,
                view: gpuTexture.createView({ dimension: "cube" }),
            });
        }

        onCreateTextureVolume(bytes, view, offset, length) {
            if (length < 40) return;
            const handle = view.getUint32(offset + 4, true);
            const width = view.getUint32(offset + 8, true);
            const height = view.getUint32(offset + 12, true);
            const depth = view.getUint32(offset + 16, true);
            const levelCount = Math.max(1, view.getUint32(offset + 20, true));
            const format = view.getUint32(offset + 24, true);
            const usage = view.getUint32(offset + 28, true);
            const gpuFormat = formatToGPU(format);
            if (!gpuFormat || isCompressedFormat(format) ||
                    (isRenderableGPUFormat(gpuFormat) &&
                        (usage & D3DUSAGE_RENDERTARGET))) {
                ++this.stats.texturesRejected;
                return;
            }
            const textureDescriptor = {
                label: "D3D9 volume texture",
                size: { width, height, depthOrArrayLayers: depth },
                dimension: "3d",
                format: gpuFormat,
                mipLevelCount: levelCount,
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_TEXTURE_BINDING,
            };
            const gpuTexture = this.createTextureOrNull(textureDescriptor,
                format);
            if (!gpuTexture) return;
            ++this.stats.texturesCreated;
            ++this.stats.volumeTexturesCreated;
            this.resources.set(handle, {
                kind: RESOURCE_TEXTURE_VOLUME, textureType: "3d",
                deviceHandle: view.getUint32(offset, true),
                gpuTexture, gpuFormat, format, usage,
                width, height, depth,
                gpuBytesPerTexel: gpuBytesPerTexel(format),
                textureDescriptor, levelCount,
                uploadedLevels: new Set(),
                view: gpuTexture.createView({ dimension: "3d" }),
            });
        }

        // createTexture throws for a format the device does not support, and an
        // exception here propagates out of the batch and discards the whole
        // frame -- one unsupported texture would blank the screen instead of
        // costing one texture. Contained, counted, and named once instead: the
        // draws that bind it fall back to the 1x1 white stand-in, which is
        // visibly wrong in a way that points at the right place.
        createTextureOrNull(descriptor, d3dFormat) {
            try {
                return this.device.createTexture(descriptor);
            } catch (error) {
                ++this.stats.texturesRejected;
                this.warnOnce("createtexture-" + descriptor.format,
                    "the WebGPU device refused a texture format the D3D9 " +
                    "format table claims to support; every draw sampling it " +
                    "gets the 1x1 white fallback instead", {
                        d3dFormat, gpuFormat: descriptor.format,
                        size: descriptor.size,
                        bcSupported: this.deviceFeatures &&
                            this.deviceFeatures.bc,
                        message: error && error.message,
                    });
                return null;
            }
        }

        onSetScissorRect(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            const left = view.getInt32(offset + 4, true);
            const top = view.getInt32(offset + 8, true);
            const right = view.getInt32(offset + 12, true);
            const bottom = view.getInt32(offset + 16, true);
            state.scissorRect = { x: Math.max(0, left), y: Math.max(0, top),
                width: Math.max(0, right - left), height: Math.max(0, bottom - top) };
        }

        onSetRenderTarget(bytes, view, offset, length) {
            const state = this.deviceState(view.getUint32(offset, true));
            const index = view.getUint32(offset + 4, true);
            if (index >= MAX_RENDER_TARGETS) return;
            state.renderTargets[index] = view.getUint32(offset + 8, true);
            state.renderTargetLevels[index] = view.getUint32(offset + 12, true);
            // Protocol 1.4 added the cube face. Length-gated so a 1.3 payload
            // still decodes as "face 0", which is what a 2D target always is.
            state.renderTargetFaces[index] = length >= 20
                ? view.getUint32(offset + 16, true) : 0;
            ++this.stats.renderTargetBinds;
        }

        // ---- texture palettes ----
        //
        // A D3D9 palette is device state consulted when a texel is sampled,
        // not a property baked into the texture: the same P8 surface takes on
        // different colours as the app switches palettes, with no upload in
        // between. WebGPU has no palettized format, so the expansion happens on
        // the CPU -- which means the indices have to be kept and replayed
        // whenever the table or the selection changes.

        paletteFor(deviceHandle, index) {
            if (!this.palettes) this.palettes = new Map();
            return this.palettes.get(deviceHandle + ":" + index) || null;
        }

        currentPaletteFor(resourceHandle) {
            const resource = this.resources.get(resourceHandle);
            const deviceHandle = resource ? resource.deviceHandle : 0;
            const state = this.devices.get(deviceHandle);
            if (!state || state.currentPalette === null ||
                    state.currentPalette === undefined)
                return null;
            return this.paletteFor(deviceHandle, state.currentPalette);
        }

        rememberPalettizedUpload(resource, upload) {
            if (!resource.palettizedUploads) resource.palettizedUploads = [];
            // Keyed by subresource *and* sub-rectangle: a partial LockRect
            // update of one region must not discard the rest of the level.
            const key = upload.level + ":" + upload.z + ":" + upload.x + ":" +
                upload.y + ":" + upload.width + ":" + upload.height;
            const existing = resource.palettizedUploads
                .findIndex(item => item.key === key);
            upload.key = key;
            if (existing >= 0) resource.palettizedUploads[existing] = upload;
            else resource.palettizedUploads.push(upload);
        }

        // Re-expands every palettized texture on the device through the palette
        // now in force. Cheap in the way that matters: palettized content is
        // one byte per texel by definition, and a palette swap is rare.
        repaintPalettizedTextures(deviceHandle) {
            let repainted = 0;
            for (const [handle, resource] of this.resources) {
                if (!resource || resource.deviceHandle !== deviceHandle) continue;
                if (!isPalettizedFormat(resource.format)) continue;
                if (!resource.palettizedUploads) continue;
                const palette = this.currentPaletteFor(handle);
                for (const upload of resource.palettizedUploads) {
                    this.uploadPalettizedRegion(resource, upload, palette);
                    ++repainted;
                }
            }
            this.stats.palettizedRepaints += repainted;
        }

        uploadPalettizedRegion(resource, upload, palette) {
            const gpuBpp = resource.gpuBytesPerTexel;
            const { level, z, x, y, width, height, depth, rowPitch,
                slicePitch, source } = upload;
            const expandedSlicePitch = width * height * gpuBpp;
            const expanded = new Uint8Array(expandedSlicePitch * depth);
            for (let slice = 0; slice < depth; ++slice) {
                for (let row = 0; row < height; ++row) {
                    expandRowToGPU(resource.format, source,
                        slice * slicePitch + row * rowPitch, width,
                        expanded,
                        slice * expandedSlicePitch + row * width * gpuBpp,
                        palette);
                }
            }
            const bytesPerRow = width * gpuBpp;
            // A repaint rewrites pixels a bind group recorded earlier in this
            // frame may still be reading, so it takes the same rename hazard
            // path an ordinary mid-frame update does.
            if (this.frame && resource.frameReferenced === this.frame.serial) {
                ++this.stats.textureUpdateHazards;
                this.renameTextureForUpdate(resource);
            }
            this.updateTextureShadow(resource, level, z, x, y, width, height,
                expanded, bytesPerRow, false, depth, bytesPerRow * height);
            this.device.queue.writeTexture(
                { texture: resource.gpuTexture, mipLevel: level,
                    origin: { x, y, z } },
                expanded, { bytesPerRow, rowsPerImage: height },
                { width, height, depthOrArrayLayers: depth });
        }

        // ---- automatic mip generation ----
        //
        // D3DUSAGE_AUTOGENMIPMAP hands the driver everything below level 0 and
        // asks it to keep the chain current. D3D9 regenerates whenever the top
        // level changes; the host is the side that can see when that actually
        // happened -- an upload landed, or a render pass had level 0 as its
        // attachment -- so the trigger lives here rather than being guessed at
        // by the guest. GenerateMipSubLevels() arrives as its own opcode for
        // the case where the app asks explicitly.

        // Remember every subresource write, irrespective of whether its pixels
        // came over the wire or were produced on the GPU.  uploadedLevels keeps
        // its historical name because it is also exposed in diagnostic state,
        // but semantically it is the set of initialized levels/faces.
        markTextureSubresourceWritten(resource, level, layer = 0) {
            if (!resource) return;
            if (resource.uploadedLevels) {
                if (resource.textureType === "3d") {
                    resource.uploadedLevels.add(level);
                } else {
                    const layerCount = Math.max(1, resource.layerCount || 1);
                    const safeLayer = Math.max(0,
                        Math.min(layer >>> 0, layerCount - 1));
                    // Six slots per level preserve the existing cube-map key
                    // layout while a 2D texture naturally occupies slot zero.
                    resource.uploadedLevels.add(level * 6 + safeLayer);
                }
            }
            if (level === 0) this.markMipsDirty(resource);
        }

        markMipsDirty(resource) {
            if (!resource || !resource.autoGenerateMips) return;
            resource.mipsDirty = true;
        }

        // Queued before whatever is about to read the texture, not executed
        // now: the chain is filled by render passes, and record time is inside
        // whatever pass is already open.
        flushGeneratedMips(resource) {
            if (!resource || !resource.autoGenerateMips || !resource.mipsDirty)
                return;
            if (!resource.gpuTexture || resource.levelCount < 2) {
                resource.mipsDirty = false;
                return;
            }
            resource.mipsDirty = false;
            const frame = this.ensureFrame();
            frame.ops.push({ kind: "generate-mips", resource });
            resource.frameReferenced = frame.serial;
            ++this.stats.mipChainsGenerated;
        }

        // One blit per level, each reading the level above with linear
        // filtering: the box downsample D3D9's default D3DTEXF_LINEAR describes.
        replayGenerateMips(encoder, op) {
            const resource = op.resource;
            const layers = resource.layerCount || 1;
            const format = resource.gpuFormat || formatToGPU(resource.format);
            const buffers = [];
            for (let layer = 0; layer < layers; ++layer) {
                for (let level = 1; level < resource.levelCount; ++level) {
                    const width = Math.max(1, resource.width >> level);
                    const height = Math.max(1, resource.height >> level);
                    const blit = {
                        kind: "blit",
                        sourceView: this.blitSourceView(resource, level - 1,
                            layer),
                        destinationView: this.targetViewFor(resource, level,
                            false, layer),
                        destinationFormat: format,
                        sourceFormat: format,
                        // The whole of the parent level, into the whole of this
                        // one.
                        sourceRect: [0, 0, 1, 1],
                        viewport: [0, 0, width, height],
                        filterPoint: false,
                    };
                    const transient = this.replayBlit(encoder, blit, null);
                    if (transient) buffers.push(transient);
                    ++this.stats.mipLevelsGenerated;
                }
            }
            return buffers;
        }

        onGenerateMips(bytes, view, offset) {
            const resource = this.resources.get(
                view.getUint32(offset + 4, true));
            if (!resource || !resource.autoGenerateMips) return;
            // An explicit call regenerates whether or not the host noticed a
            // write: the app may know something the write tracking cannot.
            resource.mipsDirty = true;
            this.flushGeneratedMips(resource);
            ++this.stats.explicitMipGenerations;
        }

        onSetTextureLOD(bytes, view, offset) {
            const resource = this.resources.get(
                view.getUint32(offset + 4, true));
            if (!resource) return;
            // Clamped against the chain that actually exists rather than
            // trusted: the guest clamps too, but a texture recreated at a
            // different level count between the two would otherwise leave a
            // lodMinClamp above lodMaxClamp, which WebGPU rejects outright.
            const levels = Math.max(1, resource.levelCount || 1);
            resource.lod = Math.min(view.getUint32(offset + 8, true) >>> 0,
                levels - 1);
        }

        // IDirect3DDevice9::SetGammaRamp. D3D9 applies this at scanout, after
        // everything the renderer did, so it is applied here in the step that
        // moves the finished back buffer onto the canvas -- see the present
        // path in finishFrame(), which swaps its plain copy for a lookup pass
        // whenever a non-identity ramp is set.
        //
        // Held as a 256x1 rgba32float lookup rather than as a curve fit: a
        // D3D9 ramp is an arbitrary table, and titles do use it for effects
        // (fades, damage flashes) that no gamma exponent can express.
        // ---- additional swap chains ----
        //
        // An additional chain targets a *different* HWND, so it needs its own
        // drawing surface: the implicit chain's canvas is the one the page
        // composites over the device window and nothing else.
        //
        // The chain's back buffer arrives as an ordinary render-target texture
        // handle, which is what keeps every other path unchanged -- draws,
        // StretchRect and readback all treat it as a texture. It becomes
        // special only here, in the step that moves the finished image onto
        // its canvas.
        //
        // The canvas itself has to come from the embedder, because only the
        // page knows where a second overlay may live in the document. Without
        // that hook the chain is refused and named rather than quietly
        // rendering nowhere.
        onCreateSwapChain(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            if (!state) return;
            const handle = view.getUint32(offset + 4, true);
            const backBufferHandle = view.getUint32(offset + 8, true);
            const surface = {
                hwnd: view.getUint32(offset + 12, true),
                x: view.getInt32(offset + 16, true),
                y: view.getInt32(offset + 20, true),
                width: view.getUint32(offset + 24, true),
                height: view.getUint32(offset + 28, true),
                swapChain: handle,
                sessionKey: state.surface ? state.surface.sessionKey : null,
                visible: true,
            };
            const create = this.options.createSwapChainCanvas;
            if (typeof create !== "function") {
                ++this.stats.swapChainsRefused;
                this.warnOnce("additional-swap-chain",
                    "the guest created an additional swap chain, but this " +
                    "embedder supplies no createSwapChainCanvas hook, so " +
                    "there is no second surface to present it on; its frames " +
                    "are counted and dropped");
                state.swapChains.set(handle, { handle, backBufferHandle,
                    surface, canvas: null, context: null });
                return;
            }
            let canvas = null;
            try {
                canvas = create(surface);
            } catch (error) {
                this.warnOnce("additional-swap-chain-canvas",
                    "createSwapChainCanvas threw; the chain has no surface to " +
                    "present on", { message: String(error) });
            }
            let context = null;
            if (canvas) {
                canvas.width = Math.max(1, surface.width);
                canvas.height = Math.max(1, surface.height);
                context = canvas.getContext("webgpu");
                if (context) {
                    context.configure({
                        device: this.device, format: this.format,
                        alphaMode: "opaque",
                        usage: TEXTURE_USAGE_RENDER_ATTACHMENT |
                            TEXTURE_USAGE_COPY_DST,
                    });
                }
            }
            state.swapChains.set(handle,
                { handle, backBufferHandle, surface, canvas, context });
            ++this.stats.swapChainsCreated;
            this.notifySwapChainSurface(surface, "create");
        }

        onDestroySwapChain(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            if (!state) return;
            const handle = view.getUint32(offset + 4, true);
            const chain = state.swapChains.get(handle);
            if (!chain) return;
            state.swapChains.delete(handle);
            if (chain.context && typeof chain.context.unconfigure === "function")
                chain.context.unconfigure();
            this.notifySwapChainSurface(
                { ...chain.surface, visible: false }, "destroy");
            ++this.stats.swapChainsDestroyed;
        }

        onPresentSwapChain(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            if (!state) return;
            const handle = view.getUint32(offset + 4, true);
            const chain = state.swapChains.get(handle);
            if (!chain) {
                ++this.stats.swapChainPresentsDropped;
                return;
            }
            const width = view.getUint32(offset + 16, true);
            const height = view.getUint32(offset + 20, true);
            chain.surface = {
                ...chain.surface,
                hwnd: view.getUint32(offset + 8, true),
                x: view.getInt32(offset + 12, true),
                // An empty client rect means the guest could not find the
                // window; the last non-empty size is the better answer, for
                // the same reason the implicit chain keeps its own.
                width: width || chain.surface.width,
                height: height || chain.surface.height,
                visible: true,
            };
            this.notifySwapChainSurface(chain.surface, "present");
            if (!chain.context) {
                ++this.stats.swapChainPresentsDropped;
                return;
            }
            const texture = this.resources.get(chain.backBufferHandle);
            if (!texture || !texture.gpuTexture) {
                ++this.stats.swapChainPresentsDropped;
                return;
            }
            if (chain.canvas) {
                if (chain.canvas.width !== texture.width)
                    chain.canvas.width = texture.width;
                if (chain.canvas.height !== texture.height)
                    chain.canvas.height = texture.height;
            }
            // Queued into the frame op list rather than run here, for the same
            // reason draws are: the chain's current texture is only valid
            // inside the task that acquires it, and a guest frame arrives
            // across several PCI submits.
            const frame = this.ensureFrame();
            frame.ops.push({
                kind: "present-swap-chain",
                chain,
                sourceView: this.blitSourceView(texture, 0, 0),
                sourceFormat: texture.gpuFormat ||
                    formatToGPU(texture.format),
                width: texture.width,
                height: texture.height,
            });
            texture.frameReferenced = frame.serial;
            ++this.stats.swapChainPresents;
        }

        notifySwapChainSurface(surface, reason) {
            if (typeof this.options.onSwapChainSurface === "function")
                this.options.onSwapChainSurface(surface, reason);
        }

        onSetGammaRamp(bytes, view, offset, length) {
            const state = this.deviceState(view.getUint32(offset, true));
            if (!state) return;
            if (length < 16 + 768 * 2) {
                ++this.stats.malformedCommands;
                return;
            }
            const values = new Float32Array(256 * 4);
            let identity = true;
            for (let index = 0; index < 256; ++index) {
                for (let channel = 0; channel < 3; ++channel) {
                    const raw = view.getUint16(
                        offset + 16 + (channel * 256 + index) * 2, true);
                    values[index * 4 + channel] = raw / 65535;
                    // The identity ramp is entry = index * 257 (0x0000, 0x0101,
                    // ... 0xffff). Recognising it matters: a title that sets the
                    // identity ramp on startup would otherwise pay for a lookup
                    // pass on every frame for no visible difference.
                    if (raw !== index * 257) identity = false;
                }
                values[index * 4 + 3] = 1;
            }
            state.gammaRampIdentity = identity;
            // Counted for every accepted ramp, identity included: "the title
            // never called SetGammaRamp" and "the title set the identity ramp"
            // are different facts, and a counter that only moved for the second
            // kind could not tell them apart.
            ++this.stats.gammaRampUpdates;
            if (identity) {
                this.retireGPUObject(state.gammaRampTexture);
                state.gammaRampTexture = null;
                state.gammaRampView = null;
                return;
            }
            if (!state.gammaRampTexture) {
                state.gammaRampTexture = this.device.createTexture({
                    label: "D3D9 gamma ramp",
                    size: { width: 256, height: 1, depthOrArrayLayers: 1 },
                    format: "rgba32float",
                    usage: TEXTURE_USAGE_TEXTURE_BINDING |
                        TEXTURE_USAGE_COPY_DST,
                });
                state.gammaRampView = state.gammaRampTexture.createView();
            }
            this.device.queue.writeTexture({ texture: state.gammaRampTexture },
                values, { bytesPerRow: 256 * 16 },
                { width: 256, height: 1, depthOrArrayLayers: 1 });
        }

        // Which device's ramp the canvas should show. A page runs one D3D9
        // device at a time in practice, but the state table is keyed by handle
        // and nothing guarantees a single entry, so this picks the first device
        // that actually has a non-identity ramp rather than assuming there is
        // exactly one.
        presentGammaView() {
            for (const state of this.devices.values()) {
                if (state && state.gammaRampView) return state.gammaRampView;
            }
            return null;
        }

        // The present-time lookup pass. Separate from blitPipelineFor() because
        // it binds a third resource the ordinary blit has no slot for, and
        // because textureLoad -- not textureSample -- is what makes the lookup
        // exact: a ramp entry is chosen by index, never interpolated between
        // two neighbours.
        gammaBlitPipelineFor(format) {
            if (!this.gammaBlitPipelines) this.gammaBlitPipelines = new Map();
            let entry = this.gammaBlitPipelines.get(format);
            if (entry) return entry;
            const module = this.moduleFor(`@group(0) @binding(0) var d9_gamma_source: texture_2d<f32>;
@group(0) @binding(1) var d9_gamma_sampler: sampler;
@group(0) @binding(2) var d9_gamma_ramp: texture_2d<f32>;

struct D9GammaOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn d9_vs_main(@builtin(vertex_index) index: u32) -> D9GammaOutput {
    var corners = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));
    let corner = corners[index];
    var result: D9GammaOutput;
    result.position = vec4<f32>(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0,
        0.0, 1.0);
    result.uv = corner;
    return result;
}

@fragment
fn d9_ps_main(stage_in: D9GammaOutput) -> @location(0) vec4<f32> {
    let source = textureSample(d9_gamma_source, d9_gamma_sampler, stage_in.uv);
    // Each channel indexes the table independently -- D3D9's ramp is three
    // separate curves, and titles do set them apart (a red damage flash is
    // exactly that).
    let index = vec3<i32>(clamp(source.rgb, vec3<f32>(0.0), vec3<f32>(1.0))
        * 255.0 + vec3<f32>(0.5));
    return vec4<f32>(
        textureLoad(d9_gamma_ramp, vec2<i32>(index.r, 0), 0).r,
        textureLoad(d9_gamma_ramp, vec2<i32>(index.g, 0), 0).g,
        textureLoad(d9_gamma_ramp, vec2<i32>(index.b, 0), 0).b,
        source.a);
}
`, "d3d9 gamma blit " + format);
            const bindGroupLayout = this.device.createBindGroupLayout({
                entries: [
                    { binding: 0, visibility: SHADER_STAGE_FRAGMENT,
                      texture: { sampleType: "float" } },
                    { binding: 1, visibility: SHADER_STAGE_FRAGMENT,
                      sampler: { type: "filtering" } },
                    // The ramp is read with textureLoad, which is defined for
                    // an unfilterable-float binding and needs no sampler.
                    { binding: 2, visibility: SHADER_STAGE_FRAGMENT,
                      texture: { sampleType: "unfilterable-float" } },
                ],
            });
            entry = {
                pipeline: this.device.createRenderPipeline({
                    label: "D3D9 gamma blit " + format,
                    layout: this.device.createPipelineLayout(
                        { bindGroupLayouts: [bindGroupLayout] }),
                    vertex: { module, entryPoint: "d9_vs_main" },
                    fragment: { module, entryPoint: "d9_ps_main",
                        targets: [{ format }] },
                    primitive: { topology: "triangle-list" },
                }),
                bindGroupLayout,
                sampler: this.device.createSampler({
                    magFilter: "nearest", minFilter: "nearest",
                    addressModeU: "clamp-to-edge",
                    addressModeV: "clamp-to-edge",
                }),
            };
            this.gammaBlitPipelines.set(format, entry);
            return entry;
        }

        onSetPalette(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const index = view.getUint32(offset + 4, true);
            const entryCount = view.getUint32(offset + 8, true);
            const dataOffset = view.getUint32(offset + 12, true);
            if (entryCount !== 256) return;
            const source = new Uint8Array(bytes.buffer,
                bytes.byteOffset + dataOffset, 256 * 4);
            // The wire carries D3DCOLOR (A8R8G8B8, little-endian BGRA bytes);
            // the expansion wants RGBA in memory order.
            const rgba = new Uint8Array(256 * 4);
            for (let entry = 0; entry < 256; ++entry) {
                const at = entry * 4;
                rgba[at] = source[at + 2];
                rgba[at + 1] = source[at + 1];
                rgba[at + 2] = source[at];
                rgba[at + 3] = source[at + 3];
            }
            if (!this.palettes) this.palettes = new Map();
            this.palettes.set(deviceHandle + ":" + index, rgba);
            ++this.stats.palettesSet;
            const state = this.devices.get(deviceHandle);
            if (state && state.currentPalette === index)
                this.repaintPalettizedTextures(deviceHandle);
        }

        onSetCurrentTexturePalette(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const index = view.getUint32(offset + 4, true);
            const state = this.deviceState(deviceHandle);
            if (state.currentPalette === index) return;
            state.currentPalette = index;
            ++this.stats.paletteSelections;
            this.repaintPalettizedTextures(deviceHandle);
        }

        onSetDepthStencilSurfaceLevel(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            const handle = view.getUint32(offset + 4, true);
            const level = view.getUint32(offset + 8, true);
            this.setDepthStencilSurface(state, handle, level);
        }

        setDepthStencilSurface(state, handle, level) {
            if (handle === D9WG_AUTO_DEPTH_STENCIL_HANDLE) {
                state.depthTargetHandle = 0;
                state.depthTargetLevel = 0;
                state.depthUnbound = false;
                return;
            }
            state.depthTargetHandle = handle;
            state.depthTargetLevel = level;
            state.depthUnbound = handle === 0;
        }

        // Everything a render pass and a pipeline need to agree on about where a
        // draw lands. Resolved per draw rather than cached on the device,
        // because the swap chain's own view does not exist until Present -- a
        // null `view` in slot 0 is the marker finishFrame() substitutes it into.
        //
        // `key` is what groups consecutive ops into one pass: two draws with the
        // same key can share a pass, and a change of key has to end it.
        renderTargetsFor(state) {
            const colors = [];
            const wantsSRGB = (state.renderStates.get(D3DRS_SRGBWRITEENABLE) || 0)
                !== 0;
            let width = state.viewport.width || this.backBufferWidthOf(state);
            let height = state.viewport.height || this.backBufferHeightOf(state);
            let key = "";
            for (let index = 0; index < MAX_RENDER_TARGETS; ++index) {
                const handle = state.renderTargets[index];
                if (!handle) {
                    if (index === 0) {
                        const format = wantsSRGB && this.swapchainSrgbFormat
                            ? this.swapchainSrgbFormat : this.format;
                        colors.push({ view: null, format,
                            swapchain: true,
                            sampleCount: state.sampleCount || 1 });
                        width = this.backBufferWidthOf(state);
                        height = this.backBufferHeightOf(state);
                        key += "bb" + (format === this.format ? "" : "s") + ";";
                    }
                    continue;
                }
                const resource = this.resources.get(handle);
                if (!resource || !resource.gpuTexture) {
                    // A bound-but-unknown target cannot be substituted with the
                    // back buffer: that would draw a render-to-texture pass
                    // straight onto the screen. Report it and drop the slot.
                    this.warnOnce("rt-unknown-" + index,
                        "a render target slot names a resource the host does " +
                        "not know; draws into it are dropped rather than " +
                        "redirected to the back buffer", { index, handle });
                    if (index === 0) return null;
                    continue;
                }
                const resourceFormat = resource.gpuFormat ||
                    formatToGPU(resource.format);
                if (!isRenderableGPUFormat(resourceFormat)) {
                    this.warnOnce("rt-non-renderable-" + index,
                        "a render target slot names a texture whose WebGPU " +
                        "format cannot be a render attachment; draws into it " +
                        "are dropped rather than submitting an invalid pass",
                        { index, handle, format: resource.format,
                            gpuFormat: resourceFormat });
                    if (index === 0) return null;
                    continue;
                }
                const level = state.renderTargetLevels[index] || 0;
                const layerCount = resource.layerCount || 1;
                const face = Math.min(state.renderTargetFaces[index] || 0,
                    layerCount - 1);
                const srgb = wantsSRGB && !!resource.srgbFormat;
                if (wantsSRGB && !resource.srgbFormat)
                    ++this.stats.srgbWriteUnavailable;
                const targetView = this.targetViewFor(resource, level, srgb,
                    face);
                if (face) ++this.stats.cubeFaceTargetBinds;
                this.markTextureSubresourceWritten(resource, level, face);
                colors.push({ view: targetView,
                    format: srgb ? resource.srgbFormat : resourceFormat,
                    swapchain: false,
                    sampleCount: resource.sampleCount || 1,
                    resource });
                if (index === 0) {
                    width = Math.max(1, resource.width >> level);
                    height = Math.max(1, resource.height >> level);
                }
                // The face belongs in the pass key: two faces of one cube are
                // different attachments, and merging their draws into one pass
                // would paint every face with the last one's contents.
                key += handle + "." + level + "." + face +
                    (srgb ? "s" : "") + ";";
            }
            if (!colors.length) return null;

            // Depth: an explicitly bound surface wins, then the device's auto
            // depth-stencil, and SetDepthStencilSurface(NULL) means neither.
            let depthView = null;
            let depthWidth = 0;
            let depthHeight = 0;
            let substituteDepth = null;
            if (state.depthTargetHandle) {
                const resource = this.resources.get(state.depthTargetHandle);
                const level = state.depthTargetLevel || 0;
                if (resource && resource.gpuTexture &&
                        (resource.usage & D3DUSAGE_DEPTHSTENCIL) !== 0 &&
                        level < resource.levelCount) {
                    // A render attachment view must select exactly one mip.
                    // targetViewFor is deliberately shared with colour render
                    // targets so both subresource paths have identical cache
                    // and descriptor semantics.
                    depthView = this.targetViewFor(resource, level, false);
                    depthWidth = Math.max(1, resource.width >> level);
                    depthHeight = Math.max(1, resource.height >> level);
                    key += "d" + state.depthTargetHandle + "." + level;
                } else {
                    this.warnOnce("depth-target-invalid-" +
                            state.depthTargetHandle + "-" + level,
                        "a depth-stencil binding names an unknown, non-depth, " +
                        "or out-of-range texture level; the pass runs without " +
                        "a depth attachment", {
                            handle: state.depthTargetHandle,
                            level,
                            levelCount: resource ? resource.levelCount : 0,
                        });
                    key += "dinvalid";
                }
            } else if (!state.depthUnbound && state.depthView) {
                depthView = state.depthView;
                depthWidth = state.depthWidth;
                depthHeight = state.depthHeight;
                key += "dauto";
            } else {
                key += "dnone";
            }
            // WebGPU requires the depth attachment to be exactly the colour
            // target's size. D3D9 requires only that it be *at least* as large,
            // and render-to-texture leans on that constantly: an app keeps one
            // full-screen depth surface and renders half-resolution passes --
            // HDR downsamples, shadow projections, reflections -- against it.
            //
            // Dropping depth for those passes is not a small approximation.
            // Nothing is occluded any more, so every alpha-blended draw that
            // should have been hidden behind geometry paints over it: the image
            // washes out and solid objects turn translucent. A substitute depth
            // texture of the right size preserves the depth *test*, which is
            // what the pass was relying on. What it cannot preserve is depth
            // written by an earlier pass, and an app doing this almost always
            // clears depth on entry anyway -- so this trades a fault that
            // ruins the frame for one that is usually invisible.
            if (depthView && (depthWidth !== width || depthHeight !== height)) {
                ++this.stats.depthTargetSizeMismatches;
                if (depthWidth >= width && depthHeight >= height) {
                    substituteDepth = this.substituteDepthFor(
                        state.depthTargetHandle, width, height);
                    depthView = substituteDepth.view;
                    ++this.stats.depthTargetSubstitutions;
                    // Deliberately not warned about here: the substitution
                    // only loses something if the pass depth-tests against
                    // contents an earlier pass wrote, and a pass that clears
                    // depth on entry has none to lose. noteSubstituteDepthUse()
                    // reports the case that actually does.
                    // The substitute is part of the pass identity: two passes
                    // standing in for different depth surfaces must not merge.
                    key += "dsub" + (state.depthTargetHandle || 0) + "." +
                        width + "x" + height;
                } else {
                    // Smaller than the target: the app is asking to depth-test
                    // fragments the depth buffer has no storage for. There is
                    // nothing to substitute that would be more correct.
                    this.warnOnce("rt-depth-undersized",
                        "the bound depth surface is smaller than the render " +
                        "target, so this pass runs without depth testing " +
                        "rather than being rejected wholesale", {
                            target: width + "x" + height,
                            depth: depthWidth + "x" + depthHeight,
                        });
                    depthView = null;
                    key += "!d";
                }
            }
            // WebGPU requires every attachment of a pass -- and the pipeline
            // drawing into it -- to agree on the sample count, so slot 0 sets
            // it and a disagreeing slot is named rather than left to fail
            // pipeline creation with nothing pointing at the cause.
            const sampleCount = colors[0].sampleCount || 1;
            for (let index = 1; index < colors.length; ++index) {
                if ((colors[index].sampleCount || 1) === sampleCount) continue;
                this.warnOnce("mrt-sample-count",
                    "the render target slots disagree about multisampling; " +
                    "WebGPU needs one sample count for the whole pass, so " +
                    "slot 0's is used", {
                        slot0: sampleCount,
                        slot: index,
                        slotSampleCount: colors[index].sampleCount || 1,
                    });
                break;
            }
            return { key: key + "x" + sampleCount, colors, depthView, width,
                height, substituteDepth,
                hasDepth: !!depthView, sampleCount,
                formats: colors.map(color => color.format) };
        }

        // StretchRect between two host-owned surfaces. A same-size, same-format
        // copy is a real GPU copy; anything that scales or changes format goes
        // through a small blit pipeline, because copyTextureToTexture cannot do
        // either. A source or destination naming the back buffer is refused
        // rather than approximated: the swap chain texture only exists inside
        // finishFrame(), and pretending otherwise would silently copy garbage.
        // ---- StretchRect ----
        //
        // Three cases, in increasing cost:
        //
        //   1. Same size, same format, neither side the back buffer -> a real
        //      copyTextureToTexture. No pass, no shader.
        //   2. Anything else -> a blit: one pass drawing a full-viewport quad
        //      that samples the source. This is what covers scaling, format
        //      conversion, and the back buffer -- whose format
        //      (getPreferredCanvasFormat, normally bgra8unorm) differs from the
        //      rgba8unorm every D3D9 texture becomes, so even a same-size
        //      back-buffer copy cannot be a copy.
        //   3. A compressed destination -> still unsupported and counted. BCn
        //      cannot be a render attachment, so there is nothing to draw into.
        //
        // A blit touching the back buffer has to be *deferred* into the frame op
        // list rather than submitted here, for the same reason draws are: the
        // swap chain texture is only valid inside the task that acquired it (see
        // ensureFrame), and a game's frame arrives across several PCI submits.
        // Doing it eagerly is what produced "the host cannot address this
        // surface" -- the back buffer genuinely has no view yet at this point.
        onStretchRect(bytes, view, offset, length) {
            const state = this.deviceState(view.getUint32(offset, true));
            const sourceHandle = view.getUint32(offset + 4, true);
            const sourceLevel = view.getUint32(offset + 8, true);
            const sourceRect = {
                left: view.getInt32(offset + 12, true),
                top: view.getInt32(offset + 16, true),
                right: view.getInt32(offset + 20, true),
                bottom: view.getInt32(offset + 24, true),
            };
            const destinationHandle = view.getUint32(offset + 28, true);
            const destinationLevel = view.getUint32(offset + 32, true);
            const destinationRect = {
                left: view.getInt32(offset + 36, true),
                top: view.getInt32(offset + 40, true),
                right: view.getInt32(offset + 44, true),
                bottom: view.getInt32(offset + 48, true),
            };
            const filterPoint = view.getUint32(offset + 52, true) !== 0;
            // Protocol 1.4. Length-gated: a 1.3 payload has no faces, and a
            // 2D surface is always face 0 anyway.
            const sourceFace = length >= 64
                ? view.getUint32(offset + 56, true) : 0;
            const destinationFace = length >= 64
                ? view.getUint32(offset + 60, true) : 0;

            const source = sourceHandle ? this.resources.get(sourceHandle) : null;
            const destination = destinationHandle
                ? this.resources.get(destinationHandle) : null;
            // Handle 0 means the back buffer; a non-zero handle the host does not
            // know is a real error, not a back buffer.
            if ((sourceHandle && !source) || (destinationHandle && !destination) ||
                    (source && !source.gpuTexture) ||
                    (destination && !destination.gpuTexture)) {
                ++this.stats.blitsSkipped;
                this.warnOnce("stretchrect-unknown",
                    "StretchRect names a resource the host does not know; it is " +
                    "skipped rather than copying unrelated memory",
                    { sourceHandle, destinationHandle });
                return;
            }
            const width = sourceRect.right - sourceRect.left;
            const height = sourceRect.bottom - sourceRect.top;
            const destinationWidth = destinationRect.right - destinationRect.left;
            const destinationHeight = destinationRect.bottom - destinationRect.top;
            if (width <= 0 || height <= 0 ||
                    destinationWidth <= 0 || destinationHeight <= 0)
                return;
            if (destination && isCompressedFormat(destination.format)) {
                ++this.stats.blitsSkipped;
                this.warnOnce("stretchrect-compressed-destination",
                    "StretchRect into a block-compressed texture is not " +
                    "implemented: BCn cannot be a render attachment, so there " +
                    "is nothing to draw into, and re-compressing on the CPU " +
                    "would be a different image than the app asked for");
                return;
            }

            const sourceFormat = source ? formatToGPU(source.format) : this.format;
            const destinationFormat = destination
                ? formatToGPU(destination.format) : this.format;
            const scaled = width !== destinationWidth ||
                height !== destinationHeight;
            const swapchainInvolved = !source || !destination;
            if (!swapchainInvolved && !scaled && sourceFormat === destinationFormat) {
                const frame = this.ensureFrame();
                // The face is the copy's z origin: a cube map is a six-layer
                // 2D texture, so "face 3" is layer 3 of one subresource range.
                frame.ops.push({ kind: "copy",
                    source: { texture: source.gpuTexture, mipLevel: sourceLevel,
                        origin: { x: sourceRect.left, y: sourceRect.top,
                            z: sourceFace } },
                    destination: { texture: destination.gpuTexture,
                        mipLevel: destinationLevel,
                        origin: { x: destinationRect.left,
                            y: destinationRect.top, z: destinationFace } },
                    size: { width, height, depthOrArrayLayers: 1 } });
                source.frameReferenced = frame.serial;
                destination.frameReferenced = frame.serial;
                this.markTextureSubresourceWritten(destination,
                    destinationLevel, destinationFace);
                ++this.stats.blits;
                return;
            }
            if (destination && !isRenderableGPUFormat(destinationFormat)) {
                ++this.stats.blitsSkipped;
                this.warnOnce("stretchrect-non-renderable-destination",
                    "a scaled or format-converting StretchRect targets a " +
                    "texture whose WebGPU format cannot be a render " +
                    "attachment; only a same-size same-format GPU copy is " +
                    "supported", { destinationHandle,
                        format: destination.format, destinationFormat });
                return;
            }

            // Source UVs are normalised against the *level* being read, not the
            // base level, or a StretchRect from mip 2 samples a quarter of the
            // image it asked for.
            const sourceWidth = source
                ? Math.max(1, source.width >> sourceLevel)
                : this.backBufferWidthOf(state);
            const sourceHeight = source
                ? Math.max(1, source.height >> sourceLevel)
                : this.backBufferHeightOf(state);
            const op = {
                kind: "blit",
                sourceView: source
                    ? this.blitSourceView(source, sourceLevel, sourceFace) : null,
                destinationView: destination
                    ? this.targetViewFor(destination, destinationLevel, false,
                        destinationFace) : null,
                destinationFormat,
                sourceFormat: source ? (source.gpuFormat ||
                    formatToGPU(source.format)) : this.format,
                sourceRect: [
                    sourceRect.left / sourceWidth, sourceRect.top / sourceHeight,
                    width / sourceWidth, height / sourceHeight,
                ],
                viewport: [destinationRect.left, destinationRect.top,
                    destinationWidth, destinationHeight],
                filterPoint,
            };
            const frame = this.ensureFrame();
            frame.ops.push(op);
            if (source) source.frameReferenced = frame.serial;
            if (destination) destination.frameReferenced = frame.serial;
            this.markTextureSubresourceWritten(destination, destinationLevel,
                destinationFace);
            ++this.stats.blits;
            if (swapchainInvolved) ++this.stats.blitsThroughBackBuffer;
        }

        // A sampled view of one mip level, cached on the resource.
        blitSourceView(resource, level, face) {
            if (!resource.blitViews) resource.blitViews = new Map();
            const baseArrayLayer = face || 0;
            const key = level + ":" + baseArrayLayer;
            let cached = resource.blitViews.get(key);
            if (!cached) {
                cached = resource.gpuTexture.createView({
                    dimension: "2d", baseMipLevel: level, mipLevelCount: 1,
                    baseArrayLayer, arrayLayerCount: 1,
                });
                resource.blitViews.set(key, cached);
            }
            return cached;
        }

        // Shared with renderTargetsFor(): a render-attachment view of one level.
        // Size-matched stand-in depth attachments, one per distinct size. Kept
        // for the device's lifetime rather than per frame: an app that renders
        // half-resolution passes does it every frame, and the sizes it uses are
        // a handful of fixed values.
        // Keyed by the depth surface being stood in for as well as the size.
        // Sharing one texture across every pass of a given size looked
        // economical and is a correctness bug: two render-to-texture passes at
        // the same resolution but against *different* depth surfaces would
        // depth-test against each other's fragments. Which is exactly the
        // hazard this whole path exists to avoid, arrived at from the other
        // direction. Kept for the device's lifetime because the set of
        // (surface, size) pairs an app uses is small and fixed.
        // A pass is about to depth-test against a stand-in. If nothing cleared
        // it this frame, it is being read for contents the real (larger) depth
        // surface holds and this one never received -- the one case where the
        // substitution actually changes the image.
        noteSubstituteDepthUse(targets, clearsDepth) {
            const record = targets && targets.substituteDepth;
            if (!record) return;
            // ensureFrame(), not this.frame: a Clear is often the first thing
            // in a frame, and reading a not-yet-created frame's serial as 0
            // made the clear and the draw that follows it disagree about which
            // frame they were in -- so every cleared substitute looked stale.
            const serial = this.ensureFrame().serial;
            if (clearsDepth) {
                record.clearedInFrame = serial;
                return;
            }
            if (record.clearedInFrame === serial) return;
            ++this.stats.depthTargetSubstitutionsUncleared;
            this.warnOnce("rt-depth-oversized-uncleared",
                "a pass depth-tests against a depth surface larger than its " +
                "render target -- which D3D9 allows and WebGPU does not -- " +
                "without clearing depth first, so it reads a stand-in that " +
                "never received what an earlier pass wrote into the larger " +
                "surface; geometry that should have been occluded is not", {
                    target: targets.width + "x" + targets.height,
                });
        }

        substituteDepthFor(sourceHandle, width, height) {
            if (!this.substituteDepthViews) this.substituteDepthViews = new Map();
            const size = width + "x" + height;
            const key = (sourceHandle || 0) + ":" + size;
            let record = this.substituteDepthViews.get(key);
            if (record) return record;
            const texture = this.device.createTexture({
                label: "D3D9 substitute depth " + size + " for " +
                    (sourceHandle || "auto"),
                size: { width, height, depthOrArrayLayers: 1 },
                format: DEPTH_FORMAT,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
            });
            // clearedInFrame is what separates the harmless case from the
            // real one: a pass that clears depth on entry loses nothing by
            // getting a fresh texture, and that is what render-to-texture does.
            record = { view: texture.createView(), clearedInFrame: -1 };
            this.substituteDepthViews.set(key, record);
            return record;
        }

        // One attachment view per (level, face, srgb). A cube map is a
        // six-layer 2D texture here, so rendering into one face is exactly
        // selecting one array layer -- which is why the layer has to reach this
        // far rather than being resolved at bind time: an attachment view names
        // a single subresource, and "the cube" is not one.
        targetViewFor(resource, level, srgb, layer) {
            if (!resource.targetViews) resource.targetViews = new Map();
            const baseArrayLayer = layer || 0;
            const key = level + ":" + baseArrayLayer + (srgb ? "s" : "");
            let cached = resource.targetViews.get(key);
            if (!cached) {
                cached = resource.gpuTexture.createView({
                    baseMipLevel: level, mipLevelCount: 1, dimension: "2d",
                    baseArrayLayer, arrayLayerCount: 1,
                    ...(srgb ? { format: resource.srgbFormat } : {}),
                });
                resource.targetViews.set(key, cached);
            }
            return cached;
        }

        // One pipeline per destination format. The quad is generated from the
        // vertex index, so a blit needs no vertex buffer at all.
        blitPipelineFor(format, filterPoint, sourceFormat) {
            // WebGPU exposes filtering and blending for 32-bit float formats
            // as independent optional features.  A D3D point blit remains
            // legal without float32-filterable, but its binding layout and
            // sampler must explicitly be non-filtering.
            const unfilterable = isFloat32GPUFormat(sourceFormat) &&
                !this.deviceFeatures.float32Filterable;
            const point = filterPoint || unfilterable;
            const key = format + "|" + (point ? "point" : "linear") + "|" +
                (unfilterable ? "unfilterable" : "filterable");
            if (!this.blitPipelines) this.blitPipelines = new Map();
            let entry = this.blitPipelines.get(key);
            if (entry) return entry;
            const module = this.moduleFor(`struct D9BlitUniforms {
    source_rect: vec4<f32>,
};
@group(0) @binding(0) var<uniform> blit: D9BlitUniforms;
@group(0) @binding(1) var d9_blit_source: texture_2d<f32>;
@group(0) @binding(2) var d9_blit_sampler: sampler;

struct D9BlitOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn d9_vs_main(@builtin(vertex_index) index: u32) -> D9BlitOutput {
    // Two triangles covering the whole viewport; setViewport restricts the
    // output to the destination rect, so no destination maths is needed here.
    var corners = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));
    let corner = corners[index];
    var result: D9BlitOutput;
    result.position = vec4<f32>(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0,
        0.0, 1.0);
    result.uv = blit.source_rect.xy + corner * blit.source_rect.zw;
    return result;
}

@fragment
fn d9_ps_main(stage_in: D9BlitOutput) -> @location(0) vec4<f32> {
    return textureSample(d9_blit_source, d9_blit_sampler, stage_in.uv);
}
`, "d3d9 blit " + key);
            const bindGroupLayout = this.device.createBindGroupLayout({
                entries: [
                    { binding: 0, visibility: SHADER_STAGE_VERTEX,
                      buffer: { type: "uniform" } },
                    { binding: 1, visibility: SHADER_STAGE_FRAGMENT,
                      texture: { sampleType: unfilterable
                          ? "unfilterable-float" : "float" } },
                    { binding: 2, visibility: SHADER_STAGE_FRAGMENT,
                      sampler: { type: unfilterable
                          ? "non-filtering" : "filtering" } },
                ],
            });
            const pipeline = this.device.createRenderPipeline({
                label: "D3D9 blit " + key,
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: { module, entryPoint: "d9_vs_main" },
                fragment: { module, entryPoint: "d9_ps_main",
                    targets: [{ format }] },
                primitive: { topology: "triangle-list" },
            });
            const sampler = this.device.createSampler({
                magFilter: point ? "nearest" : "linear",
                minFilter: point ? "nearest" : "linear",
                addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge",
            });
            entry = { pipeline, bindGroupLayout, sampler };
            this.blitPipelines.set(key, entry);
            return entry;
        }

        // Runs a recorded blit op inside finishFrame, where the swap chain view
        // exists. `swapView` substitutes for a null source/destination view.
        replayBlit(encoder, op, swapView) {
            const sourceView = op.sourceView || swapView;
            const destinationView = op.destinationView || swapView;
            if (!sourceView || !destinationView) return null;
            const entry = this.blitPipelineFor(op.destinationFormat,
                op.filterPoint, op.sourceFormat);
            const uniform = this.device.createBuffer({
                size: 16,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(uniform, 0,
                new Float32Array(op.sourceRect));
            const bindGroup = this.device.createBindGroup({
                layout: entry.bindGroupLayout,
                entries: [
                    { binding: 0, resource: { buffer: uniform } },
                    { binding: 1, resource: sourceView },
                    { binding: 2, resource: entry.sampler },
                ],
            });
            const pass = encoder.beginRenderPass({
                colorAttachments: [{ view: destinationView,
                    loadOp: "load", storeOp: "store" }],
            });
            ++this.stats.renderPasses;
            pass.setPipeline(entry.pipeline);
            pass.setBindGroup(0, bindGroup);
            pass.setViewport(op.viewport[0], op.viewport[1], op.viewport[2],
                op.viewport[3], 0, 1);
            pass.draw(6);
            pass.end();
            return uniform;
        }

        rectClearPipelineFor(targets, clearsColor, clearsDepth, clearsStencil) {
            // The key has to describe the *pass* this pipeline will be used
            // in, not just what the clear writes. WebGPU requires a pipeline's
            // attachment state -- colour formats, whether there is a
            // depth-stencil attachment, and the sample count -- to match the
            // pass exactly. Keying on the clear flags alone let a pipeline
            // built for a depth-less pass be reused in a pass that has depth,
            // which fails validation at setPipeline and invalidates the whole
            // command buffer, so the frame draws nothing. 3DMark 2001 hits
            // this the moment one pass drops depth (an undersized depth
            // surface does that) and the next one has it.
            const key = [targets.formats.join(","), clearsColor ? "c" : "-",
                clearsDepth ? "d" : "-", clearsStencil ? "s" : "-",
                targets.hasDepth ? "z" : "-",
                targets.sampleCount || 1].join("|");
            if (!this.rectClearPipelines) this.rectClearPipelines = new Map();
            let entry = this.rectClearPipelines.get(key);
            if (entry) return entry;
            const colorFields = targets.formats.map((_, index) =>
                "    @location(" + index + ") color" + index + ": vec4<f32>,");
            const colorWrites = targets.formats.map((_, index) =>
                "    result.color" + index + " = clear.color;");
            const depthField = clearsDepth
                ? "    @builtin(frag_depth) depth: f32," : "";
            const depthWrite = clearsDepth
                ? "    result.depth = clear.depth.x;" : "";
            const module = this.moduleFor(`struct D9RectClearUniforms {
    color: vec4<f32>,
    depth: vec4<f32>,
};
@group(0) @binding(0) var<uniform> clear: D9RectClearUniforms;

struct D9RectClearOutput {
${colorFields.join("\n")}
${depthField}
};

@vertex
fn d9_vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
    var positions = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0),
        vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
    return vec4<f32>(positions[index], 0.0, 1.0);
}

@fragment
fn d9_ps_main() -> D9RectClearOutput {
    var result: D9RectClearOutput;
${colorWrites.join("\n")}
${depthWrite}
    return result;
}
`, "d3d9 rectangle clear " + key);
            const bindGroupLayout = this.device.createBindGroupLayout({
                entries: [{ binding: 0, visibility: SHADER_STAGE_FRAGMENT,
                    buffer: { type: "uniform" } }],
            });
            const descriptor = {
                label: "D3D9 rectangle clear " + key,
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: { module, entryPoint: "d9_vs_main" },
                fragment: { module, entryPoint: "d9_ps_main",
                    targets: targets.formats.map(format => ({ format,
                        writeMask: clearsColor ? 0xF : 0 })) },
                primitive: { topology: "triangle-list" },
            };
            if (targets.hasDepth) {
                const stencil = clearsStencil ? { compare: "always",
                    failOp: "keep", depthFailOp: "keep", passOp: "replace" } : {};
                descriptor.depthStencil = { format: DEPTH_FORMAT,
                    depthWriteEnabled: clearsDepth, depthCompare: "always",
                    stencilFront: stencil, stencilBack: stencil,
                    stencilReadMask: clearsStencil ? 0xff : 0,
                    stencilWriteMask: clearsStencil ? 0xff : 0 };
            }
            if ((targets.sampleCount || 1) > 1)
                descriptor.multisample = { count: targets.sampleCount };
            entry = { pipeline: this.device.createRenderPipeline(descriptor),
                bindGroupLayout };
            this.rectClearPipelines.set(key, entry);
            return entry;
        }

        replayRectClear(encoder, op, swapView, swapSrgbView) {
            const entry = this.rectClearPipelineFor(op.targets, op.clearsColor,
                op.clearsDepth, op.clearsStencil);
            const uniform = this.device.createBuffer({ size: 32,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST });
            this.device.queue.writeBuffer(uniform, 0, new Float32Array([
                op.color.r, op.color.g, op.color.b, op.color.a,
                op.depth, 0, 0, 0,
            ]));
            const bindGroup = this.device.createBindGroup({
                layout: entry.bindGroupLayout,
                entries: [{ binding: 0, resource: { buffer: uniform } }],
            });
            const descriptor = {
                colorAttachments: op.targets.colors.map(color => ({
                    view: color.swapchain
                        ? (color.format === this.swapchainSrgbFormat
                            ? swapSrgbView : swapView)
                        : color.view,
                    loadOp: "load", storeOp: "store",
                })),
            };
            if (op.targets.depthView) descriptor.depthStencilAttachment = {
                view: op.targets.depthView,
                depthLoadOp: "load", depthStoreOp: "store",
                stencilLoadOp: "load", stencilStoreOp: "store",
            };
            const pass = encoder.beginRenderPass(descriptor);
            ++this.stats.renderPasses;
            pass.setPipeline(entry.pipeline);
            pass.setBindGroup(0, bindGroup);
            pass.setStencilReference(op.stencil & 0xff);
            for (const rect of op.rects) {
                pass.setViewport(rect.left, rect.top, rect.right - rect.left,
                    rect.bottom - rect.top, 0, 1);
                pass.draw(3);
            }
            pass.end();
            return uniform;
        }

        colorFillPipelineFor(format) {
            if (!this.colorFillPipelines) this.colorFillPipelines = new Map();
            let entry = this.colorFillPipelines.get(format);
            if (entry) return entry;
            const module = this.moduleFor(`struct D9ColorFillUniforms {
    color: vec4<f32>,
};
@group(0) @binding(0) var<uniform> fill: D9ColorFillUniforms;

@vertex
fn d9_vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
    var positions = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0),
        vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
    return vec4<f32>(positions[index], 0.0, 1.0);
}

@fragment
fn d9_ps_main() -> @location(0) vec4<f32> {
    return fill.color;
}
`, "d3d9 ColorFill " + format);
            const bindGroupLayout = this.device.createBindGroupLayout({
                entries: [{ binding: 0, visibility: SHADER_STAGE_FRAGMENT,
                    buffer: { type: "uniform" } }],
            });
            const pipeline = this.device.createRenderPipeline({
                label: "D3D9 ColorFill " + format,
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: { module, entryPoint: "d9_vs_main" },
                fragment: { module, entryPoint: "d9_ps_main",
                    targets: [{ format }] },
                primitive: { topology: "triangle-list" },
            });
            entry = { pipeline, bindGroupLayout };
            this.colorFillPipelines.set(format, entry);
            return entry;
        }

        replayColorFill(encoder, op) {
            const pass = encoder.beginRenderPass({ colorAttachments: [{
                view: op.targetView, loadOp: op.isFull ? "clear" : "load",
                storeOp: "store", ...(op.isFull ? { clearValue: {
                    r: op.rgba[0], g: op.rgba[1], b: op.rgba[2], a: op.rgba[3],
                } } : {}),
            }] });
            ++this.stats.renderPasses;
            let transient = null;
            if (!op.isFull) {
                const entry = this.colorFillPipelineFor(op.format);
                transient = this.device.createBuffer({ size: 16,
                    usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST });
                this.device.queue.writeBuffer(transient, 0,
                    new Float32Array(op.rgba));
                const bindGroup = this.device.createBindGroup({
                    layout: entry.bindGroupLayout,
                    entries: [{ binding: 0, resource: { buffer: transient } }],
                });
                pass.setPipeline(entry.pipeline);
                pass.setBindGroup(0, bindGroup);
                pass.setViewport(op.left, op.top, op.right - op.left,
                    op.bottom - op.top, 0, 1);
                pass.draw(3);
            }
            pass.end();
            return transient;
        }

        // A full ColorFill is a clear pass; a partial one is a viewport-limited
        // draw. This keeps the pixels outside the requested RECT intact.
        // A refusal or failure the guest DLL is reporting. This is the only
        // guest-to-host traffic in the protocol that is not a command, and it
        // exists because everything the guest turns down used to be invisible
        // from the page: the browser console sees a clean stream of valid
        // commands, and the guest's own trace file is inside a VM whose
        // filesystem is not reachable from here. The guest deduplicates by
        // exact text, so each distinct message arrives once no matter how many
        // frames it repeats on.
        onGuestLog(bytes, view, offset, length, metadata) {
            const severity = view.getUint32(offset, true);
            const textBytes = view.getUint32(offset + 4, true);
            if (8 + textBytes > length) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG guest log text overruns the command");
            }
            let text = "";
            for (let index = 0; index < textBytes; ++index)
                text += String.fromCharCode(bytes[offset + 8 + index]);
            ++this.stats.guestReports;
            (this.guestReports || (this.guestReports = [])).push(text);
            // A state restore replays the graphics journal, and with it every
            // report since the guest started: one "proxy build ... loaded" per
            // process that ever loaded the DLL. They were printed when the
            // guest sent them; the console shows what happens now.
            if (metadata && metadata.replay) return;
            // Severity picks the console channel only. The identification
            // line the guest sends at startup is info: its job is to make a
            // later silence mean "nothing was refused" rather than "the DLL in
            // the disk image is too old to say anything".
            const report = severity === GUEST_LOG_SEVERITY_FAILED
                ? console.error
                : (severity === GUEST_LOG_SEVERITY_INFO
                    ? console.log : console.warn);
            report.call(console, "[d3d9-guest] " + text);
        }

        onColorFill(bytes, view, offset, length) {
            const resource = this.resources.get(view.getUint32(offset + 4, true));
            const level = view.getUint32(offset + 8, true);
            const color = view.getUint32(offset + 12, true);
            const face = length >= 40 ? view.getUint32(offset + 32, true) : 0;
            // The question is whether this texture can be an attachment, not
            // whether D3D9 called it a render target. An offscreen plain
            // surface in D3DPOOL_DEFAULT carries no D3DUSAGE_RENDERTARGET and
            // ColorFill is nevertheless defined on it -- that is most of what
            // the call exists for -- and the GPU texture behind it is
            // attachable all the same.
            const attachable = resource && resource.textureDescriptor &&
                (resource.textureDescriptor.usage &
                    TEXTURE_USAGE_RENDER_ATTACHMENT) !== 0;
            if (!resource || !resource.gpuTexture || !attachable) {
                ++this.stats.blitsSkipped;
                this.warnOnce("colorfill-not-attachable",
                    "ColorFill on a surface whose WebGPU texture cannot be a " +
                    "render attachment is skipped: WebGPU can only clear an " +
                    "attachment, and faking it with an upload would need a CPU " +
                    "mirror this path deliberately does not keep for GPU-only " +
                    "content", { format: resource ? resource.format : 0 });
                return;
            }
            // Shares targetViewFor's cache and its single-layer descriptor.
            // Building a view here by hand left the array layers unbounded,
            // which on a cube map is a six-layer view where the pass wants one.
            const targetView = this.targetViewFor(resource, level, false,
                Math.min(face, (resource.layerCount || 1) - 1));
            const left = view.getInt32(offset + 16, true);
            const top = view.getInt32(offset + 20, true);
            const right = view.getInt32(offset + 24, true);
            const bottom = view.getInt32(offset + 28, true);
            const fullWidth = Math.max(1, resource.width >> level);
            const fullHeight = Math.max(1, resource.height >> level);
            const clippedLeft = Math.max(0, Math.min(fullWidth, left));
            const clippedTop = Math.max(0, Math.min(fullHeight, top));
            const clippedRight = Math.max(clippedLeft,
                Math.min(fullWidth, right));
            const clippedBottom = Math.max(clippedTop,
                Math.min(fullHeight, bottom));
            if (clippedRight === clippedLeft || clippedBottom === clippedTop)
                return;
            const rgba = [((color >>> 16) & 0xff) / 255,
                ((color >>> 8) & 0xff) / 255, (color & 0xff) / 255,
                ((color >>> 24) & 0xff) / 255];
            const isFull = clippedLeft === 0 && clippedTop === 0 &&
                clippedRight === fullWidth && clippedBottom === fullHeight;
            const frame = this.ensureFrame();
            frame.ops.push({ kind: "color-fill", targetView,
                format: formatToGPU(resource.format), rgba, isFull,
                left: clippedLeft, top: clippedTop,
                right: clippedRight, bottom: clippedBottom });
            resource.frameReferenced = frame.serial;
            ++this.stats.colorFills;
        }

        decodeVertexElements(bytes, view, offset, count) {
            const elements = [];
            for (let i = 0; i < count; ++i) {
                const base = offset + i * 8;
                elements.push({
                    stream: view.getUint16(base, true),
                    byteOffset: view.getUint16(base + 2, true),
                    type: view.getUint8(base + 4),
                    method: view.getUint8(base + 5),
                    usage: view.getUint8(base + 6),
                    usageIndex: view.getUint8(base + 7),
                });
            }
            return elements;
        }

        // What the fixed-function vertex stage needs to know about a decoded
        // D9WGVertexElement array. Returns null when the declaration carries
        // no position at all, which is the one thing the fixed-function stage
        // cannot work around.
        fixedFunctionVertexSignature(elements) {
            let positionType = null;
            let hasColor = false;
            let colorIsBGRA = false;
            let hasColor1 = false;
            let color1IsBGRA = false;
            let hasNormal = false;
            let hasPointSize = false;
            let blendWeightType = -1;
            let blendIndicesType = -1;
            const texCoordSets = [];
            for (const element of elements) {
                if (element.usage === DECLUSAGE_BLENDWEIGHT &&
                        element.usageIndex === 0)
                    blendWeightType = element.type;
                else if (element.usage === DECLUSAGE_BLENDINDICES &&
                        element.usageIndex === 0)
                    blendIndicesType = element.type;
                if (element.usage === DECLUSAGE_POSITION && element.usageIndex === 0)
                    positionType = "world";
                else if (element.usage === DECLUSAGE_POSITIONT && element.usageIndex === 0)
                    positionType = "screen";
                else if (element.usage === DECLUSAGE_COLOR && element.usageIndex === 0) {
                    hasColor = true;
                    // Only a D3DCOLOR-typed diffuse arrives byte-swapped; a
                    // declaration is free to use FLOAT4 instead, and swizzling
                    // that would rotate the channels for no reason.
                    colorIsBGRA = element.type === DECLTYPE_D3DCOLOR;
                } else if (element.usage === DECLUSAGE_COLOR && element.usageIndex === 1) {
                    hasColor1 = true;
                    color1IsBGRA = element.type === DECLTYPE_D3DCOLOR;
                } else if (element.usage === DECLUSAGE_NORMAL && element.usageIndex === 0)
                    hasNormal = true;
                else if (element.usage === DECLUSAGE_PSIZE && element.usageIndex === 0)
                    hasPointSize = true;
                else if (element.usage === DECLUSAGE_TEXCOORD &&
                        element.usageIndex < MAX_TEXCOORD_SETS &&
                        !texCoordSets.includes(element.usageIndex))
                    texCoordSets.push(element.usageIndex);
            }
            if (!positionType) return null;
            texCoordSets.sort((a, b) => a - b);
            // The blend element *types* travel with the signature because the
            // WGSL input for BLENDINDICES has to be declared with the base type
            // of whatever WebGPU format the declaration's D3DDECLTYPE maps to;
            // whether they are read at all is a render-state question that
            // vertexBlendPlan() answers once the state is in hand.
            return { positionType, hasColor, colorIsBGRA, hasColor1,
                color1IsBGRA, hasNormal, hasPointSize, texCoordSets,
                blendWeightType, blendIndicesType,
                hasTexCoord: texCoordSets.length > 0 };
        }

        // Resolves D3DRS_VERTEXBLEND plus D3DRS_INDEXEDVERTEXBLENDENABLE
        // against what the declaration actually carries. Returns null when the
        // draw is not blended, which is the overwhelmingly common case -- and
        // is *correct* for a declaration that carries blend data while the
        // render state is DISABLE, since D3D9 ignores the data too and poses
        // every vertex by D3DTS_WORLD alone.
        vertexBlendPlan(state, signature) {
            const rs = state.renderStates;
            const mode = rs.get(D3DRS_VERTEXBLEND) || D3DVBF_DISABLE;
            if (mode === D3DVBF_DISABLE) return null;
            // Pre-transformed vertices skip the whole transform pipeline, so
            // there is nothing for a world matrix to pose.
            if (signature.positionType === "screen") return null;
            if (mode === D3DVBF_TWEENING) {
                // Vertex tweening interpolates two *streams* by
                // D3DRS_TWEENFACTOR rather than blending matrices; nothing here
                // implements it, and fill_caps() does not claim
                // D3DVTXPCAPS_TWEENING.
                this.warnOnce("ff-vertex-tweening",
                    "D3DVBF_TWEENING is not implemented; the draw is posed by " +
                    "world matrix 0 alone");
                return null;
            }
            const indexed = (rs.get(D3DRS_INDEXEDVERTEXBLENDENABLE) || 0) !== 0;
            // 1/2/3WEIGHTS carry that many weights and one more matrix;
            // 0WEIGHTS is one matrix at full weight.
            const matrixCount = mode === D3DVBF_0WEIGHTS ? 1 : mode + 1;
            if (matrixCount < 1 || matrixCount > MAX_BLEND_MATRICES) {
                this.warnOnce("ff-vertex-blend-mode-" + mode,
                    "unsupported D3DRS_VERTEXBLEND value " + mode +
                    "; the draw is posed by world matrix 0 alone");
                return null;
            }
            const weightCount = matrixCount - 1;
            // Without weights there is nothing to distribute, and without
            // indices an indexed blend has no palette entry to look up. Either
            // way the declaration and the render state disagree; D3D9's result
            // would be undefined, so fall back to the unblended path and say so
            // rather than invent one.
            if (weightCount && signature.blendWeightType < 0) {
                this.warnOnce("ff-vertex-blend-no-weights",
                    "D3DRS_VERTEXBLEND asks for " + weightCount + " weight(s) " +
                    "but the declaration has no BLENDWEIGHT; the draw is posed " +
                    "by world matrix 0 alone");
                return null;
            }
            // Weights are read as vec4<f32>, so a BLENDWEIGHT declared with an
            // integer or packed D3DDECLTYPE would put a format the shader
            // cannot receive into the vertex layout -- a pipeline the driver
            // rejects, which costs the whole draw rather than the blend.
            if (weightCount && declTypeInputScalar(signature.blendWeightType)
                    !== "f32") {
                this.warnOnce("ff-blend-weight-type-" + signature.blendWeightType,
                    "BLENDWEIGHT uses D3DDECLTYPE " + signature.blendWeightType +
                    ", which is not a float format; the draw is posed by world " +
                    "matrix 0 alone");
                return null;
            }
            let indexScalar = "u32";
            let indexNormalized = false;
            if (indexed) {
                if (signature.blendIndicesType < 0) {
                    this.warnOnce("ff-vertex-blend-no-indices",
                        "D3DRS_INDEXEDVERTEXBLENDENABLE is set but the " +
                        "declaration has no BLENDINDICES; the draw is posed by " +
                        "world matrix 0 alone");
                    return null;
                }
                indexScalar = declTypeInputScalar(signature.blendIndicesType);
                // D3DCOLOR and UBYTE4N both map to unorm8x4, so the shader
                // receives each index byte divided by 255 rather than the byte.
                // D3DFVF_LASTBETA_D3DCOLOR is the FVF spelling of exactly that,
                // so this is a path real content takes, not a curiosity.
                indexNormalized = signature.blendIndicesType === DECLTYPE_D3DCOLOR
                    || signature.blendIndicesType === 8;
                if (!indexScalar) {
                    this.warnOnce("ff-blend-indices-type-" +
                            signature.blendIndicesType,
                        "BLENDINDICES uses D3DDECLTYPE " +
                        signature.blendIndicesType + ", which packs into a " +
                        "single uint32 rather than four components; the draw " +
                        "is posed by world matrix 0 alone");
                    return null;
                }
            }
            // How many matrices the uniform block carries. A non-indexed blend
            // reads WORLDMATRIX(0..matrixCount-1) in order, so that is all it
            // needs. An indexed one can name any palette entry, and the palette
            // is bucketed rather than sized exactly so that setting one more
            // bone does not mint a new shader and a new pipeline; see
            // blendPaletteSize.
            const matrixSlots = indexed
                ? blendPaletteSize(state.maxWorldMatrixIndex) : matrixCount;
            ++this.stats.blendedDraws;
            return { matrixCount, weightCount, indexed, indexScalar,
                indexNormalized, matrixSlots };
        }

        // ---- fixed-function state signatures (M3) ----
        //
        // Reads the texture-stage state the guest has been sending since M1 and
        // turns it into the shape buildFixedFunctionPixelShader() consumes. Both
        // the WGSL and the pipeline cache key derive from this one object, so a
        // state that changes rendering always changes the key.
        //
        // `coordVaryingFor` maps a stage to the varying that carries its
        // coordinates. With a fixed-function vertex stage that is the stage index
        // itself (the vertex stage already resolved TEXCOORDINDEX and the
        // transform); with a translated vertex shader the varyings are whatever
        // the shader wrote per semantic, so the stage's TEXCOORDINDEX selects
        // among them here instead.
        textureCascadeSignature(state, options) {
            const stageState = (stage, id, fallback) => {
                const value = state.textureStageStates.get(stage * 64 + id);
                return value === undefined ? fallback : value;
            };
            const samplerState = (stage, id, fallback) => {
                const value = state.samplerStates.get(stage * 64 + id);
                return value === undefined ? fallback : value;
            };
            const stages = [];
            const textureColorKeyEnabled =
                (state.renderStates.get(D3DRS_COLORKEYENABLE) || 0) !== 0 ||
                (state.renderStates.get(D3DRS_COLORKEYBLENDENABLE) || 0) !== 0;
            let usesTextureFactor = false;
            let usesSpecular = false;
            const unsupported = [];
            for (let index = 0; index < MAX_TEXTURE_STAGES; ++index) {
                // D3D9 defaults: stage 0 modulates its texture with the running
                // colour (which at stage 0 *is* the diffuse colour), every later
                // stage is disabled. The first disabled stage ends the cascade.
                const colorOp = stageState(index, D3DTSS_COLOROP,
                    index === 0 ? D3DTOP_MODULATE : D3DTOP_DISABLE);
                if (colorOp === D3DTOP_DISABLE) break;
                const alphaOp = stageState(index, D3DTSS_ALPHAOP,
                    index === 0 ? D3DTOP_SELECTARG1 : D3DTOP_DISABLE);
                const stage = {
                    index,
                    colorOp,
                    colorArg0: stageState(index, D3DTSS_COLORARG0, D3DTA_CURRENT),
                    colorArg1: stageState(index, D3DTSS_COLORARG1, D3DTA_TEXTURE),
                    colorArg2: stageState(index, D3DTSS_COLORARG2, D3DTA_CURRENT),
                    alphaOp,
                    alphaArg0: stageState(index, D3DTSS_ALPHAARG0, D3DTA_CURRENT),
                    alphaArg1: stageState(index, D3DTSS_ALPHAARG1, D3DTA_TEXTURE),
                    alphaArg2: stageState(index, D3DTSS_ALPHAARG2, D3DTA_CURRENT),
                    resultArg: stageState(index, D3DTSS_RESULTARG, D3DTA_CURRENT),
                    usesConstant: false,
                    samplesTexture: false,
                    textureType: "2d",
                    transformCount: 0,
                    projected: false,
                    addressU: samplerState(index, D3DSAMP_ADDRESSU, 1),
                    addressV: samplerState(index, D3DSAMP_ADDRESSV, 1),
                    addressW: samplerState(index, D3DSAMP_ADDRESSW, 1),
                    borderColor: samplerState(index, D3DSAMP_BORDERCOLOR, 0),
                    lodBias: lodBiasFor(samplerState(index,
                        D3DSAMP_MIPMAPLODBIAS, 0)),
                };
                // Which arguments a stage reads decides what has to be declared
                // and uploaded for it. Getting this wrong in either direction is
                // a hard failure rather than a shading difference: a texture
                // referenced but not declared is invalid WGSL, and a uniform
                // field referenced but not in the layout reads garbage.
                // Only MULTIPLYADD and LERP read arg0, so including it
                // unconditionally would declare textures and upload constants a
                // stage never touches -- and, worse, would leave the app's stale
                // arg0 deciding what gets bound.
                const readsArg0 = op =>
                    op === D3DTOP_MULTIPLYADD || op === D3DTOP_LERP;
                const argumentsUsed = [stage.colorArg1, stage.colorArg2];
                if (stage.alphaOp !== D3DTOP_DISABLE)
                    argumentsUsed.push(stage.alphaArg1, stage.alphaArg2);
                if (readsArg0(stage.colorOp)) argumentsUsed.push(stage.colorArg0);
                if (readsArg0(stage.alphaOp)) argumentsUsed.push(stage.alphaArg0);
                const opsUsed = [stage.colorOp];
                if (stage.alphaOp !== D3DTOP_DISABLE) opsUsed.push(stage.alphaOp);
                // Support is per *channel*, not per operation: the
                // MODULATE*_ADD* family is colour-only by definition, so
                // probing it as f32 would report every legitimate use as
                // unsupported.
                const opChannels = [{ op: stage.colorOp, type: "vec3<f32>" }];
                if (stage.alphaOp !== D3DTOP_DISABLE)
                    opChannels.push({ op: stage.alphaOp, type: "f32" });
                for (const argument of argumentsUsed) {
                    switch (argument & D3DTA_SELECTMASK) {
                    case D3DTA_TEXTURE: stage.samplesTexture = true; break;
                    case D3DTA_TFACTOR: usesTextureFactor = true; break;
                    case D3DTA_CONSTANT: stage.usesConstant = true; break;
                    case D3DTA_SPECULAR: usesSpecular = true; break;
                    default: break;
                    }
                }
                // These operations read a channel of something the arguments
                // never name, so they pull in their own dependency.
                if (opsUsed.includes(D3DTOP_BLENDTEXTUREALPHA) ||
                        opsUsed.includes(D3DTOP_BLENDTEXTUREALPHAPM) ||
                        stage.colorOp === D3DTOP_DOTPRODUCT3)
                    stage.samplesTexture = stage.samplesTexture ||
                        opsUsed.includes(D3DTOP_BLENDTEXTUREALPHA) ||
                        opsUsed.includes(D3DTOP_BLENDTEXTUREALPHAPM);
                if (opsUsed.includes(D3DTOP_BLENDFACTORALPHA))
                    usesTextureFactor = true;
                if (stage.samplesTexture) {
                    const texture = this.resources.get(state.textures.get(index));
                    // A depth texture counts as nothing bound here. The fixed
                    // function cascade has no comparison reference to offer, so
                    // it takes the white fallback and viewForStage() reports
                    // why -- rather than reaching a float layout entry with a
                    // depth view, which is invalid rather than merely wrong.
                    const usable = texture && !texture.isDepth;
                    stage.textureType = usable ? (texture.textureType || "2d") : "2d";
                    stage.hasTextureBound = !!usable;
                    // DirectDraw stores four independent key kinds. Texture
                    // rendering uses SRCBLT (kind 0), the same source-domain
                    // key used by a keyed blit.  Keep the widened integer
                    // endpoints in the immutable shader signature so changing
                    // the surface key cannot reuse stale WGSL.
                    const key = usable && textureColorKeyEnabled &&
                        texture.ddColorKey && texture.ddColorKey[0];
                    stage.colorKey = key ? {
                        low: key.low >>> 0,
                        high: key.high >>> 0,
                        indexed: !!texture.ddIndexed,
                    } : null;
                }
                const transformFlags =
                    stageState(index, D3DTSS_TEXTURETRANSFORMFLAGS, 0);
                stage.transformCount = transformFlags & 0xFF;
                stage.projected = (transformFlags & D3DTTFF_PROJECTED) !== 0;
                const coordIndex = stageState(index, D3DTSS_TEXCOORDINDEX, index);
                stage.texCoordIndex = coordIndex & 0xFFFF;
                stage.tciMode = coordIndex & D3DTSS_TCI_MASK;
                for (const { op, type } of opChannels) {
                    if (op === D3DTOP_DISABLE) continue;
                    if (textureOpExpression(op, type, ["0.0", "0.0", "0.0"],
                            "0.0") === null)
                        unsupported.push("stage " + index + " asks for " +
                            "D3DTEXTUREOP " + op + " on the " +
                            (type === "f32" ? "alpha" : "colour") + " channel, " +
                            "which is outside the set fill_caps() advertises " +
                            "in TextureOpCaps");
                }
                stages.push(stage);
            }
            // D3DTOP_BUMPENVMAP couples two adjacent stages: the one that
            // declares it samples the (du, dv) map, and the one after it is
            // what actually gets displaced. Resolving that here keeps the
            // shader builder from having to look at its neighbours.
            for (let index = 0; index + 1 < stages.length; ++index) {
                const producer = stages[index];
                const consumer = stages[index + 1];
                if (producer.colorOp !== D3DTOP_BUMPENVMAP &&
                        producer.colorOp !== D3DTOP_BUMPENVMAPLUMINANCE)
                    continue;
                // The bump stage has to sample its own map for there to be a
                // displacement at all, whatever its arguments named.
                producer.samplesTexture = true;
                producer.isBumpSource = true;
                consumer.bumpFrom = producer.index;
                if (producer.colorOp === D3DTOP_BUMPENVMAPLUMINANCE)
                    consumer.bumpLuminanceFrom = producer.index;
            }
            {
                // A trailing BUMPENVMAP with no stage after it displaces
                // nothing. Say so rather than rendering a silently unbumped
                // frame that looks almost right.
                const last = stages[stages.length - 1];
                if (last && (last.colorOp === D3DTOP_BUMPENVMAP ||
                        last.colorOp === D3DTOP_BUMPENVMAPLUMINANCE))
                    unsupported.push("stage " + last.index + " asks for " +
                        "D3DTOP_BUMPENVMAP but is the last active stage, so " +
                        "no stage samples the perturbed coordinate");
            }
            // With a translated vertex shader the fixed-function coordinate
            // generation and transform never ran, so the stage reads a varying
            // the shader wrote directly, untransformed.
            //
            // *Which* varying is the open question. This reads the one
            // D3DTSS_TEXCOORDINDEX names, but D3D9 documents the opposite:
            // "When rendering using vertex shaders, each texture stage's
            // texture coordinate index must be set to its default value. The
            // default index for each stage is equal to the stage index." --
            // i.e. stage n takes oTn and TEXCOORDINDEX does not participate.
            // An app that leaves a stale non-default index (from an earlier
            // environment-mapped pass, say) therefore sends this code to a
            // varying the shader never wrote, which reads as a constant and
            // samples one texel across the whole model.
            //
            // The documented rule is the default. The diagnostic toggle can
            // still restore the legacy TEXCOORDINDEX routing when comparing a
            // capture against an older executor build.
            if (!options.fixedVertexStage) {
                for (const stage of stages) {
                    stage.coordVarying = this.debug.texcoordFromStageIndex
                        ? Math.min(stage.index, MAX_TEXCOORD_SETS - 1)
                        : Math.min(stage.texCoordIndex, MAX_TEXCOORD_SETS - 1);
                    if (stage.tciMode !== D3DTSS_TCI_PASSTHRU ||
                            stage.transformCount) {
                        unsupported.push("stage " + stage.index + " asks for " +
                            "fixed-function coordinate generation/transform " +
                            "while a vertex shader is bound, which D3D9 does " +
                            "not apply either");
                        stage.transformCount = 0;
                        stage.projected = false;
                    }
                }
            } else {
                for (const stage of stages) stage.coordVarying = stage.index;
            }
            return { stages, usesTextureFactor, usesSpecular, unsupported };
        }

        // Reads D3DRS_LIGHTING and the material/light state into the shape
        // buildFixedFunctionVertexShader() consumes, or null when the draw is
        // not lit. Each enabled light's *type* is baked into the signature so
        // the generated WGSL is a straight-line unroll with no branching and no
        // dynamic light count.
        lightingSignature(state, vertexSignature) {
            const rs = state.renderStates;
            const get = (id, fallback) => {
                const value = rs.get(id);
                return value === undefined ? fallback : value;
            };
            // Pre-transformed (XYZRHW) vertices are already lit by definition,
            // which is why D3D9 ignores lighting for them.
            if (get(D3DRS_LIGHTING, 1) === 0 ||
                    vertexSignature.positionType === "screen")
                return null;
            // D3D9 treats a missing NORMAL as the zero vector. Direct/specular
            // light terms therefore vanish, but global ambient and material
            // emissive still contribute. Do not drop the whole lighting path:
            // GTA San Andreas submits some RenderWare character batches this
            // way with a black vertex colour and a non-zero ambient material.
            // Passing that colour through unchanged makes the character a black
            // silhouette even though the scene's ambient state should light it.
            if (!vertexSignature.hasNormal) {
                ++this.stats.drawsWithZeroNormalLighting;
            }
            const lights = [];
            for (const [index, enabled] of state.lightEnabled) {
                if (!enabled) continue;
                const light = state.lights.get(index);
                if (!light) continue;
                if (lights.length >= MAX_LIGHTS) break;
                lights.push({ index, type: light.type });
            }
            // Sorted so two draws with the same set of enabled lights produce
            // the same key regardless of the order LightEnable arrived in.
            lights.sort((a, b) => a.index - b.index);
            const colorVertex = get(D3DRS_COLORVERTEX, 1) !== 0;
            return {
                lights,
                colorVertex,
                specularEnable: get(D3DRS_SPECULARENABLE, 0) !== 0,
                localViewer: get(D3DRS_LOCALVIEWER, 1) !== 0,
                diffuseSource: get(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1),
                ambientSource: get(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL),
                specularSource: get(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2),
                emissiveSource: get(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL),
            };
        }

        // Turns a declaration plus the currently bound streams into the
        // GPUVertexBufferLayout array a pipeline needs, using `locationFor` to
        // decide which shader input (if any) each element feeds. One function
        // serves both stages: the fixed-function stage passes its semantic
        // table, a translated shader passes a lookup over its own dcl'd
        // inputs. Elements no shader input consumes are simply left out --
        // they still occupy bytes in the vertex, but the stride comes from
        // SetStreamSource, never from summing the elements.
        // (0, 0, 0, 1): what a vertex shader input no stream supplies reads
        defaultAttributeBuffer() {
            if (!this.defaultAttributes) {
                this.defaultAttributes = this.device.createBuffer({ size: 16,
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST });
                this.device.queue.writeBuffer(this.defaultAttributes, 0, new Float32Array([0, 0, 0, 1]));
            }
            return this.defaultAttributes;
        }

        vertexBufferLayoutsFor(elements, state, locationFor, instanceData) {
            const perStream = new Map();
            for (const element of elements) {
                const location = locationFor(element);
                if (location < 0) continue;
                const format = DECLTYPE_FORMATS[element.type];
                if (!format) {
                    this.warnOnce("decltype-" + element.type,
                        "unsupported D3DDECLTYPE " + element.type +
                        "; the attribute is dropped from the vertex layout");
                    continue;
                }
                const stream = state.streams.get(element.stream);
                if (!stream || !stream.stride) continue;
                let entry = perStream.get(element.stream);
                if (!entry) {
                    const frequency = (stream.frequency ?? 1) >>> 0;
                    const instanced =
                        (frequency & D3DSTREAMSOURCE_INSTANCEDATA) !== 0;
                    entry = { stream: element.stream, arrayStride: stream.stride,
                        stepMode: instanceData || instanced ? "instance" : "vertex",
                        attributes: [] };
                    perStream.set(element.stream, entry);
                }
                entry.attributes.push({ shaderLocation: location,
                    offset: element.byteOffset, format: format[0] });
            }
            // Sorted so the slot a buffer binds to is a stable function of the
            // declaration, which keeps the pipeline cache key stable too.
            const layouts = Array.from(perStream.values())
                .sort((a, b) => a.stream - b.stream);
            if (layouts.length > MAX_VERTEX_BUFFERS_PER_DRAW) {
                // Truncating here would drop whole attributes and render
                // wrong-but-plausible geometry, which is the failure mode
                // hardest to attribute. Name it instead.
                this.warnOnce("vertex-buffer-limit",
                    "this declaration spreads its attributes over " +
                    layouts.length + " streams, and WebGPU binds at most " +
                    MAX_VERTEX_BUFFERS_PER_DRAW + " vertex buffers per draw; " +
                    "the draw is skipped rather than drawn with missing " +
                    "attributes");
                return null;
            }
            for (const layout of layouts)
                layout.attributes.sort((a, b) => a.shaderLocation - b.shaderLocation);
            return layouts;
        }

        onCreateVertexDeclaration(bytes, view, offset, length) {
            const handle = view.getUint32(offset + 4, true);
            const count = view.getUint32(offset + 8, true);
            const elements = this.decodeVertexElements(bytes, view, offset + 16, count);
            this.resources.set(handle,
                { kind: RESOURCE_VERTEX_DECLARATION, elements });
        }

        onSetVertexDeclaration(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const declarationHandle = view.getUint32(offset + 4, true);
            const state = this.deviceState(deviceHandle);
            state.vertexDeclarationHandle = declarationHandle;
            state.fvfElements = null;
        }

        onSetFVF(bytes, view, offset, length) {
            const deviceHandle = view.getUint32(offset, true);
            const count = view.getUint32(offset + 8, true);
            const state = this.deviceState(deviceHandle);
            state.fvfElements = this.decodeVertexElements(bytes, view, offset + 16, count);
            // Kept only so a diagnostic can say which FVF produced a
            // declaration; nothing in the render path reads it, because the
            // guest already expanded it into the element shape above.
            state.fvf = view.getUint32(offset + 4, true);
            state.vertexDeclarationHandle = 0;
        }

        // The declaration in force, whether it arrived as a real
        // IDirect3DVertexDeclaration9 or as an FVF the guest expanded into the
        // same element shape (plan 4.3 -- the host has exactly one
        // vertex-layout code path).
        currentElements(state) {
            if (state.fvfElements) return state.fvfElements;
            const declaration = this.resources.get(state.vertexDeclarationHandle);
            return declaration ? declaration.elements : null;
        }

        onSetRenderState(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const stateId = view.getUint32(offset + 4, true);
            const value = view.getUint32(offset + 8, true);
            this.deviceState(deviceHandle).renderStates.set(stateId, value);
            this.noteUnreadState("renderState", CONSUMED_RENDER_STATES, stateId);
            if (stateId === D3DRS_SRGBWRITEENABLE && value !== 0) {
                ++this.stats.srgbWriteRequests;
            }
            // D3DRS_WRAP0..15. Named rather than left in the passive
            // unread-state list because it has a specific, recognisable
            // symptom -- a seam across cylindrically or spherically mapped
            // geometry where the coordinate crosses 0/1 -- and because it is
            // the rare gap with no route inside this host renderer: the wrap
            // decision is made per *triangle*, by comparing its three vertices'
            // coordinates, and WebGPU has no stage that sees a whole primitive.
            // The D3D7 frontend handles this before the wire while it still owns
            // the source vertices; a WRAP state reaching here came through a
            // frontend that cannot do that preprocessing.
            if (stateId >= D3DRS_WRAP0 && stateId <= D3DRS_WRAP7 && value !== 0)
                this.warnOnce("render-state-wrap",
                    "D3DRS_WRAP" + (stateId - D3DRS_WRAP0) + " asks for " +
                    "shortest-path texture coordinate interpolation, which " +
                    "is a per-primitive decision WebGPU has no stage to make; " +
                    "coordinates interpolate linearly and a seam may appear " +
                    "where they cross 0 or 1", { state: stateId, value });
        }

        // Every state the guest sends that nothing here reads. This exists
        // because the expensive failures on this path have all been silent ones:
        // a state the app clearly cares about (it would not call Set otherwise)
        // that the renderer never looks at produces a picture that is wrong in a
        // plausible way, with nothing anywhere saying so. Listing them turns
        // "why does this look wrong" into a finite list to work through.
        //
        // Bounded by construction: it records ids, not occurrences, and there
        // are only a few hundred possible ids.
        noteUnreadState(kind, consumed, stateId) {
            if (consumed.has(stateId)) return;
            const key = kind + "s";
            if (!this.unreadStates) this.unreadStates = {};
            const seen = this.unreadStates[key] || (this.unreadStates[key] = new Set());
            if (seen.has(stateId)) return;
            seen.add(stateId);
            this.stats.unreadStateIds = Object.keys(this.unreadStates)
                .reduce((out, name) => {
                    out[name] = [...this.unreadStates[name]].sort((a, b) => a - b);
                    return out;
                }, {});
        }

        onSetTextureStageState(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const stage = view.getUint32(offset + 4, true);
            const stateId = view.getUint32(offset + 8, true);
            const value = view.getUint32(offset + 12, true);
            this.deviceState(deviceHandle).textureStageStates.set(stage * 64 + stateId, value);
        }

        onSetTexture(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const stage = view.getUint32(offset + 4, true);
            const textureHandle = view.getUint32(offset + 8, true);
            this.deviceState(deviceHandle).textures.set(stage, textureHandle);
        }

        // Stored to keep host state honest with the guest's D9WGSetSamplerState/
        // D9WGSetMaterial/D9WGSetLight/D9WGLightEnable emitters (d3d9_proxy.c),
        // but not yet read anywhere in pipelineFor()/recordDraw() -- M1's fixed
        // shader always uses one hardcoded default sampler and never applies
        // lighting math. Real consumption is M2 (sampler variants, 4.4/12) and
        // M2/M3 (lighting) work.
        onSetSamplerState(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const sampler = view.getUint32(offset + 4, true);
            const stateId = view.getUint32(offset + 8, true);
            this.noteUnreadState("samplerState", CONSUMED_SAMPLER_STATES, stateId);
            const value = view.getUint32(offset + 12, true);
            this.deviceState(deviceHandle).samplerStates.set(sampler * 64 + stateId, value);
        }

        onSetMaterial(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const readVec4 = base => [
                view.getFloat32(base, true), view.getFloat32(base + 4, true),
                view.getFloat32(base + 8, true), view.getFloat32(base + 12, true),
            ];
            this.deviceState(deviceHandle).material = {
                diffuse: readVec4(offset + 4), ambient: readVec4(offset + 20),
                specular: readVec4(offset + 36), emissive: readVec4(offset + 52),
                power: view.getFloat32(offset + 68, true),
            };
        }

        onSetLight(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const index = view.getUint32(offset + 4, true);
            const readVec = (base, count) => {
                const out = [];
                for (let i = 0; i < count; ++i) out.push(view.getFloat32(base + i * 4, true));
                return out;
            };
            this.deviceState(deviceHandle).lights.set(index, {
                type: view.getUint32(offset + 8, true),
                diffuse: readVec(offset + 12, 4), specular: readVec(offset + 28, 4),
                ambient: readVec(offset + 44, 4), position: readVec(offset + 60, 3),
                direction: readVec(offset + 72, 3), range: view.getFloat32(offset + 84, true),
                falloff: view.getFloat32(offset + 88, true),
                attenuation: readVec(offset + 92, 3),
                theta: view.getFloat32(offset + 104, true), phi: view.getFloat32(offset + 108, true),
            });
        }

        onLightEnable(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const index = view.getUint32(offset + 4, true);
            const enable = view.getUint32(offset + 8, true) !== 0;
            this.deviceState(deviceHandle).lightEnabled.set(index, enable);
        }

        onSetViewport(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const state = this.deviceState(deviceHandle);
            // MinZ/MaxZ have been on the wire since M1 (D9WGSetViewport) and
            // used to be dropped here, with recordDraw hardcoding 0..1 into
            // setViewport. D3D9's viewport depth range is not decoration: an app
            // that composites a 3D object into a 2D panel routinely restricts it
            // so the object cannot collide in depth with the interface around
            // it, and discarding that puts the object at its natural depth --
            // where whatever the app expected to be in front of it no longer is.
            const minZ = view.getFloat32(offset + 20, true);
            const maxZ = view.getFloat32(offset + 24, true);
            state.viewport = {
                x: view.getUint32(offset + 4, true),
                y: view.getUint32(offset + 8, true),
                width: view.getUint32(offset + 12, true),
                height: view.getUint32(offset + 16, true),
                // A device that never calls SetViewport, and any guest that
                // sends zeros, still has to mean the D3D9 default range.
                minZ: Number.isFinite(minZ) ? minZ : 0,
                maxZ: Number.isFinite(maxZ) && maxZ !== 0 ? maxZ : 1,
            };
        }

        onSetTransform(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const transformState = view.getUint32(offset + 4, true);
            const matrix = new Float32Array(16);
            for (let i = 0; i < 16; ++i) matrix[i] = view.getFloat32(offset + 8 + i * 4, true);
            // Stored exactly as D3D sent it (row-major, row-vector
            // convention). No transpose here -- see uniformBufferFor for why
            // none is needed anywhere on this path.
            const state = this.deviceState(deviceHandle);
            state.transforms.set(transformState, matrix);
            if (transformState > D3DTS_WORLD &&
                    transformState < D3DTS_WORLD + MAX_WORLD_MATRICES) {
                state.maxWorldMatrixIndex = Math.max(state.maxWorldMatrixIndex,
                    transformState - D3DTS_WORLD);
            }
        }

        onSetClipPlane(bytes, view, offset, length) {
            if (length < 24) return;
            const state = this.deviceState(view.getUint32(offset, true));
            const index = view.getUint32(offset + 4, true);
            if (index >= 6) return;
            state.clipPlanes[index] = [
                view.getFloat32(offset + 8, true),
                view.getFloat32(offset + 12, true),
                view.getFloat32(offset + 16, true),
                view.getFloat32(offset + 20, true),
            ];
        }

        onSetStreamSource(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const stream = view.getUint32(offset + 4, true);
            const bufferHandle = view.getUint32(offset + 8, true);
            const stride = view.getUint32(offset + 12, true);
            const offsetInBytes = view.getUint32(offset + 16, true);
            const state = this.deviceState(deviceHandle);
            const previous = state.streams.get(stream);
            state.streams.set(stream, { bufferHandle, stride, offsetInBytes,
                frequency: previous ? (previous.frequency ?? 1) : 1 });
        }

        onSetStreamSourceFreq(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const stream = view.getUint32(offset + 4, true);
            const frequency = view.getUint32(offset + 8, true);
            const state = this.deviceState(deviceHandle);
            const previous = state.streams.get(stream) || {
                bufferHandle: 0, stride: 0, offsetInBytes: 0,
            };
            state.streams.set(stream, { ...previous, frequency });
        }

        onSetIndices(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const bufferHandle = view.getUint32(offset + 4, true);
            this.deviceState(deviceHandle).indexBufferHandle = bufferHandle;
        }

        // ---- programmable shaders (M2) ----

        // Translation happens here, at CREATE time, and never on a draw path
        // (plan 4.2): a shader first used mid-frame would otherwise produce an
        // unattributable latency spike. A shader this build cannot translate
        // is stored with its error rather than dropped -- recordDraw() then
        // skips draws that bind it and counts them, which is the difference
        // between "this shader is unsupported" and "the game stopped drawing".
        async onCreateShader(bytes, view, offset, kind) {
            const handle = view.getUint32(offset + 4, true);
            const tokenCount = view.getUint32(offset + 8, true);
            const codeOffset = view.getUint32(offset + 12, true);
            const suppliedHashLow = view.getUint32(offset + 16, true);
            const suppliedHashHigh = view.getUint32(offset + 20, true);
            if (codeOffset + tokenCount * 4 > bytes.byteLength) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG shader bytecode overruns the batch");
            }
            // The DMA blob is not 4-byte aligned within `bytes` in general,
            // so copy rather than aliasing a Uint32Array onto it.
            const tokens = new Uint32Array(tokenCount);
            for (let i = 0; i < tokenCount; ++i)
                tokens[i] = view.getUint32(codeOffset + i * 4, true);
            // Hashes are a cache hint carried by an untrusted guest. Verify
            // them from the bytecode so an old or buggy proxy cannot alias
            // every shader to the same cached translation (the original D3D8
            // proxy sent zero for both fields).
            const verifiedHash = shaderPipeline.hashTokens(tokens);
            const hashLow = verifiedHash.low;
            const hashHigh = verifiedHash.high;
            if (hashLow !== suppliedHashLow || hashHigh !== suppliedHashHigh) {
                this.warnOnce("shader-hash-mismatch-" + kind,
                    "guest shader bytecode hash did not match its token " +
                    "stream; using the verified hash to prevent distinct " +
                    "shaders from aliasing in the translation cache", {
                        kind: kind === RESOURCE_VERTEX_SHADER
                            ? "vertex" : "pixel",
                        suppliedHashLow,
                        suppliedHashHigh,
                        verifiedHashLow: hashLow,
                        verifiedHashHigh: hashHigh,
                    });
            }
            const compilesBefore = this.shaderCache.stats.compiles;
            let translated = this.shaderCache.get(hashLow, hashHigh);
            if (!translated) {
                const started = typeof performance !== "undefined" && performance.now
                    ? performance.now() : Date.now();
                const workerCompile = this.compileShaderInWorker(tokens);
                if (workerCompile) {
                    try {
                        translated = await workerCompile;
                        if (!translated || typeof translated.ok !== "boolean")
                            throw new Error("shader worker returned an invalid result");
                        ++this.stats.shaderWorkerCompiles;
                        const ended = typeof performance !== "undefined" && performance.now
                            ? performance.now() : Date.now();
                        translated = this.shaderCache.store(hashLow, hashHigh,
                            translated, ended - started);
                    } catch (error) {
                        ++this.stats.shaderWorkerFallbacks;
                        this.warnOnce("shader-worker-runtime",
                            "shader compile Worker failed; falling back to the " +
                            "executor thread", { message: String(error) });
                        translated = this.shaderCache.compile(tokens,
                            hashLow, hashHigh);
                    }
                } else {
                    translated = this.shaderCache.compile(tokens,
                        hashLow, hashHigh);
                }
            }
            if (this.shaderCache.stats.compiles !== compilesBefore)
                this.shaderCacheDirty = true;
            if (translated.ok) ++this.stats.shadersTranslated;
            else {
                ++this.stats.shaderTranslationFailures;
                this.warnOnce("shader-translate-" + hashHigh + "-" + hashLow,
                    "cannot translate a " + (kind === RESOURCE_VERTEX_SHADER
                        ? "vertex" : "pixel") + " shader; draws that bind it " +
                    "will be skipped: " + translated.error);
            }
            this.resources.set(handle, {
                kind, tokens, hashLow, hashHigh,
                translated,
                // Variant key -> {translated, module}. A vertex shader needs
                // one variant per set of D3DCOLOR input locations; in practice
                // that is a single entry, because a given shader is used with
                // one vertex format.
                variants: new Map(),
            });
        }

        onCreateVertexShader(bytes, view, offset) {
            return this.onCreateShader(bytes, view, offset, RESOURCE_VERTEX_SHADER);
        }

        onCreatePixelShader(bytes, view, offset) {
            return this.onCreateShader(bytes, view, offset, RESOURCE_PIXEL_SHADER);
        }

        onSetVertexShader(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            state.vertexShaderHandle = view.getUint32(offset + 4, true);
        }

        onSetPixelShader(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            state.pixelShaderHandle = view.getUint32(offset + 4, true);
        }

        // Shared decode for all six SET_*_SHADER_CONSTANT_* opcodes: they use
        // one payload shape and differ only in the destination array and how
        // wide a register is on the wire (float4/int4 = 16 bytes, bool = 4).
        applyConstants(bytes, view, offset, target, componentsPerRegister, read) {
            const startRegister = view.getUint32(offset + 4, true);
            const vectorCount = view.getUint32(offset + 8, true);
            const dataOffset = view.getUint32(offset + 12, true);
            const stride = componentsPerRegister * 4;
            if (dataOffset + vectorCount * stride > bytes.byteLength) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG shader constant data overruns the batch");
            }
            const capacity = target.length / componentsPerRegister;
            if (startRegister >= capacity) return;
            const count = Math.min(vectorCount, capacity - startRegister);
            for (let i = 0; i < count; ++i) {
                const base = dataOffset + i * stride;
                const destination = (startRegister + i) * componentsPerRegister;
                for (let c = 0; c < componentsPerRegister; ++c)
                    target[destination + c] = read(base + c * 4);
            }
        }

        onSetVertexShaderConstantF(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.vsConstF, 4,
                at => view.getFloat32(at, true));
        }

        onSetPixelShaderConstantF(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.psConstF, 4,
                at => view.getFloat32(at, true));
        }

        onSetVertexShaderConstantI(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.vsConstI, 4,
                at => view.getInt32(at, true));
        }

        onSetPixelShaderConstantI(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.psConstI, 4,
                at => view.getInt32(at, true));
        }

        onSetVertexShaderConstantB(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.vsConstB, 1,
                at => view.getUint32(at, true));
        }

        onSetPixelShaderConstantB(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            this.applyConstants(bytes, view, offset, state.psConstB, 1,
                at => view.getUint32(at, true));
        }

        // ---- D3D9 hardware cursor ----
        //
        // A fullscreen D3D9 game draws its pointer through SetCursorProperties
        // rather than GDI, so it never reaches the VGA framebuffer the page
        // composites under this canvas -- and the page hides the browser
        // cursor. Without this the pointer is invisible even though input
        // still works, which makes the game effectively unplayable.
        onSetCursorProperties(bytes, view, offset) {
            const width = view.getUint32(offset + 12, true);
            const height = view.getUint32(offset + 16, true);
            const dataBytes = view.getUint32(offset + 20, true);
            const dataOffset = view.getUint32(offset + 24, true);
            if (!width || !height) return;
            if (dataOffset + dataBytes > bytes.byteLength) {
                ++this.stats.malformedBatches;
                throw new D9WGStreamError("D9WG cursor bitmap overruns the batch");
            }
            this.cursor.hotspotX = view.getUint32(offset + 4, true);
            this.cursor.hotspotY = view.getUint32(offset + 8, true);
            if (this.cursor.width !== width || this.cursor.height !== height ||
                    !this.cursor.texture) {
                this.retireGPUObject(this.cursor.texture);
                this.cursor.texture = this.device.createTexture({
                    label: "D3D9 hardware cursor",
                    size: { width, height, depthOrArrayLayers: 1 },
                    format: "rgba8unorm",
                    usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
                });
                this.cursor.view = this.cursor.texture.createView();
                this.cursor.width = width;
                this.cursor.height = height;
            }
            // The guest sends A8R8G8B8 at a tight width*4 stride; the same
            // BGRA-to-RGBA reorder every other texture upload does.
            const source = new Uint8Array(bytes.buffer,
                bytes.byteOffset + dataOffset, dataBytes);
            const rgba = new Uint8Array(width * height * 4);
            for (let row = 0; row < height; ++row)
                expandRowToGPU(D3DFMT_A8R8G8B8, source, row * width * 4,
                    width, rgba, row * width * 4);
            this.device.queue.writeTexture({ texture: this.cursor.texture },
                rgba, { bytesPerRow: width * 4, rowsPerImage: height },
                { width, height, depthOrArrayLayers: 1 });
            ++this.stats.cursorUploads;
        }

        onSetCursorPosition(bytes, view, offset) {
            this.cursor.x = view.getInt32(offset + 4, true);
            this.cursor.y = view.getInt32(offset + 8, true);
        }

        onShowCursor(bytes, view, offset) {
            this.cursor.visible = view.getUint32(offset + 4, true) !== 0;
        }

        // Moves the overlay to match a WINDOW_STATE report.
        //
        // Deliberately conservative about what counts as a real move. The
        // report also arrives for foreground changes and other events that say
        // nothing about geometry, and a 0x0 client area is the same
        // fullscreen GetClientRect artefact onPresent() already guards
        // against -- letting either through makes the canvas flicker between
        // the real size and nothing.
        //
        // Covered windows are not hidden ones. Other windows lying over all
        // or part of the device window (occluded, visibleRegion) is state the
        // surface keeps until the next report changes it -- a Present in
        // between does not uncover anything -- and the embedder shows the
        // picture only where the guest's screen shows the window.
        applyWindowStateGeometry(deviceHandle, report) {
            if (!deviceHandle) return;
            const state = this.devices.get(deviceHandle);
            if (!state) return;
            const hidden = !report.isWindow || report.iconic || !report.visible;
            if (hidden) {
                // Visibility is tracked per device; the canvas is one shared
                // thing. Those disagree the moment anything else puts the
                // canvas back on screen -- a CreateDevice for the same
                // session does exactly that -- and this device's own flag
                // still reads false from an earlier report. Skipping the
                // notification as redundant then drops the one message that
                // would have taken the canvas down.
                //
                // A no-surface report is a teardown signal rather than a
                // geometry update, so it is never redundant: it is the last
                // thing an exiting process says, and if it is dropped its
                // final frame stays composited over the guest's desktop with
                // nothing left running to remove it.
                if (state.surface.visible === false && !report.noSurface)
                    return;
                if (report.noSurface) {
                    state.ddScreenWriteRect = null;
                    state.surface = { ...state.surface, clipRect: null };
                }
                state.surface = { ...state.surface, visible: false,
                    noSurface: !!report.noSurface };
                ++this.stats.surfaceChanges;
                this.notifySurface(state, "window-state");
                return;
            }
            const width = report.clientWidth || state.surface.width;
            const height = report.clientHeight || state.surface.height;
            if (!width || !height) {
                ++this.stats.emptySurfaceReports;
                return;
            }
            const occluded = !!report.occluded;
            const visibleRegion = report.visibleRegion || null;
            const changed = state.surface.hwnd !== report.hwnd ||
                state.surface.x !== report.windowX ||
                state.surface.y !== report.windowY ||
                state.surface.width !== width ||
                state.surface.height !== height ||
                state.surface.visible === false ||
                !!state.surface.occluded !== occluded ||
                !sameVisibleRegion(state.surface.visibleRegion || null, visibleRegion);
            if (!changed) return;
            state.surface = { ...state.surface, hwnd: report.hwnd,
                x: report.windowX, y: report.windowY, width, height,
                visible: true, noSurface: false, occluded, visibleRegion };
            ++this.stats.surfaceChanges;
            this.notifySurface(state, "window-state");
        }

        // Two jobs. The diagnostic one is why the opcode exists: see
        // D9WG_OP_WINDOW_STATE in d3d9_protocol.h for why the guest's
        // window-manager view has to be reported rather than inferred.
        //
        // The second is placement, and it exists for the D3D8 frontend. A
        // D3D9 title presents continuously, so onPresent() is a fine source of
        // truth for where the overlay goes. A D3D8 title need not: one that
        // draws a single frame and then only pumps messages still has to have
        // the overlay follow its window, and there is no further Present to
        // carry the geometry. d3d8_proxy.c sends this record on move/size/show
        // for exactly that reason.
        onWindowState(bytes, view, offset, length) {
            const flags = view.getUint32(offset + 12, true);
            const deviceHandle = view.getUint32(offset, true);
            const state = {
                hwnd: view.getUint32(offset + 4, true),
                foregroundHwnd: view.getUint32(offset + 8, true),
                isWindow: (flags & D9WG_WINDOW_IS_WINDOW) !== 0,
                visible: (flags & D9WG_WINDOW_VISIBLE) !== 0,
                iconic: (flags & D9WG_WINDOW_ICONIC) !== 0,
                foreground: (flags & D9WG_WINDOW_FOREGROUND) !== 0,
                fullscreen: (flags & D9WG_WINDOW_FULLSCREEN) !== 0,
                windowX: view.getInt32(offset + 16, true),
                windowY: view.getInt32(offset + 20, true),
                windowWidth: view.getUint32(offset + 24, true),
                windowHeight: view.getUint32(offset + 28, true),
                clientWidth: view.getUint32(offset + 32, true),
                clientHeight: view.getUint32(offset + 36, true),
                // "I have nothing to show", which is not the same claim as
                // "my window is gone": the window may be up and taking input.
                noSurface: (flags & D9WG_WINDOW_NO_SURFACE) !== 0,
                occluded: (flags & D9WG_WINDOW_OCCLUDED) !== 0,
                visibleRegion: null,
            };
            if (flags & D9WG_WINDOW_REGION) {
                state.visibleRegion = readVisibleRegion(view, offset + D9WG_WINDOW_STATE_BYTES,
                    (length === undefined ? D9WG_WINDOW_STATE_BYTES : length) - D9WG_WINDOW_STATE_BYTES,
                    state.clientWidth, state.clientHeight, state.windowX, state.windowY);
                if (state.visibleRegion) ++this.stats.windowRegionReports;
            }
            this.windowState = state;
            ++this.stats.windowStateChanges;
            this.applyWindowStateGeometry(deviceHandle, state);
            // A device that says it has nothing to present is not describing a
            // window problem, and the two diagnostics below are about window
            // problems: they would report broken input for a title that is
            // simply done drawing.
            if (state.noSurface) return;
            // Covered by another of the guest's windows, which then rightly
            // has the foreground and the input: not a window problem either
            if (state.occluded) {
                ++this.stats.windowOccludedReports;
                return;
            }
            if (!state.foreground) {
                ++this.stats.windowNotForegroundReports;
                // The guest re-takes the foreground for a fullscreen device
                // (maintain_fullscreen_foreground in d3d9_proxy.c), so a single
                // report of this at startup is normal and self-healing. Repeated
                // reports mean the claim is being refused, which is worth saying
                // out loud: the picture looks perfect either way and every click
                // goes somewhere else, so there is nothing on screen to notice.
                if (this.stats.windowNotForegroundReports > 1)
                    this.warnOnce("window-not-foreground",
                        "the game's window keeps losing the guest's foreground " +
                        "even though the guest re-claims it, so clicks go to " +
                        "whatever is on top -- the overlay still shows this " +
                        "game's frames either way. Check getStats().window",
                        state);
            }
            if (state.iconic || !state.visible)
                this.warnOnce("window-not-visible",
                    "the game's window is minimised or hidden in the guest; " +
                    "input will not reach it", state);
        }

        // A self-contained screen-space quad, built once. It deliberately does
        // not go through programFor()/pipelineFor(): the cursor is host-owned
        // compositing, not a guest draw, and giving it its own trivial
        // pipeline keeps it out of the caches keyed on guest state.
        ensureCursorPipeline() {
            if (this.cursor.pipeline) return this.cursor.pipeline;
            const module = this.device.createShaderModule({
                label: "D3D9 cursor",
                code: `
struct CursorRect { origin: vec2<f32>, size: vec2<f32> };
@group(0) @binding(0) var<uniform> rect: CursorRect;
@group(0) @binding(1) var cursor_texture: texture_2d<f32>;
@group(0) @binding(2) var cursor_sampler: sampler;

struct VSOut {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> VSOut {
    // Two triangles covering the cursor's rectangle, in normalised
    // back-buffer space supplied by the uniform.
    var corners = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));
    let corner = corners[index];
    let position = rect.origin + corner * rect.size;
    var out: VSOut;
    out.position = vec4<f32>(position.x * 2.0 - 1.0,
        1.0 - position.y * 2.0, 0.0, 1.0);
    out.uv = corner;
    return out;
}

@fragment
fn fs_main(in: VSOut) -> @location(0) vec4<f32> {
    return textureSample(cursor_texture, cursor_sampler, in.uv);
}
`,
            });
            const bindGroupLayout = this.device.createBindGroupLayout({
                entries: [
                    { binding: 0, visibility: SHADER_STAGE_VERTEX, buffer: { type: "uniform" } },
                    { binding: 1, visibility: SHADER_STAGE_FRAGMENT, texture: {} },
                    { binding: 2, visibility: SHADER_STAGE_FRAGMENT, sampler: {} },
                ],
            });
            this.cursor.bindGroupLayout = bindGroupLayout;
            this.cursor.sampler = this.device.createSampler({
                magFilter: "nearest", minFilter: "nearest",
                addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge",
            });
            this.cursor.uniform = this.device.createBuffer({
                label: "D3D9 cursor rect", size: 16,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            this.cursor.pipeline = this.device.createRenderPipeline({
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: { module, entryPoint: "vs_main" },
                fragment: { module, entryPoint: "fs_main", targets: [{
                    format: this.format,
                    // Straight alpha: a cursor bitmap's transparent texels
                    // must not paint over the frame.
                    blend: {
                        color: { srcFactor: "src-alpha",
                                 dstFactor: "one-minus-src-alpha", operation: "add" },
                        alpha: { srcFactor: "one",
                                 dstFactor: "one-minus-src-alpha", operation: "add" },
                    },
                }] },
                primitive: { topology: "triangle-list" },
            });
            return this.cursor.pipeline;
        }

        // Drawn last, in its own depth-less pass, so it sits on top of the
        // frame regardless of what the game left in the depth buffer.
        drawCursor(encoder, targetView, width, height) {
            const cursor = this.cursor;
            if (!cursor.visible || !cursor.view || !width || !height) return;
            const pipeline = this.ensureCursorPipeline();
            const originX = (cursor.x - cursor.hotspotX) / width;
            const originY = (cursor.y - cursor.hotspotY) / height;
            this.device.queue.writeBuffer(cursor.uniform, 0, new Float32Array([
                originX, originY, cursor.width / width, cursor.height / height,
            ]));
            const bindGroup = this.device.createBindGroup({
                layout: cursor.bindGroupLayout,
                entries: [
                    { binding: 0, resource: { buffer: cursor.uniform } },
                    { binding: 1, resource: cursor.view },
                    { binding: 2, resource: cursor.sampler },
                ],
            });
            const pass = encoder.beginRenderPass({
                colorAttachments: [{ view: targetView, loadOp: "load", storeOp: "store" }],
            });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, bindGroup);
            pass.draw(6);
            pass.end();
            ++this.stats.cursorDraws;
        }

        // GPUShaderModules are content-addressed by their WGSL text, so two
        // shaders that translate identically (or the same shader re-created
        // after a Reset) share one module. Compilation diagnostics are checked
        // asynchronously -- createShaderModule() never throws on bad WGSL, and
        // plan 9.6 requires the getCompilationInfo() check rather than
        // assuming successful translation implies valid output.
        moduleFor(wgsl, label) {
            let module = this.moduleCache.get(wgsl);
            if (module) return module;
            module = this.device.createShaderModule({ label, code: wgsl });
            ++this.stats.shaderModulesCreated;
            this.moduleCache.set(wgsl, module);
            if (typeof module.getCompilationInfo === "function") {
                module.getCompilationInfo().then(info => {
                    const errors = (info.messages || [])
                        .filter(message => message.type === "error");
                    if (!errors.length) return;
                    module._d9wgBroken = true;
                    this.stats.shaderCompileErrors += errors.length;
                    console.error("[d3d9-webgpu] WGSL compilation failed for " +
                        label, errors.map(e => e.lineNum + ":" + e.linePos +
                            " " + e.message), wgsl);
                }, () => {});
            }
            return module;
        }

        // ---- draw pipeline ----

        // Distils the render states a WebGPU render pipeline is allowed to
        // depend on into a small plain object. WebGPU bakes depth/blend/cull
        // into the immutable pipeline (unlike D3D9, where they are free-
        // floating device state), so this is also exactly the set that has
        // to participate in the pipeline cache key.
        pipelineStateFor(state, targets) {
            const rs = state.renderStates;
            const hasDepth = targets ? targets.hasDepth : !!state.hasDepth;
            const forceSolid = !!this.debug.forceSolidAllDraws;
            const get = (id, fallback) => {
                const value = rs.get(id);
                return value === undefined ? fallback : value;
            };

            // D3DRS_ZENABLE defaults to on whenever a depth buffer exists;
            // with no depth attachment there is nothing to test against.
            const depthEnabled = !forceSolid && hasDepth
                && get(D3DRS_ZENABLE, 1) !== D3DZB_FALSE;
            const depthWrite = !forceSolid &&
                get(D3DRS_ZWRITEENABLE, 1) !== 0;
            const depthCompare = (forceSolid || this.debug.disableDepthTest)
                ? "always"
                : (COMPARE_FUNCS[get(D3DRS_ZFUNC, 4)] || "less-equal");

            const blendEnabled = !forceSolid &&
                get(D3DRS_ALPHABLENDENABLE, 0) !== 0;
            const resolveBlend = (rawSrc, rawDst) => {
                // The legacy BOTH* source values override both halves of the
                // pair. D3D9 exposes them as one enum; WebGPU exposes the two
                // factors separately, so the mapping is exact once resolved.
                if (rawSrc === 12)
                    return { src: "src-alpha", dst: "one-minus-src-alpha",
                        valid: true };
                if (rawSrc === 13)
                    return { src: "one-minus-src-alpha", dst: "src-alpha",
                        valid: true };
                return { src: BLEND_FACTORS[rawSrc], dst: BLEND_FACTORS[rawDst],
                    valid: !!BLEND_FACTORS[rawSrc] && !!BLEND_FACTORS[rawDst] };
            };
            // D3D9 starts at ONE/ZERO.  Using SRCALPHA/INVSRCALPHA here was
            // mostly hidden while blending stayed disabled, but it changes an
            // app that enables blending before choosing new factors from an
            // overwrite into a translucent UI/overlay pass.
            const rawColorSrc = get(D3DRS_SRCBLEND, 2);
            const rawColorDst = get(D3DRS_DESTBLEND, 1);
            const rawColorOp = get(D3DRS_BLENDOP, 1);
            const colorBlend = resolveBlend(rawColorSrc, rawColorDst);
            const separateAlpha =
                get(D3DRS_SEPARATEALPHABLENDENABLE, 0) !== 0;
            const rawAlphaSrc = separateAlpha
                ? get(D3DRS_SRCBLENDALPHA, 2) : rawColorSrc;
            const rawAlphaDst = separateAlpha
                ? get(D3DRS_DESTBLENDALPHA, 1) : rawColorDst;
            const rawAlphaOp = separateAlpha
                ? get(D3DRS_BLENDOPALPHA, 1) : rawColorOp;
            const alphaBlend = separateAlpha
                ? resolveBlend(rawAlphaSrc, rawAlphaDst) : colorBlend;
            const srcFactor = colorBlend.src || "src-alpha";
            const dstFactor = colorBlend.dst || "one-minus-src-alpha";
            const blendOp = BLEND_OPS[rawColorOp] || "add";
            const alphaSrcFactor = alphaBlend.src || "one";
            const alphaDstFactor = alphaBlend.dst || "zero";
            const alphaBlendOp = BLEND_OPS[rawAlphaOp] || "add";
            if (blendEnabled && (!colorBlend.valid || !alphaBlend.valid ||
                    !BLEND_OPS[rawColorOp] || !BLEND_OPS[rawAlphaOp])) {
                ++this.stats.drawsWithUnmappedBlend;
                this.warnOnce("unmapped-blend-" + [rawColorSrc, rawColorDst,
                    rawColorOp, rawAlphaSrc, rawAlphaDst, rawAlphaOp].join("-"),
                    "a draw asks for a blend mode with no WebGPU equivalent; " +
                    "it silently falls back to src-alpha/inv-src-alpha, which " +
                    "renders as plausible-but-wrong compositing", {
                        D3DRS_SRCBLEND: rawColorSrc, mappedSrc: colorBlend.src,
                        D3DRS_DESTBLEND: rawColorDst, mappedDst: colorBlend.dst,
                        D3DRS_BLENDOP: rawColorOp, mappedOp: BLEND_OPS[rawColorOp],
                    });
            }
            const blendColor = get(D3DRS_BLENDFACTOR, 0xffffffff) >>> 0;
            const blendConstant = {
                r: ((blendColor >>> 16) & 0xff) / 255,
                g: ((blendColor >>> 8) & 0xff) / 255,
                b: (blendColor & 0xff) / 255,
                a: ((blendColor >>> 24) & 0xff) / 255,
            };

            // D3D9 stores both bias states as float bit patterns in DWORDs.
            // Its constant bias is in normalised depth units; depth24 WebGPU
            // expresses the same offset in one-ULP integer steps.
            const rawDepthBias = floatFromDWORD(get(D3DRS_DEPTHBIAS, 0));
            const scaledDepthBias = Number.isFinite(rawDepthBias)
                ? Math.round(rawDepthBias * 0x1000000) : 0;
            const depthBias = Math.max(-0x80000000,
                Math.min(0x7fffffff, scaledDepthBias));
            const rawSlopeBias = floatFromDWORD(
                get(D3DRS_SLOPESCALEDEPTHBIAS, 0));
            const depthBiasSlopeScale = Number.isFinite(rawSlopeBias)
                ? rawSlopeBias : 0;

            const stencilEnabled = !forceSolid && hasDepth &&
                get(D3DRS_STENCILENABLE, 0) !== 0;
            const stencilFace = (failId, depthFailId, passId, funcId) => ({
                compare: COMPARE_FUNCS[get(funcId, 8)] || "always",
                failOp: STENCIL_OPS[get(failId, 1)] || "keep",
                depthFailOp: STENCIL_OPS[get(depthFailId, 1)] || "keep",
                passOp: STENCIL_OPS[get(passId, 1)] || "keep",
            });
            const stencilFront = stencilFace(D3DRS_STENCILFAIL,
                D3DRS_STENCILZFAIL, D3DRS_STENCILPASS, D3DRS_STENCILFUNC);
            const stencilBack = get(D3DRS_TWOSIDEDSTENCILMODE, 0) !== 0
                ? stencilFace(D3DRS_CCW_STENCILFAIL, D3DRS_CCW_STENCILZFAIL,
                    D3DRS_CCW_STENCILPASS, D3DRS_CCW_STENCILFUNC)
                : stencilFront;

            // D3D9's front face is clockwise, so D3DCULL_CW means "cull the
            // front" and D3DCULL_CCW (its default) means "cull the back".
            const cullValue = get(D3DRS_CULLMODE, D3DCULL_CCW);
            let cullMode = "none";
            if (!forceSolid && !this.debug.disableCull) {
                if (cullValue === D3DCULL_CW) cullMode = "front";
                else if (cullValue === D3DCULL_CCW) cullMode = "back";
            }

            // D3DCOLORWRITEENABLE's RED/GREEN/BLUE/ALPHA bits happen to be
            // 1/2/4/8, matching GPUColorWrite exactly.
            const writeMask = forceSolid ? 0xF
                : get(D3DRS_COLORWRITEENABLE, 0xF) & 0xF;
            const extraWriteMasks = forceSolid ? [0xF, 0xF, 0xF] : [
                    get(D3DRS_COLORWRITEENABLE1, 0xF) & 0xF,
                    get(D3DRS_COLORWRITEENABLE2, 0xF) & 0xF,
                    get(D3DRS_COLORWRITEENABLE3, 0xF) & 0xF,
                ];

            // Alpha test is a shader construct here, not pipeline state, so
            // it travels with the rest of the immutable state and lands in
            // the fragment key rather than in the GPURenderPipeline itself.
            const alphaTest = {
                enabled: !forceSolid &&
                    get(D3DRS_ALPHATESTENABLE, 0) !== 0,
                func: get(D3DRS_ALPHAFUNC, 8) & 0xF,
                reference: get(D3DRS_ALPHAREF, 0) & 0xFF,
            };

            const sampleCount = (targets && targets.sampleCount) || 1;
            return { depthEnabled, depthWrite, depthCompare, depthBias,
                depthBiasSlopeScale, blendEnabled, srcFactor, dstFactor,
                blendOp, alphaSrcFactor, alphaDstFactor, alphaBlendOp,
                blendConstant, cullMode, writeMask, alphaTest, hasDepth,
                stencilEnabled, stencilFront, stencilBack,
                stencilReadMask: get(D3DRS_STENCILMASK, 0xffffffff) >>> 0,
                stencilWriteMask: get(D3DRS_STENCILWRITEMASK, 0xffffffff) >>> 0,
                stencilReference: get(D3DRS_STENCILREF, 0) >>> 0,
                extraWriteMasks,
                // Every colour attachment of the pass this pipeline runs in has
                // to appear in its fragment targets, in order -- WebGPU matches
                // them positionally, so an MRT pass needs the whole list baked
                // into the pipeline and therefore into its cache key.
                colorFormats: targets ? targets.formats : [this.format],
                // WebGPU takes the sample count on the pipeline as well as on
                // the attachments, and the two must agree; without this the
                // pipeline defaulted to 1 and every draw into a multisampled
                // target failed validation.
                sampleCount,
                // D3DRS_MULTISAMPLEMASK maps straight onto WebGPU's
                // multisample mask. D3DRS_MULTISAMPLEANTIALIAS turning
                // antialiasing off for one draw has no WebGPU equivalent --
                // the sample count is fixed for the whole pass -- so it is
                // approximated by writing sample 0 only, which is what
                // "no antialiasing" means for the pixels this draw covers.
                sampleMask: sampleCount > 1
                    ? (get(D3DRS_MULTISAMPLEANTIALIAS, 1) !== 0
                        ? (get(D3DRS_MULTISAMPLEMASK, 0xffffffff) >>> 0)
                        : 1)
                    : 0xffffffff,
                // Only meaningful on a multisampled target -- with one sample
                // there is no coverage to spread an alpha value over, and
                // WebGPU rejects the combination outright.
                alphaToCoverage: sampleCount > 1 &&
                    (get(D3DRS_ADAPTIVETESS_Y, 0) >>> 0) === D3DFOURCC_ATOC };
        }

        // ---- independent sampler state (plan 4.4/12) ----
        //
        // D3D9 splits sampling parameters out of texture-stage state into
        // SetSamplerState, which maps almost one-to-one onto an immutable
        // GPUSampler. M1 recorded these values but sampled every texture with
        // one hardcoded linear/repeat sampler created alongside the texture;
        // they now drive a cache keyed by the parameter tuple, so a stage's
        // sampler follows the app's state rather than the texture it happens
        // to be bound to.
        samplerFor(state, stage, unfilterable, texture) {
            const get = (id, fallback) => {
                const value = state.samplerStates.get(stage * 64 + id);
                return value === undefined ? fallback : value;
            };
            // D3D9 defaults: WRAP addressing, POINT min/mag, no mip filtering.
            const addressU = get(D3DSAMP_ADDRESSU, 1);
            const addressV = get(D3DSAMP_ADDRESSV, 1);
            const addressW = get(D3DSAMP_ADDRESSW, 1);
            const requestedMipFilter = get(D3DSAMP_MIPFILTER, 0);
            const magFilter = unfilterable ? 1 : get(D3DSAMP_MAGFILTER, 1);
            const minFilter = unfilterable ? 1 : get(D3DSAMP_MINFILTER, 1);
            const mipFilter = unfilterable && requestedMipFilter !== 0
                ? 1 : requestedMipFilter;
            let maxAnisotropy = get(D3DSAMP_MAXANISOTROPY, 1) | 0;
            if (unfilterable) maxAnisotropy = 1;
            // Two independent floors on the mip chain, and D3D9 applies the
            // more restrictive: D3DSAMP_MAXMIPLEVEL is sampler state and
            // applies to whatever is bound here, while SetLOD travels with the
            // texture. Both are level indices; WebGPU spells the same thing as
            // a LOD clamp. Clamped against the chain that exists so a stale
            // value cannot produce lodMinClamp > lodMaxClamp, which WebGPU
            // rejects outright.
            const levels = Math.max(1, (texture && texture.levelCount) || 1);
            const lodFloor = Math.min(levels - 1,
                Math.max(get(D3DSAMP_MAXMIPLEVEL, 0) >>> 0,
                    (texture && texture.lod) || 0));
            const key = [addressU, addressV, addressW, magFilter, minFilter,
                mipFilter, maxAnisotropy, lodFloor,
                this.debug.forceMipLevel0 ? "top" : "",
                unfilterable ? "non-filtering" : "filtering"].join(",");
            const cached = this.samplerCache.get(key);
            if (cached) { ++this.stats.samplerHits; return cached; }

            const descriptor = {
                addressModeU: ADDRESS_MODES[addressU] || "repeat",
                addressModeV: ADDRESS_MODES[addressV] || "repeat",
                addressModeW: ADDRESS_MODES[addressW] || "repeat",
                magFilter: FILTER_MODES[magFilter] || "nearest",
                minFilter: FILTER_MODES[minFilter] || "nearest",
                // D3DTEXF_NONE means "use only the top mip level", which is
                // what clamping the LOD range to 0 expresses in WebGPU.
                mipmapFilter: mipFilter === 2 ? "linear" : "nearest",
            };
            if (this.debug.forceMipLevel0) {
                descriptor.lodMinClamp = 0;
                descriptor.lodMaxClamp = 0;
            } else if (mipFilter === 0) {
                // D3DTEXF_NONE means "sample one level and do not blend
                // between levels". That level is the most detailed one still
                // allowed, which is the floor -- not level 0, once
                // D3DSAMP_MAXMIPLEVEL or SetLOD has raised it.
                descriptor.lodMinClamp = lodFloor;
                descriptor.lodMaxClamp = lodFloor;
            } else if (lodFloor > 0) {
                descriptor.lodMinClamp = lodFloor;
            }
            // WebGPU only accepts maxAnisotropy > 1 when all three filters are
            // linear, so anisotropy is dropped rather than forcing filters the
            // app did not ask for.
            if (!unfilterable && maxAnisotropy > 1 &&
                    descriptor.magFilter === "linear" &&
                    descriptor.minFilter === "linear" &&
                    descriptor.mipmapFilter === "linear" && mipFilter !== 0)
                descriptor.maxAnisotropy = Math.min(16, maxAnisotropy);
            if (addressU === 4 || addressV === 4 || addressW === 4)
                this.warnOnce("address-border", "D3DTADDRESS_BORDER has no " +
                    "native WebGPU sampler mode; the physical sample clamps " +
                    "to edge and the fixed-function fragment shader replaces " +
                    "out-of-domain coordinates with D3DSAMP_BORDERCOLOR");
            const sampler = this.device.createSampler(descriptor);
            ++this.stats.samplersCreated;
            this.samplerCache.set(key, sampler);
            return sampler;
        }

        // ---- program resolution ----

        // Resolves the two stages into GPUShaderModules plus everything the
        // pipeline and bind group need. Returns {error} instead of throwing
        // for anything the caller should turn into a counted skipped draw.
        programFor(state, elements, pipelineState, drawOptions) {
            drawOptions = drawOptions || {};
            const alphaTest = pipelineState.alphaTest;
            const alphaTestKey = alphaTest.enabled
                ? "_a" + alphaTest.func + "_" + alphaTest.reference : "";
            const rs = state.renderStates;
            const clipMask = (rs.get(D3DRS_CLIPPLANEENABLE) || 0) & 0x3f;
            const clipPlaneCount = clipMask
                ? 32 - Math.clz32(clipMask) : 0;
            const clipKey = "_cl" + clipPlaneCount;
            // D3DRS_SHADEMODE, applied to the two colour varyings in both
            // stages, fixed-function or translated (D3D9 flat-shades COLOR0/1
            // with shaders too, as wined3d's flatshading does). The two
            // stages have to agree: a vertex output and the fragment input at
            // one location with different interpolation make the pipeline,
            // and the frame's command buffer, invalid.
            const flatShading =
                (rs.get(D3DRS_SHADEMODE) || D3DSHADE_GOURAUD) === D3DSHADE_FLAT;
            // Pre-transformed vertices (a POSITIONT element) skip vertex
            // processing even with a vertex shader bound: D3D9 draws them as
            // fixed-function screen-space geometry, as wined3d's use_vs()
            // does. Apps draw HUD quads so without unbinding their shader;
            // matching POSITIONT against the shader's POSITION input instead
            // dropped the draw, or built a pipeline missing attribute 0, which
            // invalidates the whole frame's command buffer.
            const pretransformed = elements.some(element =>
                element.usage === DECLUSAGE_POSITIONT && element.usageIndex === 0);
            const vsHandle = pretransformed ? 0 : state.vertexShaderHandle;
            const psHandle = state.pixelShaderHandle;
            const vsResource = vsHandle ? this.resources.get(vsHandle) : null;
            const psResource = psHandle ? this.resources.get(psHandle) : null;
            if (vsHandle && !vsResource)
                return { error: "bound vertex shader handle is unknown to the host",
                    shaderError: true };
            if (psHandle && !psResource)
                return { error: "bound pixel shader handle is unknown to the host",
                    shaderError: true };
            if (this.debug.skipProgrammableDraws &&
                    !this.debug.forceSolidAllDraws &&
                    (vsResource || psResource))
                return { error: "debug.skipProgrammableDraws is on; this draw " +
                    "has a translated " + (vsResource ? "vertex" : "") +
                    (vsResource && psResource ? "/" : "") +
                    (psResource ? "pixel" : "") + " shader bound" };

            // The declaration decides whether the fixed-function vertex stage
            // can run at all, and it is also what tells the pixel stage which
            // vertex stage is in force -- D3D9 only applies texture-coordinate
            // generation and the texture matrices as part of fixed-function
            // T&L, so the answer changes what the cascade may assume about its
            // input varyings. Hence it is resolved first, before either module.
            const fixedVertexSignature = vsResource ? null
                : this.fixedFunctionVertexSignature(elements);
            if (!vsResource && !fixedVertexSignature)
                return { error: "declaration has no POSITION/POSITIONT element " +
                    "and no vertex shader is bound" };

            // Table fog (D3DRS_FOGTABLEMODE) takes precedence over vertex fog
            // when both are set, which is what D3D9 does. Screen-space XYZRHW
            // geometry is excluded: it has no eye-space depth to fog against.
            let fogMode = 0;
            let tableFog = false;
            if ((rs.get(D3DRS_FOGENABLE) || 0) !== 0 &&
                    (!fixedVertexSignature ||
                     fixedVertexSignature.positionType !== "screen")) {
                const table = rs.get(D3DRS_FOGTABLEMODE) || D3DFOG_NONE;
                tableFog = table !== D3DFOG_NONE;
                fogMode = tableFog ? table
                    : (rs.get(D3DRS_FOGVERTEXMODE) || D3DFOG_NONE);
            }

            // ---- pixel stage ----
            //
            // Resolved before the vertex stage because how many texture
            // coordinate sets the vertex stage has to produce, and with which
            // per-stage transform, depends on what consumes them: the cascade's
            // active stage count for a fixed-function pixel stage, or the
            // texcoord semantics a translated pixel shader declares.
            let fragmentModule, fragmentKey, pixelReflection = null;
            let samplerIndices = [];
            // Sampler slot -> WGSL view dimension ("2d" / "cube" / "3d").
            const samplerDimensions = {};
            let cascade = null;
            let pixelSignature = null;
            let coordStageCount = 0;
            if (psResource) {
                if (!psResource.translated.ok)
                    return { error: "pixel shader translation failed: " +
                        psResource.translated.error, shaderError: true };
                let variant = psResource.translated;
                // SM1 tex/texld have implicit sampler types. A shader can be
                // used with 2D, cube or volume textures on different draws, so
                // specialize its WGSL and cache key from the current bindings.
                // SM2+ dcl_* types remain authoritative and are checked below.
                const legacySamplerTypes = {};
                let legacySamplerKey = "";
                if (variant.reflection.version.major === 1) {
                    for (const sampler of variant.reflection.samplers) {
                        const texture = this.resources.get(state.textures.get(sampler.index));
                        const type = texture && (texture.textureType || "2d");
                        if (type && type !== sampler.type) {
                            legacySamplerTypes[sampler.index] = type;
                            legacySamplerKey += "_t" + sampler.index + ":" + type;
                        }
                    }
                }
                // Which stages have a depth texture bound decides the WGSL:
                // a shadow-map stage is texture_depth_2d sampled through a
                // comparison sampler, and there is nothing in the bytecode to
                // say so. The sampler set is a property of the bytecode rather
                // than of any variant, so the base translation's reflection is
                // the right thing to read it from.
                const depthSamplers = [];
                const depthFetchSamplers = [];
                for (const sampler of psResource.translated.reflection.samplers) {
                    const mode = this.depthSampleModeFor(
                        state.textures.get(sampler.index));
                    if (!mode) continue;
                    depthSamplers.push(sampler.index);
                    if (mode === "depth-fetch")
                        depthFetchSamplers.push(sampler.index);
                }
                const depthKey = depthSamplers.length
                    ? "_z" + depthSamplers.join(".") +
                        (depthFetchSamplers.length
                            ? "_r" + depthFetchSamplers.join(".") : "")
                    : "";
                // D3DSAMP_MIPMAPLODBIAS is sampler state, but WebGPU has no
                // sampler field for it, so it can only be applied at the sample
                // call -- which puts it in the WGSL and therefore in the variant
                // key. Only the samplers this shader actually declares are
                // considered, so an unrelated stage's stale bias cannot mint a
                // variant.
                const samplerLodBias = {};
                let lodBiasKey = "";
                // D3DTADDRESS_MIRRORONCE is finished in the shader too: the
                // sampler clamps, and abs() on the coordinate supplies the
                // mirror. Same variant-key treatment as the bias.
                const samplerMirrorOnce = {};
                let mirrorOnceKey = "";
                for (const sampler of psResource.translated.reflection.samplers) {
                    const bias = lodBiasFor(state.samplerStates.get(
                        sampler.index * 64 + D3DSAMP_MIPMAPLODBIAS) || 0);
                    if (bias) {
                        samplerLodBias[sampler.index] = bias;
                        lodBiasKey += "_b" + sampler.index + ":" + bias;
                    }
                    const axes = [
                        [D3DSAMP_ADDRESSU, "x"], [D3DSAMP_ADDRESSV, "y"],
                        [D3DSAMP_ADDRESSW, "z"],
                    ].filter(([id]) => (state.samplerStates.get(
                        sampler.index * 64 + id) || 1) === 5)
                        .map(([, axis]) => axis).join("");
                    if (axes) {
                        samplerMirrorOnce[sampler.index] = axes;
                        mirrorOnceKey += "_m" + sampler.index + ":" + axes;
                    }
                }
                const pixelVariantKey = alphaTestKey + clipKey + depthKey +
                    lodBiasKey + mirrorOnceKey + legacySamplerKey +
                    (flatShading ? "_flat" : "");
                if (alphaTest.enabled || clipPlaneCount || depthSamplers.length
                        || lodBiasKey || mirrorOnceKey || legacySamplerKey ||
                        flatShading) {
                    variant = psResource.variants.get(pixelVariantKey);
                    if (!variant) {
                        variant = shaderPipeline.compileShader(psResource.tokens, {
                            alphaTestDiscard: alphaTestDiscard(alphaTest,
                                "result.color0.a"),
                            clipPlaneCount,
                            depthSamplers,
                            depthFetchSamplers,
                            samplerLodBias,
                            samplerMirrorOnce,
                            legacySamplerTypes,
                            flatShading,
                        });
                        psResource.variants.set(pixelVariantKey, variant);
                        if (variant.ok) ++this.stats.shaderVariantsTranslated;
                    }
                    if (!variant.ok)
                        return { error: "pixel shader translation failed: " +
                            variant.error, shaderError: true };
                }
                pixelReflection = variant.reflection;
                // The declared sampler type has to match what is actually bound:
                // a texture_cube binding fed a 2D view is a WebGPU validation
                // error that kills the whole submit, not just this draw.
                for (const sampler of pixelReflection.samplers) {
                    const texture = this.resources.get(
                        state.textures.get(sampler.index));
                    const bound = texture ? (texture.textureType || "2d") : null;
                    if (bound && bound !== sampler.type)
                        return { error: "pixel shader declares sampler " +
                            sampler.index + " as " + sampler.type +
                            " but a " + bound + " texture is bound to that stage",
                            shaderError: true };
                }
                samplerIndices = pixelReflection.samplers.map(s => s.index);
                for (const sampler of pixelReflection.samplers)
                    samplerDimensions[sampler.index] = sampler.type;
                if (fogMode) {
                    ++this.stats.drawsWithUnappliedFog;
                    this.warnOnce("fog-programmable",
                        "fog is enabled on a draw with a translated pixel " +
                        "shader; the fixed-function fog blend is not applied " +
                        "there, so the fragment keeps its untinted colour");
                }
                // D3D9 hands a pixel shader the coordinates of texture stage n
                // in its texcoord n, so the vertex stage still has to run
                // generation/transform for every stage the shader reads.
                for (const input of pixelReflection.inputs || []) {
                    if (input.usage === DECLUSAGE_TEXCOORD)
                        coordStageCount = Math.max(coordStageCount,
                            input.usageIndex + 1);
                }
                if (!coordStageCount && pixelReflection.samplers.length)
                    coordStageCount = Math.max(...pixelReflection.samplers
                        .map(sampler => sampler.index)) + 1;
                fragmentKey = "ps" + psResource.hashHigh + "_" + psResource.hashLow +
                    pixelVariantKey;
                fragmentModule = this.moduleFor(variant.wgsl, "d3d9 " + fragmentKey);
            } else {
                cascade = this.textureCascadeSignature(state,
                    { fixedVertexStage: !!fixedVertexSignature });
                coordStageCount = cascade.stages.length;
                for (const stage of cascade.stages) {
                    if (!stage.samplesTexture) continue;
                    if (stage.hasTextureBound) ++this.stats.drawsWithTexture;
                    else ++this.stats.drawsWithFallbackTexture;
                }
                if (cascade.unsupported.length) {
                    ++this.stats.drawsWithUnsupportedTextureOp;
                    this.warnOnce("texture-stage-" + cascade.unsupported[0],
                        "a draw asks for texture-stage behaviour outside what " +
                        "the fixed-function cascade implements; the stage falls " +
                        "back to selecting its first argument, which renders as " +
                        "plausible-but-wrong shading: " +
                        cascade.unsupported.join("; "));
                }
                samplerIndices = cascade.stages
                    .filter(stage => stage.samplesTexture)
                    .map(stage => stage.index);
                // Per-draw, so the highlight marks only the affected draws
                // instead of repainting the frame the way shaderMode does.
                const cascadeMissesTexture = cascade.stages.some(stage =>
                    stage.samplesTexture && !stage.hasTextureBound);
                const cascadeMissesCoordSet = !!fixedVertexSignature &&
                    cascade.stages.some(stage =>
                        stage.samplesTexture &&
                        stage.tciMode === D3DTSS_TCI_PASSTHRU &&
                        !fixedVertexSignature.texCoordSets
                            .includes(stage.texCoordIndex));
                // Missing texture wins the colour when a draw manages both,
                // because it is the coarser fault: there is nothing to sample
                // whatever the coordinates do.
                const debugMode =
                    (this.debug.highlightMissingTexture && cascadeMissesTexture)
                        ? "missing"
                        : ((this.debug.highlightMissingCoordSet &&
                            cascadeMissesCoordSet)
                            ? "orphan" : this.debug.shaderMode);
                for (const stage of cascade.stages) {
                    if (stage.samplesTexture)
                        samplerDimensions[stage.index] = stage.textureType;
                }
                pixelSignature = {
                    stages: cascade.stages,
                    usesTextureFactor: cascade.usesTextureFactor,
                    fogMode, tableFog, alphaTest, clipPlaneCount,
                    // D3D9 adds the specular colour after the cascade whenever
                    // D3DRS_SPECULARENABLE is set, whether it came from lighting
                    // or straight off the vertex.
                    specularEnable: (rs.get(D3DRS_SPECULARENABLE) || 0) !== 0,
                    flatShading,
                };
                fragmentKey = "ffps" + cascade.stages.map(stage =>
                    [stage.index, stage.colorOp, stage.colorArg0, stage.colorArg1,
                     stage.colorArg2, stage.alphaOp, stage.alphaArg0,
                     stage.alphaArg1, stage.alphaArg2, stage.resultArg,
                     stage.samplesTexture ? stage.textureType : "-",
                     stage.coordVarying, stage.projected ? "p" + stage.transformCount : "",
                     stage.samplesTexture
                         ? [stage.addressU, stage.addressV, stage.addressW,
                            stage.borderColor >>> 0].join("b") : "",
                     stage.colorKey
                         ? "k" + (stage.colorKey.indexed ? "i" : "r") +
                            (stage.colorKey.low >>> 0) + ":" +
                            (stage.colorKey.high >>> 0) : "",
                     // Baked into the WGSL as a literal (WebGPU samplers have
                     // no bias field), so two stages differing only in bias are
                     // different shaders and must not share a cache entry.
                     stage.lodBias ? "l" + stage.lodBias : ""
                    ].join(".")).join("|") +
                    (pixelSignature.usesTextureFactor ? "_tf" : "") +
                    (pixelSignature.specularEnable ? "_s" : "") +
                    (flatShading ? "_flat" : "") +
                    alphaTestKey + (fogMode
                        ? (tableFog ? "_ft" : "_fv") + fogMode : "") +
                    clipKey + (debugMode ? "_" + debugMode : "");
                fragmentModule = this.moduleFor(
                    buildFixedFunctionPixelShader(pixelSignature, debugMode),
                    "d3d9 " + fragmentKey);
            }
            if (this.debug.forceSolidAllDraws) {
                // Preserve the original key in the diagnostic key. Although
                // every probe draw uses the same tiny fragment module, its
                // original shader still determines the bind-group layout
                // (constant block and sampler bindings), and two such layouts
                // must never collide in the pipeline cache.
                fragmentKey = "debug-solid-all(" + fragmentKey + ")";
                fragmentModule = this.moduleFor(DIAGNOSTIC_SOLID_PIXEL_SHADER,
                    "d3d9 diagnostic solid pixel shader");
            }

            // ---- vertex stage ----
            let vertexModule, vertexKey, vertexReflection = null, locationFor;
            let fixedFunctionSignature = null;
            if (vsResource) {
                const inputLocations = new Map();
                if (!vsResource.translated.ok)
                    return { error: "vertex shader translation failed: " +
                        vsResource.translated.error, shaderError: true };
                for (const input of vsResource.translated.reflection.inputs)
                    inputLocations.set(input.usage * 16 + input.usageIndex, input.location);
                // Only the declaration knows which attributes are D3DCOLOR and
                // therefore arrive byte-swapped; see bgraInputLocations.
                const bgra = [];
                const inputConversions = {};
                for (const element of elements) {
                    const location = inputLocations.get(
                        element.usage * 16 + element.usageIndex);
                    if (location !== undefined && element.type === DECLTYPE_D3DCOLOR)
                        bgra.push(location);
                    if (location === undefined) continue;
                    const conversion = {
                        5: "ubyte4", 6: "short2", 7: "short4",
                        13: "udec3", 14: "dec3n",
                    }[element.type];
                    if (conversion) inputConversions[location] = conversion;
                }
                bgra.sort((a, b) => a - b);
                const conversionKey = Object.keys(inputConversions)
                    .map(Number).sort((a, b) => a - b)
                    .map(location => location + ":" + inputConversions[location])
                    .join(",");
                const pointKey = drawOptions.pointExpansion
                    ? "|p:" + (drawOptions.pointSprite ? "s" : "q") : "";
                const variantKey = "b:" + bgra.join(",") + "|c:" +
                    conversionKey + pointKey + clipKey +
                    (flatShading ? "|flat" : "");
                const needsVariant = bgra.length || conversionKey.length ||
                    !!drawOptions.pointExpansion || !!clipPlaneCount ||
                    flatShading;
                let variant = vsResource.variants.get(variantKey);
                if (!variant) {
                    variant = needsVariant
                        ? shaderPipeline.compileShader(vsResource.tokens,
                            { bgraInputLocations: bgra, inputConversions,
                              pointExpansion: !!drawOptions.pointExpansion,
                              pointSprite: !!drawOptions.pointSprite,
                              clipPlaneCount, flatShading })
                        : vsResource.translated;
                    vsResource.variants.set(variantKey, variant);
                    if (needsVariant && variant.ok)
                        ++this.stats.shaderVariantsTranslated;
                }
                if (!variant.ok)
                    return { error: "vertex shader translation failed: " + variant.error,
                        shaderError: true };
                vertexReflection = variant.reflection;
                vertexKey = "vs" + vsResource.hashHigh + "_" + vsResource.hashLow +
                    "_" + variantKey;
                vertexModule = this.moduleFor(variant.wgsl, "d3d9 " + vertexKey);
                locationFor = element => {
                    const location = inputLocations.get(
                        element.usage * 16 + element.usageIndex);
                    return location === undefined ? -1 : location;
                };
                if (conversionKey.length)
                    ++this.stats.drawsWithCompactVertexInputs;
            } else {
                const signature = fixedVertexSignature;
                signature.pointExpansion = !!drawOptions.pointExpansion;
                signature.pointSprite = signature.pointExpansion &&
                    (rs.get(D3DRS_POINTSPRITEENABLE) || 0) !== 0;
                signature.pointScale = signature.pointExpansion &&
                    signature.positionType !== "screen" &&
                    (rs.get(D3DRS_POINTSCALEENABLE) || 0) !== 0;
                // Table fog is evaluated from per-fragment W in the pixel
                // stage. Only vertex fog belongs in the generated VS/oFog.
                signature.fogMode = tableFog ? D3DFOG_NONE : fogMode;
                signature.fogRange = !tableFog &&
                    (rs.get(D3DRS_RANGEFOGENABLE) || 0) !== 0;
                signature.normalizeNormals =
                    (rs.get(D3DRS_NORMALIZENORMALS) || 0) !== 0;
                signature.lighting = this.lightingSignature(state, signature);
                signature.coordStages = this.coordStagePlan(state, coordStageCount);
                /*
                 * buildFixedFunctionVertexShader() feeds a stage
                 * vec4(0,0,0,1) when texCoordSets does not carry the set
                 * D3DTSS_TEXCOORDINDEX names -- there is no coordinate to
                 * read, and a pipeline that declared the attribute anyway
                 * would be rejected outright. That substitution is silent, and
                 * its result is a constant coordinate: every fragment of the
                 * model samples the same texel and the whole thing renders as
                 * one flat colour. By eye that is indistinguishable from a
                 * missing texture or a lighting bug, and unlike every
                 * neighbouring fallback on this path it had no counter, so the
                 * one shape it produces could not be told apart from the two
                 * others that produce it. Name it here, where the declaration
                 * and the stage state are both in hand.
                 */
                const orphanCoordStages = signature.coordStages.filter(stage =>
                    stage.tciMode === D3DTSS_TCI_PASSTHRU &&
                    !signature.texCoordSets.includes(stage.texCoordIndex));
                if (orphanCoordStages.length) {
                    ++this.stats.drawsWithMissingCoordSet;
                    if (this.debug.warnOnSuspiciousDraws)
                        this.warnOnce("missing-coord-set-" + (elements || [])
                            .map(e => e.usage + "." + e.usageIndex + ":" +
                                e.type + "@" + e.byteOffset).join(","),
                        "a fixed-function texture stage reads a coordinate set " +
                        "the vertex declaration does not carry; its coordinates " +
                        "are a constant, so the whole draw samples one texel", {
                            stages: orphanCoordStages.map(stage => ({
                                stage: stage.index,
                                texCoordIndex: stage.texCoordIndex,
                            })),
                            declaredTexCoordSets: signature.texCoordSets.slice(),
                            // The declaration verbatim, plus where it came
                            // from. "The declaration carries no TEXCOORD" has
                            // two very different causes -- the app really sent
                            // one without, or the guest dropped it on the way
                            // through SetFVF/CreateVertexDeclaration -- and
                            // only the elements themselves tell them apart.
                            declarationSource: state.fvfElements
                                ? "fvf" : "declaration",
                            fvf: state.fvfElements
                                ? "0x" + ((state.fvf || 0) >>> 0).toString(16)
                                : null,
                            elements: (elements || []).map(element => ({
                                stream: element.stream,
                                offset: element.byteOffset,
                                type: element.type,
                                usage: element.usage,
                                usageIndex: element.usageIndex,
                            })),
                            streamStrides: Array.from(state.streams)
                                .map(([index, stream]) =>
                                    index + ":" + (stream.stride || 0)),
                        });
                }
                signature.clipPlaneCount = clipPlaneCount;
                signature.vertexBlend = this.vertexBlendPlan(state, signature);
                // Skinning data in the declaration that no world matrix past 0
                // will act on. This is now usually *correct* -- D3D9 ignores it
                // too whenever D3DRS_VERTEXBLEND is DISABLE, and engines share
                // one declaration between their skinned and unskinned passes --
                // so it is counted rather than warned about. It stays worth
                // counting because "the character is stuck in bind pose" and
                // "the character is missing" look alike from the outside, and a
                // nonzero count next to a zero blendedDraws says which.
                if (!signature.vertexBlend &&
                        (signature.blendWeightType >= 0 ||
                         signature.blendIndicesType >= 0))
                    ++this.stats.drawsWithUnappliedVertexBlend;
                // View space is needed for lighting, for the camera-space
                // coordinate generation modes and for range-based fog.
                signature.needsViewSpace = signature.positionType !== "screen" && (
                    !!signature.lighting ||
                    signature.pointScale ||
                    (signature.fogRange && !!signature.fogMode) ||
                    signature.coordStages.some(stage =>
                        stage.tciMode !== D3DTSS_TCI_PASSTHRU));
                signature.flatShading = flatShading;
                vertexKey = "ffvs_" + signature.positionType +
                    (flatShading ? "_flat" : "") +
                    (signature.hasColor ? (signature.colorIsBGRA ? "_cb" : "_c") : "") +
                    (signature.hasColor1 ? (signature.color1IsBGRA ? "_sb" : "_s") : "") +
                    (signature.hasNormal ? "_n" : "") +
                    (signature.hasPointSize ? "_ps" : "") +
                    (signature.vertexBlend ? "_vb" +
                        signature.vertexBlend.matrixCount +
                        (signature.vertexBlend.indexed
                            ? "i" + signature.vertexBlend.indexScalar +
                              (signature.vertexBlend.indexNormalized ? "n" : "") +
                              "." + signature.vertexBlend.matrixSlots
                            : "") : "") +
                    "_t" + signature.texCoordSets.join(".") +
                    "_x" + signature.coordStages.map(stage =>
                        [stage.index, stage.texCoordIndex, stage.tciMode,
                         stage.transformCount].join(".")).join(",") +
                    (signature.needsViewSpace ? "_v" : "") +
                    (signature.normalizeNormals ? "_nn" : "") +
                    (signature.lighting ? "_l" + signature.lighting.lights
                        .map(light => light.type).join(".") +
                        (signature.lighting.colorVertex ? "cv" : "") +
                        (signature.lighting.specularEnable ? "sp" : "") +
                        (signature.lighting.localViewer ? "lv" : "") +
                        "m" + [signature.lighting.diffuseSource,
                            signature.lighting.ambientSource,
                            signature.lighting.specularSource,
                            signature.lighting.emissiveSource].join("") : "") +
                    (signature.fogMode ? "_f" + signature.fogMode +
                        (signature.fogRange ? "r" : "") : "") +
                    (signature.pointExpansion ? "_point" +
                        (signature.pointSprite ? "s" : "") +
                        (signature.pointScale ? "a" : "") : "");
                vertexModule = this.moduleFor(
                    buildFixedFunctionVertexShader(signature), "d3d9 " + vertexKey);
                vertexReflection = null;
                locationFor = element =>
                    fixedFunctionLocationFor(element, signature.vertexBlend);
                fixedFunctionSignature = signature;
            }

            /*
             * A no-NORMAL lit batch used to turn GTA SA's characters black.
             * Keeping ambient/emissive fixed the lighting half, but a white or
             * yellow silhouette means the pixel half is still receiving only
             * that lit colour.  Make the three materially different causes
             * observable here, while all the state needed to distinguish them
             * is still together:
             *
             *   - the pixel program never samples a texture;
             *   - it samples a stage whose resource handle is absent;
             *   - it has a live texture, leaving coordinate routing/data as
             *     the remaining suspect.
             *
             * drawsWithTexture only covers the fixed-function pixel cascade,
             * so it cannot answer this for a ps_1_x batch.  samplerIndices
             * covers both the fixed and programmable pixel paths.
             */
            /*
             * The seam between a translated vertex shader and a fixed-function
             * pixel cascade. The cascade picks a varying to read coordinates
             * from; the shader decides which varyings exist. Nothing checks
             * that those two agree, and when they do not the shader stage does
             * not fail -- the varying is simply a constant, so every fragment
             * samples the same texel and the model comes out one flat colour.
             * That is indistinguishable by eye from a lighting bug, a missing
             * texture or a broken UV attribute, which is exactly why it is
             * worth naming rather than leaving to be guessed at.
             */
            if (vertexReflection && vertexReflection.writtenVaryings && cascade) {
                const written = new Set(vertexReflection.writtenVaryings);
                const orphans = cascade.stages.filter(stage =>
                    stage.samplesTexture &&
                    !written.has(VARYING_TEXCOORD0 + stage.coordVarying));
                if (orphans.length) {
                    ++this.stats.drawsWithUnwrittenCoordVarying;
                    if (this.debug.warnOnSuspiciousDraws)
                        this.warnOnce("unwritten-coord-varying",
                        "a fixed-function texture stage reads its required oTn " +
                        "varying, but the bound vertex shader never writes it; " +
                        "its coordinates are a constant and the whole draw " +
                        "samples one texel", {
                            stages: orphans.map(stage => ({
                                stage: stage.index,
                                texCoordIndex: stage.texCoordIndex,
                                readsVarying: VARYING_TEXCOORD0 + stage.coordVarying,
                            })),
                            shaderWroteVaryings: vertexReflection.writtenVaryings,
                            texcoordFromStageIndex:
                                this.debug.texcoordFromStageIndex,
                        });
                }
            }

            if (fixedFunctionSignature && fixedFunctionSignature.lighting &&
                    !fixedFunctionSignature.hasNormal) {
                const textureBindings = samplerIndices.map(index => {
                    const handle = state.textures.get(index) || 0;
                    const resource = handle ? this.resources.get(handle) : null;
                    return {
                        stage: index,
                        handle,
                        live: !!resource,
                        kind: resource ? resource.kind : null,
                        type: resource ? (resource.textureType || "2d") : null,
                        format: resource ? resource.format : null,
                        size: resource ? resource.width + "x" + resource.height : null,
                        levels: resource ? resource.levelCount : null,
                        uploadedLevels: resource && resource.uploadedLevels
                            ? resource.uploadedLevels.size : null,
                    };
                });
                const missingTexture = textureBindings.some(binding => !binding.live);
                const diagnostic = {
                    pixelPath: psResource ? "programmable" : "fixed-function",
                    pixelShader: psResource
                        ? [psResource.hashHigh, psResource.hashLow]
                            .map(value => (value >>> 0).toString(16)
                                .padStart(8, "0")).join("")
                        : null,
                    samplerIndices: samplerIndices.slice(),
                    textureBindings,
                    declaredTexCoordSets: fixedFunctionSignature.texCoordSets.slice(),
                    coordinateStages: fixedFunctionSignature.coordStages.map(stage => ({
                        stage: stage.index,
                        texCoordIndex: stage.texCoordIndex,
                        tciMode: stage.tciMode,
                        transformCount: stage.transformCount,
                        projected: stage.projected,
                    })),
                    materialAmbient: state.material
                        ? state.material.ambient.slice() : null,
                    globalAmbient: (rs.get(D3DRS_AMBIENT) || 0) >>> 0,
                };
                if (!samplerIndices.length) {
                    ++this.stats.zeroNormalDrawsWithoutTexture;
                    if (state.material && this.debug.warnOnSuspiciousDraws) {
                        this.warnOnce("zero-normal-no-texture-sample",
                            "a lit draw with no NORMAL does not sample any texture; " +
                            "ambient/material colour therefore becomes a flat " +
                            "silhouette", diagnostic);
                    }
                } else if (missingTexture) {
                    ++this.stats.zeroNormalDrawsWithMissingTexture;
                    if (textureBindings.some(binding =>
                            !binding.live && !binding.handle))
                        ++this.stats.zeroNormalDrawsWithUnboundTexture;
                    if (textureBindings.some(binding =>
                            !binding.live && binding.handle))
                        ++this.stats.zeroNormalDrawsWithUnknownTexture;
                    if (state.material && this.debug.warnOnSuspiciousDraws) {
                        this.warnOnce("zero-normal-missing-texture",
                            "a lit draw with no NORMAL samples an unbound or unknown " +
                            "texture and receives the 1x1 white fallback; its " +
                            "ambient/material colour therefore becomes a flat " +
                            "silhouette", diagnostic);
                    }
                } else {
                    ++this.stats.zeroNormalDrawsWithLiveTexture;
                    if (state.material && this.debug.warnOnSuspiciousDraws) {
                        this.warnOnce("zero-normal-live-texture",
                            "a lit draw with no NORMAL has a live sampled texture; " +
                            "if it is still a flat silhouette, inspect the reported " +
                            "TEXCOORD routing (debug.shaderMode='uv'/'texture' can " +
                            "separate coordinates from texture data)", diagnostic);
                    }
                }
            }
            if (vertexModule._d9wgBroken || fragmentModule._d9wgBroken)
                return { error: "a stage failed WGSL compilation (see the " +
                    "getCompilationInfo error logged at module creation)",
                    shaderError: true };

            const vertexBuffers = this.vertexBufferLayoutsFor(elements, state,
                locationFor, !!drawOptions.pointExpansion);
            if (vertexBuffers === null)
                return { error: "the declaration needs more vertex buffers " +
                    "than WebGPU binds per draw" };
            // A vertex shader input the declaration does not supply reads
            // (0, 0, 0, 1), as D3D9 hardware does, instead of leaving the
            // pipeline without the attribute (an invalid pipeline invalidates
            // the whole command buffer and with it the frame)
            if (vertexReflection && vertexReflection.inputs) {
                const supplied = new Set();
                for (const layout of vertexBuffers)
                    for (const attribute of layout.attributes) supplied.add(attribute.shaderLocation);
                const missing = vertexReflection.inputs.map(input => input.location)
                    .filter(location => location >= 0 && !supplied.has(location));
                if (missing.length) {
                    if (vertexBuffers.length >= MAX_VERTEX_BUFFERS_PER_DRAW)
                        return { error: "the vertex shader reads inputs the declaration " +
                            "does not supply and no vertex buffer slot is left for them" };
                    ++this.stats.drawsWithDefaultedInputs;
                    vertexBuffers.push({ stream: DEFAULT_ATTRIBUTE_STREAM, arrayStride: 0,
                        stepMode: "vertex", attributes: [...new Set(missing)].sort((a, b) => a - b)
                            .map(location => ({ shaderLocation: location, offset: 0,
                                format: "float32x4" })) });
                }
            }
            if (!vertexBuffers.length)
                return { error: "no vertex stream supplies any attribute the " +
                    "vertex stage reads" };
            const pixelUniformLayout = pixelSignature
                ? fixedPixelUniformLayout(pixelSignature) : null;
            // r32/rg32/rgba32 textures are sampleable on baseline WebGPU, but
            // linear filtering is optional.  Carry the physical format into
            // the immutable pipeline layout so an unsupported filtering
            // request degrades to exact point sampling instead of producing
            // an invalid bind group.
            // A stage the translated shader declared texture_depth_2d for is a
            // depth slot in the layout too, and nowhere else: the module and
            // the bind group layout have to agree exactly or pipeline creation
            // fails. The reflection is the only honest source for that, because
            // the translator declines depth treatment it cannot implement
            // (see isDepthSampler there) and reports what it actually emitted.
            const declaredDepth = new Map((pixelReflection
                ? pixelReflection.samplers : [])
                .filter(sampler => sampler.depth)
                .map(sampler => [sampler.index,
                    sampler.depth === "fetch" ? "depth-fetch"
                        : "depth-compare"]));
            const samplerBindingTypes = {};
            for (const index of samplerIndices) {
                if (declaredDepth.has(index)) {
                    samplerBindingTypes[index] = declaredDepth.get(index);
                    continue;
                }
                const texture = this.resources.get(state.textures.get(index));
                const gpuFormat = texture && (texture.gpuFormat ||
                    formatToGPU(texture.format));
                samplerBindingTypes[index] = isFloat32GPUFormat(gpuFormat) &&
                    !this.deviceFeatures.float32Filterable
                    ? "unfilterable" : "filterable";
            }
            let vertexSamplerError = null;
            const vertexSamplers = vertexReflection
                ? vertexReflection.samplers.map(sampler => {
                    const stage = 256 + sampler.index;
                    const texture = this.resources.get(state.textures.get(stage));
                    const bound = texture ? (texture.textureType || "2d") : null;
                    if (bound && bound !== sampler.type)
                        vertexSamplerError = "vertex shader declares sampler " +
                            sampler.index + " as " + sampler.type +
                            " but a " + bound + " texture is bound";
                    const gpuFormat = texture && (texture.gpuFormat ||
                        formatToGPU(texture.format));
                    return { ...sampler, stage,
                        bindingType: isFloat32GPUFormat(gpuFormat) &&
                            !this.deviceFeatures.float32Filterable
                            ? "unfilterable" : "filterable" };
                }) : [];
            if (vertexSamplerError)
                return { error: vertexSamplerError, shaderError: true };
            return { vertexModule, fragmentModule, vertexKey, fragmentKey,
                vertexReflection, pixelReflection, samplerIndices,
                samplerDimensions, samplerBindingTypes, vertexSamplers,
                vertexBuffers,
                fixedFunctionSignature, pixelSignature, pixelUniformLayout,
                vertexUniformLayout: fixedFunctionSignature
                    ? fixedVertexUniformLayout(fixedFunctionSignature) : null,
                // A translated pixel shader brings its own register file; the
                // fixed-function cascade's block is only as large as the fog
                // colour, texture factor and stage constants it actually reads.
                pixelUniformBytes: pixelReflection ? pixelReflection.uniformBytes
                    : (pixelUniformLayout && pixelUniformLayout.entries.length
                        ? pixelUniformLayout.byteLength : 0),
                fogMode, tableFog, pointExpansion: !!drawOptions.pointExpansion,
                pointSprite: !!drawOptions.pointSprite };
        }

        // The per-stage coordinate plan the fixed-function vertex stage needs:
        // which coordinate set (or generated vector) feeds a stage and which
        // matrix transforms it. D3D9 runs this half of fixed-function T&L
        // whether or not a pixel shader is bound, which is why it is not folded
        // into textureCascadeSignature().
        coordStagePlan(state, stageCount) {
            const stageState = (stage, id, fallback) => {
                const value = state.textureStageStates.get(stage * 64 + id);
                return value === undefined ? fallback : value;
            };
            const stages = [];
            for (let index = 0; index < Math.min(stageCount, MAX_TEXTURE_STAGES);
                    ++index) {
                const flags = stageState(index, D3DTSS_TEXTURETRANSFORMFLAGS, 0);
                // D3DTSS_TEXCOORDINDEX defaults to the stage's own number, so an
                // app that never sets it gets stage n reading TEXCOORD n.
                const coordIndex = stageState(index, D3DTSS_TEXCOORDINDEX, index);
                stages.push({ index,
                    texCoordIndex: coordIndex & 0xFFFF,
                    tciMode: coordIndex & D3DTSS_TCI_MASK,
                    transformCount: flags & 0xFF,
                    projected: (flags & D3DTTFF_PROJECTED) !== 0 });
            }
            return stages;
        }

        pipelineFor(program, pipelineState, topology, stripIndexFormat) {
            const key = program.vertexKey + "|" + program.fragmentKey + "|" +
                JSON.stringify(program.vertexBuffers) + "|" +
                topology + "|" + (stripIndexFormat || "") + "|" +
                JSON.stringify(pipelineState) + "|" +
                program.samplerIndices.map(index => index + ":" +
                    ((program.samplerDimensions &&
                      program.samplerDimensions[index]) || "2d") + ":" +
                    ((program.samplerBindingTypes &&
                      program.samplerBindingTypes[index]) || "filterable"))
                    .join(",") + "|vs:" + (program.vertexSamplers || [])
                    .map(sampler => sampler.index + ":" + sampler.type + ":" +
                        sampler.bindingType).join(",");
            let pipeline = this.pipelineCache.get(key);
            if (pipeline) { ++this.stats.pipelineHits; return pipeline; }

            // Binding 0 is the vertex stage's constant buffer (or the
            // fixed-function transform block, which occupies the same slot),
            // binding 1 the pixel stage's; samplers take 2+2n / 3+2n, the
            // numbering d3d9_shader_pipeline.js emits.
            const bindGroupEntries = [
                { binding: 0, visibility: SHADER_STAGE_VERTEX,
                  buffer: { type: "uniform", hasDynamicOffset: true } },
            ];
            if (program.pixelUniformBytes)
                bindGroupEntries.push({ binding: 1, visibility: SHADER_STAGE_FRAGMENT,
                    buffer: { type: "uniform", hasDynamicOffset: true } });
            for (const index of program.samplerIndices) {
                // The view dimension has to be declared here, not left to
                // default to "2d": WebGPU checks the layout against what the
                // shader declares, so a texture_cube<f32> binding paired with a
                // default 2D layout entry fails pipeline creation outright. naga
                // cannot catch that -- it validates one module, not the pairing.
                const dimension = (program.samplerDimensions &&
                    program.samplerDimensions[index]) || "2d";
                const bindingType = program.samplerBindingTypes &&
                    program.samplerBindingTypes[index];
                const unfilterable = bindingType === "unfilterable";
                const compare = bindingType === "depth-compare";
                const fetch = bindingType === "depth-fetch";
                const depth = compare || fetch;
                // Both depth modes are sampleType "depth"; only the comparison
                // one takes a comparison sampler. A raw fetch reads the stored
                // value through an ordinary non-filtering sampler, because
                // WebGPU will not filter a depth texture without comparing.
                bindGroupEntries.push(
                    { binding: 2 + index * 2, visibility: SHADER_STAGE_FRAGMENT,
                      texture: { viewDimension: depth ? "2d" : dimension,
                          sampleType: depth ? "depth"
                              : (unfilterable ? "unfilterable-float" : "float") } },
                    { binding: 3 + index * 2, visibility: SHADER_STAGE_FRAGMENT,
                      sampler: { type: compare ? "comparison"
                          : ((fetch || unfilterable) ? "non-filtering"
                              : "filtering") } });
            }
            for (const sampler of program.vertexSamplers || []) {
                const unfilterable = sampler.bindingType === "unfilterable";
                bindGroupEntries.push(
                    { binding: sampler.textureBinding,
                      visibility: SHADER_STAGE_VERTEX,
                      texture: { viewDimension: sampler.type,
                          sampleType: unfilterable
                              ? "unfilterable-float" : "float" } },
                    { binding: sampler.samplerBinding,
                      visibility: SHADER_STAGE_VERTEX,
                      sampler: { type: unfilterable
                          ? "non-filtering" : "filtering" } });
            }
            const bindGroupLayout = this.device.createBindGroupLayout(
                { entries: bindGroupEntries });

            // D3DRS_COLORWRITEENABLE1/2/3 mask the extra MRT attachments; slot
            // 0 uses D3DRS_COLORWRITEENABLE. An attachment the fragment shader
            // does not write still needs an entry, or WebGPU rejects the
            // pipeline against the pass.
            const colorTargets = (pipelineState.colorFormats || [this.format])
                .map((format, index) => {
                    const target = { format, writeMask: index === 0
                        ? pipelineState.writeMask
                        : (pipelineState.extraWriteMasks
                            ? pipelineState.extraWriteMasks[index - 1] : 0xF) };
                    if (pipelineState.blendEnabled &&
                            isBlendableGPUFormat(format, this.deviceFeatures)) {
                        target.blend = {
                            color: { srcFactor: pipelineState.srcFactor,
                                     dstFactor: pipelineState.dstFactor,
                                     operation: pipelineState.blendOp },
                            alpha: { srcFactor: pipelineState.alphaSrcFactor,
                                     dstFactor: pipelineState.alphaDstFactor,
                                     operation: pipelineState.alphaBlendOp },
                        };
                    } else if (pipelineState.blendEnabled &&
                            !isBlendableGPUFormat(format, this.deviceFeatures)) {
                        this.warnOnce("float32-blend-disabled-" + format,
                            "D3D blending was requested for a 32-bit float " +
                            "render target, but this WebGPU device does not " +
                            "expose float32-blendable; the draw is emitted " +
                            "without blending instead of creating an invalid " +
                            "render pipeline", { format });
                    }
                    return target;
                });
            const primitive = { topology,
                cullMode: program.pointExpansion ? "none" : pipelineState.cullMode,
                frontFace: "cw" };
            // WebGPU needs to know the restart-index width up front for an
            // indexed strip draw; it must be absent for every other topology.
            if (stripIndexFormat) primitive.stripIndexFormat = stripIndexFormat;
            const descriptor = {
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: {
                    module: program.vertexModule, entryPoint: "d9_vs_main",
                    buffers: program.vertexBuffers.map(layout =>
                        ({ arrayStride: layout.arrayStride,
                           stepMode: layout.stepMode || "vertex",
                           attributes: layout.attributes })),
                },
                fragment: { module: program.fragmentModule, entryPoint: "d9_ps_main",
                    targets: colorTargets },
                primitive,
            };
            if (pipelineState.sampleCount > 1) {
                descriptor.multisample = {
                    count: pipelineState.sampleCount,
                    mask: pipelineState.sampleMask,
                    alphaToCoverageEnabled: pipelineState.alphaToCoverage,
                };
            }
            // The pipeline must declare a depthStencil state whenever the
            // pass it runs in has a depth attachment, even for a draw that
            // does no depth testing -- hence depthCompare "always" plus
            // depthWriteEnabled false rather than omitting the block.
            if (pipelineState.hasDepth) {
                descriptor.depthStencil = {
                    format: DEPTH_FORMAT,
                    depthWriteEnabled: pipelineState.depthEnabled
                        ? pipelineState.depthWrite : false,
                    depthCompare: pipelineState.depthEnabled
                        ? pipelineState.depthCompare : "always",
                    depthBias: pipelineState.depthBias,
                    depthBiasSlopeScale: pipelineState.depthBiasSlopeScale,
                    stencilFront: pipelineState.stencilEnabled
                        ? pipelineState.stencilFront : {},
                    stencilBack: pipelineState.stencilEnabled
                        ? pipelineState.stencilBack : {},
                    stencilReadMask: pipelineState.stencilEnabled
                        ? pipelineState.stencilReadMask : 0,
                    stencilWriteMask: pipelineState.stencilEnabled
                        ? pipelineState.stencilWriteMask : 0,
                };
            }
            pipeline = this.device.createRenderPipeline(descriptor);
            pipeline._bindGroupLayout = bindGroupLayout;
            pipeline._d9wgId = this.objectId(pipeline);
            // Keep structured diagnostic data beside the cached object. The
            // old dumpPipelineStates() attempted to recover it by splitting
            // the cache key on "|", but fixed-function fragment keys use the
            // same character between texture stages, shifting every field and
            // producing a null/misattributed state exactly when multi-texture
            // debugging mattered most.
            pipeline._d9wgDiagnostic = {
                vertex: program.vertexKey,
                fragment: program.fragmentKey,
                topology,
                stripIndexFormat: stripIndexFormat || null,
                vertexBuffers: program.vertexBuffers.map(layout => ({
                    stream: layout.stream,
                    arrayStride: layout.arrayStride,
                    stepMode: layout.stepMode || "vertex",
                    attributes: layout.attributes.map(attribute =>
                        ({ ...attribute })),
                })),
                samplers: program.samplerIndices.slice(),
                state: JSON.parse(JSON.stringify(pipelineState)),
            };
            pipeline._d9wgDrawCount = 0;
            ++this.stats.pipelineCreations;
            this.pipelineCache.set(key, pipeline);
            return pipeline;
        }

        objectId(value) {
            if ((typeof value !== "object" && typeof value !== "function") ||
                    value === null)
                return String(value);
            let id = this.objectIds.get(value);
            if (!id) {
                id = this.nextObjectId++;
                this.objectIds.set(value, id);
            }
            return id;
        }

        // Chunks are created on first use and kept for the page's lifetime;
        // a run that never needs the second one never pays for it.
        uniformRingChunkAt(index) {
            if (!this.device || index >= this.uniformRingMaxChunks) return null;
            let chunk = this.uniformRingChunks[index];
            if (!chunk) {
                chunk = this.device.createBuffer({
                    label: "D3D9 uniform ring " + index,
                    size: this.uniformRingCapacity,
                    usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
                });
                this.uniformRingChunks[index] = chunk;
                this.uniformStaging[index] =
                    new Uint8Array(this.uniformRingCapacity);
                ++this.stats.uniformRingChunksAllocated;
            }
            if (index + 1 > this.stats.uniformRingChunksUsed)
                this.stats.uniformRingChunksUsed = index + 1;
            return chunk;
        }

        allocateUniformSlot(byteCount) {
            const size = alignUp(byteCount, UNIFORM_OFFSET_ALIGNMENT);
            // A block wider than a whole chunk cannot be sub-allocated at all.
            if (size <= this.uniformRingCapacity) {
                while (this.uniformRingIndex < this.uniformRingMaxChunks) {
                    const chunk = this.uniformRingChunkAt(this.uniformRingIndex);
                    if (!chunk) break;
                    const offset = alignUp(this.uniformRingCursor,
                        UNIFORM_OFFSET_ALIGNMENT);
                    if (size <= this.uniformRingCapacity - offset) {
                        this.uniformRingCursor = offset + size;
                        return { buffer: chunk, offset, transient: false,
                            chunkIndex: this.uniformRingIndex };
                    }
                    ++this.uniformRingIndex;
                    this.uniformRingCursor = 0;
                }
            }
            // Last resort, and the shape that used to be the *only* overflow
            // path. It is per-draw and uncacheable, so say so once rather than
            // letting a frame quietly allocate tens of thousands of buffers.
            this.warnOnce("uniform-ring-exhausted",
                "a single frame outran " + this.uniformRingMaxChunks +
                " x " + (this.uniformRingCapacity >> 20) + " MiB of uniform " +
                "storage; the remaining draws each allocate their own buffer " +
                "and bind group, which is slow and memory-hungry. Raise " +
                "uniformRingChunks if this frame is legitimate.", {
                    chunkBytes: this.uniformRingCapacity,
                    maxChunks: this.uniformRingMaxChunks,
                    requestedBytes: size,
                });
            const buffer = this.device.createBuffer({
                label: "D3D9 uniform ring overflow",
                size,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            ++this.stats.uniformRingOverflows;
            this.retireAfterSubmit(buffer);
            return { buffer, offset: 0, transient: true, chunkIndex: -1 };
        }

        /*
         * One writeBuffer per submit instead of one per draw.
         *
         * This is what a real D3D9 driver does with constants: it writes them
         * into a mapped ring with a plain CPU pointer and only rings the
         * doorbell when the buffer fills or a sync point demands it. Calling
         * queue.writeBuffer per draw was the missing piece -- an API call, with
         * its own staging allocation and validation, for every 300-odd bytes.
         *
         * Ordering is what makes it safe to defer: queue.writeBuffer and
         * queue.submit are both queue operations, so a write issued before the
         * submit is visible to every draw in it.
         */
        uploadUniformStaging() {
            for (let index = 0; index <= this.uniformRingIndex; ++index) {
                const chunk = this.uniformRingChunks[index];
                const staging = this.uniformStaging[index];
                if (!chunk || !staging) break;
                // Chunks before the current one were filled to capacity; the
                // current one is filled to the cursor. Both are multiples of
                // UNIFORM_OFFSET_ALIGNMENT, so the 4-byte size rule holds.
                const used = index < this.uniformRingIndex
                    ? this.uniformRingCapacity : this.uniformRingCursor;
                if (!used) continue;
                this.device.queue.writeBuffer(chunk, 0, staging, 0, used);
                ++this.stats.uniformStagingUploads;
                this.stats.constantUploadBytes += used;
            }
        }

        /*
         * Both stages share one uniform ring. Each binding uses the same dynamic
         * base offset, while binding 1's static pixelOffset keeps the two
         * register files separate.
         *
         * A run of draws with no state change between them shares one slot, and
         * that is decided by commandSerial rather than by hashing the assembled
         * bytes. The frame serial is part of the test because a flush rewinds
         * the ring: a slot from an already-submitted segment has had its bytes
         * handed back out to a later draw.
         */
        constantBufferFor(state, program) {
            const frame = this.ensureFrame();
            /*
             * Two things have to hold for the previous slot to still describe
             * this draw, and between them they cover the programmable and the
             * fixed-function paths without special-casing either.
             *
             * The serial covers device state. Every input the block is built
             * from -- constant registers, `def` defaults, viewport, clip planes,
             * transforms, lights, material, texture stage state -- moves only
             * through a command, and any non-draw command bumps the serial.
             *
             * The module keys cover the program. programFor() rebuilds its
             * return object per draw, so the object cannot be compared by
             * identity, but vertexKey/fragmentKey are the keys its WGSL modules
             * are cached under: equal keys mean the same generated shader, hence
             * the same uniform layout and, for fixed function, the same
             * signature the values are read through. That is what makes point
             * expansion safe -- it comes from the draw's primitive type rather
             * than from state, and it is part of the key.
             *
             * The frame serial is in the test because a flush rewinds the ring:
             * a slot from an already-submitted segment has had its bytes handed
             * back out to a later draw.
             */
            const cached = state.lastConstants;
            if (cached && cached.serial === this.commandSerial &&
                    cached.frameSerial === frame.serial &&
                    cached.vertexKey === program.vertexKey &&
                    cached.fragmentKey === program.fragmentKey) {
                ++this.stats.uniformSlotReuses;
                return cached.slot;
            }
            const vertexBytes = program.vertexReflection
                ? program.vertexReflection.uniformBytes
                : program.vertexUniformLayout.byteLength;
            const pixelBytes = program.pixelUniformBytes || 0;
            const pixelOffset = pixelBytes
                ? alignUp(vertexBytes, UNIFORM_OFFSET_ALIGNMENT) : 0;
            const total = Math.max(16, vertexBytes, pixelOffset + pixelBytes);
            const backing = new ArrayBuffer(alignUp(total, 4));

            if (program.vertexReflection) {
                this.writeConstantRegisters(backing, 0, program.vertexReflection,
                    state.vsConstF, state.vsConstI, state.vsConstB, state);
            } else {
                this.writeFixedVertexUniforms(state, program, backing, 0);
            }
            if (program.pixelReflection) {
                this.writeConstantRegisters(backing, pixelOffset,
                    program.pixelReflection, state.psConstF, state.psConstI,
                    state.psConstB);
            } else if (pixelBytes) {
                this.writeFixedPixelUniforms(state, program, backing, pixelOffset);
            }

            const slot = this.allocateUniformSlot(backing.byteLength);
            if (slot.chunkIndex >= 0) {
                // Into the mirror; uploadUniformStaging() sends the whole used
                // prefix once, just before this frame's submit.
                this.uniformStaging[slot.chunkIndex].set(
                    new Uint8Array(backing), slot.offset);
            } else {
                // The overflow buffer is its own allocation and is destroyed
                // after this submit, so it has no mirror to write into.
                this.device.queue.writeBuffer(slot.buffer, slot.offset, backing);
                this.stats.constantUploadBytes += backing.byteLength;
            }
            const constants = { buffer: slot.buffer, dynamicOffset: slot.offset,
                vertexBytes, pixelOffset, pixelBytes,
                transient: slot.transient };
            state.lastConstants = { serial: this.commandSerial,
                frameSerial: frame.serial, vertexKey: program.vertexKey,
                fragmentKey: program.fragmentKey, slot: constants };
            return constants;
        }

        // Fills the fixed-function vertex block. The field list comes from
        // fixedVertexUniformLayout(), the same call the WGSL struct was
        // generated from, so a field that exists in one exists in the other.
        //
        // D3D stores matrices row-major for row-vector maths (v * M); WGSL reads
        // a uniform mat4x4 column-major and applies M * v. Those two conventions
        // cancel: the *same bytes* that describe M to D3D describe M-transpose
        // to WGSL, and M-transpose is exactly the column-vector form of D3D's
        // row-vector M. So every matrix here is uploaded unchanged.
        writeFixedVertexUniforms(state, program, backing, byteOffset) {
            const signature = program.fixedFunctionSignature;
            const layout = program.vertexUniformLayout;
            const rs = state.renderStates;
            const floats = new Float32Array(backing, byteOffset,
                layout.byteLength / 4);
            const at = name => {
                const entry = layout.byName.get(name);
                return entry ? entry.offset / 4 : -1;
            };
            const screenSpace = signature.positionType === "screen";
            const blend = signature.vertexBlend;
            const view = state.transforms.get(D3DTS_VIEW) || IDENTITY4x4;
            // A blended draw's world half is applied per vertex from
            // blend_worlds, so what is pre-multiplied here stops at the view.
            const preVertex = blend ? view : multiply4x4(
                state.transforms.get(D3DTS_WORLD) || IDENTITY4x4, view);

            if (blend) {
                floats.set(multiply4x4(view,
                    state.transforms.get(D3DTS_PROJECTION) || IDENTITY4x4),
                    at("view_projection"));
                const base = at("blend_worlds");
                for (let slot = 0; slot < blend.matrixSlots; ++slot) {
                    floats.set(state.transforms.get(D3DTS_WORLD + slot) ||
                        IDENTITY4x4, base + slot * 16);
                }
            } else {
                floats.set(screenSpace ? IDENTITY4x4 : this.wvp(state),
                    at("world_view_projection"));
                if (layout.byName.has("world_matrix"))
                    floats.set(state.transforms.get(D3DTS_WORLD) || IDENTITY4x4,
                        at("world_matrix"));
            }
            const viewport = at("viewport");
            floats[viewport] = state.viewport.width || 1;
            floats[viewport + 1] = state.viewport.height || 1;
            // zw carry the viewport's origin, which the XYZRHW path subtracts:
            // D3D9 pre-transformed coordinates are absolute render-target
            // pixels, not viewport-relative ones.
            floats[viewport + 2] = state.viewport.x || 0;
            floats[viewport + 3] = state.viewport.y || 0;
            if (layout.byName.has("clip_planes")) {
                const base = at("clip_planes");
                const mask = (rs.get(D3DRS_CLIPPLANEENABLE) || 0) & 0x3f;
                for (let plane = 0; plane < signature.clipPlaneCount; ++plane)
                    floats.set((mask & (1 << plane))
                        ? state.clipPlanes[plane] : [0, 0, 0, 1],
                        base + plane * 4);
            }

            const viewSpaceField = blend ? "view_matrix" : "world_view";
            if (layout.byName.has(viewSpaceField)) {
                floats.set(preVertex, at(viewSpaceField));
                floats.set(inverseTranspose3x3(preVertex), at("normal_matrix"));
            }
            if (layout.byName.has("fog_params")) {
                // FOGSTART/FOGEND/FOGDENSITY are floats carried inside a DWORD.
                const asFloat = (id, fallback) => {
                    const raw = rs.get(id);
                    if (raw === undefined) return fallback;
                    FLOAT_BITS_U32[0] = raw >>> 0;
                    return FLOAT_BITS_F32[0];
                };
                const base = at("fog_params");
                floats[base] = asFloat(D3DRS_FOGSTART, 0);
                floats[base + 1] = asFloat(D3DRS_FOGEND, 1);
                floats[base + 2] = asFloat(D3DRS_FOGDENSITY, 1);
            }
            for (const stage of signature.coordStages) {
                if (!stage.transformCount) continue;
                floats.set(state.transforms.get(D3DTS_TEXTURE0 + stage.index) ||
                    IDENTITY4x4, at("texture_transform" + stage.index));
            }
            if (signature.pointExpansion) {
                const pointFloat = (id, fallback) => {
                    const raw = rs.get(id);
                    return raw === undefined ? fallback : floatFromDWORD(raw);
                };
                const pointViewport = at("point_viewport");
                const width = Math.max(1, state.viewport.width || 1);
                const height = Math.max(1, state.viewport.height || 1);
                floats[pointViewport] = width;
                floats[pointViewport + 1] = height;
                floats[pointViewport + 2] = 1 / width;
                floats[pointViewport + 3] = 1 / height;
                const pointParams = at("point_params");
                floats[pointParams] = pointFloat(D3DRS_POINTSIZE, 1);
                floats[pointParams + 1] = Math.max(0,
                    pointFloat(D3DRS_POINTSIZE_MIN, 1));
                floats[pointParams + 2] = Math.max(floats[pointParams + 1],
                    pointFloat(D3DRS_POINTSIZE_MAX, 64));
                if (signature.pointScale) {
                    const pointScale = at("point_scale");
                    floats[pointScale] = pointFloat(D3DRS_POINTSCALE_A, 1);
                    floats[pointScale + 1] = pointFloat(D3DRS_POINTSCALE_B, 0);
                    floats[pointScale + 2] = pointFloat(D3DRS_POINTSCALE_C, 0);
                }
            }
            if (!signature.lighting) return;

            // D3D9's default material is not all zeroes: a device that never
            // calls SetMaterial still lights with white diffuse/ambient. Using
            // zeroes here would make "the app forgot SetMaterial" and "the app
            // asked for black" indistinguishable, and the former renders black.
            const material = state.material || DEFAULT_MATERIAL;
            floats.set(material.diffuse, at("material_diffuse"));
            floats.set(material.ambient, at("material_ambient"));
            floats.set(material.specular, at("material_specular"));
            floats.set(material.emissive, at("material_emissive"));
            const ambientPower = at("ambient_power");
            const ambient = rs.get(D3DRS_AMBIENT) || 0;
            floats[ambientPower] = ((ambient >>> 16) & 0xff) / 255;
            floats[ambientPower + 1] = ((ambient >>> 8) & 0xff) / 255;
            floats[ambientPower + 2] = (ambient & 0xff) / 255;
            floats[ambientPower + 3] = material.power;

            if (!signature.lighting.lights.length) return;
            // Lights arrive in world space and are lit in view space (which is
            // where D3D9's fixed pipeline puts them), so the view transform is
            // applied here rather than carried into the shader as a second
            // matrix: eight lights is at most a few dozen multiplies per draw,
            // against a full mat4 the vertex stage would otherwise re-apply per
            // vertex.
            let base = at("lights");
            for (const entry of signature.lighting.lights) {
                const light = state.lights.get(entry.index);
                floats.set(light.diffuse, base);
                floats.set(light.specular, base + 4);
                floats.set(light.ambient, base + 8);
                const position = transformPoint(view, light.position);
                floats[base + 12] = position[0];
                floats[base + 13] = position[1];
                floats[base + 14] = position[2];
                floats[base + 15] = 1;
                const direction = normalize3(transformDirection(view, light.direction));
                floats[base + 16] = direction[0];
                floats[base + 17] = direction[1];
                floats[base + 18] = direction[2];
                floats[base + 19] = 0;
                floats[base + 20] = light.range;
                floats[base + 21] = light.falloff;
                // D3D9's Theta/Phi are the *full* cone angles, so the cosine
                // compared against rho is of the half angle.
                floats[base + 22] = Math.cos(light.theta / 2);
                floats[base + 23] = Math.cos(light.phi / 2);
                floats[base + 24] = light.attenuation[0];
                floats[base + 25] = light.attenuation[1];
                floats[base + 26] = light.attenuation[2];
                floats[base + 27] = light.type;
                base += 28;
            }
        }

        // Fills the fixed-function pixel block: only the fog inputs, texture
        // factor and per-stage constants the cascade actually reads.
        writeFixedPixelUniforms(state, program, backing, byteOffset) {
            const layout = program.pixelUniformLayout;
            const floats = new Float32Array(backing, byteOffset,
                layout.byteLength / 4);
            const writeColor = (index, argb, alpha) => {
                floats[index] = ((argb >>> 16) & 0xff) / 255;
                floats[index + 1] = ((argb >>> 8) & 0xff) / 255;
                floats[index + 2] = (argb & 0xff) / 255;
                floats[index + 3] = alpha === undefined
                    ? ((argb >>> 24) & 0xff) / 255 : alpha;
            };
            for (const entry of layout.entries) {
                if (entry.name === "fog_color") {
                    // D3DRS_FOGCOLOR's alpha byte is defined as unused.
                    writeColor(entry.offset / 4,
                        state.renderStates.get(D3DRS_FOGCOLOR) || 0, 1);
                } else if (entry.name === "fog_params") {
                    // Table fog evaluates the equation per fragment, so its
                    // start/end/density values belong to the pixel block.
                    const asFloat = (id, fallback) => {
                        const raw = state.renderStates.get(id);
                        if (raw === undefined) return fallback;
                        FLOAT_BITS_U32[0] = raw >>> 0;
                        return FLOAT_BITS_F32[0];
                    };
                    const base = entry.offset / 4;
                    floats[base] = asFloat(D3DRS_FOGSTART, 0);
                    floats[base + 1] = asFloat(D3DRS_FOGEND, 1);
                    floats[base + 2] = asFloat(D3DRS_FOGDENSITY, 1);
                } else if (entry.name === "texture_factor") {
                    writeColor(entry.offset / 4,
                        state.renderStates.get(D3DRS_TEXTUREFACTOR) === undefined
                            ? 0xffffffff
                            : state.renderStates.get(D3DRS_TEXTUREFACTOR));
                } else if (entry.bumpSource !== undefined) {
                    // BUMPENVMAT00/01/10/11 hold raw float bits, like the fog
                    // states above. Packed as (m00, m01, m10, m11).
                    const base = entry.offset / 4;
                    const stageState = id => {
                        const raw = state.textureStageStates.get(
                            entry.bumpSource * 64 + id);
                        if (raw === undefined) return 0;
                        FLOAT_BITS_U32[0] = raw >>> 0;
                        return FLOAT_BITS_F32[0];
                    };
                    floats[base] = stageState(D3DTSS_BUMPENVMAT00);
                    floats[base + 1] = stageState(D3DTSS_BUMPENVMAT01);
                    floats[base + 2] = stageState(D3DTSS_BUMPENVMAT10);
                    floats[base + 3] = stageState(D3DTSS_BUMPENVMAT11);
                } else if (entry.bumpLuminanceSource !== undefined) {
                    const base = entry.offset / 4;
                    const stageState = id => {
                        const raw = state.textureStageStates.get(
                            entry.bumpLuminanceSource * 64 + id);
                        if (raw === undefined) return 0;
                        FLOAT_BITS_U32[0] = raw >>> 0;
                        return FLOAT_BITS_F32[0];
                    };
                    floats[base] = stageState(D3DTSS_BUMPENVLSCALE);
                    floats[base + 1] = stageState(D3DTSS_BUMPENVLOFFSET);
                    floats[base + 2] = 0;
                    floats[base + 3] = 0;
                } else {
                    // stage_constant<N>; D3DTSS_CONSTANT defaults to opaque
                    // black, unlike D3DRS_TEXTUREFACTOR's opaque white.
                    writeColor(entry.offset / 4,
                        state.textureStageStates.get(
                            entry.source * 64 + D3DTSS_CONSTANT) || 0xff000000);
                }
            }
        }

        // Packs one stage's register file into the layout the translated WGSL
        // declares (plan 9.7): float4 c# registers, then int4 i#, then one
        // 32-bit slot per bool b#. `def`/`defi`/`defb` literals are written
        // last because a shader's own constant definitions take effect while
        // it is bound, over whatever the app last set for that register.
        writeConstantRegisters(backing, byteOffset, reflection, constF, constI,
                constB, state) {
            const floats = new Float32Array(backing, byteOffset,
                reflection.floatConstCount * 4);
            floats.set(constF.subarray(0, Math.min(constF.length, floats.length)));
            for (const item of reflection.floatDefaults) {
                if ((item.register + 1) * 4 > floats.length) continue;
                floats.set(item.values, item.register * 4);
            }
            const intOffset = byteOffset + reflection.floatRegionBytes;
            const ints = new Int32Array(backing, intOffset, reflection.intConstCount * 4);
            ints.set(constI.subarray(0, Math.min(constI.length, ints.length)));
            for (const item of reflection.intDefaults) {
                if ((item.register + 1) * 4 > ints.length) continue;
                ints.set(item.values, item.register * 4);
            }
            const boolOffset = intOffset + reflection.intRegionBytes;
            const bools = new Uint32Array(backing, boolOffset,
                reflection.boolVectorCount * 4);
            bools.set(constB.subarray(0, Math.min(constB.length, bools.length)));
            for (const item of reflection.boolDefaults) {
                if (item.register >= bools.length) continue;
                bools[item.register] = item.value ? 1 : 0;
            }
            // Every translated vertex shader reads this for the D3D9 half-pixel
            // offset (see the o_position fixup in d3d9_shader_pipeline.js). The
            // viewport is what maps clip space to pixels, so it -- not the
            // render target extent -- is what a half pixel is measured against.
            if (reflection.viewportOffset >= 0 && state) {
                const values = new Float32Array(backing, byteOffset);
                const slot = reflection.viewportOffset / 4;
                values[slot] = Math.max(1, state.viewport.width || 1);
                values[slot + 1] = Math.max(1, state.viewport.height || 1);
            }
            if (reflection.clipPlanesOffset >= 0 && state) {
                const values = new Float32Array(backing, byteOffset);
                const base = reflection.clipPlanesOffset / 4;
                const mask = (state.renderStates.get(
                    D3DRS_CLIPPLANEENABLE) || 0) & 0x3f;
                for (let plane = 0; plane < reflection.clipPlaneCount; ++plane)
                    values.set((mask & (1 << plane))
                        ? state.clipPlanes[plane] : [0, 0, 0, 1],
                        base + plane * 4);
            }
            if (reflection.bumpStageCount && state) {
                // ps_1_x texbem/texbeml read the D3DTSS_BUMPENVMAT* matrix of
                // the sampler they address. That is texture-stage state rather
                // than shader state, so it is written here alongside the
                // register file rather than coming from SetPixelShaderConstant.
                const values = new Float32Array(backing, byteOffset);
                const stageFloat = (stage, id) => {
                    const raw = state.textureStageStates.get(stage * 64 + id);
                    if (raw === undefined) return 0;
                    FLOAT_BITS_U32[0] = raw >>> 0;
                    return FLOAT_BITS_F32[0];
                };
                for (let stage = 0; stage < reflection.bumpStageCount; ++stage) {
                    const base = reflection.bumpOffset / 4 + stage * 4;
                    values[base] = stageFloat(stage, D3DTSS_BUMPENVMAT00);
                    values[base + 1] = stageFloat(stage, D3DTSS_BUMPENVMAT01);
                    values[base + 2] = stageFloat(stage, D3DTSS_BUMPENVMAT10);
                    values[base + 3] = stageFloat(stage, D3DTSS_BUMPENVMAT11);
                    const lum = reflection.bumpLuminanceOffset / 4 + stage * 4;
                    values[lum] = stageFloat(stage, D3DTSS_BUMPENVLSCALE);
                    values[lum + 1] = stageFloat(stage, D3DTSS_BUMPENVLOFFSET);
                    values[lum + 2] = 0;
                    values[lum + 3] = 0;
                }
            }
            if (reflection.pointExpansion && state) {
                const values = new Float32Array(backing, byteOffset);
                const viewport = reflection.pointViewportOffset / 4;
                const width = Math.max(1, state.viewport.width || 1);
                const height = Math.max(1, state.viewport.height || 1);
                values[viewport] = width;
                values[viewport + 1] = height;
                values[viewport + 2] = 1 / width;
                values[viewport + 3] = 1 / height;
                const point = reflection.pointParamsOffset / 4;
                const pointFloat = (id, fallback) => {
                    const raw = state.renderStates.get(id);
                    return raw === undefined ? fallback : floatFromDWORD(raw);
                };
                values[point] = pointFloat(D3DRS_POINTSIZE, 1);
                values[point + 1] = Math.max(0,
                    pointFloat(D3DRS_POINTSIZE_MIN, 1));
                values[point + 2] = Math.max(values[point + 1],
                    pointFloat(D3DRS_POINTSIZE_MAX, 64));
            }
        }

        // The view a stage samples through. D3DSAMP_SRGBTEXTURE asks D3D9 to
        // decode the texture from sRGB to linear on read; ignoring it hands the
        // shader values that are substantially *brighter* than the app intends
        // (sRGB 0.5 is linear 0.21), which on anything additive -- an
        // environment-mapped reflection above all -- reads as blown-out white
        // rather than as a subtle gamma difference.
        // The single point where a sampler stage turns into a bind group
        // resource, and the only one allowed to decide that a bound texture
        // cannot be sampled. Every path out of here returns a real view:
        // createBindGroup rejects null with a TypeError rather than a WebGPU
        // validation error, so it escapes executeBatch and destroys the rest of
        // the batch -- the draw that could not be drawn takes every unrelated
        // command queued behind it along with it. A visibly wrong stage is a
        // far smaller fault than a silently truncated command stream.
        viewForStage(texture, stage, depth, dimension, unfilterable, wantsSRGB,
                isCurrentDepthAttachment) {
            if (!texture)
                return this.fallbackViewFor(depth ? "depth" : dimension,
                    unfilterable);
            // WebGPU forbids a texture being an attachment and a sampled
            // resource in the same pass, and enforces it by failing the submit
            // rather than the draw. The normal shadow-map sequence unbinds the
            // map before reading it, so this is the app doing something D3D9
            // tolerates and WebGPU does not -- one degraded stage is the only
            // outcome that keeps the rest of the frame alive.
            if (isCurrentDepthAttachment) {
                ++this.stats.depthAttachmentSampledInPlace;
                this.warnOnce("depth-attachment-sampled-" + stage,
                    "a depth surface is sampled while it is still bound as " +
                    "this pass's depth attachment; WebGPU cannot read and " +
                    "write one texture in a single pass, so the stage reads " +
                    "the fallback", { stage });
                return this.fallbackViewFor(depth ? "depth" : dimension,
                    unfilterable);
            }
            if (depth) {
                // The layout says texture_depth_2d; only a depth texture can
                // fill it. A colour texture bound to a stage the shader samples
                // as a shadow map means the app changed bindings without the
                // pipeline being rebuilt, which the pipeline key rules out --
                // but the cost of being wrong is the whole submit.
                if (texture.isDepth && texture.view) return texture.view;
                ++this.stats.depthStageWithoutDepthTexture;
                this.warnOnce("depth-stage-not-depth-" + stage,
                    "a stage the pixel shader samples as a hardware shadow " +
                    "map has no sampleable depth texture bound; it reads the " +
                    "1x1 depth fallback, which compares as fully lit", {
                        stage,
                        format: texture.format,
                        isDepth: !!texture.isDepth,
                    });
                return this.fallbackViewFor("depth", false);
            }
            if (texture.isDepth) {
                // Reachable through the fixed-function cascade and through
                // vertex texture fetch, neither of which has a comparison
                // reference to offer. Sampling the raw depth aspect through a
                // float layout entry is not merely wrong, it is invalid.
                ++this.stats.depthTextureOnNonDepthStage;
                this.warnOnce("depth-texture-plain-stage-" + stage,
                    "a depth texture is bound to a stage that is not a " +
                    "translated pixel shader's shadow-map sampler (fixed " +
                    "function, or vertex texture fetch); D3D9 would return a " +
                    "hardware comparison there and this backend has no " +
                    "reference value to compare against, so the stage reads " +
                    "the 1x1 white fallback", { stage, format: texture.format });
                return this.fallbackViewFor(dimension, unfilterable);
            }
            const view = this.sampledViewFor(texture, wantsSRGB);
            if (view) return view;
            ++this.stats.stagesWithoutSampleableView;
            this.warnOnce("stage-no-view-" + stage,
                "a bound texture has no sampleable view; the stage reads the " +
                "1x1 white fallback rather than failing the draw", {
                    stage, format: texture.format,
                    gpuFormat: texture.gpuFormat });
            return this.fallbackViewFor(dimension, unfilterable);
        }

        // D3D9 hardware shadow maps return 1.0 where the reference depth is at
        // or in front of the stored depth, i.e. where the fragment is lit.
        // Filtering is what makes the comparison a PCF tap rather than a hard
        // test, so it follows the stage's own filter state: a shadow map
        // sampled with POINT should not silently acquire soft edges.
        comparisonSamplerFor(state, stage) {
            const get = (id, fallback) => {
                const value = state.samplerStates.get(stage * 64 + id);
                return value === undefined ? fallback : value;
            };
            const addressU = get(D3DSAMP_ADDRESSU, 1);
            const addressV = get(D3DSAMP_ADDRESSV, 1);
            const linear = (get(D3DSAMP_MAGFILTER, 1) !== 0) &&
                (get(D3DSAMP_MINFILTER, 1) !== 0);
            const key = "cmp," + addressU + "," + addressV + "," +
                (linear ? "linear" : "nearest");
            const cached = this.samplerCache.get(key);
            if (cached) { ++this.stats.samplerHits; return cached; }
            const sampler = this.device.createSampler({
                addressModeU: ADDRESS_MODES[addressU] || "repeat",
                addressModeV: ADDRESS_MODES[addressV] || "repeat",
                magFilter: linear ? "linear" : "nearest",
                minFilter: linear ? "linear" : "nearest",
                compare: "less-equal",
            });
            ++this.stats.samplersCreated;
            ++this.stats.comparisonSamplersCreated;
            this.samplerCache.set(key, sampler);
            return sampler;
        }

        sampledViewFor(texture, wantsSRGB) {
            if (!wantsSRGB) return texture.view;
            if (!texture.srgbFormat) {
                ++this.stats.srgbTextureUnavailable;
                this.warnOnce("srgb-no-sibling",
                    "a stage asks for sRGB decoding on a texture whose format " +
                    "has no -srgb equivalent in WebGPU, so it is sampled as " +
                    "linear and comes out too bright", { format: texture.format,
                        gpuFormat: texture.gpuFormat });
                return texture.view;
            }
            if (!texture.srgbView) {
                texture.srgbView = texture.gpuTexture.createView({
                    format: texture.srgbFormat,
                    dimension: texture.textureType === "cube" ? "cube" : "2d",
                });
                ++this.stats.srgbViewsCreated;
            }
            ++this.stats.srgbTextureSamples;
            return texture.srgbView;
        }

        // A 1x1 opaque white stand-in per view dimension, for a stage the
        // shader samples but the app left unbound. "depth" is not a view
        // dimension but is threaded through the same cache because it plays
        // the same role: the stand-in a depth slot reads when nothing usable
        // is bound.
        fallbackViewFor(dimension, unfilterable) {
            if (dimension === "depth") return this.fallbackDepthView();
            if ((dimension === "2d" || !dimension) && !unfilterable)
                return this.fallbackView;
            if (!this.fallbackViews) this.fallbackViews = new Map();
            const key = (dimension || "2d") + (unfilterable ? "|f32" : "|u8");
            let view = this.fallbackViews.get(key);
            if (view) return view;
            const layers = dimension === "cube" ? 6 : 1;
            const texture = this.device.createTexture({
                label: "D3D9 fallback white " + key,
                size: { width: 1, height: 1, depthOrArrayLayers: layers },
                format: unfilterable ? "rgba32float" : "rgba8unorm",
                dimension: dimension === "3d" ? "3d" : "2d",
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            for (let layer = 0; layer < layers; ++layer) {
                this.device.queue.writeTexture(
                    { texture, origin: { x: 0, y: 0, z: layer } },
                    unfilterable
                        ? new Float32Array([1, 1, 1, 1])
                        : new Uint8Array([255, 255, 255, 255]),
                    { bytesPerRow: unfilterable ? 16 : 4, rowsPerImage: 1 },
                    { width: 1, height: 1, depthOrArrayLayers: 1 });
            }
            view = texture.createView({ dimension: dimension || "2d" });
            this.fallbackViews.set(key, view);
            return view;
        }

        // The depth counterpart of the 1x1 white texture. It has to read as
        // "nothing occludes this fragment", and for a less-equal comparison
        // that means the far plane. A fresh WebGPU texture zero-initialises,
        // which is the near plane and would come out fully shadowed, so it is
        // cleared through an empty render pass -- depth formats cannot be
        // written with writeTexture.
        fallbackDepthView() {
            if (this.fallbackDepth) return this.fallbackDepth;
            const texture = this.device.createTexture({
                label: "D3D9 fallback depth (far plane)",
                size: { width: 1, height: 1, depthOrArrayLayers: 1 },
                format: DEPTH_FORMAT,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT |
                    TEXTURE_USAGE_TEXTURE_BINDING,
            });
            const encoder = this.device.createCommandEncoder(
                { label: "D3D9 fallback depth clear" });
            encoder.beginRenderPass({
                colorAttachments: [],
                depthStencilAttachment: {
                    view: texture.createView(),
                    depthClearValue: 1.0,
                    depthLoadOp: "clear",
                    depthStoreOp: "store",
                    stencilClearValue: 0,
                    stencilLoadOp: "clear",
                    stencilStoreOp: "store",
                },
            }).end();
            this.device.queue.submit([encoder.finish()]);
            this.fallbackDepth = texture.createView({ aspect: "depth-only" });
            return this.fallbackDepth;
        }

        retireAfterSubmit(buffer) {
            const frame = this.ensureFrame();
            (frame.transientBuffers || (frame.transientBuffers = [])).push(buffer);
        }

        bindGroupFor(state, pipeline, program, constants) {
            const entries = [{ binding: 0, resource: { buffer: constants.buffer,
                offset: 0, size: Math.max(16, constants.vertexBytes) } }];
            const identity = [pipeline._d9wgId || this.objectId(pipeline),
                this.objectId(constants.buffer), constants.vertexBytes,
                constants.pixelOffset, constants.pixelBytes];
            if (program.pixelUniformBytes)
                entries.push({ binding: 1, resource: { buffer: constants.buffer,
                    offset: constants.pixelOffset,
                    size: Math.max(16, constants.pixelBytes) } });
            for (const index of program.samplerIndices) {
                const handle = state.textures.get(index);
                const texture = this.resources.get(handle);
                if (texture && texture.mipsDirty) this.flushGeneratedMips(texture);
                if (texture && this.frame) texture.frameReferenced = this.frame.serial;
                const expectedUploads = texture
                    ? texture.levelCount * (texture.layerCount || 1) : 0;
                // A completely untouched texture is not evidence of a lost
                // upload.  D3D permits a dynamic/scratch texture to be bound
                // before its first write (3DMark 99 does this for the 256x256
                // frame-capture texture), and WebGPU safely zero-initialises
                // the allocation meanwhile.  Only a partially initialised
                // chain proves that the app supplied some subresources while
                // leaving other mip levels or cube faces unavailable.
                const initializedUploads = texture && texture.uploadedLevels
                    ? texture.uploadedLevels.size : 0;
                if (texture && texture.uploadedLevels &&
                        initializedUploads > 0 &&
                        initializedUploads < expectedUploads) {
                    ++this.stats.drawsWithIncompleteMipChain;
                    this.warnOnce("incomplete-mips",
                        "a bound texture has a partially initialized mip or " +
                        "cube-face chain; sampling a missing subresource can " +
                        "show the wrong image. Try " +
                        "v86gl.d3d9Executor.debug.forceMipLevel0 = true to " +
                        "check whether missing mip levels are responsible.", {
                            handle,
                            format: texture.format,
                            size: texture.width + "x" + texture.height,
                            declaredLevels: texture.levelCount,
                            layers: texture.layerCount || 1,
                            uploaded: [...texture.uploadedLevels].sort(
                                (a, b) => a - b).map(key =>
                                    "level " + Math.floor(key / 6) +
                                    " layer " + (key % 6)),
                        });
                }
                // A shader can sample a stage the app left unbound; a 1x1 white
                // texture keeps the draw legal and visually neutral rather than
                // dropping it. It has to match the dimension the layout
                // declares, so there is one per dimension.
                const dimension = (program.samplerDimensions &&
                    program.samplerDimensions[index]) || "2d";
                const bindingType = program.samplerBindingTypes &&
                    program.samplerBindingTypes[index];
                const unfilterable = bindingType === "unfilterable";
                const compare = bindingType === "depth-compare";
                const depth = compare || bindingType === "depth-fetch";
                const wantsSRGB = texture &&
                    (state.samplerStates.get(index * 64 + D3DSAMP_SRGBTEXTURE)
                        || 0) !== 0;
                const fixedStage = program.pixelSignature &&
                    program.pixelSignature.stages.find(stage =>
                        stage.index === index);
                const indexedView = texture && texture.ddIndexed &&
                    typeof this.ddIndexedSampleViewFor === "function"
                    ? this.ddIndexedSampleViewFor(texture,
                        fixedStage ? fixedStage.colorKey : null)
                    : null;
                const view = indexedView || this.viewForStage(texture, index,
                    depth, dimension, unfilterable, wantsSRGB,
                    !!handle && handle === state.depthTargetHandle);
                const sampler = compare
                    ? this.comparisonSamplerFor(state, index)
                    : this.samplerFor(state, index, depth || unfilterable,
                        texture);
                entries.push(
                    { binding: 2 + index * 2,
                      resource: view },
                    { binding: 3 + index * 2,
                      resource: sampler });
                identity.push(index, this.objectId(view), this.objectId(sampler));
            }
            for (const binding of program.vertexSamplers || []) {
                const texture = this.resources.get(
                    state.textures.get(binding.stage));
                if (texture && texture.mipsDirty) this.flushGeneratedMips(texture);
                if (texture && this.frame)
                    texture.frameReferenced = this.frame.serial;
                const unfilterable = binding.bindingType === "unfilterable";
                const wantsSRGB = texture &&
                    (state.samplerStates.get(binding.stage * 64 +
                        D3DSAMP_SRGBTEXTURE) || 0) !== 0;
                const view = this.viewForStage(texture, binding.stage, false,
                    binding.type, unfilterable, wantsSRGB);
                const sampler = this.samplerFor(state, binding.stage,
                    unfilterable, texture);
                entries.push(
                    { binding: binding.textureBinding, resource: view },
                    { binding: binding.samplerBinding, resource: sampler });
                identity.push(binding.stage, this.objectId(view),
                    this.objectId(sampler));
            }
            const dynamicOffsets = program.pixelUniformBytes
                ? [constants.dynamicOffset, constants.dynamicOffset]
                : [constants.dynamicOffset];
            // Overflow buffers are destroyed after this submit, so a group
            // that captures one must not outlive the frame. The persistent
            // ring is the steady-state path and is safe to cache.
            const cacheable = !constants.transient;
            const key = identity.join(":");
            if (cacheable) {
                const cached = this.bindGroupCache.get(key);
                if (cached) {
                    this.bindGroupCache.delete(key);
                    this.bindGroupCache.set(key, cached);
                    ++this.stats.bindGroupHits;
                    return { group: cached, dynamicOffsets };
                }
            }
            const group = this.device.createBindGroup(
                { layout: pipeline._bindGroupLayout, entries });
            ++this.stats.bindGroupCreations;
            if (cacheable) {
                while (this.bindGroupCache.size >= this.maxBindGroups) {
                    const oldest = this.bindGroupCache.keys().next();
                    if (oldest.done) break;
                    this.bindGroupCache.delete(oldest.value);
                    ++this.stats.bindGroupCacheEvictions;
                }
                this.bindGroupCache.set(key, group);
            }
            return { group, dynamicOffsets };
        }

        // Builds the pipeline/uniform buffer/bind group eagerly (none of
        // those are tied to the swapchain's current texture, so there is no
        // staleness concern in creating them now) but only *records* the
        // draw as a pending op -- see the comment on ensureFrame() for why
        // the actual pass.draw()/drawIndexed() call must wait until
        // finishFrame() replays it against a freshly-acquired texture.
        //
        // The stride each stream contributes is the one the application bound
        // via SetStreamSource (or that a Draw*UP command carried). It must
        // never be inferred from the vertex declaration: a declaration's
        // consumed elements are only part of the vertex, so a computed stride
        // is too small whenever the format carries anything the shader skips
        // (NORMAL, extra texcoords, padding) and every vertex after the first
        // would then be fetched from the wrong offset.
        recordDraw(state, elements, which, geometry) {
            const targets = this.renderTargetsFor(state);
            if (!targets) {
                this.noteDroppedDraw(which, state,
                    ["no usable colour render target is bound"]);
                return;
            }
            // D3DRS_FILLMODE. WebGPU has no polygon mode, so wireframe is
            // reached by rewriting the topology and the indices instead: every
            // triangle becomes its three edges as a line list. Done here, at
            // the single funnel every draw path reaches, rather than at the
            // four Draw* entry points -- and after the fan conversion above it,
            // so a fan is already an ordinary triangle list by the time it
            // arrives.
            geometry = this.applyFillMode(state, geometry) || geometry;
            // A draw against a stand-in depth attachment that nothing cleared
            // is the one case where standing in changed the image; anything
            // else has no earlier contents to have lost.
            if (targets.substituteDepth &&
                    (state.renderStates.get(D3DRS_ZENABLE) || 0) !== 0)
                this.noteSubstituteDepthUse(targets, false);
            const pipelineState = this.pipelineStateFor(state, targets);
            // A point-list that came from D3DFILL_POINT is not a point
            // sprite: sprite expansion is what D3DRS_POINTSPRITEENABLE asks
            // for, and a wireframe-mode triangle mesh asked for neither.
            const pointExpansion = geometry.topology === "point-list" &&
                !geometry.indexInfo && !geometry.fromFillMode;
            const instanceCount = this.drawInstanceCount(state);
            const hasInstanceStream = Array.from(state.streams.values()).some(stream =>
                (((stream.frequency ?? 1) >>> 0) &
                    D3DSTREAMSOURCE_INSTANCEDATA) !== 0);
            if (instanceCount > 1 && !geometry.indexInfo && !pointExpansion) {
                this.noteDroppedDraw(which, state,
                    ["D3D9 indexed instancing requires an indexed draw"]);
                return;
            }
            if (pointExpansion && (instanceCount !== 1 || hasInstanceStream)) {
                this.noteDroppedDraw(which, state,
                    ["point expansion cannot share WebGPU instance slots with D3D9 instancing"]);
                return;
            }
            const pointSprite = pointExpansion &&
                (state.renderStates.get(D3DRS_POINTSPRITEENABLE) || 0) !== 0;
            const program = this.programFor(state, elements, pipelineState,
                { pointExpansion, pointSprite });
            if (program.error) {
                if (program.shaderError) ++this.stats.drawsSkippedForBadShader;
                this.noteDroppedDraw(which, state, [program.error]);
                return;
            }
            const pipeline = this.pipelineFor(program, pipelineState,
                pointExpansion ? "triangle-list" : geometry.topology,
                pointExpansion ? undefined : geometry.stripIndexFormat);
            // The bind group captures concrete GPUTextureView objects. Create
            // the frame first so bindGroupFor can mark those textures as read;
            // a later UPDATE_TEXTURE can then rename instead of retroactively
            // changing this already-recorded draw. A draw without a preceding
            // Clear is legal and used by War3's UI passes, so relying on Clear
            // to create the frame misses exactly those textures.
            const frame = this.ensureFrame();
            const constants = this.constantBufferFor(state, program);
            const binding = this.bindGroupFor(state, pipeline, program, constants);
            const prepared = this.prepareInstanceStreams(
                geometry.streams, instanceCount);
            if (prepared.error) {
                this.noteDroppedDraw(which, state, [prepared.error]);
                return;
            }
            geometry = { ...geometry, streams: prepared.streams };
            // Bind each stream the pipeline declared a layout for, in the same
            // order, so slot N in the pipeline is slot N here.
            const vertexBuffers = [];
            for (const layout of program.vertexBuffers) {
                if (layout.stream === DEFAULT_ATTRIBUTE_STREAM) {
                    vertexBuffers.push({ buffer: this.defaultAttributeBuffer(), offset: 0 });
                    continue;
                }
                const binding = geometry.streams.get(layout.stream);
                if (!binding) {
                    this.noteDroppedDraw(which, state,
                        ["stream " + layout.stream + " is referenced by the " +
                         "declaration but not bound"]);
                    return;
                }
                vertexBuffers.push({ buffer: binding.buffer, offset: binding.offset });
            }
            // Mark every buffer this draw reads as "observed at this frame's
            // contents". applyBufferUpdate() uses that to notice a write that
            // would retroactively change what an already-recorded draw sees.
            for (const layout of program.vertexBuffers) {
                const binding = geometry.streams.get(layout.stream);
                if (binding && binding.resource)
                    binding.resource.frameReferenced = frame.serial;
            }
            if (geometry.indexResource)
                geometry.indexResource.frameReferenced = frame.serial;
            // D3DRS_SCISSORTESTENABLE gates the rect; without it D3D9 ignores
            // whatever SetScissorRect last set.
            const scissorEnabled =
                (state.renderStates.get(D3DRS_SCISSORTESTENABLE) || 0) !== 0 &&
                !!state.scissorRect;
            if (scissorEnabled) ++this.stats.drawsWithScissor;
            const attachmentCount = Math.max(1, Math.min(4,
                (targets.colors && targets.colors.length) || 1));
            ++this.mrtAttachmentDraws[attachmentCount];
            pipeline._d9wgDrawCount = (pipeline._d9wgDrawCount || 0) + 1;
            const drawPath = (state.vertexShaderHandle ||
                state.pixelShaderHandle) ? "programmable" : "fixed";
            // References are retained, not expanded, on the hot draw path.
            // blackScreenReport() serialises the two most recent paths only
            // when explicitly requested, avoiding per-draw diagnostic copies
            // during a real benchmark run.
            this.lastDraws[drawPath] = {
                which, state, elements, geometry, program, pipelineState,
                targets, pipeline,
            };
            frame.ops.push({
                kind: "draw", pipeline, bindGroup: binding.group,
                dynamicOffsets: binding.dynamicOffsets, targets,
                viewport: { ...state.viewport },
                scissor: scissorEnabled ? { ...state.scissorRect } : null,
                blendConstant: pipelineState.blendConstant,
                stencilReference: pipelineState.stencilReference,
                vertexBuffers, indexInfo: geometry.indexInfo,
                vertexCount: pointExpansion ? 6 : geometry.vertexCount,
                instanceCount: pointExpansion ? geometry.vertexCount : instanceCount,
            });
            if (pointExpansion) {
                ++this.stats.pointSpriteDraws;
                this.stats.pointSpriteInstances += geometry.vertexCount || 0;
            }
            if (!pointExpansion && instanceCount > 1) {
                ++this.stats.instancedDraws;
                this.stats.instancesDrawn += instanceCount;
            }
            // The pointer is almost always the final thing a frame draws, so
            // the texture bound by the last draw is the quickest way to name
            // the cursor's texture without hunting through the whole atlas set.
            if (program.samplerIndices.length)
                this.stats.lastDrawTexture =
                    state.textures.get(program.samplerIndices[0]) || 0;
            if (state.vertexShaderHandle || state.pixelShaderHandle)
                ++this.stats.programmableDraws;
            if (geometry.indexInfo) ++this.stats.indexedDrawCalls;
            else ++this.stats.drawCalls;
        }

        // Every draw path below can bail out for several different reasons,
        // and silently dropping them looks identical to "the app never drew"
        // from the outside -- exactly the blind spot that hid a stalled
        // renderer behind healthy-looking batch/present counters. Count every
        // drop and describe the first one in full.
        noteDroppedDraw(which, state, reasons) {
            ++this.stats.droppedDraws;
            const key = which + ":" + reasons.join(";");
            this.droppedDrawReasons = this.droppedDrawReasons || new Set();
            if (this.droppedDrawReasons.has(key)) return;
            this.droppedDrawReasons.add(key);
            const declaration = this.resources.get(state.vertexDeclarationHandle);
            console.warn("[d3d9-webgpu] " + which + " dropped: " +
                reasons.join("; "), {
                    reasons,
                    hasFvfElements: !!state.fvfElements,
                    vertexDeclarationHandle: state.vertexDeclarationHandle,
                    declarationResourceFound: !!declaration,
                    declarationElements: this.currentElements(state),
                    vertexShaderHandle: state.vertexShaderHandle,
                    pixelShaderHandle: state.pixelShaderHandle,
                    stream0: state.streams.get(0) || null,
                    indexBufferHandle: state.indexBufferHandle,
                    resourceCount: this.resources.size,
                });
        }

        // Collects the vertex buffers a draw will bind, keyed by stream. The
        // per-stream byte offset folds in both SetStreamSource's OffsetInBytes
        // and (for a non-indexed draw) StartVertex, because WebGPU takes the
        // first-vertex offset on setVertexBuffer rather than on draw().
        boundStreams(state, extraVertexOffset) {
            const streams = new Map();
            for (const [index, binding] of state.streams) {
                const resource = this.resources.get(binding.bufferHandle);
                if (!resource || !resource.gpuBuffer) continue;
                const frequency = (binding.frequency ?? 1) >>> 0;
                const instanced =
                    (frequency & D3DSTREAMSOURCE_INSTANCEDATA) !== 0;
                streams.set(index, { buffer: resource.gpuBuffer, resource,
                    stride: binding.stride || 0, frequency,
                    offset: (binding.offsetInBytes || 0) +
                        (instanced ? 0 : (extraVertexOffset || 0)) *
                            (binding.stride || 0) });
            }
            return streams;
        }

        drawInstanceCount(state) {
            const stream0 = state.streams.get(0);
            const frequency = (stream0 && (stream0.frequency ?? 1)) >>> 0;
            if ((frequency & D3DSTREAMSOURCE_INDEXEDDATA) === 0) return 1;
            return frequency & D3DSTREAMSOURCE_FREQUENCY_MASK;
        }

        // WebGPU exposes vertex/instance step modes but no D3D9-style
        // instance divisor. A divisor of one binds directly. For larger
        // divisors, expand the CPU mirror into a transient, tightly matching
        // the sequence D3D9 specifies (record 0 repeated divisor times, then
        // record 1, and so on). Dynamic vertex buffers already maintain this
        // mirror for draw-order correctness, so this is exact rather than an
        // approximation.
        prepareInstanceStreams(streams, instanceCount) {
            let result = streams;
            for (const [streamIndex, binding] of streams) {
                const frequency = (binding.frequency ?? 1) >>> 0;
                if ((frequency & D3DSTREAMSOURCE_INSTANCEDATA) === 0) continue;
                const divisor = frequency & D3DSTREAMSOURCE_FREQUENCY_MASK;
                if (!divisor)
                    return { error: "instance stream " + streamIndex +
                        " has a zero step rate" };
                if (divisor === 1) continue;
                const stride = binding.stride || 0;
                const shadow = binding.resource && binding.resource.shadow;
                if (!stride || !shadow)
                    return { error: "instance stream " + streamIndex +
                        " cannot be expanded without a CPU buffer mirror" };
                const outputBytes = instanceCount * stride;
                if (!Number.isSafeInteger(outputBytes) || outputBytes <= 0)
                    return { error: "instance stream expansion size is invalid" };
                const output = new Uint8Array(alignUp(outputBytes, 4));
                for (let instance = 0; instance < instanceCount; ++instance) {
                    const source = binding.offset +
                        Math.floor(instance / divisor) * stride;
                    if (source < 0 || source + stride > shadow.length)
                        return { error: "instance stream " + streamIndex +
                            " references data outside its vertex buffer" };
                    output.set(shadow.subarray(source, source + stride),
                        instance * stride);
                }
                const buffer = this.device.createBuffer({
                    label: "D3D9 instance divisor expansion",
                    size: Math.max(4, output.byteLength),
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
                });
                this.writeBufferAligned(buffer, 0, output, 0, outputBytes);
                this.retireAfterSubmit(buffer);
                if (result === streams) result = new Map(streams);
                result.set(streamIndex, { buffer, offset: 0, stride,
                    frequency: D3DSTREAMSOURCE_INSTANCEDATA | 1 });
                ++this.stats.expandedInstanceStreams;
            }
            return { streams: result };
        }

        // WebGPU cannot combine an index buffer with instance-rate source
        // attributes to select an arbitrary point for each instance. Indexed
        // point lists are uncommon but legal, so compact the referenced
        // vertices from the guest-maintained CPU shadows into transient,
        // sequential streams before using the same quad-expansion pipeline.
        expandIndexedPointStreams(state, streams, indexResource, firstIndex,
                indexCount, baseVertex) {
            if (!indexResource || !indexResource.shadow) return null;
            const wide = indexResource.indexFormat === "uint32";
            const indices = wide
                ? new Uint32Array(indexResource.shadow.buffer,
                    indexResource.shadow.byteOffset,
                    indexResource.shadow.byteLength >>> 2)
                : new Uint16Array(indexResource.shadow.buffer,
                    indexResource.shadow.byteOffset,
                    indexResource.shadow.byteLength >>> 1);
            if (firstIndex + indexCount > indices.length) return null;
            const result = new Map();
            for (const [streamIndex, binding] of streams) {
                const streamState = state.streams.get(streamIndex);
                const stride = streamState && streamState.stride;
                const shadow = binding.resource && binding.resource.shadow;
                if (!stride || !shadow) return null;
                const outputBytes = indexCount * stride;
                const output = new Uint8Array(alignUp(outputBytes, 4));
                for (let point = 0; point < indexCount; ++point) {
                    const vertex = Number(indices[firstIndex + point]) + baseVertex;
                    if (vertex < 0) return null;
                    const source = binding.offset + vertex * stride;
                    if (source < 0 || source + stride > shadow.length) return null;
                    output.set(shadow.subarray(source, source + stride), point * stride);
                }
                const buffer = this.device.createBuffer({
                    label: "D3D9 indexed point expansion",
                    size: Math.max(4, output.byteLength),
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
                });
                this.writeBufferAligned(buffer, 0, output, 0, outputBytes);
                this.retireAfterSubmit(buffer);
                result.set(streamIndex, { buffer, offset: 0 });
            }
            ++this.stats.indexedPointExpansions;
            return result;
        }

        onDrawPrimitive(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const primitiveType = view.getUint32(offset + 4, true);
            const startVertex = view.getUint32(offset + 8, true);
            const primitiveCount = view.getUint32(offset + 12, true);
            const state = this.deviceState(deviceHandle);
            const elements = this.currentElements(state);
            if (!elements) {
                this.noteDroppedDraw("DrawPrimitive", state,
                    ["no vertex declaration (SetFVF/SetVertexDeclaration)"]);
                return;
            }
            const vertexCount = primitiveElementCount(primitiveType, primitiveCount);
            if (vertexCount === null) {
                this.noteDroppedDraw("DrawPrimitive", state,
                    ["unsupported primitive type " + primitiveType]);
                return;
            }
            const streams = this.boundStreams(state, startVertex);
            if (primitiveType === D3DPT_TRIANGLEFAN) {
                // WebGPU has no fan topology; synthesise the index buffer that
                // turns one into a triangle list.
                const fan = this.triangleFanIndexBuffer(vertexCount);
                if (!fan) {
                    this.noteDroppedDraw("DrawPrimitive", state,
                        ["triangle fan with too few vertices"]);
                    return;
                }
                this.recordDraw(state, elements, "DrawPrimitive", {
                    topology: "triangle-list", streams,
                    indexInfo: { buffer: fan.buffer, format: "uint32", offset: 0,
                        count: (vertexCount - 2) * 3, firstIndex: 0, baseVertex: 0,
                        cpuIndices: fan.indices },
                });
                return;
            }
            this.recordDraw(state, elements, "DrawPrimitive", {
                topology: topologyFor(primitiveType), streams,
                indexInfo: null, vertexCount,
            });
        }

        onDrawIndexedPrimitive(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const primitiveType = view.getUint32(offset + 4, true);
            const baseVertexIndex = view.getInt32(offset + 8, true);
            const startIndex = view.getUint32(offset + 20, true);
            const primitiveCount = view.getUint32(offset + 24, true);
            const state = this.deviceState(deviceHandle);
            const elements = this.currentElements(state);
            const ib = this.resources.get(state.indexBufferHandle);
            if (!elements || !ib) {
                const reasons = [];
                if (!elements) reasons.push("no vertex declaration (SetFVF/SetVertexDeclaration)");
                if (!ib) reasons.push("index buffer resource missing");
                this.noteDroppedDraw("DrawIndexedPrimitive", state, reasons);
                return;
            }
            const indexCount = primitiveElementCount(primitiveType, primitiveCount);
            if (indexCount === null) {
                this.noteDroppedDraw("DrawIndexedPrimitive", state,
                    ["unsupported primitive type " + primitiveType]);
                return;
            }
            const streams = this.boundStreams(state, 0);
            if (primitiveType === D3DPT_POINTLIST) {
                const expanded = this.expandIndexedPointStreams(state, streams,
                    ib, startIndex, indexCount, baseVertexIndex);
                if (!expanded) {
                    this.noteDroppedDraw("DrawIndexedPrimitive", state,
                        ["indexed point list could not be compacted from buffer shadows"]);
                    return;
                }
                this.recordDraw(state, elements, "DrawIndexedPrimitive", {
                    topology: "point-list", streams: expanded,
                    indexInfo: null, vertexCount: indexCount,
                });
                return;
            }
            if (primitiveType === D3DPT_TRIANGLEFAN) {
                // Re-index the fan through the buffer's CPU mirror; the GPU
                // copy is write-only from here.
                const converted = this.triangleFanFromIndices(ib, startIndex, indexCount);
                if (!converted) {
                    this.noteDroppedDraw("DrawIndexedPrimitive", state,
                        ["indexed triangle fan could not be converted"]);
                    return;
                }
                this.recordDraw(state, elements, "DrawIndexedPrimitive", {
                    topology: "triangle-list", streams,
                    indexInfo: { buffer: converted.buffer, format: "uint32",
                        offset: 0, count: converted.count, firstIndex: 0,
                        baseVertex: baseVertexIndex,
                        cpuIndices: converted.indices },
                });
                return;
            }
            const topology = topologyFor(primitiveType);
            this.recordDraw(state, elements, "DrawIndexedPrimitive", {
                topology, streams,
                stripIndexFormat: isStripTopology(topology) ? ib.indexFormat : undefined,
                indexResource: ib,
                indexInfo: { buffer: ib.gpuBuffer, format: ib.indexFormat, offset: 0,
                    count: indexCount, firstIndex: startIndex,
                    baseVertex: baseVertexIndex },
            });
        }

        onDrawPrimitiveUP(bytes, view, offset, length) {
            const deviceHandle = view.getUint32(offset, true);
            const primitiveType = view.getUint32(offset + 4, true);
            const primitiveCount = view.getUint32(offset + 8, true);
            const stride = view.getUint32(offset + 12, true);
            const vertexBytes = view.getUint32(offset + 20, true);
            const dataOffset = view.getUint32(offset + 24, true);
            const state = this.deviceState(deviceHandle);
            const elements = this.currentElements(state);
            if (!elements) {
                this.noteDroppedDraw("DrawPrimitiveUP", state,
                    ["no vertex declaration (SetFVF/SetVertexDeclaration)"]);
                return;
            }
            const elementCount = primitiveElementCount(primitiveType, primitiveCount);
            if (elementCount === null) {
                this.noteDroppedDraw("DrawPrimitiveUP", state,
                    ["unsupported primitive type " + primitiveType]);
                return;
            }
            const buffer = this.device.createBuffer({
                size: Math.max(4, alignUp(vertexBytes, 4)),
                usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
            });
            this.writeBufferAligned(buffer, 0, bytes, dataOffset, vertexBytes);
            this.retireAfterSubmit(buffer);
            // Draw*UP feeds one implicit stream 0 whose stride the command
            // carries, not one bound through SetStreamSource.
            const streams = new Map([[0, { buffer, offset: 0 }]]);
            const geometry = { streams, indexInfo: null, vertexCount: elementCount,
                topology: topologyFor(primitiveType) };
            if (primitiveType === D3DPT_TRIANGLEFAN) {
                const fan = this.triangleFanIndexBuffer(elementCount);
                if (!fan) {
                    this.noteDroppedDraw("DrawPrimitiveUP", state,
                        ["triangle fan with too few vertices"]);
                    return;
                }
                geometry.topology = "triangle-list";
                geometry.indexInfo = { buffer: fan.buffer, format: "uint32",
                    offset: 0, count: (elementCount - 2) * 3, firstIndex: 0,
                    baseVertex: 0, cpuIndices: fan.indices };
            }
            this.recordDrawWithStride(state, elements, "DrawPrimitiveUP",
                geometry, stride);
            ++this.stats.upDrawCalls;
        }

        onDrawIndexedPrimitiveUP(bytes, view, offset) {
            const deviceHandle = view.getUint32(offset, true);
            const primitiveType = view.getUint32(offset + 4, true);
            const primitiveCount = view.getUint32(offset + 16, true);
            const indexFormatValue = view.getUint32(offset + 20, true);
            // M1 never read `stride` out of this payload but referenced it
            // when recording the draw, so every DrawIndexedPrimitiveUP threw
            // a ReferenceError and took the whole batch down with it (the
            // batch's catch handler discarded the frame). War3's main menu
            // happens not to use this entry point, which is why it stayed
            // hidden.
            const stride = view.getUint32(offset + 24, true);
            const indexBytes = view.getUint32(offset + 32, true);
            const vertexBytes = view.getUint32(offset + 36, true);
            const indexDataOffset = view.getUint32(offset + 40, true);
            const vertexDataOffset = view.getUint32(offset + 44, true);
            const state = this.deviceState(deviceHandle);
            const elements = this.currentElements(state);
            if (!elements) {
                this.noteDroppedDraw("DrawIndexedPrimitiveUP", state,
                    ["no vertex declaration (SetFVF/SetVertexDeclaration)"]);
                return;
            }
            const elementCount = primitiveElementCount(primitiveType, primitiveCount);
            if (elementCount === null) {
                this.noteDroppedDraw("DrawIndexedPrimitiveUP", state,
                    ["unsupported primitive type " + primitiveType]);
                return;
            }
            if (primitiveType === D3DPT_POINTLIST) {
                const wide = indexFormatValue === D3DFMT_INDEX32;
                const indexWidth = wide ? 4 : 2;
                if (elementCount * indexWidth > indexBytes) {
                    this.noteDroppedDraw("DrawIndexedPrimitiveUP", state,
                        ["point index payload is shorter than its primitive count"]);
                    return;
                }
                const outputBytes = elementCount * stride;
                const output = new Uint8Array(alignUp(outputBytes, 4));
                for (let point = 0; point < elementCount; ++point) {
                    const indexOffset = indexDataOffset + point * indexWidth;
                    const vertex = wide ? view.getUint32(indexOffset, true)
                        : view.getUint16(indexOffset, true);
                    const source = vertexDataOffset + vertex * stride;
                    if (source < vertexDataOffset ||
                            source + stride > vertexDataOffset + vertexBytes ||
                            source + stride > bytes.byteLength) {
                        this.noteDroppedDraw("DrawIndexedPrimitiveUP", state,
                            ["point index references vertex data outside the payload"]);
                        return;
                    }
                    output.set(bytes.subarray(source, source + stride), point * stride);
                }
                const vertexBuffer = this.device.createBuffer({
                    label: "D3D9 indexed UP point expansion",
                    size: Math.max(4, output.byteLength),
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
                });
                this.writeBufferAligned(vertexBuffer, 0, output, 0, outputBytes);
                this.retireAfterSubmit(vertexBuffer);
                this.recordDrawWithStride(state, elements,
                    "DrawIndexedPrimitiveUP", {
                        topology: "point-list",
                        streams: new Map([[0, { buffer: vertexBuffer, offset: 0 }]]),
                        indexInfo: null, vertexCount: elementCount,
                    }, stride);
                ++this.stats.indexedPointExpansions;
                ++this.stats.upDrawCalls;
                return;
            }
            const vertexBuffer = this.device.createBuffer({
                size: Math.max(4, alignUp(vertexBytes, 4)),
                usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
            });
            const indexBuffer = this.device.createBuffer({
                size: Math.max(4, alignUp(indexBytes, 4)),
                usage: BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST,
            });
            this.writeBufferAligned(vertexBuffer, 0, bytes, vertexDataOffset, vertexBytes);
            this.writeBufferAligned(indexBuffer, 0, bytes, indexDataOffset, indexBytes);
            this.retireAfterSubmit(vertexBuffer);
            this.retireAfterSubmit(indexBuffer);
            const format = indexFormatValue === D3DFMT_INDEX32 ? "uint32" : "uint16";
            const topology = topologyFor(primitiveType);
            if (primitiveType === D3DPT_TRIANGLEFAN) {
                this.noteDroppedDraw("DrawIndexedPrimitiveUP", state,
                    ["indexed triangle fans are not converted on the UP path"]);
                return;
            }
            this.recordDrawWithStride(state, elements, "DrawIndexedPrimitiveUP", {
                topology,
                streams: new Map([[0, { buffer: vertexBuffer, offset: 0 }]]),
                stripIndexFormat: isStripTopology(topology) ? format : undefined,
                indexInfo: { buffer: indexBuffer, format, offset: 0,
                    count: elementCount, firstIndex: 0, baseVertex: 0 },
            }, stride);
            ++this.stats.upDrawCalls;
        }

        // Draw*UP carries its own stride rather than having one bound through
        // SetStreamSource, so vertexBufferLayoutsFor() -- which reads
        // state.streams -- needs stream 0 temporarily standing in for it.
        recordDrawWithStride(state, elements, which, geometry, stride) {
            const saved = state.streams.get(0);
            state.streams.set(0, { bufferHandle: 0, stride, offsetInBytes: 0,
                frequency: 1 });
            try {
                this.recordDraw(state, elements, which, geometry);
            } finally {
                if (saved) state.streams.set(0, saved);
                else state.streams.delete(0);
            }
        }

        // (0,1,2), (0,2,3), (0,3,4)... -- the triangle list a fan of
        // `vertexCount` vertices expands to.
// D3DRS_FILLMODE for a triangle topology. Returns a replacement geometry, or
        // null to leave the draw alone -- which is the common case: solid fill,
        // or a topology that has no interior to fill.
        //
        // WebGPU deliberately omits a polygon mode (Metal and the WebGPU
        // baseline both lack the feature Vulkan calls fillModeNonSolid), so
        // wireframe cannot be a pipeline flag here the way it is in D3D9. What
        // it can be is different geometry: a triangle drawn as its three edges
        // is a line list, and that is an exact rendering of what D3DFILL_
        // WIREFRAME asks for, not an approximation. The cost is an index buffer
        // per draw, which is why nothing happens at all in solid fill.
        applyFillMode(state, geometry) {
            const fill = state.renderStates.get(D3DRS_FILLMODE) || D3DFILL_SOLID;
            if (fill !== D3DFILL_WIREFRAME && fill !== D3DFILL_POINT) return null;
            const topology = geometry.topology;
            if (topology !== "triangle-list" && topology !== "triangle-strip")
                return null;
            if (fill === D3DFILL_POINT) {
                // Every vertex becomes a point. WebGPU points are one pixel and
                // there is no point-size equivalent for this mode, which is the
                // one place D3DFILL_POINT differs from the hardware.
                this.warnOnce("fill-point", "D3DFILL_POINT draws one-pixel " +
                    "points: WebGPU has no point size outside the point-sprite " +
                    "path, so the mode's size is not reproduced");
                ++this.stats.fillModeDraws;
                return Object.assign({}, geometry, {
                    topology: "point-list",
                    stripIndexFormat: undefined,
                    fromFillMode: true,
                });
            }
            const source = this.triangleIndicesFor(geometry);
            if (!source) {
                // Naming it beats drawing the solid form and letting the
                // developer wonder why the wireframe toggle does nothing.
                this.warnOnce("fill-wireframe-indices",
                    "D3DFILL_WIREFRAME needs to read this draw's indices to " +
                    "build its edges, and this index buffer has no CPU mirror; " +
                    "the draw stays solid");
                return null;
            }
            const triangles = Math.floor(source.length / 3);
            if (!triangles) return null;
            const lines = new Uint32Array(triangles * 6);
            for (let i = 0; i < triangles; ++i) {
                const a = source[i * 3], b = source[i * 3 + 1],
                    c = source[i * 3 + 2];
                lines[i * 6] = a; lines[i * 6 + 1] = b;
                lines[i * 6 + 2] = b; lines[i * 6 + 3] = c;
                lines[i * 6 + 4] = c; lines[i * 6 + 5] = a;
            }
            const buffer = this.device.createBuffer({
                size: lines.byteLength,
                usage: BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(buffer, 0, lines);
            this.retireAfterSubmit(buffer);
            ++this.stats.fillModeDraws;
            return Object.assign({}, geometry, {
                topology: "line-list",
                stripIndexFormat: undefined,
                indexResource: undefined,
                indexInfo: {
                    buffer, format: "uint32", offset: 0, count: lines.length,
                    firstIndex: 0,
                    baseVertex: geometry.indexInfo
                        ? geometry.indexInfo.baseVertex : 0,
                },
                fromFillMode: true,
            });
        }

        // The triangle-list index sequence behind a draw, as vertex indices, or
        // null when it cannot be recovered. Strips are unrolled here so the
        // edge builder above only ever sees triples.
        triangleIndicesFor(geometry) {
            const strip = geometry.topology === "triangle-strip";
            let source = null;
            if (!geometry.indexInfo) {
                const count = geometry.vertexCount | 0;
                if (count < 3) return null;
                source = new Uint32Array(count);
                for (let i = 0; i < count; ++i) source[i] = i;
            } else if (geometry.indexInfo.cpuIndices) {
                // A fan or a *UP draw already built its indices on the CPU and
                // kept them for exactly this.
                source = geometry.indexInfo.cpuIndices;
            } else if (geometry.indexResource &&
                    geometry.indexResource.shadow) {
                const resource = geometry.indexResource;
                const wide = resource.indexFormat === "uint32";
                const all = wide
                    ? new Uint32Array(resource.shadow.buffer,
                        resource.shadow.byteOffset, resource.shadow.length >> 2)
                    : new Uint16Array(resource.shadow.buffer,
                        resource.shadow.byteOffset, resource.shadow.length >> 1);
                const first = geometry.indexInfo.firstIndex | 0;
                const count = geometry.indexInfo.count | 0;
                if (first + count > all.length) return null;
                source = all.subarray(first, first + count);
            }
            if (!source || source.length < 3) return null;
            if (!strip) return source;
            // A strip of N+2 vertices is N triangles, and every odd triangle
            // has its winding reversed. Winding does not matter for edges, but
            // unrolling in the same order the rasteriser would keeps the edge
            // set identical to the solid form's silhouette.
            const triangles = source.length - 2;
            const out = new Uint32Array(triangles * 3);
            for (let i = 0; i < triangles; ++i) {
                out[i * 3] = source[i];
                out[i * 3 + 1] = source[i + (i & 1 ? 2 : 1)];
                out[i * 3 + 2] = source[i + (i & 1 ? 1 : 2)];
            }
            return out;
        }

        triangleFanIndexBuffer(vertexCount) {
            if (vertexCount < 3) return null;
            const triangles = vertexCount - 2;
            const indices = new Uint32Array(triangles * 3);
            for (let i = 0; i < triangles; ++i) {
                indices[i * 3] = 0;
                indices[i * 3 + 1] = i + 1;
                indices[i * 3 + 2] = i + 2;
            }
            const buffer = this.device.createBuffer({
                size: indices.byteLength,
                usage: BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(buffer, 0, indices);
            this.retireAfterSubmit(buffer);
            // The CPU copy travels with the buffer because D3DFILL_WIREFRAME
            // has to read these indices back to build edges, and by then the
            // GPU copy is write-only.
            return { buffer, indices };
        }

        triangleFanFromIndices(indexResource, firstIndex, indexCount) {
            if (indexCount < 3 || !indexResource.shadow) return null;
            const wide = indexResource.indexFormat === "uint32";
            const source = wide
                ? new Uint32Array(indexResource.shadow.buffer,
                    indexResource.shadow.byteOffset, indexResource.shadow.length >> 2)
                : new Uint16Array(indexResource.shadow.buffer,
                    indexResource.shadow.byteOffset, indexResource.shadow.length >> 1);
            if (firstIndex + indexCount > source.length) return null;
            const triangles = indexCount - 2;
            const indices = new Uint32Array(triangles * 3);
            const hub = source[firstIndex];
            for (let i = 0; i < triangles; ++i) {
                indices[i * 3] = hub;
                indices[i * 3 + 1] = source[firstIndex + i + 1];
                indices[i * 3 + 2] = source[firstIndex + i + 2];
            }
            const buffer = this.device.createBuffer({
                size: indices.byteLength,
                usage: BUFFER_USAGE_INDEX | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(buffer, 0, indices);
            this.retireAfterSubmit(buffer);
            return { buffer, count: indices.length, indices };
        }
    }

    function primitiveElementCount(type, primitiveCount) {
        switch (type) {
        case D3DPT_POINTLIST: return primitiveCount;
        case D3DPT_LINELIST: return primitiveCount * 2;
        case D3DPT_LINESTRIP: return primitiveCount + 1;
        case D3DPT_TRIANGLELIST: return primitiveCount * 3;
        case D3DPT_TRIANGLESTRIP:
        case D3DPT_TRIANGLEFAN: return primitiveCount + 2;
        default: return null;
        }
    }

    // D3DPRIMITIVETYPE -> GPUPrimitiveTopology. M1 hardcoded "triangle-list"
    // for every draw while still computing strip/fan element counts, so a
    // strip of N triangles was rasterised as floor((N+2)/3) unrelated
    // triangles -- geometry that is wrong rather than missing, and therefore
    // easy to mistake for a transform bug. TRIANGLEFAN has no WebGPU
    // topology at all and is converted to an indexed triangle list by the
    // callers instead.
    function topologyFor(type) {
        switch (type) {
        case D3DPT_POINTLIST: return "point-list";
        case D3DPT_LINELIST: return "line-list";
        case D3DPT_LINESTRIP: return "line-strip";
        case D3DPT_TRIANGLESTRIP: return "triangle-strip";
        default: return "triangle-list";
        }
    }

    function isStripTopology(topology) {
        return topology === "triangle-strip" || topology === "line-strip";
    }

    D3D9WebGPUExecutor.prototype["performanceTimingVersion"] = 1;
    global.D3D9WebGPUExecutor = D3D9WebGPUExecutor;
    global.installD3D9WebGPUExecutor = function(canvas, options) {
        return new D3D9WebGPUExecutor(canvas, options);
    };

    if (typeof module !== "undefined" && module.exports) {
        module.exports = {
            D3D9WebGPUExecutor,
            V86GL_CTRL_D3D9_BATCH: 0xFFE1,
            // Exported so the WGSL validation test can run the synthesised
            // fixed-function stages through a real compiler alongside the
            // translated ones -- they meet over the same varying contract and
            // a mistake in either breaks the same pipelines.
            buildFixedFunctionVertexShader,
            buildFixedFunctionPixelShader,
        };
    }
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js                                 0000644 0000000 0000000 00000371135 00000000000 022275  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // D3D9 shader-model 1.x/2.0/3.0 bytecode -> WGSL translation pipeline (M2).
//
// Plan section 9 proposed vkd3d-shader(wasm) -> SPIR-V -> Tint(wasm) -> WGSL
// and argued (9.2) that a hand-written translator is unrealistic because
// SM2.0/3.0 needs "a control flow graph builder and SSA register versioning".
// That argument holds for a *SPIR-V* backend, which is an SSA form and does
// need both. It does not hold for WGSL, and this module takes the shorter
// route for one specific reason:
//
//   D3D9 shader assembly and WGSL are both imperative languages with mutable
//   variables and *structurally* nested control flow. D3D9 has no arbitrary
//   jumps: if/else/endif, rep/endrep, loop/endloop and call/ret nest properly
//   by specification, which is exactly WGSL's if/loop/function vocabulary.
//   So the translation is a statement-by-statement transliteration against
//   `var<private>` registers -- no basic blocks, no CFG, no SSA, no phi
//   nodes. That is what makes this a few hundred lines instead of a compiler.
//
// What that buys, versus the vkd3d/Tint toolchain: no Emscripten/Dawn build
// to keep alive, no LGPL redistribution obligation (plan section 25 flags
// this as unresolved for vkd3d), and a translator that is unit-testable
// directly in Node. What it costs: correctness rests on this file's own test
// suite instead of Wine's decades of game coverage, and the few ps_1_x
// texture-addressing forms with no honest translation are refused (see
// UNSUPPORTED_OPS) rather than approximated. compileShader() is the seam: it takes raw
// bytecode and returns WGSL + reflection, so swapping in a WASM backend later
// changes only this file.
//
// Everything here is pure computation over a Uint32Array -- no WebGPU calls,
// no DOM -- so glbridge/tests/d3d9_shader_pipeline_test.js can exercise it in
// plain Node. d3d9_executor.js owns turning the WGSL into a GPUShaderModule
// and running getCompilationInfo() on it (plan 9.6).

(function(global) {
    "use strict";

    // ---- bytecode constants (d3d9types.h) ----

    const D3DSI_OPCODE_MASK = 0x0000ffff;
    const D3DSI_INSTLENGTH_MASK = 0x0f000000;
    const D3DSI_INSTLENGTH_SHIFT = 24;
    const D3DSI_PREDICATED = 0x10000000;
    const D3DSI_COMMENTSIZE_SHIFT = 16;
    const D3DSI_COMMENTSIZE_MASK = 0x7fff;
    const D3DSP_OPCODESPECIFICCONTROL_SHIFT = 16;
    const D3DSP_OPCODESPECIFICCONTROL_MASK = 0x00ff0000;

    const D3DSP_REGNUM_MASK = 0x000007ff;
    const D3DSP_WRITEMASK_SHIFT = 16;
    const D3DSP_DSTMOD_SHIFT = 20;
    const D3DSP_DSTSHIFT_SHIFT = 24;
    const D3DSP_SWIZZLE_SHIFT = 16;
    const D3DSP_SRCMOD_SHIFT = 24;
    const D3DSHADER_ADDRESSMODE_RELATIVE = 1 << 13;

    // Register type is split across two bit fields (bits 28-30 and 11-12).
    function regTypeOf(token) {
        return ((token >>> 28) & 0x7) | ((token >>> 8) & 0x18);
    }

    const REG_TEMP = 0;
    const REG_INPUT = 1;
    const REG_CONST = 2;
    const REG_ADDR = 3;      // vertex shaders: a0
    const REG_TEXTURE = 3;   // pixel shaders: t#  (same numeric type)
    const REG_RASTOUT = 4;
    const REG_ATTROUT = 5;
    const REG_OUTPUT = 6;    // vs_3_0 o#; vs_1_1/2_0 call the same type TEXCRDOUT
    const REG_CONSTINT = 7;
    const REG_COLOROUT = 8;
    const REG_DEPTHOUT = 9;
    const REG_SAMPLER = 10;
    const REG_CONST2 = 11;
    const REG_CONST3 = 12;
    const REG_CONST4 = 13;
    const REG_CONSTBOOL = 14;
    const REG_LOOP = 15;
    const REG_MISCTYPE = 17;
    const REG_LABEL = 18;
    const REG_PREDICATE = 19;

    const RASTOUT_POSITION = 0;
    const RASTOUT_FOG = 1;
    const RASTOUT_POINTSIZE = 2;

    const MISC_POSITION = 0; // vPos
    const MISC_FACE = 1;     // vFace

    const SRCMOD_NONE = 0, SRCMOD_NEG = 1, SRCMOD_BIAS = 2, SRCMOD_BIASNEG = 3,
        SRCMOD_SIGN = 4, SRCMOD_SIGNNEG = 5, SRCMOD_COMP = 6, SRCMOD_X2 = 7,
        SRCMOD_X2NEG = 8, SRCMOD_DZ = 9, SRCMOD_DW = 10, SRCMOD_ABS = 11,
        SRCMOD_ABSNEG = 12, SRCMOD_NOT = 13;

    const DSTMOD_SATURATE = 1;

    const OP = {
        NOP: 0, MOV: 1, ADD: 2, SUB: 3, MAD: 4, MUL: 5, RCP: 6, RSQ: 7,
        DP3: 8, DP4: 9, MIN: 10, MAX: 11, SLT: 12, SGE: 13, EXP: 14, LOG: 15,
        LIT: 16, DST: 17, LRP: 18, FRC: 19, M4x4: 20, M4x3: 21, M3x4: 22,
        M3x3: 23, M3x2: 24, CALL: 25, CALLNZ: 26, LOOP: 27, RET: 28,
        ENDLOOP: 29, LABEL: 30, DCL: 31, POW: 32, CRS: 33, SGN: 34, ABS: 35,
        NRM: 36, SINCOS: 37, REP: 38, ENDREP: 39, IF: 40, IFC: 41, ELSE: 42,
        ENDIF: 43, BREAK: 44, BREAKC: 45, MOVA: 46, DEFB: 47, DEFI: 48,
        TEXCOORD: 64, TEXKILL: 65, TEX: 66, TEXBEM: 67, TEXBEML: 68,
        TEXREG2AR: 69, TEXREG2GB: 70, TEXM3x2PAD: 71, TEXM3x2TEX: 72,
        TEXM3x3PAD: 73, TEXM3x3TEX: 74, TEXM3x3SPEC: 76, TEXM3x3VSPEC: 77,
        EXPP: 78, LOGP: 79, CND: 80, DEF: 81, TEXREG2RGB: 82, TEXDP3TEX: 83,
        TEXM3x2DEPTH: 84, TEXDP3: 85, TEXM3x3: 86, TEXDEPTH: 87, CMP: 88,
        BEM: 89, DP2ADD: 90, DSX: 91, DSY: 92, TEXLDD: 93, SETP: 94,
        TEXLDL: 95, BREAKP: 96,
        PHASE: 0xfffd, COMMENT: 0xfffe, END: 0xffff,
    };

    const OP_NAMES = (() => {
        const names = {};
        for (const key of Object.keys(OP)) names[OP[key]] = key.toLowerCase();
        return names;
    })();

    // What remains of the ps_1_x texture-addressing family after the bump and
    // matrix forms were implemented (see the TEXBEM/TEXM3x*/BEM cases in
    // emit()).
    //
    // These three are the ones with no honest translation. TEXDEPTH and
    // TEXM3x2DEPTH replace the fragment's depth from a texture-addressing
    // result, which needs a frag_depth output the surrounding pipeline is not
    // built for; TEXM3x3 is the Radeon-era variant that writes a 3x3 result
    // without sampling, and nothing that reaches this translator emits it.
    // Refusing keeps the "no pretending" discipline: the shader is marked
    // unusable and draws that bind it are counted and skipped, rather than
    // silently rendering something wrong.
    const UNSUPPORTED_OPS = new Set([
        OP.TEXM3x2DEPTH, OP.TEXM3x3, OP.TEXDEPTH,
    ]);

    // Operand shape per opcode: [destCount, sourceCount]. SM2.0+ instruction
    // tokens also carry a length field, which parseShader() uses as the
    // authoritative stride; this table is what drives operand decoding, and
    // is the only source of truth for SM1.x where no length field exists.
    const OPERANDS = {
        [OP.NOP]: [0, 0], [OP.MOV]: [1, 1], [OP.ADD]: [1, 2], [OP.SUB]: [1, 2],
        [OP.MAD]: [1, 3], [OP.MUL]: [1, 2], [OP.RCP]: [1, 1], [OP.RSQ]: [1, 1],
        [OP.DP3]: [1, 2], [OP.DP4]: [1, 2], [OP.MIN]: [1, 2], [OP.MAX]: [1, 2],
        [OP.SLT]: [1, 2], [OP.SGE]: [1, 2], [OP.EXP]: [1, 1], [OP.LOG]: [1, 1],
        [OP.LIT]: [1, 1], [OP.DST]: [1, 2], [OP.LRP]: [1, 3], [OP.FRC]: [1, 1],
        [OP.M4x4]: [1, 2], [OP.M4x3]: [1, 2], [OP.M3x4]: [1, 2],
        [OP.M3x3]: [1, 2], [OP.M3x2]: [1, 2],
        [OP.CALL]: [0, 1], [OP.CALLNZ]: [0, 2], [OP.LOOP]: [0, 2],
        [OP.RET]: [0, 0], [OP.ENDLOOP]: [0, 0], [OP.LABEL]: [0, 1],
        [OP.POW]: [1, 2], [OP.CRS]: [1, 2], [OP.SGN]: [1, 3], [OP.ABS]: [1, 1],
        [OP.NRM]: [1, 1], [OP.REP]: [0, 1], [OP.ENDREP]: [0, 0],
        [OP.IF]: [0, 1], [OP.IFC]: [0, 2], [OP.ELSE]: [0, 0],
        [OP.ENDIF]: [0, 0], [OP.BREAK]: [0, 0], [OP.BREAKC]: [0, 2],
        [OP.BREAKP]: [0, 1], [OP.MOVA]: [1, 1], [OP.SETP]: [1, 2],
        [OP.TEXCOORD]: [1, 0], [OP.TEXKILL]: [1, 0],
        [OP.EXPP]: [1, 1], [OP.LOGP]: [1, 1], [OP.CND]: [1, 3],
        [OP.CMP]: [1, 3], [OP.DP2ADD]: [1, 3], [OP.DSX]: [1, 1],
        [OP.DSY]: [1, 1], [OP.TEXLDD]: [1, 4], [OP.TEXLDL]: [1, 2],
        [OP.TEXREG2AR]: [1, 1], [OP.TEXREG2GB]: [1, 1],
        [OP.TEXREG2RGB]: [1, 1], [OP.PHASE]: [0, 0],
        // The UNSUPPORTED_OPS family still needs an operand shape: the stream
        // has to decode cleanly before translate() can refuse the shader with
        // a message naming the instruction, rather than dying at "unknown
        // opcode" and hiding which feature was actually missing. BEM is
        // translated, and is here because it is the one ps_1_4 form that takes
        // two sources.
        [OP.TEXBEM]: [1, 1], [OP.TEXBEML]: [1, 1], [OP.BEM]: [1, 2],
        [OP.TEXM3x2PAD]: [1, 1], [OP.TEXM3x2TEX]: [1, 1],
        [OP.TEXM3x3PAD]: [1, 1], [OP.TEXM3x3TEX]: [1, 1],
        [OP.TEXM3x3SPEC]: [1, 2], [OP.TEXM3x3VSPEC]: [1, 1],
        [OP.TEXM3x2DEPTH]: [1, 1], [OP.TEXM3x3]: [1, 1],
        [OP.TEXDEPTH]: [1, 0], [OP.TEXDP3TEX]: [1, 1], [OP.TEXDP3]: [1, 1],
    };

    const WRITEMASK_NAMES = ["x", "y", "z", "w"];
    // Written as a hex float because that is the only spelling guaranteed to
    // be exact: the shortest decimal that round-trips through a double,
    // 3.4028235e38, is *above* f32's maximum once parsed, and Tint rejects it
    // outright ("cannot be represented as 'f32'") even though naga accepts it.
    // 0x1.fffffep+127 is f32 max exactly.
    const FLOAT_MAX = "0x1.fffffep+127";

    // Canonical vertex-output/pixel-input varying slots. Vertex and pixel
    // shaders are compiled into separate GPUShaderModules and only meet
    // inside a GPURenderPipeline, so their @location numbering has to be
    // fixed by semantic rather than negotiated per pair. Every translated
    // vertex shader emits all of these (WebGPU allows a vertex stage to
    // produce outputs the fragment stage ignores, but not the reverse), so
    // no VS/PS combination can ever fail to link.
    // Identifies *this build of the translator* to the persistent shader
    // cache. The cache's own `version` field describes the storage format, so
    // it stayed at 1 while the translator changed underneath it -- and every
    // entry already in IndexedDB was then restored verbatim, WGSL and
    // reflection included. The effect is a translator fix that does nothing
    // for exactly the shaders that have been seen before, which is silent, and
    // survives a reload: the symptom is a change that "did not work" plus a
    // reflection field that reads undefined because the stored object predates
    // it. Both happened here.
    //
    // The page already versions this file through the ?v= cache-buster it is
    // loaded with, and that string is bumped whenever the file changes, so
    // deriving the revision from it keeps the two in step with no extra
    // discipline. Outside a browser (the Node test suite) one constant serves,
    // because there the cache never outlives the process.
    const TRANSLATOR_REVISION = (function() {
        if (global.V86GL_BUILD_REVISION) return global.V86GL_BUILD_REVISION;
        try {
            const script = typeof document !== "undefined" &&
                document.currentScript;
            const source = script && script.src;
            if (source) {
                const query = source.indexOf("?v=");
                if (query >= 0) return source.slice(query + 3);
                return source;
            }
        } catch (error) { /* no document: fall through */ }
        return "node";
    })();

    const VARYING_COLOR0 = 0;
    const VARYING_COLOR1 = 1;
    const VARYING_TEXCOORD0 = 2; // .. 9 for TEXCOORD0..7
    const VARYING_FOG = 10;
    const VARYING_COUNT = 11;

    const DECLUSAGE_POSITION = 0, DECLUSAGE_BLENDWEIGHT = 1,
        DECLUSAGE_BLENDINDICES = 2, DECLUSAGE_NORMAL = 3, DECLUSAGE_PSIZE = 4,
        DECLUSAGE_TEXCOORD = 5, DECLUSAGE_TANGENT = 6, DECLUSAGE_BINORMAL = 7,
        DECLUSAGE_TESSFACTOR = 8, DECLUSAGE_POSITIONT = 9, DECLUSAGE_COLOR = 10,
        DECLUSAGE_FOG = 11, DECLUSAGE_DEPTH = 12, DECLUSAGE_SAMPLE = 13;

    /*
     * vs_1_x has no `dcl_` instructions: what a v# register means is fixed by
     * the API rather than declared by the shader. D3D8 spells that table as
     * D3DVSDE_*, D3D9 as the usage a D3DVERTEXELEMENT9 carries, and the D3D8
     * guest frontend converts its declarations with the same table
     * (d3d8_vsd_register_usage in d3d8proxy/d3d8_protocol.h) -- the two must
     * agree exactly, since the executor pairs a declaration element to a
     * shader input by (usage, usageIndex) and binds nothing when they differ.
     *
     * Without this, a real vs_1_1 -- which never carries a dcl -- reflects no
     * inputs at all: every v# read becomes a zeroed private variable and the
     * executor drops the draw for having no attribute to bind. Only shaders
     * assembled with a dcl, which vs_1_x cannot contain, appeared to work.
     */
    const VS1_FIXED_INPUT_SEMANTICS = {
        0: [DECLUSAGE_POSITION, 0], 1: [DECLUSAGE_BLENDWEIGHT, 0],
        2: [DECLUSAGE_BLENDINDICES, 0], 3: [DECLUSAGE_NORMAL, 0],
        4: [DECLUSAGE_PSIZE, 0], 5: [DECLUSAGE_COLOR, 0],
        6: [DECLUSAGE_COLOR, 1], 15: [DECLUSAGE_POSITION, 1],
    };

    function vs1InputSemantic(register) {
        const fixed = VS1_FIXED_INPUT_SEMANTICS[register];
        if (fixed) return { usage: fixed[0], usageIndex: fixed[1] };
        if (register >= 7 && register <= 14)
            return { usage: DECLUSAGE_TEXCOORD, usageIndex: register - 7 };
        return { usage: DECLUSAGE_TEXCOORD, usageIndex: 8 + (register & 7) };
    }

    const TEXTURE_TYPE_NAMES = { 2: "2d", 3: "cube", 4: "3d" };

    function varyingForSemantic(usage, usageIndex) {
        if (usage === DECLUSAGE_COLOR && usageIndex < 2)
            return VARYING_COLOR0 + usageIndex;
        if (usage === DECLUSAGE_TEXCOORD && usageIndex < 8)
            return VARYING_TEXCOORD0 + usageIndex;
        if (usage === DECLUSAGE_FOG) return VARYING_FOG;
        return -1;
    }

    // ---- bytecode parsing ----

    function decodeDest(token, relativeToken) {
        const mask = (token >>> D3DSP_WRITEMASK_SHIFT) & 0xf;
        return {
            type: regTypeOf(token),
            index: token & D3DSP_REGNUM_MASK,
            writeMask: mask === 0 ? 0xf : mask,
            modifier: (token >>> D3DSP_DSTMOD_SHIFT) & 0xf,
            shift: ((token >>> D3DSP_DSTSHIFT_SHIFT) & 0xf),
            relative: (token & D3DSHADER_ADDRESSMODE_RELATIVE) !== 0,
            relativeToken: relativeToken || 0,
        };
    }

    function decodeSource(token, relativeToken) {
        return {
            type: regTypeOf(token),
            index: token & D3DSP_REGNUM_MASK,
            swizzle: (token >>> D3DSP_SWIZZLE_SHIFT) & 0xff,
            modifier: (token >>> D3DSP_SRCMOD_SHIFT) & 0xf,
            relative: (token & D3DSHADER_ADDRESSMODE_RELATIVE) !== 0,
            relativeToken: relativeToken || 0,
        };
    }

    function parseShader(tokens) {
        if (!tokens || tokens.length < 2)
            throw new Error("shader bytecode is too short to hold a version token");
        const versionToken = tokens[0] >>> 0;
        const marker = versionToken >>> 16;
        let kind;
        if (marker === 0xfffe) kind = "vertex";
        else if (marker === 0xffff) kind = "pixel";
        else throw new Error("not a D3D9 shader: version token 0x" +
            versionToken.toString(16));
        const major = (versionToken >>> 8) & 0xff;
        const minor = versionToken & 0xff;
        if (major < 1 || major > 3)
            throw new Error("unsupported shader model " + major + "." + minor);

        const instructions = [];
        let i = 1;
        while (i < tokens.length) {
            const token = tokens[i] >>> 0;
            const opcode = token & D3DSI_OPCODE_MASK;
            if (opcode === OP.END) break;
            if (opcode === OP.COMMENT) {
                const words = (token >>> D3DSI_COMMENTSIZE_SHIFT) & D3DSI_COMMENTSIZE_MASK;
                i += 1 + words;
                continue;
            }
            const start = i;
            const length = (token & D3DSI_INSTLENGTH_MASK) >>> D3DSI_INSTLENGTH_SHIFT;
            const predicated = (token & D3DSI_PREDICATED) !== 0;
            const control = (token & D3DSP_OPCODESPECIFICCONTROL_MASK) >>>
                D3DSP_OPCODESPECIFICCONTROL_SHIFT;
            ++i;

            const instruction = { opcode, control, predicated, dest: null,
                predicate: null, sources: [], literals: null, declaration: null };

            const readOperand = decode => {
                if (i >= tokens.length)
                    throw new Error("shader bytecode ends inside an instruction");
                const operandToken = tokens[i++] >>> 0;
                let relative = 0;
                if ((operandToken & D3DSHADER_ADDRESSMODE_RELATIVE) &&
                        (major >= 2 || regTypeOf(operandToken) !== REG_CONST)) {
                    // vs_1_1 encodes c[a0.x] with the relative bit but *no*
                    // extra token (a0 is the only possible index); vs_2_0+
                    // spells the index register out in a following token.
                    if (major >= 2) relative = tokens[i++] >>> 0;
                }
                return decode(operandToken, relative);
            };

            if (opcode === OP.DCL) {
                const dclToken = tokens[i++] >>> 0;
                instruction.declaration = {
                    usage: dclToken & 0xf,
                    usageIndex: (dclToken >>> 16) & 0xf,
                    textureType: (dclToken >>> 27) & 0xf,
                };
                instruction.dest = decodeDest(tokens[i++] >>> 0, 0);
            } else if (opcode === OP.DEF || opcode === OP.DEFI) {
                instruction.dest = decodeDest(tokens[i++] >>> 0, 0);
                const raw = new Uint32Array(4);
                for (let k = 0; k < 4; ++k) raw[k] = tokens[i++] >>> 0;
                instruction.literals = opcode === OP.DEF
                    ? Array.from(new Float32Array(raw.buffer))
                    : Array.from(new Int32Array(raw.buffer));
            } else if (opcode === OP.DEFB) {
                instruction.dest = decodeDest(tokens[i++] >>> 0, 0);
                instruction.literals = [(tokens[i++] >>> 0) !== 0];
            } else {
                const shape = operandShape(opcode, kind, major, minor);
                if (!shape)
                    throw new Error("unknown opcode 0x" + opcode.toString(16));
                if (shape[0]) instruction.dest = readOperand(decodeDest);
                if (predicated) instruction.predicate = readOperand(decodeSource);
                for (let k = 0; k < shape[1]; ++k)
                    instruction.sources.push(readOperand(decodeSource));
            }

            // SM2.0+ carries an authoritative token count. Trusting it over
            // our own operand walk means a miscounted exotic instruction
            // cannot desynchronise the rest of the stream (plan 6.8's parser
            // safety rule applied one level down, to the bytecode itself).
            if (major >= 2 && length > 0) i = start + 1 + length;
            if (i <= start)
                throw new Error("shader instruction made no progress");
            instructions.push(instruction);
        }
        return { kind, major, minor, instructions };
    }

    // Instructions whose operand count depends on the shader model.
    function operandShape(opcode, kind, major, minor) {
        if (opcode === OP.TEX) {
            if (kind === "pixel" && major === 1) return minor < 4 ? [1, 0] : [1, 1];
            return [1, 2]; // ps_2_0+ texld dst, coord, sampler
        }
        if (opcode === OP.TEXCOORD)
            return (kind === "pixel" && major === 1 && minor >= 4) ? [1, 1] : [1, 0];
        if (opcode === OP.SINCOS) return major >= 3 ? [1, 1] : [1, 3];
        return OPERANDS[opcode] || null;
    }

    // ---- WGSL emission ----

    const SWIZZLE_CHARS = "xyzw";

    function swizzleString(swizzle) {
        let out = "";
        for (let i = 0; i < 4; ++i) out += SWIZZLE_CHARS[(swizzle >>> (i * 2)) & 0x3];
        return out;
    }

    function floatLiteral(value) {
        if (!isFinite(value)) return value > 0 ? FLOAT_MAX : "-" + FLOAT_MAX;
        if (Number.isInteger(value) && Math.abs(value) < 1e9)
            return value.toFixed(1);
        return String(value);
    }

    class Translator {
        constructor(parsed, options) {
            this.parsed = parsed;
            this.options = options || {};
            this.kind = parsed.kind;
            this.major = parsed.major;
            this.minor = parsed.minor;
            this.lines = [];
            this.indent = 2;
            this.temps = new Set();
            this.usedInputs = new Map();       // register -> {usage, usageIndex}
            this.outputSemantics = new Map();  // vs_3_0 o# -> {usage, usageIndex}
            this.samplers = new Map();         // index -> "2d"|"cube"|"3d"
            // Stages the caller has a D3D9 depth texture bound to. D3D9 has no
            // syntax for a shadow sample: `tex2D`/`tex2Dproj` on a sampler
            // whose texture is a depth format silently becomes a hardware
            // depth comparison returning filtered visibility. WGSL demands the
            // opposite -- texture_depth_2d and sampler_comparison are distinct
            // types chosen at module scope -- so which stages are depth has to
            // reach translation, and the same bytecode compiles to a different
            // module depending on what is bound. See isDepthSampler() for why
            // this is a request rather than a directive.
            this.requestedDepthSamplers = new Set(
                (this.options.depthSamplers || []).map(index => index | 0));
            // The subset of those which read the stored depth back rather than
            // comparing against it -- D3D9's ATI FOURCC depth formats. Same
            // texture_depth_2d declaration, an ordinary sampler instead of a
            // comparison one, and no reference value at all.
            this.requestedDepthFetchSamplers = new Set(
                (this.options.depthFetchSamplers || []).map(index => index | 0));
            // D3DSAMP_MIPMAPLODBIAS per sampler, already quantised by the
            // caller. WebGPU samplers have no bias field, so it can only be
            // applied at the sample call; it arrives as a compile option rather
            // than a uniform because that keeps it out of the per-draw uniform
            // writer, and the caller folds it into the shader variant key.
            this.samplerLodBias = this.options.samplerLodBias || null;
            // D3DTADDRESS_MIRRORONCE per sampler, as the axis letters that use
            // it ("xy", "x", ...). The host sampler is already clamp-to-edge
            // for such an axis, so mirroring about zero is all that is left,
            // and abs() on the coordinate is exactly that. It arrives as a
            // compile option for the same reason the LOD bias does: it changes
            // the WGSL, so it belongs in the shader variant key.
            this.samplerMirrorOnce = this.options.samplerMirrorOnce || null;
            // D3DRS_SHADEMODE's D3DSHADE_FLAT: the two colour varyings take
            // the provoking vertex's value, with shaders as without them (as
            // wined3d's flatshading). A vertex output and the fragment input
            // at one location must agree, so the caller passes the same flag
            // to both stages, as the fixed-function ones get it, and keys the
            // variant on it.
            this.flatShading = !!this.options.flatShading;
            this.writtenVaryings = new Set();
            this.usesAddress = false;
            this.usesLoopCounter = false;
            this.usesPredicate = false;
            this.usesPointSize = false;
            this.usesDepthOutput = false;
            this.usesFragPosition = false;
            this.usesFrontFacing = false;
            this.usesRelativeConstants = false;
            this.maxFloatConst = -1;
            this.maxIntConst = -1;
            this.maxBoolConst = -1;
            this.floatDefaults = new Map();    // c# -> [x,y,z,w] from `def`
            this.intDefaults = new Map();
            this.boolDefaults = new Map();
            this.psTexcoordInputs = new Set(); // ps t# registers touched
            // ps_1_x texture addressing. bumpStages are the samplers whose
            // D3DTSS_BUMPENVMAT* matrix a texbem/texbeml needs; matrixRows is
            // the running accumulator the texm3x*pad instructions feed and the
            // texm3x*tex/spec/vspec that follows consumes.
            this.bumpStages = new Set();
            this.matrixRows = [];
            this.psColorInputs = new Set();    // ps v# registers touched
            this.colorOutputs = new Set();
            this.controlDepth = 0;             // >0 => inside if/loop
            this.nonUniformDepth = 0;          // >0 => implicit-LOD sampling illegal
            this.nonUniformFrames = [];        // open non-uniform regions
            this.levelZeroSamples = 0;
            this.temporaryId = 0;
            this.warnings = [];
        }

        emit(text) {
            this.lines.push(" ".repeat(this.indent) + text);
        }

        // One varying of the inter-stage struct, the same in both stages:
        // with flat shading the colour slots are flat (texture coordinates
        // and fog keep interpolating, as in D3D9)
        varyingDeclaration(slot) {
            const flat = this.flatShading &&
                (slot === VARYING_COLOR0 || slot === VARYING_COLOR1);
            return "    @location(" + slot + ")" +
                (flat ? " @interpolate(flat)" : "") +
                " varying" + slot + ": vec4<f32>,";
        }

        fresh(prefix) {
            return "_" + (prefix || "t") + (this.temporaryId++);
        }

        note(message) {
            if (this.warnings.indexOf(message) === -1) this.warnings.push(message);
        }

        // ---- register access ----

        constantIndexExpression(source, bank) {
            const base = source.index + bank * 2048;
            if (!source.relative) {
                if (base > this.maxFloatConst) this.maxFloatConst = base;
                return String(base);
            }
            this.usesRelativeConstants = true;
            this.maxFloatConst = Math.max(this.maxFloatConst, 255);
            // vs_1_1 has no relative-index token: a0.x is the only legal
            // index register. vs_2_0+ names it (a0 or aL) explicitly.
            let index = "a0.x";
            if (source.relativeToken) {
                const rel = decodeSource(source.relativeToken, 0);
                const component = SWIZZLE_CHARS[rel.swizzle & 0x3];
                index = rel.type === REG_LOOP ? "aL"
                    : "a0." + component;
                if (rel.type === REG_LOOP) this.usesLoopCounter = true;
                else this.usesAddress = true;
            } else {
                this.usesAddress = true;
            }
            return "clamp(" + index + " + " + base + ", 0, " +
                (this.constantCapacity() - 1) + ")";
        }

        constantCapacity() {
            return this.kind === "vertex" ? 256 : 224;
        }

        // Raw (unswizzled, unmodified) vec4<f32> read of a source register.
        rawSource(source) {
            switch (source.type) {
            case REG_TEMP:
                this.temps.add(source.index);
                return "r" + source.index;
            case REG_CONST:
                return "d9c.f[" + this.constantIndexExpression(source, 0) + "]";
            case REG_CONST2:
                return "d9c.f[" + this.constantIndexExpression(source, 1) + "]";
            case REG_CONST3:
                return "d9c.f[" + this.constantIndexExpression(source, 2) + "]";
            case REG_CONST4:
                return "d9c.f[" + this.constantIndexExpression(source, 3) + "]";
            case REG_CONSTINT:
                this.maxIntConst = Math.max(this.maxIntConst, source.index);
                return "vec4<f32>(d9c.i[" + source.index + "])";
            case REG_CONSTBOOL:
                this.maxBoolConst = Math.max(this.maxBoolConst, source.index);
                return "vec4<f32>(f32(d9c.b[" + (source.index >> 2) + "][" +
                    (source.index & 3) + "]))";
            case REG_PREDICATE:
                this.usesPredicate = true;
                return "vec4<f32>(p0)";
            case REG_LOOP:
                this.usesLoopCounter = true;
                return "vec4<f32>(f32(aL))";
            case REG_ADDR: // === REG_TEXTURE
                if (this.kind === "vertex") {
                    this.usesAddress = true;
                    return "vec4<f32>(a0)";
                }
                this.psTexcoordInputs.add(source.index);
                return "t" + source.index;
            case REG_INPUT:
                if (this.kind === "vertex") {
                    if (!this.usedInputs.has(source.index))
                        this.usedInputs.set(source.index, null);
                    return "vin" + source.index;
                }
                this.psColorInputs.add(source.index);
                return "v" + source.index;
            case REG_MISCTYPE:
                if (source.index === MISC_POSITION) {
                    this.usesFragPosition = true;
                    return "vec4<f32>(floor(d9_frag_position.xy), " +
                        "d9_frag_position.z, d9_frag_position.w)";
                }
                if (source.index === MISC_FACE) {
                    this.usesFrontFacing = true;
                    return "vec4<f32>(d9_face)";
                }
                throw new Error("unsupported misc register index " + source.index);
            case REG_OUTPUT: // readable in vs_3_0 (o# behaves like a temp)
                if (this.kind === "vertex" && this.major >= 3)
                    return "o" + source.index;
                throw new Error("output register is not readable in this shader model");
            default:
                throw new Error("unsupported source register type " + source.type);
            }
        }

        // Applies swizzle then the source modifier, per D3D9 evaluation order.
        source(index) {
            const source = this.parsed.currentSources[index];
            return this.sourceExpression(source);
        }

        sourceExpression(source) {
            let expression = this.rawSource(source);
            const swizzle = swizzleString(source.swizzle);
            if (swizzle !== "xyzw") expression = "(" + expression + ")." + swizzle;
            switch (source.modifier) {
            case SRCMOD_NONE: return expression;
            case SRCMOD_NEG: return "-(" + expression + ")";
            case SRCMOD_BIAS: return "((" + expression + ") - vec4<f32>(0.5))";
            case SRCMOD_BIASNEG: return "-((" + expression + ") - vec4<f32>(0.5))";
            case SRCMOD_SIGN: return "((" + expression + ") * 2.0 - vec4<f32>(1.0))";
            case SRCMOD_SIGNNEG: return "-((" + expression + ") * 2.0 - vec4<f32>(1.0))";
            case SRCMOD_COMP: return "(vec4<f32>(1.0) - (" + expression + "))";
            case SRCMOD_X2: return "((" + expression + ") * 2.0)";
            case SRCMOD_X2NEG: return "-((" + expression + ") * 2.0)";
            case SRCMOD_DZ: {
                const name = this.fresh("dz");
                this.emit("let " + name + " = " + expression + ";");
                return "(" + name + " / select(-max(abs(" + name +
                    ".z), 1e-8), max(abs(" + name + ".z), 1e-8), " +
                    name + ".z >= 0.0))";
            }
            case SRCMOD_DW: {
                const name = this.fresh("dw");
                this.emit("let " + name + " = " + expression + ";");
                return "(" + name + " / select(-max(abs(" + name +
                    ".w), 1e-8), max(abs(" + name + ".w), 1e-8), " +
                    name + ".w >= 0.0))";
            }
            case SRCMOD_ABS: return "abs(" + expression + ")";
            case SRCMOD_ABSNEG: return "-abs(" + expression + ")";
            case SRCMOD_NOT: return "(vec4<f32>(1.0) - (" + expression + "))";
            default:
                throw new Error("unsupported source modifier " + source.modifier);
            }
        }

        // Name of the lvalue a destination register writes through, plus the
        // bookkeeping that makes it exist in the prologue/epilogue.
        destTarget(dest) {
            switch (dest.type) {
            case REG_TEMP:
                this.temps.add(dest.index);
                return "r" + dest.index;
            case REG_ADDR: // vs: a0 (MOV in 1.1, MOVA in 2.0+); ps: t# scratch
                if (this.kind === "vertex") {
                    this.usesAddress = true;
                    return "a0f";
                }
                this.psTexcoordInputs.add(dest.index);
                return "t" + dest.index;
            case REG_RASTOUT:
                if (dest.index === RASTOUT_POSITION) return "o_position";
                if (dest.index === RASTOUT_FOG) {
                    this.writtenVaryings.add(VARYING_FOG);
                    return "o_varying" + VARYING_FOG;
                }
                if (dest.index === RASTOUT_POINTSIZE) {
                    this.usesPointSize = true;
                    return "o_pointsize";
                }
                throw new Error("unsupported rasterizer output " + dest.index);
            case REG_ATTROUT: {
                const slot = VARYING_COLOR0 + dest.index;
                if (dest.index > 1)
                    throw new Error("only oD0/oD1 exist as colour outputs");
                this.writtenVaryings.add(slot);
                return "o_varying" + slot;
            }
            case REG_OUTPUT: {
                if (this.kind === "vertex" && this.major >= 3) {
                    const semantic = this.outputSemantics.get(dest.index);
                    if (!semantic)
                        throw new Error("vs_3_0 output o" + dest.index +
                            " was written without a dcl semantic");
                    if (semantic.usage === DECLUSAGE_POSITION) return "o_position";
                    if (semantic.usage === DECLUSAGE_PSIZE) {
                        this.usesPointSize = true;
                        return "o_pointsize";
                    }
                    const slot = varyingForSemantic(semantic.usage, semantic.usageIndex);
                    if (slot < 0)
                        throw new Error("vs_3_0 output semantic " + semantic.usage +
                            "[" + semantic.usageIndex + "] has no varying slot");
                    this.writtenVaryings.add(slot);
                    return "o_varying" + slot;
                }
                const slot = VARYING_TEXCOORD0 + dest.index;
                if (dest.index > 7)
                    throw new Error("only oT0..oT7 exist as texcoord outputs");
                this.writtenVaryings.add(slot);
                return "o_varying" + slot;
            }
            case REG_COLOROUT:
                this.colorOutputs.add(dest.index);
                return "oC" + dest.index;
            case REG_DEPTHOUT:
                this.usesDepthOutput = true;
                return "o_depthv";
            case REG_PREDICATE:
                this.usesPredicate = true;
                return "p0f";
            default:
                throw new Error("unsupported destination register type " + dest.type);
            }
        }

        // Emits `dest.<mask> = value`, honouring _sat, the ps_1_x result
        // shift, and the write mask. WGSL only allows assignment through a
        // single-component swizzle, so a multi-component mask becomes one
        // statement per component rather than `dest.xy = ...`.
        store(dest, valueExpression, options) {
            const asBool = options && options.bool;
            this.noteRegisterWrite(dest);
            const target = this.destTarget(dest);
            const name = this.fresh("v");
            let value = valueExpression;
            if (!asBool) {
                if (dest.shift) {
                    // 4-bit signed field: 1..7 scale up by 2^n, 9..15 (i.e.
                    // -7..-1) scale down.
                    const shift = dest.shift > 7 ? dest.shift - 16 : dest.shift;
                    value = "((" + value + ") * " +
                        floatLiteral(Math.pow(2, shift)) + ")";
                }
                if ((dest.modifier & DSTMOD_SATURATE) !== 0)
                    value = "clamp(" + value + ", vec4<f32>(0.0), vec4<f32>(1.0))";
            }
            this.emit("let " + name + " = " + value + ";");
            if (dest.writeMask === 0xf) {
                this.emit(target + " = " + name + ";");
                return;
            }
            for (let i = 0; i < 4; ++i) {
                if (!(dest.writeMask & (1 << i))) continue;
                const component = WRITEMASK_NAMES[i];
                this.emit(target + "." + component + " = " + name + "." + component + ";");
            }
        }

        // ---- instruction translation ----

        translate() {
            const parsed = this.parsed;
            // dcl/def are order-independent declarations; hoisting them means
            // a dcl that follows its first use (legal, and produced by some
            // compilers for vs_3_0 outputs) still informs code generation.
            for (const instruction of parsed.instructions) {
                if (instruction.opcode === OP.DCL) this.declare(instruction);
                else if (instruction.opcode === OP.DEF)
                    this.floatDefaults.set(instruction.dest.index, instruction.literals);
                else if (instruction.opcode === OP.DEFI)
                    this.intDefaults.set(instruction.dest.index, instruction.literals);
                else if (instruction.opcode === OP.DEFB)
                    this.boolDefaults.set(instruction.dest.index, instruction.literals[0]);
                else if (UNSUPPORTED_OPS.has(instruction.opcode))
                    throw new Error("unsupported instruction '" +
                        (OP_NAMES[instruction.opcode] || instruction.opcode) +
                        "' (ps_1_x bump-environment/matrix texture addressing)");
            }
            for (const [register, literals] of this.floatDefaults)
                this.maxFloatConst = Math.max(this.maxFloatConst, register);
            for (const register of this.intDefaults.keys())
                this.maxIntConst = Math.max(this.maxIntConst, register);
            for (const register of this.boolDefaults.keys())
                this.maxBoolConst = Math.max(this.maxBoolConst, register);

            // Split top-level code from `label`-introduced subroutines. D3D9
            // forbids recursion, so the call graph is a DAG and the routines
            // can simply be emitted in dependency order ahead of the body.
            const routines = this.splitRoutines(parsed.instructions);
            const bodies = new Map();
            for (const routine of routines.subroutines) {
                this.lines = [];
                this.indent = 4;
                this.emitBlock(routine.instructions);
                bodies.set(routine.label, this.lines);
            }
            this.lines = [];
            this.indent = 4;
            this.emitBlock(routines.main);
            const mainBody = this.lines;

            return this.assemble(routines, bodies, mainBody);
        }

        declare(instruction) {
            const declaration = instruction.declaration;
            const dest = instruction.dest;
            if (dest.type === REG_SAMPLER) {
                const type = TEXTURE_TYPE_NAMES[declaration.textureType] || "2d";
                this.samplers.set(dest.index, type);
                return;
            }
            if (this.kind === "vertex" && dest.type === REG_INPUT) {
                this.usedInputs.set(dest.index, {
                    usage: declaration.usage, usageIndex: declaration.usageIndex });
                return;
            }
            if (this.kind === "vertex" && dest.type === REG_OUTPUT && this.major >= 3) {
                this.outputSemantics.set(dest.index, {
                    usage: declaration.usage, usageIndex: declaration.usageIndex });
                return;
            }
            if (this.kind === "pixel") {
                // ps_2_0 declares its texcoord inputs as t#, ps_3_0 as v#
                // with an explicit semantic.
                if (dest.type === REG_TEXTURE) this.psTexcoordInputs.add(dest.index);
                else if (dest.type === REG_INPUT) {
                    this.usedInputs.set(dest.index, {
                        usage: declaration.usage, usageIndex: declaration.usageIndex });
                    this.psColorInputs.add(dest.index);
                }

            }
            // vs_1_1/2_0 output dcls carry no information we need.
        }

        splitRoutines(instructions) {
            const main = [];
            const subroutines = [];
            let current = main;
            let depth = 0;
            for (const instruction of instructions) {
                if (instruction.opcode === OP.DCL || instruction.opcode === OP.DEF ||
                        instruction.opcode === OP.DEFI || instruction.opcode === OP.DEFB)
                    continue;
                if (instruction.opcode === OP.LABEL) {
                    const label = instruction.sources[0].index;
                    const routine = { label, instructions: [] };
                    subroutines.push(routine);
                    current = routine.instructions;
                    depth = 0;
                    continue;
                }
                if (instruction.opcode === OP.RET && depth === 0 && current === main)
                    continue; // end of the main body; the epilogue follows
                if (instruction.opcode === OP.IF || instruction.opcode === OP.IFC ||
                        instruction.opcode === OP.REP || instruction.opcode === OP.LOOP)
                    ++depth;
                else if (instruction.opcode === OP.ENDIF ||
                        instruction.opcode === OP.ENDREP ||
                        instruction.opcode === OP.ENDLOOP)
                    --depth;
                current.push(instruction);
            }
            // Order subroutines so a callee is always defined before its
            // caller, as WGSL requires.
            const byLabel = new Map(subroutines.map(r => [r.label, r]));
            const ordered = [];
            const state = new Map();
            const visit = routine => {
                const status = state.get(routine.label);
                if (status === "done") return;
                if (status === "visiting")
                    throw new Error("recursive shader subroutine call");
                state.set(routine.label, "visiting");
                for (const instruction of routine.instructions) {
                    if (instruction.opcode !== OP.CALL && instruction.opcode !== OP.CALLNZ)
                        continue;
                    const callee = byLabel.get(instruction.sources[0].index);
                    if (callee) visit(callee);
                }
                state.set(routine.label, "done");
                ordered.push(routine);
            };
            for (const routine of subroutines) visit(routine);
            return { main, subroutines: ordered };
        }

        emitBlock(instructions) {
            for (const instruction of instructions) this.instruction(instruction);
        }

        instruction(instruction) {
            this.parsed.currentSources = instruction.sources;
            const opcode = instruction.opcode;
            const dest = instruction.dest;
            const sources = instruction.sources;

            if (instruction.predicated && instruction.predicate) {
                // `(p0.x) mov r0, r1` -- run the instruction, then keep the
                // old value where the predicate is false. Doing it as a
                // guarded block is simpler and matches the semantics for
                // every opcode, including texture reads.
                this.usesPredicate = true;
                const predicate = instruction.predicate;
                const component = SWIZZLE_CHARS[predicate.swizzle & 0x3];
                const negated = predicate.modifier === SRCMOD_NOT;
                this.emit("if (" + (negated ? "!" : "") + "p0." + component + ") {");
                this.indent += 2;
                ++this.controlDepth;
                ++this.nonUniformDepth;
                this.pushNonUniformFrame();
                const inner = Object.assign({}, instruction, { predicated: false });
                this.instruction(inner);
                (this.nonUniformFrames || []).pop();
                --this.nonUniformDepth;
                --this.controlDepth;
                this.indent -= 2;
                this.emit("}");
                return;
            }

            const s = i => this.sourceExpression(sources[i]);
            const scalar = (i, component) =>
                "(" + this.sourceExpression(sources[i]) + ")." + (component || "x");

            switch (opcode) {
            case OP.NOP: case OP.PHASE:
                if (opcode === OP.PHASE)
                    this.note("ps_1_4 `phase` is treated as a no-op");
                return;
            case OP.MOV:
                // vs_1_1 predates MOVA. Its only legal way to load a0.x is
                // `mov a0.x, src`, which performs the same round-to-nearest
                // float-to-integer conversion MOVA performs in later models.
                // Keep the float mirror for masked assignment, then update
                // the integer register relative c[a0.x + n] reads.
                if (this.kind === "vertex" && this.major === 1 &&
                        dest.type === REG_ADDR) {
                    this.store(dest, "round(" + s(0) + ")");
                    this.emit("a0 = vec4<i32>(a0f);");
                } else {
                    this.store(dest, s(0));
                }
                return;
            case OP.MOVA:
                this.store(dest, "round(" + s(0) + ")");
                this.emit("a0 = vec4<i32>(a0f);");
                return;
            case OP.ADD: this.store(dest, "(" + s(0) + ") + (" + s(1) + ")"); return;
            case OP.SUB: this.store(dest, "(" + s(0) + ") - (" + s(1) + ")"); return;
            case OP.MUL: this.store(dest, "(" + s(0) + ") * (" + s(1) + ")"); return;
            case OP.MAD:
                this.store(dest, "(" + s(0) + ") * (" + s(1) + ") + (" + s(2) + ")");
                return;
            case OP.MIN: this.store(dest, "min(" + s(0) + ", " + s(1) + ")"); return;
            case OP.MAX: this.store(dest, "max(" + s(0) + ", " + s(1) + ")"); return;
            case OP.SLT:
                this.store(dest, "select(vec4<f32>(0.0), vec4<f32>(1.0), (" +
                    s(0) + ") < (" + s(1) + "))");
                return;
            case OP.SGE:
                this.store(dest, "select(vec4<f32>(0.0), vec4<f32>(1.0), (" +
                    s(0) + ") >= (" + s(1) + "))");
                return;
            case OP.FRC: this.store(dest, "fract(" + s(0) + ")"); return;
            case OP.ABS: this.store(dest, "abs(" + s(0) + ")"); return;
            case OP.RCP: this.store(dest, "vec4<f32>(d9_rcp(" + scalar(0) + "))"); return;
            case OP.RSQ: this.store(dest, "vec4<f32>(d9_rsq(" + scalar(0) + "))"); return;
            case OP.EXP: this.store(dest, "vec4<f32>(exp2(" + scalar(0) + "))"); return;
            case OP.LOG: this.store(dest, "vec4<f32>(d9_log(" + scalar(0) + "))"); return;
            case OP.EXPP:
                if (this.major === 1) {
                    const name = this.fresh("e");
                    this.emit("let " + name + " = " + scalar(0) + ";");
                    this.store(dest, "vec4<f32>(exp2(floor(" + name + ")), " +
                        "fract(" + name + "), exp2(" + name + "), 1.0)");
                } else {
                    this.store(dest, "vec4<f32>(exp2(" + scalar(0) + "))");
                }
                return;
            case OP.LOGP: this.store(dest, "vec4<f32>(d9_log(" + scalar(0) + "))"); return;
            case OP.POW:
                this.store(dest, "vec4<f32>(pow(abs(" + scalar(0) + "), " +
                    scalar(1) + "))");
                return;
            case OP.DP3:
                this.store(dest, "vec4<f32>(dot((" + s(0) + ").xyz, (" + s(1) + ").xyz))");
                return;
            case OP.DP4:
                this.store(dest, "vec4<f32>(dot(" + s(0) + ", " + s(1) + "))");
                return;
            case OP.DP2ADD:
                this.store(dest, "vec4<f32>(dot((" + s(0) + ").xy, (" + s(1) +
                    ").xy) + " + scalar(2) + ")");
                return;
            case OP.CRS:
                this.store(dest, "vec4<f32>(cross((" + s(0) + ").xyz, (" +
                    s(1) + ").xyz), 0.0)");
                return;
            case OP.NRM:
                this.store(dest, "vec4<f32>(d9_normalize((" + s(0) + ").xyz), 0.0)");
                return;
            case OP.SGN: this.store(dest, "sign(" + s(0) + ")"); return;
            case OP.LIT: this.store(dest, "d9_lit(" + s(0) + ")"); return;
            case OP.DST: {
                const a = this.fresh("a"), b = this.fresh("b");
                this.emit("let " + a + " = " + s(0) + ";");
                this.emit("let " + b + " = " + s(1) + ";");
                this.store(dest, "vec4<f32>(1.0, " + a + ".y * " + b + ".y, " +
                    a + ".z, " + b + ".w)");
                return;
            }
            case OP.LRP:
                this.store(dest, "mix(" + s(2) + ", " + s(1) + ", " + s(0) + ")");
                return;
            case OP.CMP:
                this.store(dest, "select(" + s(2) + ", " + s(1) + ", (" +
                    s(0) + ") >= vec4<f32>(0.0))");
                return;
            case OP.CND:
                this.store(dest, "select(" + s(2) + ", " + s(1) + ", (" +
                    s(0) + ") > vec4<f32>(0.5))");
                return;
            case OP.SINCOS: {
                const name = this.fresh("sc");
                this.emit("let " + name + " = " + scalar(0) + ";");
                this.store(dest, "vec4<f32>(cos(" + name + "), sin(" + name +
                    "), 0.0, 0.0)");
                return;
            }
            case OP.DSX:
            case OP.DSY: {
                const builtin = opcode === OP.DSX ? "dpdx" : "dpdy";
                this.store(dest, this.nonUniformDepth > 0
                    ? this.derivativeExpression(builtin, sources[0])
                    : builtin + "(" + s(0) + ")");
                return;
            }
            case OP.M4x4: this.matrix(dest, sources, 4, 4); return;
            case OP.M4x3: this.matrix(dest, sources, 4, 3); return;
            case OP.M3x4: this.matrix(dest, sources, 3, 4); return;
            case OP.M3x3: this.matrix(dest, sources, 3, 3); return;
            case OP.M3x2: this.matrix(dest, sources, 3, 2); return;
            case OP.SETP: {
                const comparison = this.comparison(instruction.control,
                    s(0), s(1), true);
                this.store(dest, comparison, { bool: true });
                return;
            }
            case OP.TEXKILL: {
                // ps_1_x tests xyz, ps_2_0+ tests xyzw.
                const register = this.rawSource({ type: dest.type, index: dest.index,
                    swizzle: 0xe4, modifier: 0, relative: false, relativeToken: 0 });
                const components = this.major === 1 ? ".xyz" : ".xyzw";
                this.emit("if (any((" + register + ")" + components +
                    " < vec" + (this.major === 1 ? 3 : 4) + "<f32>(0.0))) { discard; }");
                return;
            }
            case OP.TEXCOORD: {
                if (this.major === 1 && this.minor < 4) {
                    // ps_1_1-1_3: dest register number *is* the texcoord index,
                    // and the result is clamped to [0,1].
                    this.psTexcoordInputs.add(dest.index);
                    this.store(dest, "clamp(t" + dest.index +
                        ", vec4<f32>(0.0), vec4<f32>(1.0))");
                } else {
                    this.store(dest, s(0));
                }
                return;
            }
            case OP.TEX: this.textureLoad(instruction); return;
            case OP.TEXLDL: this.textureLoad(instruction, { explicitLod: true }); return;
            case OP.TEXLDD: this.textureLoad(instruction, { gradients: true }); return;
            case OP.BEM: {
                // ps_1_4's arithmetic form of the same displacement, with no
                // sampling: src1 carries a (du, dv) pair, src0 the coordinate
                // to displace, and the 2x2 matrix comes from the texture stage
                // named by the *destination* register index -- the rule texbem
                // follows and the one Wine's shader backends implement.
                //
                //   dest.r = src0.r + m00 * src1.r + m10 * src1.g
                //   dest.g = src0.g + m01 * src1.r + m11 * src1.g
                //
                // The instruction writes .rg and nothing else, so the mask is
                // narrowed here rather than trusted: a full-mask encoding must
                // not clear the destination's b and a.
                const index = dest.index;
                this.bumpStages.add(index);
                const bump = "d9c.bump[" + index + "]";
                const base = this.fresh("bem");
                const delta = this.fresh("bemd");
                this.emit("let " + base + " = " + s(0) + ";");
                this.emit("let " + delta + " = " + s(1) + ";");
                this.store(Object.assign({}, dest,
                        { writeMask: dest.writeMask & 0x3 }),
                    "vec4<f32>(" + base + ".x + " + bump + ".x * " + delta +
                    ".x + " + bump + ".z * " + delta + ".y, " + base + ".y + " +
                    bump + ".y * " + delta + ".x + " + bump + ".w * " + delta +
                    ".y, 0.0, 0.0)");
                return;
            }
            case OP.TEXBEM:
            case OP.TEXBEML: {
                // ps_1_x environment bump mapping. The source register holds a
                // sampled (du, dv) pair; this stage's own texture coordinate is
                // displaced by it through the stage's D3DTSS_BUMPENVMAT*
                // matrix, and the displaced coordinate is what gets sampled.
                //
                // The matrix is texture-stage state, not shader state, so it
                // arrives through the uniform block the host fills from
                // textureStageStates -- see bumpStageCount in the reflection.
                const index = dest.index;
                if (!this.samplers.has(index)) this.samplers.set(index, "2d");
                this.psTexcoordInputs.add(index);
                this.bumpStages.add(index);
                const bump = "d9c.bump[" + index + "]";
                const source = this.rawSource({ type: sources[0].type,
                    index: sources[0].index, swizzle: 0xe4, modifier: 0,
                    relative: false, relativeToken: 0 });
                const perturbed = this.fresh("bem");
                this.emit("let " + perturbed + " = t" + index + ".xy + vec2<f32>(" +
                    bump + ".x * (" + source + ").x + " + bump + ".z * (" +
                    source + ").y, " + bump + ".y * (" + source + ").x + " +
                    bump + ".w * (" + source + ").y);");
                const sampled = this.sampleExpression(index,
                    { coord: perturbed, ref: null }, {});
                if (instruction.opcode === OP.TEXBEM) {
                    this.store(dest, sampled);
                } else {
                    // The luminance form scales the sampled colour by the bump
                    // map's blue channel through BUMPENVLSCALE/BUMPENVLOFFSET.
                    const lit = this.fresh("beml");
                    const lum = "d9c.bump_lum[" + index + "]";
                    this.emit("let " + lit + " = " + sampled + ";");
                    this.store(dest, "vec4<f32>(" + lit + ".rgb * clamp(" +
                        lum + ".x * (" + source + ").z + " + lum +
                        ".y, 0.0, 1.0), " + lit + ".a)");
                }
                return;
            }
            case OP.TEXDP3: {
                // A 3-component dot of this stage's texture coordinate with the
                // source register, replicated across the destination.
                const index = dest.index;
                this.psTexcoordInputs.add(index);
                const value = "dot(t" + index + ".xyz, (" +
                    this.rawSource({ type: sources[0].type,
                        index: sources[0].index, swizzle: 0xe4, modifier: 0,
                        relative: false, relativeToken: 0 }) + ").xyz)";
                this.store(dest, "vec4<f32>(" + value + ")");
                return;
            }
            case OP.TEXDP3TEX: {
                // Same dot, then a 1D lookup with it. WGSL has no 1D texture,
                // so the sampler is treated as 2D with v = 0 -- which is how
                // every desktop driver implements the ps_1_x 1D forms too.
                const index = dest.index;
                if (!this.samplers.has(index)) this.samplers.set(index, "2d");
                this.psTexcoordInputs.add(index);
                const coord = this.fresh("dp3tex");
                this.emit("let " + coord + " = vec2<f32>(dot(t" + index +
                    ".xyz, (" + this.rawSource({ type: sources[0].type,
                        index: sources[0].index, swizzle: 0xe4, modifier: 0,
                        relative: false, relativeToken: 0 }) +
                    ").xyz), 0.0);");
                this.store(dest, this.sampleExpression(index,
                    { coord, ref: null }, {}));
                return;
            }
            case OP.TEXM3x2PAD:
            case OP.TEXM3x3PAD: {
                // A "pad" instruction contributes one row of the matrix and
                // produces no visible result; the row is consumed by the
                // TEXM3x*TEX/SPEC/VSPEC that follows it. ps_1_x guarantees the
                // ordering, so a running list is enough.
                const row = this.fresh("m3row");
                this.psTexcoordInputs.add(dest.index);
                this.emit("let " + row + " = dot(t" + dest.index + ".xyz, (" +
                    this.rawSource({ type: sources[0].type,
                        index: sources[0].index, swizzle: 0xe4, modifier: 0,
                        relative: false, relativeToken: 0 }) + ").xyz);");
                this.matrixRows.push(row);
                return;
            }
            case OP.TEXM3x2TEX: {
                const index = dest.index;
                if (!this.samplers.has(index)) this.samplers.set(index, "2d");
                this.psTexcoordInputs.add(index);
                const last = this.fresh("m3row");
                this.emit("let " + last + " = dot(t" + index + ".xyz, (" +
                    this.rawSource({ type: sources[0].type,
                        index: sources[0].index, swizzle: 0xe4, modifier: 0,
                        relative: false, relativeToken: 0 }) + ").xyz);");
                const rows = this.takeMatrixRows(1, last);
                const coord = this.fresh("m3x2");
                this.emit("let " + coord + " = vec2<f32>(" + rows.join(", ") + ");");
                this.store(dest, this.sampleExpression(index,
                    { coord, ref: null }, {}));
                return;
            }
            case OP.TEXM3x3TEX:
            case OP.TEXM3x3SPEC:
            case OP.TEXM3x3VSPEC: {
                const index = dest.index;
                // The 3x3 forms address a cube map or a volume; both take a
                // three-component coordinate, and a cube is what environment
                // mapping actually binds.
                if (!this.samplers.has(index)) this.samplers.set(index, "cube");
                this.psTexcoordInputs.add(index);
                const last = this.fresh("m3row");
                this.emit("let " + last + " = dot(t" + index + ".xyz, (" +
                    this.rawSource({ type: sources[0].type,
                        index: sources[0].index, swizzle: 0xe4, modifier: 0,
                        relative: false, relativeToken: 0 }) + ").xyz);");
                const rows = this.takeMatrixRows(2, last);
                const normal = this.fresh("m3x3");
                this.emit("let " + normal + " = vec3<f32>(" + rows.join(", ") + ");");
                let coord = normal;
                if (instruction.opcode !== OP.TEXM3x3TEX) {
                    // SPEC takes the eye vector from a constant register;
                    // VSPEC takes it from the q components of the three
                    // texture coordinates the rows were built from.
                    const eye = instruction.opcode === OP.TEXM3x3SPEC
                        ? "(" + this.sourceExpression(sources[1]) + ").xyz"
                        : "vec3<f32>(t" + (index - 2) + ".w, t" + (index - 1) +
                          ".w, t" + index + ".w)";
                    const reflected = this.fresh("m3refl");
                    // D3D's formula: 2 * N * (N.E) / (N.N) - E.
                    this.emit("let " + reflected + " = 2.0 * " + normal +
                        " * dot(" + normal + ", " + eye + ") / max(dot(" +
                        normal + ", " + normal + "), 1e-6) - " + eye + ";");
                    coord = reflected;
                }
                this.store(dest, this.sampleExpression(index,
                    { coord, ref: null }, {}));
                return;
            }
            case OP.TEXREG2AR:
                this.textureLoadFromComponents(instruction, "wx");
                return;
            case OP.TEXREG2GB:
                this.textureLoadFromComponents(instruction, "yz");
                return;
            case OP.TEXREG2RGB:
                this.textureLoadFromComponents(instruction, "xyz");
                return;
            case OP.IF:
                this.emit("if (" + this.booleanSource(sources[0]) + ") {");
                this.enter(false);
                return;
            case OP.IFC:
                this.emit("if (" + this.comparison(instruction.control,
                    "(" + s(0) + ").x", "(" + s(1) + ").x", false) + ") {");
                this.enter(true);
                return;
            case OP.ELSE:
                this.leave();
                this.emit("} else {");
                this.enterSameUniformity();
                return;
            case OP.ENDIF:
                this.leave();
                this.emit("}");
                return;
            case OP.REP: {
                const counter = this.fresh("rep");
                this.maxIntConst = Math.max(this.maxIntConst, sources[0].index);
                this.emit("for (var " + counter + " = 0; " + counter + " < d9c.i[" +
                    sources[0].index + "].x; " + counter + " = " + counter + " + 1) {");
                this.enter(false);
                return;
            }
            case OP.ENDREP:
                this.leave();
                this.emit("}");
                return;
            case OP.LOOP: {
                const counter = this.fresh("loop");
                const register = sources[1].index;
                this.usesLoopCounter = true;
                this.maxIntConst = Math.max(this.maxIntConst, register);
                this.emit("aL = d9c.i[" + register + "].y;");
                this.emit("for (var " + counter + " = 0; " + counter + " < d9c.i[" +
                    register + "].x; " + counter + " = " + counter + " + 1) {");
                this.enter(false);
                this.emit("// aL advances at the bottom of the body");
                this.pendingLoopStep = this.pendingLoopStep || [];
                this.pendingLoopStep.push(register);
                return;
            }
            case OP.ENDLOOP: {
                const register = this.pendingLoopStep && this.pendingLoopStep.pop();
                if (register !== undefined)
                    this.emit("aL = aL + d9c.i[" + register + "].z;");
                this.leave();
                this.emit("}");
                return;
            }
            case OP.BREAK: this.emit("break;"); return;
            case OP.BREAKC:
                this.emit("if (" + this.comparison(instruction.control,
                    "(" + s(0) + ").x", "(" + s(1) + ").x", false) + ") { break; }");
                return;
            case OP.BREAKP: {
                const component = SWIZZLE_CHARS[sources[0].swizzle & 0x3];
                this.usesPredicate = true;
                this.emit("if (" + (sources[0].modifier === SRCMOD_NOT ? "!" : "") +
                    "p0." + component + ") { break; }");
                return;
            }
            case OP.CALL:
                this.emit("d9_sub" + sources[0].index + "();");
                return;
            case OP.CALLNZ:
                this.emit("if (" + this.booleanSource(sources[1]) + ") { d9_sub" +
                    sources[0].index + "(); }");
                return;
            case OP.RET:
                this.emit("return;");
                return;
            case OP.LABEL:
                return; // handled by splitRoutines
            default:
                throw new Error("unimplemented instruction '" +
                    (OP_NAMES[opcode] || ("0x" + opcode.toString(16))) + "'");
            }
        }

        // A frame per open non-uniform region, recording where its opening
        // statement began and which registers have been written since. Both are
        // what dsx/dsy needs: see derivativeExpression().
        pushNonUniformFrame(insertAt) {
            this.nonUniformFrames = this.nonUniformFrames || [];
            this.nonUniformFrames.push({
                // The `if (...) {` line is emitted before enter() runs, so the
                // position *before* the region is one line back.
                insertAt: insertAt === undefined
                    ? Math.max(0, this.lines.length - 1) : insertAt,
                indent: Math.max(0, this.indent - 2),
                written: new Set(),
            });
        }

        enter(nonUniform) {
            this.indent += 2;
            ++this.controlDepth;
            this.uniformityStack = this.uniformityStack || [];
            this.uniformityStack.push(!!nonUniform);
            if (nonUniform) {
                ++this.nonUniformDepth;
                this.pushNonUniformFrame();
            }
        }

        enterSameUniformity() {
            this.indent += 2;
            ++this.controlDepth;
            const nonUniform = this.lastLeftNonUniform;
            this.uniformityStack.push(nonUniform);
            if (nonUniform) {
                ++this.nonUniformDepth;
                // An `else` branch hoists to before the whole `if`, not to
                // before the `} else {` -- that position is inside the *then*
                // branch, where the code would run under the wrong condition.
                // Writes made by the then-branch do not reach here, so the
                // written-register set starts empty again.
                this.pushNonUniformFrame(this.lastLeftInsertAt);
            }
        }

        leave() {
            this.indent -= 2;
            --this.controlDepth;
            const nonUniform = (this.uniformityStack || []).pop();
            this.lastLeftNonUniform = nonUniform;
            if (nonUniform) {
                --this.nonUniformDepth;
                const frame = (this.nonUniformFrames || []).pop();
                this.lastLeftInsertAt = frame ? frame.insertAt : undefined;
            }
        }

        // Every register written inside an open non-uniform region, so a later
        // hoist can tell whether the value it wants still exists above it.
        noteRegisterWrite(dest) {
            if (!this.nonUniformFrames || !this.nonUniformFrames.length) return;
            const key = dest.type + ":" + dest.index;
            for (const frame of this.nonUniformFrames) frame.written.add(key);
        }

        /*
         * dsx/dsy inside data-dependent control flow.
         *
         * D3D9 runs both sides of a branch on real hardware, so a derivative
         * taken inside an `if` is well defined there. WGSL forbids it outright,
         * and the shader fails to compile -- which is not a subtle difference:
         * 3DMark06's airship rendered as a black silhouette because its pixel
         * shader would not build at all.
         *
         * The derivative almost always reads a register computed *before* the
         * branch (screen-space coordinates, most often), so hoisting the call
         * to just above the branch is both legal and exactly what the shader
         * asked for. That is only true while nothing has overwritten the
         * operand inside the region, which is what the written-register set
         * tracks; when it has, there is no value above the branch to take a
         * derivative of and the result degrades to zero -- flat, noted, and
         * still a shader that compiles.
         */
        derivativeExpression(builtin, source) {
            const registerKey = source.type + ":" + source.index;
            const frames = this.nonUniformFrames || [];
            const clobbered = frames.some(frame => frame.written.has(registerKey));
            const before = this.lines.length;
            const expression = this.sourceExpression(source);
            // A source modifier that emits its own statement cannot be hoisted
            // with the call; those statements would stay behind.
            const emitted = this.lines.length !== before;
            if (!clobbered && !emitted && !source.relative && frames.length) {
                const outermost = frames[0];
                const name = this.fresh("deriv");
                this.lines.splice(outermost.insertAt, 0,
                    " ".repeat(outermost.indent) + "let " + name + " = " +
                    builtin + "(" + expression + ");");
                for (const frame of frames) ++frame.insertAt;
                this.note("a screen-space derivative inside data-dependent " +
                    "control flow was hoisted above the branch, which WGSL " +
                    "requires and D3D9 does not");
                return name;
            }
            this.note("a screen-space derivative inside data-dependent control " +
                "flow reads a register the branch itself overwrote; there is no " +
                "value above the branch to differentiate, so it evaluates to " +
                "zero (WGSL forbids the call there)");
            return "vec4<f32>(0.0)";
        }

        comparison(control, left, right, componentwise) {
            const operators = { 1: ">", 2: "==", 3: ">=", 4: "<", 5: "!=", 6: "<=" };
            const operator = operators[control];
            if (!operator)
                throw new Error("unsupported comparison control " + control);
            void componentwise;
            return "(" + left + ") " + operator + " (" + right + ")";
        }

        // `if b3` / `callnz l0, b3` -- a bool constant register, optionally
        // negated with the `!` source modifier.
        booleanSource(source) {
            if (source.type === REG_CONSTBOOL) {
                this.maxBoolConst = Math.max(this.maxBoolConst, source.index);
                const expression = "(d9c.b[" + (source.index >> 2) + "][" +
                    (source.index & 3) + "] != 0u)";
                return source.modifier === SRCMOD_NOT ? "!" + expression : expression;
            }
            if (source.type === REG_PREDICATE) {
                this.usesPredicate = true;
                const component = SWIZZLE_CHARS[source.swizzle & 0x3];
                return (source.modifier === SRCMOD_NOT ? "!" : "") + "p0." + component;
            }
            return "((" + this.sourceExpression(source) + ").x != 0.0)";
        }

        // m4x4/m4x3/m3x4/m3x2: src1 names the first of `rows` consecutive
        // registers; each contributes one dot product against src0.
        matrix(dest, sources, size, rows) {
            const vector = this.fresh("m");
            this.emit("let " + vector + " = " + this.sourceExpression(sources[0]) + ";");
            const components = [];
            for (let row = 0; row < rows; ++row) {
                const rowSource = Object.assign({}, sources[1],
                    { index: sources[1].index + row });
                const rowExpression = this.sourceExpression(rowSource);
                components.push(size === 4
                    ? "dot(" + vector + ", " + rowExpression + ")"
                    : "dot(" + vector + ".xyz, (" + rowExpression + ").xyz)");
            }
            while (components.length < 4) components.push("0.0");
            this.store(dest, "vec4<f32>(" + components.join(", ") + ")");
        }

        samplerIndexFor(source) {
            if (source.type !== REG_SAMPLER)
                throw new Error("texture instruction source is not a sampler register");
            if (!this.samplers.has(source.index)) this.samplers.set(source.index, "2d");
            return source.index;
        }

        // Whether stage `index` is sampled as a depth comparison rather than as
        // an ordinary texture. The caller asks; this decides, because a depth
        // sample needs a comparison reference the shader must actually supply:
        //
        //  - Only 2D. A cube or volume depth texture cannot be created here at
        //    all (the protocol's render target binding carries no face index),
        //    so a request for one is a caller bug, not a shader to translate.
        //  - Not ps_1_x. Its texreg2* forms build coordinates out of a
        //    previously sampled register and have no z to compare against, and
        //    hardware shadow maps postdate that shader model entirely.
        //  - Pixel stage only. vs_3_0 vertex texture fetch on a shadow map is
        //    legal in principle but has no caller, and supporting it would mean
        //    a second binding-type path through the vertex sampler layout.
        //
        // Whatever survives is reported in the reflection so the host binds a
        // depth view to exactly the slots declared texture_depth_2d, and the
        // white fallback everywhere else. A mismatch there is a WebGPU
        // validation error that takes down the whole submit, not one draw.
        isDepthSampler(index) {
            return this.requestedDepthSamplers.has(index)
                && this.kind === "pixel" && this.major >= 2
                && (this.samplers.get(index) || "2d") === "2d";
        }

        isDepthFetchSampler(index) {
            return this.isDepthSampler(index)
                && this.requestedDepthFetchSamplers.has(index);
        }

        // Coordinate arity per sampler type; the extra components a D3D9
        // shader leaves in the register are simply not read -- except on a
        // depth sampler, where z is the comparison reference and so has to be
        // carried out alongside the uv rather than dropped with the rest.
        coordinateFor(index, expression, projected) {
            const type = this.samplers.get(index) || "2d";
            const arity = type === "cube" ? 3 : (type === "3d" ? 3 : 2);
            const name = this.fresh("uv");
            this.emit("let " + name + " = " + expression + ";");
            const swizzle = arity === 3 ? "xyz" : "xy";
            // A fetch sampler is depth but takes no reference: emitting one
            // would send it down the comparison path in sampleExpression().
            const wantsDepth = this.isDepthSampler(index)
                && !this.isDepthFetchSampler(index);
            // The divisor is spelled out twice rather than hoisted into a let:
            // the non-projected and non-depth forms have to keep producing
            // exactly the expression they produced before, and `a / b * c` does
            // not reassociate to `a * (c / b)` in floating point.
            const project = value => "(" + value + " / max(abs(" + name +
                ".w), 1e-8) * sign(" + name + ".w + 1e-20))";
            if (projected)
                return { coord: project(name + "." + swizzle),
                    ref: wantsDepth ? project(name + ".z") : null };
            return { coord: name + "." + swizzle,
                ref: wantsDepth ? name + ".z" : null };
        }

        sampleExpression(index, coordinate, options) {
            const texture = "d9_tex" + index;
            const sampler = "d9_smp" + index;
            const coord = this.mirrorOnceCoord(index, coordinate.coord);
            if (coordinate.ref !== null && coordinate.ref !== undefined)
                return this.compareExpression(texture, sampler, coord,
                    coordinate.ref, options);
            if (this.isDepthFetchSampler(index))
                return this.depthFetchExpression(texture, sampler, coord,
                    options);
            if (options && options.gradients)
                return "textureSampleGrad(" + texture + ", " + sampler + ", " +
                    coord + ", " + options.ddx + ", " + options.ddy + ")";
            if (options && options.explicitLod)
                return "textureSampleLevel(" + texture + ", " + sampler + ", " +
                    coord + ", " + options.lod + ")";
            if (options && options.bias !== undefined)
                return this.nonUniformDepth > 0
                    ? this.degradedSample(texture, sampler, coord)
                    : "textureSampleBias(" + texture + ", " + sampler + ", " +
                        coord + ", " + options.bias + ")";
            const stateBias = this.samplerLodBias
                ? this.samplerLodBias[index] : 0;
            if (this.nonUniformDepth > 0)
                return this.degradedSample(texture, sampler, coord);
            // A sampler-state bias applies to the ordinary implicit-derivative
            // sample only. D3D9 ignores it for the explicit-LOD and gradient
            // forms above, and a vertex fetch has no mip chain to bias.
            if (stateBias && this.kind !== "vertex")
                return "textureSampleBias(" + texture + ", " + sampler + ", " +
                    coord + ", " + floatLiteral(stateBias) + ")";
            // Vertex shaders have no implicit derivatives. D3D9 permits VTF
            // only in vs_3_0 and its ordinary texld form selects mip zero;
            // texldl above still uses the explicit LOD carried in coord.w.
            if (this.kind === "vertex")
                return "textureSampleLevel(" + texture + ", " + sampler + ", " +
                    coord + ", 0.0)";
            return "textureSample(" + texture + ", " + sampler + ", " + coord + ")";
        }

        // D3DTADDRESS_MIRRORONCE folded into the coordinate. Cube addressing
        // ignores address modes entirely, so a cube sampler is left alone.
        mirrorOnceCoord(index, coord) {
            const axes = this.samplerMirrorOnce
                ? this.samplerMirrorOnce[index] : null;
            if (!axes) return coord;
            const type = this.samplers.get(index) || "2d";
            if (type === "cube") return coord;
            const components = type === "3d" ? ["x", "y", "z"] : ["x", "y"];
            const vector = type === "3d" ? "vec3<f32>" : "vec2<f32>";
            return vector + "(" + components.map(component =>
                (axes.includes(component)
                    ? "abs((" + coord + ")." + component + ")"
                    : "(" + coord + ")." + component)).join(", ") + ")";
        }

        // Reading a depth texture's stored value. texture_depth_2d sampling
        // returns a scalar, and D3D9 puts the depth in every channel -- shaders
        // read .r or .x from an INTZ/DF24 fetch interchangeably.
        //
        // WebGPU refuses to filter a depth texture except through a comparison,
        // so this is always a point sample of one level. That matches the
        // formats' purpose: an app choosing DF24 wants the exact stored depth
        // to filter itself, not a value the hardware already blended.
        depthFetchExpression(texture, sampler, coord, options) {
            // textureSampleLevel on a depth texture takes a *concrete integer*
            // level, unlike the f32 every colour-texture overload takes. naga
            // rejects the f32 form outright, which is the good outcome: the
            // alternative was a driver-specific failure inside the browser.
            const lod = (options && options.explicitLod)
                ? "i32(" + options.lod + ")" : "0i";
            return "vec4<f32>(textureSampleLevel(" + texture + ", " + sampler +
                ", " + coord + ", " + lod + "))";
        }

        // The hardware shadow map path. D3D9 returns the filtered comparison
        // result broadcast across all four channels -- shaders routinely read
        // .x, .w or .rgb from it interchangeably -- so the scalar is splatted
        // rather than placed in one component.
        //
        // WGSL has no comparison sampling with a gradient or a bias, and none
        // at all under non-uniform control flow. Every one of those degrades to
        // textureSampleCompareLevel, which samples level zero: shadow maps are
        // very nearly always single-level to begin with, so this is a real
        // approximation only for the rare mipped one.
        compareExpression(texture, sampler, coord, ref, options) {
            const explicitLevel = (options && (options.gradients ||
                options.explicitLod || options.bias !== undefined)) ||
                this.nonUniformDepth > 0;
            if (explicitLevel) {
                ++this.levelZeroSamples;
                this.note("a depth comparison sample selects mip level 0: WGSL " +
                    "has no gradient, bias or non-uniform form of " +
                    "textureSampleCompare");
                return "vec4<f32>(textureSampleCompareLevel(" + texture + ", " +
                    sampler + ", " + coord + ", " + ref + "))";
            }
            return "vec4<f32>(textureSampleCompare(" + texture + ", " +
                sampler + ", " + coord + ", " + ref + "))";
        }

        /*
         * Recovers real gradients for a texture sample inside data-dependent
         * control flow.
         *
         * WGSL forbids implicit-derivative sampling there, and the fallback
         * below picks mip level 0 -- correct-ish but visibly aliased wherever
         * the surface is minified, which in practice is most of a scene. When
         * the coordinate comes from a register the branch has not touched,
         * there *is* a value above the branch to differentiate: hoist the
         * coordinate and both derivatives out, and sample with
         * textureSampleGrad, which WGSL permits under any control flow because
         * the gradients are explicit. That is not a degradation at all -- it is
         * the mip level the shader would have selected on D3D9 hardware.
         *
         * Returns null when the coordinate cannot be reconstructed above the
         * branch, leaving degradedSample() to handle it.
         */
        hoistedGradients(index, source, coordinateExpression, projected) {
            const frames = this.nonUniformFrames || [];
            if (!frames.length || !source || source.relative) return null;
            if (frames.some(frame =>
                    frame.written.has(source.type + ":" + source.index)))
                return null;
            const type = this.samplers.get(index) || "2d";
            const swizzle = (type === "cube" || type === "3d") ? "xyz" : "xy";
            const outermost = frames[0];
            const pad = " ".repeat(outermost.indent);
            const raw = this.fresh("guv");
            const uv = this.fresh("gc");
            const dx = this.fresh("gdx");
            const dy = this.fresh("gdy");
            const projectedExpression = projected
                ? "(" + raw + "." + swizzle + " / max(abs(" + raw +
                    ".w), 1e-8) * sign(" + raw + ".w + 1e-20))"
                : raw + "." + swizzle;
            this.lines.splice(outermost.insertAt, 0,
                pad + "let " + raw + " = " + coordinateExpression + ";",
                pad + "let " + uv + " = " + projectedExpression + ";",
                pad + "let " + dx + " = dpdx(" + uv + ");",
                pad + "let " + dy + " = dpdy(" + uv + ");");
            for (const frame of frames) frame.insertAt += 4;
            this.note("a texture sample inside data-dependent control flow " +
                "keeps its real mip level: the coordinate and its derivatives " +
                "are hoisted above the branch and the sample uses explicit " +
                "gradients, which WGSL allows there");
            return { coordinate: uv, ddx: dx, ddy: dy };
        }

        // WGSL forbids implicit-derivative sampling under non-uniform control
        // flow. When hoistedGradients() cannot reconstruct the coordinate above
        // the branch -- because the branch computed it -- mip level 0 is the
        // legal, deterministic fallback: visibly sharper/aliased rather than
        // wrong colours, and counted so it is never a silent difference. Note
        // this is unreachable for ps_2_0 (no flow control at all in that model)
        // and for uniform `if b#`/`rep`/`loop` bodies, whose conditions come
        // from the uniform buffer and so keep control flow uniform.
        degradedSample(texture, sampler, coordinate) {
            ++this.levelZeroSamples;
            this.note("sampling inside data-dependent control flow falls back " +
                "to mip level 0 (WGSL forbids implicit derivatives there)");
            return "textureSampleLevel(" + texture + ", " + sampler + ", " +
                coordinate + ", 0.0)";
        }

        // Consumes the rows the preceding texm3x*pad instructions produced,
        // plus the row the consuming instruction just computed.
        //
        // A shader whose pad/tex pairing is malformed (a texm3x3tex with no
        // pads before it, say) would otherwise read undefined rows. Padding
        // with zero keeps the translation well-formed and notes it, rather
        // than emitting WGSL that references a variable that was never let.
        takeMatrixRows(expected, last) {
            const rows = this.matrixRows.splice(-expected, expected);
            while (rows.length < expected) {
                rows.unshift("0.0");
                this.note("a texm3x* instruction found fewer preceding " +
                    "texm3x*pad rows than it needs; the missing rows read zero");
            }
            rows.push(last);
            return rows;
        }

        legacySamplerType(index) {
            // ps_1_x tex/texld have no sampler declaration. SetTexture selects
            // the dimension at draw time; default to 2D only for the base
            // translation made before a texture is bound.
            const type = (this.options.legacySamplerTypes || {})[index];
            return type === "cube" || type === "3d" ? type : "2d";
        }

        textureLoad(instruction, options) {
            const dest = instruction.dest;
            const sources = instruction.sources;
            const projected = (instruction.control & 0x1) !== 0;
            const biased = (instruction.control & 0x2) !== 0;
            let index, coordinateExpression;
            if (this.kind === "pixel" && this.major === 1 && this.minor < 4) {
                // ps_1_1-1_3 `tex t#`: register number selects both the
                // sampler and the texture coordinate set.
                index = dest.index;
                if (!this.samplers.has(index))
                    this.samplers.set(index, this.legacySamplerType(index));
                this.psTexcoordInputs.add(index);
                coordinateExpression = "t" + index;
            } else if (this.kind === "pixel" && this.major === 1) {
                // ps_1_4 `texld r#, t#`: sampler comes from the destination.
                index = dest.index;
                if (!this.samplers.has(index))
                    this.samplers.set(index, this.legacySamplerType(index));
                coordinateExpression = this.sourceExpression(sources[0]);
            } else {
                index = this.samplerIndexFor(sources[1]);
                coordinateExpression = this.sourceExpression(sources[0]);
            }
            // Try to keep the real mip level before anything else decides the
            // sample has to be level 0. Only the plain and biased forms need
            // it: texldd already carries explicit gradients and texldl an
            // explicit level, and both are legal in non-uniform flow as they
            // stand.
            //
            // Depth samplers are excluded: WGSL has no textureSampleCompareGrad,
            // so there is no gradient form to recover *to*, and the comparison
            // reference must survive -- compareExpression() already handles
            // them and drops to textureSampleCompareLevel.
            const wantsImplicitLod = !(options &&
                (options.explicitLod || options.gradients)) &&
                !this.isDepthSampler(index);
            const recovered = (this.nonUniformDepth > 0 && wantsImplicitLod)
                ? this.hoistedGradients(index,
                    (this.kind === "pixel" && this.major === 1 && this.minor < 4)
                        ? null : sources[0],
                    coordinateExpression, projected)
                : null;
            if (recovered) {
                this.store(dest, this.sampleExpression(index,
                    { coord: recovered.coordinate, ref: null },
                    { gradients: true, ddx: recovered.ddx, ddy: recovered.ddy }));
                return;
            }
            const coordinate = this.coordinateFor(index, coordinateExpression, projected);
            const sampleOptions = {};
            if (options && options.explicitLod) {
                const raw = this.fresh("lod");
                this.emit("let " + raw + " = (" + coordinateExpression + ").w;");
                sampleOptions.explicitLod = true;
                sampleOptions.lod = raw;
            } else if (options && options.gradients) {
                sampleOptions.gradients = true;
                sampleOptions.ddx = "(" + this.sourceExpression(sources[2]) + ")." +
                    ((this.samplers.get(index) || "2d") === "2d" ? "xy" : "xyz");
                sampleOptions.ddy = "(" + this.sourceExpression(sources[3]) + ")." +
                    ((this.samplers.get(index) || "2d") === "2d" ? "xy" : "xyz");
            } else if (biased) {
                sampleOptions.bias = "(" + coordinateExpression + ").w";
            }
            this.store(dest, this.sampleExpression(index, coordinate, sampleOptions));
        }

        // ps_1_x texreg2ar/gb/rgb: build the coordinate from components of a
        // previously-sampled register instead of a texcoord input.
        textureLoadFromComponents(instruction, components) {
            const dest = instruction.dest;
            const index = dest.index;
            if (!this.samplers.has(index))
                this.samplers.set(index, components.length === 3 ? "3d" : "2d");
            // ps_1_x only, and isDepthSampler() excludes ps_1_x, so this form
            // never carries a comparison reference.
            const coordinate = { coord: "(" +
                this.sourceExpression(instruction.sources[0]) + ")." + components,
                ref: null };
            this.store(dest, this.sampleExpression(index, coordinate, {}));
        }

        // ---- module assembly ----

        assemble(routines, bodies, mainBody) {
            const out = [];
            const kind = this.kind;
            const floatCount = Math.max(1, Math.min(this.constantCapacity(),
                this.maxFloatConst + 1));
            const intCount = Math.max(1, this.maxIntConst + 1);
            const boolVectors = Math.max(1, Math.ceil((this.maxBoolConst + 1) / 4));

            out.push("// translated from " + kind + " shader model " +
                this.major + "." + this.minor);
            out.push("struct D9Constants {");
            out.push("    f: array<vec4<f32>, " + floatCount + ">,");
            out.push("    i: array<vec4<i32>, " + intCount + ">,");
            out.push("    b: array<vec4<u32>, " + boolVectors + ">,");
            if (kind === "vertex") {
                // xy = render target size in pixels, for the D3D9 half-pixel
                // offset applied to o_position below.
                out.push("    viewport: vec4<f32>,");
                if (this.options.clipPlaneCount)
                    out.push("    clip_planes: array<vec4<f32>, " +
                        this.options.clipPlaneCount + ">,");
            }
            if (kind === "vertex" && this.options.pointExpansion) {
                out.push("    point_viewport: vec4<f32>,");
                out.push("    point_params: vec4<f32>,");
            }
            if (kind === "pixel" && this.bumpStages.size) {
                // One (m00, m01, m10, m11) per sampler up to the highest one a
                // texbem names, plus the luminance scale/offset pair. Indexed
                // by sampler so the WGSL can subscript it directly.
                const count = Math.max(...this.bumpStages) + 1;
                out.push("    bump: array<vec4<f32>, " + count + ">,");
                out.push("    bump_lum: array<vec4<f32>, " + count + ">,");
            }
            out.push("};");
            out.push("@group(0) @binding(" + (kind === "vertex" ? 0 : 1) +
                ") var<uniform> d9c: D9Constants;");

            const samplerIndices = Array.from(this.samplers.keys()).sort((a, b) => a - b);
            const samplerBindingBase = kind === "vertex" ? 34 : 2;
            for (const index of samplerIndices) {
                const type = this.samplers.get(index);
                const depth = this.isDepthSampler(index);
                const compare = depth && !this.isDepthFetchSampler(index);
                const wgslType = depth ? "texture_depth_2d"
                    : (type === "cube" ? "texture_cube<f32>"
                        : (type === "3d" ? "texture_3d<f32>" : "texture_2d<f32>"));
                out.push("@group(0) @binding(" + (samplerBindingBase + index * 2) + ") var d9_tex" +
                    index + ": " + wgslType + ";");
                out.push("@group(0) @binding(" + (samplerBindingBase + 1 + index * 2) + ") var d9_smp" +
                    index + ": " + (compare ? "sampler_comparison" : "sampler") + ";");
            }

            out.push("");
            out.push("fn d9_rcp(v: f32) -> f32 { return select(1.0 / v, " +
                FLOAT_MAX + ", v == 0.0); }");
            out.push("fn d9_rsq(v: f32) -> f32 { let a = abs(v); return " +
                "select(inverseSqrt(a), " + FLOAT_MAX + ", a == 0.0); }");
            out.push("fn d9_log(v: f32) -> f32 { let a = abs(v); return " +
                "select(log2(a), -" + FLOAT_MAX + ", a == 0.0); }");
            out.push("fn d9_normalize(v: vec3<f32>) -> vec3<f32> { let l = " +
                "dot(v, v); return select(v * inverseSqrt(l), vec3<f32>(0.0), l == 0.0); }");
            out.push("fn d9_lit(s: vec4<f32>) -> vec4<f32> {");
            out.push("    let power = clamp(s.w, -127.9961, 127.9961);");
            out.push("    let specular = select(0.0, pow(max(s.y, 0.0), power), " +
                "s.x > 0.0 && s.y > 0.0);");
            out.push("    return vec4<f32>(1.0, max(s.x, 0.0), specular, 1.0);");
            out.push("}");
            out.push("");

            // Registers live at module scope so `label` subroutines can share
            // them without threading a state struct through every call.
            for (const index of Array.from(this.temps).sort((a, b) => a - b))
                out.push("var<private> r" + index + ": vec4<f32> = vec4<f32>(0.0);");
            if (this.usesAddress) {
                out.push("var<private> a0: vec4<i32> = vec4<i32>(0);");
                out.push("var<private> a0f: vec4<f32> = vec4<f32>(0.0);");
            }
            if (this.usesLoopCounter) out.push("var<private> aL: i32 = 0;");
            if (this.usesPredicate) {
                out.push("var<private> p0: vec4<bool> = vec4<bool>(false);");
                out.push("var<private> p0f: vec4<bool> = vec4<bool>(false);");
            }

            if (kind === "vertex") {
                out.push("var<private> o_position: vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);");
                if (this.usesPointSize)
                    out.push("var<private> o_pointsize: vec4<f32> = vec4<f32>(1.0);");
                for (let slot = 0; slot < VARYING_COUNT; ++slot) {
                    // D3D9's oFog factor defaults to one (no fog) when a
                    // vertex shader does not write it. Initialising it to
                    // zero makes a fixed-function pixel fog blend replace the
                    // entire textured draw with the fog colour.
                    const initialValue = slot === VARYING_FOG
                        ? "vec4<f32>(1.0, 0.0, 0.0, 0.0)" : "vec4<f32>(0.0)";
                    out.push("var<private> o_varying" + slot +
                        ": vec4<f32> = " + initialValue + ";");
                }
                for (const index of Array.from(this.usedInputs.keys()).sort((a, b) => a - b))
                    out.push("var<private> vin" + index + ": vec4<f32> = vec4<f32>(0.0);");
            } else {
                for (const index of Array.from(this.psTexcoordInputs).sort((a, b) => a - b))
                    out.push("var<private> t" + index + ": vec4<f32> = vec4<f32>(0.0);");
                for (const index of Array.from(this.psColorInputs).sort((a, b) => a - b))
                    out.push("var<private> v" + index + ": vec4<f32> = vec4<f32>(0.0);");
                for (const index of Array.from(this.colorOutputs).sort((a, b) => a - b))
                    out.push("var<private> oC" + index + ": vec4<f32> = vec4<f32>(0.0);");
                // ps_1_x has no oC# register at all: the final colour is
                // whatever the shader left in r0. r0 is declared with the
                // other temps above, so nothing extra is needed there, but a
                // ps_2_0+ shader that never writes oC0 still needs the
                // variable to exist for the epilogue to read.
                if (this.major > 1 && !this.colorOutputs.has(0))
                    out.push("var<private> oC0: vec4<f32> = vec4<f32>(0.0);");
                if (this.usesDepthOutput)
                    out.push("var<private> o_depthv: vec4<f32> = vec4<f32>(0.0);");
                if (this.usesFragPosition)
                    out.push("var<private> d9_frag_position: vec4<f32> = vec4<f32>(0.0);");
                if (this.usesFrontFacing)
                    out.push("var<private> d9_face: f32 = 1.0;");
            }
            out.push("");

            for (const routine of routines.subroutines) {
                out.push("fn d9_sub" + routine.label + "() {");
                out.push(...bodies.get(routine.label));
                out.push("}");
                out.push("");
            }

            out.push("fn d9_body() {");
            out.push(...mainBody);
            out.push("}");
            out.push("");

            if (kind === "vertex") this.assembleVertexEntry(out);
            else this.assemblePixelEntry(out);

            const reflection = this.reflect(floatCount, intCount, boolVectors);
            return { wgsl: out.join("\n") + "\n", reflection };
        }

        assembleVertexEntry(out) {
            const inputs = Array.from(this.usedInputs.keys())
                .map(register => [register, this.inputSemanticFor(register)])
                .filter(entry => entry[1])
                .sort((a, b) => a[0] - b[0]);
            const conversions = this.options.inputConversions || {};
            const conversionKinds = new Set(Object.values(conversions));
            if (conversionKinds.has("udec3")) {
                out.push("fn d9_unpack_udec3(value: u32) -> vec4<f32> {");
                out.push("    return vec4<f32>(f32(value & 0x3ffu), " +
                    "f32((value >> 10u) & 0x3ffu), " +
                    "f32((value >> 20u) & 0x3ffu), 1.0);");
                out.push("}");
                out.push("");
            }
            if (conversionKinds.has("dec3n")) {
                out.push("fn d9_snorm10(value: u32) -> f32 {");
                out.push("    let signed_value = i32(value << 22u) >> 22;");
                out.push("    return max(f32(signed_value) / 511.0, -1.0);");
                out.push("}");
                out.push("fn d9_unpack_dec3n(value: u32) -> vec4<f32> {");
                out.push("    return vec4<f32>(d9_snorm10(value & 0x3ffu), " +
                    "d9_snorm10((value >> 10u) & 0x3ffu), " +
                    "d9_snorm10((value >> 20u) & 0x3ffu), 1.0);");
                out.push("}");
                out.push("");
            }
            out.push("struct D9VertexOutput {");
            out.push("    @builtin(position) position: vec4<f32>,");
            for (let slot = 0; slot < VARYING_COUNT; ++slot)
                out.push(this.varyingDeclaration(slot));
            const clipPlaneCount = this.options.clipPlaneCount || 0;
            for (let group = 0; group < Math.ceil(clipPlaneCount / 4); ++group)
                out.push("    @location(" + (VARYING_COUNT + group) +
                    ") clip" + group + ": vec4<f32>,");
            out.push("};");
            out.push("");
            const inputType = location => ({
                ubyte4: "vec4<u32>", short2: "vec2<i32>",
                short4: "vec4<i32>", udec3: "u32", dec3n: "u32",
            })[conversions[location]] || "vec4<f32>";
            const parameters = inputs.map(entry =>
                "@location(" + entry[0] + ") in" + entry[0] + ": " +
                    inputType(entry[0]));
            if (this.options.pointExpansion)
                parameters.push("@builtin(vertex_index) d9_vertex_index: u32");
            out.push("@vertex");
            out.push("fn d9_vs_main(" + parameters.join(", ") + ") -> D9VertexOutput {");
            // A D3DCOLOR-typed attribute is packed ARGB in memory, so WebGPU's
            // unorm8x4 delivers it as (b, g, r, a) while D3D9 hands the shader
            // (r, g, b, a). The caller passes the set of locations that need
            // correcting -- it is the only party that knows the vertex
            // declaration -- and the swizzle rides on the copy into the
            // register instead of costing a CPU pass over the vertex data.
            // This is why a shader can have more than one translated variant
            // (see bgraInputLocations/inputConversions in compileShader's
            // options). Compact integer declarations need the same treatment:
            // WebGPU exposes integer vertex formats as integer WGSL values,
            // while D3D9 always presents them to v# as a float4.
            const bgra = new Set(this.options.bgraInputLocations || []);
            const inputValue = location => {
                const name = "in" + location;
                switch (conversions[location]) {
                case "ubyte4":
                case "short4": return "vec4<f32>(" + name + ")";
                case "short2":
                    return "vec4<f32>(vec2<f32>(" + name + "), 0.0, 1.0)";
                case "udec3": return "d9_unpack_udec3(" + name + ")";
                case "dec3n": return "d9_unpack_dec3n(" + name + ")";
                default: return name + (bgra.has(location) ? ".bgra" : "");
                }
            };
            for (const entry of inputs)
                out.push("    vin" + entry[0] + " = " +
                    inputValue(entry[0]) + ";");
            out.push("    d9_body();");
            out.push("    var result: D9VertexOutput;");
            // D3D9 clip space is z in [0, w]; WebGPU's is identical, so the
            // position needs no depth-range remap (unlike an OpenGL target,
            // which would need z = 2z - w here).
            //
            // XY does need fixing up: D3D9 samples a pixel at its integer
            // corner and WebGPU at its centre, half a pixel apart, and a title
            // that aligns output to pixels has already subtracted that half
            // pixel itself. Put it back, scaled by w so it stays half a pixel
            // at any depth, with y negated because screen y grows downward
            // while NDC y grows upward. Same fix as the fixed-function path's
            // HALF_PIXEL_OFFSET_BODY, and as wined3d's posFixup.
            out.push("    result.position = vec4<f32>(");
            out.push("        o_position.x + o_position.w / d9c.viewport.x,");
            out.push("        o_position.y - o_position.w / d9c.viewport.y,");
            out.push("        o_position.zw);");
            for (let slot = 0; slot < VARYING_COUNT; ++slot)
                out.push("    result.varying" + slot + " = o_varying" + slot + ";");
            for (let group = 0; group < Math.ceil(clipPlaneCount / 4); ++group)
                out.push("    result.clip" + group + " = vec4<f32>(1.0);");
            for (let plane = 0; plane < clipPlaneCount; ++plane)
                out.push("    result.clip" + Math.floor(plane / 4) + "." +
                    "xyzw"[plane & 3] + " = dot(o_position, " +
                    "d9c.clip_planes[" + plane + "]);" );
            if (this.options.pointExpansion) {
                out.push("    let d9_point_uvs = array<vec2<f32>, 6>(");
                out.push("        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0),");
                out.push("        vec2<f32>(0.0, 1.0), vec2<f32>(0.0, 1.0),");
                out.push("        vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));");
                out.push("    let d9_point_uv = d9_point_uvs[d9_vertex_index % 6u];");
                out.push("    var d9_point_size = " + (this.usesPointSize
                    ? "o_pointsize.x;" : "d9c.point_params.x;"));
                out.push("    d9_point_size = clamp(d9_point_size, d9c.point_params.y,");
                out.push("        max(d9c.point_params.y, d9c.point_params.z));");
                out.push("    let d9_point_ndc = vec2<f32>(");
                out.push("        (d9_point_uv.x * 2.0 - 1.0) * d9_point_size / d9c.point_viewport.x,");
                out.push("        (1.0 - d9_point_uv.y * 2.0) * d9_point_size / d9c.point_viewport.y);");
                out.push("    result.position = vec4<f32>(result.position.xy +");
                out.push("        d9_point_ndc * result.position.w, result.position.zw);");
                if (this.options.pointSprite) {
                    for (let stage = 0; stage < 8; ++stage) {
                        out.push("    result.varying" + (VARYING_TEXCOORD0 + stage) +
                            " = vec4<f32>(d9_point_uv, 0.0, 1.0);");
                    }
                }
            }
            out.push("    return result;");
            out.push("}");
        }

        assemblePixelEntry(out) {
            // ps_1_x/ps_2_0 have a fixed input mapping (t# = TEXCOORD#,
            // v# = COLOR#); ps_3_0 replaces it with dcl-declared semantics on
            // v# and has no t# registers at all.
            const declared = []; // { slot, register }
            if (this.major < 3) {
                for (const index of this.psTexcoordInputs)
                    declared.push({ slot: VARYING_TEXCOORD0 + index, register: "t" + index });
                for (const index of this.psColorInputs)
                    declared.push({ slot: VARYING_COLOR0 + index, register: "v" + index });
            } else {
                for (const index of this.psColorInputs) {
                    const semantic = this.usedInputs.get(index);
                    if (!semantic)
                        throw new Error("ps_3_0 input v" + index +
                            " was read without a dcl semantic");
                    const slot = varyingForSemantic(semantic.usage, semantic.usageIndex);
                    if (slot < 0)
                        throw new Error("pixel shader input semantic " + semantic.usage +
                            "[" + semantic.usageIndex + "] has no varying slot");
                    declared.push({ slot, register: "v" + index });
                }
            }
            for (const entry of declared) {
                if (entry.slot < 0 || entry.slot >= VARYING_COUNT)
                    throw new Error("pixel shader input maps outside the varying set");
            }

            out.push("struct D9PixelInput {");
            out.push("    @builtin(position) position: vec4<f32>,");
            for (let slot = 0; slot < VARYING_COUNT; ++slot)
                out.push(this.varyingDeclaration(slot));
            const clipPlaneCount = this.options.clipPlaneCount || 0;
            for (let group = 0; group < Math.ceil(clipPlaneCount / 4); ++group)
                out.push("    @location(" + (VARYING_COUNT + group) +
                    ") clip" + group + ": vec4<f32>,");
            out.push("};");
            out.push("");
            // One @location per oC# the shader writes. D3D9 requires oC0 and
            // allows oC1..oC3 for multiple render targets; a shader that skips
            // a middle target would leave a hole WebGPU has no way to express,
            // so the declared set is filled contiguously up to the highest one
            // written and the unwritten slots get whatever oC# defaulted to
            // (zero) -- which is what a real driver leaves in an untouched
            // target within a pass, and is visible in reflection.colorOutputs.
            const targetCount = this.colorOutputs.size
                ? Math.max(...this.colorOutputs) + 1 : 1;
            out.push("struct D9PixelOutput {");
            for (let target = 0; target < targetCount; ++target)
                out.push("    @location(" + target + ") color" + target +
                    ": vec4<f32>,");
            if (this.usesDepthOutput)
                out.push("    @builtin(frag_depth) depth: f32,");
            out.push("};");
            out.push("");
            out.push("@fragment");
            const faceParameter = this.usesFrontFacing
                ? ", @builtin(front_facing) d9_front: bool" : "";
            out.push("fn d9_ps_main(stage_in: D9PixelInput" + faceParameter +
                ") -> D9PixelOutput {");
            for (let plane = 0; plane < clipPlaneCount; ++plane)
                out.push("    if (stage_in.clip" + Math.floor(plane / 4) +
                    "." + "xyzw"[plane & 3] + " < 0.0) { discard; }");
            for (const entry of declared)
                out.push("    " + entry.register + " = stage_in.varying" + entry.slot + ";");
            if (this.usesFragPosition)
                out.push("    d9_frag_position = stage_in.position;");
            if (this.usesFrontFacing)
                out.push("    d9_face = select(-1.0, 1.0, d9_front);");
            out.push("    d9_body();");
            out.push("    var result: D9PixelOutput;");
            // ps_1_x leaves its result in r0; ps_2_0+ writes oC0 explicitly.
            out.push("    result.color0 = " + (this.major === 1 ? "r0" : "oC0") + ";");
            for (let target = 1; target < targetCount; ++target)
                out.push("    result.color" + target + " = oC" + target + ";");
            // D3D9's alpha test runs after the shader, on the colour it
            // produced. WebGPU has no such stage, so the caller passes the
            // comparison in and it becomes a discard here -- which is why an
            // alpha-tested draw needs its own translated variant of the same
            // bytecode (see alphaTest in compileShader's options).
            if (this.options.alphaTestDiscard)
                out.push(this.options.alphaTestDiscard.replace(/\n$/, ""));
            if (this.usesDepthOutput)
                out.push("    result.depth = o_depthv.x;");
            out.push("    return result;");
            out.push("}");

        }

        // The semantic a used v# carries: the one its dcl declared, or the
        // API's fixed vs_1_x table when the model has no dcl to declare it.
        inputSemanticFor(register) {
            const declared = this.usedInputs.get(register);
            if (declared) return declared;
            if (this.kind === "vertex" && this.major === 1)
                return vs1InputSemantic(register);
            return null;
        }

        reflect(floatCount, intCount, boolVectors) {
            const inputs = [];
            for (const register of this.usedInputs.keys()) {
                const semantic = this.inputSemanticFor(register);
                if (!semantic) continue;
                inputs.push({ register, usage: semantic.usage,
                    usageIndex: semantic.usageIndex, location: register });
            }
            inputs.sort((a, b) => a.register - b.register);
            const samplerBindingBase = this.kind === "vertex" ? 34 : 2;
            const samplers = Array.from(this.samplers.entries())
                .map(([index, type]) => ({ index, type,
                    depth: this.isDepthSampler(index)
                        ? (this.isDepthFetchSampler(index) ? "fetch" : "compare")
                        : false,
                    textureBinding: samplerBindingBase + index * 2,
                    samplerBinding: samplerBindingBase + 1 + index * 2 }))
                .sort((a, b) => a.index - b.index);
            const floatDefaults = [];
            for (const [register, values] of this.floatDefaults)
                floatDefaults.push({ register, values });
            const intDefaults = [];
            for (const [register, values] of this.intDefaults)
                intDefaults.push({ register, values });
            const boolDefaults = [];
            for (const [register, value] of this.boolDefaults)
                boolDefaults.push({ register, value });
            const registerUniformBytes = floatCount * 16 + intCount * 16 +
                boolVectors * 16;
            const pointExpansion = this.kind === "vertex" &&
                !!this.options.pointExpansion;
            // Every vertex shader carries the render target size for the
            // half-pixel offset, so it sits between the register region and the
            // optional point-sprite fields.
            const isVertex = this.kind === "vertex";
            const viewportOffset = isVertex ? registerUniformBytes : -1;
            const clipPlaneCount = isVertex
                ? (this.options.clipPlaneCount || 0) : 0;
            const clipPlanesOffset = clipPlaneCount
                ? registerUniformBytes + 16 : -1;
            const trailingOffset = registerUniformBytes + (isVertex ? 16 : 0)
                + clipPlaneCount * 16;
            // ps_1_x texbem/texbeml: the stage matrices follow the register
            // region, in the same order the struct above declares them.
            const bumpStageCount = (!isVertex && this.bumpStages.size)
                ? Math.max(...this.bumpStages) + 1 : 0;
            const bumpOffset = bumpStageCount ? trailingOffset : -1;
            const bumpLuminanceOffset = bumpStageCount
                ? trailingOffset + bumpStageCount * 16 : -1;
            return {
                kind: this.kind,
                version: { major: this.major, minor: this.minor },
                entryPoint: this.kind === "vertex" ? "d9_vs_main" : "d9_ps_main",
                inputs,
                samplers,
                floatConstCount: floatCount,
                intConstCount: intCount,
                boolVectorCount: boolVectors,
                usesRelativeConstants: this.usesRelativeConstants,
                writesPointSize: this.usesPointSize,
                writesDepth: this.usesDepthOutput,
                readsFrontFacing: this.usesFrontFacing,
                readsFragmentPosition: this.usesFragPosition,
                colorOutputs: Array.from(this.colorOutputs).sort((a, b) => a - b),
                // Which varying slots this shader actually assigns. A fixed-
                // function pixel cascade paired with a translated vertex
                // shader has to read the slots that shader wrote; reading one
                // it never wrote yields a constant, and a constant texture
                // coordinate samples one texel across a whole model -- a flat
                // silhouette that looks like a lighting or texture bug rather
                // than the stage/varying mismatch it is.
                writtenVaryings: Array.from(this.writtenVaryings)
                    .sort((a, b) => a - b),
                floatDefaults, intDefaults, boolDefaults,
                levelZeroSamples: this.levelZeroSamples,
                warnings: this.warnings.slice(),
                uniformBytes: trailingOffset + (pointExpansion ? 32 : 0) +
                    bumpStageCount * 32,
                bumpStageCount,
                bumpOffset,
                bumpLuminanceOffset,
                floatRegionBytes: floatCount * 16,
                intRegionBytes: intCount * 16,
                boolRegionBytes: boolVectors * 16,
                viewportOffset,
                clipPlaneCount,
                clipPlanesOffset,
                pointExpansion,
                pointSprite: pointExpansion && !!this.options.pointSprite,
                pointViewportOffset: pointExpansion ? trailingOffset : -1,
                pointParamsOffset: pointExpansion ? trailingOffset + 16 : -1,
            };
        }
    }

    // Translates one shader's raw token array. Never throws: a shader this
    // module cannot handle comes back as {ok:false, error}, because the
    // caller's contract (plan 4.2) is to mark the handle unusable and skip
    // draws that bind it -- not to fail the whole command batch.
    function compileShader(tokens, options) {
        try {
            const parsed = parseShader(tokens);
            const translator = new Translator(parsed, options);
            const result = translator.translate();
            return { ok: true, wgsl: result.wgsl, reflection: result.reflection };
        } catch (error) {
            return { ok: false, error: error && error.message ? error.message :
                String(error) };
        }
    }

    // 64-bit FNV-1a over the token stream, matching shader_bytecode_hash() in
    // d3d9_proxy.c so a host cache lookup can use the hash the guest already
    // computed without re-deriving it.
    function hashTokens(tokens) {
        let low = 0x84222325 >>> 0, high = 0xcbf29ce4 >>> 0;
        const mix = byte => {
            low = (low ^ byte) >>> 0;
            // 64-bit multiply by the FNV prime 0x100000001b3, done in 16-bit
            // limbs so it stays exact in doubles.
            const primeLow = 0x000001b3;
            const l0 = low & 0xffff, l1 = low >>> 16;
            const h0 = high & 0xffff, h1 = high >>> 16;
            let r0 = l0 * primeLow;
            let r1 = l1 * primeLow + (r0 >>> 16);
            let r2 = h0 * primeLow + (r1 >>> 16) + l0; // + low << 32 term
            let r3 = h1 * primeLow + (r2 >>> 16) + l1;
            low = ((r1 & 0xffff) << 16 | (r0 & 0xffff)) >>> 0;
            high = ((r3 & 0xffff) << 16 | (r2 & 0xffff)) >>> 0;
        };
        for (let i = 0; i < tokens.length; ++i) {
            const token = tokens[i] >>> 0;
            mix(token & 0xff);
            mix((token >>> 8) & 0xff);
            mix((token >>> 16) & 0xff);
            mix((token >>> 24) & 0xff);
        }
        return { low: low >>> 0, high: high >>> 0 };
    }

    // Content-addressed cache in front of compileShader(). Keyed by the
    // guest's bytecode hash so two CreateVertexShader calls with identical
    // bytecode -- routine when a game recreates its effect set after a device
    // Reset -- translate exactly once. Deliberately holds no GPU objects:
    // WGSL text survives device loss (plan 8.5), GPUShaderModules do not.
    class D3D9ShaderCache {
        constructor(options) {
            this.options = options || {};
            this.limit = this.options.limit || 4096;
            this.entries = new Map();
            this.clock = this.options.clock || (() =>
                typeof performance !== "undefined" && performance.now
                    ? performance.now() : Date.now());
            this.compileTimes = [];
            this.totalWGSLBytes = 0;
            this.stats = { compiles: 0, hits: 0, failures: 0, evictions: 0,
                restored: 0 };
        }

        key(hashLow, hashHigh) {
            return ((hashHigh >>> 0).toString(16) + ":" + (hashLow >>> 0).toString(16));
        }

        get(hashLow, hashHigh) {
            const key = this.key(hashLow, hashHigh);
            const entry = this.entries.get(key);
            if (!entry) return null;
            // Re-insert so Map iteration order stays least-recently-used first.
            this.entries.delete(key);
            this.entries.set(key, entry);
            ++this.stats.hits;
            return entry;
        }

        compile(tokens, hashLow, hashHigh, options) {
            const existing = this.get(hashLow, hashHigh);
            if (existing) return existing;
            const started = this.clock();
            const result = compileShader(tokens, options);
            const elapsed = Math.max(0, this.clock() - started);
            return this.store(hashLow, hashHigh, result, elapsed);
        }

        store(hashLow, hashHigh, result, elapsed) {
            const key = this.key(hashLow, hashHigh);
            const existing = this.entries.get(key);
            if (existing) return existing;
            elapsed = Math.max(0, Number(elapsed) || 0);
            this.compileTimes.push(elapsed);
            if (this.compileTimes.length > this.limit)
                this.compileTimes.shift();
            ++this.stats.compiles;
            if (!result.ok) ++this.stats.failures;
            this.entries.set(key, result);
            if (result.ok) this.totalWGSLBytes += result.wgsl.length * 2;
            while (this.entries.size > this.limit) {
                const oldest = this.entries.keys().next();
                if (oldest.done) break;
                const evicted = this.entries.get(oldest.value);
                if (evicted && evicted.ok)
                    this.totalWGSLBytes -= evicted.wgsl.length * 2;
                this.entries.delete(oldest.value);
                ++this.stats.evictions;
            }
            return result;
        }

        snapshot() {
            const sorted = this.compileTimes.slice().sort((a, b) => a - b);
            const percentile = value => {
                if (!sorted.length) return 0;
                return sorted[Math.min(sorted.length - 1,
                    Math.max(0, Math.ceil(value * sorted.length) - 1))];
            };
            return { hits: this.stats.hits, misses: this.stats.compiles,
                failures: this.stats.failures, evictions: this.stats.evictions,
                restored: this.stats.restored,
                cached: this.entries.size,
                totalWGSLBytes: Math.max(0, this.totalWGSLBytes),
                compileLatencyMs: { p50: percentile(0.50),
                    p95: percentile(0.95), p99: percentile(0.99),
                    samples: sorted.length } };
        }

        exportEntries(maxBytes) {
            const limit = maxBytes || 2 * 1024 * 1024;
            const entries = [];
            let bytes = 0;
            // Newest LRU entries are at the end; keep as many of those as the
            // persistent budget permits, then restore their original order.
            for (const [key, result] of Array.from(this.entries).reverse()) {
                const item = { key, result };
                const encoded = JSON.stringify(item);
                if (bytes + encoded.length * 2 > limit) continue;
                entries.push(item);
                bytes += encoded.length * 2;
            }
            entries.reverse();
            return { version: 1, revision: TRANSLATOR_REVISION, entries };
        }

        importEntries(payload) {
            if (!payload || payload.version !== 1 || !Array.isArray(payload.entries))
                return 0;
            // A payload written by a different build of the translator holds
            // that build's WGSL and reflection. Restoring it would mean this
            // session runs code this file no longer generates.
            if (payload.revision !== TRANSLATOR_REVISION) return 0;
            let restored = 0;
            for (const item of payload.entries) {
                if (!item || typeof item.key !== "string" || !item.result) continue;
                const result = item.result;
                if (result.ok && (typeof result.wgsl !== "string" ||
                        !result.reflection)) continue;
                if (!result.ok && typeof result.error !== "string") continue;
                if (this.entries.has(item.key)) continue;
                this.entries.set(item.key, result);
                if (result.ok) this.totalWGSLBytes += result.wgsl.length * 2;
                ++restored;
                if (this.entries.size >= this.limit) break;
            }
            this.stats.restored += restored;
            return restored;
        }
    }

    const api = {
        compileShader, parseShader, hashTokens, D3D9ShaderCache,
        TRANSLATOR_REVISION,
        VARYING_COLOR0, VARYING_COLOR1, VARYING_TEXCOORD0, VARYING_FOG,
        VARYING_COUNT, varyingForSemantic,
        OP, REGISTER: {
            TEMP: REG_TEMP, INPUT: REG_INPUT, CONST: REG_CONST, ADDR: REG_ADDR,
            TEXTURE: REG_TEXTURE, RASTOUT: REG_RASTOUT, ATTROUT: REG_ATTROUT,
            OUTPUT: REG_OUTPUT, CONSTINT: REG_CONSTINT, COLOROUT: REG_COLOROUT,
            DEPTHOUT: REG_DEPTHOUT, SAMPLER: REG_SAMPLER,
            CONSTBOOL: REG_CONSTBOOL, LOOP: REG_LOOP, MISCTYPE: REG_MISCTYPE,
            LABEL: REG_LABEL, PREDICATE: REG_PREDICATE,
        },
    };

    global.D3D9ShaderPipeline = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/glbridge/d3d9-webgpu/d3d9_shader_worker.js                                   0000644 0000000 0000000 00000001705 00000000000 021772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // M6 shader-bytecode translation worker. GPUShaderModule creation remains on
// the executor thread (WebGPU objects are device-owned), while parsing and
// WGSL generation happen here so a large effect set does not block input or
// presentation on its first load.

"use strict";

// The executor passes its cache-buster through to this worker. Mirroring it on
// the translator import keeps worker-generated WGSL in lockstep with the
// page's D3D9ShaderPipeline instead of silently reviving an older script.
importScripts("d3d9_shader_pipeline.js" + self.location.search);

self.onmessage = event => {
    const message = event.data || {};
    let result;
    try {
        result = self.D3D9ShaderPipeline.compileShader(
            new Uint32Array(message.tokens || []));
    } catch (error) {
        result = { ok: false,
            error: error && error.message ? error.message : String(error) };
    }
    self.postMessage({ id: message.id, result });
};
                                                           source/v64/src/browser/glbridge/d3d9-webgpu/ddraw_ops.js                                            0000644 0000000 0000000 00000170001 00000000000 020266  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // D9WG protocol 1.7: the DirectDraw opcode group (0x500), decoded on behalf of
// glbridge/ddrawproxy/ddraw.dll.
//
// This is a mixin over D3D9WebGPUExecutor rather than a second executor, for
// the same reason DirectDraw does not get a protocol of its own: a Direct3D 7
// device renders into a DirectDraw surface, and that surface is then blitted by
// DirectDraw and sampled as a texture by Direct3D, sometimes within one frame.
// Two resource tables would turn every one of those interactions into a
// cross-table copy that exists only because of how the host was factored.
//
// So surfaces are ordinary D9WG textures created by the 0x1xx opcodes, and only
// five things here are genuinely new:
//
//   * a blit that tests a colour key, mirrors, or fills;
//   * palettised surfaces kept as r8uint indices rather than expanded to RGBA;
//   * a palette that belongs to a surface rather than to the device;
//   * the display mode an exclusive-fullscreen title asked for.
//   * persistent overlay state composited non-destructively at present time.
//
// Flipping and clip lists are deliberately absent: a flip is a guest-side
// rotation followed by a blit into the swap-chain image, and a clip list is
// resolved guest-side into per-rectangle blits.

(function(global) {
    "use strict";

    const OP_DD_BLT = 0x500;
    const OP_DD_SET_COLOR_KEY = 0x501;
    const OP_DD_SET_SURFACE_PALETTE = 0x502;
    const OP_DD_SET_DISPLAY_MODE = 0x503;
    const OP_DD_UPDATE_OVERLAY = 0x504;

    const DDBLT_KEY_SOURCE = 1 << 0;
    const DDBLT_KEY_DESTINATION = 1 << 1;
    const DDBLT_MIRROR_X = 1 << 2;
    const DDBLT_MIRROR_Y = 1 << 3;
    const DDBLT_COLOR_FILL = 1 << 4;
    const DDBLT_DEPTH_FILL = 1 << 5;
    const DDBLT_FILTER_LINEAR = 1 << 6;

    const DDCKEY_SOURCE_BLT = 0;
    const DDCKEY_DESTINATION_BLT = 1;
    const DDCKEY_SOURCE_OVERLAY = 2;
    const DDCKEY_DESTINATION_OVERLAY = 3;

    const DDOVER_SHOW = 1 << 0;
    const DDOVER_HIDE = 1 << 1;
    const DDOVER_KEY_SOURCE = 1 << 2;
    const DDOVER_KEY_DESTINATION = 1 << 3;
    const DDOVER_MIRROR_X = 1 << 4;
    const DDOVER_MIRROR_Y = 1 << 5;
    const DDOVER_KEY_SOURCE_OVERRIDE = 1 << 6;
    const DDOVER_KEY_DESTINATION_OVERRIDE = 1 << 7;

    const DDSCL_NORMAL = 1 << 0;
    const DDSCL_EXCLUSIVE = 1 << 1;
    const DDSCL_FULLSCREEN = 1 << 2;

    const BUFFER_USAGE_UNIFORM = 0x40;
    const BUFFER_USAGE_COPY_DST = 0x8;
    const TEXTURE_USAGE_COPY_SRC = 0x01;
    const TEXTURE_USAGE_COPY_DST = 0x02;
    const TEXTURE_USAGE_TEXTURE_BINDING = 0x04;
    const TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;
    const SHADER_STAGE_VERTEX = 0x1;
    const SHADER_STAGE_FRAGMENT = 0x2;

    const PALETTE_ENTRIES = 256;
    const PALETTE_BYTES = PALETTE_ENTRIES * 16; // array<vec4<f32>, 256>
    const UNIFORM_BYTES = 128;                  // eight vec4s, see WGSL below

    // The blit uniform block, built once per op.
    //   0  source_rect  u, v, du, dv  (du/dv negative when mirrored)
    //  16  source_size   level width, level height
    //  32  key_low       r, g, b (or the palette index in .x)
    //  48  key_high
    //  64  fill          float fill colour
    //  80  fill_index    index fill
    //  96  destination key low
    // 112  destination key high
    function packUniforms(op) {
        const buffer = new ArrayBuffer(UNIFORM_BYTES);
        const floats = new Float32Array(buffer);
        const uints = new Uint32Array(buffer);
        floats[0] = op.sourceRect[0];
        floats[1] = op.sourceRect[1];
        floats[2] = op.sourceRect[2];
        floats[3] = op.sourceRect[3];
        floats[4] = op.sourceSize ? op.sourceSize[0] : 1;
        floats[5] = op.sourceSize ? op.sourceSize[1] : 1;
        const key = op.colorKey;
        uints[8] = key ? (key.low >>> 16) & 0xff : 0;
        uints[9] = key ? (key.low >>> 8) & 0xff : 0;
        uints[10] = key ? key.low & 0xff : 0;
        uints[11] = key ? key.low & 0xff : 0;
        uints[12] = key ? (key.high >>> 16) & 0xff : 0;
        uints[13] = key ? (key.high >>> 8) & 0xff : 0;
        uints[14] = key ? key.high & 0xff : 0;
        uints[15] = key ? key.high & 0xff : 0;
        // An indexed source compares the index itself, which the guest put in
        // the low byte of both ends.
        if (op.sourceKind === "index" && key) {
            uints[8] = key.low & 0xff;
            uints[12] = key.high & 0xff;
        }
        const fill = op.fill || [0, 0, 0, 0];
        floats[16] = fill[0];
        floats[17] = fill[1];
        floats[18] = fill[2];
        floats[19] = fill[3];
        uints[20] = op.fillIndex >>> 0;
        const destinationKey = op.destinationColorKey;
        uints[24] = destinationKey
            ? (destinationKey.low >>> 16) & 0xff : 0;
        uints[25] = destinationKey
            ? (destinationKey.low >>> 8) & 0xff : 0;
        uints[26] = destinationKey ? destinationKey.low & 0xff : 0;
        uints[27] = destinationKey ? destinationKey.low & 0xff : 0;
        uints[28] = destinationKey
            ? (destinationKey.high >>> 16) & 0xff : 0;
        uints[29] = destinationKey
            ? (destinationKey.high >>> 8) & 0xff : 0;
        uints[30] = destinationKey ? destinationKey.high & 0xff : 0;
        uints[31] = destinationKey ? destinationKey.high & 0xff : 0;
        if (op.destinationKind === "index" && destinationKey) {
            uints[24] = destinationKey.low & 0xff;
            uints[28] = destinationKey.high & 0xff;
        }
        return new Uint8Array(buffer);
    }

    function ddBlitShaderSource(variant) {
        const indexedSource = variant.sourceKind === "index";
        const noSource = variant.sourceKind === "none";
        const indexedDestination = variant.destinationKind === "index";
        const outputType = indexedDestination ? "vec4<u32>" : "vec4<f32>";
        const lines = [];
        lines.push(`struct D9DDBlitUniforms {
    source_rect: vec4<f32>,
    source_size: vec4<f32>,
    key_low: vec4<u32>,
    key_high: vec4<u32>,
    fill: vec4<f32>,
    fill_index: vec4<u32>,
    destination_key_low: vec4<u32>,
    destination_key_high: vec4<u32>,
};
@group(0) @binding(0) var<uniform> blit: D9DDBlitUniforms;`);
        if (!noSource) {
            lines.push(indexedSource
                ? "@group(0) @binding(1) var d9dd_source: texture_2d<u32>;"
                : "@group(0) @binding(1) var d9dd_source: texture_2d<f32>;");
            if (!indexedSource)
                lines.push("@group(0) @binding(2) var d9dd_sampler: sampler;");
        }
        if (variant.paletteResolve) {
            lines.push(`struct D9DDPalette {
    entries: array<vec4<f32>, ${PALETTE_ENTRIES}>,
};
@group(0) @binding(3) var<uniform> d9dd_palette: D9DDPalette;`);
        }
        if (variant.destinationKey) {
            lines.push(variant.destinationKind === "index"
                ? "@group(0) @binding(4) var d9dd_destination_key: texture_2d<u32>;"
                : "@group(0) @binding(4) var d9dd_destination_key: texture_2d<f32>;");
        }
        lines.push(`
struct D9DDBlitOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn d9dd_vs_main(@builtin(vertex_index) index: u32) -> D9DDBlitOutput {
    // Two triangles over the whole viewport; setViewport restricts the output
    // to the destination rectangle, so no destination maths belongs here.
    var corners = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));
    let corner = corners[index];
    var result: D9DDBlitOutput;
    result.position = vec4<f32>(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0,
        0.0, 1.0);
    // Mirroring is a negative extent in source_rect rather than a shader
    // variant of its own: DDBLTFX_MIRRORLEFTRIGHT/UPDOWN are exactly a
    // reversed traversal of the source rectangle.
    result.uv = blit.source_rect.xy + corner * blit.source_rect.zw;
    return result;
}`);
        const body = [];
        if (variant.destinationKey) {
            body.push("    let destination_texel = vec2<i32>(stage_in.position.xy);");
            if (indexedDestination) {
                body.push(`    let destination_index = textureLoad(
        d9dd_destination_key, destination_texel, 0).r;
    if (destination_index < blit.destination_key_low.x ||
            destination_index > blit.destination_key_high.x) {
        discard;
    }`);
            } else {
                body.push(`    let destination_color = textureLoad(
        d9dd_destination_key, destination_texel, 0);
    let destination_quantised = vec3<u32>(round(destination_color.rgb * 255.0));
    if (any(destination_quantised < blit.destination_key_low.rgb) ||
            any(destination_quantised > blit.destination_key_high.rgb)) {
        discard;
    }`);
            }
        }
        if (noSource) {
            body.push(indexedDestination
                ? "    return vec4<u32>(blit.fill_index.x, 0u, 0u, 0u);"
                : "    return blit.fill;");
        } else if (indexedSource) {
            body.push(`    let texel = vec2<i32>(clamp(
        floor(stage_in.uv * blit.source_size.xy), vec2<f32>(0.0, 0.0),
        max(blit.source_size.xy - vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 0.0))));
    let index = textureLoad(d9dd_source, texel, 0).r;`);
            if (variant.colorKey)
                body.push(`    if (index >= blit.key_low.x && index <= blit.key_high.x) {
        discard;
    }`);
            if (indexedDestination)
                body.push("    return vec4<u32>(index, 0u, 0u, 0u);");
            else if (variant.paletteResolve)
                body.push("    return d9dd_palette.entries[index];");
            else
                // No palette bound: the indices are all the host has, and
                // inventing colours for them would be a picture the app never
                // asked for. Grey ramp, and the guest is told through the
                // ddPaletteMissing counter.
                body.push("    let level = f32(index) / 255.0;\n" +
                    "    return vec4<f32>(level, level, level, 1.0);");
        } else {
            body.push("    let color = textureSample(d9dd_source, " +
                "d9dd_sampler, stage_in.uv);");
            if (variant.colorKey)
                // Quantised back to the 8-bit-per-channel domain the key lives
                // in. Both ends of the key were widened from the surface
                // format by the same truncating 255/max scale in the guest
                // (ddraw_expand_channel), and the upload widened the texels the
                // same way, so this comparison is exact rather than nearly so.
                body.push(`    let quantised = vec3<u32>(round(color.rgb * 255.0));
    if (all(quantised >= blit.key_low.rgb) &&
            all(quantised <= blit.key_high.rgb)) {
        discard;
    }`);
            body.push(indexedDestination
                ? "    return vec4<u32>(u32(round(color.r * 255.0)), 0u, 0u, 0u);"
                : "    return color;");
        }
        lines.push(`
@fragment
fn d9dd_ps_main(stage_in: D9DDBlitOutput) -> @location(0) ${outputType} {
${body.join("\n")}
}
`);
        return lines.join("\n");
    }

    const ddrawOps = {
        // ---- 0x500 DD_BLT ----------------------------------------------
        onDDBlt(bytes, view, offset, length) {
            if (length < 80) {
                ++this.stats.malformedBatches;
                return;
            }
            const state = this.deviceState(view.getUint32(offset, true));
            const sourceHandle = view.getUint32(offset + 4, true);
            const sourceLevel = view.getUint32(offset + 8, true);
            const sourceFace = view.getUint32(offset + 12, true);
            const sourceRect = {
                left: view.getInt32(offset + 16, true),
                top: view.getInt32(offset + 20, true),
                right: view.getInt32(offset + 24, true),
                bottom: view.getInt32(offset + 28, true),
            };
            const destinationHandle = view.getUint32(offset + 32, true);
            const destinationLevel = view.getUint32(offset + 36, true);
            const destinationFace = view.getUint32(offset + 40, true);
            const flags = view.getUint32(offset + 44, true);
            const destinationRect = {
                left: view.getInt32(offset + 48, true),
                top: view.getInt32(offset + 52, true),
                right: view.getInt32(offset + 56, true),
                bottom: view.getInt32(offset + 60, true),
            };
            const fillColor = view.getUint32(offset + 64, true);
            const fillDepth = view.getFloat32(offset + 68, true);

            this.stats.ddBlits = (this.stats.ddBlits || 0) + 1;

            const destination = destinationHandle
                ? this.resources.get(destinationHandle) : null;
            if (destinationHandle && (!destination || !destination.gpuTexture)) {
                this.ddRefuse("unknown-destination",
                    "a DirectDraw blit names a destination the host does not " +
                    "know; it is skipped rather than writing unrelated memory",
                    { destinationHandle });
                return;
            }
            const destinationWidth = destination
                ? Math.max(1, destination.width >> destinationLevel)
                : this.backBufferWidthOf(state);
            const destinationHeight = destination
                ? Math.max(1, destination.height >> destinationLevel)
                : this.backBufferHeightOf(state);
            const destinationColorKey =
                (flags & DDBLT_KEY_DESTINATION) && destination
                    ? (destination.ddColorKey &&
                        destination.ddColorKey[DDCKEY_DESTINATION_BLT])
                    : null;
            if ((flags & DDBLT_KEY_DESTINATION) && !destinationColorKey) {
                this.ddRefuse("key-destination-missing",
                    "a blit asked for the destination colour key but the " +
                    "destination surface has none attached",
                    { destinationHandle });
                return;
            }
            // A fill has no source rectangle at all, so it clips against the
            // destination alone; anything else has to move both rectangles
            // together or a partly off-screen sprite stretches instead of
            // being cut off.
            const isFill = (flags & (DDBLT_COLOR_FILL | DDBLT_DEPTH_FILL)) !== 0;
            const clipped = isFill
                ? clipDestination(destinationRect, destinationWidth,
                    destinationHeight)
                : clipRects(sourceRect, destinationRect, destinationWidth,
                    destinationHeight);
            if (!clipped) return;

            // A DDSCL_NORMAL primary is the guest desktop, but the WebGPU
            // canvas is a separate layer above v86's GDI canvas.  Remember
            // which part DirectDraw actually changed so the page can clip the
            // overlay to that region instead of covering the rest of the
            // desktop with the retained back buffer.  Splash screens such as
            // 3DMark 99/2000 update only their centred 420x170 rectangle.
            const noteWindowedScreenWrite = () => {
                if (destinationHandle || !state.ddClipPrimaryToWrites) return;
                const viewport = clipped.viewport;
                const next = {
                    left: viewport[0], top: viewport[1],
                    right: viewport[0] + viewport[2],
                    bottom: viewport[1] + viewport[3],
                    baseWidth: destinationWidth,
                    baseHeight: destinationHeight,
                };
                const old = state.ddScreenWriteRect;
                if (old) {
                    next.left = Math.min(next.left, old.left);
                    next.top = Math.min(next.top, old.top);
                    next.right = Math.max(next.right, old.right);
                    next.bottom = Math.max(next.bottom, old.bottom);
                }
                state.ddScreenWriteRect = next;
                const coversScreen = next.left <= 0 && next.top <= 0 &&
                    next.right >= destinationWidth &&
                    next.bottom >= destinationHeight;
                state.surface = { ...state.surface,
                    clipRect: coversScreen ? null : next };
            };

            if (flags & DDBLT_DEPTH_FILL) {
                if (!destination || !destination.isDepth ||
                        destinationLevel >= (destination.levelCount || 1)) {
                    this.ddRefuse("depth-fill-target",
                        "DDBLT_DEPTHFILL needs a valid depth-surface level; " +
                        "the request is skipped rather than clearing a " +
                        "colour target", { destinationHandle,
                            destinationLevel });
                    return;
                }
                const frame = this.ensureFrame();
                const viewport = clipped.viewport;
                frame.ops.push({
                    kind: "rect-clear",
                    targets: {
                        key: "dd-depth:" + destinationHandle + ":" +
                            destinationLevel + ":" + destinationFace,
                        colors: [], formats: [],
                        depthView: this.targetViewFor(destination,
                            destinationLevel, false, destinationFace),
                        width: destinationWidth, height: destinationHeight,
                        hasDepth: true,
                        sampleCount: destination.sampleCount || 1,
                    },
                    clearsColor: false, clearsDepth: true,
                    clearsStencil: false,
                    color: { r: 0, g: 0, b: 0, a: 0 },
                    depth: Math.max(0, Math.min(1, fillDepth)), stencil: 0,
                    rects: [{ left: viewport[0], top: viewport[1],
                        right: viewport[0] + viewport[2],
                        bottom: viewport[1] + viewport[3] }],
                });
                destination.frameReferenced = frame.serial;
                this.stats.ddDepthFills = (this.stats.ddDepthFills || 0) + 1;
                return;
            }

            const destinationIndexed = !!(destination && destination.ddIndexed);
            const destinationFormat = destination
                ? (destination.gpuFormat || "rgba8unorm") : this.format;
            const destinationView = destination
                ? this.targetViewFor(destination, destinationLevel, false,
                    Math.min(destinationFace,
                        (destination.layerCount || 1) - 1))
                : null;

            if (flags & DDBLT_COLOR_FILL) {
                noteWindowedScreenWrite();
                const frame = this.ensureFrame();
                frame.ops.push({
                    kind: "ddblit",
                    sourceKind: "none",
                    destinationKind: destinationIndexed ? "index" : "float",
                    destinationView, destinationFormat,
                    sourceRect: [0, 0, 1, 1],
                    viewport: clipped.viewport,
                    // A DirectDraw fill colour is in the destination surface's
                    // own format. The guest converts an RGB destination's fill
                    // to D3DCOLOR; an indexed one carries the raw index.
                    fill: destinationIndexed ? null : [
                        ((fillColor >>> 16) & 0xff) / 255,
                        ((fillColor >>> 8) & 0xff) / 255,
                        (fillColor & 0xff) / 255,
                        ((fillColor >>> 24) & 0xff) / 255,
                    ],
                    fillIndex: destinationIndexed ? (fillColor & 0xff) : 0,
                    destinationColorKey,
                    destinationTexture: destination
                        ? destination.gpuTexture : null,
                    destinationLevel,
                    destinationFace,
                    destinationSize: [destinationWidth, destinationHeight],
                });
                if (destination) destination.frameReferenced = frame.serial;
                this.markTextureSubresourceWritten(destination,
                    destinationLevel, destinationFace);
                this.stats.ddFills = (this.stats.ddFills || 0) + 1;
                if (destinationColorKey)
                    this.stats.ddBlitsDestinationKeyed =
                        (this.stats.ddBlitsDestinationKeyed || 0) + 1;
                return;
            }

            const source = sourceHandle ? this.resources.get(sourceHandle) : null;
            if (sourceHandle && (!source || !source.gpuTexture)) {
                this.ddRefuse("unknown-source",
                    "a DirectDraw blit names a source the host does not know; " +
                    "it is skipped rather than sampling unrelated memory",
                    { sourceHandle });
                return;
            }
            const sourceWidth = source
                ? Math.max(1, source.width >> sourceLevel)
                : this.backBufferWidthOf(state);
            const sourceHeight = source
                ? Math.max(1, source.height >> sourceLevel)
                : this.backBufferHeightOf(state);
            const sourceIndexed = !!(source && source.ddIndexed);
            const sourceFormat = source
                ? (source.gpuFormat || "rgba8unorm") : this.format;

            if (!sourceIndexed && destinationIndexed) {
                // Colour matching an RGB image into someone else's palette is
                // a different picture, not a slower one. Real DirectDraw
                // drivers refused this too.
                this.ddRefuse("rgb-into-indexed",
                    "a blit from a true-colour surface into a palettised one " +
                    "would have to choose palette indices for colours the " +
                    "palette may not contain; it is refused rather than " +
                    "approximated");
                return;
            }

            const colorKey = (flags & DDBLT_KEY_SOURCE) && source
                ? (source.ddColorKey && source.ddColorKey[DDCKEY_SOURCE_BLT])
                : null;
            if ((flags & DDBLT_KEY_SOURCE) && !colorKey) {
                // DDBLT_KEYSRC with no key attached is an app error DirectDraw
                // answers with DDERR_NOCOLORKEY. Blitting opaquely instead
                // would paint a rectangle over the background.
                this.ddRefuse("key-source-missing",
                    "a blit asked for the source colour key but the surface " +
                    "has none attached", { sourceHandle });
                return;
            }

            const mirrorX = (flags & DDBLT_MIRROR_X) !== 0;
            const mirrorY = (flags & DDBLT_MIRROR_Y) !== 0;
            const src = clipped.source;
            if (src.left < 0 || src.top < 0 || src.right > sourceWidth ||
                    src.bottom > sourceHeight) {
                this.ddRefuse("source-out-of-bounds",
                    "a DirectDraw blit reads outside its source surface, " +
                    "which DirectDraw answers with DDERR_INVALIDRECT",
                    { sourceHandle, sourceWidth, sourceHeight });
                return;
            }
            const width = src.right - src.left;
            const height = src.bottom - src.top;
            const selfBlt = !!(source && destination &&
                source.gpuTexture === destination.gpuTexture &&
                sourceLevel === destinationLevel &&
                sourceFace === destinationFace);

            // The straight copy: nothing to key, nothing to mirror, no scale,
            // no format change, and two real textures. copyTextureToTexture is
            // both cheaper and exact, and it works for r8uint where a render
            // pass would need a pipeline.
            const scaled = width !== clipped.viewport[2] ||
                height !== clipped.viewport[3];
            if (!colorKey && !destinationColorKey && !mirrorX && !mirrorY &&
                    !scaled && source && !selfBlt &&
                    destination && sourceFormat === destinationFormat) {
                const frame = this.ensureFrame();
                frame.ops.push({ kind: "copy",
                    source: { texture: source.gpuTexture,
                        mipLevel: sourceLevel,
                        origin: { x: src.left, y: src.top, z: sourceFace } },
                    destination: { texture: destination.gpuTexture,
                        mipLevel: destinationLevel,
                        origin: { x: clipped.viewport[0],
                            y: clipped.viewport[1], z: destinationFace } },
                    size: { width, height, depthOrArrayLayers: 1 } });
                source.frameReferenced = frame.serial;
                destination.frameReferenced = frame.serial;
                this.markTextureSubresourceWritten(destination,
                    destinationLevel, destinationFace);
                this.stats.ddBlitsCopied = (this.stats.ddBlitsCopied || 0) + 1;
                return;
            }

            let paletteBuffer = null;
            if (sourceIndexed && !destinationIndexed) {
                paletteBuffer = this.ddPaletteBufferFor(source);
                if (!paletteBuffer)
                    this.stats.ddPaletteMissing =
                        (this.stats.ddPaletteMissing || 0) + 1;
            }

            const u0 = src.left / sourceWidth;
            const v0 = src.top / sourceHeight;
            const du = width / sourceWidth;
            const dv = height / sourceHeight;
            const frame = this.ensureFrame();
            noteWindowedScreenWrite();
            frame.ops.push({
                kind: "ddblit",
                sourceKind: sourceIndexed ? "index" : "float",
                destinationKind: destinationIndexed ? "index" : "float",
                sourceView: source
                    ? this.blitSourceView(source, sourceLevel, sourceFace)
                    : null,
                sourceTexture: source ? source.gpuTexture : null,
                sourceLevel,
                sourceFace,
                sourceSnapshot: selfBlt,
                destinationView, destinationFormat, sourceFormat,
                sourceRect: [
                    mirrorX ? u0 + du : u0, mirrorY ? v0 + dv : v0,
                    mirrorX ? -du : du, mirrorY ? -dv : dv,
                ],
                sourceSize: [sourceWidth, sourceHeight],
                viewport: clipped.viewport,
                colorKey: colorKey || null,
                destinationColorKey,
                destinationTexture: destination
                    ? destination.gpuTexture : null,
                destinationLevel,
                destinationFace,
                destinationSize: [destinationWidth, destinationHeight],
                paletteBuffer,
                paletteResolve: !!paletteBuffer,
                filterPoint: !(flags & DDBLT_FILTER_LINEAR) || sourceIndexed,
            });
            if (source) source.frameReferenced = frame.serial;
            if (destination) destination.frameReferenced = frame.serial;
            this.markTextureSubresourceWritten(destination, destinationLevel,
                destinationFace);
            if (colorKey)
                this.stats.ddBlitsColorKeyed =
                    (this.stats.ddBlitsColorKeyed || 0) + 1;
            if (destinationColorKey)
                this.stats.ddBlitsDestinationKeyed =
                    (this.stats.ddBlitsDestinationKeyed || 0) + 1;
            if (mirrorX || mirrorY)
                this.stats.ddBlitsMirrored =
                    (this.stats.ddBlitsMirrored || 0) + 1;
        },

        // ---- 0x501 DD_SET_COLOR_KEY ------------------------------------
        onDDSetColorKey(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            const kind = view.getUint32(offset + 4, true);
            const low = view.getUint32(offset + 8, true);
            const high = view.getUint32(offset + 12, true);
            const present = view.getUint32(offset + 16, true) !== 0;
            const resource = this.resources.get(handle);
            if (!resource) return;
            if (!resource.ddColorKey) resource.ddColorKey = {};
            if (present) resource.ddColorKey[kind] = { low, high };
            else delete resource.ddColorKey[kind];
            this.stats.ddColorKeysSet = (this.stats.ddColorKeysSet || 0) + 1;
        },

        // ---- 0x502 DD_SET_SURFACE_PALETTE ------------------------------
        onDDSetSurfacePalette(bytes, view, offset) {
            const handle = view.getUint32(offset, true);
            const paletteIndex = view.getUint32(offset + 4, true);
            const resource = this.resources.get(handle);
            if (!resource) return;
            resource.ddPaletteIndex = paletteIndex;
            // The bound palette may already have data; drop any GPU copy built
            // from the previous binding.
            resource.ddPaletteSerial = -1;
            this.stats.ddSurfacePalettes =
                (this.stats.ddSurfacePalettes || 0) + 1;
        },

        // ---- 0x503 DD_SET_DISPLAY_MODE ---------------------------------
        onDDSetDisplayMode(bytes, view, offset) {
            const state = this.deviceState(view.getUint32(offset, true));
            const width = view.getUint32(offset + 4, true);
            const height = view.getUint32(offset + 8, true);
            const bitsPerPixel = view.getUint32(offset + 12, true);
            const refreshRate = view.getUint32(offset + 16, true);
            const cooperativeFlags = view.getUint32(offset + 20, true);
            const guestModeChanged = view.getUint32(offset + 24, true) !== 0;
            state.ddDisplayMode = { width, height, bitsPerPixel, refreshRate,
                cooperativeFlags, guestModeChanged };
            const exclusiveFullscreen =
                (cooperativeFlags & DDSCL_EXCLUSIVE) !== 0 &&
                (cooperativeFlags & DDSCL_FULLSCREEN) !== 0;
            state.ddClipPrimaryToWrites =
                (cooperativeFlags & DDSCL_NORMAL) !== 0 &&
                !exclusiveFullscreen;
            state.ddScreenWriteRect = null;
            if (width && height) {
                const backBufferSizeChanged =
                    state.backBufferWidth !== width ||
                    state.backBufferHeight !== height;
                if (backBufferSizeChanged) {
                    // DirectDraw creates the executor device as soon as the
                    // cooperative level is set, while the window can still
                    // have a transient client size (dxdiag: 106x2).  The real
                    // primary/flip-chain size arrives only here.  Leaving the
                    // implicit target at the creation size makes a 640x480
                    // SCREEN_BLT clip to the top-left 106x2 -- a black strip
                    // which the page then stretches over the whole overlay.
                    //
                    // A mode switch invalidates the old primary contents.  Do
                    // not let recorded ops or a retained texture with the old
                    // dimensions survive into the first Present of this mode.
                    this.discardFrame();
                    this.retireActiveSessionBackBuffer();
                    state.backBufferWidth = width;
                    state.backBufferHeight = height;
                    if ((state.sampleCount || 1) > 1) {
                        this.configureBackBufferMSAA(state, width, height,
                            state.multisampleType, state.multisampleQuality);
                    }
                }
                state.surface = { ...state.surface, width, height,
                    // A DDSCL_NORMAL primary is the desktop, not the HWND's
                    // client area. Present will still report that client's
                    // rectangle, so retain the desktop geometry separately for
                    // the page compositor and use the client-independent dirty
                    // rectangle only as a visibility mask.
                    ddDesktopPrimary: state.ddClipPrimaryToWrites,
                    displayWidth: state.ddClipPrimaryToWrites ? width : 0,
                    displayHeight: state.ddClipPrimaryToWrites ? height : 0,
                    clipRect: null,
                    // Only a mode the guest really switched to puts the window
                    // at the origin covering the emulated screen. When
                    // ChangeDisplaySettings failed the guest keeps a window of
                    // this size instead, and the overlay has to stay where that
                    // window is or the pointer stops matching the picture.
                    ...(exclusiveFullscreen && guestModeChanged
                        ? { x: 0, y: 0 } : {}),
                    fullscreen: exclusiveFullscreen };
                this.notifySurface(state, "display-mode");
            }
            this.stats.ddDisplayModes = (this.stats.ddDisplayModes || 0) + 1;
        },

        // ---- 0x504 DD_UPDATE_OVERLAY ----------------------------------
        onDDUpdateOverlay(bytes, view, offset, length) {
            if (length < 52) {
                ++this.stats.malformedBatches;
                return;
            }
            const surfaceHandle = view.getUint32(offset, true);
            const overlayId = view.getUint32(offset + 4, true);
            const resource = this.resources.get(surfaceHandle);
            if (!resource) return;
            const state = this.deviceState(resource.deviceHandle || 0);
            if (!state.ddOverlays) state.ddOverlays = new Map();
            const flags = view.getUint32(offset + 40, true);
            const destinationHandle = view.getUint32(offset + 48, true);
            const old = state.ddOverlays.get(overlayId) || {};
            if (flags & DDOVER_HIDE) {
                state.ddOverlays.delete(overlayId);
                this.stats.ddOverlayUpdates =
                    (this.stats.ddOverlayUpdates || 0) + 1;
                return;
            }
            const sourceKey = resource.ddColorKey &&
                resource.ddColorKey[DDCKEY_SOURCE_OVERLAY];
            const destination = destinationHandle
                ? this.resources.get(destinationHandle) : null;
            const destinationKey = destination && destination.ddColorKey &&
                destination.ddColorKey[DDCKEY_DESTINATION_OVERLAY];
            const entry = {
                ...old,
                overlayId,
                surfaceHandle,
                destinationHandle,
                sourceRect: [
                    view.getInt32(offset + 8, true),
                    view.getInt32(offset + 12, true),
                    view.getInt32(offset + 16, true),
                    view.getInt32(offset + 20, true),
                ],
                destinationRect: [
                    view.getInt32(offset + 24, true),
                    view.getInt32(offset + 28, true),
                    view.getInt32(offset + 32, true),
                    view.getInt32(offset + 36, true),
                ],
                flags,
                zOrder: view.getUint32(offset + 44, true),
                visible: (flags & DDOVER_SHOW) ? true : !!old.visible,
                // Snapshot the key at UpdateOverlay time. DuplicateSurface
                // aliases share one texture handle but have independent COM
                // key state; the guest deliberately rebinds the right alias
                // immediately before this command.
                sourceColorKey: (flags & DDOVER_KEY_SOURCE) && sourceKey
                    ? { ...sourceKey } : null,
                destinationColorKey:
                    (flags & DDOVER_KEY_DESTINATION) && destinationKey
                        ? { ...destinationKey } : null,
            };
            state.ddOverlays.set(overlayId, entry);
            this.stats.ddOverlayUpdates =
                (this.stats.ddOverlayUpdates || 0) + 1;
        },

        /* Build a disposable scanout image instead of drawing overlays into
         * the retained D3D back buffer. Hiding or moving one therefore exposes
         * the untouched primary immediately, and readback never sees scanout-
         * only overlay pixels. */
        replayDDOverlays(encoder, state, sourceTexture, width, height, frame) {
            if (!state || !state.ddOverlays) return null;
            const overlays = [...state.ddOverlays.values()]
                .filter(entry => entry.visible)
                .sort((a, b) => a.zOrder - b.zOrder);
            if (!overlays.length) return null;
            const composite = this.device.createTexture({
                label: "DirectDraw overlay composite",
                size: { width, height, depthOrArrayLayers: 1 },
                format: this.format,
                mipLevelCount: 1,
                usage: TEXTURE_USAGE_COPY_SRC | TEXTURE_USAGE_COPY_DST |
                    TEXTURE_USAGE_TEXTURE_BINDING |
                    TEXTURE_USAGE_RENDER_ATTACHMENT,
            });
            encoder.copyTextureToTexture({ texture: sourceTexture },
                { texture: composite },
                { width, height, depthOrArrayLayers: 1 });
            const compositeView = composite.createView();

            for (const overlay of overlays) {
                const source = this.resources.get(overlay.surfaceHandle);
                if (!source || !source.gpuTexture) continue;
                const sourceWidth = source.width;
                const sourceHeight = source.height;
                const sourceRect = {
                    left: overlay.sourceRect[0], top: overlay.sourceRect[1],
                    right: overlay.sourceRect[2], bottom: overlay.sourceRect[3],
                };
                const destinationRect = {
                    left: overlay.destinationRect[0],
                    top: overlay.destinationRect[1],
                    right: overlay.destinationRect[2],
                    bottom: overlay.destinationRect[3],
                };
                const clipped = clipRects(sourceRect, destinationRect,
                    width, height);
                if (!clipped) continue;
                const sourceIndexed = !!source.ddIndexed;
                const sourceColorKey = (overlay.flags & DDOVER_KEY_SOURCE)
                    ? overlay.sourceColorKey : null;
                const destinationColorKey =
                    (overlay.flags & DDOVER_KEY_DESTINATION)
                        ? overlay.destinationColorKey : null;
                if ((overlay.flags & DDOVER_KEY_SOURCE) && !sourceColorKey)
                    continue;
                if ((overlay.flags & DDOVER_KEY_DESTINATION) &&
                        !destinationColorKey)
                    continue;
                let paletteBuffer = null;
                if (sourceIndexed) paletteBuffer = this.ddPaletteBufferFor(source);
                const src = clipped.source;
                const sourceU = src.left / sourceWidth;
                const sourceV = src.top / sourceHeight;
                const sourceDU = (src.right - src.left) / sourceWidth;
                const sourceDV = (src.bottom - src.top) / sourceHeight;
                const transient = this.replayDDBlit(encoder, {
                    sourceKind: sourceIndexed ? "index" : "float",
                    destinationKind: "float",
                    sourceView: this.blitSourceView(source, 0, 0),
                    destinationView: compositeView,
                    destinationFormat: this.format,
                    sourceFormat: source.gpuFormat || "rgba8unorm",
                    sourceRect: [
                        (overlay.flags & DDOVER_MIRROR_X)
                            ? sourceU + sourceDU : sourceU,
                        (overlay.flags & DDOVER_MIRROR_Y)
                            ? sourceV + sourceDV : sourceV,
                        (overlay.flags & DDOVER_MIRROR_X)
                            ? -sourceDU : sourceDU,
                        (overlay.flags & DDOVER_MIRROR_Y)
                            ? -sourceDV : sourceDV,
                    ],
                    sourceSize: [sourceWidth, sourceHeight],
                    viewport: clipped.viewport,
                    colorKey: sourceColorKey,
                    destinationColorKey,
                    destinationTexture: sourceTexture,
                    destinationLevel: 0,
                    destinationFace: 0,
                    destinationSize: [width, height],
                    paletteBuffer,
                    paletteResolve: !!paletteBuffer,
                    filterPoint: sourceIndexed,
                }, compositeView, composite);
                if (transient) frame.transientBuffers.push(transient);
                this.stats.ddOverlayComposites =
                    (this.stats.ddOverlayComposites || 0) + 1;
            }
            return composite;
        },

        // ---- helpers ---------------------------------------------------
        ddRefuse(key, message, details) {
            this.stats.ddBlitsSkipped = (this.stats.ddBlitsSkipped || 0) + 1;
            this.warnOnce("ddraw-" + key, message, details || {});
        },

        // The GPU copy of the palette a surface samples through, or null when
        // the guest has not sent one yet.
        ddPaletteBufferFor(resource) {
            const index = resource.ddPaletteIndex;
            if (index === undefined) return null;
            const key = (resource.deviceHandle || 0) + ":" + index;
            const rgba = this.palettes && this.palettes.get(key);
            if (!rgba) return null;
            if (!this.ddPaletteBuffers) this.ddPaletteBuffers = new Map();
            let entry = this.ddPaletteBuffers.get(key);
            if (!entry) {
                entry = {
                    buffer: this.device.createBuffer({
                        label: "DirectDraw palette " + key,
                        size: PALETTE_BYTES,
                        usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
                    }),
                    serial: -1,
                };
                this.ddPaletteBuffers.set(key, entry);
            }
            const serial = (this.ddPaletteSerials &&
                this.ddPaletteSerials.get(key)) || 0;
            if (entry.serial !== serial) {
                const floats = new Float32Array(PALETTE_ENTRIES * 4);
                for (let i = 0; i < PALETTE_ENTRIES; ++i) {
                    floats[i * 4] = rgba[i * 4] / 255;
                    floats[i * 4 + 1] = rgba[i * 4 + 1] / 255;
                    floats[i * 4 + 2] = rgba[i * 4 + 2] / 255;
                    floats[i * 4 + 3] = rgba[i * 4 + 3] / 255;
                }
                this.device.queue.writeBuffer(entry.buffer, 0, floats);
                entry.serial = serial;
                this.stats.ddPaletteUploads =
                    (this.stats.ddPaletteUploads || 0) + 1;
            }
            return entry.buffer;
        },

        // DirectDraw keeps P8 surfaces as r8uint so blits and readback preserve
        // the application's indices.  Fixed-function D3D sampling, however,
        // needs filterable colours. Build a companion RGBA texture from the
        // CPU index shadows and the palette attached to this *surface* (not the
        // device-global D3D9 palette). A keyed companion sets alpha to zero by
        // comparing the original index, so duplicate palette colours cannot
        // make an unrelated texel transparent.
        ddIndexedSampleViewFor(resource, colorKey) {
            if (!resource || !resource.ddIndexed) return null;
            const paletteIndex = resource.ddPaletteIndex;
            const paletteKey = paletteIndex === undefined ? null
                : (resource.deviceHandle || 0) + ":" + paletteIndex;
            const palette = paletteKey && this.palettes
                ? this.palettes.get(paletteKey) : null;
            const paletteSerial = paletteKey && this.ddPaletteSerials
                ? (this.ddPaletteSerials.get(paletteKey) || 0) : 0;
            const keyLow = colorKey ? colorKey.low & 0xff : -1;
            const keyHigh = colorKey ? colorKey.high & 0xff : -1;
            const variant = colorKey ? "keyed" : "plain";
            const serial = [resource.ddContentSerial || 0, paletteKey || "-",
                paletteSerial, keyLow, keyHigh].join(":");
            if (!resource.ddSampleViews) resource.ddSampleViews = new Map();
            const old = resource.ddSampleViews.get(variant);
            if (old && old.serial === serial) return old.view;

            const layers = resource.layerCount || 1;
            const texture = this.device.createTexture({
                label: "DirectDraw indexed D3D sample view",
                size: { width: resource.width, height: resource.height,
                    depthOrArrayLayers: layers },
                format: "rgba8unorm",
                mipLevelCount: Math.max(1, resource.levelCount || 1),
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            for (const shadow of resource.textureShadows
                    ? resource.textureShadows.values() : []) {
                const rgba = new Uint8Array(shadow.width * shadow.height * 4);
                for (let pixel = 0; pixel < shadow.width * shadow.height;
                        ++pixel) {
                    const index = shadow.data[pixel];
                    const at = pixel * 4;
                    if (palette) {
                        rgba[at] = palette[index * 4];
                        rgba[at + 1] = palette[index * 4 + 1];
                        rgba[at + 2] = palette[index * 4 + 2];
                        rgba[at + 3] = palette[index * 4 + 3];
                    } else {
                        rgba[at] = rgba[at + 1] = rgba[at + 2] = index;
                        rgba[at + 3] = 0xff;
                    }
                    if (colorKey && index >= keyLow && index <= keyHigh)
                        rgba[at + 3] = 0;
                }
                this.device.queue.writeTexture({ texture,
                    mipLevel: shadow.level,
                    origin: { x: 0, y: 0, z: shadow.layer || 0 } }, rgba,
                    { bytesPerRow: shadow.width * 4,
                        rowsPerImage: shadow.height },
                    { width: shadow.width, height: shadow.height,
                        depthOrArrayLayers: 1 });
            }
            const entry = { texture, serial, view: texture.createView({
                dimension: resource.textureType === "cube" ? "cube" : "2d",
            }) };
            resource.ddSampleViews.set(variant, entry);
            if (old) this.retireGPUObject(old.texture);
            this.stats.ddIndexedSampleResolves =
                (this.stats.ddIndexedSampleResolves || 0) + 1;
            return entry.view;
        },

        ddBlitPipelineFor(variant) {
            const key = [variant.destinationFormat, variant.sourceKind,
                variant.destinationKind, variant.colorKey ? "key" : "-",
                variant.destinationKey ? "dest-key" : "-",
                variant.paletteResolve ? "pal" : "-",
                variant.filterPoint ? "point" : "linear"].join("|");
            if (!this.ddBlitPipelines) this.ddBlitPipelines = new Map();
            let entry = this.ddBlitPipelines.get(key);
            if (entry) return entry;
            const module = this.moduleFor(ddBlitShaderSource(variant),
                "ddraw blit " + key);
            const entries = [
                { binding: 0, visibility: SHADER_STAGE_VERTEX |
                    SHADER_STAGE_FRAGMENT, buffer: { type: "uniform" } },
            ];
            if (variant.sourceKind === "index")
                entries.push({ binding: 1, visibility: SHADER_STAGE_FRAGMENT,
                    texture: { sampleType: "uint" } });
            else if (variant.sourceKind === "float") {
                entries.push({ binding: 1, visibility: SHADER_STAGE_FRAGMENT,
                    texture: { sampleType: "float" } });
                entries.push({ binding: 2, visibility: SHADER_STAGE_FRAGMENT,
                    sampler: { type: "filtering" } });
            }
            if (variant.paletteResolve)
                entries.push({ binding: 3, visibility: SHADER_STAGE_FRAGMENT,
                    buffer: { type: "uniform" } });
            if (variant.destinationKey)
                entries.push({ binding: 4, visibility: SHADER_STAGE_FRAGMENT,
                    texture: { sampleType: variant.destinationKind === "index"
                        ? "uint" : "float" } });
            const bindGroupLayout =
                this.device.createBindGroupLayout({ entries });
            const pipeline = this.device.createRenderPipeline({
                label: "DirectDraw blit " + key,
                layout: this.device.createPipelineLayout(
                    { bindGroupLayouts: [bindGroupLayout] }),
                vertex: { module, entryPoint: "d9dd_vs_main" },
                fragment: { module, entryPoint: "d9dd_ps_main",
                    targets: [{ format: variant.destinationFormat }] },
                primitive: { topology: "triangle-list" },
            });
            const sampler = variant.sourceKind === "float"
                ? this.device.createSampler({
                    magFilter: variant.filterPoint ? "nearest" : "linear",
                    minFilter: variant.filterPoint ? "nearest" : "linear",
                    addressModeU: "clamp-to-edge",
                    addressModeV: "clamp-to-edge",
                })
                : null;
            entry = { pipeline, bindGroupLayout, sampler };
            this.ddBlitPipelines.set(key, entry);
            return entry;
        },

        // Runs a recorded DirectDraw blit inside finishFrame, where the swap
        // chain view exists.
        replayDDBlit(encoder, op, swapView, swapTexture) {
            const destinationView = op.destinationView || swapView;
            if (!destinationView) return null;
            // A swap-chain source is whatever the canvas format is, never an
            // index texture, and the variant has to say so or the pipeline
            // declares a texture_2d<u32> for a float view.
            const swapchainSource = op.sourceKind !== "none" && !op.sourceView;
            const variant = {
                // The swap-chain image is whatever the canvas format is and is
                // never an index texture, so a blit that reads it is a float
                // blit no matter what the recorded kind said.
                sourceKind: swapchainSource ? "float" : op.sourceKind,
                destinationKind: op.destinationView
                    ? op.destinationKind : "float",
                destinationFormat: op.destinationView
                    ? op.destinationFormat : this.format,
                colorKey: !!op.colorKey,
                destinationKey: !!op.destinationColorKey,
                paletteResolve: !!op.paletteBuffer,
                filterPoint: !!op.filterPoint,
            };
            let snapshotTexture = null;
            let snapshotView = null;
            let destinationKeyView = null;
            if (variant.destinationKey || op.sourceSnapshot) {
                const snapshotSource = variant.destinationKey
                    ? (op.destinationTexture || swapTexture)
                    : op.sourceTexture;
                const size = variant.destinationKey
                    ? (op.destinationSize || [1, 1])
                    : (op.sourceSize || [1, 1]);
                if (!snapshotSource || !size[0] || !size[1]) return null;
                snapshotTexture = this.device.createTexture({
                    label: variant.destinationKey
                        ? "DirectDraw destination colour-key snapshot"
                        : "DirectDraw self-blit snapshot",
                    size: { width: size[0], height: size[1],
                        depthOrArrayLayers: 1 },
                    format: variant.destinationKey
                        ? variant.destinationFormat : op.sourceFormat,
                    mipLevelCount: 1,
                    usage: TEXTURE_USAGE_COPY_DST |
                        TEXTURE_USAGE_TEXTURE_BINDING,
                });
                encoder.copyTextureToTexture({ texture: snapshotSource,
                    mipLevel: variant.destinationKey
                        ? (op.destinationLevel || 0) : (op.sourceLevel || 0),
                    origin: { x: 0, y: 0,
                        z: variant.destinationKey
                            ? (op.destinationFace || 0) : (op.sourceFace || 0) } },
                    { texture: snapshotTexture },
                    { width: size[0], height: size[1],
                        depthOrArrayLayers: 1 });
                snapshotView = snapshotTexture.createView();
                if (variant.destinationKey) destinationKeyView = snapshotView;
            }
            const sourceView = op.sourceKind === "none" ? null
                : (op.sourceSnapshot ? snapshotView : (op.sourceView || swapView));
            if (op.sourceKind !== "none" && !sourceView) return null;
            const entry = this.ddBlitPipelineFor(variant);
            const uniform = this.device.createBuffer({
                size: UNIFORM_BYTES,
                usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(uniform, 0, packUniforms(op));
            const entries = [{ binding: 0, resource: { buffer: uniform } }];
            if (variant.sourceKind !== "none") {
                entries.push({ binding: 1, resource: sourceView });
                if (variant.sourceKind === "float")
                    entries.push({ binding: 2, resource: entry.sampler });
            }
            if (variant.paletteResolve)
                entries.push({ binding: 3,
                    resource: { buffer: op.paletteBuffer } });
            if (variant.destinationKey)
                entries.push({ binding: 4, resource: destinationKeyView });
            const bindGroup = this.device.createBindGroup({
                layout: entry.bindGroupLayout, entries });
            const pass = encoder.beginRenderPass({
                colorAttachments: [{ view: destinationView,
                    loadOp: "load", storeOp: "store" }],
            });
            ++this.stats.renderPasses;
            pass.setPipeline(entry.pipeline);
            pass.setBindGroup(0, bindGroup);
            pass.setViewport(op.viewport[0], op.viewport[1], op.viewport[2],
                op.viewport[3], 0, 1);
            pass.draw(6);
            pass.end();
            if (!snapshotTexture) return uniform;
            return { destroy() {
                uniform.destroy();
                snapshotTexture.destroy();
            } };
        },
    };

    // A destination rectangle is clipped to the surface; the source rectangle
    // follows it proportionally, which is what makes a sprite that runs off the
    // edge of the screen show its left half rather than its whole self squeezed
    // into the space that was left.
    function clipRects(source, destination, width, height) {
        const destinationWidth = destination.right - destination.left;
        const destinationHeight = destination.bottom - destination.top;
        const sourceWidth = source.right - source.left;
        const sourceHeight = source.bottom - source.top;
        if (destinationWidth <= 0 || destinationHeight <= 0 ||
                sourceWidth <= 0 || sourceHeight <= 0)
            return null;
        const scaleX = sourceWidth / destinationWidth;
        const scaleY = sourceHeight / destinationHeight;
        const left = Math.max(0, destination.left);
        const top = Math.max(0, destination.top);
        const right = Math.min(width, destination.right);
        const bottom = Math.min(height, destination.bottom);
        if (right <= left || bottom <= top) return null;
        return {
            viewport: [left, top, right - left, bottom - top],
            source: {
                left: source.left + Math.round((left - destination.left) * scaleX),
                top: source.top + Math.round((top - destination.top) * scaleY),
                right: source.right -
                    Math.round((destination.right - right) * scaleX),
                bottom: source.bottom -
                    Math.round((destination.bottom - bottom) * scaleY),
            },
        };
    }

    function clipDestination(destination, width, height) {
        const left = Math.max(0, destination.left);
        const top = Math.max(0, destination.top);
        const right = Math.min(width, destination.right);
        const bottom = Math.min(height, destination.bottom);
        if (right <= left || bottom <= top) return null;
        return { viewport: [left, top, right - left, bottom - top],
            source: { left: 0, top: 0, right: 0, bottom: 0 } };
    }

    function installDDrawOps(ExecutorClass) {
        if (!ExecutorClass || ExecutorClass._ddrawOpsInstalled) return;
        Object.assign(ExecutorClass.prototype, ddrawOps);

        // A palette slot's contents change under SET_PALETTE, which belongs to
        // the D3D9 command set. Wrapping it here keeps that file free of
        // DirectDraw concerns while still invalidating the GPU copies built
        // from it -- palette animation is per-frame in this era, so a stale
        // copy is not an edge case.
        const previousSetPalette = ExecutorClass.prototype.onSetPalette;
        ExecutorClass.prototype.onSetPalette = function(bytes, view, offset,
                length, metadata) {
            const result = previousSetPalette.call(this, bytes, view, offset,
                length, metadata);
            const key = view.getUint32(offset, true) + ":" +
                view.getUint32(offset + 4, true);
            if (!this.ddPaletteSerials) this.ddPaletteSerials = new Map();
            this.ddPaletteSerials.set(key,
                (this.ddPaletteSerials.get(key) || 0) + 1);
            return result;
        };

        const previousDestroyResource = ExecutorClass.prototype.onDestroyResource;
        ExecutorClass.prototype.onDestroyResource = function(bytes, view,
                offset, length, metadata) {
            const destroyedHandle = view.getUint32(offset, true);
            const resource = this.resources && this.resources.get(
                destroyedHandle);
            if (resource && resource.ddSampleViews) {
                for (const entry of resource.ddSampleViews.values())
                    this.retireGPUObject(entry.texture);
                resource.ddSampleViews.clear();
            }
            if (this.devices) {
                for (const state of this.devices.values()) {
                    if (!state.ddOverlays) continue;
                    for (const [handle, overlay] of state.ddOverlays) {
                        if (overlay.surfaceHandle === destroyedHandle ||
                                overlay.destinationHandle === destroyedHandle)
                            state.ddOverlays.delete(handle);
                    }
                }
            }
            return previousDestroyResource.call(this, bytes, view, offset,
                length, metadata);
        };

        ExecutorClass.extensionHandlers = Object.assign(
            ExecutorClass.extensionHandlers || {}, {
                [OP_DD_BLT]: ddrawOps.onDDBlt,
                [OP_DD_SET_COLOR_KEY]: ddrawOps.onDDSetColorKey,
                [OP_DD_SET_SURFACE_PALETTE]: ddrawOps.onDDSetSurfacePalette,
                [OP_DD_SET_DISPLAY_MODE]: ddrawOps.onDDSetDisplayMode,
                [OP_DD_UPDATE_OVERLAY]: ddrawOps.onDDUpdateOverlay,
            });
        ExecutorClass._ddrawOpsInstalled = true;
    }

    global.installDDrawOps = installDDrawOps;
    if (global.D3D9WebGPUExecutor) installDDrawOps(global.D3D9WebGPUExecutor);

    if (typeof module !== "undefined" && module.exports) {
        module.exports = {
            installDDrawOps, ddBlitShaderSource, clipRects, clipDestination,
            OP_DD_BLT, OP_DD_SET_COLOR_KEY, OP_DD_SET_SURFACE_PALETTE,
            OP_DD_SET_DISPLAY_MODE, OP_DD_UPDATE_OVERLAY,
            DDBLT_KEY_SOURCE, DDBLT_KEY_DESTINATION, DDBLT_MIRROR_X,
            DDBLT_MIRROR_Y, DDBLT_COLOR_FILL, DDBLT_DEPTH_FILL,
            DDBLT_FILTER_LINEAR,
            DDOVER_SHOW, DDOVER_HIDE, DDOVER_KEY_SOURCE,
            DDOVER_KEY_DESTINATION, DDOVER_MIRROR_X, DDOVER_MIRROR_Y,
            DDOVER_KEY_SOURCE_OVERRIDE, DDOVER_KEY_DESTINATION_OVERRIDE,
        };
    }
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/glbridge/gl-webgpu/COVERAGE.md                                               0000644 0000000 0000000 00000030244 00000000000 017326  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # OpenGL entry-point coverage

Generated by `node tools/gen_gl_coverage.cjs`. Do not hand-edit:
the opcode set comes from the guest DLL, the handler set from the
executor's real dispatch table, and only the approximation list inside
the generator is maintained by hand.

Classes follow section 2.3 of the implementation plan:

- **A** -- really implemented.
- **B** -- approximated, because WebGPU cannot express it exactly. The
  code names the deviation in [README.md](README.md).
- **C** -- accepted with no effect: a hint, or something the guest DLL
  already resolved before it reached the wire (`glPushAttrib` keeps its
  own stack and sends only the differences).
- **MISSING** -- no handler at all. The plan's M7 exit condition is zero
  of these.

Counts: A 208, B 4, C 5 of 217 opcodes.

| Op | Record | GL entry point | Class |
| ---: | --- | --- | --- |
| 1 | `VIEWPORT` | `glViewport` | A |
| 2 | `CLEAR_COLOR` | `glClearColor` | A |
| 3 | `CLEAR` | `glClear` | A |
| 4 | `BEGIN` | `glBegin` | A |
| 5 | `END` | `glEnd` | A |
| 6 | `COLOR4F` | `glColor4f` | A |
| 7 | `VERTEX3F` | `glVertex3f` | A |
| 8 | `FLUSH` | `glFlush` | A |
| 9 | `FINISH` | `glFinish` | A |
| 10 | `MATRIX_MODE` | `glMatrixMode` | A |
| 11 | `LOAD_IDENTITY` | `glLoadIdentity` | A |
| 12 | `FRUSTUM` | `glFrustum` | A |
| 13 | `ORTHO` | `glOrtho` | A |
| 14 | `TRANSLATEF` | `glTranslatef` | A |
| 15 | `ROTATEF` | `glRotatef` | A |
| 16 | `SCALEF` | `glScalef` | A |
| 17 | `PUSH_MATRIX` | `glPushMatrix` | A |
| 18 | `POP_MATRIX` | `glPopMatrix` | A |
| 19 | `ENABLE` | `glEnable` | A |
| 20 | `DISABLE` | `glDisable` | A |
| 21 | `DEPTH_FUNC` | `glDepthFunc` | A |
| 22 | `CLEAR_DEPTH` | `glClearDepth` | A |
| 23 | `SHADE_MODEL` | `glShadeModel` | A |
| 24 | `CULL_FACE` | `glCullFace` | A |
| 25 | `FRONT_FACE` | `glFrontFace` | A |
| 26 | `GEN_TEXTURES` | `GEN_TEXTURES` | A |
| 27 | `DELETE_TEXTURES` | `DELETE_TEXTURES` | A |
| 28 | `BIND_TEXTURE` | `glBindTexture` | A |
| 29 | `TEX_IMAGE_2D` | `TEX_IMAGE_2D` | A |
| 30 | `TEX_SUB_IMAGE_2D` | `TEX_SUB_IMAGE_2D` | A |
| 31 | `TEX_PARAMETERI` | `glTexParameteri` | A |
| 32 | `TEX_PARAMETERF` | `glTexParameterf` | A |
| 33 | `PIXEL_STOREI` | `glPixelStorei` | A |
| 34 | `TEX_ENVI` | `glTexEnvi` | A |
| 35 | `TEX_ENVF` | `glTexEnvf` | A |
| 36 | `TEX_COORD2F` | `glTexCoord2f` | A |
| 37 | `ENABLE_CLIENT_STATE` | `glEnableClientState` | A |
| 38 | `DISABLE_CLIENT_STATE` | `glDisableClientState` | A |
| 39 | `DRAW_ARRAYS` | `DRAW_ARRAYS` | A |
| 40 | `DRAW_ELEMENTS` | `DRAW_ELEMENTS` | A |
| 41 | `BLEND_FUNC` | `glBlendFunc` | A |
| 42 | `ALPHA_FUNC` | `glAlphaFunc` | A |
| 43 | `DEPTH_MASK` | `glDepthMask` | A |
| 44 | `COLOR_MASK` | `glColorMask` | A |
| 45 | `SCISSOR` | `glScissor` | A |
| 46 | `LINE_WIDTH` | `glLineWidth` | A |
| 47 | `POLYGON_MODE` | `glPolygonMode` | A |
| 48 | `ACTIVE_TEXTURE` | `glActiveTexture` | A |
| 49 | `CLIENT_ACTIVE_TEXTURE` | `glClientActiveTexture` | A |
| 50 | `MULTI_TEX_COORD4F` | `glMultiTexCoord4f` | A |
| 51 | `NORMAL3F` | `glNormal3f` | A |
| 52 | `FOGF` | `glFogf` | A |
| 53 | `FOGI` | `glFogi` | A |
| 54 | `FOGFV` | `glFogfv4` | A |
| 55 | `MATERIALF` | `glMaterialf` | A |
| 56 | `MATERIALI` | `glMateriali` | A |
| 57 | `MATERIALFV` | `glMaterialfv4` | A |
| 58 | `MATERIALIV` | `glMaterialiv4` | A |
| 59 | `TEX_ENVIV` | `glTexEnviv4` | A |
| 60 | `TEX_ENVFV` | `glTexEnvfv4` | A |
| 61 | `LIGHTF` | `glLightf` | A |
| 62 | `LIGHTI` | `glLighti` | A |
| 63 | `LIGHTFV` | `glLightfv4` | A |
| 64 | `LIGHTIV` | `glLightiv4` | A |
| 65 | `LIGHT_MODELF` | `glLightModelf` | A |
| 66 | `LIGHT_MODELI` | `glLightModeli` | A |
| 67 | `LIGHT_MODELFV` | `glLightModelfv4` | A |
| 68 | `LIGHT_MODELIV` | `glLightModeliv4` | A |
| 69 | `LOAD_MATRIXF` | `LOAD_MATRIXF` | A |
| 70 | `MULT_MATRIXF` | `MULT_MATRIXF` | A |
| 71 | `DEPTH_RANGE` | `glDepthRange` | A |
| 72 | `CLEAR_STENCIL` | `glClearStencil` | A |
| 73 | `STENCIL_FUNC` | `glStencilFunc` | A |
| 74 | `STENCIL_MASK` | `glStencilMask` | A |
| 75 | `STENCIL_OP` | `glStencilOp` | A |
| 76 | `HINT` | `glHint` | C |
| 77 | `POLYGON_OFFSET` | `glPolygonOffset` | A |
| 78 | `TEX_PARAMETERIV` | `glTexParameteriv4` | A |
| 79 | `TEX_PARAMETERFV` | `glTexParameterfv4` | A |
| 80 | `TEX_GENI` | `glTexGeni` | A |
| 81 | `TEX_GENF` | `glTexGenf` | A |
| 82 | `TEX_GENIV` | `glTexGeniv4` | A |
| 83 | `TEX_GENFV` | `glTexGenfv4` | A |
| 84 | `CLIP_PLANE` | `glClipPlane4d` | A |
| 85 | `COLOR_MATERIAL` | `glColorMaterial` | A |
| 86 | `PUSH_ATTRIB` | `glPushAttrib` | C |
| 87 | `POP_ATTRIB` | `glPopAttrib` | C |
| 88 | `PUSH_CLIENT_ATTRIB` | `glPushClientAttrib` | C |
| 89 | `POP_CLIENT_ATTRIB` | `glPopClientAttrib` | C |
| 90 | `DRAW_BUFFER` | `glDrawBuffer` | A |
| 91 | `READ_BUFFER` | `glReadBuffer` | A |
| 92 | `COPY_TEX_IMAGE_2D` | `glCopyTexImage2D` | A |
| 93 | `COPY_TEX_SUB_IMAGE_2D` | `glCopyTexSubImage2D` | A |
| 94 | `READ_PIXELS` | `READ_PIXELS` | A |
| 95 | `BLEND_COLOR` | `glBlendColor` | A |
| 96 | `BLEND_EQUATION` | `glBlendEquation` | A |
| 97 | `BLEND_FUNC_SEPARATE` | `glBlendFuncSeparate` | A |
| 98 | `SAMPLE_COVERAGE` | `glSampleCoverage` | A |
| 99 | `GENERATE_MIPMAP` | `glGenerateMipmap` | A |
| 100 | `FOG_COORDF` | `glFogCoordf` | A |
| 101 | `SECONDARY_COLOR3F` | `glSecondaryColor3f` | A |
| 102 | `POINT_PARAMETERF` | `glPointParameterf` | A |
| 103 | `POINT_PARAMETERFV` | `glPointParameterfv3` | A |
| 104 | `COMPRESSED_TEX_IMAGE_2D` | `COMPRESSED_TEX_IMAGE_2D` | A |
| 105 | `TEX_IMAGE_3D` | `TEX_IMAGE_3D` | A |
| 106 | `TEX_SUB_IMAGE_3D` | `TEX_SUB_IMAGE_3D` | A |
| 107 | `COMPRESSED_TEX_IMAGE_1D` | `COMPRESSED_TEX_IMAGE_1D` | A |
| 108 | `COMPRESSED_TEX_IMAGE_3D` | `COMPRESSED_TEX_IMAGE_3D` | A |
| 109 | `COMPRESSED_TEX_SUB_IMAGE_1D` | `COMPRESSED_TEX_SUB_IMAGE_1D` | A |
| 110 | `COMPRESSED_TEX_SUB_IMAGE_2D` | `COMPRESSED_TEX_SUB_IMAGE_2D` | A |
| 111 | `COMPRESSED_TEX_SUB_IMAGE_3D` | `COMPRESSED_TEX_SUB_IMAGE_3D` | A |
| 112 | `WINDOW_POS3F` | `glWindowPos3f` | A |
| 113 | `POINT_PARAMETERI` | `glPointParameteri` | A |
| 114 | `POINT_PARAMETERIV` | `POINT_PARAMETERIV` | A |
| 115 | `POINT_SIZE` | `glPointSize` | A |
| 116 | `LINE_STIPPLE` | `glLineStipple` | B (D-16) |
| 117 | `LOGIC_OP` | `glLogicOp` | B (D-01) |
| 118 | `PIXEL_TRANSFERF` | `glPixelTransferf` | A |
| 119 | `PIXEL_TRANSFERI` | `glPixelTransferi` | A |
| 120 | `PIXEL_ZOOM` | `glPixelZoom` | A |
| 121 | `DRAW_PIXELS` | `DRAW_PIXELS` | B (D-15) |
| 122 | `BITMAP` | `BITMAP` | A |
| 123 | `COPY_PIXELS` | `glCopyPixels` | B (D-15) |
| 124 | `TEX_IMAGE_1D` | `TEX_IMAGE_1D` | A |
| 125 | `TEX_SUB_IMAGE_1D` | `TEX_SUB_IMAGE_1D` | A |
| 126 | `COPY_TEX_IMAGE_1D` | `glCopyTexImage1D` | A |
| 127 | `COPY_TEX_SUB_IMAGE_1D` | `glCopyTexSubImage1D` | A |
| 128 | `CLEAR_ACCUM` | `glClearAccum` | A |
| 129 | `ACCUM` | `glAccum` | A |
| 130 | `POLYGON_STIPPLE` | `POLYGON_STIPPLE` | A |
| 131 | `PIXEL_MAPFV` | `PIXEL_MAPFV` | A |
| 132 | `PIXEL_MAPUIV` | `PIXEL_MAPUIV` | A |
| 133 | `PIXEL_MAPUSV` | `PIXEL_MAPUSV` | A |
| 134 | `TEX_COORD4F` | `glTexCoord4f` | A |
| 135 | `VERTEX4F` | `glVertex4f` | A |
| 136 | `RASTER_POS4F` | `glRasterPos4f` | A |
| 137 | `BLEND_EQUATION_SEPARATE` | `glBlendEquationSeparate` | A |
| 138 | `DRAW_BUFFERS` | `DRAW_BUFFERS` | A |
| 139 | `STENCIL_OP_SEPARATE` | `glStencilOpSeparate` | A |
| 140 | `STENCIL_FUNC_SEPARATE` | `glStencilFuncSeparate` | A |
| 141 | `STENCIL_MASK_SEPARATE` | `glStencilMaskSeparate` | A |
| 142 | `CREATE_PROGRAM` | `glCreateProgramMapped` | A |
| 143 | `CREATE_SHADER` | `glCreateShaderMapped` | A |
| 144 | `DELETE_PROGRAM` | `glDeleteProgramMapped` | A |
| 145 | `DELETE_SHADER` | `glDeleteShaderMapped` | A |
| 146 | `ATTACH_SHADER` | `glAttachShaderMapped` | A |
| 147 | `DETACH_SHADER` | `glDetachShaderMapped` | A |
| 148 | `SHADER_SOURCE` | `SHADER_SOURCE` | A |
| 149 | `COMPILE_SHADER` | `glCompileShaderMapped` | A |
| 150 | `LINK_PROGRAM` | `glLinkProgramMapped` | A |
| 151 | `USE_PROGRAM` | `glUseProgramMapped` | A |
| 152 | `VALIDATE_PROGRAM` | `glValidateProgramMapped` | A |
| 153 | `BIND_ATTRIB_LOCATION` | `BIND_ATTRIB_LOCATION` | A |
| 154 | `MAP_UNIFORM_LOCATION` | `MAP_UNIFORM_LOCATION` | A |
| 155 | `MAP_ATTRIB_LOCATION` | `MAP_ATTRIB_LOCATION` | A |
| 156 | `UNIFORM_FV` | `UNIFORM_FV` | A |
| 157 | `UNIFORM_IV` | `UNIFORM_IV` | A |
| 158 | `UNIFORM_MATRIX_FV` | `UNIFORM_MATRIX_FV` | A |
| 159 | `VERTEX_ATTRIB4F` | `glVertexAttrib4fMapped` | A |
| 160 | `ENABLE_VERTEX_ATTRIB_ARRAY` | `glEnableVertexAttribArrayMapped` | A |
| 161 | `DISABLE_VERTEX_ATTRIB_ARRAY` | `glDisableVertexAttribArrayMapped` | A |
| 162 | `DRAW_ARRAYS_GL2` | `DRAW_ARRAYS_GL2` | A |
| 163 | `DRAW_ELEMENTS_GL2` | `DRAW_ELEMENTS_GL2` | A |
| 164 | `UNIFORM_MATRIX_RECT_FV` | `UNIFORM_MATRIX_RECT_FV` | A |
| 165 | `GEN_FRAMEBUFFERS` | `GEN_FRAMEBUFFERS` | A |
| 166 | `DELETE_FRAMEBUFFERS` | `DELETE_FRAMEBUFFERS` | A |
| 167 | `BIND_FRAMEBUFFER` | `glBindFramebufferMapped` | A |
| 168 | `FRAMEBUFFER_TEXTURE` | `glFramebufferTextureMapped` | A |
| 169 | `FRAMEBUFFER_RENDERBUFFER` | `glFramebufferRenderbufferMapped` | A |
| 170 | `GEN_RENDERBUFFERS` | `GEN_RENDERBUFFERS` | A |
| 171 | `DELETE_RENDERBUFFERS` | `DELETE_RENDERBUFFERS` | A |
| 172 | `BIND_RENDERBUFFER` | `glBindRenderbufferMapped` | A |
| 173 | `RENDERBUFFER_STORAGE` | `glRenderbufferStorageMapped` | A |
| 174 | `QUERY_OBJECT_IV` | `QUERY_OBJECT_IV` | A |
| 175 | `QUERY_OBJECT_LOG` | `QUERY_OBJECT_LOG` | A |
| 176 | `CHECK_FRAMEBUFFER_STATUS` | `CHECK_FRAMEBUFFER_STATUS` | A |
| 177 | `QUERY_ACTIVE` | `QUERY_ACTIVE` | A |
| 178 | `GEN_QUERIES` | `GEN_QUERIES` | A |
| 179 | `DELETE_QUERIES` | `DELETE_QUERIES` | A |
| 180 | `BEGIN_QUERY` | `glBeginQueryMapped` | A |
| 181 | `END_QUERY` | `glEndQueryMapped` | A |
| 182 | `GEN_PROGRAMS_ARB` | `GEN_PROGRAMS_ARB` | A |
| 183 | `DELETE_PROGRAMS_ARB` | `DELETE_PROGRAMS_ARB` | A |
| 184 | `BIND_PROGRAM_ARB` | `glBindProgramARBMapped` | A |
| 185 | `PROGRAM_STRING_ARB` | `PROGRAM_STRING_ARB` | A |
| 186 | `PROGRAM_PARAMETER_FV_ARB` | `PROGRAM_PARAMETER_FV_ARB` | A |
| 187 | `PROGRAM_PARAMETER_DV_ARB` | `PROGRAM_PARAMETER_DV_ARB` | A |
| 188 | `QUERY_PROGRAM_IV_ARB` | `QUERY_PROGRAM_IV_ARB` | A |
| 189 | `QUERY_PROGRAM_PARAMETER_FV_ARB` | `QUERY_PROGRAM_PARAMETER_FV_ARB` | A |
| 190 | `QUERY_PROGRAM_PARAMETER_DV_ARB` | `QUERY_PROGRAM_PARAMETER_DV_ARB` | A |
| 191 | `QUERY_PROGRAM_STRING_ARB` | `QUERY_PROGRAM_STRING_ARB` | A |
| 192 | `QUERY_GL_STRING` | `QUERY_GL_STRING` | A |
| 193 | `QUERY_INTEGER` | `QUERY_INTEGER` | A |
| 194 | `GEN_BUFFERS` | `GEN_BUFFERS` | A |
| 195 | `DELETE_BUFFERS` | `DELETE_BUFFERS` | A |
| 196 | `BIND_BUFFER` | `glBindBufferMapped` | A |
| 197 | `BUFFER_DATA` | `BUFFER_DATA` | A |
| 198 | `BUFFER_SUB_DATA` | `BUFFER_SUB_DATA` | A |
| 199 | `VERTEX_POINTER_VBO` | `VERTEX_POINTER_VBO` | A |
| 200 | `COLOR_POINTER_VBO` | `COLOR_POINTER_VBO` | A |
| 201 | `TEX_COORD_POINTER_VBO` | `TEX_COORD_POINTER_VBO` | A |
| 202 | `NORMAL_POINTER_VBO` | `NORMAL_POINTER_VBO` | A |
| 203 | `SECONDARY_COLOR_POINTER_VBO` | `SECONDARY_COLOR_POINTER_VBO` | A |
| 204 | `FOG_COORD_POINTER_VBO` | `FOG_COORD_POINTER_VBO` | A |
| 205 | `VERTEX_ATTRIB_POINTER_VBO` | `VERTEX_ATTRIB_POINTER_VBO` | A |
| 206 | `DRAW_ARRAYS_DIRECT` | `glDrawArraysDirect` | A |
| 207 | `DRAW_ELEMENTS_DIRECT` | `DRAW_ELEMENTS_DIRECT` | A |
| 208 | `DRAW_RANGE_ELEMENTS_DIRECT` | `DRAW_RANGE_ELEMENTS_DIRECT` | A |
| 209 | `MULTI_DRAW_ARRAYS_DIRECT` | `MULTI_DRAW_ARRAYS_DIRECT` | A |
| 210 | `MULTI_DRAW_ELEMENTS_DIRECT` | `MULTI_DRAW_ELEMENTS_DIRECT` | A |
| 211 | `QUERY_ERROR` | `QUERY_ERROR` | A |
| 212 | `QUERY_LOCATION` | `QUERY_LOCATION` | A |
| 213 | `QUERY_UNIFORM` | `QUERY_UNIFORM` | A |
| 214 | `INVALIDATE_PROGRAM_LOCATIONS` | `glInvalidateProgramLocations` | A |
| 215 | `COPY_TEX_SUB_IMAGE_3D` | `glCopyTexSubImage3D` | A |
| 216 | `QUERY_OBJECT_BATCH` | `QUERY_OBJECT_BATCH` | A |
| 217 | `BLIT_FRAMEBUFFER` | `glBlitFramebuffer` | A |

## What this table does not cover

The guest DLL exports more entry points than there are opcodes, because
many resolve entirely inside `openglproxy/opengl32_proxy.c` and never reach
the host: display lists are recorded and replayed there,
`glPushAttrib`/`glPopAttrib` operate on its shadow state and emit only
the differences, `GL_SELECT` and `GL_FEEDBACK` are software transforms
that never touch the GPU, and pixel-buffer-object pack/unpack offsets are
resolved before the transfer. Those belong to the guest's own tests.
                                                                                                                                                                                                                                                                                                                                                            source/v64/src/browser/glbridge/gl-webgpu/gl_arb_program.js                                         0000644 0000000 0000000 00000164002 00000000000 021124  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GL_ARB_vertex_program and GL_ARB_fragment_program assembly -> WGSL.
//
// ARB assembly is a register machine: a handful of typed register files, four
// component swizzles, write masks, source modifiers, and a flat instruction
// list with no control flow. That is structurally what D3D9's shader model 1.x
// is, and d3d9_shader_pipeline.js already solved the interesting half of it --
// how to keep swizzles, masks and saturation straight while emitting readable
// WGSL. What does not transfer is the front end (text, not bytecode) and the
// instruction semantics, so those are written out here.
//
// The state bindings (state.matrix.mvp, state.light[n].position, ...) resolve
// into the *same* GLState block the fixed pipeline and the GLSL compatibility
// built-ins use, so an ARB program and a fixed-function draw see one set of
// matrices rather than two that can drift.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md chapter 9.

(function(global) {
    "use strict";

    const nodeRequire = (typeof require === "function" &&
        typeof module !== "undefined") ? require : null;
    const stateLayout = nodeRequire ? nodeRequire("./gl_state_layout.js") :
        global.GLStateLayout;
    const translator = nodeRequire ? nodeRequire("./gl_shader_translator.js") :
        global.GLShaderTranslator;

    const ARB_REVISION = 2;

    /*
     * Twenty-eight, not the ARB minimum of twenty-four.
     *
     * openglproxy/README.md records why: WineD3D 1.7.52's fixed-function
     * replacement writes program.env[27], and advertising 24 let it run four
     * bytes past its own allocation. The number is part of the contract with
     * the guest, which clamps to whatever is advertised here.
     */
    const MAX_PROGRAM_PARAMETERS = 28;
    /* Group 1 binding 0 is the shared GL state block; each stage's ARB
     * parameter block gets a binding of its own. */
    const PARAMETER_BINDING = { vertex: 1, fragment: 2 };
    const MAX_TEMPORARIES = 32;
    const MAX_TEXTURE_UNITS = stateLayout.MAX_TEXTURE_UNITS;
    const ATTR = translator.COMPAT_ATTRIBUTE_LOCATIONS;

    class ARBError extends Error {
        constructor(message, line, offset) {
            super(message);
            this.arbLine = line || 0;
            // GL_PROGRAM_ERROR_POSITION_ARB is a character offset into the
            // program string, not a line: the extension expects the caller to
            // be able to point at the exact token it rejected.
            this.arbOffset = offset === undefined ? -1 : offset;
        }
    }

    /* ================================================================== */
    /* Lexer                                                              */
    /* ================================================================== */

    const TOKEN = /(!!ARB[a-z]+1\.0)|([A-Za-z_$][A-Za-z0-9_$]*)|(-?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?)|(\s+)|(#[^\n]*)|([\s\S])/g;

    function lex(source) {
        const tokens = [];
        let line = 1;
        let match;
        TOKEN.lastIndex = 0;
        while ((match = TOKEN.exec(source)) !== null) {
            if (match[4] !== undefined || match[5] !== undefined) {
                for (const ch of match[0]) if (ch === "\n") ++line;
                continue;
            }
            const at = match.index;
            if (match[1] !== undefined)
                tokens.push({ type: "header", value: match[1], line, at });
            else if (match[2] !== undefined)
                tokens.push({ type: "ident", value: match[2], line, at });
            else if (match[3] !== undefined)
                tokens.push({ type: "number", value: parseFloat(match[3]),
                             line, at });
            else
                tokens.push({ type: "punct", value: match[6], line, at });
        }
        tokens.push({ type: "eof", value: "", line, at: source.length });
        return tokens;
    }

    /* ================================================================== */
    /* Instruction table                                                  */
    /* ================================================================== */

    /*
     * Each entry: how many sources it takes and how to emit it. `emit` receives
     * the already-swizzled source expressions and returns a vec4 expression;
     * the caller applies the write mask and saturation.
     */
    const INSTRUCTIONS = {
        ABS: { sources: 1, emit: a => "abs(" + a[0] + ")" },
        ADD: { sources: 2, emit: a => "(" + a[0] + " + " + a[1] + ")" },
        CMP: { sources: 3, fragmentOnly: true,
               emit: a => "select(" + a[2] + ", " + a[1] + ", " + a[0] +
                   " < vec4<f32>(0.0))" },
        COS: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(cos(" + a[0] + ".x))" },
        DP3: { sources: 2,
               emit: a => "vec4<f32>(dot(" + a[0] + ".xyz, " + a[1] + ".xyz))" },
        DP4: { sources: 2,
               emit: a => "vec4<f32>(dot(" + a[0] + ", " + a[1] + "))" },
        DPH: { sources: 2,
               emit: a => "vec4<f32>(dot(" + a[0] + ".xyz, " + a[1] + ".xyz) + " +
                   a[1] + ".w)" },
        DST: { sources: 2,
               // The distance-vector helper: (1, d, d^2, 1/d) assembled from
               // two operands that each hold half of it.
               emit: a => "vec4<f32>(1.0, " + a[0] + ".y * " + a[1] + ".y, " +
                   a[0] + ".z, " + a[1] + ".w)" },
        EX2: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(exp2(" + a[0] + ".x))" },
        EXP: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(exp2(floor(" + a[0] + ".x)), fract(" +
                   a[0] + ".x), exp2(" + a[0] + ".x), 1.0)" },
        FLR: { sources: 1, emit: a => "floor(" + a[0] + ")" },
        FRC: { sources: 1, emit: a => "fract(" + a[0] + ")" },
        LG2: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(log2(max(" + a[0] + ".x, 1e-30)))" },
        LIT: { sources: 1, emit: a => "arbLit(" + a[0] + ")" },
        LOG: { sources: 1, scalar: true,
               emit: a => "arbLog(" + a[0] + ".x)" },
        LRP: { sources: 3, fragmentOnly: true,
               emit: a => "mix(" + a[2] + ", " + a[1] + ", " + a[0] + ")" },
        MAD: { sources: 3,
               emit: a => "(" + a[0] + " * " + a[1] + " + " + a[2] + ")" },
        MAX: { sources: 2, emit: a => "max(" + a[0] + ", " + a[1] + ")" },
        MIN: { sources: 2, emit: a => "min(" + a[0] + ", " + a[1] + ")" },
        MOV: { sources: 1, emit: a => a[0] },
        MUL: { sources: 2, emit: a => "(" + a[0] + " * " + a[1] + ")" },
        POW: { sources: 2, scalar: true,
               emit: a => "vec4<f32>(pow(max(" + a[0] + ".x, 0.0), " +
                   a[1] + ".x))" },
        RCP: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(1.0 / " + a[0] + ".x)" },
        RSQ: { sources: 1, scalar: true,
               emit: a => "vec4<f32>(inverseSqrt(max(abs(" + a[0] +
                   ".x), 1e-30)))" },
        SCS: { sources: 1, scalar: true, fragmentOnly: true,
               emit: a => "vec4<f32>(cos(" + a[0] + ".x), sin(" + a[0] +
                   ".x), 0.0, 0.0)" },
        SGE: { sources: 2,
               emit: a => "select(vec4<f32>(0.0), vec4<f32>(1.0), " +
                   a[0] + " >= " + a[1] + ")" },
        SIN: { sources: 1, scalar: true, fragmentOnly: true,
               emit: a => "vec4<f32>(sin(" + a[0] + ".x))" },
        SLT: { sources: 2,
               emit: a => "select(vec4<f32>(0.0), vec4<f32>(1.0), " +
                   a[0] + " < " + a[1] + ")" },
        SUB: { sources: 2, emit: a => "(" + a[0] + " - " + a[1] + ")" },
        XPD: { sources: 2,
               emit: a => "vec4<f32>(cross(" + a[0] + ".xyz, " + a[1] +
                   ".xyz), 1.0)" },
        SWZ: { sources: 1, extendedSwizzle: true, emit: a => a[0] },
        // Control and texture instructions are handled by the generator.
        ARL: { sources: 1, vertexOnly: true, address: true },
        KIL: { sources: 1, fragmentOnly: true, kill: true },
        TEX: { sources: 1, texture: "sample", fragmentOnly: true },
        TXB: { sources: 1, texture: "bias", fragmentOnly: true },
        TXP: { sources: 1, texture: "proj", fragmentOnly: true },
    };

    /* WGSL helpers the instruction set needs. Only emitted when used. */
    const HELPERS = {
        arbLit:
            "fn arbLit(v : vec4<f32>) -> vec4<f32> {\n" +
            "    // ARB's lighting helper: (1, max(x,0), x>0 ? pow(max(y,0), w) : 0, 1)\n" +
            "    let diffuse = max(v.x, 0.0);\n" +
            "    let specular = select(0.0, pow(max(v.y, 0.0), clamp(v.w, -128.0, 128.0)),\n" +
            "        v.x > 0.0);\n" +
            "    return vec4<f32>(1.0, diffuse, specular, 1.0);\n" +
            "}",
        arbLog:
            "fn arbLog(x : f32) -> vec4<f32> {\n" +
            "    let a = max(abs(x), 1e-30);\n" +
            "    let e = floor(log2(a));\n" +
            "    return vec4<f32>(e, a / exp2(e), log2(a), 1.0);\n" +
            "}",
    };

    /* ================================================================== */
    /* Register bindings                                                  */
    /* ================================================================== */

    /*
     * state.* bindings resolve into the shared GLState block. Each entry names
     * the field gl_state_layout.js must include and the WGSL expression that
     * reads it, so an ARB program and a fixed-function draw literally read the
     * same bytes.
     */
    const STATE_BINDINGS = {
        "matrix.modelview": { field: "modelview", matrix: "glState.modelview" },
        "matrix.projection": { field: "projection", matrix: "glState.projection" },
        "matrix.mvp": { field: "mvp", matrix: "glState.mvp" },
        "matrix.modelview.inverse": { field: "modelviewInverse",
            matrix: "glState.modelviewInverse" },
        "matrix.modelview.transpose": { field: "modelviewTranspose",
            matrix: "glState.modelviewTranspose" },
        "matrix.modelview.invtrans": { field: "modelviewInverseTranspose",
            matrix: "glState.modelviewInverseTranspose" },
        "matrix.projection.inverse": { field: "projectionInverse",
            matrix: "glState.projectionInverse" },
        "matrix.projection.transpose": { field: "projectionTranspose",
            matrix: "glState.projectionTranspose" },
        "matrix.projection.invtrans": { field: "projectionInverseTranspose",
            matrix: "glState.projectionInverseTranspose" },
        "matrix.mvp.inverse": { field: "mvpInverse", matrix: "glState.mvpInverse" },
        "matrix.mvp.transpose": { field: "mvpTranspose",
            matrix: "glState.mvpTranspose" },
        "matrix.mvp.invtrans": { field: "mvpInverseTranspose",
            matrix: "glState.mvpInverseTranspose" },
        "material.ambient": { field: "frontMaterial",
            vector: "glState.frontMaterial.ambient" },
        "material.diffuse": { field: "frontMaterial",
            vector: "glState.frontMaterial.diffuse" },
        "material.specular": { field: "frontMaterial",
            vector: "glState.frontMaterial.specular" },
        "material.emission": { field: "frontMaterial",
            vector: "glState.frontMaterial.emission" },
        "material.shininess": { field: "frontMaterial",
            vector: "vec4<f32>(glState.frontMaterial.shininess, 0.0, 0.0, 1.0)" },
        "material.front.ambient": { field: "frontMaterial",
            vector: "glState.frontMaterial.ambient" },
        "material.front.diffuse": { field: "frontMaterial",
            vector: "glState.frontMaterial.diffuse" },
        "material.front.specular": { field: "frontMaterial",
            vector: "glState.frontMaterial.specular" },
        "material.back.ambient": { field: "backMaterial",
            vector: "glState.backMaterial.ambient" },
        "material.back.diffuse": { field: "backMaterial",
            vector: "glState.backMaterial.diffuse" },
        "material.back.specular": { field: "backMaterial",
            vector: "glState.backMaterial.specular" },
        "lightmodel.ambient": { field: "lightModelAmbient",
            vector: "glState.lightModelAmbient" },
        "lightmodel.scenecolor": { field: "frontSceneColor",
            vector: "glState.frontSceneColor" },
        "lightmodel.front.scenecolor": { field: "frontSceneColor",
            vector: "glState.frontSceneColor" },
        "lightmodel.back.scenecolor": { field: "backSceneColor",
            vector: "glState.backSceneColor" },
        "fog.color": { field: "fogColor", vector: "glState.fogColor" },
        "fog.params": { field: "fogParams", vector: "glState.fogParams" },
        "depth.range": { field: "depthRange", vector: "glState.depthRange" },
        "point.size": { field: "pointParams", vector: "glState.pointParams" },
        "point.attenuation": { field: "pointAttenuation",
            vector: "glState.pointAttenuation" },
    };

    const INDEXED_STATE = [
        { pattern: /^light\[(\d+)\]\.(ambient|diffuse|specular|position|half)$/,
          field: "lights",
          expr: (index, member) => "glState.lights[" + index + "]." +
              (member === "half" ? "halfVector" : member) },
        { pattern: /^light\[(\d+)\]\.attenuation$/, field: "lights",
          expr: index => "vec4<f32>(glState.lights[" + index +
              "].constantAttenuation, glState.lights[" + index +
              "].linearAttenuation, glState.lights[" + index +
              "].quadraticAttenuation, glState.lights[" + index +
              "].spotExponent)" },
        { pattern: /^light\[(\d+)\]\.spot\.direction$/, field: "lights",
          expr: index => "vec4<f32>(glState.lights[" + index +
              "].spotDirection, glState.lights[" + index + "].spotCosCutoff)" },
        { pattern: /^lightprod\[(\d+)\]\.(ambient|diffuse|specular)$/,
          field: "frontLightProduct",
          expr: (index, member) => "glState.frontLightProduct[" + index + "]." +
              member },
        { pattern: /^texenv\[(\d+)\]\.color$/, field: "texEnvColor",
          expr: index => "glState.texEnvColor[" + index + "]" },
        { pattern: /^texenv\.color$/, field: "texEnvColor",
          expr: () => "glState.texEnvColor[0]" },
        { pattern: /^clip\[(\d+)\]\.plane$/, field: "clipPlanes",
          expr: index => "glState.clipPlanes[" + index + "]" },
        { pattern: /^texgen\[(\d+)\]\.(eye|object)\.([stqr])$/,
          field: "texGenPlanes",
          expr: (index, space, coord) => "glState.texGenPlanes[" +
              (parseInt(index, 10) * 8 + (space === "eye" ? 4 : 0) +
               "stqr".indexOf(coord)) + "]" },
    ];

    /* Vertex program inputs, and the attribute slot each occupies. */
    const VERTEX_ATTRIBUTES = {
        "vertex.position": { name: "gl_Vertex", location: ATTR.gl_Vertex },
        "vertex.weight": { name: "gl_Weight", location: 1 },
        "vertex.normal": { name: "gl_Normal", location: ATTR.gl_Normal,
                           components: 3 },
        "vertex.color": { name: "gl_Color", location: ATTR.gl_Color },
        "vertex.color.primary": { name: "gl_Color", location: ATTR.gl_Color },
        "vertex.color.secondary": { name: "gl_SecondaryColor",
                                    location: ATTR.gl_SecondaryColor },
        "vertex.fogcoord": { name: "gl_FogCoord", location: ATTR.gl_FogCoord,
                             components: 1 },
    };

    const VERTEX_RESULTS = {
        "result.position": "position",
        "result.color": "frontColor",
        "result.color.primary": "frontColor",
        "result.color.front": "frontColor",
        "result.color.front.primary": "frontColor",
        "result.color.secondary": "frontSecondary",
        "result.color.front.secondary": "frontSecondary",
        "result.color.back": "backColor",
        "result.color.back.primary": "backColor",
        "result.color.back.secondary": "backSecondary",
        "result.fogcoord": "fogCoord",
        "result.pointsize": "pointSize",
    };

    const FRAGMENT_RESULTS = {
        "result.color": "color0",
        "result.depth": "depth",
    };

    /* ================================================================== */
    /* Parser                                                             */
    /* ================================================================== */

    class Parser {
        constructor(source) {
            this.tokens = lex(source);
            this.pos = 0;
            this.target = null;
            this.options = new Set();
            this.aliases = new Map();     // name -> resolved binding text
            this.temporaries = new Set();
            this.addresses = new Set();
            this.params = new Map();      // name -> {size, values|binding}
            this.attribs = new Map();
            this.outputs = new Map();
            this.instructions = [];
        }

        peek(offset) { return this.tokens[this.pos + (offset || 0)]; }
        /* Where the parser stopped, for GL_PROGRAM_ERROR_POSITION_ARB. Errors
         * thrown deeper in the parse do not each have to carry an offset: the
         * token the parser was looking at when it gave up is the position the
         * extension asks for. */
        currentOffset() {
            const token = this.tokens[Math.min(this.pos, this.tokens.length - 1)];
            return token && token.at !== undefined ? token.at : 0;
        }
        next() { return this.tokens[this.pos++]; }
        get line() { return this.peek().line; }
        at(value) {
            const token = this.peek();
            return token.value === value;
        }
        accept(value) {
            if (this.at(value)) { ++this.pos; return true; }
            return false;
        }
        expect(value) {
            if (!this.accept(value))
                throw new ARBError("expected '" + value + "' but found '" +
                    String(this.peek().value) + "'", this.line);
        }
        expectIdent() {
            const token = this.next();
            if (token.type !== "ident")
                throw new ARBError("expected an identifier", token.line);
            return token.value;
        }

        parse() {
            const header = this.next();
            if (header.type !== "header")
                throw new ARBError("a program must begin with !!ARBvp1.0 or " +
                    "!!ARBfp1.0", header.line, header.at);
            this.target = header.value === "!!ARBvp1.0" ? "vertex" : "fragment";
            for (;;) {
                const token = this.peek();
                if (token.type === "eof")
                    throw new ARBError("the program has no END", token.line);
                if (token.type === "ident" && token.value === "END") {
                    this.next();
                    break;
                }
                this.statement();
            }
            return this;
        }

        statement() {
            const token = this.peek();
            if (token.type !== "ident")
                throw new ARBError("unexpected token '" + String(token.value) + "'",
                    token.line);
            switch (token.value) {
            case "OPTION": {
                this.next();
                this.options.add(this.expectIdent());
                this.expect(";");
                return;
            }
            case "TEMP": {
                this.next();
                do { this.declareTemporary(this.expectIdent()); }
                while (this.accept(","));
                this.expect(";");
                return;
            }
            case "ADDRESS": {
                this.next();
                do { this.addresses.add(this.expectIdent()); }
                while (this.accept(","));
                this.expect(";");
                return;
            }
            case "ALIAS": {
                this.next();
                const name = this.expectIdent();
                this.expect("=");
                this.aliases.set(name, this.expectIdent());
                this.expect(";");
                return;
            }
            case "ATTRIB": {
                this.next();
                const name = this.expectIdent();
                this.expect("=");
                this.attribs.set(name, this.bindingPath());
                this.expect(";");
                return;
            }
            case "OUTPUT": {
                this.next();
                const name = this.expectIdent();
                this.expect("=");
                this.outputs.set(name, this.bindingPath());
                this.expect(";");
                return;
            }
            case "PARAM": {
                this.next();
                return this.paramStatement();
            }
            default:
                return this.instruction();
            }
        }

        declareTemporary(name) {
            if (this.temporaries.size >= MAX_TEMPORARIES)
                throw new ARBError("more than " + MAX_TEMPORARIES +
                    " temporaries", this.line);
            this.temporaries.add(name);
        }

        /*
         * A dotted binding path such as vertex.color.secondary or
         * state.light[0].position, kept as text for the resolver.
         *
         * `stopAtSwizzle` is what separates `result.color.secondary` (a path)
         * from `result.color.xz` (a path plus a write mask). No ARB path
         * component is spelled with only swizzle letters, so the test is exact
         * rather than a heuristic.
         */
        bindingPath(stopAtSwizzle) {
            let text = this.expectIdent();
            for (;;) {
                if (this.at(".") && stopAtSwizzle) {
                    const after = this.peek(1);
                    if (after && after.type === "ident" &&
                            /^(?:[xyzw]{1,4}|[rgba]{1,4})$/.test(after.value))
                        break;
                }
                if (this.accept(".")) {
                    const token = this.next();
                    text += "." + String(token.value);
                    continue;
                }
                if (this.at("[")) {
                    this.next();
                    let inner = "";
                    while (!this.at("]")) {
                        const token = this.next();
                        if (token.type === "eof")
                            throw new ARBError("unterminated '['", token.line);
                        inner += String(token.value);
                    }
                    this.expect("]");
                    text += "[" + inner + "]";
                    continue;
                }
                break;
            }
            return text;
        }

        /*
         * PARAM has two shapes that look alike and mean different things:
         *
         *   PARAM half = { 0.5, 0.5, 0.5, 1.0 };     one four-component constant
         *   PARAM mvp[4] = { state.matrix.mvp };     four registers, from a matrix
         *
         * The braces are the same; what decides is the [n] and whether the
         * contents are bare numbers. Reading the first as four separate
         * registers is the mistake that makes a transform silently use 0.5 as
         * its whole matrix.
         */
        paramStatement() {
            const name = this.expectIdent();
            let arraySize = 0;
            if (this.accept("[")) {
                arraySize = this.at("]") ? -1 : this.next().value;
                this.expect("]");
            }
            this.expect("=");
            const items = [];
            if (this.accept("{")) {
                do { items.push(this.paramItem()); } while (this.accept(","));
                this.expect("}");
            } else {
                items.push(this.paramItem());
            }
            this.expect(";");

            let entries;
            if (!arraySize && items.every(item => item.kind === "number")) {
                const values = items.map(item => item.value);
                /*
                 * ARB program scalar constants are scalar vector initialisers:
                 *
                 *     PARAM half = 0.5;
                 *
                 * names { 0.5, 0.5, 0.5, 0.5 }, not the conventional GL
                 * vertex expansion { 0.5, 0, 0, 1 }.  glview's bump-map
                 * vertex program uses exactly that spelling for both operands
                 * of its final MAD; expanding it like a vertex made the DOT3
                 * combiner receive a mostly negative light vector and reduced
                 * the whole 1.4/1.5 test to the clear colour.
                 */
                if (values.length === 1) {
                    values.push(values[0], values[0], values[0]);
                } else {
                    while (values.length < 4)
                        values.push(values.length === 3 ? 1 : 0);
                }
                entries = [{ kind: "constant", values }];
            } else {
                entries = items.map(item => {
                    if (item.kind === "number")
                        return { kind: "constant",
                                 values: [item.value, item.value, item.value,
                                          item.value] };
                    if (item.kind === "vector") {
                        const values = item.values.slice();
                        while (values.length < 4)
                            values.push(values.length === 3 ? 1 : 0);
                        return { kind: "constant", values };
                    }
                    return { kind: "binding", path: item.path };
                });
            }
            this.params.set(name, { arraySize, entries });
        }

        paramItem() {
            if (this.accept("{")) {
                const values = [];
                do { values.push(this.signedNumber()); } while (this.accept(","));
                this.expect("}");
                return { kind: "vector", values };
            }
            if (this.peek().type === "number" || this.at("-") || this.at("+"))
                return { kind: "number", value: this.signedNumber() };
            return { kind: "binding", path: this.bindingPath() };
        }

        signedNumber() {
            let sign = 1;
            while (this.at("-") || this.at("+")) {
                if (this.next().value === "-") sign = -sign;
            }
            const token = this.next();
            if (token.type !== "number")
                throw new ARBError("expected a number", token.line);
            return sign * token.value;
        }

        instruction() {
            const token = this.next();
            let opcode = token.value;
            let saturate = false;
            if (opcode.endsWith("_SAT")) {
                saturate = true;
                opcode = opcode.slice(0, -4);
            }
            const info = INSTRUCTIONS[opcode];
            if (!info)
                throw new ARBError("unknown instruction '" + opcode + "'",
                    token.line);
            if (info.vertexOnly && this.target !== "vertex")
                throw new ARBError(opcode + " is vertex-program only", token.line);
            if (info.fragmentOnly && this.target !== "fragment")
                throw new ARBError(opcode + " is fragment-program only", token.line);

            const instruction = { opcode, info, saturate, line: token.line,
                                  sources: [] };
            if (!info.kill) {
                instruction.destination = this.destination();
                this.expect(",");
            }
            const sourceCount = info.sources;
            for (let i = 0; i < sourceCount; ++i) {
                instruction.sources.push(this.source(info.extendedSwizzle));
                if (i + 1 < sourceCount) this.expect(",");
            }
            if (info.texture) {
                this.expect(",");
                instruction.texture = this.bindingPath();       // texture[n]
                this.expect(",");
                // "2D" lexes as a number followed by an identifier, so the
                // target is read as raw tokens up to the terminator.
                let target = "";
                while (!this.at(";") && this.peek().type !== "eof")
                    target += String(this.next().value);
                instruction.textureTarget = target;
            }
            this.expect(";");
            this.instructions.push(instruction);
        }

        destination() {
            const name = this.bindingPath(true);
            let mask = "xyzw";
            if (this.accept(".")) mask = normalizeMask(this.expectIdent());
            return { name, mask, line: this.line };
        }

        source(extended) {
            let negate = false;
            let absolute = false;
            while (this.at("-") || this.at("+")) {
                if (this.next().value === "-") negate = !negate;
            }
            if (this.accept("|")) absolute = true;
            const name = this.bindingPath(true);
            let swizzle = null;
            if (this.accept(".")) {
                const token = this.next();
                swizzle = String(token.value);
                if (extended) {
                    // SWZ's extended swizzle allows 0 and 1 as components and a
                    // sign per component, which arrives as several tokens.
                    while (this.at(",") === false && this.peek().type !== "punct")
                        swizzle += String(this.next().value);
                }
            }
            if (absolute) this.expect("|");
            return { name, swizzle, negate, absolute, line: this.line };
        }
    }

    /* ================================================================== */
    /* Generator                                                          */
    /* ================================================================== */

    class Generator {
        constructor(parsed, options) {
            this.parsed = parsed;
            this.options = options || {};
            this.stage = parsed.target;
            this.lines = [];
            this.helpers = new Set();
            this.stateFields = new Set();
            this.constants = [];          // local PARAM constants, inlined
            this.paramArrays = new Map();
            this.usedAttributes = new Map();
            this.usedResults = new Set();
            this.textureUnits = new Map();  // unit -> target
            this.usesKill = false;
            this.usesAddress = false;
            this.envUsed = false;
            this.localUsed = false;
            this.temporary = 0;
            // Declared here rather than where it is emitted: the state layout
            // is built before the shell, so a field added later would not be
            // in the struct the shell then reads from.
            if (parsed.options.has("ARB_position_invariant")) {
                this.stateFields.add("mvp");
                this.useAttribute("vertex.position",
                    VERTEX_ATTRIBUTES["vertex.position"]);
            }
        }

        emit(text) { this.lines.push(text); }

        generate() {
            const body = [];
            for (const instruction of this.parsed.instructions)
                body.push(...this.instruction(instruction));

            // WebGPU validates the inter-stage interface strictly. Desktop GL
            // leaves an unwritten ARB vertex result undefined, so when a
            // fixed-function fragment stage consumes an enabled unit we
            // materialise its missing output using this shell's existing zero
            // value for undefined results.
            if (this.stage === "vertex") {
                for (const unit of this.options.forceVertexTexCoords || []) {
                    if (unit >= 0 && unit < MAX_TEXTURE_UNITS)
                        this.usedResults.add("texcoord" + unit);
                }
            }
            // Both stages share one compact GLState uniform. Supplying the
            // union makes the canonical field offsets identical in each WGSL
            // module even when the stages read different pieces of GL state.
            for (const field of this.options.forceStateFields || [])
                this.stateFields.add(field);

            const out = [];
            out.push("// generated by gl_arb_program.js r" + ARB_REVISION +
                " (" + this.stage + " program)");
            out.push("");
            const layout = stateLayout.buildLayout([...this.stateFields]);
            if (this.stateFields.size) {
                out.push(layout.structText);
                out.push("@group(1) @binding(0) var<uniform> glState : GLState;");
                out.push("");
            }
            /*
             * program.env and program.local share one binding: they have the
             * same shape and the guest writes both through the same entry
             * point.  Do not declare the binding when neither namespace is
             * read.  WebGPU's automatic pipeline layout drops unused globals;
             * retaining the declaration here made the executor submit a
             * binding which was absent from the resulting layout.
             *
             * The two stages take *different* bindings because program.env and
             * program.local are per-program namespaces: a bound vertex and
             * fragment program each carry their own, and a single shared block
             * left one stage reading the other program's parameters.
             */
            if (this.envUsed || this.localUsed) {
                out.push("struct ARBParams {");
                out.push("    env : array<vec4<f32>, " +
                    MAX_PROGRAM_PARAMETERS + ">,");
                out.push("    local : array<vec4<f32>, " +
                    MAX_PROGRAM_PARAMETERS + ">,");
                out.push("}");
                out.push("@group(1) @binding(" +
                    PARAMETER_BINDING[this.stage] +
                    ") var<uniform> arbParams : ARBParams;");
                out.push("");
            }
            for (const [unit, target] of this.textureUnits) {
                out.push("@group(2) @binding(" + (unit * 2) + ") var t" + unit +
                    " : " + wgslTextureType(target) + ";");
                out.push("@group(2) @binding(" + (unit * 2 + 1) + ") var s" +
                    unit + " : sampler;");
            }
            if (this.textureUnits.size) out.push("");
            for (const helper of this.helpers) out.push(HELPERS[helper], "");

            if (this.stage === "vertex") this.emitVertexShell(out, body);
            else this.emitFragmentShell(out, body);
            return out.join("\n") + "\n";
        }

        emitVertexShell(out, body) {
            const flatLocations = new Set(this.options.forceFlatVaryings || []);
            const varying = location => (flatLocations.has(location) ?
                "    @interpolate(flat) " : "    ") +
                "@location(" + location + ") ";
            out.push("struct VSIn {");
            for (const [, info] of this.usedAttributes)
                out.push("    @location(" + info.location + ") " + info.field +
                    " : " + vecType(info.components || 4) + ",");
            if (!this.usedAttributes.size)
                out.push("    @builtin(vertex_index) vertexIndex : u32,");
            out.push("}");
            out.push("");
            out.push("struct VSOut {");
            out.push("    @invariant @builtin(position) position : vec4<f32>,");
            out.push(varying(0) + "frontColor : vec4<f32>,");
            out.push(varying(1) + "frontSecondary : vec4<f32>,");
            out.push(varying(2) + "fogCoord : vec4<f32>,");
            for (let i = 0; i < 8; ++i)
                if (this.usedResults.has("texcoord" + i))
                    out.push(varying(3 + i) + "texcoord" + i +
                        " : vec4<f32>,");
            out.push("}");
            out.push("");
            out.push("@vertex");
            out.push("fn vs_main(vin : VSIn) -> VSOut {");
            out.push("    var result_position = vec4<f32>(0.0, 0.0, 0.0, 1.0);");
            out.push("    var frontColor = vec4<f32>(1.0);");
            out.push("    var frontSecondary = vec4<f32>(0.0);");
            out.push("    var backColor = vec4<f32>(1.0);");
            out.push("    var backSecondary = vec4<f32>(0.0);");
            out.push("    var fogCoordValue = vec4<f32>(0.0);");
            out.push("    var pointSize = vec4<f32>(1.0);");
            for (let i = 0; i < 8; ++i)
                if (this.usedResults.has("texcoord" + i))
                    out.push("    var texcoord" + i + " = vec4<f32>(0.0);");
            for (const name of this.parsed.temporaries)
                out.push("    var " + safe(name) + " = vec4<f32>(0.0);");
            for (const name of this.parsed.addresses)
                out.push("    var " + safe(name) + " = vec4<i32>(0);");
            for (const line of body) out.push("    " + line);
            if (this.parsed.options.has("ARB_position_invariant")) {
                // The option says the program does not write result.position
                // and the fixed-function transform supplies it -- and it must
                // be the *same* expression, or a depth pre-pass z-fights.
                out.push("    result_position = glState.mvp * vin.gl_Vertex;");
            }
            out.push("    var out : VSOut;");
            out.push("    var clip = result_position;");
            out.push("    clip.z = (clip.z + clip.w) * 0.5;");
            out.push("    clip.y = -clip.y;");
            out.push("    out.position = clip;");
            out.push("    out.frontColor = frontColor;");
            out.push("    out.frontSecondary = frontSecondary;");
            out.push("    out.fogCoord = fogCoordValue;");
            for (let i = 0; i < 8; ++i)
                if (this.usedResults.has("texcoord" + i))
                    out.push("    out.texcoord" + i + " = texcoord" + i + ";");
            out.push("    return out;");
            out.push("}");
        }

        emitFragmentShell(out, body) {
            out.push("struct FSIn {");
            out.push("    @builtin(position) position : vec4<f32>,");
            out.push("    @location(0) frontColor : vec4<f32>,");
            out.push("    @location(1) frontSecondary : vec4<f32>,");
            out.push("    @location(2) fogCoord : vec4<f32>,");
            for (let i = 0; i < 8; ++i)
                if (this.usedResults.has("in_texcoord" + i))
                    out.push("    @location(" + (3 + i) + ") texcoord" + i +
                        " : vec4<f32>,");
            out.push("}");
            out.push("");
            out.push("struct FSOut {");
            out.push("    @location(0) color0 : vec4<f32>,");
            if (this.usedResults.has("depth"))
                out.push("    @builtin(frag_depth) depth : f32,");
            out.push("}");
            out.push("");
            out.push("@fragment");
            out.push("fn fs_main(fin : FSIn) -> FSOut {");
            out.push("    var color0 = vec4<f32>(0.0, 0.0, 0.0, 1.0);");
            out.push("    var depthValue = fin.position.z;");
            for (const name of this.parsed.temporaries)
                out.push("    var " + safe(name) + " = vec4<f32>(0.0);");
            for (const line of body) out.push("    " + line);
            out.push("    var out : FSOut;");
            out.push("    out.color0 = color0;");
            if (this.usedResults.has("depth"))
                out.push("    out.depth = depthValue;");
            out.push("    return out;");
            out.push("}");
        }

        instruction(instruction) {
            const info = instruction.info;
            const lines = [];

            if (info.kill) {
                const source = this.sourceExpression(instruction.sources[0]);
                lines.push("if (any(" + source + " < vec4<f32>(0.0))) { discard; }");
                this.usesKill = true;
                return lines;
            }

            let value;
            if (info.texture) {
                value = this.textureInstruction(instruction);
            } else if (info.address) {
                const source = this.sourceExpression(instruction.sources[0]);
                const target = this.resolveDestination(instruction.destination);
                this.usesAddress = true;
                lines.push(target.name + " = vec4<i32>(i32(floor(" + source +
                    ".x)));");
                return lines;
            } else {
                const sources = instruction.sources.map(source =>
                    this.sourceExpression(source));
                value = info.emit(sources);
                if (info.emit === HELPERS.arbLit) this.helpers.add("arbLit");
            }
            if (instruction.opcode === "LIT") this.helpers.add("arbLit");
            if (instruction.opcode === "LOG") this.helpers.add("arbLog");
            if (instruction.saturate)
                value = "clamp(" + value + ", vec4<f32>(0.0), vec4<f32>(1.0))";

            const destination = this.resolveDestination(instruction.destination);
            const mask = instruction.destination.mask;
            if (mask === "xyzw" || mask === "") {
                lines.push(destination.name + " = " + value + ";");
            } else {
                const temporary = "_a" + (this.temporary++);
                lines.push("let " + temporary + " = " + value + ";");
                for (const component of mask)
                    lines.push(destination.name + "." + component + " = " +
                        temporary + "." + component + ";");
            }
            return lines;
        }

        textureInstruction(instruction) {
            const unit = this.textureUnit(instruction.texture);
            const target = normalizeTextureTarget(instruction.textureTarget);
            this.textureUnits.set(unit, target);
            const source = this.sourceExpression(instruction.sources[0]);
            const coordinate = target === "CUBE" || target === "3D" ?
                source + ".xyz" : source + ".xy";
            if (instruction.info.texture === "proj") {
                const divided = target === "CUBE" || target === "3D" ?
                    "(" + source + ".xyz / " + source + ".w)" :
                    "(" + source + ".xy / " + source + ".w)";
                return "textureSample(t" + unit + ", s" + unit + ", " + divided + ")";
            }
            if (instruction.info.texture === "bias")
                return "textureSampleBias(t" + unit + ", s" + unit + ", " +
                    coordinate + ", " + source + ".w)";
            return "textureSample(t" + unit + ", s" + unit + ", " + coordinate + ")";
        }

        textureUnit(path) {
            const match = /^texture\[(\d+)\]$/.exec(path) ||
                /^texture$/.exec(path);
            if (!match) throw new ARBError("unknown texture '" + path + "'", 0);
            const unit = match[1] ? parseInt(match[1], 10) : 0;
            if (unit < 0 || unit >= MAX_TEXTURE_UNITS)
                throw new ARBError("texture unit " + unit + " is out of range", 0);
            return unit;
        }

        sourceExpression(source) {
            let text = this.resolveSource(source.name);
            if (source.swizzle) text = applySwizzle(text, source.swizzle);
            if (source.absolute) text = "abs(" + text + ")";
            if (source.negate) text = "(-(" + text + "))";
            return text;
        }

        resolveSource(name) {
            const alias = this.parsed.aliases.get(name);
            if (alias) return this.resolveSource(alias);

            // A PARAM array element: `PARAM mvp[4] = { state.matrix.mvp };`
            // then `DP4 r0.x, mvp[0], pos;`. The matrix expands to its four
            // rows, which is the whole reason the canonical transform is
            // written as four DP4s.
            const indexed = /^([A-Za-z_$][A-Za-z0-9_$]*)\[(.+)\]$/.exec(name);
            if (indexed && this.parsed.params.has(indexed[1])) {
                const registers = this.paramRegisters(indexed[1]);
                const index = /^\s*(\d+)\s*$/.exec(indexed[2]);
                if (!index)
                    throw new ARBError("a PARAM array needs a constant index; '" +
                        indexed[2] + "' is not one", 0);
                const at = parseInt(index[1], 10);
                if (at >= registers.length)
                    throw new ARBError("PARAM " + indexed[1] + "[" + at +
                        "] is past the end of the array", 0);
                return registers[at];
            }

            if (this.parsed.temporaries.has(name)) return safe(name);
            if (this.parsed.addresses.has(name)) return safe(name);
            const attrib = this.parsed.attribs.get(name);
            if (attrib) return this.resolveSource(attrib);
            const param = this.parsed.params.get(name);
            if (param) return this.resolveParam(name, param);

            // program.env[n] / program.local[n], with optional relative
            // addressing through the address register.
            const parameter = /^program\.(env|local)\[(.+)\]$/.exec(name);
            if (parameter) {
                const which = parameter[1];
                if (which === "env") this.envUsed = true; else this.localUsed = true;
                return "arbParams." + which + "[" +
                    this.parameterIndex(parameter[2]) + "]";
            }
            if (name.startsWith("state."))
                return this.resolveState(name.slice(6));
            if (this.stage === "vertex") {
                const attribute = VERTEX_ATTRIBUTES[name];
                if (attribute) return this.useAttribute(name, attribute);
                const texcoord = /^vertex\.texcoord\[?(\d*)\]?$/.exec(name);
                if (texcoord) {
                    const unit = texcoord[1] ? parseInt(texcoord[1], 10) : 0;
                    return this.useAttribute(name, {
                        name: "gl_MultiTexCoord" + unit,
                        location: ATTR.gl_MultiTexCoord0 + unit,
                    });
                }
                const generic = /^vertex\.attrib\[(\d+)\]$/.exec(name);
                if (generic) {
                    const index = parseInt(generic[1], 10);
                    return this.useAttribute(name, {
                        name: "attrib" + index, location: index,
                    });
                }
            } else {
                if (name === "fragment.color" || name === "fragment.color.primary")
                    return "fin.frontColor";
                if (name === "fragment.color.secondary") return "fin.frontSecondary";
                if (name === "fragment.fogcoord") return "fin.fogCoord";
                if (name === "fragment.position") return "fin.position";
                const texcoord = /^fragment\.texcoord\[?(\d*)\]?$/.exec(name);
                if (texcoord) {
                    const unit = texcoord[1] ? parseInt(texcoord[1], 10) : 0;
                    this.usedResults.add("in_texcoord" + unit);
                    return "fin.texcoord" + unit;
                }
            }
            throw new ARBError("unknown source '" + name + "'", 0);
        }

        parameterIndex(text) {
            const numeric = /^\d+$/.exec(text.trim());
            if (numeric) {
                const index = parseInt(numeric[0], 10);
                if (index >= MAX_PROGRAM_PARAMETERS)
                    throw new ARBError("program parameter " + index +
                        " is beyond the " + MAX_PROGRAM_PARAMETERS +
                        " this implementation provides", 0);
                return String(index);
            }
            // Relative addressing: A0.x + k. WGSL indexes uniform arrays
            // dynamically, so this maps straight across.
            const relative = /^([A-Za-z_$][A-Za-z0-9_$]*)\.([xyzw])\s*(?:\+\s*(\d+))?$/
                .exec(text.trim());
            if (!relative)
                throw new ARBError("unsupported parameter index '" + text + "'", 0);
            this.usesAddress = true;
            const offset = relative[3] ? " + " + relative[3] : "";
            return "clamp(" + safe(relative[1]) + "." + relative[2] + offset +
                ", 0, " + (MAX_PROGRAM_PARAMETERS - 1) + ")";
        }

        /* Flattens a PARAM declaration into the registers it occupies. */
        paramRegisters(name) {
            if (this.paramArrays.has(name)) return this.paramArrays.get(name);
            const param = this.parsed.params.get(name);
            const registers = [];
            for (const entry of param.entries) {
                if (entry.kind === "constant") {
                    registers.push("vec4<f32>(" +
                        entry.values.map(formatFloat).join(", ") + ")");
                    continue;
                }
                const path = entry.path.startsWith("state.") ?
                    entry.path.slice(6) : entry.path;
                const matrix = this.stateMatrix(path);
                if (matrix) {
                    this.stateFields.add(matrix.field);
                    for (let row = 0; row < 4; ++row)
                        registers.push("vec4<f32>(" + [0, 1, 2, 3].map(column =>
                            matrix.matrix + "[" + column + "][" + row + "]")
                            .join(", ") + ")");
                    continue;
                }
                registers.push(this.resolveSource(entry.path));
            }
            this.paramArrays.set(name, registers);
            return registers;
        }

        /* The matrix behind a state.matrix.* binding, or null if the path is
         * not a whole matrix. */
        stateMatrix(path) {
            const binding = STATE_BINDINGS[path];
            return binding && binding.matrix ? binding : null;
        }

        resolveParam(name, param) {
            if (param.entries.length === 1 &&
                    param.entries[0].kind === "constant" && !param.arraySize) {
                const values = param.entries[0].values;
                return "vec4<f32>(" + values.map(formatFloat).join(", ") + ")";
            }
            if (param.entries.length === 1 &&
                    param.entries[0].kind === "binding" && !param.arraySize)
                return this.resolveSource(param.entries[0].path);
            // Naming a PARAM array without an index means its first register,
            // which is how a program written for one row spells it.
            return this.paramRegisters(name)[0];
        }

        resolveState(path) {
            const direct = STATE_BINDINGS[path];
            if (direct) {
                this.stateFields.add(direct.field);
                if (direct.vector) return direct.vector;
                // A matrix binding without a row selector means row 0; the
                // usual spelling is state.matrix.mvp[i] via a PARAM array.
                return "vec4<f32>(" + direct.matrix + "[0][0], " +
                    direct.matrix + "[1][0], " + direct.matrix + "[2][0], " +
                    direct.matrix + "[3][0])";
            }
            const row = /^(matrix\.[a-z.]*?)(?:\.row\[(\d+)\]|\[(\d+)\])$/.exec(path);
            if (row) {
                const binding = STATE_BINDINGS[row[1]];
                if (binding && binding.matrix) {
                    this.stateFields.add(binding.field);
                    const index = parseInt(row[2] !== undefined ? row[2] : row[3], 10);
                    // ARB rows are the matrix's rows; WGSL indexes columns, so
                    // the row is gathered rather than indexed.
                    return "vec4<f32>(" + [0, 1, 2, 3].map(c =>
                        binding.matrix + "[" + c + "][" + index + "]").join(", ") + ")";
                }
            }
            for (const entry of INDEXED_STATE) {
                const match = entry.pattern.exec(path);
                if (!match) continue;
                this.stateFields.add(entry.field);
                return entry.expr(match[1], match[2], match[3]);
            }
            throw new ARBError("unsupported state binding 'state." + path + "'", 0);
        }

        useAttribute(path, info) {
            const field = info.name;
            if (!this.usedAttributes.has(field))
                this.usedAttributes.set(field, {
                    field, location: info.location,
                    components: info.components || 4,
                });
            void path;
            const components = info.components || 4;
            if (components === 4) return "vin." + field;
            if (components === 3) return "vec4<f32>(vin." + field + ", 1.0)";
            return "vec4<f32>(vin." + field + ", 0.0, 0.0, 1.0)";
        }

        resolveDestination(destination) {
            const name = destination.name;
            const alias = this.parsed.aliases.get(name);
            if (alias) return this.resolveDestination({ ...destination, name: alias });
            if (this.parsed.temporaries.has(name)) return { name: safe(name) };
            if (this.parsed.addresses.has(name)) return { name: safe(name) };
            const output = this.parsed.outputs.get(name);
            if (output) return this.resolveDestination({ ...destination, name: output });

            if (this.stage === "vertex") {
                const texcoord = /^result\.texcoord\[?(\d*)\]?$/.exec(name);
                if (texcoord) {
                    const unit = texcoord[1] ? parseInt(texcoord[1], 10) : 0;
                    this.usedResults.add("texcoord" + unit);
                    return { name: "texcoord" + unit };
                }
                const mapped = VERTEX_RESULTS[name];
                if (mapped) {
                    this.usedResults.add(mapped);
                    if (mapped === "position") return { name: "result_position" };
                    if (mapped === "fogCoord") return { name: "fogCoordValue" };
                    return { name: mapped };
                }
            } else {
                const indexed = /^result\.color\[(\d+)\]$/.exec(name);
                if (indexed && indexed[1] === "0") return { name: "color0" };
                const mapped = FRAGMENT_RESULTS[name];
                if (mapped) {
                    this.usedResults.add(mapped);
                    return { name: mapped === "depth" ? "depthValue" : mapped };
                }
            }
            throw new ARBError("unknown destination '" + name + "'",
                destination.line);
        }
    }

    /* GL writes masks in xyzw or rgba; the generator only speaks xyzw. */
    function normalizeMask(text) {
        return String(text).replace(/[rgba]/g,
            ch => "xyzw"["rgba".indexOf(ch)]);
    }

    function safe(name) {
        return "arb_" + name.replace(/[^A-Za-z0-9_]/g, "_");
    }

    function vecType(components) {
        return components === 1 ? "f32" : "vec" + components + "<f32>";
    }

    function formatFloat(value) {
        if (Number.isInteger(value)) return value.toFixed(1);
        return String(value);
    }

    function wgslTextureType(target) {
        switch (target) {
        case "CUBE": return "texture_cube<f32>";
        case "3D": return "texture_3d<f32>";
        default: return "texture_2d<f32>";
        }
    }

    function normalizeTextureTarget(text) {
        const upper = String(text).toUpperCase();
        if (upper.indexOf("CUBE") >= 0) return "CUBE";
        if (upper.indexOf("3D") >= 0) return "3D";
        if (upper.indexOf("1D") >= 0) return "1D";
        if (upper.indexOf("RECT") >= 0) return "RECT";
        return "2D";
    }

    /* ARB swizzles are one to four components, and a single component
     * replicates -- MOV r0, c0.x moves x into all four. */
    function applySwizzle(expression, swizzle) {
        const cleaned = swizzle.replace(/[^xyzwrgba01]/g, "")
            .replace(/[rgba]/g, ch => "xyzw"["rgba".indexOf(ch)]);
        if (!cleaned.length) return expression;
        if (/[01]/.test(cleaned)) {
            const parts = [...cleaned].map(ch =>
                ch === "0" ? "0.0" : (ch === "1" ? "1.0" :
                    "(" + expression + ")." + ch));
            while (parts.length < 4) parts.push("0.0");
            return "vec4<f32>(" + parts.join(", ") + ")";
        }
        if (cleaned.length === 1)
            return "vec4<f32>((" + expression + ")." + cleaned + ")";
        if (cleaned.length === 4) return "(" + expression + ")." + cleaned;
        const parts = [...cleaned].map(ch => "(" + expression + ")." + ch);
        while (parts.length < 4) parts.push(parts[parts.length - 1]);
        return "vec4<f32>(" + parts.join(", ") + ")";
    }

    /* ================================================================== */
    /* Public API                                                         */
    /* ================================================================== */

    function compileARBProgram(source, options) {
        const result = { ok: false, log: "", target: null, errorPosition: -1 };
        const parser = new Parser(source);
        try {
            const parsed = parser.parse();
            const generator = new Generator(parsed, options);
            result.wgsl = generator.generate();
            result.target = parsed.target;
            result.stage = parsed.target;
            result.reflection = {
                stateFields: [...generator.stateFields],
                attributes: [...generator.usedAttributes.values()],
                textures: [...generator.textureUnits.entries()].map(
                    ([unit, target]) => ({ unit, target })),
                usesKill: generator.usesKill,
                usesAddress: generator.usesAddress,
                usesEnv: generator.envUsed,
                usesLocal: generator.localUsed,
                instructionCount: parsed.instructions.length,
                temporaryCount: parsed.temporaries.size,
                positionInvariant: parsed.options.has("ARB_position_invariant"),
                maxParameters: MAX_PROGRAM_PARAMETERS,
            };
            result.ok = true;
        } catch (error) {
            if (!(error instanceof ARBError)) throw error;
            result.log = "ERROR: line " + (error.arbLine || 0) + ": " +
                error.message;
            result.errorPosition = error.arbOffset >= 0 ? error.arbOffset :
                parser.currentOffset();
        }
        return result;
    }

    const api = {
        ARB_REVISION, MAX_PROGRAM_PARAMETERS, MAX_TEMPORARIES,
        PARAMETER_BINDING,
        compileARBProgram, lex, Parser, Generator, ARBError,
        INSTRUCTIONS, STATE_BINDINGS, applySwizzle,
    };
    global.GLARBProgram = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/browser/glbridge/gl-webgpu/gl_constants.js                                           0000644 0000000 0000000 00000114544 00000000000 020653  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated from openglproxy/opengl32_proxy.c -- the guest DLL is the
// authority for both the wire opcodes and the GL enum values it forwards.
// Regenerate rather than hand-edit: a mismatch here decodes every payload
// one field off and the symptom is arbitrary.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md section 6.1.

(function(global) {
    "use strict";

    const GLFN = {
        VIEWPORT: 1,
        CLEAR_COLOR: 2,
        CLEAR: 3,
        BEGIN: 4,
        END: 5,
        COLOR4F: 6,
        VERTEX3F: 7,
        FLUSH: 8,
        FINISH: 9,
        MATRIX_MODE: 10,
        LOAD_IDENTITY: 11,
        FRUSTUM: 12,
        ORTHO: 13,
        TRANSLATEF: 14,
        ROTATEF: 15,
        SCALEF: 16,
        PUSH_MATRIX: 17,
        POP_MATRIX: 18,
        ENABLE: 19,
        DISABLE: 20,
        DEPTH_FUNC: 21,
        CLEAR_DEPTH: 22,
        SHADE_MODEL: 23,
        CULL_FACE: 24,
        FRONT_FACE: 25,
        GEN_TEXTURES: 26,
        DELETE_TEXTURES: 27,
        BIND_TEXTURE: 28,
        TEX_IMAGE_2D: 29,
        TEX_SUB_IMAGE_2D: 30,
        TEX_PARAMETERI: 31,
        TEX_PARAMETERF: 32,
        PIXEL_STOREI: 33,
        TEX_ENVI: 34,
        TEX_ENVF: 35,
        TEX_COORD2F: 36,
        ENABLE_CLIENT_STATE: 37,
        DISABLE_CLIENT_STATE: 38,
        DRAW_ARRAYS: 39,
        DRAW_ELEMENTS: 40,
        BLEND_FUNC: 41,
        ALPHA_FUNC: 42,
        DEPTH_MASK: 43,
        COLOR_MASK: 44,
        SCISSOR: 45,
        LINE_WIDTH: 46,
        POLYGON_MODE: 47,
        ACTIVE_TEXTURE: 48,
        CLIENT_ACTIVE_TEXTURE: 49,
        MULTI_TEX_COORD4F: 50,
        NORMAL3F: 51,
        FOGF: 52,
        FOGI: 53,
        FOGFV: 54,
        MATERIALF: 55,
        MATERIALI: 56,
        MATERIALFV: 57,
        MATERIALIV: 58,
        TEX_ENVIV: 59,
        TEX_ENVFV: 60,
        LIGHTF: 61,
        LIGHTI: 62,
        LIGHTFV: 63,
        LIGHTIV: 64,
        LIGHT_MODELF: 65,
        LIGHT_MODELI: 66,
        LIGHT_MODELFV: 67,
        LIGHT_MODELIV: 68,
        LOAD_MATRIXF: 69,
        MULT_MATRIXF: 70,
        DEPTH_RANGE: 71,
        CLEAR_STENCIL: 72,
        STENCIL_FUNC: 73,
        STENCIL_MASK: 74,
        STENCIL_OP: 75,
        HINT: 76,
        POLYGON_OFFSET: 77,
        TEX_PARAMETERIV: 78,
        TEX_PARAMETERFV: 79,
        TEX_GENI: 80,
        TEX_GENF: 81,
        TEX_GENIV: 82,
        TEX_GENFV: 83,
        CLIP_PLANE: 84,
        COLOR_MATERIAL: 85,
        PUSH_ATTRIB: 86,
        POP_ATTRIB: 87,
        PUSH_CLIENT_ATTRIB: 88,
        POP_CLIENT_ATTRIB: 89,
        DRAW_BUFFER: 90,
        READ_BUFFER: 91,
        COPY_TEX_IMAGE_2D: 92,
        COPY_TEX_SUB_IMAGE_2D: 93,
        READ_PIXELS: 94,
        BLEND_COLOR: 95,
        BLEND_EQUATION: 96,
        BLEND_FUNC_SEPARATE: 97,
        SAMPLE_COVERAGE: 98,
        GENERATE_MIPMAP: 99,
        FOG_COORDF: 100,
        SECONDARY_COLOR3F: 101,
        POINT_PARAMETERF: 102,
        POINT_PARAMETERFV: 103,
        COMPRESSED_TEX_IMAGE_2D: 104,
        TEX_IMAGE_3D: 105,
        TEX_SUB_IMAGE_3D: 106,
        COMPRESSED_TEX_IMAGE_1D: 107,
        COMPRESSED_TEX_IMAGE_3D: 108,
        COMPRESSED_TEX_SUB_IMAGE_1D: 109,
        COMPRESSED_TEX_SUB_IMAGE_2D: 110,
        COMPRESSED_TEX_SUB_IMAGE_3D: 111,
        WINDOW_POS3F: 112,
        POINT_PARAMETERI: 113,
        POINT_PARAMETERIV: 114,
        POINT_SIZE: 115,
        LINE_STIPPLE: 116,
        LOGIC_OP: 117,
        PIXEL_TRANSFERF: 118,
        PIXEL_TRANSFERI: 119,
        PIXEL_ZOOM: 120,
        DRAW_PIXELS: 121,
        BITMAP: 122,
        COPY_PIXELS: 123,
        TEX_IMAGE_1D: 124,
        TEX_SUB_IMAGE_1D: 125,
        COPY_TEX_IMAGE_1D: 126,
        COPY_TEX_SUB_IMAGE_1D: 127,
        CLEAR_ACCUM: 128,
        ACCUM: 129,
        POLYGON_STIPPLE: 130,
        PIXEL_MAPFV: 131,
        PIXEL_MAPUIV: 132,
        PIXEL_MAPUSV: 133,
        TEX_COORD4F: 134,
        VERTEX4F: 135,
        RASTER_POS4F: 136,
        BLEND_EQUATION_SEPARATE: 137,
        DRAW_BUFFERS: 138,
        STENCIL_OP_SEPARATE: 139,
        STENCIL_FUNC_SEPARATE: 140,
        STENCIL_MASK_SEPARATE: 141,
        CREATE_PROGRAM: 142,
        CREATE_SHADER: 143,
        DELETE_PROGRAM: 144,
        DELETE_SHADER: 145,
        ATTACH_SHADER: 146,
        DETACH_SHADER: 147,
        SHADER_SOURCE: 148,
        COMPILE_SHADER: 149,
        LINK_PROGRAM: 150,
        USE_PROGRAM: 151,
        VALIDATE_PROGRAM: 152,
        BIND_ATTRIB_LOCATION: 153,
        MAP_UNIFORM_LOCATION: 154,
        MAP_ATTRIB_LOCATION: 155,
        UNIFORM_FV: 156,
        UNIFORM_IV: 157,
        UNIFORM_MATRIX_FV: 158,
        VERTEX_ATTRIB4F: 159,
        ENABLE_VERTEX_ATTRIB_ARRAY: 160,
        DISABLE_VERTEX_ATTRIB_ARRAY: 161,
        DRAW_ARRAYS_GL2: 162,
        DRAW_ELEMENTS_GL2: 163,
        UNIFORM_MATRIX_RECT_FV: 164,
        GEN_FRAMEBUFFERS: 165,
        DELETE_FRAMEBUFFERS: 166,
        BIND_FRAMEBUFFER: 167,
        FRAMEBUFFER_TEXTURE: 168,
        FRAMEBUFFER_RENDERBUFFER: 169,
        GEN_RENDERBUFFERS: 170,
        DELETE_RENDERBUFFERS: 171,
        BIND_RENDERBUFFER: 172,
        RENDERBUFFER_STORAGE: 173,
        QUERY_OBJECT_IV: 174,
        QUERY_OBJECT_LOG: 175,
        CHECK_FRAMEBUFFER_STATUS: 176,
        QUERY_ACTIVE: 177,
        GEN_QUERIES: 178,
        DELETE_QUERIES: 179,
        BEGIN_QUERY: 180,
        END_QUERY: 181,
        GEN_PROGRAMS_ARB: 182,
        DELETE_PROGRAMS_ARB: 183,
        BIND_PROGRAM_ARB: 184,
        PROGRAM_STRING_ARB: 185,
        PROGRAM_PARAMETER_FV_ARB: 186,
        PROGRAM_PARAMETER_DV_ARB: 187,
        QUERY_PROGRAM_IV_ARB: 188,
        QUERY_PROGRAM_PARAMETER_FV_ARB: 189,
        QUERY_PROGRAM_PARAMETER_DV_ARB: 190,
        QUERY_PROGRAM_STRING_ARB: 191,
        QUERY_GL_STRING: 192,
        QUERY_INTEGER: 193,
        GEN_BUFFERS: 194,
        DELETE_BUFFERS: 195,
        BIND_BUFFER: 196,
        BUFFER_DATA: 197,
        BUFFER_SUB_DATA: 198,
        VERTEX_POINTER_VBO: 199,
        COLOR_POINTER_VBO: 200,
        TEX_COORD_POINTER_VBO: 201,
        NORMAL_POINTER_VBO: 202,
        SECONDARY_COLOR_POINTER_VBO: 203,
        FOG_COORD_POINTER_VBO: 204,
        VERTEX_ATTRIB_POINTER_VBO: 205,
        DRAW_ARRAYS_DIRECT: 206,
        DRAW_ELEMENTS_DIRECT: 207,
        DRAW_RANGE_ELEMENTS_DIRECT: 208,
        MULTI_DRAW_ARRAYS_DIRECT: 209,
        MULTI_DRAW_ELEMENTS_DIRECT: 210,
        QUERY_ERROR: 211,
        QUERY_LOCATION: 212,
        QUERY_UNIFORM: 213,
        INVALIDATE_PROGRAM_LOCATIONS: 214,
        COPY_TEX_SUB_IMAGE_3D: 215,
        QUERY_OBJECT_BATCH: 216,
        BLIT_FRAMEBUFFER: 217,
    };

    // Control records the guest emits outside the GLFN numbering.
    const CTRL = {
        MAKE_CURRENT: 0xFFF0,
        RELEASE_CURRENT: 0xFFF1,
        DESTROY_CONTEXT: 0xFFF2,
        // What the guest's window manager says about the drawing window: shown,
        // minimised, covered by other windows entirely or in part (the parts
        // that show follow). See windowState() in gl_executor.js.
        WINDOW_STATE: 0xFFF3,
    };

    const GL = {
        FALSE: 0,
        TRUE: 1,
        NO_ERROR: 0,
        ZERO: 0,
        ONE: 1,
        NONE: 0,
        VENDOR: 0x1F00,
        RENDERER: 0x1F01,
        VERSION: 0x1F02,
        EXTENSIONS: 0x1F03,
        COLOR_BUFFER_BIT: 0x00004000,
        DEPTH_BUFFER_BIT: 0x00000100,
        STENCIL_BUFFER_BIT: 0x00000400,
        NEVER: 0x0200,
        LESS: 0x0201,
        EQUAL: 0x0202,
        LEQUAL: 0x0203,
        GREATER: 0x0204,
        NOTEQUAL: 0x0205,
        GEQUAL: 0x0206,
        ALWAYS: 0x0207,
        POINTS: 0x0000,
        LINES: 0x0001,
        LINE_LOOP: 0x0002,
        LINE_STRIP: 0x0003,
        TRIANGLES: 0x0004,
        TRIANGLE_STRIP: 0x0005,
        TRIANGLE_FAN: 0x0006,
        QUADS: 0x0007,
        QUAD_STRIP: 0x0008,
        POLYGON: 0x0009,
        FRONT: 0x0404,
        BACK: 0x0405,
        FRONT_AND_BACK: 0x0408,
        CW: 0x0900,
        CCW: 0x0901,
        CURRENT_COLOR: 0x0B00,
        CURRENT_INDEX: 0x0B01,
        CURRENT_NORMAL: 0x0B02,
        CURRENT_TEXTURE_COORDS: 0x0B03,
        POINT_SMOOTH: 0x0B10,
        POINT_SIZE: 0x0B11,
        POINT_SIZE_RANGE: 0x0B12,
        POINT_SIZE_GRANULARITY: 0x0B13,
        LINE_SMOOTH: 0x0B20,
        LINE_WIDTH: 0x0B21,
        LINE_WIDTH_RANGE: 0x0B22,
        LINE_STIPPLE: 0x0B24,
        LINE_STIPPLE_PATTERN: 0x0B25,
        LINE_STIPPLE_REPEAT: 0x0B26,
        LIST_BASE: 0x0B32,
        POLYGON_MODE: 0x0B40,
        CULL_FACE: 0x0B44,
        CULL_FACE_MODE: 0x0B45,
        FRONT_FACE: 0x0B46,
        LIGHTING: 0x0B50,
        SHADE_MODEL: 0x0B54,
        FOG: 0x0B60,
        FOG_INDEX: 0x0B61,
        FOG_DENSITY: 0x0B62,
        FOG_START: 0x0B63,
        FOG_END: 0x0B64,
        FOG_MODE: 0x0B65,
        FOG_COLOR: 0x0B66,
        DEPTH_RANGE: 0x0B70,
        DEPTH_TEST: 0x0B71,
        DEPTH_WRITEMASK: 0x0B72,
        DEPTH_CLEAR_VALUE: 0x0B73,
        DEPTH_FUNC: 0x0B74,
        ACCUM_CLEAR_VALUE: 0x0B80,
        STENCIL_TEST: 0x0B90,
        STENCIL_CLEAR_VALUE: 0x0B91,
        STENCIL_FUNC: 0x0B92,
        STENCIL_VALUE_MASK: 0x0B93,
        STENCIL_FAIL: 0x0B94,
        STENCIL_PASS_DEPTH_FAIL: 0x0B95,
        STENCIL_PASS_DEPTH_PASS: 0x0B96,
        STENCIL_REF: 0x0B97,
        STENCIL_WRITEMASK: 0x0B98,
        ALPHA_TEST: 0x0BC0,
        ALPHA_TEST_FUNC: 0x0BC1,
        ALPHA_TEST_REF: 0x0BC2,
        DITHER: 0x0BD0,
        BLEND_DST: 0x0BE0,
        BLEND_SRC: 0x0BE1,
        BLEND: 0x0BE2,
        BLEND_DST_RGB: 0x80C8,
        BLEND_SRC_RGB: 0x80C9,
        BLEND_DST_ALPHA: 0x80CA,
        BLEND_SRC_ALPHA: 0x80CB,
        BLEND_EQUATION_RGB: 0x8009,
        BLEND_EQUATION_ALPHA: 0x883D,
        LOGIC_OP: 0x0BF1,
        INDEX_LOGIC_OP: 0x0BF1,
        COLOR_LOGIC_OP: 0x0BF2,
        SCISSOR_BOX: 0x0C10,
        SCISSOR_TEST: 0x0C11,
        INDEX_CLEAR_VALUE: 0x0C20,
        INDEX_WRITEMASK: 0x0C21,
        COLOR_CLEAR_VALUE: 0x0C22,
        COLOR_WRITEMASK: 0x0C23,
        DOUBLEBUFFER: 0x0C32,
        STEREO: 0x0C33,
        RENDER_MODE: 0x0C40,
        RGBA_MODE: 0x0C31,
        FEEDBACK_BUFFER_POINTER: 0x0DF0,
        FEEDBACK_BUFFER_SIZE: 0x0DF1,
        FEEDBACK_BUFFER_TYPE: 0x0DF2,
        SELECTION_BUFFER_POINTER: 0x0DF3,
        SELECTION_BUFFER_SIZE: 0x0DF4,
        PERSPECTIVE_CORRECTION_HINT: 0x0C50,
        POINT_SMOOTH_HINT: 0x0C51,
        LINE_SMOOTH_HINT: 0x0C52,
        POLYGON_SMOOTH_HINT: 0x0C53,
        FOG_HINT: 0x0C54,
        TEXTURE_GEN_S: 0x0C60,
        TEXTURE_GEN_T: 0x0C61,
        TEXTURE_GEN_R: 0x0C62,
        TEXTURE_GEN_Q: 0x0C63,
        MAX_LIGHTS: 0x0D31,
        MAX_EVAL_ORDER: 0x0D30,
        MAX_CLIP_PLANES: 0x0D32,
        MAX_TEXTURE_SIZE: 0x0D33,
        MAX_3D_TEXTURE_SIZE: 0x8073,
        MAX_CUBE_MAP_TEXTURE_SIZE: 0x851C,
        MAX_PIXEL_MAP_TABLE: 0x0D34,
        MAX_ATTRIB_STACK_DEPTH: 0x0D35,
        MAX_MODELVIEW_STACK_DEPTH: 0x0D36,
        MAX_NAME_STACK_DEPTH: 0x0D37,
        MAX_PROJECTION_STACK_DEPTH: 0x0D38,
        MAX_TEXTURE_STACK_DEPTH: 0x0D39,
        MAX_VIEWPORT_DIMS: 0x0D3A,
        MAX_CLIENT_ATTRIB_STACK_DEPTH: 0x0D3B,
        SUBPIXEL_BITS: 0x0D50,
        RED_BITS: 0x0D52,
        GREEN_BITS: 0x0D53,
        BLUE_BITS: 0x0D54,
        ALPHA_BITS: 0x0D55,
        DEPTH_BITS: 0x0D56,
        STENCIL_BITS: 0x0D57,
        MATRIX_MODE: 0x0BA0,
        VIEWPORT: 0x0BA2,
        MODELVIEW_MATRIX: 0x0BA6,
        PROJECTION_MATRIX: 0x0BA7,
        TEXTURE_MATRIX: 0x0BA8,
        MODELVIEW_STACK_DEPTH: 0x0BA3,
        PROJECTION_STACK_DEPTH: 0x0BA4,
        TEXTURE_STACK_DEPTH: 0x0BA5,
        COLOR_MATRIX_SGI: 0x80B1,
        COLOR_MATRIX_STACK_DEPTH_SGI: 0x80B2,
        MAX_COLOR_MATRIX_STACK_DEPTH_SGI: 0x80B3,
        POST_COLOR_MATRIX_RED_SCALE_SGI: 0x80B4,
        POST_COLOR_MATRIX_GREEN_SCALE_SGI: 0x80B5,
        POST_COLOR_MATRIX_BLUE_SCALE_SGI: 0x80B6,
        POST_COLOR_MATRIX_ALPHA_SCALE_SGI: 0x80B7,
        POST_COLOR_MATRIX_RED_BIAS_SGI: 0x80B8,
        POST_COLOR_MATRIX_GREEN_BIAS_SGI: 0x80B9,
        POST_COLOR_MATRIX_BLUE_BIAS_SGI: 0x80BA,
        POST_COLOR_MATRIX_ALPHA_BIAS_SGI: 0x80BB,
        ATTRIB_STACK_DEPTH: 0x0BB0,
        CLIENT_ATTRIB_STACK_DEPTH: 0x0BB1,
        UNPACK_ALIGNMENT: 0x0CF5,
        PACK_ALIGNMENT: 0x0D05,
        TEXTURE_1D: 0x0DE0,
        TEXTURE_2D: 0x0DE1,
        TEXTURE_3D: 0x806F,
        TEXTURE_WRAP_R: 0x8072,
        TEXTURE_BINDING_1D: 0x8068,
        POLYGON_OFFSET_FILL: 0x8037,
        TEXTURE_BINDING_2D: 0x8069,
        TEXTURE_BINDING_3D: 0x806A,
        TEXTURE_DEPTH: 0x8071,
        RESCALE_NORMAL: 0x803A,
        LIGHT_MODEL_COLOR_CONTROL: 0x81F8,
        SINGLE_COLOR: 0x81F9,
        SEPARATE_SPECULAR_COLOR: 0x81FA,
        CLAMP_TO_EDGE: 0x812F,
        CONSTANT_COLOR: 0x8001,
        ONE_MINUS_CONSTANT_COLOR: 0x8002,
        CONSTANT_ALPHA: 0x8003,
        ONE_MINUS_CONSTANT_ALPHA: 0x8004,
        FUNC_ADD: 0x8006,
        MIN: 0x8007,
        MAX: 0x8008,
        FUNC_SUBTRACT: 0x800A,
        FUNC_REVERSE_SUBTRACT: 0x800B,
        TEXTURE_CUBE_MAP: 0x8513,
        TEXTURE_CUBE_MAP_POSITIVE_X: 0x8515,
        TEXTURE_CUBE_MAP_NEGATIVE_X: 0x8516,
        TEXTURE_CUBE_MAP_POSITIVE_Y: 0x8517,
        TEXTURE_CUBE_MAP_NEGATIVE_Y: 0x8518,
        TEXTURE_CUBE_MAP_POSITIVE_Z: 0x8519,
        TEXTURE_CUBE_MAP_NEGATIVE_Z: 0x851A,
        PROXY_TEXTURE_CUBE_MAP: 0x851B,
        TEXTURE_BINDING_CUBE_MAP: 0x8514,
        SAMPLE_COVERAGE: 0x80A0,
        SAMPLE_COVERAGE_VALUE: 0x80AA,
        SAMPLE_COVERAGE_INVERT: 0x80AB,
        DOT3_RGB: 0x86AE,
        DOT3_RGBA: 0x86AF,
        COMPRESSED_ALPHA: 0x84E9,
        COMPRESSED_LUMINANCE: 0x84EA,
        COMPRESSED_LUMINANCE_ALPHA: 0x84EB,
        COMPRESSED_INTENSITY: 0x84EC,
        COMPRESSED_RGB: 0x84ED,
        COMPRESSED_RGBA: 0x84EE,
        TEXTURE_COMPRESSION_HINT: 0x84EF,
        TEXTURE_COMPRESSED_IMAGE_SIZE: 0x86A0,
        TEXTURE_COMPRESSED: 0x86A1,
        NUM_COMPRESSED_TEXTURE_FORMATS: 0x86A2,
        COMPRESSED_TEXTURE_FORMATS: 0x86A3,
        COMPRESSED_RGB_S3TC_DXT1_EXT: 0x83F0,
        COMPRESSED_RGBA_S3TC_DXT1_EXT: 0x83F1,
        COMPRESSED_RGBA_S3TC_DXT3_EXT: 0x83F2,
        COMPRESSED_RGBA_S3TC_DXT5_EXT: 0x83F3,
        COMPRESSED_SRGB_S3TC_DXT1_EXT: 0x8C4C,
        COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: 0x8C4D,
        COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: 0x8C4E,
        COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: 0x8C4F,
        GENERATE_MIPMAP: 0x8191,
        GENERATE_MIPMAP_HINT: 0x8192,
        TEXTURE_COMPARE_MODE_ARB: 0x884C,
        TEXTURE_COMPARE_FUNC_ARB: 0x884D,
        COMPARE_R_TO_TEXTURE_ARB: 0x884E,
        DEPTH_TEXTURE_MODE: 0x884B,
        DEPTH_COMPONENT16: 0x81A5,
        DEPTH_COMPONENT24: 0x81A6,
        DEPTH_COMPONENT32: 0x81A7,
        DEPTH_COMPONENT32F: 0x8CAC,
        DEPTH_STENCIL: 0x84F9,
        UNSIGNED_INT_24_8: 0x84FA,
        DEPTH24_STENCIL8: 0x88F0,
        DEPTH32F_STENCIL8: 0x8CAD,
        FLOAT_32_UNSIGNED_INT_24_8_REV: 0x8DAD,
        FOG_COORDINATE_SOURCE_EXT: 0x8450,
        FOG_COORDINATE_EXT: 0x8451,
        FRAGMENT_DEPTH_EXT: 0x8452,
        CURRENT_FOG_COORDINATE_EXT: 0x8453,
        FOG_COORDINATE_ARRAY_TYPE_EXT: 0x8454,
        FOG_COORDINATE_ARRAY_STRIDE_EXT: 0x8455,
        FOG_COORDINATE_ARRAY_POINTER_EXT: 0x8456,
        FOG_COORDINATE_ARRAY_EXT: 0x8457,
        COLOR_SUM_EXT: 0x8458,
        CURRENT_SECONDARY_COLOR_EXT: 0x8459,
        SECONDARY_COLOR_ARRAY_SIZE_EXT: 0x845A,
        SECONDARY_COLOR_ARRAY_TYPE_EXT: 0x845B,
        SECONDARY_COLOR_ARRAY_STRIDE_EXT: 0x845C,
        SECONDARY_COLOR_ARRAY_POINTER_EXT: 0x845D,
        SECONDARY_COLOR_ARRAY_EXT: 0x845E,
        POINT_SIZE_MIN_ARB: 0x8126,
        POINT_SIZE_MAX_ARB: 0x8127,
        POINT_FADE_THRESHOLD_SIZE_ARB: 0x8128,
        POINT_DISTANCE_ATTENUATION_ARB: 0x8129,
        INCR_WRAP_EXT: 0x8507,
        DECR_WRAP_EXT: 0x8508,
        MIRRORED_REPEAT_ARB: 0x8370,
        POINT_SPRITE_ARB: 0x8861,
        COORD_REPLACE_ARB: 0x8862,
        ARRAY_BUFFER_ARB: 0x8892,
        ELEMENT_ARRAY_BUFFER_ARB: 0x8893,
        ARRAY_BUFFER_BINDING_ARB: 0x8894,
        ELEMENT_ARRAY_BUFFER_BINDING_ARB: 0x8895,
        PIXEL_PACK_BUFFER: 0x88EB,
        PIXEL_UNPACK_BUFFER: 0x88EC,
        PIXEL_PACK_BUFFER_BINDING: 0x88ED,
        PIXEL_UNPACK_BUFFER_BINDING: 0x88EF,
        STREAM_DRAW_ARB: 0x88E0,
        STATIC_DRAW_ARB: 0x88E4,
        DYNAMIC_DRAW_ARB: 0x88E8,
        READ_ONLY_ARB: 0x88B8,
        WRITE_ONLY_ARB: 0x88B9,
        READ_WRITE_ARB: 0x88BA,
        BUFFER_SIZE_ARB: 0x8764,
        BUFFER_USAGE_ARB: 0x8765,
        BUFFER_ACCESS_ARB: 0x88BB,
        BUFFER_MAPPED_ARB: 0x88BC,
        BUFFER_MAP_POINTER_ARB: 0x88BD,
        SAMPLES_PASSED: 0x8914,
        QUERY_COUNTER_BITS: 0x8864,
        CURRENT_QUERY: 0x8865,
        QUERY_RESULT: 0x8866,
        QUERY_RESULT_AVAILABLE: 0x8867,
        ANY_SAMPLES_PASSED: 0x8C2F,
        ANY_SAMPLES_PASSED_CONSERVATIVE: 0x8D6A,
        VERTEX_ARRAY_SIZE: 0x807A,
        VERTEX_ARRAY_TYPE: 0x807B,
        VERTEX_ARRAY_STRIDE: 0x807C,
        VERTEX_ARRAY_POINTER: 0x808E,
        NORMAL_ARRAY_TYPE: 0x807E,
        NORMAL_ARRAY_STRIDE: 0x807F,
        NORMAL_ARRAY_POINTER: 0x808F,
        COLOR_ARRAY_SIZE: 0x8081,
        COLOR_ARRAY_TYPE: 0x8082,
        COLOR_ARRAY_STRIDE: 0x8083,
        COLOR_ARRAY_POINTER: 0x8090,
        INDEX_ARRAY: 0x8077,
        INDEX_ARRAY_TYPE: 0x8085,
        INDEX_ARRAY_STRIDE: 0x8086,
        INDEX_ARRAY_POINTER: 0x8091,
        TEXTURE_COORD_ARRAY_SIZE: 0x8088,
        TEXTURE_COORD_ARRAY_TYPE: 0x8089,
        TEXTURE_COORD_ARRAY_STRIDE: 0x808A,
        TEXTURE_COORD_ARRAY_POINTER: 0x8092,
        EDGE_FLAG_ARRAY: 0x8079,
        EDGE_FLAG_ARRAY_STRIDE: 0x808C,
        EDGE_FLAG_ARRAY_POINTER: 0x8093,
        ALIASED_LINE_WIDTH_RANGE: 0x846E,
        ACTIVE_TEXTURE_ARB: 0x84E0,
        CLIENT_ACTIVE_TEXTURE_ARB: 0x84E1,
        MAX_TEXTURE_UNITS_ARB: 0x84E2,
        TEXTURE0_ARB: 0x84C0,
        TEXTURE1_ARB: 0x84C1,
        TEXTURE2_ARB: 0x84C2,
        TEXTURE3_ARB: 0x84C3,
        TEXTURE4_ARB: 0x84C4,
        TEXTURE5_ARB: 0x84C5,
        TEXTURE6_ARB: 0x84C6,
        TEXTURE7_ARB: 0x84C7,
        COMBINE_ARB: 0x8570,
        MAX_TEXTURE_MAX_ANISOTROPY_EXT: 0x84FF,
        EXP: 0x0800,
        EXP2: 0x0801,
        KEEP: 0x1E00,
        REPLACE: 0x1E01,
        INCR: 0x1E02,
        DECR: 0x1E03,
        AMBIENT: 0x1200,
        DIFFUSE: 0x1201,
        SPECULAR: 0x1202,
        POSITION: 0x1203,
        SPOT_DIRECTION: 0x1204,
        SPOT_EXPONENT: 0x1205,
        SPOT_CUTOFF: 0x1206,
        CONSTANT_ATTENUATION: 0x1207,
        LINEAR_ATTENUATION: 0x1208,
        QUADRATIC_ATTENUATION: 0x1209,
        EMISSION: 0x1600,
        SHININESS: 0x1601,
        AMBIENT_AND_DIFFUSE: 0x1602,
        COLOR_INDEXES: 0x1603,
        LIGHT_MODEL_LOCAL_VIEWER: 0x0B51,
        LIGHT_MODEL_TWO_SIDE: 0x0B52,
        LIGHT_MODEL_AMBIENT: 0x0B53,
        LIGHT0: 0x4000,
        LIGHT1: 0x4001,
        LIGHT2: 0x4002,
        LIGHT3: 0x4003,
        LIGHT4: 0x4004,
        LIGHT5: 0x4005,
        LIGHT6: 0x4006,
        LIGHT7: 0x4007,
        MODULATE: 0x2100,
        DECAL: 0x2101,
        S: 0x2000,
        T: 0x2001,
        R: 0x2002,
        Q: 0x2003,
        OBJECT_LINEAR: 0x2401,
        EYE_LINEAR: 0x2400,
        SPHERE_MAP: 0x2402,
        TEXTURE_GEN_MODE: 0x2500,
        OBJECT_PLANE: 0x2501,
        EYE_PLANE: 0x2502,
        TEXTURE_ENV: 0x2300,
        TEXTURE_ENV_MODE: 0x2200,
        TEXTURE_ENV_COLOR: 0x2201,
        TEXTURE_MAG_FILTER: 0x2800,
        TEXTURE_MIN_FILTER: 0x2801,
        TEXTURE_WRAP_S: 0x2802,
        TEXTURE_WRAP_T: 0x2803,
        REPEAT: 0x2901,
        TEXTURE_BORDER_COLOR: 0x1004,
        TEXTURE_WIDTH: 0x1000,
        TEXTURE_HEIGHT: 0x1001,
        TEXTURE_COMPONENTS: 0x1003,
        TEXTURE_INTERNAL_FORMAT: 0x1003,
        TEXTURE_BORDER: 0x1005,
        TEXTURE_RED_SIZE: 0x805C,
        TEXTURE_GREEN_SIZE: 0x805D,
        TEXTURE_BLUE_SIZE: 0x805E,
        TEXTURE_ALPHA_SIZE: 0x805F,
        TEXTURE_LUMINANCE_SIZE: 0x8060,
        TEXTURE_INTENSITY_SIZE: 0x8061,
        TEXTURE_DEPTH_SIZE: 0x884A,
        POLYGON_OFFSET_FACTOR: 0x8038,
        POLYGON_OFFSET_UNITS: 0x2A00,
        CURRENT_EDGE_FLAG: 0x0B31,
        CURRENT_RASTER_POSITION: 0x0B07,
        CURRENT_RASTER_POSITION_VALID: 0x0B08,
        CURRENT_RASTER_DISTANCE: 0x0B09,
        CURRENT_RASTER_COLOR: 0x0B04,
        CURRENT_RASTER_INDEX: 0x0B05,
        CURRENT_RASTER_TEXTURE_COORDS: 0x0B06,
        COEFF: 0x0A00,
        ORDER: 0x0A01,
        DOMAIN: 0x0A02,
        MAP1_COLOR_4: 0x0D90,
        MAP1_INDEX: 0x0D91,
        MAP1_NORMAL: 0x0D92,
        MAP1_TEXTURE_COORD_1: 0x0D93,
        MAP1_TEXTURE_COORD_2: 0x0D94,
        MAP1_TEXTURE_COORD_3: 0x0D95,
        MAP1_TEXTURE_COORD_4: 0x0D96,
        MAP1_VERTEX_3: 0x0D97,
        MAP1_VERTEX_4: 0x0D98,
        MAP2_COLOR_4: 0x0DB0,
        MAP2_INDEX: 0x0DB1,
        MAP2_NORMAL: 0x0DB2,
        MAP2_TEXTURE_COORD_1: 0x0DB3,
        MAP2_TEXTURE_COORD_2: 0x0DB4,
        MAP2_TEXTURE_COORD_3: 0x0DB5,
        MAP2_TEXTURE_COORD_4: 0x0DB6,
        MAP2_VERTEX_3: 0x0DB7,
        MAP2_VERTEX_4: 0x0DB8,
        PIXEL_MAP_I_TO_I: 0x0C70,
        PIXEL_MAP_S_TO_S: 0x0C71,
        PIXEL_MAP_I_TO_R: 0x0C72,
        PIXEL_MAP_I_TO_G: 0x0C73,
        PIXEL_MAP_I_TO_B: 0x0C74,
        PIXEL_MAP_I_TO_A: 0x0C75,
        PIXEL_MAP_R_TO_R: 0x0C76,
        PIXEL_MAP_G_TO_G: 0x0C77,
        PIXEL_MAP_B_TO_B: 0x0C78,
        PIXEL_MAP_A_TO_A: 0x0C79,
        PIXEL_MAP_I_TO_I_SIZE: 0x0CB0,
        PIXEL_MAP_S_TO_S_SIZE: 0x0CB1,
        PIXEL_MAP_I_TO_R_SIZE: 0x0CB2,
        PIXEL_MAP_I_TO_G_SIZE: 0x0CB3,
        PIXEL_MAP_I_TO_B_SIZE: 0x0CB4,
        PIXEL_MAP_I_TO_A_SIZE: 0x0CB5,
        PIXEL_MAP_R_TO_R_SIZE: 0x0CB6,
        PIXEL_MAP_G_TO_G_SIZE: 0x0CB7,
        PIXEL_MAP_B_TO_B_SIZE: 0x0CB8,
        PIXEL_MAP_A_TO_A_SIZE: 0x0CB9,
        NEAREST: 0x2600,
        LINEAR: 0x2601,
        NEAREST_MIPMAP_NEAREST: 0x2700,
        LINEAR_MIPMAP_NEAREST: 0x2701,
        NEAREST_MIPMAP_LINEAR: 0x2702,
        LINEAR_MIPMAP_LINEAR: 0x2703,
        FLAT: 0x1D00,
        SMOOTH: 0x1D01,
        RENDER: 0x1C00,
        FEEDBACK: 0x1C01,
        SELECT: 0x1C02,
        "2D": 0x0600,
        "3D": 0x0601,
        "3D_COLOR": 0x0602,
        "3D_COLOR_TEXTURE": 0x0603,
        "4D_COLOR_TEXTURE": 0x0604,
        POINT_TOKEN: 0x0701,
        LINE_TOKEN: 0x0702,
        LINE_RESET_TOKEN: 0x0707,
        POLYGON_TOKEN: 0x0703,
        BITMAP_TOKEN: 0x0704,
        DRAW_PIXEL_TOKEN: 0x0705,
        COPY_PIXEL_TOKEN: 0x0706,
        PASS_THROUGH_TOKEN: 0x0700,
        DONT_CARE: 0x1100,
        FASTEST: 0x1101,
        NICEST: 0x1102,
        POINT: 0x1B00,
        LINE: 0x1B01,
        FILL: 0x1B02,
        MODELVIEW: 0x1700,
        PROJECTION: 0x1701,
        TEXTURE: 0x1702,
        COMPILE: 0x1300,
        COMPILE_AND_EXECUTE: 0x1301,
        TEXTURE_PRIORITY: 0x8066,
        TEXTURE_RESIDENT: 0x8067,
        TEXTURE_MIN_LOD: 0x813A,
        TEXTURE_MAX_LOD: 0x813B,
        TEXTURE_BASE_LEVEL: 0x813C,
        TEXTURE_MAX_LEVEL: 0x813D,
        COLOR_MATERIAL: 0x0B57,
        COLOR_MATERIAL_FACE: 0x0B55,
        COLOR_MATERIAL_PARAMETER: 0x0B56,
        CLIP_PLANE0: 0x3000,
        CLIP_PLANE1: 0x3001,
        CLIP_PLANE2: 0x3002,
        CLIP_PLANE3: 0x3003,
        CLIP_PLANE4: 0x3004,
        CLIP_PLANE5: 0x3005,
        BYTE: 0x1400,
        UNSIGNED_BYTE: 0x1401,
        SHORT: 0x1402,
        UNSIGNED_SHORT: 0x1403,
        INT: 0x1404,
        UNSIGNED_INT: 0x1405,
        FLOAT: 0x1406,
        "2_BYTES": 0x1407,
        "3_BYTES": 0x1408,
        "4_BYTES": 0x1409,
        DOUBLE: 0x140A,
        HALF_FLOAT_ARB: 0x140B,
        RED: 0x1903,
        GREEN: 0x1904,
        BLUE: 0x1905,
        ALPHA: 0x1906,
        RGB: 0x1907,
        RGBA: 0x1908,
        LUMINANCE: 0x1909,
        LUMINANCE_ALPHA: 0x190A,
        DEPTH_COMPONENT: 0x1902,
        RGB8: 0x8051,
        RGBA8: 0x8058,
        RGBA16: 0x805B,
        SRGB: 0x8C40,
        SRGB8: 0x8C41,
        SRGB_ALPHA: 0x8C42,
        SRGB8_ALPHA8: 0x8C43,
        SLUMINANCE_ALPHA: 0x8C44,
        SLUMINANCE8_ALPHA8: 0x8C45,
        SLUMINANCE: 0x8C46,
        SLUMINANCE8: 0x8C47,
        COMPRESSED_SRGB: 0x8C48,
        COMPRESSED_SRGB_ALPHA: 0x8C49,
        COMPRESSED_SLUMINANCE: 0x8C4A,
        COMPRESSED_SLUMINANCE_ALPHA: 0x8C4B,
        FRAMEBUFFER_SRGB: 0x8DB9,
        RGBA32F_ARB: 0x8814,
        RGB32F_ARB: 0x8815,
        ALPHA32F_ARB: 0x8816,
        LUMINANCE32F_ARB: 0x8818,
        LUMINANCE_ALPHA32F_ARB: 0x8819,
        RGBA16F_ARB: 0x881A,
        RGB16F_ARB: 0x881B,
        ALPHA16F_ARB: 0x881C,
        LUMINANCE16F_ARB: 0x881E,
        LUMINANCE_ALPHA16F_ARB: 0x881F,
        PACK_SWAP_BYTES: 0x0D00,
        PACK_LSB_FIRST: 0x0D01,
        PACK_ROW_LENGTH: 0x0D02,
        PACK_SKIP_ROWS: 0x0D03,
        PACK_SKIP_PIXELS: 0x0D04,
        PACK_SKIP_IMAGES: 0x806B,
        PACK_IMAGE_HEIGHT: 0x806C,
        BGR_EXT: 0x80E0,
        BGRA_EXT: 0x80E1,
        UNSIGNED_SHORT_4_4_4_4: 0x8033,
        UNSIGNED_SHORT_5_5_5_1: 0x8034,
        UNSIGNED_SHORT_5_6_5: 0x8363,
        UNSIGNED_SHORT_5_6_5_REV: 0x8364,
        UNSIGNED_SHORT_4_4_4_4_REV: 0x8365,
        UNSIGNED_SHORT_1_5_5_5_REV: 0x8366,
        UNSIGNED_INT_8_8_8_8: 0x8035,
        UNSIGNED_INT_8_8_8_8_REV: 0x8367,
        COLOR: 0x1800,
        DEPTH: 0x1801,
        STENCIL: 0x1802,
        UNPACK_SWAP_BYTES: 0x0CF0,
        UNPACK_LSB_FIRST: 0x0CF1,
        UNPACK_ROW_LENGTH: 0x0CF2,
        UNPACK_SKIP_ROWS: 0x0CF3,
        UNPACK_SKIP_PIXELS: 0x0CF4,
        UNPACK_SKIP_IMAGES: 0x806D,
        UNPACK_IMAGE_HEIGHT: 0x806E,
        INVALID_ENUM: 0x0500,
        INVALID_VALUE: 0x0501,
        INVALID_OPERATION: 0x0502,
        OUT_OF_MEMORY: 0x0505,
        INVALID_FRAMEBUFFER_OPERATION_EXT: 0x0506,
        VERTEX_ARRAY: 0x8074,
        NORMAL_ARRAY: 0x8075,
        COLOR_ARRAY: 0x8076,
        TEXTURE_COORD_ARRAY: 0x8078,
        VERTEX_ATTRIB_ARRAY_ENABLED: 0x8622,
        VERTEX_ATTRIB_ARRAY_SIZE: 0x8623,
        VERTEX_ATTRIB_ARRAY_STRIDE: 0x8624,
        VERTEX_ATTRIB_ARRAY_TYPE: 0x8625,
        CURRENT_VERTEX_ATTRIB: 0x8626,
        VERTEX_PROGRAM_POINT_SIZE: 0x8642,
        VERTEX_PROGRAM_TWO_SIDE: 0x8643,
        VERTEX_ATTRIB_ARRAY_POINTER: 0x8645,
        VERTEX_ATTRIB_ARRAY_NORMALIZED: 0x886A,
        VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: 0x889F,
        MAX_VERTEX_ATTRIBS: 0x8869,
        MAX_TEXTURE_COORDS: 0x8871,
        MAX_TEXTURE_IMAGE_UNITS: 0x8872,
        MAX_FRAGMENT_UNIFORM_COMPONENTS: 0x8B49,
        MAX_VERTEX_UNIFORM_COMPONENTS: 0x8B4A,
        MAX_VARYING_FLOATS: 0x8B4B,
        MAX_VERTEX_TEXTURE_IMAGE_UNITS: 0x8B4C,
        MAX_COMBINED_TEXTURE_IMAGE_UNITS: 0x8B4D,
        FRAGMENT_SHADER: 0x8B30,
        VERTEX_SHADER: 0x8B31,
        SHADER_TYPE: 0x8B4F,
        FLOAT_VEC2: 0x8B50,
        FLOAT_VEC3: 0x8B51,
        FLOAT_VEC4: 0x8B52,
        INT_VEC2: 0x8B53,
        INT_VEC3: 0x8B54,
        INT_VEC4: 0x8B55,
        BOOL: 0x8B56,
        BOOL_VEC2: 0x8B57,
        BOOL_VEC3: 0x8B58,
        BOOL_VEC4: 0x8B59,
        FLOAT_MAT2: 0x8B5A,
        FLOAT_MAT3: 0x8B5B,
        FLOAT_MAT4: 0x8B5C,
        SAMPLER_1D: 0x8B5D,
        SAMPLER_2D: 0x8B5E,
        SAMPLER_3D: 0x8B5F,
        SAMPLER_CUBE: 0x8B60,
        SAMPLER_1D_SHADOW: 0x8B61,
        SAMPLER_2D_SHADOW: 0x8B62,
        DELETE_STATUS: 0x8B80,
        COMPILE_STATUS: 0x8B81,
        LINK_STATUS: 0x8B82,
        VALIDATE_STATUS: 0x8B83,
        INFO_LOG_LENGTH: 0x8B84,
        ATTACHED_SHADERS: 0x8B85,
        ACTIVE_UNIFORMS: 0x8B86,
        ACTIVE_UNIFORM_MAX_LENGTH: 0x8B87,
        SHADER_SOURCE_LENGTH: 0x8B88,
        ACTIVE_ATTRIBUTES: 0x8B89,
        ACTIVE_ATTRIBUTE_MAX_LENGTH: 0x8B8A,
        FRAGMENT_SHADER_DERIVATIVE_HINT: 0x8B8B,
        SHADING_LANGUAGE_VERSION: 0x8B8C,
        CURRENT_PROGRAM: 0x8B8D,
        PROGRAM_OBJECT_ARB: 0x8B40,
        SHADER_OBJECT_ARB: 0x8B48,
        OBJECT_TYPE_ARB: 0x8B4E,
        OBJECT_SUBTYPE_ARB: 0x8B4F,
        OBJECT_DELETE_STATUS_ARB: 0x8B80,
        OBJECT_COMPILE_STATUS_ARB: 0x8B81,
        OBJECT_LINK_STATUS_ARB: 0x8B82,
        OBJECT_VALIDATE_STATUS_ARB: 0x8B83,
        OBJECT_INFO_LOG_LENGTH_ARB: 0x8B84,
        OBJECT_ATTACHED_OBJECTS_ARB: 0x8B85,
        OBJECT_ACTIVE_UNIFORMS_ARB: 0x8B86,
        OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB: 0x8B87,
        OBJECT_SHADER_SOURCE_LENGTH_ARB: 0x8B88,
        POINT_SPRITE_COORD_ORIGIN: 0x8CA0,
        LOWER_LEFT: 0x8CA1,
        UPPER_LEFT: 0x8CA2,
        STENCIL_BACK_FUNC: 0x8800,
        STENCIL_BACK_FAIL: 0x8801,
        STENCIL_BACK_PASS_DEPTH_FAIL: 0x8802,
        STENCIL_BACK_PASS_DEPTH_PASS: 0x8803,
        STENCIL_BACK_REF: 0x8CA3,
        STENCIL_BACK_VALUE_MASK: 0x8CA4,
        STENCIL_BACK_WRITEMASK: 0x8CA5,
        MAX_DRAW_BUFFERS: 0x8824,
        DRAW_BUFFER0: 0x8825,
        DRAW_BUFFER15: 0x8834,
        STENCIL_TEST_TWO_SIDE_EXT: 0x8910,
        ACTIVE_STENCIL_FACE_EXT: 0x8911,
        VERTEX_PROGRAM_ARB: 0x8620,
        PROGRAM_LENGTH_ARB: 0x8627,
        PROGRAM_STRING_ARB: 0x8628,
        PROGRAM_ERROR_POSITION_ARB: 0x864B,
        PROGRAM_BINDING_ARB: 0x8677,
        MAX_VERTEX_ATTRIBS_ARB: 0x8869,
        PROGRAM_ERROR_STRING_ARB: 0x8874,
        PROGRAM_FORMAT_ASCII_ARB: 0x8875,
        PROGRAM_FORMAT_ARB: 0x8876,
        PROGRAM_INSTRUCTIONS_ARB: 0x88A0,
        MAX_PROGRAM_INSTRUCTIONS_ARB: 0x88A1,
        PROGRAM_NATIVE_INSTRUCTIONS_ARB: 0x88A2,
        MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB: 0x88A3,
        PROGRAM_TEMPORARIES_ARB: 0x88A4,
        MAX_PROGRAM_TEMPORARIES_ARB: 0x88A5,
        PROGRAM_NATIVE_TEMPORARIES_ARB: 0x88A6,
        MAX_PROGRAM_NATIVE_TEMPORARIES_ARB: 0x88A7,
        PROGRAM_PARAMETERS_ARB: 0x88A8,
        MAX_PROGRAM_PARAMETERS_ARB: 0x88A9,
        PROGRAM_NATIVE_PARAMETERS_ARB: 0x88AA,
        MAX_PROGRAM_NATIVE_PARAMETERS_ARB: 0x88AB,
        PROGRAM_ATTRIBS_ARB: 0x88AC,
        MAX_PROGRAM_ATTRIBS_ARB: 0x88AD,
        PROGRAM_NATIVE_ATTRIBS_ARB: 0x88AE,
        MAX_PROGRAM_NATIVE_ATTRIBS_ARB: 0x88AF,
        PROGRAM_ADDRESS_REGISTERS_ARB: 0x88B0,
        MAX_PROGRAM_ADDRESS_REGISTERS_ARB: 0x88B1,
        PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB: 0x88B2,
        MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB: 0x88B3,
        MAX_PROGRAM_LOCAL_PARAMETERS_ARB: 0x88B4,
        MAX_PROGRAM_ENV_PARAMETERS_ARB: 0x88B5,
        PROGRAM_UNDER_NATIVE_LIMITS_ARB: 0x88B6,
        MAX_PROGRAM_MATRICES_ARB: 0x862F,
        FRAGMENT_PROGRAM_ARB: 0x8804,
        PROGRAM_ALU_INSTRUCTIONS_ARB: 0x8805,
        PROGRAM_TEX_INSTRUCTIONS_ARB: 0x8806,
        PROGRAM_TEX_INDIRECTIONS_ARB: 0x8807,
        PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB: 0x8808,
        PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB: 0x8809,
        PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB: 0x880A,
        MAX_PROGRAM_ALU_INSTRUCTIONS_ARB: 0x880B,
        MAX_PROGRAM_TEX_INSTRUCTIONS_ARB: 0x880C,
        MAX_PROGRAM_TEX_INDIRECTIONS_ARB: 0x880D,
        MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB: 0x880E,
        MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB: 0x880F,
        MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB: 0x8810,
        MAX_TEXTURE_COORDS_ARB: 0x8871,
        MAX_TEXTURE_IMAGE_UNITS_ARB: 0x8872,
        MAX_RENDERBUFFER_SIZE_EXT: 0x84E8,
        FRAMEBUFFER_BINDING_EXT: 0x8CA6,
        RENDERBUFFER_BINDING_EXT: 0x8CA7,
        READ_FRAMEBUFFER_EXT: 0x8CA8,
        DRAW_FRAMEBUFFER_EXT: 0x8CA9,
        READ_FRAMEBUFFER_BINDING_EXT: 0x8CAA,
        FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT: 0x8CD0,
        FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT: 0x8CD1,
        FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT: 0x8CD2,
        FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT: 0x8CD3,
        FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT: 0x8CD4,
        FRAMEBUFFER_COMPLETE_EXT: 0x8CD5,
        FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: 0x8CD6,
        FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: 0x8CD7,
        FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: 0x8CD9,
        FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: 0x8CDA,
        FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: 0x8CDB,
        FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: 0x8CDC,
        FRAMEBUFFER_UNSUPPORTED_EXT: 0x8CDD,
        MAX_COLOR_ATTACHMENTS_EXT: 0x8CDF,
        COLOR_ATTACHMENT0_EXT: 0x8CE0,
        COLOR_ATTACHMENT15_EXT: 0x8CEF,
        DEPTH_ATTACHMENT_EXT: 0x8D00,
        STENCIL_ATTACHMENT_EXT: 0x8D20,
        FRAMEBUFFER_EXT: 0x8D40,
        RENDERBUFFER_EXT: 0x8D41,
        RENDERBUFFER_WIDTH_EXT: 0x8D42,
        RENDERBUFFER_HEIGHT_EXT: 0x8D43,
        RENDERBUFFER_INTERNAL_FORMAT_EXT: 0x8D44,
        STENCIL_INDEX1_EXT: 0x8D46,
        STENCIL_INDEX4_EXT: 0x8D47,
        STENCIL_INDEX8_EXT: 0x8D48,
        STENCIL_INDEX16_EXT: 0x8D49,
        RENDERBUFFER_RED_SIZE_EXT: 0x8D50,
        RENDERBUFFER_GREEN_SIZE_EXT: 0x8D51,
        RENDERBUFFER_BLUE_SIZE_EXT: 0x8D52,
        RENDERBUFFER_ALPHA_SIZE_EXT: 0x8D53,
        RENDERBUFFER_DEPTH_SIZE_EXT: 0x8D54,
        RENDERBUFFER_STENCIL_SIZE_EXT: 0x8D55,
        TEXTURE_STENCIL_SIZE_EXT: 0x88F1,
        V2F: 0x2A20,
        V3F: 0x2A21,
        C4UB_V2F: 0x2A22,
        C4UB_V3F: 0x2A23,
        C3F_V3F: 0x2A24,
        N3F_V3F: 0x2A25,
        C4F_N3F_V3F: 0x2A26,
        T2F_V3F: 0x2A27,
        T4F_V4F: 0x2A28,
        T2F_C4UB_V3F: 0x2A29,
        T2F_C3F_V3F: 0x2A2A,
        T2F_N3F_V3F: 0x2A2B,
        T2F_C4F_N3F_V3F: 0x2A2C,
        T4F_C4F_N3F_V4F: 0x2A2D,
    };


    /*
     * Enums the guest header does not happen to #define but the host needs --
     * mostly the ones the guest passes straight through as opaque parameter
     * values (texture environment sources, sized internal formats, blend
     * factors) and never names itself.
     *
     * These are the values from the OpenGL registry. gl_protocol_consistency_test.js
     * asserts that nothing here disagrees with the guest's own table, because a
     * duplicate with a different value would be far worse than a missing one.
     */
    const GL_SUPPLEMENT = {
        ABGR_EXT: 0x8000, ACCUM_BUFFER_BIT: 0x00000200,
        ACTIVE_TEXTURE: 0x84E0, CLIENT_ACTIVE_TEXTURE: 0x84E1,
        TEXTURE0: 0x84C0, MAX_TEXTURE_UNITS: 0x84E2,
        ADD: 0x0104, ADD_SIGNED: 0x8574, SUBTRACT: 0x84E7,
        COMBINE: 0x8570, COMBINE_RGB: 0x8571, COMBINE_ALPHA: 0x8572,
        INTERPOLATE: 0x8575, CONSTANT: 0x8576, PRIMARY_COLOR: 0x8577,
        PREVIOUS: 0x8578, RGB_SCALE: 0x8573,
        SRC0_RGB: 0x8580, SRC1_RGB: 0x8581, SRC2_RGB: 0x8582,
        SRC0_ALPHA: 0x8588, SRC1_ALPHA: 0x8589, SRC2_ALPHA: 0x858A,
        OPERAND0_RGB: 0x8590, OPERAND1_RGB: 0x8591, OPERAND2_RGB: 0x8592,
        OPERAND0_ALPHA: 0x8598, OPERAND1_ALPHA: 0x8599, OPERAND2_ALPHA: 0x859A,
        SRC_COLOR: 0x0300, ONE_MINUS_SRC_COLOR: 0x0301,
        SRC_ALPHA: 0x0302, ONE_MINUS_SRC_ALPHA: 0x0303,
        DST_ALPHA: 0x0304, ONE_MINUS_DST_ALPHA: 0x0305,
        DST_COLOR: 0x0306, ONE_MINUS_DST_COLOR: 0x0307,
        SRC_ALPHA_SATURATE: 0x0308,
        MIN_EXT: 0x8007, MAX_EXT: 0x8008,
        CLEAR_LOGIC_OP: 0x1500, AND: 0x1501, AND_REVERSE: 0x1502,
        COPY: 0x1503, AND_INVERTED: 0x1504, NOOP: 0x1505,
        XOR: 0x1506, OR: 0x1507, NOR: 0x1508, EQUIV: 0x1509,
        INVERT: 0x150A, OR_REVERSE: 0x150B, COPY_INVERTED: 0x150C,
        OR_INVERTED: 0x150D, NAND: 0x150E, SET: 0x150F,
        INCR_WRAP: 0x8507, DECR_WRAP: 0x8508,
        STACK_OVERFLOW: 0x0503, STACK_UNDERFLOW: 0x0504,
        INVALID_FRAMEBUFFER_OPERATION: 0x0506,
        CLAMP: 0x2900, CLAMP_TO_BORDER: 0x812D, MIRRORED_REPEAT: 0x8370,
        BGR: 0x80E0, BGRA: 0x80E1,
        COLOR_INDEX: 0x1900, STENCIL_INDEX: 0x1901,
        COLOR_INDEX8_EXT: 0x80E5,
        INTENSITY: 0x8049, INTENSITY8: 0x804B, INTENSITY16: 0x804D,
        ALPHA4: 0x803B, ALPHA8: 0x803C, ALPHA12: 0x803D, ALPHA16: 0x803E,
        LUMINANCE4: 0x803F, LUMINANCE8: 0x8040,
        LUMINANCE12: 0x8041, LUMINANCE16: 0x8042,
        LUMINANCE4_ALPHA4: 0x8043, LUMINANCE8_ALPHA8: 0x8045,
        LUMINANCE12_ALPHA12: 0x8047, LUMINANCE16_ALPHA16: 0x8048,
        R3_G3_B2: 0x2A10, RGB4: 0x804F, RGB5: 0x8050,
        RGB10: 0x8052, RGB12: 0x8053, RGB16: 0x8054, RGB565: 0x8D62,
        RGBA2: 0x8055, RGBA4: 0x8056, RGB5_A1: 0x8057,
        RGB10_A2: 0x8059, RGBA12: 0x805A,
        HALF_FLOAT: 0x140B,
        UNSIGNED_BYTE_3_3_2: 0x8032, UNSIGNED_BYTE_2_3_3_REV: 0x8362,
        UNSIGNED_INT_10_10_10_2: 0x8036, UNSIGNED_INT_2_10_10_10_REV: 0x8368,
        RED_SCALE: 0x0D14, RED_BIAS: 0x0D15,
        GREEN_SCALE: 0x0D18, GREEN_BIAS: 0x0D19,
        BLUE_SCALE: 0x0D1A, BLUE_BIAS: 0x0D1B,
        ALPHA_SCALE: 0x0D1C, ALPHA_BIAS: 0x0D1D,
        MAP_COLOR: 0x0D10,
        NORMALIZE: 0x0BA1, POLYGON_STIPPLE: 0x0B42,
        MULTISAMPLE: 0x809D, SAMPLE_ALPHA_TO_COVERAGE: 0x809E,
        SAMPLE_BUFFERS: 0x80A8, SAMPLES: 0x80A9,
        COLOR_SUM: 0x8458,
        FOG_COORD_SRC: 0x8450, FOG_COORD: 0x8451, FRAGMENT_DEPTH: 0x8452,
        FOG_COORD_ARRAY: 0x8457, SECONDARY_COLOR_ARRAY: 0x845E,
        NORMAL_MAP: 0x8511, REFLECTION_MAP: 0x8512,
        POINT_SIZE_MIN: 0x8126, POINT_SIZE_MAX: 0x8127,
        POINT_FADE_THRESHOLD_SIZE: 0x8128,
        POINT_DISTANCE_ATTENUATION: 0x8129,
        POINT_SPRITE: 0x8861, COORD_REPLACE: 0x8862,
        TEXTURE_FILTER_CONTROL: 0x8500, TEXTURE_LOD_BIAS: 0x8501,
        TEXTURE_COMPARE_MODE: 0x884C, TEXTURE_COMPARE_FUNC: 0x884D,
        COMPARE_R_TO_TEXTURE: 0x884E,
        TEXTURE_MAX_ANISOTROPY_EXT: 0x84FE,
        DEPTH_CLAMP: 0x864F,
        ARRAY_BUFFER: 0x8892,
        ARRAY_BUFFER_BINDING: 0x8894,
        ELEMENT_ARRAY_BUFFER: 0x8893,
        ELEMENT_ARRAY_BUFFER_BINDING: 0x8895,
        STATIC_DRAW: 0x88E4,
        READ_FRAMEBUFFER: 0x8CA8, DRAW_FRAMEBUFFER: 0x8CA9,
        FRAMEBUFFER_BINDING: 0x8CA6, RENDERBUFFER_BINDING: 0x8CA7,
        MAX_RENDERBUFFER_SIZE: 0x84E8,
        COLOR_ATTACHMENT0: 0x8CE0, DEPTH_ATTACHMENT: 0x8D00,
        STENCIL_ATTACHMENT: 0x8D20, DEPTH_STENCIL_ATTACHMENT: 0x821A,
        MAX_COLOR_ATTACHMENTS: 0x8CDF,
        FRAMEBUFFER_COMPLETE: 0x8CD5,
        FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 0x8CD6,
        FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 0x8CD7,
        FRAMEBUFFER_UNDEFINED: 0x8219,
        MAX_ELEMENTS_VERTICES: 0x80E8, MAX_ELEMENTS_INDICES: 0x80E9,
        FLOAT_MAT2x3: 0x8B65, FLOAT_MAT2x4: 0x8B66,
        FLOAT_MAT3x2: 0x8B67, FLOAT_MAT3x4: 0x8B68,
        FLOAT_MAT4x2: 0x8B69, FLOAT_MAT4x3: 0x8B6A,
    };

    // The guest's own table wins wherever both define a name: it is what the
    // guest actually sends, and a disagreement should surface as a test
    // failure rather than as the host quietly using a different value.
    const GL_CONFLICTS = [];
    for (const key of Object.keys(GL_SUPPLEMENT)) {
        if (GL[key] === undefined) GL[key] = GL_SUPPLEMENT[key];
        else if (GL[key] !== GL_SUPPLEMENT[key])
            GL_CONFLICTS.push({ name: key, guest: GL[key],
                                registry: GL_SUPPLEMENT[key] });
    }

    const NAME_BY_OPCODE = [];
    for (const key of Object.keys(GLFN)) NAME_BY_OPCODE[GLFN[key]] = key;

    const api = { GLFN, CTRL, GL, NAME_BY_OPCODE, GL_SUPPLEMENT, GL_CONFLICTS };
    global.GLWGConstants = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                            source/v64/src/browser/glbridge/gl-webgpu/gl_executor.js                                            0000644 0000000 0000000 00001630025 00000000000 020473  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // OpenGL 1.1-2.1 executed on WebGPU.
//
// This is the host half of the OpenGL path. The guest DLL
// (openglproxy/opengl32_proxy.c) remains the guest-side command encoder: it
// serialises the same 217 opcodes into the same PCI DMA arena. What changed is
// everything after the opcode -- the GL state machine, the resources and the
// shaders now live here, in JavaScript, against a GPUDevice shared with
// d3d9_executor.js.
//
// Three decisions shape the whole file:
//
//   * The authoritative GL state machine is here, not in the guest. That is
//     what lets glGetError, glGetIntegerv, glGetUniformLocation and friends be
//     answered synchronously without a GPU round trip -- only glReadPixels and
//     occlusion results actually need one (plan 4.8).
//
//   * Clip space is flipped once, in the vertex shader (plan 4.3). Framebuffer
//     row 0 is then GL's bottom row, so viewport, scissor, readback,
//     glCopyTexImage and render-to-texture orientation all need no conversion.
//     The cost is reversed winding, which lives in exactly one function
//     (gpuFrontFace), and a flip in the present blit.
//
//   * A draw resolves state into a signature and looks the pipeline up. Any
//     state that changes the picture must reach the signature; a field that
//     does not is a bug whose symptom is "I changed the state and nothing
//     happened".
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md.

(function(global) {
    "use strict";

    const nodeRequire = (typeof require === "function" &&
        typeof module !== "undefined") ? require : null;
    const wire = nodeRequire ? nodeRequire("./gl_wire.js") : global.GLWireFormat;
    const constants = nodeRequire ? nodeRequire("./gl_constants.js") :
        global.GLWGConstants;
    const stateLayout = nodeRequire ? nodeRequire("./gl_state_layout.js") :
        global.GLStateLayout;
    const translator = nodeRequire ? nodeRequire("./gl_shader_translator.js") :
        global.GLShaderTranslator;
    const fixedFunction = nodeRequire ? nodeRequire("./gl_fixed_function.js") :
        global.GLFixedFunction;
    const arbProgram = nodeRequire ? nodeRequire("./gl_arb_program.js") :
        global.GLARBProgram;
    const gpuHost = nodeRequire ? nodeRequire("../webgpu_host.js") :
        global.V86GPUHost;

    const GL = constants.GL;
    const GLFN = constants.GLFN;
    const CTRL = constants.CTRL;
    // V86GL_CTRL_WINDOW_STATE flags: D9WGWindowState's (d3d9_protocol.h)
    const WINDOW_IS_WINDOW = 1 << 0;
    const WINDOW_VISIBLE = 1 << 1;
    const WINDOW_ICONIC = 1 << 2;
    const WINDOW_OCCLUDED = 1 << 6;
    const WINDOW_REGION = 1 << 7;
    const WINDOW_REGION_MAX_RECTS = 32;
    const SIGNATURES = wire.SIGNATURES;

    const EXECUTOR_REVISION = 1;

    const MAX_TEXTURE_UNITS = 8;
    const MAX_TEXTURE_COORDS = 8;
    const MAX_LIGHTS = 8;
    const MAX_CLIP_PLANES = 6;

    // glPushAttrib/glPushClientAttrib masks.  Keep these local to the executor:
    // they are state-group selectors rather than wire opcodes, and spelling the
    // groups out here makes it much harder for a newly added state field to be
    // silently restored by the wrong mask.
    const ATTRIB = {
        CURRENT: 0x00000001, POINT: 0x00000002, LINE: 0x00000004,
        POLYGON: 0x00000008, POLYGON_STIPPLE: 0x00000010,
        PIXEL_MODE: 0x00000020, LIGHTING: 0x00000040, FOG: 0x00000080,
        DEPTH_BUFFER: 0x00000100, ACCUM_BUFFER: 0x00000200,
        STENCIL_BUFFER: 0x00000400, VIEWPORT: 0x00000800,
        TRANSFORM: 0x00001000, ENABLE: 0x00002000,
        COLOR_BUFFER: 0x00004000, HINT: 0x00008000,
        EVAL: 0x00010000, LIST: 0x00020000, TEXTURE: 0x00040000,
        SCISSOR: 0x00080000, MULTISAMPLE: 0x20000000,
    };
    const CLIENT_ATTRIB = { PIXEL_STORE: 0x00000001, VERTEX_ARRAY: 0x00000002 };
    const MAX_VERTEX_ATTRIBS = 16;
    const MAX_DRAW_BUFFERS = 8;
    const MODELVIEW_STACK_DEPTH = 32;
    const OTHER_STACK_DEPTH = 4;
    /* A guest process can flush object-deletion records after its final
     * DESTROY_CONTEXT record. destroyContext() has already retired every
     * object in the orphaned share group, so replaying those deletes has no
     * semantic work left and should not look like a rendering warning. */
    const CONTEXT_FREE_TEARDOWN_OPS = new Set([
        GLFN.DELETE_TEXTURES, GLFN.DELETE_BUFFERS, GLFN.DELETE_PROGRAMS_ARB,
        GLFN.DELETE_PROGRAM, GLFN.DELETE_SHADER, GLFN.DELETE_FRAMEBUFFERS,
        GLFN.DELETE_RENDERBUFFERS, GLFN.DELETE_QUERIES,
    ]);

    function isContextFreeTeardownNoop(fn, view, offset, size) {
        if (CONTEXT_FREE_TEARDOWN_OPS.has(fn)) return true;
        /* GLView unbinds both ARB targets after deleting its last HGLRC. The
         * payload is {target, program}; only program zero is harmless. Keep a
         * warning for a non-zero late bind because that can reveal a genuine
         * control/GL stream ordering bug. */
        return fn === GLFN.BIND_PROGRAM_ARB && size >= 8 &&
            view.getUint32(offset + 4, true) === 0;
    }

    const TEXTURE_USAGE_COPY_SRC = 0x01;
    const TEXTURE_USAGE_COPY_DST = 0x02;
    const TEXTURE_USAGE_TEXTURE_BINDING = 0x04;
    const TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;
    const BUFFER_USAGE_MAP_READ = 0x0001;
    const BUFFER_USAGE_COPY_SRC = 0x0004;
    const BUFFER_USAGE_COPY_DST = 0x0008;
    const BUFFER_USAGE_INDEX = 0x0010;
    const BUFFER_USAGE_VERTEX = 0x0020;
    const BUFFER_USAGE_UNIFORM = 0x0040;
    const BUFFER_USAGE_QUERY_RESOLVE = 0x0200;
    /* D-07. Matches V86GL_QUERY_VISIBLE_SAMPLES in the guest, which uses the
     * same value when it has to answer a blocking GL_QUERY_RESULT itself. */
    const OCCLUSION_VISIBLE_SAMPLES = 0x7FFFFFFF;

    /*
     * The first bytes of a record, as 32-bit words and as hex.
     *
     * Words because every payload in this protocol starts with a run of
     * uint32 fields, so a decoded word list can be read straight against the
     * struct in openglproxy/opengl32_proxy.c; hex because the bytes after
     * them usually cannot.
     */
    function hexPreview(bytes, offset, size, limit) {
        // `offset` is relative to the Uint8Array passed to submit(), just like
        // DataView offsets and Uint8Array indices.  The array may itself be a
        // view into guest RAM with a non-zero byteOffset; subtracting that
        // backing-buffer offset a second time reads an unrelated batch.
        const start = offset;
        const count = Math.min(size, limit || 48);
        if (start < 0 || count <= 0) return "";
        const slice = bytes.subarray(start, start + count);
        const words = [];
        const view = new DataView(slice.buffer, slice.byteOffset, slice.byteLength);
        for (let i = 0; i + 4 <= slice.byteLength && words.length < 8; i += 4)
            words.push(view.getUint32(i, true));
        let hex = "";
        for (let i = 0; i < slice.byteLength; ++i)
            hex += (i && !(i % 4) ? " " : "") +
                slice[i].toString(16).padStart(2, "0");
        return "words[" + words.join(",") + "] " + hex +
            (size > count ? " …(" + size + " bytes)" : "");
    }

    /* The response region carved out of the tail of v86gl.sys's DMA
     * allocation, mirroring D9WG's layout so both paths look the same to
     * anyone reading guest memory. See plan section 6.2. */
    const GLWG_RESPONSE_REGION_BYTES = 4 * 1024 * 1024;
    const GLWG_SLOT_BYTES = 16;
    const GLWG_SLOT_COUNT = 1024;
    const GLWG_QUERY_REGION_BYTES = GLWG_SLOT_BYTES * GLWG_SLOT_COUNT;
    const GLWG_READBACK_REGION_OFFSET = GLWG_QUERY_REGION_BYTES;
    const GLWG_HEARTBEAT_BYTES = 16;
    const GLWG_HEARTBEAT_OFFSET =
        GLWG_RESPONSE_REGION_BYTES - GLWG_HEARTBEAT_BYTES;
    const GLWG_RESPONSE_PENDING = 0;
    const GLWG_RESPONSE_OK = 1;
    const GLWG_RESPONSE_FAILED = 2;

    const CLIENT_ARRAY_MT_MAGIC = 0x544D4143;   // 'CAMT'
    const CLIENT_ARRAY_MT_SECONDARY_COLOR_BIT = 0x80000000;
    const CLIENT_ARRAY_MT_FOG_COORD_BIT = 0x40000000;

    const UNIFORM_RING_BYTES = 4 * 1024 * 1024;
    const VERTEX_RING_BYTES = 8 * 1024 * 1024;

    /* ================================================================== */
    /* Small helpers                                                      */
    /* ================================================================== */

    function alignUp(value, alignment) {
        return Math.ceil(value / alignment) * alignment;
    }

    function clamp(value, low, high) {
        return value < low ? low : (value > high ? high : value);
    }

    function formatHasStencil(format) {
        return typeof format === "string" && format.indexOf("stencil") >= 0;
    }

    /*
     * An automatic WebGPU pipeline layout contains only bindings statically
     * reachable from the selected entry points.  A declaration referenced by
     * an uncalled helper function is deliberately absent.  GLSL applications
     * commonly leave helpers (and their fixed-state uniforms or samplers) in
     * a compiled shader, so looking for binding declarations alone creates a
     * bind group which is invalid against the pipeline's narrower layout.
     *
     * Generated WGSL has no function pointers or indirect calls.  Walking its
     * small, explicit call graph therefore gives the same binding set as the
     * automatic-layout algorithm without making draw submission asynchronous
     * merely to probe validation error scopes.
     */
    function collectReachableWgslBindings(source, entryPoint, result) {
        const text = String(source || "")
            .replace(/\/\*[\s\S]*?\*\//g, "")
            .replace(/\/\/[^\r\n]*/g, "");
        const bindings = new Map();
        const bindingPattern = /@group\s*\(\s*(\d+)\s*\)\s*@binding\s*\(\s*(\d+)\s*\)\s*var(?:\s*<[^>]*>)?\s+([A-Za-z_][A-Za-z0-9_]*)\s*:/g;
        for (const match of text.matchAll(bindingPattern))
            bindings.set(match[3], match[1] + ":" + match[2]);

        const functions = new Map();
        const functionPattern = /\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
        for (let match; (match = functionPattern.exec(text));) {
            const open = text.indexOf("{", functionPattern.lastIndex);
            if (open < 0) break;
            let depth = 1;
            let end = open + 1;
            while (end < text.length && depth) {
                if (text[end] === "{") ++depth;
                else if (text[end] === "}") --depth;
                ++end;
            }
            if (depth) break;
            functions.set(match[1], text.slice(open + 1, end - 1));
            functionPattern.lastIndex = end;
        }

        const pending = [entryPoint];
        const visited = new Set();
        while (pending.length) {
            const name = pending.pop();
            if (visited.has(name)) continue;
            visited.add(name);
            const body = functions.get(name);
            if (body === undefined) continue;

            for (const [variable, key] of bindings) {
                const use = new RegExp("\\b" + variable + "\\b");
                if (use.test(body)) result.add(key);
            }
            const callPattern = /\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
            for (const call of body.matchAll(callPattern)) {
                if (functions.has(call[1]) && !visited.has(call[1]))
                    pending.push(call[1]);
            }
        }
    }

    function activeShaderBindings(wgslVertex, wgslFragment) {
        const result = new Set();
        collectReachableWgslBindings(wgslVertex, "vs_main", result);
        collectReachableWgslBindings(wgslFragment, "fs_main", result);
        return result;
    }

    class GLStreamError extends Error {}

    /* ---- matrices: column-major, the same order GL and WGSL both use ---- */

    function identity4(out) {
        const m = out || new Float32Array(16);
        m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0;
        m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0;
        m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0;
        m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1;
        return m;
    }

    function multiply4(a, b, out) {
        const m = out || new Float32Array(16);
        for (let c = 0; c < 4; ++c) {
            const b0 = b[c * 4], b1 = b[c * 4 + 1];
            const b2 = b[c * 4 + 2], b3 = b[c * 4 + 3];
            m[c * 4] = a[0] * b0 + a[4] * b1 + a[8] * b2 + a[12] * b3;
            m[c * 4 + 1] = a[1] * b0 + a[5] * b1 + a[9] * b2 + a[13] * b3;
            m[c * 4 + 2] = a[2] * b0 + a[6] * b1 + a[10] * b2 + a[14] * b3;
            m[c * 4 + 3] = a[3] * b0 + a[7] * b1 + a[11] * b2 + a[15] * b3;
        }
        return m;
    }

    function invert4(m, out) {
        const inv = out || new Float32Array(16);
        const a = m;
        inv[0] = a[5]*a[10]*a[15] - a[5]*a[11]*a[14] - a[9]*a[6]*a[15] +
                 a[9]*a[7]*a[14] + a[13]*a[6]*a[11] - a[13]*a[7]*a[10];
        inv[4] = -a[4]*a[10]*a[15] + a[4]*a[11]*a[14] + a[8]*a[6]*a[15] -
                 a[8]*a[7]*a[14] - a[12]*a[6]*a[11] + a[12]*a[7]*a[10];
        inv[8] = a[4]*a[9]*a[15] - a[4]*a[11]*a[13] - a[8]*a[5]*a[15] +
                 a[8]*a[7]*a[13] + a[12]*a[5]*a[11] - a[12]*a[7]*a[9];
        inv[12] = -a[4]*a[9]*a[14] + a[4]*a[10]*a[13] + a[8]*a[5]*a[14] -
                  a[8]*a[6]*a[13] - a[12]*a[5]*a[10] + a[12]*a[6]*a[9];
        inv[1] = -a[1]*a[10]*a[15] + a[1]*a[11]*a[14] + a[9]*a[2]*a[15] -
                 a[9]*a[3]*a[14] - a[13]*a[2]*a[11] + a[13]*a[3]*a[10];
        inv[5] = a[0]*a[10]*a[15] - a[0]*a[11]*a[14] - a[8]*a[2]*a[15] +
                 a[8]*a[3]*a[14] + a[12]*a[2]*a[11] - a[12]*a[3]*a[10];
        inv[9] = -a[0]*a[9]*a[15] + a[0]*a[11]*a[13] + a[8]*a[1]*a[15] -
                 a[8]*a[3]*a[13] - a[12]*a[1]*a[11] + a[12]*a[3]*a[9];
        inv[13] = a[0]*a[9]*a[14] - a[0]*a[10]*a[13] - a[8]*a[1]*a[14] +
                  a[8]*a[2]*a[13] + a[12]*a[1]*a[10] - a[12]*a[2]*a[9];
        inv[2] = a[1]*a[6]*a[15] - a[1]*a[7]*a[14] - a[5]*a[2]*a[15] +
                 a[5]*a[3]*a[14] + a[13]*a[2]*a[7] - a[13]*a[3]*a[6];
        inv[6] = -a[0]*a[6]*a[15] + a[0]*a[7]*a[14] + a[4]*a[2]*a[15] -
                 a[4]*a[3]*a[14] - a[12]*a[2]*a[7] + a[12]*a[3]*a[6];
        inv[10] = a[0]*a[5]*a[15] - a[0]*a[7]*a[13] - a[4]*a[1]*a[15] +
                  a[4]*a[3]*a[13] + a[12]*a[1]*a[7] - a[12]*a[3]*a[5];
        inv[14] = -a[0]*a[5]*a[14] + a[0]*a[6]*a[13] + a[4]*a[1]*a[14] -
                  a[4]*a[2]*a[13] - a[12]*a[1]*a[6] + a[12]*a[2]*a[5];
        inv[3] = -a[1]*a[6]*a[11] + a[1]*a[7]*a[10] + a[5]*a[2]*a[11] -
                 a[5]*a[3]*a[10] - a[9]*a[2]*a[7] + a[9]*a[3]*a[6];
        inv[7] = a[0]*a[6]*a[11] - a[0]*a[7]*a[10] - a[4]*a[2]*a[11] +
                 a[4]*a[3]*a[10] + a[8]*a[2]*a[7] - a[8]*a[3]*a[6];
        inv[11] = -a[0]*a[5]*a[11] + a[0]*a[7]*a[9] + a[4]*a[1]*a[11] -
                  a[4]*a[3]*a[9] - a[8]*a[1]*a[7] + a[8]*a[3]*a[5];
        inv[15] = a[0]*a[5]*a[10] - a[0]*a[6]*a[9] - a[4]*a[1]*a[10] +
                  a[4]*a[2]*a[9] + a[8]*a[1]*a[6] - a[8]*a[2]*a[5];
        let det = a[0]*inv[0] + a[1]*inv[4] + a[2]*inv[8] + a[3]*inv[12];
        if (det === 0) return identity4(inv);
        det = 1.0 / det;
        for (let i = 0; i < 16; ++i) inv[i] *= det;
        return inv;
    }

    function transpose4(m, out) {
        const t = out || new Float32Array(16);
        for (let c = 0; c < 4; ++c)
            for (let r = 0; r < 4; ++r)
                t[r * 4 + c] = m[c * 4 + r];
        return t;
    }

    /* gl_NormalMatrix is the inverse transpose of the modelview's upper 3x3. */
    function normalMatrixOf(modelview, out) {
        const n = out || new Float32Array(9);
        const a = modelview;
        const m00 = a[0], m01 = a[4], m02 = a[8];
        const m10 = a[1], m11 = a[5], m12 = a[9];
        const m20 = a[2], m21 = a[6], m22 = a[10];
        const c00 = m11 * m22 - m12 * m21;
        const c01 = m12 * m20 - m10 * m22;
        const c02 = m10 * m21 - m11 * m20;
        let det = m00 * c00 + m01 * c01 + m02 * c02;
        if (det === 0) {
            n[0] = 1; n[1] = 0; n[2] = 0;
            n[3] = 0; n[4] = 1; n[5] = 0;
            n[6] = 0; n[7] = 0; n[8] = 1;
            return n;
        }
        det = 1 / det;
        // Column-major: column j holds the inverse-transpose's jth column,
        // which is the jth row of the inverse -- hence the cofactor order.
        n[0] = c00 * det; n[1] = c01 * det; n[2] = c02 * det;
        n[3] = (m02 * m21 - m01 * m22) * det;
        n[4] = (m00 * m22 - m02 * m20) * det;
        n[5] = (m01 * m20 - m00 * m21) * det;
        n[6] = (m01 * m12 - m02 * m11) * det;
        n[7] = (m02 * m10 - m00 * m12) * det;
        n[8] = (m00 * m11 - m01 * m10) * det;
        return n;
    }

    function transformPoint4(m, v, out) {
        const o = out || new Float32Array(4);
        o[0] = m[0]*v[0] + m[4]*v[1] + m[8]*v[2] + m[12]*v[3];
        o[1] = m[1]*v[0] + m[5]*v[1] + m[9]*v[2] + m[13]*v[3];
        o[2] = m[2]*v[0] + m[6]*v[1] + m[10]*v[2] + m[14]*v[3];
        o[3] = m[3]*v[0] + m[7]*v[1] + m[11]*v[2] + m[15]*v[3];
        return o;
    }

    /* ================================================================== */
    /* GL enum translation                                                */
    /* ================================================================== */

    const COMPARE_FUNCTIONS = {
        [GL.NEVER]: "never", [GL.LESS]: "less", [GL.EQUAL]: "equal",
        [GL.LEQUAL]: "less-equal", [GL.GREATER]: "greater",
        [GL.NOTEQUAL]: "not-equal", [GL.GEQUAL]: "greater-equal",
        [GL.ALWAYS]: "always",
    };

    const ALPHA_TEST_NAMES = {
        [GL.NEVER]: "never", [GL.LESS]: "less", [GL.EQUAL]: "equal",
        [GL.LEQUAL]: "lequal", [GL.GREATER]: "greater",
        [GL.NOTEQUAL]: "notequal", [GL.GEQUAL]: "gequal",
        [GL.ALWAYS]: "always",
    };

    const STENCIL_OPERATIONS = {
        [GL.KEEP]: "keep", [GL.ZERO]: "zero", [GL.REPLACE]: "replace",
        [GL.INCR]: "increment-clamp", [GL.DECR]: "decrement-clamp",
        [GL.INVERT]: "invert",
        [GL.INCR_WRAP]: "increment-wrap", [GL.DECR_WRAP]: "decrement-wrap",
    };

    const BLEND_FACTORS = {
        [GL.ZERO]: "zero", [GL.ONE]: "one",
        [GL.SRC_COLOR]: "src", [GL.ONE_MINUS_SRC_COLOR]: "one-minus-src",
        [GL.DST_COLOR]: "dst", [GL.ONE_MINUS_DST_COLOR]: "one-minus-dst",
        [GL.SRC_ALPHA]: "src-alpha", [GL.ONE_MINUS_SRC_ALPHA]: "one-minus-src-alpha",
        [GL.DST_ALPHA]: "dst-alpha", [GL.ONE_MINUS_DST_ALPHA]: "one-minus-dst-alpha",
        [GL.CONSTANT_COLOR]: "constant",
        [GL.ONE_MINUS_CONSTANT_COLOR]: "one-minus-constant",
        // WebGPU has no separate alpha blend constant: one setBlendConstant
        // covers both, so GL_CONSTANT_ALPHA maps to the same factor and the
        // executor writes the constant's alpha into it. Exact for the usual
        // case where a program sets one constant colour and uses both.
        [GL.CONSTANT_ALPHA]: "constant",
        [GL.ONE_MINUS_CONSTANT_ALPHA]: "one-minus-constant",
        [GL.SRC_ALPHA_SATURATE]: "src-alpha-saturated",
    };

    const BLEND_EQUATIONS = {
        [GL.FUNC_ADD]: "add",
        [GL.FUNC_SUBTRACT]: "subtract",
        [GL.FUNC_REVERSE_SUBTRACT]: "reverse-subtract",
        [GL.MIN]: "min", [GL.MAX]: "max",
        [GL.MIN_EXT]: "min", [GL.MAX_EXT]: "max",
    };

    /* The selected default pixel format is currently single-sampled, but ARB
     * sample coverage still has observable all-or-nothing coverage there. */
    function sampleCoverageMask(state) {
        if (!state.enabled.has(GL.MULTISAMPLE) ||
                !state.enabled.has(GL.SAMPLE_COVERAGE))
            return 0xffffffff;
        let covered = state.sampleCoverage.value > 0 ? 1 : 0;
        if (state.sampleCoverage.invert) covered ^= 1;
        return covered;
    }

    const ADDRESS_MODES = {
        [GL.REPEAT]: "repeat",
        [GL.CLAMP_TO_EDGE]: "clamp-to-edge",
        [GL.MIRRORED_REPEAT]: "mirror-repeat",
        // GL_CLAMP and GL_CLAMP_TO_BORDER sample the border colour outside
        // [0,1]; WebGPU has no border addressing at all, so the sampler clamps
        // and the shader is responsible for the border. Deviation D-03.
        [GL.CLAMP]: "clamp-to-edge",
        [GL.CLAMP_TO_BORDER]: "clamp-to-edge",
    };

    /* GL's ten primitive modes over WebGPU's five. Everything that has no
     * direct topology is expanded through an index buffer (plan 4.6). */
    const PRIMITIVE_TOPOLOGY = {
        [GL.POINTS]: "point-list",
        [GL.LINES]: "line-list",
        [GL.LINE_STRIP]: "line-strip",
        [GL.LINE_LOOP]: "line-strip",
        [GL.TRIANGLES]: "triangle-list",
        [GL.TRIANGLE_STRIP]: "triangle-strip",
        [GL.TRIANGLE_FAN]: "triangle-list",
        [GL.QUADS]: "triangle-list",
        [GL.QUAD_STRIP]: "triangle-list",
        [GL.POLYGON]: "triangle-list",
    };

    function needsIndexExpansion(mode) {
        return mode === GL.TRIANGLE_FAN || mode === GL.QUADS ||
            mode === GL.QUAD_STRIP || mode === GL.POLYGON ||
            mode === GL.LINE_LOOP;
    }

    /*
     * Flat shading takes its colour from a primitive-specific vertex, and the
     * table is not "the first one": a triangle fan uses the second vertex of
     * each triangle and a quad uses the fourth. WGSL's @interpolate(flat)
     * takes the first, so expansion puts GL's choice there. Getting this wrong
     * shifts colours by one vertex on flat-shaded models only, which is why
     * gl_flat_shading_test.exe walks the whole table.
     */
    function expandIndices(mode, count, base) {
        const first = base || 0;
        switch (mode) {
        case GL.TRIANGLE_FAN: {
            if (count < 3) return new Uint32Array(0);
            const out = new Uint32Array((count - 2) * 3);
            let w = 0;
            for (let i = 0; i < count - 2; ++i) {
                // provoking vertex i+1 leads
                out[w++] = first + i + 1;
                out[w++] = first + i + 2;
                out[w++] = first;
            }
            return out;
        }
        case GL.QUADS: {
            const quads = Math.floor(count / 4);
            const out = new Uint32Array(quads * 6);
            let w = 0;
            for (let q = 0; q < quads; ++q) {
                const b = first + q * 4;
                // provoking vertex is the quad's last, so it leads both halves
                out[w++] = b + 3; out[w++] = b; out[w++] = b + 1;
                out[w++] = b + 3; out[w++] = b + 1; out[w++] = b + 2;
            }
            return out;
        }
        case GL.QUAD_STRIP: {
            if (count < 4) return new Uint32Array(0);
            const quads = Math.floor(count / 2) - 1;
            const out = new Uint32Array(quads * 6);
            let w = 0;
            for (let q = 0; q < quads; ++q) {
                const b = first + q * 2;
                // GL's provoking vertex for quad-strip quad i is 2i + 2
                out[w++] = b + 3; out[w++] = b; out[w++] = b + 1;
                out[w++] = b + 3; out[w++] = b + 1; out[w++] = b + 2;
            }
            return out;
        }
        case GL.POLYGON: {
            if (count < 3) return new Uint32Array(0);
            const out = new Uint32Array((count - 2) * 3);
            let w = 0;
            for (let i = 0; i < count - 2; ++i) {
                // the whole polygon takes its flat colour from vertex 0
                out[w++] = first;
                out[w++] = first + i + 1;
                out[w++] = first + i + 2;
            }
            return out;
        }
        case GL.LINE_LOOP: {
            if (count < 2) return new Uint32Array(0);
            const out = new Uint32Array(count + 1);
            for (let i = 0; i < count; ++i) out[i] = first + i;
            out[count] = first;
            return out;
        }
        default: {
            const out = new Uint32Array(count);
            for (let i = 0; i < count; ++i) out[i] = first + i;
            return out;
        }
        }
    }

    /* The same expansion applied to an existing index array. */
    function expandIndexArray(mode, indices) {
        const count = indices.length;
        const map = expandIndices(mode, count, 0);
        const out = new Uint32Array(map.length);
        for (let i = 0; i < map.length; ++i) out[i] = indices[map[i]];
        return out;
    }

    function expandedIndexCount(mode, count) {
        switch (mode) {
        case GL.TRIANGLE_FAN: return count < 3 ? 0 : (count - 2) * 3;
        case GL.QUADS: return Math.floor(count / 4) * 6;
        case GL.QUAD_STRIP: return count < 4 ? 0 : (Math.floor(count / 2) - 1) * 6;
        case GL.POLYGON: return count < 3 ? 0 : (count - 2) * 3;
        case GL.LINE_LOOP: return count < 2 ? 0 : count + 1;
        default: return count;
        }
    }

    function isPolygonPrimitive(mode) {
        return mode === GL.TRIANGLES || mode === GL.TRIANGLE_STRIP ||
            mode === GL.TRIANGLE_FAN || mode === GL.QUADS ||
            mode === GL.QUAD_STRIP || mode === GL.POLYGON;
    }

    /* Produces independent triangles before polygon raster mode is applied.
     * `source` is the application's optional index array; without it the
     * vertices are numbered from zero and drawIndexed's baseVertex preserves
     * glDrawArrays(first). */
    function triangleListIndices(mode, count, source) {
        const input = source || (() => {
            const out = new Uint32Array(count);
            for (let i = 0; i < count; ++i) out[i] = i;
            return out;
        })();
        if (mode === GL.TRIANGLES)
            return input.slice(0, Math.floor(input.length / 3) * 3);
        if (mode === GL.TRIANGLE_STRIP) {
            if (input.length < 3) return new Uint32Array(0);
            const out = new Uint32Array((input.length - 2) * 3);
            let at = 0;
            for (let i = 0; i + 2 < input.length; ++i) {
                if (i & 1) {
                    out[at++] = input[i + 1]; out[at++] = input[i];
                } else {
                    out[at++] = input[i]; out[at++] = input[i + 1];
                }
                out[at++] = input[i + 2];
            }
            return out;
        }
        return expandIndexArray(mode, input);
    }

    function polygonRasterIndices(mode, count, source, rasterMode) {
        const triangles = triangleListIndices(mode, count, source);
        if (rasterMode === GL.POINT) return triangles;
        if (rasterMode !== GL.LINE) return triangles;
        const out = new Uint32Array(triangles.length * 2);
        let at = 0;
        for (let i = 0; i + 2 < triangles.length; i += 3) {
            const a = triangles[i], b = triangles[i + 1], c = triangles[i + 2];
            out[at++] = a; out[at++] = b;
            out[at++] = b; out[at++] = c;
            out[at++] = c; out[at++] = a;
        }
        return out;
    }

    /* ================================================================== */
    /* Pixel formats                                                      */
    /* ================================================================== */

    /*
     * GL's texture formats are three loosely coupled parameters: the internal
     * format says what is stored, and (format, type) say how the bytes arriving
     * from the guest are laid out. WebGPU has one format per texture, so both
     * halves are resolved here: incoming rows are converted to the storage
     * format, and the *base* internal format is remembered because the fixed
     * pipeline's texture environment depends on it.
     *
     * The channel expansion is the part worth getting exactly right:
     *   ALPHA           -> (0, 0, 0, a)
     *   LUMINANCE       -> (l, l, l, 1)
     *   LUMINANCE_ALPHA -> (l, l, l, a)
     *   INTENSITY       -> (i, i, i, i)
     *   RGB             -> (r, g, b, 1)
     * Every one of those is a rule from the GL spec's texture-sampling table,
     * and getting one wrong is a colour shift nobody can trace back to here.
     */

    const BASE_INTERNAL_FORMATS = {
        [GL.ALPHA]: "ALPHA", [GL.ALPHA4]: "ALPHA", [GL.ALPHA8]: "ALPHA",
        [GL.ALPHA12]: "ALPHA", [GL.ALPHA16]: "ALPHA",
        [GL.LUMINANCE]: "LUMINANCE", [GL.LUMINANCE4]: "LUMINANCE",
        [GL.LUMINANCE8]: "LUMINANCE", [GL.LUMINANCE12]: "LUMINANCE",
        [GL.LUMINANCE16]: "LUMINANCE",
        [GL.LUMINANCE_ALPHA]: "LUMINANCE_ALPHA",
        [GL.LUMINANCE4_ALPHA4]: "LUMINANCE_ALPHA",
        [GL.LUMINANCE8_ALPHA8]: "LUMINANCE_ALPHA",
        [GL.LUMINANCE12_ALPHA12]: "LUMINANCE_ALPHA",
        [GL.LUMINANCE16_ALPHA16]: "LUMINANCE_ALPHA",
        [GL.INTENSITY]: "INTENSITY", [GL.INTENSITY8]: "INTENSITY",
        [GL.INTENSITY16]: "INTENSITY",
        [GL.RGB]: "RGB", [GL.RGB4]: "RGB", [GL.RGB5]: "RGB", [GL.RGB8]: "RGB",
        [GL.RGB10]: "RGB", [GL.RGB12]: "RGB", [GL.RGB16]: "RGB",
        [GL.R3_G3_B2]: "RGB", [GL.RGB565]: "RGB",
        [GL.RGBA]: "RGBA", [GL.RGBA2]: "RGBA", [GL.RGBA4]: "RGBA",
        [GL.RGB5_A1]: "RGBA", [GL.RGBA8]: "RGBA", [GL.RGB10_A2]: "RGBA",
        [GL.RGBA12]: "RGBA", [GL.RGBA16]: "RGBA",
        [GL.BGR]: "RGB", [GL.BGRA]: "RGBA",
        3: "RGB", 4: "RGBA", 1: "LUMINANCE", 2: "LUMINANCE_ALPHA",
        [GL.DEPTH_COMPONENT]: "DEPTH",
        [GL.DEPTH_COMPONENT16]: "DEPTH",
        [GL.DEPTH_COMPONENT24]: "DEPTH",
        [GL.DEPTH_COMPONENT32]: "DEPTH",
        [GL.SRGB]: "RGB", [GL.SRGB8]: "RGB",
        [GL.SRGB_ALPHA]: "RGBA", [GL.SRGB8_ALPHA8]: "RGBA",
        [GL.RGBA16F_ARB]: "RGBA", [GL.RGBA32F_ARB]: "RGBA",
        [GL.RGB16F_ARB]: "RGB", [GL.RGB32F_ARB]: "RGB",
        [GL.COLOR_INDEX]: "COLOR_INDEX",
        [GL.COLOR_INDEX8_EXT]: "COLOR_INDEX",
    };

    const COMPRESSED_FORMATS = {
        [GL.COMPRESSED_RGB_S3TC_DXT1_EXT]:
            { gpu: "bc1-rgba-unorm", blockBytes: 8, base: "RGB", dxt: 1 },
        [GL.COMPRESSED_RGBA_S3TC_DXT1_EXT]:
            { gpu: "bc1-rgba-unorm", blockBytes: 8, base: "RGBA", dxt: 1 },
        [GL.COMPRESSED_RGBA_S3TC_DXT3_EXT]:
            { gpu: "bc2-rgba-unorm", blockBytes: 16, base: "RGBA", dxt: 3 },
        [GL.COMPRESSED_RGBA_S3TC_DXT5_EXT]:
            { gpu: "bc3-rgba-unorm", blockBytes: 16, base: "RGBA", dxt: 5 },
    };

    function storageFormatFor(internalFormat, features) {
        const compressed = COMPRESSED_FORMATS[internalFormat];
        if (compressed) {
            // Without the BC feature the blocks are decoded on the CPU rather
            // than the extension being withdrawn, because the guest may have
            // already been told S3TC exists. The decode is deterministic, so
            // the picture is identical; only the memory cost differs.
            return features && features.bc ?
                { gpu: compressed.gpu, compressed: true, blockBytes: compressed.blockBytes,
                  base: compressed.base, dxt: compressed.dxt } :
                { gpu: "rgba8unorm", compressed: false, decodeDXT: compressed.dxt,
                  base: compressed.base, blockBytes: compressed.blockBytes };
        }
        const base = BASE_INTERNAL_FORMATS[internalFormat];
        switch (internalFormat) {
        case GL.DEPTH_COMPONENT:
        case GL.DEPTH_COMPONENT24:
            // depth24plus has an implementation-defined texel layout and cannot
            // receive queue.writeTexture data. depth32float preserves uploaded
            // depth values and remains renderable/sampleable on core WebGPU.
            return { gpu: "depth32float", depth: true, base: "DEPTH" };
        case GL.DEPTH_COMPONENT16:
            return { gpu: "depth16unorm", depth: true, base: "DEPTH" };
        case GL.DEPTH_COMPONENT32:
            return { gpu: "depth32float", depth: true, base: "DEPTH" };
        case GL.SRGB:
        case GL.SRGB8:
        case GL.SRGB_ALPHA:
        case GL.SRGB8_ALPHA8:
            return { gpu: "rgba8unorm-srgb", base: base || "RGBA" };
        case GL.RGBA16F_ARB:
        case GL.RGB16F_ARB:
            return { gpu: "rgba16float", base: base || "RGBA", float: true };
        case GL.RGBA32F_ARB:
        case GL.RGB32F_ARB:
            return { gpu: "rgba32float", base: base || "RGBA", float: true };
        case GL.COLOR_INDEX:
        case GL.COLOR_INDEX8_EXT:
            // Palettised textures keep their index on the GPU and are resolved
            // in the shader, the same way the D3D9 path handles P8.
            return { gpu: "r8uint", base: "COLOR_INDEX", palettised: true };
        default:
            return { gpu: "rgba8unorm", base: base || "RGBA" };
        }
    }

    /* Components per texel in the *source* data, by format. */
    const SOURCE_COMPONENTS = {
        [GL.RED]: 1, [GL.GREEN]: 1, [GL.BLUE]: 1, [GL.ALPHA]: 1,
        [GL.LUMINANCE]: 1, [GL.INTENSITY]: 1, [GL.DEPTH_COMPONENT]: 1,
        [GL.COLOR_INDEX]: 1, [GL.STENCIL_INDEX]: 1,
        [GL.LUMINANCE_ALPHA]: 2,
        [GL.RGB]: 3, [GL.BGR]: 3,
        [GL.RGBA]: 4, [GL.BGRA]: 4, [GL.ABGR_EXT]: 4,
    };

    const TYPE_BYTES = {
        [GL.UNSIGNED_BYTE]: 1, [GL.BYTE]: 1,
        [GL.UNSIGNED_SHORT]: 2, [GL.SHORT]: 2,
        [GL.HALF_FLOAT]: 2,
        [GL.UNSIGNED_INT]: 4, [GL.INT]: 4, [GL.FLOAT]: 4,
        [GL.UNSIGNED_BYTE_3_3_2]: 1, [GL.UNSIGNED_BYTE_2_3_3_REV]: 1,
        [GL.UNSIGNED_SHORT_5_6_5]: 2, [GL.UNSIGNED_SHORT_5_6_5_REV]: 2,
        [GL.UNSIGNED_SHORT_4_4_4_4]: 2, [GL.UNSIGNED_SHORT_4_4_4_4_REV]: 2,
        [GL.UNSIGNED_SHORT_5_5_5_1]: 2, [GL.UNSIGNED_SHORT_1_5_5_5_REV]: 2,
        [GL.UNSIGNED_INT_8_8_8_8]: 4, [GL.UNSIGNED_INT_8_8_8_8_REV]: 4,
        [GL.UNSIGNED_INT_10_10_10_2]: 4, [GL.UNSIGNED_INT_2_10_10_10_REV]: 4,
    };

    const PACKED_TYPES = new Set([
        GL.UNSIGNED_BYTE_3_3_2, GL.UNSIGNED_BYTE_2_3_3_REV,
        GL.UNSIGNED_SHORT_5_6_5, GL.UNSIGNED_SHORT_5_6_5_REV,
        GL.UNSIGNED_SHORT_4_4_4_4, GL.UNSIGNED_SHORT_4_4_4_4_REV,
        GL.UNSIGNED_SHORT_5_5_5_1, GL.UNSIGNED_SHORT_1_5_5_5_REV,
        GL.UNSIGNED_INT_8_8_8_8, GL.UNSIGNED_INT_8_8_8_8_REV,
        GL.UNSIGNED_INT_10_10_10_2, GL.UNSIGNED_INT_2_10_10_10_REV,
    ]);

    function sourceTexelBytes(format, type) {
        const typeBytes = TYPE_BYTES[type];
        if (typeBytes === undefined) return 0;
        if (PACKED_TYPES.has(type)) return typeBytes;
        const components = SOURCE_COMPONENTS[format];
        if (components === undefined) return 0;
        return components * typeBytes;
    }

    function expandBits(value, bits) {
        // Replicating the high bits is GL's rule for widening a packed
        // component, and it is why 5-bit 31 becomes 255 and not 248.
        if (bits >= 8) return (value >>> (bits - 8)) & 0xff;
        let out = value << (8 - bits);
        let filled = bits;
        while (filled < 8) {
            out |= value >>> (bits - Math.min(bits, 8 - filled));
            filled += bits;
        }
        return out & 0xff;
    }

    /*
     * Reads one source texel into out[0..3] as 0..255, applying the source
     * format's channel meaning but not the internal format's expansion.
     */
    function readSourceTexel(view, byteOffset, format, type, out) {
        const packed = PACKED_TYPES.has(type);
        if (packed) {
            let raw;
            switch (TYPE_BYTES[type]) {
            case 1: raw = view.getUint8(byteOffset); break;
            case 2: raw = view.getUint16(byteOffset, true); break;
            default: raw = view.getUint32(byteOffset, true); break;
            }
            switch (type) {
            case GL.UNSIGNED_BYTE_3_3_2:
                out[0] = expandBits((raw >> 5) & 7, 3);
                out[1] = expandBits((raw >> 2) & 7, 3);
                out[2] = expandBits(raw & 3, 2);
                out[3] = 255;
                return;
            case GL.UNSIGNED_BYTE_2_3_3_REV:
                out[0] = expandBits(raw & 7, 3);
                out[1] = expandBits((raw >> 3) & 7, 3);
                out[2] = expandBits((raw >> 6) & 3, 2);
                out[3] = 255;
                return;
            case GL.UNSIGNED_SHORT_5_6_5:
                out[0] = expandBits((raw >> 11) & 31, 5);
                out[1] = expandBits((raw >> 5) & 63, 6);
                out[2] = expandBits(raw & 31, 5);
                out[3] = 255;
                return;
            case GL.UNSIGNED_SHORT_5_6_5_REV:
                out[0] = expandBits(raw & 31, 5);
                out[1] = expandBits((raw >> 5) & 63, 6);
                out[2] = expandBits((raw >> 11) & 31, 5);
                out[3] = 255;
                return;
            case GL.UNSIGNED_SHORT_4_4_4_4:
                out[0] = expandBits((raw >> 12) & 15, 4);
                out[1] = expandBits((raw >> 8) & 15, 4);
                out[2] = expandBits((raw >> 4) & 15, 4);
                out[3] = expandBits(raw & 15, 4);
                return;
            case GL.UNSIGNED_SHORT_4_4_4_4_REV:
                out[0] = expandBits(raw & 15, 4);
                out[1] = expandBits((raw >> 4) & 15, 4);
                out[2] = expandBits((raw >> 8) & 15, 4);
                out[3] = expandBits((raw >> 12) & 15, 4);
                return;
            case GL.UNSIGNED_SHORT_5_5_5_1:
                out[0] = expandBits((raw >> 11) & 31, 5);
                out[1] = expandBits((raw >> 6) & 31, 5);
                out[2] = expandBits((raw >> 1) & 31, 5);
                out[3] = (raw & 1) ? 255 : 0;
                return;
            case GL.UNSIGNED_SHORT_1_5_5_5_REV:
                out[0] = expandBits(raw & 31, 5);
                out[1] = expandBits((raw >> 5) & 31, 5);
                out[2] = expandBits((raw >> 10) & 31, 5);
                out[3] = (raw & 0x8000) ? 255 : 0;
                return;
            case GL.UNSIGNED_INT_8_8_8_8:
                out[0] = (raw >>> 24) & 0xff; out[1] = (raw >>> 16) & 0xff;
                out[2] = (raw >>> 8) & 0xff; out[3] = raw & 0xff;
                return;
            case GL.UNSIGNED_INT_8_8_8_8_REV:
                out[0] = raw & 0xff; out[1] = (raw >>> 8) & 0xff;
                out[2] = (raw >>> 16) & 0xff; out[3] = (raw >>> 24) & 0xff;
                return;
            case GL.UNSIGNED_INT_10_10_10_2:
                out[0] = expandBits((raw >>> 22) & 1023, 10);
                out[1] = expandBits((raw >>> 12) & 1023, 10);
                out[2] = expandBits((raw >>> 2) & 1023, 10);
                out[3] = expandBits(raw & 3, 2);
                return;
            default:  // UNSIGNED_INT_2_10_10_10_REV
                out[0] = expandBits(raw & 1023, 10);
                out[1] = expandBits((raw >>> 10) & 1023, 10);
                out[2] = expandBits((raw >>> 20) & 1023, 10);
                out[3] = expandBits((raw >>> 30) & 3, 2);
                return;
            }
        }

        const typeBytes = TYPE_BYTES[type];
        const components = SOURCE_COMPONENTS[format] || 1;
        const read = i => {
            const at = byteOffset + i * typeBytes;
            switch (type) {
            case GL.UNSIGNED_BYTE: return view.getUint8(at);
            case GL.BYTE: return clamp(view.getInt8(at), 0, 127) * 2;
            case GL.UNSIGNED_SHORT: return view.getUint16(at, true) >>> 8;
            case GL.SHORT: return clamp(view.getInt16(at, true), 0, 32767) >>> 7;
            case GL.UNSIGNED_INT: return view.getUint32(at, true) >>> 24;
            case GL.INT: return clamp(view.getInt32(at, true), 0, 0x7fffffff) >>> 23;
            case GL.FLOAT: return clamp(Math.round(view.getFloat32(at, true) * 255), 0, 255);
            default: return 0;
            }
        };
        const c = [];
        for (let i = 0; i < components; ++i) c.push(read(i));

        switch (format) {
        case GL.RED: out[0] = c[0]; out[1] = 0; out[2] = 0; out[3] = 255; return;
        case GL.GREEN: out[0] = 0; out[1] = c[0]; out[2] = 0; out[3] = 255; return;
        case GL.BLUE: out[0] = 0; out[1] = 0; out[2] = c[0]; out[3] = 255; return;
        case GL.ALPHA: out[0] = 0; out[1] = 0; out[2] = 0; out[3] = c[0]; return;
        case GL.LUMINANCE:
        case GL.INTENSITY:
        case GL.DEPTH_COMPONENT:
        case GL.COLOR_INDEX:
        case GL.STENCIL_INDEX:
            out[0] = c[0]; out[1] = c[0]; out[2] = c[0]; out[3] = 255; return;
        case GL.LUMINANCE_ALPHA:
            out[0] = c[0]; out[1] = c[0]; out[2] = c[0]; out[3] = c[1]; return;
        case GL.RGB: out[0] = c[0]; out[1] = c[1]; out[2] = c[2]; out[3] = 255; return;
        case GL.BGR: out[0] = c[2]; out[1] = c[1]; out[2] = c[0]; out[3] = 255; return;
        case GL.RGBA: out[0] = c[0]; out[1] = c[1]; out[2] = c[2]; out[3] = c[3]; return;
        case GL.BGRA: out[0] = c[2]; out[1] = c[1]; out[2] = c[0]; out[3] = c[3]; return;
        case GL.ABGR_EXT: out[0] = c[3]; out[1] = c[2]; out[2] = c[1]; out[3] = c[0]; return;
        default: out[0] = c[0] || 0; out[1] = c[1] || 0; out[2] = c[2] || 0;
                 out[3] = c[3] === undefined ? 255 : c[3];
        }
    }

    /* Applies the internal base format's expansion, in place. */
    function applyBaseFormat(base, texel) {
        switch (base) {
        case "ALPHA":
            texel[0] = 0; texel[1] = 0; texel[2] = 0;
            return;
        case "LUMINANCE":
            texel[1] = texel[0]; texel[2] = texel[0]; texel[3] = 255;
            return;
        case "LUMINANCE_ALPHA":
            texel[1] = texel[0]; texel[2] = texel[0];
            return;
        case "INTENSITY":
            texel[1] = texel[0]; texel[2] = texel[0]; texel[3] = texel[0];
            return;
        case "RGB":
            texel[3] = 255;
            break;
        default:

        }
    }

    /*
     * Converts a rectangle of guest pixel data into tightly packed RGBA8 rows.
     *
     * The fast path exists because it is the one every game actually uses:
     * GL_RGBA/GL_UNSIGNED_BYTE into an RGBA internal format is a memcpy, and
     * routing a 1024x1024 texture through the per-texel reader instead would
     * be visible as a hitch on every level load.
     */
    function convertPixels(source, byteOffset, width, height, depth,
            format, type, base, unpack) {
        const rowLength = unpack.rowLength || width;
        const skipPixels = unpack.skipPixels || 0;
        const skipRows = unpack.skipRows || 0;
        const skipImages = unpack.skipImages || 0;
        const alignment = unpack.alignment || 4;
        const texelBytes = sourceTexelBytes(format, type);
        if (!texelBytes) return null;
        const srcRowBytes = alignUp(rowLength * texelBytes, alignment);
        const imageHeight = unpack.imageHeight || height;
        const out = new Uint8Array(width * height * depth * 4);
        // The view is relative to `source`, so every offset below is too --
        // mixing in source.byteOffset would double-count it for any subarray.
        const view = new DataView(source.buffer, source.byteOffset,
            source.byteLength);
        const limit = source.byteLength;

        const fastCopy = type === GL.UNSIGNED_BYTE && format === GL.RGBA &&
            base === "RGBA";
        const fastBGRA = type === GL.UNSIGNED_BYTE && format === GL.BGRA &&
            base === "RGBA";
        const fastRGB = type === GL.UNSIGNED_BYTE && format === GL.RGB &&
            (base === "RGB" || base === "RGBA");

        const texel = new Uint8Array(4);
        for (let z = 0; z < depth; ++z) {
            for (let y = 0; y < height; ++y) {
                let src = byteOffset +
                    (skipImages + z) * imageHeight * srcRowBytes +
                    (skipRows + y) * srcRowBytes + skipPixels * texelBytes;
                let dst = ((z * height + y) * width) * 4;
                if (src + width * texelBytes > limit) return null;
                if (fastCopy) {
                    out.set(source.subarray(src, src + width * 4), dst);
                    continue;
                }
                if (fastBGRA) {
                    for (let x = 0; x < width; ++x) {
                        out[dst] = view.getUint8(src + 2);
                        out[dst + 1] = view.getUint8(src + 1);
                        out[dst + 2] = view.getUint8(src);
                        out[dst + 3] = view.getUint8(src + 3);
                        src += 4; dst += 4;
                    }
                    continue;
                }
                if (fastRGB) {
                    for (let x = 0; x < width; ++x) {
                        out[dst] = view.getUint8(src);
                        out[dst + 1] = view.getUint8(src + 1);
                        out[dst + 2] = view.getUint8(src + 2);
                        out[dst + 3] = 255;
                        src += 3; dst += 4;
                    }
                    continue;
                }
                for (let x = 0; x < width; ++x) {
                    readSourceTexel(view, src, format, type, texel);
                    applyBaseFormat(base, texel);
                    out[dst] = texel[0]; out[dst + 1] = texel[1];
                    out[dst + 2] = texel[2]; out[dst + 3] = texel[3];
                    src += texelBytes; dst += 4;
                }
            }
        }
        return out;
    }

    function halfToFloat(value) {
        const sign = (value & 0x8000) ? -1 : 1;
        const exponent = (value >>> 10) & 0x1f;
        const fraction = value & 0x3ff;
        if (!exponent) return sign * Math.pow(2, -14) * (fraction / 1024);
        if (exponent === 31) return fraction ? NaN : sign * Infinity;
        return sign * Math.pow(2, exponent - 15) * (1 + fraction / 1024);
    }

    function floatToHalf(value) {
        if (Number.isNaN(value)) return 0x7e00;
        const sign = value < 0 || Object.is(value, -0) ? 0x8000 : 0;
        const absolute = Math.abs(value);
        if (absolute === Infinity) return sign | 0x7c00;
        if (absolute === 0) return sign;
        let exponent = Math.floor(Math.log2(absolute));
        let mantissa = absolute / Math.pow(2, exponent) - 1;
        if (exponent < -14) {
            const subnormal = Math.round(absolute / Math.pow(2, -24));
            return sign | Math.min(0x3ff, subnormal);
        }
        if (exponent > 15) return sign | 0x7c00;
        let fraction = Math.round(mantissa * 1024);
        if (fraction === 1024) { fraction = 0; ++exponent; }
        if (exponent > 15) return sign | 0x7c00;
        return sign | ((exponent + 15) << 10) | (fraction & 0x3ff);
    }

    function readSourceTexelFloat(view, byteOffset, format, type, out) {
        if (PACKED_TYPES.has(type)) {
            const bytes = new Uint8Array(4);
            readSourceTexel(view, byteOffset, format, type, bytes);
            for (let i = 0; i < 4; ++i) out[i] = bytes[i] / 255;
            return;
        }
        const typeBytes = TYPE_BYTES[type];
        const components = SOURCE_COMPONENTS[format] || 1;
        const read = i => {
            const at = byteOffset + i * typeBytes;
            switch (type) {
            case GL.UNSIGNED_BYTE: return view.getUint8(at) / 255;
            case GL.BYTE: return Math.max(view.getInt8(at) / 127, -1);
            case GL.UNSIGNED_SHORT: return view.getUint16(at, true) / 65535;
            case GL.SHORT: return Math.max(view.getInt16(at, true) / 32767, -1);
            case GL.UNSIGNED_INT: return view.getUint32(at, true) / 4294967295;
            case GL.INT: return Math.max(view.getInt32(at, true) / 2147483647, -1);
            case GL.FLOAT: return view.getFloat32(at, true);
            case GL.HALF_FLOAT: return halfToFloat(view.getUint16(at, true));
            default: return 0;
            }
        };
        const c = [];
        for (let i = 0; i < components; ++i) c.push(read(i));
        out[0] = 0; out[1] = 0; out[2] = 0; out[3] = 1;
        switch (format) {
        case GL.RED: out[0] = c[0]; break;
        case GL.GREEN: out[1] = c[0]; break;
        case GL.BLUE: out[2] = c[0]; break;
        case GL.ALPHA: out[3] = c[0]; break;
        case GL.LUMINANCE: out[0] = out[1] = out[2] = c[0]; break;
        case GL.INTENSITY: out[0] = out[1] = out[2] = out[3] = c[0]; break;
        case GL.DEPTH_COMPONENT:
        case GL.COLOR_INDEX:
        case GL.STENCIL_INDEX: out[0] = out[1] = out[2] = c[0]; break;
        case GL.LUMINANCE_ALPHA:
            out[0] = out[1] = out[2] = c[0]; out[3] = c[1]; break;
        case GL.RGB: out[0] = c[0]; out[1] = c[1]; out[2] = c[2]; break;
        case GL.BGR: out[0] = c[2]; out[1] = c[1]; out[2] = c[0]; break;
        case GL.RGBA: out[0] = c[0]; out[1] = c[1]; out[2] = c[2]; out[3] = c[3]; break;
        case GL.BGRA: out[0] = c[2]; out[1] = c[1]; out[2] = c[0]; out[3] = c[3]; break;
        case GL.ABGR_EXT:
            out[0] = c[3]; out[1] = c[2]; out[2] = c[1]; out[3] = c[0]; break;
        default:
            for (let i = 0; i < Math.min(4, c.length); ++i) out[i] = c[i];
        }
    }

    function convertPixelsForStorage(source, byteOffset, width, height, depth,
            format, type, storage, unpack) {
        if (!storage.float && !storage.depth && !storage.palettised) {
            const pixels = convertPixels(source, byteOffset, width, height, depth,
                format, type, storage.base, unpack);
            return pixels ? { pixels, bytesPerTexel: 4, componentType: "u8",
                               componentCount: 4 } : null;
        }
        const texelBytes = sourceTexelBytes(format, type);
        if (!texelBytes) return null;
        const rowLength = unpack.rowLength || width;
        const skipPixels = unpack.skipPixels || 0;
        const skipRows = unpack.skipRows || 0;
        const skipImages = unpack.skipImages || 0;
        const alignment = unpack.alignment || 4;
        const srcRowBytes = alignUp(rowLength * texelBytes, alignment);
        const imageHeight = unpack.imageHeight || height;
        const texels = width * height * depth;
        let bytesPerTexel, componentType, componentCount, result, output;
        if (storage.palettised) {
            bytesPerTexel = 1; componentType = "u8"; componentCount = 1;
            result = new Uint8Array(texels); output = result;
        } else if (storage.gpu === "rgba16float") {
            bytesPerTexel = 8; componentType = "f16"; componentCount = 4;
            result = new Uint8Array(texels * bytesPerTexel);
            output = new Uint16Array(result.buffer);
        } else if (storage.gpu === "rgba32float") {
            bytesPerTexel = 16; componentType = "f32"; componentCount = 4;
            result = new Uint8Array(texels * bytesPerTexel);
            output = new Float32Array(result.buffer);
        } else if (storage.gpu === "depth16unorm") {
            bytesPerTexel = 2; componentType = "u16"; componentCount = 1;
            result = new Uint8Array(texels * bytesPerTexel);
            output = new Uint16Array(result.buffer);
        } else {
            bytesPerTexel = 4; componentType = "f32"; componentCount = 1;
            result = new Uint8Array(texels * bytesPerTexel);
            output = new Float32Array(result.buffer);
        }
        const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
        const texel = new Float32Array(4);
        let dst = 0;
        for (let z = 0; z < depth; ++z) {
            for (let y = 0; y < height; ++y) {
                let src = byteOffset + (skipImages + z) * imageHeight * srcRowBytes +
                    (skipRows + y) * srcRowBytes + skipPixels * texelBytes;
                if (src + width * texelBytes > source.byteLength) return null;
                for (let x = 0; x < width; ++x) {
                    readSourceTexelFloat(view, src, format, type, texel);
                    if (storage.palettised) {
                        output[dst++] = clamp(Math.round(texel[0] * 255), 0, 255);
                    } else if (componentCount === 1) {
                        const value = clamp(texel[0], 0, 1);
                        output[dst++] = componentType === "u16" ?
                            Math.round(value * 65535) : value;
                    } else {
                        for (let c = 0; c < 4; ++c)
                            output[dst++] = componentType === "f16" ?
                                floatToHalf(texel[c]) : texel[c];
                    }
                    src += texelBytes;
                }
            }
        }
        return { pixels: result, bytesPerTexel, componentType, componentCount };
    }

    /* ---- S3TC decode, used when the adapter has no BC support ---- */

    function decodeDXTColorBlock(src, at, out, outStride, x0, y0, width, height,
            dxt1Alpha) {
        const c0 = src[at] | (src[at + 1] << 8);
        const c1 = src[at + 2] | (src[at + 3] << 8);
        const palette = new Uint8Array(16);
        const unpack565 = (c, i) => {
            palette[i] = expandBits((c >> 11) & 31, 5);
            palette[i + 1] = expandBits((c >> 5) & 63, 6);
            palette[i + 2] = expandBits(c & 31, 5);
            palette[i + 3] = 255;
        };
        unpack565(c0, 0);
        unpack565(c1, 4);
        if (c0 > c1 || !dxt1Alpha) {
            for (let k = 0; k < 3; ++k) {
                palette[8 + k] = (2 * palette[k] + palette[4 + k] + 1) / 3 | 0;
                palette[12 + k] = (palette[k] + 2 * palette[4 + k] + 1) / 3 | 0;
            }
            palette[11] = 255; palette[15] = 255;
        } else {
            for (let k = 0; k < 3; ++k)
                palette[8 + k] = (palette[k] + palette[4 + k]) >> 1;
            palette[11] = 255;
            palette[12] = 0; palette[13] = 0; palette[14] = 0; palette[15] = 0;
        }
        const bits = src[at + 4] | (src[at + 5] << 8) | (src[at + 6] << 16) |
            (src[at + 7] << 24);
        for (let y = 0; y < 4; ++y) {
            for (let x = 0; x < 4; ++x) {
                const px = x0 + x, py = y0 + y;
                if (px >= width || py >= height) continue;
                const index = (bits >>> (2 * (4 * y + x))) & 3;
                const o = py * outStride + px * 4;
                out[o] = palette[index * 4];
                out[o + 1] = palette[index * 4 + 1];
                out[o + 2] = palette[index * 4 + 2];
                out[o + 3] = palette[index * 4 + 3];
            }
        }
    }

    function decodeDXT(dxt, src, width, height) {
        const out = new Uint8Array(width * height * 4);
        const stride = width * 4;
        const blockBytes = dxt === 1 ? 8 : 16;
        const blocksX = Math.ceil(width / 4);
        const blocksY = Math.ceil(height / 4);
        let at = 0;
        for (let by = 0; by < blocksY; ++by) {
            for (let bx = 0; bx < blocksX; ++bx) {
                const x0 = bx * 4, y0 = by * 4;
                if (dxt === 1) {
                    decodeDXTColorBlock(src, at, out, stride, x0, y0,
                        width, height, true);
                } else {
                    decodeDXTColorBlock(src, at + 8, out, stride, x0, y0,
                        width, height, false);
                    if (dxt === 3) {
                        for (let y = 0; y < 4; ++y) {
                            for (let x = 0; x < 4; ++x) {
                                const px = x0 + x, py = y0 + y;
                                if (px >= width || py >= height) continue;
                                const nibble = at + y * 2 + (x >> 1);
                                const value = (x & 1) ? (src[nibble] >> 4) :
                                    (src[nibble] & 15);
                                out[py * stride + px * 4 + 3] = expandBits(value, 4);
                            }
                        }
                    } else {
                        const a0 = src[at], a1 = src[at + 1];
                        const alpha = new Uint8Array(8);
                        alpha[0] = a0; alpha[1] = a1;
                        if (a0 > a1) {
                            for (let k = 1; k < 7; ++k)
                                alpha[k + 1] = ((7 - k) * a0 + k * a1 + 3) / 7 | 0;
                        } else {
                            for (let k = 1; k < 5; ++k)
                                alpha[k + 1] = ((5 - k) * a0 + k * a1 + 2) / 5 | 0;
                            alpha[6] = 0; alpha[7] = 255;
                        }
                        let low = src[at + 2] | (src[at + 3] << 8) |
                            (src[at + 4] << 16);
                        let high = src[at + 5] | (src[at + 6] << 8) |
                            (src[at + 7] << 16);
                        for (let y = 0; y < 4; ++y) {
                            for (let x = 0; x < 4; ++x) {
                                const px = x0 + x, py = y0 + y;
                                if (px >= width || py >= height) continue;
                                const bit = 3 * (4 * y + x);
                                const value = bit < 24 ?
                                    (low >>> bit) & 7 :
                                    (high >>> (bit - 24)) & 7;
                                out[py * stride + px * 4 + 3] = alpha[value];
                            }
                        }
                    }
                }
                at += blockBytes;
            }
        }
        return out;
    }

    /* ================================================================== */
    /* GL context state                                                   */
    /* ================================================================== */

    function cloneStateValue(value) {
        if (value === null || value === undefined || typeof value !== "object")
            return value;
        if (ArrayBuffer.isView(value)) return new value.constructor(value);
        if (value instanceof Set) return new Set(value);
        if (Array.isArray(value)) return value.map(cloneStateValue);
        const copy = Object.create(Object.getPrototypeOf(value) === null ? null :
            Object.prototype);
        for (const key of Object.keys(value)) copy[key] = cloneStateValue(value[key]);
        return copy;
    }

    function snapshotFields(state, fields) {
        const snapshot = Object.create(null);
        for (const field of fields) snapshot[field] = cloneStateValue(state[field]);
        return snapshot;
    }

    function restoreFields(state, snapshot, fields) {
        for (const field of fields)
            if (Object.prototype.hasOwnProperty.call(snapshot, field))
                state[field] = cloneStateValue(snapshot[field]);
    }

    const SERVER_ATTRIB_FIELDS = [
        [ATTRIB.CURRENT, ["current"]],
        [ATTRIB.POINT, ["pointSize", "point"]],
        [ATTRIB.LINE, ["lineWidth", "lineStipple"]],
        [ATTRIB.POLYGON, ["cullFace", "frontFace", "polygonMode", "polygonOffset"]],
        [ATTRIB.POLYGON_STIPPLE, ["polygonStipple"]],
        [ATTRIB.PIXEL_MODE, ["pixelTransfer", "pixelZoom", "readBuffer"]],
        [ATTRIB.LIGHTING, ["lightModel", "lights", "material", "colorMaterial",
                           "shadeModel"]],
        [ATTRIB.FOG, ["fog"]],
        [ATTRIB.DEPTH_BUFFER, ["depthFunc", "depthMask", "clearDepth"]],
        [ATTRIB.ACCUM_BUFFER, ["clearAccum"]],
        [ATTRIB.STENCIL_BUFFER, ["stencil", "clearStencil"]],
        [ATTRIB.VIEWPORT, ["viewport", "depthRange"]],
        [ATTRIB.TRANSFORM, ["matrixMode", "clipPlanes"]],
        [ATTRIB.COLOR_BUFFER, ["clearColor", "colorMask", "blend", "alphaFunc",
                              "logicOp", "drawBuffers"]],
        [ATTRIB.TEXTURE, ["activeTexture", "textureUnits"]],
        [ATTRIB.SCISSOR, ["scissor"]],
        [ATTRIB.MULTISAMPLE, ["sampleCoverage"]],
    ];

    function fieldsForServerAttrib(mask) {
        const fields = new Set();
        for (const [bit, names] of SERVER_ATTRIB_FIELDS)
            if (mask & bit) for (const name of names) fields.add(name);
        if (mask & ATTRIB.ENABLE) fields.add("enabled");
        return [...fields];
    }

    function captureEnableState(state) {
        return {
            enabled: new Set(state.enabled),
            textureTargets: state.textureUnits.map(unit => new Set(unit.enabledTargets)),
            texGen: state.textureUnits.map(unit => unit.texGen.map(gen => gen.enabled)),
            lights: state.lights.map(light => light.enabled),
            colorMaterial: state.colorMaterial.enabled,
        };
    }

    function restoreEnableState(state, snapshot) {
        state.enabled = new Set(snapshot.enabled);
        state.textureUnits.forEach((unit, i) => {
            unit.enabledTargets = new Set(snapshot.textureTargets[i]);
            unit.texGen.forEach((gen, j) => { gen.enabled = snapshot.texGen[i][j]; });
        });
        state.lights.forEach((light, i) => { light.enabled = snapshot.lights[i]; });
        state.colorMaterial.enabled = snapshot.colorMaterial;
    }

    /*
     * One of these per wglCreateContext. Everything the GL spec calls "server
     * state" lives here, at its documented default -- and the defaults matter:
     * a game that never calls glDepthFunc expects GL_LESS, and a wrong default
     * shows up as a subtly wrong picture in exactly the titles that touch the
     * least state.
     */
    function createContextState(id, shareGroup) {
        const state = {
            id, shareGroup,
            error: GL.NO_ERROR,
            errorQueue: [],
            arbErrorString: "",
            arbErrorPosition: -1,

            matrixMode: GL.MODELVIEW,
            stacks: {
                [GL.MODELVIEW]: [identity4()],
                [GL.PROJECTION]: [identity4()],
                [GL.COLOR]: [identity4()],
            },
            textureStacks: Array.from({ length: MAX_TEXTURE_COORDS },
                () => [identity4()]),

            current: {
                color: new Float32Array([1, 1, 1, 1]),
                secondaryColor: new Float32Array([0, 0, 0, 1]),
                normal: new Float32Array([0, 0, 1]),
                fogCoord: 0,
                edgeFlag: true,
                texCoord: Array.from({ length: MAX_TEXTURE_COORDS },
                    () => new Float32Array([0, 0, 0, 1])),
                rasterPos: new Float32Array([0, 0, 0, 1]),
                rasterValid: true,
            },

            enabled: new Set(),

            viewport: { x: 0, y: 0, width: 0, height: 0 },
            depthRange: { near: 0, far: 1 },
            scissor: { x: 0, y: 0, width: 0, height: 0, set: false },

            clearColor: new Float32Array([0, 0, 0, 0]),
            clearDepth: 1,
            clearStencil: 0,
            clearAccum: new Float32Array([0, 0, 0, 0]),

            depthFunc: GL.LESS,
            depthMask: true,
            colorMask: [true, true, true, true],
            stencil: {
                front: { func: GL.ALWAYS, ref: 0, valueMask: 0xffffffff,
                         writeMask: 0xffffffff, fail: GL.KEEP,
                         zfail: GL.KEEP, zpass: GL.KEEP },
                back: { func: GL.ALWAYS, ref: 0, valueMask: 0xffffffff,
                        writeMask: 0xffffffff, fail: GL.KEEP,
                        zfail: GL.KEEP, zpass: GL.KEEP },
            },
            blend: {
                srcRGB: GL.ONE, dstRGB: GL.ZERO,
                srcAlpha: GL.ONE, dstAlpha: GL.ZERO,
                equationRGB: GL.FUNC_ADD, equationAlpha: GL.FUNC_ADD,
                color: new Float32Array([0, 0, 0, 0]),
            },
            alphaFunc: { func: GL.ALWAYS, ref: 0 },
            logicOp: GL.COPY,
            cullFace: GL.BACK,
            frontFace: GL.CCW,
            polygonMode: { front: GL.FILL, back: GL.FILL },
            polygonOffset: { factor: 0, units: 0 },
            shadeModel: GL.SMOOTH,
            lineWidth: 1,
            lineStipple: { pattern: 0xffff, factor: 1 },
            polygonStipple: new Uint8Array(128).fill(0xff),
            pointSize: 1,
            point: {
                size: 1, sizeMin: 0, sizeMax: 64, fadeThreshold: 1,
                attenuation: new Float32Array([1, 0, 0]),
                spriteCoordOrigin: GL.UPPER_LEFT,
            },
            sampleCoverage: { value: 1, invert: false },

            lightModel: {
                ambient: new Float32Array([0.2, 0.2, 0.2, 1]),
                twoSide: false,
                localViewer: false,
                colorControl: GL.SINGLE_COLOR,
            },
            lights: Array.from({ length: MAX_LIGHTS }, (unused, i) => ({
                enabled: false,
                ambient: new Float32Array([0, 0, 0, 1]),
                diffuse: new Float32Array(i === 0 ? [1, 1, 1, 1] : [0, 0, 0, 1]),
                specular: new Float32Array(i === 0 ? [1, 1, 1, 1] : [0, 0, 0, 1]),
                position: new Float32Array([0, 0, 1, 0]),
                spotDirection: new Float32Array([0, 0, -1]),
                spotExponent: 0,
                spotCutoff: 180,
                constantAttenuation: 1,
                linearAttenuation: 0,
                quadraticAttenuation: 0,
                // Eye-space copies, refreshed when the light or the modelview
                // changes: GL specifies that glLight* captures the modelview in
                // force at the time of the call.
                eyePosition: new Float32Array([0, 0, 1, 0]),
                eyeSpotDirection: new Float32Array([0, 0, -1]),
            })),
            material: {
                front: newMaterial(), back: newMaterial(),
            },
            colorMaterial: { enabled: false, face: GL.FRONT_AND_BACK,
                             mode: GL.AMBIENT_AND_DIFFUSE },

            fog: {
                mode: GL.EXP, density: 1, start: 0, end: 1,
                color: new Float32Array([0, 0, 0, 0]),
                coordSource: GL.FRAGMENT_DEPTH,
            },

            clipPlanes: Array.from({ length: MAX_CLIP_PLANES },
                () => new Float32Array([0, 0, 0, 0])),

            activeTexture: 0,
            clientActiveTexture: 0,
            textureUnits: Array.from({ length: MAX_TEXTURE_UNITS }, () => ({
                bindings: Object.create(null),   // target -> texture name
                enabledTargets: new Set(),
                env: newTexEnv(),
                texGen: Array.from({ length: 4 }, (unused, i) => ({
                    enabled: false,
                    mode: GL.EYE_LINEAR,
                    objectPlane: new Float32Array(
                        i === 0 ? [1, 0, 0, 0] : (i === 1 ? [0, 1, 0, 0] : [0, 0, 0, 0])),
                    eyePlane: new Float32Array(
                        i === 0 ? [1, 0, 0, 0] : (i === 1 ? [0, 1, 0, 0] : [0, 0, 0, 0])),
                })),
                lodBias: 0,
            })),

            pixelStore: {
                unpackAlignment: 4, unpackRowLength: 0, unpackSkipPixels: 0,
                unpackSkipRows: 0, unpackSkipImages: 0, unpackImageHeight: 0,
                unpackSwapBytes: false, unpackLsbFirst: false,
                packAlignment: 4, packRowLength: 0, packSkipPixels: 0,
                packSkipRows: 0, packSwapBytes: false, packLsbFirst: false,
            },
            pixelTransfer: { redScale: 1, greenScale: 1, blueScale: 1,
                             alphaScale: 1, redBias: 0, greenBias: 0,
                             blueBias: 0, alphaBias: 0, mapColor: false,
                             postColorMatrixScale:
                                new Float32Array([1, 1, 1, 1]),
                             postColorMatrixBias:
                                new Float32Array([0, 0, 0, 0]) },
            pixelZoom: { x: 1, y: 1 },

            arrayBuffer: 0,
            elementArrayBuffer: 0,
            pixelPackBuffer: 0,
            pixelUnpackBuffer: 0,
            currentProgram: 0,
            arbVertexProgram: 0,
            arbFragmentProgram: 0,

            drawFramebuffer: 0,
            readFramebuffer: 0,
            renderbuffer: 0,
            drawBuffers: [GL.BACK],
            readBuffer: GL.BACK,

            activeQueries: Object.create(null),

            // Immediate mode
            immediate: null,
            renderMode: GL.RENDER,

            // Generic vertex attributes (GL 2.0)
            genericAttribs: Array.from({ length: MAX_VERTEX_ATTRIBS }, () => ({
                enabled: false,
                value: new Float32Array([0, 0, 0, 1]),
            })),

            attribStack: [],
            clientAttribStack: [],
        };
        // GL's default enables. Everything else starts off.
        state.enabled.add(GL.DITHER);
        state.enabled.add(GL.MULTISAMPLE);
        return state;
    }

    function newMaterial() {
        return {
            ambient: new Float32Array([0.2, 0.2, 0.2, 1]),
            diffuse: new Float32Array([0.8, 0.8, 0.8, 1]),
            specular: new Float32Array([0, 0, 0, 1]),
            emission: new Float32Array([0, 0, 0, 1]),
            shininess: 0,
        };
    }

    function newTexEnv() {
        return {
            mode: GL.MODULATE,
            color: new Float32Array([0, 0, 0, 0]),
            combineRGB: GL.MODULATE, combineAlpha: GL.MODULATE,
            srcRGB: [GL.TEXTURE, GL.PREVIOUS, GL.CONSTANT],
            srcAlpha: [GL.TEXTURE, GL.PREVIOUS, GL.CONSTANT],
            operandRGB: [GL.SRC_COLOR, GL.SRC_COLOR, GL.SRC_ALPHA],
            operandAlpha: [GL.SRC_ALPHA, GL.SRC_ALPHA, GL.SRC_ALPHA],
            rgbScale: 1, alphaScale: 1,
            lodBias: 0,
            pointSprite: false,
        };
    }

    /* Names the fixed-function generator understands, from GL enums. */
    const TEXENV_MODE_NAMES = {
        [GL.REPLACE]: "REPLACE", [GL.MODULATE]: "MODULATE",
        [GL.DECAL]: "DECAL", [GL.BLEND]: "BLEND", [GL.ADD]: "ADD",
        [GL.COMBINE]: "COMBINE",
    };
    const COMBINE_RGB_NAMES = {
        [GL.REPLACE]: "REPLACE", [GL.MODULATE]: "MODULATE", [GL.ADD]: "ADD",
        [GL.ADD_SIGNED]: "ADD_SIGNED", [GL.INTERPOLATE]: "INTERPOLATE",
        [GL.SUBTRACT]: "SUBTRACT",
        [GL.DOT3_RGB]: "DOT3_RGB", [GL.DOT3_RGBA]: "DOT3_RGBA",
    };
    const COMBINE_SOURCE_NAMES = {
        [GL.TEXTURE]: "TEXTURE", [GL.CONSTANT]: "CONSTANT",
        [GL.PRIMARY_COLOR]: "PRIMARY_COLOR", [GL.PREVIOUS]: "PREVIOUS",
    };
    for (let i = 0; i < MAX_TEXTURE_UNITS; ++i)
        COMBINE_SOURCE_NAMES[GL.TEXTURE0 + i] = "TEXTURE" + i;
    const OPERAND_NAMES = {
        [GL.SRC_COLOR]: "SRC_COLOR",
        [GL.ONE_MINUS_SRC_COLOR]: "ONE_MINUS_SRC_COLOR",
        [GL.SRC_ALPHA]: "SRC_ALPHA",
        [GL.ONE_MINUS_SRC_ALPHA]: "ONE_MINUS_SRC_ALPHA",
    };
    const TEXGEN_MODE_NAMES = {
        [GL.OBJECT_LINEAR]: "OBJECT", [GL.EYE_LINEAR]: "EYE",
        [GL.SPHERE_MAP]: "SPHERE", [GL.REFLECTION_MAP]: "REFLECTION",
        [GL.NORMAL_MAP]: "NORMAL",
    };
    const COLOR_MATERIAL_MODES = {
        [GL.EMISSION]: "EMISSION", [GL.AMBIENT]: "AMBIENT",
        [GL.DIFFUSE]: "DIFFUSE", [GL.SPECULAR]: "SPECULAR",
        [GL.AMBIENT_AND_DIFFUSE]: "AMBIENT_AND_DIFFUSE",
    };
    const FACE_NAMES = {
        [GL.FRONT]: "FRONT", [GL.BACK]: "BACK",
        [GL.FRONT_AND_BACK]: "FRONT_AND_BACK",
    };

    /* The GL_TEXTURE_* target a unit samples, in GL's own priority order:
     * when several targets are enabled on one unit, cube beats 3D beats 2D
     * beats 1D. */
    const TARGET_PRIORITY = [
        [GL.TEXTURE_CUBE_MAP, "Cube"],
        [GL.TEXTURE_3D, "3D"],
        [GL.TEXTURE_2D, "2D"],
        [GL.TEXTURE_1D, "1D"],
    ];

    /* ================================================================== */
    /* Resources                                                          */
    /* ================================================================== */

    /*
     * A share group owns the objects wglShareLists makes common: textures,
     * buffers, display lists, shaders, programs and renderbuffers. Framebuffer
     * objects, vertex array state and query objects are per context, which is
     * what desktop GL specifies -- and getting that split wrong is how a
     * capability-probe context ends up destroying the real one's state, the
     * failure the old bridge's README documented as unfixed.
     */
    function createShareGroup(id) {
        return {
            id,
            textures: new Map(),
            buffers: new Map(),
            shaders: new Map(),
            programs: new Map(),
            renderbuffers: new Map(),
            arbPrograms: new Map(),
            nextName: { texture: 1, buffer: 1, shader: 1, renderbuffer: 1,
                        arbProgram: 1 },
        };
    }

    function createTexture(name) {
        return {
            name,
            target: 0,
            levels: [],            // per level: {width, height, depth, bytes, format}
            gpuTexture: null,
            gpuFormat: "rgba8unorm",
            baseFormat: "RGBA",
            width: 0, height: 0, depth: 1, layers: 1,
            levelCount: 0,
            dirty: true,
            viewCache: new Map(),
            sampler: {
                minFilter: GL.NEAREST_MIPMAP_LINEAR,
                magFilter: GL.LINEAR,
                wrapS: GL.REPEAT, wrapT: GL.REPEAT, wrapR: GL.REPEAT,
                minLod: -1000, maxLod: 1000,
                baseLevel: 0, maxLevel: 1000,
                lodBias: 0,
                maxAnisotropy: 1,
                borderColor: new Float32Array([0, 0, 0, 0]),
                compareMode: GL.NONE, compareFunc: GL.LEQUAL,
                depthTextureMode: GL.LUMINANCE,
            },
            generateMipmapHint: false,
            immutableSampleCount: 1,
        };
    }

    function createBuffer(name) {
        return { name, size: 0, usage: GL.STATIC_DRAW, gpuBuffer: null,
                 shadow: null, target: 0, mapped: false };
    }

    function createProgram(name) {
        return {
            name, shaders: new Set(),
            linked: false, log: "",
            bindAttribLocations: new Map(),
            compiled: { vertex: null, fragment: null },
            link: null,                 // translator link result
            variants: new Map(),        // variant key -> {link, modules}
            uniformData: null,          // Uint8Array mirroring the block
            uniformByName: new Map(),
            uniformByLocation: new Map(),
            samplerUnits: new Map(),    // sampler name -> texture unit
            serial: 1,
            validateLog: "",
        };
    }

    function createFramebuffer(name) {
        return {
            name,
            color: new Array(MAX_DRAW_BUFFERS).fill(null),
            depth: null, stencil: null,
            width: 0, height: 0,
        };
    }

    function createRenderbuffer(name) {
        return { name, width: 0, height: 0, internalFormat: GL.RGBA4,
                 samples: 1, gpuTexture: null, gpuFormat: "rgba8unorm" };
    }

    /* ================================================================== */
    /* Executor                                                           */
    /* ================================================================== */

    class GLWebGPUExecutor {
        constructor(canvas, options) {
            this.canvas = canvas;
            this.options = options || {};
            this.host = this.options.host ||
                (gpuHost ? gpuHost.acquire(canvas, this.options.hostOptions) : null);
            // Mirrored for backwards-compatible diagnostics; query paths use
            // the per-HGLRC fields in createContextState.
            this.arbErrorString = "";
            this.arbErrorPosition = -1;
            this.device = null;
            this.deviceFeatures = { bc: false };
            this.presenterToken = 0;

            this.shareGroups = new Map();
            this.contexts = new Map();
            this.nextContextId = 1;
            this.nextShareGroupId = 1;
            // Uniform locations are opaque GLint handles.  opengl32.dll keeps
            // them in one process-wide lookup table, even across non-shared
            // HGLRCs, so the executor must not expose the translator's
            // per-program 0..N locations directly.
            this.nextUniformLocation = 1;
            this.current = null;

            this.framebuffers = new Map();  // per context id -> Map(name -> fbo)
            this.queries = new Map();

            this.pipelineCache = new Map();
            this.bindGroupCache = new Map();
            this.convertedVertexCache = new Map();
            this.convertedVertexBytes = 0;
            this.uniformValueCache = new Map();
            this.stateUniformLayouts = new WeakMap();
            this.resourceIds = new WeakMap();
            this.nextResourceId = 1;
            this.samplerCache = new Map();
            this.moduleCache = new Map();
            this.shaderCache = new Map();   // link cache key -> link result
            this.indexExpansionCache = new Map();

            this.backBuffer = null;
            this.backBufferView = null;
            this.depthTarget = null;
            this.backBufferWidth = 0;
            this.backBufferHeight = 0;

            this.encoder = null;
            this.pass = null;
            this.passTarget = null;
            this.recordedOps = 0;
            this.pendingVertexBuffers = new WeakSet();
            this.uploadPages = [];
            this.flushThreshold = Math.max(1024, this.options.flushThreshold || 16384);

            this.uniformRing = null;
            this.uniformStaging = null;
            this.uniformCursor = 0;
            this.uniformCapacity = Math.max(64 * 1024,
                this.options.uniformRingBytes || UNIFORM_RING_BYTES);
            this.vertexRing = null;
            this.vertexStaging = null;
            this.vertexCursor = 0;
            this.vertexCapacity = Math.max(256 * 1024,
                this.options.vertexRingBytes || VERTEX_RING_BYTES);

            this.pendingReadbacks = new Set();
            this.pending = [];
            this.busy = false;
            this.heartbeat = 0;
            this.warned = Object.create(null);
            this.stats = {
                batches: 0, commands: 0, draws: 0, immediateBatches: 0,
                pipelines: 0, bindGroups: 0, shaderLinks: 0, shaderCacheHits: 0,
                textureUploads: 0, textureBytes: 0,
                refusals: 0, refusalsByOp: Object.create(null),
                expandedIndices: 0, dxtDecodes: 0,
                nonUniformSamples: 0,
            };

            this.surface = { hwnd: 0, x: 0, y: 0, width: 0, height: 0,
                             visible: false };
            this.handlers = buildHandlerTable();
            installResourceHandlers(this.handlers);
            installProgramHandlers(this.handlers);
            installDrawHandlers(this.handlers);
            this.args = new Float64Array(32);
        }

        /* ---- lifecycle ---- */

        initialize() {
            if (this.readyPromise) return this.readyPromise;
            this.readyPromise = (async () => {
                if (!this.host) throw new Error("no WebGPU host available");
                await this.host.initialize();
                this.device = this.host.device;
                this.deviceFeatures = this.host.deviceFeatures ||
                    { bc: false };
                this.limits = this.host.limits || {};
                this.host.onDeviceLost(() => this.onDeviceLost());
                this.uniformRing = this.device.createBuffer({
                    label: "GL uniform ring",
                    size: this.uniformCapacity,
                    usage: BUFFER_USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
                });
                this.uniformStaging = new Uint8Array(this.uniformCapacity);
                this.vertexRing = this.device.createBuffer({
                    label: "GL vertex ring",
                    size: this.vertexCapacity,
                    usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_INDEX |
                        BUFFER_USAGE_COPY_DST,
                });
                this.vertexStaging = new Uint8Array(this.vertexCapacity);
                this.fallbackTexture = this.device.createTexture({
                    label: "GL incomplete-texture fallback",
                    size: { width: 1, height: 1, depthOrArrayLayers: 1 },
                    format: "rgba8unorm",
                    usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
                });
                // GL samples an incomplete texture as opaque black, not white:
                // the D3D9 path's white fallback would make missing textures
                // invisible instead of obvious.
                this.device.queue.writeTexture({ texture: this.fallbackTexture },
                    new Uint8Array([0, 0, 0, 255]),
                    { bytesPerRow: 4, rowsPerImage: 1 },
                    { width: 1, height: 1, depthOrArrayLayers: 1 });
                this.fallbackView = this.fallbackTexture.createView();
                this.fallbackSampler = this.device.createSampler({});
                this.fallbackComparisonSampler = this.device.createSampler({
                    compare: "less-equal",
                });
                return this;
            })().catch(error => {
                this.failed = error;
                console.error("[gl-webgpu] initialization failed", error);
                throw error;
            });
            return this.readyPromise;
        }

        trackReadback(operation) {
            this.pendingReadbacks.add(operation);
            operation.then(() => this.pendingReadbacks.delete(operation),
                () => this.pendingReadbacks.delete(operation));
            return operation;
        }

        async idle() {
            if (this.readyPromise) await this.readyPromise;
            while (this.pendingReadbacks.size)
                await Promise.all(Array.from(this.pendingReadbacks));
        }

        onDeviceLost() {
            this.uniformValueCache.clear();
            // Every GPU object belonged to the old device. The GL state machine
            // does not: it is plain JavaScript, so the resources rebuild from
            // the shadow copies the next time each is used.
            this.device = this.host.device;
            this.pipelineCache.clear();
            if (this.pixelPipelineCache) this.pixelPipelineCache.clear();
            if (this.accumPipelineCache) this.accumPipelineCache.clear();
            if (this.accumClearPipelineCache) this.accumClearPipelineCache.clear();
            if (this.clearPipelineCache) this.clearPipelineCache.clear();
            this.bindGroupCache.clear();
            this.samplerCache.clear();
            this.moduleCache.clear();
            for (const group of this.shareGroups.values()) {
                for (const texture of group.textures.values()) {
                    texture.gpuTexture = null;
                    texture.viewCache.clear();
                    texture.dirty = true;
                }
                for (const buffer of group.buffers.values()) {
                    this.invalidateVertexConversions(buffer);
                    buffer.gpuBuffer = null;
                }
                for (const program of group.programs.values())
                    program.variants.clear();
            }
            this.backBuffer = null;
            this.depthTarget = null;
            this.accumBuffer = null;
            this.uniformRing = null;
            this.vertexRing = null;
            this.readyPromise = null;
            return this.initialize();
        }

        /* ---- diagnostics ---- */

        warnOnce(key, message, details) {
            if (this.warned[key]) return;
            this.warned[key] = true;
            console.warn("[gl-webgpu] " + message, details || {});
        }

        /*
         * A command the host cannot execute is reported once with enough
         * context to find it, counted, and -- where GL defines an error for the
         * situation -- reflected in glGetError. Silently ignoring it is what
         * made the D3D8 and DirectDraw migrations expensive to debug.
         */
        refuse(op, reason, details, glError) {
            ++this.stats.refusals;
            const key = op + ":" + reason;
            this.stats.refusalsByOp[key] = (this.stats.refusalsByOp[key] || 0) + 1;
            if (glError && this.current) this.setError(glError);
            if (this.warned[key]) return;
            this.warned[key] = true;
            console.error("[gl-webgpu] refused " + op + ": " + reason,
                details || {});
        }

        setError(code) {
            const state = this.current;
            if (!state) return;
            // GL keeps the first error until it is read, which is what makes
            // glGetError usable for bisecting a bad call.
            if (state.error === GL.NO_ERROR) state.error = code;
        }

        getStats() {
            return { ...this.stats,
                contexts: this.contexts.size,
                pipelines: this.pipelineCache.size,
                bindGroups: this.bindGroupCache.size,
                shaders: this.shaderCache.size };
        }

        /* ---- context management ---- */

        makeCurrent(payload) {
            const view = new DataView(payload.buffer, payload.byteOffset,
                payload.byteLength);
            const hwnd = payload.byteLength >= 4 ? view.getUint32(0, true) : 0;
            const x = payload.byteLength >= 8 ? view.getInt32(4, true) : 0;
            const y = payload.byteLength >= 12 ? view.getInt32(8, true) : 0;
            const width = payload.byteLength >= 16 ? view.getUint32(12, true) : 0;
            const height = payload.byteLength >= 20 ? view.getUint32(16, true) : 0;
            const protocolId = payload.byteLength >= 24 ? view.getUint32(20, true) : 0;
            const protocolShareGroup = payload.byteLength >= 28 ?
                view.getUint32(24, true) : 0;
            const contextKey = protocolId ? "context:" + protocolId : "hwnd:" + hwnd;

            let context = this.contexts.get(contextKey);
            if (!context) {
                const groupKey = protocolShareGroup ?
                    "guest:" + protocolShareGroup : "private:" + this.nextShareGroupId;
                let group = this.shareGroups.get(groupKey);
                if (!group) {
                    group = createShareGroup(this.nextShareGroupId++);
                    group.protocolId = protocolShareGroup;
                    this.shareGroups.set(groupKey, group);
                }
                context = createContextState(this.nextContextId++, group);
                context.hwnd = hwnd;
                context.protocolId = protocolId;
                context.contextKey = contextKey;
                context.shareGroupKey = groupKey;
                this.contexts.set(contextKey, context);
                this.framebuffers.set(context.id, new Map());
            }
            context.hwnd = hwnd;
            this.current = context;
            if (width && height) {
                if (!context.viewport.width) {
                    context.viewport = { x: 0, y: 0, width, height };
                    context.scissor = { x: 0, y: 0, width, height, set: false };
                }
                this.resizeSurface(width, height);
            }
            // (whether other windows cover it stands until the next report)
            this.surface = { ...this.surface, hwnd, x, y, width, height, visible: true };
            this.notifySurface("current");
        }

        /*
         * V86GL_CTRL_WINDOW_STATE (opengl32_proxy.c): the drawing window as
         * the guest's window manager sees it, sent whenever that changes --
         * WinEvent hooks, not SwapBuffers, so a game that stops drawing while
         * another window covers it is still heard from.
         *
         *   u32 hwnd, u32 flags, i32 x, i32 y (the client area on the guest's
         *   screen), u32 width, u32 height (the client area), then with
         *   WINDOW_REGION: u32 count, count x (i32 left, top, right, bottom)
         *   in client coordinates -- the parts that show.
         *
         * The flags are D9WGWindowState's. A hidden or minimised window takes
         * the picture down; one covered entirely (Warcraft III's cinematic
         * popup) or in part keeps it, shown only where the window shows.
         */
        windowState(view, offset, size) {
            if (size < 24) {
                this.refuse("window-state", "payload too short", { size });
                return;
            }
            const hwnd = view.getUint32(offset, true);
            const flags = view.getUint32(offset + 4, true);
            const x = view.getInt32(offset + 8, true), y = view.getInt32(offset + 12, true);
            const width = view.getUint32(offset + 16, true), height = view.getUint32(offset + 20, true);
            const shown = (flags & WINDOW_IS_WINDOW) !== 0 && (flags & WINDOW_VISIBLE) !== 0 &&
                (flags & WINDOW_ICONIC) === 0;
            let visibleRegion = null;
            if ((flags & WINDOW_REGION) && size >= 28 && width && height) {
                const count = view.getUint32(offset + 24, true);
                if (count <= WINDOW_REGION_MAX_RECTS && size >= 28 + count * 16) {
                    const rects = [];
                    for (let i = 0; i < count; ++i) {
                        const at = offset + 28 + i * 16;
                        const r = { left: view.getInt32(at, true), top: view.getInt32(at + 4, true),
                            right: view.getInt32(at + 8, true), bottom: view.getInt32(at + 12, true) };
                        if (r.right > r.left && r.bottom > r.top) rects.push(r);
                    }
                    visibleRegion = { rects, baseWidth: width, baseHeight: height, originX: x, originY: y };
                }
            }
            this.windowStateReports = (this.windowStateReports || 0) + 1;
            if (!shown) {
                this.surface = { ...this.surface, visible: false };
                this.notifySurface("hide");
                return;
            }
            // (shown again: on screen with the next SwapBuffers)
            this.surface = { ...this.surface, hwnd,
                ...(width && height ? { x, y, width, height } : {}), visible: true,
                occluded: (flags & WINDOW_OCCLUDED) !== 0, visibleRegion };
            this.notifySurface("window-state");
        }

        releaseCurrent() {
            this.finishFrame(false);
            this.current = null;
        }

        destroyContext(payload) {
            this.finishFrame(false);
            let targets;
            if (payload && payload.byteLength >= 4) {
                const id = new DataView(payload.buffer, payload.byteOffset,
                    payload.byteLength).getUint32(0, true);
                const context = this.contexts.get("context:" + id);
                targets = context ? [context] : [];
            } else {
                // A payload-less destroy is process teardown from an older guest.
                targets = [...this.contexts.values()];
            }
            for (const context of targets) {
                this.contexts.delete(context.contextKey || ("hwnd:" + context.hwnd));
                this.framebuffers.delete(context.id);
                if (this.current === context) this.current = null;
            }
            for (const [key, group] of this.shareGroups) {
                const live = [...this.contexts.values()].some(context =>
                    context.shareGroup === group);
                if (!live) {
                    for (const texture of group.textures.values())
                        this.retire(texture.gpuTexture);
                    for (const buffer of group.buffers.values()) {
                        this.invalidateVertexConversions(buffer);
                        this.retire(buffer.gpuBuffer);
                    }
                    for (const rb of group.renderbuffers.values())
                        this.retire(rb.gpuTexture);
                    this.shareGroups.delete(key);
                }
            }
            if (!this.current) {
                this.surface = { ...this.surface, visible: false };
                this.notifySurface("hide");
            }
        }

        resetForReplay() {
            this.finishFrame(false);
            const release = object => {
                if (!object || typeof object.destroy !== "function") return;
                try { object.destroy(); } catch (ignored) { /* already gone */ }
            };
            for (const group of this.shareGroups.values()) {
                for (const texture of group.textures.values())
                    release(texture.gpuTexture);
                for (const buffer of group.buffers.values()) {
                    this.invalidateVertexConversions(buffer);
                    release(buffer.gpuBuffer);
                }
                for (const rb of group.renderbuffers.values())
                    release(rb.gpuTexture);
            }
            release(this.backBuffer);
            release(this.depthTarget);
            if (this.accumBuffer) {
                release(this.accumBuffer.textures && this.accumBuffer.textures[0]);
                release(this.accumBuffer.textures && this.accumBuffer.textures[1]);
            }
            for (const texture of this.logicTargetTextures || []) release(texture);
            this.releaseRetired();

            this.shareGroups.clear();
            this.contexts.clear();
            this.framebuffers.clear();
            this.queries.clear();
            release(this.activeOcclusionQuerySet);
            this.activeOcclusionQuerySet = null;
            this.activeQuery = null;
            this.pendingQueries = [];
            this.nextQuerySlot = 0;
            this.uniformValueCache.clear();
            this.stateUniformLayouts = new WeakMap();
            this.pixelMaps = Object.create(null);
            this.nextContextId = 1;
            this.nextShareGroupId = 1;
            this.nextUniformLocation = 1;
            this.current = null;
            this.pipelineCache.clear();
            this.bindGroupCache.clear();
            this.samplerCache.clear();
            this.moduleCache.clear();
            this.shaderCache.clear();
            this.indexExpansionCache.clear();
            if (this.ffCache) this.ffCache.clear();
            if (this.pixelPipelineCache) this.pixelPipelineCache.clear();
            if (this.accumPipelineCache) this.accumPipelineCache.clear();
            if (this.accumClearPipelineCache) this.accumClearPipelineCache.clear();
            if (this.clearPipelineCache) this.clearPipelineCache.clear();
            this.backBuffer = null;
            this.backBufferView = null;
            this.depthTarget = null;
            this.depthTargetView = null;
            this.accumBuffer = null;
            this.logicTargetTextures = [];
            this.logicTargetViews = [];
            this.pendingClear = null;
            this.vertexCursor = 0;
            this.uniformCursor = 0;
            this.surface = { hwnd: 0, x: 0, y: 0, width: 0, height: 0,
                             visible: false };
            this.notifySurface("hide");
        }

        notifySurface(reason) {
            const callback = this.options.onSurface;
            if (typeof callback === "function")
                callback({ ...this.surface, sessionKey: "gl" }, reason);
        }

        resizeSurface(width, height) {
            if (width === this.backBufferWidth && height === this.backBufferHeight)
                return;
            this.backBufferWidth = width;
            this.backBufferHeight = height;
            this.backBuffer = null;
            this.depthTarget = null;
            if (this.host) this.host.resizeCanvas(width, height);
        }

        /* ---- batch execution ---- */

        /*
         * Synchronous by construction.
         *
         * The guest is blocked inside DeviceIoControl while its port write runs
         * this code, and it reads the answer to glGetError, glGetIntegerv or
         * glGetUniformLocation straight out of the record as soon as the write
         * returns. Deferring the batch to a microtask would make every one of
         * those read stale memory -- which is why the authoritative GL state
         * lives here and why nothing on this path awaits the GPU (plan 4.8).
         *
         * Before the device exists there is nothing to be synchronous about, so
         * batches queue and replay in order once initialize() resolves. The
         * page creates the executor at load time precisely so that window is
         * empty by the time a guest runs.
         */
        submit(bytes, metadata) {
            if (!this.device) {
                this.pending.push({ bytes: bytes.slice(),
                                    metadata: metadata || {} });
                if (!this.draining) {
                    this.draining = true;
                    this.initialize().then(() => {
                        this.draining = false;
                        const queued = this.pending;
                        this.pending = [];
                        for (const item of queued)
                            this.executeBatch(item.bytes, item.metadata);
                    }).catch(() => {
                        this.draining = false;
                        this.pending.length = 0;
                    });
                }
                return;
            }
            this.executeBatch(bytes, metadata || {});
        }

        executeBatch(bytes, metadata) {
            ++this.stats.batches;
            const view = new DataView(bytes.buffer, bytes.byteOffset,
                bytes.byteLength);
            let offset = 0;
            const end = bytes.byteLength;
            while (offset < end) {
                if (offset + 4 > end) {
                    this.refuse("batch", "truncated record header",
                        { remaining: end - offset });
                    break;
                }
                const fn = view.getUint16(offset, true);
                let size = view.getUint16(offset + 2, true);
                offset += 4;
                if (size === 0xFFFF) {
                    if (offset + 4 > end) {
                        this.refuse("batch", "truncated extended length", { fn });
                        break;
                    }
                    size = view.getUint32(offset, true);
                    offset += 4;
                }
                if (offset + size > end) {
                    this.refuse("batch", "truncated record",
                        { fn, size, remaining: end - offset });
                    break;
                }
                ++this.stats.commands;
                try {
                    this.dispatch(fn, bytes, view, offset, size, metadata);
                    // Non-draw upload users (blits, pixel rectangles) also
                    // retire pages only once their complete GL command is encoded.
                    if (this.retireUploadPages()) this.flushFrame();
                } catch (error) {
                    if (error instanceof GLStreamError) {
                        /*
                         * A malformed record is a wire disagreement between
                         * the guest and this decoder, and "refused op40:
                         * client array blocks are truncated {}" says nothing
                         * about which of the two is wrong. The name and the
                         * first bytes do: the payload header is right there,
                         * and against openglproxy's struct it is usually one
                         * read to see whose offset moved.
                         */
                        this.refuse("op" + fn, error.message, {
                            name: constants.NAME_BY_OPCODE[fn] || "?",
                            size,
                            head: hexPreview(bytes, offset, size),
                        });
                    } else {
                        throw error;
                    }
                }
                offset += size;
            }
            this.beat(metadata);
        }

        dispatch(fn, bytes, view, offset, size, metadata) {

            if (fn === CTRL.MAKE_CURRENT)
                return this.makeCurrent(bytes.subarray(offset, offset + size));
            if (fn === CTRL.RELEASE_CURRENT) return this.releaseCurrent();
            if (fn === CTRL.DESTROY_CONTEXT)
                return this.destroyContext(bytes.subarray(offset, offset + size));
            if (fn === CTRL.WINDOW_STATE)
                return this.windowState(view, offset, size);

            const handler = this.handlers[fn];
            if (!handler) {
                this.refuse("op" + fn, "no handler",
                    { name: constants.NAME_BY_OPCODE[fn] || "?" });
                return;
            }
            if (!this.current && handler.needsContext !== false) {
                if (!this.contexts.size &&
                        isContextFreeTeardownNoop(fn, view, offset, size))
                    return;
                this.warnOnce("no-context",
                    "a GL command arrived with no current context; it is ignored",
                    { fn, name: constants.NAME_BY_OPCODE[fn] || "?" });
                return;
            }
            if (handler.signature) {
                const count = wire.decodeArgs(handler.signature, view, offset,
                    size, this.args);
                if (count < 0) {
                    this.refuse("op" + fn, "payload too short for signature",
                        { name: constants.NAME_BY_OPCODE[fn], size });
                    return;
                }
                return handler.call(this, this.args, bytes, view, offset, size,
                    metadata);
            }
            return handler.call(this, null, bytes, view, offset, size, metadata);
        }

        beat(metadata) {
            // The guest's readback timeout watches this counter rather than the
            // clock: a host thousands of batches behind is slow, not broken,
            // and the two need different reactions (plan 6.2).
            this.heartbeat = (this.heartbeat + 1) >>> 0;
            const write = this.options.writeGuestMemory;
            if (typeof write !== "function" || !metadata ||
                    metadata.responseBase === undefined)
                return;
            const bytes = new Uint8Array(4);
            new DataView(bytes.buffer).setUint32(0, this.heartbeat, true);
            try {
                write(metadata.responseBase + GLWG_HEARTBEAT_OFFSET, bytes, metadata);
            } catch (error) {
                this.warnOnce("heartbeat", "could not write the heartbeat counter",
                    { message: String(error) });
            }
        }
    }

    /* ================================================================== */
    /* Opcode handlers                                                    */
    /* ================================================================== */

    /*
     * One table, built once. A 217-way switch degenerates into a linear
     * comparison chain in V8, and this runs tens of thousands of times per
     * frame; a table also turns "which opcodes are unimplemented" into an
     * array scan, which is what feeds COVERAGE.md.
     */
    function buildHandlerTable() {
        const table = new Array(256).fill(null);

        const define = (name, handler, options) => {
            const opcode = GLFN[name];
            if (opcode === undefined)
                throw new Error("unknown opcode name " + name);
            const signature = SIGNATURES[name];
            if (signature && signature[1].length) handler.signature = signature[1];
            if (options && options.needsContext === false)
                handler.needsContext = false;
            handler.glName = signature ? signature[0] : name;
            table[opcode] = handler;
        };

        /* ---- framebuffer-wide state ---- */

        define("VIEWPORT", function(a) {
            const s = this.current;
            s.viewport = { x: a[0] | 0, y: a[1] | 0,
                           width: Math.max(0, a[2] | 0),
                           height: Math.max(0, a[3] | 0) };
            // GL's viewport origin is the lower left and so, after the clip
            // space flip, is WebGPU's: no conversion (plan 4.3).
        });

        define("SCISSOR", function(a) {
            const s = this.current;
            s.scissor = { x: a[0] | 0, y: a[1] | 0,
                          width: Math.max(0, a[2] | 0),
                          height: Math.max(0, a[3] | 0), set: true };
        });

        define("DEPTH_RANGE", function(a) {
            this.current.depthRange = { near: clamp(a[0], 0, 1),
                                        far: clamp(a[1], 0, 1) };
        });

        define("CLEAR_COLOR", function(a) {
            this.current.clearColor.set([a[0], a[1], a[2], a[3]]);
        });
        define("CLEAR_DEPTH", function(a) { this.current.clearDepth = clamp(a[0], 0, 1); });
        define("CLEAR_STENCIL", function(a) { this.current.clearStencil = a[0] | 0; });
        define("CLEAR_ACCUM", function(a) {
            this.current.clearAccum.set([a[0], a[1], a[2], a[3]]);
        });
        define("CLEAR", function(a) { this.clearBuffers(a[0] >>> 0); });

        /* ---- matrices ---- */

        define("MATRIX_MODE", function(a) { this.current.matrixMode = a[0] >>> 0; });
        define("LOAD_IDENTITY", function() { identity4(this.topMatrix()); this.matrixChanged(); });
        define("PUSH_MATRIX", function() { this.pushMatrix(); });
        define("POP_MATRIX", function() { this.popMatrix(); });
        define("TRANSLATEF", function(a) {
            const m = identity4(SCRATCH_A);
            m[12] = a[0]; m[13] = a[1]; m[14] = a[2];
            this.multiplyTop(m);
        });
        define("SCALEF", function(a) {
            const m = identity4(SCRATCH_A);
            m[0] = a[0]; m[5] = a[1]; m[10] = a[2];
            this.multiplyTop(m);
        });
        define("ROTATEF", function(a) {
            const angle = a[0] * Math.PI / 180;
            let x = a[1], y = a[2], z = a[3];
            const len = Math.sqrt(x * x + y * y + z * z);
            if (len === 0) return;
            x /= len; y /= len; z /= len;
            const c = Math.cos(angle), s = Math.sin(angle), t = 1 - c;
            const m = identity4(SCRATCH_A);
            m[0] = t*x*x + c;   m[4] = t*x*y - s*z; m[8]  = t*x*z + s*y;
            m[1] = t*x*y + s*z; m[5] = t*y*y + c;   m[9]  = t*y*z - s*x;
            m[2] = t*x*z - s*y; m[6] = t*y*z + s*x; m[10] = t*z*z + c;
            this.multiplyTop(m);
        });
        define("FRUSTUM", function(a) {
            const [l, r, b, t, n, f] = [a[0], a[1], a[2], a[3], a[4], a[5]];
            const m = identity4(SCRATCH_A);
            m[0] = 2 * n / (r - l); m[5] = 2 * n / (t - b);
            m[8] = (r + l) / (r - l); m[9] = (t + b) / (t - b);
            m[10] = -(f + n) / (f - n); m[11] = -1;
            m[14] = -2 * f * n / (f - n); m[15] = 0;
            m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[6] = 0; m[7] = 0;
            m[12] = 0; m[13] = 0;
            this.multiplyTop(m);
        });
        define("ORTHO", function(a) {
            const [l, r, b, t, n, f] = [a[0], a[1], a[2], a[3], a[4], a[5]];
            const m = identity4(SCRATCH_A);
            m[0] = 2 / (r - l); m[5] = 2 / (t - b); m[10] = -2 / (f - n);
            m[12] = -(r + l) / (r - l); m[13] = -(t + b) / (t - b);
            m[14] = -(f + n) / (f - n);
            this.multiplyTop(m);
        });
        define("LOAD_MATRIXF", function(a, bytes, view, offset, size) {
            if (size < 64) throw new GLStreamError("glLoadMatrixf needs 16 floats");
            const m = this.topMatrix();
            for (let i = 0; i < 16; ++i) m[i] = view.getFloat32(offset + i * 4, true);
            this.matrixChanged();
        });
        define("MULT_MATRIXF", function(a, bytes, view, offset, size) {
            if (size < 64) throw new GLStreamError("glMultMatrixf needs 16 floats");
            const m = SCRATCH_A;
            for (let i = 0; i < 16; ++i) m[i] = view.getFloat32(offset + i * 4, true);
            this.multiplyTop(m);
        });

        /* ---- enables and simple raster state ---- */

        define("ENABLE", function(a) { this.setCapability(a[0] >>> 0, true); });
        define("DISABLE", function(a) { this.setCapability(a[0] >>> 0, false); });
        define("DEPTH_FUNC", function(a) { this.current.depthFunc = a[0] >>> 0; });
        define("DEPTH_MASK", function(a) { this.current.depthMask = a[0] !== 0; });
        define("COLOR_MASK", function(a) {
            this.current.colorMask = [a[0] !== 0, a[1] !== 0, a[2] !== 0, a[3] !== 0];
        });
        define("SHADE_MODEL", function(a) { this.current.shadeModel = a[0] >>> 0; });
        define("CULL_FACE", function(a) { this.current.cullFace = a[0] >>> 0; });
        define("FRONT_FACE", function(a) { this.current.frontFace = a[0] >>> 0; });
        define("LINE_WIDTH", function(a) { this.current.lineWidth = Math.max(0, a[0]); });
        define("POINT_SIZE", function(a) {
            this.current.pointSize = Math.max(0, a[0]);
            this.current.point.size = this.current.pointSize;
        });
        define("POLYGON_MODE", function(a) {
            const face = a[0] >>> 0, mode = a[1] >>> 0;
            const s = this.current;
            if (face === GL.FRONT || face === GL.FRONT_AND_BACK) s.polygonMode.front = mode;
            if (face === GL.BACK || face === GL.FRONT_AND_BACK) s.polygonMode.back = mode;
        });
        define("POLYGON_OFFSET", function(a) {
            this.current.polygonOffset = { factor: a[0], units: a[1] };
        });
        define("LINE_STIPPLE", function(a) {
            this.current.lineStipple = { factor: clamp(a[0] | 0, 1, 256),
                                         pattern: a[1] & 0xffff };
        });
        define("LOGIC_OP", function(a) { this.current.logicOp = a[0] >>> 0; });
        define("HINT", function() { /* hints have no effect here */ });
        define("SAMPLE_COVERAGE", function(a) {
            this.current.sampleCoverage = { value: clamp(a[0], 0, 1),
                                            invert: a[1] !== 0 };
        });

        /* ---- blending, alpha test, stencil ---- */

        define("BLEND_FUNC", function(a) {
            const b = this.current.blend;
            b.srcRGB = b.srcAlpha = a[0] >>> 0;
            b.dstRGB = b.dstAlpha = a[1] >>> 0;
        });
        define("BLEND_FUNC_SEPARATE", function(a) {
            const b = this.current.blend;
            b.srcRGB = a[0] >>> 0; b.dstRGB = a[1] >>> 0;
            b.srcAlpha = a[2] >>> 0; b.dstAlpha = a[3] >>> 0;
        });
        define("BLEND_EQUATION", function(a) {
            const b = this.current.blend;
            b.equationRGB = b.equationAlpha = a[0] >>> 0;
        });
        define("BLEND_EQUATION_SEPARATE", function(a) {
            const b = this.current.blend;
            b.equationRGB = a[0] >>> 0; b.equationAlpha = a[1] >>> 0;
        });
        define("BLEND_COLOR", function(a) {
            this.current.blend.color.set([a[0], a[1], a[2], a[3]]);
        });
        define("ALPHA_FUNC", function(a) {
            this.current.alphaFunc = { func: a[0] >>> 0, ref: clamp(a[1], 0, 1) };
        });
        define("STENCIL_FUNC", function(a) {
            for (const face of ["front", "back"]) {
                const f = this.current.stencil[face];
                f.func = a[0] >>> 0; f.ref = a[1] | 0; f.valueMask = a[2] >>> 0;
            }
        });
        define("STENCIL_FUNC_SEPARATE", function(a) {
            const which = a[0] >>> 0;
            for (const face of facesOf(which)) {
                const f = this.current.stencil[face];
                f.func = a[1] >>> 0; f.ref = a[2] | 0; f.valueMask = a[3] >>> 0;
            }
        });
        define("STENCIL_OP", function(a) {
            for (const face of ["front", "back"]) {
                const f = this.current.stencil[face];
                f.fail = a[0] >>> 0; f.zfail = a[1] >>> 0; f.zpass = a[2] >>> 0;
            }
        });
        define("STENCIL_OP_SEPARATE", function(a) {
            for (const face of facesOf(a[0] >>> 0)) {
                const f = this.current.stencil[face];
                f.fail = a[1] >>> 0; f.zfail = a[2] >>> 0; f.zpass = a[3] >>> 0;
            }
        });
        define("STENCIL_MASK", function(a) {
            this.current.stencil.front.writeMask = a[0] >>> 0;
            this.current.stencil.back.writeMask = a[0] >>> 0;
        });
        define("STENCIL_MASK_SEPARATE", function(a) {
            for (const face of facesOf(a[0] >>> 0))
                this.current.stencil[face].writeMask = a[1] >>> 0;
        });

        /* ---- current vertex attributes and immediate mode ---- */

        define("BEGIN", function(a) { this.beginImmediate(a[0] >>> 0); });
        define("END", function() { this.endImmediate(); });
        define("COLOR4F", function(a) {
            this.current.current.color.set([a[0], a[1], a[2], a[3]]);
        });
        define("SECONDARY_COLOR3F", function(a) {
            this.current.current.secondaryColor.set([a[0], a[1], a[2], 1]);
        });
        define("NORMAL3F", function(a) {
            this.current.current.normal.set([a[0], a[1], a[2]]);
        });
        define("FOG_COORDF", function(a) { this.current.current.fogCoord = a[0]; });
        define("TEX_COORD2F", function(a) {
            this.current.current.texCoord[this.current.clientActiveTexture]
                .set([a[0], a[1], 0, 1]);
        });
        define("TEX_COORD4F", function(a) {
            this.current.current.texCoord[this.current.clientActiveTexture]
                .set([a[0], a[1], a[2], a[3]]);
        });
        define("MULTI_TEX_COORD4F", function(a) {
            const unit = (a[0] >>> 0) - GL.TEXTURE0;
            if (unit < 0 || unit >= MAX_TEXTURE_COORDS)
                return this.refuse("glMultiTexCoord", "texture unit out of range",
                    { unit }, GL.INVALID_ENUM);
            this.current.current.texCoord[unit].set([a[1], a[2], a[3], a[4]]);
        });
        define("VERTEX3F", function(a) { this.immediateVertex(a[0], a[1], a[2], 1); });
        define("VERTEX4F", function(a) { this.immediateVertex(a[0], a[1], a[2], a[3]); });
        define("RASTER_POS4F", function(a) { this.setRasterPos(a[0], a[1], a[2], a[3]); });
        define("WINDOW_POS3F", function(a) {
            // glWindowPos bypasses the transform: the value is already in
            // window coordinates and the position is always valid.
            const s = this.current;
            s.current.rasterPos.set([a[0], a[1], clamp(a[2], 0, 1), 1]);
            s.current.rasterValid = true;
        });
        define("VERTEX_ATTRIB4F", function(a) {
            const index = a[0] >>> 0;
            if (index >= MAX_VERTEX_ATTRIBS)
                return this.refuse("glVertexAttrib4f", "index out of range",
                    { index }, GL.INVALID_VALUE);
            this.current.genericAttribs[index].value.set([a[1], a[2], a[3], a[4]]);
        });

        /* ---- lighting and material ---- */

        define("LIGHT_MODELF", function(a) { this.setLightModel(a[0] >>> 0, [a[1]]); });
        define("LIGHT_MODELI", function(a) { this.setLightModel(a[0] >>> 0, [a[1]]); });
        define("LIGHT_MODELFV", function(a) {
            this.setLightModel(a[0] >>> 0, [a[2], a[3], a[4], a[5]], a[1] >>> 0);
        });
        define("LIGHT_MODELIV", function(a) {
            this.setLightModel(a[0] >>> 0,
                [a[2] / 2147483647, a[3] / 2147483647,
                 a[4] / 2147483647, a[5] / 2147483647], a[1] >>> 0);
        });
        define("LIGHTF", function(a) {
            this.setLight(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("LIGHTI", function(a) {
            this.setLight(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("LIGHTFV", function(a) {
            this.setLight(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("LIGHTIV", function(a) {
            this.setLight(a[0] >>> 0, a[1] >>> 0,
                [a[3] / 2147483647, a[4] / 2147483647,
                 a[5] / 2147483647, a[6] / 2147483647]);
        });
        define("MATERIALF", function(a) {
            this.setMaterial(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("MATERIALI", function(a) {
            this.setMaterial(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("MATERIALFV", function(a) {
            this.setMaterial(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("MATERIALIV", function(a) {
            this.setMaterial(a[0] >>> 0, a[1] >>> 0,
                [a[3] / 2147483647, a[4] / 2147483647,
                 a[5] / 2147483647, a[6] / 2147483647]);
        });
        define("COLOR_MATERIAL", function(a) {
            this.current.colorMaterial.face = a[0] >>> 0;
            this.current.colorMaterial.mode = a[1] >>> 0;
        });

        /* ---- fog ---- */

        define("FOGF", function(a) { this.setFog(a[0] >>> 0, [a[1]]); });
        define("FOGI", function(a) { this.setFog(a[0] >>> 0, [a[1]]); });
        define("FOGFV", function(a) {
            this.setFog(a[0] >>> 0, [a[2], a[3], a[4], a[5]]);
        });

        /* ---- clip planes ---- */

        define("CLIP_PLANE", function(a) {
            const index = (a[0] >>> 0) - GL.CLIP_PLANE0;
            if (index < 0 || index >= MAX_CLIP_PLANES)
                return this.refuse("glClipPlane", "plane index out of range",
                    { index }, GL.INVALID_ENUM);
            // GL specifies the plane in object coordinates and stores it
            // transformed by the inverse modelview at call time, so a later
            // modelview change does not move the plane.
            const s = this.current;
            const inv = invert4(this.topOf(GL.MODELVIEW), SCRATCH_B);
            const t = transpose4(inv, SCRATCH_C);
            const plane = new Float32Array([a[1], a[2], a[3], a[4]]);
            transformPoint4(t, plane, s.clipPlanes[index]);
        });

        /* ---- texture unit selection and environment ---- */

        define("ACTIVE_TEXTURE", function(a) {
            const unit = (a[0] >>> 0) - GL.TEXTURE0;
            if (unit < 0 || unit >= MAX_TEXTURE_UNITS)
                return this.refuse("glActiveTexture", "unit out of range",
                    { unit }, GL.INVALID_ENUM);
            this.current.activeTexture = unit;
        });
        define("CLIENT_ACTIVE_TEXTURE", function(a) {
            const unit = (a[0] >>> 0) - GL.TEXTURE0;
            if (unit < 0 || unit >= MAX_TEXTURE_COORDS)
                return this.refuse("glClientActiveTexture", "unit out of range",
                    { unit }, GL.INVALID_ENUM);
            this.current.clientActiveTexture = unit;
        });
        define("TEX_ENVI", function(a) {
            this.setTexEnv(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_ENVF", function(a) {
            this.setTexEnv(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_ENVIV", function(a) {
            this.setTexEnv(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("TEX_ENVFV", function(a) {
            this.setTexEnv(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("TEX_GENI", function(a) {
            this.setTexGen(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_GENF", function(a) {
            this.setTexGen(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_GENIV", function(a) {
            this.setTexGen(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("TEX_GENFV", function(a) {
            this.setTexGen(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });

        /* ---- pixel store and transfer ---- */

        define("PIXEL_STOREI", function(a) { this.setPixelStore(a[0] >>> 0, a[1] | 0); });
        define("PIXEL_TRANSFERF", function(a) { this.setPixelTransfer(a[0] >>> 0, a[1]); });
        define("PIXEL_TRANSFERI", function(a) { this.setPixelTransfer(a[0] >>> 0, a[1]); });
        define("PIXEL_ZOOM", function(a) {
            this.current.pixelZoom = { x: a[0], y: a[1] };
        });

        /* ---- point parameters ---- */

        define("POINT_PARAMETERF", function(a) {
            this.setPointParameter(a[0] >>> 0, [a[1]]);
        });
        define("POINT_PARAMETERI", function(a) {
            this.setPointParameter(a[0] >>> 0, [a[1]]);
        });
        define("POINT_PARAMETERFV", function(a) {
            this.setPointParameter(a[0] >>> 0, [a[1], a[2], a[3]]);
        });
        define("POINT_PARAMETERIV", function(a, bytes, view, offset, size) {
            if (size < 8) throw new GLStreamError("glPointParameteriv is too short");
            const pname = view.getUint32(offset, true);
            const values = [];
            for (let i = 4; i + 4 <= size; i += 4)
                values.push(view.getInt32(offset + i, true));
            this.setPointParameter(pname, values);
        });

        /* ---- client array enables ---- */

        define("ENABLE_CLIENT_STATE", function(a) {
            this.setClientState(a[0] >>> 0, true);
        });
        define("DISABLE_CLIENT_STATE", function(a) {
            this.setClientState(a[0] >>> 0, false);
        });
        define("ENABLE_VERTEX_ATTRIB_ARRAY", function(a) {
            const index = a[0] >>> 0;
            if (index < MAX_VERTEX_ATTRIBS) {
                this.current.genericAttribs[index].enabled = true;
                this.arrayState("generic" + index).enabled = true;
            }
        });
        define("DISABLE_VERTEX_ATTRIB_ARRAY", function(a) {
            const index = a[0] >>> 0;
            if (index < MAX_VERTEX_ATTRIBS) {
                this.current.genericAttribs[index].enabled = false;
                this.arrayState("generic" + index).enabled = false;
            }
        });

        /* ---- attribute stacks ---- */
        define("PUSH_ATTRIB", function(a) {
            const s = this.current;
            if (s.attribStack.length >= 16) {
                this.setError(GL.STACK_OVERFLOW);
                return;
            }
            const mask = a[0] >>> 0;
            const fields = fieldsForServerAttrib(mask);
            s.attribStack.push({ mask, fields, state: snapshotFields(s, fields),
                enableState: mask & ATTRIB.ENABLE ? captureEnableState(s) : null });
        });
        define("POP_ATTRIB", function() {
            const s = this.current;
            if (!s.attribStack.length) {
                this.setError(GL.STACK_UNDERFLOW);
                return;
            }
            const snapshot = s.attribStack.pop();
            restoreFields(s, snapshot.state, snapshot.fields);
            if (snapshot.enableState) restoreEnableState(s, snapshot.enableState);
            this.endPass();
            this.invalidateBindGroups();
        });
        define("PUSH_CLIENT_ATTRIB", function(a) {
            const s = this.current;
            if (s.clientAttribStack.length >= 16) {
                this.setError(GL.STACK_OVERFLOW);
                return;
            }
            const mask = a[0] >>> 0;
            const fields = [];
            if (mask & CLIENT_ATTRIB.PIXEL_STORE)
                fields.push("pixelStore", "pixelPackBuffer", "pixelUnpackBuffer");
            if (mask & CLIENT_ATTRIB.VERTEX_ARRAY)
                fields.push("clientActiveTexture", "arrays", "arrayBuffer",
                    "elementArrayBuffer", "genericAttribs");
            s.clientAttribStack.push({ mask, fields, state: snapshotFields(s, fields) });
        });
        define("POP_CLIENT_ATTRIB", function() {
            const s = this.current;
            if (!s.clientAttribStack.length) {
                this.setError(GL.STACK_UNDERFLOW);
                return;
            }
            const snapshot = s.clientAttribStack.pop();
            restoreFields(s, snapshot.state, snapshot.fields);
        });

        /* ---- frame boundaries ---- */

        define("FLUSH", function() { this.flushFrame(); });
        define("FINISH", function(a, bytes, view, offset, size, metadata) {
            return this.onFinish(bytes, view, offset, size, metadata);
        });

        return table;
    }

    function facesOf(which) {
        if (which === GL.FRONT) return ["front"];
        if (which === GL.BACK) return ["back"];
        return ["front", "back"];
    }

    const SCRATCH_A = new Float32Array(16);
    const SCRATCH_B = new Float32Array(16);
    const SCRATCH_C = new Float32Array(16);

    /* Shared by the handler-installing functions below. */
    function definer(table) {
        return (name, handler, options) => {
            const opcode = GLFN[name];
            if (opcode === undefined)
                throw new Error("unknown opcode name " + name);
            const signature = SIGNATURES[name];
            if (signature && signature[1].length) handler.signature = signature[1];
            if (options && options.needsContext === false)
                handler.needsContext = false;
            handler.glName = signature ? signature[0] : name;
            table[opcode] = handler;
        };
    }

    /* Reads a name array record: {count u32, names u32[count]}. */
    function readNameArray(view, offset, size) {
        if (size < 4) throw new GLStreamError("name array record is too short");
        const count = view.getUint32(offset, true);
        if (4 + count * 4 > size)
            throw new GLStreamError("name array record is truncated");
        const names = new Uint32Array(count);
        for (let i = 0; i < count; ++i)
            names[i] = view.getUint32(offset + 4 + i * 4, true);
        return names;
    }

    function readCString(bytes, offset, length) {
        let end = offset;
        const limit = offset + length;
        while (end < limit && bytes[end] !== 0) ++end;
        let text = "";
        for (let i = offset; i < end; ++i) text += String.fromCharCode(bytes[i]);
        return text;
    }

    /*
     * Writes `text` NUL-terminated into a guest buffer of `capacity` bytes and
     * returns the character count GL wants reported -- which excludes the
     * terminator, the same convention openglproxy's own copy_gl_string_result
     * uses when it answers one of these queries without the host.
     */
    function writeCString(bytes, offset, capacity, text) {
        if (capacity <= 0) return 0;
        const written = Math.min(text.length, capacity - 1);
        for (let i = 0; i < written; ++i)
            bytes[offset + i] = text.charCodeAt(i) & 0xff;
        bytes[offset + written] = 0;
        return written;
    }

    function installResourceHandlers(table) {
        const define = definer(table);

        /* ---- textures ---- */

        define("GEN_TEXTURES", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names) {
                if (!name) continue;
                if (!group.textures.has(name))
                    group.textures.set(name, createTexture(name));
            }
        });

        define("DELETE_TEXTURES", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names) {
                const texture = group.textures.get(name);
                if (!texture) continue;
                this.retire(texture.gpuTexture);
                group.textures.delete(name);
                // GL rebinds the default texture on every unit that held it,
                // which is what keeps a later draw from sampling a dead object.
                for (const unit of this.current.textureUnits) {
                    for (const target of Object.keys(unit.bindings))
                        if (unit.bindings[target] === name) unit.bindings[target] = 0;
                }
                this.invalidateBindGroups();
            }
        });

        define("BIND_TEXTURE", function(a) {
            const target = a[0] >>> 0, name = a[1] >>> 0;
            const unit = this.current.textureUnits[this.current.activeTexture];
            unit.bindings[target] = name;
            if (name) {
                const group = this.current.shareGroup;
                let texture = group.textures.get(name);
                if (!texture) {
                    texture = createTexture(name);
                    group.textures.set(name, texture);
                }
                if (!texture.target) texture.target = target;
            }
            this.invalidateBindGroups();
        });

        define("TEX_PARAMETERI", function(a) {
            this.setTexParameter(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_PARAMETERF", function(a) {
            this.setTexParameter(a[0] >>> 0, a[1] >>> 0, [a[2]]);
        });
        define("TEX_PARAMETERIV", function(a) {
            this.setTexParameter(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });
        define("TEX_PARAMETERFV", function(a) {
            this.setTexParameter(a[0] >>> 0, a[1] >>> 0, [a[3], a[4], a[5], a[6]]);
        });

        /*
         * glTexImage*: {target, level, internalFormat, width, height, depth,
         * border, format, type, dataSize} then dataSize bytes. The 1D and 2D
         * forms omit the dimensions they do not have; all three are decoded
         * through one function because everything after the header is identical.
         */
        const texImage = dimensions => function(a, bytes, view, offset, size) {
            const header = 4 * (7 + dimensions);
            if (size < header)
                throw new GLStreamError("glTexImage record is too short");
            let at = offset;
            const target = view.getUint32(at, true); at += 4;
            const level = view.getInt32(at, true); at += 4;
            const internalFormat = view.getUint32(at, true); at += 4;
            const width = view.getInt32(at, true); at += 4;
            const height = dimensions >= 2 ? view.getInt32(at, true) : 1;
            if (dimensions >= 2) at += 4;
            const depth = dimensions >= 3 ? view.getInt32(at, true) : 1;
            if (dimensions >= 3) at += 4;
            at += 4;                            // border
            const format = view.getUint32(at, true); at += 4;
            const type = view.getUint32(at, true); at += 4;
            const dataSize = view.getUint32(at, true); at += 4;
            const data = dataSize ?
                bytes.subarray(at, at + dataSize) :
                null;
            this.texImage(target, level, internalFormat, width, height, depth,
                format, type, data, dataSize);
        };
        define("TEX_IMAGE_1D", texImage(1));
        define("TEX_IMAGE_2D", texImage(2));
        define("TEX_IMAGE_3D", texImage(3));

        const texSubImage = dimensions => function(a, bytes, view, offset, size) {
            const header = 4 * (5 + dimensions * 2);
            if (size < header)
                throw new GLStreamError("glTexSubImage record is too short");
            let at = offset;
            const target = view.getUint32(at, true); at += 4;
            const level = view.getInt32(at, true); at += 4;
            const x = view.getInt32(at, true); at += 4;
            const y = dimensions >= 2 ? view.getInt32(at, true) : 0;
            if (dimensions >= 2) at += 4;
            const z = dimensions >= 3 ? view.getInt32(at, true) : 0;
            if (dimensions >= 3) at += 4;
            const width = view.getInt32(at, true); at += 4;
            const height = dimensions >= 2 ? view.getInt32(at, true) : 1;
            if (dimensions >= 2) at += 4;
            const depth = dimensions >= 3 ? view.getInt32(at, true) : 1;
            if (dimensions >= 3) at += 4;
            const format = view.getUint32(at, true); at += 4;
            const type = view.getUint32(at, true); at += 4;
            const dataSize = view.getUint32(at, true); at += 4;
            const data = dataSize ?
                bytes.subarray(at, at + dataSize) :
                null;
            this.texSubImage(target, level, x, y, z, width, height, depth,
                format, type, data, dataSize);
        };
        define("TEX_SUB_IMAGE_1D", texSubImage(1));
        define("TEX_SUB_IMAGE_2D", texSubImage(2));
        define("TEX_SUB_IMAGE_3D", texSubImage(3));

        const compressedTexImage = dimensions => function(a, bytes, view, offset, size) {
            // The guest deliberately uses one fixed wire struct for the 1D,
            // 2D and 3D entry points.  height and depth are therefore present
            // even for a 2D command (where depth is 1).  Parsing a
            // dimension-dependent header used to read the 2D border field as
            // imageSize, turning every real DXT payload into zero bytes.
            if (size < 32)
                throw new GLStreamError("compressed texture record is too short");
            let at = offset;
            const target = view.getUint32(at, true); at += 4;
            const level = view.getInt32(at, true); at += 4;
            const internalFormat = view.getUint32(at, true); at += 4;
            const width = view.getInt32(at, true); at += 4;
            const wireHeight = view.getInt32(at, true); at += 4;
            const wireDepth = view.getInt32(at, true); at += 4;
            at += 4;                            // border
            const dataSize = view.getUint32(at, true); at += 4;
            if (at - offset + dataSize > size)
                throw new GLStreamError("compressed texture record is truncated");
            const data = bytes.subarray(at, at + dataSize);
            const height = dimensions >= 2 ? wireHeight : 1;
            const depth = dimensions >= 3 ? wireDepth : 1;
            this.compressedTexImage(target, level, internalFormat, width, height,
                depth, data);
        };
        define("COMPRESSED_TEX_IMAGE_1D", compressedTexImage(1));
        define("COMPRESSED_TEX_IMAGE_2D", compressedTexImage(2));
        define("COMPRESSED_TEX_IMAGE_3D", compressedTexImage(3));

        const compressedTexSubImage = dimensions => function(a, bytes, view, offset, size) {
            // A partial update of a compressed level must land on block
            // boundaries; GL requires it and WebGPU enforces it, so a
            // misaligned rectangle is refused rather than silently rounded.
            // As above, the guest payload is the same fixed 40-byte struct for
            // all three dimensionalities.
            if (size < 40)
                throw new GLStreamError("compressed subimage record is too short");
            let at = offset;
            const target = view.getUint32(at, true); at += 4;
            const level = view.getInt32(at, true); at += 4;
            const x = view.getInt32(at, true); at += 4;
            const wireY = view.getInt32(at, true); at += 4;
            const wireZ = view.getInt32(at, true); at += 4;
            const width = view.getInt32(at, true); at += 4;
            const wireHeight = view.getInt32(at, true); at += 4;
            const wireDepth = view.getInt32(at, true); at += 4;
            const format = view.getUint32(at, true); at += 4;
            const dataSize = view.getUint32(at, true); at += 4;
            if (at - offset + dataSize > size)
                throw new GLStreamError("compressed subimage record is truncated");
            const data = bytes.subarray(at, at + dataSize);
            const y = dimensions >= 2 ? wireY : 0;
            const z = dimensions >= 3 ? wireZ : 0;
            const height = dimensions >= 2 ? wireHeight : 1;
            const depth = dimensions >= 3 ? wireDepth : 1;
            this.compressedTexSubImage(target, level, x, y, z, width, height,
                depth, format, data);
        };
        define("COMPRESSED_TEX_SUB_IMAGE_1D", compressedTexSubImage(1));
        define("COMPRESSED_TEX_SUB_IMAGE_2D", compressedTexSubImage(2));
        define("COMPRESSED_TEX_SUB_IMAGE_3D", compressedTexSubImage(3));

        define("GENERATE_MIPMAP", function(a) {
            this.generateMipmap(a[0] >>> 0);
        });

        define("COPY_TEX_IMAGE_2D", function(a) {
            this.copyTexImage(a[0] >>> 0, a[1] | 0, a[2] >>> 0, a[3] | 0, a[4] | 0,
                a[5] | 0, a[6] | 0);
        });
        define("COPY_TEX_IMAGE_1D", function(a) {
            this.copyTexImage(a[0] >>> 0, a[1] | 0, a[2] >>> 0, a[3] | 0, a[4] | 0,
                a[5] | 0, 1);
        });
        define("COPY_TEX_SUB_IMAGE_2D", function(a) {
            this.copyTexSubImage(a[0] >>> 0, a[1] | 0, a[2] | 0, a[3] | 0, 0,
                a[4] | 0, a[5] | 0, a[6] | 0, a[7] | 0);
        });
        define("COPY_TEX_SUB_IMAGE_1D", function(a) {
            this.copyTexSubImage(a[0] >>> 0, a[1] | 0, a[2] | 0, 0, 0,
                a[3] | 0, a[4] | 0, a[5] | 0, 1);
        });
        define("COPY_TEX_SUB_IMAGE_3D", function(a) {
            this.copyTexSubImage(a[0] >>> 0, a[1] | 0, a[2] | 0, a[3] | 0, a[4] | 0,
                a[5] | 0, a[6] | 0, a[7] | 0, a[8] | 0);
        });

        /* ---- buffers ---- */

        define("GEN_BUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names)
                if (name && !group.buffers.has(name))
                    group.buffers.set(name, createBuffer(name));
        });
        define("DELETE_BUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names) {
                const buffer = group.buffers.get(name);
                if (!buffer) continue;
                this.invalidateVertexConversions(buffer);
                this.retire(buffer.gpuBuffer);
                group.buffers.delete(name);
                if (this.current.arrayBuffer === name) this.current.arrayBuffer = 0;
                if (this.current.elementArrayBuffer === name)
                    this.current.elementArrayBuffer = 0;
            }
        });
        define("BIND_BUFFER", function(a) {
            const target = a[0] >>> 0, name = a[1] >>> 0;
            const group = this.current.shareGroup;
            if (name && !group.buffers.has(name))
                group.buffers.set(name, createBuffer(name));
            if (target === GL.ELEMENT_ARRAY_BUFFER)
                this.current.elementArrayBuffer = name;
            else if (target === GL.PIXEL_PACK_BUFFER)
                this.current.pixelPackBuffer = name;
            else if (target === GL.PIXEL_UNPACK_BUFFER)
                this.current.pixelUnpackBuffer = name;
            else if (target === GL.ARRAY_BUFFER)
                this.current.arrayBuffer = name;
            else
                return this.refuse("glBindBuffer", "unknown buffer target",
                    { target }, GL.INVALID_ENUM);
        });
        /*
         * {target, size, usage, data_size} then the contents. The header is
         * four words: reading the data from 12 shifts every vertex in the
         * buffer by one attribute and draws geometry that is subtly wrong
         * rather than reporting anything.
         */
        define("BUFFER_DATA", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("glBufferData record is short");
            const target = view.getUint32(offset, true);
            const byteCount = view.getUint32(offset + 4, true);
            const usage = view.getUint32(offset + 8, true);
            const dataSize = Math.min(view.getUint32(offset + 12, true), size - 16);
            const data = dataSize ?
                bytes.subarray(offset + 16,
                    offset + 16 + Math.min(dataSize, byteCount)) :
                null;
            this.bufferData(target, byteCount, usage, data);
        });
        /* {target, offset, size, data_size} then the contents. */
        define("BUFFER_SUB_DATA", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("glBufferSubData record is short");
            const target = view.getUint32(offset, true);
            const dstOffset = view.getUint32(offset + 4, true);
            const byteCount = Math.min(view.getUint32(offset + 8, true), size - 16);
            const data = bytes.subarray(offset + 16,
                offset + 16 + byteCount);
            this.bufferSubData(target, dstOffset, data);
        });

        /* ---- VBO-backed array pointers ---- */

        const pointerVBO = which => function(a, bytes, view, offset, size) {
            if (size < 16)
                throw new GLStreamError("VBO pointer record is short");
            const s = this.current;
            const array = {
                buffer: s.arrayBuffer,
                size: view.getInt32(offset, true),
                type: view.getUint32(offset + 4, true),
                stride: view.getInt32(offset + 8, true),
                offset: view.getUint32(offset + 12, true),
                normalized: which === "color" || which === "secondaryColor" ||
                    which === "normal",
                fromVBO: true,
            };
            this.setArrayPointer(which, array);
        };
        define("VERTEX_POINTER_VBO", pointerVBO("vertex"));
        define("COLOR_POINTER_VBO", pointerVBO("color"));
        define("NORMAL_POINTER_VBO", pointerVBO("normal"));
        define("SECONDARY_COLOR_POINTER_VBO", pointerVBO("secondaryColor"));
        define("FOG_COORD_POINTER_VBO", pointerVBO("fogCoord"));
        define("TEX_COORD_POINTER_VBO", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("VBO pointer record is short");
            const s = this.current;
            this.setArrayPointer("texCoord" + s.clientActiveTexture, {
                buffer: s.arrayBuffer,
                size: view.getInt32(offset, true),
                type: view.getUint32(offset + 4, true),
                stride: view.getInt32(offset + 8, true),
                offset: view.getUint32(offset + 12, true),
                normalized: false, fromVBO: true,
            });
        });
        define("VERTEX_ATTRIB_POINTER_VBO", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("attrib pointer record is short");
            const index = view.getUint32(offset, true);
            if (index >= MAX_VERTEX_ATTRIBS)
                return this.refuse("glVertexAttribPointer", "index out of range",
                    { index }, GL.INVALID_VALUE);
            this.setArrayPointer("generic" + index, {
                // glVertexAttribPointer changes the array format only.  Its
                // enable is independent state controlled by
                // glEnable/DisableVertexAttribArray; forcing it on here made
                // Cube 2's disabled vcolor array keep reading a stale world
                // VBO instead of the current constant colour used by models.
                enabled: this.current.genericAttribs[index].enabled,
                buffer: this.current.arrayBuffer,
                size: view.getInt32(offset + 4, true),
                type: view.getUint32(offset + 8, true),
                normalized: view.getUint32(offset + 12, true) !== 0,
                stride: view.getInt32(offset + 16, true),
                offset: view.getUint32(offset + 20, true),
                fromVBO: true,
            });
        });

        /* ---- framebuffer objects ---- */

        define("GEN_FRAMEBUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const map = this.framebuffers.get(this.current.id);
            for (const name of names)
                if (name && !map.has(name)) map.set(name, createFramebuffer(name));
        });
        define("DELETE_FRAMEBUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const map = this.framebuffers.get(this.current.id);
            for (const name of names) {
                map.delete(name);
                if (this.current.drawFramebuffer === name)
                    this.current.drawFramebuffer = 0;
                if (this.current.readFramebuffer === name)
                    this.current.readFramebuffer = 0;
            }
        });
        define("BIND_FRAMEBUFFER", function(a) {
            const target = a[0] >>> 0, name = a[1] >>> 0;
            const map = this.framebuffers.get(this.current.id);
            if (name && !map.has(name)) map.set(name, createFramebuffer(name));
            // Changing the render target ends the pass: WebGPU fixes the
            // attachments when the pass begins.
            this.endPass();
            if (target === GL.READ_FRAMEBUFFER) {
                this.current.readFramebuffer = name;
            } else if (target === GL.DRAW_FRAMEBUFFER) {
                this.current.drawFramebuffer = name;
            } else {
                this.current.drawFramebuffer = name;
                this.current.readFramebuffer = name;
            }
        });
        define("FRAMEBUFFER_TEXTURE", function(a) {
            this.framebufferTexture(a[0] >>> 0, a[1] >>> 0, a[2] >>> 0,
                a[3] >>> 0, a[4] | 0, a[5] | 0);
        });
        define("FRAMEBUFFER_RENDERBUFFER", function(a) {
            this.framebufferRenderbuffer(a[0] >>> 0, a[1] >>> 0, a[2] >>> 0,
                a[3] >>> 0);
        });
        define("GEN_RENDERBUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names)
                if (name && !group.renderbuffers.has(name))
                    group.renderbuffers.set(name, createRenderbuffer(name));
        });
        define("DELETE_RENDERBUFFERS", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names) {
                const rb = group.renderbuffers.get(name);
                if (rb) this.retire(rb.gpuTexture);
                group.renderbuffers.delete(name);
                if (this.current.renderbuffer === name) this.current.renderbuffer = 0;
            }
        });
        define("BIND_RENDERBUFFER", function(a) {
            const name = a[1] >>> 0;
            const group = this.current.shareGroup;
            if (name && !group.renderbuffers.has(name))
                group.renderbuffers.set(name, createRenderbuffer(name));
            this.current.renderbuffer = name;
        });
        define("RENDERBUFFER_STORAGE", function(a) {
            this.renderbufferStorage(a[1] >>> 0, a[2] | 0, a[3] | 0);
        });
        define("DRAW_BUFFER", function(a) {
            this.endPass();
            this.current.drawBuffers = [a[0] >>> 0];
        });
        define("READ_BUFFER", function(a) { this.current.readBuffer = a[0] >>> 0; });
        define("DRAW_BUFFERS", function(a, bytes, view, offset, size) {
            const count = size >= 4 ? view.getUint32(offset, true) : 0;
            const buffers = [];
            for (let i = 0; i < count && 4 + i * 4 + 4 <= size; ++i)
                buffers.push(view.getUint32(offset + 4 + i * 4, true));
            this.endPass();
            this.current.drawBuffers = buffers.length ? buffers : [GL.NONE];
        });
        define("BLIT_FRAMEBUFFER", function(a) {
            this.blitFramebuffer(a[0] | 0, a[1] | 0, a[2] | 0, a[3] | 0,
                a[4] | 0, a[5] | 0, a[6] | 0, a[7] | 0, a[8] >>> 0, a[9] >>> 0);
        });

        /* ---- occlusion queries ---- */

        define("GEN_QUERIES", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            for (const name of names)
                if (name && !this.queries.has(name))
                    this.queries.set(name, { name, result: 0, ready: true,
                                             active: false, slot: -1,
                                             generation: 0 });
        });
        define("DELETE_QUERIES", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            for (const name of names) this.queries.delete(name);
        });
        define("BEGIN_QUERY", function(a) { this.beginQuery(a[0] >>> 0, a[1] >>> 0); });
        define("END_QUERY", function(a) { this.endQuery(a[0] >>> 0); });
    }

    /* The guest observes these in the record it submitted, so the values are
     * part of the wire contract and not an internal detail. */
    const SYNC_STATUS_PENDING = 0;
    const SYNC_STATUS_OK = 1;
    const SYNC_STATUS_FAILED = 2;
    const READ_PIXELS_HEADER_SIZE = 32;

    /* openglproxy's V86GL_PROGRAM_PARAMETER_ENV / _LOCAL. */
    const PROGRAM_PARAMETER_ENV = 1;
    const PROGRAM_PARAMETER_LOCAL = 2;

    /*
     * V86GL_LOCATION_KIND_* and V86GL_ACTIVE_KIND_*. Uniform is 1 in both --
     * getting the pair the other way round is invisible until an application
     * asks for a uniform location and is handed an attribute's.
     */
    const LOCATION_KIND_ATTRIB = 2;
    const ACTIVE_KIND_ATTRIB = 2;

    /*
     * ARB program environment and local parameters are context state that the
     * extension lets an application set before -- or without ever -- handing
     * the target a program that compiles, so the storage is allocated with the
     * program object rather than at the end of a successful assemble.
     */
    function arbParameterStorage(program, kind) {
        if (!program.env) {
            program.env = new Float32Array(
                arbProgram.MAX_PROGRAM_PARAMETERS * 4);
            program.local = new Float32Array(
                arbProgram.MAX_PROGRAM_PARAMETERS * 4);
        }
        return kind === PROGRAM_PARAMETER_LOCAL ? program.local : program.env;
    }

    function installProgramHandlers(table) {
        const define = definer(table);

        define("CREATE_PROGRAM", function(a) {
            const name = a[0] >>> 0;
            const group = this.current.shareGroup;
            if (!group.programs.has(name))
                group.programs.set(name, createProgram(name));
        });
        define("CREATE_SHADER", function(a) {
            const name = a[0] >>> 0, type = a[1] >>> 0;
            const group = this.current.shareGroup;
            group.shaders.set(name, {
                name, type, source: "", compiled: null,
                stage: type === GL.VERTEX_SHADER ? "vertex" : "fragment",
            });
        });
        define("DELETE_PROGRAM", function(a) {
            this.current.shareGroup.programs.delete(a[0] >>> 0);
        });
        define("DELETE_SHADER", function(a) {
            this.current.shareGroup.shaders.delete(a[0] >>> 0);
        });
        define("ATTACH_SHADER", function(a) {
            const program = this.current.shareGroup.programs.get(a[0] >>> 0);
            if (program) program.shaders.add(a[1] >>> 0);
        });
        define("DETACH_SHADER", function(a) {
            const program = this.current.shareGroup.programs.get(a[0] >>> 0);
            if (program) program.shaders.delete(a[1] >>> 0);
        });
        define("SHADER_SOURCE", function(a, bytes, view, offset, size) {
            if (size < 8) throw new GLStreamError("glShaderSource record is short");
            const name = view.getUint32(offset, true);
            const length = view.getUint32(offset + 4, true);
            if (8 + length > size)
                throw new GLStreamError("glShaderSource record is truncated");
            const shader = this.current.shareGroup.shaders.get(name);
            if (!shader)
                return this.refuse("glShaderSource", "unknown shader",
                    { name }, GL.INVALID_VALUE);
            shader.source = readCString(bytes, offset + 8, length);
            shader.compiled = null;
        });
        define("COMPILE_SHADER", function(a) {
            const shader = this.current.shareGroup.shaders.get(a[0] >>> 0);
            if (!shader)
                return this.refuse("glCompileShader", "unknown shader",
                    { name: a[0] }, GL.INVALID_VALUE);
            shader.compiled = translator.compileShader(shader.source,
                shader.stage, this.options.translator || {});
        });
        define("LINK_PROGRAM", function(a) { this.linkProgram(a[0] >>> 0); });
        define("USE_PROGRAM", function(a) {
            this.current.currentProgram = a[0] >>> 0;
        });
        define("VALIDATE_PROGRAM", function(a) {
            const program = this.current.shareGroup.programs.get(a[0] >>> 0);
            if (program)
                program.validateLog = program.linked ? "" :
                    "program is not linked";
        });
        define("BIND_ATTRIB_LOCATION", function(a, bytes, view, offset, size) {
            if (size < 12) throw new GLStreamError("bind-attrib record is short");
            const programName = view.getUint32(offset, true);
            const location = view.getInt32(offset + 4, true);
            const nameLength = view.getUint32(offset + 8, true);
            const program = this.current.shareGroup.programs.get(programName);
            if (!program) return;
            const attribute = readCString(bytes, offset + 12, nameLength);
            // Takes effect at the next link, exactly as GL specifies.
            program.bindAttribLocations.set(attribute, location);
        });
        define("MAP_UNIFORM_LOCATION", function() { /* answered by QUERY_LOCATION */ });
        define("MAP_ATTRIB_LOCATION", function() { /* answered by QUERY_LOCATION */ });
        define("INVALIDATE_PROGRAM_LOCATIONS", function(a) {
            const program = this.current.shareGroup.programs.get(a[0] >>> 0);
            if (program) ++program.serial;
        });

        define("UNIFORM_FV", function(a, bytes, view, offset, size) {
            this.setUniformVector(view, offset, size, bytes, false);
        });
        define("UNIFORM_IV", function(a, bytes, view, offset, size) {
            this.setUniformVector(view, offset, size, bytes, true);
        });
        define("UNIFORM_MATRIX_FV", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("uniform-matrix record is short");
            const location = view.getInt32(offset, true);
            const dimension = view.getInt32(offset + 4, true);
            const count = view.getInt32(offset + 8, true);
            const transpose = view.getUint32(offset + 12, true) !== 0;
            this.setUniformMatrix(location, dimension, dimension, count,
                transpose, view, offset + 16, size - 16);
        });
        define("UNIFORM_MATRIX_RECT_FV", function(a, bytes, view, offset, size) {
            if (size < 20) throw new GLStreamError("uniform-matrix record is short");
            const location = view.getInt32(offset, true);
            const columns = view.getInt32(offset + 4, true);
            const rows = view.getInt32(offset + 8, true);
            const count = view.getInt32(offset + 12, true);
            const transpose = view.getUint32(offset + 16, true) !== 0;
            this.setUniformMatrix(location, columns, rows, count, transpose,
                view, offset + 20, size - 20);
        });

        /* ---- synchronous queries -------------------------------------- *
         *
         * These are answered in place, before the record's handler returns,
         * because the guest is blocked inside DeviceIoControl waiting for the
         * status word. That is only possible because the authoritative GL
         * state lives here: none of them touches the GPU (plan 4.8).
         */

        define("QUERY_ERROR", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("query-error record is short");
            const state = this.current;
            const error = state ? state.error : GL.NO_ERROR;
            if (state) state.error = GL.NO_ERROR;
            view.setUint32(offset, SYNC_STATUS_OK, true);
            view.setUint32(offset + 4, error, true);
        }, { needsContext: false });

        define("QUERY_INTEGER", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("query-integer record is short");
            const pname = view.getUint32(offset, true);
            const value = this.queryInteger(pname);
            if (value === null) {
                view.setUint32(offset + 4, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 4, SYNC_STATUS_OK, true);
            view.setUint32(offset + 8, value >>> 0, true);
        }, { needsContext: false });

        define("QUERY_GL_STRING", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("query-string record is short");
            const pname = view.getUint32(offset, true);
            const capacity = view.getUint32(offset + 12, true);
            const text = this.queryString(pname);
            if (text === null || 16 + capacity > size) {
                view.setUint32(offset + 4, SYNC_STATUS_FAILED, true);
                return;
            }
            const encoded = [];
            for (let i = 0; i < text.length; ++i) encoded.push(text.charCodeAt(i) & 0xff);
            encoded.push(0);
            view.setUint32(offset + 4, SYNC_STATUS_OK, true);
            view.setUint32(offset + 8, encoded.length, true);
            const limit = Math.min(encoded.length, capacity);
            for (let i = 0; i < limit; ++i)
                bytes[offset + 16 + i] = encoded[i];
        }, { needsContext: false });

        define("QUERY_LOCATION", function(a, bytes, view, offset, size) {
            if (size < 32) throw new GLStreamError("query-location record is short");
            const kind = view.getUint32(offset, true);
            const programName = view.getUint32(offset + 4, true);
            const nameLength = view.getUint32(offset + 28, true);
            if (32 + nameLength > size) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            const name = readCString(bytes, offset + 32, nameLength);
            const info = this.queryLocation(kind, programName, name);
            if (!info) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 12, SYNC_STATUS_OK, true);
            view.setUint32(offset + 16, info.location >>> 0, true);
            view.setUint32(offset + 20, info.type >>> 0, true);
            view.setUint32(offset + 24, info.size >>> 0, true);
        });

        define("QUERY_UNIFORM", function(a, bytes, view, offset, size) {
            if (size < 32) throw new GLStreamError("query-uniform record is short");
            const programName = view.getUint32(offset, true);
            const location = view.getInt32(offset + 4, true);
            const valueKind = view.getUint32(offset + 8, true);
            const values = this.readUniform(programName, location, valueKind);
            if (!values || !values.length || values.length > 16) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 12, SYNC_STATUS_OK, true);
            view.setUint32(offset + 16, values.length, true);
            for (let i = 0; i < values.length; ++i) {
                if (valueKind === 2) view.setInt32(offset + 32 + i * 4, values[i] | 0, true);
                else view.setFloat32(offset + 32 + i * 4, values[i], true);
            }
        });

        define("QUERY_OBJECT_IV", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("query-object record is short");
            const kind = view.getUint32(offset, true);
            const name = view.getUint32(offset + 4, true);
            const pname = view.getUint32(offset + 8, true);
            const value = this.queryObjectiv(kind, name, pname);
            if (value === null) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 12, SYNC_STATUS_OK, true);
            view.setUint32(offset + 16, value >>> 0, true);
        });

        /*
         * {kind, name, buf_size, status, length, data_size} then the text.
         * The header is six words, so the string starts at 24 and not at 20:
         * openglproxy reads it back at sizeof(request), and four bytes of slip
         * here hand glGetShaderInfoLog a log that is missing its first word.
         */
        define("QUERY_OBJECT_LOG", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("query-log record is short");
            const kind = view.getUint32(offset, true);
            const name = view.getUint32(offset + 4, true);
            const capacity = view.getUint32(offset + 8, true);
            const text = this.queryObjectLog(kind, name);
            if (text === null || 24 + capacity > size) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 12, SYNC_STATUS_OK, true);
            view.setUint32(offset + 16,
                writeCString(bytes, offset + 24, capacity,
                    text), true);
        });

        /*
         * {kind, program, index, buf_size, status, length, size, type,
         * data_size, reserved} then the name -- ten words, so the name starts
         * at 40. length comes before size and type, which is the order
         * glGetActiveUniform's own out-parameters are in.
         */
        define("QUERY_ACTIVE", function(a, bytes, view, offset, size) {
            if (size < 40) throw new GLStreamError("query-active record is short");
            const kind = view.getUint32(offset, true);
            const programName = view.getUint32(offset + 4, true);
            const index = view.getUint32(offset + 8, true);
            const capacity = view.getUint32(offset + 12, true);
            const info = this.queryActive(kind, programName, index);
            if (!info || 40 + capacity > size) {
                view.setUint32(offset + 16, SYNC_STATUS_FAILED, true);
                return;
            }
            view.setUint32(offset + 16, SYNC_STATUS_OK, true);
            view.setUint32(offset + 20,
                writeCString(bytes, offset + 40, capacity,
                    info.name), true);
            view.setUint32(offset + 24, info.size >>> 0, true);
            view.setUint32(offset + 28, info.type >>> 0, true);
        });

        define("CHECK_FRAMEBUFFER_STATUS", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("fbo-status record is short");
            const target = view.getUint32(offset, true);
            const status = this.checkFramebufferStatus(target);
            view.setUint32(offset + 4, SYNC_STATUS_OK, true);
            view.setUint32(offset + 8, status >>> 0, true);
        });

        /* ---- ARB assembly programs ---- */

        define("GEN_PROGRAMS_ARB", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            const group = this.current.shareGroup;
            for (const name of names)
                if (name && !group.arbPrograms.has(name))
                    group.arbPrograms.set(name, {
                        name, target: 0, source: "", compiled: null,
                        env: null, local: null, variants: new Map(),
                    });
        });
        define("DELETE_PROGRAMS_ARB", function(a, bytes, view, offset, size) {
            const names = readNameArray(view, offset, size);
            for (const name of names)
                this.current.shareGroup.arbPrograms.delete(name);
        });
        define("BIND_PROGRAM_ARB", function(a) {
            const target = a[0] >>> 0, name = a[1] >>> 0;
            const group = this.current.shareGroup;
            if (name && !group.arbPrograms.has(name))
                group.arbPrograms.set(name, { name, target, source: "",
                    compiled: null, env: null, local: null,
                    variants: new Map() });
            if (target === GL.VERTEX_PROGRAM_ARB) this.current.arbVertexProgram = name;
            else this.current.arbFragmentProgram = name;
        });
        define("PROGRAM_STRING_ARB", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("ARB program record is short");
            const target = view.getUint32(offset, true);
            const length = view.getInt32(offset + 8, true);
            if (length < 0 || 16 + length > size)
                throw new GLStreamError("ARB program record is truncated");
            const source = readCString(bytes, offset + 16, length);
            this.programStringARB(target, source);
        });
        define("PROGRAM_PARAMETER_FV_ARB", function(a, bytes, view, offset, size) {
            this.programParameterARB(view, offset, size, false);
        });
        define("PROGRAM_PARAMETER_DV_ARB", function(a, bytes, view, offset, size) {
            this.programParameterARB(view, offset, size, true);
        });
        define("QUERY_PROGRAM_IV_ARB", function(a, bytes, view, offset, size) {
            if (size < 16) throw new GLStreamError("ARB query record is short");
            const target = view.getUint32(offset, true);
            const pname = view.getUint32(offset + 4, true);
            const value = this.queryProgramivARB(target, pname);
            view.setUint32(offset + 8, value === null ?
                SYNC_STATUS_FAILED : SYNC_STATUS_OK, true);
            if (value !== null) view.setUint32(offset + 12, value >>> 0, true);
        });
        define("QUERY_PROGRAM_PARAMETER_FV_ARB", function(a, bytes, view, offset, size) {
            this.queryProgramParameterARB(view, offset, size, false);
        });
        define("QUERY_PROGRAM_PARAMETER_DV_ARB", function(a, bytes, view, offset, size) {
            this.queryProgramParameterARB(view, offset, size, true);
        });
        /*
         * {target, pname, status, length, data_size, reserved} then the
         * program text at 24. glGetProgramStringARB has no buffer size of its
         * own -- the caller is expected to have asked GL_PROGRAM_LENGTH_ARB
         * first -- so data_size is what the guest allocated and the text is
         * written without a terminator, exactly as the extension specifies.
         */
        define("QUERY_PROGRAM_STRING_ARB", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("ARB string record is short");
            const target = view.getUint32(offset, true);
            const capacity = view.getUint32(offset + 16, true);
            const program = this.arbProgramFor(target);
            if (!program || 24 + capacity > size) {
                view.setUint32(offset + 8, SYNC_STATUS_FAILED, true);
                return;
            }
            const text = program.source;
            const written = Math.min(text.length, capacity);
            view.setUint32(offset + 8, SYNC_STATUS_OK, true);
            view.setUint32(offset + 12, written, true);
            for (let i = 0; i < written; ++i)
                bytes[offset + 24 + i] = text.charCodeAt(i) & 0xff;
        });
    }

    /* ================================================================== */
    /* Draw records                                                       */
    /* ================================================================== */

    /*
     * A client-array block is {enabled, size, type, stride, dataSize} followed
     * by dataSize bytes; a draw record carries thirteen of them in a fixed
     * order -- vertex, colour, normal, eight texture coordinates, secondary
     * colour, fog coordinate -- because the guest packs every enabled array
     * into the same record rather than tracking pointers across calls.
     */
    const ARRAY_BLOCK_NAMES = ["vertex", "color", "normal",
        "texCoord0", "texCoord1", "texCoord2", "texCoord3",
        "texCoord4", "texCoord5", "texCoord6", "texCoord7",
        "secondaryColor", "fogCoord"];

    function parseArrayBlocks(bytes, view, offset, end, count) {
        const blocks = [];
        let at = offset;
        for (let i = 0; i < count; ++i) {
            if (at + 20 > end) return null;
            const enabled = view.getUint32(at, true) !== 0;
            const size = view.getInt32(at + 4, true);
            const type = view.getUint32(at + 8, true);
            const stride = view.getInt32(at + 12, true);
            const dataSize = view.getUint32(at + 16, true);
            at += 20;
            if (at + dataSize > end) return null;
            blocks.push({
                enabled, size: enabled ? size : 0, type: enabled ? type : 0,
                stride: enabled ? stride : 0,
                data: enabled && dataSize ?
                    bytes.subarray(at, at + dataSize) : null,
            });
            at += dataSize;
        }
        return { blocks, offset: at };
    }

    function parseGenericBlocks(bytes, view, offset, end, count) {
        const blocks = [];
        let at = offset;
        for (let i = 0; i < count; ++i) {
            if (at + 28 > end) return null;
            const index = view.getUint32(at, true);
            const normalized = view.getUint32(at + 4, true) !== 0;
            const enabled = view.getUint32(at + 8, true) !== 0;
            const size = view.getInt32(at + 12, true);
            const type = view.getUint32(at + 16, true);
            const stride = view.getInt32(at + 20, true);
            const dataSize = view.getUint32(at + 24, true);
            at += 28;
            if (at + dataSize > end) return null;
            blocks.push({
                index, normalized, enabled, size, type, stride,
                data: enabled && dataSize ?
                    bytes.subarray(at, at + dataSize) : null,
            });
            at += dataSize;
        }
        return { blocks, offset: at };
    }

    function installDrawHandlers(table) {
        const define = definer(table);

        const decodePackedDraw = (indexed, gl2) => function(a, bytes, view, offset, size) {
            const end = offset + size;
            let at = offset;
            const mode = view.getUint32(at, true); at += 4;
            const count = view.getInt32(at, true); at += 4;
            let indexType = 0;
            let indexDataSize = 0;
            if (indexed) {
                indexType = view.getUint32(at, true); at += 4;
                indexDataSize = view.getUint32(at, true); at += 4;
            }
            let blocksAt;
            let texUnitCount = 0;
            let hasSecondary = false;
            let hasFog = false;
            let genericCount = 0;
            let arrayCount;
            /*
             * Where the index data starts depends on the layout, which is why
             * it cannot be sliced while reading the fixed header. In the
             * multitexture layout the guest writes its own header -- magic,
             * the encoded array set, the client-active unit, and for the GL2
             * opcodes a generic-attribute count -- *between* the fixed header
             * and the indices. Slicing at the end of the fixed header instead
             * read the magic word as the first two indices: every
             * glDrawElements drew the wrong triangles, and did it quietly,
             * because the block offset below was computed correctly and
             * nothing downstream range-checks an index.
             */
            const magicAt = indexed ? offset + 16 : offset + 8;
            const magic = magicAt + 4 <= end ? view.getUint32(magicAt, true) : 0;
            let indexAt;
            if (magic === CLIENT_ARRAY_MT_MAGIC) {
                const encoded = view.getUint32(magicAt + 4, true);
                hasSecondary = (encoded & CLIENT_ARRAY_MT_SECONDARY_COLOR_BIT) !== 0;
                hasFog = (encoded & CLIENT_ARRAY_MT_FOG_COORD_BIT) !== 0;
                texUnitCount = encoded &
                    ~(CLIENT_ARRAY_MT_SECONDARY_COLOR_BIT | CLIENT_ARRAY_MT_FOG_COORD_BIT);
                if (texUnitCount > MAX_TEXTURE_COORDS)
                    throw new GLStreamError("too many texture-coordinate arrays");
                let headerEnd = magicAt + 12;      // magic, count, clientActive
                if (gl2) {
                    genericCount = view.getUint32(headerEnd, true);
                    headerEnd += 4;
                }
                indexAt = headerEnd;
                arrayCount = 3 + texUnitCount + (hasSecondary ? 1 : 0) +
                    (hasFog ? 1 : 0);
            } else {
                // The pre-multitexture layout: four blocks in vertex, colour,
                // texcoord, normal order, with the indices straight after the
                // fixed header. No shipping guest emits it any more, but the
                // state journal may still hold one.
                indexAt = offset + 16;
                arrayCount = 4;
            }

            let indexData = null;
            if (indexed) {
                if (indexAt + indexDataSize > end)
                    throw new GLStreamError("index data is truncated");
                indexData = indexDataSize ?
                    bytes.subarray(indexAt, indexAt + indexDataSize) : null;
            }
            blocksAt = indexed ? indexAt + indexDataSize :
                (magic === CLIENT_ARRAY_MT_MAGIC ? indexAt : offset + 8);

            const parsed = parseArrayBlocks(bytes, view, blocksAt, end, arrayCount);
            if (!parsed) throw new GLStreamError("client array blocks are truncated");
            let generic = null;
            if (genericCount) {
                generic = parseGenericBlocks(bytes, view, parsed.offset, end,
                    genericCount);
                if (!generic) throw new GLStreamError("generic attribute blocks are truncated");
            }

            const arrays = Object.create(null);
            if (magic === CLIENT_ARRAY_MT_MAGIC) {
                const order = ["vertex", "color", "normal"];
                for (let i = 0; i < texUnitCount; ++i) order.push("texCoord" + i);
                if (hasSecondary) order.push("secondaryColor");
                if (hasFog) order.push("fogCoord");
                order.forEach((name, i) => {
                    if (parsed.blocks[i] && parsed.blocks[i].enabled)
                        arrays[name] = parsed.blocks[i];
                });
            } else {
                ["vertex", "color", "texCoord0", "normal"].forEach((name, i) => {
                    if (parsed.blocks[i] && parsed.blocks[i].enabled)
                        arrays[name] = parsed.blocks[i];
                });
            }
            if (generic) {
                for (const block of generic.blocks)
                    if (block.enabled) arrays["generic" + block.index] = block;
            }

            this.drawPacked(mode, count, arrays, indexed ? {
                type: indexType, data: indexData,
            } : null);
        };

        define("DRAW_ARRAYS", decodePackedDraw(false, false));
        define("DRAW_ARRAYS_GL2", decodePackedDraw(false, true));
        define("DRAW_ELEMENTS", decodePackedDraw(true, false));
        define("DRAW_ELEMENTS_GL2", decodePackedDraw(true, true));

        /* The VBO-direct path: every enabled array lives in a buffer object,
         * so nothing but the parameters travels. This is the path M2's VBO
         * promotion makes the common one. */
        define("DRAW_ARRAYS_DIRECT", function(a) {
            this.drawFromBuffers(a[0] >>> 0, a[1] | 0, a[2] | 0, null);
        });
        define("DRAW_ELEMENTS_DIRECT", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("direct draw record is short");
            this.drawFromBuffers(view.getUint32(offset, true), 0,
                view.getInt32(offset + 12, true), {
                    type: view.getUint32(offset + 16, true),
                    bufferOffset: view.getUint32(offset + 20, true),
                });
        });
        define("DRAW_RANGE_ELEMENTS_DIRECT", function(a, bytes, view, offset, size) {
            if (size < 24) throw new GLStreamError("direct draw record is short");
            this.drawFromBuffers(view.getUint32(offset, true), 0,
                view.getInt32(offset + 12, true), {
                    type: view.getUint32(offset + 16, true),
                    bufferOffset: view.getUint32(offset + 20, true),
                });
        });
        define("MULTI_DRAW_ARRAYS_DIRECT", function(a, bytes, view, offset, size) {
            if (size < 8) throw new GLStreamError("multi-draw record is short");
            const mode = view.getUint32(offset, true);
            const primcount = view.getUint32(offset + 4, true);
            for (let i = 0; i < primcount; ++i) {
                const at = offset + 8 + i * 8;
                if (at + 8 > offset + size) break;
                this.drawFromBuffers(mode, view.getInt32(at, true),
                    view.getInt32(at + 4, true), null);
            }
        });
        define("MULTI_DRAW_ELEMENTS_DIRECT", function(a, bytes, view, offset, size) {
            if (size < 12) throw new GLStreamError("multi-draw record is short");
            const mode = view.getUint32(offset, true);
            const type = view.getUint32(offset + 4, true);
            const primcount = view.getUint32(offset + 8, true);
            for (let i = 0; i < primcount; ++i) {
                const at = offset + 12 + i * 8;
                if (at + 8 > offset + size) break;
                this.drawFromBuffers(mode, 0, view.getInt32(at, true), {
                    type, bufferOffset: view.getUint32(at + 4, true),
                });
            }
        });

        /* ---- pixel rectangles ---- */

        define("READ_PIXELS", function(a, bytes, view, offset, size, metadata) {
            this.readPixels(bytes, view, offset, size, metadata);
        });
        define("DRAW_PIXELS", function(a, bytes, view, offset, size) {
            this.drawPixels(bytes, view, offset, size);
        });
        define("BITMAP", function(a, bytes, view, offset, size) {
            this.drawBitmap(bytes, view, offset, size);
        });
        define("COPY_PIXELS", function(a) {
            this.copyPixels(a[0] | 0, a[1] | 0, a[2] | 0, a[3] | 0, a[4] >>> 0);
        });
        define("POLYGON_STIPPLE", function(a, bytes, view, offset, size) {
            if (size < 128) throw new GLStreamError("polygon stipple is short");
            this.current.polygonStipple.set(
                bytes.subarray(offset, offset + 128));
            this.polygonStippleTexture = null;
        });
        const pixelMap = () => function(a, bytes, view, offset, size) {
            // Pixel maps only affect glDrawPixels/glReadPixels colour transfer,
            // which the executor applies on the CPU; the table is stored so the
            // path stays exact when GL_MAP_COLOR is on.
            if (size < 8) throw new GLStreamError("pixel map record is short");
            const map = view.getUint32(offset, true);
            const count = view.getUint32(offset + 4, true);
            const values = new Float32Array(count);
            for (let i = 0; i < count && 8 + i * 4 + 4 <= size; ++i)
                values[i] = view.getFloat32(offset + 8 + i * 4, true);
            this.pixelMaps = this.pixelMaps || Object.create(null);
            this.pixelMaps[map] = values;
        };
        define("PIXEL_MAPFV", pixelMap());
        define("PIXEL_MAPUIV", pixelMap());
        define("PIXEL_MAPUSV", pixelMap());
        define("ACCUM", function(a) { this.accum(a[0] >>> 0, a[1]); });

        define("QUERY_OBJECT_BATCH", function(a, bytes, view, offset, size, metadata) {
            this.queryObjectBatch(bytes, view, offset, size, metadata);
        });
    }

    /* ================================================================== */
    /* Executor: state                                                    */
    /* ================================================================== */

    Object.assign(GLWebGPUExecutor.prototype, {

        topOf(mode) {
            const s = this.current;
            if (mode === GL.TEXTURE)
                return s.textureStacks[s.activeTexture][
                    s.textureStacks[s.activeTexture].length - 1];
            const stack = s.stacks[mode] || s.stacks[GL.MODELVIEW];
            return stack[stack.length - 1];
        },

        topMatrix() { return this.topOf(this.current.matrixMode); },

        stackFor(mode) {
            const s = this.current;
            if (mode === GL.TEXTURE) return s.textureStacks[s.activeTexture];
            return s.stacks[mode] || s.stacks[GL.MODELVIEW];
        },

        pushMatrix() {
            const stack = this.stackFor(this.current.matrixMode);
            const depth = this.current.matrixMode === GL.MODELVIEW ?
                MODELVIEW_STACK_DEPTH : OTHER_STACK_DEPTH;
            if (stack.length >= depth)
                return this.refuse("glPushMatrix", "matrix stack overflow",
                    { mode: this.current.matrixMode }, GL.STACK_OVERFLOW);
            stack.push(new Float32Array(stack[stack.length - 1]));
        },

        popMatrix() {
            const stack = this.stackFor(this.current.matrixMode);
            if (stack.length <= 1)
                return this.refuse("glPopMatrix", "matrix stack underflow",
                    { mode: this.current.matrixMode }, GL.STACK_UNDERFLOW);
            stack.pop();
            this.matrixChanged();
        },

        multiplyTop(m) {
            const top = this.topMatrix();
            multiply4(top, m, SCRATCH_B);
            top.set(SCRATCH_B);
            this.matrixChanged();
        },

        /* The eye-space copies of every light are captured when glLight* is
         * called, per the GL spec, so a later modelview change must not move
         * them -- but a modelview change *does* change eye-space geometry, so
         * the derived state is rebuilt lazily rather than here. */
        matrixChanged() {
            this.derivedDirty = true;
        },

        setCapability(cap, value) {
            const s = this.current;
            const unit = s.textureUnits[s.activeTexture];
            switch (cap) {
            case GL.TEXTURE_1D: case GL.TEXTURE_2D:
            case GL.TEXTURE_3D: case GL.TEXTURE_CUBE_MAP:
                if (value) unit.enabledTargets.add(cap);
                else unit.enabledTargets.delete(cap);
                return;
            case GL.TEXTURE_GEN_S: case GL.TEXTURE_GEN_T:
            case GL.TEXTURE_GEN_R: case GL.TEXTURE_GEN_Q:
                unit.texGen[cap - GL.TEXTURE_GEN_S].enabled = value;
                return;
            case GL.POINT_SPRITE:
                unit.env.pointSprite = value;
                if (value) s.enabled.add(cap); else s.enabled.delete(cap);
                return;
            default: break;
            }
            if (cap >= GL.LIGHT0 && cap < GL.LIGHT0 + MAX_LIGHTS) {
                s.lights[cap - GL.LIGHT0].enabled = value;
                return;
            }
            if (cap >= GL.CLIP_PLANE0 && cap < GL.CLIP_PLANE0 + MAX_CLIP_PLANES) {
                if (value) s.enabled.add(cap); else s.enabled.delete(cap);
                return;
            }
            if (cap === GL.COLOR_MATERIAL) s.colorMaterial.enabled = value;
            if (value) s.enabled.add(cap); else s.enabled.delete(cap);
        },

        isEnabled(cap) { return this.current.enabled.has(cap); },

        setLightModel(pname, values, count) {
            const model = this.current.lightModel;
            switch (pname) {
            case GL.LIGHT_MODEL_AMBIENT:
                model.ambient.set(values.slice(0, 4));
                return;
            case GL.LIGHT_MODEL_TWO_SIDE: model.twoSide = values[0] !== 0; return;
            case GL.LIGHT_MODEL_LOCAL_VIEWER: model.localViewer = values[0] !== 0; return;
            case GL.LIGHT_MODEL_COLOR_CONTROL: model.colorControl = values[0] >>> 0; return;
            default:
                this.refuse("glLightModel", "unknown parameter",
                    { pname, count }, GL.INVALID_ENUM);
            }
        },

        setLight(lightEnum, pname, values) {
            const index = lightEnum - GL.LIGHT0;
            if (index < 0 || index >= MAX_LIGHTS)
                return this.refuse("glLight", "light index out of range",
                    { index }, GL.INVALID_ENUM);
            const light = this.current.lights[index];
            switch (pname) {
            case GL.AMBIENT: light.ambient.set(values.slice(0, 4)); return;
            case GL.DIFFUSE: light.diffuse.set(values.slice(0, 4)); return;
            case GL.SPECULAR: light.specular.set(values.slice(0, 4)); return;
            case GL.POSITION: {
                light.position.set(values.slice(0, 4));
                // GL transforms the position by the modelview in force *now*.
                transformPoint4(this.topOf(GL.MODELVIEW), light.position,
                    light.eyePosition);
                this.derivedDirty = true;
                return;
            }
            case GL.SPOT_DIRECTION: {
                light.spotDirection.set(values.slice(0, 3));
                const dir = new Float32Array([values[0], values[1], values[2], 0]);
                const eye = transformPoint4(this.topOf(GL.MODELVIEW), dir,
                    new Float32Array(4));
                light.eyeSpotDirection.set([eye[0], eye[1], eye[2]]);
                this.derivedDirty = true;
                return;
            }
            case GL.SPOT_EXPONENT: light.spotExponent = clamp(values[0], 0, 128); return;
            case GL.SPOT_CUTOFF: light.spotCutoff = values[0]; return;
            case GL.CONSTANT_ATTENUATION: light.constantAttenuation = values[0]; return;
            case GL.LINEAR_ATTENUATION: light.linearAttenuation = values[0]; return;
            case GL.QUADRATIC_ATTENUATION: light.quadraticAttenuation = values[0]; return;
            default:
                this.refuse("glLight", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setMaterial(face, pname, values) {
            const targets = [];
            if (face === GL.FRONT || face === GL.FRONT_AND_BACK)
                targets.push(this.current.material.front);
            if (face === GL.BACK || face === GL.FRONT_AND_BACK)
                targets.push(this.current.material.back);
            if (!targets.length)
                return this.refuse("glMaterial", "invalid face", { face },
                    GL.INVALID_ENUM);
            for (const material of targets) {
                switch (pname) {
                case GL.AMBIENT: material.ambient.set(values.slice(0, 4)); break;
                case GL.DIFFUSE: material.diffuse.set(values.slice(0, 4)); break;
                case GL.SPECULAR: material.specular.set(values.slice(0, 4)); break;
                case GL.EMISSION: material.emission.set(values.slice(0, 4)); break;
                case GL.SHININESS: material.shininess = clamp(values[0], 0, 128); break;
                case GL.AMBIENT_AND_DIFFUSE:
                    material.ambient.set(values.slice(0, 4));
                    material.diffuse.set(values.slice(0, 4));
                    break;
                default:
                    this.refuse("glMaterial", "unknown parameter", { pname },
                        GL.INVALID_ENUM);
                    return;
                }
            }
            this.derivedDirty = true;
        },

        setFog(pname, values) {
            const fog = this.current.fog;
            switch (pname) {
            case GL.FOG_MODE: fog.mode = values[0] >>> 0; return;
            case GL.FOG_DENSITY: fog.density = values[0]; return;
            case GL.FOG_START: fog.start = values[0]; return;
            case GL.FOG_END: fog.end = values[0]; return;
            case GL.FOG_COLOR: fog.color.set(values.slice(0, 4)); return;
            case GL.FOG_COORD_SRC: fog.coordSource = values[0] >>> 0; return;
            case GL.FOG_INDEX: return;
            default:
                this.refuse("glFog", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setTexEnv(target, pname, values) {
            const s = this.current;
            const unit = s.textureUnits[s.activeTexture];
            if (target === GL.POINT_SPRITE) {
                if (pname === GL.COORD_REPLACE) unit.env.pointSprite = values[0] !== 0;
                return;
            }
            if (target === GL.TEXTURE_FILTER_CONTROL) {
                if (pname === GL.TEXTURE_LOD_BIAS) unit.lodBias = values[0];
                return;
            }
            const env = unit.env;
            switch (pname) {
            case GL.TEXTURE_ENV_MODE: env.mode = values[0] >>> 0; return;
            case GL.TEXTURE_ENV_COLOR: env.color.set(values.slice(0, 4)); return;
            case GL.COMBINE_RGB: env.combineRGB = values[0] >>> 0; return;
            case GL.COMBINE_ALPHA: env.combineAlpha = values[0] >>> 0; return;
            case GL.SRC0_RGB: env.srcRGB[0] = values[0] >>> 0; return;
            case GL.SRC1_RGB: env.srcRGB[1] = values[0] >>> 0; return;
            case GL.SRC2_RGB: env.srcRGB[2] = values[0] >>> 0; return;
            case GL.SRC0_ALPHA: env.srcAlpha[0] = values[0] >>> 0; return;
            case GL.SRC1_ALPHA: env.srcAlpha[1] = values[0] >>> 0; return;
            case GL.SRC2_ALPHA: env.srcAlpha[2] = values[0] >>> 0; return;
            case GL.OPERAND0_RGB: env.operandRGB[0] = values[0] >>> 0; return;
            case GL.OPERAND1_RGB: env.operandRGB[1] = values[0] >>> 0; return;
            case GL.OPERAND2_RGB: env.operandRGB[2] = values[0] >>> 0; return;
            case GL.OPERAND0_ALPHA: env.operandAlpha[0] = values[0] >>> 0; return;
            case GL.OPERAND1_ALPHA: env.operandAlpha[1] = values[0] >>> 0; return;
            case GL.OPERAND2_ALPHA: env.operandAlpha[2] = values[0] >>> 0; return;
            case GL.RGB_SCALE: env.rgbScale = clamp(Math.round(values[0]), 1, 4); return;
            case GL.ALPHA_SCALE: env.alphaScale = clamp(Math.round(values[0]), 1, 4); return;
            default:
                this.refuse("glTexEnv", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setTexGen(coord, pname, values) {
            const s = this.current;
            const unit = s.textureUnits[s.activeTexture];
            const index = coord - GL.S;
            if (index < 0 || index > 3)
                return this.refuse("glTexGen", "invalid coordinate", { coord },
                    GL.INVALID_ENUM);
            const gen = unit.texGen[index];
            switch (pname) {
            case GL.TEXTURE_GEN_MODE: gen.mode = values[0] >>> 0; return;
            case GL.OBJECT_PLANE: gen.objectPlane.set(values.slice(0, 4)); return;
            case GL.EYE_PLANE: {
                // Like glClipPlane, the eye plane is stored transformed by the
                // inverse modelview so the shader can dot it with the eye-space
                // position directly.
                const inv = invert4(this.topOf(GL.MODELVIEW), SCRATCH_B);
                const t = transpose4(inv, SCRATCH_C);
                transformPoint4(t, new Float32Array(values.slice(0, 4)),
                    gen.eyePlane);
                return;
            }
            default:
                this.refuse("glTexGen", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setTexParameter(target, pname, values) {
            const texture = this.boundTexture(target);
            if (!texture)
                return this.refuse("glTexParameter", "no texture bound",
                    { target }, GL.INVALID_OPERATION);
            const sampler = texture.sampler;
            switch (pname) {
            case GL.TEXTURE_MIN_FILTER: sampler.minFilter = values[0] >>> 0; break;
            case GL.TEXTURE_MAG_FILTER: sampler.magFilter = values[0] >>> 0; break;
            case GL.TEXTURE_WRAP_S: sampler.wrapS = values[0] >>> 0; break;
            case GL.TEXTURE_WRAP_T: sampler.wrapT = values[0] >>> 0; break;
            case GL.TEXTURE_WRAP_R: sampler.wrapR = values[0] >>> 0; break;
            case GL.TEXTURE_MIN_LOD: sampler.minLod = values[0]; break;
            case GL.TEXTURE_MAX_LOD: sampler.maxLod = values[0]; break;
            case GL.TEXTURE_BASE_LEVEL: sampler.baseLevel = values[0] | 0; break;
            case GL.TEXTURE_MAX_LEVEL: sampler.maxLevel = values[0] | 0; break;
            case GL.TEXTURE_LOD_BIAS: sampler.lodBias = values[0]; break;
            case GL.TEXTURE_BORDER_COLOR:
                sampler.borderColor.set(values.slice(0, 4));
                break;
            case GL.TEXTURE_MAX_ANISOTROPY_EXT:
                sampler.maxAnisotropy = clamp(Math.round(values[0]), 1, 16);
                break;
            case GL.TEXTURE_COMPARE_MODE: sampler.compareMode = values[0] >>> 0; break;
            case GL.TEXTURE_COMPARE_FUNC: sampler.compareFunc = values[0] >>> 0; break;
            case GL.DEPTH_TEXTURE_MODE: sampler.depthTextureMode = values[0] >>> 0; break;
            case GL.GENERATE_MIPMAP: texture.generateMipmapHint = values[0] !== 0; break;
            case GL.TEXTURE_PRIORITY: break;
            default:
                return this.refuse("glTexParameter", "unknown parameter",
                    { pname }, GL.INVALID_ENUM);
            }
            texture.viewCache.clear();
            this.invalidateBindGroups();
        },

        setPixelStore(pname, value) {
            const store = this.current.pixelStore;
            switch (pname) {
            case GL.UNPACK_ALIGNMENT: store.unpackAlignment = value; return;
            case GL.UNPACK_ROW_LENGTH: store.unpackRowLength = value; return;
            case GL.UNPACK_SKIP_PIXELS: store.unpackSkipPixels = value; return;
            case GL.UNPACK_SKIP_ROWS: store.unpackSkipRows = value; return;
            case GL.UNPACK_SKIP_IMAGES: store.unpackSkipImages = value; return;
            case GL.UNPACK_IMAGE_HEIGHT: store.unpackImageHeight = value; return;
            case GL.UNPACK_SWAP_BYTES: store.unpackSwapBytes = value !== 0; return;
            case GL.UNPACK_LSB_FIRST: store.unpackLsbFirst = value !== 0; return;
            case GL.PACK_ALIGNMENT: store.packAlignment = value; return;
            case GL.PACK_ROW_LENGTH: store.packRowLength = value; return;
            case GL.PACK_SKIP_PIXELS: store.packSkipPixels = value; return;
            case GL.PACK_SKIP_ROWS: store.packSkipRows = value; return;
            case GL.PACK_SWAP_BYTES: store.packSwapBytes = value !== 0; return;
            case GL.PACK_LSB_FIRST: store.packLsbFirst = value !== 0; return;
            default:
                this.refuse("glPixelStorei", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setPixelTransfer(pname, value) {
            const t = this.current.pixelTransfer;
            switch (pname) {
            case GL.RED_SCALE: t.redScale = value; return;
            case GL.GREEN_SCALE: t.greenScale = value; return;
            case GL.BLUE_SCALE: t.blueScale = value; return;
            case GL.ALPHA_SCALE: t.alphaScale = value; return;
            case GL.RED_BIAS: t.redBias = value; return;
            case GL.GREEN_BIAS: t.greenBias = value; return;
            case GL.BLUE_BIAS: t.blueBias = value; return;
            case GL.ALPHA_BIAS: t.alphaBias = value; return;
            case GL.MAP_COLOR: t.mapColor = value !== 0; return;
            case GL.POST_COLOR_MATRIX_RED_SCALE_SGI:
            case GL.POST_COLOR_MATRIX_GREEN_SCALE_SGI:
            case GL.POST_COLOR_MATRIX_BLUE_SCALE_SGI:
            case GL.POST_COLOR_MATRIX_ALPHA_SCALE_SGI:
                t.postColorMatrixScale[pname -
                    GL.POST_COLOR_MATRIX_RED_SCALE_SGI] = value;
                return;
            case GL.POST_COLOR_MATRIX_RED_BIAS_SGI:
            case GL.POST_COLOR_MATRIX_GREEN_BIAS_SGI:
            case GL.POST_COLOR_MATRIX_BLUE_BIAS_SGI:
            case GL.POST_COLOR_MATRIX_ALPHA_BIAS_SGI:
                t.postColorMatrixBias[pname -
                    GL.POST_COLOR_MATRIX_RED_BIAS_SGI] = value;
                break;
            default:     // depth/stencil scales have no effect here
            }
        },

        setPointParameter(pname, values) {
            const point = this.current.point;
            switch (pname) {
            case GL.POINT_SIZE_MIN: point.sizeMin = values[0]; return;
            case GL.POINT_SIZE_MAX: point.sizeMax = values[0]; return;
            case GL.POINT_FADE_THRESHOLD_SIZE: point.fadeThreshold = values[0]; return;
            case GL.POINT_DISTANCE_ATTENUATION:
                point.attenuation.set([values[0], values[1] || 0, values[2] || 0]);
                return;
            case GL.POINT_SPRITE_COORD_ORIGIN:
                point.spriteCoordOrigin = values[0] >>> 0;
                return;
            default:
                this.refuse("glPointParameter", "unknown parameter", { pname },
                    GL.INVALID_ENUM);
            }
        },

        setClientState(cap, value) {
            const s = this.current;
            const name = {
                [GL.VERTEX_ARRAY]: "vertex",
                [GL.COLOR_ARRAY]: "color",
                [GL.NORMAL_ARRAY]: "normal",
                [GL.SECONDARY_COLOR_ARRAY]: "secondaryColor",
                [GL.FOG_COORD_ARRAY]: "fogCoord",
                [GL.EDGE_FLAG_ARRAY]: "edgeFlag",
                [GL.INDEX_ARRAY]: "index",
            }[cap];
            if (name) {
                this.arrayState(name).enabled = value;
                return;
            }
            if (cap === GL.TEXTURE_COORD_ARRAY) {
                this.arrayState("texCoord" + s.clientActiveTexture).enabled = value;
                return;
            }
            this.refuse("glEnableClientState", "unknown array", { cap },
                GL.INVALID_ENUM);
        },

        arrayState(name) {
            const s = this.current;
            s.arrays = s.arrays || Object.create(null);
            if (!s.arrays[name])
                s.arrays[name] = { enabled: false, buffer: 0, size: 4,
                                   type: GL.FLOAT, stride: 0, offset: 0,
                                   normalized: false, fromVBO: false };
            return s.arrays[name];
        },

        setArrayPointer(name, array) {
            Object.assign(this.arrayState(name), array);
        },

        boundTexture(target) {
            const s = this.current;
            const unit = s.textureUnits[s.activeTexture];
            let key = target;
            // A cube face parameter names the cube map itself.
            if (target >= GL.TEXTURE_CUBE_MAP_POSITIVE_X &&
                    target <= GL.TEXTURE_CUBE_MAP_NEGATIVE_Z)
                key = GL.TEXTURE_CUBE_MAP;
            const name = unit.bindings[key];
            if (!name) return null;
            return s.shareGroup.textures.get(name) || null;
        },

        invalidateBindGroups() {
            this.bindGroupsDirty = true;
        },

        retire(object) {
            if (object && typeof object.destroy === "function") {
                // Destroying inside a recorded frame would invalidate commands
                // already encoded, so the object is released after the frame
                // that may still reference it.
                this.retired = this.retired || [];
                this.retired.push(object);
            }
        },

        releaseRetired() {
            if (!this.retired || !this.retired.length) return;
            for (const object of this.retired) {
                try { object.destroy(); } catch (error) { /* already gone */ }
            }
            this.retired.length = 0;
        },
    });

    /* ================================================================== */
    /* Executor: textures                                                 */
    /* ================================================================== */

    const CUBE_FACE_INDEX = {};
    for (let i = 0; i < 6; ++i)
        CUBE_FACE_INDEX[GL.TEXTURE_CUBE_MAP_POSITIVE_X + i] = i;

    Object.assign(GLWebGPUExecutor.prototype, {

        textureTargetKind(target) {
            if (target === GL.TEXTURE_1D) return "1D";
            if (target === GL.TEXTURE_3D) return "3D";
            if (CUBE_FACE_INDEX[target] !== undefined ||
                    target === GL.TEXTURE_CUBE_MAP) return "Cube";
            return "2D";
        },

        /*
         * Levels are stored on the CPU and the GPU texture is (re)built lazily.
         *
         * GL lets an application define level 3 before level 0 and change a
         * level's size after the fact, neither of which a GPUTexture allows:
         * its size and mip count are fixed at creation. Keeping the authored
         * levels means the texture can be rebuilt whenever the shape changes,
         * which is also what makes device loss recoverable without the guest
         * noticing.
         */
        texImage(target, level, internalFormat, width, height, depth,
                format, type, data) {
            const texture = this.boundTexture(target);
            if (!texture)
                return this.refuse("glTexImage", "no texture bound", { target },
                    GL.INVALID_OPERATION);
            const kind = this.textureTargetKind(target);
            texture.target = kind === "Cube" ? GL.TEXTURE_CUBE_MAP : target;
            let storage = storageFormatFor(internalFormat, this.deviceFeatures);
            if (storage.compressed) {
                // glTexImage* receives ordinary pixels even when the requested
                // internal format is a specific S3TC format; desktop GL then
                // performs the compression.  queue.writeTexture cannot encode
                // RGBA bytes into BC blocks, and these levels are often later
                // filled by CopyTexSubImage while Cube 2 builds environment
                // maps.  Keep the logical base format but use renderable RGBA8
                // storage.  glCompressedTexImage* below still preserves native
                // BC blocks when the application actually supplies them.
                storage = { gpu: "rgba8unorm", compressed: false,
                    base: storage.base };
            }
            const face = CUBE_FACE_INDEX[target] || 0;

            let pixels = null;
            let pixelLayout = {
                bytesPerTexel: storage.palettised ? 1 :
                    (storage.gpu === "rgba16float" ? 8 :
                        (storage.gpu === "rgba32float" ? 16 :
                            (storage.gpu === "depth16unorm" ? 2 : 4))),
                componentType: storage.gpu === "rgba16float" ? "f16" :
                    (storage.gpu === "depth16unorm" ? "u16" :
                        (storage.gpu === "rgba32float" || storage.depth ? "f32" : "u8")),
                componentCount: storage.palettised || storage.depth ? 1 : 4,
            };
            if (data && data.byteLength) {
                const converted = convertPixelsForStorage(data, 0, width, height,
                    depth, format, type, storage, {
                        rowLength: this.current.pixelStore.unpackRowLength,
                        skipPixels: this.current.pixelStore.unpackSkipPixels,
                        skipRows: this.current.pixelStore.unpackSkipRows,
                        skipImages: this.current.pixelStore.unpackSkipImages,
                        imageHeight: this.current.pixelStore.unpackImageHeight,
                        alignment: this.current.pixelStore.unpackAlignment,
                    });
                if (!converted)
                    return this.refuse("glTexImage", "unsupported pixel format",
                        { format, type, internalFormat }, GL.INVALID_ENUM);
                pixels = converted.pixels;
                pixelLayout = converted;
            }

            this.storeLevel(texture, kind, level, face, {
                width, height, depth,
                gpuFormat: storage.gpu, base: storage.base,
                compressed: false, pixels,
                bytesPerTexel: pixelLayout.bytesPerTexel,
                componentType: pixelLayout.componentType,
                componentCount: pixelLayout.componentCount,
            });
            ++this.stats.textureUploads;
            if (pixels) this.stats.textureBytes += pixels.byteLength;
            if (texture.generateMipmapHint && level === 0)
                this.generateMipmapFor(texture);
        },

        texSubImage(target, level, x, y, z, width, height, depth, format, type,
                data) {
            const texture = this.boundTexture(target);
            if (!texture)
                return this.refuse("glTexSubImage", "no texture bound", { target },
                    GL.INVALID_OPERATION);
            const kind = this.textureTargetKind(target);
            const face = CUBE_FACE_INDEX[target] || 0;
            const slot = this.levelSlot(texture, kind, level, face);
            if (!slot || !slot.pixels)
                return this.refuse("glTexSubImage", "level has no storage",
                    { level, face }, GL.INVALID_OPERATION);
            if (slot.compressed)
                return this.refuse("glTexSubImage",
                    "uncompressed update of a compressed level", { level },
                    GL.INVALID_OPERATION);
            const storage = { gpu: slot.gpuFormat, base: slot.base,
                float: slot.componentType === "f16" ||
                    (slot.componentType === "f32" && slot.componentCount === 4),
                depth: slot.base === "DEPTH",
                palettised: slot.base === "COLOR_INDEX" };
            const converted = convertPixelsForStorage(data, 0, width, height,
                depth, format, type, storage, {
                    rowLength: this.current.pixelStore.unpackRowLength,
                    skipPixels: this.current.pixelStore.unpackSkipPixels,
                    skipRows: this.current.pixelStore.unpackSkipRows,
                    skipImages: this.current.pixelStore.unpackSkipImages,
                    imageHeight: this.current.pixelStore.unpackImageHeight,
                    alignment: this.current.pixelStore.unpackAlignment,
                });
            if (!converted)
                return this.refuse("glTexSubImage", "unsupported pixel format",
                    { format, type }, GL.INVALID_ENUM);
            // Patch the shadow copy; the GPU upload happens with the rest of
            // the level so a run of subimage calls costs one writeTexture.
            for (let sz = 0; sz < depth; ++sz) {
                for (let sy = 0; sy < height; ++sy) {
                    const bytesPerTexel = slot.bytesPerTexel || 4;
                    const dstRow = (((z + sz) * slot.height + (y + sy)) *
                        slot.width + x) * bytesPerTexel;
                    const srcRow = ((sz * height + sy) * width) * bytesPerTexel;
                    if (dstRow < 0 ||
                            dstRow + width * bytesPerTexel > slot.pixels.length)
                        continue;
                    slot.pixels.set(
                        converted.pixels.subarray(srcRow,
                            srcRow + width * bytesPerTexel), dstRow);
                }
            }
            texture.dirty = true;
            ++this.stats.textureUploads;
        },

        compressedTexImage(target, level, internalFormat, width, height, depth,
                data) {
            const texture = this.boundTexture(target);
            if (!texture)
                return this.refuse("glCompressedTexImage", "no texture bound",
                    { target }, GL.INVALID_OPERATION);
            const kind = this.textureTargetKind(target);
            texture.target = kind === "Cube" ? GL.TEXTURE_CUBE_MAP : target;
            const storage = storageFormatFor(internalFormat, this.deviceFeatures);
            const face = CUBE_FACE_INDEX[target] || 0;
            if (storage.decodeDXT) {
                // No BC support on this adapter: decode deterministically so
                // the picture is identical and only the memory differs.
                ++this.stats.dxtDecodes;
                const pixels = decodeDXT(storage.decodeDXT, data, width, height);
                this.storeLevel(texture, kind, level, face, {
                    width, height, depth: 1, gpuFormat: "rgba8unorm",
                    base: storage.base, compressed: false, pixels,
                    bytesPerTexel: 4, componentType: "u8", componentCount: 4,
                });
                return;
            }
            this.storeLevel(texture, kind, level, face, {
                width, height, depth,
                gpuFormat: storage.gpu, base: storage.base,
                compressed: true, blockBytes: storage.blockBytes,
                pixels: data.slice(),
            });
        },

        compressedTexSubImage(target, level, x, y, z, width, height, depth,
                format, data) {
            const texture = this.boundTexture(target);
            if (!texture) return;
            const kind = this.textureTargetKind(target);
            const face = CUBE_FACE_INDEX[target] || 0;
            const slot = this.levelSlot(texture, kind, level, face);
            if (!slot)
                return this.refuse("glCompressedTexSubImage", "level has no storage",
                    { level }, GL.INVALID_OPERATION);
            if (!slot.compressed) {
                const storage = storageFormatFor(format, this.deviceFeatures);
                if (!storage.decodeDXT) {
                    return this.refuse("glCompressedTexSubImage",
                        "compressed update of an uncompressed level", { level },
                        GL.INVALID_OPERATION);
                }
                ++this.stats.dxtDecodes;
                const pixels = decodeDXT(storage.decodeDXT, data, width, height);
                for (let sy = 0; sy < height; ++sy) {
                    const dst = ((y + sy) * slot.width + x) * 4;
                    const src = sy * width * 4;
                    if (dst < 0 || dst + width * 4 > slot.pixels.length) continue;
                    slot.pixels.set(pixels.subarray(src, src + width * 4), dst);
                }
                texture.dirty = true;
                return;
            }
            if ((x & 3) || (y & 3))
                return this.refuse("glCompressedTexSubImage",
                    "the rectangle is not block aligned", { x, y },
                    GL.INVALID_OPERATION);
            const blocksPerRow = Math.ceil(slot.width / 4);
            const srcBlocksPerRow = Math.ceil(width / 4);
            const blockBytes = slot.blockBytes;
            for (let by = 0; by < Math.ceil(height / 4); ++by) {
                const dst = (((y >> 2) + by) * blocksPerRow + (x >> 2)) * blockBytes;
                const src = by * srcBlocksPerRow * blockBytes;
                if (dst + srcBlocksPerRow * blockBytes > slot.pixels.length) break;
                slot.pixels.set(
                    data.subarray(src, src + srcBlocksPerRow * blockBytes), dst);
            }
            texture.dirty = true;
        },

        levelSlot(texture, kind, level, face) {
            const layer = kind === "Cube" ? face : 0;
            const list = texture.levels[layer];
            return list ? list[level] : null;
        },

        storeLevel(texture, kind, level, face, slot) {
            const layer = kind === "Cube" ? face : 0;
            if (!texture.levels[layer]) texture.levels[layer] = [];
            texture.levels[layer][level] = slot;
            texture.kind = kind;
            texture.baseFormat = slot.base;
            texture.gpuFormat = slot.gpuFormat;
            texture.dirty = true;
            texture.viewCache.clear();
            this.invalidateBindGroups();
        },

        /*
         * GL's completeness rules: every mip level from base to max must exist
         * with the right halved size and the same format, or the texture
         * samples as opaque black. Games rely on this to disable a texture by
         * simply not uploading its mips, so it is a behaviour and not a
         * validation nicety.
         */
        textureIsComplete(texture) {
            if (!texture || !texture.levels.length) return false;
            const layers = texture.kind === "Cube" ? 6 : 1;
            const base = texture.levels[0] && texture.levels[0][0];
            if (!base) return false;
            const mipmapped = isMipmapFilter(texture.sampler.minFilter);
            const levelCount = mipmapped ?
                fullMipLevelCount(base.width, base.height, base.depth) : 1;
            for (let layer = 0; layer < layers; ++layer) {
                const list = texture.levels[layer];
                if (!list) return false;
                for (let level = 0; level < levelCount; ++level) {
                    const slot = list[level];
                    if (!slot) return false;
                    if (slot.gpuFormat !== base.gpuFormat) return false;
                    if (slot.width !== Math.max(1, base.width >> level) ||
                            slot.height !== Math.max(1, base.height >> level))
                        return false;
                }
                if (texture.kind === "Cube" &&
                        (base.width !== base.height)) return false;
            }
            return true;
        },

        /* Rebuilds the GPUTexture from the authored levels when anything about
         * the shape changed. */
        ensureTextureUploaded(texture) {
            if (!texture) return null;
            const base = texture.levels[0] && texture.levels[0][0];
            if (!base) return null;
            const layers = texture.kind === "Cube" ? 6 : 1;
            const mipmapped = isMipmapFilter(texture.sampler.minFilter);
            const levelCount = mipmapped ?
                Math.min(fullMipLevelCount(base.width, base.height, base.depth),
                    (texture.levels[0] || []).length) : 1;
            const wanted = {
                width: base.width, height: base.height,
                depth: texture.kind === "3D" ? base.depth : 1,
                layers, levelCount: Math.max(1, levelCount),
                format: base.gpuFormat,
            };
            const shapeChanged = !texture.gpuTexture ||
                texture.gpuWidth !== wanted.width ||
                texture.gpuHeight !== wanted.height ||
                texture.gpuDepth !== wanted.depth ||
                texture.gpuLayers !== wanted.layers ||
                texture.gpuLevels !== wanted.levelCount ||
                texture.gpuFormat !== wanted.format;
            if (!shapeChanged && !texture.dirty) return texture.gpuTexture;

            if (shapeChanged) {
                const oldTexture = texture.gpuTexture;
                const oldWidth = texture.gpuWidth || 0;
                const oldHeight = texture.gpuHeight || 0;
                const oldDepth = texture.gpuDepth || 1;
                const oldLayers = texture.gpuLayers || 1;
                const oldLevels = texture.gpuLevels || 0;
                const oldFormat = texture.gpuFormat;
                texture.viewCache.clear();
                const dimension = texture.kind === "3D" ? "3d" : "2d";
                // BC formats are sampled/copied block data; WebGPU does not
                // make them color-renderable.  Giving every GL texture
                // RENDER_ATTACHMENT used to invalidate ordinary DXT textures
                // as soon as Cube 2 sampled them while rendering an envmap.
                // CopyTexImage/FBO paths already reject compressed levels, so
                // only uncompressed textures need the attachment capability.
                const usage = TEXTURE_USAGE_TEXTURE_BINDING |
                    TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_COPY_SRC |
                    (base.compressed ? 0 : TEXTURE_USAGE_RENDER_ATTACHMENT);
                texture.gpuTexture = this.device.createTexture({
                    label: "GL texture " + texture.name,
                    size: {
                        width: wanted.width, height: wanted.height,
                        depthOrArrayLayers: texture.kind === "3D" ?
                            wanted.depth : wanted.layers,
                    },
                    dimension,
                    mipLevelCount: wanted.levelCount,
                    format: wanted.format,
                    usage,
                });
                texture.gpuWidth = wanted.width;
                texture.gpuHeight = wanted.height;
                texture.gpuDepth = wanted.depth;
                texture.gpuLayers = wanted.layers;
                texture.gpuLevels = wanted.levelCount;
                texture.gpuFormat = wanted.format;

                // A level produced by CopyTexImage/FBO rendering has no CPU
                // shadow.  Growing the texture to add mip levels must preserve
                // those GPU-authored texels before the old allocation retires.
                if (oldTexture && oldFormat === wanted.format &&
                        oldWidth === wanted.width && oldHeight === wanted.height &&
                        oldDepth === wanted.depth) {
                    this.endPass();
                    const encoder = this.ensureEncoder();
                    const copyLevels = Math.min(oldLevels, wanted.levelCount);
                    const copyLayers = Math.min(oldLayers, wanted.layers);
                    for (let layer = 0; layer < copyLayers; ++layer) {
                        const list = texture.levels[layer] || [];
                        for (let level = 0; level < copyLevels; ++level) {
                            const slot = list[level];
                            if (!slot || slot.pixels) continue;
                            encoder.copyTextureToTexture(
                                { texture: oldTexture, mipLevel: level,
                                  origin: { x: 0, y: 0,
                                    z: texture.kind === "3D" ? 0 : layer } },
                                { texture: texture.gpuTexture, mipLevel: level,
                                  origin: { x: 0, y: 0,
                                    z: texture.kind === "3D" ? 0 : layer } },
                                { width: Math.max(1, wanted.width >> level),
                                  height: Math.max(1, wanted.height >> level),
                                  depthOrArrayLayers: texture.kind === "3D" ?
                                    Math.max(1, wanted.depth >> level) : 1 });
                        }
                    }
                }
                this.retire(oldTexture);
            }

            for (let layer = 0; layer < layers; ++layer) {
                const list = texture.levels[layer] || [];
                for (let level = 0; level < wanted.levelCount; ++level) {
                    const slot = list[level];
                    if (!slot || !slot.pixels) continue;
                    this.writeTextureLevel(texture, slot, level, layer);
                }
            }
            texture.dirty = false;
            return texture.gpuTexture;
        },

        writeTextureLevel(texture, slot, level, layer) {
            const bytesPerRow = slot.compressed ?
                Math.ceil(slot.width / 4) * slot.blockBytes :
                slot.width * (slot.bytesPerTexel || 4);
            const rowsPerImage = slot.compressed ?
                Math.ceil(slot.height / 4) : slot.height;
            const origin = texture.kind === "3D" ?
                { x: 0, y: 0, z: 0 } : { x: 0, y: 0, z: layer };
            this.device.queue.writeTexture(
                { texture: texture.gpuTexture, mipLevel: level, origin },
                slot.pixels,
                { offset: 0, bytesPerRow, rowsPerImage },
                {
                    // WebGPU expresses BC copies in complete physical blocks.
                    // The logical 2x2 and 1x1 tail mips still occupy one 4x4
                    // block, so their copy extent must be rounded up even
                    // though the texture's logical mip size remains smaller.
                    width: slot.compressed ? alignUp(slot.width, 4) : slot.width,
                    height: slot.compressed ? alignUp(slot.height, 4) : slot.height,
                    depthOrArrayLayers: texture.kind === "3D" ? slot.depth : 1,
                });
        },

        /*
         * WebGPU has no mipmap generator, so each level is produced by a
         * full-screen draw from the one above. Box filtering by bilinear
         * sampling at the half-texel centres is exactly the 2x2 average the GL
         * spec describes for power-of-two levels.
         */
        generateMipmap(target) {
            const texture = this.boundTexture(target);
            if (!texture)
                return this.refuse("glGenerateMipmap", "no texture bound",
                    { target }, GL.INVALID_OPERATION);
            this.generateMipmapFor(texture);
        },

        generateMipmapFor(texture) {
            const layers = texture.kind === "Cube" ? 6 : 1;
            let needsGPUGeneration = false;
            for (let layer = 0; layer < layers; ++layer) {
                const list = texture.levels[layer];
                if (!list || !list[0]) continue;
                const base = list[0];
                if (base.compressed) {
                    this.refuse("glGenerateMipmap",
                        "a compressed level cannot be downsampled",
                        { name: texture.name }, GL.INVALID_OPERATION);
                    continue;
                }
                const levels = fullMipLevelCount(base.width, base.height, base.depth);
                let source = base;
                for (let level = 1; level < levels; ++level) {
                    const width = Math.max(1, source.width >> 1);
                    const height = Math.max(1, source.height >> 1);
                    const depth = texture.kind === "3D" ?
                        Math.max(1, source.depth >> 1) : 1;
                    const pixels = source.pixels ?
                        downsampleBoxStorage(source, width, height, depth) : null;
                    const slot = {
                        width, height, depth, gpuFormat: base.gpuFormat,
                        base: base.base, compressed: false, pixels,
                        bytesPerTexel: base.bytesPerTexel || 4,
                        componentType: base.componentType || "u8",
                        componentCount: base.componentCount || 4,
                    };
                    list[level] = slot;
                    source = slot;
                    if (!pixels) needsGPUGeneration = true;
                }
                list.length = levels;
            }
            texture.dirty = true;
            texture.viewCache.clear();
            this.invalidateBindGroups();
            if (needsGPUGeneration)
                this.generateTextureMipmapsGPU(texture);
        },
    });

    function isMipmapFilter(filter) {
        return filter === GL.NEAREST_MIPMAP_NEAREST ||
            filter === GL.LINEAR_MIPMAP_NEAREST ||
            filter === GL.NEAREST_MIPMAP_LINEAR ||
            filter === GL.LINEAR_MIPMAP_LINEAR;
    }

    function fullMipLevelCount(width, height, depth) {
        return Math.floor(Math.log2(Math.max(width, height, depth || 1))) + 1;
    }

    function downsampleBox(src, srcW, srcH, srcD, dstW, dstH, dstD) {
        const out = new Uint8Array(dstW * dstH * dstD * 4);
        const xScale = srcW / dstW, yScale = srcH / dstH;
        const zScale = (srcD || 1) / (dstD || 1);
        for (let z = 0; z < dstD; ++z) {
            for (let y = 0; y < dstH; ++y) {
                for (let x = 0; x < dstW; ++x) {
                    const x0 = Math.floor(x * xScale), y0 = Math.floor(y * yScale);
                    const z0 = Math.floor(z * zScale);
                    const x1 = Math.min(srcW - 1, x0 + (xScale > 1 ? 1 : 0));
                    const y1 = Math.min(srcH - 1, y0 + (yScale > 1 ? 1 : 0));
                    const z1 = Math.min((srcD || 1) - 1, z0 + (zScale > 1 ? 1 : 0));
                    const dst = ((z * dstH + y) * dstW + x) * 4;
                    for (let c = 0; c < 4; ++c) {
                        let sum = 0;
                        let n = 0;
                        for (const sz of z0 === z1 ? [z0] : [z0, z1]) {
                            for (const sy of y0 === y1 ? [y0] : [y0, y1]) {
                                for (const sx of x0 === x1 ? [x0] : [x0, x1]) {
                                    sum += src[((sz * srcH + sy) * srcW + sx) * 4 + c];
                                    ++n;
                                }
                            }
                        }
                        out[dst + c] = Math.round(sum / n);
                    }
                }
            }
        }
        return out;
    }

    function downsampleBoxStorage(source, dstW, dstH, dstD) {
        const srcW = source.width, srcH = source.height, srcD = source.depth || 1;
        const componentType = source.componentType || "u8";
        const componentCount = source.componentCount || 4;
        const bytesPerTexel = source.bytesPerTexel || 4;
        if (componentType === "u8" && componentCount === 4)
            return downsampleBox(source.pixels, srcW, srcH, srcD,
                dstW, dstH, dstD);
        const out = new Uint8Array(dstW * dstH * dstD * bytesPerTexel);
        const srcView = new DataView(source.pixels.buffer,
            source.pixels.byteOffset, source.pixels.byteLength);
        const dstView = new DataView(out.buffer);
        const read = (texel, component) => {
            const at = texel * bytesPerTexel;
            if (componentType === "f16")
                return halfToFloat(srcView.getUint16(at + component * 2, true));
            if (componentType === "f32")
                return srcView.getFloat32(at + component * 4, true);
            if (componentType === "u16")
                return srcView.getUint16(at + component * 2, true);
            return srcView.getUint8(at + component);
        };
        const write = (texel, component, value) => {
            const at = texel * bytesPerTexel;
            if (componentType === "f16")
                dstView.setUint16(at + component * 2, floatToHalf(value), true);
            else if (componentType === "f32")
                dstView.setFloat32(at + component * 4, value, true);
            else if (componentType === "u16")
                dstView.setUint16(at + component * 2, Math.round(value), true);
            else dstView.setUint8(at + component, Math.round(value));
        };
        const xScale = srcW / dstW, yScale = srcH / dstH, zScale = srcD / dstD;
        for (let z = 0; z < dstD; ++z) for (let y = 0; y < dstH; ++y)
            for (let x = 0; x < dstW; ++x) {
                const x0 = Math.floor(x * xScale), y0 = Math.floor(y * yScale);
                const z0 = Math.floor(z * zScale);
                const x1 = Math.min(srcW - 1, x0 + (xScale > 1 ? 1 : 0));
                const y1 = Math.min(srcH - 1, y0 + (yScale > 1 ? 1 : 0));
                const z1 = Math.min(srcD - 1, z0 + (zScale > 1 ? 1 : 0));
                const destination = (z * dstH + y) * dstW + x;
                for (let c = 0; c < componentCount; ++c) {
                    let sum = 0, samples = 0;
                    for (const sz of z0 === z1 ? [z0] : [z0, z1])
                        for (const sy of y0 === y1 ? [y0] : [y0, y1])
                            for (const sx of x0 === x1 ? [x0] : [x0, x1]) {
                                sum += read((sz * srcH + sy) * srcW + sx, c);
                                ++samples;
                            }
                    write(destination, c, sum / samples);
                }
            }
        return out;
    }

    /* ================================================================== */
    /* Executor: buffers and programs                                     */
    /* ================================================================== */

    Object.assign(GLWebGPUExecutor.prototype, {

        bufferFor(target) {
            const s = this.current;
            const name = target === GL.ELEMENT_ARRAY_BUFFER ? s.elementArrayBuffer :
                (target === GL.PIXEL_PACK_BUFFER ? s.pixelPackBuffer :
                    (target === GL.PIXEL_UNPACK_BUFFER ? s.pixelUnpackBuffer :
                        s.arrayBuffer));
            if (!name) return null;
            return s.shareGroup.buffers.get(name) || null;
        },

        bufferData(target, byteCount, usage, data) {
            const buffer = this.bufferFor(target);
            if (!buffer)
                return this.refuse("glBufferData", "no buffer bound", { target },
                    GL.INVALID_OPERATION);
            buffer.size = byteCount;
            buffer.usage = usage;
            buffer.target = target;
            buffer.shadow = new Uint8Array(byteCount);
            if (data) buffer.shadow.set(data.subarray(0,
                Math.min(data.byteLength, byteCount)));
            this.replaceBufferStorage(buffer);
        },

        replaceBufferStorage(buffer) {
            this.invalidateVertexConversions(buffer);
            this.retire(buffer.gpuBuffer);
            // The same buffer may be bound as vertex data now and as indices
            // later, and GL never says which; asking for both costs nothing.
            const byteCount = buffer.shadow.byteLength;
            const size = alignUp(byteCount, 4);
            buffer.gpuBuffer = byteCount ? this.device.createBuffer({
                label: "GL buffer " + buffer.name,
                size,
                usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_INDEX |
                    BUFFER_USAGE_COPY_DST | BUFFER_USAGE_COPY_SRC,
            }) : null;
            if (buffer.gpuBuffer) {
                const upload = size === byteCount ? buffer.shadow :
                    new Uint8Array(size);
                if (upload !== buffer.shadow) upload.set(buffer.shadow);
                this.device.queue.writeBuffer(buffer.gpuBuffer, 0, upload, 0, size);
            }
        },

        bufferSubData(target, offset, data) {
            const buffer = this.bufferFor(target);
            if (!buffer || !buffer.shadow)
                return this.refuse("glBufferSubData", "no buffer storage",
                    { target }, GL.INVALID_OPERATION);
            if (offset + data.byteLength > buffer.shadow.byteLength)
                return this.refuse("glBufferSubData", "update is out of range",
                    { offset, size: data.byteLength }, GL.INVALID_VALUE);
            this.invalidateVertexConversions(buffer);
            buffer.shadow.set(data, offset);
            if (buffer.gpuBuffer) {
                // Queue writes execute before a command buffer submitted later,
                // even if its draw was encoded first. Rename live storage so a
                // dynamic model update cannot change already-recorded geometry.
                // No pass/occlusion-query split is needed for this copy-on-write.
                if (this.pendingVertexBuffers.has(buffer.gpuBuffer)) {
                    this.replaceBufferStorage(buffer);
                    return;
                }
                // writeBuffer wants 4-byte alignment at both ends; a ragged
                // update is widened to the enclosing aligned span, which is
                // safe because the shadow copy holds the true contents.
                const start = offset & ~3;
                const end = alignUp(offset + data.byteLength, 4);
                const clampedEnd = Math.min(end, buffer.shadow.byteLength);
                const span = end - start;
                if (span > 0) {
                    if (end <= buffer.shadow.byteLength) {
                        this.device.queue.writeBuffer(buffer.gpuBuffer, start,
                            buffer.shadow, start, span);
                    } else {
                        const upload = new Uint8Array(span);
                        upload.set(buffer.shadow.subarray(start, clampedEnd));
                        this.device.queue.writeBuffer(buffer.gpuBuffer, start,
                            upload, 0, span);
                    }
                }
            }
        },

        /* ---- programs ---- */

        linkProgram(name) {
            const program = this.current.shareGroup.programs.get(name);
            if (!program)
                return this.refuse("glLinkProgram", "unknown program", { name },
                    GL.INVALID_VALUE);
            program.linked = false;
            program.log = "";
            program.variants.clear();
            program.compiled = { vertex: null, fragment: null };
            for (const shaderName of program.shaders) {
                const shader = this.current.shareGroup.shaders.get(shaderName);
                if (!shader) continue;
                if (!shader.compiled)
                    shader.compiled = translator.compileShader(shader.source,
                        shader.stage, this.options.translator || {});
                if (!shader.compiled.ok) {
                    program.log = shader.compiled.log;
                    return;
                }
                program.compiled[shader.stage] = shader.compiled;
            }
            if (!program.compiled.vertex || !program.compiled.fragment) {
                program.log = "ERROR: a program needs both a vertex and a " +
                    "fragment shader";
                return;
            }
            // The base link (no pipeline variant) settles the uniform layout
            // and the reflection, which every variant then shares -- so
            // glGetUniformLocation answers the same value no matter which
            // variant a later draw happens to need.
            const link = this.linkVariant(program, {});
            if (!link.ok) {
                program.log = link.log;
                return;
            }
            program.link = link;
            program.linked = true;
            program.log = link.log;
            this.buildUniformStorage(program, link.reflection);
            ++program.serial;
        },

        variantKeyFor(variant) {
            return [variant.alphaTest || "-", variant.clipPlaneCount || 0,
                    variant.pointSprite ? "p" : "-",
                    variant.pointCoordLowerLeft ? "l" : "u",
                    variant.polygonStipple ? "s" : "-",
                    "o" + (variant.logicOp || 0).toString(16),
                    variant.twoSided ? "2" : "-",
                    variant.flatShading ? "f" : "-",
                    variant.colorTargets || 1].join("|");
        },

        linkVariant(program, variant) {
            const options = {
                bindAttribLocations: program.bindAttribLocations,
                variant,
                maxColorTargets: variant.colorTargets,
                nonUniformSampleStrategy:
                    this.options.nonUniformSampleStrategy || "grad",
            };
            const key = translator.hashString(
                program.name + "|" + this.variantKeyFor(variant) + "|" +
                (program.compiled.vertex.sourceHash >>> 0) + "|" +
                (program.compiled.fragment.sourceHash >>> 0)).toString(16);
            const cached = this.shaderCache.get(key);
            if (cached) {
                ++this.stats.shaderCacheHits;
                return cached;
            }
            const link = translator.linkProgram(program.compiled.vertex,
                program.compiled.fragment, options);
            if (link.ok) {
                ++this.stats.shaderLinks;
                this.stats.nonUniformSamples += link.stats.nonUniformSamples;
                this.shaderCache.set(key, link);
            }
            return link;
        },

        buildUniformStorage(program, reflection) {
            program.uniformData = new Uint8Array(
                Math.max(16, reflection.uniformBlockBytes));
            program.uniformFloats = new Float32Array(program.uniformData.buffer);
            program.uniformInts = new Int32Array(program.uniformData.buffer);
            program.uniformByName.clear();
            program.uniformByLocation.clear();
            for (const uniform of reflection.uniforms) {
                const count = Math.max(1, uniform.arraySize);
                const location = this.nextUniformLocation;
                this.nextUniformLocation += count;
                const mapped = Object.assign({}, uniform, { location });
                program.uniformByName.set(mapped.name, mapped);
                for (let i = 0; i < count; ++i)
                    program.uniformByLocation.set(location + i,
                        { uniform: mapped, element: i });
            }
            program.samplerUnits.clear();
            for (const sampler of reflection.samplers) {
                const count = Math.max(1, sampler.arraySize);
                const location = this.nextUniformLocation;
                this.nextUniformLocation += count;
                const mapped = Object.assign({}, sampler, { location });
                program.uniformByName.set(mapped.name, mapped);
                for (let i = 0; i < count; ++i) {
                    program.uniformByLocation.set(location + i,
                        { sampler: mapped, element: i });
                    program.samplerUnits.set(mapped.name +
                        (mapped.arraySize ? "[" + i + "]" : ""), 0);
                }
            }
        },

        currentProgramObject() {
            const s = this.current;
            if (!s.currentProgram) return null;
            const program = s.shareGroup.programs.get(s.currentProgram);
            return program && program.linked ? program : null;
        },

        setUniformVector(view, offset, size, bytes, integer) {
            const program = this.currentProgramObject();
            if (!program) return;
            const location = view.getInt32(offset, true);
            const components = view.getInt32(offset + 4, true);
            const count = view.getInt32(offset + 8, true);
            if (components < 1 || components > 4 || count < 0) return;
            const entry = program.uniformByLocation.get(location);
            if (!entry) return;

            if (entry.sampler) {
                // glUniform1i on a sampler names a texture unit; it is a
                // binding change, not a value in the uniform block.
                const unit = view.getInt32(offset + 12, true);
                const key = entry.sampler.name +
                    (entry.sampler.arraySize ? "[" + entry.element + "]" : "");
                program.samplerUnits.set(key, unit | 0);
                this.invalidateBindGroups();
                return;
            }

            const uniform = entry.uniform;
            const stride = uniform.arraySize ?
                uniform.arrayStrideBytes : 0;
            for (let i = 0; i < count; ++i) {
                const element = entry.element + i;
                if (uniform.arraySize && element >= uniform.arraySize) break;
                const base = uniform.offsetBytes + element * stride;
                for (let c = 0; c < components; ++c) {
                    const src = offset + 12 + (i * components + c) * 4;
                    if (src + 4 > offset + size) return;
                    const at = (base >> 2) + c;
                    if (integer || uniform.baseType !== "float")
                        program.uniformInts[at] = view.getInt32(src, true);
                    else
                        program.uniformFloats[at] = view.getFloat32(src, true);
                }
            }
            ++program.serial;
        },

        setUniformMatrix(location, columns, rows, count, transpose, view, offset,
                size) {
            const program = this.currentProgramObject();
            if (!program) return;
            const entry = program.uniformByLocation.get(location);
            if (!entry || !entry.uniform) return;
            const uniform = entry.uniform;
            const columnStride = uniform.matrixColumnStrideBytes ||
                (rows === 2 ? 8 : 16);
            const stride = uniform.arraySize ? uniform.arrayStrideBytes : 0;
            for (let m = 0; m < count; ++m) {
                const element = entry.element + m;
                if (uniform.arraySize && element >= uniform.arraySize) break;
                const base = uniform.offsetBytes + element * stride;
                for (let c = 0; c < columns; ++c) {
                    for (let r = 0; r < rows; ++r) {
                        // GL's default is column-major; transpose means the
                        // caller handed rows first.
                        const sourceIndex = transpose ?
                            (r * columns + c) : (c * rows + r);
                        const src = offset + (m * columns * rows + sourceIndex) * 4;
                        if (src + 4 > offset + size) return;
                        const at = (base + c * columnStride) / 4 + r;
                        program.uniformFloats[at] = view.getFloat32(src, true);
                    }
                }
            }
            ++program.serial;
        },

        /* ---- synchronous query answers ---- */

        queryLocation(kind, programName, name) {
            const program = this.current.shareGroup.programs.get(programName);
            if (!program || !program.linked || !program.link) return null;
            const reflection = program.link.reflection;
            if (kind === LOCATION_KIND_ATTRIB) {
                // glGetAttribLocation
                const attribute = reflection.attributes.find(a => a.name === name);
                if (!attribute) return { location: -1, type: 0, size: 0 };
                return { location: attribute.location,
                         type: glslTypeEnum(attribute.glslType),
                         size: 1 };
            }
            // glGetUniformLocation. GL says name and name[0] are the same
            // location, and name[i] is location + i.
            let lookupName = name;
            let element = 0;
            const match = /^(.*)\[(\d+)\]$/.exec(name);
            if (match) { lookupName = match[1]; element = parseInt(match[2], 10); }
            const uniform = program.uniformByName.get(lookupName);
            if (!uniform) return { location: -1, type: 0, size: 0 };
            if (uniform.arraySize && element >= uniform.arraySize)
                return { location: -1, type: 0, size: 0 };
            return {
                location: uniform.location + element,
                type: glslTypeEnum(uniform.glslType ||
                    samplerTypeName(uniform)),
                size: uniform.arraySize || 1,
            };
        },

        readUniform(programName, location, valueKind) {
            const program = this.current.shareGroup.programs.get(programName);
            if (!program || !program.linked) return null;
            const entry = program.uniformByLocation.get(location);
            if (!entry) return null;
            if (entry.sampler) {
                const key = entry.sampler.name +
                    (entry.sampler.arraySize ? "[" + entry.element + "]" : "");
                return [program.samplerUnits.get(key) || 0];
            }
            const uniform = entry.uniform;
            const stride = uniform.arraySize ? uniform.arrayStrideBytes : 0;
            const base = uniform.offsetBytes + entry.element * stride;
            const values = [];
            if (uniform.kind === "matrix") {
                const columnStride = uniform.matrixColumnStrideBytes;
                for (let c = 0; c < uniform.columns; ++c)
                    for (let r = 0; r < uniform.rows; ++r)
                        values.push(program.uniformFloats[
                            (base + c * columnStride) / 4 + r]);
            } else {
                for (let c = 0; c < uniform.components; ++c) {
                    values.push(valueKind === 2 || uniform.baseType !== "float" ?
                        program.uniformInts[(base >> 2) + c] :
                        program.uniformFloats[(base >> 2) + c]);
                }
            }
            return values;
        },

        queryObjectiv(kind, name, pname) {
            const group = this.current.shareGroup;
            if (kind === 1) {                     // shader
                const shader = group.shaders.get(name);
                if (!shader) return null;
                switch (pname) {
                case GL.COMPILE_STATUS:
                    return shader.compiled && shader.compiled.ok ? 1 : 0;
                case GL.INFO_LOG_LENGTH:
                    return shader.compiled ? shader.compiled.log.length + 1 : 1;
                case GL.SHADER_SOURCE_LENGTH: return shader.source.length + 1;
                case GL.SHADER_TYPE: return shader.type;
                case GL.DELETE_STATUS: return 0;
                default: return 0;
                }
            }
            if (kind === 2) {                     // program
                const program = group.programs.get(name);
                if (!program) return null;
                const reflection = program.link ? program.link.reflection : null;
                switch (pname) {
                case GL.LINK_STATUS: return program.linked ? 1 : 0;
                case GL.VALIDATE_STATUS: return program.linked ? 1 : 0;
                case GL.INFO_LOG_LENGTH: return program.log.length + 1;
                case GL.ATTACHED_SHADERS: return program.shaders.size;
                case GL.ACTIVE_UNIFORMS:
                    return reflection ?
                        reflection.uniforms.length + reflection.samplers.length : 0;
                case GL.ACTIVE_ATTRIBUTES:
                    return reflection ? reflection.attributes.length : 0;
                case GL.ACTIVE_UNIFORM_MAX_LENGTH:
                    return reflection ? maxNameLength(reflection.uniforms,
                        reflection.samplers) : 1;
                case GL.ACTIVE_ATTRIBUTE_MAX_LENGTH:
                    return reflection ? maxNameLength(reflection.attributes) : 1;
                case GL.DELETE_STATUS: return 0;
                default: return 0;
                }
            }
            // Occlusion query object.
            const query = this.queries.get(name);
            if (!query) return null;
            if (pname === GL.QUERY_RESULT_AVAILABLE) return query.ready ? 1 : 0;
            if (pname === GL.QUERY_RESULT) return query.result >>> 0;
            return 0;
        },

        queryObjectLog(kind, name) {
            const group = this.current.shareGroup;
            if (kind === 1) {
                const shader = group.shaders.get(name);
                return shader ? (shader.compiled ? shader.compiled.log : "") : null;
            }
            const program = group.programs.get(name);
            return program ? program.log : null;
        },

        /* openglproxy's V86GL_ACTIVE_KIND_UNIFORM is 1 and _ATTRIB is 2. */
        queryActive(kind, programName, index) {
            const program = this.current.shareGroup.programs.get(programName);
            if (!program || !program.link) return null;
            const reflection = program.link.reflection;
            if (kind === ACTIVE_KIND_ATTRIB) {
                const attribute = reflection.attributes[index];
                if (!attribute) return null;
                return { name: attribute.name, size: 1,
                         type: glslTypeEnum(attribute.glslType) };
            }
            const all = reflection.uniforms.concat(reflection.samplers);
            const uniform = all[index];
            if (!uniform) return null;
            return {
                name: uniform.arraySize ? uniform.name + "[0]" : uniform.name,
                size: uniform.arraySize || 1,
                type: glslTypeEnum(uniform.glslType || samplerTypeName(uniform)),
            };
        },
    });

    function maxNameLength(...lists) {
        let longest = 0;
        for (const list of lists)
            for (const entry of list)
                longest = Math.max(longest, entry.name.length);
        return longest + 1;
    }

    function samplerTypeName(sampler) {
        if (!sampler.dim) return "sampler2D";
        return "sampler" + sampler.dim + (sampler.shadow ? "Shadow" : "");
    }

    /* GLSL type names to the GL_* enums glGetActiveUniform reports. */
    const GLSL_TYPE_ENUMS = {
        float: GL.FLOAT, vec2: GL.FLOAT_VEC2, vec3: GL.FLOAT_VEC3,
        vec4: GL.FLOAT_VEC4,
        int: GL.INT, ivec2: GL.INT_VEC2, ivec3: GL.INT_VEC3, ivec4: GL.INT_VEC4,
        bool: GL.BOOL, bvec2: GL.BOOL_VEC2, bvec3: GL.BOOL_VEC3,
        bvec4: GL.BOOL_VEC4,
        mat2: GL.FLOAT_MAT2, mat3: GL.FLOAT_MAT3, mat4: GL.FLOAT_MAT4,
        mat2x3: GL.FLOAT_MAT2x3, mat2x4: GL.FLOAT_MAT2x4,
        mat3x2: GL.FLOAT_MAT3x2, mat3x4: GL.FLOAT_MAT3x4,
        mat4x2: GL.FLOAT_MAT4x2, mat4x3: GL.FLOAT_MAT4x3,
        sampler1D: GL.SAMPLER_1D, sampler2D: GL.SAMPLER_2D,
        sampler3D: GL.SAMPLER_3D, samplerCube: GL.SAMPLER_CUBE,
        sampler1DShadow: GL.SAMPLER_1D_SHADOW,
        sampler2DShadow: GL.SAMPLER_2D_SHADOW,
    };

    function glslTypeEnum(name) {
        return GLSL_TYPE_ENUMS[name] || 0;
    }

    /* ================================================================== */
    /* Executor: vertex assembly and drawing                              */
    /* ================================================================== */

    /* GL vertex types that WebGPU can consume without conversion. Anything
     * else is widened to float32 on the CPU, because the generated shaders
     * declare every attribute as a float vector. */
    const DIRECT_VERTEX_FORMATS = {
        [GL.FLOAT]: { 1: "float32", 2: "float32x2", 3: "float32x3", 4: "float32x4" },
        [GL.HALF_FLOAT]: { 2: "float16x2", 4: "float16x4" },
    };
    const DIRECT_NORMALIZED_FORMATS = {
        [GL.UNSIGNED_BYTE]: { 4: "unorm8x4" },
        [GL.BYTE]: { 4: "snorm8x4" },
        [GL.UNSIGNED_SHORT]: { 2: "unorm16x2", 4: "unorm16x4" },
        [GL.SHORT]: { 2: "snorm16x2", 4: "snorm16x4" },
    };

    function componentBytes(type) {
        switch (type) {
        case GL.BYTE: case GL.UNSIGNED_BYTE: return 1;
        case GL.SHORT: case GL.UNSIGNED_SHORT: case GL.HALF_FLOAT: return 2;
        case GL.INT: case GL.UNSIGNED_INT: case GL.FLOAT: return 4;
        case GL.DOUBLE: return 8;
        default: return 0;
        }
    }

    function readComponent(view, at, type, normalized) {
        switch (type) {
        case GL.FLOAT: return view.getFloat32(at, true);
        case GL.DOUBLE: return view.getFloat64(at, true);
        case GL.BYTE: {
            const v = view.getInt8(at);
            return normalized ? Math.max(v / 127, -1) : v;
        }
        case GL.UNSIGNED_BYTE: {
            const v = view.getUint8(at);
            return normalized ? v / 255 : v;
        }
        case GL.SHORT: {
            const v = view.getInt16(at, true);
            return normalized ? Math.max(v / 32767, -1) : v;
        }
        case GL.UNSIGNED_SHORT: {
            const v = view.getUint16(at, true);
            return normalized ? v / 65535 : v;
        }
        case GL.INT: {
            const v = view.getInt32(at, true);
            return normalized ? Math.max(v / 2147483647, -1) : v;
        }
        case GL.UNSIGNED_INT: {
            const v = view.getUint32(at, true);
            return normalized ? v / 4294967295 : v;
        }
        default: return 0;
        }
    }

    Object.assign(GLWebGPUExecutor.prototype, {

        /* ---- immediate mode ---- */

        /*
         * glBegin/glEnd arrives one record per vertex, so the accumulator here
         * is where a Half-Life frame's twenty thousand vertices actually land.
         * Each vertex snapshots GL's *current* colour, normal and texture
         * coordinates, which is the whole semantic of immediate mode.
         */
        beginImmediate(mode) {
            const s = this.current;
            if (s.immediate)
                return this.refuse("glBegin", "glBegin inside glBegin", { mode },
                    GL.INVALID_OPERATION);
            if (PRIMITIVE_TOPOLOGY[mode] === undefined)
                return this.refuse("glBegin", "unknown primitive mode", { mode },
                    GL.INVALID_ENUM);
            s.immediate = {
                mode, count: 0,
                data: this.immediateBuffer || (this.immediateBuffer =
                    new Float32Array(65536)),
                stride: 0,
                used: { color: false, normal: false, secondaryColor: false,
                        fogCoord: false,
                        texCoord: new Array(MAX_TEXTURE_COORDS).fill(false),
                        generic: [] },
            };
            const used = s.immediate.used;
            const program = this.currentProgramObject();
            const arbVertex = s.enabled.has(GL.VERTEX_PROGRAM_ARB);
            // Immediate vertices must satisfy the active shader interface, not
            // stale client-array enables. Legacy renderers commonly keep a
            // normal array enabled while drawing glBegin/glEnd UI geometry;
            // conversely an ARB vertex program may read vertex.normal with
            // fixed-function lighting disabled. In both cases deriving this
            // layout only from GL_LIGHTING/client-array state leaves
            // @location(2) unbound.
            for (const entry of this.wantedAttributes(program)) {
                let source = entry.source;
                if (source.indexOf("generic") === 0 && entry.alias &&
                        (entry.alias === "vertex" || entry.alias === "normal" ||
                         entry.alias === "color" ||
                         entry.alias === "secondaryColor" ||
                         entry.alias === "fogCoord" ||
                         entry.alias.indexOf("texCoord") === 0))
                    source = entry.alias;
                if (source === "color") used.color = true;
                else if (source === "normal") used.normal = true;
                else if (source === "secondaryColor") used.secondaryColor = true;
                else if (source === "fogCoord") used.fogCoord = true;
                else if (source.indexOf("texCoord") === 0) {
                    const unit = Number(source.substring(8));
                    if (unit >= 0 && unit < MAX_TEXTURE_COORDS)
                        used.texCoord[unit] = true;
                } else if (source.indexOf("generic") === 0) {
                    const index = Number(source.substring(7));
                    if (index >= 0 && index < MAX_VERTEX_ATTRIBS &&
                            !used.generic.some(item =>
                                item.location === entry.location)) {
                        used.generic.push({
                            index, location: entry.location,
                            components: Math.min(4,
                                Math.max(1, entry.components || 4)),
                        });
                    }
                }
            }
            // The fixed pipeline always consumes current colour even when no
            // colour command occurs in the batch. Programmable shaders carry
            // it only when reflection above says they actually read it.
            if (!program && !arbVertex) used.color = true;
        },

        immediateVertex(x, y, z, w) {
            const s = this.current;
            const batch = s.immediate;
            if (!batch)
                return this.refuse("glVertex", "glVertex outside glBegin", {},
                    GL.INVALID_OPERATION);
            const used = batch.used;
            for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit)
                if (s.textureUnits[unit].enabledTargets.size)
                    used.texCoord[unit] = true;
            if (s.enabled.has(GL.LIGHTING)) used.normal = true;
            if (s.enabled.has(GL.COLOR_SUM) ||
                    s.lightModel.colorControl === GL.SEPARATE_SPECULAR_COLOR)
                used.secondaryColor = true;
            if (s.enabled.has(GL.FOG) && s.fog.coordSource === GL.FOG_COORD)
                used.fogCoord = true;

            const stride = this.immediateStride(used);
            const need = (batch.count + 1) * stride;
            if (need > batch.data.length) {
                const grown = new Float32Array(Math.max(need * 2,
                    batch.data.length * 2));
                grown.set(batch.data.subarray(0, batch.count * batch.stride));
                batch.data = grown;
                this.immediateBuffer = grown;
            }
            if (stride !== batch.stride && batch.count) {
                // A later vertex enabled an attribute the earlier ones did not
                // carry. Re-laying out the batch keeps one buffer per glEnd,
                // which is worth more than the rare copy.
                this.relayoutImmediate(batch, stride);
            }
            batch.stride = stride;
            let at = batch.count * stride;
            const data = batch.data;
            const current = s.current;
            data[at++] = x; data[at++] = y; data[at++] = z; data[at++] = w;
            if (used.color) {
                data[at++] = current.color[0]; data[at++] = current.color[1];
                data[at++] = current.color[2]; data[at++] = current.color[3];
            }
            if (used.normal) {
                data[at++] = current.normal[0]; data[at++] = current.normal[1];
                data[at++] = current.normal[2];
            }
            if (used.secondaryColor) {
                data[at++] = current.secondaryColor[0];
                data[at++] = current.secondaryColor[1];
                data[at++] = current.secondaryColor[2];
                data[at++] = current.secondaryColor[3];
            }
            if (used.fogCoord) data[at++] = current.fogCoord;
            for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit) {
                if (!used.texCoord[unit]) continue;
                const tc = current.texCoord[unit];
                data[at++] = tc[0]; data[at++] = tc[1];
                data[at++] = tc[2]; data[at++] = tc[3];
            }
            for (const item of used.generic) {
                const value = s.genericAttribs[item.index].value;
                for (let c = 0; c < item.components; ++c)
                    data[at++] = value[c];
            }
            ++batch.count;
        },

        immediateStride(used) {
            let stride = 4;
            if (used.color) stride += 4;
            if (used.normal) stride += 3;
            if (used.secondaryColor) stride += 4;
            if (used.fogCoord) stride += 1;
            for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit)
                if (used.texCoord[unit]) stride += 4;
            for (const item of used.generic) stride += item.components;
            return stride;
        },

        relayoutImmediate(batch, stride) {
            const grown = new Float32Array(
                Math.max(batch.data.length, (batch.count + 1) * stride * 2));
            for (let i = 0; i < batch.count; ++i)
                grown.set(batch.data.subarray(i * batch.stride,
                    i * batch.stride + batch.stride), i * stride);
            batch.data = grown;
            this.immediateBuffer = grown;
        },

        endImmediate() {
            const s = this.current;
            const batch = s.immediate;
            if (!batch || !batch.count) {
                s.immediate = null;
                return;
            }
            ++this.stats.immediateBatches;

            const attributes = [];
            let offset = 0;
            const push = (location, components) => {
                attributes.push({ location, components, offsetFloats: offset });
                offset += components;
            };
            push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_Vertex, 4);
            if (batch.used.color)
                push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_Color, 4);
            if (batch.used.normal)
                push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_Normal, 3);
            if (batch.used.secondaryColor)
                push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_SecondaryColor, 4);
            if (batch.used.fogCoord)
                push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_FogCoord, 1);
            for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit)
                if (batch.used.texCoord[unit])
                    push(translator.COMPAT_ATTRIBUTE_LOCATIONS.gl_MultiTexCoord0 +
                        unit, 4);
            for (const item of batch.used.generic)
                push(item.location, item.components);

            const bytes = new Uint8Array(batch.data.buffer, 0,
                batch.count * batch.stride * 4);
            const slice = this.uploadVertices(bytes);
            if (!slice) {
                s.immediate = null;
                return;
            }
            try {
                this.issueDraw({
                    mode: batch.mode,
                    vertexCount: batch.count,
                    buffers: [{
                        gpuBuffer: slice.buffer,
                        baseOffset: slice.offset,
                        stride: batch.stride * 4,
                        attributes: attributes.map(a => ({
                            location: a.location,
                            format: "float32" + (a.components > 1 ?
                                "x" + a.components : ""),
                            offset: a.offsetFloats * 4,
                        })),
                    }],
                    index: null,
                });
            } finally {
                s.immediate = null;
            }
        },

        /* ---- packed client arrays ---- */

        drawPacked(mode, count, arrays, indexInfo) {
            if (count <= 0) return;
            if (PRIMITIVE_TOPOLOGY[mode] === undefined)
                return this.refuse("glDrawArrays", "unknown primitive mode",
                    { mode }, GL.INVALID_ENUM);
            const program = this.currentProgramObject();
            const wanted = this.wantedAttributes(program);
            let sourceIndices = null;
            let firstSourceVertex = 0;
            let packedVertexCount = count;
            let drawIndexInfo = indexInfo;
            if (indexInfo && indexInfo.data) {
                const indices = indexInfo.decoded ||
                    readIndices(indexInfo.type, indexInfo.data, count);
                const expandIndexedPoints = mode === GL.POINTS &&
                    (this.current.point.size !== 1 ||
                        this.current.enabled.has(GL.POINT_SPRITE));
                if (expandIndexedPoints) {
                    sourceIndices = indices;
                    packedVertexCount = count;
                    drawIndexInfo = null;
                } else {
                    let min = 0xffffffff, max = 0;
                    for (const value of indices) {
                        min = Math.min(min, value);
                        max = Math.max(max, value);
                    }
                    const rebased = new Uint32Array(indices.length);
                    if (max - min + 1 <= count * 2) {
                        firstSourceVertex = min;
                        packedVertexCount = max - min + 1;
                        for (let i = 0; i < indices.length; ++i)
                            rebased[i] = indices[i] - min;
                    } else {
                        // Sparse draws must not allocate the entire unused
                        // interval between their lowest and highest index.
                        const remap = new Map();
                        sourceIndices = [];
                        for (let i = 0; i < indices.length; ++i) {
                            const value = indices[i];
                            if (!remap.has(value)) {
                                remap.set(value, sourceIndices.length);
                                sourceIndices.push(value);
                            }
                            rebased[i] = remap.get(value);
                        }
                        packedVertexCount = sourceIndices.length;
                    }
                    drawIndexInfo = { type: GL.UNSIGNED_INT,
                        data: new Uint8Array(rebased.buffer), decoded: rebased };
                }
            }

            const arbVertexOn = this.current.enabled.has(GL.VERTEX_PROGRAM_ARB);
            if (!program && !arbVertexOn &&
                    (!arrays.vertex || !arrays.vertex.data))
                return this.refuse("glDrawArrays",
                    "the fixed pipeline needs a vertex array", { mode },
                    GL.INVALID_OPERATION);

            // Every array is widened to float32 and interleaved into one ring
            // slice. Packing costs a pass over the data, but it is the only
            // shape that handles GL's whole type matrix, and the arrays already
            // arrived as a CPU copy from the guest.
            const layout = [];
            let stride = 0;
            for (const entry of wanted) {
                const source = this.resolveAttributeSource(arrays, entry,
                    block => !!(block && block.data));
                const block = arrays[source];
                const constant = (!block || !block.data) ?
                    this.currentAttributeValue(source, entry.location) : null;
                if ((!block || !block.data) && !constant) continue;
                const components = entry.components || (block ?
                    Math.min(4, Math.max(1, block.size || 4)) : constant.length);
                layout.push({ location: entry.location, source,
                              block, constant, components, offsetFloats: stride });
                stride += components;
            }
            if (!layout.length)
                return this.refuse("glDrawArrays", "no vertex array is enabled",
                    { mode }, GL.INVALID_OPERATION);

            const packed = new Float32Array(stride * packedVertexCount);
            for (const item of layout) {
                const block = item.block;
                if (!block || !block.data) {
                    for (let v = 0; v < packedVertexCount; ++v) {
                        const dst = v * stride + item.offsetFloats;
                        for (let c = 0; c < item.components; ++c)
                            packed[dst + c] = c < item.constant.length ?
                                item.constant[c] : (c === 3 ? 1 : 0);
                    }
                    continue;
                }
                const view = new DataView(block.data.buffer,
                    block.data.byteOffset, block.data.byteLength);
                const size = Math.max(1, block.size || item.components);
                const elementBytes = componentBytes(block.type);
                if (!elementBytes) {
                    this.refuse("glDrawArrays", "unsupported array type",
                        { type: block.type }, GL.INVALID_ENUM);
                    return;
                }
                const srcStride = block.stride || size * elementBytes;
                const normalized = this.arrayIsNormalized(item.source, block);
                for (let v = 0; v < packedVertexCount; ++v) {
                    const sourceVertex = sourceIndices ? sourceIndices[v] :
                        firstSourceVertex + v;
                    const src = sourceVertex * srcStride;
                    const dst = v * stride + item.offsetFloats;
                    for (let c = 0; c < item.components; ++c) {
                        if (c < size && src + (c + 1) * elementBytes <=
                                block.data.byteLength) {
                            packed[dst + c] = readComponent(view,
                                src + c * elementBytes, block.type, normalized);
                        } else {
                            packed[dst + c] = c === 3 ? 1 : 0;
                        }
                    }
                }
            }

            const slice = this.uploadVertices(new Uint8Array(packed.buffer));
            if (!slice) return;
            const buffers = [{
                gpuBuffer: slice.buffer,
                baseOffset: slice.offset,
                stride: stride * 4,
                attributes: layout.map(item => ({
                    location: item.location,
                    format: "float32" + (item.components > 1 ?
                        "x" + item.components : ""),
                    offset: item.offsetFloats * 4,
                })),
            }];

            let index = null;
            if (drawIndexInfo && drawIndexInfo.data) {
                index = this.uploadIndices(mode, drawIndexInfo.type, drawIndexInfo.data,
                    count, drawIndexInfo.decoded);
                if (!index) return;
            }
            this.issueDraw({ mode, vertexCount: count, buffers, index });
        },

        /* Which of the two aliased slots this attribute's array actually
         * arrived in. `usable` differs between the packed and VBO paths, so
         * the caller decides what counts as present. */
        resolveAttributeSource(arrays, entry, usable) {
            if (!entry.alias || !arrays) return entry.source;
            if (usable(arrays[entry.source])) return entry.source;
            if (usable(arrays[entry.alias])) return entry.alias;
            return entry.source;
        },

        arrayIsNormalized(source, block) {
            if (source.indexOf("generic") === 0) return !!block.normalized;
            return source === "color" || source === "secondaryColor" ||
                source === "normal";
        },

        currentAttributeValue(source, location) {
            const s = this.current;
            if (source === "color") return s.current.color;
            if (source === "secondaryColor") return s.current.secondaryColor;
            if (source === "normal") return s.current.normal;
            if (source === "fogCoord") return [s.current.fogCoord];
            const tex = /^texCoord(\d+)$/.exec(source);
            if (tex) return s.current.texCoord[Number(tex[1])] || null;
            if (source.indexOf("generic") === 0) {
                const index = Number(source.substring(7));
                return s.genericAttribs[index] ? s.genericAttribs[index].value : null;
            }
            if (location >= 0 && location < s.genericAttribs.length)
                return s.genericAttribs[location].value;
            return null;
        },

        /* Which attributes the current pipeline wants, and where each comes
         * from in the packed draw record. */
        wantedAttributes(program) {
            const ATTR = translator.COMPAT_ATTRIBUTE_LOCATIONS;
            if (program && program.link) {
                return program.link.reflection.attributes.map(a => ({
                    location: a.location,
                    components: a.components,
                    source: attributeSourceName(a.name, a.location),
                }));
            }
            const s = this.current;
            if (s.enabled.has(GL.VERTEX_PROGRAM_ARB)) {
                const arb = this.arbProgramFor(GL.VERTEX_PROGRAM_ARB);
                if (arb && arb.compiled && arb.compiled.ok) {
                    return arb.compiled.reflection.attributes.map(a => {
                        const source = attributeSourceName(a.name || a.field,
                            a.location);
                        // Only the ARB path carries an alias: GL defines the
                        // aliasing for vertex program mode, and a GLSL program
                        // names its own attributes.
                        return { location: a.location,
                                 components: a.components, source,
                                 alias: aliasedAttributeSource(source) };
                    });
                }
            }
            /* Derive the fixed-function input layout from the same signature
             * that generates VSIn. Warcraft keeps several client arrays
             * enabled across unlit UI passes; consulting those enables in the
             * shader but semantic state here made VSIn require location 2
             * while the vertex layout omitted it, invalidating the pipeline.
             * One signature is now authoritative for both sides. */
            const attributes = this.fixedFunctionSignature(
                this.currentVariant()).attributes;
            const wanted = [{ location: ATTR.gl_Vertex, components: 4,
                              source: "vertex" }];
            if (attributes.color)
                wanted.push({ location: ATTR.gl_Color, components: 4,
                              source: "color" });
            if (attributes.normal)
                wanted.push({ location: ATTR.gl_Normal, components: 3,
                              source: "normal" });
            if (attributes.secondaryColor)
                wanted.push({ location: ATTR.gl_SecondaryColor, components: 4,
                              source: "secondaryColor" });
            if (attributes.fogCoord)
                wanted.push({ location: ATTR.gl_FogCoord, components: 1,
                              source: "fogCoord" });
            for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit) {
                if (!attributes.texCoord[unit]) continue;
                wanted.push({ location: ATTR.gl_MultiTexCoord0 + unit,
                              components: attributes.texCoord[unit].components,
                              source: "texCoord" + unit });
            }
            return wanted;
        },

        /* ---- VBO-resident draws ---- */

        drawFromBuffers(mode, first, count, indexInfo) {
            if (count <= 0) return;
            const s = this.current;
            if (indexInfo && mode === GL.POINTS &&
                    (s.point.size !== 1 || s.enabled.has(GL.POINT_SPRITE)))
                return this.drawFromShadowBuffers(mode, first, count, indexInfo,
                    this.wantedAttributes(this.currentProgramObject()));
            const program = this.currentProgramObject();
            const wanted = this.wantedAttributes(program);
            const buffers = [];
            const byBuffer = new Map();
            const constants = [];

            for (const entry of wanted) {
                const source = this.resolveAttributeSource(s.arrays, entry,
                    a => !!(a && a.enabled && a.buffer));
                const array = s.arrays && s.arrays[source];
                if (!array || !array.enabled || !array.buffer) {
                    const value = this.currentAttributeValue(source,
                        entry.location);
                    if (value) {
                        constants.push({ entry, value });
                        continue;
                    }
                    return this.drawFromShadowBuffers(mode, first, count,
                        indexInfo, wanted);
                }
                const buffer = s.shareGroup.buffers.get(array.buffer);
                if (!buffer || !buffer.gpuBuffer) continue;
                const size = Math.max(1, array.size || entry.components);
                const normalized = this.arrayIsNormalized(source, array);
                const format = vertexFormatFor(array.type, size, normalized);
                const stride = array.stride ||
                    size * componentBytes(array.type);
                const shaderComponents = entry.components || size;
                const attributeBytes = size * componentBytes(array.type);
                /*
                 * GL widens a size-2/3 array to the four-component attribute
                 * consumed by an ARB program, supplying (0, 1) for the absent
                 * components. WebGPU vertex formats do not perform that GL
                 * conversion, and their attribute offset must describe one
                 * element inside arrayStride. Pack these legal GL layouts from
                 * the buffer's shadow copy instead of creating a mismatched or
                 * invalid WebGPU vertex layout. The glview 1.5 test uses vec3
                 * positions and vec2 texture coordinates with vec4 ARB inputs.
                 */
                if (!format || stride % 4 !== 0 || array.offset % 4 !== 0 ||
                        (s.enabled.has(GL.VERTEX_PROGRAM_ARB) &&
                            size !== shaderComponents) ||
                        array.offset >= stride ||
                        array.offset + attributeBytes > stride) {
                    const converted = this.convertVertexAttribute(buffer,
                        array, shaderComponents, normalized);
                    if (!converted)
                        return this.drawFromShadowBuffers(mode, first, count,
                            indexInfo, wanted);
                    buffers.push({ gpuBuffer: converted, baseOffset: 0,
                        stride: shaderComponents * 4, attributes: [{
                            location: entry.location, offset: 0,
                            format: "float32" + (shaderComponents > 1 ?
                                "x" + shaderComponents : ""),
                        }] });
                    continue;
                }
                let group = byBuffer.get(buffer.gpuBuffer);
                if (!group) {
                    group = { gpuBuffer: buffer.gpuBuffer, stride,
                              baseOffset: 0, attributes: [] };
                    byBuffer.set(buffer.gpuBuffer, group);
                    buffers.push(group);
                }
                if (group.stride !== stride) {
                    // Two arrays in one buffer with different strides need two
                    // bindings; WebGPU allows eight, which is enough in
                    // practice, and packing covers the rest.
                    const extra = { gpuBuffer: buffer.gpuBuffer, stride,
                                    baseOffset: 0, attributes: [] };
                    buffers.push(extra);
                    extra.attributes.push({ location: entry.location, format,
                                            offset: array.offset });
                    continue;
                }
                group.attributes.push({ location: entry.location, format,
                                        offset: array.offset });
            }

            if (constants.length) {
                let components = 0;
                for (const item of constants)
                    components += item.entry.components || item.value.length;
                const data = new Float32Array(components);
                const attributes = [];
                let at = 0;
                for (const item of constants) {
                    const count = item.entry.components || item.value.length;
                    for (let c = 0; c < count; ++c)
                        data[at + c] = c < item.value.length ? item.value[c] :
                            (c === 3 ? 1 : 0);
                    attributes.push({ location: item.entry.location,
                        format: "float32" + (count > 1 ? "x" + count : ""),
                        offset: at * 4 });
                    at += count;
                }
                const slice = this.uploadVertices(new Uint8Array(data.buffer));
                if (!slice) return;
                buffers.push({ gpuBuffer: slice.buffer,
                    baseOffset: slice.offset, stride: components * 4,
                    stepMode: "instance", attributes });
            }

            if (!buffers.length)
                return this.drawFromShadowBuffers(mode, first, count, indexInfo,
                    wanted);
            const maxBuffers = (this.limits && this.limits.maxVertexBuffers) || 8;
            if (buffers.length > maxBuffers)
                return this.drawFromShadowBuffers(mode, first, count, indexInfo,
                    wanted);

            let index = null;
            if (indexInfo) {
                const buffer = s.shareGroup.buffers.get(s.elementArrayBuffer);
                if (!buffer || !buffer.shadow)
                    return this.refuse("glDrawElements",
                        "no element array buffer is bound", {},
                        GL.INVALID_OPERATION);
                const elementBytes = indexInfo.type === GL.UNSIGNED_BYTE ? 1 :
                    (indexInfo.type === GL.UNSIGNED_SHORT ? 2 : 4);
                const data = buffer.shadow.subarray(indexInfo.bufferOffset,
                    indexInfo.bufferOffset + count * elementBytes);
                // Strips use WebGPU's fixed restart index, unlike legacy GL;
                // keep their widening/expansion path. Polygon line/point mode
                // also needs a CPU source index array to build its edges.
                const direct = (mode === GL.TRIANGLES || mode === GL.LINES ||
                    mode === GL.POINTS) && this.effectivePolygonMode() === GL.FILL &&
                    (indexInfo.type === GL.UNSIGNED_SHORT ||
                        indexInfo.type === GL.UNSIGNED_INT) &&
                    indexInfo.bufferOffset % elementBytes === 0 &&
                    data.byteLength === count * elementBytes && buffer.gpuBuffer;
                index = direct ? { buffer: buffer.gpuBuffer,
                    offset: indexInfo.bufferOffset, count,
                    format: elementBytes === 2 ? "uint16" : "uint32" } :
                    this.uploadIndices(mode, indexInfo.type, data, count);
                if (!index) return;
            }
            this.issueDraw({ mode, vertexCount: count, firstVertex: first,
                             buffers, index });
        },

        invalidateVertexConversions(buffer) {
            if (!buffer.convertedAttributes) return;
            for (const entry of buffer.convertedAttributes.values()) {
                this.convertedVertexCache.delete(entry);
                this.convertedVertexBytes -= entry.bytes;
                this.retire(entry.gpuBuffer);
            }
            buffer.convertedAttributes.clear();
        },

        convertVertexAttribute(buffer, array, components, normalized) {
            const elementBytes = componentBytes(array.type);
            const size = Math.max(1, array.size || components);
            const stride = array.stride || size * elementBytes;
            if (!elementBytes || !stride || !buffer.shadow) return null;
            const key = [array.type, size, stride, array.offset, components,
                normalized ? 1 : 0].join(":");
            const cache = buffer.convertedAttributes ||
                (buffer.convertedAttributes = new Map());
            let entry = cache.get(key);
            if (entry) return entry.gpuBuffer;
            const count = Math.max(0, 1 + Math.floor((buffer.shadow.byteLength -
                array.offset - size * elementBytes) / stride));
            const bytes = count * components * 4;
            // Bound resident conversion storage, including many layout variants.
            // Oversized objects use the compact per-draw packing path instead.
            const budget = 64 * 1024 * 1024;
            if (!bytes || bytes > budget) return null;
            // Do not evict here: another attribute of the current, not yet
            // encoded draw may already reference an entry. Fall back safely
            // when full; mutation/deletion/context teardown releases entries.
            if (this.convertedVertexBytes + bytes > budget ||
                    this.convertedVertexCache.size >= 256) return null;
            const values = new Float32Array(count * components);
            const view = new DataView(buffer.shadow.buffer,
                buffer.shadow.byteOffset, buffer.shadow.byteLength);
            for (let v = 0; v < count; ++v)
                for (let c = 0; c < components; ++c)
                    values[v * components + c] = c < size ?
                        readComponent(view, array.offset + v * stride +
                            c * elementBytes, array.type, normalized) :
                        (c === 3 ? 1 : 0);
            const gpuBuffer = this.device.createBuffer({
                label: "GL converted attribute " + buffer.name, size: bytes,
                usage: BUFFER_USAGE_VERTEX | BUFFER_USAGE_COPY_DST,
            });
            this.device.queue.writeBuffer(gpuBuffer, 0, values.buffer, 0, bytes);
            entry = { gpuBuffer, bytes };
            cache.set(key, entry);
            this.convertedVertexCache.set(entry, true);
            this.convertedVertexBytes += bytes;
            return gpuBuffer;
        },

        /* The fallback when a VBO's layout is not something WebGPU can bind
         * directly: read it out of the shadow copy and pack, which is exactly
         * what the client-array path does. */
        drawFromShadowBuffers(mode, first, count, indexInfo, wanted) {
            const s = this.current;
            const arrays = Object.create(null);
            let arrayVertexCount = count;
            let indices = null;
            if (indexInfo) {
                const buffer = s.shareGroup.buffers.get(s.elementArrayBuffer);
                if (buffer && buffer.shadow) {
                    const elementBytes = indexInfo.type === GL.UNSIGNED_BYTE ? 1 :
                        (indexInfo.type === GL.UNSIGNED_SHORT ? 2 : 4);
                    indices = {
                        type: indexInfo.type,
                        data: buffer.shadow.subarray(indexInfo.bufferOffset,
                            indexInfo.bufferOffset + count * elementBytes),
                    };
                    const values = readIndices(indexInfo.type, indices.data, count);
                    indices.decoded = values;
                    arrayVertexCount = values.length ? maximumIndex(values) + 1 : 0;
                }
            }
            for (const entry of wanted) {
                const source = this.resolveAttributeSource(s.arrays, entry,
                    a => !!(a && a.enabled && a.buffer));
                const array = s.arrays && s.arrays[source];
                if (!array || !array.enabled) continue;
                const buffer = array.buffer ?
                    s.shareGroup.buffers.get(array.buffer) : null;
                if (!buffer || !buffer.shadow) continue;
                const size = Math.max(1, array.size || entry.components);
                const stride = array.stride || size * componentBytes(array.type);
                const start = array.offset + first * stride;
                arrays[source] = {
                    enabled: true, size, type: array.type, stride,
                    normalized: array.normalized,
                    data: buffer.shadow.subarray(start,
                        Math.min(buffer.shadow.byteLength,
                            start + arrayVertexCount * stride)),
                };
            }
            this.drawPacked(mode, count, arrays, indices);
        },

        /* ---- ring uploads ---- */

        rotateUploadPage(kind) {
            const vertex = kind === "vertex";
            const key = vertex ? "vertexRing" : "uniformRing";
            // A draw may already own slices from this page but not yet be
            // encoded. Neither overwrite nor retire it in an intermediate
            // flush; keep it until the draw/command has been fully recorded.
            this.uploadPages.push(this[key]);
            this[key] = this.device.createBuffer({
                label: vertex ? "GL vertex ring" : "GL uniform ring",
                size: vertex ? this.vertexCapacity : this.uniformCapacity,
                usage: BUFFER_USAGE_COPY_DST | (vertex ?
                    BUFFER_USAGE_VERTEX | BUFFER_USAGE_INDEX : BUFFER_USAGE_UNIFORM),
            });
            this[vertex ? "vertexCursor" : "uniformCursor"] = 0;
        },

        retireUploadPages() {
            if (!this.uploadPages.length) return false;
            for (const page of this.uploadPages) this.retire(page);
            this.uploadPages.length = 0;
            return true;
        },

        uploadVertices(bytes) {
            const size = alignUp(bytes.byteLength, 4);
            if (size > this.vertexCapacity) {
                this.refuse("draw", "vertex data exceeds the ring capacity",
                    { size, capacity: this.vertexCapacity }, GL.OUT_OF_MEMORY);
                return null;
            }
            if (this.vertexCursor + size > this.vertexCapacity)
                this.rotateUploadPage("vertex");
            const offset = this.vertexCursor;
            this.vertexStaging.set(bytes, offset);
            this.device.queue.writeBuffer(this.vertexRing, offset,
                this.vertexStaging, offset, size);
            this.vertexCursor = offset + size;
            return { buffer: this.vertexRing, offset, size };
        },

        /*
         * Index upload, including the expansion of the primitive modes WebGPU
         * does not have. The expanded index array for a given (mode, count) is
         * cached because a Half-Life frame issues thousands of GL_QUADS draws
         * whose index pattern depends on nothing but the vertex count.
         */
        uploadIndices(mode, type, data, count, decoded) {
            const source = decoded || readIndices(type, data, count);
            let indices;
            if (needsIndexExpansion(mode)) {
                indices = expandIndexArray(mode, source);
                ++this.stats.expandedIndices;
            } else {
                indices = source;
            }
            if (!indices.length) return null;
            const bytes = new Uint8Array(indices.buffer, indices.byteOffset,
                indices.byteLength);
            const slice = this.uploadVertices(bytes);
            if (!slice) return null;
            return { buffer: slice.buffer, offset: slice.offset, count: indices.length,
                     format: "uint32", cpu: indices, source };
        },

        /* Draw with no index buffer still needs one when the mode expands. */
        expansionIndices(mode, count) {
            const key = mode + ":" + count;
            let cached = this.indexExpansionCache.get(key);
            if (!cached) {
                cached = expandIndices(mode, count, 0);
                if (this.indexExpansionCache.size > 4096)
                    this.indexExpansionCache.clear();
                this.indexExpansionCache.set(key, cached);
            }
            return cached;
        },
    });

    /*
     * ARB_vertex_program section 2.14.3 aliases the conventional vertex
     * attributes onto generic slots 0-5 and 8-15: glVertexPointer's array and
     * glVertexAttribPointerARB(0, ...) name the same attribute, and a program
     * may spell it either way. The guest sends whichever the application used,
     * so an attribute has to accept its alias -- otherwise a program written
     * against vertex.position and fed generic attribute 0 read the generic
     * attribute's (0, 0, 0, 1) default for every vertex and drew nothing, with
     * no GL error to say why.
     */
    const GENERIC_ATTRIB_ALIAS = {
        vertex: 0, weight: 1, normal: 2, color: 3,
        secondaryColor: 4, fogCoord: 5,
    };
    for (let unit = 0; unit < MAX_TEXTURE_COORDS; ++unit)
        GENERIC_ATTRIB_ALIAS["texCoord" + unit] = 8 + unit;

    const CONVENTIONAL_ATTRIB_ALIAS = {};
    for (const name of Object.keys(GENERIC_ATTRIB_ALIAS))
        CONVENTIONAL_ATTRIB_ALIAS["generic" + GENERIC_ATTRIB_ALIAS[name]] = name;

    function aliasedAttributeSource(source) {
        if (source.indexOf("generic") === 0)
            return CONVENTIONAL_ATTRIB_ALIAS[source] || null;
        const index = GENERIC_ATTRIB_ALIAS[source];
        return index === undefined ? null : "generic" + index;
    }

    function attributeSourceName(name, location) {
        const ATTR_SOURCES = {
            gl_Vertex: "vertex", gl_Normal: "normal", gl_Color: "color",
            gl_SecondaryColor: "secondaryColor", gl_FogCoord: "fogCoord",
        };
        if (ATTR_SOURCES[name]) return ATTR_SOURCES[name];
        const texMatch = /^gl_MultiTexCoord(\d)$/.exec(name);
        if (texMatch) return "texCoord" + texMatch[1];
        // Generic arrays are selected by attribute index, not by the spelling
        // of the shader variable. glBindAttribLocation may assign any user name
        // to a location, while the guest record necessarily carries that index.
        return "generic" + location;
    }

    function vertexFormatFor(type, size, normalized) {
        if (normalized) {
            const table = DIRECT_NORMALIZED_FORMATS[type];
            return table ? table[size] || null : null;
        }
        const table = DIRECT_VERTEX_FORMATS[type];
        return table ? table[size] || null : null;
    }

    function readIndices(type, data, count) {
        const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
        const out = new Uint32Array(count);
        for (let i = 0; i < count; ++i) {
            switch (type) {
            case GL.UNSIGNED_BYTE:
                if (i < data.byteLength) out[i] = view.getUint8(i);
                break;
            case GL.UNSIGNED_SHORT:
                if (i * 2 + 2 <= data.byteLength) out[i] = view.getUint16(i * 2, true);
                break;
            default:
                if (i * 4 + 4 <= data.byteLength) out[i] = view.getUint32(i * 4, true);
                break;
            }
        }
        return out;
    }

    function maximumIndex(indices) {
        let maximum = 0;
        for (let i = 0; i < indices.length; ++i)
            if (indices[i] > maximum) maximum = indices[i];
        return maximum;
    }

    /* ================================================================== */
    /* Executor: pipeline state and the draw itself                       */
    /* ================================================================== */

    Object.assign(GLWebGPUExecutor.prototype, {

        /*
         * GL's front-face convention is inverted here and nowhere else.
         *
         * The vertex shader negates clip-space Y so that framebuffer row 0 is
         * GL's bottom row (plan 4.3); that flip reverses the winding of every
         * triangle, so GL_CCW has to be reported to WebGPU as "cw". Keeping
         * this in one function is deliberate: a second place that flips winding
         * would cancel this one out somewhere and nowhere else.
         */
        gpuFrontFace(state) {
            return state.frontFace === GL.CCW ? "cw" : "ccw";
        },

        gpuCullMode(state) {
            if (!state.enabled.has(GL.CULL_FACE)) return "none";
            if (state.cullFace === GL.FRONT_AND_BACK) return "none";  // see below
            return state.cullFace === GL.FRONT ? "front" : "back";
        },

        /* The set of render targets a draw writes, resolved from the bound
         * framebuffer. */
        currentTargets() {
            const s = this.current;
            if (!s.drawFramebuffer) {
                const view = this.ensureBackBuffer();
                return {
                    color: [{ view, format: this.backBufferFormat,
                              texture: this.backBuffer, mipLevel: 0,
                              origin: { x: 0, y: 0, z: 0 } }],
                    depth: this.ensureDepthTarget(),
                    depthFormat: "depth24plus-stencil8",
                    width: this.backBufferWidth, height: this.backBufferHeight,
                    isDefault: true,
                };
            }
            const fbo = this.framebuffers.get(s.id).get(s.drawFramebuffer);
            if (!fbo) return null;
            const color = [];
            for (const buffer of s.drawBuffers) {
                if (buffer === GL.NONE) { color.push(null); continue; }
                const index = buffer >= GL.COLOR_ATTACHMENT0 ?
                    buffer - GL.COLOR_ATTACHMENT0 : 0;
                const attachment = fbo.color[index];
                if (!attachment) { color.push(null); continue; }
                const resolved = this.resolveAttachment(attachment);
                color.push(resolved);
            }
            if (!color.length) color.push(null);
            // WebGPU exposes depth and stencil as one render-pass attachment.
            // A stencil-only FBO therefore still needs to supply that view.
            const depthRecord = fbo.depth || fbo.stencil;
            const depth = depthRecord ? this.resolveAttachment(depthRecord) : null;
            return {
                color,
                depth: depth ? depth.view : null,
                depthFormat: depth ? depth.format : null,
                width: fbo.width, height: fbo.height,
                isDefault: false,
            };
        },

        resolveAttachment(attachment) {
            if (attachment.kind === "texture") {
                const texture = this.current.shareGroup.textures.get(attachment.name);
                if (!texture) return null;
                const gpuTexture = this.ensureTextureUploaded(texture);
                if (!gpuTexture) return null;
                return {
                    view: gpuTexture.createView({
                        baseMipLevel: attachment.level, mipLevelCount: 1,
                        baseArrayLayer: attachment.layer, arrayLayerCount: 1,
                        dimension: "2d",
                    }),
                    format: texture.gpuFormat,
                    texture: gpuTexture,
                    mipLevel: attachment.level,
                    origin: { x: 0, y: 0, z: attachment.layer },
                };
            }
            const rb = this.current.shareGroup.renderbuffers.get(attachment.name);
            if (!rb || !rb.gpuTexture) return null;
            return { view: rb.gpuTexture.createView(), format: rb.gpuFormat,
                     texture: rb.gpuTexture, mipLevel: 0,
                     origin: { x: 0, y: 0, z: 0 } };
        },

        ensureBackBuffer() {
            const width = Math.max(1, this.backBufferWidth);
            const height = Math.max(1, this.backBufferHeight);
            if (this.backBuffer && this.backBufferView) return this.backBufferView;
            this.retire(this.backBuffer);
            this.backBufferFormat = (this.host && this.host.format) || "bgra8unorm";
            this.backBuffer = this.device.createTexture({
                label: "GL back buffer",
                size: { width, height, depthOrArrayLayers: 1 },
                format: this.backBufferFormat,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            this.backBufferView = this.backBuffer.createView();
            return this.backBufferView;
        },

        ensureDepthTarget() {
            const width = Math.max(1, this.backBufferWidth);
            const height = Math.max(1, this.backBufferHeight);
            if (this.depthTarget && this.depthWidth === width &&
                    this.depthHeight === height)
                return this.depthTargetView;
            this.retire(this.depthTarget);
            this.depthTarget = this.device.createTexture({
                label: "GL depth-stencil",
                size: { width, height, depthOrArrayLayers: 1 },
                format: "depth24plus-stencil8",
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT,
            });
            this.depthTargetView = this.depthTarget.createView();
            this.depthWidth = width;
            this.depthHeight = height;
            return this.depthTargetView;
        },

        /* ---- render pass management ----
         *
         * The pass is opened lazily so that a glClear arriving before the first
         * draw becomes a loadOp instead of a full-screen quad. That is the
         * shape of almost every GL frame, so the common case costs nothing.
         */
        ensureEncoder() {
            if (!this.encoder)
                this.encoder = this.device.createCommandEncoder({ label: "GL frame" });
            return this.encoder;
        },

        ensurePass() {
            if (this.activeQuery && this.activeQuery.slot < 0 &&
                    this.nextQuerySlot >= this.occlusionCapacity)
                this.flushFrame();
            if (this.pass) {
                this.beginOcclusionSegment();
                return this.pass;
            }
            const targets = this.currentTargets();
            if (!targets) return null;
            const encoder = this.ensureEncoder();
            const colorAttachments = targets.color.map(target => target ? {
                view: target.view,
                loadOp: this.pendingClear && this.pendingClear.color ?
                    "clear" : "load",
                clearValue: this.pendingClear && this.pendingClear.color ?
                    this.pendingClear.color : undefined,
                storeOp: "store",
            } : null);
            const descriptor = {
                label: "GL pass",
                colorAttachments,
            };
            if (targets.depth) {
                descriptor.depthStencilAttachment = {
                    view: targets.depth,
                    depthLoadOp: this.pendingClear && this.pendingClear.depth !== undefined ?
                        "clear" : "load",
                    depthClearValue: this.pendingClear && this.pendingClear.depth !== undefined ?
                        this.pendingClear.depth : undefined,
                    depthStoreOp: "store",
                    // WebGPU requires stencil operations to be absent when the
                    // attachment format has no stencil aspect.  Cube 2 uses a
                    // depth24 renderbuffer while generating environment maps;
                    // unconditionally adding these fields invalidates the
                    // complete command encoder at finish().
                    ...(formatHasStencil(targets.depthFormat) ? {
                        stencilLoadOp: this.pendingClear &&
                            this.pendingClear.stencil !== undefined ?
                            "clear" : "load",
                        stencilClearValue: this.pendingClear &&
                            this.pendingClear.stencil !== undefined ?
                            this.pendingClear.stencil : undefined,
                        stencilStoreOp: "store",
                    } : {}),
                };
            }
            if (this.activeOcclusionQuerySet)
                descriptor.occlusionQuerySet = this.activeOcclusionQuerySet;
            // A pass can only run occlusion queries if it was *created* with
            // the query set, so beginQuery has to know whether this one was.
            this.passHasOcclusionQuerySet = !!this.activeOcclusionQuerySet;
            this.pass = encoder.beginRenderPass(descriptor);
            this.passTargets = targets;
            this.pendingClear = null;
            this.passStateApplied = false;
            this.beginOcclusionSegment();
            return this.pass;
        },

        endPass() {
            if (this.pass) {
                this.endOcclusionSegment();
                this.pass.end();
                this.pass = null;
                this.passTargets = null;
                this.passHasOcclusionQuerySet = false;
            }
        },

        flushFrame() {
            this.endPass();
            // finishFrame may rewind the rings after this submission.
            this.uniformValueCache.clear();
            this.bindGroupCache.clear();
            const resolved = this.resolvePendingQueries();
            if (this.encoder) {
                this.device.queue.submit([this.encoder.finish()]);
                this.encoder = null;
                this.recordedOps = 0;
                this.pendingVertexBuffers = new WeakSet();
                this.releaseRetired();
            }
            if (resolved) this.readQueryResults(resolved);
        },

        /*
         * Occlusion results only exist after the GPU has run the pass, so they
         * follow glReadPixels' shape: resolve into a buffer alongside the work
         * that produced them, then map it once the submission lands. Until the
         * map completes glGetQueryObjectuiv keeps answering NOT AVAILABLE,
         * which is what the guest's own spin on GL_QUERY_RESULT_AVAILABLE is
         * waiting for -- so a query that is never resolved is not a stale
         * number, it is a guest that spins forever.
         *
         * Every query outstanding at the flush resolves in one pair of buffers.
         * Cube 2 retires two thousand of them at a time, and one resolve of
         * slots [0, high] costs the same as one of slot 3.
         */
        resolvePendingQueries() {
            const pending = this.pendingQueries;
            if (!pending || !pending.length || !this.activeOcclusionQuerySet)
                return null;
            this.pendingQueries = [];
            let high = 0;
            for (const record of pending)
                if (record.slot >= 0 && record.slot + 1 > high)
                    high = record.slot + 1;
            if (!high) return null;
            // resolveQuerySet writes a u64 per slot; a mapped buffer cannot
            // also be a resolve target, hence the copy into staging.
            const byteLength = alignUp(high * 8, 256);
            const resolveBuffer = this.device.createBuffer({
                label: "GL occlusion resolve",
                size: byteLength,
                usage: BUFFER_USAGE_QUERY_RESOLVE | BUFFER_USAGE_COPY_SRC,
            });
            const staging = this.device.createBuffer({
                label: "GL occlusion readback",
                size: byteLength,
                usage: BUFFER_USAGE_COPY_DST | BUFFER_USAGE_MAP_READ,
            });
            const encoder = this.ensureEncoder();
            encoder.resolveQuerySet(this.activeOcclusionQuerySet, 0, high,
                resolveBuffer, 0);
            encoder.copyBufferToBuffer(resolveBuffer, 0, staging, 0, byteLength);
            // The slots are free again for the next frame's queries; the
            // results are already on their way out of the set.
            this.nextQuerySlot = 0;
            return { queries: pending, resolveBuffer, staging, count: high };
        },

        readQueryResults(resolved) {
            const { queries, resolveBuffer, staging } = resolved;
            this.trackReadback(staging.mapAsync(1 /* GPUMapMode.READ */).then(() => {
                const words = new Uint32Array(staging.getMappedRange().slice(0));
                staging.unmap();
                for (const record of queries) {
                    const { query, slot, generation } = record;
                    // Query names are deliberately recycled every couple of
                    // frames by Cube 2. Mapping is asynchronous, so an older
                    // readback may finish after the same object has started a
                    // newer query. Never publish that stale generation into
                    // the new one (which can otherwise cull visible geometry).
                    if (query.generation !== generation) continue;
                    const low = words[slot * 2];
                    const high = words[slot * 2 + 1];
                    // D-07: WebGPU answers "did any sample pass", not how many.
                    // A visible query reports a saturated count rather than 1,
                    // because callers threshold on it far more often than they
                    // compare it to an expected sample total.
                    const visible = !!(low || high);
                    this.completeOcclusionSegment(record,
                        visible ? OCCLUSION_VISIBLE_SAMPLES : 0);
                }
            }).catch(error => {
                this.warnOnce("occlusion", "occlusion query readback failed",
                    { message: String(error) });
                // Never leave the guest spinning on AVAILABLE for a result the
                // GPU will not deliver.  A failed readback contains no evidence
                // of occlusion, so the only rendering-safe fallback is visible.
                for (const record of queries) {
                    const { query, generation } = record;
                    if (query.generation !== generation) continue;
                    this.completeOcclusionSegment(record, OCCLUSION_VISIBLE_SAMPLES);
                }
            }).then(() => {
                try { staging.destroy(); } catch (ignored) { /* already gone */ }
                try { resolveBuffer.destroy(); } catch (ignored) { /* gone */ }
            }));
        },

        finishFrame(present) {
            this.endPass();
            if (present) this.presentToCanvas();
            this.flushFrame();
            this.vertexCursor = 0;
            this.uniformCursor = 0;
        },

        /*
         * glClear. An unrestricted clear becomes the next pass's load
         * operation. Scissor and write masks cannot be represented by loadOp,
         * so those cases use a full-screen triangle with exact colour, depth
         * and stencil write masks.
         */
        clearBuffers(mask) {
            const s = this.current;
            const gpuMask = mask & (GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT |
                GL.STENCIL_BUFFER_BIT);
            const maskedColor = !!(mask & GL.COLOR_BUFFER_BIT) &&
                s.colorMask.some(value => !value);
            const maskedDepth = !!(mask & GL.DEPTH_BUFFER_BIT) && !s.depthMask;
            const maskedStencil = !!(mask & GL.STENCIL_BUFFER_BIT) &&
                (s.stencil.front.writeMask >>> 0) !== 0xffffffff;
            if (gpuMask && ((s.enabled.has(GL.SCISSOR_TEST) && s.scissor.set) ||
                    maskedColor || maskedDepth || maskedStencil)) {
                if (mask & GL.ACCUM_BUFFER_BIT) this.clearAccumBuffer();
                this.clearBuffersWithDraw(gpuMask);
                return;
            }
            const pending = this.pendingClear || {};
            if (mask & GL.COLOR_BUFFER_BIT) {
                pending.color = {
                    r: s.clearColor[0], g: s.clearColor[1],
                    b: s.clearColor[2], a: s.clearColor[3],
                };
            }
            if (mask & GL.DEPTH_BUFFER_BIT) pending.depth = s.clearDepth;
            if (mask & GL.STENCIL_BUFFER_BIT) pending.stencil = s.clearStencil;
            if (mask & GL.ACCUM_BUFFER_BIT) this.clearAccumBuffer();
            if (!(mask & (GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT |
                    GL.STENCIL_BUFFER_BIT)))
                return;
            this.endPass();
            this.pendingClear = pending;
            // Opening the pass immediately makes the clear happen even if no
            // draw follows, which is what a frame that only clears expects.
            this.ensurePass();
        },

        clearBuffersWithDraw(mask) {
            const s = this.current;
            this.endPass();
            const targets = this.currentTargets();
            if (!targets) return;
            const clearColor = !!(mask & GL.COLOR_BUFFER_BIT);
            const clearDepth = !!(mask & GL.DEPTH_BUFFER_BIT) && s.depthMask &&
                !!targets.depth;
            const clearStencil = !!(mask & GL.STENCIL_BUFFER_BIT) &&
                (s.stencil.front.writeMask >>> 0) !== 0 && !!targets.depth &&
                targets.depthFormat && targets.depthFormat.indexOf("stencil") >= 0;
            if (!clearColor && !clearDepth && !clearStencil) return;
            const pipeline = this.clearPipeline(targets, clearColor, clearDepth,
                clearStencil);
            if (!pipeline) return;
            const pass = this.ensureEncoder().beginRenderPass({
                label: "GL masked/scissored clear",
                colorAttachments: targets.color.map(target => target ? {
                    view: target.view, loadOp: "load", storeOp: "store",
                } : null),
                ...(targets.depth ? { depthStencilAttachment: {
                    view: targets.depth,
                    depthLoadOp: "load", depthStoreOp: "store",
                    ...(formatHasStencil(targets.depthFormat) ? {
                        stencilLoadOp: "load", stencilStoreOp: "store",
                    } : {}),
                } } : {}),
            });
            this.applyAccumScissor(pass, targets);
            if (clearStencil) pass.setStencilReference(s.clearStencil >>> 0);
            pass.setPipeline(pipeline);
            pass.draw(3, 1, 0, 0);
            pass.end();
        },

        clearPipeline(targets, clearColor, clearDepth, clearStencil) {
            const s = this.current;
            const colorFormats = targets.color.map(target => target ?
                target.format : "-").join(",");
            const key = [colorFormats, targets.depthFormat || "-",
                clearColor ? s.colorMask.map(v => v ? 1 : 0).join("") : "-",
                clearDepth ? 1 : 0, clearStencil ?
                    (s.stencil.front.writeMask >>> 0) : 0,
                [...s.clearColor], s.clearDepth].join("|");
            this.clearPipelineCache = this.clearPipelineCache || new Map();
            let pipeline = this.clearPipelineCache.get(key);
            if (pipeline) return pipeline;
            const colorFields = clearColor ? targets.color.map((target, i) =>
                target ? "    @location(" + i + ") color" + i +
                    " : vec4<f32>," : "").join("\n") : "";
            const depthField = clearDepth ?
                "    @builtin(frag_depth) depth : f32," : "";
            const colorWrites = clearColor ? targets.color.map((target, i) =>
                target ? "    out.color" + i + " = vec4<f32>(" +
                    Array.from(s.clearColor).map(v => Number(v).toPrecision(9))
                        .join(", ") + ");" : "").join("\n") : "";
            const depthWrite = clearDepth ? "    out.depth = " +
                Number(s.clearDepth).toPrecision(9) + ";" : "";
            const fragmentCode = colorFields || depthField ? `
struct ClearOut {
${colorFields}
${depthField}
}
@fragment fn fs_main() -> ClearOut {
    var out : ClearOut;
${colorWrites}
${depthWrite}
    return out;
}` : "@fragment fn fs_main() {}";
            const code = `
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
${fragmentCode}`;
            const module = this.shaderModule(code);
            const descriptor = {
                label: "GL clear pipeline",
                layout: "auto",
                vertex: { module, entryPoint: "vs_main" },
                fragment: { module, entryPoint: "fs_main",
                    targets: targets.color.map(target => target ? {
                        format: target.format,
                        writeMask: clearColor ?
                            (s.colorMask[0] ? 1 : 0) |
                            (s.colorMask[1] ? 2 : 0) |
                            (s.colorMask[2] ? 4 : 0) |
                            (s.colorMask[3] ? 8 : 0) : 0,
                    } : null) },
                primitive: { topology: "triangle-list" },
            };
            if (targets.depthFormat) {
                descriptor.depthStencil = {
                    format: targets.depthFormat,
                    depthWriteEnabled: clearDepth,
                    depthCompare: "always",
                    ...(clearStencil ? {
                        stencilFront: { compare: "always", failOp: "keep",
                            depthFailOp: "keep", passOp: "replace" },
                        stencilBack: { compare: "always", failOp: "keep",
                            depthFailOp: "keep", passOp: "replace" },
                        stencilReadMask: 0xffffffff,
                        stencilWriteMask: s.stencil.front.writeMask >>> 0,
                    } : {}),
                };
            }
            try {
                pipeline = this.device.createRenderPipeline(descriptor);
            } catch (error) {
                this.refuse("glClear", "could not create masked clear pipeline",
                    { message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.clearPipelineCache.set(key, pipeline);
            return pipeline;
        },

        clearAccumBuffer() {
            this.endPass();
            const targets = this.currentTargets();
            if (!targets) return;
            const accum = this.ensureAccumBuffer(targets);
            const scissored = this.current.enabled.has(GL.SCISSOR_TEST) &&
                this.current.scissor.set;
            const pass = this.ensureEncoder().beginRenderPass({
                label: "GL accumulation clear",
                colorAttachments: [{
                    view: accum.currentView,
                    loadOp: scissored ? "load" : "clear",
                    clearValue: {
                        r: this.current.clearAccum[0],
                        g: this.current.clearAccum[1],
                        b: this.current.clearAccum[2],
                        a: this.current.clearAccum[3],
                    },
                    storeOp: "store",
                }],
            });
            this.applyAccumScissor(pass, targets);
            if (scissored) {
                const pipeline = this.accumClearPipeline();
                if (pipeline) {
                    pass.setPipeline(pipeline);
                    pass.draw(3, 1, 0, 0);
                }
            }
            pass.end();
        },

        /* ---- the draw ---- */

        issueDraw(request) {
            const s = this.current;
            if (s.renderMode !== GL.RENDER) return;   // GL_SELECT/GL_FEEDBACK
            if (s.enabled.has(GL.CULL_FACE) && s.cullFace === GL.FRONT_AND_BACK)
                return;
            let index = request.index;
            if (isPolygonPrimitive(request.mode)) {
                const rasterMode = this.effectivePolygonMode();
                if (rasterMode === GL.LINE || rasterMode === GL.POINT) {
                    const rasterIndices = polygonRasterIndices(request.mode,
                        request.vertexCount, index && index.source, rasterMode);
                    if (!rasterIndices.length) return;
                    const slice = this.uploadVertices(new Uint8Array(
                        rasterIndices.buffer, rasterIndices.byteOffset,
                        rasterIndices.byteLength));
                    if (!slice) return;
                    index = { buffer: slice.buffer, offset: slice.offset,
                        count: rasterIndices.length,
                        format: "uint32", cpu: rasterIndices };
                    request = { ...request,
                        mode: rasterMode === GL.LINE ? GL.LINES : GL.POINTS };
                }
            }
            this.drawingPoints = request.mode === GL.POINTS;
            if (s.enabled.has(GL.STENCIL_TEST) && stencilMasksDiverge(s))
                this.warnOnce("stencil-masks",
                    "the front and back stencil masks differ; WebGPU has one " +
                    "pair for both faces, so the front face's are used " +
                    "(deviation D-02)", { front: s.stencil.front,
                                          back: s.stencil.back });
            const shaders = this.resolveShaders();
            if (!shaders) return;
            if (s.enabled.has(GL.COLOR_LOGIC_OP) && s.logicOp !== GL.COPY &&
                    !this.prepareLogicOpTargets()) return;
            if (!this.ensurePass()) {
                this.refuse("draw", "no render target is bound", {},
                    GL.INVALID_FRAMEBUFFER_OPERATION);
                return;
            }

            /* WebGPU only rasterises one-pixel points. GL point size and point
             * sprites are implemented as an instanced six-vertex quad: the
             * application's attributes advance once per point, while this
             * extra corner attribute advances for the six quad vertices. */
            const expandedPoints = request.mode === GL.POINTS && !index &&
                (s.point.size !== 1 || s.enabled.has(GL.POINT_SPRITE));
            if (expandedPoints) {
                const corners = new Float32Array([
                    -1, -1,  1, -1, -1,  1,
                    -1,  1,  1, -1,  1,  1,
                ]);
                const cornerSlice = this.uploadVertices(
                    new Uint8Array(corners.buffer));
                if (!cornerSlice) return;
                request = {
                    ...request,
                    expandedPoints: true,
                    buffers: request.buffers.map(buffer => ({
                        ...buffer,
                        stepMode: "instance",
                    })).concat([{
                        gpuBuffer: cornerSlice.buffer,
                        baseOffset: cornerSlice.offset,
                        stride: 8,
                        stepMode: "vertex",
                        attributes: [{
                            location: translator.POINT_CORNER_LOCATION,
                            format: "float32x2",
                            offset: 0,
                        }],
                    }]),
                };
            }

            if (!index && needsIndexExpansion(request.mode)) {
                const expanded = this.expansionIndices(request.mode,
                    request.vertexCount);
                if (!expanded.length) return;
                const slice = this.uploadVertices(new Uint8Array(expanded.buffer,
                    expanded.byteOffset, expanded.byteLength));
                if (!slice) return;
                index = { buffer: slice.buffer, offset: slice.offset,
                          count: expanded.length,
                          format: "uint32", cpu: expanded };
            }

            const pipeline = this.ensurePipeline(shaders, request, index);
            if (!pipeline) return;
            const bindGroups = this.buildBindGroups(pipeline, shaders);
            if (!bindGroups) return;

            // Texture preparation may have split the pass. Always bind to
            // the current pass after all uploads and resource preparation.
            const pass = this.ensurePass();
            if (!pass) return;
            pass.setPipeline(pipeline);
            this.applyPassState(pass);
            for (const entry of bindGroups)
                pass.setBindGroup(entry.index, entry.group);
            request.buffers.forEach((buffer, i) => {
                pass.setVertexBuffer(i, buffer.gpuBuffer, buffer.baseOffset);
                this.pendingVertexBuffers.add(buffer.gpuBuffer);
            });
            if (index) {
                pass.setIndexBuffer(index.buffer, index.format, index.offset);
                this.pendingVertexBuffers.add(index.buffer);
                pass.drawIndexed(index.count, 1, 0, request.firstVertex || 0, 0);
            } else if (expandedPoints) {
                pass.draw(6, request.vertexCount, 0, request.firstVertex || 0);
            } else {
                pass.draw(request.vertexCount, 1, request.firstVertex || 0, 0);
            }
            ++this.stats.draws;
            ++this.recordedOps;
            if (this.retireUploadPages() || this.recordedOps >= this.flushThreshold) {
                // A frame's draw count is unbounded; flushing keeps both the
                // command buffer and the ring allocations proportional to work
                // done rather than to the frame's length.
                this.endPass();
                this.flushFrame();
            }
        },

        applyPassState(pass) {
            const s = this.current;
            const targets = this.passTargets;
            const width = targets ? targets.width : this.backBufferWidth;
            const height = targets ? targets.height : this.backBufferHeight;
            const vp = s.viewport;
            const x = clamp(vp.x, 0, width);
            const y = clamp(vp.y, 0, height);
            pass.setViewport(x, y,
                Math.max(0, Math.min(vp.width, width - x)),
                Math.max(0, Math.min(vp.height, height - y)),
                s.depthRange.near, s.depthRange.far);
            if (s.enabled.has(GL.SCISSOR_TEST) && s.scissor.set) {
                const sx = clamp(s.scissor.x, 0, width);
                const sy = clamp(s.scissor.y, 0, height);
                pass.setScissorRect(sx, sy,
                    Math.max(0, Math.min(s.scissor.width, width - sx)),
                    Math.max(0, Math.min(s.scissor.height, height - sy)));
            } else {
                pass.setScissorRect(0, 0, width, height);
            }
            if (s.enabled.has(GL.STENCIL_TEST))
                pass.setStencilReference(s.stencil.front.ref >>> 0);
            if (s.enabled.has(GL.BLEND))
                pass.setBlendConstant({
                    r: s.blend.color[0], g: s.blend.color[1],
                    b: s.blend.color[2], a: s.blend.color[3],
                });
        },

        prepareLogicOpTargets() {
            // Consume a pending loadOp clear before taking the destination
            // snapshot, then continue in a second pass that samples only the
            // copy. Sampling the live attachment would be a WebGPU feedback
            // loop and is rejected by validation.
            const initialPass = this.ensurePass();
            if (!initialPass) {
                this.refuse("draw", "no render target is bound", {},
                    GL.INVALID_FRAMEBUFFER_OPERATION);
                return false;
            }
            this.endPass();
            const targets = this.currentTargets();
            if (!targets) return false;
            const width = Math.max(1, targets.width);
            const height = Math.max(1, targets.height);
            this.logicTargetTextures = this.logicTargetTextures || [];
            this.logicTargetViews = [];
            const encoder = this.ensureEncoder();
            let fallbackView = null;
            for (let i = 0; i < targets.color.length; ++i) {
                const source = targets.color[i];
                if (!source || !source.texture) {
                    this.logicTargetViews.push(fallbackView || this.fallbackView);
                    continue;
                }
                let copy = this.logicTargetTextures[i];
                const key = source.format + ":" + width + "x" + height;
                if (!copy || copy.glLogicKey !== key) {
                    this.retire(copy);
                    copy = this.device.createTexture({
                        label: "GL logic-op destination copy " + i,
                        size: { width, height, depthOrArrayLayers: 1 },
                        format: source.format,
                        usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
                    });
                    copy.glLogicKey = key;
                    this.logicTargetTextures[i] = copy;
                }
                encoder.copyTextureToTexture({
                    texture: source.texture,
                    mipLevel: source.mipLevel || 0,
                    origin: source.origin || { x: 0, y: 0, z: 0 },
                }, { texture: copy },
                { width, height, depthOrArrayLayers: 1 });
                const view = copy.createView();
                if (!fallbackView) fallbackView = view;
                this.logicTargetViews.push(view);
            }
            if (fallbackView) {
                for (let i = 0; i < this.logicTargetViews.length; ++i)
                    if (this.logicTargetViews[i] === this.fallbackView)
                        this.logicTargetViews[i] = fallbackView;
            }
            return true;
        },

        effectivePolygonMode() {
            const s = this.current;
            const front = s.polygonMode.front;
            const back = s.polygonMode.back;
            if (front === back) return front;
            if (s.enabled.has(GL.CULL_FACE)) {
                if (s.cullFace === GL.FRONT) return back;
                if (s.cullFace === GL.BACK) return front;
            }
            this.warnOnce("two-face-polygon-mode",
                "front and back polygon modes differ without face culling; " +
                "the front mode is used for both faces",
                { front, back });
            return front;
        },
    });

    /* ================================================================== */
    /* Executor: shader selection, pipelines and bind groups              */
    /* ================================================================== */

    Object.assign(GLWebGPUExecutor.prototype, {

        /* The pipeline variant state GL still applies around a programmable
         * pipeline: alpha test, user clip planes, point sprites, two-sided
         * colour and flat shading all change the generated WGSL. */
        currentVariant() {
            const s = this.current;
            let clipPlaneCount = 0;
            for (let i = 0; i < MAX_CLIP_PLANES; ++i)
                if (s.enabled.has(GL.CLIP_PLANE0 + i)) clipPlaneCount = i + 1;
            return {
                alphaTest: s.enabled.has(GL.ALPHA_TEST) ?
                    (ALPHA_TEST_NAMES[s.alphaFunc.func] || "always") : "always",
                clipPlaneCount,
                pointSprite: this.drawingPoints &&
                    (s.enabled.has(GL.POINT_SPRITE) || s.point.size !== 1),
                pointCoordLowerLeft:
                    s.point.spriteCoordOrigin === GL.LOWER_LEFT,
                polygonStipple: s.enabled.has(GL.POLYGON_STIPPLE),
                logicOp: s.enabled.has(GL.COLOR_LOGIC_OP) ? s.logicOp : 0,
                twoSided: s.lightModel.twoSide,
                flatShading: s.shadeModel === GL.FLAT,
                colorTargets: this.colorTargetCount(),
            };
        },

        colorTargetCount() {
            const s = this.current;
            if (!s.drawFramebuffer) return 1;
            return Math.max(1, s.drawBuffers.length);
        },

        arbShaders() {
            const s = this.current;
            const vertexOn = s.enabled.has(GL.VERTEX_PROGRAM_ARB);
            const fragmentOn = s.enabled.has(GL.FRAGMENT_PROGRAM_ARB);
            if (!vertexOn && !fragmentOn) return null;
            if (s.enabled.has(GL.COLOR_LOGIC_OP)) {
                this.refuse("draw", "colour logic operations cannot be injected " +
                    "into an ARB assembly fragment program", { op: s.logicOp }, 0);
                return null;
            }
            const vertex = vertexOn ? this.arbProgramFor(GL.VERTEX_PROGRAM_ARB) : null;
            const fragment = fragmentOn ?
                this.arbProgramFor(GL.FRAGMENT_PROGRAM_ARB) : null;
            if ((vertexOn && (!vertex || !vertex.compiled || !vertex.compiled.ok)) ||
                    (fragmentOn && (!fragment || !fragment.compiled ||
                        !fragment.compiled.ok))) {
                this.refuse("draw", "an enabled ARB program has not compiled",
                    {}, GL.INVALID_OPERATION);
                return null;
            }
            if (vertexOn && !fragmentOn)
                return this.arbVertexFixedFragmentShaders(vertex);
            if (!vertexOn && fragmentOn) {
                this.refuse("draw", "a fixed vertex stage paired with an ARB " +
                    "fragment program is not implemented", {}, 0);
                return null;
            }
            const stateFields = [...new Set([
                ...vertex.compiled.reflection.stateFields,
                ...fragment.compiled.reflection.stateFields])];
            return {
                kind: "arb",
                key: "arb" + vertex.name + ":" + fragment.name,
                wgslVertex: vertex.compiled.wgsl,
                wgslFragment: fragment.compiled.wgsl,
                stateFields,
                stateFloats: stateLayout.buildLayout(stateFields).floats,
                uniformBytes: arbProgram.MAX_PROGRAM_PARAMETERS * 4 * 4 * 2,
                colorTargets: 1,
                arbVertex: vertex, arbFragment: fragment,
                textures: fragment.compiled.reflection.textures.map(entry => ({
                    unit: entry.unit,
                    textureBinding: entry.unit * 2,
                    samplerBinding: entry.unit * 2 + 1,
                    target: entry.target === "CUBE" ? "Cube" : entry.target,
                    shadow: false,
                })),
            };
        },

        arbVertexFixedFragmentShaders(vertex) {
            const variant = this.currentVariant();
            if (variant.clipPlaneCount || variant.pointSprite) {
                this.refuse("draw", "ARB vertex + fixed fragment does not yet " +
                    "support clip planes or point sprites",
                    { clipPlaneCount: variant.clipPlaneCount,
                      pointSprite: variant.pointSprite }, 0);
                return null;
            }

            const signature = this.fixedFunctionSignature(variant);
            signature.varyingInterface = "arb";
            // The two modules share one compact GLState block. Generate the
            // fixed stage with the ARB stage's fields included so every field
            // retains the same canonical byte offset in both modules.
            signature.extraStateFields =
                vertex.compiled.reflection.stateFields.slice();
            const fixedKey = fixedFunction.signatureKey(signature);
            let fixed = this.ffCache && this.ffCache.get(fixedKey);
            if (!fixed) {
                fixed = fixedFunction.generate(signature);
                this.ffCache = this.ffCache || new Map();
                this.ffCache.set(fixedKey, fixed);
            }

            const forcedTexCoords = fixed.textures.map(entry => entry.unit);
            const variantKey = fixed.key + "|tc=" + forcedTexCoords.join(",");
            vertex.variants = vertex.variants || new Map();
            let compiledVertex = vertex.variants.get(variantKey);
            if (!compiledVertex) {
                compiledVertex = arbProgram.compileARBProgram(vertex.source, {
                    forceStateFields: fixed.stateFields,
                    forceVertexTexCoords: forcedTexCoords,
                    forceFlatVaryings: variant.flatShading ? [0, 1] : [],
                });
                if (!compiledVertex.ok) {
                    this.refuse("draw", "the mixed ARB vertex variant failed " +
                        "to compile", { log: compiledVertex.log },
                        GL.INVALID_OPERATION);
                    return null;
                }
                vertex.variants.set(variantKey, compiledVertex);
            }

            return {
                kind: "arb",
                key: "arb-vp-ff:" + vertex.name + ":" + variantKey,
                wgslVertex: compiledVertex.wgsl,
                wgslFragment: fixed.wgslFragment,
                stateFields: fixed.stateFields,
                stateFloats: fixed.stateFloats,
                uniformBytes: arbProgram.MAX_PROGRAM_PARAMETERS * 4 * 4 * 2,
                colorTargets: fixed.colorTargets,
                arbVertex: vertex,
                arbFragment: null,
                textures: fixed.textures,
            };
        },

        resolveShaders() {
            if (this.current.enabled.has(GL.VERTEX_PROGRAM_ARB) ||
                    this.current.enabled.has(GL.FRAGMENT_PROGRAM_ARB))
                return this.arbShaders();
            const program = this.currentProgramObject();
            const variant = this.currentVariant();
            if (program) {
                const key = this.variantKeyFor(variant);
                let entry = program.variants.get(key);
                if (!entry) {
                    const link = this.linkVariant(program, variant);
                    if (!link.ok) {
                        this.refuse("draw", "the program variant failed to link",
                            { program: program.name, log: link.log },
                            GL.INVALID_OPERATION);
                        return null;
                    }
                    entry = { link, key };
                    program.variants.set(key, entry);
                }
                return {
                    kind: "program", key: "p" + program.name + "|" + key,
                    program,
                    wgslVertex: entry.link.wgslVertex,
                    wgslFragment: entry.link.wgslFragment,
                    reflection: entry.link.reflection,
                    stateFields: entry.link.reflection.stateFields,
                    stateFloats: entry.link.reflection.stateFloats,
                    uniformBytes: entry.link.reflection.uniformBlockBytes,
                    colorTargets: entry.link.reflection.colorTargets,
                };
            }
            const signature = this.fixedFunctionSignature(variant);
            const key = fixedFunction.signatureKey(signature);
            let generated = this.ffCache && this.ffCache.get(key);
            if (!generated) {
                generated = fixedFunction.generate(signature);
                this.ffCache = this.ffCache || new Map();
                this.ffCache.set(key, generated);
            }
            return {
                kind: "ff", key,
                wgslVertex: generated.wgslVertex,
                wgslFragment: generated.wgslFragment,
                stateFields: generated.stateFields,
                stateFloats: generated.stateFloats,
                uniformBytes: 16,
                textures: generated.textures,
                colorTargets: generated.colorTargets,
            };
        },

        fixedFunctionSignature(variant) {
            const s = this.current;

            const texture = [];
            for (let unit = 0; unit < MAX_TEXTURE_UNITS; ++unit) {
                const state = s.textureUnits[unit];
                const target = this.effectiveTarget(state);
                if (!target) { texture.push({ enabled: false }); continue; }
                const object = this.textureObjectFor(unit, target.enumValue);
                const complete = this.textureIsComplete(object);
                texture.push({
                    enabled: true,
                    target: target.kind,
                    shadow: !!(object && object.sampler.compareMode ===
                        GL.COMPARE_R_TO_TEXTURE),
                    format: complete && object ? object.baseFormat : "RGBA",
                    matrix: !isIdentity(this.textureMatrixOf(unit)),
                    texGen: state.texGen.map(gen => gen.enabled ?
                        (TEXGEN_MODE_NAMES[gen.mode] || "EYE") : null),
                    env: this.texEnvSignature(state.env),
                });
            }
            const texGenNeedsNormal = texture.some(unit => unit.enabled &&
                unit.texGen.some(mode => mode === "SPHERE" ||
                    mode === "REFLECTION" || mode === "NORMAL"));

            return {
                attributes: {
                    position: { components: 4 },
                    normal: s.enabled.has(GL.LIGHTING) || texGenNeedsNormal,
                    // Array draws use GL's current values when an array is
                    // disabled. The draw assembler supplies those values as a
                    // constant-rate vertex buffer, so the fixed shader must
                    // consume the attribute rather than bake white/defaults.
                    color: true,
                    secondaryColor: s.enabled.has(GL.COLOR_SUM) ||
                        s.lightModel.colorControl === GL.SEPARATE_SPECULAR_COLOR,
                    fogCoord: s.enabled.has(GL.FOG) &&
                        s.fog.coordSource === GL.FOG_COORD,
                    texCoord: Array.from({ length: MAX_TEXTURE_COORDS },
                        (unused, unit) => texture[unit] && texture[unit].enabled ?
                            { components: 4 } : null),
                },
                lighting: {
                    enabled: s.enabled.has(GL.LIGHTING),
                    twoSide: s.lightModel.twoSide,
                    localViewer: s.lightModel.localViewer,
                    separateSpecular:
                        s.lightModel.colorControl === GL.SEPARATE_SPECULAR_COLOR,
                    normalMode: s.enabled.has(GL.NORMALIZE) ? "normalize" :
                        (s.enabled.has(GL.RESCALE_NORMAL) ? "rescale" : "none"),
                    colorMaterial: {
                        enabled: s.colorMaterial.enabled,
                        face: FACE_NAMES[s.colorMaterial.face] || "FRONT_AND_BACK",
                        mode: COLOR_MATERIAL_MODES[s.colorMaterial.mode] ||
                            "AMBIENT_AND_DIFFUSE",
                    },
                    lights: s.lights.map(light => ({
                        enabled: light.enabled,
                        positional: light.position[3] !== 0,
                        spot: light.spotCutoff !== 180,
                    })),
                },
                fog: {
                    enabled: s.enabled.has(GL.FOG),
                    mode: s.fog.mode === GL.EXP ? "exp" :
                        (s.fog.mode === GL.EXP2 ? "exp2" : "linear"),
                    coordSource: s.fog.coordSource === GL.FOG_COORD ?
                        "coord" : "depth",
                },
                texture,
                alphaTest: variant.alphaTest,
                clipPlaneCount: variant.clipPlaneCount,
                pointSprite: variant.pointSprite,
                pointCoordLowerLeft: variant.pointCoordLowerLeft,
                polygonStipple: variant.polygonStipple,
                logicOp: variant.logicOp,
                flatShading: variant.flatShading,
                colorTargets: variant.colorTargets,
            };
        },

        texEnvSignature(env) {
            const mode = TEXENV_MODE_NAMES[env.mode] || "MODULATE";
            if (mode !== "COMBINE") return {
                mode,
                coordReplace: !!env.pointSprite,
            };
            return {
                mode,
                coordReplace: !!env.pointSprite,
                combineRGB: COMBINE_RGB_NAMES[env.combineRGB] || "MODULATE",
                combineAlpha: COMBINE_RGB_NAMES[env.combineAlpha] || "MODULATE",
                srcRGB: env.srcRGB.map(v => COMBINE_SOURCE_NAMES[v] || "TEXTURE"),
                srcAlpha: env.srcAlpha.map(v => COMBINE_SOURCE_NAMES[v] || "TEXTURE"),
                operandRGB: env.operandRGB.map(v => OPERAND_NAMES[v] || "SRC_COLOR"),
                operandAlpha: env.operandAlpha.map(v =>
                    OPERAND_NAMES[v] || "SRC_ALPHA"),
                rgbScale: env.rgbScale,
                alphaScale: env.alphaScale,
            };
        },

        effectiveTarget(unitState) {
            for (const [enumValue, kind] of TARGET_PRIORITY)
                if (unitState.enabledTargets.has(enumValue))
                    return { enumValue, kind };
            return null;
        },

        textureObjectFor(unit, target) {
            const s = this.current;
            const name = s.textureUnits[unit].bindings[target];
            if (!name) return null;
            return s.shareGroup.textures.get(name) || null;
        },

        textureMatrixOf(unit) {
            const stack = this.current.textureStacks[unit];
            return stack[stack.length - 1];
        },

        /* ---- pipelines ---- */

        ensurePipeline(shaders, request, index) {
            const s = this.current;
            const targets = this.passTargets;
            const topology = PRIMITIVE_TOPOLOGY[request.mode];
            const strip = topology === "triangle-strip" || topology === "line-strip";
            const layoutKey = request.buffers.map(b =>
                b.stride + ":" + (b.stepMode || "vertex") + "@" + b.attributes.map(a =>
                    a.location + ":" + a.format + ":" + a.offset).join(",")).join("|");
            const signature = [
                shaders.key,
                layoutKey,
                request.expandedPoints ? "triangle-list" :
                    (needsIndexExpansion(request.mode) ? "triangle-list" : topology),
                strip && index ? "u32" : "-",
                this.gpuFrontFace(s), this.gpuCullMode(s),
                s.enabled.has(GL.DEPTH_TEST) ? s.depthFunc : "off",
                s.depthMask ? 1 : 0,
                s.enabled.has(GL.STENCIL_TEST) ? stencilKey(s) : "off",
                s.enabled.has(GL.COLOR_LOGIC_OP) ?
                    "logic:" + s.logicOp.toString(16) :
                    (s.enabled.has(GL.BLEND) ? blendKey(s) : "off"),
                s.colorMask.map(v => v ? 1 : 0).join(""),
                polygonOffsetKey(s),
                s.enabled.has(GL.SAMPLE_ALPHA_TO_COVERAGE) ? "a2c" : "-",
                sampleCoverageMask(s),
                targets ? targets.color.map(c => c ? c.format : "-").join(",") : "-",
                targets ? (targets.depthFormat || "-") : "-",
                s.enabled.has(GL.DEPTH_CLAMP) ? "clamp" : "-",
            ].join("|");

            let pipeline = this.pipelineCache.get(signature);
            if (pipeline) return pipeline;

            const vertexModule = this.shaderModule(shaders.wgslVertex);
            const fragmentModule = this.shaderModule(shaders.wgslFragment);
            const buffers = request.buffers.map(buffer => ({
                arrayStride: buffer.stride,
                stepMode: buffer.stepMode || "vertex",
                attributes: buffer.attributes.map(a => ({
                    shaderLocation: a.location,
                    format: a.format,
                    offset: a.offset,
                })),
            }));
            const colorTargets = (targets ? targets.color : [null]).map(target =>
                target ? {
                    format: target.format,
                    blend: s.enabled.has(GL.BLEND) &&
                        !s.enabled.has(GL.COLOR_LOGIC_OP) ?
                        gpuBlendState(s) : undefined,
                    writeMask: (s.colorMask[0] ? 1 : 0) | (s.colorMask[1] ? 2 : 0) |
                        (s.colorMask[2] ? 4 : 0) | (s.colorMask[3] ? 8 : 0),
                } : null);

            const descriptor = {
                label: "GL pipeline",
                layout: "auto",
                vertex: { module: vertexModule, entryPoint: "vs_main", buffers },
                fragment: { module: fragmentModule, entryPoint: "fs_main",
                            targets: colorTargets },
                primitive: {
                    topology: request.expandedPoints ? "triangle-list" :
                        (needsIndexExpansion(request.mode) ?
                        (request.mode === GL.LINE_LOOP ? "line-strip" : "triangle-list") :
                        topology),
                    frontFace: this.gpuFrontFace(s),
                    cullMode: this.gpuCullMode(s),
                    ...(strip && index ? { stripIndexFormat: "uint32" } : {}),
                    ...(s.enabled.has(GL.DEPTH_CLAMP) &&
                        this.deviceFeatures.depthClipControl ?
                        { unclippedDepth: true } : {}),
                },
                multisample: {
                    count: 1,
                    mask: sampleCoverageMask(s),
                    // WebGPU validation only permits alpha-to-coverage on a
                    // multisampled target. D-06 documents the current 1x path.
                    alphaToCoverageEnabled: false,
                },
            };
            if (targets && targets.depthFormat) {
                descriptor.depthStencil = {
                    format: targets.depthFormat,
                    depthWriteEnabled: !!(s.enabled.has(GL.DEPTH_TEST) ?
                        s.depthMask : false),
                    depthCompare: s.enabled.has(GL.DEPTH_TEST) ?
                        (COMPARE_FUNCTIONS[s.depthFunc] || "less") : "always",
                    ...(targets.depthFormat.indexOf("stencil") >= 0 ?
                        gpuStencilState(s) : {}),
                    depthBias: s.enabled.has(GL.POLYGON_OFFSET_FILL) ?
                        Math.round(s.polygonOffset.units) : 0,
                    depthBiasSlopeScale: s.enabled.has(GL.POLYGON_OFFSET_FILL) ?
                        s.polygonOffset.factor : 0,
                };
            }

            try {
                pipeline = this.device.createRenderPipeline(descriptor);
            } catch (error) {
                this.refuse("pipeline", "could not create the render pipeline",
                    { message: String(error), signature }, GL.INVALID_OPERATION);
                return null;
            }
            ++this.stats.pipelines;
            if (this.pipelineCache.size > 4096) this.pipelineCache.clear();
            this.pipelineCache.set(signature, pipeline);
            pipeline.glShaders = shaders;
            pipeline.glActiveBindings = activeShaderBindings(
                shaders.wgslVertex, shaders.wgslFragment);
            return pipeline;
        },

        shaderModule(wgsl) {
            let module = this.moduleCache.get(wgsl);
            if (!module) {
                module = this.device.createShaderModule({ code: wgsl });
                this.moduleCache.set(wgsl, module);
            }
            return module;
        },

        /* ---- bind groups ---- */

        /*
         * Group 1 holds the uniform buffers, group 2 the textures and samplers.
         * The layouts come from the pipeline's automatic layout, so a group the
         * entry points do not statically use is not created or bound.  Merely
         * scanning declarations is insufficient: WebGPU omits a binding which
         * is read only by an uncalled GLSL helper function.
         */
        buildBindGroups(pipeline, shaders) {
            const activeBindings = pipeline.glActiveBindings ||
                (pipeline.glActiveBindings = activeShaderBindings(
                    shaders.wgslVertex, shaders.wgslFragment));
            const bindingIsActive = (group, binding) =>
                activeBindings.has(group + ":" + binding);
            let layout = this.stateUniformLayouts.get(shaders.stateFields);
            if (!layout) {
                layout = stateLayout.buildLayout(shaders.stateFields);
                this.stateUniformLayouts.set(shaders.stateFields, layout);
            }
            const stateSlice = bindingIsActive(1, 0) ?
                this.writeStateUniforms(layout, shaders) : null;
            if (bindingIsActive(1, 0) && !stateSlice) return null;
            // binding 1 is the GLSL program's uniform block, or the ARB
            // vertex program's parameters; binding 2 only ever holds an ARB
            // fragment program's.
            const bindingSlices = shaders.kind === "arb" ?
                this.writeARBParameters(shaders, activeBindings) :
                { 1: !bindingIsActive(1, 1) ? null : shaders.kind === "program" ?
                    this.writeProgramUniforms(shaders) :
                    this.writeEmptyUniforms() };
            if (!bindingSlices || (shaders.kind !== "arb" &&
                    bindingIsActive(1, 1) && !bindingSlices[1]))
                return null;

            const groups = [];
            try {
                const uniformEntries = [];
                if (bindingIsActive(1, 0)) {
                    uniformEntries.push({ binding: 0,
                        resource: { buffer: stateSlice.buffer,
                            offset: stateSlice.offset, size: stateSlice.size } });
                }
                for (const binding of [1, 2]) {
                    if (!bindingIsActive(1, binding)) continue;
                    const slice = bindingSlices[binding];
                    if (!slice)
                        return this.refuse("draw", "a shader reads a uniform " +
                            "binding nothing was written for",
                            { binding, shader: shaders.key },
                            GL.INVALID_OPERATION);
                    uniformEntries.push({ binding,
                        resource: { buffer: slice.buffer,
                            offset: slice.offset, size: slice.size } });
                }
                if (uniformEntries.length) {
                    groups.push({
                        index: 1,
                        group: this.cachedBindGroup(pipeline, 1, uniformEntries),
                    });
                }
                const textureEntries = this.textureBindEntries(shaders)
                    .filter(entry => bindingIsActive(2, entry.binding));
                if (textureEntries.length) {
                    groups.push({
                        index: 2,
                        group: this.cachedBindGroup(pipeline, 2, textureEntries),
                    });
                }
                if (this.current.enabled.has(GL.COLOR_LOGIC_OP) &&
                        this.current.logicOp !== GL.COPY) {
                    const views = this.logicTargetViews || [];
                    const logicEntries = Array.from({
                        length: shaders.colorTargets || 1,
                    }, (unused, binding) => ({
                        binding,
                        resource: views[binding] || views[0] ||
                            this.fallbackView,
                    })).filter(entry => bindingIsActive(3, entry.binding));
                    if (logicEntries.length) {
                        groups.push({
                            index: 3,
                            group: this.cachedBindGroup(pipeline, 3, logicEntries),
                        });
                    }
                }
            } catch (error) {
                this.refuse("draw", "could not build the bind groups",
                    { message: String(error), shader: shaders.key },
                    GL.INVALID_OPERATION);
                return null;
            }
            return groups;
        },

        resourceId(object) {
            let id = this.resourceIds.get(object);
            if (!id) {
                id = this.nextResourceId++;
                this.resourceIds.set(object, id);
            }
            return id;
        },

        cachedBindGroup(pipeline, index, entries) {
            // Automatic layouts are pipeline-specific. Key by actual view /
            // sampler / GPUBuffer identity, never by a recyclable GL name.
            const key = this.resourceId(pipeline) + ":" + index + ":" +
                entries.map(entry => {
                    const r = entry.resource;
                    return entry.binding + ":" + (r.buffer ?
                        [this.resourceId(r.buffer), r.offset || 0, r.size].join("/") :
                        this.resourceId(r));
                }).join("|");
            let group = this.bindGroupCache.get(key);
            if (!group) {
                group = this.device.createBindGroup({
                    layout: pipeline.getBindGroupLayout(index), entries,
                });
                if (this.bindGroupCache.size >= 2048) this.bindGroupCache.clear();
                this.bindGroupCache.set(key, group);
                ++this.stats.bindGroups;
            }
            return group;
        },

        textureBindEntries(shaders) {
            const entries = [];
            if (shaders.kind === "ff" || shaders.kind === "arb") {
                for (const item of shaders.textures) {
                    const unitState = this.current.textureUnits[item.unit];
                    const target = this.effectiveTarget(unitState);
                    const object = target ?
                        this.textureObjectFor(item.unit, target.enumValue) : null;
                    entries.push({ binding: item.textureBinding,
                                   resource: this.textureViewFor(object, item) });
                    entries.push({ binding: item.samplerBinding,
                                   resource: this.samplerFor(object, item.shadow) });
                }
                return entries;
            }
            const program = shaders.program;
            for (const sampler of shaders.reflection.samplers) {
                const count = Math.max(1, sampler.arraySize);
                for (let i = 0; i < count; ++i) {
                    const key = sampler.name +
                        (sampler.arraySize ? "[" + i + "]" : "");
                    const unit = program.samplerUnits.get(key) || 0;
                    const unitState = this.current.textureUnits[
                        clamp(unit, 0, MAX_TEXTURE_UNITS - 1)];
                    const targetEnum = samplerTargetEnum(sampler.dim);
                    const object = unitState ?
                        (this.current.shareGroup.textures.get(
                            unitState.bindings[targetEnum]) || null) : null;
                    entries.push({ binding: sampler.binding + i * 2,
                                   resource: this.textureViewFor(object,
                                       { target: sampler.dim, shadow: sampler.shadow }) });
                    entries.push({ binding: sampler.binding + i * 2 + 1,
                                   resource: this.samplerFor(object, sampler.shadow) });
                }
            }
            return entries;
        },

        textureViewFor(object, item) {
            if (!object || !this.textureIsComplete(object)) return this.fallbackView;
            const gpuTexture = this.ensureTextureUploaded(object);
            if (!gpuTexture) return this.fallbackView;
            const kind = item.target === "Cube" || object.kind === "Cube" ?
                "cube" : (object.kind === "3D" ? "3d" : "2d");
            const key = kind + ":" + object.sampler.baseLevel + ":" +
                object.sampler.maxLevel;
            let view = object.viewCache.get(key);
            if (!view) {
                const baseMipLevel = clamp(object.sampler.baseLevel, 0,
                    object.gpuLevels - 1);
                const mipLevelCount = clamp(
                    object.sampler.maxLevel - baseMipLevel + 1, 1,
                    object.gpuLevels - baseMipLevel);
                view = gpuTexture.createView({
                    dimension: kind,
                    baseMipLevel, mipLevelCount,
                });
                object.viewCache.set(key, view);
            }
            return view;
        },

        samplerFor(object, shadow) {
            if (!object) return shadow ? this.fallbackComparisonSampler :
                this.fallbackSampler;
            const sampler = object.sampler;
            const key = [
                sampler.minFilter, sampler.magFilter,
                sampler.wrapS, sampler.wrapT, sampler.wrapR,
                sampler.maxAnisotropy, sampler.minLod, sampler.maxLod,
                shadow ? sampler.compareFunc : "-",
            ].join("|");
            let gpuSampler = this.samplerCache.get(key);
            if (!gpuSampler) {
                const minLinear = sampler.minFilter === GL.LINEAR ||
                    sampler.minFilter === GL.LINEAR_MIPMAP_NEAREST ||
                    sampler.minFilter === GL.LINEAR_MIPMAP_LINEAR;
                const mipLinear = sampler.minFilter === GL.NEAREST_MIPMAP_LINEAR ||
                    sampler.minFilter === GL.LINEAR_MIPMAP_LINEAR;
                const magLinear = sampler.magFilter === GL.LINEAR;
                // WebGPU rejects anisotropy unless all three filters are
                // linear, so it is clamped rather than the sampler refused.
                const anisotropy = (minLinear && magLinear && mipLinear) ?
                    sampler.maxAnisotropy : 1;
                gpuSampler = this.device.createSampler({
                    addressModeU: ADDRESS_MODES[sampler.wrapS] || "repeat",
                    addressModeV: ADDRESS_MODES[sampler.wrapT] || "repeat",
                    addressModeW: ADDRESS_MODES[sampler.wrapR] || "repeat",
                    magFilter: magLinear ? "linear" : "nearest",
                    minFilter: minLinear ? "linear" : "nearest",
                    mipmapFilter: mipLinear ? "linear" : "nearest",
                    lodMinClamp: Math.max(0, sampler.minLod),
                    lodMaxClamp: Math.min(32, sampler.maxLod),
                    maxAnisotropy: anisotropy,
                    ...(shadow ? {
                        compare: COMPARE_FUNCTIONS[sampler.compareFunc] ||
                            "less-equal",
                    } : {}),
                });
                this.samplerCache.set(key, gpuSampler);
            }
            return gpuSampler;
        },
    });

    function samplerTargetEnum(dim) {
        switch (dim) {
        case "1D": return GL.TEXTURE_1D;
        case "3D": return GL.TEXTURE_3D;
        case "Cube": return GL.TEXTURE_CUBE_MAP;
        default: return GL.TEXTURE_2D;
        }
    }

    function isIdentity(m) {
        for (let i = 0; i < 16; ++i) {
            const expected = (i % 5 === 0) ? 1 : 0;
            if (m[i] !== expected) return false;
        }
        return true;
    }

    function stencilKey(s) {
        const f = s.stencil.front, b = s.stencil.back;
        return [f.func, f.valueMask, f.writeMask, f.fail, f.zfail, f.zpass,
                b.func, b.valueMask, b.writeMask, b.fail, b.zfail, b.zpass].join(",");
    }

    function blendKey(s) {
        const b = s.blend;
        return [b.srcRGB, b.dstRGB, b.srcAlpha, b.dstAlpha,
                b.equationRGB, b.equationAlpha].join(",");
    }

    function polygonOffsetKey(s) {
        return s.enabled.has(GL.POLYGON_OFFSET_FILL) ?
            s.polygonOffset.factor + ":" + s.polygonOffset.units : "-";
    }

    function gpuBlendState(s) {
        const b = s.blend;
        return {
            color: {
                srcFactor: BLEND_FACTORS[b.srcRGB] || "one",
                dstFactor: BLEND_FACTORS[b.dstRGB] || "zero",
                operation: BLEND_EQUATIONS[b.equationRGB] || "add",
            },
            alpha: {
                srcFactor: BLEND_FACTORS[b.srcAlpha] || "one",
                dstFactor: BLEND_FACTORS[b.dstAlpha] || "zero",
                operation: BLEND_EQUATIONS[b.equationAlpha] || "add",
            },
        };
    }

    /*
     * WebGPU has one stencil read mask and one write mask for both faces; GL
     * has a pair each. When they differ the front face's win, and the
     * divergence is reported once -- deviation D-02.
     */
    function gpuStencilState(s) {
        const f = s.stencil.front, b = s.stencil.back;
        const face = state => ({
            compare: COMPARE_FUNCTIONS[state.func] || "always",
            failOp: STENCIL_OPERATIONS[state.fail] || "keep",
            depthFailOp: STENCIL_OPERATIONS[state.zfail] || "keep",
            passOp: STENCIL_OPERATIONS[state.zpass] || "keep",
        });
        return {
            stencilFront: face(f),
            stencilBack: face(b),
            stencilReadMask: f.valueMask >>> 0,
            stencilWriteMask: f.writeMask >>> 0,
        };
    }

    function stencilMasksDiverge(s) {
        const f = s.stencil.front, b = s.stencil.back;
        return f.valueMask !== b.valueMask || f.writeMask !== b.writeMask;
    }

    /* ================================================================== */
    /* Executor: uniform upload                                           */
    /* ================================================================== */

    Object.assign(GLWebGPUExecutor.prototype, {

        allocateUniform(byteCount) {
            // WebGPU requires a uniform binding offset to be 256-aligned.
            const size = alignUp(Math.max(16, byteCount), 256);
            if (size > this.uniformCapacity) {
                this.refuse("draw", "uniform block exceeds the ring capacity",
                    { size }, GL.OUT_OF_MEMORY);
                return null;
            }
            if (this.uniformCursor + size > this.uniformCapacity)
                this.rotateUploadPage("uniform");
            const offset = this.uniformCursor;
            this.uniformCursor = offset + size;
            return { buffer: this.uniformRing, offset, size };
        },

        /*
         * The GL state block. Only the fields the shader actually reads are
         * uploaded, so a 2D blit costs sixteen floats rather than the seven
         * hundred the full table would.
         */
        writeStateUniforms(layout, shaders) {
            const floats = layout.uniformScratch ||
                (layout.uniformScratch = new Float32Array(layout.floats));
            floats.fill(0);
            const snapshot = this.stateSnapshot(shaders);
            stateLayout.writeLayout(layout, snapshot, floats, 0);
            return this.writeUniformSnapshot("state:" + this.resourceId(layout),
                new Uint8Array(floats.buffer));
        },

        writeEmptyUniforms() {
            return this.writeUniformSnapshot("empty", new Uint8Array(16));
        },

        writeUniformSnapshot(key, bytes) {
            const cached = this.uniformValueCache.get(key);
            if (cached && cached.bytes.length === bytes.length) {
                let i = 0;
                while (i < bytes.length && cached.bytes[i] === bytes[i]) ++i;
                if (i === bytes.length) return cached.slice;
            }
            const slice = this.allocateUniform(Math.max(16, bytes.byteLength));
            if (!slice) return null;
            this.uniformStaging.fill(0, slice.offset, slice.offset + slice.size);
            this.uniformStaging.set(bytes, slice.offset);
            this.device.queue.writeBuffer(slice.buffer, slice.offset,
                this.uniformStaging, slice.offset, slice.size);
            if (this.uniformValueCache.size >= 256) this.uniformValueCache.clear();
            // Never update an earlier draw's slice in place. Compare bytes,
            // including integer uniforms, so context switches and every setter
            // are covered without relying on an incomplete dirty-state list.
            this.uniformValueCache.set(key, { bytes: bytes.slice(), slice });
            return slice;
        },

        /*
         * env then local for one program, in the shape its generated shader
         * declares. Each stage gets its own block: program.env and
         * program.local are per-program namespaces, so a bound vertex and
         * fragment program hold different values at the same index, and
         * folding them into one block left the vertex stage reading the
         * fragment program's parameters -- silently, since nothing about the
         * draw is invalid.
         */
        writeARBProgramParameters(program) {
            const count = arbProgram.MAX_PROGRAM_PARAMETERS * 4;
            const floats = program.parameterScratch ||
                (program.parameterScratch = new Float32Array(count * 2));
            floats.set(program.env.subarray(0, count), 0);
            floats.set(program.local.subarray(0, count), count);
            return this.writeUniformSnapshot("arb:" + this.resourceId(program),
                new Uint8Array(floats.buffer));
        },

        /* One slice per stage that declared a parameter block, keyed by the
         * binding its shader reads. */
        writeARBParameters(shaders, activeBindings) {
            const slices = {};
            const stages = [["vertex", shaders.arbVertex, shaders.wgslVertex],
                            ["fragment", shaders.arbFragment, shaders.wgslFragment]];
            for (const [stage, program, wgsl] of stages) {
                const binding = arbProgram.PARAMETER_BINDING[stage];
                if (activeBindings && !activeBindings.has("1:" + binding)) continue;
                if (wgsl.indexOf("@group(1) @binding(" + binding + ")") < 0)
                    continue;
                if (!program || !program.env || !program.local)
                    return this.refuse("draw", "ARB parameter storage is missing",
                        { stage }, GL.INVALID_OPERATION);
                const slice = this.writeARBProgramParameters(program);
                if (!slice) return null;
                slices[binding] = slice;
            }
            return slices;
        },

        writeProgramUniforms(shaders) {
            const program = shaders.program;
            const bytes = Math.max(16, shaders.uniformBytes);
            const data = program.uniformData.byteLength >= bytes ?
                program.uniformData.subarray(0, bytes) : new Uint8Array(bytes);
            if (data.buffer !== program.uniformData.buffer)
                data.set(program.uniformData);
            return this.writeUniformSnapshot("program:" + this.resourceId(program), data);
        },

        /*
         * Builds the plain-object view of GL state that gl_state_layout.js
         * writes from. The derived quantities -- the scene colour, the light
         * products, each light's half vector -- are computed here rather than
         * in the shader, because they depend only on state the CPU already has
         * and would otherwise be recomputed per vertex.
         */
        stateSnapshot(shaders) {
            const s = this.current;
            const snapshot = this.snapshot || (this.snapshot = {
                matrices: {
                    modelview: new Float32Array(16),
                    projection: new Float32Array(16),
                    mvp: new Float32Array(16),
                    normal: new Float32Array(9),
                    modelviewInverse: new Float32Array(16),
                    modelviewTranspose: new Float32Array(16),
                    modelviewInverseTranspose: new Float32Array(16),
                    projectionInverse: new Float32Array(16),
                    projectionTranspose: new Float32Array(16),
                    projectionInverseTranspose: new Float32Array(16),
                    mvpInverse: new Float32Array(16),
                    mvpTranspose: new Float32Array(16),
                    mvpInverseTranspose: new Float32Array(16),
                    texture: Array.from({ length: MAX_TEXTURE_COORDS },
                        () => new Float32Array(16)),
                    textureInverse: Array.from({ length: MAX_TEXTURE_COORDS },
                        () => new Float32Array(16)),
                    textureTranspose: Array.from({ length: MAX_TEXTURE_COORDS },
                        () => new Float32Array(16)),
                    textureInverseTranspose: Array.from(
                        { length: MAX_TEXTURE_COORDS }, () => new Float32Array(16)),
                },
                lights: Array.from({ length: MAX_LIGHTS }, () => ({
                    ambient: new Float32Array(4), diffuse: new Float32Array(4),
                    specular: new Float32Array(4), position: new Float32Array(4),
                    halfVector: new Float32Array(4),
                    spotDirection: new Float32Array(3),
                    spotExponent: 0, spotCutoff: 180, spotCosCutoff: -1,
                    constantAttenuation: 1, linearAttenuation: 0,
                    quadraticAttenuation: 0,
                })),
                material: { front: null, back: null },
                lightModel: { ambient: new Float32Array(4) },
                derived: {
                    frontSceneColor: new Float32Array(4),
                    backSceneColor: new Float32Array(4),
                    frontLightProduct: Array.from({ length: MAX_LIGHTS }, () => ({
                        ambient: new Float32Array(4),
                        diffuse: new Float32Array(4),
                        specular: new Float32Array(4),
                    })),
                    backLightProduct: Array.from({ length: MAX_LIGHTS }, () => ({
                        ambient: new Float32Array(4),
                        diffuse: new Float32Array(4),
                        specular: new Float32Array(4),
                    })),
                },
                fog: { color: new Float32Array(4), density: 1, start: 0, end: 1 },
                texEnvColor: Array.from({ length: MAX_TEXTURE_UNITS },
                    () => new Float32Array(4)),
                texGen: Array.from({ length: MAX_TEXTURE_UNITS }, () =>
                    Array.from({ length: 4 }, () => ({
                        objectPlane: new Float32Array(4),
                        eyePlane: new Float32Array(4),
                    }))),
                clipPlanes: Array.from({ length: MAX_CLIP_PLANES },
                    () => new Float32Array(4)),
                depthRange: { near: 0, far: 1 },
                point: { size: 1, sizeMin: 0, sizeMax: 64, fadeThreshold: 1,
                         attenuation: new Float32Array(3) },
                alphaRef: 0,
                viewport: { x: 0, y: 0, width: 1, height: 1 },
                lineWidth: 1,
                lineStipple: { pattern: 0xffff, factor: 1 },
                polygonStippleEnabled: false,
                polygonStipple: new Uint8Array(128),
            });

            const modelview = this.topOf(GL.MODELVIEW);
            const projection = this.topOf(GL.PROJECTION);
            snapshot.matrices.modelview.set(modelview);
            snapshot.matrices.projection.set(projection);
            multiply4(projection, modelview, snapshot.matrices.mvp);
            normalMatrixOf(modelview, snapshot.matrices.normal);

            // The inverse and transpose variants are only produced when a
            // shader named one; they are four 4x4 inversions each otherwise.
            const wants = new Set(shaders.stateFields);
            if (wants.has("modelviewInverse") || wants.has("modelviewInverseTranspose")) {
                invert4(modelview, snapshot.matrices.modelviewInverse);
                if (wants.has("modelviewInverseTranspose"))
                    transpose4(snapshot.matrices.modelviewInverse,
                        snapshot.matrices.modelviewInverseTranspose);
            }
            if (wants.has("modelviewTranspose"))
                transpose4(modelview, snapshot.matrices.modelviewTranspose);
            if (wants.has("projectionInverse") || wants.has("projectionInverseTranspose")) {
                invert4(projection, snapshot.matrices.projectionInverse);
                if (wants.has("projectionInverseTranspose"))
                    transpose4(snapshot.matrices.projectionInverse,
                        snapshot.matrices.projectionInverseTranspose);
            }
            if (wants.has("projectionTranspose"))
                transpose4(projection, snapshot.matrices.projectionTranspose);
            if (wants.has("mvpInverse") || wants.has("mvpInverseTranspose")) {
                invert4(snapshot.matrices.mvp, snapshot.matrices.mvpInverse);
                if (wants.has("mvpInverseTranspose"))
                    transpose4(snapshot.matrices.mvpInverse,
                        snapshot.matrices.mvpInverseTranspose);
            }
            if (wants.has("mvpTranspose"))
                transpose4(snapshot.matrices.mvp, snapshot.matrices.mvpTranspose);

            for (let i = 0; i < MAX_TEXTURE_COORDS; ++i) {
                const m = this.textureMatrixOf(i);
                snapshot.matrices.texture[i].set(m);
                if (wants.has("textureMatrixInverse") ||
                        wants.has("textureMatrixInverseTranspose")) {
                    invert4(m, snapshot.matrices.textureInverse[i]);
                    if (wants.has("textureMatrixInverseTranspose"))
                        transpose4(snapshot.matrices.textureInverse[i],
                            snapshot.matrices.textureInverseTranspose[i]);
                }
                if (wants.has("textureMatrixTranspose"))
                    transpose4(m, snapshot.matrices.textureTranspose[i]);
            }

            for (let i = 0; i < MAX_LIGHTS; ++i) {
                const light = s.lights[i];
                const out = snapshot.lights[i];
                out.ambient.set(light.ambient);
                out.diffuse.set(light.diffuse);
                out.specular.set(light.specular);
                out.position.set(light.eyePosition);
                out.spotDirection.set(light.eyeSpotDirection);
                out.spotExponent = light.spotExponent;
                out.spotCutoff = light.spotCutoff;
                out.spotCosCutoff = light.spotCutoff === 180 ? -1 :
                    Math.cos(light.spotCutoff * Math.PI / 180);
                out.constantAttenuation = light.constantAttenuation;
                out.linearAttenuation = light.linearAttenuation;
                out.quadraticAttenuation = light.quadraticAttenuation;
                // gl_LightSource[i].halfVector, for the infinite-viewer case
                // the GL spec defines it in: normalize(normalize(P) + (0,0,1)).
                const px = light.eyePosition[0], py = light.eyePosition[1];
                const pz = light.eyePosition[2];
                const len = Math.sqrt(px * px + py * py + pz * pz) || 1;
                const hx = px / len, hy = py / len, hz = pz / len + 1;
                const hlen = Math.sqrt(hx * hx + hy * hy + hz * hz) || 1;
                out.halfVector[0] = hx / hlen;
                out.halfVector[1] = hy / hlen;
                out.halfVector[2] = hz / hlen;
                out.halfVector[3] = 0;
            }

            snapshot.material.front = s.material.front;
            snapshot.material.back = s.material.back;
            snapshot.lightModel.ambient.set(s.lightModel.ambient);

            for (const [face, key] of [["front", "frontSceneColor"],
                    ["back", "backSceneColor"]]) {
                const material = s.material[face];
                const out = snapshot.derived[key];
                for (let c = 0; c < 3; ++c)
                    out[c] = material.emission[c] +
                        material.ambient[c] * s.lightModel.ambient[c];
                out[3] = material.diffuse[3];
            }
            for (const [face, key] of [["front", "frontLightProduct"],
                    ["back", "backLightProduct"]]) {
                const material = s.material[face];
                for (let i = 0; i < MAX_LIGHTS; ++i) {
                    const light = s.lights[i];
                    const product = snapshot.derived[key][i];
                    for (let c = 0; c < 4; ++c) {
                        product.ambient[c] = material.ambient[c] * light.ambient[c];
                        product.diffuse[c] = material.diffuse[c] * light.diffuse[c];
                        product.specular[c] = material.specular[c] * light.specular[c];
                    }
                }
            }

            snapshot.fog.color.set(s.fog.color);
            snapshot.fog.density = s.fog.density;
            snapshot.fog.start = s.fog.start;
            snapshot.fog.end = s.fog.end;

            for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
                snapshot.texEnvColor[i].set(s.textureUnits[i].env.color);
                for (let c = 0; c < 4; ++c) {
                    snapshot.texGen[i][c].objectPlane.set(
                        s.textureUnits[i].texGen[c].objectPlane);
                    snapshot.texGen[i][c].eyePlane.set(
                        s.textureUnits[i].texGen[c].eyePlane);
                }
            }
            for (let i = 0; i < MAX_CLIP_PLANES; ++i)
                snapshot.clipPlanes[i].set(s.clipPlanes[i]);

            snapshot.depthRange.near = s.depthRange.near;
            snapshot.depthRange.far = s.depthRange.far;
            snapshot.point.size = s.point.size;
            snapshot.point.sizeMin = s.point.sizeMin;
            snapshot.point.sizeMax = s.point.sizeMax;
            snapshot.point.fadeThreshold = s.point.fadeThreshold;
            snapshot.point.attenuation.set(s.point.attenuation);
            snapshot.alphaRef = s.alphaFunc.ref;
            snapshot.viewport.x = s.viewport.x;
            snapshot.viewport.y = s.viewport.y;
            snapshot.viewport.width = Math.max(1, s.viewport.width);
            snapshot.viewport.height = Math.max(1, s.viewport.height);
            snapshot.lineWidth = s.lineWidth;
            snapshot.lineStipple.pattern = s.lineStipple.pattern;
            snapshot.lineStipple.factor = s.lineStipple.factor;
            snapshot.polygonStippleEnabled = s.enabled.has(GL.POLYGON_STIPPLE);
            snapshot.polygonStipple.set(s.polygonStipple);
            return snapshot;
        },
    });

    /* ================================================================== */
    /* Executor: present, framebuffers, readback, queries                 */
    /* ================================================================== */

    const PRESENT_WGSL = `
struct VSOut {
    @builtin(position) position : vec4<f32>,
    @location(0) uv : vec2<f32>,
}

@vertex
fn vs_main(@builtin(vertex_index) index : u32) -> VSOut {
    // One oversized triangle covers the target with no vertex buffer.
    var out : VSOut;
    let x = f32((index << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(index & 2u) * 2.0 - 1.0;
    out.position = vec4<f32>(x, y, 0.0, 1.0);
    // The back buffer's row 0 is GL's bottom row (plan 4.3), so presenting it
    // is where the image is turned the right way up -- once, here.
    out.uv = vec2<f32>(x * 0.5 + 0.5, y * 0.5 + 0.5);
    return out;
}

@group(0) @binding(0) var source : texture_2d<f32>;
@group(0) @binding(1) var sourceSampler : sampler;

@fragment
fn fs_main(inp : VSOut) -> @location(0) vec4<f32> {
    return textureSample(source, sourceSampler, inp.uv);
}
`;

    const COLOR_COPY_WGSL = `
struct CopyParams {
    sourceOrigin : vec2<i32>,
    destinationOrigin : vec2<i32>,
}
@group(0) @binding(0) var sourceTexture : texture_2d<f32>;
@group(0) @binding(1) var<uniform> params : CopyParams;
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment fn fs_main(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
    let source = params.sourceOrigin + vec2<i32>(p.xy) - params.destinationOrigin;
    return textureLoad(sourceTexture, source, 0);
}
`;

    const MIPMAP_WGSL = `
@group(0) @binding(0) var sourceTexture : texture_2d<f32>;
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment fn fs_main(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
    let dimensions = vec2<i32>(textureDimensions(sourceTexture));
    let maximum = dimensions - vec2<i32>(1);
    let origin = vec2<i32>(p.xy) * 2;
    let a = textureLoad(sourceTexture, min(origin, maximum), 0);
    let b = textureLoad(sourceTexture,
        min(origin + vec2<i32>(1, 0), maximum), 0);
    let c = textureLoad(sourceTexture,
        min(origin + vec2<i32>(0, 1), maximum), 0);
    let d = textureLoad(sourceTexture,
        min(origin + vec2<i32>(1, 1), maximum), 0);
    return (a + b + c + d) * 0.25;
}
`;

    const COLOR_BLIT_WGSL = `
struct BlitParams {
    sourceOrigin : vec2<f32>,
    sourceExtent : vec2<f32>,
    destinationOrigin : vec2<f32>,
    destinationExtent : vec2<f32>,
}
@group(0) @binding(0) var sourceTexture : texture_2d<f32>;
@group(0) @binding(1) var sourceSampler : sampler;
@group(0) @binding(2) var<uniform> params : BlitParams;
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment fn fs_main(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
    let relative = (p.xy - params.destinationOrigin) / params.destinationExtent;
    let sourcePosition = params.sourceOrigin + relative * params.sourceExtent;
    let dimensions = vec2<f32>(textureDimensions(sourceTexture));
    return textureSampleLevel(sourceTexture, sourceSampler,
        sourcePosition / dimensions, 0.0);
}
`;

    Object.assign(GLWebGPUExecutor.prototype, {

        colorCopyPipeline(format) {
            this.colorCopyPipelines = this.colorCopyPipelines || new Map();
            let pipeline = this.colorCopyPipelines.get(format);
            if (pipeline) return pipeline;
            const module = this.shaderModule(COLOR_COPY_WGSL);
            try {
                pipeline = this.device.createRenderPipeline({
                    label: "GL colour format copy", layout: "auto",
                    vertex: { module, entryPoint: "vs_main" },
                    fragment: { module, entryPoint: "fs_main",
                                targets: [{ format }] },
                    primitive: { topology: "triangle-list" },
                });
            } catch (error) {
                this.refuse("glCopyTexImage", "copy target is not renderable",
                    { format, message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.colorCopyPipelines.set(format, pipeline);
            return pipeline;
        },

        mipmapPipeline(format) {
            this.mipmapPipelines = this.mipmapPipelines || new Map();
            let pipeline = this.mipmapPipelines.get(format);
            if (pipeline) return pipeline;
            const module = this.shaderModule(MIPMAP_WGSL);
            try {
                pipeline = this.device.createRenderPipeline({
                    label: "GL mipmap generator", layout: "auto",
                    vertex: { module, entryPoint: "vs_main" },
                    fragment: { module, entryPoint: "fs_main",
                                targets: [{ format }] },
                    primitive: { topology: "triangle-list" },
                });
            } catch (error) {
                this.refuse("glGenerateMipmap", "texture format is not renderable",
                    { format, message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.mipmapPipelines.set(format, pipeline);
            return pipeline;
        },

        colorBlitPipeline(format) {
            this.colorBlitPipelines = this.colorBlitPipelines || new Map();
            let pipeline = this.colorBlitPipelines.get(format);
            if (pipeline) return pipeline;
            const module = this.shaderModule(COLOR_BLIT_WGSL);
            try {
                pipeline = this.device.createRenderPipeline({
                    label: "GL colour blit", layout: "auto",
                    vertex: { module, entryPoint: "vs_main" },
                    fragment: { module, entryPoint: "fs_main",
                                targets: [{ format }] },
                    primitive: { topology: "triangle-list" },
                });
            } catch (error) {
                this.refuse("glBlitFramebuffer", "blit target is not renderable",
                    { format, message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.colorBlitPipelines.set(format, pipeline);
            return pipeline;
        },

        blitColorTexture(source, destination, sx0, sy0, sx1, sy1,
                dx0, dy0, dx1, dy1, filter) {
            const pipeline = this.colorBlitPipeline(destination.format);
            if (!pipeline) return false;
            const uniform = this.allocateUniform(32);
            if (!uniform) return false;
            new Float32Array(this.uniformStaging.buffer, uniform.offset, 8).set([
                sx0, sy0, sx1 - sx0, sy1 - sy0,
                dx0, dy0, dx1 - dx0, dy1 - dy0,
            ]);
            this.device.queue.writeBuffer(uniform.buffer, uniform.offset,
                this.uniformStaging, uniform.offset, uniform.size);
            const sampler = this.device.createSampler({
                minFilter: filter === GL.LINEAR ? "linear" : "nearest",
                magFilter: filter === GL.LINEAR ? "linear" : "nearest",
            });
            const sourceView = source.view || source.texture.createView({
                dimension: "2d", baseMipLevel: source.mipLevel || 0,
                mipLevelCount: 1, baseArrayLayer: source.layer || 0,
                arrayLayerCount: 1,
            });
            const left = Math.min(dx0, dx1), top = Math.min(dy0, dy1);
            const width = Math.abs(dx1 - dx0), height = Math.abs(dy1 - dy0);
            this.endPass();
            const pass = this.ensureEncoder().beginRenderPass({
                label: "GL scaled colour blit",
                colorAttachments: [{ view: destination.view,
                    loadOp: "load", storeOp: "store" }],
            });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, this.device.createBindGroup({
                layout: pipeline.getBindGroupLayout(0),
                entries: [
                    { binding: 0, resource: sourceView },
                    { binding: 1, resource: sampler },
                    { binding: 2, resource: { buffer: uniform.buffer,
                        offset: uniform.offset, size: uniform.size } },
                ],
            }));
            pass.setViewport(left, top, width, height, 0, 1);
            pass.setScissorRect(left, top, width, height);
            pass.draw(3);
            pass.end();
            return true;
        },

        generateTextureMipmapsGPU(texture) {
            const base = texture.levels[0] && texture.levels[0][0];
            if (!base) return false;
            if (texture.kind === "3D" || base.compressed ||
                    base.base === "DEPTH" || base.base === "COLOR_INDEX") {
                for (const list of texture.levels)
                    if (list) list.length = Math.min(1, list.length);
                return this.refuse("glGenerateMipmap",
                    "GPU-authored mipmaps are unsupported for this texture type",
                    { kind: texture.kind, format: base.gpuFormat },
                    GL.INVALID_OPERATION);
            }
            const pipeline = this.mipmapPipeline(base.gpuFormat);
            if (!pipeline) return false;
            const gpuTexture = this.ensureTextureUploaded(texture);
            if (!gpuTexture) return false;
            const layers = texture.kind === "Cube" ? 6 : 1;
            this.endPass();
            for (let layer = 0; layer < layers; ++layer) {
                const list = texture.levels[layer] || [];
                for (let level = 1; level < list.length; ++level) {
                    const sourceView = gpuTexture.createView({
                        dimension: "2d", baseMipLevel: level - 1,
                        mipLevelCount: 1, baseArrayLayer: layer,
                        arrayLayerCount: 1,
                    });
                    const destinationView = gpuTexture.createView({
                        dimension: "2d", baseMipLevel: level,
                        mipLevelCount: 1, baseArrayLayer: layer,
                        arrayLayerCount: 1,
                    });
                    const pass = this.ensureEncoder().beginRenderPass({
                        label: "GL mipmap level " + level,
                        colorAttachments: [{ view: destinationView,
                            loadOp: "clear", storeOp: "store",
                            clearValue: { r: 0, g: 0, b: 0, a: 0 } }],
                    });
                    pass.setPipeline(pipeline);
                    pass.setBindGroup(0, this.device.createBindGroup({
                        layout: pipeline.getBindGroupLayout(0),
                        entries: [{ binding: 0, resource: sourceView }],
                    }));
                    pass.draw(3);
                    pass.end();
                }
            }
            texture.dirty = false;
            return true;
        },

        copyColorTexture(source, destination, sourceX, sourceY,
                destinationX, destinationY, width, height, loadOp) {
            if (!source || !destination || width <= 0 || height <= 0) return false;
            const pipeline = this.colorCopyPipeline(destination.format);
            if (!pipeline) return false;
            const uniform = this.allocateUniform(16);
            if (!uniform) return false;
            const values = new Int32Array(this.uniformStaging.buffer,
                uniform.offset, 4);
            values.set([sourceX, sourceY, destinationX, destinationY]);
            this.device.queue.writeBuffer(uniform.buffer, uniform.offset,
                this.uniformStaging, uniform.offset, uniform.size);
            const sourceView = source.view || source.texture.createView({
                dimension: "2d", baseMipLevel: source.mipLevel || 0,
                mipLevelCount: 1, baseArrayLayer: source.layer || 0,
                arrayLayerCount: 1,
            });
            this.endPass();
            const pass = this.ensureEncoder().beginRenderPass({
                label: "GL colour copy pass",
                colorAttachments: [{ view: destination.view,
                    loadOp: loadOp || "load", storeOp: "store",
                    clearValue: { r: 0, g: 0, b: 0, a: 0 } }],
            });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, this.device.createBindGroup({
                layout: pipeline.getBindGroupLayout(0),
                entries: [
                    { binding: 0, resource: sourceView },
                    { binding: 1, resource: { buffer: uniform.buffer,
                        offset: uniform.offset, size: uniform.size } },
                ],
            }));
            pass.setViewport(destinationX, destinationY, width, height, 0, 1);
            pass.setScissorRect(destinationX, destinationY, width, height);
            pass.draw(3);
            pass.end();
            return true;
        },

        presentToCanvas() {
            if (!this.host || !this.host.context) return false;
            if (!this.presenterToken)
                this.presenterToken = this.host.claimPresenter("opengl");
            if (!this.host.canPresent(this.presenterToken)) return false;
            if (!this.backBuffer) return false;
            let swapTexture;
            try {
                swapTexture = this.host.context.getCurrentTexture();
            } catch (error) {
                this.warnOnce("present", "could not acquire the swap-chain texture",
                    { message: String(error) });
                return false;
            }
            if (!this.presentPipeline) {
                const module = this.shaderModule(PRESENT_WGSL);
                this.presentPipeline = this.device.createRenderPipeline({
                    label: "GL present",
                    layout: "auto",
                    vertex: { module, entryPoint: "vs_main" },
                    fragment: { module, entryPoint: "fs_main",
                                targets: [{ format: this.host.format }] },
                    primitive: { topology: "triangle-list" },
                });
                this.presentSampler = this.device.createSampler({
                    magFilter: "linear", minFilter: "linear",
                });
            }
            const encoder = this.ensureEncoder();
            const pass = encoder.beginRenderPass({
                label: "GL present pass",
                colorAttachments: [{
                    view: swapTexture.createView(),
                    loadOp: "clear",
                    clearValue: { r: 0, g: 0, b: 0, a: 1 },
                    storeOp: "store",
                }],
            });
            pass.setPipeline(this.presentPipeline);
            pass.setBindGroup(0, this.device.createBindGroup({
                layout: this.presentPipeline.getBindGroupLayout(0),
                entries: [
                    { binding: 0, resource: this.backBufferView },
                    { binding: 1, resource: this.presentSampler },
                ],
            }));
            pass.draw(3);
            pass.end();
            return true;
        },

        onSwapBuffers() {
            this.finishFrame(true);
        },

        /* ---- framebuffer objects ---- */

        framebufferTexture(target, attachment, textarget, textureName, level, layer) {
            const s = this.current;
            const name = target === GL.READ_FRAMEBUFFER ?
                s.readFramebuffer : s.drawFramebuffer;
            const fbo = this.framebuffers.get(s.id).get(name);
            if (!fbo)
                return this.refuse("glFramebufferTexture2D",
                    "no framebuffer object is bound", { target },
                    GL.INVALID_OPERATION);
            const face = CUBE_FACE_INDEX[textarget];
            const record = textureName ? {
                kind: "texture", name: textureName, level: level | 0,
                layer: face !== undefined ? face : (layer | 0),
            } : null;
            this.attachTo(fbo, attachment, record);
            this.endPass();
        },

        framebufferRenderbuffer(target, attachment, rbTarget, rbName) {
            const s = this.current;
            const name = target === GL.READ_FRAMEBUFFER ?
                s.readFramebuffer : s.drawFramebuffer;
            const fbo = this.framebuffers.get(s.id).get(name);
            if (!fbo)
                return this.refuse("glFramebufferRenderbuffer",
                    "no framebuffer object is bound", { target },
                    GL.INVALID_OPERATION);
            void rbTarget;
            this.attachTo(fbo, attachment,
                rbName ? { kind: "renderbuffer", name: rbName, level: 0, layer: 0 } :
                    null);
            this.endPass();
        },

        attachTo(fbo, attachment, record) {
            if (attachment === GL.DEPTH_ATTACHMENT) fbo.depth = record;
            else if (attachment === GL.STENCIL_ATTACHMENT) fbo.stencil = record;
            else if (attachment === GL.DEPTH_STENCIL_ATTACHMENT) {
                fbo.depth = record;
                fbo.stencil = record;
            } else {
                const index = attachment - GL.COLOR_ATTACHMENT0;
                if (index < 0 || index >= MAX_DRAW_BUFFERS)
                    return this.refuse("glFramebufferTexture2D",
                        "attachment out of range", { attachment },
                        GL.INVALID_ENUM);
                fbo.color[index] = record;
            }
            const size = this.attachmentSize(record);
            if (size) { fbo.width = size.width; fbo.height = size.height; }
        },

        attachmentSize(record) {
            if (!record) return null;
            if (record.kind === "texture") {
                const texture = this.current.shareGroup.textures.get(record.name);
                const slot = texture && texture.levels[record.layer] &&
                    texture.levels[record.layer][record.level];
                return slot ? { width: slot.width, height: slot.height } : null;
            }
            const rb = this.current.shareGroup.renderbuffers.get(record.name);
            return rb ? { width: rb.width, height: rb.height } : null;
        },

        attachmentFormat(record) {
            if (!record) return null;
            if (record.kind === "texture") {
                const texture = this.current.shareGroup.textures.get(record.name);
                const slot = texture && texture.levels[record.layer] &&
                    texture.levels[record.layer][record.level];
                return slot ? slot.gpuFormat : null;
            }
            const rb = this.current.shareGroup.renderbuffers.get(record.name);
            return rb ? rb.gpuFormat : null;
        },

        renderbufferStorage(internalFormat, width, height) {
            const s = this.current;
            const rb = s.shareGroup.renderbuffers.get(s.renderbuffer);
            if (!rb)
                return this.refuse("glRenderbufferStorage",
                    "no renderbuffer is bound", {}, GL.INVALID_OPERATION);
            const storage = storageFormatFor(internalFormat, this.deviceFeatures);
            rb.width = Math.max(1, width);
            rb.height = Math.max(1, height);
            rb.internalFormat = internalFormat;
            // WebGPU has no renderbuffer: a texture with RENDER_ATTACHMENT is
            // the same thing with a different name.
            const stencilFormat = internalFormat === GL.STENCIL_INDEX8_EXT ||
                internalFormat === GL.DEPTH24_STENCIL8;
            rb.gpuFormat = stencilFormat ? "depth24plus-stencil8" : storage.gpu;
            this.retire(rb.gpuTexture);
            rb.gpuTexture = this.device.createTexture({
                label: "GL renderbuffer " + rb.name,
                size: { width: rb.width, height: rb.height, depthOrArrayLayers: 1 },
                format: rb.gpuFormat,
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_TEXTURE_BINDING,
            });
        },

        /*
         * GL's completeness rules, answered from the executor's own state --
         * no GPU round trip, so the guest's blocking call returns immediately.
         */
        checkFramebufferStatus(target) {
            const s = this.current;
            const name = target === GL.READ_FRAMEBUFFER ?
                s.readFramebuffer : s.drawFramebuffer;
            if (!name) return GL.FRAMEBUFFER_COMPLETE;
            const fbo = this.framebuffers.get(s.id).get(name);
            if (!fbo) return GL.FRAMEBUFFER_UNDEFINED || 0x8219;
            let width = 0, height = 0, any = false;
            const check = record => {
                if (!record) return true;
                const size = this.attachmentSize(record);
                if (!size || !size.width || !size.height) return false;
                if (!any) { width = size.width; height = size.height; any = true; }
                else if (size.width !== width || size.height !== height)
                    return false;
                return true;
            };
            for (const attachment of fbo.color)
                if (!check(attachment)) return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
            if (!check(fbo.depth))
                return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
            if (!check(fbo.stencil))
                return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
            if (!any) return GL.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;

            for (const attachment of fbo.color) {
                const format = this.attachmentFormat(attachment);
                if (format && format.indexOf("depth") === 0)
                    return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
            }
            const depthFormat = this.attachmentFormat(fbo.depth);
            if (depthFormat && depthFormat.indexOf("depth") !== 0)
                return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
            const stencilFormat = this.attachmentFormat(fbo.stencil);
            if (stencilFormat && stencilFormat.indexOf("stencil") < 0)
                return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;

            if (fbo.depth && fbo.stencil &&
                    (fbo.depth.kind !== fbo.stencil.kind ||
                     fbo.depth.name !== fbo.stencil.name ||
                     fbo.depth.level !== fbo.stencil.level ||
                     fbo.depth.layer !== fbo.stencil.layer))
                return GL.FRAMEBUFFER_UNSUPPORTED_EXT;

            if (target !== GL.READ_FRAMEBUFFER) {
                for (const buffer of s.drawBuffers) {
                    if (buffer === GL.NONE) continue;
                    const index = buffer >= GL.COLOR_ATTACHMENT0 ?
                        buffer - GL.COLOR_ATTACHMENT0 : 0;
                    if (!fbo.color[index])
                        return GL.FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT;
                }
            }
            if (target !== GL.DRAW_FRAMEBUFFER && s.readBuffer !== GL.NONE) {
                const index = s.readBuffer >= GL.COLOR_ATTACHMENT0 ?
                    s.readBuffer - GL.COLOR_ATTACHMENT0 : 0;
                if (!fbo.color[index])
                    return GL.FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT;
            }
            fbo.width = width;
            fbo.height = height;
            return GL.FRAMEBUFFER_COMPLETE;
        },

        blitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, filter) {
            // A same-size, same-format colour blit is a texture copy. Scaling,
            // axis reversal, or format conversion is implemented by a draw.
            // Depth/stencil copies require aspect-typed pipelines and are
            // rejected explicitly instead of producing a WebGPU validation
            // error that invalidates the whole command buffer.
            if (!(mask & GL.COLOR_BUFFER_BIT) ||
                    (mask & ~GL.COLOR_BUFFER_BIT) !== 0)
                return this.refuse("glBlitFramebuffer",
                    "only colour blits are implemented", { mask }, 0);
            const width = Math.abs(sx1 - sx0), height = Math.abs(sy1 - sy0);
            const dstWidth = Math.abs(dx1 - dx0), dstHeight = Math.abs(dy1 - dy0);
            const source = this.readAttachmentView();
            const target = this.currentTargets();
            if (!source || !target || !target.color[0]) return;
            const destination = target.color[0];
            const straight = sx1 >= sx0 && sy1 >= sy0 &&
                dx1 >= dx0 && dy1 >= dy0;
            if (straight && width === dstWidth && height === dstHeight &&
                    source.format === destination.format &&
                    source.texture !== destination.texture) {
                this.endPass();
                this.ensureEncoder().copyTextureToTexture(
                    { texture: source.texture, mipLevel: source.mipLevel || 0,
                      origin: { x: sx0, y: sy0, z: source.layer || 0 } },
                    { texture: destination.texture || this.backBuffer,
                      mipLevel: destination.mipLevel || 0,
                      origin: { x: dx0, y: dy0,
                        z: destination.origin ? destination.origin.z : 0 } },
                    { width, height, depthOrArrayLayers: 1 });
                return;
            }
            this.blitColorTexture(source, destination,
                sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, filter);
        },

        readAttachmentView() {
            const s = this.current;
            if (!s.readFramebuffer)
                return this.backBuffer ? { texture: this.backBuffer,
                    format: this.backBufferFormat,
                    width: this.backBufferWidth,
                    height: this.backBufferHeight } : null;
            const fbo = this.framebuffers.get(s.id).get(s.readFramebuffer);
            if (!fbo) return null;
            const index = s.readBuffer >= GL.COLOR_ATTACHMENT0 ?
                s.readBuffer - GL.COLOR_ATTACHMENT0 : 0;
            const record = fbo.color[index];
            if (!record) return null;
            if (record.kind === "texture") {
                const texture = s.shareGroup.textures.get(record.name);
                const gpuTexture = this.ensureTextureUploaded(texture);
                return gpuTexture ? { texture: gpuTexture,
                    format: texture.gpuFormat,
                    mipLevel: record.level, layer: record.layer,
                    view: gpuTexture.createView({
                        dimension: "2d", baseMipLevel: record.level,
                        mipLevelCount: 1, baseArrayLayer: record.layer,
                        arrayLayerCount: 1,
                    }),
                    width: Math.max(1, texture.gpuWidth >> record.level),
                    height: Math.max(1, texture.gpuHeight >> record.level) } : null;
            }
            const rb = s.shareGroup.renderbuffers.get(record.name);
            return rb && rb.gpuTexture ? { texture: rb.gpuTexture,
                view: rb.gpuTexture.createView(),
                format: rb.gpuFormat, width: rb.width, height: rb.height } : null;
        },

        copyTexImage(target, level, internalFormat, x, y, width, height) {
            const source = this.readAttachmentView();
            if (!source)
                return this.refuse("glCopyTexImage2D", "no readable attachment",
                    {}, GL.INVALID_FRAMEBUFFER_OPERATION);
            const texture = this.boundTexture(target);
            if (!texture) return;
            const storage = storageFormatFor(internalFormat, this.deviceFeatures);
            const kind = this.textureTargetKind(target);
            if (kind === "3D" || storage.depth || storage.palettised ||
                    storage.compressed)
                return this.refuse("glCopyTexImage2D",
                    "the requested target format cannot receive a colour copy",
                    { target, internalFormat, format: storage.gpu },
                    GL.INVALID_OPERATION);
            texture.target = kind === "Cube" ? GL.TEXTURE_CUBE_MAP : target;
            const bytesPerTexel = storage.gpu === "rgba16float" ? 8 :
                (storage.gpu === "rgba32float" ? 16 : 4);
            const componentType = storage.gpu === "rgba16float" ? "f16" :
                (storage.gpu === "rgba32float" ? "f32" : "u8");
            this.storeLevel(texture, kind, level, CUBE_FACE_INDEX[target] || 0, {
                width, height, depth: 1, gpuFormat: storage.gpu,
                base: storage.base, compressed: false,
                // The level is authored on the GPU.  Keeping pixels null is
                // important: a later lazy upload must not overwrite the copy
                // with a zero-filled CPU shadow.
                pixels: null, bytesPerTexel, componentType, componentCount: 4,
            });
            this.ensureTextureUploaded(texture);
            // Framebuffer row y is GL's row y after the clip-space flip, so the
            // copy is direct rather than mirrored.
            const view = texture.gpuTexture.createView({
                dimension: "2d", baseMipLevel: level, mipLevelCount: 1,
                baseArrayLayer: CUBE_FACE_INDEX[target] || 0,
                arrayLayerCount: 1,
            });
            this.copyColorTexture(source, { view, format: storage.gpu },
                x, y, 0, 0, width, height, "clear");
        },

        copyTexSubImage(target, level, xoffset, yoffset, zoffset, x, y, width,
                height) {
            const source = this.readAttachmentView();
            if (!source)
                return this.refuse("glCopyTexSubImage", "no readable attachment",
                    {}, GL.INVALID_FRAMEBUFFER_OPERATION);
            const texture = this.boundTexture(target);
            if (!texture) return;
            const kind = this.textureTargetKind(target);
            const layer = CUBE_FACE_INDEX[target] || 0;
            const slot = this.levelSlot(texture, kind, level, layer);
            if (!slot)
                return this.refuse("glCopyTexSubImage",
                    "destination level has no storage", { level, layer },
                    GL.INVALID_OPERATION);
            if (kind === "3D" || slot.compressed || slot.base === "DEPTH" ||
                    slot.base === "COLOR_INDEX")
                return this.refuse("glCopyTexSubImage",
                    "the destination format cannot receive a colour copy",
                    { target, format: slot.gpuFormat }, GL.INVALID_OPERATION);
            const gpuTexture = this.ensureTextureUploaded(texture);
            if (!gpuTexture) return;
            void zoffset;
            const view = gpuTexture.createView({
                dimension: "2d", baseMipLevel: level, mipLevelCount: 1,
                baseArrayLayer: layer, arrayLayerCount: 1,
            });
            if (this.copyColorTexture(source,
                    { view, format: slot.gpuFormat }, x, y,
                    xoffset, yoffset, width, height, "load")) {
                // The CPU copy is no longer authoritative after a framebuffer
                // copy.  Mipmap generation below can continue entirely on GPU.
                slot.pixels = null;
                texture.dirty = false;
            }
        },

        /* ---- glReadPixels ----
         *
         * The only place the GL path genuinely needs a GPU round trip. The
         * guest spins on the status word in the record it submitted, so the
         * answer is written back into that record when the mapping resolves --
         * and the heartbeat keeps a busy host from being mistaken for a dead
         * one (plan 6.2).
         */
        readPixels(bytes, view, offset, size, metadata) {
            if (size < READ_PIXELS_HEADER_SIZE) {
                throw new GLStreamError("glReadPixels record is too short");
            }
            const x = view.getInt32(offset, true);
            const y = view.getInt32(offset + 4, true);
            const width = view.getInt32(offset + 8, true);
            const height = view.getInt32(offset + 12, true);
            const format = view.getUint32(offset + 16, true);
            const type = view.getUint32(offset + 20, true);
            const dataSize = view.getUint32(offset + 24, true);
            view.setUint32(offset + 28, SYNC_STATUS_PENDING, true);

            const source = this.readAttachmentView();
            if (!source || width <= 0 || height <= 0) {
                view.setUint32(offset + 28, SYNC_STATUS_FAILED, true);
                return;
            }
            const bytesPerRow = alignUp(width * 4, 256);
            const staging = this.device.createBuffer({
                label: "GL readback",
                size: bytesPerRow * height,
                usage: BUFFER_USAGE_COPY_DST | BUFFER_USAGE_MAP_READ,
            });
            this.endPass();
            const encoder = this.ensureEncoder();
            encoder.copyTextureToBuffer(
                { texture: source.texture, origin: { x, y, z: 0 } },
                { buffer: staging, bytesPerRow, rowsPerImage: height },
                { width, height, depthOrArrayLayers: 1 });
            this.flushFrame();

            const writeGuest = this.options.writeGuestMemory;
            const recordOffset = offset;
            this.trackReadback(staging.mapAsync(1 /* GPUMapMode.READ */).then(() => {
                const mapped = new Uint8Array(staging.getMappedRange());
                const out = new Uint8Array(dataSize);
                const packed = packReadback(mapped, bytesPerRow, width, height,
                    format, type, source.format, dataSize);
                out.set(packed.subarray(0, dataSize));
                staging.unmap();
                staging.destroy();
                if (metadata && metadata.isMemoryValid && !metadata.isMemoryValid()) return;
                // Two ways home: the payload view when it aliases guest memory,
                // and the bridge's writer when it does not. Doing both is
                // harmless and makes the path work in either wiring.
                if (bytes.byteLength >= recordOffset + READ_PIXELS_HEADER_SIZE +
                        dataSize) {
                    bytes.set(out, recordOffset + READ_PIXELS_HEADER_SIZE);
                    new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
                        .setUint32(recordOffset + 28, SYNC_STATUS_OK, true);
                }
                if (typeof writeGuest === "function") {
                    const payload = new Uint8Array(4 + dataSize);
                    payload.set(out, 4);
                    // Status last: the guest observing OK must already see the
                    // pixels, and memory is copied in increasing order.
                    writeGuest(recordOffset + READ_PIXELS_HEADER_SIZE, out,
                        metadata);
                    const status = new Uint8Array(4);
                    new DataView(status.buffer).setUint32(0, SYNC_STATUS_OK, true);
                    writeGuest(recordOffset + 28, status, metadata);
                }
            }).catch(error => {
                this.warnOnce("readback", "glReadPixels mapping failed",
                    { message: String(error) });
                try { staging.destroy(); } catch (ignored) { /* already gone */ }
            }));
        },

        /* ---- occlusion queries ---- */

        beginQuery(target, name) {
            if (target !== GL.SAMPLES_PASSED && target !== GL.ANY_SAMPLES_PASSED)
                return this.refuse("glBeginQuery", "unsupported query target",
                    { target }, GL.INVALID_ENUM);
            const query = this.queries.get(name);
            if (!query)
                return this.refuse("glBeginQuery", "unknown query object",
                    { name }, GL.INVALID_OPERATION);
            if (this.activeQuery)
                return this.refuse("glBeginQuery", "a query is already active",
                    { name }, GL.INVALID_OPERATION);
            query.generation = (query.generation || 0) + 1;
            query.ready = false;
            query.result = 0;
            query.pendingSegments = 0;
            query.ended = false;
            query.slot = -1;
            this.ensureOcclusionQuerySet();
            this.activeQuery = query;
            // The set is created lazily, so the pass that is already open on
            // the first glBeginQuery of a session was built without it. Ending
            // it makes ensurePass rebuild one that carries it; the rebuilt
            // pass loads the attachments it just stored, so nothing is lost.
            if (this.pass && !this.passHasOcclusionQuerySet) this.endPass();
            this.ensurePass();
        },

        endQuery(target) {
            void target;
            const query = this.activeQuery;
            if (!query) return;
            this.endOcclusionSegment();
            this.activeQuery = null;
            query.ended = true;
            query.ready = query.pendingSegments === 0;
        },

        beginOcclusionSegment() {
            const query = this.activeQuery;
            if (!query || !this.pass || query.slot >= 0) return;
            query.slot = this.nextQuerySlot++;
            this.pass.beginOcclusionQuery(query.slot);
        },

        endOcclusionSegment() {
            const query = this.activeQuery;
            if (!query || !this.pass || query.slot < 0) return;
            this.pass.endOcclusionQuery();
            ++query.pendingSegments;
            this.pendingQueries = this.pendingQueries || [];
            // Keep the slot and generation immutable while mapAsync is in
            // flight. The query object itself is immediately reusable.
            this.pendingQueries.push({
                query,
                slot: query.slot,
                generation: query.generation,
            });
            query.slot = -1;
        },

        completeOcclusionSegment(record, result) {
            const { query, generation } = record;
            if (query.generation !== generation) return;
            // D-07 exposes visibility, so OR all pass/submission segments.
            // A later zero must not erase visibility from an earlier pass.
            if (result) query.result = OCCLUSION_VISIBLE_SAMPLES;
            --query.pendingSegments;
            query.ready = query.ended && query.pendingSegments === 0;
        },

        ensureOcclusionQuerySet() {
            if (this.activeOcclusionQuerySet) return;
            this.occlusionCapacity = 4096;
            this.activeOcclusionQuerySet = this.device.createQuerySet({
                type: "occlusion", count: this.occlusionCapacity,
            });
            this.nextQuerySlot = 0;
        },

        /*
         * Cube 2 keeps a pool of two thousand query objects and asks for them
         * all at once, so the batch resolves every pending query in one
         * readback rather than one per object.
         */
        queryObjectBatch(bytes, view, offset, size) {
            const headerSize = 16;
            const entrySize = 12;
            if (size < headerSize) throw new GLStreamError("query batch is short");
            const count = view.getUint32(offset, true);
            if (headerSize + count * entrySize > size) {
                view.setUint32(offset + 8, SYNC_STATUS_FAILED, true);
                return;
            }
            // Results already resolved are answered immediately; the rest keep
            // their last value, which GL permits for a query that is not ready.
            for (let i = 0; i < count; ++i) {
                const at = offset + headerSize + i * entrySize;
                const name = view.getUint32(at, true);
                const query = this.queries.get(name);
                view.setUint32(at + 4, query && query.ready ? 1 : 0, true);
                view.setUint32(at + 8, query ? query.result >>> 0 : 0, true);
            }
            view.setUint32(offset + 8, SYNC_STATUS_OK, true);
        },

        onFinish(bytes, view, offset, size) {
            this.flushFrame();
            if (size >= 4) view.setUint32(offset, SYNC_STATUS_OK, true);
        },

        /* ---- legacy pixel rectangles ---- */

        drawPixels(bytes, view, offset, size) {
            if (size < 20) throw new GLStreamError("glDrawPixels record is short");
            const width = view.getInt32(offset, true);
            const height = view.getInt32(offset + 4, true);
            const format = view.getUint32(offset + 8, true);
            const type = view.getUint32(offset + 12, true);
            const dataSize = view.getUint32(offset + 16, true);
            if (width <= 0 || height <= 0 || !this.current.current.rasterValid)
                return;
            if (20 + dataSize > size)
                throw new GLStreamError("glDrawPixels data is truncated");
            const source = bytes.subarray(offset + 20, offset + 20 + dataSize);
            const store = this.current.pixelStore;
            const rgba = convertPixels(source, 0, width, height, 1,
                format, type, "RGBA", {
                    alignment: store.unpackAlignment,
                    rowLength: store.unpackRowLength,
                    skipPixels: store.unpackSkipPixels,
                    skipRows: store.unpackSkipRows,
                    imageHeight: store.unpackImageHeight,
                    skipImages: store.unpackSkipImages,
                });
            if (!rgba)
                return this.refuse("glDrawPixels", "unsupported or truncated pixel data",
                    { width, height, format, type }, GL.INVALID_ENUM);
            this.applyPixelTransfer(rgba);
            this.drawPixelRGBA(rgba, width, height,
                this.current.current.rasterPos[0],
                this.current.current.rasterPos[1], false);
        },

        drawBitmap(bytes, view, offset, size) {
            if (size < 28) throw new GLStreamError("glBitmap record is short");
            const width = view.getInt32(offset, true);
            const height = view.getInt32(offset + 4, true);
            const xorig = view.getFloat32(offset + 8, true);
            const yorig = view.getFloat32(offset + 12, true);
            const xmove = view.getFloat32(offset + 16, true);
            const ymove = view.getFloat32(offset + 20, true);
            const dataSize = view.getUint32(offset + 24, true);
            const s = this.current;
            if (28 + dataSize > size)
                throw new GLStreamError("glBitmap data is truncated");
            if (s.current.rasterValid && width > 0 && height > 0 && dataSize) {
                const source = bytes.subarray(offset + 28,
                    offset + 28 + dataSize);
                const rgba = this.expandBitmap(source, width, height);
                this.drawPixelRGBA(rgba, width, height,
                    s.current.rasterPos[0] - xorig,
                    s.current.rasterPos[1] - yorig, true);
            }
            if (s.current.rasterValid) {
                s.current.rasterPos[0] += xmove;
                s.current.rasterPos[1] += ymove;
            }
        },

        copyPixels(x, y, width, height, type) {
            if (width <= 0 || height <= 0 || !this.current.current.rasterValid)
                return;
            if (type !== GL.COLOR)
                return this.refuse("glCopyPixels",
                    "depth and stencil pixel copies need typed attachment copies",
                    { type }, GL.INVALID_OPERATION);
            const source = this.readAttachmentView();
            if (!source) return this.refuse("glCopyPixels",
                "no readable colour attachment", {},
                GL.INVALID_FRAMEBUFFER_OPERATION);
            this.endPass();
            const texture = this.device.createTexture({
                label: "GL copy-pixels source",
                size: { width, height, depthOrArrayLayers: 1 },
                format: source.format,
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            this.ensureEncoder().copyTextureToTexture(
                { texture: source.texture, origin: { x, y, z: 0 } },
                { texture }, { width, height, depthOrArrayLayers: 1 });
            this.drawPixelTexture(texture, texture.createView(), width, height,
                this.current.current.rasterPos[0],
                this.current.current.rasterPos[1], false);
            this.retire(texture);
        },

        applyPixelTransfer(rgba) {
            const transfer = this.current.pixelTransfer;
            const maps = this.pixelMaps || Object.create(null);
            const scales = [transfer.redScale, transfer.greenScale,
                transfer.blueScale, transfer.alphaScale];
            const biases = [transfer.redBias, transfer.greenBias,
                transfer.blueBias, transfer.alphaBias];
            const matrix = this.topOf(GL.COLOR);
            const mapNames = [GL.PIXEL_MAP_R_TO_R, GL.PIXEL_MAP_G_TO_G,
                GL.PIXEL_MAP_B_TO_B, GL.PIXEL_MAP_A_TO_A];
            for (let at = 0; at < rgba.length; at += 4) {
                const input = [0, 0, 0, 0];
                for (let c = 0; c < 4; ++c) {
                    input[c] = clamp(rgba[at + c] / 255 * scales[c] +
                        biases[c], 0, 1);
                }
                const transformed = [
                    matrix[0] * input[0] + matrix[4] * input[1] +
                        matrix[8] * input[2] + matrix[12] * input[3],
                    matrix[1] * input[0] + matrix[5] * input[1] +
                        matrix[9] * input[2] + matrix[13] * input[3],
                    matrix[2] * input[0] + matrix[6] * input[1] +
                        matrix[10] * input[2] + matrix[14] * input[3],
                    matrix[3] * input[0] + matrix[7] * input[1] +
                        matrix[11] * input[2] + matrix[15] * input[3],
                ];
                for (let c = 0; c < 4; ++c) {
                    let value = clamp(transformed[c] *
                        transfer.postColorMatrixScale[c] +
                        transfer.postColorMatrixBias[c], 0, 1);
                    const map = transfer.mapColor ? maps[mapNames[c]] : null;
                    if (map && map.length) {
                        const index = clamp(Math.round(value * (map.length - 1)),
                            0, map.length - 1);
                        value = clamp(map[index], 0, 1);
                    }
                    rgba[at + c] = Math.round(value * 255);
                }
            }
        },

        expandBitmap(source, width, height) {
            const store = this.current.pixelStore;
            const rowLength = store.unpackRowLength || width;
            const rowBytes = Math.ceil(rowLength / 8);
            const stride = alignUp(rowBytes, store.unpackAlignment || 1);
            const skip = store.unpackSkipPixels || 0;
            const rgba = new Uint8Array(width * height * 4);
            const color = this.current.current.color;
            for (let row = 0; row < height; ++row) {
                const rowStart = (store.unpackSkipRows + row) * stride;
                for (let x = 0; x < width; ++x) {
                    const bit = skip + x;
                    const byte = source[rowStart + (bit >> 3)] || 0;
                    const mask = store.unpackLsbFirst ? 1 << (bit & 7) :
                        0x80 >> (bit & 7);
                    if (!(byte & mask)) continue;
                    const at = (row * width + x) * 4;
                    rgba[at] = Math.round(clamp(color[0], 0, 1) * 255);
                    rgba[at + 1] = Math.round(clamp(color[1], 0, 1) * 255);
                    rgba[at + 2] = Math.round(clamp(color[2], 0, 1) * 255);
                    rgba[at + 3] = Math.round(clamp(color[3], 0, 1) * 255);
                }
            }
            return rgba;
        },

        drawPixelRGBA(rgba, width, height, x, y, discardZeroAlpha) {
            const texture = this.device.createTexture({
                label: "GL pixel rectangle",
                size: { width, height, depthOrArrayLayers: 1 },
                format: "rgba8unorm",
                usage: TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
            this.device.queue.writeTexture({ texture }, rgba,
                { bytesPerRow: width * 4, rowsPerImage: height },
                { width, height, depthOrArrayLayers: 1 });
            this.drawPixelTexture(texture, texture.createView(), width, height,
                x, y, discardZeroAlpha);
            this.retire(texture);
        },

        drawPixelTexture(texture, textureView, width, height, x, y,
                discardZeroAlpha) {
            const s = this.current;
            const vp = s.viewport;
            if (!vp.width || !vp.height) return;
            const x0 = x, y0 = y;
            const x1 = x + width * s.pixelZoom.x;
            const y1 = y + height * s.pixelZoom.y;
            const ndcX = value => (value - vp.x) * 2 / vp.width - 1;
            // The normal GL vertex path negates clip-space Y. Expressing the
            // window coordinate directly therefore uses the same negated map.
            const ndcY = value => 1 - (value - vp.y) * 2 / vp.height;
            const range = s.depthRange.far - s.depthRange.near;
            const z = Math.abs(range) > 1e-12 ?
                (s.current.rasterPos[2] - s.depthRange.near) / range : 0;
            const vertices = new Float32Array([
                ndcX(x0), ndcY(y0), z, 1, 0, 0,
                ndcX(x1), ndcY(y0), z, 1, 1, 0,
                ndcX(x0), ndcY(y1), z, 1, 0, 1,
                ndcX(x0), ndcY(y1), z, 1, 0, 1,
                ndcX(x1), ndcY(y0), z, 1, 1, 0,
                ndcX(x1), ndcY(y1), z, 1, 1, 1,
            ]);
            const slice = this.uploadVertices(new Uint8Array(vertices.buffer));
            if (!slice) return;
            const pass = this.ensurePass();
            if (!pass) return;
            const pipeline = this.pixelPipeline(discardZeroAlpha);
            if (!pipeline) return;
            pass.setPipeline(pipeline);
            this.applyPassState(pass);
            pass.setVertexBuffer(0, slice.buffer, slice.offset);
            pass.setBindGroup(0, this.device.createBindGroup({
                layout: pipeline.getBindGroupLayout(0),
                entries: [
                    { binding: 0, resource: textureView },
                    { binding: 1, resource: this.pixelSampler ||
                        (this.pixelSampler = this.device.createSampler({
                            minFilter: "nearest", magFilter: "nearest",
                        })) },
                ],
            }));
            pass.draw(6, 1, 0, 0);
            ++this.stats.draws;
            void texture;
        },

        pixelPipeline(discardZeroAlpha) {
            const s = this.current;
            const targets = this.passTargets;
            if (!targets) return null;
            const alpha = s.enabled.has(GL.ALPHA_TEST) ?
                (ALPHA_TEST_NAMES[s.alphaFunc.func] || "always") : "always";
            const key = [discardZeroAlpha ? 1 : 0, alpha, s.alphaFunc.ref,
                s.enabled.has(GL.DEPTH_TEST) ? s.depthFunc : "off",
                s.depthMask ? 1 : 0,
                s.enabled.has(GL.STENCIL_TEST) ? stencilKey(s) : "off",
                s.enabled.has(GL.BLEND) ? blendKey(s) : "off",
                s.colorMask.map(v => v ? 1 : 0).join(""),
                targets.color.map(c => c ? c.format : "-").join(","),
                targets.depthFormat || "-"].join("|");
            this.pixelPipelineCache = this.pixelPipelineCache || new Map();
            let pipeline = this.pixelPipelineCache.get(key);
            if (pipeline) return pipeline;
            const conditions = [];
            if (discardZeroAlpha) conditions.push("color.a <= 0.0");
            if (alpha === "never") conditions.push("true");
            else if (alpha !== "always") {
                const op = {
                    less: "<", equal: "==", lequal: "<=", greater: ">",
                    notequal: "!=", gequal: ">=",
                }[alpha];
                if (op) conditions.push("!(color.a " + op + " " +
                    Number(s.alphaFunc.ref).toPrecision(9) + ")");
            }
            const outputFields = targets.color.map((target, i) => target ?
                "    @location(" + i + ") color" + i + " : vec4<f32>," : "").join("\n");
            const outputWrites = targets.color.map((target, i) => target ?
                "    out.color" + i + " = color;" : "").join("\n");
            const code = `
struct VSIn { @location(0) position : vec4<f32>, @location(1) uv : vec2<f32>, }
struct Varying { @builtin(position) position : vec4<f32>, @location(0) uv : vec2<f32>, }
@vertex fn vs_main(v : VSIn) -> Varying {
    var out : Varying; out.position = v.position; out.uv = v.uv; return out;
}
@group(0) @binding(0) var pixels : texture_2d<f32>;
@group(0) @binding(1) var pixelSampler : sampler;
struct PixelOut {
${outputFields}
}
@fragment fn fs_main(v : Varying) -> PixelOut {
    let color = textureSample(pixels, pixelSampler, v.uv);
    ${conditions.length ? "if (" + conditions.join(" || ") + ") { discard; }" : ""}
    var out : PixelOut;
${outputWrites}
    return out;
}`;
            const colorTargets = targets.color.map(target => target ? {
                format: target.format,
                blend: s.enabled.has(GL.BLEND) ? gpuBlendState(s) : undefined,
                writeMask: (s.colorMask[0] ? 1 : 0) | (s.colorMask[1] ? 2 : 0) |
                    (s.colorMask[2] ? 4 : 0) | (s.colorMask[3] ? 8 : 0),
            } : null);
            const module = this.shaderModule(code);
            const descriptor = {
                label: "GL pixel rectangle pipeline",
                layout: "auto",
                vertex: { module, entryPoint: "vs_main", buffers: [{
                    arrayStride: 24, stepMode: "vertex", attributes: [
                        { shaderLocation: 0, format: "float32x4", offset: 0 },
                        { shaderLocation: 1, format: "float32x2", offset: 16 },
                    ],
                }] },
                fragment: { module, entryPoint: "fs_main", targets: colorTargets },
                primitive: { topology: "triangle-list", cullMode: "none" },
                multisample: { count: 1 },
            };
            if (targets.depthFormat) {
                descriptor.depthStencil = {
                    format: targets.depthFormat,
                    depthWriteEnabled: !!(s.enabled.has(GL.DEPTH_TEST) && s.depthMask),
                    depthCompare: s.enabled.has(GL.DEPTH_TEST) ?
                        (COMPARE_FUNCTIONS[s.depthFunc] || "less") : "always",
                    ...(targets.depthFormat.indexOf("stencil") >= 0 &&
                        s.enabled.has(GL.STENCIL_TEST) ? gpuStencilState(s) : {}),
                };
            }
            try {
                pipeline = this.device.createRenderPipeline(descriptor);
            } catch (error) {
                this.refuse("glDrawPixels", "could not create pixel pipeline",
                    { message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.pixelPipelineCache.set(key, pipeline);
            return pipeline;
        },

        accum(op, value) {
            const ACCUM = 0x0100, LOAD = 0x0101, RETURN = 0x0102;
            const MULT = 0x0103, ADD = 0x0104;
            if (![ACCUM, LOAD, RETURN, MULT, ADD].includes(op))
                return this.refuse("glAccum", "invalid accumulation operation",
                    { op }, GL.INVALID_ENUM);
            this.endPass();
            const targets = this.currentTargets();
            if (!targets || !targets.color[0])
                return this.refuse("glAccum", "no colour buffer is bound", {},
                    GL.INVALID_OPERATION);
            const accum = this.ensureAccumBuffer(targets);
            const returning = op === RETURN;
            const destination = returning ? targets.color[0].view : accum.nextView;
            const targetFormat = returning ? targets.color[0].format : "rgba16float";
            const pipeline = this.accumPipeline(op, targetFormat);
            if (!pipeline) return;
            const params = this.allocateUniform(16);
            if (!params) return;
            new Float32Array(this.uniformStaging.buffer, params.offset, 4)
                .set([value, 0, 0, 0]);
            this.device.queue.writeBuffer(params.buffer, params.offset,
                this.uniformStaging, params.offset, params.size);
            const pass = this.ensureEncoder().beginRenderPass({
                label: "GL accumulation operation",
                colorAttachments: [{ view: destination, loadOp: "load",
                    storeOp: "store" }],
            });
            this.applyAccumScissor(pass, targets);
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, this.device.createBindGroup({
                layout: pipeline.getBindGroupLayout(0),
                entries: [
                    { binding: 0, resource: accum.currentView },
                    { binding: 1, resource: returning ? this.fallbackView :
                        targets.color[0].view },
                    { binding: 2, resource: { buffer: params.buffer,
                        offset: params.offset, size: 16 } },
                ],
            }));
            pass.draw(3, 1, 0, 0);
            pass.end();
            if (!returning) {
                const texture = accum.currentTexture;
                accum.currentTexture = accum.nextTexture;
                accum.currentView = accum.nextView;
                accum.nextTexture = texture;
                accum.nextView = texture.createView();
            }
        },

        ensureAccumBuffer(targets) {
            const width = Math.max(1, targets.width);
            const height = Math.max(1, targets.height);
            const key = this.current.id + ":" + this.current.drawFramebuffer +
                ":" + width + "x" + height;
            if (this.accumBuffer && this.accumBuffer.key === key)
                return this.accumBuffer;
            if (this.accumBuffer) {
                this.retire(this.accumBuffer.currentTexture);
                this.retire(this.accumBuffer.nextTexture);
            }
            const create = label => this.device.createTexture({
                label,
                size: { width, height, depthOrArrayLayers: 1 },
                format: "rgba16float",
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT |
                    TEXTURE_USAGE_TEXTURE_BINDING | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_COPY_DST,
            });
            const currentTexture = create("GL accumulation buffer A");
            const nextTexture = create("GL accumulation buffer B");
            this.accumBuffer = {
                key, width, height,
                currentTexture, currentView: currentTexture.createView(),
                nextTexture, nextView: nextTexture.createView(),
            };
            return this.accumBuffer;
        },

        applyAccumScissor(pass, targets) {
            const s = this.current;
            if (s.enabled.has(GL.SCISSOR_TEST) && s.scissor.set) {
                const x = clamp(s.scissor.x, 0, targets.width);
                const y = clamp(s.scissor.y, 0, targets.height);
                pass.setScissorRect(x, y,
                    Math.max(0, Math.min(s.scissor.width, targets.width - x)),
                    Math.max(0, Math.min(s.scissor.height, targets.height - y)));
            } else {
                pass.setScissorRect(0, 0, targets.width, targets.height);
            }
        },

        accumPipeline(op, targetFormat) {
            this.accumPipelineCache = this.accumPipelineCache || new Map();
            const returning = op === 0x0102;
            const mask = returning ? this.current.colorMask.map(v => v ? 1 : 0)
                .join("") : "1111";
            const key = op + "|" + targetFormat + "|" + mask;
            let pipeline = this.accumPipelineCache.get(key);
            if (pipeline) return pipeline;
            const expression = {
                0x0100: "oldAccum + framebuffer * params.value.x",
                0x0101: "framebuffer * params.value.x",
                0x0102: "oldAccum * params.value.x",
                0x0103: "oldAccum * params.value.x",
                0x0104: "oldAccum + vec4<f32>(params.value.x)",
            }[op];
            const code = `
struct Params { value : vec4<f32>, }
@group(0) @binding(0) var accumulation : texture_2d<f32>;
@group(0) @binding(1) var colorBuffer : texture_2d<f32>;
@group(0) @binding(2) var<uniform> params : Params;
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment fn fs_main(@builtin(position) p : vec4<f32>) -> @location(0) vec4<f32> {
    let xy = vec2<i32>(p.xy);
    let oldAccum = textureLoad(accumulation, xy, 0);
    let framebuffer = textureLoad(colorBuffer, xy, 0);
    return ${expression};
}`;
            const module = this.shaderModule(code);
            const writeMask = returning ?
                (this.current.colorMask[0] ? 1 : 0) |
                (this.current.colorMask[1] ? 2 : 0) |
                (this.current.colorMask[2] ? 4 : 0) |
                (this.current.colorMask[3] ? 8 : 0) : 15;
            try {
                pipeline = this.device.createRenderPipeline({
                    label: "GL accumulation pipeline",
                    layout: "auto",
                    vertex: { module, entryPoint: "vs_main" },
                    fragment: { module, entryPoint: "fs_main",
                        targets: [{ format: targetFormat, writeMask }] },
                    primitive: { topology: "triangle-list" },
                });
            } catch (error) {
                this.refuse("glAccum", "could not create accumulation pipeline",
                    { message: String(error) }, GL.INVALID_OPERATION);
                return null;
            }
            this.accumPipelineCache.set(key, pipeline);
            return pipeline;
        },

        accumClearPipeline() {
            const color = Array.from(this.current.clearAccum)
                .map(value => Number(value).toPrecision(9));
            const key = color.join(",");
            this.accumClearPipelineCache = this.accumClearPipelineCache || new Map();
            let pipeline = this.accumClearPipelineCache.get(key);
            if (pipeline) return pipeline;
            const code = `
@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
    let x = f32((i << 1u) & 2u) * 2.0 - 1.0;
    let y = f32(i & 2u) * 2.0 - 1.0;
    return vec4<f32>(x, y, 0.0, 1.0);
}
@fragment fn fs_main() -> @location(0) vec4<f32> {
    return vec4<f32>(${color.join(", ")});
}`;
            const module = this.shaderModule(code);
            pipeline = this.device.createRenderPipeline({
                label: "GL accumulation clear pipeline", layout: "auto",
                vertex: { module, entryPoint: "vs_main" },
                fragment: { module, entryPoint: "fs_main",
                    targets: [{ format: "rgba16float" }] },
                primitive: { topology: "triangle-list" },
            });
            this.accumClearPipelineCache.set(key, pipeline);
            return pipeline;
        },
        setRasterPos(x, y, z, w) {
            // The raster position is transformed like a vertex; keeping it is
            // cheap and glWindowPos-based code depends on reading it back.
            const s = this.current;
            const clip = transformPoint4(this.topOf(GL.PROJECTION),
                transformPoint4(this.topOf(GL.MODELVIEW),
                    new Float32Array([x, y, z, w]), new Float32Array(4)),
                new Float32Array(4));
            s.current.rasterValid = clip[3] !== 0;
            if (!s.current.rasterValid) return;
            const ndcX = clip[0] / clip[3], ndcY = clip[1] / clip[3];
            const ndcZ = clip[2] / clip[3];
            s.current.rasterPos[0] = s.viewport.x +
                (ndcX * 0.5 + 0.5) * s.viewport.width;
            s.current.rasterPos[1] = s.viewport.y +
                (ndcY * 0.5 + 0.5) * s.viewport.height;
            s.current.rasterPos[2] = clamp((ndcZ * 0.5 + 0.5), 0, 1);
            s.current.rasterPos[3] = 1 / clip[3];
        },
        /*
         * glProgramStringARB compiles immediately, the way the extension
         * specifies: the program's error state and GL_PROGRAM_ERROR_POSITION_ARB
         * are readable right afterwards, and a game that checks them expects an
         * answer rather than a promise.
         */
        programStringARB(target, source) {
            const program = this.arbProgramFor(target);
            if (!program)
                return this.refuse("glProgramStringARB", "no ARB program bound",
                    { target }, GL.INVALID_OPERATION);
            program.source = source;
            program.target = target;
            program.compiled = arbProgram.compileARBProgram(source, {});
            if (program.variants) program.variants.clear();
            if (!program.compiled.ok) {
                /*
                 * A program the *application* wrote wrongly is not a host
                 * refusal: the extension defines exactly how to report it, and
                 * an app that submits a deliberately bad program to check its
                 * error handling -- which is what a conformance viewer does --
                 * is behaving correctly. Counting it in stats.refusals would
                 * make that counter useless as "how much of this frame did the
                 * host fail to draw". So it takes GL's own channel: the error,
                 * the error string and the error position, and one warning
                 * rather than one error.
                 */
                this.arbErrorString = program.compiled.log;
                this.arbErrorPosition = program.compiled.errorPosition >= 0 ?
                    program.compiled.errorPosition : 0;
                this.current.arbErrorString = this.arbErrorString;
                this.current.arbErrorPosition = this.arbErrorPosition;
                this.setError(GL.INVALID_OPERATION);
                this.warnOnce("arbProgramCompile",
                    "an ARB program did not compile; the app can read the " +
                    "reason from GL_PROGRAM_ERROR_STRING_ARB",
                    { target, log: program.compiled.log,
                      position: this.arbErrorPosition });
                return;
            }
            this.arbErrorString = "";
            this.arbErrorPosition = -1;
            this.current.arbErrorString = "";
            this.current.arbErrorPosition = -1;
            arbParameterStorage(program, PROGRAM_PARAMETER_ENV);
            ++this.stats.shaderLinks;
        },

        /*
         * {kind, target, index, count} then count*4 floats, or {kind, target,
         * index, reserved} then four doubles. openglproxy sends the parameter
         * kind first -- V86GL_PROGRAM_PARAMETER_ENV is 1 and _LOCAL is 2 --
         * and the target second.
         */
        programParameterARB(view, offset, size, doublePrecision) {
            const stride = doublePrecision ? 8 : 4;
            if (size < 16 + 4 * stride)
                throw new GLStreamError("ARB parameter record is short");
            const kind = view.getUint32(offset, true);
            const target = view.getUint32(offset + 4, true);
            const index = view.getUint32(offset + 8, true);
            // The double-precision record carries exactly one parameter; the
            // float one carries glProgramEnvParameters4fvEXT's whole run.
            const count = doublePrecision ? 1 :
                Math.max(1, view.getUint32(offset + 12, true));
            const program = this.arbProgramFor(target);
            if (!program)
                return this.refuse("glProgramParameterARB",
                    "no ARB program is bound", { target },
                    GL.INVALID_OPERATION);
            if (index >= arbProgram.MAX_PROGRAM_PARAMETERS ||
                    count > arbProgram.MAX_PROGRAM_PARAMETERS - index)
                return this.refuse("glProgramParameterARB",
                    "parameter index is beyond the advertised count",
                    { index, count }, GL.INVALID_VALUE);
            if (16 + count * 4 * stride > size)
                throw new GLStreamError("ARB parameter record is truncated");
            const storage = arbParameterStorage(program, kind);
            for (let i = 0; i < count * 4; ++i) {
                const at = offset + 16 + i * stride;
                storage[index * 4 + i] = doublePrecision ?
                    view.getFloat64(at, true) : view.getFloat32(at, true);
            }
        },

        queryProgramivARB(target, pname) {
            const program = this.arbProgramFor(target);
            switch (pname) {
            case GL.PROGRAM_LENGTH_ARB:
                return program ? program.source.length : 0;
            case GL.PROGRAM_FORMAT_ARB:
                return GL.PROGRAM_FORMAT_ASCII_ARB;
            case GL.PROGRAM_BINDING_ARB:
                return target === GL.VERTEX_PROGRAM_ARB ?
                    this.current.arbVertexProgram : this.current.arbFragmentProgram;
            case GL.PROGRAM_INSTRUCTIONS_ARB:
            case GL.PROGRAM_NATIVE_INSTRUCTIONS_ARB:
                return program && program.compiled && program.compiled.ok ?
                    program.compiled.reflection.instructionCount : 0;
            case GL.PROGRAM_TEMPORARIES_ARB:
            case GL.PROGRAM_NATIVE_TEMPORARIES_ARB:
                return program && program.compiled && program.compiled.ok ?
                    program.compiled.reflection.temporaryCount : 0;
            case GL.PROGRAM_PARAMETERS_ARB:
            case GL.PROGRAM_NATIVE_PARAMETERS_ARB:
            case GL.MAX_PROGRAM_PARAMETERS_ARB:
            case GL.MAX_PROGRAM_NATIVE_PARAMETERS_ARB:
            case GL.MAX_PROGRAM_ENV_PARAMETERS_ARB:
            case GL.MAX_PROGRAM_LOCAL_PARAMETERS_ARB:
                return arbProgram.MAX_PROGRAM_PARAMETERS;
            case GL.MAX_PROGRAM_INSTRUCTIONS_ARB:
            case GL.MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB:
                return 4096;
            case GL.MAX_PROGRAM_TEMPORARIES_ARB:
            case GL.MAX_PROGRAM_NATIVE_TEMPORARIES_ARB:
                return arbProgram.MAX_TEMPORARIES;
            case GL.PROGRAM_UNDER_NATIVE_LIMITS_ARB:
                return program && program.compiled && program.compiled.ok ? 1 : 0;
            case GL.PROGRAM_ERROR_POSITION_ARB:
                // -1 means "the last ProgramString succeeded"; otherwise the
                // character offset the parser stopped at.
                return this.current && this.current.arbErrorPosition !== undefined ?
                    this.current.arbErrorPosition : -1;
            default:
                return 0;
            }
        },

        /* {kind, target, index, status, data_size, reserved} then the four
         * components at 24 -- the read-back twin of programParameterARB. */
        queryProgramParameterARB(view, offset, size, doublePrecision) {
            if (size < 24) throw new GLStreamError("ARB query record is short");
            const kind = view.getUint32(offset, true);
            const target = view.getUint32(offset + 4, true);
            const index = view.getUint32(offset + 8, true);
            const program = this.arbProgramFor(target);
            const stride = doublePrecision ? 8 : 4;
            if (!program || index >= arbProgram.MAX_PROGRAM_PARAMETERS ||
                    24 + 4 * stride > size) {
                view.setUint32(offset + 12, SYNC_STATUS_FAILED, true);
                return;
            }
            const storage = arbParameterStorage(program, kind);
            view.setUint32(offset + 12, SYNC_STATUS_OK, true);
            for (let c = 0; c < 4; ++c) {
                const at = offset + 24 + c * stride;
                if (doublePrecision) view.setFloat64(at, storage[index * 4 + c], true);
                else view.setFloat32(at, storage[index * 4 + c], true);
            }
        },
        arbProgramFor(target) {
            const s = this.current;
            const name = target === GL.VERTEX_PROGRAM_ARB ?
                s.arbVertexProgram : s.arbFragmentProgram;
            return name ? s.shareGroup.arbPrograms.get(name) || null : null;
        },
    });

    /*
     * Repacks a 256-aligned readback into the format the guest asked for.
     * GL's rows run bottom-up in the same direction the framebuffer does here,
     * so no vertical flip is involved -- which is the point of flipping in the
     * vertex shader instead.
     */
    function packReadback(mapped, bytesPerRow, width, height, format, type,
            sourceFormat, capacity) {
        const bgra = sourceFormat.indexOf("bgra") === 0;
        const components = SOURCE_COMPONENTS[format] || 4;
        const out = new Uint8Array(capacity);
        let dst = 0;
        for (let row = 0; row < height; ++row) {
            let src = row * bytesPerRow;
            for (let x = 0; x < width; ++x) {
                const r = mapped[src + (bgra ? 2 : 0)];
                const g = mapped[src + 1];
                const b = mapped[src + (bgra ? 0 : 2)];
                const a = mapped[src + 3];
                if (type === GL.UNSIGNED_BYTE) {
                    switch (format) {
                    case GL.RGBA: out[dst] = r; out[dst+1] = g; out[dst+2] = b; out[dst+3] = a; break;
                    case GL.BGRA: out[dst] = b; out[dst+1] = g; out[dst+2] = r; out[dst+3] = a; break;
                    case GL.RGB: out[dst] = r; out[dst+1] = g; out[dst+2] = b; break;
                    case GL.BGR: out[dst] = b; out[dst+1] = g; out[dst+2] = r; break;
                    case GL.ALPHA: out[dst] = a; break;
                    case GL.LUMINANCE: out[dst] = r; break;
                    default: out[dst] = r; break;
                    }
                    dst += components;
                } else if (type === GL.UNSIGNED_SHORT_5_6_5) {
                    const packed = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
                    out[dst] = packed & 0xff;
                    out[dst + 1] = packed >> 8;
                    dst += 2;
                } else {
                    out[dst] = r; out[dst+1] = g; out[dst+2] = b; out[dst+3] = a;
                    dst += 4;
                }
                src += 4;
                if (dst >= capacity) return out;
            }
        }
        return out;
    }

    /* ================================================================== */
    /* Executor: glGet* answers and capability reporting                  */
    /* ================================================================== */

    /*
     * The extension string and every GL_MAX_* are decided by what this
     * executor actually implements against this adapter -- never guessed.
     * Advertising a capability nothing backs is the mistake the D3D8 path made
     * once and paid for; see plan section 4.14.
     */
    Object.assign(GLWebGPUExecutor.prototype, {

        extensionString() {
            const list = [
                "GL_ARB_multitexture", "GL_ARB_texture_env_add",
                "GL_ARB_texture_env_combine", "GL_ARB_texture_env_dot3",
                "GL_ARB_texture_env_crossbar", "GL_ARB_texture_cube_map",
                "GL_ARB_texture_border_clamp", "GL_ARB_texture_mirrored_repeat",
                "GL_ARB_texture_compression", "GL_SGI_color_matrix",
                "GL_ARB_texture_non_power_of_two", "GL_ARB_depth_texture",
                "GL_ARB_shadow", "GL_ARB_point_parameters", "GL_ARB_point_sprite",
                "GL_ARB_transpose_matrix", "GL_ARB_window_pos",
                "GL_ARB_vertex_buffer_object", "GL_ARB_occlusion_query",
                "GL_ARB_multisample", "GL_ARB_shader_objects",
                "GL_ARB_vertex_shader", "GL_ARB_fragment_shader",
                "GL_ARB_shading_language_100", "GL_ARB_draw_buffers",
                "GL_EXT_texture3D", "GL_EXT_texture_lod_bias",
                "GL_EXT_texture_edge_clamp", "GL_EXT_blend_color",
                "GL_EXT_blend_minmax", "GL_EXT_blend_subtract",
                "GL_EXT_blend_func_separate", "GL_EXT_blend_equation_separate",
                "GL_EXT_stencil_wrap", "GL_EXT_stencil_two_side",
                "GL_EXT_secondary_color", "GL_EXT_fog_coord",
                "GL_EXT_packed_pixels", "GL_EXT_rescale_normal",
                "GL_EXT_separate_specular_color", "GL_EXT_bgra",
                "GL_EXT_framebuffer_object", "GL_EXT_framebuffer_blit",
                "GL_EXT_paletted_texture", "GL_EXT_generate_mipmap",
                "GL_SGIS_generate_mipmap", "GL_SGIS_texture_edge_clamp",
                "GL_SGIS_texture_lod", "GL_NV_blend_square",
            ];
            // Only advertised when the adapter really has the BC formats: the
            // CPU decode path keeps the picture right, but a guest that sees
            // S3TC will hand us compressed data forever, and saying so honestly
            // lets it choose.
            if (this.deviceFeatures.bc)
                list.push("GL_EXT_texture_compression_s3tc");
            if (this.deviceFeatures.float32Filterable)
                list.push("GL_ARB_texture_float", "GL_ARB_half_float_pixel");
            if (this.deviceFeatures.depthClipControl)
                list.push("GL_ARB_depth_clamp");
            list.push("GL_EXT_texture_filter_anisotropic");
            return list.join(" ");
        },

        queryString(pname) {
            switch (pname) {
            case GL.VENDOR: return "Anthropic v86gl";
            case GL.RENDERER: return "v86 WebGPU bridge";
            case GL.VERSION: return "2.1 (v86gl/WebGPU)";
            case GL.SHADING_LANGUAGE_VERSION: return "1.20";
            case GL.EXTENSIONS: return this.extensionString();
            case GL.PROGRAM_ERROR_STRING_ARB:
                // Empty after a successful ProgramString, which is what the
                // extension specifies -- not null, which would leave the guest
                // reporting "unsupported query" for a legal one.
                return this.current ? (this.current.arbErrorString || "") : "";
            default: return null;
            }
        },

        queryInteger(pname) {
            const limits = this.limits || {};
            const s = this.current;
            switch (pname) {
            case 0x76380001: // private v86gl host-capability bitset
                return 0x1 | 0x2 |
                    (this.deviceFeatures.float32Filterable ? 0x4 : 0) | 0x8;
            case GL.MAX_TEXTURE_SIZE:
                return Math.min(16384, limits.maxTextureDimension2D || 8192);
            case GL.MAX_3D_TEXTURE_SIZE:
                return Math.min(2048, limits.maxTextureDimension3D || 2048);
            case GL.MAX_CUBE_MAP_TEXTURE_SIZE:
                return Math.min(16384, limits.maxTextureDimension2D || 8192);
            case GL.MAX_TEXTURE_UNITS: return MAX_TEXTURE_UNITS;
            case GL.MAX_TEXTURE_COORDS: return MAX_TEXTURE_COORDS;
            case GL.MAX_TEXTURE_IMAGE_UNITS: return 16;
            case GL.MAX_VERTEX_TEXTURE_IMAGE_UNITS: return 16;
            case GL.MAX_COMBINED_TEXTURE_IMAGE_UNITS: return 24;
            case GL.MAX_VERTEX_ATTRIBS: return MAX_VERTEX_ATTRIBS;
            case GL.MAX_VARYING_FLOATS:
                return translator.MAX_INTER_STAGE_SLOTS * 4;
            case GL.MAX_VERTEX_UNIFORM_COMPONENTS: return 1024;
            case GL.MAX_FRAGMENT_UNIFORM_COMPONENTS: return 1024;
            case GL.MAX_DRAW_BUFFERS:
                return Math.min(MAX_DRAW_BUFFERS, limits.maxColorAttachments || 8);
            case GL.MAX_COLOR_ATTACHMENTS:
                return Math.min(MAX_DRAW_BUFFERS, limits.maxColorAttachments || 8);
            case GL.MAX_RENDERBUFFER_SIZE:
                return Math.min(16384, limits.maxTextureDimension2D || 8192);
            case GL.MAX_LIGHTS: return MAX_LIGHTS;
            case GL.MAX_CLIP_PLANES: return MAX_CLIP_PLANES;
            case GL.MAX_MODELVIEW_STACK_DEPTH: return MODELVIEW_STACK_DEPTH;
            case GL.MAX_PROJECTION_STACK_DEPTH: return OTHER_STACK_DEPTH;
            case GL.MAX_TEXTURE_STACK_DEPTH: return OTHER_STACK_DEPTH;
            case GL.MAX_TEXTURE_MAX_ANISOTROPY_EXT: return 16;
            case GL.MAX_ELEMENTS_VERTICES: return 65536;
            case GL.MAX_ELEMENTS_INDICES: return 65536;
            case GL.SAMPLE_BUFFERS: return 0;
            // GL_SAMPLES is zero when the selected framebuffer has no
            // multisample buffer; one is the raster sample count, not the GL
            // query value for this pixel format.
            case GL.SAMPLES: return 0;
            case GL.SUBPIXEL_BITS: return 8;
            case GL.RED_BITS: case GL.GREEN_BITS:
            case GL.BLUE_BITS: case GL.ALPHA_BITS: return 8;
            case GL.DEPTH_BITS: return 24;
            case GL.STENCIL_BITS: return 8;
            case GL.MAX_VIEWPORT_DIMS:
                return Math.min(16384, limits.maxTextureDimension2D || 8192);
            case GL.NUM_COMPRESSED_TEXTURE_FORMATS:
                return this.deviceFeatures.bc ? 4 : 0;
            case GL.PROGRAM_ERROR_POSITION_ARB:
                // This is the glGetIntegerv spelling, which is the one the
                // extension actually defines and the one the guest uses. It
                // must be -1 when the last glProgramStringARB succeeded: the
                // generic default of 0 reads as "an error at character 0", so
                // a conformance viewer reports a failure on a good program.
                return s && s.arbErrorPosition !== undefined ?
                    s.arbErrorPosition : -1;
            default: break;
            }
            if (!s) return null;
            switch (pname) {
            case GL.VIEWPORT: return s.viewport.width;
            case GL.ACTIVE_TEXTURE: return GL.TEXTURE0 + s.activeTexture;
            case GL.CLIENT_ACTIVE_TEXTURE:
                return GL.TEXTURE0 + s.clientActiveTexture;
            case GL.CURRENT_PROGRAM: return s.currentProgram;
            case GL.ARRAY_BUFFER_BINDING: return s.arrayBuffer;
            case GL.ELEMENT_ARRAY_BUFFER_BINDING: return s.elementArrayBuffer;
            case GL.PIXEL_PACK_BUFFER_BINDING: return s.pixelPackBuffer;
            case GL.PIXEL_UNPACK_BUFFER_BINDING: return s.pixelUnpackBuffer;
            case GL.FRAMEBUFFER_BINDING: return s.drawFramebuffer;
            case GL.RENDERBUFFER_BINDING: return s.renderbuffer;
            case GL.TEXTURE_BINDING_2D:
                return s.textureUnits[s.activeTexture].bindings[GL.TEXTURE_2D] || 0;
            case GL.MATRIX_MODE: return s.matrixMode;
            case GL.DEPTH_FUNC: return s.depthFunc;
            case GL.CULL_FACE_MODE: return s.cullFace;
            case GL.FRONT_FACE: return s.frontFace;
            case GL.SHADE_MODEL: return s.shadeModel;
            case GL.BLEND_SRC: return s.blend.srcRGB;
            case GL.BLEND_DST: return s.blend.dstRGB;
            case GL.ALPHA_TEST_FUNC: return s.alphaFunc.func;
            case GL.STENCIL_FUNC: return s.stencil.front.func;
            case GL.STENCIL_REF: return s.stencil.front.ref;
            case GL.STENCIL_VALUE_MASK: return s.stencil.front.valueMask;
            case GL.STENCIL_WRITEMASK: return s.stencil.front.writeMask;
            case GL.PACK_ALIGNMENT: return s.pixelStore.packAlignment;
            case GL.UNPACK_ALIGNMENT: return s.pixelStore.unpackAlignment;
            case GL.RENDER_MODE: return s.renderMode;
            default: return 0;
            }
        },
    });

    /* ================================================================== */
    /* Public API                                                         */
    /* ================================================================== */

    function installGLWebGPUExecutor(canvas, options) {
        const executor = new GLWebGPUExecutor(canvas, options);
        // Starting acquisition now rather than on the first batch matters:
        // the guest's synchronous queries are answered inside the port write
        // that delivered them, so the device has to already exist by then.
        executor.initialize().catch(() => { /* reported by initialize */ });
        return executor;
    }

    const api = {
        EXECUTOR_REVISION,
        GLWebGPUExecutor, installGLWebGPUExecutor,
        // Exported for the test suite.
        expandIndices, expandIndexArray, expandedIndexCount,
        convertPixels, decodeDXT, storageFormatFor, readSourceTexel,
        applyBaseFormat, normalMatrixOf, multiply4, invert4, transpose4,
        createContextState, buildHandlerTable, activeShaderBindings,
        PRIMITIVE_TOPOLOGY, BLEND_FACTORS, COMPARE_FUNCTIONS,
        STENCIL_OPERATIONS, ADDRESS_MODES,
        GLWG_RESPONSE_REGION_BYTES, GLWG_QUERY_REGION_BYTES,
        GLWG_READBACK_REGION_OFFSET, GLWG_HEARTBEAT_OFFSET,
        GLWG_RESPONSE_PENDING, GLWG_RESPONSE_OK, GLWG_RESPONSE_FAILED,
        SYNC_STATUS_PENDING, SYNC_STATUS_OK, SYNC_STATUS_FAILED,
    };
    global.installGLWebGPUExecutor = installGLWebGPUExecutor;
    global.GLWebGPUExecutorModule = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/browser/glbridge/gl-webgpu/gl_fixed_function.js                                      0000644 0000000 0000000 00000154466 00000000000 021652  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The OpenGL fixed-function pipeline, generated as WGSL.
//
// There is no interpreter here: a signature -- which lights are on, what each
// texture unit's environment does, whether fog is linear or exponential -- is
// turned into one vertex and one fragment shader, and the pair is cached. That
// is the same shape d3d9_executor.js uses for D3D9's fixed function, but none
// of its *content* transfers. GL's GL_COMBINE with its per-argument operands,
// independent RGB and alpha functions, RGB_SCALE and GL_TEXTURE<n> crossbar
// sources is a different machine from D3D9's texture stages, and GL's lighting
// differs from D3D9's in the attenuation and spotlight terms. Copying the D3D9
// tables would produce a picture that is close enough to look right and wrong
// everywhere it matters.
//
// The state uniforms come from gl_state_layout.js, shared with the GLSL
// compatibility built-ins, so ftransform() in a shader and the transform here
// are literally the same expression -- which is what GL requires for a depth
// pre-pass drawn one way and shaded the other not to z-fight.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md sections 4.5 and 10.

(function(global) {
    "use strict";

    const stateLayout = (typeof require === "function" && typeof module !== "undefined") ?
        require("./gl_state_layout.js") : global.GLStateLayout;
    const translator = (typeof require === "function" && typeof module !== "undefined") ?
        require("./gl_shader_translator.js") : global.GLShaderTranslator;

    const FIXED_FUNCTION_REVISION = 2;

    const MAX_TEXTURE_UNITS = stateLayout.MAX_TEXTURE_UNITS;
    const MAX_LIGHTS = stateLayout.MAX_LIGHTS;
    const ATTR = translator.COMPAT_ATTRIBUTE_LOCATIONS;
    const POINT_CORNER_LOCATION = translator.POINT_CORNER_LOCATION;

    /* ================================================================== */
    /* Signature                                                          */
    /* ================================================================== */

    /*
     * The signature is the cache key and the generator's only input. Anything
     * that changes the generated code must appear in it: a field that changes
     * the picture but not the signature shows up as "I changed the state and
     * nothing happened", which is the hardest class of bug in this file to
     * find. gl_state_signature_test.js walks every field to keep that honest.
     *
     * {
     *   attributes: { position:{components}, normal:bool, color:bool,
     *                 secondaryColor:bool, fogCoord:bool,
     *                 texCoord:[8 x {components}|null] },
     *   lighting: { enabled, twoSide, localViewer, separateSpecular,
     *               normalMode: "none"|"normalize"|"rescale",
     *               colorMaterial: {enabled, face, mode},
     *               lights: [8 x {enabled, positional, spot}] },
     *   fog: { enabled, mode: "linear"|"exp"|"exp2", coordSource: "depth"|"coord" },
     *   texture: [8 x { enabled, target:"1D"|"2D"|"3D"|"Cube", shadow,
     *                   format:"ALPHA"|"LUMINANCE"|"LUMINANCE_ALPHA"|
     *                          "INTENSITY"|"RGB"|"RGBA",
     *                   matrix: bool,
     *                   texGen: [4 x null|"OBJECT"|"EYE"|"SPHERE"|"REFLECTION"|"NORMAL"],
     *                   env: {...} } ],
     *   alphaTest: "always"|"never"|"less"|"lequal"|"equal"|"gequal"|"greater"|"notequal",
     *   clipPlaneCount: 0..6,
     *   pointSprite: bool,
     *   flatShading: bool,
     *   colorTargets: 1..8,
     * }
     */

    function normalizeSignature(sig) {
        const s = sig || {};
        const attributes = s.attributes || {};
        const texCoord = [];
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const entry = (attributes.texCoord || [])[i];
            texCoord.push(entry ? { components: entry.components || 4 } : null);
        }
        const lighting = s.lighting || {};
        const lights = [];
        for (let i = 0; i < MAX_LIGHTS; ++i) {
            const l = (lighting.lights || [])[i];
            lights.push(l && l.enabled ? {
                enabled: true,
                positional: !!l.positional,
                spot: !!l.spot,
            } : { enabled: false, positional: false, spot: false });
        }
        const texture = [];
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const t = (s.texture || [])[i];
            texture.push(t && t.enabled ? {
                enabled: true,
                target: t.target || "2D",
                shadow: !!t.shadow,
                format: t.format || "RGBA",
                matrix: !!t.matrix,
                texGen: (t.texGen || [null, null, null, null]).slice(0, 4),
                env: normalizeEnv(t.env),
            } : { enabled: false });
        }
        return {
            // ARB vertex programs expose the historical compatibility
            // varying ABI: primary/secondary/fog at locations 0/1/2 and
            // texture coordinates at 3+n. A fixed fragment stage paired with
            // one must consume that ABI instead of our compact internal one.
            varyingInterface: s.varyingInterface === "arb" ? "arb" : "packed",
            extraStateFields: Array.from(new Set(s.extraStateFields || [])).sort(),
            attributes: {
                position: { components: (attributes.position &&
                    attributes.position.components) || 4 },
                normal: !!attributes.normal,
                color: !!attributes.color,
                secondaryColor: !!attributes.secondaryColor,
                fogCoord: !!attributes.fogCoord,
                texCoord,
            },
            lighting: {
                enabled: !!lighting.enabled,
                twoSide: !!lighting.twoSide,
                localViewer: !!lighting.localViewer,
                separateSpecular: !!lighting.separateSpecular,
                normalMode: lighting.normalMode || "none",
                colorMaterial: lighting.colorMaterial && lighting.colorMaterial.enabled ?
                    { enabled: true,
                      face: lighting.colorMaterial.face || "FRONT_AND_BACK",
                      mode: lighting.colorMaterial.mode || "AMBIENT_AND_DIFFUSE" } :
                    { enabled: false },
                lights,
            },
            fog: s.fog && s.fog.enabled ? {
                enabled: true,
                mode: s.fog.mode || "linear",
                coordSource: s.fog.coordSource || "depth",
            } : { enabled: false },
            texture,
            alphaTest: s.alphaTest || "always",
            clipPlaneCount: Math.max(0, Math.min(6, s.clipPlaneCount || 0)),
            pointSprite: !!s.pointSprite,
            pointCoordLowerLeft: !!s.pointCoordLowerLeft,
            polygonStipple: !!s.polygonStipple,
            logicOp: s.logicOp ? (s.logicOp >>> 0) : 0,
            flatShading: !!s.flatShading,
            colorTargets: Math.max(1, Math.min(8, s.colorTargets || 1)),
        };
    }

    function normalizeEnv(env) {
        const e = env || {};
        const mode = e.mode || "MODULATE";
        if (mode !== "COMBINE") return {
            mode,
            coordReplace: !!e.coordReplace,
        };
        return {
            mode,
            coordReplace: !!e.coordReplace,
            combineRGB: e.combineRGB || "MODULATE",
            combineAlpha: e.combineAlpha || "MODULATE",
            srcRGB: (e.srcRGB || ["TEXTURE", "PREVIOUS", "CONSTANT"]).slice(0, 3),
            operandRGB: (e.operandRGB ||
                ["SRC_COLOR", "SRC_COLOR", "SRC_ALPHA"]).slice(0, 3),
            srcAlpha: (e.srcAlpha || ["TEXTURE", "PREVIOUS", "CONSTANT"]).slice(0, 3),
            operandAlpha: (e.operandAlpha ||
                ["SRC_ALPHA", "SRC_ALPHA", "SRC_ALPHA"]).slice(0, 3),
            rgbScale: e.rgbScale || 1,
            alphaScale: e.alphaScale || 1,
        };
    }

    function signatureKey(sig) {
        return "ff" + FIXED_FUNCTION_REVISION + ":" +
            JSON.stringify(normalizeSignature(sig));
    }

    /* ================================================================== */
    /* State field selection                                              */
    /* ================================================================== */

    /*
     * Only the state a given signature reads is uploaded. A 2D blit with one
     * modulate stage needs the modelview-projection matrix and nothing else --
     * 16 floats instead of the ~700 the full table would occupy, per draw.
     */
    function stateFieldsFor(sig) {
        const fields = new Set(["mvp"]);
        for (const field of sig.extraStateFields || []) fields.add(field);
        const lighting = sig.lighting;
        const needsEye = lighting.enabled ||
            sig.texture.some(t => t.enabled && t.texGen &&
                t.texGen.some(m => m === "EYE" || m === "SPHERE" ||
                    m === "REFLECTION" || m === "NORMAL")) ||
            (sig.fog.enabled && sig.fog.coordSource === "depth") ||
            sig.clipPlaneCount > 0 ||
            sig.pointSprite;
        if (needsEye) fields.add("modelview");
        if (lighting.enabled) {
            fields.add("lights");
            fields.add("frontMaterial");
            fields.add("lightModelAmbient");
            fields.add("frontSceneColor");
            if (lighting.twoSide) {
                fields.add("backMaterial");
                fields.add("backSceneColor");
            }
        }
        if (lighting.enabled || sig.attributes.normal) fields.add("normalMatrix");
        if (sig.fog.enabled) {
            fields.add("fogParams");
            fields.add("fogColor");
        }
        for (const t of sig.texture) {
            if (!t.enabled) continue;
            if (t.matrix) fields.add("textureMatrix");
            if (t.texGen && t.texGen.some(m => m === "OBJECT" || m === "EYE"))
                fields.add("texGenPlanes");
            if (t.env.mode === "BLEND" ||
                    (t.env.mode === "COMBINE" &&
                     (t.env.srcRGB.includes("CONSTANT") ||
                      t.env.srcAlpha.includes("CONSTANT"))))
                fields.add("texEnvColor");
        }
        if (sig.clipPlaneCount) fields.add("clipPlanes");
        if (sig.alphaTest !== "always" && sig.alphaTest !== "never")
            fields.add("alphaRef");
        if (sig.pointSprite) {
            fields.add("pointParams");
            fields.add("pointAttenuation");
            fields.add("viewportParams");
        }
        if (sig.polygonStipple) fields.add("polygonStipple");
        return fields;
    }

    /* ================================================================== */
    /* Varying allocation                                                 */
    /* ================================================================== */

    /*
     * Slots are assigned here rather than by the translator's packer because
     * the fixed pipeline's set is known exactly: colour, secondary colour,
     * fog, up to eight texture coordinates, and the two extras. Packing the
     * scalars (fog) alongside a colour keeps the common lit-and-fogged case
     * inside four slots.
     */
    function allocateVaryings(sig) {
        const entries = [];
        const slots = [];
        const place = (name, components, extra) => {
            let slot = -1, offset = 0;
            if (components === 4) {
                slots.push(4);
                slot = slots.length - 1;
            } else {
                for (let i = 0; i < slots.length; ++i) {
                    if (slots[i] + components <= 4) {
                        slot = i;
                        offset = slots[i];
                        slots[i] += components;
                        break;
                    }
                }
                if (slot < 0) { slots.push(components); slot = slots.length - 1; }
            }
            const entry = { name, components, slot, offset, ...(extra || {}) };
            entries.push(entry);
            return entry;
        };

        const layout = { entries, color: null, secondary: null, backColor: null,
                         backSecondary: null, fog: null, texCoord: [],
                         clip: -1, pointCoord: -1 };

        if (sig.varyingInterface === "arb") {
            const fixed = (name, components, slot, extra) => {
                const entry = { name, components, slot, offset: 0,
                                ...(extra || {}) };
                entries.push(entry);
                if (slots.indexOf(slot) < 0) slots.push(slot);
                return entry;
            };
            layout.color = fixed("color", 4, 0, { flat: sig.flatShading });
            if (sig.lighting.enabled && sig.lighting.separateSpecular)
                layout.secondary = fixed("secondary", 3, 1,
                    { flat: sig.flatShading });
            for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
                if (!sig.texture[i].enabled) {
                    layout.texCoord.push(null);
                    continue;
                }
                layout.texCoord.push(fixed("texCoord" + i,
                    textureCoordComponents(sig.texture[i]), 3 + i));
            }
            if (sig.fog.enabled) layout.fog = fixed("fog", 1, 2);
            slots.sort((a, b) => a - b);
            layout.slotIndices = slots;
            layout.packedSlots = slots.length;
            layout.slotCount = slots.length ? slots[slots.length - 1] + 1 : 0;
            if (layout.slotCount > translator.MAX_INTER_STAGE_SLOTS)
                throw new Error("fixed-function ARB interface needs location " +
                    (layout.slotCount - 1) + "; only " +
                    translator.MAX_INTER_STAGE_SLOTS + " slots are available");
            return layout;
        }

        layout.color = place("color", 4, { flat: sig.flatShading });
        if (sig.lighting.enabled && sig.lighting.separateSpecular)
            layout.secondary = place("secondary", 3, { flat: sig.flatShading });
        if (sig.lighting.enabled && sig.lighting.twoSide) {
            layout.backColor = place("backColor", 4, { flat: sig.flatShading });
            if (sig.lighting.separateSpecular)
                layout.backSecondary = place("backSecondary", 3,
                    { flat: sig.flatShading });
        }
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            if (!sig.texture[i].enabled) { layout.texCoord.push(null); continue; }
            layout.texCoord.push(place("texCoord" + i,
                textureCoordComponents(sig.texture[i])));
        }
        if (sig.fog.enabled) layout.fog = place("fog", 1);

        let next = slots.length;
        if (sig.clipPlaneCount) layout.clip = next++;
        if (sig.pointSprite) layout.pointCoord = next++;
        layout.slotCount = next;
        layout.packedSlots = slots.length;
        layout.slotIndices = Array.from({ length: slots.length },
            (unused, i) => i);
        if (next > translator.MAX_INTER_STAGE_SLOTS)
            throw new Error("fixed-function signature needs " + next +
                " varying slots; only " + translator.MAX_INTER_STAGE_SLOTS +
                " are available");
        return layout;
    }

    function textureCoordComponents(unit) {
        if (unit.shadow) return 4;
        switch (unit.target) {
        case "1D": return 1;
        case "3D": return 3;
        case "Cube": return 3;
        default: return 2;
        }
    }

    const SWIZZLE = "xyzw";
    function swz(offset, count) { return SWIZZLE.slice(offset, offset + count); }

    /* ================================================================== */
    /* Vertex shader                                                      */
    /* ================================================================== */

    function generateVertex(sig, layout, fields) {
        const L = [];
        const emit = line => L.push(line);
        const lighting = sig.lighting;

        emit("// generated by gl_fixed_function.js r" + FIXED_FUNCTION_REVISION +
            " (vertex)");
        emit("");
        emit(stateLayout.buildLayout([...fields]).structText);
        emit("@group(1) @binding(0) var<uniform> glState : GLState;");
        emit("");

        emit("struct VSIn {");
        emit("    @location(" + ATTR.gl_Vertex + ") position : vec4<f32>,");
        if (sig.attributes.normal)
            emit("    @location(" + ATTR.gl_Normal + ") normal : vec3<f32>,");
        if (sig.attributes.color)
            emit("    @location(" + ATTR.gl_Color + ") color : vec4<f32>,");
        if (sig.attributes.secondaryColor)
            emit("    @location(" + ATTR.gl_SecondaryColor + ") secondary : vec4<f32>,");
        if (sig.attributes.fogCoord)
            emit("    @location(" + ATTR.gl_FogCoord + ") fogCoord : f32,");
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const a = sig.attributes.texCoord[i];
            if (!a) continue;
            emit("    @location(" + (ATTR.gl_MultiTexCoord0 + i) + ") texCoord" + i +
                " : " + vecType(a.components) + ",");
        }
        if (sig.pointSprite)
            emit("    @location(" + POINT_CORNER_LOCATION + ") corner : vec2<f32>,");
        emit("}");
        emit("");

        emit("struct VSOut {");
        emit("    @invariant @builtin(position) position : vec4<f32>,");
        for (const i of layout.slotIndices) {
            const flat = layout.entries.some(e => e.slot === i && e.flat);
            emit("    " + (flat ? "@interpolate(flat) " : "") +
                "@location(" + i + ") v" + i + " : vec4<f32>,");
        }
        if (layout.clip >= 0)
            emit("    @location(" + layout.clip + ") clipDist : vec4<f32>,");
        if (layout.pointCoord >= 0)
            emit("    @location(" + layout.pointCoord + ") pointCoord : vec2<f32>,");
        emit("}");
        emit("");

        emit("@vertex");
        emit("fn vs_main(vin : VSIn) -> VSOut {");
        emit("    var out : VSOut;");
        emit("    let objectPos = vin.position;");
        emit("    var clip = glState.mvp * objectPos;");

        const needsEye = fields.has("modelview");
        if (needsEye) emit("    let eyePos = (glState.modelview * objectPos).xyz;");

        if (sig.attributes.normal && fields.has("normalMatrix")) {
            emit("    var eyeNormal = glState.normalMatrix * vin.normal;");
            if (lighting.normalMode === "normalize")
                emit("    eyeNormal = normalize(eyeNormal);");
            else if (lighting.normalMode === "rescale")
                // GL_RESCALE_NORMAL scales by the inverse magnitude of the
                // modelview's third column, which is exact only for a uniform
                // scale -- the condition the extension documents.
                emit("    eyeNormal = eyeNormal * inverseSqrt(max(dot(" +
                    "glState.modelview[2].xyz, glState.modelview[2].xyz), 1e-8));");
        } else if (lighting.enabled) {
            emit("    var eyeNormal = vec3<f32>(0.0, 0.0, 1.0);");
        }

        emitVertexColor(emit, sig, layout);
        emitTexCoords(emit, sig, layout);

        if (sig.fog.enabled && layout.fog) {
            const coord = sig.fog.coordSource === "coord" ?
                (sig.attributes.fogCoord ? "vin.fogCoord" : "0.0") :
                (needsEye ? "abs(eyePos.z)" : "abs(clip.z)");
            emit("    let fogCoord = " + coord + ";");
            emit("    out.v" + layout.fog.slot + "." +
                SWIZZLE[layout.fog.offset] + " = fogCoord;");
        }

        if (sig.pointSprite) {
            emit("    let ptDist = " + (needsEye ? "length(eyePos)" : "1.0") + ";");
            emit("    let ptAtten = inverseSqrt(max(glState.pointAttenuation.x + " +
                "glState.pointAttenuation.y * ptDist + " +
                "glState.pointAttenuation.z * ptDist * ptDist, 1e-8));");
            emit("    let ptSize = clamp(glState.pointParams.x * ptAtten, " +
                "glState.pointParams.y, glState.pointParams.z);");
            emit("    clip.x = clip.x + vin.corner.x * ptSize * clip.w / " +
                "glState.viewportParams.z;");
            emit("    clip.y = clip.y + vin.corner.y * ptSize * clip.w / " +
                "glState.viewportParams.w;");
            emit("    out.pointCoord = vec2<f32>(vin.corner.x * 0.5 + 0.5, " +
                (sig.pointCoordLowerLeft ?
                    "vin.corner.y * 0.5 + 0.5);" :
                    "0.5 - vin.corner.y * 0.5);"));
        }

        if (sig.clipPlaneCount) {
            const parts = [];
            for (let i = 0; i < 4; ++i) {
                if (i < sig.clipPlaneCount && needsEye)
                    parts.push("dot(vec4<f32>(eyePos, 1.0), glState.clipPlanes[" +
                        i + "])");
                else parts.push("1.0");
            }
            emit("    out.clipDist = vec4<f32>(" + parts.join(", ") + ");");
        }

        // GL clip space is z in [-w, w] and its framebuffer origin is at the
        // bottom; WebGPU wants [0, w] and a top origin. Doing the flip here --
        // once, in clip space -- is what lets viewport, scissor, readback and
        // render-to-texture skip a conversion each (plan 4.3).
        emit("    clip.z = (clip.z + clip.w) * 0.5;");
        emit("    clip.y = -clip.y;");
        emit("    out.position = clip;");
        emit("    return out;");
        emit("}");
        return L.join("\n") + "\n";
    }

    function vecType(components) {
        return components === 1 ? "f32" : "vec" + components + "<f32>";
    }

    function emitVertexColor(emit, sig, layout) {
        const lighting = sig.lighting;
        const primary = sig.attributes.color ? "vin.color" : "vec4<f32>(1.0)";

        if (!lighting.enabled) {
            writeVarying(emit, layout.color, primary, 4);
            if (layout.secondary) {
                const s = sig.attributes.secondaryColor ?
                    "vin.secondary.xyz" : "vec3<f32>(0.0)";
                writeVarying(emit, layout.secondary, s, 3);
            }
            return;
        }

        emit("    let vertexColor = " + primary + ";");
        emitLightingFace(emit, sig, layout, false);
        if (lighting.twoSide) emitLightingFace(emit, sig, layout, true);
    }

    /*
     * GL 1.5 section 2.14.1, verbatim:
     *
     *   c = e_cm + a_cm * a_cs
     *       + sum_i att_i * spot_i * ( a_cm*a_cli
     *                                + (n . VP_pli) * d_cm*d_cli
     *                                + f * (n . h_i)^srm * s_cm*s_cli )
     *
     * with f = 1 when n . VP_pli is positive and 0 otherwise. The scene colour
     * (e_cm + a_cm*a_cs) arrives precomputed in glState.frontSceneColor,
     * because it depends only on state the CPU already has.
     */
    function emitLightingFace(emit, sig, layout, back) {
        const lighting = sig.lighting;
        const prefix = back ? "back" : "front";
        const material = back ? "glState.backMaterial" : "glState.frontMaterial";
        const scene = back ? "glState.backSceneColor" : "glState.frontSceneColor";
        const normal = back ? "(-eyeNormal)" : "eyeNormal";

        const cm = lighting.colorMaterial;
        const applies = !cm.enabled ? false :
            (cm.face === "FRONT_AND_BACK" ||
             (back ? cm.face === "BACK" : cm.face === "FRONT"));
        const track = property => {
            if (!applies) return material + "." + property;
            switch (cm.mode) {
            case "EMISSION": return property === "emission" ?
                "vertexColor" : material + "." + property;
            case "AMBIENT": return property === "ambient" ?
                "vertexColor" : material + "." + property;
            case "DIFFUSE": return property === "diffuse" ?
                "vertexColor" : material + "." + property;
            case "SPECULAR": return property === "specular" ?
                "vertexColor" : material + "." + property;
            case "AMBIENT_AND_DIFFUSE":
                return (property === "ambient" || property === "diffuse") ?
                    "vertexColor" : material + "." + property;
            default: return material + "." + property;
            }
        };

        emit("    var " + prefix + "Color = vec3<f32>(0.0);");
        emit("    var " + prefix + "Spec = vec3<f32>(0.0);");
        if (applies && (cm.mode === "EMISSION" || cm.mode === "AMBIENT" ||
                cm.mode === "AMBIENT_AND_DIFFUSE")) {
            // The scene colour depends on the tracked property, so it has to
            // be recomputed here rather than taken from the uniform.
            emit("    " + prefix + "Color = " + track("emission") + ".rgb + " +
                track("ambient") + ".rgb * glState.lightModelAmbient.rgb;");
        } else {
            emit("    " + prefix + "Color = " + scene + ".rgb;");
        }

        for (let i = 0; i < MAX_LIGHTS; ++i) {
            const light = lighting.lights[i];
            if (!light.enabled) continue;
            const l = "glState.lights[" + i + "]";
            emit("    {");
            if (light.positional) {
                emit("        let toLight = " + l + ".position.xyz - eyePos;");
                emit("        let dist = length(toLight);");
                emit("        let VP = toLight / max(dist, 1e-8);");
                emit("        var atten = 1.0 / max(" + l +
                    ".constantAttenuation + " + l + ".linearAttenuation * dist + " +
                    l + ".quadraticAttenuation * dist * dist, 1e-8);");
            } else {
                emit("        let VP = normalize(" + l + ".position.xyz);");
                emit("        var atten = 1.0;");
            }
            if (light.spot) {
                emit("        let spotDot = dot(-VP, normalize(" + l +
                    ".spotDirection));");
                emit("        if (spotDot < " + l + ".spotCosCutoff) {");
                emit("            atten = 0.0;");
                emit("        } else {");
                emit("            atten = atten * pow(max(spotDot, 1e-8), " + l +
                    ".spotExponent);");
                emit("        }");
            }
            emit("        let nDotVP = dot(" + normal + ", VP);");
            emit("        " + prefix + "Color = " + prefix + "Color + atten * (" +
                track("ambient") + ".rgb * " + l + ".ambient.rgb");
            emit("            + max(nDotVP, 0.0) * " + track("diffuse") +
                ".rgb * " + l + ".diffuse.rgb);");
            emit("        if (nDotVP > 0.0) {");
            if (lighting.localViewer)
                emit("            let halfVec = normalize(VP + normalize(-eyePos));");
            else
                emit("            let halfVec = normalize(VP + vec3<f32>(0.0, 0.0, 1.0));");
            emit("            let nDotH = max(dot(" + normal + ", halfVec), 0.0);");
            emit("            let shine = pow(nDotH, max(" + material +
                ".shininess, 1e-4));");
            emit("            " + prefix + "Spec = " + prefix + "Spec + atten * " +
                "shine * " + track("specular") + ".rgb * " + l + ".specular.rgb;");
            emit("        }");
            emit("    }");
        }

        const alpha = track("diffuse") + ".a";
        const target = back ? layout.backColor : layout.color;
        const specTarget = back ? layout.backSecondary : layout.secondary;
        if (lighting.separateSpecular && specTarget) {
            writeVarying(emit, target, "vec4<f32>(clamp(" + prefix +
                "Color, vec3<f32>(0.0), vec3<f32>(1.0)), " + alpha + ")", 4);
            writeVarying(emit, specTarget, "clamp(" + prefix +
                "Spec, vec3<f32>(0.0), vec3<f32>(1.0))", 3);
        } else {
            writeVarying(emit, target, "vec4<f32>(clamp(" + prefix + "Color + " +
                prefix + "Spec, vec3<f32>(0.0), vec3<f32>(1.0)), " + alpha + ")", 4);
        }
    }

    function writeVarying(emit, entry, expr, components) {
        if (!entry) return;
        if (entry.offset === 0 && entry.components === 4 && components === 4) {
            emit("    out.v" + entry.slot + " = " + expr + ";");
            return;
        }
        const tmp = "_v" + entry.slot + "_" + entry.offset;
        emit("    let " + tmp + " = " + expr + ";");
        for (let i = 0; i < entry.components; ++i) {
            const src = entry.components === 1 && components === 1 ?
                tmp : tmp + "." + SWIZZLE[i];
            emit("    out.v" + entry.slot + "." + SWIZZLE[entry.offset + i] +
                " = " + src + ";");
        }
    }

    /*
     * Texture coordinate generation. GL applies texgen per coordinate (S, T,
     * R, Q independently), then the texture matrix, then the projective divide
     * if the shader asked for one -- and a unit may mix generated and supplied
     * coordinates, which is why each of the four is built separately rather
     * than as one vector expression.
     */
    function emitTexCoords(emit, sig, layout) {
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const unit = sig.texture[i];
            const entry = layout.texCoord[i];
            if (!unit.enabled || !entry) continue;
            const supplied = sig.attributes.texCoord[i];
            const parts = [];
            const gen = unit.texGen || [];
            const anyGen = gen.some(m => !!m);

            if (!anyGen) {
                if (supplied) {
                    const c = supplied.components;
                    parts.push(c === 1 ? "vec4<f32>(vin.texCoord" + i + ", 0.0, 0.0, 1.0)" :
                        c === 2 ? "vec4<f32>(vin.texCoord" + i + ", 0.0, 1.0)" :
                        c === 3 ? "vec4<f32>(vin.texCoord" + i + ", 1.0)" :
                        "vin.texCoord" + i);
                } else {
                    parts.push("vec4<f32>(0.0, 0.0, 0.0, 1.0)");
                }
                emit("    var tc" + i + " = " + parts[0] + ";");
            } else {
                emit("    var tc" + i + " = vec4<f32>(0.0, 0.0, 0.0, 1.0);");
                const suppliedComponent = c => {
                    if (!supplied) return c === 3 ? "1.0" : "0.0";
                    if (supplied.components === 1)
                        return c === 0 ? "vin.texCoord" + i :
                            (c === 3 ? "1.0" : "0.0");
                    return c < supplied.components ?
                        "vin.texCoord" + i + "." + SWIZZLE[c] :
                        (c === 3 ? "1.0" : "0.0");
                };
                let sphereEmitted = false;
                let reflectEmitted = false;
                for (let c = 0; c < 4; ++c) {
                    const mode = gen[c];
                    if (!mode) {
                        emit("    tc" + i + "." + SWIZZLE[c] + " = " +
                            suppliedComponent(c) + ";");
                        continue;
                    }
                    switch (mode) {
                    case "OBJECT":
                        emit("    tc" + i + "." + SWIZZLE[c] +
                            " = dot(objectPos, glState.texGenPlanes[" +
                            (i * 8 + c) + "]);");
                        break;
                    case "EYE":
                        // The eye plane is stored already multiplied by the
                        // inverse modelview at glTexGen time, so the shader
                        // dots it with the eye position directly -- the same
                        // thing desktop GL does when the plane is specified.
                        emit("    tc" + i + "." + SWIZZLE[c] +
                            " = dot(vec4<f32>(eyePos, 1.0), glState.texGenPlanes[" +
                            (i * 8 + 4 + c) + "]);");
                        break;
                    case "SPHERE":
                        if (!sphereEmitted) {
                            sphereEmitted = true;
                            emit("    let sphereR" + i +
                                " = reflect(normalize(eyePos), eyeNormal);");
                            emit("    let sphereM" + i + " = 2.0 * sqrt(" +
                                "sphereR" + i + ".x * sphereR" + i + ".x + " +
                                "sphereR" + i + ".y * sphereR" + i + ".y + " +
                                "(sphereR" + i + ".z + 1.0) * (sphereR" + i +
                                ".z + 1.0));");
                        }
                        emit("    tc" + i + "." + SWIZZLE[c] + " = sphereR" + i +
                            "." + SWIZZLE[c] + " / max(sphereM" + i +
                            ", 1e-8) + 0.5;");
                        break;
                    case "REFLECTION":
                        if (!reflectEmitted) {
                            reflectEmitted = true;
                            emit("    let reflectV" + i +
                                " = reflect(normalize(eyePos), eyeNormal);");
                        }
                        emit("    tc" + i + "." + SWIZZLE[c] + " = reflectV" + i +
                            "." + SWIZZLE[c] + ";");
                        break;
                    case "NORMAL":
                        emit("    tc" + i + "." + SWIZZLE[c] + " = eyeNormal." +
                            SWIZZLE[c] + ";");
                        break;
                    default:
                        throw new Error("unknown texgen mode " + mode);
                    }
                }
            }

            if (unit.matrix)
                emit("    tc" + i + " = glState.textureMatrix[" + i + "] * tc" + i + ";");

            const components = entry.components;
            const expr = components === 4 ? "tc" + i :
                "tc" + i + "." + swz(0, components);
            writeVarying(emit, entry, expr, components);
        }
    }

    /* ================================================================== */
    /* Fragment shader                                                    */
    /* ================================================================== */

    function generateFragment(sig, layout, fields) {
        const L = [];
        const emit = line => L.push(line);

        emit("// generated by gl_fixed_function.js r" + FIXED_FUNCTION_REVISION +
            " (fragment)");
        emit("");
        emit(stateLayout.buildLayout([...fields]).structText);
        emit("@group(1) @binding(0) var<uniform> glState : GLState;");
        emit("");

        let binding = 0;
        const bindings = [];
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const unit = sig.texture[i];
            if (!unit.enabled) { bindings.push(null); continue; }
            bindings.push({ texture: binding, sampler: binding + 1 });
            emit("@group(2) @binding(" + binding + ") var t" + i + " : " +
                textureTypeFor(unit) + ";");
            emit("@group(2) @binding(" + (binding + 1) + ") var s" + i + " : " +
                (unit.shadow ? "sampler_comparison" : "sampler") + ";");
            binding += 2;
        }
        if (binding) emit("");

        if (sig.logicOp && sig.logicOp !== 0x1503)
            emitLogicOpDeclarations(emit, sig.logicOp, sig.colorTargets);

        emit("struct FSIn {");
        emit("    @builtin(position) position : vec4<f32>,");
        if (sig.lighting.enabled && sig.lighting.twoSide)
            emit("    @builtin(front_facing) frontFacing : bool,");
        for (const i of layout.slotIndices) {
            const flat = layout.entries.some(e => e.slot === i && e.flat);
            emit("    " + (flat ? "@interpolate(flat) " : "") +
                "@location(" + i + ") v" + i + " : vec4<f32>,");
        }
        if (layout.clip >= 0)
            emit("    @location(" + layout.clip + ") clipDist : vec4<f32>,");
        if (layout.pointCoord >= 0)
            emit("    @location(" + layout.pointCoord + ") pointCoord : vec2<f32>,");
        emit("}");
        emit("");

        emit("struct FSOut {");
        for (let i = 0; i < sig.colorTargets; ++i)
            emit("    @location(" + i + ") color" + i + " : vec4<f32>,");
        emit("}");
        emit("");

        emit("@fragment");
        emit("fn fs_main(fin : FSIn) -> FSOut {");
        if (layout.clip >= 0)
            emit("    if (any(fin.clipDist < vec4<f32>(0.0))) { discard; }");
        if (sig.polygonStipple) emitPolygonStippleTest(emit, "fin.position");

        const colorRead = readVarying(layout.color);
        if (sig.lighting.enabled && sig.lighting.twoSide && layout.backColor)
            emit("    let primary = select(" + readVarying(layout.backColor) +
                ", " + colorRead + ", fin.frontFacing);");
        else
            emit("    let primary = " + colorRead + ";");
        emit("    var frag = primary;");

        // Sample every enabled unit up front: GL_COMBINE's crossbar sources let
        // stage 3 read stage 0's texture, so the samples cannot be produced
        // lazily as the chain is walked.
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const unit = sig.texture[i];
            if (!unit.enabled) continue;
            emit("    let tex" + i + " = " +
                sampleExpression(i, unit, layout.texCoord[i], sig) + ";");
        }

        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const unit = sig.texture[i];
            if (!unit.enabled) continue;
            emitTextureEnv(emit, sig, i, unit);
        }

        if (layout.secondary) {
            const secondary = (sig.lighting.twoSide && layout.backSecondary) ?
                "select(" + readVarying(layout.backSecondary) + ", " +
                    readVarying(layout.secondary) + ", fin.frontFacing)" :
                readVarying(layout.secondary);
            emit("    frag = vec4<f32>(clamp(frag.rgb + " + secondary +
                ", vec3<f32>(0.0), vec3<f32>(1.0)), frag.a);");
        }

        if (sig.fog.enabled && layout.fog) {
            const c = readVarying(layout.fog);
            switch (sig.fog.mode) {
            case "exp":
                emit("    let fogFactor = clamp(exp(-glState.fogParams.x * " +
                    c + "), 0.0, 1.0);");
                break;
            case "exp2":
                emit("    let fogArg = glState.fogParams.x * " + c + ";");
                emit("    let fogFactor = clamp(exp(-(fogArg * fogArg)), 0.0, 1.0);");
                break;
            default:
                emit("    let fogFactor = clamp((glState.fogParams.z - " + c +
                    ") * glState.fogParams.w, 0.0, 1.0);");
                break;
            }
            emit("    frag = vec4<f32>(mix(glState.fogColor.rgb, frag.rgb, " +
                "fogFactor), frag.a);");
        }

        emitAlphaTest(emit, sig);

        emit("    var out : FSOut;");
        for (let i = 0; i < sig.colorTargets; ++i) {
            if (sig.logicOp && sig.logicOp !== 0x1503)
                emit("    out.color" + i + " = glApplyLogic(frag, " +
                    "textureLoad(glLogicTarget" + i +
                    ", vec2<i32>(floor(fin.position.xy)), 0));");
            else
                emit("    out.color" + i + " = frag;");
        }
        emit("    return out;");
        emit("}");
        return L.join("\n") + "\n";
    }

    function readVarying(entry) {
        if (!entry) return "vec4<f32>(1.0)";
        if (entry.offset === 0 && entry.components === 4)
            return "fin.v" + entry.slot;
        return "fin.v" + entry.slot + "." + swz(entry.offset, entry.components);
    }

    function emitPolygonStippleTest(emit, position) {
        emit("    let stippleX = u32(floor(" + position + ".x)) & 31u;");
        emit("    let stippleY = u32(floor(" + position + ".y)) & 31u;");
        emit("    let stippleByteIndex = stippleY * 4u + (stippleX >> 3u);");
        emit("    let stippleWord = glState.polygonStipple[stippleByteIndex >> 2u];");
        emit("    let stippleLane = stippleByteIndex & 3u;");
        emit("    var stippleByte = stippleWord.x;");
        emit("    if (stippleLane == 1u) { stippleByte = stippleWord.y; }");
        emit("    if (stippleLane == 2u) { stippleByte = stippleWord.z; }");
        emit("    if (stippleLane == 3u) { stippleByte = stippleWord.w; }");
        emit("    let stippleBit = 0x80u >> (stippleX & 7u);");
        emit("    if ((u32(stippleByte) & stippleBit) == 0u) { discard; }");
    }

    function logicOpExpression(op) {
        switch (op >>> 0) {
        case 0x1500: return "vec4<u32>(0u)";       // GL_CLEAR
        case 0x1501: return "s & d";
        case 0x1502: return "s & ~d";
        case 0x1503: return "s";
        case 0x1504: return "~s & d";
        case 0x1505: return "d";
        case 0x1506: return "s ^ d";
        case 0x1507: return "s | d";
        case 0x1508: return "~(s | d)";
        case 0x1509: return "~(s ^ d)";
        case 0x150A: return "~d";
        case 0x150B: return "s | ~d";
        case 0x150C: return "~s";
        case 0x150D: return "~s | d";
        case 0x150E: return "~(s & d)";
        case 0x150F: return "vec4<u32>(255u)";    // GL_SET
        default: return "s";
        }
    }

    function emitLogicOpDeclarations(emit, op, colorTargets) {
        for (let i = 0; i < colorTargets; ++i)
            emit("@group(3) @binding(" + i + ") var glLogicTarget" + i +
                " : texture_2d<f32>;");
        emit("fn glApplyLogic(src : vec4<f32>, dst : vec4<f32>) -> vec4<f32> {");
        emit("    let s = vec4<u32>(round(clamp(src, vec4<f32>(0.0), " +
            "vec4<f32>(1.0)) * 255.0));");
        emit("    let d = vec4<u32>(round(clamp(dst, vec4<f32>(0.0), " +
            "vec4<f32>(1.0)) * 255.0));");
        emit("    let r = (" + logicOpExpression(op) + ") & vec4<u32>(255u);");
        emit("    return vec4<f32>(r) / 255.0;");
        emit("}");
        emit("");
    }

    function textureTypeFor(unit) {
        if (unit.shadow) return "texture_depth_2d";
        switch (unit.target) {
        case "3D": return "texture_3d<f32>";
        case "Cube": return "texture_cube<f32>";
        default: return "texture_2d<f32>";   // 1D rides on a height-1 2D
        }
    }

    function sampleExpression(i, unit, entry, sig) {
        const pointCoord = sig.pointSprite && unit.env.coordReplace;
        const coord = pointCoord ?
            "vec4<f32>(fin.pointCoord, 0.0, 1.0)" : readVarying(entry);
        const components = pointCoord ? 4 : (entry ? entry.components : 4);
        const q = components >= 4 ? "(" + coord + ").w" : "1.0";
        const xy = components >= 2 ? "(" + coord + ").xy" :
            "vec2<f32>((" + coord + ").x, 0.0)";
        const xyz = components >= 3 ? "(" + coord + ").xyz" :
            "vec3<f32>(" + xy + ", 0.0)";
        if (unit.shadow) {
            // A shadow lookup's reference is the third coordinate after the
            // projective divide, which is what GL's GL_COMPARE_R_TO_TEXTURE
            // means; the result replicates into all four components.
            return "vec4<f32>(textureSampleCompare(t" + i + ", s" + i + ", " +
                xy + " / max(" + q + ", 1e-8), " + xyz +
                ".z / max(" + q + ", 1e-8)))";
        }
        switch (unit.target) {
        case "1D":
            return "textureSample(t" + i + ", s" + i + ", vec2<f32>((" +
                coord + ").x / max(" + q + ", 1e-8), 0.5))";
        case "3D":
            return "textureSample(t" + i + ", s" + i + ", " + xyz +
                " / max(" + q + ", 1e-8))";
        case "Cube":
            return "textureSample(t" + i + ", s" + i + ", " + xyz + ")";
        default:
            return "textureSample(t" + i + ", s" + i + ", " + xy +
                " / max(" + q + ", 1e-8))";
        }
    }

    /*
     * GL 1.5 table 3.22 (the non-COMBINE functions) and section 3.8.13
     * (GL_COMBINE).
     *
     * The base internal format matters and cannot be folded away by the
     * upload-time channel expansion alone: an ALPHA texture leaves RGB
     * untouched, and REPLACE on an RGB or LUMINANCE texture leaves alpha
     * untouched. Uploads expand L to (l,l,l,1) and A to (0,0,0,a), which makes
     * MODULATE and ADD fall out correctly, but those two rows still need
     * saying explicitly.
     */
    function emitTextureEnv(emit, sig, i, unit) {
        const env = unit.env;
        const cs = "tex" + i;
        const format = unit.format;
        const cc = "glState.texEnvColor[" + i + "]";

        if (env.mode === "COMBINE") {
            emitCombine(emit, sig, i, unit);
            return;
        }

        const rgbOnlyFormats = format === "RGB" || format === "LUMINANCE";
        switch (env.mode) {
        case "REPLACE":
            if (format === "ALPHA")
                emit("    frag = vec4<f32>(frag.rgb, " + cs + ".a);");
            else if (rgbOnlyFormats)
                emit("    frag = vec4<f32>(" + cs + ".rgb, frag.a);");
            else
                emit("    frag = " + cs + ";");
            break;
        case "MODULATE":
            if (format === "ALPHA")
                emit("    frag = vec4<f32>(frag.rgb, frag.a * " + cs + ".a);");
            else
                emit("    frag = frag * " + cs + ";");
            break;
        case "DECAL":
            if (format === "RGB")
                emit("    frag = vec4<f32>(" + cs + ".rgb, frag.a);");
            else if (format === "RGBA")
                emit("    frag = vec4<f32>(mix(frag.rgb, " + cs + ".rgb, " +
                    cs + ".a), frag.a);");
            else
                // GL leaves DECAL undefined for the other base formats; the
                // least surprising reading is to pass the fragment through.
                emit("    // GL_DECAL is undefined for a " + format +
                    " texture; the fragment is unchanged");
            break;
        case "BLEND":
            if (format === "ALPHA")
                emit("    frag = vec4<f32>(frag.rgb, frag.a * " + cs + ".a);");
            else if (format === "INTENSITY")
                emit("    frag = vec4<f32>(mix(frag.rgb, " + cc + ".rgb, " +
                    cs + ".rgb), mix(frag.a, " + cc + ".a, " + cs + ".a));");
            else if (rgbOnlyFormats)
                emit("    frag = vec4<f32>(mix(frag.rgb, " + cc + ".rgb, " +
                    cs + ".rgb), frag.a);");
            else
                emit("    frag = vec4<f32>(mix(frag.rgb, " + cc + ".rgb, " +
                    cs + ".rgb), frag.a * " + cs + ".a);");
            break;
        case "ADD":
            if (format === "ALPHA")
                emit("    frag = vec4<f32>(frag.rgb, frag.a * " + cs + ".a);");
            else if (format === "INTENSITY")
                emit("    frag = clamp(frag + " + cs +
                    ", vec4<f32>(0.0), vec4<f32>(1.0));");
            else if (rgbOnlyFormats)
                emit("    frag = vec4<f32>(clamp(frag.rgb + " + cs +
                    ".rgb, vec3<f32>(0.0), vec3<f32>(1.0)), frag.a);");
            else
                emit("    frag = vec4<f32>(clamp(frag.rgb + " + cs +
                    ".rgb, vec3<f32>(0.0), vec3<f32>(1.0)), frag.a * " +
                    cs + ".a);");
            break;
        default:
            throw new Error("unknown texture environment mode " + env.mode);
        }
    }

    function combineSource(source, unitIndex) {
        if (source === "TEXTURE") return "tex" + unitIndex;
        const crossbar = /^TEXTURE(\d)$/.exec(source);
        if (crossbar) return "tex" + crossbar[1];
        if (source === "CONSTANT") return "glState.texEnvColor[" + unitIndex + "]";
        if (source === "PRIMARY_COLOR") return "primary";
        if (source === "PREVIOUS") return "frag";
        throw new Error("unknown GL_COMBINE source " + source);
    }

    function combineArgRGB(source, operand, unitIndex) {
        const v = combineSource(source, unitIndex);
        switch (operand) {
        case "SRC_COLOR": return "(" + v + ").rgb";
        case "ONE_MINUS_SRC_COLOR": return "(vec3<f32>(1.0) - (" + v + ").rgb)";
        case "SRC_ALPHA": return "vec3<f32>((" + v + ").a)";
        case "ONE_MINUS_SRC_ALPHA": return "vec3<f32>(1.0 - (" + v + ").a)";
        default: throw new Error("unknown RGB operand " + operand);
        }
    }

    function combineArgAlpha(source, operand, unitIndex) {
        const v = combineSource(source, unitIndex);
        switch (operand) {
        case "SRC_ALPHA": return "(" + v + ").a";
        case "ONE_MINUS_SRC_ALPHA": return "(1.0 - (" + v + ").a)";
        default: throw new Error("unknown alpha operand " + operand);
        }
    }

    function emitCombine(emit, sig, i, unit) {
        const env = unit.env;
        void sig;
        const r = [0, 1, 2].map(n =>
            combineArgRGB(env.srcRGB[n], env.operandRGB[n], i));
        const a = [0, 1, 2].map(n =>
            combineArgAlpha(env.srcAlpha[n], env.operandAlpha[n], i));

        emit("    {");
        let rgbExpr;
        let dot3Alpha = null;
        switch (env.combineRGB) {
        case "REPLACE": rgbExpr = r[0]; break;
        case "MODULATE": rgbExpr = "(" + r[0] + " * " + r[1] + ")"; break;
        case "ADD": rgbExpr = "(" + r[0] + " + " + r[1] + ")"; break;
        case "ADD_SIGNED":
            rgbExpr = "(" + r[0] + " + " + r[1] + " - vec3<f32>(0.5))";
            break;
        case "INTERPOLATE":
            rgbExpr = "mix(" + r[1] + ", " + r[0] + ", " + r[2] + ")";
            break;
        case "SUBTRACT": rgbExpr = "(" + r[0] + " - " + r[1] + ")"; break;
        case "DOT3_RGB":
        case "DOT3_RGBA":
            // 4 * dot(A0 - 0.5, A1 - 0.5), replicated. DOT3_RGBA drives alpha
            // from the same dot product, which is what makes it different from
            // DOT3_RGB rather than a naming variant.
            emit("        let dot3 = clamp(4.0 * dot(" + r[0] +
                " - vec3<f32>(0.5), " + r[1] + " - vec3<f32>(0.5)), 0.0, 1.0);");
            rgbExpr = "vec3<f32>(dot3)";
            if (env.combineRGB === "DOT3_RGBA") dot3Alpha = "dot3";
            break;
        default:
            throw new Error("unknown GL_COMBINE_RGB " + env.combineRGB);
        }

        let alphaExpr;
        if (dot3Alpha) {
            alphaExpr = dot3Alpha;
        } else {
            switch (env.combineAlpha) {
            case "REPLACE": alphaExpr = a[0]; break;
            case "MODULATE": alphaExpr = "(" + a[0] + " * " + a[1] + ")"; break;
            case "ADD": alphaExpr = "(" + a[0] + " + " + a[1] + ")"; break;
            case "ADD_SIGNED":
                alphaExpr = "(" + a[0] + " + " + a[1] + " - 0.5)";
                break;
            case "INTERPOLATE":
                alphaExpr = "mix(" + a[1] + ", " + a[0] + ", " + a[2] + ")";
                break;
            case "SUBTRACT": alphaExpr = "(" + a[0] + " - " + a[1] + ")"; break;
            default:
                throw new Error("unknown GL_COMBINE_ALPHA " + env.combineAlpha);
            }
        }

        const rgbScale = env.rgbScale === 1 ? "" : " * " + env.rgbScale + ".0";
        const alphaScale = dot3Alpha || env.alphaScale === 1 ?
            "" : " * " + env.alphaScale + ".0";
        emit("        let combinedRGB = clamp((" + rgbExpr + ")" + rgbScale +
            ", vec3<f32>(0.0), vec3<f32>(1.0));");
        emit("        let combinedA = clamp((" + alphaExpr + ")" + alphaScale +
            ", 0.0, 1.0);");
        emit("        frag = vec4<f32>(combinedRGB, combinedA);");
        emit("    }");
    }

    const ALPHA_TEST_OPERATORS = {
        less: "<", equal: "==", lequal: "<=",
        greater: ">", notequal: "!=", gequal: ">=",
    };

    function emitAlphaTest(emit, sig) {
        if (sig.alphaTest === "always") return;
        if (sig.alphaTest === "never") { emit("    discard;"); return; }
        const op = ALPHA_TEST_OPERATORS[sig.alphaTest];
        if (!op) throw new Error("unknown alpha test " + sig.alphaTest);
        emit("    if (!(frag.a " + op + " glState.alphaRef.x)) { discard; }");
    }

    /* ================================================================== */
    /* Public API                                                         */
    /* ================================================================== */

    /*
     * Produces both stages plus everything the executor needs to build the
     * pipeline and the bind groups. The vertex layout is described here rather
     * than derived in the executor so that the shader and the buffer layout
     * cannot drift apart.
     */
    function generate(rawSignature) {
        const sig = normalizeSignature(rawSignature);
        const layout = allocateVaryings(sig);
        const fields = stateFieldsFor(sig);
        const stateInfo = stateLayout.buildLayout([...fields]);

        const attributes = [];
        attributes.push({ name: "position", location: ATTR.gl_Vertex,
                          components: sig.attributes.position.components });
        if (sig.attributes.normal)
            attributes.push({ name: "normal", location: ATTR.gl_Normal, components: 3 });
        if (sig.attributes.color)
            attributes.push({ name: "color", location: ATTR.gl_Color, components: 4 });
        if (sig.attributes.secondaryColor)
            attributes.push({ name: "secondaryColor",
                              location: ATTR.gl_SecondaryColor, components: 4 });
        if (sig.attributes.fogCoord)
            attributes.push({ name: "fogCoord", location: ATTR.gl_FogCoord,
                              components: 1 });
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            const a = sig.attributes.texCoord[i];
            if (!a) continue;
            attributes.push({ name: "texCoord" + i,
                              location: ATTR.gl_MultiTexCoord0 + i,
                              components: a.components });
        }
        if (sig.pointSprite)
            attributes.push({ name: "corner", location: POINT_CORNER_LOCATION,
                              components: 2 });

        const textures = [];
        let binding = 0;
        for (let i = 0; i < MAX_TEXTURE_UNITS; ++i) {
            if (!sig.texture[i].enabled) continue;
            textures.push({
                unit: i, textureBinding: binding, samplerBinding: binding + 1,
                target: sig.texture[i].target, shadow: sig.texture[i].shadow,
            });
            binding += 2;
        }

        return {
            signature: sig,
            key: "ff" + FIXED_FUNCTION_REVISION + ":" + JSON.stringify(sig),
            wgslVertex: generateVertex(sig, layout, fields),
            wgslFragment: generateFragment(sig, layout, fields),
            stateFields: [...fields],
            stateFloats: stateInfo.floats,
            attributes, textures,
            varyingSlots: layout.slotCount,
            colorTargets: sig.colorTargets,
            usesDiscard: sig.alphaTest !== "always" || sig.clipPlaneCount > 0,
            pointSprite: sig.pointSprite,
        };
    }

    const api = {
        FIXED_FUNCTION_REVISION,
        generate, signatureKey, normalizeSignature, stateFieldsFor,
        allocateVaryings,
        MAX_TEXTURE_UNITS, MAX_LIGHTS,
    };
    global.GLFixedFunction = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                          source/v64/src/browser/glbridge/gl-webgpu/gl_shader_translator.js                                   0000644 0000000 0000000 00000731675 00000000000 022370  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLSL 1.10/1.20 -> WGSL.
//
// This is a real front end -- preprocessor, lexer, parser, type checker, code
// generator -- and not a source rewriter, for a reason specific to the games
// this bridge has to run. Cube 2's shaders are assembled at runtime by
// CubeScript: tests/cube2_glsl_coverage.md records that 25 of its shader pairs
// are literal and the rest are generated by nested substitution, so the set of
// source texts is not enumerable ahead of time. Anything pattern-based passes
// the corpus and then fails unpredictably on the variants a real map produces.
//
// Structure:
//   preprocess()  #define/#if/#extension/#version, macro expansion
//   lex()         GLSL token stream
//   parse()       AST
//   analyze()     scopes, overload resolution, implicit conversions, usage
//   generate()    WGSL text + reflection, at link time (both stages together)
//
// Compilation is per shader (glCompileShader) but code generation is per
// program (glLinkProgram), because the varying interface -- which varyings
// exist, in which slots, packed how -- is only decidable once both stages are
// known. That split matches GL's own semantics exactly.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md chapter 8.

(function(global) {
    "use strict";

    const stateLayout = (typeof require === "function" && typeof module !== "undefined") ?
        require("./gl_state_layout.js") : global.GLStateLayout;

    const TRANSLATOR_REVISION = 2;

    /* ================================================================== */
    /* Types                                                              */
    /* ================================================================== */

    // GLSL and WGSL agree that matNxM is N columns by M rows, so matrix types
    // map across without a transpose anywhere.
    const T = {};
    T.void = { kind: "void", name: "void" };
    T.bool = { kind: "scalar", base: "bool", name: "bool" };
    T.int = { kind: "scalar", base: "int", name: "int" };
    T.float = { kind: "scalar", base: "float", name: "float" };

    const VEC_NAMES = { bool: "bvec", int: "ivec", float: "vec" };
    const vectorCache = new Map();
    function vec(base, size) {
        const key = base + size;
        let t = vectorCache.get(key);
        if (!t) {
            t = { kind: "vector", base, size, name: VEC_NAMES[base] + size };
            vectorCache.set(key, t);
        }
        return t;
    }

    const matrixCache = new Map();
    function mat(cols, rows) {
        const key = cols + "x" + rows;
        let t = matrixCache.get(key);
        if (!t) {
            t = { kind: "matrix", cols, rows, base: "float",
                  name: cols === rows ? "mat" + cols : "mat" + cols + "x" + rows };
            matrixCache.set(key, t);
        }
        return t;
    }

    const samplerCache = new Map();
    function sampler(dim, shadow) {
        const key = dim + (shadow ? "S" : "");
        let t = samplerCache.get(key);
        if (!t) {
            t = { kind: "sampler", dim, shadow: !!shadow,
                  name: "sampler" + dim + (shadow ? "Shadow" : "") };
            samplerCache.set(key, t);
        }
        return t;
    }

    function arrayOf(elem, size) {
        return { kind: "array", elem, size,
                 name: elem.name + "[" + (size >= 0 ? size : "") + "]" };
    }

    function structType(name, fields) {
        return { kind: "struct", name, fields };
    }

    const BASIC_TYPES = {
        void: T.void, bool: T.bool, int: T.int, float: T.float,
        vec2: vec("float", 2), vec3: vec("float", 3), vec4: vec("float", 4),
        bvec2: vec("bool", 2), bvec3: vec("bool", 3), bvec4: vec("bool", 4),
        ivec2: vec("int", 2), ivec3: vec("int", 3), ivec4: vec("int", 4),
        mat2: mat(2, 2), mat3: mat(3, 3), mat4: mat(4, 4),
        mat2x2: mat(2, 2), mat2x3: mat(2, 3), mat2x4: mat(2, 4),
        mat3x2: mat(3, 2), mat3x3: mat(3, 3), mat3x4: mat(3, 4),
        mat4x2: mat(4, 2), mat4x3: mat(4, 3), mat4x4: mat(4, 4),
        sampler1D: sampler("1D"), sampler2D: sampler("2D"),
        sampler3D: sampler("3D"), samplerCube: sampler("Cube"),
        sampler1DShadow: sampler("1D", true), sampler2DShadow: sampler("2D", true),
        sampler2DRect: sampler("2DRect"), sampler2DRectShadow: sampler("2DRect", true),
        // GL_OES_EGL_image_external (GLSL ES): a 2D sampler of an EGL image,
        // which the executor holds as an ordinary 2D texture
        samplerExternalOES: { kind: "sampler", dim: "2D", shadow: false, name: "samplerExternalOES", external: true },
    };

    function sameType(a, b) {
        if (a === b) return true;
        if (!a || !b || a.kind !== b.kind) return false;
        switch (a.kind) {
        case "void": return true;
        case "scalar": return a.base === b.base;
        case "vector": return a.base === b.base && a.size === b.size;
        case "matrix": return a.cols === b.cols && a.rows === b.rows;
        case "sampler": return a.dim === b.dim && a.shadow === b.shadow;
        case "array": return a.size === b.size && sameType(a.elem, b.elem);
        case "struct": return a.name === b.name;
        default: return false;
        }
    }

    function componentCount(t) {
        switch (t.kind) {
        case "scalar": return 1;
        case "vector": return t.size;
        case "matrix": return t.cols * t.rows;
        default: return 0;
        }
    }

    function baseOf(t) {
        if (t.kind === "scalar" || t.kind === "vector") return t.base;
        if (t.kind === "matrix") return "float";
        return null;
    }

    /* GLSL 1.20 has exactly one implicit conversion: int -> float, applied
     * componentwise. Nothing converts to int, and bool never converts. WGSL has
     * no implicit conversions at all, so every one of these has to be made
     * explicit during analysis -- which is why it is tracked as a type relation
     * here rather than left to code generation to guess at. */
    function convertsTo(from, to) {
        if (sameType(from, to)) return true;
        if (!from || !to) return false;
        if (from.kind === "scalar" && to.kind === "scalar")
            return from.base === "int" && to.base === "float";
        if (from.kind === "vector" && to.kind === "vector")
            return from.size === to.size && from.base === "int" && to.base === "float";
        return false;
    }

    function typeToWGSL(t) {
        switch (t.kind) {
        case "void": return "void";
        case "scalar":
            return t.base === "float" ? "f32" : (t.base === "int" ? "i32" : "bool");
        case "vector":
            return "vec" + t.size + "<" +
                (t.base === "float" ? "f32" : (t.base === "int" ? "i32" : "bool")) + ">";
        case "matrix":
            return "mat" + t.cols + "x" + t.rows + "<f32>";
        case "array":
            return "array<" + typeToWGSL(t.elem) + ", " + t.size + ">";
        case "struct":
            return t.name;
        default:
            throw new Error("no WGSL type for " + t.kind);
        }
    }

    /* GLSL's == of two values of type t (already named, as each is read more
     * than once) as one WGSL bool */
    function equalityWGSL(a, b, t) {
        switch (t.kind) {
        case "vector":
            return "all(" + a + " == " + b + ")";
        case "matrix": {
            const columns = [];
            for (let c = 0; c < t.cols; ++c)
                columns.push("all(" + a + "[" + c + "] == " + b + "[" + c + "])");
            return "(" + columns.join(" && ") + ")";
        }
        case "array": {
            const elements = [];
            for (let i = 0; i < t.size; ++i)
                elements.push(equalityWGSL(a + "[" + i + "]", b + "[" + i + "]", t.elem));
            return "(" + elements.join(" && ") + ")";
        }
        case "struct":
            return "(" + t.fields.map(f => equalityWGSL(a + "." + safeName(f.name),
                b + "." + safeName(f.name), f.type)).join(" && ") + ")";
        default:
            return "(" + a + " == " + b + ")";
        }
    }

    function zeroValueWGSL(t) {
        switch (t.kind) {
        case "scalar":
            return t.base === "float" ? "0.0" : (t.base === "int" ? "0" : "false");
        case "vector":
        case "matrix":
        case "array":
        case "struct":
            return typeToWGSL(t) + "()";
        default:
            return typeToWGSL(t) + "()";
        }
    }

    /* ================================================================== */
    /* Diagnostics                                                        */
    /* ================================================================== */

    class GLSLError extends Error {
        constructor(message, line) {
            super(message);
            this.glslLine = line || 0;
        }
    }

    function fail(line, message) {
        throw new GLSLError(message, line);
    }

    /* ================================================================== */
    /* Preprocessor                                                       */
    /* ================================================================== */

    /*
     * Comment removal and line splicing, producing an array of physical lines.
     *
     * Line numbers have to survive both transformations because every later
     * error message is reported against them, so a splice or a multi-line
     * comment emits the blank lines it swallowed rather than shifting
     * everything after it.
     */
    function stripCommentsAndSplice(source) {
        const lines = [];
        let cur = "";
        let pending = 0;
        let i = 0;
        const n = source.length;
        const endLine = () => {
            lines.push(cur);
            cur = "";
            for (let k = 0; k < pending; ++k) lines.push("");
            pending = 0;
        };
        while (i < n) {
            const c = source[i];
            if (c === "\\" && source[i + 1] === "\n") { i += 2; ++pending; continue; }
            if (c === "\\" && source[i + 1] === "\r" && source[i + 2] === "\n") {
                i += 3; ++pending; continue;
            }
            if (c === "\r") { ++i; continue; }
            if (c === "/" && source[i + 1] === "/") {
                while (i < n && source[i] !== "\n") ++i;
                continue;
            }
            if (c === "/" && source[i + 1] === "*") {
                i += 2;
                while (i < n && !(source[i] === "*" && source[i + 1] === "/")) {
                    if (source[i] === "\n") ++pending;
                    ++i;
                }
                if (i >= n) fail(0, "unterminated block comment");
                i += 2;
                cur += " ";
                continue;
            }
            if (c === "\n") { endLine(); ++i; continue; }
            cur += c;
            ++i;
        }
        endLine();
        return lines;
    }

    // Preprocessor tokens are coarser than GLSL tokens: identifiers, numbers,
    // whitespace, and single punctuation characters. Macro expansion only ever
    // needs to recognise identifiers.
    const PP_TOKEN = /([A-Za-z_][A-Za-z0-9_]*)|(\d+\.\d*(?:[eE][+-]?\d+)?[fF]?|\.\d+(?:[eE][+-]?\d+)?[fF]?|\d+[eE][+-]?\d+[fF]?|0[xX][0-9a-fA-F]+|\d+)|(\s+)|([\s\S])/g;

    function ppTokenize(text) {
        const tokens = [];
        let m;
        PP_TOKEN.lastIndex = 0;
        while ((m = PP_TOKEN.exec(text)) !== null) {
            if (m[1] !== undefined) tokens.push({ type: "id", value: m[1] });
            else if (m[2] !== undefined) tokens.push({ type: "num", value: m[2] });
            else if (m[3] !== undefined) tokens.push({ type: "ws", value: " " });
            else tokens.push({ type: "punct", value: m[4] });
        }
        return tokens;
    }

    function ppJoin(tokens) {
        let out = "";
        for (const t of tokens) out += t.value;
        return out;
    }

    const SUPPORTED_EXTENSIONS = new Set([
        "GL_ARB_texture_rectangle",
        "GL_ARB_draw_buffers",
        "GL_ARB_shader_texture_lod",
        "GL_ARB_texture_cube_map",
        "GL_ARB_shading_language_120",
        "GL_OES_standard_derivatives",
        "GL_EXT_gpu_shader4",
    ]);

    /* GLSL ES 1.00's (options.es: OpenGL ES 2.0's shaders, src/gles/glsl_es.js) */
    const ES_EXTENSIONS = new Set([
        "GL_OES_standard_derivatives",
        "GL_OES_EGL_image_external",
    ]);

    class Preprocessor {
        constructor(stage, options) {
            this.stage = stage;
            this.options = options || {};
            this.macros = new Map();
            this.version = 110;
            this.extensions = new Map();
            this.warnings = [];
            this.defineBuiltins();
        }

        defineBuiltins() {
            const objectMacro = (name, value) =>
                this.macros.set(name, { params: null, body: ppTokenize(value) });
            if (this.options.es) {
                // GLSL ES 1.00, 3.4: GL_ES, and the fragment stage's highp
                this.version = 100;
                objectMacro("__VERSION__", "100");
                objectMacro("GL_ES", "1");
                if (this.stage === "fragment") objectMacro("GL_FRAGMENT_PRECISION_HIGH", "1");
                for (const ext of ES_EXTENSIONS) objectMacro(ext, "1");
                for (const [name, value] of Object.entries(this.options.defines || {}))
                    objectMacro(name, String(value));
                return;
            }
            objectMacro("__VERSION__", "110");
            objectMacro("GL_ARB_texture_rectangle", "1");
            for (const [name, value] of Object.entries(this.options.defines || {}))
                objectMacro(name, String(value));
            // __LINE__ and __FILE__ are substituted dynamically, not stored.
        }

        run(source) {
            const lines = stripCommentsAndSplice(source);
            this.out = [];
            this.conditionals = [];
            this.line = 1;
            this.sawNonDirective = false;

            for (let i = 0; i < lines.length; ++i) {
                this.line = i + 1;
                const raw = lines[i];
                const trimmed = raw.replace(/^[ \t]+/, "");
                if (trimmed.startsWith("#")) {
                    this.directive(trimmed.slice(1).replace(/^[ \t]+/, ""));
                    this.out.push("");
                    continue;
                }
                if (!this.active()) { this.out.push(""); continue; }
                if (raw.trim().length) this.sawNonDirective = true;
                this.out.push(this.expandLine(raw));
            }
            if (this.conditionals.length) fail(this.line, "unterminated #if");
            return {
                text: this.out.join("\n"),
                version: this.version,
                extensions: this.extensions,
                warnings: this.warnings,
            };
        }

        active() {
            for (const c of this.conditionals) if (!c.active) return false;
            return true;
        }

        parentActive() {
            for (let i = 0; i < this.conditionals.length - 1; ++i)
                if (!this.conditionals[i].active) return false;
            return true;
        }

        pushConditional(value) {
            const active = this.active() && value;
            this.conditionals.push({ active, everActive: active, sawElse: false });
        }

        directive(body) {
            const m = /^([A-Za-z_][A-Za-z0-9_]*)?/.exec(body);
            const name = m[1] || "";
            const rest = body.slice(name.length);

            // Conditional directives are processed even inside an inactive
            // region -- otherwise nesting could not be tracked.
            switch (name) {
            case "":
                return;
            case "ifdef":
            case "ifndef": {
                if (!this.active()) { this.pushConditional(false); return; }
                const id = this.expectIdentifier(rest);
                const defined = this.macros.has(id);
                this.pushConditional(name === "ifdef" ? defined : !defined);
                return;
            }
            case "if": {
                if (!this.active()) { this.pushConditional(false); return; }
                this.pushConditional(this.evalCondition(rest) !== 0);
                return;
            }
            case "elif": {
                const top = this.conditionals[this.conditionals.length - 1];
                if (!top) fail(this.line, "#elif without #if");
                if (top.sawElse) fail(this.line, "#elif after #else");
                if (top.everActive || !this.parentActive()) {
                    top.active = false;
                } else {
                    top.active = this.evalCondition(rest) !== 0;
                    if (top.active) top.everActive = true;
                }
                return;
            }
            case "else": {
                const top = this.conditionals[this.conditionals.length - 1];
                if (!top) fail(this.line, "#else without #if");
                if (top.sawElse) fail(this.line, "duplicate #else");
                top.sawElse = true;
                top.active = !top.everActive && this.parentActive();
                if (top.active) top.everActive = true;
                return;
            }
            case "endif": {
                if (!this.conditionals.length) fail(this.line, "#endif without #if");
                this.conditionals.pop();
                return;
            }
            }

            if (!this.active()) return;

            switch (name) {
            case "define":
                return this.defineDirective(rest);
            case "undef":
                this.macros.delete(this.expectIdentifier(rest));
                return;
            case "version": {
                if (this.sawNonDirective)
                    fail(this.line, "#version must precede any other statement");
                const v = /\s*(\d+)/.exec(rest);
                if (!v) fail(this.line, "malformed #version");
                this.version = parseInt(v[1], 10);
                if (this.options.es && this.version !== 100)
                    fail(this.line, "#version " + this.version + " is not supported: GLSL ES 1.00 is #version 100");
                if (this.version > 120) {
                    // Refusing outright turns a shader we might still translate
                    // into a hard failure; the analyzer rejects what it really
                    // cannot represent, with a message naming the construct.
                    this.warnings.push("#version " + this.version +
                        " requested; translating as GLSL 1.20");
                }
                this.macros.set("__VERSION__",
                    { params: null, body: ppTokenize(String(this.version)) });
                return;
            }
            case "extension": {
                const e = /\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_]+)/.exec(rest);
                if (!e) fail(this.line, "malformed #extension");
                const [, ext, behavior] = e;
                const supported = this.options.es ? ES_EXTENSIONS : SUPPORTED_EXTENSIONS;
                if (behavior === "require" && ext !== "all" &&
                        !supported.has(ext))
                    fail(this.line, "extension not supported: " + ext);
                if (behavior === "enable" && ext !== "all" &&
                        !supported.has(ext))
                    this.warnings.push("extension not supported: " + ext);
                this.extensions.set(ext, behavior);
                return;
            }
            case "line": {
                const expanded = ppJoin(this.expand(ppTokenize(rest)));
                const l = /\s*(\d+)/.exec(expanded);
                if (l) this.line = parseInt(l[1], 10) - 1;
                return;
            }
            case "error":
                fail(this.line, "#error" + rest);
                return;
            case "pragma":
                return;   // optimize/debug/STDGL invariant: no effect here
            default:
                fail(this.line, "unknown directive #" + name);
            }
        }

        expectIdentifier(rest) {
            const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)/.exec(rest);
            if (!m) fail(this.line, "expected an identifier");
            return m[1];
        }

        defineDirective(rest) {
            const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)/.exec(rest);
            if (!m) fail(this.line, "malformed #define");
            const name = m[1];
            let tail = rest.slice(m.index + m[0].length);
            let params = null;
            if (tail.startsWith("(")) {
                const close = tail.indexOf(")");
                if (close < 0) fail(this.line, "malformed macro parameter list");
                const inside = tail.slice(1, close).trim();
                params = inside.length ? inside.split(",").map(s => s.trim()) : [];
                for (const p of params)
                    if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(p))
                        fail(this.line, "malformed macro parameter: " + p);
                tail = tail.slice(close + 1);
            }
            this.macros.set(name, { params, body: ppTokenize(tail.trim()) });
        }

        expandLine(text) {
            return ppJoin(this.expand(ppTokenize(text)));
        }

        /*
         * Macro expansion with the usual no-self-reference rule: a macro is
         * hidden while its own body is being expanded, so `#define A A + 1`
         * terminates instead of recursing forever.
         */
        expand(tokens, hideSet) {
            const hidden = hideSet || new Set();
            const out = [];
            for (let i = 0; i < tokens.length; ++i) {
                const t = tokens[i];
                if (t.type !== "id") { out.push(t); continue; }
                if (t.value === "__LINE__") {
                    out.push({ type: "num", value: String(this.line) });
                    continue;
                }
                if (t.value === "__FILE__") {
                    out.push({ type: "num", value: "0" });
                    continue;
                }
                const macro = this.macros.get(t.value);
                if (!macro || hidden.has(t.value)) { out.push(t); continue; }

                if (macro.params === null) {
                    const nested = new Set(hidden);
                    nested.add(t.value);
                    out.push(...this.expand(macro.body, nested));
                    continue;
                }

                // A function-like macro only expands when the next non-space
                // token is '('. Otherwise the identifier stands for itself.
                let j = i + 1;
                while (j < tokens.length && tokens[j].type === "ws") ++j;
                if (j >= tokens.length || tokens[j].value !== "(") {
                    out.push(t);
                    continue;
                }
                let depth = 0;
                const args = [];
                let current = [];
                let k = j;
                for (; k < tokens.length; ++k) {
                    const tok = tokens[k];
                    if (tok.value === "(") {
                        ++depth;
                        if (depth === 1) continue;
                    } else if (tok.value === ")") {
                        --depth;
                        if (depth === 0) { args.push(current); break; }
                    } else if (tok.value === "," && depth === 1) {
                        args.push(current);
                        current = [];
                        continue;
                    }
                    current.push(tok);
                }
                if (depth !== 0) fail(this.line, "unterminated macro invocation");
                if (args.length === 1 && !macro.params.length &&
                        args[0].every(a => a.type === "ws"))
                    args.length = 0;
                if (args.length !== macro.params.length)
                    fail(this.line, "macro " + t.value + " expects " +
                        macro.params.length + " argument(s), got " + args.length);

                const substituted = [];
                const nested = new Set(hidden);
                nested.add(t.value);
                for (const bt of macro.body) {
                    if (bt.type === "id") {
                        const idx = macro.params.indexOf(bt.value);
                        if (idx >= 0) {
                            // Arguments are expanded in the caller's hide set,
                            // not the macro's, so a parameter naming the macro
                            // itself still expands once.
                            substituted.push({ type: "punct", value: "(" });
                            substituted.push(...this.expand(args[idx], hidden));
                            substituted.push({ type: "punct", value: ")" });
                            continue;
                        }
                    }
                    substituted.push(bt);
                }
                out.push(...this.expand(substituted, nested));
                i = k;
            }
            return out;
        }

        /*
         * #if expression evaluation. The operand grammar is C's, restricted to
         * integers: no floats, no sizeof, no casts. `defined X` and
         * `defined(X)` are resolved before macro expansion, per the spec.
         */
        evalCondition(text) {
            let tokens = ppTokenize(text).filter(t => t.type !== "ws");
            const resolved = [];
            for (let i = 0; i < tokens.length; ++i) {
                if (tokens[i].type === "id" && tokens[i].value === "defined") {
                    let j = i + 1;
                    let paren = false;
                    if (tokens[j] && tokens[j].value === "(") { paren = true; ++j; }
                    if (!tokens[j] || tokens[j].type !== "id")
                        fail(this.line, "malformed defined()");
                    const has = this.macros.has(tokens[j].value);
                    resolved.push({ type: "num", value: has ? "1" : "0" });
                    ++j;
                    if (paren) {
                        if (!tokens[j] || tokens[j].value !== ")")
                            fail(this.line, "malformed defined()");
                        ++j;
                    }
                    i = j - 1;
                    continue;
                }
                resolved.push(tokens[i]);
            }
            tokens = this.expand(resolved).filter(t => t.type !== "ws");
            // Any identifier surviving expansion evaluates to 0, per the C
            // rules the GLSL preprocessor inherits.
            const items = tokens.map(t =>
                t.type === "id" ? { type: "num", value: "0" } : t);
            return new PPExprParser(items, this.line).parse();
        }
    }

    const PP_TWO_CHAR = new Set(["&&", "||", "==", "!=", "<=", ">=", "<<", ">>"]);
    const PP_PRECEDENCE = {
        "||": 1, "&&": 2, "|": 3, "^": 4, "&": 5,
        "==": 6, "!=": 6,
        "<": 7, ">": 7, "<=": 7, ">=": 7,
        "<<": 8, ">>": 8,
        "+": 9, "-": 9,
        "*": 10, "/": 10, "%": 10,
    };

    function applyPPBinary(op, a, b, line) {
        switch (op) {
        case "||": return (a || b) ? 1 : 0;
        case "&&": return (a && b) ? 1 : 0;
        case "|": return a | b;
        case "^": return a ^ b;
        case "&": return a & b;
        case "==": return a === b ? 1 : 0;
        case "!=": return a !== b ? 1 : 0;
        case "<": return a < b ? 1 : 0;
        case ">": return a > b ? 1 : 0;
        case "<=": return a <= b ? 1 : 0;
        case ">=": return a >= b ? 1 : 0;
        case "<<": return a << b;
        case ">>": return a >> b;
        case "+": return (a + b) | 0;
        case "-": return (a - b) | 0;
        case "*": return Math.imul(a, b);
        case "/":
            if (b === 0) fail(line, "division by zero in #if");
            return (a / b) | 0;
        case "%":
            if (b === 0) fail(line, "division by zero in #if");
            return (a % b) | 0;
        default: fail(line, "unsupported operator '" + op + "' in #if");
        }
    }

    /* A precedence-climbing evaluator for #if. Integer only. */
    class PPExprParser {
        constructor(tokens, line) {
            this.tokens = tokens;
            this.pos = 0;
            this.line = line;
        }
        peek() { return this.tokens[this.pos]; }
        next() { return this.tokens[this.pos++]; }
        expect(v) {
            const t = this.next();
            if (!t || t.value !== v) fail(this.line, "expected '" + v + "' in #if");
            return t;
        }
        parse() {
            if (!this.tokens.length) fail(this.line, "empty #if expression");
            const value = this.ternary();
            if (this.pos !== this.tokens.length)
                fail(this.line, "trailing tokens in #if expression");
            return value;
        }
        ternary() {
            const cond = this.binary(1);
            if (this.peek() && this.peek().value === "?") {
                this.next();
                const a = this.ternary();
                this.expect(":");
                const b = this.ternary();
                return cond ? a : b;
            }
            return cond;
        }
        binary(minPrec) {
            let left = this.unary();
            for (;;) {
                const t = this.peek();
                if (!t) break;
                let op = t.value;
                const t2 = this.tokens[this.pos + 1];
                if (t2 && PP_TWO_CHAR.has(op + t2.value)) op = op + t2.value;
                const prec = PP_PRECEDENCE[op];
                if (prec === undefined || prec < minPrec) break;
                this.pos += op.length > 1 ? 2 : 1;
                const right = this.binary(prec + 1);
                left = applyPPBinary(op, left, right, this.line);
            }
            return left;
        }
        unary() {
            const t = this.peek();
            if (!t) fail(this.line, "unexpected end of #if expression");
            if (t.value === "(") {
                this.next();
                const value = this.ternary();
                this.expect(")");
                return value;
            }
            if (t.value === "!") { this.next(); return this.unary() ? 0 : 1; }
            if (t.value === "-") { this.next(); return -this.unary(); }
            if (t.value === "+") { this.next(); return this.unary(); }
            if (t.value === "~") { this.next(); return ~this.unary(); }
            if (t.type === "num") {
                this.next();
                const text = t.value.replace(/[uUlL]+$/, "");
                if (/^0[xX]/.test(text)) return parseInt(text, 16) | 0;
                if (/^0[0-7]+$/.test(text)) return parseInt(text, 8) | 0;
                if (/[.eEfF]/.test(text))
                    fail(this.line, "floating point is not allowed in #if");
                return parseInt(text, 10) | 0;
            }
            fail(this.line, "unexpected token '" + t.value + "' in #if");
        }
    }

    /* ================================================================== */
    /* Lexer                                                              */
    /* ================================================================== */

    const KEYWORDS = new Set([
        "attribute", "const", "uniform", "varying", "invariant", "centroid",
        "break", "continue", "do", "for", "while", "if", "else",
        "in", "out", "inout", "true", "false", "discard", "return", "struct",
        "void", "bool", "int", "float",
        "vec2", "vec3", "vec4", "bvec2", "bvec3", "bvec4",
        "ivec2", "ivec3", "ivec4",
        "mat2", "mat3", "mat4",
        "mat2x2", "mat2x3", "mat2x4", "mat3x2", "mat3x3", "mat3x4",
        "mat4x2", "mat4x3", "mat4x4",
        "sampler1D", "sampler2D", "sampler3D", "samplerCube",
        "sampler1DShadow", "sampler2DShadow",
        "sampler2DRect", "sampler2DRectShadow", "samplerExternalOES",
        "lowp", "mediump", "highp", "precision",
    ]);

    /* Words the spec reserves. Using one is an error rather than a silently
     * accepted identifier, because a shader that says `switch` means it and the
     * result of ignoring that is wrong pixels rather than a message. */
    const RESERVED = new Set([
        "asm", "class", "union", "enum", "typedef", "template", "this", "packed",
        "goto", "switch", "default", "inline", "noinline", "volatile", "public",
        "static", "extern", "external", "interface", "long", "short", "double",
        "half", "fixed", "unsigned", "input", "output",
        "hvec2", "hvec3", "hvec4", "dvec2", "dvec3", "dvec4",
        "fvec2", "fvec3", "fvec4", "sampler3DRect",
        "sizeof", "cast", "namespace", "using", "flat", "noperspective",
    ]);

    // Longest first: the lexer takes the first match, so "<<=" must precede
    // "<<" which must precede "<".
    const OPERATORS = [
        "<<=", ">>=",
        "++", "--", "<=", ">=", "==", "!=", "&&", "||", "^^",
        "*=", "/=", "+=", "-=", "%=", "&=", "^=", "|=", "<<", ">>",
        "(", ")", "[", "]", "{", "}", ".", ",", ":", ";", "?",
        "+", "-", "*", "/", "%", "<", ">", "&", "^", "|", "~", "!", "=",
    ];

    function lex(text) {
        const tokens = [];
        let i = 0;
        let line = 1;
        const n = text.length;
        while (i < n) {
            const c = text[i];
            if (c === "\n") { ++line; ++i; continue; }
            if (c === " " || c === "\t" || c === "\r" || c === "\f" || c === "\v") {
                ++i;
                continue;
            }
            if (/[A-Za-z_]/.test(c)) {
                let j = i + 1;
                while (j < n && /[A-Za-z0-9_]/.test(text[j])) ++j;
                const word = text.slice(i, j);
                if (RESERVED.has(word))
                    fail(line, "'" + word + "' is a reserved word in GLSL 1.20");
                tokens.push({
                    type: KEYWORDS.has(word) ? "keyword" : "ident",
                    value: word, line,
                });
                i = j;
                continue;
            }
            if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(text[i + 1] || ""))) {
                const m = /^(?:0[xX][0-9a-fA-F]+|(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?[fF]?|\d+)/.exec(text.slice(i));
                if (!m) fail(line, "malformed number");
                const raw = m[0];
                const isFloat = /[.eEfF]/.test(raw) && !/^0[xX]/.test(raw);
                let value;
                if (isFloat) {
                    value = parseFloat(raw.replace(/[fF]$/, ""));
                } else if (/^0[xX]/.test(raw)) {
                    value = parseInt(raw, 16) | 0;
                } else if (/^0[0-7]+$/.test(raw)) {
                    value = parseInt(raw, 8) | 0;
                } else {
                    value = parseInt(raw, 10) | 0;
                }
                tokens.push({ type: isFloat ? "float" : "int", value, raw, line });
                i += raw.length;
                continue;
            }
            let matched = null;
            for (const op of OPERATORS) {
                if (text.startsWith(op, i)) { matched = op; break; }
            }
            if (!matched) fail(line, "unexpected character '" + c + "'");
            tokens.push({ type: "op", value: matched, line });
            i += matched.length;
        }
        tokens.push({ type: "eof", value: "", line });
        return tokens;
    }

    /* ================================================================== */
    /* Parser                                                             */
    /* ================================================================== */

    const ASSIGN_OPS = new Set(["=", "+=", "-=", "*=", "/=", "%=",
        "<<=", ">>=", "&=", "^=", "|="]);

    // Binary precedence, lowest binding first. Bit operators are GLSL 1.30
    // and up, accepted here because EXT_gpu_shader4 shaders in the wild use
    // them and rejecting costs more than accepting.
    const BINARY_PRECEDENCE = {
        "||": 1, "^^": 2, "&&": 3,
        "|": 4, "^": 5, "&": 6,
        "==": 7, "!=": 7,
        "<": 8, ">": 8, "<=": 8, ">=": 8,
        "<<": 9, ">>": 9,
        "+": 10, "-": 10,
        "*": 11, "/": 11, "%": 11,
    };

    class Parser {
        constructor(tokens, stage) {
            this.tokens = tokens;
            this.pos = 0;
            this.stage = stage;
            this.structs = new Map();   // name -> type, so the statement parser
                                        // can tell a declaration from an
                                        // expression that starts with an ident
        }

        peek(offset) { return this.tokens[this.pos + (offset || 0)]; }
        get line() { return this.peek().line; }
        next() { return this.tokens[this.pos++]; }
        at(value) {
            const t = this.peek();
            return (t.type === "op" || t.type === "keyword") && t.value === value;
        }
        accept(value) {
            if (this.at(value)) { ++this.pos; return true; }
            return false;
        }
        expect(value) {
            if (!this.at(value))
                fail(this.line, "expected '" + value + "' but found '" +
                    String(this.peek().value) + "'");
            return this.next();
        }
        expectIdent() {
            const t = this.peek();
            if (t.type !== "ident")
                fail(t.line, "expected an identifier but found '" +
                    String(t.value) + "'");
            ++this.pos;
            return t.value;
        }

        parseProgram() {
            const decls = [];
            while (this.peek().type !== "eof") {
                const decl = this.parseExternalDeclaration();
                if (decl) decls.push(decl);
            }
            return { kind: "Program", decls };
        }

        /* `precision mediump float;` is GLSL ES syntax that desktop shaders
         * nonetheless carry when they are shared between the two. It has no
         * meaning at 1.20, so it parses and disappears. */
        parsePrecisionStatement() {
            this.expect("precision");
            const t = this.next();
            if (!["lowp", "mediump", "highp"].includes(t.value))
                fail(t.line, "expected a precision qualifier");
            this.parseTypeSpecifier();
            this.expect(";");
            return null;
        }

        parseExternalDeclaration() {
            if (this.at("precision")) return this.parsePrecisionStatement();
            if (this.accept(";")) return null;

            const line = this.line;
            const qualifiers = this.parseQualifiers();

            // struct S { ... } [name];
            if (this.at("struct")) {
                const struct = this.parseStructSpecifier();
                if (this.at(";")) { this.next(); return { kind: "StructDecl", struct, line }; }
                const declarators = this.parseDeclaratorList(struct.type);
                this.expect(";");
                return { kind: "VarDecl", qualifiers, type: struct.type,
                         declarators, struct, line };
            }

            const type = this.parseTypeSpecifier();

            // A function definition or prototype.
            if (this.peek().type === "ident" && this.peek(1) &&
                    this.peek(1).type === "op" && this.peek(1).value === "(") {
                const name = this.expectIdent();
                const params = this.parseParameterList();
                if (this.accept(";"))
                    return { kind: "FunctionProto", name, returnType: type,
                             params, line };
                const body = this.parseBlock();
                return { kind: "FunctionDef", name, returnType: type, params,
                         body, line };
            }

            if (this.at(";")) { this.next(); return null; }  // bare type spec
            const declarators = this.parseDeclaratorList(type);
            this.expect(";");
            return { kind: "VarDecl", qualifiers, type, declarators, line };
        }

        parseQualifiers() {
            const q = { storage: null, invariant: false, centroid: false,
                        direction: null };
            for (;;) {
                if (this.accept("invariant")) { q.invariant = true; continue; }
                if (this.accept("centroid")) { q.centroid = true; continue; }
                if (this.at("lowp") || this.at("mediump") || this.at("highp")) {
                    this.next();
                    continue;
                }
                if (this.at("const") || this.at("attribute") || this.at("uniform") ||
                        this.at("varying")) {
                    if (q.storage)
                        fail(this.line, "conflicting storage qualifiers");
                    q.storage = this.next().value;
                    continue;
                }
                if (this.at("in") || this.at("out") || this.at("inout")) {
                    q.direction = this.next().value;
                    continue;
                }
                break;
            }
            return q;
        }

        parseStructSpecifier() {
            this.expect("struct");
            let name = null;
            if (this.peek().type === "ident") name = this.expectIdent();
            this.expect("{");
            const fields = [];
            while (!this.at("}")) {
                this.parseQualifiers();
                const fieldType = this.parseTypeSpecifier();
                do {
                    const fname = this.expectIdent();
                    let ftype = fieldType;
                    if (this.accept("[")) {
                        const size = this.parseConstantIndex();
                        this.expect("]");
                        ftype = arrayOf(fieldType, size);
                    }
                    fields.push({ name: fname, type: ftype });
                } while (this.accept(","));
                this.expect(";");
            }
            this.expect("}");
            if (!fields.length) fail(this.line, "struct has no members");
            const structName = name || ("_anon" + this.structs.size);
            const type = structType(structName, fields);
            this.structs.set(structName, type);
            return { name: structName, type, fields };
        }

        parseTypeSpecifier() {
            const t = this.peek();
            if (t.type === "keyword" && BASIC_TYPES[t.value]) {
                ++this.pos;
                return BASIC_TYPES[t.value];
            }
            if (t.type === "keyword" && t.value === "struct")
                return this.parseStructSpecifier().type;
            if (t.type === "ident" && this.structs.has(t.value)) {
                ++this.pos;
                return this.structs.get(t.value);
            }
            fail(t.line, "expected a type but found '" + String(t.value) + "'");
        }

        parseDeclaratorList(baseType) {
            const declarators = [];
            do {
                const line = this.line;
                const name = this.expectIdent();
                let type = baseType;
                if (this.accept("[")) {
                    // An unsized array declaration is legal only when an
                    // initializer or a later redeclaration supplies the size;
                    // GLSL 1.20 also allows `varying vec4 v[]` sized by use,
                    // which the analyzer resolves.
                    let size = -1;
                    if (!this.at("]")) size = this.parseConstantIndex();
                    this.expect("]");
                    type = arrayOf(baseType, size);
                }
                let init = null;
                if (this.accept("=")) init = this.parseAssignment();
                declarators.push({ name, type, init, line });
            } while (this.accept(","));
            return declarators;
        }

        /* Array sizes must be integral constant expressions. Full constant
         * folding happens in the analyzer, but the parser needs enough of it
         * to build the type -- so it evaluates the literal-and-operator subset
         * here and defers anything else. */
        parseConstantIndex() {
            const expr = this.parseAssignment();
            const value = foldConstantInt(expr);
            if (value === null)
                fail(this.line, "array size must be an integral constant expression");
            if (value <= 0) fail(this.line, "array size must be positive");
            return value;
        }

        parseParameterList() {
            this.expect("(");
            const params = [];
            if (this.accept(")")) return params;
            if (this.at("void") && this.peek(1) && this.peek(1).value === ")") {
                this.next();
                this.expect(")");
                return params;
            }
            do {
                const line = this.line;
                const q = this.parseQualifiers();
                const baseType = this.parseTypeSpecifier();
                let name = null;
                let type = baseType;
                if (this.peek().type === "ident") name = this.expectIdent();
                if (this.accept("[")) {
                    const size = this.parseConstantIndex();
                    this.expect("]");
                    type = arrayOf(baseType, size);
                }
                params.push({
                    name, type, line,
                    direction: q.direction || "in",
                    isConst: q.storage === "const",
                });
            } while (this.accept(","));
            this.expect(")");
            return params;
        }

        parseBlock() {
            const line = this.line;
            this.expect("{");
            const stmts = [];
            while (!this.at("}")) {
                if (this.peek().type === "eof") fail(line, "unterminated block");
                const s = this.parseStatement();
                if (s) stmts.push(s);
            }
            this.expect("}");
            return { kind: "Block", stmts, line };
        }

        startsDeclaration() {
            const t = this.peek();
            if (t.type === "keyword") {
                if (BASIC_TYPES[t.value]) return true;
                if (["struct", "const", "attribute", "uniform", "varying",
                     "invariant", "centroid", "lowp", "mediump", "highp"].includes(t.value))
                    return true;
                return false;
            }
            // A declaration whose type is a user struct: `S s;` versus the
            // expression statement `S;` (which is meaningless) or `s.x = 1;`.
            if (t.type === "ident" && this.structs.has(t.value)) {
                const nt = this.peek(1);
                return !!nt && nt.type === "ident";
            }
            return false;
        }

        parseStatement() {
            const t = this.peek();
            if (t.type === "op") {
                if (t.value === "{") return this.parseBlock();
                if (t.value === ";") { this.next(); return null; }
            }
            if (t.type === "keyword") {
                switch (t.value) {
                case "if": return this.parseIf();
                case "for": return this.parseFor();
                case "while": return this.parseWhile();
                case "do": return this.parseDoWhile();
                case "return": {
                    const line = this.line;
                    this.next();
                    let expr = null;
                    if (!this.at(";")) expr = this.parseExpression();
                    this.expect(";");
                    return { kind: "Return", expr, line };
                }
                case "break": {
                    const line = this.line;
                    this.next();
                    this.expect(";");
                    return { kind: "Break", line };
                }
                case "continue": {
                    const line = this.line;
                    this.next();
                    this.expect(";");
                    return { kind: "Continue", line };
                }
                case "discard": {
                    const line = this.line;
                    if (this.stage !== "fragment")
                        fail(line, "discard is only allowed in a fragment shader");
                    this.next();
                    this.expect(";");
                    return { kind: "Discard", line };
                }
                case "precision":
                    return this.parsePrecisionStatement();
                }
            }
            if (this.startsDeclaration()) return this.parseDeclarationStatement();
            const line = this.line;
            const expr = this.parseExpression();
            this.expect(";");
            return { kind: "ExprStmt", expr, line };
        }

        parseDeclarationStatement() {
            const line = this.line;
            const qualifiers = this.parseQualifiers();
            if (this.at("struct")) {
                const struct = this.parseStructSpecifier();
                if (this.accept(";")) return { kind: "StructDecl", struct, line };
                const declarators = this.parseDeclaratorList(struct.type);
                this.expect(";");
                return { kind: "VarDecl", qualifiers, type: struct.type,
                         declarators, struct, line };
            }
            const type = this.parseTypeSpecifier();
            const declarators = this.parseDeclaratorList(type);
            this.expect(";");
            return { kind: "VarDecl", qualifiers, type, declarators, line };
        }

        parseIf() {
            const line = this.line;
            this.expect("if");
            this.expect("(");
            const cond = this.parseExpression();
            this.expect(")");
            const then = this.parseStatement();
            let otherwise = null;
            if (this.accept("else")) otherwise = this.parseStatement();
            return { kind: "If", cond, then, otherwise, line };
        }

        parseWhile() {
            const line = this.line;
            this.expect("while");
            this.expect("(");
            const cond = this.parseExpression();
            this.expect(")");
            const body = this.parseStatement();
            return { kind: "While", cond, body, line };
        }

        parseDoWhile() {
            const line = this.line;
            this.expect("do");
            const body = this.parseStatement();
            this.expect("while");
            this.expect("(");
            const cond = this.parseExpression();
            this.expect(")");
            this.expect(";");
            return { kind: "DoWhile", body, cond, line };
        }

        parseFor() {
            const line = this.line;
            this.expect("for");
            this.expect("(");
            let init = null;
            if (this.at(";")) this.next();
            else if (this.startsDeclaration()) init = this.parseDeclarationStatement();
            else {
                init = { kind: "ExprStmt", expr: this.parseExpression(),
                         line: this.line };
                this.expect(";");
            }
            let cond = null;
            if (!this.at(";")) cond = this.parseExpression();
            this.expect(";");
            let step = null;
            if (!this.at(")")) step = this.parseExpression();
            this.expect(")");
            const body = this.parseStatement();
            return { kind: "For", init, cond, step, body, line };
        }

        /* ---- expressions ---- */

        parseExpression() {
            let expr = this.parseAssignment();
            while (this.at(",")) {
                const line = this.line;
                this.next();
                const right = this.parseAssignment();
                expr = { kind: "Sequence", left: expr, right, line };
            }
            return expr;
        }

        parseAssignment() {
            const start = this.pos;
            const left = this.parseConditional();
            const t = this.peek();
            if (t.type === "op" && ASSIGN_OPS.has(t.value)) {
                const line = t.line;
                this.next();
                const value = this.parseAssignment();
                return { kind: "Assign", op: t.value, target: left, value, line };
            }
            void start;
            return left;
        }

        parseConditional() {
            const cond = this.parseBinary(1);
            if (this.at("?")) {
                const line = this.line;
                this.next();
                const then = this.parseExpression();
                this.expect(":");
                const otherwise = this.parseAssignment();
                return { kind: "Conditional", cond, then, otherwise, line };
            }
            return cond;
        }

        parseBinary(minPrec) {
            let left = this.parseUnary();
            for (;;) {
                const t = this.peek();
                if (t.type !== "op") break;
                const prec = BINARY_PRECEDENCE[t.value];
                if (prec === undefined || prec < minPrec) break;
                const line = t.line;
                this.next();
                const right = this.parseBinary(prec + 1);
                left = { kind: "Binary", op: t.value, left, right, line };
            }
            return left;
        }

        parseUnary() {
            const t = this.peek();
            if (t.type === "op" &&
                    ["++", "--", "+", "-", "!", "~"].includes(t.value)) {
                const line = t.line;
                this.next();
                const operand = this.parseUnary();
                return { kind: "Unary", op: t.value, operand, prefix: true, line };
            }
            return this.parsePostfix();
        }

        parsePostfix() {
            let expr = this.parsePrimary();
            for (;;) {
                const t = this.peek();
                if (t.type !== "op") break;
                if (t.value === "[") {
                    const line = t.line;
                    this.next();
                    const index = this.parseExpression();
                    this.expect("]");
                    expr = { kind: "Index", object: expr, index, line };
                    continue;
                }
                if (t.value === ".") {
                    const line = t.line;
                    this.next();
                    const name = this.expectIdent();
                    expr = { kind: "Field", object: expr, name, line };
                    continue;
                }
                if (t.value === "++" || t.value === "--") {
                    const line = t.line;
                    this.next();
                    expr = { kind: "Unary", op: t.value, operand: expr,
                             prefix: false, line };
                    continue;
                }
                break;
            }
            return expr;
        }

        parsePrimary() {
            const t = this.peek();
            if (t.type === "int") { this.next(); return { kind: "IntLit", value: t.value, line: t.line }; }
            if (t.type === "float") { this.next(); return { kind: "FloatLit", value: t.value, line: t.line }; }
            if (t.type === "keyword" && (t.value === "true" || t.value === "false")) {
                this.next();
                return { kind: "BoolLit", value: t.value === "true", line: t.line };
            }
            if (t.type === "op" && t.value === "(") {
                this.next();
                const expr = this.parseExpression();
                this.expect(")");
                return expr;
            }
            // Constructors read as calls whose callee names a type.
            if (t.type === "keyword" && BASIC_TYPES[t.value]) {
                this.next();
                const args = this.parseArguments();
                return { kind: "Call", callee: t.value, args,
                         constructType: BASIC_TYPES[t.value], line: t.line };
            }
            if (t.type === "ident") {
                this.next();
                if (this.at("(")) {
                    const args = this.parseArguments();
                    const structT = this.structs.get(t.value);
                    return { kind: "Call", callee: t.value, args,
                             constructType: structT || null, line: t.line };
                }
                return { kind: "Ident", name: t.value, line: t.line };
            }
            fail(t.line, "unexpected token '" + String(t.value) + "'");
        }

        parseArguments() {
            this.expect("(");
            const args = [];
            if (this.accept(")")) return args;
            if (this.at("void") && this.peek(1) && this.peek(1).value === ")") {
                this.next();
                this.expect(")");
                return args;
            }
            do {
                args.push(this.parseAssignment());
            } while (this.accept(","));
            this.expect(")");
            return args;
        }
    }

    /* Enough constant folding to size an array at parse time. Anything more
     * involved (a `const int` declared earlier) is resolved by the analyzer,
     * which re-checks every array size against the full constant environment. */
    function foldConstantInt(expr, env) {
        switch (expr.kind) {
        case "IntLit": return expr.value;
        case "Ident": {
            if (env && Object.prototype.hasOwnProperty.call(env, expr.name)) {
                const v = env[expr.name];
                return typeof v === "number" ? (v | 0) : null;
            }
            return null;
        }
        case "Unary": {
            const v = foldConstantInt(expr.operand, env);
            if (v === null) return null;
            if (expr.op === "-") return -v;
            if (expr.op === "+") return v;
            if (expr.op === "~") return ~v;
            return null;
        }
        case "Binary": {
            const a = foldConstantInt(expr.left, env);
            const b = foldConstantInt(expr.right, env);
            if (a === null || b === null) return null;
            switch (expr.op) {
            case "+": return (a + b) | 0;
            case "-": return (a - b) | 0;
            case "*": return Math.imul(a, b);
            case "/": return b === 0 ? null : (a / b) | 0;
            case "%": return b === 0 ? null : (a % b) | 0;
            case "<<": return a << b;
            case ">>": return a >> b;
            case "&": return a & b;
            case "|": return a | b;
            case "^": return a ^ b;
            default: return null;
            }
        }
        default:
            return null;
        }
    }

    /* ================================================================== */
    /* Built-in functions                                                 */
    /* ================================================================== */

    /*
     * Overloads are stored expanded: every genType entry becomes four concrete
     * signatures at module load. Resolution is then the same linear scan for
     * built-ins and user functions, which matters because GLSL's rule -- exact
     * match first, then a *unique* implicitly-convertible match -- has to be
     * applied identically to both, or a call like min(1, 2.0) resolves
     * differently depending on who declared it.
     */
    const F = BASIC_TYPES;
    const GEN_F = [F.float, F.vec2, F.vec3, F.vec4];
    const GEN_I = [F.int, F.ivec2, F.ivec3, F.ivec4];
    const MATRICES = [F.mat2, F.mat3, F.mat4, F.mat2x3, F.mat2x4,
        F.mat3x2, F.mat3x4, F.mat4x2, F.mat4x3];

    const builtinFunctions = new Map();   // name -> [overload]

    function addOverload(name, params, ret, emit, flags) {
        let list = builtinFunctions.get(name);
        if (!list) { list = []; builtinFunctions.set(name, list); }
        list.push({ name, params, ret, emit, ...(flags || {}) });
    }

    /* Straight rename: same argument order, same semantics. */
    function simple(wgslName) {
        return args => wgslName + "(" + args.join(", ") + ")";
    }

    function unaryGen(name, wgslName) {
        for (const t of GEN_F) addOverload(name, [t], t, simple(wgslName || name));
    }
    function binaryGen(name, wgslName) {
        for (const t of GEN_F) addOverload(name, [t, t], t, simple(wgslName || name));
    }
    function ternaryGen(name, wgslName) {
        for (const t of GEN_F)
            addOverload(name, [t, t, t], t, simple(wgslName || name));
    }

    unaryGen("radians"); unaryGen("degrees");
    unaryGen("sin"); unaryGen("cos"); unaryGen("tan");
    unaryGen("asin"); unaryGen("acos");
    unaryGen("atan");
    binaryGen("atan", "atan2");
    unaryGen("exp"); unaryGen("log"); unaryGen("exp2"); unaryGen("log2");
    unaryGen("sqrt");
    unaryGen("inversesqrt", "inverseSqrt");
    unaryGen("abs"); unaryGen("sign"); unaryGen("floor"); unaryGen("ceil");
    unaryGen("fract");
    binaryGen("pow");
    binaryGen("min"); binaryGen("max");
    ternaryGen("clamp");
    unaryGen("dFdx", "dpdx"); unaryGen("dFdy", "dpdy"); unaryGen("fwidth");

    /* GLSL's mod() is floor-based; WGSL's % is trunc-based, so they differ for
     * negative operands -- which is exactly where texture-coordinate wrapping
     * code lives. Emitting the definition rather than '%' is not pedantry. */
    const emitMod = args =>
        "(" + args[0] + " - " + args[1] + " * floor(" + args[0] + " / " + args[1] + "))";
    binaryGen("mod", null);
    builtinFunctions.get("mod").forEach(o => { o.emit = emitMod; });

    /* The (genType, float) forms: the scalar is broadcast. */
    for (let i = 1; i < GEN_F.length; ++i) {
        const t = GEN_F[i];
        const splat = s => typeToWGSL(t) + "(" + s + ")";
        addOverload("mod", [t, F.float], t,
            args => emitMod([args[0], splat(args[1])]));
        addOverload("min", [t, F.float], t,
            args => "min(" + args[0] + ", " + splat(args[1]) + ")");
        addOverload("max", [t, F.float], t,
            args => "max(" + args[0] + ", " + splat(args[1]) + ")");
        addOverload("clamp", [t, F.float, F.float], t,
            args => "clamp(" + args[0] + ", " + splat(args[1]) + ", " +
                splat(args[2]) + ")");
        addOverload("mix", [t, t, F.float], t,
            args => "mix(" + args[0] + ", " + args[1] + ", " + splat(args[2]) + ")");
        addOverload("step", [F.float, t], t,
            args => "step(" + splat(args[0]) + ", " + args[1] + ")");
        addOverload("smoothstep", [F.float, F.float, t], t,
            args => "smoothstep(" + splat(args[0]) + ", " + splat(args[1]) +
                ", " + args[2] + ")");
    }
    ternaryGen("mix");
    binaryGen("step");
    ternaryGen("smoothstep");

    /* Integer min/max/abs/sign/clamp come from EXT_gpu_shader4 and GLSL 1.30,
     * but shaders that declare the extension use them and they cost nothing. */
    for (const t of GEN_I) {
        addOverload("abs", [t], t, simple("abs"));
        addOverload("sign", [t], t, simple("sign"));
        addOverload("min", [t, t], t, simple("min"));
        addOverload("max", [t, t], t, simple("max"));
        addOverload("clamp", [t, t, t], t, simple("clamp"));
    }

    /* Geometric */
    for (const t of GEN_F) {
        addOverload("length", [t], F.float, simple("length"));
        addOverload("distance", [t, t], F.float, simple("distance"));
        addOverload("dot", [t, t], F.float, simple("dot"));
        addOverload("normalize", [t], t, simple("normalize"));
        addOverload("faceforward", [t, t, t], t, simple("faceForward"));
        addOverload("reflect", [t, t], t, simple("reflect"));
        addOverload("refract", [t, t, F.float], t, simple("refract"));
    }
    addOverload("cross", [F.vec3, F.vec3], F.vec3, simple("cross"));

    /* Matrix */
    for (const m of MATRICES) {
        addOverload("matrixCompMult", [m, m], m, args => {
            // WGSL has no componentwise matrix multiply; expanding it column
            // by column is the whole implementation.
            const cols = [];
            for (let c = 0; c < m.cols; ++c)
                cols.push("(" + args[0] + "[" + c + "] * " + args[1] + "[" + c + "])");
            return typeToWGSL(m) + "(" + cols.join(", ") + ")";
        });
        addOverload("transpose", [m], mat(m.rows, m.cols), simple("transpose"));
    }
    for (let c = 2; c <= 4; ++c) {
        for (let r = 2; r <= 4; ++r) {
            addOverload("outerProduct", [vec("float", r), vec("float", c)],
                mat(c, r), args => {
                    const cols = [];
                    for (let i = 0; i < c; ++i)
                        cols.push("(" + args[0] + " * " + args[1] + "[" + i + "])");
                    return "mat" + c + "x" + r + "<f32>(" + cols.join(", ") + ")";
                });
        }
    }

    /* Vector relational. WGSL spells these as operators on vectors, which
     * already produce vecN<bool>. */
    function relational(name, op) {
        for (let n = 2; n <= 4; ++n) {
            for (const base of ["float", "int"]) {
                const t = vec(base, n);
                addOverload(name, [t, t], vec("bool", n),
                    args => "(" + args[0] + " " + op + " " + args[1] + ")");
            }
        }
    }
    relational("lessThan", "<");
    relational("lessThanEqual", "<=");
    relational("greaterThan", ">");
    relational("greaterThanEqual", ">=");
    relational("equal", "==");
    relational("notEqual", "!=");
    for (let n = 2; n <= 4; ++n) {
        const bt = vec("bool", n);
        addOverload("equal", [bt, bt], bt, args => "(" + args[0] + " == " + args[1] + ")");
        addOverload("notEqual", [bt, bt], bt, args => "(" + args[0] + " != " + args[1] + ")");
        addOverload("any", [bt], F.bool, simple("any"));
        addOverload("all", [bt], F.bool, simple("all"));
        addOverload("not", [bt], bt, args => "(!" + args[0] + ")");
    }

    /*
     * noise() returns 0. The GLSL spec permits an implementation to return
     * zero and every desktop driver does, so a shader that genuinely depends
     * on it is already broken on real hardware. Deviation D-11.
     */
    for (const t of GEN_F) {
        addOverload("noise1", [t], F.float, () => "0.0", { noise: true });
        addOverload("noise2", [t], F.vec2, () => "vec2<f32>(0.0)", { noise: true });
        addOverload("noise3", [t], F.vec3, () => "vec3<f32>(0.0)", { noise: true });
        addOverload("noise4", [t], F.vec4, () => "vec4<f32>(0.0)", { noise: true });
    }

    /* ---- texture lookups ---------------------------------------------- */

    /*
     * A GLSL sampler is one value; WGSL needs a texture handle and a sampler
     * handle. Argument 0 of every lookup therefore expands to two WGSL
     * arguments, which ctx.samplerPair() produces. Shadow samplers expand to a
     * texture_depth_* plus a sampler_comparison.
     *
     * Coordinate handling per sampler dimension:
     *   1D      implemented as a height-1 2D texture, so u -> vec2(u, 0.5)
     *   2DRect  unnormalised coordinates -> divided by textureDimensions()
     *   Proj    the projective divide happens here, not in the sampler
     */
    function projSwizzle(size) {
        return ["x", "xy", "xyz"][size - 1];
    }

    function textureLookup(spec) {
        const { name, samplerType, coordType, bias, lod, proj } = spec;
        const params = [samplerType, coordType];
        if (bias || lod) params.push(F.float);
        addOverload(name, params, F.vec4, (args, node, ctx) => {
            const pair = ctx.samplerPair(node.args[0]);
            // A cube lookup takes three coordinates like a 3D one; getting
            // this wrong truncates the direction vector to .xy, which is
            // exactly what every cubemap shader in the Cube 2 corpus caught.
            const dims = (samplerType.dim === "3D" || samplerType.dim === "Cube") ?
                3 : (samplerType.dim === "1D" ? 1 : 2);
            const wComponent = coordType.size === 4 ? "w" : "z";
            let coord = args[1];
            if (proj) {
                coord = "(" + args[1] + "." + projSwizzle(dims) + " / " +
                    args[1] + "." + wComponent + ")";
            } else if (samplerType.shadow || coordType.size > dims) {
                // shadow2D takes vec3 for a 2D lookup: the extra component is
                // the depth reference, not a coordinate.
                coord = args[1] + "." + projSwizzle(dims);
            }
            if (samplerType.dim === "1D")
                coord = "vec2<f32>(" + coord + ", 0.5)";
            else if (samplerType.dim === "2DRect")
                coord = "(" + coord + " / vec2<f32>(textureDimensions(" +
                    pair.texture + ")))";

            if (samplerType.shadow) {
                const refExpr = proj ?
                    "(" + args[1] + ".z / " + args[1] + "." + wComponent + ")" :
                    args[1] + ".z";
                const call = lod ?
                    "textureSampleCompareLevel(" + pair.texture + ", " +
                        pair.sampler + ", " + coord + ", " + refExpr + ")" :
                    ctx.compareSample(pair, coord, refExpr);
                return "vec4<f32>(" + call + ")";
            }
            if (lod)
                return "textureSampleLevel(" + pair.texture + ", " +
                    pair.sampler + ", " + coord + ", " + args[2] + ")";
            return ctx.sample(pair, coord, bias ? args[2] : null);
        }, { texture: true, lod: !!lod, proj: !!proj });
    }

    (function registerTextureLookups() {
        const combos = [
            { prefix: "texture1D", st: F.sampler1D, coord: F.float, projCoords: [F.vec2, F.vec4] },
            { prefix: "texture2D", st: F.sampler2D, coord: F.vec2, projCoords: [F.vec3, F.vec4] },
            { prefix: "texture3D", st: F.sampler3D, coord: F.vec3, projCoords: [F.vec4] },
            { prefix: "textureCube", st: F.samplerCube, coord: F.vec3, projCoords: [] },
            { prefix: "texture2DRect", st: F.sampler2DRect, coord: F.vec2, projCoords: [F.vec3, F.vec4] },
        ];
        for (const c of combos) {
            textureLookup({ name: c.prefix, samplerType: c.st, coordType: c.coord });
            textureLookup({ name: c.prefix, samplerType: c.st, coordType: c.coord, bias: true });
            textureLookup({ name: c.prefix + "Lod", samplerType: c.st, coordType: c.coord, lod: true });
            for (const pc of c.projCoords) {
                textureLookup({ name: c.prefix + "Proj", samplerType: c.st, coordType: pc, proj: true });
                textureLookup({ name: c.prefix + "Proj", samplerType: c.st, coordType: pc, proj: true, bias: true });
                textureLookup({ name: c.prefix + "ProjLod", samplerType: c.st, coordType: pc, proj: true, lod: true });
            }
        }
        textureLookup({ name: "shadow1D", samplerType: F.sampler1DShadow, coordType: F.vec3 });
        textureLookup({ name: "shadow1D", samplerType: F.sampler1DShadow, coordType: F.vec3, bias: true });
        textureLookup({ name: "shadow1DLod", samplerType: F.sampler1DShadow, coordType: F.vec3, lod: true });
        textureLookup({ name: "shadow1DProj", samplerType: F.sampler1DShadow, coordType: F.vec4, proj: true });
        textureLookup({ name: "shadow2D", samplerType: F.sampler2DShadow, coordType: F.vec3 });
        textureLookup({ name: "shadow2D", samplerType: F.sampler2DShadow, coordType: F.vec3, bias: true });
        textureLookup({ name: "shadow2DLod", samplerType: F.sampler2DShadow, coordType: F.vec3, lod: true });
        textureLookup({ name: "shadow2DProj", samplerType: F.sampler2DShadow, coordType: F.vec4, proj: true });
        textureLookup({ name: "shadow2DProjLod", samplerType: F.sampler2DShadow, coordType: F.vec4, proj: true, lod: true });
        textureLookup({ name: "shadow2DRect", samplerType: F.sampler2DRectShadow, coordType: F.vec3 });
        textureLookup({ name: "shadow2DRectProj", samplerType: F.sampler2DRectShadow, coordType: F.vec4, proj: true });
    })();

    /* ftransform() must be bit-identical to the fixed-function transform, or a
     * depth pre-pass drawn with the fixed pipeline and a lighting pass drawn
     * with a shader will z-fight. Both go through the same expression. */
    addOverload("ftransform", [], F.vec4,
        (args, node, ctx) => ctx.ftransform(),
        { vertexOnly: true, usesState: ["mvp"] });

    /* ================================================================== */
    /* Built-in variables and compatibility state                          */
    /* ================================================================== */

    const GL_LIGHT_SOURCE = structType("gl_LightSourceParameters", [
        { name: "ambient", type: F.vec4 },
        { name: "diffuse", type: F.vec4 },
        { name: "specular", type: F.vec4 },
        { name: "position", type: F.vec4 },
        { name: "halfVector", type: F.vec4 },
        { name: "spotDirection", type: F.vec3 },
        { name: "spotExponent", type: F.float },
        { name: "spotCutoff", type: F.float },
        { name: "spotCosCutoff", type: F.float },
        { name: "constantAttenuation", type: F.float },
        { name: "linearAttenuation", type: F.float },
        { name: "quadraticAttenuation", type: F.float },
    ]);

    const GL_MATERIAL = structType("gl_MaterialParameters", [
        { name: "emission", type: F.vec4 },
        { name: "ambient", type: F.vec4 },
        { name: "diffuse", type: F.vec4 },
        { name: "specular", type: F.vec4 },
        { name: "shininess", type: F.float },
    ]);

    const GL_LIGHT_PRODUCTS = structType("gl_LightProducts", [
        { name: "ambient", type: F.vec4 },
        { name: "diffuse", type: F.vec4 },
        { name: "specular", type: F.vec4 },
    ]);

    const GL_LIGHT_MODEL = structType("gl_LightModelParameters", [
        { name: "ambient", type: F.vec4 },
    ]);

    const GL_LIGHT_MODEL_PRODUCTS = structType("gl_LightModelProducts", [
        { name: "sceneColor", type: F.vec4 },
    ]);

    const GL_FOG = structType("gl_FogParameters", [
        { name: "color", type: F.vec4 },
        { name: "density", type: F.float },
        { name: "start", type: F.float },
        { name: "end", type: F.float },
        { name: "scale", type: F.float },
    ]);

    const GL_DEPTH_RANGE = structType("gl_DepthRangeParameters", [
        { name: "near", type: F.float },
        { name: "far", type: F.float },
        { name: "diff", type: F.float },
    ]);

    const GL_POINT = structType("gl_PointParameters", [
        { name: "size", type: F.float },
        { name: "sizeMin", type: F.float },
        { name: "sizeMax", type: F.float },
        { name: "fadeThresholdSize", type: F.float },
        { name: "distanceConstantAttenuation", type: F.float },
        { name: "distanceLinearAttenuation", type: F.float },
        { name: "distanceQuadraticAttenuation", type: F.float },
    ]);

    const MAX_TEXTURE_COORDS = stateLayout.MAX_TEXTURE_COORDS;
    const MAX_LIGHTS = stateLayout.MAX_LIGHTS;
    const MAX_CLIP_PLANES = stateLayout.MAX_CLIP_PLANES;
    const MAX_DRAW_BUFFERS = 8;

    /*
     * Vertex attribute slots for the compatibility attributes.
     *
     * This is NVIDIA's classic aliasing layout, and it is not a free choice:
     * shaders and engines of this era assume it (gl_Vertex is attribute 0,
     * gl_MultiTexCoord0 is 8), and so does every tool that ever debugged them.
     * Generic attributes are assigned around it; see assignAttributeLocations.
     */
    const COMPAT_ATTRIBUTE_LOCATIONS = {
        gl_Vertex: 0,
        gl_Normal: 2,
        gl_Color: 3,
        gl_SecondaryColor: 4,
        gl_FogCoord: 5,
        gl_MultiTexCoord0: 8, gl_MultiTexCoord1: 9, gl_MultiTexCoord2: 10,
        gl_MultiTexCoord3: 11, gl_MultiTexCoord4: 12, gl_MultiTexCoord5: 13,
        gl_MultiTexCoord6: 14, gl_MultiTexCoord7: 15,
    };

    const COMPAT_ATTRIBUTE_TYPES = {
        gl_Vertex: F.vec4, gl_Normal: F.vec3, gl_Color: F.vec4,
        gl_SecondaryColor: F.vec4, gl_FogCoord: F.float,
        gl_MultiTexCoord0: F.vec4, gl_MultiTexCoord1: F.vec4,
        gl_MultiTexCoord2: F.vec4, gl_MultiTexCoord3: F.vec4,
        gl_MultiTexCoord4: F.vec4, gl_MultiTexCoord5: F.vec4,
        gl_MultiTexCoord6: F.vec4, gl_MultiTexCoord7: F.vec4,
    };

    /* Vertex outputs that are really varyings, and their fragment counterparts.
     * gl_TexCoord is an array in both stages: dynamic indexing of it is common
     * enough (a loop over texture units) that it cannot be flattened away. */
    const VERTEX_VARYING_OUTPUTS = {
        gl_FrontColor: F.vec4,
        gl_BackColor: F.vec4,
        gl_FrontSecondaryColor: F.vec4,
        gl_BackSecondaryColor: F.vec4,
        gl_TexCoord: arrayOf(F.vec4, MAX_TEXTURE_COORDS),
        gl_FogFragCoord: F.float,
    };

    const FRAGMENT_VARYING_INPUTS = {
        gl_Color: F.vec4,
        gl_SecondaryColor: F.vec4,
        gl_TexCoord: arrayOf(F.vec4, MAX_TEXTURE_COORDS),
        gl_FogFragCoord: F.float,
    };

    /* Which vertex output feeds which fragment input. Two-sided lighting makes
     * this a choice at the fragment end rather than a wire: gl_Color reads
     * gl_FrontColor or gl_BackColor depending on gl_FrontFacing. */
    const VARYING_LINKAGE = {
        gl_Color: { front: "gl_FrontColor", back: "gl_BackColor" },
        gl_SecondaryColor: { front: "gl_FrontSecondaryColor", back: "gl_BackSecondaryColor" },
        gl_TexCoord: { front: "gl_TexCoord", back: null },
        gl_FogFragCoord: { front: "gl_FogFragCoord", back: null },
    };

    /* GLSL name -> how to reach it inside the shared GLState block. `expr` is
     * used when the GLSL type maps onto one WGSL member with the same shape;
     * `members` handles the cases where GL packs several scalars into a vec4. */
    const STATE_UNIFORMS = {
        gl_ModelViewMatrix: { field: "modelview", type: F.mat4, expr: "glState.modelview" },
        gl_ProjectionMatrix: { field: "projection", type: F.mat4, expr: "glState.projection" },
        gl_ModelViewProjectionMatrix: { field: "mvp", type: F.mat4, expr: "glState.mvp" },
        gl_NormalMatrix: { field: "normalMatrix", type: F.mat3, expr: "glState.normalMatrix" },
        gl_ModelViewMatrixInverse: { field: "modelviewInverse", type: F.mat4, expr: "glState.modelviewInverse" },
        gl_ModelViewMatrixTranspose: { field: "modelviewTranspose", type: F.mat4, expr: "glState.modelviewTranspose" },
        gl_ModelViewMatrixInverseTranspose: { field: "modelviewInverseTranspose", type: F.mat4, expr: "glState.modelviewInverseTranspose" },
        gl_ProjectionMatrixInverse: { field: "projectionInverse", type: F.mat4, expr: "glState.projectionInverse" },
        gl_ProjectionMatrixTranspose: { field: "projectionTranspose", type: F.mat4, expr: "glState.projectionTranspose" },
        gl_ProjectionMatrixInverseTranspose: { field: "projectionInverseTranspose", type: F.mat4, expr: "glState.projectionInverseTranspose" },
        gl_ModelViewProjectionMatrixInverse: { field: "mvpInverse", type: F.mat4, expr: "glState.mvpInverse" },
        gl_ModelViewProjectionMatrixTranspose: { field: "mvpTranspose", type: F.mat4, expr: "glState.mvpTranspose" },
        gl_ModelViewProjectionMatrixInverseTranspose: { field: "mvpInverseTranspose", type: F.mat4, expr: "glState.mvpInverseTranspose" },
        gl_TextureMatrix: { field: "textureMatrix", type: arrayOf(F.mat4, MAX_TEXTURE_COORDS), expr: "glState.textureMatrix" },
        gl_TextureMatrixInverse: { field: "textureMatrixInverse", type: arrayOf(F.mat4, MAX_TEXTURE_COORDS), expr: "glState.textureMatrixInverse" },
        gl_TextureMatrixTranspose: { field: "textureMatrixTranspose", type: arrayOf(F.mat4, MAX_TEXTURE_COORDS), expr: "glState.textureMatrixTranspose" },
        gl_TextureMatrixInverseTranspose: { field: "textureMatrixInverseTranspose", type: arrayOf(F.mat4, MAX_TEXTURE_COORDS), expr: "glState.textureMatrixInverseTranspose" },
        gl_LightSource: { field: "lights", type: arrayOf(GL_LIGHT_SOURCE, MAX_LIGHTS), expr: "glState.lights" },
        gl_FrontMaterial: { field: "frontMaterial", type: GL_MATERIAL, expr: "glState.frontMaterial" },
        gl_BackMaterial: { field: "backMaterial", type: GL_MATERIAL, expr: "glState.backMaterial" },
        gl_FrontLightProduct: { field: "frontLightProduct", type: arrayOf(GL_LIGHT_PRODUCTS, MAX_LIGHTS), expr: "glState.frontLightProduct" },
        gl_BackLightProduct: { field: "backLightProduct", type: arrayOf(GL_LIGHT_PRODUCTS, MAX_LIGHTS), expr: "glState.backLightProduct" },
        gl_TextureEnvColor: { field: "texEnvColor", type: arrayOf(F.vec4, MAX_TEXTURE_COORDS), expr: "glState.texEnvColor" },
        gl_ClipPlane: { field: "clipPlanes", type: arrayOf(F.vec4, MAX_CLIP_PLANES), expr: "glState.clipPlanes" },

        gl_LightModel: { field: "lightModelAmbient", type: GL_LIGHT_MODEL, expr: null,
            members: { ambient: "glState.lightModelAmbient" } },
        gl_FrontLightModelProduct: { field: "frontSceneColor", type: GL_LIGHT_MODEL_PRODUCTS, expr: null,
            members: { sceneColor: "glState.frontSceneColor" } },
        gl_BackLightModelProduct: { field: "backSceneColor", type: GL_LIGHT_MODEL_PRODUCTS, expr: null,
            members: { sceneColor: "glState.backSceneColor" } },
        gl_Fog: { field: ["fogColor", "fogParams"], type: GL_FOG, expr: null,
            members: {
                color: "glState.fogColor",
                density: "glState.fogParams.x",
                start: "glState.fogParams.y",
                end: "glState.fogParams.z",
                scale: "glState.fogParams.w",
            } },
        gl_DepthRange: { field: "depthRange", type: GL_DEPTH_RANGE, expr: null,
            members: {
                near: "glState.depthRange.x",
                far: "glState.depthRange.y",
                diff: "glState.depthRange.z",
            } },
        gl_Point: { field: ["pointParams", "pointAttenuation"], type: GL_POINT, expr: null,
            members: {
                size: "glState.pointParams.x",
                sizeMin: "glState.pointParams.y",
                sizeMax: "glState.pointParams.z",
                fadeThresholdSize: "glState.pointParams.w",
                distanceConstantAttenuation: "glState.pointAttenuation.x",
                distanceLinearAttenuation: "glState.pointAttenuation.y",
                distanceQuadraticAttenuation: "glState.pointAttenuation.z",
            } },
    };

    /* The eye/object plane arrays are indexed per texture unit and stored
     * interleaved: unit u occupies 8 vec4 -- object planes S,T,R,Q then eye
     * planes S,T,R,Q -- so gl_EyePlaneT[u] is texGenPlanes[u*8 + 4 + 1]. */
    ["S", "T", "R", "Q"].forEach((coord, i) => {
        STATE_UNIFORMS["gl_ObjectPlane" + coord] = {
            field: "texGenPlanes", type: arrayOf(F.vec4, MAX_TEXTURE_COORDS),
            expr: null, planeStride: 8, planeOffset: i,
        };
        STATE_UNIFORMS["gl_EyePlane" + coord] = {
            field: "texGenPlanes", type: arrayOf(F.vec4, MAX_TEXTURE_COORDS),
            expr: null, planeStride: 8, planeOffset: 4 + i,
        };
    });

    const BUILTIN_CONSTANTS = {
        gl_MaxLights: { type: F.int, value: MAX_LIGHTS },
        gl_MaxClipPlanes: { type: F.int, value: MAX_CLIP_PLANES },
        gl_MaxTextureUnits: { type: F.int, value: 8 },
        gl_MaxTextureCoords: { type: F.int, value: MAX_TEXTURE_COORDS },
        gl_MaxVertexAttribs: { type: F.int, value: 16 },
        gl_MaxVertexUniformComponents: { type: F.int, value: 1024 },
        gl_MaxVaryingFloats: { type: F.int, value: 64 },
        gl_MaxVertexTextureImageUnits: { type: F.int, value: 16 },
        gl_MaxCombinedTextureImageUnits: { type: F.int, value: 24 },
        gl_MaxTextureImageUnits: { type: F.int, value: 16 },
        gl_MaxFragmentUniformComponents: { type: F.int, value: 1024 },
        gl_MaxDrawBuffers: { type: F.int, value: MAX_DRAW_BUFFERS },
    };

    /* Stage built-ins that are neither varyings nor state: they map onto a
     * WGSL entry-point builtin or an entry-point output. */
    const VERTEX_BUILTIN_OUTPUTS = {
        gl_Position: { type: F.vec4, required: true },
        gl_PointSize: { type: F.float },
        gl_ClipVertex: { type: F.vec4 },
    };

    /*
     * gl_PointCoord is deliberately not a WGSL builtin here. WebGPU has none:
     * its point-list topology draws one pixel, so the executor expands every
     * point into two triangles (plan 10.3) and the generated vertex wrapper
     * writes the corner's coordinate into an ordinary varying. A program that
     * reads gl_PointCoord therefore links in a point-sprite variant, and reads
     * (0.5, 0.5) -- the centre, which is what a 1-pixel point would sample --
     * when drawn as anything else.
     */
    const FRAGMENT_BUILTIN_INPUTS = {
        gl_FragCoord: { type: F.vec4, wgsl: "position" },
        gl_FrontFacing: { type: F.bool, wgsl: "front_facing" },
        gl_PointCoord: { type: F.vec2, wgsl: null, pointSpriteVarying: true },
    };

    const FRAGMENT_BUILTIN_OUTPUTS = {
        gl_FragColor: { type: F.vec4 },
        gl_FragData: { type: arrayOf(F.vec4, MAX_DRAW_BUFFERS) },
        gl_FragDepth: { type: F.float },
    };

    /* GLSL ES 1.00 (7.4): its constants are OpenGL ES 2.0's limits, which the
     * GLES host reports (src/gles/gles_caps.js); one draw buffer; no
     * gl_FragDepth, no compatibility state but gl_DepthRange, no fixed-function
     * attributes or varyings */
    const ES_BUILTIN_CONSTANTS = {
        gl_MaxVertexAttribs: { type: F.int, value: 16 },
        gl_MaxVertexUniformVectors: { type: F.int, value: 256 },
        gl_MaxVaryingVectors: { type: F.int, value: 15 },
        gl_MaxVertexTextureImageUnits: { type: F.int, value: 16 },
        gl_MaxCombinedTextureImageUnits: { type: F.int, value: 32 },
        gl_MaxTextureImageUnits: { type: F.int, value: 16 },
        gl_MaxFragmentUniformVectors: { type: F.int, value: 224 },
        gl_MaxDrawBuffers: { type: F.int, value: 1 },
    };
    const ES_FRAGMENT_BUILTIN_OUTPUTS = {
        gl_FragColor: { type: F.vec4 },
        gl_FragData: { type: arrayOf(F.vec4, 1) },
    };

    /* ================================================================== */
    /* Semantic analysis                                                  */
    /* ================================================================== */

    const SWIZZLE_SETS = [
        { chars: "xyzw" }, { chars: "rgba" }, { chars: "stpq" },
    ];

    function swizzleIndices(name) {
        for (const set of SWIZZLE_SETS) {
            let ok = true;
            const indices = [];
            for (const ch of name) {
                const idx = set.chars.indexOf(ch);
                if (idx < 0) { ok = false; break; }
                indices.push(idx);
            }
            if (ok) return indices;
        }
        return null;
    }

    /* Mangling exists because WGSL has no overloading. The type names are the
     * GLSL ones, so a mangled name is still readable in a shader dump -- which
     * matters when the only debugging tool is the generated source. */
    function mangle(name, paramTypes) {
        if (!paramTypes.length) return "glsl_" + name;
        return "glsl_" + name + "__" +
            paramTypes.map(t => t.name.replace(/[\[\]]/g, "_")).join("_");
    }

    class Scope {
        constructor(parent) {
            this.parent = parent;
            this.names = new Map();
        }
        lookup(name) {
            for (let s = this; s; s = s.parent) {
                const found = s.names.get(name);
                if (found) return found;
            }
            return null;
        }
        declare(name, symbol, line) {
            if (this.names.has(name))
                fail(line, "'" + name + "' is already declared in this scope");
            this.names.set(name, symbol);
            return symbol;
        }
    }

    class Analyzer {
        constructor(stage, ast, options) {
            this.stage = stage;
            this.ast = ast;
            this.options = options || {};
            this.globalScope = new Scope(null);
            this.scope = this.globalScope;
            this.functions = new Map();     // name -> [{params, returnType, def}]
            this.usage = {
                attributes: new Map(),      // name -> {type, isCompat}
                varyings: new Map(),        // name -> {type, isCompat, written, read}
                uniforms: [],               // declaration order
                uniformByName: new Map(),
                samplers: [],
                stateFields: new Set(),
                builtinInputs: new Set(),
                builtinOutputs: new Set(),
                texCoordMax: -1,
                texCoordDynamic: false,
                fragDataMax: -1,
                fragDataDynamic: false,
                usesDiscard: false,
                usesFragColor: false,
                usesFragData: false,
                writesFragDepth: false,
                writesPointSize: false,
                writesClipVertex: false,
                usesPointCoord: false,
                nonUniformSamples: 0,
                uniformSamples: 0,
                noiseCalls: 0,
            };
            this.constEnv = Object.create(null);
            this.controlFlowUniform = [true];
            this.currentFunction = null;
            this.loopDepth = 0;
        }

        get inUniformControlFlow() {
            return this.controlFlowUniform[this.controlFlowUniform.length - 1];
        }

        run() {
            this.declareBuiltins();
            // Two passes over the top level: function signatures first, so a
            // call may precede its definition the way GLSL allows after a
            // prototype, and so mutual recursion is diagnosed rather than
            // silently resolving to nothing.
            for (const decl of this.ast.decls) {
                if (decl.kind === "FunctionProto" || decl.kind === "FunctionDef")
                    this.declareFunction(decl);
            }
            for (const decl of this.ast.decls) {
                switch (decl.kind) {
                case "StructDecl": break;      // the parser already interned it
                case "VarDecl": this.globalVarDecl(decl); break;
                case "FunctionProto": break;
                case "FunctionDef": this.functionBody(decl); break;
                }
            }
            const main = this.functions.get("main");
            if (!main || !main.some(o => o.def && !o.params.length))
                fail(0, "no main() function");
            return this.usage;
        }

        declareBuiltins() {
            const g = this.globalScope;
            if (this.options.es) {
                for (const [name, info] of Object.entries(ES_BUILTIN_CONSTANTS))
                    g.names.set(name, { kind: "builtinConst", name, type: info.type,
                                        value: info.value });
                g.names.set("gl_DepthRange", { kind: "stateUniform", name: "gl_DepthRange",
                                               type: STATE_UNIFORMS.gl_DepthRange.type,
                                               info: STATE_UNIFORMS.gl_DepthRange });
                const outputs = this.stage === "vertex" ? VERTEX_BUILTIN_OUTPUTS : ES_FRAGMENT_BUILTIN_OUTPUTS;
                for (const [name, info] of Object.entries(outputs)) {
                    if (name === "gl_ClipVertex") continue;
                    g.names.set(name, { kind: "builtinOut", name, type: info.type, info });
                }
                if (this.stage === "fragment") {
                    for (const [name, info] of Object.entries(FRAGMENT_BUILTIN_INPUTS))
                        g.names.set(name, { kind: "builtinIn", name, type: info.type,
                                            info });
                }
                return;
            }
            for (const [name, info] of Object.entries(BUILTIN_CONSTANTS))
                g.names.set(name, { kind: "builtinConst", name, type: info.type,
                                    value: info.value });
            for (const [name, info] of Object.entries(STATE_UNIFORMS))
                g.names.set(name, { kind: "stateUniform", name, type: info.type,
                                    info });
            if (this.stage === "vertex") {
                for (const [name, type] of Object.entries(COMPAT_ATTRIBUTE_TYPES))
                    g.names.set(name, { kind: "compatAttribute", name, type,
                                        location: COMPAT_ATTRIBUTE_LOCATIONS[name] });
                for (const [name, type] of Object.entries(VERTEX_VARYING_OUTPUTS))
                    g.names.set(name, { kind: "compatVaryingOut", name, type });
                for (const [name, info] of Object.entries(VERTEX_BUILTIN_OUTPUTS))
                    g.names.set(name, { kind: "builtinOut", name, type: info.type,
                                        info });
            } else {
                for (const [name, type] of Object.entries(FRAGMENT_VARYING_INPUTS))
                    g.names.set(name, { kind: "compatVaryingIn", name, type });
                for (const [name, info] of Object.entries(FRAGMENT_BUILTIN_INPUTS))
                    g.names.set(name, { kind: "builtinIn", name, type: info.type,
                                        info });
                for (const [name, info] of Object.entries(FRAGMENT_BUILTIN_OUTPUTS))
                    g.names.set(name, { kind: "builtinOut", name, type: info.type,
                                        info });
            }
        }

        declareFunction(decl) {
            const paramTypes = decl.params.map(p => p.type);
            let list = this.functions.get(decl.name);
            if (!list) { list = []; this.functions.set(decl.name, list); }
            const existing = list.find(o =>
                o.params.length === paramTypes.length &&
                o.params.every((t, i) => sameType(t, paramTypes[i])));
            if (existing) {
                if (decl.kind === "FunctionDef") {
                    if (existing.def)
                        fail(decl.line, "'" + decl.name + "' is defined twice");
                    existing.def = decl;
                }
                if (!sameType(existing.returnType, decl.returnType))
                    fail(decl.line, "'" + decl.name +
                        "' redeclared with a different return type");
                decl.overload = existing;
                return existing;
            }
            if (builtinFunctions.has(decl.name) && decl.name !== "main") {
                // GLSL allows a user function to overload a built-in name; only
                // an identical signature is an error. Keeping both in separate
                // tables makes resolution prefer the user's, which matches the
                // spec's "user-defined functions hide built-ins" rule.
            }
            const overload = {
                name: decl.name,
                params: paramTypes,
                paramInfo: decl.params,
                returnType: decl.returnType,
                def: decl.kind === "FunctionDef" ? decl : null,
                mangled: decl.name === "main" ? "glsl_main" :
                    mangle(decl.name, paramTypes),
                hasOutputs: decl.params.some(p => p.direction !== "in"),
            };
            list.push(overload);
            decl.overload = overload;
            return overload;
        }

        globalVarDecl(decl) {
            const storage = decl.qualifiers.storage;
            for (const d of decl.declarators) {
                let type = d.type;
                if (type.kind === "array" && type.size < 0) {
                    // `varying vec4 v[];` is sized by its largest use. Nothing
                    // in the corpus does this, so it is refused with a message
                    // rather than guessed at.
                    fail(d.line, "unsized array '" + d.name +
                        "' is not supported; give it an explicit size");
                }
                const existing = this.globalScope.names.get(d.name);
                if (existing && existing.kind !== "builtinConst")
                    fail(d.line, "'" + d.name + "' is already declared");

                let symbol;
                if (storage === "attribute") {
                    if (this.stage !== "vertex")
                        fail(d.line, "attribute variables are vertex-shader only");
                    if (type.kind === "array" || type.kind === "struct")
                        fail(d.line, "an attribute may not be an array or a struct");
                    symbol = { kind: "attribute", name: d.name, type };
                    this.usage.attributes.set(d.name, { type, isCompat: false });
                } else if (storage === "varying") {
                    symbol = { kind: "varying", name: d.name, type,
                               centroid: decl.qualifiers.centroid,
                               invariant: decl.qualifiers.invariant };
                    this.usage.varyings.set(d.name, {
                        type, isCompat: false, written: false, read: false,
                    });
                } else if (storage === "uniform") {
                    symbol = { kind: "uniform", name: d.name, type };
                    this.registerUniform(d.name, type, d.line);
                } else if (storage === "const") {
                    if (!d.init) fail(d.line, "a const variable needs an initializer");
                    symbol = { kind: "const", name: d.name, type };
                } else {
                    symbol = { kind: "global", name: d.name, type };
                }
                this.globalScope.names.set(d.name, symbol);
                if (d.init) {
                    this.expr(d.init);
                    this.coerce(d.init, type, d.line);
                    if (storage === "const") {
                        const folded = foldConstantInt(d.init, this.constEnv);
                        if (folded !== null) this.constEnv[d.name] = folded;
                    }
                }
                d.symbol = symbol;
            }
        }

        registerUniform(name, type, line) {
            // Samplers are bindings, not buffer members; everything else joins
            // the user uniform block.
            const leafSamplers = [];
            collectSamplerLeaves(name, type, leafSamplers);
            if (leafSamplers.length) {
                // (an array of samplers is one leaf of arraySize elements)
                const elements = leafSamplers.reduce((n, leaf) => n + Math.max(1, leaf.arraySize), 0);
                if (elements !== countLeaves(type))
                    fail(line, "a struct mixing samplers with other members is " +
                        "not supported: " + name);
                for (const leaf of leafSamplers) {
                    this.usage.samplers.push({
                        name: leaf.path, type: leaf.type,
                        arraySize: leaf.arraySize || 0,
                        binding: -1,       // assigned at link time
                    });
                }
                this.usage.uniformByName.set(name, { name, type, sampler: true });
                return;
            }
            const entry = { name, type };
            this.usage.uniforms.push(entry);
            this.usage.uniformByName.set(name, entry);
        }

        functionBody(decl) {
            const overload = decl.overload || this.declareFunction(decl);
            this.currentFunction = overload;
            this.scope = new Scope(this.globalScope);
            for (const p of decl.params) {
                if (!p.name) continue;
                this.scope.declare(p.name, {
                    kind: "param", name: p.name, type: p.type,
                    direction: p.direction, isConst: p.isConst,
                }, p.line);
            }
            this.block(decl.body, false);
            this.scope = this.globalScope;
            this.currentFunction = null;
        }

        block(node, newScope = true) {
            const saved = this.scope;
            if (newScope) this.scope = new Scope(this.scope);
            for (const stmt of node.stmts) this.statement(stmt);
            this.scope = saved;
        }

        statement(node) {
            switch (node.kind) {
            case "Block": return this.block(node);
            case "VarDecl": return this.localVarDecl(node);
            case "StructDecl": return;
            case "ExprStmt": return void this.expr(node.expr);
            case "If": {
                this.expr(node.cond);
                this.requireBool(node.cond, "if");
                const uniform = this.inUniformControlFlow && !node.cond.nonUniform;
                this.controlFlowUniform.push(uniform);
                this.statement(node.then);
                if (node.otherwise) this.statement(node.otherwise);
                this.controlFlowUniform.pop();
                return;
            }
            case "While": {
                this.expr(node.cond);
                this.requireBool(node.cond, "while");
                this.enterLoop(node.cond.nonUniform, () => this.statement(node.body));
                return;
            }
            case "DoWhile": {
                this.enterLoop(true, () => this.statement(node.body));
                this.expr(node.cond);
                this.requireBool(node.cond, "do-while");
                return;
            }
            case "For": {
                const saved = this.scope;
                this.scope = new Scope(this.scope);
                if (node.init) this.statement(node.init);
                if (node.cond) {
                    this.expr(node.cond);
                    this.requireBool(node.cond, "for");
                }
                this.enterLoop(node.cond ? node.cond.nonUniform : true, () => {
                    if (node.step) this.expr(node.step);
                    this.statement(node.body);
                });
                this.scope = saved;
                return;
            }
            case "Return": {
                const expected = this.currentFunction ?
                    this.currentFunction.returnType : T.void;
                if (node.expr) {
                    this.expr(node.expr);
                    if (expected.kind === "void")
                        fail(node.line, "returning a value from a void function");
                    this.coerce(node.expr, expected, node.line);
                } else if (expected.kind !== "void") {
                    fail(node.line, "a non-void function must return a value");
                }
                return;
            }
            case "Break":
            case "Continue":
                if (!this.loopDepth)
                    fail(node.line, "'" + node.kind.toLowerCase() +
                        "' outside of a loop");
                return;
            case "Discard":
                this.usage.usesDiscard = true;
                return;
            default:
                fail(node.line || 0, "unsupported statement " + node.kind);
            }
        }

        enterLoop(condNonUniform, body) {
            const uniform = this.inUniformControlFlow && !condNonUniform;
            this.controlFlowUniform.push(uniform);
            ++this.loopDepth;
            body();
            --this.loopDepth;
            this.controlFlowUniform.pop();
        }

        localVarDecl(node) {
            for (const d of node.declarators) {
                if (d.type.kind === "array" && d.type.size < 0)
                    fail(d.line, "unsized local array '" + d.name + "'");
                if (d.type.kind === "sampler")
                    fail(d.line, "a sampler may only be a uniform or a parameter");
                const symbol = {
                    kind: node.qualifiers.storage === "const" ? "const" : "local",
                    name: d.name, type: d.type,
                    nonUniform: false,
                };
                if (d.init) {
                    this.expr(d.init);
                    this.coerce(d.init, d.type, d.line);
                    symbol.nonUniform = !!d.init.nonUniform;
                    if (node.qualifiers.storage === "const") {
                        const folded = foldConstantInt(d.init, this.constEnv);
                        if (folded !== null) this.constEnv[d.name] = folded;
                    }
                } else if (node.qualifiers.storage === "const") {
                    fail(d.line, "a const variable needs an initializer");
                }
                this.scope.declare(d.name, symbol, d.line);
                d.symbol = symbol;
            }
        }

        requireBool(node, where) {
            if (!sameType(node.type, T.bool))
                fail(node.line, where + " condition must be a bool, not " +
                    node.type.name);
        }

        /* Records the implicit conversion the analyzer decided on, so code
         * generation never has to re-derive it. */
        coerce(node, target, line) {
            if (sameType(node.type, target)) return;
            if (convertsTo(node.type, target)) {
                node.convertTo = target;
                return;
            }
            fail(line || node.line,
                "cannot convert " + node.type.name + " to " + target.name);
        }

        /* ---- expressions ---- */

        expr(node) {
            const type = this.exprInner(node);
            node.type = type;
            return type;
        }

        exprInner(node) {
            switch (node.kind) {
            case "IntLit": node.nonUniform = false; return T.int;
            case "FloatLit": node.nonUniform = false; return T.float;
            case "BoolLit": node.nonUniform = false; return T.bool;
            case "Ident": return this.identifier(node);
            case "Sequence":
                this.expr(node.left);
                this.expr(node.right);
                node.nonUniform = node.right.nonUniform;
                return node.right.type;
            case "Assign": return this.assignment(node);
            case "Conditional": return this.conditional(node);
            case "Binary": return this.binary(node);
            case "Unary": return this.unary(node);
            case "Index": return this.index(node);
            case "Field": return this.field(node);
            case "Call": return this.call(node);
            default:
                fail(node.line, "unsupported expression " + node.kind);
            }
        }

        identifier(node) {
            const symbol = this.scope.lookup(node.name);
            if (!symbol)
                fail(node.line, "undeclared identifier '" + node.name + "'");
            node.symbol = symbol;
            node.nonUniform = this.symbolIsNonUniform(symbol);
            this.noteSymbolUse(symbol, node);
            return symbol.type;
        }

        symbolIsNonUniform(symbol) {
            switch (symbol.kind) {
            case "attribute":
            case "compatAttribute":
            case "varying":
            case "compatVaryingIn":
            case "compatVaryingOut":
            case "builtinIn":
                return true;
            case "local":
            case "param":
                return !!symbol.nonUniform;
            default:
                return false;
            }
        }

        noteSymbolUse(symbol, node) {
            switch (symbol.kind) {
            case "compatAttribute":
                this.usage.attributes.set(symbol.name,
                    { type: symbol.type, isCompat: true,
                      location: symbol.location });
                break;
            case "attribute":
                this.usage.attributes.set(symbol.name,
                    { type: symbol.type, isCompat: false });
                break;
            case "varying": {
                const entry = this.usage.varyings.get(symbol.name);
                if (entry) {
                    if (this.stage === "vertex") entry.written = true;
                    else entry.read = true;
                }
                break;
            }
            case "compatVaryingIn":
            case "compatVaryingOut": {
                if (!this.usage.varyings.has(symbol.name))
                    this.usage.varyings.set(symbol.name, {
                        type: symbol.type, isCompat: true,
                        written: false, read: false,
                    });
                const entry = this.usage.varyings.get(symbol.name);
                if (this.stage === "vertex") entry.written = true;
                else entry.read = true;
                break;
            }
            case "stateUniform": {
                const fields = Array.isArray(symbol.info.field) ?
                    symbol.info.field : [symbol.info.field];
                for (const f of fields) this.usage.stateFields.add(f);
                break;
            }
            case "builtinIn":
                this.usage.builtinInputs.add(symbol.name);
                if (symbol.name === "gl_PointCoord")
                    this.usage.usesPointCoord = true;
                break;
            case "builtinOut":
                this.usage.builtinOutputs.add(symbol.name);
                if (symbol.name === "gl_FragColor") this.usage.usesFragColor = true;
                if (symbol.name === "gl_FragData") this.usage.usesFragData = true;
                if (symbol.name === "gl_FragDepth") this.usage.writesFragDepth = true;
                if (symbol.name === "gl_PointSize") this.usage.writesPointSize = true;
                if (symbol.name === "gl_ClipVertex") this.usage.writesClipVertex = true;
                break;
            }
            void node;
        }

        assignment(node) {
            this.expr(node.target);
            this.expr(node.value);
            this.requireLValue(node.target);
            if (node.op === "=") {
                this.coerce(node.value, node.target.type, node.line);
            } else {
                // Compound assignment: the arithmetic must be legal and the
                // result must fit back into the target without conversion.
                const op = node.op.slice(0, -1);
                const resultType = this.binaryResultType(op, node.target.type,
                    node.value.type, node);
                if (!sameType(resultType, node.target.type))
                    fail(node.line, "cannot assign " + resultType.name +
                        " to " + node.target.type.name);
            }
            this.propagateNonUniform(node.target, node.value.nonUniform);
            node.nonUniform = node.target.nonUniform || node.value.nonUniform;
            return node.target.type;
        }

        /* A local that is ever assigned a non-uniform value stays non-uniform
         * for the rest of the shader. Processing in source order makes this a
         * single pass; it can only over-approximate, which is the safe way for
         * a decision that picks textureSample versus textureSampleGrad. */
        propagateNonUniform(target, nonUniform) {
            if (!nonUniform) return;
            let node = target;
            while (node && (node.kind === "Field" || node.kind === "Index"))
                node = node.object;
            if (node && node.kind === "Ident" && node.symbol &&
                    (node.symbol.kind === "local" || node.symbol.kind === "param" ||
                     node.symbol.kind === "global"))
                node.symbol.nonUniform = true;
        }

        requireLValue(node) {
            let root = node;
            while (root.kind === "Field" || root.kind === "Index") {
                if (root.kind === "Field" && root.swizzle) {
                    const seen = new Set();
                    for (const i of root.swizzle) {
                        if (seen.has(i))
                            fail(root.line, "a swizzle used as an l-value may " +
                                "not repeat a component");
                        seen.add(i);
                    }
                }
                root = root.object;
            }
            if (root.kind !== "Ident")
                fail(node.line, "expression is not assignable");
            const symbol = root.symbol;
            switch (symbol.kind) {
            case "const":
            case "builtinConst":
                fail(node.line, "cannot assign to the constant '" + symbol.name + "'");
                break;
            case "uniform":
            case "stateUniform":
                fail(node.line, "cannot assign to the uniform '" + symbol.name + "'");
                break;
            case "attribute":
            case "compatAttribute":
                fail(node.line, "cannot assign to the attribute '" + symbol.name + "'");
                break;
            case "builtinIn":
                fail(node.line, "cannot assign to '" + symbol.name + "'");
                break;
            case "varying":
            case "compatVaryingIn":
                if (this.stage === "fragment")
                    fail(node.line, "cannot assign to the varying '" +
                        symbol.name + "' in a fragment shader");
                break;
            case "param":
                // (an `in` parameter is the function's own copy: only a
                // `const in` one is read-only)
                if (symbol.isConst)
                    fail(node.line, "cannot assign to the const parameter '" +
                        symbol.name + "'");
                break;
            }
        }

        conditional(node) {
            this.expr(node.cond);
            this.requireBool(node.cond, "?:");
            this.expr(node.then);
            this.expr(node.otherwise);
            let type;
            if (sameType(node.then.type, node.otherwise.type)) {
                type = node.then.type;
            } else if (convertsTo(node.then.type, node.otherwise.type)) {
                node.then.convertTo = node.otherwise.type;
                type = node.otherwise.type;
            } else if (convertsTo(node.otherwise.type, node.then.type)) {
                node.otherwise.convertTo = node.then.type;
                type = node.then.type;
            } else {
                fail(node.line, "the two arms of ?: have incompatible types (" +
                    node.then.type.name + " and " + node.otherwise.type.name + ")");
            }
            node.nonUniform = node.cond.nonUniform || node.then.nonUniform ||
                node.otherwise.nonUniform;
            return type;
        }

        binary(node) {
            this.expr(node.left);
            this.expr(node.right);
            node.nonUniform = node.left.nonUniform || node.right.nonUniform;
            return this.binaryResultType(node.op, node.left.type, node.right.type,
                node);
        }

        binaryResultType(op, left, right, node) {
            const line = node.line;
            switch (op) {
            case "&&": case "||": case "^^":
                if (!sameType(left, T.bool) || !sameType(right, T.bool))
                    fail(line, "'" + op + "' requires bool operands");
                return T.bool;
            case "==": case "!=":
                if (!sameType(left, right)) {
                    if (convertsTo(left, right)) node.left.convertTo = right;
                    else if (convertsTo(right, left)) node.right.convertTo = left;
                    else fail(line, "cannot compare " + left.name + " with " +
                        right.name);
                }
                if (left.kind === "sampler")
                    fail(line, "samplers cannot be compared");
                return T.bool;
            case "<": case ">": case "<=": case ">=":
                if (left.kind !== "scalar" || right.kind !== "scalar" ||
                        left.base === "bool" || right.base === "bool")
                    fail(line, "'" + op + "' requires scalar numeric operands");
                if (!sameType(left, right)) {
                    if (convertsTo(left, right)) node.left.convertTo = right;
                    else if (convertsTo(right, left)) node.right.convertTo = left;
                    else fail(line, "cannot compare " + left.name + " with " +
                        right.name);
                }
                return T.bool;
            case "<<": case ">>": case "&": case "|": case "^":
                if (this.options.es)
                    fail(line, "'" + op + "' is reserved in GLSL ES 1.00");
                if (baseOf(left) !== "int" || baseOf(right) !== "int")
                    fail(line, "'" + op + "' requires integer operands");
                return componentCount(left) >= componentCount(right) ? left : right;
            case "%":
                if (this.options.es)
                    fail(line, "'%' is reserved in GLSL ES 1.00");
                if (baseOf(left) !== "int" || baseOf(right) !== "int")
                    fail(line, "'%' requires integer operands in GLSL 1.20");
                return componentCount(left) >= componentCount(right) ? left : right;
            case "+": case "-": case "*": case "/":
                return this.arithmeticType(op, left, right, node);
            default:
                fail(line, "unsupported operator '" + op + "'");
            }
        }

        arithmeticType(op, left, right, node) {
            const line = node.line;
            const lb = baseOf(left), rb = baseOf(right);
            if (lb === "bool" || rb === "bool" || !lb || !rb)
                fail(line, "'" + op + "' cannot be applied to " + left.name +
                    " and " + right.name);

            // Mixed int/float: the int side converts. Matrices are float-only,
            // so an int operand next to a matrix converts too.
            let L = left, R = right;
            if (lb !== rb) {
                if (lb === "int") { node.left.convertTo = toFloatType(left); L = node.left.convertTo; }
                else { node.right.convertTo = toFloatType(right); R = node.right.convertTo; }
            } else if (lb === "int" && (left.kind === "matrix" || right.kind === "matrix")) {
                fail(line, "matrices are float-only");
            }

            if (op === "*") {
                if (L.kind === "matrix" && R.kind === "matrix") {
                    if (L.cols !== R.rows)
                        fail(line, "matrix dimensions do not agree: " +
                            L.name + " * " + R.name);
                    return mat(R.cols, L.rows);
                }
                if (L.kind === "matrix" && R.kind === "vector") {
                    if (L.cols !== R.size)
                        fail(line, L.name + " * " + R.name + " does not agree");
                    return vec("float", L.rows);
                }
                if (L.kind === "vector" && R.kind === "matrix") {
                    if (R.rows !== L.size)
                        fail(line, L.name + " * " + R.name + " does not agree");
                    return vec("float", R.cols);
                }
            }
            if (L.kind === "matrix" || R.kind === "matrix") {
                if (L.kind === "scalar") return R;
                if (R.kind === "scalar") return L;
                if (L.kind === "matrix" && R.kind === "matrix") {
                    if (L.cols !== R.cols || L.rows !== R.rows)
                        fail(line, "matrix dimensions do not agree");
                    return L;
                }
                fail(line, "'" + op + "' cannot mix " + L.name + " and " + R.name);
            }
            if (L.kind === "scalar" && R.kind === "scalar") {
                return L;
            }
            if (L.kind === "vector" && R.kind === "vector") {
                if (L.size !== R.size)
                    fail(line, "vector sizes do not agree: " + L.name + " " +
                        op + " " + R.name);
                return L;
            }
            // scalar-vector broadcast
            return L.kind === "vector" ? L : R;
        }

        unary(node) {
            this.expr(node.operand);
            node.nonUniform = node.operand.nonUniform;
            const t = node.operand.type;
            switch (node.op) {
            case "!":
                if (!sameType(t, T.bool))
                    fail(node.line, "'!' requires a bool operand");
                return T.bool;
            case "~":
                if (this.options.es)
                    fail(node.line, "'~' is reserved in GLSL ES 1.00");
                if (baseOf(t) !== "int")
                    fail(node.line, "'~' requires an integer operand");
                return t;
            case "-": case "+":
                if (!baseOf(t) || baseOf(t) === "bool")
                    fail(node.line, "'" + node.op + "' requires a numeric operand");
                return t;
            case "++": case "--":
                this.requireLValue(node.operand);
                if (!baseOf(t) || baseOf(t) === "bool")
                    fail(node.line, "'" + node.op + "' requires a numeric operand");
                return t;
            default:
                fail(node.line, "unsupported unary operator '" + node.op + "'");
            }
        }

        index(node) {
            this.expr(node.object);
            this.expr(node.index);
            if (baseOf(node.index.type) !== "int" ||
                    node.index.type.kind !== "scalar")
                fail(node.line, "an array index must be an integer");
            const constIndex = foldConstantInt(node.index, this.constEnv);
            node.constIndex = constIndex;
            node.nonUniform = node.object.nonUniform || node.index.nonUniform;

            const t = node.object.type;
            if (t.kind === "array") {
                if (constIndex !== null && (constIndex < 0 || constIndex >= t.size))
                    fail(node.line, "array index " + constIndex + " is out of range");
                this.noteArrayIndex(node, constIndex);
                return t.elem;
            }
            if (t.kind === "vector") {
                if (constIndex !== null && (constIndex < 0 || constIndex >= t.size))
                    fail(node.line, "vector index " + constIndex + " is out of range");
                return t.base === "float" ? T.float :
                    (t.base === "int" ? T.int : T.bool);
            }
            if (t.kind === "matrix") {
                if (constIndex !== null && (constIndex < 0 || constIndex >= t.cols))
                    fail(node.line, "matrix column " + constIndex + " is out of range");
                return vec("float", t.rows);
            }
            fail(node.line, t.name + " cannot be indexed");
        }

        /* gl_TexCoord and gl_FragData decide how many varying slots and colour
         * attachments the program needs, so their index range is tracked here
         * rather than rediscovered at code generation. */
        noteArrayIndex(node, constIndex) {
            let base = node.object;
            if (base.kind !== "Ident" || !base.symbol) return;
            const name = base.symbol.name;
            if (name === "gl_TexCoord") {
                if (constIndex === null) this.usage.texCoordDynamic = true;
                else this.usage.texCoordMax = Math.max(this.usage.texCoordMax, constIndex);
            } else if (name === "gl_FragData") {
                if (constIndex === null) this.usage.fragDataDynamic = true;
                else this.usage.fragDataMax = Math.max(this.usage.fragDataMax, constIndex);
            } else if (base.symbol.kind === "uniform" &&
                    base.symbol.type.kind === "array" &&
                    base.symbol.type.elem.kind === "sampler") {
                if (constIndex === null)
                    fail(node.line, "a sampler array must be indexed by a " +
                        "constant expression (WGSL has no binding arrays)");
            }
        }

        field(node) {
            this.expr(node.object);
            node.nonUniform = node.object.nonUniform;
            const t = node.object.type;
            if (t.kind === "struct") {
                const f = t.fields.find(x => x.name === node.name);
                if (!f)
                    fail(node.line, t.name + " has no member '" + node.name + "'");
                node.structField = f;
                return f.type;
            }
            if (t.kind === "vector" || t.kind === "scalar") {
                const indices = swizzleIndices(node.name);
                if (!indices)
                    fail(node.line, "'" + node.name + "' is not a valid swizzle");
                const size = t.kind === "scalar" ? 1 : t.size;
                for (const i of indices)
                    if (i >= size)
                        fail(node.line, "swizzle component out of range for " +
                            t.name);
                if (indices.length > 4)
                    fail(node.line, "a swizzle may select at most 4 components");
                node.swizzle = indices;
                const base = baseOf(t);
                return indices.length === 1 ?
                    (base === "float" ? T.float : (base === "int" ? T.int : T.bool)) :
                    vec(base, indices.length);
            }
            if (t.kind === "array" && node.name === "length")
                fail(node.line, ".length() is GLSL 1.20+ on arrays only in " +
                    "later versions; use the declared size");
            fail(node.line, t.name + " has no member '" + node.name + "'");
        }

        call(node) {
            for (const arg of node.args) this.expr(arg);
            node.nonUniform = node.args.some(a => a.nonUniform);

            if (node.constructType) return this.constructorCall(node);

            // A user function hides a built-in of the same name, per the spec.
            const userList = this.functions.get(node.callee);
            if (userList) {
                const resolved = this.resolveOverload(userList, node);
                if (resolved) {
                    node.resolved = resolved;
                    node.userCall = true;
                    if (resolved.hasOutputs) this.checkOutputArgs(node, resolved);
                    return resolved.returnType;
                }
            }
            const builtinList = builtinFunctions.get(node.callee);
            if (builtinList) {
                const resolved = this.resolveOverload(builtinList, node);
                if (resolved) {
                    node.resolved = resolved;
                    node.builtinCall = true;
                    this.noteBuiltinCall(resolved, node);
                    return resolved.ret;
                }
                fail(node.line, "no overload of '" + node.callee +
                    "' matches (" + node.args.map(a => a.type.name).join(", ") + ")");
            }
            if (userList)
                fail(node.line, "no overload of '" + node.callee +
                    "' matches (" + node.args.map(a => a.type.name).join(", ") + ")");
            fail(node.line, "call to undeclared function '" + node.callee + "'");
        }

        noteBuiltinCall(overload, node) {
            if (overload.texture) {
                /* What WGSL constrains is uniform *control flow*, not a uniform
                 * coordinate: a varying texcoord is the normal case and does
                 * not force explicit gradients. Conflating the two costs every
                 * ordinary sample its mip selection. */
                const uniform = this.inUniformControlFlow;
                node.uniformSample = uniform;
                if (uniform) ++this.usage.uniformSamples;
                else ++this.usage.nonUniformSamples;
            }
            if (overload.name === "ftransform") {
                // ftransform() is gl_ModelViewProjectionMatrix * gl_Vertex, so
                // it uses the attribute whether or not the shader names it.
                this.usage.attributes.set("gl_Vertex", {
                    type: COMPAT_ATTRIBUTE_TYPES.gl_Vertex, isCompat: true,
                    location: COMPAT_ATTRIBUTE_LOCATIONS.gl_Vertex,
                });
            }
            if (overload.noise) ++this.usage.noiseCalls;
            if (overload.vertexOnly && this.stage !== "vertex")
                fail(node.line, "'" + overload.name +
                    "' is only available in a vertex shader");
            for (const field of overload.usesState || [])
                this.usage.stateFields.add(field);
        }

        checkOutputArgs(node, overload) {
            overload.paramInfo.forEach((p, i) => {
                if (p.direction === "in") return;
                this.requireLValue(node.args[i]);
                this.propagateNonUniform(node.args[i], true);
            });
        }

        /*
         * GLSL overload resolution: an exact match wins outright; otherwise
         * there must be exactly one candidate all of whose arguments convert
         * implicitly. Ambiguity is an error rather than a first-match win,
         * because picking silently is how min(1, 2.0) ends up integer.
         */
        resolveOverload(list, node) {
            const argTypes = node.args.map(a => a.type);
            const arity = list.filter(o =>
                (o.params ? o.params.length : 0) === argTypes.length);
            const exact = arity.find(o =>
                o.params.every((p, i) => sameType(p, argTypes[i])));
            if (exact) return exact;
            const convertible = arity.filter(o =>
                o.params.every((p, i) => convertsTo(argTypes[i], p)));
            if (convertible.length === 1) {
                convertible[0].params.forEach((p, i) => {
                    if (!sameType(argTypes[i], p)) node.args[i].convertTo = p;
                });
                return convertible[0];
            }
            if (convertible.length > 1)
                fail(node.line, "ambiguous call to '" + node.callee + "'");
            return null;
        }

        constructorCall(node) {
            const target = node.constructType;
            const args = node.args;
            if (!args.length)
                fail(node.line, "a constructor needs at least one argument");

            if (target.kind === "struct") {
                if (args.length !== target.fields.length)
                    fail(node.line, target.name + " takes " +
                        target.fields.length + " arguments");
                target.fields.forEach((f, i) => this.coerce(args[i], f.type, node.line));
                return target;
            }
            if (target.kind === "scalar") {
                if (args.length !== 1)
                    fail(node.line, target.name + "() takes one argument");
                const from = args[0].type;
                if (from.kind !== "scalar" && from.kind !== "vector")
                    fail(node.line, "cannot construct " + target.name +
                        " from " + from.name);
                return target;
            }
            if (target.kind === "vector") {
                if (args.length === 1 && args[0].type.kind === "scalar")
                    return target;           // splat
                let available = 0;
                for (const a of args) {
                    if (a.type.kind === "matrix") {
                        available += componentCount(a.type);
                    } else if (a.type.kind === "scalar" || a.type.kind === "vector") {
                        available += componentCount(a.type);
                    } else {
                        fail(node.line, "cannot use " + a.type.name +
                            " in a vector constructor");
                    }
                }
                if (available < target.size)
                    fail(node.line, target.name + "() needs " + target.size +
                        " components but was given " + available);
                return target;
            }
            if (target.kind === "matrix") {
                if (args.length === 1) {
                    const from = args[0].type;
                    if (from.kind === "scalar") return target;      // diagonal
                    if (from.kind === "matrix") return target;      // resize
                    fail(node.line, "cannot construct " + target.name +
                        " from " + from.name);
                }
                let available = 0;
                let allColumns = args.length === target.cols;
                for (const a of args) {
                    if (a.type.kind === "vector") {
                        if (a.type.size !== target.rows) allColumns = false;
                    } else if (a.type.kind === "scalar") {
                        allColumns = false;
                    } else {
                        fail(node.line, "cannot use " + a.type.name +
                            " in a matrix constructor");
                    }
                    available += componentCount(a.type);
                }
                node.matrixFromColumns = allColumns;
                if (!allColumns && available < target.cols * target.rows)
                    fail(node.line, target.name + "() needs " +
                        (target.cols * target.rows) + " components");
                return target;
            }
            fail(node.line, "cannot construct " + target.name);
        }
    }

    function toFloatType(t) {
        if (t.kind === "scalar") return T.float;
        if (t.kind === "vector") return vec("float", t.size);
        return t;
    }

    function countLeaves(type) {
        if (type.kind === "array") return type.size * countLeaves(type.elem);
        if (type.kind === "struct")
            return type.fields.reduce((n, f) => n + countLeaves(f.type), 0);
        return 1;
    }

    function collectSamplerLeaves(path, type, out) {
        if (type.kind === "sampler") {
            out.push({ path, type, arraySize: 0 });
            return;
        }
        if (type.kind === "array") {
            if (type.elem.kind === "sampler") {
                out.push({ path, type: type.elem, arraySize: type.size });
                return;
            }
            for (let i = 0; i < type.size; ++i)
                collectSamplerLeaves(path + "[" + i + "]", type.elem, out);
            return;
        }
        if (type.kind === "struct") {
            for (const f of type.fields)
                collectSamplerLeaves(path + "." + f.name, f.type, out);
        }
    }

    /* ================================================================== */
    /* Uniform block layout                                               */
    /* ================================================================== */

    /*
     * Every member of the user uniform block is placed at a 16-byte boundary
     * and given an explicit @align/@size. WGSL's own layout rules would work
     * out for most of these, but "most" is the problem: a mismatch between the
     * offsets this file computes and the offsets the WGSL compiler chooses is
     * invisible until a uniform reads as garbage, and the difference shows up
     * only for the awkward types (a lone float, a vec3, a mat3). Pinning both
     * sides to the same rule removes the class of bug.
     *
     * Two consequences worth knowing:
     *   - a float uniform costs 16 bytes; uniform space is 64 KB, so this has
     *     never mattered
     *   - an array of float/vec2/vec3 is declared array<vec4<f32>, N>, because
     *     the uniform address space requires a 16-byte array stride. Reads go
     *     through a generated accessor so the swizzle stays out of the
     *     expression generator.
     */

    function roundUp(value, alignment) {
        return Math.ceil(value / alignment) * alignment;
    }

    function matrixColumnStrideBytes(type) {
        return type.rows === 2 ? 8 : 16;
    }

    function naturalSizeBytes(type) {
        switch (type.kind) {
        case "scalar": return 4;
        case "vector": return type.size * 4;
        case "matrix": return type.cols * matrixColumnStrideBytes(type);
        default: throw new Error("naturalSizeBytes: " + type.kind);
        }
    }

    /* The WGSL type a uniform member is declared with, plus how a shader reads
     * a value of the GLSL type back out of it. */
    function uniformStorageFor(type) {
        if (type.kind === "scalar") {
            if (type.base === "bool")
                return { wgsl: "i32", read: e => "(" + e + " != 0)" };
            return { wgsl: typeToWGSL(type), read: e => e };
        }
        if (type.kind === "vector") {
            if (type.base === "bool") {
                const it = "vec" + type.size + "<i32>";
                return { wgsl: it,
                         read: e => "(" + e + " != " + it + "(0))" };
            }
            return { wgsl: typeToWGSL(type), read: e => e };
        }
        if (type.kind === "matrix")
            return { wgsl: typeToWGSL(type), read: e => e };
        throw new Error("uniformStorageFor: " + type.kind);
    }

    /* Element storage for an array member: scalars and short vectors are
     * widened to a vec4 so the stride is 16. */
    function uniformArrayElementFor(type) {
        if (type.kind === "scalar" || type.kind === "vector") {
            const base = type.base === "bool" ? "i32" :
                (type.base === "int" ? "i32" : "f32");
            const count = type.kind === "scalar" ? 1 : type.size;
            const wgsl = "vec4<" + base + ">";
            const swizzle = ["x", "xy", "xyz", "xyzw"][count - 1];
            const read = e => {
                const v = e + "." + swizzle;
                if (type.base !== "bool") return v;
                const zero = count === 1 ? "0" : "vec" + count + "<i32>(0)";
                return "(" + v + " != " + zero + ")";
            };
            return { wgsl, strideBytes: 16, read, componentsUsed: count };
        }
        if (type.kind === "matrix") {
            const size = roundUp(naturalSizeBytes(type), 16);
            return { wgsl: typeToWGSL(type), strideBytes: size, read: e => e,
                     componentsUsed: type.cols * type.rows };
        }
        return null;
    }

    class UniformBlockLayout {
        constructor() {
            this.members = [];        // WGSL struct members, in order
            this.leaves = new Map();  // GL uniform path -> leaf descriptor
            this.structs = [];        // generated WGSL struct declarations
            this.structNames = new Map();
            this.accessors = [];      // generated WGSL accessor functions
            this.cursor = 0;
        }

        get sizeBytes() { return roundUp(this.cursor, 16); }

        /* Declares one GLSL uniform. Returns a descriptor code generation uses
         * to read it: `read` for a plain value, `readIndexed` for an array. */
        add(name, type) {
            const offset = roundUp(this.cursor, 16);
            const wgslName = "u_" + name;
            const descriptor = this.place(name, wgslName, type, offset);
            this.cursor = offset + descriptor.sizeBytes;
            this.members.push({
                wgslName, wgslType: descriptor.wgslType,
                align: 16, size: descriptor.sizeBytes,
            });
            return descriptor;
        }

        place(glslPath, wgslPath, type, offset) {
            if (type.kind === "sampler")
                throw new Error("samplers do not live in the uniform block");

            if (type.kind === "array") {
                const elem = type.elem;
                if (elem.kind === "struct") {
                    const structName = this.declareStruct(elem);
                    const elemSize = this.structSizeBytes(elem);
                    for (let i = 0; i < type.size; ++i) {
                        this.placeStructLeaves(
                            glslPath + "[" + i + "]",
                            "glUniforms." + wgslPath + "[" + i + "]",
                            elem, offset + i * elemSize);
                    }
                    return {
                        wgslType: "array<" + structName + ", " + type.size + ">",
                        sizeBytes: elemSize * type.size,
                        kind: "structArray",
                    };
                }
                const storage = uniformArrayElementFor(elem);
                if (!storage)
                    throw new Error("unsupported uniform array element " + elem.name);
                const accessor = "u_at_" + wgslPath;
                this.accessors.push(
                    "fn " + accessor + "(i : i32) -> " + typeToWGSL(elem) + " {\n" +
                    "    return " + storage.read("glUniforms." + wgslPath + "[i]") + ";\n" +
                    "}");
                const leaf = {
                    glslPath, type: elem, offsetBytes: offset,
                    arraySize: type.size, arrayStrideBytes: storage.strideBytes,
                    componentsUsed: storage.componentsUsed,
                    matrixColumnStrideBytes: elem.kind === "matrix" ?
                        matrixColumnStrideBytes(elem) : 0,
                    readIndexed: idx => accessor + "(" + idx + ")",
                };
                this.leaves.set(glslPath, leaf);
                return {
                    wgslType: "array<" + storage.wgsl + ", " + type.size + ">",
                    sizeBytes: storage.strideBytes * type.size,
                    kind: "array", leaf,
                };
            }

            if (type.kind === "struct") {
                const structName = this.declareStruct(type);
                this.placeStructLeaves(glslPath, "glUniforms." + wgslPath, type, offset);
                return { wgslType: structName,
                         sizeBytes: this.structSizeBytes(type), kind: "struct" };
            }

            const storage = uniformStorageFor(type);
            const leaf = {
                glslPath, type, offsetBytes: offset, arraySize: 0,
                arrayStrideBytes: 0,
                componentsUsed: componentCount(type),
                matrixColumnStrideBytes: type.kind === "matrix" ?
                    matrixColumnStrideBytes(type) : 0,
                read: storage.read("glUniforms." + wgslPath),
            };
            this.leaves.set(glslPath, leaf);
            return {
                wgslType: storage.wgsl,
                sizeBytes: roundUp(naturalSizeBytes(type), 16),
                kind: "scalar", leaf,
            };
        }

        placeStructLeaves(glslPath, wgslExpr, type, offset) {
            let cursor = offset;
            for (const field of type.fields) {
                const fieldOffset = roundUp(cursor, 16);
                const path = glslPath + "." + field.name;
                const expr = wgslExpr + "." + field.name;
                if (field.type.kind === "struct") {
                    this.placeStructLeaves(path, expr, field.type, fieldOffset);
                    cursor = fieldOffset + this.structSizeBytes(field.type);
                    continue;
                }
                if (field.type.kind === "array" && field.type.elem.kind === "struct") {
                    const elemSize = this.structSizeBytes(field.type.elem);
                    for (let i = 0; i < field.type.size; ++i)
                        this.placeStructLeaves(path + "[" + i + "]", expr + "[" + i + "]",
                            field.type.elem, fieldOffset + i * elemSize);
                    cursor = fieldOffset + elemSize * field.type.size;
                    continue;
                }
                if (field.type.kind === "array") {
                    const storage = uniformArrayElementFor(field.type.elem);
                    if (!storage)
                        throw new Error("unsupported uniform array element " +
                            field.type.elem.name);
                    this.leaves.set(path, {
                        glslPath: path, type: field.type.elem,
                        offsetBytes: fieldOffset,
                        arraySize: field.type.size,
                        arrayStrideBytes: storage.strideBytes,
                        componentsUsed: storage.componentsUsed,
                        matrixColumnStrideBytes: field.type.elem.kind === "matrix" ?
                            matrixColumnStrideBytes(field.type.elem) : 0,
                        readIndexed: idx => storage.read(expr + "[" + idx + "]"),
                    });
                    cursor = fieldOffset + storage.strideBytes * field.type.size;
                    continue;
                }
                const storage = uniformStorageFor(field.type);
                this.leaves.set(path, {
                    glslPath: path, type: field.type, offsetBytes: fieldOffset,
                    arraySize: 0, arrayStrideBytes: 0,
                    componentsUsed: componentCount(field.type),
                    matrixColumnStrideBytes: field.type.kind === "matrix" ?
                        matrixColumnStrideBytes(field.type) : 0,
                    read: storage.read(expr),
                });
                cursor = fieldOffset + roundUp(naturalSizeBytes(field.type), 16);
            }
        }

        structSizeBytes(type) {
            let cursor = 0;
            for (const field of type.fields) {
                cursor = roundUp(cursor, 16);
                if (field.type.kind === "struct")
                    cursor += this.structSizeBytes(field.type);
                else if (field.type.kind === "array" && field.type.elem.kind === "struct")
                    cursor += this.structSizeBytes(field.type.elem) * field.type.size;
                else if (field.type.kind === "array") {
                    const storage = uniformArrayElementFor(field.type.elem);
                    cursor += storage.strideBytes * field.type.size;
                } else {
                    cursor += roundUp(naturalSizeBytes(field.type), 16);
                }
            }
            return roundUp(cursor, 16);
        }

        /*
         * A uniform struct keeps the user's own type name.
         *
         * Declaring a separate padded twin was the obvious design and the wrong
         * one: WGSL types are nominal, so `f(lights[0])` then fails to match a
         * parameter declared with the GLSL struct. Emitting one type -- the
         * user's, with @align/@size on its members -- means a uniform struct and
         * a local of the same GLSL type really are the same WGSL type. The
         * padding costs a few bytes on locals and nothing else.
         */
        declareStruct(type) {
            if (this.structNames.has(type.name)) return this.structNames.get(type.name);
            const wgslName = safeName(type.name);
            this.structNames.set(type.name, wgslName);
            const lines = ["struct " + wgslName + " {"];
            for (const field of type.fields) {
                let wgslType;
                let size;
                if (field.type.kind === "struct") {
                    wgslType = this.declareStruct(field.type);
                    size = this.structSizeBytes(field.type);
                } else if (field.type.kind === "array" && field.type.elem.kind === "struct") {
                    wgslType = "array<" + this.declareStruct(field.type.elem) + ", " +
                        field.type.size + ">";
                    size = this.structSizeBytes(field.type.elem) * field.type.size;
                } else if (field.type.kind === "array") {
                    const storage = uniformArrayElementFor(field.type.elem);
                    wgslType = "array<" + storage.wgsl + ", " + field.type.size + ">";
                    size = storage.strideBytes * field.type.size;
                } else {
                    wgslType = uniformStorageFor(field.type).wgsl;
                    size = roundUp(naturalSizeBytes(field.type), 16);
                }
                lines.push("    @align(16) @size(" + size + ") " +
                    field.name + " : " + wgslType + ",");
            }
            lines.push("}");
            this.structs.push(lines.join("\n"));
            return wgslName;
        }

        structText() {
            const lines = ["struct GLUniforms {"];
            if (!this.members.length) {
                lines.push("    _unused : vec4<f32>,");
            } else {
                for (const m of this.members)
                    lines.push("    @align(16) @size(" + m.size + ") " +
                        m.wgslName + " : " + m.wgslType + ",");
            }
            lines.push("}");
            return (this.structs.length ? this.structs.join("\n\n") + "\n\n" : "") +
                lines.join("\n");
        }
    }

    /* ================================================================== */
    /* Link-time interface assignment                                     */
    /* ================================================================== */

    const MAX_INTER_STAGE_SLOTS = 16;
    const MAX_VERTEX_ATTRIBUTES = 16;

    /*
     * Attribute locations.
     *
     * The compatibility attributes sit at their historical slots (gl_Vertex 0,
     * gl_MultiTexCoord0 8, ...) because engines and tools of this era assume
     * them. glBindAttribLocation wins over everything. Generic attributes with
     * neither a binding nor a fixed slot are packed downward from 15, which
     * keeps them clear of gl_Vertex/gl_Normal/gl_Color at the bottom -- the
     * aliasing that made this layout famous is only safe when the two never
     * both appear, and here they can.
     */
    /* Desktop GL's generic attributes fill from the top, below the
     * compatibility ones' fixed slots; GLSL ES has none of those, so with
     * `ascending` (options.es) they take the lowest free locations in
     * declaration order, as ES drivers commonly do. */
    function assignAttributeLocations(usage, bindings, ascending) {
        const used = new Set();
        const result = new Map();
        for (const [name, info] of usage.attributes) {
            if (info.isCompat) {
                const loc = COMPAT_ATTRIBUTE_LOCATIONS[name];
                result.set(name, loc);
                used.add(loc);
            }
        }
        for (const [name, info] of usage.attributes) {
            if (info.isCompat) continue;
            const bound = bindings && bindings.get(name);
            if (bound === undefined || bound === null) continue;
            if (bound < 0 || bound >= MAX_VERTEX_ATTRIBUTES)
                throw new GLSLError("glBindAttribLocation(" + name + ", " + bound +
                    ") is outside the 0.." + (MAX_VERTEX_ATTRIBUTES - 1) +
                    " range", 0);
            if (used.has(bound))
                throw new GLSLError("attribute location " + bound +
                    " is claimed twice (" + name + ")", 0);
            result.set(name, bound);
            used.add(bound);
        }
        if (ascending) {
            for (const [name, info] of usage.attributes) {
                if (info.isCompat || result.has(name)) continue;
                const slots = attributeSlotCount(info.type);
                let base = 0;
                while (base + slots <= MAX_VERTEX_ATTRIBUTES && !slotsFree(used, base, slots)) ++base;
                if (base + slots > MAX_VERTEX_ATTRIBUTES)
                    throw new GLSLError("out of vertex attribute slots for '" +
                        name + "'", 0);
                for (let i = 0; i < slots; ++i) used.add(base + i);
                result.set(name, base);
            }
            return result;
        }
        let next = MAX_VERTEX_ATTRIBUTES - 1;
        for (const [name, info] of usage.attributes) {
            if (info.isCompat || result.has(name)) continue;
            const slots = attributeSlotCount(info.type);
            while (next >= 0 && !slotsFree(used, next - slots + 1, slots)) --next;
            if (next - slots + 1 < 0)
                throw new GLSLError("out of vertex attribute slots for '" +
                    name + "'", 0);
            const base = next - slots + 1;
            for (let i = 0; i < slots; ++i) used.add(base + i);
            result.set(name, base);
            next = base - 1;
        }
        return result;
    }

    function slotsFree(used, base, count) {
        if (base < 0) return false;
        for (let i = 0; i < count; ++i) if (used.has(base + i)) return false;
        return true;
    }

    /* A mat3 attribute occupies three consecutive locations, as it does in
     * desktop GL. */
    function attributeSlotCount(type) {
        return type.kind === "matrix" ? type.cols : 1;
    }

    /*
     * Varying assignment.
     *
     * Only varyings written by the vertex stage *and* read by the fragment
     * stage get a slot: dropping the rest is what keeps gl_TexCoord[8] from
     * eating half the budget on a shader that touches gl_TexCoord[0] alone.
     * Small varyings are then packed into shared vec4 slots, greedily and in
     * declaration order, so the packing is stable across compiles and the
     * shader cache can key on it.
     */
    function assignVaryings(vsUsage, fsUsage, options) {
        const entries = [];

        const texCoordCount = varyingArrayExtent(vsUsage, fsUsage, "gl_TexCoord");
        const addCompat = (name, type) => {
            const inVS = vsUsage.varyings.has(name);
            const inFS = fsUsage.varyings.has(name);
            if (!inVS || !inFS) return;
            entries.push({ name, type, compat: true, components: componentCount(type) });
        };

        // gl_Color in the fragment stage is fed by gl_FrontColor (and
        // gl_BackColor when two-sided lighting is on), so the linkage is by
        // role, not by name.
        for (const [fsName, link] of Object.entries(VARYING_LINKAGE)) {
            if (fsName === "gl_TexCoord") continue;
            if (!fsUsage.varyings.has(fsName)) continue;
            const type = FRAGMENT_VARYING_INPUTS[fsName];
            const frontWritten = vsUsage.varyings.has(link.front);
            const backWritten = link.back && vsUsage.varyings.has(link.back);
            if (!frontWritten && !backWritten) continue;
            entries.push({
                name: fsName, type, compat: true, components: componentCount(type),
                vsFront: frontWritten ? link.front : null,
                vsBack: backWritten ? link.back : null,
                flat: !!(options && options.flatShading) &&
                    (fsName === "gl_Color" || fsName === "gl_SecondaryColor"),
            });
            if (backWritten && options && options.twoSided) {
                entries.push({
                    name: fsName + "__back", type, compat: true,
                    components: componentCount(type),
                    vsFront: link.back, vsBack: null, isBackHalf: true,
                    flat: !!(options && options.flatShading),
                });
            }
        }
        void addCompat;

        for (let i = 0; i < texCoordCount; ++i) {
            entries.push({
                name: "gl_TexCoord", index: i, type: F.vec4, compat: true,
                components: 4,
            });
        }

        for (const [name, info] of vsUsage.varyings) {
            if (info.isCompat) continue;
            const fsInfo = fsUsage.varyings.get(name);
            if (!fsInfo) continue;
            if (!sameType(info.type, fsInfo.type))
                throw new GLSLError("varying '" + name + "' is declared " +
                    info.type.name + " in the vertex shader and " +
                    fsInfo.type.name + " in the fragment shader", 0);
            const type = info.type;
            if (type.kind === "array") {
                for (let i = 0; i < type.size; ++i)
                    entries.push({ name, index: i, type: type.elem,
                                   components: componentCount(type.elem) });
            } else if (type.kind === "matrix") {
                for (let c = 0; c < type.cols; ++c)
                    entries.push({ name, column: c, type: vec("float", type.rows),
                                   components: type.rows });
            } else {
                entries.push({ name, type, components: componentCount(type) });
            }
        }

        // Greedy packing. Four-component entries take a whole slot; the rest
        // fill the first slot with room, which is why the vec4s are placed
        // first -- otherwise a stream of floats fragments every slot.
        const slots = [];
        const place = entry => {
            if (entry.components === 4) {
                slots.push({ used: 4, entries: [entry] });
                entry.slot = slots.length - 1;
                entry.offset = 0;
                return;
            }
            for (let i = 0; i < slots.length; ++i) {
                if (slots[i].used + entry.components <= 4) {
                    entry.slot = i;
                    entry.offset = slots[i].used;
                    slots[i].used += entry.components;
                    slots[i].entries.push(entry);
                    return;
                }
            }
            slots.push({ used: entry.components, entries: [entry] });
            entry.slot = slots.length - 1;
            entry.offset = 0;
        };
        entries.filter(e => e.components === 4).forEach(place);
        entries.filter(e => e.components !== 4).forEach(place);

        if (slots.length > MAX_INTER_STAGE_SLOTS)
            throw new GLSLError("the program needs " + slots.length +
                " varying slots but only " + MAX_INTER_STAGE_SLOTS +
                " are available (deviation D-12)", 0);

        return { entries, slotCount: slots.length };
    }

    /* How many gl_TexCoord elements the pair actually needs. A dynamic index
     * on either side forces the full array, because nothing else can answer
     * gl_TexCoord[i] for a runtime i. */
    function varyingArrayExtent(vsUsage, fsUsage, name) {
        if (!vsUsage.varyings.has(name) || !fsUsage.varyings.has(name)) return 0;
        if (vsUsage.texCoordDynamic || fsUsage.texCoordDynamic)
            return MAX_TEXTURE_COORDS;
        const max = Math.max(vsUsage.texCoordMax, fsUsage.texCoordMax);
        return max < 0 ? 0 : max + 1;
    }

    function varyingKey(entry) {
        if (entry.index !== undefined) return entry.name + "[" + entry.index + "]";
        if (entry.column !== undefined) return entry.name + "$" + entry.column;
        return entry.name;
    }

    const SWIZZLE_CHARS = "xyzw";
    function slotSwizzle(offset, components) {
        return SWIZZLE_CHARS.slice(offset, offset + components);
    }

    /* ================================================================== */
    /* Code generation                                                    */
    /* ================================================================== */

    const WGSL_RESERVED = new Set([
        "alias", "break", "case", "const", "const_assert", "continue",
        "continuing", "default", "diagnostic", "discard", "else", "enable",
        "false", "fn", "for", "if", "let", "loop", "override", "requires",
        "return", "struct", "switch", "true", "var", "while",
        "array", "atomic", "bool", "f16", "f32", "i32", "mat2x2", "mat2x3",
        "mat2x4", "mat3x2", "mat3x3", "mat3x4", "mat4x2", "mat4x3", "mat4x4",
        "ptr", "sampler", "sampler_comparison", "texture_1d", "texture_2d",
        "texture_2d_array", "texture_3d", "texture_cube", "texture_cube_array",
        "texture_depth_2d", "u32", "vec2", "vec3", "vec4",
        "glState", "glUniforms",
    ]);

    function safeName(name) {
        return WGSL_RESERVED.has(name) ? name + "_" : name;
    }

    function floatLiteral(value) {
        if (!isFinite(value))
            return value > 0 ? "3.4028235e38" : (value < 0 ? "-3.4028235e38" : "0.0");
        if (Number.isInteger(value) && Math.abs(value) < 1e15)
            return value.toFixed(1);
        let text = String(value);
        if (!/[.eE]/.test(text)) text += ".0";
        return text;
    }

    class Generator {
        constructor(stage, ast, usage, iface, options) {
            this.stage = stage;
            this.ast = ast;
            this.usage = usage;
            this.iface = iface;
            this.options = options || {};
            this.lines = [];
            this.indent = 0;
            this.tempSerial = 0;
            this.stats = { nonUniformSamples: 0, uniformSamples: 0,
                           gradSamples: 0, levelSamples: 0 };
            this.controlFlowUniform = [true];
            // Every varying entry, keyed the way the AST reaches it.
            this.varyingBySlot = new Map();
            for (const entry of iface.varyings.entries)
                this.varyingBySlot.set(varyingKey(entry), entry);
        }

        get inUniformControlFlow() {
            return this.controlFlowUniform[this.controlFlowUniform.length - 1];
        }

        emit(text) {
            this.lines.push("    ".repeat(this.indent) + text);
        }
        emitAll(list) { for (const l of list) this.emit(l); }
        temp() { return "_t" + (this.tempSerial++); }

        /* ---- module scope ---- */

        generate() {
            this.emit("// generated by gl_shader_translator.js r" +
                TRANSLATOR_REVISION + " (" + this.stage + ")");
            // GL leaves derivatives in non-uniform control flow undefined and
            // drivers compute them anyway; WGSL refuses the shader (Tint
            // checks it, naga does not), as VX's and GX's shaders say too
            this.emit("diagnostic(off, derivative_uniformity);");
            this.emit("");
            this.emitBindings();
            this.emitUserStructs();
            this.emitIOStructs();
            this.emitPrivates();
            this.emitFunctions();
            this.emitEntryPoint();
            return this.lines.join("\n") + "\n";
        }

        emitBindings() {
            const layout = this.iface.stateLayout;
            if (layout.structText) {
                this.emitAll(layout.structText.split("\n"));
                this.emit("@group(1) @binding(0) var<uniform> glState : GLState;");
                this.emit("");
            }
            this.emitAll(this.iface.uniformLayout.structText().split("\n"));
            this.emit("@group(1) @binding(1) var<uniform> glUniforms : GLUniforms;");
            this.emit("");
            for (const s of this.iface.samplers) {
                const count = s.arraySize || 1;
                for (let i = 0; i < count; ++i) {
                    const suffix = s.arraySize ? "_" + i : "";
                    this.emit("@group(2) @binding(" + (s.binding + i * 2) + ") var t_" +
                        s.wgslName + suffix + " : " + wgslTextureType(s.type) + ";");
                    this.emit("@group(2) @binding(" + (s.binding + i * 2 + 1) + ") var s_" +
                        s.wgslName + suffix + " : " +
                        (s.type.shadow ? "sampler_comparison" : "sampler") + ";");
                }
            }
            if (this.iface.samplers.length) this.emit("");
            if (this.stage === "fragment" && this.options.logicOp &&
                    this.options.logicOp !== 0x1503) {
                for (let i = 0; i < this.iface.colorTargets; ++i)
                    this.emit("@group(3) @binding(" + i +
                        ") var glLogicTarget" + i + " : texture_2d<f32>;");
                this.emit("fn glApplyLogic(src : vec4<f32>, dst : vec4<f32>) " +
                    "-> vec4<f32> {");
                ++this.indent;
                this.emit("let s = vec4<u32>(round(clamp(src, vec4<f32>(0.0), " +
                    "vec4<f32>(1.0)) * 255.0));");
                this.emit("let d = vec4<u32>(round(clamp(dst, vec4<f32>(0.0), " +
                    "vec4<f32>(1.0)) * 255.0));");
                this.emit("let r = (" + logicOpExpression(this.options.logicOp) +
                    ") & vec4<u32>(255u);");
                this.emit("return vec4<f32>(r) / 255.0;");
                --this.indent;
                this.emit("}");
                this.emit("");
            }
            for (const accessor of this.iface.uniformLayout.accessors) {
                this.emitAll(accessor.split("\n"));
            }
            if (this.iface.uniformLayout.accessors.length) this.emit("");
        }

        emitUserStructs() {
            const seen = new Set();
            // Anything the uniform block already declared is emitted there,
            // with its alignment attributes; emitting it again would be a
            // duplicate definition of the same name.
            for (const name of this.iface.uniformLayout.structNames.keys())
                seen.add(name);
            const emitStruct = type => {
                if (seen.has(type.name)) return;
                seen.add(type.name);
                for (const f of type.fields)
                    if (f.type.kind === "struct") emitStruct(f.type);
                    else if (f.type.kind === "array" && f.type.elem.kind === "struct")
                        emitStruct(f.type.elem);
                this.emit("struct " + safeName(type.name) + " {");
                ++this.indent;
                for (const f of type.fields)
                    this.emit(safeName(f.name) + " : " + typeToWGSL(f.type) + ",");
                --this.indent;
                this.emit("}");
                this.emit("");
            };
            for (const decl of this.ast.decls) {
                if (decl.kind === "StructDecl") emitStruct(decl.struct.type);
                else if (decl.kind === "VarDecl" && decl.struct)
                    emitStruct(decl.struct.type);
            }
            // Structs introduced only as local declarations or return types.
            const walkType = t => {
                if (!t) return;
                if (t.kind === "struct") emitStruct(t);
                else if (t.kind === "array") walkType(t.elem);
            };
            for (const decl of this.ast.decls) {
                if (decl.kind === "FunctionDef" || decl.kind === "FunctionProto") {
                    walkType(decl.returnType);
                    for (const p of decl.params) walkType(p.type);
                }
            }
        }

        emitIOStructs() {
            const varyings = this.iface.varyings;
            const slotDecls = [];
            const slotCount = new Map();
            for (const entry of varyings.entries) {
                const prev = slotCount.get(entry.slot) || 0;
                slotCount.set(entry.slot, Math.max(prev, entry.offset + entry.components));
            }
            for (const [slot, used] of [...slotCount.entries()].sort((a, b) => a[0] - b[0])) {
                const flat = varyings.entries.some(e => e.slot === slot && e.flat);
                slotDecls.push({ slot, used, flat });
            }
            this.slotDecls = slotDecls;

            if (this.stage === "vertex") {
                this.emit("struct VSIn {");
                ++this.indent;
                for (const [name, loc] of this.iface.attributes) {
                    const info = this.usage.attributes.get(name);
                    if (!info) continue;
                    if (info.type.kind === "matrix") {
                        for (let c = 0; c < info.type.cols; ++c)
                            this.emit("@location(" + (loc + c) + ") " +
                                attribFieldName(name) + "_" + c + " : " +
                                typeToWGSL(vec("float", info.type.rows)) + ",");
                    } else {
                        this.emit("@location(" + loc + ") " + attribFieldName(name) +
                            " : " + typeToWGSL(info.type) + ",");
                    }
                }
                if (this.options.pointSprite)
                    this.emit("@location(" + this.options.pointCornerLocation +
                        ") glCorner : vec2<f32>,");
                if (!this.iface.attributes.size && !this.options.pointSprite)
                    this.emit("@builtin(vertex_index) glVertexIndex : u32,");
                --this.indent;
                this.emit("}");
                this.emit("");
                this.emit("struct VSOut {");
                ++this.indent;
                // GL engines share the position calculation between depth-only
                // and shaded programs. Preserve it across backend optimization
                // so LEQUAL/EQUAL multipass rendering does not develop holes.
                this.emit("@invariant @builtin(position) position : vec4<f32>,");
                for (const d of slotDecls)
                    this.emit((d.flat ? "@interpolate(flat) " : "") +
                        "@location(" + d.slot + ") v" + d.slot + " : vec4<f32>,");
                if (this.iface.clipPlaneCount)
                    this.emit("@location(" + this.iface.clipVaryingSlot +
                        ") glClipDist : vec4<f32>,");
                if (this.options.pointSprite)
                    this.emit("@location(" + this.iface.pointCoordSlot +
                        ") glPointCoord : vec2<f32>,");
                --this.indent;
                this.emit("}");
                this.emit("");
            } else {
                this.emit("struct FSIn {");
                ++this.indent;
                this.emit("@builtin(position) position : vec4<f32>,");
                if (this.usage.builtinInputs.has("gl_FrontFacing") ||
                        this.iface.twoSided)
                    this.emit("@builtin(front_facing) frontFacing : bool,");
                for (const d of slotDecls)
                    this.emit((d.flat ? "@interpolate(flat) " : "") +
                        "@location(" + d.slot + ") v" + d.slot + " : vec4<f32>,");
                if (this.iface.clipPlaneCount)
                    this.emit("@location(" + this.iface.clipVaryingSlot +
                        ") glClipDist : vec4<f32>,");
                if (this.usage.usesPointCoord)
                    this.emit("@location(" + this.iface.pointCoordSlot +
                        ") glPointCoord : vec2<f32>,");
                --this.indent;
                this.emit("}");
                this.emit("");
                this.emit("struct FSOut {");
                ++this.indent;
                const targets = this.iface.colorTargets;
                for (let i = 0; i < targets; ++i)
                    this.emit("@location(" + i + ") color" + i + " : vec4<f32>,");
                if (this.usage.writesFragDepth)
                    this.emit("@builtin(frag_depth) depth : f32,");
                --this.indent;
                this.emit("}");
                this.emit("");
            }
        }

        emitPrivates() {
            const declared = new Set();
            const declare = (name, type, init) => {
                if (declared.has(name)) return;
                declared.add(name);
                this.emit("var<private> " + name + " : " + typeToWGSL(type) +
                    (init ? " = " + init : "") + ";");
            };

            if (this.stage === "vertex") {
                for (const name of this.usage.attributes.keys()) {
                    const info = this.usage.attributes.get(name);
                    declare(safeName(name), info.type);
                }
                declare("gl_Position", F.vec4);
                for (const name of this.usage.builtinOutputs)
                    declare(name, VERTEX_BUILTIN_OUTPUTS[name].type);
                for (const [name, info] of this.usage.varyings)
                    declare(safeName(name), info.type);
            } else {
                for (const name of this.usage.builtinInputs)
                    declare(name, FRAGMENT_BUILTIN_INPUTS[name].type);
                for (const name of this.usage.builtinOutputs)
                    declare(name, FRAGMENT_BUILTIN_OUTPUTS[name].type);
                for (const [name, info] of this.usage.varyings)
                    declare(safeName(name), info.type);
            }

            // User globals that are neither uniform nor interface variables.
            for (const decl of this.ast.decls) {
                if (decl.kind !== "VarDecl") continue;
                const storage = decl.qualifiers.storage;
                if (storage === "uniform" || storage === "attribute" ||
                        storage === "varying") continue;
                for (const d of decl.declarators) {
                    if (storage === "const" && d.init &&
                            isConstantFoldable(d.init)) {
                        const pre = [];
                        this.emit("const " + safeName(d.name) + " : " +
                            typeToWGSL(d.type) + " = " +
                            this.genExpr(d.init, pre, d.type) + ";");
                        declared.add(safeName(d.name));
                        continue;
                    }
                    // A global initializer that is not a constant expression
                    // has to run somewhere; GLSL says at declaration time, so
                    // the entry point runs it before main().
                    declare(safeName(d.name), d.type);
                    if (d.init) {
                        this.deferredGlobalInits = this.deferredGlobalInits || [];
                        this.deferredGlobalInits.push(d);
                    }
                }
            }
            this.emit("");
        }

        emitFunctions() {
            for (const decl of this.ast.decls) {
                if (decl.kind !== "FunctionDef") continue;
                this.genFunction(decl);
            }
        }

        genFunction(decl) {
            const overload = decl.overload;
            const params = [];
            for (const p of decl.params) {
                if (!p.name) continue;
                if (p.type.kind === "sampler") {
                    params.push("t_" + safeName(p.name) + " : " +
                        wgslTextureType(p.type));
                    params.push("s_" + safeName(p.name) + " : " +
                        (p.type.shadow ? "sampler_comparison" : "sampler"));
                    continue;
                }
                if (p.direction === "in") {
                    params.push(safeName(p.name) + " : " + typeToWGSL(p.type));
                } else {
                    params.push(safeName(p.name) + " : ptr<function, " +
                        typeToWGSL(p.type) + ">");
                }
            }
            const ret = overload.returnType.kind === "void" ? "" :
                " -> " + typeToWGSL(overload.returnType);
            this.emit("fn " + overload.mangled + "(" + params.join(", ") + ")" +
                ret + " {");
            ++this.indent;
            this.currentMangled = overload.mangled;
            // An `in` parameter is writable in GLSL but is a `let` in WGSL, so
            // any parameter that is assigned needs a local copy. Copying all of
            // them would be wasteful for the common read-only case, so only the
            // assigned ones get one -- which the analyzer already knows.
            for (const p of decl.params) {
                if (!p.name || p.direction !== "in" || p.type.kind === "sampler")
                    continue;
                if (!parameterIsAssigned(decl, p.name)) continue;
                this.emit("var " + safeName(p.name) + "_mut : " +
                    typeToWGSL(p.type) + " = " + safeName(p.name) + ";");
                this.mutableParams = this.mutableParams || new Set();
                this.mutableParams.add(overload.mangled + ":" + p.name);
            }
            this.genBlockBody(decl.body);
            this.currentMangled = null;
            if (overload.returnType.kind !== "void")
                this.emit("return " + zeroValueWGSL(overload.returnType) + ";");
            --this.indent;
            this.emit("}");
            this.emit("");
        }

        genBlockBody(block) {
            for (const stmt of block.stmts) this.genStatement(stmt);
        }

        /* ---- statements ---- */

        genStatement(node) {
            switch (node.kind) {
            case "Block":
                this.emit("{");
                ++this.indent;
                this.genBlockBody(node);
                --this.indent;
                this.emit("}");
                return;
            case "VarDecl": return this.genLocalDecl(node);
            case "StructDecl": return;
            case "ExprStmt": {
                const pre = [];
                const text = this.genExpr(node.expr, pre, null, true);
                this.emitAll(pre);
                if (text) this.emit(text + ";");
                return;
            }
            case "If": return this.genIf(node);
            case "While": return this.genWhile(node);
            case "DoWhile": return this.genDoWhile(node);
            case "For": return this.genFor(node);
            case "Return": {
                const pre = [];
                if (node.expr) {
                    const text = this.genExpr(node.expr, pre,
                        node.expr.convertTo || null);
                    this.emitAll(pre);
                    this.emit("return " + text + ";");
                } else {
                    this.emit("return;");
                }
                return;
            }
            case "Break": this.emit("break;"); return;
            case "Continue": this.emit("continue;"); return;
            case "Discard": this.emit("discard;"); return;
            default:
                throw new GLSLError("cannot generate " + node.kind, node.line);
            }
        }

        genLocalDecl(node) {
            for (const d of node.declarators) {
                const pre = [];
                let init = null;
                if (d.init) init = this.genExpr(d.init, pre, d.type);
                this.emitAll(pre);
                this.emit("var " + safeName(d.name) + " : " + typeToWGSL(d.type) +
                    " = " + (init !== null ? init : zeroValueWGSL(d.type)) + ";");
            }
        }

        genIf(node) {
            const pre = [];
            const cond = this.genExpr(node.cond, pre);
            this.emitAll(pre);
            this.emit("if (" + cond + ") {");
            ++this.indent;
            this.controlFlowUniform.push(this.inUniformControlFlow &&
                !node.cond.nonUniform);
            this.genStatementInline(node.then);
            this.controlFlowUniform.pop();
            --this.indent;
            if (node.otherwise) {
                this.emit("} else {");
                ++this.indent;
                this.controlFlowUniform.push(this.inUniformControlFlow &&
                    !node.cond.nonUniform);
                this.genStatementInline(node.otherwise);
                this.controlFlowUniform.pop();
                --this.indent;
            }
            this.emit("}");
        }

        /* An if/else arm that is a Block should not add a second pair of
         * braces; anything else is emitted as-is. */
        genStatementInline(node) {
            if (node.kind === "Block") this.genBlockBody(node);
            else this.genStatement(node);
        }

        genWhile(node) {
            const pre = [];
            const cond = this.genExpr(node.cond, pre);
            this.controlFlowUniform.push(this.inUniformControlFlow &&
                !node.cond.nonUniform);
            if (!pre.length) {
                this.emit("while (" + cond + ") {");
                ++this.indent;
                this.genStatementInline(node.body);
                --this.indent;
                this.emit("}");
            } else {
                // A condition with side effects has to be re-evaluated at the
                // top of every iteration, which only the loop form allows.
                this.emit("loop {");
                ++this.indent;
                this.emitAll(pre);
                this.emit("if (!(" + cond + ")) { break; }");
                this.genStatementInline(node.body);
                --this.indent;
                this.emit("}");
            }
            this.controlFlowUniform.pop();
        }

        genDoWhile(node) {
            this.controlFlowUniform.push(false);
            this.emit("loop {");
            ++this.indent;
            this.genStatementInline(node.body);
            const pre = [];
            const cond = this.genExpr(node.cond, pre);
            // The test belongs in `continuing` so that `continue` inside the
            // body reaches it, which is what a GLSL do-while does.
            this.emit("continuing {");
            ++this.indent;
            this.emitAll(pre);
            this.emit("break if !(" + cond + ");");
            --this.indent;
            this.emit("}");
            --this.indent;
            this.emit("}");
            this.controlFlowUniform.pop();
        }

        genFor(node) {
            this.emit("{");
            ++this.indent;
            if (node.init) this.genStatement(node.init);
            const condPre = [];
            const cond = node.cond ? this.genExpr(node.cond, condPre) : null;
            const stepPre = [];
            const step = node.step ?
                this.genExpr(node.step, stepPre, null, true) : null;
            this.controlFlowUniform.push(this.inUniformControlFlow &&
                !(node.cond && node.cond.nonUniform));
            this.emit("loop {");
            ++this.indent;
            if (cond !== null) {
                this.emitAll(condPre);
                this.emit("if (!(" + cond + ")) { break; }");
            }
            this.genStatementInline(node.body);
            if (step !== null) {
                this.emit("continuing {");
                ++this.indent;
                this.emitAll(stepPre);
                this.emit(step + ";");
                --this.indent;
                this.emit("}");
            }
            --this.indent;
            this.emit("}");
            this.controlFlowUniform.pop();
            --this.indent;
            this.emit("}");
        }

        /* ---- expressions ---- */

        /*
         * `pre` collects statements that must run before the returned
         * expression is evaluated. That mechanism carries every construct GLSL
         * has and WGSL does not: assignment as a value, ++/--, out parameters,
         * and swizzle assignment (WGSL allows `v.x = e` but not `v.xy = e`).
         */
        genExpr(node, pre, targetType, asStatement) {
            let text = this.genExprInner(node, pre, asStatement);
            const conv = targetType && !sameType(node.type, targetType) ?
                targetType : node.convertTo;
            if (conv && !sameType(node.type, conv))
                text = typeToWGSL(conv) + "(" + text + ")";
            return text;
        }

        genExprInner(node, pre, asStatement) {
            switch (node.kind) {
            case "IntLit": return String(node.value);
            case "FloatLit": return floatLiteral(node.value);
            case "BoolLit": return node.value ? "true" : "false";
            case "Ident": return this.genIdent(node);
            case "Field": return this.genField(node, pre);
            case "Index": return this.genIndex(node, pre);
            case "Binary": return this.genBinary(node, pre);
            case "Unary": return this.genUnary(node, pre, asStatement);
            case "Assign": return this.genAssign(node, pre, asStatement);
            case "Conditional": return this.genConditional(node, pre);
            case "Call": return this.genCall(node, pre);
            case "Sequence": {
                const text = this.genExpr(node.left, pre, null, true);
                if (text) pre.push("    ".repeat(0) + text + ";");
                return this.genExpr(node.right, pre, null, asStatement);
            }
            default:
                throw new GLSLError("cannot generate " + node.kind, node.line);
            }
        }

        genIdent(node) {
            const symbol = node.symbol;
            switch (symbol.kind) {
            case "builtinConst": return String(symbol.value);
            case "stateUniform": {
                if (symbol.info.expr) return symbol.info.expr;
                throw new GLSLError("'" + symbol.name +
                    "' must be used with a member or an index", node.line);
            }
            case "uniform": {
                const base = "glUniforms.u_" + symbol.name;
                if (symbol.type.kind === "scalar" || symbol.type.kind === "vector")
                    return uniformStorageFor(symbol.type).read(base);
                return base;
            }
            case "param": {
                if (symbol.direction !== "in")
                    return "(*" + safeName(symbol.name) + ")";
                if (this.mutableParams &&
                        this.mutableParams.has(this.currentMangled + ":" + symbol.name))
                    return safeName(symbol.name) + "_mut";
                return safeName(symbol.name);
            }
            default:
                return safeName(symbol.name);
            }
        }

        genField(node, pre) {
            // gl_Fog.density and friends: GL packs several scalars into one
            // vec4, so the member map answers rather than a '.' append.
            if (node.object.kind === "Ident" && node.object.symbol &&
                    node.object.symbol.kind === "stateUniform") {
                const members = node.object.symbol.info.members;
                if (members && members[node.name]) return members[node.name];
            }
            const objText = this.genExpr(node.object, pre);
            if (node.swizzle !== undefined) {
                const chars = node.swizzle.map(i => SWIZZLE_CHARS[i]).join("");
                if (node.object.type.kind === "scalar") {
                    // `f.x` on a scalar is legal GLSL; in WGSL the scalar has
                    // no components, so the value stands for itself.
                    return node.swizzle.length === 1 ? objText :
                        typeToWGSL(node.type) + "(" + objText + ")";
                }
                return "(" + objText + ")." + chars;
            }
            const expr = "(" + objText + ")." + safeName(node.name);
            if (this.rootsAtUniform(node.object) &&
                    (node.type.kind === "scalar" || node.type.kind === "vector"))
                return uniformStorageFor(node.type).read(expr);
            return expr;
        }

        genIndex(node, pre) {
            const symbol = node.object.kind === "Ident" ? node.object.symbol : null;

            // gl_EyePlaneT[u] lives at texGenPlanes[u * 8 + 5]: one flat array
            // holds all four object planes then all four eye planes per unit.
            if (symbol && symbol.kind === "stateUniform" &&
                    symbol.info.planeStride !== undefined) {
                const idx = this.genExpr(node.index, pre);
                return "glState.texGenPlanes[(" + idx + ") * " +
                    symbol.info.planeStride + " + " + symbol.info.planeOffset + "]";
            }

            // A sampler array element resolves to its own binding, so the index
            // must be constant; the analyzer already refused a dynamic one.
            if (node.type.kind === "sampler")
                return "";              // handled by samplerPair()

            const objText = this.genExpr(node.object, pre);
            const idx = this.genExpr(node.index, pre);

            if (symbol && symbol.kind === "uniform" &&
                    symbol.type.kind === "array" &&
                    (symbol.type.elem.kind === "scalar" ||
                     symbol.type.elem.kind === "vector")) {
                // Widened to vec4 for the 16-byte uniform array stride; the
                // generated accessor puts the swizzle in one place.
                const leaf = this.iface.uniformLayout.leaves.get(symbol.name);
                if (leaf && leaf.readIndexed) return leaf.readIndexed(idx);
            }

            const expr = objText + "[" + idx + "]";
            if (this.rootsAtUniform(node.object) &&
                    node.object.type.kind === "array" &&
                    (node.type.kind === "scalar" || node.type.kind === "vector"))
                return uniformStorageFor(node.type).read(expr);
            return expr;
        }

        rootsAtUniform(node) {
            let n = node;
            while (n && (n.kind === "Field" || n.kind === "Index")) n = n.object;
            return !!(n && n.kind === "Ident" && n.symbol &&
                n.symbol.kind === "uniform");
        }

        genBinary(node, pre) {
            // Short-circuit operators must not evaluate the right side when
            // the left decides the result, so a right side that needs
            // statements becomes an if.
            if (node.op === "&&" || node.op === "||") {
                const rightPre = [];
                const left = this.genExpr(node.left, pre);
                const right = this.genExpr(node.right, rightPre);
                if (!rightPre.length)
                    return "(" + left + " " + node.op + " " + right + ")";
                const tmp = this.temp();
                pre.push("var " + tmp + " : bool = " + left + ";");
                pre.push("if (" + (node.op === "&&" ? tmp : "!" + tmp) + ") {");
                for (const l of rightPre) pre.push("    " + l);
                pre.push("    " + tmp + " = " + right + ";");
                pre.push("}");
                return tmp;
            }
            const left = this.genExpr(node.left, pre, node.left.convertTo);
            const right = this.genExpr(node.right, pre, node.right.convertTo);
            if (node.op === "^^")
                return "((" + left + ") != (" + right + "))";
            return this.binaryText(node.op, left, node.left.convertTo || node.left.type,
                right, node.right.convertTo || node.right.type, pre);
        }

        /*
         * A binary operator where GLSL and WGSL differ:
         *  - == and != of a vector, matrix, struct or array give one bool in
         *    GLSL; WGSL compares vectors componentwise and the rest not at all
         *  - &, | and ^ take a scalar beside a vector in GLSL, not in WGSL
         *  - a shift's amount is unsigned in WGSL (a vector's, a vector)
         */
        binaryText(op, left, lt, right, rt, pre) {
            if ((op === "==" || op === "!=") && lt.kind !== "scalar") {
                let a = left, b = right;
                if (lt.kind !== "vector") {
                    // the operands are read more than once
                    a = this.temp();
                    b = this.temp();
                    pre.push("let " + a + " = " + left + ";");
                    pre.push("let " + b + " = " + right + ";");
                }
                const equal = equalityWGSL(a, b, lt);
                return op === "==" ? equal : "(!" + equal + ")";
            }
            if (op === "<<" || op === ">>") {
                const amount = lt.kind !== "vector" ? "u32(" + right + ")" :
                    "vec" + lt.size + "<u32>(" + (rt.kind === "vector" ? right : "u32(" + right + ")") + ")";
                return "(" + left + " " + op + " " + amount + ")";
            }
            if ((op === "&" || op === "|" || op === "^") && lt.kind !== rt.kind) {
                if (lt.kind === "scalar") left = typeToWGSL(rt) + "(" + left + ")";
                else right = typeToWGSL(lt) + "(" + right + ")";
            }
            // WGSL has a matrix beside a scalar for * only, and matrices
            // divide by nothing: the rest is done column by column
            const matrix = lt.kind === "matrix" ? lt : rt.kind === "matrix" ? rt : null;
            if (matrix && (op === "+" || op === "-" || op === "/") &&
                    (lt.kind === "scalar" || rt.kind === "scalar" || op === "/")) {
                const a = this.temp(), b = this.temp();
                pre.push("let " + a + " = " + left + ";");
                pre.push("let " + b + " = " + right + ";");
                const columns = [];
                for (let c = 0; c < matrix.cols; ++c) {
                    columns.push("(" + (lt.kind === "matrix" ? a + "[" + c + "]" : a) + " " + op + " " +
                        (rt.kind === "matrix" ? b + "[" + c + "]" : b) + ")");
                }
                return typeToWGSL(matrix) + "(" + columns.join(", ") + ")";
            }
            return "(" + left + " " + op + " " + right + ")";
        }

        genUnary(node, pre, asStatement) {
            if (node.op === "++" || node.op === "--") {
                const target = this.lvalue(node.operand, pre);
                const one = baseOf(node.type) === "int" ? "1" : "1.0";
                const delta = node.op === "++" ? " + " : " - ";
                const isVector = node.type.kind !== "scalar";
                const rhs = node.type.kind === "matrix" ?
                    this.binaryText(delta.trim(), target.read, node.type, one, T.float, pre) :
                    isVector ?
                    target.read + delta + typeToWGSL(node.type) + "(" + one + ")" :
                    target.read + delta + one;
                if (node.prefix) {
                    this.assignTo(target, rhs, pre);
                    return asStatement ? "" : target.read;
                }
                const tmp = this.temp();
                pre.push("let " + tmp + " = " + target.read + ";");
                this.assignTo(target, rhs, pre);
                return asStatement ? "" : tmp;
            }
            const operand = this.genExpr(node.operand, pre);
            if (node.op === "+") return "(" + operand + ")";
            // (WGSL negates no matrix)
            if (node.op === "-" && node.type.kind === "matrix") return "(" + operand + " * -1.0)";
            return "(" + node.op + "(" + operand + "))";
        }

        /*
         * Resolves an assignment target into something that can be written.
         * `components` is set for a multi-component swizzle, which WGSL cannot
         * assign to in one statement.
         */
        lvalue(node, pre) {
            if (node.kind === "Field" && node.swizzle &&
                    node.swizzle.length > 1) {
                const base = this.lvalue(node.object, pre);
                return {
                    base, components: node.swizzle,
                    read: "(" + base.read + ")." +
                        node.swizzle.map(i => SWIZZLE_CHARS[i]).join(""),
                    type: node.type,
                };
            }
            if (node.kind === "Field" && node.swizzle) {
                const base = this.lvalue(node.object, pre);
                return { write: base.write + "." + SWIZZLE_CHARS[node.swizzle[0]],
                         read: base.read + "." + SWIZZLE_CHARS[node.swizzle[0]],
                         type: node.type };
            }
            if (node.kind === "Field") {
                const base = this.lvalue(node.object, pre);
                return { write: base.write + "." + safeName(node.name),
                         read: base.read + "." + safeName(node.name),
                         type: node.type };
            }
            if (node.kind === "Index") {
                const base = this.lvalue(node.object, pre);
                const idx = this.genExpr(node.index, pre);
                return { write: base.write + "[" + idx + "]",
                         read: base.read + "[" + idx + "]",
                         type: node.type };
            }
            if (node.kind === "Ident") {
                const text = this.genIdent(node);
                return { write: text, read: text, type: node.type };
            }
            throw new GLSLError("expression is not assignable", node.line);
        }

        assignTo(target, valueText, pre) {
            if (target.components) {
                const tmp = this.temp();
                pre.push("let " + tmp + " : " + typeToWGSL(target.type) +
                    " = " + valueText + ";");
                target.components.forEach((component, i) => {
                    const source = target.components.length === 1 ? tmp :
                        tmp + "." + SWIZZLE_CHARS[i];
                    pre.push(target.base.write + "." + SWIZZLE_CHARS[component] +
                        " = " + source + ";");
                });
                return;
            }
            pre.push(target.write + " = " + valueText + ";");
        }

        genAssign(node, pre, asStatement) {
            const target = this.lvalue(node.target, pre);
            let valueText;
            if (node.op === "=") {
                valueText = this.genExpr(node.value, pre,
                    node.value.convertTo || node.target.type);
            } else {
                const op = node.op.slice(0, -1);
                const rhs = this.genExpr(node.value, pre, node.value.convertTo);
                valueText = this.binaryText(op, target.read, node.target.type, rhs,
                    node.value.convertTo || node.value.type, pre);
            }
            if (!target.components && asStatement)
                return target.write + " = " + valueText;
            this.assignTo(target, valueText, pre);
            return asStatement ? "" : target.read;
        }

        genConditional(node, pre) {
            const thenPre = [];
            const elsePre = [];
            const cond = this.genExpr(node.cond, pre);
            const thenText = this.genExpr(node.then, thenPre, node.then.convertTo);
            const elseText = this.genExpr(node.otherwise, elsePre,
                node.otherwise.convertTo);
            if (!thenPre.length && !elsePre.length)
                return "select(" + elseText + ", " + thenText + ", " + cond + ")";
            // Only one arm may run, so anything with side effects becomes a
            // real branch rather than select()'s unconditional evaluation.
            const tmp = this.temp();
            pre.push("var " + tmp + " : " + typeToWGSL(node.type) + ";");
            pre.push("if (" + cond + ") {");
            for (const l of thenPre) pre.push("    " + l);
            pre.push("    " + tmp + " = " + thenText + ";");
            pre.push("} else {");
            for (const l of elsePre) pre.push("    " + l);
            pre.push("    " + tmp + " = " + elseText + ";");
            pre.push("}");
            return tmp;
        }

        genCall(node, pre) {
            if (node.constructType) return this.genConstructor(node, pre);
            if (node.builtinCall) {
                const args = node.args.map((a, i) =>
                    a.type.kind === "sampler" ? "" :
                    this.genExpr(a, pre, a.convertTo));
                return node.resolved.emit(args, node, this.emitContext(node, pre));
            }
            const overload = node.resolved;
            const argTexts = [];
            const writebacks = [];
            overload.paramInfo.forEach((p, i) => {
                const arg = node.args[i];
                if (p.type.kind === "sampler") {
                    const pair = this.samplerPair(arg);
                    argTexts.push(pair.texture, pair.sampler);
                    return;
                }
                if (p.direction === "in") {
                    argTexts.push(this.genExpr(arg, pre, arg.convertTo || p.type));
                    return;
                }
                // out/inout become pointers to a function-scope temporary; a
                // pointer to a private or to a struct member is not something
                // core WGSL allows, so the copy is not optional.
                const tmp = this.temp();
                const target = this.lvalue(arg, pre);
                if (p.direction === "inout")
                    pre.push("var " + tmp + " : " + typeToWGSL(p.type) +
                        " = " + target.read + ";");
                else
                    pre.push("var " + tmp + " : " + typeToWGSL(p.type) + ";");
                argTexts.push("&" + tmp);
                writebacks.push({ target, tmp });
            });
            const call = overload.mangled + "(" + argTexts.join(", ") + ")";
            if (!writebacks.length) return call;
            if (overload.returnType.kind === "void") {
                pre.push(call + ";");
                for (const w of writebacks) this.assignTo(w.target, w.tmp, pre);
                return "";
            }
            const result = this.temp();
            pre.push("let " + result + " = " + call + ";");
            for (const w of writebacks) this.assignTo(w.target, w.tmp, pre);
            return result;
        }

        genConstructor(node, pre) {
            const target = node.constructType;
            const args = node.args.map(a => ({
                text: this.genExpr(a, pre), type: a.type,
            }));
            /* vec4(v.rgb * n, a) reads three components out of one expression.
             * Emitting that expression once per component is correct but
             * quadratic in nesting depth, and it makes a shader dump unreadable
             * exactly when someone is reading it to find a bug. */
            for (const a of args) {
                if (componentCount(a.type) <= 1) continue;
                if (/^[A-Za-z_][A-Za-z0-9_.]*$/.test(a.text)) continue;
                const tmp = this.temp();
                pre.push("let " + tmp + " = " + a.text + ";");
                a.text = tmp;
            }

            if (target.kind === "struct")
                return safeName(target.name) + "(" +
                    node.args.map((a, i) =>
                        this.genExpr(a, pre, target.fields[i].type)).join(", ") + ")";

            if (target.kind === "scalar")
                return typeToWGSL(target) + "(" + scalarize(args[0]) + ")";

            if (target.kind === "vector") {
                if (args.length === 1 && args[0].type.kind === "scalar")
                    return typeToWGSL(target) + "(" +
                        convertScalar(args[0], target.base) + ")";
                const components = [];
                for (const a of args) {
                    if (components.length >= target.size) break;
                    for (const c of componentsOf(a, target.base)) {
                        if (components.length >= target.size) break;
                        components.push(c);
                    }
                }
                return typeToWGSL(target) + "(" + components.join(", ") + ")";
            }

            if (target.kind === "matrix") {
                if (args.length === 1 && args[0].type.kind === "scalar") {
                    const cols = [];
                    for (let c = 0; c < target.cols; ++c) {
                        const parts = [];
                        for (let r = 0; r < target.rows; ++r)
                            parts.push(c === r ? convertScalar(args[0], "float") : "0.0");
                        cols.push("vec" + target.rows + "<f32>(" + parts.join(", ") + ")");
                    }
                    return typeToWGSL(target) + "(" + cols.join(", ") + ")";
                }
                if (args.length === 1 && args[0].type.kind === "matrix") {
                    // Resizing keeps the overlapping submatrix and fills the
                    // rest from the identity, which is what GLSL specifies.
                    const from = args[0].type;
                    const tmp = this.temp();
                    pre.push("let " + tmp + " = " + args[0].text + ";");
                    const cols = [];
                    for (let c = 0; c < target.cols; ++c) {
                        const parts = [];
                        for (let r = 0; r < target.rows; ++r) {
                            if (c < from.cols && r < from.rows)
                                parts.push(tmp + "[" + c + "][" + r + "]");
                            else parts.push(c === r ? "1.0" : "0.0");
                        }
                        cols.push("vec" + target.rows + "<f32>(" + parts.join(", ") + ")");
                    }
                    return typeToWGSL(target) + "(" + cols.join(", ") + ")";
                }
                if (node.matrixFromColumns)
                    return typeToWGSL(target) + "(" +
                        args.map(a => a.text).join(", ") + ")";
                const flat = [];
                for (const a of args)
                    for (const c of componentsOf(a, "float")) flat.push(c);
                const cols = [];
                for (let c = 0; c < target.cols; ++c) {
                    const parts = [];
                    for (let r = 0; r < target.rows; ++r)
                        parts.push(flat[c * target.rows + r] || "0.0");
                    cols.push("vec" + target.rows + "<f32>(" + parts.join(", ") + ")");
                }
                return typeToWGSL(target) + "(" + cols.join(", ") + ")";
            }
            throw new GLSLError("cannot construct " + target.name, node.line);
        }

        /* ---- texture sampling context handed to the built-in emitters ---- */

        emitContext(node, pre) {
            const self = this;
            return {
                samplerPair: argNode => self.samplerPair(argNode),
                sample: (pair, coord, bias) => self.emitSample(pair, coord, bias, node),
                compareSample: (pair, coord, ref) =>
                    self.emitCompareSample(pair, coord, ref, node),
                ftransform: () => "(glState.mvp * gl_Vertex)",
                pre,
            };
        }

        samplerPair(argNode) {
            if (argNode.kind === "Index") {
                const base = argNode.object;
                if (base.kind !== "Ident")
                    throw new GLSLError("unsupported sampler expression",
                        argNode.line);
                const index = argNode.constIndex;
                if (index === null || index === undefined)
                    throw new GLSLError("a sampler array needs a constant index",
                        argNode.line);
                const name = safeName(base.symbol.name);
                return { texture: "t_" + name + "_" + index,
                         sampler: "s_" + name + "_" + index };
            }
            if (argNode.kind !== "Ident")
                throw new GLSLError("unsupported sampler expression", argNode.line);
            const name = safeName(argNode.symbol.name);
            return { texture: "t_" + name, sampler: "s_" + name };
        }

        /*
         * Which WGSL sampling function to use is not a style choice.
         *
         *  - the vertex stage has no implicit derivatives at all, so every
         *    lookup there is an explicit-level one
         *  - in non-uniform control flow textureSample's derivatives are
         *    undefined, as in GL: with derivative_uniformity off (generate())
         *    the lookup is the same as in uniform flow ("implicit", the
         *    default); "grad" passes the coordinate's own derivatives (plan
         *    section 4.10, strategy 2), "level0" samples level 0
         *
         * Both cases are counted, because an approximation nobody measures is
         * an approximation nobody can trust.
         */
        emitSample(pair, coord, bias, node) {
            if (this.stage === "vertex") {
                ++this.stats.levelSamples;
                return "textureSampleLevel(" + pair.texture + ", " + pair.sampler +
                    ", " + coord + ", 0.0)";
            }
            const uniform = this.inUniformControlFlow;
            if (uniform) ++this.stats.uniformSamples;
            else ++this.stats.nonUniformSamples;
            const strategy = this.options.nonUniformSampleStrategy || "implicit";
            if (uniform || strategy === "implicit") {
                return bias ?
                    "textureSampleBias(" + pair.texture + ", " + pair.sampler +
                        ", " + coord + ", " + bias + ")" :
                    "textureSample(" + pair.texture + ", " + pair.sampler +
                        ", " + coord + ")";
            }
            if (strategy === "level0") {
                ++this.stats.levelSamples;
                return "textureSampleLevel(" + pair.texture + ", " + pair.sampler +
                    ", " + coord + ", 0.0)";
            }
            ++this.stats.gradSamples;
            const c = "(" + coord + ")";
            return "textureSampleGrad(" + pair.texture + ", " + pair.sampler +
                ", " + c + ", dpdx" + c + ", dpdy" + c + ")";
        }

        emitCompareSample(pair, coord, ref, node) {
            const uniform = this.stage === "fragment" && this.inUniformControlFlow;
            void node;
            if (uniform) ++this.stats.uniformSamples;
            else ++this.stats.nonUniformSamples;
            // (implicit derivatives exist in the fragment stage only; see emitSample)
            if (this.stage === "fragment" &&
                    (uniform || (this.options.nonUniformSampleStrategy || "implicit") !== "level0")) {
                return "textureSampleCompare(" + pair.texture + ", " +
                    pair.sampler + ", " + coord + ", " + ref + ")";
            }
            return "textureSampleCompareLevel(" + pair.texture + ", " +
                pair.sampler + ", " + coord + ", " + ref + ")";
        }

        /* ---- entry points ---- */

        emitEntryPoint() {
            if (this.stage === "vertex") this.emitVertexEntry();
            else this.emitFragmentEntry();
        }

        emitGlobalInits() {
            for (const d of this.deferredGlobalInits || []) {
                const pre = [];
                const text = this.genExpr(d.init, pre, d.type);
                this.emitAll(pre);
                this.emit(safeName(d.name) + " = " + text + ";");
            }
        }

        emitVertexEntry() {
            this.emit("@vertex");
            this.emit("fn vs_main(vsin : VSIn) -> VSOut {");
            ++this.indent;
            for (const [name, loc] of this.iface.attributes) {
                const info = this.usage.attributes.get(name);
                if (!info) continue;
                void loc;
                if (info.type.kind === "matrix") {
                    const cols = [];
                    for (let c = 0; c < info.type.cols; ++c)
                        cols.push("vsin." + attribFieldName(name) + "_" + c);
                    this.emit(safeName(name) + " = " + typeToWGSL(info.type) +
                        "(" + cols.join(", ") + ");");
                } else {
                    this.emit(safeName(name) + " = vsin." +
                        attribFieldName(name) + ";");
                }
            }
            this.emitGlobalInits();
            this.emit("glsl_main();");
            this.emit("var out : VSOut;");
            this.emit("var clip = gl_Position;");

            if (this.options.pointSprite) {
                // Points are drawn as two triangles (plan 10.3), so the corner
                // offset is applied in clip space -- before the Y flip, so the
                // sign convention is still GL's.
                const size = this.usage.builtinOutputs.has("gl_PointSize") ?
                    "gl_PointSize" : "glState.pointParams.x";
                this.emit("let glPtSize = clamp(" + size +
                    ", glState.pointParams.y, glState.pointParams.z);");
                this.emit("clip.x = clip.x + vsin.glCorner.x * glPtSize * " +
                    "clip.w / glState.viewportParams.z;");
                this.emit("clip.y = clip.y + vsin.glCorner.y * glPtSize * " +
                    "clip.w / glState.viewportParams.w;");
                // GL_POINT_SPRITE_COORD_ORIGIN defaults to GL_UPPER_LEFT.
                this.emit("out.glPointCoord = vec2<f32>(" +
                    "vsin.glCorner.x * 0.5 + 0.5, " +
                    (this.options.pointCoordLowerLeft ?
                        "vsin.glCorner.y * 0.5 + 0.5);" :
                        "0.5 - vsin.glCorner.y * 0.5);"));
            }

            // GL clip space is z in [-w, w]; WebGPU wants [0, w]. The Y flip
            // makes framebuffer row 0 GL's bottom row, which is what lets
            // viewport, scissor, readback and render-to-texture all skip a
            // conversion (plan 4.3).
            this.emit("clip.z = (clip.z + clip.w) * 0.5;");
            this.emit("clip.y = -clip.y;");
            this.emit("out.position = clip;");

            for (const entry of this.iface.varyings.entries) {
                const source = this.vertexVaryingSource(entry);
                if (!source) continue;
                for (let i = 0; i < entry.components; ++i) {
                    const dst = "out.v" + entry.slot + "." +
                        SWIZZLE_CHARS[entry.offset + i];
                    const src = entry.components === 1 && !source.vector ?
                        source.expr :
                        source.expr + "." + SWIZZLE_CHARS[i];
                    this.emit(dst + " = " + src + ";");
                }
            }

            if (this.iface.clipPlaneCount) {
                const cv = this.usage.builtinOutputs.has("gl_ClipVertex") ?
                    "gl_ClipVertex" : null;
                const parts = [];
                for (let i = 0; i < 4; ++i) {
                    if (i < this.iface.clipPlaneCount && cv)
                        parts.push("dot(" + cv + ", glState.clipPlanes[" + i + "])");
                    else
                        parts.push("1.0");
                }
                this.emit("out.glClipDist = vec4<f32>(" + parts.join(", ") + ");");
            }

            this.emit("return out;");
            --this.indent;
            this.emit("}");
        }

        /* Where a varying's value comes from inside the vertex shader. */
        vertexVaryingSource(entry) {
            if (entry.compat) {
                if (entry.name === "gl_TexCoord")
                    return { expr: "gl_TexCoord[" + entry.index + "]", vector: true };
                const source = entry.vsFront || entry.vsBack;
                if (!source) return null;
                if (!this.usage.varyings.has(source)) return null;
                return { expr: safeName(source),
                         vector: componentCount(entry.type) > 1 };
            }
            if (!this.usage.varyings.has(entry.name)) return null;
            if (entry.index !== undefined)
                return { expr: safeName(entry.name) + "[" + entry.index + "]",
                         vector: entry.components > 1 };
            if (entry.column !== undefined)
                return { expr: safeName(entry.name) + "[" + entry.column + "]",
                         vector: entry.components > 1 };
            return { expr: safeName(entry.name), vector: entry.components > 1 };
        }

        emitFragmentEntry() {
            this.emit("@fragment");
            this.emit("fn fs_main(fsin : FSIn) -> FSOut {");
            ++this.indent;

            if (this.iface.clipPlaneCount) {
                // The vertex stage writes 1.0 into the unused lanes, so one
                // test covers however many planes are on. Deviation D-05: this
                // discards fragments rather than clipping geometry.
                this.emit("if (any(fsin.glClipDist < vec4<f32>(0.0))) { discard; }");
            }
            if (this.options.polygonStipple) {
                this.emit("let stippleX = u32(floor(fsin.position.x)) & 31u;");
                this.emit("let stippleY = u32(floor(fsin.position.y)) & 31u;");
                this.emit("let stippleByteIndex = stippleY * 4u + (stippleX >> 3u);");
                this.emit("let stippleWord = glState.polygonStipple[stippleByteIndex >> 2u];");
                this.emit("let stippleLane = stippleByteIndex & 3u;");
                this.emit("var stippleByte = stippleWord.x;");
                this.emit("if (stippleLane == 1u) { stippleByte = stippleWord.y; }");
                this.emit("if (stippleLane == 2u) { stippleByte = stippleWord.z; }");
                this.emit("if (stippleLane == 3u) { stippleByte = stippleWord.w; }");
                this.emit("let stippleBit = 0x80u >> (stippleX & 7u);");
                this.emit("if ((u32(stippleByte) & stippleBit) == 0u) { discard; }");
            }

            if (this.usage.builtinInputs.has("gl_FragCoord"))
                this.emit("gl_FragCoord = fsin.position;");
            if (this.usage.builtinInputs.has("gl_FrontFacing"))
                this.emit("gl_FrontFacing = fsin.frontFacing;");
            if (this.usage.usesPointCoord)
                this.emit("gl_PointCoord = " + (this.options.pointSprite ?
                    "fsin.glPointCoord" : "vec2<f32>(0.5, 0.5)") + ";");

            for (const entry of this.iface.varyings.entries) {
                if (entry.isBackHalf) continue;
                const target = this.fragmentVaryingTarget(entry);
                if (!target) continue;
                const read = this.slotRead(entry);
                if (entry.compat && entry.vsBack && this.iface.twoSided) {
                    const back = this.iface.varyings.entries.find(e =>
                        e.isBackHalf && e.name === entry.name + "__back");
                    if (back) {
                        this.emit(target + " = select(" + this.slotRead(back) +
                            ", " + read + ", fsin.frontFacing);");
                        continue;
                    }
                }
                this.emit(target + " = " + read + ";");
            }

            this.emitGlobalInits();
            this.emit("glsl_main();");

            if (this.options.alphaTest && this.options.alphaTest !== "always") {
                const colour = this.usage.usesFragColor ? "gl_FragColor" :
                    (this.usage.usesFragData ? "gl_FragData[0]" : null);
                if (this.options.alphaTest === "never") {
                    this.emit("discard;");
                } else if (colour) {
                    const op = ALPHA_TEST_OPERATORS[this.options.alphaTest];
                    this.emit("if (!(" + colour + ".a " + op +
                        " glState.alphaRef.x)) { discard; }");
                }
            }

            this.emit("var out : FSOut;");
            const targets = this.iface.colorTargets;
            for (let i = 0; i < targets; ++i) {
                let source;
                if (this.usage.usesFragData)
                    source = "gl_FragData[" + i + "]";
                else if (this.usage.usesFragColor)
                    source = "gl_FragColor";
                else
                    source = "vec4<f32>(0.0)";
                if (this.options.logicOp && this.options.logicOp !== 0x1503)
                    source = "glApplyLogic(" + source +
                        ", textureLoad(glLogicTarget" + i +
                        ", vec2<i32>(floor(fsin.position.xy)), 0))";
                this.emit("out.color" + i + " = " + source + ";");
            }
            if (this.usage.writesFragDepth)
                this.emit("out.depth = gl_FragDepth;");
            this.emit("return out;");
            --this.indent;
            this.emit("}");
        }

        fragmentVaryingTarget(entry) {
            if (entry.compat) {
                if (entry.name === "gl_TexCoord")
                    return "gl_TexCoord[" + entry.index + "]";
                if (!this.usage.varyings.has(entry.name)) return null;
                return safeName(entry.name);
            }
            if (!this.usage.varyings.has(entry.name)) return null;
            if (entry.index !== undefined)
                return safeName(entry.name) + "[" + entry.index + "]";
            if (entry.column !== undefined)
                return safeName(entry.name) + "[" + entry.column + "]";
            return safeName(entry.name);
        }

        slotRead(entry) {
            if (entry.offset === 0 && entry.components === 4)
                return "fsin.v" + entry.slot;
            return "fsin.v" + entry.slot + "." +
                slotSwizzle(entry.offset, entry.components);
        }
    }

    const ALPHA_TEST_OPERATORS = {
        less: "<", equal: "==", lequal: "<=",
        greater: ">", notequal: "!=", gequal: ">=",
    };

    function logicOpExpression(op) {
        switch (op >>> 0) {
        case 0x1500: return "vec4<u32>(0u)";
        case 0x1501: return "s & d";
        case 0x1502: return "s & ~d";
        case 0x1503: return "s";
        case 0x1504: return "~s & d";
        case 0x1505: return "d";
        case 0x1506: return "s ^ d";
        case 0x1507: return "s | d";
        case 0x1508: return "~(s | d)";
        case 0x1509: return "~(s ^ d)";
        case 0x150A: return "~d";
        case 0x150B: return "s | ~d";
        case 0x150C: return "~s";
        case 0x150D: return "~s | d";
        case 0x150E: return "~(s & d)";
        case 0x150F: return "vec4<u32>(255u)";
        default: return "s";
        }
    }

    /* ---- small code-generation helpers ---- */

    function wgslTextureType(type) {
        if (type.shadow) return "texture_depth_2d";
        switch (type.dim) {
        case "3D": return "texture_3d<f32>";
        case "Cube": return "texture_cube<f32>";
        default: return "texture_2d<f32>";   // 1D and 2DRect ride on 2D
        }
    }

    function attribFieldName(name) {
        return safeName(name);
    }

    function scalarize(arg) {
        if (arg.type.kind === "vector") return "(" + arg.text + ").x";
        return arg.text;
    }

    function convertScalar(arg, base) {
        const from = baseOf(arg.type);
        const text = scalarize(arg);
        if (from === base) return text;
        const ctor = base === "float" ? "f32" : (base === "int" ? "i32" : "bool");
        return ctor + "(" + text + ")";
    }

    /* Every component of a constructor argument, in GLSL's order, converted to
     * the constructed type's base. Matrices contribute column by column. */
    function componentsOf(arg, base) {
        const from = baseOf(arg.type);
        const ctor = base === "float" ? "f32" : (base === "int" ? "i32" : "bool");
        const wrap = text => from === base ? text : ctor + "(" + text + ")";
        if (arg.type.kind === "scalar") return [wrap(arg.text)];
        if (arg.type.kind === "vector") {
            const out = [];
            for (let i = 0; i < arg.type.size; ++i)
                out.push(wrap("(" + arg.text + ")." + SWIZZLE_CHARS[i]));
            return out;
        }
        if (arg.type.kind === "matrix") {
            const out = [];
            for (let c = 0; c < arg.type.cols; ++c)
                for (let r = 0; r < arg.type.rows; ++r)
                    out.push(wrap("(" + arg.text + ")[" + c + "][" + r + "]"));
            return out;
        }
        return [wrap(arg.text)];
    }

    function isConstantFoldable(expr) {
        switch (expr.kind) {
        case "IntLit": case "FloatLit": case "BoolLit": return true;
        case "Unary": return expr.op !== "++" && expr.op !== "--" &&
            isConstantFoldable(expr.operand);
        case "Binary":
            return isConstantFoldable(expr.left) && isConstantFoldable(expr.right);
        case "Call":
            return !!expr.constructType && expr.args.every(isConstantFoldable);
        case "Ident":
            return !!(expr.symbol && (expr.symbol.kind === "builtinConst" ||
                expr.symbol.kind === "const"));
        default: return false;
        }
    }

    /* WGSL function parameters are immutable; GLSL's are not. Only the ones a
     * function actually writes need a local copy. */
    function parameterIsAssigned(decl, name) {
        let found = false;
        const visitExpr = node => {
            if (!node || found || typeof node !== "object") return;
            if (node.kind === "Assign" || (node.kind === "Unary" &&
                    (node.op === "++" || node.op === "--"))) {
                let root = node.target || node.operand;
                while (root && (root.kind === "Field" || root.kind === "Index"))
                    root = root.object;
                if (root && root.kind === "Ident" && root.name === name)
                    found = true;
            }
            for (const key of Object.keys(node)) {
                if (key === "symbol" || key === "type" || key === "convertTo" ||
                        key === "resolved" || key === "constructType" ||
                        key === "structField") continue;
                const value = node[key];
                if (Array.isArray(value)) value.forEach(visitExpr);
                else if (value && typeof value === "object") visitExpr(value);
            }
        };
        visitExpr(decl.body);
        return found;
    }

    function hashString(text) {
        let h = 0x811c9dc5;
        for (let i = 0; i < text.length; ++i) {
            h ^= text.charCodeAt(i);
            h = Math.imul(h, 0x01000193) >>> 0;
        }
        return h >>> 0;
    }

    /* ================================================================== */
    /* Public API                                                         */
    /* ================================================================== */

    /*
     * glCompileShader: preprocess, parse and check one stage.
     *
     * Compilation success is decided here and nowhere else. WGSL is not
     * consulted: if this function produces an AST then the shader is valid
     * GLSL, and a later WGSL error is a bug in this translator rather than in
     * the application's shader (plan section 4.8). That distinction is what
     * keeps a mistake of ours from surfacing to the guest as its own
     * GL_INVALID_OPERATION.
     */
    function compileShader(source, stage, options) {
        const opts = options || {};
        const result = {
            ok: false, stage, log: "", warnings: [],
            sourceHash: hashString(stage + " " + source),
        };
        try {
            const pp = new Preprocessor(stage, opts);
            const pre = pp.run(source);
            result.version = pre.version;
            result.extensions = pre.extensions;
            result.warnings = pre.warnings.slice();
            const tokens = lex(pre.text);
            const ast = new Parser(tokens, stage).parseProgram();
            const analyzer = new Analyzer(stage, ast, opts);
            const usage = analyzer.run();
            result.ast = ast;
            result.usage = usage;
            result.functions = analyzer.functions;
            result.ok = true;
            result.log = result.warnings.map(w => "WARNING: " + w).join("\n");
        } catch (error) {
            if (!(error instanceof GLSLError)) throw error;
            result.log = "ERROR: 0:" + (error.glslLine || 0) + ": " + error.message;
        }
        return result;
    }

    const POINT_CORNER_LOCATION = 7;

    /*
     * glLinkProgram: decide the interface both stages share, then generate.
     *
     * `variant` carries the pipeline state that GL still applies around a
     * programmable pipeline -- alpha test, user clip planes, point sprites,
     * two-sided colour selection, flat shading. Each one changes the generated
     * WGSL, so a program links once per distinct variant and the executor keys
     * its shader cache on the pair.
     */
    function linkProgram(vs, fs, options) {
        const opts = options || {};
        const variant = opts.variant || {};
        const log = [];
        try {
            if (!vs || !vs.ok) throw new GLSLError("the vertex shader is not compiled", 0);
            if (!fs || !fs.ok) throw new GLSLError("the fragment shader is not compiled", 0);
            if (vs.stage !== "vertex" || fs.stage !== "fragment")
                throw new GLSLError("a program needs one vertex and one fragment shader", 0);

            /* ---- uniforms: one namespace across both stages ---- */
            const uniformLayout = new UniformBlockLayout();
            const seenUniforms = new Map();
            const uniformOrder = [];
            for (const stage of [vs, fs]) {
                for (const entry of stage.usage.uniforms) {
                    const existing = seenUniforms.get(entry.name);
                    if (existing) {
                        if (!sameType(existing.type, entry.type))
                            throw new GLSLError("uniform '" + entry.name +
                                "' is declared with different types in the two " +
                                "shaders (" + existing.type.name + " and " +
                                entry.type.name + ")", 0);
                        continue;
                    }
                    seenUniforms.set(entry.name, entry);
                    uniformOrder.push(entry);
                }
            }
            for (const entry of uniformOrder) uniformLayout.add(entry.name, entry.type);

            /* ---- samplers: shared bindings, two per element ---- */
            const samplers = [];
            const samplerByName = new Map();
            let bindingCursor = 0;
            for (const stage of [vs, fs]) {
                for (const s of stage.usage.samplers) {
                    const existing = samplerByName.get(s.name);
                    if (existing) {
                        if (!sameType(existing.type, s.type))
                            throw new GLSLError("sampler '" + s.name +
                                "' is declared with different types in the two " +
                                "shaders", 0);
                        continue;
                    }
                    const entry = {
                        name: s.name,
                        wgslName: safeName(s.name.replace(/[.\[\]]/g, "_")),
                        type: s.type, arraySize: s.arraySize,
                        binding: bindingCursor,
                    };
                    bindingCursor += 2 * Math.max(1, s.arraySize);
                    samplers.push(entry);
                    samplerByName.set(s.name, entry);
                }
            }

            /* ---- GL state fields: the union, plus what the variant needs ---- */
            const stateFields = new Set([...vs.usage.stateFields,
                ...fs.usage.stateFields]);
            if (variant.alphaTest && variant.alphaTest !== "always" &&
                    variant.alphaTest !== "never")
                stateFields.add("alphaRef");
            if (variant.clipPlaneCount) stateFields.add("clipPlanes");
            if (variant.pointSprite) {
                stateFields.add("pointParams");
                stateFields.add("viewportParams");
            }
            if (variant.polygonStipple) stateFields.add("polygonStipple");
            const stateLayoutInfo = stateLayout.buildLayout([...stateFields]);

            /* ---- attributes ---- */
            const bindings = normalizeBindings(opts.bindAttribLocations);
            const attributes = assignAttributeLocations(vs.usage, bindings, !!opts.es);
            if (variant.pointSprite) {
                for (const [name, loc] of attributes) {
                    const info = vs.usage.attributes.get(name);
                    const slots = info ? attributeSlotCount(info.type) : 1;
                    if (POINT_CORNER_LOCATION >= loc &&
                            POINT_CORNER_LOCATION < loc + slots)
                        throw new GLSLError("attribute '" + name +
                            "' occupies location " + POINT_CORNER_LOCATION +
                            ", which the point-sprite corner attribute needs", 0);
                }
            }

            /* ---- varyings ---- */
            const varyings = assignVaryings(vs.usage, fs.usage, {
                twoSided: !!variant.twoSided,
                flatShading: !!variant.flatShading,
            });
            let nextSlot = varyings.slotCount;
            const clipPlaneCount = variant.clipPlaneCount || 0;
            const clipVaryingSlot = clipPlaneCount ? nextSlot++ : -1;
            const usesPointCoord = fs.usage.usesPointCoord || !!variant.pointSprite;
            const pointCoordSlot = usesPointCoord ? nextSlot++ : -1;
            if (nextSlot > MAX_INTER_STAGE_SLOTS)
                throw new GLSLError("the program needs " + nextSlot +
                    " varying slots but only " + MAX_INTER_STAGE_SLOTS +
                    " are available (deviation D-12)", 0);

            if (clipPlaneCount && !vs.usage.builtinOutputs.has("gl_ClipVertex"))
                log.push("WARNING: user clip planes are enabled but the vertex " +
                    "shader does not write gl_ClipVertex; no clipping is applied");
            if (clipPlaneCount > 4)
                log.push("WARNING: only the first 4 user clip planes are applied " +
                    "to a programmable pipeline");

            /* ---- colour targets ---- */
            if (fs.usage.usesFragColor && fs.usage.usesFragData)
                throw new GLSLError("a fragment shader may write gl_FragColor " +
                    "or gl_FragData, not both", 0);
            let colorTargets = 1;
            if (fs.usage.usesFragData) {
                colorTargets = fs.usage.fragDataDynamic ? MAX_DRAW_BUFFERS :
                    Math.max(1, fs.usage.fragDataMax + 1);
            }
            if (opts.maxColorTargets)
                colorTargets = Math.min(colorTargets, opts.maxColorTargets);

            const iface = {
                attributes, varyings, uniformLayout,
                stateLayout: stateLayoutInfo, samplers,
                clipPlaneCount, clipVaryingSlot, pointCoordSlot,
                colorTargets, twoSided: !!variant.twoSided,
            };
            const genOptions = {
                pointSprite: !!variant.pointSprite,
                pointCoordLowerLeft: !!variant.pointCoordLowerLeft,
                polygonStipple: !!variant.polygonStipple,
                logicOp: variant.logicOp ? (variant.logicOp >>> 0) : 0,
                pointCornerLocation: POINT_CORNER_LOCATION,
                alphaTest: variant.alphaTest || null,
                nonUniformSampleStrategy: opts.nonUniformSampleStrategy || "implicit",
            };

            const vsGen = new Generator("vertex", vs.ast, vs.usage, iface, genOptions);
            const wgslVertex = vsGen.generate();
            const fsGen = new Generator("fragment", fs.ast, fs.usage, iface, genOptions);
            const wgslFragment = fsGen.generate();

            const reflection = buildReflection(vs, fs, iface, {
                clipPlaneCount, colorTargets, usesPointCoord, variant,
            });

            return {
                ok: true,
                log: log.join("\n"),
                wgslVertex, wgslFragment, reflection,
                stats: {
                    vertex: vsGen.stats, fragment: fsGen.stats,
                    nonUniformSamples: vsGen.stats.nonUniformSamples +
                        fsGen.stats.nonUniformSamples,
                    noiseCalls: vs.usage.noiseCalls + fs.usage.noiseCalls,
                },
                cacheKey: linkCacheKey(vs, fs, opts),
            };
        } catch (error) {
            if (!(error instanceof GLSLError)) throw error;
            log.push("ERROR: " + error.message);
            return { ok: false, log: log.join("\n") };
        }
    }

    function normalizeBindings(bindings) {
        if (!bindings) return new Map();
        if (bindings instanceof Map) return bindings;
        return new Map(Object.entries(bindings));
    }

    function linkCacheKey(vs, fs, opts) {
        const variant = opts.variant || {};
        const bindings = normalizeBindings(opts.bindAttribLocations);
        const bindingText = [...bindings.entries()]
            .sort((a, b) => (a[0] < b[0] ? -1 : 1))
            .map(entry => entry[0] + "=" + entry[1]).join(",");
        return [
            "r" + TRANSLATOR_REVISION,
            vs.sourceHash.toString(16), fs.sourceHash.toString(16),
            bindingText,
            "a" + (variant.alphaTest || "-"),
            "c" + (variant.clipPlaneCount || 0),
            variant.pointSprite ? "p" : "-",
            variant.pointCoordLowerLeft ? "l" : "u",
            variant.polygonStipple ? "s" : "-",
            "o" + (variant.logicOp || 0).toString(16),
            variant.twoSided ? "2" : "-",
            variant.flatShading ? "f" : "-",
            opts.nonUniformSampleStrategy || "implicit",
        ].join("|");
    }

    /*
     * The reflection is the contract with gl_executor.js: it says where every
     * glUniform* write lands, which texture unit each sampler reads, and which
     * vertex attribute each location expects. Nothing else in the executor is
     * allowed to guess at the generated WGSL's layout.
     */
    function buildReflection(vs, fs, iface, extra) {
        const attributes = [];
        for (const [name, location] of iface.attributes) {
            const info = vs.usage.attributes.get(name);
            attributes.push({
                name, location, glslType: info.type.name,
                components: componentCount(info.type),
                slots: attributeSlotCount(info.type),
                baseType: baseOf(info.type),
                isCompat: !!info.isCompat,
            });
        }
        attributes.sort((a, b) => a.location - b.location);

        const uniforms = [];
        let locationCursor = 0;
        for (const entry of iface.uniformLayout.leaves) {
            const path = entry[0];
            const leaf = entry[1];
            const count = leaf.arraySize || 1;
            uniforms.push({
                name: path,
                location: locationCursor,
                glslType: leaf.type.name,
                baseType: baseOf(leaf.type),
                kind: leaf.type.kind,
                components: componentCount(leaf.type),
                arraySize: leaf.arraySize,
                offsetBytes: leaf.offsetBytes,
                arrayStrideBytes: leaf.arrayStrideBytes,
                matrixColumnStrideBytes: leaf.matrixColumnStrideBytes,
                columns: leaf.type.kind === "matrix" ? leaf.type.cols : 0,
                rows: leaf.type.kind === "matrix" ? leaf.type.rows : 0,
            });
            locationCursor += count;
        }

        const samplers = [];
        for (const s of iface.samplers) {
            samplers.push({
                name: s.name,
                location: locationCursor,
                binding: s.binding,
                dim: s.type.dim,
                shadow: s.type.shadow,
                external: !!s.type.external,
                arraySize: s.arraySize,
                bindingCount: 2 * Math.max(1, s.arraySize),
            });
            locationCursor += Math.max(1, s.arraySize);
        }

        return {
            attributes, uniforms, samplers,
            uniformBlockBytes: iface.uniformLayout.sizeBytes,
            stateFields: iface.stateLayout.fields.slice(),
            stateFloats: iface.stateLayout.floats,
            varyingSlots: iface.varyings.slotCount,
            clipPlaneCount: extra.clipPlaneCount,
            clipVaryingSlot: iface.clipVaryingSlot,
            pointCoordSlot: iface.pointCoordSlot,
            colorTargets: extra.colorTargets,
            usesDiscard: fs.usage.usesDiscard,
            usesPointCoord: extra.usesPointCoord,
            writesFragDepth: fs.usage.writesFragDepth,
            writesPointSize: vs.usage.writesPointSize,
            writesClipVertex: vs.usage.builtinOutputs.has("gl_ClipVertex"),
            usesFragData: fs.usage.usesFragData,
            bindGroupLayout: {
                state: { group: 1, binding: 0 },
                uniforms: { group: 1, binding: 1 },
                textures: { group: 2 },
            },
        };
    }

    const api = {
        TRANSLATOR_REVISION,
        compileShader, linkProgram,
        // Exported for the test suite and for gl_fixed_function.js, which
        // shares the state block and the attribute slot table.
        Preprocessor, lex, Parser, Analyzer, Generator,
        UniformBlockLayout, GLSLError,
        BASIC_TYPES, T, vec, mat, arrayOf, structType, typeToWGSL, sameType,
        COMPAT_ATTRIBUTE_LOCATIONS, COMPAT_ATTRIBUTE_TYPES,
        STATE_UNIFORMS, BUILTIN_CONSTANTS, ES_BUILTIN_CONSTANTS,
        MAX_INTER_STAGE_SLOTS, MAX_VERTEX_ATTRIBUTES, POINT_CORNER_LOCATION,
        assignAttributeLocations, assignVaryings, hashString, safeName,
    };
    global.GLShaderTranslator = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                   source/v64/src/browser/glbridge/gl-webgpu/gl_state_layout.js                                        0000644 0000000 0000000 00000051116 00000000000 021347  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The canonical OpenGL "state" uniform block.
//
// Three things need to agree byte for byte about where gl_ModelViewMatrix
// lives: the fixed-function WGSL generator, the GLSL compatibility built-ins
// in gl_shader_translator.js, and the executor code that fills the buffer.
// Historically that kind of agreement is maintained by three copies of a
// struct and a bug report; here there is one table and everyone derives from
// it.
//
// Fields are allocated per program, not globally: a shader that only touches
// gl_ModelViewProjectionMatrix gets a 16-float block, not the ~4 KB the full
// table would occupy. The unit of trimming is the *field*, and for the array
// state (lights, texture matrices, clip planes) the whole array -- because
// GLSL lets a loop index gl_LightSource[i] with a non-constant i, and an array
// that only sometimes exists cannot be indexed dynamically.
//
// Matrix layout: GL and WGSL are both column-major, so a mat4 is a straight
// 16-float copy. A WGSL mat3x3 in the uniform address space pads each column
// to 16 bytes, hence 12 floats for gl_NormalMatrix.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md sections 4.12 and 8.2.

(function(global) {
    "use strict";

    const MAX_LIGHTS = 8;
    const MAX_TEXTURE_UNITS = 8;
    const MAX_TEXTURE_COORDS = 8;
    const MAX_CLIP_PLANES = 6;

    /* ---------- helpers used by the field writers ---------- */

    function writeVec4(out, offset, v) {
        out[offset] = v[0]; out[offset + 1] = v[1];
        out[offset + 2] = v[2]; out[offset + 3] = v[3];
        return offset + 4;
    }

    function writeMat4(out, offset, m) {
        for (let i = 0; i < 16; ++i) out[offset + i] = m[i];
        return offset + 16;
    }

    /* A WGSL mat3x3<f32> is three vec4-aligned columns. The source is a
     * 9-float column-major GL 3x3. */
    function writeMat3(out, offset, m) {
        out[offset] = m[0]; out[offset + 1] = m[1]; out[offset + 2] = m[2];
        out[offset + 3] = 0;
        out[offset + 4] = m[3]; out[offset + 5] = m[4]; out[offset + 6] = m[5];
        out[offset + 7] = 0;
        out[offset + 8] = m[6]; out[offset + 9] = m[7]; out[offset + 10] = m[8];
        out[offset + 11] = 0;
        return offset + 12;
    }

    function writeMaterial(out, offset, m) {
        offset = writeVec4(out, offset, m.emission);
        offset = writeVec4(out, offset, m.ambient);
        offset = writeVec4(out, offset, m.diffuse);
        offset = writeVec4(out, offset, m.specular);
        out[offset] = m.shininess;
        out[offset + 1] = 0; out[offset + 2] = 0; out[offset + 3] = 0;
        return offset + 4;
    }

    /* gl_LightSourceParameters, laid out as 8 vec4 so that a WGSL struct with
     * the same field order needs no padding surprises. */
    function writeLight(out, offset, l) {
        offset = writeVec4(out, offset, l.ambient);
        offset = writeVec4(out, offset, l.diffuse);
        offset = writeVec4(out, offset, l.specular);
        offset = writeVec4(out, offset, l.position);
        offset = writeVec4(out, offset, l.halfVector);
        out[offset] = l.spotDirection[0];
        out[offset + 1] = l.spotDirection[1];
        out[offset + 2] = l.spotDirection[2];
        out[offset + 3] = l.spotExponent;
        offset += 4;
        out[offset] = l.spotCutoff;
        out[offset + 1] = l.spotCosCutoff;
        out[offset + 2] = l.constantAttenuation;
        out[offset + 3] = l.linearAttenuation;
        offset += 4;
        out[offset] = l.quadraticAttenuation;
        out[offset + 1] = 0; out[offset + 2] = 0; out[offset + 3] = 0;
        return offset + 4;
    }

    function writeLightProduct(out, offset, p) {
        offset = writeVec4(out, offset, p.ambient);
        offset = writeVec4(out, offset, p.diffuse);
        offset = writeVec4(out, offset, p.specular);
        return offset;
    }

    /* ---------- WGSL struct declarations shared by the fields ---------- */

    const STRUCT_DECLS = {
        GLMaterial:
            "struct GLMaterial {\n" +
            "    emission : vec4<f32>,\n" +
            "    ambient : vec4<f32>,\n" +
            "    diffuse : vec4<f32>,\n" +
            "    specular : vec4<f32>,\n" +
            "    shininess : f32,\n" +
            "    _pad0 : f32,\n" +
            "    _pad1 : f32,\n" +
            "    _pad2 : f32,\n" +
            "}",
        GLLight:
            "struct GLLight {\n" +
            "    ambient : vec4<f32>,\n" +
            "    diffuse : vec4<f32>,\n" +
            "    specular : vec4<f32>,\n" +
            "    position : vec4<f32>,\n" +
            "    halfVector : vec4<f32>,\n" +
            "    spotDirection : vec3<f32>,\n" +
            "    spotExponent : f32,\n" +
            "    spotCutoff : f32,\n" +
            "    spotCosCutoff : f32,\n" +
            "    constantAttenuation : f32,\n" +
            "    linearAttenuation : f32,\n" +
            "    quadraticAttenuation : f32,\n" +
            "    _pad0 : f32,\n" +
            "    _pad1 : f32,\n" +
            "    _pad2 : f32,\n" +
            "}",
        GLLightProduct:
            "struct GLLightProduct {\n" +
            "    ambient : vec4<f32>,\n" +
            "    diffuse : vec4<f32>,\n" +
            "    specular : vec4<f32>,\n" +
            "}",
    };

    /*
     * The field table.
     *
     * id       stable key used by signatures and by the shader cache
     * wgsl     field name inside the generated GLState struct
     * type     WGSL type text
     * floats   size in f32 units (already includes WGSL padding)
     * needs    struct declarations this field's type depends on
     * write    fills `out` starting at `offset`, returns the next offset
     */
    const FIELDS = [
        /* --- matrices --- */
        { id: "modelview", wgsl: "modelview", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.modelview) },
        { id: "projection", wgsl: "projection", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.projection) },
        { id: "mvp", wgsl: "mvp", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.mvp) },
        { id: "normalMatrix", wgsl: "normalMatrix", type: "mat3x3<f32>", floats: 12,
          write: (s, o, off) => writeMat3(o, off, s.matrices.normal) },
        { id: "modelviewInverse", wgsl: "modelviewInverse", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.modelviewInverse) },
        { id: "modelviewTranspose", wgsl: "modelviewTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.modelviewTranspose) },
        { id: "modelviewInverseTranspose", wgsl: "modelviewInverseTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.modelviewInverseTranspose) },
        { id: "projectionInverse", wgsl: "projectionInverse", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.projectionInverse) },
        { id: "projectionTranspose", wgsl: "projectionTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.projectionTranspose) },
        { id: "projectionInverseTranspose", wgsl: "projectionInverseTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.projectionInverseTranspose) },
        { id: "mvpInverse", wgsl: "mvpInverse", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.mvpInverse) },
        { id: "mvpTranspose", wgsl: "mvpTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.mvpTranspose) },
        { id: "mvpInverseTranspose", wgsl: "mvpInverseTranspose", type: "mat4x4<f32>", floats: 16,
          write: (s, o, off) => writeMat4(o, off, s.matrices.mvpInverseTranspose) },

        /* Texture matrices are one array, not eight fields: GLSL allows
         * gl_TextureMatrix[i] with a runtime i. */
        { id: "textureMatrix", wgsl: "textureMatrix",
          type: "array<mat4x4<f32>, " + MAX_TEXTURE_COORDS + ">",
          floats: 16 * MAX_TEXTURE_COORDS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_TEXTURE_COORDS; ++i)
                  off = writeMat4(o, off, s.matrices.texture[i]);
              return off;
          } },
        { id: "textureMatrixInverse", wgsl: "textureMatrixInverse",
          type: "array<mat4x4<f32>, " + MAX_TEXTURE_COORDS + ">",
          floats: 16 * MAX_TEXTURE_COORDS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_TEXTURE_COORDS; ++i)
                  off = writeMat4(o, off, s.matrices.textureInverse[i]);
              return off;
          } },
        { id: "textureMatrixTranspose", wgsl: "textureMatrixTranspose",
          type: "array<mat4x4<f32>, " + MAX_TEXTURE_COORDS + ">",
          floats: 16 * MAX_TEXTURE_COORDS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_TEXTURE_COORDS; ++i)
                  off = writeMat4(o, off, s.matrices.textureTranspose[i]);
              return off;
          } },
        { id: "textureMatrixInverseTranspose", wgsl: "textureMatrixInverseTranspose",
          type: "array<mat4x4<f32>, " + MAX_TEXTURE_COORDS + ">",
          floats: 16 * MAX_TEXTURE_COORDS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_TEXTURE_COORDS; ++i)
                  off = writeMat4(o, off, s.matrices.textureInverseTranspose[i]);
              return off;
          } },

        /* --- lighting --- */
        { id: "lights", wgsl: "lights",
          type: "array<GLLight, " + MAX_LIGHTS + ">", needs: ["GLLight"],
          floats: 32 * MAX_LIGHTS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_LIGHTS; ++i)
                  off = writeLight(o, off, s.lights[i]);
              return off;
          } },
        { id: "frontMaterial", wgsl: "frontMaterial", type: "GLMaterial",
          needs: ["GLMaterial"], floats: 20,
          write: (s, o, off) => writeMaterial(o, off, s.material.front) },
        { id: "backMaterial", wgsl: "backMaterial", type: "GLMaterial",
          needs: ["GLMaterial"], floats: 20,
          write: (s, o, off) => writeMaterial(o, off, s.material.back) },
        { id: "lightModelAmbient", wgsl: "lightModelAmbient", type: "vec4<f32>",
          floats: 4,
          write: (s, o, off) => writeVec4(o, off, s.lightModel.ambient) },
        { id: "frontSceneColor", wgsl: "frontSceneColor", type: "vec4<f32>",
          floats: 4,
          write: (s, o, off) => writeVec4(o, off, s.derived.frontSceneColor) },
        { id: "backSceneColor", wgsl: "backSceneColor", type: "vec4<f32>",
          floats: 4,
          write: (s, o, off) => writeVec4(o, off, s.derived.backSceneColor) },
        { id: "frontLightProduct", wgsl: "frontLightProduct",
          type: "array<GLLightProduct, " + MAX_LIGHTS + ">",
          needs: ["GLLightProduct"], floats: 12 * MAX_LIGHTS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_LIGHTS; ++i)
                  off = writeLightProduct(o, off, s.derived.frontLightProduct[i]);
              return off;
          } },
        { id: "backLightProduct", wgsl: "backLightProduct",
          type: "array<GLLightProduct, " + MAX_LIGHTS + ">",
          needs: ["GLLightProduct"], floats: 12 * MAX_LIGHTS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_LIGHTS; ++i)
                  off = writeLightProduct(o, off, s.derived.backLightProduct[i]);
              return off;
          } },

        /* --- fog --- */
        { id: "fogColor", wgsl: "fogColor", type: "vec4<f32>", floats: 4,
          write: (s, o, off) => writeVec4(o, off, s.fog.color) },
        { id: "fogParams", wgsl: "fogParams", type: "vec4<f32>", floats: 4,
          /* density, start, end, scale = 1/(end-start); GLSL exposes these as
           * gl_Fog.density/.start/.end/.scale. */
          write: (s, o, off) => {
              const span = s.fog.end - s.fog.start;
              return writeVec4(o, off, [s.fog.density, s.fog.start, s.fog.end,
                  span !== 0 ? 1 / span : 0]);
          } },

        /* --- texture environment / coordinate generation --- */
        { id: "texEnvColor", wgsl: "texEnvColor",
          type: "array<vec4<f32>, " + MAX_TEXTURE_UNITS + ">",
          floats: 4 * MAX_TEXTURE_UNITS,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_TEXTURE_UNITS; ++i)
                  off = writeVec4(o, off, s.texEnvColor[i]);
              return off;
          } },
        /* Object/eye linear planes: 4 coordinates (S,T,R,Q) x 8 units, each a
         * pair of vec4 (object plane, eye plane). Flat array so the fixed
         * function generator can index it with a constant. */
        { id: "texGenPlanes", wgsl: "texGenPlanes",
          type: "array<vec4<f32>, " + (MAX_TEXTURE_UNITS * 8) + ">",
          floats: 4 * MAX_TEXTURE_UNITS * 8,
          write: (s, o, off) => {
              for (let u = 0; u < MAX_TEXTURE_UNITS; ++u) {
                  const gen = s.texGen[u];
                  for (let c = 0; c < 4; ++c) off = writeVec4(o, off, gen[c].objectPlane);
                  for (let c = 0; c < 4; ++c) off = writeVec4(o, off, gen[c].eyePlane);
              }
              return off;
          } },

        /* --- clipping, depth, point size, alpha test --- */
        { id: "clipPlanes", wgsl: "clipPlanes",
          type: "array<vec4<f32>, " + MAX_CLIP_PLANES + ">",
          floats: 4 * MAX_CLIP_PLANES,
          write: (s, o, off) => {
              for (let i = 0; i < MAX_CLIP_PLANES; ++i)
                  off = writeVec4(o, off, s.clipPlanes[i]);
              return off;
          } },
        { id: "depthRange", wgsl: "depthRange", type: "vec4<f32>", floats: 4,
          /* near, far, diff, unused -- matches gl_DepthRangeParameters. */
          write: (s, o, off) => writeVec4(o, off, [s.depthRange.near,
              s.depthRange.far, s.depthRange.far - s.depthRange.near, 0]) },
        { id: "pointParams", wgsl: "pointParams", type: "vec4<f32>", floats: 4,
          /* size, sizeMin, sizeMax, fadeThresholdSize */
          write: (s, o, off) => writeVec4(o, off, [s.point.size, s.point.sizeMin,
              s.point.sizeMax, s.point.fadeThreshold]) },
        { id: "pointAttenuation", wgsl: "pointAttenuation", type: "vec4<f32>", floats: 4,
          write: (s, o, off) => writeVec4(o, off, [s.point.attenuation[0],
              s.point.attenuation[1], s.point.attenuation[2], 0]) },
        { id: "alphaRef", wgsl: "alphaRef", type: "vec4<f32>", floats: 4,
          /* ref, unused... a vec4 because a lone f32 in a uniform struct still
           * costs 16 bytes of alignment; naming the padding avoids surprises. */
          write: (s, o, off) => writeVec4(o, off, [s.alphaRef, 0, 0, 0]) },

        /* --- viewport, needed by point/line expansion and stipple --- */
        { id: "viewportParams", wgsl: "viewportParams", type: "vec4<f32>", floats: 4,
          /* x, y, width, height in framebuffer pixels */
          write: (s, o, off) => writeVec4(o, off, [s.viewport.x, s.viewport.y,
              s.viewport.width, s.viewport.height]) },
        { id: "rasterParams", wgsl: "rasterParams", type: "vec4<f32>", floats: 4,
          /* lineWidth, lineStipplePattern (as float bits), lineStippleFactor,
           * polygon-stipple enable */
          write: (s, o, off) => writeVec4(o, off, [s.lineWidth,
              s.lineStipple.pattern, s.lineStipple.factor,
              s.polygonStippleEnabled ? 1 : 0]) },
        { id: "polygonStipple", wgsl: "polygonStipple",
          type: "array<vec4<f32>, 32>", floats: 128,
          /* One byte per float keeps all 1024 pattern bits exact while staying
           * inside the existing f32-only uniform staging layout. */
          write: (s, o, off) => {
              for (let i = 0; i < 128; ++i) o[off++] = s.polygonStipple[i];
              return off;
          } },
    ];

    const FIELD_BY_ID = new Map();
    for (const field of FIELDS) FIELD_BY_ID.set(field.id, field);

    /* Fields whose GLSL name maps directly onto one table entry. The compat
     * built-ins the translator resolves through structured access (lights,
     * materials, fog members) are handled in the translator itself. */
    const GLSL_TO_FIELD = {
        gl_ModelViewMatrix: "modelview",
        gl_ProjectionMatrix: "projection",
        gl_ModelViewProjectionMatrix: "mvp",
        gl_NormalMatrix: "normalMatrix",
        gl_ModelViewMatrixInverse: "modelviewInverse",
        gl_ModelViewMatrixTranspose: "modelviewTranspose",
        gl_ModelViewMatrixInverseTranspose: "modelviewInverseTranspose",
        gl_ProjectionMatrixInverse: "projectionInverse",
        gl_ProjectionMatrixTranspose: "projectionTranspose",
        gl_ProjectionMatrixInverseTranspose: "projectionInverseTranspose",
        gl_ModelViewProjectionMatrixInverse: "mvpInverse",
        gl_ModelViewProjectionMatrixTranspose: "mvpTranspose",
        gl_ModelViewProjectionMatrixInverseTranspose: "mvpInverseTranspose",
        gl_TextureMatrix: "textureMatrix",
        gl_TextureMatrixInverse: "textureMatrixInverse",
        gl_TextureMatrixTranspose: "textureMatrixTranspose",
        gl_TextureMatrixInverseTranspose: "textureMatrixInverseTranspose",
        gl_LightSource: "lights",
        gl_FrontMaterial: "frontMaterial",
        gl_BackMaterial: "backMaterial",
        gl_LightModel: "lightModelAmbient",
        gl_FrontLightModelProduct: "frontSceneColor",
        gl_BackLightModelProduct: "backSceneColor",
        gl_FrontLightProduct: "frontLightProduct",
        gl_BackLightProduct: "backLightProduct",
        gl_Fog: "fogColor",             // .color; the scalars come from fogParams
        gl_TextureEnvColor: "texEnvColor",
        gl_ObjectPlaneS: "texGenPlanes",
        gl_EyePlaneS: "texGenPlanes",
        gl_ClipPlane: "clipPlanes",
        gl_DepthRange: "depthRange",
        gl_Point: "pointParams",
    };

    /*
     * Builds the WGSL declaration for a chosen subset.
     *
     * The subset is ordered by the table, not by the order the caller
     * discovered the fields, so the same set always produces the same struct
     * -- which is what lets the shader cache key on the field list.
     */
    function buildLayout(fieldIds) {
        const wanted = new Set(fieldIds);
        const chosen = FIELDS.filter(f => wanted.has(f.id));
        const missing = [...wanted].filter(id => !FIELD_BY_ID.has(id));
        if (missing.length)
            throw new Error("unknown GL state field(s): " + missing.join(", "));

        const structs = [];
        const seenStructs = new Set();
        for (const field of chosen) {
            for (const name of field.needs || []) {
                if (seenStructs.has(name)) continue;
                seenStructs.add(name);
                structs.push(STRUCT_DECLS[name]);
            }
        }

        const lines = [];
        let floats = 0;
        const offsets = new Map();
        lines.push("struct GLState {");
        for (const field of chosen) {
            offsets.set(field.id, floats);
            lines.push("    " + field.wgsl + " : " + field.type + ",");
            floats += field.floats;
        }
        /* An empty uniform struct is invalid WGSL, and a program that touches
         * no GL state still needs a binding slot so the pipeline layout does
         * not change shape per shader. */
        if (!chosen.length) lines.push("    _unused : vec4<f32>,");
        lines.push("}");

        return {
            fields: chosen.map(f => f.id),
            floats: chosen.length ? floats : 4,
            offsets,
            structDecls: structs,
            structText: (structs.length ? structs.join("\n\n") + "\n\n" : "") +
                lines.join("\n"),
        };
    }

    /* Fills `out` (a Float32Array view of the uniform staging buffer) with the
     * layout's fields, in table order, starting at `offset`. Returns the
     * number of floats written, which must equal layout.floats. */
    function writeLayout(layout, state, out, offset) {
        const start = offset;
        for (const id of layout.fields) {
            offset = FIELD_BY_ID.get(id).write(state, out, offset);
        }
        if (!layout.fields.length) {
            out[offset] = 0; out[offset + 1] = 0;
            out[offset + 2] = 0; out[offset + 3] = 0;
            offset += 4;
        }
        return offset - start;
    }

    const api = {
        FIELDS, FIELD_BY_ID, GLSL_TO_FIELD, STRUCT_DECLS,
        MAX_LIGHTS, MAX_TEXTURE_UNITS, MAX_TEXTURE_COORDS, MAX_CLIP_PLANES,
        buildLayout, writeLayout,
    };
    global.GLStateLayout = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/browser/glbridge/gl-webgpu/gl_wire.js                                                0000644 0000000 0000000 00000021106 00000000000 017574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Wire-format decoding for the OpenGL command stream.
//
// Generated from the payload layouts in openglproxy/opengl32_proxy.c by way of
// the decoder v86_network_bridge.js forwards to the WebGPU executor.
// 140 of the 217 opcodes are a flat argument list, so they are described
// declaratively here rather than hand-decoded 140 times; the rest carry
// variable-length data and get explicit decoders in gl_executor.js.
//
// A one-field mistake in this table decodes every later argument at the wrong
// offset, and the symptom is arbitrary, so gl_protocol_consistency_test.js
// checks the table against the guest header rather than trusting it.

(function(global) {
    "use strict";

    // Each entry: [glName, argument types in order].
    //   i = signed 32-bit, u = unsigned 32-bit, f = 32-bit float,
    //   d = 64-bit float (GL's double-precision entry points)
    const SIGNATURES = {
        ACCUM: ["Accum", "uf"],
        ACTIVE_TEXTURE: ["ActiveTexture", "u"],
        ALPHA_FUNC: ["AlphaFunc", "uf"],
        ATTACH_SHADER: ["AttachShaderMapped", "uu"],
        BEGIN: ["Begin", "u"],
        BEGIN_QUERY: ["BeginQueryMapped", "uu"],
        BIND_BUFFER: ["BindBufferMapped", "uu"],
        BIND_FRAMEBUFFER: ["BindFramebufferMapped", "uu"],
        BIND_PROGRAM_ARB: ["BindProgramARBMapped", "uu"],
        BIND_RENDERBUFFER: ["BindRenderbufferMapped", "uu"],
        BIND_TEXTURE: ["BindTexture", "uu"],
        BLEND_COLOR: ["BlendColor", "ffff"],
        BLEND_EQUATION: ["BlendEquation", "u"],
        BLEND_EQUATION_SEPARATE: ["BlendEquationSeparate", "uu"],
        BLEND_FUNC: ["BlendFunc", "uu"],
        BLEND_FUNC_SEPARATE: ["BlendFuncSeparate", "uuuu"],
        BLIT_FRAMEBUFFER: ["BlitFramebuffer", "iiiiiiiiuu"],
        CLEAR: ["Clear", "u"],
        CLEAR_ACCUM: ["ClearAccum", "ffff"],
        CLEAR_COLOR: ["ClearColor", "ffff"],
        CLEAR_DEPTH: ["ClearDepth", "d"],
        CLEAR_STENCIL: ["ClearStencil", "i"],
        CLIENT_ACTIVE_TEXTURE: ["ClientActiveTexture", "u"],
        CLIP_PLANE: ["ClipPlane4d", "udddd"],
        COLOR4F: ["Color4f", "ffff"],
        COLOR_MASK: ["ColorMask", "uuuu"],
        COLOR_MATERIAL: ["ColorMaterial", "uu"],
        COMPILE_SHADER: ["CompileShaderMapped", "u"],
        COPY_PIXELS: ["CopyPixels", "iiiiu"],
        COPY_TEX_IMAGE_1D: ["CopyTexImage1D", "uiuiiii"],
        COPY_TEX_IMAGE_2D: ["CopyTexImage2D", "uiuiiiii"],
        COPY_TEX_SUB_IMAGE_1D: ["CopyTexSubImage1D", "uiiiii"],
        COPY_TEX_SUB_IMAGE_2D: ["CopyTexSubImage2D", "uiiiiiii"],
        COPY_TEX_SUB_IMAGE_3D: ["CopyTexSubImage3D", "uiiiiiiii"],
        CREATE_PROGRAM: ["CreateProgramMapped", "u"],
        CREATE_SHADER: ["CreateShaderMapped", "uu"],
        CULL_FACE: ["CullFace", "u"],
        DELETE_PROGRAM: ["DeleteProgramMapped", "u"],
        DELETE_SHADER: ["DeleteShaderMapped", "u"],
        DEPTH_FUNC: ["DepthFunc", "u"],
        DEPTH_MASK: ["DepthMask", "u"],
        DEPTH_RANGE: ["DepthRange", "dd"],
        DETACH_SHADER: ["DetachShaderMapped", "uu"],
        DISABLE: ["Disable", "u"],
        DISABLE_CLIENT_STATE: ["DisableClientState", "u"],
        DISABLE_VERTEX_ATTRIB_ARRAY: ["DisableVertexAttribArrayMapped", "u"],
        DRAW_ARRAYS_DIRECT: ["DrawArraysDirect", "uii"],
        DRAW_BUFFER: ["DrawBuffer", "u"],
        ENABLE: ["Enable", "u"],
        ENABLE_CLIENT_STATE: ["EnableClientState", "u"],
        ENABLE_VERTEX_ATTRIB_ARRAY: ["EnableVertexAttribArrayMapped", "u"],
        END: ["End", ""],
        END_QUERY: ["EndQueryMapped", "u"],
        FINISH: ["Finish", ""],
        FLUSH: ["Flush", ""],
        FOGF: ["Fogf", "uf"],
        FOGFV: ["Fogfv4", "uuffff"],
        FOGI: ["Fogi", "ui"],
        FOG_COORDF: ["FogCoordf", "f"],
        FRAMEBUFFER_RENDERBUFFER: ["FramebufferRenderbufferMapped", "uuuu"],
        FRAMEBUFFER_TEXTURE: ["FramebufferTextureMapped", "uuuuii"],
        FRONT_FACE: ["FrontFace", "u"],
        FRUSTUM: ["Frustum", "dddddd"],
        GENERATE_MIPMAP: ["GenerateMipmap", "u"],
        HINT: ["Hint", "uu"],
        INVALIDATE_PROGRAM_LOCATIONS: ["InvalidateProgramLocations", "u"],
        LIGHTF: ["Lightf", "uuf"],
        LIGHTFV: ["Lightfv4", "uuuffff"],
        LIGHTI: ["Lighti", "uui"],
        LIGHTIV: ["Lightiv4", "uuuiiii"],
        LIGHT_MODELF: ["LightModelf", "uf"],
        LIGHT_MODELFV: ["LightModelfv4", "uuffff"],
        LIGHT_MODELI: ["LightModeli", "ui"],
        LIGHT_MODELIV: ["LightModeliv4", "uuiiii"],
        LINE_STIPPLE: ["LineStipple", "iu"],
        LINE_WIDTH: ["LineWidth", "f"],
        LINK_PROGRAM: ["LinkProgramMapped", "u"],
        LOAD_IDENTITY: ["LoadIdentity", ""],
        LOGIC_OP: ["LogicOp", "u"],
        MATERIALF: ["Materialf", "uuf"],
        MATERIALFV: ["Materialfv4", "uuuffff"],
        MATERIALI: ["Materiali", "uui"],
        MATERIALIV: ["Materialiv4", "uuuiiii"],
        MATRIX_MODE: ["MatrixMode", "u"],
        MULTI_TEX_COORD4F: ["MultiTexCoord4f", "uffff"],
        NORMAL3F: ["Normal3f", "fff"],
        ORTHO: ["Ortho", "dddddd"],
        PIXEL_STOREI: ["PixelStorei", "ui"],
        PIXEL_TRANSFERF: ["PixelTransferf", "uf"],
        PIXEL_TRANSFERI: ["PixelTransferi", "ui"],
        PIXEL_ZOOM: ["PixelZoom", "ff"],
        POINT_PARAMETERF: ["PointParameterf", "uf"],
        POINT_PARAMETERFV: ["PointParameterfv3", "ufff"],
        POINT_PARAMETERI: ["PointParameteri", "ui"],
        POINT_SIZE: ["PointSize", "f"],
        POLYGON_MODE: ["PolygonMode", "uu"],
        POLYGON_OFFSET: ["PolygonOffset", "ff"],
        POP_ATTRIB: ["PopAttrib", ""],
        POP_CLIENT_ATTRIB: ["PopClientAttrib", ""],
        POP_MATRIX: ["PopMatrix", ""],
        PUSH_ATTRIB: ["PushAttrib", "u"],
        PUSH_CLIENT_ATTRIB: ["PushClientAttrib", "u"],
        PUSH_MATRIX: ["PushMatrix", ""],
        RASTER_POS4F: ["RasterPos4f", "ffff"],
        READ_BUFFER: ["ReadBuffer", "u"],
        RENDERBUFFER_STORAGE: ["RenderbufferStorageMapped", "uuii"],
        ROTATEF: ["Rotatef", "ffff"],
        SAMPLE_COVERAGE: ["SampleCoverage", "fu"],
        SCALEF: ["Scalef", "fff"],
        SCISSOR: ["Scissor", "iiii"],
        SECONDARY_COLOR3F: ["SecondaryColor3f", "fff"],
        SHADE_MODEL: ["ShadeModel", "u"],
        STENCIL_FUNC: ["StencilFunc", "uiu"],
        STENCIL_FUNC_SEPARATE: ["StencilFuncSeparate", "uuiu"],
        STENCIL_MASK: ["StencilMask", "u"],
        STENCIL_MASK_SEPARATE: ["StencilMaskSeparate", "uu"],
        STENCIL_OP: ["StencilOp", "uuu"],
        STENCIL_OP_SEPARATE: ["StencilOpSeparate", "uuuu"],
        TEX_COORD2F: ["TexCoord2f", "ff"],
        TEX_COORD4F: ["TexCoord4f", "ffff"],
        TEX_ENVF: ["TexEnvf", "uuf"],
        TEX_ENVFV: ["TexEnvfv4", "uuuffff"],
        TEX_ENVI: ["TexEnvi", "uui"],
        TEX_ENVIV: ["TexEnviv4", "uuuiiii"],
        TEX_GENF: ["TexGenf", "uuf"],
        TEX_GENFV: ["TexGenfv4", "uuuffff"],
        TEX_GENI: ["TexGeni", "uui"],
        TEX_GENIV: ["TexGeniv4", "uuuiiii"],
        TEX_PARAMETERF: ["TexParameterf", "uuf"],
        TEX_PARAMETERFV: ["TexParameterfv4", "uuuffff"],
        TEX_PARAMETERI: ["TexParameteri", "uui"],
        TEX_PARAMETERIV: ["TexParameteriv4", "uuuiiii"],
        TRANSLATEF: ["Translatef", "fff"],
        USE_PROGRAM: ["UseProgramMapped", "u"],
        VALIDATE_PROGRAM: ["ValidateProgramMapped", "u"],
        VERTEX3F: ["Vertex3f", "fff"],
        VERTEX4F: ["Vertex4f", "ffff"],
        VERTEX_ATTRIB4F: ["VertexAttrib4fMapped", "uffff"],
        VIEWPORT: ["Viewport", "iiii"],
        WINDOW_POS3F: ["WindowPos3f", "fff"],
    };

    const BYTES = { i: 4, u: 4, f: 4, d: 8 };

    function payloadBytes(types) {
        let n = 0;
        for (const t of types) n += BYTES[t];
        return n;
    }

    /* Decodes one flat argument list into `out`, returning the count. The
     * caller supplies the array so a hot draw path does not allocate. */
    function decodeArgs(types, view, offset, length, out) {
        let cursor = offset;
        const end = offset + length;
        for (let i = 0; i < types.length; ++i) {
            const t = types[i];
            const size = BYTES[t];
            if (cursor + size > end) return -1;
            switch (t) {
            case "i": out[i] = view.getInt32(cursor, true); break;
            case "u": out[i] = view.getUint32(cursor, true); break;
            case "f": out[i] = view.getFloat32(cursor, true); break;
            default: out[i] = view.getFloat64(cursor, true); break;
            }
            cursor += size;
        }
        return types.length;
    }

    const api = { SIGNATURES, BYTES, payloadBytes, decodeArgs };
    global.GLWireFormat = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/browser/glbridge/graphics_journal.js                                                 0000644 0000000 0000000 00000037463 00000000000 017622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Lossless, paged command history. The budget limits the compressed RAM cache,
// not the amount of graphics work that can be included in a save state.
(function(global) {
    "use strict";
    const MAGIC = 0x32534756;
    const HEADER = 32, ENTRY = 32, PAGE_HEADER = 16;
    const PAGE_BYTES = 4 * 1024 * 1024;
    const MAX_PAGE_BYTES = 32 * 1024 * 1024;
    let serial = 0;
    const scriptURL = typeof document !== "undefined" && document.currentScript && document.currentScript.src;

    class PageCompressor {
        constructor(enabled) { this.enabled = enabled; }
        initialize() {
            if (this.ready) return this.ready;
            this.ready = new Promise(resolve => {
                if (!this.enabled || !scriptURL || typeof global.Worker !== "function") { resolve(); return; }
                try {
                    const url = new URL("graphics_journal_worker.js", scriptURL);
                    if (global.V86GL_BUILD_REVISION) url.searchParams.set("v", global.V86GL_BUILD_REVISION);
                    const worker = this.worker = new global.Worker(url);
                    worker.onmessage = event => {
                        if (event.data.ready) resolve();
                        else if (this.pending) {
                            const pending = this.pending;
                            this.pending = null;
                            pending.resolve(event.data);
                        }
                    };
                    worker.onerror = event => {
                        event.preventDefault();
                        const error = new Error("Graphics journal compression worker failed: " + event.message);
                        if (this.pending) { this.pending.reject(error); this.pending = null; }
                        worker.terminate();
                        this.worker = null;
                        resolve(); // Startup failure can still use the local fallback.
                    };
                } catch (_) { resolve(); }
            });
            return this.ready;
        }
        async compress(buffer, length, measure = false) {
            await this.initialize();
            if (this.worker) {
                const result = await new Promise((resolve, reject) => {
                    this.pending = { resolve, reject };
                    try { this.worker.postMessage({ buffer: buffer.buffer, length, measure }, [buffer.buffer]); }
                    catch (error) { this.pending = null; reject(error); }
                });
                return { data: new Uint8Array(result.buffer, 0, result.length), codec: result.codec,
                    compression_backend: "worker", compression_ms: result.compression_ms };
            }
            const start = measure ? global.performance.now() : 0;
            const raw = buffer.subarray(0, length);
            if (typeof global.CompressionStream === "function") {
                const blob = new Blob([raw]);
                const compressed = await new Response(blob.stream().pipeThrough(new global.CompressionStream("gzip"))).arrayBuffer();
                if (compressed.byteLength < length) return { data: new Uint8Array(compressed), codec: 1,
                    compression_backend: "local-stream", compression_ms: measure ? global.performance.now() - start : null };
            }
            return { data: length === buffer.length ? raw : raw.slice(), codec: 0,
                compression_backend: "local-raw", compression_ms: measure ? global.performance.now() - start : null };
        }
        destroy() { if (this.worker) this.worker.terminate(); this.worker = null; }
    }

    class PageStore {
        constructor() {
            this.prefix = Date.now() + "-" + (++serial) + "-" + Math.random() + ":";
            this.keys = [];
            this.database = null;
        }
        open() {
            if (!this.database) this.database = new Promise((resolve, reject) => {
                const request = global.indexedDB.open("v86-graphics-journal", 1);
                request.onupgradeneeded = () => request.result.createObjectStore("pages");
                request.onsuccess = () => resolve(request.result);
                request.onerror = () => reject(request.error);
            });
            return this.database;
        }
        async transaction(mode, action) {
            const db = await this.open();
            return new Promise((resolve, reject) => {
                const transaction = db.transaction("pages", mode);
                const request = action(transaction.objectStore("pages"));
                transaction.oncomplete = () => resolve(request && request.result);
                transaction.onabort = transaction.onerror = () => reject(transaction.error || new Error("Graphics journal cache failed"));
            });
        }
        async put(data) {
            const key = this.prefix + this.keys.length;
            await this.transaction("readwrite", store => store.put(data, key));
            this.keys.push(key);
            return key;
        }
        async get(key) {
            const data = await this.transaction("readonly", store => store.get(key));
            if (!(data instanceof Uint8Array)) throw new Error("Graphics journal cache page is missing");
            return data;
        }
        async destroy() {
            if (!this.database) return;
            try {
                await this.transaction("readwrite", store => {
                    for (const key of this.keys) store.delete(key);
                });
            } finally {
                (await this.database).close();
            }
        }
    }

    async function collect(stream, expected) {
        const reader = stream.getReader(), parts = [];
        let size = 0;
        try {
            for (;;) {
                const { done, value } = await reader.read();
                if (done) break;
                size += value.byteLength;
                if (size > expected) throw new Error("Graphics journal decompression exceeds page size");
                parts.push(value);
            }
        } catch (error) {
            await reader.cancel().catch(() => {});
            throw error;
        } finally { reader.releaseLock(); }
        const result = new Uint8Array(size);
        let offset = 0;
        for (const part of parts) { result.set(part, offset); offset += part.byteLength; }
        return result;
    }

    class GraphicsJournal {
        constructor(options = {}) {
            this["performanceTimingVersion"] = 1;
            this.budget = options.budget ?? 64 * 1024 * 1024;
            this.pageBytes = options.pageBytes || PAGE_BYTES;
            this.store = options.store === undefined ?
                (global.indexedDB ? new PageStore() : null) : options.store;
            this.compressor = new PageCompressor(options.worker !== false);
            this.buffer = null;
            this.view = null;
            this.partBytes = this.partCount = this.rawBytes = this.count = this.residentBytes = 0;
            this.pages = [];
            this.trimCursor = 0;
            this.work = Promise.resolve();
            this.error = null;
            this.cacheError = null;
        }
        append(record, bytes = record.bytes) {
            if (this.destroyed) throw new Error("Graphics journal has been destroyed");
            const size = ENTRY + bytes.length;
            if (size > MAX_PAGE_BYTES)
                throw new Error("Graphics batch exceeds the supported page size");
            if (this.partBytes && this.partBytes + size > this.buffer.length) this.seal();
            if (!this.buffer) {
                this.buffer = new Uint8Array(Math.max(this.pageBytes, size));
                this.view = new DataView(this.buffer.buffer);
            }
            // One owned copy into a contiguous page: no per-batch header,
            // payload allocation, temporary word array, or Blob fragment.
            const offset = this.partBytes, view = this.view;
            view.setUint32(offset, bytes.length, true);
            view.setUint32(offset + 4, record.flags >>> 0, true);
            view.setUint32(offset + 8, record.frameId >>> 0, true);
            view.setUint32(offset + 12, record.submitCount >>> 0, true);
            view.setUint32(offset + 16, record.commandCount >>> 0, true);
            view.setUint32(offset + 20, record.responseBase >>> 0, true);
            view.setUint32(offset + 24, record.barrier ? 1 : 0, true);
            view.setUint32(offset + 28, 0, true);
            this.buffer.set(bytes, offset + ENTRY);
            this.partBytes += size;
            this.rawBytes += size;
            this.partCount++;
            this.count++;
            if (this.partBytes >= this.pageBytes) this.seal();
        }
        seal() {
            if (!this.partCount) return;
            const buffer = this.buffer, rawBytes = this.partBytes, count = this.partCount;
            const timing = this["performanceTiming"]?.["page"](rawBytes);
            this.buffer = this.view = null;
            this.partBytes = this.partCount = 0;
            this.work = this.work.then(async () => {
                if (timing) timing["start"]();
                let result;
                try { result = await this.compressor.compress(buffer, rawBytes, !!timing); }
                catch (error) { if (timing) timing["finish"](null); throw error; }
                if (timing) timing["finish"](result);
                const { data, codec } = result;
                const page = { data, bytes: data.length, rawBytes, count, codec };
                this.pages.push(page);
                this.residentBytes += page.bytes;
                await this.trim();
            }).catch(error => { this.error = error; });
        }
        async trim() {
            if (!this.store || this.cacheError) return;
            while (this.trimCursor < this.pages.length && this.residentBytes > this.budget) {
                const page = this.pages[this.trimCursor];
                try {
                    page.key = await this.store.put(page.data);
                    page.data = null;
                    this.residentBytes -= page.bytes;
                    ++this.trimCursor;
                } catch (error) {
                    // Quota/private-mode failures must not discard commands.
                    // Keep this and subsequent compressed pages in RAM.
                    this.cacheError = error;
                    console.warn("[v86gl] journal disk cache unavailable; retaining compressed history in memory", error);
                    break;
                }
            }
        }
        async data(page) { return page.data || this.store.get(page.key); }
        async snapshot(legacy = new Uint8Array(0)) {
            this.seal();
            await this.work;
            if (this.error) throw this.error;
            const size = HEADER + legacy.length + this.pages.reduce((n, page) => n + PAGE_HEADER + page.bytes, 0);
            if (size > 0x7fffffff) throw new Error("Compressed graphics state exceeds the emulator's 2 GiB state format");
            const bytes = new Uint8Array(size), view = new DataView(bytes.buffer);
            view.setUint32(0, MAGIC, true); view.setUint16(4, 3, true);
            view.setUint16(6, HEADER, true); view.setUint32(8, size, true);
            view.setUint32(12, legacy.length, true); view.setUint32(16, this.pages.length, true);
            bytes.set(legacy, HEADER);
            let offset = HEADER + legacy.length;
            for (const page of this.pages) {
                [page.bytes, page.rawBytes, page.count, page.codec].forEach((word, i) => view.setUint32(offset + i * 4, word, true));
                const data = await this.data(page);
                if (data.length !== page.bytes) throw new Error("Graphics journal cache page has the wrong size");
                bytes.set(data, offset + PAGE_HEADER);
                offset += PAGE_HEADER + page.bytes;
            }
            return bytes;
        }
        static parse(bytes) {
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            if (bytes.length < HEADER || view.getUint32(0, true) !== MAGIC || view.getUint16(4, true) !== 3 ||
                    view.getUint16(6, true) !== HEADER || view.getUint32(8, true) !== bytes.length)
                throw new Error("Invalid compressed graphics checkpoint header");
            const legacyBytes = view.getUint32(12, true);
            if (legacyBytes > bytes.length - HEADER) throw new Error("Invalid legacy checkpoint size");
            const legacy = bytes.slice(HEADER, HEADER + legacyBytes), pages = [];
            let offset = HEADER + legacyBytes;
            for (let i = 0, count = view.getUint32(16, true); i < count; ++i) {
                if (offset + PAGE_HEADER > bytes.length) throw new Error("Invalid graphics page header");
                const size = view.getUint32(offset, true), rawBytes = view.getUint32(offset + 4, true);
                const entries = view.getUint32(offset + 8, true), codec = view.getUint32(offset + 12, true);
                if (size > bytes.length - offset - PAGE_HEADER || !rawBytes || rawBytes > MAX_PAGE_BYTES ||
                        !entries || entries > rawBytes / ENTRY || codec > 1 || (codec === 0 && size !== rawBytes))
                    throw new Error("Invalid graphics checkpoint page");
                pages.push({ data: bytes.subarray(offset + PAGE_HEADER, offset + PAGE_HEADER + size), rawBytes, count: entries, codec });
                offset += PAGE_HEADER + size;
            }
            if (offset !== bytes.length) throw new Error("Invalid graphics checkpoint trailing data");
            return { version: 3, legacy, pages };
        }
        static async *records(parsed) {
            for (const page of parsed.pages) {
                let bytes = page.data;
                if (page.codec === 1) {
                    if (typeof global.DecompressionStream !== "function") throw new Error("This browser cannot decompress graphics checkpoints");
                    bytes = await collect(new Blob([bytes]).stream().pipeThrough(new global.DecompressionStream("gzip")), page.rawBytes);
                }
                if (bytes.length !== page.rawBytes) throw new Error("Graphics journal decompressed size mismatch");
                const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
                let offset = 0;
                for (let i = 0; i < page.count; ++i) {
                    if (offset + ENTRY > bytes.length) throw new Error("Invalid graphics batch header");
                    const size = view.getUint32(offset, true), kind = view.getUint32(offset + 24, true);
                    if (size > bytes.length - offset - ENTRY || kind > 1 || (kind === 1 && size) || view.getUint32(offset + 28, true))
                        throw new Error("Invalid graphics batch");
                    yield { flags: view.getUint32(offset + 4, true), frameId: view.getUint32(offset + 8, true),
                        submitCount: view.getUint32(offset + 12, true), commandCount: view.getUint32(offset + 16, true),
                        responseBase: view.getUint32(offset + 20, true), barrier: kind === 1,
                        bytes: bytes.subarray(offset + ENTRY, offset + ENTRY + size) };
                    offset += ENTRY + size;
                }
                if (offset !== bytes.length) throw new Error("Invalid graphics batch count");
            }
        }
        async destroy() {
            this.destroyed = true;
            await this.work;
            this.compressor.destroy();
            if (this.store) await this.store.destroy().catch(error => console.warn("[v86gl] journal cache cleanup failed", error));
            this.buffer = this.view = null;
            this.pages = [];
            this.residentBytes = 0;
        }
    }
    global.V86GraphicsJournal = GraphicsJournal;
    if (typeof module !== "undefined" && module.exports) module.exports = { GraphicsJournal };
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                             source/v64/src/browser/glbridge/graphics_journal_worker.js                                          0000644 0000000 0000000 00000002123 00000000000 021174  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Dedicated compression thread. Pages arrive by ownership transfer, so neither
// structured clone nor compression scans command bytes on the emulation thread.
(function() {
    "use strict";
    self.onmessage = async event => {
        const { buffer, length, measure } = event.data;
        const start = measure ? performance.now() : 0;
        let data = buffer, codec = 0;
        try {
            const blob = new Blob([new Uint8Array(buffer, 0, length)]);
            const compressed = await new Response(blob.stream().pipeThrough(new self.CompressionStream("gzip"))).arrayBuffer();
            if (compressed.byteLength < length) { data = compressed; codec = 1; }
        } catch (_) {
            // Compression is optional. Return the original owned page on failure.
        }
        if (data === buffer && length < buffer.byteLength) data = buffer.slice(0, length);
        self.postMessage({ buffer: data, codec, length: codec ? data.byteLength : length,
            compression_ms: measure ? performance.now() - start : null }, [data]);
    };
    self.postMessage({ ready: true });
})();
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/browser/glbridge/graphics_proxy.js                                                   0000644 0000000 0000000 00000035006 00000000000 017320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The graphics proxy as one of v86's device plugins (the graphics_proxy
// option, docs/graphics-proxy-plugin-plan.md). Its virtio device
// (v86gl_device.js) runs next to the CPU; this side renders, and the two talk
// over a channel. Load after v86gl_device.js, v86_network_bridge.js and the
// executors.
(function(global) {
    "use strict";

    /* Stop an executor's work before it is dropped; its device goes separately */
    async function retireExecutors(executors) {
        await Promise.allSettled(executors.flatMap(executor => [executor.readyPromise,
            executor.checkpointIdle ? executor.checkpointIdle() :
                executor.idle ? executor.idle() : executor.work]));
        for (const executor of executors) {
            executor.destroyed = true;
            if (executor.shaderCacheSaveTimer !== null && executor.shaderCacheSaveTimer !== undefined) {
                global.clearTimeout(executor.shaderCacheSaveTimer);
                executor.shaderCacheSaveTimer = null;
                await executor.flushPersistentShaderCache();
            }
            if (executor.shaderWorker) executor.shaderWorker.terminate();
            if (executor.shaderWorkerRequests) executor.shaderWorkerRequests.clear();
            if (executor.pending) executor.pending.length = 0;
        }
    }

    // Where this bundle was loaded from: a CPU worker loads the device from
    // beside it (build/glbridge/v86gl-device.js, the same revision)
    const bundleScript = typeof document !== "undefined" && document.currentScript ?
        document.currentScript.src : null;

    function defaultWorkerScript() {
        if (!bundleScript) return undefined;
        const url = new URL("v86gl-device.js", bundleScript);
        url.search = new URL(bundleScript).search;
        return url.href;
    }

    function reportUnavailable(options, error) {
        if (typeof options.onError === "function") options.onError(error);
        else console.error("[v86gl] graphics unavailable; VGA remains active", error);
    }

    /*
     * One canvas (docs/display-design.md): a compositor
     * takes over the screen canvas and shows each API's output as a window
     * layer over the guest desktop.
     *
     * options.screenCanvas is the emulator's screen canvas; options.screenBackend
     * ({ set, fallback }) hands the screen's drawing to the compositor, or back
     * to the 2D canvas if WebGPU cannot start.
     */
    function createGraphicsBridge(emulator, options) {
        options = options || {};
        const screen = options.screenCanvas;
        const backend = options.screenBackend;
        if (!screen || !backend)
            throw new Error("the graphics adapter draws through the emulator's screen canvas");
        const compositor = new global.V86WebGPUCompositor(screen);
        // before the bridge: installing an executor starts its initialization
        compositor.useHost(global.V86GPUHost.acquire(screen, options.hostOptions));
        const bridge = global.installV86GLNetworkBridge(emulator, null, { ...options, compositor });
        bridge.compositor = compositor;
        bridge.screenChanged = () => {
            if (bridge.destroyed) return;
            if (options.isGraphical && !options.isGraphical()) {
                bridge.hideLayers(true);
                bridge.d3d9SwapChainSurfaces.clear();
            }
            bridge.placeLayers();
        };
        const executors = () => [bridge.glExecutor, bridge.d3d8Executor, bridge.d3d9Executor].filter(Boolean);
        let screenTaken = false;
        const attachHost = async () => {
            await compositor.attach(global.V86GPUHost.acquire(screen, options.hostOptions));
            if (!screenTaken) {
                screenTaken = true;
                backend.set(compositor);
            }
        };
        const initializeExecutors = async () => {
            try {
                await Promise.all(executors().map(executor => executor.initialize && executor.initialize()));
            } catch (error) {
                bridge.failed = error;
                bridge.hideLayers(true);
                reportUnavailable(options, error);
            }
        };
        const initialize = async () => {
            try {
                await attachHost();
            } catch (error) {
                bridge.failed = error;
                if (!screenTaken) {
                    // No WebGPU: the screen goes back to its 2D canvas
                    screenTaken = true;
                    backend.fallback();
                }
                reportUnavailable(options, error);
                return;
            }
            await initializeExecutors();
        };
        const disposeExecutors = async () => {
            await retireExecutors(executors());
            for (const handle of Array.from(bridge.d3d9SwapChainCanvases.keys()))
                bridge.removeD3D9SwapChain(handle);
            bridge.glExecutor = bridge.d3d8Executor = bridge.d3d9Executor = null;
        };
        // A fresh device: nothing of the old timeline's GPU objects survives. The compositor moves with it and
        // the screen is drawn again from the device.
        const replaceDevice = async () => {
            const old = compositor.host;
            compositor.detach();
            if (old) {
                if (old.recovering) await old.recovering.catch(() => {});
                old.destroyed = true;
                old.deviceLostHandlers.clear();
                if (old.device && old.device.destroy) old.device.destroy();
            }
            global.V86GPUHost.reset(screen);
            compositor.useHost(global.V86GPUHost.acquire(screen, options.hostOptions));
        };
        const resetExecutors = async (restoring) => {
            ++bridge.memoryGeneration;
            bridge.suspended = true;
            bridge.restoringState = true;
            bridge.hideLayers(true);
            await disposeExecutors();
            await bridge.resetJournal();
            bridge.legacyCheckpoint = new Uint8Array(0);
            bridge.glJournal = [];
            bridge.glJournalBytes = 0;
            bridge.glJournalOverflow = false;
            if (!restoring) bridge.pendingBatches = [];
            bridge.d3d8OwnerSessionKey = bridge.d3d9OwnerSessionKey = null;
            bridge.glSurface = bridge.emptySurface();
            bridge.d3d8Surface = bridge.emptySurface();
            bridge.d3d9Surface = bridge.emptySurface();
            bridge.failed = null;
            await replaceDevice();
            bridge.installGLExecutor();
            bridge.installD3D8Executor();
            bridge.installD3D9Executor();
            try {
                await attachHost();
            } catch (error) {
                bridge.failed = error;
                reportUnavailable(options, error);
            }
            bridge.ready = bridge.failed ? Promise.resolve() : initializeExecutors();
            await bridge.ready;
            bridge.restoringState = !!restoring;
            bridge.suspended = false;
            bridge.hideLayers(true);
        };
        bridge.reset = () => resetExecutors(false);
        bridge.resetForStateRestore = () => resetExecutors(true);
        bridge.makeScreenshot = () => compositor.attached ? compositor.screenshotImage() : null;
        let cleanup;
        bridge.destroy = () => {
            if (cleanup) return cleanup;
            bridge.destroyed = true;
            ++bridge.memoryGeneration;
            bridge.hideLayers(true);
            cleanup = (async () => {
                await bridge.pendingRestore.catch(() => {});
                await disposeExecutors();
                bridge.pendingBatches = [];
                bridge.glJournal = [];
                await bridge.graphicsJournal.destroy();
                bridge.preparedCheckpoint = null;
                bridge.graphicsJournalBytes = 0;
                bridge.legacyCheckpoint = new Uint8Array(0);
                // The compositor keeps drawing the screen for as long as it exists
            })();
            return cleanup;
        };
        bridge.hideLayers(true);
        bridge.ready = initialize();
        return bridge;
    }

    /*
     * What graphics_proxy: true (or an options object) makes: the device for
     * v86's virtio_devices, and the hooks v86 calls around saves, restores,
     * resets, screen changes and screenshots. The renderer starts in start(),
     * when v86 hands over the screen and this side's end of the channel.
     */
    function V86GraphicsProxy(options) {
        options = { ...(options || {}) };
        // (tests replace the WebGPU renderer)
        const createBridge = options.createBridge || createGraphicsBridge;
        const createDevice = global.V86VirtioDeviceFactories && global.V86VirtioDeviceFactories.v86gl;
        if (typeof createDevice !== "function")
            throw new Error("graphics_proxy: v86gl_device.js is missing; load the whole libv86-webgpu.js");
        let bridge = null;
        let channel = null;
        let available = false;
        // Bumped whenever the guest's timeline is replaced: readbacks of
        // batches from before are dropped
        let epoch = 0;
        // Across threads batches are handled one at a time
        let work = Promise.resolve();
        const stats = { graphics_batches: 0, graphics_bytes: 0, graphics_pending: 0, graphics_peak_pending: 0 };

        const setAvailable = value => {
            if (!channel || available === value) return;
            available = value;
            channel.post({ type: "available", value });
        };

        const onBatch = message => {
            const batchEpoch = epoch;
            const generation = message.generation;
            const event = {
                frameId: message.frameId,
                flags: message.flags,
                commandCount: message.commandCount,
                bytes: message.bytes,
                descAddr: message.descAddr,
                descLen: message.descLen,
                batchAddr: message.batchAddr,
                responseBase: message.responseBase,
                submitCount: message.submitCount,
                handled: false,
                isMemoryValid: () => batchEpoch === epoch && !bridge.destroyed,
                writeGuestMemory: (offset, bytes) => {
                    if (batchEpoch !== epoch) return;
                    const data = channel.remote ? new Uint8Array(bytes).slice() : bytes;
                    channel.post({ type: "write", generation, offset, bytes: data },
                        channel.remote ? [data.buffer] : undefined);
                },
            };
            if (!channel.remote) {
                bridge.pushPCIBatch(event);
                channel.post({ type: "done", id: message.id });
                return;
            }
            // Acknowledged once the renderer is done with it, readbacks
            // included: the device holds the guest back while the renderer is behind
            ++stats.graphics_batches;
            stats.graphics_bytes += message.bytes.byteLength;
            stats.graphics_peak_pending = Math.max(stats.graphics_peak_pending, ++stats.graphics_pending);
            work = work.then(async () => {
                if (batchEpoch !== epoch) return;
                bridge.pushPCIBatch(event);
                await bridge.waitForSubmittedBatches();
            }).catch(error => {
                reportUnavailable(options, error);
                setAvailable(false);
            }).then(() => {
                --stats.graphics_pending;
                if (batchEpoch === epoch) channel.post({ type: "done", id: message.id });
            });
        };

        const plugin = {
            name: "v86gl",
            // The compositor draws the whole screen (docs/display-design.md)
            wants_screen: true,
            // The bridge, once started (for tests)
            bridge: null,
            // Batches across the CPU worker boundary
            stats,
            create_device: deviceChannel => createDevice(deviceChannel),
            // The same device in a CPU worker (it defines V86VirtioDeviceFactories.v86gl)
            worker_script: options.workerScript || defaultWorkerScript(),
            /*
             * context.screen: { canvas, set_backend, fallback, is_graphical };
             * context.channel: this side's end. Returns when the renderer is up
             * (or has failed and handed the screen back).
             */
            start(context) {
                const screen = context.screen;
                channel = context.channel;
                bridge = plugin.bridge = createBridge(context.emulator, {
                    ...options,
                    screenCanvas: screen.canvas,
                    screenBackend: { set: screen.set_backend, fallback: screen.fallback },
                    isGraphical: screen.is_graphical,
                });
                channel.listen(message => {
                    if (message.type === "batch") onBatch(message);
                });
                setAvailable(true);
                return bridge.ready.then(() => setAvailable(!bridge.failed));
            },
            screen_changed() {
                bridge.screenChanged();
            },
            // Settles when every batch received so far is acknowledged
            idle() {
                return work;
            },
            async prepare_save() {
                await bridge.prepareSaveState();
                return bridge.serializeCheckpoint();
            },
            release_save() {
                bridge.releaseCheckpoint();
            },
            async before_restore() {
                ++epoch;
                bridge.beginStateRestore();
                await bridge.waitForIdle(false, true);
            },
            async after_restore(checkpoint) {
                bridge.onPCIStateRestored(checkpoint);
                await bridge.finishStateRestore();
            },
            cancel_restore() {
                bridge.cancelStateRestore();
            },
            async reset() {
                ++epoch;
                await bridge.reset();
                setAvailable(!bridge.failed);
            },
            async destroy() {
                if (!bridge) return;
                setAvailable(false);
                await bridge.destroy();
            },
            screenshot() {
                return bridge ? bridge.makeScreenshot() : null;
            },
        };
        return plugin;
    }

    global.V86GraphicsProxy = V86GraphicsProxy;
    if (typeof module !== "undefined" && module.exports)
        module.exports = { V86GraphicsProxy, createGraphicsBridge };
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/browser/glbridge/gx/gx_executor.js                                                   0000644 0000000 0000000 00000567760 00000000000 017252  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GX: the renderer of VMware SVGA's DX contexts (VGPU10, level dx10;
// docs/gpu-devices.md, "GX"), D3D10-style state on WebGPU. The device side
// (src/graphics_adapters/vmware_svga/svga3d_dx.js) sends GX batches: the
// surfaces (with their contents, read from MOBs), the DX commands as the
// guest wrote them, shader tokens; this keeps the objects, translates the
// shaders (shader_ir/), builds pipelines for the state each draw uses, and
// answers readbacks and queries through the response region, like the D3D9
// executor does for D9WG.
//
// - Surfaces: buffers are GPUBuffers with a CPU copy (D3D lets the guest
//   update any byte range; WebGPU only whole dwords); textures are
//   GPUTextures (1D as 2D, cubes as 2D arrays). Formats: svga_dx_formats.js.
// - Order: uploads and copies are recorded in the command encoder, between
//   the render passes, so each draw sees the contents the guest gave before it.
// - Pipelines are cached by everything that goes into them; shader variants
//   (their interfaces depend on the input layout, the pixel shader, the
//   render targets) by the shader and those.
// - Viewports WebGPU would refuse (outside of the target) are clamped, and
//   the vertex shader moves the position to make up for it (gx_draw.viewport).
(function(global) {
    "use strict";

    const isNode = typeof module === "object" && module.exports && typeof require === "function";
    const IR = isNode ? require("../shader_ir/dxbc_frontend.js") : global.V86DXBCFrontend;
    const WGSL = isNode ? require("../shader_ir/wgsl_emitter.js") : global.V86WGSLEmitter;

    const GX_MAGIC = 0x30315847;
    const GX = {
        SURFACE_DEFINE: 1, SURFACE_DESTROY: 2, SURFACE_UPLOAD: 3, SURFACE_READBACK: 4,
        CONTEXT_DEFINE: 5, CONTEXT_DESTROY: 6, SHADER_CODE: 7, DX: 8, SURFACE_COPY: 9, QUERY_END: 10,
        COTABLE_RESET: 11, SURFACE_STRETCH: 12, SURFACE_IMPORT: 13, SURFACE_EXPORT: 14, CLEAR_RTV_INTEGER: 15,
        SURFACE_PRESENT: 16,
    };

    // SVGA_3D_CMD_DX_* (svga3d_cmd.h)
    const DX = {
        SET_SINGLE_CONSTANT_BUFFER: 1148, SET_SHADER_RESOURCES: 1149, SET_SHADER: 1150, SET_SAMPLERS: 1151,
        DRAW: 1152, DRAW_INDEXED: 1153, DRAW_INSTANCED: 1154, DRAW_INDEXED_INSTANCED: 1155, DRAW_AUTO: 1156,
        SET_INPUT_LAYOUT: 1157, SET_VERTEX_BUFFERS: 1158, SET_INDEX_BUFFER: 1159, SET_TOPOLOGY: 1160,
        SET_RENDERTARGETS: 1161, SET_BLEND_STATE: 1162, SET_DEPTHSTENCIL_STATE: 1163, SET_RASTERIZER_STATE: 1164,
        DEFINE_QUERY: 1165, DESTROY_QUERY: 1166, BEGIN_QUERY: 1169, END_QUERY: 1170, SET_PREDICATION: 1172,
        SET_SOTARGETS: 1173, SET_VIEWPORTS: 1174, SET_SCISSORRECTS: 1175, CLEAR_RENDERTARGET_VIEW: 1176,
        CLEAR_DEPTHSTENCIL_VIEW: 1177, PRED_COPY_REGION: 1178, PRED_COPY: 1179, PRESENTBLT: 1180, GENMIPS: 1181,
        DEFINE_SHADERRESOURCE_VIEW: 1185, DESTROY_SHADERRESOURCE_VIEW: 1186, DEFINE_RENDERTARGET_VIEW: 1187,
        DESTROY_RENDERTARGET_VIEW: 1188, DEFINE_DEPTHSTENCIL_VIEW: 1189, DESTROY_DEPTHSTENCIL_VIEW: 1190,
        DEFINE_ELEMENTLAYOUT: 1191, DESTROY_ELEMENTLAYOUT: 1192, DEFINE_BLEND_STATE: 1193, DESTROY_BLEND_STATE: 1194,
        DEFINE_DEPTHSTENCIL_STATE: 1195, DESTROY_DEPTHSTENCIL_STATE: 1196, DEFINE_RASTERIZER_STATE: 1197,
        DESTROY_RASTERIZER_STATE: 1198, DEFINE_SAMPLER_STATE: 1199, DESTROY_SAMPLER_STATE: 1200,
        DEFINE_SHADER: 1201, DESTROY_SHADER: 1202, DEFINE_STREAMOUTPUT: 1204, DESTROY_STREAMOUTPUT: 1205,
        SET_STREAMOUTPUT: 1206, BUFFER_COPY: 1209, TRANSFER_FROM_BUFFER: 1210, SURFACE_COPY_AND_READBACK: 1211,
        PRED_TRANSFER_FROM_BUFFER: 1215, SET_VS_CONSTANT_BUFFER_OFFSET: 1220, SET_CS_CONSTANT_BUFFER_OFFSET: 1225,
        RESOLVE_COPY: 1240, PRED_RESOLVE_COPY: 1241, PRED_CONVERT_REGION: 1242, PRED_CONVERT: 1243,
        DEFINE_UA_VIEW: 1245, DESTROY_UA_VIEW: 1246, CLEAR_UA_VIEW_UINT: 1247, CLEAR_UA_VIEW_FLOAT: 1248,
        SET_UA_VIEWS: 1250, DRAW_INDEXED_INSTANCED_INDIRECT: 1251, DRAW_INSTANCED_INDIRECT: 1252, DISPATCH: 1253,
        DISPATCH_INDIRECT: 1254, TRANSFER_TO_BUFFER: 1257, SET_CS_UA_VIEWS: 1268, SET_MIN_LOD: 1269,
        COPY_STRUCTURE_COUNT: 1249, SET_STRUCTURE_COUNT: 1258,
        DEFINE_DEPTHSTENCIL_VIEW_V2: 1272, DEFINE_STREAMOUTPUT_WITH_MOB: 1273, BIND_STREAMOUTPUT: 1275,
        PRED_STAGING_COPY: 1281, STAGING_COPY: 1282, PRED_STAGING_COPY_REGION: 1283, SET_VERTEX_BUFFERS_V2: 1284,
        SET_INDEX_BUFFER_V2: 1285, SET_VERTEX_BUFFERS_OFFSET_AND_SIZE: 1286, SET_INDEX_BUFFER_OFFSET_AND_SIZE: 1287,
        DEFINE_RASTERIZER_STATE_V2: 1288, PRED_STAGING_CONVERT_REGION: 1289, PRED_STAGING_CONVERT: 1290,
        STAGING_BUFFER_COPY: 1291,
    };

    const SVGA3D_BUFFER = 37;
    const SVGA3D_R16_UINT = 89, SVGA3D_R32_UINT = 77, SVGA3D_R8G8B8A8_UNORM = 0x44;
    // depth formats whose guest layout differs: D3D9's 32-bit integer depth, and depth in the high 24 bits
    const SVGA3D_Z_D32 = 7, SVGA3D_Z_D24S8 = 9, SVGA3D_Z_D24X8 = 0x26, SVGA3D_Z_DF24 = 0x77, SVGA3D_Z_D24S8_INT = 0x78;
    const SURFACE_CUBEMAP = 1, SURFACE_VOLUME = 0x8000;
    // the tessellator (tessellator_wgsl.js); patch lists' topologies: 10 + control points
    const TESS = isNode ? require("./tessellator_wgsl.js") : global.V86TessellatorWGSL;
    const TOPOLOGY_PATCHLIST_1 = 11, TOPOLOGY_PATCHLIST_32 = 42, TOPOLOGY_TRIANGLEFAN = 6;
    // (in the flags' high word: SVGA3D_SURFACE_BIND_UAVIEW, 1 << 33)
    const SURFACE2_BIND_UAVIEW = 2;
    // what WebGPU stores into (typed UAVs); bgra8unorm with "bgra8unorm-storage"
    const STORAGE_FORMATS = new Set(["rgba8unorm", "rgba8snorm", "rgba8uint", "rgba8sint", "rgba16uint", "rgba16sint", "rgba16float",
        "r32uint", "r32sint", "r32float", "rg32uint", "rg32sint", "rg32float", "rgba32uint", "rgba32sint", "rgba32float"]);
    // SVGA3dUABufferFlags
    const UABUFFER_RAW = 1;
    const DIM_BUFFER = 1;
    // where a buffer view starts, in GXViews (wgsl_emitter.js): UAV n at n, resource n at 64 + n
    const VIEW_BASE_RESOURCE = 64, VIEW_BASES = 192;
    const INVALID = 0xFFFFFFFF;
    const SHADER_VS = 1, SHADER_PS = 2, SHADER_GS = 3, SHADER_HS = 4, SHADER_DS = 5, SHADER_CS = 6;
    // SVGA3dQueryType: stream output statistics (all streams, stream 0-3)
    // and overflow predicates (all, stream 0-3); GX counts stream 0's
    const SO_QUERIES = new Set([5, 6, 8, 9, 10, 11, 12, 13, 14, 15]);
    const COTABLE = { RTVIEW: 0, DSVIEW: 1, SRVIEW: 2, ELEMENTLAYOUT: 3, BLENDSTATE: 4, DEPTHSTENCIL: 5,
        RASTERIZERSTATE: 6, SAMPLER: 7, STREAMOUTPUT: 8, DXQUERY: 9, DXSHADER: 10, UAVIEW: 11 };

    // response region (d9wg): query slots below 16 KiB, readbacks after
    const QUERY_REGION_BYTES = 16 * 1024;
    const RESPONSE_OK = 1, RESPONSE_FAILED = 2;

    const BUFFER_USAGE = { MAP_READ: 1, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128, INDIRECT: 256, QUERY_RESOLVE: 512 };
    const TEXTURE_USAGE = { COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16 };

    const DRAW_SLOT = 256;
    const DRAW_SLOTS = 4096;

    const BLEND_FACTORS = [null, "zero", "one", "src", "one-minus-src", "src-alpha", "one-minus-src-alpha", "dst-alpha",
        "one-minus-dst-alpha", "dst", "one-minus-dst", "src-alpha-saturated", "constant", "one-minus-constant",
        "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha", "constant", "one-minus-constant"];
    const BLEND_OPS = [null, "add", "subtract", "reverse-subtract", "min", "max"];
    const COMPARE = [null, "never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always"];
    const STENCIL_OPS = [null, "keep", "zero", "replace", "increment-clamp", "decrement-clamp", "invert", "increment-wrap", "decrement-wrap"];
    const ADDRESS = [null, "repeat", "mirror-repeat", "clamp-to-edge", "clamp-to-edge", "mirror-repeat", "clamp-to-edge"];
    // SVGA3dPrimitiveType -> WebGPU topology (adjacency drawn without it)
    const TOPOLOGY = [null, "triangle-list", "point-list", "line-list", "line-strip", "triangle-strip", null,
        "line-list", "line-strip", "triangle-list", "triangle-strip"];
    // the input primitives of a geometry shader, by SVGA3dPrimitiveType: the
    // topology code wgsl_emitter.js assembles them by, and how many a draw of
    // n vertices has
    /** An SVGA3dStreamOutputDeclarationEntry at words[at]: outputSlot, registerIndex, registerMask, stream */
    function soEntry(words, at) {
        return { slot: words[at] & 3, reg: words[at + 1], mask: words[at + 2] & 0xF, stream: words[at + 3] };
    }
    const GS_ASSEMBLY = {
        1: { code: 4, prims: n => Math.floor(n / 3) }, 2: { code: 1, prims: n => n }, 3: { code: 2, prims: n => n >> 1 },
        4: { code: 3, prims: n => n - 1 }, 5: { code: 5, prims: n => n - 2 }, 7: { code: 10, prims: n => n >> 2 },
        8: { code: 11, prims: n => n - 3 }, 9: { code: 12, prims: n => Math.floor(n / 6) }, 10: { code: 13, prims: n => (n - 4) >> 1 },
    };

    const SRGB = {
        "rgba8unorm": "rgba8unorm-srgb", "rgba8unorm-srgb": "rgba8unorm", "bgra8unorm": "bgra8unorm-srgb",
        "bgra8unorm-srgb": "bgra8unorm", "bc1-rgba-unorm": "bc1-rgba-unorm-srgb", "bc1-rgba-unorm-srgb": "bc1-rgba-unorm",
        "bc2-rgba-unorm": "bc2-rgba-unorm-srgb", "bc2-rgba-unorm-srgb": "bc2-rgba-unorm",
        "bc3-rgba-unorm": "bc3-rgba-unorm-srgb", "bc3-rgba-unorm-srgb": "bc3-rgba-unorm",
        "bc7-rgba-unorm": "bc7-rgba-unorm-srgb", "bc7-rgba-unorm-srgb": "bc7-rgba-unorm",
    };

    function align(value, to) {
        return Math.ceil(value / to) * to;
    }

    function f32(bits) {
        return new Float32Array(new Uint32Array([bits]).buffer)[0];
    }

    function isDepthFormat(format) {
        return format.startsWith("depth") || format === "stencil8";
    }

    /** A WebGPU format's family: its sRGB twin views the same texture */
    function family(format) {
        return format.replace(/-srgb$/, "");
    }

    /** A format's typeless group (D3D's): the channels and their sizes, not their type */
    function typelessGroup(format) {
        return format.replace(/(unorm|snorm|uint|sint|float|ufloat)(-srgb)?$/, "");
    }

    function hasStencil(format) {
        return format.includes("stencil");
    }

    function sampleKind(format) {
        if (isDepthFormat(format)) return "depth";
        if (/sint$/.test(format)) return "sint";
        if (/uint$/.test(format)) return "uint";
        return "float";
    }

    class GXExecutor {
        /**
         * @param options { device, formats: [[gpu, can, vertex, bw, bh, bytes], ...] by SVGA format,
         *                  features: { float32Filterable, ... } }
         */
        constructor(options) {
            this.device = options.device;
            /** the D3D9 executor on the same device: { resource(handle), flush() } */
            this.peer = options.peer || null;
            this.formats = options.formats;
            this.features = options.features || {};
            this.write = null;
            this.surfaces = new Map();
            this.contexts = new Map();
            this.encoderInstance = null;
            this.pass = null;
            this.passKey = "";
            this.pending = [];
            this.transient = [];
            this.pipelines = new Map();
            /** the orders of draws without indices that flat shade with the last vertex (provokingLast) */
            this.provokingIndices = new Map();
            this.modules = new Map();
            this.samplerCache = new Map();
            this.warned = new Set();
            this.errors = 0;
            this.stats = { batches: 0, draws: 0, pipelines: 0, shaders: 0, passes: 0, uploads: 0, readbacks: 0, dispatches: 0 };
            this.drawBuffer = this.device.createBuffer({ size: DRAW_SLOT * DRAW_SLOTS,
                usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
            this.drawSlot = 0;
            this.occlusion = null;
            this.activeOcclusion = new Map();
            this.blitPipelines = new Map();
            this.depthUploadPipelines = new Map();
            this.emptyLayout = this.device.createBindGroupLayout({ entries: [] });
            this.emptyGroup = this.device.createBindGroup({ layout: this.emptyLayout, entries: [] });
            this.dummyBuffer = this.device.createBuffer({ size: 65536, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.STORAGE | BUFFER_USAGE.VERTEX });
            // (UAVs bound to nothing write here: never the vertex buffers' dummy, which a pass reads)
            this.dummyUav = this.device.createBuffer({ size: 65536, usage: BUFFER_USAGE.STORAGE });
            this.dummyStorageTextures = new Map();
            this.clearPipelines = new Map();
            if (this.features.bgra8unormStorage) STORAGE_FORMATS.add("bgra8unorm");
            this.dummyTextures = new Map();
            this.linearSampler = this.device.createSampler({ magFilter: "linear", minFilter: "linear" });
            this.nearestSampler = this.device.createSampler({});
            if (typeof this.device.addEventListener === "function") {
                this.device.addEventListener("uncapturederror", event => this.warn("webgpu:" + (event.error && event.error.message),
                    "WebGPU error: " + (event.error && event.error.message)));
            }
        }

        warn(key, text) {
            if (this.warned.has(key)) return;
            this.warned.add(key);
            if (this.warned.size < 200) console.warn("[gx] " + text);
        }

        reset() {
            this.endPass();
            this.flushEncoder();
            for (const s of this.surfaces.values()) this.releaseSurface(s);
            this.surfaces.clear();
            this.contexts.clear();
            this.activeOcclusion.clear();
        }

        /**
         * Run a GX batch
         * @param bytes Uint8Array
         * @param options { writeResponse(offset, bytes) }
         */
        async submit(bytes, options) {
            this.write = options.writeResponse;
            // (a batch cut out of a bigger message may start anywhere)
            if (bytes.byteOffset & 3) bytes = bytes.slice();
            const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
            if (words[0] !== GX_MAGIC) throw new Error("not a GX batch");
            const end = Math.min(words[2], words.length);
            this.stats.batches++;
            for (let at = 4; at + 2 <= end;) {
                const op = words[at], n = words[at + 1];
                const body = words.subarray(at + 2, at + 2 + n);
                at += 2 + n;
                try {
                    this.command(op, body);
                } catch (error) {
                    this.errors++;
                    this.warn("exception:" + op + ":" + (body[1] || 0) + ":" + error.message,
                        "command " + op + (op === GX.DX ? " (DX " + body[1] + ")" : "") + " failed: " + (error.stack || error));
                }
            }
            this.endPass();
            this.flushEncoder();
            const pending = this.pending.splice(0);
            if (pending.length) await Promise.all(pending);
        }

        command(op, b) {
            switch (op) {
                case GX.SURFACE_DEFINE: return this.defineSurface(b);
                case GX.SURFACE_DESTROY: {
                    const s = this.surfaces.get(b[0]);
                    // (after the commands recorded with it: a submit with a
                    // destroyed texture is refused whole, readbacks and all)
                    if (s) this.flushEncoder();
                    if (s) this.releaseSurface(s);
                    this.surfaces.delete(b[0]);
                    return;
                }
                case GX.SURFACE_UPLOAD: return this.upload(b);
                case GX.SURFACE_READBACK: return this.readback(b);
                case GX.SURFACE_PRESENT: return this.present(b);
                case GX.CONTEXT_DEFINE: this.contexts.set(b[0], new GXContext(b[0])); return;
                case GX.CONTEXT_DESTROY: this.contexts.delete(b[0]); return;
                case GX.SHADER_CODE: return this.shaderCode(b);
                case GX.DX: return this.dx(b[0], b[1], b.subarray(2));
                case GX.SURFACE_COPY: return this.copySurface(b);
                case GX.SURFACE_STRETCH: return this.stretch(b);
                case GX.SURFACE_IMPORT: return this.share(b[0], b[1], false);
                case GX.SURFACE_EXPORT: return this.share(b[0], b[1], true);
                case GX.CLEAR_RTV_INTEGER: {
                    // cid, view, signed, 4 values: exact (DX's clear has floats)
                    const c = this.contexts.get(b[0]);
                    if (c) this.clearRTV(c, b[1], Array.from(b.subarray(3, 7), v => b[2] ? v | 0 : v >>> 0));
                    return;
                }
                case GX.QUERY_END: return this.endQuery(b);
                case GX.COTABLE_RESET: {
                    const c = this.contexts.get(b[0]);
                    if (c) c.reset(b[1]);
                    return;
                }
            }
            this.warn("op" + op, "unknown GX op " + op);
        }

        // ------------------------------------------------------------------
        // Encoder and passes

        encoder() {
            if (!this.encoderInstance) this.encoderInstance = this.device.createCommandEncoder();
            return this.encoderInstance;
        }

        endPass() {
            if (!this.pass) return;
            if (this.passOcclusion !== null) this.pass.endOcclusionQuery();
            this.pass.end();
            this.pass = null;
            this.passKey = "";
            this.passOcclusion = null;
        }

        flushEncoder() {
            this.endPass();
            if (this.encoderInstance) {
                this.device.queue.submit([this.encoderInstance.finish()]);
                this.encoderInstance = null;
            }
            for (const buffer of this.transient.splice(0)) buffer.destroy();
        }

        /** A buffer with these bytes, to copy from in the encoder */
        staging(bytes) {
            const size = align(Math.max(4, bytes.length), 4);
            const buffer = this.device.createBuffer({ size, usage: BUFFER_USAGE.COPY_SRC, mappedAtCreation: true });
            new Uint8Array(buffer.getMappedRange()).set(bytes);
            buffer.unmap();
            this.transient.push(buffer);
            return buffer;
        }

        // ------------------------------------------------------------------
        // Surfaces

        formatOf(format) {
            const f = this.formats[format];
            if (!f) return null;
            return { gpu: f[0], can: f[1], vertex: f[2], bw: f[3], bh: f[4], bytes: f[5] };
        }

        /** The table's first SVGA format of a WebGPU format, as formatOf gives it */
        gpuInfo(gpu) {
            if (!this.gpuInfos) this.gpuInfos = new Map();
            if (!this.gpuInfos.has(gpu)) {
                const at = Object.keys(this.formats).find(k => this.formats[k][0] === gpu);
                this.gpuInfos.set(gpu, at === undefined ? null : this.formatOf(at));
            }
            return this.gpuInfos.get(gpu);
        }

        // ------------------------------------------------------------------
        // Format aliases. A surface of a TYPELESS format (Mesa's svga makes
        // most of them so) is one WebGPU texture of one format, but its
        // views may be of any format of its texel layout (R32G32B32A32_UINT
        // of R32G32B32A32_FLOAT's texture), which WebGPU does not allow. Such
        // a view gets a texture of its own format's family, an alias; the
        // contents follow the family used last, copied raw (through a buffer)
        // when another family is used. (S.valid: the families that have them)

        /**
         * The texture that holds S as `format` (a WebGPU format), made
         * current; `write`: the others are stale after
         * @return {?{texture: !GPUTexture, views: !Map}} S itself for its own
         * family; null where no alias can be (other texel sizes, depth,
         * compressed): the caller uses S's texture as before
         */
        textureFor(S, format, write) {
            if (!S.texture) return null;
            const fam = family(format), own = family(S.f.gpu);
            let entry = S;
            if (fam !== own) {
                const f = this.gpuInfo(fam);
                if (!f || f.bytes !== S.f.bytes || f.bw !== 1 || f.bh !== 1 || S.f.bw !== 1 || S.f.bh !== 1 ||
                    typelessGroup(fam) !== typelessGroup(own) ||
                    isDepthFormat(fam) || isDepthFormat(own) || f.can.includes("e") || S.f.can.includes("e")) return null;
                if (!S.aliases) S.aliases = new Map();
                entry = S.aliases.get(fam);
                if (!entry) {
                    const t = S.texture;
                    const descriptor = { size: [t.width, t.height, t.depthOrArrayLayers], dimension: t.dimension, format: fam,
                        mipLevelCount: t.mipLevelCount,
                        usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_SRC | TEXTURE_USAGE.COPY_DST |
                            (f.can.includes("r") && (t.usage & TEXTURE_USAGE.RENDER_ATTACHMENT) ? TEXTURE_USAGE.RENDER_ATTACHMENT : 0) |
                            (STORAGE_FORMATS.has(fam) && S.uav ? TEXTURE_USAGE.STORAGE_BINDING : 0) };
                    if (SRGB[fam]) descriptor.viewFormats = [SRGB[fam]];
                    entry = { texture: this.device.createTexture(descriptor), views: new Map(), family: fam };
                    S.aliases.set(fam, entry);
                }
            }
            if (S.aliases) {
                if (!S.valid) S.valid = new Set([own]);
                if (!S.valid.has(fam)) {
                    const from = [...S.valid][0];
                    this.copyRaw(S, from === own ? S.texture : S.aliases.get(from).texture, entry.texture);
                    S.valid.add(fam);
                }
                if (write) S.valid = new Set([fam]);
            }
            return entry;
        }

        /** S's own texture made current (copies, uploads, readbacks use it) */
        primary(S, write) {
            if (S && S.aliases) this.textureFor(S, S.f.gpu, write);
        }

        /** Every image of `from` into `to`, as bytes (formats of the same texel size) */
        copyRaw(S, from, to) {
            this.endPass();
            const encoder = this.encoder();
            const bytes = S.f.bytes;
            for (let mip = 0; mip < from.mipLevelCount; mip++) {
                const w = Math.max(1, from.width >> mip), h = Math.max(1, from.height >> mip);
                const layers = from.dimension === "3d" ? Math.max(1, from.depthOrArrayLayers >> mip) : from.depthOrArrayLayers;
                const bytesPerRow = align(w * bytes, 256);
                const buffer = this.device.createBuffer({ size: bytesPerRow * h * layers, usage: BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST });
                this.transient.push(buffer);
                encoder.copyTextureToBuffer({ texture: from, mipLevel: mip }, { buffer, bytesPerRow, rowsPerImage: h }, [w, h, layers]);
                encoder.copyBufferToTexture({ buffer, bytesPerRow, rowsPerImage: h }, { texture: to, mipLevel: mip }, [w, h, layers]);
            }
            this.stats.aliasCopies = (this.stats.aliasCopies || 0) + 1;
        }

        defineSurface(b) {
            const [sid, format, flags, flags2, width, height, depth, mips, layers, samples, cube] = b;
            const old = this.surfaces.get(sid);
            if (old) this.flushEncoder();
            if (old) this.releaseSurface(old);
            const f = this.formatOf(format);
            const s = { sid, format, f, flags, width: Math.max(1, width), height: Math.max(1, height),
                depth: Math.max(1, depth), mips: Math.max(1, mips), layers: Math.max(1, layers), samples,
                cube: !!cube, buffer: null, texture: null, shadow: null, generation: 0, views: new Map(), ss: [1, 1] };
            this.surfaces.set(sid, s);
            if (format === SVGA3D_BUFFER) {
                const size = align(Math.max(4, s.width * s.height * s.depth), 4);
                s.shadow = new Uint8Array(size);
                s.buffer = this.device.createBuffer({ size, usage: BUFFER_USAGE.VERTEX | BUFFER_USAGE.INDEX |
                    BUFFER_USAGE.UNIFORM | BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST |
                    BUFFER_USAGE.INDIRECT });
                return;
            }
            if (!f || !f.gpu) {
                this.warn("format" + format, "surface format " + format + " has no WebGPU texture");
                return;
            }
            const volume = s.depth > 1 || !!(flags & SURFACE_VOLUME);
            const compressed = f.gpu.startsWith("bc");
            const target = (f.can.includes("r") || f.can.includes("d")) && !compressed && !volume;
            // A multisampled surface (4x, the one count the device offers)
            // is supersampled: a texture twice as wide and high, each sample
            // a texel of a 2x2 block, drawn at that size. Every format can
            // be, unlike WebGPU's multisampling, and nothing mixes sample
            // counts in a pass. (s.ss: the scale, x and y: 2 x 2 for 4x,
            // 4 x 2 for 8x)
            const multisampled = samples > 1 && !volume;
            s.ss = !multisampled ? [1, 1] : samples > 4 ? [4, 2] : [2, 2];
            const descriptor = {
                size: [s.width * s.ss[0], s.height * s.ss[1], volume ? s.depth : s.layers],
                dimension: volume ? "3d" : "2d",
                format: f.gpu,
                mipLevelCount: multisampled ? 1 : Math.min(s.mips, mipCount(s.width, s.height, volume ? s.depth : 1)),
                usage: TEXTURE_USAGE.TEXTURE_BINDING | TEXTURE_USAGE.COPY_SRC | TEXTURE_USAGE.COPY_DST |
                    (target ? TEXTURE_USAGE.RENDER_ATTACHMENT : 0) |
                    ((flags2 & SURFACE2_BIND_UAVIEW) && !multisampled && STORAGE_FORMATS.has(f.gpu) ? TEXTURE_USAGE.STORAGE_BINDING : 0),
            };
            if (SRGB[f.gpu]) descriptor.viewFormats = [SRGB[f.gpu]];
            s.volume = volume;
            // (UAVs of it may be of another format: format aliases)
            s.uav = !!(flags2 & SURFACE2_BIND_UAVIEW) && !multisampled;
            s.texture = this.device.createTexture(descriptor);
            s.gpuMips = descriptor.mipLevelCount;
            // "X" formats read as opaque: their alpha starts at 1
            if (f.can.includes("x") && target) this.clearTexture(s, [0, 0, 0, 1]);
        }

        releaseSurface(s) {
            if ((s.texture || s.buffer) && this.peer && this.peer.releasing) this.peer.releasing(s);
            if (s.soFilled) s.soFilled.destroy();
            s.soFilled = null;
            if (s.aliases) for (const alias of s.aliases.values()) alias.texture.destroy();
            s.aliases = s.valid = null;
            if (s.buffer) s.buffer.destroy();
            if (s.texture) s.texture.destroy();
            s.buffer = s.texture = null;
            s.generation++;
        }

        /** The size in blocks of a mip level */
        level(s, mip) {
            const width = Math.max(1, s.width >> mip), height = Math.max(1, s.height >> mip), depth = Math.max(1, s.depth >> mip);
            const f = s.f;
            return { width, height, depth, columns: Math.ceil(width / f.bw), rows: Math.ceil(height / f.bh),
                pitch: Math.ceil(width / f.bw) * f.bytes };
        }

        upload(b) {
            const [sid, layer, mip, x, y, z, w, h, d, pitch, slicePitch] = b;
            const s = this.surfaces.get(sid);
            if (!s) return;
            const data = new Uint8Array(b.buffer, b.byteOffset + 11 * 4, b.byteLength - 11 * 4);
            this.stats.uploads++;
            if (s.buffer) {
                const count = Math.min(w, s.shadow.length - x);
                if (count <= 0) return;
                s.shadow.set(data.subarray(0, count), x);
                // whole dwords: the bytes around the range come from the CPU copy
                const start = x & ~3, stop = Math.min(s.shadow.length, align(x + count, 4));
                this.endPass();
                this.encoder().copyBufferToBuffer(this.staging(s.shadow.subarray(start, stop)), 0, s.buffer, start, stop - start);
                return;
            }
            if (!s.texture || mip >= s.gpuMips) return;
            this.primary(s, true);
            // (multisampled surfaces: their samples are not in guest memory; zeros, which is what a new one has, are no news)
            if (s.samples > 1) {
                if (!data.every(b => b === 0)) this.warn("upload-ms", "uploads into multisampled surfaces are not supported");
                return;
            }
            if (isDepthFormat(s.f.gpu)) return this.uploadDepth(s, s.volume ? 0 : layer, mip, x, y, w, h, data, pitch);
            const f = s.f;
            const columns = Math.ceil(w / f.bw), rows = Math.ceil(h / f.bh);
            const rowBytes = Math.min(pitch, columns * f.bytes);
            const codec = f.can.includes("e") ? EMULATED[s.format] : null;
            const emulated = !!codec;
            const gpuRow = emulated ? columns * codec.texels * codec.gpu : rowBytes;
            const alignedPitch = align(Math.max(gpuRow, 1), 256);
            const slices = Math.max(1, d);
            const staged = new Uint8Array(alignedPitch * rows * slices);
            for (let slice = 0; slice < slices; slice++) {
                for (let row = 0; row < rows; row++) {
                    const from = slice * slicePitch + row * pitch;
                    const to = (slice * rows + row) * alignedPitch;
                    if (emulated) expandRow(s.format, f.bytes, data.subarray(from, from + rowBytes), staged.subarray(to, to + gpuRow));
                    else staged.set(data.subarray(from, from + rowBytes), to);
                }
            }
            if (!emulated) this.convertIn(s, staged, alignedPitch, columns, rows * slices);
            this.endPass();
            const level = this.level(s, mip);
            // (an emulated format's texture has blocks of one texel)
            const bw = emulated ? 1 : f.bw, bh = emulated ? 1 : f.bh;
            const copyWidth = Math.min(align(w, bw), align(level.width, bw) - x, emulated ? columns * codec.texels : Infinity);
            const copyHeight = Math.min(align(h, bh), align(level.height, bh) - y);
            if (copyWidth <= 0 || copyHeight <= 0) return;
            this.encoder().copyBufferToTexture(
                { buffer: this.staging(staged), bytesPerRow: alignedPitch, rowsPerImage: rows },
                { texture: s.texture, mipLevel: mip, origin: [x, y, s.volume ? z : layer], aspect: "all" },
                [copyWidth, copyHeight, slices]);
        }

        /**
         * Depth and stencil from the guest. WebGPU copies into depth16unorm
         * and into stencil aspects only; the other depth formats get their
         * depth by a draw that writes it (frag_depth), from the guest's
         * values decoded here.
         */
        uploadDepth(s, layer, mip, x, y, w, h, data, pitch) {
            const format = s.f.gpu, bytes = s.f.bytes;
            const level = this.level(s, mip);
            w = Math.min(w, level.width - x);
            h = Math.min(h, level.height - y);
            if (w <= 0 || h <= 0) return;
            const words = new DataView(data.buffer, data.byteOffset, data.byteLength);
            const at = (row, column) => row * pitch + column * bytes;
            if (at(h - 1, w - 1) + Math.min(bytes, 4) > data.byteLength) return;
            this.endPass();
            if (format === "depth16unorm") {
                const alignedPitch = align(w * 2, 256), staged = new Uint8Array(alignedPitch * h);
                for (let row = 0; row < h; row++) staged.set(data.subarray(row * pitch, row * pitch + w * 2), row * alignedPitch);
                this.encoder().copyBufferToTexture({ buffer: this.staging(staged), bytesPerRow: alignedPitch, rowsPerImage: h },
                    { texture: s.texture, mipLevel: mip, origin: [x, y, layer], aspect: "depth-only" }, [w, h, 1]);
                return;
            }
            // where each format keeps depth and stencil (D3D9's D24S8 has
            // depth in the high bits, DXGI's D24_UNORM_S8_UINT in the low)
            const highDepth = s.format === SVGA3D_Z_D24S8 || s.format === SVGA3D_Z_D24X8 || s.format === SVGA3D_Z_DF24 ||
                s.format === SVGA3D_Z_D24S8_INT;
            const depth = new Float32Array(w * h);
            const stencil = hasStencil(format) ? new Uint8Array(align(w, 256) * h) : null;
            for (let row = 0; row < h; row++) {
                for (let column = 0; column < w; column++) {
                    const offset = at(row, column), word = words.getUint32(offset, true);
                    let value, stencilValue = 0;
                    if (format === "depth32float" || format === "depth32float-stencil8") {
                        value = s.format === SVGA3D_Z_D32 ? word / 0xFFFFFFFF : words.getFloat32(offset, true);
                        if (bytes >= 8) stencilValue = words.getUint8(offset + 4);
                    } else if (highDepth) {
                        value = (word >>> 8) / 0xFFFFFF;
                        stencilValue = word & 0xFF;
                    } else {
                        value = (word & 0xFFFFFF) / 0xFFFFFF;
                        stencilValue = word >>> 24;
                    }
                    depth[row * w + column] = Math.min(1, Math.max(0, value || 0));
                    if (stencil) stencil[row * align(w, 256) + column] = stencilValue;
                }
            }
            let pipeline = this.depthUploadPipelines.get(format);
            if (!pipeline) {
                const code = `
struct Box { x: u32, y: u32, w: u32, pad: u32 }
@group(0) @binding(0) var<storage, read> values: array<f32>;
@group(0) @binding(1) var<uniform> box: Box;
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
    return vec4<f32>(f32(i & 1u) * 2.0 - 1.0, 1.0 - f32(i >> 1u) * 2.0, 0.0, 1.0);
}
@fragment fn fs(@builtin(position) p: vec4<f32>) -> @builtin(frag_depth) f32 {
    return values[(u32(p.y) - box.y) * box.w + u32(p.x) - box.x];
}`;
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createRenderPipeline({ layout: "auto",
                    vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [] },
                    primitive: { topology: "triangle-strip" },
                    depthStencil: { format, depthWriteEnabled: true, depthCompare: "always" } });
                this.depthUploadPipelines.set(format, pipeline);
            }
            const values = this.device.createBuffer({ size: depth.byteLength, usage: BUFFER_USAGE.STORAGE, mappedAtCreation: true });
            new Float32Array(values.getMappedRange()).set(depth);
            values.unmap();
            const uniform = this.device.createBuffer({ size: 16, usage: BUFFER_USAGE.UNIFORM, mappedAtCreation: true });
            new Uint32Array(uniform.getMappedRange()).set([x, y, w, 0]);
            uniform.unmap();
            this.transient.push(values, uniform);
            const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                { binding: 0, resource: { buffer: values } }, { binding: 1, resource: { buffer: uniform } }] });
            const attachment = { view: s.texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1,
                baseArrayLayer: layer, arrayLayerCount: 1 }), depthLoadOp: "load", depthStoreOp: "store" };
            if (stencil) { attachment.stencilLoadOp = "load"; attachment.stencilStoreOp = "store"; }
            const pass = this.encoder().beginRenderPass({ colorAttachments: [], depthStencilAttachment: attachment });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, group);
            pass.setViewport(0, 0, level.width, level.height, 0, 1);
            pass.setScissorRect(x, y, w, h);
            pass.draw(4);
            pass.end();
            if (stencil) {
                this.encoder().copyBufferToTexture({ buffer: this.staging(stencil), bytesPerRow: align(w, 256), rowsPerImage: h },
                    { texture: s.texture, mipLevel: mip, origin: [x, y, layer], aspect: "stencil-only" }, [w, h, 1]);
            }
        }

        /** Guest pixels into what the texture holds: opaque alpha for "X" formats */
        convertIn(s, bytes, pitch, columns, rows) {
            const f = s.f;
            if (f.can.includes("x") && f.bytes === 4) {
                for (let row = 0; row < rows; row++) {
                    for (let c = 0; c < columns; c++) bytes[row * pitch + c * 4 + 3] = 255;
                }
            }
        }

        /**
         * A surface's rectangle to the page's screen (SURFACE_PRESENT): the
         * peer's presenter copies it on the GPU, in this encoder's order;
         * sid 0 takes it away
         */
        present(b) {
            const [sid, x, y, w, h, dx, dy, width, height] = b;
            if (!this.peer || !this.peer.present) return;
            if (!sid) return this.peer.present(null);
            const s = this.surfaces.get(sid);
            if (!s) return;
            this.primary(s, false);
            if (!s.texture || s.samples > 1 || isDepthFormat(s.f.gpu)) {
                this.warn("present" + s.format, "presenting format " + s.format + " is not supported");
                return;
            }
            this.endPass();
            this.stats.presents = (this.stats.presents || 0) + 1;
            this.peer.present({ texture: s.texture, format: s.f.gpu, x, y, w, h, dx, dy, width, height, encoder: this.encoder() });
            // (submitted now: the compositor composes in a microtask after this)
            this.flushEncoder();
        }

        readback(b) {
            const [sid, layer, mip, x, y, z, w, h, d, id] = b;
            const s = this.surfaces.get(sid);
            const fail = () => this.respond(id, null);
            if (!s) return fail();
            this.stats.readbacks++;
            this.endPass();
            if (s.buffer) {
                const start = x & ~3, stop = Math.min(s.shadow.length, align(x + w, 4));
                const target = this.device.createBuffer({ size: Math.max(4, stop - start), usage: BUFFER_USAGE.MAP_READ | BUFFER_USAGE.COPY_DST });
                this.encoder().copyBufferToBuffer(s.buffer, start, target, 0, stop - start);
                this.flushEncoder();
                this.pending.push(target.mapAsync(1).then(() => {
                    const bytes = new Uint8Array(target.getMappedRange()).slice(x - start, x - start + w);
                    target.destroy();
                    s.shadow.set(bytes, x);
                    this.respond(id, bytes);
                }, () => fail()));
                return;
            }
            this.primary(s, false);
            if (!s.texture || s.samples > 1 || isDepthFormat(s.f.gpu) && s.f.gpu !== "depth32float" && s.f.gpu !== "depth16unorm") {
                this.warn("readback" + s.format, "reading back format " + s.format + " is not supported");
                return fail();
            }
            const f = s.f;
            const columns = Math.ceil(w / f.bw), rows = Math.ceil(h / f.bh);
            const codec = f.can.includes("e") ? EMULATED[s.format] : null;
            const emulated = !!codec;
            const texels = emulated ? Math.min(w, columns * codec.texels) : w;
            const rowBytes = columns * f.bytes, gpuRow = emulated ? texels * codec.gpu : rowBytes, alignedPitch = align(gpuRow, 256);
            const slices = Math.max(1, d);
            const target = this.device.createBuffer({ size: alignedPitch * rows * slices, usage: BUFFER_USAGE.MAP_READ | BUFFER_USAGE.COPY_DST });
            this.encoder().copyTextureToBuffer(
                { texture: s.texture, mipLevel: mip, origin: [x, y, s.volume ? z : layer], aspect: isDepthFormat(f.gpu) ? "depth-only" : "all" },
                { buffer: target, bytesPerRow: alignedPitch, rowsPerImage: rows },
                [emulated ? texels : align(w, f.bw), emulated ? h : align(h, f.bh), slices]);
            this.flushEncoder();
            this.pending.push(target.mapAsync(1).then(() => {
                const mapped = new Uint8Array(target.getMappedRange());
                const out = new Uint8Array(rowBytes * rows * slices);
                for (let r = 0; r < rows * slices; r++) {
                    const row = mapped.subarray(r * alignedPitch, r * alignedPitch + gpuRow);
                    if (emulated) packRow(s.format, f.bytes, row, out.subarray(r * rowBytes, (r + 1) * rowBytes));
                    else out.set(row, r * rowBytes);
                }
                target.destroy();
                this.respond(id, out);
            }, () => fail()));
        }

        /** A readback answer: D9WGReadbackResponse (id, bytes, 0, status, then the bytes) */
        respond(id, bytes) {
            const out = new Uint8Array(16 + (bytes ? bytes.length : 0));
            const view = new DataView(out.buffer);
            view.setUint32(0, id, true);
            view.setUint32(4, bytes ? bytes.length : 0, true);
            view.setUint32(12, bytes ? RESPONSE_OK : RESPONSE_FAILED, true);
            if (bytes) out.set(bytes, 16);
            if (this.write) this.write(QUERY_REGION_BYTES, out);
        }

        clearTexture(s, color) {
            this.primary(s, true);
            for (let layer = 0; layer < (s.volume ? 1 : s.layers); layer++) {
                this.endPass();
                const pass = this.encoder().beginRenderPass({ colorAttachments: [{
                    view: s.texture.createView({ dimension: "2d", baseMipLevel: 0, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 }),
                    loadOp: "clear", storeOp: "store", clearValue: color }] });
                pass.end();
            }
        }

        copySurface(b) {
            const [src, sLayer, sMip, sx, sy, sz, dst, dLayer, dMip, dx, dy, dz, w, h, d] = b;
            const S = this.surfaces.get(src), D = this.surfaces.get(dst);
            if (!S || !D) return;
            this.endPass();
            if (S.buffer && D.buffer) return this.copyBuffer(D, dx, S, sx, w);
            if (!S.texture || !D.texture) return;
            this.copyTexture(S, sLayer, sMip, sx, sy, sz, D, dLayer, dMip, dx, dy, dz, w, h, d);
        }

        copyBuffer(D, dx, S, sx, w) {
            const count = Math.min(w, S.shadow.length - sx, D.shadow.length - dx);
            if (count <= 0) return;
            D.shadow.set(S.shadow.subarray(sx, sx + count), dx);
            this.endPass();
            if (!(sx & 3) && !(dx & 3) && !(count & 3)) {
                this.encoder().copyBufferToBuffer(S.buffer, sx, D.buffer, dx, count);
                return;
            }
            const start = dx & ~3, stop = Math.min(D.shadow.length, align(dx + count, 4));
            this.encoder().copyBufferToBuffer(this.staging(D.shadow.subarray(start, stop)), 0, D.buffer, start, stop - start);
        }

        copyTexture(S, sLayer, sMip, sx, sy, sz, D, dLayer, dMip, dx, dy, dz, w, h, d) {
            if (sMip >= S.gpuMips || dMip >= D.gpuMips) return;
            this.primary(S, false);
            this.primary(D, true);
            // (formats of one texel layout: D's alias of S's family takes the bytes)
            let sameFamily = S.f.gpu === D.f.gpu || SRGB[S.f.gpu] === D.f.gpu;
            if (!sameFamily && S.ss[0] === 1 && D.ss[0] === 1) {
                const alias = this.textureFor(D, S.f.gpu, true);
                if (alias) {
                    const sl = this.level(S, sMip), dl = this.level(D, dMip);
                    w = Math.min(w, sl.width - sx, dl.width - dx);
                    h = Math.min(h, sl.height - sy, dl.height - dy);
                    d = Math.max(1, Math.min(d, S.volume ? sl.depth - sz : 1, D.volume ? dl.depth - dz : 1));
                    if (w <= 0 || h <= 0) return;
                    this.endPass();
                    this.encoder().copyTextureToTexture(
                        { texture: S.texture, mipLevel: sMip, origin: [sx, sy, S.volume ? sz : sLayer] },
                        { texture: alias.texture, mipLevel: dMip, origin: [dx, dy, D.volume ? dz : dLayer] }, [w, h, d]);
                    return;
                }
            }
            const sl = this.level(S, sMip), dl = this.level(D, dMip);
            w = Math.min(w, sl.width - sx, dl.width - dx);
            h = Math.min(h, sl.height - sy, dl.height - dy);
            d = Math.max(1, Math.min(d, S.volume ? sl.depth - sz : 1, D.volume ? dl.depth - dz : 1));
            if (w <= 0 || h <= 0) return;
            if (!sameFamily || S.ss[0] !== D.ss[0] || S.ss[1] !== D.ss[1]) {
                // a different format: drawn, not copied
                if (S.ss[0] !== 1 || D.ss[0] !== 1) return this.warn("copy-ms", "a copy between multisampled surfaces of different formats");
                return this.blit(S, sLayer, sMip, [sx, sy, sx + w, sy + h], D, dLayer, dMip, [dx, dy, dx + w, dy + h], false);
            }
            // (multisampled: every sample of the box)
            const [kx, ky] = S.ss;
            this.endPass();
            this.encoder().copyTextureToTexture(
                { texture: S.texture, mipLevel: sMip, origin: [sx * kx, sy * ky, S.volume ? sz : sLayer] },
                { texture: D.texture, mipLevel: dMip, origin: [dx * kx, dy * ky, D.volume ? dz : dLayer] },
                [align(w, S.f.bw) * kx, align(h, S.f.bh) * ky, d]);
        }

        /**
         * Copy every image between a surface and the D9WG resource that is
         * the same surface for legacy 3D (options.peer: the D3D9 executor on
         * the same device): a copy where the formats are the same, else a
         * draw. An "X" format's alpha is 1.
         */
        share(sid, handle, toPeer) {
            const s = this.surfaces.get(sid);
            const peer = this.peer && this.peer.resource(handle);
            if (s) this.primary(s, !toPeer);
            if (!s || !s.texture || !peer || !peer.gpuTexture) {
                if (s && s.buffer) this.warn("share-buffer", "a buffer shared by DX and legacy 3D");
                else this.warn("share-missing", "a shared surface is missing on one side");
                return;
            }
            // (the D3D9 executor records draws for later: they go first)
            this.peer.flush();
            const gpu = peer.gpuFormat;
            const block = gpu.startsWith("bc") ? 4 : 1;
            const p = { texture: peer.gpuTexture, f: { gpu, can: "", bw: block, bh: block, bytes: 0 },
                width: peer.width, height: peer.height, depth: peer.depth || 1,
                volume: peer.textureType === "3d", layers: peer.layerCount || 1,
                gpuMips: peer.levelCount || 1, samples: 1 };
            if (s.samples > 1 || isDepthFormat(s.f.gpu) || isDepthFormat(gpu)) {
                this.warn("share-kind", "a multisampled or depth surface shared by DX and legacy 3D");
                return;
            }
            const [S, D] = toPeer ? [s, p] : [p, s];
            const opaque = s.f.can.includes("x");
            const sameFamily = S.f.gpu === D.f.gpu || SRGB[S.f.gpu] === D.f.gpu || SRGB[D.f.gpu] === S.f.gpu;
            const mips = Math.min(S.gpuMips, D.gpuMips);
            const layers = S.volume || D.volume ? 1 : Math.min(S.layers, D.layers);
            this.endPass();
            for (let mip = 0; mip < mips; mip++) {
                const sl = this.level(S, mip), dl = this.level(D, mip);
                const w = Math.min(sl.width, dl.width), h = Math.min(sl.height, dl.height);
                for (let layer = 0; layer < layers; layer++) {
                    if (sameFamily && !opaque) {
                        this.encoder().copyTextureToTexture(
                            { texture: S.texture, mipLevel: mip, origin: [0, 0, S.volume ? 0 : layer] },
                            { texture: D.texture, mipLevel: mip, origin: [0, 0, D.volume ? 0 : layer] },
                            [align(w, block), align(h, block), S.volume && D.volume ? Math.min(sl.depth, dl.depth) : 1]);
                    } else if (S.volume || D.volume || block > 1) {
                        this.warn("share-format:" + S.f.gpu + ":" + D.f.gpu, "a shared surface's formats differ: " +
                            S.f.gpu + " and " + D.f.gpu);
                        return;
                    } else {
                        this.blit(S, layer, mip, [0, 0, w, h], D, layer, mip, [0, 0, w, h], false, opaque);
                    }
                    // (D9WG warns about levels nothing has written: these are written)
                    if (toPeer && peer.uploadedLevels) peer.uploadedLevels.add(peer.layerCount === 6 ? mip * 6 + layer : mip);
                }
            }
        }

        stretch(b) {
            const [src, sLayer, sMip, sl, st, sr, sb, dst, dLayer, dMip, dl, dt, dr, db, linear] = b;
            const S = this.surfaces.get(src), D = this.surfaces.get(dst);
            if (!S || !D || !S.texture || !D.texture) return;
            this.blit(S, sLayer, sMip, [sl, st, sr, sb], D, dLayer, dMip, [dl, dt, dr, db], !!linear);
        }

        /**
         * Draw a rectangle of a texture into one of another, scaled
         */
        blit(S, sLayer, sMip, [sl, st, sr, sb], D, dLayer, dMip, [dl, dt, dr, db], linear, opaque) {
            this.primary(S, false);
            this.primary(D, true);
            const format = D.f.gpu;
            if (isDepthFormat(format) || isDepthFormat(S.f.gpu)) return this.warn("blit-depth", "blits of depth surfaces are not supported");
            const kind = sampleKind(S.f.gpu);
            const key = format + ":" + kind + (opaque ? ":opaque" : "");
            let pipeline = this.blitPipelines.get(key);
            if (!pipeline) {
                const type = kind === "sint" ? "i32" : kind === "uint" ? "u32" : "f32";
                const outType = sampleKind(format) === "sint" ? "i32" : sampleKind(format) === "uint" ? "u32" : "f32";
                const code = `
struct Box { src: vec4<f32>, size: vec4<f32> }
@group(0) @binding(0) var t: texture_2d<${type}>;
@group(0) @binding(1) var s: sampler;
@group(0) @binding(2) var<uniform> box: Box;
struct Out { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> }
@vertex fn vs(@builtin(vertex_index) i: u32) -> Out {
    let corner = vec2<f32>(f32(i & 1u), f32(i >> 1u));
    var out: Out;
    out.position = vec4<f32>(corner.x * 2.0 - 1.0, 1.0 - corner.y * 2.0, 0.0, 1.0);
    out.uv = box.src.xy + corner * (box.src.zw - box.src.xy);
    return out;
}
@fragment fn fs(input: Out) -> @location(0) vec4<${outType}> {
    ${type === "f32" ? `let c = textureSampleLevel(t, s, input.uv / box.size.xy, 0.0);` :
        `let c = textureLoad(t, vec2<i32>(input.uv), 0);`}
    return vec4<${outType}>(${opaque ? `vec4<${type}>(c.rgb, ${type === "f32" ? "1.0" : "1"})` : "c"});
}`;
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createRenderPipeline({ layout: "auto",
                    vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [{ format }] },
                    primitive: { topology: "triangle-strip" } });
                this.blitPipelines.set(key, pipeline);
            }
            const sLevel = this.level(S, sMip), dLevel = this.level(D, dMip);
            dl = Math.max(0, dl); dt = Math.max(0, dt); dr = Math.min(dr, dLevel.width); db = Math.min(db, dLevel.height);
            if (dr <= dl || db <= dt) return;
            const uniform = this.device.createBuffer({ size: 32, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
            this.device.queue.writeBuffer(uniform, 0, new Float32Array([sl, st, sr, sb, sLevel.width, sLevel.height, 0, 0]));
            this.transient.push(uniform);
            const view = S.texture.createView({ dimension: "2d", baseMipLevel: sMip, mipLevelCount: 1,
                baseArrayLayer: S.volume ? 0 : sLayer, arrayLayerCount: 1 });
            const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                { binding: 0, resource: view },
                { binding: 1, resource: linear && kind === "float" ? this.linearSampler : this.nearestSampler },
                { binding: 2, resource: { buffer: uniform } }] });
            this.endPass();
            const pass = this.encoder().beginRenderPass({ colorAttachments: [{
                view: D.texture.createView({ dimension: "2d", baseMipLevel: dMip, mipLevelCount: 1, baseArrayLayer: D.volume ? 0 : dLayer, arrayLayerCount: 1 }),
                loadOp: "load", storeOp: "store" }] });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, group);
            pass.setViewport(dl, dt, dr - dl, db - dt, 0, 1);
            pass.setScissorRect(dl, dt, dr - dl, db - dt);
            pass.draw(4);
            pass.end();
        }

        // ------------------------------------------------------------------
        // Shaders

        shaderCode(b) {
            const [cid, shid, type] = b;
            const c = this.contexts.get(cid);
            if (!c) return;
            const tokens = new Uint32Array(b.buffer.slice(b.byteOffset + 12, b.byteOffset + b.byteLength));
            let program = null;
            try {
                program = IR.decode(tokens);
            } catch (error) {
                this.warn("decode:" + error.message, "shader " + shid + " does not decode: " + error.message);
            }
            const old = c.shaders.get(shid);
            c.shaders.set(shid, { type, program, generation: (old ? old.generation : 0) + 1, id: ++this.stats.shaders });
        }

        /** A shader module for a shader in an interface, translated the first time */
        module(shader, options) {
            const key = shader.id + ":" + JSON.stringify(options);
            let entry = this.modules.get(key);
            if (entry) return entry;
            const result = WGSL.emit(shader.program, options);
            for (const warning of result.warnings) this.warn("wgsl:" + warning, "shader: " + warning);
            const module = this.device.createShaderModule({ code: result.code });
            if (typeof module.getCompilationInfo === "function") {
                module.getCompilationInfo().then(info => {
                    for (const m of info.messages) {
                        if (m.type === "error") {
                            this.warn("compile:" + key, "WGSL error: " + m.message + " at line " + m.lineNum + "\n" + result.code);
                        }
                    }
                });
            }
            entry = { module, result, key };
            this.modules.set(key, entry);
            return entry;
        }

        // ------------------------------------------------------------------
        // DX commands

        dx(cid, id, p) {
            const c = this.contexts.get(cid);
            if (!c) return this.warn("cid" + cid, "a DX command for an unknown context");
            const st = c.state;
            const words = n => p.subarray(n);
            switch (id) {
                // definitions
                case DX.DEFINE_RENDERTARGET_VIEW:
                    c.rtvs.set(p[0], { sid: p[1], format: p[2], dimension: p[3], mip: p[4], first: p[5], count: p[6] });
                    return;
                case DX.DEFINE_DEPTHSTENCIL_VIEW:
                case DX.DEFINE_DEPTHSTENCIL_VIEW_V2:
                    c.dsvs.set(p[0], { sid: p[1], format: p[2], dimension: p[3], mip: p[4], first: p[5], count: p[6], flags: p[7] & 0xFF });
                    return;
                case DX.DEFINE_SHADERRESOURCE_VIEW:
                    c.srvs.set(p[0], { sid: p[1], format: p[2], dimension: p[3], desc: Array.from(p.subarray(4, 8)) });
                    return;
                case DX.DEFINE_UA_VIEW:
                    c.uavs.set(p[0], { sid: p[1], format: p[2], dimension: p[3], desc: Array.from(p.subarray(4, 9)) });
                    return;
                case DX.DEFINE_ELEMENTLAYOUT: {
                    const elements = [];
                    for (let at = 1; at + 6 <= p.length; at += 6) {
                        elements.push({ slot: p[at], offset: p[at + 1], format: p[at + 2], instanced: p[at + 3] === 1,
                            rate: p[at + 4], register: p[at + 5] });
                    }
                    c.layouts.set(p[0], { elements, generation: ++c.generation });
                    return;
                }
                case DX.DEFINE_BLEND_STATE: c.blends.set(p[0], { words: Array.from(p.subarray(1, 26)), generation: ++c.generation }); return;
                case DX.DEFINE_DEPTHSTENCIL_STATE: c.depths.set(p[0], { words: Array.from(p.subarray(1, 5)), generation: ++c.generation }); return;
                case DX.DEFINE_RASTERIZER_STATE:
                case DX.DEFINE_RASTERIZER_STATE_V2:
                    c.rasters.set(p[0], { words: Array.from(p.subarray(1, 8)), generation: ++c.generation });
                    return;
                case DX.DEFINE_SAMPLER_STATE: c.samplers.set(p[0], { words: Array.from(p.subarray(1, 11)), sampler: null }); return;
                case DX.DEFINE_SHADER: c.shaders.set(p[0], { type: p[1], program: null, generation: 0, id: ++this.stats.shaders }); return;
                case DX.DEFINE_QUERY: c.queries.set(p[0], { type: p[1], indices: [] }); return;
                case DX.DEFINE_STREAMOUTPUT: {
                    // soid, entries, 64 SVGA3dStreamOutputDeclarationEntry, 4 strides, the rasterized stream
                    const entries = [];
                    for (let i = 0; i < Math.min(p[1], 64); i++) entries.push(soEntry(p, 2 + 4 * i));
                    c.streamOutputs.set(p[0], { entries, strides: Array.from(p.subarray(258, 262)), rasterized: p[262] | 0 });
                    return;
                }
                case DX.DEFINE_STREAMOUTPUT_WITH_MOB:
                    // soid, entries, strides used, 4 strides, the rasterized stream; the entries come with BIND
                    c.streamOutputs.set(p[0], { entries: [], count: p[1], strides: Array.from(p.subarray(3, 7)), rasterized: p[7] | 0 });
                    return;
                case DX.BIND_STREAMOUTPUT: {
                    // soid, mob, offset, size, then the entries (svga3d_dx.js reads them from the MOB)
                    const so = c.streamOutputs.get(p[0]);
                    if (!so) return;
                    so.entries = [];
                    for (let at = 4; at + 4 <= p.length && so.entries.length < (so.count || 64); at += 4) so.entries.push(soEntry(p, at));
                    return;
                }
                case DX.DESTROY_STREAMOUTPUT: c.streamOutputs.delete(p[0]); return;
                case DX.SET_STREAMOUTPUT: st.soid = p[0]; return;
                case DX.DESTROY_RENDERTARGET_VIEW: c.rtvs.delete(p[0]); return;
                case DX.DESTROY_DEPTHSTENCIL_VIEW: c.dsvs.delete(p[0]); return;
                case DX.DESTROY_SHADERRESOURCE_VIEW: c.srvs.delete(p[0]); return;
                case DX.DESTROY_UA_VIEW: c.uavs.delete(p[0]); return;
                case DX.DESTROY_ELEMENTLAYOUT: c.layouts.delete(p[0]); return;
                case DX.DESTROY_BLEND_STATE: c.blends.delete(p[0]); return;
                case DX.DESTROY_DEPTHSTENCIL_STATE: c.depths.delete(p[0]); return;
                case DX.DESTROY_RASTERIZER_STATE: c.rasters.delete(p[0]); return;
                case DX.DESTROY_SAMPLER_STATE: c.samplers.delete(p[0]); return;
                case DX.DESTROY_SHADER: c.shaders.delete(p[0]); return;
                case DX.DESTROY_QUERY: c.queries.delete(p[0]); return;

                // state
                case DX.SET_SINGLE_CONSTANT_BUFFER: {
                    const stage = c.stage(p[1]);
                    if (stage && p[0] < 16) stage.cbs[p[0]] = { sid: p[2], offset: p[3], size: p[4] };
                    return;
                }
                case DX.SET_SHADER_RESOURCES: {
                    const stage = c.stage(p[1]);
                    if (!stage) return;
                    for (let i = 2; i < p.length && p[0] + i - 2 < 128; i++) stage.srvs[p[0] + i - 2] = p[i];
                    return;
                }
                case DX.SET_SAMPLERS: {
                    const stage = c.stage(p[1]);
                    if (!stage) return;
                    for (let i = 2; i < p.length && p[0] + i - 2 < 16; i++) stage.samplers[p[0] + i - 2] = p[i];
                    return;
                }
                case DX.SET_SHADER: {
                    const stage = c.stage(p[1]);
                    if (stage) stage.shader = p[0];
                    return;
                }
                case DX.SET_INPUT_LAYOUT: st.layout = p[0]; return;
                case DX.SET_VERTEX_BUFFERS:
                case DX.SET_VERTEX_BUFFERS_V2: {
                    const each = id === DX.SET_VERTEX_BUFFERS ? 3 : 4;
                    for (let i = 0; 1 + each * (i + 1) <= p.length && p[0] + i < 32; i++) {
                        const at = 1 + each * i;
                        st.vbs[p[0] + i] = { sid: p[at], stride: p[at + 1], offset: p[at + 2] };
                    }
                    return;
                }
                case DX.SET_VERTEX_BUFFERS_OFFSET_AND_SIZE:
                    for (let i = 0; 1 + 3 * (i + 1) <= p.length && p[0] + i < 32; i++) {
                        const at = 1 + 3 * i, vb = st.vbs[p[0] + i];
                        st.vbs[p[0] + i] = { sid: vb ? vb.sid : INVALID, stride: p[at], offset: p[at + 1] };
                    }
                    return;
                case DX.SET_INDEX_BUFFER:
                case DX.SET_INDEX_BUFFER_V2:
                    st.ib = { sid: p[0], format: p[1], offset: p[2] };
                    return;
                case DX.SET_INDEX_BUFFER_OFFSET_AND_SIZE:
                    st.ib = { sid: st.ib.sid, format: p[0], offset: p[1] };
                    return;
                case DX.SET_TOPOLOGY: st.topology = p[0]; return;
                case DX.SET_RENDERTARGETS:
                    st.dsv = p[0];
                    st.rtvs = Array.from(p.subarray(1, Math.min(p.length, 9)));
                    return;
                case DX.SET_BLEND_STATE:
                    st.blend = p[0];
                    st.blendFactor = [f32(p[1]), f32(p[2]), f32(p[3]), f32(p[4])];
                    st.sampleMask = p[5];
                    return;
                case DX.SET_DEPTHSTENCIL_STATE: st.depth = p[0]; st.stencilRef = p[1]; return;
                case DX.SET_RASTERIZER_STATE: st.raster = p[0]; return;
                case DX.SET_VIEWPORTS:
                    st.viewports = [];
                    for (let at = 1; at + 6 <= p.length; at += 6) st.viewports.push(Array.from(p.subarray(at, at + 6), f32));
                    return;
                case DX.SET_SCISSORRECTS:
                    st.scissors = [];
                    for (let at = 1; at + 4 <= p.length; at += 4) st.scissors.push(Array.from(p.subarray(at, at + 4), v => v | 0));
                    return;
                case DX.SET_PREDICATION: st.predication = [p[0], p[1]]; return;
                case DX.SET_SOTARGETS:
                    // (pad), then sid, offset, size each; an offset of ~0 appends to what the buffer has
                    st.soTargets = [];
                    for (let at = 1; at + 3 <= p.length && st.soTargets.length < 4; at += 3) {
                        const target = { sid: p[at], offset: p[at + 1], size: p[at + 2] };
                        st.soTargets.push(target);
                        const S = target.sid !== INVALID ? this.surfaces.get(target.sid) : null;
                        if (S && S.buffer && target.offset !== INVALID) this.device.queue.writeBuffer(this.soFilled(S), 0, Uint32Array.of(target.offset));
                    }
                    return;
                case DX.SET_UA_VIEWS: {
                    // splice index (where the targets end: the shaders' first
                    // UAV register), then the views from that register on
                    const splice = Math.min(p[0], 64);
                    for (let i = 0; i < 64; i++) st.uavs[i] = i >= splice && i - splice + 1 < p.length ? p[i - splice + 1] : INVALID;
                    return;
                }
                case DX.SET_CS_UA_VIEWS:
                    for (let i = 0; i + 1 < p.length && p[0] + i < 64; i++) st.csUavs[p[0] + i] = p[i + 1];
                    return;
                case DX.SET_STRUCTURE_COUNT:
                    // (~0: keep it)
                    if (p[1] !== INVALID) this.copyIn(this.uavCounter(c, p[0]), 0, Uint32Array.of(p[1]));
                    return;
                case DX.COPY_STRUCTURE_COUNT: {
                    const D = this.surfaces.get(p[1]);
                    if (!D || !D.buffer || p[2] + 4 > D.shadow.length || p[2] & 3) return;
                    this.endPass();
                    this.encoder().copyBufferToBuffer(this.uavCounter(c, p[0]), 0, D.buffer, p[2], 4);
                    return;
                }
                case DX.SET_MIN_LOD:
                    return;
            }
            if (id >= DX.SET_VS_CONSTANT_BUFFER_OFFSET && id <= DX.SET_CS_CONSTANT_BUFFER_OFFSET) {
                const stage = c.stage(SHADER_VS + id - DX.SET_VS_CONSTANT_BUFFER_OFFSET);
                if (stage && p[0] < 16 && stage.cbs[p[0]]) stage.cbs[p[0]] = { ...stage.cbs[p[0]], offset: p[1] };
                return;
            }
            switch (id) {
                case DX.DRAW: return this.draw(c, { count: p[0], first: p[1], instances: 1, firstInstance: 0 });
                case DX.DRAW_INDEXED: return this.draw(c, { indexed: true, count: p[0], first: p[1], base: p[2] | 0, instances: 1, firstInstance: 0 });
                case DX.DRAW_INSTANCED: return this.draw(c, { count: p[0], instances: p[1], first: p[2], firstInstance: p[3] });
                case DX.DRAW_INDEXED_INSTANCED:
                    return this.draw(c, { indexed: true, count: p[0], instances: p[1], first: p[2], base: p[3] | 0, firstInstance: p[4] });
                case DX.DRAW_INSTANCED_INDIRECT:
                case DX.DRAW_INDEXED_INSTANCED_INDIRECT:
                    return this.draw(c, { indexed: id === DX.DRAW_INDEXED_INSTANCED_INDIRECT, indirect: { sid: p[0], offset: p[1] } });
                case DX.DRAW_AUTO:
                    return this.drawAuto(c);
                case DX.DISPATCH:
                    return this.dispatchCompute(c, [p[0], p[1], p[2]], null);
                case DX.DISPATCH_INDIRECT:
                    return this.dispatchCompute(c, null, { sid: p[0], offset: p[1] });
                case DX.CLEAR_RENDERTARGET_VIEW: return this.clearRTV(c, p[0], [f32(p[1]), f32(p[2]), f32(p[3]), f32(p[4])]);
                case DX.CLEAR_DEPTHSTENCIL_VIEW: return this.clearDSV(c, p[1], p[0] & 0xFFFF, p[0] >>> 16, f32(p[2]));
                case DX.CLEAR_UA_VIEW_UINT:
                case DX.CLEAR_UA_VIEW_FLOAT:
                    return this.clearUAV(c, p[0], Array.from(p.subarray(1, 5)), id === DX.CLEAR_UA_VIEW_FLOAT);
                case DX.PRED_COPY_REGION:
                case DX.PRED_STAGING_COPY_REGION:
                    return this.copyRegion(p[0], p[1], p[2], p[3], Array.from(p.subarray(4, 13)));
                case DX.PRED_COPY:
                case DX.PRED_STAGING_COPY:
                case DX.STAGING_COPY:
                    return this.copyWhole(p[0], p[1]);
                case DX.SURFACE_COPY_AND_READBACK:
                    return this.copyRegion(p[1], 0, p[0], 0, Array.from(p.subarray(2, 11)));
                case DX.BUFFER_COPY:
                case DX.STAGING_BUFFER_COPY: {
                    const D = this.surfaces.get(p[0]), S = this.surfaces.get(p[1]);
                    if (D && S && D.buffer && S.buffer) this.copyBuffer(D, p[2], S, p[3], p[4]);
                    return;
                }
                case DX.TRANSFER_FROM_BUFFER:
                case DX.PRED_TRANSFER_FROM_BUFFER:
                    return this.transferFromBuffer(p);
                case DX.PRESENTBLT: {
                    // src, srcSub, dst, dstSub, boxSrc (x, y, z, w, h, d), boxDest, mode
                    const S = this.surfaces.get(p[0]), D = this.surfaces.get(p[2]);
                    if (!S || !D || !S.texture || !D.texture) return;
                    const [sMip, sLayer] = subresource(S, p[1]), [dMip, dLayer] = subresource(D, p[3]);
                    this.blit(S, sLayer, sMip, [p[4], p[5], p[4] + p[7], p[5] + p[8]], D, dLayer, dMip,
                        [p[10], p[11], p[10] + p[13], p[11] + p[14]], !!(p[16] & 1));
                    return;
                }
                case DX.RESOLVE_COPY:
                case DX.PRED_RESOLVE_COPY:
                    return this.resolve(p[0], p[1], p[2], p[3]);
                case DX.PRED_CONVERT_REGION:
                case DX.PRED_STAGING_CONVERT_REGION: {
                    const D = this.surfaces.get(p[0]), S = this.surfaces.get(p[8]);
                    if (!S || !D || !S.texture || !D.texture) return;
                    const [sMip, sLayer] = subresource(S, p[9]), [dMip, dLayer] = subresource(D, p[1]);
                    this.blit(S, sLayer, sMip, [p[10], p[11], p[10] + p[13], p[11] + p[14]], D, dLayer, dMip,
                        [p[2], p[3], p[2] + p[5], p[3] + p[6]], false);
                    return;
                }
                case DX.PRED_CONVERT:
                case DX.PRED_STAGING_CONVERT:
                    return this.copyWhole(p[0], p[1]);
                case DX.GENMIPS: return this.genmips(c, p[0]);
                case DX.BEGIN_QUERY: return this.beginQuery(c, p[0]);
                case DX.TRANSFER_TO_BUFFER:
                    return this.warn("transfer-to-buffer", "TRANSFER_TO_BUFFER is not supported yet");
            }
            this.warn("dx" + id, "DX command " + id + " is not supported");
        }

        copyRegion(dst, dstSub, src, srcSub, box) {
            const D = this.surfaces.get(dst), S = this.surfaces.get(src);
            if (!D || !S) return;
            const [x, y, z, w, h, d, sx, sy, sz] = box;
            if (S.buffer && D.buffer) return this.copyBuffer(D, x, S, sx, w);
            if (!S.texture || !D.texture) return;
            const [sMip, sLayer] = subresource(S, srcSub), [dMip, dLayer] = subresource(D, dstSub);
            this.copyTexture(S, sLayer, sMip, sx, sy, sz, D, dLayer, dMip, x, y, z, w, h, d);
        }

        copyWhole(dst, src) {
            const D = this.surfaces.get(dst), S = this.surfaces.get(src);
            if (!D || !S) return;
            if (S.buffer && D.buffer) return this.copyBuffer(D, 0, S, 0, Math.min(S.shadow.length, D.shadow.length));
            if (!S.texture || !D.texture) return;
            for (let layer = 0; layer < Math.min(S.layers, D.layers); layer++) {
                for (let mip = 0; mip < Math.min(S.gpuMips, D.gpuMips); mip++) {
                    const l = this.level(S, mip);
                    this.copyTexture(S, layer, mip, 0, 0, 0, D, layer, mip, 0, 0, 0, l.width, l.height, l.depth);
                }
            }
        }

        transferFromBuffer(p) {
            // srcSid, srcOffset, srcPitch, srcSlicePitch, destSid, destSubResource, destBox (x, y, z, w, h, d)
            const S = this.surfaces.get(p[0]), D = this.surfaces.get(p[4]);
            if (!S || !D || !S.buffer || !D.texture) return;
            const [mip, layer] = subresource(D, p[5]);
            const [x, y, z, w, h, d] = Array.from(p.subarray(6, 12));
            const f = D.f, rows = Math.ceil(h / f.bh), slices = Math.max(1, d);
            const bytes = new Uint8Array(p[2] * rows * slices);
            for (let slice = 0; slice < slices; slice++) {
                for (let row = 0; row < rows; row++) {
                    const from = p[1] + slice * p[3] + row * p[2];
                    bytes.set(S.shadow.subarray(from, from + p[2]), (slice * rows + row) * p[2]);
                }
            }
            const words = new Uint32Array(11 + align(bytes.length, 4) / 4);
            words.set([p[4], layer, mip, x, y, z, w, h, d, p[2], p[2] * rows]);
            new Uint8Array(words.buffer, 44).set(bytes);
            this.upload(words);
        }

        /** A multisampled (supersampled) surface into one that is not: each pixel the mean of its samples */
        resolve(dst, dstSub, src, srcSub) {
            const D = this.surfaces.get(dst), S = this.surfaces.get(src);
            if (!D || !S || !D.texture || !S.texture || S.ss[0] <= 1 || D.ss[0] !== 1) return;
            this.primary(S, false);
            this.primary(D, true);
            const [dMip, dLayer] = subresource(D, dstSub);
            const sLayer = Math.min(srcSub, S.layers - 1);
            const format = D.f.gpu, kind = sampleKind(S.f.gpu);
            if (isDepthFormat(format) || isDepthFormat(S.f.gpu)) return this.warn("resolve-depth", "depth surfaces are not resolved");
            const [kx, ky] = S.ss;
            const key = "resolve:" + format + ":" + kind + ":" + kx + "x" + ky;
            let pipeline = this.blitPipelines.get(key);
            if (!pipeline) {
                const type = kind === "sint" ? "i32" : kind === "uint" ? "u32" : "f32";
                const outType = sampleKind(format) === "sint" ? "i32" : sampleKind(format) === "uint" ? "u32" : "f32";
                // (integers are not resolved in D3D: sample 0)
                const texels = [];
                for (let y = 0; y < ky; y++) for (let x = 0; x < kx; x++) texels.push(`textureLoad(t, at + vec2<i32>(${x}, ${y}), 0)`);
                const value = type === "f32" ? `(${texels.join(" + ")}) * ${1 / (kx * ky)}` : "textureLoad(t, at, 0)";
                const code = `
@group(0) @binding(0) var t: texture_2d<${type}>;
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
    return vec4<f32>(f32(i & 1u) * 2.0 - 1.0, 1.0 - f32(i >> 1u) * 2.0, 0.0, 1.0);
}
@fragment fn fs(@builtin(position) p: vec4<f32>) -> @location(0) vec4<${outType}> {
    let at = vec2<i32>(p.xy) * vec2<i32>(${kx}, ${ky});
    return vec4<${outType}>(${value});
}`;
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createRenderPipeline({ layout: "auto",
                    vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [{ format }] },
                    primitive: { topology: "triangle-strip" } });
                this.blitPipelines.set(key, pipeline);
            }
            const view = S.texture.createView({ dimension: "2d", baseArrayLayer: sLayer, arrayLayerCount: 1 });
            const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: view }] });
            const level = this.level(D, dMip);
            this.endPass();
            const pass = this.encoder().beginRenderPass({ colorAttachments: [{
                view: D.texture.createView({ dimension: "2d", baseMipLevel: dMip, mipLevelCount: 1, baseArrayLayer: dLayer, arrayLayerCount: 1 }),
                loadOp: "load", storeOp: "store" }] });
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, group);
            pass.setScissorRect(0, 0, Math.min(level.width, S.width), Math.min(level.height, S.height));
            pass.draw(4);
            pass.end();
        }

        genmips(c, srvId) {
            const srv = c.srvs.get(srvId);
            const S = srv && this.surfaces.get(srv.sid);
            if (!S || !S.texture || S.volume) return;
            for (let layer = 0; layer < S.layers; layer++) {
                for (let mip = 1; mip < S.gpuMips; mip++) {
                    const from = this.level(S, mip - 1), to = this.level(S, mip);
                    this.blit(S, layer, mip - 1, [0, 0, from.width, from.height], S, layer, mip, [0, 0, to.width, to.height], true);
                }
            }
        }

        clearRTV(c, id, color) {
            const view = c.rtvs.get(id);
            const S = view && this.surfaces.get(view.sid);
            if (!S || !S.texture) return;
            const f = this.formatOf(view.format) || S.f;
            if (f.can.includes("x")) color = [color[0], color[1], color[2], 1];
            const kind = sampleKind(f.gpu || S.f.gpu);
            this.endPass();
            const pass = this.encoder().beginRenderPass({ colorAttachments: [{
                view: this.attachmentView(S, view, f.gpu || S.f.gpu),
                loadOp: "clear", storeOp: "store",
                // (integers: Mesa's svga sends a UINT target's values as
                // its signed ints, (float)(int), -16 for 0xFFFFFFF0: those
                // wrap; the rest saturate, as D3D's conversion)
                clearValue: kind === "float" ? color : color.map(v => {
                    v = Math.trunc(v);
                    if (kind === "uint") return v < 0 ? (Math.max(v, -0x80000000) | 0) >>> 0 : Math.min(v, 0xFFFFFFFF);
                    return Math.max(-0x80000000, Math.min(0x7FFFFFFF, v));
                }) }] });
            pass.end();
        }

        clearDSV(c, id, flags, stencil, depth) {
            const view = c.dsvs.get(id);
            const S = view && this.surfaces.get(view.sid);
            if (!S || !S.texture) return;
            const format = S.f.gpu;
            this.endPass();
            const attachment = { view: this.attachmentView(S, view, format) };
            if (!format.startsWith("stencil")) {
                attachment.depthLoadOp = flags & 1 ? "clear" : "load";
                attachment.depthStoreOp = "store";
                attachment.depthClearValue = Math.min(1, Math.max(0, depth));
            }
            if (hasStencil(format)) {
                attachment.stencilLoadOp = flags & 2 ? "clear" : "load";
                attachment.stencilStoreOp = "store";
                attachment.stencilClearValue = stencil & 0xFF;
            }
            const pass = this.encoder().beginRenderPass({ colorAttachments: [], depthStencilAttachment: attachment });
            pass.end();
        }

        /** A view of one mip level and layer, to render into */
        attachmentView(S, view, format) {
            const layer = S.volume ? 0 : Math.min(view.first, S.layers - 1);
            // (drawn into: the format's texture is current from here on)
            const T = this.textureFor(S, format, true) || S;
            if (T === S && format !== S.f.gpu && SRGB[S.f.gpu] !== format) format = S.f.gpu;
            const key = "a:" + format + ":" + view.mip + ":" + layer;
            let v = T.views.get(key);
            if (!v) {
                v = T.texture.createView({ format, dimension: "2d", baseMipLevel: Math.min(view.mip, S.gpuMips - 1), mipLevelCount: 1,
                    baseArrayLayer: layer, arrayLayerCount: 1 });
                T.views.set(key, v);
            }
            return v;
        }

        // ------------------------------------------------------------------
        // Queries

        beginQuery(c, qid) {
            const q = c.queries.get(qid);
            if (!q) return;
            if (SO_QUERIES.has(q.type)) {
                // stream output statistics and overflow: counted by the
                // stream output passes, from here on
                if (q.soBegin) q.soBegin.destroy();
                q.soBegin = this.soSnapshot();
                return;
            }
            if (q.type === 0 || q.type === 4 || q.type === 7) {
                // occlusion: counted in the render passes from here on
                this.endPass();
                q.indices = [];
                this.activeOcclusion.set(q, true);
            }
        }

        endQuery(b) {
            const [cid, qid, type, id] = b;
            const c = this.contexts.get(cid);
            const q = c && c.queries.get(qid);
            const answer = (value64) => {
                const bytes = new Uint8Array(88);
                const view = new DataView(bytes.buffer);
                view.setUint32(0, value64 >>> 0, true);
                view.setUint32(4, Math.floor(value64 / 0x100000000), true);
                if (type === 2) {
                    // timestamp disjoint: frequency 1 GHz, not disjoint
                    view.setUint32(0, 1000000000, true);
                    view.setUint32(4, 0, true);
                    view.setUint32(8, 0, true);
                }
                if (type === 4) view.setUint32(0, value64 ? 1 : 0, true);
                this.respond(id, bytes);
            };
            if (q && SO_QUERIES.has(type)) {
                // (written, needed: SVGA3dQueryResult's soStats; an overflow predicate: whether any)
                const begin = q.soBegin || null, end = this.soSnapshot();
                q.soBegin = null;
                this.flushEncoder();
                const read = buffer => buffer ? buffer.mapAsync(1).then(() => { const v = new Uint32Array(buffer.getMappedRange().slice(0)); buffer.destroy(); return v; }) :
                    Promise.resolve(new Uint32Array(4));
                this.pending.push(Promise.all([read(begin), read(end)]).then(([a, b]) => {
                    const bytes = new Uint8Array(88);
                    const view = new DataView(bytes.buffer);
                    if (type === 6 || type >= 12) view.setUint32(0, b[2] !== a[2] ? 1 : 0, true);
                    else {
                        view.setUint32(0, (b[0] - a[0]) >>> 0, true);
                        view.setUint32(8, (b[1] - a[1]) >>> 0, true);
                    }
                    this.respond(id, bytes);
                }, () => answer(0)));
                return;
            }
            if (!q || !(type === 0 || type === 4 || type === 7)) {
                answer(type === 1 ? Math.floor(performance.now() * 1e6) : 0);
                return;
            }
            this.endPass();
            this.activeOcclusion.delete(q);
            const indices = q.indices;
            if (!indices.length || !this.occlusion) return answer(0);
            const target = this.device.createBuffer({ size: indices.length * 8, usage: BUFFER_USAGE.MAP_READ | BUFFER_USAGE.COPY_DST });
            const resolved = this.device.createBuffer({ size: indices.length * 8, usage: BUFFER_USAGE.QUERY_RESOLVE | BUFFER_USAGE.COPY_SRC });
            const encoder = this.encoder();
            indices.forEach((index, i) => encoder.resolveQuerySet(this.occlusion.set, index, 1, resolved, i * 8));
            encoder.copyBufferToBuffer(resolved, 0, target, 0, indices.length * 8);
            this.transient.push(resolved);
            this.flushEncoder();
            this.pending.push(target.mapAsync(1).then(() => {
                const values = new BigUint64Array(target.getMappedRange());
                let sum = 0;
                for (const v of values) sum += Number(v);
                target.destroy();
                answer(sum);
            }, () => answer(0)));
        }

        // ------------------------------------------------------------------
        // Drawing

        /** The render and depth targets of a draw (null: none) */
        attachments(c) {
            const st = c.state;
            const colors = [];
            let width = 0, height = 0, samples = 1;
            const targets = {};
            for (let i = 0; i < st.rtvs.length; i++) {
                const view = c.rtvs.get(st.rtvs[i]);
                const S = view && this.surfaces.get(view.sid);
                if (!S || !S.texture) { colors.push(null); continue; }
                const f = this.formatOf(view.format) || S.f;
                const format = f.gpu || S.f.gpu;
                const level = this.level(S, view.mip);
                width = level.width * S.ss[0]; height = level.height * S.ss[1]; samples = S.ss[0] * S.ss[1];
                colors.push({ S, view, format, x: f.can.includes("x") });
                const kind = sampleKind(format);
                targets[i] = kind === "sint" ? "i32" : kind === "uint" ? "u32" : "f32";
            }
            const dsView = c.dsvs.get(st.dsv);
            const DS = dsView && this.surfaces.get(dsView.sid);
            let depthFormat = null;
            if (DS && DS.texture) {
                depthFormat = DS.f.gpu;
                const level = this.level(DS, dsView.mip);
                if (!width) { width = level.width * DS.ss[0]; height = level.height * DS.ss[1]; samples = DS.ss[0] * DS.ss[1]; }
            }
            if (!width) return this.noAttachments(c);
            // (width, height: the textures'; ss: their scale, of supersampled multisampling)
            return { colors, targets, width, height, samples, ss: samples > 4 ? [4, 2] : samples > 1 ? [2, 2] : [1, 1], DS, dsView, depthFormat };
        }

        /**
         * A draw without targets whose pixel shader writes UAVs (or GL's
         * framebuffers without attachments): WebGPU passes need one, so a
         * scratch one of the viewport's size, never written (write mask 0)
         */
        noAttachments(c) {
            const st = c.state;
            const ps = c.shaders.get(c.stages[SHADER_PS].shader);
            if (!ps || !ps.program || !ps.program.uavs.size) return null;
            const v = st.viewports[0] || [0, 0, 1, 1];
            const width = Math.max(1, Math.min(16384, Math.ceil(v[0] + v[2]))), height = Math.max(1, Math.min(16384, Math.ceil(v[1] + v[3])));
            const key = width + "x" + height;
            this.scratchTargets = this.scratchTargets || new Map();
            let S = this.scratchTargets.get(key);
            if (!S) {
                // (f: what a surface of R8G8B8A8_UNORM has, which attachmentView's textureFor reads)
                const f = this.formatOf(SVGA3D_R8G8B8A8_UNORM);
                const texture = this.device.createTexture({ size: [width, height, 1], format: f.gpu, usage: TEXTURE_USAGE.RENDER_ATTACHMENT });
                S = { sid: "scratch:" + key, f, generation: 0, texture, views: new Map(), layers: 1, gpuMips: 1, volume: false, ss: [1, 1] };
                this.scratchTargets.set(key, S);
            }
            const colors = [{ S, view: { mip: 0, first: 0 }, format: S.f.gpu, x: false, scratch: true }];
            return { colors, targets: {}, width, height, samples: 1, ss: [1, 1], DS: null, dsView: null, depthFormat: null };
        }

        /**
         * The input layout: as WebGPU vertex buffers, and as the elements a
         * vertex shader run as compute pulls itself (fetch)
         */
        inputLayout(c) {
            const st = c.state;
            const layout = c.layouts.get(st.layout);
            const vertexInputs = {}, buffers = [], slots = [], fetch = [];
            let pull = false;
            if (layout) {
                const bySlot = new Map();
                const running = new Map();
                for (const e of layout.elements) {
                    const f = this.formatOf(e.format);
                    if (!f || !f.vertex) {
                        this.warn("vfmt" + e.format, "vertex format " + e.format + " is not supported");
                        continue;
                    }
                    let offset = e.offset;
                    if (offset === INVALID) offset = running.get(e.slot) || 0;
                    running.set(e.slot, offset + vertexSize(f.vertex));
                    fetch.push({ reg: e.register, slot: e.slot, offset, format: f.vertex, instanced: !!e.instanced });
                    // what WebGPU's vertex fetch cannot take: the vertices are pulled
                    if (/^pull:/.test(f.vertex) || e.instanced && e.rate > 1 || offset % Math.min(4, vertexSize(f.vertex))) pull = true;
                    if (!bySlot.has(e.slot)) bySlot.set(e.slot, { instanced: e.instanced, attributes: [] });
                    bySlot.get(e.slot).attributes.push({ format: f.vertex, offset, shaderLocation: e.register });
                    vertexInputs[e.register] = /sint/.test(f.vertex) ? "i32" : /uint/.test(f.vertex) ? "u32" : "f32";
                }
                for (const [slot, b] of [...bySlot].sort((a, b2) => a[0] - b2[0])) {
                    const vb = st.vbs[slot] || { sid: INVALID, stride: 0, offset: 0 };
                    let stride = vb.stride;
                    const end = Math.max(...b.attributes.map(a => a.offset + vertexSize(a.format)));
                    if (stride && (stride & 3 || stride < end || stride > 2048)) {
                        pull = true;
                        stride = align(Math.max(stride, end), 4);
                    }
                    buffers.push({ arrayStride: stride, stepMode: b.instanced ? "instance" : "vertex", attributes: b.attributes });
                    slots.push({ slot, vb });
                }
            }
            return { vertexInputs, buffers, slots, fetch, layout, pull };
        }

        draw(c, call) {
            const st = c.state;
            const vsStage = c.stages[SHADER_VS], psStage = c.stages[SHADER_PS];
            const vs = c.shaders.get(vsStage.shader), ps = c.shaders.get(psStage.shader);
            if (!vs || !vs.program) return this.warn("no-vs", "a draw without a vertex shader");
            const gs = c.stages[SHADER_GS].shader !== INVALID ? c.shaders.get(c.stages[SHADER_GS].shader) : null;
            // (fans, which D3D10 has not but Mesa's svga sends: drawn as lists, by provokingLast)
            const fan = st.topology === TOPOLOGY_TRIANGLEFAN;
            const topology = st.topology >= TOPOLOGY_PATCHLIST_1 && st.topology <= TOPOLOGY_PATCHLIST_32 ? "patches" :
                fan ? "triangle-fan" : TOPOLOGY[st.topology];
            if (!topology) return this.warn("topology" + st.topology, "topology " + st.topology + " is not supported");
            const so = this.streamOutput(c);
            const a = this.attachments(c);
            if (!a && !so) return;
            const input = this.inputLayout(c);
            if (fan && (gs || so || input.pull || c.stages[SHADER_HS].shader !== INVALID)) {
                return this.warn("fan", "triangle fans with geometry shaders, stream output or tessellation are not supported");
            }
            // hull and domain shaders: tessellation, as compute
            const hs = c.stages[SHADER_HS].shader !== INVALID ? c.shaders.get(c.stages[SHADER_HS].shader) : null;
            const ds = c.stages[SHADER_DS].shader !== INVALID ? c.shaders.get(c.stages[SHADER_DS].shader) : null;
            if (hs && hs.program && ds && ds.program) return this.drawTessellated(c, call, vs, hs, ds, gs, ps, a, input, so);
            // a geometry shader: the vertex and geometry shaders run as compute
            if (gs && gs.program) return this.drawGeometry(c, call, vs, gs, ps, a, input, so);
            // vertices WebGPU cannot fetch: the vertex shader pulls them, as compute
            if (input.pull && !so) return a ? this.drawPulled(c, call, vs, ps, a, input) : undefined;
            // stream output of the vertex shader's primitives
            if (so) {
                this.streamVertices(c, call, vs, input, so);
                if (!a || so.noRaster) return;
            }
            const { colors, targets, width, height, samples, DS, dsView, depthFormat } = a;
            const { vertexInputs, buffers, slots } = input;

            // the pixel shader's interface decides the vertex shader's outputs
            const varyings = ps && ps.program ? WGSL.pixelVaryings(ps.program) : {};
            const blend = c.blends.get(st.blend);
            const dualSource = !!(blend && usesSource1(blend.words));
            const vsOptions = { group: 0, vertexInputs, varyings, clipDistances: !!this.features.clipDistances };
            const psOptions = { group: 1, targets, dualSource };
            this.stageOptions(c, SHADER_VS, vs.program, vsOptions);
            if (ps && ps.program) this.stageOptions(c, SHADER_PS, ps.program, psOptions);
            let vsModule, psModule = null;
            try {
                vsModule = this.module(vs, vsOptions);
                if (ps && ps.program) psModule = this.module(ps, psOptions);
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }

            const raster = c.rasters.get(st.raster);
            const depth = c.depths.get(st.depth);
            // the last vertex flat shading: vertices reordered (and drawn as a list)
            const reorder = this.provokingLast(c, raster, varyings, topology, call);
            if (reorder === false) return;
            const drawTopology = reorder ? reorder.topology : topology;
            const key = [vs.id, ps ? ps.id : 0, JSON.stringify(vsOptions), JSON.stringify(psOptions), drawTopology,
                call.indexed && !reorder && /strip/.test(topology) ? (st.ib.format === SVGA3D_R16_UINT ? 16 : 32) : 0,
                JSON.stringify(buffers), colors.map(t => t ? t.format + (t.x ? "x" : "") + (t.scratch ? "s" : "") : "-").join(","), depthFormat, samples,
                blend ? blend.words.join(",") : "", raster ? raster.words.join(",") : "", depth ? depth.words.join(",") : "",
                st.sampleMask, this.bindingKinds(c, vsModule, psModule)].join("|");
            let pipeline = this.pipelines.get(key);
            if (!pipeline) {
                pipeline = this.createPipeline(c, { vsModule, psModule, buffers, topology: drawTopology, call: reorder ? { ...call, indexed: false } : call,
                    colors, depthFormat, samples, blend, raster, depth, dualSource });
                if (!pipeline) return;
                this.pipelines.set(key, pipeline);
                this.stats.pipelines++;
            }

            // the bind groups: the vertex shader's and the pixel shader's
            const viewport = this.viewport(st, width, height, a.ss);
            const groups = [this.bindGroup(c, SHADER_VS, vsModule, pipeline.layouts[0], call, viewport.fix),
                psModule ? this.bindGroup(c, SHADER_PS, psModule, pipeline.layouts[1], call, null) : this.emptyGroup];
            if (groups.includes(null)) return;

            const pass = this.renderPass(c, a, pipeline, groups, viewport, raster);
            slots.forEach(({ vb }, i) => {
                const S = this.surfaces.get(vb.sid);
                if (S && S.buffer && vb.offset < S.shadow.length) pass.setVertexBuffer(i, S.buffer, vb.offset & ~3);
                else pass.setVertexBuffer(i, this.dummyBuffer, 0);
            });
            this.stats.draws++;
            if (call.indirect) {
                const S = call.indirect.buffer ? null : this.surfaces.get(call.indirect.sid);
                const buffer = call.indirect.buffer || (S && S.buffer);
                if (!buffer) return;
                if (call.indexed) {
                    if (!this.setIndexBuffer(pass, st)) return;
                    pass.drawIndexedIndirect(buffer, call.indirect.offset);
                } else {
                    pass.drawIndirect(buffer, call.indirect.offset);
                }
                return;
            }
            if (!call.count || !call.instances) return;
            if (reorder) {
                pass.setIndexBuffer(reorder.buffer, "uint32", 0);
                if (reorder.args) pass.drawIndexedIndirect(reorder.args, 0);
                else pass.drawIndexed(reorder.count, call.instances, 0, call.first, call.firstInstance);
            } else if (call.indexed) {
                if (!this.setIndexBuffer(pass, st)) return;
                pass.drawIndexed(call.count, call.instances, call.first, call.base, call.firstInstance);
            } else {
                pass.draw(call.count, call.instances, call.first, call.firstInstance);
            }
        }

        /**
         * GL's provoking vertex is the last of a primitive (the rasterizer
         * state's provokingVertexLast), WebGPU's the first (G-17): a draw with
         * flat varyings has its vertices reordered, the last first, as a list
         * (a rotation, so triangles keep their winding). Fans are always
         * drawn so (their first vertex leads unless GL's last does). Without
         * indices the order is made here once per count; with indices a
         * compute pass rewrites them (restarts included), the draw indirect.
         * @return {?Object|boolean} { topology, buffer, count | args }; null:
         *     drawn as it is; false: not drawn
         */
        provokingLast(c, raster, varyings, topology, call) {
            const fan = topology === "triangle-fan";
            const last = !!raster && !!(raster.words[0] >>> 24 & 0xFF) &&
                Object.values(varyings).some(v => v.type === "u32" || v.interpolation === "flat");
            if (!fan && (!last || call.indirect)) return null;
            if (fan && call.indirect) {
                this.warn("fan-indirect", "indirect triangle fans are not supported");
                return false;
            }
            const kind = { "triangle-list": 1, "triangle-strip": 2, "line-list": 3, "line-strip": 4, "triangle-fan": 5 }[topology];
            if (!kind || !call.count) return fan ? false : null;
            const list = kind <= 2 || kind === 5 ? "triangle-list" : "line-list";
            if (!call.indexed) {
                const key = kind + ":" + call.count + ":" + last;
                let entry = this.provokingIndices.get(key);
                if (!entry) {
                    const n = call.count, out = [];
                    if (kind === 1) for (let k = 0; k + 2 < n; k += 3) out.push(k + 2, k, k + 1);
                    else if (kind === 2) for (let k = 0; k + 2 < n; k++) out.push(...(k & 1 ? [k + 2, k + 1, k] : [k + 2, k, k + 1]));
                    else if (kind === 3) for (let k = 0; k + 1 < n; k += 2) out.push(k + 1, k);
                    else if (kind === 4) for (let k = 0; k + 1 < n; k++) out.push(k + 1, k);
                    else for (let k = 1; k + 1 < n; k++) out.push(...(last ? [k + 1, 0, k] : [k, k + 1, 0]));
                    if (!out.length) return false;
                    const data = Uint32Array.from(out);
                    const buffer = this.device.createBuffer({ size: align(data.byteLength, 4), usage: BUFFER_USAGE.INDEX | BUFFER_USAGE.COPY_DST });
                    this.device.queue.writeBuffer(buffer, 0, data);
                    if (this.provokingIndices.size >= 64) {
                        for (const old of this.provokingIndices.values()) old.buffer.destroy();
                        this.provokingIndices.clear();
                    }
                    entry = { buffer, count: out.length };
                    this.provokingIndices.set(key, entry);
                }
                return { topology: list, buffer: entry.buffer, count: entry.count };
            }
            const st = c.state;
            const S = this.surfaces.get(st.ib.sid);
            if (!S || !S.buffer) return false;
            const wide = st.ib.format !== SVGA3D_R16_UINT;
            let pipe = this.pipelines.get("provoking");
            if (!pipe) {
                const code = [
                    "struct P { count: u32, offset: u32, wide: u32, kind: u32, base: u32, instances: u32, first_instance: u32, last: u32 }",
                    "@group(0) @binding(0) var<storage, read> src: array<u32>;",
                    "@group(0) @binding(1) var<uniform> p: P;",
                    "@group(0) @binding(2) var<storage, read_write> dst: array<u32>;",
                    "@group(0) @binding(3) var<storage, read_write> args: array<u32, 5>;",
                    "fn index(i: u32) -> u32 {",
                    "    let at = p.offset + i;",
                    "    if (p.wide == 1u) { return src[at]; }",
                    "    let w = src[at >> 1u];",
                    "    return select(w & 0xFFFFu, w >> 16u, (at & 1u) == 1u);",
                    "}",
                    "@compute @workgroup_size(1) fn main() {",
                    "    let cut = select(0xFFFFu, 0xFFFFFFFFu, p.wide == 1u);",
                    "    var n = 0u;",
                    "    var start = 0u;",
                    "    var i = 0u;",
                    "    loop {",
                    "        if (i >= p.count) { break; }",
                    "        if (p.kind == 1u) {",
                    "            if (i + 2u < p.count) { dst[n] = index(i + 2u); dst[n + 1u] = index(i); dst[n + 2u] = index(i + 1u); n += 3u; }",
                    "            i += 3u; continue;",
                    "        }",
                    "        if (p.kind == 3u) {",
                    "            if (i + 1u < p.count) { dst[n] = index(i + 1u); dst[n + 1u] = index(i); n += 2u; }",
                    "            i += 2u; continue;",
                    "        }",
                    "        // strips: a restart starts another",
                    "        if (index(i) == cut) { start = i + 1u; i++; continue; }",
                    "        let k = i - start;",
                    "        if (p.kind == 2u && k >= 2u && index(i - 1u) != cut && index(i - 2u) != cut) {",
                    "            if ((k & 1u) == 1u) { dst[n] = index(i); dst[n + 1u] = index(i - 1u); dst[n + 2u] = index(i - 2u); }",
                    "            else { dst[n] = index(i); dst[n + 1u] = index(i - 2u); dst[n + 2u] = index(i - 1u); }",
                    "            n += 3u;",
                    "        }",
                    "        if (p.kind == 4u && k >= 1u) { dst[n] = index(i); dst[n + 1u] = index(i - 1u); n += 2u; }",
                    "        if (p.kind == 5u && k >= 2u) {",
                    "            let first = index(start);",
                    "            if (p.last == 1u) { dst[n] = index(i); dst[n + 1u] = first; dst[n + 2u] = index(i - 1u); }",
                    "            else { dst[n] = index(i - 1u); dst[n + 1u] = index(i); dst[n + 2u] = first; }",
                    "            n += 3u;",
                    "        }",
                    "        i++;",
                    "    }",
                    "    args[0] = n; args[1] = p.instances; args[2] = 0u; args[3] = p.base; args[4] = p.first_instance;",
                    "}",
                ].join("\n");
                try {
                    pipe = this.device.createComputePipeline({ layout: "auto", compute: { module: this.device.createShaderModule({ code }), entryPoint: "main" } });
                } catch (error) {
                    this.warn("provoking:" + error.message, "the provoking vertex shader failed: " + error.message);
                    return null;
                }
                this.pipelines.set("provoking", pipe);
            }
            const offset = Math.floor(st.ib.offset / (wide ? 4 : 2)) + call.first;
            const dst = this.device.createBuffer({ size: align(Math.max(16, call.count * 3 * 4), 16), usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.INDEX });
            const args = this.device.createBuffer({ size: 32, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.INDIRECT });
            this.transient.push(dst, args);
            const params = this.uniform(new Uint32Array([call.count, offset, wide ? 1 : 0, kind, call.base >>> 0, call.instances, call.firstInstance, last ? 1 : 0]));
            let group;
            try {
                group = this.device.createBindGroup({ layout: pipe.getBindGroupLayout(0), entries: [
                    { binding: 0, resource: { buffer: S.buffer } }, { binding: 1, resource: params },
                    { binding: 2, resource: { buffer: dst } }, { binding: 3, resource: { buffer: args } }] });
            } catch (error) {
                this.warn("provoking-group:" + error.message, "the provoking vertex bind group failed: " + error.message);
                return null;
            }
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(pipe);
            compute.setBindGroup(0, group);
            compute.dispatchWorkgroups(1);
            compute.end();
            return { topology: list, buffer: dst, args };
        }

        /** The render pass of a draw's attachments (the same ones keep it open), its state set */
        renderPass(c, a, pipeline, groups, viewport, raster) {
            const st = c.state, { colors, DS, dsView, width, height } = a;
            const passKey = colors.map(t => t ? t.S.sid + ":" + t.S.generation + ":" + t.view.mip + ":" + t.view.first + ":" + t.format : "-").join(",") +
                "|" + (DS && DS.texture ? DS.sid + ":" + DS.generation + ":" + dsView.mip + ":" + dsView.first : "-") +
                "|" + [...this.activeOcclusion.keys()].length;
            if (!this.pass || this.passKey !== passKey) {
                this.endPass();
                this.beginPass(colors, DS && DS.texture ? { S: DS, view: dsView } : null, passKey);
            }
            const pass = this.pass;
            pass.setPipeline(pipeline.pipeline);
            pass.setBindGroup(0, groups[0]);
            pass.setBindGroup(1, groups[1]);
            pass.setViewport(viewport.x, viewport.y, viewport.width, viewport.height, viewport.min, viewport.max);
            const scissor = this.scissor(st, raster, width, height, a.ss);
            pass.setScissorRect(scissor[0], scissor[1], scissor[2], scissor[3]);
            pass.setBlendConstant(st.blendFactor);
            pass.setStencilReference(st.stencilRef & 0xFF);
            return pass;
        }

        // ------------------------------------------------------------------
        // Geometry shaders: no WebGPU stage, so the vertex shader runs as
        // compute and pulls its vertices, the geometry shader runs as compute
        // on what it stored, and what that emitted is drawn by a vertex
        // shader reading it (wgsl_emitter.js, "vertex-compute" and "geometry")

        drawGeometry(c, call, vs, gs, ps, a, input, so) {
            const st = c.state;
            if (call.indirect) return this.warn("gs-indirect", "indirect draws with a geometry shader are not supported");
            const count = call.count, instances = call.instances;
            if (!count || !instances) return;
            const assembly = GS_ASSEMBLY[st.topology];
            if (!assembly) return this.warn("gs-topology" + st.topology, "topology " + st.topology + " with a geometry shader");
            const prims = assembly.prims(count);
            if (prims <= 0) return;
            let vsModule, gsModule;
            try {
                vsModule = this.module(vs, { group: 0, mode: "vertex-compute", fetch: input.fetch });
                gsModule = this.module(gs, { group: 0, mode: "geometry" });
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const g = gsModule.result.gs;
            const vsRecord = Math.max(1, vsModule.result.record), gsRecord = gsModule.result.record;
            // (GS instancing: g.instances invocations per input primitive)
            const vertices = count * instances, invocations = prims * instances * (g.instances || 1);
            const slots = invocations * g.maxPrims * g.perPrim;
            const vsOut = this.storageBuffer(vertices * vsRecord * 16);
            const gsOut = this.storageBuffer(slots * gsRecord * 16);

            // the vertex shader, pulling its vertices
            const vsPipe = this.computePipeline(c, SHADER_VS, vsModule);
            const gsPipe = this.computePipeline(c, SHADER_GS, gsModule);
            if (!vsPipe || !gsPipe) return;
            const ib = this.surfaces.get(st.ib.sid);
            const vsGroup = this.bindGroup(c, SHADER_VS, vsModule, vsPipe.layout, call, null, {
                "fetch": this.uniform(this.fetchParameters(st, call, input)),
                "index": { buffer: call.indexed && ib && ib.buffer ? ib.buffer : this.dummyBuffer },
                "vertex-buffer": slot => {
                    const vb = st.vbs[slot];
                    const S = vb && this.surfaces.get(vb.sid);
                    return { buffer: S && S.buffer ? S.buffer : this.dummyBuffer };
                },
                "stage-out": { buffer: vsOut },
            });
            // ... and the geometry shader on its records
            const geo = new Uint32Array([prims, instances, count, assembly.code, vsRecord, 0, 0, 0]);
            const gsGroup = this.bindGroup(c, SHADER_GS, gsModule, gsPipe.layout, call, null, {
                "geo": this.uniform(geo), "stage-in": { buffer: vsOut }, "stage-out": { buffer: gsOut },
            });
            if (!vsGroup || !gsGroup) return;
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(vsPipe.pipeline);
            compute.setBindGroup(0, vsGroup);
            this.dispatch(compute, vertices);
            compute.setPipeline(gsPipe.pipeline);
            compute.setBindGroup(0, gsGroup);
            this.dispatch(compute, invocations);
            compute.end();
            this.stats.geometryDraws = (this.stats.geometryDraws || 0) + 1;

            // what it emitted: into the stream output buffers, and drawn
            if (so) this.writeStreamOutput(c, so, gsOut, gsRecord, { geometry: true, units: invocations * g.maxPrims, perPrim: g.perPrim });
            if (a && !(so && so.noRaster)) this.drawRecords(c, a, ps, gs, gsModule, gsOut, g.topology, slots);
        }

        // ------------------------------------------------------------------
        // Stream output: what a draw's last vertex stage made, primitive by
        // primitive in order, written into the target buffers by a compute
        // shader made for the declaration; each buffer's filled size stays on
        // the GPU (DrawAuto draws that many vertices)

        /** The stream output of a draw, if one is bound: { decl, targets, noRaster } */
        streamOutput(c) {
            const st = c.state;
            if (st.soid === INVALID) return null;
            const decl = c.streamOutputs.get(st.soid);
            if (!decl || !decl.entries.length) return null;
            const targets = st.soTargets.map(t => {
                const S = t && t.sid !== INVALID ? this.surfaces.get(t.sid) : null;
                return S && S.buffer ? { ...t, S } : null;
            });
            if (!targets.some(t => t)) return null;
            return { decl, targets, noRaster: (decl.rasterized | 0) === -1 };
        }

        /** Stream output's counts since the start: primitives written, needed, overflows */
        soStatistics() {
            if (!this.soStats) {
                this.soStats = this.device.createBuffer({ size: 16, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST });
            }
            return this.soStats;
        }

        /** A copy of soStatistics where the encoder is, to read */
        soSnapshot() {
            const target = this.device.createBuffer({ size: 16, usage: BUFFER_USAGE.MAP_READ | BUFFER_USAGE.COPY_DST });
            this.endPass();
            this.encoder().copyBufferToBuffer(this.soStatistics(), 0, target, 0, 16);
            return target;
        }

        /** A buffer's stream output filled size (bytes), on the GPU */
        soFilled(S) {
            if (!S.soFilled) {
                S.soFilled = this.device.createBuffer({ size: 16, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST });
            }
            return S.soFilled;
        }

        /** Stream output without a geometry shader: the vertex shader's primitives */
        streamVertices(c, call, vs, input, so) {
            const st = c.state;
            const assembly = GS_ASSEMBLY[st.topology];
            const perPrim = { 1: 1, 2: 2, 3: 2, 4: 3, 5: 3 }[assembly ? assembly.code : 0];
            if (call.indirect || !perPrim) return this.warn("so-topology", "stream output of this draw (indirect, or adjacency) is not supported");
            const prims = assembly.prims(call.count);
            if (prims <= 0 || !call.instances) return;
            let vsModule;
            try {
                vsModule = this.module(vs, { group: 0, mode: "vertex-compute", fetch: input.fetch });
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const record = Math.max(1, vsModule.result.record);
            const vsOut = this.storageBuffer(call.count * call.instances * record * 16);
            const vsPipe = this.computePipeline(c, SHADER_VS, vsModule);
            if (!vsPipe) return;
            const ib = this.surfaces.get(st.ib.sid);
            const group = this.bindGroup(c, SHADER_VS, vsModule, vsPipe.layout, call, null, {
                "fetch": this.uniform(this.fetchParameters(st, call, input)),
                "index": { buffer: call.indexed && ib && ib.buffer ? ib.buffer : this.dummyBuffer },
                "vertex-buffer": slot => {
                    const vb = st.vbs[slot];
                    const S = vb && this.surfaces.get(vb.sid);
                    return { buffer: S && S.buffer ? S.buffer : this.dummyBuffer };
                },
                "stage-out": { buffer: vsOut },
            });
            if (!group) return;
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(vsPipe.pipeline);
            compute.setBindGroup(0, group);
            this.dispatch(compute, call.count * call.instances);
            compute.end();
            this.writeStreamOutput(c, so, vsOut, record, { geometry: false, units: prims * call.instances, perPrim,
                prims, count: call.count, code: assembly.code });
        }

        /**
         * Write records into the stream output targets, in order
         * @param shape { geometry, units, perPrim } and without a geometry
         *     shader { prims, count, code }: the vertex records' topology
         */
        writeStreamOutput(c, so, src, record, shape) {
            const decl = so.decl;
            // where each entry's components go in a vertex of its buffer
            const writes = [], strides = [0, 0, 0, 0], running = [0, 0, 0, 0];
            for (const e of decl.entries) {
                if (e.stream !== 0) continue;
                for (let lane = 0; lane < 4; lane++) {
                    if (!(e.mask >> lane & 1)) continue;
                    // (a register past the record: a gap)
                    if (e.reg < (shape.geometry ? record - 1 : record)) writes.push({ slot: e.slot, offset: running[e.slot], reg: e.reg, lane });
                    running[e.slot] += 4;
                }
            }
            for (let slot = 0; slot < 4; slot++) strides[slot] = decl.strides[slot] || running[slot];
            const used = [0, 1, 2, 3].filter(slot => so.targets[slot] && strides[slot] && (running[slot] || writes.some(w => w.slot === slot)));
            if (!used.length) return;
            const key = "so2:" + JSON.stringify({ writes, strides, used, record, g: shape.geometry, p: shape.perPrim });
            let pipe = this.pipelines.get(key);
            if (!pipe) {
                const P = shape.perPrim, lanes = "xyzw";
                const lines = [];
                lines.push("struct SOParams { units: u32, prims: u32, count: u32, topology: u32, sizes: vec4<u32> }");
                lines.push("@group(0) @binding(0) var<storage, read> src: array<vec4<u32>>;");
                lines.push("@group(0) @binding(1) var<uniform> P: SOParams;");
                lines.push("@group(0) @binding(2) var<storage, read_write> filled: array<u32>;");
                for (const slot of used) lines.push(`@group(0) @binding(${3 + slot}) var<storage, read_write> so${slot}: array<u32>;`);
                // the statistics queries' counts: primitives written, needed, overflows
                lines.push("@group(0) @binding(7) var<storage, read_write> stats: array<u32>;");
                lines.push("fn gx_vertex(prim: u32, n: u32) -> u32 {\n    switch (P.topology) {\n" +
                    "        case 1u: { return prim; }\n        case 2u: { return prim * 2u + n; }\n        case 3u: { return prim + n; }\n" +
                    "        case 4u: { return prim * 3u + n; }\n" +
                    "        case 5u: { if ((prim & 1u) == 1u && n < 2u) { return prim + 1u - n; } return prim + n; }\n" +
                    "        default: { return prim + n; }\n    }\n}");
                lines.push("@compute @workgroup_size(1) fn main() {");
                for (const slot of used) lines.push(`    var c${slot} = filled[${slot}u];`);
                lines.push("    var stopped = false;");
                lines.push("    for (var u = 0u; u < P.units; u++) {");
                if (shape.geometry) {
                    lines.push(`        let first = u * ${P}u;`);
                    lines.push(`        if (src[first * ${record}u + ${record - 1}u].x == 0u) { continue; }`);
                } else {
                    lines.push("        let instance = u / P.prims;\n        let prim = u % P.prims;");
                }
                // the whole primitive fits, or the stream output stops (the
                // primitives after it still count as needed)
                lines.push("        stats[1] += 1u;");
                lines.push("        if (stopped) { continue; }");
                lines.push("        if (" + used.map(slot => `c${slot} + ${P * strides[slot]}u > P.sizes[${slot}]`).join(" || ") + ") { stopped = true; stats[2] += 1u; continue; }");
                lines.push("        stats[0] += 1u;");
                lines.push(`        for (var n = 0u; n < ${P}u; n++) {`);
                lines.push(shape.geometry ? `            let at = (first + n) * ${record}u;` :
                    `            let at = (instance * P.count + gx_vertex(prim, n)) * ${record}u;`);
                for (const w of writes) lines.push(`            so${w.slot}[(c${w.slot} + ${w.offset}u) >> 2u] = src[at + ${w.reg}u].${lanes[w.lane]};`);
                for (const slot of used) lines.push(`            c${slot} += ${strides[slot]}u;`);
                lines.push("        }\n    }");
                for (const slot of used) lines.push(`    filled[${slot}u] = c${slot};`);
                lines.push("}");
                try {
                    const module = this.device.createShaderModule({ code: lines.join("\n") });
                    pipe = this.device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
                } catch (error) {
                    return this.warn("so:" + error.message, "the stream output shader failed: " + error.message);
                }
                this.pipelines.set(key, pipe);
            }
            const sizes = [0, 0, 0, 0];
            for (const slot of used) sizes[slot] = so.targets[slot].S.shadow.length;
            const params = new Uint32Array([shape.units, shape.prims || 1, shape.count || 0, shape.code || 0, ...sizes]);
            const filled = this.storageBuffer(16);
            this.endPass();
            const encoder = this.encoder();
            for (const slot of used) encoder.copyBufferToBuffer(this.soFilled(so.targets[slot].S), 0, filled, slot * 4, 4);
            const entries = [{ binding: 0, resource: { buffer: src } }, { binding: 1, resource: this.uniform(params) },
                { binding: 2, resource: { buffer: filled } }];
            for (const slot of used) entries.push({ binding: 3 + slot, resource: { buffer: so.targets[slot].S.buffer } });
            entries.push({ binding: 7, resource: { buffer: this.soStatistics() } });
            let group;
            try {
                group = this.device.createBindGroup({ layout: pipe.getBindGroupLayout(0), entries });
            } catch (error) {
                return this.warn("so-group:" + error.message, "the stream output bind group failed: " + error.message);
            }
            const compute = encoder.beginComputePass();
            compute.setPipeline(pipe);
            compute.setBindGroup(0, group);
            compute.dispatchWorkgroups(1);
            compute.end();
            for (const slot of used) encoder.copyBufferToBuffer(filled, slot * 4, this.soFilled(so.targets[slot].S), 0, 4);
            this.stats.streamOutputs = (this.stats.streamOutputs || 0) + 1;
        }

        /** DrawAuto: as many vertices as stream output put in vertex buffer 0 */
        drawAuto(c) {
            const st = c.state;
            const vb = st.vbs[0];
            const S = vb && this.surfaces.get(vb.sid);
            if (!S || !S.buffer || !vb.stride) return;
            let pipe = this.pipelines.get("drawauto");
            if (!pipe) {
                const code = "@group(0) @binding(0) var<storage, read> filled: array<u32>;\n" +
                    "@group(0) @binding(1) var<storage, read_write> args: array<u32>;\n" +
                    "@group(0) @binding(2) var<uniform> vb: vec4<u32>;\n" +
                    "@compute @workgroup_size(1) fn main() {\n" +
                    "    args[0] = select(0u, (filled[0] - vb.x) / vb.y, filled[0] > vb.x);\n" +
                    "    args[1] = 1u; args[2] = 0u; args[3] = 0u;\n}";
                pipe = this.device.createComputePipeline({ layout: "auto",
                    compute: { module: this.device.createShaderModule({ code }), entryPoint: "main" } });
                this.pipelines.set("drawauto", pipe);
            }
            const args = this.device.createBuffer({ size: 16, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.INDIRECT });
            this.transient.push(args);
            const group = this.device.createBindGroup({ layout: pipe.getBindGroupLayout(0), entries: [
                { binding: 0, resource: { buffer: this.soFilled(S) } }, { binding: 1, resource: { buffer: args } },
                { binding: 2, resource: this.uniform(Uint32Array.of(vb.offset >>> 0, vb.stride, 0, 0)) }] });
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(pipe);
            compute.setBindGroup(0, group);
            compute.dispatchWorkgroups(1);
            compute.end();
            this.draw(c, { count: 0, first: 0, instances: 1, firstInstance: 0, indirect: { buffer: args, offset: 0 } });
        }

        /**
         * A draw of records a compute stage wrote: position and varyings as
         * the pixel shader reads them (`instances` of `count` records each)
         */
        /**
         * Draw a compute stage's records (tess: { indices, args }: by the
         * tessellator's indices, as many as its indirect arguments say)
         */
        drawRecords(c, a, ps, shader, module, buffer, topology, count, instances, tess) {
            instances = instances || 1;
            const st = c.state;
            const varyings = ps && ps.program ? WGSL.pixelVaryings(ps.program) : {};
            const record = module.result.record, outputs = module.result.gs ? record - 1 : record;
            let position = -1;
            for (const output of shader.program.outputs) if (output.name === IR.NAME.POSITION && output.type === IR.OPERAND.OUTPUT) position = output.index;
            const perInstance = instances > 1 ? count : 0;
            const passKey = "records:" + record + ":" + outputs + ":" + position + ":" + (module.result.gs ? 1 : 0) + ":" +
                JSON.stringify(varyings) + ":" + perInstance + (tess ? ":tess" : "");
            let pass = this.modules.get(passKey);
            if (!pass) {
                const fields = ["    @builtin(position) position: vec4<f32>,"], stores = [];
                for (const reg of Object.keys(varyings).map(Number).sort((x, y) => x - y)) {
                    const vary = varyings[reg];
                    const type = vary.type === "u32" ? "u32" : "f32";
                    const flat = type === "u32" || vary.interpolation === "flat" ? "@interpolate(flat) " :
                        vary.interpolation === "linear" ? `@interpolate(linear${vary.sampling ? ", " + vary.sampling : ""}) ` :
                        vary.sampling ? `@interpolate(perspective, ${vary.sampling}) ` : "";
                    fields.push(`    ${flat}@location(${reg}) o${reg}: vec4<${type}>,`);
                    const value = reg < outputs && reg !== position ? `gx_in[at + ${reg}u]` : "vec4<u32>()";
                    stores.push(type === "u32" ? `out.o${reg} = ${value};` : `out.o${reg} = bitcast<vec4<f32>>(${value});`);
                }
                const code = "struct GXDraw { base_vertex: u32, base_instance: u32, pad0: u32, pad1: u32, viewport: vec4<f32> }\n" +
                    "@group(0) @binding(15) var<uniform> gx_draw: GXDraw;\n" +
                    "@group(0) @binding(232) var<storage, read> gx_in: array<vec4<u32>>;\n" +
                    (tess ? "@group(0) @binding(231) var<storage, read> gx_tindex: array<u32>;\n" : "") +
                    `struct Out {\n${fields.join("\n")}\n}\n` +
                    "@vertex fn main(@builtin(vertex_index) vid: u32, @builtin(instance_index) iid: u32) -> Out {\n" +
                    (tess ? `    let at = gx_tindex[vid] * ${record}u;\n    var out: Out;\n` :
                        `    let at = (iid * ${perInstance}u + vid) * ${record}u;\n    var out: Out;\n`) +
                    // an unused slot (a geometry shader's flag lane): outside the clip volume
                    (module.result.gs ? `    if (gx_in[at + ${outputs}u].x == 0u) { out.position = vec4<f32>(2.0, 2.0, 2.0, 1.0); return out; }\n` : "") +
                    (position >= 0 ? `    let p = bitcast<vec4<f32>>(gx_in[at + ${position}u]);\n` : "    let p = vec4<f32>(0.0, 0.0, 0.0, 1.0);\n") +
                    "    out.position = vec4<f32>(p.xy * gx_draw.viewport.xy + gx_draw.viewport.zw * p.w, p.zw);\n" +
                    stores.map(x => "    " + x).join("\n") + "\n    return out;\n}\n";
                pass = { module: this.device.createShaderModule({ code }),
                    result: { bindings: [{ binding: 15, type: "draw" }, { binding: 232, type: "stage-in" },
                        ...(tess ? [{ binding: 231, type: "index" }] : [])] } };
                this.modules.set(passKey, pass);
            }
            const blend = c.blends.get(st.blend);
            const dualSource = !!(blend && usesSource1(blend.words));
            let psModule = null;
            try {
                if (ps && ps.program) psModule = this.module(ps, this.stageOptions(c, SHADER_PS, ps.program, { group: 1, targets: a.targets, dualSource }));
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const raster = c.rasters.get(st.raster);
            const depth = c.depths.get(st.depth);
            const plain = { indexed: false, count, instances: 1, first: 0, base: 0, firstInstance: 0 };
            const key = [passKey, ps ? ps.id : 0, JSON.stringify({ targets: a.targets, dualSource }), topology,
                a.colors.map(t => t ? t.format + (t.x ? "x" : "") + (t.scratch ? "s" : "") : "-").join(","), a.depthFormat, a.samples,
                blend ? blend.words.join(",") : "", raster ? raster.words.join(",") : "", depth ? depth.words.join(",") : "",
                st.sampleMask, this.bindingKinds(c, null, psModule)].join("|");
            let pipeline = this.pipelines.get(key);
            if (!pipeline) {
                pipeline = this.createPipeline(c, { vsModule: pass, psModule, buffers: [], topology, call: plain, colors: a.colors,
                    depthFormat: a.depthFormat, samples: a.samples, blend, raster, depth, dualSource });
                if (!pipeline) return;
                this.pipelines.set(key, pipeline);
                this.stats.pipelines++;
            }
            const viewport = this.viewport(st, a.width, a.height, a.ss);
            const extra = { "stage-in": { buffer } };
            if (tess) extra.index = { buffer: tess.indices };
            const groups = [this.bindGroup(c, SHADER_VS, pass, pipeline.layouts[0], plain, viewport.fix, extra),
                psModule ? this.bindGroup(c, SHADER_PS, psModule, pipeline.layouts[1], plain, null) : this.emptyGroup];
            if (groups.includes(null)) return;
            const renderPass = this.renderPass(c, a, pipeline, groups, viewport, raster);
            this.stats.draws++;
            // (the tessellator's arguments: the draw's after the dispatch's three words)
            if (tess) renderPass.drawIndirect(tess.args, 12);
            else renderPass.draw(count, instances, 0, 0);
        }

        // ------------------------------------------------------------------
        // Tessellation: no WebGPU stages, so the vertex shader runs as
        // compute (its records per control point), the hull shader as
        // compute once per patch (control points, patch constants, tess
        // factors), the D3D11 tessellator in WGSL (tessellator_wgsl.js:
        // counts, their prefix sums and the indirect arguments, then the
        // points and indices), the domain shader as compute once per point
        // (an indirect dispatch), and the points are drawn by the
        // tessellator's indices (an indirect draw)

        tessellatorPipelines() {
            if (this.tessPipelines) return this.tessPipelines;
            const module = this.device.createShaderModule({ code: TESS.TESSELLATOR_WGSL });
            const layout = this.device.createBindGroupLayout({ entries: [
                { binding: 0, visibility: 4, buffer: { type: "uniform" } },
                { binding: 1, visibility: 4, buffer: { type: "read-only-storage" } },
                ...[2, 3, 4, 5, 6].map(binding => ({ binding, visibility: 4, buffer: { type: "storage" } })),
            ] });
            const pipelineLayout = this.device.createPipelineLayout({ bindGroupLayouts: [layout] });
            const make = entryPoint => this.device.createComputePipeline({ layout: pipelineLayout, compute: { module, entryPoint } });
            this.tessPipelines = { layout, count: make("count"), scan: make("scan"), generate: make("generate") };
            return this.tessPipelines;
        }

        drawTessellated(c, call, vs, hs, ds, gs, ps, a, input, so) {
            const st = c.state;
            if (call.indirect) return this.warn("tess-indirect", "indirect draws with tessellation are not supported");
            if (st.topology < TOPOLOGY_PATCHLIST_1 || st.topology > TOPOLOGY_PATCHLIST_32) {
                return this.warn("tess-topology", "tessellation needs a patch list topology");
            }
            if (gs && gs.program) this.warn("tess-gs", "a geometry shader after tessellation is not supported: left out");
            if (so) this.warn("tess-so", "stream output after tessellation is not supported");
            const count = call.count, instances = call.instances;
            if (!count || !instances || !a) return;
            let vsModule, hsModule, dsModule;
            try {
                vsModule = this.module(vs, { group: 0, mode: "vertex-compute", fetch: input.fetch });
                hsModule = this.module(hs, { group: 0, mode: "hull" });
                dsModule = this.module(ds, { group: 0, mode: "domain" });
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const h = hsModule.result.hull;
            const inCPs = st.topology - TOPOLOGY_PATCHLIST_1 + 1;
            if (inCPs !== h.inCPs) this.warn("tess-cps", "the patch list has " + inCPs + " control points, the hull shader " + h.inCPs);
            const patches = Math.floor(count / inCPs), total = patches * instances;
            if (!patches) return;
            const vsRecord = Math.max(1, vsModule.result.record), dsRecord = Math.max(1, dsModule.result.record);
            const vertices = count * instances;
            // room for what the tessellator makes: by the hull shader's largest factor, at most about a million points
            const f = Math.min(64, Math.max(1, Math.ceil(h.maxTessFactor || 64)));
            const perPatchPoints = (f + 1) * (f + 2), perPatchIndices = 6 * f * f + 12 * f;
            const maxPoints = Math.min(total * perPatchPoints, 1 << 20), maxIndices = Math.min(total * perPatchIndices, 6 << 20);
            const vsOut = this.storageBuffer(vertices * vsRecord * 16);
            const hsOut = this.storageBuffer(total * h.record * 16);
            const counts = this.storageBuffer(total * 8), offsets = this.storageBuffer(total * 8);
            const points = this.storageBuffer(maxPoints * 16), indices = this.storageBuffer(maxIndices * 4);
            const args = this.device.createBuffer({ size: 32, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.INDIRECT | BUFFER_USAGE.COPY_DST });
            this.transient.push(args);
            const dsOut = this.storageBuffer(maxPoints * dsRecord * 16);

            const vsPipe = this.computePipeline(c, SHADER_VS, vsModule);
            const hsPipe = this.computePipeline(c, SHADER_HS, hsModule);
            const dsPipe = this.computePipeline(c, SHADER_DS, dsModule);
            if (!vsPipe || !hsPipe || !dsPipe) return;
            const ib = this.surfaces.get(st.ib.sid);
            const vsGroup = this.bindGroup(c, SHADER_VS, vsModule, vsPipe.layout, call, null, {
                "fetch": this.uniform(this.fetchParameters(st, call, input)),
                "index": { buffer: call.indexed && ib && ib.buffer ? ib.buffer : this.dummyBuffer },
                "vertex-buffer": slot => {
                    const vb = st.vbs[slot];
                    const S = vb && this.surfaces.get(vb.sid);
                    return { buffer: S && S.buffer ? S.buffer : this.dummyBuffer };
                },
                "stage-out": { buffer: vsOut },
            });
            const hsGroup = this.bindGroup(c, SHADER_HS, hsModule, hsPipe.layout, call, null, {
                "hull": this.uniform(new Uint32Array([patches, instances, count, vsRecord])),
                "stage-in": { buffer: vsOut }, "stage-out": { buffer: hsOut },
            });
            const dsGroup = this.bindGroup(c, SHADER_DS, dsModule, dsPipe.layout, call, null, {
                "domain": this.uniform(new Uint32Array([patches, h.record, h.cpRegs, h.pcAt])),
                "stage-in": { buffer: hsOut }, "tess-points": { buffer: points }, "tess-args": { buffer: args },
                "stage-out": { buffer: dsOut },
            });
            if (!vsGroup || !hsGroup || !dsGroup) return;
            const tp = this.tessellatorPipelines();
            const params = new Uint32Array([total, h.domain, h.partitioning, h.outputPrimitive, h.record, h.factorAt, maxPoints, maxIndices]);
            const tessGroup = this.device.createBindGroup({ layout: tp.layout, entries: [
                this.uniform(params), { buffer: hsOut }, { buffer: counts }, { buffer: offsets }, { buffer: points }, { buffer: indices }, { buffer: args },
            ].map((resource, binding) => ({ binding, resource })) });

            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(vsPipe.pipeline);
            compute.setBindGroup(0, vsGroup);
            this.dispatch(compute, vertices);
            compute.setPipeline(hsPipe.pipeline);
            compute.setBindGroup(0, hsGroup);
            this.dispatch(compute, total);
            compute.setBindGroup(0, tessGroup);
            compute.setPipeline(tp.count);
            this.dispatch(compute, total);
            compute.setPipeline(tp.scan);
            compute.dispatchWorkgroups(1);
            compute.setPipeline(tp.generate);
            this.dispatch(compute, total);
            compute.end();
            // (the domain shader's dispatch reads the arguments the scan wrote: a pass of its own)
            const domain = this.encoder().beginComputePass();
            domain.setPipeline(dsPipe.pipeline);
            domain.setBindGroup(0, dsGroup);
            domain.dispatchWorkgroupsIndirect(args, 0);
            domain.end();
            this.stats.tessellatedDraws = (this.stats.tessellatedDraws || 0) + 1;
            const topology = h.outputPrimitive === 1 ? "point-list" : h.outputPrimitive === 2 ? "line-list" : "triangle-list";
            this.drawRecords(c, a, ps, ds, dsModule, dsOut, topology, 0, 1, { indices, args });
        }

        /** A draw whose vertices WebGPU cannot fetch: the vertex shader as compute, then its records drawn */
        drawPulled(c, call, vs, ps, a, input) {
            const st = c.state;
            if (call.indirect) return this.warn("pull-indirect", "indirect draws of vertices WebGPU cannot fetch are not supported");
            if (!call.count || !call.instances) return;
            let vsModule;
            try {
                vsModule = this.module(vs, { group: 0, mode: "vertex-compute", fetch: input.fetch });
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const record = Math.max(1, vsModule.result.record);
            const vsOut = this.storageBuffer(call.count * call.instances * record * 16);
            const vsPipe = this.computePipeline(c, SHADER_VS, vsModule);
            if (!vsPipe) return;
            const ib = this.surfaces.get(st.ib.sid);
            const group = this.bindGroup(c, SHADER_VS, vsModule, vsPipe.layout, call, null, {
                "fetch": this.uniform(this.fetchParameters(st, call, input)),
                "index": { buffer: call.indexed && ib && ib.buffer ? ib.buffer : this.dummyBuffer },
                "vertex-buffer": slot => {
                    const vb = st.vbs[slot];
                    const S = vb && this.surfaces.get(vb.sid);
                    return { buffer: S && S.buffer ? S.buffer : this.dummyBuffer };
                },
                "stage-out": { buffer: vsOut },
            });
            if (!group) return;
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(vsPipe.pipeline);
            compute.setBindGroup(0, group);
            this.dispatch(compute, call.count * call.instances);
            compute.end();
            this.stats.pulledDraws = (this.stats.pulledDraws || 0) + 1;
            this.drawRecords(c, a, ps, vs, vsModule, vsOut, TOPOLOGY[st.topology], call.count, call.instances);
        }

        /** GXFetch: the draw, and each vertex buffer's offset, stride and instance step rate */
        fetchParameters(st, call, input) {
            const words = new Uint32Array(8 + 64);
            const ib = st.ib;
            words[0] = call.count; words[1] = call.first; words[2] = (call.indexed ? call.base : 0) >>> 0;
            words[3] = call.indexed ? 1 : 0; words[4] = call.instances; words[5] = call.firstInstance >>> 0;
            words[6] = ib.format === SVGA3D_R16_UINT ? 1 : 0; words[7] = ib.offset >>> 0;
            const rates = new Map();
            if (input.layout) for (const e of input.layout.elements) if (e.instanced) rates.set(e.slot, Math.max(1, e.rate || 1));
            for (let slot = 0; slot < 16; slot++) {
                const vb = st.vbs[slot];
                if (!vb) continue;
                words[8 + 4 * slot] = vb.offset >>> 0;
                words[9 + 4 * slot] = vb.stride >>> 0;
                words[10 + 4 * slot] = rates.get(slot) || 1;
            }
            return words;
        }

        /** A uniform buffer with these words, for this encoder's work */
        uniform(words) {
            const buffer = this.device.createBuffer({ size: align(Math.max(16, words.byteLength), 16), usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
            this.device.queue.writeBuffer(buffer, 0, words);
            this.transient.push(buffer);
            return { buffer };
        }

        /** A storage buffer for this encoder's work */
        storageBuffer(size) {
            const buffer = this.device.createBuffer({ size: align(Math.max(16, size), 16), usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST });
            this.transient.push(buffer);
            return buffer;
        }

        computePipeline(c, type, module) {
            const key = "compute:" + type + ":" + module.key + ":" + this.bindingKinds(c, module, null, type);
            let pipe = this.pipelines.get(key);
            if (pipe) return pipe;
            try {
                const layout = this.bindGroupLayout(c, type, module, 4);
                pipe = { pipeline: this.device.createComputePipeline({
                    layout: this.device.createPipelineLayout({ bindGroupLayouts: [layout] }),
                    compute: { module: module.module, entryPoint: "main" } }), layout };
            } catch (error) {
                this.warn("compute:" + error.message, "a compute pipeline failed: " + error.message);
                return null;
            }
            this.pipelines.set(key, pipe);
            return pipe;
        }

        /** Enough workgroups of 64 for n invocations (the y dimension past 65535) */
        dispatch(compute, n) {
            const groups = Math.ceil(n / 64);
            const x = Math.min(groups, 65535), y = Math.ceil(groups / 65535);
            compute.dispatchWorkgroups(x, y);
        }

        setIndexBuffer(pass, st) {
            const S = this.surfaces.get(st.ib.sid);
            if (!S || !S.buffer) return false;
            const format = st.ib.format === SVGA3D_R16_UINT ? "uint16" : "uint32";
            pass.setIndexBuffer(S.buffer, format, st.ib.offset & ~(format === "uint16" ? 1 : 3));
            return true;
        }

        beginPass(colors, depth, key) {
            const descriptor = {
                colorAttachments: colors.map(t => t && { view: this.attachmentView(t.S, t.view, t.format), loadOp: "load", storeOp: "store" }),
            };
            if (depth) {
                const format = depth.S.f.gpu;
                const attachment = { view: this.attachmentView(depth.S, depth.view, format) };
                if (!format.startsWith("stencil")) { attachment.depthLoadOp = "load"; attachment.depthStoreOp = "store"; }
                if (hasStencil(format)) { attachment.stencilLoadOp = "load"; attachment.stencilStoreOp = "store"; }
                descriptor.depthStencilAttachment = attachment;
            }
            this.passOcclusion = null;
            if (this.activeOcclusion.size) {
                if (!this.occlusion) this.occlusion = { set: this.device.createQuerySet({ type: "occlusion", count: 4096 }), next: 0 };
                if (this.occlusion.next >= 4096) this.occlusion.next = 0;
                const index = this.occlusion.next++;
                descriptor.occlusionQuerySet = this.occlusion.set;
                for (const q of this.activeOcclusion.keys()) q.indices.push(index);
                this.passOcclusion = index;
            }
            this.pass = this.encoder().beginRenderPass(descriptor);
            if (this.passOcclusion !== null) this.pass.beginOcclusionQuery(this.passOcclusion);
            this.passKey = key;
            this.stats.passes++;
        }

        /** The viewport WebGPU takes, and how the position moves to make up for it */
        viewport(st, width, height, ss = [1, 1]) {
            const v = st.viewports[0] || [0, 0, width / ss[0], height / ss[1], 0, 1];
            let [x, y, w, h, min, max] = v;
            x *= ss[0]; y *= ss[1]; w *= ss[0]; h *= ss[1];
            min = Math.min(1, Math.max(0, min)); max = Math.min(1, Math.max(min, max));
            if (w <= 0 || h <= 0) return { x: 0, y: 0, width: 1, height: 1, min, max, fix: [1, 1, 0, 0] };
            const cx = Math.max(0, x), cy = Math.max(0, y);
            const cw = Math.max(1, Math.min(x + w, width) - cx), ch = Math.max(1, Math.min(y + h, height) - cy);
            if (cx === x && cy === y && cw === w && ch === h) return { x, y, width: w, height: h, min, max, fix: [1, 1, 0, 0] };
            // NDC of the wanted viewport, mapped into the clamped one
            const sx = w / cw, sy = h / ch;
            const ox = ((x + w / 2) - (cx + cw / 2)) / (cw / 2), oy = -((y + h / 2) - (cy + ch / 2)) / (ch / 2);
            return { x: cx, y: cy, width: cw, height: ch, min, max, fix: [sx, sy, ox, oy] };
        }

        scissor(st, raster, width, height, ss = [1, 1]) {
            // (rasterizer dword 4: depthClipEnable, scissorEnable, ...)
            const enabled = raster && (raster.words[4] >> 8 & 0xFF);
            if (!enabled || !st.scissors.length) return [0, 0, width, height];
            const [l, t, r, b] = st.scissors[0].map((v, i) => v * ss[i & 1]);
            const x = Math.min(width, Math.max(0, l)), y = Math.min(height, Math.max(0, t));
            return [x, y, Math.max(0, Math.min(width, r) - x), Math.max(0, Math.min(height, b) - y)];
        }

        /** Part of the pipeline key: what the bound views are (depth, filterable) */
        bindingKinds(c, vsModule, psModule, vsType) {
            const parts = [];
            for (const [type, module] of [[vsType === undefined ? SHADER_VS : vsType, vsModule], [SHADER_PS, psModule]]) {
                if (!module) continue;
                const stage = c.stages[type];
                for (const b of module.result.bindings) {
                    if (b.type !== "texture") continue;
                    const srv = c.srvs.get(stage.srvs[b.slot]);
                    const S = srv && this.surfaces.get(srv.sid);
                    parts.push(S && S.texture ? this.textureSampleType(S, srv, b) : "none");
                }
            }
            return parts.join(",");
        }

        textureSampleType(S, srv, binding) {
            if (binding.sampleType === "depth") return "depth";
            if (binding.sampleType !== "float") return binding.sampleType;
            // (WebGPU filters no multisampled texture)
            if (binding.multisampled) return "unfilterable-float";
            const f = this.formatOf(srv.format) || S.f;
            const format = f.gpu || S.f.gpu;
            if (isDepthFormat(format)) return "unfilterable-float";
            if (/32float/.test(format) && !this.features.float32Filterable) return "unfilterable-float";
            return "float";
        }

        /** The bind group layout of a module's bindings, for a stage's state */
        bindGroupLayout(c, type, module, visibility) {
            const stage = c.stages[type];
            const entries = [];
            const unfilterable = new Set();
            for (const b of module.result.bindings) {
                if (b.type === "texture") {
                    const srv = c.srvs.get(stage.srvs[b.slot]);
                    const S = srv && this.surfaces.get(srv.sid);
                    let sampleType = S && S.texture ? this.textureSampleType(S, srv, b) : (b.sampleType === "depth" ? "depth" : b.sampleType === "float" ? "unfilterable-float" : b.sampleType);
                    if (sampleType === "unfilterable-float") unfilterable.add(b.slot);
                    entries.push({ binding: b.binding, visibility, texture: { sampleType, viewDimension: b.dimension, multisampled: b.multisampled } });
                } else if (b.type === "sampler" || b.type === "comparison") {
                    entries.push({ binding: b.binding, visibility, sampler: { type: b.type === "comparison" ? "comparison" : "filtering" } });
                } else if (b.type === "uniform" || b.type === "draw" || b.type === "fetch" || b.type === "geo" || b.type === "hull" || b.type === "domain") {
                    entries.push({ binding: b.binding, visibility, buffer: { type: "uniform" } });
                } else if (b.type === "read-storage" || b.type === "index" || b.type === "vertex-buffer" || b.type === "stage-in" ||
                    b.type === "tess-points" || b.type === "tess-args") {
                    entries.push({ binding: b.binding, visibility, buffer: { type: "read-only-storage" } });
                } else if (b.type === "storage" || b.type === "stage-out" || b.type === "uav" || b.type === "uav-counter") {
                    entries.push({ binding: b.binding, visibility, buffer: { type: "storage" } });
                } else if (b.type === "uav-texture") {
                    entries.push({ binding: b.binding, visibility, storageTexture: { access: b.access === "read_write" ? "read-write" : "write-only",
                        format: b.format, viewDimension: b.dimension } });
                } else if (b.type === "views") {
                    entries.push({ binding: b.binding, visibility, buffer: { type: "uniform" } });
                }
            }
            // samplers used with unfilterable textures must not filter
            if (unfilterable.size) {
                for (const e of entries) if (e.sampler && e.sampler.type === "filtering") e.sampler.type = "non-filtering";
            }
            return this.device.createBindGroupLayout({ entries });
        }

        createPipeline(c, o) {
            const layouts = [];
            for (const [type, module] of [[SHADER_VS, o.vsModule], [SHADER_PS, o.psModule]]) {
                if (!module) { layouts.push(this.emptyLayout); continue; }
                layouts.push(this.bindGroupLayout(c, type, module, type === SHADER_VS ? 1 : 2));
            }
            const raster = o.raster ? o.raster.words : [3 | 3 << 8 | 0 << 16, 0, 0, 0, 1, 0, 0];
            const fill = raster[0] & 0xFF, cull = raster[0] >> 8 & 0xFF, ccw = raster[0] >> 16 & 0xFF;
            if (fill === 2 || fill === 1) this.warn("wireframe", "wireframe and point fill are drawn solid");
            const depthBias = raster[1] | 0, biasClamp = f32(raster[2]), slope = f32(raster[3]);
            const depthClip = raster[4] & 0xFF;
            const primitive = {
                topology: o.topology,
                cullMode: cull === 2 ? "front" : cull === 3 ? "back" : "none",
                frontFace: ccw ? "ccw" : "cw",
            };
            if (o.call.indexed && /strip/.test(o.topology)) primitive.stripIndexFormat = "uint32";
            if (!depthClip && this.features.depthClipControl) primitive.unclippedDepth = true;
            const descriptor = {
                layout: this.device.createPipelineLayout({ bindGroupLayouts: layouts }),
                vertex: { module: o.vsModule.module, entryPoint: "main", buffers: o.buffers },
                primitive,
                // (multisampled targets are supersampled: one sample per fragment)
                multisample: { count: 1 },
            };
            // sample_info and sample_pos of the rasterizer read the pipeline's samples
            if (o.vsModule.result && o.vsModule.result.usesSamples) descriptor.vertex.constants = { gx_samples: o.samples };
            if (o.call.indexed && /strip/.test(o.topology)) {
                const st = c.state;
                primitive.stripIndexFormat = st.ib.format === SVGA3D_R16_UINT ? "uint16" : "uint32";
            }
            if (o.depthFormat) {
                const d = o.depth ? o.depth.words : null;
                const byte = (word, i) => word >> (8 * i) & 0xFF;
                const ds = { format: o.depthFormat, depthWriteEnabled: false, depthCompare: "always" };
                if (d) {
                    const depthEnable = byte(d[0], 0), writeMask = byte(d[0], 1), func = byte(d[0], 2), stencilEnable = byte(d[0], 3);
                    if (depthEnable) {
                        ds.depthWriteEnabled = !!writeMask;
                        ds.depthCompare = COMPARE[func] || "always";
                    }
                    if (stencilEnable && hasStencil(o.depthFormat)) {
                        ds.stencilReadMask = byte(d[1], 2);
                        ds.stencilWriteMask = byte(d[1], 3);
                        const face = (word) => ({ failOp: STENCIL_OPS[byte(word, 0)] || "keep", depthFailOp: STENCIL_OPS[byte(word, 1)] || "keep",
                            passOp: STENCIL_OPS[byte(word, 2)] || "keep", compare: COMPARE[byte(word, 3)] || "always" });
                        ds.stencilFront = byte(d[1], 0) ? face(d[2]) : { compare: "always", failOp: "keep", depthFailOp: "keep", passOp: "keep" };
                        ds.stencilBack = byte(d[1], 1) ? face(d[3]) : { compare: "always", failOp: "keep", depthFailOp: "keep", passOp: "keep" };
                    }
                } else {
                    ds.depthWriteEnabled = true;
                    ds.depthCompare = "less";
                }
                if (/depth/.test(o.depthFormat)) {
                    ds.depthBias = depthBias;
                    ds.depthBiasSlopeScale = slope;
                    ds.depthBiasClamp = biasClamp;
                } else {
                    delete ds.depthWriteEnabled;
                    delete ds.depthCompare;
                }
                descriptor.depthStencil = ds;
            }
            // the sample mask and alpha to coverage, by the pixel shader (wgsl_emitter.js)
            const psConstants = { gx_ss: o.samples > 4 ? 2 : o.samples > 1 ? 1 : 0, gx_sample_mask: c.state.sampleMask >>> 0,
                gx_a2c: o.blend && (o.blend.words[0] & 0xFF) ? 1 : 0 };
            if (o.psModule) {
                const targets = o.colors.map((t, i) => {
                    if (!t) return null;
                    const target = { format: t.format };
                    const words = o.blend ? o.blend.words : null;
                    const independent = words ? (words[0] >> 8 & 0xFF) : 0;
                    const rt = words ? (independent ? i : 0) : -1;
                    if (rt >= 0) {
                        const w0 = words[1 + 3 * rt], w1 = words[2 + 3 * rt], w2 = words[3 + 3 * rt];
                        const byte = (word, k) => word >> (8 * k) & 0xFF;
                        const enable = byte(w0, 0), src = byte(w0, 1), dst = byte(w0, 2), op = byte(w0, 3);
                        const srcA = byte(w1, 0), dstA = byte(w1, 1), opA = byte(w1, 2), mask = byte(w1, 3);
                        target.writeMask = mask & 0xF;
                        const blendable = !/int$/.test(t.format) && (!/32float/.test(t.format) || this.features.float32Blendable);
                        if (enable && blendable) {
                            target.blend = {
                                color: { srcFactor: BLEND_FACTORS[src] || "one", dstFactor: BLEND_FACTORS[dst] || "zero", operation: BLEND_OPS[op] || "add" },
                                alpha: { srcFactor: alphaFactor(BLEND_FACTORS[srcA] || "one"), dstFactor: alphaFactor(BLEND_FACTORS[dstA] || "zero"),
                                    operation: BLEND_OPS[opA] || "add" },
                            };
                            for (const part of [target.blend.color, target.blend.alpha]) {
                                if (part.operation === "min" || part.operation === "max") { part.srcFactor = "one"; part.dstFactor = "one"; }
                            }
                        }
                    }
                    // an "X" target keeps its alpha at 1; a scratch one (no targets) is never written
                    if (t.x) target.writeMask = (target.writeMask === undefined ? 0xF : target.writeMask) & 0x7;
                    if (t.scratch) { target.writeMask = 0; delete target.blend; }
                    return target;
                });
                descriptor.fragment = { module: o.psModule.module, entryPoint: "main", targets, constants: psConstants };
                if (o.psModule.result.usesSamples) psConstants.gx_samples = o.samples;
            } else if (o.colors.some(t => t)) {
                // no pixel shader, targets bound: they are not written (WebGPU
                // wants a fragment stage for the pass's attachments)
                descriptor.fragment = { module: this.nullPixelShader(o.colors), entryPoint: "main",
                    targets: o.colors.map(t => t && { format: t.format, writeMask: 0 }) };
            }
            try {
                return { pipeline: this.device.createRenderPipeline(descriptor), layouts };
            } catch (error) {
                this.warn("pipeline:" + error.message, "a pipeline failed: " + error.message);
                return null;
            }
        }

        /** A pixel shader writing zeros into targets of these formats, for draws without one */
        nullPixelShader(colors) {
            const types = colors.map(t => {
                if (!t) return null;
                const kind = sampleKind(t.format);
                return kind === "sint" ? "i32" : kind === "uint" ? "u32" : "f32";
            });
            const key = "null-ps:" + types.join(",");
            let module = this.pipelines.get(key);
            if (!module) {
                const fields = types.map((type, i) => type && `@location(${i}) c${i}: vec4<${type}>,`).filter(f => f);
                module = this.device.createShaderModule({ code: `struct Out { ${fields.join(" ")} }\n@fragment fn main() -> Out { var o: Out; return o; }` });
                this.pipelines.set(key, module);
            }
            return module;
        }

        /**
         * @param extra the resources of the compute variants' bindings: by
         *     binding type, and "vertex-buffer" a function of the slot
         */
        bindGroup(c, type, module, layout, call, fix, extra) {
            const stage = c.stages[type];
            const uavIds = type === SHADER_CS ? c.state.csUavs : c.state.uavs;
            const entries = [];
            for (const b of module.result.bindings) {
                if (extra && extra[b.type]) {
                    const resource = typeof extra[b.type] === "function" ? extra[b.type](b.slot) : extra[b.type];
                    entries.push({ binding: b.binding, resource });
                    continue;
                }
                switch (b.type) {
                    case "uniform": {
                        const cb = stage.cbs[b.slot];
                        const S = cb && this.surfaces.get(cb.sid);
                        entries.push({ binding: b.binding, resource: this.constantBuffer(S, cb, b.size) });
                        break;
                    }
                    case "draw":
                        entries.push({ binding: b.binding, resource: this.drawParameters(call, fix || [1, 1, 0, 0]) });
                        break;
                    case "sampler":
                    case "comparison": {
                        const state = c.samplers.get(stage.samplers[b.slot]);
                        entries.push({ binding: b.binding, resource: this.sampler(state, b.type === "comparison", layout, b.binding) });
                        break;
                    }
                    case "texture": {
                        const srv = c.srvs.get(stage.srvs[b.slot]);
                        entries.push({ binding: b.binding, resource: this.textureView(srv, b) });
                        break;
                    }
                    case "read-storage":
                    case "storage": {
                        const srv = c.srvs.get(stage.srvs[b.slot]);
                        const S = srv && this.surfaces.get(srv.sid);
                        entries.push({ binding: b.binding, resource: S && S.buffer ? { buffer: S.buffer } : { buffer: this.dummyBuffer } });
                        break;
                    }
                    case "uav": {
                        const view = c.uavs.get(uavIds[b.slot]);
                        const S = view && this.surfaces.get(view.sid);
                        entries.push({ binding: b.binding, resource: { buffer: S && S.buffer ? S.buffer : this.dummyUav } });
                        break;
                    }
                    case "uav-counter":
                        entries.push({ binding: b.binding, resource: { buffer: this.uavCounter(c, uavIds[b.slot]) } });
                        break;
                    case "uav-texture":
                        entries.push({ binding: b.binding, resource: this.storageView(c.uavs.get(uavIds[b.slot]), b) });
                        break;
                    case "views":
                        entries.push({ binding: b.binding, resource: this.uniform(this.viewBases(c, type, module)) });
                        break;
                }
            }
            try {
                return this.device.createBindGroup({ layout, entries });
            } catch (error) {
                this.warn("group:" + error.message, "a bind group failed: " + error.message);
                return null;
            }
        }

        // ------------------------------------------------------------------
        // UAVs and compute (SM5)

        /**
         * A stage's module options for what is bound: the typed UAVs'
         * formats, the multisampled resources' sample counts (8; 4 when
         * not said)
         */
        stageOptions(c, type, program, options) {
            if (program.uavs.size) options.uavFormats = this.uavFormats(c, type, program);
            const stage = c.stages[type];
            for (const [slot, r] of program.resources) {
                // typed buffers: the view's format, which their loads decode
                if (r.dimension === DIM_BUFFER && r.kind === "texture") {
                    const srv = c.srvs.get(stage.srvs[slot]);
                    const f = srv && this.formatOf(srv.format);
                    if (f && f.vertex) (options.srvFormats = options.srvFormats || {})[slot] = { format: f.vertex };
                    continue;
                }
                if (r.dimension !== 4 && r.dimension !== 9) continue;
                const srv = c.srvs.get(stage.srvs[slot]);
                const S = srv && this.surfaces.get(srv.sid);
                if (S && S.ss[0] * S.ss[1] === 8) (options.msSamples = options.msSamples || {})[slot] = 8;
            }
            return options;
        }

        /** What the typed UAVs a shader declares are bound to: storage formats, a typed buffer's 32-bit lanes */
        uavFormats(c, type, program) {
            const formats = {};
            const ids = type === SHADER_CS ? c.state.csUavs : c.state.uavs;
            for (const [slot, u] of program.uavs) {
                if (u.kind !== "typed") continue;
                const view = c.uavs.get(ids[slot]);
                const S = view && this.surfaces.get(view.sid);
                const f = view && (this.formatOf(view.format) || (S && S.f));
                if (u.dimension === DIM_BUFFER) formats[slot] = { lanes: f ? Math.max(1, Math.min(4, f.bytes >> 2)) : 1 };
                else if (f && STORAGE_FORMATS.has(f.gpu)) formats[slot] = { format: f.gpu };
            }
            return formats;
        }

        /** A typed texture UAV's view, or a stand-in of the binding's format */
        storageView(view, b) {
            const S = view && this.surfaces.get(view.sid);
            const T = S && S.texture && S.ss[0] === 1 ? (S.f.gpu === b.format ? (this.primary(S, true), S) : this.textureFor(S, b.format, true)) : null;
            if (T && T.texture.format === b.format && (T.texture.usage & TEXTURE_USAGE.STORAGE_BINDING)) {
                const [mip, first, count] = view.desc;
                const volume = b.dimension === "3d";
                const layers = volume ? 1 : S.layers;
                const baseLayer = volume ? 0 : Math.min(first, layers - 1);
                const layerCount = b.dimension === "2d" ? 1 : volume ? 1 : Math.max(1, Math.min(count || layers, layers - baseLayer));
                const key = "u:" + b.format + ":" + b.dimension + ":" + mip + ":" + baseLayer + ":" + layerCount;
                let v = T.views.get(key);
                if (!v) {
                    v = T.texture.createView({ format: b.format, dimension: b.dimension, baseMipLevel: Math.min(mip, S.gpuMips - 1),
                        mipLevelCount: 1, baseArrayLayer: baseLayer, arrayLayerCount: layerCount });
                    T.views.set(key, v);
                }
                return v;
            }
            if (S) this.warn("uav-format" + S.format, "a UAV of format " + S.format + " is not a storage texture");
            const key = b.format + ":" + b.dimension;
            let v = this.dummyStorageTextures.get(key);
            if (!v) {
                const texture = this.device.createTexture({ size: [1, 1, 1], dimension: b.dimension === "3d" ? "3d" : "2d", format: b.format,
                    usage: TEXTURE_USAGE.STORAGE_BINDING });
                v = texture.createView({ dimension: b.dimension });
                this.dummyStorageTextures.set(key, v);
            }
            return v;
        }

        /** An append/consume counter (a UAV's hidden one), made at 0 */
        uavCounter(c, id) {
            let counter = c.uavCounters.get(id);
            if (!counter) {
                counter = this.device.createBuffer({ size: 4, usage: BUFFER_USAGE.STORAGE | BUFFER_USAGE.COPY_SRC | BUFFER_USAGE.COPY_DST });
                c.uavCounters.set(id, counter);
            }
            return counter;
        }

        /** Words into a buffer in this encoder's order (not the queue's) */
        copyIn(buffer, offset, words) {
            this.endPass();
            this.encoder().copyBufferToBuffer(this.staging(new Uint8Array(words.buffer, words.byteOffset, words.byteLength)), 0,
                buffer, offset, words.byteLength);
        }

        /** Where the buffer views a shader reads start, in words (GXViews) */
        viewBases(c, type, module) {
            const bases = new Uint32Array(VIEW_BASES);
            const stage = c.stages[type];
            const uavIds = type === SHADER_CS ? c.state.csUavs : c.state.uavs;
            for (const b of module.result.bindings) {
                if (b.type === "uav") {
                    const view = c.uavs.get(uavIds[b.slot]);
                    // SVGA3dUAViewDesc buffer: firstElement, numElements, flags
                    if (view) bases[b.slot] = view.desc[0] * (b.kind === "structured" ? b.stride >> 2 : b.kind === "typed" ? b.lanes || 1 : 1);
                } else if (b.type === "read-storage") {
                    const srv = c.srvs.get(stage.srvs[b.slot]);
                    // SVGA3dShaderResourceViewDesc buffer(ex): firstElement, numElements
                    if (srv) bases[VIEW_BASE_RESOURCE + b.slot] = srv.desc[0] * (b.kind === "structured" ? b.stride >> 2 : 1);
                }
            }
            return bases;
        }

        /** DISPATCH(_INDIRECT): the compute shader over the thread groups */
        dispatchCompute(c, groups, indirect) {
            const cs = c.shaders.get(c.stages[SHADER_CS].shader);
            if (!cs || !cs.program) return this.warn("no-cs", "a dispatch without a compute shader");
            let module;
            try {
                module = this.module(cs, this.stageOptions(c, SHADER_CS, cs.program, { group: 0 }));
            } catch (error) {
                return this.warn("translate:" + error.message, "shader translation failed: " + error.message);
            }
            const pipe = this.computePipeline(c, SHADER_CS, module);
            if (!pipe) return;
            const group = this.bindGroup(c, SHADER_CS, module, pipe.layout, { indexed: false, count: 0, instances: 0, first: 0, base: 0, firstInstance: 0 }, null);
            if (!group) return;
            let args = null;
            if (indirect) {
                const S = this.surfaces.get(indirect.sid);
                if (!S || !S.buffer) return;
                args = { buffer: S.buffer, offset: indirect.offset };
            } else if (!groups[0] || !groups[1] || !groups[2]) {
                return;
            }
            this.endPass();
            const pass = this.encoder().beginComputePass();
            pass.setPipeline(pipe.pipeline);
            pass.setBindGroup(0, group);
            if (args) pass.dispatchWorkgroupsIndirect(args.buffer, args.offset);
            else pass.dispatchWorkgroups(Math.min(groups[0], 65535), Math.min(groups[1], 65535), Math.min(groups[2], 65535));
            pass.end();
            this.stats.dispatches++;
        }

        /**
         * CLEAR_UA_VIEW_UINT/FLOAT: a buffer's elements (each 32-bit word the
         * first value: raw and structured; the values: typed), a texture's
         * texels by a compute shader
         */
        clearUAV(c, id, value, float) {
            const view = c.uavs.get(id);
            const S = view && this.surfaces.get(view.sid);
            if (!S) return;
            if (S.buffer) {
                const f = this.formatOf(view.format);
                const raw = !!(view.desc[2] & UABUFFER_RAW) || !f || !f.gpu && !f.vertex;
                const lanes = raw ? 1 : Math.max(1, Math.min(4, f.bytes >> 2));
                const elementBytes = raw ? 4 : lanes * 4;
                // (a structured buffer's elements are not known here: all of it from the view's start)
                const start = view.desc[0] * elementBytes;
                const count = Math.min(view.desc[1] ? view.desc[1] * elementBytes : S.shadow.length, S.shadow.length - start) >> 2;
                if (count <= 0 || start & 3) return;
                const words = new Uint32Array(count);
                for (let i = 0; i < count; i++) {
                    const v = value[i % lanes];
                    words[i] = float ? new Uint32Array(new Float32Array([new Float32Array(new Uint32Array([v]).buffer)[0]]).buffer)[0] : v;
                }
                this.copyIn(S.buffer, start, words);
                return;
            }
            this.primary(S, true);
            if (!S.texture || !(S.texture.usage & TEXTURE_USAGE.STORAGE_BINDING)) {
                return this.warn("uav-clear" + S.format, "clears of UAVs of format " + S.format + " are not supported");
            }
            const format = S.f.gpu, volume = S.volume;
            const kind = /uint$/.test(format) ? "u32" : /sint$/.test(format) ? "i32" : "f32";
            const key = format + (volume ? ":3d" : ":2d-array");
            let pipeline = this.clearPipelines.get(key);
            if (!pipeline) {
                const code = `
@group(0) @binding(0) var t: texture_storage_${volume ? "3d" : "2d_array"}<${format}, write>;
@group(0) @binding(1) var<uniform> value: vec4<u32>;
@compute @workgroup_size(8, 8, 1) fn main(@builtin(global_invocation_id) g: vec3<u32>) {
    let size = textureDimensions(t);
    if (g.x >= size.x || g.y >= size.y) { return; }
    let v = ${kind === "f32" ? (float ? "bitcast<vec4<f32>>(value)" : "vec4<f32>(value)") : kind === "i32" ? "bitcast<vec4<i32>>(value)" : "value"};
    textureStore(t, ${volume ? "g.xyz" : "g.xy, g.z"}, v);
}`;
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
                this.clearPipelines.set(key, pipeline);
            }
            const [mip, first, count] = view.desc;
            const level = this.level(S, Math.min(mip, S.gpuMips - 1));
            const layers = volume ? 1 : Math.max(1, Math.min(count || S.layers, S.layers - Math.min(first, S.layers - 1)));
            const target = S.texture.createView({ dimension: volume ? "3d" : "2d-array", baseMipLevel: Math.min(mip, S.gpuMips - 1), mipLevelCount: 1,
                baseArrayLayer: volume ? 0 : Math.min(first, S.layers - 1), arrayLayerCount: layers });
            const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                { binding: 0, resource: target }, { binding: 1, resource: this.uniform(Uint32Array.from(value)) }] });
            this.endPass();
            const pass = this.encoder().beginComputePass();
            pass.setPipeline(pipeline);
            pass.setBindGroup(0, group);
            pass.dispatchWorkgroups(Math.ceil(level.width / 8), Math.ceil(level.height / 8), volume ? level.depth : layers);
            pass.end();
        }

        /** A constant buffer binding: aligned and big enough, or a copy that is */
        constantBuffer(S, cb, size) {
            if (S && S.buffer && cb.offset % 256 === 0 && cb.offset + size <= S.shadow.length) {
                return { buffer: S.buffer, offset: cb.offset, size };
            }
            // too short, or not aligned: the bytes, copied where they fit
            const bytes = new Uint8Array(align(size, 16));
            if (S && S.shadow) bytes.set(S.shadow.subarray(cb.offset, Math.min(S.shadow.length, cb.offset + size)));
            const buffer = this.device.createBuffer({ size: bytes.length, usage: BUFFER_USAGE.UNIFORM | BUFFER_USAGE.COPY_DST });
            this.device.queue.writeBuffer(buffer, 0, bytes);
            this.transient.push(buffer);
            return { buffer, offset: 0, size };
        }

        drawParameters(call, fix) {
            if (this.drawSlot >= DRAW_SLOTS) {
                // every slot is in this encoder's work: send it first
                this.flushEncoder();
                this.drawSlot = 0;
            }
            const offset = this.drawSlot++ * DRAW_SLOT;
            const data = new ArrayBuffer(32);
            const u = new Uint32Array(data), f = new Float32Array(data);
            u[0] = call.indexed ? call.base >>> 0 : 0;
            u[1] = call.firstInstance >>> 0;
            f.set(fix, 4);
            this.device.queue.writeBuffer(this.drawBuffer, offset, data);
            // an indirect draw's base vertex and first instance are in its
            // arguments (D3D's ids leave them out, WebGPU's have them)
            const S = call.indirect && call.indirect.sid !== undefined ? this.surfaces.get(call.indirect.sid) : null;
            if (S && S.buffer && call.indirect.offset + (call.indexed ? 20 : 16) <= S.shadow.length) {
                this.endPass();
                const encoder = this.encoder();
                if (call.indexed) encoder.copyBufferToBuffer(S.buffer, call.indirect.offset + 12, this.drawBuffer, offset, 8);
                else encoder.copyBufferToBuffer(S.buffer, call.indirect.offset + 12, this.drawBuffer, offset + 4, 4);
            }
            return { buffer: this.drawBuffer, offset, size: 32 };
        }

        sampler(state, comparison, layout, binding) {
            const words = state ? state.words : null;
            const key = (words ? words.join(",") : "default") + (comparison ? ":c" : "");
            let sampler = this.samplerCache.get(key);
            if (sampler) return sampler;
            const descriptor = {};
            if (words) {
                const filter = words[0];
                const linear = bit => (filter & bit) ? "linear" : "nearest";
                descriptor.magFilter = linear(4);
                descriptor.minFilter = linear(16);
                descriptor.mipmapFilter = linear(1);
                const address = words[1];
                descriptor.addressModeU = ADDRESS[address & 0xFF] || "repeat";
                descriptor.addressModeV = ADDRESS[address >> 8 & 0xFF] || "repeat";
                descriptor.addressModeW = ADDRESS[address >> 16 & 0xFF] || "repeat";
                const anisotropy = words[3] & 0xFF;
                if (filter & 64 && anisotropy > 1) {
                    descriptor.magFilter = descriptor.minFilter = descriptor.mipmapFilter = "linear";
                    descriptor.maxAnisotropy = Math.min(16, anisotropy);
                }
                const minLod = f32(words[8]), maxLod = f32(words[9]);
                descriptor.lodMinClamp = Math.max(0, Number.isFinite(minLod) ? minLod : 0);
                descriptor.lodMaxClamp = Math.max(descriptor.lodMinClamp, Math.min(32, Number.isFinite(maxLod) ? maxLod : 32));
                if (comparison) descriptor.compare = COMPARE[words[3] >> 8 & 0xFF] || "less-equal";
            } else if (comparison) {
                descriptor.compare = "less-equal";
            }
            sampler = this.device.createSampler(descriptor);
            this.samplerCache.set(key, sampler);
            return sampler;
        }

        /** A view of a shader resource as the shader declares it */
        textureView(srv, binding) {
            const S = srv && this.surfaces.get(srv.sid);
            if (!S || !S.texture) return this.dummyTexture(binding);
            const f = this.formatOf(srv.format) || S.f;
            let format = f.gpu || S.f.gpu;
            // (another family of the texel layout: its alias)
            const T = this.textureFor(S, format, false) || S;
            if (T === S && format !== S.f.gpu && SRGB[S.f.gpu] !== format) format = S.f.gpu;
            const [most, first, mips, count] = srv.desc;
            const dimension = binding.dimension;
            const baseMip = Math.min(most, S.gpuMips - 1);
            const mipCountView = Math.max(1, Math.min(mips === INVALID ? S.gpuMips : mips, S.gpuMips - baseMip));
            let layers = S.volume ? 1 : S.layers;
            let baseLayer = S.volume ? 0 : Math.min(first, layers - 1);
            // (a cube array's view counts cubes)
            const cubes = Math.floor((layers - baseLayer) / 6);
            let layerCount = dimension === "2d" ? 1 : dimension === "cube" ? 6 :
                dimension === "cube-array" ? Math.min(count && count !== INVALID ? count : cubes, cubes) * 6 :
                Math.max(1, Math.min(count || 1, layers - baseLayer));
            if (dimension === "cube-array" && !layerCount) return this.dummyTexture(binding);
            if (dimension === "2d-array" && !count) layerCount = layers - baseLayer;
            if (dimension === "cube" && layers - baseLayer < 6) return this.dummyTexture(binding);
            const aspect = isDepthFormat(format) ? (srv.format === 82 || srv.format === 63 ? "stencil-only" : "depth-only") : "all";
            const key = "v:" + format + ":" + dimension + ":" + baseMip + ":" + mipCountView + ":" + baseLayer + ":" + layerCount + ":" + aspect;
            let view = T.views.get(key);
            if (!view) {
                // (one aspect of a depth-stencil texture: its own format, WebGPU's default for it)
                view = T.texture.createView({ format: aspect === "all" ? format : undefined, dimension: S.volume ? "3d" : dimension,
                    baseMipLevel: baseMip, mipLevelCount: mipCountView, baseArrayLayer: baseLayer, arrayLayerCount: S.volume ? 1 : layerCount, aspect });
                T.views.set(key, view);
            }
            return view;
        }

        dummyTexture(binding) {
            const key = binding.dimension + ":" + binding.sampleType + ":" + binding.multisampled;
            let view = this.dummyTextures.get(key);
            if (view) return view;
            const format = binding.sampleType === "depth" ? "depth32float" : binding.sampleType === "sint" ? "rgba8sint" :
                binding.sampleType === "uint" ? "rgba8uint" : "rgba8unorm";
            const cube = binding.dimension === "cube" || binding.dimension === "cube-array";
            const texture = this.device.createTexture({ size: [1, 1, binding.dimension === "3d" ? 1 : cube ? 6 : 1],
                dimension: binding.dimension === "3d" ? "3d" : "2d", format, sampleCount: binding.multisampled ? 4 : 1,
                usage: TEXTURE_USAGE.TEXTURE_BINDING | (binding.multisampled ? TEXTURE_USAGE.RENDER_ATTACHMENT : 0) });
            view = texture.createView({ dimension: binding.dimension });
            this.dummyTextures.set(key, view);
            return view;
        }
    }

    /** One DX context's objects and state */
    class GXContext {
        constructor(cid) {
            this.cid = cid;
            this.generation = 0;
            this.rtvs = new Map(); this.dsvs = new Map(); this.srvs = new Map(); this.uavs = new Map();
            this.layouts = new Map(); this.blends = new Map(); this.depths = new Map(); this.rasters = new Map();
            this.samplers = new Map(); this.shaders = new Map(); this.queries = new Map();
            /** stream output declarations: { entries: [{ slot, reg, mask, stream }], strides, rasterized } */
            this.streamOutputs = new Map();
            this.stages = {};
            for (let type = SHADER_VS; type <= SHADER_CS; type++) {
                this.stages[type] = { shader: INVALID, cbs: new Array(16).fill(null), srvs: new Array(128).fill(INVALID),
                    samplers: new Array(16).fill(INVALID) };
            }
            this.state = {
                layout: INVALID, vbs: new Array(32).fill(null), ib: { sid: INVALID, format: SVGA3D_R16_UINT, offset: 0 },
                topology: 1, rtvs: [], dsv: INVALID, blend: INVALID, blendFactor: [0, 0, 0, 0], sampleMask: INVALID,
                depth: INVALID, stencilRef: 0, raster: INVALID, viewports: [], scissors: [], predication: [INVALID, 0],
                soid: INVALID, soTargets: [],
                // UAVs: of the pixel shader (slots shared with the targets), of compute
                uavs: new Array(64).fill(INVALID), csUavs: new Array(64).fill(INVALID),
            };
            /** append/consume counters: UAV id -> a GPUBuffer of one u32 */
            this.uavCounters = new Map();
        }

        stage(type) {
            return this.stages[type] || null;
        }

        /** A COTable set again: its objects are defined anew */
        reset(type) {
            const maps = { [COTABLE.RTVIEW]: this.rtvs, [COTABLE.DSVIEW]: this.dsvs, [COTABLE.SRVIEW]: this.srvs,
                [COTABLE.ELEMENTLAYOUT]: this.layouts, [COTABLE.BLENDSTATE]: this.blends, [COTABLE.DEPTHSTENCIL]: this.depths,
                [COTABLE.RASTERIZERSTATE]: this.rasters, [COTABLE.SAMPLER]: this.samplers, [COTABLE.DXQUERY]: this.queries,
                [COTABLE.DXSHADER]: this.shaders, [COTABLE.UAVIEW]: this.uavs, [COTABLE.STREAMOUTPUT]: this.streamOutputs };
            if (maps[type]) maps[type].clear();
        }
    }

    /** [mip, layer] of a subresource index */
    function subresource(S, index) {
        return [index % S.mips, Math.floor(index / S.mips)];
    }

    function mipCount(width, height, depth) {
        return 1 + Math.floor(Math.log2(Math.max(width, height, depth)));
    }

    /** Bytes of a WebGPU vertex format */
    function vertexSize(format) {
        if (format === "unorm10-10-10-2" || format === "unorm8x4-bgra") return 4;
        const size = /(8|16|32)(?:x(\d))?$/.exec(format);
        return size ? (+size[1] / 8) * (+size[2] || 1) : 4;
    }

    /** Whether a blend state reads the pixel shader's second color */
    function usesSource1(words) {
        for (let rt = 0; rt < 8; rt++) {
            const w0 = words[1 + 3 * rt], w1 = words[2 + 3 * rt];
            for (const factor of [w0 >> 8 & 0xFF, w0 >> 16 & 0xFF, w1 & 0xFF, w1 >> 8 & 0xFF]) {
                if (factor >= 14 && factor <= 17) return true;
            }
        }
        return false;
    }

    /** WebGPU's alpha factors take no colors */
    function alphaFactor(factor) {
        return { "src": "src-alpha", "one-minus-src": "one-minus-src-alpha", "dst": "dst-alpha", "one-minus-dst": "one-minus-dst-alpha",
            "src1": "src1-alpha", "one-minus-src1": "one-minus-src1-alpha" }[factor] || factor;
    }

    // Formats WebGPU lacks, stored wider (svga_dx_formats.js "e"): per SVGA
    // format, how many texels a guest block holds, the bytes of a texel on
    // the GPU, and the conversions of one block
    const F16 = (() => {
        const f32 = new Float32Array(1), u32 = new Uint32Array(f32.buffer);
        return {
            encode(v) {
                f32[0] = v;
                const x = u32[0], sign = x >>> 16 & 0x8000, exp = (x >>> 23 & 0xFF) - 127 + 15, mant = x & 0x7FFFFF;
                if (exp <= 0) return sign;
                if (exp >= 31) return sign | 0x7C00;
                return sign | exp << 10 | mant >>> 13;
            },
            decode(h) {
                const sign = h & 0x8000 ? -1 : 1, exp = h >> 10 & 31, mant = h & 1023;
                if (!exp) return sign * mant * 2 ** -24;
                if (exp === 31) return mant ? NaN : sign * Infinity;
                return sign * (1 + mant / 1024) * 2 ** (exp - 15);
            },
        };
    })();
    const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
    /** n channels of a normalized integer type, as floats of `width` bytes (2 or 4) */
    function normalized(n, bits, signed, width) {
        const max = signed ? 2 ** (bits - 1) - 1 : 2 ** bits - 1;
        const bytes = bits / 8;
        const read = (v, o) => bits === 8 ? (signed ? v.getInt8(o) : v.getUint8(o)) : (signed ? v.getInt16(o, true) : v.getUint16(o, true));
        const write = (v, o, x) => bits === 8 ? (signed ? v.setInt8(o, x) : v.setUint8(o, x)) : (signed ? v.setInt16(o, x, true) : v.setUint16(o, x, true));
        return {
            texels: 1, gpu: n * width,
            expand(src, si, dst, di) {
                for (let c = 0; c < n; c++) {
                    const value = Math.max(read(src, si + c * bytes) / max, -1);
                    if (width === 4) dst.setFloat32(di + 4 * c, value, true);
                    else dst.setUint16(di + 2 * c, F16.encode(value), true);
                }
            },
            pack(src, si, dst, di) {
                for (let c = 0; c < n; c++) {
                    const value = width === 4 ? src.getFloat32(si + 4 * c, true) : F16.decode(src.getUint16(si + 2 * c, true));
                    write(dst, di + c * bytes, Math.round(clamp(value, signed ? -1 : 0, 1) * max));
                }
            },
        };
    }
    /** RGB32 into RGBA32: alpha 1 */
    const rgb32 = one => ({
        texels: 1, gpu: 16,
        expand(src, si, dst, di) { for (let c = 0; c < 3; c++) dst.setUint32(di + 4 * c, src.getUint32(si + 4 * c, true), true); dst.setUint32(di + 12, one, true); },
        pack(src, si, dst, di) { for (let c = 0; c < 3; c++) dst.setUint32(di + 4 * c, src.getUint32(si + 4 * c, true), true); },
    });
    /** 16-bit packed colors into RGBA8 */
    const packed16 = (decode, encode) => ({
        texels: 1, gpu: 4,
        expand(src, si, dst, di) { const [r, g, b, a] = decode(src.getUint16(si, true)); dst.setUint8(di, r); dst.setUint8(di + 1, g); dst.setUint8(di + 2, b); dst.setUint8(di + 3, a); },
        pack(src, si, dst, di) { dst.setUint16(di, encode(src.getUint8(si), src.getUint8(si + 1), src.getUint8(si + 2), src.getUint8(si + 3)), true); },
    });
    const c5 = v => (v & 31) * 255 / 31, c6 = v => (v & 63) * 255 / 63, c4 = v => (v & 15) * 17;
    const R565 = packed16(v => [c5(v >> 11), c6(v >> 5), c5(v), 255], (r, g, b) => (r >> 3) << 11 | (g >> 2) << 5 | b >> 3);
    const R1555 = packed16(v => [c5(v >> 10), c5(v >> 5), c5(v), v & 0x8000 ? 255 : 0], (r, g, b, a) => (a >> 7) << 15 | (r >> 3) << 10 | (g >> 3) << 5 | b >> 3);
    const R4444 = packed16(v => [c4(v >> 8), c4(v >> 4), c4(v), c4(v >> 12)], (r, g, b, a) => (a >> 4) << 12 | (r >> 4) << 8 | (g >> 4) << 4 | b >> 4);
    /** Two texels sharing R and B in a 4-byte block (R8G8_B8G8, G8R8_G8B8) */
    const pair = (r, g0, b, g1) => ({
        texels: 2, gpu: 4,
        expand(src, si, dst, di) {
            for (const [t, g] of [[0, g0], [1, g1]]) {
                dst.setUint8(di + 4 * t, src.getUint8(si + r)); dst.setUint8(di + 4 * t + 1, src.getUint8(si + g));
                dst.setUint8(di + 4 * t + 2, src.getUint8(si + b)); dst.setUint8(di + 4 * t + 3, 255);
            }
        },
        pack(src, si, dst, di) {
            dst.setUint8(di + r, src.getUint8(si)); dst.setUint8(di + g0, src.getUint8(si + 1));
            dst.setUint8(di + b, src.getUint8(si + 2)); dst.setUint8(di + g1, src.getUint8(si + 5));
        },
    });
    const EMULATED = {
        3: R565, 139: R565, 4: R1555, 5: R1555, 140: R1555, 6: R4444, 145: R4444,
        // A8 and ALPHA8: (0, 0, 0, a)
        135: { texels: 1, gpu: 4, expand(s, si, d, di) { d.setUint32(di, s.getUint8(si) << 24 >>> 0, true); }, pack(s, si, d, di) { d.setUint8(di, s.getUint8(si + 3)); } },
        32: { texels: 1, gpu: 4, expand(s, si, d, di) { d.setUint32(di, s.getUint8(si) << 24 >>> 0, true); }, pack(s, si, d, di) { d.setUint8(di, s.getUint8(si + 3)); } },
        // LUMINANCE8 (L, L, L, 1), LUMINANCE8_ALPHA8 (L, L, L, A)
        11: { texels: 1, gpu: 4, expand(s, si, d, di) { const l = s.getUint8(si); d.setUint32(di, (l | l << 8 | l << 16 | 255 << 24) >>> 0, true); }, pack(s, si, d, di) { d.setUint8(di, s.getUint8(si)); } },
        14: { texels: 1, gpu: 4, expand(s, si, d, di) { const l = s.getUint8(si), a = s.getUint8(si + 1); d.setUint32(di, (l | l << 8 | l << 16 | a << 24) >>> 0, true); },
            pack(s, si, d, di) { d.setUint8(di, s.getUint8(si)); d.setUint8(di + 1, s.getUint8(si + 3)); } },
        // A2R10G10B10 into rgb10a2unorm: R and B change places
        26: { texels: 1, gpu: 4, expand(s, si, d, di) { const v = s.getUint32(si, true); d.setUint32(di, ((v & 0xC00FFC00) | (v >>> 20 & 0x3FF) | (v & 0x3FF) << 20) >>> 0, true); },
            pack(s, si, d, di) { const v = s.getUint32(si, true); d.setUint32(di, ((v & 0xC00FFC00) | (v >>> 20 & 0x3FF) | (v & 0x3FF) << 20) >>> 0, true); } },
        49: rgb32(0x3F800000), 50: rgb32(0x3F800000), 51: rgb32(1), 52: rgb32(1),
        124: normalized(4, 16, false, 4), 55: normalized(4, 16, true, 4),
        129: normalized(2, 16, false, 4), 130: normalized(2, 16, true, 4),
        88: normalized(1, 16, false, 4), 90: normalized(1, 16, true, 4),
        127: normalized(4, 8, true, 2), 132: normalized(2, 8, true, 2), 95: normalized(1, 8, true, 2),
        99: pair(0, 1, 2, 3), 100: pair(1, 0, 3, 2),
    };

    /** A row of the guest's blocks into the GPU's texels */
    function expandRow(format, bytes, from, to) {
        const codec = EMULATED[format];
        if (!codec) return;
        const src = new DataView(from.buffer, from.byteOffset, from.byteLength), dst = new DataView(to.buffer, to.byteOffset, to.byteLength);
        const step = codec.gpu * codec.texels;
        for (let i = 0; (i + 1) * bytes <= from.length && (i + 1) * step <= to.length; i++) codec.expand(src, i * bytes, dst, i * step);
    }

    /** A row of the GPU's texels into the guest's blocks */
    function packRow(format, bytes, from, to) {
        const codec = EMULATED[format];
        if (!codec) return;
        const src = new DataView(from.buffer, from.byteOffset, from.byteLength), dst = new DataView(to.buffer, to.byteOffset, to.byteLength);
        const step = codec.gpu * codec.texels;
        for (let i = 0; (i + 1) * bytes <= to.length && (i + 1) * step <= from.length; i++) codec.pack(src, i * step, dst, i * bytes);
    }

    const api = { GXExecutor, GX, GX_MAGIC };
    if (isNode) module.exports = api;
    else global.V86GXExecutor = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                source/v64/src/browser/glbridge/gx/tessellator.js                                                   0000644 0000000 0000000 00000120122 00000000000 017230  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The D3D11 fixed-function tessellator: from a patch's tess factors, the
// domain points (u, v) and the primitives over them, exactly as D3D11
// hardware makes them. A port of Microsoft's reference (CHWTessellator in
// tessellator.cpp, MIT licensed, as Mesa carries it in
// src/gallium/auxiliary/tessellator): fixed-point 16.16 arithmetic, the
// ruler-function stitching of rows with different tess factors.
//
// GX runs the same algorithm on the GPU (tessellator.wgsl.js mirrors this
// file function by function); this one is the reference its tests compare
// with.
//
//   tessellate({ domain, partitioning, primitive, factors })
//     domain: 1 isoline, 2 tri, 3 quad (D3D11_SB_TESSELLATOR_DOMAIN)
//     partitioning: 1 integer, 2 pow2, 3 fractional_odd, 4 fractional_even
//     primitive: 1 point, 2 line, 3 triangle_cw, 4 triangle_ccw
//     factors: quad [Ueq0, Veq0, Ueq1, Veq1, insideU, insideV];
//              tri [Ueq0, Veq0, Weq0, inside]; isoline [density, detail]
//   -> { points: Float32Array of (u, v) pairs, indices: Int32Array }
(function(global) {
    "use strict";

    const PARTITIONING = { INTEGER: 1, POW2: 2, FRACTIONAL_ODD: 3, FRACTIONAL_EVEN: 4 };
    const PRIMITIVE = { POINT: 1, LINE: 2, TRIANGLE_CW: 3, TRIANGLE_CCW: 4 };
    const DOMAIN = { ISOLINE: 1, TRI: 2, QUAD: 3 };
    const EVEN = 0, ODD = 1;

    const FXP_FRACTION_BITS = 16, FXP_FRACTION_MASK = 0x0000ffff, FXP_INTEGER_MASK = 0x7fff0000;
    const FXP_ONE = 1 << FXP_FRACTION_BITS, FXP_ONE_THIRD = 0x00005555, FXP_TWO_THIRDS = 0x0000aaaa, FXP_ONE_HALF = 0x00008000;
    const MIN_ODD = 1, MAX_ODD = 63, MIN_EVEN = 2, MAX_EVEN = 64, MIN_DENSITY = 1, MAX_DENSITY = 64;
    const EPSILON = 0.0000152587890625;
    const MIN_ODD_PLUS_HALF_EPSILON = MIN_ODD + EPSILON / 2;

    const RECIPROCAL = [
        0xffffffff,
        0x10000, 0x8000, 0x5555, 0x4000, 0x3333, 0x2aab, 0x2492, 0x2000, 0x1c72, 0x199a, 0x1746, 0x1555, 0x13b1, 0x1249, 0x1111, 0x1000,
        0xf0f, 0xe39, 0xd79, 0xccd, 0xc31, 0xba3, 0xb21, 0xaab, 0xa3d, 0x9d9, 0x97b, 0x925, 0x8d4, 0x889, 0x842, 0x800,
        0x7c2, 0x788, 0x750, 0x71c, 0x6eb, 0x6bd, 0x690, 0x666, 0x63e, 0x618, 0x5f4, 0x5d1, 0x5b0, 0x591, 0x572, 0x555,
        0x539, 0x51f, 0x505, 0x4ec, 0x4d5, 0x4be, 0x4a8, 0x492, 0x47e, 0x46a, 0x457, 0x444, 0x432, 0x421, 0x410, 0x400,
    ];
    const FINAL_POINT_POSITION = [0, 32, 16, 8, 17, 4, 18, 9, 19, 2, 20, 10, 21, 5, 22, 11, 23,
        1, 24, 12, 25, 6, 26, 13, 27, 3, 28, 14, 29, 7, 30, 15, 31];
    const LOOP_START = [1, 1, 17, 9, 9, 5, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2];
    const LOOP_END = [0, 0, 17, 17, 25, 25, 25, 25, 29, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32];
    const DIAGONALS_INSIDE_TO_OUTSIDE = 0, DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE = 1, DIAGONALS_MIRRORED = 2;

    const f32 = Math.fround;

    /** IEEE 754 float to unsigned 15.16, round to nearest even (floatToIDotF) */
    function floatToFixed(x) {
        x = f32(x);
        if (Number.isNaN(x) || x <= 0) return 0;
        if (x >= 32768) return 0x7fffffff;
        const scaled = x * 65536;
        let r = Math.floor(scaled);
        const fraction = scaled - r;
        if (fraction > 0.5 || (fraction === 0.5 && (r & 1))) r++;
        return r >>> 0;
    }

    function fixedToFloat(x) {
        return f32((x >>> FXP_FRACTION_BITS) + (x & FXP_FRACTION_MASK) / (1 << FXP_FRACTION_BITS));
    }

    const isEven = x => !((x | 0) & 1);
    const fxpCeil = x => (x & FXP_FRACTION_MASK) ? ((x & FXP_INTEGER_MASK) + FXP_ONE) >>> 0 : x;
    const fxpFloor = x => (x & FXP_INTEGER_MASK) >>> 0;
    // IEEE 754R min and max: NaN in the second operand loses
    const fmin = (a, b) => Number.isNaN(b) ? a : (a < b ? a : b);
    const fmax = (a, b) => Number.isNaN(b) ? a : (a > b ? a : b);

    function removeMSB(val) {
        let check;
        if (val <= 0x0000ffff) check = val <= 0x000000ff ? 0x00000080 : 0x00008000;
        else check = val <= 0x00ffffff ? 0x00800000 : 0x80000000;
        for (let i = 0; i < 8; i++, check >>>= 1) if (val & check) return val & ~check;
        return 0;
    }

    class Tessellator {
        constructor(partitioning, primitive) {
            this.partitioning = this.originalPartitioning = partitioning;
            this.parity = this.originalParity = partitioning === PARTITIONING.FRACTIONAL_ODD ? ODD : EVEN;
            this.primitive = primitive;
            this.points = [];
            this.indices = [];
            this.numPoints = 0;
            this.numIndices = 0;
            this.patched = false;
            this.patched2 = false;
            this.ctx = {};
            this.ctx2 = {};
        }

        odd() { return this.parity === ODD; }
        hwInteger() { return this.partitioning === PARTITIONING.INTEGER || this.partitioning === PARTITIONING.POW2; }

        definePoint(u, v, offset) {
            this.points[offset * 2] = fixedToFloat(u);
            this.points[offset * 2 + 1] = fixedToFloat(v);
        }

        defineIndex(index, offset) {
            this.indices[offset] = this.patchIndexValue(index);
        }

        defineClockwiseTriangle(i0, i1, i2, base) {
            this.defineIndex(i0, base);
            if (this.primitive === PRIMITIVE.TRIANGLE_CW) {
                this.defineIndex(i1, base + 1);
                this.defineIndex(i2, base + 2);
            } else {
                this.defineIndex(i2, base + 1);
                this.defineIndex(i1, base + 2);
            }
        }

        dumpAllPoints() {
            for (let p = 0; p < this.numPoints; p++) this.defineIndex(p, this.numIndices++);
        }

        dumpAllPointsAsInOrderLineList() {
            for (let p = 1; p < this.numPoints; p++) {
                this.defineIndex(p - 1, this.numIndices++);
                this.defineIndex(p, this.numIndices++);
            }
        }

        numPointsForTessFactor(fxp) {
            if (this.odd()) return (fxpCeil(FXP_ONE_HALF + ((fxp + 1) >>> 1)) * 2) >>> FXP_FRACTION_BITS;
            return ((fxpCeil((fxp + 1) >>> 1) * 2) >>> FXP_FRACTION_BITS) + 1;
        }

        computeTessFactorContext(fxp) {
            const ctx = {};
            let half = (fxp + 1) >>> 1;
            if (this.odd() || half === FXP_ONE_HALF) half += FXP_ONE_HALF;
            const floorHalf = fxpFloor(half), ceilHalf = fxpCeil(half);
            ctx.halfTessFactorFraction = half - floorHalf;
            ctx.numHalfTessFactorPoints = ceilHalf >>> FXP_FRACTION_BITS;
            if (ceilHalf === floorHalf) {
                ctx.splitPointOnFloorHalfTessFactor = ctx.numHalfTessFactorPoints + 1;
            } else if (this.odd()) {
                ctx.splitPointOnFloorHalfTessFactor = floorHalf === FXP_ONE ? 0 : (removeMSB((floorHalf >>> FXP_FRACTION_BITS) - 1) << 1) + 1;
            } else {
                ctx.splitPointOnFloorHalfTessFactor = (removeMSB(floorHalf >>> FXP_FRACTION_BITS) << 1) + 1;
            }
            let floorSegments = (floorHalf * 2) >>> FXP_FRACTION_BITS;
            let ceilSegments = (ceilHalf * 2) >>> FXP_FRACTION_BITS;
            if (this.odd()) { floorSegments--; ceilSegments--; }
            ctx.invNumSegmentsOnFloorTessFactor = RECIPROCAL[floorSegments];
            ctx.invNumSegmentsOnCeilTessFactor = RECIPROCAL[ceilSegments];
            return ctx;
        }

        placePointIn1D(ctx, point) {
            let flip = false;
            if (point >= ctx.numHalfTessFactorPoints) {
                point = (ctx.numHalfTessFactorPoints << 1) - point;
                if (this.odd()) point--;
                flip = true;
            }
            if (point === ctx.numHalfTessFactorPoints) return FXP_ONE_HALF;
            const onCeil = point;
            let onFloor = onCeil;
            if (point > ctx.splitPointOnFloorHalfTessFactor) onFloor--;
            const locFloor = onFloor * ctx.invNumSegmentsOnFloorTessFactor;
            const locCeil = onCeil * ctx.invNumSegmentsOnCeilTessFactor;
            let location = locFloor * (FXP_ONE - ctx.halfTessFactorFraction) + locCeil * ctx.halfTessFactorFraction;
            location = Math.floor((location + FXP_ONE_HALF) / 65536);
            return flip ? FXP_ONE - location : location;
        }

        patchIndexValue(index) {
            if (this.patched) {
                const c = this.ctx;
                if (index >= c.outsidePointIndexPatchBase) {
                    index = index === c.outsidePointIndexBadValue ? c.outsidePointIndexReplacementValue : index + c.outsidePointIndexDeltaToRealValue;
                } else {
                    index = index === c.insidePointIndexBadValue ? c.insidePointIndexReplacementValue : index + c.insidePointIndexDeltaToRealValue;
                }
            } else if (this.patched2) {
                const c = this.ctx2;
                if (index >= c.baseIndexToInvert) {
                    index = index === c.cornerCaseBadValue ? c.cornerCaseReplacementValue : c.indexInversionEndPoint - index;
                } else if (index === c.cornerCaseBadValue) {
                    index = c.cornerCaseReplacementValue;
                }
            }
            return index;
        }

        stitchRegular(trapezoid, diagonals, base, numInsideEdgePoints, insideBase, outsideBase) {
            let inside = insideBase, outside = outsideBase;
            if (trapezoid) {
                this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                base += 3; outside++;
            }
            let p;
            switch (diagonals) {
                case DIAGONALS_INSIDE_TO_OUTSIDE:
                    for (p = 0; p < numInsideEdgePoints - 1; p++) {
                        this.defineClockwiseTriangle(inside, outside, outside + 1, base); base += 3;
                        this.defineClockwiseTriangle(inside, outside + 1, inside + 1, base); base += 3;
                        inside++; outside++;
                    }
                    break;
                case DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE:
                    for (p = 0; p < (numInsideEdgePoints >> 1) - 1; p++) {
                        this.defineClockwiseTriangle(outside, outside + 1, inside, base); base += 3;
                        this.defineClockwiseTriangle(inside, outside + 1, inside + 1, base); base += 3;
                        inside++; outside++;
                    }
                    this.defineClockwiseTriangle(outside, inside + 1, inside, base); base += 3;
                    this.defineClockwiseTriangle(outside, outside + 1, inside + 1, base); base += 3;
                    inside++; outside++; p += 2;
                    for (; p < numInsideEdgePoints; p++) {
                        this.defineClockwiseTriangle(outside, outside + 1, inside, base); base += 3;
                        this.defineClockwiseTriangle(inside, outside + 1, inside + 1, base); base += 3;
                        inside++; outside++;
                    }
                    break;
                case DIAGONALS_MIRRORED:
                    for (p = 0; p < (numInsideEdgePoints >> 1); p++) {
                        this.defineClockwiseTriangle(outside, inside + 1, inside, base); base += 3;
                        this.defineClockwiseTriangle(outside, outside + 1, inside + 1, base); base += 3;
                        inside++; outside++;
                    }
                    for (; p < numInsideEdgePoints - 1; p++) {
                        this.defineClockwiseTriangle(inside, outside, outside + 1, base); base += 3;
                        this.defineClockwiseTriangle(inside, outside + 1, inside + 1, base); base += 3;
                        inside++; outside++;
                    }
                    break;
            }
            if (trapezoid) {
                this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                base += 3;
            }
        }

        stitchTransition(base, insideBase, insideHalf, insideParity, outsideBase, outsideHalf, outsideParity) {
            if (insideParity === ODD) insideHalf--;
            if (outsideParity === ODD) outsideHalf--;
            let outside = outsideBase, inside = insideBase;
            const start = Math.min(LOOP_START[insideHalf], LOOP_START[outsideHalf]);
            const end = Math.max(LOOP_END[insideHalf], LOOP_END[outsideHalf]);
            if (FINAL_POINT_POSITION[0] < outsideHalf) {
                this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                base += 3; outside++;
            }
            for (let i = start; i <= end; i++) {
                if (FINAL_POINT_POSITION[i] < insideHalf) {
                    this.defineClockwiseTriangle(inside, outside, inside + 1, base);
                    base += 3; inside++;
                }
                if (FINAL_POINT_POSITION[i] < outsideHalf) {
                    this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                    base += 3; outside++;
                }
            }
            if (insideParity !== outsideParity || insideParity === ODD) {
                if (insideParity === outsideParity) {
                    this.defineClockwiseTriangle(inside, outside, inside + 1, base); base += 3;
                    this.defineClockwiseTriangle(inside + 1, outside, outside + 1, base); base += 3;
                    inside++; outside++;
                } else if (insideParity === EVEN) {
                    this.defineClockwiseTriangle(inside, outside, outside + 1, base); base += 3;
                    outside++;
                } else {
                    this.defineClockwiseTriangle(inside, outside, inside + 1, base); base += 3;
                    inside++;
                }
            }
            for (let i = end; i >= start; i--) {
                if (FINAL_POINT_POSITION[i] < outsideHalf) {
                    this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                    base += 3; outside++;
                }
                if (FINAL_POINT_POSITION[i] < insideHalf) {
                    this.defineClockwiseTriangle(inside, outside, inside + 1, base);
                    base += 3; inside++;
                }
            }
            if (FINAL_POINT_POSITION[0] < outsideHalf) {
                this.defineClockwiseTriangle(outside, outside + 1, inside, base);
                base += 3; outside++;
            }
        }

        /** The bounds of the partitioning's tess factors */
        bounds() {
            switch (this.originalPartitioning) {
                case PARTITIONING.FRACTIONAL_EVEN: return [MIN_EVEN, MAX_EVEN];
                case PARTITIONING.FRACTIONAL_ODD: return [MIN_ODD, MAX_ODD];
                default: return [MIN_ODD, MAX_EVEN];
            }
        }

        // -------------------------------------------------------------- quad

        tessellateQuad(Ueq0, Veq0, Ueq1, Veq1, insideU, insideV) {
            const pf = this.quadProcess(f32(Ueq0), f32(Veq0), f32(Ueq1), f32(Veq1), f32(insideU), f32(insideV));
            if (pf.culled) { this.numPoints = 0; this.numIndices = 0; return; }
            if (pf.minimum) {
                this.definePoint(0, 0, 0);
                this.definePoint(FXP_ONE, 0, 1);
                this.definePoint(FXP_ONE, FXP_ONE, 2);
                this.definePoint(0, FXP_ONE, 3);
                this.numPoints = 4;
                if (this.primitive === PRIMITIVE.TRIANGLE_CW || this.primitive === PRIMITIVE.TRIANGLE_CCW) {
                    this.defineClockwiseTriangle(0, 1, 3, 0);
                    this.defineClockwiseTriangle(1, 2, 3, 3);
                    this.numIndices = 6;
                } else if (this.primitive === PRIMITIVE.POINT) {
                    this.dumpAllPoints();
                } else {
                    this.dumpAllPointsAsInOrderLineList();
                }
                return;
            }
            this.quadGeneratePoints(pf);
            if (this.primitive === PRIMITIVE.POINT) return this.dumpAllPoints();
            if (this.primitive === PRIMITIVE.LINE) return this.dumpAllPointsAsInOrderLineList();
            this.quadGenerateConnectivity(pf);
        }

        quadProcess(Ueq0, Veq0, Ueq1, Veq1, insideU, insideV) {
            const pf = { culled: false, minimum: false };
            if (!(Ueq0 > 0) || !(Veq0 > 0) || !(Ueq1 > 0) || !(Veq1 > 0)) { pf.culled = true; return pf; }
            let [lower, upper] = this.bounds();
            const clamp = x => f32(fmin(upper, fmax(lower, x)));
            Ueq0 = clamp(Ueq0); Veq0 = clamp(Veq0); Ueq1 = clamp(Ueq1); Veq1 = clamp(Veq1);
            if (this.hwInteger()) { Ueq0 = Math.ceil(Ueq0); Veq0 = Math.ceil(Veq0); Ueq1 = Math.ceil(Ueq1); Veq1 = Math.ceil(Veq1); }
            if (this.originalPartitioning === PARTITIONING.FRACTIONAL_ODD) {
                if (Ueq0 > MIN_ODD_PLUS_HALF_EPSILON || Veq0 > MIN_ODD_PLUS_HALF_EPSILON || Ueq1 > MIN_ODD_PLUS_HALF_EPSILON ||
                    Veq1 > MIN_ODD_PLUS_HALF_EPSILON || insideU > MIN_ODD_PLUS_HALF_EPSILON || insideV > MIN_ODD_PLUS_HALF_EPSILON) {
                    lower = f32(MIN_ODD + EPSILON);
                }
            }
            insideU = clamp(insideU); insideV = clamp(insideV);
            if (this.hwInteger()) { insideU = Math.ceil(insideU); insideV = Math.ceil(insideV); }
            this.numPoints = 0;
            this.numIndices = 0;
            const outside = [Ueq0, Veq0, Ueq1, Veq1], inside = [insideU, insideV];
            pf.outsideParity = []; pf.insideParity = [];
            if (this.hwInteger()) {
                for (let e = 0; e < 4; e++) pf.outsideParity[e] = isEven(outside[e]) ? EVEN : ODD;
                for (let a = 0; a < 2; a++) pf.insideParity[a] = isEven(inside[a]) || inside[a] === 1 ? EVEN : ODD;
            } else {
                for (let e = 0; e < 4; e++) pf.outsideParity[e] = this.originalParity;
                pf.insideParity[0] = pf.insideParity[1] = this.originalParity;
            }
            pf.outside = outside.map(floatToFixed);
            pf.inside = inside.map(floatToFixed);
            if (this.hwInteger() || this.odd()) {
                if (pf.inside[0] === FXP_ONE && pf.inside[1] === FXP_ONE && pf.outside.every(x => x === FXP_ONE)) {
                    pf.minimum = true;
                    return pf;
                }
            }
            pf.outsideCtx = []; pf.insideCtx = [];
            for (let e = 0; e < 4; e++) { this.parity = pf.outsideParity[e]; pf.outsideCtx[e] = this.computeTessFactorContext(pf.outside[e]); }
            for (let a = 0; a < 2; a++) { this.parity = pf.insideParity[a]; pf.insideCtx[a] = this.computeTessFactorContext(pf.inside[a]); }
            pf.numPointsForOutsideEdge = [];
            for (let e = 0; e < 4; e++) {
                this.parity = pf.outsideParity[e];
                pf.numPointsForOutsideEdge[e] = this.numPointsForTessFactor(pf.outside[e]);
                this.numPoints += pf.numPointsForOutsideEdge[e];
            }
            this.numPoints -= 4;
            pf.numPointsForInside = [];
            for (let a = 0; a < 2; a++) {
                this.parity = pf.insideParity[a];
                const min = pf.insideParity[a] === ODD ? 4 : 3;
                pf.numPointsForInside[a] = Math.max(min, this.numPointsForTessFactor(pf.inside[a]));
            }
            pf.insideEdgePointBaseOffset = this.numPoints;
            this.numPoints += (pf.numPointsForInside[0] - 2) * (pf.numPointsForInside[1] - 2);
            return pf;
        }

        quadGeneratePoints(pf) {
            let offset = 0;
            for (let edge = 0; edge < 4; edge++) {
                const parity = edge & 1;
                const end = pf.numPointsForOutsideEdge[edge] - 1;
                for (let p = 0; p < end; p++, offset++) {
                    const q = edge === 1 || edge === 2 ? p : end - p;
                    this.parity = pf.outsideParity[edge];
                    const param = this.placePointIn1D(pf.outsideCtx[edge], q);
                    if (parity) this.definePoint(param, edge === 3 ? FXP_ONE : 0, offset);
                    else this.definePoint(edge === 2 ? FXP_ONE : 0, param, offset);
                }
            }
            const minPoints = Math.min(pf.numPointsForInside[0], pf.numPointsForInside[1]);
            const numRings = minPoints >> 1;
            for (let ring = 1; ring < numRings; ring++) {
                const start = ring;
                const end = [pf.numPointsForInside[0] - 1 - start, pf.numPointsForInside[1] - 1 - start];
                for (let edge = 0; edge < 4; edge++) {
                    const parity = [edge & 1, (edge + 1) & 1];
                    const perpPoint = edge < 2 ? start : end[parity[0]];
                    this.parity = pf.insideParity[parity[0]];
                    const perp = this.placePointIn1D(pf.insideCtx[parity[0]], perpPoint);
                    this.parity = pf.insideParity[parity[1]];
                    for (let p = start; p < end[parity[1]]; p++, offset++) {
                        const q = edge === 1 || edge === 2 ? p : end[parity[1]] - (p - start);
                        const param = this.placePointIn1D(pf.insideCtx[parity[1]], q);
                        if (parity[1]) this.definePoint(perp, param, offset);
                        else this.definePoint(param, perp, offset);
                    }
                }
            }
            if (pf.numPointsForInside[0] > pf.numPointsForInside[1] && pf.insideParity[1] === EVEN) {
                const start = numRings, end = pf.numPointsForInside[0] - 1 - start;
                this.parity = pf.insideParity[0];
                for (let p = start; p <= end; p++, offset++) {
                    this.definePoint(this.placePointIn1D(pf.insideCtx[0], p), FXP_ONE_HALF, offset);
                }
            } else if (pf.numPointsForInside[1] >= pf.numPointsForInside[0] && pf.insideParity[0] === EVEN) {
                const start = numRings, end = pf.numPointsForInside[1] - 1 - start;
                this.parity = pf.insideParity[1];
                for (let p = end; p >= start; p--, offset++) {
                    this.definePoint(FXP_ONE_HALF, this.placePointIn1D(pf.insideCtx[1], p), offset);
                }
            }
        }

        quadGenerateConnectivity(pf) {
            const rowsToCenter = [(pf.numPointsForInside[0] + 1) >> 1, (pf.numPointsForInside[1] + 1) >> 1];
            const numRings = Math.min(rowsToCenter[0], rowsToCenter[1]);
            const degenerateRing = [pf.insideParity[1] === EVEN ? rowsToCenter[1] - 1 : -1, pf.insideParity[0] === EVEN ? rowsToCenter[0] - 1 : -1];
            const outsideCtx = pf.outsideCtx.slice(), outsideParity = pf.outsideParity.slice(), numPointsForOutsideEdge = pf.numPointsForOutsideEdge.slice();
            let insideEdgeBase = pf.insideEdgePointBaseOffset, outsideEdgeBase = 0;
            for (let ring = 1; ring < numRings; ring++) {
                const numInside = [pf.numPointsForInside[0] - 2 * ring, pf.numPointsForInside[1] - 2 * ring];
                const edge0InsideBase = insideEdgeBase, edge0OutsideBase = outsideEdgeBase;
                for (let edge = 0; edge < 4; edge++) {
                    const parity = (edge + 1) & 1;
                    const numTriangles = numInside[parity] + numPointsForOutsideEdge[edge] - 2;
                    let insideBase, outsideBase;
                    if (edge === 3) {
                        if (ring === degenerateRing[parity]) {
                            const c = this.ctx2;
                            c.baseIndexToInvert = insideEdgeBase + 1;
                            c.cornerCaseBadValue = outsideEdgeBase + numPointsForOutsideEdge[edge] - 1;
                            c.cornerCaseReplacementValue = edge0OutsideBase;
                            c.indexInversionEndPoint = (c.baseIndexToInvert << 1) - 1;
                            insideBase = c.baseIndexToInvert;
                            outsideBase = outsideEdgeBase;
                            this.patched2 = true;
                        } else {
                            const c = this.ctx;
                            c.insidePointIndexDeltaToRealValue = insideEdgeBase;
                            c.insidePointIndexBadValue = numInside[parity] - 1;
                            c.insidePointIndexReplacementValue = edge0InsideBase;
                            c.outsidePointIndexPatchBase = c.insidePointIndexBadValue + 1;
                            c.outsidePointIndexDeltaToRealValue = outsideEdgeBase - c.outsidePointIndexPatchBase;
                            c.outsidePointIndexBadValue = c.outsidePointIndexPatchBase + numPointsForOutsideEdge[edge] - 1;
                            c.outsidePointIndexReplacementValue = edge0OutsideBase;
                            insideBase = 0;
                            outsideBase = c.outsidePointIndexPatchBase;
                            this.patched = true;
                        }
                    } else if (edge === 2 && ring === degenerateRing[parity]) {
                        const c = this.ctx2;
                        c.baseIndexToInvert = insideEdgeBase;
                        c.cornerCaseBadValue = -1;
                        c.cornerCaseReplacementValue = -1;
                        c.indexInversionEndPoint = c.baseIndexToInvert << 1;
                        insideBase = c.baseIndexToInvert;
                        outsideBase = outsideEdgeBase;
                        this.patched2 = true;
                    } else {
                        insideBase = insideEdgeBase;
                        outsideBase = outsideEdgeBase;
                    }
                    if (ring === 1) {
                        this.stitchTransition(this.numIndices, insideBase, pf.insideCtx[parity].numHalfTessFactorPoints, pf.insideParity[parity],
                            outsideBase, outsideCtx[edge].numHalfTessFactorPoints, outsideParity[edge]);
                    } else {
                        this.stitchRegular(true, DIAGONALS_MIRRORED, this.numIndices, numInside[parity], insideBase, outsideBase);
                    }
                    this.patched = false;
                    this.patched2 = false;
                    this.numIndices += numTriangles * 3;
                    outsideEdgeBase += numPointsForOutsideEdge[edge] - 1;
                    if (edge === 2 && ring === degenerateRing[parity]) insideEdgeBase -= numInside[parity] - 1;
                    else insideEdgeBase += numInside[parity] - 1;
                    numPointsForOutsideEdge[edge] = numInside[parity];
                }
                if (ring === 1) {
                    for (let edge = 0; edge < 4; edge++) {
                        outsideCtx[edge] = pf.insideCtx[edge & 1];
                        outsideParity[edge] = pf.insideParity[edge & 1];
                    }
                }
            }
            if (pf.numPointsForInside[0] > pf.numPointsForInside[1] && pf.insideParity[1] === ODD) {
                this.patched2 = true;
                const quads = (((pf.numPointsForInside[0] >> 1) - (pf.numPointsForInside[1] >> 1)) << 1) + (pf.insideParity[0] === EVEN ? 2 : 1);
                const c = this.ctx2;
                c.baseIndexToInvert = outsideEdgeBase + quads + 2;
                c.cornerCaseBadValue = c.baseIndexToInvert;
                c.cornerCaseReplacementValue = outsideEdgeBase;
                c.indexInversionEndPoint = c.baseIndexToInvert + c.baseIndexToInvert + quads;
                this.stitchRegular(false, DIAGONALS_INSIDE_TO_OUTSIDE, this.numIndices, quads + 1, c.baseIndexToInvert, outsideEdgeBase + 1);
                this.patched2 = false;
                this.numIndices += quads * 6;
            } else if (pf.numPointsForInside[1] >= pf.numPointsForInside[0] && pf.insideParity[0] === ODD) {
                this.patched2 = true;
                const quads = (((pf.numPointsForInside[1] >> 1) - (pf.numPointsForInside[0] >> 1)) << 1) + (pf.insideParity[1] === EVEN ? 2 : 1);
                const c = this.ctx2;
                c.baseIndexToInvert = outsideEdgeBase + quads + 1;
                c.cornerCaseBadValue = -1;
                c.indexInversionEndPoint = c.baseIndexToInvert + c.baseIndexToInvert + quads;
                const diagonals = pf.insideParity[1] === EVEN ? DIAGONALS_INSIDE_TO_OUTSIDE : DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE;
                this.stitchRegular(false, diagonals, this.numIndices, quads + 1, c.baseIndexToInvert, outsideEdgeBase);
                this.patched2 = false;
                this.numIndices += quads * 6;
            }
        }

        // --------------------------------------------------------------- tri

        tessellateTri(Ueq0, Veq0, Weq0, inside) {
            const pf = this.triProcess(f32(Ueq0), f32(Veq0), f32(Weq0), f32(inside));
            if (pf.culled) { this.numPoints = 0; this.numIndices = 0; return; }
            if (pf.minimum) {
                this.definePoint(0, FXP_ONE, 0);
                this.definePoint(0, 0, 1);
                this.definePoint(FXP_ONE, 0, 2);
                this.numPoints = 3;
                if (this.primitive === PRIMITIVE.TRIANGLE_CW || this.primitive === PRIMITIVE.TRIANGLE_CCW) {
                    this.defineClockwiseTriangle(0, 1, 2, this.numIndices);
                    this.numIndices = 3;
                } else if (this.primitive === PRIMITIVE.POINT) {
                    this.dumpAllPoints();
                } else {
                    this.dumpAllPointsAsInOrderLineList();
                }
                return;
            }
            this.triGeneratePoints(pf);
            if (this.primitive === PRIMITIVE.POINT) return this.dumpAllPoints();
            if (this.primitive === PRIMITIVE.LINE) return this.dumpAllPointsAsInOrderLineList();
            this.triGenerateConnectivity(pf);
        }

        triProcess(Ueq0, Veq0, Weq0, inside) {
            const pf = { culled: false, minimum: false };
            if (!(Ueq0 > 0) || !(Veq0 > 0) || !(Weq0 > 0)) { pf.culled = true; return pf; }
            let [lower, upper] = this.bounds();
            const clamp = x => f32(fmin(upper, fmax(lower, x)));
            Ueq0 = clamp(Ueq0); Veq0 = clamp(Veq0); Weq0 = clamp(Weq0);
            if (this.hwInteger()) { Ueq0 = Math.ceil(Ueq0); Veq0 = Math.ceil(Veq0); Weq0 = Math.ceil(Weq0); }
            if (this.originalPartitioning === PARTITIONING.FRACTIONAL_ODD) {
                if (Ueq0 > MIN_ODD_PLUS_HALF_EPSILON || Veq0 > MIN_ODD_PLUS_HALF_EPSILON || Weq0 > MIN_ODD_PLUS_HALF_EPSILON) {
                    lower = f32(MIN_ODD + EPSILON);
                }
            }
            inside = clamp(inside);
            if (this.hwInteger()) inside = Math.ceil(inside);
            this.numPoints = 0;
            this.numIndices = 0;
            const outside = [Ueq0, Veq0, Weq0];
            pf.outsideParity = [];
            if (this.hwInteger()) {
                for (let e = 0; e < 3; e++) pf.outsideParity[e] = isEven(outside[e]) ? EVEN : ODD;
                pf.insideParity = isEven(inside) || inside === 1 ? EVEN : ODD;
            } else {
                for (let e = 0; e < 3; e++) pf.outsideParity[e] = this.originalParity;
                pf.insideParity = this.originalParity;
            }
            pf.outside = outside.map(floatToFixed);
            pf.inside = floatToFixed(inside);
            if (this.hwInteger() || this.odd()) {
                if (pf.inside === FXP_ONE && pf.outside.every(x => x === FXP_ONE)) { pf.minimum = true; return pf; }
            }
            pf.outsideCtx = [];
            for (let e = 0; e < 3; e++) { this.parity = pf.outsideParity[e]; pf.outsideCtx[e] = this.computeTessFactorContext(pf.outside[e]); }
            this.parity = pf.insideParity;
            pf.insideCtx = this.computeTessFactorContext(pf.inside);
            pf.numPointsForOutsideEdge = [];
            for (let e = 0; e < 3; e++) {
                this.parity = pf.outsideParity[e];
                pf.numPointsForOutsideEdge[e] = this.numPointsForTessFactor(pf.outside[e]);
                this.numPoints += pf.numPointsForOutsideEdge[e];
            }
            this.numPoints -= 3;
            this.parity = pf.insideParity;
            pf.numPointsForInside = Math.max(this.odd() ? 4 : 3, this.numPointsForTessFactor(pf.inside));
            pf.insideEdgePointBaseOffset = this.numPoints;
            const rings = (pf.numPointsForInside >> 1) - 1;
            this.numPoints += this.odd() ? 3 * (rings * (rings + 1) - rings) : 3 * (rings * (rings + 1)) + 1;
            return pf;
        }

        triGeneratePoints(pf) {
            let offset = 0;
            for (let edge = 0; edge < 3; edge++) {
                const parity = edge & 1;
                const end = pf.numPointsForOutsideEdge[edge] - 1;
                for (let p = 0; p < end; p++, offset++) {
                    const q = parity ? p : end - p;
                    this.parity = pf.outsideParity[edge];
                    const param = this.placePointIn1D(pf.outsideCtx[edge], q);
                    if (edge === 0) this.definePoint(0, param, offset);
                    else this.definePoint(param, edge === 2 ? FXP_ONE - param : 0, offset);
                }
            }
            this.parity = pf.insideParity;
            const numRings = pf.numPointsForInside >> 1;
            for (let ring = 1; ring < numRings; ring++) {
                const start = ring, end = pf.numPointsForInside - 1 - start;
                for (let edge = 0; edge < 3; edge++) {
                    const parity = edge & 1;
                    let perp = this.placePointIn1D(pf.insideCtx, start);
                    perp = Math.floor((perp * FXP_TWO_THIRDS + FXP_ONE_HALF) / 65536);
                    for (let p = start; p < end; p++, offset++) {
                        const q = parity ? p : end - (p - start);
                        const param = this.placePointIn1D(pf.insideCtx, q);
                        const shifted = param - ((perp + 1) >>> 1);
                        if (edge === 0) this.definePoint(perp, shifted, offset);
                        else if (edge === 1) this.definePoint(shifted, perp, offset);
                        else this.definePoint(shifted, FXP_ONE - shifted - perp, offset);
                    }
                }
            }
            if (!this.odd()) this.definePoint(FXP_ONE_THIRD, FXP_ONE_THIRD, offset);
        }

        triGenerateConnectivity(pf) {
            const numRings = (pf.numPointsForInside + 1) >> 1;
            const outsideCtx = pf.outsideCtx.slice(), outsideParity = pf.outsideParity.slice(), numPointsForOutsideEdge = pf.numPointsForOutsideEdge.slice();
            let insideEdgeBase = pf.insideEdgePointBaseOffset, outsideEdgeBase = 0;
            for (let ring = 1; ring < numRings; ring++) {
                const numInside = pf.numPointsForInside - 2 * ring;
                const edge0InsideBase = insideEdgeBase, edge0OutsideBase = outsideEdgeBase;
                for (let edge = 0; edge < 3; edge++) {
                    const numTriangles = numInside + numPointsForOutsideEdge[edge] - 2;
                    let insideBase, outsideBase;
                    if (edge === 2) {
                        const c = this.ctx;
                        c.insidePointIndexDeltaToRealValue = insideEdgeBase;
                        c.insidePointIndexBadValue = numInside - 1;
                        c.insidePointIndexReplacementValue = edge0InsideBase;
                        c.outsidePointIndexPatchBase = c.insidePointIndexBadValue + 1;
                        c.outsidePointIndexDeltaToRealValue = outsideEdgeBase - c.outsidePointIndexPatchBase;
                        c.outsidePointIndexBadValue = c.outsidePointIndexPatchBase + numPointsForOutsideEdge[edge] - 1;
                        c.outsidePointIndexReplacementValue = edge0OutsideBase;
                        this.patched = true;
                        insideBase = 0;
                        outsideBase = c.outsidePointIndexPatchBase;
                    } else {
                        insideBase = insideEdgeBase;
                        outsideBase = outsideEdgeBase;
                    }
                    if (ring === 1) {
                        this.stitchTransition(this.numIndices, insideBase, pf.insideCtx.numHalfTessFactorPoints, pf.insideParity,
                            outsideBase, outsideCtx[edge].numHalfTessFactorPoints, outsideParity[edge]);
                    } else {
                        this.stitchRegular(true, DIAGONALS_MIRRORED, this.numIndices, numInside, insideBase, outsideBase);
                    }
                    if (edge === 2) this.patched = false;
                    this.numIndices += numTriangles * 3;
                    outsideEdgeBase += numPointsForOutsideEdge[edge] - 1;
                    insideEdgeBase += numInside - 1;
                    numPointsForOutsideEdge[edge] = numInside;
                }
                if (ring === 1) {
                    for (let edge = 0; edge < 3; edge++) {
                        outsideCtx[edge] = pf.insideCtx;
                        outsideParity[edge] = pf.insideParity;
                    }
                }
            }
            if (this.odd()) {
                this.defineClockwiseTriangle(outsideEdgeBase, outsideEdgeBase + 1, outsideEdgeBase + 2, this.numIndices);
                this.numIndices += 3;
            }
        }

        // ----------------------------------------------------------- isoline

        tessellateIsoLine(density, detail) {
            density = f32(density); detail = f32(detail);
            if (!(density > 0) || !(detail > 0)) { this.numPoints = 0; this.numIndices = 0; return; }
            const [lower, upper] = this.bounds();
            density = f32(fmin(MAX_DENSITY, fmax(MIN_DENSITY, density)));
            detail = f32(fmin(upper, fmax(lower, detail)));
            this.numPoints = 0;
            this.numIndices = 0;
            let detailParity;
            if (this.hwInteger()) {
                detail = Math.ceil(detail);
                detailParity = isEven(detail) ? EVEN : ODD;
            } else {
                detailParity = this.originalParity;
            }
            const fxpDetail = floatToFixed(detail);
            this.parity = detailParity;
            const detailCtx = this.computeTessFactorContext(fxpDetail);
            const pointsPerLine = this.numPointsForTessFactor(fxpDetail);
            this.partitioning = PARTITIONING.INTEGER;
            density = Math.ceil(density);
            const densityParity = isEven(density) ? EVEN : ODD;
            this.parity = densityParity;
            const fxpDensity = floatToFixed(density);
            const densityCtx = this.computeTessFactorContext(fxpDensity);
            const numLines = this.numPointsForTessFactor(fxpDensity) - 1;
            this.partitioning = this.originalPartitioning;
            this.numPoints = pointsPerLine * numLines;
            let offset = 0;
            for (let line = 0; line < numLines; line++) {
                for (let point = 0; point < pointsPerLine; point++) {
                    this.parity = densityParity;
                    const v = this.placePointIn1D(densityCtx, line);
                    this.parity = detailParity;
                    const u = this.placePointIn1D(detailCtx, point);
                    this.definePoint(u, v, offset++);
                }
            }
            offset = 0;
            let index = 0;
            for (let line = 0; line < numLines; line++) {
                for (let point = 0; point < pointsPerLine; point++) {
                    if (this.primitive === PRIMITIVE.POINT) {
                        this.defineIndex(offset, index++);
                    } else if (point > 0) {
                        this.defineIndex(offset - 1, index++);
                        this.defineIndex(offset, index++);
                    }
                    offset++;
                }
            }
            this.numIndices = index;
        }
    }

    function tessellate({ domain, partitioning, primitive, factors }) {
        // (lines and points from tri and quad domains come out as in D3D11's reference)
        const t = new Tessellator(partitioning, primitive);
        if (domain === DOMAIN.QUAD) t.tessellateQuad(...factors);
        else if (domain === DOMAIN.TRI) t.tessellateTri(...factors);
        else t.tessellateIsoLine(factors[0], factors[1]);
        return { points: Float32Array.from(t.points.slice(0, t.numPoints * 2)), indices: Int32Array.from(t.indices.slice(0, t.numIndices)) };
    }

    const exports = { tessellate, PARTITIONING, PRIMITIVE, DOMAIN, floatToFixed };
    if (typeof module === "object" && module.exports) module.exports = exports;
    else global.V86Tessellator = exports;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/browser/glbridge/gx/tessellator_wgsl.js                                              0000644 0000000 0000000 00000107306 00000000000 020275  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The D3D11 tessellator on the GPU: tessellator.js (the reference port, see
// there) in WGSL, function by function. One invocation per pi; three
// entry points, run in order:
//   count:    each patch's points and indices
//   scan:     where each patch's go (exclusive prefix sums, so primitives
//             keep D3D's order), the indirect arguments: the domain
//             shader's dispatch and the draw
//   generate: the points (u, v, pi) and the indices, at those places
//
// Bindings (group 0): 0 GXTessParams (uniform), 1 the hull shader's
// records (each patch's tess factors at factor_at: edges, then inside), 2
// counts, 3 offsets, 4 points, 5 indices, 6 the indirect arguments
// (dispatch x y z, then draw vertex count, instances, first vertex, first
// instance).
(function(global) {
    "use strict";

    const TESSELLATOR_WGSL = /* wgsl */ `
struct GXTessParams {
    patches: u32,
    domain: u32,        // 1 isoline, 2 tri, 3 quad
    partitioning: u32,  // 1 integer, 2 pow2, 3 fractional_odd, 4 fractional_even
    primitive: u32,     // 1 point, 2 line, 3 triangle_cw, 4 triangle_ccw
    record: u32,        // vec4s per pi in hull
    factor_at: u32,     // the tess factors' first vec4 in a record
    max_points: u32,    // the room in points
    max_indices: u32,   // the room in indices
}
@group(0) @binding(0) var<uniform> tp: GXTessParams;
@group(0) @binding(1) var<storage, read> hull: array<vec4<u32>>;
@group(0) @binding(2) var<storage, read_write> counts: array<vec2<u32>>;
@group(0) @binding(3) var<storage, read_write> offsets: array<vec2<u32>>;
@group(0) @binding(4) var<storage, read_write> points: array<vec4<u32>>;
@group(0) @binding(5) var<storage, read_write> indices: array<u32>;
@group(0) @binding(6) var<storage, read_write> args: array<u32>;

const EVEN = 0;
const ODD = 1;
const P_INTEGER = 1u;
const P_POW2 = 2u;
const P_FRACTIONAL_ODD = 3u;
const P_FRACTIONAL_EVEN = 4u;
const O_POINT = 1u;
const O_LINE = 2u;
const O_TRIANGLE_CW = 3u;
const O_TRIANGLE_CCW = 4u;
const FXP_ONE = 0x10000u;
const FXP_ONE_THIRD = 0x5555u;
const FXP_TWO_THIRDS = 0xaaaau;
const FXP_ONE_HALF = 0x8000u;
const FXP_FRACTION_MASK = 0xffffu;
const FXP_INTEGER_MASK = 0x7fff0000u;
const EPSILON = 0.0000152587890625;
const MIN_ODD_PLUS_HALF_EPSILON = 1.00000762939453125;
const DIAGONALS_INSIDE_TO_OUTSIDE = 0;
const DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE = 1;
const DIAGONALS_MIRRORED = 2;

var<private> RECIPROCAL: array<u32, 65> = array<u32, 65>(0xffffffffu,
    0x10000u, 0x8000u, 0x5555u, 0x4000u, 0x3333u, 0x2aabu, 0x2492u, 0x2000u, 0x1c72u, 0x199au, 0x1746u, 0x1555u, 0x13b1u, 0x1249u, 0x1111u, 0x1000u,
    0xf0fu, 0xe39u, 0xd79u, 0xccdu, 0xc31u, 0xba3u, 0xb21u, 0xaabu, 0xa3du, 0x9d9u, 0x97bu, 0x925u, 0x8d4u, 0x889u, 0x842u, 0x800u,
    0x7c2u, 0x788u, 0x750u, 0x71cu, 0x6ebu, 0x6bdu, 0x690u, 0x666u, 0x63eu, 0x618u, 0x5f4u, 0x5d1u, 0x5b0u, 0x591u, 0x572u, 0x555u,
    0x539u, 0x51fu, 0x505u, 0x4ecu, 0x4d5u, 0x4beu, 0x4a8u, 0x492u, 0x47eu, 0x46au, 0x457u, 0x444u, 0x432u, 0x421u, 0x410u, 0x400u);
var<private> FINAL_POINT_POSITION: array<i32, 33> = array<i32, 33>(0, 32, 16, 8, 17, 4, 18, 9, 19, 2, 20, 10, 21, 5, 22, 11, 23,
    1, 24, 12, 25, 6, 26, 13, 27, 3, 28, 14, 29, 7, 30, 15, 31);
var<private> LOOP_START: array<i32, 33> = array<i32, 33>(1, 1, 17, 9, 9, 5, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2);
var<private> LOOP_END: array<i32, 33> = array<i32, 33>(0, 0, 17, 17, 25, 25, 25, 25, 29, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32);

struct Ctx { frac: u32, half: i32, split: i32, inv_floor: u32, inv_ceil: u32 }

// the tessellator's state
var<private> parity: i32;
var<private> original_parity: i32;
var<private> partitioning: u32;
var<private> original_partitioning: u32;
var<private> num_points: i32;
var<private> num_indices: i32;
var<private> patched: bool;
var<private> patched2: bool;
// INDEX_PATCH_CONTEXT
var<private> c_in_delta: i32;
var<private> c_in_bad: i32;
var<private> c_in_replace: i32;
var<private> c_out_base: i32;
var<private> c_out_delta: i32;
var<private> c_out_bad: i32;
var<private> c_out_replace: i32;
// INDEX_PATCH_CONTEXT2
var<private> c2_invert: i32;
var<private> c2_end: i32;
var<private> c2_bad: i32;
var<private> c2_replace: i32;
// the processed tess factors (quad: all; tri: outside 0..2, inside 0)
var<private> pf_culled: bool;
var<private> pf_minimum: bool;
var<private> pf_outside: array<u32, 4>;
var<private> pf_inside: array<u32, 2>;
var<private> pf_outside_parity: array<i32, 4>;
var<private> pf_inside_parity: array<i32, 2>;
var<private> pf_outside_ctx: array<Ctx, 4>;
var<private> pf_inside_ctx: array<Ctx, 2>;
var<private> pf_n_outside: array<i32, 4>;
var<private> pf_n_inside: array<i32, 2>;
var<private> pf_inside_base: i32;
// where this patch's points and indices go; whether they are written
var<private> writing: bool;
var<private> point_base: u32;
var<private> index_base: u32;
var<private> patch_id: u32;

fn is_nan(x: f32) -> bool { return (bitcast<u32>(x) & 0x7fffffffu) > 0x7f800000u; }
// IEEE 754R min and max: a NaN second operand loses
fn fmin_(a: f32, b: f32) -> f32 { if (is_nan(b)) { return a; } return select(b, a, a < b); }
fn fmax_(a: f32, b: f32) -> f32 { if (is_nan(b)) { return a; } return select(b, a, a > b); }
fn positive(x: f32) -> bool { return !is_nan(x) && x > 0.0; }

fn float_to_fixed(x: f32) -> u32 {
    if (!positive(x)) { return 0u; }
    if (x >= 32768.0) { return 0x7fffffffu; }
    return u32(round(x * 65536.0));
}
fn fixed_to_float(x: u32) -> f32 { return f32(x >> 16u) + f32(x & FXP_FRACTION_MASK) / 65536.0; }
fn is_even(x: f32) -> bool { return (i32(x) & 1) == 0; }
fn fxp_ceil(x: u32) -> u32 { if ((x & FXP_FRACTION_MASK) != 0u) { return (x & FXP_INTEGER_MASK) + FXP_ONE; } return x; }
fn fxp_floor(x: u32) -> u32 { return x & FXP_INTEGER_MASK; }
fn odd() -> bool { return parity == ODD; }
fn hw_integer() -> bool { return partitioning == P_INTEGER || partitioning == P_POW2; }

fn remove_msb(val: i32) -> i32 {
    let v = u32(val);
    var check: u32;
    if (v <= 0xffffu) { check = select(0x8000u, 0x80u, v <= 0xffu); } else { check = select(0x80000000u, 0x800000u, v <= 0xffffffu); }
    for (var i = 0; i < 8; i++) {
        if ((v & check) != 0u) { return i32(v & ~check); }
        check = check >> 1u;
    }
    return 0;
}

fn define_point(u: u32, v: u32, offset: i32) {
    if (writing && point_base + u32(offset) < tp.max_points) {
        points[point_base + u32(offset)] = vec4<u32>(bitcast<u32>(fixed_to_float(u)), bitcast<u32>(fixed_to_float(v)), patch_id, 0u);
    }
}

fn patch_index_value(index_in: i32) -> i32 {
    var index = index_in;
    if (patched) {
        if (index >= c_out_base) {
            index = select(index + c_out_delta, c_out_replace, index == c_out_bad);
        } else {
            index = select(index + c_in_delta, c_in_replace, index == c_in_bad);
        }
    } else if (patched2) {
        if (index >= c2_invert) {
            index = select(c2_end - index, c2_replace, index == c2_bad);
        } else if (index == c2_bad) {
            index = c2_replace;
        }
    }
    return index;
}

fn define_index(index: i32, offset: i32) {
    let value = patch_index_value(index);
    if (writing && index_base + u32(offset) < tp.max_indices) {
        indices[index_base + u32(offset)] = point_base + u32(value);
    }
}

fn define_clockwise_triangle(i0: i32, i1: i32, i2: i32, base: i32) {
    define_index(i0, base);
    if (tp.primitive == O_TRIANGLE_CW) {
        define_index(i1, base + 1);
        define_index(i2, base + 2);
    } else {
        define_index(i2, base + 1);
        define_index(i1, base + 2);
    }
}

fn dump_all_points() {
    for (var p = 0; p < num_points; p++) { define_index(p, num_indices); num_indices++; }
}

fn dump_all_points_as_line_list() {
    for (var p = 1; p < num_points; p++) {
        define_index(p - 1, num_indices); num_indices++;
        define_index(p, num_indices); num_indices++;
    }
}

fn num_points_for_tess_factor(fxp: u32) -> i32 {
    if (odd()) { return i32((fxp_ceil(FXP_ONE_HALF + ((fxp + 1u) >> 1u)) * 2u) >> 16u); }
    return i32((fxp_ceil((fxp + 1u) >> 1u) * 2u) >> 16u) + 1;
}

fn compute_ctx(fxp: u32) -> Ctx {
    var ctx: Ctx;
    var half = (fxp + 1u) >> 1u;
    if (odd() || half == FXP_ONE_HALF) { half += FXP_ONE_HALF; }
    let floor_half = fxp_floor(half);
    let ceil_half = fxp_ceil(half);
    ctx.frac = half - floor_half;
    ctx.half = i32(ceil_half >> 16u);
    if (ceil_half == floor_half) {
        ctx.split = ctx.half + 1;
    } else if (odd()) {
        if (floor_half == FXP_ONE) { ctx.split = 0; } else { ctx.split = (remove_msb(i32(floor_half >> 16u) - 1) << 1u) + 1; }
    } else {
        ctx.split = (remove_msb(i32(floor_half >> 16u)) << 1u) + 1;
    }
    var floor_segments = i32((floor_half * 2u) >> 16u);
    var ceil_segments = i32((ceil_half * 2u) >> 16u);
    if (odd()) { floor_segments -= 1; ceil_segments -= 1; }
    ctx.inv_floor = RECIPROCAL[floor_segments];
    ctx.inv_ceil = RECIPROCAL[ceil_segments];
    return ctx;
}

fn place_point_1d(ctx: Ctx, point_in: i32) -> u32 {
    var point = point_in;
    var flip = false;
    if (point >= ctx.half) {
        point = (ctx.half << 1u) - point;
        if (odd()) { point -= 1; }
        flip = true;
    }
    if (point == ctx.half) { return FXP_ONE_HALF; }
    let on_ceil = u32(point);
    var on_floor = on_ceil;
    if (point > ctx.split) { on_floor -= 1u; }
    let loc_floor = on_floor * ctx.inv_floor;
    let loc_ceil = on_ceil * ctx.inv_ceil;
    var location = loc_floor * (FXP_ONE - ctx.frac) + loc_ceil * ctx.frac;
    location = (location + FXP_ONE_HALF) >> 16u;
    if (flip) { location = FXP_ONE - location; }
    return location;
}

fn stitch_regular(trapezoid: bool, diagonals: i32, base_in: i32, num_inside_points: i32, inside_base: i32, outside_base: i32) {
    var base = base_in;
    var inside = inside_base;
    var outside = outside_base;
    if (trapezoid) {
        define_clockwise_triangle(outside, outside + 1, inside, base);
        base += 3; outside++;
    }
    var p: i32;
    if (diagonals == DIAGONALS_INSIDE_TO_OUTSIDE) {
        for (p = 0; p < num_inside_points - 1; p++) {
            define_clockwise_triangle(inside, outside, outside + 1, base); base += 3;
            define_clockwise_triangle(inside, outside + 1, inside + 1, base); base += 3;
            inside++; outside++;
        }
    } else if (diagonals == DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE) {
        for (p = 0; p < (num_inside_points >> 1u) - 1; p++) {
            define_clockwise_triangle(outside, outside + 1, inside, base); base += 3;
            define_clockwise_triangle(inside, outside + 1, inside + 1, base); base += 3;
            inside++; outside++;
        }
        define_clockwise_triangle(outside, inside + 1, inside, base); base += 3;
        define_clockwise_triangle(outside, outside + 1, inside + 1, base); base += 3;
        inside++; outside++; p += 2;
        for (; p < num_inside_points; p++) {
            define_clockwise_triangle(outside, outside + 1, inside, base); base += 3;
            define_clockwise_triangle(inside, outside + 1, inside + 1, base); base += 3;
            inside++; outside++;
        }
    } else {
        for (p = 0; p < (num_inside_points >> 1u); p++) {
            define_clockwise_triangle(outside, inside + 1, inside, base); base += 3;
            define_clockwise_triangle(outside, outside + 1, inside + 1, base); base += 3;
            inside++; outside++;
        }
        for (; p < num_inside_points - 1; p++) {
            define_clockwise_triangle(inside, outside, outside + 1, base); base += 3;
            define_clockwise_triangle(inside, outside + 1, inside + 1, base); base += 3;
            inside++; outside++;
        }
    }
    if (trapezoid) {
        define_clockwise_triangle(outside, outside + 1, inside, base);
        base += 3;
    }
}

fn stitch_transition(base_in: i32, inside_base: i32, inside_half_in: i32, inside_parity: i32,
                     outside_base: i32, outside_half_in: i32, outside_parity: i32) {
    var base = base_in;
    var inside_half = inside_half_in;
    var outside_half = outside_half_in;
    if (inside_parity == ODD) { inside_half -= 1; }
    if (outside_parity == ODD) { outside_half -= 1; }
    var outside = outside_base;
    var inside = inside_base;
    let start = min(LOOP_START[inside_half], LOOP_START[outside_half]);
    let end = max(LOOP_END[inside_half], LOOP_END[outside_half]);
    if (FINAL_POINT_POSITION[0] < outside_half) {
        define_clockwise_triangle(outside, outside + 1, inside, base);
        base += 3; outside++;
    }
    for (var i = start; i <= end; i++) {
        if (FINAL_POINT_POSITION[i] < inside_half) {
            define_clockwise_triangle(inside, outside, inside + 1, base);
            base += 3; inside++;
        }
        if (FINAL_POINT_POSITION[i] < outside_half) {
            define_clockwise_triangle(outside, outside + 1, inside, base);
            base += 3; outside++;
        }
    }
    if (inside_parity != outside_parity || inside_parity == ODD) {
        if (inside_parity == outside_parity) {
            define_clockwise_triangle(inside, outside, inside + 1, base); base += 3;
            define_clockwise_triangle(inside + 1, outside, outside + 1, base); base += 3;
            inside++; outside++;
        } else if (inside_parity == EVEN) {
            define_clockwise_triangle(inside, outside, outside + 1, base); base += 3;
            outside++;
        } else {
            define_clockwise_triangle(inside, outside, inside + 1, base); base += 3;
            inside++;
        }
    }
    for (var i = end; i >= start; i--) {
        if (FINAL_POINT_POSITION[i] < outside_half) {
            define_clockwise_triangle(outside, outside + 1, inside, base);
            base += 3; outside++;
        }
        if (FINAL_POINT_POSITION[i] < inside_half) {
            define_clockwise_triangle(inside, outside, inside + 1, base);
            base += 3; inside++;
        }
    }
    if (FINAL_POINT_POSITION[0] < outside_half) {
        define_clockwise_triangle(outside, outside + 1, inside, base);
        base += 3; outside++;
    }
}

fn lower_bound() -> f32 {
    if (original_partitioning == P_FRACTIONAL_EVEN) { return 2.0; }
    return 1.0;
}
fn upper_bound() -> f32 {
    if (original_partitioning == P_FRACTIONAL_ODD) { return 63.0; }
    return 64.0;
}
fn clamp_factor(x: f32, lower: f32, upper: f32) -> f32 { return fmin_(upper, fmax_(lower, x)); }

// ---------------------------------------------------------------- quad

fn quad_process(ue0_in: f32, ve0_in: f32, ue1_in: f32, ve1_in: f32, iu_in: f32, iv_in: f32) {
    pf_culled = false;
    pf_minimum = false;
    if (!positive(ue0_in) || !positive(ve0_in) || !positive(ue1_in) || !positive(ve1_in)) { pf_culled = true; return; }
    var lower = lower_bound();
    let upper = upper_bound();
    var outside = array<f32, 4>(clamp_factor(ue0_in, lower, upper), clamp_factor(ve0_in, lower, upper),
        clamp_factor(ue1_in, lower, upper), clamp_factor(ve1_in, lower, upper));
    if (hw_integer()) { for (var e = 0; e < 4; e++) { outside[e] = ceil(outside[e]); } }
    if (original_partitioning == P_FRACTIONAL_ODD) {
        if (outside[0] > MIN_ODD_PLUS_HALF_EPSILON || outside[1] > MIN_ODD_PLUS_HALF_EPSILON || outside[2] > MIN_ODD_PLUS_HALF_EPSILON ||
            outside[3] > MIN_ODD_PLUS_HALF_EPSILON || iu_in > MIN_ODD_PLUS_HALF_EPSILON || iv_in > MIN_ODD_PLUS_HALF_EPSILON) {
            lower = 1.0 + EPSILON;
        }
    }
    var inside = array<f32, 2>(clamp_factor(iu_in, lower, upper), clamp_factor(iv_in, lower, upper));
    if (hw_integer()) { inside[0] = ceil(inside[0]); inside[1] = ceil(inside[1]); }
    num_points = 0;
    num_indices = 0;
    if (hw_integer()) {
        for (var e = 0; e < 4; e++) { pf_outside_parity[e] = select(ODD, EVEN, is_even(outside[e])); }
        for (var a = 0; a < 2; a++) { pf_inside_parity[a] = select(ODD, EVEN, is_even(inside[a]) || inside[a] == 1.0); }
    } else {
        for (var e = 0; e < 4; e++) { pf_outside_parity[e] = original_parity; }
        pf_inside_parity[0] = original_parity;
        pf_inside_parity[1] = original_parity;
    }
    for (var e = 0; e < 4; e++) { pf_outside[e] = float_to_fixed(outside[e]); }
    for (var a = 0; a < 2; a++) { pf_inside[a] = float_to_fixed(inside[a]); }
    if (hw_integer() || odd()) {
        if (pf_inside[0] == FXP_ONE && pf_inside[1] == FXP_ONE && pf_outside[0] == FXP_ONE && pf_outside[1] == FXP_ONE &&
            pf_outside[2] == FXP_ONE && pf_outside[3] == FXP_ONE) {
            pf_minimum = true;
            return;
        }
    }
    for (var e = 0; e < 4; e++) { parity = pf_outside_parity[e]; pf_outside_ctx[e] = compute_ctx(pf_outside[e]); }
    for (var a = 0; a < 2; a++) { parity = pf_inside_parity[a]; pf_inside_ctx[a] = compute_ctx(pf_inside[a]); }
    for (var e = 0; e < 4; e++) {
        parity = pf_outside_parity[e];
        pf_n_outside[e] = num_points_for_tess_factor(pf_outside[e]);
        num_points += pf_n_outside[e];
    }
    num_points -= 4;
    for (var a = 0; a < 2; a++) {
        parity = pf_inside_parity[a];
        let least = select(3, 4, pf_inside_parity[a] == ODD);
        pf_n_inside[a] = max(least, num_points_for_tess_factor(pf_inside[a]));
    }
    pf_inside_base = num_points;
    num_points += (pf_n_inside[0] - 2) * (pf_n_inside[1] - 2);
}

fn quad_generate_points() {
    var offset = 0;
    for (var edge = 0; edge < 4; edge++) {
        let par = edge & 1;
        let end = pf_n_outside[edge] - 1;
        for (var p = 0; p < end; p++) {
            let q = select(end - p, p, edge == 1 || edge == 2);
            parity = pf_outside_parity[edge];
            let param = place_point_1d(pf_outside_ctx[edge], q);
            if (par != 0) { define_point(param, select(0u, FXP_ONE, edge == 3), offset); }
            else { define_point(select(0u, FXP_ONE, edge == 2), param, offset); }
            offset++;
        }
    }
    let num_rings = min(pf_n_inside[0], pf_n_inside[1]) >> 1u;
    for (var ring = 1; ring < num_rings; ring++) {
        let start = ring;
        var end = array<i32, 2>(pf_n_inside[0] - 1 - start, pf_n_inside[1] - 1 - start);
        for (var edge = 0; edge < 4; edge++) {
            let par0 = edge & 1;
            let par1 = (edge + 1) & 1;
            let perp_point = select(end[par0], start, edge < 2);
            parity = pf_inside_parity[par0];
            let perp = place_point_1d(pf_inside_ctx[par0], perp_point);
            parity = pf_inside_parity[par1];
            for (var p = start; p < end[par1]; p++) {
                let q = select(end[par1] - (p - start), p, edge == 1 || edge == 2);
                let param = place_point_1d(pf_inside_ctx[par1], q);
                if (par1 != 0) { define_point(perp, param, offset); } else { define_point(param, perp, offset); }
                offset++;
            }
        }
    }
    if (pf_n_inside[0] > pf_n_inside[1] && pf_inside_parity[1] == EVEN) {
        let start = num_rings;
        let end = pf_n_inside[0] - 1 - start;
        parity = pf_inside_parity[0];
        for (var p = start; p <= end; p++) { define_point(place_point_1d(pf_inside_ctx[0], p), FXP_ONE_HALF, offset); offset++; }
    } else if (pf_n_inside[1] >= pf_n_inside[0] && pf_inside_parity[0] == EVEN) {
        let start = num_rings;
        let end = pf_n_inside[1] - 1 - start;
        parity = pf_inside_parity[1];
        for (var p = end; p >= start; p--) { define_point(FXP_ONE_HALF, place_point_1d(pf_inside_ctx[1], p), offset); offset++; }
    }
}

fn quad_generate_connectivity() {
    var rows = array<i32, 2>((pf_n_inside[0] + 1) >> 1u, (pf_n_inside[1] + 1) >> 1u);
    let num_rings = min(rows[0], rows[1]);
    var degenerate = array<i32, 2>(select(-1, rows[1] - 1, pf_inside_parity[1] == EVEN), select(-1, rows[0] - 1, pf_inside_parity[0] == EVEN));
    var outside_half: array<i32, 4>;
    var outside_parity: array<i32, 4>;
    var n_outside: array<i32, 4>;
    for (var e = 0; e < 4; e++) { outside_half[e] = pf_outside_ctx[e].half; outside_parity[e] = pf_outside_parity[e]; n_outside[e] = pf_n_outside[e]; }
    var inside_edge_base = pf_inside_base;
    var outside_edge_base = 0;
    for (var ring = 1; ring < num_rings; ring++) {
        var n_inside = array<i32, 2>(pf_n_inside[0] - 2 * ring, pf_n_inside[1] - 2 * ring);
        let edge0_inside_base = inside_edge_base;
        let edge0_outside_base = outside_edge_base;
        for (var edge = 0; edge < 4; edge++) {
            let par = (edge + 1) & 1;
            let num_triangles = n_inside[par] + n_outside[edge] - 2;
            var inside_base: i32;
            var outside_base: i32;
            if (edge == 3) {
                if (ring == degenerate[par]) {
                    c2_invert = inside_edge_base + 1;
                    c2_bad = outside_edge_base + n_outside[edge] - 1;
                    c2_replace = edge0_outside_base;
                    c2_end = (c2_invert << 1u) - 1;
                    inside_base = c2_invert;
                    outside_base = outside_edge_base;
                    patched2 = true;
                } else {
                    c_in_delta = inside_edge_base;
                    c_in_bad = n_inside[par] - 1;
                    c_in_replace = edge0_inside_base;
                    c_out_base = c_in_bad + 1;
                    c_out_delta = outside_edge_base - c_out_base;
                    c_out_bad = c_out_base + n_outside[edge] - 1;
                    c_out_replace = edge0_outside_base;
                    inside_base = 0;
                    outside_base = c_out_base;
                    patched = true;
                }
            } else if (edge == 2 && ring == degenerate[par]) {
                c2_invert = inside_edge_base;
                c2_bad = -1;
                c2_replace = -1;
                c2_end = c2_invert << 1u;
                inside_base = c2_invert;
                outside_base = outside_edge_base;
                patched2 = true;
            } else {
                inside_base = inside_edge_base;
                outside_base = outside_edge_base;
            }
            if (ring == 1) {
                stitch_transition(num_indices, inside_base, pf_inside_ctx[par].half, pf_inside_parity[par],
                    outside_base, outside_half[edge], outside_parity[edge]);
            } else {
                stitch_regular(true, DIAGONALS_MIRRORED, num_indices, n_inside[par], inside_base, outside_base);
            }
            patched = false;
            patched2 = false;
            num_indices += num_triangles * 3;
            outside_edge_base += n_outside[edge] - 1;
            if (edge == 2 && ring == degenerate[par]) { inside_edge_base -= n_inside[par] - 1; }
            else { inside_edge_base += n_inside[par] - 1; }
            n_outside[edge] = n_inside[par];
        }
        if (ring == 1) {
            for (var e = 0; e < 4; e++) { outside_half[e] = pf_inside_ctx[e & 1].half; outside_parity[e] = pf_inside_parity[e & 1]; }
        }
    }
    if (pf_n_inside[0] > pf_n_inside[1] && pf_inside_parity[1] == ODD) {
        patched2 = true;
        let quads = (((pf_n_inside[0] >> 1u) - (pf_n_inside[1] >> 1u)) << 1u) + select(1, 2, pf_inside_parity[0] == EVEN);
        c2_invert = outside_edge_base + quads + 2;
        c2_bad = c2_invert;
        c2_replace = outside_edge_base;
        c2_end = c2_invert + c2_invert + quads;
        stitch_regular(false, DIAGONALS_INSIDE_TO_OUTSIDE, num_indices, quads + 1, c2_invert, outside_edge_base + 1);
        patched2 = false;
        num_indices += quads * 6;
    } else if (pf_n_inside[1] >= pf_n_inside[0] && pf_inside_parity[0] == ODD) {
        patched2 = true;
        let quads = (((pf_n_inside[1] >> 1u) - (pf_n_inside[0] >> 1u)) << 1u) + select(1, 2, pf_inside_parity[1] == EVEN);
        c2_invert = outside_edge_base + quads + 1;
        c2_bad = -1;
        c2_end = c2_invert + c2_invert + quads;
        let diagonals = select(DIAGONALS_INSIDE_TO_OUTSIDE_EXCEPT_MIDDLE, DIAGONALS_INSIDE_TO_OUTSIDE, pf_inside_parity[1] == EVEN);
        stitch_regular(false, diagonals, num_indices, quads + 1, c2_invert, outside_edge_base);
        patched2 = false;
        num_indices += quads * 6;
    }
}

fn tessellate_quad(f: array<f32, 6>) {
    quad_process(f[0], f[1], f[2], f[3], f[4], f[5]);
    if (pf_culled) { num_points = 0; num_indices = 0; return; }
    if (pf_minimum) {
        define_point(0u, 0u, 0);
        define_point(FXP_ONE, 0u, 1);
        define_point(FXP_ONE, FXP_ONE, 2);
        define_point(0u, FXP_ONE, 3);
        num_points = 4;
        if (tp.primitive == O_TRIANGLE_CW || tp.primitive == O_TRIANGLE_CCW) {
            define_clockwise_triangle(0, 1, 3, 0);
            define_clockwise_triangle(1, 2, 3, 3);
            num_indices = 6;
        } else if (tp.primitive == O_POINT) {
            dump_all_points();
        } else {
            dump_all_points_as_line_list();
        }
        return;
    }
    quad_generate_points();
    if (tp.primitive == O_POINT) { dump_all_points(); return; }
    if (tp.primitive == O_LINE) { dump_all_points_as_line_list(); return; }
    quad_generate_connectivity();
}

// ----------------------------------------------------------------- tri

fn tri_process(ue0_in: f32, ve0_in: f32, we0_in: f32, inside_in: f32) {
    pf_culled = false;
    pf_minimum = false;
    if (!positive(ue0_in) || !positive(ve0_in) || !positive(we0_in)) { pf_culled = true; return; }
    var lower = lower_bound();
    let upper = upper_bound();
    var outside = array<f32, 3>(clamp_factor(ue0_in, lower, upper), clamp_factor(ve0_in, lower, upper), clamp_factor(we0_in, lower, upper));
    if (hw_integer()) { for (var e = 0; e < 3; e++) { outside[e] = ceil(outside[e]); } }
    if (original_partitioning == P_FRACTIONAL_ODD) {
        if (outside[0] > MIN_ODD_PLUS_HALF_EPSILON || outside[1] > MIN_ODD_PLUS_HALF_EPSILON || outside[2] > MIN_ODD_PLUS_HALF_EPSILON) {
            lower = 1.0 + EPSILON;
        }
    }
    var inside = clamp_factor(inside_in, lower, upper);
    if (hw_integer()) { inside = ceil(inside); }
    num_points = 0;
    num_indices = 0;
    if (hw_integer()) {
        for (var e = 0; e < 3; e++) { pf_outside_parity[e] = select(ODD, EVEN, is_even(outside[e])); }
        pf_inside_parity[0] = select(ODD, EVEN, is_even(inside) || inside == 1.0);
    } else {
        for (var e = 0; e < 3; e++) { pf_outside_parity[e] = original_parity; }
        pf_inside_parity[0] = original_parity;
    }
    for (var e = 0; e < 3; e++) { pf_outside[e] = float_to_fixed(outside[e]); }
    pf_inside[0] = float_to_fixed(inside);
    if (hw_integer() || odd()) {
        if (pf_inside[0] == FXP_ONE && pf_outside[0] == FXP_ONE && pf_outside[1] == FXP_ONE && pf_outside[2] == FXP_ONE) {
            pf_minimum = true;
            return;
        }
    }
    for (var e = 0; e < 3; e++) { parity = pf_outside_parity[e]; pf_outside_ctx[e] = compute_ctx(pf_outside[e]); }
    parity = pf_inside_parity[0];
    pf_inside_ctx[0] = compute_ctx(pf_inside[0]);
    for (var e = 0; e < 3; e++) {
        parity = pf_outside_parity[e];
        pf_n_outside[e] = num_points_for_tess_factor(pf_outside[e]);
        num_points += pf_n_outside[e];
    }
    num_points -= 3;
    parity = pf_inside_parity[0];
    pf_n_inside[0] = max(select(3, 4, odd()), num_points_for_tess_factor(pf_inside[0]));
    pf_inside_base = num_points;
    let rings = (pf_n_inside[0] >> 1u) - 1;
    if (odd()) { num_points += 3 * (rings * (rings + 1) - rings); } else { num_points += 3 * (rings * (rings + 1)) + 1; }
}

fn tri_generate_points() {
    var offset = 0;
    for (var edge = 0; edge < 3; edge++) {
        let par = edge & 1;
        let end = pf_n_outside[edge] - 1;
        for (var p = 0; p < end; p++) {
            let q = select(end - p, p, par != 0);
            parity = pf_outside_parity[edge];
            let param = place_point_1d(pf_outside_ctx[edge], q);
            if (edge == 0) { define_point(0u, param, offset); }
            else { define_point(param, select(0u, FXP_ONE - param, edge == 2), offset); }
            offset++;
        }
    }
    parity = pf_inside_parity[0];
    let num_rings = pf_n_inside[0] >> 1u;
    for (var ring = 1; ring < num_rings; ring++) {
        let start = ring;
        let end = pf_n_inside[0] - 1 - start;
        for (var edge = 0; edge < 3; edge++) {
            let par = edge & 1;
            var perp = place_point_1d(pf_inside_ctx[0], start);
            perp = (perp * FXP_TWO_THIRDS + FXP_ONE_HALF) >> 16u;
            for (var p = start; p < end; p++) {
                let q = select(end - (p - start), p, par != 0);
                let param = place_point_1d(pf_inside_ctx[0], q);
                let shifted = param - ((perp + 1u) >> 1u);
                if (edge == 0) { define_point(perp, shifted, offset); }
                else if (edge == 1) { define_point(shifted, perp, offset); }
                else { define_point(shifted, FXP_ONE - shifted - perp, offset); }
                offset++;
            }
        }
    }
    if (!odd()) { define_point(FXP_ONE_THIRD, FXP_ONE_THIRD, offset); }
}

fn tri_generate_connectivity() {
    let num_rings = (pf_n_inside[0] + 1) >> 1u;
    var outside_half: array<i32, 3>;
    var outside_parity: array<i32, 3>;
    var n_outside: array<i32, 3>;
    for (var e = 0; e < 3; e++) { outside_half[e] = pf_outside_ctx[e].half; outside_parity[e] = pf_outside_parity[e]; n_outside[e] = pf_n_outside[e]; }
    var inside_edge_base = pf_inside_base;
    var outside_edge_base = 0;
    for (var ring = 1; ring < num_rings; ring++) {
        let n_inside = pf_n_inside[0] - 2 * ring;
        let edge0_inside_base = inside_edge_base;
        let edge0_outside_base = outside_edge_base;
        for (var edge = 0; edge < 3; edge++) {
            let num_triangles = n_inside + n_outside[edge] - 2;
            var inside_base: i32;
            var outside_base: i32;
            if (edge == 2) {
                c_in_delta = inside_edge_base;
                c_in_bad = n_inside - 1;
                c_in_replace = edge0_inside_base;
                c_out_base = c_in_bad + 1;
                c_out_delta = outside_edge_base - c_out_base;
                c_out_bad = c_out_base + n_outside[edge] - 1;
                c_out_replace = edge0_outside_base;
                patched = true;
                inside_base = 0;
                outside_base = c_out_base;
            } else {
                inside_base = inside_edge_base;
                outside_base = outside_edge_base;
            }
            if (ring == 1) {
                stitch_transition(num_indices, inside_base, pf_inside_ctx[0].half, pf_inside_parity[0],
                    outside_base, outside_half[edge], outside_parity[edge]);
            } else {
                stitch_regular(true, DIAGONALS_MIRRORED, num_indices, n_inside, inside_base, outside_base);
            }
            if (edge == 2) { patched = false; }
            num_indices += num_triangles * 3;
            outside_edge_base += n_outside[edge] - 1;
            inside_edge_base += n_inside - 1;
            n_outside[edge] = n_inside;
        }
        if (ring == 1) {
            for (var e = 0; e < 3; e++) { outside_half[e] = pf_inside_ctx[0].half; outside_parity[e] = pf_inside_parity[0]; }
        }
    }
    if (odd()) {
        define_clockwise_triangle(outside_edge_base, outside_edge_base + 1, outside_edge_base + 2, num_indices);
        num_indices += 3;
    }
}

fn tessellate_tri(f: array<f32, 6>) {
    tri_process(f[0], f[1], f[2], f[3]);
    if (pf_culled) { num_points = 0; num_indices = 0; return; }
    if (pf_minimum) {
        define_point(0u, FXP_ONE, 0);
        define_point(0u, 0u, 1);
        define_point(FXP_ONE, 0u, 2);
        num_points = 3;
        if (tp.primitive == O_TRIANGLE_CW || tp.primitive == O_TRIANGLE_CCW) {
            define_clockwise_triangle(0, 1, 2, num_indices);
            num_indices = 3;
        } else if (tp.primitive == O_POINT) {
            dump_all_points();
        } else {
            dump_all_points_as_line_list();
        }
        return;
    }
    tri_generate_points();
    if (tp.primitive == O_POINT) { dump_all_points(); return; }
    if (tp.primitive == O_LINE) { dump_all_points_as_line_list(); return; }
    tri_generate_connectivity();
}

// ------------------------------------------------------------- isoline

fn tessellate_isoline(density_in: f32, detail_in: f32) {
    if (!positive(density_in) || !positive(detail_in)) { num_points = 0; num_indices = 0; return; }
    var density = fmin_(64.0, fmax_(1.0, density_in));
    var detail = clamp_factor(detail_in, lower_bound(), upper_bound());
    num_points = 0;
    num_indices = 0;
    var detail_parity: i32;
    if (hw_integer()) {
        detail = ceil(detail);
        detail_parity = select(ODD, EVEN, is_even(detail));
    } else {
        detail_parity = original_parity;
    }
    let fxp_detail = float_to_fixed(detail);
    parity = detail_parity;
    let detail_ctx = compute_ctx(fxp_detail);
    let per_line = num_points_for_tess_factor(fxp_detail);
    partitioning = P_INTEGER;
    density = ceil(density);
    let density_parity = select(ODD, EVEN, is_even(density));
    parity = density_parity;
    let fxp_density = float_to_fixed(density);
    let density_ctx = compute_ctx(fxp_density);
    let lines = num_points_for_tess_factor(fxp_density) - 1;
    partitioning = original_partitioning;
    num_points = per_line * lines;
    var offset = 0;
    for (var line = 0; line < lines; line++) {
        for (var point = 0; point < per_line; point++) {
            parity = density_parity;
            let v = place_point_1d(density_ctx, line);
            parity = detail_parity;
            let u = place_point_1d(detail_ctx, point);
            define_point(u, v, offset);
            offset++;
        }
    }
    offset = 0;
    var index = 0;
    for (var line = 0; line < lines; line++) {
        for (var point = 0; point < per_line; point++) {
            if (tp.primitive == O_POINT) {
                define_index(offset, index); index++;
            } else if (point > 0) {
                define_index(offset - 1, index); index++;
                define_index(offset, index); index++;
            }
            offset++;
        }
    }
    num_indices = index;
}

// -------------------------------------------------------- entry points

fn tessellate(pi: u32) {
    patch_id = pi;
    partitioning = tp.partitioning;
    original_partitioning = tp.partitioning;
    parity = select(EVEN, ODD, tp.partitioning == P_FRACTIONAL_ODD);
    original_parity = parity;
    num_points = 0;
    num_indices = 0;
    patched = false;
    patched2 = false;
    let at = pi * tp.record + tp.factor_at;
    let a = bitcast<vec4<f32>>(hull[at]);
    let b = bitcast<vec4<f32>>(hull[at + 1u]);
    var f = array<f32, 6>(a.x, a.y, a.z, a.w, b.x, b.y);
    if (tp.domain == 3u) { tessellate_quad(f); }
    else if (tp.domain == 2u) { tessellate_tri(f); }
    else { tessellate_isoline(f[0], f[1]); }
}

@compute @workgroup_size(64) fn count(@builtin(global_invocation_id) gid: vec3<u32>) {
    let pi = gid.x + gid.y * 65535u * 64u;
    if (pi >= tp.patches) { return; }
    writing = false;
    tessellate(pi);
    counts[pi] = vec2<u32>(u32(num_points), u32(num_indices));
}

@compute @workgroup_size(1) fn scan() {
    var total = vec2<u32>(0u, 0u);
    for (var pi = 0u; pi < tp.patches; pi++) {
        offsets[pi] = total;
        total += counts[pi];
    }
    // (past the room: as many as fit)
    total = min(total, vec2<u32>(tp.max_points, tp.max_indices));
    let groups = (total.x + 63u) / 64u;
    args[0] = min(groups, 65535u);
    args[1] = (groups + 65534u) / 65535u;
    args[2] = 1u;
    args[3] = total.y;
    args[4] = 1u;
    args[5] = 0u;
    args[6] = 0u;
    args[7] = total.x;
}

@compute @workgroup_size(64) fn generate(@builtin(global_invocation_id) gid: vec3<u32>) {
    let pi = gid.x + gid.y * 65535u * 64u;
    if (pi >= tp.patches) { return; }
    writing = true;
    point_base = offsets[pi].x;
    index_base = offsets[pi].y;
    tessellate(pi);
}
`;

    const exports = { TESSELLATOR_WGSL };
    if (typeof module === "object" && module.exports) module.exports = exports;
    else global.V86TessellatorWGSL = exports;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                          source/v64/src/browser/glbridge/package.json                                                        0000644 0000000 0000000 00000000043 00000000000 016200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {"type":"commonjs","private":true}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/browser/glbridge/shader_ir/dxbc_frontend.js                                          0000644 0000000 0000000 00000064771 00000000000 021051  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VGPU10 shader tokens (SM4.0, SM4.1, SM5.0: the DXBC SHEX instruction
// stream VMware's SVGA DX commands carry, plus its VMWARE opcodes) decoded
// into the shader IR wgsl_emitter.js turns into WGSL (docs/gpu-devices.md,
// "GX"). The IR is the instruction list with its operands spelled out, and
// the declarations gathered by kind. virgl's TGSI comes here too, as VGPU10
// tokens (src/graphics_adapters/virtio_gpu/tgsi_vgpu10.js).
//
// Token layout: VGPU10ShaderTokens.h (third_party/vmware-svga). A program is
// a version token, a length token (dwords, both included), then
// instructions: an opcode token (opcode, controls, length, extended), maybe
// extended opcode tokens, then operands: an operand token, maybe an extended
// operand token (modifiers), then per index dimension an immediate or a
// relative operand, or for immediates their 1 or 4 values.
//
// decode(Uint32Array) -> { type, major, minor, decls, code, icb, temps,
//     indexable, signature }; a malformed program throws ShaderDecodeError.
(function(global) {
    "use strict";

    class ShaderDecodeError extends Error {}

    const PROGRAM = { PS: 0, VS: 1, GS: 2, HS: 3, DS: 4, CS: 5 };
    const PROGRAM_NAMES = ["ps", "vs", "gs", "hs", "ds", "cs"];

    // Opcodes (VGPU10_OPCODE_TYPE)
    const OP = {
        ADD: 0, AND: 1, BREAK: 2, BREAKC: 3, CALL: 4, CALLC: 5, CASE: 6, CONTINUE: 7, CONTINUEC: 8,
        CUT: 9, DEFAULT: 10, DERIV_RTX: 11, DERIV_RTY: 12, DISCARD: 13, DIV: 14, DP2: 15, DP3: 16, DP4: 17,
        ELSE: 18, EMIT: 19, EMITTHENCUT: 20, ENDIF: 21, ENDLOOP: 22, ENDSWITCH: 23, EQ: 24, EXP: 25,
        FRC: 26, FTOI: 27, FTOU: 28, GE: 29, IADD: 30, IF: 31, IEQ: 32, IGE: 33, ILT: 34, IMAD: 35,
        IMAX: 36, IMIN: 37, IMUL: 38, INE: 39, INEG: 40, ISHL: 41, ISHR: 42, ITOF: 43, LABEL: 44,
        LD: 45, LD_MS: 46, LOG: 47, LOOP: 48, LT: 49, MAD: 50, MIN: 51, MAX: 52, CUSTOMDATA: 53,
        MOV: 54, MOVC: 55, MUL: 56, NE: 57, NOP: 58, NOT: 59, OR: 60, RESINFO: 61, RET: 62, RETC: 63,
        ROUND_NE: 64, ROUND_NI: 65, ROUND_PI: 66, ROUND_Z: 67, RSQ: 68, SAMPLE: 69, SAMPLE_C: 70,
        SAMPLE_C_LZ: 71, SAMPLE_L: 72, SAMPLE_D: 73, SAMPLE_B: 74, SQRT: 75, SWITCH: 76, SINCOS: 77,
        UDIV: 78, ULT: 79, UGE: 80, UMUL: 81, UMAD: 82, UMAX: 83, UMIN: 84, USHR: 85, UTOF: 86, XOR: 87,
        DCL_RESOURCE: 88, DCL_CONSTANT_BUFFER: 89, DCL_SAMPLER: 90, DCL_INDEX_RANGE: 91,
        DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY: 92, DCL_GS_INPUT_PRIMITIVE: 93, DCL_MAX_OUTPUT_VERTEX_COUNT: 94,
        DCL_INPUT: 95, DCL_INPUT_SGV: 96, DCL_INPUT_SIV: 97, DCL_INPUT_PS: 98, DCL_INPUT_PS_SGV: 99,
        DCL_INPUT_PS_SIV: 100, DCL_OUTPUT: 101, DCL_OUTPUT_SGV: 102, DCL_OUTPUT_SIV: 103, DCL_TEMPS: 104,
        DCL_INDEXABLE_TEMP: 105, DCL_GLOBAL_FLAGS: 106, VMWARE: 107, LOD: 108, GATHER4: 109,
        SAMPLE_POS: 110, SAMPLE_INFO: 111, HS_DECLS: 113, HS_CONTROL_POINT_PHASE: 114, HS_FORK_PHASE: 115,
        HS_JOIN_PHASE: 116, EMIT_STREAM: 117, CUT_STREAM: 118, EMITTHENCUT_STREAM: 119, INTERFACE_CALL: 120,
        BUFINFO: 121, DERIV_RTX_COARSE: 122, DERIV_RTX_FINE: 123, DERIV_RTY_COARSE: 124, DERIV_RTY_FINE: 125,
        GATHER4_C: 126, GATHER4_PO: 127, GATHER4_PO_C: 128, RCP: 129, F32TOF16: 130, F16TOF32: 131,
        UADDC: 132, USUBB: 133, COUNTBITS: 134, FIRSTBIT_HI: 135, FIRSTBIT_LO: 136, FIRSTBIT_SHI: 137,
        UBFE: 138, IBFE: 139, BFI: 140, BFREV: 141, SWAPC: 142, DCL_STREAM: 143, DCL_FUNCTION_BODY: 144,
        DCL_FUNCTION_TABLE: 145, DCL_INTERFACE: 146, DCL_INPUT_CONTROL_POINT_COUNT: 147,
        DCL_OUTPUT_CONTROL_POINT_COUNT: 148, DCL_TESS_DOMAIN: 149, DCL_TESS_PARTITIONING: 150,
        DCL_TESS_OUTPUT_PRIMITIVE: 151, DCL_HS_MAX_TESSFACTOR: 152, DCL_HS_FORK_PHASE_INSTANCE_COUNT: 153,
        DCL_HS_JOIN_PHASE_INSTANCE_COUNT: 154, DCL_THREAD_GROUP: 155, DCL_UAV_TYPED: 156, DCL_UAV_RAW: 157,
        DCL_UAV_STRUCTURED: 158, DCL_TGSM_RAW: 159, DCL_TGSM_STRUCTURED: 160, DCL_RESOURCE_RAW: 161,
        DCL_RESOURCE_STRUCTURED: 162, LD_UAV_TYPED: 163, STORE_UAV_TYPED: 164, LD_RAW: 165, STORE_RAW: 166,
        LD_STRUCTURED: 167, STORE_STRUCTURED: 168, ATOMIC_AND: 169, ATOMIC_OR: 170, ATOMIC_XOR: 171,
        ATOMIC_CMP_STORE: 172, ATOMIC_IADD: 173, ATOMIC_IMAX: 174, ATOMIC_IMIN: 175, ATOMIC_UMAX: 176,
        ATOMIC_UMIN: 177, IMM_ATOMIC_ALLOC: 178, IMM_ATOMIC_CONSUME: 179, IMM_ATOMIC_IADD: 180,
        IMM_ATOMIC_AND: 181, IMM_ATOMIC_OR: 182, IMM_ATOMIC_XOR: 183, IMM_ATOMIC_EXCH: 184,
        IMM_ATOMIC_CMP_EXCH: 185, IMM_ATOMIC_IMAX: 186, IMM_ATOMIC_IMIN: 187, IMM_ATOMIC_UMAX: 188,
        IMM_ATOMIC_UMIN: 189, SYNC: 190, DADD: 191, DMAX: 192, DMIN: 193, DMUL: 194, DEQ: 195, DGE: 196,
        DLT: 197, DNE: 198, DMOV: 199, DMOVC: 200, DTOF: 201, FTOD: 202, EVAL_SNAPPED: 203,
        EVAL_SAMPLE_INDEX: 204, EVAL_CENTROID: 205, DCL_GS_INSTANCE_COUNT: 206, ABORT: 207,
        DEBUG_BREAK: 208, DDIV: 210, DFMA: 211, DRCP: 212, MSAD: 213, DTOI: 214, DTOU: 215, ITOD: 216,
        UTOD: 217,
    };
    const OP_NAMES = [];
    for (const name of Object.keys(OP)) OP_NAMES[OP[name]] = name.toLowerCase();

    // VGPU10_VMWARE_OPCODE_TYPE: in the controls of OP.VMWARE
    const VMWARE_OP = { IDIV: 0, DFRC: 1, DRSQ: 2 };

    // Operand types (VGPU10_OPERAND_TYPE)
    const OPERAND = {
        TEMP: 0, INPUT: 1, OUTPUT: 2, INDEXABLE_TEMP: 3, IMMEDIATE32: 4, IMMEDIATE64: 5, SAMPLER: 6,
        RESOURCE: 7, CONSTANT_BUFFER: 8, IMMEDIATE_CONSTANT_BUFFER: 9, LABEL: 10, INPUT_PRIMITIVEID: 11,
        OUTPUT_DEPTH: 12, NULL: 13, RASTERIZER: 14, OUTPUT_COVERAGE_MASK: 15, STREAM: 16,
        FUNCTION_BODY: 17, FUNCTION_TABLE: 18, INTERFACE: 19, FUNCTION_INPUT: 20, FUNCTION_OUTPUT: 21,
        OUTPUT_CONTROL_POINT_ID: 22, INPUT_FORK_INSTANCE_ID: 23, INPUT_JOIN_INSTANCE_ID: 24,
        INPUT_CONTROL_POINT: 25, OUTPUT_CONTROL_POINT: 26, INPUT_PATCH_CONSTANT: 27,
        INPUT_DOMAIN_POINT: 28, THIS_POINTER: 29, UAV: 30, THREAD_GROUP_SHARED_MEMORY: 31,
        INPUT_THREAD_ID: 32, INPUT_THREAD_GROUP_ID: 33, INPUT_THREAD_ID_IN_GROUP: 34,
        INPUT_COVERAGE_MASK: 35, INPUT_THREAD_ID_IN_GROUP_FLATTENED: 36, INPUT_GS_INSTANCE_ID: 37,
        OUTPUT_DEPTH_GREATER_EQUAL: 38, OUTPUT_DEPTH_LESS_EQUAL: 39, CYCLE_COUNTER: 40,
    };

    // System value names (VGPU10_SYSTEM_NAME)
    const NAME = {
        UNDEFINED: 0, POSITION: 1, CLIP_DISTANCE: 2, CULL_DISTANCE: 3, RENDER_TARGET_ARRAY_INDEX: 4,
        VIEWPORT_ARRAY_INDEX: 5, VERTEX_ID: 6, PRIMITIVE_ID: 7, INSTANCE_ID: 8, IS_FRONT_FACE: 9,
        SAMPLE_INDEX: 10,
        // a hull shader's tess factors (patch constant outputs)
        FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR: 11, FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR: 12,
        FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR: 13, FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR: 14,
        FINAL_QUAD_U_INSIDE_TESSFACTOR: 15, FINAL_QUAD_V_INSIDE_TESSFACTOR: 16,
        FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR: 17, FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR: 18, FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR: 19,
        FINAL_TRI_INSIDE_TESSFACTOR: 20, FINAL_LINE_DETAIL_TESSFACTOR: 21, FINAL_LINE_DENSITY_TESSFACTOR: 22,
    };

    const INTERPOLATION = {
        UNDEFINED: 0, CONSTANT: 1, LINEAR: 2, LINEAR_CENTROID: 3, LINEAR_NOPERSPECTIVE: 4,
        LINEAR_NOPERSPECTIVE_CENTROID: 5, LINEAR_SAMPLE: 6, LINEAR_NOPERSPECTIVE_SAMPLE: 7,
    };

    const DIM = {
        UNKNOWN: 0, BUFFER: 1, TEXTURE1D: 2, TEXTURE2D: 3, TEXTURE2DMS: 4, TEXTURE3D: 5, TEXTURECUBE: 6,
        TEXTURE1DARRAY: 7, TEXTURE2DARRAY: 8, TEXTURE2DMSARRAY: 9, TEXTURECUBEARRAY: 10, RAW_BUFFER: 11,
        STRUCTURED_BUFFER: 12,
    };

    const RETURN = { UNORM: 1, SNORM: 2, SINT: 3, UINT: 4, FLOAT: 5, MIXED: 6, DOUBLE: 7, CONTINUED: 8, UNUSED: 9 };

    const PRIMITIVE = { UNDEFINED: 0, POINT: 1, LINE: 2, TRIANGLE: 3, LINE_ADJ: 6, TRIANGLE_ADJ: 7 };

    const CUSTOMDATA = { COMMENT: 0, DEBUGINFO: 1, OPAQUE: 2, ICB: 3 };

    // How many destination operands an instruction has (the rest are sources)
    const DESTINATIONS = new Map([
        [OP.SINCOS, 2], [OP.UDIV, 2], [OP.IMUL, 2], [OP.UMUL, 2], [OP.SWAPC, 2], [OP.UADDC, 2], [OP.USUBB, 2],
    ]);
    // Instructions with no destination
    const NO_DESTINATION = new Set([
        OP.BREAK, OP.BREAKC, OP.CALL, OP.CALLC, OP.CASE, OP.CONTINUE, OP.CONTINUEC, OP.CUT, OP.DEFAULT,
        OP.DISCARD, OP.ELSE, OP.EMIT, OP.EMITTHENCUT, OP.ENDIF, OP.ENDLOOP, OP.ENDSWITCH, OP.IF, OP.LABEL,
        OP.LOOP, OP.NOP, OP.RET, OP.RETC, OP.SWITCH, OP.EMIT_STREAM, OP.CUT_STREAM, OP.EMITTHENCUT_STREAM,
        OP.INTERFACE_CALL, OP.SYNC, OP.ABORT, OP.DEBUG_BREAK, OP.HS_DECLS, OP.HS_CONTROL_POINT_PHASE,
        OP.HS_FORK_PHASE, OP.HS_JOIN_PHASE,
    ]);
    // ... and those whose first operand is written although it is a UAV or
    // shared memory (stores, atomics without a returned value)
    const STORES = new Set([
        OP.STORE_UAV_TYPED, OP.STORE_RAW, OP.STORE_STRUCTURED, OP.ATOMIC_AND, OP.ATOMIC_OR, OP.ATOMIC_XOR,
        OP.ATOMIC_CMP_STORE, OP.ATOMIC_IADD, OP.ATOMIC_IMAX, OP.ATOMIC_IMIN, OP.ATOMIC_UMAX, OP.ATOMIC_UMIN,
    ]);

    function isDeclaration(op) {
        return (op >= OP.DCL_RESOURCE && op <= OP.DCL_GLOBAL_FLAGS) || op === OP.DCL_STREAM ||
            (op >= OP.DCL_FUNCTION_BODY && op <= OP.DCL_RESOURCE_STRUCTURED) || op === OP.DCL_GS_INSTANCE_COUNT;
    }

    /**
     * One shader program
     * @param tokens Uint32Array of the program's dwords (more after its
     *               length are ignored: VMware appends a signature there)
     */
    function decode(tokens) {
        if (!(tokens instanceof Uint32Array)) tokens = new Uint32Array(tokens);
        if (tokens.length < 2) throw new ShaderDecodeError("a shader of " + tokens.length + " tokens");
        const version = tokens[0];
        const type = version >>> 16;
        const major = version >>> 4 & 0xF, minor = version & 0xF;
        const length = tokens[1];
        if (type > PROGRAM.CS || length < 2 || length > tokens.length) {
            throw new ShaderDecodeError("bad program header " + version.toString(16) + ", length " + length);
        }
        const program = {
            type, stage: PROGRAM_NAMES[type], major, minor,
            decls: [], code: [], icb: null, temps: 0, indexable: new Map(),
            inputs: [], outputs: [], resources: new Map(), samplers: new Map(), cbuffers: new Map(),
            uavs: new Map(), tgsm: new Map(), globalFlags: 0,
            gs: { input: 0, outputTopology: 0, maxVertices: 0, instances: 1, streams: [] },
            // hull and domain shaders: control points, the tessellator's
            // settings, and a hull shader's phases (code and declarations
            // carry their phase's index; -1 outside of a hull shader)
            tess: { inputCPs: 0, outputCPs: 0, domain: 0, partitioning: 0, outputPrimitive: 0, maxTessFactor: 64, phases: [] },
            threadGroup: [1, 1, 1], indexRanges: [],
            signature: decodeSignature(tokens, length),
        };

        let at = 2;
        let phase = -1;
        while (at < length) {
            const start = at;
            const token = tokens[at];
            const op = token & 0x7FF;
            let size = token >>> 24 & 0x7F;
            if (op === OP.CUSTOMDATA) {
                // its length is the next dword (the two header dwords included)
                size = tokens[at + 1];
                if (size < 2 || start + size > length) throw new ShaderDecodeError("bad customdata length " + size);
                const kind = token >>> 11;
                if (kind === CUSTOMDATA.ICB) program.icb = tokens.slice(start + 2, start + size);
                at = start + size;
                continue;
            }
            if (size === 0 || start + size > length) {
                throw new ShaderDecodeError("instruction " + (OP_NAMES[op] || op) + " at " + start + ": length " + size);
            }
            const end = start + size;
            // a hull shader's phases begin with these
            const PHASES = { [OP.HS_DECLS]: "decls", [OP.HS_CONTROL_POINT_PHASE]: "cp", [OP.HS_FORK_PHASE]: "fork", [OP.HS_JOIN_PHASE]: "join" };
            if (PHASES[op]) {
                program.tess.phases.push({ kind: PHASES[op], instances: 1 });
                phase = program.tess.phases.length - 1;
            }
            const instruction = {
                op, name: OP_NAMES[op] || ("op" + op), at: start, phase,
                controls: token >>> 11 & 0x1FFF,
                saturate: !!(token >>> 13 & 1),
                test: token >>> 18 & 1,
                precise: token >>> 19 & 0xF,
                offsets: null, dimension: 0, returnTypes: null,
                dst: [], src: [],
            };
            at++;
            // extended opcode tokens
            let extended = token >>> 31;
            while (extended) {
                if (at >= end) throw new ShaderDecodeError("extended opcode beyond its instruction");
                const t = tokens[at++];
                switch (t & 0x3F) {
                    case 1: { // sample controls: signed 4-bit texel offsets
                        const s4 = v => v & 8 ? v - 16 : v;
                        instruction.offsets = [s4(t >>> 9 & 0xF), s4(t >>> 13 & 0xF), s4(t >>> 17 & 0xF)];
                        break;
                    }
                    case 2: instruction.dimension = t >>> 6 & 0x1F; break;
                    case 3: instruction.returnTypes = [t >>> 6 & 0xF, t >>> 10 & 0xF, t >>> 14 & 0xF, t >>> 18 & 0xF]; break;
                }
                extended = t >>> 31;
            }

            if (isDeclaration(op)) {
                decodeDeclaration(program, instruction, tokens, at, end);
                program.decls.push(instruction);
                at = end;
                continue;
            }

            const operands = [];
            while (at < end) {
                const [operand, next] = decodeOperand(tokens, at, end);
                operands.push(operand);
                at = next;
            }
            let dsts = NO_DESTINATION.has(op) ? 0 : (DESTINATIONS.get(op) || 1);
            if (STORES.has(op)) dsts = 1;
            // VMware's integer division: quotient and remainder (Mesa's svga
            // writes the second as a null operand)
            if (op === OP.VMWARE && (instruction.controls & 0xF) === VMWARE_OP.IDIV) dsts = 2;
            instruction.dst = operands.slice(0, dsts);
            instruction.src = operands.slice(dsts);
            if (op === OP.VMWARE) instruction.vmware = instruction.controls & 0xF;
            program.code.push(instruction);
        }
        return program;
    }

    /**
     * One operand at tokens[at]
     * @return [operand, the index after it]
     */
    function decodeOperand(tokens, at, end) {
        const token = tokens[at++];
        const ncomp = [0, 1, 4, -1][token & 3];
        const operand = {
            type: token >>> 12 & 0xFF,
            ncomp,
            mode: "mask", mask: 0xF, swizzle: [0, 1, 2, 3],
            indices: [],
            modifier: 0,
            imm: null,
        };
        if (ncomp === 4) {
            const selection = token >>> 2 & 3;
            if (selection === 0) {
                operand.mode = "mask";
                operand.mask = token >>> 4 & 0xF;
                // (a mask of 0 means all of them)
                if (!operand.mask) operand.mask = 0xF;
            } else if (selection === 1) {
                operand.mode = "swizzle";
                operand.swizzle = [token >>> 4 & 3, token >>> 6 & 3, token >>> 8 & 3, token >>> 10 & 3];
            } else {
                operand.mode = "select1";
                const c = token >>> 4 & 3;
                operand.swizzle = [c, c, c, c];
            }
        } else if (ncomp === 1) {
            operand.mode = "select1";
            operand.swizzle = [0, 0, 0, 0];
        }
        const dimensions = token >>> 20 & 3;
        const representations = [token >>> 22 & 7, token >>> 25 & 7, token >>> 28 & 7];
        let extended = token >>> 31;
        while (extended) {
            if (at >= end) throw new ShaderDecodeError("extended operand beyond its instruction");
            const t = tokens[at++];
            if ((t & 0x3F) === 1) operand.modifier = t >>> 6 & 0xFF;
            extended = t >>> 31;
        }
        if (operand.type === OPERAND.IMMEDIATE32) {
            const count = ncomp === 4 ? 4 : 1;
            if (at + count > end) throw new ShaderDecodeError("immediate beyond its instruction");
            operand.imm = Array.from(tokens.subarray(at, at + count));
            return [operand, at + count];
        }
        if (operand.type === OPERAND.IMMEDIATE64) {
            const count = ncomp === 4 ? 4 : 2;
            operand.imm = Array.from(tokens.subarray(at, at + count));
            return [operand, at + count];
        }
        for (let d = 0; d < dimensions; d++) {
            const representation = representations[d];
            const index = { imm: 0, rel: null };
            switch (representation) {
                case 0: // immediate32
                    index.imm = tokens[at++];
                    break;
                case 1: // immediate64 (the low dword is enough here)
                    index.imm = tokens[at];
                    at += 2;
                    break;
                case 2: { // relative
                    const [rel, next] = decodeOperand(tokens, at, end);
                    index.rel = rel;
                    at = next;
                    break;
                }
                case 3: { // immediate32 + relative
                    index.imm = tokens[at++];
                    const [rel, next] = decodeOperand(tokens, at, end);
                    index.rel = rel;
                    at = next;
                    break;
                }
                case 4: { // immediate64 + relative
                    index.imm = tokens[at];
                    at += 2;
                    const [rel, next] = decodeOperand(tokens, at, end);
                    index.rel = rel;
                    at = next;
                    break;
                }
                default:
                    throw new ShaderDecodeError("index representation " + representation);
            }
            operand.indices.push(index);
        }
        if (at > end) throw new ShaderDecodeError("operand beyond its instruction");
        return [operand, at];
    }

    function decodeDeclaration(program, instruction, tokens, at, end) {
        const op = instruction.op;
        const controls = instruction.controls;
        const operand = () => {
            const [o, next] = decodeOperand(tokens, at, end);
            at = next;
            return o;
        };
        const word = () => {
            if (at >= end) throw new ShaderDecodeError(instruction.name + " is too short");
            return tokens[at++];
        };
        switch (op) {
            case OP.DCL_TEMPS:
                program.temps = Math.max(program.temps, word());
                break;
            case OP.DCL_INDEXABLE_TEMP: {
                const index = word(), size = word(), components = word();
                program.indexable.set(index, { size, components });
                break;
            }
            case OP.DCL_GLOBAL_FLAGS:
                program.globalFlags = controls;
                break;
            case OP.DCL_INPUT:
            case OP.DCL_INPUT_SGV:
            case OP.DCL_INPUT_SIV:
            case OP.DCL_INPUT_PS:
            case OP.DCL_INPUT_PS_SGV:
            case OP.DCL_INPUT_PS_SIV: {
                const o = operand();
                const name = op === OP.DCL_INPUT_SGV || op === OP.DCL_INPUT_SIV ||
                    op === OP.DCL_INPUT_PS_SGV || op === OP.DCL_INPUT_PS_SIV ? word() & 0xFFFF : 0;
                const interpolation = op >= OP.DCL_INPUT_PS && op <= OP.DCL_INPUT_PS_SIV ? controls & 0xF : 0;
                program.inputs.push({ operand: o, type: o.type, index: indexOf(o), index2: o.indices.length > 1 ? o.indices[1].imm : -1,
                    mask: o.mask, name, interpolation, phase: instruction.phase });
                break;
            }
            case OP.DCL_OUTPUT:
            case OP.DCL_OUTPUT_SGV:
            case OP.DCL_OUTPUT_SIV: {
                const o = operand();
                const name = op !== OP.DCL_OUTPUT ? word() & 0xFFFF : 0;
                program.outputs.push({ operand: o, type: o.type, index: indexOf(o), mask: o.mask, name, phase: instruction.phase });
                break;
            }
            case OP.DCL_RESOURCE: {
                const o = operand();
                const r = word();
                program.resources.set(indexOf(o), { kind: "texture", dimension: controls & 0x1F,
                    samples: controls >>> 5 & 0x7F, returnTypes: [r & 0xF, r >>> 4 & 0xF, r >>> 8 & 0xF, r >>> 12 & 0xF] });
                break;
            }
            case OP.DCL_RESOURCE_RAW: {
                const o = operand();
                program.resources.set(indexOf(o), { kind: "raw", dimension: DIM.RAW_BUFFER, samples: 0, returnTypes: null });
                break;
            }
            case OP.DCL_RESOURCE_STRUCTURED: {
                const o = operand();
                program.resources.set(indexOf(o), { kind: "structured", dimension: DIM.STRUCTURED_BUFFER,
                    samples: 0, returnTypes: null, stride: word() });
                break;
            }
            case OP.DCL_UAV_TYPED: {
                const o = operand();
                const r = word();
                program.uavs.set(indexOf(o), { kind: "typed", dimension: controls & 0x1F,
                    returnTypes: [r & 0xF, r >>> 4 & 0xF, r >>> 8 & 0xF, r >>> 12 & 0xF],
                    counter: !!(controls >>> 12 & 1), coherent: !!(controls >>> 5 & 1) });
                break;
            }
            case OP.DCL_UAV_RAW: {
                const o = operand();
                program.uavs.set(indexOf(o), { kind: "raw", dimension: DIM.RAW_BUFFER, counter: !!(controls >>> 12 & 1) });
                break;
            }
            case OP.DCL_UAV_STRUCTURED: {
                const o = operand();
                program.uavs.set(indexOf(o), { kind: "structured", dimension: DIM.STRUCTURED_BUFFER,
                    stride: word(), counter: !!(controls >>> 12 & 1) });
                break;
            }
            case OP.DCL_TGSM_RAW: {
                const o = operand();
                program.tgsm.set(indexOf(o), { kind: "raw", bytes: word() });
                break;
            }
            case OP.DCL_TGSM_STRUCTURED: {
                const o = operand();
                const stride = word(), count = word();
                program.tgsm.set(indexOf(o), { kind: "structured", stride, count, bytes: stride * count });
                break;
            }
            case OP.DCL_CONSTANT_BUFFER: {
                // cb#[size]: the second index is the size in vec4s
                const o = operand();
                program.cbuffers.set(o.indices[0].imm, { size: o.indices.length > 1 ? o.indices[1].imm : 4096,
                    dynamic: !!(controls & 1) });
                break;
            }
            case OP.DCL_SAMPLER: {
                const o = operand();
                program.samplers.set(indexOf(o), { mode: controls & 0xF });
                break;
            }
            case OP.DCL_INDEX_RANGE: {
                const o = operand();
                program.indexRanges.push({ type: o.type, index: indexOf(o), count: word() });
                break;
            }
            case OP.DCL_GS_INPUT_PRIMITIVE:
                program.gs.input = controls & 0x3F;
                break;
            case OP.DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY:
                program.gs.outputTopology = controls & 0x7F;
                break;
            case OP.DCL_MAX_OUTPUT_VERTEX_COUNT:
                program.gs.maxVertices = word();
                break;
            case OP.DCL_GS_INSTANCE_COUNT:
                program.gs.instances = word();
                break;
            case OP.DCL_STREAM:
                program.gs.streams.push(indexOf(operand()));
                break;
            case OP.DCL_THREAD_GROUP:
                program.threadGroup = [word(), word(), word()];
                break;
            case OP.DCL_INPUT_CONTROL_POINT_COUNT:
                program.tess.inputCPs = controls & 0x3F;
                break;
            case OP.DCL_OUTPUT_CONTROL_POINT_COUNT:
                program.tess.outputCPs = controls & 0x3F;
                break;
            case OP.DCL_TESS_DOMAIN:
                program.tess.domain = controls & 3;
                break;
            case OP.DCL_TESS_PARTITIONING:
                program.tess.partitioning = controls & 7;
                break;
            case OP.DCL_TESS_OUTPUT_PRIMITIVE:
                program.tess.outputPrimitive = controls & 7;
                break;
            case OP.DCL_HS_MAX_TESSFACTOR:
                program.tess.maxTessFactor = new Float32Array(new Uint32Array([word()]).buffer)[0];
                break;
            case OP.DCL_HS_FORK_PHASE_INSTANCE_COUNT:
            case OP.DCL_HS_JOIN_PHASE_INSTANCE_COUNT: {
                const p = program.tess.phases[instruction.phase];
                if (p) p.instances = word();
                break;
            }
            default:
                // the tessellation and interface declarations are taken as
                // they come; the stages that need them read instruction.raw
                instruction.raw = Array.from(tokens.subarray(at, end));
        }
    }

    function indexOf(operand) {
        return operand.indices.length ? operand.indices[operand.indices.length === 1 ? 0 : 0].imm : 0;
    }

    /**
     * VMware's signature block after the program (SVGA3dDXShaderSignatureHeader
     * and its entries), if there is one
     */
    function decodeSignature(tokens, length) {
        const at = length;
        if (tokens.length < at + 4 || tokens[at] !== 0x08a92d12) return null;
        const inputs = tokens[at + 1], outputs = tokens[at + 2], patch = tokens[at + 3];
        const total = inputs + outputs + patch;
        if (tokens.length < at + 4 + 5 * total) return null;
        const entry = i => {
            const e = at + 4 + 5 * i;
            return { register: tokens[e], name: tokens[e + 1], mask: tokens[e + 2], componentType: tokens[e + 3] };
        };
        const list = (first, count) => Array.from({ length: count }, (_, i) => entry(first + i));
        return { inputs: list(0, inputs), outputs: list(inputs, outputs), patch: list(inputs + outputs, patch) };
    }

    /**
     * Assemble tokens from a compact description, for tests: see
     * tests/glbridge/dxbc_wgsl_test.js
     */
    const api = {
        decode, ShaderDecodeError, PROGRAM, PROGRAM_NAMES, OP, OP_NAMES, VMWARE_OP, OPERAND, NAME, INTERPOLATION,
        DIM, RETURN, PRIMITIVE, CUSTOMDATA,
    };
    if (typeof module === "object" && module.exports) module.exports = api;
    else global.V86DXBCFrontend = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
       source/v64/src/browser/glbridge/shader_ir/wgsl_emitter.js                                           0000644 0000000 0000000 00000401710 00000000000 020723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The shader IR (dxbc_frontend.js) as WGSL (docs/gpu-devices.md, "GX").
//
// The register files are arrays of raw 32-bit lanes (vec4<u32>): DXBC
// registers have no type, each instruction says how it reads them, so every
// read is a bitcast to the instruction's type and every write a bitcast
// back. Temps, inputs and outputs are private arrays, so relative indexing
// and subroutines (label/call) need nothing special; the entry point copies
// the stage's inputs in, calls shader_main() and copies the outputs out.
//
// The interfaces depend on the pipeline, not only on the shader, and the
// caller says how (options):
//   vertexInputs: register -> "f32" | "i32" | "u32", from the input
//       layout's formats (WebGPU types vertex attributes)
//   varyings: register -> { type: "f32" | "u32", interpolation, sampling },
//       from the pixel shader's declarations, for the vertex shader's
//       outputs (WebGPU wants both stages to agree)
//   targets: render target -> "f32" | "i32" | "u32" (absent: no target)
//   dualSource: the blend state reads the second color (SRC1_*)
//   group: the bind group of this stage
//
// Bindings in the group: constant buffer n at n (0-14), the draw
// parameters at 15, sampler n at 16 + n, resource n at 32 + n, UAV n at
// 160 + n, its append/consume counter at 300 + n, and at 299 where the
// buffer views start (GXViews). emit() returns them, for the bind group
// layout. options.uavFormats: { slot: { format, lanes } }, a typed UAV's
// view: the storage texture format, or a typed buffer's 32-bit lanes.
//
// Geometry shaders have no WebGPU stage, so a draw with one runs its
// vertex and geometry shaders as compute shaders (options.mode):
//   "vertex-compute": a vertex shader that pulls its inputs from the vertex
//       buffers (vertex buffer n at 200 + n, read as words; options.fetch:
//       [{ reg, slot, offset, format, instanced }]), the indices at 231 and
//       the draw at 230 (GXFetch), and stores each vertex's outputs (a
//       record of `record` vec4s) at 233
//   "geometry": a geometry shader, one invocation per input primitive (and
//       instance): its vertices come from the vertex shader's records at
//       232 (GXGeo at 234 says how many, the topology and the record
//       size), and what it emits goes to 233 as primitives of the output
//       topology, maxPrims slots of each per input primitive, a record of
//       outputs + 1 vec4s each (the last: 1 if the slot is used)
(function(global) {
    "use strict";

    const F = (typeof require === "function" && typeof module === "object") ?
        require("./dxbc_frontend.js") : global.V86DXBCFrontend;
    const { OP, OPERAND, NAME, INTERPOLATION, DIM, RETURN, PROGRAM, VMWARE_OP } = F;

    class ShaderTranslateError extends Error {}

    // (SAMPLER_COMPARE: the comparison twin of a sampler used both ways)
    const BINDING = { CB: 0, DRAW: 15, SAMPLER: 16, RESOURCE: 32, UAV: 160, VB: 200, FETCH: 230, INDEX: 231,
        STAGE_IN: 232, STAGE_OUT: 233, GEO: 234, TESS_POINTS: 235, TESS_ARGS: 236, SAMPLER_COMPARE: 240, VIEWS: 299, UAV_COUNTER: 300 };
    // the markers that begin a hull shader's phases
    const HS_PHASE_MARKERS = new Set([OP.HS_DECLS, OP.HS_CONTROL_POINT_PHASE, OP.HS_FORK_PHASE, OP.HS_JOIN_PHASE]);
    // where each tess factor goes among the tessellator's six (tessellator_wgsl.js)
    const TESS_FACTOR_SLOT = { [NAME.FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR]: 0, [NAME.FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR]: 1,
        [NAME.FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR]: 2, [NAME.FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR]: 3,
        [NAME.FINAL_QUAD_U_INSIDE_TESSFACTOR]: 4, [NAME.FINAL_QUAD_V_INSIDE_TESSFACTOR]: 5,
        [NAME.FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR]: 0, [NAME.FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR]: 1,
        [NAME.FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR]: 2, [NAME.FINAL_TRI_INSIDE_TESSFACTOR]: 3,
        [NAME.FINAL_LINE_DENSITY_TESSFACTOR]: 0, [NAME.FINAL_LINE_DETAIL_TESSFACTOR]: 1 };
    // where a buffer view starts, in words, in GXViews: UAV n at n, resource n at 64 + n
    const VIEW_BASE_UAV = 0, VIEW_BASE_RESOURCE = 64, VIEW_BASES = 192;
    // vertices of a GS input primitive (D3D10_SB_PRIMITIVE): point, line, triangle, line_adj, triangle_adj
    const GS_INPUT_VERTICES = { 1: 1, 2: 2, 3: 3, 6: 4, 7: 6 };
    const LANES = "xyzw";
    const ALL = 0xF;

    function u32(value) {
        return (value >>> 0) + "u";
    }

    /**
     * @param program decoded by dxbc_frontend.decode
     * @param options see above
     * @return { code, bindings: [{ binding, type, ... }], usesDraw, inputs, outputs, warnings }
     */
    function emit(program, options) {
        options = options || {};
        const e = new Emitter(program, options);
        return e.run();
    }

    class Emitter {
        constructor(program, options) {
            this.p = program;
            this.o = options;
            this.stage = program.type;
            this.group = options.group || 0;
            this.lines = [];
            this.indent = 1;
            this.helpers = new Set();
            /** @type {!Map<string, string>} the typed buffers' readers, by name */
            this.typedBuffers = new Map();
            this.warnings = [];
            this.usesDraw = false;
            this.usesSamples = false;
            // resources used for comparison: they are depth textures
            this.compared = new Set();
            // samplers used for comparisons, and for plain sampling: WGSL's
            // sampler types differ, and a declaration's mode does not say
            // (Mesa's svga declares every sampler "default")
            this.compareSamplers = new Set();
            this.plainSamplers = new Set();
            // samplers that are both: a comparison twin at SAMPLER_COMPARE
            this.twinSamplers = new Set();
            this.gathered = new Set();
            this.counters = new Set();
            this.uavLoads = new Set();
            // whether a buffer view's start is read from GXViews
            this.usesViews = false;
            this.temps = Math.max(1, program.temps);
            this.inputCount = 1;
            this.outputCount = 1;
            this.switches = [];
            this.needDepth = false;
            this.needMask = false;
            this.clipDistances = 0;
            this.mode = options.mode || "";
        }

        warn(text) {
            if (!this.warnings.includes(text)) this.warnings.push(text);
        }

        line(text) {
            this.lines.push("    ".repeat(this.indent) + text);
        }

        run() {
            const p = this.p;
            const geometry = this.mode === "geometry" && this.stage === PROGRAM.GS;
            const hull = this.mode === "hull" && this.stage === PROGRAM.HS;
            const domain = this.mode === "domain" && this.stage === PROGRAM.DS;
            if (this.stage !== PROGRAM.VS && this.stage !== PROGRAM.PS && this.stage !== PROGRAM.CS && !geometry && !hull && !domain) {
                throw new ShaderTranslateError(p.stage + " shaders are emulated elsewhere");
            }
            if (hull) this.hull = this.hullLayout();
            if (domain) this.domain = this.domainLayout();
            if (geometry) {
                const g = p.gs;
                this.gsVertices = GS_INPUT_VERTICES[g.input] || 0;
                if (!this.gsVertices) throw new ShaderTranslateError("geometry shader input primitive " + g.input);
                // the output topology (D3D10_SB_PRIMITIVE_TOPOLOGY): point list 1, line strip 3, triangle strip 5
                this.gsOutput = g.outputTopology === 1 ? "point-list" : g.outputTopology === 3 ? "line-list" : "triangle-list";
                this.gsPerPrim = this.gsOutput === "point-list" ? 1 : this.gsOutput === "line-list" ? 2 : 3;
                const max = Math.max(1, g.maxVertices);
                this.gsMaxPrims = this.gsOutput === "point-list" ? max : Math.max(1, max - this.gsPerPrim + 1);
                // GS instancing: invocations per input primitive (SV_GSInstanceID)
                this.gsInstances = Math.max(1, g.instances || 1);
            }
            for (const input of p.inputs) if (input.type === OPERAND.INPUT) this.inputCount = Math.max(this.inputCount, inputRegister(input) + 1);
            for (const output of p.outputs) if (output.type === OPERAND.OUTPUT) this.outputCount = Math.max(this.outputCount, output.index + 1);
            this.scanUsage();

            // the body first: it says which helpers are needed
            const [main, labels] = hull ? [[], []] : this.split();
            const functions = [];
            for (const [label, code] of labels) {
                this.lines = [];
                this.indent = 1;
                this.body(code);
                functions.push("fn label" + label + "() {\n" + this.lines.join("\n") + "\n}\n");
            }
            // a hull shader: a function per phase
            if (hull) {
                p.tess.phases.forEach((phase, k) => {
                    if (phase.kind === "decls") return;
                    this.hsPhase = phase.kind;
                    this.lines = [];
                    this.indent = 1;
                    this.body(p.code.filter(ins => ins.phase === k && !HS_PHASE_MARKERS.has(ins.op)));
                    functions.push(`fn hs_phase${k}() {\n` + this.lines.join("\n") + "\n}\n");
                });
                this.hsPhase = null;
            }
            this.lines = [];
            this.indent = 1;
            this.body(main);
            const mainBody = this.lines.join("\n");

            // the entry point before the declarations: it says whether the draw parameters are read
            const entry = this.entryPoint();
            const out = [];
            out.push("diagnostic(off, derivative_uniformity);");
            if (this.stage === PROGRAM.PS && this.o.dualSource) out.push("enable dual_source_blending;");
            if (this.clipDistances) out.push("enable clip_distances;");
            out.push("");
            out.push(...this.declarations());
            if (this.usesSamples) out.push("override gx_samples: u32 = 1u;");
            out.push(...this.helperCode());
            out.push(...functions);
            out.push("fn shader_main() {\n" + mainBody + "\n}\n");
            out.push(entry);
            return {
                code: out.join("\n"),
                bindings: this.bindings,
                usesDraw: this.usesDraw,
                // the override constant gx_samples: the pipeline's sample count
                usesSamples: this.usesSamples,
                warnings: this.warnings,
                stage: p.stage,
                // a compute variant's records: vec4s per vertex, and a geometry shader's output
                record: this.mode === "geometry" ? this.outputCount + 1 : this.mode === "hull" ? this.hull.record : this.outputCount,
                // a hull shader's records: its control points, patch constants and tess factors
                hull: this.hull || null,
                gs: this.mode === "geometry" ? { vertices: this.gsVertices, topology: this.gsOutput,
                    perPrim: this.gsPerPrim, maxPrims: this.gsMaxPrims, instances: this.gsInstances } : null,
            };
        }

        /** Which resources are compared or gathered: their WGSL types depend on it */
        scanUsage() {
            for (const ins of this.p.code) {
                switch (ins.op) {
                    case OP.SAMPLE_C: case OP.SAMPLE_C_LZ: case OP.GATHER4_C: case OP.GATHER4_PO_C: {
                        const r = ins.op === OP.GATHER4_PO_C ? ins.src[2] : ins.src[1];
                        if (r) this.compared.add(r.indices[0].imm);
                        const s = ins.op === OP.GATHER4_PO_C ? ins.src[3] : ins.src[2];
                        if (s) this.compareSamplers.add(s.indices[0].imm);
                        break;
                    }
                    case OP.SAMPLE: case OP.SAMPLE_B: case OP.SAMPLE_L: case OP.SAMPLE_D: case OP.GATHER4: case OP.GATHER4_PO: {
                        const s = ins.op === OP.GATHER4_PO ? ins.src[3] : ins.src[2];
                        if (s) this.plainSamplers.add(s.indices[0].imm);
                        break;
                    }
                    // UAVs with an append/consume counter, typed UAVs read
                    case OP.IMM_ATOMIC_ALLOC: case OP.IMM_ATOMIC_CONSUME:
                        if (ins.src[0]) this.counters.add(ins.src[0].indices[0].imm);
                        break;
                    case OP.LD_UAV_TYPED:
                        if (ins.src[1]) this.uavLoads.add(ins.src[1].indices[0].imm);
                        break;
                }
            }
        }

        /** The main program and the subroutines (label n ... ret) after it */
        split() {
            const code = this.p.code;
            const first = code.findIndex(i => i.op === OP.LABEL);
            if (first < 0) return [code, []];
            const labels = [];
            let at = first;
            while (at < code.length) {
                const label = code[at].src[0].indices[0].imm;
                let end = at + 1;
                while (end < code.length && code[end].op !== OP.LABEL) end++;
                labels.push([label, code.slice(at + 1, end)]);
                at = end;
            }
            return [code.slice(0, first), labels];
        }

        // ---------------------------------------------------------------
        // Declarations

        declarations() {
            const p = this.p, g = this.group, out = [];
            this.bindings = [];
            for (const [slot, cb] of p.cbuffers) {
                const size = Math.max(1, Math.min(cb.size, 4096));
                out.push(`@group(${g}) @binding(${BINDING.CB + slot}) var<uniform> cb${slot}: array<vec4<u32>, ${size}>;`);
                this.bindings.push({ binding: BINDING.CB + slot, type: "uniform", slot, size: size * 16 });
            }
            if (this.usesDraw) {
                // viewport: (scale x, scale y, offset x, offset y) applied to
                // the position, for viewports WebGPU would not take as they are
                out.push("struct GXDraw { base_vertex: u32, base_instance: u32, pad0: u32, pad1: u32, viewport: vec4<f32> }");
                out.push(`@group(${g}) @binding(${BINDING.DRAW}) var<uniform> gx_draw: GXDraw;`);
                this.bindings.push({ binding: BINDING.DRAW, type: "draw" });
            }
            for (const [slot, s] of p.samplers) {
                // as used: a comparison sampler when nothing samples plainly with it
                const plain = this.plainSamplers.has(slot), compares = this.compareSamplers.has(slot);
                const comparison = !plain && (compares || s.mode === 1);
                out.push(`@group(${g}) @binding(${BINDING.SAMPLER + slot}) var s${slot}: ${comparison ? "sampler_comparison" : "sampler"};`);
                this.bindings.push({ binding: BINDING.SAMPLER + slot, type: comparison ? "comparison" : "sampler", slot });
                if (plain && compares) {
                    this.twinSamplers.add(slot);
                    out.push(`@group(${g}) @binding(${BINDING.SAMPLER_COMPARE + slot}) var sc${slot}: sampler_comparison;`);
                    this.bindings.push({ binding: BINDING.SAMPLER_COMPARE + slot, type: "comparison", slot });
                }
            }
            for (const [slot, r] of p.resources) {
                const type = this.resourceType(slot, r);
                // (buffers: storage buffers read only)
                const space = type.binding.type === "read-storage" ? "<storage, read>" : "";
                out.push(`@group(${g}) @binding(${BINDING.RESOURCE + slot}) var${space} t${slot}: ${type.wgsl};`);
                this.bindings.push({ binding: BINDING.RESOURCE + slot, slot, ...type.binding });
            }
            if (p.uavs.size && this.stage === PROGRAM.VS && !this.mode) this.warn("vertex shader UAVs are not supported");
            for (const [slot, u] of p.uavs) {
                if (u.kind === "typed" && u.dimension !== DIM.BUFFER) {
                    out.push(this.storageTexture(g, slot, u));
                    continue;
                }
                // raw, structured and typed buffers: 32-bit words
                const lanes = u.kind === "typed" ? ((this.o.uavFormats || {})[slot] || {}).lanes || 1 : 0;
                out.push(`@group(${g}) @binding(${BINDING.UAV + slot}) var<storage, read_write> u${slot}: array<atomic<u32>>;`);
                this.bindings.push({ binding: BINDING.UAV + slot, slot, type: "uav", kind: u.kind, stride: u.stride || 0, lanes });
                if (this.counters.has(slot)) {
                    out.push(`@group(${g}) @binding(${BINDING.UAV_COUNTER + slot}) var<storage, read_write> uc${slot}: atomic<u32>;`);
                    this.bindings.push({ binding: BINDING.UAV_COUNTER + slot, slot, type: "uav-counter" });
                }
            }
            for (const [slot, t] of p.tgsm) {
                out.push(`var<workgroup> g${slot}: array<atomic<u32>, ${Math.max(1, Math.ceil(t.bytes / 4))}>;`);
            }
            if (p.icb) {
                const n = p.icb.length >> 2;
                const items = [];
                for (let i = 0; i < n; i++) items.push(`vec4<u32>(${[0, 1, 2, 3].map(c => u32(p.icb[4 * i + c])).join(", ")})`);
                out.push(`var<private> icb: array<vec4<u32>, ${Math.max(1, n)}> = array<vec4<u32>, ${Math.max(1, n)}>(${items.join(", ") || "vec4<u32>()"});`);
            }
            out.push(`var<private> r: array<vec4<u32>, ${this.temps}>;`);
            for (const [index, x] of p.indexable) out.push(`var<private> x${index}: array<vec4<u32>, ${Math.max(1, x.size)}>;`);
            if (this.mode === "geometry") {
                out.push(`var<private> v: array<array<vec4<u32>, ${this.inputCount}>, ${this.gsVertices}>;`);
            } else {
                out.push(`var<private> v: array<vec4<u32>, ${this.inputCount}>;`);
            }
            out.push(`var<private> o: array<vec4<u32>, ${this.outputCount}>;`);
            if (this.mode === "vertex-compute") out.push(...this.fetchDeclarations());
            if (this.mode === "hull") out.push(...this.hullDeclarations());
            if (this.mode === "domain") out.push(...this.domainDeclarations());
            if (this.mode === "geometry") out.push(...this.geometryDeclarations());
            if (this.stage === PROGRAM.PS) {
                out.push("var<private> odepth: u32;");
                out.push("var<private> omask: u32 = 0xFFFFFFFFu;");
                out.push("var<private> prim_id: u32;");
                // which sample of a supersampled target a fragment is
                out.push("var<private> gx_sample: u32;");
                // set by GX per pipeline: whether the target is multisampled
                // (supersampled), the sample mask, alpha to coverage
                out.push("override gx_ss: u32 = 0u;");
                out.push("override gx_sample_mask: u32 = 0xFFFFFFFFu;");
                out.push("override gx_a2c: u32 = 0u;");
            }
            if (this.usesViews) {
                out.push(`struct GXViews { base: array<vec4<u32>, ${VIEW_BASES / 4}> }`);
                out.push(`@group(${g}) @binding(${BINDING.VIEWS}) var<uniform> gx_views: GXViews;`);
                out.push("fn gx_view_base(i: u32) -> u32 { return gx_views.base[i >> 2u][i & 3u]; }");
                this.bindings.push({ binding: BINDING.VIEWS, type: "views" });
            }
            if (this.stage === PROGRAM.CS) {
                out.push("var<private> cs_thread: vec3<u32>;");
                out.push("var<private> cs_group: vec3<u32>;");
                out.push("var<private> cs_local: vec3<u32>;");
                out.push("var<private> cs_flat: u32;");
            }
            out.push("");
            return out;
        }

        /** The WGSL type of a resource, and its binding */
        resourceType(slot, r) {
            if (r.kind === "raw" || r.kind === "structured") {
                return { wgsl: "array<u32>", binding: { type: "read-storage", kind: r.kind, stride: r.stride || 0 } };
            }
            const ret = r.returnTypes ? r.returnTypes[0] : RETURN.FLOAT;
            const scalar = ret === RETURN.SINT ? "i32" : ret === RETURN.UINT ? "u32" : "f32";
            const sampleType = ret === RETURN.SINT ? "sint" : ret === RETURN.UINT ? "uint" : "float";
            const depth = this.compared.has(slot);
            if (depth && scalar !== "f32") this.warn("comparison on an integer texture");
            let wgsl, dimension, multisampled = false;
            switch (r.dimension) {
                case DIM.BUFFER:
                    // typed buffers: elements of 32-bit lanes; the format is applied when read
                    return { wgsl: "array<u32>", binding: { type: "read-storage", kind: "typed", returnType: ret } };
                case DIM.TEXTURE1D:
                case DIM.TEXTURE2D:
                    // (1D textures are 2D ones of one row: WebGPU's 1D ones have no mips)
                    wgsl = depth ? "texture_depth_2d" : `texture_2d<${scalar}>`; dimension = "2d"; break;
                case DIM.TEXTURE1DARRAY:
                case DIM.TEXTURE2DARRAY:
                    wgsl = depth ? "texture_depth_2d_array" : `texture_2d_array<${scalar}>`; dimension = "2d-array"; break;
                // GX keeps multisampled surfaces supersampled: each sample a
                // texel of a texture twice as wide and high (gx_ms_texel)
                case DIM.TEXTURE2DMS:
                    wgsl = depth ? "texture_depth_2d" : `texture_2d<${scalar}>`; dimension = "2d"; break;
                case DIM.TEXTURE2DMSARRAY:
                    wgsl = depth ? "texture_depth_2d_array" : `texture_2d_array<${scalar}>`; dimension = "2d-array"; break;
                case DIM.TEXTURE3D:
                    wgsl = `texture_3d<${scalar}>`; dimension = "3d"; break;
                case DIM.TEXTURECUBE:
                    wgsl = depth ? "texture_depth_cube" : `texture_cube<${scalar}>`; dimension = "cube"; break;
                case DIM.TEXTURECUBEARRAY:
                    wgsl = depth ? "texture_depth_cube_array" : `texture_cube_array<${scalar}>`; dimension = "cube-array"; break;
                default:
                    throw new ShaderTranslateError("resource dimension " + r.dimension);
            }
            return { wgsl, binding: { type: "texture", dimension, sampleType: depth ? "depth" : sampleType, multisampled,
                one: r.dimension === DIM.TEXTURE1D || r.dimension === DIM.TEXTURE1DARRAY } };
        }

        // ---------------------------------------------------------------
        // Entry points

        entryPoint() {
            if (this.mode === "vertex-compute") return this.vertexComputeEntry();
            if (this.mode === "geometry") return this.geometryEntry();
            if (this.mode === "hull") return this.hullEntry();
            if (this.mode === "domain") return this.domainEntry();
            switch (this.stage) {
                case PROGRAM.VS: return this.vertexEntry();
                case PROGRAM.PS: return this.fragmentEntry();
                case PROGRAM.CS: return this.computeEntry();
            }
            return "";
        }

        vertexEntry() {
            const p = this.p, o = this.o;
            const inputs = [], loads = [];
            let needVertex = false, needInstance = false;
            for (const input of p.inputs) {
                if (input.type !== OPERAND.INPUT) continue;
                const reg = inputRegister(input);
                if (input.name === NAME.VERTEX_ID) {
                    needVertex = true;
                    this.usesDraw = true;
                    loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(vid - gx_draw.base_vertex)", input.mask)};`);
                } else if (input.name === NAME.INSTANCE_ID) {
                    needInstance = true;
                    this.usesDraw = true;
                    loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(iid - gx_draw.base_instance)", input.mask)};`);
                } else {
                    const type = (o.vertexInputs && o.vertexInputs[reg]) || null;
                    if (!type) {
                        // not in the input layout: D3D reads zeros
                        continue;
                    }
                    if (inputs.some(i => i.reg === reg)) continue;
                    inputs.push({ reg, type });
                    loads.push(`v[${reg}] = bitcast<vec4<u32>>(input.a${reg});`);
                }
            }
            const fields = inputs.map(i => `    @location(${i.reg}) a${i.reg}: vec4<${i.type}>,`);
            if (needVertex) fields.push("    @builtin(vertex_index) vid: u32,");
            if (needInstance) fields.push("    @builtin(instance_index) iid: u32,");
            const outFields = [], stores = [];
            let position = null;
            for (const output of p.outputs) {
                if (output.type !== OPERAND.OUTPUT) continue;
                if (output.name === NAME.POSITION) position = output.index;
            }
            outFields.push("    @builtin(position) position: vec4<f32>,");
            // clip distances (SV_ClipDistance): WebGPU's, where the device has them
            const clips = [];
            for (const output of p.outputs) {
                if (output.type !== OPERAND.OUTPUT || output.name !== NAME.CLIP_DISTANCE) continue;
                for (let c = 0; c < 4; c++) if (output.mask >> c & 1) clips.push([output.index, c]);
            }
            clips.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
            if (clips.length && o.clipDistances) {
                this.clipDistances = Math.min(8, clips.length);
                outFields.push(`    @builtin(clip_distances) clip: array<f32, ${this.clipDistances}>,`);
                clips.slice(0, 8).forEach(([reg, c], i) => stores.push(`out.clip[${i}] = bitcast<f32>(o[${reg}].${"xyzw"[c]});`));
            } else if (clips.length) {
                this.warn("clip distances need WebGPU's clip-distances");
            }
            this.usesDraw = true;
            stores.push(position === null ? "out.position = vec4<f32>(0.0, 0.0, 0.0, 1.0);" :
                `let p = bitcast<vec4<f32>>(o[${position}]);\n    out.position = vec4<f32>(p.xy * gx_draw.viewport.xy + gx_draw.viewport.zw * p.w, p.zw);`);
            // the varyings the pixel shader reads, as it declares them
            const varyings = o.varyings || defaultVaryings(p);
            for (const reg of Object.keys(varyings).map(Number).sort((a, b) => a - b)) {
                const vary = varyings[reg];
                const type = vary.type === "u32" ? "u32" : "f32";
                outFields.push(`    ${interpolationAttribute(vary, type)}@location(${reg}) o${reg}: vec4<${type}>,`);
                const value = reg < this.outputCount && reg !== position ? `o[${reg}]` : "vec4<u32>()";
                stores.push(type === "u32" ? `out.o${reg} = ${value};` : `out.o${reg} = bitcast<vec4<f32>>(${value});`);
            }
            const struct_in = fields.length ? `struct VSIn {\n${fields.join("\n")}\n}\n` : "";
            return struct_in +
                `struct VSOut {\n${outFields.join("\n")}\n}\n` +
                `@vertex fn main(${fields.length ? "input: VSIn" : ""}) -> VSOut {\n` +
                (needVertex ? "    let vid = input.vid;\n" : "") + (needInstance ? "    let iid = input.iid;\n" : "") +
                loads.map(l => "    " + l).join("\n") + "\n" +
                "    shader_main();\n    var out: VSOut;\n" +
                stores.map(s => "    " + s).join("\n") + "\n    return out;\n}\n";
        }

        /**
         * The pixel shader's entry point. Into a multisampled target (GX
         * supersamples them, gx_ss 1) each fragment is a sample: its index
         * comes from the position, the position is the pixel's again, and
         * the sample mask, alpha to coverage and oMask discard the samples
         * they leave out.
         */
        fragmentEntry() {
            const p = this.p, o = this.o;
            // (the position always: it says which sample a fragment is)
            const fields = ["    @builtin(position) position: vec4<f32>,"], loads = [];
            const seen = new Set();
            // per-sample shading sees the sample's position, else the pixel's center
            const perSample = p.inputs.some(i => i.type === OPERAND.INPUT && (i.name === NAME.SAMPLE_INDEX ||
                i.interpolation === INTERPOLATION.LINEAR_SAMPLE || i.interpolation === INTERPOLATION.LINEAR_NOPERSPECTIVE_SAMPLE));
            for (const input of p.inputs) {
                const reg = inputRegister(input);
                if (input.type === OPERAND.INPUT_PRIMITIVEID) continue;
                if (input.type === OPERAND.INPUT_COVERAGE_MASK) continue;
                if (input.type !== OPERAND.INPUT) continue;
                switch (input.name) {
                    case NAME.POSITION: {
                        const pixel = perSample ? "input.position.xy / gx_scale" : "floor(input.position.xy / gx_scale) + 0.5";
                        const position = `vec4<f32>(select(input.position.xy, ${pixel}, gx_ss != 0u), input.position.zw)`;
                        loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, `bitcast<vec4<u32>>(${position})`, input.mask)};`);
                        continue;
                    }
                    case NAME.IS_FRONT_FACE:
                        fields.push("    @builtin(front_facing) front: bool,");
                        loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(select(0u, 0xFFFFFFFFu, input.front))", input.mask)};`);
                        continue;
                    case NAME.SAMPLE_INDEX:
                        loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(gx_sample)", input.mask)};`);
                        continue;
                    case NAME.PRIMITIVE_ID:
                        loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(0u)", input.mask)};`);
                        continue;
                    case NAME.CLIP_DISTANCE:
                    case NAME.CULL_DISTANCE:
                    case NAME.RENDER_TARGET_ARRAY_INDEX:
                    case NAME.VIEWPORT_ARRAY_INDEX:
                        loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(0u)", input.mask)};`);
                        continue;
                }
                if (seen.has(reg)) continue;
                seen.add(reg);
                const vary = varyingOf(input);
                const type = vary.type;
                fields.push(`    ${interpolationAttribute(vary, type)}@location(${reg}) i${reg}: vec4<${type}>,`);
                loads.push(type === "u32" ? `v[${reg}] = input.i${reg};` : `v[${reg}] = bitcast<vec4<u32>>(input.i${reg});`);
            }
            const outFields = [], stores = [];
            const targets = o.targets || { 0: "f32" };
            for (const index of Object.keys(targets).map(Number).sort((a, b) => a - b)) {
                const type = targets[index];
                if (!type) continue;
                const value = index < this.outputCount ? `o[${index}]` : "vec4<u32>()";
                if (o.dualSource && index === 0) {
                    outFields.push(`    @location(0) @blend_src(0) c0: vec4<${type}>,`);
                    outFields.push(`    @location(0) @blend_src(1) c1: vec4<${type}>,`);
                    stores.push(`out.c0 = ${fromBits(value, type)};`);
                    stores.push(`out.c1 = ${fromBits(this.outputCount > 1 ? "o[1]" : "vec4<u32>()", type)};`);
                    break;
                }
                outFields.push(`    @location(${index}) c${index}: vec4<${type}>,`);
                stores.push(`out.c${index} = ${fromBits(value, type)};`);
            }
            for (const output of p.outputs) {
                if (output.type === OPERAND.OUTPUT_DEPTH || output.type === OPERAND.OUTPUT_DEPTH_GREATER_EQUAL ||
                    output.type === OPERAND.OUTPUT_DEPTH_LESS_EQUAL) {
                    outFields.push("    @builtin(frag_depth) depth: f32,");
                    stores.push("out.depth = bitcast<f32>(odepth);");
                }
            }
            // the samples left out
            const discards = [];
            if (p.outputs.some(output => output.type === OPERAND.OUTPUT_COVERAGE_MASK)) discards.push("((omask >> gx_sample) & 1u) == 0u");
            discards.push("((gx_sample_mask >> gx_sample) & 1u) == 0u");
            if (targets[0] === "f32" && this.outputCount > 0) {
                discards.push("gx_ss != 0u && gx_a2c != 0u && bitcast<f32>(o[0].w) < (f32(gx_sample) + 0.5) / select(4.0, 8.0, gx_ss == 2u)");
            }
            const struct_in = `struct PSIn {\n${fields.join("\n")}\n}\n`;
            const struct_out = outFields.length ? `struct PSOut {\n${outFields.join("\n")}\n}\n` : "";
            return struct_in + struct_out +
                `@fragment fn main(input: PSIn)${outFields.length ? " -> PSOut" : ""} {\n` +
                // (gx_ss 1: 4 samples, 2 x 2; 2: 8 samples, 4 x 2)
                "    let gx_scale = select(vec2<f32>(2.0, 2.0), vec2<f32>(4.0, 2.0), gx_ss == 2u);\n" +
                "    gx_sample = select(select(0u, (u32(input.position.x) & 1u) | ((u32(input.position.y) & 1u) << 1u), gx_ss == 1u),\n" +
                "        (u32(input.position.x) & 3u) | ((u32(input.position.y) & 1u) << 2u), gx_ss == 2u);\n" +
                loads.map(l => "    " + l).join("\n") + "\n" +
                "    shader_main();\n" +
                `    if (${discards.map(d => "(" + d + ")").join(" || ")}) { discard; }\n` +
                (outFields.length ? "    var out: PSOut;\n" + stores.map(s => "    " + s).join("\n") + "\n    return out;\n" : "") +
                "}\n";
        }

        computeEntry() {
            const [x, y, z] = this.p.threadGroup;
            return `@compute @workgroup_size(${x}, ${y}, ${z}) fn main(@builtin(global_invocation_id) gid: vec3<u32>, ` +
                `@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, ` +
                `@builtin(local_invocation_index) lindex: u32) {\n` +
                "    cs_thread = gid;\n    cs_group = wid;\n    cs_local = lid;\n    cs_flat = lindex;\n" +
                "    shader_main();\n}\n";
        }

        // ---------------------------------------------------------------
        // Compute variants: a vertex shader that pulls its vertices, and a
        // geometry shader (see the top of this file)

        fetchDeclarations() {
            const g = this.group, out = [];
            out.push("struct GXFetch { count: u32, first: u32, base: i32, indexed: u32, instances: u32, first_instance: u32, " +
                "index16: u32, index_offset: u32, vb: array<vec4<u32>, 16> }");
            out.push(`@group(${g}) @binding(${BINDING.FETCH}) var<uniform> gx_fetch: GXFetch;`);
            out.push(`@group(${g}) @binding(${BINDING.INDEX}) var<storage, read> gx_index: array<u32>;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_OUT}) var<storage, read_write> gx_out: array<vec4<u32>>;`);
            this.bindings.push({ binding: BINDING.FETCH, type: "fetch" });
            this.bindings.push({ binding: BINDING.INDEX, type: "index" });
            this.bindings.push({ binding: BINDING.STAGE_OUT, type: "stage-out" });
            const slots = [...new Set((this.o.fetch || []).map(f => f.slot))].sort((a, b) => a - b);
            for (const slot of slots) {
                out.push(`@group(${g}) @binding(${BINDING.VB + slot}) var<storage, read> vb${slot}: array<u32>;`);
                this.bindings.push({ binding: BINDING.VB + slot, type: "vertex-buffer", slot });
                // a word at any byte
                out.push(`fn vbword${slot}(byte: u32) -> u32 { let w = byte >> 2u; let s = (byte & 3u) * 8u;\n` +
                    `    if (s == 0u) { return vb${slot}[w]; }\n    return (vb${slot}[w] >> s) | (vb${slot}[w + 1u] << (32u - s)); }`);
            }
            out.push("fn gx_sext(value: u32, bits: u32) -> u32 { return u32(i32(value << (32u - bits)) >> (32u - bits)); }");
            out.push("fn gx_unorm(value: u32, bits: u32) -> u32 { return bitcast<u32>(f32(value) / f32((1u << bits) - 1u)); }");
            out.push("fn gx_snorm(value: u32, bits: u32) -> u32 { let v = i32(value << (32u - bits)) >> (32u - bits);\n" +
                "    return bitcast<u32>(max(f32(v) / f32((1u << (bits - 1u)) - 1u), -1.0)); }");
            out.push("fn gx_uf(value: u32, mantissa: u32) -> u32 { let e = value >> mantissa; let m = value & ((1u << mantissa) - 1u);\n" +
                "    if (e == 0u) { return bitcast<u32>(f32(m) * exp2(-14.0 - f32(mantissa))); }\n" +
                "    if (e == 31u) { return select(0x7F800000u, 0x7FC00000u, m != 0u); }\n" +
                "    return bitcast<u32>((1.0 + f32(m) / f32(1u << mantissa)) * exp2(f32(e) - 15.0)); }");
            out.push("");
            return out;
        }

        /** An input element's value, from its bytes at `byte` in its slot, as vec4<u32> lanes */
        fetchValue(format, slot) {
            const word = at => `vbword${slot}(byte + ${at}u)`;
            const ONE = "0x3F800000u";
            const pad = (lanes, n, one) => { while (lanes.length < 4) lanes.push(lanes.length === 3 ? one : "0u"); return `vec4<u32>(${lanes.join(", ")})`; };
            if (format === "unorm10-10-10-2") {
                return `vec4<u32>(gx_unorm(${word(0)} & 0x3FFu, 10u), gx_unorm((${word(0)} >> 10u) & 0x3FFu, 10u), ` +
                    `gx_unorm((${word(0)} >> 20u) & 0x3FFu, 10u), gx_unorm(${word(0)} >> 30u, 2u))`;
            }
            if (format === "pull:uint10-10-10-2") {
                return `vec4<u32>(${word(0)} & 0x3FFu, (${word(0)} >> 10u) & 0x3FFu, (${word(0)} >> 20u) & 0x3FFu, ${word(0)} >> 30u)`;
            }
            if (format === "pull:unorm8x4-bgrx") {
                return `vec4<u32>(gx_unorm((${word(0)} >> 16u) & 0xFFu, 8u), gx_unorm((${word(0)} >> 8u) & 0xFFu, 8u), ` +
                    `gx_unorm(${word(0)} & 0xFFu, 8u), ${ONE})`;
            }
            if (format === "pull:ufloat11-11-10") {
                return `vec4<u32>(gx_uf(${word(0)} & 0x7FFu, 6u), gx_uf((${word(0)} >> 11u) & 0x7FFu, 6u), gx_uf(${word(0)} >> 22u, 5u), ${ONE})`;
            }
            const m = /^(float|unorm|snorm|uint|sint)(8|16|32)(?:x(\d))?(-bgra)?$/.exec(format);
            if (!m) {
                this.warn("vertex format " + format + " is read as zeros");
                return "vec4<u32>(0u, 0u, 0u, 0u)";
            }
            const kind = m[1], bits = +m[2], count = m[3] ? +m[3] : 1;
            const integer = kind === "uint" || kind === "sint";
            const one = integer ? "1u" : ONE;
            const lanes = [];
            for (let c = 0; c < count; c++) {
                const bit = c * bits;
                const raw = bits === 32 ? word(4 * c) : `((${word(bit >> 5 << 2)} >> ${bit & 31}u) & ${(2 ** bits - 1) >>> 0}u)`;
                if (kind === "float") lanes.push(bits === 32 ? raw : `bitcast<u32>(unpack2x16float(${raw}).x)`);
                else if (kind === "uint") lanes.push(raw);
                else if (kind === "sint") lanes.push(bits === 32 ? raw : `gx_sext(${raw}, ${bits}u)`);
                else if (kind === "unorm") lanes.push(`gx_unorm(${raw}, ${bits}u)`);
                else lanes.push(`gx_snorm(${raw}, ${bits}u)`);
            }
            if (m[4]) [lanes[0], lanes[2]] = [lanes[2], lanes[0]];
            return pad(lanes, count, one);
        }

        vertexComputeEntry() {
            const p = this.p, loads = [];
            const fetch = new Map((this.o.fetch || []).map(f => [f.reg, f]));
            for (const input of p.inputs) {
                if (input.type !== OPERAND.INPUT) continue;
                const reg = inputRegister(input);
                if (input.name === NAME.VERTEX_ID) {
                    loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(vid)", input.mask)};`);
                } else if (input.name === NAME.INSTANCE_ID) {
                    loads.push(`v[${reg}] = ${maskInto(`v[${reg}]`, "vec4<u32>(instance)", input.mask)};`);
                } else if (fetch.has(reg)) {
                    const f = fetch.get(reg);
                    const record = f.instanced ? "gx_fetch.first_instance + instance / max(1u, gx_fetch.vb[" + f.slot + "].z)" : "vertex";
                    loads.push(`{ let byte = gx_fetch.vb[${f.slot}].x + (${record}) * gx_fetch.vb[${f.slot}].y + ${f.offset}u;\n` +
                        `        v[${reg}] = ${this.fetchValue(f.format, f.slot)}; }`);
                    fetch.delete(reg);
                }
            }
            const stores = [];
            for (let i = 0; i < this.outputCount; i++) stores.push(`gx_out[at + ${i}u] = o[${i}];`);
            return "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n" +
                "    let total = gx_fetch.count * gx_fetch.instances;\n" +
                "    let k = gid.x + gid.y * 65535u * 64u;\n" +
                "    if (k >= total) { return; }\n" +
                "    let instance = k / gx_fetch.count;\n" +
                "    let n = k % gx_fetch.count;\n" +
                "    var vertex = gx_fetch.first + n;\n" +
                "    var vid = vertex;\n" +
                "    if (gx_fetch.indexed != 0u) {\n" +
                "        let byte = gx_fetch.index_offset + (gx_fetch.first + n) * select(4u, 2u, gx_fetch.index16 != 0u);\n" +
                "        var index = gx_index[byte >> 2u];\n" +
                "        if (gx_fetch.index16 != 0u) { index = (index >> ((byte & 2u) * 8u)) & 0xFFFFu; }\n" +
                "        vid = index;\n" +
                "        vertex = u32(i32(index) + gx_fetch.base);\n" +
                "    }\n" +
                loads.map(l => "    " + l).join("\n") + "\n" +
                "    shader_main();\n" +
                `    let at = k * ${this.outputCount}u;\n` +
                stores.map(l => "    " + l).join("\n") + "\n}\n";
        }

        geometryDeclarations() {
            const g = this.group, out = [];
            out.push("struct GXGeo { prims: u32, instances: u32, count: u32, topology: u32, in_record: u32, pad0: u32, pad1: u32, pad2: u32 }");
            out.push(`@group(${g}) @binding(${BINDING.GEO}) var<uniform> gx_geo: GXGeo;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_IN}) var<storage, read> gx_in: array<vec4<u32>>;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_OUT}) var<storage, read_write> gx_out: array<vec4<u32>>;`);
            this.bindings.push({ binding: BINDING.GEO, type: "geo" });
            this.bindings.push({ binding: BINDING.STAGE_IN, type: "stage-in" });
            this.bindings.push({ binding: BINDING.STAGE_OUT, type: "stage-out" });
            const OUT = this.outputCount, REC = OUT + 1, MAXP = this.gsMaxPrims;
            out.push("var<private> prim_id: u32;");
            out.push(`var<private> gs_s0: array<vec4<u32>, ${OUT}>;`);
            out.push(`var<private> gs_s1: array<vec4<u32>, ${OUT}>;`);
            out.push("var<private> gs_len: u32;");
            out.push("var<private> gs_prims: u32;");
            out.push("var<private> gs_base: u32;");
            out.push("var<private> gs_instance: u32;");
            out.push(`fn gs_put(slot: u32, value: array<vec4<u32>, ${OUT}>) {\n` +
                `    let at = slot * ${REC}u;\n` +
                `    for (var i = 0u; i < ${OUT}u; i++) { gx_out[at + i] = value[i]; }\n` +
                `    gx_out[at + ${OUT}u] = vec4<u32>(1u, 0u, 0u, 0u);\n}`);
            // what the strip so far makes with this vertex: a triangle of the
            // last three (winding kept), a line of the last two, a point
            let make;
            if (this.gsOutput === "triangle-list") {
                make = "if (gs_len >= 2u) {\n" +
                    "        let at = gs_base + gs_prims * 3u;\n" +
                    "        if ((gs_len & 1u) == 0u) { gs_put(at, gs_s0); gs_put(at + 1u, gs_s1); }\n" +
                    "        else { gs_put(at, gs_s1); gs_put(at + 1u, gs_s0); }\n" +
                    "        gs_put(at + 2u, cur);\n        gs_prims += 1u;\n    }";
            } else if (this.gsOutput === "line-list") {
                make = "if (gs_len >= 1u) { let at = gs_base + gs_prims * 2u; gs_put(at, gs_s1); gs_put(at + 1u, cur); gs_prims += 1u; }";
            } else {
                make = "gs_put(gs_base + gs_prims, cur);\n    gs_prims += 1u;";
            }
            out.push("fn gs_emit() {\n    let cur = o;\n" +
                `    if (gs_prims < ${MAXP}u) {\n    ${make}\n    }\n` +
                "    gs_s0 = gs_s1;\n    gs_s1 = cur;\n    gs_len += 1u;\n}");
            out.push("fn gs_cut() { gs_len = 0u; }");
            // the vertex of an input primitive, by the draw's topology (GXGeo.topology:
            // 1 point list, 2 line list, 3 line strip, 4 triangle list, 5 triangle strip,
            // 10-13 their adjacency kinds)
            out.push("fn gx_vertex(prim: u32, n: u32) -> u32 {\n" +
                "    switch (gx_geo.topology) {\n" +
                "        case 1u: { return prim; }\n" +
                "        case 2u: { return prim * 2u + n; }\n" +
                "        case 3u, 11u: { return prim + n; }\n" +
                "        case 4u: { return prim * 3u + n; }\n" +
                "        case 5u: { if ((prim & 1u) == 1u && n < 2u) { return prim + 1u - n; } return prim + n; }\n" +
                "        case 10u: { return prim * 4u + n; }\n" +
                "        case 12u: { return prim * 6u + n; }\n" +
                "        case 13u: { return prim * 2u + n; }\n" +
                `        default: { return prim * ${this.gsVertices}u + n; }\n` +
                "    }\n}");
            out.push("");
            return out;
        }

        geometryEntry() {
            const p = this.p, NV = this.gsVertices, OUT = this.outputCount, REC = OUT + 1;
            const slots = this.gsMaxPrims * this.gsPerPrim;
            const loads = [];
            for (const input of p.inputs) {
                if (input.type === OPERAND.INPUT_PRIMITIVEID) continue;
                if (input.type !== OPERAND.INPUT) continue;
                if (input.name === NAME.PRIMITIVE_ID) {
                    const reg = inputRegister(input);
                    for (let n = 0; n < NV; n++) loads.push(`v[${n}][${reg}] = vec4<u32>(prim);`);
                }
            }
            // (a primitive's GS instances one after the other, so their output keeps D3D's order)
            const GI = this.gsInstances;
            return "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n" +
                `    let total = gx_geo.prims * gx_geo.instances * ${GI}u;\n` +
                "    let k = gid.x + gid.y * 65535u * 64u;\n" +
                "    if (k >= total) { return; }\n" +
                `    gs_instance = k % ${GI}u;\n` +
                `    let instance = k / ${GI}u / gx_geo.prims;\n` +
                `    let prim = (k / ${GI}u) % gx_geo.prims;\n` +
                `    for (var n = 0u; n < ${NV}u; n++) {\n` +
                "        let at = (instance * gx_geo.count + gx_vertex(prim, n)) * gx_geo.in_record;\n" +
                `        for (var reg = 0u; reg < min(${this.inputCount}u, gx_geo.in_record); reg++) { v[n][reg] = gx_in[at + reg]; }\n` +
                "    }\n" +
                loads.map(l => "    " + l).join("\n") + "\n" +
                "    prim_id = prim;\n" +
                `    gs_base = k * ${slots}u;\n` +
                `    for (var i = 0u; i < ${slots}u; i++) { gx_out[(gs_base + i) * ${REC}u + ${OUT}u] = vec4<u32>(); }\n` +
                "    gs_len = 0u;\n    gs_prims = 0u;\n" +
                "    shader_main();\n}\n";
        }

        // ---------------------------------------------------------------
        // Tessellation: hull and domain shaders as compute (see GX's
        // drawTessellated). A hull shader runs once per patch, its phases
        // in order; its record per patch: the output control points
        // (cpRegs vec4s each), the patch constants (pcRegs), then the six
        // tess factors (two vec4s of floats, tessellator_wgsl.js's order). A
        // domain shader runs once per point the tessellator made.

        hullLayout() {
            const p = this.p, t = p.tess;
            const kind = phase => (t.phases[phase] || {}).kind;
            let inRegs = 1, cpRegs = 0, pcRegs = 1;
            for (const input of p.inputs) {
                if (input.type === OPERAND.INPUT_CONTROL_POINT || (input.type === OPERAND.INPUT && input.index2 >= 0)) {
                    inRegs = Math.max(inRegs, input.index2 + 1);
                }
            }
            const hasCP = t.phases.some(ph => ph.kind === "cp");
            for (const output of p.outputs) {
                if (output.type !== OPERAND.OUTPUT) continue;
                if (kind(output.phase) === "cp") cpRegs = Math.max(cpRegs, output.index + 1);
                else pcRegs = Math.max(pcRegs, output.index + 1);
            }
            // without a control point phase the input control points pass through
            if (!hasCP) cpRegs = inRegs;
            cpRegs = Math.max(1, cpRegs);
            const inCPs = Math.max(1, t.inputCPs), outCPs = Math.max(1, hasCP ? t.outputCPs : t.outputCPs || t.inputCPs);
            const pcAt = outCPs * cpRegs;
            return { inCPs, outCPs, inRegs, cpRegs, pcRegs, hasCP, pcAt, factorAt: pcAt + pcRegs, record: pcAt + pcRegs + 2,
                domain: t.domain, partitioning: t.partitioning, outputPrimitive: t.outputPrimitive, maxTessFactor: t.maxTessFactor };
        }

        hullDeclarations() {
            const g = this.group, h = this.hull, out = [];
            out.push("struct GXHull { patches: u32, instances: u32, count: u32, in_record: u32 }");
            out.push(`@group(${g}) @binding(${BINDING.GEO}) var<uniform> gx_hull: GXHull;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_IN}) var<storage, read> gx_in: array<vec4<u32>>;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_OUT}) var<storage, read_write> gx_out: array<vec4<u32>>;`);
            this.bindings.push({ binding: BINDING.GEO, type: "hull" });
            this.bindings.push({ binding: BINDING.STAGE_IN, type: "stage-in" });
            this.bindings.push({ binding: BINDING.STAGE_OUT, type: "stage-out" });
            out.push(`var<private> vicp: array<array<vec4<u32>, ${h.inRegs}>, ${h.inCPs}>;`);
            out.push(`var<private> vocp: array<array<vec4<u32>, ${h.cpRegs}>, ${h.outCPs}>;`);
            out.push(`var<private> opc: array<vec4<u32>, ${h.pcRegs}>;`);
            out.push("var<private> hs_cpid: u32;");
            out.push("var<private> hs_inst: u32;");
            out.push("var<private> prim_id: u32;");
            return out;
        }

        hullEntry() {
            const p = this.p, h = this.hull, phases = p.tess.phases;
            const lines = [];
            lines.push("    let k = gid.x + gid.y * 65535u * 64u;");
            lines.push("    if (k >= gx_hull.patches * gx_hull.instances) { return; }");
            lines.push("    let instance = k / gx_hull.patches;");
            lines.push("    let prim = k % gx_hull.patches;");
            lines.push(`    for (var n = 0u; n < ${h.inCPs}u; n++) {`);
            lines.push(`        let at = (instance * gx_hull.count + prim * ${h.inCPs}u + n) * gx_hull.in_record;`);
            lines.push(`        for (var reg = 0u; reg < min(${h.inRegs}u, gx_hull.in_record); reg++) { vicp[n][reg] = gx_in[at + reg]; }`);
            lines.push("    }");
            lines.push("    prim_id = prim;");
            const cp = phases.findIndex(ph => ph.kind === "cp");
            lines.push(`    for (var cp = 0u; cp < ${h.outCPs}u; cp++) {`);
            lines.push("        hs_cpid = cp;");
            if (cp >= 0) {
                lines.push(`        for (var reg = 0u; reg < ${this.outputCount}u; reg++) { o[reg] = vec4<u32>(); }`);
                lines.push(`        hs_phase${cp}();`);
                lines.push(`        for (var reg = 0u; reg < ${h.cpRegs}u; reg++) { vocp[cp][reg] = o[reg]; }`);
            } else {
                lines.push(`        for (var reg = 0u; reg < ${h.cpRegs}u; reg++) { vocp[cp][reg] = vicp[min(cp, ${h.inCPs - 1}u)][reg]; }`);
            }
            lines.push("    }");
            phases.forEach((phase, k) => {
                if (phase.kind !== "fork" && phase.kind !== "join") return;
                lines.push(`    for (var i = 0u; i < ${Math.max(1, phase.instances)}u; i++) { hs_inst = i; hs_phase${k}(); }`);
            });
            lines.push(`    let out = k * ${h.record}u;`);
            lines.push(`    for (var cp = 0u; cp < ${h.outCPs}u; cp++) {`);
            lines.push(`        for (var reg = 0u; reg < ${h.cpRegs}u; reg++) { gx_out[out + cp * ${h.cpRegs}u + reg] = vocp[cp][reg]; }`);
            lines.push("    }");
            lines.push(`    for (var reg = 0u; reg < ${h.pcRegs}u; reg++) { gx_out[out + ${h.pcAt}u + reg] = opc[reg]; }`);
            // the tess factors, from the patch constants their declarations name
            const factors = ["0.0", "0.0", "0.0", "0.0", "0.0", "0.0"];
            for (const output of p.outputs) {
                const slot = TESS_FACTOR_SLOT[output.name];
                if (slot === undefined || output.type !== OPERAND.OUTPUT) continue;
                let lane = 0;
                while (lane < 3 && !(output.mask >> lane & 1)) lane++;
                factors[slot] = `bitcast<f32>(opc[${output.index}].${LANES[lane]})`;
            }
            lines.push(`    gx_out[out + ${h.factorAt}u] = bitcast<vec4<u32>>(vec4<f32>(${factors.slice(0, 4).join(", ")}));`);
            lines.push(`    gx_out[out + ${h.factorAt + 1}u] = bitcast<vec4<u32>>(vec4<f32>(${factors[4]}, ${factors[5]}, 0.0, 0.0));`);
            return "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n" + lines.join("\n") + "\n}\n";
        }

        domainLayout() {
            const p = this.p;
            let cpRegs = 1, pcRegs = 1;
            for (const input of p.inputs) {
                if (input.type === OPERAND.INPUT_CONTROL_POINT) cpRegs = Math.max(cpRegs, input.index2 + 1);
                if (input.type === OPERAND.INPUT_PATCH_CONSTANT) pcRegs = Math.max(pcRegs, input.index + 1);
            }
            return { cps: Math.max(1, p.tess.inputCPs), cpRegs, pcRegs, domain: p.tess.domain };
        }

        domainDeclarations() {
            const g = this.group, d = this.domain, out = [];
            // the hull shader's records: cp_regs vec4s per control point, the patch constants at pc_at
            out.push("struct GXDomain { patches: u32, hull_record: u32, cp_regs: u32, pc_at: u32 }");
            out.push(`@group(${g}) @binding(${BINDING.GEO}) var<uniform> gx_dom: GXDomain;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_IN}) var<storage, read> gx_in: array<vec4<u32>>;`);
            out.push(`@group(${g}) @binding(${BINDING.TESS_POINTS}) var<storage, read> gx_points: array<vec4<u32>>;`);
            out.push(`@group(${g}) @binding(${BINDING.TESS_ARGS}) var<storage, read> gx_targs: array<u32>;`);
            out.push(`@group(${g}) @binding(${BINDING.STAGE_OUT}) var<storage, read_write> gx_out: array<vec4<u32>>;`);
            this.bindings.push({ binding: BINDING.GEO, type: "domain" });
            this.bindings.push({ binding: BINDING.STAGE_IN, type: "stage-in" });
            this.bindings.push({ binding: BINDING.TESS_POINTS, type: "tess-points" });
            this.bindings.push({ binding: BINDING.TESS_ARGS, type: "tess-args" });
            this.bindings.push({ binding: BINDING.STAGE_OUT, type: "stage-out" });
            out.push(`var<private> vicp: array<array<vec4<u32>, ${d.cpRegs}>, ${d.cps}>;`);
            out.push(`var<private> vpc: array<vec4<u32>, ${d.pcRegs}>;`);
            out.push("var<private> gx_domain: vec3<f32>;");
            out.push("var<private> prim_id: u32;");
            return out;
        }

        domainEntry() {
            const d = this.domain, OUT = this.outputCount;
            return "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) gid: vec3<u32>) {\n" +
                "    let k = gid.x + gid.y * 65535u * 64u;\n" +
                // (the tessellator's point count, after the draw's arguments)
                "    if (k >= gx_targs[7]) { return; }\n" +
                "    let point = gx_points[k];\n" +
                "    let u = bitcast<f32>(point.x);\n" +
                "    let v = bitcast<f32>(point.y);\n" +
                (d.domain === 2 ? "    gx_domain = vec3<f32>(u, v, 1.0 - u - v);\n" : "    gx_domain = vec3<f32>(u, v, 0.0);\n") +
                "    let at = point.z * gx_dom.hull_record;\n" +
                `    for (var cp = 0u; cp < ${d.cps}u; cp++) {\n` +
                `        for (var reg = 0u; reg < min(${d.cpRegs}u, gx_dom.cp_regs); reg++) { vicp[cp][reg] = gx_in[at + cp * gx_dom.cp_regs + reg]; }\n` +
                "    }\n" +
                `    for (var reg = 0u; reg < ${d.pcRegs}u; reg++) { vpc[reg] = gx_in[at + gx_dom.pc_at + reg]; }\n` +
                "    prim_id = point.z % max(gx_dom.patches, 1u);\n" +
                "    shader_main();\n" +
                `    for (var reg = 0u; reg < ${OUT}u; reg++) { gx_out[k * ${OUT}u + reg] = o[reg]; }\n` +
                "}\n";
        }

        // ---------------------------------------------------------------
        // Operands

        /** An index (immediate, plus maybe a register's component) as a u32 expression */
        index(index) {
            if (!index.rel) return u32(index.imm);
            const rel = this.read(index.rel, "u") + ".x";
            return index.imm ? `(${u32(index.imm)} + ${rel})` : rel;
        }

        /** The register an operand names, as an lvalue/rvalue of vec4<u32> */
        reg(op) {
            const i = op.indices;
            switch (op.type) {
                case OPERAND.TEMP: return `r[${this.index(i[0])}]`;
                case OPERAND.INPUT:
                    // a geometry shader's are [vertex][register]
                    if (this.mode === "geometry" && i.length > 1) return `v[${this.index(i[0])}][${this.index(i[1])}]`;
                    // a hull shader's control point phase names the input control points v[cp][register]
                    if (this.mode === "hull" && i.length > 1) return `vicp[${this.index(i[0])}][${this.index(i[1])}]`;
                    return `v[${this.index(i[i.length - 1])}]`;
                // (a hull shader's fork and join phases write patch constants)
                case OPERAND.OUTPUT: return this.hsPhase === "fork" || this.hsPhase === "join" ? `opc[${this.index(i[0])}]` : `o[${this.index(i[0])}]`;
                case OPERAND.INPUT_CONTROL_POINT: return `vicp[${this.index(i[0])}][${this.index(i[1])}]`;
                case OPERAND.OUTPUT_CONTROL_POINT: return `vocp[${this.index(i[0])}][${this.index(i[1])}]`;
                case OPERAND.INPUT_PATCH_CONSTANT: return this.mode === "hull" ? `opc[${this.index(i[0])}]` : `vpc[${this.index(i[0])}]`;
                case OPERAND.OUTPUT_CONTROL_POINT_ID: return "vec4<u32>(hs_cpid)";
                case OPERAND.INPUT_FORK_INSTANCE_ID:
                case OPERAND.INPUT_JOIN_INSTANCE_ID: return "vec4<u32>(hs_inst)";
                case OPERAND.INPUT_DOMAIN_POINT: return "bitcast<vec4<u32>>(vec4<f32>(gx_domain, 0.0))";
                case OPERAND.INDEXABLE_TEMP: return `x${i[0].imm}[${this.index(i[1])}]`;
                case OPERAND.CONSTANT_BUFFER: {
                    const slot = i[0].imm;
                    if (!this.p.cbuffers.has(slot)) {
                        this.p.cbuffers.set(slot, { size: 4096, dynamic: true });
                    }
                    return `cb${slot}[${this.index(i[1])}]`;
                }
                case OPERAND.IMMEDIATE_CONSTANT_BUFFER:
                    if (!this.p.icb) this.p.icb = new Uint32Array(4);
                    return `icb[${this.index(i[0])}]`;
                case OPERAND.INPUT_PRIMITIVEID: return "vec4<u32>(prim_id)";
                case OPERAND.INPUT_GS_INSTANCE_ID: return "vec4<u32>(gs_instance)";
                case OPERAND.OUTPUT_DEPTH:
                case OPERAND.OUTPUT_DEPTH_GREATER_EQUAL:
                case OPERAND.OUTPUT_DEPTH_LESS_EQUAL:
                    this.needDepth = true;
                    return "odepth";
                case OPERAND.OUTPUT_COVERAGE_MASK: return "omask";
                // (one sample per fragment)
                case OPERAND.INPUT_COVERAGE_MASK: return "vec4<u32>(select(1u, 1u << gx_sample, gx_ss != 0u))";
                case OPERAND.INPUT_THREAD_ID: return "vec4<u32>(cs_thread, 0u)";
                case OPERAND.INPUT_THREAD_GROUP_ID: return "vec4<u32>(cs_group, 0u)";
                case OPERAND.INPUT_THREAD_ID_IN_GROUP: return "vec4<u32>(cs_local, 0u)";
                case OPERAND.INPUT_THREAD_ID_IN_GROUP_FLATTENED: return "vec4<u32>(cs_flat)";
                case OPERAND.CYCLE_COUNTER: return "vec4<u32>(0u)";
            }
            throw new ShaderTranslateError("operand type " + op.type + " is not supported");
        }

        /**
         * A source operand as vec4 of a type: "u" (raw), "f", "i"; with its
         * swizzle and modifier
         */
        read(op, kind) {
            let value;
            if (op.type === OPERAND.IMMEDIATE32) {
                const v = op.imm.length === 4 ? op.imm : [op.imm[0], op.imm[0], op.imm[0], op.imm[0]];
                value = `vec4<u32>(${v.map(u32).join(", ")})`;
            } else if (op.type === OPERAND.IMMEDIATE64) {
                // the doubles' dwords: two doubles, or one twice
                const v = op.imm.length >= 4 ? op.imm.slice(0, 4) : [op.imm[0], op.imm[1], op.imm[0], op.imm[1]];
                value = `vec4<u32>(${v.map(u32).join(", ")})`;
            } else {
                value = this.reg(op);
                // scalars (odepth, omask) are vectors when read
                if (value === "odepth" || value === "omask") value = `vec4<u32>(${value})`;
                const s = op.swizzle;
                if (op.ncomp === 4 || op.ncomp === 1) {
                    if (!(s[0] === 0 && s[1] === 1 && s[2] === 2 && s[3] === 3)) {
                        value += "." + s.map(c => LANES[c]).join("");
                    }
                }
            }
            if (kind === "u") return value;
            const typed = kind === "f" ? `bitcast<vec4<f32>>(${value})` : `bitcast<vec4<i32>>(${value})`;
            switch (op.modifier) {
                case 1: return `(-${typed})`;
                case 2: return `abs(${typed})`;
                case 3: return `(-abs(${typed}))`;
            }
            return typed;
        }

        f(ins, i) { return this.read(ins.src[i], "f"); }
        i(ins, i) { return this.read(ins.src[i], "i"); }
        u(ins, i) { return this.read(ins.src[i], "u"); }

        /** A double source: its lanes as bits, a negate or abs modifier on each double's high word */
        doubleSource(ins, i) {
            const op = ins.src[i];
            const value = this.read(op, "u");
            switch (op.modifier) {
                case 1: return `(${value} ^ vec4<u32>(0u, 0x80000000u, 0u, 0x80000000u))`;
                case 2: return `(${value} & vec4<u32>(0xFFFFFFFFu, 0x7FFFFFFFu, 0xFFFFFFFFu, 0x7FFFFFFFu))`;
                case 3: return `(${value} | vec4<u32>(0u, 0x80000000u, 0u, 0x80000000u))`;
            }
            return value;
        }

        /**
         * Two results (one per double) onto the destination's written lanes,
         * in order: "dtof r0.z, r1.xy" puts the first in z
         */
        spread(ins, pair, kind) {
            const T = kind === "f" ? "f32" : kind === "i" ? "i32" : "u32";
            return `gx_spread_${T}(${pair}, ${ins.dst[0] ? ins.dst[0].mask : 15}u)`;
        }

        /** The component of a select-1 or scalar source, of a type */
        scalar(ins, i, kind) {
            return this.read(ins.src[i], kind) + ".x";
        }

        /**
         * Write a vec4 value of a type ("f", "i", "u") to a destination,
         * through its write mask; float results may be saturated
         */
        write(ins, value, kind, d = 0) {
            const dst = ins.dst[d];
            if (!dst || dst.type === OPERAND.NULL) return;
            if (kind === "f" && ins.saturate) value = `clamp(${value}, vec4<f32>(0.0), vec4<f32>(1.0))`;
            const bits = kind === "u" ? value : `bitcast<vec4<u32>>(${value})`;
            const target = this.reg(dst);
            if (target === "odepth" || target === "omask") {
                const lane = LANES[Math.max(0, [1, 2, 4, 8].indexOf(dst.mask & -dst.mask))] || "x";
                this.line(`${target} = (${bits}).${lane};`);
                return;
            }
            const mask = dst.mode === "mask" ? dst.mask : ALL;
            if (mask === ALL) {
                this.line(`${target} = ${bits};`);
                return;
            }
            const lanes = [0, 1, 2, 3].filter(c => mask >> c & 1);
            if (lanes.length === 1) {
                this.line(`${target}.${LANES[lanes[0]]} = (${bits}).${LANES[lanes[0]]};`);
                return;
            }
            this.line("{");
            this.indent++;
            this.line(`let t = ${bits};`);
            for (const c of lanes) this.line(`${target}.${LANES[c]} = t.${LANES[c]};`);
            this.indent--;
            this.line("}");
        }

        /** A condition on the first component of a source (if, breakc, ...) */
        test(ins, i = 0) {
            return `${this.u(ins, i)}.x ${ins.test ? "!=" : "=="} 0u`;
        }

        // ---------------------------------------------------------------
        // Instructions

        body(code) {
            for (const ins of code) this.instruction(ins);
            // a switch still open (malformed) is closed
            while (this.switches.length) this.endSwitch();
        }

        instruction(ins) {
            const f = (i) => this.f(ins, i), I = (i) => this.i(ins, i), U = (i) => this.u(ins, i);
            const wf = v => this.write(ins, v, "f"), wi = v => this.write(ins, v, "i"), wu = v => this.write(ins, v, "u");
            const mask = v => `select(vec4<u32>(0u), vec4<u32>(0xFFFFFFFFu), ${v})`;
            const shift = i => `(${U(i)} & vec4<u32>(31u))`;
            switch (ins.op) {
                // float arithmetic
                case OP.ADD: return wf(`${f(0)} + ${f(1)}`);
                case OP.MUL: return wf(`${f(0)} * ${f(1)}`);
                case OP.MAD: return wf(`fma(${f(0)}, ${f(1)}, ${f(2)})`);
                case OP.DIV: return wf(`${f(0)} / ${f(1)}`);
                case OP.MIN: return wf(`min(${f(0)}, ${f(1)})`);
                case OP.MAX: return wf(`max(${f(0)}, ${f(1)})`);
                case OP.SQRT: return wf(`sqrt(${f(0)})`);
                case OP.RSQ: return wf(`inverseSqrt(${f(0)})`);
                case OP.RCP: return wf(`vec4<f32>(1.0) / ${f(0)}`);
                case OP.EXP: return wf(`exp2(${f(0)})`);
                case OP.LOG: return wf(`log2(${f(0)})`);
                case OP.FRC: return wf(`fract(${f(0)})`);
                case OP.ROUND_NE: return wf(`round(${f(0)})`);
                case OP.ROUND_NI: return wf(`floor(${f(0)})`);
                case OP.ROUND_PI: return wf(`ceil(${f(0)})`);
                case OP.ROUND_Z: return wf(`trunc(${f(0)})`);
                case OP.DP2: return wf(`vec4<f32>(dot(${f(0)}.xy, ${f(1)}.xy))`);
                case OP.DP3: return wf(`vec4<f32>(dot(${f(0)}.xyz, ${f(1)}.xyz))`);
                case OP.DP4: return wf(`vec4<f32>(dot(${f(0)}, ${f(1)}))`);
                // double precision (SM5): a double is two lanes (low, high
                // word), so a vec4 holds two; WGSL has no f64, so they are
                // computed as f32 (gx_d2f, gx_f2d): ranges and precision
                // are float's
                case OP.DADD: case OP.DMUL: case OP.DMAX: case OP.DMIN: case OP.DDIV: case OP.DFMA: case OP.DRCP: {
                    this.helpers.add("doubles");
                    const d = i => this.doubleSource(ins, i);
                    const op = {
                        [OP.DADD]: "a + b", [OP.DMUL]: "a * b", [OP.DMAX]: "max(a, b)", [OP.DMIN]: "min(a, b)",
                        [OP.DDIV]: "a / b", [OP.DFMA]: "fma(a, b, c)", [OP.DRCP]: "1.0 / a",
                    }[ins.op];
                    const args = ins.op === OP.DFMA ? 3 : ins.op === OP.DRCP ? 1 : 2;
                    this.line("{");
                    this.indent++;
                    this.line(`let a = gx_d2f2(${d(0)});`);
                    if (args > 1) this.line(`let b = gx_d2f2(${d(1)});`);
                    if (args > 2) this.line(`let c = gx_d2f2(${d(2)});`);
                    wu(`gx_f2d2(${op})`);
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.DEQ: case OP.DGE: case OP.DLT: case OP.DNE: {
                    this.helpers.add("doubles");
                    const cmp = { [OP.DEQ]: "==", [OP.DGE]: ">=", [OP.DLT]: "<", [OP.DNE]: "!=" }[ins.op];
                    const r = `gx_d2f2(${this.doubleSource(ins, 0)}) ${cmp} gx_d2f2(${this.doubleSource(ins, 1)})`;
                    return wu(this.spread(ins, `select(vec2<u32>(0u), vec2<u32>(0xFFFFFFFFu), ${r})`, "u"));
                }
                case OP.DMOV:
                    return wu(this.doubleSource(ins, 0));
                case OP.DMOVC:
                    return wu(`select(${this.doubleSource(ins, 2)}, ${this.doubleSource(ins, 1)}, ${U(0)} != vec4<u32>(0u))`);
                case OP.DTOF:
                    this.helpers.add("doubles");
                    return wf(this.spread(ins, `gx_d2f2(${this.doubleSource(ins, 0)})`, "f"));
                case OP.DTOI:
                    this.helpers.add("doubles");
                    return wi(this.spread(ins, `vec2<i32>(gx_d2f2(${this.doubleSource(ins, 0)}))`, "i"));
                case OP.DTOU:
                    this.helpers.add("doubles");
                    return wu(this.spread(ins, `vec2<u32>(gx_d2f2(${this.doubleSource(ins, 0)}))`, "u"));
                case OP.FTOD: case OP.ITOD: case OP.UTOD: {
                    // the first one or two source lanes, to the destination's doubles
                    this.helpers.add("doubles");
                    const src = ins.op === OP.FTOD ? f(0) : ins.op === OP.ITOD ? `vec4<f32>(${I(0)})` : `vec4<f32>(${U(0)})`;
                    return wu(`gx_f2d2(${src}.xy)`);
                }
                // pull-model interpolation: the attribute where the fragment is (each fragment is a sample)
                case OP.EVAL_SNAPPED: case OP.EVAL_SAMPLE_INDEX: case OP.EVAL_CENTROID:
                    this.warn("eval_* reads the attribute where the fragment is");
                    return wu(U(0));
                case OP.MSAD:
                    this.helpers.add("msad");
                    return wu(`gx_msad(${U(0)}, ${U(1)}, ${U(2)})`);
                case OP.ABORT:
                case OP.DEBUG_BREAK:
                    return;
                case OP.SINCOS:
                    // (the source read once: a destination may be it, "sincos r1.x, r0.x, r1.x")
                    this.line("{");
                    this.indent++;
                    this.line(`let a = ${f(0)};`);
                    if (ins.dst[0] && ins.dst[0].type !== OPERAND.NULL) this.write(ins, "sin(a)", "f", 0);
                    if (ins.dst[1] && ins.dst[1].type !== OPERAND.NULL) this.write(ins, "cos(a)", "f", 1);
                    this.indent--;
                    this.line("}");
                    return;
                case OP.EQ: return wu(mask(`${f(0)} == ${f(1)}`));
                case OP.NE: return wu(mask(`${f(0)} != ${f(1)}`));
                case OP.LT: return wu(mask(`${f(0)} < ${f(1)}`));
                case OP.GE: return wu(mask(`${f(0)} >= ${f(1)}`));
                case OP.MOV:
                    if (ins.saturate || ins.src[0].modifier) return wf(f(0));
                    return wu(U(0));
                case OP.MOVC: {
                    if (ins.saturate) return wf(`select(${f(2)}, ${f(1)}, ${U(0)} != vec4<u32>(0u))`);
                    return wu(`select(${U(2)}, ${U(1)}, ${U(0)} != vec4<u32>(0u))`);
                }
                case OP.SWAPC: {
                    const c = `${U(0)} != vec4<u32>(0u)`;
                    this.line("{");
                    this.indent++;
                    this.line(`let a = ${U(1)};`);
                    this.line(`let b = ${U(2)};`);
                    this.line(`let c = ${c};`);
                    this.write(ins, "select(a, b, c)", "u", 0);
                    this.write(ins, "select(b, a, c)", "u", 1);
                    this.indent--;
                    this.line("}");
                    return;
                }

                // conversions
                case OP.ITOF: return wf(`vec4<f32>(${I(0)})`);
                case OP.UTOF: return wf(`vec4<f32>(${U(0)})`);
                case OP.FTOI: return wi(`vec4<i32>(${f(0)})`);
                case OP.FTOU: return wu(`vec4<u32>(${f(0)})`);
                case OP.F32TOF16:
                    this.helpers.add("f32tof16");
                    return wu(`gx_f32tof16(${f(0)})`);
                case OP.F16TOF32:
                    this.helpers.add("f16tof32");
                    return wf(`gx_f16tof32(${U(0)})`);

                // bits and integers
                case OP.AND: return wu(`${U(0)} & ${U(1)}`);
                case OP.OR: return wu(`${U(0)} | ${U(1)}`);
                case OP.XOR: return wu(`${U(0)} ^ ${U(1)}`);
                case OP.NOT: return wu(`~${U(0)}`);
                case OP.ISHL: return wu(`${U(0)} << ${shift(1)}`);
                case OP.ISHR: return wi(`${I(0)} >> ${shift(1)}`);
                case OP.USHR: return wu(`${U(0)} >> ${shift(1)}`);
                case OP.IADD: return wi(`${I(0)} + ${I(1)}`);
                case OP.INEG: return wi(`-${I(0)}`);
                case OP.IMAD: return wi(`${I(0)} * ${I(1)} + ${I(2)}`);
                case OP.UMAD: return wu(`${U(0)} * ${U(1)} + ${U(2)}`);
                case OP.IMUL:
                case OP.UMUL: {
                    const signed = ins.op === OP.IMUL;
                    this.helpers.add(signed ? "imul_hi" : "umul_hi");
                    // (the sources read once: the high half may overwrite one)
                    this.line("{");
                    this.indent++;
                    this.line(`let a = ${signed ? I(0) : U(0)};`);
                    this.line(`let b = ${signed ? I(1) : U(1)};`);
                    if (ins.dst[0] && ins.dst[0].type !== OPERAND.NULL) {
                        this.write(ins, signed ? "gx_imul_hi(a, b)" : "gx_umul_hi(a, b)", signed ? "i" : "u", 0);
                    }
                    if (ins.dst[1] && ins.dst[1].type !== OPERAND.NULL) this.write(ins, "a * b", signed ? "i" : "u", 1);
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.UDIV: {
                    this.line("{");
                    this.indent++;
                    this.line(`let a = ${U(0)};`);
                    this.line(`let b = ${U(1)};`);
                    this.line("let zero = b == vec4<u32>(0u);");
                    this.line("let safe = select(b, vec4<u32>(1u), zero);");
                    if (ins.dst[0] && ins.dst[0].type !== OPERAND.NULL) this.write(ins, "select(a / safe, vec4<u32>(0xFFFFFFFFu), zero)", "u", 0);
                    if (ins.dst[1] && ins.dst[1].type !== OPERAND.NULL) this.write(ins, "select(a % safe, vec4<u32>(0xFFFFFFFFu), zero)", "u", 1);
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.IMIN: return wi(`min(${I(0)}, ${I(1)})`);
                case OP.IMAX: return wi(`max(${I(0)}, ${I(1)})`);
                case OP.UMIN: return wu(`min(${U(0)}, ${U(1)})`);
                case OP.UMAX: return wu(`max(${U(0)}, ${U(1)})`);
                case OP.IEQ: return wu(mask(`${I(0)} == ${I(1)}`));
                case OP.INE: return wu(mask(`${I(0)} != ${I(1)}`));
                case OP.ILT: return wu(mask(`${I(0)} < ${I(1)}`));
                case OP.IGE: return wu(mask(`${I(0)} >= ${I(1)}`));
                case OP.ULT: return wu(mask(`${U(0)} < ${U(1)}`));
                case OP.UGE: return wu(mask(`${U(0)} >= ${U(1)}`));
                case OP.COUNTBITS: return wu(`countOneBits(${U(0)})`);
                case OP.FIRSTBIT_LO: return wu(`firstTrailingBit(${U(0)})`);
                case OP.FIRSTBIT_HI: {
                    // counted from the top, ~0 if there is none
                    this.line("{");
                    this.indent++;
                    this.line(`let b = firstLeadingBit(${U(0)});`);
                    this.write(ins, "select(vec4<u32>(31u) - b, vec4<u32>(0xFFFFFFFFu), b == vec4<u32>(0xFFFFFFFFu))", "u");
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.FIRSTBIT_SHI: {
                    this.line("{");
                    this.indent++;
                    this.line(`let b = bitcast<vec4<u32>>(firstLeadingBit(${I(0)}));`);
                    this.write(ins, "select(vec4<u32>(31u) - b, vec4<u32>(0xFFFFFFFFu), b == vec4<u32>(0xFFFFFFFFu))", "u");
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.UBFE:
                case OP.IBFE: {
                    // width, offset, value: per component
                    const signed = ins.op === OP.IBFE;
                    this.helpers.add(signed ? "ibfe" : "ubfe");
                    return signed ? wi(`gx_ibfe(${U(0)}, ${U(1)}, ${I(2)})`) : wu(`gx_ubfe(${U(0)}, ${U(1)}, ${U(2)})`);
                }
                case OP.BFI:
                    this.helpers.add("bfi");
                    return wu(`gx_bfi(${U(0)}, ${U(1)}, ${U(2)}, ${U(3)})`);
                case OP.BFREV: return wu(`reverseBits(${U(0)})`);
                case OP.UADDC:
                case OP.USUBB: {
                    const add = ins.op === OP.UADDC;
                    this.line("{");
                    this.indent++;
                    this.line(`let a = ${U(0)};`);
                    this.line(`let b = ${U(1)};`);
                    this.line(`let s = ${add ? "a + b" : "a - b"};`);
                    if (ins.dst[0] && ins.dst[0].type !== OPERAND.NULL) this.write(ins, "s", "u", 0);
                    if (ins.dst[1] && ins.dst[1].type !== OPERAND.NULL) {
                        this.write(ins, add ? "select(vec4<u32>(0u), vec4<u32>(1u), s < a)" : "select(vec4<u32>(0u), vec4<u32>(1u), a < b)", "u", 1);
                    }
                    this.indent--;
                    this.line("}");
                    return;
                }
                case OP.VMWARE:
                    if (ins.vmware === VMWARE_OP.IDIV) {
                        // signed quotient and remainder, by zero ~0
                        this.line("{");
                        this.indent++;
                        this.line(`let a = ${I(0)};`);
                        this.line(`let b = ${I(1)};`);
                        this.line("let zero = b == vec4<i32>(0);");
                        this.line("let safe = select(b, vec4<i32>(1), zero);");
                        if (ins.dst[0] && ins.dst[0].type !== OPERAND.NULL) this.write(ins, "select(a / safe, vec4<i32>(-1), zero)", "i", 0);
                        if (ins.dst[1] && ins.dst[1].type !== OPERAND.NULL) this.write(ins, "select(a % safe, vec4<i32>(-1), zero)", "i", 1);
                        this.indent--;
                        this.line("}");
                        return;
                    }
                    if (ins.vmware === VMWARE_OP.DFRC || ins.vmware === VMWARE_OP.DRSQ) {
                        // double fraction and reciprocal square root (Mesa's
                        // svga), as f32 like the other double instructions
                        this.helpers.add("doubles");
                        this.line("{");
                        this.indent++;
                        this.line(`let a = gx_d2f2(${this.doubleSource(ins, 0)});`);
                        wu(`gx_f2d2(${ins.vmware === VMWARE_OP.DFRC ? "a - floor(a)" : "inverseSqrt(a)"})`);
                        this.indent--;
                        this.line("}");
                        return;
                    }
                    this.warn("VMware opcode " + ins.vmware);
                    return;

                // derivatives
                case OP.DERIV_RTX:
                case OP.DERIV_RTX_COARSE:
                case OP.DERIV_RTX_FINE:
                case OP.DERIV_RTY:
                case OP.DERIV_RTY_COARSE:
                case OP.DERIV_RTY_FINE: {
                    if (this.stage !== PROGRAM.PS) return wf("vec4<f32>(0.0)");
                    const name = {
                        [OP.DERIV_RTX]: "dpdx", [OP.DERIV_RTX_COARSE]: "dpdxCoarse", [OP.DERIV_RTX_FINE]: "dpdxFine",
                        [OP.DERIV_RTY]: "dpdy", [OP.DERIV_RTY_COARSE]: "dpdyCoarse", [OP.DERIV_RTY_FINE]: "dpdyFine",
                    }[ins.op];
                    return wf(`${name}(${f(0)})`);
                }

                // control flow
                case OP.IF:
                    this.line(`if (${this.test(ins)}) {`);
                    this.indent++;
                    return;
                case OP.ELSE:
                    this.indent--;
                    this.line("} else {");
                    this.indent++;
                    return;
                case OP.ENDIF:
                case OP.ENDLOOP:
                    this.indent--;
                    this.line("}");
                    return;
                case OP.LOOP:
                    this.line("loop {");
                    this.indent++;
                    return;
                case OP.BREAK:
                    this.line("break;");
                    return;
                case OP.BREAKC:
                    this.line(`if (${this.test(ins)}) { break; }`);
                    return;
                case OP.CONTINUE:
                    this.line("continue;");
                    return;
                case OP.CONTINUEC:
                    this.line(`if (${this.test(ins)}) { continue; }`);
                    return;
                case OP.RET:
                    this.line("return;");
                    return;
                case OP.RETC:
                    this.line(`if (${this.test(ins)}) { return; }`);
                    return;
                case OP.DISCARD:
                    if (this.stage === PROGRAM.PS) this.line(`if (${this.test(ins)}) { discard; }`);
                    return;
                case OP.CALL:
                    this.line(`label${ins.src[0].indices[0].imm}();`);
                    return;
                case OP.CALLC:
                    this.line(`if (${this.test(ins)}) { label${ins.src[1].indices[0].imm}(); }`);
                    return;
                case OP.SWITCH:
                    this.line(`switch (${this.read(ins.src[0], "i")}.x) {`);
                    this.indent++;
                    this.switches.push({ labels: [], open: false, hasDefault: false });
                    return;
                case OP.CASE:
                case OP.DEFAULT: {
                    const s = this.switches[this.switches.length - 1];
                    if (!s) throw new ShaderTranslateError(ins.name + " outside of a switch");
                    if (s.open) {
                        // the case before falls into this one: D3D compilers end cases with break
                        this.indent--;
                        this.line("}");
                        s.open = false;
                    }
                    if (ins.op === OP.CASE) {
                        s.labels.push(String(ins.src[0].imm[0] | 0) + "i");
                    } else {
                        s.labels.push("default");
                        s.hasDefault = true;
                    }
                    return;
                }
                case OP.ENDSWITCH:
                    this.endSwitch();
                    return;
                case OP.NOP:
                case OP.LABEL:
                case OP.HS_DECLS:
                    return;

                // textures
                case OP.SAMPLE:
                case OP.SAMPLE_B:
                case OP.SAMPLE_L:
                case OP.SAMPLE_D:
                case OP.SAMPLE_C:
                case OP.SAMPLE_C_LZ:
                    return this.sample(ins);
                case OP.GATHER4:
                case OP.GATHER4_C:
                case OP.GATHER4_PO:
                case OP.GATHER4_PO_C:
                    return this.gather(ins);
                case OP.LD:
                case OP.LD_MS:
                    return this.load(ins);
                case OP.RESINFO:
                    return this.resinfo(ins);
                case OP.SAMPLE_INFO: {
                    const count = this.sampleCount(ins.src[0]);
                    const value = (ins.controls & 1) ? `vec4<u32>(${count}, 0u, 0u, 0u)` : `vec4<f32>(f32(${count}), 0.0, 0.0, 0.0)`;
                    return this.write(ins, this.swizzled(value, ins.src[0]), (ins.controls & 1) ? "u" : "f");
                }
                case OP.SAMPLE_POS:
                    this.helpers.add("sample_pos");
                    return this.write(ins, this.swizzled(`gx_sample_pos(${this.u(ins, 1)}.x, ${this.sampleCount(ins.src[0])})`, ins.src[0]), "f");
                case OP.LOD:
                    return this.lod(ins);
                case OP.BUFINFO: {
                    // the buffer's words past the view's start, in elements (raw: bytes)
                    const r = ins.src[0];
                    const slot = r.indices[0].imm;
                    const b = this.bufferName(r);
                    const decl = (r.type === OPERAND.RESOURCE ? this.p.resources : this.p.uavs).get(slot) || {};
                    const words = `(arrayLength(&${b.name}) - ${b.base})`;
                    const lanes = decl.kind === "typed" ? ((this.o.uavFormats || {})[slot] || {}).lanes || 1 : 0;
                    const elements = decl.kind === "structured" ? `${words} * 4u / ${Math.max(4, decl.stride || 4)}u` :
                        decl.kind === "raw" ? `${words} * 4u` : lanes ? `${words} / ${lanes}u` : words;
                    return wu(`vec4<u32>(${elements})`);
                }
                case OP.LD_UAV_TYPED:
                    return this.loadTyped(ins);
                case OP.STORE_UAV_TYPED:
                    return this.storeTyped(ins);
                case OP.LD_RAW:
                    return this.loadRaw(ins, false);
                case OP.LD_STRUCTURED:
                    return this.loadRaw(ins, true);
                case OP.STORE_RAW:
                    return this.storeRaw(ins, false);
                case OP.STORE_STRUCTURED:
                    return this.storeRaw(ins, true);
                case OP.SYNC:
                    if (ins.controls & 1) this.line("workgroupBarrier();");
                    else if (ins.controls & 0xC) this.line("storageBarrier();");
                    return;
                case OP.EMIT:
                case OP.CUT:
                case OP.EMITTHENCUT:
                case OP.EMIT_STREAM:
                case OP.CUT_STREAM:
                case OP.EMITTHENCUT_STREAM: {
                    if (this.mode !== "geometry") throw new ShaderTranslateError("geometry shader instruction " + ins.name);
                    const streamed = ins.op === OP.EMIT_STREAM || ins.op === OP.CUT_STREAM || ins.op === OP.EMITTHENCUT_STREAM;
                    const operand = (ins.dst && ins.dst[0]) || (ins.src && ins.src[0]);
                    const stream = streamed && operand ? operand.indices[0].imm : 0;
                    if (stream !== 0) {
                        // only stream 0 is rasterized; the others only feed stream output
                        this.warn("geometry shader stream " + stream + " is not emulated");
                        return;
                    }
                    const emit = ins.op === OP.EMIT || ins.op === OP.EMITTHENCUT || ins.op === OP.EMIT_STREAM || ins.op === OP.EMITTHENCUT_STREAM;
                    const cut = ins.op === OP.CUT || ins.op === OP.EMITTHENCUT || ins.op === OP.CUT_STREAM || ins.op === OP.EMITTHENCUT_STREAM;
                    if (emit) this.line("gs_emit();");
                    if (cut) this.line("gs_cut();");
                    return;
                }
            }
            if (ins.op >= OP.ATOMIC_AND && ins.op <= OP.IMM_ATOMIC_UMIN) return this.atomic(ins);
            throw new ShaderTranslateError("instruction " + ins.name + " is not supported");
        }

        endSwitch() {
            const s = this.switches.pop();
            if (s.open) {
                this.indent--;
                this.line("}");
            }
            if (s.labels.length) {
                // labels with no code (at the end)
                this.line(s.labels.length === 1 && s.labels[0] === "default" ? "default: {}" : `case ${s.labels.join(", ")}: {}`);
                if (s.labels.includes("default")) s.hasDefault = true;
            }
            if (!s.hasDefault) this.line("default: {}");
            this.indent--;
            this.line("}");
        }

        /** Code inside a switch opens the case its labels name */
        openCase() {
            const s = this.switches[this.switches.length - 1];
            if (!s || s.open) return;
            if (!s.labels.length) return;
            this.line(`case ${s.labels.join(", ")}: {`);
            if (s.labels.includes("default")) s.hasDefault = true;
            s.labels = [];
            s.open = true;
            this.indent++;
        }

        // ---------------------------------------------------------------
        // Texture instructions

        /** The coordinates a dimension takes, from a float address: [coords, array index or null] */
        coordinates(dimension, address) {
            switch (dimension) {
                case DIM.TEXTURE1D: return [`vec2<f32>(${address}.x, 0.5)`, null];
                case DIM.TEXTURE1DARRAY: return [`vec2<f32>(${address}.x, 0.5)`, `i32(round(${address}.y))`];
                case DIM.TEXTURE2D:
                case DIM.TEXTURE2DMS: return [`${address}.xy`, null];
                case DIM.TEXTURE2DARRAY:
                case DIM.TEXTURE2DMSARRAY: return [`${address}.xy`, `i32(round(${address}.z))`];
                case DIM.TEXTURE3D:
                case DIM.TEXTURECUBE: return [`${address}.xyz`, null];
                case DIM.TEXTURECUBEARRAY: return [`${address}.xyz`, `i32(round(${address}.w))`];
            }
            throw new ShaderTranslateError("sampling a resource of dimension " + dimension);
        }

        offset(ins, dimension) {
            const o = ins.offsets;
            if (!o || (!o[0] && !o[1] && !o[2])) return null;
            if (dimension === DIM.TEXTURECUBE || dimension === DIM.TEXTURECUBEARRAY) return null;
            if (dimension === DIM.TEXTURE3D) return `vec3<i32>(${o[0]}, ${o[1]}, ${o[2]})`;
            if (dimension === DIM.TEXTURE1D || dimension === DIM.TEXTURE1DARRAY) return `vec2<i32>(${o[0]}, 0)`;
            return `vec2<i32>(${o[0]}, ${o[1]})`;
        }

        resource(operand) {
            const slot = operand.indices[0].imm;
            const r = this.p.resources.get(slot);
            if (!r) throw new ShaderTranslateError("resource t" + slot + " is not declared");
            return { slot, r, name: "t" + slot };
        }

        /** The result of a texture instruction (a vec4 of the resource's type) through the resource's swizzle */
        swizzled(value, operand) {
            const s = operand.swizzle;
            if (s[0] === 0 && s[1] === 1 && s[2] === 2 && s[3] === 3) return value;
            return `(${value}).${s.map(c => LANES[c]).join("")}`;
        }

        resultKind(r) {
            const ret = r.returnTypes ? r.returnTypes[0] : RETURN.FLOAT;
            return ret === RETURN.SINT ? "i" : ret === RETURN.UINT ? "u" : "f";
        }

        /** A sampler's name, for comparisons or not (twinSamplers) */
        samplerName(operand, compare) {
            const slot = operand.indices[0].imm;
            return (compare && this.twinSamplers.has(slot) ? "sc" : "s") + slot;
        }

        /**
         * Sampling an integer texture (GL's texture() on an isampler, as
         * Mesa's svga sends it; WGSL samples only floats): the texel under
         * the coordinates, clamped to the level's edges
         */
        sampleInteger(ins, t, kind) {
            const a = this.f(ins, 0), name = t.name;
            const level = ins.op === OP.SAMPLE_L ? `i32(${this.scalar(ins, 3, "f")})` : "0";
            const o = ins.offsets || [0, 0, 0];
            const texel = (coords, size, offset) =>
                `clamp(vec${size.n}<i32>(floor(${coords} * vec${size.n}<f32>(${size.v}))) + ${offset}, vec${size.n}<i32>(0), ${size.v} - vec${size.n}<i32>(1))`;
            const layer = c => `clamp(i32(round(${c})), 0, i32(textureNumLayers(${name})) - 1)`;
            let call;
            switch (t.r.dimension) {
                case DIM.TEXTURE1D:
                case DIM.TEXTURE1DARRAY: {
                    const size = { n: 2, v: `vec2<i32>(textureDimensions(${name}, ${level}))` };
                    const at = texel(`vec2<f32>(${a}.x, 0.0)`, size, `vec2<i32>(${o[0]}, 0)`);
                    call = t.r.dimension === DIM.TEXTURE1D ? `textureLoad(${name}, ${at}, ${level})` :
                        `textureLoad(${name}, ${at}, ${layer(a + ".y")}, ${level})`;
                    break;
                }
                case DIM.TEXTURE2D:
                case DIM.TEXTURE2DARRAY: {
                    const size = { n: 2, v: `vec2<i32>(textureDimensions(${name}, ${level}))` };
                    const at = texel(`${a}.xy`, size, `vec2<i32>(${o[0]}, ${o[1]})`);
                    call = t.r.dimension === DIM.TEXTURE2D ? `textureLoad(${name}, ${at}, ${level})` :
                        `textureLoad(${name}, ${at}, ${layer(a + ".z")}, ${level})`;
                    break;
                }
                case DIM.TEXTURE3D: {
                    const size = { n: 3, v: `vec3<i32>(textureDimensions(${name}, ${level}))` };
                    call = `textureLoad(${name}, ${texel(`${a}.xyz`, size, `vec3<i32>(${o[0]}, ${o[1]}, ${o[2]})`)}, ${level})`;
                    break;
                }
                default:
                    // (cubes: a texel of a face; not done)
                    this.warn("sampling an integer cube texture");
                    call = kind === "i" ? "vec4<i32>(0)" : "vec4<u32>(0u)";
            }
            this.write(ins, this.swizzled(call, ins.src[1]), kind);
        }

        sample(ins) {
            const t = this.resource(ins.src[1]);
            const integer = this.resultKind(t.r);
            if (integer !== "f" && !this.compared.has(t.slot) && ins.op !== OP.SAMPLE_C && ins.op !== OP.SAMPLE_C_LZ) {
                return this.sampleInteger(ins, t, integer);
            }
            const sampler = this.samplerName(ins.src[2], ins.op === OP.SAMPLE_C || ins.op === OP.SAMPLE_C_LZ);
            const dimension = t.r.dimension;
            const [coords, layer] = this.coordinates(dimension, this.f(ins, 0));
            const offset = this.offset(ins, dimension);
            const args = [t.name, sampler, coords];
            if (layer) args.push(layer);
            const fragment = this.stage === PROGRAM.PS;
            const depth = this.compared.has(t.slot);
            let call;
            switch (ins.op) {
                case OP.SAMPLE:
                    call = fragment ? `textureSample(${args.join(", ")}${offset ? ", " + offset : ""})` :
                        `textureSampleLevel(${args.join(", ")}, ${depth ? "0" : "0.0"}${offset ? ", " + offset : ""})`;
                    break;
                case OP.SAMPLE_B:
                    call = fragment ? `textureSampleBias(${args.join(", ")}, ${this.scalar(ins, 3, "f")}${offset ? ", " + offset : ""})` :
                        `textureSampleLevel(${args.join(", ")}, 0.0${offset ? ", " + offset : ""})`;
                    break;
                case OP.SAMPLE_L:
                    call = depth ? `textureSampleLevel(${args.join(", ")}, i32(${this.scalar(ins, 3, "f")})${offset ? ", " + offset : ""})` :
                        `textureSampleLevel(${args.join(", ")}, ${this.scalar(ins, 3, "f")}${offset ? ", " + offset : ""})`;
                    break;
                case OP.SAMPLE_D: {
                    const width = dimension === DIM.TEXTURE3D || dimension === DIM.TEXTURECUBE || dimension === DIM.TEXTURECUBEARRAY ? "xyz" :
                        dimension === DIM.TEXTURE1D || dimension === DIM.TEXTURE1DARRAY ? null : "xy";
                    const grad = i => width ? `${this.f(ins, i)}.${width}` : `vec2<f32>(${this.f(ins, i)}.x, 0.0)`;
                    call = `textureSampleGrad(${args.join(", ")}, ${grad(3)}, ${grad(4)}${offset ? ", " + offset : ""})`;
                    break;
                }
                case OP.SAMPLE_C:
                case OP.SAMPLE_C_LZ: {
                    const reference = this.scalar(ins, 3, "f");
                    const level = ins.op === OP.SAMPLE_C_LZ || !fragment;
                    call = `vec4<f32>(${level ? "textureSampleCompareLevel" : "textureSampleCompare"}(${args.join(", ")}, ${reference}${offset ? ", " + offset : ""}))`;
                    return this.write(ins, this.swizzled(call, ins.src[1]), "f");
                }
            }
            if (depth) call = `vec4<f32>(${call})`;
            this.write(ins, this.swizzled(call, ins.src[1]), "f");
        }

        gather(ins) {
            const po = ins.op === OP.GATHER4_PO || ins.op === OP.GATHER4_PO_C;
            const compare = ins.op === OP.GATHER4_C || ins.op === OP.GATHER4_PO_C;
            const tOperand = ins.src[po ? 2 : 1], sOperand = ins.src[po ? 3 : 2];
            const t = this.resource(tOperand);
            const sampler = this.samplerName(sOperand, compare);
            const dimension = t.r.dimension;
            let address = this.f(ins, 0);
            const [coords0, layer] = this.coordinates(dimension, address);
            let coords = coords0;
            let offset = this.offset(ins, dimension);
            if (po) {
                // programmable offsets: WGSL wants constants, so the
                // coordinates move by the offset in texels instead
                coords = `(${coords0} + vec2<f32>(${this.i(ins, 1)}.xy) / vec2<f32>(textureDimensions(${t.name})))`;
                offset = null;
            }
            const component = sOperand.swizzle[0];
            const args = [t.name, sampler, coords];
            if (layer) args.push(layer);
            let call;
            if (compare) {
                call = `textureGatherCompare(${args.join(", ")}, ${this.scalar(ins, po ? 4 : 3, "f")}${offset ? ", " + offset : ""})`;
            } else if (this.compared.has(t.slot)) {
                call = `textureGather(${args.join(", ")}${offset ? ", " + offset : ""})`;
            } else {
                call = `textureGather(${component}, ${args.join(", ")}${offset ? ", " + offset : ""})`;
            }
            this.write(ins, this.swizzled(call, tOperand), compare ? "f" : this.resultKind(t.r));
        }

        load(ins) {
            const ms = ins.op === OP.LD_MS;
            const tOperand = ins.src[1];
            if (tOperand.type === OPERAND.UAV) return this.loadTyped(ins);
            const t = this.resource(tOperand);
            const dimension = t.r.dimension;
            const a = this.i(ins, 0);
            const o = ins.offsets || [0, 0, 0];
            const off2 = o[0] || o[1] ? ` + vec2<i32>(${o[0]}, ${o[1]})` : "";
            const kind = this.compared.has(t.slot) ? "f" : this.resultKind(t.r);
            let call;
            switch (dimension) {
                case DIM.BUFFER:
                    return this.loadTypedBuffer(ins, t);
                case DIM.TEXTURE1D:
                    call = `textureLoad(${t.name}, vec2<i32>(${a}.x + ${o[0]}, 0), ${a}.w)`; break;
                case DIM.TEXTURE1DARRAY:
                    call = `textureLoad(${t.name}, vec2<i32>(${a}.x + ${o[0]}, 0), ${a}.y, ${a}.w)`; break;
                case DIM.TEXTURE2D:
                    call = `textureLoad(${t.name}, ${a}.xy${off2}, ${a}.w)`; break;
                case DIM.TEXTURE2DARRAY:
                    call = `textureLoad(${t.name}, ${a}.xy${off2}, ${a}.z, ${a}.w)`; break;
                case DIM.TEXTURE3D:
                    call = `textureLoad(${t.name}, ${a}.xyz${o[0] || o[1] || o[2] ? ` + vec3<i32>(${o[0]}, ${o[1]}, ${o[2]})` : ""}, ${a}.w)`; break;
                case DIM.TEXTURE2DMS:
                case DIM.TEXTURE2DMSARRAY: {
                    // (2 x 2 texels a pixel for 4 samples, 4 x 2 for 8)
                    this.helpers.add("ms_texel");
                    const eight = this.msSamples(t.slot) === 8;
                    const sample = `u32(${ms ? this.scalar(ins, 2, "i") : "0"})`;
                    const texel = `(${a}.xy${off2}) * ${eight ? "vec2<i32>(4, 2)" : "2"} + ${eight ? `gx_ms_texel8(${sample})` : `gx_ms_texel(${sample})`}`;
                    call = dimension === DIM.TEXTURE2DMS ? `textureLoad(${t.name}, ${texel}, 0)` : `textureLoad(${t.name}, ${texel}, ${a}.z, 0)`;
                    break;
                }
                default:
                    throw new ShaderTranslateError("ld from a resource of dimension " + dimension);
            }
            if (this.compared.has(t.slot)) call = `vec4<f32>(${call})`;
            this.write(ins, this.swizzled(call, tOperand), kind);
        }

        /**
         * A typed buffer's element: decoded by the view's format (GX gives
         * it, o.srvFormats: a WebGPU format name) from the 32-bit words,
         * from the view's first element on; what the format lacks is 0, alpha 1
         */
        loadTypedBuffer(ins, t) {
            const format = ((this.o.srvFormats || {})[t.slot] || {}).format || "rgba32uint";
            const name = `gx_tb${t.slot}`;
            if (!this.typedBuffers.has(name)) this.typedBuffers.set(name, typedBufferReader(name, t.name, format));
            this.usesViews = true;
            const index = `(u32(${this.i(ins, 0)}.x) + gx_view_base(${VIEW_BASE_RESOURCE + t.slot}u))`;
            this.write(ins, this.swizzled(`${name}(${index})`, ins.src[1]), "u");
        }

        resinfo(ins) {
            const t = this.resource(ins.src[1]);
            const dimension = t.r.dimension;
            const mip = `u32(${this.i(ins, 0)}.x)`;
            const type = ins.controls & 3;
            let dims;
            const ms = dimension === DIM.TEXTURE2DMS || dimension === DIM.TEXTURE2DMSARRAY;
            const levels = ms ? "1u" : `textureNumLevels(${t.name})`;
            const level = ms ? "" : `, ${mip}`;
            switch (dimension) {
                case DIM.TEXTURE1D: dims = `vec4<u32>(textureDimensions(${t.name}${level}).x, 0u, 0u, ${levels})`; break;
                case DIM.TEXTURE1DARRAY: dims = `vec4<u32>(textureDimensions(${t.name}${level}).x, textureNumLayers(${t.name}), 0u, ${levels})`; break;
                case DIM.TEXTURE2D:
                case DIM.TEXTURECUBE: dims = `vec4<u32>(textureDimensions(${t.name}${level}), 0u, ${levels})`; break;
                // (supersampled: the texture is 2 x 2 or 4 x 2 times the surface)
                case DIM.TEXTURE2DMS: dims = `vec4<u32>(textureDimensions(${t.name}) / ${this.msScale(t.slot)}, 0u, 1u)`; break;
                case DIM.TEXTURE2DARRAY:
                case DIM.TEXTURECUBEARRAY: dims = `vec4<u32>(textureDimensions(${t.name}${level}), textureNumLayers(${t.name}), ${levels})`; break;
                case DIM.TEXTURE2DMSARRAY: dims = `vec4<u32>(textureDimensions(${t.name}) / ${this.msScale(t.slot)}, textureNumLayers(${t.name}), 1u)`; break;
                case DIM.TEXTURE3D: dims = `vec4<u32>(textureDimensions(${t.name}${level}), ${levels})`; break;
                default: throw new ShaderTranslateError("resinfo of dimension " + dimension);
            }
            // (a mip level beyond the texture reads zeros in D3D; WGSL clamps it)
            if (type === 2) return this.write(ins, this.swizzled(dims, ins.src[1]), "u");
            let value = `vec4<f32>(${dims})`;
            if (type === 1) value = `vec4<f32>(vec3<f32>(1.0) / vec4<f32>(${dims}).xyz, f32(${levels}))`;
            this.write(ins, this.swizzled(value, ins.src[1]), "f");
        }

        /**
         * The samples of the rasterizer (the pipeline's, an override
         * constant) or of a multisampled resource, as a u32 expression
         */
        sampleCount(operand) {
            if (operand.type === OPERAND.RASTERIZER) {
                this.usesSamples = true;
                return "gx_samples";
            }
            const t = this.resource(operand);
            const ms = t.r.dimension === DIM.TEXTURE2DMS || t.r.dimension === DIM.TEXTURE2DMSARRAY;
            return ms ? this.msSamples(t.slot) + "u" : "1u";
        }

        /** A multisampled resource's samples (options.msSamples; 4 when not said) */
        msSamples(slot) {
            return ((this.o.msSamples || {})[slot]) || 4;
        }

        /** ... and how many texels wide and high a pixel is */
        msScale(slot) {
            return this.msSamples(slot) === 8 ? "vec2<u32>(4u, 2u)" : "2u";
        }

        /**
         * lod: the mip level a sample would take, from the coordinates'
         * derivatives (WGSL has no query): x clamped to the view's levels,
         * y not. Only pixel shaders have derivatives; elsewhere it is 0.
         */
        lod(ins) {
            const t = this.resource(ins.src[1]);
            if (this.stage !== PROGRAM.PS) return this.write(ins, "vec4<f32>(0.0)", "f");
            const a = this.f(ins, 0), name = t.name;
            let coords, size;
            switch (t.r.dimension) {
                case DIM.TEXTURE1D:
                case DIM.TEXTURE1DARRAY:
                    coords = `vec3<f32>(${a}.x, 0.0, 0.0)`;
                    size = `vec3<f32>(f32(textureDimensions(${name}).x), 0.0, 0.0)`;
                    break;
                case DIM.TEXTURE2D:
                case DIM.TEXTURE2DARRAY:
                    coords = `vec3<f32>(${a}.xy, 0.0)`;
                    size = `vec3<f32>(vec2<f32>(textureDimensions(${name})), 0.0)`;
                    break;
                case DIM.TEXTURE3D:
                    coords = `${a}.xyz`;
                    size = `vec3<f32>(textureDimensions(${name}))`;
                    break;
                case DIM.TEXTURECUBE:
                case DIM.TEXTURECUBEARRAY:
                    // on the face: the direction over its major axis, [-1, 1] across
                    this.helpers.add("cube_face");
                    coords = `gx_cube_face(${a}.xyz)`;
                    size = `vec3<f32>(f32(textureDimensions(${name}).x) * 0.5)`;
                    break;
                default:
                    throw new ShaderTranslateError("lod of a resource of dimension " + t.r.dimension);
            }
            this.helpers.add("lod");
            this.write(ins, this.swizzled(`gx_lod(${coords} * ${size}, f32(textureNumLevels(${name})))`, ins.src[1]), "f");
        }

        // ---------------------------------------------------------------
        // Raw and structured buffers, atomics (SM5)

        /**
         * A typed texture UAV: a storage texture of the bound view's format
         * (options.uavFormats; R32 of the declared type when none is bound),
         * read-write if the shader reads it (WebGPU can for R32 formats only,
         * as D3D11.0 can)
         */
        storageTexture(g, slot, u) {
            const t = this.storageInfo(slot, u);
            if (this.uavLoads.has(slot) && t.access !== "read_write") this.warn("typed UAV loads of " + t.format + " read zeros");
            this.bindings.push({ binding: BINDING.UAV + slot, slot, type: "uav-texture", format: t.format, access: t.access, dimension: t.dimension });
            return `@group(${g}) @binding(${BINDING.UAV + slot}) var u${slot}: texture_storage_${t.wgsl}<${t.format}, ${t.access}>;`;
        }

        /** A typed texture UAV's storage format, access, dimension and texel kind */
        storageInfo(slot, u) {
            const info = (this.o.uavFormats || {})[slot] || {};
            const ret = u.returnTypes ? u.returnTypes[0] : RETURN.FLOAT;
            const format = info.format || (ret === RETURN.UINT ? "r32uint" : ret === RETURN.SINT ? "r32sint" : "r32float");
            const access = this.uavLoads.has(slot) && /^r32/.test(format) ? "read_write" : "write";
            const [wgsl, dimension] = {
                [DIM.TEXTURE1D]: ["2d", "2d"], [DIM.TEXTURE2D]: ["2d", "2d"],
                [DIM.TEXTURE1DARRAY]: ["2d_array", "2d-array"], [DIM.TEXTURE2DARRAY]: ["2d_array", "2d-array"],
                [DIM.TEXTURE3D]: ["3d", "3d"],
            }[u.dimension] || [];
            if (!wgsl) throw new ShaderTranslateError("a typed UAV of dimension " + u.dimension);
            const kind = /uint$/.test(format) ? "u" : /sint$/.test(format) ? "i" : "f";
            return { format, access, wgsl, dimension, kind };
        }

        /** A typed UAV's coordinates and layer, from an integer address */
        storageAddress(slot, a) {
            const u = this.p.uavs.get(slot);
            switch (u.dimension) {
                case DIM.TEXTURE1D: return `vec2<i32>(${a}.x, 0)`;
                case DIM.TEXTURE1DARRAY: return `vec2<i32>(${a}.x, 0), ${a}.y`;
                case DIM.TEXTURE2D: return `${a}.xy`;
                case DIM.TEXTURE2DARRAY: return `${a}.xy, ${a}.z`;
                case DIM.TEXTURE3D: return `${a}.xyz`;
            }
            throw new ShaderTranslateError("a typed UAV of dimension " + u.dimension);
        }

        loadTyped(ins) {
            const operand = ins.src[1];
            const slot = operand.indices[0].imm;
            const u = this.p.uavs.get(slot);
            if (!u) throw new ShaderTranslateError("UAV u" + slot + " is not declared");
            if (u.dimension === DIM.BUFFER) {
                const b = this.bufferName(operand);
                const lanes = ((this.o.uavFormats || {})[slot] || {}).lanes || 1;
                const word = k => k < lanes ? `atomicLoad(&u${slot}[${b.base} + base + ${k}u])` : k === 3 ? "1u" : "0u";
                this.line("{");
                this.indent++;
                this.line(`let base = u32(${this.i(ins, 0)}.x) * ${lanes}u;`);
                this.write(ins, this.swizzled(`vec4<u32>(${word(0)}, ${word(1)}, ${word(2)}, ${word(3)})`, operand), "u");
                this.indent--;
                this.line("}");
                return;
            }
            const t = this.storageInfo(slot, u);
            if (t.access !== "read_write") return this.write(ins, "vec4<u32>(0u)", "u");
            this.write(ins, this.swizzled(`textureLoad(u${slot}, ${this.storageAddress(slot, this.i(ins, 0))})`, operand), t.kind);
        }

        storeTyped(ins) {
            const dst = ins.dst[0];
            const slot = dst.indices[0].imm;
            const u = this.p.uavs.get(slot);
            if (!u) throw new ShaderTranslateError("UAV u" + slot + " is not declared");
            if (u.dimension === DIM.BUFFER) {
                const b = this.bufferName(dst);
                const lanes = ((this.o.uavFormats || {})[slot] || {}).lanes || 1;
                this.line("{");
                this.indent++;
                this.line(`let base = u32(${this.i(ins, 0)}.x) * ${lanes}u;`);
                this.line(`let value = ${this.u(ins, 1)};`);
                for (let c = 0; c < lanes; c++) this.line(`atomicStore(&u${slot}[${b.base} + base + ${c}u], value.${LANES[c]});`);
                this.indent--;
                this.line("}");
                return;
            }
            const kind = this.storageInfo(slot, u).kind;
            const value = kind === "u" ? this.u(ins, 1) : kind === "i" ? this.i(ins, 1) : this.f(ins, 1);
            this.line(`textureStore(u${slot}, ${this.storageAddress(slot, this.i(ins, 0))}, ${value});`);
        }

        bufferName(operand) {
            const slot = operand.indices[0].imm;
            // (a view's first element: from GXViews)
            const base = index => { this.usesViews = true; return `gx_view_base(${index}u)`; };
            switch (operand.type) {
                case OPERAND.RESOURCE: return { name: "t" + slot, atomic: false, stride: (this.p.resources.get(slot) || {}).stride || 0,
                    base: base(VIEW_BASE_RESOURCE + slot) };
                case OPERAND.UAV: return { name: "u" + slot, atomic: true, stride: (this.p.uavs.get(slot) || {}).stride || 0,
                    base: base(VIEW_BASE_UAV + slot) };
                case OPERAND.THREAD_GROUP_SHARED_MEMORY: return { name: "g" + slot, atomic: true, stride: (this.p.tgsm.get(slot) || {}).stride || 0,
                    base: "0u" };
            }
            throw new ShaderTranslateError("a buffer operand of type " + operand.type);
        }

        loadRaw(ins, structured) {
            const b = this.bufferName(ins.src[structured ? 2 : 1]);
            const address = structured ? `(u32(${this.u(ins, 0)}.x) * ${b.stride}u + u32(${this.u(ins, 1)}.x)) / 4u` :
                `u32(${this.u(ins, 0)}.x) / 4u`;
            const word = k => b.atomic ? `atomicLoad(&${b.name}[base + ${k}u])` : `${b.name}[base + ${k}u]`;
            this.line("{");
            this.indent++;
            this.line(`let base = ${b.base} + ${address};`);
            this.write(ins, this.swizzled(`vec4<u32>(${word(0)}, ${word(1)}, ${word(2)}, ${word(3)})`, ins.src[structured ? 2 : 1]), "u");
            this.indent--;
            this.line("}");
        }

        storeRaw(ins, structured) {
            const dst = ins.dst[0];
            const b = this.bufferName(dst);
            const address = structured ? `(u32(${this.u(ins, 0)}.x) * ${b.stride}u + u32(${this.u(ins, 1)}.x)) / 4u` :
                `u32(${this.u(ins, 0)}.x) / 4u`;
            const value = this.u(ins, structured ? 2 : 1);
            this.line("{");
            this.indent++;
            this.line(`let base = ${b.base} + ${address};`);
            this.line(`let value = ${value};`);
            let k = 0;
            for (let c = 0; c < 4; c++) {
                if (!(dst.mask >> c & 1)) continue;
                this.line(b.atomic ? `atomicStore(&${b.name}[base + ${k}u], value.${LANES[c]});` : `${b.name}[base + ${k}u] = value.${LANES[c]};`);
                k++;
            }
            this.indent--;
            this.line("}");
        }

        atomic(ins) {
            const immediate = ins.op >= OP.IMM_ATOMIC_ALLOC;
            const target = immediate ? ins.src[0] : ins.dst[0];
            const srcs = immediate ? ins.src.slice(1) : ins.src;
            if (ins.op === OP.IMM_ATOMIC_ALLOC || ins.op === OP.IMM_ATOMIC_CONSUME) {
                // the UAV's hidden counter: the index before the increment, or after the decrement
                const slot = target.indices[0].imm;
                return this.write(ins, ins.op === OP.IMM_ATOMIC_ALLOC ? `vec4<u32>(atomicAdd(&uc${slot}, 1u))` :
                    `vec4<u32>(atomicSub(&uc${slot}, 1u) - 1u)`, "u");
            }
            if (target.type === OPERAND.UAV && (this.p.uavs.get(target.indices[0].imm) || {}).kind === "typed" &&
                this.p.uavs.get(target.indices[0].imm).dimension !== DIM.BUFFER) {
                this.warn("atomics on typed texture UAVs are not supported");
                if (immediate) this.write(ins, "vec4<u32>(0u)", "u");
                return;
            }
            const b = this.bufferName(target);
            const read = i => this.read(srcs[i], "u");
            // raw: a byte address; structured: (element, byte offset); typed buffer: an element
            const typedLanes = target.type === OPERAND.UAV && (this.p.uavs.get(target.indices[0].imm) || {}).kind === "typed" ?
                ((this.o.uavFormats || {})[target.indices[0].imm] || {}).lanes || 1 : 0;
            const address = `${b.base} + ` + (typedLanes ? `${read(0)}.x * ${typedLanes}u` :
                b.stride ? `(${read(0)}.x * ${b.stride}u + ${read(0)}.y) / 4u` : `${read(0)}.x / 4u`);
            const name = {
                [OP.ATOMIC_AND]: "atomicAnd", [OP.ATOMIC_OR]: "atomicOr", [OP.ATOMIC_XOR]: "atomicXor",
                [OP.ATOMIC_IADD]: "atomicAdd", [OP.ATOMIC_UMAX]: "atomicMax", [OP.ATOMIC_UMIN]: "atomicMin",
                [OP.ATOMIC_IMAX]: "atomicMax", [OP.ATOMIC_IMIN]: "atomicMin",
                [OP.IMM_ATOMIC_IADD]: "atomicAdd", [OP.IMM_ATOMIC_AND]: "atomicAnd", [OP.IMM_ATOMIC_OR]: "atomicOr",
                [OP.IMM_ATOMIC_XOR]: "atomicXor", [OP.IMM_ATOMIC_EXCH]: "atomicExchange",
                [OP.IMM_ATOMIC_UMAX]: "atomicMax", [OP.IMM_ATOMIC_UMIN]: "atomicMin",
                [OP.IMM_ATOMIC_IMAX]: "atomicMax", [OP.IMM_ATOMIC_IMIN]: "atomicMin",
            }[ins.op];
            if (ins.op === OP.ATOMIC_IMAX || ins.op === OP.ATOMIC_IMIN || ins.op === OP.IMM_ATOMIC_IMAX || ins.op === OP.IMM_ATOMIC_IMIN) {
                this.warn("signed atomic min/max are done unsigned");
            }
            if (ins.op === OP.ATOMIC_CMP_STORE || ins.op === OP.IMM_ATOMIC_CMP_EXCH) {
                const call = `atomicCompareExchangeWeak(&${b.name}[${address}], ${read(1)}.x, ${read(2)}.x).old_value`;
                if (immediate) this.write(ins, `vec4<u32>(${call})`, "u");
                else this.line(`_ = ${call};`);
                return;
            }
            const call = `${name}(&${b.name}[${address}], ${read(1)}.x)`;
            if (immediate) this.write(ins, `vec4<u32>(${call})`, "u");
            else this.line(`_ = ${call};`);
        }

        // ---------------------------------------------------------------

        helperCode() {
            const h = this.helpers, out = [...this.typedBuffers.values()];
            if (h.has("umul_hi") || h.has("imul_hi")) {
                out.push(`fn gx_umul_hi1(a: u32, b: u32) -> u32 {
    let al = a & 0xFFFFu; let ah = a >> 16u; let bl = b & 0xFFFFu; let bh = b >> 16u;
    let ll = al * bl; let lh = al * bh; let hl = ah * bl; let hh = ah * bh;
    let mid = (ll >> 16u) + (lh & 0xFFFFu) + (hl & 0xFFFFu);
    return hh + (lh >> 16u) + (hl >> 16u) + (mid >> 16u);
}
fn gx_umul_hi(a: vec4<u32>, b: vec4<u32>) -> vec4<u32> {
    return vec4<u32>(gx_umul_hi1(a.x, b.x), gx_umul_hi1(a.y, b.y), gx_umul_hi1(a.z, b.z), gx_umul_hi1(a.w, b.w));
}`);
            }
            if (h.has("imul_hi")) {
                out.push(`fn gx_imul_hi(a: vec4<i32>, b: vec4<i32>) -> vec4<i32> {
    let ua = bitcast<vec4<u32>>(a); let ub = bitcast<vec4<u32>>(b);
    var hi = gx_umul_hi(ua, ub);
    hi = hi - select(vec4<u32>(0u), ub, a < vec4<i32>(0)) - select(vec4<u32>(0u), ua, b < vec4<i32>(0));
    return bitcast<vec4<i32>>(hi);
}`);
            }
            if (h.has("ubfe")) {
                out.push(`fn gx_ubfe1(w: u32, o: u32, v: u32) -> u32 {
    let width = w & 31u; let offset = o & 31u;
    if (width == 0u) { return 0u; }
    if (width + offset < 32u) { return (v << (32u - width - offset)) >> (32u - width); }
    return v >> offset;
}
fn gx_ubfe(w: vec4<u32>, o: vec4<u32>, v: vec4<u32>) -> vec4<u32> {
    return vec4<u32>(gx_ubfe1(w.x, o.x, v.x), gx_ubfe1(w.y, o.y, v.y), gx_ubfe1(w.z, o.z, v.z), gx_ubfe1(w.w, o.w, v.w));
}`);
            }
            if (h.has("ibfe")) {
                out.push(`fn gx_ibfe1(w: u32, o: u32, v: i32) -> i32 {
    let width = w & 31u; let offset = o & 31u;
    if (width == 0u) { return 0; }
    if (width + offset < 32u) { return (v << (32u - width - offset)) >> (32u - width); }
    return v >> offset;
}
fn gx_ibfe(w: vec4<u32>, o: vec4<u32>, v: vec4<i32>) -> vec4<i32> {
    return vec4<i32>(gx_ibfe1(w.x, o.x, v.x), gx_ibfe1(w.y, o.y, v.y), gx_ibfe1(w.z, o.z, v.z), gx_ibfe1(w.w, o.w, v.w));
}`);
            }
            if (h.has("bfi")) {
                out.push(`fn gx_bfi1(w: u32, o: u32, insert: u32, base: u32) -> u32 {
    let width = w & 31u; let offset = o & 31u;
    let mask = (((1u << width) - 1u) << offset);
    return ((insert << offset) & mask) | (base & ~mask);
}
fn gx_bfi(w: vec4<u32>, o: vec4<u32>, insert: vec4<u32>, base: vec4<u32>) -> vec4<u32> {
    return vec4<u32>(gx_bfi1(w.x, o.x, insert.x, base.x), gx_bfi1(w.y, o.y, insert.y, base.y),
        gx_bfi1(w.z, o.z, insert.z, base.z), gx_bfi1(w.w, o.w, insert.w, base.w));
}`);
            }
            if (h.has("f32tof16")) {
                out.push(`fn gx_f32tof16(v: vec4<f32>) -> vec4<u32> {
    return vec4<u32>(pack2x16float(vec2<f32>(v.x, 0.0)), pack2x16float(vec2<f32>(v.y, 0.0)),
        pack2x16float(vec2<f32>(v.z, 0.0)), pack2x16float(vec2<f32>(v.w, 0.0))) & vec4<u32>(0xFFFFu);
}`);
            }
            if (h.has("f16tof32")) {
                out.push(`fn gx_f16tof32(v: vec4<u32>) -> vec4<f32> {
    return vec4<f32>(unpack2x16float(v.x).x, unpack2x16float(v.y).x, unpack2x16float(v.z).x, unpack2x16float(v.w).x);
}`);
            }
            if (h.has("sample_pos")) {
                // where GX's samples are, in pixels from the center: one at
                // the center, four on the supersampled 2x2 grid (gx_ms_texel);
                // an index past the samples is at 0
                out.push(`fn gx_sample_pos(i: u32, count: u32) -> vec4<f32> {
    if (count == 4u && i < 4u) { return vec4<f32>(f32(i & 1u) * 0.5 - 0.25, f32(i >> 1u) * 0.5 - 0.25, 0.0, 0.0); }
    if (count == 8u && i < 8u) { return vec4<f32>((f32(i & 3u) + 0.5) * 0.25 - 0.5, f32(i >> 2u) * 0.5 - 0.25, 0.0, 0.0); }
    return vec4<f32>(0.0);
}`);
            }
            if (h.has("ms_texel")) {
                out.push(`fn gx_ms_texel(sample: u32) -> vec2<i32> {
    return vec2<i32>(i32(sample & 1u), i32((sample >> 1u) & 1u));
}
fn gx_ms_texel8(sample: u32) -> vec2<i32> {
    return vec2<i32>(i32(sample & 3u), i32((sample >> 2u) & 1u));
}`);
            }
            if (h.has("doubles")) {
                out.push(`fn gx_d2f(lo: u32, hi: u32) -> f32 {
    let e = (hi >> 20u) & 0x7FFu;
    let s = select(1.0, -1.0, (hi >> 31u) != 0u);
    if (e == 0u) { return 0.0 * s; }
    if (e == 0x7FFu) { return s * bitcast<f32>(0x7F800000u | select(0u, 0x400000u, ((hi & 0xFFFFFu) | lo) != 0u)); }
    let m = f32(hi & 0xFFFFFu) / 1048576.0 + f32(lo >> 11u) / 2199023255552.0;
    return s * ldexp(1.0 + m, i32(e) - 1023);
}
fn gx_f2d(f: f32) -> vec2<u32> {
    let b = bitcast<u32>(f);
    let s = b & 0x80000000u;
    let e = (b >> 23u) & 0xFFu;
    let m = b & 0x7FFFFFu;
    if (e == 0u) { return vec2<u32>(0u, s); }
    if (e == 0xFFu) { return vec2<u32>(0u, s | 0x7FF00000u | select(0u, 0x80000u, m != 0u)); }
    return vec2<u32>(m << 29u, s | ((e + 896u) << 20u) | (m >> 3u));
}
fn gx_d2f2(v: vec4<u32>) -> vec2<f32> { return vec2<f32>(gx_d2f(v.x, v.y), gx_d2f(v.z, v.w)); }
fn gx_f2d2(v: vec2<f32>) -> vec4<u32> { let a = gx_f2d(v.x); let b = gx_f2d(v.y); return vec4<u32>(a.x, a.y, b.x, b.y); }
fn gx_spread_f32(p: vec2<f32>, m: u32) -> vec4<f32> { var r = vec4<f32>(0.0); var k = 0u; for (var c = 0u; c < 4u; c++) { if (((m >> c) & 1u) != 0u) { r[c] = p[k & 1u]; k++; } } return r; }
fn gx_spread_i32(p: vec2<i32>, m: u32) -> vec4<i32> { var r = vec4<i32>(0); var k = 0u; for (var c = 0u; c < 4u; c++) { if (((m >> c) & 1u) != 0u) { r[c] = p[k & 1u]; k++; } } return r; }
fn gx_spread_u32(p: vec2<u32>, m: u32) -> vec4<u32> { var r = vec4<u32>(0u); var k = 0u; for (var c = 0u; c < 4u; c++) { if (((m >> c) & 1u) != 0u) { r[c] = p[k & 1u]; k++; } } return r; }`);
            }
            if (h.has("msad")) {
                // masked sum of absolute byte differences: bytes of the reference that are 0 do not count
                out.push(`fn gx_msad1(r: u32, s: u32, a: u32) -> u32 {
    var sum = a;
    for (var i = 0u; i < 32u; i += 8u) {
        let rb = (r >> i) & 0xFFu;
        let sb = (s >> i) & 0xFFu;
        if (rb != 0u) { sum += select(sb - rb, rb - sb, rb > sb); }
    }
    return sum;
}
fn gx_msad(r: vec4<u32>, s: vec4<u32>, a: vec4<u32>) -> vec4<u32> {
    return vec4<u32>(gx_msad1(r.x, s.x, a.x), gx_msad1(r.y, s.y, a.y), gx_msad1(r.z, s.z, a.z), gx_msad1(r.w, s.w, a.w));
}`);
            }
            if (h.has("cube_face")) {
                out.push(`fn gx_cube_face(d: vec3<f32>) -> vec3<f32> {
    let m = max(max(abs(d.x), abs(d.y)), abs(d.z));
    return d / max(m, 1e-30);
}`);
            }
            if (h.has("lod")) {
                // texels: the coordinates scaled by the texture's size
                out.push(`fn gx_lod(texels: vec3<f32>, levels: f32) -> vec4<f32> {
    let dx = dpdx(texels);
    let dy = dpdy(texels);
    let lod = 0.5 * log2(max(max(dot(dx, dx), dot(dy, dy)), 1e-30));
    return vec4<f32>(clamp(lod, 0.0, levels - 1.0), lod, 0.0, 0.0);
}`);
            }
            return out;
        }
    }

    // code inside a switch: every instruction but case/default/endswitch opens its case
    const originalInstruction = Emitter.prototype.instruction;
    Emitter.prototype.instruction = function(ins) {
        if (this.switches.length && ins.op !== OP.CASE && ins.op !== OP.DEFAULT && ins.op !== OP.ENDSWITCH) this.openCase();
        return originalInstruction.call(this, ins);
    };

    function inputRegister(input) {
        const o = input.operand;
        return o && o.indices.length ? o.indices[o.indices.length - 1].imm : input.index;
    }

    /** value with only the masked lanes of `bits` written over `old` */
    function maskInto(old, bits, mask) {
        if (!mask || mask === ALL) return bits;
        const lanes = [0, 1, 2, 3].map(c => mask >> c & 1 ? `(${bits}).${LANES[c]}` : `${old}.${LANES[c]}`);
        return `vec4<u32>(${lanes.join(", ")})`;
    }

    function fromBits(value, type) {
        return type === "u32" ? value : `bitcast<vec4<${type}>>(${value})`;
    }

    /** How a pixel shader input is interpolated, and its type */
    function varyingOf(input) {
        const m = input.interpolation;
        if (m === INTERPOLATION.CONSTANT) return { type: "u32", interpolation: "flat", sampling: "" };
        const linear = m === INTERPOLATION.LINEAR_NOPERSPECTIVE || m === INTERPOLATION.LINEAR_NOPERSPECTIVE_CENTROID ||
            m === INTERPOLATION.LINEAR_NOPERSPECTIVE_SAMPLE;
        const sampling = m === INTERPOLATION.LINEAR_CENTROID || m === INTERPOLATION.LINEAR_NOPERSPECTIVE_CENTROID ? "centroid" :
            m === INTERPOLATION.LINEAR_SAMPLE || m === INTERPOLATION.LINEAR_NOPERSPECTIVE_SAMPLE ? "sample" : "";
        return { type: "f32", interpolation: linear ? "linear" : "perspective", sampling };
    }

    function interpolationAttribute(vary, type) {
        if (type === "u32" || vary.interpolation === "flat") return "@interpolate(flat) ";
        if (vary.interpolation === "linear") return `@interpolate(linear${vary.sampling ? ", " + vary.sampling : ""}) `;
        if (vary.sampling) return `@interpolate(perspective, ${vary.sampling}) `;
        return "";
    }

    /** Without a pixel shader to link with: every output but the position, perspective */
    function defaultVaryings(program) {
        const varyings = {};
        for (const output of program.outputs) {
            if (output.type !== OPERAND.OUTPUT || output.name !== NAME.UNDEFINED) continue;
            varyings[output.index] = { type: "f32", interpolation: "perspective", sampling: "" };
        }
        return varyings;
    }

    /**
     * The varyings a pixel shader reads (for linking a vertex shader to it)
     * @return register -> { type, interpolation, sampling }
     */
    /**
     * A WGSL function reading element `i` of a typed buffer `buffer`
     * (array<u32>) of a format as WebGPU's vertex formats name the memory
     * ("unorm8x4", "float32x3", "unorm8x4-bgra"): its lanes as bits (floats
     * for the float and normalized formats)
     */
    function typedBufferReader(name, buffer, format) {
        const v = /^(unorm|snorm|uint|sint|float)(8|16|32)(?:x(\d))?(-bgra)?$/.exec(format) || [0, "uint", "32", "4", ""];
        const m = [0, v[4] ? "bgra" : "rgba".slice(0, +(v[3] || 1)), v[2], v[1]];
        const comps = m[1].length, bits = +m[2], kind = m[3];
        const integer = kind === "uint" || kind === "sint";
        const one = integer ? "1u" : "0x3F800000u";
        const lanes = [];
        if (bits === 32) {
            for (let c = 0; c < 4; c++) lanes.push(c < comps ? `${buffer}[i * ${comps}u + ${c}u]` : c === 3 ? one : "0u");
        } else {
            // a component's bits: from the word holding them
            const at = c => `(i * ${comps * bits / 8}u + ${c * bits / 8}u)`;
            const raw = c => `((${buffer}[${at(c)} >> 2u] >> ((${at(c)} & 3u) * 8u)) & ${bits === 8 ? "0xFFu" : "0xFFFFu"})`;
            const max = bits === 8 ? 255 : 65535, half = bits === 8 ? 127 : 32767, sign = bits === 8 ? 24 : 16;
            const decode = v => {
                switch (kind) {
                    case "uint": return v;
                    case "sint": return `u32((i32(${v} << ${sign}u)) >> ${sign}u)`;
                    case "unorm": return `bitcast<u32>(f32(${v}) / ${max}.0)`;
                    case "snorm": return `bitcast<u32>(max(f32((i32(${v} << ${sign}u)) >> ${sign}u) / ${half}.0, -1.0))`;
                    default: return `bitcast<u32>(unpack2x16float(${v}).x)`;
                }
            };
            for (let c = 0; c < 4; c++) lanes.push(c < comps ? decode(raw(c)) : c === 3 ? one : "0u");
            if (m[1] === "bgra") [lanes[0], lanes[2]] = [lanes[2], lanes[0]];
        }
        return `fn ${name}(i: u32) -> vec4<u32> { return vec4<u32>(${lanes.join(", ")}); }`;
    }

    function pixelVaryings(program) {
        const varyings = {};
        for (const input of program.inputs) {
            if (input.type !== OPERAND.INPUT) continue;
            if (input.name !== NAME.UNDEFINED && input.name !== NAME.CLIP_DISTANCE && input.name !== NAME.CULL_DISTANCE) {
                if (input.name !== NAME.PRIMITIVE_ID && input.name !== NAME.RENDER_TARGET_ARRAY_INDEX &&
                    input.name !== NAME.VIEWPORT_ARRAY_INDEX) continue;
            }
            if (input.name !== NAME.UNDEFINED) continue;
            varyings[inputRegister(input)] = varyingOf(input);
        }
        return varyings;
    }

    const api = { emit, pixelVaryings, ShaderTranslateError, BINDING };
    if (typeof module === "object" && module.exports) module.exports = api;
    else global.V86WGSLEmitter = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                        source/v64/src/browser/glbridge/svga_renderer.js                                                    0000644 0000000 0000000 00000034335 00000000000 017111  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The host half of the display adapters' 3D (graphics_adapter "vmware_svga"
// and "virtio_gpu"; docs/gpu-devices.md, "Architecture"). At levels vgpu9 and
// gb9 the SVGA device (src/graphics_adapters/vmware_svga/svga3d.js) turns the
// guest's SVGA3D commands into D9WG batches; this runs them through a D3D9
// executor of its own. GX batches (SVGA's DX levels, virgl) go to GX
// (gx/gx_executor.js) and VX batches (Venus) to VX (vx/vx_executor.js), both
// on the D3D9 executor's WebGPU device. It answers with what the batches
// wrote back and when each has run. It draws nothing on the page: pictures go
// back to the device as readbacks, and the device shows them on its screens
// like 2D ones.
//
// With options.scanoutLayer (a layer of the page's compositor, whose device
// it then shares, webgpu_compositor.js) GX's SURFACE_PRESENT copies a
// scanout's picture into that layer on the GPU: no readback
// (docs/gfxstream-plan.md G4).
//
// The ranchu machine's GLES host (docs/gles-proxy-plan.md) sends stream
// "gles": GLES batches for the GLES executor (V86GLESExecutor, E3), on the
// same device.
//
// Channel messages, device -> renderer:
//   submit { seq, bytes, stream }   a D9WG batch, or with stream "gx" a GX
//                           batch, "vx" a VX one (virtio-gpu's Vulkan),
//                           "gles" a GLES one
//   reset  {}               the machine was reset: forget every object
//   hello  {}               the device asks what the renderer can do
//   gles_save { id }        (the GLES host, before a snapshot) the GLES
//                           executor's state, with the GPU's contents
//   gles_restore { state }  (after a reset) a snapshot's GLES state back
// renderer -> device:
//   write  { offset, bytes } into the response region: a query result or a
//                            readback, tagged with its request id
//   done   { seq }           the batch has run and its writes were sent
//   lost   { reason }        the renderer cannot go on
//   caps   { present }       (to hello and reset) whether SURFACE_PRESENT shows pictures
//   frame  { width, height, bytes }  (stream "gles", without a layer) a posted
//                            color buffer, RGBA rows from the top
//   gles_saved { id, state } gles_save's answer (null: no GLES executor yet)
(function(global) {
    "use strict";

    // d3d9_protocol.h: the response region is the last 4 MiB of a 16 MiB arena
    const RESPONSE_REGION_OFFSET = 12 * 1024 * 1024;
    const HEARTBEAT_OFFSET = 4 * 1024 * 1024 - 16;

    /**
     * @param channel { post(message, transfer), listen(handler) }
     * @param options { canvas, executorOptions }
     */
    function createSVGARenderer(channel, options) {
        options = options || {};
        const Executor = global.D3D9WebGPUExecutor;
        if (typeof Executor !== "function")
            throw new Error("the SVGA renderer needs d3d9_executor.js (libv86-webgpu.js)");
        // The executor wants a canvas for its device; nothing is shown on it
        const canvas = options.canvas || new global.OffscreenCanvas(1, 1);
        const executor = new Executor(canvas, { ...(options.executorOptions || {}) });
        let generation = 0;
        let lost = false;
        // submits and resets in the order they came
        let queue = Promise.resolve();

        const writer = forGeneration => (offset, data) => {
            // (the heartbeat at the end of the region is for proxies spinning
            // on a readback; the device waits for done instead)
            if (forGeneration !== generation || offset >= RESPONSE_REGION_OFFSET + HEARTBEAT_OFFSET) return;
            const bytes = data instanceof Uint8Array ? data.slice() : new Uint8Array(data);
            channel.post({ type: "write", offset: offset - RESPONSE_REGION_OFFSET, bytes }, [bytes.buffer]);
        };

        const fail = reason => {
            if (lost) return;
            lost = true;
            console.error("[svga-renderer] " + reason);
            channel.post({ type: "lost", reason: String(reason) });
        };

        // GX (DX contexts, level dx10 and up), made on the D3D9 executor's device the first time
        let gx = null;
        const gxExecutor = async () => {
            if (gx) return gx;
            if (!executor.device) await executor.initialize();
            const GX = global.V86GXExecutor;
            if (!GX || !global.V86SVGADXFormats) throw new Error("the SVGA renderer needs gx_executor.js (libv86-webgpu.js)");
            // surfaces legacy 3D and DX share are copied between the two on the GPU
            const peer = {
                resource: handle => executor.resources ? executor.resources.get(handle) || null : null,
                flush: () => { if (executor.frame) executor.finishFrame(false); },
                // (a surface goes: VX's commands recorded with it, as images Venus imported, are submitted first)
                releasing: () => { if (vx) vx.flushEncoder(); },
            };
            if (layer) peer.present = present;
            gx = new GX.GXExecutor({ device: executor.device, formats: global.V86SVGADXFormats,
                features: executor.deviceFeatures || {}, peer });
            return gx;
        };

        // The page's screen: a layer of its compositor, the GX surface's
        // rectangle copied into it (the same format) and shown over the screen
        const layer = options.scanoutLayer || null;
        const present = p => {
            if (!p) {
                layer.place(0, 0, 0, 0, false);
                return;
            }
            const configuration = layer.context.getConfiguration();
            if (!configuration || configuration.format !== p.format) {
                layer.context.configure({ format: p.format });
                layer.texture = null;
            }
            layer.canvas.width = p.width;
            layer.canvas.height = p.height;
            p.encoder.copyTextureToTexture({ texture: p.texture, origin: [p.x, p.y, 0] },
                { texture: layer.context.getCurrentTexture(), origin: [p.dx, p.dy, 0] }, [p.w, p.h, 1]);
            layer.place(0, 0, p.width, p.height, true);
        };
        const caps = () => channel.post({ type: "caps", present: !!layer });

        // VX (virtio-gpu's Venus contexts), on the same device
        let vx = null;
        const vxExecutor = async () => {
            if (vx) return vx;
            if (!executor.device) await executor.initialize();
            const VX = global.V86VXExecutor;
            if (!VX) throw new Error("the renderer needs vx_executor.js (libv86-webgpu.js)");
            // (GX's surfaces: the images Venus imports from virtio-gpu resources)
            const peer = { surface: sid => gx && gx.surfaces ? gx.surfaces.get(sid) || null : null };
            vx = new VX.VXExecutor({ device: executor.device, formats: global.V86VenusFormats, peer });
            return vx;
        };

        // GLES (the ranchu machine's GLES host), on the same device; until
        // the page has its executor, a batch's reads fail (the guest reads
        // zeros) and nothing is drawn
        let gles = null;
        const glesExecutor = async () => {
            if (gles) return gles;
            const GLES = global.V86GLESExecutor;
            if (!GLES) return null;
            if (!executor.device) await executor.initialize();
            gles = new GLES.GLESExecutor({ device: executor.device, layer, features: executor.deviceFeatures || {} });
            return gles;
        };
        const glesUnanswered = bytes => {
            // (the records' READ_PIXELS and COLOR_BUFFER_READ: request ids at
            // dword 3 and dword 9 of their bodies; renderer_protocol.js GLES)
            const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
            for (let at = 4, i = 0; i < words[3] && at + 1 < words.length; i++) {
                const op = words[at], request = op === 17 ? words[at + 3] : op === 11 ? words[at + 9] : 0;
                if (request) {
                    const answer = new Uint8Array(16);
                    new DataView(answer.buffer).setUint32(0, request, true);
                    new DataView(answer.buffer).setUint32(12, 2, true); // RESPONSE_FAILED
                    channel.post({ type: "write", offset: 0, bytes: answer }, [answer.buffer]);
                }
                at += 2 + words[at + 1];
            }
        };

        channel.listen(message => {
            switch (message.type) {
                case "submit": {
                    const seq = message.seq, bytes = message.bytes, forGeneration = generation;
                    const stream = message.stream || "d9wg";
                    queue = queue.then(async () => {
                        if (forGeneration !== generation) return;
                        if (stream === "gles") {
                            try {
                                const target = lost ? null : await glesExecutor();
                                if (target) {
                                    await target.submit(bytes, { writeResponse: (offset, data) => {
                                        if (forGeneration !== generation) return;
                                        const copy = data.slice();
                                        channel.post({ type: "write", offset, bytes: copy }, [copy.buffer]);
                                    }, frame: (rgba, width, height) => {
                                        if (forGeneration !== generation) return;
                                        channel.post({ type: "frame", width, height, bytes: rgba }, [rgba.buffer]);
                                    } });
                                } else {
                                    glesUnanswered(bytes);
                                }
                            } catch (error) {
                                fail(error && error.stack || error);
                            }
                        } else if (!lost && stream === "vx") {
                            try {
                                const target = await vxExecutor();
                                await target.submit(bytes, { writeResponse: (offset, data) => {
                                    if (forGeneration !== generation) return;
                                    const copy = data.slice();
                                    channel.post({ type: "write", offset, bytes: copy }, [copy.buffer]);
                                } });
                            } catch (error) {
                                fail(error && error.stack || error);
                            }
                        } else if (!lost && stream === "gx") {
                            try {
                                const target = await gxExecutor();
                                await target.submit(bytes, { writeResponse: (offset, data) => {
                                    if (forGeneration !== generation) return;
                                    const copy = data.slice();
                                    channel.post({ type: "write", offset, bytes: copy }, [copy.buffer]);
                                } });
                            } catch (error) {
                                fail(error && error.stack || error);
                            }
                        } else if (!lost) {
                            await executor.submit(bytes, { writeGuestMemory: writer(forGeneration),
                                submitCount: seq });
                            if (executor.failed && !executor.device) fail(executor.failed);
                        }
                        if (forGeneration === generation) channel.post({ type: "done", seq });
                    });
                    break;
                }
                case "hello":
                    caps();
                    break;
                case "gles_save": {
                    // (after the batches sent before it)
                    const id = message.id;
                    queue = queue.then(async () => {
                        let state = null;
                        try {
                            if (gles && !lost) state = await gles.save();
                        } catch (error) {
                            console.warn("GLES: the page's state could not be saved: " + (error && error.message || error));
                        }
                        channel.post({ type: "gles_saved", id, state }, state ? state[1].map(b => b.buffer) : []);
                    });
                    break;
                }
                case "gles_restore": {
                    const state = message.state, forGeneration = generation;
                    queue = queue.then(async () => {
                        if (forGeneration !== generation || lost) return;
                        try {
                            const target = await glesExecutor();
                            if (target) target.restore(state);
                        } catch (error) {
                            fail(error && error.stack || error);
                        }
                    });
                    break;
                }
                case "reset":
                    ++generation;
                    if (layer) layer.place(0, 0, 0, 0, false);
                    caps();
                    queue = queue.then(() => {
                        // (VX first: its images may be GX's surfaces)
                        if (gles) gles.reset();
                        if (vx) vx.reset();
                        if (gx) gx.reset();
                        return executor.resetForReplay();
                    }).catch(error => fail(error));
                    break;
            }
        });

        return {
            executor,
            get gx() { return gx; },
            get vx() { return vx; },
            get gles() { return gles; },
            // the batches sent so far have run
            idle: () => queue.then(() => executor.checkpointIdle()),
            destroy() {
                ++generation;
                executor.destroyed = true;
                if (executor.shaderWorker) executor.shaderWorker.terminate();
            },
        };
    }

    global.V86SVGARenderer = createSVGARenderer;
    if (typeof module !== "undefined" && module.exports)
        module.exports = { createSVGARenderer };
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                   source/v64/src/browser/glbridge/v86_network_bridge.js                                               0000644 0000000 0000000 00000120045 00000000000 017765  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // v86 PCI DMA graphics router.
//
// OpenGL records are executed directly by gl-webgpu/gl_executor.js. D3D8 and
// D3D9 keep their tagged envelopes on the same v86gl.sys transport, but there
// is deliberately no GL4ES/WebGL decoder or fallback in this file.

(function(global) {
    "use strict";

    const GraphicsJournal = global.V86GraphicsJournal ||
        (typeof require === "function" ? require("./graphics_journal.js").GraphicsJournal : null);
    const V86GL_BRIDGE_VERSION = "gl-webgpu-only-v1-20260824";
    const CTRL_D3D8_BATCH = 0xFFE0;
    const CTRL_D3D9_BATCH = 0xFFE1;
    const EXTENDED_RECORD_SIZE = 0xFFFF;
    const CHECKPOINT_MAGIC = 0x32534756; // "VGS2"
    const CHECKPOINT_VERSION = 2;
    const JOURNAL_ENTRY_BYTES = 32;
    const CHECKPOINT_HEADER_BYTES = 32;
    const DEFAULT_JOURNAL_MEMORY_BYTES = 64 * 1024 * 1024;

    // Version 3 compresses/spools every accepted batch, including queries and Presents.
    // Readback writers are disabled during replay; object creation and query
    // begin/end still run, so guest handles and unfinished frames survive.

    function u16(bytes, offset) {
        return bytes[offset] | bytes[offset + 1] << 8;
    }

    function u32(bytes, offset) {
        return (bytes[offset] | bytes[offset + 1] << 8 |
            bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
    }

    function asBytes(value) {
        if (value instanceof Uint8Array) return value;
        if (ArrayBuffer.isView(value))
            return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
        if (value instanceof ArrayBuffer) return new Uint8Array(value);
        return new Uint8Array(value || []);
    }

    function ownedBytes(value) {
        return asBytes(value).slice();
    }

    class V86GLNetworkBridge {
        constructor(emulator, canvas, options) {
            this.emulator = emulator;
            this.options = options || {};
            // Each API draws into a window layer of the one screen canvas,
            // which the compositor (webgpu_compositor.js) shows over the guest
            // desktop where the guest has its window
            this.compositor = this.options.compositor;
            if (!this.compositor)
                throw new Error("the graphics bridge needs a compositor (webgpu_compositor.js)");
            const layer = name => this.compositor.createLayer(name).canvas;
            this.glCanvas = this.options.glCanvas || layer("gl");
            this.d3d8Canvas = this.options.d3d8Canvas || layer("d3d8");
            this.d3d9Canvas = this.options.d3d9Canvas || layer("d3d9");
            this.screenCanvas = this.options.screenCanvas || this.compositor.canvas || null;
            this.destroyed = false;
            this.memoryGeneration = 0;

            this.glExecutor = null;
            this.d3d8Executor = null;
            this.d3d9Executor = null;
            this.glSurface = this.emptySurface();
            this.d3d8Surface = this.emptySurface();
            this.d3d9Surface = this.emptySurface();
            this.activeOwner = null;
            this.d3d8OwnerSessionKey = null;
            this.d3d9OwnerSessionKey = null;
            this.d3d9SwapChainCanvases = new Map();
            this.d3d9SwapChainSurfaces = new Map();

            this.journalBudget = this.options.graphicsJournalMemoryBytes ??
                this.options.maxGraphicsJournalBytes ?? this.options.maxGLJournalBytes ?? DEFAULT_JOURNAL_MEMORY_BYTES;
            this.graphicsJournal = new GraphicsJournal({ budget: this.journalBudget });
            this.preparedCheckpoint = null;
            this.graphicsJournalBytes = 0;
            this.legacyCheckpoint = new Uint8Array(0);
            this.glJournal = [];
            this.glJournalBytes = 0;
            this.glJournalOverflow = false;
            this.replayingState = false;
            this.restoringState = false;
            this.restorePrepared = false;
            this.restoreSeen = false;
            this.restoreHadCheckpoint = false;
            this.pendingRestore = Promise.resolve();
            this.pendingBatches = [];

            // Batches arrive through graphics_proxy.js
            this.installGLExecutor();
            this.installD3D8Executor();
            this.installD3D9Executor();
        }

        /* The host an executor draws through when its canvas is a compositor layer */
        layerHost(canvas) {
            return canvas && canvas.layer ? canvas.layer.host : null;
        }

        emptySurface() {
            return { hwnd: 0, x: 0, y: 0, width: 0, height: 0,
                     displayWidth: 0, displayHeight: 0, visible: false };
        }

        installGLExecutor() {
            if (this.options.glExecutor) {
                this.glExecutor = this.options.glExecutor;
                return;
            }
            const install = this.options.installGLWebGPUExecutor ||
                global.installGLWebGPUExecutor;
            if (!this.glCanvas || typeof install !== "function") {
                console.error("[gl-webgpu] executor unavailable; load " +
                    "gl_executor.js and provide the shared graphics canvas");
                return;
            }
            const executorOptions = { ...(this.options.gl || {}) };
            if (!executorOptions.host && this.layerHost(this.glCanvas))
                executorOptions.host = this.layerHost(this.glCanvas);
            const userSurface = executorOptions.onSurface;
            executorOptions.onSurface = (surface, reason) => {
                this.glSurface = { ...this.glSurface, ...surface };
                if (reason === "hide" || surface.visible === false) {
                    if (this.activeOwner === "gl") this.hideLayers();
                } else if (reason === "window-state") {
                    // Where the window is and what of it shows: it does not
                    // make OpenGL the one on screen, SwapBuffers does
                    if (this.activeOwner === "gl") this.placeOwner("gl", true);
                } else {
                    this.showOwner("gl");
                }
                if (typeof userSurface === "function") userSurface(surface, reason);
            };
            executorOptions.writeGuestMemory = (offsetInBatch, data, metadata) => {
                if (this.destroyed || this.suspended || this.restoringState || this.replayingState) return;
                if (metadata && metadata.graphicsGeneration !== undefined &&
                    metadata.graphicsGeneration !== this.memoryGeneration) return;
                if (!metadata || metadata.batchAddress === undefined) return;
                if (typeof metadata.writeGuestMemory === "function")
                    return metadata.writeGuestMemory(32 + offsetInBatch, asBytes(data));
                if (!this.emulator ||
                        typeof this.emulator.write_memory !== "function") return;
                this.emulator.write_memory(asBytes(data),
                    (metadata.batchAddress + offsetInBatch) >>> 0);
            };
            this.glExecutor = install(this.glCanvas, executorOptions);
        }

        installD3D8Executor() {
            if (this.options.d3d8Executor) {
                this.d3d8Executor = this.options.d3d8Executor;
                return;
            }
            const install = this.options.installD3D8WebGPUExecutor ||
                global.installD3D8WebGPUExecutor;
            if (!this.d3d8Canvas || typeof install !== "function") return;
            const opts = { ...(this.options.d3d8 || {}) };
            if (!opts.host && this.layerHost(this.d3d8Canvas))
                opts.host = this.layerHost(this.d3d8Canvas);
            const userSurface = opts.onSurface;
            const userPresent = opts.onPresent;
            const userDestroy = opts.onDestroy;
            opts.onSurface = (surface, reason) => {
                const session = surface.sessionKey || null;
                if (reason === "hide" || surface.visible === false) {
                    if (!session || session === this.d3d8OwnerSessionKey) {
                        this.d3d8Surface = { ...this.d3d8Surface, ...surface };
                        if (this.activeOwner === "d3d8") this.hideLayers();
                    }
                } else {
                    this.d3d8OwnerSessionKey = session;
                    this.d3d8Surface = { ...this.d3d8Surface, ...surface };
                    this.placeOwner("d3d8", false);
                }
                if (typeof userSurface === "function") userSurface(surface, reason);
            };
            opts.onPresent = (surface, stats) => {
                this.d3d8OwnerSessionKey = surface.sessionKey || null;
                this.d3d8Surface = { ...this.d3d8Surface, ...surface };
                if (surface.visible === false) this.hideLayers();
                else this.showOwner("d3d8");
                if (typeof userPresent === "function") userPresent(surface, stats);
            };
            opts.onDestroy = (surface, reason) => {
                const session = surface.sessionKey || null;
                if (!session || session === this.d3d8OwnerSessionKey) {
                    this.d3d8OwnerSessionKey = null;
                    this.d3d8Surface = { ...this.d3d8Surface, ...surface,
                        visible: false };
                    if (this.activeOwner === "d3d8") this.hideLayers();
                }
                if (typeof userDestroy === "function") userDestroy(surface, reason);
            };
            this.d3d8Executor = install(this.d3d8Canvas, opts);
        }

        installD3D9Executor() {
            if (this.options.d3d9Executor) {
                this.d3d9Executor = this.options.d3d9Executor;
                return;
            }
            const install = this.options.installD3D9WebGPUExecutor ||
                global.installD3D9WebGPUExecutor;
            if (!this.d3d9Canvas || typeof install !== "function") return;
            const opts = { ...(this.options.d3d9 || {}) };
            if (!opts.host && this.layerHost(this.d3d9Canvas))
                opts.host = this.layerHost(this.d3d9Canvas);
            const userSurface = opts.onSurface;
            const userPresent = opts.onPresent;
            const userDestroy = opts.onDestroy;
            opts.onSurface = (surface, reason) => {
                const session = surface.sessionKey || null;
                if (reason === "hide" || surface.visible === false) {
                    if (!session || session === this.d3d9OwnerSessionKey) {
                        this.d3d9Surface = { ...this.d3d9Surface, ...surface };
                        if (this.activeOwner === "d3d9")
                            this.hideLayers();
                        else
                            this.placeLayer(this.d3d9Canvas,
                                0, 0, 0, 0, false);
                    }
                } else {
                    /* A CREATE/RESET only declares where a process would
                     * present; it does not make that process the visible
                     * owner. Capability helpers interleave their batches with
                     * games and dxdiag, so stealing ownership here made the
                     * live canvas disappear until the helper's (often absent)
                     * Present. Ownership changes only after a successful
                     * onPresent below. */
                    const hasOwner = this.d3d9OwnerSessionKey !== null;
                    const belongsToOwner = hasOwner &&
                        session === this.d3d9OwnerSessionKey;
                    const legacyOwner = !hasOwner && !session &&
                        this.activeOwner === "d3d9";
                    if (!hasOwner || belongsToOwner) {
                        this.d3d9Surface = { ...this.d3d9Surface, ...surface };
                        // Only a successful Present may put the shared canvas
                        // on screen.  In particular, DirectDraw sends a
                        // display-mode report while tearing down 3DMark 2000;
                        // treating that geometry report as visibility showed
                        // the retained (black) canvas after the primary had
                        // already told us to hide it.
                        this.placeOwner("d3d9",
                            this.activeOwner === "d3d9" &&
                            (belongsToOwner || legacyOwner));
                    }
                }
                if (typeof userSurface === "function") userSurface(surface, reason);
            };
            opts.onPresent = (surface, stats) => {
                this.d3d9OwnerSessionKey = surface.sessionKey || null;
                this.d3d9Surface = { ...this.d3d9Surface, ...surface };
                if (surface.visible === false) this.hideLayers();
                else this.showOwner("d3d9");
                if (typeof userPresent === "function") userPresent(surface, stats);
            };
            opts.onDestroy = (surface, reason) => {
                const session = surface.sessionKey || null;
                // The session check stops a helper process -- dxdiag, a
                // capability probe -- from tearing down a running game's
                // canvas, and that has to keep working.
                //
                // What it cannot answer is the orphaned case: the canvas is
                // still showing frames while no session claims it any more,
                // which is where an earlier destroy in the same session has
                // already cleared the owner. Nothing can take it down after
                // that, so an exiting process leaves a picture of itself over
                // the guest's desktop with nothing left running to remove it.
                // A session ending is a safe moment to reclaim that: there is
                // no owner left to protect.
                const orphaned = this.d3d9OwnerSessionKey === null &&
                    this.activeOwner === "d3d9";
                if (!session || session === this.d3d9OwnerSessionKey ||
                        (reason === "session-end" && orphaned)) {
                    this.d3d9OwnerSessionKey = null;
                    this.d3d9Surface = { ...this.d3d9Surface, ...surface,
                        visible: false };
                    if (this.activeOwner === "d3d9")
                        this.hideLayers();
                    else
                        this.placeLayer(this.d3d9Canvas,
                            0, 0, 0, 0, false);
                }
                if (typeof userDestroy === "function") userDestroy(surface, reason);
            };
            const userCreateSwapChainCanvas = opts.createSwapChainCanvas;
            opts.createSwapChainCanvas = surface => {
                if (this.destroyed || this.suspended) return null;
                if (typeof userCreateSwapChainCanvas === "function")
                    return userCreateSwapChainCanvas(surface);
                const layer = this.compositor.createLayer("d3d9 swap chain " + surface.swapChain);
                layer.canvas.width = Math.max(1, surface.width || 1);
                layer.canvas.height = Math.max(1, surface.height || 1);
                this.d3d9SwapChainCanvases.set(surface.swapChain, layer.canvas);
                return layer.canvas;
            };
            const userSwapChainSurface = opts.onSwapChainSurface;
            opts.onSwapChainSurface = (surface, reason) => {
                if (reason === "destroy") this.removeD3D9SwapChain(surface.swapChain);
                else this.placeD3D9SwapChain(surface);
                if (typeof userSwapChainSurface === "function")
                    userSwapChainSurface(surface, reason);
            };
            this.d3d9Executor = install(this.d3d9Canvas, opts);
        }

        pushPCIBatch(event) {
            if (this.destroyed || this.failed) return;
            event.handled = true;
            const bytes = asBytes(event && event.bytes);
            if (this.restoringState) {
                this.pendingBatches.push({ ...event, bytes: bytes.slice() });
                return;
            }
            if (!this.replayingState) this.recordGraphicsBatch(event, bytes);
            return this.executePCIBatch(event, bytes);
        }

        executePCIBatch(event, bytes) {
            if (this.isEnvelope(bytes, CTRL_D3D8_BATCH))
                return this.pushD3D8PCIBatch(event, bytes);
            if (this.isEnvelope(bytes, CTRL_D3D9_BATCH))
                return this.pushD3D9PCIBatch(event, bytes);
            this.pushGLPCIBatch(event, bytes);
        }

        isEnvelope(bytes, opcode) {
            return bytes.byteLength >= 8 && u16(bytes, 0) === opcode &&
                u16(bytes, 2) === EXTENDED_RECORD_SIZE;
        }

        pushGLPCIBatch(event, bytes) {
            if (!this.glExecutor || typeof this.glExecutor.submit !== "function") {
                console.error("[gl-webgpu] executor unavailable");
                return;
            }
            this.glExecutor.submit(bytes, {
                ...(event.replay ? { replay: true } : {}),
                pciFrameId: event.frameId >>> 0,
                submitCount: event.submitCount >>> 0,
                descriptorCommandCount: event.commandCount >>> 0,
                batchAddress: event.batchAddr === undefined ? undefined :
                    event.batchAddr >>> 0,
                responseBase: event.responseBase,
                writeGuestMemory: event.writeGuestMemory,
                isMemoryValid: event.isMemoryValid,
                graphicsGeneration: this.memoryGeneration,
            });
            if (event.flags & 1) {
                this.glExecutor.onSwapBuffers();
                this.showOwner("gl");
            }
        }

        pushD3D8PCIBatch(event, bytes) {
            if (!this.d3d8Executor ||
                    typeof this.d3d8Executor.submit !== "function") {
                console.error("[d3d8-webgpu] executor unavailable");
                return;
            }
            const payloadBytes = u32(bytes, 4);
            if (payloadBytes !== bytes.byteLength - 8) {
                console.error("[d3d8-webgpu] malformed D8WG envelope");
                return;
            }
            return this.d3d8Executor.submit(bytes.subarray(8), {
                ...(event.replay ? { replay: true } : {}),
                pciFrameId: event.frameId >>> 0,
                submitCount: event.submitCount >>> 0,
                descriptorCommandCount: event.commandCount >>> 0,
            });
        }

        pushD3D9PCIBatch(event, bytes) {
            if (!this.d3d9Executor ||
                    typeof this.d3d9Executor.submit !== "function") {
                console.error("[d3d9-webgpu] executor unavailable");
                return;
            }
            const payloadBytes = u32(bytes, 4);
            if (payloadBytes !== bytes.byteLength - 8) {
                console.error("[d3d9-webgpu] malformed D9WG envelope");
                return;
            }
            const descriptorBase = event.descAddr >>> 0;
            const generation = this.memoryGeneration;
            const writeGuestMemory = (dmaOffset, data) => {
                if (this.destroyed || this.suspended || this.restoringState ||
                    generation !== this.memoryGeneration) return;
                const source = asBytes(data);
                if (typeof event.writeGuestMemory === "function")
                    return event.writeGuestMemory(dmaOffset, source);
                const offset = dmaOffset >>> 0;
                const end = offset + source.byteLength;
                if (end < offset || end > 16 * 1024 * 1024)
                    throw new RangeError("D9WG response write is outside DMA memory");
                if (!this.emulator ||
                        typeof this.emulator.write_memory !== "function")
                    throw new Error("v86 physical-memory writer is unavailable");
                this.emulator.write_memory(source,
                    (descriptorBase + offset) >>> 0);
            };
            return this.d3d9Executor.submit(bytes.subarray(8), {
                ...(event.replay ? { replay: true } : {}),
                pciFrameId: event.frameId >>> 0,
                submitCount: event.submitCount >>> 0,
                descriptorCommandCount: event.commandCount >>> 0,
                descriptorBase,
                writeGuestMemory,
            });
        }

        recordGraphicsBatch(event, bytes) {
            this.preparedCheckpoint = null;
            this.graphicsJournal.append(event, bytes);
            this.graphicsJournalBytes += JOURNAL_ENTRY_BYTES + bytes.byteLength;
            if (!event.barrier && !this.isEnvelope(bytes, CTRL_D3D8_BATCH) &&
                    !this.isEnvelope(bytes, CTRL_D3D9_BATCH))
                this.glJournalBytes += bytes.byteLength;
        }

        async resetJournal() {
            await this.graphicsJournal.destroy();
            this.graphicsJournal = new GraphicsJournal({ budget: this.journalBudget });
            this.graphicsJournalBytes = 0;
            this.preparedCheckpoint = null;
        }

        serializeCheckpoint() {
            if (this.restoringState || this.replayingState)
                throw new Error("graphics state is being restored");
            if (!this.preparedCheckpoint)
                throw new Error("Graphics checkpoint is not prepared; await emulator.save_state()");
            return this.preparedCheckpoint;
        }

        releaseCheckpoint() { this.preparedCheckpoint = null; }

        parseCheckpoint(checkpoint) {
            const bytes = asBytes(checkpoint);
            if (bytes.byteLength < CHECKPOINT_HEADER_BYTES)
                throw new Error("graphics checkpoint is truncated");
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            const version = view.getUint16(4, true);
            if (version === 3) {
                const parsed = GraphicsJournal.parse(bytes);
                if (parsed.legacy.length && (parsed.legacy.length < CHECKPOINT_HEADER_BYTES ||
                        new DataView(parsed.legacy.buffer).getUint16(4, true) !== 1))
                    throw new Error("graphics checkpoint legacy data must be version 1");
                if (parsed.legacy.length) this.parseCheckpoint(parsed.legacy);
                return parsed;
            }
            if (view.getUint32(0, true) !== CHECKPOINT_MAGIC ||
                    (version !== 1 && version !== CHECKPOINT_VERSION))
                throw new Error("graphics checkpoint version is unsupported");
            const header = view.getUint16(6, true);
            const total = view.getUint32(8, true);
            if (header !== CHECKPOINT_HEADER_BYTES || total !== bytes.byteLength)
                throw new Error("graphics checkpoint lengths are invalid");
            if (version === 1) {
                const glBytes = view.getUint32(12, true);
                const d3d8Bytes = view.getUint32(16, true);
                if (header + glBytes + d3d8Bytes !== total)
                    throw new Error("graphics checkpoint lengths are invalid");
                return { version, gl: bytes.slice(header, header + glBytes),
                    d3d8: bytes.slice(header + glBytes), records: [] };
            }
            const legacyBytes = view.getUint32(12, true);
            if (legacyBytes > total - header)
                throw new Error("graphics checkpoint legacy data is truncated");
            const legacy = bytes.slice(header, header + legacyBytes);
            if (legacyBytes && (legacyBytes < CHECKPOINT_HEADER_BYTES ||
                    new DataView(legacy.buffer).getUint16(4, true) !== 1))
                throw new Error("graphics checkpoint legacy data must be version 1");
            if (legacyBytes) this.parseCheckpoint(legacy);
            const count = view.getUint32(16, true);
            const records = [];
            let offset = header + legacyBytes;
            for (let i = 0; i < count; ++i) {
                if (offset + JOURNAL_ENTRY_BYTES > total)
                    throw new Error("graphics checkpoint batch header is truncated");
                const size = view.getUint32(offset, true);
                const kind = view.getUint32(offset + 24, true);
                if (size > total - offset - JOURNAL_ENTRY_BYTES || kind > 1 ||
                        (kind === 1 && size) || view.getUint32(offset + 28, true))
                    throw new Error("graphics checkpoint batch is invalid");
                records.push({ flags: view.getUint32(offset + 4, true),
                    frameId: view.getUint32(offset + 8, true),
                    submitCount: view.getUint32(offset + 12, true),
                    commandCount: view.getUint32(offset + 16, true),
                    responseBase: view.getUint32(offset + 20, true), barrier: kind === 1,
                    bytes: bytes.slice(offset + JOURNAL_ENTRY_BYTES,
                        offset + JOURNAL_ENTRY_BYTES + size) });
                offset += JOURNAL_ENTRY_BYTES + size;
            }
            if (offset !== total) throw new Error("graphics checkpoint has trailing data");
            return { version, legacy, records };
        }

        async waitForIdle(flush, allowFailure = false) {
            const executors = [this.glExecutor, this.d3d8Executor, this.d3d9Executor].filter(Boolean);
            for (const executor of executors) {
                try {
                    if (executor.readyPromise) await executor.readyPromise;
                    if (executor.idle) await executor.idle();
                    else if (executor.work) await executor.work;
                } catch (error) {
                    if (!allowFailure) throw error;
                }
            }
            if (flush) {
                if (this.glExecutor && this.glExecutor.flushFrame) this.glExecutor.flushFrame();
                if (this.d3d8Executor && this.d3d8Executor.finishFrame) this.d3d8Executor.finishFrame(false);
                if (this.d3d9Executor && this.d3d9Executor.flushForCheckpoint)
                    this.d3d9Executor.flushForCheckpoint();
            }
            for (const executor of executors) {
                try {
                    if (executor.checkpointIdle) await executor.checkpointIdle();
                    else if (executor.idle) await executor.idle();
                    const queue = executor.device && executor.device.queue;
                    if (queue && queue.onSubmittedWorkDone) await queue.onSubmittedWorkDone();
                    if (executor.failed) throw executor.failed;
                } catch (error) {
                    // Loading a good checkpoint must recover an executor that
                    // failed while processing the timeline being discarded.
                    if (!allowFailure) throw error;
                }
            }
        }

        async waitForSubmittedBatches() {
            // Drain JS continuations/readbacks without inserting a GPU fence for
            // every transport batch. Checkpoint barriers still fence the GPU.
            for (const executor of [this.glExecutor, this.d3d8Executor, this.d3d9Executor]) {
                if (!executor) continue;
                if (executor.checkpointIdle) await executor.checkpointIdle();
                else if (executor.idle) await executor.idle();
                else if (executor.work) await executor.work;
                if (executor.failed) throw executor.failed;
            }
        }

        // The checkpoint travels in the snapshot as the device's host state
        // (graphics_proxy.js prepare_save/after_restore)
        async prepareSaveState() {
            await this.waitForIdle(true);
            // Flushes can split an unfinished frame/query. Replay that boundary
            // too, including when this checkpoint later becomes a parent save.
            this.recordGraphicsBatch({ barrier: true }, new Uint8Array(0));
            this.preparedCheckpoint = await this.graphicsJournal.snapshot(this.legacyCheckpoint);
            return { entries: this.graphicsJournal.count, bytes: this.preparedCheckpoint.byteLength };
        }

        beginStateRestore() {
            this.restorePrepared = true;
            this.restoreSeen = false;
            this.restoreHadCheckpoint = false;
            this.restoringState = true;
            this.pendingRestore = Promise.resolve();
            this.placeLayers();
        }

        onPCIStateRestored(checkpoint) {
            ++this.memoryGeneration;
            this.restoreSeen = true;
            this.restoreHadCheckpoint = !!(checkpoint && checkpoint.byteLength);
            this.restoringState = true;
            this.pendingRestore = Promise.resolve().then(() =>
                this.restoreCheckpoint(checkpoint));
            this.pendingRestore.catch(error =>
                console.error("[v86gl] graphics state restore failed", error));
        }

        async restoreCheckpoint(checkpoint) {
            // Validate before discarding live resources. Version 1 can restore
            // only the GL/D3D8 data that old writers actually saved.
            const parsed = checkpoint && checkpoint.byteLength ? this.parseCheckpoint(checkpoint) :
                { version: 2, legacy: new Uint8Array(0), records: [] };
            await this.waitForIdle(false, true);
            this.replayingState = true;
            this.placeLayers();
            let complete = false;
            try {
                if (this.resetForStateRestore) await this.resetForStateRestore();
                else {
                    if (this.glExecutor) this.glExecutor.resetForReplay();
                    if (this.d3d8Executor && this.d3d8Executor.restoreState)
                        await this.d3d8Executor.restoreState(new Uint8Array(0));
                    if (this.d3d9Executor && this.d3d9Executor.resetForReplay)
                        await this.d3d9Executor.resetForReplay();
                }
                await this.resetJournal();
                this.glJournal = [];
                this.glJournalBytes = 0;
                this.glJournalOverflow = false;
                this.legacyCheckpoint = parsed.version === 1 ? ownedBytes(checkpoint) : parsed.legacy;
                const legacy = parsed.version === 1 ? parsed :
                    (parsed.legacy.byteLength ? this.parseCheckpoint(parsed.legacy) : null);
                if (legacy) {
                    if (legacy.gl.byteLength) {
                        this.glExecutor.submit(legacy.gl.slice(), { replay: true });
                        this.glExecutor.onSwapBuffers();
                        this.glJournalBytes = legacy.gl.byteLength;
                    }
                    if (this.d3d8Executor && this.d3d8Executor.restoreState)
                        await this.d3d8Executor.restoreState(legacy.d3d8);
                }
                const records = parsed.version === 3 ? GraphicsJournal.records(parsed) : parsed.records;
                for await (const record of records) {
                    if (record.barrier) await this.waitForIdle(true);
                    else {
                        // Each replay owns its response buffer. Never let query
                        // responses mutate the journal or restored guest RAM.
                        const event = { ...record, replay: true, batchAddr: 0, descAddr: 0,
                            writeGuestMemory() {}, isMemoryValid: () => true };
                        await this.executePCIBatch(event, record.bytes.slice());
                    }
                    this.recordGraphicsBatch(record, record.bytes);
                    // Do not accumulate an entire decompressed history during
                    // restore. Compression and disk writes keep pace with replay.
                    await this.graphicsJournal.work;
                }
                await this.waitForIdle(false);
                complete = true;
            } finally {
                this.replayingState = false;
                this.restoringState = false;
                if (complete) {
                    this.placeLayers();
                    this.drainPendingBatches();
                } else {
                    this.hideLayers(true);
                    this.pendingBatches = [];
                }
            }
        }

        async finishStateRestore() {
            if (!this.restoreSeen) this.onPCIStateRestored(null);
            await this.pendingRestore;
            this.restorePrepared = false;
            return { hasGLState: this.restoreHadCheckpoint };
        }

        cancelStateRestore() {
            this.restorePrepared = false;
            this.restoreSeen = false;
            this.restoreHadCheckpoint = false;
            this.replayingState = false;
            this.restoringState = false;
            this.pendingRestore = Promise.resolve();
            this.drainPendingBatches();
        }

        drainPendingBatches() {
            const pending = this.pendingBatches.splice(0);
            for (const event of pending) this.pushPCIBatch(event);
        }

        ownerCanvas(owner) {
            if (owner === "d3d8") return this.d3d8Canvas;
            if (owner === "d3d9") return this.d3d9Canvas;
            return this.glCanvas;
        }

        ownerSurface(owner) {
            if (owner === "d3d8") return this.d3d8Surface;
            if (owner === "d3d9") return this.d3d9Surface;
            return this.glSurface;
        }

        /* Put a window layer where the guest has its window, in guest desktop
         * pixels, which are the screen canvas's pixels. Nothing shows while
         * state is being restored or the guest shows text. */
        placeLayer(canvas, left, top, width, height, visible) {
            if (!canvas || !canvas.layer) return;
            if (this.destroyed || this.suspended || this.restoringState || this.replayingState ||
                    this.options.isGraphical && !this.options.isGraphical())
                visible = false;
            canvas.layer.place(left, top, width, height, visible);
            canvas.layer.setClip(null);
            canvas.layer.setVisibleRegion(null);
        }

        ownerRect(owner) {
            const canvas = this.ownerCanvas(owner);
            const surface = this.ownerSurface(owner);
            // DDSCL_NORMAL exposes the desktop primary. Its Present HWND is
            // merely the application asking for scanout; using that HWND's
            // client rectangle to place the layer shrinks the entire desktop
            // texture into a splash window and makes its logo fill the window.
            // Keep the layer coincident with the v86 desktop and let clipRect
            // reveal only the primary pixels this application actually wrote.
            const desktopPrimary = !!surface.ddDesktopPrimary;
            return {
                left: desktopPrimary ? 0 : (surface.x || 0),
                top: desktopPrimary ? 0 : (surface.y || 0),
                width: surface.displayWidth || surface.width || canvas.width || 1,
                height: surface.displayHeight || surface.height || canvas.height || 1,
            };
        }

        /* The parts of the layer other guest windows leave showing
         * (surface.visibleRegion, from the guest's window-state reports), as
         * fractions of the layer placed at `rect`; null for all of it */
        layerRegion(surface, rect) {
            const region = surface && surface.visibleRegion;
            if (!region || !region.baseWidth || !region.baseHeight || !rect.width || !rect.height)
                return null;
            // The layer is the window's client area, perhaps scaled -- or, for
            // a DirectDraw desktop primary, the whole desktop
            const x = surface.ddDesktopPrimary ?
                v => (region.originX + v - rect.left) / rect.width : v => v / region.baseWidth;
            const y = surface.ddDesktopPrimary ?
                v => (region.originY + v - rect.top) / rect.height : v => v / region.baseHeight;
            return region.rects.map(r => ({ left: x(r.left), top: y(r.top), right: x(r.right), bottom: y(r.bottom) }));
        }

        placeOwner(owner, visible, targetCanvas) {
            const canvas = targetCanvas || this.ownerCanvas(owner);
            if (!canvas) return;
            const surface = this.ownerSurface(owner);
            const rect = this.ownerRect(owner);
            // Covered by other guest windows: shown again when the guest says
            // it is uncovered, whatever is presented meanwhile
            this.placeLayer(canvas, rect.left, rect.top, rect.width, rect.height,
                (visible === undefined ? this.activeOwner === owner : visible) &&
                !(surface && surface.occluded));
            let clip = surface && surface.clipRect;
            // Clip windowed rendering to the guest desktop, preserving any
            // DirectDraw primary clip region as well.
            if (this.screenCanvas && this.screenCanvas.width && this.screenCanvas.height) {
                const w = rect.width, h = rect.height, x = rect.left, y = rect.top;
                const source = clip && clip.baseWidth > 0 && clip.baseHeight > 0 ? clip :
                    { left: 0, top: 0, right: w, bottom: h, baseWidth: w, baseHeight: h };
                clip = {
                    baseWidth: w, baseHeight: h,
                    left: Math.min(w, Math.max(0, -x, source.left / source.baseWidth * w)),
                    top: Math.min(h, Math.max(0, -y, source.top / source.baseHeight * h)),
                    right: Math.max(0, Math.min(w, this.screenCanvas.width - x, source.right / source.baseWidth * w)),
                    bottom: Math.max(0, Math.min(h, this.screenCanvas.height - y, source.bottom / source.baseHeight * h)),
                };
            }
            if (clip && clip.baseWidth > 0 && clip.baseHeight > 0) {
                canvas.layer.setClip({
                    left: Math.max(0, clip.left) / clip.baseWidth,
                    top: Math.max(0, clip.top) / clip.baseHeight,
                    right: Math.min(clip.baseWidth, clip.right) / clip.baseWidth,
                    bottom: Math.min(clip.baseHeight, clip.bottom) / clip.baseHeight,
                });
            }
            canvas.layer.setVisibleRegion(this.layerRegion(surface, rect));
        }

        showOwner(owner) {
            if (this.destroyed || this.suspended) return;
            this.activeOwner = owner;
            const active = this.ownerCanvas(owner);
            for (const canvas of [this.glCanvas, this.d3d8Canvas, this.d3d9Canvas]) {
                if (canvas && canvas !== active)
                    this.placeLayer(canvas, 0, 0, 0, 0, false);
            }
            this.placeOwner(owner, true);
        }

        placeLayers() {
            if (this.activeOwner) this.placeOwner(this.activeOwner, true);
            for (const surface of this.d3d9SwapChainSurfaces.values())
                this.placeD3D9SwapChain(surface);
        }

        hideLayers(includeSwapChains) {
            for (const canvas of [this.glCanvas, this.d3d8Canvas, this.d3d9Canvas])
                if (canvas) this.placeLayer(canvas, 0, 0, 0, 0, false);
            this.activeOwner = null;
            if (includeSwapChains) {
                for (const canvas of this.d3d9SwapChainCanvases.values())
                    this.placeLayer(canvas, 0, 0, 0, 0, false);
            }
        }

        placeD3D9SwapChain(surface) {
            this.d3d9SwapChainSurfaces.set(surface.swapChain, surface);
            const canvas = this.d3d9SwapChainCanvases.get(surface.swapChain);
            if (!canvas) return;
            // Placed by its own surface alone: the primary window's size,
            // clip and desktop-primary flag are not this window's
            const saved = this.d3d9Surface;
            this.d3d9Surface = { ...this.emptySurface(), ...surface };
            this.placeOwner("d3d9", surface.visible !== false, canvas);
            this.d3d9Surface = saved;
        }

        removeD3D9SwapChain(handle) {
            const canvas = this.d3d9SwapChainCanvases.get(handle);
            if (!canvas) return;
            this.d3d9SwapChainCanvases.delete(handle);
            this.d3d9SwapChainSurfaces.delete(handle);
            canvas.layer.destroy();
        }
    }
    global.V86GL_BRIDGE_VERSION = V86GL_BRIDGE_VERSION;
    global.installV86GLNetworkBridge = function(emulator, canvas, options) {
        return new V86GLNetworkBridge(emulator, canvas, options);
    };
})(typeof window !== "undefined" ? window : globalThis);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/browser/glbridge/v86gl_device.js                                                     0000644 0000000 0000000 00000026442 00000000000 016550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The v86gl virtio device: the CPU side of the graphics proxy, a descriptor
// for v86's virtio_devices. It runs where the CPU runs (the page, or the CPU
// worker), knows nothing of WebGPU, and talks to the renderer
// (graphics_proxy.js) over a channel. See docs/graphics-proxy-plugin-plan.md.
//
// The PCI identity, slot, ports, configuration space and request layout are
// v86gl.sys's ABI. The VGL2/GLWG/D9WG rendering protocols ride in the batches
// unchanged. See docs/glbridge.md.
//
// Channel messages, device -> host:
//   batch      { id, generation, frameId, flags, commandCount, descAddr,
//                descLen, batchAddr, responseBase, submitCount, bytes }
// host -> device:
//   write      { generation, offset, bytes }  readback into the arena
//   done       { id }                         the batch no longer needs its capacity
//   available  { value }                      whether a renderer takes batches

(function(global) {
    "use strict";

    const MAGIC = 0x324C4756;
    // v86gl_pci.js's snapshots (state[92] before virtio_devices)
    const LEGACY_STATE_MAGIC = 0x56514731;
    const STATE_VERSION = 2;
    const ARENA_BYTES = 16 * 1024 * 1024;
    const RESPONSE_AREA_BYTES = 4 * 1024 * 1024;
    const HEADER_BYTES = 32;
    const REQUEST_BYTES = 24;
    const RESPONSE_BYTES = 16;
    const F_SHARED_ARENA = 0;
    const F_VERSION_1 = 32;
    const REGISTER_ARENA = 1;
    const SUBMIT = 2;
    const UNREGISTER_ARENA = 3;
    const OK = 0;
    const INVALID = 1;
    const NO_ARENA = 2;
    const NO_RENDERER = 3;

    // Flow control across threads only: on one thread the renderer takes each
    // batch as it comes, as it always has
    const MAX_INFLIGHT_BATCHES = 8;
    const MAX_INFLIGHT_BYTES = 32 * 1024 * 1024;

    /**
     * @param channel { remote, post(message, transfer), listen(handler) }
     * @return a virtio_devices descriptor
     */
    function createV86GLDevice(channel) {
        const remote = !!channel.remote;
        let dev = null;
        let arenaAddress = 0;
        let arenaBytes = 0;
        let arenaGeneration = 0;
        let lastFrameId = 0;
        let lastBytes = 0;
        let submitCount = 0;
        let hostAvailable = false;
        let nextBatch = 0;
        const inflight = new Map();
        let inflightBytes = 0;
        let processing = false;
        let processAgain = false;

        function releaseArena() {
            ++arenaGeneration;
            arenaAddress = 0;
            arenaBytes = 0;
        }

        function forgetInflight() {
            inflight.clear();
            inflightBytes = 0;
        }

        function canAccept() {
            return !remote || inflight.size < MAX_INFLIGHT_BATCHES &&
                inflightBytes <= MAX_INFLIGHT_BYTES - ARENA_BYTES;
        }

        channel.listen(message => {
            switch (message.type) {
                case "write": {
                    // A readback lands in the arena of the batch that asked for it
                    const offset = message.offset;
                    const bytes = message.bytes;
                    if (message.generation !== arenaGeneration || !arenaBytes) return;
                    if (!Number.isInteger(offset) || offset < 0 || offset + bytes.length > arenaBytes)
                        throw new RangeError("v86gl write outside registered arena");
                    dev.write_memory(bytes, arenaAddress + offset);
                    break;
                }
                case "done": {
                    const bytes = inflight.get(message.id);
                    if (bytes === undefined) return;
                    inflight.delete(message.id);
                    inflightBytes -= bytes;
                    // Descriptors left with the guest while the renderer was full
                    processQueue();
                    break;
                }
                case "available":
                    hostAvailable = !!message.value;
                    break;
            }
        });

        // A local renderer answers inside post(): its "done" comes back while
        // the queue is being processed
        function processQueue() {
            if (processing) {
                processAgain = true;
                return;
            }
            processing = true;
            try {
                do {
                    processAgain = false;
                    processRequests();
                } while (processAgain);
            } finally {
                processing = false;
            }
        }

        function processRequests() {
            if (!dev.is_feature_negotiated(F_SHARED_ARENA) || !dev.is_feature_negotiated(F_VERSION_1)) return;
            // Leave descriptors with the guest until the renderer has room
            while (canAccept() && dev.has_request(0)) {
                const request = dev.pop_request(0);
                if (!request) break;
                if (request.readable !== REQUEST_BYTES || request.writable !== RESPONSE_BYTES) {
                    dev.needs_reset();
                    break;
                }
                let result = INVALID;
                try {
                    result = handleRequest(request.read());
                } catch (error) {
                    console.error("[virtio-v86gl] request failed", error);
                }
                request.write(new Uint8Array(new Uint32Array([result, lastFrameId, lastBytes, submitCount]).buffer));
                request.complete();
            }
            dev.flush(0);
        }

        function handleRequest(request) {
            const view = new DataView(request.buffer, request.byteOffset, REQUEST_BYTES);
            const op = view.getUint32(0, true);
            const address = view.getUint32(4, true);
            const high = view.getUint32(8, true);
            const length = view.getUint32(12, true);
            const flags = view.getUint32(16, true);
            if (view.getUint32(20, true)) return INVALID;
            if (op === REGISTER_ARENA) {
                // A 64-bit guest-physical address: RAM anywhere on the 36-bit bus
                const arena = address + high * 0x100000000;
                if (arenaBytes || flags || length !== ARENA_BYTES || !arena || !dev.is_ram(arena, length))
                    return INVALID;
                ++arenaGeneration;
                arenaAddress = arena;
                arenaBytes = length;
                return OK;
            }
            if (address || high) return INVALID;
            if (op === UNREGISTER_ARENA) {
                if (length || flags) return INVALID;
                releaseArena();
                return OK;
            }
            if (op !== SUBMIT || (flags & ~1)) return INVALID;
            if (!arenaBytes) return NO_ARENA;
            if (length < HEADER_BYTES || length > arenaBytes) return INVALID;

            // A view of guest RAM while the batch has one contiguous backing
            // (checked per submission: the physical map may have changed)
            const raw = dev.read_memory(arenaAddress, length);
            const header = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
            const commandBytes = header.getUint32(20, true);
            // VGL2 reserved words belong to the graphics protocol, not to the
            // virtqueue request. Shipping D3D8/D3D9/DDraw DLLs put D9WG_MAGIC in
            // reserved0; the old PCI transport ignored both words. Preserve that ABI.
            if (header.getUint32(0, true) !== MAGIC || header.getUint32(4, true) !== 1 ||
                    commandBytes !== length - HEADER_BYTES || (header.getUint32(8, true) & ~1))
                return INVALID;
            if (!hostAvailable) return NO_RENDERER;

            const id = ++nextBatch;
            // Across threads a copy the renderer owns; never the guest's memory
            const bytes = remote ? raw.slice(HEADER_BYTES) : raw.subarray(HEADER_BYTES);
            inflight.set(id, bytes.byteLength);
            inflightBytes += bytes.byteLength;
            const frameId = header.getUint32(12, true);
            channel.post({
                type: "batch",
                id,
                generation: arenaGeneration,
                frameId,
                flags: header.getUint32(8, true) | flags,
                commandCount: header.getUint32(16, true),
                descAddr: arenaAddress,
                descLen: length,
                batchAddr: arenaAddress + HEADER_BYTES,
                responseBase: arenaBytes - RESPONSE_AREA_BYTES - HEADER_BYTES,
                submitCount: submitCount + 1,
                bytes,
            }, remote ? [bytes.buffer] : undefined);
            lastFrameId = frameId;
            lastBytes = commandBytes;
            ++submitCount;
            return OK;
        }

        return {
            name: "v86gl",
            // The slot keeps Windows' device instance, and so the installed driver
            pci_slot: 0x13,
            io_base: 0xF100,
            // Provisional, unallocated local ID. NOT the standard virtio-gpu ID.
            device_id: 0x107F,
            subsystem_device_id: 0x5686,
            features: [F_SHARED_ARENA],
            queues: [{ size: 8 }],
            config: [
                { bytes: 4, name: "magic", read: () => MAGIC },
                { bytes: 4, name: "version", read: () => 1 },
                { bytes: 4, name: "arena_bytes", read: () => ARENA_BYTES },
                { bytes: 4, name: "max_batch_bytes", read: () => ARENA_BYTES },
            ],
            init(handle) {
                dev = handle;
            },
            notify() {
                processQueue();
            },
            // Batches the renderer has not acknowledged yet
            busy() {
                return inflight.size;
            },
            reset() {
                releaseArena();
                lastFrameId = lastBytes = submitCount = 0;
                forgetInflight();
            },
            get_state() {
                return [STATE_VERSION, arenaAddress, arenaBytes, lastFrameId, lastBytes, submitCount];
            },
            set_state(state) {
                if (!Array.isArray(state) || state[0] !== STATE_VERSION)
                    throw new Error("Unsupported virtio-v86gl state in snapshot");
                const [, address, bytes, frameId, last, count] = state;
                if (bytes && (bytes !== ARENA_BYTES || !dev.is_ram(address, bytes)))
                    throw new Error("Invalid virtio-v86gl arena in snapshot");
                releaseArena();
                arenaAddress = address;
                arenaBytes = bytes;
                lastFrameId = frameId;
                lastBytes = last;
                submitCount = count;
                forgetInflight();
            },
            // [magic, transport, arena address, arena bytes, frame id, bytes,
            //  submit count, 0, graphics checkpoint]
            upgrade_state(slot) {
                if (!Array.isArray(slot) || slot[0] !== LEGACY_STATE_MAGIC) return null;
                return [slot[1], [STATE_VERSION, slot[2], slot[3], slot[4], slot[5], slot[6]], slot[8]];
            },
        };
    }

    const factories = global.V86VirtioDeviceFactories || (global.V86VirtioDeviceFactories = {});
    factories.v86gl = createV86GLDevice;
    if (typeof module !== "undefined" && module.exports)
        module.exports = { createV86GLDevice };
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                              source/v64/src/browser/glbridge/vx/naga/Cargo.toml                                                  0000644 0000000 0000000 00000000704 00000000000 017211  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       [package]
name = "vx_naga"
version = "0.1.0"
edition = "2021"
description = "SPIR-V to WGSL for VX (virtio-gpu's Venus contexts), with naga"
publish = false

[lib]
crate-type = ["cdylib", "rlib"]
path = "src/lib.rs"

[dependencies]
naga = { version = "30.0.0", default-features = false, features = ["spv-in", "wgsl-out"] }

[profile.release]
opt-level = "s"
lto = true
panic = "abort"
codegen-units = 1

# (not a member of v86's workspace)
[workspace]
                                                            source/v64/src/browser/glbridge/vx/naga/examples/dump.rs                                            0000644 0000000 0000000 00000003101 00000000000 020404  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! cargo run --example dump -- <file.spv>: the module naga reads (after VX's
//! SPIR-V passes): its global variables and entry points, for debugging
fn main() {
    let path = std::env::args().nth(1).expect("a SPIR-V file");
    let bytes = std::fs::read(&path).expect("read");
    // (DUMP_SPV=<file>: the SPIR-V after VX's passes written there)
    if let Ok(out) = std::env::var("DUMP_SPV") {
        std::fs::write(out, vx_naga::passes_for_debugging(&bytes)).expect("write");
    }
    let module = vx_naga::parse_for_debugging(&bytes).expect("parse");
    for (handle, var) in module.global_variables.iter() {
        println!("{:?} {:?} {:?} {:?} {:?}", handle, var.name, var.space, var.binding, module.types[var.ty].inner);
    }
    // (DUMP_FUNCTION=<index>: that function's expressions and stores)
    if let Ok(index) = std::env::var("DUMP_FUNCTION") {
        let f = &module.functions[module.functions.iter().nth(index.parse().unwrap()).unwrap().0];
        for (h, e) in f.expressions.iter() {
            println!("  {:?} {:?}", h, e);
        }
        println!("  body {:?}", f.body);
        for (h, v) in f.local_variables.iter() {
            println!("  local {:?} {:?}", h, module.types[v.ty].inner);
        }
    }
    for ep in &module.entry_points {
        println!("entry {} {:?}", ep.name, ep.stage);
        for a in &ep.function.arguments {
            println!("  in {:?} {:?} {:?}", a.name, a.binding, module.types[a.ty].inner);
        }
        if let Some(r) = &ep.function.result {
            println!("  out {:?}", module.types[r.ty].inner);
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/glbridge/vx/naga/examples/geometry.rs                                        0000644 0000000 0000000 00000001343 00000000000 021300  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The compute shader of a geometry shader's SPIR-V (geometry.rs): cargo
//! run --example geometry -- shader.spv [group]
fn main() {
    let args: Vec<String> = std::env::args().collect();
    let bytes = std::fs::read(&args[1]).expect("the SPIR-V");
    let group = args.get(2).map_or(1, |g| g.parse().unwrap());
    let options = vx_naga::Options { immediates_group: 0, immediates_binding: 0, keep_coordinate_space: true, storage_uniforms: Vec::new(), drop_frag_depth: false,
        reverse_depth: false, gl_depth: false, int_wraps: Vec::new() };
    match vx_naga::translate_geometry(&bytes, &options, group) {
        Ok(json) => println!("{}", json),
        Err(e) => { eprintln!("error: {}", e); std::process::exit(1); }
    }
}
                                                                                                                                                                                                                                                                                             source/v64/src/browser/glbridge/vx/naga/examples/tessellation.rs                                    0000644 0000000 0000000 00000001434 00000000000 022154  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The compute shader of a tessellation shader's SPIR-V (tessellation.rs):
//! cargo run --example tessellation -- shader.spv control|evaluation [group]
fn main() {
    let args: Vec<String> = std::env::args().collect();
    let bytes = std::fs::read(&args[1]).expect("the SPIR-V");
    let group = args.get(3).map_or(1, |g| g.parse().unwrap());
    let options = vx_naga::Options { immediates_group: 0, immediates_binding: 0, keep_coordinate_space: true, storage_uniforms: Vec::new(), drop_frag_depth: false,
        reverse_depth: false, gl_depth: false, int_wraps: Vec::new() };
    match vx_naga::translate_tessellation(&bytes, &options, args[2] == "control", group) {
        Ok(json) => println!("{}", json),
        Err(e) => { eprintln!("error: {}", e); std::process::exit(1); }
    }
}
                                                                                                                                                                                                                                    source/v64/src/browser/glbridge/vx/naga/examples/translate.rs                                       0000644 0000000 0000000 00000002045 00000000000 021442  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! cargo run --example translate -- <file.spv>...: the JSON answer of each
//! (VX_INT_WRAPS=<key>:<modes>,...: integer images' address modes, Options::int_wraps)
fn main() {
    let int_wraps: Vec<(u32, u32)> = std::env::var("VX_INT_WRAPS").unwrap_or_default().split(',').filter(|s| !s.is_empty())
        .map(|s| { let (k, m) = s.split_once(':').expect("key:modes"); (k.parse().unwrap(), u32::from_str_radix(m.trim_start_matches("0x"), 16).unwrap()) }).collect();
    for path in std::env::args().skip(1) {
        let bytes = std::fs::read(&path).expect("read");
        match vx_naga::translate(&bytes, &vx_naga::Options { immediates_group: 3, immediates_binding: 998, keep_coordinate_space: false, storage_uniforms: Vec::new(), drop_frag_depth: std::env::var("VX_NO_DEPTH").is_ok(), reverse_depth: std::env::var("VX_REVERSE_DEPTH").is_ok(), gl_depth: std::env::var("VX_GL_DEPTH").is_ok(), int_wraps: int_wraps.clone() }) {
            Ok(json) => println!("{}: {}", path, json),
            Err(e) => println!("{}: ERROR {}", path, e),
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/browser/glbridge/vx/naga/examples/xfb.rs                                             0000644 0000000 0000000 00000002636 00000000000 020232  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The compute shader of a capturing draw for a vertex shader's SPIR-V
//! (xfb.rs): cargo run --example xfb -- shader.spv [group]; its vertex
//! input: attributes (location, slot, VkFormat, offset) 0/0/R32G32_SFLOAT/0,
//! 1/1/R8G8B8A8_UNORM/0, 2/1/R32_UINT/4; slots 0 stride 8, 1 stride 8
fn main() {
    let args: Vec<String> = std::env::args().collect();
    let bytes = std::fs::read(&args[1]).expect("the SPIR-V");
    let group = args.get(2).map_or(1, |g| g.parse().unwrap());
    let input = vx_naga::XfbInput {
        attributes: vec![
            vx_naga::xfb::Attribute { location: 0, slot: 0, format: 103, offset: 0 },
            vx_naga::xfb::Attribute { location: 1, slot: 1, format: 37, offset: 0 },
            vx_naga::xfb::Attribute { location: 2, slot: 1, format: 98, offset: 4 },
        ],
        slots: vec![vx_naga::xfb::Slot { slot: 0, stride: 8, instance: false }, vx_naga::xfb::Slot { slot: 1, stride: 8, instance: false }],
        group,
        all: std::env::var("XFB_ALL").is_ok(),
    };
    let options = vx_naga::Options { immediates_group: 3, immediates_binding: 998, keep_coordinate_space: true, storage_uniforms: Vec::new(), drop_frag_depth: false, reverse_depth: false, gl_depth: false, int_wraps: Vec::new() };
    match vx_naga::translate_xfb(&bytes, &options, &input) {
        Ok(json) => println!("{}", json),
        Err(e) => { eprintln!("error: {}", e); std::process::exit(1); }
    }
}
                                                                                                  source/v64/src/browser/glbridge/vx/naga/src/atomics.rs                                              0000644 0000000 0000000 00000011350 00000000000 020054  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Atomic operations whose value is of the other signedness than their
//! result: glslang writes GLSL ES 3.1's atomic counters (in Vulkan's rules,
//! a storage block of `uint`s) as `OpAtomicIAdd` of a signed constant 1 or
//! -1, which naga refuses (`InvalidAtomic`). The value becomes the result's
//! type: a constant of the same bits, declared before the first function,
//! or an `OpBitcast` before the operation.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_TYPE_INT: u32 = 21;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_BITCAST: u32 = 124;
/// the operations whose last operand is a value of the result's type
const OP_ATOMIC_EXCHANGE: u32 = 229;
const OP_ATOMIC_I_ADD: u32 = 234;
const OP_ATOMIC_XOR: u32 = 242;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The module with its atomic operations' values of their results' types,
/// or the words as they were when none needs it
pub fn values(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    // the integer types (id: width, signedness), the values' types (constants' and other results')
    let mut ints: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    let mut types: BTreeMap<u32, u32> = BTreeMap::new();
    let mut constants: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    for w in &instructions {
        match op(w) {
            OP_TYPE_INT if w.len() >= 4 => {
                ints.insert(w[1], (w[2], w[3]));
            },
            OP_CONSTANT if w.len() >= 4 => {
                constants.insert(w[2], (w[1], w[3]));
                types.insert(w[2], w[1]);
            },
            // (a result type and a result: function calls, loads, extracts, conversions, arithmetic, atomics, phis)
            o if w.len() >= 3 && matches!(o, 57 | 61 | 81 | 109..=124 | 126..=200 | 227 | 229..=242 | 245) => {
                types.insert(w[2], w[1]);
            },
            _ => {},
        }
    }
    let is_atomic_value = |w: &[u32]| matches!(op(w), OP_ATOMIC_EXCHANGE | OP_ATOMIC_I_ADD..=OP_ATOMIC_XOR) && w.len() >= 7;
    let mismatched = |w: &[u32]| {
        let value = w[w.len() - 1];
        let result = w[1];
        match (types.get(&value), ints.get(&result)) {
            (Some(&t), Some(&(width, _))) => t != result && ints.get(&t).map_or(false, |&(w2, _)| w2 == width),
            _ => false,
        }
    };
    if !instructions.iter().any(|w| is_atomic_value(w) && mismatched(w)) {
        return words.to_vec();
    }
    let mut bound = words[3];
    let mut fresh = || {
        let id = bound;
        bound += 1;
        id
    };
    // constants of the results' types: (type, bits) to id
    let mut own: BTreeMap<(u32, u32), u32> = constants.iter().map(|(&id, &(t, v))| ((t, v), id)).collect();
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut body: Vec<Vec<u32>> = Vec::new();
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    for (i, w) in instructions.iter().enumerate() {
        if i < first_function || !(is_atomic_value(w) && mismatched(w)) {
            body.push(w.to_vec());
            continue;
        }
        let value = w[w.len() - 1];
        let result_type = w[1];
        let replacement = match constants.get(&value) {
            Some(&(_, bits)) => *own.entry((result_type, bits)).or_insert_with(|| {
                let id = fresh();
                declarations.push(instruction(OP_CONSTANT, &[result_type, id, bits]));
                id
            }),
            None => {
                let id = fresh();
                body.push(instruction(OP_BITCAST, &[result_type, id, value]));
                id
            },
        };
        let mut changed = w.to_vec();
        let last = changed.len() - 1;
        changed[last] = replacement;
        body.push(changed);
    }
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    if first_function >= body.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out
}
                                                                                                                                                                                                                                                                                        source/v64/src/browser/glbridge/vx/naga/src/blockarrays.rs                                          0000644 0000000 0000000 00000035007 00000000000 020736  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Descriptor arrays (GLSL's `uniform B { ... } b[2];` and `uniform
//! sampler2D s[4];`): WGSL binds no arrays of buffers, and WebGPU no
//! arrays of textures or samplers, so each element a shader uses becomes a
//! variable of its own, element 0 at the array's binding, element e > 0 at
//! `ELEMENT_BINDING + 16 * binding + e` (lib.rs's rebind makes that WGSL's
//! 300 + 2 (16b + e), its split sampler's one more), and each access chain
//! into the array with a constant index starts at that element's variable
//! (or is that variable, with no more indices). An array indexed otherwise,
//! used other than by access chains, or of a binding past 19, is left as it
//! was (GLSL ES 3.0 indexes them with constant expressions only). This runs
//! before split.rs, which splits the combined elements as any other.
//!
//! A module marked by `OpModuleProcessed` CONSECUTIVE (the GLES host's,
//! glsl_program.js, whose bindings give each element of a block array a
//! binding of its own, the array's plus the index) has its arrays of
//! blocks' elements at those bindings, of any binding and length.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

/// The SPIR-V bindings of the elements after the first
pub const ELEMENT_BINDING: u32 = 0x20000;
/// The elements an array can have, and the largest binding of one
pub const ELEMENTS_A_BINDING: u32 = 16;
const LAST_BINDING: u32 = 19;
/// The marker of modules whose block arrays' elements have consecutive bindings
pub const CONSECUTIVE: &[u8] = b"vx consecutive block elements";
const OP_MODULE_PROCESSED: u32 = 330;

const OP_TYPE_IMAGE: u32 = 25;
const OP_TYPE_SAMPLER: u32 = 26;
const OP_TYPE_SAMPLED_IMAGE: u32 = 27;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_FUNCTION_CALL: u32 = 57;
const OP_VARIABLE: u32 = 59;
const OP_LOAD: u32 = 61;
const OP_ARRAY_LENGTH: u32 = 68;
const OP_ACCESS_CHAIN: u32 = 65;
const OP_IN_BOUNDS_ACCESS_CHAIN: u32 = 66;
const OP_DECORATE: u32 = 71;
const DECORATION_BLOCK: u32 = 2;
const DECORATION_BUFFER_BLOCK: u32 = 3;
const DECORATION_BINDING: u32 = 33;
const DECORATION_DESCRIPTOR_SET: u32 = 34;

/// Whether word i of an instruction of this opcode is a literal, not an id
/// (the ones a function's code has that might equal one by chance)
pub(crate) fn literal(op: u32, i: usize) -> bool {
    match op {
        8 | 317 => true,                       // OpLine, OpNoLine
        12 => i == 4,                          // OpExtInst's instruction
        61 => i >= 4,                          // OpLoad's memory access
        62 => i >= 3,                          // OpStore's
        79 => i >= 5,                          // OpVectorShuffle's components
        81 => i >= 4,                          // OpCompositeExtract's indices
        82 => i >= 5,                          // OpCompositeInsert's
        87 | 88 | 91 | 92 | 95 | 98 => i == 5, // image operands' masks
        89 | 90 | 93 | 94 | 96 | 97 => i == 6,
        99 => i == 4,
        59 => i == 3,                          // OpVariable's storage class
        246 => i >= 3,                         // OpLoopMerge's controls
        247 => i == 2,                         // OpSelectionMerge's
        250 => i >= 4,                         // OpBranchConditional's weights
        _ => false,
    }
}

/// Whether an instruction names `id` among its operands: its ids, not its
/// literals (a member's offset, a constant's value, a pointer's storage
/// class, an entry point's name), and nothing for debug names, decorations
/// and the module's settings, which keep no type declared (layout.rs's too)
pub(crate) fn names(w: &[u32], id: u32) -> bool {
    let at = |i: usize| w.get(i) == Some(&id);
    match w[0] & 0xFFFF {
        2..=11 | 14 | 16 | 17 | 19..=22 | 26 | 71..=74 | 330..=332 => false,
        // (OpEntryPoint: its function, and its interface after the name's words)
        15 => {
            let name_end = w.iter().skip(3).position(|x| x.to_le_bytes().contains(&0)).map_or(w.len(), |p| p + 4);
            at(2) || w.iter().skip(name_end).any(|&x| x == id)
        },
        23..=25 | 27 | 29 => at(2),
        32 => at(3),
        43 | 50 => at(1),
        52 => at(1) || w.iter().skip(4).any(|&x| x == id),
        _ => w.iter().enumerate().skip(1).any(|(i, &x)| x == id && !literal(w[0] & 0xFFFF, i)),
    }
}

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The module with its arrays of blocks split, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let types: BTreeMap<u32, &[u32]> = instructions.iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let constants: BTreeMap<u32, u32> = instructions.iter().filter(|w| op(w) == OP_CONSTANT && w.len() == 4).map(|w| (w[2], w[3])).collect();
    let blocks: Vec<u32> = instructions.iter().filter(|w| op(w) == OP_DECORATE && w.len() >= 3 && matches!(w[2], DECORATION_BLOCK | DECORATION_BUFFER_BLOCK))
        .map(|w| w[1]).collect();
    let decoration = |id: u32, d: u32| instructions.iter().find(|w| op(w) == OP_DECORATE && w.len() >= 4 && w[1] == id && w[2] == d).map(|w| w[3]);
    let marker = |w: &[u32]| op(w) == OP_MODULE_PROCESSED && w[1..].iter().flat_map(|x| x.to_le_bytes()).take_while(|&b| b != 0).eq(CONSECUTIVE.iter().copied());
    let consecutive = instructions.iter().any(|w| marker(w));
    // the variables of arrays of blocks: (variable, its class, the block, the length, set, binding, its elements' bindings consecutive)
    let mut arrays = Vec::new();
    for w in &instructions {
        if op(w) != OP_VARIABLE || w.len() < 4 {
            continue;
        }
        let Some(pointer) = types.get(&w[1]) else { continue };
        if op(pointer) != OP_TYPE_POINTER || pointer.len() < 4 {
            continue;
        }
        let Some(array) = types.get(&pointer[3]) else { continue };
        if op(array) != OP_TYPE_ARRAY {
            continue;
        }
        let element = types.get(&array[2]).map(|t| op(t));
        let block = blocks.contains(&array[2]) && element == Some(OP_TYPE_STRUCT);
        if !block && !matches!(element, Some(OP_TYPE_IMAGE | OP_TYPE_SAMPLER | OP_TYPE_SAMPLED_IMAGE)) {
            continue;
        }
        let (Some(&length), Some(set), Some(binding)) = (constants.get(&array[3]), decoration(w[2], DECORATION_DESCRIPTOR_SET), decoration(w[2], DECORATION_BINDING))
        else {
            continue;
        };
        let own_bindings = block && consecutive;
        if length < 1 || !own_bindings && (length > ELEMENTS_A_BINDING || binding > LAST_BINDING) {
            continue;
        }
        arrays.push((w[2], pointer[2], array[2], length, set, binding, own_bindings, w[1], pointer[3]));
    }
    if arrays.is_empty() {
        return words.to_vec();
    }
    // (an entry point listing one among its interface: SPIR-V 1.4's, not done)
    const OP_ENTRY_POINT: u32 = 15;
    if instructions.iter().any(|w| op(w) == OP_ENTRY_POINT && arrays.iter().any(|a| w[3..].contains(&a.0))) {
        return words.to_vec();
    }
    // every use of such a variable: an access chain with a constant first
    // index (the elements used); a chain of that index alone is the
    // element's variable, which only loads, calls and array lengths may then use
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let mut used_elements: BTreeSet<(u32, u32)> = BTreeSet::new();
    let mut whole: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    for w in &instructions[first_function..] {
        let chain = matches!(op(w), OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN) && w.len() >= 5;
        for &(var, ..) in &arrays {
            let used = w[1..].iter().enumerate().any(|(i, &x)| x == var && !(chain && i + 1 == 3) && !literal(op(w), i + 1));
            if used || chain && w[3] == var && !constants.contains_key(&w[4]) {
                return words.to_vec();
            }
            if chain && w[3] == var {
                used_elements.insert((var, constants[&w[4]]));
                if w.len() == 5 {
                    whole.insert(w[2], (var, constants[&w[4]]));
                }
            }
        }
        // (a load's pointer, an array length's structure, a call's arguments, a chain's own result or base)
        let allowed = |i: usize| match op(w) {
            OP_LOAD | OP_ARRAY_LENGTH => i == 3,
            OP_FUNCTION_CALL => i >= 4,
            OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN => i == 2 || i == 3,
            _ => false,
        };
        if w.iter().enumerate().skip(1).any(|(i, x)| whole.contains_key(x) && !allowed(i) && !literal(op(w), i)) {
            return words.to_vec();
        }
    }
    let mut bound = words[3];
    let mut fresh = || {
        bound += 1;
        bound - 1
    };
    // the elements' variables, and pointer types to the blocks
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut annotations: Vec<Vec<u32>> = Vec::new();
    let mut elements: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
    let mut pointers: BTreeMap<(u32, u32), u32> = types.values().filter(|w| op(w) == OP_TYPE_POINTER && w.len() >= 4).map(|w| ((w[2], w[3]), w[1])).collect();
    for &(var, class, block, length, set, binding, own_bindings, ..) in &arrays {
        let pointer = match pointers.get(&(class, block)) {
            Some(&p) => p,
            None => {
                let p = fresh();
                declarations.push(instruction(OP_TYPE_POINTER, &[p, class, block]));
                pointers.insert((class, block), p);
                p
            },
        };
        let mut list = Vec::new();
        for e in 0..length {
            // (the elements not used: none)
            if !used_elements.contains(&(var, e)) {
                list.push(0);
                continue;
            }
            let id = fresh();
            declarations.push(instruction(OP_VARIABLE, &[pointer, id, class]));
            annotations.push(instruction(OP_DECORATE, &[id, DECORATION_DESCRIPTOR_SET, set]));
            let element_binding = if e == 0 { binding } else if own_bindings { binding + e } else { ELEMENT_BINDING + ELEMENTS_A_BINDING * binding + e };
            annotations.push(instruction(OP_DECORATE, &[id, DECORATION_BINDING, element_binding]));
            list.push(id);
        }
        elements.insert(var, list);
    }
    // the arrays' pointer and array types where nothing else names them (an array of blocks with an unsized array, which
    // naga refuses to declare at all)
    const OP_NAME: u32 = 5;
    let naming = |w: &[u32]| matches!(op(w), OP_NAME | OP_DECORATE);
    let variables: BTreeSet<u32> = arrays.iter().map(|a| a.0).collect();
    let dead_pointers: BTreeSet<u32> = arrays.iter().map(|a| a.7).filter(|&p| !instructions.iter().any(|w| {
        let defines = op(w) == OP_TYPE_POINTER && w[1] == p || op(w) == OP_VARIABLE && w.len() >= 3 && variables.contains(&w[2]);
        !defines && names(w, p)
    })).collect();
    let dead_arrays: BTreeSet<u32> = arrays.iter().filter(|a| dead_pointers.contains(&a.7)).map(|a| a.8).filter(|&t| !instructions.iter().any(|w| {
        let defines = op(w) == OP_TYPE_ARRAY && w[1] == t || op(w) == OP_TYPE_POINTER && dead_pointers.contains(&w[1]);
        !defines && names(w, t)
    })).collect();
    let dead = |id: u32| dead_pointers.contains(&id) || dead_arrays.contains(&id);
    let first_global = instructions.iter().position(|w| matches!(op(w), 19..=39 | 41..=52 | OP_VARIABLE)).unwrap_or(first_function);
    let mut out = words[..5].to_vec();
    for (i, w) in instructions.iter().enumerate() {
        if i == first_global {
            for a in &annotations {
                out.extend_from_slice(a);
            }
        }
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        let o = op(w);
        // the arrays' variables and their decorations go, and the marker, and the types nothing names
        if marker(w) || matches!(o, OP_TYPE_POINTER | OP_TYPE_ARRAY) && dead(w[1]) || naming(w) && w.len() >= 2 && dead(w[1]) {
            continue;
        }
        if o == OP_VARIABLE && w.len() >= 3 && elements.contains_key(&w[2]) || o == OP_DECORATE && w.len() >= 2 && elements.contains_key(&w[1]) {
            continue;
        }
        if matches!(o, OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN) && w.len() >= 5 {
            if let Some(list) = elements.get(&w[3]) {
                let e = constants[&w[4]] as usize;
                if e >= list.len() {
                    return words.to_vec();
                }
                // (a chain of the index alone: the element's variable in its uses)
                if w.len() == 5 {
                    continue;
                }
                let mut operands = Vec::from([w[1], w[2], list[e]]);
                operands.extend_from_slice(&w[5..]);
                out.extend_from_slice(&instruction(o, &operands));
                continue;
            }
        }
        let element_of = |id: u32| whole.get(&id).map(|&(var, e)| elements[&var][e as usize]);
        if matches!(o, OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN) && w.len() >= 4 {
            if let Some(v) = element_of(w[3]) {
                let mut c = w.to_vec();
                c[3] = v;
                out.extend_from_slice(&c);
                continue;
            }
        }
        if matches!(o, OP_LOAD | OP_ARRAY_LENGTH) && w.len() >= 4 {
            if let Some(v) = element_of(w[3]) {
                let mut l = w.to_vec();
                l[3] = v;
                out.extend_from_slice(&l);
                continue;
            }
        }
        if o == OP_FUNCTION_CALL && w.len() >= 4 && w[4..].iter().any(|x| whole.contains_key(x)) {
            let mut c = w.to_vec();
            for x in c[4..].iter_mut() {
                if let Some(v) = element_of(*x) {
                    *x = v;
                }
            }
            out.extend_from_slice(&c);
            continue;
        }
        out.extend_from_slice(w);
    }
    out[3] = bound;
    out
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/browser/glbridge/vx/naga/src/border.rs                                               0000644 0000000 0000000 00000023175 00000000000 017702  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Clamp to border (GLES 3.2, EXT_texture_border_clamp) for samples of float
//! images: WebGPU's samplers have no border, so the sampler clamps to the
//! edge and a sample whose coordinate is outside [0, 1) on an axis that
//! clamps to the border takes the border color instead. That is GL's
//! answer with the nearest filter; with the linear one the texels at the
//! edge do not blend with the border (a deviation). The border colors are
//! the draw's, constants of the translation, as the caller gives them in
//! the wraps list (intsample.rs's): an image's address modes
//! (VkSamplerAddressMode, 3 clamp to border, a nibble an axis), and each
//! color component's bits by `BORDER_COLOR | component << 24 | key`.
//! Depth comparisons, projective samples, gathers and cube images are left
//! as they were.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

/// The flag of a border color component's entry in the wraps list
pub const BORDER_COLOR: u32 = 0x8000_0000;
const CLAMP_TO_BORDER: u32 = 3;

const OP_TYPE_BOOL: u32 = 20;
const OP_TYPE_FLOAT: u32 = 22;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_IMAGE: u32 = 25;
const OP_TYPE_SAMPLED_IMAGE: u32 = 27;
const OP_CONSTANT: u32 = 43;
const OP_CONSTANT_COMPOSITE: u32 = 44;
const OP_FUNCTION: u32 = 54;
const OP_LOAD: u32 = 61;
const OP_DECORATE: u32 = 71;
const OP_COMPOSITE_CONSTRUCT: u32 = 80;
const OP_COMPOSITE_EXTRACT: u32 = 81;
const OP_SAMPLED_IMAGE: u32 = 86;
const OP_IMAGE_SAMPLE_IMPLICIT_LOD: u32 = 87;
const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u32 = 88;
const OP_LOGICAL_OR: u32 = 166;
const OP_SELECT: u32 = 169;
const OP_F_ORD_LESS_THAN: u32 = 184;
const OP_F_ORD_GREATER_THAN_EQUAL: u32 = 190;
const DECORATION_BINDING: u32 = 33;
const DECORATION_DESCRIPTOR_SET: u32 = 34;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type (intsample.rs's)
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

/// The module with its samples of images whose samplers clamp to the border
/// choosing the border color outside the image, or the words as they were
pub fn lower(words: &[u32], wraps: &[(u32, u32)]) -> Vec<u32> {
    // the images that clamp to the border: their axes and colors
    let mut borders: BTreeMap<u32, (u32, [u32; 4])> = BTreeMap::new();
    for &(key, modes) in wraps {
        if key & BORDER_COLOR != 0 {
            continue;
        }
        let axes = (0..3).filter(|k| modes >> (4 * k) & 0xF == CLAMP_TO_BORDER).fold(0, |m, k| m | 1 << k);
        if axes != 0 {
            let mut color = [0u32; 4];
            for (c, bits) in color.iter_mut().enumerate() {
                *bits = wraps.iter().find(|(x, _)| *x == BORDER_COLOR | (c as u32) << 24 | key).map_or(0, |(_, v)| *v);
            }
            borders.insert(key, (axes, color));
        }
    }
    if borders.is_empty() || words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let types: BTreeMap<u32, &[u32]> = instructions[..first_function].iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let defs: BTreeMap<u32, &[u32]> = instructions[first_function..].iter().filter(|w| w.len() >= 3 && !untyped(op(w))).map(|w| (w[2], *w)).collect();
    let decoration = |id: u32, d: u32| instructions[..first_function].iter().find(|w| op(w) == OP_DECORATE && w.len() >= 4 && w[1] == id && w[2] == d).map(|w| w[3]);
    // a sampled image's image key (an OpSampledImage of an OpLoad of a variable, intsample.rs's) and its image type
    let image_of = |si: u32| -> Option<(u32, &[u32])> {
        let s = defs.get(&si)?;
        if op(s) != OP_SAMPLED_IMAGE || s.len() < 5 {
            return None;
        }
        let load = defs.get(&s[3])?;
        if op(load) != OP_LOAD || load.len() < 4 {
            return None;
        }
        let key = decoration(load[3], DECORATION_DESCRIPTOR_SET)? << 16 | crate::wgsl_binding(decoration(load[3], DECORATION_BINDING)?);
        let sampled = types.get(&s[1])?;
        let image = if op(sampled) == OP_TYPE_SAMPLED_IMAGE { types.get(&sampled[2])? } else { return None };
        if op(image) != OP_TYPE_IMAGE || image.len() < 9 {
            return None;
        }
        Some((key, *image))
    };
    let float_vec4 = |ty: u32| types.get(&ty).is_some_and(|t| op(t) == OP_TYPE_VECTOR && t[3] == 4 && types.get(&t[2]).is_some_and(|f| op(f) == OP_TYPE_FLOAT));

    let mut bound = words[3];
    let mut fresh = || { bound += 1; bound - 1 };
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut boolean = types.iter().find(|(_, t)| op(t) == OP_TYPE_BOOL).map(|(&id, _)| id);
    let mut bvec4 = None;
    let mut constants: BTreeMap<(u32, u32), u32> = instructions[..first_function].iter().filter(|w| op(w) == OP_CONSTANT && w.len() == 4)
        .map(|w| ((w[1], w[3]), w[2])).collect();
    let mut colors: BTreeMap<u32, u32> = BTreeMap::new();
    let mut body: Vec<Vec<u32>> = Vec::new();
    let mut changed = false;
    for (i, w) in instructions.iter().enumerate() {
        let sample = i >= first_function && matches!(op(w), OP_IMAGE_SAMPLE_IMPLICIT_LOD | OP_IMAGE_SAMPLE_EXPLICIT_LOD) && w.len() >= 5;
        let found = if sample && float_vec4(w[1]) { image_of(w[3]).and_then(|(key, image)| borders.get(&key).map(|b| (key, *b, image))) } else { None };
        // (1D, 2D or 3D, arrayed or not; not a cube's; its float component type)
        let Some((key, (axes, color), image)) = found.filter(|(_, _, image)| image[3] <= 2 && image[4] != 1 && types.get(&image[2]).is_some_and(|t| op(t) == OP_TYPE_FLOAT)) else {
            body.push(w.to_vec());
            continue;
        };
        changed = true;
        let float = image[2];
        let spatial = image[3] + 1;
        let vec4 = w[1];
        let b = *boolean.get_or_insert_with(|| { let id = fresh(); declarations.push(instruction(OP_TYPE_BOOL, &[id])); id });
        let bv = *bvec4.get_or_insert_with(|| {
            types.iter().find(|(_, t)| op(t) == OP_TYPE_VECTOR && t[2] == b && t[3] == 4).map(|(&id, _)| id)
                .unwrap_or_else(|| { let id = fresh(); declarations.push(instruction(OP_TYPE_VECTOR, &[id, b, 4])); id })
        });
        let mut constant = |bits: u32, declarations: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32| *constants.entry((float, bits)).or_insert_with(|| {
            let id = fresh();
            declarations.push(instruction(OP_CONSTANT, &[float, id, bits]));
            id
        });
        let zero = constant(0, &mut declarations, &mut fresh);
        let one = constant(0x3F80_0000, &mut declarations, &mut fresh);
        let border = match colors.get(&key) {
            Some(&id) => id,
            None => {
                let parts: Vec<u32> = color.iter().map(|&bits| constant(bits, &mut declarations, &mut fresh)).collect();
                let id = fresh();
                declarations.push(instruction(OP_CONSTANT_COMPOSITE, &[vec4, id, parts[0], parts[1], parts[2], parts[3]]));
                colors.insert(key, id);
                id
            },
        };
        // the sample's own result renamed; the original result the choice
        let result = w[2];
        let sampled = fresh();
        let mut renamed = w.to_vec();
        renamed[2] = sampled;
        body.push(renamed);
        let coordinate = w[4];
        let coordinate_is_vector = defs.get(&coordinate).and_then(|d| types.get(&d[1])).is_some_and(|t| op(t) == OP_TYPE_VECTOR)
            || image[3] > 0 || image[5] != 0;
        let mut outside = None;
        for k in 0..spatial {
            if axes >> k & 1 == 0 {
                continue;
            }
            let x = if coordinate_is_vector {
                let id = fresh();
                body.push(instruction(OP_COMPOSITE_EXTRACT, &[float, id, coordinate, k]));
                id
            } else { coordinate };
            let (below, above, either) = (fresh(), fresh(), fresh());
            body.push(instruction(OP_F_ORD_LESS_THAN, &[b, below, x, zero]));
            body.push(instruction(OP_F_ORD_GREATER_THAN_EQUAL, &[b, above, x, one]));
            body.push(instruction(OP_LOGICAL_OR, &[b, either, below, above]));
            outside = Some(match outside {
                None => either,
                Some(previous) => {
                    let id = fresh();
                    body.push(instruction(OP_LOGICAL_OR, &[b, id, previous, either]));
                    id
                },
            });
        }
        let Some(outside) = outside else {
            body.last_mut().unwrap()[2] = result;
            continue;
        };
        let condition = fresh();
        body.push(instruction(OP_COMPOSITE_CONSTRUCT, &[bv, condition, outside, outside, outside, outside]));
        body.push(instruction(OP_SELECT, &[vec4, result, condition, border, sampled]));
    }
    if !changed {
        return words.to_vec();
    }
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    out
}
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/glbridge/vx/naga/src/counters.rs                                             0000644 0000000 0000000 00000031064 00000000000 020263  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! GLSL ES 3.1's atomic counters, which glslang writes (in Vulkan's relaxed
//! rules) as a storage block per binding, `gl_AtomicCounterBlock_<binding>`,
//! a member per counter at its layout offset in the order of the shader's
//! declarations: a first counter past offset 0 naga moves to 0 (its WGSL
//! struct has no room before the first member), and offsets that do not grow
//! (counters declared in reverse order) it refuses. Each such block becomes
//! one array of `uint`s 4 bytes apart at offset 0:
//! - a counter's pointer, the array's element at its offset / 4 (an array
//!   of counters' element: plus its indices times their strides / 4);
//! - a load of a counter (glslang's atomicCounter()), an atomic load: the
//!   array is atomic in WGSL as soon as one of its counters is written.
//!
//! A module with another access to such a block (a counter array's pointer
//! of its own) is left as it was.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

const OP_NAME: u32 = 5;
const OP_MEMBER_NAME: u32 = 6;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_LOAD: u32 = 61;
const OP_ACCESS_CHAIN: u32 = 65;
const OP_IN_BOUNDS_ACCESS_CHAIN: u32 = 66;
const OP_BITCAST: u32 = 124;
const OP_I_ADD: u32 = 128;
const OP_I_MUL: u32 = 132;
const OP_ATOMIC_LOAD: u32 = 227;
const DECORATION_ARRAY_STRIDE: u32 = 6;
const DECORATION_OFFSET: u32 = 35;
const SCOPE_DEVICE: u32 = 1;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type (intsample.rs's)
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

fn string_at(words: &[u32]) -> Vec<u8> {
    let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
    bytes.into_iter().take_while(|&b| b != 0).collect()
}

/// A counter block: its members' offsets and (per array level, outermost first) strides, its length in uints
struct Block {
    offsets: Vec<u32>,
    strides: Vec<Vec<u32>>,
    length: u32,
    uint: u32,
}

/// The module with its atomic counter blocks as arrays of uints, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let names: BTreeMap<u32, Vec<u8>> = instructions.iter().filter(|w| op(w) == OP_NAME && w.len() >= 3).map(|w| (w[1], string_at(&w[2..]))).collect();
    let types: BTreeMap<u32, &[u32]> = instructions[..first_function].iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let constants: BTreeMap<u32, (u32, u32)> = instructions[..first_function].iter().filter(|w| op(w) == OP_CONSTANT && w.len() == 4).map(|w| (w[2], (w[1], w[3]))).collect();
    let strides: BTreeMap<u32, u32> = instructions.iter().filter(|w| op(w) == OP_DECORATE && w.len() == 4 && w[2] == DECORATION_ARRAY_STRIDE).map(|w| (w[1], w[3])).collect();
    // the blocks: structs named so, every member a uint or an array (of arrays) of them
    let mut blocks: BTreeMap<u32, Block> = BTreeMap::new();
    for w in &instructions[..first_function] {
        if op(w) != OP_TYPE_STRUCT || !names.get(&w[1]).map_or(false, |n| n.starts_with(b"gl_AtomicCounterBlock")) {
            continue;
        }
        let members = &w[2..];
        let mut offsets = Vec::new();
        let mut member_strides = Vec::new();
        let mut length = 0;
        let mut uint = 0;
        for (m, &member) in members.iter().enumerate() {
            let offset = instructions.iter().find(|d| op(d) == OP_MEMBER_DECORATE && d.len() == 5 && d[1] == w[1] && d[2] == m as u32 && d[3] == DECORATION_OFFSET);
            let Some(offset) = offset.map(|d| d[4]) else { return words.to_vec() };
            // (the array levels down to the uint: their strides and the elements they hold)
            let mut level_strides = Vec::new();
            let mut count = 1;
            let mut t = member;
            while let Some(ty) = types.get(&t).filter(|ty| op(ty) == OP_TYPE_ARRAY && ty.len() == 4) {
                let Some(&(_, n)) = constants.get(&ty[3]) else { return words.to_vec() };
                level_strides.push(strides.get(&t).copied().unwrap_or(0));
                count *= n;
                t = ty[2];
            }
            match types.get(&t) {
                Some(ty) if op(ty) == OP_TYPE_INT && ty.len() == 4 && ty[2] == 32 && ty[3] == 0 => uint = t,
                _ => return words.to_vec(),
            }
            if offset % 4 != 0 || level_strides.iter().any(|&s| s == 0 || s % 4 != 0) {
                return words.to_vec();
            }
            length = length.max(offset / 4 + count);
            offsets.push(offset);
            member_strides.push(level_strides);
        }
        if uint != 0 && length > 0 {
            blocks.insert(w[1], Block { offsets, strides: member_strides, length, uint });
        }
    }
    if blocks.is_empty() {
        return words.to_vec();
    }
    // the blocks' variables
    let pointers: BTreeMap<u32, u32> = instructions[..first_function].iter().filter(|w| op(w) == OP_TYPE_POINTER && w.len() == 4 && blocks.contains_key(&w[3])).map(|w| (w[1], w[3])).collect();
    let variables: BTreeMap<u32, u32> = instructions.iter().filter(|w| op(w) == OP_VARIABLE && w.len() >= 4 && pointers.contains_key(&w[1])).map(|w| (w[2], pointers[&w[1]])).collect();
    let results: BTreeMap<u32, u32> = instructions[first_function..].iter().filter(|w| w.len() >= 3 && !untyped(op(w))).map(|w| (w[2], w[1])).collect();
    let type_of = |id: u32| constants.get(&id).map(|&(t, _)| t).or_else(|| results.get(&id).copied());

    let mut bound = words[3];
    let mut fresh = || { bound += 1; bound - 1 };
    // constants by (type, value): the module's, then this pass's (declared before the first function)
    let mut own: BTreeMap<(u32, u32), u32> = constants.iter().map(|(&id, &(t, v))| ((t, v), id)).collect();
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut constant = |t: u32, v: u32, declarations: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32| *own.entry((t, v)).or_insert_with(|| {
        let id = fresh();
        declarations.push(instruction(OP_CONSTANT, &[t, id, v]));
        id
    });
    // each block's array type and its length (declared before the struct)
    let arrays: BTreeMap<u32, (u32, u32)> = blocks.keys().map(|&s| (s, (fresh(), fresh()))).collect();
    let mut chains: BTreeSet<u32> = BTreeSet::new();
    let mut body: Vec<Vec<u32>> = Vec::new();
    let mut decorated: BTreeSet<u32> = BTreeSet::new();
    for (i, w) in instructions.iter().enumerate() {
        match op(w) {
            OP_MEMBER_NAME if blocks.contains_key(&w[1]) => {},
            OP_MEMBER_DECORATE if blocks.contains_key(&w[1]) => {
                // (the array's offset and stride in place of the members')
                if decorated.insert(w[1]) {
                    body.push(instruction(OP_MEMBER_DECORATE, &[w[1], 0, DECORATION_OFFSET, 0]));
                    body.push(instruction(OP_DECORATE, &[arrays[&w[1]].0, DECORATION_ARRAY_STRIDE, 4]));
                }
            },
            OP_TYPE_STRUCT if blocks.contains_key(&w[1]) => {
                let block = &blocks[&w[1]];
                let (array, length) = arrays[&w[1]];
                body.push(instruction(OP_CONSTANT, &[block.uint, length, block.length]));
                body.push(instruction(OP_TYPE_ARRAY, &[array, block.uint, length]));
                body.push(instruction(OP_TYPE_STRUCT, &[w[1], array]));
            },
            OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN if i > first_function && w.len() >= 5 && variables.contains_key(&w[3]) => {
                let block = &blocks[&variables[&w[3]]];
                let Some(&(index_type, m)) = constants.get(&w[4]) else { return words.to_vec() };
                let m = m as usize;
                if m >= block.offsets.len() || w.len() - 5 != block.strides[m].len() {
                    return words.to_vec();
                }
                // the element: the counter's offset / 4, plus each index times its level's stride / 4
                let mut fixed = block.offsets[m] / 4;
                let mut sum: Option<(u32, u32)> = None;
                for (&index, &stride) in w[5..].iter().zip(&block.strides[m]) {
                    if let Some(&(_, v)) = constants.get(&index) {
                        fixed += v * (stride / 4);
                        continue;
                    }
                    let Some(t) = type_of(index) else { return words.to_vec() };
                    let t_sum = sum.map_or(t, |(t_sum, _)| t_sum);
                    let mut term = index;
                    if t != t_sum {
                        let cast = fresh();
                        body.push(instruction(OP_BITCAST, &[t_sum, cast, term]));
                        term = cast;
                    }
                    if stride != 4 {
                        let scaled = fresh();
                        let factor = constant(t_sum, stride / 4, &mut declarations, &mut fresh);
                        body.push(instruction(OP_I_MUL, &[t_sum, scaled, term, factor]));
                        term = scaled;
                    }
                    sum = Some(match sum {
                        Some((t_sum, acc)) => {
                            let added = fresh();
                            body.push(instruction(OP_I_ADD, &[t_sum, added, acc, term]));
                            (t_sum, added)
                        },
                        None => (t_sum, term),
                    });
                }
                let element = match sum {
                    None => constant(index_type, fixed, &mut declarations, &mut fresh),
                    Some((t_sum, acc)) if fixed != 0 => {
                        let added = fresh();
                        let base = constant(t_sum, fixed, &mut declarations, &mut fresh);
                        body.push(instruction(OP_I_ADD, &[t_sum, added, acc, base]));
                        added
                    },
                    Some((_, acc)) => acc,
                };
                let zero = constant(index_type, 0, &mut declarations, &mut fresh);
                body.push(instruction(op(w), &[w[1], w[2], w[3], zero, element]));
                chains.insert(w[2]);
            },
            OP_LOAD if w.len() >= 4 && chains.contains(&w[3]) => {
                let uint = blocks.values().next().unwrap().uint;
                let scope = constant(uint, SCOPE_DEVICE, &mut declarations, &mut fresh);
                let semantics = constant(uint, 0, &mut declarations, &mut fresh);
                body.push(instruction(OP_ATOMIC_LOAD, &[w[1], w[2], w[3], scope, semantics]));
            },
            _ => body.push(w.to_vec()),
        }
    }
    // (another use of a block's variable: left as it was)
    let chain_ids: BTreeSet<u32> = instructions[first_function..].iter().filter(|w| matches!(op(w), OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN) && w.len() >= 4 && variables.contains_key(&w[3])).map(|w| w[2]).collect();
    let other_use = instructions[first_function..].iter().any(|w| {
        let operands = if untyped(op(w)) { &w[1..] } else if w.len() >= 3 { &w[3..] } else { &w[1..] };
        !matches!(op(w), OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN) && operands.iter().any(|x| variables.contains_key(x))
    });
    if other_use || chain_ids.len() != chains.len() {
        return words.to_vec();
    }
    let first_function = body.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(body.len());
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    if first_function >= body.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/browser/glbridge/vx/naga/src/cubes.rs                                                0000644 0000000 0000000 00000030465 00000000000 017526  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Samples of integer cube images (GLSL's `texture` of an isamplerCube or
//! usamplerCube): WGSL samples only float textures and loads from no cube,
//! so the image becomes a 2D array of its six faces (VX binds a `2d-array`
//! view of the cube for a binding of kind `texture-*-faces`) and each sample
//! a load of the texel the nearest filter takes in the face the direction
//! selects (Vulkan's cube map face selection: the largest magnitude, then
//! s = (sc / |ma| + 1) / 2, t = (tc / |ma| + 1) / 2), clamped to the face, at
//! an explicit lod's level, else 0. This runs after layers.rs (whose size
//! queries of arrays would take the faces for layers). Gathers, and images
//! a function receives as arguments, are left as they were.

use alloc::string::String;
use alloc::vec::Vec;
use naga::{BinaryOperator, Expression, Function, Handle, ImageClass, ImageDimension, ImageQuery, Literal, MathFunction, SampleLevel, Scalar, ScalarKind,
    Span, Type, TypeInner, UnaryOperator, VectorSize};

/// The name a cube made a 2D array gets (lib.rs's kind reads it)
pub const FACES: &str = "vx_faces";

type H = Handle<Expression>;

/// The integer cube image an expression is, if it is a global variable's
fn cube(module: &naga::Module, function: &Function, image: H) -> Option<Handle<naga::GlobalVariable>> {
    let Expression::GlobalVariable(g) = function.expressions[image] else { return None };
    match module.types[module.global_variables[g].ty].inner {
        TypeInner::Image { dim: ImageDimension::Cube, arrayed: false, class: ImageClass::Sampled { kind: ScalarKind::Sint | ScalarKind::Uint, multi: false } } => Some(g),
        _ => None,
    }
}

/// The function's samples of integer cubes made loads; the images it made faces
fn fix(module: &mut naga::Module, function: &mut Function, faces: &mut Vec<Handle<naga::GlobalVariable>>) {
    let samples: Vec<(H, H, H, SampleLevel, Handle<naga::GlobalVariable>)> = function.expressions.iter().filter_map(|(h, e)| match *e {
        Expression::ImageSample { image, coordinate, gather: None, array_index: None, depth_ref: None, level, .. } =>
            cube(module, function, image).map(|g| (h, image, coordinate, level, g)),
        _ => None,
    }).collect();
    if samples.is_empty() {
        return;
    }
    let vec2 = |module: &mut naga::Module, scalar: Scalar| module.types.insert(Type { name: None, inner: TypeInner::Vector { size: VectorSize::Bi, scalar } },
        Span::UNDEFINED);
    let vec2f = vec2(module, Scalar::F32);
    let mut f = function.clone();
    let mut moves = Vec::new();
    for &(h, image, c, level, g) in &samples {
        // (literals before the image's expression, outside of every emit range)
        let mut literal = |f: &mut Function, l: Literal| {
            let e = f.expressions.append(Expression::Literal(l), Span::UNDEFINED);
            moves.push((e, image));
            e
        };
        let zero = literal(&mut f, Literal::F32(0.0));
        let half = literal(&mut f, Literal::F32(0.5));
        let one = literal(&mut f, Literal::F32(1.0));
        let face_literals: Vec<H> = (0..6).map(|i| literal(&mut f, Literal::I32(i))).collect();
        let izero = face_literals[0];
        let ione = face_literals[1];
        let mut list = Vec::new();
        let mut add = |f: &mut Function, e: Expression| {
            let x = f.expressions.append(e, Span::UNDEFINED);
            list.push(x);
            x
        };
        let cx = add(&mut f, Expression::AccessIndex { base: c, index: 0 });
        let cy = add(&mut f, Expression::AccessIndex { base: c, index: 1 });
        let cz = add(&mut f, Expression::AccessIndex { base: c, index: 2 });
        let abs = |f: &mut Function, add: &mut dyn FnMut(&mut Function, Expression) -> H, x: H| add(f, Expression::Math { fun: MathFunction::Abs, arg: x, arg1: None, arg2: None, arg3: None });
        let ax = abs(&mut f, &mut add, cx);
        let ay = abs(&mut f, &mut add, cy);
        let az = abs(&mut f, &mut add, cz);
        let ge = |f: &mut Function, add: &mut dyn FnMut(&mut Function, Expression) -> H, l: H, r: H| add(f, Expression::Binary { op: BinaryOperator::GreaterEqual, left: l, right: r });
        let x_ge_y = ge(&mut f, &mut add, ax, ay);
        let x_ge_z = ge(&mut f, &mut add, ax, az);
        let y_ge_z = ge(&mut f, &mut add, ay, az);
        let x_major = add(&mut f, Expression::Binary { op: BinaryOperator::LogicalAnd, left: x_ge_y, right: x_ge_z });
        let not_x = add(&mut f, Expression::Unary { op: UnaryOperator::LogicalNot, expr: x_major });
        let y_major = add(&mut f, Expression::Binary { op: BinaryOperator::LogicalAnd, left: not_x, right: y_ge_z });
        let px = ge(&mut f, &mut add, cx, zero);
        let py = ge(&mut f, &mut add, cy, zero);
        let pz = ge(&mut f, &mut add, cz, zero);
        let select = |f: &mut Function, add: &mut dyn FnMut(&mut Function, Expression) -> H, condition: H, accept: H, reject: H|
            add(f, Expression::Select { condition, accept, reject });
        let negate = |f: &mut Function, add: &mut dyn FnMut(&mut Function, Expression) -> H, x: H| add(f, Expression::Unary { op: UnaryOperator::Negate, expr: x });
        // the face: +x 0, -x 1, +y 2, -y 3, +z 4, -z 5
        let fx = select(&mut f, &mut add, px, face_literals[0], face_literals[1]);
        let fy = select(&mut f, &mut add, py, face_literals[2], face_literals[3]);
        let fz = select(&mut f, &mut add, pz, face_literals[4], face_literals[5]);
        let fyz = select(&mut f, &mut add, y_major, fy, fz);
        let face = select(&mut f, &mut add, x_major, fx, fyz);
        // sc, tc and ma of each axis
        let ncx = negate(&mut f, &mut add, cx);
        let ncy = negate(&mut f, &mut add, cy);
        let ncz = negate(&mut f, &mut add, cz);
        let scx = select(&mut f, &mut add, px, ncz, cz);
        let scz = select(&mut f, &mut add, pz, cx, ncx);
        let tcy = select(&mut f, &mut add, py, cz, ncz);
        let syz = select(&mut f, &mut add, y_major, cx, scz);
        let sc = select(&mut f, &mut add, x_major, scx, syz);
        let tyz = select(&mut f, &mut add, y_major, tcy, ncy);
        let tc = select(&mut f, &mut add, x_major, ncy, tyz);
        let myz = select(&mut f, &mut add, y_major, ay, az);
        let ma = select(&mut f, &mut add, x_major, ax, myz);
        // the face's coordinates
        let st = add(&mut f, Expression::Compose { ty: vec2f, components: Vec::from([sc, tc]) });
        let ma2 = add(&mut f, Expression::Splat { size: VectorSize::Bi, value: ma });
        let ratio = add(&mut f, Expression::Binary { op: BinaryOperator::Divide, left: st, right: ma2 });
        let one2 = add(&mut f, Expression::Splat { size: VectorSize::Bi, value: one });
        let shifted = add(&mut f, Expression::Binary { op: BinaryOperator::Add, left: ratio, right: one2 });
        let half2 = add(&mut f, Expression::Splat { size: VectorSize::Bi, value: half });
        let uv = add(&mut f, Expression::Binary { op: BinaryOperator::Multiply, left: shifted, right: half2 });
        // the level, the texel: the nearest mip filter's, ceil(λ + 0.5) - 1 within the
        // levels, λ an explicit lod or (a fragment shader's) log2(ρ) of the face
        // coordinate's derivatives in texels at level 0, plus the bias
        let lambda = match level {
            SampleLevel::Exact(l) => Some(l),
            SampleLevel::Auto | SampleLevel::Bias(_) => {
                let size0 = add(&mut f, Expression::ImageQuery { image, query: ImageQuery::Size { level: Some(izero) } });
                let size0f = add(&mut f, Expression::As { expr: size0, kind: ScalarKind::Float, convert: Some(4) });
                let texels = add(&mut f, Expression::Binary { op: BinaryOperator::Multiply, left: uv, right: size0f });
                let dx = add(&mut f, Expression::Derivative { axis: naga::DerivativeAxis::X, ctrl: naga::DerivativeControl::None, expr: texels });
                let dy = add(&mut f, Expression::Derivative { axis: naga::DerivativeAxis::Y, ctrl: naga::DerivativeControl::None, expr: texels });
                let lx = add(&mut f, Expression::Math { fun: MathFunction::Length, arg: dx, arg1: None, arg2: None, arg3: None });
                let ly = add(&mut f, Expression::Math { fun: MathFunction::Length, arg: dy, arg1: None, arg2: None, arg3: None });
                let rho = add(&mut f, Expression::Math { fun: MathFunction::Max, arg: lx, arg1: Some(ly), arg2: None, arg3: None });
                let log = add(&mut f, Expression::Math { fun: MathFunction::Log2, arg: rho, arg1: None, arg2: None, arg3: None });
                Some(match level {
                    SampleLevel::Bias(b) => add(&mut f, Expression::Binary { op: BinaryOperator::Add, left: log, right: b }),
                    _ => log,
                })
            },
            _ => None,
        };
        let lod = match lambda {
            Some(l) => {
                let raised = add(&mut f, Expression::Binary { op: BinaryOperator::Add, left: l, right: half });
                let ceiled = add(&mut f, Expression::Math { fun: MathFunction::Ceil, arg: raised, arg1: None, arg2: None, arg3: None });
                let below = add(&mut f, Expression::Binary { op: BinaryOperator::Subtract, left: ceiled, right: one });
                let whole = add(&mut f, Expression::As { expr: below, kind: ScalarKind::Sint, convert: Some(4) });
                let levels = add(&mut f, Expression::ImageQuery { image, query: ImageQuery::NumLevels });
                let levels_i = add(&mut f, Expression::As { expr: levels, kind: ScalarKind::Sint, convert: Some(4) });
                let last_level = add(&mut f, Expression::Binary { op: BinaryOperator::Subtract, left: levels_i, right: ione });
                add(&mut f, Expression::Math { fun: MathFunction::Clamp, arg: whole, arg1: Some(izero), arg2: Some(last_level), arg3: None })
            },
            _ => izero,
        };
        let size = add(&mut f, Expression::ImageQuery { image, query: ImageQuery::Size { level: Some(lod) } });
        let sizef = add(&mut f, Expression::As { expr: size, kind: ScalarKind::Float, convert: Some(4) });
        let scaled = add(&mut f, Expression::Binary { op: BinaryOperator::Multiply, left: uv, right: sizef });
        let floor = add(&mut f, Expression::Math { fun: MathFunction::Floor, arg: scaled, arg1: None, arg2: None, arg3: None });
        let texel = add(&mut f, Expression::As { expr: floor, kind: ScalarKind::Sint, convert: Some(4) });
        let sizei = add(&mut f, Expression::As { expr: size, kind: ScalarKind::Sint, convert: Some(4) });
        let one_i = add(&mut f, Expression::Splat { size: VectorSize::Bi, value: ione });
        let last = add(&mut f, Expression::Binary { op: BinaryOperator::Subtract, left: sizei, right: one_i });
        let zero_i = add(&mut f, Expression::Splat { size: VectorSize::Bi, value: izero });
        let clamped = add(&mut f, Expression::Math { fun: MathFunction::Clamp, arg: texel, arg1: Some(zero_i), arg2: Some(last), arg3: None });
        for &x in &list {
            moves.push((x, h));
        }
        f.expressions[h] = Expression::ImageLoad { image, coordinate: clamped, array_index: Some(face), sample: None, level: Some(lod) };
        if !faces.contains(&g) {
            faces.push(g);
        }
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
    else {
        faces.retain(|g| !samples.iter().any(|s| s.4 == *g));
    }
}

/// The module's samples of integer cube images made loads from their faces
pub fn lower(module: &mut naga::Module) {
    let mut faces = Vec::new();
    let handles: Vec<Handle<Function>> = module.functions.iter().map(|(h, _)| h).collect();
    for h in handles {
        let mut f = core::mem::take(&mut module.functions[h]);
        fix(module, &mut f, &mut faces);
        module.functions[h] = f;
    }
    for e in 0..module.entry_points.len() {
        let mut f = core::mem::take(&mut module.entry_points[e].function);
        fix(module, &mut f, &mut faces);
        module.entry_points[e].function = f;
    }
    // the images: 2D arrays of the faces
    for g in faces {
        let TypeInner::Image { class, .. } = module.types[module.global_variables[g].ty].inner else { continue };
        let ty = module.types.insert(Type { name: None, inner: TypeInner::Image { dim: ImageDimension::D2, arrayed: true, class } }, Span::UNDEFINED);
        let var = &mut module.global_variables[g];
        var.ty = ty;
        var.name = Some(String::from(FACES));
    }
}
                                                                                                                                                                                                           source/v64/src/browser/glbridge/vx/naga/src/depth.rs                                                0000644 0000000 0000000 00000016722 00000000000 017531  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Depth for what WebGPU's pipelines and viewports cannot do:
//! - a fragment shader writing depth in a pipeline with no depth attachment
//!   (Vulkan ignores the write, WebGPU refuses the pipeline): its FragDepth
//!   output dropped (`drop_frag_depth`);
//! - a viewport whose minDepth is greater than its maxDepth (GL's
//!   glDepthRangef(1, 0): Vulkan maps depth through it reversed, WebGPU's
//!   viewports cannot): the vertex shader's position z becomes w - z
//!   (`reverse_depth`) and VX swaps the viewport's depths, the same window
//!   depth;
//! - GL's clip space (the GLES host's shaders, docs/gles3-plan.md): depth
//!   from -w to w, WebGPU's from 0 to w: z becomes (z + w) / 2 (`gl_depth`).

use alloc::vec::Vec;
use naga::{Binding, BinaryOperator, Block, BuiltIn, Expression, Handle, ShaderStage, Span, Statement, Type, TypeInner};

/// The fragment entry points' FragDepth outputs dropped
pub fn drop_frag_depth(module: &mut naga::Module) {
    let frag_depth = |m: &naga::StructMember| matches!(m.binding, Some(Binding::BuiltIn(BuiltIn::FragDepth)));
    for ep in module.entry_points.iter_mut() {
        if ep.stage != ShaderStage::Fragment {
            continue;
        }
        let Some(result) = ep.function.result.clone() else { continue };
        if matches!(result.binding, Some(Binding::BuiltIn(BuiltIn::FragDepth))) {
            // (depth its only output: none)
            ep.function.result = None;
            none_returns(&mut ep.function.body);
            continue;
        }
        let (members, span) = match &module.types[result.ty].inner {
            TypeInner::Struct { members, span } => (members.clone(), *span),
            _ => continue,
        };
        let keep: Vec<bool> = members.iter().map(|m| !frag_depth(m)).collect();
        if keep.iter().all(|k| *k) {
            continue;
        }
        let kept = members.into_iter().zip(&keep).filter(|(_, k)| **k).map(|(m, _)| m).collect();
        let new = module.types.insert(Type { name: None, inner: TypeInner::Struct { members: kept, span } }, Span::UNDEFINED);
        crate::retype(&mut ep.function, result.ty, new, Some(&keep));
    }
}

fn none_returns(block: &mut Block) {
    for s in block.iter_mut() {
        match s {
            Statement::Return { value } => *value = None,
            Statement::Block(b) => none_returns(b),
            Statement::If { accept, reject, .. } => {
                none_returns(accept);
                none_returns(reject);
            },
            Statement::Loop { body, continuing, .. } => {
                none_returns(body);
                none_returns(continuing);
            },
            Statement::Switch { cases, .. } => cases.iter_mut().for_each(|c| none_returns(&mut c.body)),
            _ => {},
        }
    }
}

/// The vertex entry points' position z made w - z on return
pub fn reverse_depth(module: &mut naga::Module) {
    position_z(module, false);
}

/// The vertex entry points' position z made (z + w) / 2 on return (GL's clip space)
pub fn gl_depth(module: &mut naga::Module) {
    position_z(module, true);
}

fn position_z(module: &mut naga::Module, gl: bool) {
    for e in 0..module.entry_points.len() {
        if module.entry_points[e].stage != ShaderStage::Vertex {
            continue;
        }
        let Some(result) = module.entry_points[e].function.result.clone() else { continue };
        // (the position alone: the result itself, index usize::MAX)
        let (index, position_ty) = match module.types[result.ty].inner {
            TypeInner::Struct { ref members, .. } => {
                let Some(index) = members.iter().position(|m| matches!(m.binding, Some(Binding::BuiltIn(BuiltIn::Position { .. })))) else { continue };
                (index, members[index].ty)
            },
            _ if matches!(result.binding, Some(Binding::BuiltIn(BuiltIn::Position { .. }))) => (usize::MAX, result.ty),
            _ => continue,
        };
        let f = &mut module.entry_points[e].function;
        // (a literal is never emitted: before the returns' new expressions)
        let half = if gl { Some(f.expressions.append(Expression::Literal(naga::Literal::F32(0.5)), Span::UNDEFINED)) } else { None };
        reverse_returns(&mut f.body, &mut f.expressions, result.ty, index, position_ty, half);
    }
}

fn reverse_returns(block: &mut Block, expressions: &mut naga::Arena<Expression>, ty: Handle<Type>, index: usize, position_ty: Handle<Type>,
    half: Option<Handle<Expression>>) {
    let mut i = 0;
    while i < block.len() {
        let mut insert = None;
        match &mut block[i] {
            Statement::Return { value: Some(value) } => {
                // (naga's wrapper returns a compose of the outputs, or the position alone)
                let members = match expressions[*value] {
                    _ if index == usize::MAX => Vec::from([*value]),
                    Expression::Compose { ref components, .. } if components.len() > index => components.clone(),
                    _ => {
                        i += 1;
                        continue;
                    },
                };
                let first = expressions.len();
                let p = members[if index == usize::MAX { 0 } else { index }];
                let xyzw: Vec<Handle<Expression>> = (0..4).map(|k| expressions.append(Expression::AccessIndex { base: p, index: k }, Span::UNDEFINED)).collect();
                let z = match half {
                    Some(half) => {
                        let sum = expressions.append(Expression::Binary { op: BinaryOperator::Add, left: xyzw[2], right: xyzw[3] }, Span::UNDEFINED);
                        expressions.append(Expression::Binary { op: BinaryOperator::Multiply, left: sum, right: half }, Span::UNDEFINED)
                    },
                    None => expressions.append(Expression::Binary { op: BinaryOperator::Subtract, left: xyzw[3], right: xyzw[2] }, Span::UNDEFINED),
                };
                let reversed = expressions.append(Expression::Compose { ty: position_ty, components: Vec::from([xyzw[0], xyzw[1], z, xyzw[3]]) },
                    Span::UNDEFINED);
                if index == usize::MAX {
                    *value = reversed;
                } else {
                    let parts: Vec<Handle<Expression>> = members.iter().enumerate().map(|(m, &c)| if m == index { reversed } else { c }).collect();
                    *value = expressions.append(Expression::Compose { ty, components: parts }, Span::UNDEFINED);
                }
                insert = Some(Statement::Emit(expressions.range_from(first)));
            },
            Statement::Block(b) => reverse_returns(b, expressions, ty, index, position_ty, half),
            Statement::If { accept, reject, .. } => {
                reverse_returns(accept, expressions, ty, index, position_ty, half);
                reverse_returns(reject, expressions, ty, index, position_ty, half);
            },
            Statement::Loop { body, continuing, .. } => {
                reverse_returns(body, expressions, ty, index, position_ty, half);
                reverse_returns(continuing, expressions, ty, index, position_ty, half);
            },
            Statement::Switch { cases, .. } => {
                for case in cases.iter_mut() {
                    reverse_returns(&mut case.body, expressions, ty, index, position_ty, half);
                }
            },
            _ => {},
        }
        if let Some(emit) = insert {
            block.splice(i..i, Block::from_vec(Vec::from([emit])));
            i += 1;
        }
        i += 1;
    }
}

                                              source/v64/src/browser/glbridge/vx/naga/src/fetches.rs                                              0000644 0000000 0000000 00000013643 00000000000 020045  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Offsets of fetches (GLSL's `texelFetchOffset`, OpImageFetch with a
//! ConstOffset or Offset operand): naga's front end reads a fetch's Lod and
//! Sample operands only and drops the rest, and WGSL's `textureLoad` takes no
//! offset. The offset is added to the coordinate's spatial components (an
//! array's layer kept), and the operand goes.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_TYPE_VECTOR: u32 = 23;
const OP_FUNCTION: u32 = 54;
const OP_COMPOSITE_CONSTRUCT: u32 = 80;
const OP_COMPOSITE_EXTRACT: u32 = 81;
const OP_IMAGE_FETCH: u32 = 95;
const OP_I_ADD: u32 = 128;
const OPERANDS_CONST_OFFSET: u32 = 0x8;
const OPERANDS_OFFSET: u32 = 0x10;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The image operands' words each bit takes, in their order
fn operand_words(bit: u32) -> usize {
    match bit {
        0x4 => 2, // Grad
        0x40 => 1, // Sample
        0x80 => 1, // MinLod
        0x100..=0x800 => 0, // memory model bits
        _ => 1,
    }
}

/// The module with its fetches' offsets added to their coordinates, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let fetch_with_offset = |w: &[u32]| op(w) == OP_IMAGE_FETCH && w.len() >= 6 && w[5] & (OPERANDS_CONST_OFFSET | OPERANDS_OFFSET) != 0;
    if !instructions.iter().any(|w| fetch_with_offset(w)) {
        return words.to_vec();
    }
    // the types of values (results and constants), and vector types
    let mut type_of: BTreeMap<u32, u32> = BTreeMap::new();
    let mut vectors: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    // (the instructions of no result type in a function: debug, stores, copies, barriers, control flow)
    let untyped = |o: u32| matches!(o, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317);
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    for (i, w) in instructions.iter().enumerate() {
        let o = op(w);
        if o == OP_TYPE_VECTOR && w.len() >= 4 {
            vectors.insert(w[1], (w[2], w[3]));
        }
        else if w.len() >= 3 && ((41..=52).contains(&o) || o == 59 || i >= first_function && !untyped(o)) {
            type_of.insert(w[2], w[1]);
        }
    }
    let mut bound = words[3];
    let mut out = words[..5].to_vec();
    for (i, w) in instructions.iter().enumerate() {
        if i < first_function || !fetch_with_offset(w) {
            out.extend_from_slice(w);
            continue;
        }
        let (rt, result, image, coordinate, mask) = (w[1], w[2], w[3], w[4], w[5]);
        // the operands: the offset's taken out
        let mut kept = Vec::new();
        let mut offset = None;
        let mut at = 6;
        let mut bits = mask;
        let mut whole = true;
        while bits != 0 {
            let bit = 1 << bits.trailing_zeros();
            let n = operand_words(bit);
            if at + n > w.len() {
                whole = false;
                break;
            }
            if bit == OPERANDS_CONST_OFFSET || bit == OPERANDS_OFFSET {
                offset = Some(w[at]);
            }
            else {
                kept.extend_from_slice(&w[at..at + n]);
            }
            at += n;
            bits ^= bit;
        }
        let (true, Some(offset), Some(&coordinate_ty), Some(&offset_ty)) = (whole, offset, type_of.get(&coordinate), offset.and_then(|o| type_of.get(&o))) else {
            out.extend_from_slice(w);
            continue;
        };
        let coordinate_n = vectors.get(&coordinate_ty).map_or(1, |v| v.1);
        let offset_n = vectors.get(&offset_ty).map_or(1, |v| v.1);
        let scalar = vectors.get(&coordinate_ty).map_or(coordinate_ty, |v| v.0);
        // (an array's layer: the offset made as long, a zero more)
        let full_offset = if offset_n == coordinate_n { offset } else {
            let mut parts = Vec::new();
            for k in 0..offset_n {
                let id = bound;
                bound += 1;
                if offset_n == 1 {
                    parts.push(offset);
                    break;
                }
                out.extend_from_slice(&instruction(OP_COMPOSITE_EXTRACT, &[scalar, id, offset, k]));
                parts.push(id);
            }
            // a zero of the coordinate's scalar type: the coordinate's own last component minus itself
            let (last, zero) = (bound, bound + 1);
            bound += 2;
            out.extend_from_slice(&instruction(OP_COMPOSITE_EXTRACT, &[scalar, last, coordinate, coordinate_n - 1]));
            out.extend_from_slice(&instruction(130, &[scalar, zero, last, last]));
            while (parts.len() as u32) < coordinate_n {
                parts.push(zero);
            }
            let id = bound;
            bound += 1;
            let mut c = Vec::from([coordinate_ty, id]);
            c.extend(parts);
            out.extend_from_slice(&instruction(OP_COMPOSITE_CONSTRUCT, &c));
            id
        };
        let moved = bound;
        bound += 1;
        out.extend_from_slice(&instruction(OP_I_ADD, &[coordinate_ty, moved, coordinate, full_offset]));
        let rest = mask & !(OPERANDS_CONST_OFFSET | OPERANDS_OFFSET);
        let mut operands = Vec::from([rt, result, image, moved]);
        if rest != 0 {
            operands.push(rest);
            operands.extend(kept);
        }
        out.extend_from_slice(&instruction(OP_IMAGE_FETCH, &operands));
    }
    out[3] = bound;
    out
}
                                                                                             source/v64/src/browser/glbridge/vx/naga/src/geometry.rs                                             0000644 0000000 0000000 00000065736 00000000000 020271  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Geometry shaders (GLES 3.2, docs/gles3-plan.md L6) as compute shaders:
//! WebGPU has no geometry stage. A draw with one runs its vertex shader as a
//! compute shader first (xfb.rs, every output captured: a record a vertex),
//! then its geometry shader once an input primitive and invocation, here:
//! the SPIR-V made a compute shader's (`prepare`: the inputs and outputs
//! private variables of names this module knows, EmitVertex and
//! EndPrimitive calls of functions it writes), the emitted vertices a list
//! of primitives (a strip's made a list's, GL's provoking vertex, the last,
//! first as WebGPU's flat inputs take it) in a buffer the draw reads as its
//! vertex buffer through a vertex shader that passes them on (the caller's,
//! of `outputs`).
//!
//! A record is u32 words: the position at 0, the point size at 4, gl_Layer
//! at 5, gl_PrimitiveID at 6, location l's components at 8 + 4l. The list
//! has `list` records an invocation; those it does not fill get a position
//! outside the clip volume (2, 2, 2, 1): nothing is drawn of them.
//!
//! The resources, in the group the caller gives:
//! - 960: the parameters (uniform, VxGsParams): the input primitives (all
//!   instances'), the vertex records' stride in words, the primitives an
//!   instance (gl_PrimitiveIDIn counts from 0 in each);
//! - 961: the vertex records (read-only storage);
//! - 962: each input primitive's vertices' record indices (read-only);
//! - 963: the emitted vertices (storage, `max_vertices` records an invocation);
//! - 964: the list (storage).

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use naga::{ScalarKind, TypeInner};

const OP_NAME: u32 = 5;
const OP_MEMBER_NAME: u32 = 6;
const OP_ENTRY_POINT: u32 = 15;
const OP_EXECUTION_MODE: u32 = 16;
const OP_CAPABILITY: u32 = 17;
const OP_TYPE_VOID: u32 = 19;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_TYPE_FUNCTION: u32 = 33;
const OP_FUNCTION: u32 = 54;
const OP_FUNCTION_END: u32 = 56;
const OP_FUNCTION_CALL: u32 = 57;
const OP_VARIABLE: u32 = 59;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const OP_EMIT_VERTEX: u32 = 218;
const OP_END_PRIMITIVE: u32 = 219;
const OP_LABEL: u32 = 248;
const OP_RETURN: u32 = 253;

const MODEL_GEOMETRY: u32 = 3;
const MODEL_GL_COMPUTE: u32 = 5;
const STORAGE_INPUT: u32 = 1;
const STORAGE_OUTPUT: u32 = 3;
const STORAGE_PRIVATE: u32 = 6;

const DECORATION_RELAXED_PRECISION: u32 = 0;
const DECORATION_BLOCK: u32 = 2;
const DECORATION_BUILTIN: u32 = 11;
const DECORATION_NO_PERSPECTIVE: u32 = 13;
const DECORATION_FLAT: u32 = 14;
const DECORATION_CENTROID: u32 = 16;
const DECORATION_SAMPLE: u32 = 17;
const DECORATION_LOCATION: u32 = 30;

const BUILTIN_POSITION: u32 = 0;
const BUILTIN_POINT_SIZE: u32 = 1;
const BUILTIN_PRIMITIVE_ID: u32 = 7;
const BUILTIN_INVOCATION_ID: u32 = 8;
const BUILTIN_LAYER: u32 = 9;

/// The record's words: position, point size, layer, primitive id, then location l at LOCATIONS + 4l
const LAYER_WORD: u32 = 5;
const PRIMITIVE_WORD: u32 = 6;
const LOCATIONS: u32 = 8;

/// The names the converted variables and functions get (not ending in a
/// digit: naga's namer would add an underscore)
pub const MAIN: &str = "vx_gsmain";
const EMIT: &str = "vx_emit";
const END: &str = "vx_end";
fn input_name(location: u32) -> String { format!("vx_gi{}x", location) }
fn output_name(location: u32) -> String { format!("vx_go{}x", location) }
fn builtin_name(builtin: u32, output: bool) -> String { format!("vx_gb{}{}x", builtin, if output { "o" } else { "i" }) }
const PER_VERTEX_IN: &str = "vx_gpvix";
const PER_VERTEX_OUT: &str = "vx_gpvox";
pub(crate) fn member_name(index: usize) -> String { format!("vx_m{}x", index) }

/// What `prepare` read of the geometry shader
#[derive(Clone, Debug, Default)]
pub struct Geometry {
    /// vertices an input primitive: 1, 2, 4 (lines with adjacency), 3, 6
    pub input_vertices: u32,
    /// 0 points, 1 line strip, 2 triangle strip
    pub output: u32,
    pub max_vertices: u32,
    pub invocations: u32,
    /// the outputs' interpolation by location: 1 flat, 2 no perspective, 4 centroid, 8 sample
    interpolation: BTreeMap<u32, u32>,
    /// the per-vertex blocks' members' built-ins (gl_in's, the output's)
    in_members: Vec<u32>,
    out_members: Vec<u32>,
    /// the inputs' and outputs' locations, the built-ins (built-in, output)
    inputs: Vec<u32>,
    outputs: Vec<u32>,
    builtins: Vec<(u32, bool)>,
}

pub(crate) fn string_words(text: &str) -> Vec<u32> {
    let mut bytes = text.as_bytes().to_vec();
    bytes.push(0);
    while bytes.len() % 4 != 0 {
        bytes.push(0);
    }
    bytes.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
}

pub(crate) fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The words of a literal string at the start of `w`: how many
pub(crate) fn string_length(w: &[u32]) -> usize {
    w.iter().position(|word| word.to_le_bytes().contains(&0)).map_or(w.len(), |i| i + 1)
}

/// The geometry shader's SPIR-V as a compute shader's (see above), and what it read
pub fn prepare(words: &[u32]) -> Result<(Vec<u32>, Geometry), String> {
    if words.len() < 5 {
        return Err(String::from("not SPIR-V"));
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return Err(String::from("SPIR-V: a malformed instruction"));
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let mut entry = None;
    let mut void = None;
    let mut void_function = None;
    let mut pointers: BTreeMap<u32, u32> = BTreeMap::new();
    let mut arrays: BTreeMap<u32, u32> = BTreeMap::new();
    let mut structs: BTreeMap<u32, usize> = BTreeMap::new();
    let mut variables: Vec<(u32, u32, bool)> = Vec::new();
    let mut decorations: BTreeMap<u32, Vec<(u32, u32)>> = BTreeMap::new();
    let mut members: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new();
    for w in &instructions {
        match op(w) {
            OP_ENTRY_POINT if w.len() >= 3 && w[1] == MODEL_GEOMETRY && entry.is_none() => entry = Some(w[2]),
            OP_TYPE_VOID if w.len() >= 2 => void = Some(w[1]),
            OP_TYPE_FUNCTION if w.len() == 3 && Some(w[2]) == void => void_function = Some(w[1]),
            OP_TYPE_POINTER if w.len() >= 4 => {
                pointers.insert(w[1], w[3]);
            },
            OP_TYPE_ARRAY if w.len() >= 3 => {
                arrays.insert(w[1], w[2]);
            },
            OP_TYPE_STRUCT if w.len() >= 2 => {
                structs.insert(w[1], w.len() - 2);
            },
            OP_VARIABLE if w.len() >= 4 && (w[3] == STORAGE_INPUT || w[3] == STORAGE_OUTPUT) => variables.push((w[2], w[1], w[3] == STORAGE_OUTPUT)),
            OP_DECORATE if w.len() >= 3 => decorations.entry(w[1]).or_default().push((w[2], w.get(3).copied().unwrap_or(0))),
            OP_MEMBER_DECORATE if w.len() >= 4 => members.entry((w[1], w[2])).or_default().push((w[3], w.get(4).copied().unwrap_or(0))),
            _ => {},
        }
    }
    let entry = entry.ok_or("no geometry entry point")?;
    let void = void.ok_or("no void type")?;
    let void_function = void_function.ok_or("no void function type")?;
    let find = |list: Option<&Vec<(u32, u32)>>, d: u32| list.and_then(|l| l.iter().find(|(k, _)| *k == d).map(|(_, v)| *v));

    // each variable's role and name; the blocks of the interface
    let mut g = Geometry { invocations: 1, ..Geometry::default() };
    let mut names: BTreeMap<u32, String> = BTreeMap::new();
    let mut io_structs: BTreeSet<u32> = BTreeSet::new();
    for &(var, pointer, output) in &variables {
        let mut ty = pointers.get(&pointer).copied().unwrap_or(0);
        while let Some(&element) = arrays.get(&ty) {
            ty = element;
        }
        if structs.contains_key(&ty) {
            io_structs.insert(ty);
        }
        let decorated = decorations.get(&var);
        let name = if let Some(builtin) = find(decorated, DECORATION_BUILTIN) {
            g.builtins.push((builtin, output));
            builtin_name(builtin, output)
        }
        else if let Some(&count) = structs.get(&ty).filter(|_| (0..structs[&ty] as u32).any(|m| find(members.get(&(ty, m)), DECORATION_BUILTIN).is_some())) {
            let list: Vec<u32> = (0..count as u32).map(|m| find(members.get(&(ty, m)), DECORATION_BUILTIN).unwrap_or(u32::MAX)).collect();
            if output {
                g.out_members = list;
                String::from(PER_VERTEX_OUT)
            }
            else {
                g.in_members = list;
                String::from(PER_VERTEX_IN)
            }
        }
        else {
            let location = find(decorated, DECORATION_LOCATION).or_else(|| find(members.get(&(ty, 0)), DECORATION_LOCATION))
                .ok_or("an input or output of no location")?;
            if output {
                let mut flags = 0;
                for (d, bit) in [(DECORATION_FLAT, 1), (DECORATION_NO_PERSPECTIVE, 2), (DECORATION_CENTROID, 4), (DECORATION_SAMPLE, 8)] {
                    if decorated.is_some_and(|l| l.iter().any(|(k, _)| *k == d)) {
                        flags |= bit;
                    }
                }
                g.interpolation.insert(location, flags);
                g.outputs.push(location);
                output_name(location)
            }
            else {
                g.inputs.push(location);
                input_name(location)
            }
        };
        names.insert(var, name);
    }
    let converted: BTreeSet<u32> = variables.iter().map(|v| v.0).collect();

    let mut bound = words[3];
    let mut fresh = || {
        let id = bound;
        bound += 1;
        id
    };
    let emit = fresh();
    let end = fresh();
    let mut out = words[..5].to_vec();
    let mut named_stubs = false;
    for w in &instructions {
        match op(w) {
            OP_CAPABILITY if w.len() >= 2 && matches!(w[1], 2 | 24 | 54) => continue,
            OP_ENTRY_POINT if w.len() >= 3 && w[2] == entry => {
                let n = string_length(&w[3..]);
                let mut operands = vec![MODEL_GL_COMPUTE, entry];
                operands.extend_from_slice(&w[3..3 + n]);
                out.extend(instruction(OP_ENTRY_POINT, &operands));
                // (LocalSize 1 1 1: naga wants a compute shader's size; the module's own entry point goes, vx_geometry calls its function)
                out.extend(instruction(OP_EXECUTION_MODE, &[entry, 17, 1, 1, 1]));
                continue;
            },
            OP_EXECUTION_MODE if w.len() >= 3 && w[1] == entry => {
                match w[2] {
                    0 => g.invocations = w.get(3).copied().unwrap_or(1).max(1),
                    19 => g.input_vertices = 1,
                    20 => g.input_vertices = 2,
                    21 => g.input_vertices = 4,
                    22 => g.input_vertices = 3,
                    23 => g.input_vertices = 6,
                    26 => g.max_vertices = w.get(3).copied().unwrap_or(0),
                    27 => g.output = 0,
                    28 => g.output = 1,
                    29 => g.output = 2,
                    _ => {
                        out.extend_from_slice(w);
                    },
                }
                continue;
            },
            OP_NAME if w.len() >= 2 => {
                if let Some(name) = names.get(&w[1]) {
                    let mut operands = vec![w[1]];
                    operands.extend(string_words(name));
                    out.extend(instruction(OP_NAME, &operands));
                    continue;
                }
                if w[1] == entry {
                    let mut operands = vec![entry];
                    operands.extend(string_words(MAIN));
                    out.extend(instruction(OP_NAME, &operands));
                    for (id, name) in [(emit, EMIT), (end, END)] {
                        let mut operands = vec![id];
                        operands.extend(string_words(name));
                        out.extend(instruction(OP_NAME, &operands));
                    }
                    named_stubs = true;
                    continue;
                }
            },
            OP_MEMBER_NAME if w.len() >= 3 && io_structs.contains(&w[1]) => {
                let mut operands = vec![w[1], w[2]];
                operands.extend(string_words(&member_name(w[2] as usize)));
                out.extend(instruction(OP_MEMBER_NAME, &operands));
                continue;
            },
            OP_DECORATE if w.len() >= 3 && (converted.contains(&w[1]) && w[2] != DECORATION_RELAXED_PRECISION
                || io_structs.contains(&w[1]) && w[2] == DECORATION_BLOCK) => continue,
            OP_MEMBER_DECORATE if w.len() >= 4 && io_structs.contains(&w[1]) && w[3] != DECORATION_RELAXED_PRECISION => continue,
            OP_TYPE_POINTER if w.len() >= 4 && (w[2] == STORAGE_INPUT || w[2] == STORAGE_OUTPUT) => {
                out.extend(instruction(OP_TYPE_POINTER, &[w[1], STORAGE_PRIVATE, w[3]]));
                continue;
            },
            OP_VARIABLE if w.len() >= 4 && converted.contains(&w[2]) => {
                let mut operands = vec![w[1], w[2], STORAGE_PRIVATE];
                operands.extend_from_slice(&w[4..]);
                out.extend(instruction(OP_VARIABLE, &operands));
                continue;
            },
            OP_EMIT_VERTEX | OP_END_PRIMITIVE => {
                let callee = if op(w) == OP_EMIT_VERTEX { emit } else { end };
                let result = fresh();
                out.extend(instruction(OP_FUNCTION_CALL, &[void, result, callee]));
                continue;
            },
            _ => {},
        }
        out.extend_from_slice(w);
    }
    if g.input_vertices == 0 || g.max_vertices == 0 {
        return Err(String::from("a geometry shader without its input or output layout"));
    }
    if !named_stubs {
        return Err(String::from("the geometry shader's entry point has no name"));
    }
    // the functions EmitVertex and EndPrimitive call: empty, their WGSL written after naga's (finish)
    for callee in [emit, end] {
        let label = fresh();
        out.extend(instruction(OP_FUNCTION, &[void, callee, 0, void_function]));
        out.extend(instruction(OP_LABEL, &[label]));
        out.extend(instruction(OP_RETURN, &[]));
        out.extend(instruction(OP_FUNCTION_END, &[]));
    }
    out[3] = bound;
    Ok((out, g))
}

/// A scalar or vector of an input or output, at its location: its WGSL
/// access (from the variable's), kind and components
pub(crate) struct Leaf {
    pub(crate) access: String,
    pub(crate) location: u32,
    pub(crate) kind: ScalarKind,
    pub(crate) components: u32,
}

/// The leaves of a value of type `ty` (`access`), from `location`; how many locations they take
pub(crate) fn leaves(module: &naga::Module, ty: naga::Handle<naga::Type>, access: &str, location: u32, out: &mut Vec<Leaf>) -> Result<u32, String> {
    match module.types[ty].inner {
        TypeInner::Scalar(s) => {
            out.push(Leaf { access: String::from(access), location, kind: s.kind, components: 1 });
            Ok(1)
        },
        TypeInner::Vector { size, scalar } => {
            out.push(Leaf { access: String::from(access), location, kind: scalar.kind, components: size as u32 });
            Ok(1)
        },
        TypeInner::Matrix { columns, rows, .. } => {
            for c in 0..columns as u32 {
                out.push(Leaf { access: format!("{}[{}]", access, c), location: location + c, kind: ScalarKind::Float, components: rows as u32 });
            }
            Ok(columns as u32)
        },
        TypeInner::Array { base, size: naga::ArraySize::Constant(n), .. } => {
            let mut used = 0;
            for e in 0..n.get() {
                used += leaves(module, base, &format!("{}[{}]", access, e), location + used, out)?;
            }
            Ok(used)
        },
        TypeInner::Struct { ref members, .. } => {
            let mut used = 0;
            for (k, m) in members.iter().enumerate() {
                used += leaves(module, m.ty, &format!("{}.{}", access, member_name(k)), location + used, out)?;
            }
            Ok(used)
        },
        _ => Err(String::from("an input or output of a type not done")),
    }
}

fn scalar_name(kind: ScalarKind) -> &'static str {
    match kind {
        ScalarKind::Sint => "i32",
        ScalarKind::Uint => "u32",
        ScalarKind::Bool => "bool",
        _ => "f32",
    }
}

/// A leaf's value read from words `base + k` (a WGSL expression) of `buffer`
pub(crate) fn load_from(buffer: &str, kind: ScalarKind, components: u32, base: &str) -> String {
    let one = |k: u32| {
        let word = format!("{}[{} + {}u]", buffer, base, k);
        match kind {
            ScalarKind::Sint => format!("bitcast<i32>({})", word),
            ScalarKind::Uint => word,
            ScalarKind::Bool => format!("({} != 0u)", word),
            _ => format!("bitcast<f32>({})", word),
        }
    };
    if components == 1 {
        return one(0);
    }
    let parts: Vec<String> = (0..components).map(one).collect();
    format!("vec{}<{}>({})", components, scalar_name(kind), parts.join(", "))
}

fn load(kind: ScalarKind, components: u32, base: &str) -> String { load_from("vx_gs_in", kind, components, base) }

/// A component of a leaf as a word
pub(crate) fn store(kind: ScalarKind, value: &str) -> String {
    match kind {
        ScalarKind::Uint => String::from(value),
        ScalarKind::Bool => format!("select(0u, 1u, {})", value),
        _ => format!("bitcast<u32>({})", value),
    }
}

/// What the caller needs of a translated geometry shader: the WGSL of
/// vx_emit and vx_end (in place of naga's empty ones) and the rest to
/// append, and the JSON of the outputs and layout
pub struct Finished {
    pub emit: String,
    pub end: String,
    pub appended: String,
    pub json: String,
}

/// The module (naga's, of `prepare`'s SPIR-V) without its entry point; the
/// WGSL of the compute shader vx_geometry that runs the shader's function
pub fn finish(module: &mut naga::Module, g: &Geometry, group: u32) -> Result<Finished, String> {
    module.entry_points.clear();
    let global = |name: &str| module.global_variables.iter().find(|(_, v)| v.name.as_deref() == Some(name)).map(|(h, v)| (h, v.ty));
    let n = g.input_vertices;
    let list = match g.output {
        0 => g.max_vertices,
        1 => 2 * g.max_vertices.saturating_sub(1),
        _ => 3 * g.max_vertices.saturating_sub(2),
    }.max(1);

    // the outputs' leaves: the record's stride
    let mut outputs: Vec<Leaf> = Vec::new();
    for &location in &g.outputs {
        let (_, ty) = global(&output_name(location)).ok_or("an output naga left out")?;
        leaves(module, ty, &output_name(location), location, &mut outputs)?;
    }
    let stride = LOCATIONS + 4 * outputs.iter().map(|l| l.location + 1).max().unwrap_or(0);

    // vx_emit: the outputs into the emitted record, then the list's primitive of it
    let mut emit = format!("fn {}() {{\n    if (vx_gs_n >= {}u) {{ return; }}\n    let r = vx_gs_ebase + vx_gs_n * {}u;\n", EMIT, g.max_vertices, stride);
    let mut word = |w: u32, value: String, out: &mut String| out.push_str(&format!("    vx_gs_emit[r + {}u] = {};\n", w, value));
    let vector4 = |access: &str, out: &mut String, word: &mut dyn FnMut(u32, String, &mut String)| {
        for k in 0..4 {
            word(k, store(ScalarKind::Float, &format!("{}[{}]", access, k)), out);
        }
    };
    if let Some((_, _)) = global(PER_VERTEX_OUT) {
        for (k, &builtin) in g.out_members.iter().enumerate() {
            let access = format!("{}.{}", PER_VERTEX_OUT, member_name(k));
            match builtin {
                BUILTIN_POSITION => vector4(&access, &mut emit, &mut word),
                BUILTIN_POINT_SIZE => word(4, store(ScalarKind::Float, &access), &mut emit),
                _ => {},
            }
        }
    }
    for &(builtin, output) in &g.builtins {
        if !output || global(&builtin_name(builtin, true)).is_none() {
            continue;
        }
        let access = builtin_name(builtin, true);
        match builtin {
            BUILTIN_POSITION => vector4(&access, &mut emit, &mut word),
            BUILTIN_POINT_SIZE => word(4, store(ScalarKind::Float, &access), &mut emit),
            BUILTIN_LAYER => word(LAYER_WORD, store(ScalarKind::Sint, &access), &mut emit),
            BUILTIN_PRIMITIVE_ID => word(PRIMITIVE_WORD, store(ScalarKind::Sint, &access), &mut emit),
            _ => {},
        }
    }
    for leaf in &outputs {
        for k in 0..leaf.components {
            let value = if leaf.components == 1 { leaf.access.clone() } else { format!("{}[{}]", leaf.access, k) };
            word(LOCATIONS + 4 * leaf.location + k, store(leaf.kind, &value), &mut emit);
        }
    }
    emit.push_str("    vx_gs_n = vx_gs_n + 1u;\n    vx_gs_strip = vx_gs_strip + 1u;\n    let k = vx_gs_n - 1u;\n");
    emit.push_str(match g.output {
        0 => "    vx_gs_copy(k);\n",
        1 => "    if (vx_gs_strip >= 2u) { vx_gs_copy(k); vx_gs_copy(k - 1u); }\n",
        _ => "    if (vx_gs_strip >= 3u) {\n        vx_gs_copy(k);\n        if (((vx_gs_strip - 3u) & 1u) == 0u) { vx_gs_copy(k - 2u); vx_gs_copy(k - 1u); }\n        \
            else { vx_gs_copy(k - 1u); vx_gs_copy(k - 2u); }\n    }\n",
    });
    emit.push_str("}\n");
    let end = format!("fn {}() {{\n    vx_gs_strip = 0u;\n}}\n", END);

    let mut wgsl = String::new();
    wgsl.push_str("\nstruct VxGsParams { prims: u32, in_stride: u32, prims_per_instance: u32, pad: u32 }\n");
    wgsl.push_str(&format!("@group({g}) @binding(960) var<uniform> vx_gs_p: VxGsParams;\n\
        @group({g}) @binding(961) var<storage, read> vx_gs_in: array<u32>;\n\
        @group({g}) @binding(962) var<storage, read> vx_gs_ids: array<u32>;\n\
        @group({g}) @binding(963) var<storage, read_write> vx_gs_emit: array<u32>;\n\
        @group({g}) @binding(964) var<storage, read_write> vx_gs_out: array<u32>;\n", g = group));
    wgsl.push_str("var<private> vx_gs_n: u32;\nvar<private> vx_gs_strip: u32;\nvar<private> vx_gs_listed: u32;\n\
        var<private> vx_gs_ebase: u32;\nvar<private> vx_gs_lbase: u32;\n");
    // (\"from\" is a reserved word of WGSL's)
    wgsl.push_str(&format!("fn vx_gs_copy(k: u32) {{\n    let vx_from = vx_gs_ebase + k * {s}u;\n    let vx_to = vx_gs_lbase + vx_gs_listed * {s}u;\n    \
        for (var w = 0u; w < {s}u; w = w + 1u) {{ vx_gs_out[vx_to + w] = vx_gs_emit[vx_from + w]; }}\n    vx_gs_listed = vx_gs_listed + 1u;\n}}\n", s = stride));
    wgsl.push_str(&format!("@compute @workgroup_size(64) fn vx_geometry(@builtin(global_invocation_id) id: vec3<u32>) {{\n    \
        let n = id.x;\n    if (n >= vx_gs_p.prims * {inv}u) {{ return; }}\n    let prim = n / {inv}u;\n    let inv = n % {inv}u;\n    \
        vx_gs_ebase = n * {maxv}u * {s}u;\n    vx_gs_lbase = n * {list}u * {s}u;\n    vx_gs_n = 0u;\n    vx_gs_strip = 0u;\n    vx_gs_listed = 0u;\n",
        inv = g.invocations, maxv = g.max_vertices, s = stride, list = list));
    // the inputs, from the vertex records
    for i in 0..n {
        wgsl.push_str(&format!("    let r{i} = vx_gs_ids[prim * {n}u + {i}u] * vx_gs_p.in_stride;\n", i = i, n = n));
    }
    if let Some((_, _)) = global(PER_VERTEX_IN) {
        for i in 0..n {
            for (k, &builtin) in g.in_members.iter().enumerate() {
                let access = format!("{}[{}].{}", PER_VERTEX_IN, i, member_name(k));
                match builtin {
                    BUILTIN_POSITION => wgsl.push_str(&format!("    {} = {};\n", access, load(ScalarKind::Float, 4, &format!("r{}", i)))),
                    BUILTIN_POINT_SIZE => wgsl.push_str(&format!("    {} = {};\n", access, load(ScalarKind::Float, 1, &format!("r{} + 4u", i)))),
                    _ => {},
                }
            }
        }
    }
    for &location in &g.inputs {
        let Some((_, ty)) = global(&input_name(location)) else { continue };
        let TypeInner::Array { base, .. } = module.types[ty].inner else { return Err(String::from("a geometry input not an array")) };
        for i in 0..n {
            let mut list = Vec::new();
            leaves(module, base, &format!("{}[{}]", input_name(location), i), location, &mut list)?;
            for leaf in list {
                let at = format!("r{} + {}u", i, LOCATIONS + 4 * leaf.location);
                wgsl.push_str(&format!("    {} = {};\n", leaf.access, load(leaf.kind, leaf.components, &at)));
            }
        }
    }
    for &(builtin, output) in &g.builtins {
        if output || global(&builtin_name(builtin, false)).is_none() {
            continue;
        }
        match builtin {
            BUILTIN_PRIMITIVE_ID => wgsl.push_str(&format!("    {} = i32(prim % vx_gs_p.prims_per_instance);\n", builtin_name(builtin, false))),
            BUILTIN_INVOCATION_ID => wgsl.push_str(&format!("    {} = i32(inv);\n", builtin_name(builtin, false))),
            _ => return Err(format!("a geometry shader's built-in input {} not done", builtin)),
        }
    }
    wgsl.push_str(&format!("    {}();\n", MAIN));
    // (the list's slots left: outside the clip volume)
    wgsl.push_str(&format!("    for (var k = vx_gs_listed; k < {list}u; k = k + 1u) {{\n        let vx_to = vx_gs_lbase + k * {s}u;\n        \
        vx_gs_out[vx_to] = 0x40000000u;\n        vx_gs_out[vx_to + 1u] = 0x40000000u;\n        vx_gs_out[vx_to + 2u] = 0x40000000u;\n        \
        vx_gs_out[vx_to + 3u] = 0x3F800000u;\n    }}\n}}\n", list = list, s = stride));

    // the outputs the pass-through vertex shader has: [location, kind, components, interpolation]
    let mut json = format!("{{\"input\":{},\"output\":{},\"max_vertices\":{},\"invocations\":{},\"list\":{},\"stride\":{},\"outputs\":[",
        n, g.output, g.max_vertices, g.invocations, list, stride);
    for (i, leaf) in outputs.iter().enumerate() {
        if i > 0 { json.push(','); }
        let kind = match leaf.kind { ScalarKind::Sint => "i", ScalarKind::Uint => "u", _ => "f" };
        // (the variable's interpolation, by its first location)
        let flags = g.interpolation.range(..=leaf.location).next_back().map_or(0, |(_, f)| *f);
        json.push_str(&format!("[{},\"{}\",{},{}]", leaf.location, kind, leaf.components, flags));
    }
    json.push_str(&format!("],\"layer\":{},\"primitive_id\":{}}}",
        g.builtins.contains(&(BUILTIN_LAYER, true)), g.builtins.contains(&(BUILTIN_PRIMITIVE_ID, true))));
    Ok(Finished { emit, end, appended: wgsl, json })
}

/// naga's WGSL with its empty vx_emit and vx_end replaced by `finished`'s
pub fn replace_stubs(wgsl: &mut String, finished: &Finished) -> Result<(), String> {
    for (name, body) in [(EMIT, &finished.emit), (END, &finished.end)] {
        let head = format!("fn {}() {{", name);
        let start = wgsl.find(&head).ok_or_else(|| format!("naga wrote no {}", name))?;
        let close = wgsl[start..].find("\n}\n").ok_or("an unterminated function")? + start + 3;
        wgsl.replace_range(start..close, body);
    }
    Ok(())
}
                                  source/v64/src/browser/glbridge/vx/naga/src/imagecubes.rs                                           0000644 0000000 0000000 00000010612 00000000000 020521  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! GLSL ES 3.1's cube images (imageCube, an image unit's layered cube):
//! WGSL has no storage cube textures, so each becomes a 2D array of its six
//! faces (VX binds a `2d-array` view of the cube's level). Loads, stores and
//! texel pointers take the same coordinates (x, y, and the face as the
//! layer); a size query, which of an array has the layers too, keeps its
//! first two components.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

const OP_TYPE_INT: u32 = 21;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_IMAGE: u32 = 25;
const OP_FUNCTION: u32 = 54;
const OP_VECTOR_SHUFFLE: u32 = 79;
const OP_IMAGE_QUERY_SIZE: u32 = 104;
const DIM_2D: u32 = 1;
const DIM_CUBE: u32 = 3;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type (intsample.rs's)
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

/// The module with its storage cube images as 2D arrays, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    // (OpTypeImage: id, sampled type, dim, depth, arrayed, ms, sampled (2: storage), format)
    let cubes: BTreeSet<u32> = instructions[..first_function].iter()
        .filter(|w| op(w) == OP_TYPE_IMAGE && w.len() >= 9 && w[3] == DIM_CUBE && w[5] == 0 && w[6] == 0 && w[7] == 2).map(|w| w[1]).collect();
    if cubes.is_empty() {
        return words.to_vec();
    }
    let types: BTreeMap<u32, &[u32]> = instructions[..first_function].iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let results: BTreeMap<u32, u32> = instructions[first_function..].iter().filter(|w| w.len() >= 3 && !untyped(op(w))).map(|w| (w[2], w[1])).collect();
    let mut bound = words[3];
    let mut fresh = || { bound += 1; bound - 1 };
    // 3-component vectors of the size queries' components: the module's, or new ones (before the first function)
    let mut vec3s: BTreeMap<u32, u32> = instructions[..first_function].iter().filter(|w| op(w) == OP_TYPE_VECTOR && w.len() == 4 && w[3] == 3).map(|w| (w[2], w[1])).collect();
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut body: Vec<Vec<u32>> = Vec::new();
    for w in &instructions {
        match op(w) {
            OP_TYPE_IMAGE if cubes.contains(&w[1]) => {
                let mut changed = w.to_vec();
                changed[3] = DIM_2D;
                changed[5] = 1;
                body.push(changed);
            },
            OP_IMAGE_QUERY_SIZE if w.len() == 4 && results.get(&w[3]).map_or(false, |t| cubes.contains(t)) => {
                // (the array's width, height and layers, then the first two under the query's id)
                let component = match types.get(&w[1]) {
                    Some(t) if op(t) == OP_TYPE_VECTOR && t.len() == 4 && t[3] == 2 && types.get(&t[2]).map_or(false, |c| op(c) == OP_TYPE_INT) => t[2],
                    _ => return words.to_vec(),
                };
                let vec3 = *vec3s.entry(component).or_insert_with(|| {
                    let id = fresh();
                    declarations.push(instruction(OP_TYPE_VECTOR, &[id, component, 3]));
                    id
                });
                let size = fresh();
                body.push(instruction(OP_IMAGE_QUERY_SIZE, &[vec3, size, w[3]]));
                body.push(instruction(OP_VECTOR_SHUFFLE, &[w[1], w[2], size, size, 0, 1]));
            },
            _ => body.push(w.to_vec()),
        }
    }
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    out
}
                                                                                                                      source/v64/src/browser/glbridge/vx/naga/src/intsample.rs                                            0000644 0000000 0000000 00000064256 00000000000 020426  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Samples of integer images (GLSL's `texture` of a usampler2D or isampler3D)
//! as fetches: WGSL samples only float textures. The texel is the one the
//! nearest filter takes, `floor(coordinate * size)` (plus a constant
//! offset), clamped to the image: the sampler's wrap mode is the
//! sampler's, which the shader cannot read, so it is always clamp to edge.
//! An array's layer is the coordinate rounded, clamped; a projective
//! sample's coordinate is divided first; the level is an explicit lod's,
//! else 0. Cube images are left as they were.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_EXT_INST_IMPORT: u32 = 11;
const OP_MEMORY_MODEL: u32 = 14;
const OP_EXT_INST: u32 = 12;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_FLOAT: u32 = 22;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_IMAGE: u32 = 25;
const OP_TYPE_SAMPLED_IMAGE: u32 = 27;
const OP_CONSTANT: u32 = 43;
const OP_CONSTANT_COMPOSITE: u32 = 44;
const OP_FUNCTION: u32 = 54;
const OP_VECTOR_SHUFFLE: u32 = 79;
const OP_COMPOSITE_EXTRACT: u32 = 81;
const OP_COMPOSITE_CONSTRUCT: u32 = 80;
const OP_IMAGE_SAMPLE_IMPLICIT_LOD: u32 = 87;
const OP_IMAGE_SAMPLE_EXPLICIT_LOD: u32 = 88;
const OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD: u32 = 91;
const OP_IMAGE_SAMPLE_PROJ_EXPLICIT_LOD: u32 = 92;
const OP_IMAGE_FETCH: u32 = 95;
const OP_IMAGE: u32 = 100;
const OP_IMAGE_QUERY_SIZE_LOD: u32 = 103;
const OP_CONVERT_F_TO_S: u32 = 110;
const OP_CONVERT_S_TO_F: u32 = 111;
const OP_I_ADD: u32 = 128;
const OP_F_ADD: u32 = 129;
const OP_I_SUB: u32 = 130;
const OP_F_MUL: u32 = 133;
const OP_F_DIV: u32 = 136;
const GLSL_FLOOR: u32 = 8;
const GLSL_CEIL: u32 = 9;
const GLSL_LOG2: u32 = 30;
const OP_F_SUB: u32 = 131;
const GLSL_F_MAX: u32 = 40;
const GLSL_F_CLAMP: u32 = 43;
const GLSL_LENGTH: u32 = 66;
const OP_IMAGE_QUERY_LEVELS: u32 = 106;
const OP_DPDX: u32 = 207;
const OP_I_MUL: u32 = 132;
const OP_S_REM: u32 = 138;
const OP_S_LESS_THAN: u32 = 177;
const OP_SELECT: u32 = 169;
const OP_TYPE_BOOL: u32 = 20;
const OP_DPDY: u32 = 208;
const GLSL_S_CLAMP: u32 = 45;
const IMAGE_OPERANDS_BIAS: u32 = 1;
const IMAGE_OPERANDS_LOD: u32 = 2;
const IMAGE_OPERANDS_GRAD: u32 = 4;
const IMAGE_OPERANDS_CONST_OFFSET: u32 = 8;
const IMAGE_OPERANDS_OFFSET: u32 = 0x10;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

struct Pass {
    bound: u32,
    types: BTreeMap<u32, Vec<u32>>,
    vectors: BTreeMap<(u32, u32), u32>,
    constants: BTreeMap<(u32, u32), u32>,
    composites: BTreeMap<(u32, Vec<u32>), u32>,
    int: Option<u32>,
    declarations: Vec<Vec<u32>>,
}

impl Pass {
    fn fresh(&mut self) -> u32 {
        self.bound += 1;
        self.bound - 1
    }
    fn declare(&mut self, w: Vec<u32>) { self.declarations.push(w); }
    fn int(&mut self) -> u32 {
        if let Some(id) = self.int {
            return id;
        }
        let id = self.fresh();
        self.declare(instruction(OP_TYPE_INT, &[id, 32, 1]));
        self.int = Some(id);
        id
    }
    /// the bool type, existing or new
    fn boolean(&mut self) -> u32 {
        if let Some((&id, _)) = self.types.iter().find(|(_, w)| w[0] & 0xFFFF == OP_TYPE_BOOL) {
            return id;
        }
        let id = self.fresh();
        let w = instruction(OP_TYPE_BOOL, &[id]);
        self.types.insert(id, w.clone());
        self.declare(w);
        id
    }

    fn vector(&mut self, component: u32, n: u32) -> u32 {
        if n == 1 {
            return component;
        }
        if let Some(&id) = self.vectors.get(&(component, n)) {
            return id;
        }
        let id = self.fresh();
        self.declare(instruction(OP_TYPE_VECTOR, &[id, component, n]));
        self.vectors.insert((component, n), id);
        id
    }
    fn constant(&mut self, ty: u32, bits: u32) -> u32 {
        if let Some(&id) = self.constants.get(&(ty, bits)) {
            return id;
        }
        let id = self.fresh();
        self.declare(instruction(OP_CONSTANT, &[ty, id, bits]));
        self.constants.insert((ty, bits), id);
        id
    }
    /// A constant vector of `n` of the scalar constant
    fn splat(&mut self, scalar_ty: u32, bits: u32, n: u32) -> u32 {
        let c = self.constant(scalar_ty, bits);
        if n == 1 {
            return c;
        }
        let ty = self.vector(scalar_ty, n);
        let parts: Vec<u32> = core::iter::repeat(c).take(n as usize).collect();
        if let Some(&id) = self.composites.get(&(ty, parts.clone())) {
            return id;
        }
        let id = self.fresh();
        let mut operands = Vec::from([ty, id]);
        operands.extend(&parts);
        self.declare(instruction(OP_CONSTANT_COMPOSITE, &operands));
        self.composites.insert((ty, parts), id);
        id
    }
}

/// The module with its samples of integer images made fetches, or the words
/// as they were; `wraps`: their samplers' address modes by the images'
/// group << 16 | WGSL binding (VkSamplerAddressMode u | v << 4 | w << 8:
/// repeat 0 and mirrored repeat 1 wrap the texel, the others clamp it);
/// `fetched`: the images made fetches of, so
pub fn lower(words: &[u32], wraps: &[(u32, u32)], fetched: &mut Vec<u32>) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let sample = |o: u32| matches!(o, OP_IMAGE_SAMPLE_IMPLICIT_LOD | OP_IMAGE_SAMPLE_EXPLICIT_LOD | OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD | OP_IMAGE_SAMPLE_PROJ_EXPLICIT_LOD);
    if !instructions.iter().any(|w| sample(op(w))) {
        return words.to_vec();
    }
    let mut pass = Pass { bound: words[3], types: BTreeMap::new(), vectors: BTreeMap::new(), constants: BTreeMap::new(), composites: BTreeMap::new(),
        int: None, declarations: Vec::new() };
    let mut type_of: BTreeMap<u32, u32> = BTreeMap::new();
    let mut glsl = None;
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    for (i, w) in instructions.iter().enumerate() {
        let o = op(w);
        match o {
            19..=39 if w.len() >= 2 => {
                pass.types.insert(w[1], w.to_vec());
                if o == OP_TYPE_VECTOR && w.len() >= 4 {
                    pass.vectors.entry((w[2], w[3])).or_insert(w[1]);
                }
                if o == OP_TYPE_INT && w.len() >= 4 && w[2] == 32 && w[3] == 1 {
                    pass.int = Some(w[1]);
                }
            },
            OP_CONSTANT if w.len() == 4 => {
                pass.constants.entry((w[1], w[3])).or_insert(w[2]);
            },
            OP_EXT_INST_IMPORT if w.len() >= 3 => {
                let name: Vec<u8> = w[2..].iter().flat_map(|x| x.to_le_bytes()).take_while(|&b| b != 0).collect();
                if name == b"GLSL.std.450" {
                    glsl = Some(w[1]);
                }
            },
            _ => {},
        }
        if (i >= first_function && !untyped(o) && o != 248 || i < first_function && (41..=52).contains(&o)) && w.len() >= 3 {
            type_of.insert(w[2], w[1]);
        }
    }
    // (GLSL.std.450, for floor and clamp: imported when the shader does not)
    let imported = glsl.is_none();
    let glsl = match glsl {
        Some(id) => id,
        None => {
            pass.bound += 1;
            pass.bound - 1
        },
    };
    // what defines each id in the functions, and the variables' set and binding
    // (a sampled image's image: OpSampledImage of an OpLoad of a variable)
    let defs: BTreeMap<u32, &[u32]> = instructions[first_function..].iter().filter(|w| w.len() >= 3 && !untyped(op(w))).map(|w| (w[2], *w)).collect();
    let decoration = |id: u32, d: u32| instructions[..first_function].iter().find(|w| op(w) == 71 && w.len() >= 4 && w[1] == id && w[2] == d).map(|w| w[3]);
    let image_key = |si: u32| -> Option<u32> {
        let s = defs.get(&si)?;
        if op(s) != 86 || s.len() < 5 {
            return None;
        }
        let load = defs.get(&s[3])?;
        if op(load) != 61 || load.len() < 4 {
            return None;
        }
        let (set, binding) = (decoration(load[3], 34)?, decoration(load[3], 33)?);
        Some(set << 16 | crate::wgsl_binding(binding))
    };
    // the image type of a sampled image's type, when its texels are integers and it is not a cube
    let integer_image = |pass: &Pass, sampled_image_ty: u32| -> Option<(u32, u32, bool)> {
        let si = pass.types.get(&sampled_image_ty)?;
        if op(si) != OP_TYPE_SAMPLED_IMAGE {
            return None;
        }
        let image = pass.types.get(&si[2])?;
        if op(image) != OP_TYPE_IMAGE || op(pass.types.get(&image[2])?) != OP_TYPE_INT {
            return None;
        }
        // (dim: 1 2D, 2 3D; arrayed)
        let (dim, arrayed, ms) = (image[3], image[5], image[6]);
        if ms != 0 || !matches!(dim, 1 | 2) {
            return None;
        }
        Some((si[2], dim, arrayed != 0))
    };
    let mut body: Vec<Vec<u32>> = Vec::new();
    let mut changed = false;
    for w in &instructions[first_function..] {
        let o = op(w);
        let sampled = if sample(o) && w.len() >= 5 { type_of.get(&w[3]).and_then(|&t| integer_image(&pass, t)) } else { None };
        let Some((image_ty, dim, arrayed)) = sampled else {
            body.push(w.to_vec());
            continue;
        };
        let (rt, result, si, coord) = (w[1], w[2], w[3], w[4]);
        let Some(&coord_ty) = type_of.get(&coord) else {
            body.push(w.to_vec());
            continue;
        };
        let float = match pass.types.get(&coord_ty).map(|t| (op(t), t.clone())) {
            Some((OP_TYPE_VECTOR, t)) => t[2],
            _ => {
                body.push(w.to_vec());
                continue;
            },
        };
        if pass.types.get(&float).map(|t| op(t)) != Some(OP_TYPE_FLOAT) {
            body.push(w.to_vec());
            continue;
        }
        changed = true;
        let int = pass.int();
        let spatial = if dim == 2 { 3 } else { 2 };
        let size_n = spatial + arrayed as u32;
        // the image operands: an explicit lod, a constant offset
        let mask = *w.get(5).unwrap_or(&0);
        let mut arg = 6;
        let mut lod_f = None;
        let mut bias = None;
        let mut grad = None;
        let mut offset = None;
        for (bit, args) in [(IMAGE_OPERANDS_BIAS, 1), (IMAGE_OPERANDS_LOD, 1), (IMAGE_OPERANDS_GRAD, 2), (IMAGE_OPERANDS_CONST_OFFSET, 1), (IMAGE_OPERANDS_OFFSET, 1)] {
            if mask & bit != 0 {
                if bit == IMAGE_OPERANDS_LOD {
                    lod_f = w.get(arg).copied();
                }
                if bit == IMAGE_OPERANDS_BIAS {
                    bias = w.get(arg).copied();
                }
                if bit == IMAGE_OPERANDS_GRAD {
                    grad = w.get(arg).copied().zip(w.get(arg + 1).copied());
                }
                if bit == IMAGE_OPERANDS_CONST_OFFSET || bit == IMAGE_OPERANDS_OFFSET {
                    offset = w.get(arg).copied();
                }
                arg += args;
            }
        }
        let image = pass.fresh();
        body.push(instruction(OP_IMAGE, &[image_ty, image, si]));
        let size_ty = pass.vector(int, size_n);
        // the coordinate: divided by q for a projective one
        let fvec = pass.vector(float, spatial);
        let ivec = pass.vector(int, spatial);
        let mut xy = pass.fresh();
        let mut operands = Vec::from([fvec, xy, coord, coord]);
        operands.extend(0..spatial);
        body.push(instruction(OP_VECTOR_SHUFFLE, &operands));
        if matches!(o, OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD | OP_IMAGE_SAMPLE_PROJ_EXPLICIT_LOD) {
            let q_index = pass.types.get(&coord_ty).map_or(spatial, |t| t[3] - 1);
            let (q, qs, divided) = (pass.fresh(), pass.fresh(), pass.fresh());
            body.push(instruction(OP_COMPOSITE_EXTRACT, &[float, q, coord, q_index]));
            let mut c = Vec::from([fvec, qs]);
            c.extend(core::iter::repeat(q).take(spatial as usize));
            body.push(instruction(OP_COMPOSITE_CONSTRUCT, &c));
            body.push(instruction(OP_F_DIV, &[fvec, divided, xy, qs]));
            xy = divided;
        }
        // (the spatial components of a size query)
        let spatial_of = |pass: &mut Pass, body: &mut Vec<Vec<u32>>, size: u32| if arrayed {
            let id = pass.fresh();
            let mut operands = Vec::from([ivec, id, size, size]);
            operands.extend(0..spatial);
            body.push(instruction(OP_VECTOR_SHUFFLE, &operands));
            id
        }
        else {
            size
        };
        // the level, as the nearest mip filter takes it: ceil(λ + 0.5) - 1 within
        // the levels (0 for an image of one level), λ an explicit lod, or
        // log2(ρ) of the texel coordinate's derivatives at level 0 (given, or a
        // fragment shader's own, plus the bias)
        let implicit = matches!(o, OP_IMAGE_SAMPLE_IMPLICIT_LOD | OP_IMAGE_SAMPLE_PROJ_IMPLICIT_LOD);
        let lambda = match (lod_f, grad) {
            (Some(l), _) => Some(l),
            (None, grad) if grad.is_some() || implicit => {
                let zero = pass.constant(int, 0);
                let size0 = pass.fresh();
                body.push(instruction(OP_IMAGE_QUERY_SIZE_LOD, &[size_ty, size0, image, zero]));
                let size0 = spatial_of(&mut pass, &mut body, size0);
                let fsize0 = pass.fresh();
                body.push(instruction(OP_CONVERT_S_TO_F, &[fvec, fsize0, size0]));
                let (dx, dy) = match grad {
                    Some((gx, gy)) => {
                        // (the gradients' spatial components, in texels)
                        let (sx, sy, tx, ty) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh());
                        let shuffle = |from: u32, to: u32, body: &mut Vec<Vec<u32>>| {
                            let mut operands = Vec::from([fvec, to, from, from]);
                            operands.extend(0..spatial);
                            body.push(instruction(OP_VECTOR_SHUFFLE, &operands));
                        };
                        let gx_ty = type_of.get(&gx).copied();
                        if gx_ty == Some(fvec) { body.push(instruction(OP_F_MUL, &[fvec, tx, gx, fsize0])); }
                        else { shuffle(gx, sx, &mut body); body.push(instruction(OP_F_MUL, &[fvec, tx, sx, fsize0])); }
                        let gy_ty = type_of.get(&gy).copied();
                        if gy_ty == Some(fvec) { body.push(instruction(OP_F_MUL, &[fvec, ty, gy, fsize0])); }
                        else { shuffle(gy, sy, &mut body); body.push(instruction(OP_F_MUL, &[fvec, ty, sy, fsize0])); }
                        (tx, ty)
                    },
                    None => {
                        let (scaled0, dx, dy) = (pass.fresh(), pass.fresh(), pass.fresh());
                        body.push(instruction(OP_F_MUL, &[fvec, scaled0, xy, fsize0]));
                        body.push(instruction(OP_DPDX, &[fvec, dx, scaled0]));
                        body.push(instruction(OP_DPDY, &[fvec, dy, scaled0]));
                        (dx, dy)
                    },
                };
                let (lx, ly, rho, lambda) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh());
                body.push(instruction(OP_EXT_INST, &[float, lx, glsl, GLSL_LENGTH, dx]));
                body.push(instruction(OP_EXT_INST, &[float, ly, glsl, GLSL_LENGTH, dy]));
                body.push(instruction(OP_EXT_INST, &[float, rho, glsl, GLSL_F_MAX, lx, ly]));
                body.push(instruction(OP_EXT_INST, &[float, lambda, glsl, GLSL_LOG2, rho]));
                Some(match bias {
                    Some(b) => {
                        let id = pass.fresh();
                        body.push(instruction(OP_F_ADD, &[float, id, lambda, b]));
                        id
                    },
                    None => lambda,
                })
            },
            _ => None,
        };
        let lod = match lambda {
            Some(lambda) => {
                let half = pass.constant(float, 0x3F00_0000);
                let zero_f = pass.constant(float, 0);
                let one_f = pass.constant(float, 0x3F80_0000);
                let one = pass.constant(int, 1);
                let (rounded, ceiled, below, levels, last, last_f, level, lod) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(),
                    pass.fresh(), pass.fresh(), pass.fresh());
                body.push(instruction(OP_F_ADD, &[float, rounded, lambda, half]));
                body.push(instruction(OP_EXT_INST, &[float, ceiled, glsl, GLSL_CEIL, rounded]));
                body.push(instruction(OP_F_SUB, &[float, below, ceiled, one_f]));
                body.push(instruction(OP_IMAGE_QUERY_LEVELS, &[int, levels, image]));
                body.push(instruction(OP_I_SUB, &[int, last, levels, one]));
                body.push(instruction(OP_CONVERT_S_TO_F, &[float, last_f, last]));
                body.push(instruction(OP_EXT_INST, &[float, level, glsl, GLSL_F_CLAMP, below, zero_f, last_f]));
                body.push(instruction(OP_CONVERT_F_TO_S, &[int, lod, level]));
                lod
            },
            None => pass.constant(int, 0),
        };
        let size = pass.fresh();
        body.push(instruction(OP_IMAGE_QUERY_SIZE_LOD, &[size_ty, size, image, lod]));
        let size_xy = spatial_of(&mut pass, &mut body, size);
        let (fsize, scaled, floored, texel) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh());
        body.push(instruction(OP_CONVERT_S_TO_F, &[fvec, fsize, size_xy]));
        body.push(instruction(OP_F_MUL, &[fvec, scaled, xy, fsize]));
        body.push(instruction(OP_EXT_INST, &[fvec, floored, glsl, GLSL_FLOOR, scaled]));
        body.push(instruction(OP_CONVERT_F_TO_S, &[ivec, texel, floored]));
        let mut texel = texel;
        if let Some(offset) = offset {
            let id = pass.fresh();
            body.push(instruction(OP_I_ADD, &[ivec, id, texel, offset]));
            texel = id;
        }
        // the sampler's address modes, each axis's
        let key = image_key(w[3]);
        if let Some(k) = key {
            fetched.push(k);
        }
        let modes = key.and_then(|k| wraps.iter().find(|(x, _)| *x == k)).map_or(0x222, |&(_, m)| m);
        let mode = |k: u32| modes >> (4 * k) & 0xF;
        let (zero, one) = (pass.splat(int, 0, spatial), pass.splat(int, 1, spatial));
        let (last, clamped) = (pass.fresh(), pass.fresh());
        body.push(instruction(OP_I_SUB, &[ivec, last, size_xy, one]));
        body.push(instruction(OP_EXT_INST, &[ivec, clamped, glsl, GLSL_S_CLAMP, texel, zero, last]));
        // (repeat: the texel modulo the size; mirrored repeat: modulo twice the size, folded back)
        let clamped = if (0..spatial).all(|k| mode(k) >= 2) { clamped } else {
            let boolean = pass.boolean();
            let (one1, two1) = (pass.constant(int, 1), pass.constant(int, 2));
            let mut parts = Vec::new();
            for k in 0..spatial {
                let part = pass.fresh();
                body.push(instruction(OP_COMPOSITE_EXTRACT, &[int, part, if mode(k) >= 2 { clamped } else { texel }, k]));
                if mode(k) >= 2 {
                    parts.push(part);
                    continue;
                }
                let size_k = pass.fresh();
                body.push(instruction(OP_COMPOSITE_EXTRACT, &[int, size_k, size_xy, k]));
                // (a floored modulo, never negative, of remainders: ((a % b) + b) % b; naga refuses OpSMod of
                // integers, and negate.rs makes a shader's own OpSMod the remainder)
                let floored = |pass: &mut Pass, body: &mut Vec<Vec<u32>>, a: u32, b: u32| {
                    let (r, shifted, m) = (pass.fresh(), pass.fresh(), pass.fresh());
                    body.push(instruction(OP_S_REM, &[int, r, a, b]));
                    body.push(instruction(OP_I_ADD, &[int, shifted, r, b]));
                    body.push(instruction(OP_S_REM, &[int, m, shifted, b]));
                    m
                };
                if mode(k) == 0 {
                    let wrapped = floored(&mut pass, &mut body, part, size_k);
                    parts.push(wrapped);
                    continue;
                }
                let (twice, back, last_k, under, mirrored) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh());
                body.push(instruction(OP_I_MUL, &[int, twice, size_k, two1]));
                let folded = floored(&mut pass, &mut body, part, twice);
                body.push(instruction(OP_I_SUB, &[int, last_k, twice, one1]));
                body.push(instruction(OP_I_SUB, &[int, back, last_k, folded]));
                body.push(instruction(OP_S_LESS_THAN, &[boolean, under, folded, size_k]));
                body.push(instruction(OP_SELECT, &[int, mirrored, under, folded, back]));
                parts.push(mirrored);
            }
            let id = pass.fresh();
            let mut c = Vec::from([ivec, id]);
            c.extend(parts);
            body.push(instruction(OP_COMPOSITE_CONSTRUCT, &c));
            id
        };
        let fetch_at = if arrayed {
            // the layer: floor(z + 0.5), clamped
            let half = pass.constant(float, 0x3F00_0000);
            let (z, zh, zf, zi, layers, layers_last, layer, at) = (pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(), pass.fresh(),
                pass.fresh(), pass.fresh());
            body.push(instruction(OP_COMPOSITE_EXTRACT, &[float, z, coord, spatial]));
            body.push(instruction(OP_F_ADD, &[float, zh, z, half]));
            body.push(instruction(OP_EXT_INST, &[float, zf, glsl, GLSL_FLOOR, zh]));
            body.push(instruction(OP_CONVERT_F_TO_S, &[int, zi, zf]));
            body.push(instruction(OP_COMPOSITE_EXTRACT, &[int, layers, size, spatial]));
            let (zero1, one1) = (pass.constant(int, 0), pass.constant(int, 1));
            body.push(instruction(OP_I_SUB, &[int, layers_last, layers, one1]));
            body.push(instruction(OP_EXT_INST, &[int, layer, glsl, GLSL_S_CLAMP, zi, zero1, layers_last]));
            let all = pass.vector(int, spatial + 1);
            let mut c = Vec::from([all, at]);
            for k in 0..spatial {
                let x = pass.fresh();
                body.push(instruction(OP_COMPOSITE_EXTRACT, &[int, x, clamped, k]));
                c.push(x);
            }
            c.push(layer);
            body.push(instruction(OP_COMPOSITE_CONSTRUCT, &c));
            at
        }
        else {
            clamped
        };
        body.push(instruction(OP_IMAGE_FETCH, &[rt, result, image, fetch_at, IMAGE_OPERANDS_LOD, lod]));
    }
    if !changed {
        return words.to_vec();
    }
    let mut out = words[..5].to_vec();
    for w in &instructions[..first_function] {
        if imported && op(w) == OP_MEMORY_MODEL {
            let mut import = Vec::from([glsl]);
            import.extend(b"GLSL.std.450\0\0\0\0".chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])));
            out.extend_from_slice(&instruction(OP_EXT_INST_IMPORT, &import));
        }
        out.extend_from_slice(w);
    }
    for d in &pass.declarations {
        out.extend_from_slice(d);
    }
    for w in &body {
        out.extend_from_slice(w);
    }
    out[3] = pass.bound;
    out
}

/// Each image's coordinate types declared (float and signed int vectors of
/// its dimensions' size): naga's SPIR-V front end looks them up for an
/// array image's coordinates (a fetch splits off the layer) and panics when
/// the module never declared them
pub fn coordinate_types(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let mut sizes: Vec<u32> = instructions.iter().filter(|w| op(w) == OP_TYPE_IMAGE && w.len() >= 9 && w[5] != 0)
        .filter_map(|w| match w[3] { 1 => Some(2), 2 | 3 => Some(3), _ => None }).collect();
    sizes.sort_unstable();
    sizes.dedup();
    if sizes.is_empty() {
        return words.to_vec();
    }
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let find = |pred: &dyn Fn(&[u32]) -> bool| instructions[..first_function].iter().find(|w| pred(w)).map(|w| w[1]);
    let mut bound = words[3];
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut fresh = || {
        bound += 1;
        bound - 1
    };
    let float = find(&|w| op(w) == OP_TYPE_FLOAT && w[2] == 32).unwrap_or_else(|| {
        let id = fresh();
        declarations.push(instruction(OP_TYPE_FLOAT, &[id, 32]));
        id
    });
    let int = find(&|w| op(w) == OP_TYPE_INT && w[2] == 32 && w[3] == 1).unwrap_or_else(|| {
        let id = fresh();
        declarations.push(instruction(OP_TYPE_INT, &[id, 32, 1]));
        id
    });
    for size in sizes {
        for component in [float, int] {
            if find(&|w| op(w) == OP_TYPE_VECTOR && w[2] == component && w[3] == size).is_none() {
                let id = fresh();
                declarations.push(instruction(OP_TYPE_VECTOR, &[id, component, size]));
            }
        }
    }
    if declarations.is_empty() {
        return words.to_vec();
    }
    let mut out = words[..5].to_vec();
    for (i, w) in instructions.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    if first_function == instructions.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out[3] = bound;
    out
}
                                                                                                                                                                                                                                                                                                                                                  source/v64/src/browser/glbridge/vx/naga/src/io.rs                                                   0000644 0000000 0000000 00000046333 00000000000 017035  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Entry point inputs and outputs that WGSL cannot have at a location:
//! matrices, arrays and structs (a matrix vertex attribute, a matrix or
//! array varying, an array of fragment outputs). Each becomes its vectors
//! and scalars at consecutive locations in Vulkan's order (a matrix's
//! columns, an array's elements, a struct's members, one location each), so
//! a vertex shader's outputs still meet the fragment shader's inputs, and a
//! matrix attribute's columns are the pipeline's attributes at those
//! locations. The entry point (naga's wrapper of the SPIR-V's main) makes
//! the value of its inputs again, and takes its outputs apart on return. A
//! fragment shader's outputs of fewer than 4 components get the rest (0, and
//! 1 for alpha): WebGPU wants as many as the target has.

use alloc::string::String;
use alloc::vec::Vec;
use naga::{ArraySize, Binding, Block, Expression, Handle, Span, Statement, Type, TypeInner, VectorSize};

/// A type a location can have (a scalar or vector of 32 bits)
fn shareable(module: &naga::Module, ty: Handle<Type>) -> bool {
    match module.types[ty].inner {
        TypeInner::Scalar(s) | TypeInner::Vector { scalar: s, .. } => s.width == 4,
        _ => false,
    }
}

/// The vectors and scalars of a type, each with the indices that reach it
fn leaves(module: &mut naga::Module, ty: Handle<Type>, path: &mut Vec<u32>, out: &mut Vec<(Handle<Type>, Vec<u32>)>) -> bool {
    match module.types[ty].inner.clone() {
        TypeInner::Scalar(_) | TypeInner::Vector { .. } => {
            out.push((ty, path.clone()));
            true
        },
        TypeInner::Matrix { columns, rows, scalar } => {
            let column = module.types.insert(Type { name: None, inner: TypeInner::Vector { size: rows, scalar } }, Span::UNDEFINED);
            for c in 0..columns as u32 {
                path.push(c);
                out.push((column, path.clone()));
                path.pop();
            }
            true
        },
        TypeInner::Array { base, size: ArraySize::Constant(n), .. } => {
            for i in 0..n.get() {
                path.push(i);
                let ok = leaves(module, base, path, out);
                path.pop();
                if !ok {
                    return false;
                }
            }
            true
        },
        TypeInner::Struct { members, .. } => {
            for (i, m) in members.iter().enumerate() {
                path.push(i as u32);
                let ok = leaves(module, m.ty, path, out);
                path.pop();
                if !ok {
                    return false;
                }
            }
            true
        },
        _ => false,
    }
}

/// The binding of a leaf `k` locations after `binding`; for a varying
/// (`varying`: a vertex output, a fragment input), an integer leaf's is flat
/// (a struct's or array's of mixed kinds had the first member's), and a
/// leaf without one gets naga's default (naga gives none to the types it
/// cannot pass)
fn shifted(module: &naga::Module, binding: &Binding, k: u32, ty: Handle<Type>, varying: bool) -> Binding {
    match binding.clone() {
        Binding::Location { location, interpolation, sampling, blend_src, per_primitive } => {
            let integer = matches!(module.types[ty].inner.scalar_kind(), Some(naga::ScalarKind::Sint | naga::ScalarKind::Uint));
            let (interpolation, sampling) = if !varying {
                (interpolation, sampling)
            }
            else if integer {
                (Some(naga::Interpolation::Flat), None)
            }
            else if interpolation.is_none() {
                (Some(naga::Interpolation::Perspective), Some(naga::Sampling::Center))
            }
            else {
                (interpolation, sampling)
            };
            Binding::Location { location: location + k, interpolation, sampling, blend_src, per_primitive }
        },
        b => b,
    }
}

/// The value of type `ty` made of leaf expressions (by path), the composes appended
fn compose(module: &naga::Module, f: &mut naga::Function, ty: Handle<Type>, path: &mut Vec<u32>, leaf: &dyn Fn(&[u32]) -> Option<Handle<Expression>>)
    -> Option<Handle<Expression>> {
    if let Some(h) = leaf(path) {
        return Some(h);
    }
    let count = match module.types[ty].inner {
        TypeInner::Matrix { columns, .. } => columns as u32,
        TypeInner::Array { size: ArraySize::Constant(n), .. } => n.get(),
        TypeInner::Struct { ref members, .. } => members.len() as u32,
        _ => return None,
    };
    let mut components = Vec::new();
    for i in 0..count {
        let inner = match module.types[ty].inner {
            TypeInner::Matrix { rows, scalar, .. } => module.types.get(&Type { name: None, inner: TypeInner::Vector { size: rows, scalar } })?,
            TypeInner::Array { base, .. } => base,
            TypeInner::Struct { ref members, .. } => members[i as usize].ty,
            _ => return None,
        };
        path.push(i);
        let c = compose(module, f, inner, path, leaf);
        path.pop();
        components.push(c?);
    }
    Some(f.expressions.append(Expression::Compose { ty, components }, Span::UNDEFINED))
}

/// Uses of expression `from` in a block's statements made uses of `to`; false where another kind of use is met
fn replace_uses(block: &mut Block, from: Handle<Expression>, to: Handle<Expression>) -> bool {
    let swap = |h: &mut Handle<Expression>| {
        if *h == from {
            *h = to;
        }
    };
    for statement in block.iter_mut() {
        match statement {
            Statement::Store { pointer, value } => {
                if *pointer == from {
                    return false;
                }
                swap(value);
            },
            Statement::Return { value: Some(v) } => swap(v),
            Statement::Call { arguments, .. } => arguments.iter_mut().for_each(swap),
            Statement::Block(b) => {
                if !replace_uses(b, from, to) {
                    return false;
                }
            },
            Statement::If { condition, accept, reject } => {
                if *condition == from || !replace_uses(accept, from, to) || !replace_uses(reject, from, to) {
                    return false;
                }
            },
            Statement::Loop { body, continuing, .. } => {
                if !replace_uses(body, from, to) || !replace_uses(continuing, from, to) {
                    return false;
                }
            },
            Statement::Emit(_) | Statement::Return { value: None } | Statement::Kill | Statement::Break | Statement::Continue => {},
            _ => {},
        }
    }
    true
}

/// The entry points' inputs and outputs of those types, flattened
pub fn flatten(module: &mut naga::Module) -> Result<(), String> {
    for e in 0..module.entry_points.len() {
        flatten_inputs(module, e)?;
        flatten_outputs(module, e)?;
    }
    // the structs the entry points had (naga's WGSL writer writes every
    // struct, and WGSL refuses a location on a matrix or an array): their
    // members of such types unbound
    let unbind: Vec<Handle<Type>> = module.types.iter().filter(|(_, ty)| match &ty.inner {
        TypeInner::Struct { members, .. } => members.iter().any(|m| matches!(m.binding, Some(Binding::Location { .. })) && !shareable(module, m.ty)),
        _ => false,
    }).map(|(handle, _)| handle).collect();
    for handle in unbind {
        let mut ty = module.types[handle].clone();
        if let TypeInner::Struct { members, .. } = &mut ty.inner {
            for m in members.iter_mut() {
                if matches!(m.binding, Some(Binding::Location { .. })) && !shareable(module, m.ty) {
                    m.binding = None;
                }
            }
        }
        module.types.replace(handle, ty);
    }
    Ok(())
}

fn flatten_inputs(module: &mut naga::Module, e: usize) -> Result<(), String> {
    let count = module.entry_points[e].function.arguments.len();
    let fragment = module.entry_points[e].stage == naga::ShaderStage::Fragment;
    for a in 0..count {
        let argument = module.entry_points[e].function.arguments[a].clone();
        let Some(binding @ Binding::Location { .. }) = argument.binding.clone() else { continue };
        if shareable(module, argument.ty) {
            continue;
        }
        let mut list = Vec::new();
        if !leaves(module, argument.ty, &mut Vec::new(), &mut list) || list.is_empty() {
            return Err(String::from("an input of a type not done"));
        }
        // (the function out of the module while it changes)
        let mut function = core::mem::take(&mut module.entry_points[e].function);
        let f = &mut function;
        // the argument becomes the first leaf, the others are appended
        let mut leaf_arguments = Vec::new();
        for (k, (ty, _)) in list.iter().enumerate() {
            let index = if k == 0 {
                f.arguments[a].ty = *ty;
                f.arguments[a].binding = Some(shifted(module, &binding, 0, *ty, fragment));
                a
            }
            else {
                f.arguments.push(naga::FunctionArgument { name: None, ty: *ty, binding: Some(shifted(module, &binding, k as u32, *ty, fragment)) });
                f.arguments.len() - 1
            };
            leaf_arguments.push(f.expressions.append(Expression::FunctionArgument(index as u32), Span::UNDEFINED));
        }
        let olds: Vec<Handle<Expression>> = f.expressions.iter()
            .filter(|(h, x)| matches!(x, Expression::FunctionArgument(i) if *i as usize == a) && !leaf_arguments.contains(h))
            .map(|(h, _)| h).collect();
        let first = f.expressions.len();
        let by_path = |path: &[u32]| list.iter().position(|(_, p)| p.as_slice() == path).map(|k| leaf_arguments[k]);
        let value = compose(module, f, argument.ty, &mut Vec::new(), &by_path);
        let value = match value {
            Some(v) => v,
            None => {
                module.entry_points[e].function = function;
                return Err(String::from("an input's value"));
            },
        };
        // (no expression may use the old argument: the wrapper only stores it)
        let used = f.expressions.iter().any(|(h, x)| h.index() < first && matches!(x,
            Expression::AccessIndex { base, .. } | Expression::Access { base, .. } if olds.contains(base)));
        if used {
            module.entry_points[e].function = function;
            return Err(String::from("an input used other than stored"));
        }
        for &old in &olds {
            if !replace_uses(&mut f.body, old, value) {
                module.entry_points[e].function = function;
                return Err(String::from("an input used other than stored"));
            }
        }
        if f.expressions.len() > first {
            let range = f.expressions.range_from(first);
            f.body.splice(0..0, Block::from_vec(Vec::from([Statement::Emit(range)])));
        }
        module.entry_points[e].function = function;
    }
    Ok(())
}

fn flatten_outputs(module: &mut naga::Module, e: usize) -> Result<(), String> {
    let Some(result) = module.entry_points[e].function.result.clone() else { return Ok(()) };
    // the members (or the one value) at a location of a type not shareable
    let members: Vec<naga::StructMember> = match module.types[result.ty].inner {
        TypeInner::Struct { ref members, .. } => members.clone(),
        _ => match result.binding {
            Some(ref b @ Binding::Location { .. }) => Vec::from([naga::StructMember { name: None, ty: result.ty, binding: Some(b.clone()), offset: 0 }]),
            _ => return Ok(()),
        },
    };
    let single = !matches!(module.types[result.ty].inner, TypeInner::Struct { .. });
    let fragment = module.entry_points[e].stage == naga::ShaderStage::Fragment;
    let flatten_member = |module: &naga::Module, m: &naga::StructMember| matches!(m.binding, Some(Binding::Location { .. })) && !shareable(module, m.ty);
    // (a fragment output of fewer than 4 components: WebGPU wants as many as the target has, Vulkan leaves the rest undefined)
    let narrow = |module: &naga::Module, ty: Handle<Type>| -> Option<(naga::Scalar, u32)> {
        match module.types[ty].inner {
            TypeInner::Scalar(s) if fragment => Some((s, 1)),
            TypeInner::Vector { size, scalar } if fragment && (size as u32) < 4 => Some((scalar, size as u32)),
            _ => None,
        }
    };
    if !members.iter().any(|m| flatten_member(module, m) || matches!(m.binding, Some(Binding::Location { .. })) && narrow(module, m.ty).is_some()) {
        return Ok(());
    }
    // the new members: (member, leaf path, widened from) each
    let mut new_members = Vec::new();
    let mut sources: Vec<Source> = Vec::new();
    for (i, m) in members.iter().enumerate() {
        let binding = m.binding.clone();
        let mut list = Vec::new();
        if flatten_member(module, m) {
            if !leaves(module, m.ty, &mut Vec::new(), &mut list) {
                return Err(String::from("an output of a type not done"));
            }
        }
        else {
            list.push((m.ty, Vec::new()));
        }
        for (k, (ty, path)) in list.into_iter().enumerate() {
            let at = |module: &naga::Module, b: &Option<Binding>, ty: Handle<Type>| b.as_ref().map(|b| shifted(module, b, k as u32, ty, !fragment));
            let located = matches!(binding, Some(Binding::Location { .. }));
            match narrow(module, ty).filter(|_| located) {
                Some((scalar, count)) => {
                    let wide = module.types.insert(Type { name: None, inner: TypeInner::Vector { size: VectorSize::Quad, scalar } }, Span::UNDEFINED);
                    new_members.push(naga::StructMember { name: m.name.clone(), ty: wide, binding: at(module, &binding, wide), offset: 0 });
                    sources.push(Source { member: i, path, widen: Some((scalar, count, wide)) });
                },
                None => {
                    new_members.push(naga::StructMember { name: m.name.clone(), ty, binding: at(module, &binding, ty), offset: 0 });
                    sources.push(Source { member: i, path, widen: None });
                },
            }
        }
    }
    // their offsets (an output struct's layout is its own)
    let mut layouter = naga::proc::Layouter::default();
    layouter.update(module.to_ctx()).map_err(|_| String::from("layout"))?;
    let mut offset = 0;
    let mut alignment = naga::proc::Alignment::ONE;
    for m in new_members.iter_mut() {
        let layout = layouter[m.ty];
        offset = layout.alignment.round_up(offset);
        m.offset = offset;
        offset += layout.size;
        alignment = alignment.max(layout.alignment);
    }
    let span = alignment.round_up(offset);
    let new_ty = module.types.insert(Type { name: None, inner: TypeInner::Struct { members: new_members, span } }, Span::UNDEFINED);
    let f = &mut module.entry_points[e].function;
    f.result = Some(naga::FunctionResult { ty: new_ty, binding: None });
    rewrite_returns(&mut f.body, &mut f.expressions, &sources, single, new_ty);
    Ok(())
}

/// A member of the new outputs: the original member, the path to its leaf,
/// and, for one widened to 4 components, its scalar, its components and
/// the vector type
struct Source {
    member: usize,
    path: Vec<u32>,
    widen: Option<(naga::Scalar, u32, Handle<Type>)>,
}

/// A literal of a scalar kind: 0, or 1 for the alpha
fn literal(scalar: naga::Scalar, one: bool) -> naga::Literal {
    match scalar.kind {
        naga::ScalarKind::Sint => naga::Literal::I32(one as i32),
        naga::ScalarKind::Uint => naga::Literal::U32(one as u32),
        naga::ScalarKind::Bool => naga::Literal::Bool(one),
        _ => naga::Literal::F32(if one { 1.0 } else { 0.0 }),
    }
}

/// Each return's value taken apart into the new struct's members
fn rewrite_returns(block: &mut Block, expressions: &mut naga::Arena<Expression>, sources: &[Source], single: bool, ty: Handle<Type>) {
    let mut i = 0;
    while i < block.len() {
        let mut insert = None;
        match &mut block[i] {
            Statement::Return { value: Some(value) } => {
                // (the literals of widened members first: they are not emitted)
                let mut pads = Vec::new();
                for source in sources {
                    if let Some((scalar, count, _)) = source.widen {
                        let pad: Vec<Handle<Expression>> = (count..4).map(|c| expressions.append(Expression::Literal(literal(scalar, c == 3)), Span::UNDEFINED)).collect();
                        pads.push(pad);
                    }
                    else {
                        pads.push(Vec::new());
                    }
                }
                let first = expressions.len();
                let v = *value;
                // the original members' values: the compose's components, or indexed
                let components: Option<Vec<Handle<Expression>>> = match expressions[v] {
                    Expression::Compose { ref components, .. } if !single => Some(components.clone()),
                    _ => None,
                };
                let member = |expressions: &mut naga::Arena<Expression>, m: usize| -> Handle<Expression> {
                    if single {
                        return v;
                    }
                    match &components {
                        Some(c) => c[m],
                        None => expressions.append(Expression::AccessIndex { base: v, index: m as u32 }, Span::UNDEFINED),
                    }
                };
                let mut parts = Vec::new();
                for (source, pad) in sources.iter().zip(&pads) {
                    let mut h = member(expressions, source.member);
                    for &index in &source.path {
                        h = expressions.append(Expression::AccessIndex { base: h, index }, Span::UNDEFINED);
                    }
                    if let Some((_, _, wide)) = source.widen {
                        let mut components = Vec::from([h]);
                        components.extend(pad.iter().copied());
                        h = expressions.append(Expression::Compose { ty: wide, components }, Span::UNDEFINED);
                    }
                    parts.push(h);
                }
                let new_value = expressions.append(Expression::Compose { ty, components: parts }, Span::UNDEFINED);
                *value = new_value;
                insert = Some(Statement::Emit(expressions.range_from(first)));
            },
            Statement::Block(b) => rewrite_returns(b, expressions, sources, single, ty),
            Statement::If { accept, reject, .. } => {
                rewrite_returns(accept, expressions, sources, single, ty);
                rewrite_returns(reject, expressions, sources, single, ty);
            },
            Statement::Loop { body, continuing, .. } => {
                rewrite_returns(body, expressions, sources, single, ty);
                rewrite_returns(continuing, expressions, sources, single, ty);
            },
            Statement::Switch { cases, .. } => {
                for case in cases.iter_mut() {
                    rewrite_returns(&mut case.body, expressions, sources, single, ty);
                }
            },
            _ => {},
        }
        if let Some(emit) = insert {
            block.splice(i..i, Block::from_vec(Vec::from([emit])));
            i += 1;
        }
        i += 1;
    }
}
                                                                                                                                                                                                                                                                                                     source/v64/src/browser/glbridge/vx/naga/src/layers.rs                                               0000644 0000000 0000000 00000012343 00000000000 017717  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The size of an array image with its layers: SPIR-V's OpImageQuerySize(Lod)
//! of one has the layer count as its last component, which naga's SPIR-V
//! front end leaves out (a 2D array's size comes out as 2 components where
//! the shader takes 3). Each such query becomes the vector of the size's
//! components and the image's `NumLayers`, in the query's own place (its
//! users unchanged), the new expressions put before it (remap.rs).
//!
//! And the layer of a sample of an array image: SPIR-V's is the coordinate's
//! last component rounded, floor(z + 0.5), naga's front end converts it to
//! an integer (truncating); the conversion gets floor(z + 0.5).

use alloc::vec::Vec;
use naga::{Expression, Function, Handle, ImageQuery, Scalar, Span, Type, TypeInner, VectorSize};

/// The array image type an image expression has, if it has one: (dimension's components)
fn arrayed(module: &naga::Module, function: &Function, image: Handle<Expression>) -> Option<u32> {
    let ty = match function.expressions[image] {
        Expression::GlobalVariable(g) => module.global_variables[g].ty,
        Expression::FunctionArgument(i) => function.arguments.get(i as usize)?.ty,
        _ => return None,
    };
    match module.types[ty].inner {
        TypeInner::Image { dim, arrayed: true, .. } => Some(match dim {
            naga::ImageDimension::D1 => 1,
            _ => 2,
        }),
        _ => None,
    }
}

fn fix(module: &mut naga::Module, function: &mut Function) {
    let queries: Vec<(Handle<Expression>, Handle<Expression>, Option<Handle<Expression>>, u32)> = function.expressions.iter()
        .filter_map(|(h, e)| match *e {
            Expression::ImageQuery { image, query: ImageQuery::Size { level } } => arrayed(module, function, image).map(|n| (h, image, level, n)),
            _ => None,
        })
        .collect();
    if queries.is_empty() {
        return;
    }
    let mut f = function.clone();
    let mut moves = Vec::new();
    for (q, image, level, n) in queries {
        let size = f.expressions.append(Expression::ImageQuery { image, query: ImageQuery::Size { level } }, Span::UNDEFINED);
        let mut components = Vec::new();
        moves.push((size, q));
        if n == 1 {
            components.push(size);
        }
        else {
            for i in 0..n {
                let c = f.expressions.append(Expression::AccessIndex { base: size, index: i }, Span::UNDEFINED);
                moves.push((c, q));
                components.push(c);
            }
        }
        let layers = f.expressions.append(Expression::ImageQuery { image, query: ImageQuery::NumLayers }, Span::UNDEFINED);
        moves.push((layers, q));
        components.push(layers);
        let size_n = if n == 1 { VectorSize::Bi } else { VectorSize::Tri };
        let ty = module.types.insert(Type { name: None, inner: TypeInner::Vector { size: size_n, scalar: Scalar::U32 } }, Span::UNDEFINED);
        f.expressions[q] = Expression::Compose { ty, components };
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
}

/// The function's samples' layers rounded (the layer naga converts with `As`)
fn round_layers(function: &mut Function) {
    let layers: Vec<(Handle<Expression>, Handle<Expression>, Handle<Expression>)> = function.expressions.iter().filter_map(|(_, e)| match *e {
        Expression::ImageSample { image, array_index: Some(index), .. } => match function.expressions[index] {
            Expression::As { expr, kind: naga::ScalarKind::Sint, convert: Some(4) } => Some((index, expr, image)),
            _ => None,
        },
        _ => None,
    }).collect();
    if layers.is_empty() {
        return;
    }
    let mut f = function.clone();
    let mut moves = Vec::new();
    let mut done = alloc::collections::BTreeSet::new();
    for (index, z, image) in layers {
        if !done.insert(index) {
            continue;
        }
        // (the literal before the image's expression: outside of every emit range)
        let half = f.expressions.append(Expression::Literal(naga::Literal::F32(0.5)), Span::UNDEFINED);
        moves.push((half, image));
        let sum = f.expressions.append(Expression::Binary { op: naga::BinaryOperator::Add, left: z, right: half }, Span::UNDEFINED);
        let floor = f.expressions.append(Expression::Math { fun: naga::MathFunction::Floor, arg: sum, arg1: None, arg2: None, arg3: None }, Span::UNDEFINED);
        moves.push((sum, index));
        moves.push((floor, index));
        f.expressions[index] = Expression::As { expr: floor, kind: naga::ScalarKind::Sint, convert: Some(4) };
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
}

/// Every function's queries of array images' sizes made whole, and its samples' layers rounded
pub fn lower(module: &mut naga::Module) {
    let handles: Vec<Handle<naga::Function>> = module.functions.iter().map(|(h, _)| h).collect();
    for h in handles {
        let mut f = core::mem::take(&mut module.functions[h]);
        fix(module, &mut f);
        round_layers(&mut f);
        module.functions[h] = f;
    }
    for e in 0..module.entry_points.len() {
        let mut f = core::mem::take(&mut module.entry_points[e].function);
        fix(module, &mut f);
        round_layers(&mut f);
        module.entry_points[e].function = f;
    }
}
                                                                                                                                                                                                                                                                                             source/v64/src/browser/glbridge/vx/naga/src/layout.rs                                               0000644 0000000 0000000 00000131754 00000000000 017745  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Matrices of explicitly laid out blocks that naga cannot read: column
//! major ones whose columns are not their natural stride apart (std140's
//! mat2, mat3x2 and mat4x2: 2-row columns 16 bytes apart; naga refuses
//! them), and row major ones (naga keeps their type and transposes on load,
//! right for square ones only). Such a member (or an array of them) becomes
//! an array of 4-component vectors at the matrix stride (2-component ones
//! for a row major one whose rows are 8 bytes apart, std430's): the
//! columns of a column major one, the rows of a row major one, as they are
//! in memory. The accesses become:
//! - a load of the matrix: a load of the array, the matrix made of its
//!   vectors (their first components, or across them for a row major one);
//! - a load of a column: of its vector (column major), or of each row's
//!   component (row major);
//! - an element's pointer: the vector's component (column major), the row's
//!   (row major: the indices swapped);
//! - a load of a struct or array holding such members: member by member;
//! - a store (storage blocks'): component by component, of the matrix, a
//!   column, a struct or array holding such members (the padding of a
//!   vector stays as it was).
//!
//! An unsized array (a storage block's last member) of such matrices or
//! elements is done over the same way, its length (OpArrayLength) the
//! same: its elements stay as far apart.
//!
//! Arrays of scalars and 2-component vectors 16 bytes apart (std140's
//! `float a[4]`, `vec2 b[2]`; WGSL's are 4 and 8 apart, and naga writes
//! them so) are done over the same way, as column major "matrices" whose
//! columns are the elements: arrays of 4-component vectors, an element the
//! first components of its vector.
//!
//! The blocks get copies of their structs (and arrays) with the vectors
//! (`storage_of`), the originals stay for values, without their layout. A
//! module with an access this does not do (a copy of memory, an atomic,
//! such a pointer passed to a function) is left as it was.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

use crate::blockarrays::names;

const OP_TYPE_INT: u32 = 21;
const OP_TYPE_FLOAT: u32 = 22;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_MATRIX: u32 = 24;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_RUNTIME_ARRAY: u32 = 29;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_LOAD: u32 = 61;
const OP_STORE: u32 = 62;
const OP_ACCESS_CHAIN: u32 = 65;
const OP_ARRAY_LENGTH: u32 = 68;
const OP_IN_BOUNDS_ACCESS_CHAIN: u32 = 66;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const OP_VECTOR_SHUFFLE: u32 = 79;
const OP_COMPOSITE_CONSTRUCT: u32 = 80;
const OP_COMPOSITE_EXTRACT: u32 = 81;

const DECORATION_ROW_MAJOR: u32 = 4;
const DECORATION_COL_MAJOR: u32 = 5;
const DECORATION_ARRAY_STRIDE: u32 = 6;
const DECORATION_MATRIX_STRIDE: u32 = 7;
const DECORATION_BLOCK: u32 = 2;
const DECORATION_BUFFER_BLOCK: u32 = 3;
const DECORATION_OFFSET: u32 = 35;

/// The storage classes of explicitly laid out memory: Uniform, PushConstant, StorageBuffer, PhysicalStorageBuffer
fn laid_out(class: u32) -> bool { matches!(class, 2 | 9 | 12 | 5349) }

/// The opcodes before the types: the header, debug information and annotations
fn preamble(op: u32) -> bool { matches!(op, 2..=7 | 10 | 11 | 14..=17 | 71..=75 | 330..=332 | 5632 | 5633) }

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// A matrix member done over: its matrix, how it is stored, the arrays around it
#[derive(Clone)]
struct Bad {
    /// the matrix type, its column type, the float type
    matrix: u32,
    column: u32,
    float: u32,
    columns: u32,
    rows: u32,
    row_major: bool,
    /// the stored vectors: how many, their type (4 components), the array of them
    vectors: u32,
    vector: u32,
    stored: u32,
    /// the arrays around the matrix, outermost first, and their storage copies
    wrappers: Vec<u32>,
    wrapper_storage: Vec<u32>,
    /// an array of padded elements (`matrix` the array, `column` the element), not a matrix
    padded: bool,
}

/// What a pointer this pass follows points at
#[derive(Clone)]
enum Ptr {
    /// a struct or array holding such members (`ty`, the value type; the pointer itself points at its storage copy)
    Copied { ty: u32, class: u32 },
    /// into a member done over, `depth` arrays in (at the matrix when depth is the arrays' count)
    Member { bad: usize, depth: usize, class: u32 },
    /// a column of a column major one (a pointer to its stored vector)
    Column { bad: usize, class: u32 },
    /// a column of a row major one: no pointer of its own, the matrix's and the column's index
    RowColumn { bad: usize, class: u32, matrix: u32, column: u32 },
}

struct Lowering {
    instructions: Vec<Vec<u32>>,
    bound: u32,
    /// type and constant declarations by id
    types: BTreeMap<u32, Vec<u32>>,
    constants: BTreeMap<u32, (u32, u32)>,
    member_decorations: BTreeMap<(u32, u32), Vec<Vec<u32>>>,
    decorations: BTreeMap<u32, Vec<Vec<u32>>>,
    /// the members done over, by (struct, member)
    bads: Vec<Bad>,
    bad_of: BTreeMap<(u32, u32), usize>,
    copy_memo: BTreeMap<u32, bool>,
    storage_memo: BTreeMap<u32, u32>,
    /// new declarations and annotations
    new_globals: Vec<Vec<u32>>,
    new_annotations: Vec<Vec<u32>>,
    /// pointer types (class, pointee) and vector types, existing or new
    pointers: BTreeMap<(u32, u32), u32>,
    vectors: BTreeMap<(u32, u32), u32>,
    uint: Option<u32>,
}

impl Lowering {
    fn op(w: &[u32]) -> u32 { w[0] & 0xFFFF }

    fn fresh(&mut self) -> u32 {
        let id = self.bound;
        self.bound += 1;
        id
    }

    fn new(words: &[u32]) -> Option<Lowering> {
        if words.len() < 5 {
            return None;
        }
        let mut instructions = Vec::new();
        let mut at = 5;
        while at < words.len() {
            let count = (words[at] >> 16) as usize;
            if count == 0 || at + count > words.len() {
                return None;
            }
            instructions.push(words[at..at + count].to_vec());
            at += count;
        }
        let mut l = Lowering {
            instructions,
            bound: words[3],
            types: BTreeMap::new(),
            constants: BTreeMap::new(),
            member_decorations: BTreeMap::new(),
            decorations: BTreeMap::new(),
            bads: Vec::new(),
            bad_of: BTreeMap::new(),
            copy_memo: BTreeMap::new(),
            storage_memo: BTreeMap::new(),
            new_globals: Vec::new(),
            new_annotations: Vec::new(),
            pointers: BTreeMap::new(),
            vectors: BTreeMap::new(),
            uint: None,
        };
        for w in &l.instructions {
            match Lowering::op(w) {
                op @ 19..=39 if w.len() >= 2 => {
                    l.types.insert(w[1], w.clone());
                    if op == OP_TYPE_POINTER && w.len() >= 4 {
                        l.pointers.entry((w[2], w[3])).or_insert(w[1]);
                    }
                    if op == OP_TYPE_VECTOR && w.len() >= 4 {
                        l.vectors.entry((w[2], w[3])).or_insert(w[1]);
                    }
                    if op == OP_TYPE_INT && w.len() >= 4 && w[2] == 32 && w[3] == 0 {
                        l.uint = Some(w[1]);
                    }
                },
                OP_CONSTANT if w.len() == 4 => {
                    l.constants.insert(w[2], (w[1], w[3]));
                },
                OP_DECORATE if w.len() >= 3 => l.decorations.entry(w[1]).or_default().push(w.clone()),
                OP_MEMBER_DECORATE if w.len() >= 4 => l.member_decorations.entry((w[1], w[2])).or_default().push(w.clone()),
                _ => {},
            }
        }
        Some(l)
    }

    fn type_op(&self, id: u32) -> u32 { self.types.get(&id).map_or(0, |w| Lowering::op(w)) }

    fn member_decoration(&self, s: u32, m: u32, decoration: u32) -> Option<u32> {
        self.member_decorations.get(&(s, m))?.iter().find(|w| w[3] == decoration).map(|w| *w.get(4).unwrap_or(&0))
    }

    fn array_stride(&self, id: u32) -> Option<u32> {
        self.decorations.get(&id)?.iter().find(|w| w[2] == DECORATION_ARRAY_STRIDE).and_then(|w| w.get(3).copied())
    }

    /// An integer constant's value
    fn constant_value(&self, id: u32) -> Option<u32> {
        let (ty, value) = *self.constants.get(&id)?;
        if self.type_op(ty) == OP_TYPE_INT && self.types[&ty][2] == 32 { Some(value) } else { None }
    }

    /// A 32-bit integer constant of `value`, existing or new
    fn constant(&mut self, value: u32) -> u32 {
        if let Some((&id, _)) = self.constants.iter().find(|(&id, &(ty, v))| v == value && self.constant_value(id).is_some() && {
            let w = &self.types[&ty];
            w[3] == 0
        }) {
            return id;
        }
        let uint = match self.uint {
            Some(id) => id,
            None => {
                let id = self.fresh();
                self.new_globals.push(instruction(OP_TYPE_INT, &[id, 32, 0]));
                self.types.insert(id, instruction(OP_TYPE_INT, &[id, 32, 0]));
                self.uint = Some(id);
                id
            },
        };
        let id = self.fresh();
        self.new_globals.push(instruction(OP_CONSTANT, &[uint, id, value]));
        self.constants.insert(id, (uint, value));
        id
    }

    fn pointer(&mut self, class: u32, pointee: u32) -> u32 {
        if let Some(&id) = self.pointers.get(&(class, pointee)) {
            return id;
        }
        let id = self.fresh();
        let w = instruction(OP_TYPE_POINTER, &[id, class, pointee]);
        self.new_globals.push(w.clone());
        self.types.insert(id, w);
        self.pointers.insert((class, pointee), id);
        id
    }

    fn vector(&mut self, component: u32, count: u32) -> u32 {
        if let Some(&id) = self.vectors.get(&(component, count)) {
            return id;
        }
        let id = self.fresh();
        let w = instruction(OP_TYPE_VECTOR, &[id, component, count]);
        self.new_globals.push(w.clone());
        self.types.insert(id, w);
        self.vectors.insert((component, count), id);
        id
    }

    /// An array type of `length` (a constant's id), or a runtime array for None
    fn array(&mut self, element: u32, length: Option<u32>, stride: u32) -> u32 {
        let id = self.fresh();
        let w = match length {
            Some(length) => instruction(OP_TYPE_ARRAY, &[id, element, length]),
            None => instruction(OP_TYPE_RUNTIME_ARRAY, &[id, element]),
        };
        self.new_globals.push(w.clone());
        self.types.insert(id, w);
        self.new_annotations.push(instruction(OP_DECORATE, &[id, DECORATION_ARRAY_STRIDE, stride]));
        id
    }

    /// The member `m` of struct `s` done over, if it is one of those matrices (or arrays of them)
    fn find_bad(&mut self, s: u32, m: u32, member_type: u32) -> Option<usize> {
        if let Some(&b) = self.bad_of.get(&(s, m)) {
            return Some(b);
        }
        if let Some(b) = self.find_padded(s, m, member_type) {
            return Some(b);
        }
        let stride = self.member_decoration(s, m, DECORATION_MATRIX_STRIDE)?;
        let row_major = self.member_decoration(s, m, DECORATION_ROW_MAJOR).is_some();
        let mut wrappers = Vec::new();
        let mut ty = member_type;
        while matches!(self.type_op(ty), OP_TYPE_ARRAY | OP_TYPE_RUNTIME_ARRAY) {
            wrappers.push(ty);
            ty = self.types[&ty][2];
        }
        if self.type_op(ty) != OP_TYPE_MATRIX {
            return None;
        }
        let (column, columns) = (self.types[&ty][2], self.types[&ty][3]);
        if self.type_op(column) != OP_TYPE_VECTOR {
            return None;
        }
        let (float, rows) = (self.types[&column][2], self.types[&column][3]);
        if self.type_op(float) != OP_TYPE_FLOAT || self.types[&float][2] != 32 {
            return None;
        }
        let natural = if rows == 2 { 8 } else { 16 };
        if !row_major && stride == natural {
            return None;
        }
        // (the stored vectors: 4 components a stride of 16, each needing at most 4; a row major one's rows of 2 8 apart)
        let width = if row_major { columns } else { rows };
        let components = if stride == 16 && width <= 4 { 4 } else if stride == 8 && width == 2 && row_major { 2 } else { return None };
        if wrappers.iter().any(|&w| self.array_stride(w).is_none()) {
            return None;
        }
        let vectors = if row_major { rows } else { columns };
        let vector = self.vector(float, components);
        let length = self.constant(vectors);
        let stored = self.array(vector, Some(length), stride);
        // the arrays around it, innermost first
        let mut wrapper_storage = Vec::new();
        let mut inner = stored;
        for &w in wrappers.iter().rev() {
            let (length, stride) = (self.types[&w].get(3).copied(), self.array_stride(w).unwrap_or(0));
            inner = self.array(inner, length, stride);
            wrapper_storage.push(inner);
        }
        wrapper_storage.reverse();
        let b = self.bads.len();
        self.bads.push(Bad { matrix: ty, column, float, columns, rows, row_major, vectors, vector, stored, wrappers, wrapper_storage, padded: false });
        self.bad_of.insert((s, m), b);
        Some(b)
    }

    /// The member `m` of struct `s` done over if it is an array of padded elements (or arrays of them)
    fn find_padded(&mut self, s: u32, m: u32, member_type: u32) -> Option<usize> {
        // the arrays around the innermost one
        let mut wrappers = Vec::new();
        let mut ty = member_type;
        while matches!(self.type_op(ty), OP_TYPE_ARRAY | OP_TYPE_RUNTIME_ARRAY) && self.type_op(self.types[&ty][2]) == OP_TYPE_ARRAY {
            wrappers.push(ty);
            ty = self.types[&ty][2];
        }
        if !matches!(self.type_op(ty), OP_TYPE_ARRAY | OP_TYPE_RUNTIME_ARRAY) || self.array_stride(ty) != Some(16) {
            return None;
        }
        let element = self.types[&ty][2];
        let (scalar, rows) = match self.type_op(element) {
            OP_TYPE_INT | OP_TYPE_FLOAT => (element, 1),
            OP_TYPE_VECTOR if self.types[&element][3] == 2 => (self.types[&element][2], 2),
            _ => return None,
        };
        if !matches!(self.type_op(scalar), OP_TYPE_INT | OP_TYPE_FLOAT) || self.types[&scalar][2] != 32 || wrappers.iter().any(|&w| self.array_stride(w).is_none()) {
            return None;
        }
        // (a runtime array's elements: none to load or store whole)
        let length = self.types[&ty].get(3).copied();
        let columns = match length {
            Some(l) => self.constant_value(l)?,
            None => 0,
        };
        let vector = self.vector(scalar, 4);
        let stored = self.array(vector, length, 16);
        let mut wrapper_storage = Vec::new();
        let mut inner = stored;
        for &w in wrappers.iter().rev() {
            let (length, stride) = (self.types[&w].get(3).copied(), self.array_stride(w).unwrap_or(0));
            inner = self.array(inner, length, stride);
            wrapper_storage.push(inner);
        }
        wrapper_storage.reverse();
        let b = self.bads.len();
        self.bads.push(Bad { matrix: ty, column: element, float: scalar, columns, rows, row_major: false, vectors: columns, vector, stored, wrappers,
            wrapper_storage, padded: true });
        self.bad_of.insert((s, m), b);
        Some(b)
    }

    /// Whether a type holds members done over (so its blocks get a copy of it)
    fn needs_copy(&mut self, ty: u32) -> bool {
        if let Some(&n) = self.copy_memo.get(&ty) {
            return n;
        }
        self.copy_memo.insert(ty, false);
        let n = match self.type_op(ty) {
            OP_TYPE_STRUCT => {
                let members = self.types[&ty][2..].to_vec();
                let mut any = false;
                for (m, &mt) in members.iter().enumerate() {
                    if self.find_bad(ty, m as u32, mt).is_some() || self.needs_copy(mt) {
                        any = true;
                    }
                }
                any
            },
            OP_TYPE_ARRAY | OP_TYPE_RUNTIME_ARRAY => {
                let element = self.types[&ty][2];
                self.needs_copy(element)
            },
            _ => false,
        };
        self.copy_memo.insert(ty, n);
        n
    }

    /// The storage copy of a type that needs one
    fn storage_of(&mut self, ty: u32) -> u32 {
        if let Some(&id) = self.storage_memo.get(&ty) {
            return id;
        }
        let w = self.types[&ty].clone();
        let id = self.fresh();
        self.storage_memo.insert(ty, id);
        match Lowering::op(&w) {
            OP_TYPE_STRUCT => {
                let mut members = Vec::new();
                for (m, &mt) in w[2..].iter().enumerate() {
                    let m = m as u32;
                    members.push(if let Some(b) = self.find_bad(ty, m, mt) {
                        self.bads[b].wrapper_storage.first().copied().unwrap_or(self.bads[b].stored)
                    }
                    else if self.needs_copy(mt) {
                        self.storage_of(mt)
                    }
                    else {
                        mt
                    });
                    // the member's decorations: those of the matrix go with it
                    let bad = self.bad_of.contains_key(&(ty, m));
                    for d in self.member_decorations.get(&(ty, m)).cloned().unwrap_or_default() {
                        if bad && matches!(d[3], DECORATION_ROW_MAJOR | DECORATION_COL_MAJOR | DECORATION_MATRIX_STRIDE) {
                            continue;
                        }
                        let mut d = d.clone();
                        d[1] = id;
                        self.new_annotations.push(d);
                    }
                }
                let mut operands = Vec::from([id]);
                operands.extend(members);
                let s = instruction(OP_TYPE_STRUCT, &operands);
                self.new_globals.push(s.clone());
                self.types.insert(id, s);
                for d in self.decorations.get(&ty).cloned().unwrap_or_default() {
                    let mut d = d.clone();
                    d[1] = id;
                    self.new_annotations.push(d);
                }
            },
            op => {
                let element = self.storage_of(w[2]);
                let a = if op == OP_TYPE_ARRAY { instruction(OP_TYPE_ARRAY, &[id, element, w[3]]) } else { instruction(OP_TYPE_RUNTIME_ARRAY, &[id, element]) };
                self.new_globals.push(a.clone());
                self.types.insert(id, a);
                if let Some(stride) = self.array_stride(ty) {
                    self.new_annotations.push(instruction(OP_DECORATE, &[id, DECORATION_ARRAY_STRIDE, stride]));
                }
            },
        }
        id
    }

    /// The type a pointer into member `b` points at, `depth` arrays in
    fn member_storage(&self, b: usize, depth: usize) -> u32 {
        let bad = &self.bads[b];
        bad.wrapper_storage.get(depth).copied().unwrap_or(bad.stored)
    }

    /// The value type there
    fn member_value(&self, b: usize, depth: usize) -> u32 {
        let bad = &self.bads[b];
        bad.wrappers.get(depth).copied().unwrap_or(bad.matrix)
    }

    fn run(mut self) -> Option<(Vec<u32>, u32)> {
        // the variables of laid out memory, and the pointer types to redirect
        let mut ptrs: BTreeMap<u32, Ptr> = BTreeMap::new();
        let mut redirect: BTreeMap<u32, u32> = BTreeMap::new();
        let pointer_types: Vec<(u32, u32, u32)> = self.types.values().filter(|w| Lowering::op(w) == OP_TYPE_POINTER && w.len() >= 4)
            .map(|w| (w[1], w[2], w[3])).collect();
        for (id, class, pointee) in pointer_types {
            if laid_out(class) && self.needs_copy(pointee) {
                let storage = self.storage_of(pointee);
                let p = self.pointer(class, storage);
                redirect.insert(id, p);
            }
        }
        if self.bads.is_empty() {
            return None;
        }
        let pointer_info = |types: &BTreeMap<u32, Vec<u32>>, ty: u32| types.get(&ty).filter(|w| Lowering::op(w) == OP_TYPE_POINTER).map(|w| (w[2], w[3]));
        for w in &self.instructions {
            if Lowering::op(w) == OP_VARIABLE && w.len() >= 4 {
                if let Some((class, pointee)) = pointer_info(&self.types, w[1]) {
                    if laid_out(class) && *self.copy_memo.get(&pointee).unwrap_or(&false) {
                        ptrs.insert(w[2], Ptr::Copied { ty: pointee, class });
                    }
                }
            }
        }
        // the functions
        let first_function = self.instructions.iter().position(|w| Lowering::op(w) == OP_FUNCTION).unwrap_or(self.instructions.len());
        let mut body = Vec::new();
        let instructions = core::mem::take(&mut self.instructions);
        for w in &instructions[first_function..] {
            let op = Lowering::op(w);
            match op {
                OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN if w.len() >= 4 && ptrs.contains_key(&w[3]) => {
                    self.chain(w, &mut ptrs, &mut body)?;
                },
                OP_LOAD if w.len() >= 4 && ptrs.contains_key(&w[3]) => {
                    if w.len() > 4 && w[4] != 0 && w[4] != 2 {
                        // (memory operands other than Aligned: not done)
                        return None;
                    }
                    let info = ptrs[&w[3]].clone();
                    self.load(w[1], w[2], w[3], &info, &mut body)?;
                },
                // (an unsized array's length: its copy's, the elements as far apart)
                OP_ARRAY_LENGTH if w.len() == 5 && matches!(ptrs.get(&w[3]), Some(Ptr::Copied { .. })) => body.push(w.clone()),
                OP_STORE if w.len() >= 3 && ptrs.contains_key(&w[1]) && !ptrs.contains_key(&w[2]) => {
                    if w.len() > 3 && w[3] != 0 && w[3] != 2 {
                        return None;
                    }
                    let info = ptrs[&w[1]].clone();
                    self.store(w[1], w[2], &info, &mut body)?;
                },
                _ => {
                    // another use of a pointer followed here: not done
                    if w[1..].iter().any(|id| ptrs.contains_key(id)) {
                        return None;
                    }
                    let mut w = w.clone();
                    if w.len() >= 3 && matches!(op, 1 | 55 | 59 | 83 | 169 | 245) {
                        if let Some(&p) = redirect.get(&w[1]) {
                            w[1] = p;
                        }
                    }
                    body.push(w);
                },
            }
        }
        let out = self.assemble(&instructions[..first_function], &redirect, body);
        Some((out, self.bound))
    }

    /// An access chain from a pointer followed here
    fn chain(&mut self, w: &[u32], ptrs: &mut BTreeMap<u32, Ptr>, body: &mut Vec<Vec<u32>>) -> Option<()> {
        let (result, base) = (w[2], w[3]);
        let mut state = Some(ptrs[&base].clone());
        // the chain to emit: its base and indices
        let mut root = base;
        if let Some(Ptr::RowColumn { matrix, .. }) = state {
            root = matrix;
        }
        let mut emitted: Vec<u32> = Vec::new();
        for &index in &w[4..] {
            // (None: out of the kinds followed here, a plain pointer)
            let Some(current) = state.clone() else {
                emitted.push(index);
                continue;
            };
            state = match current {
                Ptr::Copied { ty, class } => {
                    emitted.push(index);
                    let t = self.types[&ty].clone();
                    if Lowering::op(&t) == OP_TYPE_STRUCT {
                        let m = self.constant_value(index)?;
                        let mt = *t.get(2 + m as usize)?;
                        if let Some(&bad) = self.bad_of.get(&(ty, m)) {
                            Some(Ptr::Member { bad, depth: 0, class })
                        }
                        else if *self.copy_memo.get(&mt).unwrap_or(&false) {
                            Some(Ptr::Copied { ty: mt, class })
                        }
                        else {
                            None
                        }
                    }
                    else if *self.copy_memo.get(&t[2]).unwrap_or(&false) {
                        Some(Ptr::Copied { ty: t[2], class })
                    }
                    else {
                        None
                    }
                },
                Ptr::Member { bad, depth, class } => {
                    if depth < self.bads[bad].wrappers.len() {
                        emitted.push(index);
                        Some(Ptr::Member { bad, depth: depth + 1, class })
                    }
                    else if self.bads[bad].row_major {
                        // (a column of a row major one: its index goes after the row's)
                        Some(Ptr::RowColumn { bad, class, matrix: 0, column: index })
                    }
                    else {
                        emitted.push(index);
                        Some(Ptr::Column { bad, class })
                    }
                },
                Ptr::Column { .. } => {
                    emitted.push(index);
                    None
                },
                Ptr::RowColumn { column, .. } => {
                    // an element: the row's component
                    emitted.push(index);
                    emitted.push(column);
                    None
                },
            };
        }
        let chain_op = Lowering::op(w);
        let emit = |ty: u32, id: u32, root: u32, emitted: &[u32], body: &mut Vec<Vec<u32>>| {
            let mut operands = Vec::from([ty, id, root]);
            operands.extend_from_slice(emitted);
            body.push(instruction(chain_op, &operands));
        };
        match state {
            // (a pointer of the type the chain had)
            None => emit(w[1], result, root, &emitted, body),
            Some(Ptr::Copied { ty, class }) => {
                let storage = self.storage_of(ty);
                let p = self.pointer(class, storage);
                emit(p, result, root, &emitted, body);
                ptrs.insert(result, Ptr::Copied { ty, class });
            },
            Some(Ptr::Member { bad, depth, class }) => {
                let storage = self.member_storage(bad, depth);
                let p = self.pointer(class, storage);
                emit(p, result, root, &emitted, body);
                ptrs.insert(result, Ptr::Member { bad, depth, class });
            },
            Some(Ptr::Column { bad, class }) => {
                let vector = self.bads[bad].vector;
                let p = self.pointer(class, vector);
                emit(p, result, root, &emitted, body);
                ptrs.insert(result, Ptr::Column { bad, class });
            },
            Some(Ptr::RowColumn { bad, class, column, .. }) => {
                // the matrix's pointer, the column for the loads
                let stored = self.bads[bad].stored;
                let p = self.pointer(class, stored);
                let matrix = self.fresh();
                emit(p, matrix, root, &emitted, body);
                ptrs.insert(result, Ptr::RowColumn { bad, class, matrix, column });
            },
        }
        Some(())
    }

    /// A load through a pointer followed here, into `result` of type `ty`
    fn load(&mut self, ty: u32, result: u32, pointer: u32, info: &Ptr, body: &mut Vec<Vec<u32>>) -> Option<()> {
        match *info {
            Ptr::Copied { ty: value, class } => self.load_value(pointer, value, class, ty, result, body),
            Ptr::Member { bad, depth, class } => self.load_member(pointer, bad, depth, class, result, body),
            Ptr::Column { bad, .. } => {
                let (vector, rows) = (self.bads[bad].vector, self.bads[bad].rows);
                let loaded = if rows == 4 { result } else { self.fresh() };
                body.push(instruction(OP_LOAD, &[vector, loaded, pointer]));
                if rows == 1 {
                    // (a padded scalar: the vector's first component)
                    body.push(instruction(OP_COMPOSITE_EXTRACT, &[ty, result, loaded, 0]));
                }
                else if rows != 4 {
                    let mut operands = Vec::from([ty, result, loaded, loaded]);
                    operands.extend(0..rows);
                    body.push(instruction(OP_VECTOR_SHUFFLE, &operands));
                }
                Some(())
            },
            Ptr::RowColumn { bad, class, matrix, column } => {
                let (float, rows) = (self.bads[bad].float, self.bads[bad].rows);
                let p = self.pointer(class, float);
                let mut components = Vec::new();
                for r in 0..rows {
                    let (index, at, value) = (self.constant(r), self.fresh(), self.fresh());
                    body.push(instruction(OP_ACCESS_CHAIN, &[p, at, matrix, index, column]));
                    body.push(instruction(OP_LOAD, &[float, value, at]));
                    components.push(value);
                }
                let mut operands = Vec::from([ty, result]);
                operands.extend(components);
                body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
                Some(())
            },
        }
    }

    /// A store through a pointer followed here of `object`: component by component where vectors are stored
    fn store(&mut self, pointer: u32, object: u32, info: &Ptr, body: &mut Vec<Vec<u32>>) -> Option<()> {
        match *info {
            Ptr::Copied { ty: value, class } => self.store_value(pointer, value, class, object, body),
            Ptr::Member { bad, depth, class } => self.store_member(pointer, bad, depth, class, object, body),
            Ptr::Column { bad, class } => {
                let (float, rows) = (self.bads[bad].float, self.bads[bad].rows);
                let p = self.pointer(class, float);
                for r in 0..rows {
                    let x = if rows == 1 { object } else { self.extract(float, object, r, body) };
                    let (index, at) = (self.constant(r), self.fresh());
                    body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                    body.push(instruction(OP_STORE, &[at, x]));
                }
                Some(())
            },
            Ptr::RowColumn { bad, class, matrix, column } => {
                let (float, rows) = (self.bads[bad].float, self.bads[bad].rows);
                let p = self.pointer(class, float);
                for r in 0..rows {
                    let x = self.extract(float, object, r, body);
                    let (index, at) = (self.constant(r), self.fresh());
                    body.push(instruction(OP_ACCESS_CHAIN, &[p, at, matrix, index, column]));
                    body.push(instruction(OP_STORE, &[at, x]));
                }
                Some(())
            },
        }
    }

    /// A part of a composite value
    fn extract(&mut self, ty: u32, composite: u32, index: u32, body: &mut Vec<Vec<u32>>) -> u32 {
        let id = self.fresh();
        body.push(instruction(OP_COMPOSITE_EXTRACT, &[ty, id, composite, index]));
        id
    }

    /// A store of a whole struct or array holding members done over: member by member
    fn store_value(&mut self, pointer: u32, value: u32, class: u32, object: u32, body: &mut Vec<Vec<u32>>) -> Option<()> {
        let t = self.types[&value].clone();
        let parts: Vec<(u32, u32)> = match Lowering::op(&t) {
            OP_TYPE_STRUCT => t[2..].iter().enumerate().map(|(m, &mt)| (m as u32, mt)).collect(),
            OP_TYPE_ARRAY => (0..self.constant_value(t[3])?).map(|i| (i, t[2])).collect(),
            _ => return None,
        };
        let structure = Lowering::op(&t) == OP_TYPE_STRUCT;
        for (k, mt) in parts {
            let part = self.extract(mt, object, k, body);
            let index = self.constant(k);
            let at = self.fresh();
            if let Some(&b) = self.bad_of.get(&(value, k)).filter(|_| structure) {
                let p = { let s = self.member_storage(b, 0); self.pointer(class, s) };
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                self.store_member(at, b, 0, class, part, body)?;
            }
            else if *self.copy_memo.get(&mt).unwrap_or(&false) {
                let p = { let s = self.storage_of(mt); self.pointer(class, s) };
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                self.store_value(at, mt, class, part, body)?;
            }
            else {
                let p = self.pointer(class, mt);
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                body.push(instruction(OP_STORE, &[at, part]));
            }
        }
        Some(())
    }

    /// A store of a member done over (`depth` arrays in): the arrays element by element, the matrix component by component
    fn store_member(&mut self, pointer: u32, b: usize, depth: usize, class: u32, object: u32, body: &mut Vec<Vec<u32>>) -> Option<()> {
        let bad = self.bads[b].clone();
        if depth < bad.wrappers.len() {
            let length = self.types[&bad.wrappers[depth]].get(3).copied().and_then(|l| self.constant_value(l))?;
            let p = { let s = self.member_storage(b, depth + 1); self.pointer(class, s) };
            let element = self.member_value(b, depth + 1);
            for i in 0..length {
                let part = self.extract(element, object, i, body);
                let (index, at) = (self.constant(i), self.fresh());
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                self.store_member(at, b, depth + 1, class, part, body)?;
            }
            return Some(());
        }
        let p = self.pointer(class, bad.float);
        for c in 0..bad.columns {
            let column = self.extract(bad.column, object, c, body);
            for r in 0..bad.rows {
                let x = if bad.rows == 1 { column } else { self.extract(bad.float, column, r, body) };
                // (a row major one's element at its row's component)
                let (vector, component) = if bad.row_major { (r, c) } else { (c, r) };
                let (vi, ci, at) = (self.constant(vector), self.constant(component), self.fresh());
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, vi, ci]));
                body.push(instruction(OP_STORE, &[at, x]));
            }
        }
        Some(())
    }

    /// A load of a whole struct or array holding members done over: member by member
    fn load_value(&mut self, pointer: u32, value: u32, class: u32, ty: u32, result: u32, body: &mut Vec<Vec<u32>>) -> Option<()> {
        let t = self.types[&value].clone();
        let mut parts = Vec::new();
        match Lowering::op(&t) {
            OP_TYPE_STRUCT => {
                for (m, &mt) in t[2..].iter().enumerate() {
                    let m = m as u32;
                    let index = self.constant(m);
                    let (at, part) = (self.fresh(), self.fresh());
                    if let Some(&b) = self.bad_of.get(&(value, m)) {
                        let p = { let s = self.member_storage(b, 0); self.pointer(class, s) };
                        body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                        self.load_member(at, b, 0, class, part, body)?;
                    }
                    else if *self.copy_memo.get(&mt).unwrap_or(&false) {
                        let p = { let s = self.storage_of(mt); self.pointer(class, s) };
                        body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                        self.load_value(at, mt, class, mt, part, body)?;
                    }
                    else {
                        let p = self.pointer(class, mt);
                        body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                        body.push(instruction(OP_LOAD, &[mt, part, at]));
                    }
                    parts.push(part);
                }
            },
            OP_TYPE_ARRAY => {
                let element = t[2];
                let length = self.constant_value(t[3])?;
                for i in 0..length {
                    let index = self.constant(i);
                    let (at, part) = (self.fresh(), self.fresh());
                    let p = { let s = self.storage_of(element); self.pointer(class, s) };
                    body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                    self.load_value(at, element, class, element, part, body)?;
                    parts.push(part);
                }
            },
            _ => return None,
        }
        let mut operands = Vec::from([ty, result]);
        operands.extend(parts);
        body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
        Some(())
    }

    /// A load of a member done over (`depth` arrays in): the arrays element by element, the matrix of its vectors
    fn load_member(&mut self, pointer: u32, b: usize, depth: usize, class: u32, result: u32, body: &mut Vec<Vec<u32>>) -> Option<()> {
        let bad = self.bads[b].clone();
        if depth < bad.wrappers.len() {
            let length = self.types[&bad.wrappers[depth]].get(3).copied().and_then(|l| self.constant_value(l))?;
            let p = { let s = self.member_storage(b, depth + 1); self.pointer(class, s) };
            let mut parts = Vec::new();
            for i in 0..length {
                let index = self.constant(i);
                let (at, part) = (self.fresh(), self.fresh());
                body.push(instruction(OP_ACCESS_CHAIN, &[p, at, pointer, index]));
                self.load_member(at, b, depth + 1, class, part, body)?;
                parts.push(part);
            }
            let mut operands = Vec::from([self.member_value(b, depth), result]);
            operands.extend(parts);
            body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
            return Some(());
        }
        let array = self.fresh();
        body.push(instruction(OP_LOAD, &[bad.stored, array, pointer]));
        let mut vectors = Vec::new();
        for k in 0..bad.vectors {
            let v = self.fresh();
            body.push(instruction(OP_COMPOSITE_EXTRACT, &[bad.vector, v, array, k]));
            vectors.push(v);
        }
        let mut columns = Vec::new();
        for c in 0..bad.columns {
            let column = self.fresh();
            if bad.row_major {
                // across the rows
                let mut operands = Vec::from([bad.column, column]);
                for &row in &vectors {
                    let x = self.fresh();
                    body.push(instruction(OP_COMPOSITE_EXTRACT, &[bad.float, x, row, c]));
                    operands.push(x);
                }
                body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
            }
            else if bad.rows == 1 {
                body.push(instruction(OP_COMPOSITE_EXTRACT, &[bad.column, column, vectors[c as usize], 0]));
            }
            else {
                let v = vectors[c as usize];
                let mut operands = Vec::from([bad.column, column, v, v]);
                operands.extend(0..bad.rows);
                body.push(instruction(OP_VECTOR_SHUFFLE, &operands));
            }
            columns.push(column);
        }
        let mut operands = Vec::from([bad.matrix, result]);
        operands.extend(columns);
        body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
        Some(())
    }

    /// The module again: the new annotations after the old (the value
    /// types' layout dropped), the declarations each after what it uses,
    /// the variables' pointer types redirected, the functions
    fn assemble(&mut self, globals: &[Vec<u32>], redirect: &BTreeMap<u32, u32>, body: Vec<Vec<u32>>) -> Vec<u32> {
        let copied: BTreeSet<u32> = self.copy_memo.iter().filter(|(_, &n)| n).map(|(&id, _)| id).collect();
        // (and a padded array's own type: a value type now)
        let wrappers: BTreeSet<u32> = self.bads.iter().flat_map(|b| b.wrappers.iter().copied().chain(b.padded.then_some(b.matrix))).collect();
        let bad_members: BTreeSet<(u32, u32)> = self.bad_of.keys().copied().collect();
        let mut out: Vec<u32> = Vec::new();
        let header = globals.iter().position(|w| !preamble(Lowering::op(w))).unwrap_or(globals.len());
        for w in &globals[..header] {
            let op = Lowering::op(w);
            // the value types: no layout
            if op == OP_DECORATE && w.len() >= 3 && ((copied.contains(&w[1]) && matches!(w[2], DECORATION_ARRAY_STRIDE | DECORATION_BLOCK | DECORATION_BUFFER_BLOCK))
                || wrappers.contains(&w[1]) && w[2] == DECORATION_ARRAY_STRIDE) {
                continue;
            }
            if op == OP_MEMBER_DECORATE && w.len() >= 4 && (copied.contains(&w[1]) || bad_members.contains(&(w[1], w[2])))
                && matches!(w[3], DECORATION_OFFSET | DECORATION_MATRIX_STRIDE | DECORATION_ROW_MAJOR | DECORATION_COL_MAJOR) {
                continue;
            }
            out.extend_from_slice(w);
        }
        for a in &self.new_annotations {
            out.extend_from_slice(a);
        }
        // the declarations, each after the ids it uses
        let mut declarations: Vec<Vec<u32>> = globals[header..].to_vec();
        for w in declarations.iter_mut() {
            if Lowering::op(w) == OP_VARIABLE && w.len() >= 3 {
                if let Some(&p) = redirect.get(&w[1]) {
                    w[1] = p;
                }
            }
        }
        // (the pointer types the variables had, to the types now without their layout: gone where nothing else names them,
        // naga refuses a Uniform pointer to a struct of an unsized array that is no block any more)
        let named = |id: u32, declarations: &[Vec<u32>]| declarations.iter().any(|w| !(Lowering::op(w) == OP_TYPE_POINTER && w[1] == id) && names(w, id))
            || body.iter().any(|w| names(w, id));
        let dead: BTreeSet<u32> = redirect.keys().copied().filter(|&id| !named(id, &declarations)).collect();
        declarations.retain(|w| !(Lowering::op(w) == OP_TYPE_POINTER && dead.contains(&w[1])));
        let original = declarations.len();
        declarations.extend(self.new_globals.iter().cloned());
        let defined = |w: &[u32]| -> Option<u32> {
            match Lowering::op(w) {
                19..=38 | 322 | 4456 | 5341 | 6086 => w.get(1).copied(),
                39 => None,
                _ => w.get(2).copied(),
            }
        };
        let mut by_id: BTreeMap<u32, usize> = BTreeMap::new();
        for (i, w) in declarations.iter().enumerate() {
            if let Some(id) = defined(w) {
                by_id.entry(id).or_insert(i);
            }
        }
        let uses = |w: &[u32]| -> Vec<u32> {
            match Lowering::op(w) {
                OP_TYPE_INT | OP_TYPE_FLOAT | 19 | 20 => Vec::new(),
                OP_TYPE_VECTOR | OP_TYPE_MATRIX | 27 | 25 => w.get(2).copied().into_iter().collect(),
                OP_TYPE_POINTER => w.get(3).copied().into_iter().collect(),
                OP_CONSTANT | 50 | 41 | 42 | 46 | 1 => w.get(1).copied().into_iter().collect(),
                OP_VARIABLE => { let mut u = Vec::from([w[1]]); u.extend(w.get(4).copied()); u },
                op if (19..=39).contains(&op) => w[2..].to_vec(),
                _ => { let mut u = Vec::from([w[1]]); u.extend_from_slice(w.get(3..).unwrap_or(&[])); u },
            }
        };
        let mut state = Vec::from_iter(core::iter::repeat(0u8).take(declarations.len()));
        let mut order = Vec::new();
        fn visit(i: usize, declarations: &[Vec<u32>], by_id: &BTreeMap<u32, usize>, uses: &dyn Fn(&[u32]) -> Vec<u32>, state: &mut Vec<u8>, order: &mut Vec<usize>) {
            if state[i] != 0 {
                return;
            }
            state[i] = 1;
            for id in uses(&declarations[i]) {
                if let Some(&j) = by_id.get(&id) {
                    if j != i {
                        visit(j, declarations, by_id, uses, state, order);
                    }
                }
            }
            state[i] = 2;
            order.push(i);
        }
        for i in 0..declarations.len() {
            if i < original || state[i] == 0 {
                visit(i, &declarations, &by_id, &uses, &mut state, &mut order);
            }
        }
        for i in order {
            out.extend_from_slice(&declarations[i]);
        }
        for w in body {
            out.extend_from_slice(&w);
        }
        out
    }
}

/// The module with those matrices done over, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    match Lowering::new(words).and_then(|l| l.run()) {
        Some((rest, bound)) => {
            let mut out = words[..5].to_vec();
            out[3] = bound;
            out.extend(rest);
            out
        },
        None => words.to_vec(),
    }
}
                    source/v64/src/browser/glbridge/vx/naga/src/lib.rs                                                  0000644 0000000 0000000 00000106267 00000000000 017177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! SPIR-V to WGSL for VX, the renderer of virtio-gpu's Venus contexts
//! (src/browser/glbridge/vx/vx_executor.js), with naga. Built to
//! build/glbridge/vx_naga.wasm by tools/build_glbridge.mjs.
//!
//! What it changes on the way:
//! - combined image samplers become an image and a sampler (split.rs)
//! - NaN and infinity tests become bit tests (relational.rs: WGSL has none);
//!   negations of unsigned integers subtractions from zero, GLSL's `%` of
//!   signed integers WGSL's (negate.rs)
//! - samples of integer images become fetches (intsample.rs: WGSL samples
//!   float textures only); samples of images clamped to the border choose
//!   the border color outside the image (border.rs)
//! - input attachments become textures read at the fragment's position
//!   (subpass.rs)
//! - matrices of laid out blocks naga cannot read (std140's 2-row ones, row
//!   major ones) become arrays of vectors (layout.rs)
//! - entry point inputs and outputs of matrices, arrays and structs at a
//!   location become their vectors at consecutive locations (io.rs; a struct
//!   output's members get their locations first, structio.rs)
//! - an array image's size has its layer count (layers.rs: naga's SPIR-V
//!   front end leaves it out)
//! - outer products become matrices of columns, modf's and frexp's results
//!   naga's special types (math.rs)
//! - switch cases that fall through get the next ones' statements (switches.rs)
//! - bindings: Vulkan's binding b of a set is WGSL's binding 2b of the same
//!   group, and 2b + 1 for the sampler of a combined image sampler; a
//!   descriptor array of blocks becomes a block each (blockarrays.rs), its
//!   element e > 0 at 300 + 12b + e
//! - push constants (naga's immediates) become a read-only storage buffer
//!   at the group and binding the caller says
//! - uniform buffers whose layout WGSL's uniform rules refuse are storage too,
//!   and so are those the caller names (a stage has 12 uniform buffers in
//!   WebGPU, Vulkan's devices report more: the rest are read-only storage)
//! - Y of the position is flipped (naga's default for SPIR-V: Vulkan's
//!   clip space has Y down, WebGPU's up)
//! - a vertex shader's gl_PointSize is dropped (WGSL has none: WebGPU's
//!   points are one pixel); a capturing draw's compute shader keeps it
//! - gl_SampleMask and gl_SampleMaskIn, GLSL's int arrays, become WGSL's
//!   u32 sample mask (samplemask.rs); centroid and sample interpolation
//!   naga's front end drops are put back (sampling.rs)
//! - a geometry shader becomes a compute shader (geometry.rs:
//!   vx_translate_geometry), a vertex shader's capture of every output its
//!   input (xfb.rs); so do the tessellation shaders (tessellation.rs:
//!   vx_translate_tessellation)
//!
//! It answers in JSON: the WGSL, and per entry point the bindings it uses
//! and their kind; the overrides (specialization constants) by id.

extern crate alloc;

mod atomics;
mod counters;
mod imagecubes;
mod intsample;
mod io;
mod layers;
mod layout;
mod math;
mod negate;
mod relational;
mod remap;
mod blockarrays;
mod border;
mod cubes;
mod fetches;
mod depth;
mod geometry;
mod samplemask;
mod sizes;
mod tessellation;
mod sampling;
mod split;
mod structio;
mod subpass;
mod switches;
pub mod xfb;

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use naga::{AddressSpace, ImageClass, ImageDimension, ResourceBinding, ShaderStage, StorageAccess, TypeInner};

pub use split::SAMPLER_BINDING;

/// Where push constants go; whether Vulkan's clip space stays as it is
pub struct Options {
    pub immediates_group: u32,
    pub immediates_binding: u32,
    /// (WebGPU's y is Vulkan's flipped, and naga flips the vertex position
    /// to make up for it; a draw with a viewport of a negative height,
    /// Vulkan's own flip, which WebGPU's viewports cannot do, keeps it as
    /// it is: ANGLE draws GL's frames so)
    pub keep_coordinate_space: bool,
    /// The uniform buffers to make read-only storage buffers, by their
    /// group and WGSL binding, `group << 16 | binding`
    pub storage_uniforms: Vec<u32>,
    /// a fragment shader's depth output dropped (a pipeline with no depth
    /// attachment); a vertex shader's depth reversed (a viewport with its
    /// depths reversed): depth.rs
    pub drop_frag_depth: bool,
    pub reverse_depth: bool,
    /// GL's clip space: a vertex shader's depth from -w to w made WebGPU's 0 to w (depth.rs; the GLES host)
    pub gl_depth: bool,
    /// The address modes of the samplers of integer images (whose samples
    /// are fetches, intsample.rs), by their group and WGSL binding
    /// (`group << 16 | binding`): VkSamplerAddressMode u | v << 4 | w << 8;
    /// clamp to edge for the others
    pub int_wraps: Vec<(u32, u32)>,
}

fn quote(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// A resource's kind, as the bind groups need it
fn kind(module: &naga::Module, var: &naga::GlobalVariable) -> &'static str {
    match var.space {
        AddressSpace::Uniform => "uniform",
        AddressSpace::Storage { access } => if access.contains(StorageAccess::STORE) { "storage-rw" } else { "storage" },
        AddressSpace::Handle => match module.types[var.ty].inner {
            TypeInner::Sampler { comparison } => if comparison { "sampler-comparison" } else { "sampler" },
            TypeInner::Image { class, dim, .. } => match class {
                ImageClass::Storage { .. } => "storage-texture",
                ImageClass::Depth { multi: true } => "texture-depth-ms",
                ImageClass::Depth { .. } => "texture-depth",
                ImageClass::Sampled { multi: true, .. } => "texture-ms",
                // (an integer cube's faces, cubes.rs)
                ImageClass::Sampled { kind, .. } if var.name.as_deref() == Some(cubes::FACES) => match kind {
                    naga::ScalarKind::Uint => "texture-uint-faces",
                    _ => "texture-sint-faces",
                },
                ImageClass::Sampled { kind, .. } => match kind {
                    naga::ScalarKind::Uint => "texture-uint",
                    naga::ScalarKind::Sint => "texture-sint",
                    _ => if dim == ImageDimension::D1 { "texture-1d" } else { "texture" },
                },
                _ => "texture",
            },
            _ => "other",
        },
        _ => "other",
    }
}

/// WGSL's binding of a SPIR-V binding: Vulkan's b is 2b, a split sampler's
/// 2b + 1; element e > 0 of a descriptor array (blockarrays.rs) is
/// ELEMENTS + 2 (16b + e), its split sampler's one more (vx_executor.js's
/// descriptorKey reads them back)
pub(crate) fn wgsl_binding(binding: u32) -> u32 {
    if binding >= blockarrays::ELEMENT_BINDING + SAMPLER_BINDING {
        ELEMENTS + (binding - blockarrays::ELEMENT_BINDING - SAMPLER_BINDING) * 2 + 1
    }
    else if binding >= blockarrays::ELEMENT_BINDING {
        ELEMENTS + (binding - blockarrays::ELEMENT_BINDING) * 2
    }
    else if binding >= SAMPLER_BINDING {
        (binding - SAMPLER_BINDING) * 2 + 1
    }
    else {
        binding * 2
    }
}

const ELEMENTS: u32 = 300;

fn rebind(module: &mut naga::Module, options: &Options) {
    for (_, var) in module.global_variables.iter_mut() {
        if let (AddressSpace::Uniform, Some(b)) = (var.space, var.binding.as_ref()) {
            if options.storage_uniforms.contains(&(b.group << 16 | wgsl_binding(b.binding))) {
                var.space = AddressSpace::Storage { access: StorageAccess::LOAD };
            }
        }
        if matches!(var.space, AddressSpace::Immediate) {
            var.space = AddressSpace::Storage { access: StorageAccess::LOAD };
            var.binding = Some(ResourceBinding { group: options.immediates_group, binding: options.immediates_binding });
            continue;
        }
        if let Some(b) = var.binding.as_mut() {
            b.binding = wgsl_binding(b.binding);
        }
    }
}

/// Function `f`'s values of struct type `from` made of `to` instead: its
/// result, and its Compose (of the members `keep` says) and ZeroValue
/// expressions
pub(crate) fn retype(f: &mut naga::Function, from: naga::Handle<naga::Type>, to: naga::Handle<naga::Type>, keep: Option<&[bool]>) {
    if let Some(r) = f.result.as_mut() {
        if r.ty == from {
            r.ty = to;
        }
    }
    for (_, e) in f.expressions.iter_mut() {
        match e {
            naga::Expression::Compose { ty, components } if *ty == from => {
                *ty = to;
                if let Some(keep) = keep {
                    let mut i = 0;
                    components.retain(|_| {
                        i += 1;
                        keep.get(i - 1).copied().unwrap_or(true)
                    });
                }
            },
            naga::Expression::ZeroValue(ty) if *ty == from => *ty = to,
            _ => {},
        }
    }
}

/// The vertex entry points' gl_PointSize outputs dropped: each result a new
/// struct without them, and the structs that keep them (gl_PerVertex's, a
/// private global's, the old results: naga may have made them one type)
/// unbound, since naga's WGSL writes every struct
fn drop_point_size(module: &mut naga::Module) {
    let point_size = |m: &naga::StructMember| matches!(m.binding, Some(naga::Binding::BuiltIn(naga::BuiltIn::PointSize)));
    for ep in module.entry_points.iter_mut() {
        if ep.stage != ShaderStage::Vertex {
            continue;
        }
        let Some(old) = ep.function.result.as_ref().map(|r| r.ty) else { continue };
        let (members, span) = match &module.types[old].inner {
            TypeInner::Struct { members, span } => (members.clone(), *span),
            _ => continue,
        };
        let keep: Vec<bool> = members.iter().map(|m| !point_size(m)).collect();
        if keep.iter().all(|k| *k) {
            continue;
        }
        let kept = members.into_iter().zip(&keep).filter(|(_, k)| **k).map(|(m, _)| m).collect();
        let new = module.types.insert(naga::Type { name: Some(String::from("VxVertexOutput")), inner: TypeInner::Struct { members: kept, span } },
            naga::Span::UNDEFINED);
        retype(&mut ep.function, old, new, Some(&keep));
    }
    let results: Vec<naga::Handle<naga::Type>> = module.entry_points.iter().filter_map(|ep| ep.function.result.as_ref().map(|r| r.ty)).collect();
    let unbind: Vec<naga::Handle<naga::Type>> = module.types.iter().filter(|(handle, ty)| !results.contains(handle) && match &ty.inner {
        TypeInner::Struct { members, .. } => members.iter().any(point_size),
        _ => false,
    }).map(|(handle, _)| handle).collect();
    for handle in unbind {
        let mut ty = module.types[handle].clone();
        if let TypeInner::Struct { members, .. } = &mut ty.inner {
            for m in members.iter_mut() {
                if point_size(m) {
                    m.binding = None;
                }
            }
        }
        module.types.replace(handle, ty);
    }
}

fn validate(module: &naga::Module) -> Result<naga::valid::ModuleInfo, String> {
    naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())
        .validate(module)
        .map_err(|e| format!("{:?}", e.into_inner()))
}

/// VX's passes on the SPIR-V, in order; VX_SKIP (a list of their names, in
/// a native build's environment: debugging) leaves some out
/// (`wraps`: the address modes of integer images' samplers, intsample.rs;
/// `sampled`: the integer images it made fetches of)
fn passes(words: &[u32], wraps: &[(u32, u32)], sampled: &mut Vec<u32>) -> Vec<u32> {
    let skip = std::env::var("VX_SKIP").unwrap_or_default();
    let list: [(&str, fn(&[u32]) -> Vec<u32>); 12] = [("blockarrays", blockarrays::lower), ("counters", counters::lower), ("imagecubes", imagecubes::lower), ("split", split::split), ("coordinates", intsample::coordinate_types), ("subpass", subpass::lower),
        ("relational", relational::lower), ("fetches", fetches::lower), ("layout", layout::lower), ("atomics", atomics::values), ("structio", structio::lower),
        ("negate", negate::lower)];
    let mut words = words.to_vec();
    for (name, pass) in list {
        // (clamp to border after split: the images' own loads, border.rs)
        if name == "coordinates" && !skip.split(',').any(|s| s == "border") {
            words = border::lower(&words, wraps);
        }
        // (intsample after subpass; sizes before it: the shader's own size queries, not intsample's)
        if name == "relational" && !skip.split(',').any(|s| s == "sizes") {
            words = sizes::lower(&words);
        }
        if name == "relational" && !skip.split(',').any(|s| s == "intsample") {
            words = intsample::lower(&words, wraps, sampled);
        }
        if !skip.split(',').any(|s| s == name) {
            words = pass(&words);
        }
    }
    words
}

/// The module naga reads of SPIR-V (bytes), after VX's passes on the SPIR-V
/// (examples/dump.rs)
pub fn parse_for_debugging(bytes: &[u8]) -> Result<naga::Module, String> {
    let words: Vec<u32> = bytes.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
    let words = passes(&words, &[], &mut Vec::new());
    let data: Vec<u8> = xfb::strip(&words).iter().flat_map(|w| w.to_le_bytes()).collect();
    let spv = naga::front::spv::Options { adjust_coordinate_space: true, strict_capabilities: false, block_ctx_dump_prefix: None };
    naga::front::spv::parse_u8_slice(&data, &spv).map_err(|e| format!("SPIR-V: {:?}", e))
}

/// The SPIR-V (bytes) after VX's passes on it (examples/dump.rs)
pub fn passes_for_debugging(bytes: &[u8]) -> Vec<u8> {
    let words: Vec<u32> = bytes.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
    passes(&words, &[], &mut Vec::new()).iter().flat_map(|w| w.to_le_bytes()).collect()
}

/// SPIR-V (bytes) to the JSON answer
pub fn translate(bytes: &[u8], options: &Options) -> Result<String, String> { translate_with(bytes, options, Mode::Shader) }

/// What a capturing draw's compute shader needs (xfb.rs): the pipeline's
/// vertex input and the group of its own resources
pub struct XfbInput {
    pub attributes: Vec<xfb::Attribute>,
    pub slots: Vec<xfb::Slot>,
    pub group: u32,
    /// every output captured into buffer 0 as a geometry shader's input
    /// record (geometry.rs) rather than those the SPIR-V decorates
    pub all: bool,
}

/// What translate_with makes: a stage's shader, a capturing draw's compute
/// shader, or a geometry shader's compute shader (its resources' group)
enum Mode<'a> {
    Shader,
    Xfb(&'a XfbInput),
    Geometry(u32),
    Tessellation(tessellation::Stage, u32),
}

/// Struct members whose offsets are not WGSL's own layout's (std140's: a
/// struct or array member 16-aligned, a struct's size rounded to 16) get a
/// `@size` that puts the next one where the module says: naga's WGSL writer
/// writes no layout attributes, and the shader would read the wrong bytes
/// (or, in a uniform buffer, be refused). The structs are written in the
/// type arena's order, the predeclared ones left out, as naga's writer does.
fn explicit_layout(module: &naga::Module, wgsl: &mut String) {
    let mut layouter = naga::proc::Layouter::default();
    if layouter.update(module.to_ctx()).is_err() {
        return;
    }
    let predeclared: Vec<naga::Handle<naga::Type>> = module.special_types.predeclared_types.values().copied().collect();
    // a struct in an array whose stride is more than the struct's size (std140
    // rounds a struct's size to 16): WGSL has no array stride, so the struct's
    // own size becomes the stride
    let mut spans: alloc::collections::BTreeMap<naga::Handle<naga::Type>, u32> = alloc::collections::BTreeMap::new();
    for (_, ty) in module.types.iter() {
        if let TypeInner::Array { base, stride, .. } = ty.inner {
            if let TypeInner::Struct { span, .. } = module.types[base].inner {
                if stride > span {
                    spans.insert(base, stride);
                }
            }
        }
    }
    // for each struct written: the member indices to give a size, and the sizes
    let mut sizes: Vec<Vec<(usize, u32)>> = Vec::new();
    for (handle, ty) in module.types.iter() {
        let TypeInner::Struct { ref members, span } = ty.inner else { continue };
        let span = spans.get(&handle).copied().unwrap_or(span);
        if predeclared.contains(&handle) || Some(handle) == module.special_types.external_texture_params
            || Some(handle) == module.special_types.external_texture_transfer_function {
            continue;
        }
        let mut list = Vec::new();
        let alignment = members.iter().map(|m| layouter[m.ty].alignment.round_up(1)).max().unwrap_or(1);
        for (i, member) in members.iter().enumerate() {
            let layout = layouter[member.ty];
            let natural_end = member.offset + layout.size;
            let next = members.get(i + 1).map(|n| n.offset);
            let target_end = match next {
                Some(offset) => {
                    // (where the next member goes without a size: its alignment after this one's end)
                    if layouter[members[i + 1].ty].alignment.round_up(natural_end) == offset { continue; }
                    offset
                }
                None => {
                    if span == (natural_end + alignment - 1) / alignment * alignment { continue; }
                    span
                }
            };
            if target_end > natural_end {
                list.push((i, target_end - member.offset));
            }
        }
        sizes.push(list);
    }
    if sizes.iter().all(|l| l.is_empty()) {
        return;
    }
    // the written structs, in order: a line "struct name {", members a line each, "}"
    let mut out = String::with_capacity(wgsl.len() + 64);
    let mut which = 0usize;
    let mut member: Option<usize> = None;
    for line in wgsl.split_inclusive('\n') {
        if member.is_none() && line.starts_with("struct ") && line.trim_end().ends_with('{') {
            member = Some(0);
            out.push_str(line);
            continue;
        }
        if let Some(index) = member {
            if line.trim_start().starts_with('}') {
                member = None;
                which += 1;
                out.push_str(line);
                continue;
            }
            if let Some(list) = sizes.get(which) {
                if let Some(&(_, size)) = list.iter().find(|&&(i, _)| i == index) {
                    let indent = line.len() - line.trim_start().len();
                    out.push_str(&line[..indent]);
                    out.push_str(&format!("@size({}) ", size));
                    out.push_str(&line[indent..]);
                    member = Some(index + 1);
                    continue;
                }
            }
            member = Some(index + 1);
        }
        out.push_str(line);
    }
    *wgsl = out;
}

/// The compute shader of a capturing draw (vx_translate_xfb), as JSON
pub fn translate_xfb(bytes: &[u8], options: &Options, input: &XfbInput) -> Result<String, String> { translate_with(bytes, options, Mode::Xfb(input)) }

/// The compute shader of a geometry shader (geometry.rs), its own resources in `group`, as JSON
pub fn translate_geometry(bytes: &[u8], options: &Options, group: u32) -> Result<String, String> { translate_with(bytes, options, Mode::Geometry(group)) }

/// The compute shader of a tessellation control (`control`) or evaluation shader (tessellation.rs), as JSON
pub fn translate_tessellation(bytes: &[u8], options: &Options, control: bool, group: u32) -> Result<String, String> {
    let stage = if control { tessellation::Stage::Control } else { tessellation::Stage::Evaluation };
    translate_with(bytes, options, Mode::Tessellation(stage, group))
}

fn translate_with(bytes: &[u8], options: &Options, mode: Mode) -> Result<String, String> {
    if bytes.len() % 4 != 0 || bytes.len() < 20 {
        return Err(String::from("not SPIR-V: not whole words"));
    }
    let words: Vec<u32> = bytes.chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
    let (words, geometry) = match mode {
        Mode::Geometry(_) => {
            let (words, g) = geometry::prepare(&words)?;
            (words, Some(g))
        },
        _ => (words, None),
    };
    let (words, tess) = match mode {
        Mode::Tessellation(stage, _) => {
            let (words, t) = tessellation::prepare(&words, stage)?;
            (words, Some(t))
        },
        _ => (words, None),
    };
    let mut sampled = Vec::new();
    let words = passes(&words, &options.int_wraps, &mut sampled);
    // (transform feedback's: read by xfb::captures, naga refuses them)
    let data: Vec<u8> = xfb::strip(&words).iter().flat_map(|w| w.to_le_bytes()).collect();
    let spv = naga::front::spv::Options { adjust_coordinate_space: !options.keep_coordinate_space, strict_capabilities: false, block_ctx_dump_prefix: None };
    let mut module = naga::front::spv::parse_u8_slice(&data, &spv).map_err(|e| format!("SPIR-V: {:?}", e))?;
    sampling::restore(&mut module, &sampling::read(&words));
    layers::lower(&mut module);
    samplemask::lower(&mut module);
    cubes::lower(&mut module);
    math::lower(&mut module);
    switches::lower(&mut module);
    rebind(&mut module, options);
    // (transform feedback: the compute shader of a capturing draw, xfb.rs)
    let mut appended = String::new();
    let mut capture_json = String::new();
    let mut finished = None;
    if let Mode::Xfb(input) = mode {
        let (captures, strides, buffers) = if input.all {
            (Vec::new(), [0; 4], vec![0])
        }
        else {
            let (captures, strides) = xfb::captures(&words).ok_or("the vertex shader captures nothing")?;
            let mut buffers: Vec<u32> = captures.iter().map(|c| c.buffer).collect();
            buffers.sort_unstable();
            buffers.dedup();
            (captures, strides, buffers)
        };
        let (wgsl, strides) = xfb::compute_shader(&mut module, &captures, strides, &input.attributes, &input.slots, input.group, input.all)?;
        appended = wgsl;
        capture_json = format!(",\"xfb\":{{\"strides\":[{},{},{},{}],\"buffers\":{:?},\"slots\":{:?}}}", strides[0], strides[1], strides[2], strides[3],
            buffers, { let mut s: Vec<u32> = input.attributes.iter().map(|a| a.slot).collect(); s.sort_unstable(); s.dedup(); s });
    }
    else if let (Mode::Geometry(group), Some(g)) = (&mode, &geometry) {
        let f = geometry::finish(&mut module, g, *group)?;
        capture_json = format!(",\"geometry\":{}", f.json);
        finished = Some(f);
    }
    else if let (Mode::Tessellation(_, group), Some(t)) = (&mode, &tess) {
        let f = tessellation::finish(&mut module, t, *group)?;
        capture_json = format!(",\"tessellation\":{}", f.json);
        appended = f.appended;
    }
    else if xfb::captures(&words).is_some() {
        capture_json = String::from(",\"captures\":true");
    }
    drop_point_size(&mut module);
    io::flatten(&mut module)?;
    if options.drop_frag_depth {
        depth::drop_frag_depth(&mut module);
    }
    if options.gl_depth {
        depth::gl_depth(&mut module);
    }
    if options.reverse_depth {
        depth::reverse_depth(&mut module);
    }
    let info = match validate(&module) {
        Ok(info) => info,
        Err(first) => {
            // uniform buffers of a layout WGSL's uniforms refuse: as storage
            for (_, var) in module.global_variables.iter_mut() {
                if matches!(var.space, AddressSpace::Uniform) {
                    var.space = AddressSpace::Storage { access: StorageAccess::LOAD };
                }
            }
            validate(&module).map_err(|_| first)?
        }
    };
    // the types nothing uses any more (the arrays blockarrays.rs split, the
    // structs io.rs flattened) gone: naga's WGSL writer writes every type,
    // and enables binding arrays when one is among them
    let _ = info;
    naga::compact::compact(&mut module, naga::compact::KeepUnused::Yes);
    let info = validate(&module)?;
    let mut wgsl = naga::back::wgsl::write_string(&module, &info, naga::back::wgsl::WriterFlags::empty())
        .map_err(|e| format!("WGSL: {:?}", e))?;
    explicit_layout(&module, &mut wgsl);
    if let Some(f) = &finished {
        geometry::replace_stubs(&mut wgsl, f)?;
        appended = f.appended.clone();
    }
    wgsl.push_str(&appended);

    let mut layouter = naga::proc::Layouter::default();
    let laid = layouter.update(module.to_ctx()).is_ok();
    let mut json = String::from("{\"wgsl\":");
    json.push_str(&quote(&wgsl));
    json.push_str(",\"entries\":[");
    // (a geometry or tessellation shader's compute entry point: the resources its function uses, and the group the caller gave)
    let own_entry = if finished.is_some() { Some((geometry::MAIN, "vx_geometry")) } else {
        match tess.as_ref().and_then(|t| t.stage) {
            Some(tessellation::Stage::Control) => Some((tessellation::CONTROL_MAIN, "vx_tess_control")),
            Some(tessellation::Stage::Evaluation) => Some((tessellation::EVALUATION_MAIN, "vx_tess_eval")),
            None => None,
        }
    };
    if let Some((main, entry_name)) = own_entry {
        let (handle, _) = module.functions.iter().find(|(_, f)| f.name.as_deref() == Some(main)).ok_or("the shader's function is gone")?;
        let uses = &info[handle];
        json.push_str(&format!("{{\"name\":\"{}\",\"stage\":\"compute\",\"workgroup\":[64,1,1],\"flat\":false,\"bindings\":[", entry_name));
        let mut first = true;
        for (h, var) in module.global_variables.iter() {
            let Some(binding) = var.binding else { continue };
            if uses[h].is_empty() { continue; }
            if !first { json.push(','); }
            first = false;
            let size = match var.space {
                AddressSpace::Uniform | AddressSpace::Storage { .. } if laid => layouter[var.ty].size,
                _ => 0,
            };
            json.push_str(&format!("[{},{},\"{}\",{}]", binding.group, binding.binding, kind(&module, var), size));
        }
        json.push_str("]}");
    }
    for (index, entry) in module.entry_points.iter().enumerate() {
        if index > 0 { json.push(','); }
        let stage = match entry.stage {
            ShaderStage::Vertex => "vertex",
            ShaderStage::Fragment => "fragment",
            ShaderStage::Compute => "compute",
            _ => "other",
        };
        // (a vertex shader's outputs flat shaded: the provoking vertex matters, vx_executor.js's provokingLast)
        let flat_binding = |b: &Option<naga::Binding>| matches!(b, Some(naga::Binding::Location { interpolation: Some(naga::Interpolation::Flat), .. }));
        let flat = entry.function.result.as_ref().is_some_and(|r| flat_binding(&r.binding) || match &module.types[r.ty].inner {
            TypeInner::Struct { members, .. } => members.iter().any(|m| flat_binding(&m.binding)),
            _ => false,
        });
        json.push_str(&format!("{{\"name\":{},\"stage\":\"{}\",\"workgroup\":[{},{},{}],\"flat\":{},\"bindings\":[",
            quote(&entry.name), stage, entry.workgroup_size[0], entry.workgroup_size[1], entry.workgroup_size[2], flat));
        let uses = info.get_entry_point(index);
        let mut first = true;
        for (handle, var) in module.global_variables.iter() {
            let Some(binding) = var.binding else { continue };
            if uses[handle].is_empty() { continue; }
            if !first { json.push(','); }
            first = false;
            // (a buffer's: the size WebGPU wants bound at least, its type's: one element of a runtime array)
            let size = match var.space {
                AddressSpace::Uniform | AddressSpace::Storage { .. } if laid => layouter[var.ty].size,
                _ => 0,
            };
            json.push_str(&format!("[{},{},\"{}\",{}]", binding.group, binding.binding, kind(&module, var), size));
        }
        json.push_str("]}");
    }
    json.push_str("],\"overrides\":[");
    let mut first = true;
    for (_, o) in module.overrides.iter() {
        let Some(id) = o.id else { continue };
        let ty = match module.types[o.ty].inner {
            TypeInner::Scalar(s) => match s.kind {
                naga::ScalarKind::Bool => "bool",
                naga::ScalarKind::Sint => "i32",
                naga::ScalarKind::Uint => "u32",
                _ => "f32",
            },
            _ => "other",
        };
        if !first { json.push(','); }
        first = false;
        json.push_str(&format!("[{},\"{}\"]", id, ty));
    }
    json.push(']');
    // (the integer images whose samples are fetches: their samplers' address modes matter, int_wraps)
    sampled.sort_unstable();
    sampled.dedup();
    json.push_str(&format!(",\"intsamples\":{:?}", sampled));
    json.push_str(&capture_json);
    json.push('}');
    Ok(json)
}

// ---------------------------------------------------------------------------
// The wasm interface: the caller copies SPIR-V into memory it got from
// vx_alloc, calls vx_translate, reads the answer (a length, then UTF-8 JSON)
// and frees both with vx_free

#[no_mangle]
pub extern "C" fn vx_alloc(len: usize) -> *mut u8 {
    let mut v = Vec::<u8>::with_capacity(len.max(1));
    let p = v.as_mut_ptr();
    core::mem::forget(v);
    p
}

/// # Safety
/// `ptr` and `len` as vx_alloc gave them
#[no_mangle]
pub unsafe extern "C" fn vx_free(ptr: *mut u8, len: usize) {
    drop(Vec::from_raw_parts(ptr, 0, len.max(1)));
}

/// The compute shader of a capturing draw (xfb.rs) for the vertex shader in
/// `ptr` (`len` bytes, translated as vx_translate does with Vulkan's clip
/// space kept): `input` holds `input_count` words: the group, the attribute
/// count, each attribute's location, slot, VkFormat and offset, the slot
/// count, each slot's slot, stride and input rate
///
/// # Safety
/// as vx_translate's
#[no_mangle]
pub unsafe extern "C" fn vx_translate_xfb(ptr: *const u8, len: usize, immediates_group: u32, immediates_binding: u32,
    storage: *const u32, storage_count: usize, input: *const u32, input_count: usize) -> *mut u8 {
    let bytes = core::slice::from_raw_parts(ptr, len);
    let storage_uniforms = if storage.is_null() || storage_count == 0 { Vec::new() } else { core::slice::from_raw_parts(storage, storage_count).to_vec() };
    let w = core::slice::from_raw_parts(input, input_count);
    let mut at = 0;
    let mut next = || { let v = w.get(at).copied().unwrap_or(0); at += 1; v };
    let group = next();
    let attributes = (0..next()).map(|_| xfb::Attribute { location: next(), slot: next(), format: next(), offset: next() }).collect();
    let slots = (0..next()).map(|_| xfb::Slot { slot: next(), stride: next(), instance: next() != 0 }).collect();
    let options = Options { immediates_group, immediates_binding, keep_coordinate_space: true, storage_uniforms, drop_frag_depth: false, reverse_depth: false, gl_depth: false,
        int_wraps: Vec::new() };
    // (the group's bit 31: every output captured, a geometry shader's input, XfbInput::all)
    let (group, all) = (group & 0x7FFF_FFFF, group & 0x8000_0000 != 0);
    let answer = match translate_with(bytes, &options, Mode::Xfb(&XfbInput { attributes, slots, group, all })) {
        Ok(json) => json,
        Err(error) => format!("{{\"error\":{}}}", quote(&error)),
    };
    let out = vx_alloc(answer.len() + 4);
    core::ptr::copy_nonoverlapping((answer.len() as u32).to_le_bytes().as_ptr(), out, 4);
    core::ptr::copy_nonoverlapping(answer.as_ptr(), out.add(4), answer.len());
    out
}

/// The compute shader of the geometry shader in `ptr` (`len` bytes, its
/// clip space kept), its own resources in `group` (geometry.rs)
///
/// # Safety
/// as vx_translate's
#[no_mangle]
pub unsafe extern "C" fn vx_translate_geometry(ptr: *const u8, len: usize, group: u32, wraps: *const u32, wrap_count: usize) -> *mut u8 {
    let bytes = core::slice::from_raw_parts(ptr, len);
    let int_wraps = if wraps.is_null() || wrap_count == 0 { Vec::new() } else {
        core::slice::from_raw_parts(wraps, wrap_count * 2).chunks_exact(2).map(|p| (p[0], p[1])).collect()
    };
    let options = Options { immediates_group: 0, immediates_binding: 0, keep_coordinate_space: true, storage_uniforms: Vec::new(), drop_frag_depth: false,
        reverse_depth: false, gl_depth: false, int_wraps };
    let answer = match translate_geometry(bytes, &options, group) {
        Ok(json) => json,
        Err(error) => format!("{{\"error\":{}}}", quote(&error)),
    };
    let out = vx_alloc(answer.len() + 4);
    core::ptr::copy_nonoverlapping((answer.len() as u32).to_le_bytes().as_ptr(), out, 4);
    core::ptr::copy_nonoverlapping(answer.as_ptr(), out.add(4), answer.len());
    out
}

/// The compute shader of the tessellation control (`control` 1) or
/// evaluation shader in `ptr` (`len` bytes), its own resources in `group`
/// (tessellation.rs)
///
/// # Safety
/// as vx_translate's
#[no_mangle]
pub unsafe extern "C" fn vx_translate_tessellation(ptr: *const u8, len: usize, control: u32, group: u32) -> *mut u8 {
    let bytes = core::slice::from_raw_parts(ptr, len);
    let options = Options { immediates_group: 0, immediates_binding: 0, keep_coordinate_space: true, storage_uniforms: Vec::new(), drop_frag_depth: false,
        reverse_depth: false, gl_depth: false, int_wraps: Vec::new() };
    let answer = match translate_tessellation(bytes, &options, control != 0, group) {
        Ok(json) => json,
        Err(error) => format!("{{\"error\":{}}}", quote(&error)),
    };
    let out = vx_alloc(answer.len() + 4);
    core::ptr::copy_nonoverlapping((answer.len() as u32).to_le_bytes().as_ptr(), out, 4);
    core::ptr::copy_nonoverlapping(answer.as_ptr(), out.add(4), answer.len());
    out
}

/// # Safety
/// `ptr` holds `len` bytes; `flags` bit 0: keep Vulkan's clip space (Options);
/// `storage` holds `storage_count` words, the uniform buffers to make
/// storage (Options::storage_uniforms; null when none)
#[no_mangle]
pub unsafe extern "C" fn vx_translate(ptr: *const u8, len: usize, immediates_group: u32, immediates_binding: u32, flags: u32,
    storage: *const u32, storage_count: usize, wraps: *const u32, wrap_count: usize) -> *mut u8 {
    let bytes = core::slice::from_raw_parts(ptr, len);
    let storage_uniforms = if storage.is_null() || storage_count == 0 { Vec::new() } else { core::slice::from_raw_parts(storage, storage_count).to_vec() };
    // (pairs: the image's group << 16 | binding, its address modes)
    let int_wraps = if wraps.is_null() || wrap_count == 0 { Vec::new() } else {
        core::slice::from_raw_parts(wraps, wrap_count * 2).chunks_exact(2).map(|p| (p[0], p[1])).collect()
    };
    let options = Options { immediates_group, immediates_binding, keep_coordinate_space: flags & 1 != 0, storage_uniforms,
        drop_frag_depth: flags & 2 != 0, reverse_depth: flags & 4 != 0, gl_depth: flags & 8 != 0, int_wraps };
    let answer = match translate(bytes, &options) {
        Ok(json) => json,
        Err(error) => format!("{{\"error\":{}}}", quote(&error)),
    };
    let out = vx_alloc(answer.len() + 4);
    core::ptr::copy_nonoverlapping((answer.len() as u32).to_le_bytes().as_ptr(), out, 4);
    core::ptr::copy_nonoverlapping(answer.as_ptr(), out.add(4), answer.len());
    out
}
                                                                                                                                                                                                                                                                                                                                         source/v64/src/browser/glbridge/vx/naga/src/math.rs                                                 0000644 0000000 0000000 00000027460 00000000000 017357  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Math naga reads from SPIR-V but cannot write as WGSL, or types wrongly:
//! - `outerProduct` (OpOuterProduct, naga's Math Outer, which WGSL has not):
//!   in its place the matrix of `a * b[i]` columns, the new expressions
//!   before it (remap.rs);
//! - modf's and frexp's results (GLSL.std.450's ModfStruct, FrexpStruct):
//!   their result structs registered as naga's special types, which its
//!   front end leaves out;
//! - normalize, reflect, refract and faceforward of scalars (GLSL has
//!   them, WGSL only of vectors): of `vec2(x, 0)` each, their `.x`;
//! - atan2 and tanh where Chrome's Metal compiler gets them wrong
//!   (dEQP-GLES3 builtin_functions.precision): `atan(y, x)` of x == 0 is
//!   the opposite of its sign there, so it is `sign(y) * π/2`; `tanh(x)`
//!   of |x| past 10 is NaN there, so it is `sign(x)` (1 to within a float
//!   from 9 on).

use alloc::vec::Vec;
use naga::{BinaryOperator, Expression, Function, Handle, MathFunction, Span, Type, TypeInner, VectorSize};

fn fix(module: &mut naga::Module, function: &mut Function) {
    let outers: Vec<(Handle<Expression>, Handle<Expression>, Handle<Expression>)> = function.expressions.iter().filter_map(|(h, e)| match *e {
        Expression::Math { fun: MathFunction::Outer, arg, arg1: Some(arg1), .. } => Some((h, arg, arg1)),
        _ => None,
    }).collect();
    if outers.is_empty() {
        return;
    }
    // the operands' sizes
    let mut typifier = naga::front::Typifier::new();
    let mut sizes = Vec::new();
    {
        let ctx = naga::proc::ResolveContext::with_locals(module, &function.local_variables, &function.arguments);
        for &(_, a, b) in &outers {
            if typifier.grow(a, &function.expressions, &ctx).is_err() || typifier.grow(b, &function.expressions, &ctx).is_err() {
                return;
            }
            let size = |inner: &TypeInner| match *inner {
                TypeInner::Vector { size, scalar } => Some((size, scalar)),
                _ => None,
            };
            let (Some((rows, scalar)), Some((columns, _))) = (size(typifier.get(a, &module.types)), size(typifier.get(b, &module.types))) else { return };
            sizes.push((rows, columns, scalar));
        }
    }
    let mut f = function.clone();
    let mut moves = Vec::new();
    for (&(h, a, b), &(rows, columns, scalar)) in outers.iter().zip(&sizes) {
        let ty = module.types.insert(Type { name: None, inner: TypeInner::Matrix { columns, rows, scalar } }, Span::UNDEFINED);
        let mut components = Vec::new();
        for i in 0..columns as u32 {
            let bi = f.expressions.append(Expression::AccessIndex { base: b, index: i }, Span::UNDEFINED);
            let column = f.expressions.append(Expression::Binary { op: BinaryOperator::Multiply, left: a, right: bi }, Span::UNDEFINED);
            moves.push((bi, h));
            moves.push((column, h));
            components.push(column);
        }
        f.expressions[h] = Expression::Compose { ty, components };
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
}

/// Normalize, Reflect, Refract and FaceForward of scalars as of 2-vectors with a 0 second component
fn scalars(module: &mut naga::Module, function: &mut Function) {
    const VECTOR_ONLY: [MathFunction; 4] = [MathFunction::Normalize, MathFunction::Reflect, MathFunction::Refract, MathFunction::FaceForward];
    let found: Vec<(Handle<Expression>, MathFunction, Handle<Expression>, Option<Handle<Expression>>, Option<Handle<Expression>>)> =
        function.expressions.iter().filter_map(|(h, e)| match *e {
            Expression::Math { fun, arg, arg1, arg2, .. } if VECTOR_ONLY.contains(&fun) => Some((h, fun, arg, arg1, arg2)),
            _ => None,
        }).collect();
    if found.is_empty() {
        return;
    }
    // (each expression's type on its own: naga's typifier stops at the first it
    // cannot resolve, which is the very scalar normalize this is for)
    let mut resolutions: Vec<Option<naga::proc::TypeResolution>> = Vec::new();
    {
        let ctx = naga::proc::ResolveContext::with_locals(module, &function.local_variables, &function.arguments);
        for (_, e) in function.expressions.iter() {
            let r = ctx.resolve(e, |p| resolutions[p.index()].as_ref().ok_or(naga::proc::ResolveError::InvalidAccess { expr: p, indexed: false }));
            resolutions.push(r.ok());
        }
    }
    let scalar_of: Vec<Option<naga::Scalar>> = found.iter().map(|&(_, _, arg, _, _)| match resolutions[arg.index()] {
        Some(ref r) => match *r.inner_with(&module.types) { TypeInner::Scalar(s) => Some(s), _ => None },
        None => None,
    }).collect();
    if scalar_of.iter().all(|s| s.is_none()) {
        return;
    }
    // (the literals before an expression that no emit range holds)
    let Some((first, _)) = function.expressions.iter().find(|(_, e)| matches!(e, Expression::Literal(_) | Expression::Constant(_)
        | Expression::GlobalVariable(_) | Expression::FunctionArgument(_) | Expression::LocalVariable(_) | Expression::ZeroValue(_))) else { return };
    let mut f = function.clone();
    let mut moves = Vec::new();
    for (&(h, fun, arg, arg1, arg2), scalar) in found.iter().zip(&scalar_of) {
        let Some(scalar) = *scalar else { continue };
        let ty = module.types.insert(Type { name: None, inner: TypeInner::Vector { size: VectorSize::Bi, scalar } }, Span::UNDEFINED);
        let zero = f.expressions.append(Expression::Literal(naga::Literal::F32(0.0)), Span::UNDEFINED);
        moves.push((zero, first));
        let mut wrap = |x: Handle<Expression>| {
            let c = f.expressions.append(Expression::Compose { ty, components: alloc::vec![x, zero] }, Span::UNDEFINED);
            moves.push((c, h));
            c
        };
        let (a, a1, a2) = match fun {
            MathFunction::Normalize => (wrap(arg), None, None),
            MathFunction::Reflect => (wrap(arg), arg1.map(&mut wrap), None),
            MathFunction::Refract => (wrap(arg), arg1.map(&mut wrap), arg2),
            _ => (wrap(arg), arg1.map(&mut wrap), arg2.map(&mut wrap)),
        };
        let math = f.expressions.append(Expression::Math { fun, arg: a, arg1: a1, arg2: a2, arg3: None }, Span::UNDEFINED);
        moves.push((math, h));
        f.expressions[h] = Expression::AccessIndex { base: math, index: 0 };
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
}

/// atan2 at x == 0 and tanh past |x| = 10 given their values there (atan2's
/// comparison of the operand's own shape, `x == x - x`; tanh's with 10 splat
/// to the operand's size)
fn guards(module: &naga::Module, function: &mut Function) {
    let found: Vec<(Handle<Expression>, MathFunction, Handle<Expression>, Option<Handle<Expression>>)> = function.expressions.iter().filter_map(|(h, e)| match *e {
        Expression::Math { fun: fun @ (MathFunction::Atan2 | MathFunction::Tanh), arg, arg1, .. } => Some((h, fun, arg, arg1)),
        _ => None,
    }).collect();
    if found.is_empty() {
        return;
    }
    let Some((first, _)) = function.expressions.iter().find(|(_, e)| matches!(e, Expression::Literal(_) | Expression::Constant(_)
        | Expression::GlobalVariable(_) | Expression::FunctionArgument(_) | Expression::LocalVariable(_) | Expression::ZeroValue(_))) else { return };
    // (each tanh operand's vector size, None for a scalar's)
    let mut resolutions: Vec<Option<naga::proc::TypeResolution>> = Vec::new();
    {
        let ctx = naga::proc::ResolveContext::with_locals(module, &function.local_variables, &function.arguments);
        for (_, e) in function.expressions.iter() {
            let r = ctx.resolve(e, |p| resolutions[p.index()].as_ref().ok_or(naga::proc::ResolveError::InvalidAccess { expr: p, indexed: false }));
            resolutions.push(r.ok());
        }
    }
    let size_of = |h: Handle<Expression>| -> Option<Option<VectorSize>> {
        match *resolutions[h.index()].as_ref()?.inner_with(&module.types) {
            TypeInner::Scalar(_) => Some(None),
            TypeInner::Vector { size, .. } => Some(Some(size)),
            _ => None,
        }
    };
    let mut f = function.clone();
    let mut moves: Vec<(Handle<Expression>, Handle<Expression>)> = Vec::new();
    // (literals with the others, before any emit range; the rest just before the expression they replace)
    let add = |f: &mut Function, moves: &mut Vec<(Handle<Expression>, Handle<Expression>)>, e: Expression, before: Handle<Expression>| {
        let id = f.expressions.append(e, Span::UNDEFINED);
        moves.push((id, before));
        id
    };
    let math = |fun, arg, arg1| Expression::Math { fun, arg, arg1, arg2: None, arg3: None };
    let literal = |v: f32| Expression::Literal(naga::Literal::F32(v));
    for &(h, fun, arg, arg1) in &found {
        let (condition, accept, reject) = if fun == MathFunction::Atan2 {
            let Some(x) = arg1 else { continue };
            let half_pi = add(&mut f, &mut moves, literal(core::f32::consts::FRAC_PI_2), first);
            let original = add(&mut f, &mut moves, math(MathFunction::Atan2, arg, Some(x)), h);
            let zero = add(&mut f, &mut moves, Expression::Binary { op: BinaryOperator::Subtract, left: x, right: x }, h);
            let at_zero = add(&mut f, &mut moves, Expression::Binary { op: BinaryOperator::Equal, left: x, right: zero }, h);
            let sign = add(&mut f, &mut moves, math(MathFunction::Sign, arg, None), h);
            let axis = add(&mut f, &mut moves, Expression::Binary { op: BinaryOperator::Multiply, left: sign, right: half_pi }, h);
            (at_zero, axis, original)
        } else {
            let Some(size) = size_of(arg) else { continue };
            let ten = add(&mut f, &mut moves, literal(10.0), first);
            let original = add(&mut f, &mut moves, math(MathFunction::Tanh, arg, None), h);
            let magnitude = add(&mut f, &mut moves, math(MathFunction::Abs, arg, None), h);
            let tens = match size {
                Some(size) => add(&mut f, &mut moves, Expression::Splat { size, value: ten }, h),
                None => ten,
            };
            let past = add(&mut f, &mut moves, Expression::Binary { op: BinaryOperator::Greater, left: magnitude, right: tens }, h);
            let sign = add(&mut f, &mut moves, math(MathFunction::Sign, arg, None), h);
            (past, sign, original)
        };
        f.expressions[h] = Expression::Select { condition, accept, reject };
    }
    if crate::remap::place(&mut f, &moves) {
        *function = f;
    }
}

/// The module's outer products made matrices of columns, and modf's and frexp's result types registered
pub fn lower(module: &mut naga::Module) {
    let any = |f: &Function, which: &[MathFunction]| f.expressions.iter().any(|(_, e)| matches!(e, Expression::Math { fun, .. } if which.contains(fun)));
    let special = module.functions.iter().any(|(_, f)| any(f, &[MathFunction::Modf, MathFunction::Frexp]))
        || module.entry_points.iter().any(|e| any(&e.function, &[MathFunction::Modf, MathFunction::Frexp]));
    if special {
        for size in [None, Some(VectorSize::Bi), Some(VectorSize::Tri), Some(VectorSize::Quad)] {
            module.generate_predeclared_type(naga::PredeclaredType::ModfResult { size, scalar: naga::Scalar::F32 });
            module.generate_predeclared_type(naga::PredeclaredType::FrexpResult { size, scalar: naga::Scalar::F32 });
        }
    }
    let handles: Vec<Handle<Function>> = module.functions.iter().map(|(h, _)| h).collect();
    for h in handles {
        let mut f = core::mem::take(&mut module.functions[h]);
        fix(module, &mut f);
        scalars(module, &mut f);
        guards(module, &mut f);
        module.functions[h] = f;
    }
    for e in 0..module.entry_points.len() {
        let mut f = core::mem::take(&mut module.entry_points[e].function);
        fix(module, &mut f);
        scalars(module, &mut f);
        guards(module, &mut f);
        module.entry_points[e].function = f;
    }
}

                                                                                                                                                                                                                source/v64/src/browser/glbridge/vx/naga/src/negate.rs                                               0000644 0000000 0000000 00000013771 00000000000 017671  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Integer operations naga cannot read as glslang writes them:
//! - negation of unsigned integers (GLSL's `-v` of a uint or uvec, which is
//!   two's complement): OpSNegate of the unsigned type, which naga refuses
//!   (`InvalidUnaryOperandType(Negate)`: WGSL negates signed integers and
//!   floats only), becomes OpISub from a null (zero) constant of the type,
//!   declared before the first function;
//! - GLSL's `%` of signed integers: OpSMod, which naga lowers through
//!   floor (refused for integers), becomes OpSRem, WGSL's `%`: the two
//!   differ only for negative operands, whose result GLSL ES leaves
//!   undefined;
//! - bitCount, findLSB and findMSB of unsigned integers (an `int` result):
//!   OpBitCount and GLSL.std.450's FindILsb, FindSMsb and FindUMsb of
//!   another signedness than their result, whose result naga gives the
//!   operand's type (`InvalidStoreTypes` where it is stored), become the
//!   operation in the operand's type, then an OpBitcast to the result's.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_EXT_INST_IMPORT: u32 = 11;
const OP_EXT_INST: u32 = 12;
const OP_TYPE_INT: u32 = 21;
const OP_CONSTANT: u32 = 43;
const OP_BITCAST: u32 = 124;
const OP_BIT_COUNT: u32 = 205;
/// GLSL.std.450's FindILsb, FindSMsb, FindUMsb
const GLSL_FIND_BITS: [u32; 3] = [73, 74, 75];
const OP_TYPE_VECTOR: u32 = 23;
const OP_CONSTANT_NULL: u32 = 46;
const OP_FUNCTION: u32 = 54;
const OP_S_NEGATE: u32 = 126;
const OP_I_SUB: u32 = 130;
const OP_S_REM: u32 = 138;
const OP_S_MOD: u32 = 139;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type (intsample.rs's)
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

/// The module with its negations of unsigned integers made subtractions from zero, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let types: BTreeMap<u32, &[u32]> = instructions.iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let unsigned = |ty: u32| {
        let scalar = match types.get(&ty) {
            Some(t) if op(t) == OP_TYPE_VECTOR => t[2],
            _ => ty,
        };
        types.get(&scalar).is_some_and(|t| op(t) == OP_TYPE_INT && t.len() >= 4 && t[3] == 0)
    };
    let integer = |ty: u32| {
        let scalar = match types.get(&ty) {
            Some(t) if op(t) == OP_TYPE_VECTOR => t[2],
            _ => ty,
        };
        types.get(&scalar).is_some_and(|t| op(t) == OP_TYPE_INT)
    };
    // the bit operations' operands of another type than their results (by the values' types: constants' and results')
    let glsl = instructions.iter().find(|w| op(w) == OP_EXT_INST_IMPORT && w.len() >= 3 && w[2..].iter().flat_map(|x| x.to_le_bytes())
        .take_while(|&b| b != 0).eq(b"GLSL.std.450".iter().copied())).map(|w| w[1]);
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let values: BTreeMap<u32, u32> = instructions.iter().enumerate()
        .filter(|(i, w)| w.len() >= 3 && (*i >= first_function && !untyped(op(w)) || op(w) == OP_CONSTANT))
        .map(|(_, w)| (w[2], w[1])).collect();
    let operand_of = |w: &[u32]| -> Option<u32> {
        if op(w) == OP_BIT_COUNT && w.len() == 4 {
            return Some(w[3]);
        }
        (op(w) == OP_EXT_INST && w.len() == 6 && Some(w[3]) == glsl && GLSL_FIND_BITS.contains(&w[4])).then(|| w[5])
    };
    let mismatched = |w: &[u32]| -> Option<u32> {
        let ty = *values.get(&operand_of(w)?)?;
        (ty != w[1] && integer(ty) && integer(w[1])).then_some(ty)
    };
    if !instructions.iter().any(|w| op(w) == OP_S_NEGATE && w.len() == 4 && unsigned(w[1]) || op(w) == OP_S_MOD && w.len() == 5 && integer(w[1])
        || mismatched(w).is_some()) {
        return words.to_vec();
    }
    let mut bound = words[3];
    let mut nulls: BTreeMap<u32, u32> = BTreeMap::new();
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut body: Vec<Vec<u32>> = Vec::new();
    for w in &instructions {
        if op(w) == OP_S_NEGATE && w.len() == 4 && unsigned(w[1]) {
            let zero = *nulls.entry(w[1]).or_insert_with(|| {
                let id = bound;
                bound += 1;
                declarations.push(instruction(OP_CONSTANT_NULL, &[w[1], id]));
                id
            });
            body.push(instruction(OP_I_SUB, &[w[1], w[2], zero, w[3]]));
        }
        else if op(w) == OP_S_MOD && w.len() == 5 && integer(w[1]) {
            body.push(instruction(OP_S_REM, &w[1..]));
        }
        else if let Some(ty) = mismatched(w) {
            // (the operation in the operand's type, under a new id; the result's id its bitcast)
            let id = bound;
            bound += 1;
            let mut changed = w[1..].to_vec();
            changed[0] = ty;
            changed[1] = id;
            body.push(instruction(op(w), &changed));
            body.push(instruction(OP_BITCAST, &[w[1], w[2], id]));
        }
        else {
            body.push(w.to_vec());
        }
    }
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    if first_function >= body.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out
}
       source/v64/src/browser/glbridge/vx/naga/src/relational.rs                                           0000644 0000000 0000000 00000012625 00000000000 020555  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! `OpIsNan` and `OpIsInf` as bit tests: WGSL has neither, so naga's WGSL
//! writer refuses them. Each becomes a bitcast of the (32-bit) float to
//! unsigned, the sign masked off, compared with the exponent's all ones
//! (0x7F800000): equal is infinite, above it NaN. The unsigned types and
//! the constants this needs are declared before the first function.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_TYPE_BOOL: u32 = 20;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_VECTOR: u32 = 23;
const OP_CONSTANT: u32 = 43;
const OP_CONSTANT_COMPOSITE: u32 = 44;
const OP_FUNCTION: u32 = 54;
const OP_BITCAST: u32 = 124;
const OP_IS_NAN: u32 = 156;
const OP_IS_INF: u32 = 157;
const OP_IEQUAL: u32 = 170;
const OP_UGREATER_THAN: u32 = 172;
const OP_BITWISE_AND: u32 = 199;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The module with its NaN and infinity tests made bit tests, or the words
/// as they were when it has none
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    if !instructions.iter().any(|w| matches!(op(w), OP_IS_NAN | OP_IS_INF) && w.len() >= 4) {
        return words.to_vec();
    }
    // the bool vectors' sizes (by type id), the unsigned int and its vectors
    let mut bool_type = None;
    let mut bool_vectors: BTreeMap<u32, u32> = BTreeMap::new();
    let mut uint = None;
    let mut uint_vectors: BTreeMap<u32, u32> = BTreeMap::new();
    for w in &instructions {
        match op(w) {
            OP_TYPE_BOOL if w.len() >= 2 => bool_type = Some(w[1]),
            OP_TYPE_INT if w.len() >= 4 && w[2] == 32 && w[3] == 0 => uint = Some(w[1]),
            _ => {},
        }
    }
    for w in &instructions {
        if op(w) == OP_TYPE_VECTOR && w.len() >= 4 {
            if Some(w[2]) == bool_type {
                bool_vectors.insert(w[1], w[3]);
            }
            else if Some(w[2]) == uint {
                uint_vectors.insert(w[3], w[1]);
            }
        }
    }
    let mut bound = words[3];
    let mut fresh = || {
        let id = bound;
        bound += 1;
        id
    };
    // what to declare: per size, the unsigned type and the two constants
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let uint = match uint {
        Some(id) => id,
        None => {
            let id = fresh();
            declarations.push(instruction(OP_TYPE_INT, &[id, 32, 0]));
            id
        },
    };
    let mut sizes: BTreeMap<u32, (u32, u32, u32)> = BTreeMap::new();
    for w in &instructions {
        if !matches!(op(w), OP_IS_NAN | OP_IS_INF) || w.len() < 4 {
            continue;
        }
        let size = bool_vectors.get(&w[1]).copied().unwrap_or(1);
        if sizes.contains_key(&size) {
            continue;
        }
        let (mask, exponent) = (fresh(), fresh());
        let ty = if size == 1 {
            declarations.push(instruction(OP_CONSTANT, &[uint, mask, 0x7FFF_FFFF]));
            declarations.push(instruction(OP_CONSTANT, &[uint, exponent, 0x7F80_0000]));
            uint
        }
        else {
            let ty = match uint_vectors.get(&size) {
                Some(&ty) => ty,
                None => {
                    let ty = fresh();
                    declarations.push(instruction(OP_TYPE_VECTOR, &[ty, uint, size]));
                    ty
                },
            };
            let (m, e) = (fresh(), fresh());
            declarations.push(instruction(OP_CONSTANT, &[uint, m, 0x7FFF_FFFF]));
            declarations.push(instruction(OP_CONSTANT, &[uint, e, 0x7F80_0000]));
            let mut ms = Vec::from([ty, mask]);
            let mut es = Vec::from([ty, exponent]);
            for _ in 0..size {
                ms.push(m);
                es.push(e);
            }
            declarations.push(instruction(OP_CONSTANT_COMPOSITE, &ms));
            declarations.push(instruction(OP_CONSTANT_COMPOSITE, &es));
            ty
        };
        sizes.insert(size, (ty, mask, exponent));
    }
    let mut out = words[..5].to_vec();
    let mut declared = false;
    for w in &instructions {
        if op(w) == OP_FUNCTION && !declared {
            declared = true;
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        if matches!(op(w), OP_IS_NAN | OP_IS_INF) && w.len() >= 4 {
            let size = bool_vectors.get(&w[1]).copied().unwrap_or(1);
            let (ty, mask, exponent) = sizes[&size];
            let (bits, magnitude) = (fresh(), fresh());
            out.extend_from_slice(&instruction(OP_BITCAST, &[ty, bits, w[3]]));
            out.extend_from_slice(&instruction(OP_BITWISE_AND, &[ty, magnitude, bits, mask]));
            let compare = if op(w) == OP_IS_INF { OP_IEQUAL } else { OP_UGREATER_THAN };
            out.extend_from_slice(&instruction(compare, &[w[1], w[2], magnitude, exponent]));
            continue;
        }
        out.extend_from_slice(w);
    }
    out[3] = bound;
    out
}
                                                                                                           source/v64/src/browser/glbridge/vx/naga/src/remap.rs                                                0000644 0000000 0000000 00000023040 00000000000 017520  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! New expressions of a function put before the ones that use them: naga
//! wants an expression's operands before it, so a pass that replaces an
//! expression with a new one made of others (appended at the arena's end)
//! has the arena made again, each appended expression moved before the
//! expression it names, every handle (in the expressions, the statements,
//! the emit ranges, the named expressions and local variables' initializers)
//! remapped. An appended expression is emitted with the one it goes before.
//! Kinds of expressions and statements graphics shaders do not have (ray
//! queries, subgroups, cooperative matrices) leave the function as it was.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use naga::{Arena, Block, Expression, Function, Handle, SampleLevel, Statement};

type H = Handle<Expression>;

/// The handles an expression uses, remapped by `f`; None for a kind not done here
pub(crate) fn remap_expression(e: &Expression, f: &dyn Fn(H) -> H) -> Option<Expression> {
    use Expression as E;
    let o = |h: &Option<H>| h.map(|h| f(h));
    Some(match e {
        E::Literal(_) | E::Constant(_) | E::Override(_) | E::ZeroValue(_) | E::FunctionArgument(_) | E::GlobalVariable(_) | E::LocalVariable(_)
        | E::CallResult(_) | E::AtomicResult { .. } | E::WorkGroupUniformLoadResult { .. } => e.clone(),
        E::Compose { ty, components } => E::Compose { ty: *ty, components: components.iter().map(|&h| f(h)).collect() },
        E::Access { base, index } => E::Access { base: f(*base), index: f(*index) },
        E::AccessIndex { base, index } => E::AccessIndex { base: f(*base), index: *index },
        E::Splat { size, value } => E::Splat { size: *size, value: f(*value) },
        E::Swizzle { size, vector, pattern } => E::Swizzle { size: *size, vector: f(*vector), pattern: *pattern },
        E::Load { pointer } => E::Load { pointer: f(*pointer) },
        E::ImageSample { image, sampler, gather, coordinate, array_index, offset, level, depth_ref, clamp_to_edge } => E::ImageSample {
            image: f(*image),
            sampler: f(*sampler),
            gather: *gather,
            coordinate: f(*coordinate),
            array_index: o(array_index),
            offset: o(offset),
            level: match *level {
                SampleLevel::Auto => SampleLevel::Auto,
                SampleLevel::Zero => SampleLevel::Zero,
                SampleLevel::Exact(h) => SampleLevel::Exact(f(h)),
                SampleLevel::Bias(h) => SampleLevel::Bias(f(h)),
                SampleLevel::Gradient { x, y } => SampleLevel::Gradient { x: f(x), y: f(y) },
            },
            depth_ref: o(depth_ref),
            clamp_to_edge: *clamp_to_edge,
        },
        E::ImageLoad { image, coordinate, array_index, sample, level } => E::ImageLoad {
            image: f(*image),
            coordinate: f(*coordinate),
            array_index: o(array_index),
            sample: o(sample),
            level: o(level),
        },
        E::ImageQuery { image, query } => E::ImageQuery {
            image: f(*image),
            query: match *query {
                naga::ImageQuery::Size { level } => naga::ImageQuery::Size { level: level.map(|h| f(h)) },
                q => q,
            },
        },
        E::Unary { op, expr } => E::Unary { op: *op, expr: f(*expr) },
        E::Binary { op, left, right } => E::Binary { op: *op, left: f(*left), right: f(*right) },
        E::Select { condition, accept, reject } => E::Select { condition: f(*condition), accept: f(*accept), reject: f(*reject) },
        E::Derivative { axis, ctrl, expr } => E::Derivative { axis: *axis, ctrl: *ctrl, expr: f(*expr) },
        E::Relational { fun, argument } => E::Relational { fun: *fun, argument: f(*argument) },
        E::Math { fun, arg, arg1, arg2, arg3 } => E::Math { fun: *fun, arg: f(*arg), arg1: o(arg1), arg2: o(arg2), arg3: o(arg3) },
        E::As { expr, kind, convert } => E::As { expr: f(*expr), kind: *kind, convert: *convert },
        E::ArrayLength(h) => E::ArrayLength(f(*h)),
        _ => return None,
    })
}

/// A block's statements with their handles remapped (emit ranges by `range`); false for a kind not done here
pub(crate) fn remap_block(block: &mut Block, f: &dyn Fn(H) -> H, range: &dyn Fn(&naga::Range<Expression>) -> naga::Range<Expression>) -> bool {
    use Statement as S;
    for s in block.iter_mut() {
        let ok = match s {
            S::Emit(r) => {
                *r = range(r);
                true
            },
            S::Block(b) => remap_block(b, f, range),
            S::If { condition, accept, reject } => {
                *condition = f(*condition);
                remap_block(accept, f, range) && remap_block(reject, f, range)
            },
            S::Switch { selector, cases } => {
                *selector = f(*selector);
                cases.iter_mut().all(|c| remap_block(&mut c.body, f, range))
            },
            S::Loop { body, continuing, break_if } => {
                *break_if = break_if.map(|h| f(h));
                remap_block(body, f, range) && remap_block(continuing, f, range)
            },
            S::Break | S::Continue | S::Kill | S::ControlBarrier(_) | S::MemoryBarrier(_) => true,
            S::Return { value } => {
                *value = value.map(|h| f(h));
                true
            },
            S::Store { pointer, value } => {
                *pointer = f(*pointer);
                *value = f(*value);
                true
            },
            S::ImageStore { image, coordinate, array_index, value } => {
                *image = f(*image);
                *coordinate = f(*coordinate);
                *array_index = array_index.map(|h| f(h));
                *value = f(*value);
                true
            },
            S::Atomic { pointer, fun, value, result } => {
                *pointer = f(*pointer);
                if let naga::AtomicFunction::Exchange { compare } = fun {
                    *compare = compare.map(|h| f(h));
                }
                *value = f(*value);
                *result = result.map(|h| f(h));
                true
            },
            S::ImageAtomic { image, coordinate, array_index, fun, value } => {
                *image = f(*image);
                *coordinate = f(*coordinate);
                *array_index = array_index.map(|h| f(h));
                if let naga::AtomicFunction::Exchange { compare } = fun {
                    *compare = compare.map(|h| f(h));
                }
                *value = f(*value);
                true
            },
            S::WorkGroupUniformLoad { pointer, result } => {
                *pointer = f(*pointer);
                *result = f(*result);
                true
            },
            S::Call { arguments, result, .. } => {
                arguments.iter_mut().for_each(|h| *h = f(*h));
                *result = result.map(|h| f(h));
                true
            },
            _ => false,
        };
        if !ok {
            return false;
        }
    }
    true
}

/// The function's expressions again with each of `moves` (an appended
/// expression, the one it goes before) in its place; false (the function
/// as it was) when that cannot be done
pub fn place(function: &mut Function, moves: &[(H, H)]) -> bool {
    let count = function.expressions.len();
    let moved: BTreeMap<usize, usize> = moves.iter().map(|&(m, before)| (m.index(), before.index())).collect();
    // the order: each original expression after those moved before it
    let mut before: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for (&m, &b) in &moved {
        before.entry(b).or_default().push(m);
    }
    let mut order = Vec::with_capacity(count);
    let mut group_start = Vec::from_iter(core::iter::repeat(0usize).take(count));
    for i in 0..count {
        if moved.contains_key(&i) {
            continue;
        }
        group_start[i] = order.len();
        if let Some(list) = before.get(&i) {
            order.extend(list.iter().copied());
        }
        order.push(i);
    }
    for (&m, _) in &moved {
        if !order.contains(&m) {
            return false;
        }
    }
    let mut position = Vec::from_iter(core::iter::repeat(0usize).take(count));
    for (p, &i) in order.iter().enumerate() {
        position[i] = p;
        if moved.contains_key(&i) {
            group_start[i] = p;
        }
    }
    let handles: Vec<H> = function.expressions.iter().map(|(h, _)| h).collect();
    let at = |h: H| handles[position[h.index()]];
    // (the new handles are the old arena's, in order: handles[p] is the p-th)
    let mut arena: Arena<Expression> = Arena::new();
    for &i in &order {
        let h = handles[i];
        let Some(e) = remap_expression(&function.expressions[h], &at) else { return false };
        arena.append(e, function.expressions.get_span(h));
    }
    let range = |r: &naga::Range<Expression>| -> naga::Range<Expression> {
        match r.first_and_last() {
            Some((first, last)) => naga::Range::new_from_bounds(handles[group_start[first.index()]], handles[position[last.index()]]),
            None => r.clone(),
        }
    };
    let mut body = function.body.clone();
    if !remap_block(&mut body, &at, &range) {
        return false;
    }
    function.expressions = arena;
    function.body = body;
    let named: Vec<(H, alloc::string::String)> = function.named_expressions.iter().map(|(&h, n)| (at(h), n.clone())).collect();
    function.named_expressions.clear();
    for (h, n) in named {
        function.named_expressions.insert(h, n);
    }
    for (_, v) in function.local_variables.iter_mut() {
        v.init = v.init.map(|h| at(h));
    }
    true
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/browser/glbridge/vx/naga/src/samplemask.rs                                           0000644 0000000 0000000 00000013157 00000000000 020561  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! GLSL's gl_SampleMaskIn and gl_SampleMask are arrays of int (one element
//! for up to 32 samples), WGSL's sample_mask a u32. naga's SPIR-V front end
//! keeps GLSL's type for the entry point's argument and result member, and
//! gives the output's private variable a u32 initializer (all samples):
//! the validator refuses both. Here the argument and the result member are
//! u32, bit casts of the private arrays' element 0, and the initializer an
//! array of all ones.

use alloc::vec::Vec;
use naga::{ArraySize, Binding, Block, BuiltIn, Expression, Handle, Literal, Scalar, ScalarKind, Span, Statement, Type, TypeInner};

fn is_mask(module: &naga::Module, ty: Handle<Type>) -> bool {
    match module.types[ty].inner {
        TypeInner::Array { base, size: ArraySize::Constant(n), .. } => n.get() == 1 && module.types[base].inner == TypeInner::Scalar(Scalar::I32),
        _ => false,
    }
}

pub fn lower(module: &mut naga::Module) {
    let masks: Vec<Handle<naga::GlobalVariable>> = module.global_variables.iter()
        .filter(|(_, v)| is_mask(module, v.ty) && v.init.is_some_and(|i| matches!(module.global_expressions[i], Expression::Literal(Literal::U32(_)))))
        .map(|(h, _)| h).collect();
    for h in masks {
        let ty = module.global_variables[h].ty;
        let one = module.global_expressions.append(Expression::Literal(Literal::I32(-1)), Span::UNDEFINED);
        let init = module.global_expressions.append(Expression::Compose { ty, components: Vec::from([one]) }, Span::UNDEFINED);
        module.global_variables[h].init = Some(init);
    }
    let u32_ty = module.types.insert(Type { name: None, inner: TypeInner::Scalar(Scalar::U32) }, Span::UNDEFINED);
    for e in 0..module.entry_points.len() {
        // the argument: its store into the private array a compose of its bit cast
        let arguments: Vec<(usize, Handle<Type>)> = module.entry_points[e].function.arguments.iter().enumerate()
            .filter(|(_, a)| matches!(a.binding, Some(Binding::BuiltIn(BuiltIn::SampleMask))) && is_mask(module, a.ty))
            .map(|(i, a)| (i, a.ty)).collect();
        for (index, array_ty) in arguments {
            let f = &mut module.entry_points[e].function;
            f.arguments[index].ty = u32_ty;
            let Some((argument, _)) = f.expressions.iter().find(|(_, x)| matches!(x, Expression::FunctionArgument(i) if *i as usize == index)) else { continue };
            let mut i = 0;
            while i < f.body.len() {
                if let Statement::Store { value, .. } = &mut f.body[i] {
                    if *value == argument {
                        let first = f.expressions.len();
                        let cast = f.expressions.append(Expression::As { expr: argument, kind: ScalarKind::Sint, convert: None }, Span::UNDEFINED);
                        *value = f.expressions.append(Expression::Compose { ty: array_ty, components: Vec::from([cast]) }, Span::UNDEFINED);
                        let emit = Statement::Emit(f.expressions.range_from(first));
                        f.body.splice(i..i, Block::from_vec(Vec::from([emit])));
                        i += 1;
                    }
                }
                i += 1;
            }
        }
        // the result's member: element 0 of the array the wrapper loads, bit cast
        let Some(result) = module.entry_points[e].function.result.clone() else { continue };
        let (members, span) = match &module.types[result.ty].inner {
            TypeInner::Struct { members, span } => (members.clone(), *span),
            _ => continue,
        };
        let Some(index) = members.iter().position(|m| matches!(m.binding, Some(Binding::BuiltIn(BuiltIn::SampleMask))) && is_mask(module, m.ty)) else { continue };
        // (a struct of its own: the wrapper's compose of the old one stays valid, unused)
        let mut changed = members.clone();
        changed[index].ty = u32_ty;
        let new_ty = module.types.insert(Type { name: None, inner: TypeInner::Struct { members: changed, span } }, Span::UNDEFINED);
        let f = &mut module.entry_points[e].function;
        f.result.as_mut().unwrap().ty = new_ty;
        returns(&mut f.body, &mut f.expressions, new_ty, index);
    }
}

fn returns(block: &mut Block, expressions: &mut naga::Arena<Expression>, ty: Handle<Type>, index: usize) {
    let mut i = 0;
    while i < block.len() {
        let mut insert = None;
        match &mut block[i] {
            Statement::Return { value: Some(value) } => {
                if let Expression::Compose { ref components, .. } = expressions[*value] {
                    if components.len() > index {
                        let mut parts = components.clone();
                        let first = expressions.len();
                        let element = expressions.append(Expression::AccessIndex { base: parts[index], index: 0 }, Span::UNDEFINED);
                        parts[index] = expressions.append(Expression::As { expr: element, kind: ScalarKind::Uint, convert: None }, Span::UNDEFINED);
                        *value = expressions.append(Expression::Compose { ty, components: parts }, Span::UNDEFINED);
                        insert = Some(Statement::Emit(expressions.range_from(first)));
                    }
                }
            },
            Statement::Block(b) => returns(b, expressions, ty, index),
            Statement::If { accept, reject, .. } => {
                returns(accept, expressions, ty, index);
                returns(reject, expressions, ty, index);
            },
            _ => {},
        }
        if let Some(emit) = insert {
            block.splice(i..i, Block::from_vec(Vec::from([emit])));
            i += 1;
        }
        i += 1;
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/src/browser/glbridge/vx/naga/src/sampling.rs                                             0000644 0000000 0000000 00000007015 00000000000 020232  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The sampling of inputs and outputs decorated Centroid or Sample: naga's
//! SPIR-V front end gives a binding without an interpolation decoration
//! (GLSL's smooth, the default) perspective interpolation at the center,
//! over what the decorations said. `read` takes them from the SPIR-V,
//! `restore` puts them back on the entry points' bindings.

use alloc::vec::Vec;
use naga::{Binding, Interpolation, Sampling, TypeInner};

const OP_VARIABLE: u32 = 59;
const OP_DECORATE: u32 = 71;
const DECORATION_CENTROID: u32 = 16;
const DECORATION_SAMPLE: u32 = 17;
const DECORATION_LOCATION: u32 = 30;
const STORAGE_INPUT: u32 = 1;
const STORAGE_OUTPUT: u32 = 3;

/// The inputs' and outputs' sampling other than the center: (output, location, sampling)
pub fn read(words: &[u32]) -> Vec<(bool, u32, Sampling)> {
    use alloc::collections::BTreeMap;
    let mut storage: BTreeMap<u32, bool> = BTreeMap::new();
    let mut locations: BTreeMap<u32, u32> = BTreeMap::new();
    let mut sampling: BTreeMap<u32, Sampling> = BTreeMap::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            break;
        }
        let w = &words[at..at + count];
        match w[0] & 0xFFFF {
            OP_VARIABLE if count >= 4 && (w[3] == STORAGE_INPUT || w[3] == STORAGE_OUTPUT) => {
                storage.insert(w[2], w[3] == STORAGE_OUTPUT);
            },
            OP_DECORATE if count >= 4 && w[2] == DECORATION_LOCATION => {
                locations.insert(w[1], w[3]);
            },
            OP_DECORATE if count >= 3 && w[2] == DECORATION_CENTROID => {
                sampling.insert(w[1], Sampling::Centroid);
            },
            OP_DECORATE if count >= 3 && w[2] == DECORATION_SAMPLE => {
                sampling.insert(w[1], Sampling::Sample);
            },
            _ => {},
        }
        at += count;
    }
    sampling.iter().filter_map(|(id, s)| Some((*storage.get(id)?, *locations.get(id)?, *s))).collect()
}

/// The entry points' bindings at those locations given their sampling back
/// (before io.rs splits a matrix or array into locations after its first)
pub fn restore(module: &mut naga::Module, list: &[(bool, u32, Sampling)]) {
    if list.is_empty() {
        return;
    }
    let fix = |binding: &mut Option<Binding>, output: bool| {
        if let Some(Binding::Location { location, interpolation, sampling, .. }) = binding {
            if matches!(interpolation, Some(Interpolation::Perspective) | Some(Interpolation::Linear)) {
                if let Some((_, _, s)) = list.iter().find(|(o, l, _)| *o == output && *l == *location) {
                    *sampling = Some(*s);
                }
            }
        }
    };
    for ep in module.entry_points.iter_mut() {
        for a in ep.function.arguments.iter_mut() {
            fix(&mut a.binding, false);
        }
        let Some(result) = ep.function.result.as_mut() else { continue };
        fix(&mut result.binding, true);
        if let TypeInner::Struct { members, span } = module.types[result.ty].inner.clone() {
            let mut changed = members.clone();
            for m in changed.iter_mut() {
                fix(&mut m.binding, true);
            }
            // (UniqueArena's replace refuses a type it has)
            if changed != members {
                let name = module.types[result.ty].name.clone();
                module.types.replace(result.ty, naga::Type { name, inner: TypeInner::Struct { members: changed, span } });
            }
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/glbridge/vx/naga/src/sizes.rs                                                0000644 0000000 0000000 00000017115 00000000000 017557  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! GLSL's textureSize(sampler, lod) of a level past the base: the page's
//! view of a texture whose filter takes no mipmaps holds its base level
//! alone (so that WebGPU picks the minification filter as GL does, by the
//! unclamped λ), where WGSL's textureDimensions of a level past it has
//! nothing to answer. GL's level sizes follow from the base's, each axis
//! halved a level and at least 1, so the query becomes the base level's
//! (level 0 of the view) shifted right by the lod on its spatial axes
//! (an array's layer count as it is). A query of level 0 (a constant) is
//! left as it is.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_EXT_INST_IMPORT: u32 = 11;
const OP_EXT_INST: u32 = 12;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_IMAGE: u32 = 25;
const OP_TYPE_SAMPLED_IMAGE: u32 = 27;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_COMPOSITE_CONSTRUCT: u32 = 80;
const OP_COMPOSITE_EXTRACT: u32 = 81;
const OP_IMAGE_QUERY_SIZE_LOD: u32 = 103;
const OP_SHIFT_RIGHT_ARITHMETIC: u32 = 195;
const GLSL_S_MAX: u32 = 42;
const DIM_1D: u32 = 0;
const DIM_3D: u32 = 2;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The opcodes in a function that have no result type (intsample.rs's)
fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

/// "GLSL.std.450" as an OpExtInstImport's name words
fn glsl_name() -> Vec<u32> {
    let mut bytes = b"GLSL.std.450".to_vec();
    bytes.resize((bytes.len() / 4 + 1) * 4, 0);
    bytes.chunks(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
}

/// The module with its size queries of levels past the base made the base's shifted, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let types: BTreeMap<u32, &[u32]> = instructions[..first_function].iter().filter(|w| (19..=39).contains(&op(w)) && w.len() >= 2).map(|w| (w[1], *w)).collect();
    let constants: BTreeMap<u32, (u32, u32)> = instructions[..first_function].iter().filter(|w| op(w) == OP_CONSTANT && w.len() == 4).map(|w| (w[2], (w[1], w[3]))).collect();
    let defs: BTreeMap<u32, &[u32]> = instructions[first_function..].iter().filter(|w| w.len() >= 3 && !untyped(op(w))).map(|w| (w[2], *w)).collect();
    // an image operand's image type: its definition's result type (an image, or a sampled image's image)
    let image_type = |image: u32| -> Option<&[u32]> {
        let ty = types.get(&defs.get(&image)?[1])?;
        let ty = if op(ty) == OP_TYPE_SAMPLED_IMAGE { types.get(&ty[2])? } else { ty };
        (op(ty) == OP_TYPE_IMAGE && ty.len() >= 9).then_some(*ty)
    };
    let queries: Vec<usize> = instructions.iter().enumerate().skip(first_function)
        .filter(|(_, w)| op(w) == OP_IMAGE_QUERY_SIZE_LOD && w.len() == 5 && constants.get(&w[4]).map_or(true, |&(_, v)| v != 0) && image_type(w[3]).is_some())
        .map(|(i, _)| i).collect();
    if queries.is_empty() {
        return words.to_vec();
    }
    let mut bound = words[3];
    let mut fresh = || { bound += 1; bound - 1 };
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut header: Vec<Vec<u32>> = Vec::new();
    let glsl = match instructions.iter().find(|w| op(w) == OP_EXT_INST_IMPORT && w[2..] == glsl_name()[..]) {
        Some(w) => w[1],
        None => {
            let id = fresh();
            let mut operands = Vec::from([id]);
            operands.extend(glsl_name());
            header.push(instruction(OP_EXT_INST_IMPORT, &operands));
            id
        },
    };
    let mut body: Vec<Vec<u32>> = Vec::new();
    let mut zeros: BTreeMap<u32, u32> = BTreeMap::new();
    let mut ones: BTreeMap<u32, u32> = BTreeMap::new();
    for (i, w) in instructions.iter().enumerate() {
        if !queries.contains(&i) {
            body.push(w.to_vec());
            continue;
        }
        let (result_type, result, image, lod) = (w[1], w[2], w[3], w[4]);
        let image_ty = image_type(image).unwrap();
        let (dim, arrayed) = (image_ty[3], image_ty[5] != 0);
        let spatial = if dim == DIM_1D { 1 } else if dim == DIM_3D { 3 } else { 2 };
        // the component type: the result's (an int, or a vector of them)
        let (int, count) = match types.get(&result_type) {
            Some(t) if op(t) == OP_TYPE_VECTOR => (t[2], t[3]),
            Some(t) if op(t) == OP_TYPE_INT => (result_type, 1),
            _ => { body.push(w.to_vec()); continue; },
        };
        let constant = |map: &mut BTreeMap<u32, u32>, value: u32, declarations: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32| *map.entry(int).or_insert_with(|| {
            let id = constants.iter().find(|(_, &(t, v))| t == int && v == value).map(|(&id, _)| id).unwrap_or_else(|| {
                let id = fresh();
                declarations.push(instruction(OP_CONSTANT, &[int, id, value]));
                id
            });
            id
        });
        let zero = constant(&mut zeros, 0, &mut declarations, &mut fresh);
        let one = constant(&mut ones, 1, &mut declarations, &mut fresh);
        let base = fresh();
        body.push(instruction(OP_IMAGE_QUERY_SIZE_LOD, &[result_type, base, image, zero]));
        let shift = |body: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32, x: u32| {
            let (shifted, at_least) = (fresh(), fresh());
            body.push(instruction(OP_SHIFT_RIGHT_ARITHMETIC, &[int, shifted, x, lod]));
            body.push(instruction(OP_EXT_INST, &[int, at_least, glsl, GLSL_S_MAX, shifted, one]));
            at_least
        };
        if count == 1 {
            // (a scalar's: the shifted value under the query's own id)
            let shifted = fresh();
            body.push(instruction(OP_SHIFT_RIGHT_ARITHMETIC, &[int, shifted, base, lod]));
            body.push(instruction(OP_EXT_INST, &[int, result, glsl, GLSL_S_MAX, shifted, one]));
            continue;
        }
        let mut parts = Vec::new();
        for k in 0..count {
            let part = fresh();
            body.push(instruction(OP_COMPOSITE_EXTRACT, &[int, part, base, k]));
            // (the layer count of an array: as it is)
            parts.push(if k < spatial && !(arrayed && k == count - 1) { shift(&mut body, &mut fresh, part) } else { part });
        }
        let mut operands = Vec::from([result_type, result]);
        operands.extend(parts);
        body.push(instruction(OP_COMPOSITE_CONSTRUCT, &operands));
    }
    // (the import with the others, the constants before the first function)
    let first_import = body.iter().position(|w| op(w) == OP_EXT_INST_IMPORT || op(w) == 14).unwrap_or(0);
    let mut out = words[..5].to_vec();
    out[3] = bound;
    for (i, w) in body.iter().enumerate() {
        if i == first_import {
            for h in &header {
                out.extend_from_slice(h);
            }
        }
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    out
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/glbridge/vx/naga/src/split.rs                                                0000644 0000000 0000000 00000025241 00000000000 017554  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Combined image samplers (GLSL's `sampler2D`, as glslang writes them) as
//! separate images and samplers: naga reads only the separate kind
//! (`OpSampledImage` of an image and a sampler). Each UniformConstant
//! variable of an `OpTypeSampledImage` (or an array of them) becomes a
//! variable of the image, and a new one of the sampler, bound at the same
//! set with the binding `SAMPLER_BINDING + binding`; each load of it loads
//! both and makes the sampled image of them.

use alloc::vec::Vec;
use alloc::collections::BTreeMap;

/// The bindings of the samplers split off: SAMPLER_BINDING + the binding
pub const SAMPLER_BINDING: u32 = 0x10000;

const OP_ENTRY_POINT: u32 = 15;
const OP_TYPE_SAMPLER: u32 = 26;
const OP_TYPE_SAMPLED_IMAGE: u32 = 27;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_RUNTIME_ARRAY: u32 = 29;
const OP_TYPE_POINTER: u32 = 32;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_LOAD: u32 = 61;
const OP_ACCESS_CHAIN: u32 = 65;
const OP_IN_BOUNDS_ACCESS_CHAIN: u32 = 66;
const OP_DECORATE: u32 = 71;
const OP_SAMPLED_IMAGE: u32 = 86;
const DECORATION_BINDING: u32 = 33;
const DECORATION_DESCRIPTOR_SET: u32 = 34;
const UNIFORM_CONSTANT: u32 = 0;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// What a combined pointer type points at
#[derive(Clone, Copy)]
enum Pointee {
    /// a sampled image of this image type
    One { image: u32 },
    /// an array of them: (length id or none for runtime arrays)
    Array { image: u32, length: Option<u32> },
}

/// The module with its combined image samplers split, or the words as they
/// were when it has none
pub fn split(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    // the instructions
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |i: &[u32]| i[0] & 0xFFFF;

    let mut sampled = BTreeMap::new(); // sampled image type -> image type
    let mut arrays = BTreeMap::new(); // array type -> (sampled image type, length)
    let mut sampler_type = None;
    for i in &instructions {
        match op(i) {
            OP_TYPE_SAMPLED_IMAGE => { sampled.insert(i[1], i[2]); }
            OP_TYPE_SAMPLER => { sampler_type = Some(i[1]); }
            _ => {}
        }
    }
    if sampled.is_empty() {
        return words.to_vec();
    }
    for i in &instructions {
        match op(i) {
            OP_TYPE_ARRAY if sampled.contains_key(&i[2]) => { arrays.insert(i[1], (i[2], Some(i[3]))); }
            OP_TYPE_RUNTIME_ARRAY if sampled.contains_key(&i[2]) => { arrays.insert(i[1], (i[2], None)); }
            _ => {}
        }
    }
    let mut pointers = BTreeMap::new(); // pointer type -> pointee
    for i in &instructions {
        if op(i) == OP_TYPE_POINTER && i[2] == UNIFORM_CONSTANT {
            if let Some(&image) = sampled.get(&i[3]) {
                pointers.insert(i[1], Pointee::One { image });
            } else if let Some(&(s, length)) = arrays.get(&i[3]) {
                pointers.insert(i[1], Pointee::Array { image: sampled[&s], length });
            }
        }
    }
    // the variables
    let mut variables = BTreeMap::new(); // combined variable -> pointee
    for i in &instructions {
        if op(i) == OP_VARIABLE && i[3] == UNIFORM_CONSTANT {
            if let Some(&p) = pointers.get(&i[1]) {
                variables.insert(i[2], p);
            }
        }
    }
    if variables.is_empty() {
        return words.to_vec();
    }

    let mut bound = words[3];
    let mut fresh = || { let id = bound; bound += 1; id };
    let mut types: Vec<Vec<u32>> = Vec::new();
    let sampler = match sampler_type {
        Some(id) => id,
        None => {
            let id = fresh();
            types.push(instruction(OP_TYPE_SAMPLER, &[id]));
            id
        }
    };
    let pointer_to_sampler = fresh();
    types.push(instruction(OP_TYPE_POINTER, &[pointer_to_sampler, UNIFORM_CONSTANT, sampler]));
    // per image type: a pointer to it; per array: arrays of images and samplers, pointers to them
    let mut pointer_to_image = BTreeMap::new();
    let mut array_types = BTreeMap::new(); // (image, length) -> (pointer to image array, pointer to sampler array)
    let mut new_variables = BTreeMap::new(); // combined variable -> (new type, sampler variable, sampler variable's type)
    for (&variable, &pointee) in &variables {
        let (image, length) = match pointee {
            Pointee::One { image } => (image, None),
            Pointee::Array { image, length } => (image, Some(length)),
        };
        let image_pointer = *pointer_to_image.entry(image).or_insert_with(|| {
            let id = fresh();
            types.push(instruction(OP_TYPE_POINTER, &[id, UNIFORM_CONSTANT, image]));
            id
        });
        match length {
            None => { new_variables.insert(variable, (image_pointer, fresh(), pointer_to_sampler)); }
            Some(length) => {
                let key = (image, length.unwrap_or(0));
                let (image_array_pointer, sampler_array_pointer) = *array_types.entry(key).or_insert_with(|| {
                    let (image_array, sampler_array) = (fresh(), fresh());
                    match length {
                        Some(n) => {
                            types.push(instruction(OP_TYPE_ARRAY, &[image_array, image, n]));
                            types.push(instruction(OP_TYPE_ARRAY, &[sampler_array, sampler, n]));
                        }
                        None => {
                            types.push(instruction(OP_TYPE_RUNTIME_ARRAY, &[image_array, image]));
                            types.push(instruction(OP_TYPE_RUNTIME_ARRAY, &[sampler_array, sampler]));
                        }
                    }
                    let (a, b) = (fresh(), fresh());
                    types.push(instruction(OP_TYPE_POINTER, &[a, UNIFORM_CONSTANT, image_array]));
                    types.push(instruction(OP_TYPE_POINTER, &[b, UNIFORM_CONSTANT, sampler_array]));
                    (a, b)
                });
                new_variables.insert(variable, (image_array_pointer, fresh(), sampler_array_pointer));
            }
        }
    }
    // decorations of the samplers: the variable's set, its binding + SAMPLER_BINDING
    let mut decorations: Vec<Vec<u32>> = Vec::new();
    for i in &instructions {
        if op(i) == OP_DECORATE && i.len() >= 4 {
            if let Some(&(_, sampler_variable, _)) = new_variables.get(&i[1]) {
                match i[2] {
                    DECORATION_DESCRIPTOR_SET => decorations.push(instruction(OP_DECORATE, &[sampler_variable, DECORATION_DESCRIPTOR_SET, i[3]])),
                    DECORATION_BINDING => decorations.push(instruction(OP_DECORATE, &[sampler_variable, DECORATION_BINDING, SAMPLER_BINDING + i[3]])),
                    _ => {}
                }
            }
        }
    }

    // the rewrite
    let mut out: Vec<u32> = words[..5].to_vec();
    let mut decorated = false;
    let mut typed = false;
    // access chains into combined arrays: chain -> its sampler twin
    let mut chains: BTreeMap<u32, u32> = BTreeMap::new();
    for i in &instructions {
        let o = op(i);
        // (the new decorations after the annotations, before the first
        // type, constant, variable or function; the new types, then the
        // variables of the images and samplers, after every other global:
        // after everything they name, whatever the order of the types)
        if !decorated && ((19..=52).contains(&o) || o == OP_VARIABLE || o == OP_FUNCTION || o == 1) {
            for d in &decorations { out.extend_from_slice(d); }
            decorated = true;
        }
        if !typed && o == OP_FUNCTION {
            for t in &types { out.extend_from_slice(t); }
            for (&variable, &(image_type, sampler_variable, sampler_type)) in &new_variables {
                out.extend(instruction(OP_VARIABLE, &[image_type, variable, UNIFORM_CONSTANT]));
                out.extend(instruction(OP_VARIABLE, &[sampler_type, sampler_variable, UNIFORM_CONSTANT]));
            }
            typed = true;
        }
        match o {
            OP_ENTRY_POINT => {
                // the interface: the samplers too
                let mut operands = i[1..].to_vec();
                // (execution model, function, name words..., interface ids: the name ends with a zero byte)
                let mut j = 3;
                while j < operands.len() && operands[j] & 0xFF00_0000 != 0 { j += 1; }
                j += 1;
                let interface: Vec<u32> = operands.get(j..).map(|s| s.to_vec()).unwrap_or_default();
                for id in interface {
                    if let Some(&(_, sampler_variable, _)) = new_variables.get(&id) { operands.push(sampler_variable); }
                }
                out.extend(instruction(OP_ENTRY_POINT, &operands));
            }
            // (made again before the first function)
            OP_VARIABLE if new_variables.contains_key(&i[2]) => {}
            OP_ACCESS_CHAIN | OP_IN_BOUNDS_ACCESS_CHAIN if new_variables.contains_key(&i[3]) => {
                let (_, sampler_variable, _) = new_variables[&i[3]];
                let image = match variables[&i[3]] { Pointee::Array { image, .. } | Pointee::One { image } => image };
                let twin = fresh();
                let mut operands = i[1..].to_vec();
                operands[0] = pointer_to_image[&image];
                out.extend(instruction(o, &operands));
                operands[0] = pointer_to_sampler;
                operands[1] = twin;
                operands[2] = sampler_variable;
                out.extend(instruction(o, &operands));
                chains.insert(i[2], twin);
            }
            OP_LOAD if sampled.contains_key(&i[1]) && (new_variables.contains_key(&i[3]) || chains.contains_key(&i[3])) => {
                let image = sampled[&i[1]];
                let sampler_pointer = match new_variables.get(&i[3]) { Some(&(_, v, _)) => v, None => chains[&i[3]] };
                let (loaded_image, loaded_sampler) = (fresh(), fresh());
                out.extend(instruction(OP_LOAD, &[image, loaded_image, i[3]]));
                out.extend(instruction(OP_LOAD, &[sampler, loaded_sampler, sampler_pointer]));
                out.extend(instruction(OP_SAMPLED_IMAGE, &[i[1], i[2], loaded_image, loaded_sampler]));
            }
            _ => out.extend_from_slice(i),
        }
    }
    out[3] = bound;
    out
}
                                                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/glbridge/vx/naga/src/structio.rs                                             0000644 0000000 0000000 00000011626 00000000000 020277  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Outputs of a struct type at a location (GLSL's `out S var;`, a struct
//! varying): naga's SPIR-V front end makes an output struct's members the
//! entry point's results only when they have bindings of their own, so the
//! whole output went missing (and the next stage's input had nothing to
//! read). Here each member gets a location of its own, consecutive from the
//! variable's (a matrix's columns, an array's elements), with the
//! variable's interpolation decorations; io.rs then splits them as it does
//! any other output.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;

const OP_TYPE_MATRIX: u32 = 24;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const STORAGE_OUTPUT: u32 = 3;
const DECORATION_BUILTIN: u32 = 11;
const DECORATION_LOCATION: u32 = 30;
/// what a member takes of its variable: NoPerspective, Flat, Centroid, Sample
const INTERPOLATION: [u32; 4] = [13, 14, 16, 17];

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

/// The module with its struct outputs' members at locations of their own, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let mut types: BTreeMap<u32, &[u32]> = BTreeMap::new();
    let mut constants: BTreeMap<u32, u32> = BTreeMap::new();
    let mut decorations: BTreeMap<u32, Vec<(u32, u32)>> = BTreeMap::new();
    let mut member_decorated: BTreeMap<u32, bool> = BTreeMap::new();
    let mut outputs: Vec<(u32, u32)> = Vec::new();
    for w in &instructions {
        match op(w) {
            19..=39 if w.len() >= 2 => {
                types.insert(w[1], *w);
            },
            OP_CONSTANT if w.len() == 4 => {
                constants.insert(w[2], w[3]);
            },
            OP_DECORATE if w.len() >= 3 => decorations.entry(w[1]).or_default().push((w[2], w.get(3).copied().unwrap_or(0))),
            OP_MEMBER_DECORATE if w.len() >= 4 && (w[3] == DECORATION_LOCATION || w[3] == DECORATION_BUILTIN) => {
                member_decorated.insert(w[1], true);
            },
            OP_VARIABLE if w.len() >= 4 && w[3] == STORAGE_OUTPUT => outputs.push((w[2], w[1])),
            _ => {},
        }
    }
    // the locations a type takes
    fn span(types: &BTreeMap<u32, &[u32]>, constants: &BTreeMap<u32, u32>, ty: u32) -> u32 {
        match types.get(&ty) {
            Some(t) if t[0] & 0xFFFF == OP_TYPE_MATRIX => t[3],
            Some(t) if t[0] & 0xFFFF == OP_TYPE_ARRAY => constants.get(&t[3]).copied().unwrap_or(1) * span(types, constants, t[2]),
            Some(t) if t[0] & 0xFFFF == OP_TYPE_STRUCT => t[2..].iter().map(|&m| span(types, constants, m)).sum(),
            _ => 1,
        }
    }
    let mut added: Vec<Vec<u32>> = Vec::new();
    for (var, pointer) in outputs {
        let Some(p) = types.get(&pointer).filter(|p| op(p) == OP_TYPE_POINTER && p.len() >= 4) else { continue };
        let ty = p[3];
        let Some(s) = types.get(&ty).filter(|s| op(s) == OP_TYPE_STRUCT) else { continue };
        if member_decorated.contains_key(&ty) {
            continue;
        }
        let decorated = decorations.get(&var).cloned().unwrap_or_default();
        let Some(&(_, location)) = decorated.iter().find(|(d, _)| *d == DECORATION_LOCATION) else { continue };
        let mut next = location;
        for (m, &member) in s[2..].iter().enumerate() {
            added.push(instruction(OP_MEMBER_DECORATE, &[ty, m as u32, DECORATION_LOCATION, next]));
            for &(d, _) in decorated.iter().filter(|(d, _)| INTERPOLATION.contains(d)) {
                added.push(instruction(OP_MEMBER_DECORATE, &[ty, m as u32, d]));
            }
            next += span(&types, &constants, member);
        }
        member_decorated.insert(ty, true);
    }
    if added.is_empty() {
        return words.to_vec();
    }
    // (the new decorations with the others: before the first type)
    let first_type = instructions.iter().position(|w| (19..=39).contains(&op(w)) || op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    let mut out = words[..5].to_vec();
    for (i, w) in instructions.iter().enumerate() {
        if i == first_type {
            for d in &added {
                out.extend_from_slice(d);
            }
        }
        out.extend_from_slice(w);
    }
    out
}
                                                                                                          source/v64/src/browser/glbridge/vx/naga/src/subpass.rs                                              0000644 0000000 0000000 00000020124 00000000000 020074  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Input attachments (`subpassInput`, SubpassData images): WGSL has none, so
//! each becomes a 2D (or multisampled 2D) texture of the same binding, read
//! at the fragment's position: OpImageRead's coordinate (an offset) plus
//! `gl_FragCoord.xy` (declared when the shader has none). VX binds the view
//! as a texture, and a copy of it when it is attached to the draw's pass
//! (vx_executor.js attachmentCopies).

use alloc::vec::Vec;

const OP_CAPABILITY: u32 = 17;
const OP_ENTRY_POINT: u32 = 15;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_FLOAT: u32 = 22;
const OP_TYPE_VECTOR: u32 = 23;
const OP_TYPE_IMAGE: u32 = 25;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_LOAD: u32 = 61;
const OP_DECORATE: u32 = 71;
const OP_VECTOR_SHUFFLE: u32 = 79;
const OP_IMAGE_FETCH: u32 = 95;
const OP_IMAGE_READ: u32 = 98;
const OP_CONVERT_F_TO_S: u32 = 110;
const OP_I_ADD: u32 = 128;
const DIM_SUBPASS_DATA: u32 = 6;
const CAPABILITY_INPUT_ATTACHMENT: u32 = 40;
const DECORATION_BUILTIN: u32 = 11;
const DECORATION_INPUT_ATTACHMENT_INDEX: u32 = 43;
const BUILTIN_FRAG_COORD: u32 = 15;
const STORAGE_INPUT: u32 = 1;
const IMAGE_OPERANDS_LOD: u32 = 2;
const IMAGE_OPERANDS_SAMPLE: u32 = 0x40;
const EXECUTION_MODEL_FRAGMENT: u32 = 4;

fn instruction(op: u32, operands: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(operands.len() + 1);
    out.push((operands.len() as u32 + 1) << 16 | op);
    out.extend_from_slice(operands);
    out
}

fn untyped(op: u32) -> bool { matches!(op, 8 | 56 | 62 | 63 | 99 | 224 | 225 | 246..=255 | 317) }

/// The module with its input attachments made textures, or the words as they were
pub fn lower(words: &[u32]) -> Vec<u32> {
    if words.len() < 5 {
        return words.to_vec();
    }
    let mut instructions: Vec<Vec<u32>> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        instructions.push(words[at..at + count].to_vec());
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let subpass: Vec<u32> = instructions.iter().filter(|w| op(w) == OP_TYPE_IMAGE && w.len() >= 9 && w[3] == DIM_SUBPASS_DATA).map(|w| w[1]).collect();
    if subpass.is_empty() {
        return words.to_vec();
    }
    let mut bound = words[3];
    let mut fresh = || {
        bound += 1;
        bound - 1
    };
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    // the types and the fragment position this needs, existing or new
    let find = |pred: &dyn Fn(&[u32]) -> bool| instructions[..first_function].iter().find(|w| pred(w)).map(|w| w[1]);
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut annotations: Vec<Vec<u32>> = Vec::new();
    let float = match find(&|w| op(w) == OP_TYPE_FLOAT && w[2] == 32) {
        Some(id) => id,
        None => { let id = fresh(); declarations.push(instruction(OP_TYPE_FLOAT, &[id, 32])); id },
    };
    let int = match find(&|w| op(w) == OP_TYPE_INT && w[2] == 32 && w[3] == 1) {
        Some(id) => id,
        None => { let id = fresh(); declarations.push(instruction(OP_TYPE_INT, &[id, 32, 1])); id },
    };
    let vector = |component: u32, n: u32, declarations: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32| -> u32 {
        if let Some(id) = instructions[..first_function].iter().chain(declarations.iter())
            .find(|w| op(w) == OP_TYPE_VECTOR && w[2] == component && w[3] == n).map(|w| w[1]) {
            return id;
        }
        let id = fresh();
        declarations.push(instruction(OP_TYPE_VECTOR, &[id, component, n]));
        id
    };
    let vec4 = vector(float, 4, &mut declarations, &mut fresh);
    let vec2 = vector(float, 2, &mut declarations, &mut fresh);
    let ivec2 = vector(int, 2, &mut declarations, &mut fresh);
    let zero = match find(&|w| op(w) == OP_CONSTANT && w[1] == int && w[3] == 0) {
        Some(_) => instructions[..first_function].iter().find(|w| op(w) == OP_CONSTANT && w[1] == int && w[3] == 0).map(|w| w[2]).unwrap(),
        None => { let id = fresh(); declarations.push(instruction(OP_CONSTANT, &[int, id, 0])); id },
    };
    // gl_FragCoord: the shader's, or a new input
    let frag_coord_vars: Vec<u32> = instructions.iter().filter(|w| op(w) == OP_DECORATE && w.len() >= 4 && w[2] == DECORATION_BUILTIN && w[3] == BUILTIN_FRAG_COORD)
        .map(|w| w[1]).collect();
    let frag_coord = match instructions[..first_function].iter().find(|w| op(w) == OP_VARIABLE && frag_coord_vars.contains(&w[2])) {
        Some(w) => w[2],
        None => {
            let pointer = match instructions[..first_function].iter().find(|w| op(w) == OP_TYPE_POINTER && w[2] == STORAGE_INPUT && w[3] == vec4) {
                Some(w) => w[1],
                None => { let id = fresh(); declarations.push(instruction(OP_TYPE_POINTER, &[id, STORAGE_INPUT, vec4])); id },
            };
            let id = fresh();
            declarations.push(instruction(OP_VARIABLE, &[pointer, id, STORAGE_INPUT]));
            annotations.push(instruction(OP_DECORATE, &[id, DECORATION_BUILTIN, BUILTIN_FRAG_COORD]));
            id
        },
    };
    let declared_new_input = !instructions[..first_function].iter().any(|w| op(w) == OP_VARIABLE && w[2] == frag_coord);
    // the types of values, for the reads' images
    let mut type_of = alloc::collections::BTreeMap::new();
    for w in &instructions[first_function..] {
        if w.len() >= 3 && !untyped(op(w)) && op(w) != 248 {
            type_of.insert(w[2], w[1]);
        }
    }
    let mut out: Vec<u32> = words[..5].to_vec();
    let first_global = instructions.iter().position(|w| matches!(op(w), 19..=39 | 41..=52 | OP_VARIABLE)).unwrap_or(first_function);
    for (i, w) in instructions.iter().enumerate() {
        let o = op(w);
        if i == first_global {
            for a in &annotations {
                out.extend_from_slice(a);
            }
        }
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        if o == OP_CAPABILITY && w.get(1) == Some(&CAPABILITY_INPUT_ATTACHMENT) {
            continue;
        }
        if o == OP_DECORATE && w.len() >= 3 && w[2] == DECORATION_INPUT_ATTACHMENT_INDEX {
            continue;
        }
        if o == OP_TYPE_IMAGE && subpass.contains(&w[1]) {
            // a 2D sampled image of the same texel type and multisampling
            out.extend_from_slice(&instruction(OP_TYPE_IMAGE, &[w[1], w[2], 1, w[4], 0, w[6], 1, 0]));
            continue;
        }
        if o == OP_ENTRY_POINT && declared_new_input && w.len() >= 3 && w[1] == EXECUTION_MODEL_FRAGMENT {
            let mut e = w.clone();
            e.push(frag_coord);
            e[0] = (e.len() as u32) << 16 | OP_ENTRY_POINT;
            out.extend_from_slice(&e);
            continue;
        }
        if o == OP_IMAGE_READ && w.len() >= 5 && type_of.get(&w[3]).is_some_and(|t| subpass.contains(t)) {
            let (rt, result, image, coord) = (w[1], w[2], w[3], w[4]);
            let ms = w.len() >= 7 && w[5] & IMAGE_OPERANDS_SAMPLE != 0;
            let (fc, xy, ixy, place) = (fresh(), fresh(), fresh(), fresh());
            out.extend_from_slice(&instruction(OP_LOAD, &[vec4, fc, frag_coord]));
            out.extend_from_slice(&instruction(OP_VECTOR_SHUFFLE, &[vec2, xy, fc, fc, 0, 1]));
            out.extend_from_slice(&instruction(OP_CONVERT_F_TO_S, &[ivec2, ixy, xy]));
            out.extend_from_slice(&instruction(OP_I_ADD, &[ivec2, place, ixy, coord]));
            if ms {
                out.extend_from_slice(&instruction(OP_IMAGE_FETCH, &[rt, result, image, place, IMAGE_OPERANDS_SAMPLE, w[6]]));
            }
            else {
                out.extend_from_slice(&instruction(OP_IMAGE_FETCH, &[rt, result, image, place, IMAGE_OPERANDS_LOD, zero]));
            }
            continue;
        }
        out.extend_from_slice(w);
    }
    if first_function == instructions.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out[3] = bound;
    out
}
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/browser/glbridge/vx/naga/src/switches.rs                                             0000644 0000000 0000000 00000016512 00000000000 020253  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Switch cases that fall through (GLSL allows them, WGSL has no fallthrough
//! and naga's WGSL writer does not do them): a case that falls through into
//! the next gets a copy of the next one's statements (and so on, while they
//! fall through too), its expressions copied as new ones, so that it ends as
//! the next one does. Cases with nothing in them that fall through stay
//! (naga writes them as one case of several values).

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use naga::{Arena, Block, Expression, Handle, Span, Statement};

type H = Handle<Expression>;

/// A copy of a block: its emitted expressions copied (`map`, old to new),
/// the call and atomic results new ones; None for a kind of statement not done
fn copy(block: &Block, expressions: &mut Arena<Expression>, map: &mut BTreeMap<usize, H>) -> Option<Block> {
    let mut out = Vec::new();
    for statement in block.iter() {
        let s = match statement {
            Statement::Emit(range) => {
                let first = expressions.len();
                for h in range.clone() {
                    let e = {
                        let m = &*map;
                        crate::remap::remap_expression(&expressions[h], &|x: H| m.get(&x.index()).copied().unwrap_or(x))?
                    };
                    let new = expressions.append(e, Span::UNDEFINED);
                    map.insert(h.index(), new);
                }
                Statement::Emit(expressions.range_from(first))
            },
            Statement::Block(b) => Statement::Block(copy(b, expressions, map)?),
            Statement::If { condition, accept, reject } => {
                let condition = map.get(&condition.index()).copied().unwrap_or(*condition);
                Statement::If { condition, accept: copy(accept, expressions, map)?, reject: copy(reject, expressions, map)? }
            },
            Statement::Loop { body, continuing, break_if } => {
                let body = copy(body, expressions, map)?;
                let continuing = copy(continuing, expressions, map)?;
                let break_if = break_if.map(|h| map.get(&h.index()).copied().unwrap_or(h));
                Statement::Loop { body, continuing, break_if }
            },
            Statement::Switch { selector, cases } => {
                let selector = map.get(&selector.index()).copied().unwrap_or(*selector);
                let mut new_cases = Vec::new();
                for case in cases {
                    new_cases.push(naga::SwitchCase { value: case.value, body: copy(&case.body, expressions, map)?, fall_through: case.fall_through });
                }
                Statement::Switch { selector, cases: new_cases }
            },
            Statement::Call { function, arguments, result } => {
                let result = match result {
                    Some(r) => {
                        let new = expressions.append(Expression::CallResult(*function), Span::UNDEFINED);
                        map.insert(r.index(), new);
                        Some(new)
                    },
                    None => None,
                };
                let arguments = arguments.iter().map(|h| map.get(&h.index()).copied().unwrap_or(*h)).collect();
                Statement::Call { function: *function, arguments, result }
            },
            Statement::Atomic { result: Some(r), .. } => {
                let ty = match expressions[*r] {
                    Expression::AtomicResult { ty, comparison } => Expression::AtomicResult { ty, comparison },
                    _ => return None,
                };
                let new = expressions.append(ty, Span::UNDEFINED);
                map.insert(r.index(), new);
                let mut b = Block::from_vec(Vec::from([statement.clone()]));
                let m = &*map;
                if !crate::remap::remap_block(&mut b, &|x: H| m.get(&x.index()).copied().unwrap_or(x), &|r| r.clone()) {
                    return None;
                }
                b.span_into_iter().next().map(|(s, _)| s)?
            },
            other => {
                let mut b = Block::from_vec(Vec::from([other.clone()]));
                let m = &*map;
                if !crate::remap::remap_block(&mut b, &|x: H| m.get(&x.index()).copied().unwrap_or(x), &|r| r.clone()) {
                    return None;
                }
                b.span_into_iter().next().map(|(s, _)| s)?
            },
        };
        out.push(s);
    }
    Some(Block::from_vec(out))
}

/// The switches of a block (and those within), their falling cases closed
fn fix(block: &mut Block, expressions: &mut Arena<Expression>) -> bool {
    for statement in block.iter_mut() {
        let ok = match statement {
            Statement::Block(b) => fix(b, expressions),
            Statement::If { accept, reject, .. } => fix(accept, expressions) && fix(reject, expressions),
            Statement::Loop { body, continuing, .. } => fix(body, expressions) && fix(continuing, expressions),
            Statement::Switch { cases, .. } => {
                let mut ok = cases.iter_mut().all(|c| fix(&mut c.body, expressions));
                // from the last: a case falling into the next takes a copy of the next's statements
                for i in (0..cases.len()).rev() {
                    if !ok || !cases[i].fall_through || cases[i].body.is_empty() || i + 1 >= cases.len() {
                        continue;
                    }
                    let next = cases[i + 1].body.clone();
                    match copy(&next, expressions, &mut BTreeMap::new()) {
                        Some(copied) => {
                            let mut copied = copied;
                            cases[i].body.append(&mut copied);
                            cases[i].fall_through = cases[i + 1].fall_through;
                        },
                        None => ok = false,
                    }
                }
                ok
            },
            _ => true,
        };
        if !ok {
            return false;
        }
    }
    true
}

/// The module's falling switch cases closed (each function as it was where that cannot be done)
pub fn lower(module: &mut naga::Module) {
    let any = |b: &Block| format_has_fall_through(b);
    let handles: Vec<Handle<naga::Function>> = module.functions.iter().map(|(h, _)| h).collect();
    for h in handles {
        let f = &mut module.functions[h];
        if any(&f.body) {
            let mut copy = f.clone();
            if fix(&mut copy.body, &mut copy.expressions) {
                *f = copy;
            }
        }
    }
    for e in module.entry_points.iter_mut() {
        if any(&e.function.body) {
            let mut copy = e.function.clone();
            if fix(&mut copy.body, &mut copy.expressions) {
                e.function = copy;
            }
        }
    }
}

/// Whether a block has a case with statements that falls through
fn format_has_fall_through(block: &Block) -> bool {
    block.iter().any(|s| match s {
        Statement::Block(b) => format_has_fall_through(b),
        Statement::If { accept, reject, .. } => format_has_fall_through(accept) || format_has_fall_through(reject),
        Statement::Loop { body, continuing, .. } => format_has_fall_through(body) || format_has_fall_through(continuing),
        Statement::Switch { cases, .. } => cases.iter().any(|c| c.fall_through && !c.body.is_empty() || format_has_fall_through(&c.body)),
        _ => false,
    })
}
                                                                                                                                                                                      source/v64/src/browser/glbridge/vx/naga/src/tessellation.rs                                         0000644 0000000 0000000 00000070555 00000000000 021137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Tessellation (GLES 3.2, docs/gles3-plan.md L6) as compute shaders, as
//! geometry.rs does geometry shaders: WebGPU has no tessellation stages. A
//! draw of patches runs its vertex shader as a compute shader (xfb.rs,
//! every output captured), then
//! - the control shader (`Stage::Control`) a workgroup a patch, an
//!   invocation an output vertex: its inputs private variables the wrapper
//!   fills from the vertex records, its outputs workgroup variables
//!   (barrier() a workgroup barrier with workgroup memory), written after it
//!   as a record an output vertex and a record a patch whose first eight
//!   words are the tess factors as GX's tessellator (tessellator_wgsl.js)
//!   reads them for the domain the caller gives (triangles: three edges and
//!   the inside; quads: four edges, two insides; isolines: two), then GL's
//!   outer levels (8), inner (12) and the patch outputs (location l at
//!   16 + 4l);
//! - the tessellator (the caller's);
//! - the evaluation shader (`Stage::Evaluation`) once a point the
//!   tessellator made: gl_TessCoord, the patch's control points and patch
//!   values, its outputs a record a point as a vertex shader's (position
//!   at word 0, point size at 4, location l at 8 + 4l), which the caller
//!   draws by the tessellator's indices through a pass-through vertex
//!   shader.
//!
//! (The wrappers' locals are not named patch: WGSL reserves it.)
//!
//! The control shader's resources, in the caller's group: 960 its
//! parameters (VxTcParams: the patches, the vertex records' stride in
//! words, the vertices a patch, the patches an instance, the domain), 961
//! the vertex records, 962 each patch's vertices' records, 963 the control
//! point records, 964 the patch records. The evaluation shader's: 960
//! VxTeParams (the patches an instance, the domain), 961 the control point
//! records, 962 the patch records, 963 the tessellator's points, 964 its
//! indirect arguments (the points' count at word 7), 965 the vertex records.

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use naga::{ScalarKind, TypeInner};

use crate::geometry::{Leaf, instruction, leaves, load_from, member_name, store, string_length, string_words};

const OP_NAME: u32 = 5;
const OP_MEMBER_NAME: u32 = 6;
const OP_ENTRY_POINT: u32 = 15;
const OP_EXECUTION_MODE: u32 = 16;
const OP_CAPABILITY: u32 = 17;
const OP_TYPE_INT: u32 = 21;
const OP_TYPE_ARRAY: u32 = 28;
const OP_TYPE_STRUCT: u32 = 30;
const OP_TYPE_POINTER: u32 = 32;
const OP_CONSTANT: u32 = 43;
const OP_FUNCTION: u32 = 54;
const OP_VARIABLE: u32 = 59;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const OP_CONTROL_BARRIER: u32 = 224;

const MODEL_TESS_CONTROL: u32 = 1;
const MODEL_TESS_EVALUATION: u32 = 2;
const MODEL_GL_COMPUTE: u32 = 5;
const STORAGE_INPUT: u32 = 1;
const STORAGE_OUTPUT: u32 = 3;
const STORAGE_WORKGROUP: u32 = 4;
const STORAGE_PRIVATE: u32 = 6;

const DECORATION_RELAXED_PRECISION: u32 = 0;
const DECORATION_BLOCK: u32 = 2;
const DECORATION_BUILTIN: u32 = 11;
const DECORATION_NO_PERSPECTIVE: u32 = 13;
const DECORATION_FLAT: u32 = 14;
const DECORATION_PATCH: u32 = 15;
const DECORATION_CENTROID: u32 = 16;
const DECORATION_SAMPLE: u32 = 17;
const DECORATION_LOCATION: u32 = 30;

const BUILTIN_POSITION: u32 = 0;
const BUILTIN_POINT_SIZE: u32 = 1;
const BUILTIN_PRIMITIVE_ID: u32 = 7;
const BUILTIN_INVOCATION_ID: u32 = 8;
const BUILTIN_TESS_LEVEL_OUTER: u32 = 11;
const BUILTIN_TESS_LEVEL_INNER: u32 = 12;
const BUILTIN_TESS_COORD: u32 = 13;
const BUILTIN_PATCH_VERTICES: u32 = 14;

/// The patch record's words: the tessellator's factors at 0, GL's outer levels at 8, inner at 12, location l at 16 + 4l
const OUTER_WORD: u32 = 8;
const INNER_WORD: u32 = 12;
const PATCH_LOCATIONS: u32 = 16;
/// A vertex record's: the position at 0, the point size at 4, location l at 8 + 4l
const LOCATIONS: u32 = 8;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
    Control,
    Evaluation,
}

pub const CONTROL_MAIN: &str = "vx_tcmain";
pub const EVALUATION_MAIN: &str = "vx_temain";
fn vertex_name(location: u32, output: bool) -> String { format!("vx_t{}{}x", if output { "o" } else { "i" }, location) }
fn patch_name(location: u32, output: bool) -> String { format!("vx_tp{}{}x", if output { "o" } else { "i" }, location) }
fn builtin_name(builtin: u32, output: bool) -> String { format!("vx_tb{}{}x", builtin, if output { "o" } else { "i" }) }
const PER_VERTEX_IN: &str = "vx_tpvix";
const PER_VERTEX_OUT: &str = "vx_tpvox";

/// What `prepare` read of a tessellation shader
#[derive(Clone, Debug, Default)]
pub struct Tessellation {
    pub stage: Option<Stage>,
    /// the control shader's output vertices
    pub vertices: u32,
    /// the evaluation shader's: GX's domain (1 isolines, 2 triangles, 3 quads), partitioning (1 equal, 3 fractional odd, 4 fractional even)
    /// and output primitive (1 points, 2 lines, 3 D3D's clockwise triangles (GL's counterclockwise), 4 D3D's counterclockwise)
    pub domain: u32,
    pub spacing: u32,
    pub primitive: u32,
    point_mode: bool,
    clockwise: bool,
    inputs: Vec<u32>,
    outputs: Vec<u32>,
    patch_inputs: Vec<u32>,
    patch_outputs: Vec<u32>,
    builtins: Vec<(u32, bool)>,
    in_members: Vec<u32>,
    out_members: Vec<u32>,
    interpolation: BTreeMap<u32, u32>,
}

/// The tessellation shader's SPIR-V as a compute shader's (above), and what it read
pub fn prepare(words: &[u32], stage: Stage) -> Result<(Vec<u32>, Tessellation), String> {
    if words.len() < 5 {
        return Err(String::from("not SPIR-V"));
    }
    let mut instructions: Vec<&[u32]> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return Err(String::from("SPIR-V: a malformed instruction"));
        }
        instructions.push(&words[at..at + count]);
        at += count;
    }
    let op = |w: &[u32]| w[0] & 0xFFFF;
    let model = if stage == Stage::Control { MODEL_TESS_CONTROL } else { MODEL_TESS_EVALUATION };
    let mut entry = None;
    let mut uint = None;
    let mut pointers: BTreeMap<u32, u32> = BTreeMap::new();
    let mut arrays: BTreeMap<u32, u32> = BTreeMap::new();
    let mut structs: BTreeMap<u32, usize> = BTreeMap::new();
    let mut constants: BTreeMap<(u32, u32), u32> = BTreeMap::new();
    let mut variables: Vec<(u32, u32, bool)> = Vec::new();
    let mut decorations: BTreeMap<u32, Vec<(u32, u32)>> = BTreeMap::new();
    let mut members: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new();
    for w in &instructions {
        match op(w) {
            OP_ENTRY_POINT if w.len() >= 3 && w[1] == model && entry.is_none() => entry = Some(w[2]),
            OP_TYPE_INT if w.len() >= 4 && w[2] == 32 && w[3] == 0 => uint = Some(w[1]),
            OP_TYPE_POINTER if w.len() >= 4 => {
                pointers.insert(w[1], w[3]);
            },
            OP_TYPE_ARRAY if w.len() >= 3 => {
                arrays.insert(w[1], w[2]);
            },
            OP_TYPE_STRUCT if w.len() >= 2 => {
                structs.insert(w[1], w.len() - 2);
            },
            OP_CONSTANT if w.len() == 4 => {
                constants.entry((w[1], w[3])).or_insert(w[2]);
            },
            OP_VARIABLE if w.len() >= 4 && (w[3] == STORAGE_INPUT || w[3] == STORAGE_OUTPUT) => variables.push((w[2], w[1], w[3] == STORAGE_OUTPUT)),
            OP_DECORATE if w.len() >= 3 => decorations.entry(w[1]).or_default().push((w[2], w.get(3).copied().unwrap_or(0))),
            OP_MEMBER_DECORATE if w.len() >= 4 => members.entry((w[1], w[2])).or_default().push((w[3], w.get(4).copied().unwrap_or(0))),
            _ => {},
        }
    }
    let entry = entry.ok_or("no tessellation entry point")?;
    let find = |list: Option<&Vec<(u32, u32)>>, d: u32| list.and_then(|l| l.iter().find(|(k, _)| *k == d).map(|(_, v)| *v));
    let has = |list: Option<&Vec<(u32, u32)>>, d: u32| list.is_some_and(|l| l.iter().any(|(k, _)| *k == d));

    let mut t = Tessellation { stage: Some(stage), spacing: 1, ..Tessellation::default() };
    let mut names: BTreeMap<u32, String> = BTreeMap::new();
    let mut io_structs: BTreeSet<u32> = BTreeSet::new();
    for &(var, pointer, output) in &variables {
        let mut ty = pointers.get(&pointer).copied().unwrap_or(0);
        while let Some(&element) = arrays.get(&ty) {
            ty = element;
        }
        if structs.contains_key(&ty) {
            io_structs.insert(ty);
        }
        let decorated = decorations.get(&var);
        let name = if let Some(builtin) = find(decorated, DECORATION_BUILTIN) {
            t.builtins.push((builtin, output));
            builtin_name(builtin, output)
        }
        else if structs.get(&ty).is_some_and(|&n| (0..n as u32).any(|m| find(members.get(&(ty, m)), DECORATION_BUILTIN).is_some())) {
            let list: Vec<u32> = (0..structs[&ty] as u32).map(|m| find(members.get(&(ty, m)), DECORATION_BUILTIN).unwrap_or(u32::MAX)).collect();
            if output {
                t.out_members = list;
                String::from(PER_VERTEX_OUT)
            }
            else {
                t.in_members = list;
                String::from(PER_VERTEX_IN)
            }
        }
        else {
            let location = find(decorated, DECORATION_LOCATION).or_else(|| find(members.get(&(ty, 0)), DECORATION_LOCATION))
                .ok_or("an input or output of no location")?;
            if has(decorated, DECORATION_PATCH) {
                if output { t.patch_outputs.push(location) } else { t.patch_inputs.push(location) }
                patch_name(location, output)
            }
            else {
                if output {
                    let mut flags = 0;
                    for (d, bit) in [(DECORATION_FLAT, 1), (DECORATION_NO_PERSPECTIVE, 2), (DECORATION_CENTROID, 4), (DECORATION_SAMPLE, 8)] {
                        if has(decorated, d) {
                            flags |= bit;
                        }
                    }
                    t.interpolation.insert(location, flags);
                    t.outputs.push(location);
                }
                else {
                    t.inputs.push(location);
                }
                vertex_name(location, output)
            }
        };
        names.insert(var, name);
    }
    let converted: BTreeMap<u32, bool> = variables.iter().map(|v| (v.0, v.2)).collect();
    // (the control shader's outputs shared by the patch's invocations: workgroup memory)
    let output_storage = if stage == Stage::Control { STORAGE_WORKGROUP } else { STORAGE_PRIVATE };

    let mut bound = words[3];
    let mut fresh = || { bound += 1; bound - 1 };
    // (a barrier's memory scope and semantics: the workgroup's, its memory acquired and released)
    let mut declarations: Vec<Vec<u32>> = Vec::new();
    let mut uint_constant = |value: u32, declarations: &mut Vec<Vec<u32>>, fresh: &mut dyn FnMut() -> u32| -> u32 {
        let ty = match uint {
            Some(ty) => ty,
            None => {
                let ty = fresh();
                declarations.push(instruction(OP_TYPE_INT, &[ty, 32, 0]));
                uint = Some(ty);
                ty
            },
        };
        *constants.entry((ty, value)).or_insert_with(|| {
            let id = fresh();
            declarations.push(instruction(OP_CONSTANT, &[ty, id, value]));
            id
        })
    };
    let barrier_scope = uint_constant(2, &mut declarations, &mut fresh);
    let barrier_semantics = uint_constant(0x108, &mut declarations, &mut fresh);
    let mut out = words[..5].to_vec();
    let first_function = instructions.iter().position(|w| op(w) == OP_FUNCTION).unwrap_or(instructions.len());
    for (i, w) in instructions.iter().enumerate() {
        if i == first_function {
            for d in &declarations {
                out.extend_from_slice(d);
            }
        }
        match op(w) {
            OP_CAPABILITY if w.len() >= 2 && matches!(w[1], 3 | 23) => continue,
            OP_ENTRY_POINT if w.len() >= 3 && w[2] == entry => {
                let n = string_length(&w[3..]);
                let mut operands = Vec::from([MODEL_GL_COMPUTE, entry]);
                operands.extend_from_slice(&w[3..3 + n]);
                out.extend(instruction(OP_ENTRY_POINT, &operands));
                out.extend(instruction(OP_EXECUTION_MODE, &[entry, 17, 1, 1, 1]));
                continue;
            },
            OP_EXECUTION_MODE if w.len() >= 3 && w[1] == entry => {
                match w[2] {
                    26 => t.vertices = w.get(3).copied().unwrap_or(0),
                    22 => t.domain = 2,
                    24 => t.domain = 3,
                    25 => t.domain = 1,
                    1 => t.spacing = 1,
                    2 => t.spacing = 4,
                    3 => t.spacing = 3,
                    4 => t.clockwise = true,
                    5 => t.clockwise = false,
                    10 => t.point_mode = true,
                    _ => out.extend_from_slice(w),
                }
                continue;
            },
            OP_NAME if w.len() >= 2 && (names.contains_key(&w[1]) || w[1] == entry) => {
                let name = if w[1] == entry {
                    String::from(if stage == Stage::Control { CONTROL_MAIN } else { EVALUATION_MAIN })
                } else { names[&w[1]].clone() };
                let mut operands = Vec::from([w[1]]);
                operands.extend(string_words(&name));
                out.extend(instruction(OP_NAME, &operands));
                continue;
            },
            OP_MEMBER_NAME if w.len() >= 3 && io_structs.contains(&w[1]) => {
                let mut operands = Vec::from([w[1], w[2]]);
                operands.extend(string_words(&member_name(w[2] as usize)));
                out.extend(instruction(OP_MEMBER_NAME, &operands));
                continue;
            },
            OP_DECORATE if w.len() >= 3 && (converted.contains_key(&w[1]) && w[2] != DECORATION_RELAXED_PRECISION
                || io_structs.contains(&w[1]) && w[2] == DECORATION_BLOCK) => continue,
            OP_MEMBER_DECORATE if w.len() >= 4 && io_structs.contains(&w[1]) && w[3] != DECORATION_RELAXED_PRECISION => continue,
            OP_TYPE_POINTER if w.len() >= 4 && (w[2] == STORAGE_INPUT || w[2] == STORAGE_OUTPUT) => {
                out.extend(instruction(OP_TYPE_POINTER, &[w[1], if w[2] == STORAGE_OUTPUT { output_storage } else { STORAGE_PRIVATE }, w[3]]));
                continue;
            },
            OP_VARIABLE if w.len() >= 4 && converted.contains_key(&w[2]) => {
                out.extend(instruction(OP_VARIABLE, &[w[1], w[2], if converted[&w[2]] { output_storage } else { STORAGE_PRIVATE }]));
                continue;
            },
            OP_CONTROL_BARRIER if w.len() == 4 => {
                out.extend(instruction(OP_CONTROL_BARRIER, &[w[1], barrier_scope, barrier_semantics]));
                continue;
            },
            _ => {},
        }
        out.extend_from_slice(w);
    }
    if first_function >= instructions.len() {
        for d in &declarations {
            out.extend_from_slice(d);
        }
    }
    out[3] = bound;
    if stage == Stage::Control && t.vertices == 0 {
        return Err(String::from("a tessellation control shader without its output vertices"));
    }
    if stage == Stage::Evaluation {
        if t.domain == 0 {
            return Err(String::from("a tessellation evaluation shader without its primitive mode"));
        }
        // (GL's order is D3D's other one: the tessellator's v runs the other way)
        t.primitive = if t.point_mode { 1 } else if t.domain == 1 { 2 } else if t.clockwise { 4 } else { 3 };
    }
    Ok((out, t))
}

/// What the caller needs of a translated tessellation shader: the WGSL to append and the JSON
pub struct Finished {
    pub appended: String,
    pub json: String,
}

/// The leaves of a variable's element `index` (an array's, the variable's own when `index` is None)
fn variable_leaves(module: &naga::Module, name: &str, location: u32, index: Option<&str>) -> Result<Vec<Leaf>, String> {
    let (_, ty) = module.global_variables.iter().find(|(_, v)| v.name.as_deref() == Some(name)).map(|(h, v)| (h, v.ty))
        .ok_or_else(|| format!("{} naga left out", name))?;
    let (ty, access) = match (index, &module.types[ty].inner) {
        (Some(i), TypeInner::Array { base, .. }) => (*base, format!("{}[{}]", name, i)),
        (Some(_), _) => return Err(format!("{} is not an array", name)),
        (None, _) => (ty, String::from(name)),
    };
    let mut out = Vec::new();
    leaves(module, ty, &access, location, &mut out)?;
    Ok(out)
}

fn exists(module: &naga::Module, name: &str) -> bool {
    module.global_variables.iter().any(|(_, v)| v.name.as_deref() == Some(name))
}

/// The stores of leaves into `buffer` at `base` + LOCATIONS
fn write_leaves(wgsl: &mut String, list: &[Leaf], buffer: &str, base: &str, first_word: u32) {
    for leaf in list {
        for k in 0..leaf.components {
            let value = if leaf.components == 1 { leaf.access.clone() } else { format!("{}[{}]", leaf.access, k) };
            wgsl.push_str(&format!("    {}[{} + {}u] = {};\n", buffer, base, first_word + 4 * leaf.location + k, store(leaf.kind, &value)));
        }
    }
}

/// The reads of leaves from `buffer` at `base`
fn read_leaves(wgsl: &mut String, list: &[Leaf], buffer: &str, base: &str, first_word: u32) {
    for leaf in list {
        let at = format!("{} + {}u", base, first_word + 4 * leaf.location);
        wgsl.push_str(&format!("        {} = {};\n", leaf.access, load_from(buffer, leaf.kind, leaf.components, &at)));
    }
}

/// The position and point size of the per-vertex block (or the built-ins) into a vertex record
fn write_position(wgsl: &mut String, members: &[u32], block: &str, builtins: &[(u32, bool)], module: &naga::Module, buffer: &str, base: &str) {
    let mut put = |access: String, builtin: u32| {
        match builtin {
            BUILTIN_POSITION => for k in 0..4 {
                wgsl.push_str(&format!("    {}[{} + {}u] = {};\n", buffer, base, k, store(ScalarKind::Float, &format!("{}[{}]", access, k))));
            },
            BUILTIN_POINT_SIZE => wgsl.push_str(&format!("    {}[{} + 4u] = {};\n", buffer, base, store(ScalarKind::Float, &access))),
            _ => {},
        }
    };
    if exists(module, PER_VERTEX_OUT) {
        for (k, &b) in members.iter().enumerate() {
            put(format!("{}.{}", block, member_name(k)), b);
        }
    }
    for &(b, output) in builtins {
        if output && (b == BUILTIN_POSITION || b == BUILTIN_POINT_SIZE) && exists(module, &builtin_name(b, true)) {
            put(builtin_name(b, true), b);
        }
    }
}

/// The record of the outputs' leaves: its stride in words
fn stride_of(list: &[Leaf], first_word: u32) -> u32 {
    first_word + 4 * list.iter().map(|l| l.location + 1).max().unwrap_or(0)
}

/// The module without its entry point; the WGSL of the compute shader that runs its function
pub fn finish(module: &mut naga::Module, t: &Tessellation, group: u32) -> Result<Finished, String> {
    module.entry_points.clear();
    let mut wgsl = String::new();
    // the per-vertex inputs: control points (the vertex records, or the control shader's), as arrays of the patch's
    let fill_inputs = |wgsl: &mut String, module: &naga::Module, buffer: &str, record: &str| -> Result<(), String> {
        if exists(module, PER_VERTEX_IN) {
            for (k, &b) in t.in_members.iter().enumerate() {
                let access = format!("{}[k].{}", PER_VERTEX_IN, member_name(k));
                match b {
                    BUILTIN_POSITION => wgsl.push_str(&format!("        {} = {};\n", access, load_from(buffer, ScalarKind::Float, 4, record))),
                    BUILTIN_POINT_SIZE => wgsl.push_str(&format!("        {} = {};\n", access, load_from(buffer, ScalarKind::Float, 1, &format!("{} + 4u", record)))),
                    _ => {},
                }
            }
        }
        for &location in &t.inputs {
            if exists(module, &vertex_name(location, false)) {
                let list = variable_leaves(module, &vertex_name(location, false), location, Some("k"))?;
                read_leaves(wgsl, &list, buffer, record, LOCATIONS);
            }
        }
        Ok(())
    };
    let builtin = |b: u32, output: bool| Some(builtin_name(b, output)).filter(|n| exists(module, n));
    match t.stage {
        Some(Stage::Control) => {
            let n = t.vertices;
            let mut outputs = Vec::new();
            for &location in &t.outputs {
                outputs.extend(variable_leaves(module, &vertex_name(location, true), location, Some("inv"))?);
            }
            let mut patch = Vec::new();
            for &location in &t.patch_outputs {
                patch.extend(variable_leaves(module, &patch_name(location, true), location, None)?);
            }
            let cp_stride = stride_of(&outputs, LOCATIONS);
            let patch_stride = stride_of(&patch, PATCH_LOCATIONS);
            wgsl.push_str("\nstruct VxTcParams { patches: u32, in_stride: u32, patch_vertices: u32, per_instance: u32, domain: u32, pad0: u32, pad1: u32, pad2: u32 }\n");
            wgsl.push_str(&format!("@group({g}) @binding(960) var<uniform> vx_tc_p: VxTcParams;\n\
                @group({g}) @binding(961) var<storage, read> vx_tc_in: array<u32>;\n\
                @group({g}) @binding(962) var<storage, read> vx_tc_ids: array<u32>;\n\
                @group({g}) @binding(963) var<storage, read_write> vx_tc_cp: array<u32>;\n\
                @group({g}) @binding(964) var<storage, read_write> vx_tc_patch: array<u32>;\n", g = group));
            wgsl.push_str(&format!("@compute @workgroup_size({n}) fn vx_tess_control(@builtin(workgroup_id) wg: vec3<u32>, \
                @builtin(local_invocation_id) lid: vec3<u32>) {{\n    let vx_patch = wg.x + wg.y * 65535u;\n    \
                if (vx_patch >= vx_tc_p.patches) {{ return; }}\n    let inv = lid.x;\n    \
                for (var k = 0u; k < vx_tc_p.patch_vertices; k = k + 1u) {{\n        \
                let r = vx_tc_ids[vx_patch * vx_tc_p.patch_vertices + k] * vx_tc_p.in_stride;\n", n = n));
            fill_inputs(&mut wgsl, module, "vx_tc_in", "r")?;
            wgsl.push_str("    }\n");
            if let Some(name) = builtin(BUILTIN_INVOCATION_ID, false) { wgsl.push_str(&format!("    {} = i32(inv);\n", name)); }
            if let Some(name) = builtin(BUILTIN_PRIMITIVE_ID, false) { wgsl.push_str(&format!("    {} = i32(vx_patch % vx_tc_p.per_instance);\n", name)); }
            if let Some(name) = builtin(BUILTIN_PATCH_VERTICES, false) { wgsl.push_str(&format!("    {} = i32(vx_tc_p.patch_vertices);\n", name)); }
            wgsl.push_str(&format!("    {}();\n    workgroupBarrier();\n    let o = (vx_patch * {}u + inv) * {}u;\n", CONTROL_MAIN, n, cp_stride));
            let block = format!("{}[inv]", PER_VERTEX_OUT);
            write_position(&mut wgsl, &t.out_members, &block, &[], module, "vx_tc_cp", "o");
            write_leaves(&mut wgsl, &outputs, "vx_tc_cp", "o", LOCATIONS);
            // the patch's record: the tessellator's factors by the domain, GL's levels, the patch outputs
            wgsl.push_str(&format!("    if (inv != 0u) {{ return; }}\n    let p = vx_patch * {}u;\n", patch_stride));
            let outer = builtin(BUILTIN_TESS_LEVEL_OUTER, true).map_or(String::from("array<f32, 4>(0.0, 0.0, 0.0, 0.0)"), |n| n);
            let inner = builtin(BUILTIN_TESS_LEVEL_INNER, true).map_or(String::from("array<f32, 2>(0.0, 0.0)"), |n| n);
            wgsl.push_str(&format!("    let outer = {};\n    let inner = {};\n", outer, inner));
            wgsl.push_str("    var f = array<f32, 8>(outer[0], outer[1], outer[2], outer[3], inner[0], inner[1], 0.0, 0.0);\n    \
                if (vx_tc_p.domain == 2u) { f[3] = inner[0]; f[4] = 0.0; f[5] = 0.0; }\n    \
                if (vx_tc_p.domain == 1u) { f[2] = 0.0; f[3] = 0.0; f[4] = 0.0; f[5] = 0.0; }\n    \
                for (var k = 0u; k < 8u; k = k + 1u) { vx_tc_patch[p + k] = bitcast<u32>(f[k]); }\n");
            wgsl.push_str(&format!("    for (var k = 0u; k < 4u; k = k + 1u) {{ vx_tc_patch[p + {o}u + k] = bitcast<u32>(outer[k]); }}\n    \
                vx_tc_patch[p + {i}u] = bitcast<u32>(inner[0]);\n    vx_tc_patch[p + {i}u + 1u] = bitcast<u32>(inner[1]);\n", o = OUTER_WORD, i = INNER_WORD));
            write_leaves(&mut wgsl, &patch, "vx_tc_patch", "p", PATCH_LOCATIONS);
            wgsl.push_str("}\n");
            let json = format!("{{\"stage\":\"control\",\"vertices\":{},\"cp_stride\":{},\"patch_stride\":{}}}", n, cp_stride, patch_stride);
            Ok(Finished { appended: wgsl, json })
        },
        _ => {
            let mut outputs = Vec::new();
            for &location in &t.outputs {
                outputs.extend(variable_leaves(module, &vertex_name(location, true), location, None)?);
            }
            let stride = stride_of(&outputs, LOCATIONS);
            wgsl.push_str("\nstruct VxTeParams { per_instance: u32, cp_stride: u32, patch_stride: u32, vertices: u32, domain: u32, pad0: u32, pad1: u32, pad2: u32 }\n");
            wgsl.push_str(&format!("@group({g}) @binding(960) var<uniform> vx_te_p: VxTeParams;\n\
                @group({g}) @binding(961) var<storage, read> vx_te_cp: array<u32>;\n\
                @group({g}) @binding(962) var<storage, read> vx_te_patch: array<u32>;\n\
                @group({g}) @binding(963) var<storage, read> vx_te_points: array<vec4<u32>>;\n\
                @group({g}) @binding(964) var<storage, read> vx_te_args: array<u32>;\n\
                @group({g}) @binding(965) var<storage, read_write> vx_te_out: array<u32>;\n", g = group));
            wgsl.push_str("@compute @workgroup_size(64) fn vx_tess_eval(@builtin(global_invocation_id) id: vec3<u32>) {\n    \
                let n = id.x + id.y * 65535u * 64u;\n    if (n >= vx_te_args[7]) { return; }\n    let vx_point = vx_te_points[n];\n    \
                let u = bitcast<f32>(vx_point.x);\n    let v = bitcast<f32>(vx_point.y);\n    let vx_patch = vx_point.z;\n");
            if let Some(name) = builtin(BUILTIN_TESS_COORD, false) {
                wgsl.push_str(&format!("    {} = select(vec3<f32>(u, v, 0.0), vec3<f32>(u, v, 1.0 - u - v), vx_te_p.domain == 2u);\n", name));
            }
            wgsl.push_str("    for (var k = 0u; k < vx_te_p.vertices; k = k + 1u) {\n        let r = (vx_patch * vx_te_p.vertices + k) * vx_te_p.cp_stride;\n");
            fill_inputs(&mut wgsl, module, "vx_te_cp", "r")?;
            wgsl.push_str("    }\n    let p = vx_patch * vx_te_p.patch_stride;\n");
            for &location in &t.patch_inputs {
                if exists(module, &patch_name(location, false)) {
                    let list = variable_leaves(module, &patch_name(location, false), location, None)?;
                    read_leaves(&mut wgsl, &list, "vx_te_patch", "p", PATCH_LOCATIONS);
                }
            }
            if let Some(name) = builtin(BUILTIN_TESS_LEVEL_OUTER, false) {
                wgsl.push_str(&format!("    for (var k = 0u; k < 4u; k = k + 1u) {{ {}[k] = bitcast<f32>(vx_te_patch[p + {}u + k]); }}\n", name, OUTER_WORD));
            }
            if let Some(name) = builtin(BUILTIN_TESS_LEVEL_INNER, false) {
                wgsl.push_str(&format!("    for (var k = 0u; k < 2u; k = k + 1u) {{ {}[k] = bitcast<f32>(vx_te_patch[p + {}u + k]); }}\n", name, INNER_WORD));
            }
            if let Some(name) = builtin(BUILTIN_PRIMITIVE_ID, false) { wgsl.push_str(&format!("    {} = i32(vx_patch % vx_te_p.per_instance);\n", name)); }
            if let Some(name) = builtin(BUILTIN_PATCH_VERTICES, false) { wgsl.push_str(&format!("    {} = i32(vx_te_p.vertices);\n", name)); }
            wgsl.push_str(&format!("    {}();\n    let o = n * {}u;\n", EVALUATION_MAIN, stride));
            write_position(&mut wgsl, &t.out_members, PER_VERTEX_OUT, &t.builtins, module, "vx_te_out", "o");
            write_leaves(&mut wgsl, &outputs, "vx_te_out", "o", LOCATIONS);
            wgsl.push_str("}\n");
            let mut json = format!("{{\"stage\":\"evaluation\",\"domain\":{},\"spacing\":{},\"primitive\":{},\"stride\":{},\"outputs\":[",
                t.domain, t.spacing, t.primitive, stride);
            for (i, leaf) in outputs.iter().enumerate() {
                if i > 0 { json.push(','); }
                let kind = match leaf.kind { ScalarKind::Sint => "i", ScalarKind::Uint => "u", _ => "f" };
                let flags = t.interpolation.range(..=leaf.location).next_back().map_or(0, |(_, f)| *f);
                json.push_str(&format!("[{},\"{}\",{},{}]", leaf.location, kind, leaf.components, flags));
            }
            json.push_str("]}");
            Ok(Finished { appended: wgsl, json })
        },
    }
}
                                                                                                                                                   source/v64/src/browser/glbridge/vx/naga/src/xfb.rs                                                  0000644 0000000 0000000 00000055676 00000000000 017217  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Transform feedback (VK_EXT_transform_feedback) for VX: WebGPU's vertex
//! stage cannot write storage buffers, so a draw that captures runs its
//! vertex shader again as a compute shader first, one invocation a vertex,
//! which reads the vertex attributes from the vertex buffers itself (as
//! storage buffers of u32) and writes the outputs the SPIR-V decorates with
//! XfbBuffer, XfbStride and Offset into the transform feedback buffers.
//!
//! The vertex entry point stays as it is; a copy of it becomes an ordinary
//! function (vx_vs: its arguments without their bindings, its result the
//! entry point's output struct, whose members get the names vx_o0m, ...), and
//! the compute entry point vx_xfb (WGSL appended to naga's) calls it. Its
//! resources, in the group the caller gives (one the vertex shader does not
//! use):
//! - binding 960: the parameters (uniform, VxXfbParams): first vertex,
//!   vertex count (an instance's), first instance, instance count, the
//!   capture's first vertex (its place in the buffers), the vertices to
//!   capture (those of the primitives that fit), then each transform feedback
//!   buffer's offset in bytes, and each vertex buffer slot's;
//! - 961 + slot: vertex buffer `slot`'s memory (read-only storage, whole);
//! - 970 + buffer: transform feedback buffer `buffer` (read-write storage).
//!
//! Positions are as Vulkan's (the caller translates with the clip space
//! kept), so that what is captured is what Vulkan's would be.

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use naga::{Binding, BuiltIn, Handle, ScalarKind, TypeInner, VectorSize};

/// What a captured output is (by its binding) and where it goes
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Output {
    Location(u32),
    Position,
    PointSize,
}
#[derive(Clone, Copy, Debug)]
pub struct Capture {
    pub output: Output,
    pub buffer: u32,
    pub offset: u32,
}

/// A vertex attribute of the pipeline: its location, buffer slot, VkFormat and offset
#[derive(Clone, Copy, Debug)]
pub struct Attribute {
    pub location: u32,
    pub slot: u32,
    pub format: u32,
    pub offset: u32,
}
/// A vertex buffer slot of the pipeline: its stride and input rate (1: per instance)
#[derive(Clone, Copy, Debug)]
pub struct Slot {
    pub slot: u32,
    pub stride: u32,
    pub instance: bool,
}

const OP_EXECUTION_MODE: u32 = 16;
const OP_DECORATE: u32 = 71;
const OP_MEMBER_DECORATE: u32 = 72;
const OP_VARIABLE: u32 = 59;
const OP_TYPE_POINTER: u32 = 32;
const EXECUTION_MODE_XFB: u32 = 11;
const DECORATION_BUILTIN: u32 = 11;
const DECORATION_LOCATION: u32 = 30;
const DECORATION_OFFSET: u32 = 35;
const DECORATION_XFB_BUFFER: u32 = 36;
const DECORATION_XFB_STRIDE: u32 = 37;
const BUILTIN_POSITION: u32 = 0;
const BUILTIN_POINT_SIZE: u32 = 1;
const STORAGE_OUTPUT: u32 = 3;

/// The captured outputs a vertex shader's SPIR-V declares (an Xfb execution
/// mode, outputs with XfbBuffer and Offset), and each buffer's stride; none
/// when it captures nothing
pub fn captures(words: &[u32]) -> Option<(Vec<Capture>, [u32; 4])> {
    use alloc::collections::BTreeMap;
    let mut xfb = false;
    // decorations by id, and by (struct type, member)
    let mut decorations: BTreeMap<u32, Vec<(u32, u32)>> = BTreeMap::new();
    let mut members: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new();
    let mut pointers: BTreeMap<u32, u32> = BTreeMap::new();
    let mut outputs: Vec<(u32, u32)> = Vec::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        let op = words[at] & 0xFFFF;
        if count == 0 || at + count > words.len() {
            return None;
        }
        let w = &words[at..at + count];
        match op {
            OP_EXECUTION_MODE if count >= 3 && w[2] == EXECUTION_MODE_XFB => xfb = true,
            OP_DECORATE if count >= 3 => decorations.entry(w[1]).or_default().push((w[2], *w.get(3).unwrap_or(&0))),
            OP_MEMBER_DECORATE if count >= 4 => members.entry((w[1], w[2])).or_default().push((w[3], *w.get(4).unwrap_or(&0))),
            OP_TYPE_POINTER if count >= 4 => {
                pointers.insert(w[1], w[3]);
            },
            OP_VARIABLE if count >= 4 && w[3] == STORAGE_OUTPUT => outputs.push((w[2], w[1])),
            _ => {},
        }
        at += count;
    }
    if !xfb {
        return None;
    }
    let find = |list: &Vec<(u32, u32)>, d: u32| list.iter().find(|(k, _)| *k == d).map(|(_, v)| *v);
    let mut strides = [0u32; 4];
    let mut captures = Vec::new();
    for (var, pointer) in outputs {
        let empty = Vec::new();
        let decorated = decorations.get(&var).unwrap_or(&empty);
        let buffer = find(decorated, DECORATION_XFB_BUFFER);
        if let Some(stride) = find(decorated, DECORATION_XFB_STRIDE) {
            if let Some(b) = buffer {
                strides[b as usize & 3] = stride;
            }
        }
        // a block's members (gl_PerVertex's position)
        let ty = pointers.get(&pointer).copied().unwrap_or(0);
        for ((t, member), list) in members.range((ty, 0)..=(ty, u32::MAX)) {
            let _ = (t, member);
            let (Some(builtin), Some(offset)) = (find(list, DECORATION_BUILTIN), find(list, DECORATION_OFFSET))
            else {
                continue;
            };
            let Some(b) = find(list, DECORATION_XFB_BUFFER).or(buffer)
            else {
                continue;
            };
            if let Some(stride) = find(list, DECORATION_XFB_STRIDE) {
                strides[b as usize & 3] = stride;
            }
            if builtin == BUILTIN_POSITION {
                captures.push(Capture { output: Output::Position, buffer: b, offset });
            }
            else if builtin == BUILTIN_POINT_SIZE {
                captures.push(Capture { output: Output::PointSize, buffer: b, offset });
            }
        }
        let (Some(b), Some(offset)) = (buffer, find(decorated, DECORATION_OFFSET))
        else {
            continue;
        };
        if let Some(location) = find(decorated, DECORATION_LOCATION) {
            captures.push(Capture { output: Output::Location(location), buffer: b, offset });
        }
        else if find(decorated, DECORATION_BUILTIN) == Some(BUILTIN_POSITION) {
            captures.push(Capture { output: Output::Position, buffer: b, offset });
        }
        else if find(decorated, DECORATION_BUILTIN) == Some(BUILTIN_POINT_SIZE) {
            captures.push(Capture { output: Output::PointSize, buffer: b, offset });
        }
    }
    if captures.is_empty() {
        return None;
    }
    Some((captures, strides))
}

/// The SPIR-V without what naga refuses of transform feedback (the Xfb
/// execution mode; the TransformFeedback capability, the XfbBuffer,
/// XfbStride and Stream decorations, and the Offset of outputs, which naga
/// has no use for): `captures` has read them first
pub fn strip(words: &[u32]) -> Vec<u32> {
    const OP_CAPABILITY: u32 = 17;
    const CAPABILITY_TRANSFORM_FEEDBACK: u32 = 53;
    const DECORATION_STREAM: u32 = 29;
    let mut outputs = alloc::collections::BTreeSet::new();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        if count == 0 || at + count > words.len() {
            return words.to_vec();
        }
        if words[at] & 0xFFFF == OP_VARIABLE && count >= 4 && words[at + 3] == STORAGE_OUTPUT {
            outputs.insert(words[at + 2]);
        }
        at += count;
    }
    let mut out = words[..5.min(words.len())].to_vec();
    let mut at = 5;
    while at < words.len() {
        let count = (words[at] >> 16) as usize;
        let op = words[at] & 0xFFFF;
        let w = &words[at..at + count];
        let drop = match op {
            OP_EXECUTION_MODE => count >= 3 && w[2] == EXECUTION_MODE_XFB,
            OP_CAPABILITY => count >= 2 && w[1] == CAPABILITY_TRANSFORM_FEEDBACK,
            OP_DECORATE => count >= 3 && (matches!(w[2], DECORATION_XFB_BUFFER | DECORATION_XFB_STRIDE | DECORATION_STREAM)
                || w[2] == DECORATION_OFFSET && outputs.contains(&w[1])),
            OP_MEMBER_DECORATE => count >= 4 && matches!(w[3], DECORATION_XFB_BUFFER | DECORATION_XFB_STRIDE | DECORATION_STREAM),
            _ => false,
        };
        if !drop {
            out.extend_from_slice(w);
        }
        at += count;
    }
    out
}

/// A scalar or vector type in WGSL
fn wgsl_type(module: &naga::Module, ty: Handle<naga::Type>) -> Option<String> {
    let scalar = |s: naga::Scalar| match (s.kind, s.width) {
        (ScalarKind::Float, 4) => Some("f32"),
        (ScalarKind::Sint, 4) => Some("i32"),
        (ScalarKind::Uint, 4) => Some("u32"),
        (ScalarKind::Bool, _) => Some("bool"),
        _ => None,
    };
    match module.types[ty].inner {
        TypeInner::Scalar(s) => scalar(s).map(String::from),
        TypeInner::Vector { size, scalar: s } => scalar(s).map(|n| format!("vec{}<{}>", size as u8, n)),
        _ => None,
    }
}

/// The scalars of a value of type `ty` named `name` (WGSL expressions) and
/// whether they are floats, in the order transform feedback writes them
fn scalars(module: &naga::Module, ty: Handle<naga::Type>, name: &str, out: &mut Vec<(String, ScalarKind)>) -> bool {
    match module.types[ty].inner {
        TypeInner::Scalar(s) => {
            out.push((String::from(name), s.kind));
            true
        },
        TypeInner::Vector { size, scalar } => {
            for i in 0..size as usize {
                out.push((format!("{}[{}]", name, i), scalar.kind));
            }
            true
        },
        TypeInner::Matrix { columns, rows, scalar } => {
            for c in 0..columns as usize {
                for r in 0..rows as usize {
                    out.push((format!("{}[{}][{}]", name, c, r), scalar.kind));
                }
            }
            true
        },
        TypeInner::Array { base, size: naga::ArraySize::Constant(n), .. } => {
            (0..n.get()).all(|i| scalars(module, base, &format!("{}[{}]", name, i), out))
        },
        _ => false,
    }
}

/// A vertex format's WGSL decoding of the attribute at byte address `a` of
/// slot `s` into `ty`: (components, bytes each, kind); kinds: f float, n
/// unorm, s snorm, u uint, i sint, U uscaled, S sscaled
fn format_info(format: u32) -> Option<(u32, u32, char)> {
    Some(match format {
        // 8-bit: R8 9-15, R8G8 16-22, R8G8B8 23-29, R8G8B8A8 37-43 (UNORM, SNORM, USCALED, SSCALED, UINT, SINT, SRGB)
        9..=14 => (1, 1, ['n', 's', 'U', 'S', 'u', 'i'][(format - 9) as usize]),
        16..=21 => (2, 1, ['n', 's', 'U', 'S', 'u', 'i'][(format - 16) as usize]),
        23..=28 => (3, 1, ['n', 's', 'U', 'S', 'u', 'i'][(format - 23) as usize]),
        37..=42 => (4, 1, ['n', 's', 'U', 'S', 'u', 'i'][(format - 37) as usize]),
        // 16-bit: R16 70-76, R16G16 77-83, R16G16B16 84-90, R16G16B16A16 91-97 (UNORM, SNORM, USCALED, SSCALED, UINT, SINT, SFLOAT)
        70..=76 => (1, 2, ['n', 's', 'U', 'S', 'u', 'i', 'h'][(format - 70) as usize]),
        77..=83 => (2, 2, ['n', 's', 'U', 'S', 'u', 'i', 'h'][(format - 77) as usize]),
        84..=90 => (3, 2, ['n', 's', 'U', 'S', 'u', 'i', 'h'][(format - 84) as usize]),
        91..=97 => (4, 2, ['n', 's', 'U', 'S', 'u', 'i', 'h'][(format - 91) as usize]),
        // 32-bit: R32 98-100, R32G32 101-103, R32G32B32 104-106, R32G32B32A32 107-109 (UINT, SINT, SFLOAT)
        98..=100 => (1, 4, ['u', 'i', 'f'][(format - 98) as usize]),
        101..=103 => (2, 4, ['u', 'i', 'f'][(format - 101) as usize]),
        104..=106 => (3, 4, ['u', 'i', 'f'][(format - 104) as usize]),
        107..=109 => (4, 4, ['u', 'i', 'f'][(format - 107) as usize]),
        _ => return None,
    })
}

/// One component of a format (a WGSL f32, i32 or u32 expression, as the kind
/// gives) at the byte address in `a` of vertex buffer slot `s`
fn component(s: u32, a: &str, bytes: u32, kind: char) -> String {
    let raw = match bytes {
        1 => format!("vx_byte{}({})", s, a),
        2 => format!("(vx_byte{s}({a}) | (vx_byte{s}({a} + 1u) << 8u))"),
        _ => format!("vx_word{}({})", s, a),
    };
    let bits = bytes * 8;
    // (WGSL chains no shifts, and mixes them with nothing unparenthesized)
    let signed = format!("((i32({}) << {}u) >> {}u)", raw, 32 - bits, 32 - bits);
    match kind {
        'f' => format!("bitcast<f32>({})", raw),
        'h' => format!("unpack2x16float({}).x", raw),
        'n' => format!("(f32({}) / {}.0)", raw, (1u64 << bits) - 1),
        's' => format!("max(f32({}) / {}.0, -1.0)", signed, (1u64 << (bits - 1)) - 1),
        'U' => format!("f32({})", raw),
        'S' => format!("f32({})", signed),
        'u' => raw,
        _ => if bits == 32 { format!("bitcast<i32>({})", raw) } else { signed },
    }
}

/// The components of a value of type `ty` named `name` from `location`, a
/// location each scalar, vector or matrix column: (expression, kind,
/// location, component); how many locations they take
fn location_scalars(module: &naga::Module, ty: Handle<naga::Type>, name: &str, location: u32, out: &mut Vec<(String, ScalarKind, u32, u32)>) -> Option<u32> {
    match module.types[ty].inner {
        TypeInner::Scalar(s) => {
            out.push((String::from(name), s.kind, location, 0));
            Some(1)
        },
        TypeInner::Vector { size, scalar } => {
            for i in 0..size as u32 {
                out.push((format!("{}[{}]", name, i), scalar.kind, location, i));
            }
            Some(1)
        },
        TypeInner::Matrix { columns, rows, scalar } => {
            for c in 0..columns as u32 {
                for r in 0..rows as u32 {
                    out.push((format!("{}[{}][{}]", name, c, r), scalar.kind, location + c, r));
                }
            }
            Some(columns as u32)
        },
        TypeInner::Array { base, size: naga::ArraySize::Constant(n), .. } => {
            let mut used = 0;
            for i in 0..n.get() {
                used += location_scalars(module, base, &format!("{}[{}]", name, i), location + used, out)?;
            }
            Some(used)
        },
        _ => None,
    }
}

/// The compute shader for a vertex shader that captures (naga's module of
/// it, its SPIR-V's captures and strides), with the pipeline's vertex input;
/// the WGSL to append to the module's own (which `module` becomes) and the
/// buffers' strides. `all`: every output captured into buffer 0 instead, a
/// record a vertex as a geometry shader reads it (geometry.rs: the position
/// at word 0, the point size at 4, location l at 8 + 4l)
pub fn compute_shader(module: &mut naga::Module, captures: &[Capture], strides: [u32; 4], attributes: &[Attribute], slots: &[Slot], group: u32,
    all: bool) -> Result<(String, [u32; 4]), String> {
    let entry = module.entry_points.iter().position(|e| e.stage == naga::ShaderStage::Vertex).ok_or("no vertex entry point")?;
    // the entry point's copy, an ordinary function
    let mut function = module.entry_points[entry].function.clone();
    function.name = Some(String::from("vx_vs"));
    let arguments: Vec<(Option<Binding>, Handle<naga::Type>)> = function.arguments.iter().map(|a| (a.binding.clone(), a.ty)).collect();
    for argument in function.arguments.iter_mut() {
        argument.binding = None;
    }
    let result = function.result.clone().ok_or("the vertex shader has no outputs")?;
    // the output struct's members; the copy's own struct of them, named, and
    // without bindings (an ordinary struct: gl_PointSize too, which WGSL's
    // entry points cannot have)
    let (members, span) = match &module.types[result.ty].inner {
        TypeInner::Struct { members, span } => (members.clone(), *span),
        _ => return Err(String::from("the vertex shader's output is not a struct")),
    };
    let plain: Vec<naga::StructMember> = members.iter().enumerate().map(|(i, m)| naga::StructMember {
        // (not ending in a digit: naga's namer would add an underscore)
        name: Some(format!("vx_o{}m", i)),
        ty: m.ty,
        binding: None,
        offset: m.offset,
    }).collect();
    let plain = module.types.insert(naga::Type { name: Some(String::from("VxVertexOut")), inner: TypeInner::Struct { members: plain, span } },
        naga::Span::UNDEFINED);
    crate::retype(&mut function, result.ty, plain, None);
    module.functions.append(function, naga::Span::UNDEFINED);

    let mut wgsl = String::new();
    wgsl.push_str("\nstruct VxXfbParams { first_vertex: u32, vertex_count: u32, first_instance: u32, instance_count: u32, first_capture: u32, \
        limit: u32, pad1: u32, pad2: u32, offsets: vec4<u32>, vb: array<vec4<u32>, 2> }\n");
    wgsl.push_str(&format!("@group({}) @binding(960) var<uniform> vx_xfb_p: VxXfbParams;\n", group));
    let mut used_slots: Vec<u32> = attributes.iter().map(|a| a.slot).collect();
    used_slots.sort_unstable();
    used_slots.dedup();
    for &s in &used_slots {
        wgsl.push_str(&format!("@group({g}) @binding({b}) var<storage, read> vx_vb{s}: array<u32>;\n\
            fn vx_word{s}(a: u32) -> u32 {{ let w = a >> 2u; let k = (a & 3u) * 8u; if (k == 0u) {{ return vx_vb{s}[w]; }} \
            return (vx_vb{s}[w] >> k) | (vx_vb{s}[w + 1u] << (32u - k)); }}\n\
            fn vx_byte{s}(a: u32) -> u32 {{ return (vx_vb{s}[a >> 2u] >> ((a & 3u) * 8u)) & 0xFFu; }}\n",
            g = group, b = 961 + s, s = s));
    }
    let mut used_buffers: Vec<u32> = if all { vec![0] } else { captures.iter().map(|c| c.buffer).collect() };
    used_buffers.sort_unstable();
    used_buffers.dedup();
    for &b in &used_buffers {
        wgsl.push_str(&format!("@group({}) @binding({}) var<storage, read_write> vx_xfb{}: array<u32>;\n", group, 970 + b, b));
    }
    wgsl.push_str("@compute @workgroup_size(64) fn vx_xfb(@builtin(global_invocation_id) id: vec3<u32>) {\n\
        let n = id.x;\n\
        if (n >= vx_xfb_p.limit) { return; }\n\
        let vertex = vx_xfb_p.first_vertex + n % vx_xfb_p.vertex_count;\n\
        let instance = vx_xfb_p.first_instance + n / vx_xfb_p.vertex_count;\n");
    let mut call = Vec::new();
    for (i, (binding, ty)) in arguments.iter().enumerate() {
        let wgsl_ty = wgsl_type(module, *ty).ok_or("a vertex input of a type not done")?;
        let value = match binding {
            Some(Binding::BuiltIn(BuiltIn::VertexIndex)) => format!("{}(vertex)", wgsl_ty),
            Some(Binding::BuiltIn(BuiltIn::InstanceIndex)) => format!("{}(instance)", wgsl_ty),
            Some(Binding::Location { location, .. }) => {
                let a = attributes.iter().find(|a| a.location == *location).ok_or("a vertex input without an attribute")?;
                let slot = slots.iter().find(|s| s.slot == a.slot).ok_or("an attribute without its buffer")?;
                let (count, bytes, kind) = format_info(a.format).ok_or_else(|| format!("vertex format {} not done", a.format))?;
                wgsl.push_str(&format!("    let a{i} = vx_xfb_p.vb[{}][{}] + {} * {}u + {}u;\n", a.slot / 4, a.slot % 4,
                    if slot.instance { "instance" } else { "vertex" }, slot.stride, a.offset));
                let parts: Vec<String> = (0..count).map(|k| component(a.slot, &format!("a{} + {}u", i, k * bytes), bytes, kind)).collect();
                // (the input's type: as many components as it has, the format's missing ones 0, 0, 0, 1)
                let (size, scalar) = match module.types[*ty].inner {
                    TypeInner::Scalar(s) => (1, s),
                    TypeInner::Vector { size, scalar } => (size as u32, scalar),
                    _ => return Err(String::from("a vertex input of a type not done")),
                };
                let base = wgsl_type(module, module.types.iter().find(|(_, t)| t.inner == TypeInner::Scalar(scalar)).map(|(h, _)| h)
                    .unwrap_or(*ty)).unwrap_or_else(|| String::from("f32"));
                let one = if scalar.kind == ScalarKind::Float { "1.0" } else { "1" };
                let values: Vec<String> = (0..size).map(|k| if k < count { format!("{}({})", base, parts[k as usize]) }
                    else if k == 3 { format!("{}({})", base, one) } else { format!("{}(0)", base) }).collect();
                if size == 1 { values[0].clone() } else { format!("{}({})", wgsl_ty, values.join(", ")) }
            },
            _ => return Err(String::from("a vertex input not done")),
        };
        wgsl.push_str(&format!("    let v{} = {};\n", i, value));
        call.push(format!("v{}", i));
    }
    wgsl.push_str(&format!("    let o = vx_vs({});\n    let at = vx_xfb_p.first_capture + n;\n", call.join(", ")));
    if all {
        // (each output's words: as geometry.rs reads them)
        let mut writes: Vec<(String, ScalarKind, u32)> = Vec::new();
        let mut last = 0u32;
        for (i, m) in members.iter().enumerate() {
            let name = format!("o.vx_o{}m", i);
            match m.binding {
                Some(Binding::BuiltIn(BuiltIn::Position { .. })) => {
                    for k in 0..4 {
                        writes.push((format!("{}[{}]", name, k), ScalarKind::Float, k));
                    }
                },
                Some(Binding::BuiltIn(BuiltIn::PointSize)) => writes.push((name, ScalarKind::Float, 4)),
                Some(Binding::Location { location, .. }) => {
                    let mut parts = Vec::new();
                    let used = location_scalars(module, m.ty, &name, location, &mut parts).ok_or("an output of a type not done")?;
                    last = last.max(location + used);
                    for (expr, kind, l, k) in parts {
                        writes.push((expr, kind, 8 + 4 * l + k));
                    }
                },
                _ => {},
            }
        }
        let stride = 4 * (8 + 4 * last);
        for (expr, kind, word) in writes {
            let value = if kind == ScalarKind::Uint { expr } else { format!("bitcast<u32>({})", expr) };
            wgsl.push_str(&format!("    vx_xfb0[vx_xfb_p.offsets[0] / 4u + at * {}u + {}u] = {};\n", stride / 4, word, value));
        }
        wgsl.push_str("}\n");
        return Ok((wgsl, [stride, 0, 0, 0]));
    }
    for c in captures {
        let member = members.iter().position(|m| match (&m.binding, c.output) {
            (Some(Binding::Location { location, .. }), Output::Location(l)) => *location == l,
            (Some(Binding::BuiltIn(BuiltIn::Position { .. })), Output::Position) => true,
            (Some(Binding::BuiltIn(BuiltIn::PointSize)), Output::PointSize) => true,
            _ => false,
        }).ok_or("a captured output the shader does not write")?;
        let mut parts = Vec::new();
        if !scalars(module, members[member].ty, &format!("o.vx_o{}m", member), &mut parts) {
            return Err(String::from("a captured output of a type not done"));
        }
        let stride = strides[c.buffer as usize & 3];
        for (k, (expr, kind)) in parts.iter().enumerate() {
            let value = if *kind == ScalarKind::Uint { expr.clone() } else { format!("bitcast<u32>({})", expr) };
            wgsl.push_str(&format!("    vx_xfb{b}[(vx_xfb_p.offsets[{b}] + at * {stride}u + {off}u) / 4u] = {v};\n",
                b = c.buffer, stride = stride, off = c.offset + 4 * k as u32, v = value));
        }
    }
    wgsl.push_str("}\n");
    let _ = VectorSize::Bi;
    Ok((wgsl, strides))
}
                                                                  source/v64/src/browser/glbridge/vx/vx_executor.js                                                   0000644 0000000 0000000 00000532260 00000000000 017273  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VX: the renderer of virtio-gpu's Venus contexts (Vulkan; docs/gpu-devices.md,
// "Venus (Vulkan)"), on WebGPU. The device
// (src/graphics_adapters/virtio_gpu/venus_vk*.js) keeps the guest's Vulkan
// objects and sends VX batches: the GPU objects to make, the bytes the guest
// wrote into mapped memory, each submission's commands (BEGIN .. END: one
// command encoder), and readbacks of memory, answered through the response
// region as GX answers its own.
//
// - A VkDeviceMemory is a GPUBuffer; buffers are ranges of it, named in
//   each command by (memory, offset). A VkImage is a GPUTexture (cubes are
//   2D arrays), its views GPUTextureViews.
// - WebGPU copies between buffers and textures only with rows of a multiple
//   of 256 bytes: other pitches go through a staging buffer, row by row.
// - Clears, blits and resolves are render passes.
(function(global) {
    "use strict";

    const VX_MAGIC = 0x30315856;
    const VX = {
        MEMORY_CREATE: 1, DESTROY: 2, MEMORY_WRITE: 3, MEMORY_READ: 4, TEXTURE_CREATE: 5, VIEW_CREATE: 6, SAMPLER_CREATE: 7,
        BEGIN: 8, END: 9, COPY_BUFFER: 10, FILL_BUFFER: 11, UPDATE_BUFFER: 12, COPY_BUFFER_IMAGE: 13, COPY_IMAGE: 14,
        BLIT_IMAGE: 15, CLEAR_IMAGE: 16, RESOLVE_IMAGE: 17,
        SHADER_CREATE: 18, PIPELINE_CREATE: 19, BEGIN_PASS: 20, END_PASS: 21, BIND_PIPELINE: 22, SET_BIND_GROUP: 23,
        SET_VERTEX_BUFFER: 24, SET_INDEX_BUFFER: 25, SET_PUSH_CONSTANTS: 26, SET_VIEWPORT: 27, SET_SCISSOR: 28,
        SET_BLEND_CONSTANTS: 29, SET_STENCIL_REFERENCE: 30, DRAW: 31, DRAW_INDEXED: 32, DRAW_INDIRECT: 33,
        DISPATCH: 34, DISPATCH_INDIRECT: 35, CLEAR_ATTACHMENTS: 36,
        QUERY_POOL_CREATE: 37, BEGIN_QUERY: 38, END_QUERY: 39, COPY_QUERY_RESULTS: 40, TEXTURE_READ: 41, TEXTURE_WRITE: 42,
        TEXTURE_IMPORT: 43, XFB_BIND: 44, XFB_BEGIN: 45, XFB_END: 46, SET_STENCIL_COMPARE_MASK: 47, SET_STENCIL_WRITE_MASK: 48,
        SET_DEPTH_BIAS: 49,
    };
    // VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT; VkPrimitiveTopology's vertices a primitive (lists only)
    const QUERY_XFB = 1000028004;
    const LIST_VERTICES = { 0: 1, 1: 2, 3: 3 };
    // where the bundle is: naga's wasm is beside it
    const SCRIPT = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : null;
    // Vulkan's enums, as WebGPU's
    const TOPOLOGY = ["point-list", "line-list", "line-strip", "triangle-list", "triangle-strip", null];
    // WGSL's bindings of a Vulkan binding b (vx/naga's rebind): 2b, 2b + 1 for
    // a combined image sampler's sampler; for element e > 0 of a descriptor
    // array (vx/naga/src/blockarrays.rs) ELEMENTS + 2 (16b + e), and one more
    // for its sampler (below 960: xfb.rs binds from there)
    const ELEMENTS = 300, ELEMENTS_END = 960;
    /** vx_naga's translation flags */
    const TRANSLATE = { KEEP: 1, NO_DEPTH: 2, REVERSE_DEPTH: 4 };
    /** The descriptor (binding * 1024 + element) a WGSL binding is of */
    const descriptorKey = binding => binding >= ELEMENTS && binding < ELEMENTS_END ?
        ((binding - ELEMENTS) >> 5) * 1024 + ((binding - ELEMENTS) >> 1 & 15) : (binding >> 1) * 1024;
    const samplerBinding = binding => (binding & 1) === 1;
    /** A render pass's or pipeline's attachments, as WebGPU compares them (trailing empty colors aside) */
    const attachmentState = (colors, depth, samples) => {
        const c = colors.map(f => f || "-");
        while (c.length && c[c.length - 1] === "-") c.pop();
        return c.join(",") + "|" + (depth || "") + "|" + samples;
    };
    const BLEND_FACTOR = ["zero", "one", "src", "one-minus-src", "dst", "one-minus-dst", "src-alpha", "one-minus-src-alpha",
        "dst-alpha", "one-minus-dst-alpha", "constant", "one-minus-constant", "constant", "one-minus-constant",
        "src-alpha-saturated", "src1", "one-minus-src1", "src1-alpha", "one-minus-src1-alpha"];
    const BLEND_OP = ["add", "subtract", "reverse-subtract", "min", "max"];
    const STENCIL_OP = ["keep", "zero", "replace", "increment-clamp", "decrement-clamp", "invert", "increment-wrap", "decrement-wrap"];
    // the group and binding of push constants (vx/naga): after the sets, or in the last group
    const PUSH_BINDING = 998;
    // (WebGPU's uniform buffers a stage, the default limit; the rest a stage
    // uses are read-only storage buffers: createPipeline)
    const MAX_UNIFORMS_PER_STAGE = 12;
    /** the attachment of passes and pipelines without any (WebGPU needs one) */
    const PLACEHOLDER_FORMAT = "r8unorm";
    const pushGroup = setCount => setCount < 4 ? setCount : 3;
    const QUERY_REGION_BYTES = 16 * 1024, RESPONSE_OK = 1, RESPONSE_FAILED = 2;
    const BUFFER = { MAP_READ: 1, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64, STORAGE: 128, INDIRECT: 256, QUERY_RESOLVE: 512 };
    const TEXTURE = { COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16 };
    // VkImageUsageFlagBits
    const USAGE = { TRANSFER_DST: 0x2, SAMPLED: 0x4, STORAGE: 0x8, COLOR: 0x10, DEPTH: 0x20, INPUT: 0x80 };
    // VkImageAspectFlagBits
    const ASPECT = { COLOR: 1, DEPTH: 2, STENCIL: 4 };

    const align = (value, to) => Math.ceil(value / to) * to;
    /** The bytes of a WebGPU vertex format ("float32x3": 12, "unorm10-10-10-2": 4) */
    const vertexFormatBytes = format => {
        const m = /^[a-z]+(8|16|32)(?:x([234]))?$/.exec(format);
        return m ? +m[1] / 8 * (+m[2] || 1) : 4;
    };
    /**
     * How a view bound as `kind` is sampled through a copy (VX.swizzleCopies),
     * the view's field holding it: "depthRead" for a depth view bound as a float
     * texture, "swizzled" for a swizzled color view; null: the view itself
     */
    const copyMode = (v, kind) => {
        if (kind === "texture" && v.f.hasDepth && v.descriptor.aspect !== "stencil-only" && v.texture.samples <= 1) return "depthRead";
        if (v.swizzle && !v.f.depth && v.texture.samples <= 1 && kind !== "storage-texture") return "swizzled";
        return null;
    };
    /** VK_FORMAT_R5G6B5_UNORM_PACK16: an rgba8unorm texture whose alpha stays 1 (draws and clears leave it) */
    const R5G6B5 = 4;
    /** The color write mask a format's target takes: no alpha into R5G6B5 */
    const alphaMask = f => f && f.packed === R5G6B5 ? 0x7 : 0xF;
    /** The most vertices a draw's packed vertex input has (VX.packVertices) */
    const PACKED_ROWS = 1 << 20;
    const f32 = bits => new Float32Array(new Uint32Array([bits]).buffer)[0];
    const SRGB_TWIN = { "rgba8unorm": "rgba8unorm-srgb", "rgba8unorm-srgb": "rgba8unorm", "bgra8unorm": "bgra8unorm-srgb", "bgra8unorm-srgb": "bgra8unorm" };
    const VIEW_DIMENSION = ["2d", "2d", "3d", "cube", "2d-array", "2d-array", "cube-array"];
    const ADDRESS = ["repeat", "mirror-repeat", "clamp-to-edge", "clamp-to-edge", "mirror-repeat"];
    const COMPARE = ["never", "less", "equal", "less-equal", "greater", "not-equal", "greater-equal", "always"];

    class VXExecutor {
        /**
         * @param options { device, formats: VkFormat -> [WebGPU format, capabilities, vertex format, bytes] }
         */
        constructor(options) {
            this.device = options.device;
            this.formats = options.formats || global.V86VenusFormats || {};
            /** a pipeline's buffers' least binding sizes (group << 16 | binding), by its groups (which its variants share) */
            this.bindingSizes = new WeakMap();
            // { surface(sid) }: GX's surfaces, for images Venus imports from virtio-gpu resources
            this.peer = options.peer || null;
            this.objects = new Map();
            this.encoderInstance = null;
            this.pending = [];
            this.transient = [];
            this.pipelines = new Map();
            this.warned = new Set();
            this.warnings = [];
            this.errors = 0;
            this.stats = { batches: 0, commands: 0, readbacks: 0, submits: 0, draws: 0, dispatches: 0, pipelines: 0 };
            this.write = null;
            this.nagaUrl = options.nagaUrl || global.V86VenusNagaUrl || (SCRIPT ? new URL("vx_naga.wasm", SCRIPT).href : "vx_naga.wasm");
            this.naga = null;
            this.pass = null;
            this.computePass = null;
            this.queryResolves = [];
            this.activeQuery = -1;
            this.ones = null;
            // transform feedback: each counter's bytes (memory:offset -> value), as End wrote it; the active query
            this.xfbCounters = new Map();
            this.xfbQuery = null;
            this.resetState();
        }

        resetState() {
            this.state = {
                graphics: null, compute: null, pipelineApplied: false,
                // group contents by bind point (0 graphics, 1 compute): group -> { version, descriptors }
                groups: [new Map(), new Map()], groupVersion: 0,
                vertex: [], vertexDirty: true, index: null, indexDirty: true,
                push: new Uint8Array(256), pushVersion: 0,
                viewport: null, scissor: null, blend: null, stencilReference: 0, stencilMasks: [0xFF, 0xFF], stencilBack: [0xFF, 0xFF, 0], dynamicDirty: true,
                passWidth: 0, passHeight: 0,
                // transform feedback: the buffers ({ memory, offset, size } by binding), whether it is active, the bytes captured into each
                xfb: { buffers: [], active: false, written: [0, 0, 0, 0] },
            };
        }

        /** a JSON body: the bytes after `skip` dwords */
        json(b, skip) {
            const bytes = new Uint8Array(b.buffer, b.byteOffset + skip * 4, b.byteLength - skip * 4);
            let end = bytes.length;
            while (end && !bytes[end - 1]) end--;
            return JSON.parse(new TextDecoder().decode(bytes.subarray(0, end)));
        }

        warn(key, text) {
            if (this.warned.has(key)) return;
            this.warned.add(key);
            if (this.warnings.length < 100) this.warnings.push(text);
            console.warn("[vx] " + text);
        }

        reset() {
            this.flushEncoder();
            for (const object of this.objects.values()) this.release(object);
            this.objects.clear();
        }

        release(object) {
            if (object.buffer) object.buffer.destroy();
            if (object.querySet) object.querySet.destroy();
            // (an imported image's texture is its GX surface's)
            if (object.texture && object.kind === "texture" && !object.borrowed) object.texture.destroy();
        }

        /**
         * Run a VX batch
         * @param bytes Uint8Array
         * @param options { writeResponse(offset, bytes) }
         */
        async submit(bytes, options) {
            this.write = options.writeResponse;
            if (bytes.byteOffset & 3) bytes = bytes.slice();
            const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
            if (words[0] !== VX_MAGIC) throw new Error("not a VX batch");
            const end = Math.min(words[2], words.length);
            this.stats.batches++;
            // (WebGPU's validation errors come later: what a batch did wrong is warned about)
            this.device.pushErrorScope("validation");
            for (let at = 4; at + 2 <= end;) {
                const op = words[at], n = words[at + 1];
                const body = words.subarray(at + 2, at + 2 + n);
                at += 2 + n;
                this.stats.commands++;
                try {
                    const r = this.command(op, body);
                    // (pipelines wait for their shaders' translation)
                    if (r && r.then) await r;
                } catch (error) {
                    this.errors++;
                    this.warn("exception:" + op + ":" + error.message, "VX op " + op + " failed: " + (error.stack || error));
                }
            }
            this.endPasses();
            this.flushEncoder();
            this.device.popErrorScope().then(error => {
                if (!error) return;
                this.errors++;
                this.warn("validation:" + error.message.slice(0, 80), "WebGPU: " + error.message);
            });
            const pending = this.pending.splice(0);
            if (pending.length) await Promise.all(pending);
        }

        command(op, b) {
            switch (op) {
                case VX.MEMORY_CREATE: return this.createMemory(b[0], b[1] + b[2] * 0x100000000);
                case VX.DESTROY: {
                    const object = this.objects.get(b[0]);
                    if (object) {
                        // (after the work that uses it)
                        this.flushEncoder();
                        this.release(object);
                    }
                    this.objects.delete(b[0]);
                    return;
                }
                case VX.MEMORY_WRITE: return this.writeMemory(b);
                case VX.MEMORY_READ: return this.readMemory(b);
                case VX.TEXTURE_CREATE: return this.createTexture(b);
                case VX.VIEW_CREATE: return this.createView(b);
                case VX.SAMPLER_CREATE: return this.createSampler(b);
                case VX.BEGIN: return;
                case VX.END: this.stats.submits++; return this.flushEncoder();
                case VX.COPY_BUFFER: return this.copyBuffer(b);
                case VX.FILL_BUFFER: return this.fillBuffer(b);
                case VX.UPDATE_BUFFER: return this.updateBuffer(b);
                case VX.COPY_BUFFER_IMAGE: return this.copyBufferImage(b);
                case VX.COPY_IMAGE: return this.copyImage(b);
                case VX.BLIT_IMAGE: return this.blitImage(b);
                case VX.CLEAR_IMAGE: return this.clearImage(b);
                case VX.RESOLVE_IMAGE: return this.resolveImage(b);
                case VX.SHADER_CREATE: {
                    this.objects.set(b[0], { kind: "shader", spirv: new Uint8Array(b.buffer, b.byteOffset + 8, b[1]).slice(), translations: new Map() });
                    return;
                }
                case VX.PIPELINE_CREATE: return this.createPipeline(b[0], this.json(b, 1));
                case VX.BEGIN_PASS: return this.beginPass(this.json(b, 0));
                case VX.END_PASS: {
                    this.endPass();
                    // (the depth and stencil resolved, VK_KHR_depth_stencil_resolve's sample zero)
                    const depth = this.passDesc && this.passDesc.depth;
                    if (depth && depth.resolve) this.resolveDepthStencil(depth);
                    return;
                }
                case VX.BIND_PIPELINE: {
                    const p = this.objects.get(b[0]);
                    if (p && p.kind === "pipeline") {
                        if (p.compute) this.state.compute = p;
                        else { this.state.graphics = p; this.state.pipelineApplied = false; }
                    }
                    return;
                }
                case VX.SET_BIND_GROUP: return this.setBindGroup(b);
                case VX.SET_VERTEX_BUFFER: {
                    this.state.vertex[b[0]] = { memory: b[1], offset: b[2] + b[3] * 0x100000000, size: b[4] + b[5] * 0x100000000 };
                    this.state.vertexDirty = true;
                    return;
                }
                case VX.SET_INDEX_BUFFER:
                    this.state.index = { memory: b[0], offset: b[1] + b[2] * 0x100000000, size: b[3] + b[4] * 0x100000000, type: b[5] };
                    this.state.indexDirty = true;
                    return;
                case VX.SET_PUSH_CONSTANTS: {
                    this.state.push.set(new Uint8Array(b.buffer, b.byteOffset + 8, Math.min(b[1], 256 - b[0])), b[0]);
                    this.state.pushVersion++;
                    return;
                }
                case VX.SET_VIEWPORT: this.state.viewport = Array.from(b.subarray(0, 6), f32); this.state.dynamicDirty = true; return;
                case VX.SET_SCISSOR: this.state.scissor = [b[0] | 0, b[1] | 0, b[2], b[3]]; this.state.dynamicDirty = true; return;
                case VX.SET_BLEND_CONSTANTS: this.state.blend = Array.from(b.subarray(0, 4), f32); this.state.dynamicDirty = true; return;
                case VX.SET_STENCIL_REFERENCE:
                    if (b[0] & 1) this.state.stencilReference = b[1];
                    if (b[0] & 2) this.state.stencilBack[2] = b[1];
                    this.state.dynamicDirty = true;
                    return;
                // (the front face's: WebGPU has one pair for both faces)
                // (the back face's: stencilBack, compare and write masks and reference)
                case VX.SET_STENCIL_COMPARE_MASK:
                    if (b[0] & 1) this.state.stencilMasks[0] = b[1] & 0xFF;
                    if (b[0] & 2) this.state.stencilBack[0] = b[1] & 0xFF;
                    return;
                case VX.SET_STENCIL_WRITE_MASK:
                    if (b[0] & 1) this.state.stencilMasks[1] = b[1] & 0xFF;
                    if (b[0] & 2) this.state.stencilBack[1] = b[1] & 0xFF;
                    return;
                case VX.SET_DEPTH_BIAS: this.state.depthBias = Array.from(b.subarray(0, 3), f32); return;
                case VX.DRAW: return this.draw(b, 0);
                case VX.DRAW_INDEXED: return this.draw(b, 1);
                case VX.DRAW_INDIRECT: return this.draw(b, 2);
                case VX.DISPATCH: return this.dispatch(b, false);
                case VX.DISPATCH_INDIRECT: return this.dispatch(b, true);
                case VX.CLEAR_ATTACHMENTS: return this.clearAttachments(this.json(b, 0));
                case VX.QUERY_POOL_CREATE:
                    if (b[1] === 0) this.objects.set(b[0], { kind: "queries", querySet: this.device.createQuerySet({ type: "occlusion", count: Math.max(1, b[2]) }) });
                    // (transform feedback's: the captures count the primitives)
                    if (b[1] === QUERY_XFB) this.objects.set(b[0], { kind: "queries", xfb: true, count: b[2] });
                    return;
                case VX.BEGIN_QUERY:
                    if (this.objects.get(b[0]) && this.objects.get(b[0]).xfb) { this.xfbQuery = { pool: b[0], query: b[1], written: 0, needed: 0 }; return; }
                    if (this.pass && this.passInfo.occlusion === b[0]) { this.pass.beginOcclusionQuery(b[1]); this.activeQuery = b[1]; }
                    else this.warn("query-outside", "an occlusion query outside of a render pass, or of another pool than the pass's");
                    return;
                case VX.END_QUERY: {
                    if (this.xfbQuery && this.xfbQuery.pool === b[0] && this.xfbQuery.query === b[1]) {
                        // (two u64, primitives written and needed; the queue's write goes before this encoder)
                        const q = this.xfbQuery, memory = this.memory(b[2]);
                        this.xfbQuery = null;
                        if (memory && b[1] * 16 + 16 <= memory.buffer.size) this.device.queue.writeBuffer(memory.buffer, b[1] * 16,
                            new Uint32Array([q.written >>> 0, Math.floor(q.written / 0x100000000), q.needed >>> 0, Math.floor(q.needed / 0x100000000)]));
                        return;
                    }
                    if (!this.pass || this.activeQuery !== b[1]) return;
                    this.pass.endOcclusionQuery();
                    this.activeQuery = -1;
                    const pool = this.objects.get(b[0]), memory = this.memory(b[2]);
                    if (pool && memory) this.queryResolves.push([pool.querySet, b[1], memory]);
                    return;
                }
                case VX.COPY_QUERY_RESULTS: return this.copyQueryResults(b);
                case VX.TEXTURE_READ: return this.readTexture(b);
                case VX.TEXTURE_WRITE: return this.writeTexture(b);
                case VX.TEXTURE_IMPORT: return this.importTexture(b);
                case VX.XFB_BIND:
                    this.state.xfb.buffers[b[0] & 3] = { memory: b[1], offset: b[2] + b[3] * 0x100000000, size: b[4] + b[5] * 0x100000000 };
                    return;
                case VX.XFB_BEGIN: return this.xfbBegin(b, true);
                case VX.XFB_END: return this.xfbBegin(b, false);
            }
            this.warn("op" + op, "unknown VX op " + op);
        }

        // ------------------------------------------------------------------
        // The encoder

        encoder() {
            // (copies and render passes are outside of compute passes)
            if (this.computePass) { this.computePass.end(); this.computePass = null; }
            if (!this.encoderInstance) this.encoderInstance = this.device.createCommandEncoder();
            return this.encoderInstance;
        }

        endPasses() {
            this.endPass();
            if (this.computePass) { this.computePass.end(); this.computePass = null; }
        }

        /** the occlusion queries a pass ended: their results into their pools' memory (through 256-aligned places) */
        resolveQueries() {
            const list = this.queryResolves;
            if (!list.length) return;
            this.queryResolves = [];
            const scratch = this.scratch(list.length * 256, BUFFER.QUERY_RESOLVE | BUFFER.COPY_SRC);
            const encoder = this.encoder();
            list.forEach(([set, index, memory], i) => {
                encoder.resolveQuerySet(set, index, 1, scratch, i * 256);
                encoder.copyBufferToBuffer(scratch, i * 256, memory.buffer, index * 8, 8);
            });
        }

        /**
         * vkCmdCopyQueryPoolResults: the u64 results (`values` a query: two
         * for transform feedback's), or their low halves, and availability
         * (1: run in order, they are done)
         */
        copyQueryResults(b) {
            const [from, first, count, to, low, high, stride, flags] = b;
            const values = b[8] || 1;
            const src = this.memory(from), dst = this.memory(to);
            if (!src || !dst) return;
            const offset = low + high * 0x100000000, size = flags & 1 ? 8 : 4;
            if (!this.ones) {
                this.ones = this.device.createBuffer({ size: 8, usage: BUFFER.COPY_SRC, mappedAtCreation: true });
                new Uint32Array(this.ones.getMappedRange()).set([1, 0]);
                this.ones.unmap();
            }
            const encoder = this.encoder();
            for (let i = 0; i < count; i++) {
                const at = offset + i * stride;
                if (at + values * size > dst.buffer.size) break;
                for (let k = 0; k < values; k++) encoder.copyBufferToBuffer(src.buffer, ((first + i) * values + k) * 8, dst.buffer, at + k * size, size);
                if (flags & 4 && at + (values + 1) * size <= dst.buffer.size) encoder.copyBufferToBuffer(this.ones, 0, dst.buffer, at + values * size, size);
            }
        }

        flushEncoder() {
            this.endPasses();
            if (this.encoderInstance) {
                this.device.queue.submit([this.encoderInstance.finish()]);
                this.encoderInstance = null;
            }
            for (const buffer of this.transient.splice(0)) buffer.destroy();
        }

        /** A buffer with these bytes, to copy from in the encoder */
        staging(bytes) {
            const size = align(Math.max(4, bytes.length), 4);
            const buffer = this.device.createBuffer({ size, usage: BUFFER.COPY_SRC, mappedAtCreation: true });
            new Uint8Array(buffer.getMappedRange()).set(bytes);
            buffer.unmap();
            this.transient.push(buffer);
            return buffer;
        }

        scratch(size, usage) {
            const buffer = this.device.createBuffer({ size: align(Math.max(4, size), 4), usage });
            this.transient.push(buffer);
            return buffer;
        }

        // ------------------------------------------------------------------
        // Memory

        createMemory(id, size) {
            const limit = this.device.limits.maxBufferSize;
            if (size > limit) {
                this.warn("memory-size", "memory of " + size + " bytes is more than WebGPU's buffers have (" + limit + ")");
                return;
            }
            const usage = BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.INDEX | BUFFER.VERTEX | BUFFER.UNIFORM | BUFFER.STORAGE |
                BUFFER.INDIRECT | BUFFER.QUERY_RESOLVE;
            this.objects.set(id, { kind: "memory", buffer: this.device.createBuffer({ size: align(Math.max(4, size), 4), usage }), size });
        }

        memory(id) {
            const m = this.objects.get(id);
            return m && m.kind === "memory" ? m : null;
        }

        writeMemory(b) {
            const m = this.memory(b[0]);
            const offset = b[1] + b[2] * 0x100000000, length = b[3];
            if (!m) return;
            const bytes = new Uint8Array(b.buffer, b.byteOffset + 16, length);
            this.flushEncoder();
            // (whole dwords: the memory's size is rounded up to them)
            const padded = length & 3 || offset & 3 ? null : bytes;
            if (padded) this.device.queue.writeBuffer(m.buffer, offset, padded);
            else {
                const start = offset & ~3, stop = Math.min(m.buffer.size, align(offset + length, 4));
                if (start === offset && length % 4 === 0) this.device.queue.writeBuffer(m.buffer, offset, bytes);
                else {
                    // (an unaligned edge: the bytes around it come from a readback first)
                    this.warn("unaligned-write", "a memory write of " + length + " bytes at " + offset + " is not in whole dwords");
                    const whole = new Uint8Array(stop - start);
                    whole.set(bytes, offset - start);
                    this.device.queue.writeBuffer(m.buffer, start, whole);
                }
            }
        }

        readMemory(b) {
            const [id, low, high, length, request] = b;
            const m = this.memory(id);
            const offset = low + high * 0x100000000;
            if (!m || offset + length > m.buffer.size) return this.respond(request, null);
            this.stats.readbacks++;
            const start = offset & ~3, stop = Math.min(m.buffer.size, align(offset + length, 4));
            const target = this.device.createBuffer({ size: Math.max(4, stop - start), usage: BUFFER.MAP_READ | BUFFER.COPY_DST });
            if (stop > start) this.encoder().copyBufferToBuffer(m.buffer, start, target, 0, stop - start);
            this.flushEncoder();
            this.pending.push(target.mapAsync(1).then(() => {
                const bytes = new Uint8Array(target.getMappedRange()).slice(offset - start, offset - start + length);
                target.destroy();
                this.respond(request, bytes);
            }, () => { target.destroy(); this.respond(request, null); }));
        }

        /** A readback's answer: id, length, 0, status, then the bytes */
        respond(id, bytes) {
            const out = new Uint8Array(16 + (bytes ? bytes.length : 0));
            const view = new DataView(out.buffer);
            view.setUint32(0, id, true);
            view.setUint32(4, bytes ? bytes.length : 0, true);
            view.setUint32(12, bytes ? RESPONSE_OK : RESPONSE_FAILED, true);
            if (bytes) out.set(bytes, 16);
            if (this.write) this.write(QUERY_REGION_BYTES, out);
        }

        copyBuffer(b) {
            const src = this.memory(b[0]), dst = this.memory(b[3]);
            const from = b[1] + b[2] * 0x100000000, to = b[4] + b[5] * 0x100000000, size = b[6] + b[7] * 0x100000000;
            if (!src || !dst) return;
            if ((from | to | size) & 3) {
                this.copyBytes(src.buffer, from, dst.buffer, to, size);
                return;
            }
            if (src === dst) {
                // (WebGPU copies between two buffers only: through another)
                const between = this.scratch(size, BUFFER.COPY_SRC | BUFFER.COPY_DST);
                this.encoder().copyBufferToBuffer(src.buffer, from, between, 0, size);
                this.encoder().copyBufferToBuffer(between, 0, dst.buffer, to, size);
                return;
            }
            this.encoder().copyBufferToBuffer(src.buffer, from, dst.buffer, to, size);
        }

        /**
         * A copy of bytes not in whole dwords (Vulkan's copies have no
         * alignment, WebGPU's are of dwords): repack's, one row
         */
        copyBytes(src, from, dst, to, size) {
            if (size) this.repack(src, { offset: from, pitch: size, image: size }, dst, { offset: to, pitch: size, image: size }, size, 1, 1);
        }

        /**
         * Rows of bytes from one buffer layout to another, neither in whole
         * dwords: a compute shader writes each destination dword, the
         * source's bytes merged into it (the bytes between the rows kept).
         * Layouts: { offset, pitch (a row's), image (a slice's) }; a repack
         * within one buffer goes through a scratch buffer first
         */
        repack(src, from, dst, to, rowBytes, rows, slices) {
            const last = (l) => l.offset + (slices - 1) * l.image + (rows - 1) * l.pitch + rowBytes;
            if (src === dst) {
                const start = from.offset & ~3, length = align(last(from) - start, 4);
                const between = this.scratch(length, BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.STORAGE);
                this.encoder().copyBufferToBuffer(src, start, between, 0, length);
                src = between;
                from = Object.assign({}, from, { offset: from.offset - start });
            }
            if (!this.repacker) {
                const code = [
                    "struct P { src: u32, src_pitch: u32, src_image: u32, dst: u32, dst_pitch: u32, dst_image: u32, row: u32, rows: u32, slices: u32, end: u32 };",
                    "@group(0) @binding(0) var<uniform> p: P;",
                    "@group(0) @binding(1) var<storage, read> s: array<u32>;",
                    "@group(0) @binding(2) var<storage, read_write> d: array<u32>;",
                    "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>) {",
                    "    let w = (p.dst >> 2u) + id.x;",
                    "    if (w * 4u >= p.end) { return; }",
                    "    var word = d[w];",
                    "    for (var k = 0u; k < 4u; k++) {",
                    "        let at = w * 4u + k;",
                    "        if (at < p.dst || at >= p.end) { continue; }",
                    "        let rel = at - p.dst;",
                    "        let slice = rel / p.dst_image;",
                    "        let row = (rel % p.dst_image) / p.dst_pitch;",
                    "        let column = (rel % p.dst_image) % p.dst_pitch;",
                    "        if (slice >= p.slices || row >= p.rows || column >= p.row) { continue; }",
                    "        let i = p.src + slice * p.src_image + row * p.src_pitch + column;",
                    "        let b = (s[i >> 2u] >> ((i & 3u) * 8u)) & 0xFFu;",
                    "        word = (word & ~(0xFFu << (k * 8u))) | (b << (k * 8u));",
                    "    }",
                    "    d[w] = word;",
                    "}",
                ].join("\n");
                this.repacker = this.device.createComputePipeline({ layout: "auto", compute: { module: this.device.createShaderModule({ code }), entryPoint: "main" } });
            }
            const end = last(to);
            const params = this.device.createBuffer({ size: 48, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
            this.device.queue.writeBuffer(params, 0, Uint32Array.from([from.offset, from.pitch, from.image, to.offset, to.pitch, to.image, rowBytes, rows, slices, end, 0, 0]));
            this.transient.push(params);
            const group = this.device.createBindGroup({ layout: this.repacker.getBindGroupLayout(0), entries: [
                { binding: 0, resource: { buffer: params } }, { binding: 1, resource: { buffer: src } }, { binding: 2, resource: { buffer: dst } }] });
            const pass = this.encoder().beginComputePass();
            pass.setPipeline(this.repacker);
            pass.setBindGroup(0, group);
            pass.dispatchWorkgroups(Math.ceil((((end + 3) >> 2) - (to.offset >> 2)) / 64));
            pass.end();
        }

        fillBuffer(b) {
            const dst = this.memory(b[0]);
            const offset = b[1] + b[2] * 0x100000000, size = b[3] + b[4] * 0x100000000, data = b[5];
            if (!dst || !size) return;
            if (data === 0) {
                this.encoder().clearBuffer(dst.buffer, offset, size);
                return;
            }
            const pattern = new Uint32Array(size / 4).fill(data);
            this.encoder().copyBufferToBuffer(this.staging(new Uint8Array(pattern.buffer)), 0, dst.buffer, offset, size);
        }

        updateBuffer(b) {
            const dst = this.memory(b[0]);
            const offset = b[1] + b[2] * 0x100000000, length = b[3];
            if (!dst || !length) return;
            const bytes = new Uint8Array(b.buffer, b.byteOffset + 16, length);
            this.encoder().copyBufferToBuffer(this.staging(bytes), 0, dst.buffer, offset, align(length, 4));
        }

        // ------------------------------------------------------------------
        // Textures

        format(vk) {
            const entry = this.formats[vk];
            if (!entry || !entry[0]) return null;
            const [wanted, caps, , bytes] = entry;
            // (an optional format the device has not got: the nearest it has)
            const gpu = wanted === "depth32float-stencil8" && this.device && !this.device.features.has(wanted) ? "depth24plus-stencil8" : wanted;
            return { gpu, bytes, caps, float: /[fx]/.test(caps), int: caps.includes("i"), depth: caps.includes("d"), packed: caps.includes("p") ? vk : 0,
                renderable: caps.includes("r") || caps.includes("d"),
                uint: /uint$/.test(gpu), sint: /sint$/.test(gpu),
                hasDepth: /^depth/.test(gpu), hasStencil: /stencil/.test(gpu) };
        }

        createTexture(b) {
            const [id, vkformat, type, width, height, depth, mips, layers, samples, usage, flags] = b;
            const f = this.format(vkformat);
            if (!f) {
                this.warn("format" + vkformat, "images of VkFormat " + vkformat + " are not done");
                return;
            }
            let gpu_usage = TEXTURE.COPY_SRC | TEXTURE.COPY_DST | TEXTURE.TEXTURE_BINDING;
            // (render passes do clears, blits and resolves)
            if (f.renderable) gpu_usage |= TEXTURE.RENDER_ATTACHMENT;
            // (a format WebGPU cannot store to, sRGB: a mutable image's
            // storage views would be of its linear twin, which WebGPU's
            // textures cannot have; without storage, those views fail)
            if (usage & USAGE.STORAGE && f.caps.includes("s")) gpu_usage |= TEXTURE.STORAGE_BINDING;
            const volume = type === 2;
            const descriptor = {
                size: [width, volume ? height : Math.max(1, height), volume ? depth : layers],
                dimension: volume ? "3d" : "2d",
                format: f.gpu, mipLevelCount: mips, sampleCount: samples > 1 ? 4 : 1, usage: gpu_usage,
            };
            // VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT: its sRGB twin may view it
            if (flags & 0x8 && SRGB_TWIN[f.gpu]) descriptor.viewFormats = [SRGB_TWIN[f.gpu]];
            if (samples > 1) descriptor.usage &= ~TEXTURE.STORAGE_BINDING;
            const texture = this.device.createTexture(descriptor);
            this.objects.set(id, { kind: "texture", texture, vkformat, f, volume, width, height, depth, mips, layers, samples });
        }

        /**
         * An image bound to an imported virtio-gpu resource: it becomes the
         * texture of the resource's GX surface (same device), so Venus draws
         * into what virgl, the display and the guest's transfers see. The
         * image's own texture goes; GX keeps owning the surface's.
         */
        importTexture(b) {
            const [id, sid] = b;
            const image = this.objects.get(id);
            const surface = this.peer ? this.peer.surface(sid) : null;
            if (!image || image.kind !== "texture") return;
            if (!surface || !surface.texture) {
                this.warn("import" + sid, "resource " + sid + " has no GX texture to import");
                return;
            }
            const texture = surface.texture;
            if (texture.format !== image.f.gpu || texture.width !== image.width || texture.height !== Math.max(1, image.height) ||
                surface.ss[0] !== 1 || surface.ss[1] !== 1) {
                this.warn("import-mismatch" + sid, "resource " + sid + " (" + texture.format + " " + texture.width + "x" + texture.height +
                    ") does not match its image (" + image.f.gpu + " " + image.width + "x" + image.height + ")");
                return;
            }
            this.flushEncoder();
            const old = image.borrowed ? null : image.texture;
            // (in place: a restored state makes the image's views before
            // importing it again, and they are remade on the new texture)
            Object.assign(image, { texture, borrowed: true, mips: texture.mipLevelCount, layers: texture.depthOrArrayLayers });
            for (const v of this.objects.values()) {
                if (v.kind !== "view" || v.texture !== image) continue;
                v.view = this.view(texture, Object.assign({}, v.descriptor));
                v.attachment = v.storage = v.faces = v.swizzled = v.depthRead = null;
            }
            if (old) old.destroy();
        }

        texture(id) {
            const t = this.objects.get(id);
            return t && t.kind === "texture" ? t : null;
        }

        /**
         * A texture view; an sRGB view of a texture that has storage usage
         * leaves it out (a view has its texture's usage unless it says
         * otherwise, and sRGB formats cannot be stored to)
         */
        view(texture, descriptor) {
            if (texture.usage & TEXTURE.STORAGE_BINDING && /-srgb$/.test(descriptor.format)) {
                descriptor.usage = texture.usage & ~TEXTURE.STORAGE_BINDING;
            }
            return texture.createView(descriptor);
        }

        createView(b) {
            const [id, tid, type, vkformat, aspect, baseMip, mips, baseLayer, layers, ...components] = b;
            const t = this.texture(tid);
            if (!t) return;
            const f = this.format(vkformat) || t.f;
            const dimension = t.volume ? "3d" : VIEW_DIMENSION[type] || "2d";
            const only = aspect === ASPECT.DEPTH && t.f.hasStencil ? "depth-only" : aspect === ASPECT.STENCIL && t.f.hasDepth ? "stencil-only" : "all";
            const descriptor = {
                // (a view of one aspect has that aspect's format: depth24plus of depth24plus-stencil8, stencil8)
                format: only === "depth-only" ? f.gpu.replace(/-stencil8$/, "") : only === "stencil-only" ? "stencil8" : f.gpu, dimension,
                aspect: only,
                baseMipLevel: baseMip, mipLevelCount: mips,
                baseArrayLayer: t.volume ? 0 : baseLayer, arrayLayerCount: t.volume ? 1 : layers,
            };
            const view = this.view(t.texture, Object.assign({}, descriptor));
            // the view's swizzle (VkComponentMapping: identity 0, zero 1, one 2, r..a 3..6) as
            // codes 0 zero, 1 one, 2..5 r..a; none when it is the identity
            const codes = [0, 1, 2, 3].map(i => components[i] === 0 || components[i] === undefined ? i + 2 : components[i] - 1);
            const swizzle = codes.join() === "2,3,4,5" ? null : codes;
            this.objects.set(id, { kind: "view", view, descriptor, texture: t, f, aspect, baseMip, mips, baseLayer, layers, dimension, swizzle });
        }

        /** A write into a texture (a copy, a clear, a pass's attachment, a storage binding): its swizzled copies are old */
        touch(texture) {
            if (texture) texture.vxGeneration = (texture.vxGeneration || 0) + 1;
        }

        /**
         * The views a pipeline samples that WebGPU cannot bind as they are,
         * through copies: a view with a swizzle (WebGPU's views have none;
         * ANGLE's GL_ALPHA, GL_LUMINANCE and GL ES 3.0's texture swizzles are
         * VkComponentMappings), and a depth view sampled as a float texture
         * (GL's sampler2D of a depth texture; WebGPU binds depth as depth or
         * unfilterable float only): each one's copy made again where its
         * texture was written since (a pass of its own per mip and layer),
         * outside of any pass; true when one was
         */
        swizzleCopies(p, point) {
            const stale = [];
            for (const [group, used] of p.groups) {
                const contents = this.state.groups[point].get(group);
                if (!contents) continue;
                for (const [binding, kind] of used) {
                    if (group === p.push && binding === PUSH_BINDING || samplerBinding(binding) || !/^texture/.test(kind) || kind === "storage-texture") continue;
                    const d = contents.descriptors.get(descriptorKey(binding));
                    const v = d && this.objects.get(d.rid);
                    if (!v || v.kind !== "view") continue;
                    const mode = copyMode(v, kind);
                    if (!mode) {
                        if (v.swizzle && (v.f.depth || v.texture.samples > 1)) this.warn("swizzle-kind", "swizzles of depth, stencil and multisampled views are not done");
                        continue;
                    }
                    const generation = v.texture.borrowed ? NaN : v.texture.texture.vxGeneration || 0;
                    if (!v[mode] || v[mode].generation !== generation) stale.push([v, generation, mode]);
                }
            }
            if (!stale.length) return false;
            const resume = !!this.pass;
            this.endPass();
            for (const [v, generation, mode] of stale) this.swizzleCopy(v, generation, mode);
            if (resume) this.resumePass();
            return true;
        }

        /** a view's copy (`mode`: copyMode's), drawn again: v[mode].view is the one bound */
        swizzleCopy(v, generation, mode) {
            const t = v.texture, f = v.f, depth = mode === "depthRead";
            const type = f.uint ? "u32" : f.sint ? "i32" : "f32";
            // (a copy of four components, of the view's kind and at least its precision; depth's in its
            // red, 32-bit where the device filters them)
            const view = v.descriptor.format, wide = this.device.features.has("float32-filterable");
            const format = depth ? (v.swizzle ? "rgba" : "r") + (wide ? "32float" : "16float") : f.uint ? "rgba32uint" : f.sint ? "rgba32sint" :
                /^(r|rg|rgba|bgra)8unorm-srgb$/.test(view) ? "rgba8unorm-srgb" : /^(r|rg|rgba|bgra)8unorm$/.test(view) ? "rgba8unorm" :
                /32float/.test(view) ? "rgba32float" : "rgba16float";
            if (depth && !wide) this.warn("depth-read16", "depth read as a float texture at 16 bits (the device filters no 32-bit floats)");
            const volume = t.volume, slices = m => volume ? Math.max(1, t.depth >> (v.baseMip + m)) : v.layers;
            if (!v[mode] || !v[mode].texture) {
                const texture = this.device.createTexture({ size: [Math.max(1, t.width >> v.baseMip), Math.max(1, Math.max(1, t.height) >> v.baseMip),
                    volume ? Math.max(1, t.depth >> v.baseMip) : v.layers], dimension: volume ? "3d" : "2d", format, mipLevelCount: v.mips,
                    usage: TEXTURE.TEXTURE_BINDING | TEXTURE.RENDER_ATTACHMENT });
                v[mode] = { texture, view: texture.createView({ dimension: v.dimension, format }) };
                // (bind groups made before bound the view itself)
                this.swizzleEpoch = (this.swizzleEpoch || 0) + 1;
            }
            const key = "swizzle:" + format + ":" + type + (volume ? ":3d" : "") + (depth ? ":depth" : "");
            let pipeline = this.pipelines.get(key);
            if (!pipeline) {
                const texel = depth ? "    let c = vec4f(textureLoad(source, vec2i(at.xy), i32(s.layer), i32(s.mip)), 0.0, 0.0, 1.0);" :
                    volume ? "    let c = textureLoad(source, vec3i(vec2i(at.xy), i32(s.layer)), i32(s.mip));" :
                        "    let c = textureLoad(source, vec2i(at.xy), i32(s.layer), i32(s.mip));";
                const code = [
                    "struct S { swizzle: vec4u, mip: u32, layer: u32 };",
                    "@group(0) @binding(0) var<uniform> s: S;",
                    "@group(0) @binding(1) var source: " + (depth ? "texture_depth_2d_array;" : (volume ? "texture_3d<" : "texture_2d_array<") + type + ">;"),
                    "@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {",
                    "    return vec4f(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);",
                    "}",
                    "fn pick(c: vec4<" + type + ">, k: u32) -> " + type + " {",
                    "    switch k { case 0u: { return " + type + "(0); } case 1u: { return " + type + "(1); } case 2u: { return c.x; }",
                    "        case 3u: { return c.y; } case 4u: { return c.z; } default: { return c.w; } }",
                    "}",
                    "@fragment fn fs(@builtin(position) at: vec4f) -> @location(0) vec4<" + type + "> {",
                    texel,
                    "    return vec4<" + type + ">(pick(c, s.swizzle.x), pick(c, s.swizzle.y), pick(c, s.swizzle.z), pick(c, s.swizzle.w));",
                    "}",
                ].join("\n");
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [{ format }] }, primitive: { topology: "triangle-list" } });
                this.pipelines.set(key, pipeline);
            }
            const source = depth ? t.texture.createView({ dimension: "2d-array", aspect: "depth-only", format: v.descriptor.format }) :
                t.texture.createView({ dimension: volume ? "3d" : "2d-array", format: v.descriptor.format });
            const encoder = this.encoder();
            for (let m = 0; m < v.mips; m++) {
                for (let l = 0; l < slices(m); l++) {
                    const ubo = this.device.createBuffer({ size: 32, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
                    this.device.queue.writeBuffer(ubo, 0, Uint32Array.from([...v.swizzle || [2, 3, 4, 5], v.baseMip + m, volume ? l : v.baseLayer + l, 0, 0]));
                    this.transient.push(ubo);
                    const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                        { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: source }] });
                    const target = { view: v[mode].texture.createView({ dimension: volume ? "3d" : "2d", baseMipLevel: m, mipLevelCount: 1,
                        baseArrayLayer: volume ? 0 : l, arrayLayerCount: 1 }), loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 0] };
                    if (volume) target.depthSlice = l;
                    const pass = encoder.beginRenderPass({ colorAttachments: [target] });
                    pass.setPipeline(pipeline);
                    pass.setBindGroup(0, group);
                    pass.draw(3);
                    pass.end();
                }
            }
            v[mode].generation = generation;
            this.stats.swizzleCopies = (this.stats.swizzleCopies || 0) + 1;
        }

        createSampler(b) {
            const [id, mag, min, mipmap, u, v, w, bias, anisotropy, compare, compareOp, minLod, maxLod] = b;
            const linear = mag === 1 && min === 1 && mipmap === 1;
            const descriptor = {
                magFilter: mag === 1 ? "linear" : "nearest", minFilter: min === 1 ? "linear" : "nearest",
                mipmapFilter: mipmap === 1 ? "linear" : "nearest",
                addressModeU: ADDRESS[u] || "repeat", addressModeV: ADDRESS[v] || "repeat", addressModeW: ADDRESS[w] || "repeat",
                lodMinClamp: Math.max(0, f32(minLod)), lodMaxClamp: Math.max(Math.max(0, f32(minLod)), Math.min(32, f32(maxLod))),
                maxAnisotropy: linear ? Math.max(1, Math.min(16, Math.floor(f32(anisotropy)))) : 1,
            };
            if (compare) descriptor.compare = COMPARE[compareOp] || "always";
            if (f32(bias)) this.warn("lod-bias", "samplers' LOD bias is not done");
            if (u === 3 || v === 3 || w === 3) this.warn("border", "clamp to border is clamp to edge");
            // (its address modes, for integer images' samples: vx_naga's int_wraps)
            this.objects.set(id, { kind: "sampler", sampler: this.device.createSampler(descriptor), wrap: (u & 15) | (v & 15) << 4 | (w & 15) << 8 });
        }

        /** The aspect a copy names, and the bytes of its texels */
        copyAspect(t, aspect) {
            if (aspect === ASPECT.STENCIL) return { aspect: "stencil-only", bytes: 1, gpu: 1 };
            if (aspect === ASPECT.DEPTH) {
                if (t.f.gpu === "depth24plus" || t.f.gpu === "depth24plus-stencil8") return null;
                const bytes = t.f.gpu === "depth16unorm" ? 2 : 4;
                return { aspect: t.f.hasStencil ? "depth-only" : "all", bytes, gpu: bytes };
            }
            // (16-bit packed texels: the texture's are rgba8unorm, `gpu` bytes)
            return { aspect: "all", bytes: t.f.bytes, gpu: t.f.packed ? 4 : t.f.bytes };
        }

        /**
         * Depth from a memory (4 bytes a texel: a float, or 24-bit depth in
         * the low bits) into an image, which WebGPU copies only into
         * depth16unorm: a draw over the region writing frag_depth, a layer at
         * a time; and 24-bit depth out of an image, which WebGPU copies out of
         * no buffer: a dispatch reading it into the memory
         */
        depthByShader(toImage, m, guest, t, mip, layer, layers, x, y, w, h) {
            const d24 = /^depth24/.test(t.f.gpu) ? 1 : 0;
            const key = "depth-" + (toImage ? "up:" + t.f.gpu : "down");
            let pipeline = this.pipelines.get(key);
            if (!pipeline) {
                const common = [
                    "struct P { offset: u32, pitch: u32, x: u32, y: u32, w: u32, h: u32, d24: u32, layer: u32 };",
                    "@group(0) @binding(0) var<uniform> p: P;",
                ];
                const code = toImage ? [...common,
                    "@group(0) @binding(1) var<storage, read> src: array<u32>;",
                    "@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {",
                    "    return vec4f(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);",
                    "}",
                    "@fragment fn fs(@builtin(position) at: vec4f) -> @builtin(frag_depth) f32 {",
                    "    let word = src[(p.offset + (u32(at.y) - p.y) * p.pitch + (u32(at.x) - p.x) * 4u) >> 2u];",
                    "    return select(bitcast<f32>(word), f32(word & 0xFFFFFFu) / 16777215.0, p.d24 == 1u);",
                    "}",
                ] : [...common,
                    "@group(0) @binding(1) var source: texture_depth_2d_array;",
                    "@group(0) @binding(2) var<storage, read_write> dst: array<u32>;",
                    "@compute @workgroup_size(8, 8) fn main(@builtin(global_invocation_id) id: vec3<u32>) {",
                    "    if (id.x >= p.w || id.y >= p.h) { return; }",
                    "    let depth = textureLoad(source, vec2u(p.x + id.x, p.y + id.y), p.layer, 0);",
                    "    dst[(p.offset + id.y * p.pitch + id.x * 4u) >> 2u] = u32(round(clamp(depth, 0.0, 1.0) * 16777215.0));",
                    "}",
                ];
                const module = this.device.createShaderModule({ code: code.join("\n") });
                pipeline = toImage ? this.device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [] }, primitive: { topology: "triangle-list" },
                    depthStencil: { format: t.f.gpu, depthWriteEnabled: true, depthCompare: "always" } }) :
                    this.device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "main" } });
                this.pipelines.set(key, pipeline);
            }
            const encoder = this.encoder();
            for (let i = 0; i < layers; i++) {
                const ubo = this.device.createBuffer({ size: 32, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
                this.device.queue.writeBuffer(ubo, 0, Uint32Array.from([guest.offset + i * guest.image, guest.pitch, x, y, w, h, d24, layer + i]));
                this.transient.push(ubo);
                if (toImage) {
                    const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                        { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: m.buffer } }] });
                    const ds = { view: this.attachment(t, mip, layer + i), depthLoadOp: "load", depthStoreOp: "store" };
                    if (t.f.hasStencil) Object.assign(ds, { stencilLoadOp: "load", stencilStoreOp: "store" });
                    const pass = encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: ds });
                    pass.setPipeline(pipeline);
                    pass.setBindGroup(0, group);
                    pass.setViewport(x, y, w, h, 0, 1);
                    pass.setScissorRect(x, y, w, h);
                    pass.draw(3);
                    pass.end();
                }
                else {
                    const source = t.texture.createView({ dimension: "2d-array", aspect: "depth-only", baseMipLevel: mip, mipLevelCount: 1,
                        format: t.f.gpu.replace(/-stencil8$/, "") });
                    const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                        { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: source }, { binding: 2, resource: { buffer: m.buffer } }] });
                    const pass = encoder.beginComputePass();
                    pass.setPipeline(pipeline);
                    pass.setBindGroup(0, group);
                    pass.dispatchWorkgroups(Math.ceil(w / 8), Math.ceil(h / 8));
                    pass.end();
                }
            }
        }

        /**
         * A pass's depth and stencil resolved into its resolve view (sample
         * zero, the mode Venus offers; WebGPU resolves colors only): the depth
         * by a draw writing frag_depth from sample 0, the stencil cleared, then
         * written a bit at a time (a draw replacing through a write mask of the
         * bit, discarding where sample 0's bit is clear)
         */
        resolveDepthStencil(desc) {
            const v = this.attachmentOf(desc.view), r = this.attachmentOf(desc.resolve);
            if (!v || !r || v.texture.samples <= 1 || r.texture.samples > 1) return;
            const f = r.f, layer = { dimension: "2d", baseMipLevel: v.baseMip, mipLevelCount: 1, baseArrayLayer: v.texture.volume ? 0 : v.baseLayer, arrayLayerCount: 1 };
            const encoder = this.encoder();
            const vs = "@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {\n" +
                "    return vec4f(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);\n}\n";
            const ds = { view: r.attachment };
            if (f.hasDepth) Object.assign(ds, { depthLoadOp: "load", depthStoreOp: "store" });
            if (f.hasStencil) Object.assign(ds, { stencilLoadOp: "load", stencilStoreOp: "store" });
            if (desc.resolve_depth && f.hasDepth && v.f.hasDepth) {
                const key = "resolve-depth:" + f.gpu;
                let pipeline = this.pipelines.get(key);
                if (!pipeline) {
                    const module = this.device.createShaderModule({ code: vs + "@group(0) @binding(0) var source: texture_depth_multisampled_2d;\n" +
                        "@fragment fn fs(@builtin(position) at: vec4f) -> @builtin(frag_depth) f32 { return textureLoad(source, vec2i(at.xy), 0); }\n" });
                    pipeline = this.device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs" },
                        fragment: { module, entryPoint: "fs", targets: [] }, primitive: { topology: "triangle-list" },
                        depthStencil: { format: f.gpu, depthWriteEnabled: true, depthCompare: "always" } });
                    this.pipelines.set(key, pipeline);
                }
                const source = v.texture.texture.createView(Object.assign({ aspect: "depth-only", format: v.f.gpu.replace(/-stencil8$/, "") }, layer));
                const pass = encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: ds });
                pass.setPipeline(pipeline);
                pass.setBindGroup(0, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: source }] }));
                pass.draw(3);
                pass.end();
            }
            if (desc.resolve_stencil && f.hasStencil && v.f.hasStencil) {
                const source = v.texture.texture.createView(Object.assign({ aspect: "stencil-only", format: "stencil8" }, layer));
                const pass = encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: Object.assign({}, ds,
                    { stencilLoadOp: "clear", stencilClearValue: 0 }) });
                pass.setStencilReference(0xFF);
                for (let bit = 0; bit < 8; bit++) {
                    const key = "resolve-stencil:" + f.gpu + ":" + bit;
                    let pipeline = this.pipelines.get(key);
                    if (!pipeline) {
                        const module = this.device.createShaderModule({ code: vs + "@group(0) @binding(0) var source: texture_multisampled_2d<u32>;\n" +
                            "@fragment fn fs(@builtin(position) at: vec4f) {\n" +
                            "    if ((textureLoad(source, vec2i(at.xy), 0).x & " + (1 << bit) + "u) == 0u) { discard; }\n}\n" });
                        const face = { compare: "always", passOp: "replace", failOp: "keep", depthFailOp: "keep" };
                        pipeline = this.device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs" },
                            fragment: { module, entryPoint: "fs", targets: [] }, primitive: { topology: "triangle-list" },
                            depthStencil: { format: f.gpu, depthWriteEnabled: false, depthCompare: "always", stencilFront: face, stencilBack: face,
                                stencilWriteMask: 1 << bit } });
                        this.pipelines.set(key, pipeline);
                    }
                    pass.setPipeline(pipeline);
                    pass.setBindGroup(0, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: source }] }));
                    pass.draw(3);
                }
                pass.end();
            }
            this.touch(r.texture.texture);
        }

        /**
         * A copy between a memory and part of a depth or stencil aspect
         * (`a`, copyAspect's), which WebGPU copies only whole: the whole
         * subresource through a buffer, the region repacked in it
         */
        copyPartialAspect(toImage, m, guest, t, a, mip, layer, layers, x, y, w, h) {
            const W = Math.max(1, t.width >> mip), H = Math.max(1, Math.max(1, t.height) >> mip), aligned = align(W * a.bytes, 256);
            const staging = this.scratch(aligned * H * layers, BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.STORAGE);
            const whole = { texture: t.texture, mipLevel: mip, origin: [0, 0, layer], aspect: a.aspect };
            const layout = { buffer: staging, offset: 0, bytesPerRow: aligned, rowsPerImage: H };
            const ours = { offset: y * aligned + x * a.bytes, pitch: aligned, image: aligned * H };
            this.encoder().copyTextureToBuffer(whole, layout, [W, H, layers]);
            if (toImage) {
                this.repack(m.buffer, guest, staging, ours, w * a.bytes, h, layers);
                this.encoder().copyBufferToTexture(layout, whole, [W, H, layers]);
            }
            else this.repack(staging, ours, m.buffer, guest, w * a.bytes, h, layers);
        }

        /**
         * A copy between images of depth or stencil that is not of whole
         * subresources: stencil (and 16-bit depth) through buffers, other
         * depth by a draw writing frag_depth from the source's texels
         */
        copyPartialDepthStencil(s, sa, smip, slayer, sx, sy, t, da, dmip, dlayer, dx, dy, w, h, layers) {
            const as = this.copyAspect(s, sa), at = this.copyAspect(t, da);
            if (as && at && (sa === ASPECT.STENCIL || s.f.gpu === "depth16unorm" && t.f.gpu === "depth16unorm")) {
                const SW = Math.max(1, s.width >> smip), SH = Math.max(1, Math.max(1, s.height) >> smip), sAligned = align(SW * as.bytes, 256);
                const staging = this.scratch(sAligned * SH * layers, BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.STORAGE);
                this.encoder().copyTextureToBuffer({ texture: s.texture, mipLevel: smip, origin: [0, 0, slayer], aspect: as.aspect },
                    { buffer: staging, offset: 0, bytesPerRow: sAligned, rowsPerImage: SH }, [SW, SH, layers]);
                const m = { buffer: staging };
                return this.copyPartialAspect(true, m, { offset: sy * sAligned + sx * as.bytes, pitch: sAligned, image: sAligned * SH }, t, at,
                    dmip, dlayer, layers, dx, dy, w, h);
            }
            if (sa !== ASPECT.DEPTH || da !== ASPECT.DEPTH) {
                this.warn("copy-depth-partial", "partial copies between these depth and stencil images are not done");
                return;
            }
            const key = "depth-copy:" + t.f.gpu;
            let pipeline = this.pipelines.get(key);
            if (!pipeline) {
                const code = [
                    "struct P { dx: i32, dy: i32, sx: i32, sy: i32, layer: u32, mip: u32 };",
                    "@group(0) @binding(0) var<uniform> p: P;",
                    "@group(0) @binding(1) var source: texture_depth_2d_array;",
                    "@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {",
                    "    return vec4f(f32(i & 1u) * 4.0 - 1.0, f32(i >> 1u) * 4.0 - 1.0, 0.0, 1.0);",
                    "}",
                    "@fragment fn fs(@builtin(position) at: vec4f) -> @builtin(frag_depth) f32 {",
                    "    return textureLoad(source, vec2i(at.xy) - vec2i(p.dx, p.dy) + vec2i(p.sx, p.sy), p.layer, p.mip);",
                    "}",
                ].join("\n");
                const module = this.device.createShaderModule({ code });
                pipeline = this.device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs" },
                    fragment: { module, entryPoint: "fs", targets: [] }, primitive: { topology: "triangle-list" },
                    depthStencil: { format: t.f.gpu, depthWriteEnabled: true, depthCompare: "always" } });
                this.pipelines.set(key, pipeline);
            }
            const source = s.texture.createView({ dimension: "2d-array", aspect: "depth-only", format: s.f.gpu.replace(/-stencil8$/, "") });
            const encoder = this.encoder();
            for (let i = 0; i < layers; i++) {
                const ubo = this.device.createBuffer({ size: 32, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
                this.device.queue.writeBuffer(ubo, 0, Int32Array.from([dx, dy, sx, sy, slayer + i, smip, 0, 0]));
                this.transient.push(ubo);
                const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
                    { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: source }] });
                const ds = { view: this.attachment(t, dmip, dlayer + i), depthLoadOp: "load", depthStoreOp: "store" };
                if (t.f.hasStencil) Object.assign(ds, { stencilLoadOp: "load", stencilStoreOp: "store" });
                const pass = encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: ds });
                pass.setPipeline(pipeline);
                pass.setBindGroup(0, group);
                pass.setViewport(dx, dy, w, h, 0, 1);
                pass.setScissorRect(dx, dy, w, h);
                pass.draw(3);
                pass.end();
            }
        }

        /**
         * A copy between a memory and an image of 16-bit packed texels
         * (R5G6B5, R5G5B5A1, A1R5G5B5: textures of rgba8unorm here): through
         * a staging buffer of WebGPU's pitch that a compute shader unpacks
         * into or packs from
         */
        copyPacked(m, guest, place, size, toImage, format) {
            const [w, h, slices] = size, aligned = align(w * 4, 256);
            const staging = this.scratch(aligned * h * slices, BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.STORAGE);
            const layout = { buffer: staging, offset: 0, bytesPerRow: aligned, rowsPerImage: h };
            const ours = { offset: 0, pitch: aligned, image: aligned * h };
            if (!this.packer) {
                const code = [
                    "struct P { src: u32, src_pitch: u32, src_image: u32, dst: u32, dst_pitch: u32, dst_image: u32, w: u32, h: u32, slices: u32, end: u32, format: u32, pack: u32 };",
                    "@group(0) @binding(0) var<uniform> p: P;",
                    "@group(0) @binding(1) var<storage, read> s: array<u32>;",
                    "@group(0) @binding(2) var<storage, read_write> d: array<u32>;",
                    "fn to8(x: u32, top: u32) -> u32 { return (x * 255u + top / 2u) / top; }",
                    "fn from8(x: u32, top: u32) -> u32 { return (x * top + 127u) / 255u; }",
                    "fn bits(v: u32, at: u32, n: u32) -> u32 { return (v >> at) & ((1u << n) - 1u); }",
                    "// (VkFormat 4 R5G6B5, 6 R5G5B5A1, 8 A1R5G5B5; rgba8 with red in the low byte)",
                    "fn unpack(v: u32) -> u32 {",
                    "    var c = vec4u(to8(bits(v, 10u, 5u), 31u), to8(bits(v, 5u, 5u), 31u), to8(bits(v, 0u, 5u), 31u), bits(v, 15u, 1u) * 255u);",
                    "    if (p.format == 4u) { c = vec4u(to8(bits(v, 11u, 5u), 31u), to8(bits(v, 5u, 6u), 63u), to8(bits(v, 0u, 5u), 31u), 255u); }",
                    "    if (p.format == 6u) { c = vec4u(to8(bits(v, 11u, 5u), 31u), to8(bits(v, 6u, 5u), 31u), to8(bits(v, 1u, 5u), 31u), bits(v, 0u, 1u) * 255u); }",
                    "    return c.x | (c.y << 8u) | (c.z << 16u) | (c.w << 24u);",
                    "}",
                    "fn pack(t: u32) -> u32 {",
                    "    let c = vec4u(bits(t, 0u, 8u), bits(t, 8u, 8u), bits(t, 16u, 8u), bits(t, 24u, 8u));",
                    "    let a = select(0u, 1u, c.w >= 128u);",
                    "    if (p.format == 4u) { return (from8(c.x, 31u) << 11u) | (from8(c.y, 63u) << 5u) | from8(c.z, 31u); }",
                    "    if (p.format == 6u) { return (from8(c.x, 31u) << 11u) | (from8(c.y, 31u) << 6u) | (from8(c.z, 31u) << 1u) | a; }",
                    "    return (a << 15u) | (from8(c.x, 31u) << 10u) | (from8(c.y, 31u) << 5u) | from8(c.z, 31u);",
                    "}",
                    "@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3<u32>, @builtin(num_workgroups) n: vec3<u32>) {",
                    "    let i = id.x + id.y * n.x * 64u;",
                    "    if (p.pack == 0u) {",
                    "        // a texel of the image from the memory's 16 bits",
                    "        if (i >= p.w * p.h * p.slices) { return; }",
                    "        let slice = i / (p.w * p.h); let row = (i % (p.w * p.h)) / p.w; let column = i % p.w;",
                    "        let at = p.src + slice * p.src_image + row * p.src_pitch + column * 2u;",
                    "        let v = bits(s[at >> 2u], (at & 3u) * 8u, 16u);",
                    "        d[(p.dst + slice * p.dst_image + row * p.dst_pitch + column * 4u) >> 2u] = unpack(v);",
                    "        return;",
                    "    }",
                    "    // a dword of the memory: its texels in the region packed, the rest kept",
                    "    let w = (p.dst >> 2u) + i;",
                    "    if (w * 4u >= p.end) { return; }",
                    "    var word = d[w];",
                    "    for (var k = 0u; k < 4u; k += 2u) {",
                    "        let at = w * 4u + k;",
                    "        if (at < p.dst || at >= p.end) { continue; }",
                    "        let rel = at - p.dst;",
                    "        let slice = rel / p.dst_image; let row = (rel % p.dst_image) / p.dst_pitch; let byte = (rel % p.dst_image) % p.dst_pitch;",
                    "        if (slice >= p.slices || row >= p.h || byte >= p.w * 2u) { continue; }",
                    "        let texel = s[(p.src + slice * p.src_image + row * p.src_pitch + byte * 2u) >> 2u];",
                    "        word = (word & ~(0xFFFFu << (k * 8u))) | (pack(texel) << (k * 8u));",
                    "    }",
                    "    d[w] = word;",
                    "}",
                ].join("\n");
                this.packer = this.device.createComputePipeline({ layout: "auto", compute: { module: this.device.createShaderModule({ code }), entryPoint: "main" } });
            }
            const run = (src, from, dst, to, pack) => {
                const end = to.offset + (slices - 1) * to.image + (h - 1) * to.pitch + w * (pack ? 2 : 4);
                const params = this.device.createBuffer({ size: 48, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
                this.device.queue.writeBuffer(params, 0, Uint32Array.from([from.offset, from.pitch, from.image, to.offset, to.pitch, to.image, w, h, slices, end,
                    format, pack ? 1 : 0]));
                this.transient.push(params);
                const group = this.device.createBindGroup({ layout: this.packer.getBindGroupLayout(0), entries: [
                    { binding: 0, resource: { buffer: params } }, { binding: 1, resource: { buffer: src } }, { binding: 2, resource: { buffer: dst } }] });
                const invocations = pack ? ((end + 3) >> 2) - (to.offset >> 2) : w * h * slices;
                const groups = Math.ceil(invocations / 64);
                const pass = this.encoder().beginComputePass();
                pass.setPipeline(this.packer);
                pass.setBindGroup(0, group);
                pass.dispatchWorkgroups(Math.min(groups, 65535), Math.ceil(groups / 65535));
                pass.end();
            };
            if (toImage) {
                run(m.buffer, guest, staging, ours, false);
                this.encoder().copyBufferToTexture(layout, place, size);
            }
            else {
                this.encoder().copyTextureToBuffer(place, layout, size);
                run(staging, ours, m.buffer, guest, true);
            }
        }

        /** a texture's image (one mip, one layer or slice, one aspect), for a snapshot: null where WebGPU cannot copy it (multisampled, 24-bit depth) */
        readTexture(b) {
            const [id, aspectMask, mip, layer, request] = b;
            const t = this.texture(id);
            // (24-bit depth, which WebGPU copies out of no texture: read by a dispatch, 4 bytes a texel)
            if (t && t.samples <= 1 && aspectMask === ASPECT.DEPTH && /^depth24/.test(t.f.gpu)) {
                const w = Math.max(1, t.width >> mip), h = Math.max(1, t.height >> mip);
                const out = this.device.createBuffer({ size: w * h * 4, usage: BUFFER.STORAGE | BUFFER.COPY_SRC });
                const target = this.device.createBuffer({ size: w * h * 4, usage: BUFFER.MAP_READ | BUFFER.COPY_DST });
                this.transient.push(out);
                this.depthByShader(false, { buffer: out }, { offset: 0, pitch: w * 4, image: w * h * 4 }, t, mip, layer, 1, 0, 0, w, h);
                this.encoder().copyBufferToBuffer(out, 0, target, 0, w * h * 4);
                this.flushEncoder();
                this.pending.push(target.mapAsync(1).then(() => {
                    const bytes = new Uint8Array(target.getMappedRange()).slice();
                    target.destroy();
                    this.respond(request, bytes);
                }, () => { target.destroy(); this.respond(request, null); }));
                return;
            }
            const a = t && t.samples <= 1 ? this.copyAspect(t, aspectMask) : null;
            if (!a) return this.respond(request, null);
            const w = Math.max(1, t.width >> mip), h = Math.max(1, t.height >> mip);
            // (the texture's texels: rgba8unorm ones of 16-bit packed formats)
            const rowBytes = w * a.gpu, aligned = align(rowBytes, 256);
            const target = this.device.createBuffer({ size: aligned * h, usage: BUFFER.MAP_READ | BUFFER.COPY_DST });
            this.encoder().copyTextureToBuffer({ texture: t.texture, mipLevel: mip, origin: [0, 0, layer], aspect: a.aspect },
                { buffer: target, bytesPerRow: aligned, rowsPerImage: h }, [w, h, 1]);
            this.flushEncoder();
            this.pending.push(target.mapAsync(1).then(() => {
                const all = new Uint8Array(target.getMappedRange()), out = new Uint8Array(rowBytes * h);
                for (let r = 0; r < h; r++) out.set(all.subarray(r * aligned, r * aligned + rowBytes), r * rowBytes);
                target.destroy();
                this.respond(request, out);
            }, () => { target.destroy(); this.respond(request, null); }));
        }

        /** a snapshot's image back into its texture (depth WebGPU writes no buffer into: by a draw, depthByShader) */
        writeTexture(b) {
            const [id, aspectMask, mip, layer, length] = b;
            const t = this.texture(id);
            if (!t || t.samples > 1) return;
            this.touch(t.texture);
            if (aspectMask === ASPECT.DEPTH && t.f.hasDepth && t.f.gpu !== "depth16unorm") {
                const w = Math.max(1, t.width >> mip), h = Math.max(1, t.height >> mip);
                if (length < w * h * 4) return;
                const staged = this.device.createBuffer({ size: w * h * 4, usage: BUFFER.STORAGE | BUFFER.COPY_DST });
                this.transient.push(staged);
                this.device.queue.writeBuffer(staged, 0, new Uint8Array(b.buffer, b.byteOffset + 20, w * h * 4));
                this.depthByShader(true, { buffer: staged }, { offset: 0, pitch: w * 4, image: w * h * 4 }, t, mip, layer, 1, 0, 0, w, h);
                return;
            }
            const a = this.copyAspect(t, aspectMask);
            if (!a) return;
            const w = Math.max(1, t.width >> mip), h = Math.max(1, t.height >> mip);
            if (length < w * h * a.gpu) return;
            this.flushEncoder();
            this.device.queue.writeTexture({ texture: t.texture, mipLevel: mip, origin: [0, 0, layer], aspect: a.aspect },
                new Uint8Array(b.buffer, b.byteOffset + 20, length), { bytesPerRow: w * a.gpu, rowsPerImage: h }, [w, h, 1]);
        }

        copyBufferImage(b) {
            const [toImage, mid, low, high, rowLength, imageHeight, tid, aspectMask, mip, layer, layers, x, y, z, w, h, d] = b;
            const m = this.memory(mid), t = this.texture(tid);
            if (!m || !t || !w || !h || !d) return;
            if (toImage) this.touch(t.texture);
            // (depth WebGPU copies no buffer into, or 24-bit depth out of: by a draw, a dispatch)
            if (aspectMask === ASPECT.DEPTH && t.f.hasDepth && t.f.gpu !== "depth16unorm" && t.samples <= 1 && (toImage || /^depth24/.test(t.f.gpu))) {
                const offset = low + high * 0x100000000, pitch = (rowLength || w) * 4, rows = imageHeight || h;
                return this.depthByShader(toImage, m, { offset, pitch, image: pitch * rows }, t, mip, layer, layers, x, y, w, h);
            }
            const a = this.copyAspect(t, aspectMask);
            if (!a) {
                this.warn("copy-d24", "copies of 24-bit depth are not done");
                return;
            }
            const offset = low + high * 0x100000000;
            const pitch = (rowLength || w) * a.bytes, rows = imageHeight || h;
            const slices = t.volume ? d : layers;
            const rowBytes = w * a.bytes, aligned = align(rowBytes, 256);
            const place = { texture: t.texture, mipLevel: mip, origin: [x, y, t.volume ? z : layer], aspect: a.aspect };
            const size = [w, h, slices];
            if (t.f.packed && a.aspect === "all") return this.copyPacked(m, { offset, pitch, image: pitch * rows }, place, size, toImage, t.f.packed);
            // (depth and stencil: WebGPU copies only whole subresources of them)
            if (t.f.depth && (x || y || w !== Math.max(1, t.width >> mip) || h !== Math.max(1, Math.max(1, t.height) >> mip))) {
                return this.copyPartialAspect(toImage, m, { offset, pitch, image: pitch * rows }, t, a, mip, layer, slices, x, y, w, h);
            }
            const encoder = this.encoder();
            if (pitch % 256 === 0 && offset % 4 === 0) {
                const layout = { buffer: m.buffer, offset, bytesPerRow: pitch, rowsPerImage: rows };
                if (toImage) encoder.copyBufferToTexture(layout, place, size);
                else encoder.copyTextureToBuffer(place, layout, size);
                return;
            }
            if ((offset | pitch | rowBytes | pitch * rows) & 3) {
                // (rows not in whole dwords: repacked by a compute shader to and from WebGPU's pitch)
                const staging = this.scratch(aligned * h * slices, BUFFER.COPY_SRC | BUFFER.COPY_DST | BUFFER.STORAGE);
                const layout = { buffer: staging, offset: 0, bytesPerRow: aligned, rowsPerImage: h };
                const guest = { offset, pitch, image: pitch * rows }, ours = { offset: 0, pitch: aligned, image: aligned * h };
                if (toImage) {
                    this.repack(m.buffer, guest, staging, ours, rowBytes, h, slices);
                    this.encoder().copyBufferToTexture(layout, place, size);
                }
                else {
                    this.encoder().copyTextureToBuffer(place, layout, size);
                    this.repack(staging, ours, m.buffer, guest, rowBytes, h, slices);
                }
                return;
            }
            // row by row through a staging buffer of WebGPU's pitch
            const staging = this.scratch(aligned * h * slices, BUFFER.COPY_SRC | BUFFER.COPY_DST);
            const layout = { buffer: staging, offset: 0, bytesPerRow: aligned, rowsPerImage: h };
            if (!toImage) encoder.copyTextureToBuffer(place, layout, size);
            for (let s = 0; s < slices; s++) {
                for (let r = 0; r < h; r++) {
                    const there = offset + s * pitch * rows + r * pitch, here = (s * h + r) * aligned;
                    if (toImage) encoder.copyBufferToBuffer(m.buffer, there, staging, here, rowBytes);
                    else encoder.copyBufferToBuffer(staging, here, m.buffer, there, rowBytes);
                }
            }
            if (toImage) encoder.copyBufferToTexture(layout, place, size);
        }

        copyImage(b) {
            const [sid, sa, smip, slayer, sx, sy, sz, did, da, dmip, dlayer, dx, dy, dz, w, h, d, layers] = b;
            const s = this.texture(sid), t = this.texture(did);
            if (!s || !t) return;
            this.touch(t.texture);
            // (depth and stencil: WebGPU copies whole subresources of all their aspects only)
            if (s.f.depth || t.f.depth) {
                const all = f => (f.hasDepth ? ASPECT.DEPTH : 0) | (f.hasStencil ? ASPECT.STENCIL : 0);
                const full = (f, mip, x0, y0) => !x0 && !y0 && w === Math.max(1, f.width >> mip) && h === Math.max(1, Math.max(1, f.height) >> mip);
                if (s.f.gpu === t.f.gpu && sa === all(s.f) && da === sa && full(s, smip, sx, sy) && full(t, dmip, dx, dy) && s.samples === t.samples) {
                    this.encoder().copyTextureToTexture({ texture: s.texture, mipLevel: smip, origin: [0, 0, slayer] },
                        { texture: t.texture, mipLevel: dmip, origin: [0, 0, dlayer] }, [w, h, layers]);
                    return;
                }
                for (const aspect of [ASPECT.DEPTH, ASPECT.STENCIL]) {
                    if (sa & aspect) this.copyPartialDepthStencil(s, aspect, smip, slayer, sx, sy, t, aspect, dmip, dlayer, dx, dy, w, h, layers);
                }
                return;
            }
            const as = this.copyAspect(s, sa), at = this.copyAspect(t, da);
            if (!as || !at) {
                this.warn("copy-d24", "copies of 24-bit depth are not done");
                return;
            }
            const size = [w, h, s.volume ? d : layers];
            const from = { texture: s.texture, mipLevel: smip, origin: [sx, sy, s.volume ? sz : slayer], aspect: as.aspect };
            const to = { texture: t.texture, mipLevel: dmip, origin: [dx, dy, t.volume ? dz : dlayer], aspect: at.aspect };
            const base = f => f.gpu.replace("-srgb", "");
            if (!s.f.packed !== !t.f.packed) {
                this.warn("copy-packed", "copies between 16-bit packed images and others are not done");
                return;
            }
            if (base(s.f) === base(t.f)) {
                this.encoder().copyTextureToTexture(from, to, size);
                return;
            }
            // formats of the same size: through a buffer
            const aligned = align(w * as.bytes, 256);
            const staging = this.scratch(aligned * h * size[2], BUFFER.COPY_SRC | BUFFER.COPY_DST);
            const layout = { buffer: staging, offset: 0, bytesPerRow: aligned, rowsPerImage: h };
            this.encoder().copyTextureToBuffer(from, layout, size);
            this.encoder().copyBufferToTexture(layout, to, size);
        }

        /** A view of one mip and layer (or depth slice's layer: 0) for a render pass */
        attachment(t, mip, layer, format) {
            return this.view(t.texture, { format: format || t.f.gpu, dimension: t.volume ? "3d" : "2d", baseMipLevel: mip, mipLevelCount: 1,
                baseArrayLayer: t.volume ? 0 : layer, arrayLayerCount: 1 });
        }

        clearImage(b) {
            const [tid, aspect, baseMip, mips, baseLayer, layers, v0, v1, v2, v3] = b;
            const t = this.texture(tid);
            if (!t) return;
            this.touch(t.texture);
            const encoder = this.encoder();
            for (let mip = baseMip; mip < baseMip + mips; mip++) {
                const slices = t.volume ? Math.max(1, t.depth >> mip) : layers;
                for (let i = 0; i < slices; i++) {
                    const layer = t.volume ? 0 : baseLayer + i;
                    const view = this.attachment(t, mip, layer);
                    if (t.f.depth) {
                        const ds = { view };
                        if (t.f.hasDepth) Object.assign(ds, aspect & ASPECT.DEPTH ?
                            { depthLoadOp: "clear", depthClearValue: f32(v0), depthStoreOp: "store" } : { depthLoadOp: "load", depthStoreOp: "store" });
                        if (t.f.hasStencil) Object.assign(ds, aspect & ASPECT.STENCIL ?
                            { stencilLoadOp: "clear", stencilClearValue: v1, stencilStoreOp: "store" } : { stencilLoadOp: "load", stencilStoreOp: "store" });
                        encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: ds }).end();
                        continue;
                    }
                    if (!t.f.renderable) {
                        this.warn("clear-format" + t.vkformat, "clearing VkFormat " + t.vkformat + " (not renderable) is not done");
                        return;
                    }
                    const values = [v0, v1, v2, v3];
                    const clearValue = t.f.uint ? values.map(v => v >>> 0) : t.f.sint ? values.map(v => v | 0) : values.map(f32);
                    if (t.f.packed === R5G6B5) clearValue[3] = 1;
                    const attachment = { view, loadOp: "clear", storeOp: "store", clearValue: { r: clearValue[0], g: clearValue[1], b: clearValue[2], a: clearValue[3] } };
                    if (t.volume) attachment.depthSlice = i;
                    encoder.beginRenderPass({ colorAttachments: [attachment] }).end();
                }
            }
        }

        resolveImage(b) {
            const [sid, smip, slayer, sx, sy, did, dmip, dlayer, dx, dy, w, h, layers] = b;
            const s = this.texture(sid), t = this.texture(did);
            if (!s || !t) return;
            this.touch(t.texture);
            const sw = Math.max(1, s.width >> smip), sh = Math.max(1, s.height >> smip);
            const tw = Math.max(1, t.width >> dmip), th = Math.max(1, t.height >> dmip);
            // (a render pass resolves all of an attachment into one of its
            // size: a region, or an image of another size, is resolved whole
            // into a single-sample copy, and the region copied from there)
            const whole = !sx && !sy && !dx && !dy && w === sw && h === sh && tw === sw && th === sh;
            let single = null;
            if (!whole) {
                single = this.device.createTexture({ size: [sw, sh, 1], format: s.f.gpu, usage: TEXTURE.RENDER_ATTACHMENT | TEXTURE.COPY_SRC });
                this.transient.push(single);
            }
            for (let i = 0; i < layers; i++) {
                const resolveTarget = whole ? this.attachment(t, dmip, dlayer + i) : this.view(single, { dimension: "2d" });
                this.encoder().beginRenderPass({ colorAttachments: [{
                    view: this.attachment(s, smip, slayer + i), resolveTarget, loadOp: "load", storeOp: "store",
                }] }).end();
                if (!whole) {
                    this.encoder().copyTextureToTexture({ texture: single, mipLevel: 0, origin: [sx, sy, 0] },
                        { texture: t.texture, mipLevel: dmip, origin: [dx, dy, dlayer + i] }, [w, h, 1]);
                }
            }
        }

        /** The blit pipeline into a format: a quad sampling the source */
        /** a blit's pipeline into `format` from a texture of `kind` (f, u, i), a 3D one when `volume` (at the depth rect.w) */
        blitPipeline(format, kind, volume, mask = 0xF) {
            const key = format + ":" + kind + (volume ? ":3d" : "") + ":" + mask;
            let p = this.pipelines.get(key);
            if (p) return p;
            const type = kind === "u" ? "u32" : kind === "i" ? "i32" : "f32";
            const at = volume ? "vec3f(in.uv, rect.w)" : "in.uv";
            const code = [
                "struct Rect { dst: vec4f, src: vec4f, level: f32, w: f32 };",
                "@group(0) @binding(0) var<uniform> rect: Rect;",
                "@group(0) @binding(1) var source: texture_" + (volume ? "3d" : "2d") + "<" + type + ">;",
                kind === "f" ? "@group(0) @binding(2) var smp: sampler;" : "",
                "struct Out { @builtin(position) position: vec4f, @location(0) uv: vec2f };",
                "@vertex fn vs(@builtin(vertex_index) i: u32) -> Out {",
                "    let corner = vec2f(f32(i & 1u), f32(i >> 1u));",
                "    var out: Out;",
                "    let xy = mix(rect.dst.xy, rect.dst.zw, corner);",
                "    out.position = vec4f(xy.x * 2.0 - 1.0, 1.0 - xy.y * 2.0, 0.0, 1.0);",
                "    out.uv = mix(rect.src.xy, rect.src.zw, corner);",
                "    return out;",
                "}",
                "@fragment fn fs(in: Out) -> @location(0) vec4<" + type + "> {",
                kind === "f" ? "    return textureSampleLevel(source, smp, " + at + ", rect.level);" :
                    "    let size = " + (volume ? "vec3f" : "vec2f") + "(textureDimensions(source, u32(rect.level)));\n" +
                    "    return textureLoad(source, " + (volume ? "vec3i" : "vec2i") + "(floor(" + at + " * size)), i32(rect.level));",
                "}",
            ].join("\n");
            const module = this.device.createShaderModule({ code });
            p = this.device.createRenderPipeline({
                layout: "auto",
                vertex: { module, entryPoint: "vs" },
                fragment: { module, entryPoint: "fs", targets: [{ format, writeMask: mask }] },
                primitive: { topology: "triangle-strip" },
            });
            this.pipelines.set(key, p);
            return p;
        }

        blitImage(b) {
            const [sid, smip, slayer, sx0, sy0, sz0, sx1, sy1, sz1, did, dmip, dlayer, dx0, dy0, dz0, dx1, dy1, dz1, layers, linear] = b;
            const s = this.texture(sid), t = this.texture(did);
            if (!s || !t) return;
            this.touch(t.texture);
            // (Venus offers neither: VK_FORMAT_FEATURE_BLIT_DST_BIT is for the renderable color formats)
            if (t.f.depth || s.f.depth || !t.f.renderable) {
                this.warn("blit-kind", "blits of depth and into formats not renderable are not done");
                return;
            }
            const kind = s.f.uint ? "u" : s.f.sint ? "i" : "f";
            const pipeline = this.blitPipeline(t.f.gpu, kind, s.volume, alphaMask(t.f));
            const sw = Math.max(1, s.width >> smip), sh = Math.max(1, s.height >> smip);
            const tw = Math.max(1, t.width >> dmip), th = Math.max(1, t.height >> dmip);
            // the destination's corners in order, the source's following them (flips)
            const flipX = dx0 > dx1, flipY = dy0 > dy1;
            const rect = new Float32Array(12);
            rect.set([Math.min(dx0, dx1) / tw, Math.min(dy0, dy1) / th, Math.max(dx0, dx1) / tw, Math.max(dy0, dy1) / th,
                (flipX ? sx1 : sx0) / sw, (flipY ? sy1 : sy0) / sh, (flipX ? sx0 : sx1) / sw, (flipY ? sy0 : sy1) / sh, 0]);
            const uniform = this.staging(new Uint8Array(rect.buffer));
            const rects = this.scratch(48, BUFFER.UNIFORM | BUFFER.COPY_DST);
            const encoder = this.encoder();
            encoder.copyBufferToBuffer(uniform, 0, rects, 0, 48);
            const sampler = kind === "f" ? this.device.createSampler({ magFilter: linear ? "linear" : "nearest", minFilter: linear ? "linear" : "nearest" }) : null;
            // the slices: a 3D destination's of the blit's depths (each from the
            // source's depth its middle maps to, Vulkan's rule), else the layers
            const sd = Math.max(1, s.depth >> smip), td = Math.max(1, t.depth >> dmip);
            const slices = t.volume ? Math.abs(dz1 - dz0) : layers;
            const volumeSource = s.volume ? s.texture.createView({ dimension: "3d", baseMipLevel: smip, mipLevelCount: 1 }) : null;
            for (let i = 0; i < slices; i++) {
                const z = Math.min(dz0, dz1) + i;
                let ubo = rects;
                if (s.volume) {
                    const w = t.volume ? (sz0 + (z + 0.5 - dz0) * (sz1 - sz0) / (dz1 - dz0)) / sd : (sz0 + sz1) / 2 / sd;
                    rect[9] = w;
                    ubo = this.scratch(48, BUFFER.UNIFORM | BUFFER.COPY_DST);
                    encoder.copyBufferToBuffer(this.staging(new Uint8Array(rect.buffer)), 0, ubo, 0, 48);
                }
                const source = volumeSource || s.texture.createView({ dimension: "2d", baseMipLevel: smip, mipLevelCount: 1,
                    baseArrayLayer: slayer + (t.volume ? 0 : i), arrayLayerCount: 1 });
                const entries = [{ binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: source }];
                if (sampler) entries.push({ binding: 2, resource: sampler });
                const group = this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries });
                const target = { view: this.attachment(t, dmip, t.volume ? 0 : dlayer + i), loadOp: "load", storeOp: "store" };
                if (t.volume) {
                    if (z < 0 || z >= td) continue;
                    target.depthSlice = z;
                }
                const pass = encoder.beginRenderPass({ colorAttachments: [target] });
                pass.setPipeline(pipeline);
                pass.setBindGroup(0, group);
                pass.draw(4);
                pass.end();
            }
        }

        // ------------------------------------------------------------------
        // Shaders: SPIR-V to WGSL with naga (vx_naga.wasm)

        async loadNaga() {
            if (this.naga) return this.naga;
            const response = await fetch(this.nagaUrl);
            if (!response.ok) throw new Error("vx_naga.wasm: " + response.status);
            const { instance } = await WebAssembly.instantiate(await response.arrayBuffer(), {});
            this.naga = instance.exports;
            return this.naga;
        }

        /** a shader module's translation for a pipeline layout's push constant group */
        async translate(shader, push, storage = [], flags = 0) {
            await this.loadNaga();
            return this.translateNow(shader, push, flags, storage);
        }

        /**
         * The same, naga loaded; `flags` (TRANSLATE): Vulkan's clip space
         * kept (draws with a viewport of a negative height), the fragment
         * depth output dropped (a pipeline with no depth attachment), depth
         * reversed (a viewport's depths reversed): vertexVariant; `storage`:
         * the uniform buffers (group << 16 | binding) that are read-only
         * storage buffers in it (spilledUniforms)
         */
        translateNow(shader, push, flags, storage = [], wraps = []) {
            const key = String(push) + (flags ? ":f" + flags : "") + (storage.length ? ":" + storage.join(",") : "") +
                (wraps.length ? ":w" + wraps.flat().join(",") : "");
            let t = shader.translations.get(key);
            if (t) return t;
            const naga = this.naga;
            const input = naga.vx_alloc(shader.spirv.length);
            new Uint8Array(naga.memory.buffer, input, shader.spirv.length).set(shader.spirv);
            const list = storage.length ? naga.vx_alloc(storage.length * 4) : 0;
            if (list) new Uint32Array(naga.memory.buffer, list, storage.length).set(storage);
            // (integer images' samplers' address modes: pairs of the image's group << 16 | binding, the modes)
            const wrapList = wraps.length ? naga.vx_alloc(wraps.length * 8) : 0;
            if (wrapList) new Uint32Array(naga.memory.buffer, wrapList, wraps.length * 2).set(wraps.flat());
            let out;
            try {
                out = naga.vx_translate(input, shader.spirv.length, push, PUSH_BINDING, flags, list, storage.length, wrapList, wraps.length);
            } catch (error) {
                // (a panic: a fresh instance next time)
                this.naga = null;
                throw error;
            }
            naga.vx_free(input, shader.spirv.length);
            if (list) naga.vx_free(list, storage.length * 4);
            if (wrapList) naga.vx_free(wrapList, wraps.length * 8);
            const length = new DataView(naga.memory.buffer).getUint32(out, true);
            const text = new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length));
            naga.vx_free(out, length + 4);
            t = JSON.parse(text);
            // (derivatives in non-uniform control flow: SPIR-V allows them, WGSL by default not)
            if (!t.error) t.wgsl = "diagnostic(off, derivative_uniformity);\n" + t.wgsl;
            if (!t.error) t.module = this.device.createShaderModule({ code: t.wgsl });
            shader.translations.set(key, t);
            return t;
        }

        // ------------------------------------------------------------------
        // Pipelines

        stageState(t, stage) {
            const entry = t.entries.find(e => e.name === stage.entry) || t.entries[0];
            const constants = {};
            for (const [id, type] of t.overrides) {
                if (!(id in stage.constants)) continue;
                const v = stage.constants[id];
                constants[id] = type === "bool" ? (v ? 1 : 0) : type === "i32" ? v | 0 : type === "u32" ? v >>> 0 : f32(v);
            }
            return { module: t.module, entryPoint: entry ? entry.name : stage.entry, constants, entry };
        }

        /**
         * The uniform buffers a pipeline's stages make read-only storage
         * buffers: WebGPU has 12 uniform buffers a stage, the device reports
         * more (venus_device_info.js); in each stage with more, those after
         * its first 12 (by set and binding), the same in every stage that
         * has them (an automatic layout merges the stages' bindings)
         * @return {!Array<number>} set << 16 | binding, sorted
         */
        spilledUniforms(translations) {
            const spilled = new Set();
            for (const [t, stage] of translations) {
                const entry = t.entries.find(e => e.name === stage.entry) || t.entries[0];
                const uniforms = (entry ? entry.bindings : []).filter(b => b[2] === "uniform").map(([group, binding]) => group << 16 | binding)
                    .sort((a, b) => a - b);
                for (const key of uniforms.slice(MAX_UNIFORMS_PER_STAGE)) spilled.add(key);
            }
            return [...spilled].sort((a, b) => a - b);
        }

        async createPipeline(id, d) {
            const push = pushGroup(d.set_count);
            const p = { kind: "pipeline", desc: d, compute: d.kind === "compute", gpu: null, groups: new Map(), push,
                bindGroups: new Map(), error: null, storage: [] };
            this.objects.set(id, p);
            this.stats.pipelines++;
            try {
                const shaders = d.stages.map(stage => {
                    const shader = this.objects.get(stage.shader);
                    if (!shader) throw new Error("no shader " + stage.shader);
                    return shader;
                });
                // (a fragment shader writing depth with no depth attachment: its depth output dropped)
                const flagsOf = stage => stage.stage === 16 && !d.depth_format ? TRANSLATE.NO_DEPTH : 0;
                let translations = [];
                for (const [i, stage] of d.stages.entries()) translations.push([await this.translate(shaders[i], push, [], flagsOf(stage)), stage]);
                for (const [t] of translations) if (t.error) throw new Error("shader: " + t.error);
                // (more uniform buffers than a stage has: some are storage, every stage translated so)
                p.storage = this.spilledUniforms(translations);
                if (p.storage.length) {
                    this.stats.spilledUniforms = (this.stats.spilledUniforms || 0) + 1;
                    translations = [];
                    for (const [i, stage] of d.stages.entries()) translations.push([await this.translate(shaders[i], push, p.storage, flagsOf(stage)), stage]);
                    for (const [t] of translations) if (t.error) throw new Error("shader: " + t.error);
                }
                const stages = translations.map(([t, stage]) => [stage.stage, this.stageState(t, stage)]);
                // (integer images sampled: the draws' samplers' address modes, wrapVariant)
                p.intsamples = [...new Set(translations.flatMap(([t]) => t.intsamples || []))];
                p.stageSources = d.stages.map((stage, i) => ({ shader: shaders[i], stage, flags: flagsOf(stage) }));
                // the bindings the stages use, by group (and the buffers' least sizes)
                const sizes = new Map();
                this.bindingSizes.set(p.groups, sizes);
                for (const [, st] of stages) {
                    for (const [group, binding, kind, size] of st.entry ? st.entry.bindings : []) {
                        if (!p.groups.has(group)) p.groups.set(group, new Map());
                        p.groups.get(group).set(binding, kind);
                        if (size) sizes.set(group << 16 | binding, Math.max(size, sizes.get(group << 16 | binding) || 0));
                    }
                }
                const strip = s => ({ module: s.module, entryPoint: s.entryPoint, constants: s.constants });
                if (p.compute) {
                    p.gpu = await this.device.createComputePipelineAsync({ layout: "auto", compute: strip(stages[0][1]) });
                    p.workgroup = stages[0][1].entry ? stages[0][1].entry.workgroup : [1, 1, 1];
                    return;
                }
                const vertex = stages.find(([s]) => s === 1), fragment = stages.find(([s]) => s === 16);
                if (!vertex) throw new Error("no vertex stage");
                // (its shader again for the flipped variant)
                const vertex_stage = d.stages.find(stage => stage.stage === 1);
                p.vertexSource = { shader: this.objects.get(vertex_stage.shader), stage: vertex_stage };
                p.vertexLayout = this.vertexLayout(d);
                // (VK_BLEND_FACTOR_CONSTANT_ALPHA: WebGPU's constant is the color's for color; such a
                // pipeline's draws get the constant's alpha in all four, warned when it uses both)
                const colorFactors = d.targets.filter(x => x.blend).flatMap(x => [x.src_color, x.dst_color]);
                p.constantAlpha = colorFactors.some(f => f === 12 || f === 13);
                if (p.constantAlpha && colorFactors.some(f => f === 10 || f === 11)) this.warn("constant-alpha", "a pipeline blends with the constant's color and its alpha (not done)");
                // (flat varyings of a pipeline of GL's provoking vertex: its draws reordered, provokingLast)
                p.flat = !!(vertex[1].entry && vertex[1].entry.flat);
                const buffers = p.vertexLayout.native ? p.vertexLayout.buffers : p.vertexLayout.packed;
                // (triangle fans: lists, drawn through fanIndices)
                const topology = d.topology === 5 ? "triangle-list" : TOPOLOGY[d.topology];
                if (!topology) this.warn("topology" + d.topology, "topology " + d.topology + " is not done");
                const descriptor = {
                    layout: "auto",
                    vertex: Object.assign(strip(vertex[1]), { buffers }),
                    primitive: {
                        topology: topology || "triangle-list",
                        cullMode: d.cull === 1 ? "front" : d.cull === 2 ? "back" : "none",
                        frontFace: d.front ? "cw" : "ccw",
                    },
                    multisample: { count: d.samples > 1 ? 4 : 1, mask: d.sample_mask >>> 0, alphaToCoverageEnabled: d.alpha_to_coverage },
                };
                if (d.polygon) this.warn("polygon-mode", "polygon modes other than fill are fill");
                if (d.depth_format) {
                    const f = this.format(d.depth_format);
                    const z = d.depth || { test: false, write: false, compare: 7, stencil: false };
                    const face = s => s && z.stencil ? { compare: COMPARE[s.compare], failOp: STENCIL_OP[s.fail], depthFailOp: STENCIL_OP[s.depth_fail], passOp: STENCIL_OP[s.pass] } : {};
                    descriptor.depthStencil = {
                        format: f.gpu,
                        depthWriteEnabled: !!(z.test && z.write),
                        depthCompare: z.test ? COMPARE[z.compare] : "always",
                    };
                    if (f.hasStencil) Object.assign(descriptor.depthStencil, { stencilFront: face(z.front), stencilBack: face(z.back),
                        stencilReadMask: z.stencil && z.front ? z.front.read_mask : 0xFFFFFFFF, stencilWriteMask: z.stencil && z.front ? z.front.write_mask : 0 });
                    // (WebGPU biases triangles only)
                    if (d.depth_bias && d.topology >= 3) Object.assign(descriptor.depthStencil, { depthBias: Math.round(d.depth_bias.constant),
                        depthBiasSlopeScale: d.depth_bias.slope, depthBiasClamp: d.depth_bias.clamp });
                }
                const targets = d.targets.map(t => {
                    const f = this.format(t.format);
                    if (!f) return null;
                    const target = { format: f.gpu, writeMask: d.discard ? 0 : t.write_mask & alphaMask(f) };
                    // (min and max take no factors in Vulkan; WebGPU wants them one)
                    const component = (src, dst, op) => op === 3 || op === 4 ? { srcFactor: "one", dstFactor: "one", operation: BLEND_OP[op] } :
                        { srcFactor: BLEND_FACTOR[src], dstFactor: BLEND_FACTOR[dst], operation: BLEND_OP[op] };
                    if (t.blend && !f.int && !d.discard) target.blend = {
                        color: component(t.src_color, t.dst_color, t.color_op),
                        alpha: component(t.src_alpha, t.dst_alpha, t.alpha_op),
                    };
                    return target;
                });
                if (fragment && !d.discard) descriptor.fragment = Object.assign(strip(fragment[1]), { targets });
                else if (d.discard) {
                    // rasterizer discard: a fragment stage that writes nothing,
                    // for the pass's attachments, and no depth or stencil writes
                    descriptor.fragment = { module: this.emptyFragment(), entryPoint: "fs", targets };
                    if (descriptor.depthStencil) Object.assign(descriptor.depthStencil, { depthWriteEnabled: false, stencilWriteMask: 0 });
                }
                else {
                    // no fragment shader (a depth-only draw; Vulkan leaves the colors undefined): one that writes
                    // nothing, for the pass's attachments
                    descriptor.fragment = { module: this.emptyFragment(), entryPoint: "fs", targets: targets.map(t => t && { format: t.format, writeMask: 0 }) };
                }
                if (!descriptor.depthStencil && !(descriptor.fragment && descriptor.fragment.targets.some(t => t))) {
                    // no attachments (WebGPU needs one): the placeholder the pass gets too, single-sampled
                    descriptor.fragment = descriptor.fragment || { module: this.emptyFragment(), entryPoint: "fs", targets: [] };
                    descriptor.fragment.targets = [{ format: PLACEHOLDER_FORMAT, writeMask: 0 }];
                    descriptor.multisample.count = 1;
                }
                p.descriptor = descriptor;
                p.gpu = await this.device.createRenderPipelineAsync(descriptor);
            } catch (error) {
                p.error = String(error && error.message || error);
                this.warn("pipeline:" + p.error, "a pipeline failed: " + p.error);
            }
        }

        /** a fragment stage that writes nothing */
        emptyFragment() {
            if (!this.emptyFragmentModule) this.emptyFragmentModule = this.device.createShaderModule({ code: "@fragment fn fs() {}" });
            return this.emptyFragmentModule;
        }

        /** the attachment of a pass without any, by its size */
        placeholder(width, height) {
            const key = Math.max(1, width) + "x" + Math.max(1, height);
            if (!this.placeholders) this.placeholders = new Map();
            let view = this.placeholders.get(key);
            if (!view) {
                view = this.device.createTexture({ size: [Math.max(1, width), Math.max(1, height)], format: PLACEHOLDER_FORMAT,
                    usage: TEXTURE.RENDER_ATTACHMENT }).createView();
                this.placeholders.set(key, view);
            }
            return view;
        }

        // ------------------------------------------------------------------
        // Passes

        /** a view of one mip and layer, for an attachment */
        attachmentOf(id) {
            const v = this.objects.get(id);
            if (!v || v.kind !== "view") return null;
            if (!v.attachment) v.attachment = this.view(v.texture.texture, { format: v.f.gpu, dimension: v.texture.volume ? "3d" : "2d",
                baseMipLevel: v.baseMip, mipLevelCount: 1, baseArrayLayer: v.texture.volume ? 0 : v.baseLayer, arrayLayerCount: 1 });
            return v;
        }

        beginPass(d) {
            this.endPasses();
            // (a capture's compute pass ends it, and it begins again: resumePass)
            this.passDesc = d;
            const colorFormats = [];
            const colorAttachments = d.colors.map((c, i) => {
                if (!c) return null;
                const v = this.attachmentOf(c.view);
                if (!v) return null;
                const f = v.f;
                colorFormats[i] = f.gpu;
                const value = f.uint ? c.clear.map(x => x >>> 0) : f.sint ? c.clear.map(x => x | 0) : c.clear.map(f32);
                if (f.packed === R5G6B5) value[3] = 1;
                const a = { view: v.attachment, loadOp: c.load === 0 ? "load" : "clear", storeOp: c.store === 1 ? "discard" : "store",
                    clearValue: { r: value[0], g: value[1], b: value[2], a: value[3] } };
                const resolve = c.resolve ? this.attachmentOf(c.resolve) : null;
                if (resolve) a.resolveTarget = resolve.attachment;
                // (a slice of a 3D image: Vulkan's 2D view of it)
                if (v.texture.volume) a.depthSlice = v.baseLayer;
                return a;
            });
            const descriptor = { colorAttachments };
            if (!colorAttachments.some(a => a) && !(d.depth && this.attachmentOf(d.depth.view))) {
                // no attachments: the pipelines' placeholder (see createPipeline)
                colorAttachments.splice(0, colorAttachments.length, { view: this.placeholder(d.width, d.height), loadOp: "clear", storeOp: "discard" });
                colorFormats.splice(0, colorFormats.length, PLACEHOLDER_FORMAT);
            }
            let depthFormat = "";
            if (d.depth) {
                const v = this.attachmentOf(d.depth.view);
                if (v) {
                    depthFormat = v.texture.f.gpu;
                    const ds = { view: v.attachment };
                    if (v.texture.f.hasDepth) Object.assign(ds, { depthLoadOp: d.depth.load === 0 ? "load" : "clear", depthClearValue: d.depth.clear_depth,
                        depthStoreOp: d.depth.store === 1 && !d.depth.resolve ? "discard" : "store" });
                    if (v.texture.f.hasStencil) Object.assign(ds, { stencilLoadOp: d.depth.stencil_load === 0 ? "load" : "clear",
                        stencilClearValue: d.depth.clear_stencil, stencilStoreOp: d.depth.stencil_store === 1 && !d.depth.resolve ? "discard" : "store" });
                    descriptor.depthStencilAttachment = ds;
                }
            }
            const queries = d.occlusion ? this.objects.get(d.occlusion) : null;
            if (queries && queries.querySet) descriptor.occlusionQuerySet = queries.querySet;
            this.pass = this.encoder().beginRenderPass(descriptor);
            this.activeQuery = -1;
            const first = d.colors.find(c => c) || d.depth;
            const firstView = first && this.objects.get(first.view);
            this.passInfo = { colors: d.colors, depth: d.depth, samples: firstView && firstView.texture ? firstView.texture.samples : 1,
                occlusion: queries && queries.querySet ? d.occlusion : 0 };
            this.passAttachments = attachmentState(Array.from(colorFormats, f => f || null), depthFormat, this.passInfo.samples > 1 ? 4 : 1);
            // (the textures attached: a draw that samples one reads a copy, attachmentCopies)
            this.passTextures = new Set([...d.colors.flatMap(c => c ? [c.view, c.resolve] : []), d.depth && d.depth.view]
                .map(id => id && this.objects.get(id)).filter(v => v && v.kind === "view").map(v => v.texture.texture));
            this.state.passWidth = d.width;
            this.state.passHeight = d.height;
            this.state.pipelineApplied = false;
            this.state.vertexDirty = this.state.indexDirty = this.state.dynamicDirty = true;
            this.state.applied = new Map();
        }

        endPass() {
            if (this.pass) {
                this.pass.end();
                this.pass = null;
                this.resolveQueries();
                // (what it drew into: written)
                if (this.passTextures) for (const texture of this.passTextures) this.touch(texture);
            }
        }

        // ------------------------------------------------------------------
        // Descriptors

        setBindGroup(b) {
            const group = b[0] & 0xFFFF, point = b[0] >>> 16, count = b[1];
            const descriptors = new Map();
            for (let i = 0; i < count; i++) {
                const w = b.subarray(2 + i * 8, 10 + i * 8);
                descriptors.set(w[0] * 1024 + w[1], { type: w[2], rid: w[3], sampler: w[4], offset: w[5] + w[6] * 0x100000000, size: w[7] });
            }
            this.state.groups[point].set(group, { version: ++this.state.groupVersion, descriptors });
        }

        /** The buffers a compute pipeline's bind groups bind as writable storage */
        writableBuffers(p) {
            const writable = new Set();
            for (const [group, used] of p.groups) {
                const contents = this.state.groups[1].get(group);
                for (const [binding, kind] of used) {
                    const d = kind === "storage-rw" && contents && contents.descriptors.get(descriptorKey(binding));
                    const m = d && this.memory(d.rid);
                    if (m) writable.add(m.buffer);
                }
            }
            return writable;
        }

        /**
         * the bind group of a pipeline's group from what is bound there;
         * `writable`: buffers a dispatch writes, whose other bindings in it
         * become copies (WebGPU allows no other use of a buffer a dispatch
         * writes; Vulkan's bindings of one memory's other ranges may)
         */
        bindGroup(p, point, group, writable) {
            const used = p.groups.get(group);
            if (!used) return null;
            const isPush = group === p.push;
            const contents = this.state.groups[point].get(group);
            const aliased = writable && [...used].some(([binding, kind]) => {
                const d = (kind === "uniform" || kind === "storage") && contents && contents.descriptors.get(descriptorKey(binding));
                const m = d && this.memory(d.rid);
                return m && writable.has(m.buffer);
            });
            const key = (contents ? contents.version : 0) + (isPush ? ":" + this.state.pushOffset : "") + ":" + (this.swizzleEpoch || 0);
            let bg = p.bindGroups.get(group);
            const substituted = !!this.substitutes;
            if (bg && bg.key === key && !aliased && !substituted) return bg.group;
            const entries = [];
            const sizes = this.bindingSizes.get(p.groups);
            for (const [binding, kind] of used) {
                if (isPush && binding === PUSH_BINDING) {
                    entries.push({ binding, resource: { buffer: this.pushBuffer, offset: this.state.pushOffset, size: 256 } });
                    continue;
                }
                const d = contents && contents.descriptors.get(descriptorKey(binding));
                if (!d) { this.warn("unbound" + group + ":" + binding, "group " + group + " binding " + binding + " has nothing bound"); return null; }
                if (samplerBinding(binding) || kind === "sampler" || kind === "sampler-comparison") {
                    const s = this.objects.get(samplerBinding(binding) ? d.sampler : d.sampler || d.rid);
                    if (!s || !s.sampler) return null;
                    entries.push({ binding, resource: s.sampler });
                    continue;
                }
                if (kind === "uniform" || kind === "storage" || kind === "storage-rw") {
                    const m = this.memory(d.rid);
                    if (!m) return null;
                    let size = Math.min(d.size, m.buffer.size - d.offset);
                    // (a range smaller than the shader's block, as std140's padding at its end may leave it:
                    // Vulkan reads what the shader reads, WebGPU wants the whole block; the memory after it)
                    const least = sizes && sizes.get(group << 16 | binding) || 0;
                    if (size < least) {
                        if (m.buffer.size - d.offset >= least) size = least;
                        else this.warn("binding-size", "a buffer bound smaller than the shader's block, at the end of its memory (not done)");
                    }
                    if (aliased && kind !== "storage-rw" && writable.has(m.buffer)) {
                        // (what it binds as it is before the dispatch)
                        const copy = this.scratch(size, BUFFER.COPY_DST | BUFFER.UNIFORM | BUFFER.STORAGE);
                        this.encoder().copyBufferToBuffer(m.buffer, d.offset, copy, 0, align(size, 4));
                        entries.push({ binding, resource: { buffer: copy, offset: 0, size } });
                        continue;
                    }
                    entries.push({ binding, resource: { buffer: m.buffer, offset: d.offset, size } });
                    continue;
                }
                const v = this.objects.get(d.rid);
                if (!v || v.kind !== "view") return null;
                const copy = this.substitutes && this.substitutes.get(v);
                if (kind === "storage-texture") this.touch(v.texture.texture);
                const mode = copyMode(v, kind), swizzled = mode && v[mode] ? v[mode].view : null;
                // (a texture of the render pass this binds into, not copied: WebGPU would drop the batch)
                if (point === 0 && this.pass && !copy && !swizzled && this.passTextures && this.passTextures.has(v.texture.texture)) {
                    this.warn("feedback:" + group + ":" + binding + ":" + kind, "a draw samples a texture of its own pass, not copied (group " + group +
                        " binding " + binding + " " + kind + ", " + v.f.gpu + " " + v.texture.width + "x" + v.texture.height + ")");
                }
                entries.push({ binding, resource: copy || (kind === "storage-texture" ? this.singleMip(v) : /-faces$/.test(kind) ? this.facesView(v) :
                    swizzled || v.view) });
            }
            const created = this.device.createBindGroup({ layout: p.gpu.getBindGroupLayout(group), entries });
            if (!aliased && !substituted) p.bindGroups.set(group, { key, group: created });
            return created;
        }

        /** A cube view's faces as a 2D array (integer cubes, which vx_naga's cubes.rs loads from) */
        facesView(v) {
            if (v.dimension !== "cube") return v.view;
            if (!v.faces) v.faces = v.texture.texture.createView({ format: v.descriptor.format, dimension: "2d-array", baseMipLevel: v.baseMip, mipLevelCount: v.mips,
                baseArrayLayer: v.baseLayer, arrayLayerCount: 6 });
            return v.faces;
        }

        singleMip(v) {
            if (v.mips === 1) return v.view;
            if (!v.storage) v.storage = v.texture.texture.createView({ format: v.f.gpu, dimension: v.dimension, baseMipLevel: v.baseMip, mipLevelCount: 1,
                baseArrayLayer: v.baseLayer, arrayLayerCount: v.layers });
            return v.storage;
        }

        /**
         * A render pipeline whose vertex shader is another translation
         * (`flags`, TRANSLATE): for draws with a viewport of a negative height
         * (Vulkan flips y with it, ANGLE draws GL's frames so; WebGPU's
         * viewports cannot, so the vertex stage keeps Vulkan's clip space
         * instead of flipping into WebGPU's), and for a viewport whose depths
         * are reversed (z made w - z, the viewport's depths swapped). Made at
         * the first such draw; its own (automatic) layout, so its own bind
         * groups: WebGPU does not let another pipeline use an automatic
         * layout's bind group layouts.
         */
        vertexVariant(p, flags) {
            p.vertexVariants = p.vertexVariants || new Map();
            if (p.vertexVariants.has(flags)) return p.vertexVariants.get(flags);
            let v = null;
            try {
                const t = this.translateNow(p.vertexSource.shader, p.push, flags, p.storage);
                if (t.error) throw new Error("shader: " + t.error);
                const st = this.stageState(t, p.vertexSource.stage);
                const descriptor = Object.assign({}, p.descriptor, {
                    vertex: Object.assign({}, p.descriptor.vertex, { module: st.module, entryPoint: st.entryPoint, constants: st.constants }),
                });
                v = { kind: "pipeline", desc: p.desc, groups: p.groups, push: p.push, gpu: this.device.createRenderPipeline(descriptor), bindGroups: new Map(),
                    error: null, descriptor };
            } catch (error) {
                this.warn("vertex-variant:" + flags + ":" + error.message, "a pipeline's variant for flipped or reversed viewports failed: " + error.message);
            }
            p.vertexVariants.set(flags, v);
            return v;
        }

        /**
         * The address modes of the samplers bound with a pipeline's integer
         * images (their samples are fetches, vx_naga's intsample.rs), where
         * one is not clamp to edge: [group << 16 | binding, modes] pairs
         */
        intWraps(p, point) {
            if (!p.intsamples || !p.intsamples.length) return [];
            const wraps = [];
            for (const key of p.intsamples) {
                const contents = this.state.groups[point].get(key >>> 16);
                const d = contents && contents.descriptors.get(descriptorKey(key & 0xFFFF));
                const s = d && this.objects.get(d.sampler);
                if (s && s.kind === "sampler" && [0, 4, 8].some(shift => (s.wrap >> shift & 15) < 2)) wraps.push([key, s.wrap]);
            }
            return wraps;
        }

        /**
         * A render pipeline whose stages are translated again with integer
         * images' address modes (`wraps`, intWraps) and the vertex shader's
         * `flags` (vertexVariant's): made at the first draw with them, its own
         * bind groups (an automatic layout)
         */
        wrapVariant(p, flags, wraps) {
            p.wrapVariants = p.wrapVariants || new Map();
            const key = flags + ":" + wraps.flat().join(",");
            if (p.wrapVariants.has(key)) return p.wrapVariants.get(key);
            let v = null;
            try {
                const descriptor = Object.assign({}, p.descriptor);
                for (const { shader, stage, flags: own } of p.stageSources) {
                    const t = this.translateNow(shader, p.push, own | (stage.stage === 1 ? flags : 0), p.storage, wraps);
                    if (t.error) throw new Error("shader: " + t.error);
                    const st = this.stageState(t, stage);
                    const replaced = { module: st.module, entryPoint: st.entryPoint, constants: st.constants };
                    if (stage.stage === 1) descriptor.vertex = Object.assign({}, p.descriptor.vertex, replaced);
                    else if (stage.stage === 16 && p.descriptor.fragment && !p.desc.discard) descriptor.fragment = Object.assign({}, p.descriptor.fragment, replaced);
                }
                v = { kind: "pipeline", desc: p.desc, groups: p.groups, push: p.push, gpu: this.device.createRenderPipeline(descriptor), bindGroups: new Map(),
                    error: null, descriptor };
            } catch (error) {
                this.warn("wrap-variant:" + error.message, "a pipeline's variant for its integer images' address modes failed: " + error.message);
            }
            p.wrapVariants.set(key, v);
            return v;
        }

        /** wrapVariant's for a compute pipeline */
        wrapComputeVariant(p, wraps) {
            p.wrapVariants = p.wrapVariants || new Map();
            const key = wraps.flat().join(",");
            if (p.wrapVariants.has(key)) return p.wrapVariants.get(key);
            let v = null;
            try {
                const { shader, stage } = p.stageSources[0];
                const t = this.translateNow(shader, p.push, 0, p.storage, wraps);
                if (t.error) throw new Error("shader: " + t.error);
                const st = this.stageState(t, stage);
                v = { kind: "pipeline", desc: p.desc, groups: p.groups, push: p.push, bindGroups: new Map(), error: null,
                    gpu: this.device.createComputePipeline({ layout: "auto", compute: { module: st.module, entryPoint: st.entryPoint, constants: st.constants } }) };
            } catch (error) {
                this.warn("wrap-variant:" + error.message, "a pipeline's variant for its integer images' address modes failed: " + error.message);
            }
            p.wrapVariants.set(key, v);
            return v;
        }

        /**
         * A render pipeline with other stencil masks: the dynamic ones
         * (VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, _WRITE_MASK) of a draw, as
         * WebGPU's are the pipeline's. Made at the first draw with them; its
         * own bind groups (an automatic layout, as vertexVariant's)
         */
        maskedPipeline(q, read, write) {
            const ds = q.descriptor.depthStencil;
            if ((ds.stencilReadMask & 0xFF) === read && (ds.stencilWriteMask & 0xFF) === write) return q;
            return this.variant(q, "masks:" + read + ":" + write,
                d => Object.assign(d, { depthStencil: Object.assign({}, ds, { stencilReadMask: read, stencilWriteMask: write }) }));
        }

        /**
         * A render pipeline's variant by `key`, its descriptor as `change`
         * makes it of a copy of the pipeline's: made at the first draw that
         * needs it, with its own bind groups (an automatic layout)
         */
        variant(q, key, change) {
            q.variants = q.variants || new Map();
            if (q.variants.has(key)) return q.variants.get(key);
            let v = null;
            try {
                const descriptor = change(Object.assign({}, q.descriptor));
                v = { kind: "pipeline", desc: q.desc, groups: q.groups, push: q.push, descriptor, gpu: this.device.createRenderPipeline(descriptor),
                    bindGroups: new Map(), error: null };
            } catch (error) {
                this.warn("variant:" + error.message, "a pipeline's variant (" + key + ") failed: " + error.message);
            }
            q.variants.set(key, v);
            return v;
        }

        /**
         * A pipeline's vertex input as WebGPU's buffers: Vulkan's bindings at
         * their slots (`buffers`, `native`), and packed (`packed`, `fields`,
         * `strides`: each attribute a field of slot 0 (bindings of stride 0),
         * 1 (per vertex) or 2 (per instance), which draws repack into, for
         * what WebGPU cannot take: more than 8 bindings (ANGLE gives each
         * attribute one), strides not in dwords or above 2048, attributes not
         * aligned to their size, buffers bound at offsets not in dwords)
         */
        vertexLayout(d) {
            const buffers = [], attributes = [];
            let native = true;
            for (const b of d.buffers) {
                if (b.binding >= 8 || b.stride % 4 || b.stride > 2048) { native = false; continue; }
                // (slots of no binding: none, which WebGPU wants no buffer for)
                while (buffers.length <= b.binding) buffers.push(null);
                buffers[b.binding] = { arrayStride: b.stride, stepMode: b.rate ? "instance" : "vertex", attributes: [] };
            }
            for (const a of d.attributes) {
                const f = this.formats[a.format], b = d.buffers.find(x => x.binding === a.binding);
                if (!f || !f[2]) { this.warn("vertex-format" + a.format, "vertex format " + a.format + " is not done"); continue; }
                if (!b) continue;
                const bytes = vertexFormatBytes(f[2]);
                if (a.offset % Math.min(4, bytes) || b.stride && a.offset + bytes > b.stride) native = false;
                attributes.push({ a, b, format: f[2], bytes });
                if (buffers[a.binding]) buffers[a.binding].attributes.push({ format: f[2], offset: a.offset, shaderLocation: a.location });
            }
            const slots = [[], [], []], strides = [0, 0, 0], fields = [];
            for (const { a, b, format, bytes } of attributes) {
                const slot = b.stride === 0 ? 0 : b.rate ? 2 : 1;
                slots[slot].push({ format, offset: strides[slot], shaderLocation: a.location });
                fields.push({ slot, offset: strides[slot], binding: a.binding, from: a.offset, stride: b.stride, bytes });
                strides[slot] += align(bytes, 4);
            }
            const packed = slots.map((list, slot) => list.length ? { arrayStride: slot ? strides[slot] : 0, stepMode: slot === 2 ? "instance" : "vertex",
                attributes: list } : null);
            if (!native) this.stats.packedPipelines = (this.stats.packedPipelines || 0) + 1;
            return { native, buffers, packed, fields, strides };
        }

        /**
         * A draw's vertex input repacked into scratch buffers (vertexLayout's
         * `packed`), between two halves of its pass: { buffers (by slot),
         * variant (a pipeline of native input bound at an offset WebGPU
         * refuses: its packed variant) }, or null when the draw needs none.
         * The rows are a draw's vertices and instances from 0 (the shader's
         * vertex and instance indices are kept); for indexed and indirect
         * draws, as many as the bound buffers have (up to PACKED_ROWS)
         */
        packVertices(p, kind, b) {
            const layout = p.vertexLayout, s = this.state;
            if (!layout || layout.native && !p.desc.buffers.some(x => s.vertex[x.binding] && s.vertex[x.binding].offset % 4)) return null;
            const bound = f => {
                const v = s.vertex[f.binding], m = v && this.memory(v.memory);
                return m ? { v, m, size: Math.min(v.size, m.buffer.size - v.offset) } : null;
            };
            const available = f => {
                const x = bound(f);
                if (!x || x.size < f.from + f.bytes) return 0;
                return f.stride ? Math.floor((x.size - f.from - f.bytes) / f.stride) + 1 : 1;
            };
            const rows = [1, kind === 0 ? b[2] + b[0] : 0, kind === 0 ? b[3] + b[1] : kind === 1 ? b[4] + b[1] : 0];
            for (const f of layout.fields) {
                if (f.slot === 1 && kind !== 0 || f.slot === 2 && kind === 2) rows[f.slot] = Math.max(rows[f.slot], available(f));
            }
            if (rows[1] > PACKED_ROWS) { this.warn("packed-rows", "a draw's vertices repacked: the first " + PACKED_ROWS + " only"); rows[1] = PACKED_ROWS; }
            // (a slot of the pipeline's always gets a buffer, of one row at least: WebGPU wants each set)
            const buffers = layout.packed.map((l, slot) => l ?
                this.scratch(Math.max(1, rows[slot]) * (layout.strides[slot] || 4), BUFFER.VERTEX | BUFFER.STORAGE | BUFFER.COPY_DST) : null);
            const resume = !!this.pass;
            this.endPass();
            for (const f of layout.fields) {
                const x = bound(f), dst = buffers[f.slot], n = Math.min(rows[f.slot], available(f));
                if (!x || !dst || !n) continue;
                const from = f.stride || f.bytes, to = layout.strides[f.slot] || 4;
                this.repack(x.m.buffer, { offset: x.v.offset + f.from, pitch: from, image: from * n }, dst, { offset: f.offset, pitch: to, image: to * n }, f.bytes, n, 1);
            }
            this.stats.packedDraws = (this.stats.packedDraws || 0) + 1;
            if (resume) this.resumePass();
            return { buffers, variant: layout.native };
        }

        /**
         * GL's provoking vertex (VK_EXT_provoking_vertex's last vertex,
         * which ANGLE asks of every pipeline) is the last of a primitive,
         * WebGPU's the first: a draw of such a pipeline whose vertex shader
         * has flat outputs is drawn as a list of its primitives with their
         * vertices rotated, the last first (so triangles keep their winding);
         * indexed triangle fans so too, either way. Without indices the order
         * is made here once per count; with indices a compute pass (between
         * two halves of the render pass) rewrites them, restarts included, and
         * the draw is indirect (the count is the pass's). Indirect draws are
         * drawn as they are (warned).
         * @return {?Object} { topology, buffer, count | args }, or null: drawn as it is
         */
        provokingLast(p, kind, b) {
            const s = this.state, d = p.desc, fan = d.topology === 5;
            const last = !!d.provoking_last && p.flat;
            // (and primitive restart in lists, GL ES 3.0's, which WebGPU does in strips only: the
            // restart index dropped, the primitive it cuts short too)
            const listRestart = kind === 1 && d.restart && (d.topology === 0 || d.topology === 1 || d.topology === 3);
            if (!last && !(fan && kind === 1) && !listRestart) return null;
            if (kind === 2) {
                if (last) this.warn("provoking-indirect", "indirect draws of flat varyings keep WebGPU's first vertex");
                return null;
            }
            // (VkPrimitiveTopology as GX's kinds: triangle list 1, strip 2, line list 3, strip 4, triangle fan 5; and point list 6)
            const order = { 0: 6, 1: 3, 2: 4, 3: 1, 4: 2, 5: 5 }[d.topology];
            if (!order || !b[0] || order === 6 && kind === 0) return null;
            const list = order <= 2 || order === 5 ? "triangle-list" : order === 6 ? "point-list" : "line-list";
            if (kind === 0) {
                const key = order + ":" + b[0] + ":" + last;
                this.provokingIndices = this.provokingIndices || new Map();
                let entry = this.provokingIndices.get(key);
                if (!entry) {
                    const n = b[0], out = [];
                    if (order === 1) for (let k = 0; k + 2 < n; k += 3) out.push(k + 2, k, k + 1);
                    else if (order === 2) for (let k = 0; k + 2 < n; k++) out.push(...(k & 1 ? [k + 2, k + 1, k] : [k + 2, k, k + 1]));
                    else if (order === 3) for (let k = 0; k + 1 < n; k += 2) out.push(k + 1, k);
                    else if (order === 4) for (let k = 0; k + 1 < n; k++) out.push(k + 1, k);
                    else for (let k = 1; k + 1 < n; k++) out.push(...(last ? [k + 1, 0, k] : [k, k + 1, 0]));
                    if (!out.length) return null;
                    const data = Uint32Array.from(out);
                    const buffer = this.device.createBuffer({ size: align(data.byteLength, 4), usage: BUFFER.INDEX | BUFFER.COPY_DST });
                    this.device.queue.writeBuffer(buffer, 0, data);
                    if (this.provokingIndices.size >= 64) {
                        for (const old of this.provokingIndices.values()) old.buffer.destroy();
                        this.provokingIndices.clear();
                    }
                    entry = { buffer, count: out.length };
                    this.provokingIndices.set(key, entry);
                }
                return { topology: list, buffer: entry.buffer, count: entry.count };
            }
            const ib = s.index, m = ib && this.memory(ib.memory);
            if (!m) return null;
            const wide = ib.type === 1;
            if (!this.provokingPipeline) {
                const code = [
                    "struct P { count: u32, offset: u32, wide: u32, kind: u32, base: u32, instances: u32, first_instance: u32, last: u32, restart: u32 }",
                    "@group(0) @binding(0) var<storage, read> src: array<u32>;",
                    "@group(0) @binding(1) var<uniform> p: P;",
                    "@group(0) @binding(2) var<storage, read_write> dst: array<u32>;",
                    "@group(0) @binding(3) var<storage, read_write> args: array<u32, 5>;",
                    "fn index(i: u32) -> u32 {",
                    "    let at = p.offset + i;",
                    "    if (p.wide == 1u) { return src[at]; }",
                    "    let w = src[at >> 1u];",
                    "    return select(w & 0xFFFFu, w >> 16u, (at & 1u) == 1u);",
                    "}",
                    "@compute @workgroup_size(1) fn main() {",
                    "    let cut = select(0xFFFFu, 0xFFFFFFFFu, p.wide == 1u);",
                    "    var n = 0u;",
                    "    var start = 0u;",
                    "    var i = 0u;",
                    "    // lists: a primitive's indices gathered (a restart drops the one it cuts short), then the last first or as they were",
                    "    if (p.kind == 1u || p.kind == 3u || p.kind == 6u) {",
                    "        let per = select(select(1u, 2u, p.kind == 3u), 3u, p.kind == 1u);",
                    "        var k = 0u; var a = 0u; var b = 0u; var c = 0u;",
                    "        for (var j = 0u; j < p.count; j++) {",
                    "            let v = index(j);",
                    "            if (p.restart == 1u && v == cut) { k = 0u; continue; }",
                    "            if (k == 0u) { a = v; } else if (k == 1u) { b = v; } else { c = v; }",
                    "            k++;",
                    "            if (k < per) { continue; }",
                    "            if (per == 1u) { dst[n] = a; }",
                    "            else if (per == 2u) { dst[n] = select(a, b, p.last == 1u); dst[n + 1u] = select(b, a, p.last == 1u); }",
                    "            else if (p.last == 1u) { dst[n] = c; dst[n + 1u] = a; dst[n + 2u] = b; }",
                    "            else { dst[n] = a; dst[n + 1u] = b; dst[n + 2u] = c; }",
                    "            n += per; k = 0u;",
                    "        }",
                    "        args[0] = n; args[1] = p.instances; args[2] = 0u; args[3] = p.base; args[4] = p.first_instance;",
                    "        return;",
                    "    }",
                    "    loop {",
                    "        if (i >= p.count) { break; }",
                    "        // strips and fans: a restart starts another",
                    "        if (index(i) == cut) { start = i + 1u; i++; continue; }",
                    "        let k = i - start;",
                    "        if (p.kind == 2u && k >= 2u) {",
                    "            if ((k & 1u) == 1u) { dst[n] = index(i); dst[n + 1u] = index(i - 1u); dst[n + 2u] = index(i - 2u); }",
                    "            else { dst[n] = index(i); dst[n + 1u] = index(i - 2u); dst[n + 2u] = index(i - 1u); }",
                    "            n += 3u;",
                    "        }",
                    "        if (p.kind == 4u && k >= 1u) { dst[n] = index(i); dst[n + 1u] = index(i - 1u); n += 2u; }",
                    "        if (p.kind == 5u && k >= 2u) {",
                    "            let first = index(start);",
                    "            if (p.last == 1u) { dst[n] = index(i); dst[n + 1u] = first; dst[n + 2u] = index(i - 1u); }",
                    "            else { dst[n] = index(i - 1u); dst[n + 1u] = index(i); dst[n + 2u] = first; }",
                    "            n += 3u;",
                    "        }",
                    "        i++;",
                    "    }",
                    "    args[0] = n; args[1] = p.instances; args[2] = 0u; args[3] = p.base; args[4] = p.first_instance;",
                    "}",
                ].join("\n");
                this.provokingPipeline = this.device.createComputePipeline({ layout: "auto", compute: { module: this.device.createShaderModule({ code }), entryPoint: "main" } });
            }
            // b: indexCount, instanceCount, firstIndex, vertexOffset, firstInstance
            const offset = Math.floor(ib.offset / (wide ? 4 : 2)) + b[2];
            const dst = this.scratch(Math.max(16, b[0] * 3 * 4), BUFFER.STORAGE | BUFFER.INDEX);
            const args = this.scratch(32, BUFFER.STORAGE | BUFFER.INDIRECT);
            const params = this.device.createBuffer({ size: 48, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
            this.device.queue.writeBuffer(params, 0, Uint32Array.from([b[0], offset, wide ? 1 : 0, order, b[3] >>> 0, b[1], b[4], last ? 1 : 0,
                d.restart ? 1 : 0, 0, 0, 0]));
            this.transient.push(params);
            const group = this.device.createBindGroup({ layout: this.provokingPipeline.getBindGroupLayout(0), entries: [
                { binding: 0, resource: { buffer: m.buffer } }, { binding: 1, resource: { buffer: params } },
                { binding: 2, resource: { buffer: dst } }, { binding: 3, resource: { buffer: args } }] });
            const resume = !!this.pass;
            this.endPass();
            const compute = this.encoder().beginComputePass();
            compute.setPipeline(this.provokingPipeline);
            compute.setBindGroup(0, group);
            compute.dispatchWorkgroups(1);
            compute.end();
            this.stats.provokingDraws = (this.stats.provokingDraws || 0) + 1;
            if (resume) this.resumePass();
            return { topology: list, buffer: dst, args };
        }

        /** An index buffer of triangle fans as lists for fans of up to `n` vertices: Vulkan's (i + 1, i + 2, 0), its provoking vertex first */
        fanIndices(n) {
            if (this.fans && this.fans.vertices >= n) return this.fans.buffer;
            const vertices = Math.max(64, 1 << Math.ceil(Math.log2(n)));
            const indices = new Uint32Array(3 * (vertices - 2));
            for (let i = 0; i < vertices - 2; i++) indices.set([i + 1, i + 2, 0], 3 * i);
            if (this.fans) this.transient.push(this.fans.buffer);
            const buffer = this.device.createBuffer({ size: indices.byteLength, usage: BUFFER.INDEX | BUFFER.COPY_DST });
            this.device.queue.writeBuffer(buffer, 0, indices);
            this.fans = { vertices, buffer };
            return buffer;
        }

        // ------------------------------------------------------------------
        // Draws and dispatches

        draw(b, kind) {
            // (transform feedback: what the draw's vertices capture, before the draw: a pass of its own)
            if (this.state.xfb.active && this.state.graphics && this.state.graphics.gpu) {
                if (kind === 0) this.capture(this.state.graphics, b);
                else this.warn("xfb-indexed", "indexed and indirect draws capture nothing (GL ES 3.0 has none)");
            }
            if (this.pass && this.state.graphics && this.state.graphics.gpu) {
                this.attachmentCopies(this.state.graphics);
                // (swizzled views: their copies, drawn again where their textures were written)
                this.swizzleCopies(this.state.graphics, 0);
            }
            // (vertex input WebGPU cannot take: repacked, between two halves of the pass)
            const packed = this.pass && this.state.graphics && this.state.graphics.gpu ? this.packVertices(this.state.graphics, kind, b) : null;
            // (GL's provoking vertex with flat varyings, and indexed fans: the vertices reordered)
            const reorder = this.pass && this.state.graphics && this.state.graphics.gpu ? this.provokingLast(this.state.graphics, kind, b) : null;
            const p = this.state.graphics, pass = this.pass;
            if (!pass || !p || !p.gpu) {
                if (p && p.error) this.warn("draw-pipeline", "draws with a failed pipeline are skipped");
                return;
            }
            this.stats.draws++;
            const s = this.state;
            // (both faces culled: no triangle drawn; WebGPU culls one face or none)
            if (p.desc.cull === 3 && p.desc.topology >= 3 && !p.desc.discard) return;
            // viewport and scissor: the dynamic ones, or the pipeline's; within the target (WebGPU's rule)
            const viewport = p.desc.dynamic.includes(0) && s.viewport ? s.viewport :
                p.desc.viewport ? [p.desc.viewport.x, p.desc.viewport.y, p.desc.viewport.width, p.desc.viewport.height, p.desc.viewport.minDepth, p.desc.viewport.maxDepth] : null;
            // (a viewport flipped, or with its depths reversed: a variant of the vertex shader)
            const reversed = viewport && viewport[4] > viewport[5];
            const variant = (viewport && viewport[3] < 0 ? TRANSLATE.KEEP : 0) | (reversed ? TRANSLATE.REVERSE_DEPTH : 0);
            // (integer images sampled with samplers that repeat: their address modes in the shaders)
            const wraps = this.intWraps(p, 0);
            let q = wraps.length ? this.wrapVariant(p, variant, wraps) : variant ? this.vertexVariant(p, variant) : p;
            if (!q) return;
            // the stencil masks and reference of each face (the dynamic ones, or
            // the pipeline's): WebGPU's are one for both faces, so a draw whose
            // faces differ is drawn twice, a face each, the other culled
            const z = p.desc.depth, dyn = state => p.desc.dynamic.includes(state);
            const stencil = !p.desc.discard && q.descriptor && q.descriptor.depthStencil && q.descriptor.depthStencil.stencilFront &&
                !!q.descriptor.depthStencil.stencilFront.compare && z;
            const faceOf = back => {
                const fixed = back ? z.back : z.front;
                return { read: (dyn(6) ? back ? s.stencilBack[0] : s.stencilMasks[0] : fixed.read_mask) & 0xFF,
                    write: (dyn(7) ? back ? s.stencilBack[1] : s.stencilMasks[1] : fixed.write_mask) & 0xFF,
                    reference: dyn(8) ? back ? s.stencilBack[2] : s.stencilReference : fixed.reference };
            };
            let faces = [{ face: null, cull: null }];
            if (stencil) {
                const front = faceOf(false), back = faceOf(true);
                const same = front.read === back.read && front.write === back.write && front.reference === back.reference;
                // (lines and points are front faces; a pipeline culling one face draws the other)
                if (p.desc.topology < 3 || p.desc.cull === 2 || same) faces = [{ face: front, cull: null }];
                else if (p.desc.cull === 1) faces = [{ face: back, cull: null }];
                else faces = [{ face: front, cull: "back" }, { face: back, cull: "front" }];
            }
            // (the dynamic depth bias, when the pipeline biases: a variant per bias)
            if (p.desc.dynamic.includes(3) && p.desc.depth_bias && p.desc.topology >= 3 && s.depthBias && q.descriptor && q.descriptor.depthStencil) {
                const [constant, clamp, slope] = s.depthBias, ds = q.descriptor.depthStencil;
                if (ds.depthBias !== Math.round(constant) || ds.depthBiasSlopeScale !== slope || ds.depthBiasClamp !== clamp) {
                    q = this.variant(q, "bias:" + constant + ":" + clamp + ":" + slope, d => Object.assign(d, { depthStencil: Object.assign({}, ds,
                        { depthBias: Math.round(constant), depthBiasSlopeScale: slope, depthBiasClamp: clamp }) }));
                    if (!q) return;
                }
            }
            // (indexed strips: WebGPU wants the index format in the pipeline)
            const indexed = kind === 1 || kind === 2 && b[5];
            if (reorder && q.descriptor) {
                q = this.variant(q, "list:" + reorder.topology, d => Object.assign(d, { primitive: Object.assign({}, d.primitive,
                    { topology: reorder.topology, stripIndexFormat: undefined }) }));
                if (!q) return;
            }
            else if (indexed && (p.desc.topology === 2 || p.desc.topology === 4) && q.descriptor) {
                const format = s.index && s.index.type === 1 ? "uint32" : "uint16";
                q = this.variant(q, "strip:" + format, d => Object.assign(d, { primitive: Object.assign({}, d.primitive, { stripIndexFormat: format }) }));
                if (!q) return;
            }
            if (packed && packed.variant && q.descriptor) {
                q = this.variant(q, "packed", d => Object.assign(d, { vertex: Object.assign({}, d.vertex, { buffers: p.vertexLayout.packed }) }));
                if (!q) return;
            }
            const fan = p.desc.topology === 5;
            if (fan && kind !== 0 && !reorder) {
                this.warn("fan-indexed", "indexed and indirect triangle fans are not done");
                return;
            }
            // (a pipeline for other attachments: WebGPU would drop the whole batch for it)
            const attachments = q.attachments || (q.attachments = attachmentState(q.descriptor && q.descriptor.fragment ?
                q.descriptor.fragment.targets.map(t => t ? t.format : null) : [], q.descriptor && q.descriptor.depthStencil ? q.descriptor.depthStencil.format : "",
                q.descriptor && q.descriptor.multisample ? q.descriptor.multisample.count || 1 : 1));
            if (attachments !== this.passAttachments) {
                this.warn("attachments:" + attachments + ":" + this.passAttachments, "a draw's pipeline is for other attachments: " + attachments +
                    ", the pass's " + this.passAttachments + " (skipped)");
                return;
            }
            if (p.desc.push_size && p.groups.has(p.push)) this.pushWrite();
            // each face's pipeline (its masks, and the other face culled) and bind groups
            const draws = [];
            for (const { face, cull } of faces) {
                let f = q;
                if (face) f = this.maskedPipeline(f, face.read, face.write);
                if (f && cull) f = this.variant(f, "cull:" + cull, d => Object.assign(d, { primitive: Object.assign({}, d.primitive, { cullMode: cull }) }));
                if (!f) return;
                const groups = [];
                for (const group of p.groups.keys()) {
                    const bg = this.bindGroup(f, 0, group);
                    if (!bg) return;
                    groups.push([group, bg]);
                }
                draws.push({ f, groups, reference: face ? face.reference : z && z.front ? z.front.reference : 0 });
            }
            if (packed) packed.buffers.forEach((buffer, slot) => { if (buffer) pass.setVertexBuffer(slot, buffer); });
            else {
                // (the pipeline's bindings only: others may be bound where WebGPU refuses; one with
                // nothing bound reads zeros, as WebGPU would drop the whole batch for it)
                for (const { binding: slot } of p.desc.buffers) {
                    const v = s.vertex[slot], m = v && this.memory(v.memory);
                    if (slot >= 8) continue;
                    if (m) pass.setVertexBuffer(slot, m.buffer, v.offset, Math.min(v.size, m.buffer.size - v.offset));
                    else {
                        this.warn("vertex-unbound" + slot, "vertex binding " + slot + " has nothing bound (zeros)");
                        if (!this.zeroVertices) this.zeroVertices = this.device.createBuffer({ size: 1 << 16, usage: BUFFER.VERTEX });
                        pass.setVertexBuffer(slot, this.zeroVertices);
                    }
                }
            }
            if (viewport) {
                let [x, y, w, h, near, far] = viewport;
                // (flipped by the pipeline's variant: the rows it covers)
                if (h < 0) { y += h; h = -h; }
                const x0 = Math.max(0, x), y0 = Math.max(0, y);
                const x1 = Math.min(s.passWidth, x + w), y1 = Math.min(s.passHeight, y + h);
                if (reversed) [near, far] = [far, near];
                if (x1 > x0 && y1 > y0) pass.setViewport(x0, y0, x1 - x0, y1 - y0, Math.max(0, Math.min(1, near)), Math.max(0, Math.min(1, far)));
            }
            const scissor = p.desc.dynamic.includes(1) && s.scissor ? s.scissor :
                p.desc.scissor ? [p.desc.scissor.offset.x, p.desc.scissor.offset.y, p.desc.scissor.extent.width, p.desc.scissor.extent.height] : null;
            if (scissor) {
                const x0 = Math.max(0, scissor[0]), y0 = Math.max(0, scissor[1]);
                const x1 = Math.min(s.passWidth, scissor[0] + scissor[2]), y1 = Math.min(s.passHeight, scissor[1] + scissor[3]);
                pass.setScissorRect(x0, y0, Math.max(0, x1 - x0), Math.max(0, y1 - y0));
            }
            const blend = p.desc.dynamic.includes(4) && s.blend ? s.blend : p.desc.blend_constants;
            if (p.constantAlpha) pass.setBlendConstant({ r: blend[3], g: blend[3], b: blend[3], a: blend[3] });
            else pass.setBlendConstant({ r: blend[0], g: blend[1], b: blend[2], a: blend[3] });
            if ((kind === 1 || kind === 2 && b[5]) && !reorder) {
                const ib = s.index, m = ib && this.memory(ib.memory);
                if (!m) return;
                pass.setIndexBuffer(m.buffer, ib.type === 1 ? "uint32" : "uint16", ib.offset, Math.min(ib.size, m.buffer.size - ib.offset));
            }
            this.substitutes = null;
            for (const { f, groups, reference } of draws) {
                pass.setPipeline(f.gpu);
                for (const [group, bg] of groups) pass.setBindGroup(group, bg);
                pass.setStencilReference(reference);
                if (!this.issueDraw(pass, b, kind, reorder, fan)) return;
            }
        }

        /** A draw's call, its pipeline and state set: false when it cannot be drawn */
        issueDraw(pass, b, kind, reorder, fan) {
            if (reorder) {
                pass.setIndexBuffer(reorder.buffer, "uint32");
                if (reorder.args) pass.drawIndexedIndirect(reorder.args, 0);
                // (the vertices from the draw's first: its vertex index kept)
                else pass.drawIndexed(reorder.count, b[1], 0, b[2], b[3]);
            }
            else if (kind === 0 && fan) {
                if (b[0] < 3) return false;
                pass.setIndexBuffer(this.fanIndices(b[0]), "uint32");
                pass.drawIndexed(3 * (b[0] - 2), b[1], 0, b[2], b[3]);
            }
            else if (kind === 0) pass.draw(b[0], b[1], b[2], b[3]);
            else if (kind === 1) pass.drawIndexed(b[0], b[1], b[2], b[3] | 0, b[4]);
            else {
                const m = this.memory(b[0]);
                if (!m) return false;
                const offset = b[1] + b[2] * 0x100000000;
                for (let i = 0; i < b[3]; i++) {
                    if (b[5]) pass.drawIndexedIndirect(m.buffer, offset + i * b[4]);
                    else pass.drawIndirect(m.buffer, offset + i * b[4]);
                }
            }
            return true;
        }

        // ------------------------------------------------------------------
        // Transform feedback (VK_EXT_transform_feedback): WebGPU's vertex
        // stage cannot write storage buffers, so a draw that captures runs
        // its vertex shader as a compute shader first (vx/naga/src/xfb.rs),
        // in a compute pass between two halves of the render pass, into
        // scratch buffers copied where the transform feedback buffers are
        // (a vertex buffer and a capture buffer may be one memory, which a
        // dispatch cannot have as storage both read and written). The
        // primitives that fit are counted here (GL ES 3.0 captures draws of
        // lists, not indexed nor indirect): so are the counters and queries.

        /** XFB_BEGIN (`begin`) or XFB_END: the bytes captured from each counter (End: into it) */
        xfbBegin(b, begin) {
            const x = this.state.xfb, first = b[0], count = b[1];
            if (begin) { x.active = true; x.written = [0, 0, 0, 0]; }
            for (let i = 0; i < count; i++) {
                const rid = b[2 + 3 * i], offset = b[3 + 3 * i] + b[4 + 3 * i] * 0x100000000, slot = first + i;
                if (!rid || slot > 3) continue;
                const key = rid + ":" + offset;
                if (begin) { x.written[slot] = this.xfbCounters.get(key) || 0; continue; }
                this.xfbCounters.set(key, x.written[slot]);
                const m = this.memory(rid);
                if (m && offset + 4 <= m.buffer.size) this.device.queue.writeBuffer(m.buffer, offset, new Uint32Array([x.written[slot]]));
            }
            if (!begin) x.active = false;
        }

        /** a capturing draw's compute pipeline (made at its first draw), or null */
        xfbPipeline(p) {
            if (p.xfb !== undefined) return p.xfb;
            p.xfb = null;
            try {
                const vs = p.vertexSource, d = p.desc;
                // (its own resources in a group the vertex shader does not use)
                const group = [0, 1, 2, 3].find(g => !p.groups.has(g));
                if (group === undefined) throw new Error("the vertex shader uses every bind group");
                const words = [group, d.attributes.length];
                for (const a of d.attributes) words.push(a.location, a.binding, a.format, a.offset);
                words.push(d.buffers.length);
                for (const v of d.buffers) words.push(v.binding, v.stride, v.rate ? 1 : 0);
                const t = this.translateXfb(vs.shader, p.push, p.storage, words);
                if (t.error) throw new Error(t.error);
                const st = this.stageState(t, vs.stage);
                const module = this.device.createShaderModule({ code: "diagnostic(off, derivative_uniformity);\n" + t.wgsl });
                const gpu = this.device.createComputePipeline({ layout: "auto", compute: { module, entryPoint: "vx_xfb", constants: st.constants } });
                const groups = new Map();
                for (const [g, binding, kind] of st.entry ? st.entry.bindings : []) {
                    if (!groups.has(g)) groups.set(g, new Map());
                    groups.get(g).set(binding, kind);
                }
                p.xfb = { kind: "pipeline", gpu, groups, push: p.push, bindGroups: new Map(), group, strides: t.xfb.strides, buffers: t.xfb.buffers,
                    slots: t.xfb.slots };
            } catch (error) {
                this.warn("xfb:" + error.message, "a capturing draw's compute shader failed: " + error.message);
            }
            return p.xfb;
        }

        /** The vertices of draw `b` (vertices, instances, first vertex, first instance) captured */
        capture(p, b) {
            const x = this.state.xfb;
            const vertices = LIST_VERTICES[p.desc.topology];
            if (!vertices) { this.warn("xfb-topology", "captures of strips and fans are not done (GL ES 3.0 captures lists)"); return; }
            const c = this.xfbPipeline(p);
            if (!c) return;
            const [count, instances, firstVertex, firstInstance] = b;
            const primitives = Math.floor(count / vertices), needed = primitives * instances;
            // the primitives that fit in every buffer the shader captures into
            let fit = needed;
            for (const buffer of c.buffers) {
                const bound = x.buffers[buffer], stride = c.strides[buffer];
                if (!bound || !stride) { fit = 0; break; }
                fit = Math.min(fit, Math.max(0, Math.floor((bound.size - x.written[buffer]) / (stride * vertices))));
            }
            if (this.xfbQuery) { this.xfbQuery.written += fit; this.xfbQuery.needed += needed; }
            const limit = fit * vertices;
            if (!limit) return;
            this.stats.captures = (this.stats.captures || 0) + 1;
            if (p.desc.push_size && p.groups.has(p.push)) this.pushWrite();
            const groups = [];
            for (const group of c.groups.keys()) {
                const bg = this.bindGroup(c, 0, group);
                if (!bg) return;
                groups.push([group, bg]);
            }
            // the parameters (VxXfbParams), the vertex buffers' memories, the scratch buffers
            const params = new Uint32Array(20);
            params.set([firstVertex, primitives * vertices, firstInstance, instances, 0, limit]);
            const entries = [];
            for (const slot of c.slots) {
                const v = this.state.vertex[slot], m = v && this.memory(v.memory);
                if (!m) { this.warn("xfb-vertex", "a capture without its vertex buffer"); return; }
                params[12 + slot] = v.offset;
                entries.push({ binding: 961 + slot, resource: { buffer: m.buffer } });
            }
            const uniform = this.device.createBuffer({ size: params.byteLength, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
            this.transient.push(uniform);
            this.device.queue.writeBuffer(uniform, 0, params);
            entries.push({ binding: 960, resource: { buffer: uniform } });
            const scratch = [];
            for (const buffer of c.buffers) {
                const bytes = limit * c.strides[buffer];
                const s = this.scratch(bytes, BUFFER.STORAGE | BUFFER.COPY_SRC);
                scratch.push([buffer, s, bytes]);
                entries.push({ binding: 970 + buffer, resource: { buffer: s } });
            }
            groups.push([c.group, this.device.createBindGroup({ layout: c.gpu.getBindGroupLayout(c.group), entries })]);
            // between the halves of the render pass
            const resume = !!this.pass;
            this.endPasses();
            const encoder = this.encoder();
            const pass = encoder.beginComputePass();
            pass.setPipeline(c.gpu);
            for (const [group, bg] of groups) pass.setBindGroup(group, bg);
            pass.dispatchWorkgroups(Math.ceil(limit / 64));
            pass.end();
            for (const [buffer, s, bytes] of scratch) {
                const bound = x.buffers[buffer], m = this.memory(bound.memory);
                if (m) encoder.copyBufferToBuffer(s, 0, m.buffer, bound.offset + x.written[buffer], Math.min(bytes, m.buffer.size - bound.offset - x.written[buffer]));
                x.written[buffer] += bytes;
            }
            if (resume) this.resumePass();
        }

        /** The render pass again after a capture's compute pass: as it was begun, its attachments loaded */
        resumePass() {
            const d = JSON.parse(JSON.stringify(this.passDesc));
            for (const c of d.colors) if (c) { if (c.store === 1) this.warn("resume-discard", "a pass ended in its middle (a capture, a copy of an attachment it samples) whose attachments it discards"); c.load = 0; }
            if (d.depth) { d.depth.load = 0; d.depth.stencil_load = 0; }
            // (its occlusion queries go on in no pass: an occlusion query across a capture counts its first half)
            d.occlusion = 0;
            const pipeline = this.state.graphics;
            this.beginPass(d);
            this.state.graphics = pipeline;
        }

        /**
         * A draw that samples a texture attached to its pass (an input
         * attachment of its own subpass: framebuffer fetch, ANGLE's advanced
         * blending): WebGPU samples no attachment of the pass it is in, so
         * the pass ends, each such texture is copied, the pass goes on and
         * the draw samples the copies (what the attachments held before it,
         * the non-coherent behaviour). Multisampled ones are not copied.
         */
        attachmentCopies(p) {
            this.substitutes = null;
            if (!this.passTextures || !this.passTextures.size) return;
            const views = new Set();
            for (const [group, used] of p.groups) {
                const contents = this.state.groups[0].get(group);
                if (!contents) continue;
                for (const [binding, kind] of used) {
                    // (push constants share a group with the last set when there are 4)
                    if (group === p.push && binding === PUSH_BINDING || samplerBinding(binding) || !/^texture/.test(kind)) continue;
                    const d = contents.descriptors.get(descriptorKey(binding));
                    const v = d && this.objects.get(d.rid);
                    if (v && v.kind === "view" && this.passTextures.has(v.texture.texture)) views.add(v);
                }
            }
            if (!views.size) return;
            this.endPass();
            const substitutes = new Map();
            for (const v of views) {
                const t = v.texture;
                if (t.samples > 1) {
                    this.warn("fetch-ms", "a draw reading its multisampled attachment reads it as it is (not done)");
                    continue;
                }
                const copy = this.device.createTexture({ size: [t.width, Math.max(1, t.height), t.volume ? t.depth : t.layers], dimension: t.volume ? "3d" : "2d",
                    format: t.texture.format, mipLevelCount: t.mips, usage: TEXTURE.TEXTURE_BINDING | TEXTURE.COPY_DST });
                this.transient.push(copy);
                for (let mip = v.baseMip; mip < v.baseMip + v.mips; mip++) {
                    const width = Math.max(1, t.width >> mip), height = Math.max(1, Math.max(1, t.height) >> mip);
                    this.encoder().copyTextureToTexture({ texture: t.texture, mipLevel: mip, origin: [0, 0, t.volume ? 0 : v.baseLayer] },
                        { texture: copy, mipLevel: mip, origin: [0, 0, t.volume ? 0 : v.baseLayer] },
                        [width, height, t.volume ? Math.max(1, t.depth >> mip) : v.layers]);
                }
                substitutes.set(v, copy.createView(Object.assign({}, v.descriptor)));
            }
            this.resumePass();
            this.substitutes = substitutes;
        }

        /** The compute shader of a capturing draw (vx_translate_xfb), naga loaded */
        translateXfb(shader, push, storage, words) {
            const naga = this.naga;
            const input = naga.vx_alloc(shader.spirv.length);
            new Uint8Array(naga.memory.buffer, input, shader.spirv.length).set(shader.spirv);
            const list = storage.length ? naga.vx_alloc(storage.length * 4) : 0;
            if (list) new Uint32Array(naga.memory.buffer, list, storage.length).set(storage);
            const desc = naga.vx_alloc(words.length * 4);
            new Uint32Array(naga.memory.buffer, desc, words.length).set(words);
            let out;
            try {
                out = naga.vx_translate_xfb(input, shader.spirv.length, push, PUSH_BINDING, list, storage.length, desc, words.length);
            } catch (error) {
                this.naga = null;
                throw error;
            }
            naga.vx_free(input, shader.spirv.length);
            if (list) naga.vx_free(list, storage.length * 4);
            naga.vx_free(desc, words.length * 4);
            const length = new DataView(naga.memory.buffer).getUint32(out, true);
            const text = new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length));
            naga.vx_free(out, length + 4);
            return JSON.parse(text);
        }

        /** push constants into the push buffer, before the pass they are for (a copy is not in a pass) */
        pushWrite() {
            const s = this.state;
            if (s.pushWritten === s.pushVersion && this.pushBuffer) return;
            if (!this.pushBuffer || this.pushUsed + 256 > this.pushBuffer.size) {
                this.pushBuffer = this.device.createBuffer({ size: 256 * 256, usage: BUFFER.STORAGE | BUFFER.COPY_DST });
                this.pushUsed = 0;
            }
            s.pushOffset = this.pushUsed;
            this.pushUsed += 256;
            // (queue writes go before the encoder's work: each place is written once, before the submit that reads it)
            this.device.queue.writeBuffer(this.pushBuffer, s.pushOffset, s.push);
            s.pushWritten = s.pushVersion;
        }

        dispatch(b, indirect) {
            const p = this.state.compute;
            if (!p || !p.gpu) return;
            this.stats.dispatches++;
            if (p.desc.push_size && p.groups.has(p.push)) this.pushWrite();
            this.endPass();
            this.swizzleCopies(p, 1);
            // (integer images sampled with samplers that repeat: a variant of the shader)
            const wraps = this.intWraps(p, 1);
            const q = wraps.length ? this.wrapComputeVariant(p, wraps) : p;
            if (!q) return;
            // (the bind groups first: their copies are outside the compute pass)
            const writable = this.writableBuffers(p);
            const groups = [];
            for (const group of p.groups.keys()) {
                const bg = this.bindGroup(q, 1, group, writable);
                if (!bg) return;
                groups.push([group, bg]);
            }
            if (!this.computePass) {
                const encoder = this.encoder();
                this.computePass = encoder.beginComputePass();
            }
            const pass = this.computePass;
            pass.setPipeline(q.gpu);
            for (const [group, bg] of groups) pass.setBindGroup(group, bg);
            if (indirect) {
                const m = this.memory(b[0]);
                if (m) pass.dispatchWorkgroupsIndirect(m.buffer, b[1] + b[2] * 0x100000000);
            } else pass.dispatchWorkgroups(b[0], b[1], b[2]);
        }

        /**
         * vkCmdClearAttachments: in the render pass, a draw over each rectangle
         * writing the value into the one attachment (the others masked)
         */
        clearAttachments(d) {
            const pass = this.pass, info = this.passInfo;
            if (!pass || !info) return;
            const colors = info.colors.map(c => c && this.format(c.format));
            const depthFormat = info.depth ? this.format(info.depth.format) : null;
            for (const a of d.attachments) {
                const color = a.aspect & ASPECT.COLOR;
                if (color && !colors[a.index]) continue;
                const key = "clear:" + colors.map(f => f ? f.gpu : "-").join(",") + ":" + (depthFormat ? depthFormat.gpu : "") + ":" +
                    info.samples + ":" + (color ? "c" + a.index : "d" + (a.aspect & (ASPECT.DEPTH | ASPECT.STENCIL)));
                let p = this.pipelines.get(key);
                if (!p) {
                    const type = f => f.uint ? "u32" : f.sint ? "i32" : "f32";
                    const outputs = colors.map((f, i) => f ? "@location(" + i + ") c" + i + ": vec4<" + type(f) + ">" : null).filter(x => x);
                    const values = colors.map((f, i) => !f ? null : "c" + i + " = " + (i === a.index ?
                        (f.uint ? "value.bits" : f.sint ? "bitcast<vec4<i32>>(value.bits)" : "bitcast<vec4<f32>>(value.bits)") : "vec4<" + type(f) + ">()") + ";").filter(x => x);
                    // (depth written only where there is depth: a stencil8 attachment has none; nothing to
                    // return when nothing is written, the value still used, for the bind group)
                    const writesDepth = !color && depthFormat && depthFormat.hasDepth;
                    if (writesDepth) outputs.push("@builtin(frag_depth) depth: f32");
                    const code = [
                        "struct Value { bits: vec4<u32>, depth: f32 };",
                        "@group(0) @binding(0) var<uniform> value: Value;",
                        outputs.length ? "struct Out { " + outputs.join(", ") + " };" : "",
                        "@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {",
                        "    let corner = vec2f(f32(i & 1u), f32(i >> 1u));",
                        "    return vec4f(corner * 2.0 - 1.0, 0.0, 1.0);",
                        "}",
                        outputs.length ? "@fragment fn fs() -> Out {" : "@fragment fn fs() {",
                        "    _ = value;",
                        outputs.length ? "    var out: Out;" : "",
                        ...values.map(v => "    out." + v),
                        writesDepth ? "    out.depth = value.depth;" : "",
                        outputs.length ? "    return out;" : "",
                        "}",
                    ].join("\n");
                    const module = this.device.createShaderModule({ code });
                    const descriptor = {
                        layout: "auto",
                        vertex: { module, entryPoint: "vs" },
                        fragment: { module, entryPoint: "fs", targets: colors.map((f, i) => f ? { format: f.gpu, writeMask: color && i === a.index ? alphaMask(f) : 0 } : null) },
                        primitive: { topology: "triangle-strip" },
                        multisample: { count: info.samples > 1 ? 4 : 1 },
                    };
                    if (depthFormat) {
                        const depthToo = !color && a.aspect & ASPECT.DEPTH, stencilToo = !color && a.aspect & ASPECT.STENCIL;
                        descriptor.depthStencil = { format: depthFormat.gpu, depthWriteEnabled: !!depthToo && depthFormat.hasDepth, depthCompare: "always" };
                        if (depthFormat.hasStencil) {
                            const face = { compare: "always", passOp: stencilToo ? "replace" : "keep", failOp: "keep", depthFailOp: "keep" };
                            Object.assign(descriptor.depthStencil, { stencilFront: face, stencilBack: face, stencilWriteMask: stencilToo ? 0xFF : 0 });
                        }
                    }
                    p = this.device.createRenderPipeline(descriptor);
                    this.pipelines.set(key, p);
                }
                const bytes = new Uint32Array(8);
                bytes.set(a.clear.slice(0, 4));
                if (!color) {
                    new Float32Array(bytes.buffer, 16, 1)[0] = f32(a.clear[0]);
                }
                const ubo = this.device.createBuffer({ size: 32, usage: BUFFER.UNIFORM | BUFFER.COPY_DST });
                this.device.queue.writeBuffer(ubo, 0, bytes);
                this.transient.push(ubo);
                const group = this.device.createBindGroup({ layout: p.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: ubo } }] });
                pass.setPipeline(p);
                pass.setBindGroup(0, group);
                if (!color && a.aspect & ASPECT.STENCIL) pass.setStencilReference(a.clear[1]);
                for (const r of d.rects) {
                    const x0 = Math.max(0, r.x), y0 = Math.max(0, r.y);
                    const x1 = Math.min(this.state.passWidth, r.x + r.width), y1 = Math.min(this.state.passHeight, r.y + r.height);
                    if (x1 <= x0 || y1 <= y0) continue;
                    pass.setViewport(x0, y0, x1 - x0, y1 - y0, 0, 1);
                    pass.setScissorRect(x0, y0, x1 - x0, y1 - y0);
                    pass.draw(4);
                }
            }
        }
    }

    const api = { VXExecutor, VX, VX_MAGIC };
    if (typeof module === "object" && module.exports) module.exports = api;
    else global.V86VXExecutor = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                                                                                                                                                                source/v64/src/browser/glbridge/webgpu_compositor.js                                                0000644 0000000 0000000 00000053462 00000000000 020034  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // One canvas for the whole screen (docs/display-design.md).
// The scanout -- whatever the guest's display device shows: text or
// graphics, drawn by src/browser/screen.js -- lives in a texture, and every
// guest D3D/GL surface is a window layer composited on top of it in guest
// desktop coordinates, clipped to the part of it the guest reports visible.
//
// The executors are unaware of this: each layer hands them a canvas-like
// object whose WebGPU context returns the layer's texture from
// getCurrentTexture(), and a host view that shares the compositor's device.
// What they "present" is what the next composition samples.

(function(global) {
    "use strict";

    const USAGE_COPY_SRC = 0x01;
    const USAGE_COPY_DST = 0x02;
    const USAGE_TEXTURE_BINDING = 0x04;
    const USAGE_UNIFORM = 0x40;
    const USAGE_RENDER_ATTACHMENT = 0x10;
    const BUFFER_USAGE_COPY_DST = 0x08;

    const COMPOSE_WGSL = `
struct Quad { dst: vec4<f32>, uv: vec4<f32> };
@group(0) @binding(0) var<uniform> quad: Quad;
@group(0) @binding(1) var source: texture_2d<f32>;
@group(0) @binding(2) var source_sampler: sampler;

struct VSOut {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> VSOut {
    var corners = array<vec2<f32>, 6>(
        vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0),
        vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0));
    let c = corners[index];
    var out: VSOut;
    out.position = vec4<f32>(mix(quad.dst.x, quad.dst.z, c.x), mix(quad.dst.y, quad.dst.w, c.y), 0.0, 1.0);
    out.uv = vec2<f32>(mix(quad.uv.x, quad.uv.z, c.x), mix(quad.uv.y, quad.uv.w, c.y));
    return out;
}

@fragment
fn fs_main(in: VSOut) -> @location(0) vec4<f32> {
    return vec4<f32>(textureSample(source, source_sampler, in.uv).rgb, 1.0);
}
`;

    function srgbSiblingOf(format) {
        const host = global.V86GPUHost;
        if (host && host.srgbSiblingOf) return host.srgbSiblingOf(format);
        if (format === "bgra8unorm") return "bgra8unorm-srgb";
        if (format === "rgba8unorm") return "rgba8unorm-srgb";
        return null;
    }

    /* What an executor sees as its canvas: a size and a WebGPU context. */
    class LayerCanvas {
        constructor(layer) {
            this.layer = layer;
            this.widthValue = 1;
            this.heightValue = 1;
            this.style = {};
        }
        get width() { return this.widthValue; }
        set width(value) { this.widthValue = Math.max(1, value | 0); }
        get height() { return this.heightValue; }
        set height(value) { this.heightValue = Math.max(1, value | 0); }
        getContext(type) { return type === "webgpu" ? this.layer.context : null; }
    }

    /* What an executor sees as its canvas context. Unlike a real one, the
     * texture persists between frames, which only matters to an executor
     * that relied on a fresh texture being cleared: every one of them either
     * copies a whole back buffer in or clears the pass. */
    class LayerContext {
        constructor(layer) {
            this.layer = layer;
            this.canvas = layer.canvas;
            this.configuration = null;
        }
        configure(configuration) { this.configuration = configuration || null; }
        unconfigure() { this.configuration = null; }
        getConfiguration() { return this.configuration; }
        getCurrentTexture() { return this.layer.currentTexture(); }
    }

    class WindowLayer {
        constructor(compositor, name, z) {
            this.compositor = compositor;
            this.name = name;
            this.z = z;
            this.canvas = new LayerCanvas(this);
            this.context = new LayerContext(this);
            this.x = 0;
            this.y = 0;
            this.width = 0;
            this.height = 0;
            this.visible = false;
            // Visible part of the layer as fractions of it, or null for all of it
            this.clip = null;
            // Where other guest windows leave it showing: rectangles as
            // fractions of the layer, or null for everywhere (within the clip)
            this.visibleRegion = null;
            this.texture = null;
            this.textureDevice = null;
            this.bindGroup = null;
            this.uniform = null;
            this.destroyed = false;
            this.host = compositor.hostViewFor(this);
        }

        currentTexture() {
            const compositor = this.compositor;
            const device = compositor.device;
            if (!device) throw new Error("the compositor has no WebGPU device");
            const width = this.canvas.width, height = this.canvas.height;
            if (!this.texture || this.textureDevice !== device ||
                    this.texture.width !== width || this.texture.height !== height) {
                const configuration = this.context.configuration || {};
                const format = configuration.format || compositor.format;
                const sibling = srgbSiblingOf(format);
                this.texture = device.createTexture({
                    label: "v86 window layer " + this.name,
                    size: { width, height, depthOrArrayLayers: 1 },
                    format,
                    ...(configuration.viewFormats || sibling ?
                        { viewFormats: configuration.viewFormats || [sibling] } : {}),
                    usage: USAGE_RENDER_ATTACHMENT | USAGE_COPY_SRC | USAGE_COPY_DST |
                        USAGE_TEXTURE_BINDING,
                });
                this.textureDevice = device;
                this.bindGroup = null;
            }
            compositor.scheduleCompose();
            return this.texture;
        }

        /**
         * Where the layer goes, in guest desktop pixels (the canvas's pixels)
         */
        place(x, y, width, height, visible) {
            const changed = x !== this.x || y !== this.y || width !== this.width ||
                height !== this.height || !!visible !== this.visible;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.visible = !!visible;
            if (changed) this.compositor.scheduleCompose();
        }

        /**
         * @param {{left:number, top:number, right:number, bottom:number}|null} clip
         *        the visible part as fractions of the layer
         */
        setClip(clip) {
            this.clip = clip;
            this.compositor.scheduleCompose();
        }

        /**
         * @param {Array<{left:number, top:number, right:number, bottom:number}>|null} rects
         *        the parts other guest windows leave showing, as fractions of
         *        the layer; null for all of it
         */
        setVisibleRegion(rects) {
            this.visibleRegion = rects;
            this.compositor.scheduleCompose();
        }

        destroy() {
            this.destroyed = true;
            this.visible = false;
            this.compositor.removeLayer(this);
        }
    }

    class V86WebGPUCompositor {
        constructor(canvas, options) {
            this.canvas = canvas;
            this.options = options || {};
            this.host = null;
            this.device = null;
            this.context = null;
            this.format = null;
            this.layers = [];
            this.nextZ = 0;
            this.scanout = null;
            this.scanoutWidth = 0;
            this.scanoutHeight = 0;
            this.scanoutBindGroup = null;
            this.scanoutUniform = null;
            this.scanoutDirty = true;
            this.composeScheduled = false;
            this.presenter = null;
            this.destroyed = false;
            this.stats = { compositions: 0, uploads: 0, uploadBytes: 0 };
        }

        get attached() { return !!this.device; }

        /* ---- the device ---- */

        /* Adopt the host now, so that executors created before it is ready
         * already share its device; attach() waits for it. */
        useHost(host) {
            if (this.host === host) return;
            this.detach();
            this.host = host;
        }

        async attach(host) {
            this.useHost(host);
            await host.initialize();
            if (this.destroyed || this.host !== host) return;
            this.setupDevice();
            host.onDeviceLost(() => {
                if (this.host === host) this.setupDevice();
            });
        }

        /** Stop using the device (it is about to be destroyed) */
        detach() {
            this.device = null;
            this.context = null;
            this.scanout = null;
            this.scanoutBindGroup = null;
            this.scanoutUniform = null;
            for (const layer of this.layers) {
                layer.texture = null;
                layer.bindGroup = null;
                layer.uniform = null;
            }
        }

        setupDevice() {
            const host = this.host;
            this.device = host.device;
            this.context = host.context;
            this.format = host.format;
            const module = this.device.createShaderModule({ label: "v86 compositor", code: COMPOSE_WGSL });
            this.pipeline = this.device.createRenderPipeline({
                label: "v86 compositor",
                layout: "auto",
                vertex: { module, entryPoint: "vs_main" },
                fragment: { module, entryPoint: "fs_main", targets: [{ format: this.format }] },
                primitive: { topology: "triangle-list" },
            });
            // The scanout is shown pixel for pixel; window layers may be scaled
            this.nearest = this.device.createSampler({ magFilter: "nearest", minFilter: "nearest" });
            this.linear = this.device.createSampler({ magFilter: "linear", minFilter: "linear" });
            this.scanout = null;
            this.scanoutBindGroup = null;
            this.scanoutUniform = null;
            for (const layer of this.layers) {
                layer.bindGroup = null;
                layer.uniform = null;
            }
            if (this.scanoutWidth && this.scanoutHeight) this.createScanout();
            // Everything that was in the old scanout texture has to be sent again
            if (this.presenter && typeof this.presenter["invalidate"] === "function")
                this.presenter["invalidate"]();
            this.scheduleCompose();
        }

        createScanout() {
            this.scanout = this.device.createTexture({
                label: "v86 scanout",
                size: { width: this.scanoutWidth, height: this.scanoutHeight, depthOrArrayLayers: 1 },
                format: "rgba8unorm",
                // RENDER_ATTACHMENT for clear(), which blanks it with a render pass
                usage: USAGE_COPY_DST | USAGE_TEXTURE_BINDING | USAGE_COPY_SRC | USAGE_RENDER_ATTACHMENT,
            });
            this.scanoutBindGroup = null;
            this.scanoutDirty = true;
        }

        /* ---- window layers ---- */

        createLayer(name) {
            const layer = new WindowLayer(this, name, this.nextZ++);
            this.layers.push(layer);
            return layer;
        }

        removeLayer(layer) {
            const index = this.layers.indexOf(layer);
            if (index >= 0) this.layers.splice(index, 1);
            this.scheduleCompose();
        }

        /* A host for one layer: the compositor's current host and device, but
         * the layer's own canvas and context, and no competition for the
         * presenter -- each layer is its own. */
        hostViewFor(layer) {
            const compositor = this;
            const overrides = {
                canvas: layer.canvas,
                context: layer.context,
                configureCanvas() {},
                resizeCanvas(width, height) {
                    const w = Math.max(1, width | 0), h = Math.max(1, height | 0);
                    if (layer.canvas.width === w && layer.canvas.height === h) return false;
                    layer.canvas.width = w;
                    layer.canvas.height = h;
                    return true;
                },
                claimPresenter() { return 1; },
                canPresent(token) { return !!token; },
                releasePresenter() {},
            };
            return new Proxy({}, {
                get(target, name) {
                    if (Object.prototype.hasOwnProperty.call(overrides, name)) return overrides[name];
                    const host = compositor.host;
                    if (!host) {
                        if (name === "initialize") return () => Promise.reject(new Error("the compositor has no WebGPU host"));
                        return undefined;
                    }
                    const value = host[name];
                    return typeof value === "function" ? value.bind(host) : value;
                },
                set(target, name, value) {
                    // Per layer, so that one executor cannot mark the shared host destroyed
                    overrides[name] = value;
                    return true;
                },
                has(target, name) {
                    return Object.prototype.hasOwnProperty.call(overrides, name) ||
                        !!(compositor.host && name in compositor.host);
                },
            });
        }

        /* ---- the presenter backend (src/browser/screen.js) ---- */

        attach_presenter(presenter) {
            this.presenter = presenter;
        }

        resize(width, height) {
            width = Math.max(1, width | 0);
            height = Math.max(1, height | 0);
            if (width === this.scanoutWidth && height === this.scanoutHeight) return;
            this.scanoutWidth = width;
            this.scanoutHeight = height;
            if (this.device) this.createScanout();
        }

        /**
         * Copy a rectangle of RGBA pixels into the scanout, like putImageData:
         * (sx, sy, sw, sh) of a buffer `stride` pixels wide and `rows` high
         * goes to (dx, dy), clipped to both.
         */
        put_pixels(data, stride, rows, sx, sy, sw, sh, dx, dy) {
            if (!this.scanout) return;
            if (dx < 0) { sx -= dx; sw += dx; dx = 0; }
            if (dy < 0) { sy -= dy; sh += dy; dy = 0; }
            if (sx < 0) { dx -= sx; sw += sx; sx = 0; }
            if (sy < 0) { dy -= sy; sh += sy; sy = 0; }
            sw = Math.min(sw, stride - sx, this.scanoutWidth - dx);
            sh = Math.min(sh, rows - sy, this.scanoutHeight - dy);
            if (sw <= 0 || sh <= 0) return;
            this.device.queue.writeTexture(
                { texture: this.scanout, origin: { x: dx, y: dy, z: 0 } },
                data,
                { offset: (sy * stride + sx) * 4, bytesPerRow: stride * 4, rowsPerImage: sh },
                { width: sw, height: sh, depthOrArrayLayers: 1 });
            this.stats.uploads++;
            this.stats.uploadBytes += sw * sh * 4;
            this.scanoutDirty = true;
        }

        clear() {
            if (!this.scanout) return;
            const encoder = this.device.createCommandEncoder();
            encoder.beginRenderPass({
                colorAttachments: [{ view: this.scanout.createView(), loadOp: "clear",
                    clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" }],
            }).end();
            this.device.queue.submit([encoder.finish()]);
            this.scanoutDirty = true;
        }

        /** The presenter finished a frame */
        present() {
            if (this.scanoutDirty || this.layers.some(layer => layer.visible))
                this.compose();
        }

        /** A data URL of the screen as it is composed right now */
        screenshot() {
            if (!this.compose()) return this.canvas.toDataURL("image/png");
            // Read in the same task as the composition, while the canvas still
            // holds its current texture: reading it later races the presentation
            return this.canvas.toDataURL("image/png");
        }

        screenshotImage() {
            const doc = this.canvas.ownerDocument || global.document;
            const image = new (doc.defaultView || global).Image();
            image.src = this.screenshot();
            return image;
        }

        /* ---- composition ---- */

        scheduleCompose() {
            if (this.composeScheduled || this.destroyed) return;
            this.composeScheduled = true;
            // After the synchronous stretch in which an executor acquired its
            // texture and submitted the frame into it
            queueMicrotask(() => {
                this.composeScheduled = false;
                this.compose();
            });
        }

        quadUniform(existing) {
            return existing || this.device.createBuffer({
                label: "v86 compositor quad", size: 32,
                usage: USAGE_UNIFORM | BUFFER_USAGE_COPY_DST,
            });
        }

        /**
         * @return {boolean} whether a frame was composed
         */
        compose() {
            if (this.destroyed || !this.device || !this.context || !this.scanout) return false;
            const width = this.canvas.width, height = this.canvas.height;
            if (!width || !height) return false;
            const device = this.device;
            let target;
            try {
                target = this.context.getCurrentTexture();
            } catch (error) {
                return false;
            }
            const toX = x => x / width * 2 - 1;
            const toY = y => 1 - y / height * 2;
            const encoder = device.createCommandEncoder({ label: "v86 compositor" });
            const pass = encoder.beginRenderPass({
                colorAttachments: [{ view: target.createView(), loadOp: "clear",
                    clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" }],
            });
            pass.setPipeline(this.pipeline);

            this.scanoutUniform = this.quadUniform(this.scanoutUniform);
            device.queue.writeBuffer(this.scanoutUniform, 0, new Float32Array([
                -1, 1, toX(this.scanoutWidth), toY(this.scanoutHeight), 0, 0, 1, 1]));
            if (!this.scanoutBindGroup) {
                this.scanoutBindGroup = device.createBindGroup({
                    layout: this.pipeline.getBindGroupLayout(0),
                    entries: [
                        { binding: 0, resource: { buffer: this.scanoutUniform } },
                        { binding: 1, resource: this.scanout.createView() },
                        { binding: 2, resource: this.nearest },
                    ],
                });
            }
            pass.setBindGroup(0, this.scanoutBindGroup);
            pass.draw(6);

            const layers = this.layers.filter(layer => layer.visible && layer.texture &&
                layer.textureDevice === device && layer.width > 0 && layer.height > 0)
                .sort((a, b) => a.z - b.z);
            for (const layer of layers) {
                const clip = layer.clip || { left: 0, top: 0, right: 1, bottom: 1 };
                const x0 = Math.max(0, Math.round(layer.x + clip.left * layer.width));
                const y0 = Math.max(0, Math.round(layer.y + clip.top * layer.height));
                const x1 = Math.min(width, Math.round(layer.x + clip.right * layer.width));
                const y1 = Math.min(height, Math.round(layer.y + clip.bottom * layer.height));
                if (x1 <= x0 || y1 <= y0) continue;
                layer.uniform = this.quadUniform(layer.uniform);
                device.queue.writeBuffer(layer.uniform, 0, new Float32Array([
                    toX(layer.x), toY(layer.y), toX(layer.x + layer.width), toY(layer.y + layer.height),
                    0, 0, 1, 1]));
                // A layer shown at its own size is copied pixel for pixel
                const sampler = layer.texture.width === layer.width &&
                    layer.texture.height === layer.height ? this.nearest : this.linear;
                if (!layer.bindGroup || layer.bindGroupSampler !== sampler) {
                    layer.bindGroup = device.createBindGroup({
                        layout: this.pipeline.getBindGroupLayout(0),
                        entries: [
                            { binding: 0, resource: { buffer: layer.uniform } },
                            { binding: 1, resource: layer.texture.createView() },
                            { binding: 2, resource: sampler },
                        ],
                    });
                    layer.bindGroupSampler = sampler;
                }
                pass.setBindGroup(0, layer.bindGroup);
                // Once per part the guest's other windows leave showing
                for (const part of layer.visibleRegion || [null]) {
                    let sx0 = x0, sy0 = y0, sx1 = x1, sy1 = y1;
                    if (part) {
                        sx0 = Math.max(sx0, Math.round(layer.x + part.left * layer.width));
                        sy0 = Math.max(sy0, Math.round(layer.y + part.top * layer.height));
                        sx1 = Math.min(sx1, Math.round(layer.x + part.right * layer.width));
                        sy1 = Math.min(sy1, Math.round(layer.y + part.bottom * layer.height));
                    }
                    if (sx1 <= sx0 || sy1 <= sy0) continue;
                    pass.setScissorRect(sx0, sy0, sx1 - sx0, sy1 - sy0);
                    pass.draw(6);
                }
            }
            pass.end();
            device.queue.submit([encoder.finish()]);
            this.scanoutDirty = false;
            this.stats.compositions++;
            return true;
        }

        destroy() {
            this.destroyed = true;
            this.detach();
            this.layers = [];
        }
    }

    const api = { V86WebGPUCompositor, WindowLayer, LayerCanvas };
    global.V86WebGPUCompositor = V86WebGPUCompositor;
    global.V86WebGPUCompositorAPI = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                                                                              source/v64/src/browser/glbridge/webgpu_host.js                                                      0000644 0000000 0000000 00000036543 00000000000 016614  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Shared WebGPU device/canvas ownership for every guest graphics frontend.
//
// Before this module each executor called requestAdapter()/requestDevice() and
// context.configure() for itself. That works only as long as exactly one of
// them ever runs: a GPUCanvasContext belongs to whichever device configured it
// last, so two executors sharing one canvas element silently drop one of the
// two frame streams (v86_network_bridge.js carries a long comment about
// exactly that hazard). Adding OpenGL as a third stream would have made it a
// three-way race.
//
// So the device, the canvas context and its configuration have one owner. The
// executors ask for it and get the same objects back. Sharing a device also
// means a texture created by one executor is usable by the other, which is
// what makes a future "GDI/DirectDraw surface composited under a GL overlay"
// possible at all -- separate devices could never do that.
//
// The three-way race was not hypothetical. This module shipped with only the
// OpenGL executor using it, while D3D8 and D3D9/DDraw kept acquiring their own
// devices -- and since DDraw drives the Windows desktop, the canvas was always
// already configured by the D3D9 device before any GL app started. Every
// OpenGL present pass then died with
//
//   [TextureView of Texture "...WebgpuSwapChainTexture..."] is associated with
//   [Device], and cannot be used with [Device]
//
// All three now acquire through here. tests/webgpu_shared_device_test.js
// builds all three on one canvas and asserts they land on one device, because
// each executor's own suite only ever constructs one and so cannot see this.
//
// See docs/opengl-webgpu-implementation-plan.zh-CN.md section 4.2.

(function(global) {
    "use strict";

    const TEXTURE_USAGE_COPY_SRC = 0x01;
    const TEXTURE_USAGE_COPY_DST = 0x02;
    const TEXTURE_USAGE_TEXTURE_BINDING = 0x04;
    const TEXTURE_USAGE_RENDER_ATTACHMENT = 0x10;

    // The union of what d3d9_executor.js and gl_executor.js each ask for. It is
    // one list rather than a per-caller negotiation because a GPUDevice's
    // feature set is fixed at creation: if the first caller asked for less, the
    // second would need a *different* device, which is the thing this module
    // exists to prevent. Every entry is optional -- an adapter that lacks one
    // simply does not get it, and the executors check deviceFeatures.
    const DEFAULT_FEATURES = [
        "texture-compression-bc",
        "float32-filterable",
        "float32-blendable",
        "timestamp-query",
        // GL_DEPTH_CLAMP / D3D9's clipping disable. Optional everywhere today.
        "depth-clip-control",
        // Real user clip planes instead of the fragment-discard emulation
        // (plan deviation D-05). Not yet shipping in any browser; asking for it
        // costs nothing when absent.
        "clip-distances",
        // VMware SVGA's DX contexts (gx_executor.js): D24/D32 with stencil
        // 8 of D3D10's formats, SRC1 blend factors, DrawInstancedIndirect's
        // first instance
        "depth32float-stencil8",
        "dual-source-blending",
        "rg11b10ufloat-renderable",
        "indirect-first-instance",
        "texture-compression-bc-sliced-3d",
        // D3D11's typed UAVs of B8G8R8A8
        "bgra8unorm-storage",
        // GLES 3.0's ETC2 and EAC, GLES 3.2's ASTC (the GLES executor, src/gles/page/gles3_executor.js)
        "texture-compression-etc2",
        "texture-compression-astc",
        // GLES 3.0's TEXTURE_SWIZZLE_*
        "texture-component-swizzle",
    ];

    // Limits raised to what the adapter allows: D3D10 has 8 render targets
    // of up to 16 bytes a pixel, 32 varyings, 128 textures and 16 samplers a
    // stage, 16 vertex buffers; D3D11 16384 texels a side, 8 (64) UAVs,
    // thread groups of 1024 with 32 KiB shared (gx_executor.js). Higher
    // limits cost nothing to the executors that need less.
    const RAISED_LIMITS = [
        "maxColorAttachmentBytesPerSample", "maxInterStageShaderVariables", "maxSampledTexturesPerShaderStage",
        "maxSamplersPerShaderStage", "maxStorageBuffersPerShaderStage", "maxUniformBuffersPerShaderStage",
        "maxVertexBuffers", "maxVertexAttributes", "maxBindingsPerBindGroup", "maxTextureArrayLayers",
        "maxStorageBufferBindingSize", "maxBufferSize",
        "maxTextureDimension1D", "maxTextureDimension2D", "maxTextureDimension3D", "maxStorageTexturesPerShaderStage",
        "maxComputeWorkgroupStorageSize", "maxComputeInvocationsPerWorkgroup", "maxComputeWorkgroupSizeX",
        "maxComputeWorkgroupSizeY", "maxComputeWorkgroupSizeZ", "maxComputeWorkgroupsPerDimension",
    ];

    function srgbSiblingOf(format) {
        if (format === "bgra8unorm") return "bgra8unorm-srgb";
        if (format === "rgba8unorm") return "rgba8unorm-srgb";
        return null;
    }

    class V86GPUHost {
        constructor(canvas, options) {
            this.canvas = canvas;
            this.options = options || {};
            this.gpu = this.options.gpu ||
                (global.navigator && global.navigator.gpu);
            this.adapter = this.options.adapter || null;
            this.device = this.options.device || null;
            this.context = this.options.context || null;
            this.format = this.options.format || null;
            this.swapchainSrgbFormat = null;
            this.deviceFeatures = null;
            this.readyPromise = null;
            this.failed = null;
            // name -> token. A presenter owns the swap chain; see claimPresenter.
            this.presenter = null;
            this.presenterToken = 0;
            this.nextPresenterToken = 1;
            this.deviceLostHandlers = new Set();
            this.generation = 0;
        }

        initialize() {
            if (this.readyPromise) return this.readyPromise;
            this.readyPromise = (async () => {
                if (!this.device) {
                    if (!this.gpu || typeof this.gpu.requestAdapter !== "function")
                        throw new Error("WebGPU is unavailable");
                    this.adapter = this.adapter || await this.gpu.requestAdapter({
                        powerPreference: "high-performance",
                    });
                    if (!this.adapter)
                        throw new Error("WebGPU adapter request failed");
                    const requested = [];
                    const available = this.adapter.features;
                    const supports = name => !!(available &&
                        typeof available.has === "function" && available.has(name));
                    const wanted = this.options.requiredFeatures || DEFAULT_FEATURES;
                    for (const name of wanted) {
                        if (supports(name)) requested.push(name);
                    }
                    const requiredLimits = {};
                    const limits = this.adapter.limits || {};
                    for (const name of RAISED_LIMITS) {
                        if (typeof limits[name] === "number") requiredLimits[name] = limits[name];
                    }
                    this.device = await this.adapter.requestDevice({
                        ...(requested.length ? { requiredFeatures: requested } : {}),
                        requiredLimits,
                    });
                }
                this.deviceFeatures = this.featureFlags();
                this.limits = this.device.limits || (this.adapter && this.adapter.limits) || {};
                this.configureCanvas();
                this.watchForDeviceLoss();
                return this;
            })().catch(error => {
                this.failed = error;
                console.error("[webgpu-host] initialization failed", error);
                throw error;
            });
            return this.readyPromise;
        }

        featureFlags() {
            const features = this.device && this.device.features;
            const has = name => !!(features &&
                typeof features.has === "function" && features.has(name));
            return {
                bc: has("texture-compression-bc"),
                float32Filterable: has("float32-filterable"),
                float32Blendable: has("float32-blendable"),
                timestampQuery: has("timestamp-query"),
                depthClipControl: has("depth-clip-control"),
                clipDistances: has("clip-distances"),
                depth32Stencil8: has("depth32float-stencil8"),
                dualSourceBlending: has("dual-source-blending"),
                bgra8unormStorage: has("bgra8unorm-storage"),
            };
        }

        configureCanvas() {
            if (!this.canvas) return;
            this.context = this.context ||
                (typeof this.canvas.getContext === "function" ?
                    this.canvas.getContext("webgpu") : null);
            if (!this.context)
                throw new Error("could not acquire a WebGPU canvas context");
            this.format = this.format || (this.gpu &&
                typeof this.gpu.getPreferredCanvasFormat === "function" ?
                this.gpu.getPreferredCanvasFormat() : "bgra8unorm");
            this.swapchainSrgbFormat = srgbSiblingOf(this.format);
            // Same usage set d3d9_executor.js has always configured: a canvas
            // context defaults to RENDER_ATTACHMENT alone, but both backends
            // copy into and sample from the swap-chain texture (GL's
            // glCopyTexImage2D from the back buffer, D3D9's StretchRect
            // post-processing), so the extra usages are not optional.
            this.context.configure({
                device: this.device,
                format: this.format,
                ...(this.swapchainSrgbFormat ?
                    { viewFormats: [this.swapchainSrgbFormat] } : {}),
                alphaMode: "opaque",
                usage: TEXTURE_USAGE_RENDER_ATTACHMENT | TEXTURE_USAGE_COPY_SRC |
                    TEXTURE_USAGE_COPY_DST | TEXTURE_USAGE_TEXTURE_BINDING,
            });
        }

        /*
         * A presenter owns the swap chain. Only one may at a time, because
         * getCurrentTexture() hands out the same texture to whoever asks and
         * the last render into it before the frame ends is what the user sees.
         *
         * A game process loads exactly one of opengl32.dll / d3d8.dll /
         * d3d9.dll / ddraw.dll, so in practice nobody ever contends. The point
         * of the token is that when the deployment rule *is* violated, the
         * second claimant learns about it in one console line instead of by
         * having its frames silently disappear. It keeps rendering into its own
         * back buffer either way, so getStats()/dumpSmallTextures() still work.
         */
        claimPresenter(name) {
            if (this.presenter && this.presenter !== name) {
                if (!this.presenterConflictReported) {
                    this.presenterConflictReported = true;
                    console.error("[webgpu-host] two graphics APIs are both " +
                        "presenting to the same canvas; only the first keeps " +
                        "the swap chain. A game directory must contain exactly " +
                        "one of opengl32.dll/d3d8.dll/d3d9.dll/ddraw.dll.", {
                            owner: this.presenter,
                            rejected: name,
                        });
                }
                return 0;
            }
            if (!this.presenter) {
                this.presenter = name;
                this.presenterToken = this.nextPresenterToken++;
            }
            return this.presenterToken;
        }

        releasePresenter(token) {
            if (token && token === this.presenterToken) {
                this.presenter = null;
                this.presenterToken = 0;
                this.presenterConflictReported = false;
            }
        }

        canPresent(token) {
            return !!token && token === this.presenterToken;
        }

        /* Executors register here instead of each attaching to device.lost, so
         * that recovery happens once and in a defined order: the host rebuilds
         * the device and reconfigures the canvas, then every executor rebuilds
         * its own resources against the new device. */
        onDeviceLost(handler) {
            this.deviceLostHandlers.add(handler);
            return () => this.deviceLostHandlers.delete(handler);
        }

        watchForDeviceLoss() {
            const device = this.device;
            if (!device || !device.lost || typeof device.lost.then !== "function")
                return;
            device.lost.then(info => {
                if (this.device !== device) return;   // already replaced
                if (info && info.reason === "destroyed") return;
                console.error("[webgpu-host] GPUDevice lost", info && info.message);
                this.recover();
            }).catch(() => { /* a destroyed device rejecting is not an error */ });
        }

        async recover() {
            if (this.destroyed) return;
            if (this.recovering) return this.recovering;
            this.recovering = (async () => {
                this.device = null;
                this.context = null;
                this.format = this.options.format || null;
                this.readyPromise = null;
                ++this.generation;
                await this.initialize();
                for (const handler of Array.from(this.deviceLostHandlers)) {
                    try {
                        await handler(this);
                    } catch (error) {
                        console.error("[webgpu-host] device-loss handler failed",
                            error);
                    }
                }
            })().finally(() => { this.recovering = null; });
            return this.recovering;
        }

        /* Canvas size is a shared resource too: whichever executor owns the
         * presenter decides it, and the other must not fight over it. */
        resizeCanvas(width, height) {
            const w = Math.max(1, width | 0);
            const h = Math.max(1, height | 0);
            if (!this.canvas) return false;
            if (this.canvas.width === w && this.canvas.height === h) return false;
            this.canvas.width = w;
            this.canvas.height = h;
            return true;
        }
    }

    // One host per canvas element. Keyed weakly so a page that swaps canvases
    // (the state-restore path replaces the overlay element) does not leak.
    const hosts = new WeakMap();
    // Tests inject a fake canvas object that is not a real Element; a WeakMap
    // handles those identically, but the fallback list keeps a host reachable
    // when the caller passes null (headless executor tests).
    let nullCanvasHost = null;

    function acquire(canvas, options) {
        if (!canvas) {
            if (!nullCanvasHost) nullCanvasHost = new V86GPUHost(null, options);
            return nullCanvasHost;
        }
        let host = hosts.get(canvas);
        if (!host) {
            host = new V86GPUHost(canvas, options);
            hosts.set(canvas, host);
        }
        return host;
    }

    function reset(canvas) {
        if (!canvas) { nullCanvasHost = null; return; }
        hosts.delete(canvas);
    }

    const api = { V86GPUHost, acquire, reset, DEFAULT_FEATURES, srgbSiblingOf };
    global.V86GPUHost = api;
    if (typeof module !== "undefined" && module.exports) module.exports = api;
})(typeof globalThis !== "undefined" ? globalThis : this);
                                                                                                                                                             source/v64/src/browser/inbrowser_network.js                                                         0000644 0000000 0000000 00000003221 00000000000 016255  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // For Types Only
import { BusConnector } from "../bus.js";

/**
 * Network adapter "inbrowser" which connects the emulated NIC
 * to a shared in-browser BroadcastChannel.
 *
 * NOTE: BroadcastChannel.postMessage() sends the given message to
 *       *other* BroadcastChannel objects set up for the same channel.
 *       Since we use the same BroadcastChannel instance for both
 *       sending and receiving we do not receive copies of our
 *       own sent messages.
 *       Source: https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts
 *
 * @constructor
 *
 * @param {BusConnector} bus
 * @param {*=} config
 */
export function InBrowserNetworkAdapter(bus, config)
{
    const id = config.id || 0;

    this.bus = bus;
    this.bus_send_msgid = `net${id}-send`;
    this.bus_recv_msgid = `net${id}-receive`;
    this.channel = new BroadcastChannel(`v86-inbrowser-${id}`);
    this.is_open = true;

    // forward ethernet frames from emulated NIC to hub
    this.nic_to_hub_fn = (eth_frame) => {
        this.channel.postMessage(eth_frame);
    };
    this.bus.register(this.bus_send_msgid, this.nic_to_hub_fn, this);

    // forward ethernet frames from hub to emulated NIC
    this.hub_to_nic_fn = (ev) => {
        this.bus.send(this.bus_recv_msgid, ev.data);
    };
    this.channel.addEventListener("message", this.hub_to_nic_fn);
}

InBrowserNetworkAdapter.prototype.destroy = function()
{
    if(this.is_open) {
        this.bus.unregister(this.bus_send_msgid, this.nic_to_hub_fn);
        this.channel.removeEventListener("message", this.hub_to_nic_fn);
        this.channel.close();
        this.is_open = false;
    }
};
                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/keyboard.js                                                                  0000644 0000000 0000000 00000034377 00000000000 014312  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // For Types Only
import { BusConnector } from "../bus.js";

const SHIFT_SCAN_CODE = 0x2A;
const SCAN_CODE_RELEASE = 0x80;

const PLATFOM_WINDOWS = typeof window !== "undefined" && window.navigator.platform.toString().toLowerCase().search("win") >= 0;

/**
 * @constructor
 *
 * @param {BusConnector} bus
 */
export function KeyboardAdapter(bus)
{
    var
        /**
         * @type {!Object.<boolean>}
         */
        keys_pressed = {},

        /**
         * Deferred KeyboardEvent or null (Windows AltGr-Filter)
         * @type {KeyboardEvent|Object|null}
         */
        deferred_event = null,

        /**
         * Deferred keydown state (Windows AltGr-Filter)
         * @type {boolean}
         */
        deferred_keydown = false,

        /**
         * Timeout-ID returned by setTimeout() or 0 (Windows AltGr-Filter)
         * @type {number}
         */
        deferred_timeout_id = 0,

        keyboard = this;

    /**
     * Set by emulator
     * @type {boolean}
     */
    this.emu_enabled = true;

    // Format:
    // Javascript event.keyCode -> make code
    const charmap = new Uint16Array([
        0, 0, 0, 0,  0, 0, 0, 0,
        // 0x08: backspace, tab, enter
        0x0E, 0x0F, 0, 0,  0, 0x1C, 0, 0,

        // 0x10: shift, ctrl, alt, pause, caps lock
        0x2A, 0x1D, 0x38, 0,  0x3A, 0, 0, 0,

        // 0x18: escape
        0, 0, 0, 0x01,  0, 0, 0, 0,

        // 0x20: spacebar, page down/up, end, home, arrow keys, ins, del
        0x39, 0xE049, 0xE051, 0xE04F,  0xE047, 0xE04B, 0xE048, 0xE04D,
        0x50, 0, 0, 0,  0, 0x52, 0x53, 0,

        // 0x30: numbers
        0x0B, 0x02, 0x03, 0x04,  0x05, 0x06, 0x07, 0x08,
        0x09, 0x0A,

        // 0x3B: ;= (firefox only)
        0, 0x27, 0, 0x0D, 0, 0,

        // 0x40
        0,

        // 0x41: letters
        0x1E, 0x30, 0x2E, 0x20, 0x12, 0x21, 0x22, 0x23, 0x17, 0x24, 0x25, 0x26, 0x32,
        0x31, 0x18, 0x19, 0x10, 0x13, 0x1F, 0x14, 0x16, 0x2F, 0x11, 0x2D, 0x15, 0x2C,

        // 0x5B: Left Win, Right Win, Menu
        0xE05B, 0xE05C, 0xE05D, 0, 0,

        // 0x60: keypad
        0x52, 0x4F, 0x50, 0x51, 0x4B, 0x4C, 0x4D, 0x47,
        0x48, 0x49, 0, 0, 0, 0, 0, 0,

        // 0x70: F1 to F12
        0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x57, 0x58,

        0, 0, 0, 0,

        // 0x80
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,

        // 0x90: Numlock
        0x45, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,     0, 0, 0, 0,

        // 0xA0: - (firefox only)
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0x0C, 0, 0,

        // 0xB0
        // ,
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0x27, 0x0D,  0x33, 0x0C, 0x34, 0x35,

        // 0xC0
        // `
        0x29, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,     0, 0, 0, 0,

        // 0xD0
        // [']\
        0, 0, 0, 0,     0, 0, 0, 0,
        0, 0, 0, 0x1A,  0x2B, 0x1B, 0x28, 0,

        // 0xE0
        // Apple key on Gecko, Right alt
        0xE05B, 0xE038, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,            0, 0, 0, 0,
    ]);


    // ascii -> javascript event code (US layout)
    const asciimap = {8: 8, 10: 13, 32: 32, 39: 222, 44: 188, 45: 189, 46: 190, 47: 191, 48: 48, 49: 49, 50: 50, 51: 51, 52: 52, 53: 53, 54: 54, 55: 55, 56: 56, 57: 57, 59: 186, 61: 187, 91: 219, 92: 220, 93: 221, 96: 192, 97: 65, 98: 66, 99: 67, 100: 68, 101: 69, 102: 70, 103: 71, 104: 72, 105: 73, 106: 74, 107: 75, 108: 76, 109: 77, 110: 78, 111: 79, 112: 80, 113: 81, 114: 82, 115: 83, 116: 84, 117: 85, 118: 86, 119: 87, 120: 88, 121: 89, 122: 90};
    const asciimap_shift = {33: 49, 34: 222, 35: 51, 36: 52, 37: 53, 38: 55, 40: 57, 41: 48, 42: 56, 43: 187, 58: 186, 60: 188, 62: 190, 63: 191, 64: 50, 65: 65, 66: 66, 67: 67, 68: 68, 69: 69, 70: 70, 71: 71, 72: 72, 73: 73, 74: 74, 75: 75, 76: 76, 77: 77, 78: 78, 79: 79, 80: 80, 81: 81, 82: 82, 83: 83, 84: 84, 85: 85, 86: 86, 87: 87, 88: 88, 89: 89, 90: 90, 94: 54, 95: 189, 123: 219, 124: 220, 125: 221, 126: 192};

    // From:
    // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code#Code_values_on_Linux_%28X11%29_%28When_scancode_is_available%29
    // http://stanislavs.org/helppc/make_codes.html
    // http://www.computer-engineering.org/ps2keyboard/scancodes1.html
    //
    // Mapping from event.code to scancode
    var codemap = {
        "Escape": 0x0001,
        "Digit1": 0x0002,
        "Digit2": 0x0003,
        "Digit3": 0x0004,
        "Digit4": 0x0005,
        "Digit5": 0x0006,
        "Digit6": 0x0007,
        "Digit7": 0x0008,
        "Digit8": 0x0009,
        "Digit9": 0x000a,
        "Digit0": 0x000b,
        "Minus": 0x000c,
        "Equal": 0x000d,
        "Backspace": 0x000e,
        "Tab": 0x000f,
        "KeyQ": 0x0010,
        "KeyW": 0x0011,
        "KeyE": 0x0012,
        "KeyR": 0x0013,
        "KeyT": 0x0014,
        "KeyY": 0x0015,
        "KeyU": 0x0016,
        "KeyI": 0x0017,
        "KeyO": 0x0018,
        "KeyP": 0x0019,
        "BracketLeft": 0x001a,
        "BracketRight": 0x001b,
        "Enter": 0x001c,
        "ControlLeft": 0x001d,
        "KeyA": 0x001e,
        "KeyS": 0x001f,
        "KeyD": 0x0020,
        "KeyF": 0x0021,
        "KeyG": 0x0022,
        "KeyH": 0x0023,
        "KeyJ": 0x0024,
        "KeyK": 0x0025,
        "KeyL": 0x0026,
        "Semicolon": 0x0027,
        "Quote": 0x0028,
        "Backquote": 0x0029,
        "ShiftLeft": 0x002a,
        "Backslash": 0x002b,
        "KeyZ": 0x002c,
        "KeyX": 0x002d,
        "KeyC": 0x002e,
        "KeyV": 0x002f,
        "KeyB": 0x0030,
        "KeyN": 0x0031,
        "KeyM": 0x0032,
        "Comma": 0x0033,
        "Period": 0x0034,
        "Slash": 0x0035,
        "IntlRo": 0x0035,
        "ShiftRight": 0x0036,
        "NumpadMultiply": 0x0037,
        "AltLeft": 0x0038,
        "Space": 0x0039,
        "CapsLock": 0x003a,
        "F1": 0x003b,
        "F2": 0x003c,
        "F3": 0x003d,
        "F4": 0x003e,
        "F5": 0x003f,
        "F6": 0x0040,
        "F7": 0x0041,
        "F8": 0x0042,
        "F9": 0x0043,
        "F10": 0x0044,
        "NumLock": 0x0045,
        "ScrollLock": 0x0046,
        "Numpad7": 0x0047,
        "Numpad8": 0x0048,
        "Numpad9": 0x0049,
        "NumpadSubtract": 0x004a,
        "Numpad4": 0x004b,
        "Numpad5": 0x004c,
        "Numpad6": 0x004d,
        "NumpadAdd": 0x004e,
        "Numpad1": 0x004f,
        "Numpad2": 0x0050,
        "Numpad3": 0x0051,
        "Numpad0": 0x0052,
        "NumpadDecimal": 0x0053,
        "IntlBackslash": 0x0056,
        "F11": 0x0057,
        "F12": 0x0058,

        "NumpadEnter": 0xe01c,
        "ControlRight": 0xe01d,
        "NumpadDivide": 0xe035,
        //"PrintScreen": 0x0063,
        "AltRight": 0xe038,
        "Home": 0xe047,
        "ArrowUp": 0xe048,
        "PageUp": 0xe049,
        "ArrowLeft": 0xe04b,
        "ArrowRight": 0xe04d,
        "End": 0xe04f,
        "ArrowDown": 0xe050,
        "PageDown": 0xe051,
        "Insert": 0xe052,
        "Delete": 0xe053,

        "MetaLeft": 0xe05b,
        "OSLeft": 0xe05b,
        "MetaRight": 0xe05c,
        "OSRight": 0xe05c,
        "ContextMenu": 0xe05d,
    };

    this.bus = bus;

    this.destroy = function()
    {
        if(typeof window !== "undefined")
        {
            window.removeEventListener("keyup", keyup_handler, false);
            window.removeEventListener("keydown", keydown_handler, false);
            window.removeEventListener("blur", blur_handler, false);
            window.removeEventListener("input", input_handler, false);
        }
    };

    this.init = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        this.destroy();

        window.addEventListener("keyup", keyup_handler, false);
        window.addEventListener("keydown", keydown_handler, false);
        window.addEventListener("blur", blur_handler, false);
        window.addEventListener("input", input_handler, false);
    };
    this.init();

    this.simulate_press = function(code)
    {
        var ev = { keyCode: code };
        handler(ev, true);
        handler(ev, false);
    };

    this.simulate_char = function(chr)
    {
        var code = chr.charCodeAt(0);

        if(code in asciimap)
        {
            this.simulate_press(asciimap[code]);
        }
        else if(code in asciimap_shift)
        {
            send_to_controller(SHIFT_SCAN_CODE);
            this.simulate_press(asciimap_shift[code]);
            send_to_controller(SHIFT_SCAN_CODE | SCAN_CODE_RELEASE);
        }
        else
        {
            console.log("ascii -> keyCode not found: ", code, chr);
        }
    };

    function may_handle(e)
    {
        if(e.shiftKey && e.ctrlKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 75))
        {
              // don't prevent opening chromium dev tools
              // maybe add other important combinations here, too
              return false;
        }

        if(!keyboard.emu_enabled)
        {
            return false;
        }

        if(e.target)
        {
            // className shouldn't be hardcoded here
            return e.target.classList.contains("phone_keyboard") ||
                (e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA");
        }
        else
        {
            return true;
        }
    }

    function translate(e)
    {
        if(e.code !== undefined)
        {
            var code = codemap[e.code];

            if(code !== undefined)
            {
                return code;
            }
        }

        return charmap[e.keyCode];
    }

    function keyup_handler(e)
    {
        if(!e.altKey && keys_pressed[0x38])
        {
            // trigger ALT keyup manually - some browsers don't
            // see issue #165
            handle_code(0x38, false);
        }
        return handler(e, false);
    }

    function keydown_handler(e)
    {
        if(!e.altKey && keys_pressed[0x38])
        {
            // trigger ALT keyup manually - some browsers don't
            // see issue #165
            handle_code(0x38, false);
        }
        return handler(e, true);
    }

    function blur_handler(e)
    {
        // trigger keyup for all pressed keys
        var keys = Object.keys(keys_pressed),
            key;

        for(var i = 0; i < keys.length; i++)
        {
            key = +keys[i];

            if(keys_pressed[key])
            {
                handle_code(key, false);
            }
        }

        keys_pressed = {};
    }

    function input_handler(e)
    {
        if(!keyboard.bus)
        {
            return;
        }

        if(!may_handle(e))
        {
            return;
        }

        switch(e.inputType)
        {
            case "insertText":
                for(var i = 0; i < e.data.length; i++)
                {
                    keyboard.simulate_char(e.data[i]);
                }
                break;

            case "insertLineBreak":
                keyboard.simulate_press(13); // enter
                break;

            case "deleteContentBackward":
                keyboard.simulate_press(8); // backspace
                break;
        }
    }

    /**
     * @param {KeyboardEvent|Object} e
     * @param {boolean} keydown
     */
    function handler(e, keydown)
    {
        if(!keyboard.bus)
        {
            return;
        }

        if(!may_handle(e))
        {
            return;
        }

        if(e.code === "" || e.key === "Process" || e.key === "Unidentified" || e.keyCode === 229)
        {
            // Handling mobile browsers and virtual keyboards
            return;
        }

        e.preventDefault && e.preventDefault();

        if(PLATFOM_WINDOWS)
        {
            // Remove ControlLeft from key sequence [ControlLeft, AltRight] when
            // AltGraph-key is pressed or released.
            //
            // NOTE: AltGraph is false for the 1st key (ControlLeft-Down), becomes
            // true with the 2nd (AltRight-Down) and stays true until key AltGraph
            // is released (AltRight-Up).
            if(deferred_event)
            {
                clearTimeout(deferred_timeout_id);
                if(!(e.getModifierState && e.getModifierState("AltGraph") &&
                        deferred_keydown === keydown &&
                        deferred_event.code === "ControlLeft" && e.code === "AltRight"))
                {
                    handle_event(deferred_event, deferred_keydown);
                }
                deferred_event = null;
            }

            if(e.code === "ControlLeft")
            {
                // defer ControlLeft-Down/-Up until the next invocation of this method or 10ms have passed, whichever comes first
                deferred_event = e;
                deferred_keydown = keydown;
                deferred_timeout_id = setTimeout(() => {
                    handle_event(deferred_event, deferred_keydown);
                    deferred_event = null;
                }, 10);
                return false;
            }
        }

        handle_event(e, keydown);
        return false;
    }

    /**
     * @param {KeyboardEvent|Object} e
     * @param {boolean} keydown
     */
    function handle_event(e, keydown)
    {
        var code = translate(e);

        if(!code)
        {
            console.log("Missing char in map: keyCode=" + (e.keyCode || -1).toString(16) + " code=" + e.code);
            return;
        }

        handle_code(code, keydown, e.repeat);
    }

    /**
     * @param {number} code
     * @param {boolean} keydown
     * @param {boolean=} is_repeat
     */
    function handle_code(code, keydown, is_repeat)
    {
        if(keydown)
        {
            if(keys_pressed[code] && !is_repeat)
            {
                handle_code(code, false);
            }
        }
        else
        {
            if(!keys_pressed[code])
            {
                // stray keyup
                return;
            }
        }

        keys_pressed[code] = keydown;

        if(!keydown)
        {
            code |= 0x80;
        }
        //console.log("Key: " + code.toString(16) + " from " + chr.toString(16) + " down=" + keydown);

        if(code > 0xFF)
        {
            // prefix
            send_to_controller(code >> 8);
            send_to_controller(code & 0xFF);
        }
        else
        {
            send_to_controller(code);
        }
    }

    function send_to_controller(code)
    {
        keyboard.bus.send("keyboard-code", code);
    }
}
                                                                                                                                                                                                                                                                 source/v64/src/browser/main.js                                                                      0000644 0000000 0000000 00000171311 00000000000 013424  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { V86 } from "./starter.js";
import { LOG_NAMES } from "../const.js";
import { SyncBuffer, SyncFileBuffer } from "../buffer.js";
import { h, pad0, pads, hex_dump, dump_file, download } from "../lib.js";
import { log_data, LOG_LEVEL, set_log_level } from "../log.js";
import * as iso9660 from "../iso9660.js";
import { DEFAULT_CPU_CORES, DEFAULT_GRAPHICS_ADAPTER, MAX_ARRAY_BUFFER_SIZE_MB, settings_to_options } from "./vm_options.js";
import { bool_arg, cpu_type_arg, machine_type_arg, start_settings, format_query_args } from "./query_compat.js";


// (served from this computer: the local network relay)
const ON_LOCALHOST = ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname);

function query_append()
{
    const version = $("version");
    return version ? "?" + version.textContent : "";
}

function set_title(text)
{
    document.title = text + " - v86" +  (DEBUG ? " - debug" : "");
    const description = document.querySelector("meta[name=description]");
    description && (description.content = "Running " + text);
}

function format_timestamp(time)
{
    if(time < 60)
    {
        return time + "s";
    }
    else if(time < 3600)
    {
        return (time / 60 | 0) + "m " + pad0(time % 60, 2) + "s";
    }
    else
    {
        return (time / 3600 | 0) + "h " +
            pad0((time / 60 | 0) % 60, 2) + "m " +
            pad0(time % 60, 2) + "s";
    }
}

function read_file(file)
{
    return new Promise((resolve, reject) => {
        const fr = new FileReader();
        fr.onload = () => resolve(fr.result);
        fr.onerror = e => reject(e);
        fr.readAsArrayBuffer(file);
    });
}

let progress_ticks = 0;

function show_progress(e)
{
    const el = $("loading");
    el.style.display = "block";

    const file_name = e.file_name.split("?", 1)[0];

    if(file_name.endsWith(".wasm"))
    {
        const parts = file_name.split("/");
        el.textContent = "Fetching " + parts[parts.length - 1] + " ...";
        return;
    }

    if(e.file_index === e.file_count - 1 && e.loaded >= e.total - 2048)
    {
        // last file is (almost) loaded
        el.textContent = "Done downloading. Starting now ...";
        return;
    }

    let line = "Downloading images ";

    if(typeof e.file_index === "number" && e.file_count)
    {
        line += "[" + (e.file_index + 1) + "/" + e.file_count + "] ";
    }

    if(e.total && typeof e.loaded === "number")
    {
        var per100 = Math.floor(e.loaded / e.total * 100);
        per100 = Math.min(100, Math.max(0, per100));

        var per50 = Math.floor(per100 / 2);

        line += per100 + "% [";
        line += "#".repeat(per50);
        line += " ".repeat(50 - per50) + "]";
    }
    else
    {
        line += ".".repeat(progress_ticks++ % 50);
    }

    el.textContent = line;
}

function $(id)
{
    return document.getElementById(id);
}

/** RAM and video memory from which the page saves states as V7 streams */
const STREAMED_STATE_MEMORY = 1024 * 1024 * 1024;

/**
 * (docs/disk-persistence-plan.md D3: the page's notes about its disks)
 * @param {string} text
 */
function show_disk_status(text)
{
    $("disk_status").textContent = text;
    $("disk_status").style.display = "";
}

/**
 * Save a V7 snapshot, which never exists in one buffer: straight into a file
 * where the browser lets the page write one, else collected into a Blob
 * @param {V86} emulator
 * @param {string} name
 */
async function save_state_stream_to_file(emulator, name)
{
    if(typeof window["showSaveFilePicker"] === "function")
    {
        let handle;
        try
        {
            handle = await window["showSaveFilePicker"]({ "suggestedName": name });
        }
        catch(e)
        {
            if(e.name === "AbortError") return;
            throw e;
        }
        const writable = await handle["createWritable"]();
        try
        {
            await emulator.save_state_stream(chunk => writable["write"](chunk.slice()));
            await writable["close"]();
        }
        catch(e)
        {
            await writable["abort"]().catch(() => {});
            throw e;
        }
        return;
    }
    const parts = [];
    await emulator.save_state_stream(chunk => { parts.push(chunk.slice()); });
    dump_file(parts, name);
}

// These values were previously stored in localStorage
const elements_to_restore = [
    "memory_size",
    "video_memory_size",
    "networking_proxy",
    "disable_audio",
    "enable_acpi",
    "boot_order",
];
for(const item of elements_to_restore)
{
    try
    {
        window.localStorage.removeItem(item);
    }
    catch(e) {}
}

function onload()
{
    if(!window.WebAssembly)
    {
        alert("Your browser is not supported because it doesn't support WebAssembly");
        return;
    }

    $("start_emulation").onclick = function(e)
    {
        start_emulation(null, null);
        $("start_emulation").blur();
        e.preventDefault();
    };

    if(DEBUG)
    {
        debug_onload();
    }

    if(DEBUG && ON_LOCALHOST)
    {
        // don't use online relay in debug mode
        $("relay_url").value = "ws://localhost:8080/";
    }

    const query_args = new URLSearchParams(location.search);
    if(query_args.has("graphics_proxy")) $("graphics_proxy").checked = bool_arg(query_args.get("graphics_proxy"));
    // (the systems this page starts by ?profile=<id>: in DEBUG, the kvm-unit-tests)
    const oses = [];

    if(DEBUG)
    {
        // see tests/kvm-unit-tests/x86/
        const tests = [
            "realmode",
            // All tests below require an APIC
            "cmpxchg8b",
            "port80",
            "setjmp",
            "sieve",
            "hypercall", // crashes
            "init", // stops execution
            "msr", // TODO: Expects 64 bit msrs
            "smap", // test stops, SMAP not enabled
            "tsc_adjust", // TODO: IA32_TSC_ADJUST
            "tsc", // TODO: rdtscp
            "rmap_chain", // crashes
            "memory", // missing mfence (uninteresting)
            "taskswitch", // TODO: Jump
            "taskswitch2", // TODO: Call TSS
            "eventinj", // Missing #nt
            "ioapic",
            "apic",
        ];

        for(const test of tests)
        {
            oses.push({
                name: "Test case: " + test,
                id: "test-" + test,
                memory_size: 128 * 1024 * 1024,
                multiboot: { url: "tests/kvm-unit-tests/x86/" + test + ".flat" }
            });
        }
    }

    const profile = query_args.get("profile");

    if(!profile && !DEBUG)
    {
        const link = document.createElement("link");
        link.rel = "prefetch";
        link.href = "build/v86.wasm" + query_append();
        document.head.appendChild(link);
    }

    const link = document.createElement("link");
    link.rel = "prefetch";
    link.href = "build/xterm.js";
    document.head.appendChild(link);

    for(const os of oses)
    {
        if(profile === os.id)
        {
            start_emulation(os, query_args);
            return;
        }

        const element = $("start_" + os.id);

        if(element)
        {
            element.onclick = e =>
            {
                if(!e.ctrlKey)
                {
                    e.preventDefault();
                    element.blur();
                    start_emulation(os, null);
                }
            };
        }
    }

    if(profile === "custom")
    {
        // TODO: if one of the file form fields has a value (firefox), start here?

        if(query_args.has("hda.url") || query_args.has("cdrom.url") || query_args.has("fda.url"))
        {
            start_emulation(null, query_args);
            return;
        }
    }

    if(query_args.has("m")) $("memory_size").value = query_args.get("m");
    if(query_args.has("cores")) $("cpu_cores").value = query_args.get("cores");
    if(query_args.has("parallel")) $("parallel").checked = bool_arg(query_args.get("parallel"));
    $("cpu_type").value = cpu_type_arg(query_args) || $("cpu_type").value;
    $("machine_type").value = machine_type_arg(query_args) || $("machine_type").value;
    if(query_args.has("vram")) $("vga_memory_size").value = query_args.get("vram");
    if(query_args.has("graphics_adapter")) $("graphics_adapter").value = query_args.get("graphics_adapter");
    if(query_args.has("relay_url")) $("relay_url").value = query_args.get("relay_url");
    if(query_args.has("mute")) $("disable_audio").checked = bool_arg(query_args.get("mute"));
    if(query_args.has("acpi")) $("acpi").checked = bool_arg(query_args.get("acpi"));
    if(query_args.has("boot_order")) $("boot_order").value = query_args.get("boot_order");
    if(query_args.has("net_device_type")) $("net_device_type").value = query_args.get("net_device_type");
    if(query_args.has("audio_device")) $("audio_device").value = query_args.get("audio_device");
    if(query_args.has("mtu")) $("mtu").value = query_args.get("mtu");
    if(query_args.has("modem")) $("modem").value = query_args.get("modem");

    $("mtu_ui").style.display = $("net_device_type").value === "virtio" ? "table-row" : "none";
    $("net_device_type").onchange = function()
    {
        $("mtu_ui").style.display = $("net_device_type").value === "virtio" ? "table-row" : "none";
        $("net_device_type").blur();
    };

    for(const dev of ["fda", "fdb"])
    {
        const toggle = $(dev + "_toggle_empty_disk");
        if(!toggle) continue;

        toggle.onclick = function(e)
        {
            e.preventDefault();
            const select = document.createElement("select");
            select.id = dev + "_empty_size";
            for(const n_sect of [320, 360, 400, 640, 720, 800, 1440, 2400, 2880, 3444, 5760, 7680])
            {
                const n_bytes = n_sect * 512, kb = 1024, MB = kb * 1000;
                const option = document.createElement("option");
                if(n_bytes < MB)
                {
                    option.textContent = (n_bytes / kb) + " kB";
                }
                else
                {
                    option.textContent = (n_bytes / MB).toFixed(2) + " MB";
                }
                if(n_sect === 2880)
                {
                    option.selected = true;
                }
                option.value = n_bytes;
                select.appendChild(option);
            }
            // TODO (when closure compiler supports it): parent.parentNode.replaceChildren(...);
            const parent = toggle.parentNode;
            parent.innerHTML = "";
            parent.append("Empty disk of ", select);
        };
    }

    for(const dev of ["hda", "hdb"])
    {
        const toggle = $(dev + "_toggle_empty_disk");
        if(!toggle) continue;

        toggle.onclick = function(e)
        {
            e.preventDefault();
            const input = document.createElement("input");
            input.id = dev + "_empty_size";
            input.type = "number";
            input.min = "0";
            input.max = String(MAX_ARRAY_BUFFER_SIZE_MB);
            input.step = "100";
            input.value = "100";
            // TODO (when closure compiler supports it): parent.parentNode.replaceChildren(...);
            const parent = toggle.parentNode;
            parent.innerHTML = "";
            parent.append("Empty disk of ", input, " MB");
        };
    }

    const os_info = Array.from(document.querySelectorAll("#oses a.tr")).map(element =>
    {
        const [_, size_raw, unit] = element.children[1].textContent.match(/([\d\.]+)\+? (\w+)/);
        let size = +size_raw;
        if(unit === "MB") size *= 1024 * 1024;
        else if(unit === "KB") size *= 1024;
        return {
            element,
            size,
            graphical: element.children[2].firstChild.className === "gui_icon",
            family: element.children[3].textContent.replace(/-like/, ""),
            arch: element.children[4].textContent,
            status: element.children[5].textContent,
            source: element.children[6].textContent,
            languages: new Set(element.children[7].textContent.split(", ")),
            medium: element.children[8].textContent,
        };
    });

    const known_filter = [
        [   // Family:
            { id: "linux", condition: os => os.family === "Linux" },
            { id: "bsd", condition: os => os.family === "BSD" },
            { id: "windows", condition: os => os.family === "Windows" },
            { id: "unix", condition: os => os.family === "Unix" },
            { id: "dos", condition: os => os.family === "DOS" },
            { id: "custom", condition: os => os.family === "Custom" },
        ],
        [   // UI:
            { id: "graphical", condition: os => os.graphical },
            { id: "text", condition: os => !os.graphical },
        ],
        [   // Medium:
            { id: "floppy", condition: os => os.medium === "Floppy" },
            { id: "cd", condition: os => os.medium === "CD" },
            { id: "hd", condition: os => os.medium === "HD" },
        ],
        [   // Size:
            { id: "bootsector", condition: os => os.size <= 512 },
            { id: "lt5mb", condition: os => os.size <= 5 * 1024 * 1024 },
            { id: "gt5mb", condition: os => os.size > 5 * 1024 * 1024 },
        ],
        [   // Status:
            { id: "modern", condition: os => os.status === "Modern" },
            { id: "historic", condition: os => os.status === "Historic" },
        ],
        [   // License:
            { id: "opensource", condition: os => os.source === "Open-source" },
            { id: "proprietary", condition: os => os.source === "Proprietary" },
        ],
        [   // Arch:
            { id: "16bit", condition: os => os.arch === "16-bit" },
            { id: "32bit", condition: os => os.arch === "32-bit" },
        ],
        [   // Lang:
            { id: "asm", condition: os => os.languages.has("ASM") },
            { id: "c", condition: os => os.languages.has("C") },
            { id: "cpp", condition: os => os.languages.has("C++") },
            { id: "other_lang", condition: os => ["ASM", "C", "C++"].every(lang => !os.languages.has(lang)) },
        ],
    ];

    const defined_filter = [];
    for(const known_category of known_filter)
    {
        const category = known_category.filter(filter => {
            const element = document.getElementById(`filter_${filter.id}`);
            if(element)
            {
                element.onchange = update_filters;
                filter.element = element;
            }
            return element;
        });
        if(category.length)
        {
            defined_filter.push(category);
        }
    }

    function update_filters()
    {
        const conjunction = [];
        for(const category of defined_filter)
        {
            const disjunction = category.filter(filter => filter.element.checked);
            if(disjunction.length)
            {
                conjunction.push(disjunction);
            }
        }
        for(const os of os_info)
        {
            os.element.style.display = conjunction.every(disjunction => disjunction.some(filter => filter.condition(os))) ? "" : "none";
        }
    }

    if($("reset_filters"))
    {
        $("reset_filters").onclick = function()
        {
            for(const element of document.querySelectorAll("#filter input[type=checkbox]"))
            {
                element.checked = false;
            }
            update_filters();
        };
    }

    function set_proxy_value(id, value)
    {
        const elem = $(id);
        if(elem)
        {
            elem.onclick = () => $("relay_url").value = value;
        }
    }
    set_proxy_value("network_none", "");
    set_proxy_value("network_inbrowser", "inbrowser");
    set_proxy_value("network_fetch", "fetch");
    set_proxy_value("network_relay", "wss://relay.widgetry.org/");
    set_proxy_value("network_wisp", "wisps://wisp.mercurywork.shop/v86/");
}

function debug_onload()
{
    // called on window.onload, in debug mode

    const log_levels = $("log_levels");

    if(!log_levels)
    {
        return;
    }

    for(let i = 0; i < LOG_NAMES.length; i++)
    {
        const mask = LOG_NAMES[i][0];

        if(mask === 1)
            continue;

        const name = LOG_NAMES[i][1].toLowerCase();
        const input = document.createElement("input");
        const label = document.createElement("label");

        input.type = "checkbox";

        label.htmlFor = input.id = "log_" + name;

        if(LOG_LEVEL & mask)
        {
            input.checked = true;
        }
        input.mask = mask;

        label.append(input, pads(name, 4) + " ");
        log_levels.appendChild(label);

        if(i === Math.floor(LOG_NAMES.length / 2))
        {
            log_levels.append("\n");
        }
    }

    log_levels.onchange = function(e)
    {
        const target = e.target;
        const mask = target.mask;

        if(target.checked)
        {
            set_log_level(LOG_LEVEL | mask);
        }
        else
        {
            set_log_level(LOG_LEVEL & ~mask);
        }

        target.blur();
    };
}

window.addEventListener("load", onload, false);

// old webkit fires popstate on every load, fuck webkit
// https://code.google.com/p/chromium/issues/detail?id=63040
window.addEventListener("load", function()
{
    setTimeout(function()
    {
        window.addEventListener("popstate", onpopstate);
    }, 0);
});

// works in firefox and chromium
if(document.readyState === "complete")
{
    onload();
}

function set_graphics_proxy_status(message)
{
    const status = $("graphics_proxy_status");
    status.textContent = message;
    status.style.display = message ? "block" : "none";
}

async function load_graphics_proxy()
{
    if(!navigator["gpu"])
    {
        throw new Error("WebGPU is unavailable. Use a WebGPU-capable browser over HTTPS or localhost.");
    }
    if(typeof window["V86GraphicsProxy"] === "function") return;

    // Fetch the current revision so the bundle and shader workers use matching assets.
    const response = await fetch("build/glbridge/manifest.json", { cache: "no-store" });
    if(!response.ok) throw new Error("Graphics bundle is missing. Run make glbridge and reload.");
    const manifest = await response.json();
    await new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.src = "build/glbridge/libv86-webgpu.js?v=" + encodeURIComponent(manifest["revision"]);
        script.onload = () => resolve();
        script.onerror = () => {
            script.remove();
            reject(new Error("Could not load the graphics bundle. Run make glbridge and reload."));
        };
        document.head.appendChild(script);
    });
    if(typeof window["V86GraphicsProxy"] !== "function")
    {
        throw new Error("Graphics bundle did not initialize. Check the browser console and rebuild with make glbridge.");
    }
}

/**
 * The boot form's fields (src/browser/vm_options.js, DEFAULT_FORM)
 * @return {!Object}
 */
function read_form()
{
    const file = id => $(id)?.files[0];
    return {
        relay_url: $("relay_url").value,
        disable_audio: $("disable_audio").checked,
        files: {
            bios: file("bios"),
            vga_bios: file("vga_bios"),
            fda: file("fda_image"),
            fdb: file("fdb_image"),
            cdrom: file("cdrom_image"),
            hda: file("hda_image"),
            hdb: file("hdb_image"),
            multiboot: file("multiboot_image"),
            bzimage: file("bzimage"),
            initrd: file("initrd"),
        },
        empty_sizes: {
            fda: +$("fda_empty_size")?.value,
            fdb: +$("fdb_empty_size")?.value,
            hda: +$("hda_empty_size")?.value,
            hdb: +$("hdb_empty_size")?.value,
        },
        // (read by the disk's name: quoted, or Closure renames them)
        urls: { "hda": $("hda_url")?.value, "hdb": $("hdb_url")?.value },
        disk_options: { "hda": $("hda_disk_option")?.value, "hdb": $("hdb_disk_option")?.value },
        memory_size: $("memory_size").value,
        vga_memory_size: $("vga_memory_size").value,
        graphics_adapter: $("graphics_adapter").value,
        boot_order: $("boot_order").value,
        cpu_cores: $("cpu_cores").value,
        parallel: $("parallel").checked,
        cpu_type: $("cpu_type").value,
        machine_type: $("machine_type").value,
        acpi: $("acpi").checked,
        net_device_type: $("net_device_type").value,
        audio_device: $("audio_device").value,
        mtu: $("mtu").value,
        modem: $("modem").value,
    };
}

// we can get here in various ways:
// - the user clicked on the "start emulation" button
// - the user clicked on a profile
// - the ?profile= query parameter specified a valid profile
// - the ?profile= query parameter was set to "custom" and at least one disk image was given
async function start_emulation(profile, query_args)
{
    $("boot_options").style.display = "none";

    const graphics_proxy = query_args?.has("graphics_proxy") ?
        bool_arg(query_args.get("graphics_proxy")) : $("graphics_proxy").checked;
    set_graphics_proxy_status("");
    if(graphics_proxy)
    {
        set_graphics_proxy_status("Loading graphics proxy...");
        try
        {
            await load_graphics_proxy();
            set_graphics_proxy_status("");
        }
        catch(error)
        {
            set_graphics_proxy_status("Graphics proxy could not start: " + error.message);
            $("boot_options").style.display = "block";
            return;
        }
    }

    // the settings of the profile, the address and the form (src/browser/query_compat.js)
    const start = start_settings(profile, query_args, read_form(),
        { location_args: new URLSearchParams(window.location.search), origin: location.origin, debug: DEBUG, graphics_proxy });
    const settings = start.settings;

    if(profile)
    {
        if(profile.state)
        {
            $("reset").style.display = "none";
        }

        set_title(profile.name);

        if(!DEBUG && profile.homepage)
        {
            $("description").style.display = "block";
            const link = document.createElement("a");
            link.href = profile.homepage;
            link.textContent = profile.name;
            link.target = "_blank";
            $("description").append(document.createTextNode("Running "), link);
        }
    }

    if(start.error)
    {
        alert(start.error);
        $("boot_options").style.display = "block";
        return;
    }
    for(const id of ["memory_size", "vga_memory_size", "cpu_type", "machine_type"])
    {
        if(start.updates[id] !== undefined) $(id).value = start.updates[id];
    }
    if(start.updates["acpi"]) $("acpi").checked = true;
    if(start.title)
    {
        set_title(start.title);
    }

    if(!query_args)
    {
        push_state(start.new_query_args);
    }

    const options = settings_to_options(settings, {
        cpu_worker: start.cpu_worker,
        debug: DEBUG,
        query_append: query_append(),
        graphics_proxy: graphics_proxy && {
            "onError": error => {
                console.error("Graphics proxy initialization failed", error);
                set_graphics_proxy_status("Graphics proxy failed; VGA remains available: " + error.message);
            },
        },
        screen_container: $("screen_container"),
    });

    // (tests/app/legacy_options.mjs: the options this page gives V86, recorded
    // instead of starting the emulator)
    if(typeof window["v86_record_options"] === "function")
    {
        window["v86_record_options"](options);
        return;
    }

    const emulator = new V86(options);

    if(DEBUG) window.emulator = emulator;

    // virtio_gpu: the guest's display follows the window (the guest's
    // driver asks for the new size after a display event); with several
    // displays (?displays=N), each gets its share of the width
    if((settings.graphics_adapter || DEFAULT_GRAPHICS_ADAPTER) === "virtio_gpu")
    {
        let resize_timer = 0;
        const displays = settings.displays || 1;
        const report_display_size = () => {
            clearTimeout(resize_timer);
            resize_timer = setTimeout(() => {
                for(let i = 0; i < displays; i++) emulator.set_display_size(Math.floor(window.innerWidth / displays), window.innerHeight, i);
            }, 250);
        };
        window.addEventListener("resize", report_display_size);
        emulator.add_listener("emulator-ready", report_display_size);
    }

    emulator.add_listener("emulator-ready", function()
    {
        if(DEBUG && !emulator.worker_controller)
        {
            debug_start(emulator);
        }
        else if(DEBUG)
        {
            // the CPU is in the Worker (a release build): nothing to inspect here
            for(const id of ["dump_regs", "dump_gdt", "dump_idt", "dump_pt"])
            {
                $(id).disabled = true;
                $(id).title = "The CPU runs in a Worker; open debug.html?cpu_worker=0 to debug it in the page";
            }
        }

        if(!emulator.worker_controller && emulator.v86.cpu.wm.exports["profiler_is_enabled"]())
        {
            const CLEAR_STATS = false;

            const panel = document.createElement("pre");
            document.body.appendChild(panel);

            setInterval(function()
                {
                    if(!emulator.is_running())
                    {
                        return;
                    }

                    panel.textContent = emulator.get_instruction_stats();

                    CLEAR_STATS && emulator.v86.cpu.clear_stats();
                }, CLEAR_STATS ? 5000 : 1000);
        }

        init_ui(profile, settings, emulator);

        if(query_args?.has("c"))
        {
            setTimeout(function()
            {
                emulator.keyboard_send_text(query_args.get("c") + "\n");
            }, 25);
        }

        if(query_args?.has("s"))
        {
            setTimeout(function()
            {
                emulator.serial0_send(query_args.get("s") + "\n");
            }, 25);
        }

        if(query_args?.has("theatre") && bool_arg(query_args?.get("theatre")))
        {
            $("toggle_theatre").click();
        }
    });

    emulator.add_listener("emulator-loaded", function()
    {
        if(emulator.worker_controller ? !emulator.worker_controller.device_info["cdrom"] : !emulator.v86.cpu.devices.cdrom)
        {
            $("change_cdrom_image").style.display = "none";
        }
        // how the cores run: in host threads, or taking turns (and why)
        const cores = settings.cpu_cores || DEFAULT_CPU_CORES;
        Promise.resolve(emulator.get_diagnostics()).then(diagnostics => {
            const execution = diagnostics && diagnostics["execution"];
            const fallback = execution && execution["fallback"];
            $("info_execution").textContent = cores === 1 ? "1 core" :
                execution && execution["mode"] === "parallel" ? cores + " cores, each in a host thread" :
                cores + " cores taking turns on one thread" +
                    (fallback && fallback !== "not requested" ? " (parallel unavailable: " + fallback + ")" : "");
        }).catch(() => {});
    });

    emulator.add_listener("emulator-error", function(error)
    {
        $("loading").style.display = "block";
        $("loading").textContent = "Emulator failed: " + error.message;
        if(DEBUG && emulator.worker_controller && !emulator.worker_controller.ready)
        {
            $("loading").textContent += " (the CPU Worker is build/cpu-worker.js from `make all-debug`; " +
                "debug.html?cpu_worker=0 runs the CPU in the page)";
        }
    });

    emulator.add_listener("download-progress", function(e)
    {
        show_progress(e);
    });

    emulator.add_listener("download-error", function(e)
    {
        const el = $("loading");
        el.style.display = "block";
        el.textContent = `Loading ${e.file_name} failed. Check your connection and reload the page to try again.`;
    });
}

/**
 * @param {Object} settings
 * @param {V86} emulator
 */
function init_ui(profile, settings, emulator)
{
    $("loading").style.display = "none";
    $("runtime_options").style.display = "block";
    $("runtime_infos").style.display = "block";
    $("screen_container").style.display = "block";

    var filesystem_is_enabled = false;

    if(settings.filesystem)
    {
        filesystem_is_enabled = true;
        init_filesystem_panel(emulator);
    }
    else
    {
        emulator.add_listener("9p-attach", function()
        {
            filesystem_is_enabled = true;
            init_filesystem_panel(emulator);
        });
    }

    $("run").onclick = function()
    {
        if(emulator.is_running())
        {
            $("run").textContent = "Run";
            emulator.stop();
        }
        else
        {
            $("run").textContent = "Pause";
            emulator.run();
        }

        $("run").blur();
    };

    $("exit").onclick = function()
    {
        emulator.destroy();
        const params = new URLSearchParams(location.search);
        params.delete("profile");
        location.href = location.pathname + format_query_args(params);
    };

    $("lock_mouse").onclick = function()
    {
        if(!mouse_is_enabled)
        {
            $("toggle_mouse").onclick();
        }

        emulator.lock_mouse();
        $("lock_mouse").blur();
    };

    var mouse_is_enabled = true;

    $("toggle_mouse").onclick = function()
    {
        mouse_is_enabled = !mouse_is_enabled;

        emulator.mouse_set_enabled(mouse_is_enabled);
        $("toggle_mouse").textContent = (mouse_is_enabled ? "Dis" : "En") + "able mouse";
        $("toggle_mouse").blur();
    };

    if(profile?.mouse_disabled_default)
    {
        $("toggle_mouse").onclick();
    }

    var theatre_mode = false;
    var theatre_ui = true;
    var theatre_zoom_to_fit = false;

    function zoom_to_fit()
    {
        // reset size
        emulator.screen_set_scale(1, 1);

        const emulator_screen = $("screen_container").getBoundingClientRect();
        const emulator_screen_width = emulator_screen.width;
        const emulator_screen_height = emulator_screen.height;

        const viewport_screen_width = window.innerWidth;
        const viewport_screen_height = window.innerHeight;

        const n = Math.min(viewport_screen_width / emulator_screen_width, viewport_screen_height / emulator_screen_height);
        emulator.screen_set_scale(n, n);
    }

    /**
     * @param {boolean} enabled
     */
    function enable_theatre_ui(enabled)
    {
        theatre_ui = enabled;

        $("runtime_options").style.display = theatre_ui ? "block" : "none";
        $("runtime_infos").style.display = theatre_ui ? "block" : "none";
        $("filesystem_panel").style.display = (filesystem_is_enabled && theatre_ui) ? "block" : "none";

        $("toggle_ui").textContent = (theatre_ui ? "Hide" : "Show") + " UI";
    }

    /**
     * @param {boolean} enabled
     */
    function enable_zoom_to_fit(enabled)
    {
        theatre_zoom_to_fit = enabled;
        $("scale").disabled = theatre_zoom_to_fit;

        if(theatre_zoom_to_fit)
        {
            window.addEventListener("resize", zoom_to_fit, true);
            emulator.add_listener("screen-set-size", zoom_to_fit);

            zoom_to_fit();
        }
        else
        {
            window.removeEventListener("resize", zoom_to_fit, true);
            emulator.remove_listener("screen-set-size", zoom_to_fit);

            const n = parseFloat($("scale").value) || 1;
            emulator.screen_set_scale(n, n);
        }

        $("toggle_zoom_to_fit").textContent = (theatre_zoom_to_fit ? "Dis" : "En") + "able zoom to fit";
    }

    /**
     * @param {boolean} enabled
     */
    function enable_theatre_mode(enabled)
    {
        theatre_mode = enabled;

        if(!theatre_ui)
        {
            enable_theatre_ui(true);
        }

        if(!theatre_mode && theatre_zoom_to_fit)
        {
            enable_zoom_to_fit(false);
        }

        for(const el of ["screen_container", "runtime_options", "runtime_infos", "filesystem_panel"])
        {
            $(el).classList.toggle("theatre_" + el);
        }

        $("theatre_background").style.display = theatre_mode ? "block" : "none";
        $("toggle_zoom_to_fit").style.display = theatre_mode ? "inline" : "none";
        $("toggle_ui").style.display = theatre_mode ? "block" : "none";

        // hide scrolling
        document.body.style.overflow = theatre_mode ? "hidden" : "visible";

        $("toggle_theatre").textContent = (theatre_mode ? "Dis" : "En") + "able theatre mode";
    }

    $("toggle_ui").onclick = function()
    {
        enable_theatre_ui(!theatre_ui);
        $("toggle_ui").blur();
    };

    $("toggle_theatre").onclick = function()
    {
        enable_theatre_mode(!theatre_mode);
        $("toggle_theatre").blur();
    };

    $("toggle_zoom_to_fit").onclick = function()
    {
        enable_zoom_to_fit(!theatre_zoom_to_fit);
        $("toggle_zoom_to_fit").blur();
    };

    var last_tick = 0;
    var running_time = 0;
    var last_instr_counter = 0;
    var interval = null;
    var os_uses_mouse = false;
    var os_uses_absolute_mouse = false;
    var total_instructions = 0;

    function update_info()
    {
        var now = Date.now();

        var instruction_counter = emulator.get_instruction_counter();

        if(instruction_counter < last_instr_counter)
        {
            // 32-bit wrap-around
            last_instr_counter -= 0x100000000;
        }

        var last_ips = instruction_counter - last_instr_counter;
        last_instr_counter = instruction_counter;
        total_instructions += last_ips;

        var delta_time = now - last_tick;

        if(delta_time)
        {
            running_time += delta_time;
            last_tick = now;

            $("speed").textContent = (last_ips / 1000 / delta_time).toFixed(1);
            $("avg_speed").textContent = (total_instructions / 1000 / running_time).toFixed(1);
            $("running_time").textContent = format_timestamp(running_time / 1000 | 0);
        }
    }

    emulator.add_listener("emulator-started", function()
    {
        last_tick = Date.now();
        interval = setInterval(update_info, 1000);
    });

    emulator.add_listener("emulator-stopped", function()
    {
        update_info();
        if(interval !== null)
        {
            clearInterval(interval);
        }
    });

    var stats_9p = {
        read: 0,
        write: 0,
        files: [],
    };

    emulator.add_listener("9p-read-start", function(args)
    {
        const file = args[0];
        stats_9p.files.push(file);
        $("info_filesystem").style.display = "block";
        $("info_filesystem_status").textContent = "Loading ...";
        $("info_filesystem_last_file").textContent = file;
    });
    emulator.add_listener("9p-read-end", function(args)
    {
        stats_9p.read += args[1];
        $("info_filesystem_bytes_read").textContent = stats_9p.read;

        const file = args[0];
        stats_9p.files = stats_9p.files.filter(f => f !== file);

        if(stats_9p.files[0])
        {
            $("info_filesystem_last_file").textContent = stats_9p.files[0];
        }
        else
        {
            $("info_filesystem_status").textContent = "Idle";
        }
    });
    emulator.add_listener("9p-write-end", function(args)
    {
        stats_9p.write += args[1];
        $("info_filesystem_bytes_written").textContent = stats_9p.write;

        if(!stats_9p.files[0])
        {
            $("info_filesystem_last_file").textContent = args[0];
        }
    });

    var stats_storage = {
        read: 0,
        read_sectors: 0,
        write: 0,
        write_sectors: 0,
    };

    $("storage_bus").textContent = settings.machine_type === "q35" ? "AHCI" : "IDE";
    $("ide_type").textContent = settings.cdrom ? " (CD-ROM)" : " (hard disk)";

    emulator.add_listener("ide-read-start", function()
    {
        $("info_storage").style.display = "block";
        $("info_storage_status").textContent = "Loading ...";
    });
    emulator.add_listener("ide-read-end", function(args)
    {
        stats_storage.read += args[1];
        stats_storage.read_sectors += args[2];

        $("info_storage_status").textContent = "Idle";
        $("info_storage_bytes_read").textContent = stats_storage.read;
        $("info_storage_sectors_read").textContent = stats_storage.read_sectors;
    });
    emulator.add_listener("ide-write-end", function(args)
    {
        stats_storage.write += args[1];
        stats_storage.write_sectors += args[2];

        $("info_storage_bytes_written").textContent = stats_storage.write;
        $("info_storage_sectors_written").textContent = stats_storage.write_sectors;
    });

    var stats_net = {
        bytes_transmitted: 0,
        bytes_received: 0,
    };

    emulator.add_listener("eth-receive-end", function(args)
    {
        stats_net.bytes_received += args[0];

        $("info_network").style.display = "block";
        $("info_network_bytes_received").textContent = stats_net.bytes_received;
    });
    emulator.add_listener("eth-transmit-end", function(args)
    {
        stats_net.bytes_transmitted += args[0];

        $("info_network").style.display = "block";
        $("info_network_bytes_transmitted").textContent = stats_net.bytes_transmitted;
    });


    emulator.add_listener("mouse-enable", function(is_enabled)
    {
        os_uses_mouse = is_enabled;
        $("info_mouse_enabled").textContent = is_enabled ? "Yes" : "No";
    });

    emulator.add_listener("vmware-absolute-mouse", function(is_enabled)
    {
        os_uses_absolute_mouse = is_enabled;
    });

    // (the ARM machines' virtio tablet and touch screens: [active, the guest's cursor])
    emulator.add_listener("absolute-pointer", function(state)
    {
        os_uses_absolute_mouse = state[0];
    });

    emulator.add_listener("screen-set-size", function(args)
    {
        const [w, h, bpp] = args;
        $("info_res").textContent = w + "x" + h + (bpp ? "x" + bpp : "");
        $("info_vga_mode").textContent = bpp ? "Graphical" : "Text";
    });


    $("reset").onclick = function()
    {
        emulator.restart();
        $("reset").blur();
    };

    add_image_download_button(settings.hda, () => emulator.v86.cpu.disk_device("hda").buffer, "hda");
    add_image_download_button(settings.hdb, () => emulator.v86.cpu.disk_device("hdb").buffer, "hdb");
    add_image_download_button(settings.fda, () => emulator.v86.cpu.devices.fdc.drives[0].buffer, "fda");
    add_image_download_button(settings.fdb, () => emulator.v86.cpu.devices.fdc.drives[1].buffer, "fdb");
    add_image_download_button(settings.cdrom, () => emulator.v86.cpu.disk_device("cdrom").buffer, "cdrom");

    function add_image_download_button(obj, get_buffer, type)
    {
        var elem = $("get_" + type + "_image");

        // (a disk image in a container format: exported RAW, in parts;
        // docs/disk-image-formats-plan.md P2)
        const exported = obj && obj.format && obj.format !== "raw";
        if(!obj || obj.async && !exported)
        {
            elem.style.display = "none";
        }

        elem.onclick = async function(e)
        {
            if(exported)
            {
                const parts = [];
                try
                {
                    await emulator.export_disk_image(type, { write: chunk => { parts.push(chunk); } });
                    download(new Blob(parts), (profile?.id || "v86") + "-" + type + ".img");
                }
                catch(error)
                {
                    alert("The disk could not be exported: " + error.message);
                }
                elem.blur();
                return;
            }
            if(emulator.worker_controller)
            {
                const name = (profile?.id || "v86") + "-" + type + (type === "cdrom" ? ".iso" : ".img");
                const result = await emulator.worker_controller.rpc("disk", [type]);
                if(result instanceof Blob)
                {
                    // (a local file read in parts, with the blocks written)
                    download(result, result instanceof File ? result.name : name);
                }
                else if(result)
                {
                    dump_file(result, name);
                }
                else
                {
                    alert("The file could not be loaded. Maybe it's too big?");
                }
                elem.blur();
                return;
            }
            const buffer = get_buffer();
            const filename = buffer.file && buffer.file.name || ((profile?.id || "v86") + "-" + type + (type === "cdrom" ? ".iso" : ".img"));

            if(buffer.get_as_file)
            {
                var file = buffer.get_as_file(filename);
                download(file, filename);
            }
            else
            {
                buffer.get_buffer(function(b)
                {
                    if(b)
                    {
                        dump_file(b, filename);
                    }
                    else
                    {
                        alert("The file could not be loaded. Maybe it's too big?");
                    }
                });
            }

            elem.blur();
        };
    }

    function pick_file(multiple)
    {
        return new Promise(resolve => {
            const file_input = document.createElement("input");
            file_input.type = "file";
            file_input.multiple = multiple;
            file_input.onchange = function()
            {
                resolve(file_input.files);
            };
            file_input.oncancel = function()
            {
                resolve([]);
            };
            file_input.click();
        });
    }

    $("change_fda_image").textContent = settings.fda ? "Eject floppy image" : "Insert floppy image";
    $("change_fda_image").ondragover = function(e)
    {
        e.preventDefault();
    };
    async function insert_fda(files)
    {
        const file = files[0];
        if(file)
        {
            await emulator.set_fda({ buffer: file });
            $("change_fda_image").textContent = "Eject floppy image";
            $("get_fda_image").style.display = "block";
        }
    }
    $("change_fda_image").ondrop = function(e)
    {
        e.preventDefault();
        if(emulator.get_disk_fda())
        {
            emulator.eject_fda();
        }
        insert_fda(e.dataTransfer.files);
    };
    $("change_fda_image").onclick = async function()
    {
        if(emulator.get_disk_fda())
        {
            emulator.eject_fda();
            $("change_fda_image").textContent = "Insert floppy image";
            $("get_fda_image").style.display = "none";
        }
        else
        {
            const files = await pick_file(false);
            insert_fda(files);
        }
        $("change_fda_image").blur();
    };

    $("change_fdb_image").textContent = settings.fdb ? "Eject second floppy image" : "Insert second floppy image";
    $("change_fdb_image").ondragover = function(e)
    {
        e.preventDefault();
    };
    async function insert_fdb(files)
    {
        const file = files[0];
        if(file)
        {
            await emulator.set_fdb({ buffer: file });
            $("change_fdb_image").textContent = "Eject second floppy image";
            $("get_fdb_image").style.display = "block";
        }
    }
    $("change_fdb_image").ondrop = function(e)
    {
        e.preventDefault();
        if(emulator.get_disk_fdb())
        {
            emulator.eject_fdb();
        }
        insert_fdb(e.dataTransfer.files);
    };
    $("change_fdb_image").onclick = async function()
    {
        if(emulator.get_disk_fdb())
        {
            emulator.eject_fdb();
            $("change_fdb_image").textContent = "Insert second floppy image";
            $("get_fdb_image").style.display = "none";
        }
        else
        {
            const files = await pick_file(false);
            insert_fdb(files);
        }
        $("change_fdb_image").blur();
    };

    $("change_cdrom_image").textContent = settings.cdrom ? "Eject CD image" : "Insert CD image";
    $("change_cdrom_image").ondragover = function(e)
    {
        e.preventDefault();
    };
    async function insert_cdrom(files)
    {
        let buffer;

        if(files.length === 1 && /\.(iso(9660|img)?|cdr)$/i.test(files[0].name))
        {
            buffer = files[0];
        }
        else if(files.length)
        {
            const files2 = [];
            for(const file of files)
            {
                files2.push({
                    name: file.name,
                    contents: new Uint8Array(await read_file(file)),
                });

            }
            buffer = iso9660.generate(files2).buffer;
        }

        if(buffer)
        {
            await emulator.set_cdrom({ buffer });
            $("change_cdrom_image").textContent = "Eject CD image";
            $("get_cdrom_image").style.display = "block";
        }
    }
    $("change_cdrom_image").ondrop = function(e)
    {
        e.preventDefault();
        if(emulator.worker_controller ? emulator.worker_controller.device_info["cdrom_present"] : emulator.v86.cpu.devices.cdrom.has_disk())
        {
            emulator.eject_cdrom();
        }
        insert_cdrom(e.dataTransfer.files);
    };
    $("change_cdrom_image").onclick = async function()
    {
        if(emulator.worker_controller ? emulator.worker_controller.device_info["cdrom_present"] : emulator.v86.cpu.devices.cdrom.has_disk())
        {
            emulator.eject_cdrom();
            $("change_cdrom_image").textContent = "Insert CD image";
            $("get_cdrom_image").style.display = "none";
        }
        else
        {
            const files = await pick_file(true);
            insert_cdrom(files);
        }
        $("change_cdrom_image").blur();
    };

    $("memory_dump").onclick = async function()
    {
        if(emulator.worker_controller)
        {
            dump_file(await emulator.worker_controller.rpc("memory_dump"), "v86memory.bin");
            return;
        }
        const mem8 = emulator.v86.cpu.mem8;
        dump_file(new Uint8Array(mem8.buffer, mem8.byteOffset, mem8.length), "v86memory.bin");
        $("memory_dump").blur();
    };

    //$("memory_dump_dmp").onclick = function()
    //{
    //    var memory = emulator.v86.cpu.mem8;
    //    var memory_size = memory.length;
    //    var page_size = 4096;
    //    var header = new Uint8Array(4096);
    //    var header32 = new Int32Array(header.buffer);

    //    header32[0] = 0x45474150; // 'PAGE'
    //    header32[1] = 0x504D5544; // 'DUMP'

    //    header32[0x10 >> 2] = emulator.v86.cpu.cr[3]; // DirectoryTableBase
    //    header32[0x24 >> 2] = 1; // NumberProcessors
    //    header32[0xf88 >> 2] = 1; // DumpType: full dump
    //    header32[0xfa0 >> 2] = header.length + memory_size; // RequiredDumpSpace

    //    header32[0x064 + 0 >> 2] = 1; // NumberOfRuns
    //    header32[0x064 + 4 >> 2] = memory_size / page_size; // NumberOfPages
    //    header32[0x064 + 8 >> 2] = 0; // BasePage
    //    header32[0x064 + 12 >> 2] = memory_size / page_size; // PageCount

    //    dump_file([header, memory], "v86memory.dmp");

    //    $("memory_dump_dmp").blur();
    //};

    /**
     * @this HTMLElement
     */
    $("capture_network_traffic").onclick = function()
    {
        this.textContent = "0 packets";

        let capture = [];

        function do_capture(direction, data)
        {
            capture.push({ direction, time: performance.now() / 1000, hex_dump: hex_dump(data) });
            $("capture_network_traffic").textContent = capture.length + " packets";
        }

        emulator.emulator_bus.register("net0-receive", do_capture.bind(this, "I"));
        emulator.add_listener("net0-send", do_capture.bind(this, "O"));

        this.onclick = function()
        {
            const capture_raw = capture.map(({ direction, time, hex_dump }) => {
                // https://www.wireshark.org/docs/wsug_html_chunked/ChIOImportSection.html
                // In wireshark: file -> import from hex -> tick direction indication, timestamp %s.%f
                return direction + " " + time.toFixed(6) + hex_dump + "\n";
            }).join("");
            dump_file(capture_raw, "traffic.hex");
            capture = [];
            this.textContent = "0 packets";
        };
    };


    $("save_state").onclick = async function()
    {
        const button = $("save_state");
        button.disabled = true;
        const label = button.textContent;
        button.textContent = "Saving...";
        try
        {
            // A single-buffer snapshot is less than 2 GiB (the RAM in use,
            // video memory, the SVGA's 3D objects), and the browser allocates
            // it in one piece, beside the guest's RAM: machines of 1 GiB or
            // more save a V7 stream, written to the file as it is made (into
            // a Blob where the browser lets the page write no file); the
            // others too when one buffer fails (RangeError)
            let result = null;
            if(!settings.extended_memory_size && settings.memory_size + (settings.vram_size || 0) < STREAMED_STATE_MEMORY)
            {
                try
                {
                    result = await emulator.save_state();
                }
                catch(error)
                {
                    if(!/RangeError|save_state_stream/.test(String(error && (error.stack || error.message)))) throw error;
                }
            }
            if(result) dump_file(result, "v86state.bin");
            else await save_state_stream_to_file(emulator, "v86state.bin");
        }
        catch(error)
        {
            console.error("Could not save emulator state", error);
            alert("Could not save the state:\n" + error.message);
        }
        finally
        {
            button.disabled = false;
            button.textContent = label;
            button.blur();
        }
    };

    // Disks written back (docs/disk-persistence-plan.md D3): their changes
    // are in their images, a snapshot holds only a reference of each, valid
    // until the image is written again. So the page offers "save and power
    // off": the state saved, the machine destroyed (the disks flushed and
    // closed); restored later with the same disks, the machine goes on.
    const written_back = [settings.hda, settings.hdb, settings.fda, settings.fdb].some(disk => disk && disk.disk_option === "read_write");
    $("save_and_power_off").style.display = written_back ? "" : "none";
    $("save_and_power_off").onclick = async function()
    {
        const button = $("save_and_power_off");
        button.disabled = true;
        try
        {
            const parts = [];
            await emulator.save_state_stream(chunk => { parts.push(chunk.slice()); });
            dump_file(parts, "v86state.bin");
            await emulator.destroy();
            show_disk_status("Saved the state (v86state.bin, " + parts.reduce((n, p) => n + p.length, 0) + " bytes) and powered off: " +
                "the disks written back are flushed and closed. Load the state with the same disks to go on.");
        }
        catch(error)
        {
            console.error("Could not save and power off", error);
            alert("Could not save the state:\n" + error.message);
            button.disabled = false;
        }
    };
    // a disk's read or write failed: with disk_error "stop" the machine
    // waits for the user: retry (or, when it cannot be retried, continue:
    // the guest sees the error), or power off
    emulator.add_listener("disk-error", event =>
    {
        const stop = event["policy"] === "stop";
        $("disk_error_text").textContent = "Disk " + event["disk"] + ": the " + event["operation"] + " of " + event["length"] +
            " bytes at " + event["offset"] + " failed: " + event["reason"] + ". " +
            (!stop ? "The guest was told." : event["retryable"] ? "The machine is stopped: retry once the disk can be reached again, or power off." :
                "The machine is stopped: this cannot be retried; continue (the guest is told), or power off.");
        $("disk_error_retry").textContent = event["retryable"] ? "Retry" : "Continue";
        $("disk_error_retry").style.display = stop ? "" : "none";
        $("disk_error_power_off").style.display = stop ? "" : "none";
        $("disk_error_box").style.display = "";
    });
    $("disk_error_retry").onclick = function()
    {
        $("disk_error_box").style.display = "none";
        emulator.run();
    };
    $("disk_error_power_off").onclick = async function()
    {
        $("disk_error_box").style.display = "none";
        await emulator.destroy();
        show_disk_status("Powered off: the requests still waiting for the disk are dropped, as by a power loss.");
    };

    $("load_state").onclick = async function()
    {
        $("load_state").blur();

        const files = await pick_file(false);
        const file = files[0];

        if(!file)
        {
            return;
        }

        const button = $("load_state");
        const label = button.textContent;
        button.disabled = true;
        button.textContent = "Loading...";
        try
        {
            // streams (large machines) are read from the file as needed:
            // odd versions, 7 and 9 (src/state.js)
            const header = new DataView(await file.slice(0, 8).arrayBuffer());
            const stream = header.byteLength === 8 && header.getUint32(0, true) === 0x86768676 &&
                header.getUint32(4, true) % 2 === 1;
            const state = stream ? null : await new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = () => reject(reader.error);
                reader.onabort = () => reject(new Error("State file reading was cancelled"));
                reader.readAsArrayBuffer(file);
            });
            const was_running = emulator.is_running();
            if(was_running) await emulator.stop();
            if(stream) await emulator.restore_state_stream(file);
            else await emulator.restore_state(state);
            if(was_running) emulator.run();
        }
        catch(err)
        {
            console.error("Could not restore emulator state", err);
            alert("Something bad happened while restoring the state:\n" + err + "\n\n" +
                  "Note that the current configuration must be the same as the original");
        }
        finally
        {
            button.disabled = false;
            button.textContent = label;
        }
    };

    $("ctrlaltdel").onclick = function()
    {
        emulator.keyboard_send_scancodes([
            0x1D, // ctrl
            0x38, // alt
            0x53, // delete

            // break codes
            0x1D | 0x80,
            0x38 | 0x80,
            0x53 | 0x80,
        ]);

        $("ctrlaltdel").blur();
    };

    $("alttab").onclick = function()
    {
        emulator.keyboard_send_scancodes([
            0x38, // alt
            0x0F, // tab
        ]);

        setTimeout(function()
        {
            emulator.keyboard_send_scancodes([
                0x38 | 0x80,
                0x0F | 0x80,
            ]);
        }, 100);

        $("alttab").blur();
    };

    /**
     * @this HTMLElement
     */
    $("scale").onchange = function()
    {
        var n = parseFloat(this.value);

        if(n || n > 0)
        {
            emulator.screen_set_scale(n, n);
        }
    };

    $("fullscreen").onclick = function()
    {
        emulator.screen_go_fullscreen();
    };

    $("screen_container").onclick = function(e)
    {
        if(emulator.is_running() && emulator.speaker_adapter?.audio_context?.state === "suspended")
        {
            emulator.speaker_adapter.audio_context.resume();
        }

        // No need to lock the mouse if the guest tracks the host cursor
        // through the absolute pointing device. The "Lock mouse" button can
        // still be used, e.g. for games (movement is then sent as relative
        // deltas).
        if(mouse_is_enabled && os_uses_mouse && !os_uses_absolute_mouse)
        {
            emulator.lock_mouse();
        }

        // allow text selection
        if(window.getSelection().isCollapsed)
        {
            const phone_keyboard = document.getElementsByClassName("phone_keyboard")[0];

            phone_keyboard.style.top = window.scrollY + e.clientY + 20 + "px";
            phone_keyboard.style.left = window.scrollX + e.clientX + "px";

            // clean after previous input
            phone_keyboard.value = "";
            phone_keyboard.focus();
        }
    };

    const phone_keyboard = document.getElementsByClassName("phone_keyboard")[0];

    phone_keyboard.setAttribute("autocorrect", "off");
    phone_keyboard.setAttribute("autocapitalize", "off");
    phone_keyboard.setAttribute("spellcheck", "false");
    phone_keyboard.tabIndex = 0;

    $("take_screenshot").onclick = function()
    {
        const image = emulator.screen_make_screenshot();
        try {
            const w = window.open("");
            w.document.write(image.outerHTML);
        }
        catch(e) {}
        $("take_screenshot").blur();
    };

    if(emulator.speaker_adapter)
    {
        let is_muted = false;

        $("mute").onclick = function()
        {
            if(is_muted)
            {
                emulator.speaker_adapter.mixer.set_volume(1, undefined);
                is_muted = false;
                $("mute").textContent = "Mute";
            }
            else
            {
                emulator.speaker_adapter.mixer.set_volume(0, undefined);
                is_muted = true;
                $("mute").textContent = "Unmute";
            }

            $("mute").blur();
        };
    }
    else
    {
        $("mute").remove();
    }

    window.addEventListener("keydown", ctrl_w_rescue, false);
    window.addEventListener("keyup", ctrl_w_rescue, false);
    window.addEventListener("blur", ctrl_w_rescue, false);

    function ctrl_w_rescue(e)
    {
        if(e.ctrlKey)
        {
            window.onbeforeunload = function()
            {
                window.onbeforeunload = null;
                return "CTRL-W cannot be sent to the emulator.";
            };
        }
        else
        {
            window.onbeforeunload = null;
        }
    }

    const script = document.createElement("script");
    script.src = "build/xterm.js";
    script.async = true;
    script.onload = function()
    {
        emulator.set_serial_container_xtermjs($("terminal"));
        emulator.serial_adapter.term.write("This is the serial console. Whatever you type or paste here will be sent to COM1");
    };
    document.body.appendChild(script);
}

function init_filesystem_panel(emulator)
{
    $("filesystem_panel").style.display = "block";

    /**
     * @this HTMLElement
     */
    $("filesystem_send_file").onchange = function()
    {
        Array.prototype.forEach.call(this.files, function(file)
        {
            var loader = new SyncFileBuffer(file);
            loader.onload = function()
            {
                loader.get_buffer(async function(buffer)
                {
                    await emulator.create_file("/" + file.name, new Uint8Array(buffer));
                });
            };
            loader.load();
        }, this);

        this.value = "";
        this.blur();
    };

    /**
     * @this HTMLElement
     */
    $("filesystem_get_file").onkeypress = async function(e)
    {
        if(e.which !== 13)
        {
            return;
        }

        this.disabled = true;

        let result;
        try
        {
             result = await emulator.read_file(this.value);
        }
        catch(err)
        {
            console.log(err);
        }

        this.disabled = false;

        if(result)
        {
            var filename = this.value.replace(/\/$/, "").split("/");
            filename = filename[filename.length - 1] || "root";

            dump_file(result, filename);
            this.value = "";
        }
        else
        {
            alert("Can't read file");
        }
    };
}

function debug_start(emulator)
{
    if(!emulator.v86)
    {
        return;
    }

    // called as soon as soon as emulation is started, in debug mode
    const cpu = emulator.v86.cpu;

    $("dump_gdt").onclick = cpu.dump_gdt_ldt.bind(cpu);
    $("dump_idt").onclick = cpu.dump_idt.bind(cpu);
    $("dump_regs").onclick = () => { cpu.dump_regs_short(); cpu.dump_state(); };
    $("dump_pt").onclick = cpu.dump_page_structures.bind(cpu);

    $("dump_log").onclick = function()
    {
        dump_file(log_data.join(""), "v86.log");
    };

    $("debug_panel").style.display = "block";
    setInterval(function()
    {
        $("debug_panel").textContent =
            cpu.get_regs_short().join("\n") + "\n" + cpu.debug_get_state();

        $("dump_log").textContent = "Dump log" + (log_data.length ? " (" + log_data.length + " lines)" : "");
    }, 1000);

    // helps debugging
    window.cpu = cpu;
    window.h = h;
    window.dump_file = dump_file;
}

function onpopstate(e)
{
    location.reload();
}

function push_state(params)
{
    if(window.history.pushState)
    {
        const search = format_query_args(params);
        window.history.pushState({ search }, "", search);
    }
}
                                                                                                                                                                                                                                                                                                                       source/v64/src/browser/modem.js                                                                     0000644 0000000 0000000 00000065534 00000000000 013612  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_log } from "../log.js";
import { LOG_MODEM } from "../const.js";

// For Types Only
import { BusConnector } from "../bus.js";

/*
 * Hayes-compatible Modem emulation.
 *
 * Reference:
 * - [V250] V.250: Serial asynchronous automatic dialling and control
 *   https://www.itu.int/rec/T-REC-V.250-200307-I/en
 * - [TELIT] AT Commands Reference Guide
 *   https://docs.rs-online.com/c5f6/0900766b81541066.pdf
 */

const ASCII_BEL = 0x07;     // bell character
const ASCII_WS = 0x20;      // whitespace character " "
const ASCII_ZERO = 0x30;    // "0"

/*
 * AT command sprecifications
 *
 * The standard syntax for base AT commands is:
 *     "AT" ["&"]<CMD>[<ARG>]
 * - Commands that do not expect an argument are declared below using [].
 * - Commands that do not support a default argument value are declared using [<min>, <max>],
 *   with <min> and <max> defining the integer boundaries of <ARG>, both inclusive.
 * - Commands that support a default argument value are declared using [<min>, <max>, <default>].
 * - Commands having a non-standard syntax are declared using "custom".
 */
const AT_COMMANDS =
{
    "A":   [],          // [V250] 6.3.5 Answer
    "D":   "custom",    // [V250] 6.3.1 Dial
    "E":   [0, 1, 1],   // [V250] 6.2.4 Command echo
    "H":   [0, 0, 0],   // [V250] 6.3.6 Hook control
    "I":   [3, 3],      // [V250] 6.1.3 Request identification information
    "L":   [0, 3, 1],   // [V250] 6.3.13 Monitor speaker loudness
    "M":   [0, 2, 1],   // [V250] 6.3.14 Monitor speaker mode
    "O":   [0, 0, 0],   // [V250] 6.3.7 Return to online data state
    "P":   [],          // [V250] 6.3.3 Select pulse dialling
    "Q":   [0, 1, 0],   // [V250] 6.2.5 Result code suppression
    "S":   [0, 5],      // [V250] see Modem.reset() below
    "T":   [],          // [V250] 6.3.2 Select tone dialling
    "V":   [0, 1, 0],   // [V250] 6.2.6 DCE response format
    "X":   [0, 4, 0],   // [V250] 6.2.7 Result code selection
    "Z":   [0, 0, 0],   // [V250] 6.1.1 Reset to default configuration
    "&C":  [0, 1, 1],   // [V250] 6.2.8 Received line signal (DCD) detector behaviour
    "&D":  [0, 2, 2],   // [V250] 6.2.9 Data terminal ready (DTR) behaviour
    "&F":  [0, 0, 0],   // [V250] 6.1.2 Set to factory-defined configuration
    "&K":  [0, 6, 3]    // [TELIT] 3.5.3.2.9 Flow Control
};

// AT response codes
const AT_RESP_OK = 0;
const AT_RESP_CONNECT = 1;
const AT_RESP_RING = 2;
const AT_RESP_NO_CARRIER = 3;
const AT_RESP_ERROR = 4;

const AT_RESP_NAME =
{
    [AT_RESP_OK]: "OK",
    [AT_RESP_CONNECT]: "CONNECT",
    [AT_RESP_RING]: "RING",
    [AT_RESP_NO_CARRIER]: "NO CARRIER",
    [AT_RESP_ERROR]: "ERROR"
};

// S-Register indices
const SREG_AUTOANSWER_CNT = 0;
const SREG_RING_CNT = 1;
const SREG_ESC = 2;
const SREG_CR = 3;
const SREG_LF = 4;
const SREG_BS = 5;

// what to do when DTR drops from high to low (Modem.dtr_low_behaviour)
const DTR_LOW_IGNORE = 0;
const DTR_LOW_KEEP_CONN = 1;
const DTR_LOW_DROP_CONN = 2;

// online escape sequence timing
const ESC_MIN_PAUSE_MS = 1000;
const ESC_MAX_DELAY_MS = 200;

const CMDLINE_BUF_SIZE = 256;

const SEND_BUF_SIZE = 512;
const SEND_BUF_MAX_IDLE_TIME_MS = 5;

// matches all strings that start with "ws://" or "wss://" (case-insensitive)
const RE_WS_ADDR = /^ws[s]?:\/\//i;

const text_encoder = new TextEncoder();
const text_decoder = new TextDecoder();

/**
 * @constructor
 * @param {BusConnector} bus
 * @param {Object} options
 */
export function Modem(bus, options)
{
    /** @const @type {BusConnector} */
    this.bus = bus;

    /** @const @type {number} */
    this.uart = options.uart;

    /** @const @type {Uint8Array} */
    this.cli_buffer = new Uint8Array(CMDLINE_BUF_SIZE);

    // state that is not defined in this.reset():
    this.destroyed = false;
    this.dtr_state = false;
    this.rts_state = false;
    this.sreg = new Uint8Array(6);

    this.in_data_mode = false;
    this.data_mode_send_buffer = new Uint8Array(SEND_BUF_SIZE);
    this.data_mode_send_cursor = 0;
    this.data_mode_send_timer = null;
    this.data_mode_esc_timer = null;

    this.phonebook = options.phonebook || {};

    this.socket = null;

    this.reset();

    this.bus.register(`serial${this.uart}-data-terminal-ready-output`, this.uart_dtr_changed, this);
    this.bus.register(`serial${this.uart}-request-to-send-output`, this.uart_rts_changed, this);
    this.bus.register(`serial${this.uart}-output-byte`, this.uart_byte_received, this);
}

Modem.prototype.initialize = function()
{
    this.uart_set_dsr(true);
    this.uart_set_cts(true);
    this.uart_set_ring(false);
    this.uart_set_dcd(false);
    dbg_log(`Modem at UART${this.uart} ready`, LOG_MODEM);
};

Modem.prototype.destroy = function()
{
    this.destroyed = true;
    this.bus.unregister(`serial${this.uart}-data-terminal-ready-output`, this.uart_dtr_changed);
    this.bus.unregister(`serial${this.uart}-request-to-send-output`, this.uart_rts_changed);
    this.bus.unregister(`serial${this.uart}-output-byte`, this.uart_byte_received);
    this.cancel_data_mode_send_timer();
    this.cancel_data_mode_esc_timer();
    if(this.socket)
    {
        this.socket.close();
    }
};

Modem.prototype.cancel_data_mode_send_timer = function()
{
    if(this.data_mode_send_timer !== null)
    {
        clearTimeout(this.data_mode_send_timer);
        this.data_mode_send_timer = null;
    }
};

Modem.prototype.cancel_data_mode_esc_timer = function()
{
    if(this.data_mode_esc_timer !== null)
    {
        clearTimeout(this.data_mode_esc_timer);
        this.data_mode_esc_timer = null;
    }
};

Modem.prototype.reset = function()
{
    this.do_echo = true;
    this.cli_cursor = 0;
    this.cli_overflow = false;
    this.resp_suppress = false;
    this.resp_verbose = true;
    this.use_rtscts_flowctrl = true;
    this.use_tone_dialling = false;
    this.dcd_always_on = false;
    this.dtr_low_behaviour = DTR_LOW_DROP_CONN;

    this.uart_recv_tm = 0;
    this.data_mode_esc_count = 0;
    this.reset_on_disconnect = false;

    this.sreg[SREG_AUTOANSWER_CNT] = 0; // S0: Number of RINGs before automatic answer, see [V250] 6.3.8
    this.sreg[SREG_RING_CNT] = 0;       // S1: RING counter, see [TELIT] 3.5.3.6.2
    this.sreg[SREG_ESC] = 0x2b;         // S2: DATA mode escape character "+", see [TELIT] 3.5.3.6.3
    this.sreg[SREG_CR] = 0x0d;          // S3: Command line termination character "\r" (Carriage return), see [V250] 6.2.1
    this.sreg[SREG_LF] = 0x0a;          // S4: Response formatting character "\n" (Line feed), see [V250] 6.2.2
    this.sreg[SREG_BS] = 0x08;          // S5: Command line editing character "\b" (Backspace), see [V250] 6.2.3
};

/**
 * @param {boolean} dcd_state
 */
Modem.prototype.uart_set_dcd = function(dcd_state)
{
    dbg_log(`DCD=${dcd_state}`, LOG_MODEM);
    this.bus.send(`serial${this.uart}-carrier-detect-input`, dcd_state);
};

/**
 * @param {boolean} ring_state
 */
Modem.prototype.uart_set_ring = function(ring_state)
{
    dbg_log(`RING=${ring_state}`, LOG_MODEM);
    this.bus.send(`serial${this.uart}-ring-indicator-input`, ring_state);
};

/**
 * @param {boolean} dsr_state
 */
Modem.prototype.uart_set_dsr = function(dsr_state)
{
    dbg_log(`DSR=${dsr_state}`, LOG_MODEM);
    this.bus.send(`serial${this.uart}-data-set-ready-input`, dsr_state);
};

/**
 * @param {boolean} cts_state
 */
Modem.prototype.uart_set_cts = function(cts_state)
{
    dbg_log(`CTS=${cts_state}`, LOG_MODEM);
    this.bus.send(`serial${this.uart}-clear-to-send-input`, cts_state);
};

/**
 * @param {number} data
 */
Modem.prototype.uart_write_byte = function(data)
{
    this.bus.send(`serial${this.uart}-input`, data);
};

/**
 * @param {string} str
 */
Modem.prototype.uart_write = function(str)
{
    for(const ch of text_encoder.encode(str))
    {
        this.uart_write_byte(ch);
    }
};

/**
 * @param {boolean} dtr_state
 */
Modem.prototype.uart_dtr_changed = function(dtr_state)
{
    dtr_state = !!dtr_state;
    if(this.dtr_state !== dtr_state)
    {
        dbg_log(`DTR=${dtr_state}`, LOG_MODEM);
        this.dtr_state = dtr_state;
        if(this.socket && !dtr_state)
        {
            if(this.dtr_low_behaviour === DTR_LOW_KEEP_CONN)
            {
                this.enter_cli_mode();
                this.cli_write_response_code(AT_RESP_OK);
            }
            else if(this.dtr_low_behaviour === DTR_LOW_DROP_CONN)
            {
                this.socket.close();
            }
        }
    }
};

/**
 * @param {boolean} rts_state
 */
Modem.prototype.uart_rts_changed = function(rts_state)
{
    rts_state = !!rts_state;
    if(this.rts_state !== rts_state)
    {
        dbg_log(`RTS=${rts_state}`, LOG_MODEM);
        this.rts_state = rts_state;
    }
};

/**
 * @param {number} data
 */
Modem.prototype.uart_byte_received = function(data)
{
    this.cancel_data_mode_esc_timer();
    if(this.in_data_mode)
    {
        this.data_mode_uart_recv(data);
    }
    else
    {
        this.cli_mode_uart_recv(data);
    }
};

Modem.prototype.enter_cli_mode = function()
{
    if(this.in_data_mode)
    {
        dbg_log(`switching to command mode`, LOG_MODEM);
        this.in_data_mode = false;
        this.cancel_data_mode_esc_timer();
        this.cancel_data_mode_send_timer();
        this.data_mode_flush();
        this.uart_set_dsr(true);
        this.uart_set_cts(true);
        this.uart_set_ring(false);
        if(!this.dcd_always_on)
        {
            this.uart_set_dcd(this.socket !== null);
        }
    }
};

Modem.prototype.enter_data_mode = function()
{
    if(!this.in_data_mode)
    {
        dbg_log(`switching to data mode`, LOG_MODEM);
        this.in_data_mode = true;
        this.data_mode_send_cursor = 0;
        this.uart_set_ring(false);
        if(!this.dcd_always_on)
        {
            this.uart_set_dcd(true);
        }
    }
};

Modem.prototype.flush_escape_buffer = function()
{
    for(; this.data_mode_esc_count > 0; this.data_mode_esc_count--)
    {
        if(this.in_data_mode)
        {
            this.data_mode_send(this.sreg[SREG_ESC]);
        }
        else
        {
            this.uart_write_byte(this.sreg[SREG_ESC]);
        }
    }
};

/**
 * @param {number} data
 */
Modem.prototype.data_mode_send = function(data)
{
    if(this.socket)
    {
        this.cancel_data_mode_send_timer();
        this.data_mode_send_buffer[this.data_mode_send_cursor++] = data;
        if(this.data_mode_send_cursor === this.data_mode_send_buffer.byteLength)
        {
            this.data_mode_flush();
        }
        else
        {
            this.data_mode_send_timer = setTimeout(() => {
                this.data_mode_flush();
            }, SEND_BUF_MAX_IDLE_TIME_MS);
        }
    }
};

Modem.prototype.data_mode_flush = function()
{
    if(this.data_mode_send_cursor && this.socket && this.socket.readyState === WebSocket.OPEN)
    {
        if(this.data_mode_send_cursor === this.data_mode_send_buffer.byteLength)
        {
            this.socket.send(this.data_mode_send_buffer);
        }
        else
        {
            this.socket.send(this.data_mode_send_buffer.subarray(0, this.data_mode_send_cursor));
        }
    }
    this.data_mode_send_cursor = 0;
};

/**
 * @param {number} uart_byte
 */
Modem.prototype.data_mode_uart_recv = function(uart_byte)
{
    if(uart_byte === this.sreg[SREG_ESC] &&
        this.data_mode_esc_count < 3 &&
        (this.data_mode_esc_count > 0 || (performance.now() - this.uart_recv_tm) > ESC_MIN_PAUSE_MS))
    {
        // received an escape character (default "+", escape sequence: pause +++ pause)
        // - if it's the 1st in the sequence of 3 then a minimum pause of ESC_MIN_PAUSE_MS has passed before
        // - if it's the 2nd or 3rd then at most ESC_MAX_DELAY_MS have passed since the previous escape character
        // - if, after the 3rd, no other byte was received for a time of ESC_MIN_PAUSE_MS, accept the escape sequence
        // - in all other cases abort and send the 1..3 buffered escape characters
        if(++this.data_mode_esc_count < 3)
        {
            this.data_mode_esc_timer = setTimeout(() => {
                this.data_mode_esc_timer = null;
                this.flush_escape_buffer();
            }, ESC_MAX_DELAY_MS);
        }
        else
        {
            this.data_mode_esc_timer = setTimeout(() => {
                this.data_mode_esc_timer = null;
                this.enter_cli_mode();
                this.flush_escape_buffer();
                this.cli_write_response_code(AT_RESP_OK);
            }, ESC_MIN_PAUSE_MS);
        }
    }
    else
    {
        this.uart_recv_tm = performance.now();
        this.flush_escape_buffer();
        this.data_mode_send(uart_byte);
    }
};

/**
 * @param {number} uart_byte
 */
Modem.prototype.cli_mode_uart_recv = function(uart_byte)
{
    if(this.do_echo)
    {
        this.uart_write_byte(uart_byte);
        if(uart_byte === this.sreg[SREG_BS])
        {
            this.uart_write_byte(ASCII_WS);
            this.uart_write_byte(this.sreg[SREG_BS]);
        }
    }
    switch(uart_byte)
    {
        case this.sreg[SREG_BS]:
            if(this.cli_cursor > 0)
            {
                this.cli_cursor--;
            }
            break;
        case this.sreg[SREG_CR]:
            if(this.cli_overflow)
            {
                const data = text_decoder.decode(this.cli_buffer.buffer);
                dbg_log(`error: AT command buffer overflow: "${data}"`, LOG_MODEM);
                this.cli_overflow = false;
                // do NOT send any response when clearing buffer after overflow
            }
            else
            {
                this.cli_exec(text_decoder.decode(this.cli_buffer.slice(0, this.cli_cursor)).replace(/\s/g, ""));
            }
            this.cli_cursor = 0;
            break;
        case this.sreg[SREG_LF]:
            break;
        default:
            if(this.cli_cursor < this.cli_buffer.length)
            {
                this.cli_buffer[this.cli_cursor++] = uart_byte;
            }
            else
            {
                this.cli_overflow = true;
                this.uart_write_byte(ASCII_BEL);
            }
            break;
    }
};

/**
 * @param {Array} cmd_spec
 * @param {number|undefined} arg
 */
Modem.prototype.cli_decode_arg = function(cmd_spec, arg)
{
    if(arg === undefined)
    {
        if(cmd_spec.length)
        {
            if(cmd_spec.length > 2)
            {
                return cmd_spec[2];  // use default argument value
            }
            else
            {
                return false;  // error: missing required argument
            }
        }
    }
    else if(cmd_spec.length < 2 || arg < cmd_spec[0] || arg > cmd_spec[1])
    {
        return false;  // error: unexpected argument or value out of bounds
    }
    return arg;
};

/**
 * @param {string} dial_address
 * @param {boolean} use_wss_protocol
 */
Modem.prototype.cli_translate_dial_address = function(dial_address, use_wss_protocol)
{
    let ws_address;
    if(dial_address in this.phonebook)
    {
        ws_address = this.phonebook[dial_address];
    }
    else if(dial_address.length)
    {
        const m = dial_address.match(/(\d{1,3})[^\d]*(\d{1,3})[^\d]*(\d{1,3})[^\d]*(\d{1,3})[^\d]*(\d{0,5})/);
        if(m)
        {
            const num = (index, limit) => {
                if(m[index].length) {
                    const n = Number(m[index]);
                    return n < limit ? n : -1;
                }
                return undefined;
            };
            const n1 = num(1, 256), n2 = num(2, 256), n3 = num(3, 256), n4 = num(4, 256), n5 = num(5, 65536);
            if(n1 >= 0 && n2 >= 0 && n3 >= 0 && n4 >= 0 && (n5 === undefined || n5 >= 0))
            {
                ws_address = n5 === undefined ? `${n1}.${n2}.${n3}.${n4}` : `${n1}.${n2}.${n3}.${n4}:${n5}`;
            }
        }
        if(ws_address === undefined)
        {
            ws_address = dial_address;
        }
        if(!RE_WS_ADDR.test(ws_address))
        {
            ws_address = (use_wss_protocol ? "wss://" : "ws://") + ws_address;
        }
    }
    return ws_address;
};

/**
 * @param {string} dial_address
 * @param {number} offset
 */
Modem.prototype.cli_exec_dial = function(dial_address, offset)
{
    // strip prefix "T" or "P", quotes and trailing ";" from dial_address
    let enter_data_mode = true;
    let use_wss_protocol = this.use_tone_dialling;
    const index_semi = dial_address.lastIndexOf(";");
    if(index_semi >= 0)
    {
        enter_data_mode = false;
        dial_address = dial_address.substring(0, index_semi);
    }
    if(offset < dial_address.length)
    {
        const dial_method = dial_address[offset].toUpperCase();
        if(dial_method === "T" || dial_method === "P")
        {
            offset++;
            use_wss_protocol = dial_method === "T";
        }
    }
    if(offset < dial_address.length && dial_address[offset] === "\"")
    {
        offset++;
        const index_quot = dial_address.indexOf("\"", offset);
        if(index_quot >= 0)
        {
            dial_address = dial_address.substring(0, index_quot);
        }
    }
    dial_address = dial_address.substring(offset);

    // translate remaining dial address into a fully-qualified WebSocket address
    const ws_address = this.cli_translate_dial_address(dial_address, use_wss_protocol);
    if(ws_address === undefined)
    {
        dbg_log(`error: invalid dial address "${dial_address}"`, LOG_MODEM);
        this.cli_write_response_code(AT_RESP_ERROR);
        return;
    }

    // create and connect client WebSocket
    dbg_log(`connecting "${ws_address}"`, LOG_MODEM);
    try
    {
        this.socket = new WebSocket(ws_address);
    }
    catch(e)
    {
        dbg_log(`error: WebSocket constructor failed using address "${ws_address}"`, LOG_MODEM);
        this.cli_write_response_code(AT_RESP_ERROR);
        return;
    }

    this.socket.binaryType = "arraybuffer";
    this.socket.addEventListener("open", (event) => {
        if(enter_data_mode)
        {
            this.enter_data_mode();
            this.cli_write_response_code(AT_RESP_CONNECT);
        }
        else
        {
            this.cli_write_response_code(AT_RESP_OK);
        }
    });
    this.socket.addEventListener("message", (event) => {
        if(this.in_data_mode && (!this.use_rtscts_flowctrl || this.rts_state))
        {
            const bytes = new Uint8Array(event.data);
            for(let i=0; i<event.data.byteLength; i++)
            {
                this.uart_write_byte(bytes[i]);
            }
        }
    });
    this.socket.addEventListener("close", (event) => {
        this.socket = null;
        if(!this.destroyed)
        {
            this.enter_cli_mode();
            if(this.reset_on_disconnect)
            {
                this.reset();
                this.reset_on_disconnect = false;
            }
            this.cli_write_response_code(AT_RESP_NO_CARRIER);
        }
    });
};

/**
 * @param {string} cmdline
 */
Modem.prototype.cli_exec = function(cmdline)
{
    const length = cmdline.length;
    if(length === 0)
    {
        dbg_log(`received empty AT command line`, LOG_MODEM);
        if(this.socket && this.socket.readyState === WebSocket.CONNECTING)
        {
            // abort dial command, exit parser without response (delayed in "close" socket event)
            this.socket.close();
        }
        else
        {
            this.cli_write_response_code(AT_RESP_OK);
        }
        return;
    }
    let offset = cmdline.search(/(at|AT)/);
    if(offset < 0)
    {
        // do NOT send any response for non-empty lines without AT command (Trumpet Winsock trips over this)
        dbg_log(`error: missing AT command in "${cmdline}"`, LOG_MODEM);
        return;
    }
    offset += 2;

    const decode_uint = () => {
        const start_offset = offset;
        let acc = 0;
        while(offset < length)
        {
            const digit = cmdline.charCodeAt(offset) - ASCII_ZERO;
            if(digit < 0 || digit > 9)
            {
                break;
            }
            else
            {
                acc = acc * 10 + digit;
                offset++;
            }
        }
        return offset === start_offset ? undefined : acc;
    };

    dbg_log(`executing command line "${cmdline}"`, LOG_MODEM);

    let response_code = true;
    while(offset < length && response_code === true)
    {
        let cmd = cmdline[offset++].toUpperCase();
        if(offset < length && cmd === "&")
        {
            cmd += cmdline[offset++].toUpperCase();
        }
        if(!(cmd in AT_COMMANDS))
        {
            dbg_log(`error: unknown command "${cmd}"`, LOG_MODEM);
            response_code = AT_RESP_ERROR;
            break;
        }
        const cmd_spec = AT_COMMANDS[cmd];

        let arg;
        if(cmd_spec !== "custom")
        {
            arg = this.cli_decode_arg(cmd_spec, decode_uint());
            if(arg === false)
            {
                dbg_log(`error: bad argument for command "${cmd}"`, LOG_MODEM);
                response_code = AT_RESP_ERROR;
                break;
            }
        }

        if(arg !== undefined)
        {
            dbg_log(`AT command: "${cmd}${arg}"`, LOG_MODEM);
        }
        else
        {
            dbg_log(`AT command: "${cmd}"`, LOG_MODEM);
        }

        switch(cmd)
        {
            case "D":   // D[T|P](.*)[;]: Dial
                if(this.socket)
                {
                    response_code = AT_RESP_ERROR;
                }
                else
                {
                    this.cli_exec_dial(cmdline, offset);
                    response_code = false; // exit parser without response (delayed in dial command)
                }
                break;
            case "E":   // E[0..1]: Command echo
                this.do_echo = arg === 1;
                break;
            case "H":   // H[0]: Hook control
                if(this.socket)
                {
                    this.socket.close();
                    response_code = false; // exit parser without response (delayed in "close" socket event)
                }
                else
                {
                    response_code = AT_RESP_ERROR;
                }
                break;
            case "I":   // I3: Request identification information
                this.cli_write_info_text("V86 Modem Emulation");
                break;
            case "L":   // L[0..3]: Monitor speaker loudness
                break;
            case "M":   // M[0..3]: Monitor speaker mode
                break;
            case "O":   // O: Switch to online data mode
                if(this.socket)
                {
                    this.enter_data_mode();
                    response_code = AT_RESP_CONNECT;
                }
                else
                {
                    response_code = AT_RESP_ERROR;
                }
                break;
            case "P":   // P: Select pulse dialling
                this.use_tone_dialling = false;
                break;
            case "Q":   // Q[0..1]: Result code suppression
                this.resp_suppress = arg === 1;
                break;
            case "S":   // S(0..5) [?|=<n>]: Read or write register S<n>
                if(offset < length && cmdline[offset] === "?")
                {
                    offset++;
                    this.cli_write_info_text(this.sreg[arg].toString().padStart(3, "0"));
                }
                else if(offset < length && cmdline[offset] === "=")
                {
                    offset++;
                    const val = decode_uint();
                    if(val !== undefined && val < 256)
                    {
                        this.sreg[arg] = val;
                    }
                    else
                    {
                        response_code = AT_RESP_ERROR;
                    }
                }
                else
                {
                    response_code = AT_RESP_ERROR;
                }
                break;
            case "T":   // T: Select tone dialling
                this.use_tone_dialling = true;
                break;
            case "V":   // V[0..1]: DCE response format
                this.resp_verbose = arg === 1;
                break;
            case "X":   // X[0..4]: Result code selection
                break;
            case "Z":   // Z[0]: Reset to default configuration
            case "&F":  // &F[0]: Set to factory-defined configuration (same as Z, but continue command line evaluation)
                if(this.socket)
                {
                    this.reset_on_disconnect = true;
                    this.socket.close();
                    response_code = false; // exit parser without response (delayed in "close" socket event)
                }
                else
                {
                    this.reset();
                }
                break;
            case "&C":  // &C[0..1]: Received line signal (DCD) detector behaviour
                this.dcd_always_on = arg === 0;
                if(this.dcd_always_on)
                {
                    this.uart_set_dcd(true);
                }
                else
                {
                    this.uart_set_dcd(this.socket !== null);
                }
                break;
            case "&D":  // &D(0..2): Data terminal ready (DTR) behaviour
                this.dtr_low_behaviour = arg;
                break;
            case "&K":  // &K[0..6]: Flow Control
                if(arg === 0 || arg === 3)
                {
                    this.use_rtscts_flowctrl = arg === 3;
                }
                else
                {
                    response_code = AT_RESP_ERROR;
                }
                break;
            default:
                dbg_log(`error: command "${cmd}" is without implementation`, LOG_MODEM);
                response_code = AT_RESP_ERROR;
                break;
        }
    }

    if(response_code === true)
    {
        this.cli_write_response_code(AT_RESP_OK);
    }
    else if(typeof(response_code) === "number")
    {
        this.cli_write_response_code(response_code);
    }
};

/**
 * @param {string} text
 */
Modem.prototype.cli_write_info_text = function(text)
{
    dbg_log(`AT info response: "${text}"`, LOG_MODEM);
    if(this.resp_verbose)
    {
        this.uart_write_byte(this.sreg[SREG_CR]);
        this.uart_write_byte(this.sreg[SREG_LF]);
    }
    this.uart_write(text);
    this.uart_write_byte(this.sreg[SREG_CR]);
    this.uart_write_byte(this.sreg[SREG_LF]);
};

/**
 * @param {number} code
 */
Modem.prototype.cli_write_response_code = function(code)
{
    if(!this.resp_suppress)
    {
        const text = AT_RESP_NAME[code in AT_RESP_NAME ? code : AT_RESP_ERROR];
        if(this.resp_verbose)
        {
            dbg_log(`AT response: "${text}"`, LOG_MODEM);
            this.uart_write_byte(this.sreg[SREG_CR]);
            this.uart_write_byte(this.sreg[SREG_LF]);
            this.uart_write(text);
            this.uart_write_byte(this.sreg[SREG_CR]);
            this.uart_write_byte(this.sreg[SREG_LF]);
        }
        else
        {
            dbg_log(`AT response code: "${code} (${text})"`, LOG_MODEM);
            this.uart_write(code.toString());
            this.uart_write_byte(this.sreg[SREG_CR]);
        }
    }
};
                                                                                                                                                                    source/v64/src/browser/mouse.js                                                                     0000644 0000000 0000000 00000023600 00000000000 013625  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_log } from "../log.js";

// For Types Only
import { BusConnector } from "../bus.js";

/**
 * @constructor
 *
 * @param {BusConnector} bus
 */
export function MouseAdapter(bus, screen_container)
{
    const SPEED_FACTOR = 1;

    var left_down = false,
        right_down = false,
        middle_down = false,

        last_x = 0,
        last_y = 0,

        mouse = this;

    // set by controller
    this.enabled = false;

    // set by emulator
    this.emu_enabled = true;

    // set by the guest's absolute pointing device driver
    this.absolute_mouse = false;

    this.bus = bus;

    this.bus.register("mouse-enable", function(enabled)
    {
        this.enabled = enabled;
        this.update_cursor();
    }, this);

    this.bus.register("vmware-absolute-mouse", function(enabled)
    {
        this.absolute_mouse = enabled;
        this.update_cursor();
    }, this);

    // set by an absolute pointing device's driver (the ARM machines' virtio
    // tablet and touch screens): the guest draws its own cursor (a tablet; a
    // touch screen has none and the host's stays)
    this.guest_cursor = false;
    this.bus.register("absolute-pointer", function(state)
    {
        this.guest_cursor = state[0] && state[1];
        this.update_cursor();
    }, this);

    // set by the USB tablet (usb.tablet) while the guest uses it
    this.usb_tablet = false;
    this.bus.register("usb-tablet-active", function(active)
    {
        this.usb_tablet = !!active;
        this.update_cursor();
    }, this);

    // TODO: Should probably not use bus for this
    this.is_running = false;
    this.bus.register("emulator-stopped", function()
    {
        this.is_running = false;
    }, this);
    this.bus.register("emulator-started", function()
    {
        this.is_running = true;
    }, this);

    this.update_cursor = function()
    {
        if(screen_container)
        {
            // (the guest draws its own cursor where the host's is)
            const hide = this.emu_enabled && (this.usb_tablet || (this.absolute_mouse || this.guest_cursor) && this.enabled);
            screen_container.style.cursor = hide ? "none" : "";
        }
    };

    this.destroy = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        window.removeEventListener("touchstart", touch_start_handler, false);
        window.removeEventListener("touchend", touch_end_handler, false);
        window.removeEventListener("touchmove", mousemove_handler, false);
        window.removeEventListener("mousemove", mousemove_handler, false);
        window.removeEventListener("mousedown", mousedown_handler, false);
        window.removeEventListener("mouseup", mouseup_handler, false);
        window.removeEventListener("wheel", mousewheel_handler, { passive: false });
        window.removeEventListener("contextmenu", contextmenu_handler, false);
        document.removeEventListener("pointerlockchange", pointerlockchange_handler, false);
    };

    this.init = function()
    {
        if(typeof window === "undefined")
        {
            return;
        }
        this.destroy();

        window.addEventListener("touchstart", touch_start_handler, false);
        window.addEventListener("touchend", touch_end_handler, false);
        window.addEventListener("touchmove", mousemove_handler, false);
        window.addEventListener("mousemove", mousemove_handler, false);
        window.addEventListener("mousedown", mousedown_handler, false);
        window.addEventListener("mouseup", mouseup_handler, false);
        window.addEventListener("wheel", mousewheel_handler, { passive: false });
        window.addEventListener("contextmenu", contextmenu_handler, false);
        document.addEventListener("pointerlockchange", pointerlockchange_handler, false);
    };
    this.init();

    function pointerlockchange_handler()
    {
        mouse.bus.send("mouse-pointer-lock", !!document.pointerLockElement);
    }

    function contextmenu_handler(e)
    {
        if(may_handle(e))
        {
            e.preventDefault();
        }
    }

    function is_child(child, parent)
    {
        while(child.parentNode)
        {
            if(child === parent)
            {
                return true;
            }
            child = child.parentNode;
        }

        return false;
    }

    function may_handle(e)
    {
        if(!mouse.enabled || !mouse.emu_enabled)
        {
            return false;
        }

        const MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY = true;

        if(MOVE_MOUSE_WHEN_OVER_SCREEN_ONLY)
        {
            var parent = screen_container || document.body;
            return document.pointerLockElement || is_child(e.target, parent);
        }
        else
        {
            if(e.type === "mousemove" || e.type === "touchmove")
            {
                return true;
            }

            if(e.type === "mousewheel" || e.type === "DOMMouseScroll")
            {
                return is_child(e.target, parent);
            }

            return !e.target || e.target.nodeName !== "INPUT" && e.target.nodeName !== "TEXTAREA";
        }
    }

    function touch_start_handler(e)
    {
        if(may_handle(e))
        {
            var touches = e["changedTouches"];

            if(touches && touches.length)
            {
                var touch = touches[touches.length - 1];
                last_x = touch.clientX;
                last_y = touch.clientY;
            }
            send_touches(e);
        }
    }

    function touch_end_handler(e)
    {
        if(left_down || middle_down || right_down)
        {
            mouse.bus.send("mouse-click", [false, false, false]);
            left_down = middle_down = right_down = false;
        }
        send_touches(e);
    }

    /**
     * The touches on the screen, for a multi-touch device (the virt
     * machine's virtio-input, docs/arm64-virt-android16-plan.md P7.4):
     * each one's identifier and place on the screen, and its size
     */
    function send_touches(e)
    {
        if(!mouse.bus || !screen_container || !mouse.is_running) return;
        const rect = screen_container.getBoundingClientRect();
        const touches = Array.from(e["touches"] || [], touch =>
            [touch["identifier"], touch.clientX - rect.left, touch.clientY - rect.top]);
        mouse.bus.send("touch", { "touches": touches, "width": rect.width, "height": rect.height });
    }

    function mousemove_handler(e)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(!may_handle(e))
        {
            return;
        }

        if(!mouse.is_running)
        {
            return;
        }

        var delta_x = 0;
        var delta_y = 0;

        var touches = e["changedTouches"];

        if(touches)
        {
            if(touches.length)
            {
                var touch = touches[touches.length - 1];
                delta_x = touch.clientX - last_x;
                delta_y = touch.clientY - last_y;

                last_x = touch.clientX;
                last_y = touch.clientY;

                e.preventDefault();
            }
            send_touches(e);
        }
        else
        {
            if(typeof e["movementX"] === "number")
            {
                delta_x = e["movementX"];
                delta_y = e["movementY"];
            }
            else if(typeof e["webkitMovementX"] === "number")
            {
                delta_x = e["webkitMovementX"];
                delta_y = e["webkitMovementY"];
            }
            else if(typeof e["mozMovementX"] === "number")
            {
                delta_x = e["mozMovementX"];
                delta_y = e["mozMovementY"];
            }
            else
            {
                // Fallback for other browsers?
                delta_x = e.clientX - last_x;
                delta_y = e.clientY - last_y;

                last_x = e.clientX;
                last_y = e.clientY;
            }
        }

        delta_x *= SPEED_FACTOR;
        delta_y *= SPEED_FACTOR;

        //if(Math.abs(delta_x) > 100 || Math.abs(delta_y) > 100)
        //{
        //    // Large mouse delta, drop?
        //}

        delta_y = -delta_y;

        // NOTE: affected by https://issues.chromium.org/issues/40737979
        //       Causes cursor jumps on multi-monitor and/or 120+ HZ monitors

        mouse.bus.send("mouse-delta", [delta_x, delta_y]);

        // Under pointer lock the page coordinates don't change, so no
        // meaningful absolute position can be reported
        if(screen_container && !document.pointerLockElement)
        {
            const rect = screen_container.getBoundingClientRect();
            mouse.bus.send("mouse-absolute", [
                e.clientX - rect.left, e.clientY - rect.top, rect.width, rect.height]);
        }
    }

    function mousedown_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, true);
        }
    }

    function mouseup_handler(e)
    {
        if(may_handle(e))
        {
            click_event(e, false);
        }
    }

    function click_event(e, down)
    {
        if(!mouse.bus)
        {
            return;
        }

        if(e.which === 1)
        {
            left_down = down;
        }
        else if(e.which === 2)
        {
            middle_down = down;
        }
        else if(e.which === 3)
        {
            right_down = down;
        }
        else
        {
            dbg_log("Unknown event.which: " + e.which);
        }
        mouse.bus.send("mouse-click", [left_down, middle_down, right_down]);
        e.preventDefault();
    }

    function mousewheel_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var delta_x = e.wheelDelta || -e.detail;
        var delta_y = 0;

        if(delta_x < 0)
        {
            delta_x = -1;
        }
        else if(delta_x > 0)
        {
            delta_x = 1;
        }

        mouse.bus.send("mouse-wheel", [delta_x, delta_y]);
        e.preventDefault();
    }
}
                                                                                                                                source/v64/src/browser/network.js                                                                   0000644 0000000 0000000 00000006265 00000000000 014176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // For Types Only
import { BusConnector } from "../bus.js";

/**
 * An ethernet-through-websocket adapter, to be used with
 *     https://github.com/benjamincburns/websockproxy
 *
 * emulated ethernet card <--> this <--> websocket proxy <--> network
 *
 * @constructor
 *
 * @param {string} url
 * @param {BusConnector} bus
 * @param {number} [id=0] id
 */
export function NetworkAdapter(url, bus, id)
{
    this.bus = bus;
    this.socket = undefined;
    this.id = id || 0;

    // TODO: circular buffer?
    this.send_queue = [];
    this.url = url;

    this.reconnect_interval = 10000;
    this.last_connect_attempt = Date.now() - this.reconnect_interval;
    this.send_queue_limit = 64;
    this.destroyed = false;

    this.bus.register("net" + this.id + "-send", function(data)
    {
        this.send(data);
    }, this);
}

NetworkAdapter.prototype.handle_message = function(e)
{
    if(this.bus)
    {
        this.bus.send("net" + this.id + "-receive", new Uint8Array(e.data));
    }
};

NetworkAdapter.prototype.handle_close = function(e)
{
    //console.log("onclose", e);

    if(!this.destroyed)
    {
        this.connect();
        setTimeout(this.connect.bind(this), this.reconnect_interval);
    }
};

NetworkAdapter.prototype.handle_open = function(e)
{
    //console.log("open", e);

    for(var i = 0; i < this.send_queue.length; i++)
    {
        this.send(this.send_queue[i]);
    }

    this.send_queue = [];
};

NetworkAdapter.prototype.handle_error = function(e)
{
    //console.log("onerror", e);
};

NetworkAdapter.prototype.destroy = function()
{
    this.destroyed = true;
    if(this.socket)
    {
        this.socket.close();
    }
};

NetworkAdapter.prototype.connect = function()
{
    if(typeof WebSocket === "undefined")
    {
        return;
    }

    if(this.socket)
    {
        var state = this.socket.readyState;

        if(state === 0 || state === 1)
        {
            // already or almost there
            return;
        }
    }

    var now = Date.now();

    if(this.last_connect_attempt + this.reconnect_interval > now)
    {
        return;
    }

    this.last_connect_attempt = Date.now();

    try
    {
        this.socket = new WebSocket(this.url);
    }
    catch(e)
    {
        console.error(e);
        return;
    }

    this.socket.binaryType = "arraybuffer";

    this.socket.onopen = this.handle_open.bind(this);
    this.socket.onmessage = this.handle_message.bind(this);
    this.socket.onclose = this.handle_close.bind(this);
    this.socket.onerror = this.handle_error.bind(this);
};

NetworkAdapter.prototype.send = function(data)
{
    //console.log("send", data);

    if(!this.socket || this.socket.readyState !== 1)
    {
        this.send_queue.push(data);

        if(this.send_queue.length > 2 * this.send_queue_limit)
        {
            this.send_queue = this.send_queue.slice(-this.send_queue_limit);
        }

        this.connect();
    }
    else
    {
        this.socket.send(data);
    }
};

NetworkAdapter.prototype.change_proxy = function(url)
{
    this.url = url;

    if(this.socket)
    {
        this.socket.onclose = function() {};
        this.socket.onerror = function() {};
        this.socket.close();
        this.socket = undefined;
    }
};
                                                                                                                                                                                                                                                                                                                                           source/v64/src/browser/print_stats.js                                                               0000644 0000000 0000000 00000003713 00000000000 015052  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       export function stats_to_string(cpu)
{
    return print_misc_stats(cpu);
}

function print_misc_stats(cpu)
{
    let text = "";

    // Keep in sync with the stat enum in src/rust/profiler.rs.
    const stat_names = [
        "RUN_INTERPRETED",
        "RUN_INTERPRETED_STEPS",
        "RUN_INTERPRETED_STEPS/RUN_INTERPRETED",
        "DIRTY_PAGE_DID_NOT_HAVE_CODE",
        "PAGE_FAULT",
        "TLB_MISS",
        "MAIN_LOOP",
        "MAIN_LOOP_IDLE",
        "DO_MANY_CYCLES",
        "CYCLE_INTERNAL",
        "CLEAR_TLB",
        "FULL_CLEAR_TLB",
        "TLB_FULL",
        "TLB_GLOBAL_FULL",
        "X87_EXACT",
        "X87_SOFTFLOAT",
        "X87_NATIVE_F64",
    ];

    let j = 0;
    const stat_values = {};
    for(let i = 0; i < stat_names.length; i++)
    {
        const name = stat_names[i];
        let value;
        if(name.includes("/"))
        {
            j++; // skip profiler_stat_get
            const [left, right] = name.split("/");
            value = stat_values[left] / stat_values[right];
        }
        else
        {
            const stat = stat_values[name] = cpu.wm.exports["profiler_stat_get"](i - j);
            value = stat >= 100e6 ? Math.round(stat / 1e6) + "m" : stat >= 100e3 ? Math.round(stat / 1e3) + "k" : stat;
        }
        text += name + "=" + value + "\n";
    }

    text += "\n";

    const tlb_entries = cpu.wm.exports["get_valid_tlb_entries_count"]();
    const global_tlb_entries = cpu.wm.exports["get_valid_global_tlb_entries_count"]();
    const nonglobal_tlb_entries = tlb_entries - global_tlb_entries;

    text += "TLB_ENTRIES=" + tlb_entries + " (" + global_tlb_entries + " global, " + nonglobal_tlb_entries + " non-global)\n";
    text += "WASM_TABLE_FREE=" + cpu.wm.exports["jit_get_wasm_table_index_free_list_count"]() + "\n";
    text += "FLAT_SEGMENTS=" + cpu.wm.exports["has_flat_segmentation"]() + "\n";

    text += "wasm memory size: " + (cpu.wasm_memory.buffer.byteLength >> 20) + "m\n";

    return text;
}
                                                     source/v64/src/browser/query_compat.js                                                              0000644 0000000 0000000 00000023301 00000000000 015203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The old page's address (docs/vm-manager-plan.md, U0): ?profile=, ?hda.url=
// and the rest, as the page's settings, and a start's settings from the
// profile, the address and the form (src/browser/vm_options.js). Sites and
// bookmarks link to these addresses; the VM manager and the debug page both
// import this module (the plan's G5: no Closure defines, no internals).

import { CPU_TYPES, MACHINE_TYPES, Q35_ROOT_PORTS_MAX } from "../machine_options.js";
import { clamp_chunk_size, clamp_memory_size, clamp_vram_size, set_memory_size, profile_settings, apply_form } from "./vm_options.js";

/**
 * A boolean argument: present and not "0"
 * @param {*} x
 * @return {boolean}
 */
export function bool_arg(x)
{
    return !!x && x !== "0";
}

/**
 * ?cpu_type=; undefined when absent or unknown
 * @param {URLSearchParams} query_args
 * @return {string|undefined}
 */
export function cpu_type_arg(query_args)
{
    const cpu_type = query_args.get("cpu_type");
    return cpu_type && CPU_TYPES.includes(cpu_type) ? cpu_type : undefined;
}

/**
 * ?machine_type=; undefined when absent or unknown
 * @param {URLSearchParams} query_args
 * @return {string|undefined}
 */
export function machine_type_arg(query_args)
{
    const machine_type = query_args.get("machine_type");
    return machine_type && MACHINE_TYPES.includes(machine_type) ? machine_type : undefined;
}

/**
 * ?root_ports=: Q35's PCI Express root ports; undefined when absent or out of range
 * @param {URLSearchParams} query_args
 * @return {number|undefined}
 */
export function root_ports_arg(query_args)
{
    const ports = parseInt(query_args.get("root_ports"), 10);
    return ports >= 0 && ports <= Q35_ROOT_PORTS_MAX ? ports : undefined;
}

/**
 * The address's settings: on top of a profile's, except those a state image
 * (the profile's initial_state) does not allow
 * @param {!Object} settings
 * @param {!URLSearchParams} query_args
 */
export function apply_query_args(settings, query_args)
{
    // ignore certain settings when using a state image
    if(!settings.initial_state)
    {
        const chunk_size = clamp_chunk_size(parseInt(query_args.get("chunk_size"), 10));

        if(query_args.has("hda.url"))
        {
            settings.hda = {
                size: parseInt(query_args.get("hda.size"), 10) || undefined,
                // TODO: synchronous if small?
                url: query_args.get("hda.url"),
                fixed_chunk_size: chunk_size,
                async: true,
            };
        }
        else if(query_args.has("hda.empty"))
        {
            const empty_size = parseInt(query_args.get("hda.empty"), 10);
            if(empty_size > 0)
            {
                settings.hda = { buffer: new ArrayBuffer(empty_size) };
            }
        }

        if(query_args.has("hdb.url"))
        {
            settings.hdb = {
                size: parseInt(query_args.get("hdb.size"), 10) || undefined,
                // TODO: synchronous if small?
                url: query_args.get("hdb.url"),
                fixed_chunk_size: chunk_size,
                async: true,
            };
        }
        else if(query_args.has("hdb.empty"))
        {
            const empty_size = parseInt(query_args.get("hdb.empty"), 10);
            if(empty_size > 0)
            {
                settings.hdb = { buffer: new ArrayBuffer(empty_size) };
            }
        }

        if(query_args.has("cdrom.url"))
        {
            settings.cdrom = {
                size: parseInt(query_args.get("cdrom.size"), 10) || undefined,
                url: query_args.get("cdrom.url"),
                fixed_chunk_size: chunk_size,
                async: true,
            };
        }

        if(query_args.has("fda.url"))
        {
            settings.fda = {
                size: parseInt(query_args.get("fda.size"), 10) || undefined,
                url: query_args.get("fda.url"),
                async: false,
            };
        }

        // the disks' policies (docs/disk-persistence-plan.md): hda.disk_option=read_write
        // with a disk service's URL writes the guest's changes back; hda.disk_error=report
        // (the settings' names as properties, as main.js had them for its ADVANCED build)
        for(const [name, disk] of [["hda", settings.hda], ["hdb", settings.hdb], ["fda", settings.fda]])
        {
            if(!disk) continue;
            if(query_args.has(name + ".disk_option")) disk.disk_option = query_args.get(name + ".disk_option");
            if(query_args.has(name + ".disk_error")) disk.disk_error = query_args.get(name + ".disk_error");
        }

        // (a kernel and an initrd: the PC's bzImage, or the arm64 virt machine's Image)
        if(query_args.has("kernel.url")) settings.bzimage = { url: query_args.get("kernel.url"), async: false };
        if(query_args.has("initrd.url")) settings.initrd = { url: query_args.get("initrd.url"), async: false };
        if(query_args.has("cmdline")) settings.cmdline = query_args.get("cmdline");

        const m = parseInt(query_args.get("m"), 10);
        if(m > 0)
        {
            set_memory_size(settings, clamp_memory_size(m));
        }

        const cores = parseInt(query_args.get("cores"), 10);
        if(cores > 0)
        {
            settings.cpu_cores = cores;
        }
        if(query_args.has("parallel"))
        {
            settings.parallel = bool_arg(query_args.get("parallel"));
        }
        settings.cpu_type = cpu_type_arg(query_args);
        settings.machine_type = machine_type_arg(query_args);
        if(query_args.has("hpet")) settings.hpet = bool_arg(query_args.get("hpet"));
        if(query_args.has("smbus")) settings.smbus = bool_arg(query_args.get("smbus"));
        settings.pcie_root_ports = root_ports_arg(query_args);

        const vram = parseInt(query_args.get("vram"), 10);
        if(vram > 0)
        {
            settings.vram_size = clamp_vram_size(vram) * 1024 * 1024;
        }
        if(query_args.has("graphics_adapter"))
        {
            settings.graphics_adapter = query_args.get("graphics_adapter");
        }
        // virtio_gpu: how many displays the guest gets (side by side in
        // the window), a developer's setting
        if(query_args.has("displays"))
        {
            settings.displays = Math.max(1, Math.min(4, parseInt(query_args.get("displays"), 10) || 1));
        }

        settings.acpi = query_args.has("acpi") ? bool_arg(query_args.get("acpi")) : settings.acpi;
        settings.use_bochs_bios = query_args.get("bios") === "bochs";
        settings.net_device_type = query_args.get("net_device_type") || settings.net_device_type;
        settings.audio_device = query_args.get("audio_device") || settings.audio_device;
        settings.mtu = parseInt(query_args.get("mtu"), 10) || undefined;
    }

    settings.relay_url = query_args.get("relay_url");
    settings.disable_jit = bool_arg(query_args.get("disable_jit"));
    settings.disable_audio = bool_arg(query_args.get("mute"));

    if(query_args.has("modem"))
    {
        const modem = parseInt(query_args.get("modem"), 10);
        if(!Number.isNaN(modem) && modem >= 0 && modem < 4)
        {
            settings.modem = {uart: modem};
        }
    }
}

/**
 * A start's settings (the old page's start_emulation): the profile's, the
 * address's (query_args: null when the user started from the form) and the
 * form's (DEFAULT_FORM when there is none), and the CPU's policies of the address
 * @param {Object} profile
 * @param {URLSearchParams} query_args
 * @param {!Object} form
 * @param {{location_args: !URLSearchParams, origin: string, debug: boolean, graphics_proxy: boolean}} page the page's
 *     address (the CPU's policies when query_args is null), origin, debug builds and graphics proxy
 * @return {{settings: !Object, new_query_args: !Map<string, string>, cpu_worker: boolean,
 *     error: (string|undefined), title: (string|undefined), updates: !Object}} new_query_args: the start's
 *     address for push_state; error: why it cannot start; title: of the chosen files; updates: the form's
 *     fields the start changed
 */
export function start_settings(profile, query_args, form, page)
{
    // Manual starts rebuild the URL. Read the CPU policies before push_state
    // and preserve the ones that differ from the defaults.
    const cpu_args = query_args || page.location_args;

    // The CPU runs in a Worker unless the URL says ?cpu_worker=0
    const cpu_worker = !cpu_args.has("cpu_worker") || bool_arg(cpu_args.get("cpu_worker"));

    const new_query_args = new Map();
    new_query_args.set("profile", profile?.id || "custom");
    if(!cpu_worker) new_query_args.set("cpu_worker", "0");
    if(page.graphics_proxy) new_query_args.set("graphics_proxy", "1");
    // ir_tier0 (32-bit code in the x64 page tier) and the x87 fast paths are on unless the URL passes =0.
    const settings = {};
    for(const name of ["ir_tier0", "x87_fast_math", "x87_jit_cache"])
    {
        settings[name] = !cpu_args.has(name) || bool_arg(cpu_args.get(name));
        if(!settings[name]) new_query_args.set(name, "0");
    }

    if(profile)
    {
        profile_settings(profile, settings);
    }

    if(query_args)
    {
        apply_query_args(settings, query_args);
    }

    const { error, title, updates } = apply_form(settings, form, new_query_args, page);
    return { settings, new_query_args, cpu_worker, error, title, updates };
}

/**
 * The address of a start's arguments (new_query_args), as push_state writes it
 * @param {!Map<string, string>|!URLSearchParams} params
 * @return {string}
 */
export function format_query_args(params)
{
    const entries = Array.from(params.entries());
    if(entries.length)
    {
        return "?" + entries.map(([key, value]) => key + "=" + value.replace(/[?&=#+]/g, encodeURIComponent)).join("&");
    }
    else
    {
        return "";
    }
}
                                                                                                                                                                                                                                                                                                                               source/v64/src/browser/screen.js                                                                    0000644 0000000 0000000 00000060164 00000000000 013762  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "../log.js";
import { get_charmap } from "../lib.js";
import { DISPLAY_FLAG_BLINKING, DISPLAY_FLAG_FONT_PAGE_B } from "../display.js";

// For Types Only
import { DisplaySink } from "../display.js";

// Draws entire buffer and visualizes the layers that would be drawn
export const DEBUG_SCREEN_LAYERS = DEBUG && false;

/**
 * The default way to put pixels on the canvas: its 2D context. The other one is
 * a WebGPU compositor that also shows guest D3D/GL windows
 * (glbridge/webgpu_compositor.js); both have these methods, under quoted names
 * because the compositor is not compiled with this file.
 * @param {!HTMLCanvasElement} canvas
 * @return {!Object}
 */
function create_canvas2d_backend(canvas)
{
    const context = canvas.getContext("2d", { alpha: false });

    /** @type {ImageData} */
    let image_data = null;
    /** @type {Uint8ClampedArray} */
    let image_source = null;

    /**
     * ImageData over a pixel buffer, reused while the buffer is. ImageData
     * refuses shared memory (cores in host threads, src/parallel): then copy
     * the rows that are drawn.
     * @param {!Uint8ClampedArray} data
     * @param {number} stride
     * @param {number} rows
     * @param {number} first_row
     * @param {number} row_count
     * @return {!ImageData}
     */
    function image_data_for(data, stride, rows, first_row, row_count)
    {
        if(typeof SharedArrayBuffer !== "undefined" && data.buffer instanceof SharedArrayBuffer)
        {
            if(!image_data || image_source !== null || image_data.width !== stride || image_data.height !== rows)
            {
                image_data = new ImageData(stride, rows);
                image_source = null;
            }
            const first = Math.max(0, first_row) * stride * 4;
            const end = Math.min(rows, first_row + row_count) * stride * 4;
            if(first < end) image_data.data.set(data.subarray(first, end), first);
            return /** @type {!ImageData} */ (image_data);
        }
        if(image_source !== data)
        {
            image_data = new ImageData(data, stride, rows);
            image_source = data;
        }
        return /** @type {!ImageData} */ (image_data);
    }

    return {
        "context": context,
        "attach_presenter": presenter => {},
        "resize": (width, height) => {
            // reset whenever the canvas is resized
            context.imageSmoothingEnabled = false;
        },
        // like putImageData: (sx, sy, sw, sh) of a buffer `stride` pixels wide goes to (dx, dy)
        "put_pixels": (data, stride, rows, sx, sy, sw, sh, dx, dy) => {
            context.putImageData(image_data_for(data, stride, rows, sy, sh), dx - sx, dy - sy, sx, sy, sw, sh);
        },
        "clear": () => {
            context.fillStyle = "#000";
            context.fillRect(0, 0, canvas.width, canvas.height);
        },
        "present": () => {},
        "screenshot": () => canvas.toDataURL("image/png"),
    };
}

/**
 * Adapter to use visual screen in browsers (in contrast to node). Everything
 * is drawn on one canvas: text mode with the guest's own VGA font, graphics
 * modes from the device's pixels.
 * @constructor
 * @implements {DisplaySink}
 * @param {Object} options
 * @param {function(boolean)} screen_fill_buffer asks the device for a new picture,
 *        with every pixel when the argument is true
 */
export function ScreenAdapter(options, screen_fill_buffer)
{
    const screen_container = options.container;
    this.screen_fill_buffer = screen_fill_buffer;

    console.assert(screen_container, "options.container must be provided");

    const MODE_GRAPHICAL = 1;
    const MODE_GRAPHICAL_TEXT = 2;

    const CHARACTER_INDEX = 0;
    const FLAGS_INDEX = 1;
    const BG_COLOR_INDEX = 2;
    const FG_COLOR_INDEX = 3;
    const TEXT_BUF_COMPONENT_SIZE = 4;

    const FLAG_BLINKING = DISPLAY_FLAG_BLINKING;
    const FLAG_FONT_PAGE_B = DISPLAY_FLAG_FONT_PAGE_B;

    // Pages written for the old two-canvas graphics proxy tag its overlay
    // canvas data-v86-graphics; the screen is the other one.
    let graphic_screen = options.canvas || Array.from(screen_container.getElementsByTagName("canvas"))
        .find(canvas => !canvas.hasAttribute("data-v86-graphics"));
    if(!graphic_screen)
    {
        graphic_screen = document.createElement("canvas");
        screen_container.appendChild(graphic_screen);
    }
    // Where the pixels go (create_canvas2d_backend). With options.deferred_backend
    // the canvas is left alone until set_backend or use_canvas2d chooses.
    /** @type {Object} */
    let backend = null;
    let full_frame_wanted = false;
    this.get_graphics_canvas = () => graphic_screen;
    this.is_graphical = () => mode === MODE_GRAPHICAL;
    this.on_geometry_change = null;
    const notify_geometry = () => this.on_geometry_change && this.on_geometry_change();

    var
        /** @type {number} */
        cursor_row,

        /** @type {number} */
        cursor_col,

        /** @type {number} */
        scale_x = options.scale !== undefined ? options.scale : 1,

        /** @type {number} */
        scale_y = options.scale !== undefined ? options.scale : 1,

        base_scale = 1,

        changed_rows,

        // current display mode: MODE_GRAPHICAL or MODE_GRAPHICAL_TEXT
        mode,

        // Index 0: ASCII code
        // Index 1: Flags bitset (see FLAG_...)
        // Index 2: Background color
        // Index 3: Foreground color
        text_mode_data,

        // number of columns
        text_mode_width,

        // number of rows
        text_mode_height,

        // the text screen's pixels, drawn from the guest's font
        /** @type {ImageData} */
        text_image = null,
        /** @type {Uint32Array} */
        text_pixels = null,

        // fonts: a copy of VGA plane 2, 8 pages of 256 glyphs of 32 bytes
        /** @type {Uint8Array} */
        font_bitmap = null,
        font_height,
        font_width,
        font_width_9px,
        font_width_dbl,
        font_copy_8th_col,
        font_page_a = 0,
        font_page_b = 0,

        // blink state
        blink_visible,
        tm_last_update = 0,

        // cursor attributes
        cursor_start,
        cursor_end,
        cursor_enabled,

        // 8-bit-text to Unicode character map
        charmap = get_charmap(options.encoding),

        // render loop state
        timer_id = 0,
        paused = false;

    /**
     * @param {number} color 0xRRGGBB
     * @return {number} the same colour as an RGBA ImageData pixel, read as one little-endian word
     */
    function to_pixel(color)
    {
        return 0xFF000000 | (color & 0xFF) << 16 | color & 0xFF00 | color >> 16 & 0xFF;
    }

    /**
     * Draw one text row into text_pixels, in plain JS: the result is exact and
     * does not depend on how the browser composites canvases.
     * @param {number} row
     */
    function render_row(row)
    {
        const width = text_image.width;
        const row_start = row * font_height * width;
        for(let col = 0, txt_i = row * text_mode_width * TEXT_BUF_COMPONENT_SIZE; col < text_mode_width; col++, txt_i += TEXT_BUF_COMPONENT_SIZE)
        {
            const chr = text_mode_data[txt_i + CHARACTER_INDEX];
            const flags = text_mode_data[txt_i + FLAGS_INDEX];
            const bg = to_pixel(text_mode_data[txt_i + BG_COLOR_INDEX]);
            const fg = to_pixel(text_mode_data[txt_i + FG_COLOR_INDEX]);
            const page = flags & FLAG_FONT_PAGE_B ? font_page_b : font_page_a;
            const visible = !(flags & FLAG_BLINKING) || blink_visible;
            const glyph = (page << 13) + chr * 32;
            // line graphics characters extend into the 9th column
            const ninth = font_width_9px && font_copy_8th_col && chr >= 0xC0 && chr <= 0xDF;

            for(let y = 0, p = row_start + col * font_width; y < font_height; y++, p += width)
            {
                const bits = visible ? font_bitmap[glyph + y] : 0;
                if(font_width_dbl)
                {
                    for(let x = 0; x < 8; x++)
                    {
                        const color = bits & 0x80 >> x ? fg : bg;
                        text_pixels[p + 2 * x] = color;
                        text_pixels[p + 2 * x + 1] = color;
                    }
                }
                else
                {
                    for(let x = 0; x < 8; x++)
                    {
                        text_pixels[p + x] = bits & 0x80 >> x ? fg : bg;
                    }
                    if(font_width_9px)
                    {
                        text_pixels[p + 8] = ninth && bits & 1 ? fg : bg;
                    }
                }
            }
        }

        if(row === cursor_row && cursor_enabled && blink_visible && cursor_col < text_mode_width)
        {
            const fg = to_pixel(text_mode_data[(row * text_mode_width + cursor_col) * TEXT_BUF_COMPONENT_SIZE + FG_COLOR_INDEX]);
            const last = Math.min(cursor_end, font_height - 1);
            for(let y = cursor_start, p = row_start + cursor_start * width + cursor_col * font_width; y <= last; y++, p += width)
            {
                text_pixels.fill(fg, p, p + font_width);
            }
        }
    }

    /**
     * @return {number} rows drawn
     */
    function render_changed_rows()
    {
        if(!text_image || !font_bitmap || !backend)
        {
            return 0;
        }

        let n_rows_rendered = 0;
        for(let row = 0; row < text_mode_height; row++)
        {
            if(changed_rows[row])
            {
                render_row(row);
                const y = row * font_height;
                backend["put_pixels"](text_image.data, text_image.width, text_image.height,
                    0, y, text_image.width, font_height, 0, y);
                n_rows_rendered++;
            }
        }
        changed_rows.fill(0);

        return n_rows_rendered;
    }

    function mark_blinking_rows_dirty()
    {
        const txt_row_size = text_mode_width * TEXT_BUF_COMPONENT_SIZE;
        for(let row_i = 0, txt_i = 0; row_i < text_mode_height; ++row_i)
        {
            if(changed_rows[row_i])
            {
                txt_i += txt_row_size;
                continue;
            }
            for(let col_i = 0; col_i < text_mode_width; ++col_i, txt_i += TEXT_BUF_COMPONENT_SIZE)
            {
                if(text_mode_data[txt_i + FLAGS_INDEX] & FLAG_BLINKING)
                {
                    changed_rows[row_i] = 1;
                    txt_i += txt_row_size - col_i * TEXT_BUF_COMPONENT_SIZE;
                    break;
                }
            }
        }
    }

    this.init = function()
    {
        // initialize display mode and size to 80x25 text with 9x16 font
        this.set_mode(false);
        this.set_size_text(80, 25);
        resize_canvas(720, 400);

        // initialize CSS scaling
        this.set_scale(scale_x, scale_y);

        this.timer();
    };

    this.make_screenshot = function()
    {
        const image = new Image();
        image.src = backend ? backend["screenshot"]() : graphic_screen.toDataURL("image/png");
        return image;
    };

    /**
     * Draw through `new_backend` from now on (create_canvas2d_backend lists
     * its methods)
     * @param {!Object} new_backend
     */
    this.set_backend = function(new_backend)
    {
        backend = new_backend;
        backend["attach_presenter"]({ "invalidate": () => this.invalidate() });
        backend["resize"](graphic_screen.width, graphic_screen.height);
        this.invalidate();
    };

    /**
     * A canvas keeps the first kind of context it hands out (2D or WebGPU):
     * put a fresh copy of it where it was
     */
    const replace_canvas = () =>
    {
        const fresh = /** @type {!HTMLCanvasElement} */ (graphic_screen.cloneNode(false));
        if(graphic_screen.parentNode)
        {
            graphic_screen.parentNode.replaceChild(fresh, graphic_screen);
        }
        graphic_screen = fresh;
    };

    /**
     * The canvas, able to give out a context of `type` ("2d" or "webgpu").
     * If it already went to the other kind -- another emulator in this
     * container drew on it, or WebGPU took it and then failed to start -- it
     * is replaced by a fresh copy.
     * @param {string} type
     * @return {!HTMLCanvasElement}
     */
    this.claim_canvas = function(type)
    {
        if(type === "webgpu" && !(typeof navigator !== "undefined" && navigator["gpu"]))
        {
            return graphic_screen;
        }
        if(!graphic_screen.getContext(type, type === "2d" ? { alpha: false } : undefined))
        {
            replace_canvas();
        }
        return graphic_screen;
    };

    this.use_canvas2d = function()
    {
        this.set_backend(create_canvas2d_backend(this.claim_canvas("2d")));
    };

    /** Everything on the screen has to be drawn again */
    this.invalidate = function()
    {
        if(changed_rows)
        {
            changed_rows.fill(1);
        }
        full_frame_wanted = true;
    };

    this.put_char = function(row, col, chr, flags, bg_color, fg_color)
    {
        dbg_assert(row >= 0 && row < text_mode_height);
        dbg_assert(col >= 0 && col < text_mode_width);
        dbg_assert(chr >= 0 && chr < 0x100);

        const p = TEXT_BUF_COMPONENT_SIZE * (row * text_mode_width + col);

        text_mode_data[p + CHARACTER_INDEX] = chr;
        text_mode_data[p + FLAGS_INDEX] = flags;
        text_mode_data[p + BG_COLOR_INDEX] = bg_color;
        text_mode_data[p + FG_COLOR_INDEX] = fg_color;

        changed_rows[row] = 1;
    };

    this.timer = function()
    {
        timer_id = requestAnimationFrame(() => this.update_screen());
    };

    this.update_screen = function()
    {
        if(!paused)
        {
            if(mode === MODE_GRAPHICAL)
            {
                this.update_graphical();
            }
            else
            {
                this.update_graphical_text();
            }
            if(backend)
            {
                backend["present"]();
            }
        }
        this.timer();
    };

    this.update_graphical = function()
    {
        if(backend)
        {
            const full = full_frame_wanted;
            full_frame_wanted = false;
            this.screen_fill_buffer(full);
        }
    };

    this.update_graphical_text = function()
    {
        if(text_image)
        {
            // toggle cursor and blinking character visibility at a frequency of ~3.75hz
            const tm_now = performance.now();
            if(tm_now - tm_last_update > 266)
            {
                blink_visible = !blink_visible;
                if(cursor_enabled && cursor_row < text_mode_height)
                {
                    changed_rows[cursor_row] = 1;
                }
                mark_blinking_rows_dirty();
                tm_last_update = tm_now;
            }
            render_changed_rows();
        }
    };

    this.destroy = function()
    {
        this.on_geometry_change = null;
        if(timer_id)
        {
            cancelAnimationFrame(timer_id);
            timer_id = 0;
        }
    };

    this.pause = function()
    {
        paused = true;
    };

    this.continue = function()
    {
        paused = false;
    };

    /**
     * Invalidates text rendering state.  This means the next set of
     * calls to set_font_bitmap, set_size_text, etc will be working
     * from a fresh slate even if the dimensions of the loaded state
     * differ from the current dimensions.
     */
    this.clear_text_state = function() {
        font_width = null;
        font_height = null;
        text_mode_width = null;
        text_mode_height = null;
        font_page_a = null;
        font_page_b = null;
    };

    /**
     * Entering a graphics mode leaves the picture undefined until the device
     * sends the size and the pixels, which it always does next.
     */
    this.set_mode = function(graphical)
    {
        mode = graphical ? MODE_GRAPHICAL : MODE_GRAPHICAL_TEXT;

        if(mode === MODE_GRAPHICAL_TEXT)
        {
            // The canvas may still have the size of the graphics mode that just ended
            if(text_image)
            {
                resize_canvas(text_image.width, text_image.height);
            }
            if(changed_rows)
            {
                changed_rows.fill(1);
            }
        }
        notify_geometry();
    };

    this.set_font_bitmap = function(height, width_9px, width_dbl, copy_8th_col, vga_bitmap, vga_bitmap_changed)
    {
        const width = width_dbl ? 16 : (width_9px ? 9 : 8);
        if(font_height !== height || font_width !== width || font_width_9px !== width_9px ||
            font_width_dbl !== width_dbl || font_copy_8th_col !== copy_8th_col ||
            vga_bitmap_changed)
        {
            const size_changed = font_width !== width || font_height !== height;
            font_height = height;
            font_width = width;
            font_width_9px = width_9px;
            font_width_dbl = width_dbl;
            font_copy_8th_col = copy_8th_col;
            // plane 2 changes under us; the picture changes when the device says so
            font_bitmap = vga_bitmap.slice();
            changed_rows.fill(1);
            if(size_changed || !text_image)
            {
                this.set_size_graphical_text();
            }
        }
    };

    this.set_font_page = function(page_a, page_b)
    {
        if(font_page_a !== page_a || font_page_b !== page_b)
        {
            font_page_a = page_a;
            font_page_b = page_b;
            changed_rows.fill(1);
        }
    };

    this.clear_screen = function()
    {
        if(backend)
        {
            backend["clear"]();
        }
    };

    this.set_size_graphical_text = function()
    {
        if(!font_bitmap || !font_width || !text_mode_width)
        {
            return;
        }

        const gfx_width = font_width * text_mode_width;
        const gfx_height = font_height * text_mode_height;

        if(!text_image || text_image.width !== gfx_width || text_image.height !== gfx_height)
        {
            text_image = new ImageData(gfx_width, gfx_height);
            text_pixels = new Uint32Array(text_image.data.buffer);

            if(mode === MODE_GRAPHICAL_TEXT)
            {
                resize_canvas(gfx_width, gfx_height);
            }

            changed_rows.fill(1);
        }
    };

    /**
     * @param {number} cols
     * @param {number} rows
     */
    this.set_size_text = function(cols, rows)
    {
        if(cols === text_mode_width && rows === text_mode_height)
        {
            return;
        }

        changed_rows = new Int8Array(rows);
        changed_rows.fill(1);
        text_mode_data = new Int32Array(cols * rows * TEXT_BUF_COMPONENT_SIZE);

        text_mode_width = cols;
        text_mode_height = rows;

        this.set_size_graphical_text();
    };

    this.set_size_graphical = function(width, height, buffer_width, buffer_height)
    {
        if(DEBUG_SCREEN_LAYERS)
        {
            // Draw the entire buffer. Useful for debugging
            // panning / page flipping / screen splitting code for both
            // v86 developers and os developers
            width = buffer_width;
            height = buffer_height;
        }

        resize_canvas(width, height);
    };

    /**
     * @param {number} width
     * @param {number} height
     */
    function resize_canvas(width, height)
    {
        if(graphic_screen.width === width && graphic_screen.height === height && graphic_screen.style.display === "block")
        {
            return;
        }

        graphic_screen.style.display = "block";

        graphic_screen.width = width;
        graphic_screen.height = height;

        if(backend)
        {
            backend["resize"](width, height);
        }

        // add some scaling to tiny resolutions
        if(width <= 640 &&
            width * 2 < window.innerWidth * window.devicePixelRatio &&
            height * 2 < window.innerHeight * window.devicePixelRatio)
        {
            base_scale = 2;
        }
        else
        {
            base_scale = 1;
        }

        update_scale_graphic();
        notify_geometry();
    }

    this.set_scale = function(s_x, s_y)
    {
        scale_x = s_x;
        scale_y = s_y;

        update_scale_graphic();
        notify_geometry();
    };

    function update_scale_graphic()
    {
        let s_x = scale_x * base_scale;
        let s_y = scale_y * base_scale;
        if(!s_x || !s_y)
        {
            return;
        }

        graphic_screen.style.width = "";
        graphic_screen.style.height = "";

        const rectangle = graphic_screen.getBoundingClientRect();

        // unblur non-fractional scales
        if(s_x % 1 === 0 && s_y % 1 === 0)
        {
            graphic_screen.style["imageRendering"] = "crisp-edges"; // firefox
            graphic_screen.style["imageRendering"] = "pixelated";
            graphic_screen.style["-ms-interpolation-mode"] = "nearest-neighbor";
        }
        else
        {
            graphic_screen.style["imageRendering"] = "";
            graphic_screen.style["-ms-interpolation-mode"] = "";
        }

        // undo fractional css-to-device pixel ratios
        const device_pixel_ratio = window.devicePixelRatio || 1;
        if(device_pixel_ratio % 1 !== 0)
        {
            s_x /= device_pixel_ratio;
            s_y /= device_pixel_ratio;
        }

        if(s_x !== 1)
        {
            graphic_screen.style.width = rectangle.width * s_x + "px";
        }
        if(s_y !== 1)
        {
            graphic_screen.style.height = rectangle.height * s_y + "px";
        }
    }

    this.update_cursor_scanline = function(start, end, enabled)
    {
        if(start !== cursor_start || end !== cursor_end || enabled !== cursor_enabled)
        {
            if(cursor_row < text_mode_height)
            {
                changed_rows[cursor_row] = 1;
            }

            cursor_start = start;
            cursor_end = end;
            cursor_enabled = enabled;
        }
    };

    this.update_cursor = function(row, col)
    {
        if(row !== cursor_row || col !== cursor_col)
        {
            if(row < text_mode_height)
            {
                changed_rows[row] = 1;
            }
            if(cursor_row < text_mode_height)
            {
                changed_rows[cursor_row] = 1;
            }

            cursor_row = row;
            cursor_col = col;
        }
    };

    this.update_buffer = function(layers)
    {
        if(!backend)
        {
            return;
        }

        const debug_context = backend["context"];
        if(DEBUG_SCREEN_LAYERS && debug_context)
        {
            // For each visible layer that would've been drawn, draw a
            // rectangle to visualise the layer instead.
            debug_context.strokeStyle = "#0F0";
            debug_context.lineWidth = 4;
            for(const layer of layers)
            {
                debug_context.strokeRect(
                    layer.buffer_x,
                    layer.buffer_y,
                    layer.buffer_width,
                    layer.buffer_height
                );
            }
            debug_context.lineWidth = 1;
            return;
        }

        for(const layer of layers)
        {
            const pixels = layer.pixels;
            backend["put_pixels"](pixels.data, pixels.width, pixels.height,
                layer.buffer_x, layer.buffer_y, layer.buffer_width, layer.buffer_height,
                layer.screen_x, layer.screen_y);
        }
    };

    // XXX: duplicated in DummyScreenAdapter
    this.get_text_screen = function()
    {
        var screen = [];

        for(var i = 0; i < text_mode_height; i++)
        {
            screen.push(this.get_text_row(i));
        }

        return screen;
    };

    this.get_text_row = function(y)
    {
        if(!(y >= 0 && y < text_mode_height))
        {
            return "";
        }
        const begin = y * text_mode_width * TEXT_BUF_COMPONENT_SIZE + CHARACTER_INDEX;
        const end = begin + text_mode_width * TEXT_BUF_COMPONENT_SIZE;
        let row = "";
        for(let i = begin; i < end; i += TEXT_BUF_COMPONENT_SIZE)
        {
            row += charmap[text_mode_data[i]];
        }
        return row;
    };

    if(!options.deferred_backend)
    {
        this.use_canvas2d();
    }
    this.init();
}
                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/browser/serial.js                                                                    0000644 0000000 0000000 00000017442 00000000000 013763  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert, dbg_log } from "../log.js";

// For Types Only
import { BusConnector } from "../bus.js";

/**
 * @constructor
 *
 * @param {HTMLTextAreaElement} element
 */
function TextAreaAdapter(element)
{
    var serial = this;

    this.enabled = true;
    this.text = "";
    this.text_new_line = false;

    this.last_update = 0;

    this.destroy = function()
    {
        this.enabled = false;

        element.removeEventListener("keypress", keypress_handler, false);
        element.removeEventListener("keydown", keydown_handler, false);
        element.removeEventListener("paste", paste_handler, false);
        window.removeEventListener("mousedown", window_click_handler, false);
    };

    this.init = function()
    {
        this.destroy();
        this.enabled = true;

        element.style.display = "block";
        element.addEventListener("keypress", keypress_handler, false);
        element.addEventListener("keydown", keydown_handler, false);
        element.addEventListener("paste", paste_handler, false);
        window.addEventListener("mousedown", window_click_handler, false);
    };
    this.init();

    this.show_char = function(chr)
    {
        if(chr === "\x08")
        {
            this.text = this.text.slice(0, -1);
            this.update();
        }
        else if(chr === "\r")
        {
            // do nothing
        }
        else
        {
            this.text += chr;

            if(chr === "\n")
            {
                this.text_new_line = true;
            }

            this.update();
        }
    };

    this.update = function()
    {
        var now = Date.now();
        var delta = now - this.last_update;

        if(delta < 16)
        {
            if(this.update_timer === undefined)
            {
                this.update_timer = setTimeout(() => {
                    this.update_timer = undefined;
                    var now = Date.now();
                    dbg_assert(now - this.last_update >= 15);
                    this.last_update = now;
                    this.render();
                }, 16 - delta);
            }
        }
        else
        {
            if(this.update_timer !== undefined)
            {
                clearTimeout(this.update_timer);
                this.update_timer = undefined;
            }

            this.last_update = now;
            this.render();
        }
    };

    this.render = function()
    {
        element.value = this.text;

        if(this.text_new_line)
        {
            this.text_new_line = false;
            element.scrollTop = 1e9;
        }
    };

    /**
     * @param {number} chr_code
     */
    this.send_char = function(chr_code)
    {
        // placeholder
    };

    function may_handle(e)
    {
        if(!serial.enabled)
        {
            return false;
        }

        // Something here?

        return true;
    }

    function keypress_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var chr = e.which;

        serial.send_char(chr);
        e.preventDefault();
    }

    function keydown_handler(e)
    {
        var chr = e.which;

        if(chr === 8)
        {
            // supress backspace
            serial.send_char(127);
            e.preventDefault();
        }
        else if(chr === 9)
        {
            // tab
            serial.send_char(9);
            e.preventDefault();
        }
    }

    function paste_handler(e)
    {
        if(!may_handle(e))
        {
            return;
        }

        var data = e.clipboardData.getData("text/plain");

        for(var i = 0; i < data.length; i++)
        {
            serial.send_char(data.charCodeAt(i));
        }

        e.preventDefault();
    }

    function window_click_handler(e)
    {
        if(e.target !== element)
        {
            element.blur();
        }
    }
}

/**
 * @constructor
 *
 * @param {HTMLTextAreaElement} element
 * @param {BusConnector} bus
 */
export function SerialAdapter(element, bus)
{
    var adapter = Reflect.construct(TextAreaAdapter, [element], SerialAdapter);

    adapter.send_char = function(chr_code)
    {
        bus.send("serial0-input", chr_code);
    };

    bus.register("serial0-output-byte", function(byte)
    {
        var chr = String.fromCharCode(byte);
        adapter.show_char && adapter.show_char(chr);
    }, adapter);

    return adapter;
}

Reflect.setPrototypeOf(SerialAdapter.prototype, TextAreaAdapter.prototype);
Reflect.setPrototypeOf(SerialAdapter, TextAreaAdapter);

/**
 * @constructor
 *
 * @param {HTMLTextAreaElement} element
 * @param {BusConnector} bus
 */
export function VirtioConsoleAdapter(element, bus)
{
    var adapter = Reflect.construct(TextAreaAdapter, [element], VirtioConsoleAdapter);

    adapter.send_char = function(chr_code)
    {
        bus.send("virtio-console0-input-bytes", new Uint8Array([chr_code]));
    };

    const decoder = new TextDecoder();
    bus.register("virtio-console0-output-bytes", function(bytes)
    {
        for(const chr of decoder.decode(bytes))
        {
            adapter.show_char && adapter.show_char(chr);
        }
    }, adapter);

    return adapter;
}

Reflect.setPrototypeOf(VirtioConsoleAdapter.prototype, TextAreaAdapter.prototype);
Reflect.setPrototypeOf(VirtioConsoleAdapter, TextAreaAdapter);

/**
 * @constructor
 *
 * @param {BusConnector} bus
 */
function SerialRecordingAdapter(bus)
{
    var serial = this;
    this.text = "";

    bus.register("serial0-output-byte", function(byte)
    {
        var chr = String.fromCharCode(byte);
        this.text += chr;
    }, this);
}

/**
 * @constructor
 *
 * @param {HTMLElement} element
 * @param {Function} xterm_lib
 */
function XtermJSAdapter(element, xterm_lib)
{
    this.element = element;

    var term = this.term = new xterm_lib({
        "logLevel": "off",
        "convertEol": "true",
    });

    this.destroy = function() {
        this.on_data_disposable && this.on_data_disposable["dispose"]();
        term["dispose"]();
    };
}

XtermJSAdapter.prototype.show = function()
{
    this.term && this.term.open(this.element);
};

/**
 * @constructor
 *
 * @extends XtermJSAdapter
 * @param {HTMLElement} element
 * @param {BusConnector} bus
 * @param {Function} xterm_lib
 */
export function SerialAdapterXtermJS(element, bus, xterm_lib)
{
    if(!xterm_lib)
    {
        return;
    }

    var adapter = Reflect.construct(XtermJSAdapter, [element, xterm_lib], SerialAdapterXtermJS);

    bus.register("serial0-output-byte", function(utf8_byte)
    {
        adapter.term.write(Uint8Array.of(utf8_byte));
    }, adapter);

    const utf8_encoder = new TextEncoder();
    adapter.on_data_disposable = adapter.term["onData"](function(data_str) {
        for(const utf8_byte of utf8_encoder.encode(data_str))
        {
            bus.send("serial0-input", utf8_byte);
        }
    });

    return adapter;
}

Reflect.setPrototypeOf(SerialAdapterXtermJS.prototype, XtermJSAdapter.prototype);
Reflect.setPrototypeOf(SerialAdapterXtermJS, XtermJSAdapter);

/**
 * @constructor
 *
 * @extends XtermJSAdapter
 * @param {HTMLElement} element
 * @param {BusConnector} bus
 * @param {Function} xterm_lib
 */
export function VirtioConsoleAdapterXtermJS(element, bus, xterm_lib)
{
    if(!xterm_lib)
    {
        return;
    }

    var adapter = Reflect.construct(XtermJSAdapter, [element, xterm_lib], VirtioConsoleAdapterXtermJS);

    bus.register("virtio-console0-output-bytes", function(utf8_bytes)
    {
        adapter.term.write(utf8_bytes);
    }, adapter);

    const utf8_encoder = new TextEncoder();
    adapter.on_data_disposable = adapter.term["onData"](function(data_str) {
        bus.send("virtio-console0-input-bytes", utf8_encoder.encode(data_str));
    });

    return adapter;
}

Reflect.setPrototypeOf(VirtioConsoleAdapterXtermJS.prototype, XtermJSAdapter.prototype);
Reflect.setPrototypeOf(VirtioConsoleAdapterXtermJS, XtermJSAdapter);
                                                                                                                                                                                                                              source/v64/src/browser/speaker.js                                                                   0000644 0000000 0000000 00000107717 00000000000 014143  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import {
    MIXER_CHANNEL_BOTH, MIXER_CHANNEL_LEFT, MIXER_CHANNEL_RIGHT,
    MIXER_SRC_PCSPEAKER, MIXER_SRC_DAC, MIXER_SRC_MASTER,
} from "../const.js";
import { dbg_assert, dbg_log } from "../log.js";
import { OSCILLATOR_FREQ } from "../pit.js";
import { dump_file } from "../lib.js";

// For Types Only
import { BusConnector } from "../bus.js";

/* global registerProcessor, sampleRate */

const DAC_QUEUE_RESERVE = 0.2;

const AUDIOBUFFER_MINIMUM_SAMPLING_RATE = 8000;

/** the user gestures that may resume an AudioContext */
const UNLOCK_EVENTS = ["pointerdown", "keydown", "touchend"];

/**
 * @constructor
 * @param {!BusConnector} bus
 */
export function SpeakerAdapter(bus)
{
    if(typeof window === "undefined")
    {
        return;
    }
    if(!window.AudioContext && !window["webkitAudioContext"])
    {
        console.warn("Web browser doesn't support Web Audio API");
        return;
    }

    var SpeakerDAC = window.AudioWorklet ? SpeakerWorkletDAC : SpeakerBufferSourceDAC;

    /** @const */
    this.bus = bus;

    this.audio_context = window.AudioContext ? new AudioContext() : new webkitAudioContext();

    /** @const */
    this.mixer = new SpeakerMixer(bus, this.audio_context);

    /** @const */
    this.pcspeaker = new PCSpeaker(bus, this.audio_context, this.mixer);

    this.dac = new SpeakerDAC(bus, this.audio_context, this.mixer);

    this.pcspeaker.start();

    bus.register("emulator-stopped", function()
    {
        this.pause();
    }, this);

    bus.register("emulator-started", function()
    {
        this.dac.paused = false;
        this.audio_context.resume();
        this.dac.pump();
    }, this);

    bus.register("speaker-confirm-initialized", function()
    {
        bus.send("speaker-has-initialized");
    }, this);
    bus.send("speaker-has-initialized");

    // The browser's autoplay policy: a context made before the page had a
    // user gesture stays suspended, and resume() works only from one. The
    // first click, key or touch on the page while the emulator runs resumes
    // it (a page started from a button has its gesture already).
    /** @type {?function()} */
    this.unlock = () =>
    {
        if(!this.audio_context || this.audio_context.state !== "suspended" || this.dac.paused) return;
        this.audio_context.resume().then(() => this.audio_context && this.audio_context.state === "running" && this.remove_unlock());
    };
    if(typeof document !== "undefined")
    {
        for(const type of UNLOCK_EVENTS) document.addEventListener(type, this.unlock, true);
    }
}


SpeakerAdapter.prototype.remove_unlock = function()
{
    if(this.unlock && typeof document !== "undefined")
    {
        for(const type of UNLOCK_EVENTS) document.removeEventListener(type, this.unlock, true);
    }
    this.unlock = null;
};

SpeakerAdapter.prototype.pause = function()
{
    if(this.dac) this.dac.paused = true;
    return this.audio_context ? this.audio_context.suspend() : Promise.resolve();
};

SpeakerAdapter.prototype.destroy = function()
{
    this.remove_unlock();
    this.audio_context && this.audio_context.close();
    this.audio_context = null;
    this.dac && this.dac.node_processor && this.dac.node_processor.port.close();
    this.dac = null;
};

/**
 * @constructor
 * @param {!BusConnector} bus
 * @param {!AudioContext} audio_context
 */
function SpeakerMixer(bus, audio_context)
{
    /** @const */
    this.audio_context = audio_context;

    this.sources = new Map();

    // States

    this.volume_both = 1;
    this.volume_left = 1;
    this.volume_right = 1;
    this.gain_left = 1;
    this.gain_right = 1;

    // Nodes
    // TODO: Find / calibrate / verify the filter frequencies

    this.node_treble_left = this.audio_context.createBiquadFilter();
    this.node_treble_right = this.audio_context.createBiquadFilter();
    this.node_treble_left.type = "highshelf";
    this.node_treble_right.type = "highshelf";
    this.node_treble_left.frequency.setValueAtTime(2000, this.audio_context.currentTime);
    this.node_treble_right.frequency.setValueAtTime(2000, this.audio_context.currentTime);

    this.node_bass_left = this.audio_context.createBiquadFilter();
    this.node_bass_right = this.audio_context.createBiquadFilter();
    this.node_bass_left.type = "lowshelf";
    this.node_bass_right.type = "lowshelf";
    this.node_bass_left.frequency.setValueAtTime(200, this.audio_context.currentTime);
    this.node_bass_right.frequency.setValueAtTime(200, this.audio_context.currentTime);

    this.node_gain_left = this.audio_context.createGain();
    this.node_gain_right = this.audio_context.createGain();

    this.node_merger = this.audio_context.createChannelMerger(2);

    // Graph

    this.input_left = this.node_treble_left;
    this.input_right = this.node_treble_right;

    this.node_treble_left.connect(this.node_bass_left);
    this.node_bass_left.connect(this.node_gain_left);
    this.node_gain_left.connect(this.node_merger, 0, 0);

    this.node_treble_right.connect(this.node_bass_right);
    this.node_bass_right.connect(this.node_gain_right);
    this.node_gain_right.connect(this.node_merger, 0, 1);

    this.node_merger.connect(this.audio_context.destination);

    // Interface

    bus.register("mixer-connect", function(data)
    {
        var source_id = data[0];
        var channel = data[1];
        this.connect_source(source_id, channel);
    }, this);

    bus.register("mixer-disconnect", function(data)
    {
        var source_id = data[0];
        var channel = data[1];
        this.disconnect_source(source_id, channel);
    }, this);

    bus.register("mixer-volume", function(data)
    {
        var source_id = data[0];
        var channel = data[1];
        var decibels = data[2];

        var gain = Math.pow(10, decibels / 20);

        var source = source_id === MIXER_SRC_MASTER ? this : this.sources.get(source_id);

        if(source === undefined)
        {
            dbg_assert(false, "Mixer set volume - cannot set volume for undefined source: " + source_id);
            return;
        }

        source.set_volume(gain, channel);
    }, this);

    bus.register("mixer-gain-left", function(/** number */ decibels)
    {
        this.gain_left = Math.pow(10, decibels / 20);
        this.update();
    }, this);

    bus.register("mixer-gain-right", function(/** number */ decibels)
    {
        this.gain_right = Math.pow(10, decibels / 20);
        this.update();
    }, this);

    function create_gain_handler(audio_node)
    {
        return function(decibels)
        {
            audio_node.gain.setValueAtTime(decibels, this.audio_context.currentTime);
        };
    }
    bus.register("mixer-treble-left", create_gain_handler(this.node_treble_left), this);
    bus.register("mixer-treble-right", create_gain_handler(this.node_treble_right), this);
    bus.register("mixer-bass-left", create_gain_handler(this.node_bass_left), this);
    bus.register("mixer-bass-right", create_gain_handler(this.node_bass_right), this);
}

/**
 * @param {!AudioNode} source_node
 * @param {number} source_id
 * @return {SpeakerMixerSource}
 */
SpeakerMixer.prototype.add_source = function(source_node, source_id)
{
    var source = new SpeakerMixerSource(
        this.audio_context,
        source_node,
        this.input_left,
        this.input_right
    );

    dbg_assert(!this.sources.has(source_id), "Mixer add source - overwritting source: " + source_id);

    this.sources.set(source_id, source);
    return source;
};

/**
 * @param {number} source_id
 * @param {number=} channel
 */
SpeakerMixer.prototype.connect_source = function(source_id, channel)
{
    var source = this.sources.get(source_id);

    if(source === undefined)
    {
        dbg_assert(false, "Mixer connect - cannot connect undefined source: " + source_id);
        return;
    }

    source.connect(channel);
};

/**
 * @param {number} source_id
 * @param {number=} channel
 */
SpeakerMixer.prototype.disconnect_source = function(source_id, channel)
{
    var source = this.sources.get(source_id);

    if(source === undefined)
    {
        dbg_assert(false, "Mixer disconnect - cannot disconnect undefined source: " + source_id);
        return;
    }

    source.disconnect(channel);
};

/**
 * @param {number} value
 * @param {number=} channel
 */
SpeakerMixer.prototype.set_volume = function(value, channel)
{
    if(channel === undefined)
    {
        channel = MIXER_CHANNEL_BOTH;
    }

    switch(channel)
    {
        case MIXER_CHANNEL_LEFT:
            this.volume_left = value;
            break;
        case MIXER_CHANNEL_RIGHT:
            this.volume_right = value;
            break;
        case MIXER_CHANNEL_BOTH:
            this.volume_both = value;
            break;
        default:
            dbg_assert(false, "Mixer set master volume - unknown channel: " + channel);
            return;
    }

    this.update();
};

SpeakerMixer.prototype.update = function()
{
    var net_gain_left = this.volume_both * this.volume_left * this.gain_left;
    var net_gain_right = this.volume_both * this.volume_right * this.gain_right;

    this.node_gain_left.gain.setValueAtTime(net_gain_left, this.audio_context.currentTime);
    this.node_gain_right.gain.setValueAtTime(net_gain_right, this.audio_context.currentTime);
};

/**
 * @constructor
 * @param {!AudioContext} audio_context
 * @param {!AudioNode} source_node
 * @param {!AudioNode} destination_left
 * @param {!AudioNode} destination_right
 */
function SpeakerMixerSource(audio_context, source_node, destination_left, destination_right)
{
    /** @const */
    this.audio_context = audio_context;

    // States

    this.connected_left = true;
    this.connected_right = true;
    this.gain_hidden = 1;
    this.volume_both = 1;
    this.volume_left = 1;
    this.volume_right = 1;

    // Nodes

    this.node_splitter = audio_context.createChannelSplitter(2);
    this.node_gain_left = audio_context.createGain();
    this.node_gain_right = audio_context.createGain();

    // Graph

    source_node.connect(this.node_splitter);

    this.node_splitter.connect(this.node_gain_left, 0);
    this.node_gain_left.connect(destination_left);

    this.node_splitter.connect(this.node_gain_right, 1);
    this.node_gain_right.connect(destination_right);
}

SpeakerMixerSource.prototype.update = function()
{
    var net_gain_left = this.connected_left * this.gain_hidden * this.volume_both * this.volume_left;
    var net_gain_right = this.connected_right * this.gain_hidden * this.volume_both * this.volume_right;

    this.node_gain_left.gain.setValueAtTime(net_gain_left, this.audio_context.currentTime);
    this.node_gain_right.gain.setValueAtTime(net_gain_right, this.audio_context.currentTime);
};

/** @param {number=} channel */
SpeakerMixerSource.prototype.connect = function(channel)
{
    var both = !channel || channel === MIXER_CHANNEL_BOTH;
    if(both || channel === MIXER_CHANNEL_LEFT)
    {
        this.connected_left = true;
    }
    if(both || channel === MIXER_CHANNEL_RIGHT)
    {
        this.connected_right = true;
    }
    this.update();
};

/** @param {number=} channel */
SpeakerMixerSource.prototype.disconnect = function(channel)
{
    var both = !channel || channel === MIXER_CHANNEL_BOTH;
    if(both || channel === MIXER_CHANNEL_LEFT)
    {
        this.connected_left = false;
    }
    if(both || channel === MIXER_CHANNEL_RIGHT)
    {
        this.connected_right = false;
    }
    this.update();
};

/**
 * @param {number} value
 * @param {number=} channel
 */
SpeakerMixerSource.prototype.set_volume = function(value, channel)
{
    if(channel === undefined)
    {
        channel = MIXER_CHANNEL_BOTH;
    }

    switch(channel)
    {
        case MIXER_CHANNEL_LEFT:
            this.volume_left = value;
            break;
        case MIXER_CHANNEL_RIGHT:
            this.volume_right = value;
            break;
        case MIXER_CHANNEL_BOTH:
            this.volume_both = value;
            break;
        default:
            dbg_assert(false, "Mixer set volume - unknown channel: " + channel);
            return;
    }

    this.update();
};

SpeakerMixerSource.prototype.set_gain_hidden = function(value)
{
    this.gain_hidden = value;
};

/**
 * @constructor
 * @param {!BusConnector} bus
 * @param {!AudioContext} audio_context
 * @param {!SpeakerMixer} mixer
 */
function PCSpeaker(bus, audio_context, mixer)
{
    // Nodes

    this.node_oscillator = audio_context.createOscillator();
    this.node_oscillator.type = "square";
    this.node_oscillator.frequency.setValueAtTime(440, audio_context.currentTime);

    // Interface

    this.mixer_connection = mixer.add_source(this.node_oscillator, MIXER_SRC_PCSPEAKER);
    this.mixer_connection.disconnect();

    bus.register("pcspeaker-enable", function()
    {
        mixer.connect_source(MIXER_SRC_PCSPEAKER);
    }, this);

    bus.register("pcspeaker-disable", function()
    {
        mixer.disconnect_source(MIXER_SRC_PCSPEAKER);
    }, this);

    bus.register("pcspeaker-update", function(data)
    {
        var counter_mode = data[0];
        var counter_reload = data[1];

        var frequency = 0;
        var beep_enabled = counter_mode === 3;

        if(beep_enabled)
        {
            frequency = OSCILLATOR_FREQ * 1000 / counter_reload;
            frequency = Math.min(frequency, this.node_oscillator.frequency.maxValue);
            frequency = Math.max(frequency, 0);
        }

        this.node_oscillator.frequency.setValueAtTime(frequency, audio_context.currentTime);
    }, this);
}

PCSpeaker.prototype.start = function()
{
    this.node_oscillator.start();
};

/**
 * @constructor
 * @param {!BusConnector} bus
 * @param {!AudioContext} audio_context
 * @param {!SpeakerMixer} mixer
 */
function SpeakerWorkletDAC(bus, audio_context, mixer)
{
    /** @const */
    this.bus = bus;

    /** @const */
    this.audio_context = audio_context;

    // State

    this.enabled = false;
    this.sampling_rate = 48000;
    this.paused = true;
    this.generation = 0;

    // Worklet

    function worklet()
    {
        const RENDER_QUANTUM = 128;
        const MINIMUM_BUFFER_SIZE = 2 * RENDER_QUANTUM;
        const QUEUE_RESERVE = 1024;

        function sinc(x)
        {
            if(x === 0) return 1;
            x *= Math.PI;
            return Math.sin(x) / x;
        }

        var EMPTY_BUFFER =
        [
            new Float32Array(MINIMUM_BUFFER_SIZE),
            new Float32Array(MINIMUM_BUFFER_SIZE),
        ];

        /**
         * @constructor
         * @extends AudioWorkletProcessor
         */
        function DACProcessor()
        {
            var self = Reflect.construct(AudioWorkletProcessor, [], DACProcessor);

            // Params

            self.kernel_size = 3;

            // States

            // Buffers waiting for their turn to be consumed
            self.queue_data = new Array(1024);
            self.queue_start = 0;
            self.queue_end = 0;
            self.queue_length = 0;
            self.queue_size = self.queue_data.length;
            self.queued_samples = 0;

            // Buffers being actively consumed
            /** @type{Array<Float32Array>} */
            self.source_buffer_previous = EMPTY_BUFFER;
            /** @type{Array<Float32Array>} */
            self.source_buffer_current = EMPTY_BUFFER;

            // Ratio of alienland sample rate to homeland sample rate.
            self.source_samples_per_destination = 1.0;

            // Integer representing the position of the first destination sample
            // for the current block, relative to source_buffer_current.
            self.source_block_start = 0;

            // Real number representing the position of the current destination
            // sample relative to source_buffer_current, since source_block_start.
            self.source_time = 0.0;

            // Same as source_time but rounded down to an index.
            self.source_offset = 0;
            self.generation = 0;

            // Interface

            self.cpu_audio_port = null;
            self.cpu_audio_epoch = 0;
            self.cpu_audio_enabled = false;
            const receive = (event) =>
            {
                if(event.data["cpu_port"])
                {
                    if(self.cpu_audio_port) self.cpu_audio_port.close();
                    self.cpu_audio_port = event.data["cpu_port"];
                    self.cpu_audio_port.onmessage = e => {
                        const m = e.data, type = m["cpu_audio"];
                        if(type === "reset")
                        {
                            self.cpu_audio_epoch = m["epoch"];
                            receive({ data: { type: "reset", value: self.generation + 1 } });
                            self.cpu_audio_port.postMessage({ "cpu_audio": "reset-done", "epoch": self.cpu_audio_epoch, "sequence": m["sequence"] });
                        }
                        else if(m["epoch"] === self.cpu_audio_epoch)
                        {
                            if(type === "queue") self.queue_push(m["value"]);
                            if(type === "rate") self.source_samples_per_destination = m["value"] / sampleRate;
                            if(type === "enabled") self.cpu_audio_enabled = m["value"];
                        }
                    };
                    return;
                }
                switch(event.data.type)
                {
                    case "reset":
                        self.queue_data.fill(null);
                        self.queue_start = self.queue_end = self.queue_length = self.queued_samples = 0;
                        self.source_buffer_previous = self.source_buffer_current = EMPTY_BUFFER;
                        self.source_block_start = self.source_time = self.source_offset = 0;
                        self.generation = event.data.value;
                        break;
                    case "queue":
                        self.queue_push(event.data.value);
                        break;
                    case "sampling-rate":
                        self.source_samples_per_destination = event.data.value / sampleRate;
                        break;
                }
            };

            self.port.onmessage = receive;

            return self;
        }

        Reflect.setPrototypeOf(DACProcessor.prototype, AudioWorkletProcessor.prototype);
        Reflect.setPrototypeOf(DACProcessor, AudioWorkletProcessor);

        DACProcessor.prototype["process"] =
        DACProcessor.prototype.process = function(inputs, outputs, parameters)
        {
            for(var i = 0; i < outputs[0][0].length; i++)
            {
                // Lanczos resampling
                var sum0 = 0;
                var sum1 = 0;

                var start = this.source_offset - this.kernel_size + 1;
                var end = this.source_offset + this.kernel_size;

                for(var j = start; j <= end; j++)
                {
                    var convolute_index = this.source_block_start + j;
                    sum0 += this.get_sample(convolute_index, 0) * this.kernel(this.source_time - j);
                    sum1 += this.get_sample(convolute_index, 1) * this.kernel(this.source_time - j);
                }

                if(isNaN(sum0) || isNaN(sum1))
                {
                    // NaN values cause entire audio graph to cease functioning.
                    sum0 = sum1 = 0;
                    this.dbg_log("ERROR: NaN values! Ignoring for now.");
                }

                outputs[0][0][i] = sum0;
                outputs[0][1][i] = sum1;

                this.source_time += this.source_samples_per_destination;
                this.source_offset = Math.floor(this.source_time);
            }

            // +2 to safeguard against rounding variations
            var samples_needed_per_block = this.source_offset;
            samples_needed_per_block += this.kernel_size + 2;

            this.source_time -= this.source_offset;
            this.source_block_start += this.source_offset;
            this.source_offset = 0;

            // Note: This needs to be done after source_block_start is updated.
            this.ensure_enough_data(samples_needed_per_block);

            return true;
        };

        DACProcessor.prototype.kernel = function(x)
        {
            return sinc(x) * sinc(x / this.kernel_size);
        };

        DACProcessor.prototype.get_sample = function(index, channel)
        {
            if(index < 0)
            {
                // -ve index represents previous buffer
                //          <-------|
                // [Previous buffer][Current buffer]
                index += this.source_buffer_previous[0].length;
                return this.source_buffer_previous[channel][index];
            }
            else
            {
                return this.source_buffer_current[channel][index];
            }
        };

        DACProcessor.prototype.ensure_enough_data = function(needed)
        {
            var current_length = this.source_buffer_current[0].length;
            var remaining = current_length - this.source_block_start;

            if(remaining < needed)
            {
                this.prepare_next_buffer();
                this.source_block_start -= current_length;
            }
        };

        DACProcessor.prototype.prepare_next_buffer = function()
        {
            if(this.queued_samples < MINIMUM_BUFFER_SIZE && this.queue_length)
            {
                this.dbg_log("Not enough samples - should not happen during midway of playback");
            }

            this.source_buffer_previous = this.source_buffer_current;
            this.source_buffer_current = this.queue_shift();

            var sample_count = this.source_buffer_current[0].length;

            if(sample_count < MINIMUM_BUFFER_SIZE)
            {
                // Unfortunately, this single buffer is too small :(

                var queue_pos = this.queue_start;
                var buffer_count = 0;

                // Figure out how many small buffers to combine.
                while(sample_count < MINIMUM_BUFFER_SIZE && buffer_count < this.queue_length)
                {
                    sample_count += this.queue_data[queue_pos][0].length;

                    queue_pos = queue_pos + 1 & this.queue_size - 1;
                    buffer_count++;
                }

                // Note: if not enough buffers, this will be end-padded with zeros:
                var new_big_buffer_size = Math.max(sample_count, MINIMUM_BUFFER_SIZE);
                var new_big_buffer =
                [
                    new Float32Array(new_big_buffer_size),
                    new Float32Array(new_big_buffer_size),
                ];

                // Copy the first, already-shifted, small buffer into the new buffer.
                new_big_buffer[0].set(this.source_buffer_current[0]);
                new_big_buffer[1].set(this.source_buffer_current[1]);
                var new_big_buffer_pos = this.source_buffer_current[0].length;

                // Copy the rest.
                for(var i = 0; i < buffer_count; i++)
                {
                    var small_buffer = this.queue_shift();
                    new_big_buffer[0].set(small_buffer[0], new_big_buffer_pos);
                    new_big_buffer[1].set(small_buffer[1], new_big_buffer_pos);
                    new_big_buffer_pos += small_buffer[0].length;
                }

                // Pretend that everything's just fine.
                this.source_buffer_current = new_big_buffer;
            }

            this.pump();
        };

        DACProcessor.prototype.pump = function()
        {
            if(this.queued_samples / this.source_samples_per_destination < QUEUE_RESERVE)
            {
                if(this.cpu_audio_port)
                {
                    if(this.cpu_audio_enabled) this.cpu_audio_port.postMessage({ "cpu_audio": "pump", "epoch": this.cpu_audio_epoch });
                }
                else this.port.postMessage(
                {
                    type: "pump",
                    generation: this.generation,
                });
            }
        };

        DACProcessor.prototype.queue_push = function(item)
        {
            if(this.queue_length < this.queue_size)
            {
                this.queue_data[this.queue_end] = item;
                this.queue_end = this.queue_end + 1 & this.queue_size - 1;
                this.queue_length++;

                this.queued_samples += item[0].length;

                this.pump();
            }
        };

        DACProcessor.prototype.queue_shift = function()
        {
            if(!this.queue_length)
            {
                return EMPTY_BUFFER;
            }

            var item = this.queue_data[this.queue_start];

            this.queue_data[this.queue_start] = null;
            this.queue_start = this.queue_start + 1 & this.queue_size - 1;
            this.queue_length--;

            this.queued_samples -= item[0].length;

            return item;
        };

        DACProcessor.prototype.dbg_log = function(message)
        {
            if(DEBUG)
            {
                this.port.postMessage(
                {
                    type: "debug-log",
                    value: message,
                });
            }
        };

        registerProcessor("dac-processor", DACProcessor);
    }

    var worklet_string = worklet.toString();

    var worklet_code_start = worklet_string.indexOf("{") + 1;
    var worklet_code_end = worklet_string.lastIndexOf("}");
    var worklet_code = worklet_string.substring(worklet_code_start, worklet_code_end);

    if(DEBUG)
    {
        worklet_code = "var DEBUG = true;\n" + worklet_code;
    }

    var worklet_blob = new Blob([worklet_code], { type: "application/javascript" });
    var worklet_url = URL.createObjectURL(worklet_blob);

    /** @type {AudioWorkletNode} */
    this.node_processor = null;

    // Placeholder pass-through node to connect to, when worklet node is not ready yet.
    this.node_output = this.audio_context.createGain();

    this.ready = this.audio_context
        .audioWorklet
        .addModule(worklet_url)
        .then(() =>
    {
        URL.revokeObjectURL(worklet_url);

        this.node_processor = new AudioWorkletNode(this.audio_context, "dac-processor",
        {
            numberOfInputs: 0,
            numberOfOutputs: 1,
            outputChannelCount: [2],
            parameterData: {},
            processorOptions: {},
        });

        this.node_processor.port.postMessage(
        {
            type: "reset",
            value: this.generation,
        });
        this.node_processor.port.postMessage(
        {
            type: "sampling-rate",
            value: this.sampling_rate,
        });

        this.node_processor.port.onmessage = (event) =>
        {
            switch(event.data.type)
            {
                case "pump":
                    if(event.data.generation === this.generation) this.pump();
                    break;
                case "debug-log":
                    dbg_log("SpeakerWorkletDAC - Worklet: " + event.data.value);
                    break;
            }
        };

        // Graph

        this.node_processor.connect(this.node_output);
    });

    // Interface

    this.mixer_connection = mixer.add_source(this.node_output, MIXER_SRC_DAC);
    this.mixer_connection.set_gain_hidden(3);

    bus.register("dac-reset", this.reset, this);

    bus.register("dac-send-data", function(data)
    {
        this.queue(data);
    }, this);

    bus.register("dac-enable", function(enabled)
    {
        this.enabled = true;
    }, this);

    bus.register("dac-disable", function()
    {
        this.enabled = false;
    }, this);

    bus.register("dac-tell-sampling-rate", function(/** number */ rate)
    {
        dbg_assert(rate > 0, "Sampling rate should be nonzero");
        this.sampling_rate = rate;

        if(!this.node_processor)
        {
            return;
        }

        this.node_processor.port.postMessage(
        {
            type: "sampling-rate",
            value: rate,
        });
    }, this);

    if(DEBUG)
    {
        this.debugger = new SpeakerDACDebugger(this.audio_context, this.node_output);
    }
}

// The CPU worker and AudioWorklet exchange PCM without main-thread scheduling.
SpeakerWorkletDAC.prototype.connect_cpu_worker = async function()
{
    await this.ready;
    const channel = new globalThis.MessageChannel();
    this.node_processor.port.postMessage({ "cpu_port": channel.port1 }, [channel.port1]);
    return channel.port2;
};

SpeakerWorkletDAC.prototype.queue = function(data)
{
    if(!this.node_processor)
    {
        return;
    }

    if(DEBUG)
    {
        this.debugger.push_queued_data(data);
    }

    this.node_processor.port.postMessage(
    {
        type: "queue",
        value: data,
    }, [data[0].buffer, data[1].buffer]);
};

SpeakerWorkletDAC.prototype.pump = function()
{
    if(!this.enabled || this.paused)
    {
        return;
    }
    this.bus.send("dac-request-data");
};

SpeakerWorkletDAC.prototype.reset = function()
{
    ++this.generation;
    if(this.node_processor) this.node_processor.port.postMessage({ type: "reset", value: this.generation });
};

/**
 * @constructor
 * @param {!BusConnector} bus
 * @param {!AudioContext} audio_context
 * @param {!SpeakerMixer} mixer
 */
function SpeakerBufferSourceDAC(bus, audio_context, mixer)
{
    /** @const */
    this.bus = bus;

    /** @const */
    this.audio_context = audio_context;

    // States

    this.enabled = false;
    this.sampling_rate = 22050;
    this.buffered_time = 0;
    this.rate_ratio = 1;
    this.paused = true;
    this.generation = 0;
    this.sources = new Set();

    // Nodes

    this.node_lowpass = this.audio_context.createBiquadFilter();
    this.node_lowpass.type = "lowpass";

    // Interface

    this.node_output = this.node_lowpass;

    this.mixer_connection = mixer.add_source(this.node_output, MIXER_SRC_DAC);
    this.mixer_connection.set_gain_hidden(3);

    bus.register("dac-reset", this.reset, this);

    bus.register("dac-send-data", function(data)
    {
        this.queue(data);
    }, this);

    bus.register("dac-enable", function(enabled)
    {
        this.enabled = true;
        this.pump();
    }, this);

    bus.register("dac-disable", function()
    {
        this.enabled = false;
    }, this);

    bus.register("dac-tell-sampling-rate", function(/** number */ rate)
    {
        dbg_assert(rate > 0, "Sampling rate should be nonzero");
        this.sampling_rate = rate;
        this.rate_ratio = Math.ceil(AUDIOBUFFER_MINIMUM_SAMPLING_RATE / rate);
        this.node_lowpass.frequency.setValueAtTime(rate / 2, this.audio_context.currentTime);
    }, this);

    if(DEBUG)
    {
        this.debugger = new SpeakerDACDebugger(this.audio_context, this.node_output);
    }
}

SpeakerBufferSourceDAC.prototype.queue = function(data)
{
    if(DEBUG)
    {
        this.debugger.push_queued_data(data);
    }

    var sample_count = data[0].length;
    var block_duration = sample_count / this.sampling_rate;

    var buffer;
    if(this.rate_ratio > 1)
    {
        var new_sample_count = sample_count * this.rate_ratio;
        var new_sampling_rate = this.sampling_rate * this.rate_ratio;
        buffer = this.audio_context.createBuffer(2, new_sample_count, new_sampling_rate);
        var buffer_data0 = buffer.getChannelData(0);
        var buffer_data1 = buffer.getChannelData(1);

        var buffer_index = 0;
        for(var i = 0; i < sample_count; i++)
        {
            for(var j = 0; j < this.rate_ratio; j++, buffer_index++)
            {
                buffer_data0[buffer_index] = data[0][i];
                buffer_data1[buffer_index] = data[1][i];
            }
        }
    }
    else
    {
        // Allocating new AudioBuffer every block
        // - Memory profiles show insignificant improvements if recycling old buffers.
        buffer = this.audio_context.createBuffer(2, sample_count, this.sampling_rate);
        if(buffer.copyToChannel)
        {
            buffer.copyToChannel(data[0], 0);
            buffer.copyToChannel(data[1], 1);
        }
        else
        {
            // Safari doesn't support copyToChannel yet. See #286
            buffer.getChannelData(0).set(data[0]);
            buffer.getChannelData(1).set(data[1]);
        }
    }

    var source = this.audio_context.createBufferSource();
    source.buffer = buffer;
    source.connect(this.node_lowpass);
    const generation = this.generation;
    const pump = () => { if(this.generation === generation) this.pump(); };
    this.sources.add(source);
    source.addEventListener("ended", () => {
        this.sources.delete(source);
        source.disconnect();
        pump();
    });

    var current_time = this.audio_context.currentTime;

    if(this.buffered_time < current_time)
    {
        dbg_log("Speaker DAC - Creating/Recreating reserve - shouldn't occur frequently during playback");

        // Schedule pump() to queue evenly, starting from current time
        this.buffered_time = current_time;
        var target_silence_duration = DAC_QUEUE_RESERVE - block_duration;
        var current_silence_duration = 0;
        while(current_silence_duration <= target_silence_duration)
        {
            current_silence_duration += block_duration;
            this.buffered_time += block_duration;
            setTimeout(pump, current_silence_duration * 1000);
        }
    }

    source.start(this.buffered_time);
    this.buffered_time += block_duration;

    // Chase the schedule - ensure reserve is full
    setTimeout(pump, 0);
};

SpeakerBufferSourceDAC.prototype.pump = function()
{
    if(!this.enabled || this.paused)
    {
        return;
    }
    if(this.buffered_time - this.audio_context.currentTime > DAC_QUEUE_RESERVE)
    {
        return;
    }
    this.bus.send("dac-request-data");
};

SpeakerBufferSourceDAC.prototype.reset = function()
{
    ++this.generation;
    for(const source of this.sources)
    {
        source.stop();
        source.disconnect();
    }
    this.sources.clear();
    this.buffered_time = 0;
};

/**
 * @constructor
 */
function SpeakerDACDebugger(audio_context, source_node)
{
    /** @const */
    this.audio_context = audio_context;

    /** @const */
    this.node_source = source_node;

    this.node_processor = null;

    this.node_gain = this.audio_context.createGain();
    this.node_gain.gain.setValueAtTime(0, this.audio_context.currentTime);

    this.node_gain.connect(this.audio_context.destination);

    this.is_active = false;
    this.queued_history = [];
    this.output_history = [];
    this.queued = [[], []];
    this.output = [[], []];
}

/** @suppress {deprecated} */
SpeakerDACDebugger.prototype.start = function(duration_ms)
{
    this.is_active = true;
    this.queued = [[], []];
    this.output = [[], []];
    this.queued_history.push(this.queued);
    this.output_history.push(this.output);

    this.node_processor = this.audio_context.createScriptProcessor(1024, 2, 2);
    this.node_processor.onaudioprocess = (event) =>
    {
        this.output[0].push(event.inputBuffer.getChannelData(0).slice());
        this.output[1].push(event.inputBuffer.getChannelData(1).slice());
    };

    this.node_source.connect(this.node_processor);
    this.node_processor.connect(this.node_gain);

    setTimeout(() =>
    {
        this.stop();
    }, duration_ms);
};

SpeakerDACDebugger.prototype.stop = function()
{
    this.is_active = false;
    this.node_source.disconnect(this.node_processor);
    this.node_processor.disconnect();
    this.node_processor = null;
};

SpeakerDACDebugger.prototype.push_queued_data = function(data)
{
    if(this.is_active)
    {
        this.queued[0].push(data[0].slice());
        this.queued[1].push(data[1].slice());
    }
};

// Useful for Audacity imports
SpeakerDACDebugger.prototype.download_txt = function(history_id, channel)
{
    var txt = this.output_history[history_id][channel]
        .map((v) => v.join(" "))
        .join(" ");

    dump_file(txt, "dacdata.txt");
};

// Useful for general plotting
SpeakerDACDebugger.prototype.download_csv = function(history_id)
{
    var buffers = this.output_history[history_id];
    var csv_rows = [];
    for(var buffer_id = 0; buffer_id < buffers[0].length; buffer_id++)
    {
        for(var i = 0; i < buffers[0][buffer_id].length; i++)
        {
            csv_rows.push(`${buffers[0][buffer_id][i]},${buffers[1][buffer_id][i]}`);
        }
    }
    dump_file(csv_rows.join("\n"), "dacdata.csv");
};
                                                 source/v64/src/browser/starter.js                                                                   0000644 0000000 0000000 00000401015 00000000000 014161  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { wasm_fallback_path } from "./wasm_paths.js";
import { instantiate_v86, memory_import } from "../parallel/relocate.js";
import { default_worker_url, parallel_unsupported_reason } from "../parallel/machine.js";
import { CPUWorkerController, encode_worker_file } from "./cpu_worker.js";
import * as iso9660 from "../iso9660.js";
import { get_jit_switches } from "../jit_switches.js";
import { v86 } from "../main.js";
import { LOG_CPU, LOG_VGA, WASM_TABLE_OFFSET, WASM_TABLE_SIZE } from "../const.js";
import { get_rand_int, load_file, read_sized_string_from_mem } from "../lib.js";
import { dbg_assert, dbg_trace, dbg_log, set_log_level } from "../log.js";
import * as print_stats from "./print_stats.js";
import { Bus } from "../bus.js";
import { BOOT_ORDER_FD_FIRST, BOOT_ORDER_HD_FIRST, BOOT_ORDER_CD_FIRST } from "../rtc.js";
import { EEXIST, ENOENT } from "../../lib/9p.js";
import { check_graphics_adapter_options, load_graphics_adapter } from "../graphics_adapter.js";
import { AUDIO_PLUGINS, GLES_PLUGINS, NET_PLUGINS, TPM_PLUGINS, USB_PLUGINS, default_glslang_wasm_path, default_tpm_wasm_path,
    load_device_plugin } from "../device_plugin.js";
import { check_machine_options, is_arm, AUDIO_DEVICE_PLUGINS, NET_DEVICE_PLUGINS } from "../machine_options.js";

import { SpeakerAdapter } from "./speaker.js";
import { NetworkAdapter } from "./network.js";
import { FetchNetworkAdapter } from "./fetch_network.js";
import { WispNetworkAdapter } from "./wisp_network.js";
import { KeyboardAdapter } from "./keyboard.js";
import { MouseAdapter } from "./mouse.js";
import { ScreenAdapter } from "./screen.js";
import { DummyScreenAdapter } from "./dummy_screen.js";
import { ANSIScreenAdapter } from "./ansi_screen.js";
import { SerialAdapter, VirtioConsoleAdapter, SerialAdapterXtermJS, VirtioConsoleAdapterXtermJS } from "./serial.js";
import { InBrowserNetworkAdapter } from "./inbrowser_network.js";
import { Modem } from "./modem.js";

import { MemoryFileStorage, ServerFileStorageWrapper } from "./filestorage.js";
import { SyncBuffer, buffer_from_object } from "../buffer.js";
import { check_image_options, create_disk_image, import_ova, set_buffer_sector_size } from "../image/factory.js";
import { check_disk_options, check_disk_policy, check_disk_bindings, set_disk_policy, disk_kind, is_service_url } from "../disk_options.js";
import { NodeFileDisk, check_loaded_disks, disk_buffers } from "../disk_writeback.js";
import { floppy_format_size } from "../floppy.js";
import { DiskServiceDisk } from "../disk_service.js";
import { OpfsDisk, is_opfs_url, opfs_file } from "../opfs_disk.js";
// (for types only)
import { PCIeRootPort } from "../pcie_root_port.js";
import { android_bootloader, ANDROID_DEVICES } from "../android/bootloader.js";
import { DEFAULT_GLES_VERSION, GLES_VERSIONS, ranchu_gpu_mode } from "../android/devices.js";
import { PartitionBuffer } from "../android/partition_buffer.js";
import { FS } from "../../lib/filesystem.js";

/**
 * A whole file of a URL (load_file), or why it could not be loaded: an
 * answer of 4xx fails at once (a missing image must not hang the start or
 * become a disk; 5xx answers and network errors are tried again)
 * @param {string} name the option it is for (fda, cdrom, ...)
 * @param {string} url
 * @param {Object=} options more of load_file's options (progress, as_json)
 * @return {!Promise<*>}
 */
function load_whole_file(name, url, options)
{
    return new Promise((resolve, reject) => load_file(url, Object.assign({}, options, {
        done: resolve,
        error: status => reject(new Error(name + ": " + url + " could not be loaded (" +
            (typeof status === "number" ? "HTTP " + status : status) + ")")),
    })));
}

/**
 * graphics_adapter selects the display hardware the guest sees (a plugin,
 * src/graphics_adapter.js); graphics_proxy adds the D3D/DDraw/GL proxy of
 * libv86-webgpu.js, which the page loads first, as xterm.js for a serial
 * terminal (docs/glbridge.md)
 * @return {Object} the proxy's device plugin, or null
 */
function create_graphics_proxy(options)
{
    if(options["v86gl_pci"] !== undefined)
    {
        throw new Error("v86gl_pci was removed; use graphics_proxy: true");
    }
    if(options["graphics_options"] !== undefined)
    {
        throw new Error("graphics_options was removed; pass them as graphics_proxy: { ... }");
    }
    const proxy = options["graphics_proxy"];
    if(!proxy) return null;
    const factory = globalThis["V86GraphicsProxy"];
    if(typeof factory !== "function")
    {
        throw new Error("graphics_proxy requires libv86-webgpu.js to be loaded before new V86()");
    }
    return factory(proxy === true ? {} : proxy);
}

/** The name of the channel between the display adapter's device and its renderer, with a CPU worker */
export const ADAPTER_RENDERER_CHANNEL = "graphics_adapter_renderer";

/**
 * The 3D renderer of the display adapter, on this page: GX (V86SVGARenderer
 * of libv86-webgpu.js), for vmware_svga and virtio_gpu (virgl), when the
 * page has loaded it and WebGPU has an adapter. The device then declares 3D.
 *
 * With a CPU worker the device is in the worker and the renderer stays here:
 * `host` is this page's end of their channel (CPUWorkerController's
 * device_channel), and the worker gives the device the other end. In the
 * worker, `options` brings that end (graphics_adapter_renderer_channel).
 * @param {Object=} options
 * @param {Object=} host
 * @return {!Promise<Object>} the device's end of the channel (`host`
 *     itself if it was given), or null
 */
V86.prototype.create_adapter_renderer = async function(options, host)
{
    const remote = options && options["graphics_adapter_renderer_channel"];
    if(remote) return remote;
    const create = globalThis["V86SVGARenderer"];
    const gpu = typeof navigator !== "undefined" && navigator["gpu"];
    if(this.graphics_adapter !== "vmware_svga" && this.graphics_adapter !== "virtio_gpu" && !this.gles_host || typeof create !== "function" || !gpu) return null;
    let adapter = null;
    try
    {
        adapter = await gpu["requestAdapter"]();
    }
    catch(e)
    {
        dbg_log("WebGPU: " + e, LOG_VGA);
    }
    if(!adapter || this.destroyed) return null;
    // (with the graphics proxy's compositor on this page: a layer of it, the
    // renderer on its device showing scanouts there without readbacks,
    // docs/gfxstream-plan.md G4; its plugin objects' names are quoted)
    let compositor = this.device_plugins.map(plugin => plugin["bridge"] && plugin["bridge"]["compositor"]).find(Boolean);
    // (the ranchu machine's GLES host without the graphics proxy: a
    // compositor of its own takes over the screen canvas, as the proxy's
    // does, so that a posted frame is a layer over the screen and is not read
    // back, docs/gles-proxy-plan.md E5; the 2D canvas again if it cannot start)
    if(!compositor && this.gles_host) compositor = await this.gles_screen_compositor();
    const layer = compositor ? compositor["createLayer"]("display adapter") : null;
    const renderer_options = layer ? { "canvas": layer["canvas"], "executorOptions": { "host": layer["host"] }, "scanoutLayer": layer } : {};
    if(host)
    {
        this.adapter_renderer = create(host, renderer_options);
        return host;
    }
    const channel = create_local_channel();
    this.adapter_renderer = create(channel.host, renderer_options);
    return channel.device;
};

/**
 * A WebGPU compositor of the screen canvas for the GLES host's frames
 * (create_adapter_renderer), when the page has the compositor
 * (libv86-webgpu.js) and a browser screen; null otherwise or if it fails
 * @return {!Promise<Object>}
 */
V86.prototype.gles_screen_compositor = async function()
{
    const Compositor = globalThis["V86WebGPUCompositor"], hosts = globalThis["V86GPUHost"];
    const screen_adapter = this.screen_adapter;
    if(typeof Compositor !== "function" || !hosts || !screen_adapter || !screen_adapter.claim_canvas) return null;
    const canvas = screen_adapter.claim_canvas("webgpu");
    const compositor = new Compositor(canvas);
    try
    {
        compositor["useHost"](hosts["acquire"](canvas, undefined));
        await compositor["attach"](hosts["acquire"](canvas, undefined));
    }
    catch(e)
    {
        dbg_log("GLES: the screen's compositor did not start (" + e + "): frames are read back", LOG_VGA);
        compositor["destroy"]();
        screen_adapter.use_canvas2d();
        return null;
    }
    if(this.destroyed)
    {
        compositor["destroy"]();
        return null;
    }
    screen_adapter.set_backend(compositor);
    this.gles_compositor = compositor;
    return compositor;
};

/**
 * The ends of a channel between a plugin's device and its host side on one
 * thread: a message arrives before post returns, and may hold views of guest RAM
 */
function create_local_channel()
{
    const handlers = [null, null];
    const end = (self, other) => ({
        "remote": false,
        "post": (message, transfer) => { handlers[other] && handlers[other](message); },
        "listen": handler => { handlers[self] = handler; },
    });
    return { device: end(0, 1), host: end(1, 0) };
}

/**
 * Check a loaded core (docs/arm64-virt-android16-plan.md P1.3): the ARM core
 * exports the ISA marker isa_aarch64, the x86 core does not, and the core's
 * own table entries end below WASM_TABLE_OFFSET, where compiled code's begin
 * @param {!Object} exports
 * @param {string} cpu_type
 * @param {WebAssembly.Table} wasm_table
 */
function check_core(exports, cpu_type, wasm_table)
{
    const arm = !!exports["isa_aarch64"];
    if(arm !== is_arm(cpu_type))
    {
        throw new Error("The Wasm core is the " + (arm ? "ARM" : "x86") + " core (" + (arm ? "v86-arm64.wasm" : "v86.wasm") +
            "), cpu_type is \"" + cpu_type + "\": wasm_path names the wrong file");
    }
    if(wasm_table && wasm_table.length > WASM_TABLE_OFFSET && wasm_table.get(WASM_TABLE_OFFSET - 1) !== null)
    {
        throw new Error("The Wasm core's own table entries reach WASM_TABLE_OFFSET (" + WASM_TABLE_OFFSET + "): raise it in src/const.js");
    }
}

/**
 * Constructor for emulator instances.
 *
 * For API usage, see v86.d.ts in the root of this repository.
 *
 * @param {{
      disable_mouse: (boolean|undefined),
      disable_keyboard: (boolean|undefined),
      wasm_fn: (Function|undefined),
      screen: ({
          scale: (number|undefined),
      } | undefined),
    }} options
 * @constructor
 */
export function V86(options)
{
    if(typeof options.log_level === "number")
    {
        // XXX: Shared between all emulator instances
        set_log_level(options.log_level);
    }

    this.cpu_is_running = false;
    this.destroyed = false;
    this.cpu_exception_hook = function(n) {};

    // The display adapter is required; its plugin loads with the other files
    this.graphics_adapter = check_graphics_adapter_options(options);
    // the guest CPU, the machine and the options that belong to them
    // (src/machine_options.js; CPU.init checks again)
    const machine = check_machine_options(options);
    this.cpu_type = machine.cpu_type;
    this.machine_type = machine.machine_type;
    // the ranchu machine's GLES host (ranchu_gpu "host", or an emulator
    // image's GPU mode "host"): it needs the page's renderer, as a 3D
    // display adapter does (docs/gles-proxy-plan.md)
    const android_device = options.android && ANDROID_DEVICES[options.android.device || "cf_arm64_only_phone"];
    this.gles_host = options.ranchu_gpu === "host" || !!options.gles_backdoor || !!(android_device && android_device.machine === "ranchu" &&
        ranchu_gpu_mode(android_device, options.android.gpu_mode).ranchu_gpu === "host");
    // each disk's disk_option and disk_error (docs/disk-persistence-plan.md
    // "启动校验"); the disks, to find an image bound twice (attach_sata_drive)
    /** @type {!Array<!Array<*>>} [name, descriptor] */
    this.disk_descriptors = check_disk_options(options).map(([name, file]) => [name, file]);

    const bus = Bus.create();
    this.bus = bus[0];
    this.emulator_bus = bus[1];
    if(options["worker_bus_setup"]) options["worker_bus_setup"](this);

    // Device plugins: a virtio device next to the CPU and a host side here,
    // talking over a channel (docs/graphics-proxy-plugin-plan.md)
    this["graphics_proxy"] = create_graphics_proxy(options);
    this.device_plugins = this["graphics_proxy"] ? [this["graphics_proxy"]] : [];
    /** the display adapter's 3D renderer on this page (create_adapter_renderer) */
    this.adapter_renderer = null;
    /** the GLES host's own compositor of the screen (gles_screen_compositor), or null */
    this.gles_compositor = null;
    this.plugins_ready = [];

    // the page goes away: the sessions of the disks written back to a disk
    // service are closed as far as the browser still sends it (completed
    // writes are in the image anyway; the service flushes when the lease ends)
    if(typeof window !== "undefined" && typeof window.addEventListener === "function")
    {
        this.pagehide_listener = () => this.pagehide_disks();
        window.addEventListener("pagehide", this.pagehide_listener);
    }

    if(options["cpu_worker"] && typeof Worker !== "undefined")
    {
        this.worker_controller = new CPUWorkerController(this, options);
        this.continue_init(null, options).catch(error => this.worker_controller.fail(error));
        return;
    }

    var cpu;
    var wasm_memory;

    // Host-parallel execution of the application processors (docs/multicore.md), an
    // internal option: `true` forces it (tests: it fails where it cannot
    // run), "auto" uses it where the host can and otherwise keeps the
    // requested cores cooperative; get_diagnostics() reports the choice.
    const parallel_option = options["parallel"];
    this.parallel_forced = parallel_option === true;
    this.parallel_requested = false;
    this.parallel_fallback = "not requested";
    if(parallel_option === true || parallel_option === "auto")
    {
        const reason = (options.cpu_cores || 1) <= 1 ? "one core" :
            options.cpu_clock && options.cpu_clock["mode"] === "deterministic" ? "deterministic clock" :
            options.cpu_clock && options.cpu_clock["rate"] !== undefined && options.cpu_clock["rate"] !== 1 ? "clock rate" :
            parallel_unsupported_reason(options.cpu_cores);
        // (cores in workers keep the host's time: a clock rate needs cooperative cores)
        if(reason === "clock rate" && this.parallel_forced) throw new Error("cpu_clock.rate: the cores must be cooperative, not parallel: true");
        if(!reason || this.parallel_forced) this.parallel_requested = true;
        this.parallel_fallback = reason;
    }

    const wasm_table = new WebAssembly.Table({ element: "anyfunc", initial: WASM_TABLE_SIZE + WASM_TABLE_OFFSET });

    const wasm_shared_funcs = {
        "cpu_exception_hook": n => this.cpu_exception_hook(n),
        "run_hardware_timers": function(a, t) { return cpu.run_hardware_timers(a, t); },
        "cpu_event_halt": () => { this.emulator_bus.send("cpu-event-halt"); },
        "abort": function() { dbg_assert(false); },
        "microtick": () => cpu ? cpu.clock.now() : v86.microtick(),
        "get_rand_int": function() { return get_rand_int(); },
        "stop_idling": function() { return cpu.stop_idling(); },
        // (cores built before the wide-native path was removed import it:
        // the M1 baselines, docs/jit-unification-plan.md P1.2)
        "x64_native_discard": () => {},
        "jit_publish": (client, id, slot, pointer, length) => cpu.jit_publish(client, id, slot, pointer, length),

        "io_port_read8": function(addr) { return cpu.io.port_read8(addr); },
        "io_port_read16": function(addr) { return cpu.io.port_read16(addr); },
        "io_port_read32": function(addr) { return cpu.io.port_read32(addr); },
        "io_port_write8": function(addr, value) { cpu.io.port_write8(addr, value); },
        "io_port_write16": function(addr, value) { cpu.io.port_write16(addr, value); },
        "io_port_write32": function(addr, value) { cpu.io.port_write32(addr, value); },

        "mmap_read8": function(addr) { return cpu.mmap_read8(addr); },
        "mmap_read32": function(addr) { return cpu.mmap_read32(addr); },
        "mmap_write8": function(addr, value) { cpu.mmap_write8(addr, value); },
        "mmap_write16": function(addr, value) { cpu.mmap_write16(addr, value); },
        "mmap_write32": function(addr, value) { cpu.mmap_write32(addr, value); },
        "mmap_write64": function(addr, value0, value1) { cpu.mmap_write64(addr, value0, value1); },
        "mmap_write128": function(addr, value0, value1, value2, value3) {
            cpu.mmap_write128(addr, value0, value1, value2, value3);
        },

        "log_from_wasm": function(offset, len) {
            const str = read_sized_string_from_mem(wasm_memory, offset, len);
            dbg_log(str, LOG_CPU);
        },
        "console_log_from_wasm": function(offset, len) {
            const str = read_sized_string_from_mem(wasm_memory, offset, len);
            console.error(str);
        },
        "dbg_trace_from_wasm": function() {
            dbg_trace(LOG_CPU);
        },

        // v86-parallel.wasm: wake a vCPU waiting on a word of the shared memory
        "parallel_notify": address => { Atomics.notify(new Int32Array(wasm_memory.buffer), address >>> 2); },
        // the ARM core: device registers of the virt machine (src/virt/io.js)
        "a64_mmio_read": (owner, offset, width) => cpu.io.mmio_read(owner, offset, width),
        "a64_mmio_write": (owner, offset, width, value) => { cpu.io.mmio_write(owner, offset, width, value); },
        // the arm32 GLES backdoor's calls (src/arm/backdoor_a32.js): r0 to r3, the answer for r0
        "a32_backdoor": (r0, r1, r2, r3) => cpu.backdoor_call(r0, r1, r2, r3),
        // extended RAM pages (src/extended_memory.js)
        "extended_load": (page, pointer) => { cpu.extended_store.load(page, wasm_memory, pointer); },
        "extended_store": (page, pointer) => { cpu.extended_store.store(page, wasm_memory, pointer); },
        "jit_clear_func": (wasm_table_index) => cpu.jit_clear_func(wasm_table_index),

        "__indirect_function_table": wasm_table,
    };

    let wasm_fn = options.wasm_fn;

    if(!wasm_fn)
    {
        wasm_fn = env =>
        {
            /* global __dirname */

            return new Promise(resolve => {
                // the core of the CPU's family (docs/arm64-virt-android16-plan.md
                // P1.3): the ARM core for arm64, the x86 core otherwise; the
                // fallback stays in the family
                const arm = is_arm(this.cpu_type);
                let v86_bin = arm ? (DEBUG ? "v86-arm64-debug.wasm" : "v86-arm64.wasm") : DEBUG ? "v86-debug.wasm" : "v86.wasm";
                let v86_bin_fallback = arm ? "v86-arm64-fallback.wasm" : "v86-fallback.wasm";
                // cores in vCPU workers need the relocatable build (src/parallel);
                // "auto" falls back to the cooperative build
                if(this.parallel_requested)
                {
                    if(!this.parallel_forced) v86_bin_fallback = v86_bin;
                    v86_bin = arm ? "v86-arm64-parallel.wasm" : "v86-parallel.wasm";
                }

                // (tests: V86_WASM selects another build, e.g. build/v86-parallel.wasm)
                const wasm_path = options.wasm_path ||
                    typeof process !== "undefined" && process.env && process.env["V86_WASM"];
                if(wasm_path)
                {
                    v86_bin = wasm_path;
                    v86_bin_fallback = wasm_fallback_path(v86_bin);
                }
                else if(typeof window === "undefined" && typeof __dirname === "string")
                {
                    v86_bin = __dirname + "/" + v86_bin;
                    v86_bin_fallback = __dirname + "/" + v86_bin_fallback;
                }
                else
                {
                    v86_bin = "build/" + v86_bin;
                    v86_bin_fallback = "build/" + v86_bin_fallback;
                }

                v86_bin_fallback = options["wasm_fallback_path"] || v86_bin_fallback;
                // an explicit wasm_path is the cooperative build: with cores in
                // workers, parallel_wasm_path replaces it ("auto" falls back to it)
                if(this.parallel_requested && options["parallel_wasm_path"])
                {
                    if(!this.parallel_forced) v86_bin_fallback = v86_bin;
                    v86_bin = options["parallel_wasm_path"];
                }

                load_file(v86_bin, {
                    // ("auto": v86-parallel.wasm is not there)
                    error: this.parallel_requested && !this.parallel_forced ? () => load_file(v86_bin_fallback, {
                        done: async bytes => {
                            const { instance } = await instantiate_v86(bytes, env);
                            this.wasm_source = bytes;
                            resolve(instance.exports);
                        },
                    }) : undefined,
                    done: async bytes =>
                    {
                        try
                        {
                            const { instance } = await instantiate_v86(bytes, env);
                            this.wasm_source = bytes;
                            resolve(instance.exports);
                        }
                        catch(err)
                        {
                            load_file(v86_bin_fallback, {
                                    done: async bytes => {
                                        const { instance } = await instantiate_v86(bytes, env);
                                        this.wasm_source = bytes;
                                        resolve(instance.exports);
                                    },
                                });
                        }
                    },
                    progress: e =>
                    {
                        this.emulator_bus.send("download-progress", {
                            file_index: 0,
                            file_count: 1,
                            file_name: v86_bin,

                            lengthComputable: e.lengthComputable,
                            total: e.total,
                            loaded: e.loaded,
                        });
                    }
                });
            });
        };
    }

    Promise.resolve().then(() => wasm_fn({ "env": wasm_shared_funcs }))
        .then((exports) => {
            if(this.destroyed) return;
            check_core(exports, this.cpu_type, wasm_table);
            wasm_memory = exports.memory;
            exports["rust_init"]();

            const emulator = this.v86 = new v86(this.emulator_bus, { exports, wasm_table });
            cpu = emulator.cpu;

            return this.continue_init(emulator, options);
        }).catch(error => {
            if(!this.destroyed) this.emulator_bus.send("emulator-error", error);
        });

    this.zstd_worker = null;
    this.zstd_worker_request_id = 0;
}

/**
 * The backend of a disk written back (docs/disk-persistence-plan.md): a
 * browser disk (opfs:, docs/vm-manager-plan.md U6), a disk service's URL,
 * or in Node a local file
 * @param {string} name
 * @param {!Object} file
 * @return {!Object}
 */
function writeback_backend(name, file)
{
    if(is_opfs_url(file.url))
    {
        return new OpfsDisk(file.url, { name, size: file.size });
    }
    if(is_service_url(file.url))
    {
        const base = typeof location !== "undefined" ? location.href : undefined;
        return new DiskServiceDisk(new URL(file.url, base).href, { name, token: file.token, size: file.size });
    }
    return new NodeFileDisk(file.url, { name, size: file.size });
}

/**
 * A browser disk (url "opfs:...") read only: its image as a File, read as a
 * file the user picked is, the changes in memory (src/opfs_disk.js)
 * @param {string} name
 * @param {?Object} file
 * @return {!Promise<?Object>}
 */
async function opfs_readable(name, file)
{
    if(!file || !is_opfs_url(file.url) || file.disk_option === "read_write") return file;
    const copy = Object.assign({}, file, { buffer: await opfs_file(file.url, name), async: true });
    delete copy.url;
    return copy;
}

V86.prototype.continue_init = async function(emulator, options)
{
    // (browser disks read only: their File, before the disks are made)
    options = Object.assign({}, options);
    for(const name of ["hda", "hdb", "cdrom", "fda", "fdb"])
    {
        options[name] = await opfs_readable(name, options[name]);
    }
    if(options.virtio_disks)
    {
        options.virtio_disks = await Promise.all(options.virtio_disks.map((disk, i) => opfs_readable("virtio_disk" + i, disk)));
    }
    if(options.usb && options.usb.mass_storage)
    {
        options.usb = Object.assign({}, options.usb, { mass_storage: await Promise.all(options.usb.mass_storage.map(async disk =>
            Object.assign({}, disk, { image: await opfs_readable("usb:" + disk.id, disk.image) }))) });
    }
    // android: { device, gpu_mode, selinux, vendor_ramdisk }: the kernel,
    // initrd and command line from the disk (docs/android-images-plan.md I2)
    if(options.android)
    {
        const android = options.android;
        if(android.device !== undefined && !ANDROID_DEVICES[android.device]) throw new Error("android.device: one of " + Object.keys(ANDROID_DEVICES).join(", "));
        // (the device's CPU and machine: Cuttlefish's arm64 virt, an emulator image's ranchu)
        const device = ANDROID_DEVICES[android.device || "cf_arm64_only_phone"];
        if(this.cpu_type !== device.cpu) throw new Error("android: " + device.id + " needs cpu_type \"" + device.cpu + "\"");
        if(this.machine_type !== device.machine) throw new Error("android: " + device.id + " needs machine_type \"" + device.machine + "\"");
        if(options.kernel || options.initrd || options.bzimage) throw new Error("android: the disk's boot partitions give the kernel and initrd (kernel and initrd left out)");
        if(!options.virtio_disks || !options.virtio_disks.length) throw new Error("android: the disk with the device's partitions is the first of virtio_disks");
        // (gfxstream: for the gfxstream device's development, docs/gfxstream-plan.md;
        // an emulator image's: guest or host, docs/gles-proxy-plan.md)
        const gpu_modes = device.machine === "ranchu" ? ["guest", "host", "swiftshader"] : ["swiftshader", "venus", "gfxstream"];
        if(android.gpu_mode !== undefined && !gpu_modes.includes(android.gpu_mode)) throw new Error("android.gpu_mode: " + gpu_modes.join(", "));
        if(android.selinux !== undefined && !["enforcing", "permissive"].includes(android.selinux)) throw new Error("android.selinux: enforcing or permissive");
        if(android.gles_version !== undefined && !GLES_VERSIONS[android.gles_version]) throw new Error("android.gles_version: " + Object.keys(GLES_VERSIONS).join(", "));
    }

    this.bus.register("emulator-stopped", function()
    {
        this.cpu_is_running = false;
        this.screen_adapter.pause();
    }, this);

    this.bus.register("emulator-started", function()
    {
        this.cpu_is_running = true;
        this.screen_adapter.continue();
    }, this);

    var settings = {};

    const boot_order =
        options.boot_order ? options.boot_order :
        options.fda ? BOOT_ORDER_FD_FIRST :
        options.hda ? BOOT_ORDER_HD_FIRST : BOOT_ORDER_CD_FIRST;

    if(options.modem)
    {
        settings.modem = options.modem;
        switch(options.modem.uart)
        {
            case 1:
                options.uart1 = true;
                break;
            case 2:
                options.uart2 = true;
                break;
            case 3:
                options.uart3 = true;
                break;
        }
    }

    settings.acpi = options.acpi;
    settings.machine_type = this.machine_type;
    settings.pcie_root_ports = options.pcie_root_ports;
    settings.hpet = options.hpet;
    settings.smbus = options.smbus;
    settings["ahci_test_drives"] = options["ahci_test_drives"]; // (tests only, see cpu.js)
    settings["ahci_test_pci_id"] = options["ahci_test_pci_id"];
    settings.cpu_cores = options.cpu_cores;
    settings.qemu_compatible = options.qemu_compatible;
    settings.parallel = this.parallel_requested;
    settings.parallel_fault = options["parallel_fault"];   // (test hook, src/parallel/vcpu.js)
    settings.cpu_clock = options.cpu_clock;
    settings.cpu_quantum = options.cpu_quantum;
    settings.cpu_schedule_seed = options.cpu_schedule_seed;
    settings.experimental_smp_jit = options.experimental_smp_jit;
    settings["cpu_type"] = this.cpu_type;
    settings["cpu_features"] = options["cpu_features"];
    settings["cpu_features_unreleased"] = options["cpu_features_unreleased"]; // (tests and development)
    settings["jit_switches"] = options["jit_switches"]; // (src/jit_switches.js)
    settings["cpu_profile"] = options["cpu_profile"]; // (the CPU model: src/machine_options.js, src/arm/cpu.js)
    settings.disable_jit = options.disable_jit;
    settings["jit_backend"] = options["jit_backend"];
    // (ir_region_budget, ir_stats, ir_verify, ir_dump, ir_opt_level,
    // ir_passes_disabled and ir_page_mode are deprecated and ignored: the IR
    // region tiers went in docs/jit-unification-plan.md M11)
    settings["ir_sync_publication"] = options["ir_sync_publication"];
    settings["ir_tier0"] = options["ir_tier0"];
    settings["x87_fast_math"] = options["x87_fast_math"];
    settings["x87_jit_cache"] = options["x87_jit_cache"];
    settings.load_devices = true;
    settings.memory_size = options.memory_size || 64 * 1024 * 1024;
    settings.high_memory_size = options.high_memory_size;
    settings.extended_memory_size = options.extended_memory_size;
    settings.extended_memory_cache = options.extended_memory_cache;
    settings.vram_size = options["vram_size"];
    // (internal, see src/graphics_adapter.js)
    settings.graphics_adapter_test = options["graphics_adapter_test"];
    settings.boot_order = boot_order;
    settings.fastboot = options.fastboot || false;
    settings.bootmenu = options.bootmenu || false;
    settings.fda = undefined;
    settings.fdb = undefined;
    settings.uart1 = options.uart1;
    settings.uart2 = options.uart2;
    settings.uart3 = options.uart3;
    settings.parallel1 = options.parallel1;
    settings.cmdline = options.cmdline;
    settings.preserve_mac_from_state_image = options.preserve_mac_from_state_image;
    settings.mac_address_translation = options.mac_address_translation;
    settings.cpuid_level = options.cpuid_level;
    settings.virtio_balloon = options.virtio_balloon;
    settings.virtio_console = !!options.virtio_console;

    const relay_url = options.network_relay_url || options.net_device && options.net_device.relay_url;
    if(relay_url)
    {
        // TODO: remove bus, use direct calls instead
        if(relay_url === "fetch")
        {
            this.network_adapter = new FetchNetworkAdapter(this.bus, options.net_device);
        }
        else if(relay_url === "inbrowser")
        {
            // NOTE: experimental, will change when usage of options.net_device gets refactored in favour of emulator.bus
            this.network_adapter = new InBrowserNetworkAdapter(this.bus, options.net_device);
        }
        else if(relay_url.startsWith("wisp://") || relay_url.startsWith("wisps://"))
        {
            this.network_adapter = new WispNetworkAdapter(relay_url, this.bus, options.net_device);
        }
        else
        {
            this.network_adapter = new NetworkAdapter(relay_url, this.bus);
        }
    }

    // Enable unconditionally, so that state images don't miss hardware
    // TODO: Should be properly fixed in restore_state
    // (the virt machine: only when asked for, since its virtio devices take
    // the virtio-mmio slots in order, as the reference's -device options do)
    settings.net_device = options.net_device || { type: is_arm(this.cpu_type) ? "none" : "ne2k" };
    // the sound card: the Sound Blaster 16 unless audio_device says otherwise
    settings.audio_device = is_arm(this.cpu_type) ? undefined : options.audio_device || "sb16";
    settings.usb = is_arm(this.cpu_type) ? undefined : options.usb || undefined;
    settings.tpm = is_arm(this.cpu_type) ? undefined : options.tpm || undefined;
    // the UEFI firmware (docs/uefi.md); its images arrive as firmware_code and firmware_vars
    settings.firmware = options.firmware && options.firmware.type === "uefi" ? options.firmware : undefined;
    this.usb_enabled = !!settings.usb;
    // (its USB disks' images: usb_disks[i] for mass_storage[i])
    if(settings.usb) settings.usb_disks = [];
    // the virt machine's virtio-blk disks (P5.4) and virtio-rng (P5.5)
    // (src/machine_options.js refuses them on the PC machines)
    if(options.virtio_disks) settings.virtio_disks = [];
    if(options.virtio_rng) settings.virtio_rng = true;
    // (their transport: virtio-mmio or the PCIe host, P5.7)
    if(options.virtio_transport) settings.virtio_transport = options.virtio_transport;
    // (virtio-input: a keyboard and a tablet, or the kinds listed, P5.8, P7.4)
    if(options.virtio_input) settings.virtio_input = Array.isArray(options.virtio_input) ? options.virtio_input.slice() : true;
    // (Android, P10.7: virtio-vsock, that many console ports, the GPU's PCI slot)
    if(options.virtio_vsock) settings.virtio_vsock = true;
    if(options.virtio_sound) settings.virtio_sound = true;
    if(options.virtio_console_ports) settings.virtio_console_ports = options.virtio_console_ports;
    if(options.virtio_gpu_pci_slot) settings.virtio_gpu_pci_slot = options.virtio_gpu_pci_slot;
    // (the ranchu machine: its framebuffer's size and density, its boot properties, src/virt/ranchu.js)
    if(options.ranchu_display) settings.ranchu_display = Object.assign({}, options.ranchu_display);
    if(options.ranchu_properties) settings.ranchu_properties = Object.assign({}, options.ranchu_properties);
    if(options.ranchu_gpu) settings.ranchu_gpu = options.ranchu_gpu;
    // (the GLES host's version: the options', an emulator image's (the bootloader's, below), else GLES 3.0; the ranchu
    // machine's option alone: another machine given it is refused, check_machine_options)
    if(settings.machine_type === "ranchu" || options.ranchu_gles_version !== undefined)
    {
        settings.ranchu_gles_version = options.ranchu_gles_version || DEFAULT_GLES_VERSION;
    }
    // (arm32's GLES backdoor: the GLES host's services for user code, src/arm/backdoor_a32.js)
    if(options.gles_backdoor) settings.gles_backdoor = true;

    // built-in devices behind PCI Express root ports (machine_type "q35"):
    // pcie_root_port of their options, and pcie_plugged (false: the slot
    // starts empty; attach_pcie_device plugs the device in)
    settings.root_port_devices = {};
    for(const [name, device_options] of [["net", options.net_device], ["virtio_9p", options.filesystem],
        ["virtio_console", options.virtio_console], ["virtio_balloon", options.virtio_balloon]])
    {
        if(device_options && typeof device_options === "object" && device_options.pcie_root_port !== undefined)
        {
            settings.root_port_devices[name] = { port: device_options.pcie_root_port, plugged: device_options.pcie_plugged !== false };
        }
    }

    const screen_options = options.screen || {};
    if(options.screen_container)
    {
        screen_options.container = options.screen_container;
    }

    if(!options.disable_keyboard)
    {
        this.keyboard_adapter = new KeyboardAdapter(this.bus);
    }
    if(!options.disable_mouse)
    {
        this.mouse_adapter = new MouseAdapter(this.bus, screen_options.container);
    }

    // Pointer lock is not needed while the guest uses absolute pointer
    // positions (the guest cursor follows the host cursor), so release it
    // when the guest driver enables absolute positioning
    this.absolute_pointer_enabled = false;
    const absolute_pointer = function(enabled)
    {
        if(enabled && !this.absolute_pointer_enabled &&
            typeof document !== "undefined" && document.pointerLockElement)
        {
            document.exitPointerLock();
        }
        this.absolute_pointer_enabled = enabled;
    };
    this.bus.register("vmware-absolute-mouse", absolute_pointer, this);
    // (the ARM machines' virtio tablet and touch screens: [active, the guest's cursor])
    this.bus.register("absolute-pointer", state => absolute_pointer.call(this, state[0]), this);

    if(options["screen_adapter"])
    {
        this.screen_adapter = options["screen_adapter"];
    }
    else if(screen_options.container)
    {
        this.screen_container = screen_options.container;
        // A plugin that draws the screen (graphics_proxy's compositor) owns the canvas:
        // the screen waits for it
        screen_options.deferred_backend = this.device_plugins.some(plugin => plugin["wants_screen"]);
        this.screen_adapter = new ScreenAdapter(screen_options, full => this.worker_controller ? this.worker_controller.request_frame(full) :
            this.v86.cpu.devices.display && this.v86.cpu.devices.display.request_frame(full));
    }
    else if(screen_options.ansi)
    {
        this.screen_adapter = new ANSIScreenAdapter(screen_options);
    }
    else
    {
        this.screen_adapter = new DummyScreenAdapter(screen_options);
    }
    settings.screen = this.screen_adapter;
    settings.screen_options = screen_options;

    // Plugins are not compiled with v86: every name they see is quoted
    const plugin_devices = [];
    for(const plugin of this.device_plugins)
    {
        // With a CPU worker the device is made there, from the plugin's worker_script
        const channel = this.worker_controller ?
            { device: null, host: this.worker_controller.device_channel(plugin["name"]) } :
            create_local_channel();
        let screen = null;
        if(plugin["wants_screen"])
        {
            const screen_adapter = this.screen_adapter;
            if(!screen_adapter.claim_canvas)
            {
                throw new Error(plugin["name"] + " needs a browser screen container");
            }
            screen = {
                "canvas": screen_adapter.claim_canvas("webgpu"),
                // Once its renderer is up, or back to the 2D canvas if it cannot start
                "set_backend": backend => screen_adapter.set_backend(backend),
                "fallback": () => screen_adapter.use_canvas2d(),
                "is_graphical": () => screen_adapter.is_graphical(),
            };
        }
        try
        {
            if(!this.worker_controller) plugin_devices.push(plugin["create_device"](channel.device));
            this.plugins_ready.push(Promise.resolve(
                plugin["start"]({ "emulator": this, "screen": screen, "channel": channel.host })));
        }
        catch(error)
        {
            if(screen) this.screen_adapter.use_canvas2d();
            throw error;
        }
    }
    if(this.device_plugins.some(plugin => plugin["screen_changed"]))
    {
        this.screen_adapter.on_geometry_change = () => {
            for(const plugin of this.device_plugins)
            {
                plugin["screen_changed"] && plugin["screen_changed"]();
            }
        };
    }
    settings.virtio_devices = plugin_devices.length ?
        (options["virtio_devices"] || []).concat(plugin_devices) : options["virtio_devices"];

    settings.serial_console = options.serial_console || { type: "none" };

    // NOTE: serial_container_xtermjs and serial_container are deprecated
    if(options.serial_container_xtermjs)
    {
        settings.serial_console.type = "xtermjs";
        settings.serial_console.container = options.serial_container_xtermjs;
    }
    else if(options.serial_container)
    {
        settings.serial_console.type = "textarea";
        settings.serial_console.container = options.serial_container;
    }

    if(settings.serial_console?.type === "xtermjs")
    {
        const xterm_lib = settings.serial_console.xterm_lib || window["Terminal"];
        this.serial_adapter = new SerialAdapterXtermJS(settings.serial_console.container, this.bus, xterm_lib);
    }
    else if(settings.serial_console?.type === "textarea")
    {
        this.serial_adapter = new SerialAdapter(settings.serial_console.container, this.bus);
        //this.recording_adapter = new SerialRecordingAdapter(this.bus);
    }

    const virtio_console_settings = (options.virtio_console && typeof options.virtio_console === "boolean") ? { type: "none" } : options.virtio_console;

    if(virtio_console_settings?.type === "xtermjs")
    {
        const xterm_lib = virtio_console_settings.xterm_lib || window["Terminal"];
        this.virtio_console_adapter = new VirtioConsoleAdapterXtermJS(virtio_console_settings.container, this.bus, xterm_lib);
    }
    else if(virtio_console_settings?.type === "textarea")
    {
        this.virtio_console_adapter = new VirtioConsoleAdapter(virtio_console_settings.container, this.bus);
    }

    if(settings.modem)
    {
        this.modem = new Modem(this.bus, settings.modem);
    }

    if(!options.disable_speaker)
    {
        this.speaker_adapter = new SpeakerAdapter(this.bus);
    }

    if(this.worker_controller)
    {
        this.serial_adapter?.show?.();
        this.virtio_console_adapter?.show?.();
        this.modem?.initialize();
        // the display adapter's renderer stays on this page (WebGPU is here)
        this.worker_controller.adapter_renderer = !!await this.create_adapter_renderer(undefined,
            this.worker_controller.device_channel(ADAPTER_RENDERER_CHANNEL));
        await this.worker_controller.start();
        return;
    }

    // The display adapter's plugin, fetched while the files load, and its 3D
    // renderer if it has one and WebGPU works
    const graphics_adapter = this.graphics_adapter === "none" ? Promise.resolve(undefined) :
        load_graphics_adapter(this.graphics_adapter, options["graphics_adapter_path"]);
    graphics_adapter.catch(() => {});
    // the network card's plugin (net_device.type "ne2k", the default, "e1000"), likewise
    const net_type = settings.net_device.type;
    const net_plugin = NET_DEVICE_PLUGINS.includes(net_type) ?
        load_device_plugin(NET_PLUGINS, net_type, settings.net_device.plugin_path, "net_device.plugin_path") : Promise.resolve(undefined);
    net_plugin.catch(() => {});
    // and the sound card's (audio_device "sb16", the default, "hd_audio")
    const audio_plugin = AUDIO_DEVICE_PLUGINS.includes(settings.audio_device) ?
        load_device_plugin(AUDIO_PLUGINS, settings.audio_device, options.audio_device_path, "audio_device_path") : Promise.resolve(undefined);
    audio_plugin.catch(() => {});
    // and USB's (usb: a controller and its devices)
    const usb_plugin = settings.usb ? load_device_plugin(USB_PLUGINS, "usb", settings.usb["plugin_path"], "usb.plugin_path") :
        Promise.resolve(undefined);
    usb_plugin.catch(() => {});
    // and the TPM's (tpm: docs/tpm.md); its module and its state are files (below)
    const tpm_plugin = settings.tpm ? load_device_plugin(TPM_PLUGINS, "tpm", settings.tpm["plugin_path"], "tpm.plugin_path") :
        Promise.resolve(undefined);
    tpm_plugin.catch(() => {});
    const adapter_renderer = this.create_adapter_renderer(options);

    // the disks' policies (src/disk_options.js), put on their buffers
    const disk_policies = new Map();
    /** @type {!Array<!Array<*>>} [name, buffer, descriptor] of the disks loaded */
    const loaded_disks = [];
    const disk_descriptors = new Map();

    // ugly, but required for closure compiler compilation
    function put_on_settings(name, buffer)
    {
        if(disk_policies.has(name))
        {
            set_disk_policy(buffer, name, disk_policies.get(name));
            loaded_disks.push([name, buffer, disk_descriptors.get(name)]);
        }

        // (virtio_disks[i]: "virtio_disk" + i)
        if(name.startsWith("virtio_disk"))
        {
            const i = +name.slice("virtio_disk".length);
            const disk = options.virtio_disks[i];
            settings.virtio_disks[i] = { buffer, id: disk.id, readonly: !!disk.readonly };
            return;
        }

        // (usb.mass_storage: "usb:" and the disk's id)
        if(name.startsWith("usb:"))
        {
            const disks = settings.usb.mass_storage;
            const i = disks.findIndex(disk => "usb:" + disk.id === name);
            settings.usb_disks[i] = { id: disks[i].id, buffer, read_only: !!disks[i].read_only };
            return;
        }
        switch(name)
        {
            case "hda":
                settings.hda = buffer;
                break;
            case "hdb":
                settings.hdb = buffer;
                break;
            case "cdrom":
                settings.cdrom = buffer;
                break;
            case "fda":
                settings.fda = buffer;
                break;
            case "fdb":
                settings.fdb = buffer;
                break;

            case "multiboot":
                settings.multiboot = buffer.buffer;
                break;
            case "bzimage":
                settings.bzimage = buffer.buffer;
                break;
            case "initrd":
                settings.initrd = buffer.buffer;
                break;
            // machine_type "virt" (src/virt/loader.js)
            case "kernel":
                settings.kernel = buffer.buffer;
                break;
            case "dtb":
                settings.dtb = buffer.buffer;
                break;
            // android.vendor_ramdisk (docs/android-images-plan.md I2)
            case "android_vendor_ramdisk":
                settings.android_vendor_ramdisk = buffer.buffer;
                break;

            case "bios":
                settings.bios = buffer.buffer;
                break;
            case "vga_bios":
                settings.vga_bios = buffer.buffer;
                break;
            case "firmware_code":
                settings.firmware_code = buffer.buffer;
                break;
            case "firmware_vars":
                // (a buffer object: src/pflash.js writes into it)
                settings.firmware_vars = buffer;
                break;
            case "tpm_wasm":
                settings.tpm_wasm = buffer.buffer;
                break;
            case "tpm_state":
                // (a buffer object: src/tpm/store.js writes into it)
                settings.tpm_state = buffer;
                break;
            case "initial_state":
                settings.initial_state = buffer.buffer;
                break;
            case "fs9p_json":
                settings.fs9p_json = buffer;
                break;
            default:
                dbg_assert(false, name);
        }
    }

    var files_to_load = [];

    const add_file = (name, file) =>
    {
        if(!file)
        {
            return;
        }

        // (virtio_disks[i]: "virtio_disk" + i)
        if(disk_kind(name) !== "other")
        {
            disk_policies.set(name, check_disk_policy(name, file));
            disk_descriptors.set(name, file);
            // written back (docs/disk-persistence-plan.md): in Node, the
            // url's local file (src/disk_writeback.js); a buffer object of
            // one's own is its own backend
            if(disk_policies.get(name).disk_option === "read_write" && !(file.get && file.set && file.load))
            {
                files_to_load.push({ name, loadable: writeback_backend(name, file) });
                return;
            }
        }

        // hard disks in a container format (docs/disk-image-formats-plan.md);
        // without a format, RAW in the buffers of src/buffer.js
        if(check_image_options(name, file, name === "hda" || name === "hdb" || name.startsWith("virtio_disk") || name.startsWith("usb:")))
        {
            files_to_load.push({
                name,
                loadable: create_disk_image(name, file, this.disk_image_settings()),
            });
            return;
        }

        // (a RAW disk's logical sectors: set on its buffer once loaded)
        const sector_size = file["logical_sector_size"];

        if(file.get && file.set && file.load)
        {
            files_to_load.push({
                name: name,
                loadable: file,
                sector_size,
            });
            return;
        }

        if(name === "bios" || name === "vga_bios" || name === "firmware_code" || name === "firmware_vars" || name === "tpm_wasm" || name === "tpm_state" ||
            name === "initial_state" || name === "multiboot" ||
            name === "bzimage" || name === "initrd" || name === "kernel" || name === "dtb" || name === "android_vendor_ramdisk")
        {
            // Ignore async for these because they must be available before boot.
            // This should make result.buffer available after the object is loaded
            file.async = false;
        }

        if(name === "fda" || name === "fdb")
        {
            // small, doesn't make sense loading asynchronously
            file.async = false;
        }

        if(file.url && !file.async)
        {
            files_to_load.push({
                name: name,
                url: file.url,
                size: file.size,
                sector_size,
            });
        }
        else
        {
            files_to_load.push({
                name,
                loadable: buffer_from_object(file, this.zstd_decompress_worker.bind(this)),
                sector_size,
            });
        }
    };

    if(options.state)
    {
        console.warn("Warning: Unknown option 'state'. Did you mean 'initial_state'?");
    }

    add_file("bios", options.bios);
    add_file("vga_bios", options.vga_bios);
    if(settings.firmware)
    {
        add_file("firmware_code", options.firmware.code);
        add_file("firmware_vars", options.firmware.vars);
    }
    if(settings.tpm)
    {
        // (beside the bundle unless wasm_path says; in Node a path)
        let wasm = settings.tpm["wasm_path"] || default_tpm_wasm_path();
        if(wasm.startsWith("file:")) wasm = decodeURIComponent(new URL(wasm).pathname);
        add_file("tpm_wasm", { url: wasm });
        add_file("tpm_state", settings.tpm["state"]);
    }
    add_file("cdrom", options.cdrom);
    add_file("hda", options.hda);
    add_file("hdb", options.hdb);
    add_file("fda", options.fda);
    add_file("fdb", options.fdb);
    add_file("initial_state", options.initial_state);
    add_file("multiboot", options.multiboot);
    add_file("bzimage", options.bzimage);
    add_file("initrd", options.initrd);
    add_file("kernel", options.kernel);
    add_file("dtb", options.dtb);
    add_file("android_vendor_ramdisk", options.android && options.android.vendor_ramdisk);
    // the virt machine's virtio-blk disks: {url or buffer, async, size, id,
    // readonly}; the buffer an ArrayBuffer, a File, or a buffer object of
    // its own (get, set, load), as hda may be
    (options.virtio_disks || []).forEach((disk, i) =>
    {
        const own = disk.buffer && disk.buffer.get && disk.buffer.set && disk.buffer.load;
        add_file("virtio_disk" + i, own ? disk.buffer : disk);
    });
    // USB disks (usb.mass_storage: { id, image, read_only }), the image as hda's
    if(settings.usb)
    {
        for(const disk of settings.usb.mass_storage || [])
        {
            const image = disk.image;
            const own = image.buffer && image.buffer.get && image.buffer.set && image.buffer.load;
            add_file("usb:" + disk.id, own ? image.buffer : image);
        }
    }

    if(options.filesystem && options.filesystem.handle9p)
    {
        settings.handle9p = options.filesystem.handle9p;
    }
    else if(options.filesystem && options.filesystem.proxy_url)
    {
        settings.proxy9p = options.filesystem.proxy_url;
    }
    else if(options.filesystem)
    {
        var fs_url = options.filesystem.basefs;
        var base_url = options.filesystem.baseurl;

        let file_storage = new MemoryFileStorage();

        if(base_url)
        {
            file_storage = new ServerFileStorageWrapper(file_storage, base_url, this.zstd_decompress.bind(this));
        }
        settings.fs9p = this.fs9p = new FS(file_storage);

        if(fs_url)
        {
            dbg_assert(base_url, "Filesystem: baseurl must be specified");

            var size;

            if(typeof fs_url === "object")
            {
                size = fs_url.size;
                fs_url = fs_url.url;
            }
            dbg_assert(typeof fs_url === "string");

            files_to_load.push({
                name: "fs9p_json",
                url: fs_url,
                size: size,
                as_json: true,
            });
        }
    }

    var starter = this;
    var total = files_to_load.length;
    let resolve_initialized, reject_initialized;
    const initialized = new Promise((resolve, reject) => {
        resolve_initialized = resolve;
        reject_initialized = reject;
    });

    var cont = function(index)
    {
        if(index === total)
        {
            setTimeout(() => done.call(this).then(resolve_initialized, reject_initialized), 0);
            return;
        }

        var f = files_to_load[index];

        // (a disk whose size is not a multiple of its sectors fails the start)
        const put = buffer =>
        {
            try
            {
                set_buffer_sector_size(f.name, buffer, f.sector_size);
            }
            catch(error)
            {
                reject_initialized(error);
                return;
            }
            put_on_settings.call(this, f.name, buffer);
            cont(index + 1);
        };

        if(f.loadable)
        {
            f.loadable.onload = function(e)
            {
                put(f.loadable);
            }.bind(this);
            // (a disk that cannot be opened fails the start: emulator-error)
            const loading = f.loadable.load();
            if(loading && typeof loading.catch === "function")
            {
                loading.catch(reject_initialized);
            }
        }
        else
        {
            load_whole_file(f.name, f.url, {
                progress: function progress(e)
                {
                    if(e.target.status === 200)
                    {
                        starter.emulator_bus.send("download-progress", {
                            file_index: index,
                            file_count: total,
                            file_name: f.url,

                            lengthComputable: e.lengthComputable,
                            total: e.total || f.size,
                            loaded: e.loaded,
                        });
                    }
                    else
                    {
                        starter.emulator_bus.send("download-error", {
                            file_index: index,
                            file_count: total,
                            file_name: f.url,
                            request: e.target,
                        });
                    }
                },
                as_json: f.as_json,
            }).then(result =>
            {
                if(f.url.endsWith(".zst") && f.name !== "initial_state")
                {
                    dbg_assert(f.size, "A size must be provided for compressed images");
                    result = this.zstd_decompress(f.size, new Uint8Array(/** @type {!ArrayBuffer} */ (result)));
                }

                put(f.as_json ? result : new SyncBuffer(result));
            }).catch(reject_initialized);
        }
    }.bind(this);
    // (a start that fails: the files written back opened so far are closed)
    initialized.catch(() =>
    {
        for(const f of files_to_load)
        {
            if(f.loadable && f.loadable.writeback && typeof f.loadable.close_now === "function") f.loadable.close_now();
        }
    });
    cont(0);
    return initialized;

    async function done()
    {
        // (a disk written back and another disk of the same file, by
        // another name: src/disk_writeback.js)
        await check_loaded_disks(loaded_disks);
        // (a floppy written back is used as it is: a floppy format's size)
        for(const [name, buffer] of loaded_disks)
        {
            if(disk_kind(String(name)) === "floppy" && buffer.writeback && !floppy_format_size(buffer.byteLength))
            {
                throw new Error(name + ": a floppy image written back must have the size of a floppy format (such as 1474560 bytes), not " +
                    buffer.byteLength);
            }
        }
        //if(settings.initial_state)
        //{
        //    // avoid large allocation now, memory will be restored later anyway
        //    settings.memory_size = 0;
        //}

        if(settings.fs9p && settings.fs9p_json)
        {
            if(!settings.initial_state)
            {
                settings.fs9p.load_from_json(settings.fs9p_json);

                if(options.bzimage_initrd_from_filesystem)
                {
                    const { bzimage_path, initrd_path } = this.get_bzimage_initrd_from_filesystem(settings.fs9p);

                    dbg_log("Found bzimage: " + bzimage_path + " and initrd: " + initrd_path);

                    const [initrd, bzimage] = await Promise.all([
                        settings.fs9p.read_file(initrd_path),
                        settings.fs9p.read_file(bzimage_path),
                    ]);
                    put_on_settings.call(this, "initrd", new SyncBuffer(initrd.buffer));
                    put_on_settings.call(this, "bzimage", new SyncBuffer(bzimage.buffer));
                }
            }
            else
            {
                dbg_log("Filesystem basefs ignored: Overridden by state image");
            }
        }
        else
        {
            dbg_assert(
                !options.bzimage_initrd_from_filesystem || settings.initial_state,
                "bzimage_initrd_from_filesystem: Requires a filesystem");
        }

        this.serial_adapter && this.serial_adapter.show && this.serial_adapter.show();
        this.virtio_console_adapter && this.virtio_console_adapter.show && this.virtio_console_adapter.show();

        if(!settings.initial_state)
        {
            // ide needs to read the mbr to calculate the device geometry
            if(settings.hda)
            {
                await new Promise(resolve => settings.hda.get_and_cache(0, 512, resolve));
            }
            if(settings.hdb)
            {
                await new Promise(resolve => settings.hdb.get_and_cache(0, 512, resolve));
            }
        }

        settings.graphics_adapter = await graphics_adapter;
        settings.net_device_plugin = await net_plugin;
        settings.audio_device_plugin = await audio_plugin;
        settings.usb_plugin = await usb_plugin;
        settings.tpm_plugin = await tpm_plugin;
        // (the TPM's module compiled and instantiated before the machine: asynchronous)
        if(settings.tpm_plugin) settings.tpm_prepared = await settings.tpm_plugin["prepare"]({ "wasm": settings.tpm_wasm });
        settings.graphics_adapter_renderer = await adapter_renderer;

        if(options.android)
        {
            // Android's bootloader (docs/android-images-plan.md I2): the
            // kernel, the initrd with bootconfig and the command line from
            // the first disk's boot partitions. Also with a state: a reset
            // loads them again (src/arm/cpu.js)
            const disk = settings.virtio_disks[0].buffer;
            const boot = await android_bootloader((offset, length) => new Promise(resolve => disk.get(offset, length, resolve)), disk.byteLength, {
                device: options.android.device, gpu_mode: options.android.gpu_mode, gles_version: options.ranchu_gles_version || options.android.gles_version,
                selinux: options.android.selinux,
                memory_mb: Math.round((settings.memory_size + (settings.extended_memory_size || 0)) / 1048576),
                vendor_ramdisk: settings.android_vendor_ramdisk ? new Uint8Array(settings.android_vendor_ramdisk) : undefined,
            });
            settings.kernel = boot.kernel.slice().buffer;
            settings.initrd = boot.initrd.slice().buffer;
            settings.cmdline = [boot.cmdline, options.cmdline].filter(Boolean).join(" ");
            // (an emulator image's device: its boot properties, under the options')
            if(boot.properties) settings.ranchu_properties = Object.assign({}, boot.properties, options.ranchu_properties);
            // (and its clock rate, with cooperative cores, unless the options set the clock)
            if(boot.clock_rate && !options.cpu_clock && !this.parallel_requested) settings.cpu_clock = { "rate": boot.clock_rate };
            // (and its GPU mode, which its command line follows)
            if(boot.ranchu_gpu) settings.ranchu_gpu = boot.ranchu_gpu;
            if(boot.gles_version) settings.ranchu_gles_version = boot.gles_version;
            if(boot.disks)
            {
                // (an emulator image: its disks the partitions, the first
                // written one keeping the disk's snapshot state)
                const owner = boot.disks.findIndex(d => !d.readonly);
                settings.virtio_disks = boot.disks.map((d, i) => ({ buffer: new PartitionBuffer(disk, d, i === owner), id: d.name, readonly: d.readonly }))
                    .concat(settings.virtio_disks.slice(1));
            }
            dbg_log("android: " + settings.kernel.byteLength + " bytes of kernel, " + settings.initrd.byteLength + " of initrd, " +
                (boot.vbmeta ? "vbmeta " + boot.vbmeta.digest : (boot.disks || []).map(d => d.name).join(", ")) + ", cmdline " + settings.cmdline);
        }

        // the GLES host's plugin (ranchu_gpu "host", gles_backdoor; docs/gles-proxy-plan.md):
        // the machine's GPU mode is known only now, after Android's bootloader
        if(settings.ranchu_gpu === "host" || settings.gles_backdoor)
        {
            settings.gles_plugin = await load_device_plugin(GLES_PLUGINS, "gles", options.ranchu_gpu_path, "ranchu_gpu_path");
            // (its GLSL ES compiler, glslang: GLSL ES 3.x's shaders; docs/gles3-plan.md)
            if(settings.gles_plugin["prepare"])
            {
                let glslang = null;
                try
                {
                    glslang = await load_whole_file("gles_glslang_path", options.gles_glslang_path || default_glslang_wasm_path());
                }
                catch(error)
                {
                    // (Node in the source tree, build/glslang.wasm not made: the repository's own)
                    const node = typeof process !== "undefined" && process.versions && process.versions.node;
                    if(node && !options.gles_glslang_path) glslang = await load_whole_file("gles_glslang_path", "bios/glslang.wasm").catch(() => null);
                    // (GLES 2.0's shaders need no glslang: without it, a GLES 3.x is the error)
                    if(!glslang && settings.ranchu_gles_version !== "2.0") throw error;
                    if(!glslang) console.warn(error.message + ": the GLES host offers GLES 2.0 alone");
                }
                if(glslang) settings.gles_prepared = await settings.gles_plugin["prepare"]({ "glslang": glslang });
            }
            // (no WebGPU, no renderer: say so rather than draw nothing)
            if(!settings.graphics_adapter_renderer)
            {
                throw new Error((settings.gles_backdoor ? "gles_backdoor" : "ranchu_gpu \"host\"") + ": the GLES host draws with the page's " +
                    "WebGPU renderer (libv86-webgpu.js and a WebGPU adapter), which this page does not have" +
                    (settings.gles_backdoor ? "" : "; use \"guest\" (the guest draws)"));
            }
        }

        if(this.destroyed) return;
        this.v86.init(settings);

        const parallel_bytes = this.parallel_requested && this.wasm_source && new Uint8Array(this.wasm_source);
        if(this.parallel_requested && (!parallel_bytes || !memory_import(parallel_bytes)?.shared))
        {
            if(this.parallel_forced) throw new Error("parallel: the CPU core is not v86-parallel.wasm");
            this.parallel_requested = false;
            this.parallel_fallback = "v86-parallel.wasm unavailable";
        }
        this.v86.cpu.parallel_fallback = this.parallel_requested ? "" : this.parallel_fallback;
        if(this.parallel_requested)
        {
            // application processors in vCPU workers (src/parallel/machine.js)
            const bytes = parallel_bytes;
            const worker_settings = {};
            for(const key of ["disable_jit", "jit_backend", "ir_tier0", "cpu_type", "x87_fast_math", "x87_jit_cache",
                "cpuid_level", "cpu_quantum", "parallel_fault"])
            {
                if(settings[key] !== undefined) worker_settings[key] = settings[key];
            }
            // the JIT switches set on the machine (src/jit_switches.js)
            worker_settings["jit_switches"] = get_jit_switches(this.v86.cpu.wm.exports, this.v86.cpu.wasm_memory, true);
            // (the same compiler policy as the machine's core, see CPU.prototype.init)
            worker_settings["disable_jit"] = !!settings.disable_jit || !settings.experimental_smp_jit;
            await this.v86.cpu.start_parallel({ bytes, settings: worker_settings,
                worker_url: options["vcpu_worker_url"] || await default_worker_url() });
            if(this.destroyed) return;
        }

        await Promise.all(this.plugins_ready);
        if(this.destroyed) return;

        this.modem && this.modem.initialize();

        if(settings.initial_state)
        {
            await this.restore_state(settings.initial_state);

            // The GC can't free settings, since it is referenced from
            // several closures. This isn't needed anymore, so we delete it
            // here
            settings.initial_state = undefined;
        }

        if(options.autostart)
        {
            this.v86.run();
        }

        this.emulator_bus.send("emulator-loaded");
    }
};

/**
 * What the disk images (src/image/factory.js) need from the emulator
 * @return {!Object}
 */
V86.prototype.disk_image_settings = function()
{
    return {
        // a QCOW2 cluster or a downloaded image: an error for data that is
        // not a Zstandard frame of that size (the core returns no data)
        zstd_decompress: (size, bytes) =>
        {
            const cpu = this.v86.cpu;
            const context = cpu.zstd_create_ctx(bytes.length);
            try
            {
                new Uint8Array(cpu.wasm_memory.buffer).set(bytes, cpu.zstd_get_src_ptr(context) >>> 0);
                const pointer = cpu.zstd_read(context, size) >>> 0;
                if(!pointer) throw new Error("not a Zstandard frame of " + size + " bytes");
                const result = new Uint8Array(cpu.wasm_memory.buffer.slice(pointer, pointer + size));
                cpu.zstd_read_free(pointer, size);
                return result;
            }
            finally
            {
                cpu.zstd_free_ctx(context);
            }
        },
        zstd_decompress_worker: this.zstd_decompress_worker.bind(this),
        progress: (file_name, e) =>
        {
            this.emulator_bus.send("download-progress", {
                file_index: 0,
                file_count: 1,
                file_name,
                lengthComputable: e.lengthComputable,
                total: e.total,
                loaded: e.loaded,
            });
        },
    };
};

/**
 * @param {number} decompressed_size
 * @param {Uint8Array} src
 * @return {ArrayBuffer}
 */
V86.prototype.zstd_decompress = function(decompressed_size, src)
{
    const cpu = this.v86.cpu;

    dbg_assert(!this.zstd_context);
    this.zstd_context = cpu.zstd_create_ctx(src.length);

    new Uint8Array(cpu.wasm_memory.buffer).set(src, cpu.zstd_get_src_ptr(this.zstd_context));

    const ptr = cpu.zstd_read(this.zstd_context, decompressed_size);
    const result = cpu.wasm_memory.buffer.slice(ptr, ptr + decompressed_size);
    cpu.zstd_read_free(ptr, decompressed_size);

    cpu.zstd_free_ctx(this.zstd_context);
    this.zstd_context = null;

    return result;
};

/**
 * @param {number} decompressed_size
 * @param {Uint8Array} src
 * @return {Promise<ArrayBuffer>}
 */
V86.prototype.zstd_decompress_worker = async function(decompressed_size, src)
{
    if(!this.zstd_worker)
    {
        function the_worker()
        {
            let wasm;

            // The limits of the imported table and memory (the import section)
            function import_limits(bytes)
            {
                let at = 8;
                const uleb = () => { let result = 0, shift = 0, byte; do { byte = bytes[at++]; result += (byte & 0x7F) * 2 ** shift; shift += 7; } while(byte & 0x80); return result; };
                const name = () => { const n = uleb(); at += n; };
                const result = { table: 0, memory: null };
                while(at < bytes.length)
                {
                    const id = bytes[at++], size = uleb(), end = at + size;
                    if(id === 2)
                    {
                        for(let count = uleb(); count--;)
                        {
                            name(); name();
                            const kind = bytes[at++];
                            if(kind === 0) uleb();
                            else if(kind === 1) { at++; const flags = uleb(); result.table = uleb(); if(flags & 1) uleb(); }
                            else if(kind === 2) { const flags = uleb(); const initial = uleb(); const maximum = flags & 1 ? uleb() : undefined; result.memory = { initial, maximum, shared: !!(flags & 2) }; }
                            else if(kind === 3) at += 2;
                        }
                        return result;
                    }
                    at = end;
                }
                return result;
            }

            globalThis.onmessage = function(e)
            {
                if(!wasm)
                {
                    // Every import of the core (whichever it is: x86 or ARM,
                    // cooperative or parallel) gets a stand-in: functions
                    // that must not run, the table and memory with the
                    // limits the module declares (the parallel core imports
                    // a shared memory)
                    const module = new WebAssembly.Module(e.data);
                    const limits = import_limits(new Uint8Array(e.data));
                    const env = {};
                    let memory = null;
                    for(const { name, kind } of WebAssembly.Module.imports(module))
                    {
                        if(kind === "function")
                        {
                            env[name] = () => console.error("zstd worker unexpectedly called " + name);
                        }
                        else if(kind === "table")
                        {
                            env[name] = new WebAssembly.Table({ element: "anyfunc", initial: limits.table || 0 });
                        }
                        else if(kind === "memory")
                        {
                            const m = limits.memory;
                            env[name] = memory = new WebAssembly.Memory(m.shared ?
                                { initial: m.initial, maximum: m.maximum, shared: true } : { initial: m.initial });
                        }
                    }
                    env["abort"] = () => { throw new Error("zstd worker aborted"); };
                    env["log_from_wasm"] = env["console_log_from_wasm"] = (off, len) => {
                        console.log(read_sized_string_from_mem((memory || wasm.exports.memory).buffer, off, len));
                    };
                    env["dbg_trace_from_wasm"] = () => console.trace();

                    const instance = new WebAssembly.Instance(module, { "env": env });
                    wasm = { exports: memory && !instance.exports.memory ? Object.assign({ memory }, instance.exports) : instance.exports };
                    return;
                }

                const { src, decompressed_size, id } = e.data;
                const exports = wasm.exports;

                const zstd_context = exports["zstd_create_ctx"](src.length);
                new Uint8Array(exports.memory.buffer).set(src, exports["zstd_get_src_ptr"](zstd_context));

                const ptr = exports["zstd_read"](zstd_context, decompressed_size);
                const result = exports.memory.buffer.slice(ptr, ptr + decompressed_size);
                exports["zstd_read_free"](ptr, decompressed_size);

                exports["zstd_free_ctx"](zstd_context);

                postMessage({ result, id }, [result]);
            };
        }

        const url = URL.createObjectURL(new Blob(["(" + the_worker.toString() + ")()"], { type: "text/javascript" }));
        this.zstd_worker = new Worker(url);
        URL.revokeObjectURL(url);
        this.zstd_worker.postMessage(this.wasm_source, [this.wasm_source]);
    }

    return new Promise(resolve => {
        const id = this.zstd_worker_request_id++;
        const done = async e =>
        {
            if(e.data.id === id)
            {
                this.zstd_worker.removeEventListener("message", done);
                dbg_assert(decompressed_size === e.data.result.byteLength);
                resolve(e.data.result);
            }
        };
        this.zstd_worker.addEventListener("message", done);
        this.zstd_worker.postMessage({ src, decompressed_size, id }, [src.buffer]);
    });
};

V86.prototype.get_bzimage_initrd_from_filesystem = function(filesystem)
{
    const root = (filesystem.read_dir("/") || []).map(x => "/" + x);
    const boot = (filesystem.read_dir("/boot/") || []).map(x => "/boot/" + x);

    let initrd_path;
    let bzimage_path;

    for(const f of [].concat(root, boot))
    {
        const old = /old/i.test(f) || /fallback/i.test(f);
        const is_bzimage = /vmlinuz/i.test(f) || /bzimage/i.test(f);
        const is_initrd = /initrd/i.test(f) || /initramfs/i.test(f);

        if(is_bzimage && (!bzimage_path || !old))
        {
            bzimage_path = f;
        }

        if(is_initrd && (!initrd_path || !old))
        {
            initrd_path = f;
        }
    }

    if(!initrd_path || !bzimage_path)
    {
        console.log("Failed to find bzimage or initrd in filesystem. Files:");
        console.log(root.join(" "));
        console.log(boot.join(" "));
    }

    return { initrd_path, bzimage_path };
};

/**
 * Start emulation. Do nothing if emulator is running already. Can be asynchronous.
 */
V86.prototype.run = async function()
{
    if(this.worker_controller) return this.worker_controller.serialize(() => this.worker_controller.rpc("run"));
    this.v86.run();
};

/**
 * Stop emulation. Do nothing if emulator is not running. Can be asynchronous.
 */
V86.prototype.stop = async function()
{
    if(this.worker_controller) return this.worker_controller.serialize(() => this.worker_controller.stop());
    if(!this.cpu_is_running)
    {
        // (stopped already: the disks written back are made durable all the same)
        await this.flush_writeback_disks();
        return;
    }

    await new Promise(resolve => {
        const listener = () => {
            this.remove_listener("emulator-stopped", listener);
            resolve();
        };
        this.add_listener("emulator-stopped", listener);
        this.v86.stop();
    });
    // cores in vCPU workers stop at their next safe point: wait for it, so
    // that the stopped machine's state is the one its cores are in
    const cpu = this.v86.cpu;
    // (after a vCPU failed there is no consistent state to capture)
    if(cpu.parallel && !cpu.parallel.failure && !this.v86.running)
    {
        await cpu.parallel.park();
        if(!this.v86.running) cpu.parallel_capture();
    }
    // the disks written back: their writes durable (docs/disk-persistence-plan.md)
    await this.flush_writeback_disks();
};

/**
 * [name, buffer] of the machine's disks
 * @return {!Array<!Array<*>>}
 */
V86.prototype.disk_buffers = function()
{
    if(!this.v86) return [];
    return disk_buffers(this.v86.cpu).map(([name, buffer]) => [name, buffer, undefined]);
};

/**
 * Flush (or, closing, flush and close) the disks written back
 * @param {boolean=} close
 * @return {!Promise<undefined>}
 */
V86.prototype.flush_writeback_disks = async function(close)
{
    const buffers = new Set(this.disk_buffers().map(([, buffer]) => buffer).filter(buffer => buffer.writeback));
    for(const buffer of buffers)
    {
        const operation = close ? buffer.close : buffer.flush;
        if(typeof operation !== "function") continue;
        await new Promise(resolve => operation.call(buffer, error =>
        {
            if(error) console.error((close ? "Closing " : "Flushing ") + (buffer.disk_name || "a disk") + ": " + error.message);
            resolve();
        }));
    }
};

/**
 * Free resources associated with this instance
 */
/** (pagehide: src/disk_service.js) */
V86.prototype.pagehide_disks = function()
{
    if(this.worker_controller)
    {
        this.worker_controller.rpc("pagehide").catch(() => {});
        return;
    }
    for(const [, buffer] of this.disk_buffers())
    {
        if(buffer.writeback && typeof buffer.close_keepalive === "function") buffer.close_keepalive();
    }
};

V86.prototype.destroy = async function()
{
    this.destroyed = true;
    if(this.pagehide_listener) window.removeEventListener("pagehide", this.pagehide_listener);
    if(this.worker_controller) await this.worker_controller.destroy();
    else await this.stop();
    if(this.device_state_operation) await this.device_state_operation;
    // (the disks written back: flushed, their files closed)
    if(!this.worker_controller) await this.flush_writeback_disks(true);

    for(const plugin of this.device_plugins)
    {
        plugin["destroy"] && await plugin["destroy"]();
    }
    this.adapter_renderer && this.adapter_renderer["destroy"]();
    this.gles_compositor && this.gles_compositor["destroy"]();
    this.v86 && this.v86.destroy();
    this.keyboard_adapter && this.keyboard_adapter.destroy();
    this.network_adapter && this.network_adapter.destroy();
    this.mouse_adapter && this.mouse_adapter.destroy();
    this.screen_adapter && this.screen_adapter.destroy();
    this.serial_adapter && this.serial_adapter.destroy();
    this.speaker_adapter && this.speaker_adapter.destroy();
    this.virtio_console_adapter && this.virtio_console_adapter.destroy();
    this.modem && this.modem.destroy();
};

/**
 * Restart (force a reboot).
 * @param {string=} reason "power-on" after the guest turned the machine off
 */
V86.prototype.restart = async function(reason)
{
    if(this.worker_controller) return this.worker_controller.state("restart", reason);
    if(!this.device_plugins.length) return this.v86.restart(reason);
    return this.with_device_state(async () => {
        for(const plugin of this.device_plugins)
        {
            plugin["reset"] && await plugin["reset"]();
        }
        this.v86.restart(reason);
    }, false);
};

/**
 * Diagnostic snapshot of the machine (CPU mode and registers, interrupt
 * controllers, ACPI device and tables) as plain data. For debugging and test
 * reports; the format is not a stable API.
 */
V86.prototype.get_diagnostics = async function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_diagnostics");
    return this.v86.cpu.get_diagnostics();
};

/**
 * Press the ACPI power button. A running ACPI guest gets a power button event
 * (usually starting an orderly shutdown). A machine that the guest has turned
 * off (event "acpi-power-off"; the virt machine: PSCI SYSTEM_OFF) is powered
 * on and started again. Resolves to false if the machine has no ACPI (option
 * acpi) and is not off.
 */
/**
 * The ACPI power state: "S0", "S3" (suspended to RAM), "S4" (hibernated and
 * off) or "S5" (soft off).
 * @return {Promise<string>}
 */
V86.prototype.power_state = async function()
{
    if(this.worker_controller) return this.worker_controller.rpc("power_state");
    const acpi = this.v86.cpu.devices.acpi;
    // (the virt machine: PSCI SYSTEM_OFF, the machine's power hook)
    if(!acpi) return this.v86.cpu.powered_off() ? "S5" : "S0";
    return acpi.sleeping ? "S3" : acpi.soft_off ? "S" + acpi.soft_off : "S0";
};

V86.prototype.power_button = async function()
{
    if(this.worker_controller) return this.worker_controller.serialize(() => this.worker_controller.rpc("power_button"));
    const acpi = this.v86.cpu.devices.acpi;
    if(!acpi)
    {
        // (the virt machine has no power button; one the guest turned off
        // with PSCI SYSTEM_OFF is powered on and started again)
        if(this.v86.cpu.powered_off && this.v86.cpu.powered_off())
        {
            await this.restart("power-on");
            await this.run();
            return true;
        }
        return false;
    }
    if(acpi.soft_off)
    {
        // power-on after S4/S5: RAM does not keep its contents
        await this.restart("power-on");
        await this.run();
    }
    else
    {
        acpi.press_power_button();
    }
    return true;
};

/**
 * Add an event listener (the emulator is an event emitter).
 *
 * The callback function gets a single argument which depends on the event.
 *
 * @param {string} event Name of the event.
 * @param {function(?)} listener The callback function.
 */
V86.prototype.add_listener = function(event, listener)
{
    this.bus.register(event, listener, this);
};

/**
 * Remove an event listener.
 *
 * @param {string} event
 * @param {function(*)} listener
 */
V86.prototype.remove_listener = function(event, listener)
{
    this.bus.unregister(event, listener);
};

/**
 * Restore the emulator state from the given state, which must be an
 * ArrayBuffer returned by
 * [`save_state`](#save_statefunctionobject-arraybuffer-callback).
 *
 * Note that the state can only be restored correctly if this constructor has
 * been created with the same options as the original instance (e.g., same disk
 * images, memory size, etc.).
 *
 * Different versions of the emulator might use a different format for the
 * state buffer.
 *
 * @param {ArrayBuffer} state
 */
V86.prototype.restore_state = async function(state)
{
    if(this.worker_controller) return this.worker_controller.state("restore", state);
    dbg_assert(arguments.length === 1);
    if(!this.device_plugins.length) return this.v86.restore_state(state);
    return this.with_device_state(() => this.restore_with_plugins(() => this.v86.restore_state(state)), false);
};

/**
 * Asynchronously save the current state of the emulator.
 *
 * @return {Promise<ArrayBuffer>}
 */
V86.prototype.save_state = async function()
{
    if(this.worker_controller) return this.worker_controller.state("save");
    dbg_assert(arguments.length === 0);
    if(!this.device_plugins.length && !this.adapter_host_state()) return this.v86.save_state();
    return this.with_device_state(async () => {
        await this.prepare_host_state();
        return this.save_with_plugins(() => this.v86.save_state());
    }, true);
};

/**
 * Save a V7 snapshot with bounded RAM buffers and writer backpressure.
 * @param {function(!Uint8Array): (void|!Promise<void>)} write
 * @return {!Promise<void>}
 */
V86.prototype.save_state_stream = async function(write)
{
    if(typeof write !== "function") throw new TypeError("Snapshot writer must be a function");
    if(this.worker_controller) return this.worker_controller.state_stream("save", write);
    if(!this.device_plugins.length && !this.adapter_host_state()) return this.v86.save_state_stream(write);
    return this.with_device_state(async () => {
        await this.prepare_host_state();
        return this.save_with_plugins(() => this.v86.save_state_stream(write));
    }, true);
};

/**
 * Restore a V7 stream from a Blob or a random-access byte source.
 * A read failure during restoration leaves the machine stopped.
 * @param {*} source
 * @return {!Promise<void>}
 */
V86.prototype.restore_state_stream = async function(source)
{
    if(this.worker_controller) return this.worker_controller.state_stream("restore", source);
    if(!this.device_plugins.length) return this.v86.restore_state_stream(source);
    return this.with_device_state(() => this.restore_with_plugins(() => this.v86.restore_state_stream(source)), false);
};

/**
 * Whether the display adapter, or the ranchu machine's GLES host, keeps
 * state on the GPU that a snapshot fetches
 * @return {boolean}
 */
V86.prototype.adapter_host_state = function()
{
    const devices = this.v86 && this.v86.cpu.devices;
    const adapter = devices && devices.graphics_adapter;
    return !!adapter && adapter.has_host_state() || !!(devices && devices.gles);
};

/**
 * Before a save: the GPU's state the display adapter and the GLES host
 * keep fetched (their prepare_save)
 * @return {!Promise<undefined>}
 */
V86.prototype.prepare_host_state = async function()
{
    if(!this.adapter_host_state()) return;
    const devices = this.v86.cpu.devices;
    const adapter = devices.graphics_adapter;
    if(adapter && adapter.has_host_state()) await adapter.prepare_save();
    const prepare = devices.gles && devices.gles.device["prepare_save"];
    if(prepare) await prepare();
};

/**
 * The CPU side of a device plugin
 * @param {!Object} plugin
 */
V86.prototype.plugin_device = function(plugin)
{
    return this.v86.cpu.devices.virtio_devices.find(device => device.name === plugin["name"]);
};

/**
 * Each plugin's host state goes into the snapshot with its device
 * @param {function():!Promise<*>} save
 */
V86.prototype.save_with_plugins = async function(save)
{
    try
    {
        for(const plugin of this.device_plugins)
        {
            this.plugin_device(plugin).host_state = plugin["prepare_save"] ? await plugin["prepare_save"]() : undefined;
        }
        return await save();
    }
    finally
    {
        for(const plugin of this.device_plugins)
        {
            this.plugin_device(plugin).host_state = undefined;
            plugin["release_save"] && plugin["release_save"]();
        }
    }
};

/**
 * @param {function():!Promise<*>} restore
 */
V86.prototype.restore_with_plugins = async function(restore)
{
    try
    {
        for(const plugin of this.device_plugins)
        {
            plugin["before_restore"] && await plugin["before_restore"]();
        }
        await restore();
        for(const plugin of this.device_plugins)
        {
            const device = this.plugin_device(plugin);
            const host_state = device.restored_host_state;
            device.restored_host_state = undefined;
            plugin["after_restore"] && await plugin["after_restore"](host_state);
        }
    }
    catch(error)
    {
        for(const plugin of this.device_plugins)
        {
            plugin["cancel_restore"] && plugin["cancel_restore"]();
        }
        throw error;
    }
};

// Serialize saves/restores and pause the CPU while plugins can still write
// guest RAM. A failed restore leaves the CPU stopped; a failed save resumes
// the untouched guest.
V86.prototype.with_device_state = function(operation, resume_on_error)
{
    const previous = this.device_state_operation || Promise.resolve();
    const next = previous.catch(() => {}).then(async () => {
        if(this.destroyed) throw new Error("Emulator has been destroyed");
        const was_running = this.is_running();
        await this.stop();
        if(this.speaker_adapter) await this.speaker_adapter.pause();
        let success = false;
        try
        {
            const result = await operation();
            success = true;
            return result;
        }
        finally
        {
            if(was_running && !this.destroyed && (success || resume_on_error)) this.run();
        }
    });
    // Keep only a completion barrier, not the potentially large saved buffer.
    this.device_state_operation = next.then(() => {}, () => {});
    return next;
};

/**
 * @return {number}
 * @ignore
 */
V86.prototype.get_instruction_counter = function()
{
    if(this.worker_controller) return this.worker_controller.instructions;
    if(this.v86)
    {
        const cpu = this.v86.cpu;
        // (the ARM core counts the instructions each core retired, P0.9)
        if(is_arm(cpu.cpu_type))
        {
            let retired = 0;
            for(let core = 0; core < cpu.cores; core++) retired += cpu.retired_instructions(core);
            return retired >>> 0;
        }
        return cpu.instruction_counter[0] >>> 0;
    }
    else
    {
        // TODO: Should be handled using events
        return 0;
    }
};

/**
 * @return {boolean}
 */
V86.prototype.is_running = function()
{
    return this.cpu_is_running;
};

/**
 * Set the image inserted in the floppy drive. Can be changed at runtime, as
 * when physically changing the floppy disk. With disk_option "read_write"
 * (docs/disk-persistence-plan.md) the guest's writes go back to the image;
 * the disk taken out (another inserted, or ejected) is flushed and closed.
 */
V86.prototype.set_fda = async function(file)
{
    if(this.worker_controller) return this.worker_controller.rpc("set_fda", [encode_worker_file(file)]);
    await this.insert_floppy(0, file);
};

/**
 * Set the image inserted in the second floppy drive, also at runtime.
 */
V86.prototype.set_fdb = async function(file)
{
    if(this.worker_controller) return this.worker_controller.rpc("set_fdb", [encode_worker_file(file)]);
    await this.insert_floppy(1, file);
};

/**
 * @param {number} index
 * @param {!Object} file
 */
V86.prototype.insert_floppy = async function(index, file)
{
    const name = index ? "fdb" : "fda";
    file = /** @type {!Object} */ (await opfs_readable(name, file));
    check_image_options(name, file, false);
    const policy = check_disk_policy(name, file);
    const others = this.disk_descriptors.filter(([n]) => n !== name);
    check_disk_bindings([[name, file, policy]], others);
    const drive = this.v86.cpu.devices.fdc.drives[index];
    let image;
    if(policy.disk_option === "read_write" && !(file.get && file.set && file.load))
    {
        image = writeback_backend(name, file);
        await image.load();
        if(!floppy_format_size(image.byteLength))
        {
            image.close_now();
            throw new Error(name + ": a floppy image written back must have the size of a floppy format (such as 1474560 bytes), not " + image.byteLength);
        }
    }
    else if(file.url && !file.async)
    {
        image = new SyncBuffer(await load_whole_file(name, file.url));
    }
    else
    {
        image = buffer_from_object(file, this.zstd_decompress_worker.bind(this));
        await new Promise((resolve, reject) => { image.onload = resolve; Promise.resolve(image.load()).catch(reject); });
    }
    set_disk_policy(image, name, policy);
    this.close_floppy(drive);
    drive.insert_disk(image);
    this.disk_descriptors = others.concat([[name, file]]);
};

/**
 * The disk taken out of a floppy drive: written back, it is flushed and closed
 * @param {?} drive
 */
V86.prototype.close_floppy = function(drive)
{
    this.v86.cpu.devices.fdc.disk_removed(drive);
    const buffer = drive.buffer;
    if(buffer && buffer.writeback && typeof buffer.close === "function")
    {
        buffer.close(error => { if(error) console.error(error.message); });
    }
};

/**
 * Eject floppy drive fda.
 */
V86.prototype.eject_fda = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("eject_fda");
    const drive = this.v86.cpu.devices.fdc.drives[0];
    this.close_floppy(drive);
    drive.eject_disk();
    this.disk_descriptors = this.disk_descriptors.filter(([n]) => n !== "fda");
};

/**
 * Eject second floppy drive fdb.
 */
V86.prototype.eject_fdb = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("eject_fdb");
    const drive = this.v86.cpu.devices.fdc.drives[1];
    this.close_floppy(drive);
    drive.eject_disk();
    this.disk_descriptors = this.disk_descriptors.filter(([n]) => n !== "fdb");
};

/**
 * Read an OVF package, an OVA archive (docs/disk-image-formats-plan.md P4),
 * before a machine is made: its disks as descriptors for hda, hdb or
 * attach_sata_drive (the archive with archive_member: read in it, not
 * extracted), the hardware it describes as v86 options (memory_size,
 * cpu_cores, machine_type, hda, hdb), and notes for what v86 does not have
 * (architecture, firmware, controllers, devices).
 * @param {!Object} file the archive, as for hda (url, buffer)
 * @return {!Promise<!Object>} {ovf, files, disks, options, notes}
 */
V86.import_ova = function(file)
{
    return import_ova(file, {});
};

/**
 * The buffer of a hard disk or CD drive by its name (hda, hdb, cdrom,
 * sata<port>)
 * @param {string} name
 * @return {?}
 */
V86.prototype.disk_buffer = function(name)
{
    const entry = this.v86.cpu.disk_devices().find(([device_name]) => device_name === name);
    const buffer = entry && entry[1].buffer;
    if(!buffer) throw new Error("No disk " + name);
    return buffer;
};

/**
 * What an export of a disk writes (export_disk_image): its size as the guest
 * sees it, and its image's format, file size and the bytes the guest wrote;
 * the guest's sector size
 * @param {string} name hda, hdb, cdrom, sata<port>, (virt) virtio_disk<n>
 * @return {!Promise<!Object>}
 */
V86.prototype.disk_image_info = async function(name)
{
    if(this.worker_controller) return this.worker_controller.rpc("disk-info", [name]);
    const buffer = this.disk_buffer(name);
    const reader = buffer.reader;
    const device = this.v86.cpu.disk_devices().find(([device_name]) => device_name === name)[1];
    return {
        "name": name,
        "format": reader ? reader.format : "raw",
        "size": buffer.byteLength,
        "file_size": reader ? reader.source.byteLength : buffer.byteLength,
        "written": buffer.overlay ? buffer.overlay.size() : buffer.written_blocks ? buffer.written_blocks.size * 256 : undefined,
        // (an IDE or AHCI drive's, a CD's 2048; a virtio disk's image's)
        "logical_sector_size": device.sector_size || buffer.logical_sector_size || 512,
    };
};

/**
 * Export a disk as the guest sees it, as a RAW image of its whole size
 * (docs/disk-image-formats-plan.md P2) or as a new QCOW2 image (format:
 * "qcow2", P5: version 3, 64 KiB clusters, the clusters of zeros left out):
 * the image's data with the guest's writes. The machine stops and its disk
 * I/O finishes first, so the stream is one view of the disk; it goes on
 * afterwards. `write` gets each chunk (at most 1 MiB) and may return a
 * promise: the next chunk waits for it.
 * @param {string} name hda, hdb, cdrom, sata<port>, (virt) virtio_disk<n>
 * @param {{write: function(!Uint8Array):(Promise<*>|undefined),
 *          format: (string|undefined),
 *          progress: (function({loaded: number, total: number})|undefined),
 *          signal: (AbortSignal|undefined)}} options
 * @return {!Promise<number>} the size written
 */
V86.prototype.export_disk_image = async function(name, options)
{
    if(!options || typeof options.write !== "function") throw new TypeError("export_disk_image: options.write must be a function");
    if(this.worker_controller) return this.worker_controller.export_disk(name, options);
    const buffer = this.disk_buffer(name);
    // (a disk written back: flushed, then read from its image)
    if(buffer.writeback && typeof buffer.flush === "function") await new Promise(resolve => buffer.flush(resolve));
    return this.v86.export_disk(buffer, options.write, options);
};

/**
 * Return buffer object of floppy disk of drive fda or null if the drive is empty.
 * @return {Uint8Array|null}
 */
V86.prototype.get_disk_fda = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_disk_fda");
    return this.v86.cpu.devices.fdc.drives[0].get_buffer();
};

/**
 * Return buffer object of second floppy disk of drive fdb or null if the drive is empty.
 * @return {Uint8Array|null}
 */
V86.prototype.get_disk_fdb = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_disk_fdb");
    return this.v86.cpu.devices.fdc.drives[1].get_buffer();
};

/**
 * A CD of files into the CD-ROM drive: an ISO 9660 image made of them, the
 * files in its root directory
 * @param {Array<{name: string, contents: Uint8Array}>} files
 */
V86.prototype.set_cdrom_files = async function(files)
{
    await this.set_cdrom({ buffer: iso9660.generate(files).buffer });
};

/**
 * Watch the first network card's traffic: each packet the guest sends
 * ("O") and receives ("I"), as it passes
 * @param {function(string, Uint8Array)} listener
 * @return {function()} stops watching
 */
V86.prototype.capture_network_traffic = function(listener)
{
    const received = data => listener("I", data);
    const sent = data => listener("O", data);
    this.emulator_bus.register("net0-receive", received, this);
    this.bus.register("net0-send", sent, this);
    return () =>
    {
        this.emulator_bus.unregister("net0-receive", received);
        this.bus.unregister("net0-send", sent);
    };
};

/**
 * The speaker's volume: 0 mutes it, 1 is full
 * @param {number} volume
 * @return {boolean} whether the machine has a speaker (none with disable_speaker)
 */
V86.prototype.set_speaker_volume = function(volume)
{
    if(!this.speaker_adapter) return false;
    this.speaker_adapter.mixer.set_volume(volume, undefined);
    return true;
};

/**
 * The CD-ROM drive: whether the machine has one (an IDE or AHCI drive; the
 * virt machine's CD image is a virtio disk) and whether a disc is in it
 * @return {!Promise<{present: boolean, inserted: boolean}>}
 */
V86.prototype.get_cdrom_state = async function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_cdrom_state");
    const devices = this.v86.cpu.devices;
    const cdrom = devices && devices.cdrom;
    return { "present": !!cdrom, "inserted": !!cdrom && cdrom.has_disk() };
};

/**
 * Set the image inserted in the CD-ROM drive. Can be changed at runtime, as
 * when physically changing the CD-ROM.
 */
V86.prototype.set_cdrom = async function(file)
{
    if(this.worker_controller) return this.worker_controller.rpc("set_cdrom", [encode_worker_file(file)]);
    file = await opfs_readable("cdrom", file);
    check_image_options("cdrom", file, false);
    if(file.url && !file.async)
    {
        this.v86.cpu.devices.cdrom.set_cdrom(new SyncBuffer(await load_whole_file("cdrom", file.url)));
    }
    else
    {
        const image = buffer_from_object(file, this.zstd_decompress_worker.bind(this));
        image.onload = () =>
        {
            this.v86.cpu.devices.cdrom.set_cdrom(image);
        };
        await image.load();
    }
};

/**
 * Eject the CD-ROM.
 */
V86.prototype.eject_cdrom = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("eject_cdrom");
    this.v86.cpu.devices.cdrom.eject();
};

/**
 * Hot plug a drive into a free SATA port of the Q35 machine's AHCI
 * controller (ports 0-5; hda, hdb and cdrom are on ports 0, 1 and 2). The
 * guest sees the link come up and finds the drive by resetting the port, as
 * with a drive plugged into a hot plug capable port.
 *
 * A snapshot holds the drives on the ports. To restore one taken with a hot
 * plugged drive, attach the same image to the same port first; otherwise the
 * restored guest sees the drive removed.
 *
 * @param {number} port
 * @param {Object|null} file the image, as for the hda option; for a CD drive
 *     the disc, or null for an empty drive
 * @param {{cdrom: (boolean|undefined)}=} options cdrom: an ATAPI CD drive
 */
V86.prototype.attach_sata_drive = async function(port, file, options)
{
    const cdrom = !!(options && options.cdrom);
    if(this.worker_controller) return this.worker_controller.rpc("attach_sata_drive", [port, encode_worker_file(file), { "cdrom": cdrom }]);
    const ahci = this.v86.cpu.devices.ahci;
    if(!ahci) throw new Error("attach_sata_drive: no AHCI controller (machine_type: \"q35\")");
    if(!file && !cdrom) throw new Error("attach_sata_drive: a disk needs an image");
    const name = cdrom ? "cdrom" : "sata" + port;
    const image = await this.load_attached_disk(name, file, cdrom, "attach_sata_drive");
    try { ahci.attach(port, { buffer: image, is_cdrom: cdrom }); }
    catch(error)
    {
        this.disk_descriptors = this.disk_descriptors.filter(([disk_name]) => disk_name !== name);
        throw error;
    }
};

/**
 * The image of a drive attached to the running machine (a SATA drive, a USB
 * disk), loaded as the disk options' are: written back by its disk_option,
 * a disk image's container, a whole file, or a buffer; its policy on it
 * (docs/disk-persistence-plan.md: checked with the disks the machine has)
 * @param {string} name the disk's name (its policy, errors, sector size)
 * @param {Object|null} file the image, as for the hda option (null: an empty CD drive)
 * @param {boolean} cdrom
 * @param {string} caller
 * @return {!Promise<?Object>}
 */
V86.prototype.load_attached_disk = async function(name, file, cdrom, caller)
{
    file = await opfs_readable(name, file);
    const policy = check_disk_policy(name, file);
    if(file) check_disk_bindings([[name, file, policy]], this.disk_descriptors);
    let image;
    const writeback = policy.disk_option === "read_write" && !(file.get && file.set && file.load);
    const disk_image = !writeback && !!check_image_options(name, file, !cdrom);
    if(writeback)
    {
        // (written back: src/disk_writeback.js, src/disk_service.js)
        image = writeback_backend(name, /** @type {!Object} */ (file));
        await image.load();
        try { await check_loaded_disks([[name, image, file]].concat(this.disk_buffers())); }
        catch(error) { image.close_now(); throw error; }
    }
    else if(disk_image)
    {
        // a hard disk in a container format (docs/disk-image-formats-plan.md)
        image = create_disk_image(name, /** @type {!Object} */ (file), this.disk_image_settings());
        await image.load();
    }
    else if(file && file.url && !file.async)
    {
        image = new SyncBuffer(await load_whole_file(name, file.url));
    }
    else if(file)
    {
        // (a descriptor as for the hda option, or a buffer object of one's own)
        image = await new Promise((resolve, reject) => {
            const buffer = file.get && file.set && file.load ? file : buffer_from_object(file, this.zstd_decompress_worker.bind(this));
            if(!buffer) throw new Error(caller + ": not a disk image");
            buffer.onload = () => resolve(buffer);
            Promise.resolve(buffer.load()).catch(reject);
        });
    }
    if(image && !cdrom)
    {
        // (a RAW disk's logical sectors; a disk image has its own)
        if(!disk_image) set_buffer_sector_size(name, image, file["logical_sector_size"]);
        // (an ATA disk's CHS geometry comes from its partition table)
        if(typeof image.get_and_cache === "function") await new Promise(resolve => image.get_and_cache(0, 512, resolve));
    }
    set_disk_policy(image, name, policy);
    if(file) this.disk_descriptors.push([name, file]);
    return image;
};

/**
 * Remove the drive of a SATA port of the Q35 machine (a surprise removal,
 * as when pulling a drive out of a hot plug capable port). Writes the guest
 * issued before are in the image; the guest learns of the removal from the
 * link going down.
 *
 * @param {number} port
 */
V86.prototype.detach_sata_drive = function(port)
{
    if(this.worker_controller) return this.worker_controller.rpc("detach_sata_drive", [port]);
    const ahci = this.v86.cpu.devices.ahci;
    if(!ahci) throw new Error("detach_sata_drive: no AHCI controller (machine_type: \"q35\")");
    const device = ahci.ports[port] && ahci.ports[port].device;
    ahci.detach(port);
    // (a disk written back: its writes flushed, the file closed)
    if(device && device.buffer && device.buffer.writeback && typeof device.buffer.close === "function")
    {
        device.buffer.close(error => { if(error) console.error(error.message); });
    }
    const names = ["sata" + port, ["hda", "hdb", "cdrom"][port]];
    this.disk_descriptors = this.disk_descriptors.filter(([name]) => !names.includes(name));
};

/**
 * Plug a card into a PCI Express root port of the Q35 machine: the device
 * whose options put it behind that port (pcie_root_port), after it was
 * pulled out or when it started out (pcie_plugged: false). The guest sees a
 * card inserted into a hot plug slot, and the device starts afresh: in a slot
 * that is off (empty slots are after reset, as in QEMU), presence detect
 * changed and the attention button pressed (as QEMU), and the guest switches
 * the slot on; in a powered slot, presence detect changed and the link comes
 * up. Guests need PCI Express native hot plug (Linux: pciehp; the ACPI tables
 * grant it through _OSC).
 *
 * A snapshot holds which slots have their card in.
 *
 * @param {number} port
 */
V86.prototype.attach_pcie_device = async function(port)
{
    if(this.worker_controller) return this.worker_controller.rpc("attach_pcie_device", [port]);
    root_port_of(this, port, "attach_pcie_device").insert();
};

/**
 * Pull the card out of a PCI Express root port of the Q35 machine. By
 * default, as with the slot's attention button: the guest releases the
 * device and switches the slot and its power indicator off, then the card
 * leaves (Linux and Windows wait 5 seconds for a second press, which would
 * cancel), and the promise is fulfilled. A guest without hot plug never does; surprise: true pulls the
 * card at once, as from a slot without a button. (Reads from a card that is
 * gone return all ones; Linux's virtio drivers, as of 6.18, then wait forever
 * for the device's reset: take virtio devices out with the button.)
 *
 * @param {number} port
 * @param {{surprise: (boolean|undefined)}=} options
 * @return {!Promise<void>}
 */
V86.prototype.detach_pcie_device = async function(port, options)
{
    const surprise = !!(options && options.surprise);
    if(this.worker_controller) return this.worker_controller.detach_pcie_device(port, surprise);
    await root_port_of(this, port, "detach_pcie_device").remove(surprise);
};

/**
 * Plug a USB device out of its port or back in (usb's devices: "tablet"):
 * the guest sees it leave or arrive, as at a socket. Fulfilled once done;
 * rejected for a device the machine does not have.
 * @param {string} id
 * @param {boolean} plugged
 * @return {!Promise<void>}
 */
V86.prototype.usb_plug = function(id, plugged)
{
    if(!this.usb_enabled) return Promise.reject(new Error("usb_plug: the machine has no USB (the usb option)"));
    return new Promise((resolve, reject) =>
    {
        const listener = data =>
        {
            if(data[0] !== id) return;
            this.remove_listener("usb-plugged", listener);
            if(data[2]) reject(new Error("usb_plug: " + data[2]));
            else resolve();
        };
        this.add_listener("usb-plugged", listener);
        this.bus.send("usb-plug", [id, !!plugged]);
    });
};

/**
 * The USB devices: each one's id, port, whether it is in its port, the
 * controller that has it ("xhci", "ehci", or "uhci": the UHCI or an EHCI's
 * companion) and its speed in Mbit/s (12, 480, 5000)
 * @return {!Promise<!Array<{id: string, port: number, plugged: boolean, controller: string, speed: number}>>}
 */
V86.prototype.usb_devices = async function()
{
    if(this.worker_controller) return this.worker_controller.rpc("usb_devices");
    const usb = this.v86 && this.v86.cpu.devices.usb;
    return usb ? usb.device["device_list"]() : [];
};

/**
 * Plug a disk image into the machine as a USB disk (a USB stick: usb's
 * mass storage, in the first free port of the USB controller). The guest
 * sees it arrive and mounts it. The image is as for the hda option, with
 * disk_option and disk_error; read_only: the guest sees it write protected.
 *
 * A snapshot holds the USB disks in their ports: to restore one taken with
 * a USB disk, attach the same image with the same id first; otherwise the
 * restored guest sees the disk leave.
 *
 * @param {string} id the disk's id (usb_plug, usb_detach_disk, "usb:" + id is its name for disk_buffer)
 * @param {!Object} file
 * @param {{read_only: (boolean|undefined)}=} options
 * @return {!Promise<void>}
 */
V86.prototype.usb_attach_disk = async function(id, file, options)
{
    const read_only = !!(options && options.read_only);
    if(this.worker_controller) return this.worker_controller.rpc("usb_attach_disk", [id, encode_worker_file(file), { "read_only": read_only }]);
    const usb = this.v86.cpu.devices.usb;
    if(!usb) throw new Error("usb_attach_disk: the machine has no USB (the usb option)");
    if(typeof id !== "string" || !id || id === "tablet") throw new Error("usb_attach_disk: a USB disk needs an id of its own");
    if(!file) throw new Error("usb_attach_disk: a USB disk needs an image");
    const name = "usb:" + id;
    const image = await this.load_attached_disk(name, file, false, "usb_attach_disk");
    try { this.v86.cpu.usb_attach_disk(id, image, read_only); }
    catch(error)
    {
        this.disk_descriptors = this.disk_descriptors.filter(([disk_name]) => disk_name !== name);
        throw error;
    }
};

/**
 * Pull a USB disk out (a surprise removal, as when pulling a USB stick
 * out): writes the guest issued before are in the image; a disk written
 * back is flushed and closed. (To let the guest finish first, eject it in
 * the guest; the "usb-disk-ejected" event tells when the guest ejected it.)
 * @param {string} id
 * @return {!Promise<void>}
 */
V86.prototype.usb_detach_disk = async function(id)
{
    if(this.worker_controller) return this.worker_controller.rpc("usb_detach_disk", [id]);
    const buffer = this.v86.cpu.usb_detach_disk(id);
    if(buffer && buffer.writeback && typeof buffer.close === "function")
    {
        await new Promise(resolve => buffer.close(error => { if(error) console.error(error.message); resolve(); }));
    }
    this.disk_descriptors = this.disk_descriptors.filter(([name]) => name !== "usb:" + id);
};

/**
 * @param {V86} emulator
 * @param {number} port
 * @param {string} caller
 * @return {PCIeRootPort}
 */
function root_port_of(emulator, port, caller)
{
    const ports = emulator.v86.cpu.devices.pcie_root_ports || [];
    if(!ports[port])
    {
        throw new Error(caller + ": no root port " + port + " (machine_type \"q35\", pcie_root_ports: " + ports.length + ")");
    }
    return ports[port];
}

/**
 * Send a sequence of scan codes to the emulated PS2 controller. A list of
 * codes can be found at http://stanislavs.org/helppc/make_codes.html.
 * Do nothing if there is no keyboard controller.
 *
 * @param {Array.<number>} codes
 * @param {number=} delay
 */
V86.prototype.keyboard_send_scancodes = async function(codes, delay)
{
    for(var i = 0; i < codes.length; i++)
    {
        this.bus.send("keyboard-code", codes[i]);
        if(delay) await new Promise(resolve => setTimeout(resolve, delay));
    }
};

/**
 * Send translated keys
 * @param {Array.<number>} codes
 * @param {number=} delay
 */
V86.prototype.keyboard_send_keys = async function(codes, delay)
{
    for(var i = 0; i < codes.length; i++)
    {
        this.keyboard_adapter.simulate_press(codes[i]);
        if(delay) await new Promise(resolve => setTimeout(resolve, delay));
    }
};

/**
 * Send text, assuming the guest OS uses a US keyboard layout
 * @param {string} string
 * @param {number=} delay
 */
V86.prototype.keyboard_send_text = async function(string, delay)
{
    for(var i = 0; i < string.length; i++)
    {
        this.keyboard_adapter.simulate_char(string[i]);
        if(delay) await new Promise(resolve => setTimeout(resolve, delay));
    }
};

/**
 * Download a screenshot (returns an <img> element, only works in browsers)
 */
V86.prototype.screen_make_screenshot = function()
{
    for(const plugin of this.device_plugins)
    {
        const image = plugin["screenshot"] && plugin["screenshot"]();
        if(image) return image;
    }
    if(this.screen_adapter)
    {
        return this.screen_adapter.make_screenshot();
    }
    return null;
};

/**
 * Set the scaling level of the emulated screen.
 *
 * @param {number} sx
 * @param {number} sy
 */
V86.prototype.screen_set_scale = function(sx, sy)
{
    if(this.screen_adapter)
    {
        this.screen_adapter.set_scale(sx, sy);
    }
};

/**
 * Tell the display adapter what size the page would show the guest's display
 * at, such as the size of its window. Adapters that can ask the guest to
 * change its resolution do (virtio_gpu); the others ignore it.
 *
 * @param {number} width
 * @param {number} height
 * @param {number=} display which of the guest's displays (0, the first)
 */
V86.prototype.set_display_size = function(width, height, display)
{
    this.bus.send("display-host-size", [width >>> 0, height >>> 0, display >>> 0]);
};

/**
 * Go fullscreen (only browsers)
 */
V86.prototype.screen_go_fullscreen = function()
{
    if(!this.screen_adapter)
    {
        return;
    }

    // The configured container, whatever its id
    var elem = this.screen_container || this.screen_adapter.get_graphics_canvas &&
        this.screen_adapter.get_graphics_canvas().parentElement;

    if(!elem)
    {
        return;
    }

    // bracket notation because otherwise they get renamed by closure compiler
    var fn = elem["requestFullscreen"] || elem["requestFullScreen"] ||
            elem["webkitRequestFullscreen"] ||
            elem["mozRequestFullScreen"] ||
            elem["msRequestFullScreen"];

    if(fn)
    {
        fn.call(elem);

        // This is necessary, because otherwise chromium keyboard doesn't work anymore.
        // Might (but doesn't seem to) break something else
        var focus_element = document.getElementsByClassName("phone_keyboard")[0];
        focus_element && focus_element.focus();
    }

    try {
        navigator.keyboard.lock();
    } catch(e) {}

    this.lock_mouse();
};

/**
 * Lock the mouse cursor: It becomes invisble and is not moved out of the
 * browser window.
 */
V86.prototype.lock_mouse = async function()
{
    const elem = document.body;

    try
    {
        await elem.requestPointerLock({
            unadjustedMovement: true,
        });
    }
    catch(e)
    {
        // as per MDN, retry without unadjustedMovement option
        await elem.requestPointerLock();
    }
};

/**
 * Enable or disable sending mouse events to the emulated PS2 controller.
 *
 * @param {boolean} enabled
 */
V86.prototype.mouse_set_enabled = function(enabled)
{
    if(this.mouse_adapter)
    {
        this.mouse_adapter.emu_enabled = enabled;
        this.mouse_adapter.update_cursor();
    }
};
V86.prototype.mouse_set_status = V86.prototype.mouse_set_enabled;

/**
 * Enable or disable sending keyboard events to the emulated PS2 controller.
 *
 * @param {boolean} enabled
 */
V86.prototype.keyboard_set_enabled = function(enabled)
{
    if(this.keyboard_adapter)
    {
        this.keyboard_adapter.emu_enabled = enabled;
    }
};
V86.prototype.keyboard_set_status = V86.prototype.keyboard_set_enabled;

/**
 * Send a string to the first emulated serial terminal.
 *
 * @param {string} data
 */
V86.prototype.serial0_send = function(data)
{
    for(var i = 0; i < data.length; i++)
    {
        this.bus.send("serial0-input", data.charCodeAt(i));
    }
};

/**
 * Send text (as UTF-8) or bytes to the guest's first virtio console port
 * (hvc0 on the virt machine, the kernel's console there)
 * @param {string|Uint8Array} data
 */
V86.prototype.virtio_console_send = function(data)
{
    this.bus.send("virtio-console0-input-bytes", typeof data === "string" ? new TextEncoder().encode(data) : data);
};

/**
 * A stream socket to a port of the guest's vsock (machine_type "virt" with
 * virtio_vsock; src/virtio_vsock.js): resolves when the guest accepts,
 * rejects when it refuses. The stream has write(bytes), close(), and the
 * callbacks on_data(bytes) and on_close() to be set.
 *
 * @param {number} port
 * @return {!Promise<!Object>}
 */
V86.prototype.vsock_connect = function(port)
{
    const id = this.vsock_next_id = (this.vsock_next_id || 0) + 1;
    const stream = {
        "closed": false,
        "on_data": null,
        "on_close": null,
        "write": bytes => { if(!stream["closed"]) this.bus.send("virtio-vsock-send", [id, bytes]); },
        "close": () => { if(!stream["closed"]) this.bus.send("virtio-vsock-close", [id]); },
    };
    return new Promise((resolve, reject) => {
        let connected = false;
        const on_connected = ([i]) => { if(i === id) { connected = true; resolve(stream); } };
        const on_data = ([i, bytes]) => { if(i === id && stream["on_data"]) stream["on_data"](bytes); };
        const on_closed = ([i]) => {
            if(i !== id) return;
            stream["closed"] = true;
            this.bus.unregister("virtio-vsock-connected", on_connected);
            this.bus.unregister("virtio-vsock-data", on_data);
            this.bus.unregister("virtio-vsock-closed", on_closed);
            if(!connected) reject(new Error("vsock: the guest refused port " + port));
            else if(stream["on_close"]) stream["on_close"]();
        };
        this.bus.register("virtio-vsock-connected", on_connected, this);
        this.bus.register("virtio-vsock-data", on_data, this);
        this.bus.register("virtio-vsock-closed", on_closed, this);
        this.bus.send("virtio-vsock-connect", [id, port]);
    });
};

/**
 * Send bytes to a serial port (to be received by the emulated PC).
 *
 * @param {Uint8Array} data
 */
V86.prototype.serial_send_bytes = function(serial, data)
{
    for(var i = 0; i < data.length; i++)
    {
        this.bus.send("serial" + serial + "-input", data[i]);
    }
};

/**
 * Set or clear the data carrier detect (DCD) status of a serial port.
 *
 * @param {number} serial
 * @param {boolean} status
 */
V86.prototype.serial_set_carrier_detect = function(serial, status)
{
    this.bus.send("serial" + serial + "-carrier-detect-input", status);
};

/**
 * Set or clear the ring indicator (RING) status of a serial port.
 *
 * @param {number} serial
 * @param {boolean} status
 */
V86.prototype.serial_set_ring_indicator = function(serial, status)
{
    this.bus.send("serial" + serial + "-ring-indicator-input", status);
};

/**
 * Set or clear the data set ready (DSR) status of a serial port.
 *
 * @param {number} serial
 * @param {boolean} status
 */
V86.prototype.serial_set_data_set_ready = function(serial, status)
{
    this.bus.send("serial" + serial + "-data-set-ready-input", status);
};

/**
 * Set or clear the clear to send (CTS) status of a serial port.
 *
 * @param {number} serial
 * @param {boolean} status
 */
V86.prototype.serial_set_clear_to_send = function(serial, status)
{
    this.bus.send("serial" + serial + "-clear-to-send-input", status);
};

/**
 * Write to a file in the 9p filesystem. Nothing happens if no filesystem has
 * been initialized.
 *
 * @param {string} file
 * @param {Uint8Array} data
 */
V86.prototype.create_file = async function(file, data)
{
    if(this.worker_controller) return this.worker_controller.rpc("create_file", [file, data]);
    dbg_assert(arguments.length === 2);
    var fs = this.fs9p;

    if(!fs)
    {
        return;
    }

    var parts = file.split("/");
    var filename = parts[parts.length - 1];

    var path_infos = fs.SearchPath(file);
    var parent_id = path_infos.parentid;
    var not_found = filename === "" || parent_id === -1;

    if(!not_found)
    {
        await fs.CreateBinaryFile(filename, parent_id, data);
    }
    else
    {
        return Promise.reject(new FileNotFoundError());
    }
};

/**
 * Read a file in the 9p filesystem. Nothing happens if no filesystem has been
 * initialized.
 *
 * @param {string} file
 */
V86.prototype.read_file = async function(file)
{
    if(this.worker_controller) return this.worker_controller.rpc("read_file", [file]);
    dbg_assert(arguments.length === 1);
    var fs = this.fs9p;

    if(!fs)
    {
        return;
    }

    const result = await fs.read_file(file);

    if(result)
    {
        return result;
    }
    else
    {
        return Promise.reject(new FileNotFoundError());
    }
};

/*
 * @deprecated
 * Use wait_until_vga_screen_contains etc.
 */
V86.prototype.automatically = function(steps)
{
    const run = (steps) =>
    {
        const step = steps[0];

        if(!step)
        {
            return;
        }

        const remaining_steps = steps.slice(1);

        if(step.sleep)
        {
            setTimeout(() => run(remaining_steps), step.sleep * 1000);
            return;
        }

        if(step.vga_text)
        {
            this.wait_until_vga_screen_contains(step.vga_text).then(() => run(remaining_steps));
            return;
        }

        if(step.keyboard_send)
        {
            if(Array.isArray(step.keyboard_send))
            {
                this.keyboard_send_scancodes(step.keyboard_send);
            }
            else
            {
                dbg_assert(typeof step.keyboard_send === "string");
                this.keyboard_send_text(step.keyboard_send);
            }

            run(remaining_steps);
            return;
        }

        if(step.call)
        {
            step.call();
            run(remaining_steps);
            return;
        }

        dbg_assert(false, step);
    };

    run(steps);
};

/**
 * Wait until expected text is present on the VGA text screen.
 *
 * Returns immediately if the expected text is already present on screen
 * at the time this funtion is called.
 *
 * An optional timeout may be specified in `options.timeout_msec`, returns
 * false if the timeout expires before the expected text could be detected.
 *
 * Expected text (or texts, see below) must be of type string or RegExp,
 * strings are tested against the beginning of a screen line, regular
 * expressions against the full line but may use wildcards for partial
 * matching.
 *
 * Two methods of text detection are supported depending on the type of the
 * argument `expected`:
 *
 * 1. If `expected` is a string or RegExp then the given text string or
 *    regular expression may match any line on screen for this function
 *    to succeed.
 *
 * 2. If `expected` is an array of strings and/or RegExp objects then the
 *    list of expected lines must match exactly at "the bottom" of the
 *    screen. The "bottom" line is the first non-empty line starting from
 *    the screen's end.
 *    Expected lines should not contain any trailing whitespace and/or
 *    newline characters. Expecting an empty line is valid.
 *
 * Returns `true` on success and `false` when the timeout has expired.
 *
 * @param {string|RegExp|Array<string|RegExp>} expected
 * @param {{timeout_msec:(number|undefined)}=} options
 */
V86.prototype.wait_until_vga_screen_contains = async function(expected, options)
{
    if(this.graphics_adapter === "none")
    {
        throw new Error("wait_until_vga_screen_contains: there is no VGA text screen (graphics_adapter is \"none\")");
    }
    const match_multi = Array.isArray(expected);
    const timeout_msec = options?.timeout_msec || 0;
    const contains_expected = (screen_line, pattern) => pattern.test ? pattern.test(screen_line) : screen_line.startsWith(pattern);

    const screen_contains_expected = () =>
    {
        const screen = this.screen_adapter.get_text_screen();
        if(!match_multi)
        {
            return screen.some(screen_line => contains_expected(screen_line, expected));
        }

        const screen_lines = screen.map(screen_line => screen_line.trimRight());
        let screen_height = screen_lines.length;
        while(screen_height > 0 && screen_lines[screen_height - 1] === "")
        {
            screen_height--;
        }
        const screen_offset = screen_height - expected.length;
        if(screen_offset < 0)
        {
            return false;
        }
        for(let i = 0; i < expected.length; i++)
        {
            if(!contains_expected(screen_lines[screen_offset + i], expected[i]))
            {
                return false;
            }
        }
        return true;
    };

    // Read the whole screen every 100 ms, not only after an event that says it
    // changed: no event may follow the last change (the screen of a CPU in a
    // worker comes in batches of its own), and a mode set resizes the text
    // screen through transient sizes (80x256 while the VGA BIOS programs the
    // CRTC), so rows that changed earlier may no longer exist
    let succeeded = screen_contains_expected();
    const end = timeout_msec ? performance.now() + timeout_msec : 0;
    while(!succeeded && (!end || performance.now() < end))
    {
        await new Promise(resolve => setTimeout(resolve, 100));
        succeeded = screen_contains_expected();
    }
    return succeeded;
};

/**
 * Reads data from memory at specified offset.
 *
 * @param {number} offset
 * @param {number} length
 * @returns
 */
V86.prototype.read_memory = function(offset, length)
{
    if(this.worker_controller) return this.worker_controller.rpc("read_memory", [offset, length]);
    return this.v86.cpu.read_blob_physical(offset, length);
};

/**
 * Writes data to memory at specified offset.
 *
 * @param {Array.<number>|Uint8Array} blob
 * @param {number} offset
 */
V86.prototype.write_memory = function(blob, offset)
{
    if(this.worker_controller) return this.worker_controller.rpc("write_memory", [blob, offset]);
    this.v86.cpu.write_blob_physical(blob, offset);
};

/** Read a physical range with bounded allocations, including addresses above 4 GiB.
 * @param {number} offset
 * @param {number} length
 * @param {number=} chunk_size
 */
V86.prototype.read_memory_chunks = async function*(offset, length, chunk_size = 1024 * 1024)
{
    // (the machine's physical address space: 36 bits on the PC machines, 40 on virt)
    const limit = is_arm(this.cpu_type) ? 0x10000000000 : 0x1000000000;
    if(!Number.isSafeInteger(offset) || offset < 0 || offset >= limit ||
        !Number.isSafeInteger(length) || length < 0 || offset + length > limit ||
        !Number.isInteger(chunk_size) || chunk_size < 1 || chunk_size > 16 * 1024 * 1024)
        throw new RangeError("Invalid physical range or chunk size");
    for(let done = 0; done < length; done += chunk_size)
        yield await this.read_memory(offset + done, Math.min(chunk_size, length - done));
};

/*
 * @param {HTMLElement} element
 * @param {Function} [xterm_lib]
 */
V86.prototype.set_serial_container_xtermjs = function(element, xterm_lib = window["Terminal"])
{
    this.serial_adapter && this.serial_adapter.destroy && this.serial_adapter.destroy();
    this.serial_adapter = new SerialAdapterXtermJS(element, this.bus, xterm_lib);
    this.serial_adapter.show();
};

/*
 * @param {HTMLElement} element
 * @param {Function} [xterm_lib]
 */
V86.prototype.set_virtio_console_container_xtermjs = function(element, xterm_lib = window["Terminal"])
{
    this.virtio_console_adapter && this.virtio_console_adapter.destroy && this.virtio_console_adapter.destroy();
    this.virtio_console_adapter = new VirtioConsoleAdapterXtermJS(element, this.bus, xterm_lib);
    this.virtio_console_adapter.show();
};

V86.prototype.get_instruction_stats = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_instruction_stats");
    return print_stats.stats_to_string(this.v86.cpu);
};

/** Deprecated: the IR region tiers' diagnostics (docs/jit-unification-plan.md M11 deleted them). Returns false. */
V86.prototype.configure_ir_diagnostics = function(period)
{
    return false;
};
// eslint-disable-next-line no-self-assign -- Keep the public name through Closure compilation.
V86.prototype["configure_ir_diagnostics"] = V86.prototype.configure_ir_diagnostics;

/** Deprecated: the IR region tiers' compiler dumps (docs/jit-unification-plan.md M11 deleted them). Returns an empty list. */
V86.prototype.get_ir_dumps = function(clear = false)
{
    return [];
};
// eslint-disable-next-line no-self-assign -- Keep the public name through Closure compilation.
V86.prototype["get_ir_dumps"] = V86.prototype.get_ir_dumps;

/** Returns a copied runtime snapshot; in CPU Worker mode returns a Promise. */
V86.prototype.get_jit_info = function()
{
    if(this.worker_controller) return this.worker_controller.rpc("get_jit_info");
    return this.v86.cpu.get_jit_info();
};
// eslint-disable-next-line no-self-assign -- Keep the public name through Closure compilation.
V86.prototype["get_jit_info"] = V86.prototype.get_jit_info;

/**
 * @ignore
 * @constructor
 *
 * @param {string=} message
 */
function FileExistsError(message)
{
    this.message = message || "File already exists";
}
FileExistsError.prototype = Error.prototype;

/**
 * @ignore
 * @constructor
 *
 * @param {string=} message
 */
function FileNotFoundError(message)
{
    this.message = message || "File not found";
}
FileNotFoundError.prototype = Error.prototype;

/* global module, self */

// The optional graphics bundle uses these across the compilation boundary.
/* eslint-disable no-self-assign -- Quoted names export methods across Closure ADVANCED. */
V86.prototype["add_listener"] = V86.prototype.add_listener;
V86.prototype["remove_listener"] = V86.prototype.remove_listener;
V86.prototype["write_memory"] = V86.prototype.write_memory;
V86.prototype["read_memory_chunks"] = V86.prototype.read_memory_chunks;
V86.prototype["save_state_stream"] = V86.prototype.save_state_stream;
V86.prototype["export_disk_image"] = V86.prototype.export_disk_image;
V86.prototype["disk_image_info"] = V86.prototype.disk_image_info;
V86["import_ova"] = V86.import_ova;
V86.prototype["restore_state_stream"] = V86.prototype.restore_state_stream;
V86.prototype["vsock_connect"] = V86.prototype.vsock_connect;
/* eslint-enable no-self-assign */

if(typeof module !== "undefined" && typeof module.exports !== "undefined")
{
    module.exports["V86"] = V86;
}
else if(typeof window !== "undefined")
{
    window["V86"] = V86;
}
else if(typeof importScripts === "function")
{
    // web worker
    self["V86"] = V86;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/browser/state_stream_transport.js                                                    0000644 0000000 0000000 00000006526 00000000000 017314  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { STATE_STREAM_CHUNK_SIZE, state_stream_source } from "../state.js";

// Exactly one request may be in flight. No RAM, whole snapshot, or unbounded
// queue is cloned across the CPU Worker boundary.
export function state_stream_client(port)
{
    let pending = null, sequence = 0;
    port.onmessage = event => {
        const message = event.data;
        if(!pending || message["id"] !== pending.id) return;
        const current = pending;
        pending = null;
        if(message["error"]) current.reject(new Error(message["error"]));
        else current.resolve(message["bytes"]);
    };
    port.onmessageerror = () => {
        if(pending) { pending.reject(new Error("Snapshot message could not be decoded")); pending = null; }
    };
    const request = (message, transfer) => new Promise((resolve, reject) => {
        if(pending) { reject(new Error("Concurrent snapshot chunk request")); return; }
        const id = ++sequence;
        pending = { id, resolve, reject };
        try { port.postMessage({ "id": id, ...message }, transfer); }
        catch(error) { pending = null; reject(error); }
    });
    return {
        "write": bytes => request({ "kind": "write", "bytes": bytes }, [bytes.buffer]),
        "read": (offset, length) => request({ "kind": "read", "offset": offset, "length": length }, []),
        "close": () => {
            if(pending) pending.reject(new Error("Snapshot stream closed"));
            pending = null;
            port.close();
        },
    };
}

export function state_stream_server(port, kind, value)
{
    const source = kind === "restore" ? state_stream_source(value) : null;
    let busy = false, closed = false;
    port.onmessage = async event => {
        const message = event.data, id = message["id"];
        try
        {
            if(busy || closed) throw new Error("Concurrent or closed snapshot stream");
            busy = true;
            if(kind === "save")
            {
                const bytes = message["bytes"];
                if(message["kind"] !== "write" || !(bytes instanceof Uint8Array) || bytes.length > STATE_STREAM_CHUNK_SIZE)
                    throw new Error("Invalid snapshot write request");
                await value(bytes);
                if(!closed) port.postMessage({ "id": id });
            }
            else
            {
                const offset = message["offset"], length = message["length"];
                if(message["kind"] !== "read" || !Number.isSafeInteger(offset) || offset < 0 ||
                    !Number.isInteger(length) || length < 0 || length > STATE_STREAM_CHUNK_SIZE || offset + length > source["size"])
                    throw new Error("Invalid snapshot read request");
                const result = await source["read"](offset, length);
                if(!(result instanceof Uint8Array) || result.length !== length) throw new Error("Short snapshot read");
                // User-owned views must not be detached by transport.
                const bytes = result.slice();
                if(!closed) port.postMessage({ "id": id, "bytes": bytes }, [bytes.buffer]);
            }
        }
        catch(error)
        {
            if(!closed) port.postMessage({ "id": id, "error": String(error?.message || error) });
        }
        finally { busy = false; }
    };
    return { "size": source?.["size"] || 0, "close": () => { closed = true; port.close(); } };
}
                                                                                                                                                                          source/v64/src/browser/vm_options.js                                                                0000644 0000000 0000000 00000063614 00000000000 014703  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A page's V86 options (docs/vm-manager-plan.md, U0): the settings of a
// profile and of the old page's form, normalized as the old page always did
// it, and the options new V86() gets for them. The VM manager (index.html,
// an ES module outside Closure) and the debug page (debug.html,
// src/browser/main.js) both import this module, so it uses neither Closure's
// defines nor the emulator's internals (the plan's G5); the library reads
// some options by their quoted names, and they stay quoted here as they were
// in main.js.

import { CPU_TYPES, MACHINE_TYPES, MAX_VRAM_SIZE, is_arm } from "../machine_options.js";

export const DEFAULT_NETWORKING_PROXIES = ["wss://relay.widgetry.org/", "ws://localhost:8080/"];
export const DEFAULT_MEMORY_SIZE = 128;
// Guest RAM up to 2048 MB lives in the WebAssembly heap (just under 2 GiB:
// wasm32). The rest is extended RAM at 4 GiB and above, host-backed and usable
// by 64-bit guests only (docs/x86-64.md); the 36-bit physical address space
// ends at 64 GiB.
export const MAX_HEAP_MEMORY_SIZE = 2048;
/** The arm64 core's RAM in MB: below 2 GiB with the display adapter's 128 MiB of device memory */
export const ARM64_MAX_MEMORY_SIZE = 1792;
/** The arm64 virt machine's command line when none is given: Alpine's ISO (its initramfs finds the ISO on virtio-blk) */
export const ARM64_DEFAULT_CMDLINE = "console=ttyAMA0 console=tty0 modules=loop,squashfs,sd-mod,usb-storage";
/** The same without a display: the last console, where init writes and the login comes, is the serial one */
export const ARM64_SERIAL_CMDLINE = "console=ttyAMA0 modules=loop,squashfs,sd-mod,usb-storage";
export const MAX_MEMORY_SIZE = MAX_HEAP_MEMORY_SIZE + 60 * 1024;
export const DEFAULT_CPU_CORES = 1;
export const DEFAULT_CPU_TYPE = CPU_TYPES[0];
export const DEFAULT_MACHINE_TYPE = MACHINE_TYPES[0];
export const DEFAULT_VGA_MEMORY_SIZE = 8;
export const DEFAULT_GRAPHICS_ADAPTER = "bochs_vga";
export const DEFAULT_BOOT_ORDER = 0;
export const DEFAULT_MTU = 1500;
export const DEFAULT_NIC_TYPE = "ne2k";
/** The sound card (audio_device) of the PC machines */
export const DEFAULT_AUDIO_DEVICE = "sb16";

/** The largest empty hard disk in MB (an ArrayBuffer) */
export const MAX_ARRAY_BUFFER_SIZE_MB = 2000;

/**
 * The Q35 machine's own optional devices, as the page has them: the HPET and
 * the SMBus controller, as a real Q35 board and QEMU's Q35 have them; no root
 * ports, which only serve devices placed behind them (the API's hot plug)
 */
export const Q35_PAGE_DEVICES = { hpet: true, smbus: true, pcie_root_ports: 0 };

/**
 * The old page's form as index.html has it before anyone changes it (the
 * fields' values as strings, the checkboxes' states): what a start from the
 * address (?profile=, ?hda.url=) reads besides the address
 */
export const DEFAULT_FORM = {
    relay_url: DEFAULT_NETWORKING_PROXIES[0],
    disable_audio: false,
    /** the chosen files: bios, vga_bios, fda, fdb, cdrom, hda, hdb, multiboot, bzimage, initrd */
    files: {},
    /** empty disks: fda and fdb in bytes, hda and hdb in MB */
    empty_sizes: {},
    /** the hard disks' URLs ("hda", "hdb": read by the disk's name, so quoted) */
    urls: {},
    /** the hard disks' disk_option ("hda", "hdb") */
    disk_options: {},
    memory_size: String(DEFAULT_MEMORY_SIZE),
    vga_memory_size: String(DEFAULT_VGA_MEMORY_SIZE),
    graphics_adapter: DEFAULT_GRAPHICS_ADAPTER,
    boot_order: String(DEFAULT_BOOT_ORDER),
    cpu_cores: String(DEFAULT_CPU_CORES),
    parallel: true,
    cpu_type: DEFAULT_CPU_TYPE,
    machine_type: DEFAULT_MACHINE_TYPE,
    acpi: false,
    net_device_type: DEFAULT_NIC_TYPE,
    mtu: String(DEFAULT_MTU),
    modem: "none",
    audio_device: DEFAULT_AUDIO_DEVICE,
};

/**
 * @param {number} x
 * @return {number}
 */
function round_up_to_next_power_of_2(x)
{
    return x <= 1 ? 1 : 1 << 32 - Math.clz32(x - 1);
}

/**
 * A chunk size of ?chunk_size= (a power of two from 512 bytes to 4 MiB; 256 KiB without it)
 * @param {number} chunk_size
 * @return {number}
 */
export function clamp_chunk_size(chunk_size)
{
    if(chunk_size >= 0)
    {
        chunk_size = Math.min(4 * 1024 * 1024, Math.max(512, chunk_size));
        return round_up_to_next_power_of_2(chunk_size);
    }
    return 256 * 1024;
}

/**
 * A Video Memory size in MB that can be configured: vram_size is a power of
 * two, at most MAX_VRAM_SIZE
 * @param {number} size
 * @return {number}
 */
export function clamp_vram_size(size)
{
    return round_up_to_next_power_of_2(Math.min(Math.max(1, size), MAX_VRAM_SIZE >> 20));
}

/**
 * A guest RAM size in MB that can be configured: extended RAM comes in 2 MB pages
 * @param {number} total
 * @return {number}
 */
export function clamp_memory_size(total)
{
    total = Math.min(Math.max(16, total), MAX_MEMORY_SIZE);
    if(total > MAX_HEAP_MEMORY_SIZE)
    {
        total = MAX_HEAP_MEMORY_SIZE + Math.ceil((total - MAX_HEAP_MEMORY_SIZE) / 2) * 2;
    }
    return total;
}

/**
 * `total` MB of guest RAM: the WebAssembly heap first, then extended RAM
 * @param {Object} settings
 * @param {number} total
 */
export function set_memory_size(settings, total)
{
    const MB = 1024 * 1024;
    settings.memory_size = Math.min(total, MAX_HEAP_MEMORY_SIZE) * MB;
    settings.extended_memory_size = Math.max(0, total - MAX_HEAP_MEMORY_SIZE) * MB;
}

/**
 * A profile's settings (debug.html's kvm-unit-tests: name, memory_size, multiboot, ...)
 * @param {!Object} profile
 * @param {!Object} settings
 */
export function profile_settings(profile, settings)
{
    settings.initial_state = profile.state;
    settings.filesystem = profile.filesystem;
    settings.fda = profile.fda;
    settings.fdb = profile.fdb;
    settings.cdrom = profile.cdrom;
    settings.hda = profile.hda;
    settings.hdb = profile.hdb;
    settings.multiboot = profile.multiboot;
    settings.bzimage = profile.bzimage;
    settings.initrd = profile.initrd;
    settings.cmdline = profile.cmdline;
    settings.bzimage_initrd_from_filesystem = profile.bzimage_initrd_from_filesystem;
    settings.mac_address_translation = profile.mac_address_translation;
    settings.cpuid_level = profile.cpuid_level;
    settings.acpi = profile.acpi;
    settings.memory_size = profile.memory_size;
    settings.graphics_adapter = profile.graphics_adapter;
    settings.vram_size = profile.vram_size;
    settings.boot_order = profile.boot_order;
    settings.net_device_type = profile.net_device_type;
    settings.audio_device = profile.audio_device;
    settings.modem = profile.modem;
}

/**
 * The form's settings (DEFAULT_FORM's fields) on top of the profile's and the
 * address's, and the settings made consistent: the field's default keeps a
 * profile's or the address's choice, a value the user chose wins. Some
 * settings cannot be overridden when a state image is used.
 * @param {!Object} settings
 * @param {!Object} form
 * @param {!Map<string, string>} new_query_args the address of the start, for push_state
 * @param {{location_args: !URLSearchParams, origin: string, debug: boolean}} page the page's address
 *     and origin (in the message about read write), its debug builds of the firmware
 * @return {{error: (string|undefined), title: (string|undefined), updates: !Object}} updates: the form's
 *     fields the start changed, by their ids
 */
export function apply_form(settings, form, new_query_args, page)
{
    /** @type {!Object} */
    const updates = {};
    let title;

    if(!settings.relay_url)
    {
        settings.relay_url = form.relay_url;
        if(!DEFAULT_NETWORKING_PROXIES.includes(settings.relay_url)) new_query_args.set("relay_url", settings.relay_url);
    }
    if(settings.relay_url.startsWith("fetch:"))
    {
        settings.cors_proxy = settings.relay_url.slice(6);
        settings.relay_url = "fetch";
    }
    settings.disable_audio = form.disable_audio || settings.disable_audio;
    if(settings.disable_audio) new_query_args.set("mute", "1");

    // some settings cannot be overridden when a state image is used
    if(!settings.initial_state)
    {
        const files = form.files;
        const empty_sizes = form.empty_sizes;
        const bios = files.bios;
        if(bios)
        {
            settings.bios = { buffer: bios };
        }
        const vga_bios = files.vga_bios;
        if(vga_bios)
        {
            settings.vga_bios = { buffer: vga_bios };
        }
        const fda = files.fda;
        if(fda)
        {
            settings.fda = { buffer: fda };
        }
        const fda_empty_size = empty_sizes.fda;
        if(fda_empty_size)
        {
            settings.fda = { buffer: new ArrayBuffer(fda_empty_size) };
        }
        const fdb = files.fdb;
        if(fdb)
        {
            settings.fdb = { buffer: fdb };
        }
        const fdb_empty_size = empty_sizes.fdb;
        if(fdb_empty_size)
        {
            settings.fdb = { buffer: new ArrayBuffer(fdb_empty_size) };
        }
        const cdrom = files.cdrom;
        if(cdrom)
        {
            settings.cdrom = { buffer: cdrom };
        }
        const hda = files.hda;
        if(hda)
        {
            settings.hda = { buffer: hda };
        }
        const hda_empty_size = empty_sizes.hda;
        if(hda_empty_size)
        {
            const size = Math.max(1, Math.min(MAX_ARRAY_BUFFER_SIZE_MB, hda_empty_size)) * 1024 * 1024;
            settings.hda = { buffer: new ArrayBuffer(size) };
            new_query_args.set("hda.empty", String(size));
        }
        const hdb = files.hdb;
        if(hdb)
        {
            settings.hdb = { buffer: hdb };
        }
        const hdb_empty_size = empty_sizes.hdb;
        if(hdb_empty_size)
        {
            const size = Math.max(1, Math.min(MAX_ARRAY_BUFFER_SIZE_MB, hdb_empty_size)) * 1024 * 1024;
            settings.hdb = { buffer: new ArrayBuffer(size) };
            new_query_args.set("hdb.empty", String(size));
        }
        // (or an image's URL; read write: the guest's changes written back to
        // it, which needs a disk service's URL, docs/disk-persistence-plan.md:
        // a file chosen above can only be read)
        const disk_from_url = name =>
        {
            const url = form.urls[name]?.trim();
            if(!url) return undefined;
            const disk = { url, async: true };
            new_query_args.set(name + ".url", url);
            if(form.disk_options[name] === "read_write")
            {
                disk.disk_option = "read_write";
                new_query_args.set(name + ".disk_option", "read_write");
            }
            return disk;
        };
        const hda_url = disk_from_url("hda");
        if(hda_url) settings.hda = hda_url;
        const hdb_url = disk_from_url("hdb");
        if(hdb_url) settings.hdb = hdb_url;
        for(const [name, label, disk] of [["hda", "Hard disk image", settings.hda], ["hdb", "Second hard disk image", settings.hdb]])
        {
            if(form.disk_options[name] === "read_write" && !(disk && disk.url))
            {
                return {
                    error: label + ": read write needs the image's URL from a disk service (e.g. http://127.0.0.1:8471/disk.img, " +
                        "started by make run for images/, or node tools/disk-service.mjs --dir <directory> --origin " + page.origin +
                        "). A file chosen on this computer can only be read, so its changes stay in memory: choose read only for it.",
                    title: undefined,
                    updates,
                };
            }
        }
        const multiboot = files.multiboot;
        if(multiboot)
        {
            settings.multiboot = { buffer: multiboot };
        }
        const bzimage = files.bzimage;
        if(bzimage)
        {
            settings.bzimage = { buffer: bzimage };
        }
        const initrd = files.initrd;
        if(initrd)
        {
            settings.initrd = { buffer: initrd };
        }

        title = multiboot?.name || hda?.name || cdrom?.name || hdb?.name || fda?.name || bios?.name;

        const MB = 1024 * 1024;

        const memory_size = clamp_memory_size(parseInt(form.memory_size, 10) || DEFAULT_MEMORY_SIZE);
        updates["memory_size"] = String(memory_size);
        if(!settings.memory_size || memory_size !== DEFAULT_MEMORY_SIZE)
        {
            set_memory_size(settings, memory_size);
        }
        if(memory_size !== DEFAULT_MEMORY_SIZE) new_query_args.set("m", String(memory_size));

        const vram_mb = clamp_vram_size(parseInt(form.vga_memory_size, 10) || DEFAULT_VGA_MEMORY_SIZE);
        updates["vga_memory_size"] = String(vram_mb);
        if(!settings.vram_size || vram_mb !== DEFAULT_VGA_MEMORY_SIZE)
        {
            settings.vram_size = vram_mb * MB;
        }
        if(vram_mb !== DEFAULT_VGA_MEMORY_SIZE) new_query_args.set("vram", String(vram_mb));

        // (like the sizes above: the field's default keeps a profile's or ?graphics_adapter='s choice)
        const graphics_adapter = form.graphics_adapter || DEFAULT_GRAPHICS_ADAPTER;
        if(!settings.graphics_adapter || graphics_adapter !== DEFAULT_GRAPHICS_ADAPTER)
        {
            settings.graphics_adapter = graphics_adapter;
        }
        if(settings.graphics_adapter !== DEFAULT_GRAPHICS_ADAPTER) new_query_args.set("graphics_adapter", settings.graphics_adapter);
        // (?displays=N: virtio_gpu's displays, kept from the address)
        const displays = parseInt(page.location_args.get("displays"), 10);
        if(displays > 1)
        {
            settings.displays = Math.min(4, displays);
            new_query_args.set("displays", String(settings.displays));
        }

        const boot_order = parseInt(form.boot_order, 16) || DEFAULT_BOOT_ORDER;
        if(!settings.boot_order || boot_order !== DEFAULT_BOOT_ORDER)
        {
            settings.boot_order = boot_order;
        }
        if(settings.boot_order !== DEFAULT_BOOT_ORDER) new_query_args.set("boot_order", settings.boot_order.toString(16));

        const cpu_cores = parseInt(form.cpu_cores, 10) || DEFAULT_CPU_CORES;
        if(!settings.cpu_cores)
        {
            settings.cpu_cores = cpu_cores;
        }
        if(settings.cpu_cores !== DEFAULT_CPU_CORES) new_query_args.set("cores", String(settings.cpu_cores));
        // with more than one core: cores in host threads where the page allows
        // it (src/parallel), else they take turns on one thread
        if(settings.parallel === undefined)
        {
            settings.parallel = form.parallel;
        }
        if(settings.cpu_cores > 1 && !settings.parallel) new_query_args.set("parallel", "0");

        if(settings.cpu_type === undefined)
        {
            settings.cpu_type = form.cpu_type || DEFAULT_CPU_TYPE;
        }
        // the 64-bit CPUs reach extended RAM: x86_64 above the Wasm heap's
        // RAM, arm64 above ARM64_MAX_MEMORY_SIZE MB (its RAM and a display
        // adapter's device memory are less than 2 GiB of the heap), at 4 GiB
        // (docs/aarch64.md)
        if(settings.cpu_type === "arm64")
        {
            const total = (settings.memory_size + (settings.extended_memory_size || 0)) / MB;
            if(total > ARM64_MAX_MEMORY_SIZE)
            {
                settings.memory_size = ARM64_MAX_MEMORY_SIZE * MB;
                settings.extended_memory_size = Math.ceil((total - ARM64_MAX_MEMORY_SIZE) / 2) * 2 * MB;
            }
        }
        else if(settings.extended_memory_size && settings.cpu_type !== "x86_64")
        {
            console.log("More than " + MAX_HEAP_MEMORY_SIZE + " MB of memory: selecting the x86_64 CPU");
            settings.cpu_type = "x86_64";
            updates["cpu_type"] = "x86_64";
        }
        if(settings.cpu_type !== DEFAULT_CPU_TYPE) new_query_args.set("cpu_type", settings.cpu_type);

        // (the instruction sets come with the CPU type, docs/x86-64.md: x86
        // up to SSE3, x86_64 all of them; the library's cpu_features option
        // is for tests and debugging, the page has none, and an old link's
        // cpu_features is dropped)

        if(settings.machine_type === undefined)
        {
            settings.machine_type = form.machine_type || DEFAULT_MACHINE_TYPE;
        }
        // the arm64 CPU runs on the virt machine, the x86 CPUs on the PC
        // machines (src/machine_options.js)
        const arm = settings.cpu_type === "arm64" || settings.cpu_type === "arm32";
        if(arm !== (settings.machine_type === "virt" || settings.machine_type === "ranchu"))
        {
            settings.machine_type = arm ? "virt" : DEFAULT_MACHINE_TYPE;
            updates["machine_type"] = settings.machine_type;
        }
        if(settings.machine_type !== DEFAULT_MACHINE_TYPE) new_query_args.set("machine_type", settings.machine_type);
        if(settings.machine_type === "q35")
        {
            // Q35's own devices are not on the form: the page's machine has
            // Q35_PAGE_DEVICES (?hpet=, ?smbus= and ?root_ports= change them)
            if(settings.hpet === undefined) settings.hpet = Q35_PAGE_DEVICES.hpet;
            if(settings.smbus === undefined) settings.smbus = Q35_PAGE_DEVICES.smbus;
            if(settings.pcie_root_ports === undefined) settings.pcie_root_ports = Q35_PAGE_DEVICES.pcie_root_ports;
            if(settings.hpet !== Q35_PAGE_DEVICES.hpet) new_query_args.set("hpet", settings.hpet ? "1" : "0");
            if(settings.smbus !== Q35_PAGE_DEVICES.smbus) new_query_args.set("smbus", settings.smbus ? "1" : "0");
            if(settings.pcie_root_ports !== Q35_PAGE_DEVICES.pcie_root_ports) new_query_args.set("root_ports", String(settings.pcie_root_ports));
        }

        // multiple cores are described to the guest through ACPI (MADT);
        // Q35 always has ACPI (virt describes itself with a device tree)
        if(is_arm(settings.cpu_type))
        {
            settings.acpi = false;
        }
        else if((settings.cpu_cores > 1 || settings.machine_type === "q35") && !settings.acpi)
        {
            settings.acpi = true;
            updates["acpi"] = true;
        }
        if(settings.acpi === undefined)
        {
            settings.acpi = form.acpi;
        }
        if(settings.acpi) new_query_args.set("acpi", "1");

        const BIOSPATH = "bios/";

        if(is_arm(settings.cpu_type))
        {
            // (virt: no PC firmware, ACPI, VGA or NE2000)
            settings.acpi = false;
            if(settings.graphics_adapter !== "virtio_gpu") settings.graphics_adapter = "none";
        }
        else if(!settings.bios)
        {
            settings.bios = { url: BIOSPATH + (page.debug ? "seabios-debug.bin" : "seabios.bin") };
        }
        if(!settings.vga_bios && !is_arm(settings.cpu_type))
        {
            settings.vga_bios = { url: BIOSPATH + (page.debug ? "vgabios-debug.bin" : "vgabios.bin") };
        }
        if(settings.use_bochs_bios && !is_arm(settings.cpu_type))
        {
            settings.bios = { url: BIOSPATH + "bochs-bios.bin" };
            settings.vga_bios = { url: BIOSPATH + "bochs-vgabios.bin" };
        }

        const nic_type = form.net_device_type || DEFAULT_NIC_TYPE;
        if(!settings.net_device_type || nic_type !== DEFAULT_NIC_TYPE)
        {
            settings.net_device_type = nic_type;
        }
        if(settings.net_device_type !== DEFAULT_NIC_TYPE) new_query_args.set("net_device_type", settings.net_device_type);

        const audio_device = form.audio_device || DEFAULT_AUDIO_DEVICE;
        if(!settings.audio_device || audio_device !== DEFAULT_AUDIO_DEVICE)
        {
            settings.audio_device = audio_device;
        }
        if(settings.audio_device !== DEFAULT_AUDIO_DEVICE) new_query_args.set("audio_device", settings.audio_device);

        const mtu = parseInt(form.mtu, 10) || DEFAULT_MTU;
        if(!settings.mtu || mtu !== DEFAULT_MTU)
        {
            settings.mtu = mtu;
        }
        if(settings.mtu !== DEFAULT_MTU) new_query_args.set("mtu", settings.mtu.toString());

        const modem = parseInt(form.modem, 10);
        if(!Number.isNaN(modem) && modem >= 0 && modem < 4)
        {
            settings.modem = {uart: modem};
            new_query_args.set("modem", modem.toString());
        }
    }

    return { error: undefined, title, updates };
}

/**
 * What virtio_gpu is pinned to (graphics_adapter_test, the device's own
 * name for it): its displays, and its level when the settings ask for one
 * (virtio_gpu_level: "venus", Vulkan through the page's renderer)
 * @param {!Object} settings
 * @return {(Object|undefined)}
 */
function virtio_gpu_test(settings)
{
    if(settings.graphics_adapter !== "virtio_gpu") return undefined;
    const test = {};
    if(settings.displays > 1) test["scanouts"] = settings.displays;
    if(settings.virtio_gpu_level) test["level"] = settings.virtio_gpu_level;
    return Object.keys(test).length ? test : undefined;
}

/**
 * The options of new V86() for the settings
 * @param {!Object} settings
 * @param {{cpu_worker: boolean, debug: boolean, query_append: string, graphics_proxy: (Object|boolean), screen_container: *}} env
 *     the page: the CPU in a Worker, the debug builds, the files' ?version, the graphics proxy's
 *     option, the screen's element
 * @return {!Object}
 */
export function settings_to_options(settings, env)
{
    const query_append = env.query_append;
    const debug = env.debug;
    return {
        "cpu_worker": env.cpu_worker,
        "cpu_worker_url": "build/cpu-worker.js" + query_append,
        "ir_tier0": settings["ir_tier0"],
        // (the core of the CPU type: arm64's is a separate build, docs/aarch64.md)
        wasm_path: "build/" + (is_arm(settings.cpu_type) ? (debug ? "v86-arm64-debug.wasm" : "v86-arm64.wasm") :
            debug ? "v86-debug.wasm" : "v86.wasm") + query_append,
        // more than one core: each in a host thread (v86-parallel.wasm) where the
        // page is cross-origin isolated and the host has the threads; otherwise
        // the build above with the cores taking turns (see the runtime infos)
        "parallel": settings.cpu_cores > 1 && settings.parallel ? "auto" : false,
        "parallel_wasm_path": "build/" + (is_arm(settings.cpu_type) ? "v86-arm64-parallel.wasm" : "v86-parallel.wasm") + query_append,
        // (the source tree's module entry, unless the bundled CPU worker starts them)
        "vcpu_worker_url": debug && !env.cpu_worker ? undefined : "build/vcpu-worker.js" + query_append,
        "graphics_proxy": env.graphics_proxy,
        screen: {
            container: env.screen_container,
        },
        net_device: {
            type: is_arm(settings.cpu_type) ? "virtio" : settings.net_device_type || DEFAULT_NIC_TYPE,
            relay_url: settings.relay_url,
            cors_proxy: settings.cors_proxy,
            mtu: settings.mtu
        },
        modem: is_arm(settings.cpu_type) ? undefined : settings.modem,
        autostart: true,

        memory_size: settings.memory_size,
        extended_memory_size: settings.extended_memory_size || undefined,
        "graphics_adapter": settings.graphics_adapter || DEFAULT_GRAPHICS_ADAPTER,
        "vram_size": settings.vram_size,
        "graphics_adapter_test": virtio_gpu_test(settings),
        boot_order: settings.boot_order,

        // the arm64 virt machine (docs/virt.md): the page's kernel and
        // initrd, the CD-ROM image and the disks as virtio-blk disks (the
        // image read-only), virtio-rng, the keyboard, tablet and touch screen
        // with a display; the PC's firmware, floppies and IDE otherwise
        ...(is_arm(settings.cpu_type) ? {
            kernel: settings.bzimage,
            initrd: settings.initrd,
            virtio_disks: [settings.cdrom && Object.assign({}, settings.cdrom, { readonly: true }), settings.hda, settings.hdb].filter(Boolean),
            virtio_rng: true,
            virtio_input: settings.graphics_adapter === "virtio_gpu" ? ["keyboard", "tablet", "multitouch"] : undefined,
            cmdline: settings.cmdline || (settings.graphics_adapter === "virtio_gpu" ? ARM64_DEFAULT_CMDLINE : ARM64_SERIAL_CMDLINE),
            // (the A64 page tier: the library's default is off until its F gate;
            // quoted, as the library reads it, or Closure renames it)
            "jit_switches": settings.disable_jit ? undefined : { "a64_page": 1 },
        } : {
            bios: settings.bios,
            vga_bios: settings.vga_bios,
            fda: settings.fda,
            fdb: settings.fdb,
            hda: settings.hda,
            hdb: settings.hdb,
            cdrom: settings.cdrom,
            multiboot: settings.multiboot,
            bzimage: settings.bzimage,
            initrd: settings.initrd,
            cmdline: settings.cmdline,
            bzimage_initrd_from_filesystem: settings.bzimage_initrd_from_filesystem,
        }),
        acpi: !is_arm(settings.cpu_type) && (settings.acpi || settings.cpu_cores > 1 || settings.machine_type === "q35"),
        // (the CPU model: the cpu_type's default when not chosen; generic-arm64-compat32 runs 32-bit programs too)
        "cpu_profile": settings.cpu_profile || undefined,
        cpu_cores: settings.cpu_cores,
        "cpu_type": settings.cpu_type,
        machine_type: settings.machine_type,
        pcie_root_ports: settings.machine_type === "q35" ? settings.pcie_root_ports : undefined,
        hpet: settings.machine_type === "q35" ? settings.hpet : undefined,
        smbus: settings.machine_type === "q35" ? settings.smbus : undefined,
        // without it, more than one core runs in the interpreter
        experimental_smp_jit: settings.cpu_cores > 1 && !settings.disable_jit,
        disable_jit: settings.disable_jit,
        "x87_fast_math": is_arm(settings.cpu_type) ? undefined : settings["x87_fast_math"],
        "x87_jit_cache": is_arm(settings.cpu_type) ? undefined : settings["x87_jit_cache"],
        initial_state: settings.initial_state,
        filesystem: settings.filesystem || {},
        disable_speaker: settings.disable_audio,
        // (the library's default is the SB16; the virt machine has virtio_sound)
        audio_device: is_arm(settings.cpu_type) || !settings.audio_device || settings.audio_device === DEFAULT_AUDIO_DEVICE ?
            undefined : settings.audio_device,
        mac_address_translation: settings.mac_address_translation,
        cpuid_level: settings.cpuid_level,
    };
}
                                                                                                                    source/v64/src/browser/wasm_paths.js                                                                0000644 0000000 0000000 00000000326 00000000000 014643  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Preserve URL query/fragment and custom core names when selecting a portable build.
export function wasm_fallback_path(primary)
{
    return primary.replace(/(?:-fallback)?\.wasm(?=[?#]|$)/, "-fallback.wasm");
}
                                                                                                                                                                                                                                                                                                          source/v64/src/browser/wisp_network.js                                                              0000644 0000000 0000000 00000020245 00000000000 015232  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_NET } from "../const.js";
import { dbg_log } from "../log.js";

import {
    create_eth_encoder_buf,
    handle_fake_networking,
    TCPConnection,
    TCP_STATE_SYN_RECEIVED,
} from "./fake_network.js";

// For Types Only
import { BusConnector } from "../bus.js";

/**
 * @constructor
 *
 * @param {String} wisp_url
 * @param {BusConnector} bus
 * @param {*=} config
 */
export function WispNetworkAdapter(wisp_url, bus, config)
{
    this.register_ws(wisp_url);
    this.last_stream = 1;
    this.connections = {0: {congestion: 0}};
    this.congested_buffer = [];

    config = config || {};
    this.bus = bus;
    this.id = config.id || 0;
    this.router_mac = new Uint8Array((config.router_mac || "52:54:0:1:2:3").split(":").map(function(x) { return parseInt(x, 16); }));
    this.router_ip = new Uint8Array((config.router_ip || "192.168.86.1").split(".").map(function(x) { return parseInt(x, 10); }));
    this.vm_ip = new Uint8Array((config.vm_ip || "192.168.86.100").split(".").map(function(x) { return parseInt(x, 10); }));
    this.masquerade = config.masquerade === undefined || !!config.masquerade;
    this.vm_mac = new Uint8Array(6);
    this.dns_method = config.dns_method || "doh";
    this.doh_server = config.doh_server;
    this.tcp_conn = {};
    this.mtu = config.mtu;
    this.eth_encoder_buf = create_eth_encoder_buf(this.mtu);

    this.bus.register("net" + this.id + "-mac", function(mac) {
        this.vm_mac = new Uint8Array(mac.split(":").map(function(x) { return parseInt(x, 16); }));
    }, this);
    this.bus.register("net" + this.id + "-send", function(data) {
        this.send(data);
    }, this);
}

WispNetworkAdapter.prototype.register_ws = function(wisp_url) {
    this.wispws = new WebSocket(wisp_url.replace("wisp://", "ws://").replace("wisps://", "wss://"));
    this.wispws.binaryType = "arraybuffer";
    this.wispws.onmessage = (event) => {
        this.process_incoming_wisp_frame(new Uint8Array(event.data));
    };
    this.wispws.onclose = () => {
        setTimeout(() => {
            this.register_ws(wisp_url);
        }, 10000); // wait 10s before reconnecting
    };
};

WispNetworkAdapter.prototype.send_packet = function(data, type, stream_id) {
    if(this.connections[stream_id]) {
        if(this.connections[stream_id].congestion > 0) {
            if(type === "DATA") {
                this.connections[stream_id].congestion--;
            }
            this.wispws.send(data);
        } else {
            this.connections[stream_id].congested = true;
            this.congested_buffer.push({data: data, type: type});
        }
    }
};

WispNetworkAdapter.prototype.process_incoming_wisp_frame = function(frame) {
    const view = new DataView(frame.buffer);
    const stream_id = view.getUint32(1, true);
    switch(frame[0]) {
        case 1: // CONNECT
            // The server should never send this actually
            dbg_log("Server sent client-only packet CONNECT", LOG_NET);
            break;
        case 2: // DATA
            if(this.connections[stream_id])
                this.connections[stream_id].data_callback(frame.slice(5));
            else
                throw new Error("Got a DATA packet but stream not registered. ID: " + stream_id);
            break;
        case 3: // CONTINUE
            if(this.connections[stream_id]) {
                this.connections[stream_id].congestion = view.getUint32(5, true);
            }

            if(this.connections[stream_id].congested) {
                const buffer = this.congested_buffer.slice(0);
                this.congested_buffer.length = 0;
                this.connections[stream_id].congested = false;
                for(const packet of buffer) {
                    this.send_packet(packet.data, packet.type, stream_id);
                }
            }
            break;
        case 4: // CLOSE
            if(this.connections[stream_id])
                this.connections[stream_id].close_callback(view.getUint8(5));
            delete this.connections[stream_id];
            break;
        case 5: // PROTOEXT
            dbg_log("got a wisp V2 upgrade request, ignoring", LOG_NET);
            // Not responding, this is wisp v1 client not wisp v2;
            break;
        default:
            dbg_log("Wisp server returned unknown packet: " + frame[0], LOG_NET);
    }
};


// FrameObj will be the following
// FrameObj.stream_id (number)
//
// FrameObj.type -- CONNECT
//      FrameObj.hostname (string)
//      FrameObj.port (number)
//      FrameObj.data_callback (function (Uint8Array))
//      FrameObj.close_callback (function (number)) OPTIONAL
//
//
// FrameObj.type -- DATA
//      FrameObj.data (Uint8Array)
//
// FrameObj.type -- CLOSE
//      FrameObj.reason (number)
//
//

WispNetworkAdapter.prototype.send_wisp_frame = function(frame_obj) {
    let full_packet;
    let view;
    switch(frame_obj.type) {
        case "CONNECT":
            const hostname_buffer = new TextEncoder().encode(frame_obj.hostname);
            full_packet = new Uint8Array(5 + 1 + 2 + hostname_buffer.length);
            view = new DataView(full_packet.buffer);
            view.setUint8(0, 0x01);                       // TYPE
            view.setUint32(1, frame_obj.stream_id, true); // Stream ID
            view.setUint8(5, 0x01);                       // TCP
            view.setUint16(6, frame_obj.port, true);      // PORT
            full_packet.set(hostname_buffer, 8);          // hostname

            // Setting callbacks
            this.connections[frame_obj.stream_id] = {
                data_callback: frame_obj.data_callback,
                close_callback: frame_obj.close_callback,
                congestion: this.connections[0].congestion
            };
            break;
        case "DATA":
            full_packet = new Uint8Array(5 + frame_obj.data.length);
            view = new DataView(full_packet.buffer);
            view.setUint8(0, 0x02);                       // TYPE
            view.setUint32(1, frame_obj.stream_id, true); // Stream ID
            full_packet.set(frame_obj.data, 5);           // Actual data
            break;
        case "CLOSE":
            full_packet = new Uint8Array(5 + 1);
            view = new DataView(full_packet.buffer);
            view.setUint8(0, 0x04);                       // TYPE
            view.setUint32(1, frame_obj.stream_id, true); // Stream ID
            view.setUint8(5, frame_obj.reason);           // Packet size
            break;
        default:
            dbg_log("Client tried to send unknown packet: " + frame_obj.type, LOG_NET);

    }
    this.send_packet(full_packet, frame_obj.type, frame_obj.stream_id);
};

WispNetworkAdapter.prototype.destroy = function()
{
    if(this.wispws) {
        this.wispws.onmessage = null;
        this.wispws.onclose = null;
        this.wispws.close();
        this.wispws = null;
    }
};

/**
 * @param {TCPConnection} conn
 * @param {Uint8Array} packet
 */
WispNetworkAdapter.prototype.on_tcp_connection = function(conn, packet)
{
    conn.stream_id = this.last_stream++;

    conn.on("data", data => {
        if(data.length !== 0) {
            this.send_wisp_frame({
                type: "DATA",
                stream_id: conn.stream_id,
                data: data
            });
        }
    });

    conn.on_close = () => {
        this.send_wisp_frame({
            type: "CLOSE",
            stream_id: conn.stream_id,
            reason: 0x02    // 0x02: Voluntary stream closure
        });
    };

    // WISP doesn't implement shutdown, use close as workaround
    conn.on_shutdown = conn.on_close;

    this.send_wisp_frame({
        type: "CONNECT",
        stream_id: conn.stream_id,
        hostname: packet.ipv4.dest.join("."),
        port: conn.sport,
        data_callback: (data) => {
            conn.write(data);
        },
        close_callback: (data) => {
            conn.close();
        }
    });

    conn.accept();
    return true;
};

/**
 * @param {Uint8Array} data
 */
WispNetworkAdapter.prototype.send = function(data)
{
    // TODO: forward UDP traffic to WISP server once this WISP client supports UDP
    handle_fake_networking(data, this);
};

/**
 * @param {Uint8Array} data
 */
WispNetworkAdapter.prototype.receive = function(data)
{
    this.bus.send("net" + this.id + "-receive", new Uint8Array(data));
};
                                                                                                                                                                                                                                                                                                                                                           source/v64/src/browser/worker_bus.js                                                                0000644 0000000 0000000 00000002215 00000000000 014656  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "../log.js";

/** @constructor */
export var Connector = function(pair)
{
    this.listeners = {};
    this.pair = pair;

    pair.addEventListener("message", function(e)
    {
        var data = e.data;
        var listeners = this.listeners[data[0]];

        for(var i = 0; i < listeners.length; i++)
        {
            var listener = listeners[i];
            listener.fn.call(listener.this_value, data[1]);
        }
    }.bind(this), false);

};

Connector.prototype.register = function(name, fn, this_value)
{
    var listeners = this.listeners[name];

    if(listeners === undefined)
    {
        listeners = this.listeners[name] = [];
    }

    listeners.push({
        fn: fn,
        this_value: this_value,
    });
};

/**
 * Send ("emit") a message
 *
 * @param {string} name
 * @param {*=} value
 * @param {*=} transfer_list
 */
Connector.prototype.send = function(name, value, transfer_list)
{
    dbg_assert(arguments.length >= 1);

    if(!this.pair)
    {
        return;
    }

    this.pair.postMessage([name, value], transfer_list);
};


export var init = function(worker)
{
    return new Connector(worker);
};
                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/buffer.js                                                                            0000644 0000000 0000000 00000077207 00000000000 012277  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { CPU } from "./cpu.js";
import { load_file, get_file_size, response_header } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

/**
 * A read the buffer could not complete (src/block_backend.js: by the disk's
 * disk_error policy); `kind` as the errors of src/image/source.js
 * @param {string} message
 * @param {string} kind
 * @param {boolean} retryable
 * @return {!Error}
 */
function read_error(message, kind, retryable)
{
    const error = new Error(message);
    /** @type {?} */ (error).kind = kind;
    error["retryable"] = retryable;
    return error;
}

/**
 * A disk read over HTTP sees one version of its file
 * (docs/disk-persistence-plan.md "一致读取"): the first response's ETag (or,
 * without one, its Last-Modified) is kept, every later response of the same
 * file must have the same; otherwise the file changed while it was read
 * (written by another session, or the site published a new image), and the
 * read fails rather than mixing sectors of two versions. The requests are
 * not changed (no If-Match: a header of its own would need a CORS preflight
 * that a static host may refuse). Without either header (or with headers a
 * cross-origin server does not expose: ETag is not readable across origins
 * unless exposed, Last-Modified always is) nothing is checked.
 * @param {!Map<string, {etag: ?string, last_modified: ?string}>} versions by file name
 * @param {string} filename
 * @param {*} http the response's XMLHttpRequest (none in Node)
 * @return {!Error|undefined}
 */
export function check_response_version(versions, filename, http)
{
    if(!http || typeof http.getResponseHeader !== "function") return undefined;
    const etag = response_header(http, "ETag");
    const last_modified = response_header(http, "Last-Modified");
    const known = versions.get(filename);
    if(!known)
    {
        if(etag || last_modified) versions.set(filename, { etag, last_modified });
        return undefined;
    }
    const changed = known.etag && etag ? known.etag !== etag :
        !known.etag && known.last_modified && last_modified ? known.last_modified !== last_modified : false;
    if(!changed) return undefined;
    return read_error(filename + " changed while it was read (" +
        (known.etag ? "ETag " + known.etag + ", now " + etag : "Last-Modified " + known.last_modified + ", now " + last_modified) +
        "): its sectors are not mixed with the other version's", "changed", false);
}


// The smallest size the emulated hardware can emit
const BLOCK_SIZE = 256;

// The lazily loaded disks keep the blocks written to them in chunks of this
// many (16 MiB), not in an ArrayBuffer each: gigabytes written are then a few
// hundred buffers in a snapshot, not millions (a V7 manifest lists every buffer
// and is limited to 16 MiB), a snapshot references them instead of copying
// them, and the garbage collector has a few hundred objects to visit, not
// millions
const WRITE_CHUNK_BLOCKS = 0x10000;

const ASYNC_SAFE = false;

/**
 * Synchronous access to ArrayBuffer
 * @constructor
 */
export function SyncBuffer(buffer)
{
    dbg_assert(buffer instanceof ArrayBuffer);

    this.buffer = buffer;
    this.byteLength = buffer.byteLength;
    this.onload = undefined;
    this.onprogress = undefined;
}

SyncBuffer.prototype.load = function()
{
    this.onload && this.onload({ buffer: this.buffer });
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 * @param {number} start
 * @param {number} len
 * @param {function(!Uint8Array)} fn
 */
SyncBuffer.prototype.get = function(start, len, fn)
{
    dbg_assert(start + len <= this.byteLength);
    fn(new Uint8Array(this.buffer, start, len));
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 * @param {number} start
 * @param {number} len
 * @param {function(!Uint8Array)} fn
 */
SyncBuffer.prototype.get_and_cache = function(start, len, fn)
{
    this.get(start, len, fn);
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 * @param {number} start
 * @param {number} len
 * @return {Uint8Array|undefined}
 */
SyncBuffer.prototype.get_from_cache = function(start, len)
{
    dbg_assert(start + len <= this.byteLength);
    return new Uint8Array(this.buffer, start, len);
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 * @param {number} start
 * @param {!Uint8Array} slice
 * @param {function()} fn
 */
SyncBuffer.prototype.set = function(start, slice, fn)
{
    dbg_assert(start + slice.byteLength <= this.byteLength);

    new Uint8Array(this.buffer, start, slice.byteLength).set(slice);
    fn();
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 * @param {function(!ArrayBuffer)} fn
 */
SyncBuffer.prototype.get_buffer = function(fn)
{
    fn(this.buffer);
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 */
SyncBuffer.prototype.get_state = function()
{
    const state = [];
    state[0] = this.byteLength;
    state[1] = new Uint8Array(this.buffer);
    return state;
};

/**
 * @this {SyncBuffer|SyncFileBuffer}
 */
SyncBuffer.prototype.set_state = function(state)
{
    this.byteLength = state[0];
    this.buffer = state[1].slice().buffer;
};

/**
 * Asynchronous access to ArrayBuffer, loading blocks lazily as needed,
 * using the `Range: bytes=...` header
 *
 * @constructor
 * @param {string} filename Name of the file to download
 * @param {number|undefined} size
 * @param {number|undefined} fixed_chunk_size
 */
function AsyncXHRBuffer(filename, size, fixed_chunk_size)
{
    this.filename = filename;

    this.byteLength = size;

    // blocks kept from reads (a Uint8Array each)
    this.block_cache = new Map();
    // blocks written: block number -> slot, its place in write_chunks
    this.written_blocks = new Map();
    this.write_chunks = [];

    this.fixed_chunk_size = fixed_chunk_size;
    this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing)

    /** @type {!Map<string, {etag: ?string, last_modified: ?string}>} (check_response_version) */
    this.versions = new Map();

    this.onload = undefined;
    this.onprogress = undefined;
}

AsyncXHRBuffer.prototype.load = async function()
{
    if(this.byteLength !== undefined)
    {
        this.onload && this.onload(Object.create(null));
        return;
    }

    const size = await get_file_size(this.filename);
    this.byteLength = size;
    this.onload && this.onload(Object.create(null));
};

/**
 * @param {number} offset
 * @param {number} len
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 */
AsyncXHRBuffer.prototype.get_from_cache = function(offset, len)
{
    var number_of_blocks = len / BLOCK_SIZE;
    var block_index = offset / BLOCK_SIZE;

    for(var i = 0; i < number_of_blocks; i++)
    {
        if(!this.written_blocks.has(block_index + i) && !this.block_cache.has(block_index + i))
        {
            return;
        }
    }

    if(number_of_blocks === 1)
    {
        return this.cached_block(block_index);
    }
    else
    {
        var result = new Uint8Array(len);
        for(var i = 0; i < number_of_blocks; i++)
        {
            result.set(/** @type {!Uint8Array} */ (this.cached_block(block_index + i)), i * BLOCK_SIZE);
        }
        return result;
    }
};

/**
 * The data of a block that was written or kept from a read
 *
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 * @param {number} index
 * @return {!Uint8Array|undefined}
 */
AsyncXHRBuffer.prototype.cached_block = function(index)
{
    const slot = this.written_blocks.get(index);
    if(slot === undefined)
    {
        return this.block_cache.get(index);
    }
    const offset = slot % WRITE_CHUNK_BLOCKS * BLOCK_SIZE;
    return this.write_chunks[Math.floor(slot / WRITE_CHUNK_BLOCKS)].subarray(offset, offset + BLOCK_SIZE);
};

/**
 * @param {number} offset
 * @param {number} len
 * @param {function((!Uint8Array|undefined), !Error=)} fn the data, or (undefined, the error)
 */
AsyncXHRBuffer.prototype.get = function(offset, len, fn, options)
{
    dbg_assert(offset + len <= this.byteLength);
    dbg_assert(offset % BLOCK_SIZE === 0);
    dbg_assert(len % BLOCK_SIZE === 0);
    dbg_assert(len);

    var block = this.get_from_cache(offset, len);
    if(block)
    {
        if(ASYNC_SAFE)
        {
            setTimeout(fn.bind(this, block), 0);
        }
        else
        {
            fn(block);
        }
        return;
    }

    var requested_start = offset;
    var requested_length = len;
    if(this.fixed_chunk_size)
    {
        requested_start = offset - (offset % this.fixed_chunk_size);
        requested_length = Math.ceil((offset - requested_start + len) / this.fixed_chunk_size) * this.fixed_chunk_size;
    }

    load_file(this.filename, {
        done: function done(buffer, http)
        {
            const changed = check_response_version(this.versions, this.filename, http);
            if(changed)
            {
                fn(undefined, changed);
                return;
            }
            var block = new Uint8Array(buffer);
            // (a chunk at the end of the file may be shorter than asked for)
            if(block.length < Math.min(requested_length, this.byteLength - requested_start))
            {
                fn(undefined, read_error(this.filename + ": " + block.length + " bytes at " + requested_start +
                    " instead of " + requested_length, "io", true));
                return;
            }
            this.handle_read(requested_start, requested_length, block);
            if(requested_start === offset && requested_length === len)
            {
                fn(block);
            }
            else
            {
                fn(block.subarray(offset - requested_start, offset - requested_start + len));
            }
        }.bind(this),
        error: status => fn(undefined, read_error(this.filename + ": the read of " + requested_length + " bytes at " + requested_start +
            " failed (" + (typeof status === "number" ? "HTTP status " + status : status) + ")", "io", true)),
        range: { start: requested_start, length: requested_length },
        signal: options?.signal,
    });
};

/**
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 * @param {number} offset
 * @param {number} len
 * @param {function((!Uint8Array|undefined), !Error=)} fn the data, or (undefined, the error)
 */
AsyncXHRBuffer.prototype.get_and_cache = function(offset, len, fn, options)
{
    this.get(offset, len, function(block, error)
    {
        if(!block)
        {
            fn(block, error);
            return;
        }
        const start_block = offset / BLOCK_SIZE;
        const block_count = len / BLOCK_SIZE;

        for(let i = 0; i < block_count; i++)
        {
            if(!this.written_blocks.has(start_block + i) && !this.block_cache.has(start_block + i))
            {
                this.block_cache.set(start_block + i, block.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE));
            }
        }

        fn(block);
    }.bind(this), options);
};

/**
 * Relies on this.byteLength, this.written_blocks and this.write_chunks
 *
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 *
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function()} fn
 */
AsyncXHRBuffer.prototype.set = function(start, data, fn)
{
    var len = data.length;
    dbg_assert(start + data.byteLength <= this.byteLength);
    dbg_assert(start % BLOCK_SIZE === 0);
    dbg_assert(len % BLOCK_SIZE === 0);
    dbg_assert(len);

    var start_block = start / BLOCK_SIZE;
    var block_count = len / BLOCK_SIZE;

    for(var i = 0; i < block_count; i++)
    {
        this.write_block(start_block + i, data.subarray(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE));
    }

    fn();
};

/**
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 * @param {number} index
 * @param {!Uint8Array} data
 */
AsyncXHRBuffer.prototype.write_block = function(index, data)
{
    dbg_assert(data.length === BLOCK_SIZE);
    let slot = this.written_blocks.get(index);
    if(slot === undefined)
    {
        // (no block leaves written_blocks: the next slot is its size)
        slot = this.written_blocks.size;
        if(slot % WRITE_CHUNK_BLOCKS === 0)
        {
            this.write_chunks.push(new Uint8Array(WRITE_CHUNK_BLOCKS * BLOCK_SIZE));
        }
        this.written_blocks.set(index, slot);
        this.block_cache.delete(index);
    }
    this.write_chunks[Math.floor(slot / WRITE_CHUNK_BLOCKS)].set(data, slot % WRITE_CHUNK_BLOCKS * BLOCK_SIZE);
};

/**
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 * @param {number} offset
 * @param {number} len
 * @param {!Uint8Array} block
 */
AsyncXHRBuffer.prototype.handle_read = function(offset, len, block)
{
    // Used by AsyncXHRBuffer, AsyncXHRPartfileBuffer and AsyncFileBuffer
    // Overwrites blocks from the original source that have been written since

    var start_block = offset / BLOCK_SIZE;
    var block_count = len / BLOCK_SIZE;

    for(var i = 0; i < block_count; i++)
    {
        const cached_block = this.cached_block(start_block + i);

        if(cached_block)
        {
            block.set(cached_block, i * BLOCK_SIZE);
        }
        else if(this.cache_reads)
        {
            this.block_cache.set(start_block + i, block.slice(i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE));
        }
    }
};

AsyncXHRBuffer.prototype.get_buffer = function(fn)
{
    // We must download all parts, unlikely a good idea for big files
    fn();
};

///**
// * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
// */
//AsyncXHRBuffer.prototype.get_block_cache = function()
//{
//    var count = Object.keys(this.block_cache).length;

//    var buffer = new Uint8Array(count * BLOCK_SIZE);
//    var indices = [];

//    var i = 0;
//    for(var index of Object.keys(this.block_cache))
//    {
//        var block = this.block_cache.get(index);
//        dbg_assert(block.length === BLOCK_SIZE);
//        index = +index;
//        indices.push(index);
//        buffer.set(
//            block,
//            i * BLOCK_SIZE
//        );
//        i++;
//    }

//    return {
//        buffer,
//        indices,
//        block_size: BLOCK_SIZE,
//    };
//};

/**
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 */
AsyncXHRBuffer.prototype.get_state = function()
{
    // The written blocks: their numbers in the order of their data in the
    // chunks. The snapshot references the chunks, it does not copy them: the
    // machine is stopped until it is saved.
    const count = this.written_blocks.size;
    const indices = new Float64Array(count);
    for(const [index, slot] of this.written_blocks)
    {
        indices[slot] = index;
    }

    const state = [];
    state[0] = null; // [[block number, data], ...] in snapshots from before
    state[1] = indices;
    state[2] = this.write_chunks.map((chunk, i) =>
        chunk.subarray(0, Math.min(WRITE_CHUNK_BLOCKS, count - i * WRITE_CHUNK_BLOCKS) * BLOCK_SIZE));
    return state;
};

/**
 * @this {AsyncXHRBuffer|AsyncXHRPartfileBuffer|AsyncFileBuffer}
 */
AsyncXHRBuffer.prototype.set_state = function(state)
{
    this.block_cache.clear();
    this.written_blocks.clear();
    this.write_chunks = [];

    if(state[0])
    {
        // a snapshot from before: [[block number, data], ...]
        for(const [index, block] of state[0])
        {
            dbg_assert(isFinite(index));
            this.write_block(index, block);
        }
        return;
    }

    const indices = state[1];
    const chunks = state[2];
    const block_count = this.byteLength / BLOCK_SIZE;
    let total = 0;
    for(const chunk of chunks)
    {
        if(!(chunk instanceof Uint8Array) || chunk.length % BLOCK_SIZE) throw new Error("Invalid disk snapshot: chunk");
        total += chunk.length / BLOCK_SIZE;
    }
    if(!(indices instanceof Float64Array) || indices.length !== total ||
        indices.some(index => !Number.isInteger(index) || index < 0 || index >= block_count))
    {
        throw new Error("Invalid disk snapshot: block numbers");
    }

    let i = 0;
    for(const chunk of chunks)
    {
        const count = chunk.length / BLOCK_SIZE;
        if(count === WRITE_CHUNK_BLOCKS && i % WRITE_CHUNK_BLOCKS === 0)
        {
            // a full chunk becomes this disk's as it is (a restore makes new
            // buffers for the snapshot's)
            this.write_chunks.push(chunk);
            for(const end = i + count; i < end; i++)
            {
                this.written_blocks.set(indices[i], i);
            }
            if(this.written_blocks.size !== i) throw new Error("Invalid disk snapshot: a block saved twice");
        }
        else
        {
            for(let offset = 0; offset < chunk.length; offset += BLOCK_SIZE)
            {
                this.write_block(indices[i++], chunk.subarray(offset, offset + BLOCK_SIZE));
            }
        }
    }
};

/**
 * Asynchronous access to ArrayBuffer, loading blocks lazily as needed,
 * downloading files named filename-%d-%d.ext (where the %d are start and end offset).
 * Or, if partfile_alt_format is set, filename-%08d.ext (where %d is the part number, compatible with gnu split).
 *
 * @constructor
 * @param {string} filename Name of the file to download
 * @param {number|undefined} size
 * @param {number|undefined} fixed_chunk_size
 * @param {boolean|undefined} partfile_alt_format
 */
export function AsyncXHRPartfileBuffer(filename, size, fixed_chunk_size, partfile_alt_format, zstd_decompress)
{
    const parts = filename.match(/\.[^\.]+(\.zst)?$/);

    this.extension = parts ? parts[0] : "";
    this.basename = filename.substring(0, filename.length - this.extension.length);

    this.is_zstd = this.extension.endsWith(".zst");

    if(!this.basename.endsWith("/"))
    {
        this.basename += "-";
    }

    this.block_cache = new Map();
    this.written_blocks = new Map();
    this.write_chunks = [];

    this.byteLength = size;
    this.fixed_chunk_size = fixed_chunk_size;
    this.partfile_alt_format = !!partfile_alt_format;
    this.zstd_decompress = zstd_decompress;

    this.cache_reads = !!fixed_chunk_size; // TODO: could also be useful in other cases (needs testing)

    /** @type {!Map<string, {etag: ?string, last_modified: ?string}>} each part's (check_response_version) */
    this.versions = new Map();

    this.onload = undefined;
    this.onprogress = undefined;
}

AsyncXHRPartfileBuffer.prototype.load = function()
{
    if(this.byteLength !== undefined)
    {
        this.onload && this.onload(Object.create(null));
        return;
    }
    dbg_assert(false);
    this.onload && this.onload(Object.create(null));
};

/**
 * @param {number} offset
 * @param {number} len
 * @param {function((!Uint8Array|undefined), !Error=)} fn the data, or (undefined, the error)
 */
AsyncXHRPartfileBuffer.prototype.get = function(offset, len, fn, options)
{
    dbg_assert(offset + len <= this.byteLength);
    dbg_assert(offset % BLOCK_SIZE === 0);
    dbg_assert(len % BLOCK_SIZE === 0);
    dbg_assert(len);

    const block = this.get_from_cache(offset, len);

    if(block)
    {
        if(ASYNC_SAFE)
        {
            setTimeout(fn.bind(this, block), 0);
        }
        else
        {
            fn(block);
        }
        return;
    }

    if(this.fixed_chunk_size)
    {
        const start_index = Math.floor(offset / this.fixed_chunk_size);
        const m_offset = offset - start_index * this.fixed_chunk_size;
        dbg_assert(m_offset >= 0);
        const total_count = Math.ceil((m_offset + len) / this.fixed_chunk_size);
        const blocks = new Uint8Array(total_count * this.fixed_chunk_size);
        let finished = 0;
        // (one part failed: the read fails once)
        let failed = false;
        const fail = error => { if(!failed) { failed = true; fn(undefined, error); } };

        for(let i = 0; i < total_count; i++)
        {
            const offset = (start_index + i) * this.fixed_chunk_size;

            const part_filename =
                this.partfile_alt_format ?
                    // matches output of gnu split:
                    //   split -b 512 -a8 -d --additional-suffix .img w95.img w95-
                    this.basename + (start_index + i + "").padStart(8, "0") + this.extension
                :
                    this.basename + offset + "-" + (offset + this.fixed_chunk_size) + this.extension;

            // XXX: unnecessary allocation
            const block = this.get_from_cache(offset, this.fixed_chunk_size);

            if(block)
            {
                blocks.set(block, i * this.fixed_chunk_size);
                finished++;
                if(finished === total_count)
                {
                    fn(blocks.subarray(m_offset, m_offset + len));
                }
            }
            else
            {
                load_file(part_filename, {
                    done: async function done(buffer, http)
                    {
                        if(failed) return;
                        const changed = check_response_version(this.versions, part_filename, http);
                        if(changed)
                        {
                            fail(changed);
                            return;
                        }
                        let block = new Uint8Array(buffer);

                        if(this.is_zstd)
                        {
                            const decompressed = await this.zstd_decompress(this.fixed_chunk_size, block);
                            block = new Uint8Array(decompressed);
                        }

                        if(failed) return;
                        blocks.set(block, i * this.fixed_chunk_size);
                        this.handle_read((start_index + i) * this.fixed_chunk_size, this.fixed_chunk_size|0, block);

                        finished++;
                        if(finished === total_count)
                        {
                            fn(blocks.subarray(m_offset, m_offset + len));
                        }
                    }.bind(this),
                    error: status => fail(read_error(part_filename + ": the read failed (" +
                        (typeof status === "number" ? "HTTP status " + status : status) + ")", "io", true)),
                    signal: options?.signal,
                });
            }
        }
    }
    else
    {
        const part_filename = this.basename + offset + "-" + (offset + len) + this.extension;

        load_file(part_filename, {
            done: function done(buffer, http)
            {
                const changed = check_response_version(this.versions, part_filename, http);
                if(changed)
                {
                    fn(undefined, changed);
                    return;
                }
                if(buffer.byteLength !== len)
                {
                    fn(undefined, read_error(part_filename + ": " + buffer.byteLength + " bytes instead of " + len, "io", true));
                    return;
                }
                var block = new Uint8Array(buffer);
                this.handle_read(offset, len, block);
                fn(block);
            }.bind(this),
            error: status => fn(undefined, read_error(part_filename + ": the read failed (" +
                (typeof status === "number" ? "HTTP status " + status : status) + ")", "io", true)),
            signal: options?.signal,
        });
    }
};

AsyncXHRPartfileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache;
AsyncXHRPartfileBuffer.prototype.get_and_cache = AsyncXHRBuffer.prototype.get_and_cache;
AsyncXHRPartfileBuffer.prototype.cached_block = AsyncXHRBuffer.prototype.cached_block;
AsyncXHRPartfileBuffer.prototype.set = AsyncXHRBuffer.prototype.set;
AsyncXHRPartfileBuffer.prototype.write_block = AsyncXHRBuffer.prototype.write_block;
AsyncXHRPartfileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read;
//AsyncXHRPartfileBuffer.prototype.get_block_cache = AsyncXHRBuffer.prototype.get_block_cache;
AsyncXHRPartfileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state;
AsyncXHRPartfileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state;

/**
 * Synchronous access to File, loading blocks from the input type=file
 * The whole file is loaded into memory during initialisation
 *
 * @constructor
 */
export function SyncFileBuffer(file)
{
    this.file = file;
    this.byteLength = file.size;

    if(file.size > (1 << 30))
    {
        console.warn("SyncFileBuffer: Allocating buffer of " + (file.size >> 20) + " MB ...");
    }

    this.buffer = new ArrayBuffer(file.size);

    this.onload = undefined;
    this.onprogress = undefined;
}

SyncFileBuffer.prototype.load = function()
{
    this.load_next(0);
};

/**
 * @param {number} start
 */
SyncFileBuffer.prototype.load_next = function(start)
{
    const PART_SIZE = 4 << 20;

    var filereader = new FileReader();

    filereader.onload = function(e)
    {
        var buffer = new Uint8Array(e.target.result);
        new Uint8Array(this.buffer, start).set(buffer);
        this.load_next(start + PART_SIZE);
    }.bind(this);

    if(this.onprogress)
    {
        this.onprogress({
            loaded: start,
            total: this.byteLength,
            lengthComputable: true,
        });
    }

    if(start < this.byteLength)
    {
        var end = Math.min(start + PART_SIZE, this.byteLength);
        var slice = this.file.slice(start, end);
        filereader.readAsArrayBuffer(slice);
    }
    else
    {
        this.file = undefined;
        this.onload && this.onload({ buffer: this.buffer });
    }
};

SyncFileBuffer.prototype.get = SyncBuffer.prototype.get;
SyncFileBuffer.prototype.get_and_cache = SyncBuffer.prototype.get_and_cache;
SyncFileBuffer.prototype.get_from_cache = SyncBuffer.prototype.get_from_cache;
SyncFileBuffer.prototype.set = SyncBuffer.prototype.set;
SyncFileBuffer.prototype.get_buffer = SyncBuffer.prototype.get_buffer;
SyncFileBuffer.prototype.get_state = SyncBuffer.prototype.get_state;
SyncFileBuffer.prototype.set_state = SyncBuffer.prototype.set_state;

/**
 * Asynchronous access to File, loading blocks from the input type=file
 *
 * @constructor
 */
export function AsyncFileBuffer(file)
{
    this.file = file;
    this.byteLength = file.size;

    this.block_cache = new Map();
    this.written_blocks = new Map();
    this.write_chunks = [];

    this.onload = undefined;
    this.onprogress = undefined;
}

AsyncFileBuffer.prototype.load = function()
{
    this.onload && this.onload(Object.create(null));
};

/**
 * @param {number} offset
 * @param {number} len
 * @param {function((!Uint8Array|undefined), !Error=)} fn the data, or (undefined, the error)
 */
AsyncFileBuffer.prototype.get = function(offset, len, fn)
{
    dbg_assert(offset % BLOCK_SIZE === 0);
    dbg_assert(len % BLOCK_SIZE === 0);
    dbg_assert(len);

    var block = this.get_from_cache(offset, len);
    if(block)
    {
        fn(block);
        return;
    }

    // In a worker (the CPU worker), read synchronously, as from a buffer in
    // memory (about 0.5 ms a request). An asynchronous read completes only
    // once the CPU loop yields, a whole slice later: a guest that polls
    // for the data waits that long for each request (SeaBIOS's AHCI
    // driver, polling through SMM: the 2300 reads of Windows' boot loader
    // took minutes instead of seconds)
    if(typeof FileReaderSync !== "undefined")
    {
        try
        {
            block = new Uint8Array(new FileReaderSync().readAsArrayBuffer(this.file.slice(offset, offset + len)));
        }
        catch(e)
        {
            fn(undefined, read_error("the file " + this.file.name + " could not be read (" + e.name + ")", "io", true));
            return;
        }
        this.handle_read(offset, len, block);
        fn(block);
        return;
    }

    var fr = new FileReader();

    fr.onload = function(e)
    {
        var buffer = e.target.result;
        var block = new Uint8Array(buffer);

        this.handle_read(offset, len, block);
        fn(block);
    }.bind(this);
    // (the file changed or went away since it was picked: NotReadableError)
    fr.onerror = function()
    {
        fn(undefined, read_error("the file " + this.file.name + " could not be read (" + (fr.error && fr.error.name) + ")", "io", true));
    }.bind(this);

    fr.readAsArrayBuffer(this.file.slice(offset, offset + len));
};
AsyncFileBuffer.prototype.get_from_cache = AsyncXHRBuffer.prototype.get_from_cache;
AsyncFileBuffer.prototype.get_and_cache = AsyncXHRBuffer.prototype.get_and_cache;
AsyncFileBuffer.prototype.cached_block = AsyncXHRBuffer.prototype.cached_block;
AsyncFileBuffer.prototype.set = AsyncXHRBuffer.prototype.set;
AsyncFileBuffer.prototype.write_block = AsyncXHRBuffer.prototype.write_block;
AsyncFileBuffer.prototype.handle_read = AsyncXHRBuffer.prototype.handle_read;
AsyncFileBuffer.prototype.get_state = AsyncXHRBuffer.prototype.get_state;
AsyncFileBuffer.prototype.set_state = AsyncXHRBuffer.prototype.set_state;

AsyncFileBuffer.prototype.get_buffer = function(fn)
{
    // We must load all parts, unlikely a good idea for big files
    fn();
};

AsyncFileBuffer.prototype.get_as_file = function(name)
{
    var parts = [];
    // (blocks kept from reads are as in the file)
    var existing_blocks = Float64Array.from(this.written_blocks.keys()).sort();

    var current_offset = 0;

    for(var i = 0; i < existing_blocks.length;)
    {
        // a run of blocks that follow each other on the disk and in a chunk,
        // as a guest writing data in sequence leaves them: one part
        const block_index = existing_blocks[i];
        const slot = this.written_blocks.get(block_index);
        let count = 1;
        while(i + count < existing_blocks.length && existing_blocks[i + count] === block_index + count &&
            this.written_blocks.get(block_index + count) === slot + count && (slot + count) % WRITE_CHUNK_BLOCKS)
        {
            count++;
        }
        var start = block_index * BLOCK_SIZE;
        dbg_assert(start >= current_offset);

        if(start !== current_offset)
        {
            parts.push(this.file.slice(current_offset, start));
            current_offset = start;
        }

        const offset = slot % WRITE_CHUNK_BLOCKS * BLOCK_SIZE;
        parts.push(this.write_chunks[Math.floor(slot / WRITE_CHUNK_BLOCKS)].subarray(offset, offset + count * BLOCK_SIZE));
        current_offset += count * BLOCK_SIZE;
        i += count;
    }

    if(current_offset !== this.file.size)
    {
        parts.push(this.file.slice(current_offset));
    }

    var file = new File(parts, name);
    dbg_assert(file.size === this.file.size);

    return file;
};

export function buffer_from_object(obj, zstd_decompress_worker)
{
    // TODO: accept Uint8Array, ArrayBuffer, File, url rather than { url }

    if(obj.buffer instanceof ArrayBuffer)
    {
        return new SyncBuffer(obj.buffer);
    }
    else if(typeof File !== "undefined" && obj.buffer instanceof File)
    {
        // SyncFileBuffer:
        // - loads the whole disk image into memory, impossible for large files (more than 1GB)
        // - can later serve get/set operations fast and synchronously
        // - takes some time for first load, neglectable for small files (up to 100Mb)
        //
        // AsyncFileBuffer:
        // - loads slices of the file asynchronously as requested
        // - slower get/set

        // Heuristics: If file is larger than or equal to 256M, use AsyncFileBuffer
        let is_async = obj.async;
        if(is_async === undefined)
        {
            is_async = obj.buffer.size >= 256 * 1024 * 1024;
        }

        if(is_async)
        {
            return new AsyncFileBuffer(obj.buffer);
        }
        else
        {
            return new SyncFileBuffer(obj.buffer);
        }
    }
    else if(obj.url)
    {
        // Note: Only async for now

        if(obj.use_parts)
        {
            return new AsyncXHRPartfileBuffer(obj.url, obj.size, obj.fixed_chunk_size, false, zstd_decompress_worker);
        }
        else
        {
            return new AsyncXHRBuffer(obj.url, obj.size, obj.fixed_chunk_size);
        }
    }
    else
    {
        dbg_log("Ignored file: url=" + obj.url + " buffer=" + obj.buffer);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/bus.js                                                                               0000644 0000000 0000000 00000003540 00000000000 011604  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "./log.js";

export var Bus = {};

/** @constructor */
export function BusConnector()
{
    this.listeners = {};
    this.pair = undefined;
}

/**
 * @param {string} name
 * @param {function(?)} fn
 * @param {Object} this_value
 */
BusConnector.prototype.register = function(name, fn, this_value)
{
    var listeners = this.listeners[name];

    if(listeners === undefined)
    {
        listeners = this.listeners[name] = [];
    }

    listeners.push({
        fn: fn,
        this_value: this_value,
    });
};

/**
 * Unregister one message with the given name and callback
 *
 * @param {string} name
 * @param {function(?)} fn
 */
BusConnector.prototype.unregister = function(name, fn)
{
    var listeners = this.listeners[name];

    if(listeners === undefined)
    {
        return;
    }

    this.listeners[name] = listeners.filter(function(l)
    {
        return l.fn !== fn;
    });
};

/**
 * Send ("emit") a message
 *
 * @param {string} name
 * @param {*=} value
 * @param {*=} unused_transfer
 */
BusConnector.prototype.send = function(name, value, unused_transfer)
{
    if(!this.pair)
    {
        return;
    }

    var listeners = this.pair.listeners[name];

    if(listeners === undefined)
    {
        return;
    }

    for(var i = 0; i < listeners.length; i++)
    {
        var listener = listeners[i];
        listener.fn.call(listener.this_value, value);
    }
};

/**
 * Send a message, guaranteeing that it is received asynchronously
 *
 * @param {string} name
 * @param {Object=} value
 */
BusConnector.prototype.send_async = function(name, value)
{
    dbg_assert(arguments.length === 1 || arguments.length === 2);

    setTimeout(this.send.bind(this, name, value), 0);
};

Bus.create = function()
{
    var c0 = new BusConnector();
    var c1 = new BusConnector();

    c0.pair = c1;
    c1.pair = c0;

    return [c0, c1];
};
                                                                                                                                                                source/v64/src/cjs.js                                                                               0000644 0000000 0000000 00000000366 00000000000 011575  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /**
 * @define {boolean}
 * Overridden for production by closure compiler
 */
var DEBUG = true;

/**
 * Only the Closure bundles contain this file (src/parallel/machine.js picks
 * the bundled vCPU worker script by it)
 */
var V86_BUNDLE = true;
                                                                                                                                                                                                                                                                          source/v64/src/const.js                                                                             0000644 0000000 0000000 00000007202 00000000000 012140  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       export const
    LOG_ALL = -1,
    LOG_NONE = 0,

    LOG_OTHER =  0x0000001,
    LOG_CPU =    0x0000002,
    LOG_FPU =    0x0000004,
    LOG_MEM =    0x0000008,
    LOG_DMA =    0x0000010,
    LOG_IO =     0x0000020,
    LOG_PS2 =    0x0000040,
    LOG_PIC =    0x0000080,
    LOG_VGA =    0x0000100,
    LOG_PIT =    0x0000200,
    LOG_MOUSE =  0x0000400,
    LOG_PCI =    0x0000800,
    LOG_BIOS =   0x0001000,
    LOG_FLOPPY = 0x0002000,
    LOG_SERIAL = 0x0004000,
    LOG_DISK =   0x0008000,
    LOG_RTC =    0x0010000,
    // unused    0x0020000,
    LOG_ACPI =   0x0040000,
    LOG_APIC =   0x0080000,
    LOG_NET =    0x0100000,
    LOG_VIRTIO = 0x0200000,
    LOG_9P =     0x0400000,
    LOG_SB16 =   0x0800000,
    LOG_FETCH =  0x1000000,
    LOG_MODEM =  0x2000000;


/**
 * @type {Array<Array<string|number>>}
 */
export const LOG_NAMES = [
    [1, ""],
    [LOG_CPU, "CPU"],
    [LOG_DISK, "DISK"],
    [LOG_FPU, "FPU"],
    [LOG_MEM, "MEM"],
    [LOG_DMA, "DMA"],
    [LOG_IO, "IO"],
    [LOG_PS2, "PS2"],
    [LOG_PIC, "PIC"],
    [LOG_VGA, "VGA"],
    [LOG_PIT, "PIT"],
    [LOG_MOUSE, "MOUS"],
    [LOG_PCI, "PCI"],
    [LOG_BIOS, "BIOS"],
    [LOG_FLOPPY, "FLOP"],
    [LOG_SERIAL, "SERI"],
    [LOG_RTC, "RTC"],
    [LOG_ACPI, "ACPI"],
    [LOG_APIC, "APIC"],
    [LOG_NET, "NET"],
    [LOG_VIRTIO, "VIO"],
    [LOG_9P, "9P"],
    [LOG_SB16, "SB16"],
    [LOG_FETCH, "FETC"],
    [LOG_MODEM, "MODM"],
];

export const
    // flags register bitflags
    FLAG_CARRY = 1,
    FLAG_PARITY = 4,
    FLAG_ADJUST = 16,
    FLAG_ZERO = 64,
    FLAG_SIGN = 128,
    FLAG_TRAP = 256,
    FLAG_INTERRUPT = 512,
    FLAG_DIRECTION = 1024,
    FLAG_OVERFLOW = 2048,
    FLAG_IOPL = 1 << 12 | 1 << 13,
    FLAG_NT = 1 << 14,
    FLAG_RF = 1 << 16,
    FLAG_VM = 1 << 17,
    FLAG_AC = 1 << 18,
    FLAG_VIF = 1 << 19,
    FLAG_VIP = 1 << 20,
    FLAG_ID = 1 << 21,

    // default values of reserved flags bits
    FLAGS_DEFAULT = 1 << 1,

    REG_EAX = 0,
    REG_ECX = 1,
    REG_EDX = 2,
    REG_EBX = 3,
    REG_ESP = 4,
    REG_EBP = 5,
    REG_ESI = 6,
    REG_EDI = 7,

    REG_ES = 0,
    REG_CS = 1,
    REG_SS = 2,
    REG_DS = 3,
    REG_FS = 4,
    REG_GS = 5,

    REG_LDTR = 7; // local descriptor table register

export const
    // The minimum number of bytes that can be memory-mapped by one device.
    MMAP_BLOCK_BITS = 17,
    MMAP_BLOCK_SIZE = 1 << MMAP_BLOCK_BITS,
    MMAP_MAX = 0x100000000;

export const CR0_PG = 1 << 31;
export const CR4_PAE = 1 << 5;


// https://github.com/qemu/seabios/blob/14221cd86eadba82255fdc55ed174d401c7a0a04/src/fw/paravirt.c#L205-L219

export const FW_CFG_SIGNATURE = 0x00;
export const FW_CFG_ID = 0x01;
export const FW_CFG_RAM_SIZE = 0x03;
export const FW_CFG_NB_CPUS = 0x05;
export const FW_CFG_BOOT_MENU = 0x0E;
export const FW_CFG_MAX_CPUS = 0x0F;
export const FW_CFG_NUMA = 0x0D;
export const FW_CFG_FILE_DIR = 0x19;

export const FW_CFG_CUSTOM_START = 0x8000;
// This value is specific to v86, choosen to hopefully not collide with other indexes
export const FW_CFG_FILE_START = 0xC000;
export const FW_CFG_SIGNATURE_QEMU = 0x554D4551;


// See same constant in jit.rs
export const WASM_TABLE_SIZE = 12000;

export const WASM_TABLE_OFFSET = 1024;

export const MIXER_CHANNEL_LEFT = 0;
export const MIXER_CHANNEL_RIGHT = 1;
export const MIXER_CHANNEL_BOTH = 2;
export const MIXER_SRC_MASTER = 0;
export const MIXER_SRC_PCSPEAKER = 1;
export const MIXER_SRC_DAC = 2;

/**
 * The largest single-buffer snapshot (save_state): its header holds the
 * length as an Int32, and browsers allocate no ArrayBuffer of 2 GiB (Chrome
 * fails from there). Larger machines are saved with save_state_stream.
 */
export const STATE_MAX_SINGLE_BUFFER = 0x7FFFFFFF;
                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/cpu.js                                                                               0000644 0000000 0000000 00000535461 00000000000 011616  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { check_disk_state, is_writeback_state, restore_disk_state } from "./disk_writeback.js";
import { drop_disk_holds } from "./block_backend.js";
import {
    LOG_CPU, LOG_BIOS,
    FW_CFG_SIGNATURE, FW_CFG_SIGNATURE_QEMU,
    WASM_TABLE_SIZE, WASM_TABLE_OFFSET, FW_CFG_ID,
    FW_CFG_RAM_SIZE, FW_CFG_NB_CPUS, FW_CFG_MAX_CPUS, FW_CFG_BOOT_MENU,
    FW_CFG_NUMA, FW_CFG_FILE_DIR, FW_CFG_FILE_START,
    FW_CFG_CUSTOM_START, FLAGS_DEFAULT,
    MMAP_BLOCK_BITS, MMAP_BLOCK_SIZE, MMAP_MAX,
    REG_ESP, REG_EBP, REG_ESI, REG_EAX, REG_EBX, REG_ECX, REG_EDX, REG_EDI,
    REG_CS, REG_DS, REG_ES, REG_FS, REG_GS, REG_SS, CR0_PG, CR4_PAE, REG_LDTR,
    FLAG_VM, FLAG_INTERRUPT, FLAG_CARRY, FLAG_ADJUST, FLAG_ZERO, FLAG_SIGN, FLAG_TRAP,
    FLAG_DIRECTION, FLAG_OVERFLOW, FLAG_PARITY, STATE_MAX_SINGLE_BUFFER,
} from "./const.js";
import { h, view, Bitmap } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";
import { v86 } from "./main.js";
import { MachineClock } from "./machine_clock.js";

import { ACPI, acpi_system_states_file } from "./acpi.js";
import { build_e820, build_smbios } from "./smbios.js";
import { PFlash } from "./pflash.js";
import { ACPI_LOADER_FILE, ACPI_RSDP_FILE, ACPI_TABLES_FILE, TPM_LOG_FILE, build_acpi_tables, locate_acpi_tables } from "./acpi_tables.js";
import { ACPI_PM_BASE_DEFAULT, MACHINE_LAYOUT_VERSION, Platform, check_platform, create_platform, pci_functions } from "./platform.js";
import { CORE_STATE_RANGES, INIT_PRESERVED, STATE_OFFSETS } from "./state_layout.js";
import { CPU_FEATURES, CPU_FEATURE_PRESETS } from "./cpu_features.js";
import { build_jit_defaults, set_jit_switches } from "./jit_switches.js";
import { ParallelMachine } from "./parallel/machine.js";
import { ExtendedStore } from "./extended_memory.js";
import { COMMAND_RELOAD, COMMAND_RESET } from "./parallel/control.js";
import { PIT } from "./pit.js";
import { DMA } from "./dma.js";
import { UART } from "./uart.js";
import { ParallelPort } from "./parallel.js";
import { IO } from "./io.js";
import { VirtioConsole } from "./virtio_console.js";
import { PCI } from "./pci.js";
import { Q35 } from "./q35.js";
import { PS2 } from "./ps2.js";
import { VMwareMouse } from "./vmware.js";
import { read_elf, elf_unsupported_reason } from "./elf.js";

import { FloppyController } from "./floppy.js";
import { IDEController } from "./ide.js";
import { AHCIController } from "./ahci.js";
import { PCIeRootPort } from "./pcie_root_port.js";
import { HPET } from "./hpet.js";
import { SMBus } from "./smbus.js";
import { VirtioNet } from "./virtio_net.js";
import { GraphicsAdapter, graphics_adapter_of_state, patch_vga_bios_ids } from "./graphics_adapter.js";
import { PluginDevice, AUDIO_PLUGINS, NET_PLUGINS, TPM_PLUGINS, USB_PLUGINS, plugin_of_state } from "./device_plugin.js";
import { STORE_SIZE as TPM_STORE_SIZE } from "./tpm/store.js";
import { SyncBuffer } from "./buffer.js";
import { DisplayHub } from "./display.js";
import { VirtioBalloon } from "./virtio_balloon.js";
import { create_virtio_devices, get_virtio_devices_state, resolve_virtio_devices_state, set_virtio_devices_state } from "./virtio_devices.js";
import { Virtio9p, Virtio9pHandler, Virtio9pProxy } from "../lib/9p.js";

import { load_kernel } from "./kernel.js";
import { check_machine_options } from "./machine_options.js";

import {
    RTC,
    CMOS_EQUIPMENT_INFO, CMOS_BIOS_SMP_COUNT,
    CMOS_MEM_HIGHMEM_HIGH, CMOS_MEM_HIGHMEM_MID, CMOS_MEM_HIGHMEM_LOW,
    CMOS_DISK_DATA, CMOS_BIOS_DISKTRANSFLAG, CMOS_FLOPPY_DRIVE_TYPE,
    BOOT_ORDER_CD_FIRST, CMOS_BIOS_BOOTFLAG1, CMOS_BIOS_BOOTFLAG2,
    CMOS_MEM_BASE_LOW, CMOS_MEM_BASE_HIGH,
    CMOS_MEM_OLD_EXT_LOW, CMOS_MEM_OLD_EXT_HIGH, CMOS_MEM_EXTMEM_LOW,
    CMOS_MEM_EXTMEM_HIGH, CMOS_MEM_EXTMEM2_LOW, CMOS_MEM_EXTMEM2_HIGH
} from "./rtc.js";


// For Types Only

import { BusConnector } from "./bus.js";

// Resources:
// https://pdos.csail.mit.edu/6.828/2006/readings/i386/toc.htm
// https://www-ssl.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html
// http://ref.x86asm.net/geek32.html


/** @constructor */
export function CPU(bus, wm, stop_idling)
{
    this.stop_idling = stop_idling;
    this.wm = wm;
    this.clock = new MachineClock({ now: v86.microtick });
    this.execution_epoch = 0;
    this.in_cpu = false;
    this.reset_pending = false;
    this.scheduler_quantum = 4096;
    this.scheduler_seed = 0;
    this.scheduler_round = 0;
    this.jit_backend = "ir";
    this.wasm_patch();
    this.create_jit_imports();

    const memory = this.wm.exports.memory;

    this.wasm_memory = memory;

    // Address of offset 0 of the state layout (src/state_layout.js): 0 in
    // v86.wasm; the state block of this instance in v86-parallel.wasm, where
    // each vCPU worker has its own (src/parallel/relocate.js)
    // (an i32: a vCPU's instance may lie above 2 GiB when guest RAM is large)
    const state_base = this.state_base = this.wm.exports["state_base"] ? this.wm.exports["state_base"]() >>> 0 : 0;

    /** @type {ParallelMachine} application processors in vCPU workers (start_parallel) */
    this.parallel = null;
    /** why the cores run cooperatively although parallel execution was requested ("" if not) */
    this.parallel_fallback = "";

    /** the CPU features (src/cpu_features.js) and whether cpu_features chose them (init) */
    this.cpu_features = 0;
    this.cpu_features_explicit = false;

    // extended RAM (configure_extended_memory)
    this.extended_pages = 0;
    this.extended_base = 0;
    /** @type {ExtendedStore} */
    this.extended_store = null;

    this.memory_size = view(Uint32Array, memory, state_base + STATE_OFFSETS.memory_size, 1);
    // RAM below 4 GiB; less than memory_size when high_memory_size is set
    this.low_memory_size = 0;

    this.mem8 = new Uint8Array(0);
    this.mem32s = new Int32Array(this.mem8.buffer);

    this.segment_is_null = view(Uint8Array, memory, state_base + STATE_OFFSETS.segment_is_null, 8);
    this.segment_offsets = view(Int32Array, memory, state_base + STATE_OFFSETS.segment_offsets, 8);
    this.segment_limits = view(Uint32Array, memory, state_base + STATE_OFFSETS.segment_limits, 8);
    this.segment_access_bytes = view(Uint8Array, memory, state_base + STATE_OFFSETS.segment_access_bytes, 8);

    /**
     * Wheter or not in protected mode
     */
    this.protected_mode = view(Int32Array, memory, state_base + STATE_OFFSETS.protected_mode, 1);

    this.idtr_size = view(Int32Array, memory, state_base + STATE_OFFSETS.idtr_size, 1);
    this.idtr_offset = view(Int32Array, memory, state_base + STATE_OFFSETS.idtr_offset, 1);

    /**
     * global descriptor table register
     */
    this.gdtr_size = view(Int32Array, memory, state_base + STATE_OFFSETS.gdtr_size, 1);
    this.gdtr_offset = view(Int32Array, memory, state_base + STATE_OFFSETS.gdtr_offset, 1);

    this.tss_size_32 = view(Int32Array, memory, state_base + STATE_OFFSETS.tss_size_32, 1);

    this.cr = view(Int32Array, memory, state_base + STATE_OFFSETS.cr, 8);

    // current privilege level
    this.cpl = view(Uint8Array, memory, state_base + STATE_OFFSETS.cpl, 1);

    // current operand/address size
    this.is_32 = view(Int32Array, memory, state_base + STATE_OFFSETS.is_32, 1);

    this.stack_size_32 = view(Int32Array, memory, state_base + STATE_OFFSETS.stack_size_32, 1);

    /**
     * Was the last instruction a hlt?
     */
    this.in_hlt = view(Uint8Array, memory, state_base + STATE_OFFSETS.in_hlt, 1);

    this.last_virt_eip = view(Int32Array, memory, state_base + STATE_OFFSETS.last_virt_eip, 1);
    this.eip_phys = view(Int32Array, memory, state_base + STATE_OFFSETS.eip_phys, 1);


    this.sysenter_cs = view(Int32Array, memory, state_base + STATE_OFFSETS.sysenter_cs, 1);

    this.sysenter_esp = view(Int32Array, memory, state_base + STATE_OFFSETS.sysenter_esp, 1);

    this.sysenter_eip = view(Int32Array, memory, state_base + STATE_OFFSETS.sysenter_eip, 1);

    this.prefixes = view(Int32Array, memory, state_base + STATE_OFFSETS.prefixes, 1);

    this.flags = view(Int32Array, memory, state_base + STATE_OFFSETS.flags, 1);

    /**
     * bitmap of flags which are not updated in the flags variable
     * changed by arithmetic instructions, so only relevant to arithmetic flags
     */
    this.flags_changed = view(Int32Array, memory, state_base + STATE_OFFSETS.flags_changed, 1);

    /**
     * enough infos about the last arithmetic operation to compute eflags
     */
    this.last_op_size = view(Int32Array, memory, state_base + STATE_OFFSETS.last_op_size, 1);
    this.last_op1 = view(Int32Array, memory, state_base + STATE_OFFSETS.last_op1, 1);
    this.last_result = view(Int32Array, memory, state_base + STATE_OFFSETS.last_result, 1);

    this.current_tsc = view(Uint32Array, memory, state_base + STATE_OFFSETS.current_tsc, 2); // 64 bit

    /** @type {!Object} */
    this.devices = {};

    /**
     * Device plugins' timers (src/device_plugin.js, add_timer): run with the
     * machine's other timers, each returns milliseconds until it needs to
     * run again
     * @type {!Array<function(number):number>}
     */
    this.device_timers = [];

    this.instruction_pointer = view(Int32Array, memory, state_base + STATE_OFFSETS.instruction_pointer, 1);
    this.previous_ip = view(Int32Array, memory, state_base + STATE_OFFSETS.previous_ip, 1);

    // configured by guest
    this.apic_enabled = view(Uint8Array, memory, state_base + STATE_OFFSETS.apic_enabled, 1);
    // configured when the emulator starts (changes bios initialisation)
    this.acpi_enabled = view(Uint8Array, memory, state_base + STATE_OFFSETS.acpi_enabled, 1);

    // managed in io.js
    /** @const */ this.memory_map_read8 = [];
    /** @const */ this.memory_map_write8 = [];
    /** @const */ this.memory_map_read32 = [];
    /** @const */ this.memory_map_write32 = [];

    /**
     * @const
     * @type {{main: ArrayBuffer, vga: ArrayBuffer}}
     */
    this.bios = {
        main: null,
        vga: null,
    };

    /**
     * The UEFI firmware (firmware: { type: "uefi" }, docs/uefi.md): its code
     * image, its variable store (a buffer object: src/buffer.js's, or a disk
     * written back), the flash at the top of 4 GiB (the code's mmio_ram
     * region, -1 until mapped; the store's pflash) and the debug console
     * @type {?{code: !ArrayBuffer, vars: ?Object, code_region: number, pflash: ?PFlash, debug_console: boolean, secure_boot: boolean}}
     */
    this.firmware = null;

    /** The TPM's state store (tpm: docs/tpm.md), a buffer object @type {?Object} */
    this.tpm_store = null;

    this.instruction_counter = view(Uint32Array, memory, state_base + STATE_OFFSETS.instruction_counter, 1);

    // registers
    this.reg32 = view(Int32Array, memory, state_base + STATE_OFFSETS.reg32, 8);

    this.fpu_st = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_st, 4 * 8);

    this.fpu_stack_empty = view(Uint8Array, memory, state_base + STATE_OFFSETS.fpu_stack_empty, 1);
    this.fpu_stack_empty[0] = 0xFF;
    this.fpu_stack_ptr = view(Uint8Array, memory, state_base + STATE_OFFSETS.fpu_stack_ptr, 1);
    this.fpu_stack_ptr[0] = 0;

    this.fpu_control_word = view(Uint16Array, memory, state_base + STATE_OFFSETS.fpu_control_word, 1);
    this.fpu_control_word[0] = 0x37F;
    this.fpu_status_word = view(Uint16Array, memory, state_base + STATE_OFFSETS.fpu_status_word, 1);
    this.fpu_status_word[0] = 0;
    this.fpu_ip = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_ip, 1);
    this.fpu_ip[0] = 0;
    this.fpu_ip_selector = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_ip_selector, 1);
    this.fpu_ip_selector[0] = 0;
    this.fpu_opcode = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_opcode, 1);
    this.fpu_opcode[0] = 0;
    this.fpu_dp = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_dp, 1);
    this.fpu_dp[0] = 0;
    this.fpu_dp_selector = view(Int32Array, memory, state_base + STATE_OFFSETS.fpu_dp_selector, 1);
    this.fpu_dp_selector[0] = 0;

    this.reg_xmm32s = view(Int32Array, memory, state_base + STATE_OFFSETS.reg_xmm, 8 * 4);

    this.mxcsr = view(Int32Array, memory, state_base + STATE_OFFSETS.mxcsr, 1);

    // segment registers, tr and ldtr
    this.sreg = view(Uint16Array, memory, state_base + STATE_OFFSETS.sreg, 8);

    // debug registers
    this.dreg = view(Int32Array, memory, state_base + STATE_OFFSETS.dreg, 8);

    this.reg_pdpte = view(Int32Array, memory, state_base + STATE_OFFSETS.reg_pdpte, 8);

    this.svga_dirty_bitmap_min_offset = view(Uint32Array, memory, state_base + STATE_OFFSETS.svga_dirty_bitmap_min_offset, 1);
    this.svga_dirty_bitmap_max_offset = view(Uint32Array, memory, state_base + STATE_OFFSETS.svga_dirty_bitmap_max_offset, 1);

    this.fw_value = [];
    this.fw_pointer = 0;
    /**
     * Files of the fw_cfg file directory (option ROMs, ACPI tables, ...).
     * get_data, if present, produces the contents when the firmware selects
     * the file; it must return as many bytes as data, which gives the size.
     * @type {!Array<{name: string, data: !Uint8Array, get_data: (function():!Uint8Array|undefined)}>}
     */
    this.option_roms = [];

    /** @type {?Platform} description of the emulated platform */
    this.platform = null;

    /**
     * The cores of the machine (setup_cores). One runs at a time: its state is
     * in the fixed state block and `saved` is null; the others keep theirs in
     * `saved`. `running` is false for an AP waiting for a start-up IPI.
     * @type {!Array<{running: boolean, saved: ?Array<!Uint8Array>, slices: number, steps: number}>}
     */
    this.cores = [];
    this.active_core = 0;
    /** The core in a worker whose port or MMIO access is being performed
     * (src/parallel/machine.js), or -1: the active core's */
    this.io_core = -1;
    /** State of a core after reset_cpu, used for INIT @type {!Array<!Uint8Array>} */
    this.core_reset_state = [];

    /** @type {?function()} */
    this.reload_direct_boot_kernel = null;

    /**
     * Asserted level-triggered sources (ACPI SCI, PCI INTx) per IRQ line, see
     * set_shared_irq_level
     * @type {!Array<!Set<number>>}
     */
    this.shared_irq_sources = Array.from({ length: 24 }, () => new Set());

    this.io = undefined;

    this.bus = bus;

    this.set_tsc(0, 0);

    //Object.seal(this);
}

CPU.prototype.mmap_read8 = function(addr)
{
    const value = this.memory_map_read8[addr >>> MMAP_BLOCK_BITS](addr);
    dbg_assert(value >= 0 && value <= 0xFF);
    return value;
};

CPU.prototype.mmap_write8 = function(addr, value)
{
    dbg_assert(value >= 0 && value <= 0xFF);
    this.memory_map_write8[addr >>> MMAP_BLOCK_BITS](addr, value);
};

CPU.prototype.mmap_write16 = function(addr, value)
{
    var fn = this.memory_map_write8[addr >>> MMAP_BLOCK_BITS];

    dbg_assert(value >= 0 && value <= 0xFFFF);
    fn(addr, value & 0xFF);
    fn(addr + 1 | 0, value >> 8);
};

CPU.prototype.mmap_read32 = function(addr)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;

    return this.memory_map_read32[aligned_addr](addr);
};

CPU.prototype.mmap_write32 = function(addr, value)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;

    this.memory_map_write32[aligned_addr](addr, value);
};

CPU.prototype.mmap_write64 = function(addr, value0, value1)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;
    // This should hold since writes across pages are split up
    dbg_assert(aligned_addr === (addr + 7) >>> MMAP_BLOCK_BITS);

    var write_func32 = this.memory_map_write32[aligned_addr];
    write_func32(addr, value0);
    write_func32(addr + 4, value1);
};

CPU.prototype.mmap_write128 = function(addr, value0, value1, value2, value3)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;
    // This should hold since writes across pages are split up
    dbg_assert(aligned_addr === (addr + 12) >>> MMAP_BLOCK_BITS);

    var write_func32 = this.memory_map_write32[aligned_addr];
    write_func32(addr, value0);
    write_func32(addr + 4, value1);
    write_func32(addr + 8, value2);
    write_func32(addr + 12, value3);
};

/**
 * @param {Array.<number>|Uint8Array} blob
 * @param {number} offset
 */
CPU.prototype.write_blob = function(blob, offset)
{
    dbg_assert(blob && blob.length >= 0);

    if(blob.length)
    {
        dbg_assert(!this.in_mapped_range(offset));
        dbg_assert(!this.in_mapped_range(offset + blob.length - 1));

        this.jit_dirty_cache(offset, offset + blob.length);
        this.mem8.set(blob, offset);
    }
};

CPU.prototype.read_blob = function(offset, length)
{
    if(length)
    {
        dbg_assert(!this.in_mapped_range(offset));
        dbg_assert(!this.in_mapped_range(offset + length - 1));
    }
    return this.mem8.subarray(offset, offset + length);
};

// Legacy VGA memory and the BIOS ROMs, never RAM for a device
const LEGACY_HOLE_START = 0xA0000;
const LEGACY_HOLE_END = 0x100000;
const PAGE_SIZE = 4096;
// x64_phys_kind
const PHYS_KIND_RAM = 1;
const PHYS_KIND_EXTENDED = 3;

/** The end of the physical address space: the 36-bit bus */
CPU.prototype.physical_limit = 0x1000000000;

/**
 * Where a device's DMA to [address, address + length) goes (the machine's
 * DMA facade, docs/arm64-virt-android16-plan.md P1.6)
 * @param {number} address
 * @param {number} length
 * @return {number} the offset of one contiguous plain-RAM backing,
 *     -1 for other RAM, -2 for anything that is not RAM
 */
CPU.prototype.dma_classify = function(address, length)
{
    if(!Number.isSafeInteger(address) || !Number.isSafeInteger(length) || address < 0 || length <= 0 ||
        address + length > this.physical_limit ||
        address < LEGACY_HOLE_END && address + length > LEGACY_HOLE_START)
    {
        return -2;
    }

    const kind = this.wm.exports["x64_phys_kind"];
    const resolve = this.wm.exports["x64_phys_resolve"];
    const first = resolve(address >>> 0, Math.floor(address / 0x100000000));
    let contiguous = first >= 0;

    for(let page = address - address % PAGE_SIZE; page < address + length; page += PAGE_SIZE)
    {
        const low = page >>> 0;
        const high = Math.floor(page / 0x100000000);
        const page_kind = kind(low, high);
        if(page_kind !== PHYS_KIND_RAM && page_kind !== PHYS_KIND_EXTENDED) return -2;
        // (extended RAM frames are cached, never a view)
        if(contiguous && (page_kind !== PHYS_KIND_RAM ||
            page > address && resolve(low, high) !== first + (page - address)))
        {
            contiguous = false;
        }
    }

    return contiguous ? first : -1;
};

/** Validate a complete 36-bit DMA range without reading any device. */
CPU.prototype.validate_physical_range = function(address, length)
{
    if(!Number.isSafeInteger(address) || !Number.isSafeInteger(length) || address < 0 || address >= 0x1000000000 || length < 0 ||
        address + length > 0x1000000000) throw new RangeError("Physical address exceeds the 36-bit bus");
    const resolve = this.wm.exports["x64_phys_resolve"];
    for(let at = address; at < address + length;)
    {
        const end = Math.min(address + length, Math.floor(at / 4096 + 1) * 4096);
        if(resolve(at >>> 0, Math.floor(at / 0x100000000)) < 0 ||
            resolve((end - 1) >>> 0, Math.floor((end - 1) / 0x100000000)) < 0)
            throw new RangeError("Physical range is not mapped");
        at = end;
    }
};

/** @param {number} address @param {number} width @return {number} */
CPU.prototype.read_physical_scalar = function(address, width)
{
    this.validate_physical_range(address, width / 8);
    const value = this.wm.exports["x64_phys_read" + width](address >>> 0, Math.floor(address / 0x100000000));
    if(value < 0) throw new RangeError("Physical range is not mapped");
    return value;
};
CPU.prototype.read8_physical = function(address) { return this.read_physical_scalar(address, 8); };
CPU.prototype.read16_physical = function(address) { return this.read_physical_scalar(address, 16); };
CPU.prototype.read32_physical = function(address) { return this.read_physical_scalar(address, 32); };
CPU.prototype.write_physical_scalar = function(address, value, width)
{
    this.validate_physical_range(address, width / 8);
    if(!this.wm.exports["x64_phys_write" + width](address >>> 0, Math.floor(address / 0x100000000), value >>> 0))
        throw new RangeError("Physical range is not mapped");
};
CPU.prototype.write8_physical = function(address, value) { this.write_physical_scalar(address, value, 8); };
CPU.prototype.write16_physical = function(address, value) { this.write_physical_scalar(address, value, 16); };
CPU.prototype.write32_physical = function(address, value) { this.write_physical_scalar(address, value, 32); };

/** Copy one requested chunk; never allocate based on a physical address. */
CPU.prototype.read_blob_physical = function(address, length)
{
    this.validate_physical_range(address, length);
    const result = new Uint8Array(length);
    for(let done = 0; done < length;)
    {
        const at = address + done;
        const count = Math.min(length - done, 4096 - at % 4096);
        const kind = this.wm.exports["x64_phys_kind"](at >>> 0, Math.floor(at / 0x100000000));
        if(kind === 1)
        {
            const backing = this.wm.exports["x64_phys_resolve"](at >>> 0, Math.floor(at / 0x100000000));
            result.set(this.mem8.subarray(backing, backing + count), done);
        }
        else if(kind === 3) result.set(this.extended_page_bytes(at, count, false), done);
        else for(let i = 0; i < count; i++) result[done + i] = this.read8_physical(at + i);
        done += count;
    }
    return result;
};
CPU.prototype.write_blob_physical = function(blob, address)
{
    this.validate_physical_range(address, blob.length);
    for(let done = 0; done < blob.length;)
    {
        const at = address + done;
        const count = Math.min(blob.length - done, 4096 - at % 4096);
        const kind = this.wm.exports["x64_phys_kind"](at >>> 0, Math.floor(at / 0x100000000));
        if(kind === 1)
        {
            const backing = this.wm.exports["x64_phys_resolve"](at >>> 0, Math.floor(at / 0x100000000));
            this.jit_dirty_cache(backing, backing + count);
            this.mem8.set(blob.slice(done, done + count), backing);
        }
        else if(kind === 3) this.extended_page_bytes(at, count, blob.subarray(done, done + count));
        else for(let i = 0; i < count; i++) this.write8_physical(at + i, blob[done + i]);
        done += count;
    }
};

/**
 * Copy bytes of one extended RAM page (DMA, debugging): its frame is pinned
 * meanwhile (src/rust/x64/extended.rs)
 * @param {number} address guest physical, in extended RAM
 * @param {number} count bytes within the page
 * @param {Uint8Array|boolean} write the bytes to write, or false to read
 * @return {!Uint8Array} the bytes read
 */
CPU.prototype.extended_page_bytes = function(address, count, write)
{
    const page = Math.floor((address - this.extended_base) / 4096);
    // (an i32: the frame pool may lie above 2 GiB)
    const frame = this.wm.exports["x64_ext_pin"](page, !!write) >>> 0;
    dbg_assert(frame !== 0 && address % 4096 + count <= 4096);
    const bytes = new Uint8Array(this.wasm_memory.buffer, frame + address % 4096, count);
    let result = bytes;
    if(write) bytes.set(/** @type {!Uint8Array} */ (write));
    else result = bytes.slice();
    this.wm.exports["x64_ext_unpin"](page);
    return result;
};

CPU.prototype.clear_stats = function()
{
    this.wm.exports["profiler_init"]();
};

// Compiled code of the page tiers (src/rust/jitrt/publish.rs: the x64
// page tier is client 0). Installed synchronously when the host allows it:
// the core is at a scheduling point with no Rust lock held, so the function
// is callable before the guest continues. Resolves to whether the function
// was installed (the performance recorder times it).
CPU.prototype.jit_publish = function(client, id, slot, pointer, length)
{
    const exports = this.wm.exports;
    return this.publish_code(slot, pointer, length, () => exports["jit_install"](client, id, slot),
        () => exports["jit_ready"](client, id, slot), () => exports["jit_cancel"](client, id, slot));
};

CPU.prototype.publish_code = function(slot, pointer, length, install, ready, cancel)
{
    const wasm = this.wm, exports = wasm.exports, table = wasm.wasm_table;
    const epoch = this.execution_epoch;
    const code = new Uint8Array(exports["memory"].buffer, pointer >>> 0, length >>> 0).slice();
    const current = () => this.execution_epoch === epoch && this.wm === wasm;
    const set = instance => {
        if(!current()) return false;
        const f = instance.exports["f"];
        if(typeof f !== "function" || !install())
        {
            cancel();
            return false;
        }
        table.set(slot + WASM_TABLE_OFFSET, f);
        ready();
        return true;
    };
    if(this.ir_sync_publication)
    {
        try
        {
            return Promise.resolve(set(new WebAssembly.Instance(new WebAssembly.Module(code), { "e": this.jit_imports })));
        }
        catch(error)
        {
            if(error instanceof WebAssembly.CompileError || error instanceof WebAssembly.LinkError)
            {
                dbg_log("page function rejected: " + error, LOG_CPU);
                if(current()) cancel();
                return Promise.resolve(false);
            }
            this.ir_sync_publication = false;
        }
    }
    return WebAssembly.instantiate(code, { "e": this.jit_imports }).then(result => set(result.instance), error => {
        dbg_log("page function rejected: " + error, LOG_CPU);
        if(current()) cancel();
        return false;
    });
};

CPU.prototype.create_jit_imports = function()
{
    // Set this.jit_imports as generated WASM modules will expect

    const jit_imports = Object.create(null);

    jit_imports["m"] = this.wm.exports["memory"];

    for(const name of Object.keys(this.wm.exports))
    {
        if(name.startsWith("_") || name.startsWith("zstd") || name.endsWith("_js"))
        {
            continue;
        }

        jit_imports[name] = this.wm.exports[name];
    }

    // With Wasm tail calls, x64 page functions continue in the next page's
    // function directly, through the shared function table (x64::pages CHAIN).
    const table = this.wm.wasm_table;
    if(table && this.wm.exports["jit_set_tail_calls"])
    {
        // (module (func (return_call 0)))
        const probe = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4, 0, 18, 0, 11]);
        const supported = WebAssembly.validate(probe);
        if(supported) jit_imports["t"] = table;
        this.wm.exports["jit_set_tail_calls"](supported ? 1 : 0);
        this.wm.exports["x64_page_set_chaining"]?.(supported ? 1 : 0);
    }
    // FMA with relaxed SIMD's multiply-adds where they fuse (ir::native_fp)
    this.wm.exports["ir_relaxed_fma_fused"]?.(relaxed_fma_fused() ? 1 : 0);

    this.jit_imports = jit_imports;
};

let relaxed_fma_result;
/**
 * Whether the engine has Wasm relaxed SIMD and its f32x4/f64x2 relaxed_madd
 * and relaxed_nmadd fuse, rounding once like x86's FMA (an engine may choose
 * either, and keeps its choice). Each is given (1 + ulp) * (1 + ulp) and an
 * addend that cancels all but the product's last bit, 2^-104 or 2^-46, which
 * only a fused operation keeps.
 * @return {boolean}
 */
export function relaxed_fma_fused()
{
    if(relaxed_fma_result !== undefined) return relaxed_fma_result;
    const leb = n => {
        const out = [];
        do { out.push(n > 127 ? n & 127 | 128 : n); n >>>= 7; } while(n);
        return out;
    };
    const simd = op => [0xFD, ...leb(op)];
    // v128.const of a double's 32-bit halves or a single in every lane
    const lanes = (double, ...words) => [...simd(0x0C), ...(double ? [...words, ...words] : [words[0], words[0], words[0], words[0]])
        .flatMap(w => [w & 255, w >>> 8 & 255, w >>> 16 & 255, w >>> 24 & 255])];
    // op(a, a, c) === expected in every lane (i64x2/i32x4 eq, all_true)
    const check = (op, double, a, c, expected) => [...lanes(double, ...a), ...lanes(double, ...a), ...lanes(double, ...c),
        ...simd(op), ...lanes(double, ...expected), ...simd(double ? 0xD6 : 0x37), ...simd(double ? 0xC3 : 0xA3)];
    const body = [0,
        ...check(0x107, true, [1, 0x3FF00000], [2, 0xBFF00000], [0, 0x39700000]), // f64x2.relaxed_madd
        ...check(0x108, true, [1, 0x3FF00000], [2, 0x3FF00000], [0, 0xB9700000]), 0x71, // f64x2.relaxed_nmadd, i32.and
        ...check(0x105, false, [0x3F800001], [0xBF800002], [0x28800000]), 0x71, // f32x4.relaxed_madd
        ...check(0x106, false, [0x3F800001], [0x3F800002], [0xA8800000]), 0x71, // f32x4.relaxed_nmadd
        0x0B];
    const code = [1, ...leb(body.length), ...body];
    // (module (func (export "f") (result i32) ...))
    const bytes = new Uint8Array([0, 0x61, 0x73, 0x6D, 1, 0, 0, 0, 1, 5, 1, 0x60, 0, 1, 0x7F, 3, 2, 1, 0, 7, 5, 1, 1, 0x66, 0, 0,
        10, ...leb(code.length), ...code]);
    relaxed_fma_result = false;
    try
    {
        relaxed_fma_result = WebAssembly.validate(bytes) &&
            new WebAssembly.Instance(new WebAssembly.Module(bytes)).exports["f"]() === 1;
    }
    catch(e) {}
    return relaxed_fma_result;
}

CPU.prototype.wasm_patch = function()
{
    const get_optional_import = name => this.wm.exports[name];

    const get_import = name =>
    {
        const f = get_optional_import(name);
        console.assert(f, "Missing import: " + name);
        return f;
    };
    // An address in the wasm memory, returned as an i32: above 2 GiB (a vCPU's
    // instance when guest RAM is large) it would read as negative
    const get_address_import = name =>
    {
        const f = get_import(name);
        return (...args) => f(...args) >>> 0;
    };

    this.reset_cpu = get_import("reset_cpu");

    this.getiopl = get_import("getiopl");
    this.get_eflags = get_import("get_eflags");

    this.handle_irqs = get_import("handle_irqs");

    const main_loop = get_import("main_loop");
    const run_cpu_slice = get_import("run_cpu_slice");
    this.main_loop = () => this.execute_cpu(() => main_loop());
    this.run_cpu_slice = budget => this.execute_cpu(() => run_cpu_slice(budget));

    this.read8 = get_import("read8");
    this.read16 = get_import("read16");
    this.read32s = get_import("read32s");
    this.write8 = get_import("write8");
    this.write16 = get_import("write16");
    this.write32 = get_import("write32");
    this.in_mapped_range = get_import("in_mapped_range");

    // used by nasmtests
    this.fpu_load_tag_word = get_import("fpu_load_tag_word");
    this.fpu_load_status_word = get_import("fpu_load_status_word");
    this.fpu_get_sti_f64 = get_import("fpu_get_sti_f64");

    this.translate_address_system_read = get_import("translate_address_system_read_js");

    this.get_seg_cs = get_import("get_seg_cs");
    this.get_real_eip = get_import("get_real_eip");

    this.clear_tlb = get_import("clear_tlb");
    this.full_clear_tlb = get_import("full_clear_tlb");

    this.apic_set_core_count = get_import("apic_set_core_count");
    this.apic_set_current_core = get_import("apic_set_current_core");
    this.apic_take_core_events = get_import("apic_take_core_events");
    this.apic_peek_core_events = get_import("apic_peek_core_events");
    this.apic_restore_core_events = get_import("apic_restore_core_events");
    this.apic_init_core = get_import("apic_init_core");
    this.apic_core_interrupt_pending = get_import("apic_core_interrupt_pending");
    this.apic_addr = get_address_import("apic_addr");
    this.apic_core_nmi_pending = get_import("apic_core_nmi_pending");
    this.apic_raise_smi = get_import("apic_raise_smi");
    this.apic_core_smi_pending = get_import("apic_core_smi_pending");
    this.apic_restore_smi = get_import("apic_restore_smi");
    this.update_state_flags = get_import("update_state_flags");

    this.set_tsc = get_import("set_tsc");
    this.store_current_tsc = get_import("store_current_tsc");

    this.set_cpuid_level = get_import("set_cpuid_level");

    this.device_raise_irq = get_import("device_raise_irq");
    this.device_lower_irq = get_import("device_lower_irq");
    // (IOAPIC inputs 16-23 of the Q35 PIRQs; missing in older builds)
    this.ioapic_raise_irq = get_optional_import("ioapic_raise_irq");
    this.ioapic_lower_irq = get_optional_import("ioapic_lower_irq");
    // (PCI message signalled interrupts; missing in older builds)
    this.apic_msi = get_optional_import("apic_msi");
    // (system management mode, src/rust/cpu/smm.rs; missing in older builds)
    this.smm_enter = get_optional_import("smm_enter");
    this.smm_active = get_optional_import("smm_active");
    this.smram_set_control = get_optional_import("smram_set_control");
    this.smram_set_tseg = get_optional_import("smram_set_tseg");

    this.apic_timer = get_import("apic_timer");

    this.jit_clear_cache = get_import("jit_clear_cache_js");
    this.jit_dirty_cache = get_import("jit_dirty_cache");

    this.allocate_memory = get_import("allocate_memory");
    this.zero_memory = get_import("zero_memory");
    this.is_memory_zeroed = get_import("is_memory_zeroed");

    // Device memory behind PCI memory BARs (src/rust/cpu/mmio_ram.rs)
    this.mmio_ram_allocate = get_import("mmio_ram_allocate");
    this.mmio_ram_backing = get_import("mmio_ram_backing");
    this.mmio_ram_map = get_import("mmio_ram_map");
    this.mmio_ram_unmap = get_import("mmio_ram_unmap");
    this.mmio_ram_set_writable = get_import("mmio_ram_set_writable");
    this.mmio_ram_reserve = get_import("mmio_ram_reserve");
    this.mmio_ram_read8 = get_import("mmio_ram_read8");
    this.mmio_ram_write8 = get_import("mmio_ram_write8");
    this.mmio_ram_mark_dirty = get_import("mmio_ram_mark_dirty");
    this.mmio_ram_take_dirty = get_import("mmio_ram_take_dirty");
    this.mmio_ram_allocate_pixels = get_import("mmio_ram_allocate_pixels");
    this.mmio_ram_fill_pixels = get_import("mmio_ram_fill_pixels");

    this.get_pic_addr_master = get_address_import("get_pic_addr_master");
    this.get_pic_addr_slave = get_address_import("get_pic_addr_slave");
    this.get_apic_addr = get_address_import("get_apic_addr");
    this.get_ioapic_addr = get_address_import("get_ioapic_addr");

    this.zstd_create_ctx = get_import("zstd_create_ctx");
    this.zstd_get_src_ptr = get_import("zstd_get_src_ptr");
    this.zstd_free_ctx = get_import("zstd_free_ctx");
    this.zstd_read = get_import("zstd_read");
    this.zstd_read_free = get_import("zstd_read_free");
};

CPU.prototype.jit_clear_func = function(index)
{
    dbg_assert(index >= 0 && index < WASM_TABLE_SIZE);
    this.wm.wasm_table.set(index + WASM_TABLE_OFFSET, null);
};

CPU.prototype.get_state = function(skip_memory = false)
{
    // Capture one machine time before collecting devices or per-core TSC offsets.
    const clock_state = this.clock.get_state();
    this.wm.exports["fpu_sync_all"]?.();
    var state = [];

    state[0] = this.memory_size[0];
    state[1] = new Uint8Array([...this.segment_is_null, ...this.segment_access_bytes]);
    state[2] = this.segment_offsets;
    state[3] = this.segment_limits;
    state[4] = this.protected_mode[0];
    state[5] = this.idtr_offset[0];
    state[6] = this.idtr_size[0];
    state[7] = this.gdtr_offset[0];
    state[8] = this.gdtr_size[0];
    // 9 (formerly page_fault)
    state[10] = this.cr;
    state[11] = this.cpl[0];

    state[13] = this.is_32[0];

    state[16] = this.stack_size_32[0];
    state[17] = this.in_hlt[0];
    state[18] = this.last_virt_eip[0];
    state[19] = this.eip_phys[0];

    state[22] = this.sysenter_cs[0];
    state[23] = this.sysenter_eip[0];
    state[24] = this.sysenter_esp[0];
    state[25] = this.prefixes[0];
    state[26] = this.flags[0];
    state[27] = this.flags_changed[0];
    state[28] = this.last_op1[0];

    state[30] = this.last_op_size[0];

    state[37] = this.instruction_pointer[0];
    state[38] = this.previous_ip[0];
    state[39] = this.reg32;
    state[40] = this.sreg;
    state[41] = this.dreg;
    state[42] = this.reg_pdpte;

    this.store_current_tsc();
    state[43] = this.current_tsc;

    state[45] = this.devices.virtio_9p;
    state[46] = this.get_state_apic();
    state[47] = this.devices.rtc;
    state[48] = this.devices.pci;
    state[49] = this.devices.dma;
    state[50] = this.devices.acpi;
    // 51 (formerly hpet)
    // the display adapter (nothing with graphics_adapter: "none")
    state[52] = this.devices.graphics_adapter;
    state[53] = this.devices.ps2;
    state[54] = this.devices.uart0;
    state[55] = this.devices.fdc;

    if(!this.devices.ide)
    {
        // (Q35: the drives are on the AHCI ports, state[101])
    }
    else if(!this.devices.ide.secondary)
    {
        if(this.devices.ide.primary?.master.is_atapi)
        {
            state[56] = this.devices.ide.primary;
        }
        else
        {
            state[57] = this.devices.ide.primary;
        }
    }
    else
    {
        state[85] = this.devices.ide;
    }

    state[58] = this.devices.pit;
    state[59] = this.devices.net;
    state[60] = this.get_state_pic();
    // (the sound card: its plugin's slot, or none)
    state[61] = this.devices.audio;
    // (USB: the plugin's slot, or none; its disks' buffers by their ids:
    // the guest's writes, as a hard disk's state has them)
    state[107] = this.devices.usb;
    state[108] = this.usb_disks ? Array.from(this.usb_disks) : null;
    // (the UEFI firmware's variable store: its bytes, or a reference to the
    // store written back, src/pflash.js)
    state[109] = this.firmware && this.firmware.pflash;
    // (the TPM: the plugin's slot; its store's bytes or reference, as a disk's)
    state[110] = this.devices.tpm;
    state[111] = this.devices.tpm ? this.tpm_store : null;

    state[62] = this.fw_value;

    state[63] = this.get_state_ioapic();

    state[64] = this.tss_size_32[0];

    state[66] = this.reg_xmm32s;

    state[67] = this.fpu_st;
    state[68] = this.fpu_stack_empty[0];
    state[69] = this.fpu_stack_ptr[0];
    state[70] = this.fpu_control_word[0];
    state[71] = this.fpu_ip[0];
    state[72] = this.fpu_ip_selector[0];
    state[73] = this.fpu_dp[0];
    state[74] = this.fpu_dp_selector[0];
    state[75] = this.fpu_opcode[0];

    if(skip_memory) { state[77] = null; state[78] = null; }
    else
    {
        // (a single-buffer snapshot does not hold extended RAM: the stream
        // does; pages written only in their frames count too)
        if(this.extended_store)
        {
            this.flush_extended_memory();
            if(this.extended_store.touched.some(byte => byte !== 0))
            {
                throw new Error("A snapshot of extended RAM needs save_state_stream");
            }
        }
        const { packed_memory, bitmap } = this.pack_memory();
        state[77] = packed_memory;
        state[78] = new Uint8Array(bitmap.get_buffer());
    }

    state[79] = this.devices.uart1;
    state[80] = this.devices.uart2;
    state[81] = this.devices.uart3;
    state[82] = this.devices.virtio_console;
    state[83] = this.devices.virtio_net;
    state[84] = this.devices.virtio_balloon;

    // state[85] new ide set above

    state[86] = this.last_result;
    state[87] = this.fpu_status_word;
    state[88] = this.mxcsr;
    state[89] = this.devices.vmware;
    state[90] = this.devices.parallel0;
    state[91] = this.devices.parallel1;
    state[92] = get_virtio_devices_state(this.devices.virtio_devices);
    state[93] = this.shared_irq_sources.map(sources => Array.from(sources));
    state[94] = [this.apic_enabled[0],
        new Uint8Array(this.wasm_memory.buffer)[this.state_base + STATE_OFFSETS.nmi_blocked],
        +this.apic_core_nmi_pending(0), this.apic_peek_core_events(0)];

    state[95] = clock_state;
    state[96] = this.get_machine_core_state();
    state[97] = [1, this.get_physical_windows()];
    // extended RAM pages (its contents are records of the snapshot stream)
    state[98] = this.extended_pages;
    // the machine type and the version of its device layout
    // (99: the extended RAM bitmap of streamed snapshots, src/state.js)
    state[100] = this.devices.q35;
    state[101] = this.devices.ahci;
    state[102] = this.devices.hpet;
    state[103] = [this.platform.machine, MACHINE_LAYOUT_VERSION];
    state[104] = this.devices.smbus;
    // the root ports' hot plug slots
    state[105] = (this.devices.pcie_root_ports || []).map(port => port.get_state());
    // the CPU features (settings cpu_features, CPU_FEATURES)
    state[106] = this.cpu_features;
    return state;
};

/** A temporary host buffer never aliases guest RAM or survives its callback. */
CPU.prototype.with_wide_state_buffer = function(words, operation)
{
    const ex = this.wm.exports;
    // Above 2 GiB (large guest RAM), the i32 result reads as negative.
    const pointer = ex["v86_malloc"](Math.max(4, words.byteLength)) >>> 0;
    try
    {
        new Uint32Array(this.wasm_memory.buffer, pointer, words.length).set(words);
        return operation(pointer, words.length);
    }
    finally { ex["v86_free"](pointer); }
};

CPU.prototype.get_physical_windows = function()
{
    const words = new Uint32Array(80);
    for(let slot = 0; slot < 16; slot++) for(let field = 0; field < 5; field++)
        words[slot * 5 + field] = this.wm.exports["x64_phys_get_window"](slot, field);
    return words;
};

CPU.prototype.get_wide_tlb = function(id)
{
    const ex = this.wm.exports;
    const words = new Uint32Array(ex["x64_tlb_snapshot_dwords"](id));
    this.with_wide_state_buffer(words, (pointer, count) => {
        if(ex["x64_tlb_snapshot_write"](id, pointer, count) !== count) throw new Error("Cannot capture wide TLB");
        words.set(new Uint32Array(this.wasm_memory.buffer, pointer, count));
    });
    return words;
};

CPU.prototype.validate_physical_state = function(state)
{
    if(state === undefined) return;
    if(!Array.isArray(state) || state[0] !== 1 || !(state[1] instanceof Uint32Array) || state[1].length !== 80 ||
        !this.with_wide_state_buffer(state[1], (pointer, count) => this.wm.exports["x64_phys_validate_windows"](pointer, count)))
        throw new Error("Invalid physical memory map in snapshot");
};

/**
 * The features cpu_type "x86_64" has when cpu_features is not given: every
 * released one of its profile (the owner's decision of 2026-10-17, which
 * replaced docs/simd-xsave-plan.md Q1's "the old CPU unless asked")
 */
const X86_64_DEFAULT_FEATURES = Object.keys(CPU_FEATURES).filter(name =>
    CPU_FEATURES[name]["released"] && CPU_FEATURES[name]["profiles"].includes("x86_64"));

/**
 * The feature set (src/rust/cpu/features.rs) of the setting cpu_features: an
 * array of the names of src/cpu_features.js, or the name of a preset; not
 * given, every released feature for x86_64 and none for x86 ([]: none). A
 * feature that cpuid_level cannot report is left out, with the features that
 * require it (docs/simd-xsave-plan.md 6.1); an unknown feature, one the CPU
 * profile cannot have or one without its requirements is an error.
 * @param {Array<string>|string|undefined} requested
 * @param {boolean} x86_64
 * @param {number} cpuid_level
 * @return {number}
 */
export function resolve_cpu_features(requested, x86_64, cpuid_level)
{
    if(requested === undefined)
    {
        if(!x86_64) return 0;
        requested = X86_64_DEFAULT_FEATURES;
    }
    const names = typeof requested === "string" ? CPU_FEATURE_PRESETS[requested] : requested;
    if(!Array.isArray(names))
    {
        throw new Error("cpu_features: unknown preset " + JSON.stringify(requested));
    }
    const profile = x86_64 ? "x86_64" : "x86";
    for(const name of names)
    {
        const feature = CPU_FEATURES[name];
        if(!feature) throw new Error("cpu_features: unknown feature " + JSON.stringify(name));
        if(!feature["profiles"].includes(profile)) throw new Error("cpu_features: " + name + " needs cpu_type: \"x86_64\"");
        for(const required of feature["requires"])
        {
            if(!names.includes(required)) throw new Error("cpu_features: " + name + " requires " + required);
        }
    }
    let kept = names.filter(name => CPU_FEATURES[name]["min_cpuid_level"] <= cpuid_level);
    for(let count = -1; count !== kept.length;)
    {
        count = kept.length;
        kept = kept.filter(name => CPU_FEATURES[name]["requires"].every(required => kept.includes(required)));
    }
    return kept.reduce((set, name) => set | 1 << CPU_FEATURES[name]["bit"], 0);
}

/**
 * The features of the setting cpu_features whose milestone is not released
 * yet (docs/simd-xsave-plan.md 4.1): they are for tests and development, and
 * their instructions may still be #UD
 * @param {Array<string>|string|undefined} requested
 * @return {Array<string>}
 */
export function unreleased_cpu_features(requested)
{
    const names = typeof requested === "string" ? CPU_FEATURE_PRESETS[requested] || [] : requested || [];
    return names.filter(name => CPU_FEATURES[name] && !CPU_FEATURES[name]["released"]);
}

// Version 1 predates the x64 extension banks. Keep exact byte ranges for import.
const CORE_STATE_RANGES_V1 = [[64, 108], [112, 552], [556, 620], [628, 652], [668, 716],
    [724, 812], [816, 960], [968, 1132], [1152, 1280]];

/** All cores at a scheduler boundary; versioned independently of legacy single-core slots. */
CPU.prototype.get_machine_core_state = function()
{
    const ex = this.wm.exports;
    ex["context_capture"]();
    const cores = this.cores.map((core, id) => {
        const tlb = new Uint32Array(ex["context_tlb_len"](id) * 2);
        for(let i = 0; i < tlb.length; i++) tlb[i] = ex["context_tlb_get"](id, i >> 1, i & 1);
        return [core.running, id === this.active_core ? this.save_core_state() : core.saved,
            new Uint8Array(this.wasm_memory.buffer, this.apic_addr(id), 184).slice(),
            new Uint8Array(this.wasm_memory.buffer, ex["apic_aux_addr"](id) >>> 0, ex["apic_aux_size"]()).slice(),
            this.apic_peek_core_events(id), !!this.apic_core_nmi_pending(id),
            [ex["context_tsc_get"](id, false) >>> 0, ex["context_tsc_get"](id, true) >>> 0],
            tlb, core.slices, core.steps,
            new Uint8Array(this.wasm_memory.buffer, ex["core_statistics_addr"](id) >>> 0, ex["core_statistics_size"]()).slice(), ex["exception_shutdown"](id), this.get_wide_tlb(id),
            !!this.apic_core_smi_pending(id)];
    });
    return [2, this.cores.length, this.active_core, this.scheduler_quantum,
        this.scheduler_seed, this.scheduler_round, cores, CORE_STATE_RANGES.map(range => range.slice())];
};

CPU.prototype.validate_machine_core_state = function(state)
{
    if(!state)
    {
        if(this.cores.length !== 1) throw new Error("Snapshot topology mismatch: legacy snapshot has one core");
        return;
    }
    const fail = () => { throw new Error("Invalid multicore snapshot or topology mismatch"); };
    // Version 2 lists its ranges; a snapshot from before a range was added
    // restores that range to its reset value (set_machine_core_state)
    if(state[0] === 2 && !(Array.isArray(state[7]) && state[7].every(range => Array.isArray(range) &&
        CORE_STATE_RANGES.some(([start, end]) => range[0] === start && range[1] === end)))) fail();
    const ranges = state[0] === 1 ? CORE_STATE_RANGES_V1 : state[7];
    if(state[0] !== 1 && state[0] !== 2 || state[1] !== this.cores.length || !Array.isArray(state[6]) || state[6].length !== state[1] ||
        !Number.isInteger(state[2]) || state[2] < 0 || state[2] >= state[1] ||
        !Number.isInteger(state[3]) || state[3] < 1 || state[3] > 100000 ||
        !Number.isSafeInteger(state[4]) || state[4] < 0 || state[4] > 0xFFFFFFFF ||
        !Number.isSafeInteger(state[5]) || state[5] < 0) fail();
    for(const core of state[6])
    {
        if(!Array.isArray(core) || typeof core[0] !== "boolean" || !Array.isArray(core[1]) ||
            core[1].length !== ranges.length || !(core[2] instanceof Uint8Array) || core[2].length !== 184 ||
            !(core[3] instanceof Uint8Array) || core[3].length !== this.wm.exports["apic_aux_size"]() ||
            !Array.isArray(core[6]) || core[6].length !== 2 ||
            core[11] !== undefined && (!Number.isInteger(core[11]) || core[11] < 0 || core[11] > 2) ||
            core[10] !== undefined && (!(core[10] instanceof Uint8Array) || core[10].length !== this.wm.exports["core_statistics_size"]()) ||
            !(core[7] instanceof Uint32Array) || core[7].length % 2 || core[7].length > 20000) fail();
        ranges.forEach(([start, end], i) => {
            if(!(core[1][i] instanceof Uint8Array) || core[1][i].length !== end - start) fail();
        });
        if(core[12] !== undefined && (!(core[12] instanceof Uint32Array) || core[12].length > 256 * 18 ||
            !this.with_wide_state_buffer(core[12], (pointer, count) => this.wm.exports["x64_tlb_snapshot_validate"](pointer, count)))) fail();
        const pages = new Set();
        for(let i = 0; i < core[7].length; i += 2)
        {
            if(core[7][i] >= 0x100000 || !(core[7][i + 1] & 1) || pages.has(core[7][i])) fail();
            pages.add(core[7][i]);
        }
    }
};

CPU.prototype.set_machine_core_state = function(state)
{
    const ex = this.wm.exports;
    ex["context_reset_all"]();
    ex["core_statistics_reset"]();
    state[6].forEach((saved, id) => {
        const ranges = state[0] === 1 ? CORE_STATE_RANGES_V1 : state[7];
        const fixed = CORE_STATE_RANGES.map(([start, end]) => {
            const index = ranges.findIndex(range => range[0] === start && range[1] === end);
            if(index !== -1) return saved[1][index].slice();
            const bytes = new Uint8Array(end - start);
            if(start <= STATE_OFFSETS.x64_pat && end >= STATE_OFFSETS.x64_pat + 8)
            {
                const view = new DataView(bytes.buffer);
                view.setUint32(STATE_OFFSETS.x64_pat - start, 0x00070406, true);
                view.setUint32(STATE_OFFSETS.x64_pat - start + 4, 0x00070406, true);
            }
            if(start <= STATE_OFFSETS.smbase && end >= STATE_OFFSETS.smbase + 4)
            {
                // (SMBASE's reset value)
                new DataView(bytes.buffer).setUint32(STATE_OFFSETS.smbase - start, 0x30000, true);
            }
            if(start <= STATE_OFFSETS.xcr0 && end >= STATE_OFFSETS.xcr0 + 8)
            {
                // (XCR0's reset value: x87 state only)
                new DataView(bytes.buffer).setUint32(STATE_OFFSETS.xcr0 - start, 1, true);
            }
            return bytes;
        });
        this.cores[id] = { running: saved[0], saved: fixed, slices: saved[8], steps: saved[9] };
        new Uint8Array(this.wasm_memory.buffer, this.apic_addr(id), 184).set(saved[2]);
        new Uint8Array(this.wasm_memory.buffer, ex["apic_aux_addr"](id) >>> 0, ex["apic_aux_size"]()).set(saved[3]);
        this.apic_restore_core_events(id, saved[4], saved[5]);
        this.apic_restore_smi(id, !!saved[13]);
        ex["exception_restore"](id, saved[11] || 0);
        ex["context_tsc_set"](id, saved[6][0], saved[6][1]);
        if(saved[10]) new Uint8Array(this.wasm_memory.buffer, ex["core_statistics_addr"](id) >>> 0, ex["core_statistics_size"]()).set(saved[10]);
        for(let i = 0; i < saved[7].length; i += 2) ex["context_tlb_push"](id, saved[7][i], saved[7][i + 1]);
        if(saved[12]) this.with_wide_state_buffer(saved[12], (pointer, count) => {
            if(!ex["x64_tlb_snapshot_restore"](id, pointer, count)) throw new Error("Cannot restore wide TLB");
        });
    });
    this.active_core = state[2];
    this.apic_set_current_core(this.active_core);
    this.load_core_state(/** @type {!Array<!Uint8Array>} */ (this.cores[this.active_core].saved), true);
    this.cores[this.active_core].saved = null;
    ex["context_install"](this.active_core);
    this.scheduler_quantum = state[3];
    this.scheduler_seed = state[4];
    this.scheduler_round = state[5];
};

CPU.prototype.get_state_pic = function()
{
    const pic_size = 13;
    const pic = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_master(), pic_size);
    const pic_slave = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_slave(), pic_size);

    const state = [];
    const state_slave = [];

    state[0] = pic[0]; // irq_mask
    state[1] = pic[1]; // irq_map
    state[2] = pic[2]; // isr
    state[3] = pic[3]; // irr
    state[4] = pic[4]; // is_master
    state[5] = state_slave;
    state[6] = pic[6]; // expect_icw4
    state[7] = pic[7]; // state
    state[8] = pic[8]; // read_isr
    state[9] = pic[9]; // auto_eoi
    state[10] = pic[10]; // elcr
    state[11] = pic[11]; // irq_value
    state[12] = pic[12]; // special_mask_mode

    state_slave[0] = pic_slave[0]; // irq_mask
    state_slave[1] = pic_slave[1]; // irq_map
    state_slave[2] = pic_slave[2]; // isr
    state_slave[3] = pic_slave[3]; // irr
    state_slave[4] = pic_slave[4]; // is_master
    state_slave[5] = null;
    state_slave[6] = pic_slave[6]; // expect_icw4
    state_slave[7] = pic_slave[7]; // state
    state_slave[8] = pic_slave[8]; // read_isr
    state_slave[9] = pic_slave[9]; // auto_eoi
    state_slave[10] = pic_slave[10]; // elcr
    state_slave[11] = pic_slave[11]; // irq_value
    state_slave[12] = pic_slave[12]; // special_mask_mode

    return state;
};

CPU.prototype.get_state_apic = function()
{
    const APIC_STRUCT_SIZE = 4 * 46; // keep in sync with apic.rs
    return new Uint8Array(this.wasm_memory.buffer, this.get_apic_addr(), APIC_STRUCT_SIZE);
};

CPU.prototype.get_state_ioapic = function()
{
    const IOAPIC_STRUCT_SIZE = 4 * 52; // keep in sync with ioapic.rs
    return new Uint8Array(this.wasm_memory.buffer, this.get_ioapic_addr(), IOAPIC_STRUCT_SIZE);
};

CPU.prototype.validate_state = function(state)
{
    // (snapshots from before machine_type are of i440FX machines)
    const machine = state[103] ? state[103][0] : "i440fx";
    if(machine !== this.platform.machine)
    {
        throw new Error("The snapshot is from a machine with machine_type: \"" + machine +
            "\", this one has \"" + this.platform.machine + "\"");
    }
    this.validate_machine_core_state(state[96]);
    this.validate_physical_state(state[97]);
    this.validate_disk_states(state);
    resolve_virtio_devices_state(this.devices.virtio_devices, state[92]);
    if(this.devices.graphics_adapter)
    {
        this.devices.graphics_adapter.check_state(state[52]);
    }
    else if(this.devices.display && graphics_adapter_of_state(state[52]) !== "none")
    {
        throw new Error("The snapshot is from a machine with graphics_adapter: \"" +
            graphics_adapter_of_state(state[52]) + "\", this one has \"none\"");
    }
    // the network card: its plugin's slot (from before plugins, an untagged
    // slot is the NE2000's own state, which its plugin reads)
    const saved_net = plugin_of_state(NET_PLUGINS, state[59]);
    if(this.devices.net)
    {
        this.devices.net.check_state(state[59]);
    }
    else if(saved_net !== null)
    {
        throw new Error("The snapshot is from a machine with net_device: \"" + saved_net +
            "\", this one has \"" + (this.devices.virtio_net ? "virtio" : "none") + "\"");
    }
    // the sound card likewise (an untagged slot: the SB16's own state)
    const saved_audio = plugin_of_state(AUDIO_PLUGINS, state[61]);
    if(this.devices.audio)
    {
        this.devices.audio.check_state(state[61]);
    }
    else if(saved_audio !== null)
    {
        throw new Error("The snapshot is from a machine with audio_device: \"" + saved_audio + "\", this one has \"none\"");
    }
    // USB: both or neither
    if(this.devices.usb)
    {
        this.devices.usb.check_state(state[107]);
    }
    else if(plugin_of_state(USB_PLUGINS, state[107]) !== null)
    {
        throw new Error("The snapshot is from a machine with usb, this one has none");
    }
    // the TPM: both or neither; its store as a disk's
    if(this.devices.tpm)
    {
        this.devices.tpm.check_state(state[110]);
        check_disk_state("tpm_state", this.tpm_store, state[111]);
    }
    else if(plugin_of_state(TPM_PLUGINS, state[110]) !== null)
    {
        throw new Error("The snapshot is from a machine with a TPM, this one has none");
    }
    // A remapped snapshot must retain the RAM/MMIO split used when validating
    // its windows. Reject this before changing clocks, RAM, or CPU state.
    if(state[97] && state[0] !== this.memory_size[0] &&
        state[97][1].some((word, index) => index % 5 === 4 && word !== 0))
        throw new Error("Snapshot RAM size differs from its physical memory map");
    if(!Number.isSafeInteger(state[0]) || state[0] <= 0 || state[0] > this.mem8.length || state[0] % 4096)
        throw new Error("Invalid snapshot RAM size");
    if((state[98] || 0) !== this.extended_pages)
        throw new Error("Snapshot extended RAM size differs from this machine's");
    // The guest has seen these in CPUID and may use them (snapshots from
    // before them have none): a machine whose features were not chosen
    // (cpu_features not given) takes the snapshot's, set_state
    const features = state[106] || 0;
    if(features !== this.cpu_features && this.cpu_features_explicit)
    {
        const names = mask => Object.keys(CPU_FEATURES).filter(name => mask & 1 << CPU_FEATURES[name].bit).join(" ") || "none";
        throw new Error("The snapshot is from a machine with the CPU features " + names(features) +
            " (cpu_features), this one has " + names(this.cpu_features));
    }
};

/**
 * A snapshot's hard disks must be the images this machine has: the changes
 * of a disk image in a container format are not applied to another image
 * (docs/disk-image-formats-plan.md P1). Checked before anything is restored.
 * @param {!Array<*>} state
 */
CPU.prototype.validate_disk_states = function(state)
{
    // (and a disk written back takes only a reference of its image in the
    // same generation: src/disk_writeback.js)
    const check = (device, saved) =>
    {
        if(!device || !device.buffer || !saved) return;
        // (a hard disk's logical sectors, IDEInterface state 20: its LBAs
        // and the guest's view of it are in them)
        if(!device.is_atapi && !saved[13] && saved[20] !== undefined && saved[20] !== device.sector_size)
        {
            throw new Error("The snapshot's disk " + device.name + " has " + saved[20] + "-byte sectors, this machine's " +
                device.sector_size + "-byte ones: its state cannot be restored onto it");
        }
        check_disk_state(device.buffer.disk_name || device.name, device.buffer, saved[28]);
    };
    const ide = this.devices.ide;
    if(ide)
    {
        const saved = state[85] || [state[56] || state[57]];
        [ide.primary, ide.secondary].forEach((channel, i) =>
        {
            if(!channel || !saved[i]) return;
            check(channel.master, saved[i][0]);
            check(channel.slave, saved[i][1]);
        });
    }
    const ahci = this.devices.ahci;
    if(ahci && state[101])
    {
        ahci.ports.forEach((port, i) => check(port.device, state[101][3][i] && state[101][3][i][17]));
    }
    // (the floppy drives' disks: written back, a reference)
    const fdc = this.devices.fdc;
    if(fdc && state[55])
    {
        fdc.drives.forEach((drive, i) =>
        {
            const saved = state[55][44 + i];
            if(!saved) return;
            if(drive.buffer) check_disk_state(drive.buffer.disk_name || (i ? "fdb" : "fda"), drive.buffer, saved[10]);
            else if(is_writeback_state(saved[10])) throw new Error("The snapshot's floppy " + (i ? "fdb" : "fda") + " was written back; this machine has no disk in that drive");
        });
    }
    // (USB disks with the same id; the others leave or arrive, src/usb/plugin.js)
    for(const [id, saved] of /** @type {!Array<!Array<*>>} */ (state[108] || []))
    {
        const buffer = this.usb_disks && this.usb_disks.get(/** @type {string} */ (id));
        if(buffer) check_disk_state("usb:" + id, buffer, saved);
    }
    const pflash = this.firmware && this.firmware.pflash;
    if(pflash && state[109]) check_disk_state("firmware_vars", pflash.buffer, state[109][2]);
};

CPU.prototype.set_state = function(state, skip_memory = false)
{
    this.validate_state(state);
    // (disk requests held after an I/O error belong to the machine left behind)
    drop_disk_holds(this);
    // (the snapshot's CPU features, where this machine's were the default)
    if((state[106] || 0) !== this.cpu_features)
    {
        this.cpu_features = state[106] || 0;
        this.wm.exports["set_cpu_features"](this.cpu_features);
    }
    if(state[95]) this.clock.set_state(state[95]);
    this.wm.exports["take_clock_progress"]();
    this.wm.exports["set_deterministic_execution"](this.clock.mode === "deterministic");
    this.execution_epoch++;
    this.wm.exports["fpu_discard_cache"]?.();
    this.memory_size[0] = state[0];

    if(this.mem8.length !== this.memory_size[0])
    {
        console.warn("Note: Memory size mismatch. we=" + this.mem8.length + " state=" + this.memory_size[0]);
    }

    if(state[1].length === 8)
    {
        // NOTE: support for old state images; delete this when bumping STATE_VERSION
        this.segment_is_null.set(state[1]);
        this.segment_access_bytes.fill(0x80 | (3 << 5) | 0x10 | 0x02);
        this.segment_access_bytes[REG_CS] = 0x80 | (3 << 5) | 0x10 | 0x08 | 0x02;
    }
    else if(state[1].length === 16)
    {
        this.segment_is_null.set(state[1].subarray(0, 8));
        this.segment_access_bytes.set(state[1].subarray(8, 16));
    }
    else
    {
        dbg_assert("Unexpected cpu segment state length:" + state[1].length);
    }
    this.segment_offsets.set(state[2]);
    this.segment_limits.set(state[3]);

    this.protected_mode[0] = state[4];
    this.idtr_offset[0] = state[5];
    this.idtr_size[0] = state[6];
    this.gdtr_offset[0] = state[7];
    this.gdtr_size[0] = state[8];
    this.cr.set(state[10]);
    this.cpl[0] = state[11];

    this.is_32[0] = state[13];

    this.stack_size_32[0] = state[16];

    this.in_hlt[0] = state[17];
    this.last_virt_eip[0] = state[18];
    this.eip_phys[0] = state[19];

    this.sysenter_cs[0] = state[22];
    this.sysenter_eip[0] = state[23];
    this.sysenter_esp[0] = state[24];
    this.prefixes[0] = state[25];

    this.flags[0] = state[26];
    this.flags_changed[0] = state[27];
    this.last_op1[0] = state[28];

    this.last_op_size[0] = state[30];

    this.instruction_pointer[0] = state[37];
    this.previous_ip[0] = state[38];
    this.reg32.set(state[39]);
    this.sreg.set(state[40]);
    this.dreg.set(state[41]);
    state[42] && this.reg_pdpte.set(state[42]);

    this.set_tsc(state[43][0], state[43][1]);

    this.devices.virtio_9p && this.devices.virtio_9p.set_state(state[45]);
    state[46] && this.set_state_apic(state[46]);
    this.devices.rtc && this.devices.rtc.set_state(state[47]);
    this.devices.dma && this.devices.dma.set_state(state[49]);
    this.devices.acpi && this.devices.acpi.set_state(state[50]);
    // 51 (formerly hpet)
    this.devices.graphics_adapter && this.devices.graphics_adapter.set_state(state[52]);
    this.devices.ps2 && this.devices.ps2.set_state(state[53]);
    this.devices.uart0 && this.devices.uart0.set_state(state[54]);
    this.devices.fdc && this.devices.fdc.set_state(state[55]);

    if((state[56] || state[57]) && this.devices.ide)
    {
        // ide device from older version of v86, only primary: state[56] contains cdrom, state[57] contains hard drive

        const ide_config = [[undefined, undefined], [undefined, undefined]];
        if(state[56])
        {
            ide_config[0][0] = { is_cdrom: true, buffer: this.devices.cdrom.buffer };
        }
        else
        {
            ide_config[0][0] = { is_cdrom: false, buffer: this.devices.ide.primary.master.buffer };

        }
        this.devices.ide = new IDEController(this, this.devices.ide.bus, ide_config);
        this.devices.cdrom = state[56] ? this.devices.ide.primary.master : undefined;
        this.devices.ide.primary.set_state(state[56] || state[57]);
    }
    else if(state[85] && this.devices.ide)
    {
        this.devices.ide.set_state(state[85]);
    }

    this.devices.q35 && state[100] && this.devices.q35.set_state(state[100]);
    this.devices.ahci && state[101] && this.devices.ahci.set_state(state[101]);
    this.devices.hpet && state[102] && this.devices.hpet.set_state(state[102]);
    this.devices.smbus && state[104] && this.devices.smbus.set_state(state[104]);
    this.devices.pci && this.devices.pci.set_state(state[48]);
    // (after the root ports' registers: snapshots from before hot plug have
    // every card in)
    (this.devices.pcie_root_ports || []).forEach((port, i) => {
        port.set_state(state[105] && state[105][i] || [1, port.has_card(), false, false]);
    });

    this.devices.pit && this.devices.pit.set_state(state[58]);
    this.devices.net && this.devices.net.set_state(state[59]);
    this.set_state_pic(state[60]);
    this.devices.audio && this.devices.audio.set_state(state[61]);
    this.devices.usb && this.devices.usb.set_state(state[107]);
    // (the TPM's store first: the TPM powers on from it)
    if(this.devices.tpm)
    {
        restore_disk_state(this.tpm_store, state[111]);
        this.devices.tpm.set_state(state[110]);
    }
    for(const [id, saved] of /** @type {!Array<!Array<*>>} */ (state[108] || []))
    {
        const buffer = this.usb_disks && this.usb_disks.get(/** @type {string} */ (id));
        if(buffer && saved) restore_disk_state(buffer, saved);
    }
    this.firmware && this.firmware.pflash && state[109] && this.firmware.pflash.set_state(state[109]);

    this.devices.uart1 && this.devices.uart1.set_state(state[79]);
    this.devices.uart2 && this.devices.uart2.set_state(state[80]);
    this.devices.uart3 && this.devices.uart3.set_state(state[81]);
    this.devices.virtio_console && this.devices.virtio_console.set_state(state[82]);
    this.devices.virtio_net && this.devices.virtio_net.set_state(state[83]);
    this.devices.virtio_balloon && this.devices.virtio_balloon.set_state(state[84]);
    this.devices.vmware && state[89] && this.devices.vmware.set_state(state[89]);
    this.devices.parallel0 && state[90] && this.devices.parallel0.set_state(state[90]);
    this.devices.parallel1 && state[91] && this.devices.parallel1.set_state(state[91]);
    set_virtio_devices_state(this.devices.virtio_devices,
        resolve_virtio_devices_state(this.devices.virtio_devices, state[92]));

    this.fw_value = state[62];

    state[63] && this.set_state_ioapic(state[63]);

    this.tss_size_32[0] = state[64];

    this.reg_xmm32s.set(state[66]);

    this.fpu_st.set(state[67]);
    this.fpu_stack_empty[0] = state[68];
    this.fpu_stack_ptr[0] = state[69];
    this.fpu_control_word[0] = state[70];
    this.fpu_ip[0] = state[71];
    this.fpu_ip_selector[0] = state[72];
    this.fpu_dp[0] = state[73];
    this.fpu_dp_selector[0] = state[74];
    this.fpu_opcode[0] = state[75];

    // (into the views of the Wasm memory, which must not be replaced)
    if(state[86] !== undefined) this.last_result[0] = state[86][0];
    if(state[87] !== undefined) this.fpu_status_word[0] = state[87][0];
    if(state[88] !== undefined) this.mxcsr[0] = state[88][0];

    if(!skip_memory)
    {
        const bitmap = new Bitmap(state[78].buffer);
        this.unpack_memory(bitmap, state[77]);
        this.clear_extended_memory();
    }

    this.update_state_flags();

    this.full_clear_tlb();

    this.jit_clear_cache();
    this.with_wide_state_buffer(state[97] ? state[97][1] : new Uint32Array(80), (pointer, count) => {
        if(!this.wm.exports["x64_phys_restore_windows"](pointer, count)) throw new Error("Cannot restore physical memory map");
    });
    // configure_high_memory uses slot 0 for the relocated top of RAM
    this.low_memory_size = this.wm.exports["x64_phys_get_window"](0, 4) === 1 &&
        this.wm.exports["x64_phys_get_window"](0, 2) + this.wm.exports["x64_phys_get_window"](0, 3) === this.memory_size[0] ?
        this.wm.exports["x64_phys_get_window"](0, 2) : this.memory_size[0];

    // Older single-core snapshots predate NMI state and APIC enable storage.
    this.apic_enabled[0] = state[94] ? state[94][0] : this.acpi_enabled[0];
    new Uint8Array(this.wasm_memory.buffer)[this.state_base + STATE_OFFSETS.nmi_blocked] = state[94]?.[1] || 0;
    this.apic_restore_core_events(0, state[94]?.[3] || 0, !!state[94]?.[2]);
    this.apic_restore_smi(0, false);
    this.wm.exports["apic_restore_legacy_aux"](0, !!this.apic_enabled[0]);
    new Uint8Array(this.wasm_memory.buffer)[this.state_base + STATE_OFFSETS.interrupt_shadow] = 0;
    if(state[96]) this.set_machine_core_state(state[96]);
    else
    {
        this.wm.exports["core_statistics_reset"]();
        const bytes = new Uint8Array(this.wasm_memory.buffer);
        for(const [start, end] of CORE_STATE_RANGES) if(start >= 1360) bytes.fill(0, this.state_base + start, this.state_base + end);
        new Uint32Array(this.wasm_memory.buffer, this.state_base + STATE_OFFSETS.x64_pat, 2).fill(0x00070406);
        new Uint32Array(this.wasm_memory.buffer, this.state_base + STATE_OFFSETS.smbase, 1)[0] = 0x30000;
        new Uint32Array(this.wasm_memory.buffer, this.state_base + STATE_OFFSETS.xcr0, 2).set([1, 0]);
        this.with_wide_state_buffer(new Uint32Array(0), (pointer, count) => this.wm.exports["x64_tlb_snapshot_restore"](0, pointer, count));
        this.wm.exports["exception_restore"](0, 0);
        this.cores[0].slices = this.cores[0].steps = 0;
    }
    if(!state[95])
    {
        // Legacy snapshots stored host-absolute deadlines without a shared
        // clock anchor. Preserve counts/calendar and restart their phase at
        // restore time, rather than waiting for the old host's uptime.
        const now = this.clock.now();
        this.devices.pit.counter_start_time.fill(now);
        new Float64Array(this.wasm_memory.buffer, this.apic_addr(0) + 24, 1)[0] = now;
        this.clock.wall_epoch_ms = this.devices.rtc.rtc_time - now;
    }

    // Older state images don't record the sources; devices then lower their
    // lines unconditionally, as they used to. Done last: re-deriving the SCI
    // may deliver an interrupt, which needs the complete machine state.
    this.shared_irq_sources.forEach((sources, irq) => {
        sources.clear();
        state[93]?.[irq]?.forEach(source => sources.add(source));
    });
    this.devices.acpi && this.devices.acpi.sync_sci();
    // (a drive present in the snapshot or in this machine only is a hot
    // plug event for the restored guest)
    this.devices.ahci && this.devices.ahci.update_irq();
};

CPU.prototype.set_state_pic = function(state)
{
    // Note: This could exists for compatibility with old state images
    // It should be deleted when the state version changes

    const pic_size = 13;
    const pic = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_master(), pic_size);
    const pic_slave = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_slave(), pic_size);

    pic[0] = state[0]; // irq_mask
    pic[1] = state[1]; // irq_map
    pic[2] = state[2]; // isr
    pic[3] = state[3]; // irr
    pic[4] = state[4]; // is_master
    const state_slave = state[5];
    pic[6] = state[6]; // expect_icw4
    pic[7] = state[7]; // state
    pic[8] = state[8]; // read_isr
    pic[9] = state[9]; // auto_eoi
    pic[10] = state[10]; // elcr
    pic[11] = state[11]; // irq_value (undefined in old state images)
    pic[12] = state[12]; // special_mask_mode (undefined in old state images)

    pic_slave[0] = state_slave[0]; // irq_mask
    pic_slave[1] = state_slave[1]; // irq_map
    pic_slave[2] = state_slave[2]; // isr
    pic_slave[3] = state_slave[3]; // irr
    pic_slave[4] = state_slave[4]; // is_master
    // dummy
    pic_slave[6] = state_slave[6]; // expect_icw4
    pic_slave[7] = state_slave[7]; // state
    pic_slave[8] = state_slave[8]; // read_isr
    pic_slave[9] = state_slave[9]; // auto_eoi
    pic_slave[10] = state_slave[10]; // elcr
    pic_slave[11] = state_slave[11]; // irq_value (undefined in old state images)
    pic_slave[12] = state_slave[12]; // special_mask_mode (undefined in old state images)
};

// keep in sync with apic.rs
const CORE_EVENT_INIT = 1;
const CORE_EVENT_SIPI = 2;

/**
 * Cores of a single-socket machine (docs/multicore.md).
 * They run one at a time on this Wasm instance: the scheduler
 * (run_cores) switches the active core at main-loop boundaries with
 * save_core_state/load_core_state; each core has its own local APIC.
 */
CPU.prototype.setup_cores = function()
{
    const count = this.platform.cores;
    this.apic_set_core_count(count);
    this.wm.exports["context_reset_all"]();
    this.wm.exports["core_statistics_reset"]();
    this.core_reset_state = this.save_core_state();
    this.active_core = 0;
    // the BSP runs from reset; the APs wait for INIT and a start-up IPI
    this.cores = Array.from({ length: count }, (_, i) => ({ running: i === 0, saved: i === 0 ? null : this.core_reset_state,
        slices: 0, steps: 0 }));
};

/** Machine reset: the BSP becomes the active core and the APs wait for a start-up IPI again */
CPU.prototype.reset_cores = function()
{
    this.switch_core(0);
    this.apic_set_core_count(this.cores.length);
    this.wm.exports["context_reset_all"]();
    this.wm.exports["core_statistics_reset"]();
    this.execution_epoch++;
    this.scheduler_round = 0;
    this.cores.forEach((core, i) => {
        core.running = i === 0;
        core.saved = i === 0 ? null : this.core_reset_state;
        core.slices = 0;
        core.steps = 0;
    });
};

/** @param {number} core */
CPU.prototype.switch_core = function(core)
{
    if(core === this.active_core)
    {
        return;
    }
    this.cores[this.active_core].saved = this.save_core_state();
    this.wm.exports["context_switch"](this.active_core, core);
    this.load_core_state(/** @type {!Array<!Uint8Array>} */ (this.cores[core].saved), true);
    this.cores[core].saved = null;
    this.active_core = core;
    this.apic_set_current_core(core);
};

/**
 * INIT and start-up IPIs sent to a core since it was last scheduled
 * @param {number} core
 */
CPU.prototype.take_core_events = function(core)
{
    const events = this.apic_take_core_events(core);
    if(!events)
    {
        return;
    }
    const state = this.cores[core];

    if(events & CORE_EVENT_INIT)
    {
        if(this.wm.exports["exception_shutdown"](core) === 2) return;
        dbg_log("core " + core + ": INIT", LOG_CPU);
        this.apic_init_core(core);
        this.wm.exports["context_reset"](core);
        // INIT leaves the x87, SSE and XSAVE state, the PAT, the MTRRs, the
        // machine-check banks and SMBASE alone (SDM Vol.3A, "Processor States
        // Following Power-up, Reset, or INIT"; INIT_PRESERVED); everything
        // else takes its reset value
        const next = this.core_reset_state.map(bytes => bytes.slice());
        const current = core === this.active_core ? this.save_core_state() : state.saved;
        if(current) for(const [offset, size] of INIT_PRESERVED)
        {
            const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
            const at = offset - CORE_STATE_RANGES[index][0];
            next[index].set(current[index].subarray(at, at + size), at);
        }
        if(core === this.active_core)
        {
            this.load_core_state(next);
        }
        else
        {
            state.saved = next;
        }
        // an AP waits for a start-up IPI; the BSP restarts at the reset vector
        state.running = core === 0;
    }

    if((events & CORE_EVENT_SIPI) && !state.running)
    {
        // real mode at vector * 0x1000
        const vector = events >> 8 & 0xFF;
        dbg_log("core " + core + ": start-up IPI, vector " + h(vector, 2), LOG_CPU);
        this.switch_core(core);
        this.sreg[REG_CS] = vector << 8;
        this.segment_offsets[REG_CS] = vector << 12;
        this.instruction_pointer[0] = vector << 12;
        this.previous_ip[0] = vector << 12;
        this.update_state_flags();
        state.running = true;
    }
};

/**
 * Whether a core that is not the active one can make progress: it is not
 * halted, or it is halted with interrupts enabled and one pending
 * @param {number} core
 */
CPU.prototype.core_runnable = function(core)
{
    const state = this.cores[core];
    if(!state.running)
    {
        return false;
    }
    // Read a field of the live or saved core without switching it in.
    const field = (offset, size) => {
        if(core === this.active_core)
        {
            const view = new DataView(this.wasm_memory.buffer, this.state_base + offset, size);
            return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
        }
        const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
        dbg_assert(index !== -1);
        const view = new DataView(state.saved[index].buffer, offset - CORE_STATE_RANGES[index][0], size);
        return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
    };
    const nmi = !!this.apic_core_nmi_pending(core) && !field(STATE_OFFSETS.nmi_blocked, 1);
    // (an SMI waits while the core is in SMM: smm_state bit 0)
    const smi = !!this.apic_core_smi_pending(core) && !(field(STATE_OFFSETS.smm_state, 4) & 1);
    const shutdown = this.wm.exports["exception_shutdown"](core);
    if(shutdown) return shutdown === 1 && (nmi || smi);
    const halted = field(STATE_OFFSETS.in_hlt, 1) !== 0;
    if(!halted)
    {
        return true;
    }
    const interrupts_enabled = (field(STATE_OFFSETS.flags, 4) & FLAG_INTERRUPT) !== 0;
    // The BSP also accepts the legacy PIC, which is checked in run_cpu_slice.
    return nmi || smi || interrupts_enabled && this.apic_core_interrupt_pending(core);
};

/**
 * Run each core for a bounded slice, rotating or seeded round robin. Dispatch
 * budgets bound host work; deterministic time separately counts committed work.
 * @return {number} milliseconds until the machine needs to run again
 */
/**
 * Whether the guest turned the machine off (ACPI S5 or S4): the machine's
 * power hook (src/main.js; docs/arm64-virt-android16-plan.md P1.8)
 * @return {boolean}
 */
CPU.prototype.powered_off = function()
{
    return !!this.devices?.acpi?.soft_off;
};

CPU.prototype.run_cores = function()
{
    if(this.parallel)
    {
        return this.run_parallel();
    }
    if(this.devices.acpi?.sleeping)
    {
        // S3: no core runs; the device timers do (an RTC alarm may wake us)
        const now = this.clock.now();
        const next = this.run_hardware_timers(!!this.acpi_enabled[0], now);
        if(!this.devices.acpi.sleeping) return 0;
        if(this.clock.mode === "deterministic")
        {
            this.clock.advance_to(Math.max(this.clock.now(), now + Math.min(next, 100)));
            return 0;
        }
        return Math.min(next, 100);
    }
    if(this.cores.length === 1 && this.clock.mode !== "deterministic")
    {
        this.take_core_events(0);
        return this.main_loop();
    }
    // Always service the shared devices, even if every core is in CLI/HLT.
    // AP execution never advances the machine's timers a second time.
    const now = this.clock.now();
    let next = this.run_hardware_timers(!!this.acpi_enabled[0], now);
    let ran = false;
    let start = this.scheduler_round++ % this.cores.length;
    if(this.scheduler_seed)
    {
        let seed = this.scheduler_seed | 0;
        seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
        this.scheduler_seed = seed >>> 0;
        start = this.scheduler_seed % this.cores.length;
    }
    for(let turn = 0; turn < this.cores.length; turn++)
    {
        const core = (start + turn) % this.cores.length;
        this.take_core_events(core);
        if(!this.core_runnable(core))
        {
            continue;
        }
        this.switch_core(core);
        const state = this.cores[core];
        const epoch = this.execution_epoch;
        const steps = this.run_cpu_slice(this.scheduler_quantum);
        if(epoch !== this.execution_epoch) return 0;
        state.steps += steps;
        state.slices++;
        ran = true;
        if(!this.in_hlt[0]) next = 0;
    }
    // An AP may have just interrupted a core whose turn was earlier in this
    // round. Do not sleep until a device timer before scheduling that core.
    if(this.cores.some((_, core) => this.apic_peek_core_events(core) ||
        this.core_runnable(core) && (this.apic_core_interrupt_pending(core) ||
            this.apic_core_nmi_pending(core) || this.apic_core_smi_pending(core)))) next = 0;
    this.clock.now();
    // The guest may have reprogrammed a timer before HLT. Recompute its
    // deadline next round before sleeping or advancing deterministic time.
    if(ran) next = 0;
    if(this.clock.mode === "deterministic" && next > 0 && Number.isFinite(next))
    {
        this.clock.advance_to(Math.max(this.clock.now(), now + next));
        return 0;
    }
    return next;
};

/**
 * Host-parallel execution (src/parallel/machine.js): the application
 * processors run in vCPU workers; this thread runs the BSP and the devices,
 * serves the workers' I/O and stops them at safe points when the machine
 * pauses, sleeps, resets or takes a snapshot.
 * @param {{bytes: Uint8Array, settings: Object, worker_url: (string|URL)}} options
 */
CPU.prototype.start_parallel = async function(options)
{
    dbg_assert(this.cores.length > 1 && this.clock.mode !== "deterministic");
    this.parallel = new ParallelMachine(this, options);
    await this.parallel.start();
};

/** @return {number} milliseconds until the machine needs to run again */
CPU.prototype.run_parallel = function()
{
    const machine = this.parallel;
    // (a failed vCPU stops the machine: see v86.prototype.do_tick)
    if(machine.check_failure()) return 0;
    machine.service();
    if(machine.pending_reset)
    {
        machine.request_stop();
        if(!machine.all_parked()) return 0;
        const { reason, keep_memory } = machine.pending_reset;
        machine.pending_reset = null;
        this.reboot_internal(reason, keep_memory);
        return 0;
    }
    if(this.devices.acpi?.sleeping)
    {
        // S3: every core stops; the device timers run (an RTC alarm may wake us)
        machine.request_stop();
        const now = this.clock.now();
        const next = this.run_hardware_timers(!!this.acpi_enabled[0], now);
        return this.devices.acpi.sleeping ? Math.min(next, 100) : 0;
    }
    if(machine.stopping())
    {
        machine.resume();
    }
    // (this core takes other cores' code publications and writes, see
    // crate::parallel::code; while it is halted between ticks it counts as idle)
    this.wm.exports["parallel_idle"](false);
    this.take_core_events(0);
    const t = this.main_loop();
    machine.service();
    if(this.in_hlt[0] && t > 0) this.wm.exports["parallel_idle"](true);
    return t;
};

/** Copy the parked workers' cores into this.cores, the format of a cooperative machine */
CPU.prototype.parallel_capture = function()
{
    const machine = this.parallel, ex = this.wm.exports;
    dbg_assert(machine.all_parked() && this.active_core === 0);
    for(let core = 1; core < this.cores.length; core++)
    {
        const counters = machine.core_counters(core);
        this.cores[core] = { running: machine.core_running(core), saved: machine.read_core(core),
            slices: counters.slices, steps: counters.steps };
        const [low, high] = machine.core_tsc_offset(core);
        ex["context_tsc_set"](core, low, high);
    }
};

/** Hand restored cores (this.cores) to the parked workers */
CPU.prototype.parallel_install = function()
{
    const machine = this.parallel, ex = this.wm.exports;
    dbg_assert(machine.all_parked());
    this.switch_core(0);
    for(let core = 1; core < this.cores.length; core++)
    {
        machine.write_core(core, this.cores[core].saved);
        machine.set_core_running(core, this.cores[core].running);
        machine.set_core_tsc_offset(core, [ex["context_tsc_get"](core, false) >>> 0, ex["context_tsc_get"](core, true) >>> 0]);
    }
    machine.schedule(COMMAND_RELOAD);
};

/**
 * The per-core part of the CPU state (CORE_STATE_RANGES, from
 * gen/state_layout.js), for switching the active core. Only valid at a
 * main-loop safe point, when no generated code or helper is running.
 * Local APIC, TSC and TLB state are saved separately by the machine scheduler.
 * @return {!Array<!Uint8Array>}
 */
CPU.prototype.save_core_state = function()
{
    // The x87 shadow cache is not core state: write it back into fpu_st
    this.wm.exports["fpu_cache_barrier"]();
    const memory = new Uint8Array(this.wasm_memory.buffer);
    return CORE_STATE_RANGES.map(([start, end]) => memory.slice(this.state_base + start, this.state_base + end));
};

/**
 * Make a core saved by save_core_state the active one. State derived from
 * the previous core is dropped: the TLB (which also resets the EIP
 * translation cache), the cached state flags and the x87 shadow cache.
 * Compiled code stays valid: it reads the state at the fixed addresses and
 * re-checks the TLB and mode on entry.
 * @param {!Array<!Uint8Array>} saved
 * @param {boolean=} preserve_tlb
 */
CPU.prototype.load_core_state = function(saved, preserve_tlb)
{
    dbg_assert(saved.length === CORE_STATE_RANGES.length);
    this.wm.exports["fpu_discard_cache"]();
    const memory = new Uint8Array(this.wasm_memory.buffer);
    CORE_STATE_RANGES.forEach(([start], i) => memory.set(saved[i], this.state_base + start));
    if(!preserve_tlb) this.full_clear_tlb();
    this.update_state_flags();
};

/**
 * A snapshot of the machine for diagnosing hangs and failed tests: CPU mode
 * and registers, interrupt controllers, ACPI device and tables. Plain data
 * (JSON-serializable); the format may grow (per-core entries with SMP).
 * @return {!Object}
 */
CPU.prototype.get_diagnostics = function()
{
    const hex = x => "0x" + (x >>> 0).toString(16);
    const eflags = this.get_eflags();
    const cr0 = this.cr[0];
    const cs_base = this.segment_offsets[1];
    const mode = !this.protected_mode[0] ? "real" : eflags & 1 << 17 ? "vm86" : this.is_32[0] ? "protected32" : "protected16";

    const apic = new Int32Array(this.wasm_memory.buffer, this.get_apic_addr(), 46);
    const bits = words => {
        const vectors = [];
        for(let i = 0; i < 256; i++) if(words[i >> 5] >>> (i & 31) & 1) vectors.push(i);
        return vectors;
    };
    const pic = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_master(), 13);
    const pic_slave = new Uint8Array(this.wasm_memory.buffer, this.get_pic_addr_slave(), 13);

    const acpi = this.devices && this.devices.acpi;
    const tables = this.acpi_enabled[0] ? locate_acpi_tables(this.mem8) : null;

    // per core: the active one from the live state, the others from their saved state
    const cores = this.cores.map((state, core) => {
        const field = (offset, size) => {
            if(core === this.active_core || this.parallel && core !== 0)
            {
                // (a core in a worker: its live state, read while it runs)
                const base = core === this.active_core ? this.state_base : this.parallel.state_base(core);
                const view = new DataView(this.wasm_memory.buffer, base + offset, size);
                return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
            }
            const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
            const view = new DataView(state.saved[index].buffer, offset - CORE_STATE_RANGES[index][0], size);
            return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
        };
        const lapic = new Int32Array(this.wasm_memory.buffer, this.apic_addr(core), 46);
        return {
            "state": this.wm.exports["exception_shutdown"](core) ? "shutdown" :
                !(this.parallel && core ? this.parallel.core_running(core) : state.running) ? "wait-for-sipi" :
                field(STATE_OFFSETS.in_hlt, 1) ? "halted" : "runnable",
            "slices": this.parallel && core ? this.parallel.core_counters(core).slices : state.slices,
            "interpreter_steps": this.parallel && core ? this.parallel.core_counters(core).steps : state.steps,
            "retired_instructions": this.wm.exports["core_statistics_get"](core, 0),
            "rep_elements": this.wm.exports["core_statistics_get"](core, 1),
            "faults": this.wm.exports["core_statistics_get"](core, 2),
            "halt_count": this.wm.exports["core_statistics_get"](core, 3),
            "runtime_ms": this.wm.exports["core_statistics_get"](core, 4),
            "ipi_sent": this.wm.exports["apic_core_ipi_sent"](core) >>> 0,
            "ipi_received": this.wm.exports["apic_core_ipi_received"](core) >>> 0,
            "apic_id": lapic[0] >>> 24,
            "apic_irr": bits(lapic.subarray(16, 24)),
            "apic_isr": bits(lapic.subarray(24, 32)),
            "apic_tpr": lapic[13],
            "halted": !!field(STATE_OFFSETS.in_hlt, 1),
            "interrupts_enabled": !!(field(STATE_OFFSETS.flags, 4) & FLAG_INTERRUPT),
            "linear_ip": hex(field(STATE_OFFSETS.instruction_pointer, 4)),
            "cs": hex(field(STATE_OFFSETS.sreg + 2, 4) & 0xFFFF),
            "cr0": hex(field(STATE_OFFSETS.cr, 4)),
        };
    });

    return {
        "active_core": this.active_core,
        "cores": cores,
        "parallel": this.parallel ? this.parallel.status() : null,
        // how the cores run: "parallel" (vCPU workers) or "cooperative", and why not parallel
        "execution": { "mode": this.parallel ? "parallel" : "cooperative", "fallback": this.parallel_fallback || null },
        "clock": Object.assign({ "mode": this.clock.mode, "now_ms": this.clock.now() }, this.clock.get_diagnostics()),
        "scheduler": { "quantum": this.scheduler_quantum, "seed": this.scheduler_seed, "round": this.scheduler_round },
        "cpu": {
            "mode": mode,
            "paging": !!(cr0 & 1 << 31),
            "pae": !!(this.cr[4] & 1 << 5),
            "cs": hex(this.sreg[1]),
            "eip": hex(this.instruction_pointer[0] - cs_base),
            "linear_ip": hex(this.instruction_pointer[0]),
            "eflags": hex(eflags),
            "cpl": this.cpl[0],
            "cr0": hex(cr0),
            "cr3": hex(this.cr[3]),
            "cr4": hex(this.cr[4]),
            "halted": !!this.in_hlt[0],
        },
        "apic": this.acpi_enabled[0] ? {
            "id": apic[0] >>> 24,
            "enabled": !!this.apic_enabled[0],
            "software_enabled": !!(apic[40] & 0x100),
            "tpr": apic[13],
            "irr": bits(apic.subarray(16, 24)),
            "isr": bits(apic.subarray(24, 32)),
            "lvt_timer": hex(apic[8]),
            "lvt_lint0": hex(apic[10]),
            "lvt_lint1": hex(apic[11]),
        } : null,
        "pic": {
            "master": { "irr": hex(pic[3]), "isr": hex(pic[2]), "enabled": hex(pic[0]), "elcr": hex(pic[10]) },
            "slave": { "irr": hex(pic_slave[3]), "isr": hex(pic_slave[2]), "enabled": hex(pic_slave[0]), "elcr": hex(pic_slave[10]) },
        },
        "shared_irq_sources": Object.fromEntries(this.shared_irq_sources
            .map((sources, irq) => [irq, Array.from(sources)]).filter(([, sources]) => sources.length)),
        "acpi": acpi ? {
            "pm_base": acpi.pm_base === -1 ? null : hex(acpi.pm_base),
            "sci_enabled": !!(acpi.pm1_cnt & 1),
            "sci_level": acpi.sci_level,
            "pm1_sts": hex(acpi.pm1_sts),
            "pm1_en": hex(acpi.pm1_en),
            "gpe_sts": hex(acpi.gpe_sts),
            "gpe_en": hex(acpi.gpe_en),
            "soft_off": acpi.soft_off,
        } : null,
        "acpi_tables": tables && {
            "rsdp": hex(tables.rsdp),
            "revision": tables.revision,
            "oem_id": tables.oem_id,
            "tables": tables.tables.map(t => ({ "signature": t.signature, "address": hex(t.address), "length": t.length, "checksum_ok": t.checksum_ok })),
        },
    };
};

CPU.prototype.set_state_apic = function(state)
{
    const APIC_STRUCT_SIZE = 4 * 46; // keep in sync with apic.rs
    const IOAPIC_CONFIG_MASKED = 1 << 16;

    if(state instanceof Array)
    {
        // old js state image; delete this code path when the state version changes
        const apic = new Int32Array(this.wasm_memory.buffer, this.get_apic_addr(), APIC_STRUCT_SIZE >> 2);
        apic[0] = state[0]; // apic_id
        apic[1] = state[1]; // timer_divier
        apic[2] = state[2]; // timer_divider_shift
        apic[3] = state[3]; // timer_initial_count
        apic[4] = state[4]; // timer_current_count
        // skip next_tick (in js: state[4]; in rust: apic[6] and apic[7])
        apic[8] = state[6]; // lvt_timer
        apic[9] = state[7]; // lvt_perf_counter
        apic[10] = state[8]; // lvt_int0
        apic[11] = state[9]; // lvt_int1
        apic[12] = state[10]; // lvt_error
        apic[13] = state[11]; // tpr
        apic[14] = state[12]; // icr0
        apic[15] = state[13]; // icr1
        apic.set(state[15], 16); // irr
        apic.set(state[15], 24); // isr
        apic.set(state[16], 32); // tmr
        apic[40] = state[17]; // spurious_vector
        apic[41] = state[18]; // destination_format
        apic[42] = state[19]; // local_destination
        apic[43] = state[20]; // error
        apic[44] = state[21]; // read_error
        apic[45] = state[22] || IOAPIC_CONFIG_MASKED; // lvt_thermal_sensor
    }
    else
    {
        const apic = new Uint8Array(this.wasm_memory.buffer, this.get_apic_addr(), APIC_STRUCT_SIZE);
        dbg_assert(state instanceof Uint8Array);
        dbg_assert(state.length === apic.length); // later versions might need to handle state upgrades here
        apic.set(state);
    }
};

CPU.prototype.set_state_ioapic = function(state)
{
    const IOAPIC_STRUCT_SIZE = 4 * 52; // keep in sync with ioapic.rs

    if(state instanceof Array)
    {
        // old js state image; delete this code path when the state version changes
        dbg_assert(state[0].length === 24);
        dbg_assert(state[1].length === 24);
        dbg_assert(state.length === 6);
        const ioapic = new Int32Array(this.wasm_memory.buffer, this.get_ioapic_addr(), IOAPIC_STRUCT_SIZE >> 2);
        ioapic.set(state[0], 0); // ioredtbl_config
        ioapic.set(state[1], 24); // ioredtbl_destination
        ioapic[48] = state[2]; // ioregsel
        ioapic[49] = state[3]; // ioapic_id
        ioapic[50] = state[4]; // irr
        ioapic[51] = state[5]; // irq_value
    }
    else
    {
        const ioapic = new Uint8Array(this.wasm_memory.buffer, this.get_ioapic_addr(), IOAPIC_STRUCT_SIZE);
        dbg_assert(state instanceof Uint8Array);
        dbg_assert(state.length === ioapic.length); // later versions might need to handle state upgrades here
        ioapic.set(state);
    }
};

CPU.prototype.pack_memory = function()
{
    dbg_assert((this.mem8.length & 0xFFF) === 0);

    const page_count = this.mem8.length >> 12;
    const nonzero_pages = [];
    for(let page = 0; page < page_count; page++)
    {
        if(!this.is_memory_zeroed(page << 12, 0x1000))
        {
            nonzero_pages.push(page);
        }
    }

    // (only single-buffer snapshots pack RAM: streams write it page by page)
    const packed_size = nonzero_pages.length * 0x1000;
    if(packed_size > STATE_MAX_SINGLE_BUFFER)
    {
        throw new RangeError("The state (" + Math.ceil(packed_size / 1048576) + " MB of RAM) is larger than a " +
            "single-buffer snapshot can be (2 GiB): use save_state_stream");
    }
    const bitmap = new Bitmap(page_count);
    const packed_memory = new Uint8Array(packed_size);

    for(const [i, page] of nonzero_pages.entries())
    {
        bitmap.set(page, 1);

        const offset = page << 12;
        const page_contents = this.mem8.subarray(offset, offset + 0x1000);
        packed_memory.set(page_contents, i << 12);
    }

    return { bitmap, packed_memory };
};

CPU.prototype.unpack_memory = function(bitmap, packed_memory)
{
    this.zero_memory(0, this.memory_size[0]);

    const page_count = this.memory_size[0] >> 12;
    let packed_page = 0;

    for(let page = 0; page < page_count; page++)
    {
        if(bitmap.get(page))
        {
            const offset = packed_page << 12;
            const view = packed_memory.subarray(offset, offset + 0x1000);
            this.mem8.set(view, page << 12);
            packed_page++;
        }
    }
};

/** @param {function():number} run @return {number} */
CPU.prototype.execute_cpu = function(run)
{
    const core = this.active_core;
    const start = v86.microtick();
    this.in_cpu = true;
    try { return run(); }
    finally
    {
        this.in_cpu = false;
        this.wm.exports["core_statistics_runtime"](core, Math.max(0, v86.microtick() - start));
        if(this.wm.exports["exception_take_bsp_reset"]())
        {
            this.reset_pending = true;
            this.note_reset("triple-fault");
        }
        if(this.reset_pending)
        {
            this.reset_pending = false;
            this.reboot_internal();
        }
    }
};

/**
 * Diagnostics only: why and where the last board reset was requested.
 * @param {string} reason
 */
CPU.prototype.note_reset = function(reason)
{
    const d = this.get_diagnostics().cpu;
    const high = new Uint32Array(this.wasm_memory.buffer, this.state_base + STATE_OFFSETS.x64_rip_hi, 1)[0];
    this.last_reset = {
        "reason": reason, "count": (this.last_reset ? this.last_reset["count"] : 0) + 1,
        "rip": "0x" + (BigInt(high) << 32n | BigInt(this.instruction_pointer[0] >>> 0)).toString(16),
        "mode": d["mode"], "cs": d["cs"], "cpl": d["cpl"], "cr3": d["cr3"], "cr2": "0x" + (this.cr[2] >>> 0).toString(16),
        "active_core": this.active_core,
    };
    const words = new Uint32Array(this.wasm_memory.buffer, this.state_base + STATE_OFFSETS.x64_idtr_base_hi, 2);
    const base = (high, low) => "0x" + (BigInt(high >>> 0) << 32n | BigInt(low >>> 0)).toString(16);
    this.last_reset["gdtr"] = [base(words[1], this.gdtr_offset[0]), this.gdtr_size[0]];
    this.last_reset["idtr"] = [base(words[0], this.idtr_offset[0]), this.idtr_size[0]];
    const log = this.wm.exports["x64_fault_log"];
    if(log)
    {
        const hex = (index, field) => "0x" + (BigInt(log(index, field, true) >>> 0) << 32n | BigInt(log(index, field, false) >>> 0)).toString(16);
        this.last_reset["x64_faults"] = [];
        for(let i = 0; i < 6; i++)
        {
            if(!log(i, 2, true) && !log(i, 2, false)) break;
            this.last_reset["x64_faults"].push({ "vector": log(i, 0, false), "error": hex(i, 1), "rip": hex(i, 2), "address": hex(i, 3), "rsp": hex(i, 4), "cs": hex(i, 5) });
        }
    }
};

/** @param {string=} reason */
/**
 * S3 entered (ACPI): stop executing at the end of the current instruction.
 * run_cores then only services device timers until a wake event.
 */
CPU.prototype.enter_sleep = function()
{
    this.wm.exports["request_core_yield"]();
};

/**
 * Wake from S3: CPUs and devices are reset as on a hardware reset, but RAM
 * and the shadowed BIOS (with SeaBIOS's "POST ran" flag) are kept, so the
 * firmware takes its resume path.
 */
CPU.prototype.resume_from_sleep = function()
{
    this.reboot_internal("s3-wake", true);
};

/**
 * @param {string=} reason
 * @param {boolean=} keep_memory wake from S3: do not reload the firmware
 */
CPU.prototype.reboot_internal = function(reason, keep_memory)
{
    if(reason) this.note_reset(reason);
    // A guest CF9/8042 OUT finishes before architectural state is replaced.
    if(this.in_cpu)
    {
        this.reset_pending = true;
        this.wm.exports["request_core_yield"]();
        return;
    }
    if(this.parallel && !this.parallel.all_parked())
    {
        // the application processors stop first (see run_parallel)
        this.parallel.pending_reset = { reason, keep_memory };
        this.parallel.request_stop();
        this.stop_idling();
        return;
    }
    if(this.parallel)
    {
        this.parallel.schedule(COMMAND_RESET);
    }
    this.clock.now();
    this.reset_cores();
    this.wm.exports["reset_interrupt_controllers"]();
    this.reset_cpu();
    this.wm.exports["context_reset_all"]();

    this.fw_value = [];

    if(this.devices.pci)
    {
        this.devices.pci.reset();
    }
    for(const port of this.devices.pcie_root_ports || [])
    {
        port.reset();
    }
    if(this.devices.acpi)
    {
        this.devices.acpi.reset();
    }
    if(this.devices.q35)
    {
        this.devices.q35.reset();
    }
    if(this.devices.hpet)
    {
        this.devices.hpet.reset();
    }
    if(this.devices.smbus)
    {
        this.devices.smbus.reset();
    }

    // Like PCIRST#, a reset deasserts every level-triggered source
    this.shared_irq_sources.forEach((sources, irq) => {
        if(sources.size)
        {
            sources.clear();
            // (16-23: IOAPIC-only inputs)
            irq < 16 ? this.device_lower_irq(irq) : this.ioapic_lower_irq(irq);
        }
    });

    // (disk I/O still in flight must not reach the machine that starts now)
    if(this.devices.ide)
    {
        this.devices.ide.reset();
    }
    if(this.devices.ahci)
    {
        this.devices.ahci.reset();
    }
    if(this.devices.ahci_test)
    {
        this.devices.ahci_test.reset();
    }
    if(this.devices.dma)
    {
        this.devices.dma.cancel_transfers();
    }

    if(this.devices.virtio_9p)
    {
        this.devices.virtio_9p.reset();
    }
    if(this.devices.virtio_console)
    {
        this.devices.virtio_console.reset();
    }
    if(this.devices.virtio_net)
    {
        this.devices.virtio_net.reset();
    }
    if(this.devices.ps2)
    {
        this.devices.ps2.reset();
    }
    for(const device of this.devices.virtio_devices || [])
    {
        device.reset();
    }
    if(this.devices.graphics_adapter)
    {
        this.devices.graphics_adapter.reset();
    }
    if(this.devices.net)
    {
        this.devices.net.reset();
    }
    if(this.devices.audio)
    {
        this.devices.audio.reset();
    }
    if(this.devices.usb)
    {
        this.devices.usb.reset();
    }
    if(this.devices.tpm)
    {
        this.devices.tpm.reset();
    }

    if(keep_memory)
    {
        return;
    }

    if(reason === "power-on")
    {
        // Power was off (ACPI S4/S5): RAM does not keep its contents. A guest
        // resuming from S4 has to restore itself from disk. (A raw fill does
        // not reach the JIT's write notification: drop all compiled code.)
        this.zero_memory(0, this.memory_size[0]);
        this.clear_extended_memory();
        this.jit_clear_cache();
        this.full_clear_tlb();
    }

    this.load_bios();

    if(this.reload_direct_boot_kernel)
    {
        this.reload_direct_boot_kernel();
    }
};

/**
 * The storage device behind a configured drive name ("hda", "hdb",
 * "cdrom"): an IDE interface, or the device on an AHCI port. Every one has
 * `buffer`; the CD drive also has has_disk/set_cdrom/eject. Undefined for a
 * drive the machine does not have.
 * @param {string} name
 * @return {?}
 */
CPU.prototype.disk_device = function(name)
{
    const devices = this.devices;
    if(devices.ahci)
    {
        return devices.ahci.disk_device(name);
    }
    const ide = devices.ide;
    switch(name)
    {
        case "hda": return ide && ide.primary ? ide.primary.master : undefined;
        case "hdb": return ide && ide.primary ? ide.primary.slave : undefined;
        case "cdrom": return devices.cdrom;
    }
    return undefined;
};

/**
 * Every storage device that can hold a disk, with a name for diagnostics
 * @return {!Array<!Array<?>>} [name, device] pairs
 */
CPU.prototype.disk_devices = function()
{
    const devices = this.devices;
    // (USB disks: "usb:" and the disk's id)
    const usb = this.usb_disks ? Array.from(this.usb_disks, ([id, buffer]) => ["usb:" + id, { buffer, sector_size: 512 }]) : [];
    if(devices.ahci)
    {
        return devices.ahci.disk_devices().concat(usb);
    }
    const ide = devices.ide;
    return [["hda", ide?.primary?.master], ["hdb", ide?.primary?.slave],
        ["cdrom", ide?.secondary?.master], ["secondary_slave", ide?.secondary?.slave]].filter(([, device]) => device).concat(usb);
};

/**
 * Drive a level-triggered interrupt source that may share its line with
 * others (ACPI SCI, PCI INTx). The line stays asserted until every source on
 * it has deasserted. Devices that own their line exclusively keep calling
 * device_raise_irq/device_lower_irq directly.
 * @param {number} irq
 * @param {number} source unique per device: pci_id for PCI functions
 * @param {boolean} level
 */
CPU.prototype.set_shared_irq_level = function(irq, source, level)
{
    const sources = this.shared_irq_sources[irq];

    if(level)
    {
        sources.add(source);
        this.device_raise_irq(irq);
    }
    else
    {
        sources.delete(source);
        if(sources.size === 0)
        {
            this.device_lower_irq(irq);
        }
    }
};

/**
 * The storage of the Q35 machine: the ICH9 AHCI controller (00:1f.2) with
 * hda on port 0, hdb on port 1 and an ATAPI drive on port 2 that holds cdrom
 * (empty without it)
 * @param {Object} settings
 * @param {BusConnector} device_bus
 */
CPU.prototype.create_q35_storage = function(settings, device_bus)
{
    this.devices.ahci = new AHCIController(this, device_bus, [
        settings.hda ? { buffer: settings.hda } : undefined,
        settings.hdb ? { buffer: settings.hdb } : undefined,
        { buffer: settings.cdrom, is_cdrom: true },
    ]);
    this.devices.cdrom = this.devices.ahci.disk_device("cdrom");
};

/**
 * A device plugin's timer (src/device_plugin.js, add_timer)
 * @param {function(number):number} timer
 */
CPU.prototype.add_device_timer = function(timer)
{
    this.device_timers.push(timer);
};

/**
 * The network card of a plugin (net_device.type "ne2k", "e1000"): the PCI
 * slot of the NE2000 (or the one behind its root port), net0 of the network bus
 * @param {!Object} settings
 * @param {BusConnector} bus
 * @return {!PluginDevice}
 */
CPU.prototype.create_net_plugin = function(settings, bus)
{
    const id = 0;
    const pci_id = this.root_port_pci_id("net");
    return new PluginDevice(this, NET_PLUGINS, settings.net_device_plugin,
        pci_id !== undefined ? pci_id : pci_functions(this.platform).ne2k, {
            "net": {
                "id": id,
                // a frame to the network; its MAC address to the backend
                "send": data =>
                {
                    bus.send("net" + id + "-send", data);
                    bus.send("eth-transmit-end", [data.length]);
                },
                "set_mac": mac => bus.send("net" + id + "-mac", mac),
                // frames from the network: the handler returns whether the
                // card took the frame
                "on_receive": handler => bus.register("net" + id + "-receive", data =>
                {
                    if(handler(data)) bus.send("eth-receive-end", [data.length]);
                }, this),
            },
        }, {
            "preserve_mac_from_state_image": !!settings.preserve_mac_from_state_image,
            "mac_address_translation": !!settings.mac_address_translation,
        });
};

/**
 * The sound card of a plugin (audio_device "sb16", "hd_audio"): its slot
 * (pci_functions; the SB16 is an ISA card, none), the speaker (the dac-*
 * messages of src/browser/speaker.js)
 * @param {!Object} settings
 * @param {BusConnector} bus
 * @return {!PluginDevice}
 */
CPU.prototype.create_audio_plugin = function(settings, bus)
{
    const isa = settings.audio_device_plugin["name"] === "sb16";
    return new PluginDevice(this, AUDIO_PLUGINS, settings.audio_device_plugin, isa ? -1 : pci_functions(this.platform).hda, {
        "audio": {
            "send": (left, right) => bus.send("dac-send-data", [left, right]),
            "set_sampling_rate": rate => bus.send("dac-tell-sampling-rate", rate),
            "enable": () => bus.send("dac-enable"),
            "disable": () => bus.send("dac-disable"),
            // the samples as the stream has them, for tests
            "pcm": pcm => bus.send("hd-audio-pcm", pcm),
            // the speaker's own messages (the SB16's: it answers the
            // speaker's requests for data, and has a mixer)
            "bus_send": (name, data, transfer) => bus.send(name, data, transfer),
            "bus_register": (name, handler) => bus.register(name, handler, this),
        },
    }, {});
};

/**
 * USB (usb: { controller, tablet, mass_storage }): the plugin's controller
 * in its slot (pci_functions), its devices; the bus for the pointer's
 * messages; the USB disks' images (settings.usb_disks)
 * @param {!Object} settings
 * @param {BusConnector} bus
 * @return {!PluginDevice}
 */
CPU.prototype.create_usb_plugin = function(settings, bus)
{
    /** @type {!Map<string, !Object>} the USB disks' buffers by their ids (disk_devices) */
    this.usb_disks = new Map((settings.usb_disks || []).map(disk => [disk.id, disk.buffer]));
    // (EHCI: its own function, 7; its companions are the plugin's functions 0 to 2)
    const functions = pci_functions(this.platform);
    const controller = settings.usb["controller"];
    return new PluginDevice(this, USB_PLUGINS, settings.usb_plugin, controller === "ehci" ? functions.ehci : controller === "xhci" ? functions.xhci : functions.uhci, {
        "bus": {
            "register": (name, handler) => bus.register(name, handler, null),
            // to the page and to the other devices (the PS/2 mouse, the
            // VMware backdoor: "usb-tablet-active")
            "send": (name, value) =>
            {
                bus.send(name, value);
                bus.pair.send(name, value);
            },
        },
    }, {
        "controller": settings.usb["controller"],
        "tablet": !!settings.usb["tablet"],
        "mass_storage": (settings.usb_disks || []).map(disk => ({ "id": disk.id, "buffer": disk.buffer, "read_only": disk.read_only })),
    });
};

/**
 * A USB disk into the first free port (V86.usb_attach_disk)
 * @param {string} id
 * @param {!Object} buffer
 * @param {boolean} read_only
 */
CPU.prototype.usb_attach_disk = function(id, buffer, read_only)
{
    if(!this.devices.usb) throw new Error("usb_attach_disk: the machine has no USB (the usb option)");
    this.devices.usb.device["attach_disk"](id, buffer, read_only);
    this.usb_disks.set(id, buffer);
};

/**
 * A USB disk out of its port and gone (V86.usb_detach_disk)
 * @param {string} id
 * @return {!Object} its buffer
 */
CPU.prototype.usb_detach_disk = function(id)
{
    const buffer = this.usb_disks && this.usb_disks.get(id);
    if(!buffer) throw new Error("usb_detach_disk: no USB disk " + JSON.stringify(id));
    this.devices.usb.device["detach_disk"](id);
    this.usb_disks.delete(id);
    return buffer;
};

/**
 * Where a built-in device goes when its options put it behind a PCI Express
 * root port (pcie_root_port, platform.root_port_devices): device 0 on that
 * port's secondary bus; undefined for its usual place
 * @param {string} name
 * @return {number|undefined}
 */
CPU.prototype.root_port_pci_id = function(name)
{
    const port = this.platform.root_port_devices[name];
    return port === undefined ? undefined : this.devices.pcie_root_ports[port].pci_secondary_bus << 8;
};

/**
 * An SMI (Q35: the APM control port, the TCO watchdog) for a core, by
 * default the one whose port access raised it: latched until the core can
 * enter system management mode (src/rust/cpu/smm.rs). The current core
 * enters it at once (after the long-mode instruction it is in, if any),
 * another core at its next slice, a core in SMM after RSM.
 * @param {number=} core
 */
CPU.prototype.smi = function(core)
{
    this.apic_raise_smi(core === undefined ? (this.io_core >= 0 ? this.io_core : this.active_core) : core);
    this.handle_irqs();
};

/**
 * set_shared_irq_level for an IOAPIC input without a PIC counterpart (GSI
 * 16-23: Q35's PIRQ lines in APIC mode)
 * @param {number} gsi
 * @param {number} source
 * @param {boolean} level
 */
CPU.prototype.set_shared_gsi_level = function(gsi, source, level)
{
    dbg_assert(gsi >= 16 && gsi < this.shared_irq_sources.length);
    const sources = this.shared_irq_sources[gsi];

    if(level)
    {
        sources.add(source);
        this.ioapic_raise_irq(gsi);
    }
    else
    {
        sources.delete(source);
        if(sources.size === 0)
        {
            this.ioapic_lower_irq(gsi);
        }
    }
};

CPU.prototype.reset_memory = function()
{
    this.mem8.fill(0);
};

/**
 * Relocate the top `size` bytes of RAM to guest physical 4 GiB. Low RAM
 * then ends at `low_memory_size`; the backing bytes stay in the wasm32 heap.
 * @param {number} size
 * @param {number} low_minimum bytes that must remain below the relocated range
 */
CPU.prototype.configure_high_memory = function(size, low_minimum)
{
    this.low_memory_size = this.memory_size[0];
    if(!size) return;
    const low = this.memory_size[0] - size;
    if(!Number.isSafeInteger(size) || size < 0 || size % (1 << 20) !== 0 || low < Math.max(32 << 20, low_minimum))
    {
        throw new Error("high_memory_size must be a multiple of 1 MiB that leaves at least 32 MiB (and the initrd) below 4 GiB");
    }
    if(!this.wm.exports["x64_phys_set_window"](0, 0, 1, low, size, 1))
    {
        throw new Error("Cannot map high_memory_size above 4 GiB");
    }
    this.low_memory_size = low;
};

/**
 * RAM beyond the wasm32 backing store (extended RAM): `size` bytes at guest physical
 * 4 GiB + high_memory_size, kept in an ExtendedStore (src/extended_memory.js)
 * and cached in `cache_size` bytes of frames (src/rust/x64/extended.rs).
 * Only a long-mode guest can address it.
 * @param {number} size
 * @param {number=} cache_size
 */
CPU.prototype.configure_extended_memory = function(size, cache_size)
{
    this.extended_pages = 0;
    this.extended_base = 0;
    this.extended_store = null;
    if(!size) return;
    if(!Number.isSafeInteger(size) || size < 0 || size % (2 << 20))
    {
        throw new Error("extended_memory_size must be a multiple of 2 MiB");
    }
    const base = 0x100000000 + (this.memory_size[0] - this.low_memory_size);
    if(base + size > 0x1000000000)
    {
        throw new Error("extended_memory_size: guest RAM would exceed the 36-bit physical address space");
    }
    const cache = Math.min(size, cache_size || 512 << 20);
    if(!Number.isSafeInteger(cache) || cache < 1 << 20 || cache % 4096)
    {
        throw new Error("extended_memory_cache must be a multiple of 4 KiB and at least 1 MiB");
    }
    let store;
    try
    {
        store = new ExtendedStore(size / 4096);
    }
    catch(e)
    {
        throw new Error("extended_memory_size: the host cannot allocate " + size + " bytes (" + e.message + ")");
    }
    if(!this.wm.exports["x64_ext_configure"](base >>> 0, Math.floor(base / 0x100000000), size / 4096, cache / 4096))
    {
        throw new Error("extended_memory_size: cannot allocate the frame cache");
    }
    this.extended_store = store;
    this.extended_pages = size / 4096;
    this.extended_base = base;
};

/** Every dirty frame back into the store (src/state.js: a snapshot stream) */
CPU.prototype.flush_extended_memory = function()
{
    this.wm.exports["x64_ext_flush"]();
};

/** Extended RAM reads as zero again (power-on); every core is stopped */
CPU.prototype.clear_extended_memory = function()
{
    if(!this.extended_store) return;
    this.wm.exports["x64_ext_discard"]();
    this.extended_store.clear();
};

/**
 * @param {number} size
 * @param {number} minimum_size
 * @param {number=} granularity the size is a multiple of it: the memory map's
 *     blocks, or larger (a power of two)
 */
CPU.prototype.create_memory = function(size, minimum_size, granularity = MMAP_BLOCK_SIZE)
{
    // e.g. `2048 << 20` is negative: reject it instead of silently using the minimum
    if(!(size >= 0))
    {
        throw new Error("memory_size must be a non-negative number of bytes, got " + size);
    }
    // The size is kept in 32 bits and RAM lives in wasm32 memory: at most
    // 2 GiB - 128 KiB (- 1 MiB in whole MiB). (A multiple of 4 GiB used to
    // wrap to 0 bytes here.)
    const max_size = Math.pow(2, 31) - granularity;
    if(size < minimum_size)
    {
        size = minimum_size;
        dbg_log("Rounding memory size up to " + size, LOG_CPU);
    }
    else if(size > max_size)
    {
        // (2 GiB itself only loses the last 128 KiB, or MiB: not worth a warning)
        if(size > Math.pow(2, 31))
        {
            console.warn("memory_size of " + Math.round(size / (1 << 20)) + " MB exceeds the maximum; using " +
                (max_size / (1 << 20)) + " MB");
        }
        size = max_size;
    }

    size = ((size - 1) | (granularity - 1)) + 1 | 0;
    dbg_assert((size | 0) > 0);
    dbg_assert((size & MMAP_BLOCK_SIZE - 1) === 0 && (size & granularity - 1) === 0);

    console.assert(this.memory_size[0] === 0, "Expected uninitialised memory");

    this.memory_size[0] = size;

    const memory_offset = this.allocate_memory(size);

    this.mem8 = view(Uint8Array, this.wasm_memory, memory_offset, size);
    this.mem32s = view(Uint32Array, this.wasm_memory, memory_offset, size >> 2);
};

// Constructor policy only. IR is the only compiler.
CPU.prototype.configure_jit_backend = function(settings)
{
    if(settings["jit_backend"] !== undefined && settings["jit_backend"] !== "ir")
        throw new Error("jit_backend must be ir (the legacy backend was removed)");
    const exports = this.wm.exports;
    if(!exports["jit_set_enabled"])
        throw new Error("This core has no JIT; rebuild build/v86.wasm");
    // (the IR region tiers' settings, ir_region_budget, ir_opt_level,
    // ir_passes_disabled, ir_verify, ir_dump, ir_stats and ir_page_mode, are
    // deprecated and have no effect: docs/jit-unification-plan.md M11
    // deleted the region tiers, and the x64 page tier compiles all code)
    const enabled = !settings.disable_jit;
    if(!exports["jit_set_enabled"](enabled ? 1 : 0))
        throw new Error("Cannot configure the JIT");
    if(settings["ir_tier0"] !== undefined && typeof settings["ir_tier0"] !== "boolean")
        throw new Error("ir_tier0 must be a boolean");
    // 32-bit and 16-bit code in the x64 page tier (default on; the name is
    // IR Tier-0's, which it replaced in P7.5): without it that code runs in
    // the interpreter
    if(!exports["jit_set_page32"](enabled && settings["ir_tier0"] !== false ? 1 : 0))
        throw new Error("Cannot configure ir_tier0");
    this.jit_backend = "ir";
    this.ir_sync_publication = settings["ir_sync_publication"] === true;
};

CPU.prototype.get_jit_info = function()
{
    const exports = this.wm.exports;
    // (the page tier's counters, through jitrt's jit_stat: client 0,
    // docs/jit-unification-plan.md P5.10)
    const stat = exports["jit_stat"] ? field => exports["jit_stat"](0, field) : null;
    // (the IR region tiers' statistics and settings went with them,
    // docs/jit-unification-plan.md M11; IR Tier-0's before, P7.5)
    return {
        "backend": this.jit_backend,
        "ir_available": !!exports["jit_set_enabled"],
        "ir": {
            // (1 when the JIT compiles: configure_jit_backend, jit_set_enabled)
            "enabled": exports["jit_is_enabled"] ? +exports["jit_is_enabled"]() : 0,
            "tier0": null,
            // (32-bit and 16-bit code in the x64 page tier)
            "page_tier": stat ? {
                "legacy32": !!stat(40),
                "compat32": !!stat(41),
                // (16-bit protected-mode code, x64_page_prot16)
                "prot16": !!stat(42),
                // (real-mode and virtual-8086 code, x64_page_v86)
                "v86": !!stat(44),
                "functions": stat(12) >>> 0,
                "native_instructions": stat(1) >>> 0,
                "activations": stat(13) >>> 0,
            } : null,
        },
    };
};

/**
 * @param {BusConnector} device_bus
 */
CPU.prototype.init = function(settings, device_bus)
{
    // (the V86 constructor checked the options; this is the x86 CPU, of the
    // PC machines: docs/arm64-virt-android16-plan.md P1.1)
    const machine_type = check_machine_options(settings).machine_type;
    if(machine_type === "virt" || machine_type === "ranchu")
    {
        throw new Error("The x86 CPU does not run machine_type \"" + machine_type + "\"");
    }
    const multicore = (settings.cpu_cores || 1) > 1;
    this.clock = new MachineClock(Object.assign({ now: v86.microtick }, settings.cpu_clock));
    this.clock.set_instruction_source(() => this.wm.exports["take_clock_progress"]());
    const deterministic = this.clock.mode === "deterministic";
    this.wm.exports["set_deterministic_execution"](deterministic);
    // Compiled code retires a slice in microseconds: switching cores (their
    // state is copied) would dominate a short one
    const default_quantum = settings.disable_jit || deterministic ? 4096 : 32768;
    this.scheduler_quantum = settings.cpu_quantum === undefined ? default_quantum : settings.cpu_quantum;
    if(!Number.isInteger(this.scheduler_quantum) || this.scheduler_quantum < 1 || this.scheduler_quantum > 100000)
    {
        throw new Error("cpu_quantum must be an integer from 1 to 100000");
    }
    this.scheduler_seed = settings.cpu_schedule_seed >>> 0;
    if(multicore && settings.cpuid_level !== undefined && settings.cpuid_level < 0x1F)
    {
        throw new Error("Multicore topology requires cpuid_level >= 0x1F");
    }
    // Deterministic time uses the interpreter's architectural commit ledger.
    // Multicore JIT remains opt-in until the complete cross-core stress matrix passes.
    if(settings.parallel && deterministic) throw new Error("parallel: deterministic time needs cooperative cores");
    const interpreted = deterministic || multicore && !settings.experimental_smp_jit;
    this.configure_jit_backend(interpreted ? Object.assign({}, settings, { disable_jit: true }) : settings);
    // The JIT switches (src/jit_switches.js): the build's JIT_DEFAULTS, then
    // the setting jit_switches
    set_jit_switches(this.wm.exports, this.wasm_memory, build_jit_defaults(this.wm.exports, this.wasm_memory), "JIT_DEFAULTS");
    set_jit_switches(this.wm.exports, this.wasm_memory, settings["jit_switches"]);
    // The x86-64 CPU profile (CPUID long mode, NX, SYSCALL, CX16, ...) is
    // opt-in while x64 support is experimental
    this.wm.exports["set_x64_test_capabilities"](settings["cpu_type"] === "x86_64");
    this.wm.exports["set_x87_fast_math"]?.(settings["x87_fast_math"] !== false);
    this.wm.exports["set_x87_jit_cache"]?.(settings["x87_jit_cache"] !== false);
    this.create_memory(
        settings.memory_size || 64 * 1024 * 1024,
        settings.initrd ? 64 * 1024 * 1024 : 1024 * 1024,
        // (UEFI: whole MiB, as QEMU's machines have; OVMF's SMM build places
        // TSEG below the top of RAM in MiB)
        settings.firmware_code ? 1 << 20 : MMAP_BLOCK_SIZE,
    );

    this.platform = create_platform(settings, this.memory_size[0]);
    this.configure_high_memory(settings.high_memory_size || 0, settings.initrd ? 64 * 1024 * 1024 + settings.initrd.byteLength : 0);
    this.configure_extended_memory(settings.extended_memory_size || 0, settings.extended_memory_cache);

    settings.cpuid_level && this.set_cpuid_level(settings.cpuid_level);
    // The features of docs/simd-xsave-plan.md (src/cpu_features.js): those
    // cpu_features names (for x86_64 every released one if it names none),
    // and for tests and development the unreleased ones, which warn unless
    // cpu_features_unreleased is set
    this.cpu_features = resolve_cpu_features(settings["cpu_features"], settings["cpu_type"] === "x86_64", settings.cpuid_level || 0x16);
    this.cpu_features_explicit = settings["cpu_features"] !== undefined;
    const unreleased = unreleased_cpu_features(settings["cpu_features"]);
    if(unreleased.length && !settings["cpu_features_unreleased"])
    {
        console.warn("cpu_features: " + unreleased.join(", ") + " not released yet (docs/simd-xsave-plan.md): " +
            "for tests and development, their instructions may still be #UD");
    }
    this.wm.exports["set_cpu_features"](this.cpu_features);

    this.acpi_enabled[0] = +this.platform.acpi;

    this.reset_cpu();
    this.setup_cores();

    var io = new IO(this);
    this.io = io;

    this.bios.main = settings.bios;
    // The display adapter plugin's descriptor; none with graphics_adapter: "none"
    this.graphics_adapter_descriptor = settings.graphics_adapter;
    this.bios.vga = settings.vga_bios;
    if(settings.firmware_code)
    {
        this.firmware = {
            code: settings.firmware_code,
            vars: settings.firmware_vars || null,
            code_region: -1,
            pflash: null,
            debug_console: !!(settings.firmware && settings.firmware["debug_console"]),
            // (the Secure Boot build: its variable store written only in SMM)
            secure_boot: !!(settings.firmware && settings.firmware["secure_boot"]),
        };
    }

    this.load_bios();

    if(settings.bzimage)
    {
        const { bzimage, initrd } = settings;
        const cmdline = settings.cmdline || "";
        const option_rom = load_kernel(this.mem8, bzimage, initrd, cmdline);

        if(option_rom)
        {
            this.option_roms.push(option_rom);
            // The running kernel reuses the memory it was loaded to, so every
            // reset has to place it again (like QEMU's -kernel)
            this.reload_direct_boot_kernel = () => load_kernel(this.mem8, bzimage, initrd, cmdline);
        }
    }

    io.register_read(0xB3, this, function()
    {
        // seabios smm_relocate_and_restore
        dbg_log("port 0xB3 read");
        return 0;
    });

    var a20_byte = 0;

    io.register_read(0x92, this, function()
    {
        return a20_byte;
    });

    io.register_write(0x92, this, function(out_byte)
    {
        a20_byte = out_byte;
    });

    io.register_read(0x511, this, function()
    {
        // bios config port (used by seabios and kvm-unit-test)
        if(this.fw_pointer < this.fw_value.length)
        {
            return this.fw_value[this.fw_pointer++];
        }
        else
        {
            dbg_assert(false, "config port: Read past value");
            return 0;
        }
    });
    io.register_write(0x510, this, undefined, function(value)
    {
        // https://wiki.osdev.org/QEMU_fw_cfg
        // https://github.com/qemu/qemu/blob/master/docs/specs/fw_cfg.txt

        dbg_log("bios config port, index=" + h(value));

        function i32(x)
        {
            return new Uint8Array(Int32Array.of(x).buffer);
        }
        function i64(low, high)
        {
            return new Uint8Array(Int32Array.of(low, high).buffer);
        }

        function to_be16(x)
        {
            return x >> 8 | x << 8 & 0xFF00;
        }

        function to_be32(x)
        {
            return x << 24 | x << 8 & 0xFF0000 | x >> 8 & 0xFF00 | x >>> 24;
        }

        this.fw_pointer = 0;

        if(value === FW_CFG_SIGNATURE)
        {
            // Pretend to be qemu (for seabios)
            this.fw_value = i32(FW_CFG_SIGNATURE_QEMU);
        }
        else if(value === FW_CFG_ID)
        {
            // the traditional interface (bit 0), no DMA: OVMF needs a revision
            // of at least 1; SeaBIOS only looks at the DMA bit
            this.fw_value = i32(1);
        }
        else if(value === FW_CFG_RAM_SIZE)
        {
            this.fw_value = i64(this.memory_size[0], 0);
        }
        else if(value === FW_CFG_NB_CPUS)
        {
            this.fw_value = i32(this.platform.cores);
        }
        else if(value === FW_CFG_MAX_CPUS)
        {
            this.fw_value = i32(this.platform.cores);
        }
        else if(value === FW_CFG_BOOT_MENU)
        {
            this.fw_value = i32(+settings.bootmenu);
        }
        else if(value === FW_CFG_NUMA)
        {
            this.fw_value = new Uint8Array(16);
        }
        else if(value === FW_CFG_FILE_DIR)
        {
            const buffer_size = 4 + 64 * this.option_roms.length;
            const buffer32 = new Int32Array(buffer_size);
            const buffer8 = new Uint8Array(buffer32.buffer);

            buffer32[0] = to_be32(this.option_roms.length);

            for(let i = 0; i < this.option_roms.length; i++)
            {
                const { name, data } = this.option_roms[i];
                const file_struct_ptr = 4 + 64 * i;

                dbg_assert(FW_CFG_FILE_START + i < 0x10000);
                buffer32[file_struct_ptr + 0 >> 2] = to_be32(data.length);
                buffer32[file_struct_ptr + 4 >> 2] = to_be16(FW_CFG_FILE_START + i);

                dbg_assert(name.length < 64 - 8);

                for(let j = 0; j < name.length; j++)
                {
                    buffer8[file_struct_ptr + 8 + j] = name.charCodeAt(j);
                }
            }

            this.fw_value = buffer8;
        }
        else if(value >= FW_CFG_CUSTOM_START && value < FW_CFG_FILE_START)
        {
            this.fw_value = i32(0);
        }
        else if(value >= FW_CFG_FILE_START && value - FW_CFG_FILE_START < this.option_roms.length)
        {
            const file = this.option_roms[value - FW_CFG_FILE_START];
            this.fw_value = file.get_data ? file.get_data() : file.data;
            dbg_assert(this.fw_value.length === file.data.length, "fw_cfg file " + file.name + " changed size");
        }
        else
        {
            dbg_log("Warning: Unimplemented fw index: " + h(value));
            this.fw_value = i32(0);
        }
    });

    if(DEBUG)
    {
        // Avoid logging noisey ports
        io.register_write(0x80, this, function(out_byte) {});
        io.register_read(0x80, this, function() { return 0xFF; });
        io.register_write(0xE9, this, function(out_byte) {});
    }

    this.devices = {};

    // TODO: Make this more configurable
    if(settings.load_devices)
    {
        this.devices.pci = new PCI(this);

        if(this.acpi_enabled[0])
        {
            const acpi = this.devices.acpi = new ACPI(this, device_bus);

            // v86's own tables, installed by SeaBIOS's table loader. They are
            // generated when SeaBIOS reads them, after it has programmed the PM
            // base (0x600 when the loader is present); the sizes don't depend on it.
            const platform = /** @type {Platform} */ (this.platform);
            const build_tables = () => {
                const pm_base = acpi.pm_base === -1 ? ACPI_PM_BASE_DEFAULT : acpi.pm_base;
                check_platform(platform, pm_base);
                return build_acpi_tables(platform, pm_base);
            };
            const tables = build_tables();
            this.option_roms.push(
                { name: ACPI_LOADER_FILE, data: tables.loader },
                { name: ACPI_RSDP_FILE, data: tables.rsdp },
                { name: ACPI_TABLES_FILE, data: tables.tables, get_data: () => build_tables().tables });
            if(tables.tpm_log)
            {
                this.option_roms.push({ name: TPM_LOG_FILE, data: tables.tpm_log });
            }

            // Only read by SeaBIOS's fallback builder, if the loader fails:
            // advertise only the sleep states that are implemented
            this.option_roms.push({ name: "etc/system-states", data: acpi_system_states_file(platform) });
        }

        if(this.platform.machine === "q35")
        {
            if(!this.ioapic_raise_irq)
            {
                throw new Error("machine_type \"q35\" needs a newer v86.wasm (ioapic_raise_irq)");
            }
            // (the MCH and the ICH9 LPC; the AHCI function is created with the drives)
            this.devices.q35 = new Q35(this);
            // the PCI Express root ports, before anything is put behind them
            const root_ports = this.platform.pcie_root_ports;
            this.devices.pcie_root_ports = Array.from({ length: root_ports }, (_, i) => new PCIeRootPort(this, i, root_ports));
            if(this.platform.hpet)
            {
                this.devices.hpet = new HPET(this);
            }
            if(this.platform.smbus)
            {
                this.devices.smbus = new SMBus(this);
            }
        }

        this.devices.rtc = new RTC(this);
        this.fill_cmos(this.devices.rtc, settings);
        if(this.firmware)
        {
            this.add_uefi_fw_cfg_files();
        }

        this.devices.dma = new DMA(this);

        this.devices.display = new DisplayHub(device_bus, settings.screen);
        if(this.graphics_adapter_descriptor)
        {
            this.devices.graphics_adapter = new GraphicsAdapter(this, this.graphics_adapter_descriptor,
                { vram_size: settings.vram_size, test: settings.graphics_adapter_test, renderer: settings.graphics_adapter_renderer });
            // (tests and debugging reach into the VGA core)
            this.devices.vga = this.devices.graphics_adapter.vga();
        }

        this.devices.ps2 = new PS2(this, device_bus);
        this.devices.vmware = new VMwareMouse(this, device_bus);

        this.devices.uart0 = new UART(this, 0x3F8, device_bus);
        this.devices.parallel0 = new ParallelPort(this, 0x378, 7, 0, device_bus);

        if(settings.uart1)
        {
            this.devices.uart1 = new UART(this, 0x2F8, device_bus);
        }
        if(settings.uart2)
        {
            this.devices.uart2 = new UART(this, 0x3E8, device_bus);
        }
        if(settings.uart3)
        {
            this.devices.uart3 = new UART(this, 0x2E8, device_bus);
        }
        if(settings.parallel1)
        {
            this.devices.parallel1 = new ParallelPort(this, 0x278, 5, 1, device_bus);
        }

        if(DEBUG)
        {
            // The platform description (and so the ACPI tables) lists these ports
            for(const { port } of this.platform.uarts.concat(this.platform.parallel_ports))
            {
                dbg_assert(this.io.ports[port].device, "platform port " + h(port) + " has no device");
            }
        }

        this.devices.fdc = new FloppyController(this, settings.fda, settings.fdb);

        if(this.platform.machine === "q35")
        {
            this.create_q35_storage(settings, device_bus);

            if(settings["ahci_test_drives"])
            {
                // (tests only: a second AHCI controller with drives of its
                // own, e.g. behind a root port with ahci_test_pci_id 1 << 8;
                // not part of the machine contract)
                this.devices.ahci_test = new AHCIController(this, device_bus, settings["ahci_test_drives"],
                    settings["ahci_test_pci_id"] === undefined ? 0x0D << 3 : settings["ahci_test_pci_id"]);
            }
        }
        else
        {
            const ide_config = [[undefined, undefined], [undefined, undefined]];
            if(settings.hda)
            {
                ide_config[0][0] = { buffer: settings.hda };
                ide_config[0][1] = { buffer: settings.hdb };
            }
            else if(this.firmware)
            {
                // (the primary channel without drives, as QEMU's PIIX3 has
                // it: OVMF waits 35 s for BSY to clear on a channel that
                // reads as an open bus)
                ide_config[0][0] = { buffer: undefined };
            }
            ide_config[1][0] = { is_cdrom: true, buffer: settings.cdrom };
            this.devices.ide = new IDEController(this, device_bus, ide_config);
            this.devices.cdrom = this.devices.ide.secondary.master;

            if(settings["ahci_test_drives"])
            {
                // (tests only: an AHCI controller on the i440FX at 00:0d.0,
                // with drives of its own; not part of the machine contract)
                this.devices.ahci_test = new AHCIController(this, device_bus, settings["ahci_test_drives"], 0x0D << 3);
            }
        }

        this.devices.pit = new PIT(this, device_bus);

        if(settings.net_device.type === "virtio")
        {
            this.devices.virtio_net = new VirtioNet(this, device_bus, settings.preserve_mac_from_state_image, settings.net_device.mtu,
                this.root_port_pci_id("net"));
        }
        else if(settings.net_device_plugin)
        {
            // the network card, a plugin's (net_device.type "ne2k", "e1000"):
            // the NE2000's slot, its snapshot in state[59]
            this.devices.net = this.create_net_plugin(settings, device_bus);
        }

        if(settings.fs9p)
        {
            this.devices.virtio_9p = new Virtio9p(settings.fs9p, this, device_bus, this.root_port_pci_id("virtio_9p"));
        }
        else if(settings.handle9p)
        {
            this.devices.virtio_9p = new Virtio9pHandler(settings.handle9p, this, this.root_port_pci_id("virtio_9p"));
        }
        else if(settings.proxy9p)
        {
            this.devices.virtio_9p = new Virtio9pProxy(settings.proxy9p, this, this.root_port_pci_id("virtio_9p"));
        }
        if(settings.virtio_console)
        {
            this.devices.virtio_console = new VirtioConsole(this, device_bus, this.root_port_pci_id("virtio_console"));
        }
        if(settings.virtio_balloon)
        {
            this.devices.virtio_balloon = new VirtioBalloon(this, device_bus, this.root_port_pci_id("virtio_balloon"));
        }

        // the sound card (audio_device), a plugin's ("sb16", "hd_audio"), or none
        if(settings.audio_device_plugin)
        {
            this.devices.audio = this.create_audio_plugin(settings, device_bus);
        }

        // USB (usb: a controller and its devices, the plugin's)
        if(settings.usb_plugin)
        {
            this.devices.usb = this.create_usb_plugin(settings, device_bus);
        }
        // the TPM (tpm: docs/tpm.md, the plugin's), its state in a store: a
        // buffer object, written back or in memory; no PCI function
        if(settings.tpm_plugin)
        {
            this.tpm_store = settings.tpm_state || new SyncBuffer(new ArrayBuffer(TPM_STORE_SIZE));
            this.devices.tpm = new PluginDevice(this, TPM_PLUGINS, settings.tpm_plugin, -1, {}, {
                "prepared": settings.tpm_prepared,
                "state": this.tpm_store,
            });
        }

        // Last, so that they get a slot and ports that nothing else uses
        if(settings.virtio_devices)
        {
            this.devices.virtio_devices = create_virtio_devices(this, settings.virtio_devices);
        }

        // the root ports' slots: the cards the options put behind them,
        // plugged in unless pcie_plugged is false
        const unplugged = new Set();
        for(const placement of Object.values(settings.root_port_devices || {}))
        {
            if(!placement.plugged) unplugged.add(placement.port);
        }
        for(const descriptor of settings.virtio_devices || [])
        {
            if(descriptor["pcie_root_port"] !== undefined && descriptor["pcie_plugged"] === false) unplugged.add(descriptor["pcie_root_port"]);
        }
        for(const port of this.devices.pcie_root_ports || [])
        {
            port.setup(!unplugged.has(port.number));
        }
    }

    if(settings.multiboot)
    {
        dbg_log("loading multiboot", LOG_CPU);
        const option_rom = this.load_multiboot_option_rom(settings.multiboot, settings.initrd, settings.cmdline);

        if(option_rom)
        {
            if(this.bios.main)
            {
                dbg_log("adding option rom for multiboot", LOG_CPU);
                this.option_roms.push(option_rom);
            }
            else
            {
                dbg_log("loaded multiboot without bios", LOG_CPU);
                this.reg32[REG_EAX] = this.io.port_read32(0xF4);
            }
        }
    }

    this.debug_init();
};

CPU.prototype.load_multiboot = function (buffer)
{
    if(this.bios.main)
    {
        dbg_assert(false, "load_multiboot not supported with BIOS");
    }

    const option_rom = this.load_multiboot_option_rom(buffer, undefined, "");
    if(option_rom)
    {
        dbg_log("loaded multiboot", LOG_CPU);
        this.reg32[REG_EAX] = this.io.port_read32(0xF4);
    }
};

CPU.prototype.load_multiboot_option_rom = function(buffer, initrd, cmdline)
{
    // https://www.gnu.org/software/grub/manual/multiboot/multiboot.html

    dbg_log("Trying multiboot from buffer of size " + buffer.byteLength, LOG_CPU);

    const ELF_MAGIC = 0x464C457F;
    const MULTIBOOT_HEADER_MAGIC = 0x1BADB002;
    const MULTIBOOT_HEADER_MEMORY_INFO = 0x2;
    const MULTIBOOT_HEADER_ADDRESS = 0x10000;
    const MULTIBOOT_BOOTLOADER_MAGIC = 0x2BADB002;
    const MULTIBOOT_SEARCH_BYTES = 8192;
    const MULTIBOOT_INFO_STRUCT_LEN = 116;
    const MULTIBOOT_INFO_CMDLINE = 0x4;
    const MULTIBOOT_INFO_MODS = 0x8;
    const MULTIBOOT_INFO_MEM_MAP = 0x40;

    if(buffer.byteLength < MULTIBOOT_SEARCH_BYTES)
    {
        var buf32 = new Int32Array(MULTIBOOT_SEARCH_BYTES / 4);
        new Uint8Array(buf32.buffer).set(new Uint8Array(buffer));
    }
    else
    {
        var buf32 = new Int32Array(buffer, 0, MULTIBOOT_SEARCH_BYTES / 4);
    }

    for(var offset = 0; offset < MULTIBOOT_SEARCH_BYTES; offset += 4)
    {
        if(buf32[offset >> 2] === MULTIBOOT_HEADER_MAGIC)
        {
            var flags = buf32[offset + 4 >> 2];
            var checksum = buf32[offset + 8 >> 2];
            var total = MULTIBOOT_HEADER_MAGIC + flags + checksum | 0;

            if(total)
            {
                dbg_log("Multiboot checksum check failed", LOG_CPU);
                continue;
            }
        }
        else
        {
            continue;
        }

        dbg_log("Multiboot magic found, flags: " + h(flags >>> 0, 8), LOG_CPU);
        // bit 0 : load modules on page boundaries (may as well, if we load modules)
        // bit 1 : provide a memory map (which we always will)
        dbg_assert((flags & ~MULTIBOOT_HEADER_ADDRESS & ~3) === 0, "TODO");

        // The image is loaded later (from the option ROM); reject what cannot
        // be loaded now, with an error the embedder sees
        if(!(flags & MULTIBOOT_HEADER_ADDRESS))
        {
            if(buf32[0] !== ELF_MAGIC)
            {
                throw new Error("Multiboot image has neither an address header nor an ELF header");
            }
            const reason = elf_unsupported_reason(buffer);
            if(reason)
            {
                throw new Error("Unsupported multiboot ELF image: " + reason);
            }
        }

        // do this in a io register hook, so it can happen after BIOS does its work
        var cpu = this;

        this.io.register_read(0xF4, this, function () {return 0;} , function () { return 0;}, function () {
            // actually do the load and return the multiboot magic
            const multiboot_info_addr = 0x7C00;
            let multiboot_data = multiboot_info_addr + MULTIBOOT_INFO_STRUCT_LEN;
            let info = 0;

            // command line
            if(cmdline)
            {
                info |= MULTIBOOT_INFO_CMDLINE;

                cpu.write32(multiboot_info_addr + 16, multiboot_data);

                cmdline += "\x00";
                const encoder = new TextEncoder();
                const cmdline_utf8 = encoder.encode(cmdline);
                cpu.write_blob(cmdline_utf8, multiboot_data);
                multiboot_data += cmdline_utf8.length;
            }

            // memory map
            if(flags & MULTIBOOT_HEADER_MEMORY_INFO)
            {
                info |= MULTIBOOT_INFO_MEM_MAP;
                let multiboot_mmap_count = 0;
                cpu.write32(multiboot_info_addr + 44, 0);
                cpu.write32(multiboot_info_addr + 48, multiboot_data);

                // Create a memory map for the multiboot kernel
                // does not exclude traditional bios exclusions
                let start = 0;
                let was_memory = false;
                const ram = addr => addr < cpu.low_memory_size && cpu.memory_map_read8[addr >>> MMAP_BLOCK_BITS] === undefined;
                for(let addr = 0; addr < MMAP_MAX; addr += MMAP_BLOCK_SIZE)
                {
                    if(was_memory && !ram(addr))
                    {
                        cpu.write32(multiboot_data, 20); // size
                        cpu.write32(multiboot_data + 4, start); //addr (64-bit)
                        cpu.write32(multiboot_data + 8, 0);
                        cpu.write32(multiboot_data + 12, addr - start); // len (64-bit)
                        cpu.write32(multiboot_data + 16, 0);
                        cpu.write32(multiboot_data + 20, 1); // type (MULTIBOOT_MEMORY_AVAILABLE)
                        multiboot_data += 24;
                        multiboot_mmap_count += 24;
                        was_memory = false;
                    }
                    else if(!was_memory && ram(addr))
                    {
                        start = addr;
                        was_memory = true;
                    }
                }
                dbg_assert (!was_memory, "top of 4GB shouldn't have memory");
                // relocated and extended RAM
                const high = cpu.memory_size[0] - cpu.low_memory_size + cpu.extended_pages * 4096;
                if(high)
                {
                    cpu.write32(multiboot_data, 20);
                    cpu.write32(multiboot_data + 4, 0); // addr = 4 GiB
                    cpu.write32(multiboot_data + 8, 1);
                    cpu.write32(multiboot_data + 12, high >>> 0);
                    cpu.write32(multiboot_data + 16, Math.floor(high / 0x100000000));
                    cpu.write32(multiboot_data + 20, 1);
                    multiboot_data += 24;
                    multiboot_mmap_count += 24;
                }
                cpu.write32(multiboot_info_addr + 44, multiboot_mmap_count);
            }

            let entrypoint = 0;
            let top_of_load = 0;

            if(flags & MULTIBOOT_HEADER_ADDRESS)
            {
                dbg_log("Multiboot specifies its own address table", LOG_CPU);

                var header_addr = buf32[offset + 12 >> 2];
                var load_addr = buf32[offset + 16 >> 2];
                var load_end_addr = buf32[offset + 20 >> 2];
                var bss_end_addr = buf32[offset + 24 >> 2];
                var entry_addr = buf32[offset + 28 >> 2];

                dbg_log("header=" + h(header_addr, 8) +
                        " load=" + h(load_addr, 8) +
                        " load_end=" + h(load_end_addr, 8) +
                        " bss_end=" + h(bss_end_addr, 8) +
                        " entry=" + h(entry_addr, 8));

                dbg_assert(load_addr <= header_addr);

                var file_start = offset - (header_addr - load_addr);

                if(load_end_addr === 0)
                {
                    var length = undefined;
                }
                else
                {
                    dbg_assert(load_end_addr >= load_addr);
                    var length = load_end_addr - load_addr;
                }

                const blob = new Uint8Array(buffer, file_start, length);
                cpu.write_blob(blob, load_addr);

                entrypoint = entry_addr | 0;
                top_of_load = Math.max(load_end_addr, bss_end_addr);
            }
            else if(buf32[0] === ELF_MAGIC)
            {
                dbg_log("Multiboot image is in elf format", LOG_CPU);

                const elf = read_elf(buffer);

                entrypoint = elf.header.entry;

                for(const program of elf.program_headers)
                {
                    if(program.type === 0)
                    {
                        // null
                    }
                    else if(program.type === 1)
                    {
                        // load

                        dbg_assert(program.filesz <= program.memsz);

                        if(program.paddr + program.memsz < cpu.memory_size[0])
                        {
                            if(program.filesz) // offset might be outside of buffer if filesz is 0
                            {
                                const blob = new Uint8Array(buffer, program.offset, program.filesz);
                                cpu.write_blob(blob, program.paddr);
                            }
                            top_of_load = Math.max(top_of_load, program.paddr + program.memsz);
                            dbg_log("prg load " + program.paddr + " to " + (program.paddr + program.memsz), LOG_CPU);

                            // Since multiboot specifies that paging is disabled, we load to the physical address;
                            // but the entry point is specified in virtual addresses so adjust the entrypoint if needed

                            if(entrypoint === elf.header.entry && program.vaddr <= entrypoint && (program.vaddr + program.memsz) > entrypoint)
                            {
                                entrypoint = (entrypoint - program.vaddr) + program.paddr;
                            }
                        }
                        else
                        {
                            dbg_log("Warning: Skipped loading section, paddr=" + h(program.paddr) + " memsz=" + program.memsz, LOG_CPU);
                        }
                    }
                    else if(
                        program.type === 2 || // dynamic
                        program.type === 3 || // interp
                        program.type === 4 || // note
                        program.type === 6 || // phdr
                        program.type === 7 || // tls
                        program.type === 0x6474e550 || // gnu_eh_frame
                        program.type === 0x6474e551 || // gnu_stack
                        program.type === 0x6474e552 || // gnu_relro
                        program.type === 0x6474e553)   // gnu_property
                    {
                        dbg_log("skip load type " + program.type + " " + program.paddr + " to " + (program.paddr + program.memsz), LOG_CPU);
                        // ignore for now
                    }
                    else
                    {
                        dbg_assert(false, "unimplemented elf section type: " + h(program.type));
                    }
                }
            }
            else
            {
                dbg_assert(false, "Not a bootable multiboot format");
            }

            if(initrd)
            {
                info |= MULTIBOOT_INFO_MODS;

                cpu.write32(multiboot_info_addr + 20, 1); // mods_count
                cpu.write32(multiboot_info_addr + 24, multiboot_data); // mods_addr;

                var ramdisk_address = top_of_load;
                if((ramdisk_address & 4095) !== 0)
                {
                    ramdisk_address = (ramdisk_address & ~4095) + 4096;
                }
                dbg_log("ramdisk address " + ramdisk_address);
                var ramdisk_top = ramdisk_address + initrd.byteLength;

                cpu.write32(multiboot_data, ramdisk_address); // mod_start
                cpu.write32(multiboot_data + 4, ramdisk_top); // mod_end
                cpu.write32(multiboot_data + 8, 0); // string
                cpu.write32(multiboot_data + 12, 0); // reserved
                multiboot_data += 16;

                dbg_assert(ramdisk_top < cpu.memory_size[0]);

                cpu.write_blob(new Uint8Array(initrd), ramdisk_address);
            }

            cpu.write32(multiboot_info_addr, info);

            // set state for multiboot

            cpu.reg32[REG_EBX] = multiboot_info_addr;
            cpu.cr[0] = 1;
            cpu.protected_mode[0] = +true;
            cpu.flags[0] = FLAGS_DEFAULT;
            cpu.is_32[0] = +true;
            cpu.stack_size_32[0] = +true;

            for(var i = 0; i < 6; i++)
            {
                cpu.segment_is_null[i] = 0;
                cpu.segment_offsets[i] = 0;
                cpu.segment_limits[i] = 0xFFFFFFFF;
                // cpu.segment_access_bytes[i]
                cpu.sreg[i] = i === REG_CS ? 0x08 : 0x10;
            }
            cpu.instruction_pointer[0] = cpu.get_seg_cs() + entrypoint | 0;
            cpu.update_state_flags();
            dbg_log("Starting multiboot kernel at:", LOG_CPU);
            cpu.dump_state();
            cpu.dump_regs_short();

            return MULTIBOOT_BOOTLOADER_MAGIC;
        });

        // only for kvm-unit-test
        this.io.register_write_consecutive(0xF4, this,
            function(value)
            {
                console.log("Test exited with code " + h(value, 2));
                throw "HALT";
            },
            function() {},
            function() {},
            function() {});

        // only for kvm-unit-test
        for(let i = 0; i <= 0xF; i++)
        {
            function handle_write(value)
            {
                dbg_log("kvm-unit-test: Set irq " + h(i) + " to " + h(value, 2));
                if(value)
                {
                    this.device_raise_irq(i);
                }
                else
                {
                    this.device_lower_irq(i);
                }
            }

            this.io.register_write(0x2000 + i, this, handle_write, handle_write, handle_write);
        }

        // This rom will be executed by seabios after its initialisation
        // It sets up the multiboot environment.
        const SIZE = 0x200;

        const data8 = new Uint8Array(SIZE);
        const data16 = new Uint16Array(data8.buffer);

        data16[0] = 0xAA55;
        data8[2] = SIZE / 0x200;
        let i = 3;
        // trigger load
        data8[i++] = 0x66; // in 0xF4
        data8[i++] = 0xE5;
        data8[i++] = 0xF4;

        dbg_assert(i < SIZE);

        const checksum_index = i;
        data8[checksum_index] = 0;

        let rom_checksum = 0;

        for(let i = 0; i < data8.length; i++)
        {
            rom_checksum += data8[i];
        }

        data8[checksum_index] = -rom_checksum;

        return {
            name: "genroms/multiboot.bin",
            data: data8
        };
    }
    dbg_log("Multiboot header not found", LOG_CPU);
};

CPU.prototype.fill_cmos = function(rtc, settings)
{
    var boot_order = settings.boot_order || BOOT_ORDER_CD_FIRST;

    // Used by seabios to determine the boot order
    //   Nibble
    //   1: FloppyPrio
    //   2: HDPrio
    //   3: CDPrio
    //   4: BEVPrio
    // bootflag 1, high nibble, lowest priority
    // Low nibble: Disable floppy signature check (1)
    rtc.cmos_write(CMOS_BIOS_BOOTFLAG1 , 1 | boot_order >> 4 & 0xF0);

    // bootflag 2, both nibbles, high and middle priority
    rtc.cmos_write(CMOS_BIOS_BOOTFLAG2, boot_order & 0xFF);

    // 640k or less if less memory is used
    rtc.cmos_write(CMOS_MEM_BASE_LOW, 640 & 0xFF);
    rtc.cmos_write(CMOS_MEM_BASE_HIGH, 640 >> 8);

    const low_memory = this.low_memory_size;
    // (above 4 GiB: relocated RAM, then extended RAM)
    const high_memory = this.memory_size[0] - low_memory + this.extended_pages * 4096;
    var memory_above_1m = 0; // in k
    if(low_memory >= 1024 * 1024)
    {
        memory_above_1m = (low_memory - 1024 * 1024) >> 10;
        memory_above_1m = Math.min(memory_above_1m, 0xFFFF);
    }

    rtc.cmos_write(CMOS_MEM_OLD_EXT_LOW, memory_above_1m & 0xFF);
    rtc.cmos_write(CMOS_MEM_OLD_EXT_HIGH, memory_above_1m >> 8 & 0xFF);
    rtc.cmos_write(CMOS_MEM_EXTMEM_LOW, memory_above_1m & 0xFF);
    rtc.cmos_write(CMOS_MEM_EXTMEM_HIGH, memory_above_1m >> 8 & 0xFF);

    var memory_above_16m = 0; // in 64k blocks
    if(low_memory >= 16 * 1024 * 1024)
    {
        memory_above_16m = (low_memory - 16 * 1024 * 1024) >> 16;
        memory_above_16m = Math.min(memory_above_16m, 0xFFFF);
    }
    rtc.cmos_write(CMOS_MEM_EXTMEM2_LOW, memory_above_16m & 0xFF);
    rtc.cmos_write(CMOS_MEM_EXTMEM2_HIGH, memory_above_16m >> 8 & 0xFF);

    // memory above 4G, in 64k blocks (high_memory_size relocates it there)
    rtc.cmos_write(CMOS_MEM_HIGHMEM_LOW, Math.floor(high_memory / 0x10000) & 0xFF);
    rtc.cmos_write(CMOS_MEM_HIGHMEM_MID, Math.floor(high_memory / 0x1000000) & 0xFF);
    rtc.cmos_write(CMOS_MEM_HIGHMEM_HIGH, Math.floor(high_memory / 0x100000000) & 0xFF);

    rtc.cmos_write(CMOS_EQUIPMENT_INFO, 0x2F);

    rtc.cmos_write(CMOS_BIOS_SMP_COUNT, this.platform.cores - 1);

    // Used by bochs BIOS to skip the boot menu delay.
    if(settings.fastboot) rtc.cmos_write(0x3f, 0x01);
};

CPU.prototype.load_bios = function()
{
    if(this.firmware)
    {
        this.load_firmware_flash();
        return;
    }

    var bios = this.bios.main;
    var vga_bios = this.bios.vga;

    if(!bios)
    {
        dbg_log("Warning: No BIOS");
        return;
    }

    dbg_assert(bios instanceof ArrayBuffer);

    // load bios
    var data = new Uint8Array(bios),
        start = 0x100000 - bios.byteLength;

    this.write_blob(data, start);

    const adapter = this.graphics_adapter_descriptor;
    if(vga_bios && !adapter)
    {
        dbg_log("Warning: VGA BIOS not loaded: graphics_adapter is \"none\"");
    }
    else if(vga_bios)
    {
        dbg_assert(vga_bios instanceof ArrayBuffer);

        // load vga bios, its PCI ROM header naming the adapter's device
        var vga_bios8 = new Uint8Array(vga_bios).slice();
        patch_vga_bios_ids(vga_bios8, adapter["pci_vendor"], adapter["pci_device"]);

        // older versions of seabios
        this.write_blob(vga_bios8, 0xC0000);

        // newer versions of seabios (needs to match pci rom address, see
        // vga_core.js). One block of the memory map, no more: SeaBIOS puts
        // other devices' BARs right above the ROM (virtio-vga's capabilities),
        // and this runs again at every reset
        this.io.mmap_register(0xFEB00000, 0x20000,
            function(addr)
            {
                addr = (addr - 0xFEB00000) | 0;
                if(addr < vga_bios8.length)
                {
                    return vga_bios8[addr];
                }
                else
                {
                    return 0;
                }
            },
            function(addr, value)
            {
                dbg_assert(false, "Unexpected write to VGA rom");
            });
    }
    else
    {
        dbg_log("Warning: No VGA BIOS");
    }

    // seabios expects the bios to be mapped to 0xFFF00000 also
    this.io.mmap_register(0xFFF00000, 0x100000,
        function(addr)
        {
            addr &= 0xFFFFF;
            return this.mem8[addr];
        }.bind(this),
        function(addr, value)
        {
            addr &= 0xFFFFF;
            this.mem8[addr] = value;
        }.bind(this));
};

/**
 * The fw_cfg files that OVMF reads besides the ACPI ones (docs/uefi.md):
 * etc/e820 and the SMBIOS tables, as QEMU has them. Only with the UEFI
 * firmware: SeaBIOS would prefer etc/e820 to CMOS and build no SMBIOS of its own.
 */
CPU.prototype.add_uefi_fw_cfg_files = function()
{
    const low_memory = this.low_memory_size;
    const high_memory = this.memory_size[0] - low_memory + this.extended_pages * 4096;
    const query = this.wm.exports["cpuid_query"];
    const cpuid = (leaf, subleaf) => [0, 1, 2, 3].map(register => query(leaf, subleaf, register));
    const smbios = build_smbios(/** @type {Platform} */ (this.platform), { low_memory, high_memory, cpuid });
    this.option_roms.push(
        { name: "etc/e820", data: build_e820(low_memory, high_memory) },
        { name: "etc/smbios/smbios-anchor", data: smbios.anchor },
        { name: "etc/smbios/smbios-tables", data: smbios.tables });
};

/**
 * The UEFI firmware's flash: the variable store and the code, in this order,
 * ending at 4 GiB, where the reset vector is (QEMU's pflash units 1 and 0).
 * The code is read-only device memory; the variable store is CFI flash
 * (src/pflash.js) whose writes go to its buffer, written back with
 * disk_option "read_write". Without a variable store, the code is an image
 * holding both (OVMF.fd), read-only: OVMF keeps its variables in RAM then.
 * The last 128 KiB of the code also appear below 1 MiB at 0xE0000, as
 * QEMU's isa-bios alias. At a reset the store keeps its bytes.
 */
CPU.prototype.load_firmware_flash = function()
{
    const firmware = this.firmware;
    const code = new Uint8Array(firmware.code);
    if(firmware.code_region === -1)
    {
        const vars_size = firmware.vars ? firmware.vars.byteLength : 0;
        const code_base = 2 ** 32 - code.length;
        const base = code_base - vars_size;
        dbg_assert(code.length % 4096 === 0 && vars_size % 4096 === 0 && code.length + vars_size <= 16 << 20, "the firmware's size");
        firmware.code_region = this.mmio_ram_allocate(code.length);
        dbg_assert(firmware.code_region !== -1, "no device memory region for the firmware's code");
        new Uint8Array(this.wasm_memory.buffer, this.mmio_ram_backing(firmware.code_region) >>> 0, code.length).set(code);
        this.mmio_ram_set_writable(firmware.code_region, false);
        this.mmio_ram_map(firmware.code_region, code_base | 0);
        if(vars_size)
        {
            const region = this.mmio_ram_allocate(vars_size);
            dbg_assert(region !== -1, "no device memory region for the variable store");
            firmware.pflash = new PFlash(this, region, base, /** @type {!Object} */ (firmware.vars), firmware.secure_boot);
        }
        // The memory map has what device memory does not take: writes, the
        // store's reads outside read array mode (in blocks of the map's size)
        const map_base = base & ~(MMAP_BLOCK_SIZE - 1);
        const pflash = firmware.pflash;
        this.io.mmap_register(map_base, 2 ** 32 - map_base,
            addr => {
                addr >>>= 0;
                return pflash && addr >= base && addr < code_base ? pflash.read(addr - base) :
                    addr >= code_base ? code[addr - code_base] : 0xFF;
            },
            (addr, value) => {
                addr >>>= 0;
                if(pflash && addr >= base && addr < code_base) pflash.write(addr - base, value);
            });
        if(firmware.debug_console)
        {
            // QEMU's isa-debugcon at 0x402: OVMF writes its log there once
            // the port reads as 0xE9
            this.io.register_read(0x402, this, () => 0xE9);
            this.io.register_write(0x402, this, value => {
                this.bus.send("debug-console-output-byte", value);
            });
        }
    }
    else if(firmware.pflash)
    {
        firmware.pflash.reset();
    }
    this.write_blob(code.subarray(code.length - 0x20000), 0xE0000);
};

CPU.prototype.run_hardware_timers = function(acpi_enabled, now)
{
    const pit_time = this.devices.pit.timer(now, false);
    const rtc_time = this.devices.rtc.timer(now, false);
    const display_time = this.devices.display.timer(now);
    const hpet_time = this.devices.hpet ? this.devices.hpet.timer(now) : 100;
    let plugin_time = 100;
    for(const timer of this.device_timers) plugin_time = Math.min(plugin_time, timer(now));

    let acpi_time = 100;
    let apic_time = 100;
    if(acpi_enabled)
    {
        acpi_time = this.devices.acpi.timer(now);
        apic_time = this.apic_timer(now);
    }

    return Math.min(pit_time, rtc_time, display_time, hpet_time, plugin_time, acpi_time, apic_time);
};

CPU.prototype.debug_init = function()
{
    if(!DEBUG) return;

    if(this.io)
    {
        // write seabios debug output to console
        var seabios_debug = "";

        // (the UEFI firmware's debug console has the port: load_firmware_flash)
        if(!this.firmware || !this.firmware.debug_console)
        {
            this.io.register_write(0x402, this, handle); // seabios
        }
        this.io.register_write(0x500, this, handle); // vgabios
    }

    function handle(out_byte)
    {
        if(out_byte === 10)
        {
            dbg_log(seabios_debug, LOG_BIOS);
            seabios_debug = "";
        }
        else
        {
            seabios_debug += String.fromCharCode(out_byte);
        }
    }
};

CPU.prototype.dump_stack = function(start, end)
{
    if(!DEBUG) return;

    var esp = this.reg32[REG_ESP];
    dbg_log("========= STACK ==========");

    if(end >= start || end === undefined)
    {
        start = 5;
        end = -5;
    }

    for(var i = start; i > end; i--)
    {
        var line = "    ";

        if(!i) line = "=>  ";

        line += h(i, 2) + " | ";

        dbg_log(line + h(esp + 4 * i, 8) + " | " + h(this.read32s(esp + 4 * i) >>> 0));
    }
};

/** @param {string=} where */
CPU.prototype.debug_get_state = function(where)
{
    if(!DEBUG) return;

    var mode = this.protected_mode[0] ? "prot" : "real";
    var vm = (this.flags[0] & FLAG_VM) ? 1 : 0;
    var flags = this.get_eflags();
    var iopl = this.getiopl();
    var cpl = this.cpl[0];
    var cs_eip = h(this.sreg[REG_CS], 4) + ":" + h(this.get_real_eip() >>> 0, 8);
    var ss_esp = h(this.sreg[REG_SS], 4) + ":" + h(this.reg32[REG_ES] >>> 0, 8);
    var op_size = this.is_32[0] ? "32" : "16";
    var if_ = (this.flags[0] & FLAG_INTERRUPT) ? 1 : 0;

    var flag_names = {
        [FLAG_CARRY]: "c",
        [FLAG_PARITY]: "p",
        [FLAG_ADJUST]: "a",
        [FLAG_ZERO]: "z",
        [FLAG_SIGN]: "s",
        [FLAG_TRAP]: "t",
        [FLAG_INTERRUPT]: "i",
        [FLAG_DIRECTION]: "d",
        [FLAG_OVERFLOW]: "o",
    };
    var flag_string = "";

    for(var i = 0; i < 16; i++)
    {
        if(flag_names[1 << i])
        {
            if(flags & 1 << i)
            {
                flag_string += flag_names[1 << i];
            }
            else
            {
                flag_string += " ";
            }
        }
    }

    return ("mode=" + mode + "/" + op_size + " paging=" + (+((this.cr[0] & CR0_PG) !== 0)) +
        " pae=" + (+((this.cr[4] & CR4_PAE) !== 0)) +
        " iopl=" + iopl + " cpl=" + cpl + " if=" + if_ + " cs:eip=" + cs_eip +
        " cs_off=" + h(this.get_seg_cs() >>> 0, 8) +
        " flgs=" + h(this.get_eflags() >>> 0, 6) + " (" + flag_string + ")" +
        " ss:esp=" + ss_esp +
        " ssize=" + (+this.stack_size_32[0]) +
        (where ? " in " + where : ""));
};

/** @param {string=} where */
CPU.prototype.dump_state = function(where)
{
    if(!DEBUG) return;

    dbg_log(this.debug_get_state(where), LOG_CPU);
};

CPU.prototype.get_regs_short = function()
{
    if(!DEBUG) return;

    var
    r32 = { "eax": REG_EAX, "ecx": REG_ECX, "edx": REG_EDX, "ebx": REG_EBX,
        "esp": REG_ESP, "ebp": REG_EBP, "esi": REG_ESI, "edi": REG_EDI },
        r32_names = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"],
        s = { "cs": REG_CS, "ds": REG_DS, "es": REG_ES, "fs": REG_FS, "gs": REG_GS, "ss": REG_SS },
        line1 = "",
        line2 = "";

    for(var i = 0; i < 4; i++)
    {
        line1 += r32_names[i] + "="  + h(this.reg32[r32[r32_names[i]]] >>> 0, 8) + " ";
        line2 += r32_names[i+4] + "="  + h(this.reg32[r32[r32_names[i+4]]] >>> 0, 8) + " ";
    }

    //line1 += " eip=" + h(this.get_real_eip() >>> 0, 8);
    //line2 += " flg=" + h(this.get_eflags(), 8);

    line1 += "  ds=" + h(this.sreg[REG_DS], 4) + " es=" + h(this.sreg[REG_ES], 4) + " fs=" + h(this.sreg[REG_FS], 4);
    line2 += "  gs=" + h(this.sreg[REG_GS], 4) + " cs=" + h(this.sreg[REG_CS], 4) + " ss=" + h(this.sreg[REG_SS], 4);

    return [line1, line2];
};

CPU.prototype.dump_regs_short = function()
{
    if(!DEBUG) return;

    var lines = this.get_regs_short();

    dbg_log(lines[0], LOG_CPU);
    dbg_log(lines[1], LOG_CPU);
};

CPU.prototype.dump_gdt_ldt = function()
{
    if(!DEBUG) return;

    dbg_log("gdt: (len = " + h(this.gdtr_size[0]) + ")");
    dump_table(this.translate_address_system_read(this.gdtr_offset[0]), this.gdtr_size[0]);

    dbg_log("\nldt: (len = " + h(this.segment_limits[REG_LDTR]) + ")");
    dump_table(this.translate_address_system_read(this.segment_offsets[REG_LDTR]), this.segment_limits[REG_LDTR]);

    function dump_table(addr, size)
    {
        for(var i = 0; i < size; i += 8, addr += 8)
        {
            var base = this.read16(addr + 2) |
                this.read8(addr + 4) << 16 |
                this.read8(addr + 7) << 24,

                limit = this.read16(addr) | (this.read8(addr + 6) & 0xF) << 16,
                access = this.read8(addr + 5),
                flags = this.read8(addr + 6) >> 4,
                flags_str = "",
                dpl = access >> 5 & 3;

            if(!(access & 128))
            {
                // present bit not set
                //continue;
                flags_str += "NP ";
            }
            else
            {
                flags_str += " P ";
            }

            if(access & 16)
            {
                if(flags & 4)
                {
                    flags_str += "32b ";
                }
                else
                {
                    flags_str += "16b ";
                }

                if(access & 8)
                {
                    // executable
                    flags_str += "X ";

                    if(access & 4)
                    {
                        flags_str += "C ";
                    }
                }
                else
                {
                    // data
                    flags_str += "R ";
                }

                flags_str += "RW ";
            }
            else
            {
                // system
                flags_str += "sys: " + h(access & 15);
            }

            if(flags & 8)
            {
                limit = limit << 12 | 0xFFF;
            }

            dbg_log(h(i & ~7, 4) + " " + h(base >>> 0, 8) + " (" + h(limit >>> 0, 8) + " bytes) " +
                flags_str + ";  dpl = " + dpl + ", a = " + access.toString(2) +
                ", f = " + flags.toString(2));
        }
    }
};

CPU.prototype.dump_idt = function()
{
    if(!DEBUG) return;

    for(var i = 0; i < this.idtr_size[0]; i += 8)
    {
        var addr = this.translate_address_system_read(this.idtr_offset[0] + i),
            base = this.read16(addr) | this.read16(addr + 6) << 16,
            selector = this.read16(addr + 2),
            type = this.read8(addr + 5),
            line,
            dpl = type >> 5 & 3;

        if((type & 31) === 5)
        {
            line = "task gate ";
        }
        else if((type & 31) === 14)
        {
            line = "intr gate ";
        }
        else if((type & 31) === 15)
        {
            line = "trap gate ";
        }
        else
        {
            line = "invalid   ";
        }


        if(type & 128)
        {
            line += " P";
        }
        else
        {
            // present bit not set
            //continue;
            line += "NP";
        }


        dbg_log(h(i >> 3, 4) + " " + h(base >>> 0, 8) + ", " +
            h(selector, 4) + "; " + line + ";  dpl = " + dpl + ", t = " + type.toString(2));
    }
};

CPU.prototype.dump_page_structures = function()
{
    var pae = !!(this.cr[4] & CR4_PAE);
    if(pae)
    {
        dbg_log("PAE enabled");

        for(var i = 0; i < 4; i++) {
            var addr = this.cr[3] + 8 * i;
            var dword = this.read32s(addr);
            if(dword & 1)
            {
                this.dump_page_directory(dword & 0xFFFFF000, true, i << 30);
            }
        }
    }
    else
    {
        dbg_log("PAE disabled");
        this.dump_page_directory(this.cr[3], false, 0);
    }
};

// NOTE: PAE entries are 64-bits, we ignore the high half here.
CPU.prototype.dump_page_directory = function(pd_addr, pae, start)
{
    if(!DEBUG) return;

    function load_page_entry(dword_entry, pae, is_directory)
    {
        if(!DEBUG) return;

        if(!(dword_entry & 1))
        {
            // present bit not set
            return false;
        }

        var size = (dword_entry & 128) === 128,
            address;

        if(size && !is_directory)
        {
            address = dword_entry & (pae ? 0xFFE00000 : 0xFFC00000);
        }
        else
        {
            address = dword_entry & 0xFFFFF000;
        }

        return {
            size: size,
            global: (dword_entry & 256) === 256,
            accessed: (dword_entry & 0x20) === 0x20,
            dirty: (dword_entry & 0x40) === 0x40,
            cache_disable : (dword_entry & 16) === 16,
            user : (dword_entry & 4) === 4,
            read_write : (dword_entry & 2) === 2,
            address : address >>> 0
        };
    }

    var n = pae ? 512 : 1024;
    var entry_size = pae ? 8 : 4;
    var pd_shift = pae ? 21 : 22;

    for(var i = 0; i < n; i++)
    {
        var addr = pd_addr + i * entry_size,
            dword = this.read32s(addr),
            entry = load_page_entry(dword, pae, true);

        if(!entry)
        {
            continue;
        }

        var flags = "";

        flags += entry.size ? "S " : "  ";
        flags += entry.accessed ? "A " : "  ";
        flags += entry.cache_disable ? "Cd " : "  ";
        flags += entry.user ? "U " : "  ";
        flags += entry.read_write ? "Rw " : "   ";

        if(entry.size)
        {
            dbg_log("=== " + h(start + (i << pd_shift) >>> 0, 8) + " -> " +
                h(entry.address >>> 0, 8) + " | " + flags);
            continue;
        }
        else
        {
            dbg_log("=== " + h(start + (i << pd_shift) >>> 0, 8) + " | " + flags);
        }

        for(var j = 0; j < n; j++)
        {
            var sub_addr = entry.address + j * entry_size;
            dword = this.read32s(sub_addr);

            var subentry = load_page_entry(dword, pae, false);

            if(subentry)
            {
                flags = "";

                flags += subentry.cache_disable ? "Cd " : "   ";
                flags += subentry.user ? "U " : "  ";
                flags += subentry.read_write ? "Rw " : "   ";
                flags += subentry.global ? "G " : "  ";
                flags += subentry.accessed ? "A " : "  ";
                flags += subentry.dirty ? "Di " : "   ";

                dbg_log("# " + h(start + (i << pd_shift | j << 12) >>> 0, 8) + " -> " +
                    h(subentry.address, 8) + " | " + flags + "        (at " + h(sub_addr, 8) + ")");
            }
        }
    }
};

CPU.prototype.get_memory_dump = function(start, count)
{
    if(!DEBUG) return;

    if(start === undefined)
    {
        start = 0;
        count = this.memory_size[0];
    }
    else if(count === undefined)
    {
        count = start;
        start = 0;
    }

    return this.mem8.slice(start, start + count).buffer;
};

CPU.prototype.memory_hex_dump = function(addr, length)
{
    if(!DEBUG) return;

    length = length || 4 * 0x10;
    var line, byt;

    for(var i = 0; i < length >> 4; i++)
    {
        line = h(addr + (i << 4), 5) + "   ";

        for(var j = 0; j < 0x10; j++)
        {
            byt = this.read8(addr + (i << 4) + j);
            line += h(byt, 2) + " ";
        }

        line += "  ";

        for(j = 0; j < 0x10; j++)
        {
            byt = this.read8(addr + (i << 4) + j);
            line += (byt < 33 || byt > 126) ? "." : String.fromCharCode(byt);
        }

        dbg_log(line);
    }
};

CPU.prototype.used_memory_dump = function()
{
    if(!DEBUG) return;

    var width = 0x80,
        height = 0x10,
        block_size = this.memory_size[0] / width / height | 0,
        row;

    for(var i = 0; i < height; i++)
    {
        row = h(i * width * block_size, 8) + " | ";

        for(var j = 0; j < width; j++)
        {
            var used = this.mem32s[(i * width + j) * block_size] > 0;

            row += used ? "X" : " ";
        }

        dbg_log(row);
    }
};

CPU.prototype.debug_interrupt = function(interrupt_nr)
{
    //if(interrupt_nr === 0x20)
    //{
    //    //var vxd_device = this.safe_read16(this.instruction_pointer + 2);
    //    //var vxd_sub = this.safe_read16(this.instruction_pointer + 0);
    //    //var service = "";
    //    //if(vxd_device === 1)
    //    //{
    //    //    service = vxd_table1[vxd_sub];
    //    //}
    //    //dbg_log("vxd: " + h(vxd_device, 4) + " " + h(vxd_sub, 4) + " " + service);
    //}

    //if(interrupt_nr >= 0x21 && interrupt_nr < 0x30)
    //{
    //    dbg_log("dos: " + h(interrupt_nr, 2) + " ah=" + h(this.reg8[reg_ah], 2) + " ax=" + h(this.reg16[reg_ax], 4));
    //}

    //if(interrupt_nr === 0x13 && (this.reg8[reg_ah] | 1) === 0x43)
    //{
    //    this.debug.memory_hex_dump(this.get_seg(reg_ds) + this.reg16[reg_si], 0x18);
    //}

    //if(interrupt_nr == 0x10)
    //{
    //    dbg_log("int10 ax=" + h(this.reg16[reg_ax], 4) + " '" + String.fromCharCode(this.reg8[reg_al]) + "'");
    //    this.debug.dump_regs_short();
    //    if(this.reg8[reg_ah] == 0xe) vga.tt_write(this.reg8[reg_al]);
    //}

    //if(interrupt_nr === 0x13)
    //{
    //    this.debug.dump_regs_short();
    //}

    //if(interrupt_nr === 6)
    //{
    //    this.instruction_pointer += 2;
    //    dbg_log("BUG()", LOG_CPU);
    //    dbg_log("line=" + this.read_imm16() + " " +
    //            "file=" + this.read_string(this.translate_address_read(this.read_imm32s())), LOG_CPU);
    //    this.instruction_pointer -= 8;
    //    this.debug.dump_regs_short();
    //}

    //if(interrupt_nr === 0x80)
    //{
    //    dbg_log("linux syscall");
    //    this.debug.dump_regs_short();
    //}

    //if(interrupt_nr === 0x40)
    //{
    //    dbg_log("kolibri syscall");
    //    this.debug.dump_regs_short();
    //}
};
                                                                                                                                                                                                               source/v64/src/cpu_features.js                                                                      0000644 0000000 0000000 00000010050 00000000000 013472  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by gen/cpu_features.js from its feature table; do not edit.

/**
 * The CPU features of docs/simd-xsave-plan.md: bit in the machine's set
 * (src/rust/cpu/features.rs), required features, the lowest cpuid_level that
 * reports it, the CPU profiles that may have it and whether its milestone is
 * released (else it is for tests and development)
 */
export const CPU_FEATURES = {
    "SSSE3": {
        "bit": 0,
        "requires": [],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "SSE4.1": {
        "bit": 1,
        "requires": [
            "SSSE3"
        ],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "SSE4.2": {
        "bit": 2,
        "requires": [
            "SSE4.1"
        ],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "XSAVE": {
        "bit": 3,
        "requires": [],
        "min_cpuid_level": 13,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "AVX": {
        "bit": 4,
        "requires": [
            "XSAVE",
            "SSE4.2"
        ],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "AVX2": {
        "bit": 5,
        "requires": [
            "AVX"
        ],
        "min_cpuid_level": 7,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "FMA": {
        "bit": 6,
        "requires": [
            "AVX"
        ],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "F16C": {
        "bit": 7,
        "requires": [
            "AVX"
        ],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "BMI1": {
        "bit": 8,
        "requires": [],
        "min_cpuid_level": 7,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "BMI2": {
        "bit": 9,
        "requires": [],
        "min_cpuid_level": 7,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "LZCNT": {
        "bit": 10,
        "requires": [],
        "min_cpuid_level": 1,
        "profiles": [
            "x86_64"
        ],
        "released": true
    },
    "MOVBE": {
        "bit": 11,
        "requires": [],
        "min_cpuid_level": 1,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "XSAVEOPT": {
        "bit": 12,
        "requires": [
            "XSAVE"
        ],
        "min_cpuid_level": 13,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "XSAVEC": {
        "bit": 13,
        "requires": [
            "XSAVE"
        ],
        "min_cpuid_level": 13,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "XGETBV1": {
        "bit": 14,
        "requires": [
            "XSAVE"
        ],
        "min_cpuid_level": 13,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    },
    "XSAVES": {
        "bit": 15,
        "requires": [
            "XSAVEC"
        ],
        "min_cpuid_level": 13,
        "profiles": [
            "x86",
            "x86_64"
        ],
        "released": true
    }
};

/** Feature sets by name */
export const CPU_FEATURE_PRESETS = {
    "x86-64-v2": [
        "SSSE3",
        "SSE4.1",
        "SSE4.2"
    ],
    "x86-64-v3": [
        "SSSE3",
        "SSE4.1",
        "SSE4.2",
        "XSAVE",
        "AVX",
        "AVX2",
        "FMA",
        "F16C",
        "BMI1",
        "BMI2",
        "LZCNT",
        "MOVBE"
    ]
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/device_machine.js                                                                    0000644 0000000 0000000 00000030045 00000000000 013736  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A plugin's view of the machine (plugin side of src/device_plugin.js). v86
// hands a plugin a handle whose names are all quoted, because the plugin is
// not compiled with v86. DeviceMachine wraps that handle in a typed class, so
// that the device code reads like any other v86 device, and converts what
// crosses the boundary (port handlers, the PCI description) between plugin
// names and quoted names. Display adapters extend it (GraphicsMachine in
// src/graphics_adapters/machine.js); network and sound cards use it with
// their kind's part (NetMachine, AudioMachine). ISA cards (the SB16) have
// their interrupt line and the 8237's channels here too.

/**
 * Make a plugin's device known to v86. Plugin files call this when they load.
 * @param {string} registry the kind's global registry ("V86GraphicsAdapters",
 *     "V86NetAdapters", "V86AudioDevices")
 * @param {!Object} descriptor { "name", "create", ... }
 */
export function register_device_plugin(registry, descriptor)
{
    const entries = globalThis[registry] || (globalThis[registry] = {});
    entries[descriptor["name"]] = descriptor;
}

/**
 * @constructor
 * @param {!Object} handle the quoted machine handle from src/device_plugin.js
 */
export function DeviceMachine(handle)
{
    this.handle = handle;

    /** @const @type {string} */
    this.name = handle["name"];

    /** @const @type {!WebAssembly.Memory} */
    this.wasm_memory = handle["wasm_memory"];

    /** @const @type {boolean} */
    this.qemu_compatible = !!handle["qemu_compatible"];

    /** @const @type {string} "i440fx", "q35" */
    this.machine_type = handle["machine_type"] || "i440fx";
}

/**
 * Like IO.register_read; the handlers are called with `device` as this
 * @param {number} port
 * @param {!Object} device
 * @param {function(number):number=} r8
 * @param {function(number):number=} r16
 * @param {function(number):number=} r32
 */
DeviceMachine.prototype.register_read = function(port, device, r8, r16, r32)
{
    this.handle["register_read"](port, r8 && r8.bind(device), r16 && r16.bind(device), r32 && r32.bind(device));
};

/**
 * Like IO.register_write
 * @param {number} port
 * @param {!Object} device
 * @param {function(number)=} w8
 * @param {function(number)=} w16
 * @param {function(number)=} w32
 */
DeviceMachine.prototype.register_write = function(port, device, w8, w16, w32)
{
    this.handle["register_write"](port, w8 && w8.bind(device), w16 && w16.bind(device), w32 && w32.bind(device));
};

/**
 * Like IO.register_write_consecutive: two (or four) byte ports, wider writes split
 * @param {number} port
 * @param {!Object} device
 * @param {function(number)} w8_1
 * @param {function(number)} w8_2
 * @param {function(number)=} w8_3
 * @param {function(number)=} w8_4
 */
DeviceMachine.prototype.register_write_consecutive = function(port, device, w8_1, w8_2, w8_3, w8_4)
{
    this.handle["register_write_consecutive"](port, w8_1.bind(device), w8_2.bind(device),
        w8_3 && w8_3.bind(device), w8_4 && w8_4.bind(device));
};

/**
 * Like IO.register_read_consecutive: two (or four) byte ports, wider reads combined
 * @param {number} port
 * @param {!Object} device
 * @param {function():number} r8_1
 * @param {function():number} r8_2
 * @param {function():number=} r8_3
 * @param {function():number=} r8_4
 */
DeviceMachine.prototype.register_read_consecutive = function(port, device, r8_1, r8_2, r8_3, r8_4)
{
    this.handle["register_read_consecutive"](port, r8_1.bind(device), r8_2.bind(device),
        r8_3 && r8_3.bind(device), r8_4 && r8_4.bind(device));
};

/**
 * Like IO.mmap_register: whole 128 KiB blocks
 * @param {number} address
 * @param {number} size
 * @param {function(number):number} read8
 * @param {function(number, number)} write8
 * @param {function(number):number=} read32
 * @param {function(number, number)=} write32
 */
DeviceMachine.prototype.mmap_register = function(address, size, read8, write8, read32, write32)
{
    this.handle["mmap_register"](address, size, read8, write8, read32, write32);
};

/**
 * Like IO.mmap_register_range: an exact range (a BAR), owned by the device
 * @param {number} address
 * @param {number} size
 * @param {function(number):number} read8
 * @param {function(number, number)} write8
 * @param {function(number):number=} read32 aligned dwords
 * @param {function(number, number)=} write32
 */
DeviceMachine.prototype.mmap_register_range = function(address, size, read8, write8, read32, write32)
{
    this.handle["mmap_register_range"](address, size, read8, write8, read32, write32);
};

/**
 * @param {number} address
 * @param {number} size
 */
DeviceMachine.prototype.mmap_unregister_range = function(address, size)
{
    this.handle["mmap_unregister_range"](address, size);
};

/**
 * A free window of I/O ports for an I/O BAR
 * @param {number} size a power of two
 * @return {number} its first port
 */
DeviceMachine.prototype.allocate_io = function(size)
{
    return this.handle["allocate_io"](size);
};

/**
 * Another function of the device's PCI slot (a device of several, as EHCI
 * with its companions): a machine of its own for that function's PCI
 * registration, interrupt and configuration space
 * @param {number} number 0 to 7
 * @return {!DeviceMachine}
 */
DeviceMachine.prototype.function_machine = function(number)
{
    return new DeviceMachine(this.handle["function"](number));
};

/**
 * Describe the device on the PCI bus. v86 picks the slot. The hooks are
 * src/pci.js's: on_command_change (the command register: memory decode, bus
 * mastering), on_config_restore (a snapshot restored the space),
 * on_upstream_change (a bridge's forwarding changed), on_config_write
 * (offset, size: a write to the space beyond the header).
 * @param {{
 *     pci_space: !Array<number>,
 *     pci_bars: !Array<?{size: number, on_move: (function(number)|undefined)}>,
 *     pci_rom_size: (number|undefined),
 *     pci_rom_address: (number|undefined),
 *     on_command_change: (function()|undefined),
 *     on_config_restore: (function()|undefined),
 *     on_upstream_change: (function()|undefined),
 *     on_config_write: (function(number, number)|undefined),
 * }} description
 * @return {*} (v86's own record of the function; the device uses pci_config)
 */
DeviceMachine.prototype.register_pci = function(description)
{
    return this.handle["register_pci"]({
        "pci_space": description.pci_space,
        "pci_bars": description.pci_bars.map(bar => bar && { "size": bar.size, "on_move": bar.on_move }),
        "pci_rom_size": description.pci_rom_size,
        "pci_rom_address": description.pci_rom_address,
        "on_command_change": description.on_command_change,
        "on_config_restore": description.on_config_restore,
        "on_upstream_change": description.on_upstream_change,
        "on_config_write": description.on_config_write,
    });
};

/** @return {number} the device's PCI function (bus << 8 | device << 3 | function) */
DeviceMachine.prototype.pci_id = function()
{
    return this.handle["pci_id"]();
};

DeviceMachine.prototype.raise_irq = function()
{
    this.handle["raise_irq"]();
};

DeviceMachine.prototype.lower_irq = function()
{
    this.handle["lower_irq"]();
};

/**
 * Whether the function decodes memory at [base, base + size): memory space
 * enabled, and the bridges upstream forward the range
 * @param {number} base
 * @param {number} size
 * @return {boolean}
 */
DeviceMachine.prototype.memory_decoded = function(base, size)
{
    return this.handle["memory_decoded"](base, size);
};

/** @return {boolean} whether the function may master the bus (DMA, MSI) */
DeviceMachine.prototype.is_bus_master = function()
{
    return this.handle["is_bus_master"]();
};

/**
 * The bytes of a single-vector MSI capability (src/pci.js)
 * @param {number} next the next capability's offset, or 0
 * @return {!Array<number>}
 */
DeviceMachine.prototype.msi_capability = function(next)
{
    return this.handle["msi_capability"](next);
};

/**
 * The guest wrote the MSI capability at `cap`: keep its read-only bits
 * @param {number} cap
 * @param {number=} next
 */
DeviceMachine.prototype.msi_config_written = function(cap, next)
{
    this.handle["msi_config_written"](cap, next || 0);
};

/**
 * @param {number} cap
 * @return {boolean}
 */
DeviceMachine.prototype.msi_enabled = function(cap)
{
    return this.handle["msi_enabled"](cap);
};

/**
 * Send the message of the MSI capability at `cap`
 * @param {number} cap
 * @return {boolean} whether a local APIC accepted it
 */
DeviceMachine.prototype.msi_notify = function(cap)
{
    return this.handle["msi_notify"](cap);
};

/**
 * The function's configuration space, a view taken now (a snapshot restores
 * it in place; the view is not kept)
 * @return {!Uint8Array}
 */
DeviceMachine.prototype.pci_config = function()
{
    return this.handle["pci_config"]();
};

/**
 * An ISA card's interrupt line (0 to 15): raised
 * @param {number} irq
 */
DeviceMachine.prototype.isa_raise_irq = function(irq)
{
    this.handle["isa_raise_irq"](irq);
};

/** @param {number} irq */
DeviceMachine.prototype.isa_lower_irq = function(irq)
{
    this.handle["isa_lower_irq"](irq);
};

/**
 * The 8237 DMA: `listener` is called with a channel when the guest unmasks it
 * @param {function(number)} listener
 */
DeviceMachine.prototype.dma_on_unmask = function(listener)
{
    this.handle["dma_on_unmask"](listener);
};

/**
 * @param {number} channel
 * @return {boolean} whether the guest masked the channel (its DREQ is ignored)
 */
DeviceMachine.prototype.dma_masked = function(channel)
{
    return this.handle["dma_masked"](channel);
};

/**
 * A transfer from memory to the device on `channel` (the 8237 programmed by
 * the guest), into `target` from `start`, at most `length` bytes: the
 * DMA's callback (error, cause, retry)
 * @param {number} channel
 * @param {!Uint8Array} target
 * @param {number} start
 * @param {number} length
 * @param {function(boolean, *=, function()=)} callback
 */
DeviceMachine.prototype.dma_write = function(channel, target, start, length, callback)
{
    this.handle["dma_write"](channel, target, start, length, callback);
};

/**
 * Guest physical memory, including RAM above 4 GiB
 * @param {number} address
 * @param {number} length
 * @return {!Uint8Array}
 */
DeviceMachine.prototype.read_physical = function(address, length)
{
    return this.handle["read_physical"](address, length);
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 */
DeviceMachine.prototype.write_physical = function(bytes, address)
{
    this.handle["write_physical"](bytes, address);
};

/**
 * @param {number} address
 * @return {number}
 */
DeviceMachine.prototype.read16_physical = function(address)
{
    return this.handle["read16_physical"](address);
};

/**
 * @param {number} address
 * @return {number}
 */
DeviceMachine.prototype.read32_physical = function(address)
{
    return this.handle["read32_physical"](address);
};

/**
 * @param {number} address
 * @param {number} value
 */
DeviceMachine.prototype.write16_physical = function(address, value)
{
    this.handle["write16_physical"](address, value);
};

/**
 * @param {number} address
 * @param {number} value
 */
DeviceMachine.prototype.write32_physical = function(address, value)
{
    this.handle["write32_physical"](address, value);
};

/**
 * Whether [address, address + length) is guest memory a device may access
 * (throws a RangeError where it is not)
 * @param {number} address
 * @param {number} length
 * @return {boolean}
 */
DeviceMachine.prototype.validate_physical_range = function(address, length)
{
    return this.handle["validate_physical_range"](address, length);
};

/** @return {number} the machine clock, in milliseconds */
DeviceMachine.prototype.now = function()
{
    return this.handle["now"]();
};

/**
 * Called whenever the machine's timers run (each slice of the CPU's): a
 * device's own polling. Returns milliseconds until it needs to run again.
 * @param {function(number):number} timer
 */
DeviceMachine.prototype.add_timer = function(timer)
{
    this.handle["add_timer"](timer);
};

/**
 * Something outside the machine's own run (a frame from the network) set a
 * deadline: run the timers soon, also when the machine is halted
 */
DeviceMachine.prototype.wake = function()
{
    this.handle["wake"]();
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/device_plugin.js                                                                     0000644 0000000 0000000 00000051273 00000000000 013636  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Device plugins: display adapters (src/graphics_adapter.js), network cards
// (net_device.type "ne2k", "e1000") and sound cards (audio_device "sb16",
// "hd_audio") each live in their own file and are loaded only when
// configured. This is v86's side of what they share: finding and loading a
// plugin file, the machine handle a plugin works with, the machine's timers,
// and the plugin's slot in a snapshot. Plugins are not compiled with v86 (an ADVANCED build renames
// properties), so the handle, the descriptor and the device use quoted names
// only. src/device_machine.js is the plugin's end of it.
// See docs/gpu-devices.md, "Adapter plugins", and
// docs/modern-pc-devices-plan.md, "设备插件".

import { LOG_PCI } from "./const.js";
import { BlockBackend, block_drop_holds } from "./block_backend.js";
import { dbg_log } from "./log.js";
import { msi_capability } from "./pci.js";

// For Types Only
import { CPU } from "./cpu.js";

/* global __dirname, V86_BUNDLE, V86_BUNDLE_URL */

const NODE = typeof process !== "undefined" && process.versions && process.versions.node;

/**
 * The bundle's own URL: plugins are built beside it. libv86.mjs gets it from
 * its output wrapper (import.meta.url); a classic script in a page (libv86.js)
 * from document.currentScript while it runs
 */
const BUNDLE_URL = typeof V86_BUNDLE_URL === "string" ? V86_BUNDLE_URL :
    typeof document !== "undefined" && document.currentScript && document.currentScript.src || "";

/** Where allocate_io looks for ports (below the virtio_devices pool at 0xE000) */
const IO_POOL_START = 0xD000;
const IO_POOL_END = 0xE000;

/**
 * The kinds of plugin: the global registry plugin files add their
 * descriptors to, the option that names them (for messages), the directory
 * of their entry modules in the source tree (or the entry module itself:
 * one plugin of the kind), their snapshot slot's tag, and the plugin whose
 * state an untagged slot is (the device the slot held before plugins)
 * @typedef {{registry: string, option: string, dir: string, tag: string, entry: (string|undefined), legacy: (string|undefined)}}
 */
export let PluginKind;

/** @const @type {PluginKind} */
export const GRAPHICS_PLUGINS = { registry: "V86GraphicsAdapters", option: "graphics_adapter", dir: "graphics_adapters", tag: "graphics_adapter" };
/** @const @type {PluginKind} (state[59] was the NE2000's own state before it was a plugin) */
export const NET_PLUGINS = { registry: "V86NetAdapters", option: "net_device", dir: "net_adapters", tag: "net_adapter", legacy: "ne2k" };
/** @const @type {PluginKind} (state[61] was the SB16's own state before it was a plugin) */
export const AUDIO_PLUGINS = { registry: "V86AudioDevices", option: "audio_device", dir: "audio_devices", tag: "audio_device", legacy: "sb16" };
/** @const @type {PluginKind} the USB controllers and devices: one plugin, "usb" */
export const USB_PLUGINS = { registry: "V86UsbControllers", option: "usb", dir: "usb", tag: "usb", entry: "./usb/plugin.js" };
/** @const @type {PluginKind} the TPM 2.0 (docs/tpm.md): one plugin, "tpm" */
export const TPM_PLUGINS = { registry: "V86TpmDevices", option: "tpm", dir: "tpm", tag: "tpm", entry: "./tpm/plugin.js" };
/** @const @type {PluginKind} the GLES host of the ranchu machine (docs/gles-proxy-plan.md): one plugin, "gles" */
export const GLES_PLUGINS = { registry: "V86GlesHosts", option: "ranchu_gpu", dir: "gles", tag: "gles", entry: "./gles/plugin.js" };

/**
 * The TPM's module (build/libtpms.wasm) where tpm.wasm_path does not say:
 * beside the bundle, as the plugins
 * @return {string}
 */
export function default_tpm_wasm_path()
{
    if(BUNDLE_URL) return beside_bundle("libtpms.wasm");
    if(NODE && typeof __dirname === "string") return __dirname + "/libtpms.wasm";
    return "build/libtpms.wasm";
}

/**
 * The GLES host's GLSL ES compiler (build/glslang.wasm, docs/gles3-plan.md)
 * where gles_glslang_path does not say: beside the bundle, as the plugins
 * @return {string}
 */
export function default_glslang_wasm_path()
{
    if(BUNDLE_URL) return beside_bundle("glslang.wasm");
    if(NODE && typeof __dirname === "string") return __dirname + "/glslang.wasm";
    return "build/glslang.wasm";
}

/** A plugin slot's snapshot entry: [tag, STATE_VERSION, name, device state] */
const STATE_VERSION = 1;

/**
 * A file beside the bundle, with the bundle's query: a page that loads
 * libv86.js?v=<revision> (a version against stale caches) gets the plugins
 * of that revision as well
 * @param {string} file
 * @return {string}
 */
function beside_bundle(file)
{
    const url = new URL(file, BUNDLE_URL);
    url.search = new URL(BUNDLE_URL).search;
    return url.href;
}

/**
 * The file of a plugin: v86-<name>.js, underscores as dashes
 * @param {string} name
 * @return {string}
 */
export function plugin_file(name)
{
    return "v86-" + name.replace(/_/g, "-") + ".js";
}

/**
 * Where a bundle looks for a plugin without a path option: beside the bundle
 * where it knows its own location (a classic script in a page, CommonJS in
 * node), otherwise build/ relative to the page, like wasm_path
 * @param {string} name
 * @return {string}
 */
export function default_plugin_path(name)
{
    const file = plugin_file(name);
    if(BUNDLE_URL) return beside_bundle(file);
    if(NODE && typeof __dirname === "string") return __dirname + "/" + file;
    return "build/" + file;
}

/**
 * An absolute URL of a plugin file
 * @param {string} path
 * @return {string}
 */
export function resolve_plugin_path(path)
{
    if(NODE)
    {
        if(/^[a-z]+:/i.test(path)) return path;
        const absolute = path.startsWith("/") ? path : process["cwd"]() + "/" + path;
        return "file://" + absolute;
    }
    return new URL(path, typeof location !== "undefined" ? location.href : undefined).href;
}

/**
 * @param {PluginKind} kind
 * @param {string} name
 * @return {Object|undefined}
 */
function registered(kind, name)
{
    const registry = globalThis[kind.registry];
    return registry ? registry[name] : undefined;
}

/**
 * Load a plugin, unless the page already did
 * @param {PluginKind} kind
 * @param {string} name
 * @param {string|undefined} path the kind's path option
 * @param {string} path_option its name, for messages
 * @return {!Promise<!Object>} its descriptor (checked: a "name" and a "create")
 */
export async function load_device_plugin(kind, name, path, path_option)
{
    const label = kind.option + " \"" + name + "\"";
    let descriptor = registered(kind, name);

    if(!descriptor)
    {
        if(typeof V86_BUNDLE === "undefined" && path === undefined)
        {
            // From the source tree: the plugin's entry module
            await import(kind.entry || "./" + kind.dir + "/" + name + "/plugin.js");
        }
        else
        {
            const url = resolve_plugin_path(path || default_plugin_path(name));
            try
            {
                if(typeof importScripts === "function")
                {
                    // a classic worker (the CPU worker)
                    importScripts(url);
                }
                else
                {
                    await import(url);
                }
            }
            catch(error)
            {
                throw new Error(label + ": cannot load " + url +
                    " (" + (error && error.message || error) + "); set " + path_option + " to the plugin file");
            }
        }

        descriptor = registered(kind, name);
        if(!descriptor)
        {
            throw new Error(label + ": the plugin file defines no such device");
        }
    }

    if(descriptor["name"] !== name || typeof descriptor["create"] !== "function")
    {
        throw new Error(label + ": invalid plugin descriptor");
    }
    return descriptor;
}

/**
 * A free window of I/O ports for an I/O BAR, aligned to its size: the same
 * one for the same machine configuration, so that snapshots line up. The
 * guest's firmware usually moves it anyway (PCI.set_io_bars).
 * @param {CPU} cpu
 * @param {number} size a power of two
 * @param {string} label for the message
 * @return {number}
 */
export function allocate_io_ports(cpu, size, label)
{
    const ports = cpu.io.ports;
    for(let base = IO_POOL_START; base + size <= IO_POOL_END; base += size)
    {
        let free = true;
        for(let port = base; port < base + size && free; port++)
        {
            free = !ports[port].device;
        }
        if(free) return base;
    }
    throw new Error(label + ": no free I/O ports");
}

/**
 * What every plugin works with (src/device_machine.js): ports and memory
 * maps, guest memory, the machine clock and timers, IRQs and the PCI
 * function. `owner` owns the port and memory map entries (the plugin's
 * handlers come bound to its own device) and has `name`, `pci_id` and
 * `register_pci(description)`.
 * @param {CPU} cpu
 * @param {!Object} owner
 * @return {!Object}
 */
export function device_handle(cpu, owner)
{
    const io = cpu.io;
    const pci = () => cpu.devices.pci;
    return {
        "name": owner.name,
        "wasm_memory": cpu.wasm_memory,
        "qemu_compatible": !!(cpu.platform && cpu.platform.qemu_compatible),
        "machine_type": cpu.platform ? cpu.platform.machine : "i440fx",

        "register_read": (port, r8, r16, r32) => io.register_read(port, owner, r8, r16, r32),
        "register_write": (port, w8, w16, w32) => io.register_write(port, owner, w8, w16, w32),
        "register_write_consecutive": (port, w8_1, w8_2, w8_3, w8_4) =>
        {
            if(w8_3) io.register_write_consecutive(port, owner, w8_1, w8_2, w8_3, w8_4);
            else io.register_write_consecutive(port, owner, w8_1, w8_2);
        },
        "register_read_consecutive": (port, r8_1, r8_2, r8_3, r8_4) =>
        {
            if(r8_3) io.register_read_consecutive(port, owner, r8_1, r8_2, r8_3, r8_4);
            else io.register_read_consecutive(port, owner, r8_1, r8_2);
        },
        "mmap_register": (address, size, r8, w8, r32, w32) => io.mmap_register(address, size, r8, w8, r32, w32),
        // an exact range inside a 128 KiB block (docs/arm64-virt-android16-plan.md P1.7)
        "mmap_register_range": (address, size, r8, w8, r32, w32) => io.mmap_register_range(address, size, owner, r8, w8, r32, w32),
        "mmap_unregister_range": (address, size) => io.mmap_unregister_range(address, size, owner),
        "allocate_io": size => owner.allocate_io ? owner.allocate_io(size) : allocate_io_ports(cpu, size, owner.name),

        "register_pci": description => owner.register_pci(description),
        "pci_id": () => owner.pci_id,
        "raise_irq": () => pci().raise_irq(owner.pci_id),
        "lower_irq": () => pci().lower_irq(owner.pci_id),
        // whether the function decodes memory at [base, base + size): its memory
        // space is enabled and the bridges upstream forward the range
        "memory_decoded": (base, size) => pci().memory_decoded(owner.pci_id, base, size),
        // whether it may master the bus (DMA, MSI)
        "is_bus_master": () => pci().is_bus_master(owner.pci_id),
        // single-vector MSI: the capability's bytes (src/pci.js), and the
        // calls with its offset in the configuration space
        "msi_capability": next => msi_capability(next),
        "msi_config_written": (cap, next) => pci().msi_config_written(owner.pci_id, cap, next || 0),
        "msi_enabled": cap => pci().msi_enabled(owner.pci_id, cap),
        "msi_notify": cap => pci().msi_notify(owner.pci_id, cap),
        // the function's configuration space as bytes (a view taken now): a
        // device keeps its capabilities' read-only bytes after a write
        "pci_config": () => pci().space_bytes(owner.pci_id),

        // an ISA card's: its interrupt line (0 to 15), the 8237's channels
        // (a listener for a channel unmasked, whether one is masked, a
        // transfer to memory into `target` at `start`, the callback the
        // DMA's: (error, cause, retry))
        "isa_raise_irq": irq => cpu.device_raise_irq(irq),
        "isa_lower_irq": irq => cpu.device_lower_irq(irq),
        "dma_on_unmask": listener => cpu.devices.dma.on_unmask(listener, owner),
        "dma_masked": channel => cpu.devices.dma.channel_mask[channel] !== 0,
        "dma_write": (channel, target, start, length, callback) =>
            cpu.devices.dma.do_write(byte_target(target), start, length, channel, callback),

        "read_physical": (address, length) => cpu.read_blob_physical(address, length),
        "write_physical": (bytes, address) => cpu.write_blob_physical(bytes, address),
        "read16_physical": address => cpu.read16_physical(address),
        "read32_physical": address => cpu.read32_physical(address),
        "write16_physical": (address, value) => cpu.write16_physical(address, value),
        "write32_physical": (address, value) => cpu.write32_physical(address, value),
        "validate_physical_range": (address, length) => cpu.validate_physical_range(address, length),

        "now": () => cpu.clock.now(),
        // run whenever the machine's timers run (each slice of the CPU's);
        // returns milliseconds until it needs to run again
        "add_timer": timer => /** @type {?} */ (cpu).add_device_timer(timer),
        // an event from the host (a frame from the network) set a deadline:
        // a halted machine runs its timers again now rather than when it
        // planned to wake
        "wake": () => cpu.stop_idling(),
        // a disk image the host gave the plugin (a USB disk's): block_handle
        "block_backend": buffer => block_handle(/** @type {!CPU} */ (cpu), buffer),
        // another function of the device's PCI slot: function_handle
        "function": number => function_handle(cpu, owner, number),
    };
}

/**
 * A plugin's bytes as the DMA writes into a buffer object (src/buffer.js):
 * the plugin is not compiled with v86, so it hands over the bytes, not one
 * of its own buffer objects
 * @param {!Uint8Array} target
 * @return {!Object}
 */
function byte_target(target)
{
    return {
        byteLength: target.length,
        set: (start, data, done) =>
        {
            target.set(data, start);
            done();
        },
    };
}

/**
 * Another function of a plugin's PCI device (EHCI's UHCI companions,
 * functions 0 to 2 beside its 7): its own PCI function (register_pci,
 * interrupt pin, configuration space, bus mastering); the rest is the
 * machine's, as the device's own handle has it
 * @param {CPU} cpu
 * @param {!Object} owner the device's owner (PluginDevice)
 * @param {number} number the function, 0 to 7
 * @return {!Object}
 */
function function_handle(cpu, owner, number)
{
    const sub = {
        name: owner.name + "." + number,
        pci_id: owner.pci_id & ~7 | number,
        pci_device: null,
        register_pci: description =>
        {
            if(sub.pci_device) throw new Error(owner.name + ": PCI function " + number + " registered twice");
            sub.pci_device = plugin_pci_device(sub, description);
            // (a reset of the function is the device's)
            sub.pci_device.reset = () => owner.reset();
            dbg_log(owner.name + " function " + number + " at PCI " + sub.pci_id.toString(16), LOG_PCI);
            return cpu.devices.pci.register_device(sub.pci_device);
        },
    };
    return device_handle(cpu, sub);
}

/**
 * A disk image for a plugin's device: the core's block backend
 * (src/block_backend.js) on the image's buffer, by quoted names: reads a
 * reset cancels, "flush" after the writes before it, I/O a snapshot waits
 * for, the disk's error policy; "drop" when the device is gone (its requests
 * held after an error are dropped)
 * @param {!CPU} cpu
 * @param {!Object} buffer
 * @return {!Object}
 */
export function block_handle(cpu, buffer)
{
    const backend = new BlockBackend(cpu, buffer);
    return {
        "byte_length": backend.byte_length,
        "read": (start, length, callback, on_error) => backend.read(start, length, callback, on_error),
        "write": (start, data, callback, on_error) => backend.write(start, data, callback, on_error),
        "flush": (callback, on_error) => backend.when_writes_done(callback, on_error),
        "reset": () => backend.reset(),
        "drop": () => block_drop_holds(backend),
    };
}

/**
 * The PCI function a plugin describes (register_pci), with the hooks of
 * src/pci.js that it may give
 * @param {!Object} owner { name, pci_id }
 * @param {!Object} description quoted { pci_space, pci_bars, pci_rom_size,
 *     pci_rom_address, on_command_change, on_config_restore,
 *     on_upstream_change, on_config_write }
 * @return {!Object}
 */
export function plugin_pci_device(owner, description)
{
    const device = {
        name: owner.name,
        pci_id: owner.pci_id,
        pci_space: description["pci_space"],
        pci_bars: description["pci_bars"].map(bar => bar && {
            size: bar["size"],
            on_move: bar["on_move"],
        }),
        pci_rom_size: description["pci_rom_size"],
        pci_rom_address: description["pci_rom_address"],
    };
    for(const hook of ["on_command_change", "on_config_restore", "on_upstream_change", "on_config_write"])
    {
        if(typeof description[hook] === "function") device[hook] = description[hook];
    }
    return device;
}

/**
 * A network or sound card from a plugin: v86's side of the device. The
 * machine puts it at `pci_id` (its kind's slot); the device's state is the
 * kind's snapshot slot ([tag, version, name, state]).
 * @constructor
 * @param {CPU} cpu
 * @param {PluginKind} kind
 * @param {!Object} descriptor from load_device_plugin
 * @param {number} pci_id
 * @param {!Object} extra the kind's part of the handle (quoted names)
 * @param {!Object} options the device's options (quoted names)
 */
export function PluginDevice(cpu, kind, descriptor, pci_id, extra, options)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.kind = kind;
    this.descriptor = descriptor;
    /** @const @type {string} */
    this.name = descriptor["name"];
    this.pci_id = pci_id;
    this.pci_device = null;

    const handle = Object.assign(device_handle(cpu, this), extra);
    this.device = descriptor["create"](handle, options);
    if(!this.device || typeof this.device["get_state"] !== "function" || typeof this.device["set_state"] !== "function")
    {
        throw new Error(kind.option + " \"" + this.name + "\": the plugin made no device");
    }
}

/**
 * @param {!Object} description quoted, see plugin_pci_device
 */
PluginDevice.prototype.register_pci = function(description)
{
    if(this.pci_device)
    {
        throw new Error(this.kind.option + " \"" + this.name + "\" registered its PCI function twice");
    }
    this.pci_device = plugin_pci_device(this, description);
    // (a reset of the function alone, e.g. a hot plugged card arriving)
    this.pci_device.reset = () => this.reset();
    dbg_log(this.kind.option + " \"" + this.name + "\" at PCI " + this.pci_id.toString(16), LOG_PCI);
    return this.cpu.devices.pci.register_device(this.pci_device);
};

/** A machine reset (PCIRST#): the plugin's optional reset hook */
PluginDevice.prototype.reset = function()
{
    const reset = this.device["reset"];
    if(typeof reset === "function") reset();
};

/** The machine goes away: the plugin's optional destroy hook */
PluginDevice.prototype.destroy = function()
{
    const destroy = this.device["destroy"];
    if(typeof destroy === "function") destroy();
};

PluginDevice.prototype.get_state = function()
{
    return [this.kind.tag, STATE_VERSION, this.name, this.device["get_state"]()];
};

/**
 * Throws if a snapshot's slot does not belong to this device. Changes
 * nothing, so that CPU.validate_state can call it before restoring anything.
 * @param {*} state
 */
PluginDevice.prototype.check_state = function(state)
{
    const saved = plugin_of_state(this.kind, state);
    if(saved !== this.name)
    {
        throw new Error("The snapshot is from a machine " + (saved === null ? "without " + this.kind.option + " \"" + this.name + "\"" :
            "with " + this.kind.option + ": \"" + saved + "\", this one has \"" + this.name + "\""));
    }
    if(state[0] === this.kind.tag && state[1] !== STATE_VERSION)
    {
        throw new Error("Unsupported " + this.kind.option + " state version " + state[1]);
    }
};

/** @param {*} state */
PluginDevice.prototype.set_state = function(state)
{
    this.check_state(state);
    // (an untagged slot: the state of the kind's device before plugins,
    // which its plugin reads as it is)
    this.device["set_state"](state[0] === this.kind.tag ? state[3] : state);
};

/**
 * Which plugin a snapshot's slot belongs to: its name, or null if the slot is
 * empty. An untagged slot is the kind's device before plugins (the NE2000's,
 * the SB16's).
 * @param {PluginKind} kind
 * @param {*} state
 * @return {?string}
 */
export function plugin_of_state(kind, state)
{
    if(!Array.isArray(state)) return null;
    return state[0] === kind.tag ? state[2] : kind.legacy || null;
}
                                                                                                                                                                                                                                                                                                                                     source/v64/src/disk_options.js                                                                      0000644 0000000 0000000 00000026051 00000000000 013522  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The policy of a disk (docs/disk-persistence-plan.md): where the guest's
// writes go (disk_option: "read_only", the default, keeps them in memory;
// "read_write" writes them back to the image), and what a failed read or
// write does (disk_error: "stop", the default, stops the machine until
// run() retries the request; "report" ends the command with the device's
// error status). Both are options of each disk's descriptor, never of the
// V86 options themselves; they are checked when the machine is created (and
// when attach_sata_drive attaches a drive), before anything is loaded.
//
// A disk's buffer carries its policy for src/block_backend.js: disk_name
// (hda, hdb, sata<port>, cdrom, virtio_disk<n>, usb:<id>) and disk_error.

/** what disk_option may be */
export const DISK_OPTIONS = ["read_only", "read_write"];

/** what disk_error may be */
export const DISK_ERRORS = ["stop", "report"];

/** what a buffer object of one's own needs for disk_option "read_write" (besides load, get, set) */
export const BACKEND_CONTRACT = ["flush", "close", "mark", "generation", "get_state", "set_state", "check_state"];

/**
 * What kind of descriptor a name is
 * @param {string} name
 * @return {string} "hard_disk", "cdrom", "floppy" or "other"
 */
export function disk_kind(name)
{
    // (the UEFI firmware's variable store and the TPM's state are written
    // back as a disk is: docs/uefi.md, docs/tpm.md)
    if(name === "hda" || name === "hdb" || /^sata\d+$/.test(name) || /^virtio_disk\d+$/.test(name) || name.startsWith("usb:") ||
        name === "firmware_vars" || name === "tpm_state") return "hard_disk";
    if(name === "cdrom") return "cdrom";
    if(name === "fda" || name === "fdb") return "floppy";
    return "other";
}

/**
 * @param {string} message
 * @return {!Error}
 */
function config_error(message)
{
    const error = new Error(message);
    /** @type {?} */ (error).kind = "config";
    return error;
}

/**
 * Whether we run in Node (where a disk's url is a local file path)
 * @return {boolean}
 */
export function in_node()
{
    return typeof process !== "undefined" && !!process.versions && !!process.versions.node &&
        typeof XMLHttpRequest === "undefined";
}

/**
 * Why a descriptor's image cannot take disk_option "read_write", or "" if
 * it can (docs/disk-persistence-plan.md "配置": a disk service's URL, a
 * local file in Node, a buffer object implementing the backend contract)
 * @param {string} name
 * @param {!Object} file
 * @return {string}
 */
export function writeback_problem(name, file)
{
    const keep = " Without disk_option (or with \"read_only\"), the guest's changes stay in memory.";
    if(file.get && file.set && file.load)
    {
        const missing = BACKEND_CONTRACT.filter(method => typeof file[method] !== "function");
        return missing.length ? name + ": a buffer object of one's own is written back only when it implements the backend contract " +
            "(docs/disk-persistence-plan.md, \"后端契约\"); it has no " + missing.join(", ") + "." + keep : "";
    }
    if(file.buffer instanceof ArrayBuffer)
    {
        return name + ": an ArrayBuffer is an image in memory, with no persistent source to write the changes back to." + keep +
            " (They change that ArrayBuffer itself: pass a copy to keep the original.)";
    }
    if(typeof Blob !== "undefined" && file.buffer instanceof Blob)
    {
        return name + ": a File cannot be written back (a browser does not write into a file the user picked in place). " +
            "To keep the changes in a file of your own, serve it with the local disk service (tools/disk-service.mjs)." + keep;
    }
    if(typeof file.url !== "string")
    {
        return name + ": disk_option \"read_write\" needs a url (a disk service, or a local file in Node)." + keep;
    }
    if(file.use_parts || file.url.endsWith(".zst"))
    {
        return name + ": an image in parts (use_parts, .zst) can only be read, not written back." + keep;
    }
    // (in Node a local file, src/disk_writeback.js; a URL: a disk service,
    // src/disk_service.js, which tells at the start whether it is one)
    return "";
}

/**
 * Whether a disk written back is a disk service's (a URL), not a local
 * file (in Node, a path)
 * @param {string} url
 * @return {boolean}
 */
export function is_service_url(url)
{
    return !in_node() || /^https?:\/\//i.test(url);
}

/**
 * Check a descriptor's disk_option, disk_error and token
 * @param {string} name hda, hdb, cdrom, fda, sata<port>, virtio_disk<n>, bios, ...
 * @param {*} file the descriptor (or a buffer object of one's own)
 * @return {{disk_option: string, disk_error: string}}
 */
export function check_disk_policy(name, file)
{
    const policy = { disk_option: "read_only", disk_error: "stop" };
    if(!file || typeof file !== "object") return policy;
    // (a browser disk, docs/vm-manager-plan.md U6: in a browser's private storage)
    if(typeof file.url === "string" && file.url.startsWith("opfs:") && in_node())
    {
        throw config_error(name + ": a browser disk (" + file.url + ") is in a browser's private storage (OPFS), not in Node");
    }
    const option = file.disk_option, on_error = file.disk_error, token = file.token;
    const kind = disk_kind(name);
    if(option !== undefined)
    {
        if(kind === "other" || kind === "cdrom")
        {
            throw config_error(name + ": disk_option is for disks (hda, hdb, fda, fdb, SATA drives, virtio_disks, USB disks), not " + name);
        }
        if(!DISK_OPTIONS.includes(option))
        {
            throw config_error(name + ": disk_option " + JSON.stringify(option) + " is not one of " + DISK_OPTIONS.join(", "));
        }
        policy.disk_option = option;
    }
    if(on_error !== undefined)
    {
        if(kind === "other")
        {
            throw config_error(name + ": disk_error is for disks and CD drives, not " + name);
        }
        if(!DISK_ERRORS.includes(on_error))
        {
            throw config_error(name + ": disk_error " + JSON.stringify(on_error) + " is not one of " + DISK_ERRORS.join(", "));
        }
        policy.disk_error = on_error;
    }
    if(token !== undefined)
    {
        if(kind === "other")
        {
            throw config_error(name + ": token is for disks (a disk service's), not " + name);
        }
        if(typeof token !== "string")
        {
            throw config_error(name + ": token must be a string");
        }
    }
    if(policy.disk_option === "read_write")
    {
        if(file.readonly)
        {
            throw config_error(name + ": disk_option \"read_write\" and readonly: the guest cannot write the disk, " +
                "there is nothing to write back");
        }
        if(file.format !== undefined && file.format !== "raw")
        {
            throw config_error(name + ": disk_option \"read_write\" is for RAW images; writing back into a " + file.format +
                " image is not supported (docs/disk-image-formats-plan.md P5)");
        }
        const problem = writeback_problem(name, file);
        if(problem) throw config_error(problem);
    }
    return policy;
}

/**
 * The source a descriptor reads, to find a source bound twice: its URL, or
 * its buffer object
 * @param {!Object} file
 * @return {*}
 */
function source_of(file)
{
    if(file.get && file.set && file.load) return file;
    if(file.buffer) return file.buffer;
    if(typeof file.url === "string")
    {
        try { return "url:" + new URL(file.url, globalThis.location ? globalThis.location.href : undefined).href; }
        catch(e) { return "url:" + file.url; }
    }
    return undefined;
}

/**
 * Check the disks of a machine's options (the V86 constructor): no
 * disk_option, disk_error or token in the V86 options themselves, each
 * disk's policy, and no image bound to two disks with one of them
 * read_write
 * @param {!Object} options the V86 options
 * @param {!Array<!Array<*>>=} also [name, descriptor] of disks attached already (attach_sata_drive)
 * @return {!Array<!Array<*>>} [name, descriptor, policy] of each disk
 */
export function check_disk_options(options, also)
{
    // (the options by property, as the rest of v86 reads them: an ADVANCED
    // build, as the old page's v86_all.js was, renames them alike)
    for(const [key, value] of [["disk_option", options.disk_option], ["disk_error", options.disk_error], ["token", options.token]])
    {
        if(value !== undefined)
        {
            throw config_error(key + " is an option of each disk (hda: { url, " + key + " }), not of the machine");
        }
    }
    const disks = [["hda", options.hda], ["hdb", options.hdb], ["cdrom", options.cdrom], ["fda", options.fda], ["fdb", options.fdb]]
        .filter(([, file]) => file);
    (options.virtio_disks || []).forEach((disk, i) => { if(disk) disks.push(["virtio_disk" + i, disk]); });
    // (usb.mass_storage: "usb:" and the disk's id)
    (options.usb && options.usb.mass_storage || []).forEach(disk => { if(disk && disk.image) disks.push(["usb:" + disk.id, disk.image]); });
    const firmware = options.firmware || {};
    const tpm = options.tpm || {};
    for(const [name, file] of [["bios", options.bios], ["vga_bios", options.vga_bios], ["firmware_code", firmware.code], ["firmware_vars", firmware.vars],
        ["tpm_state", tpm.state],
        ["initial_state", options.initial_state],
        ["multiboot", options.multiboot], ["bzimage", options.bzimage], ["initrd", options.initrd], ["kernel", options.kernel], ["dtb", options.dtb]])
    {
        check_disk_policy(name, file);
    }
    return check_disk_bindings(disks.map(([name, file]) => [name, file, check_disk_policy(name, file)]), also);
}

/**
 * No image bound to two disks of a machine with one of them read_write
 * @param {!Array<!Array<*>>} disks [name, descriptor, policy]
 * @param {!Array<!Array<*>>=} also [name, descriptor] of disks attached already
 * @return {!Array<!Array<*>>} disks
 */
export function check_disk_bindings(disks, also)
{
    const all = (also || []).map(([name, file]) => [name, file, check_disk_policy(name, file)]).concat(disks);
    const seen = new Map();
    for(const [name, file, policy] of all)
    {
        const source = source_of(/** @type {!Object} */ (file));
        if(source === undefined) continue;
        const other = seen.get(source);
        if(other && (other.policy.disk_option === "read_write" || policy.disk_option === "read_write"))
        {
            throw config_error(other.name + " and " + name + " are the same image, and one of them has disk_option " +
                "\"read_write\": an image written back has one disk");
        }
        if(!other) seen.set(source, { name, policy });
    }
    return disks;
}

/**
 * Put a disk's policy on its buffer (src/block_backend.js reads it there)
 * @param {?} buffer
 * @param {string} name
 * @param {{disk_option: string, disk_error: string}} policy
 */
export function set_disk_policy(buffer, name, policy)
{
    if(!buffer || typeof buffer !== "object") return;
    buffer.disk_name = name;
    buffer.disk_error = policy.disk_error;
    // (a write-back backend: the device reports a write cache, src/ide.js)
    if(policy.disk_option === "read_write") buffer.writeback = true;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/disk_service.js                                                                      0000644 0000000 0000000 00000060241 00000000000 013466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A disk written back to a disk service (docs/disk-persistence-plan.md
// "磁盘协议": a server, or the local disk service on 127.0.0.1; the
// reference implementation is tools/disk-service.mjs): disk_option
// "read_write" with the service's URL. All requests go to the image's URL:
// reads are Range GETs, the rest POSTs with X-V86-Disk-Op (open, renew,
// write, flush, mark, close). The service answers the open with
// X-V86-Disk-Protocol; anything else (a static server) cannot be written
// back, and the start fails saying so.
// - A write completes when the service has it in the image; writes of
//   overlapping ranges go one after the other; a write is retried (with its
//   session, epoch and sequence number: the service applies it once) after
//   network errors and 5xx answers, at most 4 times, each attempt 30 s at
//   most; the block layer's held retry (disk_error "stop") reuses them too.
// - The session's lease is renewed every third of it; a lost lease (another
//   writer took the image over) fails what follows, not to be retried.
// - Reads: a cache of 4 KiB blocks (16 MiB at most, the least recently used
//   go); a write updates the cached blocks before it completes, and a read
//   is cached only if no write to its blocks completed since it began.
// - flush: the service's fdatasync; the timed flush as for local files (1 s
//   after the last write, 5 s at most).
// - Snapshots: prepare_snapshot (flush, mark: the generation recorded),
//   then get_state gives the reference (identity: the URL and the
//   service's UUID of the image; generation; size).
// - In a worker (the CPU Worker), reads and writes to the local disk service
//   on this computer (127.0.0.1, localhost, [::1]) are synchronous
//   XMLHttpRequests: they complete before the device goes on, as a local
//   file's do, which the firmware's polling drivers need (SeaBIOS's AHCI
//   driver waits for each command; an asynchronous answer arrives only after
//   the emulator's batch of instructions). One attempt of 2 s at most: what
//   fails goes the asynchronous way, with its retries (reads can be repeated,
//   a write's sequence number makes the service apply it once).

import { WRITEBACK_STATE, WRITEBACK_STATE_VERSION, FLUSH_IDLE_MS, FLUSH_MAX_MS, disk_error, is_writeback_state } from "./disk_writeback.js";
import { dbg_log } from "./log.js";
import { LOG_DISK } from "./const.js";

const SECTOR_SIZE = 512;
const CACHE_BLOCK = 4096;
const CACHE_BLOCKS = 4096;
const ATTEMPTS = 4;
const ATTEMPT_MS = 30000;
const SYNC_ATTEMPT_MS = 2000;

/**
 * Whether the requests to a disk service may block: in a worker, to this
 * computer (docs/disk-persistence-plan.md, D2's synchronous XHR)
 * @param {string} url
 * @return {boolean}
 */
function sync_requests(url)
{
    if(typeof window !== "undefined" || typeof XMLHttpRequest === "undefined") return false;
    let host;
    try { host = new URL(url).hostname; } catch(e) { return false; }
    return host === "127.0.0.1" || host === "localhost" || host === "[::1]";
}

/**
 * @constructor
 * @param {string} url
 * @param {{name: string, token: (string|undefined), size: (number|undefined)}} options
 */
export function DiskServiceDisk(url, options)
{
    this.url = url;
    this.name = options.name;
    this.token = options.token;
    this.expected_size = options.size;
    /** @type {number} */
    this.byteLength = 0;
    this.writeback = true;
    /** reads and writes as synchronous requests (sync_requests) */
    this.sync = sync_requests(url);
    this.sync_requests = 0;
    this.session = "";
    this.epoch = 0;
    this.lease_ms = 0;
    this.lease_lost = false;
    this.closed = false;
    /** @type {!Object} */
    this.identity = {};
    this.generation_known = "";
    /** the generation prepare_snapshot recorded, until the next write */
    this.marked = null;
    this.sequence = 0;
    /** @type {!WeakMap<!Uint8Array, number>} a failed write's sequence number, for its retry */
    this.retry_sequence = new WeakMap();
    /** @type {!Array<{start: number, end: number, done: !Promise<undefined>}>} writes in flight */
    this.writing = [];
    /** @type {!Map<number, !Uint8Array>} cached blocks, least recently used first */
    this.cache = new Map();
    /** @type {!Map<number, number>} the completion number of the last write to a block */
    this.block_written = new Map();
    this.writes_completed = 0;
    this.dirty_since = 0;
    this.flush_timer = 0;
    this.renew_timer = 0;
    this.flushes = 0;
    this.flush_requests = 0;
    this.writes = 0;
    this.requests = 0;
    this.onload = undefined;
    this.onprogress = undefined;
}

/**
 * The headers of a session's request
 * @param {string} op
 * @return {!Object<string, string>}
 */
DiskServiceDisk.prototype.headers = function(op)
{
    const headers = { "X-V86-Disk-Op": op };
    if(this.session)
    {
        headers["X-V86-Disk-Session"] = this.session;
        headers["X-V86-Disk-Epoch"] = String(this.epoch);
    }
    if(this.token) headers["Authorization"] = "Bearer " + this.token;
    return headers;
};

/**
 * One request, with its timeout; network errors and 5xx answers (but 507)
 * are tried again
 * @param {string} what
 * @param {!Object} init fetch's
 * @param {number=} attempts
 * @return {!Promise<!Response>}
 */
DiskServiceDisk.prototype.request = async function(what, init, attempts = ATTEMPTS)
{
    let last;
    for(let attempt = 0; attempt < attempts; attempt++)
    {
        if(attempt) await new Promise(resolve => setTimeout(resolve, 250 * 2 ** (attempt - 1)));
        const abort = new AbortController();
        const timer = setTimeout(() => abort.abort(), ATTEMPT_MS);
        const signal = init.signal;
        const forward = () => abort.abort();
        signal && signal.addEventListener("abort", forward, { once: true });
        this.requests++;
        try
        {
            const response = await fetch(this.url, { ...init, signal: abort.signal, cache: "no-store" });
            if(response.status >= 500 && response.status !== 507 && attempt + 1 < attempts)
            {
                last = disk_error(this.name + ": the " + what + " got HTTP status " + response.status, "io", true);
                continue;
            }
            return response;
        }
        catch(e)
        {
            if(signal && signal.aborted) throw e;
            last = disk_error(this.name + ": the " + what + " at " + this.url + " failed (" +
                (abort.signal.aborted ? "no answer in " + ATTEMPT_MS / 1000 + " s" : e.message) + ")", "io", true);
        }
        finally
        {
            clearTimeout(timer);
            signal && signal.removeEventListener("abort", forward);
        }
    }
    throw last;
};

/**
 * One synchronous request (this.sync): its answer, or null when it did not
 * get one, or got a 5xx (but 507): then the asynchronous way tries it again
 * @param {string} method
 * @param {!Object<string, string>} headers
 * @param {!Uint8Array=} body
 * @return {?{status: number, header: function(string): ?string, data: !ArrayBuffer}}
 */
DiskServiceDisk.prototype.request_sync = function(method, headers, body)
{
    const xhr = new XMLHttpRequest();
    this.requests++;
    this.sync_requests++;
    try
    {
        xhr.open(method, this.url, false);
        xhr.responseType = "arraybuffer";
        xhr.timeout = SYNC_ATTEMPT_MS;
        for(const name of Object.keys(headers)) xhr.setRequestHeader(name, headers[name]);
        xhr.send(body || null);
    }
    catch(e)
    {
        dbg_log(this.name + ": a synchronous " + method + " failed (" + e.message + "), asynchronously again", LOG_DISK);
        return null;
    }
    if(xhr.status === 0 || xhr.status >= 500 && xhr.status !== 507) return null;
    return { status: xhr.status, header: name => xhr.getResponseHeader(name), data: /** @type {!ArrayBuffer} */ (xhr.response) };
};

/**
 * A refusal of the service as an error (not to be retried)
 * @param {!Response} response
 * @param {string} what
 * @return {!Promise<!Error>}
 */
DiskServiceDisk.prototype.refusal = async function(response, what)
{
    /** @type {?} */
    let body = {};
    try { body = await response.json(); } catch(e) {}
    return this.refusal_of(response.status, body, what);
};

/**
 * @param {number} status
 * @param {?} body the answer's JSON
 * @param {string} what
 * @return {!Error}
 */
DiskServiceDisk.prototype.refusal_of = function(status, body, what)
{
    const code = body["code"] || "";
    if(code === "lease" || code === "epoch") this.lease_lost = true;
    const kind = code === "no_space" ? "no_space" : code === "lease" || code === "epoch" ? "lease" : "io";
    return disk_error(this.name + ": the " + what + " was refused (HTTP " + status + (body["error"] ? ": " + body["error"] : "") + ")" +
        (kind === "lease" ? "; another session writes the image now" : ""), kind, false);
};

DiskServiceDisk.prototype.load = async function()
{
    const keep = " Without disk_option (or with \"read_only\"), the guest's changes stay in memory.";
    let response;
    try
    {
        response = await this.request("open", { method: "POST", headers: this.headers("open") }, 1);
    }
    catch(e)
    {
        throw disk_error(this.name + ": the disk service at " + this.url + " cannot be reached, or does not let this page use it " +
            "(CORS: the service needs this page's origin, tools/disk-service.mjs --origin): " + e.message + "." + keep, "config", false);
    }
    if(!response.headers.get("X-V86-Disk-Protocol"))
    {
        throw disk_error(this.name + "'s URL can only be read, not written back (" + this.url + " is not a disk service: HTTP " +
            response.status + "). To keep the changes, use a disk service that supports writing (tools/disk-service.mjs), " +
            "or omit disk_option to keep the changes in memory.", "config", false);
    }
    if(!response.ok)
    {
        const error = await this.refusal(response, "open");
        /** @type {?} */ (error).kind = "config";
        throw error;
    }
    const answer = await response.json();
    const size = answer["size"];
    if(!Number.isSafeInteger(size) || size % SECTOR_SIZE || answer["sector_size"] !== SECTOR_SIZE)
    {
        await this.close_session();
        throw disk_error(this.name + ": the disk service's image has " + size + " bytes in sectors of " + answer["sector_size"] +
            ": not a whole number of 512-byte sectors", "config", false);
    }
    if(this.expected_size !== undefined && this.expected_size !== size)
    {
        await this.close_session();
        throw disk_error(this.name + ": the disk service's image has " + size + " bytes, the descriptor's size says " + this.expected_size, "config", false);
    }
    this.byteLength = size;
    this.session = answer["session"];
    this.epoch = answer["epoch"];
    this.lease_ms = answer["lease_ms"];
    this.generation_known = String(answer["generation"]);
    this.identity = { "url": this.url, "uuid": answer["identity"]["uuid"] };
    this.schedule_renew();
    this.onload && this.onload(Object.create(null));
};

/** (a start that fails after the open) */
DiskServiceDisk.prototype.close_session = async function()
{
    try { await this.request("close", { method: "POST", headers: this.headers("close") }, 1); } catch(e) {}
};

DiskServiceDisk.prototype.schedule_renew = function()
{
    clearTimeout(this.renew_timer);
    if(this.closed || this.lease_lost) return;
    this.renew_timer = setTimeout(async () =>
    {
        try
        {
            const response = await this.request("renew", { method: "POST", headers: this.headers("renew") });
            if(!response.ok) dbg_log((await this.refusal(response, "lease renewal")).message, LOG_DISK);
        }
        catch(e)
        {
            dbg_log(e.message, LOG_DISK);
        }
        this.schedule_renew();
    }, Math.max(1, this.lease_ms / 3));
    this.renew_timer && this.renew_timer.unref && this.renew_timer.unref();
};

/**
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array|undefined} the cached data, if all of it is
 */
DiskServiceDisk.prototype.get_from_cache = function(start, length)
{
    const first = Math.floor(start / CACHE_BLOCK), last = Math.floor((start + length - 1) / CACHE_BLOCK);
    for(let b = first; b <= last; b++) if(!this.cache.has(b)) return undefined;
    const data = new Uint8Array(length);
    for(let b = first; b <= last; b++)
    {
        const block = /** @type {!Uint8Array} */ (this.cache.get(b));
        // (least recently used first)
        this.cache.delete(b);
        this.cache.set(b, block);
        const from = Math.max(start, b * CACHE_BLOCK), to = Math.min(start + length, (b + 1) * CACHE_BLOCK);
        data.set(block.subarray(from - b * CACHE_BLOCK, to - b * CACHE_BLOCK), from - start);
    }
    return data;
};

/**
 * @param {number} start
 * @param {number} length
 * @param {function((!Uint8Array|undefined), !Error=)} fn
 * @param {{signal: (AbortSignal|undefined)}=} options
 */
DiskServiceDisk.prototype.get = function(start, length, fn, options)
{
    const cached = this.get_from_cache(start, length);
    if(cached)
    {
        fn(cached);
        return;
    }
    if(this.closed || this.lease_lost)
    {
        fn(undefined, disk_error(this.name + ": " + (this.closed ? "the disk is closed" : "the session's lease is lost"), "io", false));
        return;
    }
    // (whole cache blocks, inside the image)
    const from = Math.floor(start / CACHE_BLOCK) * CACHE_BLOCK;
    const to = Math.min(this.byteLength, Math.ceil((start + length) / CACHE_BLOCK) * CACHE_BLOCK);
    const began = this.writes_completed;
    const signal = options && options.signal;
    const headers = this.headers("read");
    delete headers["X-V86-Disk-Op"];
    headers["Range"] = "bytes=" + from + "-" + (to - 1);
    if(this.sync)
    {
        const answer = this.request_sync("GET", headers);
        if(answer)
        {
            let data;
            try { data = this.got(from, to, began, answer.status, answer.header("Content-Range") || "", new Uint8Array(answer.data)); }
            catch(error) { fn(undefined, /** @type {!Error} */ (error)); return; }
            fn(data.subarray(start - from, start - from + length));
            return;
        }
    }
    this.request("read", { method: "GET", headers, signal }).then(async response =>
    {
        const data = this.got(from, to, began, response.status, response.headers.get("Content-Range") || "", new Uint8Array(await response.arrayBuffer()));
        if(signal && signal.aborted) return;
        fn(data.subarray(start - from, start - from + length));
    }).catch(error =>
    {
        if(signal && signal.aborted) return;
        fn(undefined, /** @type {!Error} */ (error));
    });
};

/**
 * A read's answer: checked, and cached unless a write completed since it began
 * @param {number} from
 * @param {number} to
 * @param {number} began writes_completed when the read began
 * @param {number} status
 * @param {string} range the answer's Content-Range
 * @param {!Uint8Array} data
 * @return {!Uint8Array} data
 */
DiskServiceDisk.prototype.got = function(from, to, began, status, range, data)
{
    if(status !== 206 || range !== "bytes " + from + "-" + (to - 1) + "/" + this.byteLength || data.length !== to - from)
    {
        throw disk_error(this.name + ": the read of " + (to - from) + " bytes at " + from + " got HTTP " + status +
            ", Content-Range " + JSON.stringify(range) + ", " + data.length + " bytes", "io", status >= 500 || status === 206);
    }
    for(let b = from / CACHE_BLOCK; b * CACHE_BLOCK < to; b++)
    {
        // (a write that completed since the read began has newer data)
        if((this.block_written.get(b) || 0) > began) continue;
        if((b + 1) * CACHE_BLOCK > to) continue;
        this.cache.delete(b);
        this.cache.set(b, data.slice(b * CACHE_BLOCK - from, (b + 1) * CACHE_BLOCK - from));
        if(this.cache.size > CACHE_BLOCKS) this.cache.delete(this.cache.keys().next().value);
    }
    return data;
};

DiskServiceDisk.prototype.get_and_cache = DiskServiceDisk.prototype.get;

/**
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function(!Error=)} fn
 */
DiskServiceDisk.prototype.set = function(start, data, fn)
{
    if(this.closed || this.lease_lost)
    {
        fn(disk_error(this.name + ": " + (this.closed ? "the disk is closed" : "the session's lease is lost: another session writes the image now"), "lease", false));
        return;
    }
    const end = start + data.length;
    // (a retry has the sequence number of the write it repeats)
    const sequence = this.retry_sequence.get(data) || ++this.sequence;
    const before = this.writing.filter(w => w.start < end && start < w.end).map(w => w.done);
    let finished;
    const entry = { start, end, done: new Promise(resolve => { finished = resolve; }) };
    this.writing.push(entry);
    const complete = error =>
    {
        this.writing.splice(this.writing.indexOf(entry), 1);
        finished();
        if(error)
        {
            if(error["retryable"]) this.retry_sequence.set(data, sequence);
            fn(error);
            return;
        }
        this.retry_sequence.delete(data);
        // (the cache first, then the completion)
        const completion = ++this.writes_completed;
        for(let b = Math.floor(start / CACHE_BLOCK); b * CACHE_BLOCK < end; b++)
        {
            this.block_written.set(b, completion);
            const block = this.cache.get(b);
            if(!block) continue;
            const from = Math.max(start, b * CACHE_BLOCK), to = Math.min(end, (b + 1) * CACHE_BLOCK);
            block.set(data.subarray(from - start, to - start), from - b * CACHE_BLOCK);
        }
        this.marked = null;
        this.writes++;
        this.schedule_flush();
        fn(undefined);
    };
    const headers = this.headers("write");
    headers["X-V86-Disk-Sequence"] = String(sequence);
    headers["X-V86-Disk-Offset"] = String(start);
    headers["Content-Type"] = "application/octet-stream";
    // (synchronous when no write it overlaps is on its way)
    if(this.sync && !before.length)
    {
        const answer = this.request_sync("POST", headers, data);
        if(answer)
        {
            /** @type {?} */
            let body = {};
            try { body = JSON.parse(new TextDecoder().decode(answer.data)); } catch(e) {}
            if(answer.status < 200 || answer.status > 299)
            {
                complete(this.refusal_of(answer.status, body, "write of " + data.length + " bytes at " + start));
                return;
            }
            this.generation_known = String(body["generation"]);
            complete(undefined);
            return;
        }
    }
    Promise.all(before).then(async () =>
    {
        const response = await this.request("write", { method: "POST", headers, body: data });
        if(!response.ok) throw await this.refusal(response, "write of " + data.length + " bytes at " + start);
        this.generation_known = String((await response.json())["generation"]);
    }).then(() => complete(undefined), error => complete(error));
};

DiskServiceDisk.prototype.schedule_flush = function()
{
    const now = Date.now();
    if(!this.dirty_since) this.dirty_since = now;
    clearTimeout(this.flush_timer);
    const wait = Math.max(0, Math.min(FLUSH_IDLE_MS, this.dirty_since + FLUSH_MAX_MS - now));
    this.flush_timer = setTimeout(() =>
    {
        this.flush_timer = 0;
        this.flush(error => { if(error) dbg_log(error.message, LOG_DISK); });
    }, wait);
    this.flush_timer && this.flush_timer.unref && this.flush_timer.unref();
};

/**
 * One of the service's operations without data (flush, mark, close)
 * @param {string} op
 * @param {function(!Error=)} fn
 */
DiskServiceDisk.prototype.operation = function(op, fn)
{
    this.request(op, { method: "POST", headers: this.headers(op) }).then(async response =>
    {
        if(!response.ok) throw await this.refusal(response, op);
        this.generation_known = String((await response.json())["generation"]);
    }).then(() => fn(undefined), error => fn(/** @type {!Error} */ (error)));
};

/**
 * The writes completed before are durable
 * @param {function(!Error=)} fn
 */
DiskServiceDisk.prototype.flush = function(fn)
{
    this.flush_requests++;
    if(this.closed || !this.dirty_since)
    {
        fn(undefined);
        return;
    }
    if(this.lease_lost)
    {
        fn(disk_error(this.name + ": the session's lease is lost", "lease", false));
        return;
    }
    clearTimeout(this.flush_timer);
    this.flush_timer = 0;
    // (writes completed while the flush is on its way are not covered by it)
    const writes = this.writes;
    this.operation("flush", error =>
    {
        if(!error)
        {
            this.flushes++;
            if(this.writes === writes) this.dirty_since = 0;
        }
        fn(error);
    });
};

/**
 * Before a snapshot (the machine stopped, its disk I/O done): flush, and
 * the generation the snapshot records
 * @param {function(!Error=)} fn
 */
DiskServiceDisk.prototype.prepare_snapshot = function(fn)
{
    const writes = this.writes;
    this.operation("mark", error =>
    {
        if(!error)
        {
            this.marked = this.generation_known;
            if(this.writes === writes) this.dirty_since = 0;
        }
        fn(error);
    });
};

/** @return {string} */
DiskServiceDisk.prototype.generation = function()
{
    return this.generation_known;
};

/** (synchronous: what prepare_snapshot recorded) */
DiskServiceDisk.prototype.mark = function()
{
    if(this.marked === null)
    {
        throw new Error(this.name + ": a snapshot of a disk written back to a disk service needs it flushed first (V86.save_state does it)");
    }
    return this.marked;
};

DiskServiceDisk.prototype.get_state = function()
{
    return [WRITEBACK_STATE, WRITEBACK_STATE_VERSION, JSON.stringify(this.identity), this.mark(), this.byteLength];
};

/**
 * @param {*} state
 */
DiskServiceDisk.prototype.check_state = function(state)
{
    const name = this.name;
    if(!is_writeback_state(state))
    {
        throw new Error(state ?
            "The snapshot's disk " + name + " has its changes in memory (disk_option \"read_only\", or an older v86): " +
            "they are not written into " + this.url + ", which this machine writes back" :
            "The snapshot has no disk " + name + ", this machine writes back " + this.url);
    }
    if(state[1] !== WRITEBACK_STATE_VERSION)
    {
        throw new Error("The snapshot's disk " + name + " has a reference of version " + state[1] + ", this v86 reads version " + WRITEBACK_STATE_VERSION);
    }
    if(state[2] !== JSON.stringify(this.identity) || state[3] !== this.generation_known || state[4] !== this.byteLength)
    {
        throw new Error("The snapshot's disk " + name + " is " + state[2] + " in generation " + state[3] + "; this machine's is " +
            JSON.stringify(this.identity) + " in generation " + this.generation_known +
            " (an image written to after the snapshot was saved cannot go back to it)");
    }
};

DiskServiceDisk.prototype.set_state = function(state)
{
    this.check_state(state);
    this.cache.clear();
};

/** (no whole image in memory: export reads the service) */
DiskServiceDisk.prototype.get_buffer = function(fn)
{
    fn(undefined);
};

/**
 * Flush and close the session (destroy(), the drive pulled out)
 * @param {function(!Error=)} fn
 */
DiskServiceDisk.prototype.close = function(fn)
{
    if(this.closed)
    {
        fn(undefined);
        return;
    }
    clearTimeout(this.flush_timer);
    clearTimeout(this.renew_timer);
    Promise.all(this.writing.map(w => w.done)).then(() =>
    {
        this.closed = true;
        if(this.lease_lost) { fn(undefined); return; }
        this.operation("close", fn);
    });
};

/** (a start that failed later: the session is given up) */
DiskServiceDisk.prototype.close_now = function()
{
    if(this.closed) return;
    this.closed = true;
    clearTimeout(this.flush_timer);
    clearTimeout(this.renew_timer);
    if(this.session) this.close_session();
};

/** The page goes away (pagehide): close the session, as far as the browser still sends it */
DiskServiceDisk.prototype.close_keepalive = function()
{
    if(this.closed || this.lease_lost || !this.session) return;
    this.closed = true;
    clearTimeout(this.flush_timer);
    clearTimeout(this.renew_timer);
    try { fetch(this.url, { method: "POST", headers: this.headers("close"), keepalive: true }).catch(() => {}); }
    catch(e) {}
};
                                                                                                                                                                                                                                                                                                                                                               source/v64/src/disk_writeback.js                                                                    0000644 0000000 0000000 00000050234 00000000000 014002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Write-back disks (docs/disk-persistence-plan.md): disk_option "read_write"
// writes the guest's changes into the image itself. This file has what a
// write-back backend needs beyond the buffers of src/buffer.js (the backend
// contract: load, byteLength, get, set, flush, close, mark, generation,
// get_state, set_state, check_state) and the rules for snapshots of disks
// written back:
// - a backend has an identity (the image) and a generation (its version,
//   which every write moves on); a snapshot of the disk is only a reference
//   (identity, generation, size), without data: the data is in the image;
// - saving flushes first and marks the generation; the first write after
//   that moves the generation on before it writes;
// - restoring: a read_write disk takes only a reference of the same
//   identity and generation; a read_only disk takes such a reference too
//   (its changes in memory are then dropped) when it can tell its image's
//   identity and generation (a local file in Node read in ranges, or a
//   disk service's image read in ranges: its ETag); a snapshot with
//   changes in memory never goes into an image written back.
// The reference backend: NodeFileDisk, a local file in Node (the descriptor's
// url), read and written synchronously (fs.readSync, fs.writeSync,
// fs.fdatasyncSync). Completion means the write is in the file (the host's
// page cache: a crash of the browser or process keeps it); durability needs
// a flush, which the guest asks for or the backend does by itself: 1 s
// after the last write, at the latest 5 s after the first one not yet
// flushed, and on stop(), destroy() and when the drive is pulled out.

import { is_disk_image_state } from "./image/disk_image.js";
import { dbg_log } from "./log.js";
import { LOG_DISK } from "./const.js";

/** a snapshot's reference of a disk written back */
export const WRITEBACK_STATE = "v86-writeback";
export const WRITEBACK_STATE_VERSION = 1;

/** the timed flush: after the last write, at the latest after the first */
export const FLUSH_IDLE_MS = 1000;
export const FLUSH_MAX_MS = 5000;

const SECTOR_SIZE = 512;

/** @type {?} node:fs, once loaded (ensure_node_fs) */
let node_fs = null;

/**
 * Load node:fs for the synchronous file operations (Node only)
 * @return {!Promise<?>}
 */
export async function ensure_node_fs()
{
    if(!node_fs)
    {
        /* global require */
    // (Electron renderers with nodeIntegration: require; string concat
        // for closure compiler, as src/lib.js)
        node_fs = typeof require !== "undefined" ? require("fs") : await import("node:" + "fs");
    }
    return node_fs;
}

/**
 * @param {string} message
 * @param {string} kind
 * @param {boolean} retryable
 * @return {!Error}
 */
export function disk_error(message, kind, retryable)
{
    const error = new Error(message);
    /** @type {?} */ (error).kind = kind;
    error["retryable"] = retryable;
    return error;
}

/**
 * Whether a snapshot's state of a disk is a reference of a disk written back
 * @param {*} state
 * @return {boolean}
 */
export function is_writeback_state(state)
{
    return Array.isArray(state) && state[0] === WRITEBACK_STATE;
}

/**
 * The identity and generation of a local file (Node; node:fs loaded): its
 * real path, device and inode; (inode, size, mtime in nanoseconds)
 * @param {string} path
 * @return {{identity: !Object, generation: string, size: number}}
 */
export function node_file_reference(path)
{
    const fs = node_fs;
    const stat = fs["statSync"](path, { "bigint": true });
    return {
        identity: { "path": fs["realpathSync"](path), "dev": String(stat["dev"]), "ino": String(stat["ino"]) },
        generation: String(stat["ino"]) + ":" + String(stat["size"]) + ":" + String(stat["mtimeNs"]),
        size: Number(stat["size"]),
    };
}

/**
 * @param {*} a
 * @param {*} b
 * @return {boolean}
 */
function same_identity(a, b)
{
    return !!a && !!b && JSON.stringify(a) === JSON.stringify(b);
}

/**
 * The reference a disk's buffer can give of its image, if any: a write-back
 * backend's, or a read_only local file's in Node (read in ranges: its
 * changes are in memory, apart from the file)
 * @param {?} buffer
 * @return {?{identity: !Object, generation: string}}
 */
function reference_of(buffer)
{
    if(buffer.writeback) return null;
    if(typeof buffer.filename !== "string" || !(buffer.written_blocks instanceof Map) || buffer.basename) return null;
    if(node_fs)
    {
        try { return node_file_reference(buffer.filename); }
        catch(e) { return null; }
    }
    // (read over HTTP from a disk service: the ETag of its responses,
    // "<the image's UUID>:<generation>", tools/disk-service.mjs)
    const version = buffer.versions instanceof Map ? buffer.versions.get(buffer.filename) : undefined;
    const match = version && version.etag && /^"([0-9a-f-]{36}):(\d+)"$/.exec(version.etag);
    if(!match) return null;
    let url = buffer.filename;
    try { url = new URL(buffer.filename, globalThis.location ? globalThis.location.href : undefined).href; } catch(e) {}
    return { identity: { "url": url, "uuid": match[1] }, generation: match[2] };
}

/**
 * Check a snapshot's state of a disk before anything is restored (the
 * table of docs/disk-persistence-plan.md "快照")
 * @param {string} name
 * @param {?} buffer
 * @param {*} saved the snapshot's state of the buffer
 */
export function check_disk_state(name, buffer, saved)
{
    if(typeof buffer.check_state === "function")
    {
        buffer.check_state(saved);
        return;
    }
    if(is_disk_image_state(saved))
    {
        throw new Error("The snapshot's disk " + name + " is a disk image in a container format, " +
            "this machine's is RAW: its changes cannot be applied to it");
    }
    if(is_writeback_state(saved))
    {
        const reference = reference_of(buffer);
        const identity = JSON.parse(saved[2]);
        if(!reference)
        {
            throw new Error("The snapshot's disk " + name + " was written back (disk_option \"read_write\", " + identity["path"] +
                "); this machine's cannot tell whether its image is that one in that version: give it as a local file read in ranges " +
                "(async: true) or with disk_option \"read_write\"");
        }
        if(!same_identity(identity, reference.identity) || saved[3] !== reference.generation)
        {
            throw new Error("The snapshot's disk " + name + " is " + JSON.stringify(identity) + " in generation " + saved[3] +
                "; this machine's is " + JSON.stringify(reference.identity) + " in generation " + reference.generation);
        }
    }
}

/**
 * Restore a disk's buffer from a snapshot's state (checked before)
 * @param {?} buffer
 * @param {*} saved
 */
export function restore_disk_state(buffer, saved)
{
    if(is_writeback_state(saved) && !buffer.writeback)
    {
        // (a read_only disk of the same image in the same generation: no
        // changes in memory)
        buffer.written_blocks = new Map();
        buffer.write_chunks = [];
        buffer.block_cache && buffer.block_cache.clear();
        return;
    }
    buffer.set_state(saved);
}

/**
 * After the disks loaded: a disk written back and another disk of the
 * machine are not the same file under two names (a symbolic link, a
 * relative path: the descriptors' urls differ, the files' device and inode
 * do not)
 * @param {!Array<!Array<*>>} disks [name, buffer, descriptor]
 * @return {!Promise<undefined>}
 */
export async function check_loaded_disks(disks)
{
    const path_of = (buffer, file) => file && typeof file.url === "string" ? file.url : buffer && typeof buffer.filename === "string" ? buffer.filename : "";
    // (in Node, node:fs for the references of local files: a read_only
    // disk restoring a snapshot of a disk written back, check_disk_state)
    if(typeof process !== "undefined" && process.versions && process.versions.node && typeof XMLHttpRequest === "undefined" &&
        disks.some(([, buffer, file]) => path_of(buffer, file)))
    {
        await ensure_node_fs();
    }
    const written = disks.filter(([, buffer]) => buffer && buffer.writeback && buffer.identity && buffer.identity["ino"]);
    if(!written.length) return;
    for(const [name, buffer, file] of disks)
    {
        if(!buffer || written.some(([, other]) => other === buffer)) continue;
        const path = path_of(buffer, file);
        if(!path) continue;
        let reference;
        try { reference = node_file_reference(path); }
        catch(e) { continue; }
        const same = written.find(([, other]) => other.identity["dev"] === reference.identity["dev"] && other.identity["ino"] === reference.identity["ino"]);
        if(same)
        {
            throw disk_error(same[0] + " and " + name + " are the same file (" + reference.identity["path"] + "), and " + same[0] +
                " has disk_option \"read_write\": an image written back has one disk", "config", false);
        }
    }
}

/** @type {!Set<string>} the local files written back by a machine of this process */
const open_files = new Set();

/**
 * A local file in Node, written back
 * @constructor
 * @param {string} path the descriptor's url
 * @param {{name: string, size: (number|undefined)}} options
 */
export function NodeFileDisk(path, options)
{
    this.path = path;
    this.name = options.name;
    this.expected_size = options.size;
    /** @type {number} */
    this.byteLength = 0;
    /** a backend of the contract (src/block_backend.js, src/ide.js: the write cache) */
    this.writeback = true;
    this.fd = -1;
    this.closed = false;
    /** @type {!Object} */
    this.identity = {};
    /** the generation the last snapshot recorded, until the next write */
    this.marked = null;
    /** writes not flushed yet: since when */
    this.dirty_since = 0;
    this.flush_timer = 0;
    /** the flushes asked for (by the guest, the timer, stop()) and those done (fdatasync) */
    this.flush_requests = 0;
    this.flushes = 0;
    this.writes = 0;
    this.onload = undefined;
    this.onprogress = undefined;
}

NodeFileDisk.prototype.load = async function()
{
    const fs = await ensure_node_fs();
    const fail = message => { throw disk_error(this.name + ": " + message, "config", false); };
    try
    {
        this.fd = fs["openSync"](this.path, "r+");
    }
    catch(e)
    {
        fail("the file " + this.path + " cannot be opened for writing (" + e.message + "); without disk_option " +
            "(or with \"read_only\") the guest's changes stay in memory");
    }
    const reference = node_file_reference(this.path);
    if(reference.size % SECTOR_SIZE)
    {
        this.close_now();
        fail(this.path + " has " + reference.size + " bytes, not a whole number of " + SECTOR_SIZE + "-byte sectors");
    }
    if(this.expected_size !== undefined && this.expected_size !== reference.size)
    {
        this.close_now();
        fail(this.path + " has " + reference.size + " bytes, the descriptor's size says " + this.expected_size);
    }
    const key = reference.identity["dev"] + ":" + reference.identity["ino"];
    if(open_files.has(key))
    {
        this.close_now();
        fail(this.path + " is written back by another disk of this process already: an image written back has one writer");
    }
    open_files.add(key);
    this.key = key;
    this.identity = reference.identity;
    this.byteLength = reference.size;
    this.onload && this.onload(Object.create(null));
};

/**
 * @param {*} e
 * @param {string} what
 * @return {!Error}
 */
NodeFileDisk.prototype.io_error = function(e, what)
{
    // (no space, a read-only file system, a file closed: trying again does not help)
    const code = e && e.code;
    const retryable = !["ENOSPC", "EDQUOT", "EROFS", "EBADF", "EACCES", "EPERM", "EFBIG"].includes(code);
    return disk_error(this.name + ": the " + what + " of " + this.path + " failed (" + (e && e.message || e) + ")", "io", retryable);
};

/**
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array}
 */
NodeFileDisk.prototype.read_now = function(start, length)
{
    if(this.closed) throw disk_error(this.name + ": the disk is closed", "io", false);
    const data = new Uint8Array(length);
    for(let done = 0; done < length;)
    {
        const n = node_fs["readSync"](this.fd, data, done, length - done, start + done);
        if(!n) break;
        done += n;
    }
    return data;
};

/**
 * @param {number} start
 * @param {number} length
 * @param {function((!Uint8Array|undefined), !Error=)} fn
 */
NodeFileDisk.prototype.get = function(start, length, fn)
{
    let data;
    try { data = this.read_now(start, length); }
    catch(e) { fn(undefined, e["retryable"] === undefined ? this.io_error(e, "read") : e); return; }
    fn(data);
};

NodeFileDisk.prototype.get_and_cache = NodeFileDisk.prototype.get;

/**
 * (synchronous anyway)
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array|undefined}
 */
NodeFileDisk.prototype.get_from_cache = function(start, length)
{
    try { return this.read_now(start, length); }
    catch(e) { return undefined; }
};

/**
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function(!Error=)} fn
 */
NodeFileDisk.prototype.set = function(start, data, fn)
{
    if(this.closed)
    {
        fn(disk_error(this.name + ": the disk is closed", "io", false));
        return;
    }
    try
    {
        const marked = this.marked;
        if(marked !== null)
        {
            // the first write after a snapshot: the generation moves on
            // before the data changes
            this.move_generation(marked);
        }
        for(let done = 0; done < data.length;)
        {
            done += node_fs["writeSync"](this.fd, data, done, data.length - done, start + done);
        }
        if(marked !== null)
        {
            // (a file system with coarse timestamps may give the write the
            // marked time again)
            if(this.generation() === marked) this.move_generation(marked);
            this.marked = null;
        }
    }
    catch(e)
    {
        fn(this.io_error(e, "write"));
        return;
    }
    this.writes++;
    this.schedule_flush();
    fn(undefined);
};

/**
 * The file's generation is the snapshot's: give it another
 * @param {?} marked
 */
NodeFileDisk.prototype.move_generation = function(marked)
{
    const fs = node_fs;
    const stat = fs["fstatSync"](this.fd);
    // (seconds as a double, as futimes takes them: 1 ms after the marked
    // time, or now if that is later)
    const next = Number(marked.split(":")[2]) / 1e9 + 0.001;
    fs["futimesSync"](this.fd, stat["atimeMs"] / 1000, Math.max(Date.now() / 1000, next));
};

/** @return {string} the file's generation now */
NodeFileDisk.prototype.generation = function()
{
    const stat = node_fs["fstatSync"](this.fd, { "bigint": true });
    return String(stat["ino"]) + ":" + String(stat["size"]) + ":" + String(stat["mtimeNs"]);
};

/** The timed flush (FLUSH_IDLE_MS after the last write, FLUSH_MAX_MS at most) */
NodeFileDisk.prototype.schedule_flush = function()
{
    const now = Date.now();
    if(!this.dirty_since) this.dirty_since = now;
    clearTimeout(this.flush_timer);
    const wait = Math.max(0, Math.min(FLUSH_IDLE_MS, this.dirty_since + FLUSH_MAX_MS - now));
    this.flush_timer = setTimeout(() =>
    {
        this.flush_timer = 0;
        this.flush(error => { if(error) dbg_log(error.message, LOG_DISK); });
    }, wait);
    // (in Node the timer does not keep the process alive)
    this.flush_timer && this.flush_timer.unref && this.flush_timer.unref();
};

/**
 * The writes completed before are durable
 * @param {function(!Error=)} fn
 */
NodeFileDisk.prototype.flush = function(fn)
{
    this.flush_requests++;
    if(this.closed || !this.dirty_since)
    {
        fn(undefined);
        return;
    }
    clearTimeout(this.flush_timer);
    this.flush_timer = 0;
    try
    {
        node_fs["fdatasyncSync"](this.fd);
    }
    catch(e)
    {
        // (after a failed fsync the kernel may have dropped the data: not retried)
        const error = this.io_error(e, "flush");
        error["retryable"] = false;
        fn(error);
        return;
    }
    this.dirty_since = 0;
    this.flushes++;
    fn(undefined);
};

/**
 * Flush and close (destroy(), the drive pulled out); the disk is not used
 * afterwards
 * @param {function(!Error=)} fn
 */
NodeFileDisk.prototype.close = function(fn)
{
    if(this.closed)
    {
        fn(undefined);
        return;
    }
    this.flush(error =>
    {
        this.close_now();
        fn(error);
    });
};

NodeFileDisk.prototype.close_now = function()
{
    clearTimeout(this.flush_timer);
    this.flush_timer = 0;
    if(this.fd >= 0)
    {
        try { node_fs["closeSync"](this.fd); } catch(e) {}
        this.fd = -1;
    }
    if(this.key) open_files.delete(this.key);
    this.closed = true;
};

/**
 * Flush and record the generation, for a snapshot
 * @return {string}
 */
NodeFileDisk.prototype.mark = function()
{
    let failed;
    this.flush(error => { failed = error; });
    if(failed) throw failed;
    this.marked = this.generation();
    return this.marked;
};

/** (no whole image in memory: export reads the file) */
NodeFileDisk.prototype.get_buffer = function(fn)
{
    fn(undefined);
};

/**
 * A snapshot's reference: identity, generation, size; no data
 * @return {!Array<*>}
 */
NodeFileDisk.prototype.get_state = function()
{
    const generation = this.mark();
    return [WRITEBACK_STATE, WRITEBACK_STATE_VERSION, JSON.stringify(this.identity), generation, this.byteLength];
};

/**
 * @param {*} state
 */
NodeFileDisk.prototype.check_state = function(state)
{
    const name = this.name;
    if(!is_writeback_state(state))
    {
        throw new Error(state ?
            "The snapshot's disk " + name + " has its changes in memory (disk_option \"read_only\", or an older v86): " +
            "they are not written into " + this.path + ", which this machine writes back" :
            "The snapshot has no disk " + name + ", this machine writes back " + this.path);
    }
    if(state[1] !== WRITEBACK_STATE_VERSION)
    {
        throw new Error("The snapshot's disk " + name + " has a reference of version " + state[1] + ", this v86 reads version " + WRITEBACK_STATE_VERSION);
    }
    const identity = JSON.parse(state[2]);
    const generation = this.generation();
    if(!same_identity(identity, this.identity) || state[3] !== generation || state[4] !== this.byteLength)
    {
        throw new Error("The snapshot's disk " + name + " is " + JSON.stringify(identity) + " in generation " + state[3] +
            "; this machine's is " + JSON.stringify(this.identity) + " in generation " + generation +
            " (an image written to after the snapshot was saved cannot go back to it)");
    }
};

NodeFileDisk.prototype.set_state = function(state)
{
    this.check_state(state);
};

/**
 * The disks written back whose backend prepares a snapshot asynchronously
 * (a disk service: flush, then the generation recorded)
 * @param {?} cpu
 * @return {!Array<?>}
 */
export function disks_to_prepare(cpu)
{
    return disk_buffers(cpu).map(([, buffer]) => buffer).filter(buffer => buffer.writeback && typeof buffer.prepare_snapshot === "function");
}

/**
 * [name, buffer] of a machine's disks: its hard disks and CD drives
 * (cpu.disk_devices), its floppy drives' disks; each buffer once
 * @param {?} cpu
 * @return {!Array<!Array<*>>}
 */
export function disk_buffers(cpu)
{
    const seen = new Set(), disks = [];
    const add = (name, buffer) => { if(buffer && !seen.has(buffer)) { seen.add(buffer); disks.push([name, buffer]); } };
    for(const [name, device] of typeof cpu.disk_devices === "function" ? cpu.disk_devices() : []) add(name, device && device.buffer);
    const fdc = cpu.devices && cpu.devices.fdc;
    if(fdc && fdc.drives) fdc.drives.forEach((drive, i) => add(i ? "fdb" : "fda", drive.buffer));
    // (the UEFI firmware's variable store, src/pflash.js; the TPM's state, src/tpm/store.js)
    const pflash = cpu.firmware && cpu.firmware.pflash;
    if(pflash) add("firmware_vars", pflash.buffer);
    if(cpu.devices && cpu.devices.tpm) add("tpm_state", cpu.tpm_store);
    return disks;
}

/**
 * @param {!Array<?>} disks
 * @return {!Promise<undefined>}
 */
export async function prepare_disks(disks)
{
    for(const disk of disks)
    {
        await new Promise((resolve, reject) => disk.prepare_snapshot(error => error ? reject(error) : resolve()));
    }
}
                                                                                                                                                                                                                                                                                                                                                                    source/v64/src/display.js                                                                           0000644 0000000 0000000 00000031155 00000000000 012463  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The boundary between a guest display device and whatever presents its
// output: a canvas, a terminal, nothing (node), or the CPU Worker transport.
// See docs/display-design.md.

// For Types Only
import { BusConnector } from "./bus.js";

/** Text cell flag: the cell blinks. */
export const DISPLAY_FLAG_BLINKING = 0x01;

/** Text cell flag: the glyph comes from font page B rather than A. */
export const DISPLAY_FLAG_FONT_PAGE_B = 0x02;

/**
 * What a display device drives. Every presenter implements all of it, so a
 * device never needs to know which one it is talking to.
 * @interface
 */
export function DisplaySink() {}

/** @param {boolean} graphical */
DisplaySink.prototype.set_mode = function(graphical) {};

/**
 * @param {number} cols
 * @param {number} rows
 */
DisplaySink.prototype.set_size_text = function(cols, rows) {};

/**
 * @param {number} width
 * @param {number} height
 * @param {number} buffer_width
 * @param {number} buffer_height
 */
DisplaySink.prototype.set_size_graphical = function(width, height, buffer_width, buffer_height) {};

/**
 * @param {number} row
 * @param {number} col
 * @param {number} chr
 * @param {number} flags DISPLAY_FLAG_*
 * @param {number} bg_color 0xRRGGBB
 * @param {number} fg_color 0xRRGGBB
 */
DisplaySink.prototype.put_char = function(row, col, chr, flags, bg_color, fg_color) {};

/**
 * @param {number} row
 * @param {number} col
 */
DisplaySink.prototype.update_cursor = function(row, col) {};

/**
 * @param {number} start
 * @param {number} end
 * @param {boolean} enabled
 */
DisplaySink.prototype.update_cursor_scanline = function(start, end, enabled) {};

/**
 * @param {number} height font height, 1..32px
 * @param {boolean} width_9px
 * @param {boolean} width_dbl 16px wide, overrides width_9px
 * @param {boolean} copy_8th_col duplicate the 8th column into the 9th for 0xC0-0xDF
 * @param {Uint8Array} bitmap VGA plane 2, 32 bytes per glyph
 * @param {boolean} bitmap_changed
 */
DisplaySink.prototype.set_font_bitmap = function(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed) {};

/**
 * @param {number} page_a
 * @param {number} page_b
 */
DisplaySink.prototype.set_font_page = function(page_a, page_b) {};

DisplaySink.prototype.clear_screen = function() {};

/**
 * Forget the text geometry and fonts, so that a restored state redraws from
 * scratch even if its dimensions match the current ones.
 */
DisplaySink.prototype.clear_text_state = function() {};

/**
 * Draw rectangles of a pixel buffer. Each layer is
 * { pixels, screen_x, screen_y, buffer_x, buffer_y, buffer_width, buffer_height },
 * where pixels is { data, width, height }: RGBA bytes like ImageData's, but a
 * plain view (possibly of shared memory), since ImageData is a browser type.
 * @param {!Array<!Object>} layers
 */
DisplaySink.prototype.update_buffer = function(layers) {};

DisplaySink.prototype.pause = function() {};

DisplaySink.prototype.continue = function() {};

DisplaySink.prototype.destroy = function() {};

/**
 * @param {number} s_x
 * @param {number} s_y
 */
DisplaySink.prototype.set_scale = function(s_x, s_y) {};

/** @return {!Array<string>} */
DisplaySink.prototype.get_text_screen = function() {};

/**
 * @param {number} y
 * @return {string} "" for rows outside the text screen
 */
DisplaySink.prototype.get_text_row = function(y) {};

/**
 * A guest device that produces a picture.
 * @interface
 */
export function DisplaySource() {}

/**
 * The length of one refresh of the current mode.
 * @return {number} milliseconds
 */
DisplaySource.prototype.vblank_period = function() {};

/** Called at the start of each vertical retrace, in machine time. */
DisplaySource.prototype.on_vblank = function() {};

/** Send the pixels that changed since the last call to the sink. */
DisplaySource.prototype.render = function() {};

/** The next render sends every pixel: the sink lost its copy. */
DisplaySource.prototype.invalidate = function() {};

/**
 * Sits between the display devices and the sink. Devices call it instead of
 * the sink; it keeps the refresh timing on the machine clock (so retrace no
 * longer depends on the host drawing frames) and tells the embedder about
 * screen changes on the bus.
 * @constructor
 * @param {BusConnector} bus
 * @param {DisplaySink} sink
 */
export function DisplayHub(bus, sink)
{
    this.bus = bus;
    this.sink = sink;

    /** @type {DisplaySource} */
    this.source = null;

    /** @type {!Array<function(number):number>} devices' timers */
    this.timers = [];

    /** machine time of the most recent and the next vertical retrace */
    this.last_vblank = 0;
    this.next_vblank = 0;
    this.frame_count = 0;
}

/**
 * Make a device the one whose picture is shown. The first one registered wins
 * until something (a driver taking over a newer device) switches it.
 * @param {DisplaySource} source
 */
DisplayHub.prototype.add_source = function(source)
{
    if(!this.source)
    {
        this.source = source;
    }
};

/**
 * Advance the refresh schedule to `now`, signalling each retrace that passed.
 * A long gap (a paused machine) signals only one: nothing can observe the rest.
 * @param {number} now
 * @return {number} milliseconds until the next retrace
 */
DisplayHub.prototype.timer = function(now)
{
    let next = 100;
    for(const timer of this.timers) next = Math.min(next, timer(now));
    const source = this.source;
    if(!source)
    {
        return next;
    }
    if(now < this.last_vblank)
    {
        // The machine clock went back (restored state)
        this.last_vblank = this.next_vblank = now;
    }
    if(now >= this.next_vblank)
    {
        const period = source.vblank_period();
        const behind = Math.floor((now - this.next_vblank) / period);
        this.last_vblank = this.next_vblank + behind * period;
        this.next_vblank = this.last_vblank + period;
        this.frame_count++;
        source.on_vblank();
    }
    return Math.min(next, this.next_vblank - now);
};

/**
 * A device's timer, run with the display's (each time the machine's timers
 * run): returns milliseconds until it needs to run again
 * @param {function(number):number} timer
 */
DisplayHub.prototype.add_timer = function(timer)
{
    this.timers.push(timer);
};

/**
 * @param {number} now
 * @return {number} milliseconds since the start of the current retrace
 */
DisplayHub.prototype.time_since_vblank = function(now)
{
    this.timer(now);
    return now - this.last_vblank;
};

/**
 * The presenter wants a new picture
 * @param {boolean=} full every pixel, not only those that changed
 */
DisplayHub.prototype.request_frame = function(full)
{
    if(this.source)
    {
        if(full)
        {
            this.source.invalidate();
        }
        this.source.render();
    }
};

/** @param {boolean} graphical */
DisplayHub.prototype.set_mode = function(graphical)
{
    this.sink.set_mode(graphical);
};

/**
 * @param {number} cols
 * @param {number} rows
 */
DisplayHub.prototype.set_size_text = function(cols, rows)
{
    this.sink.set_size_text(cols, rows);
    this.bus.send("screen-set-size", [cols, rows, 0]);
};

/**
 * @param {number} width
 * @param {number} height
 * @param {number} buffer_width
 * @param {number} buffer_height
 * @param {number} bpp
 */
DisplayHub.prototype.set_size_graphical = function(width, height, buffer_width, buffer_height, bpp)
{
    this.sink.set_size_graphical(width, height, buffer_width, buffer_height);
    this.bus.send("screen-set-size", [width, height, bpp]);
};

/**
 * @param {number} row
 * @param {number} col
 * @param {number} chr
 * @param {number} flags
 * @param {number} bg_color
 * @param {number} fg_color
 */
DisplayHub.prototype.put_char = function(row, col, chr, flags, bg_color, fg_color)
{
    this.bus.send("screen-put-char", [row, col, chr]);
    this.sink.put_char(row, col, chr, flags, bg_color, fg_color);
};

/**
 * @param {number} row
 * @param {number} col
 */
DisplayHub.prototype.update_cursor = function(row, col)
{
    this.sink.update_cursor(row, col);
};

/**
 * @param {number} start
 * @param {number} end
 * @param {boolean} enabled
 */
DisplayHub.prototype.update_cursor_scanline = function(start, end, enabled)
{
    this.sink.update_cursor_scanline(start, end, enabled);
};

/**
 * @param {number} height
 * @param {boolean} width_9px
 * @param {boolean} width_dbl
 * @param {boolean} copy_8th_col
 * @param {Uint8Array} bitmap
 * @param {boolean} bitmap_changed
 */
DisplayHub.prototype.set_font_bitmap = function(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed)
{
    this.sink.set_font_bitmap(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed);
};

/**
 * @param {number} page_a
 * @param {number} page_b
 */
DisplayHub.prototype.set_font_page = function(page_a, page_b)
{
    this.sink.set_font_page(page_a, page_b);
};

DisplayHub.prototype.clear_screen = function()
{
    this.sink.clear_screen();
};

DisplayHub.prototype.clear_text_state = function()
{
    this.sink.clear_text_state();
};

/** @param {!Array<!Object>} layers */
DisplayHub.prototype.update_buffer = function(layers)
{
    this.sink.update_buffer(layers);
};

/**
 * Records the device-facing calls so they can cross the CPU Worker boundary,
 * where DISPLAY_SINK_REPLAY applies them to the real presenter. update_buffer
 * is not recorded: pixels travel as frames, which the worker copies itself.
 * @constructor
 * @implements {DisplaySink}
 * @param {function(string, !Array)} record
 * @param {function(!Array<!Object>)} update_buffer
 */
export function DisplaySinkRecorder(record, update_buffer)
{
    this.record = record;
    this.update_buffer = update_buffer;
}

/** @override */
DisplaySinkRecorder.prototype.set_mode = function(graphical)
{
    this.record("set_mode", [graphical]);
};

/** @override */
DisplaySinkRecorder.prototype.set_size_text = function(cols, rows)
{
    this.record("set_size_text", [cols, rows]);
};

/** @override */
DisplaySinkRecorder.prototype.set_size_graphical = function(width, height, buffer_width, buffer_height)
{
    this.record("set_size_graphical", [width, height, buffer_width, buffer_height]);
};

/** @override */
DisplaySinkRecorder.prototype.put_char = function(row, col, chr, flags, bg_color, fg_color)
{
    this.record("put_char", [row, col, chr, flags, bg_color, fg_color]);
};

/** @override */
DisplaySinkRecorder.prototype.update_cursor = function(row, col)
{
    this.record("update_cursor", [row, col]);
};

/** @override */
DisplaySinkRecorder.prototype.update_cursor_scanline = function(start, end, enabled)
{
    this.record("update_cursor_scanline", [start, end, enabled]);
};

/** @override */
DisplaySinkRecorder.prototype.set_font_bitmap = function(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed)
{
    // The bitmap aliases guest-visible memory; snapshot it before the CPU continues
    this.record("set_font_bitmap", [height, width_9px, width_dbl, copy_8th_col, bitmap.slice(), bitmap_changed]);
};

/** @override */
DisplaySinkRecorder.prototype.set_font_page = function(page_a, page_b)
{
    this.record("set_font_page", [page_a, page_b]);
};

/** @override */
DisplaySinkRecorder.prototype.clear_screen = function()
{
    this.record("clear_screen", []);
};

/** @override */
DisplaySinkRecorder.prototype.clear_text_state = function()
{
    this.record("clear_text_state", []);
};

/** @override */
DisplaySinkRecorder.prototype.pause = function() {};

/** @override */
DisplaySinkRecorder.prototype.continue = function() {};

/** @override */
DisplaySinkRecorder.prototype.destroy = function() {};

/** @override */
DisplaySinkRecorder.prototype.set_scale = function(s_x, s_y) {};

/** @override */
DisplaySinkRecorder.prototype.get_text_screen = function()
{
    // The text lives on the presenting side of the worker boundary
    return [];
};

/** @override */
DisplaySinkRecorder.prototype.get_text_row = function(y)
{
    return "";
};

/**
 * Applies calls recorded by DisplaySinkRecorder. Keyed by the quoted names the
 * recorder uses, and each entry calls the method directly, so the table stays
 * correct when Closure renames the methods.
 * @const {!Object<string, function(!DisplaySink, !Array)>}
 */
export const DISPLAY_SINK_REPLAY = {
    "set_mode": (s, a) => s.set_mode(a[0]),
    "set_size_text": (s, a) => s.set_size_text(a[0], a[1]),
    "set_size_graphical": (s, a) => s.set_size_graphical(a[0], a[1], a[2], a[3]),
    "put_char": (s, a) => s.put_char(a[0], a[1], a[2], a[3], a[4], a[5]),
    "update_cursor": (s, a) => s.update_cursor(a[0], a[1]),
    "update_cursor_scanline": (s, a) => s.update_cursor_scanline(a[0], a[1], a[2]),
    "set_font_bitmap": (s, a) => s.set_font_bitmap(a[0], a[1], a[2], a[3], a[4], a[5]),
    "set_font_page": (s, a) => s.set_font_page(a[0], a[1]),
    "clear_screen": (s, a) => s.clear_screen(),
    "clear_text_state": (s, a) => s.clear_text_state(),
};
                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/dma.js                                                                               0000644 0000000 0000000 00000041556 00000000000 011565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { track_state_io } from "./state_io.js";
import { LOG_DMA } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";

/**
 * @constructor
 * @param {CPU} cpu
 */
export function DMA(cpu)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    this.channel_page = new Uint8Array(8);
    this.channel_pagehi = new Uint8Array(8);
    this.channel_addr = new Uint16Array(8);
    this.channel_addr_init = new Uint16Array(8);
    this.channel_count = new Uint16Array(8);
    this.channel_count_init = new Uint16Array(8);
    this.channel_mask = new Uint8Array(8);
    this.channel_mode = new Uint8Array(8);
    this.unmask_listeners = [];

    this.lsb_msb_flipflop = 0;

    /** @type {number} machine resets so far: a transfer completing after one is dropped */
    this.epoch = 0;

    var io = cpu.io;

    io.register_write(0x00, this, this.port_addr_write.bind(this, 0));
    io.register_write(0x02, this, this.port_addr_write.bind(this, 1));
    io.register_write(0x04, this, this.port_addr_write.bind(this, 2));
    io.register_write(0x06, this, this.port_addr_write.bind(this, 3));
    io.register_write(0x01, this, this.port_count_write.bind(this, 0));
    io.register_write(0x03, this, this.port_count_write.bind(this, 1));
    io.register_write(0x05, this, this.port_count_write.bind(this, 2));
    io.register_write(0x07, this, this.port_count_write.bind(this, 3));

    io.register_read(0x00, this, this.port_addr_read.bind(this, 0));
    io.register_read(0x02, this, this.port_addr_read.bind(this, 1));
    io.register_read(0x04, this, this.port_addr_read.bind(this, 2));
    io.register_read(0x06, this, this.port_addr_read.bind(this, 3));
    io.register_read(0x01, this, this.port_count_read.bind(this, 0));
    io.register_read(0x03, this, this.port_count_read.bind(this, 1));
    io.register_read(0x05, this, this.port_count_read.bind(this, 2));
    io.register_read(0x07, this, this.port_count_read.bind(this, 3));

    io.register_write(0xC0, this, this.port_addr_write.bind(this, 4));
    io.register_write(0xC4, this, this.port_addr_write.bind(this, 5));
    io.register_write(0xC8, this, this.port_addr_write.bind(this, 6));
    io.register_write(0xCC, this, this.port_addr_write.bind(this, 7));
    io.register_write(0xC2, this, this.port_count_write.bind(this, 4));
    io.register_write(0xC6, this, this.port_count_write.bind(this, 5));
    io.register_write(0xCA, this, this.port_count_write.bind(this, 6));
    io.register_write(0xCE, this, this.port_count_write.bind(this, 7));

    io.register_read(0xC0, this, this.port_addr_read.bind(this, 4));
    io.register_read(0xC4, this, this.port_addr_read.bind(this, 5));
    io.register_read(0xC8, this, this.port_addr_read.bind(this, 6));
    io.register_read(0xCC, this, this.port_addr_read.bind(this, 7));
    io.register_read(0xC2, this, this.port_count_read.bind(this, 4));
    io.register_read(0xC6, this, this.port_count_read.bind(this, 5));
    io.register_read(0xCA, this, this.port_count_read.bind(this, 6));
    io.register_read(0xCE, this, this.port_count_read.bind(this, 7));

    io.register_write(0x87, this, this.port_page_write.bind(this, 0));
    io.register_write(0x83, this, this.port_page_write.bind(this, 1));
    io.register_write(0x81, this, this.port_page_write.bind(this, 2));
    io.register_write(0x82, this, this.port_page_write.bind(this, 3));
    io.register_write(0x8F, this, this.port_page_write.bind(this, 4));
    io.register_write(0x8B, this, this.port_page_write.bind(this, 5));
    io.register_write(0x89, this, this.port_page_write.bind(this, 6));
    io.register_write(0x8A, this, this.port_page_write.bind(this, 7));

    io.register_read(0x87, this, this.port_page_read.bind(this, 0));
    io.register_read(0x83, this, this.port_page_read.bind(this, 1));
    io.register_read(0x81, this, this.port_page_read.bind(this, 2));
    io.register_read(0x82, this, this.port_page_read.bind(this, 3));
    io.register_read(0x8F, this, this.port_page_read.bind(this, 4));
    io.register_read(0x8B, this, this.port_page_read.bind(this, 5));
    io.register_read(0x89, this, this.port_page_read.bind(this, 6));
    io.register_read(0x8A, this, this.port_page_read.bind(this, 7));

    io.register_write(0x487, this, this.port_pagehi_write.bind(this, 0));
    io.register_write(0x483, this, this.port_pagehi_write.bind(this, 1));
    io.register_write(0x481, this, this.port_pagehi_write.bind(this, 2));
    io.register_write(0x482, this, this.port_pagehi_write.bind(this, 3));
    io.register_write(0x48B, this, this.port_pagehi_write.bind(this, 5));
    io.register_write(0x489, this, this.port_pagehi_write.bind(this, 6));
    io.register_write(0x48A, this, this.port_pagehi_write.bind(this, 7));

    io.register_read(0x487, this, this.port_pagehi_read.bind(this, 0));
    io.register_read(0x483, this, this.port_pagehi_read.bind(this, 1));
    io.register_read(0x481, this, this.port_pagehi_read.bind(this, 2));
    io.register_read(0x482, this, this.port_pagehi_read.bind(this, 3));
    io.register_read(0x48B, this, this.port_pagehi_read.bind(this, 5));
    io.register_read(0x489, this, this.port_pagehi_read.bind(this, 6));
    io.register_read(0x48A, this, this.port_pagehi_read.bind(this, 7));

    io.register_write(0x0A, this, this.port_singlemask_write.bind(this, 0));
    io.register_write(0xD4, this, this.port_singlemask_write.bind(this, 4));
    io.register_write(0x0F, this, this.port_multimask_write.bind(this, 0));
    io.register_write(0xDE, this, this.port_multimask_write.bind(this, 4));

    io.register_read(0x0F, this, this.port_multimask_read.bind(this, 0));
    io.register_read(0xDE, this, this.port_multimask_read.bind(this, 4));

    io.register_write(0x0B, this, this.port_mode_write.bind(this, 0));
    io.register_write(0xD6, this, this.port_mode_write.bind(this, 4));

    io.register_write(0x0C, this, this.portC_write);
    io.register_write(0xD8, this, this.portC_write);
}

DMA.prototype.get_state = function()
{
    return [
        this.channel_page,
        this.channel_pagehi,
        this.channel_addr,
        this.channel_addr_init,
        this.channel_count,
        this.channel_count_init,
        this.channel_mask,
        this.channel_mode,
        this.lsb_msb_flipflop,
    ];
};

DMA.prototype.set_state = function(state)
{
    this.channel_page = state[0];
    this.channel_pagehi = state[1];
    this.channel_addr = state[2];
    this.channel_addr_init = state[3];
    this.channel_count = state[4];
    this.channel_count_init = state[5];
    this.channel_mask = state[6];
    this.channel_mode = state[7];
    this.lsb_msb_flipflop = state[8];
};

DMA.prototype.port_count_write = function(channel, data_byte)
{
    dbg_log("count write [" + channel + "] = " + h(data_byte), LOG_DMA);

    this.channel_count[channel] =
        this.flipflop_get(this.channel_count[channel], data_byte, false);

    this.channel_count_init[channel] =
        this.flipflop_get(this.channel_count_init[channel], data_byte, true);
};

DMA.prototype.port_count_read = function(channel)
{
    dbg_log("count read [" + channel + "] -> " + h(this.channel_count[channel]), LOG_DMA);
    return this.flipflop_read(this.channel_count[channel]);
};

DMA.prototype.port_addr_write = function(channel, data_byte)
{
    dbg_log("addr write [" + channel + "] = " + h(data_byte), LOG_DMA);

    this.channel_addr[channel] =
        this.flipflop_get(this.channel_addr[channel], data_byte, false);

    this.channel_addr_init[channel] =
        this.flipflop_get(this.channel_addr_init[channel], data_byte, true);
};

DMA.prototype.port_addr_read = function(channel)
{
    dbg_log("addr read [" + channel + "] -> " + h(this.channel_addr[channel]), LOG_DMA);
    return this.flipflop_read(this.channel_addr[channel]);
};

DMA.prototype.port_pagehi_write = function(channel, data_byte)
{
    dbg_log("pagehi write [" + channel + "] = " + h(data_byte), LOG_DMA);
    this.channel_pagehi[channel] = data_byte;
};

DMA.prototype.port_pagehi_read = function(channel)
{
    dbg_log("pagehi read [" + channel + "]", LOG_DMA);
    return this.channel_pagehi[channel];
};

DMA.prototype.port_page_write = function(channel, data_byte)
{
    dbg_log("page write [" + channel + "] = " + h(data_byte), LOG_DMA);
    this.channel_page[channel] = data_byte;
};

DMA.prototype.port_page_read = function(channel)
{
    dbg_log("page read [" + channel + "]", LOG_DMA);
    return this.channel_page[channel];
};

DMA.prototype.port_singlemask_write = function(channel_offset, data_byte)
{
    var channel = (data_byte & 0x3) + channel_offset;
    var value = data_byte & 0x4 ? 1 : 0;
    dbg_log("singlechannel mask write [" + channel + "] = " + value, LOG_DMA);
    this.update_mask(channel, value);
};

DMA.prototype.port_multimask_write = function(channel_offset, data_byte)
{
    dbg_log("multichannel mask write: " + h(data_byte), LOG_DMA);
    for(var i = 0; i < 4; i++)
    {
        this.update_mask(channel_offset + i, data_byte & (1 << i));
    }
};

DMA.prototype.port_multimask_read = function(channel_offset)
{
    var value = 0;
    value |= this.channel_mask[channel_offset + 0];
    value |= this.channel_mask[channel_offset + 1] << 1;
    value |= this.channel_mask[channel_offset + 2] << 2;
    value |= this.channel_mask[channel_offset + 3] << 3;
    dbg_log("multichannel mask read: " + h(value), LOG_DMA);
    return value;
};

DMA.prototype.port_mode_write = function(channel_offset, data_byte)
{
    var channel = (data_byte & 0x3) + channel_offset;
    dbg_log("mode write [" + channel + "] = " + h(data_byte), LOG_DMA);
    this.channel_mode[channel] = data_byte;
};

DMA.prototype.portC_write = function(data_byte)
{
    dbg_log("flipflop reset", LOG_DMA);
    this.lsb_msb_flipflop = 0;
};

DMA.prototype.on_unmask = function(fn, this_value)
{
    this.unmask_listeners.push({
        fn: fn,
        this_value: this_value,
    });
};

DMA.prototype.update_mask = function(channel, value)
{
    if(this.channel_mask[channel] !== value)
    {
        this.channel_mask[channel] = value;

        if(!value)
        {
            dbg_log("firing on_unmask(" + channel + ")", LOG_DMA);
            for(var i = 0; i < this.unmask_listeners.length; i++)
            {
                this.unmask_listeners[i].fn.call(
                    this.unmask_listeners[i].this_value,
                    channel
                );
            }
        }
    }
};

// read data, write to memory
DMA.prototype.do_read = function(buffer, start, len, channel, fn)
{
    var read_count = this.count_get_8bit(channel),
        addr = this.address_get_8bit(channel);

    dbg_log("DMA write channel " + channel, LOG_DMA);
    dbg_log("to " + h(addr) + " len " + h(read_count), LOG_DMA);

    if(len < read_count)
    {
        dbg_log("DMA should read more than provided: " + h(len) + " " + h(read_count), LOG_DMA);
    }

    if(start + read_count > buffer.byteLength)
    {
        dbg_log("DMA read outside of buffer", LOG_DMA);
        fn(true);
    }
    else
    {
        var cpu = this.cpu;
        try
        {
            if(addr + read_count > 0x100000000) throw new RangeError("DMA exceeds 32-bit address width");
            cpu.validate_physical_range(addr, read_count);
        }
        catch(error)
        {
            if(!(error instanceof RangeError)) throw error;
            fn(true);
            return;
        }
        this.channel_addr[channel] += read_count;

        const epoch = this.epoch;
        // (the image's read; when it fails, fn gets the error and this, to try
        // it again into the same memory: the registers are already as after
        // the transfer, docs/disk-persistence-plan.md, disk_error "stop")
        const attempt = () =>
        {
            if(epoch !== this.epoch) return;
            track_state_io(cpu, done => buffer.get(start, read_count, done), (data, error) =>
            {
                // (a machine reset in between: the transfer belongs to the machine before it)
                if(epoch !== this.epoch) return;
                // (the image failed the read: docs/disk-persistence-plan.md D3)
                if(error || !data)
                {
                    fn(true, error || new Error("the disk image returned no data"), attempt);
                    return;
                }
                try
                {
                    cpu.write_blob_physical(data, addr);
                }
                catch(error)
                {
                    if(!(error instanceof RangeError)) throw error;
                    fn(true);
                    return;
                }
                fn(false);
            });
        };
        attempt();
    }
};

// write data, read memory
// start and len in bytes
DMA.prototype.do_write = function(buffer, start, len, channel, fn)
{
    var read_count = (this.channel_count[channel] + 1) & 0xFFFF,
        bytes_per_count = channel >= 5 ? 2 : 1,
        read_bytes = read_count * bytes_per_count,
        addr = this.address_get_8bit(channel),
        unfinished = false,
        want_more = false,
        autoinit = this.channel_mode[channel] & 0x10;

    dbg_log("DMA write channel " + channel, LOG_DMA);
    dbg_log("to " + h(addr) + " len " + h(read_bytes), LOG_DMA);

    if(len < read_bytes)
    {
        dbg_log("DMA should read more than provided", LOG_DMA);
        read_count = Math.floor(len / bytes_per_count);
        read_bytes = read_count * bytes_per_count;
        unfinished = true;
    }
    else if(len > read_bytes)
    {
        dbg_log("DMA attempted to read more than provided", LOG_DMA);
        want_more = true;
    }

    if(start + read_bytes > buffer.byteLength)
    {
        dbg_log("DMA write outside of buffer", LOG_DMA);
        fn(true);
    }
    else
    {
        let data;
        try
        {
            if(addr + read_bytes > 0x100000000) throw new RangeError("DMA exceeds 32-bit address width");
            data = this.cpu.read_blob_physical(addr, read_bytes);
        }
        catch(error)
        {
            if(!(error instanceof RangeError)) throw error;
            fn(true);
            return;
        }
        this.channel_addr[channel] += read_count;
        this.channel_count[channel] -= read_count;
        // when complete, counter should underflow to 0xFFFF

        if(!unfinished && autoinit)
        {
            dbg_log("DMA autoinit", LOG_DMA);
            this.channel_addr[channel] = this.channel_addr_init[channel];
            this.channel_count[channel] = this.channel_count_init[channel];
        }

        const epoch = this.epoch;
        // (the image's write; when it fails, fn gets the error and this, to
        // write the same data again; after a reset it still lands, unanswered,
        // as a held write does in src/block_backend.js)
        const attempt = () =>
        {
            track_state_io(this.cpu, done => buffer.set(start, data, done),
                error =>
                {
                    if(epoch !== this.epoch) return;
                    if(error)
                    {
                        fn(true, error, attempt);
                        return;
                    }
                    if(want_more && autoinit)
                    {
                        dbg_log("DMA continuing from start", LOG_DMA);
                        this.do_write(buffer, start + read_bytes, len - read_bytes, channel, fn);
                    }
                    else
                    {
                        fn(false);
                    }
                }
            );
        };
        attempt();
    }
};

/**
 * Machine reset or power-on: transfers still in flight belong to the machine
 * before it and complete without effect (the controller's registers are
 * programmed again by the firmware)
 */
DMA.prototype.cancel_transfers = function()
{
    this.epoch++;
};

DMA.prototype.address_get_8bit = function(channel)
{
    var addr = this.channel_addr[channel];

    // http://wiki.osdev.org/ISA_DMA#16_bit_issues
    // (the 16-bit channels count words: the address register drives A1-A16
    // and the page register A17-A23, its bit 0 unused)
    if(channel >= 5)
    {
        addr = (addr << 1) & 0x1FFFF | (this.channel_page[channel] & 0xFE) << 16;
    }
    else
    {
        addr |= this.channel_page[channel] << 16;
    }

    addr |= this.channel_pagehi[channel] << 24;

    return addr >>> 0;
};

DMA.prototype.count_get_8bit = function(channel)
{
    var count = this.channel_count[channel] + 1;

    if(channel >= 5)
    {
        count *= 2;
    }

    return count;
};

DMA.prototype.flipflop_get = function(old_dword, new_byte, continuing)
{
    if(!continuing)
    {
        this.lsb_msb_flipflop ^= 1;
    }

    if(this.lsb_msb_flipflop)
    {
        // low byte
        return old_dword & ~0xFF | new_byte;
    }
    else
    {
        // high byte
        return old_dword & ~0xFF00 | new_byte << 8;
    }
};

DMA.prototype.flipflop_read = function(dword)
{
    this.lsb_msb_flipflop ^= 1;

    if(this.lsb_msb_flipflop)
    {
        // low byte
        return dword & 0xFF;
    }
    else
    {
        // high byte
        return (dword >> 8) & 0xFF;
    }
};
                                                                                                                                                  source/v64/src/elf.js                                                                               0000644 0000000 0000000 00000014716 00000000000 011570  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_log, LOG_LEVEL } from "./log.js";

// A minimal elf parser for loading 32 bit, x86, little endian, executable elf files

const ELF_MAGIC = 0x464C457F;

const types = DataView.prototype;
const U8 = { size: 1, get: types.getUint8, set: types.setUint8, };
const U16 = { size: 2, get: types.getUint16, set: types.setUint16, };
const U32 = { size: 4, get: types.getUint32, set: types.setUint32, };
const pad = function(size)
{
    return {
        size,
        get: offset => -1,
    };
};

const Header = create_struct([
    { magic: U32, },

    { class: U8, },
    { data: U8, },
    { version0: U8, },
    { osabi: U8, },

    { abiversion: U8, },
    { pad0: pad(7) },

    { type: U16, },
    { machine: U16, },

    { version1: U32, },
    { entry: U32, },
    { phoff: U32, },
    { shoff: U32, },
    { flags: U32, },

    { ehsize: U16, },
    { phentsize: U16, },
    { phnum: U16, },
    { shentsize: U16, },
    { shnum: U16, },
    { shstrndx: U16, },
]);
console.assert(Header.reduce((a, entry) => a + entry.size, 0) === 52);

const ProgramHeader = create_struct([
    { type: U32, },
    { offset: U32, },
    { vaddr: U32, },
    { paddr: U32, },
    { filesz: U32, },
    { memsz: U32, },
    { flags: U32, },
    { align: U32, },
]);
console.assert(ProgramHeader.reduce((a, entry) => a + entry.size, 0) === 32);

const SectionHeader = create_struct([
    { name: U32, },
    { type: U32, },
    { flags: U32, },
    { addr: U32, },
    { offset: U32, },
    { size: U32, },
    { link: U32, },
    { info: U32, },
    { addralign: U32, },
    { entsize: U32, },
]);
console.assert(SectionHeader.reduce((a, entry) => a + entry.size, 0) === 40);


// From [{ name: type }, ...] to [{ name, type, size, get, set }, ...]
function create_struct(struct)
{
    return struct.map(function(entry)
    {
        const keys = Object.keys(entry);
        console.assert(keys.length === 1);
        const name = keys[0];
        const type = entry[name];

        console.assert(type.size > 0);

        return {
            name,
            type,
            size: type.size,
            get: type.get,
            set: type.set,
        };
    });
}

/**
 * Why a direct-boot ELF image cannot be loaded (only 32-bit little-endian
 * i386 executables can), or null.
 * @param {ArrayBuffer} buffer
 */
export function elf_unsupported_reason(buffer)
{
    if(buffer.byteLength < 52) return "truncated header";
    const view = new DataView(buffer);
    if(view.getUint32(0, true) !== ELF_MAGIC) return "bad magic";
    // 1, 2 in EI_CLASS: 32 or 64 bit
    if(view.getUint8(4) === 2) return "64-bit ELF (x86-64 kernels boot from a BIOS disk or ISO, or through a 32-bit multiboot entry)";
    if(view.getUint8(4) !== 1) return "unknown ELF class";
    if(view.getUint8(5) !== 1) return "big endian";
    if(view.getUint8(6) !== 1 || view.getUint32(20, true) !== 1) return "bad version";
    // 1, 2, 3, 4 specify whether the object is relocatable, executable,
    // shared, or core, respectively.
    if(view.getUint16(16, true) !== 2) return "not an executable";
    // EM_386
    if(view.getUint16(18, true) !== 3) return "not an i386 image (machine " + view.getUint16(18, true) + ")";
    if(view.getUint16(40, true) !== 52 || view.getUint16(42, true) !== 32 ||
        view.getUint16(46, true) !== 40 && view.getUint16(48, true) !== 0) return "bad header sizes";
    return null;
}

/** @param {ArrayBuffer} buffer */
export function read_elf(buffer)
{
    const view = new DataView(buffer);

    const [header, offset] = read_struct(view, Header);
    console.assert(offset === 52);

    if(DEBUG)
    {
        for(const key of Object.keys(header))
        {
            dbg_log(key + ": 0x" + (header[key].toString(16) >>> 0));
        }
    }

    const reason = elf_unsupported_reason(buffer);
    if(reason) throw new Error("Unsupported ELF image: " + reason);

    const [program_headers, ph_offset] = read_structs(
        view_slice(view, header.phoff, header.phentsize * header.phnum),
        ProgramHeader,
        header.phnum);

    const [sections_headers, sh_offset] = read_structs(
        view_slice(view, header.shoff, header.shentsize * header.shnum),
        SectionHeader,
        header.shnum);

    if(DEBUG && LOG_LEVEL)
    {
        console.log("%d program headers:", program_headers.length);
        for(const program of program_headers)
        {
            console.log(
                "type=%s offset=%s vaddr=%s paddr=%s " +
                "filesz=%s memsz=%s flags=%s align=%s",
                program.type.toString(16),
                program.offset.toString(16),
                program.vaddr.toString(16),
                program.paddr.toString(16),
                program.filesz.toString(16),
                program.memsz.toString(16),
                program.flags.toString(16),
                program.align.toString(16)
            );
        }

        console.log("%d section headers:", sections_headers.length);
        for(const section of sections_headers)
        {
            console.log(
                "name=%s type=%s flags=%s addr=%s offset=%s " +
                "size=%s link=%s info=%s addralign=%s entsize=%s",
                section.name.toString(16),
                section.type.toString(16),
                section.flags.toString(16),
                section.addr.toString(16),
                section.offset.toString(16),
                section.size.toString(16),
                section.link.toString(16),
                section.info.toString(16),
                section.addralign.toString(16),
                section.entsize.toString(16)
            );
        }
    }

    return {
        header,
        program_headers,
        sections_headers,
    };
}

function read_struct(view, Struct)
{
    const result = {};
    let offset = 0;
    const LITTLE_ENDIAN = true; // big endian not supported yet

    for(const entry of Struct)
    {
        const value = entry.get.call(view, offset, LITTLE_ENDIAN);
        console.assert(result[entry.name] === undefined);
        result[entry.name] = value;
        offset += entry.size;
    }

    return [result, offset];
}

function read_structs(view, Struct, count)
{
    const result = [];
    let offset = 0;

    for(var i = 0; i < count; i++)
    {
        const [s, size] = read_struct(view_slice(view, offset), Struct);
        result.push(s);
        offset += size;
    }

    return [result, offset];
}

/** @param {number=} length */
function view_slice(view, offset, length)
{
    return new DataView(view.buffer, view.byteOffset + offset, length);
}
                                                  source/v64/src/extended_memory.js                                                                   0000644 0000000 0000000 00000007445 00000000000 014213  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The host store of extended RAM (docs/x86-64.md):
// guest RAM beyond the wasm32 backing store, at guest physical 4 GiB plus
// high_memory_size. The CPU caches its pages in frames of the wasm heap
// (src/rust/x64/extended.rs) and copies a page in or out through the
// imports extended_load and extended_store. The pages are kept in buffers of
// at most 1 GiB, shared with vCPU workers (SharedArrayBuffer) where the host
// has them; a bitmap marks pages ever written, so that power-on and
// snapshots skip the rest.

export const EXTENDED_PAGE_SIZE = 4096;
export const EXTENDED_CHUNK_PAGES = 1 << 18;

export class ExtendedStore
{
    /**
     * @param {number} pages
     * @param {Array<!ArrayBuffer|!SharedArrayBuffer>=} chunks the buffers of another store (a vCPU worker's view)
     * @param {(!ArrayBuffer|!SharedArrayBuffer)=} touched its bitmap
     */
    constructor(pages, chunks, touched)
    {
        const shared = typeof SharedArrayBuffer === "function";
        const allocate = bytes => shared ? new SharedArrayBuffer(bytes) : new ArrayBuffer(bytes);
        this.pages = pages;
        this.shared = shared;
        if(!chunks)
        {
            chunks = [];
            for(let first = 0; first < pages; first += EXTENDED_CHUNK_PAGES)
            {
                chunks.push(allocate(Math.min(EXTENDED_CHUNK_PAGES, pages - first) * EXTENDED_PAGE_SIZE));
            }
            touched = allocate(Math.ceil(pages / 8));
        }
        /** @type {!Array<!Uint8Array>} */
        this.chunks = chunks.map(buffer => new Uint8Array(buffer));
        this.touched = new Uint8Array(touched);
    }

    /** The buffers, for a vCPU worker's store */
    transfer()
    {
        return { "pages": this.pages, "chunks": this.chunks.map(chunk => chunk.buffer), "touched": this.touched.buffer };
    }

    /** @param {number} page @return {!Uint8Array} its bytes in the store */
    page(page)
    {
        const offset = (page % EXTENDED_CHUNK_PAGES) * EXTENDED_PAGE_SIZE;
        return this.chunks[Math.floor(page / EXTENDED_CHUNK_PAGES)].subarray(offset, offset + EXTENDED_PAGE_SIZE);
    }

    is_touched(page)
    {
        return (this.touched[page >> 3] >> (page & 7) & 1) !== 0;
    }

    touch(page)
    {
        if(this.is_touched(page)) return;
        if(this.shared) Atomics.or(this.touched, page >> 3, 1 << (page & 7));
        else this.touched[page >> 3] |= 1 << (page & 7);
    }

    /** extended_load: a page into a frame at `pointer` of the wasm memory */
    load(page, memory, pointer)
    {
        // (a wasm i32: the frames may lie above 2 GiB)
        new Uint8Array(memory.buffer, pointer >>> 0, EXTENDED_PAGE_SIZE).set(this.page(page));
    }

    /** extended_store: a frame back into the store */
    store(page, memory, pointer)
    {
        this.touch(page);
        this.page(page).set(new Uint8Array(memory.buffer, pointer >>> 0, EXTENDED_PAGE_SIZE));
    }

    /** Write a page (snapshot restore) */
    write(page, bytes)
    {
        this.touch(page);
        this.page(page).set(bytes);
    }

    /** Power-on: every page reads as zero again (every CPU is stopped) */
    clear()
    {
        for(let byte = 0; byte < this.touched.length; byte++)
        {
            if(!this.touched[byte]) continue;
            for(let bit = 0; bit < 8; bit++)
            {
                if(this.touched[byte] & 1 << bit) this.page(byte * 8 + bit).fill(0);
            }
            this.touched[byte] = 0;
        }
    }

    /** @param {number} page @return {boolean} whether it holds only zeros */
    is_zero(page)
    {
        if(!this.is_touched(page)) return true;
        const bytes = this.page(page);
        const words = new Int32Array(bytes.buffer, bytes.byteOffset, EXTENDED_PAGE_SIZE / 4);
        for(let i = 0; i < words.length; i++) if(words[i]) return false;
        return true;
    }
}
                                                                                                                                                                                                                           source/v64/src/externs.js                                                                           0000644 0000000 0000000 00000001340 00000000000 012477  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       var global = {};
var process = { hrtime: function() {} };

/**
 * The bundle's own URL, defined by the output wrapper of libv86.mjs
 * (import.meta.url, which Closure cannot compile)
 * @type {string|undefined}
 */
var V86_BUNDLE_URL;

/**
 * @param {string} name
 * @param {function()} processor
 */
var registerProcessor = function(name, processor) {};

const sampleRate = 0;

var WabtModule = {
    readWasm: function(buf, opt) {},
    generateNames: function() {},
    applyNames: function() {},
    toText: function() {},
};
var cs = {
    Capstone: function() {},
    ARCH_X86: 0,
    MODE_16: 0,
    MODE_32: 0,
    disasm: { bytes: "", mnemonic: "", op_str: "", },
};

const Buffer = {
    allocUnsafe : function(length) {},
};
                                                                                                                                                                                                                                                                                                source/v64/src/floppy.js                                                                            0000644 0000000 0000000 00000154200 00000000000 012324  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // v86 Floppy Disk Controller emulation
//
// This file is licensed under both BSD and MIT, see LICENSE and LICENSE.MIT.
//
// Links
// - Intel 82078 44 Pin CHMOS Single-Chip Floppy Disk Controller
//   https://wiki.qemu.org/images/f/f0/29047403.pdf
// - qemu: fdc.c
//   https://github.com/qemu/qemu/blob/master/hw/block/fdc.c
// - Programming Floppy Disk Controllers
//   https://www.isdaman.com/alsos/hardware/fdc/floppy.htm
// - OSDev: Floppy Disk Controller
//   https://wiki.osdev.org/Floppy_Disk_Controller

import { LOG_FLOPPY } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";
import { CMOS_FLOPPY_DRIVE_TYPE } from "./rtc.js";
import { SyncBuffer } from "./buffer.js";
import { restore_disk_state } from "./disk_writeback.js";
import { block_failed } from "./block_backend.js";

// For Types Only
import { CPU } from "./cpu.js";
import { DMA } from "./dma.js";
import { IO } from "./io.js";

// System resources
const FDC_IRQ_CHANNEL = 6;
const FDC_DMA_CHANNEL = 2;

/**
 * Floppy drive types
 * CMOS register 0x10 bits: upper nibble: fda, lower nibble: fdb
 * @see {@link https://wiki.osdev.org/CMOS#Register_0x10}
 */
const CMOS_FDD_TYPE_NO_DRIVE = 0x0; // no floppy drive
const CMOS_FDD_TYPE_360      = 0x1; // 360 KB 5"1/4 drive
const CMOS_FDD_TYPE_1200     = 0x2; // 1.2 MB 5"1/4 drive
const CMOS_FDD_TYPE_720      = 0x3; // 720 KB 3"1/2 drive
const CMOS_FDD_TYPE_1440     = 0x4; // 1.44 MB 3"1/2 drive
const CMOS_FDD_TYPE_2880     = 0x5; // 2.88 MB 3"1/2 drive

// Physical floppy disk size identifier of each drive type
const CMOS_FDD_TYPE_MEDIUM = {
    [CMOS_FDD_TYPE_NO_DRIVE]: 0,    // no disk
    [CMOS_FDD_TYPE_360]:      525,  // 5"1/4 disk
    [CMOS_FDD_TYPE_1200]:     525,  // 5"1/4 disk
    [CMOS_FDD_TYPE_720]:      350,  // 3"1/2 disk
    [CMOS_FDD_TYPE_1440]:     350,  // 3"1/2 disk
    [CMOS_FDD_TYPE_2880]:     350,  // 3"1/2 disk
};

// Floppy Controller PIO Register offsets (base: 0x3F0/0x370, offset 0x6 is reserved for ATA IDE)
const REG_SRA       = 0x0;  // R,  Status Register A (SRA)
const REG_SRB       = 0x1;  // R,  Status Register B (SRB)
const REG_DOR       = 0x2;  // RW, Digital Output Register (DOR)
const REG_TDR       = 0x3;  // RW, Tape Drive Register (TDR)
const REG_MSR       = 0x4;  // R,  Main Status Register (MSR)
const REG_DSR       = 0x4;  // W,  Datarate Select Register (DSR)
const REG_FIFO      = 0x5;  // RW, W: command bytes, R: response bytes (FIFO)
const REG_DIR       = 0x7;  // R,  Digital Input Register (DIR)
const REG_CCR       = 0x7;  // W,  Configuration Control Register (CCR)

// Status Register A (SRA) bits
const SRA_NDRV2     = 0x40; // true: second drive is not connected
const SRA_INTPEND   = 0x80; // true: interrupt pending

// Status Register B (SRB) bits
const SRB_MTR0      = 0x1;  // follows DOR.DOR_MOT0
const SRB_MTR1      = 0x2;  // follows DOR.DOR_MOT1
const SRB_DR0       = 0x20; // follows DOR.DOR_SEL_LO
const SRB_RESET     = 0xc0; // magic value after reset

// Digital Output Register (DOR) bits
const DOR_SEL_LO    = 0x1;  // lower bit of selected FDD number
const DOR_SEL_HI    = 0x2;  // upper bit of selected FDD number
const DOR_NRESET    = 0x4;  // true: normal controller mode, false: reset mode ("not RESET")
const DOR_DMAEN     = 0x8;  // true: use DMA
const DOR_MOTEN0    = 0x10; // true: enable motor of FDD0
const DOR_MOTEN1    = 0x20; // true: enable motor of FDD1
const DOR_MOTEN2    = 0x40; // true: enable motor of FDD2
const DOR_MOTEN3    = 0x80; // true: enable motor of FDD3
const DOR_SELMASK   = 0x01;

// Tape Drive Register (TDR) bits
const TDR_BOOTSEL   = 0x4;

// Main Status Register (MSR) bits
const MSR_FDD0      = 0x1;  // true: FDD0 is busy in seek mode
const MSR_FDD1      = 0x2;  // true: FDD1 is busy in seek mode
const MSR_FDD2      = 0x4;  // true: FDD2 is busy in seek mode
const MSR_FDD3      = 0x8;  // true: FDD3 is busy in seek mode
const MSR_CMDBUSY   = 0x10; // true: FDC busy, Read/Write command in progress, cleared at end of Result phase
const MSR_NDMA      = 0x20; // Non-DMA mode, set in Execution phase of PIO mode read/write commands only.
const MSR_DIO       = 0x40; // Data Input/Output, true: FDC has data for CPU, false: FDC expects data from CPU
const MSR_RQM       = 0x80; // true: DATA register is ready for I/O

// Datarate Select Register (DSR) bits
const DSR_DRATEMASK = 0x3;
const DSR_PWRDOWN   = 0x40;
const DSR_SWRESET   = 0x80;

// Digital Input Register (DIR) bits
const DIR_DOOR      = 0x80; // true: No disk or disk changed since last command

// Status Register 0 (SR0) bits
const SR0_DS0       = 0x1;  // Drive select 0..3 lower bit
const SR0_DS1       = 0x2;  // Drive select 0..3 upper bit
const SR0_HEAD      = 0x4;  // true: Use 2nd head
const SR0_EQPMT     = 0x10; // (?)
const SR0_SEEK      = 0x20; // (?)
const SR0_ABNTERM   = 0x40; // true: Command failed
const SR0_INVCMD    = 0x80; // true: Unknown/unimplemented command code
const SR0_RDYCHG    = SR0_ABNTERM | SR0_INVCMD; // 0xC0 (?)

// Status Register 1 (SR1) bits
const SR1_MA        = 0x1;  // true: Missing address mark error
const SR1_NW        = 0x2;  // true: Not writable error
const SR1_EC        = 0x80; // true: End of cylinder error

// Status Register 2 (SR2) bits
const SR2_SNS       = 0x4;  // true: Scan not satisfied (?)
const SR2_SEH       = 0x8;  // true: Scan equal hit (?)

/**
 * FDC command codes
 * We declare all known floppy commands but implement only the subset that
 * we actually observe in the field. See also build_cmd_lookup_table().
 * @see {@link https://github.com/qemu/qemu/blob/6e1571533fd92bec67e5ab9b1dd1e15032925757/hw/block/fdc.c#L619}
 */
const CMD_READ_TRACK             = 0x2; // unimplemented
const CMD_SPECIFY                = 0x3;
const CMD_SENSE_DRIVE_STATUS     = 0x4;
const CMD_WRITE                  = 0x5;
const CMD_READ                   = 0x6;
const CMD_RECALIBRATE            = 0x7;
const CMD_SENSE_INTERRUPT_STATUS = 0x8;
const CMD_WRITE_DELETED_DATA     = 0x9; // unimplemented
const CMD_READ_ID                = 0xa;
const CMD_READ_DELETED_DATA      = 0xc; // unimplemented
const CMD_FORMAT_TRACK           = 0xd;
const CMD_DUMP_REGS              = 0xe;
const CMD_SEEK                   = 0xf;
const CMD_VERSION                = 0x10;
const CMD_SCAN_EQUAL             = 0x11; // unimplemented
const CMD_PERPENDICULAR_MODE     = 0x12;
const CMD_CONFIGURE              = 0x13;
const CMD_LOCK                   = 0x14;
const CMD_VERIFY                 = 0x16; // unimplemented
const CMD_POWERDOWN_MODE         = 0x17; // unimplemented
const CMD_PART_ID                = 0x18;
const CMD_SCAN_LOW_OR_EQUAL      = 0x19; // unimplemented
const CMD_SCAN_HIGH_OR_EQUAL     = 0x1d; // unimplemented
const CMD_SAVE                   = 0x2e; // unimplemented
const CMD_OPTION                 = 0x33; // unimplemented
const CMD_RESTORE                = 0x4e; // unimplemented
const CMD_DRIVE_SPECIFICATION    = 0x8e; // unimplemented
const CMD_RELATIVE_SEEK_OUT      = 0x8f; // unimplemented
const CMD_FORMAT_AND_WRITE       = 0xcd; // unimplemented
const CMD_RELATIVE_SEEK_IN       = 0xcf; // unimplemented

// FDC command flags
const CMD_FLAG_MULTI_TRACK  = 0x1;  // MT: multi-track selector (use both heads) in READ/WRITE

// FDC command execution phases
const CMD_PHASE_COMMAND     = 1;
const CMD_PHASE_EXECUTION   = 2;
const CMD_PHASE_RESULT      = 3;

// FDC config bits
const CONFIG_PRETRK     = 0xff; // Pre-compensation set to track 0
const CONFIG_FIFOTHR    = 0x0f; // FIFO threshold set to 1 byte
const CONFIG_POLL       = 0x10; // Poll enabled
const CONFIG_EFIFO      = 0x20; // FIFO disabled
const CONFIG_EIS        = 0x40; // No implied seeks

// Number of CMD_SENSE_INTERRUPT_STATUS expected after reset
const RESET_SENSE_INT_MAX = 4;

// Sector size
const SECTOR_SIZE       = 512;  // fixed size of 512 bytes/sector
const SECTOR_SIZE_CODE  = 2;    // sector size code 2: 512 bytes/sector

// class FloppyController ----------------------------------------------------

/**
 * @constructor
 *
 * @param {CPU} cpu
 * @param {SyncBuffer|Uint8Array|null|undefined} fda_image
 * @param {SyncBuffer|Uint8Array|null|undefined} fdb_image
 * @param {Object=} fdc_config
 *
 * Structure and defaults of optional configuration object fdc_config:
 *
 *   fdc_config = {
 *       fda: { drive_type: undefined, read_only: false },
 *       fdb: { drive_type: undefined, read_only: false }
 *   }
 *
 * drive_type:
 *     Fixed drive type code whether or not a buffer is defined:
 *       0: no floppy drive
 *       1: 360 KB 5"1/4 drive
 *       2: 1.2 MB 5"1/4 drive
 *       3: 720 KB 3"1/2 drive
 *       4: 1.44 MB 3"1/2 drive (default)
 *       5: 2.88 MB 3"1/2 drive
 *     If undefined, the drive type is either derived from the given
 *     buffer or set to the default of 4 if no buffer is specified.
 * read_only:
 *     If true, treat the given disk image as write-protected.
 *     Ignored if no disk image is provided. Default: false.
 *
 * NOTE: To hide fdb from the guest set its drive_type to 0, i.e.:
 *
 *   fdc_config = { fdb: { drive_type: 0 } }
 */
export function FloppyController(cpu, fda_image, fdb_image, fdc_config)
{
    /** @const @type {IO|undefined} */
    this.io = cpu.io;

    /** @const @type {CPU} */
    this.cpu = cpu;

    /** @const @type {DMA} */
    this.dma = cpu.devices.dma;

    /** @const */
    this.cmd_table = this.build_cmd_lookup_table();

    this.sra = 0;
    this.srb = SRB_RESET;
    this.dor = DOR_NRESET | DOR_DMAEN;
    this.tdr = 0;
    this.msr = MSR_RQM;
    this.dsr = 0;

    this.cmd_phase = CMD_PHASE_COMMAND;
    this.cmd_code = 0;
    this.cmd_flags = 0;
    this.cmd_buffer = new Uint8Array(17);    // CMD_RESTORE has 17 argument bytes
    this.cmd_cursor = 0;
    this.cmd_remaining = 0;

    this.response_data = new Uint8Array(15); // CMD_SAVE response size is 15 bytes
    this.response_cursor = 0;
    this.response_length = 0;
    this.status0 = 0;
    this.status1 = 0;

    this.curr_drive_no = 0;         // was: this.drive; qemu: fdctrl->cur_drv
    this.reset_sense_int_count = 0; // see SENSE INTERRUPT
    this.locked = false;            // see LOCK
    this.step_rate_interval = 0;    // see SPECIFY, qemu: timer0
    this.head_load_time = 0;        // see SPECIFY, qemu: timer1
    this.fdc_config = CONFIG_EIS | CONFIG_EFIFO;    // see CONFIGURE, qemu: config
    this.precomp_trk = 0;           // see CONFIGURE
    this.eot = 0;                   // see READ/WRITE

    this.drives = [
        new FloppyDrive("fda", fdc_config?.fda, fda_image, CMOS_FDD_TYPE_1440),
        new FloppyDrive("fdb", fdc_config?.fdb, fdb_image, CMOS_FDD_TYPE_1440)
    ];

    Object.seal(this);

    // To make the floppy drives visible to the guest OS we MUST write a
    // drive type other than 0 (CMOS_FDD_TYPE_NO_DRIVE) to either nibble of
    // CMOS register 0x10 before the guest is started (CMOS registers are
    // usually read only once at startup).
    this.cpu.devices.rtc.cmos_write(CMOS_FLOPPY_DRIVE_TYPE, (this.drives[0].drive_type << 4) | this.drives[1].drive_type);

    const fdc_io_base = 0x3F0;  // alt: 0x370

    this.io.register_read(fdc_io_base | REG_SRA, this, this.read_reg_sra);
    this.io.register_read(fdc_io_base | REG_SRB, this, this.read_reg_srb);
    this.io.register_read(fdc_io_base | REG_DOR, this, this.read_reg_dor);
    this.io.register_read(fdc_io_base | REG_TDR, this, this.read_reg_tdr);
    this.io.register_read(fdc_io_base | REG_MSR, this, this.read_reg_msr);
    this.io.register_read(fdc_io_base | REG_FIFO, this, this.read_reg_fifo);
    this.io.register_read(fdc_io_base | REG_DIR, this, this.read_reg_dir);

    this.io.register_write(fdc_io_base | REG_DOR, this, this.write_reg_dor);
    this.io.register_write(fdc_io_base | REG_TDR, this, this.write_reg_tdr);
    this.io.register_write(fdc_io_base | REG_DSR, this, this.write_reg_dsr);
    this.io.register_write(fdc_io_base | REG_FIFO, this, this.write_reg_fifo);
    this.io.register_write(fdc_io_base | REG_CCR, this, this.write_reg_ccr);

    dbg_log("floppy controller ready", LOG_FLOPPY);
}

FloppyController.prototype.build_cmd_lookup_table = function()
{
    /**
     * NOTE: The order of items in the table below is significant.
     * @see {@link https://github.com/qemu/qemu/blob/aec6836c73403cffa56b9a4c5556451ee16071fe/hw/block/fdc.c#L2160}
     */
    const CMD_DESCRIPTOR = [
        { code: CMD_READ, mask: 0x1f, argc: 8, name: "READ", handler: this.exec_read },
        { code: CMD_WRITE, mask: 0x3f, argc: 8, name: "WRITE", handler: this.exec_write },
        { code: CMD_SEEK, mask: 0xff, argc: 2, name: "SEEK", handler: this.exec_seek },
        { code: CMD_SENSE_INTERRUPT_STATUS, mask: 0xff, argc: 0, name: "SENSE INTERRUPT STATUS", handler: this.exec_sense_interrupt_status },
        { code: CMD_RECALIBRATE, mask: 0xff, argc: 1, name: "RECALIBRATE", handler: this.exec_recalibrate },
        { code: CMD_FORMAT_TRACK, mask: 0xbf, argc: 5, name: "FORMAT TRACK", handler: this.exec_format_track },
        { code: CMD_READ_TRACK, mask: 0xbf, argc: 8, name: "READ TRACK", handler: this.exec_unimplemented },
        { code: CMD_RESTORE, mask: 0xff, argc: 17, name: "RESTORE", handler: this.exec_unimplemented },
        { code: CMD_SAVE, mask: 0xff, argc: 0, name: "SAVE", handler: this.exec_unimplemented },
        { code: CMD_READ_DELETED_DATA, mask: 0x1f, argc: 8, name: "READ DELETED DATA", handler: this.exec_unimplemented },
        { code: CMD_SCAN_EQUAL, mask: 0x1f, argc: 8, name: "SCAN EQUAL", handler: this.exec_unimplemented },
        { code: CMD_VERIFY, mask: 0x1f, argc: 8, name: "VERIFY", handler: this.exec_unimplemented },
        { code: CMD_SCAN_LOW_OR_EQUAL, mask: 0x1f, argc: 8, name: "SCAN LOW OR EQUAL", handler: this.exec_unimplemented },
        { code: CMD_SCAN_HIGH_OR_EQUAL, mask: 0x1f, argc: 8, name: "SCAN HIGH OR EQUAL", handler: this.exec_unimplemented },
        { code: CMD_WRITE_DELETED_DATA, mask: 0x3f, argc: 8, name: "WRITE DELETED DATA", handler: this.exec_unimplemented },
        { code: CMD_READ_ID, mask: 0xbf, argc: 1, name: "READ ID", handler: this.exec_read_id },
        { code: CMD_SPECIFY, mask: 0xff, argc: 2, name: "SPECIFY", handler: this.exec_specify },
        { code: CMD_SENSE_DRIVE_STATUS, mask: 0xff, argc: 1, name: "SENSE DRIVE STATUS", handler: this.exec_sense_drive_status },
        { code: CMD_PERPENDICULAR_MODE, mask: 0xff, argc: 1, name: "PERPENDICULAR MODE", handler: this.exec_perpendicular_mode },
        { code: CMD_CONFIGURE, mask: 0xff, argc: 3, name: "CONFIGURE", handler: this.exec_configure },
        { code: CMD_POWERDOWN_MODE, mask: 0xff, argc: 2, name: "POWERDOWN MODE", handler: this.exec_unimplemented },
        { code: CMD_OPTION, mask: 0xff, argc: 1, name: "OPTION", handler: this.exec_unimplemented },
        { code: CMD_DRIVE_SPECIFICATION, mask: 0xff, argc: 5, name: "DRIVE SPECIFICATION", handler: this.exec_unimplemented },
        { code: CMD_RELATIVE_SEEK_OUT, mask: 0xff, argc: 2, name: "RELATIVE SEEK OUT", handler: this.exec_unimplemented },
        { code: CMD_FORMAT_AND_WRITE, mask: 0xff, argc: 10, name: "FORMAT AND WRITE", handler: this.exec_unimplemented },
        { code: CMD_RELATIVE_SEEK_IN, mask: 0xff, argc: 2, name: "RELATIVE SEEK IN", handler: this.exec_unimplemented },
        { code: CMD_LOCK, mask: 0x7f, argc: 0, name: "LOCK", handler: this.exec_lock },
        { code: CMD_DUMP_REGS, mask: 0xff, argc: 0, name: "DUMP REGISTERS", handler: this.exec_dump_regs },
        { code: CMD_VERSION, mask: 0xff, argc: 0, name: "VERSION", handler: this.exec_version },
        { code: CMD_PART_ID, mask: 0xff, argc: 0, name: "PART ID", handler: this.exec_part_id },

        { code: 0, mask: 0x00, argc: 0, name: "UNKNOWN COMMAND", handler: this.exec_unimplemented },    // default handler
    ];

    const cmd_table = new Array(256);
    for(let i = CMD_DESCRIPTOR.length-1; i >= 0; i--)
    {
        const cmd_desc = CMD_DESCRIPTOR[i];
        if(cmd_desc.mask === 0xff)
        {
            cmd_table[cmd_desc.code] = cmd_desc;
        }
        else
        {
            for(let j = 0; j < 256; j++)
            {
                if((j & cmd_desc.mask) === cmd_desc.code)
                {
                    cmd_table[j] = cmd_desc;
                }
            }
        }
    }
    return cmd_table;
};

FloppyController.prototype.raise_irq = function(reason)
{
    if(!(this.sra & SRA_INTPEND))
    {
        this.cpu.device_raise_irq(FDC_IRQ_CHANNEL);
        this.sra |= SRA_INTPEND;
        dbg_log("IRQ raised, reason: " + reason, LOG_FLOPPY);
    }
    this.reset_sense_int_count = 0;
};

FloppyController.prototype.lower_irq = function(reason)
{
    this.status0 = 0;
    if(this.sra & SRA_INTPEND)
    {
        this.cpu.device_lower_irq(FDC_IRQ_CHANNEL);
        this.sra &= ~SRA_INTPEND;
        dbg_log("IRQ lowered, reason: " + reason, LOG_FLOPPY);
    }
};

FloppyController.prototype.set_curr_drive_no = function(curr_drive_no)
{
    this.curr_drive_no = curr_drive_no & 1;
    return this.drives[this.curr_drive_no];
};

FloppyController.prototype.enter_command_phase = function()
{
    this.cmd_phase = CMD_PHASE_COMMAND;
    this.cmd_cursor = 0;
    this.cmd_remaining = 0;
    this.msr &= ~(MSR_CMDBUSY | MSR_DIO);
    this.msr |= MSR_RQM;
};

FloppyController.prototype.enter_result_phase = function(fifo_len)
{
    this.cmd_phase = CMD_PHASE_RESULT;
    this.response_cursor = 0;
    this.response_length = fifo_len;
    this.msr |= MSR_CMDBUSY | MSR_RQM | MSR_DIO;
};

FloppyController.prototype.reset_fdc = function()
{
    dbg_log("resetting controller", LOG_FLOPPY);
    this.lower_irq("controller reset");

    this.sra = 0;   // NOTE: set SRA to SRA_NDRV2 if fdb does not exist
    this.srb = SRB_RESET;
    this.dor = DOR_NRESET | DOR_DMAEN;
    this.msr = MSR_RQM;
    this.curr_drive_no = 0;
    this.status0 |= SR0_RDYCHG;

    this.response_cursor = 0;
    this.response_length = 0;

    this.drives[0].seek(0, 0, 1);
    this.drives[1].seek(0, 0, 1);

    // raise interrupt
    this.enter_command_phase();
    this.raise_irq("controller reset");
    this.reset_sense_int_count = RESET_SENSE_INT_MAX;
};

// Register I/O callbacks ----------------------------------------------------

FloppyController.prototype.read_reg_sra = function()
{
    dbg_log("SRA read: " + h(this.sra), LOG_FLOPPY);
    return this.sra;
};

FloppyController.prototype.read_reg_srb = function()
{
    dbg_log("SRB read: " + h(this.srb), LOG_FLOPPY);
    return this.srb;
};

FloppyController.prototype.read_reg_dor = function()
{
    const dor_byte = (this.dor & ~(DOR_SEL_LO|DOR_SEL_HI)) | this.curr_drive_no;
    dbg_log("DOR read: " + h(dor_byte), LOG_FLOPPY);
    return dor_byte;
};

FloppyController.prototype.read_reg_tdr = function()
{
    dbg_log("TDR read: " + h(this.tdr), LOG_FLOPPY);
    return this.tdr;
};

FloppyController.prototype.read_reg_msr = function()
{
    dbg_log("MSR read: " + h(this.msr), LOG_FLOPPY);
    this.dsr &= ~DSR_PWRDOWN;
    this.dor |= DOR_NRESET;
    return this.msr;
};

FloppyController.prototype.read_reg_fifo = function()
{
    this.dsr &= ~DSR_PWRDOWN;
    if(!(this.msr & MSR_RQM) || !(this.msr & MSR_DIO))
    {
        dbg_log("FIFO read rejected: controller not ready for reading", LOG_FLOPPY);
        return 0;
    }
    else if(this.cmd_phase !== CMD_PHASE_RESULT)
    {
        dbg_log("FIFO read rejected: floppy controller not in RESULT phase, phase: " + this.cmd_phase, LOG_FLOPPY);
        return 0;
    }

    if(this.response_cursor < this.response_length)
    {
        const fifo_byte = this.response_data[this.response_cursor++];
        if(this.response_cursor === this.response_length)
        {
            const lower_irq_reason = DEBUG ? "end of " + this.cmd_table[this.cmd_code].name + " response" : "";
            this.msr &= ~MSR_RQM;
            this.enter_command_phase();
            this.lower_irq(lower_irq_reason);
        }
        return fifo_byte;
    }
    else
    {
        dbg_log("FIFO read: empty", LOG_FLOPPY);
        return 0;
    }
};

FloppyController.prototype.read_reg_dir = function()
{
    const curr_drive = this.drives[this.curr_drive_no];
    const dir_byte = curr_drive.media_changed ? DIR_DOOR : 0;
    dbg_log("DIR read: " + h(dir_byte), LOG_FLOPPY);
    return dir_byte;
};

FloppyController.prototype.write_reg_dor = function(dor_byte)
{
    // update motor and drive bits in Status Register B
    this.srb = (this.srb & ~(SRB_MTR0 | SRB_MTR1 | SRB_DR0)) |
        (dor_byte & DOR_MOTEN0 ? SRB_MTR0 : 0) |
        (dor_byte & DOR_MOTEN1 ? SRB_MTR1 : 0) |
        (dor_byte & DOR_SEL_LO ? SRB_DR0 : 0);

    // RESET-state transitions
    if(this.dor & DOR_NRESET)
    {
        if(!(dor_byte & DOR_NRESET))
        {
            dbg_log("enter RESET state", LOG_FLOPPY);
        }
    }
    else
    {
        if(dor_byte & DOR_NRESET)
        {
            this.reset_fdc();
            this.dsr &= ~DSR_PWRDOWN;
            dbg_log("exit RESET state", LOG_FLOPPY);
        }
    }

    // select current drive
    const new_drive_no = dor_byte & (DOR_SEL_LO|DOR_SEL_HI);
    dbg_log("DOR write: " + h(dor_byte) + ", motors: " + h(dor_byte >> 4) +
        ", dma: " + !!(dor_byte & DOR_DMAEN) + ", reset: " + !(dor_byte & DOR_NRESET) +
        ", drive: " + new_drive_no, LOG_FLOPPY);
    if(new_drive_no > 1)
    {
        dbg_log("*** WARNING: floppy drive number " + new_drive_no + " not implemented!", LOG_FLOPPY);
    }
    this.curr_drive_no = new_drive_no & DOR_SEL_LO;

    this.dor = dor_byte;
};

FloppyController.prototype.write_reg_tdr = function(tdr_byte)
{
    if(!(this.dor & DOR_NRESET))
    {
        dbg_log("TDR write " + h(tdr_byte) + " rejected: Floppy controller in RESET mode!", LOG_FLOPPY);
        return;
    }

    dbg_log("TDR write: " + h(tdr_byte), LOG_FLOPPY);
    this.tdr = tdr_byte & TDR_BOOTSEL;  // Disk boot selection indicator
};

FloppyController.prototype.write_reg_dsr = function(dsr_byte)
{
    if(!(this.dor & DOR_NRESET))
    {
        dbg_log("DSR write: " + h(dsr_byte) + " rejected: Floppy controller in RESET mode!", LOG_FLOPPY);
        return;
    }

    dbg_log("DSR write: " + h(dsr_byte), LOG_FLOPPY);
    if(dsr_byte & DSR_SWRESET)
    {
        this.dor &= ~DOR_NRESET;
        this.reset_fdc();
        this.dor |= DOR_NRESET;
    }
    if(dsr_byte & DSR_PWRDOWN)
    {
        this.reset_fdc();
    }
    this.dsr = dsr_byte;
};

FloppyController.prototype.write_reg_fifo = function(fifo_byte)
{
    this.dsr &= ~DSR_PWRDOWN;
    if(!(this.dor & DOR_NRESET))
    {
        dbg_log("FIFO write " + h(fifo_byte) + " rejected: floppy controller in RESET mode!", LOG_FLOPPY);
        return;
    }
    else if(!(this.msr & MSR_RQM) || (this.msr & MSR_DIO))
    {
        dbg_log("FIFO write " + h(fifo_byte) + " rejected: controller not ready for writing", LOG_FLOPPY);
        return;
    }
    else if(this.cmd_phase !== CMD_PHASE_COMMAND)
    {
        dbg_log("FIFO write " + h(fifo_byte) + " rejected: floppy controller not in COMMAND phase, phase: " + this.cmd_phase, LOG_FLOPPY);
        return;
    }

    if(this.cmd_remaining === 0)
    {
        // start reading command, fifo_byte contains the command code
        const cmd_desc = this.cmd_table[fifo_byte];
        this.cmd_code = fifo_byte;
        this.cmd_remaining = cmd_desc.argc;
        this.cmd_cursor = 0;
        this.cmd_flags = 0;
        if((cmd_desc.code === CMD_READ || cmd_desc.code === CMD_WRITE) && (this.cmd_code & 0x80)) // 0x80: Multi-track (MT)
        {
            this.cmd_flags |= CMD_FLAG_MULTI_TRACK;
        }
        if(this.cmd_remaining)
        {
            this.msr |= MSR_RQM;
        }
        this.msr |= MSR_CMDBUSY;
    }
    else
    {
        // continue reading command, fifo_byte contains an argument value
        this.cmd_buffer[this.cmd_cursor++] = fifo_byte;
        this.cmd_remaining--;
    }

    if(this.cmd_remaining === 0)
    {
        // done reading command: execute
        this.cmd_phase = CMD_PHASE_EXECUTION;
        const cmd_desc = this.cmd_table[this.cmd_code];
        const args = this.cmd_buffer.slice(0, this.cmd_cursor);
        if(DEBUG)
        {
            const args_hex = [];
            for(const arg of args)
            {
                args_hex.push(h(arg, 2));
            }
            dbg_log("FD command " + h(this.cmd_code) + ": " + cmd_desc.name + "(" + args_hex.join(", ") + ")", LOG_FLOPPY);
        }
        cmd_desc.handler.call(this, args);
    }
};

FloppyController.prototype.write_reg_ccr = function(ccr_byte)
{
    if(!(this.dor & DOR_NRESET))
    {
        dbg_log("CCR write: " + h(ccr_byte) + " rejected: Floppy controller in RESET mode!", LOG_FLOPPY);
        return;
    }

    dbg_log("CCR write: " + h(ccr_byte), LOG_FLOPPY);
    // only the rate selection bits used in AT mode, and we store those in the DSR
    this.dsr = (this.dsr & ~DSR_DRATEMASK) | (ccr_byte & DSR_DRATEMASK);
};

// Floppy command handler ----------------------------------------------------

FloppyController.prototype.exec_unimplemented = function(args)
{
    dbg_assert(false, "Unimplemented floppy command code " + h(this.cmd_code) + "!");
    this.status0 = SR0_INVCMD;
    this.response_data[0] = this.status0;

    // no interrupt
    this.enter_result_phase(1);
};

FloppyController.prototype.exec_read = function(args)
{
    this.start_read_write(args, false);
};

FloppyController.prototype.exec_write = function(args)
{
    this.start_read_write(args, true);
};

FloppyController.prototype.exec_seek = function(args)
{
    const curr_drive = this.set_curr_drive_no(args[0] & DOR_SELMASK);
    const track = args[1];

    this.enter_command_phase();
    curr_drive.seek(curr_drive.curr_head, track, curr_drive.curr_sect);

    // raise interrupt without response
    this.status0 |= SR0_SEEK;
    this.raise_irq("SEEK command");
};

FloppyController.prototype.exec_sense_interrupt_status = function(args)
{
    const curr_drive = this.drives[this.curr_drive_no];

    let status0;
    if(this.reset_sense_int_count > 0)
    {
        const drv_nr = RESET_SENSE_INT_MAX - this.reset_sense_int_count--;
        status0 = SR0_RDYCHG | drv_nr;
    }
    else if(this.sra & SRA_INTPEND)
    {
        status0 = (this.status0 & ~(SR0_HEAD | SR0_DS1 | SR0_DS0)) | this.curr_drive_no;
    }
    else
    {
        dbg_log("No interrupt pending, aborting SENSE INTERRUPT command!", LOG_FLOPPY);
        this.response_data[0] = SR0_INVCMD;
        this.enter_result_phase(1);
        return;
    }

    this.response_data[0] = status0;
    this.response_data[1] = curr_drive.curr_track;

    // lower interrupt
    this.enter_result_phase(2);
    this.lower_irq("SENSE INTERRUPT command");
    this.status0 = SR0_RDYCHG;
};

FloppyController.prototype.exec_recalibrate = function(args)
{
    const curr_drive = this.set_curr_drive_no(args[0] & DOR_SELMASK);

    curr_drive.seek(0, 0, 1);

    // raise interrupt without response
    this.enter_command_phase();
    this.status0 |= SR0_SEEK;
    this.raise_irq("RECALIBRATE command");
};

FloppyController.prototype.exec_format_track = function(args)
{
    const curr_drive = this.set_curr_drive_no(args[0] & DOR_SELMASK);

    let status0 = 0, status1 = 0;
    if(curr_drive.read_only)
    {
        status0 = SR0_ABNTERM | SR0_SEEK;
        status1 = SR1_NW;
    }

    // raise interrupt
    this.end_read_write(status0, status1, 0);
};

FloppyController.prototype.exec_read_id = function(args)
{
    const head_sel = args[0];
    const curr_drive = this.drives[this.curr_drive_no];

    curr_drive.curr_head = (head_sel >> 2) & 1;
    if(curr_drive.max_sect !== 0)
    {
        curr_drive.curr_sect = (curr_drive.curr_sect % curr_drive.max_sect) + 1;
    }

    // raise interrupt
    this.end_read_write(0, 0, 0);
};

FloppyController.prototype.exec_specify = function(args)
{
    const hut_srt = args[0]; // 0..3: Head Unload Time (HUT), 4..7: Step Rate Interval (SRT)
    const nd_hlt = args[1];  // 0: Non-DMA mode flag (ND), 1..7: Head Load Time (HLT)

    this.step_rate_interval = hut_srt >> 4;
    this.head_load_time = nd_hlt >> 1;
    if(nd_hlt & 0x1)
    {
        this.dor &= ~DOR_DMAEN;
    }
    else
    {
        this.dor |= DOR_DMAEN;
    }

    // no interrupt or response
    this.enter_command_phase();
};

FloppyController.prototype.exec_sense_drive_status = function(args)
{
    const drv_sel = args[0];
    const curr_drive = this.set_curr_drive_no(drv_sel & DOR_SELMASK);
    curr_drive.curr_head = (drv_sel >> 2) & 1;

    this.response_data[0] = (curr_drive.read_only ? 0x40 : 0) |    // response byte is Status Register 3
        (curr_drive.curr_track === 0 ? 0x10 : 0) |
        (curr_drive.curr_head << 2) |
        this.curr_drive_no |
        0x28;   // bits 3 and 5 unused, always "1"

    // no interrupt
    this.enter_result_phase(1);
};

FloppyController.prototype.exec_perpendicular_mode = function(args)
{
    const perp_mode = args[0];

    if(perp_mode & 0x80)  // 0x80: OW, bits D0 and D1 can be overwritten
    {
        const curr_drive = this.drives[this.curr_drive_no];
        curr_drive.perpendicular = perp_mode & 0x7;
    }

    // no interrupt or response
    this.enter_command_phase();
};

FloppyController.prototype.exec_configure = function(args)
{
    // args[0] is always 0
    this.fdc_config = args[1];
    this.precomp_trk = args[2];

    // no interrupt or response
    this.enter_command_phase();
};

FloppyController.prototype.exec_lock = function(args)
{
    if(this.cmd_code & 0x80)
    {
        // LOCK command
        this.locked = true;
        this.response_data[0] = 0x10;
    }
    else
    {
        // UNLOCK command
        this.locked = false;
        this.response_data[0] = 0;
    }

    // no interrupt
    this.enter_result_phase(1);
};

FloppyController.prototype.exec_dump_regs = function(args)
{
    const curr_drive = this.drives[this.curr_drive_no];

    // drive positions
    this.response_data[0] = this.drives[0].curr_track;
    this.response_data[1] = this.drives[1].curr_track;
    this.response_data[2] = 0;
    this.response_data[3] = 0;
    // timers
    this.response_data[4] = this.step_rate_interval;
    this.response_data[5] = (this.head_load_time << 1) | ((this.dor & DOR_DMAEN) ? 1 : 0);
    this.response_data[6] = curr_drive.max_sect;
    this.response_data[7] = (this.locked ? 0x80 : 0) | (curr_drive.perpendicular << 2);
    this.response_data[8] = this.fdc_config;
    this.response_data[9] = this.precomp_trk;

    // no interrupt
    this.enter_result_phase(10);
};

FloppyController.prototype.exec_version = function(args)
{
    this.response_data[0] = 0x90;   // 0x80: Standard controller, 0x81: Intel 82077, 0x90: Intel 82078

    // no interrupt
    this.enter_result_phase(1);
};

FloppyController.prototype.exec_part_id = function(args)
{
    this.response_data[0] = 0x41;   // Stepping 1 (PS/2 mode)

    // no interrupt
    this.enter_result_phase(1);
};

// ---------------------------------------------------------------------------

FloppyController.prototype.start_read_write = function(args, do_write)
{
    const curr_drive = this.set_curr_drive_no(args[0] & DOR_SELMASK);
    const track = args[1];
    const head = args[2];
    const sect = args[3];
    const ssc = args[4];    // sector size code 0..7 (0:128, 1:256, 2:512, ..., 7:16384 bytes/sect)
    const eot = args[5];    // last sector number of current track
    const dtl = args[7] < 128 ? args[7] : 128;  // data length in bytes if ssc is 0, else unused

    switch(curr_drive.seek(head, track, sect))
    {
    case 2: // error: sect too big
        this.end_read_write(SR0_ABNTERM, 0, 0);
        this.response_data[3] = track;
        this.response_data[4] = head;
        this.response_data[5] = sect;
        return;
    case 3: // error: track too big
        this.end_read_write(SR0_ABNTERM, SR1_EC, 0);
        this.response_data[3] = track;
        this.response_data[4] = head;
        this.response_data[5] = sect;
        return;
    case 1: // track changed
        this.status0 |= SR0_SEEK;
        break;
    }

    const sect_size = 128 << (ssc > 7 ? 7 : ssc);               // sector size in bytes
    const sect_start = curr_drive.chs2lba(track, head, sect);   // linear start sector
    const data_offset = sect_start * sect_size;                 // data offset in bytes
    let data_length;                                            // data length in bytes
    if(sect_size === 128)
    {
        // if requested data length (dtl) is < 128:
        // - READ: return only dtl bytes, skipping the sector's remaining bytes (OK)
        // - WRITE: we must fill the sector's remaining bytes with 0 (TODO!)
        if(do_write && dtl < 128)
        {
            dbg_assert(false, "dtl=" + dtl + " is less than 128, zero-padding is still unimplemented!");
        }
        data_length = dtl;
    }
    else
    {
        if(this.cmd_flags & CMD_FLAG_MULTI_TRACK)
        {
            data_length = (2 * eot - sect + 1) * sect_size;
        }
        else
        {
            data_length = (eot - sect + 1) * sect_size;
        }
        if(data_length <= 0)
        {
            dbg_log("invalid data_length: " + data_length + " sect=" + sect + " eot=" + eot, LOG_FLOPPY);
            this.end_read_write(SR0_ABNTERM, SR1_MA, 0);
            this.response_data[3] = track;
            this.response_data[4] = head;
            this.response_data[5] = sect;
            return;
        }
    }
    this.eot = eot;

    if(DEBUG)
    {
        dbg_log("Floppy " + this.cmd_table[this.cmd_code].name +
            " from: " + h(data_offset) + ", length: " + h(data_length) +
            ", C/H/S: " + track + "/" + head + "/" + sect + ", ro: " + curr_drive.read_only +
            ", #S: " + curr_drive.max_sect + ", #H: " + curr_drive.max_head,
            LOG_FLOPPY);
    }

    if(do_write && curr_drive.read_only)
    {
        this.end_read_write(SR0_ABNTERM | SR0_SEEK, SR1_NW, 0);
        this.response_data[3] = track;
        this.response_data[4] = head;
        this.response_data[5] = sect;
        return;
    }

    if(this.dor & DOR_DMAEN)
    {
        // start DMA transfer
        this.msr &= ~MSR_RQM;
        const do_dma = do_write ? this.dma.do_write : this.dma.do_read;
        do_dma.call(this.dma,
            curr_drive.buffer,
            data_offset,
            data_length,
            FDC_DMA_CHANNEL,
            (dma_error, error, retry) => {
                if(dma_error && error)
                {
                    // (the image failed the read or write: the disk's policy,
                    // as for hard disks (src/block_backend.js): "stop" holds
                    // the transfer, the command unfinished, and stops the
                    // machine, run() tries it again; "report" ends the
                    // command with an error; the host gets a disk-error event)
                    const owner = { buffer: curr_drive.buffer, cpu: this.cpu, name: curr_drive.name, drive: curr_drive };
                    block_failed(owner, do_write ? "write" : "read", data_offset, data_length, error, retry,
                        () => this.end_read_write(SR0_ABNTERM, 0, 0), () => {});
                }
                else if(dma_error)
                {
                    dbg_log("DMA floppy error", LOG_FLOPPY);
                    this.end_read_write(SR0_ABNTERM, 0, 0);
                }
                else
                {
                    this.seek_next_sect();
                    this.end_read_write(0, 0, 0);
                }
            }
        );
    }
    else
    {
        // start PIO transfer
        dbg_assert(false, this.cmd_table[this.cmd_code].name + " in PIO mode not supported!");
    }
};

/**
 * A drive's disk is taken out (ejected, or another inserted): its transfer
 * held after an error ends with the error, as the guest would see a disk
 * pulled out
 * @param {!FloppyDrive} drive
 */
FloppyController.prototype.disk_removed = function(drive)
{
    const holds = this.cpu.disk_holds;
    if(!holds || !holds.length) return;
    const mine = holds.filter(hold => hold.owner.drive === drive);
    this.cpu.disk_holds = holds.filter(hold => hold.owner.drive !== drive);
    mine.forEach(hold => hold.report(hold.error));
};

FloppyController.prototype.end_read_write = function(status0, status1, status2)
{
    const curr_drive = this.drives[this.curr_drive_no];

    this.status0 &= ~(SR0_DS0 | SR0_DS1 | SR0_HEAD);
    this.status0 |= this.curr_drive_no;
    if(curr_drive.curr_head)
    {
        this.status0 |= SR0_HEAD;
    }
    this.status0 |= status0;

    this.msr |= MSR_RQM | MSR_DIO;
    this.msr &= ~MSR_NDMA;

    this.response_data[0] = this.status0;
    this.response_data[1] = status1;
    this.response_data[2] = status2;
    this.response_data[3] = curr_drive.curr_track;
    this.response_data[4] = curr_drive.curr_head;
    this.response_data[5] = curr_drive.curr_sect;
    this.response_data[6] = SECTOR_SIZE_CODE;

    // raise interrupt
    this.enter_result_phase(7);
    this.raise_irq(this.cmd_table[this.cmd_code].name + " command");
};

FloppyController.prototype.seek_next_sect = function()
{
    // Seek to next sector
    // returns 0 when end of track reached (for DBL_SIDES on head 1). otherwise returns 1
    const curr_drive = this.drives[this.curr_drive_no];

    // XXX: curr_sect >= max_sect should be an error in fact (TODO: this comment comes from qemu, not sure what to make of it)
    let new_track = curr_drive.curr_track;
    let new_head = curr_drive.curr_head;
    let new_sect = curr_drive.curr_sect;
    let ret = 1;

    if(new_sect >= curr_drive.max_sect || new_sect === this.eot)
    {
        new_sect = 1;
        if(this.cmd_flags & CMD_FLAG_MULTI_TRACK)
        {
            if(new_head === 0 && curr_drive.max_head === 2)
            {
                new_head = 1;
            }
            else
            {
                new_head = 0;
                new_track++;
                this.status0 |= SR0_SEEK;
                if(curr_drive.max_head === 1)
                {
                    ret = 0;
                }
            }
        }
        else
        {
            this.status0 |= SR0_SEEK;
            new_track++;
            ret = 0;
        }
    }
    else
    {
        new_sect++;
    }

    curr_drive.seek(new_head, new_track, new_sect);
    return ret;
};

FloppyController.prototype.get_state = function()
{
    // NOTE: Old-style state snapshots (state indices 0..18) did not include
    // the disk image buffer, only a few register states, so a floppy drive
    // remained essentially unchangd when a state snapshot was applied.
    // The snapshotted registers can be safely ignored when restoring state,
    // hence the entire old-style state is now ignored and deprecated.
    const state = [];
    state[19] = this.sra;
    state[20] = this.srb;
    state[21] = this.dor;
    state[22] = this.tdr;
    state[23] = this.msr;
    state[24] = this.dsr;
    state[25] = this.cmd_phase;
    state[26] = this.cmd_code;
    state[27] = this.cmd_flags;
    state[28] = this.cmd_buffer;    // Uint8Array
    state[29] = this.cmd_cursor;
    state[30] = this.cmd_remaining;
    state[31] = this.response_data; // Uint8Array
    state[32] = this.response_cursor;
    state[33] = this.response_length;
    state[34] = this.status0;
    state[35] = this.status1;
    state[36] = this.curr_drive_no;
    state[37] = this.reset_sense_int_count;
    state[38] = this.locked;
    state[39] = this.step_rate_interval;
    state[40] = this.head_load_time;
    state[41] = this.fdc_config;
    state[42] = this.precomp_trk;
    state[43] = this.eot;
    state[44] = this.drives[0].get_state();
    state[45] = this.drives[1].get_state();
    return state;
};

FloppyController.prototype.set_state = function(state)
{
    if(typeof state[19] === "undefined")
    {
        // see comment above in get_state()
        return;
    }
    this.sra = state[19];
    this.srb = state[20];
    this.dor = state[21];
    this.tdr = state[22];
    this.msr = state[23];
    this.dsr = state[24];
    this.cmd_phase = state[25];
    this.cmd_code = state[26];
    this.cmd_flags = state[27];
    this.cmd_buffer.set(state[28]);     // Uint8Array
    this.cmd_cursor = state[29];
    this.cmd_remaining = state[30];
    this.response_data.set(state[31]);  // Uint8Array
    this.response_cursor = state[32];
    this.response_length = state[33];
    this.status0 = state[34];
    this.status1 = state[35];
    this.curr_drive_no = state[36];
    this.reset_sense_int_count = state[37];
    this.locked = state[38];
    this.step_rate_interval = state[39];
    this.head_load_time = state[40];
    this.fdc_config = state[41];
    this.precomp_trk = state[42];
    this.eot = state[43];
    this.drives[0].set_state(state[44]);
    this.drives[1].set_state(state[45]);
};

// class FloppyDrive ---------------------------------------------------------

/**
 * Floppy disk formats
 *
 * In many cases, the total sector count (sectors*tracks*heads) of a format
 * is enough to uniquely identify it. However, there are some total sector
 * collisions between formats of different physical size (drive_type), these
 * are highlighed below in the "collides" column.
 *
 * Matches that are higher up in the table take precedence over later matches.
 *
 * @see {@link https://github.com/qemu/qemu/blob/e240f6cc25917f3138d9e95e0343ae23b63a3f8c/hw/block/fdc.c#L99}
 * @see {@link https://en.wikipedia.org/wiki/List_of_floppy_disk_formats}
 */
/**
 * Whether an image has the size of a floppy format (an image written back
 * is used as it is)
 * @param {number} size
 * @return {boolean}
 */
export function floppy_format_size(size)
{
    return DISK_FORMATS.some(f => f.sectors * f.tracks * f.heads * SECTOR_SIZE === size);
}

const DISK_FORMATS = [
    //                                                                 ttl_sect     size     collides
    // 1.44 MB 3"1/2 floppy disks                                             |     |        |
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 18, tracks: 80, heads: 2 }, // 2880  1.44 MB  3.5"
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 20, tracks: 80, heads: 2 }, // 3200  1.6 MB   3.5"
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 21, tracks: 80, heads: 2 }, // 3360  1.68 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 21, tracks: 82, heads: 2 }, // 3444  1.72 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 21, tracks: 83, heads: 2 }, // 3486  1.74 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 22, tracks: 80, heads: 2 }, // 3520  1.76 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 23, tracks: 80, heads: 2 }, // 3680  1.84 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 24, tracks: 80, heads: 2 }, // 3840  1.92 MB
    // 2.88 MB 3"1/2 floppy disks
    { drive_type: CMOS_FDD_TYPE_2880, sectors: 36, tracks: 80, heads: 2 }, // 5760  2.88 MB
    { drive_type: CMOS_FDD_TYPE_2880, sectors: 39, tracks: 80, heads: 2 }, // 6240  3.12 MB
    { drive_type: CMOS_FDD_TYPE_2880, sectors: 40, tracks: 80, heads: 2 }, // 6400  3.2 MB
    { drive_type: CMOS_FDD_TYPE_2880, sectors: 44, tracks: 80, heads: 2 }, // 7040  3.52 MB
    { drive_type: CMOS_FDD_TYPE_2880, sectors: 48, tracks: 80, heads: 2 }, // 7680  3.84 MB
    // 720 kB 3"1/2 floppy disks
    { drive_type: CMOS_FDD_TYPE_1440, sectors:  8, tracks: 80, heads: 2 }, // 1280  640 kB
    { drive_type: CMOS_FDD_TYPE_1440, sectors:  9, tracks: 80, heads: 2 }, // 1440  720 kB   3.5"
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 10, tracks: 80, heads: 2 }, // 1600  800 kB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 10, tracks: 82, heads: 2 }, // 1640  820 kB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 10, tracks: 83, heads: 2 }, // 1660  830 kB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 13, tracks: 80, heads: 2 }, // 2080  1.04 MB
    { drive_type: CMOS_FDD_TYPE_1440, sectors: 14, tracks: 80, heads: 2 }, // 2240  1.12 MB
    // 1.2 MB 5"1/4 floppy disks
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 15, tracks: 80, heads: 2 }, // 2400  1.2 MB
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 18, tracks: 80, heads: 2 }, // 2880  1.44 MB  5.25"
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 18, tracks: 82, heads: 2 }, // 2952  1.48 MB
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 18, tracks: 83, heads: 2 }, // 2988  1.49 MB
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 20, tracks: 80, heads: 2 }, // 3200  1.6 MB   5.25"
    // 720 kB 5"1/4 floppy disks
    { drive_type: CMOS_FDD_TYPE_1200, sectors:  9, tracks: 80, heads: 2 }, // 1440  720 kB   5.25"
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 11, tracks: 80, heads: 2 }, // 1760  880 kB
    // 360 kB 5"1/4 floppy disks
    { drive_type: CMOS_FDD_TYPE_1200, sectors:  9, tracks: 40, heads: 2 }, // 720   360 kB   5.25"
    { drive_type: CMOS_FDD_TYPE_1200, sectors:  9, tracks: 40, heads: 1 }, // 360   180 kB
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 10, tracks: 41, heads: 2 }, // 820   410 kB
    { drive_type: CMOS_FDD_TYPE_1200, sectors: 10, tracks: 42, heads: 2 }, // 840   420 kB
    // 320 kB 5"1/4 floppy disks
    { drive_type: CMOS_FDD_TYPE_1200, sectors:  8, tracks: 40, heads: 2 }, // 640   320 kB
    { drive_type: CMOS_FDD_TYPE_1200, sectors:  8, tracks: 40, heads: 1 }, // 320   160 kB
    // 360 kB must match 5"1/4 better than 3"1/2...
    { drive_type: CMOS_FDD_TYPE_1440, sectors:  9, tracks: 80, heads: 1 }, // 720   360 kB   3.5"
    // types defined in earlier v86 releases (not defined in qemu)
    { drive_type: CMOS_FDD_TYPE_360,  sectors: 10, tracks: 40, heads: 1 }, // 400   200 kB
    { drive_type: CMOS_FDD_TYPE_360,  sectors: 10, tracks: 40, heads: 2 }, // 800   400 kB
];

/**
 * @constructor
 *
 * @param {string} name
 * @param {Object|undefined} fdd_config
 * @param {SyncBuffer|Uint8Array|null|undefined} buffer
 * @param {number} fallback_drive_type
 */
function FloppyDrive(name, fdd_config, buffer, fallback_drive_type)
{
    /** @const */
    this.name = name;

    // drive state
    this.drive_type = CMOS_FDD_TYPE_NO_DRIVE;

    // disk state
    this.max_track = 0;     // disk's max. track, was: FloppyController.number_of_cylinders (qemu: max_track)
    this.max_head = 0;      // disk's max. head (1 or 2), was: FloppyController.number_of_heads
    this.max_sect = 0;      // disk's max. sect, was: FloppyController.sectors_per_track (qemu: last_sect)
    this.curr_track = 0;    // >= 0, was: FloppyController.last_cylinder (qemu: track)
    this.curr_head = 0;     // 0 or 1, was: FloppyController.last_head (qemu: head)
    this.curr_sect = 1;     // > 0, was: FloppyController.last_sector (qemu: sect)
    this.perpendicular = 0;
    this.read_only = false;
    this.media_changed = true;
    this.buffer = null;

    Object.seal(this);

    // Drive type this.drive_type is either (in this order):
    // - specified in fdd_config.drive_type (if defined),
    // - derived from given image buffer (if provided), or
    // - specfied in fallback_drive_type.
    // If buffer is undefined and fdd_config.drive_type is
    // CMOS_FDD_TYPE_NO_DRIVE then the drive will be invisible to the guest.
    const cfg_drive_type = fdd_config?.drive_type;
    if(cfg_drive_type !== undefined && cfg_drive_type >= 0 && cfg_drive_type <= 5)
    {
        this.drive_type = cfg_drive_type;
    }

    this.insert_disk(buffer, !! fdd_config?.read_only);

    if(this.drive_type === CMOS_FDD_TYPE_NO_DRIVE && cfg_drive_type === undefined)
    {
        this.drive_type = fallback_drive_type;
    }

    dbg_log("floppy drive " + this.name + " ready, drive type: " + this.drive_type, LOG_FLOPPY);
}

/**
 * Insert disk image into floppy drive.
 *
 * @param {SyncBuffer|Uint8Array|null|undefined} buffer
 * @param {boolean=} read_only
 * @return {boolean} true if the given buffer was accepted
 */
FloppyDrive.prototype.insert_disk = function(buffer, read_only)
{
    if(!buffer)
    {
        return false;
    }

    if(buffer instanceof Uint8Array)
    {
        buffer = new SyncBuffer(buffer.buffer);
    }

    const [new_buffer, disk_format] = this.find_disk_format(buffer, this.drive_type);
    // (a disk written back is not copied into a larger buffer: it has a
    // floppy format's size)
    if(new_buffer && buffer.writeback && new_buffer !== buffer)
    {
        dbg_log("WARNING: disk rejected, an image written back must have the size of a floppy format, not " +
            buffer.byteLength + " bytes", LOG_FLOPPY);
        return false;
    }
    if(!new_buffer)
    {
        dbg_log("WARNING: disk rejected, no suitable disk format found for image of size " +
            buffer.byteLength + " bytes", LOG_FLOPPY);
        return false;
    }

    this.max_track = disk_format.tracks;
    this.max_head = disk_format.heads;
    this.max_sect = disk_format.sectors;
    this.read_only = !!read_only;
    this.media_changed = true;
    this.buffer = new_buffer;

    if(this.drive_type === CMOS_FDD_TYPE_NO_DRIVE)
    {
        // auto-select drive type once during construction
        this.drive_type = disk_format.drive_type;
    }

    if(DEBUG)
    {
        dbg_log("disk inserted into " + this.name + ": type: " + disk_format.drive_type +
            ", C/H/S: " + disk_format.tracks + "/" + disk_format.heads + "/" +
            disk_format.sectors + ", size: " + new_buffer.byteLength,
            LOG_FLOPPY);
    }
    return true;
};

/**
 * Eject disk from this floppy drive.
 */
FloppyDrive.prototype.eject_disk = function()
{
    this.max_track = 0;
    this.max_head = 0;
    this.max_sect = 0;
    this.media_changed = true;
    this.buffer = null;
};

/**
 * Returns this drive's current image buffer or null if no disk is inserted.
 * @return {Uint8Array|null}
 */
FloppyDrive.prototype.get_buffer = function()
{
    return this.buffer ? new Uint8Array(this.buffer.buffer) : null;
};

/**
 * Map structured C/H/S address to linear block address (LBA).
 * @param {number} track
 * @param {number} head
 * @param {number} sect
 * @return {number} lba the linear block address
 */
FloppyDrive.prototype.chs2lba = function(track, head, sect)
{
    return (track * this.max_head + head) * this.max_sect + sect - 1;
};

/**
 * Find best-matching disk format for the given image buffer.
 *
 * If the given drive_type is CMOS_FDD_TYPE_NO_DRIVE then drive types are
 * ignored and the first matching disk format is selected (auto-detect).
 *
 * If the size of the given buffer does not match any known floppy disk
 * format then the smallest format larger than the image buffer is
 * selected, and buffer is copied into a new, format-sized buffer with
 * trailing zeroes.
 *
 * Returns [null, null] if the given buffer is larger than any known
 * floppy disk format.
 *
 * @param {SyncBuffer} buffer
 * @param {number} drive_type
 * @return [{SyncBuffer|null}, {Object|null}] [buffer, disk_format]
 */
FloppyDrive.prototype.find_disk_format = function(buffer, drive_type)
{
    const autodetect = drive_type === CMOS_FDD_TYPE_NO_DRIVE;
    const buffer_size = buffer.byteLength;

    let preferred_match=-1, medium_match=-1, size_match=-1, nearest_match=-1, nearest_size=-1;
    for(let i = 0; i < DISK_FORMATS.length; i++)
    {
        const disk_format = DISK_FORMATS[i];
        const disk_size = disk_format.sectors * disk_format.tracks * disk_format.heads * SECTOR_SIZE;
        if(buffer_size === disk_size)
        {
            if(autodetect || disk_format.drive_type === drive_type)
            {
                // (1) same size and CMOS drive type
                preferred_match = i;
                break;
            }
            else if(!autodetect && CMOS_FDD_TYPE_MEDIUM[disk_format.drive_type] === CMOS_FDD_TYPE_MEDIUM[drive_type])
            {
                // (2) same size and physical medium size (5"1/4 or 3"1/2)
                medium_match = (medium_match === -1) ? i : medium_match;
            }
            else
            {
                // (3) same size
                size_match = (size_match === -1) ? i : size_match;
            }
        }
        else if(buffer_size < disk_size)
        {
            if(nearest_size === -1 || disk_size < nearest_size)
            {
                // (4) nearest matching size
                nearest_match = i;
                nearest_size = disk_size;
            }
        }
    }

    if(preferred_match !== -1)
    {
        return [buffer, DISK_FORMATS[preferred_match]];
    }
    else if(medium_match !== -1)
    {
        return [buffer, DISK_FORMATS[medium_match]];
    }
    else if(size_match !== -1)
    {
        return [buffer, DISK_FORMATS[size_match]];
    }
    else if(nearest_match !== -1)
    {
        const tmp_buffer = new Uint8Array(nearest_size);
        tmp_buffer.set(new Uint8Array(buffer.buffer));
        return [new SyncBuffer(tmp_buffer.buffer), DISK_FORMATS[nearest_match]];
    }
    else
    {
        return [null, null];
    }
};

/**
 * Seek to a new position, returns:
 *   0 if already on right track
 *   1 if track changed
 *   2 if track is invalid
 *   3 if sector is invalid
 *
 * @param {number} head
 * @param {number} track
 * @param {number} sect
 * @return {number}
 */
FloppyDrive.prototype.seek = function(head, track, sect)
{
    if((track > this.max_track) || (head !== 0 && this.max_head === 1))
    {
        dbg_log("WARNING: attempt to seek to invalid track: head: " + head + ", track: " + track + ", sect: " + sect, LOG_FLOPPY);
        return 2;
    }
    if(sect > this.max_sect)
    {
        dbg_log("WARNING: attempt to seek beyond last sector: " + sect + " (max: " + this.max_sect + ")", LOG_FLOPPY);
        return 3;
    }

    let result = 0;
    const curr_lba = this.chs2lba(this.curr_track, this.curr_head, this.curr_sect);
    const new_lba = this.chs2lba(track, head, sect);
    if(curr_lba !== new_lba)
    {
        if(this.curr_track !== track)
        {
            if(this.buffer)
            {
                this.media_changed = false;
            }
            result = 1;
        }
        this.curr_head = head;
        this.curr_track = track;
        this.curr_sect = sect;
    }

    if(!this.buffer)
    {
        result = 2;
    }

    return result;
};

FloppyDrive.prototype.get_state = function()
{
    const state = [];
    state[0]  = this.drive_type;
    state[1]  = this.max_track;
    state[2]  = this.max_head;
    state[3]  = this.max_sect;
    state[4]  = this.curr_track;
    state[5]  = this.curr_head;
    state[6]  = this.curr_sect;
    state[7]  = this.perpendicular;
    state[8]  = this.read_only;
    state[9]  = this.media_changed;
    state[10] = this.buffer ? this.buffer.get_state() : null;   // SyncBuffer
    return state;
};

FloppyDrive.prototype.set_state = function(state)
{
    this.drive_type = state[0];
    this.max_track = state[1];
    this.max_head = state[2];
    this.max_sect = state[3];
    this.curr_track = state[4];
    this.curr_head = state[5];
    this.curr_sect = state[6];
    this.perpendicular = state[7];
    this.read_only = state[8];
    this.media_changed = state[9];
    if(state[10])
    {
        if(!this.buffer)
        {
            this.buffer = new SyncBuffer(new ArrayBuffer(0));
        }
        // (a disk written back: a reference, src/disk_writeback.js)
        restore_disk_state(this.buffer, state[10]);
    }
    else
    {
        this.buffer = null;
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/gles/gles1_state.js                                                                  0000644 0000000 0000000 00000100272 00000000000 014160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // OpenGL ES 1.1's own state (docs/gles-proxy-plan.md E4), written from the
// GLES 1.1 specification: the matrix stacks and their operations, the
// current color, normal, texture coordinates and point size, the client
// arrays (the encoder's *PointerData/*PointerOffset), lights, the light
// model, the material, the shade model, each texture unit's environment and
// enable, fog, the alpha test, user clip planes (kept in eye coordinates,
// as the specification transforms them), point parameters and sprites, the
// logic op; the 16.16 fixed variants; the queries of all of it. The shadow
// state (src/gles/gles_shadow.js) runs these for GLES 1.1 contexts, beside
// the object state both versions share; the page's executor draws from the
// same state with gl-webgpu's fixed-function generator.

const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
export const UNITS = 4;
const LIGHTS = 8;
const CLIP_PLANES = 6;
const STACK_DEPTH = { 0x1700: 16, 0x1701: 2, 0x1702: 2 };
const STACK_OVERFLOW = 0x0503, STACK_UNDERFLOW = 0x0504;
const INVALID_ENUM = 0x0500, INVALID_VALUE = 0x0501, INVALID_OPERATION = 0x0502;
const FIXED = 0x140C, FLOAT = 0x1406, BYTE = 0x1400, UNSIGNED_BYTE = 0x1401, SHORT = 0x1402;
/** the client arrays glEnableClientState takes */
export const CLIENT_ARRAYS = { 0x8074: "vertex", 0x8075: "normal", 0x8076: "color", 0x8078: "texcoord", 0x8B9C: "point_size" };

/** @param {!Array<number>} a @param {!Array<number>} b @return {!Array<number>} a * b, column-major */
export function mat_mul(a, b)
{
    const m = new Array(16);
    for(let c = 0; c < 4; c++)
    {
        for(let r = 0; r < 4; r++)
        {
            m[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
        }
    }
    return m;
}

/** @param {!Array<number>} m @return {!Array<number>} its inverse (the identity for a singular one) */
export function mat_inverse(m)
{
    const inv = new Array(16);
    inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
    inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
    inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
    inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
    inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
    inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
    inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
    inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
    inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
    inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
    inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
    inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
    inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
    inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
    inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
    inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];
    const det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
    if(!det) return IDENTITY.slice();
    return inv.map(v => v / det);
}

/** @param {!Array<number>} m @param {!Array<number>} v @return {!Array<number>} m * v */
function transform(m, v)
{
    return [0, 1, 2, 3].map(r => m[r] * v[0] + m[4 + r] * v[1] + m[8 + r] * v[2] + m[12 + r] * v[3]);
}

/** A GLES 1.1 context's fixed-function state (GLES 1.1 tables 6.x), at its initial values */
export function new_ff_state()
{
    const pointer = () => ({ enabled: false, size: 4, type: FLOAT, stride: 0, buffer: 0, offset: 0, data: null });
    return {
        matrix_mode: 0x1700,
        stacks: { 0x1700: [IDENTITY.slice()], 0x1701: [IDENTITY.slice()], 0x1702: Array.from({ length: UNITS }, () => [IDENTITY.slice()]) },
        color: [1, 1, 1, 1], normal: [0, 0, 1], texcoord: Array.from({ length: UNITS }, () => [0, 0, 0, 1]),
        client_active_texture: 0,
        arrays: { vertex: pointer(), normal: Object.assign(pointer(), { size: 3 }), color: pointer(), point_size: Object.assign(pointer(), { size: 1 }),
            texcoord: Array.from({ length: UNITS }, pointer) },
        texture_enabled: Array.from({ length: UNITS }, () => ({ 0x0DE1: false, 0x8D65: false })),
        lights: Array.from({ length: LIGHTS }, (_, i) => ({
            ambient: [0, 0, 0, 1], diffuse: i ? [0, 0, 0, 1] : [1, 1, 1, 1], specular: i ? [0, 0, 0, 1] : [1, 1, 1, 1],
            position: [0, 0, 1, 0], spot_direction: [0, 0, -1], spot_exponent: 0, spot_cutoff: 180, attenuation: [1, 0, 0],
        })),
        light_model: { ambient: [0.2, 0.2, 0.2, 1], two_side: 0 },
        material: { ambient: [0.2, 0.2, 0.2, 1], diffuse: [0.8, 0.8, 0.8, 1], specular: [0, 0, 0, 1], emission: [0, 0, 0, 1], shininess: 0 },
        shade_model: 0x1D01,
        env: Array.from({ length: UNITS }, () => ({
            mode: 0x2100, color: [0, 0, 0, 0], combine_rgb: 0x2100, combine_alpha: 0x2100,
            src_rgb: [0x1702, 0x8578, 0x8576], src_alpha: [0x1702, 0x8578, 0x8576],
            operand_rgb: [0x0300, 0x0300, 0x0302], operand_alpha: [0x0302, 0x0302, 0x0302], rgb_scale: 1, alpha_scale: 1, coord_replace: 0,
        })),
        fog: { mode: 0x0800, density: 1, start: 0, end: 1, color: [0, 0, 0, 0] },
        alpha_func: 0x0207, alpha_ref: 0,
        clip_planes: Array.from({ length: CLIP_PLANES }, () => [0, 0, 0, 0]),
        point: { size: 1, min: 0, max: 1, fade: 1, attenuation: [1, 0, 0] },
        logic_op: 0x1503,
    };
}

/** @param {!Object} ff @return {!Array<!Array<number>>} the current matrix's stack */
function stack(ff, active_texture)
{
    const s = ff.stacks[ff.matrix_mode];
    return ff.matrix_mode === 0x1702 ? s[active_texture] : s;
}

/** @param {!Object} c the context @return {!Array<number>} the current modelview matrix */
export function modelview(c)
{
    return c.ff.stacks[0x1700].at(-1);
}

const x2f = v => v / 65536;
const xs = values => values.map(x2f);

/** @param {?Uint8Array} bytes @param {boolean} fixed @return {!Array<number>} f32s, or 16.16s as numbers */
function values_of(bytes, fixed)
{
    if(!bytes) return [];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const out = [];
    for(let at = 0; at + 4 <= bytes.length; at += 4) out.push(fixed ? view.getInt32(at, true) / 65536 : view.getFloat32(at, true));
    return out;
}

/** The matrix operations: (context, fail, matrix) => the new top or a code */
function matrix_op(build)
{
    return (shadow, c, args, fail) =>
    {
        const m = build(args);
        if(typeof m === "number") return fail(c, m);
        const s = stack(c.ff, c.active_texture);
        s[s.length - 1] = mat_mul(s.at(-1), m);
        return undefined;
    };
}

const translate = ([x, y, z]) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
const scale = ([x, y, z]) => [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1];
function rotate([angle, x, y, z])
{
    const length = Math.hypot(x, y, z);
    if(!length) return IDENTITY.slice();
    x /= length; y /= length; z /= length;
    const a = angle * Math.PI / 180, cs = Math.cos(a), sn = Math.sin(a), t = 1 - cs;
    return [x * x * t + cs, y * x * t + z * sn, x * z * t - y * sn, 0, x * y * t - z * sn, y * y * t + cs, y * z * t + x * sn, 0,
        x * z * t + y * sn, y * z * t - x * sn, z * z * t + cs, 0, 0, 0, 0, 1];
}
function frustum([l, r, b, t, n, f])
{
    if(n <= 0 || f <= 0 || l === r || b === t || n === f) return INVALID_VALUE;
    return [2 * n / (r - l), 0, 0, 0, 0, 2 * n / (t - b), 0, 0, (r + l) / (r - l), (t + b) / (t - b), -(f + n) / (f - n), -1,
        0, 0, -2 * f * n / (f - n), 0];
}
function ortho([l, r, b, t, n, f])
{
    if(l === r || b === t || n === f) return INVALID_VALUE;
    return [2 / (r - l), 0, 0, 0, 0, 2 / (t - b), 0, 0, 0, 0, -2 / (f - n), 0, -(r + l) / (r - l), -(t + b) / (t - b), -(f + n) / (f - n), 1];
}

/** glLight's: a light's parameter (`v` its values), GLES 1.1 2.12.1's checks */
function light(shadow, c, light_enum, pname, v, scalar, fail)
{
    const index = light_enum - 0x4000;
    if(index < 0 || index >= LIGHTS) return fail(c, INVALID_ENUM);
    const l = c.ff.lights[index];
    const vector = { 0x1200: "ambient", 0x1201: "diffuse", 0x1202: "specular", 0x1203: "position", 0x1204: "spot_direction" }[pname];
    if(vector)
    {
        if(scalar) return fail(c, INVALID_ENUM);
        if(pname === 0x1203) l.position = transform(modelview(c), v.slice(0, 4));
        else if(pname === 0x1204)
        {
            const m = modelview(c);
            l.spot_direction = [0, 1, 2].map(r => m[r] * v[0] + m[4 + r] * v[1] + m[8 + r] * v[2]);
        }
        else l[vector] = v.slice(0, 4);
        return undefined;
    }
    const value = v[0];
    switch(pname)
    {
        case 0x1205: if(value < 0 || value > 128) return fail(c, INVALID_VALUE); l.spot_exponent = value; break;
        case 0x1206: if((value < 0 || value > 90) && value !== 180) return fail(c, INVALID_VALUE); l.spot_cutoff = value; break;
        case 0x1207: case 0x1208: case 0x1209:
            if(value < 0) return fail(c, INVALID_VALUE);
            l.attenuation[pname - 0x1207] = value;
            break;
        default: return fail(c, INVALID_ENUM);
    }
    return undefined;
}

function light_model(shadow, c, pname, v, scalar, fail)
{
    if(pname === 0x0B53 && !scalar) c.ff.light_model.ambient = v.slice(0, 4);
    else if(pname === 0x0B52) c.ff.light_model.two_side = v[0] ? 1 : 0;
    else return fail(c, INVALID_ENUM);
    return undefined;
}

function material(shadow, c, face, pname, v, scalar, fail)
{
    if(face !== 0x0408) return fail(c, INVALID_ENUM);
    const m = c.ff.material;
    switch(pname)
    {
        case 0x1601:
            if(v[0] < 0 || v[0] > 128) return fail(c, INVALID_VALUE);
            m.shininess = v[0];
            return undefined;
        case 0x1200: case 0x1201: case 0x1202: case 0x1600: case 0x1602:
            if(scalar) return fail(c, INVALID_ENUM);
            if(pname === 0x1602) m.ambient = m.diffuse = v.slice(0, 4);
            else m[{ 0x1200: "ambient", 0x1201: "diffuse", 0x1202: "specular", 0x1600: "emission" }[pname]] = v.slice(0, 4);
            return undefined;
    }
    return fail(c, INVALID_ENUM);
}

/** glTexEnv's pnames: the field, and its values (null: any value) */
const ENV_PNAMES = {
    0x2200: ["mode", [0x2100, 0x2101, 0x0BE2, 0x0104, 0x1E01, 0x8570]],
    0x8571: ["combine_rgb", [0x1E01, 0x2100, 0x0104, 0x8574, 0x8575, 0x84E7, 0x86AE, 0x86AF]],
    0x8572: ["combine_alpha", [0x1E01, 0x2100, 0x0104, 0x8574, 0x8575, 0x84E7]],
    0x8573: ["rgb_scale", null], 0x0D1C: ["alpha_scale", null],
};
const SOURCES = [0x1702, 0x8576, 0x8577, 0x8578];

function tex_env(shadow, c, target, pname, v, scalar, fail)
{
    const env = c.ff.env[c.active_texture] || c.ff.env[0];
    if(target === 0x8861)
    {
        if(pname !== 0x8862) return fail(c, INVALID_ENUM);
        env.coord_replace = v[0] ? 1 : 0;
        return undefined;
    }
    if(target !== 0x2300) return fail(c, INVALID_ENUM);
    if(pname === 0x2201)
    {
        if(scalar) return fail(c, INVALID_ENUM);
        env.color = v.slice(0, 4).map(x => Math.min(1, Math.max(0, x)));
        return undefined;
    }
    const value = v[0];
    if(pname >= 0x8580 && pname <= 0x858A)
    {
        // SRC0..2_RGB, SRC0..2_ALPHA, OPERAND0..2_RGB (0x8590...), handled below
    }
    const src = { 0x8580: ["src_rgb", 0], 0x8581: ["src_rgb", 1], 0x8582: ["src_rgb", 2], 0x8588: ["src_alpha", 0], 0x8589: ["src_alpha", 1],
        0x858A: ["src_alpha", 2] }[pname];
    if(src)
    {
        if(!SOURCES.includes(value)) return fail(c, INVALID_ENUM);
        env[src[0]][src[1]] = value;
        return undefined;
    }
    const operand = { 0x8590: ["operand_rgb", 0], 0x8591: ["operand_rgb", 1], 0x8592: ["operand_rgb", 2], 0x8598: ["operand_alpha", 0],
        0x8599: ["operand_alpha", 1], 0x859A: ["operand_alpha", 2] }[pname];
    if(operand)
    {
        const allowed = operand[0] === "operand_rgb" ? [0x0300, 0x0301, 0x0302, 0x0303] : [0x0302, 0x0303];
        if(!allowed.includes(value)) return fail(c, INVALID_ENUM);
        env[operand[0]][operand[1]] = value;
        return undefined;
    }
    const entry = ENV_PNAMES[pname];
    if(!entry) return fail(c, INVALID_ENUM);
    if(entry[1] && !entry[1].includes(value)) return fail(c, INVALID_ENUM);
    if(!entry[1] && value !== 1 && value !== 2 && value !== 4) return fail(c, INVALID_VALUE);
    env[entry[0]] = value;
    return undefined;
}

function fog(shadow, c, pname, v, scalar, fail)
{
    const f = c.ff.fog;
    switch(pname)
    {
        case 0x0B65: if(![0x2601, 0x0800, 0x0801].includes(v[0])) return fail(c, INVALID_ENUM); f.mode = v[0]; break;
        case 0x0B62: if(v[0] < 0) return fail(c, INVALID_VALUE); f.density = v[0]; break;
        case 0x0B63: f.start = v[0]; break;
        case 0x0B64: f.end = v[0]; break;
        case 0x0B66: if(scalar) return fail(c, INVALID_ENUM); f.color = v.slice(0, 4).map(x => Math.min(1, Math.max(0, x))); break;
        default: return fail(c, INVALID_ENUM);
    }
    return undefined;
}

function point_parameter(shadow, c, pname, v, scalar, fail)
{
    const p = c.ff.point;
    switch(pname)
    {
        case 0x8126: if(v[0] < 0) return fail(c, INVALID_VALUE); p.min = v[0]; break;
        case 0x8127: if(v[0] < 0) return fail(c, INVALID_VALUE); p.max = v[0]; break;
        case 0x8128: if(v[0] < 0) return fail(c, INVALID_VALUE); p.fade = v[0]; break;
        case 0x8129: if(scalar) return fail(c, INVALID_ENUM); p.attenuation = v.slice(0, 3); break;
        default: return fail(c, INVALID_ENUM);
    }
    return undefined;
}

function clip_plane(shadow, c, plane, v, fail)
{
    const index = plane - 0x3000;
    if(index < 0 || index >= CLIP_PLANES) return fail(c, INVALID_ENUM);
    // (into eye coordinates: the plane times the inverse modelview)
    const inv = mat_inverse(modelview(c));
    c.ff.clip_planes[index] = [0, 1, 2, 3].map(col => v[0] * inv[col * 4] + v[1] * inv[col * 4 + 1] + v[2] * inv[col * 4 + 2] + v[3] * inv[col * 4 + 3]);
    return undefined;
}

/** A client array's pointer: GLES 1.1 2.8's sizes and types */
function pointer(array, sizes, types)
{
    return (shadow, c, args, fail, data_form) =>
    {
        let unit = null, size, type, stride, rest;
        if(array === "texcoord" && data_form) [unit, size, type, stride, ...rest] = args;
        else if(sizes) [size, type, stride, ...rest] = args;
        else { [type, stride, ...rest] = args; size = array === "normal" ? 3 : 1; }
        if(sizes && !sizes.includes(size) || stride < 0) return fail(c, INVALID_VALUE);
        if(!types.includes(type)) return fail(c, INVALID_ENUM);
        const ff = c.ff;
        const p = array === "texcoord" ? ff.arrays.texcoord[unit === null ? ff.client_active_texture : unit] : ff.arrays[array];
        if(!p) return fail(c, INVALID_VALUE);
        Object.assign(p, { size, type, stride, buffer: data_form ? 0 : c.array_buffer, offset: data_form ? 0 : rest[0], data: data_form ? rest[0] : null });
        return undefined;
    };
}

const POSITION_TYPES = [BYTE, SHORT, FIXED, FLOAT];
const ARRAY_HANDLERS = {
    "glVertexPointer": pointer("vertex", [2, 3, 4], POSITION_TYPES),
    "glColorPointer": pointer("color", [4], [UNSIGNED_BYTE, FIXED, FLOAT]),
    "glNormalPointer": pointer("normal", null, POSITION_TYPES),
    "glTexCoordPointer": pointer("texcoord", [2, 3, 4], POSITION_TYPES),
    "glPointSizePointer": pointer("point_size", null, [FIXED, FLOAT]),
};

/**
 * GLES 1.1's commands: (shadow, context, args, fail) to the answer (fail's
 * result when refused). `query(shadow)` marks a call that only asks.
 * @param {function(!Object, number): symbol} fail
 * @param {function(!Object)} query
 * @return {!Object<string, function>}
 */
export function gles1_handlers(fail, query)
{
    const H = {};
    // (the matrix operations, with this fail)
    const matrix = build => { const op = matrix_op(build); return (s, c, a) => op(s, c, a, fail); };
    const both = (name, f) => { H[name + "f"] = (s, c, a) => f(s, c, a, false); H[name + "x"] = (s, c, a) => f(s, c, a.map((v, i) => typeof v === "number" ? v : v), true); };
    H["glMatrixMode"] = (s, c, [mode]) =>
    {
        if(!STACK_DEPTH[mode]) return fail(c, INVALID_ENUM);
        c.ff.matrix_mode = mode;
        return undefined;
    };
    H["glLoadIdentity"] = (s, c) => { const st = stack(c.ff, c.active_texture); st[st.length - 1] = IDENTITY.slice(); return undefined; };
    H["glLoadMatrixf"] = (s, c, [m]) => { const st = stack(c.ff, c.active_texture); st[st.length - 1] = values_of(m, false).slice(0, 16); return undefined; };
    H["glLoadMatrixx"] = (s, c, [m]) => { const st = stack(c.ff, c.active_texture); st[st.length - 1] = values_of(m, true).slice(0, 16); return undefined; };
    H["glMultMatrixf"] = matrix(([m]) => values_of(m, false).slice(0, 16));
    H["glMultMatrixx"] = matrix(([m]) => values_of(m, true).slice(0, 16));
    H["glPushMatrix"] = (s, c) =>
    {
        const st = stack(c.ff, c.active_texture);
        if(st.length >= STACK_DEPTH[c.ff.matrix_mode]) return fail(c, STACK_OVERFLOW);
        st.push(st.at(-1).slice());
        return undefined;
    };
    H["glPopMatrix"] = (s, c) =>
    {
        const st = stack(c.ff, c.active_texture);
        if(st.length <= 1) return fail(c, STACK_UNDERFLOW);
        st.pop();
        return undefined;
    };
    H["glTranslatef"] = matrix(translate);
    H["glTranslatex"] = matrix(a => translate(xs(a)));
    H["glScalef"] = matrix(scale);
    H["glScalex"] = matrix(a => scale(xs(a)));
    H["glRotatef"] = matrix(rotate);
    H["glRotatex"] = matrix(a => rotate(xs(a)));
    H["glFrustumf"] = matrix(frustum);
    H["glFrustumx"] = matrix(a => frustum(xs(a)));
    H["glOrthof"] = matrix(ortho);
    H["glOrthox"] = matrix(a => ortho(xs(a)));
    // current values
    H["glColor4f"] = (s, c, rgba) => { c.ff.color = rgba.slice(); return undefined; };
    H["glColor4x"] = (s, c, rgba) => { c.ff.color = xs(rgba); return undefined; };
    H["glColor4ub"] = (s, c, rgba) => { c.ff.color = rgba.map(v => v / 255); return undefined; };
    H["glNormal3f"] = (s, c, n) => { c.ff.normal = n.slice(); return undefined; };
    H["glNormal3x"] = (s, c, n) => { c.ff.normal = xs(n); return undefined; };
    const texcoord = fixed => (s, c, [target, ...v]) =>
    {
        const unit = target - 0x84C0;
        if(unit < 0 || unit >= UNITS) return fail(c, INVALID_ENUM);
        c.ff.texcoord[unit] = fixed ? xs(v) : v.slice();
        return undefined;
    };
    H["glMultiTexCoord4f"] = texcoord(false);
    H["glMultiTexCoord4x"] = texcoord(true);
    H["glPointSize"] = (s, c, [size]) => { if(!(size > 0)) return fail(c, INVALID_VALUE); c.ff.point.size = size; return undefined; };
    H["glPointSizex"] = (s, c, [size]) => H["glPointSize"](s, c, [x2f(size)]);
    // client arrays
    H["glClientActiveTexture"] = (s, c, [texture]) =>
    {
        const unit = texture - 0x84C0;
        if(unit < 0 || unit >= UNITS) return fail(c, INVALID_ENUM);
        c.ff.client_active_texture = unit;
        return undefined;
    };
    const client_state = enable => (s, c, [array]) =>
    {
        const name = CLIENT_ARRAYS[array];
        if(!name) return fail(c, INVALID_ENUM);
        const p = name === "texcoord" ? c.ff.arrays.texcoord[c.ff.client_active_texture] : c.ff.arrays[name];
        p.enabled = enable;
        return undefined;
    };
    H["glEnableClientState"] = client_state(true);
    H["glDisableClientState"] = client_state(false);
    for(const [name, handler] of Object.entries(ARRAY_HANDLERS))
    {
        H[name + "Data"] = (s, c, a) => handler(s, c, a, fail, true);
        H[name + "Offset"] = (s, c, a) => handler(s, c, a, fail, false);
    }
    // (OES_matrix_palette is not offered: its calls change nothing)
    for(const name of ["glWeightPointerData", "glWeightPointerOffset", "glMatrixIndexPointerData", "glMatrixIndexPointerOffset",
        "glCurrentPaletteMatrixOES", "glLoadPaletteFromModelViewMatrixOES"]) H[name] = () => undefined;
    // lighting, material, environment, fog, points
    for(const [name, f] of [["glLight", light], ["glMaterial", material]])
    {
        H[name + "f"] = (s, c, [a, pname, v]) => f(s, c, a, pname, [v], true, fail);
        H[name + "x"] = (s, c, [a, pname, v]) => f(s, c, a, pname, [pname === 0x1206 || pname === 0x1205 || pname >= 0x1207 || pname === 0x1601 ? x2f(v) : x2f(v)], true, fail);
        H[name + "fv"] = (s, c, [a, pname, v]) => f(s, c, a, pname, values_of(v, false), false, fail);
        H[name + "xv"] = (s, c, [a, pname, v]) => f(s, c, a, pname, values_of(v, true), false, fail);
    }
    for(const [name, f] of [["glLightModel", light_model], ["glFog", fog], ["glPointParameter", point_parameter]])
    {
        // (enum values come as themselves in the x forms: GL_FOG_MODE's)
        const enum_valued = pname => name === "glFog" && pname === 0x0B65;
        H[name + "f"] = (s, c, [pname, v]) => f(s, c, pname, [v], true, fail);
        H[name + "x"] = (s, c, [pname, v]) => f(s, c, pname, [enum_valued(pname) ? v : x2f(v)], true, fail);
        H[name + "fv"] = (s, c, [pname, v]) => f(s, c, pname, values_of(v, false), false, fail);
        H[name + "xv"] = (s, c, [pname, v]) => f(s, c, pname, enum_valued(pname) ? [values_of(v, true)[0] * 65536] : values_of(v, true), false, fail);
    }
    const env_enum = pname => pname !== 0x2201 && pname !== 0x8573 && pname !== 0x0D1C;
    H["glTexEnvf"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, [v], true, fail);
    H["glTexEnvi"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, [v], true, fail);
    H["glTexEnvx"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, [env_enum(pname) ? v : x2f(v)], true, fail);
    H["glTexEnvfv"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, values_of(v, false), false, fail);
    H["glTexEnviv"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, pname === 0x2201 ?
        values_of(v, true).map(x => x * 65536 / 0x7FFFFFFF) : values_of(v, true).map(x => x * 65536), false, fail);
    H["glTexEnvxv"] = (s, c, [t, pname, v]) => tex_env(s, c, t, pname, env_enum(pname) ? values_of(v, true).map(x => x * 65536) : values_of(v, true), false, fail);
    H["glShadeModel"] = (s, c, [mode]) => { if(mode !== 0x1D00 && mode !== 0x1D01) return fail(c, INVALID_ENUM); c.ff.shade_model = mode; return undefined; };
    H["glAlphaFunc"] = (s, c, [func, ref]) =>
    {
        if(func < 0x0200 || func > 0x0207) return fail(c, INVALID_ENUM);
        c.ff.alpha_func = func;
        c.ff.alpha_ref = Math.min(1, Math.max(0, ref));
        return undefined;
    };
    H["glAlphaFuncx"] = (s, c, [func, ref]) => H["glAlphaFunc"](s, c, [func, x2f(ref)]);
    H["glClipPlanef"] = (s, c, [plane, eq]) => clip_plane(s, c, plane, values_of(eq, false), fail);
    H["glClipPlanex"] = (s, c, [plane, eq]) => clip_plane(s, c, plane, values_of(eq, true), fail);
    H["glLogicOp"] = (s, c, [op]) => { if(op < 0x1500 || op > 0x150F) return fail(c, INVALID_ENUM); c.ff.logic_op = op; return undefined; };
    // the draw_texture extension: a screen-aligned rectangle (GLES 1.1 OES_draw_texture)
    const draw_tex = (s, c, [x, y, z, w, h]) => w <= 0 || h <= 0 ? fail(c, INVALID_VALUE) : undefined;
    H["glDrawTexsOES"] = draw_tex;
    H["glDrawTexiOES"] = draw_tex;
    H["glDrawTexfOES"] = draw_tex;
    H["glDrawTexxOES"] = (s, c, a) => draw_tex(s, c, xs(a));
    H["glDrawTexsvOES"] = (s, c, [v]) => draw_tex(s, c, Array.from(new Int16Array(v.slice().buffer)));
    H["glDrawTexivOES"] = (s, c, [v]) => draw_tex(s, c, Array.from(new Int32Array(v.slice().buffer)));
    H["glDrawTexfvOES"] = (s, c, [v]) => draw_tex(s, c, values_of(v, false));
    H["glDrawTexxvOES"] = (s, c, [v]) => draw_tex(s, c, values_of(v, true));
    // (the shared commands' fixed forms)
    for(const [x, f, convert] of [["glClearColorx", "glClearColor", xs], ["glClearDepthx", "glClearDepthf", xs], ["glDepthRangex", "glDepthRangef", xs],
        ["glLineWidthx", "glLineWidth", xs], ["glPolygonOffsetx", "glPolygonOffset", xs], ["glSampleCoveragex", "glSampleCoverage", a => [x2f(a[0]), a[1]]]])
    {
        H[x] = (s, c, a) => s.handlers[f](s, c, convert(a));
    }
    // queries
    H["glGetLightfv"] = (s, c, [l, pname, out]) => get_light(s, c, l, pname, out, "f", query, fail);
    H["glGetLightxv"] = (s, c, [l, pname, out]) => get_light(s, c, l, pname, out, "x", query, fail);
    H["glGetMaterialfv"] = (s, c, [face, pname, out]) => get_material(s, c, face, pname, out, "f", query, fail);
    H["glGetMaterialxv"] = (s, c, [face, pname, out]) => get_material(s, c, face, pname, out, "x", query, fail);
    H["glGetTexEnvfv"] = (s, c, [t, pname, out]) => get_tex_env(s, c, t, pname, out, "f", query, fail);
    H["glGetTexEnviv"] = (s, c, [t, pname, out]) => get_tex_env(s, c, t, pname, out, "i", query, fail);
    H["glGetTexEnvxv"] = (s, c, [t, pname, out]) => get_tex_env(s, c, t, pname, out, "x", query, fail);
    H["glGetClipPlanef"] = (s, c, [plane, out]) => get_clip_plane(s, c, plane, out, "f", query, fail);
    H["glGetClipPlanex"] = (s, c, [plane, out]) => get_clip_plane(s, c, plane, out, "x", query, fail);
    void both;
    return H;
}

/** Values into an out buffer: "f" floats, "x" 16.16, "i" integers (colors normalized) */
function put_values(out, values, as, normalized)
{
    for(let i = 0; i < values.length && 4 * i + 4 <= out.size; i++)
    {
        const v = values[i];
        if(as === "f") out.view.setFloat32(4 * i, v, true);
        else if(as === "x") out.view.setInt32(4 * i, Math.round(v * 65536), true);
        else out.view.setInt32(4 * i, normalized ? Math.round(Math.max(-1, Math.min(1, v)) * 0x7FFFFFFF) : Math.round(v), true);
    }
}

function get_light(s, c, light_enum, pname, out, as, query, fail)
{
    query(s);
    const l = c.ff.lights[light_enum - 0x4000];
    if(!l) return fail(c, INVALID_ENUM);
    const value = { 0x1200: l.ambient, 0x1201: l.diffuse, 0x1202: l.specular, 0x1203: l.position, 0x1204: l.spot_direction,
        0x1205: [l.spot_exponent], 0x1206: [l.spot_cutoff], 0x1207: [l.attenuation[0]], 0x1208: [l.attenuation[1]], 0x1209: [l.attenuation[2]] }[pname];
    if(!value) return fail(c, INVALID_ENUM);
    put_values(out, value, as, false);
    return undefined;
}

function get_material(s, c, face, pname, out, as, query, fail)
{
    query(s);
    if(face !== 0x0404 && face !== 0x0405) return fail(c, INVALID_ENUM);
    const m = c.ff.material;
    const value = { 0x1200: m.ambient, 0x1201: m.diffuse, 0x1202: m.specular, 0x1600: m.emission, 0x1601: [m.shininess] }[pname];
    if(!value) return fail(c, INVALID_ENUM);
    put_values(out, value, as, false);
    return undefined;
}

function get_tex_env(s, c, target, pname, out, as, query, fail)
{
    query(s);
    const env = c.ff.env[c.active_texture] || c.ff.env[0];
    if(target === 0x8861 && pname === 0x8862) { put_values(out, [env.coord_replace], as === "x" ? "i" : as, false); return undefined; }
    if(target !== 0x2300) return fail(c, INVALID_ENUM);
    if(pname === 0x2201) { put_values(out, env.color, as, as === "i"); return undefined; }
    const value = { 0x2200: env.mode, 0x8571: env.combine_rgb, 0x8572: env.combine_alpha, 0x8573: env.rgb_scale, 0x0D1C: env.alpha_scale,
        0x8580: env.src_rgb[0], 0x8581: env.src_rgb[1], 0x8582: env.src_rgb[2], 0x8588: env.src_alpha[0], 0x8589: env.src_alpha[1],
        0x858A: env.src_alpha[2], 0x8590: env.operand_rgb[0], 0x8591: env.operand_rgb[1], 0x8592: env.operand_rgb[2],
        0x8598: env.operand_alpha[0], 0x8599: env.operand_alpha[1], 0x859A: env.operand_alpha[2] }[pname];
    if(value === undefined) return fail(c, INVALID_ENUM);
    // (enum values as themselves, also in the fixed form; the scales as numbers)
    const scale = pname === 0x8573 || pname === 0x0D1C;
    put_values(out, [value], as === "x" && !scale ? "i" : as, false);
    return undefined;
}

function get_clip_plane(s, c, plane, out, as, query, fail)
{
    query(s);
    const p = c.ff.clip_planes[plane - 0x3000];
    if(!p) return fail(c, INVALID_ENUM);
    put_values(out, p, as, false);
    return undefined;
}

/**
 * GLES 1.1's glGet values, beyond the shared ones: [values, kind] ("f"
 * float, "n" a color or normal, "i" integer, "b" boolean), or null
 * @param {!Object} c
 * @param {number} pname
 * @return {?Array}
 */
export function gles1_state_value(c, pname)
{
    const ff = c.ff;
    const unit = c.active_texture;
    const tex = ff.arrays.texcoord[ff.client_active_texture];
    switch(pname)
    {
        case 0x0BA0: return [[ff.matrix_mode], "i"];
        case 0x0BA6: return [ff.stacks[0x1700].at(-1), "f"];
        case 0x0BA7: return [ff.stacks[0x1701].at(-1), "f"];
        case 0x0BA8: return [ff.stacks[0x1702][unit].at(-1), "f"];
        case 0x0BA3: return [[ff.stacks[0x1700].length], "i"];
        case 0x0BA4: return [[ff.stacks[0x1701].length], "i"];
        case 0x0BA5: return [[ff.stacks[0x1702][unit].length], "i"];
        case 0x0B00: return [ff.color, "n"];
        case 0x0B02: return [ff.normal, "n"];
        case 0x0B03: return [ff.texcoord[unit], "f"];
        case 0x0B11: return [[ff.point.size], "f"];
        case 0x8126: return [[ff.point.min], "f"];
        case 0x8127: return [[ff.point.max], "f"];
        case 0x8128: return [[ff.point.fade], "f"];
        case 0x8129: return [ff.point.attenuation, "f"];
        case 0x0B54: return [[ff.shade_model], "i"];
        case 0x0B53: return [ff.light_model.ambient, "n"];
        case 0x0B52: return [[ff.light_model.two_side], "b"];
        case 0x0B65: return [[ff.fog.mode], "i"];
        case 0x0B62: return [[ff.fog.density], "f"];
        case 0x0B63: return [[ff.fog.start], "f"];
        case 0x0B64: return [[ff.fog.end], "f"];
        case 0x0B66: return [ff.fog.color, "n"];
        case 0x0BC1: return [[ff.alpha_func], "i"];
        case 0x0BC2: return [[ff.alpha_ref], "n"];
        case 0x0BF0: return [[ff.logic_op], "i"];
        case 0x84E1: return [[0x84C0 + ff.client_active_texture], "i"];
        case 0x807A: return [[ff.arrays.vertex.size], "i"];
        case 0x807B: return [[ff.arrays.vertex.type], "i"];
        case 0x807C: return [[ff.arrays.vertex.stride], "i"];
        case 0x807E: return [[ff.arrays.normal.type], "i"];
        case 0x807F: return [[ff.arrays.normal.stride], "i"];
        case 0x8081: return [[ff.arrays.color.size], "i"];
        case 0x8082: return [[ff.arrays.color.type], "i"];
        case 0x8083: return [[ff.arrays.color.stride], "i"];
        case 0x8088: return [[tex.size], "i"];
        case 0x8089: return [[tex.type], "i"];
        case 0x808A: return [[tex.stride], "i"];
        case 0x898A: return [[ff.arrays.point_size.type], "i"];
        case 0x898B: return [[ff.arrays.point_size.stride], "i"];
        case 0x8896: return [[ff.arrays.vertex.buffer], "i"];
        case 0x8897: return [[ff.arrays.normal.buffer], "i"];
        case 0x8898: return [[ff.arrays.color.buffer], "i"];
        case 0x889A: return [[tex.buffer], "i"];
        case 0x8B9F: return [[ff.arrays.point_size.buffer], "i"];
        case 0x8074: return [[+ff.arrays.vertex.enabled], "b"];
        case 0x8075: return [[+ff.arrays.normal.enabled], "b"];
        case 0x8076: return [[+ff.arrays.color.enabled], "b"];
        case 0x8078: return [[+tex.enabled], "b"];
        case 0x8B9C: return [[+ff.arrays.point_size.enabled], "b"];
        case 0x0DE1: return [[+ff.texture_enabled[unit][0x0DE1]], "b"];
        case 0x8D65: return [[+ff.texture_enabled[unit][0x8D65]], "b"];
    }
    return null;
}
                                                                                                                                                                                                                                                                                                                                      source/v64/src/gles/gles31_state.js                                                                 0000644 0000000 0000000 00000213006 00000000000 014243  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.1's state in the shadow state (docs/gles3-plan.md L5), written
// from the GLES 3.1 specification: what a context of version 31 or 32 has
// beyond GLES 3.0's (gles3_state.js), the commands GLES 3.1 adds, and its
// forms of 3.0's whose rules it changed. Its handlers come before 3.0's for
// those contexts (gles_shadow.js).
//
// - Compute: glDispatchCompute(Indirect) of the current program (or the
//   bound pipeline's compute program); the buffers bound for storage and
//   atomic counters are the GPU's then ("gpu_newer": the CPU side asks the
//   page for their bytes when mapped, as transform feedback's).
// - Shader storage and atomic counter buffers (indexed bindings), image
//   units, memory barriers.
// - Vertex attribute bindings (glBindVertexBuffer and the formats): each
//   vertex array has binding points; an attribute's buffer, offset, stride
//   and divisor (what GLES 3.0's handlers and the executor read) follow its
//   binding point's.
// - Separable programs and program pipelines, glProgramUniform*, the
//   program interface queries.
// - Multisampled 2D textures, the sample mask, framebuffers without
//   attachments (their default size), glGetTexLevelParameter*.
// - Indirect draws (the AEMU forms: the parameters with the command, or
//   in the draw indirect buffer), robustness's reset status and sized reads.

import { GL_STATE } from "./gles_caps.js";
import { GL3, LIMITS3, MAX_UNITS, SLOT } from "./gles3_state.js";
import { format_info, image_bytes3 } from "./gles_formats3.js";

export const GL31 = {
    SHADER_STORAGE_BUFFER: 0x90D2, ATOMIC_COUNTER_BUFFER: 0x92C0, DISPATCH_INDIRECT_BUFFER: 0x90EE, DRAW_INDIRECT_BUFFER: 0x8F3F,
    TEXTURE_2D_MULTISAMPLE: 0x9100, COMPUTE_SHADER: 0x91B9, PROGRAM_SEPARABLE: 0x8258, READ_ONLY: 0x88B8, WRITE_ONLY: 0x88B9,
    READ_WRITE: 0x88BA, ALL_BARRIER_BITS: 0xFFFFFFFF, VERTEX_SHADER_BIT: 1, FRAGMENT_SHADER_BIT: 2, COMPUTE_SHADER_BIT: 0x20,
};

/**
 * The limits GLES 3.1's contexts answer: the specification's minimums, within WebGPU's defaults (docs/gles3-plan.md "限制");
 * more binding points of storage blocks and atomic counters (dEQP-GLES31 binds counters at 1, six blocks of instance arrays)
 */
export const LIMITS31 = {
    MAX_COMPUTE_WORK_GROUP_COUNT: [65535, 65535, 65535], MAX_COMPUTE_WORK_GROUP_SIZE: [128, 128, 64], MAX_COMPUTE_WORK_GROUP_INVOCATIONS: 128,
    MAX_COMPUTE_SHARED_MEMORY_SIZE: 16384, MAX_COMPUTE_UNIFORM_BLOCKS: 12, MAX_COMPUTE_TEXTURE_IMAGE_UNITS: 16, MAX_COMPUTE_UNIFORM_COMPONENTS: 1024,
    MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS: 1, MAX_COMPUTE_ATOMIC_COUNTERS: 8, MAX_COMPUTE_IMAGE_UNIFORMS: 4, MAX_COMPUTE_SHADER_STORAGE_BLOCKS: 4,
    MAX_UNIFORM_LOCATIONS: 1024, MAX_FRAMEBUFFER_WIDTH: 4096, MAX_FRAMEBUFFER_HEIGHT: 4096, MAX_FRAMEBUFFER_SAMPLES: 4,
    MAX_VERTEX_ATOMIC_COUNTER_BUFFERS: 0, MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS: 0, MAX_COMBINED_ATOMIC_COUNTER_BUFFERS: 1,
    MAX_VERTEX_ATOMIC_COUNTERS: 0, MAX_FRAGMENT_ATOMIC_COUNTERS: 0, MAX_COMBINED_ATOMIC_COUNTERS: 8, MAX_ATOMIC_COUNTER_BUFFER_SIZE: 32,
    MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: 4, MAX_VERTEX_IMAGE_UNIFORMS: 0, MAX_FRAGMENT_IMAGE_UNIFORMS: 0, MAX_COMBINED_IMAGE_UNIFORMS: 4,
    MAX_IMAGE_UNITS: 4, MAX_VERTEX_SHADER_STORAGE_BLOCKS: 0, MAX_FRAGMENT_SHADER_STORAGE_BLOCKS: 0, MAX_COMBINED_SHADER_STORAGE_BLOCKS: 4,
    MAX_SHADER_STORAGE_BUFFER_BINDINGS: 8, MAX_SHADER_STORAGE_BLOCK_SIZE: 1 << 27, SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: 256,
    MAX_COMBINED_SHADER_OUTPUT_RESOURCES: 4, MAX_VERTEX_ATTRIB_RELATIVE_OFFSET: 2047, MAX_VERTEX_ATTRIB_BINDINGS: 16,
    MAX_VERTEX_ATTRIB_STRIDE: 2048, MAX_SAMPLE_MASK_WORDS: 1, MAX_COLOR_TEXTURE_SAMPLES: 4, MAX_DEPTH_TEXTURE_SAMPLES: 4,
    MAX_INTEGER_SAMPLES: 4, MIN_PROGRAM_TEXTURE_GATHER_OFFSET: -8, MAX_PROGRAM_TEXTURE_GATHER_OFFSET: 7,
};

/** The image formats an image unit takes (GLES 3.1 table 8.27) */
const IMAGE_FORMATS = new Set([0x8814, 0x881A, 0x822E, 0x8D70, 0x8D76, 0x8D7C, 0x8236, 0x8D82, 0x8D88, 0x8D8E, 0x8235, 0x8058, 0x8F97]);
/** The standard sample positions of 4 samples (glGetMultisamplefv; WebGPU's, Direct3D's) */
const SAMPLE_POSITIONS_4 = [[0.375, 0.125], [0.875, 0.375], [0.125, 0.625], [0.625, 0.875]];
const MAX_ATTRIBS = 16;

/** A GLES 3.1 context's state beyond GLES 3.0's (tables 20.2 to 20.53's additions) */
/** A GLES 3.1 context a snapshot brought back from when there were fewer binding points: as many as now */
export function pad_context31(c)
{
    while(c.storage_bindings.length < LIMITS31.MAX_SHADER_STORAGE_BUFFER_BINDINGS) c.storage_bindings.push({ buffer: 0, offset: 0, size: 0 });
    while(c.atomic_bindings.length < LIMITS31.MAX_ATOMIC_COUNTER_BUFFER_BINDINGS) c.atomic_bindings.push({ buffer: 0, offset: 0, size: 0 });
}

export function extend_context31(c)
{
    const bindings = n => Array.from({ length: n }, () => ({ buffer: 0, offset: 0, size: 0 }));
    c.storage_bindings = bindings(LIMITS31.MAX_SHADER_STORAGE_BUFFER_BINDINGS);
    c.atomic_bindings = bindings(LIMITS31.MAX_ATOMIC_COUNTER_BUFFER_BINDINGS);
    c.image_units = Array.from({ length: LIMITS31.MAX_IMAGE_UNITS }, () => ({ texture: 0, level: 0, layered: false, layer: 0, access: GL31.READ_ONLY,
        format: 0x8236 }));
    c.program_pipelines = new Map();
    c.program_pipeline = 0;
    c.reserved3.pipeline = new Set();
    c.next3.pipeline = 1;
    c.sample_mask = 0xFFFFFFFF;
}

/** A vertex array's binding points (GLES 3.1's model of 3.0's arrays), made at first use */
function vertex_bindings(c)
{
    const vao = c.vao ? c.vaos.get(c.vao) : c.default_vao;
    if(!vao.bindings)
    {
        // (each attribute's own binding point, as GLES 3.0's calls leave them: a tight one's stride its element's, 16 at first)
        vao.bindings = vao.attribs.map(a => ({ buffer: a.buffer, offset: a.offset, stride: a.stride || element_bytes(a), divisor: a.divisor }));
        vao.attribs.forEach((a, i) => { a.binding = i; a.relative_offset = 0; });
    }
    return vao.bindings;
}

/** The bytes of an attribute's element (its tight stride) */
function element_bytes(a)
{
    return a.type === 0x8368 || a.type === 0x8D9F ? 4 : a.size * ({ 0x1400: 1, 0x1401: 1, 0x1402: 2, 0x1403: 2, 0x140B: 2, 0x8D61: 2 }[a.type] || 4);
}

/** The attributes of a binding point: their buffer, offset, stride and divisor as GLES 3.0's handlers and the executor read them */
function follow_binding(c, index)
{
    const bindings = vertex_bindings(c);
    const b = bindings[index];
    c.attribs.forEach(a =>
    {
        if(a.binding !== index) return;
        a.buffer = b.buffer;
        a.offset = b.offset + (a.relative_offset || 0);
        // (an explicit stride of 0: every vertex the same; the executor reads 0 as tight, gpu-deviations.md)
        a.stride = b.stride;
        a.divisor = b.divisor;
    });
}

/** GLES 3.1's names of the program interfaces (glGetProgramInterfaceiv) */
const INTERFACES = { UNIFORM: 0x92E1, UNIFORM_BLOCK: 0x92E2, PROGRAM_INPUT: 0x92E3, PROGRAM_OUTPUT: 0x92E4, BUFFER_VARIABLE: 0x92E5,
    SHADER_STORAGE_BLOCK: 0x92E6, ATOMIC_COUNTER_BUFFER: 0x92C0, TRANSFORM_FEEDBACK_VARYING: 0x92F4 };
/** GL's matrix types: their columns and rows */
const MATRICES = { 0x8B5A: [2, 2], 0x8B5B: [3, 3], 0x8B5C: [4, 4], 0x8B65: [2, 3], 0x8B66: [2, 4], 0x8B67: [3, 2], 0x8B68: [3, 4], 0x8B69: [4, 2],
    0x8B6A: [4, 3] };
/** glslang's stage bits (STAGE: vertex 0, fragment 4, compute 5) of REFERENCED_BY_*_SHADER */
const REFERENCED = { 0x9306: 1 << 0, 0x930A: 1 << 4, 0x930B: 1 << 5 };

/**
 * A program's resources of an interface, as the program interface queries
 * list them: name, and each property's value (by its enum), from the
 * link's GL view and glslang's reflection
 * @return {?Array<{name: string, props: !Object<number, (number|!Array<number>)>}>} null for no such interface
 */
function resources(program, iface)
{
    const info = program.info;
    if(!info || !info.ok) return [];
    const reflection = info.reflection || {};
    const stages = s => Object.fromEntries(Object.entries(REFERENCED).map(([p, bit]) => [p, s & bit ? 1 : 0]));
    const array_name = (name, size) => size > 1 && !name.endsWith("]") ? name + "[0]" : name;
    switch(iface)
    {
        case INTERFACES.UNIFORM:
        {
            // (the offsets and strides of uniforms in buffers: blocks' members, atomic counters, theirs in their buffers)
            const counter_buffers = [...atomic_buffers(info).keys()];
            return info.uniforms.map(u =>
            {
                const atomic = u.opaque === "atomic", in_buffer = u.block_index >= 0 || atomic;
                return { name: array_name(u.name, u.size), props: Object.assign({
                    0x92FA: u.type, 0x92FB: u.size, 0x92FC: in_buffer ? u.offset : -1, 0x92FD: u.block_index,
                    0x92FE: in_buffer ? u.array_stride || 0 : -1, 0x92FF: in_buffer ? u.matrix_stride || 0 : -1,
                    0x9300: u.row_major ? 1 : 0, 0x9301: atomic ? counter_buffers.indexOf(u.binding) : -1, 0x930E: in_buffer ? -1 : u.location,
                }, stages(u.stages)) };
            });
        }
        case INTERFACES.UNIFORM_BLOCK:
            return (info.blocks || []).map((b, i) => ({ name: b.name, props: Object.assign({
                0x9302: program.block_bindings ? program.block_bindings[i] : b.binding, 0x9303: b.size, 0x9304: b.members.length, 0x9305: b.members,
            }, stages(b.stages)) }));
        case INTERFACES.SHADER_STORAGE_BLOCK:
        {
            // (an instance array's elements each have the array's variables, which glslang gives its first element)
            const blocks = reflection.bufferBlocks || [];
            const array_of = k => blocks[k] ? blocks[k].name.replace(/(?:\[\d+\])+$/, "") : null;
            return (info.storage_blocks || []).map((b, i) =>
            {
                const element = !!blocks[i] && blocks[i].name.endsWith("]");
                const members = (reflection.bufferVariables || []).map((v, k) => [v, k])
                    .filter(([v]) => v.index === i || element && array_of(v.index) === array_of(i)).map(([, k]) => k);
                const block = blocks[i] || {};
                return { name: b.name, props: Object.assign({ 0x9302: program.storage_bindings ? program.storage_bindings[i] : b.binding, 0x9303: b.size,
                    0x9304: members.length, 0x9305: members }, stages(block.stages || 0)) };
            });
        }
        case INTERFACES.BUFFER_VARIABLE:
            return (reflection.bufferVariables || []).map(v =>
            {
                // (a block member that is an array of scalars, vectors or matrices is the variable's own array, ARRAY_SIZE and
                // ARRAY_STRIDE; glslang gives it as the top level's too, dEQP's reference layout a top level of 1 and stride 0;
                // one of no declared size (glslang's top level 0) has an ARRAY_SIZE of 0, glslang's the elements used)
                const own_array = /^(?:\w+\.)?\w+\[0\]$/.test(array_name(v.name, v.size));
                const unsized = own_array && v.topLevelArraySize === 0;
                // (a top-level member that is no array (a struct): a top level of 1, stride 0; the name after an instance's block's)
                const block = (reflection.bufferBlocks || [])[v.index];
                const prefix = block ? block.name.replace(/\[\d+\]$/, "") + "." : "";
                const top_array = /^\w+\[/.test(prefix && v.name.startsWith(prefix) ? v.name.slice(prefix.length) : v.name);
                const top_level = own_array || !top_array;
                // (a matrix's stride, which glslang does not reflect: its columns' (rows' if row major) vectors in the block's
                // packing; shared and packed blocks are std430's, glsl_es_rewrite.js std_blocks)
                const matrix = MATRICES[v.type];
                const vector = matrix ? (v.rowMajor ? matrix[0] : matrix[1]) : 0;
                const matrix_stride = !matrix ? 0 : v.packing === "std140" || vector > 2 ? 16 : 8;
                return { name: array_name(v.name, v.size), props: Object.assign({
                    0x92FA: v.type, 0x92FB: unsized ? 0 : Math.max(0, v.size), 0x92FC: v.offset, 0x92FD: v.index, 0x92FE: v.arrayStride || 0,
                    0x92FF: v.matrixStride || matrix_stride, 0x9300: v.rowMajor && matrix ? 1 : 0,
                    0x930C: top_level || v.topLevelArraySize === undefined ? 1 : v.topLevelArraySize, 0x930D: top_level ? 0 : v.topLevelArrayStride || 0,
                }, stages(v.stages || 0)) };
            });
        case INTERFACES.PROGRAM_INPUT:
            return (reflection.inputs || []).filter(i => i.stages & (info.spirv && info.spirv.some(m => m.stage === "vertex") ? 1 : 1 << 4))
                .map(i => ({ name: array_name(i.name, i.size), props: Object.assign({ 0x92FA: i.type, 0x92FB: Math.max(1, i.size),
                    0x930E: i.builtIn ? -1 : (info.attributes.find(a => a.name === i.name) || { location: i.location }).location }, stages(i.stages || 0)) }));
        case INTERFACES.PROGRAM_OUTPUT:
        {
            // (the last stage's: a fragment shader's outputs have locations, assigned at the link; another stage's, their own or -1)
            const fragment = !info.spirv || info.spirv.some(m => m.stage === "fragment");
            return (reflection.outputs || []).map(o => ({ name: array_name(o.name, o.size), props: Object.assign({ 0x92FA: o.type,
                0x92FB: Math.max(1, o.size), 0x930E: o.builtIn ? -1 : fragment ? Math.max(0, o.location) : o.location }, stages(o.stages || 0)) }));
        }
        case INTERFACES.TRANSFORM_FEEDBACK_VARYING:
            return (info.tf_varyings || []).map(v => ({ name: v.name, props: { 0x92FA: v.type, 0x92FB: v.size } }));
        case INTERFACES.ATOMIC_COUNTER_BUFFER:
            return [...atomic_buffers(info)].map(([binding, b]) => ({ name: "", props: Object.assign({ 0x9302: binding, 0x9303: b.size,
                0x9304: b.members.length, 0x9305: b.members }, stages(b.stages)) }));
    }
    return null;
}

/**
 * A program's atomic counter buffers, in the order of their first counters
 * among the uniforms: each one's binding, counters (uniform indices),
 * stages and size (the declared counters', glsl_program.js's)
 * @return {!Map<number, {members: !Array<number>, size: number, stages: number}>}
 */
function atomic_buffers(info)
{
    const buffers = new Map();
    info.uniforms.forEach((u, k) =>
    {
        if(u.opaque !== "atomic") return;
        if(!buffers.has(u.binding)) buffers.set(u.binding, { members: [], size: (info.counter_buffers || {})[u.binding] || 0, stages: 0 });
        const b = buffers.get(u.binding);
        b.members.push(k);
        b.size = Math.max(b.size, Math.max(0, u.offset) + 4 * u.size);
        b.stages |= u.stages;
    });
    return buffers;
}

/**
 * The handlers of GLES 3.1's contexts: GLES 3.1's commands and its forms of
 * GLES 3.0's (those not here are 3.0's)
 * @param {!Object} h gles_shadow.js's helpers
 * @param {!Object} H3 gles3_state.js's handlers (their `helpers` too)
 * @return {!Object<string, function(!Object, !Object, !Array<*>)>}
 */
export function gles31_handlers(h, H3)
{
    const { fail, query, put, put_text, i32s, f32s, text_of, REFUSED, base, initial_values } = h;
    const { bound_buffer3, generated, new_buffer, current_tf, program_of, put64, get_attrib3, status_of } = H3.helpers;
    const GL = GL3;

    /** The program whose stage runs: the current program's, else the bound pipeline's for the stage */
    const stage_program = (c, stage_bit) =>
    {
        if(c.program) return c.group.objects.get(c.program) || null;
        const pipeline = c.program_pipelines.get(c.program_pipeline);
        const name = pipeline && pipeline.stages[stage_bit];
        return name ? c.group.objects.get(name) || null : null;
    };
    /** The buffers a program's run writes (storage, atomic counters): the GPU's newer copies */
    const written = (c, programs) =>
    {
        const info = programs.map(p => p && p.info).filter(Boolean);
        if(info.some(i => (i.storage_blocks || []).length)) for(const b of c.storage_bindings) mark(c, b.buffer);
        if(info.some(i => i.uniforms.some(u => u.opaque === "atomic"))) for(const b of c.atomic_bindings) mark(c, b.buffer);
    };
    const mark = (c, name) =>
    {
        const buffer = name && c.group.buffers.get(name);
        if(buffer) buffer.gpu_newer = true;
    };
    /** glUniform*'s handler run on another program (glProgramUniform*, a pipeline's active program) */
    const on_program = (c, name, run) =>
    {
        const saved = c.program;
        c.program = name;
        try
        {
            return run();
        }
        finally
        {
            c.program = saved;
        }
    };
    /** A draw of GLES 3.1: 3.0's checks, then what it writes */
    const draw31 = handler => (shadow, c, args) =>
    {
        if(pipeline_refused(c)) return fail(c, GL.INVALID_OPERATION);
        const r = handler(shadow, c, args);
        if(r !== REFUSED) written(c, [stage_program(c, GL31.VERTEX_SHADER_BIT), stage_program(c, GL31.FRAGMENT_SHADER_BIT)]);
        return r;
    };
    /** An indirect draw's checks (GLES 3.1 10.5): a vertex array object, its parameters from the command or the bound buffer */
    const indirect = (shadow, c, mode, type, data, offset, elements) =>
    {
        if(![0, 1, 2, 3, 4, 5, 6].includes(mode) || elements && ![0x1401, 0x1403, 0x1405].includes(type)) return fail(c, GL.INVALID_ENUM);
        if(!c.vao) return fail(c, GL.INVALID_OPERATION);
        if(elements && !c.element_array_buffer) return fail(c, GL.INVALID_OPERATION);
        if(current_tf(c).active && !current_tf(c).paused || pipeline_refused(c)) return fail(c, GL.INVALID_OPERATION);
        if(offset !== undefined)
        {
            const buffer = c.group.buffers.get(c.buffers.draw_indirect);
            if(!buffer) return fail(c, GL.INVALID_OPERATION);
            if(offset % 4) return fail(c, GL.INVALID_VALUE);
            if(offset + (elements ? 20 : 16) > buffer.size || buffer.mapped) return fail(c, GL.INVALID_OPERATION);
        }
        if(!H3.helpers.complete(c, false)) return REFUSED;
        written(c, [stage_program(c, GL31.VERTEX_SHADER_BIT), stage_program(c, GL31.FRAGMENT_SHADER_BIT)]);
        void data;
        return undefined;
    };
    /** glGetIntegeri_v / glGetInteger64i_v / glGetBooleani_v of GLES 3.1's indexed state, else 3.0's */
    const indexed31 = (shadow, c, [target, index, data], as) =>
    {
        query(shadow);
        const list = (bindings, field) =>
        {
            if(index >= bindings.length) { fail(c, GL.INVALID_VALUE); return null; }
            return [bindings[index][field]];
        };
        let value;
        switch(target)
        {
            case 0x90D3: value = list(c.storage_bindings, "buffer"); break;
            case 0x90D4: value = list(c.storage_bindings, "offset"); break;
            case 0x90D5: value = list(c.storage_bindings, "size"); break;
            case 0x92C1: value = list(c.atomic_bindings, "buffer"); break;
            case 0x92C2: value = list(c.atomic_bindings, "offset"); break;
            case 0x92C3: value = list(c.atomic_bindings, "size"); break;
            case 0x8F3A: value = list(c.image_units, "texture"); break;
            case 0x8F3B: value = list(c.image_units, "level"); break;
            case 0x8F3C: value = list(c.image_units, "layered"); if(value) value = [value[0] ? 1 : 0]; break;
            case 0x8F3D: value = list(c.image_units, "layer"); break;
            case 0x8F3E: value = list(c.image_units, "access"); break;
            case 0x906E: value = list(c.image_units, "format"); break;
            case 0x8F4F: value = list(vertex_bindings(c), "buffer"); break;
            case 0x82D7: value = list(vertex_bindings(c), "offset"); break;
            case 0x82D8: value = list(vertex_bindings(c), "stride"); break;
            case 0x82D6: value = list(vertex_bindings(c), "divisor"); break;
            case 0x91BE: value = index < 3 ? [LIMITS31.MAX_COMPUTE_WORK_GROUP_COUNT[index]] : (fail(c, GL.INVALID_VALUE), null); break;
            case 0x91BF: value = index < 3 ? [LIMITS31.MAX_COMPUTE_WORK_GROUP_SIZE[index]] : (fail(c, GL.INVALID_VALUE), null); break;
            case 0x8E52: value = index < 1 ? [c.sample_mask | 0] : (fail(c, GL.INVALID_VALUE), null); break;
            default:
                H3[as === "64" ? "glGetInteger64i_v" : as === "b" ? "glGetBooleani_v" : "glGetIntegeri_v"](shadow, c, [target, index, data]);
                return;
        }
        if(!value) return;
        if(as === "64") put64(data, value);
        else if(as === "b") put(data, value.map(v => v ? 1 : 0), "b", "b");
        else put(data, value, "i", "i");
    };
    /** The capabilities GLES 3.1 and 3.2 add */
    const own_cap = (c, cap) => cap === 0x8E51 || c.version >= 32 && (cap === 0x8C36 || cap === 0x92E0 || cap === 0x8242);
    /** What a 3.1 helper answers for what is 3.0's */
    const NOT_HERE = Symbol("GLES 3.0's");
    /** glBindBufferRange/Base of GLES 3.1's indexed targets (storage, atomic counters), else NOT_HERE */
    const bind_indexed31 = (shadow, c, target, index, name, offset, size, range) =>
    {
        const storage = target === GL31.SHADER_STORAGE_BUFFER;
        if(!storage && target !== GL31.ATOMIC_COUNTER_BUFFER) return NOT_HERE;
        const list = storage ? c.storage_bindings : c.atomic_bindings;
        if(index >= list.length) return fail(c, GL.INVALID_VALUE);
        if(range && name && (size <= 0 || offset < 0)) return fail(c, GL.INVALID_VALUE);
        if(range && name && (storage ? offset % LIMITS31.SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT : offset % 4)) return fail(c, GL.INVALID_VALUE);
        // (an unused name makes a buffer, as glBindBufferBase's other targets do; glBindVertexBuffer's must be generated)
        if(name && !c.group.buffers.has(name)) c.group.buffers.set(name, new_buffer());
        list[index] = { buffer: name, offset: range ? offset : 0, size: range ? size : 0 };
        c.buffers[storage ? "shader_storage" : "atomic_counter"] = name;
        return undefined;
    };
    /** glProgramUniform*: glUniform*'s handler on that program */
    const program_uniform = uniform => (shadow, c, [p, ...args]) =>
    {
        const program = program_of(c, p);
        if(!program) return REFUSED;
        return on_program(c, p, () => H3[uniform](shadow, c, args));
    };
    /** glUniform*: with no current program, the bound pipeline's active program's */
    const uniform31 = uniform => (shadow, c, args) =>
    {
        if(c.program || !c.program_pipeline) return H3[uniform](shadow, c, args);
        const pipeline = c.program_pipelines.get(c.program_pipeline);
        return on_program(c, pipeline ? pipeline.active : 0, () => H3[uniform](shadow, c, args));
    };
    /** A program pipeline, made when first bound (glGenProgramPipelines' names) */
    const pipeline_of = (shadow, c, name, make) =>
    {
        let pipeline = c.program_pipelines.get(name);
        if(!pipeline && make && name && generated(shadow, c.reserved3.pipeline, name))
        {
            c.program_pipelines.set(name, pipeline = { stages: {}, active: 0, log: "", valid: false });
        }
        return pipeline || null;
    };
    /**
     * What makes a pipeline invalid by glValidateProgramPipeline's rules
     * (GLES 3.1 7.4.1, 7.4.2): stages of separable, linked programs, vertex
     * with fragment, and their interfaces matching: each fragment shader
     * input a vertex shader output and each output an input, by location
     * where it has one, else by name, a location on both or neither, of one
     * type, size and interpolation (the programs' reflections; one of a snapshot from
     * before they had the vertex program's outputs is not checked)
     * @return {string} "" for none
     */
    const pipeline_problem = (c, pipeline) =>
    {
        const programs = Object.entries(pipeline.stages).filter(([, p]) => p).map(([bit, p]) => [+bit, c.group.objects.get(p)]);
        const problem = !programs.length ? "no program" :
            programs.some(([, p]) => !p || !p.info || !p.info.ok) ? "a program is not linked" :
            programs.some(([, p]) => !p.separable) ? "a program is not separable" :
            !!pipeline.stages[GL31.VERTEX_SHADER_BIT] !== !!pipeline.stages[GL31.FRAGMENT_SHADER_BIT] && !pipeline.stages[GL31.COMPUTE_SHADER_BIT] ?
                "a vertex shader without a fragment shader, or the other way" : "";
        const vertex = pipeline.stages[GL31.VERTEX_SHADER_BIT], fragment = pipeline.stages[GL31.FRAGMENT_SHADER_BIT];
        if(problem || !vertex || !fragment || vertex === fragment) return problem;
        const all_outputs = (c.group.objects.get(vertex).info.reflection || {}).outputs || [];
        if(!all_outputs.length) return "";
        const outputs = all_outputs.filter(o => !o.builtIn);
        const inputs = ((c.group.objects.get(fragment).info.reflection || {}).inputs || []).filter(x => !x.builtIn);
        // (by location where there is one, by name between two without)
        const match = (x, list) => x.location >= 0 ? list.find(y => y.location === x.location) : list.find(y => y.name === x.name && !(y.location >= 0));
        for(const i of inputs)
        {
            const o = match(i, outputs);
            if(!o) return "the fragment shader's input " + i.name + " is no output of the vertex shader";
            if(o.location >= 0 !== i.location >= 0) return "the fragment shader's input " + i.name + " has a location, the output not, or the other way";
            if(o.type !== i.type || o.size !== i.size || !!o.flat !== !!i.flat) return "the fragment shader's input " + i.name + " and its output differ";
        }
        // (GLES 3.1's separable interfaces match exactly: an output no input reads too)
        const unread = outputs.find(o => !match(o, inputs));
        return unread ? "the vertex shader's output " + unread.name + " is no input of the fragment shader" : "";
    };
    const validate = (c, pipeline) =>
    {
        const problem = pipeline_problem(c, pipeline);
        pipeline.valid = !problem;
        pipeline.log = problem;
        return !problem;
    };
    /** A draw's pipeline, when there is no current program: INVALID_OPERATION if it is not valid (GLES 3.1 11.1.3.11) */
    const pipeline_refused = c =>
    {
        const pipeline = !c.program && c.program_pipeline && c.program_pipelines.get(c.program_pipeline);
        return !!pipeline && !!pipeline_problem(c, pipeline);
    };

    const H = {
        // (GLES 3.1's capability: the sample mask; GLES 3.2's: sample shading, KHR_debug's output)
        "glEnable": (shadow, c, [cap]) => own_cap(c, cap) ? void c.enabled.add(cap) : H3["glEnable"](shadow, c, [cap]),
        "glDisable": (shadow, c, [cap]) => own_cap(c, cap) ? void c.enabled.delete(cap) : H3["glDisable"](shadow, c, [cap]),
        "glIsEnabled": (shadow, c, [cap]) => { if(!own_cap(c, cap)) return H3["glIsEnabled"](shadow, c, [cap]); query(shadow); return c.enabled.has(cap) ? 1 : 0; },
        "glCreateShader": (shadow, c, [type]) =>
        {
            // (GLES 3.2's geometry and tessellation shaders too)
            const own = type === GL31.COMPUTE_SHADER || c.version >= 32 && STAGES32.includes(type);
            if(!own) return base["glCreateShader"](shadow, c, [type]);
            const name = shadow.given_name || c.group.fresh("object", c.group.objects);
            c.group.objects.set(name, { kind: "shader", type, source: null, compiled: null, compiled_source: null, deleted: false, attached: 0 });
            return name;
        },
        "glProgramParameteri": (shadow, c, [p, pname, value]) =>
        {
            if(pname !== GL31.PROGRAM_SEPARABLE) return H3["glProgramParameteri"](shadow, c, [p, pname, value]);
            const program = program_of(c, p);
            if(!program) return REFUSED;
            if(value !== 0 && value !== 1) return fail(c, GL.INVALID_VALUE);
            program.separable = !!value;
            return undefined;
        },
        "glGetProgramiv": (shadow, c, [p, pname, params]) =>
        {
            // (GLES 3.1's: PROGRAM_SEPARABLE, ACTIVE_ATOMIC_COUNTER_BUFFERS, COMPUTE_WORK_GROUP_SIZE (a program linked with no compute stage: INVALID_OPERATION);
            // GLES 3.2's geometry layout (none linked: INVALID_OPERATION))
            const geometry = c.version >= 32 && GEOMETRY_QUERIES.has(pname), tessellation = c.version >= 32 && TESSELLATION_QUERIES.has(pname);
            if(![GL31.PROGRAM_SEPARABLE, 0x92D9, 0x8267].includes(pname) && !geometry && !tessellation) return H3["glGetProgramiv"](shadow, c, [p, pname, params]);
            query(shadow);
            const program = program_of(c, p);
            if(!program) return undefined;
            const info = program.info && program.info.ok ? program.info : null;
            if(geometry)
            {
                if(!info || !info.geometry) return void fail(c, GL.INVALID_OPERATION);
                put(params, [info.geometry[GEOMETRY_QUERIES.get(pname)]], "i", "i");
            }
            else if(tessellation)
            {
                // (the control shader's output vertices of a program with one, the rest of a program with an evaluation shader)
                const t = info && info.tessellation;
                if(!t || !(pname === 0x8E75 ? t.control : t.evaluation)) return void fail(c, GL.INVALID_OPERATION);
                put(params, [t[TESSELLATION_QUERIES.get(pname)]], "i", "i");
            }
            else if(pname === GL31.PROGRAM_SEPARABLE) put(params, [program.separable ? 1 : 0], "i", "i");
            else if(pname === 0x92D9) put(params, [info ? new Set(info.uniforms.filter(u => u.opaque === "atomic").map(u => u.binding)).size : 0], "i", "i");
            else if(!info || !(info.local_size && info.local_size.some(Boolean))) fail(c, GL.INVALID_OPERATION);
            else put(params, info.local_size.slice(0, 3), "i", "i");
            return undefined;
        },
        "glCreateShaderProgramvAEMU": (shadow, c, [type, count, packed]) =>
        {
            // (glCreateShaderProgramv, GLES 3.1 7.3: the strings compiled, a separable program linked of the shader, which
            // goes; the program's name the answer, the page's (given_name) the same; the page links with the batch's PROGRAM_LINK)
            if(type !== 0x8B31 && type !== 0x8B30 && type !== GL31.COMPUTE_SHADER) { fail(c, GL.INVALID_ENUM); return 0; }
            if(count < 0) { fail(c, GL.INVALID_VALUE); return 0; }
            const name = shadow.given_name || c.group.fresh("object", c.group.objects);
            const source = text_of(packed);
            const program = { kind: "program", shaders: new Set(), bindings: new Map(), info: null, linked_once: true, validated: 0, deleted: false,
                values: new Map(), separable: true };
            c.group.objects.set(name, program);
            const compiled = shadow.compile(source, type, c.glslang);
            if(shadow.pending_links && shadow.pending_links.has(name))
            {
                program.provided = shadow.pending_links.get(name);
                shadow.pending_links.delete(name);
            }
            program.info = compiled.ok ? shadow.link(program, [{ type, compiled, compiled_source: source }]) :
                { ok: false, log: compiled.log, attributes: [], uniforms: [], locations: new Map(), by_location: [], reflection: null };
            program.link = { vs: null, fs: null, bindings: [], glslang: true, shaders: [[type, source]], separable: true, tf: null };
            program.keep_info = !shadow.glslang;
            program.values = initial_values(program.info);
            return name;
        },

        // ---- buffers
        "glBindBufferRange": (shadow, c, args) =>
        {
            const r = bind_indexed31(shadow, c, args[0], args[1], args[2], args[3], args[4], true);
            return r === NOT_HERE ? H3["glBindBufferRange"](shadow, c, args) : r;
        },
        "glBindBufferBase": (shadow, c, args) =>
        {
            const r = bind_indexed31(shadow, c, args[0], args[1], args[2], 0, 0, false);
            return r === NOT_HERE ? H3["glBindBufferBase"](shadow, c, args) : r;
        },
        "glGetIntegeri_v": (shadow, c, args) => indexed31(shadow, c, args, "i"),
        "glGetInteger64i_v": (shadow, c, args) => indexed31(shadow, c, args, "64"),
        "glGetBooleani_v": (shadow, c, args) => indexed31(shadow, c, args, "b"),
        "glMemoryBarrier": (shadow, c, [barriers]) =>
        {
            if(barriers !== GL31.ALL_BARRIER_BITS && barriers & ~0x3FFF) return fail(c, GL.INVALID_VALUE);
            return undefined;
        },
        "glMemoryBarrierByRegion": (shadow, c, [barriers]) =>
        {
            // (the barriers a fragment shader's region may have: GLES 3.1 7.11.2)
            if(barriers !== GL31.ALL_BARRIER_BITS && barriers & ~(0x4 | 0x8 | 0x20 | 0x400 | 0x1000 | 0x2000)) return fail(c, GL.INVALID_VALUE);
            return undefined;
        },

        // ---- compute
        "glDispatchCompute": (shadow, c, [x, y, z]) =>
        {
            const program = stage_program(c, GL31.COMPUTE_SHADER_BIT);
            if(!program || !program.info || !program.info.ok || !(program.info.spirv || []).some(m => m.stage === "compute") &&
                !(program.info.local_size && program.info.local_size.some(Boolean)))
            {
                return fail(c, GL.INVALID_OPERATION);
            }
            const max = LIMITS31.MAX_COMPUTE_WORK_GROUP_COUNT;
            if(x > max[0] || y > max[1] || z > max[2]) return fail(c, GL.INVALID_VALUE);
            written(c, [program]);
            return undefined;
        },
        "glDispatchComputeIndirect": (shadow, c, [offset]) =>
        {
            const program = stage_program(c, GL31.COMPUTE_SHADER_BIT);
            if(!program || !program.info || !program.info.ok) return fail(c, GL.INVALID_OPERATION);
            if(offset < 0 || offset % 4) return fail(c, GL.INVALID_VALUE);
            const buffer = c.group.buffers.get(c.buffers.dispatch_indirect);
            if(!buffer || offset + 12 > buffer.size || buffer.mapped) return fail(c, GL.INVALID_OPERATION);
            written(c, [program]);
            return undefined;
        },

        // ---- draws (what they write), indirect draws
        "glDrawArrays": draw31(H3["glDrawArrays"]),
        "glDrawArraysInstanced": draw31(H3["glDrawArraysInstanced"]),
        "glDrawElementsOffset": draw31(H3["glDrawElementsOffset"]),
        "glDrawElementsData": draw31(H3["glDrawElementsData"]),
        "glDrawElementsInstancedOffsetAEMU": draw31(H3["glDrawElementsInstancedOffsetAEMU"]),
        "glDrawElementsInstancedDataAEMU": draw31(H3["glDrawElementsInstancedDataAEMU"]),
        "glDrawRangeElementsOffsetAEMU": draw31(H3["glDrawRangeElementsOffsetAEMU"]),
        "glDrawRangeElementsDataAEMU": draw31(H3["glDrawRangeElementsDataAEMU"]),
        "glDrawArraysIndirectDataAEMU": (shadow, c, [mode, data]) => indirect(shadow, c, mode, 0, data, undefined, false),
        "glDrawArraysIndirectOffsetAEMU": (shadow, c, [mode, offset]) => indirect(shadow, c, mode, 0, null, offset, false),
        "glDrawElementsIndirectDataAEMU": (shadow, c, [mode, type, data]) => indirect(shadow, c, mode, type, data, undefined, true),
        "glDrawElementsIndirectOffsetAEMU": (shadow, c, [mode, type, offset]) => indirect(shadow, c, mode, type, null, offset, true),

        // ---- vertex attribute bindings
        "glBindVertexBuffer": (shadow, c, [index, buffer, offset, stride]) =>
        {
            if(index >= LIMITS31.MAX_VERTEX_ATTRIB_BINDINGS || offset < 0 || stride < 0 || stride > LIMITS31.MAX_VERTEX_ATTRIB_STRIDE) {
                return fail(c, GL.INVALID_VALUE);
            }
            if(!c.vao) return fail(c, GL.INVALID_OPERATION);
            if(buffer && !c.group.buffers.has(buffer))
            {
                if(!generated(shadow, c.group.reserved.buffer, buffer)) return fail(c, GL.INVALID_OPERATION);
                c.group.buffers.set(buffer, new_buffer());
            }
            Object.assign(vertex_bindings(c)[index], { buffer, offset, stride });
            follow_binding(c, index);
            return undefined;
        },
        "glVertexAttribBinding": (shadow, c, [attrib, binding]) =>
        {
            if(attrib >= MAX_ATTRIBS || binding >= LIMITS31.MAX_VERTEX_ATTRIB_BINDINGS) return fail(c, GL.INVALID_VALUE);
            if(!c.vao) return fail(c, GL.INVALID_OPERATION);
            vertex_bindings(c);
            c.attribs[attrib].binding = binding;
            follow_binding(c, binding);
            return undefined;
        },
        "glVertexAttribFormat": (shadow, c, [attrib, size, type, normalized, relative]) =>
            attrib_format(shadow, c, attrib, size, type, normalized, relative, false),
        "glVertexAttribIFormat": (shadow, c, [attrib, size, type, relative]) => attrib_format(shadow, c, attrib, size, type, false, relative, true),
        "glVertexBindingDivisor": (shadow, c, [binding, divisor]) =>
        {
            if(binding >= LIMITS31.MAX_VERTEX_ATTRIB_BINDINGS) return fail(c, GL.INVALID_VALUE);
            if(!c.vao) return fail(c, GL.INVALID_OPERATION);
            vertex_bindings(c)[binding].divisor = divisor >>> 0;
            follow_binding(c, binding);
            return undefined;
        },
        // (GLES 3.0's calls in 3.1's model: the attribute's own binding point)
        "glVertexAttribPointerOffset": (shadow, c, args) => pointer31(shadow, c, args, "glVertexAttribPointerOffset"),
        "glVertexAttribPointerData": (shadow, c, args) => pointer31(shadow, c, args, "glVertexAttribPointerData"),
        "glVertexAttribIPointerOffsetAEMU": (shadow, c, args) => pointer31(shadow, c, args, "glVertexAttribIPointerOffsetAEMU"),
        "glVertexAttribIPointerDataAEMU": (shadow, c, args) => pointer31(shadow, c, args, "glVertexAttribIPointerDataAEMU"),
        "glVertexAttribDivisor": (shadow, c, [index, divisor]) =>
        {
            if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
            vertex_bindings(c);
            c.attribs[index].binding = index;
            vertex_bindings(c)[index].divisor = divisor >>> 0;
            follow_binding(c, index);
            return undefined;
        },
        "glGetVertexAttribiv": (shadow, c, args) => attrib_query31(shadow, c, args, "iv"),
        "glGetVertexAttribfv": (shadow, c, args) => attrib_query31(shadow, c, args, "f"),
        "glGetVertexAttribIiv": (shadow, c, args) => attrib_query31(shadow, c, args, "i"),
        "glGetVertexAttribIuiv": (shadow, c, args) => attrib_query31(shadow, c, args, "ui"),

        // ---- images
        "glBindImageTexture": (shadow, c, [unit, texture, level, layered, layer, access, format]) =>
        {
            if(unit >= LIMITS31.MAX_IMAGE_UNITS || level < 0 || layer < 0) return fail(c, GL.INVALID_VALUE);
            if(![GL31.READ_ONLY, GL31.WRITE_ONLY, GL31.READ_WRITE].includes(access) || !IMAGE_FORMATS.has(format)) return fail(c, GL.INVALID_VALUE);
            if(texture)
            {
                const t = c.group.textures.get(texture);
                if(!t) return fail(c, GL.INVALID_VALUE);
                if(!t.immutable) return fail(c, GL.INVALID_OPERATION);
            }
            c.image_units[unit] = { texture, level, layered: !!layered, layer, access, format };
            return undefined;
        },

        // ---- multisampled textures, the sample mask
        "glTexStorage2DMultisample": (shadow, c, [target, samples, internalformat, width, height, fixed]) =>
        {
            if(target !== GL31.TEXTURE_2D_MULTISAMPLE) return fail(c, GL.INVALID_ENUM);
            const name = c.textures[c.active_texture][SLOT.TEXTURE_2D_MULTISAMPLE];
            const texture = name ? c.group.textures.get(name) : null;
            if(!texture || texture.immutable) return fail(c, GL.INVALID_OPERATION);
            const info = format_info(internalformat);
            if(!info || !info.sized || !(info.renderable || info.kind === "depth" || info.kind === "depth_stencil")) return fail(c, GL.INVALID_ENUM);
            if(width < 1 || height < 1 || samples < 1) return fail(c, GL.INVALID_VALUE);
            if(width > LIMITS3.MAX_TEXTURE_SIZE || height > LIMITS3.MAX_TEXTURE_SIZE) return fail(c, GL.INVALID_VALUE);
            if(samples > LIMITS31.MAX_COLOR_TEXTURE_SAMPLES) return fail(c, GL.INVALID_OPERATION);
            texture.images.clear();
            texture.images.set(0, { width, height, depth: 1, format: info.format, type: info.types[0], internal: internalformat, compressed: false,
                samples: 4, fixed_locations: !!fixed });
            texture.immutable = true;
            texture.immutable_levels = 1;
            return undefined;
        },
        "glSampleMaski": (shadow, c, [index, mask]) =>
        {
            if(index >= LIMITS31.MAX_SAMPLE_MASK_WORDS) return fail(c, GL.INVALID_VALUE);
            c.sample_mask = mask >>> 0;
            return undefined;
        },
        "glGetMultisamplefv": (shadow, c, [pname, index, val]) =>
        {
            query(shadow);
            if(pname !== 0x8E50) { fail(c, GL.INVALID_ENUM); return; }
            if(index >= 4) { fail(c, GL.INVALID_VALUE); return; }
            put(val, SAMPLE_POSITIONS_4[index], "f", "f");
        },
        "glGetTexLevelParameteriv": (shadow, c, args) => tex_level_parameter(shadow, c, args, "i"),
        "glGetTexLevelParameterfv": (shadow, c, args) => tex_level_parameter(shadow, c, args, "f"),

        "glFramebufferTexture2D": (shadow, c, [target, attachment, textarget, name, level]) =>
        {
            // (GLES 3.1: a multisampled texture's level 0 too)
            if(textarget !== GL31.TEXTURE_2D_MULTISAMPLE) return H3["glFramebufferTexture2D"](shadow, c, [target, attachment, textarget, name, level]);
            const fb = target === GL.READ_FRAMEBUFFER ? c.read_framebuffer : target === GL.FRAMEBUFFER || target === GL.DRAW_FRAMEBUFFER ? c.framebuffer : -1;
            if(fb < 0) return fail(c, GL.INVALID_ENUM);
            const fbo = c.framebuffers.get(fb);
            if(!fbo) return fail(c, GL.INVALID_OPERATION);
            const texture = name ? c.group.textures.get(name) : null;
            if(name && (!texture || texture.target !== GL31.TEXTURE_2D_MULTISAMPLE)) return fail(c, GL.INVALID_OPERATION);
            if(name && level !== 0) return fail(c, GL.INVALID_VALUE);
            const points = attachment === 0x821A ? [GL.DEPTH_ATTACHMENT, GL.STENCIL_ATTACHMENT] : [attachment];
            for(const point of points)
            {
                if(name) fbo.attachments.set(point, { type: GL.TEXTURE, name, level: 0, face: 0, layer: 0 });
                else fbo.attachments.delete(point);
            }
            return undefined;
        },

        // ---- framebuffers without attachments
        "glFramebufferParameteri": (shadow, c, [target, pname, param]) =>
        {
            const name = target === GL.READ_FRAMEBUFFER ? c.read_framebuffer : target === GL.FRAMEBUFFER || target === GL.DRAW_FRAMEBUFFER ? c.framebuffer : -1;
            if(name < 0) return fail(c, GL.INVALID_ENUM);
            if(!name) return fail(c, GL.INVALID_OPERATION);
            const fbo = c.framebuffers.get(name);
            switch(pname)
            {
                case 0x9310: if(param < 0 || param > LIMITS31.MAX_FRAMEBUFFER_WIDTH) return fail(c, GL.INVALID_VALUE); fbo.default_width = param; break;
                case 0x9311: if(param < 0 || param > LIMITS31.MAX_FRAMEBUFFER_HEIGHT) return fail(c, GL.INVALID_VALUE); fbo.default_height = param; break;
                case 0x9313: if(param < 0 || param > LIMITS31.MAX_FRAMEBUFFER_SAMPLES) return fail(c, GL.INVALID_VALUE); fbo.default_samples = param; break;
                case 0x9314: fbo.default_fixed = !!param; break;
                default: return fail(c, GL.INVALID_ENUM);
            }
            return undefined;
        },
        "glGetFramebufferParameteriv": (shadow, c, [target, pname, params]) =>
        {
            query(shadow);
            const name = target === GL.READ_FRAMEBUFFER ? c.read_framebuffer : target === GL.FRAMEBUFFER || target === GL.DRAW_FRAMEBUFFER ? c.framebuffer : -1;
            if(name < 0) { fail(c, GL.INVALID_ENUM); return; }
            if(!name) { fail(c, GL.INVALID_OPERATION); return; }
            const fbo = c.framebuffers.get(name);
            const values = { 0x9310: fbo.default_width || 0, 0x9311: fbo.default_height || 0, 0x9313: fbo.default_samples || 0,
                0x9314: fbo.default_fixed ? 1 : 0 };
            if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
            put(params, [values[pname]], "i", "i");
        },

        // ---- program pipelines
        "glGenProgramPipelines": (shadow, c, [n, names]) =>
        {
            query(shadow);
            if(n < 0) { fail(c, GL.INVALID_VALUE); return; }
            for(let i = 0; i < n && 4 * i + 4 <= names.size; i++)
            {
                let name = c.next3.pipeline;
                while(c.program_pipelines.has(name) || c.reserved3.pipeline.has(name)) name++;
                c.next3.pipeline = name + 1;
                c.reserved3.pipeline.add(name);
                names.view.setUint32(4 * i, name, true);
            }
        },
        "glDeleteProgramPipelines": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                c.reserved3.pipeline.delete(name);
                c.program_pipelines.delete(name);
                if(c.program_pipeline === name) c.program_pipeline = 0;
            }
            return undefined;
        },
        "glIsProgramPipeline": (shadow, c, [name]) => { query(shadow); return c.program_pipelines.has(name) ? 1 : 0; },
        "glBindProgramPipeline": (shadow, c, [name]) =>
        {
            if(name && !pipeline_of(shadow, c, name, true)) return fail(c, GL.INVALID_OPERATION);
            if(current_tf(c).active && !current_tf(c).paused) return fail(c, GL.INVALID_OPERATION);
            c.program_pipeline = name;
            return undefined;
        },
        "glUseProgramStages": (shadow, c, [name, stages, p]) =>
        {
            const bits = [GL31.VERTEX_SHADER_BIT, GL31.FRAGMENT_SHADER_BIT, GL31.COMPUTE_SHADER_BIT, ...(c.version >= 32 ? STAGE_BITS32 : [])];
            if(stages !== GL31.ALL_BARRIER_BITS && stages & ~bits.reduce((m, b) => m | b, 0)) return fail(c, GL.INVALID_VALUE);
            const pipeline = pipeline_of(shadow, c, name, true);
            if(!pipeline) return fail(c, GL.INVALID_OPERATION);
            if(p)
            {
                const program = program_of(c, p);
                if(!program) return REFUSED;
                if(!program.separable || !program.info || !program.info.ok) return fail(c, GL.INVALID_OPERATION);
            }
            for(const bit of bits) if(stages & bit) pipeline.stages[bit] = p;
            return undefined;
        },
        "glActiveShaderProgram": (shadow, c, [name, p]) =>
        {
            const pipeline = pipeline_of(shadow, c, name, true);
            if(!pipeline) return fail(c, GL.INVALID_OPERATION);
            if(p && !program_of(c, p)) return REFUSED;
            if(p && !c.group.objects.get(p).info?.ok) return fail(c, GL.INVALID_OPERATION);
            pipeline.active = p;
            return undefined;
        },
        "glValidateProgramPipeline": (shadow, c, [name]) =>
        {
            const pipeline = pipeline_of(shadow, c, name, true);
            if(!pipeline) return fail(c, GL.INVALID_OPERATION);
            validate(c, pipeline);
            return undefined;
        },
        "glGetProgramPipelineiv": (shadow, c, [name, pname, params]) =>
        {
            query(shadow);
            const pipeline = pipeline_of(shadow, c, name, true);
            if(!pipeline) { fail(c, GL.INVALID_OPERATION); return; }
            const values = { 0x8259: pipeline.active, 0x8B31: pipeline.stages[GL31.VERTEX_SHADER_BIT] || 0, 0x8B30: pipeline.stages[GL31.FRAGMENT_SHADER_BIT] || 0,
                0x91B9: pipeline.stages[GL31.COMPUTE_SHADER_BIT] || 0, 0x8B84: pipeline.log ? pipeline.log.length + 1 : 0, 0x8B83: pipeline.valid ? 1 : 0 };
            // (GLES 3.2's stages: geometry, tessellation control and evaluation)
            if(c.version >= 32) STAGES32.forEach((type, i) => { values[type] = pipeline.stages[STAGE_BITS32[i]] || 0; });
            if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
            put(params, [values[pname]], "i", "i");
        },
        "glGetProgramPipelineInfoLog": (shadow, c, [name, size, length, log]) =>
        {
            query(shadow);
            const pipeline = pipeline_of(shadow, c, name, true);
            if(!pipeline) { fail(c, GL.INVALID_OPERATION); return; }
            const n = put_text(log, pipeline.log);
            if(length && length.size) length.view.setInt32(0, n, true);
            void size;
        },

        // ---- program interface queries
        "glGetProgramInterfaceiv": (shadow, c, [p, iface, pname, params]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const list = resources(program, iface);
            if(!list || ![0x92F5, 0x92F6, 0x92F7].includes(pname)) { fail(c, GL.INVALID_ENUM); return; }
            if(pname === 0x92F6 && iface === INTERFACES.ATOMIC_COUNTER_BUFFER) { fail(c, GL.INVALID_OPERATION); return; }
            if(pname === 0x92F7 && ![INTERFACES.UNIFORM_BLOCK, INTERFACES.SHADER_STORAGE_BLOCK, INTERFACES.ATOMIC_COUNTER_BUFFER].includes(iface)) {
                fail(c, GL.INVALID_OPERATION);
                return;
            }
            const value = pname === 0x92F5 ? list.length : pname === 0x92F6 ? list.reduce((n, r) => Math.max(n, r.name.length + 1), 0) :
                list.reduce((n, r) => Math.max(n, r.props[0x9304] || 0), 0);
            put(params, [value], "i", "i");
        },
        "glGetProgramResourceIndex": (shadow, c, [p, iface, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return 0xFFFFFFFF;
            const list = resources(program, iface);
            if(!list || iface === INTERFACES.ATOMIC_COUNTER_BUFFER) { fail(c, GL.INVALID_ENUM); return 0xFFFFFFFF; }
            const wanted = text_of(name);
            const index = list.findIndex(r => r.name === wanted || r.name === wanted + "[0]");
            return index < 0 ? 0xFFFFFFFF : index;
        },
        "glGetProgramResourceName": (shadow, c, [p, iface, index, size, length, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const list = resources(program, iface);
            if(!list || iface === INTERFACES.ATOMIC_COUNTER_BUFFER) { fail(c, GL.INVALID_ENUM); return; }
            if(index >= list.length) { fail(c, GL.INVALID_VALUE); return; }
            const n = put_text(name, list[index].name);
            if(length && length.size) length.view.setInt32(0, n, true);
            void size;
        },
        "glGetProgramResourceiv": (shadow, c, [p, iface, index, count, props, size, length, params]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const list = resources(program, iface);
            if(!list) { fail(c, GL.INVALID_ENUM); return; }
            if(index >= list.length || count <= 0 || size < 0) { fail(c, GL.INVALID_VALUE); return; }
            const r = list[index];
            const values = [];
            for(const prop of i32s(props).slice(0, count))
            {
                const v = prop === 0x92F9 ? (iface === INTERFACES.ATOMIC_COUNTER_BUFFER ? undefined : r.name.length + 1) : r.props[prop];
                if(v === undefined) { fail(c, GL.INVALID_OPERATION); return; }
                values.push(...Array.isArray(v) ? v : [v]);
            }
            put(params, values.slice(0, Math.max(0, size)), "i", "i");
            if(length && length.size) length.view.setInt32(0, Math.min(values.length, size), true);
        },
        "glGetProgramResourceLocation": (shadow, c, [p, iface, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return -1;
            if(![INTERFACES.UNIFORM, INTERFACES.PROGRAM_INPUT, INTERFACES.PROGRAM_OUTPUT].includes(iface)) { fail(c, GL.INVALID_ENUM); return -1; }
            if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return -1; }
            const wanted = text_of(name);
            if(iface === INTERFACES.UNIFORM)
            {
                const at = program.info.locations.get(wanted);
                return at === undefined ? -1 : at;
            }
            const r = resources(program, iface).find(x => x.name === wanted || x.name === wanted + "[0]");
            return r ? r.props[0x930E] : -1;
        },

        // ---- robustness (EXT_robustness): no context is ever lost
        "glGetGraphicsResetStatusEXT": shadow => { query(shadow); return 0; },
        "glReadnPixelsEXT": (shadow, c, [x, y, width, height, format, type, size]) =>
        {
            const r = H3["glReadPixels"](shadow, c, [x, y, width, height, format, type]);
            if(r === REFUSED) return r;
            // (the bytes glReadPixels would write by the pack state: more than bufSize is an error)
            const needed = image_bytes3(width, height, 1, format, type, { alignment: c.pack_alignment, row_length: c.pack.row_length, image_height: 0,
                skip_pixels: c.pack.skip_pixels, skip_rows: c.pack.skip_rows, skip_images: 0 });
            if(needed > size) return fail(c, GL.INVALID_OPERATION);
            return r;
        },
        "glGetnUniformfvEXT": (shadow, c, [p, location, size, params]) => H3["glGetUniformfv"](shadow, c, [p, location, params]),
        "glGetnUniformivEXT": (shadow, c, [p, location, size, params]) => H3["glGetUniformiv"](shadow, c, [p, location, params]),
    };

    /** glVertexAttribFormat / IFormat: an attribute's format, its offset in its binding point's vertex */
    function attrib_format(shadow, c, attrib, size, type, normalized, relative, integer)
    {
        if(attrib >= MAX_ATTRIBS || size < 1 || size > 4 || relative < 0 || relative > LIMITS31.MAX_VERTEX_ATTRIB_RELATIVE_OFFSET) {
            return fail(c, GL.INVALID_VALUE);
        }
        if(!c.vao) return fail(c, GL.INVALID_OPERATION);
        const types = integer ? [0x1400, 0x1401, 0x1402, 0x1403, 0x1404, 0x1405] :
            [0x1400, 0x1401, 0x1402, 0x1403, 0x1404, 0x1405, 0x1406, 0x140B, 0x140C, 0x8368, 0x8D9F];
        if(!types.includes(type)) return fail(c, GL.INVALID_ENUM);
        if((type === 0x8368 || type === 0x8D9F) && size !== 4) return fail(c, GL.INVALID_OPERATION);
        vertex_bindings(c);
        Object.assign(c.attribs[attrib], { size, type, normalized: !!normalized, integer, relative_offset: relative });
        follow_binding(c, c.attribs[attrib].binding);
        return undefined;
    }

    /** GLES 3.0's glVertexAttrib*Pointer in 3.1's model: binding point `index` holds the buffer, offset and stride */
    function pointer31(shadow, c, args, name)
    {
        const r = H3[name](shadow, c, args);
        if(r === REFUSED) return r;
        const index = args[0];
        const a = c.attribs[index];
        const bindings = vertex_bindings(c);
        const element = element_bytes(a);
        Object.assign(bindings[index], { buffer: a.buffer, offset: a.offset, stride: a.stride || element });
        a.binding = index;
        a.relative_offset = 0;
        // (the attribute reads its stride as GLES 3.0 gave it: 0 is tight)
        follow_binding(c, index);
        a.stride = a.stride === element && !args[name.includes("IPointer") ? 3 : 4] ? 0 : a.stride;
        return r;
    }

    /** glGetVertexAttrib* with GLES 3.1's VERTEX_ATTRIB_BINDING and _RELATIVE_OFFSET */
    function attrib_query31(shadow, c, [index, pname, params], as)
    {
        if(pname !== 0x82D4 && pname !== 0x82D5) return get_attrib3(shadow, c, index, pname, params, as);
        query(shadow);
        if(index >= MAX_ATTRIBS) { fail(c, GL.INVALID_VALUE); return undefined; }
        vertex_bindings(c);
        const a = c.attribs[index];
        put(params, [pname === 0x82D4 ? a.binding : a.relative_offset || 0], as === "f" ? "f" : "i", "i");
        return undefined;
    }

    /** glGetTexLevelParameter{i,f}v (GLES 3.1 8.10.3): a level's size, format and component sizes */
    function tex_level_parameter(shadow, c, [target, level, pname, params], as)
    {
        query(shadow);
        const face = target >= 0x8515 && target <= 0x851A ? target - 0x8515 : 0;
        const slot = target === GL.TEXTURE_2D ? SLOT.TEXTURE_2D : face || target === 0x8515 ? SLOT.TEXTURE_CUBE_MAP : target === GL.TEXTURE_3D ?
            SLOT.TEXTURE_3D : target === GL.TEXTURE_2D_ARRAY ? SLOT.TEXTURE_2D_ARRAY : target === GL31.TEXTURE_2D_MULTISAMPLE ? SLOT.TEXTURE_2D_MULTISAMPLE : -1;
        if(slot < 0) { fail(c, GL.INVALID_ENUM); return; }
        if(level < 0 || level > 31) { fail(c, GL.INVALID_VALUE); return; }
        const name = c.textures[c.active_texture][slot];
        const texture = name ? c.group.textures.get(name) : c.defaults && c.defaults.get(target);
        const image = texture && texture.images.get(face * 32 + level);
        const info = image && !image.compressed ? format_info(image.internal || image.format) : null;
        const bits = info ? info.bits : [0, 0, 0, 0, 0, 0];
        const kind = info ? info.kind : "";
        const type = k => !image ? 0 : bits[k] ? { unorm: 0x8C17, snorm: 0x8F9C, float: 0x1406, int: 0x1404, uint: 0x1405, depth: 0x8C17,
            depth_stencil: k === 5 ? 0x8C17 : 0x8C17 }[kind] || 0x8C17 : 0;
        const values = {
            0x1000: image ? image.width : 0, 0x1001: image ? image.height : 0, 0x8071: image ? image.depth || 1 : 0,
            0x1003: image ? image.internal || image.format : 0x1908, 0x805C: bits[0], 0x805D: bits[1], 0x805E: bits[2], 0x805F: bits[3],
            0x884A: bits[4], 0x88F1: bits[5], 0x8C3F: info && info.value === 0x8C3D ? 5 : 0, 0x8C10: type(0), 0x8C11: type(1), 0x8C12: type(2),
            0x8C13: type(3), 0x8C16: type(4), 0x9106: image && image.samples ? image.samples : 0, 0x9107: image ? (image.fixed_locations !== false ? 1 : 0) : 1,
            0x86A1: image && image.compressed ? 1 : 0, 0x86A0: image && image.compressed ? image.size || 0 : 0,
        };
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [values[pname]], as === "f" ? "f" : "i", "i");
    }

    // glUniform* and glProgramUniform*
    const uniforms = ["1f", "2f", "3f", "4f", "1i", "2i", "3i", "4i", "1ui", "2ui", "3ui", "4ui", "1fv", "2fv", "3fv", "4fv", "1iv", "2iv", "3iv", "4iv",
        "1uiv", "2uiv", "3uiv", "4uiv", "Matrix2fv", "Matrix3fv", "Matrix4fv", "Matrix2x3fv", "Matrix3x2fv", "Matrix2x4fv", "Matrix4x2fv",
        "Matrix3x4fv", "Matrix4x3fv"];
    for(const u of uniforms)
    {
        H["glProgramUniform" + u] = program_uniform("glUniform" + u);
        H["glUniform" + u] = uniform31("glUniform" + u);
    }
    void f32s;
    void status_of;
    void bound_buffer3;
    return H;
}

/** GLES 3.2's shader types: geometry, tessellation control, tessellation evaluation; their pipeline stage bits */
const STAGES32 = [0x8DD9, 0x8E88, 0x8E87];
const STAGE_BITS32 = [0x4, 0x8, 0x10];
/** glGetProgramiv's geometry layout: GEOMETRY_LINKED_VERTICES_OUT, _INPUT_TYPE, _OUTPUT_TYPE, GEOMETRY_SHADER_INVOCATIONS */
const GEOMETRY_QUERIES = new Map([[0x8916, "vertices"], [0x8917, "input"], [0x8918, "output"], [0x887F, "invocations"]]);
/** glGetProgramiv's tessellation layout: TESS_CONTROL_OUTPUT_VERTICES, TESS_GEN_MODE, _SPACING, _VERTEX_ORDER, _POINT_MODE */
const TESSELLATION_QUERIES = new Map([[0x8E75, "vertices"], [0x8E76, "mode"], [0x8E77, "spacing"], [0x8E78, "order"], [0x8E79, "point_mode"]]);

/**
 * GLES 3.2's state beyond 3.1's (tables 21.2 to 21.58): KHR_debug's initial
 * values and limits (its entry points are not on the guest's wire), the
 * geometry and tessellation stages' limits (the specification's minimums),
 * robustness, the bounding box, sample shading's
 */
const STATE32 = new Map([
    [0x821E, [0]], [0x9143, [1024]], [0x9144, [1]], [0x9145, [0]], [0x8243, [0]], [0x826C, [64]], [0x826D, [1]], [0x82E8, [256]],
    [0x92BE, [-1, -1, -1, 1, 1, 1, 1, 1]], [0x9381, [1, 1]], [0x9382, [1]], [0x8C37, [0]], [0x8256, [0x8261]], [0x90F3, [0]], [0x9317, [256]],
    [0x825E, [0x8E4E]], [0x8E5D, [4]], [0x8E5B, [-0.5]], [0x8E5C, [0.5]], [0x8E72, [3]],
    // geometry
    [0x8DDF, [1024]], [0x8A2C, [12]], [0x9123, [64]], [0x9124, [64]], [0x8DE0, [256]], [0x8DE1, [1024]], [0x8C29, [16]], [0x8E5A, [32]],
    [0x92CF, [0]], [0x92D5, [0]], [0x90CD, [0]], [0x90D7, [0]], [0x8A32, [1024 + 12 * 4096]],
    // tessellation
    [0x8E7D, [32]], [0x8E7E, [64]], [0x8E7F, [1024]], [0x8E80, [1024]], [0x8E81, [16]], [0x8E82, [16]], [0x8E83, [64]], [0x8E84, [120]],
    [0x8E85, [2048]], [0x8E86, [64]], [0x8E89, [12]], [0x8E8A, [12]], [0x886C, [64]], [0x886D, [64]], [0x92CD, [0]], [0x92CE, [0]],
    [0x92D3, [0]], [0x92D4, [0]], [0x90CB, [0]], [0x90CC, [0]], [0x90D8, [0]], [0x90D9, [0]], [0x8E1E, [1024 + 12 * 4096]], [0x8E1F, [1024 + 12 * 4096]],
    // texture buffers (no entry point reaches them: their limits are the minimums)
    [0x8C2B, [65536]], [0x919F, [256]], [0x8C2C, [0]], [0x8C2A, [0]],
]);
/**
 * The limits of glslang's built-in constants (gl_Max*) and of its checks,
 * by glslangValidator's names: what glGet answers (gles_caps.js's GL_STATE,
 * LIMITS3, LIMITS31, STATE32), GLSL ES 3.x's; GLSL ES 1.00's
 * gl_MaxDrawBuffers is 1 (GLES 2.0 has no EXT_draw_buffers here); a
 * GLES 2.0 context's are GLES 2.0's where GLES 3.x raised them
 * @param {number} version the shader's GLSL ES version
 * @param {boolean=} es2 a GLES 2.0 context's
 * @return {!Object<string, number>}
 */
export function glslang_limits(version, es2)
{
    if(es2) return version < 300 ? GLSLANG_LIMITS_ES2_100 : GLSLANG_LIMITS_ES2_3;
    return version < 300 ? GLSLANG_LIMITS_100 : GLSLANG_LIMITS_3;
}

const GLSLANG_LIMITS_3 = (() =>
{
    const L = LIMITS3, M = LIMITS31, one = pname => (GL_STATE.get(pname) || STATE32.get(pname))[0];
    return {
        "MaxVertexAttribs": one(0x8869), "MaxVertexUniformVectors": one(0x8DFB), "MaxVaryingVectors": one(0x8DFC),
        "MaxFragmentUniformVectors": L.MAX_FRAGMENT_UNIFORM_COMPONENTS / 4, "MaxCombinedTextureImageUnits": MAX_UNITS, "MaxVertexTextureImageUnits": one(0x8B4C),
        "MaxTextureImageUnits": one(0x8872), "MaxDrawBuffers": L.MAX_DRAW_BUFFERS,
        "MaxVertexOutputVectors": L.MAX_VERTEX_OUTPUT_COMPONENTS / 4, "MaxFragmentInputVectors": L.MAX_FRAGMENT_INPUT_COMPONENTS / 4,
        "MaxVertexOutputComponents": L.MAX_VERTEX_OUTPUT_COMPONENTS, "MaxFragmentInputComponents": L.MAX_FRAGMENT_INPUT_COMPONENTS,
        "MaxVertexUniformComponents": L.MAX_VERTEX_UNIFORM_COMPONENTS, "MaxFragmentUniformComponents": L.MAX_FRAGMENT_UNIFORM_COMPONENTS,
        "MaxVaryingComponents": L.MAX_VARYING_COMPONENTS, "MinProgramTexelOffset": L.MIN_PROGRAM_TEXEL_OFFSET,
        "MaxProgramTexelOffset": L.MAX_PROGRAM_TEXEL_OFFSET, "MaxSamples": L.MAX_SAMPLES,
        "MaxTransformFeedbackInterleavedComponents": L.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS,
        "MaxTransformFeedbackBuffers": L.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS,
        // GLES 3.1's
        "MaxComputeWorkGroupCountX": M.MAX_COMPUTE_WORK_GROUP_COUNT[0], "MaxComputeWorkGroupCountY": M.MAX_COMPUTE_WORK_GROUP_COUNT[1],
        "MaxComputeWorkGroupCountZ": M.MAX_COMPUTE_WORK_GROUP_COUNT[2], "MaxComputeWorkGroupSizeX": M.MAX_COMPUTE_WORK_GROUP_SIZE[0],
        "MaxComputeWorkGroupSizeY": M.MAX_COMPUTE_WORK_GROUP_SIZE[1], "MaxComputeWorkGroupSizeZ": M.MAX_COMPUTE_WORK_GROUP_SIZE[2],
        "MaxComputeUniformComponents": M.MAX_COMPUTE_UNIFORM_COMPONENTS, "MaxComputeTextureImageUnits": M.MAX_COMPUTE_TEXTURE_IMAGE_UNITS,
        "MaxComputeImageUniforms": M.MAX_COMPUTE_IMAGE_UNIFORMS, "MaxComputeAtomicCounters": M.MAX_COMPUTE_ATOMIC_COUNTERS,
        "MaxComputeAtomicCounterBuffers": M.MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS, "MaxVertexAtomicCounters": M.MAX_VERTEX_ATOMIC_COUNTERS,
        "MaxFragmentAtomicCounters": M.MAX_FRAGMENT_ATOMIC_COUNTERS, "MaxCombinedAtomicCounters": M.MAX_COMBINED_ATOMIC_COUNTERS,
        "MaxAtomicCounterBindings": M.MAX_ATOMIC_COUNTER_BUFFER_BINDINGS, "MaxVertexAtomicCounterBuffers": M.MAX_VERTEX_ATOMIC_COUNTER_BUFFERS,
        "MaxFragmentAtomicCounterBuffers": M.MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS, "MaxCombinedAtomicCounterBuffers": M.MAX_COMBINED_ATOMIC_COUNTER_BUFFERS,
        "MaxAtomicCounterBufferSize": M.MAX_ATOMIC_COUNTER_BUFFER_SIZE, "MaxImageUnits": M.MAX_IMAGE_UNITS,
        "MaxVertexImageUniforms": M.MAX_VERTEX_IMAGE_UNIFORMS, "MaxFragmentImageUniforms": M.MAX_FRAGMENT_IMAGE_UNIFORMS,
        "MaxCombinedImageUniforms": M.MAX_COMBINED_IMAGE_UNIFORMS, "MaxCombinedShaderOutputResources": M.MAX_COMBINED_SHADER_OUTPUT_RESOURCES,
        // GLES 3.2's (STATE32): geometry, tessellation
        "MaxGeometryUniformComponents": one(0x8DDF), "MaxGeometryInputComponents": one(0x9123), "MaxGeometryOutputComponents": one(0x9124),
        "MaxGeometryOutputVertices": one(0x8DE0), "MaxGeometryTotalOutputComponents": one(0x8DE1), "MaxGeometryTextureImageUnits": one(0x8C29),
        "MaxGeometryAtomicCounterBuffers": one(0x92CF), "MaxGeometryAtomicCounters": one(0x92D5), "MaxGeometryImageUniforms": one(0x90CD),
        "MaxPatchVertices": one(0x8E7D), "MaxTessGenLevel": one(0x8E7E), "MaxTessControlUniformComponents": one(0x8E7F),
        "MaxTessEvaluationUniformComponents": one(0x8E80), "MaxTessControlTextureImageUnits": one(0x8E81),
        "MaxTessEvaluationTextureImageUnits": one(0x8E82), "MaxTessControlOutputComponents": one(0x8E83), "MaxTessPatchComponents": one(0x8E84),
        "MaxTessControlTotalOutputComponents": one(0x8E85), "MaxTessEvaluationOutputComponents": one(0x8E86),
        "MaxTessControlInputComponents": one(0x886C), "MaxTessEvaluationInputComponents": one(0x886D),
        "MaxTessControlAtomicCounterBuffers": one(0x92CD), "MaxTessEvaluationAtomicCounterBuffers": one(0x92CE),
        "MaxTessControlAtomicCounters": one(0x92D3), "MaxTessEvaluationAtomicCounters": one(0x92D4),
        "MaxTessControlImageUniforms": one(0x90CB), "MaxTessEvaluationImageUniforms": one(0x90CC),
    };
})();
const GLSLANG_LIMITS_100 = Object.assign({}, GLSLANG_LIMITS_3, { "MaxDrawBuffers": 1 });
/** A GLES 2.0 context's (api 20: GLES 2.0's limits, GL_STATE's, where 3.x raised them) */
const ES2_LIMITS = { "MaxFragmentUniformVectors": GL_STATE.get(0x8DFD)[0], "MaxCombinedTextureImageUnits": GL_STATE.get(0x8B4D)[0] };
const GLSLANG_LIMITS_ES2_100 = Object.assign({}, GLSLANG_LIMITS_100, ES2_LIMITS);
const GLSLANG_LIMITS_ES2_3 = Object.assign({}, GLSLANG_LIMITS_3, ES2_LIMITS);

/** GLES 3.2's float state */
export const FLOAT_STATE32 = new Set([0x92BE, 0x9381, 0x9382, 0x8C37, 0x8E5B, 0x8E5C]);

/** GLES 3.1's state values (glGet*), null for one not GLES 3.1's (then GLES 3.0's) */
export function state_value31(shadow, c, pname)
{
    const L = LIMITS31;
    if(c.version >= 32 && STATE32.has(pname)) return STATE32.get(pname);
    if(c.version >= 32 && (pname === 0x92E0 || pname === 0x8242 || pname === 0x8C36)) return [c.enabled.has(pname) ? 1 : 0];
    switch(pname)
    {
        case 0x90DB: return [L.MAX_COMPUTE_SHADER_STORAGE_BLOCKS];
        case 0x91BB: return [L.MAX_COMPUTE_UNIFORM_BLOCKS];
        case 0x91BC: return [L.MAX_COMPUTE_TEXTURE_IMAGE_UNITS];
        case 0x91BD: return [L.MAX_COMPUTE_IMAGE_UNIFORMS];
        case 0x8262: return [L.MAX_COMPUTE_SHARED_MEMORY_SIZE];
        case 0x8263: return [L.MAX_COMPUTE_UNIFORM_COMPONENTS];
        case 0x8264: return [L.MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS];
        case 0x8265: return [L.MAX_COMPUTE_ATOMIC_COUNTERS];
        case 0x8266: return [L.MAX_COMPUTE_UNIFORM_COMPONENTS + L.MAX_COMPUTE_UNIFORM_BLOCKS * LIMITS3.MAX_UNIFORM_BLOCK_SIZE / 4];
        case 0x90EB: return [L.MAX_COMPUTE_WORK_GROUP_INVOCATIONS];
        case 0x826E: return [L.MAX_UNIFORM_LOCATIONS];
        case 0x9315: return [L.MAX_FRAMEBUFFER_WIDTH];
        case 0x9316: return [L.MAX_FRAMEBUFFER_HEIGHT];
        case 0x9318: return [L.MAX_FRAMEBUFFER_SAMPLES];
        case 0x92CC: return [L.MAX_VERTEX_ATOMIC_COUNTER_BUFFERS];
        case 0x92D0: return [L.MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS];
        case 0x92D1: return [L.MAX_COMBINED_ATOMIC_COUNTER_BUFFERS];
        case 0x92D2: return [L.MAX_VERTEX_ATOMIC_COUNTERS];
        case 0x92D6: return [L.MAX_FRAGMENT_ATOMIC_COUNTERS];
        case 0x92D7: return [L.MAX_COMBINED_ATOMIC_COUNTERS];
        case 0x92D8: return [L.MAX_ATOMIC_COUNTER_BUFFER_SIZE];
        case 0x92DC: return [L.MAX_ATOMIC_COUNTER_BUFFER_BINDINGS];
        case 0x90CA: return [L.MAX_VERTEX_IMAGE_UNIFORMS];
        case 0x90CE: return [L.MAX_FRAGMENT_IMAGE_UNIFORMS];
        case 0x90CF: return [L.MAX_COMBINED_IMAGE_UNIFORMS];
        case 0x8F38: return [L.MAX_IMAGE_UNITS];
        case 0x90D6: return [L.MAX_VERTEX_SHADER_STORAGE_BLOCKS];
        case 0x90DA: return [L.MAX_FRAGMENT_SHADER_STORAGE_BLOCKS];
        case 0x90DC: return [L.MAX_COMBINED_SHADER_STORAGE_BLOCKS];
        case 0x90DD: return [L.MAX_SHADER_STORAGE_BUFFER_BINDINGS];
        case 0x90DE: return [L.MAX_SHADER_STORAGE_BLOCK_SIZE];
        case 0x90DF: return [L.SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT];
        case 0x8F39: return [L.MAX_COMBINED_SHADER_OUTPUT_RESOURCES];
        case 0x82D9: return [L.MAX_VERTEX_ATTRIB_RELATIVE_OFFSET];
        case 0x82DA: return [L.MAX_VERTEX_ATTRIB_BINDINGS];
        case 0x82E5: return [L.MAX_VERTEX_ATTRIB_STRIDE];
        case 0x8E59: return [L.MAX_SAMPLE_MASK_WORDS];
        case 0x910E: return [L.MAX_COLOR_TEXTURE_SAMPLES];
        case 0x910F: return [L.MAX_DEPTH_TEXTURE_SAMPLES];
        case 0x9110: return [L.MAX_INTEGER_SAMPLES];
        case 0x8E5E: return [L.MIN_PROGRAM_TEXTURE_GATHER_OFFSET];
        case 0x8E5F: return [L.MAX_PROGRAM_TEXTURE_GATHER_OFFSET];
        case 0x90EF: return [c.buffers.dispatch_indirect];
        case 0x8F43: return [c.buffers.draw_indirect];
        case 0x90D3: return [c.buffers.shader_storage];
        case 0x92C1: return [c.buffers.atomic_counter];
        case 0x825A: return [c.program_pipeline];
        case 0x9104: return [c.textures[c.active_texture][SLOT.TEXTURE_2D_MULTISAMPLE]];
        case 0x900A: return c.version >= 32 ? [c.textures[c.active_texture][SLOT.TEXTURE_CUBE_MAP_ARRAY]] : null;
        case 0x8E51: return [c.enabled.has(0x8E51) ? 1 : 0];
    }
    return null;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/gles/gles3_state.js                                                                  0000644 0000000 0000000 00000401714 00000000000 014167  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.0's state in the shadow state (docs/gles3-plan.md L2), written
// from the GLES 3.0 specification: what a context of api 3 (GLES 3.0 to
// 3.2, Context.version) has beyond GLES 2.0's, the commands GLES 3.0 adds,
// and its forms of GLES 2.0's commands whose rules it changed. GLES 2.0's
// handlers (gles_shadow.js) stay as they are for 2.0 and 1.1 contexts.
//
// Objects: vertex arrays, transform feedbacks, queries and framebuffers
// belong to the context; samplers and syncs to the share group (GLES 3.0,
// appendix D). Buffers keep a copy of their bytes on the CPU side
// (`bytes`, the shadow's keep_bytes) for glMapBufferRange's answers;
// `gpu_newer` says the page wrote it since (transform feedback, copies,
// pack buffers), which the CPU side then asks the page for (L3).

import { COMPRESSED_FORMATS, COMPRESSED_TEXTURE_FORMATS_3, COMPRESSED_TEXTURE_FORMATS_32, F, SIZED_FORMATS, compressed_bytes, component_type, format_info, image_bytes3,
    pixel_bytes, renderable, tex_image_format } from "./gles_formats3.js";

export const GL3 = {
    TEXTURE_3D: 0x806F, TEXTURE_2D_ARRAY: 0x8C1A, TEXTURE_2D: 0x0DE1, TEXTURE_CUBE_MAP: 0x8513, TEXTURE_EXTERNAL_OES: 0x8D65,
    TEXTURE_CUBE_MAP_POSITIVE_X: 0x8515,
    ARRAY_BUFFER: 0x8892, ELEMENT_ARRAY_BUFFER: 0x8893, COPY_READ_BUFFER: 0x8F36, COPY_WRITE_BUFFER: 0x8F37,
    PIXEL_PACK_BUFFER: 0x88EB, PIXEL_UNPACK_BUFFER: 0x88EC, TRANSFORM_FEEDBACK_BUFFER: 0x8C8E, UNIFORM_BUFFER: 0x8A11,
    FRAMEBUFFER: 0x8D40, DRAW_FRAMEBUFFER: 0x8CA9, READ_FRAMEBUFFER: 0x8CA8, RENDERBUFFER: 0x8D41,
    COLOR_ATTACHMENT0: 0x8CE0, DEPTH_ATTACHMENT: 0x8D00, STENCIL_ATTACHMENT: 0x8D20, DEPTH_STENCIL_ATTACHMENT: 0x821A,
    BACK: 0x0405, NONE: 0, COLOR: 0x1800, DEPTH: 0x1801, STENCIL: 0x1802, DEPTH_STENCIL: 0x84F9,
    TEXTURE: 0x1702, FRAMEBUFFER_DEFAULT: 0x8218,
    FRAMEBUFFER_COMPLETE: 0x8CD5, INCOMPLETE_ATTACHMENT: 0x8CD6, INCOMPLETE_MISSING_ATTACHMENT: 0x8CD7,
    FRAMEBUFFER_UNSUPPORTED: 0x8CDD, INCOMPLETE_MULTISAMPLE: 0x8D56,
    TRANSFORM_FEEDBACK: 0x8E22, INTERLEAVED_ATTRIBS: 0x8C8C, SEPARATE_ATTRIBS: 0x8C8D,
    ANY_SAMPLES_PASSED: 0x8C2F, ANY_SAMPLES_PASSED_CONSERVATIVE: 0x8D6A, TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: 0x8C88,
    POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6,
    NO_ERROR: 0, INVALID_ENUM: 0x0500, INVALID_VALUE: 0x0501, INVALID_OPERATION: 0x0502, INVALID_FRAMEBUFFER_OPERATION: 0x0506,
    NEAREST: 0x2600, LINEAR: 0x2601, NEAREST_MIPMAP_NEAREST: 0x2700, LINEAR_MIPMAP_NEAREST: 0x2701, NEAREST_MIPMAP_LINEAR: 0x2702,
    LINEAR_MIPMAP_LINEAR: 0x2703, REPEAT: 0x2901, CLAMP_TO_EDGE: 0x812F, MIRRORED_REPEAT: 0x8370,
    RASTERIZER_DISCARD: 0x8C89, PRIMITIVE_RESTART_FIXED_INDEX: 0x8D69,
    MAP_READ_BIT: 1, MAP_WRITE_BIT: 2, MAP_INVALIDATE_RANGE_BIT: 4, MAP_INVALIDATE_BUFFER_BIT: 8, MAP_FLUSH_EXPLICIT_BIT: 0x10,
    MAP_UNSYNCHRONIZED_BIT: 0x20,
};

/** The limits GLES 3.x's contexts answer (WebGPU's defaults bound them; docs/gles3-plan.md "限制") */
export const LIMITS3 = {
    MAX_3D_TEXTURE_SIZE: 2048, MAX_ARRAY_TEXTURE_LAYERS: 256, MAX_COLOR_ATTACHMENTS: 4, MAX_DRAW_BUFFERS: 4, MAX_SAMPLES: 4,
    MAX_UNIFORM_BUFFER_BINDINGS: 36, MAX_UNIFORM_BLOCK_SIZE: 16384, MAX_VERTEX_UNIFORM_BLOCKS: 12, MAX_FRAGMENT_UNIFORM_BLOCKS: 12,
    MAX_COMBINED_UNIFORM_BLOCKS: 24, MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: 4, MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: 64,
    MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: 4, MAX_VERTEX_OUTPUT_COMPONENTS: 64, MAX_FRAGMENT_INPUT_COMPONENTS: 60,
    MAX_VERTEX_UNIFORM_COMPONENTS: 1024, MAX_FRAGMENT_UNIFORM_COMPONENTS: 1024, MAX_VARYING_COMPONENTS: 60,
    UNIFORM_BUFFER_OFFSET_ALIGNMENT: 256, MAX_ELEMENT_INDEX: 0xFFFFFFFF, MAX_PROGRAM_TEXEL_OFFSET: 7, MIN_PROGRAM_TEXEL_OFFSET: -8,
    MAX_TEXTURE_LOD_BIAS: 2, MAX_TEXTURE_SIZE: 4096,
};

export const MAX_UNITS = 48;
/** The sampler states among the texture parameters: filters, wraps, LODs, comparison, the border color (GLES 3.2's) */
const SAMPLER_STATES = new Set([0x2801, 0x2800, 0x2802, 0x2803, 0x8072, 0x813A, 0x813B, 0x884C, 0x884D, 0x1004]);
const MAX_ATTRIBS = 16;
const MAX_LEVELS_2D = Math.log2(LIMITS3.MAX_TEXTURE_SIZE) + 1;
const MAX_LEVELS_3D = Math.log2(LIMITS3.MAX_3D_TEXTURE_SIZE) + 1;

/** Texture binding slots of a unit: GLES 2.0's three, then 3.0's (gles_shadow.js texture_slot) */
export const SLOT = { TEXTURE_2D: 0, TEXTURE_CUBE_MAP: 1, TEXTURE_EXTERNAL_OES: 2, TEXTURE_3D: 3, TEXTURE_2D_ARRAY: 4, TEXTURE_2D_MULTISAMPLE: 5,
    TEXTURE_CUBE_MAP_ARRAY: 6 };
/** GLES 3.2's cube map arrays */
const TEXTURE_CUBE_MAP_ARRAY = 0x9009;
/** @return {boolean} whether a target is of layers (2D arrays; GLES 3.2's cube map arrays, their layer-faces) */
const layered = (c, target) => target === GL3.TEXTURE_2D_ARRAY || target === TEXTURE_CUBE_MAP_ARRAY && c.version >= 32;

const BUFFER_TARGETS = new Map([[GL3.ARRAY_BUFFER, "array"], [GL3.ELEMENT_ARRAY_BUFFER, "element"], [GL3.COPY_READ_BUFFER, "copy_read"],
    [GL3.COPY_WRITE_BUFFER, "copy_write"], [GL3.PIXEL_PACK_BUFFER, "pixel_pack"], [GL3.PIXEL_UNPACK_BUFFER, "pixel_unpack"],
    [GL3.TRANSFORM_FEEDBACK_BUFFER, "transform_feedback"], [GL3.UNIFORM_BUFFER, "uniform"],
    // (GLES 3.1's: gles31_state.js)
    [0x90D2, "shader_storage"], [0x92C0, "atomic_counter"], [0x90EE, "dispatch_indirect"], [0x8F3F, "draw_indirect"]]);
/** The buffer targets only GLES 3.1 has */
const TARGETS31 = new Set([0x90D2, 0x92C0, 0x90EE, 0x8F3F]);
/** @return {boolean} whether a context of its version has the buffer target */
const target_ok = (c, target) => BUFFER_TARGETS.has(target) && (c.version >= 31 || !TARGETS31.has(target));
const USAGES3 = new Set([0x88E0, 0x88E1, 0x88E2, 0x88E4, 0x88E5, 0x88E6, 0x88E8, 0x88E9, 0x88EA]);
const COMPARE_FUNCS = new Set([0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207]);
const WRAPS = new Set([GL3.REPEAT, GL3.CLAMP_TO_EDGE, GL3.MIRRORED_REPEAT]);
/** The bytes of a pixel transfer type's datum (a packed type's whole), for an unpack buffer's offset */
const DATUM_BYTES = { 0x1400: 1, 0x1401: 1, 0x1402: 2, 0x1403: 2, 0x1404: 4, 0x1405: 4, 0x1406: 4, 0x140B: 2, 0x8D61: 2, 0x8033: 2, 0x8034: 2,
    0x8363: 2, 0x8368: 4, 0x8C3B: 4, 0x8C3E: 4, 0x84FA: 4, 0x8DAD: 8 };
/** GLES 3.2's CLAMP_TO_BORDER and TEXTURE_BORDER_COLOR */
const CLAMP_TO_BORDER = 0x812D, TEXTURE_BORDER_COLOR = 0x1004;
/** GLES 3.1's DEPTH_STENCIL_TEXTURE_MODE (DEPTH_COMPONENT or STENCIL_INDEX) */
const DEPTH_STENCIL_TEXTURE_MODE = 0x90EA;
const wrap_ok = (c, wrap) => WRAPS.has(wrap) || c.version >= 32 && wrap === CLAMP_TO_BORDER;
/**
 * A border color as glTexParameteriv or glSamplerParameteriv gives it:
 * signed normalized (GLES 3.2 8.10's conversion), else as it is
 */
const border_color = (params, float) => [0, 1, 2, 3].map(k => k >= params.length ? 0 : float ? Math.fround(params[k]) : Math.fround((2 * params[k] + 1) / 4294967295));
/** A border color component as glGetTexParameteriv answers it */
const border_int = v => Math.max(-2147483648, Math.min(2147483647, Math.round((v * 4294967295 - 1) / 2)));
const MIN_FILTERS = new Set([GL3.NEAREST, GL3.LINEAR, GL3.NEAREST_MIPMAP_NEAREST, GL3.LINEAR_MIPMAP_NEAREST, GL3.NEAREST_MIPMAP_LINEAR,
    GL3.LINEAR_MIPMAP_LINEAR]);
const SWIZZLES = new Set([0x1903, 0x1904, 0x1905, 0x1906, 0, 1]);
const MODES = new Set([0, 1, 2, 3, 4, 5, 6]);
/** GLES 3.2's advanced blend equations (KHR_blend_equation_advanced's), in the order of BLEND_SUPPORT's names */
export const ADVANCED_EQUATIONS = [0x9294, 0x9295, 0x9296, 0x9297, 0x9298, 0x9299, 0x929A, 0x929B, 0x929C, 0x929E, 0x92A0, 0x92AD, 0x92AE,
    0x92AF, 0x92B0];
/** GLES 3.2's: lines and triangles with adjacency (a geometry shader's; without one the adjacent vertices are left out) */
const ADJACENCY_MODES = new Set([0xA, 0xB, 0xC, 0xD]);
/** whether a context of its version draws the mode */
const mode_ok = (c, mode) => MODES.has(mode) || c.version >= 32 && (ADJACENCY_MODES.has(mode) || mode === PATCHES);
/** GLES 3.2's PATCHES: tessellation's */
const PATCHES = 0xE;
/** the modes a geometry shader of each input type takes (GLES 3.2 11.3.4.1) */
const GEOMETRY_MODES = new Map([[0x0000, [0]], [0x0001, [1, 2, 3]], [0x0004, [4, 5, 6]], [0x000A, [0xA, 0xB]], [0x000C, [0xC, 0xD]]]);
const INDEX_TYPES = new Set([0x1401, 0x1403, 0x1405]);
const QUERY_TARGETS = new Set([GL3.ANY_SAMPLES_PASSED, GL3.ANY_SAMPLES_PASSED_CONSERVATIVE, GL3.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN]);

/** A vertex attribute's state, with GLES 3.0's integer and divisor */
export function new_attrib3()
{
    return { enabled: false, size: 4, type: 0x1406, normalized: false, stride: 0, buffer: 0, offset: 0, current: [0, 0, 0, 1],
        integer: false, divisor: 0, current_type: "f" };
}

/** A vertex array object */
function new_vao()
{
    return { attribs: Array.from({ length: MAX_ATTRIBS }, new_attrib3), element_array_buffer: 0, bound_once: false };
}

/** A transform feedback object */
function new_tf()
{
    return { active: false, paused: false, mode: 0, program: 0, bindings: Array.from({ length: 4 }, () => ({ buffer: 0, offset: 0, size: 0 })),
        vertices: [0, 0, 0, 0], bound_once: false };
}

/** A framebuffer object's GLES 3.0 state */
export function new_framebuffer3()
{
    return { attachments: new Map(), draw_buffers: [GL3.COLOR_ATTACHMENT0, GL3.NONE, GL3.NONE, GL3.NONE], read_buffer: GL3.COLOR_ATTACHMENT0 };
}

/** A sampler object's state (GLES 3.0 table 6.10) */
function new_sampler()
{
    return { min_filter: GL3.NEAREST_MIPMAP_LINEAR, mag_filter: GL3.LINEAR, wrap_s: GL3.REPEAT, wrap_t: GL3.REPEAT, wrap_r: GL3.REPEAT,
        min_lod: -1000, max_lod: 1000, compare_mode: 0, compare_func: 0x0203 };
}

/** A GLES 3.0 context's state beyond GLES 2.0's (tables 6.2 to 6.37) */
/**
 * A context a snapshot brought back from when the limits were lower: its
 * texture units and uniform buffer binding points as many as now
 */
export function pad_context3(c)
{
    while(c.textures.length < MAX_UNITS) c.textures.push([0, 0, 0, 0, 0, 0, 0]);
    while(c.samplers.length < MAX_UNITS) c.samplers.push(0);
    while(c.uniform_bindings.length < LIMITS3.MAX_UNIFORM_BUFFER_BINDINGS) c.uniform_bindings.push({ buffer: 0, offset: 0, size: 0 });
}

export function extend_context3(c)
{
    c.textures = Array.from({ length: MAX_UNITS }, () => [0, 0, 0, 0, 0, 0, 0]);
    c.samplers = new Array(MAX_UNITS).fill(0);
    c.buffers = { copy_read: 0, copy_write: 0, pixel_pack: 0, pixel_unpack: 0, transform_feedback: 0, uniform: 0,
        shader_storage: 0, atomic_counter: 0, dispatch_indirect: 0, draw_indirect: 0 };
    c.uniform_bindings = Array.from({ length: LIMITS3.MAX_UNIFORM_BUFFER_BINDINGS }, () => ({ buffer: 0, offset: 0, size: 0 }));
    c.default_vao = new_vao();
    c.attribs = c.default_vao.attribs;
    c.vaos = new Map();
    c.vao = 0;
    c.tfs = new Map([[0, new_tf()]]);
    c.tf = 0;
    c.queries = new Map();
    /** @type {!Map<number, number>} the active query of each target */
    c.active_queries = new Map();
    c.reserved3 = { vao: new Set(), tf: new Set(), query: new Set() };
    c.next3 = { vao: 1, tf: 1, query: 1 };
    c.read_framebuffer = 0;
    c.default_draw_buffer = GL3.BACK;
    c.default_read_buffer = GL3.BACK;
    c.unpack = { row_length: 0, image_height: 0, skip_pixels: 0, skip_rows: 0, skip_images: 0 };
    c.pack = { row_length: 0, skip_pixels: 0, skip_rows: 0 };
    c.hints.set(0x8B8B, 0x1100);
}

/** A share group's objects of GLES 3.0: samplers and syncs */
export function extend_group3(g)
{
    if(g.samplers) return;
    g.samplers = new Map();
    g.syncs = new Map();
    g.reserved.sampler = new Set();
    g.next.sampler = 1;
    g.next_sync = 1;
}

/** @param {!Object} c @param {string} kind @param {!Map} objects @return {number} a name the context's objects of the kind lack */
function fresh_context_name(c, kind, objects)
{
    let name = c.next3[kind];
    while(objects.has(name) || c.reserved3[kind].has(name)) name++;
    c.next3[kind] = name + 1;
    return name;
}

/**
 * The handlers of GLES 3.x's contexts: GLES 3.0's commands and its forms
 * of GLES 2.0's
 * @param {!Object} h gles_shadow.js's helpers
 * @return {!Object<string, function(!Object, !Object, !Array<*>)>}
 */
export function gles3_handlers(h)
{
    const { fail, query, put, put_text, i32s, f32s, text_of, REFUSED, base, framebuffer_status3 } = h;
    const GL = GL3;

    /** @return {number} a value as glGet's i form reads a float state, rounded */
    const round = v => Math.round(v);

    /** A glGen* of the context's objects (vertex arrays, transform feedbacks, queries) */
    const gen3 = (kind, map_of) => (shadow, c, [n, names]) =>
    {
        query(shadow);
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        const objects = map_of(c);
        for(let i = 0; i < n && 4 * i + 4 <= names.size; i++)
        {
            const name = fresh_context_name(c, kind, objects);
            c.reserved3[kind].add(name);
            names.view.setUint32(4 * i, name, true);
        }
        return undefined;
    };

    // ---- buffers

    /** The name bound to a buffer target, or -1 for a target that is none */
    const buffer_binding = (c, target) =>
    {
        const which = BUFFER_TARGETS.get(target);
        if(!which) return -1;
        if(which === "array") return c.array_buffer;
        if(which === "element") return c.element_array_buffer;
        return c.buffers[which];
    };
    /** The buffer bound to a target, or null with the error set */
    const bound_buffer3 = (c, target) =>
    {
        const name = buffer_binding(c, target);
        if(name < 0) { fail(c, GL.INVALID_ENUM); return null; }
        const buffer = c.group.buffers.get(name);
        if(!buffer) { fail(c, GL.INVALID_OPERATION); return null; }
        return buffer;
    };
    const set_buffer_binding = (c, target, name) =>
    {
        const which = BUFFER_TARGETS.get(target);
        if(which === "array") c.array_buffer = name;
        else if(which === "element") c.element_array_buffer = name;
        else c.buffers[which] = name;
    };
    /**
     * Whether a name was made by glGen*: those calls are the CPU side's
     * alone (queries), so the page's shadow (`trusted`) takes the names the
     * CPU side accepted as made. GLES 3.x wants it of vertex arrays,
     * transform feedbacks, queries, samplers and program pipelines; a
     * buffer, texture, framebuffer or renderbuffer is still made by binding
     * an unused name (GLES 2.0's rule, which 3.x keeps)
     */
    const generated = (shadow, made, name) => shadow.trusted || made.has(name);
    const new_buffer = () => ({ size: 0, usage: 0x88E4, mapped: null, bytes: null, gpu_newer: false });
    /** whether the buffer is bound for transform feedback while one is active (writes to it are errors then) */
    const tf_bound_active = (c, name) =>
    {
        const tf = c.tfs.get(c.tf);
        return !!tf && tf.active && tf.bindings.some(b => b.buffer === name);
    };
    /** The buffer's bytes on the CPU side, as large as it is */
    const bytes_of = (shadow, buffer) =>
    {
        if(!shadow.keep_bytes) return null;
        if(!buffer.bytes || buffer.bytes.length !== buffer.size) buffer.bytes = new Uint8Array(buffer.size);
        return buffer.bytes;
    };

    // ---- textures

    const target_slot = (target, c) => target === GL.TEXTURE_2D ? SLOT.TEXTURE_2D : target === GL.TEXTURE_CUBE_MAP ? SLOT.TEXTURE_CUBE_MAP :
        target === GL.TEXTURE_EXTERNAL_OES ? SLOT.TEXTURE_EXTERNAL_OES : target === GL.TEXTURE_3D ? SLOT.TEXTURE_3D :
        target === GL.TEXTURE_2D_ARRAY ? SLOT.TEXTURE_2D_ARRAY : target === 0x9100 && c.version >= 31 ? SLOT.TEXTURE_2D_MULTISAMPLE :
        target === TEXTURE_CUBE_MAP_ARRAY && c.version >= 32 ? SLOT.TEXTURE_CUBE_MAP_ARRAY : -1;
    /** The texture bound to a target of the active unit (the default one for name 0), or null with the error set */
    const bound_texture3 = (c, target) =>
    {
        const slot = target_slot(target, c);
        if(slot < 0) { fail(c, GL.INVALID_ENUM); return null; }
        const name = c.textures[c.active_texture][slot];
        let texture = c.group.textures.get(name);
        if(!texture && !name)
        {
            c.defaults = c.defaults || new Map();
            texture = c.defaults.get(target);
            if(!texture) c.defaults.set(target, texture = h.new_texture(target));
        }
        return texture || null;
    };
    /** The face of a 2D image target: 0 for TEXTURE_2D, 0 to 5 for a cube face, -1 for none */
    const face_of = target =>
    {
        if(target === GL.TEXTURE_2D) return 0;
        const face = target - GL.TEXTURE_CUBE_MAP_POSITIVE_X;
        return face >= 0 && face < 6 ? face : -1;
    };
    const image_key = (face, level) => face * 32 + level;
    /** The unpack state as image_bytes3 takes it */
    const unpack_store = c => ({ alignment: c.unpack_alignment, row_length: c.unpack.row_length, image_height: c.unpack.image_height,
        skip_pixels: c.unpack.skip_pixels, skip_rows: c.unpack.skip_rows, skip_images: c.unpack.skip_images });
    /**
     * The data of a TexImage-like call: from the call's bytes, or (Offset
     * forms) from the pixel unpack buffer: @return {boolean} whether it is
     * there, else the error is set
     */
    const source_ok = (c, needed, bytes, offset, type) =>
    {
        if(offset === undefined)
        {
            if(c.buffers.pixel_unpack) return true; // (the encoder sends the Offset form with a buffer bound)
            if(bytes && bytes.length < needed) { fail(c, GL.INVALID_OPERATION); return false; }
            return true;
        }
        const buffer = c.group.buffers.get(c.buffers.pixel_unpack);
        if(!buffer) { fail(c, GL.INVALID_OPERATION); return false; }
        if(buffer.mapped || offset < 0 || offset + needed > buffer.size) { fail(c, GL.INVALID_OPERATION); return false; }
        // (the offset a whole number of the type's datums: GLES 3.0 3.7.1)
        if(type !== undefined && offset % (DATUM_BYTES[type] || 1)) { fail(c, GL.INVALID_OPERATION); return false; }
        return true;
    };
    const max_level_of = target => target === GL.TEXTURE_3D ? MAX_LEVELS_3D - 1 : MAX_LEVELS_2D - 1;
    /** A TexImage's size and level checks (GLES 3.0 3.8.3) @return {boolean} */
    const size_ok = (c, target, level, width, height, depth, border) =>
    {
        const max = target === GL.TEXTURE_3D ? LIMITS3.MAX_3D_TEXTURE_SIZE : LIMITS3.MAX_TEXTURE_SIZE;
        if(level < 0 || level > max_level_of(target) || width < 0 || height < 0 || depth < 0 || border !== 0 ||
            width > max >> level || height > max >> level ||
            (target === GL.TEXTURE_3D ? depth > max >> level : layered(c, target) ? depth > LIMITS3.MAX_ARRAY_TEXTURE_LAYERS : false) ||
            target !== GL.TEXTURE_2D && target !== GL.TEXTURE_3D && target !== GL.TEXTURE_2D_ARRAY && width !== height ||
            target === TEXTURE_CUBE_MAP_ARRAY && depth % 6)
        {
            fail(c, GL.INVALID_VALUE);
            return false;
        }
        return true;
    };
    /** glTexImage2D/3D, the Offset forms too */
    const tex_image = (shadow, c, three, args) =>
    {
        const [target, level, internalformat, width, height, depth, border, format, type, data] = three ? args :
            [args[0], args[1], args[2], args[3], args[4], 1, args[5], args[6], args[7], args[8]];
        const offset = typeof data === "number" ? data : undefined;
        let texture, face;
        if(three)
        {
            if(target !== GL.TEXTURE_3D && !layered(c, target)) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target);
            face = 0;
        }
        else
        {
            face = face_of(target);
            if(face < 0) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
        }
        if(!texture) return REFUSED;
        // (a 3D texture of depth: refused as INVALID_OPERATION before the format's checks, dEQP's negative_api.texture.teximage3d)
        if(three && target === GL.TEXTURE_3D && (format === 0x1902 || format === 0x84F9)) return fail(c, GL.INVALID_OPERATION);
        const f = tex_image_format(internalformat, format, type);
        if(f.error) return fail(c, f.error);
        const info = format_info(f.internal);
        if(three && target === GL.TEXTURE_3D && info && (info.kind === "depth" || info.kind === "depth_stencil")) return fail(c, GL.INVALID_OPERATION);
        if(!size_ok(c, target, level, width, height, depth, border)) return REFUSED;
        if(texture.immutable) return fail(c, GL.INVALID_OPERATION);
        const needed = image_bytes3(width, height, depth, format, type, unpack_store(c));
        if(!source_ok(c, needed, offset === undefined ? data : null, offset, type)) return REFUSED;
        texture.images.set(image_key(face, level), { width, height, depth, format, type, internal: f.internal, compressed: false });
        return undefined;
    };
    /** glTexSubImage2D/3D, the Offset forms too */
    const tex_sub_image = (shadow, c, three, args) =>
    {
        const [target, level, x, y, z, width, height, depth, format, type, data] = three ? args :
            [args[0], args[1], args[2], args[3], 0, args[4], args[5], 1, args[6], args[7], args[8]];
        const offset = typeof data === "number" ? data : undefined;
        let texture, face;
        if(three)
        {
            if(target !== GL.TEXTURE_3D && !layered(c, target)) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target);
            face = 0;
        }
        else
        {
            face = face_of(target);
            if(face < 0) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
        }
        if(!texture) return REFUSED;
        if(pixel_bytes(format, type) === 0) return fail(c, GL.INVALID_ENUM);
        if(level < 0 || level > max_level_of(target) || x < 0 || y < 0 || z < 0 || width < 0 || height < 0 || depth < 0) return fail(c, GL.INVALID_VALUE);
        const image = texture.images.get(image_key(face, level));
        if(!image || image.compressed) return fail(c, GL.INVALID_OPERATION);
        if(x + width > image.width || y + height > image.height || z + depth > (image.depth || 1)) return fail(c, GL.INVALID_VALUE);
        if(tex_image_format(image.internal || image.format, format, type).error) return fail(c, GL.INVALID_OPERATION);
        const needed = image_bytes3(width, height, depth, format, type, unpack_store(c));
        if(!source_ok(c, needed, offset === undefined ? data : null, offset, type)) return REFUSED;
        return undefined;
    };
    /** glTexStorage2D/3D */
    const tex_storage = (shadow, c, target, levels, internalformat, width, height, depth) =>
    {
        const two_d = target === GL.TEXTURE_2D || target === GL.TEXTURE_CUBE_MAP;
        if(!two_d && depth === undefined || two_d && depth !== undefined && depth !== 1) return fail(c, GL.INVALID_ENUM);
        const texture = bound_texture3(c, target);
        if(!texture) return REFUSED;
        const info = SIZED_FORMATS.get(internalformat);
        const compressed = COMPRESSED_FORMATS.get(internalformat);
        if(!info && !compressed) return fail(c, GL.INVALID_ENUM);
        if(depth === undefined) depth = 1;
        if(width < 1 || height < 1 || depth < 1 || levels < 1) return fail(c, GL.INVALID_VALUE);
        const max = target === GL.TEXTURE_3D ? LIMITS3.MAX_3D_TEXTURE_SIZE : LIMITS3.MAX_TEXTURE_SIZE;
        if(width > max || height > max || (target === GL.TEXTURE_3D && depth > max) ||
            (layered(c, target) && depth > LIMITS3.MAX_ARRAY_TEXTURE_LAYERS) || (target === GL.TEXTURE_CUBE_MAP || target === TEXTURE_CUBE_MAP_ARRAY) && width !== height ||
            target === TEXTURE_CUBE_MAP_ARRAY && depth % 6)
        {
            return fail(c, GL.INVALID_VALUE);
        }
        const largest = target === GL.TEXTURE_3D ? Math.max(width, height, depth) : Math.max(width, height);
        if(levels > Math.floor(Math.log2(largest)) + 1) return fail(c, GL.INVALID_OPERATION);
        if(texture.immutable) return fail(c, GL.INVALID_OPERATION);
        if(info && target === GL.TEXTURE_3D && (info.kind === "depth" || info.kind === "depth_stencil")) return fail(c, GL.INVALID_OPERATION);
        if(compressed && target === GL.TEXTURE_3D) return fail(c, GL.INVALID_OPERATION);
        texture.images.clear();
        const faces = target === GL.TEXTURE_CUBE_MAP ? 6 : 1;
        for(let level = 0; level < levels; level++)
        {
            const w = Math.max(1, width >> level), hh = Math.max(1, height >> level);
            const d = target === GL.TEXTURE_3D ? Math.max(1, depth >> level) : depth;
            for(let face = 0; face < faces; face++)
            {
                texture.images.set(image_key(face, level), { width: w, height: hh, depth: d, format: info ? info.format : internalformat,
                    type: info ? info.types[0] : 0x1401, internal: internalformat, compressed: !!compressed });
            }
        }
        texture.immutable = true;
        texture.immutable_levels = levels;
        return undefined;
    };
    /** glCompressedTexImage2D/3D, the Offset forms too */
    const compressed_image = (shadow, c, three, args) =>
    {
        const [target, level, internalformat, width, height, depth, border, size, data] = three ? args :
            [args[0], args[1], args[2], args[3], args[4], 1, args[5], args[6], args[7]];
        const offset = typeof data === "number" ? data : undefined;
        const face = three ? 0 : face_of(target);
        if(three ? !layered(c, target) && target !== GL.TEXTURE_3D : face < 0) return fail(c, GL.INVALID_ENUM);
        const texture = bound_texture3(c, three ? target : target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
        if(!texture) return REFUSED;
        if(!COMPRESSED_FORMATS.has(internalformat)) return fail(c, GL.INVALID_ENUM);
        if(target === GL.TEXTURE_3D) return fail(c, GL.INVALID_OPERATION);
        if(!size_ok(c, three ? target : target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP, level, width, height, depth, border)) return REFUSED;
        if(texture.immutable) return fail(c, GL.INVALID_OPERATION);
        if(size !== compressed_bytes(internalformat, width, height, depth)) return fail(c, GL.INVALID_VALUE);
        if(offset === undefined ? !c.buffers.pixel_unpack && data && data.length < size : !source_ok(c, size, null, offset)) return fail(c, GL.INVALID_VALUE);
        texture.images.set(image_key(face, level), { width, height, depth, format: internalformat, type: 0x1401, internal: internalformat,
            compressed: true });
        return undefined;
    };
    /** glCompressedTexSubImage2D/3D */
    const compressed_sub_image = (shadow, c, three, args) =>
    {
        const [target, level, x, y, z, width, height, depth, format, size] = three ? args :
            [args[0], args[1], args[2], args[3], 0, args[4], args[5], 1, args[6], args[7]];
        const face = three ? 0 : face_of(target);
        if(three ? !layered(c, target) && target !== GL.TEXTURE_3D : face < 0) return fail(c, GL.INVALID_ENUM);
        const texture = bound_texture3(c, three ? target : target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
        if(!texture) return REFUSED;
        if(!COMPRESSED_FORMATS.has(format)) return fail(c, GL.INVALID_ENUM);
        if(level < 0 || level > max_level_of(target) || x < 0 || y < 0 || z < 0 || width < 0 || height < 0 || depth < 0) return fail(c, GL.INVALID_VALUE);
        const image = texture.images.get(image_key(face, level));
        if(!image || !image.compressed || image.internal !== format || format === 0x8D64) return fail(c, GL.INVALID_OPERATION);
        const { block_width: bw, block_height: bh } = COMPRESSED_FORMATS.get(format);
        if(x % bw || y % bh || x + width > image.width || y + height > image.height || z + depth > image.depth ||
            width % bw && x + width !== image.width || height % bh && y + height !== image.height)
        {
            return fail(c, GL.INVALID_OPERATION);
        }
        if(size !== compressed_bytes(format, width, height, depth)) return fail(c, GL.INVALID_VALUE);
        return undefined;
    };

    // ---- framebuffers

    /** The framebuffer bound to a target's name, or -1 for a target that is none */
    const framebuffer_of = (c, target) => target === GL.FRAMEBUFFER || target === GL.DRAW_FRAMEBUFFER ? c.framebuffer :
        target === GL.READ_FRAMEBUFFER ? c.read_framebuffer : -1;
    const color_attachment = attachment => attachment >= GL.COLOR_ATTACHMENT0 && attachment < GL.COLOR_ATTACHMENT0 + LIMITS3.MAX_COLOR_ATTACHMENTS;
    const attachment_ok = attachment => color_attachment(attachment) || attachment === GL.DEPTH_ATTACHMENT ||
        attachment === GL.STENCIL_ATTACHMENT || attachment === GL.DEPTH_STENCIL_ATTACHMENT;
    /** Attach (or detach, a null record) at an attachment point: DEPTH_STENCIL is both */
    const attach = (fbo, attachment, record) =>
    {
        const points = attachment === GL.DEPTH_STENCIL_ATTACHMENT ? [GL.DEPTH_ATTACHMENT, GL.STENCIL_ATTACHMENT] : [attachment];
        for(const point of points)
        {
            if(record) fbo.attachments.set(point, Object.assign({}, record));
            else fbo.attachments.delete(point);
        }
    };
    /** The image of an attachment: size, samples, format info, or null */
    const attachment_image = (c, a) =>
    {
        if(a.type === GL.RENDERBUFFER)
        {
            const rb = c.group.renderbuffers.get(a.name);
            if(!rb || !rb.width || !rb.height) return null;
            return { width: rb.width, height: rb.height, samples: rb.samples || 0, info: format_info(rb.format) || h.renderbuffer_info(rb.format) };
        }
        const texture = c.group.textures.get(a.name);
        const image = texture && texture.images.get(image_key(a.face, a.level));
        if(!image || !image.width || !image.height) return null;
        if((texture.target === GL.TEXTURE_3D || layered(c, texture.target)) && a.layer >= (image.depth || 1)) return null;
        return { width: image.width, height: image.height, samples: image.samples || 0,
            info: image.compressed ? null : format_info(image.internal || image.format) || h.renderbuffer_info(image.format) };
    };
    /** A framebuffer's status by GLES 3.0's rules (4.4.4) */
    const status_of = (c, name) =>
    {
        if(!name) return GL.FRAMEBUFFER_COMPLETE;
        const fbo = c.framebuffers.get(name);
        let any = false, samples = -1;
        for(const [attachment, a] of fbo.attachments)
        {
            const image = attachment_image(c, a);
            if(!image || !image.info) return GL.INCOMPLETE_ATTACHMENT;
            const k = image.info.kind;
            if(color_attachment(attachment) ? !renderable(image.info, c.color_buffer_float) || k === "depth" || k === "depth_stencil" :
                attachment === GL.DEPTH_ATTACHMENT ? k !== "depth" && k !== "depth_stencil" :
                k !== "depth_stencil" && image.info.value !== 0x8D48)
            {
                return GL.INCOMPLETE_ATTACHMENT;
            }
            if(samples >= 0 && samples !== image.samples) return GL.INCOMPLETE_MULTISAMPLE;
            samples = image.samples;
            any = true;
        }
        // (GLES 3.1: none, with a default width and height: a framebuffer drawn to without attachments)
        if(!any) return c.version >= 31 && fbo.default_width > 0 && fbo.default_height > 0 ? GL.FRAMEBUFFER_COMPLETE : GL.INCOMPLETE_MISSING_ATTACHMENT;
        const depth = fbo.attachments.get(GL.DEPTH_ATTACHMENT), stencil = fbo.attachments.get(GL.STENCIL_ATTACHMENT);
        if(depth && stencil && (depth.type !== stencil.type || depth.name !== stencil.name || depth.level !== stencil.level ||
            depth.face !== stencil.face || depth.layer !== stencil.layer))
        {
            return GL.FRAMEBUFFER_UNSUPPORTED;
        }
        return GL.FRAMEBUFFER_COMPLETE;
    };
    framebuffer_status3.fn = status_of;
    /** INVALID_FRAMEBUFFER_OPERATION unless the draw (and for reads, the read) framebuffer is complete @return {boolean} */
    const complete = (c, read) =>
    {
        if(status_of(c, c.framebuffer) !== GL.FRAMEBUFFER_COMPLETE || read && status_of(c, c.read_framebuffer) !== GL.FRAMEBUFFER_COMPLETE)
        {
            fail(c, GL.INVALID_FRAMEBUFFER_OPERATION);
            return false;
        }
        return true;
    };
    /** The format of what a framebuffer reads from (its read buffer), or null */
    const read_image = (c) =>
    {
        if(!c.read_framebuffer)
        {
            if(c.default_read_buffer === GL.NONE) return null;
            const bits = h.framebuffer_bits(c);
            return { info: { kind: "unorm", bits, value: bits[3] ? 0x8058 : 0x8051, format: bits[3] ? 0x1908 : 0x1907 }, samples: 0 };
        }
        const fbo = c.framebuffers.get(c.read_framebuffer);
        if(fbo.read_buffer === GL.NONE) return null;
        const a = fbo.attachments.get(fbo.read_buffer);
        return a ? attachment_image(c, a) : null;
    };

    // ---- transform feedback

    const current_tf = c => c.tfs.get(c.tf);
    /** The primitives a draw of `count` vertices in `mode` makes */
    const primitives = (mode, count) => mode === GL.POINTS ? count : mode === GL.LINES ? count >> 1 :
        mode === GL.TRIANGLES ? Math.floor(count / 3) : 0;
    /**
     * A draw while transform feedback is active: GLES 3.0's errors (the
     * mode must be the feedback's, no room is an error), and the vertices
     * written (the CPU side's count of TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN)
     * @return {boolean}
     */
    const tf_draw = (shadow, c, mode, count, instances, elements) =>
    {
        const tf = current_tf(c);
        if(!tf.active || tf.paused) return true;
        if(elements || mode !== tf.mode) { fail(c, GL.INVALID_OPERATION); return false; }
        const program = c.group.objects.get(tf.program);
        const varyings = program && program.info && program.info.tf_varyings || [];
        const prims = primitives(mode, count) * instances;
        const vertices = prims * (mode === GL.POINTS ? 1 : mode === GL.LINES ? 2 : 3);
        const interleaved = program && program.info && program.info.tf_mode === GL.INTERLEAVED_ATTRIBS;
        const strides = interleaved ? [varyings.reduce((n, v) => n + v.bytes, 0)] : varyings.map(v => v.bytes);
        for(let i = 0; i < strides.length; i++)
        {
            const b = tf.bindings[i];
            const buffer = c.group.buffers.get(b.buffer);
            const room = buffer ? Math.floor(((b.size || buffer.size - b.offset) - tf.vertices[i] * strides[i]) / Math.max(1, strides[i])) : 0;
            if(vertices > room) { fail(c, GL.INVALID_OPERATION); return false; }
        }
        for(let i = 0; i < strides.length; i++) tf.vertices[i] += vertices;
        const q = c.active_queries.get(GL.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
        if(q) c.queries.get(q).result += prims;
        for(const b of tf.bindings)
        {
            const buffer = c.group.buffers.get(b.buffer);
            if(buffer) buffer.gpu_newer = true;
        }
        return true;
    };

    /** The draw's geometry shader's layout (link_glslang_program's `geometry`), or null */
    const geometry_of = c =>
    {
        const pipeline = !c.program && c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
        const program = c.group.objects.get(c.program || pipeline && pipeline.stages[4]);
        return program && program.info && program.info.ok && program.info.geometry || null;
    };
    /** Whether the draw has a tessellation evaluation shader (link_glslang_program's `tessellation`) */
    const tessellates = c =>
    {
        const pipeline = !c.program && c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
        const program = c.group.objects.get(c.program || pipeline && pipeline.stages[0x10]);
        return !!(program && program.info && program.info.ok && program.info.tessellation && program.info.tessellation.evaluation);
    };

    /** A draw's checks: mode, counts, the framebuffer, transform feedback */
    const draw_checks = (shadow, c, mode, count, instances, elements, type) =>
    {
        if(!mode_ok(c, mode) || elements && !INDEX_TYPES.has(type)) return fail(c, GL.INVALID_ENUM);
        if(count < 0 || instances < 0) return fail(c, GL.INVALID_VALUE);
        // (tessellation takes patches, and only it; a geometry shader the modes of its input type, after tessellation its output's)
        const tessellation = c.version >= 32 && tessellates(c);
        if(tessellation !== (mode === PATCHES)) return fail(c, GL.INVALID_OPERATION);
        const geometry = c.version >= 32 && !tessellation ? geometry_of(c) : null;
        if(geometry && !(GEOMETRY_MODES.get(geometry.input) || []).includes(mode)) return fail(c, GL.INVALID_OPERATION);
        // (an advanced blend equation: one draw buffer, a fragment shader that declares the equation's support)
        if(c.version >= 32 && c.enabled.has(0x0BE2) && ADVANCED_EQUATIONS.includes(c.blend_equation[0]))
        {
            const fbo = c.framebuffer && c.framebuffers.get(c.framebuffer);
            if(fbo && fbo.draw_buffers.slice(1).some(b => b !== GL.NONE)) return fail(c, GL.INVALID_OPERATION);
            const pipeline = !c.program && c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
            const fragment = c.group.objects.get(c.program || pipeline && pipeline.stages[2]);
            const support = fragment && fragment.info && fragment.info.blend_support || [];
            if(!support.includes(c.blend_equation[0])) return fail(c, GL.INVALID_OPERATION);
        }
        if(!complete(c, false)) return REFUSED;
        if(!tf_draw(shadow, c, mode, count, instances, elements)) return REFUSED;
        const occlusion = [GL.ANY_SAMPLES_PASSED, GL.ANY_SAMPLES_PASSED_CONSERVATIVE].map(t => c.active_queries.get(t)).filter(Boolean);
        for(const q of occlusion) c.queries.get(q).drawn = true;
        return undefined;
    };

    // ---- uniforms

    /** The current program's uniform at a location (null for -1), REFUSED with the error set */
    const uniform_at3 = (c, location, count) =>
    {
        const program = c.group.objects.get(c.program);
        if(!program || !program.info || !program.info.ok) return fail(c, GL.INVALID_OPERATION);
        if(count < 0) return fail(c, GL.INVALID_VALUE);
        if(location === -1) return null;
        const at = program.info.by_location[location];
        if(!at) return fail(c, GL.INVALID_OPERATION);
        // (an array of one active element is still an array: its name ends in [0], the rest of the count is ignored)
        if(count > 1 && at.uniform.size === 1 && at.uniform.name === at.uniform.base) return fail(c, GL.INVALID_OPERATION);
        return { program, at };
    };
    /**
     * glUniform* of GLES 3.0 (2.12.6): the function's kind ("f", "i",
     * "ui", "m" for a matrix of columns x rows) against the uniform's type;
     * the values stored by location (program.values), as numbers
     */
    const uniform3 = (components, kind, vector, columns, rows) => (shadow, c, args) =>
    {
        const location = args[0];
        let count = 1, values;
        if(kind === "m")
        {
            count = args[1];
            values = f32s(args[3]);
        }
        else if(vector)
        {
            count = args[1];
            values = kind === "f" ? f32s(args[2]) : kind === "ui" ? i32s(args[2]).map(v => v >>> 0) : i32s(args[2]);
        }
        else values = args.slice(1).map(v => kind === "ui" ? v >>> 0 : v);
        const target = uniform_at3(c, location, count);
        if(target === REFUSED || target === null) return target === null ? undefined : target;
        const u = target.at.uniform;
        if(kind === "m" && args[2] && c.version < 30) return fail(c, GL.INVALID_VALUE);
        const ok = kind === "m" ? u.columns === columns && u.rows === rows :
            !u.columns && u.components === components && (u.bool ||
                (u.sampler || u.opaque ? kind === "i" && components === 1 :
                kind === "f" ? !u.int : kind === "i" ? u.int && !u.uint : u.uint));
        if(!ok) return fail(c, GL.INVALID_OPERATION);
        if(u.sampler && values.slice(0, count).some(v => v < 0 || v >= MAX_UNITS)) return fail(c, GL.INVALID_VALUE);
        const size = kind === "m" ? columns * rows : components;
        const first = target.at.element;
        const n = Math.min(count, u.size - first);
        for(let i = 0; i < n; i++)
        {
            let v = values.slice(i * size, (i + 1) * size);
            // (a transposed matrix's values in columns)
            if(kind === "m" && args[2])
            {
                const t = [];
                for(let col = 0; col < columns; col++) for(let row = 0; row < rows; row++) t.push(v[row * columns + col]);
                v = t;
            }
            if(u.bool) v = v.map(x => x ? 1 : 0);
            target.program.values.set(u.location + first + i, v);
        }
        return undefined;
    };
    /** glGetUniform{f,i,ui}v of GLES 3.0 */
    const get_uniform3 = as => (shadow, c, [p, location, params]) =>
    {
        query(shadow);
        const program = c.group.objects.get(p);
        if(!program) { fail(c, GL.INVALID_VALUE); return; }
        if(program.kind !== "program" || !program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return; }
        const at = program.info.by_location[location];
        if(!at) { fail(c, GL.INVALID_OPERATION); return; }
        const u = at.uniform;
        const values = program.values.get(location) || new Array(u.columns ? u.columns * u.rows : u.components).fill(0);
        if(as === "f") put(params, values, "f", "f");
        else if(as === "ui") put(params, values.map(v => u.int ? v >>> 0 : Math.round(v) >>> 0), "i", "i");
        else put(params, values.map(v => u.int ? v | 0 : Math.round(v)), "i", "i");
    };

    /** The program of a query with GLES 3.0's errors, linked or not */
    const program_of = (c, p) =>
    {
        const program = c.group.objects.get(p);
        if(!program) { fail(c, GL.INVALID_VALUE); return null; }
        if(program.kind !== "program") { fail(c, GL.INVALID_OPERATION); return null; }
        return program;
    };

    /** int64 values into an out buffer */
    const put64 = (out, values) =>
    {
        for(let i = 0; i < values.length && 8 * i + 8 <= out.size; i++) out.view.setBigInt64(8 * i, BigInt(Math.trunc(values[i])), true);
    };

    /**
     * A float form of glVertexAttrib: GLES 2.0's, and the value the
     * context's current one (attrib_current's), which a query answers
     * before the vertex array's: else a value an integer form set earlier
     */
    const float_attrib = name => (shadow, c, args) =>
    {
        const r = base[name](shadow, c, args);
        if(args[0] < MAX_ATTRIBS) attrib_current(c, args[0], c.attribs[args[0]].current, "f");
        return r;
    };

    // ---- the handlers
    const H = {
        // ---- state
        "glEnable": (shadow, c, [cap]) =>
        {
            if(cap === GL.RASTERIZER_DISCARD || cap === GL.PRIMITIVE_RESTART_FIXED_INDEX) { c.enabled.add(cap); return undefined; }
            return base["glEnable"](shadow, c, [cap]);
        },
        "glDisable": (shadow, c, [cap]) =>
        {
            if(cap === GL.RASTERIZER_DISCARD || cap === GL.PRIMITIVE_RESTART_FIXED_INDEX) { c.enabled.delete(cap); return undefined; }
            return base["glDisable"](shadow, c, [cap]);
        },
        "glIsEnabled": (shadow, c, [cap]) =>
        {
            if(cap === GL.RASTERIZER_DISCARD || cap === GL.PRIMITIVE_RESTART_FIXED_INDEX) { query(shadow); return c.enabled.has(cap) ? 1 : 0; }
            return base["glIsEnabled"](shadow, c, [cap]);
        },
        "glHint": (shadow, c, [target, mode]) =>
        {
            if(target !== 0x8192 && target !== 0x8B8B || ![0x1100, 0x1101, 0x1102].includes(mode)) return fail(c, GL.INVALID_ENUM);
            c.hints.set(target, mode);
            return undefined;
        },
        "glPixelStorei": (shadow, c, [pname, param]) =>
        {
            const fields = { 0x0CF2: ["unpack", "row_length"], 0x806E: ["unpack", "image_height"], 0x0CF4: ["unpack", "skip_pixels"],
                0x0CF3: ["unpack", "skip_rows"], 0x806D: ["unpack", "skip_images"], 0x0D02: ["pack", "row_length"],
                0x0D04: ["pack", "skip_pixels"], 0x0D03: ["pack", "skip_rows"] };
            if(fields[pname])
            {
                if(param < 0) return fail(c, GL.INVALID_VALUE);
                c[fields[pname][0]][fields[pname][1]] = param;
                return undefined;
            }
            return base["glPixelStorei"](shadow, c, [pname, param]);
        },
        "glGetInteger64v": (shadow, c, [pname, data]) =>
        {
            query(shadow);
            const v = shadow.state_value(c, pname);
            if(!v) { fail(c, GL.INVALID_ENUM); return; }
            put64(data, h.state_kind(pname) === "n" ? v.map(x => x * 0x7FFFFFFF) : v);
        },
        "glGetIntegeri_v": (shadow, c, [target, index, data]) => { query(shadow); indexed(c, target, index, data, false); },
        "glGetInteger64i_v": (shadow, c, [target, index, data]) => { query(shadow); indexed(c, target, index, data, true); },
        // (GLES 3.1's; its own targets are gles31_state.js's, GLES 3.0's these)
        "glGetBooleani_v": (shadow, c, [target, index, data]) => { query(shadow); indexed(c, target, index, data, "b"); },

        // ---- buffers
        "glBindBuffer": (shadow, c, [target, name]) =>
        {
            if(!target_ok(c, target)) return fail(c, GL.INVALID_ENUM);
            if(name && !c.group.buffers.has(name)) c.group.buffers.set(name, new_buffer());
            set_buffer_binding(c, target, name);
            return undefined;
        },
        "glDeleteBuffers": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!name) continue;
                c.group.reserved.buffer.delete(name);
                if(!c.group.buffers.delete(name)) continue;
                for(const target of BUFFER_TARGETS.keys()) if(buffer_binding(c, target) === name) set_buffer_binding(c, target, 0);
                // (the bound vertex array's bindings alone: another keeps the name, GLES 3.0 2.10)
                const vao = c.vao ? c.vaos.get(c.vao) : c.default_vao;
                if(vao)
                {
                    for(const a of vao.attribs) if(a.buffer === name) a.buffer = 0;
                    if(vao.element_array_buffer === name) vao.element_array_buffer = 0;
                    // (GLES 3.1's vertex buffer binding points)
                    for(const b of vao.bindings || []) if(b.buffer === name) b.buffer = 0;
                }
                // (the indexed binding points: uniform blocks', GLES 3.1's storage blocks' and atomic counters')
                for(const b of [...c.uniform_bindings, ...c.storage_bindings || [], ...c.atomic_bindings || []])
                {
                    if(b.buffer === name) Object.assign(b, { buffer: 0, offset: 0, size: 0 });
                }
                for(const b of current_tf(c).bindings) if(b.buffer === name) Object.assign(b, { buffer: 0, offset: 0, size: 0 });
            }
            return undefined;
        },
        "glBufferData": (shadow, c, [target, size, data, usage]) =>
        {
            if(!target_ok(c, target) || !USAGES3.has(usage)) return fail(c, GL.INVALID_ENUM);
            if(size < 0) return fail(c, GL.INVALID_VALUE);
            const buffer = bound_buffer3(c, target);
            if(!buffer) return REFUSED;
            if(tf_bound_active(c, buffer_binding(c, target)) && target === GL.TRANSFORM_FEEDBACK_BUFFER) return fail(c, GL.INVALID_OPERATION);
            buffer.size = size;
            buffer.usage = usage;
            buffer.mapped = null;
            buffer.gpu_newer = false;
            const bytes = bytes_of(shadow, buffer);
            if(bytes && data) bytes.set(data.subarray(0, size));
            return undefined;
        },
        "glBufferSubData": (shadow, c, [target, offset, size, data]) =>
        {
            if(!target_ok(c, target)) return fail(c, GL.INVALID_ENUM);
            const buffer = bound_buffer3(c, target);
            if(!buffer) return REFUSED;
            if(offset < 0 || size < 0 || offset + size > buffer.size) return fail(c, GL.INVALID_VALUE);
            if(buffer.mapped) return fail(c, GL.INVALID_OPERATION);
            const bytes = bytes_of(shadow, buffer);
            if(bytes && data && !buffer.gpu_newer) bytes.set(data.subarray(0, size), offset);
            return undefined;
        },
        "glGetBufferParameteriv": (shadow, c, [target, pname, params]) =>
        {
            query(shadow);
            if(!target_ok(c, target)) { fail(c, GL.INVALID_ENUM); return; }
            const buffer = bound_buffer3(c, target);
            if(!buffer) return;
            const m = buffer.mapped;
            const values = { 0x8764: buffer.size, 0x8765: buffer.usage, 0x911F: m ? m.access : 0, 0x88BC: m ? 1 : 0,
                0x9120: m ? m.length : 0, 0x9121: m ? m.offset : 0 };
            if(!(pname in values) || pname === 0x9120 || pname === 0x9121) { fail(c, GL.INVALID_ENUM); return; }
            put(params, [values[pname]], "i", "i");
        },
        "glMapBufferRangeAEMU": (shadow, c, [target, offset, length, access, mapped]) =>
        {
            query(shadow);
            if(!target_ok(c, target)) { fail(c, GL.INVALID_ENUM); return; }
            const buffer = bound_buffer3(c, target);
            if(!buffer) return;
            if(offset < 0 || length < 0 || offset + length > buffer.size || access & ~0x3F) { fail(c, GL.INVALID_VALUE); return; }
            if(buffer.mapped || !length || !(access & 3) ||
                access & GL.MAP_READ_BIT && access & (GL.MAP_INVALIDATE_RANGE_BIT | GL.MAP_INVALIDATE_BUFFER_BIT | GL.MAP_UNSYNCHRONIZED_BIT) ||
                access & GL.MAP_FLUSH_EXPLICIT_BIT && !(access & GL.MAP_WRITE_BIT))
            {
                fail(c, GL.INVALID_OPERATION);
                return;
            }
            buffer.mapped = { offset, length, access };
            // (the mapped bytes: the CPU side's copy; of a buffer the page wrote since, the page's: the host asks for them, stale_map)
            const bytes = bytes_of(shadow, buffer);
            if(bytes && mapped && mapped.size) mapped.data.set(bytes.subarray(offset, offset + Math.min(length, mapped.size)));
            if(buffer.gpu_newer && bytes && !(access & (GL.MAP_INVALIDATE_RANGE_BIT | GL.MAP_INVALIDATE_BUFFER_BIT)))
            {
                shadow.stale_map = { name: buffer_binding(c, target), offset, length, bytes };
            }
        },
        "glUnmapBufferAEMU": (shadow, c, [target, offset, length, access, guest_buffer, out_res]) =>
        {
            if(!target_ok(c, target)) return fail(c, GL.INVALID_ENUM);
            const buffer = bound_buffer3(c, target);
            if(!buffer) return REFUSED;
            // (the mapping and its bytes come with the command, as gfxstream's decoder takes them: the page's shadow,
            // which never sees glMapBufferRangeAEMU (a query), takes them so)
            if(!buffer.mapped && !shadow.trusted) return fail(c, GL.INVALID_OPERATION);
            buffer.mapped = null;
            const bytes = bytes_of(shadow, buffer);
            if(bytes && guest_buffer && access & GL.MAP_WRITE_BIT && !(access & GL.MAP_FLUSH_EXPLICIT_BIT) && offset >= 0 && offset + length <= buffer.size)
            {
                bytes.set(guest_buffer.subarray(0, length), offset);
            }
            if(out_res && out_res.size) out_res.data[0] = 1;
            return undefined;
        },
        "glFlushMappedBufferRangeAEMU": (shadow, c, [target, offset, length, access, guest_buffer]) =>
        {
            if(!target_ok(c, target)) return fail(c, GL.INVALID_ENUM);
            const buffer = bound_buffer3(c, target);
            if(!buffer) return REFUSED;
            // (`offset` is the buffer's, not the mapping's: the encoder adds the mapping's, gfxstream's decoder says)
            const m = buffer.mapped;
            if(!shadow.trusted)
            {
                if(!m || !(m.access & GL.MAP_FLUSH_EXPLICIT_BIT)) return fail(c, GL.INVALID_OPERATION);
                if(offset < m.offset || length < 0 || offset + length > m.offset + m.length) return fail(c, GL.INVALID_VALUE);
            }
            const bytes = bytes_of(shadow, buffer);
            if(bytes && guest_buffer && offset >= 0 && offset + length <= buffer.size) bytes.set(guest_buffer.subarray(0, length), offset);
            return undefined;
        },
        "glCopyBufferSubData": (shadow, c, [read_target, write_target, read_offset, write_offset, size]) =>
        {
            if(!target_ok(c, read_target) || !target_ok(c, write_target)) return fail(c, GL.INVALID_ENUM);
            const from = bound_buffer3(c, read_target), to = from && bound_buffer3(c, write_target);
            if(!to) return REFUSED;
            if(read_offset < 0 || write_offset < 0 || size < 0 || read_offset + size > from.size || write_offset + size > to.size) return fail(c, GL.INVALID_VALUE);
            if(from === to && Math.abs(read_offset - write_offset) < size) return fail(c, GL.INVALID_VALUE);
            if(from.mapped || to.mapped) return fail(c, GL.INVALID_OPERATION);
            const a = bytes_of(shadow, from), b = bytes_of(shadow, to);
            if(a && b && !from.gpu_newer) b.set(a.slice(read_offset, read_offset + size), write_offset);
            else to.gpu_newer = to.gpu_newer || from.gpu_newer;
            return undefined;
        },
        "glBindBufferRange": (shadow, c, [target, index, buffer, offset, size]) => bind_buffer_indexed(shadow, c, target, index, buffer, offset, size, true),
        "glBindBufferBase": (shadow, c, [target, index, buffer]) => bind_buffer_indexed(shadow, c, target, index, buffer, 0, 0, false),

        // ---- vertex arrays and attributes
        "glGenVertexArrays": gen3("vao", c => c.vaos),
        "glBindVertexArray": (shadow, c, [name]) =>
        {
            if(name && !c.vaos.has(name))
            {
                if(!generated(shadow, c.reserved3.vao, name)) return fail(c, GL.INVALID_OPERATION);
                c.vaos.set(name, new_vao());
            }
            const vao = name ? c.vaos.get(name) : c.default_vao;
            const old = c.vao ? c.vaos.get(c.vao) : c.default_vao;
            old.element_array_buffer = c.element_array_buffer;
            c.attribs = vao.attribs;
            c.element_array_buffer = vao.element_array_buffer;
            c.vao = name;
            return undefined;
        },
        "glDeleteVertexArrays": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!name) continue;
                c.reserved3.vao.delete(name);
                if(!c.vaos.has(name)) continue;
                if(c.vao === name) H["glBindVertexArray"](shadow, c, [0]);
                c.vaos.delete(name);
            }
            return undefined;
        },
        "glIsVertexArray": (shadow, c, [name]) => { query(shadow); return c.vaos.has(name) ? 1 : 0; },
        "glVertexAttribPointerData": (shadow, c, args) =>
        {
            // (a client array: none in a vertex array object of GLES 3.0's)
            if(c.vao) return fail(c, GL.INVALID_OPERATION);
            return attrib3(c, args[0], args[1], args[2], args[3], args[4], 0, 0, false);
        },
        "glVertexAttribPointerOffset": (shadow, c, [index, size, type, normalized, stride, offset]) =>
        {
            if(c.vao && !c.array_buffer && offset) return fail(c, GL.INVALID_OPERATION);
            return attrib3(c, index, size, type, normalized, stride, c.array_buffer, offset, false);
        },
        "glVertexAttribIPointerDataAEMU": (shadow, c, [index, size, type, stride]) =>
        {
            if(c.vao) return fail(c, GL.INVALID_OPERATION);
            return attrib3(c, index, size, type, false, stride, 0, 0, true);
        },
        "glVertexAttribIPointerOffsetAEMU": (shadow, c, [index, size, type, stride, offset]) =>
        {
            if(c.vao && !c.array_buffer && offset) return fail(c, GL.INVALID_OPERATION);
            return attrib3(c, index, size, type, false, stride, c.array_buffer, offset, true);
        },
        "glVertexAttribDivisor": (shadow, c, [index, divisor]) =>
        {
            if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
            c.attribs[index].divisor = divisor >>> 0;
            return undefined;
        },
        "glVertexAttrib1f": float_attrib("glVertexAttrib1f"),
        "glVertexAttrib2f": float_attrib("glVertexAttrib2f"),
        "glVertexAttrib3f": float_attrib("glVertexAttrib3f"),
        "glVertexAttrib4f": float_attrib("glVertexAttrib4f"),
        "glVertexAttrib1fv": float_attrib("glVertexAttrib1fv"),
        "glVertexAttrib2fv": float_attrib("glVertexAttrib2fv"),
        "glVertexAttrib3fv": float_attrib("glVertexAttrib3fv"),
        "glVertexAttrib4fv": float_attrib("glVertexAttrib4fv"),
        "glVertexAttribI4i": (shadow, c, [index, ...v]) => attrib_current(c, index, v, "i"),
        "glVertexAttribI4ui": (shadow, c, [index, ...v]) => attrib_current(c, index, v.map(x => x >>> 0), "ui"),
        "glVertexAttribI4iv": (shadow, c, [index, v]) => attrib_current(c, index, i32s(v).slice(0, 4), "i"),
        "glVertexAttribI4uiv": (shadow, c, [index, v]) => attrib_current(c, index, i32s(v).slice(0, 4).map(x => x >>> 0), "ui"),
        "glGetVertexAttribIiv": (shadow, c, [index, pname, params]) => get_attrib3(shadow, c, index, pname, params, "i"),
        "glGetVertexAttribIuiv": (shadow, c, [index, pname, params]) => get_attrib3(shadow, c, index, pname, params, "ui"),
        "glGetVertexAttribiv": (shadow, c, [index, pname, params]) => get_attrib3(shadow, c, index, pname, params, "iv"),
        "glGetVertexAttribfv": (shadow, c, [index, pname, params]) => get_attrib3(shadow, c, index, pname, params, "f"),

        // ---- drawing
        "glDrawArrays": (shadow, c, [mode, first, count]) =>
        {
            if(first < 0) return mode_ok(c, mode) ? fail(c, GL.INVALID_VALUE) : fail(c, GL.INVALID_ENUM);
            return draw_checks(shadow, c, mode, count, 1, false);
        },
        "glDrawArraysInstanced": (shadow, c, [mode, first, count, instances]) =>
        {
            if(first < 0) return mode_ok(c, mode) ? fail(c, GL.INVALID_VALUE) : fail(c, GL.INVALID_ENUM);
            return draw_checks(shadow, c, mode, count, instances, false);
        },
        "glDrawElementsOffset": (shadow, c, [mode, count, type]) => elements3(shadow, c, mode, count, type, 1, true),
        "glDrawElementsData": (shadow, c, [mode, count, type]) => elements3(shadow, c, mode, count, type, 1, false),
        "glDrawElementsInstancedOffsetAEMU": (shadow, c, [mode, count, type, offset, instances]) => elements3(shadow, c, mode, count, type, instances, true),
        "glDrawElementsInstancedDataAEMU": (shadow, c, [mode, count, type, data, instances]) => elements3(shadow, c, mode, count, type, instances, false),
        "glDrawRangeElementsOffsetAEMU": (shadow, c, [mode, start, end, count, type]) =>
        {
            if(end < start) return fail(c, GL.INVALID_VALUE);
            return elements3(shadow, c, mode, count, type, 1, true);
        },
        "glDrawRangeElementsDataAEMU": (shadow, c, [mode, start, end, count, type]) =>
        {
            if(end < start) return fail(c, GL.INVALID_VALUE);
            return elements3(shadow, c, mode, count, type, 1, false);
        },
        "glClear": (shadow, c, [mask]) =>
        {
            if(mask & ~(0x4000 | 0x0100 | 0x0400)) return fail(c, GL.INVALID_VALUE);
            if(!complete(c, false)) return REFUSED;
            return undefined;
        },
        "glClearBufferiv": (shadow, c, [buffer, drawbuffer]) => clear_buffer(c, buffer, drawbuffer, "i"),
        "glClearBufferuiv": (shadow, c, [buffer, drawbuffer]) => clear_buffer(c, buffer, drawbuffer, "ui"),
        "glClearBufferfv": (shadow, c, [buffer, drawbuffer]) => clear_buffer(c, buffer, drawbuffer, "f"),
        "glClearBufferfi": (shadow, c, [buffer, drawbuffer]) => clear_buffer(c, buffer, drawbuffer, "fi"),
        "glReadPixels": (shadow, c, [x, y, width, height, format, type]) => read_pixels3(shadow, c, width, height, format, type, false),
        "glReadPixelsOffsetAEMU": (shadow, c, [x, y, width, height, format, type, offset]) =>
        {
            const buffer = c.group.buffers.get(c.buffers.pixel_pack);
            if(!buffer || buffer.mapped) return fail(c, GL.INVALID_OPERATION);
            const r = read_pixels3(shadow, c, width, height, format, type, true);
            if(r === REFUSED) return r;
            const needed = image_bytes3(width, height, 1, format, type, { alignment: c.pack_alignment, row_length: c.pack.row_length,
                image_height: 0, skip_pixels: c.pack.skip_pixels, skip_rows: c.pack.skip_rows, skip_images: 0 });
            if(offset < 0 || offset + needed > buffer.size || offset % Math.max(1, pixel_bytes(format, type) >= 4 ? 4 : pixel_bytes(format, type))) {
                return fail(c, GL.INVALID_OPERATION);
            }
            buffer.gpu_newer = true;
            return undefined;
        },

        // ---- textures
        "glActiveTexture": (shadow, c, [unit]) =>
        {
            const index = unit - 0x84C0;
            if(index < 0 || index >= MAX_UNITS) return fail(c, GL.INVALID_ENUM);
            c.active_texture = index;
            return undefined;
        },
        "glBindTexture": (shadow, c, [target, name]) =>
        {
            const slot = target_slot(target, c);
            if(slot < 0) return fail(c, GL.INVALID_ENUM);
            if(name)
            {
                const texture = c.group.textures.get(name);
                if(texture && texture.target !== target) return fail(c, GL.INVALID_OPERATION);
                if(!texture) c.group.textures.set(name, h.new_texture(target));
            }
            c.textures[c.active_texture][slot] = name;
            return undefined;
        },
        "glDeleteTextures": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!name) continue;
                c.group.reserved.texture.delete(name);
                const texture = c.group.textures.get(name);
                if(!c.group.textures.delete(name)) continue;
                for(const unit of c.textures) for(let i = 0; i < unit.length; i++) if(unit[i] === name) unit[i] = 0;
                for(const fbo of c.framebuffers.values())
                {
                    if(fbo.name !== c.framebuffer && fbo.name !== c.read_framebuffer) continue;
                    for(const [attachment, a] of fbo.attachments) if(a.type === GL.TEXTURE && a.name === name) fbo.attachments.delete(attachment);
                }
                h.detach(c, GL.TEXTURE, name);
                h.keep_orphan(c, GL.TEXTURE, c.group.textures, name, texture);
            }
            return undefined;
        },
        "glTexImage2D": (shadow, c, args) => tex_image(shadow, c, false, args),
        "glTexImage2DOffsetAEMU": (shadow, c, args) => tex_image(shadow, c, false, args),
        "glTexImage3D": (shadow, c, args) => tex_image(shadow, c, true, args),
        "glTexImage3DOffsetAEMU": (shadow, c, args) => tex_image(shadow, c, true, args),
        "glTexSubImage2D": (shadow, c, args) => tex_sub_image(shadow, c, false, args),
        "glTexSubImage2DOffsetAEMU": (shadow, c, args) => tex_sub_image(shadow, c, false, args),
        "glTexSubImage3D": (shadow, c, args) => tex_sub_image(shadow, c, true, args),
        "glTexSubImage3DOffsetAEMU": (shadow, c, args) => tex_sub_image(shadow, c, true, args),
        "glTexStorage2D": (shadow, c, [target, levels, internalformat, width, height]) =>
        {
            if(target !== GL.TEXTURE_2D && target !== GL.TEXTURE_CUBE_MAP) return fail(c, GL.INVALID_ENUM);
            return tex_storage(shadow, c, target, levels, internalformat, width, height, undefined);
        },
        "glTexStorage3D": (shadow, c, [target, levels, internalformat, width, height, depth]) =>
        {
            if(target !== GL.TEXTURE_3D && !layered(c, target)) return fail(c, GL.INVALID_ENUM);
            return tex_storage(shadow, c, target, levels, internalformat, width, height, depth);
        },
        "glCompressedTexImage2D": (shadow, c, args) => compressed_image(shadow, c, false, args),
        "glCompressedTexImage2DOffsetAEMU": (shadow, c, args) => compressed_image(shadow, c, false, args),
        "glCompressedTexImage3D": (shadow, c, args) => compressed_image(shadow, c, true, args),
        "glCompressedTexImage3DOffsetAEMU": (shadow, c, args) => compressed_image(shadow, c, true, args),
        "glCompressedTexSubImage2D": (shadow, c, args) => compressed_sub_image(shadow, c, false, args),
        "glCompressedTexSubImage2DOffsetAEMU": (shadow, c, args) => compressed_sub_image(shadow, c, false, args),
        "glCompressedTexSubImage3D": (shadow, c, args) => compressed_sub_image(shadow, c, true, args),
        "glCompressedTexSubImage3DOffsetAEMU": (shadow, c, args) => compressed_sub_image(shadow, c, true, args),
        "glCopyTexImage2D": (shadow, c, [target, level, internalformat, x, y, width, height, border]) =>
        {
            const face = face_of(target);
            if(face < 0) return fail(c, GL.INVALID_ENUM);
            const texture = bound_texture3(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
            if(!texture) return REFUSED;
            const info = format_info(internalformat) || ([0x1907, 0x1908].includes(internalformat) ? format_info(internalformat === 0x1907 ? 0x8051 : 0x8058) : null);
            if(!info) return fail(c, GL.INVALID_ENUM);
            if(!size_ok(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP, level, width, height, 1, border)) return REFUSED;
            if(texture.immutable) return fail(c, GL.INVALID_OPERATION);
            if(!complete(c, true)) return REFUSED;
            const source = read_image(c);
            if(!source || !copy_compatible(source.info, info) || source.samples) return fail(c, GL.INVALID_OPERATION);
            texture.images.set(image_key(face, level), { width, height, depth: 1, format: info.format, type: info.types[0],
                internal: info.sized ? info.value : internalformat, compressed: false });
            return undefined;
        },
        "glCopyTexSubImage2D": (shadow, c, [target, level, xoffset, yoffset, x, y, width, height]) =>
            copy_sub(shadow, c, target, level, xoffset, yoffset, 0, width, height, false),
        "glCopyTexSubImage3D": (shadow, c, [target, level, xoffset, yoffset, zoffset, x, y, width, height]) =>
            copy_sub(shadow, c, target, level, xoffset, yoffset, zoffset, width, height, true),
        "glGenerateMipmap": (shadow, c, [target]) =>
        {
            if(![GL.TEXTURE_2D, GL.TEXTURE_CUBE_MAP, GL.TEXTURE_3D, GL.TEXTURE_2D_ARRAY].includes(target) && !layered(c, target)) return fail(c, GL.INVALID_ENUM);
            const texture = bound_texture3(c, target);
            if(!texture) return REFUSED;
            const base_level = Math.min(texture.base_level || 0, 31);
            const faces = target === GL.TEXTURE_CUBE_MAP ? 6 : 1;
            const first = texture.images.get(image_key(0, base_level));
            if(!first) return fail(c, GL.INVALID_OPERATION);
            const info = first.compressed ? null : format_info(first.internal || first.format);
            if(!info || !info.filterable || info.sized && !renderable(info, c.color_buffer_float) || info.kind === "depth" || info.kind === "depth_stencil") {
                return fail(c, GL.INVALID_OPERATION);
            }
            for(let face = 0; face < faces; face++)
            {
                const image = texture.images.get(image_key(face, base_level));
                if(!image || image.width !== first.width || image.height !== first.height || image.internal !== first.internal) return fail(c, GL.INVALID_OPERATION);
            }
            const last = texture.immutable ? texture.immutable_levels - 1 : 31;
            for(let face = 0; face < faces; face++)
            {
                let w = first.width, hh = first.height, d = first.depth || 1;
                for(let level = base_level + 1; level <= last && (w > 1 || hh > 1 || target === GL.TEXTURE_3D && d > 1); level++)
                {
                    w = Math.max(1, w >> 1);
                    hh = Math.max(1, hh >> 1);
                    if(target === GL.TEXTURE_3D) d = Math.max(1, d >> 1);
                    texture.images.set(image_key(face, level), Object.assign({}, first, { width: w, height: hh, depth: d }));
                }
            }
            return undefined;
        },
        "glTexParameterf": (shadow, c, [target, pname, param]) => tex_parameter3(shadow, c, target, pname, [param], true),
        "glTexParameteri": (shadow, c, [target, pname, param]) => tex_parameter3(shadow, c, target, pname, [param], false),
        "glTexParameterfv": (shadow, c, [target, pname, params]) => tex_parameter3(shadow, c, target, pname, f32s(params), true, true),
        "glTexParameteriv": (shadow, c, [target, pname, params]) => tex_parameter3(shadow, c, target, pname, i32s(params), false, true),
        "glGetTexParameteriv": (shadow, c, [target, pname, params]) => get_tex_parameter3(shadow, c, target, pname, params, "i"),
        "glGetTexParameterfv": (shadow, c, [target, pname, params]) => get_tex_parameter3(shadow, c, target, pname, params, "f"),

        // ---- samplers
        "glGenSamplers": (shadow, c, [n, names]) =>
        {
            query(shadow);
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(let i = 0; i < n && 4 * i + 4 <= names.size; i++)
            {
                const name = c.group.fresh("sampler", c.group.samplers);
                c.group.samplers.set(name, new_sampler());
                names.view.setUint32(4 * i, name, true);
            }
            return undefined;
        },
        "glDeleteSamplers": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!c.group.samplers.delete(name)) continue;
                for(let i = 0; i < c.samplers.length; i++) if(c.samplers[i] === name) c.samplers[i] = 0;
            }
            return undefined;
        },
        "glIsSampler": (shadow, c, [name]) => { query(shadow); return c.group.samplers.has(name) ? 1 : 0; },
        "glBindSampler": (shadow, c, [unit, name]) =>
        {
            if(unit >= MAX_UNITS) return fail(c, GL.INVALID_VALUE);
            if(name && !c.group.samplers.has(name))
            {
                if(!shadow.trusted) return fail(c, GL.INVALID_OPERATION);
                c.group.samplers.set(name, new_sampler());
            }
            c.samplers[unit] = name;
            return undefined;
        },
        "glSamplerParameterf": (shadow, c, [s, pname, param]) => sampler_parameter(shadow, c, s, pname, [param], true),
        "glSamplerParameteri": (shadow, c, [s, pname, param]) => sampler_parameter(shadow, c, s, pname, [param], false),
        "glSamplerParameterfv": (shadow, c, [s, pname, params]) => sampler_parameter(shadow, c, s, pname, f32s(params), true, true),
        "glSamplerParameteriv": (shadow, c, [s, pname, params]) => sampler_parameter(shadow, c, s, pname, i32s(params), false, true),
        "glGetSamplerParameterfv": (shadow, c, [s, pname, params]) => get_sampler_parameter(shadow, c, s, pname, params, "f"),
        "glGetSamplerParameteriv": (shadow, c, [s, pname, params]) => get_sampler_parameter(shadow, c, s, pname, params, "i"),

        // ---- renderbuffers and framebuffers
        "glRenderbufferStorage": (shadow, c, [target, format, width, height]) => renderbuffer_storage(c, target, 0, format, width, height),
        "glRenderbufferStorageMultisample": (shadow, c, [target, samples, format, width, height]) =>
            renderbuffer_storage(c, target, samples, format, width, height),
        "glGetRenderbufferParameteriv": (shadow, c, [target, pname, params]) =>
        {
            if(pname === 0x8CAB)
            {
                query(shadow);
                if(target !== GL.RENDERBUFFER) { fail(c, GL.INVALID_ENUM); return undefined; }
                const rb = c.group.renderbuffers.get(c.renderbuffer);
                if(!rb) { fail(c, GL.INVALID_OPERATION); return undefined; }
                put(params, [rb.samples || 0], "i", "i");
                return undefined;
            }
            return base["glGetRenderbufferParameteriv"](shadow, c, [target, pname, params]);
        },
        "glGetInternalformativ": (shadow, c, [target, internalformat, pname, size, params]) =>
        {
            query(shadow);
            // (GLES 3.1's multisampled textures, 3.2's arrays: the renderbuffers' counts)
            const textures = c.version >= 31 && target === 0x9100 || c.version >= 32 && target === 0x9102;
            if(target !== GL.RENDERBUFFER && !textures || pname !== 0x80A9 && pname !== 0x9380) { fail(c, GL.INVALID_ENUM); return; }
            const info = format_info(internalformat) || (internalformat === 0x8D48 ? { kind: "stencil" } : null);
            if(!info || !(info.kind === "stencil" || renderable(info, c.color_buffer_float))) { fail(c, GL.INVALID_ENUM); return; }
            if(size < 0) { fail(c, GL.INVALID_VALUE); return; }
            const counts = info.kind === "int" || info.kind === "uint" ? [] : [4];
            if(pname === 0x9380) put(params, [counts.length], "i", "i");
            else put(params, counts.slice(0, Math.max(0, size)), "i", "i");
        },
        "glGenFramebuffers": (shadow, c, args) => base["glGenFramebuffers"](shadow, c, args),
        "glBindFramebuffer": (shadow, c, [target, name]) =>
        {
            if(framebuffer_of(c, target) < 0) return fail(c, GL.INVALID_ENUM);
            if(name && !c.framebuffers.has(name)) c.framebuffers.set(name, Object.assign(new_framebuffer3(), { name }));
            if(target !== GL.READ_FRAMEBUFFER) c.framebuffer = name;
            if(target !== GL.DRAW_FRAMEBUFFER) c.read_framebuffer = name;
            return undefined;
        },
        "glDeleteFramebuffers": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!name) continue;
                c.reserved_framebuffers.delete(name);
                if(!c.framebuffers.delete(name)) continue;
                if(c.framebuffer === name) c.framebuffer = 0;
                if(c.read_framebuffer === name) c.read_framebuffer = 0;
            }
            return undefined;
        },
        "glCheckFramebufferStatus": (shadow, c, [target]) =>
        {
            query(shadow);
            const name = framebuffer_of(c, target);
            if(name < 0) { fail(c, GL.INVALID_ENUM); return 0; }
            return status_of(c, name);
        },
        "glFramebufferRenderbuffer": (shadow, c, [target, attachment, rbtarget, name]) =>
        {
            const fb = framebuffer_of(c, target);
            if(fb < 0 || !attachment_ok(attachment) || rbtarget !== GL.RENDERBUFFER) return fail(c, GL.INVALID_ENUM);
            const fbo = c.framebuffers.get(fb);
            if(!fbo || name && !c.group.renderbuffers.has(name)) return fail(c, GL.INVALID_OPERATION);
            attach(fbo, attachment, name ? { type: GL.RENDERBUFFER, name, level: 0, face: 0, layer: 0 } : null);
            return undefined;
        },
        "glFramebufferTexture2D": (shadow, c, [target, attachment, textarget, name, level]) =>
        {
            const fb = framebuffer_of(c, target);
            if(fb < 0 || !attachment_ok(attachment)) return fail(c, GL.INVALID_ENUM);
            const fbo = c.framebuffers.get(fb);
            if(!fbo) return fail(c, GL.INVALID_OPERATION);
            if(!name) { attach(fbo, attachment, null); return undefined; }
            const face = face_of(textarget);
            if(face < 0) return fail(c, GL.INVALID_ENUM);
            const texture = c.group.textures.get(name);
            if(!texture || (texture.target === GL.TEXTURE_CUBE_MAP) !== (textarget !== GL.TEXTURE_2D) ||
                texture.target !== GL.TEXTURE_2D && texture.target !== GL.TEXTURE_CUBE_MAP)
            {
                return fail(c, GL.INVALID_OPERATION);
            }
            if(level < 0 || level >= MAX_LEVELS_2D) return fail(c, GL.INVALID_VALUE);
            attach(fbo, attachment, { type: GL.TEXTURE, name, level, face, layer: 0 });
            return undefined;
        },
        "glFramebufferTextureLayer": (shadow, c, [target, attachment, name, level, layer]) =>
        {
            const fb = framebuffer_of(c, target);
            if(fb < 0 || !attachment_ok(attachment)) return fail(c, GL.INVALID_ENUM);
            const fbo = c.framebuffers.get(fb);
            if(!fbo) return fail(c, GL.INVALID_OPERATION);
            if(!name) { attach(fbo, attachment, null); return undefined; }
            const texture = c.group.textures.get(name);
            if(!texture || texture.target !== GL.TEXTURE_3D && !layered(c, texture.target)) return fail(c, GL.INVALID_OPERATION);
            const max_layer = texture.target === GL.TEXTURE_3D ? LIMITS3.MAX_3D_TEXTURE_SIZE : LIMITS3.MAX_ARRAY_TEXTURE_LAYERS;
            if(layer < 0 || layer >= max_layer || level < 0 || level > max_level_of(texture.target)) return fail(c, GL.INVALID_VALUE);
            attach(fbo, attachment, { type: GL.TEXTURE, name, level, face: 0, layer });
            return undefined;
        },
        "glGetFramebufferAttachmentParameteriv": (shadow, c, [target, attachment, pname, params]) =>
        {
            query(shadow);
            const fb = framebuffer_of(c, target);
            if(fb < 0) { fail(c, GL.INVALID_ENUM); return; }
            const value = attachment_parameter(c, fb, attachment, pname);
            if(value !== null) put(params, [value], "i", "i");
        },
        "glDrawBuffers": (shadow, c, [n, bufs]) =>
        {
            const list = i32s(bufs).slice(0, Math.max(0, n));
            if(n < 0 || n > LIMITS3.MAX_DRAW_BUFFERS) return fail(c, GL.INVALID_VALUE);
            if(!c.framebuffer)
            {
                if(n !== 1 || list[0] !== GL.BACK && list[0] !== GL.NONE) return fail(c, GL.INVALID_OPERATION);
                c.default_draw_buffer = list[0];
                return undefined;
            }
            for(let i = 0; i < n; i++)
            {
                if(list[i] !== GL.NONE && list[i] !== GL.COLOR_ATTACHMENT0 + i)
                {
                    return color_attachment(list[i]) || list[i] === GL.BACK ? fail(c, GL.INVALID_OPERATION) : fail(c, GL.INVALID_ENUM);
                }
            }
            const fbo = c.framebuffers.get(c.framebuffer);
            fbo.draw_buffers = Array.from({ length: LIMITS3.MAX_DRAW_BUFFERS }, (_, i) => i < n ? list[i] : GL.NONE);
            return undefined;
        },
        "glReadBuffer": (shadow, c, [src]) =>
        {
            if(src !== GL.BACK && src !== GL.NONE && !(src >= GL.COLOR_ATTACHMENT0 && src < GL.COLOR_ATTACHMENT0 + 32)) return fail(c, GL.INVALID_ENUM);
            if(!c.read_framebuffer)
            {
                if(src !== GL.BACK && src !== GL.NONE) return fail(c, GL.INVALID_OPERATION);
                c.default_read_buffer = src;
                return undefined;
            }
            if(src === GL.BACK) return fail(c, GL.INVALID_OPERATION);
            if(src !== GL.NONE && !color_attachment(src)) return fail(c, GL.INVALID_OPERATION);
            c.framebuffers.get(c.read_framebuffer).read_buffer = src;
            return undefined;
        },
        "glBlitFramebuffer": (shadow, c, [sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, filter]) =>
        {
            if(mask & ~(0x4000 | 0x0100 | 0x0400)) return fail(c, GL.INVALID_VALUE);
            if(filter !== GL.NEAREST && filter !== GL.LINEAR) return fail(c, GL.INVALID_ENUM);
            if(filter === GL.LINEAR && mask & (0x0100 | 0x0400)) return fail(c, GL.INVALID_OPERATION);
            if(!complete(c, true)) return REFUSED;
            const source = read_image(c);
            if(mask & 0x4000 && source)
            {
                if(source.samples && (sx0 !== dx0 || sy0 !== dy0 || sx1 !== dx1 || sy1 !== dy1)) return fail(c, GL.INVALID_OPERATION);
                const kind = source.info.kind;
                if((kind === "int" || kind === "uint") && filter === GL.LINEAR) return fail(c, GL.INVALID_OPERATION);
                for(const image of draw_images(c))
                {
                    const dk = image.info.kind;
                    const integer = k => k === "int" || k === "uint";
                    if(integer(kind) !== integer(dk) || integer(kind) && kind !== dk) return fail(c, GL.INVALID_OPERATION);
                    if(source.samples && image.info.value !== source.info.value) return fail(c, GL.INVALID_OPERATION);
                }
                if(draw_images(c).some(i => i.samples)) return fail(c, GL.INVALID_OPERATION);
            }
            for(const [bit, point] of [[0x0100, GL.DEPTH_ATTACHMENT], [0x0400, GL.STENCIL_ATTACHMENT]])
            {
                if(!(mask & bit)) continue;
                const a = depth_stencil_image(c, c.read_framebuffer, point), b = depth_stencil_image(c, c.framebuffer, point);
                if(a && b && a.info.value !== b.info.value) return fail(c, GL.INVALID_OPERATION);
            }
            if(c.read_framebuffer && c.read_framebuffer === c.framebuffer) return fail(c, GL.INVALID_OPERATION);
            return undefined;
        },
        "glInvalidateFramebuffer": (shadow, c, [target, n, attachments]) => invalidate(c, target, n, attachments, 0, 0),
        "glInvalidateSubFramebuffer": (shadow, c, [target, n, attachments, x, y, width, height]) =>
            invalidate(c, target, n, attachments, width, height),

        // ---- programs: uniform blocks, transform feedback varyings, the rest of GLES 3.0's
        "glGetUniformBlockIndex": (shadow, c, [p, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return -1 >>> 0;
            if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return -1 >>> 0; }
            const text = text_of(name);
            const index = (program.info.blocks || []).findIndex(b => b.name === text || b.name + "[0]" === text);
            return index < 0 ? 0xFFFFFFFF : index;
        },
        "glGetActiveUniformBlockiv": (shadow, c, [p, index, pname, params]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const blocks = program.info && program.info.ok ? program.info.blocks || [] : [];
            if(index >= blocks.length) { fail(c, GL.INVALID_VALUE); return; }
            const b = blocks[index];
            const binding = (program.block_bindings || [])[index] || 0;
            const values = { 0x8A3F: [binding], 0x8A40: [b.size], 0x8A41: [b.name.length + 1], 0x8A42: [b.members.length],
                0x8A43: b.members, 0x8A44: [b.stages & 1 ? 1 : 0], 0x8A46: [b.stages & 16 ? 1 : 0] };
            if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
            put(params, values[pname], "i", "i");
        },
        "glGetActiveUniformBlockName": (shadow, c, [p, index, size, length, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const blocks = program.info && program.info.ok ? program.info.blocks || [] : [];
            if(index >= blocks.length || size < 0) { fail(c, GL.INVALID_VALUE); return; }
            const written = put_text(name, blocks[index].name);
            if(length && length.size) put(length, [written], "i", "i");
        },
        "glUniformBlockBinding": (shadow, c, [p, index, binding]) =>
        {
            const program = program_of(c, p);
            if(!program) return REFUSED;
            const blocks = program.info && program.info.ok ? program.info.blocks || [] : [];
            if(index >= blocks.length || binding >= LIMITS3.MAX_UNIFORM_BUFFER_BINDINGS) return fail(c, GL.INVALID_VALUE);
            program.block_bindings = program.block_bindings || blocks.map(b => b.binding);
            program.block_bindings[index] = binding;
            return undefined;
        },
        "glGetUniformIndicesAEMU": (shadow, c, [p, count, packed, length, indices]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            if(count < 0) { fail(c, GL.INVALID_VALUE); return; }
            const names = text_of(packed).split(";").slice(0, count);
            const uniforms = program.info && program.info.ok ? program.info.uniforms : [];
            put(indices, names.map(n =>
            {
                const i = uniforms.findIndex(u => u.name === n || u.base === n && u.name.endsWith("[0]"));
                return i < 0 ? -1 : i;
            }), "i", "i");
        },
        "glGetActiveUniformsiv": (shadow, c, [p, count, indices, pname, params]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            if(count < 0) { fail(c, GL.INVALID_VALUE); return; }
            const uniforms = program.info && program.info.ok ? program.info.uniforms : [];
            const list = i32s(indices).slice(0, count);
            if(list.some(i => i < 0 || i >= uniforms.length)) { fail(c, GL.INVALID_VALUE); return; }
            // (the offsets and strides of uniforms in buffers: blocks' members, atomic counters)
            const in_buffer = u => u.block_index >= 0 || u.opaque === "atomic";
            const field = { 0x8A37: u => u.type, 0x8A38: u => u.size, 0x8A39: u => u.name.length + 1, 0x8A3A: u => u.block_index,
                0x8A3B: u => in_buffer(u) ? u.offset : -1, 0x8A3C: u => !in_buffer(u) ? -1 : u.size > 1 || u.name.endsWith("]") ? u.array_stride : 0,
                0x8A3D: u => !in_buffer(u) ? -1 : u.columns ? u.matrix_stride : 0, 0x8A3E: u => u.row_major ? 1 : 0 }[pname];
            if(!field) { fail(c, GL.INVALID_ENUM); return; }
            put(params, list.map(i => field(uniforms[i])), "i", "i");
        },
        "glUniform1ui": uniform3(1, "ui", false),
        "glUniform2ui": uniform3(2, "ui", false),
        "glUniform3ui": uniform3(3, "ui", false),
        "glUniform4ui": uniform3(4, "ui", false),
        "glUniform1uiv": uniform3(1, "ui", true),
        "glUniform2uiv": uniform3(2, "ui", true),
        "glUniform3uiv": uniform3(3, "ui", true),
        "glUniform4uiv": uniform3(4, "ui", true),
        "glUniform1f": uniform3(1, "f", false), "glUniform2f": uniform3(2, "f", false), "glUniform3f": uniform3(3, "f", false),
        "glUniform4f": uniform3(4, "f", false),
        "glUniform1fv": uniform3(1, "f", true), "glUniform2fv": uniform3(2, "f", true), "glUniform3fv": uniform3(3, "f", true),
        "glUniform4fv": uniform3(4, "f", true),
        "glUniform1i": uniform3(1, "i", false), "glUniform2i": uniform3(2, "i", false), "glUniform3i": uniform3(3, "i", false),
        "glUniform4i": uniform3(4, "i", false),
        "glUniform1iv": uniform3(1, "i", true), "glUniform2iv": uniform3(2, "i", true), "glUniform3iv": uniform3(3, "i", true),
        "glUniform4iv": uniform3(4, "i", true),
        "glUniformMatrix2fv": uniform3(0, "m", true, 2, 2), "glUniformMatrix3fv": uniform3(0, "m", true, 3, 3),
        "glUniformMatrix4fv": uniform3(0, "m", true, 4, 4),
        "glUniformMatrix2x3fv": uniform3(0, "m", true, 2, 3), "glUniformMatrix3x2fv": uniform3(0, "m", true, 3, 2),
        "glUniformMatrix2x4fv": uniform3(0, "m", true, 2, 4), "glUniformMatrix4x2fv": uniform3(0, "m", true, 4, 2),
        "glUniformMatrix3x4fv": uniform3(0, "m", true, 3, 4), "glUniformMatrix4x3fv": uniform3(0, "m", true, 4, 3),
        "glGetUniformfv": get_uniform3("f"),
        "glGetUniformiv": get_uniform3("i"),
        "glGetUniformuiv": get_uniform3("ui"),
        "glGetFragDataLocation": (shadow, c, [p, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return -1;
            if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return -1; }
            const text = text_of(name);
            // (a fragment shader's outputs: a separable program of another stage reflects its own)
            if(program.info.spirv && !program.info.spirv.some(m => m.stage === "fragment")) return -1;
            const outputs = program.info.reflection && program.info.reflection.outputs || program.info.outputs || [];
            const o = outputs.find(x => x.name === text || x.name === text + "[0]" || x.name.replace(/\[0\]$/, "") === text.replace(/\[\d+\]$/, ""));
            if(!o) return -1;
            const element = /\[(\d+)\]$/.exec(text);
            return (o.location >= 0 ? o.location : 0) + (element ? +element[1] : 0);
        },
        "glGetProgramiv": (shadow, c, [p, pname, params]) =>
        {
            const own = [0x8C83, 0x8C7F, 0x8C76, 0x8A36, 0x8A35, 0x8257, 0x8741];
            if(!own.includes(pname)) return base["glGetProgramiv"](shadow, c, [p, pname, params]);
            query(shadow);
            const program = program_of(c, p);
            if(!program) return undefined;
            const info = program.info && program.info.ok ? program.info : null;
            const varyings = info ? info.tf_varyings || [] : [];
            const blocks = info ? info.blocks || [] : [];
            const longest = list => list.reduce((n, x) => Math.max(n, x.name.length + 1), 0);
            const value = { 0x8C83: varyings.length, 0x8C7F: info ? info.tf_mode || GL.INTERLEAVED_ATTRIBS : GL.INTERLEAVED_ATTRIBS,
                0x8C76: longest(varyings), 0x8A36: blocks.length, 0x8A35: longest(blocks), 0x8257: program.binary_hint || 0, 0x8741: 0 }[pname];
            put(params, [value], "i", "i");
            return undefined;
        },
        "glProgramParameteri": (shadow, c, [p, pname, value]) =>
        {
            const program = program_of(c, p);
            if(!program) return REFUSED;
            if(pname !== 0x8257) return fail(c, GL.INVALID_ENUM);
            if(value !== 0 && value !== 1) return fail(c, GL.INVALID_VALUE);
            program.binary_hint = value;
            return undefined;
        },
        "glGetProgramBinary": (shadow, c, [p, size, length]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            // (no binary formats: GL_NUM_PROGRAM_BINARY_FORMATS 0)
            if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return; }
            fail(c, GL.INVALID_OPERATION);
            if(length && length.size) put(length, [0], "i", "i");
        },
        "glProgramBinary": (shadow, c, [p]) =>
        {
            const program = program_of(c, p);
            if(!program) return REFUSED;
            return fail(c, GL.INVALID_ENUM);
        },
        "glTransformFeedbackVaryingsAEMU": (shadow, c, [p, count, packed, length, mode]) =>
        {
            const program = program_of(c, p);
            if(!program) return REFUSED;
            if(mode !== GL.INTERLEAVED_ATTRIBS && mode !== GL.SEPARATE_ATTRIBS) return fail(c, GL.INVALID_ENUM);
            if(count < 0 || mode === GL.SEPARATE_ATTRIBS && count > LIMITS3.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS) return fail(c, GL.INVALID_VALUE);
            program.tf_request = { names: text_of(packed).split(";").slice(0, count), mode };
            return undefined;
        },
        "glGetTransformFeedbackVarying": (shadow, c, [p, index, size, length, out_size, type, name]) =>
        {
            query(shadow);
            const program = program_of(c, p);
            if(!program) return;
            const varyings = program.info && program.info.ok ? program.info.tf_varyings || [] : [];
            if(index >= varyings.length || size < 0) { fail(c, GL.INVALID_VALUE); return; }
            const v = varyings[index];
            const written = put_text(name, v.name);
            if(length && length.size) put(length, [written], "i", "i");
            if(out_size && out_size.size) put(out_size, [v.size], "i", "i");
            if(type && type.size) put(type, [v.type], "i", "i");
        },

        // ---- transform feedback objects
        "glGenTransformFeedbacks": gen3("tf", c => c.tfs),
        "glDeleteTransformFeedbacks": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            const list = i32s(names).slice(0, n);
            if(list.some(name => name && c.tfs.has(name) && c.tfs.get(name).active)) return fail(c, GL.INVALID_OPERATION);
            for(const name of list)
            {
                if(!name) continue;
                c.reserved3.tf.delete(name);
                if(!c.tfs.delete(name)) continue;
                if(c.tf === name) c.tf = 0;
            }
            return undefined;
        },
        "glIsTransformFeedback": (shadow, c, [name]) => { query(shadow); return name && c.tfs.has(name) && c.tfs.get(name).bound_once ? 1 : 0; },
        "glBindTransformFeedback": (shadow, c, [target, name]) =>
        {
            if(target !== GL.TRANSFORM_FEEDBACK) return fail(c, GL.INVALID_ENUM);
            const tf = current_tf(c);
            if(tf.active && !tf.paused) return fail(c, GL.INVALID_OPERATION);
            if(name && !c.tfs.has(name))
            {
                if(!generated(shadow, c.reserved3.tf, name)) return fail(c, GL.INVALID_OPERATION);
                c.tfs.set(name, new_tf());
            }
            c.tf = name;
            c.tfs.get(name).bound_once = true;
            return undefined;
        },
        "glBeginTransformFeedback": (shadow, c, [mode]) =>
        {
            if(mode !== GL.POINTS && mode !== GL.LINES && mode !== GL.TRIANGLES) return fail(c, GL.INVALID_ENUM);
            const tf = current_tf(c);
            if(tf.active) return fail(c, GL.INVALID_OPERATION);
            const program = c.group.objects.get(c.program);
            const varyings = program && program.info && program.info.ok ? program.info.tf_varyings || [] : [];
            if(!varyings.length) return fail(c, GL.INVALID_OPERATION);
            const buffers = program.info.tf_mode === GL.INTERLEAVED_ATTRIBS ? 1 : varyings.length;
            for(let i = 0; i < buffers; i++) if(!tf.bindings[i].buffer) return fail(c, GL.INVALID_OPERATION);
            Object.assign(tf, { active: true, paused: false, mode, program: c.program, vertices: [0, 0, 0, 0] });
            return undefined;
        },
        "glEndTransformFeedback": (shadow, c) =>
        {
            const tf = current_tf(c);
            if(!tf.active) return fail(c, GL.INVALID_OPERATION);
            tf.active = tf.paused = false;
            return undefined;
        },
        "glPauseTransformFeedback": (shadow, c) =>
        {
            const tf = current_tf(c);
            if(!tf.active || tf.paused) return fail(c, GL.INVALID_OPERATION);
            tf.paused = true;
            return undefined;
        },
        "glResumeTransformFeedback": (shadow, c) =>
        {
            const tf = current_tf(c);
            if(!tf.active || !tf.paused || tf.program !== c.program) return fail(c, GL.INVALID_OPERATION);
            tf.paused = false;
            return undefined;
        },
        "glUseProgram": (shadow, c, args) =>
        {
            const tf = current_tf(c);
            if(tf.active && !tf.paused) return fail(c, GL.INVALID_OPERATION);
            return base["glUseProgram"](shadow, c, args);
        },
        "glLinkProgram": (shadow, c, args) =>
        {
            const tf = current_tf(c);
            if(tf.active && tf.program === args[0]) return fail(c, GL.INVALID_OPERATION);
            return base["glLinkProgram"](shadow, c, args);
        },

        // ---- queries
        "glGenQueries": gen3("query", c => c.queries),
        "glDeleteQueries": (shadow, c, [n, names]) =>
        {
            if(n < 0) return fail(c, GL.INVALID_VALUE);
            for(const name of i32s(names).slice(0, n))
            {
                if(!name) continue;
                c.reserved3.query.delete(name);
                for(const [target, active] of c.active_queries) if(active === name) c.active_queries.delete(target);
                c.queries.delete(name);
            }
            return undefined;
        },
        "glIsQuery": (shadow, c, [name]) => { query(shadow); return c.queries.has(name) ? 1 : 0; },
        "glBeginQuery": (shadow, c, [target, name]) =>
        {
            if(!QUERY_TARGETS.has(target)) return fail(c, GL.INVALID_ENUM);
            const occlusion = target !== GL.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
            if(c.active_queries.has(target) || occlusion && c.active_queries.has(target === GL.ANY_SAMPLES_PASSED ?
                GL.ANY_SAMPLES_PASSED_CONSERVATIVE : GL.ANY_SAMPLES_PASSED))
            {
                return fail(c, GL.INVALID_OPERATION);
            }
            if(!name || !c.queries.has(name) && !generated(shadow, c.reserved3.query, name)) return fail(c, GL.INVALID_OPERATION);
            const q = c.queries.get(name);
            if(q && q.target !== target) return fail(c, GL.INVALID_OPERATION);
            if([...c.active_queries.values()].includes(name)) return fail(c, GL.INVALID_OPERATION);
            c.queries.set(name, { target, result: 0, drawn: false, available: false, ended: false });
            c.active_queries.set(target, name);
            return undefined;
        },
        "glEndQuery": (shadow, c, [target]) =>
        {
            if(!QUERY_TARGETS.has(target)) return fail(c, GL.INVALID_ENUM);
            const name = c.active_queries.get(target);
            if(!name) return fail(c, GL.INVALID_OPERATION);
            c.active_queries.delete(target);
            const q = c.queries.get(name);
            q.ended = true;
            // (occlusion: nothing drawn is 0, else the page answers, query_read; the CPU side counts feedback's primitives)
            if(target !== GL.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN) q.result = q.drawn ? 1 : 0;
            q.available = true;
            return undefined;
        },
        "glGetQueryiv": (shadow, c, [target, pname, params]) =>
        {
            query(shadow);
            if(!QUERY_TARGETS.has(target) || pname !== 0x8865) { fail(c, GL.INVALID_ENUM); return; }
            put(params, [c.active_queries.get(target) || 0], "i", "i");
        },
        "glGetQueryObjectuiv": (shadow, c, [name, pname, params]) =>
        {
            query(shadow);
            if(pname !== 0x8866 && pname !== 0x8867) { fail(c, GL.INVALID_ENUM); return; }
            const q = c.queries.get(name);
            if(!q || !q.ended || [...c.active_queries.values()].includes(name)) { fail(c, GL.INVALID_OPERATION); return; }
            put(params, [pname === 0x8867 ? (q.available ? 1 : 0) : q.result], "i", "i");
            if(pname === 0x8866 && q.target !== GL.TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN && q.drawn && !q.answered) shadow.query_read = { name, query: q };
        },

        // ---- sync objects (GLES 3.0's own, not EGL's: done in order, as renderControl's)
        "glFenceSyncAEMU": (shadow, c, [condition, flags]) =>
        {
            query(shadow);
            if(condition !== 0x9117) { fail(c, GL.INVALID_ENUM); return 0; }
            if(flags) { fail(c, GL.INVALID_VALUE); return 0; }
            const handle = c.group.next_sync++;
            c.group.syncs.set(handle, { condition, flags });
            return handle;
        },
        "glClientWaitSyncAEMU": (shadow, c, [sync, flags]) =>
        {
            query(shadow);
            if(!c.group.syncs.has(sync)) { fail(c, GL.INVALID_VALUE); return 0x911D; }
            if(flags & ~1) { fail(c, GL.INVALID_VALUE); return 0x911D; }
            return 0x911A; // GL_ALREADY_SIGNALED
        },
        "glWaitSyncAEMU": (shadow, c, [sync, flags, timeout]) =>
        {
            if(!c.group.syncs.has(sync)) return fail(c, GL.INVALID_VALUE);
            // (GL_TIMEOUT_IGNORED, all ones: as u64 read into a number, 2 ** 64)
            if(flags || timeout < 2 ** 63) return fail(c, GL.INVALID_VALUE);
            return undefined;
        },
        "glDeleteSyncAEMU": (shadow, c, [sync]) =>
        {
            if(sync && !c.group.syncs.delete(sync)) return fail(c, GL.INVALID_VALUE);
            return undefined;
        },
        "glIsSyncAEMU": (shadow, c, [sync]) => { query(shadow); return c.group.syncs.has(sync) ? 1 : 0; },
        "glGetSyncivAEMU": (shadow, c, [sync, pname, size, length, values]) =>
        {
            query(shadow);
            const s = c.group.syncs.get(sync);
            if(!s) { fail(c, GL.INVALID_VALUE); return; }
            const value = { 0x9112: 0x9116, 0x9113: s.condition, 0x9114: 0x9119, 0x9115: s.flags }[pname];
            if(value === undefined) { fail(c, GL.INVALID_ENUM); return; }
            if(size < 0) { fail(c, GL.INVALID_VALUE); return; }
            if(size > 0) put(values, [value], "i", "i");
            if(length && length.size) put(length, [size > 0 ? 1 : 0], "i", "i");
        },
        "glGetStringi": (shadow, c, [name, index]) =>
        {
            query(shadow);
            if(name !== 0x1F03) { fail(c, GL.INVALID_ENUM); return 0; }
            if(index >= h.extensions(c).length) fail(c, GL.INVALID_VALUE);
            return 0;
        },
        "glGetCompressedTextureFormats": (shadow, c, [count, formats]) =>
        {
            query(shadow);
            put(formats, c.version >= 32 ? COMPRESSED_TEXTURE_FORMATS_32 : COMPRESSED_TEXTURE_FORMATS_3, "i", "i");
        },
    };

    // ---- the helpers above use

    function bind_buffer_indexed(shadow, c, target, index, name, offset, size, range)
    {
        if(target !== GL.UNIFORM_BUFFER && target !== GL.TRANSFORM_FEEDBACK_BUFFER) return fail(c, GL.INVALID_ENUM);
        const tf = current_tf(c);
        const max = target === GL.UNIFORM_BUFFER ? LIMITS3.MAX_UNIFORM_BUFFER_BINDINGS : LIMITS3.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
        if(index >= max) return fail(c, GL.INVALID_VALUE);
        if(range && name && (size <= 0 || offset < 0)) return fail(c, GL.INVALID_VALUE);
        if(target === GL.UNIFORM_BUFFER && range && name && offset % LIMITS3.UNIFORM_BUFFER_OFFSET_ALIGNMENT) return fail(c, GL.INVALID_VALUE);
        if(target === GL.TRANSFORM_FEEDBACK_BUFFER && range && name && (offset % 4 || size % 4)) return fail(c, GL.INVALID_VALUE);
        if(target === GL.TRANSFORM_FEEDBACK_BUFFER && tf.active) return fail(c, GL.INVALID_OPERATION);
        if(name && !c.group.buffers.has(name)) c.group.buffers.set(name, new_buffer());
        const list = target === GL.UNIFORM_BUFFER ? c.uniform_bindings : tf.bindings;
        list[index] = { buffer: name, offset: range ? offset : 0, size: range ? size : 0 };
        if(target === GL.UNIFORM_BUFFER) c.buffers.uniform = name;
        else c.buffers.transform_feedback = name;
        return undefined;
    }

    /** @param {boolean|string} wide 64-bit integers, or "b" booleans */
    function indexed(c, target, index, data, wide)
    {
        let list, field;
        switch(target)
        {
            case 0x8A28: list = c.uniform_bindings; field = "buffer"; break;
            case 0x8A29: list = c.uniform_bindings; field = "offset"; break;
            case 0x8A2A: list = c.uniform_bindings; field = "size"; break;
            case 0x8C8F: list = current_tf(c).bindings; field = "buffer"; break;
            case 0x8C84: list = current_tf(c).bindings; field = "offset"; break;
            case 0x8C85: list = current_tf(c).bindings; field = "size"; break;
            default: fail(c, GL.INVALID_ENUM); return;
        }
        if(index >= list.length) { fail(c, GL.INVALID_VALUE); return; }
        const value = list[index][field];
        if(wide === "b") put(data, [value], "b", "b");
        else if(wide) put64(data, [value]);
        else put(data, [value], "i", "i");
    }

    function attrib3(c, index, size, type, normalized, stride, buffer, offset, integer)
    {
        if(index >= MAX_ATTRIBS || size < 1 || size > 4 || stride < 0 || stride > 255) return fail(c, GL.INVALID_VALUE);
        const types = integer ? [0x1400, 0x1401, 0x1402, 0x1403, 0x1404, 0x1405] :
            [0x1400, 0x1401, 0x1402, 0x1403, 0x1404, 0x1405, 0x1406, 0x140B, 0x8D61, 0x140C, 0x8368, 0x8D9F];
        if(!types.includes(type)) return fail(c, GL.INVALID_ENUM);
        if((type === 0x8368 || type === 0x8D9F) && size !== 4) return fail(c, GL.INVALID_OPERATION);
        Object.assign(c.attribs[index], { size, type, normalized: !!normalized, stride, buffer, offset, integer });
        return undefined;
    }

    function attrib_current(c, index, values, kind)
    {
        if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
        c.attribs[index].current = values.slice(0, 4);
        c.attribs[index].current_type = kind;
        // (current values belong to the context, not to vertex arrays: GLES 3.0 table 6.6)
        c.current_values = c.current_values || [];
        c.current_values[index] = { values: values.slice(0, 4), kind };
        return undefined;
    }

    function get_attrib3(shadow, c, index, pname, params, as)
    {
        query(shadow);
        if(index >= MAX_ATTRIBS) { fail(c, GL.INVALID_VALUE); return; }
        const a = c.attribs[index];
        if(pname === 0x8626)
        {
            const current = c.current_values && c.current_values[index] || { values: a.current, kind: a.current_type || "f" };
            if(as === "f") put(params, current.values, "f", "f");
            else if(as === "ui") put(params, current.values.map(v => v >>> 0), "i", "i");
            else put(params, current.values.map(v => current.kind === "f" ? Math.round(v) : v | 0), "i", "i");
            return;
        }
        const values = { 0x8622: a.enabled ? 1 : 0, 0x8623: a.size, 0x8624: a.stride, 0x8625: a.type, 0x886A: a.normalized ? 1 : 0,
            0x889F: a.buffer, 0x88FD: a.integer ? 1 : 0, 0x88FE: a.divisor };
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [values[pname]], as === "f" ? "f" : "i", "i");
    }

    function elements3(shadow, c, mode, count, type, instances, from_buffer)
    {
        if(!mode_ok(c, mode) || !INDEX_TYPES.has(type)) return fail(c, GL.INVALID_ENUM);
        if(count < 0 || instances < 0) return fail(c, GL.INVALID_VALUE);
        if(from_buffer && !c.element_array_buffer) return fail(c, GL.INVALID_OPERATION);
        const buffer = c.group.buffers.get(c.element_array_buffer);
        if(buffer && buffer.mapped) return fail(c, GL.INVALID_OPERATION);
        return draw_checks(shadow, c, mode, count, instances, true, type);
    }

    function draw_images(c)
    {
        if(!c.framebuffer) return [{ info: { kind: "unorm", value: 0x8058 }, samples: 0 }];
        const fbo = c.framebuffers.get(c.framebuffer);
        return fbo.draw_buffers.filter(b => b !== GL.NONE).map(b => fbo.attachments.get(b)).filter(Boolean)
            .map(a => attachment_image(c, a)).filter(Boolean);
    }

    function depth_stencil_image(c, fb, point)
    {
        if(!fb) return null;
        const a = c.framebuffers.get(fb).attachments.get(point);
        return a ? attachment_image(c, a) : null;
    }

    function clear_buffer(c, buffer, drawbuffer, kind)
    {
        const ok = { i: [GL.COLOR, GL.STENCIL], ui: [GL.COLOR], f: [GL.COLOR, GL.DEPTH], fi: [GL.DEPTH_STENCIL] }[kind];
        if(!ok.includes(buffer)) return fail(c, GL.INVALID_ENUM);
        if(buffer === GL.COLOR ? drawbuffer < 0 || drawbuffer >= LIMITS3.MAX_DRAW_BUFFERS : drawbuffer !== 0) return fail(c, GL.INVALID_VALUE);
        if(!complete(c, false)) return REFUSED;
        return undefined;
    }

    function read_pixels3(shadow, c, width, height, format, type, pack)
    {
        if(width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        if(pixel_bytes(format, type) === 0) return fail(c, GL.INVALID_ENUM);
        if(!pack && c.buffers.pixel_pack) return fail(c, GL.INVALID_OPERATION);
        if(!complete(c, true)) return REFUSED;
        const source = read_image(c);
        if(!source) return fail(c, GL.INVALID_OPERATION);
        if(source.samples) return fail(c, GL.INVALID_OPERATION);
        // (GLES 3.0 4.3.2: RGBA with UNSIGNED_BYTE, FLOAT or INT/UNSIGNED_INT by the buffer's kind; or the implementation's pair)
        const kind = source.info.kind;
        const [rf, rt] = implementation_read(source.info);
        const normal = kind === "int" ? format === 0x8D99 && type === 0x1404 : kind === "uint" ? format === 0x8D99 && type === 0x1405 :
            kind === "float" ? format === 0x1908 && type === 0x1406 :
            format === 0x1908 && (type === 0x1401 || source.info.value === 0x8059 && type === 0x8368);
        if(!normal && !(format === rf && type === rt)) return fail(c, GL.INVALID_OPERATION);
        return undefined;
    }

    /** GL_IMPLEMENTATION_COLOR_READ_FORMAT and _TYPE of a read buffer's format: its own format and first type */
    function implementation_read(info)
    {
        if(!info || !info.format || !info.types) return [0x1908, 0x1401];
        return [info.format, info.types[info.types.length > 1 && info.types[0] === 0x1401 ? 1 : 0]];
    }

    function copy_compatible(source, dest)
    {
        // (GLES 3.0 table 3.15: the destination's channels a subset of the source's, the same kind of component)
        if(!source || !dest) return false;
        const integer = k => k === "int" || k === "uint";
        if(integer(source.kind) !== integer(dest.kind) || integer(source.kind) && source.kind !== dest.kind) return false;
        if(source.kind === "float" !== (dest.kind === "float") && dest.sized) return false;
        const channels = info => info.bits.slice(0, 4).map(b => b > 0);
        const s = channels(source), d = channels(dest);
        if(dest.value === 0x1909 || dest.value === 0x190A) d[0] = true;
        return d.every((need, i) => !need || s[i]);
    }

    function copy_sub(shadow, c, target, level, x, y, z, width, height, three)
    {
        let texture, face;
        if(three)
        {
            if(target !== GL.TEXTURE_3D && !layered(c, target)) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target);
            face = 0;
        }
        else
        {
            face = face_of(target);
            if(face < 0) return fail(c, GL.INVALID_ENUM);
            texture = bound_texture3(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
        }
        if(!texture) return REFUSED;
        if(level < 0 || level > max_level_of(target) || x < 0 || y < 0 || z < 0 || width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        const image = texture.images.get(image_key(face, level));
        if(!image) return fail(c, GL.INVALID_OPERATION);
        if(x + width > image.width || y + height > image.height || z >= (image.depth || 1)) return fail(c, GL.INVALID_VALUE);
        if(!complete(c, true)) return REFUSED;
        const source = read_image(c);
        if(image.compressed || !source || source.samples || !copy_compatible(source.info, format_info(image.internal || image.format))) {
            return fail(c, GL.INVALID_OPERATION);
        }
        return undefined;
    }

    /** @param {boolean=} vector glTexParameter*v's (TEXTURE_BORDER_COLOR is theirs alone) */
    function tex_parameter3(shadow, c, target, pname, params, float, vector = false)
    {
        const texture = bound_texture3(c, target);
        if(!texture) return REFUSED;
        const value = params[0];
        const integer = float ? Math.round(value) : value;
        const external = target === GL.TEXTURE_EXTERNAL_OES;
        // (GLES 3.1's multisampled textures (3.2's arrays): no sampler state, the base level 0)
        if(target === 0x9100 || target === 0x9102)
        {
            if(SAMPLER_STATES.has(pname)) return fail(c, GL.INVALID_ENUM);
            if(pname === 0x813C && integer !== 0) return fail(c, GL.INVALID_OPERATION);
        }
        switch(pname)
        {
            case 0x2801: // GL_TEXTURE_MIN_FILTER
                if(!MIN_FILTERS.has(integer) || external && integer !== GL.NEAREST && integer !== GL.LINEAR) return fail(c, GL.INVALID_ENUM);
                texture.min_filter = integer;
                return undefined;
            case 0x2800: // GL_TEXTURE_MAG_FILTER
                if(integer !== GL.NEAREST && integer !== GL.LINEAR) return fail(c, GL.INVALID_ENUM);
                texture.mag_filter = integer;
                return undefined;
            case 0x2802: case 0x2803: case 0x8072: // wrap s, t, r
                if(!wrap_ok(c, integer) || external && integer !== GL.CLAMP_TO_EDGE) return fail(c, GL.INVALID_ENUM);
                texture[{ 0x2802: "wrap_s", 0x2803: "wrap_t", 0x8072: "wrap_r" }[pname]] = integer;
                return undefined;
            case 0x813A: texture.min_lod = Math.fround(value); return undefined;
            case 0x813B: texture.max_lod = Math.fround(value); return undefined;
            case 0x813C: // GL_TEXTURE_BASE_LEVEL
                if(integer < 0 || external && integer !== 0) return fail(c, external ? GL.INVALID_OPERATION : GL.INVALID_VALUE);
                texture.base_level = integer;
                return undefined;
            case 0x813D: // GL_TEXTURE_MAX_LEVEL
                if(integer < 0) return fail(c, GL.INVALID_VALUE);
                texture.max_level = integer;
                return undefined;
            case 0x884C: // GL_TEXTURE_COMPARE_MODE
                if(integer !== 0 && integer !== 0x884E) return fail(c, GL.INVALID_ENUM);
                texture.compare_mode = integer;
                return undefined;
            case 0x884D: // GL_TEXTURE_COMPARE_FUNC
                if(!COMPARE_FUNCS.has(integer)) return fail(c, GL.INVALID_ENUM);
                texture.compare_func = integer;
                return undefined;
            case 0x8E42: case 0x8E43: case 0x8E44: case 0x8E45: // swizzles
                if(!SWIZZLES.has(integer)) return fail(c, GL.INVALID_ENUM);
                texture.swizzle = texture.swizzle || [0x1903, 0x1904, 0x1905, 0x1906];
                texture.swizzle[pname - 0x8E42] = integer;
                return undefined;
            case TEXTURE_BORDER_COLOR:
                // (the scalar calls take none, an external texture none; the guest's encoder may send fewer than four: the rest 0)
                if(c.version < 32 || !vector || external) return fail(c, GL.INVALID_ENUM);
                texture.border_color = border_color(params, float);
                return undefined;
            case DEPTH_STENCIL_TEXTURE_MODE:
                // (GLES 3.1's: a depth and stencil texture sampled as its depth or its stencil; dEQP's state reset sets it)
                if(c.version < 31) return fail(c, GL.INVALID_ENUM);
                if(integer !== 0x1902 && integer !== 0x1901) return fail(c, GL.INVALID_ENUM);
                texture.depth_stencil_mode = integer;
                return undefined;
        }
        return fail(c, GL.INVALID_ENUM);
    }

    function get_tex_parameter3(shadow, c, target, pname, params, as)
    {
        query(shadow);
        const texture = bound_texture3(c, target);
        if(!texture) return;
        const swizzle = texture.swizzle || [0x1903, 0x1904, 0x1905, 0x1906];
        const values = { 0x2801: texture.min_filter, 0x2800: texture.mag_filter, 0x2802: texture.wrap_s, 0x2803: texture.wrap_t,
            0x8072: texture.wrap_r || GL.REPEAT, 0x813A: texture.min_lod === undefined ? -1000 : texture.min_lod,
            0x813B: texture.max_lod === undefined ? 1000 : texture.max_lod, 0x813C: texture.base_level || 0,
            0x813D: texture.max_level === undefined ? 1000 : texture.max_level, 0x884C: texture.compare_mode || 0,
            0x884D: texture.compare_func || 0x0203, 0x8E42: swizzle[0], 0x8E43: swizzle[1], 0x8E44: swizzle[2], 0x8E45: swizzle[3],
            0x912F: texture.immutable ? 1 : 0, 0x82DF: texture.immutable_levels || 0 };
        if(target === GL.TEXTURE_EXTERNAL_OES) values[0x8D68] = 1; // GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES
        if(c.version >= 31) values[DEPTH_STENCIL_TEXTURE_MODE] = texture.depth_stencil_mode || 0x1902;
        if(pname === TEXTURE_BORDER_COLOR && c.version >= 32)
        {
            const color = texture.border_color || [0, 0, 0, 0];
            return void put(params, as === "f" ? color : color.map(border_int), as, as === "f" ? "f" : "i");
        }
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        // (the levels of detail are floats: an integer query rounds them, as the sampler's do)
        put(params, [as === "i" && (pname === 0x813A || pname === 0x813B) ? round(values[pname]) : values[pname]], as, as === "f" ? "f" : "i");
    }

    function sampler_parameter(shadow, c, s, pname, params, float, vector = false)
    {
        if(s && shadow.trusted && !c.group.samplers.has(s)) c.group.samplers.set(s, new_sampler());
        const sampler = c.group.samplers.get(s);
        if(!sampler) return fail(c, GL.INVALID_OPERATION);
        const value = params[0];
        const integer = float ? Math.round(value) : value;
        switch(pname)
        {
            case 0x2801: if(!MIN_FILTERS.has(integer)) return fail(c, GL.INVALID_ENUM); sampler.min_filter = integer; return undefined;
            case 0x2800: if(integer !== GL.NEAREST && integer !== GL.LINEAR) return fail(c, GL.INVALID_ENUM); sampler.mag_filter = integer; return undefined;
            case 0x2802: case 0x2803: case 0x8072:
                if(!wrap_ok(c, integer)) return fail(c, GL.INVALID_ENUM);
                sampler[{ 0x2802: "wrap_s", 0x2803: "wrap_t", 0x8072: "wrap_r" }[pname]] = integer;
                return undefined;
            case TEXTURE_BORDER_COLOR:
                if(c.version < 32 || !vector) return fail(c, GL.INVALID_ENUM);
                sampler.border_color = border_color(params, float);
                return undefined;
            case 0x813A: sampler.min_lod = Math.fround(value); return undefined;
            case 0x813B: sampler.max_lod = Math.fround(value); return undefined;
            case 0x884C: if(integer !== 0 && integer !== 0x884E) return fail(c, GL.INVALID_ENUM); sampler.compare_mode = integer; return undefined;
            case 0x884D: if(!COMPARE_FUNCS.has(integer)) return fail(c, GL.INVALID_ENUM); sampler.compare_func = integer; return undefined;
        }
        return fail(c, GL.INVALID_ENUM);
    }

    function get_sampler_parameter(shadow, c, s, pname, params, as)
    {
        query(shadow);
        const sampler = c.group.samplers.get(s);
        if(!sampler) { fail(c, GL.INVALID_OPERATION); return; }
        const values = { 0x2801: sampler.min_filter, 0x2800: sampler.mag_filter, 0x2802: sampler.wrap_s, 0x2803: sampler.wrap_t,
            0x8072: sampler.wrap_r, 0x813A: sampler.min_lod, 0x813B: sampler.max_lod, 0x884C: sampler.compare_mode, 0x884D: sampler.compare_func };
        if(pname === TEXTURE_BORDER_COLOR && c.version >= 32)
        {
            const color = sampler.border_color || [0, 0, 0, 0];
            return void put(params, as === "f" ? color : color.map(border_int), as, as === "f" ? "f" : "i");
        }
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [as === "i" && (pname === 0x813A || pname === 0x813B) ? round(values[pname]) : values[pname]], as, as === "f" ? "f" : "i");
    }

    function renderbuffer_storage(c, target, samples, format, width, height)
    {
        if(target !== GL.RENDERBUFFER) return fail(c, GL.INVALID_ENUM);
        const info = format_info(format);
        const stencil = format === 0x8D48;
        const legacy = h.renderbuffer_info(format);
        if(!stencil && !(info && renderable(info, c.color_buffer_float)) && !legacy) return fail(c, GL.INVALID_ENUM);
        if(samples < 0 || width < 0 || height < 0 || width > LIMITS3.MAX_TEXTURE_SIZE || height > LIMITS3.MAX_TEXTURE_SIZE) return fail(c, GL.INVALID_VALUE);
        if(samples > LIMITS3.MAX_SAMPLES || samples > 0 && info && (info.kind === "int" || info.kind === "uint")) return fail(c, GL.INVALID_OPERATION);
        const rb = c.group.renderbuffers.get(c.renderbuffer);
        if(!rb) return fail(c, GL.INVALID_OPERATION);
        Object.assign(rb, { width, height, format, image: 0, samples: samples ? LIMITS3.MAX_SAMPLES : 0 });
        return undefined;
    }

    function attachment_parameter(c, fb, attachment, pname)
    {
        // (the default framebuffer: its BACK, DEPTH and STENCIL)
        if(!fb)
        {
            if(attachment !== GL.BACK && attachment !== 0x1801 && attachment !== 0x1802) { fail(c, GL.INVALID_ENUM); return null; }
            const bits = h.framebuffer_bits(c);
            const has = attachment === GL.BACK ? true : attachment === 0x1801 ? bits[4] > 0 : bits[5] > 0;
            if(pname === 0x8CD0) return has ? GL.FRAMEBUFFER_DEFAULT : GL.NONE;
            if(!has) { fail(c, GL.INVALID_ENUM); return null; }
            const sizes = { 0x8212: bits[0], 0x8213: bits[1], 0x8214: bits[2], 0x8215: bits[3], 0x8216: bits[4], 0x8217: bits[5] };
            if(pname in sizes) return attachment === GL.BACK ? (pname <= 0x8215 ? sizes[pname] : 0) :
                attachment === 0x1801 ? (pname === 0x8216 ? bits[4] : 0) : pname === 0x8217 ? bits[5] : 0;
            if(pname === 0x8211) return attachment === GL.BACK ? F.UNSIGNED_NORMALIZED : attachment === 0x1801 ? F.UNSIGNED_NORMALIZED : F.UNSIGNED_INT;
            if(pname === 0x8210) return F.LINEAR;
            fail(c, GL.INVALID_ENUM);
            return null;
        }
        if(!attachment_ok(attachment)) { fail(c, GL.INVALID_ENUM); return null; }
        const fbo = c.framebuffers.get(fb);
        const point = attachment === GL.DEPTH_STENCIL_ATTACHMENT ? GL.DEPTH_ATTACHMENT : attachment;
        const a = fbo.attachments.get(point);
        if(attachment === GL.DEPTH_STENCIL_ATTACHMENT)
        {
            const s = fbo.attachments.get(GL.STENCIL_ATTACHMENT);
            if(a && s && (a.type !== s.type || a.name !== s.name)) { fail(c, GL.INVALID_OPERATION); return null; }
        }
        if(pname === 0x8CD0) return a ? a.type : GL.NONE;
        if(!a)
        {
            if(pname === 0x8CD1) return 0;
            fail(c, GL.INVALID_OPERATION);
            return null;
        }
        if(pname === 0x8CD1) return a.name;
        if(a.type === GL.TEXTURE)
        {
            if(pname === 0x8CD2) return a.level;
            if(pname === 0x8CD3)
            {
                // (a cube map's face, POSITIVE_X's too; NONE for any other texture)
                const texture = c.group.textures.get(a.name);
                return texture && texture.target === GL.TEXTURE_CUBE_MAP ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + a.face : 0;
            }
            if(pname === 0x8CD4) return a.layer || 0;
        }
        const image = attachment_image(c, a);
        const info = image && image.info;
        const bits = info ? info.bits : [0, 0, 0, 0, 0, 0];
        if(pname >= 0x8212 && pname <= 0x8217) return bits[pname - 0x8212];
        if(pname === 0x8211)
        {
            if(attachment === GL.DEPTH_STENCIL_ATTACHMENT) { fail(c, GL.INVALID_OPERATION); return null; }
            return info ? point === GL.STENCIL_ATTACHMENT ? F.UNSIGNED_INT : component_type(info) : GL.NONE;
        }
        if(pname === 0x8210) return info && info.srgb ? F.SRGB : F.LINEAR;
        fail(c, GL.INVALID_ENUM);
        return null;
    }

    function invalidate(c, target, n, attachments, width, height)
    {
        const fb = framebuffer_of(c, target);
        if(fb < 0) return fail(c, GL.INVALID_ENUM);
        if(n < 0 || width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        for(const a of i32s(attachments).slice(0, n))
        {
            if(fb ? !attachment_ok(a) && !(a >= GL.COLOR_ATTACHMENT0 && a < GL.COLOR_ATTACHMENT0 + 32) : ![0x1800, 0x1801, 0x1802].includes(a))
            {
                return fail(c, GL.INVALID_ENUM);
            }
            if(fb && a >= GL.COLOR_ATTACHMENT0 + LIMITS3.MAX_COLOR_ATTACHMENTS && a < GL.COLOR_ATTACHMENT0 + 32) return fail(c, GL.INVALID_OPERATION);
        }
        return undefined;
    }

    // (what gles31_state.js's handlers build on: not a command's name)
    H.helpers = { target_ok, buffer_binding, set_buffer_binding, bound_buffer3, generated, new_buffer, current_tf, program_of, status_of, complete,
        uniform3, bound_texture3, attachment_image, draw_checks, tf_bound_active, put64, get_attrib3, attrib3, bytes_of };
    return H;
}

/**
 * A pname of GLES 3.0's glGet in a GLES 3.x context, or null for one
 * GLES 2.0's answers (gles_shadow.js's state_value)
 * @return {?Array<number>}
 */
export function state_value3(shadow, c, pname)
{
    const L = LIMITS3;
    const tf = c.tfs.get(c.tf);
    const fbo = c.framebuffer && c.framebuffers.get(c.framebuffer);
    switch(pname)
    {
        case 0x80A8: case 0x80A9: // GL_SAMPLE_BUFFERS, GL_SAMPLES: the bound framebuffer's (the default one's: GL_STATE's)
        {
            if(!fbo) return null;
            let samples = 0;
            for(const a of fbo.attachments.values())
            {
                const rb = a.type === 0x8D41 ? c.group.renderbuffers.get(a.name) : null; // (GL_RENDERBUFFER)
                const texture = a.type === 0x8D41 ? null : c.group.textures.get(a.name);
                const image = texture && texture.images.get(a.face * 32 + a.level);
                samples = Math.max(samples, rb ? rb.samples || 0 : image ? image.samples || 0 : 0);
            }
            return [pname === 0x80A9 ? samples : samples > 0 ? 1 : 0];
        }
        // (GLES 3.1's minimums, which GLES 3.0's contexts have too: GL_STATE's are GLES 2.0's)
        case 0x8B4D: return [MAX_UNITS]; // GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
        case 0x8DFD: return [L.MAX_FRAGMENT_UNIFORM_COMPONENTS / 4]; // GL_MAX_FRAGMENT_UNIFORM_VECTORS
        case 0x821B: return [3]; // GL_MAJOR_VERSION
        case 0x821C: return [c.version % 10]; // GL_MINOR_VERSION
        case 0x821D: return [shadow.extensions3(c).length]; // GL_NUM_EXTENSIONS
        case 0x87FE: return [0]; // GL_NUM_PROGRAM_BINARY_FORMATS
        case 0x87FF: return []; // GL_PROGRAM_BINARY_FORMATS
        case 0x8073: return [L.MAX_3D_TEXTURE_SIZE];
        case 0x88FF: return [L.MAX_ARRAY_TEXTURE_LAYERS];
        case 0x8CDF: return [L.MAX_COLOR_ATTACHMENTS];
        case 0x8824: return [L.MAX_DRAW_BUFFERS];
        case 0x8D57: return [L.MAX_SAMPLES];
        case 0x8A2F: return [L.MAX_UNIFORM_BUFFER_BINDINGS];
        case 0x8A30: return [L.MAX_UNIFORM_BLOCK_SIZE];
        case 0x8A2B: return [L.MAX_VERTEX_UNIFORM_BLOCKS];
        case 0x8A2D: return [L.MAX_FRAGMENT_UNIFORM_BLOCKS];
        case 0x8A2E: return [L.MAX_COMBINED_UNIFORM_BLOCKS];
        case 0x8A31: return [L.MAX_VERTEX_UNIFORM_COMPONENTS + L.MAX_VERTEX_UNIFORM_BLOCKS * L.MAX_UNIFORM_BLOCK_SIZE / 4];
        case 0x8A33: return [L.MAX_FRAGMENT_UNIFORM_COMPONENTS + L.MAX_FRAGMENT_UNIFORM_BLOCKS * L.MAX_UNIFORM_BLOCK_SIZE / 4];
        case 0x8A34: return [L.UNIFORM_BUFFER_OFFSET_ALIGNMENT];
        case 0x8C8A: return [L.MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS];
        case 0x8C8B: return [L.MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS];
        case 0x8C80: return [L.MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS];
        case 0x9122: return [L.MAX_VERTEX_OUTPUT_COMPONENTS];
        case 0x9125: return [L.MAX_FRAGMENT_INPUT_COMPONENTS];
        case 0x8B4A: return [L.MAX_VERTEX_UNIFORM_COMPONENTS];
        case 0x8B49: return [L.MAX_FRAGMENT_UNIFORM_COMPONENTS];
        case 0x8B4B: return [L.MAX_VARYING_COMPONENTS];
        case 0x8D6B: return [L.MAX_ELEMENT_INDEX];
        case 0x80E8: case 0x80E9: return [0x7FFFFFFF]; // GL_MAX_ELEMENTS_VERTICES, _INDICES
        case 0x8905: return [L.MAX_PROGRAM_TEXEL_OFFSET];
        case 0x8904: return [L.MIN_PROGRAM_TEXEL_OFFSET];
        case 0x84FD: return [L.MAX_TEXTURE_LOD_BIAS];
        case 0x9111: return [0]; // GL_MAX_SERVER_WAIT_TIMEOUT
        case 0x8F36: return [c.buffers.copy_read];
        case 0x8F37: return [c.buffers.copy_write];
        case 0x88ED: return [c.buffers.pixel_pack];
        case 0x88EF: return [c.buffers.pixel_unpack];
        case 0x8A28: return [c.buffers.uniform];
        case 0x8C8F: return [c.buffers.transform_feedback];
        case 0x8E25: return [c.tf];
        case 0x8E24: return [tf.active ? 1 : 0];
        case 0x8E23: return [tf.paused ? 1 : 0];
        case 0x85B5: return [c.vao];
        case 0x8919: return [c.samplers[c.active_texture]];
        case 0x806A: return [c.textures[c.active_texture][SLOT.TEXTURE_3D]];
        case 0x8C1D: return [c.textures[c.active_texture][SLOT.TEXTURE_2D_ARRAY]];
        case 0x8CAA: return [c.read_framebuffer];
        case 0x0C02: return [c.read_framebuffer ? c.framebuffers.get(c.read_framebuffer).read_buffer : c.default_read_buffer];
        case 0x0CF2: return [c.unpack.row_length];
        case 0x806E: return [c.unpack.image_height];
        case 0x0CF4: return [c.unpack.skip_pixels];
        case 0x0CF3: return [c.unpack.skip_rows];
        case 0x806D: return [c.unpack.skip_images];
        case 0x0D02: return [c.pack.row_length];
        case 0x0D04: return [c.pack.skip_pixels];
        case 0x0D03: return [c.pack.skip_rows];
        case 0x8C89: return [c.enabled.has(0x8C89) ? 1 : 0];
        case 0x8D69: return [c.enabled.has(0x8D69) ? 1 : 0];
        case 0x8B8B: return [c.hints.get(0x8B8B)];
        case 0x84E8: return [L.MAX_TEXTURE_SIZE]; // GL_MAX_RENDERBUFFER_SIZE
        // (GLES 3.2's: ASTC's too)
        case 0x86A2: return [(c.version >= 32 ? COMPRESSED_TEXTURE_FORMATS_32 : COMPRESSED_TEXTURE_FORMATS_3).length];
        case 0x86A3: return c.version >= 32 ? COMPRESSED_TEXTURE_FORMATS_32 : COMPRESSED_TEXTURE_FORMATS_3;
        case 0x8B9A: case 0x8B9B: // GL_IMPLEMENTATION_COLOR_READ_TYPE, _FORMAT
        {
            const info = shadow.read_info3(c);
            if(!info) { shadow.read_error3 = true; return null; }
            return [pname === 0x8B9B ? info[0] : info[1]];
        }
    }
    if(pname >= 0x8825 && pname < 0x8825 + L.MAX_DRAW_BUFFERS)
    {
        const i = pname - 0x8825;
        return [fbo ? fbo.draw_buffers[i] : i === 0 ? c.default_draw_buffer : 0];
    }
    return null;
}

/** GLES 3.0's int64 state (glGet's i form clamps these) */
export const INT64_STATE = new Set([0x8D6B, 0x9111, 0x8A30, 0x8A31, 0x8A33]);
                                                    source/v64/src/gles/gles_batch.js                                                                   0000644 0000000 0000000 00000010541 00000000000 014037  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES batches (docs/gles-proxy-plan.md "渲染器通道", E2): what the GLES
// host sends the page, written with GX's writer (GXWriter, GLES_MAGIC:
// src/graphics_adapters/renderer_protocol.js has the records) and read
// back here: by the page's executor (E3) and by the tools that look at a
// recorded boot (tools/gles/batches.mjs).

import { GLES, GLES_MAGIC } from "../graphics_adapters/renderer_protocol.js";
import { command_of_opcode, decode_arguments } from "./gles_wire.js";

/** Each record's dwords, by name (gles_host.js writes them so) */
export const GLES_FIELDS = {
    COMMAND: ["conn", "ret", "length"],
    CONTEXT_CREATE: ["context", "config", "share", "api"],
    CONTEXT_DESTROY: ["context"],
    SURFACE_CREATE: ["surface", "config", "width", "height"],
    SURFACE_DESTROY: ["surface"],
    SURFACE_COLOR_BUFFER: ["surface", "color_buffer"],
    MAKE_CURRENT: ["conn", "context", "draw", "read"],
    COLOR_BUFFER_CREATE: ["color_buffer", "width", "height", "format"],
    COLOR_BUFFER_DESTROY: ["color_buffer"],
    COLOR_BUFFER_UPDATE: ["color_buffer", "x", "y", "width", "height", "format", "type", "length"],
    COLOR_BUFFER_READ: ["color_buffer", "x", "y", "width", "height", "format", "type", "request"],
    COLOR_BUFFER_BIND: ["conn", "color_buffer", "texture"],
    IMAGE_CREATE: ["image", "context", "target", "buffer"],
    IMAGE_DESTROY: ["image"],
    POST: ["color_buffer"],
    FLUSH_SURFACE: ["surface"],
    READ_PIXELS: ["conn", "request", "x", "y", "width", "height", "format", "type"],
    CONNECTION_CLOSE: ["conn"],
    PROGRAM_LINK: ["conn", "program", "length"],
    BUFFER_READ: ["conn", "request", "buffer", "offset", "length"],
    QUERY_READ: ["conn", "request", "query"],
};

/** Record names by opcode */
export const GLES_RECORD_NAMES = Object.fromEntries(Object.entries(GLES).map(([name, op]) => [op, name]));

/**
 * A record read back
 * @typedef {{op: number, name: string, bytes: (Uint8Array|undefined), command: (Object|undefined), args: (Array|undefined)}}
 */
export let GLESRecord;

/**
 * A batch's records, in order: each its fields by name; a command's bytes
 * (and with `decode`, the command and its arguments, gles_wire.js's), an
 * update's pixels. Throws on a batch that is not one.
 * @param {!Uint8Array} bytes
 * @param {boolean=} decode
 * @return {!Array<!Object>}
 */
export function read_gles_batch(bytes, decode)
{
    if(bytes.length < 16 || bytes.length % 4) throw new Error(`GLES batch: ${bytes.length} bytes`);
    const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2);
    if(words[0] !== GLES_MAGIC) throw new Error("GLES batch: magic " + words[0].toString(16));
    if(words[2] !== words.length) throw new Error(`GLES batch: ${words[2]} dwords in the header, ${words.length} sent`);
    const records = [];
    let at = 4;
    for(let i = 0; i < words[3]; i++)
    {
        if(at + 2 > words.length) throw new Error("GLES batch: record " + i + " is beyond its end");
        const op = words[at], body = words[at + 1];
        const name = GLES_RECORD_NAMES[op];
        const fields = GLES_FIELDS[name];
        if(!fields || at + 2 + body > words.length || body < fields.length) throw new Error(`GLES batch: record ${i}: op ${op}, ${body} dwords`);
        const record = { op, name };
        fields.forEach((field, j) => { record[field] = words[at + 2 + j]; });
        const length = name === "COMMAND" || name === "COLOR_BUFFER_UPDATE" || name === "PROGRAM_LINK" ? record.length : 0;
        if(length)
        {
            const start = (at + 2 + fields.length) * 4;
            if(start + length > (at + 2 + body) * 4) throw new Error(`GLES batch: record ${i}: ${length} bytes in ${body} dwords`);
            record.bytes = bytes.subarray(start, start + length);
            if(name === "COMMAND" && decode)
            {
                const view = new DataView(record.bytes.buffer, record.bytes.byteOffset, record.bytes.length);
                record.command = command_of_opcode(view.getUint32(0, true));
                if(!record.command) throw new Error(`GLES batch: record ${i}: opcode ${view.getUint32(0, true)}`);
                record.args = decode_arguments(record.command, record.bytes);
            }
        }
        records.push(record);
        at += 2 + body;
    }
    if(at !== words.length) throw new Error(`GLES batch: the records end at ${at} of ${words.length} dwords`);
    return records;
}
                                                                                                                                                               source/v64/src/gles/gles_caps.js                                                                    0000644 0000000 0000000 00000043110 00000000000 013702  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the GLES host says about itself (docs/gles-proxy-plan.md): its EGL
// configurations as renderControl packs them, its strings, the GLES
// implementation limits and the state's initial values that queries answer.
// The executor (E3) and the shadow state (E2) keep to the same numbers.

/** EGL's enums (EGL 1.4, EGL_KHR_image_base, EGL_ANDROID_recordable) */
export const EGL = {
    NONE: 0x3038, DONT_CARE: -1, TRUE: 1, FALSE: 0,
    BUFFER_SIZE: 0x3020, ALPHA_SIZE: 0x3021, BLUE_SIZE: 0x3022, GREEN_SIZE: 0x3023, RED_SIZE: 0x3024, DEPTH_SIZE: 0x3025,
    STENCIL_SIZE: 0x3026, CONFIG_CAVEAT: 0x3027, CONFIG_ID: 0x3028, LEVEL: 0x3029, MAX_PBUFFER_HEIGHT: 0x302A,
    MAX_PBUFFER_PIXELS: 0x302B, MAX_PBUFFER_WIDTH: 0x302C, NATIVE_RENDERABLE: 0x302D, NATIVE_VISUAL_ID: 0x302E,
    NATIVE_VISUAL_TYPE: 0x302F, PRESERVED_RESOURCES: 0x3030, SAMPLES: 0x3031, SAMPLE_BUFFERS: 0x3032, SURFACE_TYPE: 0x3033,
    TRANSPARENT_TYPE: 0x3034, TRANSPARENT_BLUE_VALUE: 0x3035, TRANSPARENT_GREEN_VALUE: 0x3036, TRANSPARENT_RED_VALUE: 0x3037,
    BIND_TO_TEXTURE_RGB: 0x3039, BIND_TO_TEXTURE_RGBA: 0x303A, MIN_SWAP_INTERVAL: 0x303B, MAX_SWAP_INTERVAL: 0x303C,
    LUMINANCE_SIZE: 0x303D, ALPHA_MASK_SIZE: 0x303E, COLOR_BUFFER_TYPE: 0x303F, RENDERABLE_TYPE: 0x3040,
    MATCH_NATIVE_PIXMAP: 0x3041, CONFORMANT: 0x3042, RECORDABLE_ANDROID: 0x3142, FRAMEBUFFER_TARGET_ANDROID: 0x3147,
    SLOW_CONFIG: 0x3050, NON_CONFORMANT_CONFIG: 0x3051, RGB_BUFFER: 0x308E, LUMINANCE_BUFFER: 0x308F,
    PBUFFER_BIT: 1, WINDOW_BIT: 4, OPENGL_ES_BIT: 1, OPENGL_ES2_BIT: 4, OPENGL_ES3_BIT: 0x40,
    VENDOR: 0x3053, VERSION: 0x3054, EXTENSIONS: 0x3055, CLIENT_APIS: 0x308D,
    CONDITION_SATISFIED_KHR: 0x30F6,
};

/**
 * The attributes of a configuration in renderControl's order (gfxstream's
 * host/gl/EmulatedEglConfig.cpp kConfigAttributes: the guest finds them by
 * the first row rcGetConfigs gives, so the order is the host's own)
 */
export const CONFIG_ATTRIBUTES = [
    EGL.DEPTH_SIZE, EGL.STENCIL_SIZE, EGL.RENDERABLE_TYPE, EGL.SURFACE_TYPE, EGL.CONFIG_ID, EGL.BUFFER_SIZE,
    EGL.ALPHA_SIZE, EGL.BLUE_SIZE, EGL.GREEN_SIZE, EGL.RED_SIZE, EGL.CONFIG_CAVEAT, EGL.LEVEL, EGL.MAX_PBUFFER_HEIGHT,
    EGL.MAX_PBUFFER_PIXELS, EGL.MAX_PBUFFER_WIDTH, EGL.NATIVE_RENDERABLE, EGL.NATIVE_VISUAL_ID, EGL.NATIVE_VISUAL_TYPE,
    EGL.PRESERVED_RESOURCES, EGL.SAMPLES, EGL.SAMPLE_BUFFERS, EGL.TRANSPARENT_TYPE, EGL.TRANSPARENT_BLUE_VALUE,
    EGL.TRANSPARENT_GREEN_VALUE, EGL.TRANSPARENT_RED_VALUE, EGL.BIND_TO_TEXTURE_RGB, EGL.BIND_TO_TEXTURE_RGBA,
    EGL.MIN_SWAP_INTERVAL, EGL.MAX_SWAP_INTERVAL, EGL.LUMINANCE_SIZE, EGL.ALPHA_MASK_SIZE, EGL.COLOR_BUFFER_TYPE,
    EGL.RECORDABLE_ANDROID, EGL.CONFORMANT,
];

/** The largest surface and texture (WebGPU's default maxTextureDimension2D is 8192) */
export const MAX_SIZE = 4096;

/** Android's HAL pixel formats, a configuration's EGL_NATIVE_VISUAL_ID (SurfaceFlinger matches it) */
const HAL_PIXEL_FORMAT = { RGBA_8888: 1, RGBX_8888: 2, RGB_565: 4 };

/**
 * The configurations: RGBA8888, RGBX8888 and RGB565, each without depth,
 * with 16- or 24-bit depth, and with 24-bit depth and 8-bit stencil; no
 * multisampling (E4). The guest's configuration is its index, its
 * EGL_CONFIG_ID the index plus 1.
 * @type {!Array<!Array<number>>} each in CONFIG_ATTRIBUTES' order
 */
export const CONFIGS = [];
for(const [r, g, b, a, visual] of [[8, 8, 8, 8, HAL_PIXEL_FORMAT.RGBA_8888], [8, 8, 8, 0, HAL_PIXEL_FORMAT.RGBX_8888],
    [5, 6, 5, 0, HAL_PIXEL_FORMAT.RGB_565]])
{
    for(const [depth, stencil] of [[0, 0], [16, 0], [24, 0], [24, 8]])
    {
        const values = new Map([
            [EGL.DEPTH_SIZE, depth], [EGL.STENCIL_SIZE, stencil], [EGL.RENDERABLE_TYPE, EGL.OPENGL_ES_BIT | EGL.OPENGL_ES2_BIT],
            [EGL.SURFACE_TYPE, EGL.WINDOW_BIT | EGL.PBUFFER_BIT], [EGL.CONFIG_ID, CONFIGS.length + 1],
            [EGL.BUFFER_SIZE, r + g + b + a], [EGL.ALPHA_SIZE, a], [EGL.BLUE_SIZE, b], [EGL.GREEN_SIZE, g], [EGL.RED_SIZE, r],
            [EGL.CONFIG_CAVEAT, EGL.NONE], [EGL.LEVEL, 0], [EGL.MAX_PBUFFER_HEIGHT, MAX_SIZE], [EGL.MAX_PBUFFER_PIXELS, MAX_SIZE * MAX_SIZE],
            [EGL.MAX_PBUFFER_WIDTH, MAX_SIZE], [EGL.NATIVE_RENDERABLE, EGL.FALSE], [EGL.NATIVE_VISUAL_ID, visual],
            [EGL.NATIVE_VISUAL_TYPE, EGL.NONE], [EGL.PRESERVED_RESOURCES, 0], [EGL.SAMPLES, 0], [EGL.SAMPLE_BUFFERS, 0],
            [EGL.TRANSPARENT_TYPE, EGL.NONE], [EGL.TRANSPARENT_BLUE_VALUE, 0], [EGL.TRANSPARENT_GREEN_VALUE, 0],
            [EGL.TRANSPARENT_RED_VALUE, 0], [EGL.BIND_TO_TEXTURE_RGB, a ? EGL.FALSE : EGL.TRUE], [EGL.BIND_TO_TEXTURE_RGBA, a ? EGL.TRUE : EGL.FALSE],
            [EGL.MIN_SWAP_INTERVAL, 0], [EGL.MAX_SWAP_INTERVAL, 1], [EGL.LUMINANCE_SIZE, 0], [EGL.ALPHA_MASK_SIZE, 0],
            [EGL.COLOR_BUFFER_TYPE, EGL.RGB_BUFFER], [EGL.RECORDABLE_ANDROID, EGL.TRUE], [EGL.CONFORMANT, EGL.OPENGL_ES_BIT | EGL.OPENGL_ES2_BIT],
        ]);
        CONFIGS.push(CONFIG_ATTRIBUTES.map(attribute => values.get(attribute)));
    }
}

/**
 * The configurations as a host of the GLES version answers them: GLES 3.x's
 * add EGL_OPENGL_ES3_BIT_KHR to EGL_RENDERABLE_TYPE and EGL_CONFORMANT (an
 * application asks for it to make a GLES 3 context, dEQP-GLES3 too)
 * @param {number} max_version 20, or 30 to 32
 * @return {!Array<!Array<number>>}
 */
export function configs_for(max_version)
{
    if(max_version < 30) return CONFIGS;
    if(!configs_for.es3)
    {
        const types = [CONFIG_ATTRIBUTES.indexOf(EGL.RENDERABLE_TYPE), CONFIG_ATTRIBUTES.indexOf(EGL.CONFORMANT)];
        configs_for.es3 = CONFIGS.map(config => config.map((value, i) => types.includes(i) ? value | EGL.OPENGL_ES3_BIT : value));
    }
    return configs_for.es3;
}

/** How eglChooseConfig compares an attribute (EGL 1.4, table 3.4): the default value and the rule */
const MATCH = new Map([
    [EGL.BUFFER_SIZE, [0, "atleast"]], [EGL.RED_SIZE, [0, "atleast"]], [EGL.GREEN_SIZE, [0, "atleast"]],
    [EGL.BLUE_SIZE, [0, "atleast"]], [EGL.LUMINANCE_SIZE, [0, "atleast"]], [EGL.ALPHA_SIZE, [0, "atleast"]],
    [EGL.ALPHA_MASK_SIZE, [0, "atleast"]], [EGL.BIND_TO_TEXTURE_RGB, [EGL.DONT_CARE, "exact"]],
    [EGL.BIND_TO_TEXTURE_RGBA, [EGL.DONT_CARE, "exact"]], [EGL.COLOR_BUFFER_TYPE, [EGL.RGB_BUFFER, "exact"]],
    [EGL.CONFIG_CAVEAT, [EGL.DONT_CARE, "exact"]], [EGL.CONFIG_ID, [EGL.DONT_CARE, "exact"]],
    [EGL.CONFORMANT, [0, "mask"]], [EGL.DEPTH_SIZE, [0, "atleast"]], [EGL.LEVEL, [0, "exact"]],
    [EGL.MAX_SWAP_INTERVAL, [EGL.DONT_CARE, "exact"]], [EGL.MIN_SWAP_INTERVAL, [EGL.DONT_CARE, "exact"]],
    [EGL.NATIVE_RENDERABLE, [EGL.DONT_CARE, "exact"]], [EGL.NATIVE_VISUAL_TYPE, [EGL.DONT_CARE, "exact"]],
    [EGL.RENDERABLE_TYPE, [EGL.OPENGL_ES_BIT, "mask"]], [EGL.SAMPLE_BUFFERS, [0, "atleast"]], [EGL.SAMPLES, [0, "atleast"]],
    [EGL.STENCIL_SIZE, [0, "atleast"]], [EGL.SURFACE_TYPE, [EGL.WINDOW_BIT, "mask"]], [EGL.TRANSPARENT_TYPE, [EGL.NONE, "exact"]],
    [EGL.TRANSPARENT_RED_VALUE, [EGL.DONT_CARE, "exact"]], [EGL.TRANSPARENT_GREEN_VALUE, [EGL.DONT_CARE, "exact"]],
    [EGL.TRANSPARENT_BLUE_VALUE, [EGL.DONT_CARE, "exact"]], [EGL.RECORDABLE_ANDROID, [EGL.DONT_CARE, "exact"]],
    // (every configuration is one: the guest's EGL answers EGL_TRUE for it)
    [EGL.FRAMEBUFFER_TARGET_ANDROID, [EGL.DONT_CARE, "true"]],
]);

/**
 * eglChooseConfig on the configurations (EGL 1.4, 3.4.1.2): the matching
 * configurations' indices in EGL's sort order. Attributes EGL ignores
 * (EGL_MAX_PBUFFER_*, EGL_NATIVE_VISUAL_ID) and unknown ones are ignored.
 * @param {!Array<number>} attribs pairs, up to EGL_NONE
 * @param {!Array<!Array<number>>=} configs configs_for's, CONFIGS unless given
 * @return {!Array<number>}
 */
export function choose_configs(attribs, configs = CONFIGS)
{
    const wanted = new Map([...MATCH].map(([attribute, [value]]) => [attribute, value]));
    for(let i = 0; i + 1 < attribs.length && attribs[i] !== EGL.NONE; i += 2) if(MATCH.has(attribs[i])) wanted.set(attribs[i], attribs[i + 1]);
    const value_of = (config, attribute) => configs[config][CONFIG_ATTRIBUTES.indexOf(attribute)];
    const matching = [];
    configs.forEach((config, index) =>
    {
        for(const [attribute, value] of wanted)
        {
            if(value === EGL.DONT_CARE) continue;
            const rule = MATCH.get(attribute)[1];
            if(rule === "true") { if(value !== EGL.TRUE) return; continue; }
            const own = value_of(index, attribute);
            if(rule === "atleast" ? own < value : rule === "mask" ? (own & value) !== value : own !== value) return;
        }
        matching.push(index);
    });
    // (the color bits counted: those asked for with a value above 0)
    const color = config => [EGL.RED_SIZE, EGL.GREEN_SIZE, EGL.BLUE_SIZE, EGL.ALPHA_SIZE]
        .reduce((sum, attribute) => sum + (wanted.get(attribute) > 0 ? value_of(config, attribute) : 0), 0);
    const caveat = config => [EGL.NONE, EGL.SLOW_CONFIG, EGL.NON_CONFORMANT_CONFIG].indexOf(value_of(config, EGL.CONFIG_CAVEAT));
    const keys = [caveat, config => value_of(config, EGL.COLOR_BUFFER_TYPE), config => -color(config),
        ...[EGL.BUFFER_SIZE, EGL.SAMPLE_BUFFERS, EGL.SAMPLES, EGL.DEPTH_SIZE, EGL.STENCIL_SIZE, EGL.ALPHA_MASK_SIZE,
            EGL.CONFIG_ID].map(attribute => config => value_of(config, attribute))];
    return matching.sort((x, y) =>
    {
        for(const key of keys) if(key(x) !== key(y)) return key(x) - key(y);
        return 0;
    });
}

/** The EGL strings rcQueryEGLString answers (the guest's EGL makes its own extension string) */
export const EGL_STRINGS = new Map([
    [EGL.VENDOR, "v86"],
    [EGL.VERSION, "1.4 v86"],
    [EGL.EXTENSIONS, "EGL_KHR_image_base EGL_KHR_gl_texture_2D_image EGL_ANDROID_recordable "],
    [EGL.CLIENT_APIS, "OpenGL_ES"],
]);

/** GL's string names */
const GL_VENDOR = 0x1F00;
const GL_RENDERER = 0x1F01;
const GL_VERSION = 0x1F02;
const GL_EXTENSIONS = 0x1F03;
const GL_SHADING_LANGUAGE_VERSION = 0x8B8C;

/**
 * The extensions each API's contexts have. A short list on purpose: each
 * is something E3 (GLES 2.0) or E4 (GLES 1.1) implements; more when an
 * application needs it. No host feature strings (ANDROID_EMU_*): no
 * checksums, GLES 2.0 at most (docs/gles-proxy-plan.md "协议与生成器").
 */
const EXTENSIONS = {
    1: ["GL_OES_EGL_image", "GL_OES_EGL_image_external", "GL_OES_compressed_ETC1_RGB8_texture", "GL_OES_element_index_uint",
        "GL_OES_framebuffer_object", "GL_OES_depth24", "GL_OES_packed_depth_stencil", "GL_OES_rgb8_rgba8", "GL_OES_texture_npot",
        "GL_OES_blend_func_separate", "GL_OES_blend_equation_separate", "GL_OES_blend_subtract",
        "GL_OES_draw_texture", "GL_OES_point_sprite", "GL_OES_point_size_array", "GL_EXT_texture_format_BGRA8888"],
    2: ["GL_OES_EGL_image", "GL_OES_EGL_image_external", "GL_OES_compressed_ETC1_RGB8_texture", "GL_OES_element_index_uint",
        "GL_OES_depth24", "GL_OES_packed_depth_stencil", "GL_OES_rgb8_rgba8", "GL_OES_texture_npot", "GL_OES_standard_derivatives",
        "GL_EXT_texture_format_BGRA8888"],
    // (GLES 3.x: GLES 2.0's, those 3.0 has in its core too: the guest's EGL makes a GLES 2.0 context one of the
    // highest version announced, and GLES 2.0 programs, dEQP-GLES2 among them, look for them; docs/gles3-plan.md)
    3: ["GL_OES_EGL_image", "GL_OES_EGL_image_external", "GL_OES_EGL_image_external_essl3", "GL_OES_compressed_ETC1_RGB8_texture",
        "GL_OES_element_index_uint", "GL_OES_depth24", "GL_OES_packed_depth_stencil", "GL_OES_rgb8_rgba8", "GL_OES_texture_npot",
        "GL_OES_standard_derivatives", "GL_EXT_texture_format_BGRA8888"],
};

/** GL_EXTENSIONS of GLES 3.x's contexts, as glGetStringi counts them */
export const EXTENSIONS_3 = EXTENSIONS[3];

/**
 * What rcGetGLString answers: the strings of the connection's current
 * context's API (1: GLES 1.1, 2: GLES 2.0, 30 to 32: GLES 3.0 to 3.2;
 * none current: 2.0's). The extensions end with the host's feature string
 * of the highest version announced (ANDROID_EMU_gles_max_version_3_*),
 * which the guest's libraries look for there (docs/gles3-plan.md).
 * @param {number} name
 * @param {number} api
 * @param {number=} max_version 20 to 32
 * @return {string} "" for a name it does not know
 */
export function gl_string(name, api, max_version)
{
    const es3 = api >= 30;
    switch(name)
    {
        case GL_VENDOR: return "v86";
        case GL_RENDERER: return "v86 GLES (WebGPU)";
        case GL_VERSION: return api === 1 ? "OpenGL ES-CM 1.1 v86" : es3 ? "OpenGL ES " + (api / 10).toFixed(1) + " v86" : "OpenGL ES 2.0 v86";
        case GL_EXTENSIONS:
        {
            const feature = max_version >= 30 ? "ANDROID_EMU_gles_max_version_" + (max_version / 10).toFixed(1).replace(".", "_") + " " : "";
            return EXTENSIONS[api === 1 ? 1 : es3 ? 3 : 2].join(" ") + " " + feature;
        }
        case GL_SHADING_LANGUAGE_VERSION: return api === 1 ? "" : es3 ? "OpenGL ES GLSL ES " + (api / 10).toFixed(2) : "OpenGL ES GLSL ES 1.00";
    }
    return "";
}

/** The compressed texture formats (GL_COMPRESSED_TEXTURE_FORMATS): ETC1 */
export const COMPRESSED_TEXTURE_FORMATS = [0x8D64];

/**
 * The implementation's limits and the state's initial values, by pname:
 * what glGet* answers before the shadow state (E2) tracks the value.
 * Values are numbers (booleans 0 or 1); the viewport and scissor box are
 * the draw surface's (gles_defaults.js).
 * @type {!Map<number, !Array<number>>}
 */
export const GL_STATE = new Map([
    // limits (GLES 2.0 table 6.18-6.20; WebGPU's defaults bound them)
    [0x0D33, [MAX_SIZE]], // GL_MAX_TEXTURE_SIZE
    [0x851C, [MAX_SIZE]], // GL_MAX_CUBE_MAP_TEXTURE_SIZE
    [0x84E8, [MAX_SIZE]], // GL_MAX_RENDERBUFFER_SIZE
    [0x0D3A, [MAX_SIZE, MAX_SIZE]], // GL_MAX_VIEWPORT_DIMS
    [0x8869, [16]], // GL_MAX_VERTEX_ATTRIBS
    [0x8DFB, [256]], // GL_MAX_VERTEX_UNIFORM_VECTORS
    [0x8DFC, [15]], // GL_MAX_VARYING_VECTORS
    [0x8DFD, [224]], // GL_MAX_FRAGMENT_UNIFORM_VECTORS
    [0x8B4D, [32]], // GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
    [0x8B4C, [16]], // GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS
    [0x8872, [16]], // GL_MAX_TEXTURE_IMAGE_UNITS
    [0x846D, [1, 256]], // GL_ALIASED_POINT_SIZE_RANGE
    [0x846E, [1, 1]], // GL_ALIASED_LINE_WIDTH_RANGE
    [0x0D50, [4]], // GL_SUBPIXEL_BITS
    [0x80A8, [0]], // GL_SAMPLE_BUFFERS
    [0x80A9, [0]], // GL_SAMPLES
    [0x86A2, [COMPRESSED_TEXTURE_FORMATS.length]], // GL_NUM_COMPRESSED_TEXTURE_FORMATS
    [0x86A3, COMPRESSED_TEXTURE_FORMATS], // GL_COMPRESSED_TEXTURE_FORMATS
    [0x8DF9, [0]], // GL_NUM_SHADER_BINARY_FORMATS
    [0x8DFA, [1]], // GL_SHADER_COMPILER
    [0x8B9A, [0x1401]], // GL_IMPLEMENTATION_COLOR_READ_TYPE: GL_UNSIGNED_BYTE
    [0x8B9B, [0x1908]], // GL_IMPLEMENTATION_COLOR_READ_FORMAT: GL_RGBA
    // GLES 1.1's (table 6.25-6.26)
    [0x0D31, [8]], // GL_MAX_LIGHTS
    [0x0D32, [6]], // GL_MAX_CLIP_PLANES
    [0x0D36, [16]], // GL_MAX_MODELVIEW_STACK_DEPTH
    [0x0D38, [2]], // GL_MAX_PROJECTION_STACK_DEPTH
    [0x0D39, [2]], // GL_MAX_TEXTURE_STACK_DEPTH
    [0x84E2, [4]], // GL_MAX_TEXTURE_UNITS
    [0x0B12, [1, 1]], // GL_SMOOTH_POINT_SIZE_RANGE
    [0x0B22, [1, 1]], // GL_SMOOTH_LINE_WIDTH_RANGE
    // initial values (GLES 2.0 tables 6.2-6.17, GLES 1.1's)
    [0x0B70, [0, 1]], // GL_DEPTH_RANGE
    [0x0B21, [1]], // GL_LINE_WIDTH
    [0x0B45, [0x0405]], // GL_CULL_FACE_MODE: GL_BACK
    [0x0B46, [0x0901]], // GL_FRONT_FACE: GL_CCW
    [0x80AA, [1]], // GL_SAMPLE_COVERAGE_VALUE
    [0x84E0, [0x84C0]], // GL_ACTIVE_TEXTURE: GL_TEXTURE0
    [0x84E1, [0x84C0]], // GL_CLIENT_ACTIVE_TEXTURE: GL_TEXTURE0
    [0x0C23, [1, 1, 1, 1]], // GL_COLOR_WRITEMASK
    [0x0B72, [1]], // GL_DEPTH_WRITEMASK
    [0x0B98, [-1]], // GL_STENCIL_WRITEMASK
    [0x8CA5, [-1]], // GL_STENCIL_BACK_WRITEMASK
    [0x0B73, [1]], // GL_DEPTH_CLEAR_VALUE
    [0x0B74, [0x0201]], // GL_DEPTH_FUNC: GL_LESS
    [0x80C9, [1]], // GL_BLEND_SRC_RGB: GL_ONE
    [0x80CB, [1]], // GL_BLEND_SRC_ALPHA: GL_ONE
    [0x0BE1, [1]], // GL_BLEND_SRC: GL_ONE
    [0x8009, [0x8006]], // GL_BLEND_EQUATION_RGB: GL_FUNC_ADD
    [0x883D, [0x8006]], // GL_BLEND_EQUATION_ALPHA: GL_FUNC_ADD
    [0x0B92, [0x0207]], // GL_STENCIL_FUNC: GL_ALWAYS
    [0x8800, [0x0207]], // GL_STENCIL_BACK_FUNC: GL_ALWAYS
    [0x0B93, [-1]], // GL_STENCIL_VALUE_MASK
    [0x8CA4, [-1]], // GL_STENCIL_BACK_VALUE_MASK
    [0x0B94, [0x1E00]], [0x0B95, [0x1E00]], [0x0B96, [0x1E00]], // GL_STENCIL_FAIL, _PASS_DEPTH_FAIL, _PASS_DEPTH_PASS: GL_KEEP
    [0x8801, [0x1E00]], [0x8802, [0x1E00]], [0x8803, [0x1E00]], // the back face's
    [0x0CF5, [4]], // GL_UNPACK_ALIGNMENT
    [0x0D05, [4]], // GL_PACK_ALIGNMENT
    [0x8192, [0x1100]], // GL_GENERATE_MIPMAP_HINT: GL_DONT_CARE
    [0x0C50, [0x1100]], [0x0C51, [0x1100]], [0x0C52, [0x1100]], [0x0C54, [0x1100]], // GLES 1.1's hints
    [0x0BA0, [0x1700]], // GL_MATRIX_MODE: GL_MODELVIEW
    [0x0B54, [0x1D01]], // GL_SHADE_MODEL: GL_SMOOTH
    [0x0B00, [1, 1, 1, 1]], // GL_CURRENT_COLOR
    [0x0B02, [0, 0, 1]], // GL_CURRENT_NORMAL
    [0x0B03, [0, 0, 0, 1]], // GL_CURRENT_TEXTURE_COORDS
    [0x0B11, [1]], // GL_POINT_SIZE
    [0x8127, [256]], // GL_POINT_SIZE_MAX
    [0x8128, [1]], // GL_POINT_FADE_THRESHOLD_SIZE
    [0x8129, [1, 0, 0]], // GL_POINT_DISTANCE_ATTENUATION
    [0x0BC1, [0x0207]], // GL_ALPHA_TEST_FUNC: GL_ALWAYS
    [0x0B65, [0x0800]], // GL_FOG_MODE: GL_EXP
    [0x0B62, [1]], // GL_FOG_DENSITY
    [0x0B64, [1]], // GL_FOG_END
    [0x0B53, [0.2, 0.2, 0.2, 1]], // GL_LIGHT_MODEL_AMBIENT
    [0x0BF0, [0x1503]], // GL_LOGIC_OP_MODE: GL_COPY
    [0x0BA3, [1]], [0x0BA4, [1]], [0x0BA5, [1]], // the matrix stacks' depths
    [0x0BA6, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], // GL_MODELVIEW_MATRIX
    [0x0BA7, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], // GL_PROJECTION_MATRIX
    [0x0BA8, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]], // GL_TEXTURE_MATRIX
]);

/** The capabilities enabled at first: GL_DITHER, GLES 1.1's GL_MULTISAMPLE */
export const GL_ENABLED_INITIALLY = [0x0BD0, 0x809D];
                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/gles/gles_formats.js                                                                 0000644 0000000 0000000 00000021311 00000000000 014426  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // OpenGL ES 2.0 and 1.1's enums and format rules that the shadow state
// (src/gles/gles_shadow.js) checks calls against and the executor (E3)
// stores images by: which format and type pairs TexImage2D takes, what a
// renderbuffer's internal format holds, which images a framebuffer can
// render to, the bytes of a row (pixel store alignment), the GL type of a
// GLSL type. With the extensions the host offers (gles_caps.js):
// OES_rgb8_rgba8, OES_depth24, OES_packed_depth_stencil,
// EXT_texture_format_BGRA8888, OES_compressed_ETC1_RGB8_texture,
// OES_element_index_uint, OES_texture_npot, OES_EGL_image(_external).

export const GL = {
    NO_ERROR: 0, INVALID_ENUM: 0x0500, INVALID_VALUE: 0x0501, INVALID_OPERATION: 0x0502, OUT_OF_MEMORY: 0x0505,
    INVALID_FRAMEBUFFER_OPERATION: 0x0506,
    FALSE: 0, TRUE: 1, NONE: 0,
    // primitives
    POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6,
    // types
    BYTE: 0x1400, UNSIGNED_BYTE: 0x1401, SHORT: 0x1402, UNSIGNED_SHORT: 0x1403, INT: 0x1404, UNSIGNED_INT: 0x1405,
    FLOAT: 0x1406, FIXED: 0x140C, HALF_FLOAT_OES: 0x8D61,
    UNSIGNED_SHORT_4_4_4_4: 0x8033, UNSIGNED_SHORT_5_5_5_1: 0x8034, UNSIGNED_SHORT_5_6_5: 0x8363,
    // formats
    DEPTH_COMPONENT: 0x1902, ALPHA: 0x1906, RGB: 0x1907, RGBA: 0x1908, LUMINANCE: 0x1909, LUMINANCE_ALPHA: 0x190A,
    BGRA_EXT: 0x80E1, ETC1_RGB8_OES: 0x8D64,
    RGBA4: 0x8056, RGB5_A1: 0x8057, RGB565: 0x8D62, RGB8_OES: 0x8051, RGBA8_OES: 0x8058, DEPTH_COMPONENT16: 0x81A5,
    DEPTH_COMPONENT24_OES: 0x81A6, STENCIL_INDEX8: 0x8D48, DEPTH24_STENCIL8_OES: 0x88F0,
    // objects and targets
    TEXTURE_2D: 0x0DE1, TEXTURE_CUBE_MAP: 0x8513, TEXTURE_CUBE_MAP_POSITIVE_X: 0x8515, TEXTURE_EXTERNAL_OES: 0x8D65,
    TEXTURE0: 0x84C0, ARRAY_BUFFER: 0x8892, ELEMENT_ARRAY_BUFFER: 0x8893, FRAMEBUFFER: 0x8D40, RENDERBUFFER: 0x8D41,
    TEXTURE: 0x1702, COLOR_ATTACHMENT0: 0x8CE0, DEPTH_ATTACHMENT: 0x8D00, STENCIL_ATTACHMENT: 0x8D20,
    STREAM_DRAW: 0x88E0, STATIC_DRAW: 0x88E4, DYNAMIC_DRAW: 0x88E8,
    VERTEX_SHADER: 0x8B31, FRAGMENT_SHADER: 0x8B30,
    // framebuffer status
    FRAMEBUFFER_COMPLETE: 0x8CD5, FRAMEBUFFER_INCOMPLETE_ATTACHMENT: 0x8CD6, FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: 0x8CD7,
    FRAMEBUFFER_INCOMPLETE_DIMENSIONS: 0x8CD9, FRAMEBUFFER_UNSUPPORTED: 0x8CDD,
    // texture parameters
    TEXTURE_MAG_FILTER: 0x2800, TEXTURE_MIN_FILTER: 0x2801, TEXTURE_WRAP_S: 0x2802, TEXTURE_WRAP_T: 0x2803,
    GENERATE_MIPMAP: 0x8191, TEXTURE_CROP_RECT_OES: 0x8B9D,
    NEAREST: 0x2600, LINEAR: 0x2601, NEAREST_MIPMAP_NEAREST: 0x2700, LINEAR_MIPMAP_NEAREST: 0x2701,
    NEAREST_MIPMAP_LINEAR: 0x2702, LINEAR_MIPMAP_LINEAR: 0x2703,
    REPEAT: 0x2901, CLAMP_TO_EDGE: 0x812F, MIRRORED_REPEAT: 0x8370,
    // pixel store
    UNPACK_ALIGNMENT: 0x0CF5, PACK_ALIGNMENT: 0x0D05,
};

/** The capabilities glEnable takes: GLES 2.0's */
export const CAPS_2 = new Set([0x0B44, 0x0BE2, 0x0BD0, 0x0B90, 0x0B71, 0x0C11, 0x8037, 0x809E, 0x80A0]);
/** GLES 1.1's: 2.0's (but none of them the sample ones' alpha) and the fixed function's */
export const CAPS_1 = new Set([0x0B44, 0x0BE2, 0x0BD0, 0x0B90, 0x0B71, 0x0C11, 0x8037, 0x809E, 0x80A0,
    0x0BC0, 0x0B50, 0x0B57, 0x0BA1, 0x0B60, 0x0BF2, 0x0B20, 0x0B10, 0x809D, 0x803A, 0x809F, 0x8861, 0x8513,
    0x4000, 0x4001, 0x4002, 0x4003, 0x4004, 0x4005, 0x4006, 0x4007, 0x3000, 0x3001, 0x3002, 0x3003, 0x3004, 0x3005,
    0x8074, 0x8075, 0x8076, 0x8078, 0x8B9C, 0x8842, 0x86AD, 0x8D65]);

/** TexImage2D's format and type pairs (format is also the internal format) and each texel's bytes */
const TEXTURE_TYPES = new Map([
    [GL.RGBA, new Map([[GL.UNSIGNED_BYTE, 4], [GL.UNSIGNED_SHORT_4_4_4_4, 2], [GL.UNSIGNED_SHORT_5_5_5_1, 2]])],
    [GL.RGB, new Map([[GL.UNSIGNED_BYTE, 3], [GL.UNSIGNED_SHORT_5_6_5, 2]])],
    [GL.LUMINANCE_ALPHA, new Map([[GL.UNSIGNED_BYTE, 2]])],
    [GL.LUMINANCE, new Map([[GL.UNSIGNED_BYTE, 1]])],
    [GL.ALPHA, new Map([[GL.UNSIGNED_BYTE, 1]])],
    [GL.BGRA_EXT, new Map([[GL.UNSIGNED_BYTE, 4]])],
]);
/** Every enum TexImage2D might name as a type: the others are INVALID_ENUM */
const TYPE_ENUMS = new Set([GL.BYTE, GL.UNSIGNED_BYTE, GL.SHORT, GL.UNSIGNED_SHORT, GL.INT, GL.UNSIGNED_INT, GL.FLOAT,
    GL.HALF_FLOAT_OES, GL.UNSIGNED_SHORT_4_4_4_4, GL.UNSIGNED_SHORT_5_5_5_1, GL.UNSIGNED_SHORT_5_6_5]);
const FORMAT_ENUMS = new Set([GL.DEPTH_COMPONENT, GL.ALPHA, GL.RGB, GL.RGBA, GL.LUMINANCE, GL.LUMINANCE_ALPHA, GL.BGRA_EXT]);

/**
 * TexImage2D's (and TexSubImage2D's) check of a format and type
 * @param {number} format
 * @param {number} type
 * @return {number} GL.NO_ERROR, INVALID_ENUM (an enum that is no format or
 *     no type) or INVALID_OPERATION (a pair GLES does not have)
 */
export function texture_format_error(format, type)
{
    if(!FORMAT_ENUMS.has(format) || !TYPE_ENUMS.has(type)) return GL.INVALID_ENUM;
    const types = TEXTURE_TYPES.get(format);
    return types && types.has(type) ? GL.NO_ERROR : GL.INVALID_OPERATION;
}

/** @return {number} a texel's bytes in the format and type (0: none) */
export function texel_bytes(format, type)
{
    const types = TEXTURE_TYPES.get(format);
    return types && types.get(type) || 0;
}

/**
 * The bytes of an image the guest sends or receives: rows padded to the
 * pixel store's alignment, the last row not
 * @param {number} width
 * @param {number} height
 * @param {number} bytes_per_texel
 * @param {number} alignment 1, 2, 4 or 8
 * @return {number}
 */
export function image_bytes(width, height, bytes_per_texel, alignment)
{
    if(width <= 0 || height <= 0) return 0;
    const row = width * bytes_per_texel;
    const stride = Math.ceil(row / alignment) * alignment;
    return stride * (height - 1) + row;
}

/** ETC1's bytes: 8 per 4 by 4 block */
export function etc1_bytes(width, height)
{
    return Math.ceil(width / 4) * Math.ceil(height / 4) * 8;
}

/**
 * The sizes of the color, depth and stencil an image holds: red, green,
 * blue, alpha, depth, stencil, and whether a framebuffer renders color into it
 * @typedef {{bits: !Array<number>, color: boolean, depth: boolean, stencil: boolean}}
 */
export let ImageKind;

/** Renderbuffers' internal formats (RenderbufferStorage) */
export const RENDERBUFFER_FORMATS = new Map([
    [GL.RGBA4, { bits: [4, 4, 4, 4, 0, 0], color: true, depth: false, stencil: false }],
    [GL.RGB5_A1, { bits: [5, 5, 5, 1, 0, 0], color: true, depth: false, stencil: false }],
    [GL.RGB565, { bits: [5, 6, 5, 0, 0, 0], color: true, depth: false, stencil: false }],
    [GL.RGB8_OES, { bits: [8, 8, 8, 0, 0, 0], color: true, depth: false, stencil: false }],
    [GL.RGBA8_OES, { bits: [8, 8, 8, 8, 0, 0], color: true, depth: false, stencil: false }],
    [GL.DEPTH_COMPONENT16, { bits: [0, 0, 0, 0, 16, 0], color: false, depth: true, stencil: false }],
    [GL.DEPTH_COMPONENT24_OES, { bits: [0, 0, 0, 0, 24, 0], color: false, depth: true, stencil: false }],
    [GL.STENCIL_INDEX8, { bits: [0, 0, 0, 0, 0, 8], color: false, depth: false, stencil: true }],
    [GL.DEPTH24_STENCIL8_OES, { bits: [0, 0, 0, 0, 24, 8], color: false, depth: true, stencil: true }],
]);

/**
 * A texture image's kind by its format and type (an EGL image's or a
 * color buffer's by its internal format: GL_RGBA, GL_RGB, ...)
 * @param {number} format
 * @param {number} type
 * @return {!ImageKind}
 */
export function texture_kind(format, type)
{
    const color = !(format === GL.LUMINANCE || format === GL.LUMINANCE_ALPHA || format === GL.ALPHA || format === GL.ETC1_RGB8_OES);
    let bits;
    switch(format)
    {
        case GL.RGBA: case GL.BGRA_EXT:
            bits = type === GL.UNSIGNED_SHORT_4_4_4_4 ? [4, 4, 4, 4] : type === GL.UNSIGNED_SHORT_5_5_5_1 ? [5, 5, 5, 1] : [8, 8, 8, 8];
            break;
        case GL.RGB: case GL.ETC1_RGB8_OES:
            bits = type === GL.UNSIGNED_SHORT_5_6_5 ? [5, 6, 5, 0] : [8, 8, 8, 0];
            break;
        case GL.ALPHA: bits = [0, 0, 0, 8]; break;
        case GL.LUMINANCE: bits = [8, 8, 8, 0]; break;
        case GL.LUMINANCE_ALPHA: bits = [8, 8, 8, 8]; break;
        default: bits = [8, 8, 8, 8];
    }
    return { bits: [...bits, 0, 0], color, depth: false, stencil: false };
}

/** The GL types of GLSL ES's types (glGetActiveUniform, glGetActiveAttrib) */
export const GLSL_TYPES = {
    "float": 0x1406, "vec2": 0x8B50, "vec3": 0x8B51, "vec4": 0x8B52, "int": 0x1404, "ivec2": 0x8B53, "ivec3": 0x8B54,
    "ivec4": 0x8B55, "bool": 0x8B56, "bvec2": 0x8B57, "bvec3": 0x8B58, "bvec4": 0x8B59, "mat2": 0x8B5A, "mat3": 0x8B5B,
    "mat4": 0x8B5C, "sampler2D": 0x8B5E, "samplerCube": 0x8B60, "samplerExternalOES": 0x8D66,
};

/** @return {number} the GL type of a sampler by its reflection's dim (and whether it is external) */
export function sampler_type(dim, external)
{
    return external ? GLSL_TYPES["samplerExternalOES"] : dim === "Cube" ? GLSL_TYPES["samplerCube"] : GLSL_TYPES["sampler2D"];
}
                                                                                                                                                                                                                                                                                                                       source/v64/src/gles/gles_formats3.js                                                                0000644 0000000 0000000 00000043130 00000000000 014514  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.0's texture and renderbuffer formats (docs/gles3-plan.md,
// "纹理、采样器与格式"): the sized internal formats of the GLES 3.0
// specification's tables 3.2, 3.13 and 3.14 with the format and types each
// takes, whether a framebuffer can render to it and a sampler filter it,
// its channels' bits, its components' type and its WebGPU format (the
// page's: L3). The shadow state (gles3_state.js) checks the guest's calls
// with it, the page's executor stores textures by it.

export const F = {
    // formats
    RED: 0x1903, RG: 0x8227, RGB: 0x1907, RGBA: 0x1908, RED_INTEGER: 0x8D94, RG_INTEGER: 0x8228, RGB_INTEGER: 0x8D98,
    RGBA_INTEGER: 0x8D99, DEPTH_COMPONENT: 0x1902, DEPTH_STENCIL: 0x84F9, LUMINANCE: 0x1909, LUMINANCE_ALPHA: 0x190A, ALPHA: 0x1906,
    BGRA_EXT: 0x80E1, STENCIL_INDEX: 0x1901,
    // types
    BYTE: 0x1400, UNSIGNED_BYTE: 0x1401, SHORT: 0x1402, UNSIGNED_SHORT: 0x1403, INT: 0x1404, UNSIGNED_INT: 0x1405, FLOAT: 0x1406,
    HALF_FLOAT: 0x140B, HALF_FLOAT_OES: 0x8D61, UNSIGNED_SHORT_4_4_4_4: 0x8033, UNSIGNED_SHORT_5_5_5_1: 0x8034,
    UNSIGNED_SHORT_5_6_5: 0x8363, UNSIGNED_INT_2_10_10_10_REV: 0x8368, UNSIGNED_INT_10F_11F_11F_REV: 0x8C3B,
    UNSIGNED_INT_5_9_9_9_REV: 0x8C3E, UNSIGNED_INT_24_8: 0x84FA, FLOAT_32_UNSIGNED_INT_24_8_REV: 0x8DAD,
    // component types (GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE)
    UNSIGNED_NORMALIZED: 0x8C17, SIGNED_NORMALIZED: 0x8F9C,
    LINEAR: 0x2601, SRGB: 0x8C40,
};

/**
 * The sized internal formats: [name, value, format, types, color-renderable,
 * texture-filterable, bits (r, g, b, a, depth, stencil), component kind,
 * WebGPU format (the page's; "rgba" variants where WebGPU has no 3- or
 * 1-channel one of the kind it needs)]
 */
const SIZED = [
    ["R8", 0x8229, F.RED, [F.UNSIGNED_BYTE], true, true, [8, 0, 0, 0, 0, 0], "unorm", "r8unorm"],
    ["R8_SNORM", 0x8F94, F.RED, [F.BYTE], false, true, [8, 0, 0, 0, 0, 0], "snorm", "r8snorm"],
    ["R16F", 0x822D, F.RED, [F.HALF_FLOAT, F.FLOAT], false, true, [16, 0, 0, 0, 0, 0], "float", "r16float"],
    ["R32F", 0x822E, F.RED, [F.FLOAT], false, false, [32, 0, 0, 0, 0, 0], "float", "r32float"],
    ["R8UI", 0x8232, F.RED_INTEGER, [F.UNSIGNED_BYTE], true, false, [8, 0, 0, 0, 0, 0], "uint", "r8uint"],
    ["R8I", 0x8231, F.RED_INTEGER, [F.BYTE], true, false, [8, 0, 0, 0, 0, 0], "int", "r8sint"],
    ["R16UI", 0x8234, F.RED_INTEGER, [F.UNSIGNED_SHORT], true, false, [16, 0, 0, 0, 0, 0], "uint", "r16uint"],
    ["R16I", 0x8233, F.RED_INTEGER, [F.SHORT], true, false, [16, 0, 0, 0, 0, 0], "int", "r16sint"],
    ["R32UI", 0x8236, F.RED_INTEGER, [F.UNSIGNED_INT], true, false, [32, 0, 0, 0, 0, 0], "uint", "r32uint"],
    ["R32I", 0x8235, F.RED_INTEGER, [F.INT], true, false, [32, 0, 0, 0, 0, 0], "int", "r32sint"],
    ["RG8", 0x822B, F.RG, [F.UNSIGNED_BYTE], true, true, [8, 8, 0, 0, 0, 0], "unorm", "rg8unorm"],
    ["RG8_SNORM", 0x8F95, F.RG, [F.BYTE], false, true, [8, 8, 0, 0, 0, 0], "snorm", "rg8snorm"],
    ["RG16F", 0x822F, F.RG, [F.HALF_FLOAT, F.FLOAT], false, true, [16, 16, 0, 0, 0, 0], "float", "rg16float"],
    ["RG32F", 0x8230, F.RG, [F.FLOAT], false, false, [32, 32, 0, 0, 0, 0], "float", "rg32float"],
    ["RG8UI", 0x8238, F.RG_INTEGER, [F.UNSIGNED_BYTE], true, false, [8, 8, 0, 0, 0, 0], "uint", "rg8uint"],
    ["RG8I", 0x8237, F.RG_INTEGER, [F.BYTE], true, false, [8, 8, 0, 0, 0, 0], "int", "rg8sint"],
    ["RG16UI", 0x823A, F.RG_INTEGER, [F.UNSIGNED_SHORT], true, false, [16, 16, 0, 0, 0, 0], "uint", "rg16uint"],
    ["RG16I", 0x8239, F.RG_INTEGER, [F.SHORT], true, false, [16, 16, 0, 0, 0, 0], "int", "rg16sint"],
    ["RG32UI", 0x823C, F.RG_INTEGER, [F.UNSIGNED_INT], true, false, [32, 32, 0, 0, 0, 0], "uint", "rg32uint"],
    ["RG32I", 0x823B, F.RG_INTEGER, [F.INT], true, false, [32, 32, 0, 0, 0, 0], "int", "rg32sint"],
    ["RGB8", 0x8051, F.RGB, [F.UNSIGNED_BYTE], true, true, [8, 8, 8, 0, 0, 0], "unorm", "rgba8unorm"],
    ["SRGB8", 0x8C41, F.RGB, [F.UNSIGNED_BYTE], false, true, [8, 8, 8, 0, 0, 0], "unorm", "rgba8unorm-srgb"],
    ["RGB565", 0x8D62, F.RGB, [F.UNSIGNED_BYTE, F.UNSIGNED_SHORT_5_6_5], true, true, [5, 6, 5, 0, 0, 0], "unorm", "rgba8unorm"],
    ["RGB8_SNORM", 0x8F96, F.RGB, [F.BYTE], false, true, [8, 8, 8, 0, 0, 0], "snorm", "rgba8snorm"],
    ["R11F_G11F_B10F", 0x8C3A, F.RGB, [F.UNSIGNED_INT_10F_11F_11F_REV, F.HALF_FLOAT, F.FLOAT], false, true, [11, 11, 10, 0, 0, 0], "float",
        "rg11b10ufloat"],
    ["RGB9_E5", 0x8C3D, F.RGB, [F.UNSIGNED_INT_5_9_9_9_REV, F.HALF_FLOAT, F.FLOAT], false, true, [9, 9, 9, 0, 0, 0], "float", "rgb9e5ufloat"],
    ["RGB16F", 0x881B, F.RGB, [F.HALF_FLOAT, F.FLOAT], false, true, [16, 16, 16, 0, 0, 0], "float", "rgba16float"],
    ["RGB32F", 0x8815, F.RGB, [F.FLOAT], false, false, [32, 32, 32, 0, 0, 0], "float", "rgba32float"],
    ["RGB8UI", 0x8D7D, F.RGB_INTEGER, [F.UNSIGNED_BYTE], false, false, [8, 8, 8, 0, 0, 0], "uint", "rgba8uint"],
    ["RGB8I", 0x8D8F, F.RGB_INTEGER, [F.BYTE], false, false, [8, 8, 8, 0, 0, 0], "int", "rgba8sint"],
    ["RGB16UI", 0x8D77, F.RGB_INTEGER, [F.UNSIGNED_SHORT], false, false, [16, 16, 16, 0, 0, 0], "uint", "rgba16uint"],
    ["RGB16I", 0x8D89, F.RGB_INTEGER, [F.SHORT], false, false, [16, 16, 16, 0, 0, 0], "int", "rgba16sint"],
    ["RGB32UI", 0x8D71, F.RGB_INTEGER, [F.UNSIGNED_INT], false, false, [32, 32, 32, 0, 0, 0], "uint", "rgba32uint"],
    ["RGB32I", 0x8D83, F.RGB_INTEGER, [F.INT], false, false, [32, 32, 32, 0, 0, 0], "int", "rgba32sint"],
    ["RGBA8", 0x8058, F.RGBA, [F.UNSIGNED_BYTE], true, true, [8, 8, 8, 8, 0, 0], "unorm", "rgba8unorm"],
    ["SRGB8_ALPHA8", 0x8C43, F.RGBA, [F.UNSIGNED_BYTE], true, true, [8, 8, 8, 8, 0, 0], "unorm", "rgba8unorm-srgb"],
    ["RGBA8_SNORM", 0x8F97, F.RGBA, [F.BYTE], false, true, [8, 8, 8, 8, 0, 0], "snorm", "rgba8snorm"],
    ["RGB5_A1", 0x8057, F.RGBA, [F.UNSIGNED_BYTE, F.UNSIGNED_SHORT_5_5_5_1, F.UNSIGNED_INT_2_10_10_10_REV], true, true, [5, 5, 5, 1, 0, 0],
        "unorm", "rgba8unorm"],
    ["RGBA4", 0x8056, F.RGBA, [F.UNSIGNED_BYTE, F.UNSIGNED_SHORT_4_4_4_4], true, true, [4, 4, 4, 4, 0, 0], "unorm", "rgba8unorm"],
    ["RGB10_A2", 0x8059, F.RGBA, [F.UNSIGNED_INT_2_10_10_10_REV], true, true, [10, 10, 10, 2, 0, 0], "unorm", "rgb10a2unorm"],
    ["RGBA16F", 0x881A, F.RGBA, [F.HALF_FLOAT, F.FLOAT], false, true, [16, 16, 16, 16, 0, 0], "float", "rgba16float"],
    ["RGBA32F", 0x8814, F.RGBA, [F.FLOAT], false, false, [32, 32, 32, 32, 0, 0], "float", "rgba32float"],
    ["RGBA8UI", 0x8D7C, F.RGBA_INTEGER, [F.UNSIGNED_BYTE], true, false, [8, 8, 8, 8, 0, 0], "uint", "rgba8uint"],
    ["RGBA8I", 0x8D8E, F.RGBA_INTEGER, [F.BYTE], true, false, [8, 8, 8, 8, 0, 0], "int", "rgba8sint"],
    ["RGB10_A2UI", 0x906F, F.RGBA_INTEGER, [F.UNSIGNED_INT_2_10_10_10_REV], true, false, [10, 10, 10, 2, 0, 0], "uint", "rgb10a2uint"],
    ["RGBA16UI", 0x8D76, F.RGBA_INTEGER, [F.UNSIGNED_SHORT], true, false, [16, 16, 16, 16, 0, 0], "uint", "rgba16uint"],
    ["RGBA16I", 0x8D88, F.RGBA_INTEGER, [F.SHORT], true, false, [16, 16, 16, 16, 0, 0], "int", "rgba16sint"],
    ["RGBA32I", 0x8D82, F.RGBA_INTEGER, [F.INT], true, false, [32, 32, 32, 32, 0, 0], "int", "rgba32sint"],
    ["RGBA32UI", 0x8D70, F.RGBA_INTEGER, [F.UNSIGNED_INT], true, false, [32, 32, 32, 32, 0, 0], "uint", "rgba32uint"],
    ["DEPTH_COMPONENT16", 0x81A5, F.DEPTH_COMPONENT, [F.UNSIGNED_SHORT, F.UNSIGNED_INT], false, false, [0, 0, 0, 0, 16, 0], "depth",
        "depth16unorm"],
    ["DEPTH_COMPONENT24", 0x81A6, F.DEPTH_COMPONENT, [F.UNSIGNED_INT], false, false, [0, 0, 0, 0, 24, 0], "depth", "depth24plus"],
    ["DEPTH_COMPONENT32F", 0x8CAC, F.DEPTH_COMPONENT, [F.FLOAT], false, false, [0, 0, 0, 0, 32, 0], "depth", "depth32float"],
    ["DEPTH24_STENCIL8", 0x88F0, F.DEPTH_STENCIL, [F.UNSIGNED_INT_24_8], false, false, [0, 0, 0, 0, 24, 8], "depth_stencil",
        "depth24plus-stencil8"],
    ["DEPTH32F_STENCIL8", 0x8CAD, F.DEPTH_STENCIL, [F.FLOAT_32_UNSIGNED_INT_24_8_REV], false, false, [0, 0, 0, 0, 32, 8], "depth_stencil",
        "depth32float-stencil8"],
];

/** @typedef {{name: string, value: number, format: number, types: !Array<number>, renderable: boolean, filterable: boolean,
 *     bits: !Array<number>, kind: string, webgpu: string, sized: boolean, compressed: boolean, srgb: boolean}} */
export let FormatInfo;

/** @type {!Map<number, !FormatInfo>} the sized internal formats */
export const SIZED_FORMATS = new Map(SIZED.map(([name, value, format, types, renderable, filterable, bits, kind, webgpu]) =>
    [value, { name, value, format, types, renderable, filterable, bits, kind, webgpu, sized: true, compressed: false,
        srgb: name.startsWith("SRGB") }]));

/** The unsized ones (table 3.3): format, the types each takes, the sized format each pair amounts to */
const UNSIZED = new Map([
    [F.RGBA, new Map([[F.UNSIGNED_BYTE, 0x8058], [F.UNSIGNED_SHORT_4_4_4_4, 0x8056], [F.UNSIGNED_SHORT_5_5_5_1, 0x8057]])],
    [F.RGB, new Map([[F.UNSIGNED_BYTE, 0x8051], [F.UNSIGNED_SHORT_5_6_5, 0x8D62]])],
    [F.LUMINANCE_ALPHA, new Map([[F.UNSIGNED_BYTE, F.LUMINANCE_ALPHA]])],
    [F.LUMINANCE, new Map([[F.UNSIGNED_BYTE, F.LUMINANCE]])],
    [F.ALPHA, new Map([[F.UNSIGNED_BYTE, F.ALPHA]])],
    [F.BGRA_EXT, new Map([[F.UNSIGNED_BYTE, F.BGRA_EXT]])],
]);

/** The legacy formats as FormatInfo (LUMINANCE, ALPHA, LUMINANCE_ALPHA, BGRA: rgba8 on the page, swizzled) */
const LEGACY = new Map([
    [F.LUMINANCE, { name: "LUMINANCE", value: F.LUMINANCE, format: F.LUMINANCE, types: [F.UNSIGNED_BYTE], renderable: false, filterable: true,
        bits: [8, 0, 0, 0, 0, 0], kind: "unorm", webgpu: "rgba8unorm", sized: false, compressed: false, srgb: false }],
    [F.ALPHA, { name: "ALPHA", value: F.ALPHA, format: F.ALPHA, types: [F.UNSIGNED_BYTE], renderable: false, filterable: true,
        bits: [0, 0, 0, 8, 0, 0], kind: "unorm", webgpu: "rgba8unorm", sized: false, compressed: false, srgb: false }],
    [F.LUMINANCE_ALPHA, { name: "LUMINANCE_ALPHA", value: F.LUMINANCE_ALPHA, format: F.LUMINANCE_ALPHA, types: [F.UNSIGNED_BYTE],
        renderable: false, filterable: true, bits: [8, 0, 0, 8, 0, 0], kind: "unorm", webgpu: "rgba8unorm", sized: false, compressed: false,
        srgb: false }],
    [F.BGRA_EXT, { name: "BGRA8_EXT", value: F.BGRA_EXT, format: F.BGRA_EXT, types: [F.UNSIGNED_BYTE], renderable: true, filterable: true,
        bits: [8, 8, 8, 8, 0, 0], kind: "unorm", webgpu: "rgba8unorm", sized: false, compressed: false, srgb: false }],
]);

/** The compressed formats of GLES 3.0 (ETC2 and EAC), and ETC1: [value, name, block bytes, channels, WebGPU's format] */
const COMPRESSED = [
    [0x9270, "COMPRESSED_R11_EAC", 8, 1, "eac-r11unorm"], [0x9271, "COMPRESSED_SIGNED_R11_EAC", 8, 1, "eac-r11snorm"],
    [0x9272, "COMPRESSED_RG11_EAC", 16, 2, "eac-rg11unorm"], [0x9273, "COMPRESSED_SIGNED_RG11_EAC", 16, 2, "eac-rg11snorm"],
    [0x9274, "COMPRESSED_RGB8_ETC2", 8, 3, "etc2-rgb8unorm"], [0x9275, "COMPRESSED_SRGB8_ETC2", 8, 3, "etc2-rgb8unorm-srgb"],
    [0x9276, "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2", 8, 4, "etc2-rgb8a1unorm"],
    [0x9277, "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2", 8, 4, "etc2-rgb8a1unorm-srgb"],
    [0x9278, "COMPRESSED_RGBA8_ETC2_EAC", 16, 4, "etc2-rgba8unorm"], [0x9279, "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC", 16, 4, "etc2-rgba8unorm-srgb"],
    [0x8D64, "ETC1_RGB8_OES", 8, 3, "etc2-rgb8unorm"],
];
/** GLES 3.2's ASTC (LDR): [value, block width, block height], the sRGB ones 0x20 after; 16 bytes a block */
const ASTC = [[0x93B0, 4, 4], [0x93B1, 5, 4], [0x93B2, 5, 5], [0x93B3, 6, 5], [0x93B4, 6, 6], [0x93B5, 8, 5], [0x93B6, 8, 6], [0x93B7, 8, 8],
    [0x93B8, 10, 5], [0x93B9, 10, 6], [0x93BA, 10, 8], [0x93BB, 10, 10], [0x93BC, 12, 10], [0x93BD, 12, 12]];
/** @type {!Map<number, {name: string, block_bytes: number, channels: number, webgpu: string, block_width: number, block_height: number}>} */
export const COMPRESSED_FORMATS = new Map([
    ...COMPRESSED.map(([value, name, block_bytes, channels, webgpu]) => [value, { name, block_bytes, channels, webgpu, block_width: 4, block_height: 4 }]),
    ...ASTC.flatMap(([value, w, h]) => [false, true].map(srgb => [value + (srgb ? 0x20 : 0), {
        name: (srgb ? "COMPRESSED_SRGB8_ALPHA8_ASTC_" : "COMPRESSED_RGBA_ASTC_") + w + "x" + h, block_bytes: 16, channels: 4,
        webgpu: "astc-" + w + "x" + h + "-unorm" + (srgb ? "-srgb" : ""), block_width: w, block_height: h, astc: true }])),
]);

/** GLES 3.0's GL_COMPRESSED_TEXTURE_FORMATS: ETC2 and EAC, and ETC1 */
export const COMPRESSED_TEXTURE_FORMATS_3 = COMPRESSED.map(c => c[0]);
/** GLES 3.2's: ASTC's too */
export const COMPRESSED_TEXTURE_FORMATS_32 = [...COMPRESSED_FORMATS.keys()];

/** @param {number} internalformat @return {?FormatInfo} a sized format's, or a legacy one's */
export function format_info(internalformat)
{
    return SIZED_FORMATS.get(internalformat) || LEGACY.get(internalformat) || null;
}

const FORMATS = new Set([F.RED, F.RG, F.RGB, F.RGBA, F.RED_INTEGER, F.RG_INTEGER, F.RGB_INTEGER, F.RGBA_INTEGER, F.DEPTH_COMPONENT,
    F.DEPTH_STENCIL, F.LUMINANCE, F.LUMINANCE_ALPHA, F.ALPHA, F.BGRA_EXT]);
const TYPES = new Set([F.BYTE, F.UNSIGNED_BYTE, F.SHORT, F.UNSIGNED_SHORT, F.INT, F.UNSIGNED_INT, F.FLOAT, F.HALF_FLOAT, F.HALF_FLOAT_OES,
    F.UNSIGNED_SHORT_4_4_4_4, F.UNSIGNED_SHORT_5_5_5_1, F.UNSIGNED_SHORT_5_6_5, F.UNSIGNED_INT_2_10_10_10_REV, F.UNSIGNED_INT_10F_11F_11F_REV,
    F.UNSIGNED_INT_5_9_9_9_REV, F.UNSIGNED_INT_24_8, F.FLOAT_32_UNSIGNED_INT_24_8_REV]);

/**
 * glTexImage*'s internal format, format and type, by GLES 3.0's rules
 * (3.8.3): the sized format they make, or the error
 * @return {{error: number, internal: number}} internal: the sized (or
 *     legacy) format the image has; error: 0, or INVALID_ENUM,
 *     INVALID_VALUE, INVALID_OPERATION
 */
export function tex_image_format(internalformat, format, type)
{
    if(!FORMATS.has(format) || !TYPES.has(type)) return { error: 0x0500, internal: 0 };
    const unsized = UNSIZED.get(internalformat);
    if(unsized)
    {
        if(format !== internalformat) return { error: 0x0502, internal: 0 };
        // (GLES 2.0's OES_texture_half_float: an unsized format of half floats; GLES 3.0 also takes FLOAT with OES_texture_float)
        if(!unsized.has(type)) return { error: 0x0502, internal: 0 };
        return { error: 0, internal: unsized.get(type) };
    }
    const sized = SIZED_FORMATS.get(internalformat);
    if(!sized) return { error: 0x0501, internal: 0 };
    if(sized.format !== format || !sized.types.includes(type)) return { error: 0x0502, internal: 0 };
    return { error: 0, internal: internalformat };
}

/** @return {number} the bytes of one pixel of the format and type (as client memory holds it); 0 for a pair that is none */
export function pixel_bytes(format, type)
{
    switch(type)
    {
        case F.UNSIGNED_SHORT_4_4_4_4: case F.UNSIGNED_SHORT_5_5_5_1: case F.UNSIGNED_SHORT_5_6_5: return 2;
        case F.UNSIGNED_INT_2_10_10_10_REV: case F.UNSIGNED_INT_10F_11F_11F_REV: case F.UNSIGNED_INT_5_9_9_9_REV: case F.UNSIGNED_INT_24_8: return 4;
        case F.FLOAT_32_UNSIGNED_INT_24_8_REV: return 8;
    }
    const channels = { [F.RED]: 1, [F.RED_INTEGER]: 1, [F.DEPTH_COMPONENT]: 1, [F.LUMINANCE]: 1, [F.ALPHA]: 1, [F.STENCIL_INDEX]: 1,
        [F.RG]: 2, [F.RG_INTEGER]: 2, [F.LUMINANCE_ALPHA]: 2, [F.RGB]: 3, [F.RGB_INTEGER]: 3, [F.RGBA]: 4, [F.RGBA_INTEGER]: 4,
        [F.BGRA_EXT]: 4 }[format] || 0;
    const size = { [F.BYTE]: 1, [F.UNSIGNED_BYTE]: 1, [F.SHORT]: 2, [F.UNSIGNED_SHORT]: 2, [F.HALF_FLOAT]: 2, [F.HALF_FLOAT_OES]: 2,
        [F.INT]: 4, [F.UNSIGNED_INT]: 4, [F.FLOAT]: 4 }[type] || 0;
    return channels * size;
}

/**
 * The bytes an image of client memory takes by the pixel store's state
 * (GLES 3.0, 3.7.1): rows of row_length (or width) pixels aligned,
 * image_height (or height) rows an image, after the skips
 * @param {{alignment: number, row_length: number, image_height: number, skip_pixels: number, skip_rows: number, skip_images: number}} store
 * @return {number} 0 for an empty image
 */
export function image_bytes3(width, height, depth, format, type, store)
{
    if(!width || !height || !depth) return 0;
    const pixel = pixel_bytes(format, type);
    const row_pixels = store.row_length > 0 ? store.row_length : width;
    const row = Math.ceil(row_pixels * pixel / store.alignment) * store.alignment;
    const image_rows = store.image_height > 0 ? store.image_height : height;
    const skip = store.skip_images * image_rows * row + store.skip_rows * row + store.skip_pixels * pixel;
    return skip + (depth - 1) * image_rows * row + (height - 1) * row + width * pixel;
}

/** @return {number} the bytes of a compressed image of the format, or -1 for no such format */
export function compressed_bytes(internalformat, width, height, depth)
{
    const c = COMPRESSED_FORMATS.get(internalformat);
    if(!c) return -1;
    return Math.ceil(width / c.block_width) * Math.ceil(height / c.block_height) * c.block_bytes * depth;
}

/**
 * What GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE answers for the format
 * @return {number}
 */
export function component_type(info)
{
    switch(info.kind)
    {
        case "snorm": return F.SIGNED_NORMALIZED;
        case "float": return F.FLOAT;
        case "int": return F.INT;
        case "uint": return F.UNSIGNED_INT;
        case "depth": case "depth_stencil": return info.value === 0x8CAC || info.value === 0x8CAD ? F.FLOAT : F.UNSIGNED_NORMALIZED;
        default: return F.UNSIGNED_NORMALIZED;
    }
}

/**
 * Whether a framebuffer can render to the format: GLES 3.0's
 * color-renderable ones, the depth and stencil formats; with
 * EXT_color_buffer_float the float formats too
 */
export function renderable(info, color_buffer_float)
{
    if(!info) return false;
    if(info.kind === "depth" || info.kind === "depth_stencil" || info.value === 0x8D48) return true;
    if(info.renderable) return true;
    return !!color_buffer_float && info.kind === "float" && info.value !== 0x8C3D && info.format !== F.RGB || !!color_buffer_float && info.value === 0x8C3A;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/gles/gles_host.js                                                                    0000644 0000000 0000000 00000056671 00000000000 013751  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GLES host (docs/gles-proxy-plan.md): the services a transport
// connects the guest to. Android's goldfish pipe (src/virt/goldfish.js)
// opens "opengles", one connection per GL thread (a GLESStream whose
// commands go to renderControl or to the shadow state), and
// "GLProcessPipe", one per process: it answers the guest library's
// confirmation (a u32, 100) with the process's unique id, which the
// process's connections then report with rcSetPuid; its closing is the
// process's end, when renderControl drops what the process had.
//
// A service: write(bytes) the guest's, read(max) the bytes it may read
// now (null: none yet), available() whether there are any, close().
// `wake` tells the transport that a service has bytes for the guest which
// it did not have when last asked.
//
// The page (E2): the shadow state (src/gles/gles_shadow.js) answers every
// query; what changes state goes into GLES batches (renderer_protocol.js's
// GLES records) for the renderer channel's stream "gles", in the guest's
// order across connections. A batch is sent at the guest's flush points: a
// frame (rcFlushWindowColorBuffer, rcFBPost), glFinish and glFlush (the
// encoder's glFinishRoundTrip), a sync wait, a read; and when it grows past
// FLUSH_BYTES. The calls that need only order are answered once their batch
// is sent; when more than MAX_IN_FLIGHT batches have not run, the frame's
// and glFinish's answers wait for the oldest (backpressure). Only reads
// (glReadPixels, rcReadColorBuffer) wait for the page's data. Without a
// renderer (or one lost), batches go nowhere and reads give zeros.
//
// A snapshot (E5) keeps renderControl's objects, the shadow state and
// each connection (its context and surfaces, the bytes of a command not
// whole yet, the replies not read: the pipe's channel keeps its service's
// state, src/virt/goldfish.js); prepare_save first answers every call that
// waits for the page, then fetches the page's state (the executor's
// objects and the GPU's contents, read back: "gles_save"). A restore resets
// the page and gives it that state back ("gles_restore"), on whatever
// renderer the machine has now. No graphics journal is replayed.

import { pack_program } from "./glsl_program.js";
import { GLESStream } from "./gles_stream.js";
import { RenderControl } from "./render_control.js";
import { CONFIGS } from "./gles_caps.js";
import { GLESShadow, SHADOW_CLASSES } from "./gles_shadow.js";
import { pack, shadow_skip, unpack } from "./gles_snapshot.js";
import { GLES, GLES_MAGIC, GXWriter, READBACK_HEADER_BYTES, RESPONSE_OK } from "../graphics_adapters/renderer_protocol.js";

/** A batch this large is sent at once */
export const FLUSH_BYTES = 4 << 20;
/** Batches sent that the page may not have run before the frame's answer waits */
export const MAX_IN_FLIGHT = 2;

/**
 * @constructor
 * @param {{width: number, height: number, dpi: number}} display
 * @param {?{post: function(!Object, !Array=), listen: function(function(!Object))}} renderer the
 *     renderer channel (stream "gles"), or null
 * @param {function(!Uint8Array, number, number)=} present the screen's
 *     (the frames the page reads back when it shows them nowhere itself)
 */
export function GLESHost(display, renderer, present, options)
{
    /** glslang (the plugin's prepare) and the highest version announced (docs/gles3-plan.md) */
    this.options = options || {};
    /** the screen: a posted frame read back (RGBA rows from the top) */
    this.present = present || (() => {});
    this.rc = new RenderControl(display);
    this.rc.events = (kind, ...args) => this.on_event(kind, args);
    this.renderer = renderer;
    if(renderer) renderer.listen(message => this.receive(message));
    this.reset();
    if(renderer) renderer.post({ "type": "hello" });
}

GLESHost.prototype.reset = function()
{
    this.rc.reset();
    this.rc.max_version = { "3.0": 30, "3.1": 31, "3.2": 32 }[this.options.max_version] || 20;
    this.shadow = new GLESShadow(this.rc);
    this.shadow.glslang = this.options.glslang || null;
    // (buffers' bytes on the CPU side: glMapBufferRange's answers, docs/gles3-plan.md)
    this.shadow.keep_bytes = true;
    this.writer = new GXWriter(GLES_MAGIC);
    this.next_connection = 1;
    this.next_puid = 1;
    /** @type {!Set<!GLESStream>} */
    this.streams = new Set();
    /** what the closed connections counted */
    this.closed_counts = new Map();
    this.closed_unknown = new Map();
    this.closed_malformed = new Map();
    this.closed_failed = new Map();
    this.connections = 0;
    this.processes = 0;
    this.submitted = 0;
    this.completed = 0;
    /** @type {!Array<{seq: number, run: function()}>} */
    this.completions = [];
    this.next_request = 1;
    /** @type {!Map<number, function(?Uint8Array)>} */
    this.requests = new Map();
    this.lost = !this.renderer;
    /** @type {!Map<number, function(*)>} the page's states asked for (prepare_save) */
    this.saves = new Map();
    this.page_state = null;
    /** what went to the page, and what waited for it */
    this.stats = { batches: 0, bytes: 0, records: 0, refused: 0, reads: 0, throttled: 0, frames: 0, cpu_ms: 0 };
    /** @type {!Map<string, number>} refused calls by name and the error they left */
    this.refused = new Map();
    if(this.renderer) this.renderer.post({ "type": "reset" });
};

/**
 * A service of a name, or null for one the host does not have
 * @param {string} name
 * @param {function()} wake
 * @param {*=} saved the service's state in a snapshot (its get_state's)
 * @return {?Object} {write, read, available, close, get_state}
 */
GLESHost.prototype.service = function(name, wake, saved)
{
    if(name === "opengles") return this.connect(wake, saved);
    if(name === "GLProcessPipe") return this.process_pipe(saved);
    return null;
};

/** @param {function()} wake @param {*=} saved @return {!Object} a connection's service */
GLESHost.prototype.connect = function(wake, saved)
{
    const state = saved ? unpack(saved) : null;
    const conn = state ? state.conn : { id: this.next_connection++, puid: null, context: 0, draw: 0, read: 0 };
    const stream = new GLESStream((command, args, bytes) =>
    {
        // (the host's own time on the machine's thread: E5's measure)
        const start = performance.now();
        const ret = command.api === "rc" ? this.rc_call(conn, command, args) : this.gl_call(conn, command, args, bytes);
        this.stats.cpu_ms += performance.now() - start;
        return ret;
    }, wake);
    if(state) stream.set_state(state.stream);
    else this.connections++;
    this.streams.add(stream);
    return {
        write: bytes => stream.write(bytes),
        read: max => stream.read(max),
        available: () => stream.output_bytes > 0,
        close: () =>
        {
            stream.close();
            this.streams.delete(stream);
            add_counts(this.closed_counts, stream.counts);
            add_counts(this.closed_unknown, stream.unknown);
            add_counts(this.closed_malformed, stream.malformed);
            add_counts(this.closed_failed, stream.failed);
            this.rc.disconnect(conn);
            this.record(GLES.CONNECTION_CLOSE, [conn.id]);
        },
        get_state: () => pack({ conn, stream: stream.get_state() }),
    };
};

/** @param {*=} saved @return {!Object} a process pipe's service */
GLESHost.prototype.process_pipe = function(saved)
{
    let puid = null, reply = null;
    if(saved) [puid, reply] = saved;
    else this.processes++;
    return {
        get_state: () => [puid, reply && reply.slice()],
        write: bytes =>
        {
            // (the confirmation, once: the reply is the process's id, a u64)
            if(puid !== null || bytes.length < 4) return;
            puid = this.next_puid++;
            reply = new Uint8Array(8);
            new DataView(reply.buffer).setUint32(0, puid, true);
        },
        read: max =>
        {
            if(!reply) return null;
            const bytes = reply.subarray(0, max);
            reply = bytes.length < reply.length ? reply.subarray(bytes.length) : null;
            return bytes;
        },
        available: () => reply !== null,
        close: () => { if(puid !== null) this.rc.release("p" + puid); },
    };
};

// ---- the calls

/** Whether a call only asks (or only names: glGen*): the shadow state answers it, nothing for the page */
function is_query(name)
{
    // (glMapBufferRangeAEMU's answer is the bytes: the page never sees it, the unmap brings what was written)
    return /^gl(Get|Is|Gen|CheckFramebufferStatus|FinishRoundTrip|MapBufferRangeAEMU)/.test(name);
}

/**
 * A GLES call: the shadow state answers; what it accepts and the page needs
 * is recorded. glReadPixels waits for the pixels, glFinish's answer (the
 * encoder's glFinishRoundTrip) for room among the batches in flight.
 */
GLESHost.prototype.gl_call = function(conn, command, args, bytes)
{
    const { ret, keep } = this.shadow.call(conn.context, command, args);
    if(command.name === "glReadPixels" || command.name === "glReadnPixelsEXT")
    {
        if(!keep) return ret;
        // (EXT_robustness's: its buffer's size before the pixels)
        const [x, y, width, height, format, type, pixels] = command.name === "glReadPixels" ? args : [...args.slice(0, 6), args[7]];
        const request = this.request(pixels);
        this.record(GLES.READ_PIXELS, [conn.id, request.id, x, y, width, height, format, type]);
        this.flush();
        return request.done;
    }
    // (a map of a buffer the page wrote: its bytes from the page, into the guest's and the CPU side's copy)
    if(command.name === "glMapBufferRangeAEMU" && this.shadow.stale_map)
    {
        const stale = this.shadow.stale_map;
        this.shadow.stale_map = null;
        const mapped = args[4];
        if(!mapped || !mapped.size) return ret;
        const request = this.request(mapped);
        this.record(GLES.BUFFER_READ, [conn.id, request.id, stale.name, stale.offset, stale.length]);
        this.flush();
        return request.done.then(() => { stale.bytes.set(mapped.data.subarray(0, Math.min(stale.length, mapped.size)), stale.offset); });
    }
    // (an occlusion query's result: the page's)
    if(command.name === "glGetQueryObjectuiv" && this.shadow.query_read)
    {
        const { name, query } = this.shadow.query_read;
        this.shadow.query_read = null;
        const params = args[2];
        if(!params || params.size < 4) return ret;
        const request = this.request(params);
        this.record(GLES.QUERY_READ, [conn.id, request.id, name]);
        this.flush();
        return request.done.then(() => { query.result = new DataView(params.data.buffer, params.data.byteOffset).getUint32(0, true) ? 1 : 0; query.answered = true; });
    }
    // (a link through glslang: its result first, which the page links with)
    if(keep && (command.name === "glLinkProgram" || command.name === "glCreateShaderProgramvAEMU") && this.shadow.last_link)
    {
        const packed = pack_program(this.shadow.last_link);
        this.record(GLES.PROGRAM_LINK, [conn.id, (command.name === "glLinkProgram" ? args[0] : ret) >>> 0, packed.length], packed);
        this.shadow.last_link = null;
    }
    if(keep) this.record(GLES.COMMAND, [conn.id, ret >>> 0, bytes.length], bytes);
    else if(!is_query(command.name))
    {
        // (which calls the rules refuse, and with what error: the guest's mistakes, or the shadow's)
        this.stats.refused++;
        const c = this.shadow.context(conn.context);
        const key = command.name + (c ? ":0x" + c.error.toString(16) : ":no context");
        this.refused.set(key, (this.refused.get(key) || 0) + 1);
    }
    switch(command.name)
    {
        case "glFinishRoundTrip":
            return this.throttle(ret);
        case "glFinish": case "glFlush":
            this.flush();
            break;
    }
    if(this.writer.size() > FLUSH_BYTES) this.flush();
    return ret;
};

/** renderControl's call, and what the page or the guest waits on */
GLESHost.prototype.rc_call = function(conn, command, args)
{
    if(command.name === "rcReadColorBuffer")
    {
        const [color_buffer, x, y, width, height, format, type, pixels] = args;
        if(!this.rc.color_buffers.has(color_buffer)) return undefined;
        const request = this.request(pixels);
        this.record(GLES.COLOR_BUFFER_READ, [color_buffer, x, y, width, height, format, type, request.id]);
        this.flush();
        return request.done;
    }
    const ret = this.rc.call(conn, command, args);
    switch(command.name)
    {
        case "rcFlushWindowColorBuffer":
        case "rcClientWaitSyncKHR":
            return this.throttle(ret);
        case "rcFlushWindowColorBufferAsync":
        case "rcFlushWindowColorBufferAsyncWithFrameNumber":
        case "rcFBPost":
        case "rcWaitSyncKHR":
            this.flush();
            break;
    }
    if(this.writer.size() > FLUSH_BYTES) this.flush();
    return ret;
};

/** renderControl's objects and frames: the shadow state follows, the page gets records */
GLESHost.prototype.on_event = function(kind, args)
{
    switch(kind)
    {
        case "context_create":
        {
            const [context, config, share, requested] = args;
            // (a GLES 2.0 context of a host with glslang: GLSL ES 1.00 through it, drawn as GLES 3.x's: api 20, Context's glslang)
            const api = requested === 2 && this.shadow.glslang ? 20 : requested;
            this.shadow.create_context(context, api, share);
            this.record(GLES.CONTEXT_CREATE, [context, config, share, api]);
            break;
        }
        case "context_destroy":
            this.shadow.destroy_context(args[0]);
            this.record(GLES.CONTEXT_DESTROY, args);
            break;
        case "surface_create": this.record(GLES.SURFACE_CREATE, args); break;
        case "surface_destroy": this.record(GLES.SURFACE_DESTROY, args); break;
        case "surface_color_buffer": this.record(GLES.SURFACE_COLOR_BUFFER, args); break;
        case "make_current":
        {
            const [conn, context, draw, read] = args;
            const surface = this.rc.surfaces.get(draw);
            this.shadow.make_current(context, surface ? { width: surface.width, height: surface.height, config: CONFIGS[surface.config] } : null);
            this.record(GLES.MAKE_CURRENT, [conn.id, context, draw, read]);
            break;
        }
        case "color_buffer_create": this.record(GLES.COLOR_BUFFER_CREATE, args); break;
        case "color_buffer_destroy": this.record(GLES.COLOR_BUFFER_DESTROY, args); break;
        case "color_buffer_update":
        {
            const [color_buffer, x, y, width, height, format, type, pixels] = args;
            this.record(GLES.COLOR_BUFFER_UPDATE, [color_buffer, x, y, width, height, format, type, pixels.length], pixels);
            break;
        }
        case "bind":
        {
            const [conn, color_buffer, texture] = args;
            if(this.shadow.bind_color_buffer(conn.context, color_buffer, texture)) this.record(GLES.COLOR_BUFFER_BIND, [conn.id, color_buffer, +texture]);
            break;
        }
        case "image_create": this.record(GLES.IMAGE_CREATE, args); break;
        case "image_destroy": this.record(GLES.IMAGE_DESTROY, args); break;
        case "post": this.record(GLES.POST, args); break;
        case "flush_surface": this.record(GLES.FLUSH_SURFACE, args); break;
    }
};

// ---- batches

/**
 * @param {number} op
 * @param {!Array<number>} dwords
 * @param {Uint8Array=} bytes
 */
GLESHost.prototype.record = function(op, dwords, bytes)
{
    if(this.lost) return;
    this.writer.command(op, dwords.map(v => v >>> 0), bytes);
    this.stats.records++;
};

/** Send the batch being written */
GLESHost.prototype.flush = function()
{
    if(this.writer.empty()) return;
    const bytes = this.writer.finish();
    const seq = ++this.submitted;
    this.stats.batches++;
    this.stats.bytes += bytes.length;
    this.renderer.post({ "type": "submit", "seq": seq, "bytes": bytes, "stream": "gles" }, [bytes.buffer]);
};

/**
 * Send what was written; the answer, once no more than MAX_IN_FLIGHT
 * batches wait to run
 * @param {*} value
 * @return {*} the value, or a promise of it
 */
GLESHost.prototype.throttle = function(value)
{
    this.flush();
    if(this.submitted - this.completed <= MAX_IN_FLIGHT) return value;
    this.stats.throttled++;
    return new Promise(resolve => this.completions.push({ seq: this.submitted - MAX_IN_FLIGHT, run: () => resolve(value) }));
};

/**
 * A read the page answers: its id, and the promise of its answer (the
 * bytes into `out`, zeros if the page has none)
 * @param {!Object} out an OutBuffer
 * @return {{id: number, done: !Promise}}
 */
GLESHost.prototype.request = function(out)
{
    const id = this.next_request++;
    this.stats.reads++;
    if(this.lost) return { id, done: Promise.resolve(undefined) };
    const done = new Promise(resolve => this.requests.set(id, bytes =>
    {
        if(bytes) out.data.set(bytes.subarray(0, out.size));
        resolve(undefined);
    }));
    return { id, done };
};

/** @param {!Object} message from the renderer */
GLESHost.prototype.receive = function(message)
{
    switch(message["type"])
    {
        case "write":
        {
            const bytes = message["bytes"];
            if(bytes.length < READBACK_HEADER_BYTES) return;
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            const id = view.getUint32(0, true), count = view.getUint32(4, true), status = view.getUint32(12, true);
            const answer = this.requests.get(id);
            if(!answer) return;
            this.requests.delete(id);
            answer(status === RESPONSE_OK ? bytes.subarray(READBACK_HEADER_BYTES, READBACK_HEADER_BYTES + count) : null);
            break;
        }
        case "frame":
            this.stats.frames++;
            this.present(message["bytes"], message["width"], message["height"]);
            break;
        case "gles_saved":
        {
            const answer = this.saves.get(message["id"]);
            this.saves.delete(message["id"]);
            if(answer) answer(message["state"] || null);
            break;
        }
        case "done":
            this.completed = Math.max(this.completed, message["seq"]);
            while(this.completions.length && this.completions[0].seq <= this.completed) this.completions.shift().run();
            break;
        case "lost":
            // (nothing waits for the page any more; nothing more goes to it)
            this.lost = true;
            console.warn("GLES: the renderer was lost: " + message["reason"]);
            this.completed = this.submitted;
            for(const answer of this.requests.values()) answer(null);
            this.requests.clear();
            for(const answer of this.saves.values()) answer(null);
            this.saves.clear();
            while(this.completions.length) this.completions.shift().run();
            break;
    }
};

// ---- snapshots

/**
 * Before a save (the machine stopped): every call that waits for the page
 * answered (the batches run, the reads back, what the streams held after
 * them decoded), then the page's state fetched
 * @return {!Promise<undefined>}
 */
GLESHost.prototype.prepare_save = async function()
{
    for(;;)
    {
        this.flush();
        const busy = this.requests.size > 0 || this.completed < this.submitted || [...this.streams].some(s => s.waiting || s.backlog.length);
        if(!busy) break;
        if(this.completed < this.submitted) await new Promise(resolve => this.completions.push({ seq: this.submitted, run: resolve }));
        // (the answers' promises, and the streams' commands after them)
        await new Promise(resolve => setTimeout(resolve, 0));
    }
    this.page_state = null;
    if(this.lost) return;
    const id = this.next_request++;
    // (a page that does not answer within a minute: the snapshot goes without its contents)
    this.page_state = await new Promise(resolve =>
    {
        const timer = setTimeout(() =>
        {
            this.saves.delete(id);
            console.warn("GLES: the page did not give its state for the snapshot; its textures and color buffers are not kept");
            resolve(null);
        }, 60000);
        this.saves.set(id, state => { clearTimeout(timer); resolve(state); });
        this.renderer.post({ "type": "gles_save", "id": id });
    });
};

/** @return {!Array<*>} a snapshot's: the version, the host's state packed, the page's (prepare_save's, or null) */
GLESHost.prototype.get_state = function()
{
    const rc = this.rc;
    const state = pack({
        rc: { next_handle: rc.next_handle, contexts: rc.contexts, surfaces: rc.surfaces, color_buffers: rc.color_buffers, images: rc.images,
            syncs: rc.syncs, displays: rc.displays, buffers: rc.buffers, posted: rc.posted, posts: rc.posts, swap_interval: rc.swap_interval,
            update_bytes: rc.update_bytes },
        shadow: this.shadow.get_state(),
        next_connection: this.next_connection, next_puid: this.next_puid, connections: this.connections, processes: this.processes,
        closed_counts: this.closed_counts, closed_unknown: this.closed_unknown, closed_malformed: this.closed_malformed,
        closed_failed: this.closed_failed, stats: this.stats, refused: this.refused,
    }, { classes: SHADOW_CLASSES, skip: shadow_skip });
    const page = this.page_state;
    this.page_state = null;
    return [1, state, page];
};

/**
 * A snapshot's state (the connections came back with the pipe's channels,
 * src/virt/goldfish.js, before this): the page reset and given its state
 * @param {!Array<*>} state get_state's; [] from a snapshot of E1 (nothing kept)
 */
GLESHost.prototype.set_state = function(state)
{
    const streams = this.streams;
    this.reset();
    if(!state || state[0] !== 1) return;
    this.streams = streams;
    const saved = unpack(state[1], SHADOW_CLASSES);
    Object.assign(this.rc, saved.rc);
    this.shadow.set_state(saved.shadow);
    for(const key of ["next_connection", "next_puid", "connections", "processes", "closed_counts", "closed_unknown", "closed_malformed",
        "closed_failed", "stats", "refused"])
    {
        if(saved[key] !== undefined) this[key] = saved[key];
    }
    if(state[2] && !this.lost) this.renderer.post({ "type": "gles_restore", "state": state[2] });
};

/** @param {!Map} into @param {!Map} from */
function add_counts(into, from)
{
    for(const [key, n] of from) into.set(key, (into.get(key) || 0) + n);
}

/**
 * What the connections decoded: calls by name, opcodes of no range,
 * commands that did not decode, renderControl's objects, the batches
 * @return {!Object}
 */
GLESHost.prototype.summary = function()
{
    const counts = new Map(this.closed_counts), unknown = new Map(this.closed_unknown), malformed = new Map(this.closed_malformed);
    let dropped_bytes = 0, broken = 0;
    const failed = new Map(this.closed_failed);
    for(const stream of this.streams)
    {
        add_counts(failed, stream.failed);
        add_counts(counts, stream.counts);
        add_counts(unknown, stream.unknown);
        add_counts(malformed, stream.malformed);
        dropped_bytes += stream.dropped_bytes;
        if(stream.broken) broken++;
    }
    const sorted = map => Object.fromEntries([...map].sort((a, b) => b[1] - a[1]));
    return {
        connections: this.connections, open_connections: this.streams.size, processes: this.processes,
        counts: sorted(counts), unknown: sorted(unknown), malformed: sorted(malformed), failed: sorted(failed), broken, dropped_bytes,
        render_control: this.rc.summary(), batches: Object.assign({ submitted: this.submitted, completed: this.completed }, this.stats),
        shaders: this.shadow.stats, refused: sorted(this.refused),
    };
};
                                                                       source/v64/src/gles/gles_protocol.js                                                                0000644 0000000 0000000 00000264172 00000000000 014632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/gles/gen.mjs from gfxstream's host specs
// (codegen/{renderControl,gles1,gles2} at 7e9d595b, docs/gfxstream-protocol.md):
// the emugl GLES wire format (docs/gles-proxy-plan.md). Do not edit.
//
// GLES_APIS[api] = { base, commands }: a command's opcode is base plus its
// index; a command is [name, return, parameters, flags]:
// - return: the value's kind ("void", "u8", "i16", "u16", "i32", "u32",
//   "f32", "u64", "i64"; a pointer's is "u32", it is never sent)
// - parameters: [name, kind, direction, flags] each; kind as above or
//   "ptr" (in, out or inout; flags "nullAllowed", "isLarge", "DMA")
// - flags: "unsupported" (the guest never sends it), "custom_decoder",
//   "not_api", "flushOnEncode"


export const GLES_APIS = {
    rc: { base: 10000, commands: [
        ["rcGetRendererVersion", "i32", []],
        ["rcGetEGLVersion", "i32", [["major", "ptr", "out"], ["minor", "ptr", "out"]]],
        ["rcQueryEGLString", "i32", [["name", "u32"], ["buffer", "ptr", "out"], ["bufferSize", "i32"]]],
        ["rcGetGLString", "i32", [["name", "u32"], ["buffer", "ptr", "out"], ["bufferSize", "i32"]]],
        ["rcGetNumConfigs", "i32", [["numAttribs", "ptr", "out"]]],
        ["rcGetConfigs", "i32", [["bufSize", "u32"], ["buffer", "ptr", "out"]]],
        ["rcChooseConfig", "i32", [["attribs", "ptr", "in"], ["attribs_size", "u32"], ["configs", "ptr", "out", ["nullAllowed"]], ["configs_size", "u32"]]],
        ["rcGetFBParam", "i32", [["param", "i32"]]],
        ["rcCreateContext", "u32", [["config", "u32"], ["share", "u32"], ["glVersion", "u32"]]],
        ["rcDestroyContext", "void", [["context", "u32"]]],
        ["rcCreateWindowSurface", "u32", [["config", "u32"], ["width", "u32"], ["height", "u32"]]],
        ["rcDestroyWindowSurface", "void", [["windowSurface", "u32"]]],
        ["rcCreateColorBuffer", "u32", [["width", "u32"], ["height", "u32"], ["internalFormat", "u32"]]],
        ["rcOpenColorBuffer", "void", [["colorbuffer", "u32"]]],
        ["rcCloseColorBuffer", "void", [["colorbuffer", "u32"]], ["flushOnEncode"]],
        ["rcSetWindowColorBuffer", "void", [["windowSurface", "u32"], ["colorBuffer", "u32"]]],
        ["rcFlushWindowColorBuffer", "i32", [["windowSurface", "u32"]]],
        ["rcMakeCurrent", "i32", [["context", "u32"], ["drawSurf", "u32"], ["readSurf", "u32"]]],
        ["rcFBPost", "void", [["colorBuffer", "u32"]]],
        ["rcFBSetSwapInterval", "void", [["interval", "i32"]]],
        ["rcBindTexture", "void", [["colorBuffer", "u32"]]],
        ["rcBindRenderbuffer", "void", [["colorBuffer", "u32"]]],
        ["rcColorBufferCacheFlush", "i32", [["colorbuffer", "u32"], ["postCount", "i32"], ["forRead", "i32"]]],
        ["rcReadColorBuffer", "void", [["colorbuffer", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "out"]]],
        ["rcUpdateColorBuffer", "i32", [["colorbuffer", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["isLarge"]]]],
        ["rcOpenColorBuffer2", "i32", [["colorbuffer", "u32"]]],
        ["rcCreateClientImage", "u32", [["context", "u32"], ["target", "u32"], ["buffer", "u32"]]],
        ["rcDestroyClientImage", "i32", [["image", "u32"]]],
        ["rcSelectChecksumHelper", "void", [["newProtocol", "u32"], ["reserved", "u32"]]],
        ["rcCreateSyncKHR", "void", [["type", "u32"], ["attribs", "ptr", "in"], ["num_attribs", "u32"], ["destroy_when_signaled", "i32"], ["glsync_out", "ptr", "out"], ["syncthread_out", "ptr", "out"]]],
        ["rcClientWaitSyncKHR", "i32", [["sync", "u64"], ["flags", "i32"], ["timeout", "u64"]]],
        ["rcFlushWindowColorBufferAsync", "void", [["windowSurface", "u32"]]],
        ["rcDestroySyncKHR", "i32", [["sync", "u64"]]],
        ["rcSetPuid", "void", [["puid", "u64"]]],
        ["rcUpdateColorBufferDMA", "i32", [["colorbuffer", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["DMA"]], ["pixels_size", "u32"]], ["flushOnEncode"]],
        ["rcCreateColorBufferDMA", "u32", [["width", "u32"], ["height", "u32"], ["internalFormat", "u32"], ["frameworkFormat", "i32"]]],
        ["rcWaitSyncKHR", "void", [["sync", "u64"], ["flags", "i32"]]],
        ["rcCompose", "i32", [["bufferSize", "u32"], ["buffer", "ptr", "in"]], ["flushOnEncode"]],
        ["rcCreateDisplay", "i32", [["displayId", "ptr", "out"]]],
        ["rcDestroyDisplay", "i32", [["displayId", "u32"]]],
        ["rcSetDisplayColorBuffer", "i32", [["displayId", "u32"], ["colorBuffer", "u32"]]],
        ["rcGetDisplayColorBuffer", "i32", [["displayId", "u32"], ["colorBuffer", "ptr", "out"]]],
        ["rcGetColorBufferDisplay", "i32", [["colorBuffer", "u32"], ["displayId", "ptr", "out"]]],
        ["rcGetDisplayPose", "i32", [["displayId", "u32"], ["x", "ptr", "out"], ["y", "ptr", "out"], ["w", "ptr", "out"], ["h", "ptr", "out"]]],
        ["rcSetDisplayPose", "i32", [["displayId", "u32"], ["x", "i32"], ["y", "i32"], ["w", "u32"], ["h", "u32"]]],
        ["rcSetColorBufferVulkanMode", "i32", [["colorBuffer", "u32"], ["mode", "u32"]]],
        ["rcReadColorBufferYUV", "void", [["colorbuffer", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["pixels", "ptr", "out"], ["pixels_size", "u32"]]],
        ["rcIsSyncSignaled", "i32", [["sync", "u64"]]],
        ["rcCreateColorBufferWithHandle", "void", [["width", "u32"], ["height", "u32"], ["internalFormat", "u32"], ["handle", "u32"]]],
        ["rcCreateBuffer", "u32", [["size", "u32"]]],
        ["rcCloseBuffer", "void", [["buffer", "u32"]]],
        ["rcSetColorBufferVulkanMode2", "i32", [["colorBuffer", "u32"], ["mode", "u32"], ["memoryProperty", "u32"]]],
        ["rcMapGpaToBufferHandle", "i32", [["bufferHandle", "u32"], ["gpa", "u64"]]],
        ["rcCreateBuffer2", "u32", [["size", "u64"], ["memoryProperty", "u32"]]],
        ["rcMapGpaToBufferHandle2", "i32", [["bufferHandle", "u32"], ["gpa", "u64"], ["size", "u64"]]],
        ["rcFlushWindowColorBufferAsyncWithFrameNumber", "void", [["windowSurface", "u32"], ["frameNumber", "u32"]]],
        ["rcSetTracingForPuid", "void", [["puid", "u64"], ["enable", "u32"], ["guestTime", "u64"]]],
        ["rcMakeCurrentAsync", "void", [["context", "u32"], ["drawSurf", "u32"], ["readSurf", "u32"]], ["flushOnEncode"]],
        ["rcComposeAsync", "void", [["bufferSize", "u32"], ["buffer", "ptr", "in"]], ["flushOnEncode"]],
        ["rcDestroySyncKHRAsync", "void", [["sync", "u64"]], ["flushOnEncode"]],
        ["rcComposeWithoutPost", "i32", [["bufferSize", "u32"], ["buffer", "ptr", "in"]], ["flushOnEncode"]],
        ["rcComposeAsyncWithoutPost", "void", [["bufferSize", "u32"], ["buffer", "ptr", "in"]], ["flushOnEncode"]],
        ["rcCreateDisplayById", "i32", [["displayId", "u32"]]],
        ["rcSetDisplayPoseDpi", "i32", [["displayId", "u32"], ["x", "i32"], ["y", "i32"], ["w", "u32"], ["h", "u32"], ["dpi", "u32"]]],
        ["rcReadColorBufferDMA", "i32", [["colorbuffer", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "out", ["DMA"]], ["pixels_size", "u32"]]],
        ["rcGetFBDisplayConfigsCount", "i32", []],
        ["rcGetFBDisplayConfigsParam", "i32", [["configId", "i32"], ["param", "i32"]]],
        ["rcGetFBDisplayActiveConfig", "i32", []],
        ["rcSetProcessMetadata", "void", [["key", "ptr", "in"], ["valuePtr", "ptr", "in"], ["valueSize", "u32"]]],
        ["rcGetHostExtensionsString", "i32", [["bufferSize", "u32"], ["buffer", "ptr", "out"]]],
        ["rcGetDisplayColorTransform", "i32", [["displayId", "u32"], ["outColorTransformMatrix", "ptr", "in"]]],
        ["rcSetDisplayColorTransform", "i32", [["displayId", "u32"], ["colorTransformMatrix", "ptr", "in"]]],
    ] },
    gles1: { base: 1024, commands: [
        ["glAlphaFunc", "void", [["func", "u32"], ["ref", "f32"]]],
        ["glClearColor", "void", [["red", "f32"], ["green", "f32"], ["blue", "f32"], ["alpha", "f32"]]],
        ["glClearDepthf", "void", [["depth", "f32"]]],
        ["glClipPlanef", "void", [["plane", "u32"], ["equation", "ptr", "in"]]],
        ["glColor4f", "void", [["red", "f32"], ["green", "f32"], ["blue", "f32"], ["alpha", "f32"]]],
        ["glDepthRangef", "void", [["zNear", "f32"], ["zFar", "f32"]]],
        ["glFogf", "void", [["pname", "u32"], ["param", "f32"]]],
        ["glFogfv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glFrustumf", "void", [["left", "f32"], ["right", "f32"], ["bottom", "f32"], ["top", "f32"], ["zNear", "f32"], ["zFar", "f32"]]],
        ["glGetClipPlanef", "void", [["pname", "u32"], ["eqn", "ptr", "out"]]],
        ["glGetFloatv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetLightfv", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetMaterialfv", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexEnvfv", "void", [["env", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexParameterfv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glLightModelf", "void", [["pname", "u32"], ["param", "f32"]]],
        ["glLightModelfv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLightf", "void", [["light", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glLightfv", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLineWidth", "void", [["width", "f32"]]],
        ["glLoadMatrixf", "void", [["m", "ptr", "in"]]],
        ["glMaterialf", "void", [["face", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glMaterialfv", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glMultMatrixf", "void", [["m", "ptr", "in"]]],
        ["glMultiTexCoord4f", "void", [["target", "u32"], ["s", "f32"], ["t", "f32"], ["r", "f32"], ["q", "f32"]]],
        ["glNormal3f", "void", [["nx", "f32"], ["ny", "f32"], ["nz", "f32"]]],
        ["glOrthof", "void", [["left", "f32"], ["right", "f32"], ["bottom", "f32"], ["top", "f32"], ["zNear", "f32"], ["zFar", "f32"]]],
        ["glPointParameterf", "void", [["pname", "u32"], ["param", "f32"]]],
        ["glPointParameterfv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glPointSize", "void", [["size", "f32"]]],
        ["glPolygonOffset", "void", [["factor", "f32"], ["units", "f32"]]],
        ["glRotatef", "void", [["angle", "f32"], ["x", "f32"], ["y", "f32"], ["z", "f32"]]],
        ["glScalef", "void", [["x", "f32"], ["y", "f32"], ["z", "f32"]]],
        ["glTexEnvf", "void", [["target", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glTexEnvfv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexParameterf", "void", [["target", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glTexParameterfv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTranslatef", "void", [["x", "f32"], ["y", "f32"], ["z", "f32"]]],
        ["glActiveTexture", "void", [["texture", "u32"]]],
        ["glAlphaFuncx", "void", [["func", "u32"], ["ref", "i32"]]],
        ["glBindBuffer", "void", [["target", "u32"], ["buffer", "u32"]]],
        ["glBindTexture", "void", [["target", "u32"], ["texture", "u32"]]],
        ["glBlendFunc", "void", [["sfactor", "u32"], ["dfactor", "u32"]]],
        ["glBufferData", "void", [["target", "u32"], ["size", "i32"], ["data", "ptr", "in", ["nullAllowed"]], ["usage", "u32"]]],
        ["glBufferSubData", "void", [["target", "u32"], ["offset", "i32"], ["size", "i32"], ["data", "ptr", "in", ["nullAllowed"]]]],
        ["glClear", "void", [["mask", "u32"]]],
        ["glClearColorx", "void", [["red", "i32"], ["green", "i32"], ["blue", "i32"], ["alpha", "i32"]]],
        ["glClearDepthx", "void", [["depth", "i32"]]],
        ["glClearStencil", "void", [["s", "i32"]]],
        ["glClientActiveTexture", "void", [["texture", "u32"]]],
        ["glColor4ub", "void", [["red", "u8"], ["green", "u8"], ["blue", "u8"], ["alpha", "u8"]]],
        ["glColor4x", "void", [["red", "i32"], ["green", "i32"], ["blue", "i32"], ["alpha", "i32"]]],
        ["glColorMask", "void", [["red", "u8"], ["green", "u8"], ["blue", "u8"], ["alpha", "u8"]]],
        ["glColorPointer", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glCompressedTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed"]]]],
        ["glCompressedTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed"]]]],
        ["glCopyTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["border", "i32"]]],
        ["glCopyTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glCullFace", "void", [["mode", "u32"]]],
        ["glDeleteBuffers", "void", [["n", "i32"], ["buffers", "ptr", "in"]], ["custom_decoder"]],
        ["glDeleteTextures", "void", [["n", "i32"], ["textures", "ptr", "in"]], ["custom_decoder"]],
        ["glDepthFunc", "void", [["func", "u32"]]],
        ["glDepthMask", "void", [["flag", "u8"]]],
        ["glDepthRangex", "void", [["zNear", "i32"], ["zFar", "i32"]]],
        ["glDisable", "void", [["cap", "u32"]]],
        ["glDisableClientState", "void", [["array", "u32"]]],
        ["glDrawArrays", "void", [["mode", "u32"], ["first", "i32"], ["count", "i32"]]],
        ["glDrawElements", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"]], ["unsupported"]],
        ["glEnable", "void", [["cap", "u32"]]],
        ["glEnableClientState", "void", [["array", "u32"]]],
        ["glFinish", "void", []],
        ["glFlush", "void", []],
        ["glFogx", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glFogxv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glFrontFace", "void", [["mode", "u32"]]],
        ["glFrustumx", "void", [["left", "i32"], ["right", "i32"], ["bottom", "i32"], ["top", "i32"], ["zNear", "i32"], ["zFar", "i32"]]],
        ["glGetBooleanv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetBufferParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glClipPlanex", "void", [["pname", "u32"], ["eqn", "ptr", "in"]]],
        ["glGenBuffers", "void", [["n", "i32"], ["buffers", "ptr", "out"]], ["custom_decoder"]],
        ["glGenTextures", "void", [["n", "i32"], ["textures", "ptr", "out"]], ["custom_decoder"]],
        ["glGetError", "u32", []],
        ["glGetFixedv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetIntegerv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetLightxv", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetMaterialxv", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetPointerv", "void", [["pname", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glGetString", "u32", [["name", "u32"]], ["unsupported"]],
        ["glGetTexEnviv", "void", [["env", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexEnvxv", "void", [["env", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexParameterxv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glHint", "void", [["target", "u32"], ["mode", "u32"]]],
        ["glIsBuffer", "u8", [["buffer", "u32"]]],
        ["glIsEnabled", "u8", [["cap", "u32"]]],
        ["glIsTexture", "u8", [["texture", "u32"]]],
        ["glLightModelx", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glLightModelxv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLightx", "void", [["light", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glLightxv", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLineWidthx", "void", [["width", "i32"]]],
        ["glLoadIdentity", "void", []],
        ["glLoadMatrixx", "void", [["m", "ptr", "in"]]],
        ["glLogicOp", "void", [["opcode", "u32"]]],
        ["glMaterialx", "void", [["face", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glMaterialxv", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glMatrixMode", "void", [["mode", "u32"]]],
        ["glMultMatrixx", "void", [["m", "ptr", "in"]]],
        ["glMultiTexCoord4x", "void", [["target", "u32"], ["s", "i32"], ["t", "i32"], ["r", "i32"], ["q", "i32"]]],
        ["glNormal3x", "void", [["nx", "i32"], ["ny", "i32"], ["nz", "i32"]]],
        ["glNormalPointer", "void", [["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glOrthox", "void", [["left", "i32"], ["right", "i32"], ["bottom", "i32"], ["top", "i32"], ["zNear", "i32"], ["zFar", "i32"]]],
        ["glPixelStorei", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glPointParameterx", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glPointParameterxv", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glPointSizex", "void", [["size", "i32"]]],
        ["glPolygonOffsetx", "void", [["factor", "i32"], ["units", "i32"]]],
        ["glPopMatrix", "void", []],
        ["glPushMatrix", "void", []],
        ["glReadPixels", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "out"]]],
        ["glRotatex", "void", [["angle", "i32"], ["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glSampleCoverage", "void", [["value", "f32"], ["invert", "u8"]]],
        ["glSampleCoveragex", "void", [["value", "i32"], ["invert", "u8"]]],
        ["glScalex", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glScissor", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glShadeModel", "void", [["mode", "u32"]]],
        ["glStencilFunc", "void", [["func", "u32"], ["ref", "i32"], ["mask", "u32"]]],
        ["glStencilMask", "void", [["mask", "u32"]]],
        ["glStencilOp", "void", [["fail", "u32"], ["zfail", "u32"], ["zpass", "u32"]]],
        ["glTexCoordPointer", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glTexEnvi", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexEnvx", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexEnviv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexEnvxv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "i32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTexParameteri", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexParameterx", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexParameterxv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTranslatex", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glVertexPointer", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glViewport", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glPointSizePointerOES", "void", [["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glVertexPointerOffset", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glColorPointerOffset", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glNormalPointerOffset", "void", [["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glPointSizePointerOffset", "void", [["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glTexCoordPointerOffset", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glWeightPointerOffset", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glMatrixIndexPointerOffset", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glVertexPointerData", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glColorPointerData", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glNormalPointerData", "void", [["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glTexCoordPointerData", "void", [["unit", "i32"], ["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glPointSizePointerData", "void", [["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glWeightPointerData", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glMatrixIndexPointerData", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsOffset", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsData", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glGetCompressedTextureFormats", "void", [["count", "i32"], ["formats", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glFinishRoundTrip", "i32", [], ["custom_decoder","not_api"]],
        ["glBlendEquationSeparateOES", "void", [["modeRGB", "u32"], ["modeAlpha", "u32"]]],
        ["glBlendFuncSeparateOES", "void", [["srcRGB", "u32"], ["dstRGB", "u32"], ["srcAlpha", "u32"], ["dstAlpha", "u32"]]],
        ["glBlendEquationOES", "void", [["mode", "u32"]]],
        ["glDrawTexsOES", "void", [["x", "i16"], ["y", "i16"], ["z", "i16"], ["width", "i16"], ["height", "i16"]]],
        ["glDrawTexiOES", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glDrawTexxOES", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glDrawTexsvOES", "void", [["coords", "ptr", "in"]]],
        ["glDrawTexivOES", "void", [["coords", "ptr", "in"]]],
        ["glDrawTexxvOES", "void", [["coords", "ptr", "in"]]],
        ["glDrawTexfOES", "void", [["x", "f32"], ["y", "f32"], ["z", "f32"], ["width", "f32"], ["height", "f32"]]],
        ["glDrawTexfvOES", "void", [["coords", "ptr", "in"]]],
        ["glEGLImageTargetTexture2DOES", "void", [["target", "u32"], ["image", "u32"]]],
        ["glEGLImageTargetRenderbufferStorageOES", "void", [["target", "u32"], ["image", "u32"]]],
        ["glAlphaFuncxOES", "void", [["func", "u32"], ["ref", "i32"]]],
        ["glClearColorxOES", "void", [["red", "i32"], ["green", "i32"], ["blue", "i32"], ["alpha", "i32"]]],
        ["glClearDepthxOES", "void", [["depth", "i32"]]],
        ["glClipPlanexOES", "void", [["plane", "u32"], ["equation", "ptr", "in"]]],
        ["glClipPlanexIMG", "void", [["plane", "u32"], ["equation", "ptr", "in"]]],
        ["glColor4xOES", "void", [["red", "i32"], ["green", "i32"], ["blue", "i32"], ["alpha", "i32"]]],
        ["glDepthRangexOES", "void", [["zNear", "i32"], ["zFar", "i32"]]],
        ["glFogxOES", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glFogxvOES", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glFrustumxOES", "void", [["left", "i32"], ["right", "i32"], ["bottom", "i32"], ["top", "i32"], ["zNear", "i32"], ["zFar", "i32"]]],
        ["glGetClipPlanexOES", "void", [["pname", "u32"], ["eqn", "ptr", "out"]]],
        ["glGetClipPlanex", "void", [["pname", "u32"], ["eqn", "ptr", "out"]]],
        ["glGetFixedvOES", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetLightxvOES", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetMaterialxvOES", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexEnvxvOES", "void", [["env", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexParameterxvOES", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glLightModelxOES", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glLightModelxvOES", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLightxOES", "void", [["light", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glLightxvOES", "void", [["light", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glLineWidthxOES", "void", [["width", "i32"]]],
        ["glLoadMatrixxOES", "void", [["m", "ptr", "in"]]],
        ["glMaterialxOES", "void", [["face", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glMaterialxvOES", "void", [["face", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glMultMatrixxOES", "void", [["m", "ptr", "in"]]],
        ["glMultiTexCoord4xOES", "void", [["target", "u32"], ["s", "i32"], ["t", "i32"], ["r", "i32"], ["q", "i32"]]],
        ["glNormal3xOES", "void", [["nx", "i32"], ["ny", "i32"], ["nz", "i32"]]],
        ["glOrthoxOES", "void", [["left", "i32"], ["right", "i32"], ["bottom", "i32"], ["top", "i32"], ["zNear", "i32"], ["zFar", "i32"]]],
        ["glPointParameterxOES", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glPointParameterxvOES", "void", [["pname", "u32"], ["params", "ptr", "in"]]],
        ["glPointSizexOES", "void", [["size", "i32"]]],
        ["glPolygonOffsetxOES", "void", [["factor", "i32"], ["units", "i32"]]],
        ["glRotatexOES", "void", [["angle", "i32"], ["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glSampleCoveragexOES", "void", [["value", "i32"], ["invert", "u8"]]],
        ["glScalexOES", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glTexEnvxOES", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexEnvxvOES", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexParameterxOES", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexParameterxvOES", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTranslatexOES", "void", [["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glIsRenderbufferOES", "u8", [["renderbuffer", "u32"]]],
        ["glBindRenderbufferOES", "void", [["target", "u32"], ["renderbuffer", "u32"]]],
        ["glDeleteRenderbuffersOES", "void", [["n", "i32"], ["renderbuffers", "ptr", "in"]], ["custom_decoder"]],
        ["glGenRenderbuffersOES", "void", [["n", "i32"], ["renderbuffers", "ptr", "out"]], ["custom_decoder"]],
        ["glRenderbufferStorageOES", "void", [["target", "u32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]]],
        ["glGetRenderbufferParameterivOES", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glIsFramebufferOES", "u8", [["framebuffer", "u32"]]],
        ["glBindFramebufferOES", "void", [["target", "u32"], ["framebuffer", "u32"]]],
        ["glDeleteFramebuffersOES", "void", [["n", "i32"], ["framebuffers", "ptr", "in"]], ["custom_decoder"]],
        ["glGenFramebuffersOES", "void", [["n", "i32"], ["framebuffers", "ptr", "out"]], ["custom_decoder"]],
        ["glCheckFramebufferStatusOES", "u32", [["target", "u32"]]],
        ["glFramebufferRenderbufferOES", "void", [["target", "u32"], ["attachment", "u32"], ["renderbuffertarget", "u32"], ["renderbuffer", "u32"]]],
        ["glFramebufferTexture2DOES", "void", [["target", "u32"], ["attachment", "u32"], ["textarget", "u32"], ["texture", "u32"], ["level", "i32"]]],
        ["glGetFramebufferAttachmentParameterivOES", "void", [["target", "u32"], ["attachment", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGenerateMipmapOES", "void", [["target", "u32"]]],
        ["glMapBufferOES", "u32", [["target", "u32"], ["access", "u32"]], ["unsupported"]],
        ["glUnmapBufferOES", "u8", [["target", "u32"]]],
        ["glGetBufferPointervOES", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glCurrentPaletteMatrixOES", "void", [["matrixpaletteindex", "u32"]]],
        ["glLoadPaletteFromModelViewMatrixOES", "void", []],
        ["glMatrixIndexPointerOES", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glWeightPointerOES", "void", [["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glQueryMatrixxOES", "u32", [["mantissa", "ptr", "out"], ["exponent", "ptr", "out"]]],
        ["glDepthRangefOES", "void", [["zNear", "f32"], ["zFar", "f32"]]],
        ["glFrustumfOES", "void", [["left", "f32"], ["right", "f32"], ["bottom", "f32"], ["top", "f32"], ["zNear", "f32"], ["zFar", "f32"]]],
        ["glOrthofOES", "void", [["left", "f32"], ["right", "f32"], ["bottom", "f32"], ["top", "f32"], ["zNear", "f32"], ["zFar", "f32"]]],
        ["glClipPlanefOES", "void", [["plane", "u32"], ["equation", "ptr", "in"]]],
        ["glClipPlanefIMG", "void", [["plane", "u32"], ["equation", "ptr", "in"]]],
        ["glGetClipPlanefOES", "void", [["pname", "u32"], ["eqn", "ptr", "out"]]],
        ["glClearDepthfOES", "void", [["depth", "f32"]]],
        ["glTexGenfOES", "void", [["coord", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glTexGenfvOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexGeniOES", "void", [["coord", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexGenivOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexGenxOES", "void", [["coord", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexGenxvOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glGetTexGenfvOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glGetTexGenivOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glGetTexGenxvOES", "void", [["coord", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glBindVertexArrayOES", "void", [["array", "u32"]]],
        ["glDeleteVertexArraysOES", "void", [["n", "i32"], ["arrays", "ptr", "in"]], ["custom_decoder"]],
        ["glGenVertexArraysOES", "void", [["n", "i32"], ["arrays", "ptr", "out"]], ["custom_decoder"]],
        ["glIsVertexArrayOES", "u8", [["array", "u32"]]],
        ["glDiscardFramebufferEXT", "void", [["target", "u32"], ["numAttachments", "i32"], ["attachments", "ptr", "in"]]],
        ["glMultiDrawArraysEXT", "void", [["mode", "u32"], ["first", "ptr", "in"], ["count", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glMultiDrawElementsEXT", "void", [["mode", "u32"], ["count", "ptr", "in"], ["type", "u32"], ["indices", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glMultiDrawArraysSUN", "void", [["mode", "u32"], ["first", "ptr", "in"], ["count", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glMultiDrawElementsSUN", "void", [["mode", "u32"], ["count", "ptr", "in"], ["type", "u32"], ["indices", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glRenderbufferStorageMultisampleIMG", "void", [["target", "u32"], ["samples", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]]],
        ["glFramebufferTexture2DMultisampleIMG", "void", [["target", "u32"], ["attachment", "u32"], ["textarget", "u32"], ["texture", "u32"], ["level", "i32"], ["samples", "i32"]]],
        ["glDeleteFencesNV", "void", [["n", "i32"], ["fences", "ptr", "in"]]],
        ["glGenFencesNV", "void", [["n", "i32"], ["fences", "ptr", "in"]]],
        ["glIsFenceNV", "u8", [["fence", "u32"]]],
        ["glTestFenceNV", "u8", [["fence", "u32"]]],
        ["glGetFenceivNV", "void", [["fence", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glFinishFenceNV", "void", [["fence", "u32"]]],
        ["glSetFenceNV", "void", [["fence", "u32"], ["condition", "u32"]]],
        ["glGetDriverControlsQCOM", "void", [["num", "ptr", "out"], ["size", "i32"], ["driverControls", "ptr", "out"]]],
        ["glGetDriverControlStringQCOM", "void", [["driverControl", "u32"], ["bufSize", "i32"], ["length", "ptr", "out"], ["driverControlString", "ptr", "out"]]],
        ["glEnableDriverControlQCOM", "void", [["driverControl", "u32"]]],
        ["glDisableDriverControlQCOM", "void", [["driverControl", "u32"]]],
        ["glExtGetTexturesQCOM", "void", [["textures", "ptr", "out"], ["maxTextures", "i32"], ["numTextures", "ptr", "out"]]],
        ["glExtGetBuffersQCOM", "void", [["buffers", "ptr", "out"], ["maxBuffers", "i32"], ["numBuffers", "ptr", "out"]]],
        ["glExtGetRenderbuffersQCOM", "void", [["renderbuffers", "ptr", "out"], ["maxRenderbuffers", "i32"], ["numRenderbuffers", "ptr", "out"]]],
        ["glExtGetFramebuffersQCOM", "void", [["framebuffers", "ptr", "out"], ["maxFramebuffers", "i32"], ["numFramebuffers", "ptr", "out"]]],
        ["glExtGetTexLevelParameterivQCOM", "void", [["texture", "u32"], ["face", "u32"], ["level", "i32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glExtTexObjectStateOverrideiQCOM", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glExtGetTexSubImageQCOM", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["type", "u32"], ["texels", "ptr", "out"]]],
        ["glExtGetBufferPointervQCOM", "void", [["target", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glExtGetShadersQCOM", "void", [["shaders", "ptr", "out"], ["maxShaders", "i32"], ["numShaders", "ptr", "out"]]],
        ["glExtGetProgramsQCOM", "void", [["programs", "ptr", "out"], ["maxPrograms", "i32"], ["numPrograms", "ptr", "out"]]],
        ["glExtIsProgramBinaryQCOM", "u8", [["program", "u32"]]],
        ["glExtGetProgramBinarySourceQCOM", "void", [["program", "u32"], ["shadertype", "u32"], ["source", "ptr", "in"], ["length", "ptr", "in"]], ["unsupported"]],
        ["glStartTilingQCOM", "void", [["x", "u32"], ["y", "u32"], ["width", "u32"], ["height", "u32"], ["preserveMask", "u32"]]],
        ["glEndTilingQCOM", "void", [["preserveMask", "u32"]]],
        ["glGetGraphicsResetStatusEXT", "u32", []],
        ["glReadnPixelsEXT", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["bufSize", "i32"], ["data", "ptr", "out"]]],
    ] },
    gles2: { base: 2048, commands: [
        ["glActiveTexture", "void", [["texture", "u32"]]],
        ["glAttachShader", "void", [["program", "u32"], ["shader", "u32"]], ["custom_decoder"]],
        ["glBindAttribLocation", "void", [["program", "u32"], ["index", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glBindBuffer", "void", [["target", "u32"], ["buffer", "u32"]]],
        ["glBindFramebuffer", "void", [["target", "u32"], ["framebuffer", "u32"]]],
        ["glBindRenderbuffer", "void", [["target", "u32"], ["renderbuffer", "u32"]]],
        ["glBindTexture", "void", [["target", "u32"], ["texture", "u32"]]],
        ["glBlendColor", "void", [["red", "f32"], ["green", "f32"], ["blue", "f32"], ["alpha", "f32"]]],
        ["glBlendEquation", "void", [["mode", "u32"]]],
        ["glBlendEquationSeparate", "void", [["modeRGB", "u32"], ["modeAlpha", "u32"]]],
        ["glBlendFunc", "void", [["sfactor", "u32"], ["dfactor", "u32"]]],
        ["glBlendFuncSeparate", "void", [["srcRGB", "u32"], ["dstRGB", "u32"], ["srcAlpha", "u32"], ["dstAlpha", "u32"]]],
        ["glBufferData", "void", [["target", "u32"], ["size", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]], ["usage", "u32"]]],
        ["glBufferSubData", "void", [["target", "u32"], ["offset", "i32"], ["size", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCheckFramebufferStatus", "u32", [["target", "u32"]]],
        ["glClear", "void", [["mask", "u32"]]],
        ["glClearColor", "void", [["red", "f32"], ["green", "f32"], ["blue", "f32"], ["alpha", "f32"]]],
        ["glClearDepthf", "void", [["depth", "f32"]]],
        ["glClearStencil", "void", [["s", "i32"]]],
        ["glColorMask", "void", [["red", "u8"], ["green", "u8"], ["blue", "u8"], ["alpha", "u8"]]],
        ["glCompileShader", "void", [["shader", "u32"]], ["custom_decoder"]],
        ["glCompressedTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCompressedTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCopyTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["border", "i32"]]],
        ["glCopyTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glCreateProgram", "u32", [], ["custom_decoder"]],
        ["glCreateShader", "u32", [["type", "u32"]], ["custom_decoder"]],
        ["glCullFace", "void", [["mode", "u32"]]],
        ["glDeleteBuffers", "void", [["n", "i32"], ["buffers", "ptr", "in"]], ["custom_decoder"]],
        ["glDeleteFramebuffers", "void", [["n", "i32"], ["framebuffers", "ptr", "in"]], ["custom_decoder"]],
        ["glDeleteProgram", "void", [["program", "u32"]], ["custom_decoder"]],
        ["glDeleteRenderbuffers", "void", [["n", "i32"], ["renderbuffers", "ptr", "in"]], ["custom_decoder"]],
        ["glDeleteShader", "void", [["shader", "u32"]], ["custom_decoder"]],
        ["glDeleteTextures", "void", [["n", "i32"], ["textures", "ptr", "in"]], ["custom_decoder"]],
        ["glDepthFunc", "void", [["func", "u32"]]],
        ["glDepthMask", "void", [["flag", "u8"]]],
        ["glDepthRangef", "void", [["zNear", "f32"], ["zFar", "f32"]]],
        ["glDetachShader", "void", [["program", "u32"], ["shader", "u32"]], ["custom_decoder"]],
        ["glDisable", "void", [["cap", "u32"]]],
        ["glDisableVertexAttribArray", "void", [["index", "u32"]]],
        ["glDrawArrays", "void", [["mode", "u32"], ["first", "i32"], ["count", "i32"]]],
        ["glDrawElements", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"]], ["unsupported"]],
        ["glEnable", "void", [["cap", "u32"]]],
        ["glEnableVertexAttribArray", "void", [["index", "u32"]]],
        ["glFinish", "void", []],
        ["glFlush", "void", []],
        ["glFramebufferRenderbuffer", "void", [["target", "u32"], ["attachment", "u32"], ["renderbuffertarget", "u32"], ["renderbuffer", "u32"]]],
        ["glFramebufferTexture2D", "void", [["target", "u32"], ["attachment", "u32"], ["textarget", "u32"], ["texture", "u32"], ["level", "i32"]]],
        ["glFrontFace", "void", [["mode", "u32"]]],
        ["glGenBuffers", "void", [["n", "i32"], ["buffers", "ptr", "out"]], ["custom_decoder"]],
        ["glGenerateMipmap", "void", [["target", "u32"]]],
        ["glGenFramebuffers", "void", [["n", "i32"], ["framebuffers", "ptr", "out"]], ["custom_decoder"]],
        ["glGenRenderbuffers", "void", [["n", "i32"], ["renderbuffers", "ptr", "out"]], ["custom_decoder"]],
        ["glGenTextures", "void", [["n", "i32"], ["textures", "ptr", "out"]], ["custom_decoder"]],
        ["glGetActiveAttrib", "void", [["program", "u32"], ["index", "u32"], ["bufsize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["size", "ptr", "out", ["nullAllowed"]], ["type", "ptr", "out", ["nullAllowed"]], ["name", "ptr", "out", ["nullAllowed"]]], ["custom_decoder"]],
        ["glGetActiveUniform", "void", [["program", "u32"], ["index", "u32"], ["bufsize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["size", "ptr", "out", ["nullAllowed"]], ["type", "ptr", "out", ["nullAllowed"]], ["name", "ptr", "out", ["nullAllowed"]]], ["custom_decoder"]],
        ["glGetAttachedShaders", "void", [["program", "u32"], ["maxcount", "i32"], ["count", "ptr", "out", ["nullAllowed"]], ["shaders", "ptr", "out"]], ["custom_decoder"]],
        ["glGetAttribLocation", "i32", [["program", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glGetBooleanv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetBufferParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetError", "u32", []],
        ["glGetFloatv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetFramebufferAttachmentParameteriv", "void", [["target", "u32"], ["attachment", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetIntegerv", "void", [["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetProgramiv", "void", [["program", "u32"], ["pname", "u32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetProgramInfoLog", "void", [["program", "u32"], ["bufsize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["infolog", "ptr", "out"]], ["custom_decoder"]],
        ["glGetRenderbufferParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetShaderiv", "void", [["shader", "u32"], ["pname", "u32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetShaderInfoLog", "void", [["shader", "u32"], ["bufsize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["infolog", "ptr", "out"]], ["custom_decoder"]],
        ["glGetShaderPrecisionFormat", "void", [["shadertype", "u32"], ["precisiontype", "u32"], ["range", "ptr", "out"], ["precision", "ptr", "out"]]],
        ["glGetShaderSource", "void", [["shader", "u32"], ["bufsize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["source", "ptr", "out"]], ["custom_decoder"]],
        ["glGetString", "u32", [["name", "u32"]], ["unsupported"]],
        ["glGetTexParameterfv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetUniformfv", "void", [["program", "u32"], ["location", "i32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetUniformiv", "void", [["program", "u32"], ["location", "i32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetUniformLocation", "i32", [["program", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glGetVertexAttribfv", "void", [["index", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetVertexAttribiv", "void", [["index", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetVertexAttribPointerv", "void", [["index", "u32"], ["pname", "u32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glHint", "void", [["target", "u32"], ["mode", "u32"]]],
        ["glIsBuffer", "u8", [["buffer", "u32"]]],
        ["glIsEnabled", "u8", [["cap", "u32"]]],
        ["glIsFramebuffer", "u8", [["framebuffer", "u32"]]],
        ["glIsProgram", "u8", [["program", "u32"]], ["custom_decoder"]],
        ["glIsRenderbuffer", "u8", [["renderbuffer", "u32"]]],
        ["glIsShader", "u8", [["shader", "u32"]], ["custom_decoder"]],
        ["glIsTexture", "u8", [["texture", "u32"]]],
        ["glLineWidth", "void", [["width", "f32"]]],
        ["glLinkProgram", "void", [["program", "u32"]], ["custom_decoder"]],
        ["glPixelStorei", "void", [["pname", "u32"], ["param", "i32"]]],
        ["glPolygonOffset", "void", [["factor", "f32"], ["units", "f32"]]],
        ["glReadPixels", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "out"]]],
        ["glReleaseShaderCompiler", "void", []],
        ["glRenderbufferStorage", "void", [["target", "u32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]]],
        ["glSampleCoverage", "void", [["value", "f32"], ["invert", "u8"]]],
        ["glScissor", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glShaderBinary", "void", [["n", "i32"], ["shaders", "ptr", "in"], ["binaryformat", "u32"], ["binary", "ptr", "in"], ["length", "i32"]], ["unsupported"]],
        ["glShaderSource", "void", [["shader", "u32"], ["count", "i32"], ["string", "ptr", "in"], ["length", "ptr", "in"]], ["unsupported"]],
        ["glStencilFunc", "void", [["func", "u32"], ["ref", "i32"], ["mask", "u32"]]],
        ["glStencilFuncSeparate", "void", [["face", "u32"], ["func", "u32"], ["ref", "i32"], ["mask", "u32"]]],
        ["glStencilMask", "void", [["mask", "u32"]]],
        ["glStencilMaskSeparate", "void", [["face", "u32"], ["mask", "u32"]]],
        ["glStencilOp", "void", [["fail", "u32"], ["zfail", "u32"], ["zpass", "u32"]]],
        ["glStencilOpSeparate", "void", [["face", "u32"], ["fail", "u32"], ["zfail", "u32"], ["zpass", "u32"]]],
        ["glTexImage2D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "i32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTexParameterf", "void", [["target", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glTexParameterfv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexParameteri", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glTexParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glTexSubImage2D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glUniform1f", "void", [["location", "i32"], ["x", "f32"]]],
        ["glUniform1fv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform1i", "void", [["location", "i32"], ["x", "i32"]]],
        ["glUniform1iv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform2f", "void", [["location", "i32"], ["x", "f32"], ["y", "f32"]]],
        ["glUniform2fv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform2i", "void", [["location", "i32"], ["x", "i32"], ["y", "i32"]]],
        ["glUniform2iv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform3f", "void", [["location", "i32"], ["x", "f32"], ["y", "f32"], ["z", "f32"]]],
        ["glUniform3fv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform3i", "void", [["location", "i32"], ["x", "i32"], ["y", "i32"], ["z", "i32"]]],
        ["glUniform3iv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform4f", "void", [["location", "i32"], ["x", "f32"], ["y", "f32"], ["z", "f32"], ["w", "f32"]]],
        ["glUniform4fv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniform4i", "void", [["location", "i32"], ["x", "i32"], ["y", "i32"], ["z", "i32"], ["w", "i32"]]],
        ["glUniform4iv", "void", [["location", "i32"], ["count", "i32"], ["v", "ptr", "in"]]],
        ["glUniformMatrix2fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix3fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix4fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUseProgram", "void", [["program", "u32"]], ["custom_decoder"]],
        ["glValidateProgram", "void", [["program", "u32"]], ["custom_decoder"]],
        ["glVertexAttrib1f", "void", [["indx", "u32"], ["x", "f32"]]],
        ["glVertexAttrib1fv", "void", [["indx", "u32"], ["values", "ptr", "in"]]],
        ["glVertexAttrib2f", "void", [["indx", "u32"], ["x", "f32"], ["y", "f32"]]],
        ["glVertexAttrib2fv", "void", [["indx", "u32"], ["values", "ptr", "in"]]],
        ["glVertexAttrib3f", "void", [["indx", "u32"], ["x", "f32"], ["y", "f32"], ["z", "f32"]]],
        ["glVertexAttrib3fv", "void", [["indx", "u32"], ["values", "ptr", "in"]]],
        ["glVertexAttrib4f", "void", [["indx", "u32"], ["x", "f32"], ["y", "f32"], ["z", "f32"], ["w", "f32"]]],
        ["glVertexAttrib4fv", "void", [["indx", "u32"], ["values", "ptr", "in"]]],
        ["glVertexAttribPointer", "void", [["indx", "u32"], ["size", "i32"], ["type", "u32"], ["normalized", "u8"], ["stride", "i32"], ["ptr", "ptr", "in"]], ["unsupported"]],
        ["glViewport", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glEGLImageTargetTexture2DOES", "void", [["target", "u32"], ["image", "u32"]]],
        ["glEGLImageTargetRenderbufferStorageOES", "void", [["target", "u32"], ["image", "u32"]]],
        ["glGetProgramBinaryOES", "void", [["program", "u32"], ["bufSize", "i32"], ["length", "ptr", "in"], ["binaryFormat", "ptr", "in"], ["binary", "ptr", "in"]], ["unsupported","custom_decoder"]],
        ["glProgramBinaryOES", "void", [["program", "u32"], ["binaryFormat", "u32"], ["binary", "ptr", "in"], ["length", "i32"]], ["unsupported","custom_decoder"]],
        ["glMapBufferOES", "u32", [["target", "u32"], ["access", "u32"]], ["unsupported"]],
        ["glUnmapBufferOES", "u8", [["target", "u32"]]],
        ["glTexImage3DOES", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTexSubImage3DOES", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["type", "u32"], ["pixels", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCopyTexSubImage3DOES", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glCompressedTexImage3DOES", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCompressedTexSubImage3DOES", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glFramebufferTexture3DOES", "void", [["target", "u32"], ["attachment", "u32"], ["textarget", "u32"], ["texture", "u32"], ["level", "i32"], ["zoffset", "i32"]]],
        ["glBindVertexArrayOES", "void", [["array", "u32"]]],
        ["glDeleteVertexArraysOES", "void", [["n", "i32"], ["arrays", "ptr", "in"]], ["custom_decoder"]],
        ["glGenVertexArraysOES", "void", [["n", "i32"], ["arrays", "ptr", "out"]], ["custom_decoder"]],
        ["glIsVertexArrayOES", "u8", [["array", "u32"]]],
        ["glDiscardFramebufferEXT", "void", [["target", "u32"], ["numAttachments", "i32"], ["attachments", "ptr", "in"]]],
        ["glMultiDrawArraysEXT", "void", [["mode", "u32"], ["first", "ptr", "in"], ["count", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glMultiDrawElementsEXT", "void", [["mode", "u32"], ["count", "ptr", "in"], ["type", "u32"], ["indices", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glGetPerfMonitorGroupsAMD", "void", [["numGroups", "ptr", "in"], ["groupsSize", "i32"], ["groups", "ptr", "in"]], ["unsupported"]],
        ["glGetPerfMonitorCountersAMD", "void", [["group", "u32"], ["numCounters", "ptr", "in"], ["maxActiveCounters", "ptr", "in"], ["counterSize", "i32"], ["counters", "ptr", "in"]], ["unsupported"]],
        ["glGetPerfMonitorGroupStringAMD", "void", [["group", "u32"], ["bufSize", "i32"], ["length", "ptr", "in"], ["groupString", "ptr", "in"]], ["unsupported"]],
        ["glGetPerfMonitorCounterStringAMD", "void", [["group", "u32"], ["counter", "u32"], ["bufSize", "i32"], ["length", "ptr", "in"], ["counterString", "ptr", "in"]], ["unsupported"]],
        ["glGetPerfMonitorCounterInfoAMD", "void", [["group", "u32"], ["counter", "u32"], ["pname", "u32"], ["data", "ptr", "in"]], ["unsupported"]],
        ["glGenPerfMonitorsAMD", "void", [["n", "i32"], ["monitors", "ptr", "in"]], ["unsupported"]],
        ["glDeletePerfMonitorsAMD", "void", [["n", "i32"], ["monitors", "ptr", "in"]], ["unsupported"]],
        ["glSelectPerfMonitorCountersAMD", "void", [["monitor", "u32"], ["enable", "u8"], ["group", "u32"], ["numCounters", "i32"], ["countersList", "ptr", "in"]], ["unsupported"]],
        ["glBeginPerfMonitorAMD", "void", [["monitor", "u32"]], ["unsupported"]],
        ["glEndPerfMonitorAMD", "void", [["monitor", "u32"]], ["unsupported"]],
        ["glGetPerfMonitorCounterDataAMD", "void", [["monitor", "u32"], ["pname", "u32"], ["dataSize", "i32"], ["data", "ptr", "in"], ["bytesWritten", "ptr", "in"]], ["unsupported"]],
        ["glRenderbufferStorageMultisampleIMG", "void", [["target", "u32"], ["samples", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]], ["unsupported"]],
        ["glFramebufferTexture2DMultisampleIMG", "void", [["target", "u32"], ["attachment", "u32"], ["textarget", "u32"], ["texture", "u32"], ["level", "i32"], ["samples", "i32"]], ["unsupported"]],
        ["glDeleteFencesNV", "void", [["n", "i32"], ["fences", "ptr", "in"]], ["unsupported"]],
        ["glGenFencesNV", "void", [["n", "i32"], ["fences", "ptr", "in"]], ["unsupported"]],
        ["glIsFenceNV", "u8", [["fence", "u32"]], ["unsupported"]],
        ["glTestFenceNV", "u8", [["fence", "u32"]], ["unsupported"]],
        ["glGetFenceivNV", "void", [["fence", "u32"], ["pname", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glFinishFenceNV", "void", [["fence", "u32"]], ["unsupported"]],
        ["glSetFenceNV", "void", [["fence", "u32"], ["condition", "u32"]], ["unsupported"]],
        ["glCoverageMaskNV", "void", [["mask", "u8"]], ["unsupported"]],
        ["glCoverageOperationNV", "void", [["operation", "u32"]], ["unsupported"]],
        ["glGetDriverControlsQCOM", "void", [["num", "ptr", "in"], ["size", "i32"], ["driverControls", "ptr", "in"]], ["unsupported"]],
        ["glGetDriverControlStringQCOM", "void", [["driverControl", "u32"], ["bufSize", "i32"], ["length", "ptr", "in"], ["driverControlString", "ptr", "in"]], ["unsupported"]],
        ["glEnableDriverControlQCOM", "void", [["driverControl", "u32"]], ["unsupported"]],
        ["glDisableDriverControlQCOM", "void", [["driverControl", "u32"]], ["unsupported"]],
        ["glExtGetTexturesQCOM", "void", [["textures", "ptr", "in"], ["maxTextures", "i32"], ["numTextures", "ptr", "in"]], ["unsupported"]],
        ["glExtGetBuffersQCOM", "void", [["buffers", "ptr", "in"], ["maxBuffers", "i32"], ["numBuffers", "ptr", "in"]], ["unsupported"]],
        ["glExtGetRenderbuffersQCOM", "void", [["renderbuffers", "ptr", "in"], ["maxRenderbuffers", "i32"], ["numRenderbuffers", "ptr", "in"]], ["unsupported"]],
        ["glExtGetFramebuffersQCOM", "void", [["framebuffers", "ptr", "in"], ["maxFramebuffers", "i32"], ["numFramebuffers", "ptr", "in"]], ["unsupported"]],
        ["glExtGetTexLevelParameterivQCOM", "void", [["texture", "u32"], ["face", "u32"], ["level", "i32"], ["pname", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glExtTexObjectStateOverrideiQCOM", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]], ["unsupported"]],
        ["glExtGetTexSubImageQCOM", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["type", "u32"], ["texels", "ptr", "in"]], ["unsupported"]],
        ["glExtGetBufferPointervQCOM", "void", [["target", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glExtGetShadersQCOM", "void", [["shaders", "ptr", "in"], ["maxShaders", "i32"], ["numShaders", "ptr", "in"]], ["unsupported"]],
        ["glExtGetProgramsQCOM", "void", [["programs", "ptr", "in"], ["maxPrograms", "i32"], ["numPrograms", "ptr", "in"]], ["unsupported"]],
        ["glExtIsProgramBinaryQCOM", "u8", [["program", "u32"]], ["unsupported"]],
        ["glExtGetProgramBinarySourceQCOM", "void", [["program", "u32"], ["shadertype", "u32"], ["source", "ptr", "in"], ["length", "ptr", "in"]], ["unsupported"]],
        ["glStartTilingQCOM", "void", [["x", "u32"], ["y", "u32"], ["width", "u32"], ["height", "u32"], ["preserveMask", "u32"]], ["unsupported"]],
        ["glEndTilingQCOM", "void", [["preserveMask", "u32"]], ["unsupported"]],
        ["glVertexAttribPointerData", "void", [["indx", "u32"], ["size", "i32"], ["type", "u32"], ["normalized", "u8"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glVertexAttribPointerOffset", "void", [["indx", "u32"], ["size", "i32"], ["type", "u32"], ["normalized", "u8"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsOffset", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsData", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glGetCompressedTextureFormats", "void", [["count", "i32"], ["formats", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glShaderString", "void", [["shader", "u32"], ["string", "ptr", "in"], ["len", "i32"]], ["custom_decoder","not_api"]],
        ["glFinishRoundTrip", "i32", [], ["custom_decoder","not_api"]],
        ["glGenVertexArrays", "void", [["n", "i32"], ["arrays", "ptr", "out"]], ["custom_decoder"]],
        ["glBindVertexArray", "void", [["array", "u32"]]],
        ["glDeleteVertexArrays", "void", [["n", "i32"], ["arrays", "ptr", "in"]], ["custom_decoder"]],
        ["glIsVertexArray", "u8", [["array", "u32"]]],
        ["glMapBufferRange", "u32", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"]], ["unsupported"]],
        ["glUnmapBuffer", "u8", [["target", "u32"]], ["unsupported"]],
        ["glFlushMappedBufferRange", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"]], ["unsupported"]],
        ["glMapBufferRangeAEMU", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["mapped", "ptr", "out", ["nullAllowed"]]], ["custom_decoder","not_api"]],
        ["glUnmapBufferAEMU", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["guest_buffer", "ptr", "in", ["nullAllowed"]], ["out_res", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glFlushMappedBufferRangeAEMU", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["guest_buffer", "ptr", "in", ["nullAllowed"]]], ["custom_decoder","not_api"]],
        ["glReadPixelsOffsetAEMU", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api","custom_decoder","not_api"]],
        ["glCompressedTexImage2DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["imageSize", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glCompressedTexSubImage2DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["imageSize", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glTexImage2DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "i32"], ["width", "i32"], ["height", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glTexSubImage2DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glBindBufferRange", "void", [["target", "u32"], ["index", "u32"], ["buffer", "u32"], ["offset", "i32"], ["size", "i32"]]],
        ["glBindBufferBase", "void", [["target", "u32"], ["index", "u32"], ["buffer", "u32"]]],
        ["glCopyBufferSubData", "void", [["readtarget", "u32"], ["writetarget", "u32"], ["readoffset", "i32"], ["writeoffset", "i32"], ["size", "i32"]], ["flushOnEncode"]],
        ["glClearBufferiv", "void", [["buffer", "u32"], ["drawBuffer", "i32"], ["value", "ptr", "in"]]],
        ["glClearBufferuiv", "void", [["buffer", "u32"], ["drawBuffer", "i32"], ["value", "ptr", "in"]]],
        ["glClearBufferfv", "void", [["buffer", "u32"], ["drawBuffer", "i32"], ["value", "ptr", "in"]]],
        ["glClearBufferfi", "void", [["buffer", "u32"], ["drawBuffer", "i32"], ["depth", "f32"], ["stencil", "i32"]]],
        ["glGetBufferParameteri64v", "void", [["target", "u32"], ["value", "u32"], ["data", "ptr", "in"]], ["unsupported"]],
        ["glGetBufferPointerv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "in"]], ["unsupported"]],
        ["glUniformBlockBinding", "void", [["program", "u32"], ["uniformBlockIndex", "u32"], ["uniformBlockBinding", "u32"]], ["custom_decoder"]],
        ["glGetUniformBlockIndex", "u32", [["program", "u32"], ["uniformBlockName", "ptr", "in"]], ["custom_decoder"]],
        ["glGetUniformIndices", "void", [["program", "u32"], ["uniformCount", "i32"], ["uniformNames", "ptr", "in"], ["uniformIndices", "ptr", "in"]], ["unsupported"]],
        ["glGetUniformIndicesAEMU", "void", [["program", "u32"], ["uniformCount", "i32"], ["packedUniformNames", "ptr", "in"], ["packedLen", "i32"], ["uniformIndices", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glGetActiveUniformBlockiv", "void", [["program", "u32"], ["uniformBlockIndex", "u32"], ["pname", "u32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetActiveUniformBlockName", "void", [["program", "u32"], ["uniformBlockIndex", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["uniformBlockName", "ptr", "out", ["nullAllowed"]]], ["custom_decoder"]],
        ["glUniform1ui", "void", [["location", "i32"], ["v0", "u32"]]],
        ["glUniform2ui", "void", [["location", "i32"], ["v0", "u32"], ["v1", "u32"]]],
        ["glUniform3ui", "void", [["location", "i32"], ["v0", "u32"], ["v1", "u32"], ["v2", "u32"]]],
        ["glUniform4ui", "void", [["location", "i32"], ["v0", "i32"], ["v1", "u32"], ["v2", "u32"], ["v3", "u32"]]],
        ["glUniform1uiv", "void", [["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]]],
        ["glUniform2uiv", "void", [["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]]],
        ["glUniform3uiv", "void", [["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]]],
        ["glUniform4uiv", "void", [["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]]],
        ["glUniformMatrix2x3fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix3x2fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix2x4fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix4x2fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix3x4fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glUniformMatrix4x3fv", "void", [["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]]],
        ["glGetUniformuiv", "void", [["program", "u32"], ["location", "i32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetActiveUniformsiv", "void", [["program", "u32"], ["uniformCount", "i32"], ["uniformIndices", "ptr", "in"], ["pname", "u32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glVertexAttribI4i", "void", [["index", "u32"], ["v0", "i32"], ["v1", "i32"], ["v2", "i32"], ["v3", "i32"]]],
        ["glVertexAttribI4ui", "void", [["index", "u32"], ["v0", "u32"], ["v1", "u32"], ["v2", "u32"], ["v3", "u32"]]],
        ["glVertexAttribI4iv", "void", [["index", "u32"], ["v", "ptr", "in"]]],
        ["glVertexAttribI4uiv", "void", [["index", "u32"], ["v", "ptr", "in"]]],
        ["glVertexAttribIPointer", "void", [["index", "u32"], ["size", "i32"], ["type", "u32"], ["stride", "i32"], ["pointer", "ptr", "in"]], ["unsupported"]],
        ["glVertexAttribIPointerOffsetAEMU", "void", [["index", "u32"], ["size", "i32"], ["type", "u32"], ["stride", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glVertexAttribIPointerDataAEMU", "void", [["index", "u32"], ["size", "i32"], ["type", "u32"], ["stride", "i32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glGetVertexAttribIiv", "void", [["index", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetVertexAttribIuiv", "void", [["index", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glVertexAttribDivisor", "void", [["index", "u32"], ["divisor", "u32"]]],
        ["glDrawArraysInstanced", "void", [["mode", "u32"], ["first", "i32"], ["count", "i32"], ["primcount", "i32"]]],
        ["glDrawElementsInstanced", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"], ["primcount", "i32"]], ["unsupported"]],
        ["glDrawElementsInstancedDataAEMU", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"], ["primcount", "i32"], ["datalen", "i32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsInstancedOffsetAEMU", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["offset", "u32"], ["primcount", "i32"]], ["custom_decoder","not_api"]],
        ["glDrawRangeElements", "void", [["mode", "u32"], ["start", "u32"], ["end", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"]], ["unsupported"]],
        ["glDrawRangeElementsDataAEMU", "void", [["mode", "u32"], ["start", "u32"], ["end", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"], ["datalen", "i32"]], ["custom_decoder","not_api"]],
        ["glDrawRangeElementsOffsetAEMU", "void", [["mode", "u32"], ["start", "u32"], ["end", "u32"], ["count", "i32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glFenceSync", "u64", [["condition", "u32"], ["flags", "u32"]], ["unsupported"]],
        ["glClientWaitSync", "u32", [["wait_on", "u64"], ["flags", "u32"], ["timeout", "u64"]], ["unsupported"]],
        ["glWaitSync", "void", [["wait_on", "u64"], ["flags", "u32"], ["timeout", "u64"]], ["unsupported"]],
        ["glDeleteSync", "void", [["to_delete", "u64"]], ["unsupported"]],
        ["glIsSync", "u8", [["sync", "u64"]], ["unsupported"]],
        ["glGetSynciv", "void", [["sync", "u64"], ["pname", "u32"], ["bufSize", "i32"], ["length", "ptr", "in"], ["values", "ptr", "in"]], ["unsupported"]],
        ["glFenceSyncAEMU", "u64", [["condition", "u32"], ["flags", "u32"]], ["custom_decoder","not_api"]],
        ["glClientWaitSyncAEMU", "u32", [["wait_on", "u64"], ["flags", "u32"], ["timeout", "u64"]], ["custom_decoder","not_api"]],
        ["glWaitSyncAEMU", "void", [["wait_on", "u64"], ["flags", "u32"], ["timeout", "u64"]], ["custom_decoder","not_api"]],
        ["glDeleteSyncAEMU", "void", [["to_delete", "u64"]], ["custom_decoder","not_api"]],
        ["glIsSyncAEMU", "u8", [["sync", "u64"]], ["custom_decoder","not_api"]],
        ["glGetSyncivAEMU", "void", [["sync", "u64"], ["pname", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["values", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glDrawBuffers", "void", [["n", "i32"], ["bufs", "ptr", "in"]]],
        ["glReadBuffer", "void", [["src", "u32"]]],
        ["glBlitFramebuffer", "void", [["srcX0", "i32"], ["srcY0", "i32"], ["srcX1", "i32"], ["srcY1", "i32"], ["dstX0", "i32"], ["dstY0", "i32"], ["dstX1", "i32"], ["dstY1", "i32"], ["mask", "u32"], ["filter", "u32"]]],
        ["glInvalidateFramebuffer", "void", [["target", "u32"], ["numAttachments", "i32"], ["attachments", "ptr", "in"]]],
        ["glInvalidateSubFramebuffer", "void", [["target", "u32"], ["numAttachments", "i32"], ["attachments", "ptr", "in"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glFramebufferTextureLayer", "void", [["target", "u32"], ["attachment", "u32"], ["texture", "u32"], ["level", "i32"], ["layer", "i32"]]],
        ["glRenderbufferStorageMultisample", "void", [["target", "u32"], ["samples", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]]],
        ["glTexStorage2D", "void", [["target", "u32"], ["levels", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"]]],
        ["glGetInternalformativ", "void", [["target", "u32"], ["internalformat", "u32"], ["pname", "u32"], ["bufSize", "i32"], ["params", "ptr", "out"]]],
        ["glBeginTransformFeedback", "void", [["primitiveMode", "u32"]]],
        ["glEndTransformFeedback", "void", []],
        ["glGenTransformFeedbacks", "void", [["n", "i32"], ["ids", "ptr", "out"]], ["custom_decoder"]],
        ["glDeleteTransformFeedbacks", "void", [["n", "i32"], ["ids", "ptr", "in"]], ["custom_decoder"]],
        ["glBindTransformFeedback", "void", [["target", "u32"], ["id", "u32"]]],
        ["glPauseTransformFeedback", "void", []],
        ["glResumeTransformFeedback", "void", []],
        ["glIsTransformFeedback", "u8", [["id", "u32"]]],
        ["glTransformFeedbackVaryings", "void", [["program", "u32"], ["count", "i32"], ["varyings", "ptr", "in"], ["bufferMode", "u32"]], ["unsupported","custom_decoder"]],
        ["glTransformFeedbackVaryingsAEMU", "void", [["program", "u32"], ["count", "i32"], ["packedVaryings", "ptr", "in"], ["packedVaryingsLen", "u32"], ["bufferMode", "u32"]], ["custom_decoder","not_api"]],
        ["glGetTransformFeedbackVarying", "void", [["program", "u32"], ["index", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["size", "ptr", "out"], ["type", "ptr", "out", ["nullAllowed","nullAllowed"]], ["name", "ptr", "out", ["nullAllowed"]]], ["custom_decoder"]],
        ["glGenSamplers", "void", [["n", "i32"], ["samplers", "ptr", "out"]], ["custom_decoder"]],
        ["glDeleteSamplers", "void", [["n", "i32"], ["samplers", "ptr", "in"]], ["custom_decoder"]],
        ["glBindSampler", "void", [["unit", "u32"], ["sampler", "u32"]]],
        ["glSamplerParameterf", "void", [["sampler", "u32"], ["pname", "u32"], ["param", "f32"]]],
        ["glSamplerParameteri", "void", [["sampler", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glSamplerParameterfv", "void", [["sampler", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glSamplerParameteriv", "void", [["sampler", "u32"], ["pname", "u32"], ["params", "ptr", "in"]]],
        ["glGetSamplerParameterfv", "void", [["sampler", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetSamplerParameteriv", "void", [["sampler", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glIsSampler", "u8", [["sampler", "u32"]]],
        ["glGenQueries", "void", [["n", "i32"], ["queries", "ptr", "out"]], ["custom_decoder"]],
        ["glDeleteQueries", "void", [["n", "i32"], ["queries", "ptr", "in"]], ["custom_decoder"]],
        ["glBeginQuery", "void", [["target", "u32"], ["query", "u32"]]],
        ["glEndQuery", "void", [["target", "u32"]]],
        ["glGetQueryiv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetQueryObjectuiv", "void", [["query", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glIsQuery", "u8", [["query", "u32"]]],
        ["glProgramParameteri", "void", [["program", "u32"], ["pname", "u32"], ["value", "i32"]], ["custom_decoder"]],
        ["glProgramBinary", "void", [["program", "u32"], ["binaryFormat", "u32"], ["binary", "ptr", "in"], ["length", "i32"]], ["custom_decoder"]],
        ["glGetProgramBinary", "void", [["program", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["binaryFormat", "ptr", "out"], ["binary", "ptr", "out"]], ["custom_decoder"]],
        ["glGetFragDataLocation", "i32", [["program", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glGetInteger64v", "void", [["pname", "u32"], ["data", "ptr", "out"]]],
        ["glGetIntegeri_v", "void", [["target", "u32"], ["index", "u32"], ["data", "ptr", "out"]]],
        ["glGetInteger64i_v", "void", [["target", "u32"], ["index", "u32"], ["data", "ptr", "out"]]],
        ["glTexImage3D", "void", [["target", "u32"], ["level", "i32"], ["internalFormat", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTexImage3DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["internalFormat", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["format", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glTexStorage3D", "void", [["target", "u32"], ["levels", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"]]],
        ["glTexSubImage3D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["type", "u32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glTexSubImage3DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glCompressedTexImage3D", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCompressedTexImage3DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["border", "i32"], ["imageSize", "i32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glCompressedTexSubImage3D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["imageSize", "i32"], ["data", "ptr", "in", ["nullAllowed","isLarge"]]]],
        ["glCompressedTexSubImage3DOffsetAEMU", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["width", "i32"], ["height", "i32"], ["depth", "i32"], ["format", "u32"], ["imageSize", "i32"], ["data", "u32"]], ["custom_decoder","not_api"]],
        ["glCopyTexSubImage3D", "void", [["target", "u32"], ["level", "i32"], ["xoffset", "i32"], ["yoffset", "i32"], ["zoffset", "i32"], ["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"]]],
        ["glGetStringi", "u32", [["name", "u32"], ["index", "u32"]], ["unsupported"]],
        ["glGetBooleani_v", "void", [["target", "u32"], ["index", "u32"], ["data", "ptr", "out"]]],
        ["glMemoryBarrier", "void", [["barriers", "u32"]]],
        ["glMemoryBarrierByRegion", "void", [["barriers", "u32"]]],
        ["glGenProgramPipelines", "void", [["n", "i32"], ["pipelines", "ptr", "out"]], ["custom_decoder"]],
        ["glDeleteProgramPipelines", "void", [["n", "i32"], ["pipelines", "ptr", "in"]], ["custom_decoder"]],
        ["glBindProgramPipeline", "void", [["pipeline", "u32"]]],
        ["glGetProgramPipelineiv", "void", [["pipeline", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetProgramPipelineInfoLog", "void", [["pipeline", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["infoLog", "ptr", "out"]]],
        ["glValidateProgramPipeline", "void", [["pipeline", "u32"]]],
        ["glIsProgramPipeline", "u8", [["pipeline", "u32"]]],
        ["glUseProgramStages", "void", [["pipeline", "u32"], ["stages", "u32"], ["program", "u32"]], ["custom_decoder"]],
        ["glActiveShaderProgram", "void", [["pipeline", "u32"], ["program", "u32"]], ["custom_decoder"]],
        ["glCreateShaderProgramv", "u32", [["type", "u32"], ["count", "i32"], ["strings", "ptr", "in"]], ["unsupported"]],
        ["glCreateShaderProgramvAEMU", "u32", [["type", "u32"], ["count", "i32"], ["packedStrings", "ptr", "in"], ["packedLen", "u32"]], ["custom_decoder","not_api"]],
        ["glProgramUniform1f", "void", [["program", "u32"], ["location", "i32"], ["v0", "f32"]], ["custom_decoder"]],
        ["glProgramUniform2f", "void", [["program", "u32"], ["location", "i32"], ["v0", "f32"], ["v1", "f32"]], ["custom_decoder"]],
        ["glProgramUniform3f", "void", [["program", "u32"], ["location", "i32"], ["v0", "f32"], ["v1", "f32"], ["v2", "f32"]], ["custom_decoder"]],
        ["glProgramUniform4f", "void", [["program", "u32"], ["location", "i32"], ["v0", "f32"], ["v1", "f32"], ["v2", "f32"], ["v3", "f32"]], ["custom_decoder"]],
        ["glProgramUniform1i", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"]], ["custom_decoder"]],
        ["glProgramUniform2i", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "i32"]], ["custom_decoder"]],
        ["glProgramUniform3i", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "i32"], ["v2", "i32"]], ["custom_decoder"]],
        ["glProgramUniform4i", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "i32"], ["v2", "i32"], ["v3", "i32"]], ["custom_decoder"]],
        ["glProgramUniform1ui", "void", [["program", "u32"], ["location", "i32"], ["v0", "u32"]], ["custom_decoder"]],
        ["glProgramUniform2ui", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "u32"]], ["custom_decoder"]],
        ["glProgramUniform3ui", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "i32"], ["v2", "u32"]], ["custom_decoder"]],
        ["glProgramUniform4ui", "void", [["program", "u32"], ["location", "i32"], ["v0", "i32"], ["v1", "i32"], ["v2", "i32"], ["v3", "u32"]], ["custom_decoder"]],
        ["glProgramUniform1fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform2fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform3fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform4fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform1iv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform2iv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform3iv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform4iv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform1uiv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform2uiv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform3uiv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniform4uiv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix2fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix3fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix4fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix2x3fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix3x2fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix2x4fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix4x2fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix3x4fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glProgramUniformMatrix4x3fv", "void", [["program", "u32"], ["location", "i32"], ["count", "i32"], ["transpose", "u8"], ["value", "ptr", "in"]], ["custom_decoder"]],
        ["glGetProgramInterfaceiv", "void", [["program", "u32"], ["programInterface", "u32"], ["pname", "u32"], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetProgramResourceiv", "void", [["program", "u32"], ["programInterface", "u32"], ["index", "u32"], ["propCount", "i32"], ["props", "ptr", "in"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["params", "ptr", "out"]], ["custom_decoder"]],
        ["glGetProgramResourceIndex", "u32", [["program", "u32"], ["programInterface", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glGetProgramResourceLocation", "i32", [["program", "u32"], ["programInterface", "u32"], ["name", "ptr", "in"]], ["custom_decoder"]],
        ["glGetProgramResourceName", "void", [["program", "u32"], ["programInterface", "u32"], ["index", "u32"], ["bufSize", "i32"], ["length", "ptr", "out", ["nullAllowed"]], ["name", "ptr", "out"]], ["custom_decoder"]],
        ["glBindImageTexture", "void", [["unit", "u32"], ["texture", "u32"], ["level", "i32"], ["layered", "u8"], ["layer", "i32"], ["access", "u32"], ["format", "u32"]]],
        ["glDispatchCompute", "void", [["num_groups_x", "u32"], ["num_groups_y", "u32"], ["num_groups_z", "u32"]]],
        ["glDispatchComputeIndirect", "void", [["indirect", "i32"]]],
        ["glBindVertexBuffer", "void", [["bindingindex", "u32"], ["buffer", "u32"], ["offset", "i32"], ["stride", "i32"]]],
        ["glVertexAttribBinding", "void", [["attribindex", "u32"], ["bindingindex", "u32"]]],
        ["glVertexAttribFormat", "void", [["attribindex", "u32"], ["size", "i32"], ["type", "u32"], ["normalized", "u8"], ["relativeoffset", "u32"]]],
        ["glVertexAttribIFormat", "void", [["attribindex", "u32"], ["size", "i32"], ["type", "u32"], ["relativeoffset", "u32"]]],
        ["glVertexBindingDivisor", "void", [["bindingindex", "u32"], ["divisor", "u32"]]],
        ["glDrawArraysIndirect", "void", [["mode", "u32"], ["indirect", "ptr", "in"]], ["unsupported"]],
        ["glDrawArraysIndirectDataAEMU", "void", [["mode", "u32"], ["indirect", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawArraysIndirectOffsetAEMU", "void", [["mode", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsIndirect", "void", [["mode", "u32"], ["type", "u32"], ["indirect", "ptr", "in"]], ["unsupported"]],
        ["glDrawElementsIndirectDataAEMU", "void", [["mode", "u32"], ["type", "u32"], ["indirect", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsIndirectOffsetAEMU", "void", [["mode", "u32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glTexStorage2DMultisample", "void", [["target", "u32"], ["samples", "i32"], ["internalformat", "u32"], ["width", "i32"], ["height", "i32"], ["fixedsamplelocations", "u8"]]],
        ["glSampleMaski", "void", [["maskNumber", "u32"], ["mask", "u32"]]],
        ["glGetMultisamplefv", "void", [["pname", "u32"], ["index", "u32"], ["val", "ptr", "out"]]],
        ["glFramebufferParameteri", "void", [["target", "u32"], ["pname", "u32"], ["param", "i32"]]],
        ["glGetFramebufferParameteriv", "void", [["target", "u32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexLevelParameterfv", "void", [["target", "u32"], ["level", "i32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glGetTexLevelParameteriv", "void", [["target", "u32"], ["level", "i32"], ["pname", "u32"], ["params", "ptr", "out"]]],
        ["glMapBufferRangeDMA", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["paddr", "u64"]], ["custom_decoder","not_api"]],
        ["glUnmapBufferDMA", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["paddr", "u64"], ["out_res", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glMapBufferRangeDirect", "u64", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["paddr", "u64"]], ["custom_decoder","not_api"]],
        ["glUnmapBufferDirect", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["paddr", "u64"], ["guest_ptr", "u64"], ["out_res", "ptr", "out"]], ["custom_decoder","not_api"]],
        ["glFlushMappedBufferRangeDirect", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"]], ["custom_decoder","not_api"]],
        ["glGetGraphicsResetStatusEXT", "u32", []],
        ["glReadnPixelsEXT", "void", [["x", "i32"], ["y", "i32"], ["width", "i32"], ["height", "i32"], ["format", "u32"], ["type", "u32"], ["bufSize", "i32"], ["data", "ptr", "out"]]],
        ["glGetnUniformfvEXT", "void", [["program", "u32"], ["location", "i32"], ["bufSize", "i32"], ["params", "ptr", "out"]]],
        ["glGetnUniformivEXT", "void", [["program", "u32"], ["location", "i32"], ["bufSize", "i32"], ["params", "ptr", "out"]]],
        ["glDrawArraysNullAEMU", "void", [["mode", "u32"], ["first", "i32"], ["count", "i32"]]],
        ["glDrawElementsNullAEMU", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["indices", "ptr", "in"]], ["unsupported"]],
        ["glDrawElementsOffsetNullAEMU", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["offset", "u32"]], ["custom_decoder","not_api"]],
        ["glDrawElementsDataNullAEMU", "void", [["mode", "u32"], ["count", "i32"], ["type", "u32"], ["data", "ptr", "in"], ["datalen", "u32"]], ["custom_decoder","not_api"]],
        ["glUnmapBufferAsyncAEMU", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["guest_buffer", "ptr", "in", ["nullAllowed","isLarge"]], ["out_res", "ptr", "in"]], ["custom_decoder","not_api"]],
        ["glFlushMappedBufferRangeAEMU2", "void", [["target", "u32"], ["offset", "i32"], ["length", "i32"], ["access", "u32"], ["guest_buffer", "ptr", "in", ["nullAllowed","isLarge"]]], ["custom_decoder","not_api"]],
        ["glBufferDataSyncAEMU", "u8", [["target", "u32"], ["size", "i32"], ["data", "ptr", "in", ["nullAllowed"]], ["usage", "u32"]], ["not_api","custom_decoder"]],
        ["glTexBufferOES", "void", [["target", "u32"], ["internalFormat", "u32"], ["buffer", "u32"]], ["custom_decoder"]],
        ["glTexBufferRangeOES", "void", [["target", "u32"], ["internalFormat", "u32"], ["buffer", "u32"], ["offset", "i32"], ["size", "i32"]], ["custom_decoder"]],
        ["glTexBufferEXT", "void", [["target", "u32"], ["internalFormat", "u32"], ["buffer", "u32"]], ["custom_decoder"]],
        ["glTexBufferRangeEXT", "void", [["target", "u32"], ["internalFormat", "u32"], ["buffer", "u32"], ["offset", "i32"], ["size", "i32"]], ["custom_decoder"]],
        ["glEnableiEXT", "void", [["cap", "u32"], ["index", "u32"]], ["custom_decoder"]],
        ["glDisableiEXT", "void", [["cap", "u32"], ["index", "u32"]], ["custom_decoder"]],
        ["glBlendEquationiEXT", "void", [["index", "u32"], ["mode", "u32"]], ["custom_decoder"]],
        ["glBlendEquationSeparateiEXT", "void", [["index", "u32"], ["modeRGB", "u32"], ["modeAlpha", "u32"]], ["custom_decoder"]],
        ["glBlendFunciEXT", "void", [["index", "u32"], ["sfactor", "u32"], ["dfactor", "u32"]], ["custom_decoder"]],
        ["glBlendFuncSeparateiEXT", "void", [["index", "u32"], ["srcRGB", "u32"], ["dstRGB", "u32"], ["srcAlpha", "u32"], ["dstAlpha", "u32"]], ["custom_decoder"]],
        ["glColorMaskiEXT", "void", [["index", "u32"], ["red", "u8"], ["green", "u8"], ["blue", "u8"], ["alpha", "u8"]], ["custom_decoder"]],
        ["glIsEnablediEXT", "u8", [["cap", "u32"], ["index", "u32"]], ["custom_decoder"]],
    ] },
};
                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/gles/gles_shadow.js                                                                  0000644 0000000 0000000 00000244020 00000000000 014244  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The shadow state (docs/gles-proxy-plan.md "影子状态", E2): OpenGL ES 2.0's
// state machine, written from the GLES 2.0 specification, on the CPU side,
// so that the guest's queries are answered without waiting for the page:
// glGetError and the errors' rules, glGet* and glIsEnabled, the objects'
// names and parameters (textures, buffers, renderbuffers, framebuffers and
// their completeness, shaders and programs: compiled and linked by GLSL
// ES's front end, src/gles/glsl_es.js), uniforms' values and locations, the
// attributes' state.
//
// call() runs one command: its answer, and whether it goes to the page (a
// call the rules refuse sets the error and changes nothing; a query changes
// nothing either). The page's executor (E3) runs the same state machine on
// the commands it receives, so both sides agree on every name, location and
// binding.
//
// Objects: textures, buffers, renderbuffers, shaders and programs belong
// to the share group; framebuffers to the context (ES 3.0's rule, which no
// ES 2.0 guest relies against). GLES 1.1 contexts share the objects' part;
// their fixed-function state is answered from its initial values until E4.

import { GL, CAPS_1, CAPS_2, RENDERBUFFER_FORMATS, etc1_bytes, image_bytes, texel_bytes, texture_format_error, texture_kind } from "./gles_formats.js";
import { CONFIG_ATTRIBUTES, COMPRESSED_TEXTURE_FORMATS, EGL, GL_STATE, MAX_SIZE } from "./gles_caps.js";
import { compile_shader, link_program } from "./glsl_es.js";
import { STAGE_OF_GL_TYPE } from "./glslang.js";
import { es3_rules, glsl_version } from "./glsl_es_rewrite.js";
import { link_glslang_program } from "./glsl_program.js";
import { ADVANCED_EQUATIONS, INT64_STATE, extend_context3, extend_group3, gles3_handlers, new_framebuffer3, pad_context3, state_value3 } from "./gles3_state.js";
import { FLOAT_STATE32, extend_context31, gles31_handlers, glslang_limits, pad_context31, state_value31 } from "./gles31_state.js";
import { EXTENSIONS_3 } from "./gles_caps.js";
import { CLIENT_ARRAYS, gles1_handlers, gles1_state_value, new_ff_state } from "./gles1_state.js";
import { format_info as SIZED_INFO } from "./gles_formats3.js";
import { relink } from "./gles_snapshot.js";

const MAX_ATTRIBS = 16;
const MAX_UNITS = 32;
const MAX_VIEWPORT = MAX_SIZE;
/** log2 of MAX_SIZE: the levels a texture can have */
const MAX_LEVEL = Math.log2(MAX_SIZE);

const BLEND_EQUATIONS = new Set([0x8006, 0x800A, 0x800B]);
/** GLES 3.0's MIN and MAX; GLES 3.2's advanced equations (KHR_blend_equation_advanced: glBlendEquation's, not the separate one's) */
const BLEND_MINMAX = new Set([0x8007, 0x8008]);
const equation_ok = (c, mode, advanced) => BLEND_EQUATIONS.has(mode) || c.version >= 30 && BLEND_MINMAX.has(mode) ||
    advanced && c.version >= 32 && ADVANCED_EQUATIONS.includes(mode);
const BLEND_FACTORS = new Set([0, 1, 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, 0x8001, 0x8002, 0x8003, 0x8004]);
const SRC_ALPHA_SATURATE = 0x0308;
/** @return {boolean} whether a blend factor is a source's (SRC_ALPHA_SATURATE too) */
const source_factor = f => BLEND_FACTORS.has(f) || f === SRC_ALPHA_SATURATE;
/** @return {boolean} whether a blend factor is a destination's: SRC_ALPHA_SATURATE too from GLES 3.0 on (GLES 2.0: sources' alone) */
const destination_factor = (c, f) => BLEND_FACTORS.has(f) || f === SRC_ALPHA_SATURATE && c.version >= 30;
const COMPARE_FUNCS = new Set([0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207]);
const STENCIL_OPS = new Set([0, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508]);
const FACES = new Set([0x0404, 0x0405, 0x0408]);
const FRONT = 0x0404, BACK = 0x0405;
const HINT_MODES = new Set([0x1100, 0x1101, 0x1102]);
const MODES = new Set([GL.POINTS, GL.LINES, GL.LINE_LOOP, GL.LINE_STRIP, GL.TRIANGLES, GL.TRIANGLE_STRIP, GL.TRIANGLE_FAN]);
const INDEX_TYPES = new Set([GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT, GL.UNSIGNED_INT]);
const ATTRIB_TYPES = new Set([GL.BYTE, GL.UNSIGNED_BYTE, GL.SHORT, GL.UNSIGNED_SHORT, GL.FLOAT, GL.FIXED, GL.HALF_FLOAT_OES]);
const CLEAR_BITS = 0x4000 | 0x0100 | 0x0400;
const USAGES = new Set([GL.STREAM_DRAW, GL.STATIC_DRAW, GL.DYNAMIC_DRAW]);
const MIN_FILTERS = new Set([GL.NEAREST, GL.LINEAR, GL.NEAREST_MIPMAP_NEAREST, GL.LINEAR_MIPMAP_NEAREST, GL.NEAREST_MIPMAP_LINEAR, GL.LINEAR_MIPMAP_LINEAR]);
const WRAPS = new Set([GL.REPEAT, GL.CLAMP_TO_EDGE, GL.MIRRORED_REPEAT]);
const ATTACHMENTS = [GL.COLOR_ATTACHMENT0, GL.DEPTH_ATTACHMENT, GL.STENCIL_ATTACHMENT];

/** A call's outcome when the rules refuse it */
const REFUSED = Symbol("refused");

/** The share group's objects and names */
function ShareGroup()
{
    /** @type {!Map<number, !Object>} */
    this.textures = new Map();
    /** @type {!Map<number, {size: number, usage: number}>} */
    this.buffers = new Map();
    /** @type {!Map<number, {width: number, height: number, format: number, image: number}>} */
    this.renderbuffers = new Map();
    /** @type {!Map<number, !Object>} shaders and programs: one name space */
    this.objects = new Map();
    /** names given out by glGen*, by kind (they are objects only once bound) */
    this.reserved = { texture: new Set(), buffer: new Set(), renderbuffer: new Set() };
    this.next = { texture: 1, buffer: 1, renderbuffer: 1, object: 1 };
    this.contexts = 0;
}

/** @param {string} kind @param {!Map} objects @return {number} a name nothing has */
ShareGroup.prototype.fresh = function(kind, objects)
{
    const reserved = this.reserved[kind];
    let name = this.next[kind];
    while(objects.has(name) || reserved && reserved.has(name)) name++;
    this.next[kind] = name + 1;
    return name;
};

/** A texture: its target, images (by face and level), parameters */
function new_texture(target)
{
    const external = target === GL.TEXTURE_EXTERNAL_OES;
    return {
        target, images: new Map(), min_filter: external ? GL.LINEAR : GL.NEAREST_MIPMAP_LINEAR, mag_filter: GL.LINEAR,
        wrap_s: external ? GL.CLAMP_TO_EDGE : GL.REPEAT, wrap_t: external ? GL.CLAMP_TO_EDGE : GL.REPEAT,
        generate_mipmap: 0, crop: [0, 0, 0, 0],
    };
}

/** A vertex attribute's state */
function new_attrib()
{
    return { enabled: false, size: 4, type: GL.FLOAT, normalized: false, stride: 0, buffer: 0, offset: 0, current: [0, 0, 0, 1] };
}

/**
 * One context's state (GLES 2.0 tables 6.2 to 6.17; GLES 3.x's in gles3_state.js)
 * @param {number} api renderControl's: 1 (GLES 1.1), 2 (2.0), 30 to 32 (3.0 to 3.2)
 */
function Context(api, group)
{
    /** 1, 2, or 3 for any GLES 3.x; `version` says which (11, 20, 30, 31, 32) */
    this.api = api >= 30 ? 3 : api === 20 ? 2 : api;
    this.version = api >= 30 ? api : api === 1 ? 11 : 20;
    /**
     * GLSL ES 1.00 through glslang, the program drawn on the page as GLES
     * 3.x's (api 20: a GLES 2.0 context of a host that has glslang;
     * docs/gles3-plan.md L3); a GLES 2.0 context of api 2 has gl-webgpu's
     * front end
     */
    this.glslang = api === 20 || api >= 30;
    this.group = group;
    this.error = GL.NO_ERROR;
    /** @type {?{width: number, height: number, config: !Array<number>}} */
    this.surface = null;
    this.made_current = false;
    /** @type {!Map<number, {attachments: !Map<number, {type: number, name: number, level: number, face: number}>}>} */
    this.framebuffers = new Map();
    this.reserved_framebuffers = new Set();
    this.next_framebuffer = 1;
    this.enabled = new Set([0x0BD0, ...(api === 1 ? [0x809D] : [])]);
    this.viewport = [0, 0, 0, 0];
    this.scissor = [0, 0, 0, 0];
    this.depth_range = [0, 1];
    this.line_width = 1;
    this.cull_face = BACK;
    this.front_face = 0x0901;
    this.polygon_offset = [0, 0];
    this.sample_coverage = [1, 0];
    this.clear_color = [0, 0, 0, 0];
    this.clear_depth = 1;
    this.clear_stencil = 0;
    this.color_mask = [1, 1, 1, 1];
    this.depth_mask = 1;
    this.stencil_writemask = [-1, -1];
    this.blend_func = [1, 0, 1, 0]; // src rgb, dst rgb, src alpha, dst alpha
    this.blend_equation = [0x8006, 0x8006];
    this.blend_color = [0, 0, 0, 0];
    this.depth_func = 0x0201;
    this.stencil_func = [[0x0207, 0, -1], [0x0207, 0, -1]]; // front, back: func, ref, mask
    this.stencil_op = [[0x1E00, 0x1E00, 0x1E00], [0x1E00, 0x1E00, 0x1E00]];
    this.unpack_alignment = 4;
    this.pack_alignment = 4;
    this.hints = new Map([[0x8192, 0x1100], [0x8B8B, 0x1100], [0x0C50, 0x1100], [0x0C51, 0x1100], [0x0C52, 0x1100], [0x0C54, 0x1100]]);
    this.active_texture = 0;
    /** texture bindings by unit: [2D, cube map, external] */
    this.textures = Array.from({ length: MAX_UNITS }, () => [0, 0, 0]);
    this.array_buffer = 0;
    this.element_array_buffer = 0;
    this.framebuffer = 0;
    this.renderbuffer = 0;
    this.program = 0;
    this.attribs = Array.from({ length: MAX_ATTRIBS }, new_attrib);
    /** GLES 1.1's fixed-function state (src/gles/gles1_state.js) */
    this.ff = api === 1 ? new_ff_state() : null;
    if(this.api === 3)
    {
        extend_group3(group);
        extend_context3(this);
        if(this.version >= 31) extend_context31(this);
    }
}

/**
 * A linked program's uniform values before any glUniform*: a sampler's or
 * image's layout(binding), its unit (an array's elements the units after
 * it); the others 0
 * @param {?Object} info the link's
 * @return {!Map<number, !Array<number>>}
 */
function initial_values(info)
{
    const values = new Map();
    if(!info || !info.ok) return values;
    for(const u of info.uniforms)
    {
        if(u.opaque !== "sampler" && u.opaque !== "image" || !(u.binding > 0) || u.location < 0) continue;
        for(let e = 0; e < u.size; e++) values.set(u.location + e, [u.binding + e]);
    }
    return values;
}

/** @param {number} target @return {number} the binding slot of a texture target, -1 for none */
function texture_slot(target)
{
    return target === GL.TEXTURE_2D ? 0 : target === GL.TEXTURE_CUBE_MAP ? 1 : target === GL.TEXTURE_EXTERNAL_OES ? 2 : -1;
}

/** @param {number} target TexImage2D's: 2D or a cube map face @return {number} the face (0 for 2D), -1 for none */
function face_of(target)
{
    if(target === GL.TEXTURE_2D) return 0;
    const face = target - GL.TEXTURE_CUBE_MAP_POSITIVE_X;
    return face >= 0 && face < 6 ? face : -1;
}

/** @param {?Uint8Array} bytes @return {!Array<number>} as i32 */
function i32s(bytes)
{
    if(!bytes) return [];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const values = [];
    for(let at = 0; at + 4 <= bytes.length; at += 4) values.push(view.getInt32(at, true));
    return values;
}

/** @param {?Uint8Array} bytes @return {!Array<number>} as f32 */
function f32s(bytes)
{
    if(!bytes) return [];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const values = [];
    for(let at = 0; at + 4 <= bytes.length; at += 4) values.push(view.getFloat32(at, true));
    return values;
}

/** @param {?Uint8Array} bytes @return {string} a C string's text */
function text_of(bytes)
{
    if(!bytes) return "";
    const end = bytes.indexOf(0);
    return new TextDecoder().decode(end < 0 ? bytes : bytes.subarray(0, end));
}

/**
 * Values into an out buffer, as many as fit, by glGet's conversions
 * (GLES 2.0, 6.1.2)
 * @param {!Object} out an OutBuffer
 * @param {!Array<number>} values
 * @param {string} as "b" boolean, "i" integer, "f" float, "x" 16.16 fixed
 * @param {string} kind the state's own: "b", "i", "f", or "n" (a color or depth, normalized)
 */
function put(out, values, as, kind)
{
    const size = as === "b" ? 1 : 4;
    for(let i = 0; i < values.length && (i + 1) * size <= out.size; i++)
    {
        const v = values[i];
        switch(as)
        {
            case "b": out.data[i] = v ? 1 : 0; break;
            case "f": out.view.setFloat32(4 * i, kind === "b" ? (v ? 1 : 0) : v, true); break;
            case "x": out.view.setInt32(4 * i, Math.round(v * 65536), true); break;
            default:
                if(kind === "n") out.view.setInt32(4 * i, Math.round(Math.max(-1, Math.min(1, v)) * 0x7FFFFFFF), true);
                else out.view.setInt32(4 * i, kind === "f" ? Math.round(v) : v | 0, true);
        }
    }
}

/** @param {!Object} out an OutBuffer @param {string} text written with its NUL, truncated to fit @return {number} the length written */
function put_text(out, text)
{
    if(!out.size) return 0;
    const bytes = new TextEncoder().encode(text).subarray(0, out.size - 1);
    out.data.set(bytes);
    out.data[bytes.length] = 0;
    return bytes.length;
}

/** The state glGet answers that is a float, a color or depth (normalized) or a boolean; the rest are integers */
const STATE_KIND = new Map([
    [0x0B70, "n"], [0x0B21, "f"], [0x8038, "f"], [0x2A00, "f"], [0x80AA, "f"], [0x0C22, "n"], [0x0B73, "n"], [0x8005, "n"],
    [0x846D, "f"], [0x846E, "f"], [0x0B12, "f"], [0x0B22, "f"],
    [0x0C23, "b"], [0x0B72, "b"], [0x80AB, "b"], [0x8DFA, "b"],
    // (GLES 3.2's: gles31_state.js's FLOAT_STATE32)
    ...[...FLOAT_STATE32].map(pname => [pname, "f"]),
]);

/**
 * @constructor
 * @param {?Object} rc the RenderControl (src/gles/render_control.js): EGL
 *     images and color buffers, which textures and renderbuffers take as images
 */
export function GLESShadow(rc)
{
    this.rc = rc;
    /** @type {!Map<number, !Context>} by renderControl's context handle */
    this.contexts = new Map();
    /** @type {!Map<number, !ShareGroup>} by the group's first context */
    this.groups = new Map();
    /** whether the call being run goes to the page */
    this.keep = true;
    /** the name glCreateShader or glCreateProgram gives (the page's: the CPU side's answer), 0: a fresh one */
    this.given_name = 0;
    /** the commands both versions share (GLES 1.1's fixed forms call them) */
    this.handlers = HANDLERS;
    /** shaders compiled and programs linked; the logs of the first failures */
    this.stats = { compiled: 0, compile_failed: 0, linked: 0, link_failed: 0, failures: [], compile_ms: 0 };
    /** @type {?Object} glslang (src/gles/glslang.js), on the CPU side: GLSL ES 3.x's shaders, and 1.00's in
     *  contexts of glslang's (Context's `glslang`); the page has none and takes links from the batch */
    this.glslang = null;
    /** the last glLinkProgram's result through glslang (gles_host.js sends it to the page) */
    this.last_link = null;
}

/** What glslang's code pass needs of the limits */
const GLSLANG_LIMITS = { maxVaryingVectors: 15, maxDrawBuffers: 4 };

/** @param {number} type a shader's GL type @return {string} its stage, glsl_program.js's name */
function stage_of(type)
{
    return ["vertex", "tess_control", "tess_evaluation", "geometry", "fragment", "compute"][STAGE_OF_GL_TYPE.get(type)];
}

/**
 * A shader compiled: GLSL ES 3.x (and 1.00 where `es100`: a context of
 * glslang's) by glslang's check pass, else gl-webgpu's front end; on the
 * page, such a shader is not compiled at all: its program's link comes with
 * the batch
 * @param {boolean=} es100 GLSL ES 1.00 through glslang too
 * @param {boolean=} es2 a GLES 2.0 context's (GLES 2.0's limits)
 * @return {!Object} {ok, log, ...}
 */
GLESShadow.prototype.compile = function(source, type, es100, es2)
{
    const version = glsl_version(source);
    const stage = stage_of(type);
    if(version >= 300 || es100)
    {
        if(!this.glslang) return { ok: true, log: "", glslang: true, stage };
        this.glslang.set_limits(glslang_limits(version, es2));
        const checked = this.glslang.check_shader(STAGE_OF_GL_TYPE.get(type), source);
        // (what GLSL ES refuses and glslang's relaxed check does not: an #extension after the code, reserved words)
        const refused = checked.ok ? es3_rules(source) : null;
        if(refused) return { ok: false, log: refused, glslang: true, stage };
        return { ok: checked.ok, log: checked.log, glslang: true, stage };
    }
    return compile_shader(source, stage);
};

/**
 * A program's shaders linked
 * @param {!Object} program
 * @param {!Array<!Object>} shaders the attached ones
 * @param {boolean=} es2 a GLES 2.0 context's (GLES 2.0's limits)
 * @return {!Object} ProgramInfo
 */
GLESShadow.prototype.link = function(program, shaders, es2)
{
    this.last_link = null;
    if(!shaders.some(s => s.compiled && s.compiled.glslang))
    {
        const shader = type => shaders.find(s => s.type === type);
        const vs = shader(GL.VERTEX_SHADER), fs = shader(GL.FRAGMENT_SHADER);
        return link_program(vs && vs.compiled, fs && fs.compiled, new Map(program.bindings));
    }
    const failed = log => ({ ok: false, log, attributes: [], uniforms: [], locations: new Map(), by_location: [], reflection: null });
    if(program.provided)
    {
        const info = program.provided;
        program.provided = null;
        return info;
    }
    if(!this.glslang) return failed("ERROR: no link of this program came with the batch");
    if(shaders.some(s => !s.compiled || !s.compiled.glslang)) return failed("ERROR: the shaders' versions differ");
    if(shaders.some(s => !s.compiled.ok)) return failed("ERROR: a shader is not compiled");
    this.glslang.set_limits(glslang_limits(glsl_version(shaders[0].compiled_source), es2));
    const info = link_glslang_program(this.glslang, shaders.map(s => ({ stage: s.compiled.stage, source: s.compiled_source })),
        { bindings: new Map(program.bindings), separable: !!program.separable, limits: GLSLANG_LIMITS, tf: program.tf_request || null });
    if(info.ok) this.last_link = info;
    return info;
};

/** The classes of the shadow's objects, for a snapshot's packing (gles_snapshot.js) */
export const SHADOW_CLASSES = { "ShareGroup": ShareGroup.prototype, "Context": Context.prototype };

/** What a snapshot keeps (packed with SHADOW_CLASSES and shadow_skip, gles_snapshot.js) */
GLESShadow.prototype.get_state = function()
{
    return { contexts: this.contexts, groups: this.groups, stats: this.stats };
};

/** @param {{contexts: !Map, groups: !Map, stats: !Object}} state get_state's, unpacked */
GLESShadow.prototype.set_state = function(state)
{
    this.contexts = state.contexts;
    this.groups = state.groups;
    this.stats = state.stats;
    for(const c of this.contexts.values())
    {
        if(c && c.version >= 30 && c.textures && c.uniform_bindings) pad_context3(c);
        if(c && c.version >= 31 && c.storage_bindings && c.atomic_bindings) pad_context31(c);
    }
    relink(this.groups, this);
};

/**
 * @param {number} handle
 * @param {number} api 1 (GLES 1.1), 2, or 30 to 32 (GLES 3.0 to 3.2)
 * @param {number} share the group's first context, or 0
 */
GLESShadow.prototype.create_context = function(handle, api, share)
{
    const group_id = share || handle;
    let group = this.groups.get(group_id);
    if(!group) this.groups.set(group_id, group = new ShareGroup());
    group.contexts++;
    const context = new Context(api, group);
    context.group_id = group_id;
    // (the group's shaders compile as its contexts' do: a snapshot's relink)
    if(context.glslang) group.glslang = true;
    if(context.glslang && context.api === 2) group.es2 = true;
    this.contexts.set(handle, context);
};

/** @param {number} handle */
GLESShadow.prototype.destroy_context = function(handle)
{
    const context = this.contexts.get(handle);
    if(!context) return;
    this.contexts.delete(handle);
    if(--context.group.contexts === 0) this.groups.delete(context.group_id);
};

/**
 * A context made current on a surface (EGL: the first time, its viewport
 * and scissor box become the surface's)
 * @param {number} handle
 * @param {?{width: number, height: number, config: !Array<number>}} surface
 */
GLESShadow.prototype.make_current = function(handle, surface)
{
    const context = this.contexts.get(handle);
    if(!context) return;
    context.surface = surface;
    if(!context.made_current && surface)
    {
        context.viewport = [0, 0, surface.width, surface.height];
        context.scissor = [0, 0, surface.width, surface.height];
    }
    context.made_current = context.made_current || !!surface;
};

/** @param {number} handle @return {?Context} */
GLESShadow.prototype.context = function(handle)
{
    return this.contexts.get(handle) || null;
};

/**
 * One GLES call in a context
 * @param {number} handle the connection's current context (0: none: the call does nothing)
 * @param {!Object} command (gles_wire.js)
 * @param {!Array<*>} args
 * @return {{ret: *, keep: boolean}} the answer, and whether the page needs the call
 */
GLESShadow.prototype.call = function(handle, command, args)
{
    const context = this.contexts.get(handle);
    if(!context) return { ret: 0, keep: false };
    const name = command.name, base = name.replace(/OES$/, "");
    const handler = context.api === 1 && (GLES1_HANDLERS[name] || GLES1_HANDLERS[base]) ||
        context.version >= 31 && (GLES31_HANDLERS[name] || GLES31_HANDLERS[base]) ||
        context.api === 3 && (GLES3_HANDLERS[name] || GLES3_HANDLERS[base]) || HANDLERS[name] || HANDLERS[base];
    this.keep = true;
    if(!handler)
    {
        // (a call nothing here follows: GLES 1.1's fixed function until E4)
        return { ret: 0, keep: true };
    }
    const ret = handler(this, context, args);
    if(ret === REFUSED) return { ret: 0, keep: false };
    return { ret, keep: this.keep };
};

/** Record an error (the first stays until glGetError) @return {symbol} REFUSED */
function fail(context, error)
{
    if(context.error === GL.NO_ERROR) context.error = error;
    return REFUSED;
}

/** @param {!GLESShadow} shadow the call is a query: nothing for the page */
function query(shadow)
{
    shadow.keep = false;
}

// ---- framebuffers

/**
 * An attachment's image: its size and kind, or null for none or one with no image
 * @return {?{width: number, height: number, kind: !Object}}
 */
GLESShadow.prototype.attachment_image = function(context, a)
{
    if(a.type === GL.RENDERBUFFER)
    {
        const rb = context.group.renderbuffers.get(a.name);
        if(!rb || !rb.width || !rb.height) return null;
        return { width: rb.width, height: rb.height, kind: RENDERBUFFER_FORMATS.get(rb.format) || texture_kind(GL.RGBA, GL.UNSIGNED_BYTE) };
    }
    const texture = context.group.textures.get(a.name);
    const image = texture && texture.images.get(a.face * 32 + a.level);
    if(!image || !image.width || !image.height) return null;
    return { width: image.width, height: image.height, kind: texture_kind(image.format, image.type) };
};

/**
 * The bound framebuffer's status (GLES 2.0, 4.4.5)
 * @param {!Context} context
 * @return {number}
 */
GLESShadow.prototype.framebuffer_status = function(context)
{
    if(context.api === 3) return FRAMEBUFFER_STATUS3.fn(context, context.framebuffer);
    if(!context.framebuffer) return GL.FRAMEBUFFER_COMPLETE;
    const fbo = context.framebuffers.get(context.framebuffer);
    let size = null, any = false;
    for(const [attachment, a] of fbo.attachments)
    {
        const image = this.attachment_image(context, a);
        if(!image) return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
        const k = image.kind;
        if(attachment === GL.COLOR_ATTACHMENT0 ? !k.color : attachment === GL.DEPTH_ATTACHMENT ? !k.depth : !k.stencil)
        {
            return GL.FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
        }
        if(size && (size[0] !== image.width || size[1] !== image.height)) return GL.FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
        size = [image.width, image.height];
        any = true;
    }
    if(!any) return GL.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
    // (depth and stencil apart are WebGPU's one depth-stencil texture: only
    // as the same packed renderbuffer)
    const depth = fbo.attachments.get(GL.DEPTH_ATTACHMENT), stencil = fbo.attachments.get(GL.STENCIL_ATTACHMENT);
    if(depth && stencil && (depth.type !== stencil.type || depth.name !== stencil.name)) return GL.FRAMEBUFFER_UNSUPPORTED;
    return GL.FRAMEBUFFER_COMPLETE;
};

/** The red, green, blue, alpha, depth and stencil bits of what is drawn to */
GLESShadow.prototype.framebuffer_bits = function(context)
{
    if(!context.framebuffer)
    {
        const config = context.surface && context.surface.config;
        const value = attribute => config ? config[CONFIG_ATTRIBUTES.indexOf(attribute)] : 0;
        return [value(EGL.RED_SIZE), value(EGL.GREEN_SIZE), value(EGL.BLUE_SIZE), value(EGL.ALPHA_SIZE), value(EGL.DEPTH_SIZE), value(EGL.STENCIL_SIZE)];
    }
    const fbo = context.framebuffers.get(context.framebuffer);
    const bits = [0, 0, 0, 0, 0, 0];
    for(const [attachment, a] of fbo.attachments)
    {
        const image = this.attachment_image(context, a);
        if(!image) continue;
        const k = image.kind.bits;
        if(attachment === GL.COLOR_ATTACHMENT0) for(let i = 0; i < 4; i++) bits[i] = k[i];
        if(attachment === GL.DEPTH_ATTACHMENT) bits[4] = k[4];
        if(attachment === GL.STENCIL_ATTACHMENT) bits[5] = k[5];
    }
    return bits;
};

/** INVALID_FRAMEBUFFER_OPERATION when what is drawn to is not complete @return {boolean} whether it is */
function framebuffer_ok(shadow, context)
{
    if(shadow.framebuffer_status(context) === GL.FRAMEBUFFER_COMPLETE) return true;
    fail(context, GL.INVALID_FRAMEBUFFER_OPERATION);
    return false;
}

/** An object deleted: what the context had bound or attached of it goes */
function detach(context, type, name)
{
    const fbo = context.framebuffer && context.framebuffers.get(context.framebuffer);
    if(!fbo) return;
    for(const [attachment, a] of fbo.attachments) if(a.type === type && a.name === name) fbo.attachments.delete(attachment);
}

/**
 * A texture or renderbuffer deleted while framebuffers that are not bound
 * have it attached (GL keeps it for them; a new object of its name is
 * another): theirs, under a name of its own past those glGen gives
 * @param {!Map<number, !Object>} objects the group's of its kind
 */
function keep_orphan(context, type, objects, name, object)
{
    let orphan = 0;
    for(const fbo of context.framebuffers.values())
    {
        for(const a of fbo.attachments.values())
        {
            if(a.type !== type || a.name !== name) continue;
            if(!orphan) orphan = context.group.next_orphan = (context.group.next_orphan || 0x40000000) + 1;
            a.name = orphan;
        }
    }
    if(orphan) objects.set(orphan, object);
}

// ---- glGet

/**
 * A pname's value in the context, or null for a pname glGet does not know
 * @return {?Array<number>}
 */
GLESShadow.prototype.state_value = function(context, pname)
{
    const c = context;
    if(c.api === 3)
    {
        const value = c.version >= 31 && state_value31(this, c, pname) || state_value3(this, c, pname);
        if(value) return value;
        if(this.read_error3) { this.read_error3 = false; return null; }
    }
    switch(pname)
    {
        case 0x0BA2: return c.viewport;
        case 0x0C10: return c.scissor;
        case 0x0B70: return c.depth_range;
        case 0x0B21: return [c.line_width];
        case 0x0B45: return [c.cull_face];
        case 0x0B46: return [c.front_face];
        case 0x8038: return [c.polygon_offset[0]];
        case 0x2A00: return [c.polygon_offset[1]];
        case 0x80AA: return [c.sample_coverage[0]];
        case 0x80AB: return [c.sample_coverage[1]];
        case 0x0C22: return c.clear_color;
        case 0x0B73: return [c.clear_depth];
        case 0x0B91: return [c.clear_stencil];
        case 0x0C23: return c.color_mask;
        case 0x0B72: return [c.depth_mask];
        // (the masks are unsigned: a float or 64-bit query of all bits set is 4294967295)
        case 0x0B98: return [c.stencil_writemask[0] >>> 0];
        case 0x8CA5: return [c.stencil_writemask[1] >>> 0];
        case 0x80C9: return [c.blend_func[0]];
        case 0x80C8: return [c.blend_func[1]];
        case 0x80CB: return [c.blend_func[2]];
        case 0x80CA: return [c.blend_func[3]];
        case 0x0BE1: return [c.blend_func[0]]; // GLES 1.1's GL_BLEND_SRC
        case 0x0BE0: return [c.blend_func[1]];
        case 0x8009: return [c.blend_equation[0]];
        case 0x883D: return [c.blend_equation[1]];
        case 0x8005: return c.blend_color;
        case 0x0B74: return [c.depth_func];
        case 0x0B92: return [c.stencil_func[0][0]];
        case 0x0B97: return [c.stencil_func[0][1]];
        case 0x0B93: return [c.stencil_func[0][2] >>> 0];
        case 0x8800: return [c.stencil_func[1][0]];
        case 0x8CA3: return [c.stencil_func[1][1]];
        case 0x8CA4: return [c.stencil_func[1][2] >>> 0];
        case 0x0B94: return [c.stencil_op[0][0]];
        case 0x0B95: return [c.stencil_op[0][1]];
        case 0x0B96: return [c.stencil_op[0][2]];
        case 0x8801: return [c.stencil_op[1][0]];
        case 0x8802: return [c.stencil_op[1][1]];
        case 0x8803: return [c.stencil_op[1][2]];
        case GL.UNPACK_ALIGNMENT: return [c.unpack_alignment];
        case GL.PACK_ALIGNMENT: return [c.pack_alignment];
        case 0x84E0: return [GL.TEXTURE0 + c.active_texture];
        case 0x8069: return [c.textures[c.active_texture][0]];
        case 0x8514: return [c.textures[c.active_texture][1]];
        case 0x8D67: return [c.textures[c.active_texture][2]]; // GL_TEXTURE_BINDING_EXTERNAL_OES
        case 0x8894: return [c.array_buffer];
        case 0x8895: return [c.element_array_buffer];
        case 0x8CA6: return [c.framebuffer];
        case 0x8CA7: return [c.renderbuffer];
        case 0x8B8D: return [c.program];
        case 0x0D52: case 0x0D53: case 0x0D54: case 0x0D55: case 0x0D56: case 0x0D57:
            return [this.framebuffer_bits(c)[pname - 0x0D52]];
        case 0x86A3: return COMPRESSED_TEXTURE_FORMATS;
    }
    if(c.hints.has(pname) && (c.api === 1 || pname === 0x8192 || pname === 0x8B8B)) return [c.hints.get(pname)];
    if((c.api === 1 ? CAPS_1 : CAPS_2).has(pname)) return [c.enabled.has(pname) ? 1 : 0];
    if(GL_STATE.has(pname)) return GL_STATE.get(pname);
    return null;
};

/** glGet{Boolean,Integer,Float,Fixed}v: "b", "i", "f", "x" */
function get(as)
{
    return (shadow, c, [pname, params]) =>
    {
        query(shadow);
        const own = c.api === 1 ? gles1_state_value(c, pname) : null;
        if(own) return put(params, own[0], as, own[1]);
        let value = shadow.state_value(c, pname);
        if(!value) return fail(c, GL.INVALID_ENUM);
        // (GLES 3.0's 64-bit state through a 32-bit glGet: clamped)
        if(INT64_STATE.has(pname) && as !== "f") value = value.map(v => Math.min(v, 0x7FFFFFFF));
        put(params, value, as, STATE_KIND.get(pname) || "i");
        return undefined;
    };
}

// ---- the commands

/** @param {!Context} c @param {number} name @param {string} kind "shader" or "program" @return {?Object} the object, or null with the error set */
function object_of(c, name, kind)
{
    const object = c.group.objects.get(name);
    if(!object) { fail(c, GL.INVALID_VALUE); return null; }
    if(object.kind !== kind) { fail(c, GL.INVALID_OPERATION); return null; }
    return object;
}

/** The texture bound to a target of the active unit, or null with the error set */
function bound_texture(c, target)
{
    const slot = texture_slot(target);
    if(slot < 0) { fail(c, GL.INVALID_ENUM); return null; }
    const name = c.textures[c.active_texture][slot];
    let texture = c.group.textures.get(name);
    if(!texture && !name)
    {
        // (name 0: the context's default texture of the target)
        c.defaults = c.defaults || new Map();
        texture = c.defaults.get(target);
        if(!texture) c.defaults.set(target, texture = new_texture(target));
    }
    return texture || null;
}

/** @return {?Object} the texture a TexImage2D-like call names (2D or a cube face), with its face, or null with the error set */
function image_target(c, target)
{
    const face = face_of(target);
    if(face < 0) { fail(c, GL.INVALID_ENUM); return null; }
    const texture = bound_texture(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
    return texture ? { texture, face } : null;
}

/** TexImage2D's checks of the level and size @return {boolean} */
function image_size_ok(c, target, level, width, height, border)
{
    if(level < 0 || level > MAX_LEVEL || width < 0 || height < 0 || border !== 0 ||
        (width << level) > MAX_SIZE || (height << level) > MAX_SIZE ||
        target !== GL.TEXTURE_2D && width !== height)
    {
        fail(c, GL.INVALID_VALUE);
        return false;
    }
    return true;
}

/** The buffer bound to a target, or null with the error set */
function bound_buffer(c, target)
{
    if(target !== GL.ARRAY_BUFFER && target !== GL.ELEMENT_ARRAY_BUFFER) { fail(c, GL.INVALID_ENUM); return null; }
    const name = target === GL.ARRAY_BUFFER ? c.array_buffer : c.element_array_buffer;
    const buffer = c.group.buffers.get(name);
    if(!buffer) { fail(c, GL.INVALID_OPERATION); return null; }
    return buffer;
}

/** The linked current program's uniform at a location: null for -1 (ignored), REFUSED with the error set */
function uniform_at(c, location, count)
{
    const program = c.group.objects.get(c.program);
    if(!program || !program.info || !program.info.ok) return fail(c, GL.INVALID_OPERATION);
    if(count < 0) return fail(c, GL.INVALID_VALUE);
    if(location === -1) return null;
    const at = program.info.by_location[location];
    if(!at) return fail(c, GL.INVALID_OPERATION);
    // (an array of one active element is still an array: its name ends in [0], the rest of the count is ignored)
    if(count > 1 && at.uniform.size === 1 && at.uniform.name === at.uniform.base) return fail(c, GL.INVALID_OPERATION);
    return { program, at };
}

/**
 * glUniform*: the values into the program's storage, after GLES 2.0's
 * checks (2.10.4): the size and kind of the function against the uniform's
 * @param {number} components 1 to 4, or 4, 9, 16 for the matrices
 * @param {string} kind "f", "i" or "m" (a matrix)
 */
function uniform(components, kind, vector)
{
    return (shadow, c, args) =>
    {
        const location = args[0];
        let count = 1, values;
        if(kind === "m")
        {
            count = args[1];
            if(args[2]) return fail(c, GL.INVALID_VALUE);
            values = f32s(args[3]);
        }
        else if(vector)
        {
            count = args[1];
            values = kind === "f" ? f32s(args[2]) : i32s(args[2]);
        }
        else values = args.slice(1);
        const target = uniform_at(c, location, count);
        if(target === REFUSED || target === null) return target === null ? undefined : target;
        const u = target.at.uniform;
        if(kind === "m" ? !u.columns || u.columns * u.columns !== components : u.columns || u.components !== components ||
            (kind === "f" ? u.int && !u.bool : !u.int && !u.bool) || u.sampler && (kind !== "i" || components !== 1))
        {
            return fail(c, GL.INVALID_OPERATION);
        }
        const store = target.program.values;
        const n = Math.min(count, u.size - target.at.element);
        for(let i = 0; i < n; i++)
        {
            const slice = values.slice(i * components, (i + 1) * components);
            store.set(location + i, u.bool ? slice.map(v => v ? 1 : 0) : kind === "f" || kind === "m" ? slice.map(Math.fround) : slice);
        }
    };
}

/** glVertexAttrib{1,2,3,4}f(v) */
function vertex_attrib(components, vector)
{
    return (shadow, c, args) =>
    {
        const index = args[0];
        if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
        const values = vector ? f32s(args[1]).slice(0, components) : args.slice(1, 1 + components);
        const current = [0, 0, 0, 1];
        values.forEach((v, i) => { current[i] = Math.fround(v); });
        c.attribs[index].current = current;
    };
}

/** A glGen*: names nothing has, reserved */
function gen(kind, map_of)
{
    return (shadow, c, [n, names]) =>
    {
        query(shadow);
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        const objects = map_of(c);
        const reserved = kind === "framebuffer" ? c.reserved_framebuffers : c.group.reserved[kind];
        for(let i = 0; i < n && 4 * i + 4 <= names.size; i++)
        {
            let name;
            if(kind === "framebuffer")
            {
                name = c.next_framebuffer;
                while(objects.has(name) || reserved.has(name)) name++;
                c.next_framebuffer = name + 1;
            }
            else name = c.group.fresh(kind, objects);
            reserved.add(name);
            names.view.setUint32(4 * i, name, true);
        }
    };
}

/** @type {!Object<string, function(!GLESShadow, !Context, !Array<*>): *>} */
const HANDLERS = {
    "glGetError": (shadow, c) =>
    {
        query(shadow);
        const error = c.error;
        c.error = GL.NO_ERROR;
        return error;
    },
    "glGetGraphicsResetStatusEXT": shadow => { query(shadow); return 0; },
    "glFinishRoundTrip": shadow => { query(shadow); return 0; },
    "glFinish": () => {},
    "glFlush": () => {},
    "glGetBooleanv": get("b"),
    "glGetIntegerv": get("i"),
    "glGetFloatv": get("f"),
    "glGetFixedv": get("x"),
    "glGetCompressedTextureFormats": (shadow, c, [count, formats]) =>
    {
        query(shadow);
        put(formats, COMPRESSED_TEXTURE_FORMATS, "i", "i");
    },
    "glGetShaderPrecisionFormat": (shadow, c, [shadertype, precisiontype, range, precision]) =>
    {
        query(shadow);
        if(shadertype !== GL.VERTEX_SHADER && shadertype !== GL.FRAGMENT_SHADER || precisiontype < 0x8DF0 || precisiontype > 0x8DF5)
        {
            return fail(c, GL.INVALID_ENUM);
        }
        // (WebGPU's: f32 and i32 at every precision)
        const float = precisiontype <= 0x8DF2;
        put(range, float ? [127, 127] : [31, 30], "i", "i");
        put(precision, [float ? 23 : 0], "i", "i");
    },
    "glEnable": (shadow, c, [cap]) =>
    {
        if(!(c.api === 1 ? CAPS_1 : CAPS_2).has(cap)) return fail(c, GL.INVALID_ENUM);
        c.enabled.add(cap);
    },
    "glDisable": (shadow, c, [cap]) =>
    {
        if(!(c.api === 1 ? CAPS_1 : CAPS_2).has(cap)) return fail(c, GL.INVALID_ENUM);
        c.enabled.delete(cap);
    },
    "glIsEnabled": (shadow, c, [cap]) =>
    {
        query(shadow);
        if(!(c.api === 1 ? CAPS_1 : CAPS_2).has(cap)) { fail(c, GL.INVALID_ENUM); return 0; }
        return c.enabled.has(cap) ? 1 : 0;
    },
    "glViewport": (shadow, c, [x, y, width, height]) =>
    {
        if(width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        c.viewport = [x, y, Math.min(width, MAX_VIEWPORT), Math.min(height, MAX_VIEWPORT)];
    },
    "glScissor": (shadow, c, [x, y, width, height]) =>
    {
        if(width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        c.scissor = [x, y, width, height];
    },
    "glDepthRangef": (shadow, c, [near, far]) =>
    {
        c.depth_range = [Math.min(1, Math.max(0, near)), Math.min(1, Math.max(0, far))].map(Math.fround);
    },
    "glLineWidth": (shadow, c, [width]) =>
    {
        if(!(width > 0)) return fail(c, GL.INVALID_VALUE);
        c.line_width = Math.fround(width);
    },
    "glCullFace": (shadow, c, [mode]) =>
    {
        if(!FACES.has(mode)) return fail(c, GL.INVALID_ENUM);
        c.cull_face = mode;
    },
    "glFrontFace": (shadow, c, [mode]) =>
    {
        if(mode !== 0x0900 && mode !== 0x0901) return fail(c, GL.INVALID_ENUM);
        c.front_face = mode;
    },
    "glPolygonOffset": (shadow, c, [factor, units]) => { c.polygon_offset = [Math.fround(factor), Math.fround(units)]; },
    "glSampleCoverage": (shadow, c, [value, invert]) => { c.sample_coverage = [Math.fround(Math.min(1, Math.max(0, value))), invert ? 1 : 0]; },
    "glClearColor": (shadow, c, rgba) => { c.clear_color = rgba.map(v => Math.fround(Math.min(1, Math.max(0, v)))); },
    "glClearDepthf": (shadow, c, [depth]) => { c.clear_depth = Math.fround(Math.min(1, Math.max(0, depth))); },
    "glClearStencil": (shadow, c, [s]) => { c.clear_stencil = s; },
    "glColorMask": (shadow, c, rgba) => { c.color_mask = rgba.map(v => v ? 1 : 0); },
    "glDepthMask": (shadow, c, [flag]) => { c.depth_mask = flag ? 1 : 0; },
    "glStencilMask": (shadow, c, [mask]) => { c.stencil_writemask = [mask | 0, mask | 0]; },
    "glStencilMaskSeparate": (shadow, c, [face, mask]) =>
    {
        if(!FACES.has(face)) return fail(c, GL.INVALID_ENUM);
        if(face !== BACK) c.stencil_writemask[0] = mask | 0;
        if(face !== FRONT) c.stencil_writemask[1] = mask | 0;
    },
    "glBlendColor": (shadow, c, rgba) => { c.blend_color = rgba.map(v => Math.fround(Math.min(1, Math.max(0, v)))); },
    "glBlendEquation": (shadow, c, [mode]) =>
    {
        if(!equation_ok(c, mode, true)) return fail(c, GL.INVALID_ENUM);
        c.blend_equation = [mode, mode];
    },
    "glBlendEquationSeparate": (shadow, c, [rgb, alpha]) =>
    {
        if(!equation_ok(c, rgb, false) || !equation_ok(c, alpha, false)) return fail(c, GL.INVALID_ENUM);
        c.blend_equation = [rgb, alpha];
    },
    "glBlendFunc": (shadow, c, [src, dst]) =>
    {
        if(!source_factor(src) || !destination_factor(c, dst)) return fail(c, GL.INVALID_ENUM);
        c.blend_func = [src, dst, src, dst];
    },
    "glBlendFuncSeparate": (shadow, c, [src_rgb, dst_rgb, src_alpha, dst_alpha]) =>
    {
        if(!source_factor(src_rgb) || !source_factor(src_alpha) || !destination_factor(c, dst_rgb) || !destination_factor(c, dst_alpha)) {
            return fail(c, GL.INVALID_ENUM);
        }
        c.blend_func = [src_rgb, dst_rgb, src_alpha, dst_alpha];
    },
    "glDepthFunc": (shadow, c, [func]) =>
    {
        if(!COMPARE_FUNCS.has(func)) return fail(c, GL.INVALID_ENUM);
        c.depth_func = func;
    },
    "glStencilFunc": (shadow, c, [func, ref, mask]) =>
    {
        if(!COMPARE_FUNCS.has(func)) return fail(c, GL.INVALID_ENUM);
        c.stencil_func = [[func, ref, mask | 0], [func, ref, mask | 0]];
    },
    "glStencilFuncSeparate": (shadow, c, [face, func, ref, mask]) =>
    {
        if(!FACES.has(face) || !COMPARE_FUNCS.has(func)) return fail(c, GL.INVALID_ENUM);
        if(face !== BACK) c.stencil_func[0] = [func, ref, mask | 0];
        if(face !== FRONT) c.stencil_func[1] = [func, ref, mask | 0];
    },
    "glStencilOp": (shadow, c, ops) =>
    {
        if(!ops.every(op => STENCIL_OPS.has(op))) return fail(c, GL.INVALID_ENUM);
        c.stencil_op = [ops.slice(), ops.slice()];
    },
    "glStencilOpSeparate": (shadow, c, [face, ...ops]) =>
    {
        if(!FACES.has(face) || !ops.every(op => STENCIL_OPS.has(op))) return fail(c, GL.INVALID_ENUM);
        if(face !== BACK) c.stencil_op[0] = ops.slice();
        if(face !== FRONT) c.stencil_op[1] = ops.slice();
    },
    "glHint": (shadow, c, [target, mode]) =>
    {
        if(!(c.api === 1 ? c.hints.has(target) : target === 0x8192 || target === 0x8B8B) || !HINT_MODES.has(mode)) return fail(c, GL.INVALID_ENUM);
        c.hints.set(target, mode);
    },
    "glPixelStorei": (shadow, c, [pname, param]) =>
    {
        if(pname !== GL.UNPACK_ALIGNMENT && pname !== GL.PACK_ALIGNMENT) return fail(c, GL.INVALID_ENUM);
        if(![1, 2, 4, 8].includes(param)) return fail(c, GL.INVALID_VALUE);
        if(pname === GL.UNPACK_ALIGNMENT) c.unpack_alignment = param;
        else c.pack_alignment = param;
    },

    // ---- textures
    "glActiveTexture": (shadow, c, [unit]) =>
    {
        const index = unit - GL.TEXTURE0;
        if(index < 0 || index >= (c.api === 1 ? GL_STATE.get(0x84E2)[0] : MAX_UNITS)) return fail(c, GL.INVALID_ENUM);
        c.active_texture = index;
    },
    "glGenTextures": gen("texture", c => c.group.textures),
    "glBindTexture": (shadow, c, [target, name]) =>
    {
        const slot = texture_slot(target);
        if(slot < 0) return fail(c, GL.INVALID_ENUM);
        if(name)
        {
            const texture = c.group.textures.get(name);
            if(texture && texture.target !== target) return fail(c, GL.INVALID_OPERATION);
            if(!texture) c.group.textures.set(name, new_texture(target));
        }
        c.textures[c.active_texture][slot] = name;
    },
    "glDeleteTextures": (shadow, c, [n, names]) =>
    {
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        for(const name of i32s(names).slice(0, n))
        {
            if(!name) continue;
            c.group.reserved.texture.delete(name);
            if(!c.group.textures.delete(name)) continue;
            for(const unit of c.textures) for(let i = 0; i < 3; i++) if(unit[i] === name) unit[i] = 0;
            detach(c, GL.TEXTURE, name);
        }
    },
    "glIsTexture": (shadow, c, [name]) => { query(shadow); return c.group.textures.has(name) ? 1 : 0; },
    "glTexImage2D": (shadow, c, [target, level, internalformat, width, height, border, format, type, pixels]) =>
    {
        const t = image_target(c, target);
        if(!t) return REFUSED;
        const error = texture_format_error(format, type);
        if(error) return fail(c, error);
        if(internalformat !== format) return fail(c, texture_format_error(internalformat, type) === GL.INVALID_ENUM ? GL.INVALID_VALUE : GL.INVALID_OPERATION);
        if(!image_size_ok(c, target, level, width, height, border)) return REFUSED;
        if(pixels && pixels.length < image_bytes(width, height, texel_bytes(format, type), c.unpack_alignment)) return fail(c, GL.INVALID_OPERATION);
        t.texture.images.set(t.face * 32 + level, { width, height, format, type, compressed: false });
    },
    "glTexSubImage2D": (shadow, c, [target, level, x, y, width, height, format, type, pixels]) =>
    {
        const t = image_target(c, target);
        if(!t) return REFUSED;
        const error = texture_format_error(format, type);
        if(error) return fail(c, error);
        if(level < 0 || level > MAX_LEVEL || x < 0 || y < 0 || width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        const image = t.texture.images.get(t.face * 32 + level);
        if(!image || image.compressed) return fail(c, GL.INVALID_OPERATION);
        if(x + width > image.width || y + height > image.height) return fail(c, GL.INVALID_VALUE);
        if(image.format !== format || image.type !== type) return fail(c, GL.INVALID_OPERATION);
    },
    "glCompressedTexImage2D": (shadow, c, [target, level, internalformat, width, height, border, size, data]) =>
    {
        const t = image_target(c, target);
        if(!t) return REFUSED;
        if(internalformat !== GL.ETC1_RGB8_OES) return fail(c, GL.INVALID_ENUM);
        if(!image_size_ok(c, target, level, width, height, border)) return REFUSED;
        if(size !== etc1_bytes(width, height) || (data ? data.length : 0) < size) return fail(c, GL.INVALID_VALUE);
        t.texture.images.set(t.face * 32 + level, { width, height, format: internalformat, type: GL.UNSIGNED_BYTE, compressed: true });
    },
    // (ETC1 has no partial updates: OES_compressed_ETC1_RGB8_texture)
    "glCompressedTexSubImage2D": (shadow, c, [target]) =>
    {
        if(!image_target(c, target)) return REFUSED;
        return fail(c, GL.INVALID_OPERATION);
    },
    "glCopyTexImage2D": (shadow, c, [target, level, internalformat, x, y, width, height, border]) =>
    {
        const t = image_target(c, target);
        if(!t) return REFUSED;
        if(![GL.ALPHA, GL.LUMINANCE, GL.LUMINANCE_ALPHA, GL.RGB, GL.RGBA].includes(internalformat)) return fail(c, GL.INVALID_ENUM);
        if(!image_size_ok(c, target, level, width, height, border)) return REFUSED;
        if(!framebuffer_ok(shadow, c)) return REFUSED;
        // (the framebuffer's channels must cover the format's: GLES 2.0 table 3.9)
        const bits = shadow.framebuffer_bits(c);
        if((internalformat === GL.ALPHA || internalformat === GL.LUMINANCE_ALPHA || internalformat === GL.RGBA) && !bits[3]) return fail(c, GL.INVALID_OPERATION);
        t.texture.images.set(t.face * 32 + level, { width, height, format: internalformat, type: GL.UNSIGNED_BYTE, compressed: false });
    },
    "glCopyTexSubImage2D": (shadow, c, [target, level, xoffset, yoffset, x, y, width, height]) =>
    {
        const t = image_target(c, target);
        if(!t) return REFUSED;
        // (a level above log2 of the largest size: INVALID_VALUE, before whether it has an image)
        if(level < 0 || level > MAX_LEVEL || xoffset < 0 || yoffset < 0 || width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        const image = t.texture.images.get(t.face * 32 + level);
        if(!image || image.compressed) return fail(c, GL.INVALID_OPERATION);
        if(xoffset + width > image.width || yoffset + height > image.height) return fail(c, GL.INVALID_VALUE);
        if(!framebuffer_ok(shadow, c)) return REFUSED;
    },
    "glGenerateMipmap": (shadow, c, [target]) =>
    {
        if(target !== GL.TEXTURE_2D && target !== GL.TEXTURE_CUBE_MAP) return fail(c, GL.INVALID_ENUM);
        const texture = bound_texture(c, target);
        const faces = target === GL.TEXTURE_2D ? 1 : 6;
        const base = texture.images.get(0);
        if(!base || base.compressed) return fail(c, GL.INVALID_OPERATION);
        for(let face = 0; face < faces; face++)
        {
            const image = texture.images.get(face * 32);
            if(!image || image.width !== base.width || image.height !== base.height || image.format !== base.format) return fail(c, GL.INVALID_OPERATION);
        }
        for(let face = 0; face < faces; face++)
        {
            let w = base.width, h = base.height;
            for(let level = 1; w > 1 || h > 1; level++)
            {
                w = Math.max(1, w >> 1);
                h = Math.max(1, h >> 1);
                texture.images.set(face * 32 + level, { width: w, height: h, format: base.format, type: base.type, compressed: false });
            }
        }
    },
    "glTexParameterf": (shadow, c, [target, pname, param]) => tex_parameter(c, target, pname, [param]),
    "glTexParameteri": (shadow, c, [target, pname, param]) => tex_parameter(c, target, pname, [param]),
    "glTexParameterx": (shadow, c, [target, pname, param]) => tex_parameter(c, target, pname, [param]),
    "glTexParameterfv": (shadow, c, [target, pname, params]) => tex_parameter(c, target, pname, f32s(params)),
    "glTexParameteriv": (shadow, c, [target, pname, params]) => tex_parameter(c, target, pname, i32s(params)),
    "glTexParameterxv": (shadow, c, [target, pname, params]) => tex_parameter(c, target, pname, i32s(params)),
    "glGetTexParameteriv": (shadow, c, [target, pname, params]) => get_tex_parameter(shadow, c, target, pname, params, "i"),
    "glGetTexParameterfv": (shadow, c, [target, pname, params]) => get_tex_parameter(shadow, c, target, pname, params, "f"),
    "glGetTexParameterxv": (shadow, c, [target, pname, params]) => get_tex_parameter(shadow, c, target, pname, params, "i"),
    // EGL images (OES_EGL_image): the image's color buffer is the texture's level 0
    "glEGLImageTargetTexture2DOES": (shadow, c, [target, image]) =>
    {
        if(target !== GL.TEXTURE_2D && target !== GL.TEXTURE_EXTERNAL_OES) return fail(c, GL.INVALID_ENUM);
        const size = shadow.image_size(image);
        if(!size) return fail(c, GL.INVALID_VALUE);
        const texture = bound_texture(c, target);
        if(!texture) return REFUSED;
        texture.images.clear();
        texture.images.set(0, { width: size.width, height: size.height, format: size.format, type: GL.UNSIGNED_BYTE, compressed: false, image });
    },
    "glEGLImageTargetRenderbufferStorageOES": (shadow, c, [target, image]) =>
    {
        if(target !== GL.RENDERBUFFER) return fail(c, GL.INVALID_ENUM);
        const size = shadow.image_size(image);
        if(!size) return fail(c, GL.INVALID_VALUE);
        const rb = c.group.renderbuffers.get(c.renderbuffer);
        if(!rb) return fail(c, GL.INVALID_OPERATION);
        Object.assign(rb, { width: size.width, height: size.height, format: size.format === GL.RGB ? GL.RGB8_OES : GL.RGBA8_OES, image });
    },

    // ---- buffers
    "glGenBuffers": gen("buffer", c => c.group.buffers),
    "glBindBuffer": (shadow, c, [target, name]) =>
    {
        if(target !== GL.ARRAY_BUFFER && target !== GL.ELEMENT_ARRAY_BUFFER) return fail(c, GL.INVALID_ENUM);
        if(name && !c.group.buffers.has(name)) c.group.buffers.set(name, { size: 0, usage: GL.STATIC_DRAW });
        if(target === GL.ARRAY_BUFFER) c.array_buffer = name;
        else c.element_array_buffer = name;
    },
    "glDeleteBuffers": (shadow, c, [n, names]) =>
    {
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        for(const name of i32s(names).slice(0, n))
        {
            if(!name) continue;
            c.group.reserved.buffer.delete(name);
            if(!c.group.buffers.delete(name)) continue;
            if(c.array_buffer === name) c.array_buffer = 0;
            if(c.element_array_buffer === name) c.element_array_buffer = 0;
            for(const a of c.attribs) if(a.buffer === name) a.buffer = 0;
        }
    },
    "glIsBuffer": (shadow, c, [name]) => { query(shadow); return c.group.buffers.has(name) ? 1 : 0; },
    "glBufferData": (shadow, c, [target, size, data, usage]) =>
    {
        if(target !== GL.ARRAY_BUFFER && target !== GL.ELEMENT_ARRAY_BUFFER || !USAGES.has(usage)) return fail(c, GL.INVALID_ENUM);
        if(size < 0) return fail(c, GL.INVALID_VALUE);
        const buffer = bound_buffer(c, target);
        if(!buffer) return REFUSED;
        buffer.size = size;
        buffer.usage = usage;
    },
    "glBufferSubData": (shadow, c, [target, offset, size, data]) =>
    {
        const buffer = bound_buffer(c, target);
        if(!buffer) return REFUSED;
        if(offset < 0 || size < 0 || offset + size > buffer.size) return fail(c, GL.INVALID_VALUE);
    },
    "glGetBufferParameteriv": (shadow, c, [target, pname, params]) =>
    {
        query(shadow);
        if(pname !== 0x8764 && pname !== 0x8765) { fail(c, GL.INVALID_ENUM); return; }
        const buffer = bound_buffer(c, target);
        if(!buffer) return;
        put(params, [pname === 0x8764 ? buffer.size : buffer.usage], "i", "i");
    },

    // ---- renderbuffers and framebuffers
    "glGenRenderbuffers": gen("renderbuffer", c => c.group.renderbuffers),
    "glBindRenderbuffer": (shadow, c, [target, name]) =>
    {
        if(target !== GL.RENDERBUFFER) return fail(c, GL.INVALID_ENUM);
        if(name && !c.group.renderbuffers.has(name)) c.group.renderbuffers.set(name, { width: 0, height: 0, format: GL.RGBA4, image: 0 });
        c.renderbuffer = name;
    },
    "glDeleteRenderbuffers": (shadow, c, [n, names]) =>
    {
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        for(const name of i32s(names).slice(0, n))
        {
            if(!name) continue;
            c.group.reserved.renderbuffer.delete(name);
            const renderbuffer = c.group.renderbuffers.get(name);
            if(!c.group.renderbuffers.delete(name)) continue;
            if(c.renderbuffer === name) c.renderbuffer = 0;
            detach(c, GL.RENDERBUFFER, name);
            keep_orphan(c, GL.RENDERBUFFER, c.group.renderbuffers, name, renderbuffer);
        }
    },
    "glIsRenderbuffer": (shadow, c, [name]) => { query(shadow); return c.group.renderbuffers.has(name) ? 1 : 0; },
    "glRenderbufferStorage": (shadow, c, [target, format, width, height]) =>
    {
        if(target !== GL.RENDERBUFFER || !RENDERBUFFER_FORMATS.has(format)) return fail(c, GL.INVALID_ENUM);
        if(width < 0 || height < 0 || width > MAX_SIZE || height > MAX_SIZE) return fail(c, GL.INVALID_VALUE);
        const rb = c.group.renderbuffers.get(c.renderbuffer);
        if(!rb) return fail(c, GL.INVALID_OPERATION);
        Object.assign(rb, { width, height, format, image: 0 });
    },
    "glGetRenderbufferParameteriv": (shadow, c, [target, pname, params]) =>
    {
        query(shadow);
        if(target !== GL.RENDERBUFFER) { fail(c, GL.INVALID_ENUM); return; }
        const rb = c.group.renderbuffers.get(c.renderbuffer);
        if(!rb) { fail(c, GL.INVALID_OPERATION); return; }
        // (GLES 2.0's formats, else GLES 3.0's sized ones)
        const bits = rb.width ? (RENDERBUFFER_FORMATS.get(rb.format) || SIZED_INFO(rb.format) || { bits: [0, 0, 0, 0, 0, 0] }).bits : [0, 0, 0, 0, 0, 0];
        const values = { 0x8D42: rb.width, 0x8D43: rb.height, 0x8D44: rb.format, 0x8D50: bits[0], 0x8D51: bits[1], 0x8D52: bits[2],
            0x8D53: bits[3], 0x8D54: bits[4], 0x8D55: bits[5] };
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [values[pname]], "i", "i");
    },
    "glGenFramebuffers": gen("framebuffer", c => c.framebuffers),
    "glBindFramebuffer": (shadow, c, [target, name]) =>
    {
        if(target !== GL.FRAMEBUFFER) return fail(c, GL.INVALID_ENUM);
        if(name && !c.framebuffers.has(name)) c.framebuffers.set(name, { attachments: new Map() });
        c.framebuffer = name;
    },
    "glDeleteFramebuffers": (shadow, c, [n, names]) =>
    {
        if(n < 0) return fail(c, GL.INVALID_VALUE);
        for(const name of i32s(names).slice(0, n))
        {
            if(!name) continue;
            c.reserved_framebuffers.delete(name);
            if(!c.framebuffers.delete(name)) continue;
            if(c.framebuffer === name) c.framebuffer = 0;
        }
    },
    "glIsFramebuffer": (shadow, c, [name]) => { query(shadow); return c.framebuffers.has(name) ? 1 : 0; },
    "glCheckFramebufferStatus": (shadow, c, [target]) =>
    {
        query(shadow);
        if(target !== GL.FRAMEBUFFER) { fail(c, GL.INVALID_ENUM); return 0; }
        return shadow.framebuffer_status(c);
    },
    "glFramebufferRenderbuffer": (shadow, c, [target, attachment, rbtarget, name]) =>
    {
        if(target !== GL.FRAMEBUFFER || !ATTACHMENTS.includes(attachment) || rbtarget !== GL.RENDERBUFFER) return fail(c, GL.INVALID_ENUM);
        const fbo = c.framebuffers.get(c.framebuffer);
        if(!fbo || name && !c.group.renderbuffers.has(name)) return fail(c, GL.INVALID_OPERATION);
        if(name) fbo.attachments.set(attachment, { type: GL.RENDERBUFFER, name, level: 0, face: 0 });
        else fbo.attachments.delete(attachment);
    },
    "glFramebufferTexture2D": (shadow, c, [target, attachment, textarget, name, level]) =>
    {
        if(target !== GL.FRAMEBUFFER || !ATTACHMENTS.includes(attachment)) return fail(c, GL.INVALID_ENUM);
        const fbo = c.framebuffers.get(c.framebuffer);
        if(!fbo) return fail(c, GL.INVALID_OPERATION);
        if(!name)
        {
            fbo.attachments.delete(attachment);
            return;
        }
        const face = face_of(textarget);
        if(face < 0) return fail(c, GL.INVALID_ENUM);
        if(level !== 0) return fail(c, GL.INVALID_VALUE);
        const texture = c.group.textures.get(name);
        if(!texture || (texture.target === GL.TEXTURE_CUBE_MAP) !== (textarget !== GL.TEXTURE_2D)) return fail(c, GL.INVALID_OPERATION);
        fbo.attachments.set(attachment, { type: GL.TEXTURE, name, level, face });
    },
    "glGetFramebufferAttachmentParameteriv": (shadow, c, [target, attachment, pname, params]) =>
    {
        query(shadow);
        if(target !== GL.FRAMEBUFFER || !ATTACHMENTS.includes(attachment)) { fail(c, GL.INVALID_ENUM); return; }
        const fbo = c.framebuffers.get(c.framebuffer);
        if(!fbo) { fail(c, GL.INVALID_OPERATION); return; }
        const a = fbo.attachments.get(attachment);
        let value;
        if(pname === 0x8CD0) value = a ? a.type : GL.NONE;
        else if(!a || pname !== 0x8CD1 && (a.type !== GL.TEXTURE || pname !== 0x8CD2 && pname !== 0x8CD3)) { fail(c, GL.INVALID_ENUM); return; }
        else value = pname === 0x8CD1 ? a.name : pname === 0x8CD2 ? a.level : a.face ? GL.TEXTURE_CUBE_MAP_POSITIVE_X + a.face : 0;
        put(params, [value], "i", "i");
    },
    "glDiscardFramebufferEXT": () => {},

    // ---- drawing
    "glClear": (shadow, c, [mask]) =>
    {
        if(mask & ~CLEAR_BITS) return fail(c, GL.INVALID_VALUE);
        if(!framebuffer_ok(shadow, c)) return REFUSED;
    },
    "glDrawArrays": (shadow, c, [mode, first, count]) =>
    {
        if(!MODES.has(mode)) return fail(c, GL.INVALID_ENUM);
        if(first < 0 || count < 0) return fail(c, GL.INVALID_VALUE);
        if(!framebuffer_ok(shadow, c)) return REFUSED;
    },
    "glDrawElementsOffset": (shadow, c, [mode, count, type, offset]) => draw_elements(shadow, c, mode, count, type, !!c.element_array_buffer),
    "glDrawElementsData": (shadow, c, [mode, count, type, data]) => draw_elements(shadow, c, mode, count, type, true),
    "glReadPixels": (shadow, c, [x, y, width, height, format, type]) =>
    {
        if(width < 0 || height < 0) return fail(c, GL.INVALID_VALUE);
        if(texture_format_error(format, type) === GL.INVALID_ENUM) return fail(c, GL.INVALID_ENUM);
        if(format !== GL.RGBA || type !== GL.UNSIGNED_BYTE) return fail(c, GL.INVALID_OPERATION);
        if(!framebuffer_ok(shadow, c)) return REFUSED;
    },

    // ---- vertex attributes (the encoder's: client arrays' data with the pointer, or a buffer's offset)
    "glEnableVertexAttribArray": (shadow, c, [index]) =>
    {
        if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
        c.attribs[index].enabled = true;
    },
    "glDisableVertexAttribArray": (shadow, c, [index]) =>
    {
        if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
        c.attribs[index].enabled = false;
    },
    "glVertexAttribPointerData": (shadow, c, [index, size, type, normalized, stride]) => attrib_pointer(c, index, size, type, normalized, stride, 0, 0),
    "glVertexAttribPointerOffset": (shadow, c, [index, size, type, normalized, stride, offset]) =>
        attrib_pointer(c, index, size, type, normalized, stride, c.array_buffer, offset),
    "glVertexAttrib1f": vertex_attrib(1, false),
    "glVertexAttrib2f": vertex_attrib(2, false),
    "glVertexAttrib3f": vertex_attrib(3, false),
    "glVertexAttrib4f": vertex_attrib(4, false),
    "glVertexAttrib1fv": vertex_attrib(1, true),
    "glVertexAttrib2fv": vertex_attrib(2, true),
    "glVertexAttrib3fv": vertex_attrib(3, true),
    "glVertexAttrib4fv": vertex_attrib(4, true),
    "glGetVertexAttribfv": (shadow, c, [index, pname, params]) => get_vertex_attrib(shadow, c, index, pname, params, "f"),
    "glGetVertexAttribiv": (shadow, c, [index, pname, params]) => get_vertex_attrib(shadow, c, index, pname, params, "i"),

    // ---- shaders and programs
    "glCreateShader": (shadow, c, [type]) =>
    {
        if(type !== GL.VERTEX_SHADER && type !== GL.FRAGMENT_SHADER) { fail(c, GL.INVALID_ENUM); return 0; }
        const name = shadow.given_name || c.group.fresh("object", c.group.objects);
        c.group.objects.set(name, { kind: "shader", type, source: null, compiled: null, compiled_source: null, deleted: false, attached: 0 });
        return name;
    },
    "glCreateProgram": (shadow, c) =>
    {
        const name = shadow.given_name || c.group.fresh("object", c.group.objects);
        c.group.objects.set(name, { kind: "program", shaders: new Set(), bindings: new Map(), info: null, linked_once: false,
            validated: 0, deleted: false, values: new Map() });
        return name;
    },
    "glShaderString": (shadow, c, [name, string]) =>
    {
        const shader = object_of(c, name, "shader");
        if(!shader) return REFUSED;
        shader.source = text_of(string);
    },
    "glCompileShader": (shadow, c, [name]) =>
    {
        const shader = object_of(c, name, "shader");
        if(!shader) return REFUSED;
        // (the source compiled: a snapshot compiles it again, gles_snapshot.js)
        shader.compiled_source = shader.source || "";
        const start = performance.now();
        shader.compiled = shadow.compile(shader.compiled_source, shader.type, c.glslang, c.api === 2);
        shadow.stats.compile_ms += performance.now() - start;
        shadow.stats.compiled++;
        if(!shader.compiled.ok)
        {
            shadow.stats.compile_failed++;
            if(shadow.stats.failures.length < 8) shadow.stats.failures.push(shader.compiled.log + "\n" + shader.source);
        }
    },
    "glDeleteShader": (shadow, c, [name]) =>
    {
        if(!name) return undefined;
        const shader = object_of(c, name, "shader");
        if(!shader) return REFUSED;
        shader.deleted = true;
        if(!shader.attached) c.group.objects.delete(name);
    },
    "glDeleteProgram": (shadow, c, [name]) =>
    {
        if(!name) return undefined;
        const program = object_of(c, name, "program");
        if(!program) return REFUSED;
        program.deleted = true;
        if(!shadow.program_in_use(name)) shadow.free_program(c.group, name);
    },
    "glIsShader": (shadow, c, [name]) => { query(shadow); const o = c.group.objects.get(name); return o && o.kind === "shader" ? 1 : 0; },
    "glIsProgram": (shadow, c, [name]) => { query(shadow); const o = c.group.objects.get(name); return o && o.kind === "program" ? 1 : 0; },
    "glAttachShader": (shadow, c, [p, s]) =>
    {
        const program = object_of(c, p, "program");
        const shader = program && object_of(c, s, "shader");
        if(!shader) return REFUSED;
        if(program.shaders.has(s) || [...program.shaders].some(other => c.group.objects.get(other).type === shader.type)) return fail(c, GL.INVALID_OPERATION);
        program.shaders.add(s);
        shader.attached++;
    },
    "glDetachShader": (shadow, c, [p, s]) =>
    {
        const program = object_of(c, p, "program");
        const shader = program && object_of(c, s, "shader");
        if(!shader) return REFUSED;
        if(!program.shaders.has(s)) return fail(c, GL.INVALID_OPERATION);
        program.shaders.delete(s);
        if(--shader.attached === 0 && shader.deleted) c.group.objects.delete(s);
    },
    "glBindAttribLocation": (shadow, c, [p, index, name]) =>
    {
        const program = object_of(c, p, "program");
        if(!program) return REFUSED;
        if(index >= MAX_ATTRIBS) return fail(c, GL.INVALID_VALUE);
        const text = text_of(name);
        if(text.startsWith("gl_")) return fail(c, GL.INVALID_OPERATION);
        program.bindings.set(text, index);
    },
    "glLinkProgram": (shadow, c, [p]) =>
    {
        const program = object_of(c, p, "program");
        if(!program) return REFUSED;
        const shaders = [...program.shaders].map(s => c.group.objects.get(s));
        const shader = type => shaders.find(s => s.type === type);
        const vs = shader(GL.VERTEX_SHADER), fs = shader(GL.FRAGMENT_SHADER);
        const start = performance.now();
        program.info = shadow.link(program, shaders, c.api === 2);
        shadow.stats.compile_ms += performance.now() - start;
        // (what was linked: a snapshot links it again)
        program.link = { vs: vs && vs.compiled ? vs.compiled_source : null, fs: fs && fs.compiled ? fs.compiled_source : null,
            bindings: [...program.bindings] };
        if(shaders.some(s => s.compiled && s.compiled.glslang))
        {
            program.link.glslang = true;
            program.link.shaders = shaders.map(s => [s.type, s.compiled_source]);
            program.link.separable = !!program.separable;
            program.link.tf = program.tf_request || null;
            // (the page cannot link it again: its snapshot keeps the result)
            program.keep_info = !shadow.glslang;
        }
        program.linked_once = true;
        shadow.stats.linked++;
        if(!program.info.ok)
        {
            shadow.stats.link_failed++;
            if(shadow.stats.failures.length < 8) shadow.stats.failures.push(program.info.log);
        }
        program.values = initial_values(program.info);
    },
    "glValidateProgram": (shadow, c, [p]) =>
    {
        const program = object_of(c, p, "program");
        if(!program) return REFUSED;
        program.validated = program.info && program.info.ok ? 1 : 0;
    },
    "glUseProgram": (shadow, c, [p]) =>
    {
        if(p)
        {
            const program = object_of(c, p, "program");
            if(!program) return REFUSED;
            if(!program.info || !program.info.ok) return fail(c, GL.INVALID_OPERATION);
        }
        const old = c.program;
        c.program = p;
        const previous = old && c.group.objects.get(old);
        if(previous && previous.deleted && !shadow.program_in_use(old)) shadow.free_program(c.group, old);
    },
    "glReleaseShaderCompiler": () => {},
    "glGetShaderiv": (shadow, c, [name, pname, params]) =>
    {
        query(shadow);
        const shader = object_of(c, name, "shader");
        if(!shader) return;
        const log = shader.compiled ? shader.compiled.log : "";
        const values = {
            0x8B4F: shader.type, 0x8B80: shader.deleted ? 1 : 0, 0x8B81: shader.compiled && shader.compiled.ok ? 1 : 0,
            0x8B84: log ? new TextEncoder().encode(log).length + 1 : 0,
            0x8B88: shader.source ? new TextEncoder().encode(shader.source).length + 1 : 0,
        };
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [values[pname]], "i", "i");
    },
    "glGetShaderInfoLog": (shadow, c, [name, bufsize, length, log]) =>
    {
        query(shadow);
        if(bufsize < 0) { fail(c, GL.INVALID_VALUE); return; }
        const shader = object_of(c, name, "shader");
        if(!shader) return;
        put(length, [put_text(log, shader.compiled ? shader.compiled.log : "")], "i", "i");
    },
    "glGetShaderSource": (shadow, c, [name, bufsize, length, source]) =>
    {
        query(shadow);
        if(bufsize < 0) { fail(c, GL.INVALID_VALUE); return; }
        const shader = object_of(c, name, "shader");
        if(!shader) return;
        put(length, [put_text(source, shader.source || "")], "i", "i");
    },
    "glGetProgramiv": (shadow, c, [name, pname, params]) =>
    {
        query(shadow);
        const program = object_of(c, name, "program");
        if(!program) return;
        const info = program.info;
        const linked = info && info.ok;
        const longest = list => list.reduce((n, item) => Math.max(n, new TextEncoder().encode(item.name).length + 1), 0);
        const values = {
            0x8B80: program.deleted ? 1 : 0, 0x8B82: linked ? 1 : 0, 0x8B83: program.validated,
            0x8B84: info && info.log ? new TextEncoder().encode(info.log).length + 1 : 0, 0x8B85: program.shaders.size,
            0x8B86: linked ? info.uniforms.length : 0, 0x8B87: linked ? longest(info.uniforms) : 0,
            0x8B89: linked ? info.attributes.length : 0, 0x8B8A: linked ? longest(info.attributes) : 0,
        };
        if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
        put(params, [values[pname]], "i", "i");
    },
    "glGetProgramInfoLog": (shadow, c, [name, bufsize, length, log]) =>
    {
        query(shadow);
        if(bufsize < 0) { fail(c, GL.INVALID_VALUE); return; }
        const program = object_of(c, name, "program");
        if(!program) return;
        put(length, [put_text(log, program.info ? program.info.log : "")], "i", "i");
    },
    "glGetAttachedShaders": (shadow, c, [name, maxcount, count, shaders]) =>
    {
        query(shadow);
        if(maxcount < 0) { fail(c, GL.INVALID_VALUE); return; }
        const program = object_of(c, name, "program");
        if(!program) return;
        const list = [...program.shaders].slice(0, maxcount);
        put(count, [list.length], "i", "i");
        put(shaders, list, "i", "i");
    },
    "glGetActiveAttrib": (shadow, c, args) => get_active(shadow, c, args, "attributes"),
    "glGetActiveUniform": (shadow, c, args) => get_active(shadow, c, args, "uniforms"),
    "glGetAttribLocation": (shadow, c, [name, text]) =>
    {
        query(shadow);
        const program = object_of(c, name, "program");
        if(!program) return -1;
        if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return -1; }
        const attribute = program.info.attributes.find(a => a.name === text_of(text));
        return attribute ? attribute.location : -1;
    },
    "glGetUniformLocation": (shadow, c, [name, text]) =>
    {
        query(shadow);
        const program = object_of(c, name, "program");
        if(!program) return -1;
        if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return -1; }
        const location = program.info.locations.get(text_of(text));
        return location === undefined ? -1 : location;
    },
    "glGetUniformfv": (shadow, c, [name, location, params]) => get_uniform(shadow, c, name, location, params, "f"),
    "glGetUniformiv": (shadow, c, [name, location, params]) => get_uniform(shadow, c, name, location, params, "i"),
    "glUniform1f": uniform(1, "f", false), "glUniform2f": uniform(2, "f", false), "glUniform3f": uniform(3, "f", false),
    "glUniform4f": uniform(4, "f", false), "glUniform1i": uniform(1, "i", false), "glUniform2i": uniform(2, "i", false),
    "glUniform3i": uniform(3, "i", false), "glUniform4i": uniform(4, "i", false),
    "glUniform1fv": uniform(1, "f", true), "glUniform2fv": uniform(2, "f", true), "glUniform3fv": uniform(3, "f", true),
    "glUniform4fv": uniform(4, "f", true), "glUniform1iv": uniform(1, "i", true), "glUniform2iv": uniform(2, "i", true),
    "glUniform3iv": uniform(3, "i", true), "glUniform4iv": uniform(4, "i", true),
    "glUniformMatrix2fv": uniform(4, "m", true), "glUniformMatrix3fv": uniform(9, "m", true), "glUniformMatrix4fv": uniform(16, "m", true),
    // (no binary formats: GL_NUM_SHADER_BINARY_FORMATS is 0)
    "glShaderBinary": (shadow, c) => fail(c, GL.INVALID_ENUM),
    "glUnmapBufferOES": shadow => { query(shadow); return 1; },
};

/**
 * GLES 1.1's commands (src/gles/gles1_state.js), and the shared ones whose
 * rules differ: glEnable's texture targets are per unit, its client arrays
 * are glEnableClientState's (glIsEnabled answers both)
 */
const GLES1_HANDLERS = gles1_handlers(fail, query);

/** GLES 3.0's status of a framebuffer (gles3_state.js sets fn) */
const FRAMEBUFFER_STATUS3 = { fn: null };

/** GLES 3.x's handlers (gles3_state.js) over GLES 2.0's */
const GLES3_HANDLERS = gles3_handlers({
    fail, query, put, put_text, i32s, f32s, text_of, REFUSED, base: HANDLERS, framebuffer_status3: FRAMEBUFFER_STATUS3, new_texture,
    detach, keep_orphan, state_kind: pname => STATE_KIND.get(pname) || (INT64_STATE.has(pname) ? "i" : "i"),
    // (the default framebuffer's: the draw surface's configuration)
    framebuffer_bits: c => GLESShadow.prototype.framebuffer_bits.call(null, { framebuffer: 0, surface: c.surface }),
    extensions: () => EXTENSIONS_3,
    renderbuffer_info: format =>
    {
        const r = RENDERBUFFER_FORMATS.get(format);
        if(!r) return null;
        return { kind: r.depth && r.stencil ? "depth_stencil" : r.depth ? "depth" : r.stencil ? "stencil" : "unorm", bits: r.bits,
            value: format, format: r.color ? (r.bits[3] ? 0x1908 : 0x1907) : 0, types: [0x1401], renderable: true, sized: true };
    },
});

/** GLES 3.1's handlers (gles31_state.js) over GLES 3.0's */
const GLES31_HANDLERS = gles31_handlers({ fail, query, put, put_text, i32s, f32s, text_of, REFUSED, base: HANDLERS, initial_values }, GLES3_HANDLERS);

/** GL_EXTENSIONS of a GLES 3.x context, as glGetStringi counts them */
GLESShadow.prototype.extensions3 = function()
{
    return EXTENSIONS_3;
};

/** GL_IMPLEMENTATION_COLOR_READ_FORMAT and _TYPE of the read buffer, or null for none */
GLESShadow.prototype.read_info3 = function(c)
{
    if(!c.read_framebuffer) return [c.default_read_buffer === 0 ? 0x1908 : 0x1908, 0x1401];
    const fbo = c.framebuffers.get(c.read_framebuffer);
    const a = fbo.attachments.get(fbo.read_buffer);
    if(!a) return null;
    const rb = a.type === GL.RENDERBUFFER ? c.group.renderbuffers.get(a.name) : null;
    const texture = a.type === GL.RENDERBUFFER ? null : c.group.textures.get(a.name);
    const image = texture && texture.images.get(a.face * 32 + a.level);
    const format = rb ? rb.format : image ? image.internal || image.format : 0;
    const info = SIZED_INFO(format);
    if(!info || !info.types) return [0x1908, 0x1401];
    return [info.format, info.types[info.types.length > 1 && info.types[0] === 0x1401 ? 1 : 0]];
};
for(const [name, enable] of [["glEnable", true], ["glDisable", false]])
{
    GLES1_HANDLERS[name] = (shadow, c, [cap]) =>
    {
        if(cap === GL.TEXTURE_2D || cap === GL.TEXTURE_EXTERNAL_OES)
        {
            c.ff.texture_enabled[c.active_texture][cap] = enable;
            return undefined;
        }
        if(CLIENT_ARRAYS[cap]) return fail(c, GL.INVALID_ENUM);
        return HANDLERS[name](shadow, c, [cap]);
    };
}
GLES1_HANDLERS["glIsEnabled"] = (shadow, c, [cap]) =>
{
    const own = gles1_state_value(c, cap);
    if(own && own[1] === "b") { query(shadow); return own[0][0] ? 1 : 0; }
    return HANDLERS["glIsEnabled"](shadow, c, [cap]);
};

/** A draw of elements' checks; `indices` whether there are any (a buffer bound or the data sent) */
function draw_elements(shadow, c, mode, count, type, indices)
{
    if(!MODES.has(mode) || !INDEX_TYPES.has(type)) return fail(c, GL.INVALID_ENUM);
    if(count < 0) return fail(c, GL.INVALID_VALUE);
    if(!framebuffer_ok(shadow, c)) return REFUSED;
    return undefined;
}

function attrib_pointer(c, index, size, type, normalized, stride, buffer, offset)
{
    if(index >= MAX_ATTRIBS || size < 1 || size > 4 || stride < 0) return fail(c, GL.INVALID_VALUE);
    if(!ATTRIB_TYPES.has(type)) return fail(c, GL.INVALID_ENUM);
    Object.assign(c.attribs[index], { size, type, normalized: !!normalized, stride, buffer, offset });
    return undefined;
}

function tex_parameter(c, target, pname, params)
{
    const texture = bound_texture(c, target);
    if(!texture) return REFUSED;
    const value = params[0];
    const external = target === GL.TEXTURE_EXTERNAL_OES;
    switch(pname)
    {
        case GL.TEXTURE_MIN_FILTER:
            if(!MIN_FILTERS.has(value) || external && value !== GL.NEAREST && value !== GL.LINEAR) return fail(c, GL.INVALID_ENUM);
            texture.min_filter = value;
            return undefined;
        case GL.TEXTURE_MAG_FILTER:
            if(value !== GL.NEAREST && value !== GL.LINEAR) return fail(c, GL.INVALID_ENUM);
            texture.mag_filter = value;
            return undefined;
        case GL.TEXTURE_WRAP_S: case GL.TEXTURE_WRAP_T:
            if(!WRAPS.has(value) || external && value !== GL.CLAMP_TO_EDGE) return fail(c, GL.INVALID_ENUM);
            if(pname === GL.TEXTURE_WRAP_S) texture.wrap_s = value;
            else texture.wrap_t = value;
            return undefined;
        case GL.GENERATE_MIPMAP:
            if(c.api !== 1) return fail(c, GL.INVALID_ENUM);
            texture.generate_mipmap = value ? 1 : 0;
            return undefined;
        case GL.TEXTURE_CROP_RECT_OES:
            if(c.api !== 1) return fail(c, GL.INVALID_ENUM);
            texture.crop = params.slice(0, 4);
            return undefined;
    }
    return fail(c, GL.INVALID_ENUM);
}

function get_tex_parameter(shadow, c, target, pname, params, as)
{
    query(shadow);
    const texture = bound_texture(c, target);
    if(!texture) return;
    const values = {
        [GL.TEXTURE_MIN_FILTER]: [texture.min_filter], [GL.TEXTURE_MAG_FILTER]: [texture.mag_filter],
        [GL.TEXTURE_WRAP_S]: [texture.wrap_s], [GL.TEXTURE_WRAP_T]: [texture.wrap_t],
    };
    if(c.api === 1)
    {
        values[GL.GENERATE_MIPMAP] = [texture.generate_mipmap];
        values[GL.TEXTURE_CROP_RECT_OES] = texture.crop;
    }
    if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
    put(params, values[pname], as, "i");
}

function get_vertex_attrib(shadow, c, index, pname, params, as)
{
    query(shadow);
    if(index >= MAX_ATTRIBS) { fail(c, GL.INVALID_VALUE); return; }
    const a = c.attribs[index];
    const values = {
        0x8622: [a.enabled ? 1 : 0], 0x8623: [a.size], 0x8624: [a.stride], 0x8625: [a.type], 0x886A: [a.normalized ? 1 : 0],
        0x889F: [a.buffer], 0x8626: a.current,
    };
    if(!(pname in values)) { fail(c, GL.INVALID_ENUM); return; }
    put(params, values[pname], as, pname === 0x8626 ? "f" : "i");
}

function get_active(shadow, c, [name, index, bufsize, length, size, type, text], list)
{
    query(shadow);
    const program = object_of(c, name, "program");
    if(!program) return;
    const items = program.info && program.info.ok ? program.info[list] : [];
    if(index >= items.length || bufsize < 0) { fail(c, GL.INVALID_VALUE); return; }
    const item = items[index];
    put(length, [put_text(text, item.name)], "i", "i");
    put(size, [item.size], "i", "i");
    put(type, [item.type], "i", "i");
}

function get_uniform(shadow, c, name, location, params, as)
{
    query(shadow);
    const program = object_of(c, name, "program");
    if(!program) return;
    if(!program.info || !program.info.ok) { fail(c, GL.INVALID_OPERATION); return; }
    const at = program.info.by_location[location];
    if(!at) { fail(c, GL.INVALID_OPERATION); return; }
    const u = at.uniform;
    const count = u.columns ? u.columns * u.columns : u.components;
    const values = program.values.get(location) || new Array(count).fill(0);
    put(params, values, as, u.int || u.bool ? "i" : "f");
}

/**
 * rcBindTexture and rcBindRenderbuffer: a color buffer becomes the image
 * of the context's bound 2D texture (level 0) or renderbuffer
 * @param {number} handle the context
 * @param {number} color_buffer
 * @param {boolean} texture
 * @return {boolean} whether there was something to bind it to
 */
GLESShadow.prototype.bind_color_buffer = function(handle, color_buffer, texture)
{
    const c = this.contexts.get(handle);
    const cb = this.rc && this.rc.color_buffers.get(color_buffer);
    if(!c || !cb) return false;
    const format = cb.format === GL.RGB ? GL.RGB : GL.RGBA;
    if(texture)
    {
        const t = bound_texture(c, GL.TEXTURE_2D);
        t.images.clear();
        t.images.set(0, { width: cb.width, height: cb.height, format, type: GL.UNSIGNED_BYTE, compressed: false, color_buffer });
        return true;
    }
    const rb = c.group.renderbuffers.get(c.renderbuffer);
    if(!rb) return false;
    Object.assign(rb, { width: cb.width, height: cb.height, format: format === GL.RGB ? GL.RGB8_OES : GL.RGBA8_OES, image: 0 });
    return true;
};

/** Whether a program is current in any context of the shadow */
GLESShadow.prototype.program_in_use = function(name)
{
    for(const context of this.contexts.values()) if(context.program === name) return true;
    return false;
};

/** A program goes: its shaders lose an attachment */
GLESShadow.prototype.free_program = function(group, name)
{
    const program = group.objects.get(name);
    if(!program) return;
    for(const s of program.shaders)
    {
        const shader = group.objects.get(s);
        if(shader && --shader.attached === 0 && shader.deleted) group.objects.delete(s);
    }
    group.objects.delete(name);
};

/**
 * An EGL image's size and format: its color buffer's (renderControl's)
 * @param {number} image
 * @return {?{width: number, height: number, format: number}}
 */
GLESShadow.prototype.image_size = function(image)
{
    if(!this.rc) return null;
    const object = this.rc.images.get(image);
    if(!object) return null;
    const cb = this.rc.color_buffers.get(object.buffer);
    if(!cb) return null;
    return { width: cb.width, height: cb.height, format: cb.format === GL.RGB ? GL.RGB : GL.RGBA };
};

/** @param {string} name @return {boolean} whether the shadow state follows the call */
export function shadow_handles(name)
{
    return Object.prototype.hasOwnProperty.call(HANDLERS, name) || Object.prototype.hasOwnProperty.call(HANDLERS, name.replace(/OES$/, ""));
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/gles/gles_snapshot.js                                                                0000644 0000000 0000000 00000017102 00000000000 014615  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES state in snapshots (docs/gles-proxy-plan.md E5): what the GLES host
// keeps (renderControl's objects, the shadow state, the connections) and
// what the page's executor keeps (its shadow, color buffers, surfaces and
// the GPU's contents read back) packed into what v86's snapshots hold: a
// JSON string and the typed arrays beside it ([json, buffers]).
//
// The packing keeps Maps, Sets, typed arrays, undefined and the numbers JSON
// has no words for, and objects reached twice (a share group of several
// contexts) once; instances of the classes named in `classes` come back
// with their prototypes. A function, or an instance of a class not named
// (a GPU object), is left out, as is a key `skip` refuses.
//
// The shadow's compiled shaders and linked programs are not kept: their
// sources are (compiled_source, link: gles_shadow.js), compiled and linked
// again at the restore, which gives the same answers.

import { compile_shader, link_program } from "./glsl_es.js";

const TYPED = { Uint8Array, Int8Array, Uint8ClampedArray, Uint16Array, Int16Array, Uint32Array, Int32Array, Float32Array, Float64Array };

/**
 * @param {*} value
 * @param {{classes: (!Object<string, !Object>|undefined), skip: (function(string, !Object): boolean|undefined)}=} options
 *     classes: tags and the prototypes of their instances; skip(key, owner)
 *     whether an object's key is left out
 * @return {!Array<*>} [json, buffers]
 */
export function pack(value, options = {})
{
    const classes = new Map(Object.entries(options.classes || {}).map(([tag, prototype]) => [prototype, tag]));
    const skip = options.skip || (() => false);
    /** @type {!Array<!Uint8Array>} */
    const buffers = [];
    const seen = new Map();
    const walk = v =>
    {
        if(v === undefined) return { $u: 1 };
        if(typeof v === "number") return Number.isFinite(v) && !Object.is(v, -0) ? v : { $n: Object.is(v, -0) ? "-0" : String(v) };
        if(typeof v === "bigint") return { $g: v.toString() };
        if(typeof v === "function" || typeof v === "symbol") return { $u: 1 };
        if(v === null || typeof v !== "object") return v;
        if(ArrayBuffer.isView(v))
        {
            const name = Object.keys(TYPED).find(n => v instanceof TYPED[n]);
            if(!name) return { $u: 1 };
            buffers.push(new Uint8Array(v.buffer.slice(v.byteOffset, v.byteOffset + v.byteLength)));
            return { $t: name, $b: buffers.length - 1 };
        }
        if(v instanceof ArrayBuffer)
        {
            buffers.push(new Uint8Array(v.slice(0)));
            return { $t: "ArrayBuffer", $b: buffers.length - 1 };
        }
        if(seen.has(v)) return { $r: seen.get(v) };
        const prototype = Object.getPrototypeOf(v);
        const tag = classes.get(prototype);
        if(prototype !== Object.prototype && prototype !== null && !tag && !Array.isArray(v) && !(v instanceof Map) && !(v instanceof Set))
        {
            return { $u: 1 };
        }
        const id = seen.size;
        seen.set(v, id);
        if(Array.isArray(v)) return { $i: id, $a: v.map(walk) };
        if(v instanceof Map) return { $i: id, $m: [...v].map(([k, x]) => [walk(k), walk(x)]) };
        if(v instanceof Set) return { $i: id, $s: [...v].map(walk) };
        const fields = {};
        for(const key of Object.keys(v)) if(!skip(key, v)) fields[key] = walk(v[key]);
        return tag ? { $i: id, $o: fields, $c: tag } : { $i: id, $o: fields };
    };
    return [JSON.stringify(walk(value)), buffers];
}

/**
 * @param {!Array<*>} packed [json, buffers] (pack's)
 * @param {!Object<string, !Object>=} classes the same tags' prototypes
 * @return {*}
 */
export function unpack(packed, classes = {})
{
    const [json, buffers] = packed;
    const objects = new Map();
    const walk = v =>
    {
        if(v === null || typeof v !== "object") return v;
        if("$u" in v) return undefined;
        if("$n" in v) return v.$n === "-0" ? -0 : Number(v.$n);
        if("$g" in v) return BigInt(v.$g);
        if("$t" in v)
        {
            const bytes = buffers[v.$b];
            const copy = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
            return v.$t === "ArrayBuffer" ? copy : new TYPED[v.$t](copy);
        }
        if("$r" in v) return objects.get(v.$r);
        if("$a" in v)
        {
            const array = [];
            objects.set(v.$i, array);
            for(const x of v.$a) array.push(walk(x));
            return array;
        }
        if("$m" in v)
        {
            const map = new Map();
            objects.set(v.$i, map);
            for(const [k, x] of v.$m) map.set(walk(k), walk(x));
            return map;
        }
        if("$s" in v)
        {
            const set = new Set();
            objects.set(v.$i, set);
            for(const x of v.$s) set.add(walk(x));
            return set;
        }
        const object = Object.create(v.$c ? classes[v.$c] : Object.prototype);
        objects.set(v.$i, object);
        for(const [key, x] of Object.entries(v.$o)) object[key] = walk(x);
        return object;
    };
    return walk(JSON.parse(json));
}

/**
 * What of a shadow's objects a snapshot leaves out: the GPU's part (the
 * page's), the compiled shaders and linked programs (compiled again)
 * @param {string} key
 * @param {!Object} owner
 * @return {boolean}
 */
export function shadow_skip(key, owner)
{
    // (a program glslang linked keeps its result where nothing can link it
    // again: on the page; the CPU side links it again, as the rest)
    return key === "gpu" || owner.kind === "shader" && key === "compiled" ||
        owner.kind === "program" && key === "info" && !(owner.link && owner.link.glslang && owner.keep_info);
}

/**
 * The shaders compiled and the programs linked again from their sources
 * (after unpack)
 * @param {!Map<*, {objects: !Map<number, !Object>}>} groups the shadow's share groups
 */
export function relink(groups, shadow)
{
    const cache = new Map();
    const compiled = (source, stage) =>
    {
        const key = stage + "\n" + source;
        if(!cache.has(key)) cache.set(key, compile_shader(source, stage));
        return cache.get(key);
    };
    for(const group of groups.values())
    {
        for(const object of group.objects.values())
        {
            if(object.kind === "shader")
            {
                object.compiled = object.compiled_source === null || object.compiled_source === undefined ? null :
                    shadow ? shadow.compile(object.compiled_source, object.type, !!group.glslang, !!group.es2) :
                    compiled(object.compiled_source, object.type === 0x8B31 ? "vertex" : "fragment");
            }
            else if(object.kind === "program" && object.link && object.link.glslang)
            {
                // (glslang's: linked again on the CPU side as it was linked, not as the program is now; the page kept its result)
                if(object.info) continue;
                const link = object.link;
                const shaders = link.shaders.map(([type, source]) => ({ type, compiled_source: source,
                    compiled: shadow.compile(source, type, true, !!group.es2) }));
                object.info = shadow.link({ bindings: link.bindings, separable: !!link.separable, tf_request: link.tf || null }, shaders, !!group.es2);
            }
            else if(object.kind === "program")
            {
                const link = object.link;
                object.info = link ? link_program(link.vs === null ? null : compiled(link.vs, "vertex"),
                    link.fs === null ? null : compiled(link.fs, "fragment"), new Map(link.bindings)) : null;
            }
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/gles/gles_stream.js                                                                  0000644 0000000 0000000 00000023056 00000000000 014256  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // One connection to the GLES host (docs/gles-proxy-plan.md "协议与生成器",
// E1): the guest's bytes as they come (a pipe's writes, split anywhere),
// a u32 of client flags first (gfxstream's host/RenderThread.cpp reads it
// and drops it), then commands, each an opcode and a total size (u32 each,
// the 8 bytes included) and its parameters. A whole command goes to the
// decoder of its opcode's range (renderControl's, GLESv1's, GLESv2's:
// src/gles/gles_protocol.js), whose reply joins the bytes the guest reads.
//
// A decoder may answer later (a promise: data the page has to give back,
// E2): the stream decodes nothing after that command until the answer is
// there, so the replies keep the commands' order. An opcode of no range
// is counted and skipped (its size is in its header); so is a command whose
// parameters do not fill it (a layout the guest's encoder disagrees with).
// A size below 8 or above MAX_COMMAND breaks the stream: nothing after it
// can be found, the rest of the connection is dropped and counted.

import { command_of_opcode, decode_arguments, encode_reply, has_reply } from "./gles_wire.js";

/** The largest command: a 4096 by 4096 RGBA texture, with room */
export const MAX_COMMAND = 80 << 20;

/**
 * @constructor
 * @param {function(!Object, !Array<*>, !Uint8Array): *} decode the
 *     decoders: a command ({api, opcode, name, ...}: gles_wire.js), its
 *     arguments (out pointers to fill) and its bytes to the return value, or
 *     a promise of it
 * @param {function()=} readable called when a reply that waited is there
 */
export function GLESStream(decode, readable)
{
    this.decode = decode;
    this.readable = readable || (() => {});
    /** the client flags (null until the guest wrote them) */
    this.flags = null;
    this.header = new Uint8Array(8);
    this.header_fill = 0;
    /** @type {?Uint8Array} the command being put together */
    this.command = null;
    this.command_fill = 0;
    /** @type {!Array<!Uint8Array>} what the guest wrote while a reply waited */
    this.backlog = [];
    this.waiting = false;
    /** @type {!Array<!Uint8Array>} the replies the guest has not read */
    this.output = [];
    this.output_bytes = 0;
    this.broken = false;
    this.closed = false;
    /** @type {!Map<string, number>} commands decoded, by name */
    this.counts = new Map();
    /** @type {!Map<number, number>} opcodes of no range, and how often */
    this.unknown = new Map();
    /** @type {!Map<string, number>} commands whose parameters did not fill them */
    this.malformed = new Map();
    /** @type {!Map<string, number>} commands whose decoder failed (answered with zeros) */
    this.failed = new Map();
    this.dropped_bytes = 0;
}

/** @param {!Uint8Array} bytes the guest's (copied where kept) */
GLESStream.prototype.write = function(bytes)
{
    if(this.closed) return;
    if(this.broken)
    {
        this.dropped_bytes += bytes.length;
        return;
    }
    if(this.waiting)
    {
        this.backlog.push(bytes.slice());
        return;
    }
    let at = 0;
    while(at < bytes.length && !this.waiting && !this.broken)
    {
        if(!this.command)
        {
            // the flags word, then a command's header
            const want = this.flags === null ? 4 : 8;
            const n = Math.min(want - this.header_fill, bytes.length - at);
            this.header.set(bytes.subarray(at, at + n), this.header_fill);
            this.header_fill += n;
            at += n;
            if(this.header_fill < want) break;
            this.header_fill = 0;
            const view = new DataView(this.header.buffer);
            if(this.flags === null)
            {
                this.flags = view.getUint32(0, true);
                continue;
            }
            const size = view.getUint32(4, true);
            if(size < 8 || size > MAX_COMMAND)
            {
                this.broken = true;
                this.dropped_bytes += bytes.length - at;
                console.warn(`GLES stream: a command of ${size} bytes (opcode ${view.getUint32(0, true)}): the rest of the connection is dropped`);
                break;
            }
            this.command = new Uint8Array(size);
            this.command.set(this.header);
            this.command_fill = 8;
        }
        const n = Math.min(this.command.length - this.command_fill, bytes.length - at);
        this.command.set(bytes.subarray(at, at + n), this.command_fill);
        this.command_fill += n;
        at += n;
        if(this.command_fill === this.command.length)
        {
            const command = this.command;
            this.command = null;
            this.dispatch(command);
        }
    }
    if(at < bytes.length && this.waiting) this.backlog.push(bytes.slice(at));
};

/** @param {!Uint8Array} bytes a whole command */
GLESStream.prototype.dispatch = function(bytes)
{
    const opcode = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
    const command = command_of_opcode(opcode >>> 0);
    if(!command)
    {
        this.unknown.set(opcode >>> 0, (this.unknown.get(opcode >>> 0) || 0) + 1);
        return;
    }
    this.counts.set(command.name, (this.counts.get(command.name) || 0) + 1);
    let args;
    try
    {
        args = decode_arguments(command, bytes);
    }
    catch(e)
    {
        if(!this.malformed.has(command.name)) console.warn("GLES stream: " + e.message);
        this.malformed.set(command.name, (this.malformed.get(command.name) || 0) + 1);
        return;
    }
    // (a fault of a decoder: the call is answered with zeros, counted, the stream goes on)
    let ret;
    try
    {
        ret = this.decode(command, args, bytes);
    }
    catch(e)
    {
        if(!this.failed.has(command.name)) console.warn("GLES stream: " + command.name + " failed: " + (e && e.stack || e));
        this.failed.set(command.name, (this.failed.get(command.name) || 0) + 1);
        ret = 0;
    }
    if(ret && typeof ret.then === "function")
    {
        this.waiting = true;
        ret.then(value =>
        {
            if(this.closed) return;
            this.reply(command, args, value);
            this.waiting = false;
            const backlog = this.backlog;
            this.backlog = [];
            for(const chunk of backlog) this.write(chunk);
            this.readable();
        });
        return;
    }
    this.reply(command, args, ret);
};

GLESStream.prototype.reply = function(command, args, ret)
{
    if(!has_reply(command)) return;
    const reply = encode_reply(command, args, ret);
    if(!reply) return;
    this.output.push(reply);
    this.output_bytes += reply.length;
};

/**
 * The replies' bytes the guest reads next, at most `max`
 * @param {number} max
 * @return {?Uint8Array} null when there are none
 */
GLESStream.prototype.read = function(max)
{
    if(!this.output_bytes || max <= 0) return null;
    const first = this.output[0];
    if(first.length <= max && (this.output.length === 1 || first.length === max))
    {
        this.output.shift();
        this.output_bytes -= first.length;
        return first;
    }
    const n = Math.min(max, this.output_bytes);
    const bytes = new Uint8Array(n);
    let at = 0;
    while(at < n)
    {
        const chunk = this.output[0];
        const take = Math.min(chunk.length, n - at);
        bytes.set(chunk.subarray(0, take), at);
        at += take;
        if(take === chunk.length) this.output.shift();
        else this.output[0] = chunk.subarray(take);
    }
    this.output_bytes -= n;
    return bytes;
};

/** The guest closed the connection: what waited is dropped */
GLESStream.prototype.close = function()
{
    this.closed = true;
    this.backlog = [];
    this.output = [];
    this.output_bytes = 0;
};

/**
 * What a snapshot keeps (gles_snapshot.js's packing): the bytes of a
 * header or command not whole yet, the replies not read; nothing may wait
 * (the GLES host's prepare_save answered every call first)
 * @return {!Object}
 */
GLESStream.prototype.get_state = function()
{
    const output = new Uint8Array(this.output_bytes);
    let at = 0;
    for(const chunk of this.output) { output.set(chunk, at); at += chunk.length; }
    return {
        flags: this.flags, header: this.header.slice(), header_fill: this.header_fill,
        command: this.command && this.command.slice(0, this.command_fill), command_size: this.command ? this.command.length : 0,
        output, broken: this.broken, dropped_bytes: this.dropped_bytes,
        counts: this.counts, unknown: this.unknown, malformed: this.malformed, failed: this.failed, waiting: this.waiting || this.backlog.length > 0,
    };
};

/** @param {!Object} state get_state's */
GLESStream.prototype.set_state = function(state)
{
    this.flags = state.flags;
    this.header.set(state.header);
    this.header_fill = state.header_fill;
    this.command = null;
    this.command_fill = 0;
    if(state.command_size)
    {
        this.command = new Uint8Array(state.command_size);
        this.command.set(state.command);
        this.command_fill = state.command.length;
    }
    this.output = state.output.length ? [state.output] : [];
    this.output_bytes = state.output.length;
    this.broken = state.broken;
    this.dropped_bytes = state.dropped_bytes;
    this.counts = state.counts;
    this.unknown = state.unknown;
    this.malformed = state.malformed;
    this.failed = state.failed || new Map();
    // (a call that waited when the snapshot was taken has no answer: the
    // connection cannot go on, as one whose commands could not be found)
    if(state.waiting)
    {
        this.broken = true;
        console.warn("GLES stream: the snapshot was taken while a call waited for the page: the connection is dropped");
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/gles/gles_wire.js                                                                    0000644 0000000 0000000 00000024211 00000000000 013723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The emugl GLES wire format by the generated layouts (src/gles/gles_protocol.js,
// docs/gles-proxy-plan.md "协议与生成器"): a command's arguments taken out of
// its bytes, its reply put together, and (for tests, and the guest library's
// shape in JS) a command encoded. Values are little-endian; an in or inout
// pointer is its length (u32) and its bytes, an out pointer its length only,
// a DMA pointer an 8-byte guest physical address; the reply is the out and
// inout pointers' bytes in order, then the return value.

import { GLES_APIS } from "./gles_protocol.js";

/** The bytes of each value kind */
export const KIND_BYTES = { "void": 0, "u8": 1, "i16": 2, "u16": 2, "i32": 4, "u32": 4, "f32": 4, "u64": 8, "i64": 8 };

/**
 * A command's description: its API, opcode, name, return kind, parameters, flags
 * @typedef {{api: string, opcode: number, name: string, ret: string, params: !Array<!Array>, flags: !Array<string>}}
 */
export let GLESCommand;

/** @type {!Map<number, !GLESCommand>} */
const BY_OPCODE = new Map();
/** @type {!Map<string, !GLESCommand>} */
const BY_NAME = new Map();
/** @type {!Array<{api: string, first: number, last: number}>} */
export const GLES_RANGES = [];

for(const [api, { base, commands }] of Object.entries(GLES_APIS))
{
    commands.forEach(([name, ret, params, flags], i) =>
    {
        const command = { api, opcode: base + i, name, ret, params, flags: flags || [] };
        BY_OPCODE.set(base + i, command);
        // (GLESv1 and GLESv2 share names: the API's own first, under "api:name" too)
        BY_NAME.set(api + ":" + name, command);
        if(!BY_NAME.has(name)) BY_NAME.set(name, command);
    });
    GLES_RANGES.push({ api, first: base, last: base + commands.length - 1 });
}

/** @param {number} opcode @return {?GLESCommand} */
export function command_of_opcode(opcode) { return BY_OPCODE.get(opcode) || null; }

/** @param {string} name "rcFBPost", "gles2:glDrawArrays" @return {?GLESCommand} */
export function command_of_name(name) { return BY_NAME.get(name) || null; }

/**
 * An out (or inout) pointer's place in the reply: the handler fills data
 * (zeros if it does not)
 * @constructor
 * @param {number} size
 * @param {?Uint8Array} input an inout pointer's bytes
 */
export function OutBuffer(size, input)
{
    this.size = size;
    this.data = new Uint8Array(size);
    if(input) this.data.set(input.subarray(0, size));
    this.view = new DataView(this.data.buffer);
}

/**
 * @param {!DataView} view
 * @param {number} at
 * @param {string} kind
 * @return {number}
 */
function read_value(view, at, kind)
{
    switch(kind)
    {
        case "u8": return view.getUint8(at);
        case "i16": return view.getInt16(at, true);
        case "u16": return view.getUint16(at, true);
        case "i32": return view.getInt32(at, true);
        case "u32": return view.getUint32(at, true);
        case "f32": return view.getFloat32(at, true);
        case "u64": return view.getUint32(at, true) + view.getUint32(at + 4, true) * 0x100000000;
        case "i64": return view.getUint32(at, true) + view.getInt32(at + 4, true) * 0x100000000;
    }
    return 0;
}

/**
 * @param {!DataView} view
 * @param {number} at
 * @param {string} kind
 * @param {number|boolean} value
 */
function write_value(view, at, kind, value)
{
    const v = +value;
    switch(kind)
    {
        case "u8": view.setUint8(at, v); break;
        case "i16": view.setInt16(at, v, true); break;
        case "u16": view.setUint16(at, v, true); break;
        case "i32": view.setInt32(at, v, true); break;
        case "u32": view.setUint32(at, v >>> 0, true); break;
        case "f32": view.setFloat32(at, v, true); break;
        case "u64":
        case "i64":
            view.setUint32(at, v >>> 0, true);
            view.setUint32(at + 4, Math.floor(v / 0x100000000) >>> 0, true);
            break;
    }
}

/**
 * A command's arguments, from its bytes (header included): values as
 * numbers; an in pointer as its bytes (null for a NULL one: length 0 and
 * nullAllowed), an out or inout pointer as an OutBuffer, a DMA pointer as
 * {dma: address}. Throws when the parameters do not fill the command
 * exactly (a layout that disagrees with the guest's encoder)
 * @param {!GLESCommand} command
 * @param {!Uint8Array} bytes
 * @return {!Array<*>}
 */
export function decode_arguments(command, bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const args = [];
    let at = 8;
    for(const [name, kind, dir, flags] of command.params)
    {
        if(kind !== "ptr")
        {
            const n = KIND_BYTES[kind];
            if(at + n > bytes.length) throw new Error(`${command.name}: ${name} is beyond the command's ${bytes.length} bytes`);
            args.push(read_value(view, at, kind));
            at += n;
            continue;
        }
        if(flags && flags.includes("DMA"))
        {
            if(at + 8 > bytes.length) throw new Error(`${command.name}: ${name} is beyond the command's ${bytes.length} bytes`);
            args.push({ dma: read_value(view, at, "u64") });
            at += 8;
            continue;
        }
        if(at + 4 > bytes.length) throw new Error(`${command.name}: ${name}'s length is beyond the command's ${bytes.length} bytes`);
        const size = view.getUint32(at, true);
        at += 4;
        if(dir === "out")
        {
            args.push(new OutBuffer(size, null));
            continue;
        }
        if(at + size > bytes.length) throw new Error(`${command.name}: ${name}'s ${size} bytes are beyond the command's ${bytes.length}`);
        const data = bytes.subarray(at, at + size);
        at += size;
        if(dir === "inout") args.push(new OutBuffer(size, data));
        else args.push(size === 0 && flags && flags.includes("nullAllowed") ? null : data);
    }
    if(at !== bytes.length) throw new Error(`${command.name}: the parameters take ${at} bytes, the command has ${bytes.length}`);
    return args;
}

/**
 * The reply to a command: its out and inout pointers' bytes, then its return value
 * @param {!GLESCommand} command
 * @param {!Array<*>} args decode_arguments's (the handler filled the OutBuffers)
 * @param {number|boolean|undefined} ret
 * @return {?Uint8Array} null when the command has no reply
 */
export function encode_reply(command, args, ret)
{
    let size = KIND_BYTES[command.ret];
    command.params.forEach(([, kind, dir, flags], i) =>
    {
        if(kind === "ptr" && (dir === "out" || dir === "inout") && !(flags && flags.includes("DMA"))) size += args[i].size;
    });
    if(!size) return null;
    const reply = new Uint8Array(size), view = new DataView(reply.buffer);
    let at = 0;
    command.params.forEach(([, kind, dir, flags], i) =>
    {
        if(kind === "ptr" && (dir === "out" || dir === "inout") && !(flags && flags.includes("DMA")))
        {
            reply.set(args[i].data, at);
            at += args[i].size;
        }
    });
    if(command.ret !== "void") write_value(view, at, command.ret, ret === undefined ? 0 : ret);
    return reply;
}

/**
 * Whether a command is answered (the guest waits for the reply)
 * @param {!GLESCommand} command
 * @return {boolean}
 */
export function has_reply(command)
{
    return command.ret !== "void" || command.params.some(([, kind, dir, flags]) =>
        kind === "ptr" && (dir === "out" || dir === "inout") && !(flags && flags.includes("DMA")));
}

/**
 * A command encoded as the guest's encoder would: values as numbers, an in
 * or inout pointer as its bytes (null: a NULL pointer, length 0), an out
 * pointer as its length, a DMA pointer as its address
 * @param {string} name
 * @param {!Array<*>} args
 * @return {!Uint8Array}
 */
export function encode_command(name, args)
{
    const command = command_of_name(name);
    if(!command) throw new Error("no GLES command " + name);
    if(args.length !== command.params.length) throw new Error(`${name} takes ${command.params.length} arguments, got ${args.length}`);
    let size = 8;
    command.params.forEach(([, kind, dir, flags], i) =>
    {
        if(kind !== "ptr") size += KIND_BYTES[kind];
        else if(flags && flags.includes("DMA")) size += 8;
        else size += 4 + (dir === "out" ? 0 : args[i] ? args[i].length : 0);
    });
    const bytes = new Uint8Array(size), view = new DataView(bytes.buffer);
    view.setUint32(0, command.opcode, true);
    view.setUint32(4, size, true);
    let at = 8;
    command.params.forEach(([, kind, dir, flags], i) =>
    {
        const value = /** @type {number} */ (args[i]);
        if(kind !== "ptr")
        {
            write_value(view, at, kind, value);
            at += KIND_BYTES[kind];
        }
        else if(flags && flags.includes("DMA"))
        {
            write_value(view, at, "u64", value);
            at += 8;
        }
        else if(dir === "out")
        {
            view.setUint32(at, value >>> 0, true);
            at += 4;
        }
        else
        {
            const data = /** @type {?Uint8Array} */ (args[i]) || new Uint8Array(0);
            view.setUint32(at, data.length, true);
            bytes.set(data, at + 4);
            at += 4 + data.length;
        }
    });
    return bytes;
}

/**
 * A reply read as the guest's encoder reads it: the out and inout pointers'
 * bytes (by their lengths in the command) and the return value
 * @param {string} name
 * @param {!Array<*>} args the command's (out pointers' lengths)
 * @param {!Uint8Array} reply
 * @return {{outs: !Array<!Uint8Array>, ret: number}}
 */
export function decode_reply(name, args, reply)
{
    const command = command_of_name(name);
    const view = new DataView(reply.buffer, reply.byteOffset, reply.byteLength);
    const outs = [];
    let at = 0;
    command.params.forEach(([, kind, dir, flags], i) =>
    {
        if(kind === "ptr" && (dir === "out" || dir === "inout") && !(flags && flags.includes("DMA")))
        {
            const n = dir === "out" ? args[i] : args[i].length;
            outs.push(reply.subarray(at, at + n));
            at += n;
        }
    });
    const ret = command.ret === "void" ? 0 : read_value(view, at, command.ret);
    if(at + KIND_BYTES[command.ret] !== reply.length) throw new Error(`${name}: a reply of ${reply.length} bytes, expected ${at + KIND_BYTES[command.ret]}`);
    return { outs, ret };
}
                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/gles/glsl_es.js                                                                      0000644 0000000 0000000 00000011510 00000000000 013371  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLSL ES 1.00 on the CPU side (docs/gles-proxy-plan.md "影子状态"): the
// shadow state answers glGetShaderiv, glGetProgramiv, the info logs,
// glGetActiveUniform/Attrib and glGetUniform/AttribLocation itself, so it
// compiles and links with gl-webgpu's front end (gl_shader_translator.js,
// its ES mode) and turns the link's reflection into GL's view of the
// program: the active attributes and uniforms with their GL names, sizes and
// types, and every name glGetUniformLocation takes. The page's executor
// links the same sources with the same bindings, so the locations agree.

import "../browser/glbridge/gl-webgpu/gl_state_layout.js";
import "../browser/glbridge/gl-webgpu/gl_shader_translator.js";
import { GLSL_TYPES, sampler_type } from "./gles_formats.js";

/** @return {!Object} gl-webgpu's front end (set by the scripts above) */
function translator()
{
    return globalThis["GLShaderTranslator"];
}

/**
 * A shader compiled: whether it compiled, its log, and what linking needs
 * @param {string} source
 * @param {string} stage "vertex" or "fragment"
 * @return {{ok: boolean, log: string, result: !Object}}
 */
export function compile_shader(source, stage)
{
    // (a fault of the front end itself is the shader's error, never the machine's)
    let result;
    try
    {
        result = translator().compileShader(source, stage, { es: true });
    }
    catch(e)
    {
        return { ok: false, log: "ERROR: internal compiler error: " + (e && e.message || e), result: null };
    }
    return { ok: result.ok, log: result.log, result };
}

/**
 * An active uniform as GL lists it
 * @typedef {{name: string, size: number, type: number, location: number, components: number,
 *     base: string, sampler: boolean, int: boolean, bool: boolean, columns: number}}
 */
export let ActiveUniform;

/**
 * A program linked: GL's view of it
 * @typedef {{ok: boolean, log: string, attributes: !Array<{name: string, size: number, type: number, location: number}>,
 *     uniforms: !Array<!ActiveUniform>, locations: !Map<string, number>,
 *     by_location: !Array<{uniform: !ActiveUniform, element: number}>, reflection: ?Object,
 *     wgsl: ({vertex: string, fragment: string}|undefined)}}
 *     wgsl: the generated shaders, which the page's executor draws with
 */
export let ProgramInfo;

/**
 * Link two compiled shaders with the attribute bindings in force
 * @param {?Object} vs compile_shader's result
 * @param {?Object} fs
 * @param {!Map<string, number>} bindings glBindAttribLocation's
 * @return {!ProgramInfo}
 */
export function link_program(vs, fs, bindings)
{
    const empty = log => ({ ok: false, log, attributes: [], uniforms: [], locations: new Map(), by_location: [], reflection: null });
    if(!vs || !fs) return empty("ERROR: a program needs a vertex and a fragment shader");
    if(!vs.ok || !fs.ok) return empty("ERROR: " + (!vs.ok ? "the vertex" : "the fragment") + " shader is not compiled");
    let linked;
    try
    {
        linked = translator().linkProgram(vs.result, fs.result, { es: true, bindAttribLocations: bindings });
    }
    catch(e)
    {
        return empty("ERROR: internal linker error: " + (e && e.message || e));
    }
    if(!linked.ok) return empty(linked.log);
    const reflection = linked.reflection;
    const attributes = reflection.attributes.map(a => ({ name: a.name, size: 1, type: GLSL_TYPES[a.glslType], location: a.location }));
    /** @type {!Array<!ActiveUniform>} */
    const uniforms = [];
    for(const u of reflection.uniforms)
    {
        const size = Math.max(1, u.arraySize);
        uniforms.push({
            name: u.arraySize ? u.name + "[0]" : u.name, base: u.name, size, type: GLSL_TYPES[u.glslType], location: u.location,
            components: u.components, sampler: false, int: u.baseType === "int", bool: u.baseType === "bool", columns: u.columns,
        });
    }
    for(const s of reflection.samplers)
    {
        const size = Math.max(1, s.arraySize);
        uniforms.push({
            name: s.arraySize ? s.name + "[0]" : s.name, base: s.name, size, type: sampler_type(s.dim, s.external), location: s.location,
            components: 1, sampler: true, int: true, bool: false, columns: 0,
        });
    }
    // the names glGetUniformLocation takes: "a", "a[0]", ... "a[n-1]" for
    // an array, the name for anything else; and what each location is
    const locations = new Map();
    const by_location = [];
    for(const u of uniforms)
    {
        locations.set(u.base, u.location);
        for(let i = 0; i < u.size; i++)
        {
            if(u.size > 1 || u.name !== u.base) locations.set(u.base + "[" + i + "]", u.location + i);
            by_location[u.location + i] = { uniform: u, element: i };
        }
    }
    return { ok: true, log: linked.log, attributes, uniforms, locations, by_location, reflection,
        wgsl: { vertex: linked.wgslVertex, fragment: linked.wgslFragment } };
}
                                                                                                                                                                                        source/v64/src/gles/glsl_es_rewrite.js                                                              0000644 0000000 0000000 00000100766 00000000000 015146  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A shader's source as glslang's SPIR-V pass takes it (docs/gles3-plan.md,
// "着色器的数据流"): the check pass has already judged the source at its own
// version, so this only rewrites what Vulkan's relaxed rules read
// differently, token by token (comments and line breaks kept):
// - GLSL ES 1.00 becomes 3.00 es: attribute and varying, gl_FragColor and
//   gl_FragData as outputs, the 1.00 texture functions and their extensions'
//   (texture2D, texture2DLodEXT, shadow2DEXT, ...) as texture(),
//   textureLod(), ...; gl_FragDepthEXT as gl_FragDepth; samplerExternalOES
//   as sampler2D (the host's external images are 2D textures);
//   gl_MaxVaryingVectors, which 3.00 lacks, as its number; the #extension
//   lines go (what they enabled is 3.00's own);
// - at any version samplerExternalOES is sampler2D and its extensions'
//   #extension lines go;
// - user names that are keywords or built-in functions there (3.00's to a
//   1.00 shader; Vulkan GLSL's separate texture and sampler types to any)
//   get a suffix: `renames` maps the new names back to GL's;
// - a 1.00 shader's overloads of built-in functions (1.00 has them, 3.00
//   refuses them): the uses of the name with as many arguments as one of
//   the user's and none of the built-in's get a suffix (those of the same
//   count as a built-in's stay: 3.00 refuses the shader);
// - a fragment shader's gl_SamplePosition and interpolateAtCentroid,
//   interpolateAtSample and interpolateAtOffset (GLSL ES 3.20's, OES_sample_variables'
//   and OES_shader_multisample_interpolation's), which naga cannot read:
//   functions of gl_SampleID, the samples' standard positions (the sample
//   count specialization constant 71, the page's: 4, or 1 with a position of
//   0.5) and derivatives (an offset's value as the interpolant's plane at
//   the fragment's center gives it);
// - a fragment shader's gl_HelperInvocation (GLSL ES 3.20's), which naga
//   cannot read: false (a helper invocation writes nothing; what differs is
//   a derivative of a value that depends on it);
// - a fragment shader that declares advanced blend equations' support
//   (layout(blend_support_*) out;, GLES 3.2's KHR_blend_equation_advanced):
//   its color output a variable, blended in the shader with the draw's
//   destination (the sampler _v86_dst, a copy the page makes) by the
//   equation of specialization constant 72, the page's; the page's
//   pipeline does not blend.

/** 1.00's texture functions (and extensions') as 3.00's */
const TEXTURE_FUNCTIONS = new Map([
    ["texture2D", "texture"], ["texture2DProj", "textureProj"], ["texture2DLod", "textureLod"],
    ["texture2DProjLod", "textureProjLod"], ["textureCube", "texture"], ["textureCubeLod", "textureLod"],
    ["texture2DLodEXT", "textureLod"], ["texture2DProjLodEXT", "textureProjLod"], ["textureCubeLodEXT", "textureLod"],
    ["texture2DGradEXT", "textureGrad"], ["texture2DProjGradEXT", "textureProjGrad"], ["textureCubeGradEXT", "textureGrad"],
    ["shadow2DEXT", "texture"], ["shadow2DProjEXT", "textureProj"],
    ["texture3D", "texture"], ["texture3DProj", "textureProj"], ["texture3DLod", "textureLod"], ["texture3DProjLod", "textureProjLod"],
]);

/** Names 3.00 has and 1.00 does not: in a 1.00 shader they are the user's (1.00's in, out and inout qualify parameters) */
const ES300_NAMES = new Set((
    "flat smooth centroid layout uint uvec2 uvec3 uvec4 switch case default " +
    "mat2x2 mat2x3 mat2x4 mat3x2 mat3x3 mat3x4 mat4x2 mat4x3 mat4x4 " +
    "sampler3D samplerCubeShadow sampler2DArray sampler2DArrayShadow isampler2D isampler3D isamplerCube " +
    "isampler2DArray usampler2D usampler3D usamplerCube usampler2DArray " +
    "sinh cosh tanh asinh acosh atanh trunc round roundEven isnan isinf floatBitsToInt floatBitsToUint " +
    "intBitsToFloat uintBitsToFloat packSnorm2x16 unpackSnorm2x16 packUnorm2x16 unpackUnorm2x16 " +
    "packHalf2x16 unpackHalf2x16 outerProduct transpose determinant inverse " +
    "texture textureProj textureLod textureOffset texelFetch texelFetchOffset textureProjOffset " +
    "textureLodOffset textureProjLod textureProjLodOffset textureGrad textureGradOffset textureProjGrad " +
    "textureProjGradOffset textureSize"
).split(" "));

/** Vulkan GLSL's keywords that OpenGL ES's GLSL leaves to the user */
const VULKAN_NAMES = new Set((
    "texture1D texture2D texture3D textureCube texture2DRect texture1DArray texture2DArray textureBuffer " +
    "texture2DMS texture2DMSArray textureCubeArray itexture1D itexture2D itexture3D itextureCube itexture2DRect " +
    "itexture1DArray itexture2DArray itextureBuffer itexture2DMS itexture2DMSArray itextureCubeArray " +
    "utexture1D utexture2D utexture3D utextureCube utexture2DRect utexture1DArray utexture2DArray utextureBuffer " +
    "utexture2DMS utexture2DMSArray utextureCubeArray sampler samplerShadow subpassInput subpassInputMS " +
    "isubpassInput isubpassInputMS usubpassInput usubpassInputMS attachmentEXT iattachmentEXT uattachmentEXT"
).split(" "));

const SUFFIX = "_v86";

/** The specialization constant of the draw's sample count (gles3_executor.js's pipeline3) */
export const SAMPLES_CONSTANT = 71;
/** The specialization constant of the draw's advanced blend equation (its index in ADVANCED_BLEND), and its destination's sampler */
export const BLEND_CONSTANT = 72;
export const BLEND_DESTINATION = "_v86_dst";
/** KHR_blend_equation_advanced's equations: the enums, the layout qualifiers' names */
export const ADVANCED_BLEND = [[0x9294, "multiply"], [0x9295, "screen"], [0x9296, "overlay"], [0x9297, "darken"], [0x9298, "lighten"],
    [0x9299, "colordodge"], [0x929A, "colorburn"], [0x929B, "hardlight"], [0x929C, "softlight"], [0x929E, "difference"], [0x92A0, "exclusion"],
    [0x92AD, "hsl_hue"], [0x92AE, "hsl_saturation"], [0x92AF, "hsl_color"], [0x92B0, "hsl_luminosity"]];

/** The equations a fragment shader's layout(blend_support_*) out; qualifiers declare (their enums) */
export function blend_support(source)
{
    const equations = new Set();
    for(const m of source.matchAll(/\blayout\s*\(([^)]*)\)\s*out\s*;/g))
    {
        for(const name of m[1].matchAll(/\bblend_support_(\w+)/g))
        {
            for(const [e, n] of ADVANCED_BLEND) if(name[1] === n || name[1] === "all_equations") equations.add(e);
        }
    }
    return [...equations];
}

/** KHR_blend_equation_advanced's equations (its section 3.8.x) in GLSL: f(), the HSL functions, the coverage terms */
const BLEND_FUNCTIONS = `
uniform highp sampler2D ${BLEND_DESTINATION};
layout(constant_id = ${BLEND_CONSTANT}) const int _v86_equation = 0;
highp float _v86_lum(highp vec3 c) { return dot(c, vec3(0.30, 0.59, 0.11)); }
highp vec3 _v86_clip(highp vec3 c) {
    highp float l = _v86_lum(c), n = min(min(c.r, c.g), c.b), x = max(max(c.r, c.g), c.b);
    if (n < 0.0) c = l + ((c - l) * l) / (l - n);
    if (x > 1.0) c = l + ((c - l) * (1.0 - l)) / (x - l);
    return c;
}
highp vec3 _v86_setlum(highp vec3 base, highp vec3 lum) { return _v86_clip(base + (_v86_lum(lum) - _v86_lum(base))); }
highp float _v86_sat(highp vec3 c) { return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }
highp vec3 _v86_setsatlum(highp vec3 base, highp vec3 sat, highp vec3 lum) {
    highp float s = _v86_sat(base);
    highp vec3 c = s > 0.0 ? (base - min(min(base.r, base.g), base.b)) * _v86_sat(sat) / s : vec3(0.0);
    return _v86_setlum(c, lum);
}
highp float _v86_f(int e, highp float s, highp float d) {
    if (e == 0) return s * d;
    if (e == 1) return s + d - s * d;
    if (e == 2) return d <= 0.5 ? 2.0 * s * d : 1.0 - 2.0 * (1.0 - s) * (1.0 - d);
    if (e == 3) return min(s, d);
    if (e == 4) return max(s, d);
    if (e == 5) return d <= 0.0 ? 0.0 : s >= 1.0 ? 1.0 : min(1.0, d / (1.0 - s));
    if (e == 6) return d >= 1.0 ? 1.0 : s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - d) / s);
    if (e == 7) return s <= 0.5 ? 2.0 * s * d : 1.0 - 2.0 * (1.0 - s) * (1.0 - d);
    if (e == 8) return s <= 0.5 ? d - (1.0 - 2.0 * s) * d * (1.0 - d) :
        d <= 0.25 ? d + (2.0 * s - 1.0) * d * ((16.0 * d - 12.0) * d + 3.0) : d + (2.0 * s - 1.0) * (sqrt(d) - d);
    if (e == 9) return abs(d - s);
    return s + d - 2.0 * s * d;
}
highp vec4 _v86_blend(highp vec4 src, highp vec4 dst) {
    int e = _v86_equation;
    src = clamp(src, 0.0, 1.0);
    highp vec3 cs = src.a == 0.0 ? vec3(0.0) : src.rgb / src.a, cd = dst.a == 0.0 ? vec3(0.0) : dst.rgb / dst.a;
    highp vec3 f;
    if (e <= 10) f = vec3(_v86_f(e, cs.r, cd.r), _v86_f(e, cs.g, cd.g), _v86_f(e, cs.b, cd.b));
    else if (e == 11) f = _v86_setsatlum(cs, cd, cd);
    else if (e == 12) f = _v86_setsatlum(cd, cs, cd);
    else if (e == 13) f = _v86_setlum(cs, cd);
    else f = _v86_setlum(cd, cs);
    highp float p0 = src.a * dst.a, p1 = src.a * (1.0 - dst.a), p2 = dst.a * (1.0 - src.a);
    return vec4(f * p0 + cs * p1 + cd * p2, p0 + p1 + p2);
}
`;

/**
 * A blend_support fragment shader's tokens rewritten (see above): the
 * qualifier statements gone, the first output declaration's layout and
 * `out` gone (a variable), main renamed; the text to append, or null when
 * it has no output to blend
 */
function rewrite_blend(tokens)
{
    const significant = tokens.map((t, i) => i).filter(i => !["space", "comment", "newline"].includes(tokens[i].kind));
    let brace = 0, paren = 0, start = 0, output = null;
    for(let k = 0; k < significant.length; k++)
    {
        const t = tokens[significant[k]];
        if(t.text === "{") brace++;
        else if(t.text === "}") { if(--brace === 0) start = k + 1; continue; }
        else if(t.text === "(") paren++;
        else if(t.text === ")") paren--;
        if(brace === 0 && paren === 0 && t.kind === "name" && t.text === "main" && tokens[significant[k + 1]] && tokens[significant[k + 1]].text === "(")
        {
            t.text = "_v86_main";
        }
        if(brace !== 0 || paren !== 0 || t.text !== ";") continue;
        const statement = significant.slice(start, k + 1).map(i => tokens[i]);
        start = k + 1;
        const words = statement.map(x => x.text);
        if(!words.includes("out")) continue;
        if(words.some(w => /^blend_support_/.test(w)))
        {
            for(const x of statement) x.text = "";
            continue;
        }
        if(output) continue;
        // (the output: its layout and out gone; its name the last before ; or [)
        const end = words.indexOf("[") >= 0 ? words.indexOf("[") : words.length - 1;
        output = words[end - 1];
        const layout = words.indexOf("layout");
        if(layout >= 0)
        {
            let depth = 0;
            for(let j = layout; j < statement.length; j++)
            {
                const x = statement[j].text;
                statement[j].text = "";
                if(x === "(") depth++;
                else if(x === ")" && --depth === 0) break;
            }
        }
        statement[words.indexOf("out")].text = "";
    }
    if(!output) return null;
    return BLEND_FUNCTIONS + "layout(location = 0) out highp vec4 _v86_color;\n" +
        `void main() { _v86_main(); _v86_color = _v86_blend(${output}, texelFetch(${BLEND_DESTINATION}, ivec2(gl_FragCoord.xy), 0)); }\n`;
}

const SAMPLE_FUNCTIONS = new Set(["gl_SamplePosition", "interpolateAtCentroid", "interpolateAtSample", "interpolateAtOffset"]);

/**
 * GLSL ES 3.10's extended integer functions, whose SPIR-V (OpIAddCarry,
 * OpISubBorrow, OpUMulExtended, OpSMulExtended) naga does not read: calls
 * to these instead, of plain integer arithmetic (the 32 by 32 bit products
 * from 16-bit halves), for each scalar and vector size
 */
const EXTENDED_FUNCTIONS = new Set(["uaddCarry", "usubBorrow", "umulExtended", "imulExtended"]);

function extended_helpers(uses)
{
    let text = "";
    for(const n of ["", "2", "3", "4"])
    {
        const u = n ? "uvec" + n : "uint", i = n ? "ivec" + n : "int";
        const below = (a, b) => n ? `${u}(lessThan(${a}, ${b}))` : `(${a} < ${b} ? 1u : 0u)`;
        if(uses.has("uaddCarry")) text += `highp ${u} _v86_uaddCarry(highp ${u} a, highp ${u} b, out highp ${u} carry) { highp ${u} s = a + b; carry = ${below("s", "a")}; return s; }\n`;
        if(uses.has("usubBorrow")) text += `highp ${u} _v86_usubBorrow(highp ${u} a, highp ${u} b, out highp ${u} borrow) { borrow = ${below("a", "b")}; return a - b; }\n`;
        if(uses.has("umulExtended") || uses.has("imulExtended"))
        {
            text += `void _v86_umulExtended(highp ${u} x, highp ${u} y, out highp ${u} msb, out highp ${u} lsb) { ` +
                `highp ${u} xl = x & 0xFFFFu, xh = x >> 16u, yl = y & 0xFFFFu, yh = y >> 16u; ` +
                `highp ${u} ll = xl * yl, lh = xl * yh, hl = xh * yl; ` +
                `highp ${u} mid = (ll >> 16u) + (lh & 0xFFFFu) + (hl & 0xFFFFu); ` +
                `msb = xh * yh + (lh >> 16u) + (hl >> 16u) + (mid >> 16u); lsb = x * y; }\n`;
        }
        if(uses.has("imulExtended"))
        {
            // (the signed product's high word: the unsigned one's less each negative operand's other)
            const negative = (a, b) => n ? `${u}(lessThan(${a}, ${i}(0))) * ${u}(${b})` : `(${a} < 0 ? ${u}(${b}) : 0u)`;
            text += `void _v86_imulExtended(highp ${i} x, highp ${i} y, out highp ${i} msb, out highp ${i} lsb) { highp ${u} m, l; ` +
                `_v86_umulExtended(${u}(x), ${u}(y), m, l); m -= ${negative("x", "y")} + ${negative("y", "x")}; msb = ${i}(m); lsb = ${i}(l); }\n`;
        }
    }
    return text;
}

/** The functions that stand in for the sample functions `uses` names */
function sample_helpers(uses)
{
    let text = "";
    if(uses.has("gl_SamplePosition") || uses.has("interpolateAtSample"))
    {
        text += `layout(constant_id = ${SAMPLES_CONSTANT}) const int _v86_samples = 4;\n` +
            // (the constant through a variable: a comparison of it would be an OpSpecConstantOp, which naga cannot read)
            "highp vec2 _v86_sample_offset(int i) { int n = _v86_samples; return n == 1 ? vec2(0.0) : (i == 0 ? vec2(0.375, 0.125) : i == 1 ? vec2(0.875, 0.375) : " +
            "i == 2 ? vec2(0.125, 0.625) : vec2(0.625, 0.875)) - 0.5; }\n";
    }
    if(uses.has("gl_SamplePosition")) text += "highp vec2 _v86_SamplePosition() { return _v86_sample_offset(gl_SampleID) + 0.5; }\n";
    for(const type of ["float", "vec2", "vec3", "vec4"])
    {
        if(uses.has("interpolateAtCentroid")) text += `highp ${type} _v86_interpolateAtCentroid(highp ${type} x) { return x; }\n`;
        if(uses.has("interpolateAtOffset") || uses.has("interpolateAtSample"))
        {
            text += `highp ${type} _v86_interpolateAtOffset(highp ${type} x, highp vec2 o) { return x + dFdx(x) * o.x + dFdy(x) * o.y; }\n`;
        }
        if(uses.has("interpolateAtSample")) text += `highp ${type} _v86_interpolateAtSample(highp ${type} x, int i) { return _v86_interpolateAtOffset(x, _v86_sample_offset(i)); }\n`;
    }
    return text;
}

/** GLSL ES 1.00's built-in functions: their argument counts */
const BUILTINS_100 = new Map(Object.entries({
    radians: [1], degrees: [1], sin: [1], cos: [1], tan: [1], asin: [1], acos: [1], atan: [1, 2], pow: [2], exp: [1], log: [1], exp2: [1],
    log2: [1], sqrt: [1], inversesqrt: [1], abs: [1], sign: [1], floor: [1], ceil: [1], fract: [1], mod: [2], min: [2], max: [2], clamp: [3],
    mix: [3], step: [2], smoothstep: [3], length: [1], distance: [2], dot: [2], cross: [2], normalize: [1], faceforward: [3], reflect: [2],
    refract: [3], matrixCompMult: [2], lessThan: [2], lessThanEqual: [2], greaterThan: [2], greaterThanEqual: [2], equal: [2], notEqual: [2],
    any: [1], all: [1], not: [1], dFdx: [1], dFdy: [1], fwidth: [1],
}));

/**
 * The tokens that name a 1.00 shader's own overloads of built-in functions
 * (a function of a built-in's name declared outside any function), marked
 * `overload`: those followed by an argument list of a count the user's
 * declarations have and the built-in has not
 */
function mark_overloads(tokens)
{
    const significant = tokens.map((t, i) => i).filter(i => !["space", "comment", "newline"].includes(tokens[i].kind));
    // each name followed by "(": its argument count, and whether it is a declaration (at file scope, after its
    // return type: a call in a global's initializer is at file scope too, after an operator, "=", "(" or ",")
    const uses = [];
    let depth = 0;
    for(let k = 0; k < significant.length; k++)
    {
        const t = tokens[significant[k]];
        if(t.text === "{") depth++;
        else if(t.text === "}") depth--;
        if(t.kind !== "name" || !BUILTINS_100.has(t.text) || !tokens[significant[k + 1]] || tokens[significant[k + 1]].text !== "(") continue;
        let level = 0, count = 0, empty = true;
        for(let j = k + 1; j < significant.length; j++)
        {
            const x = tokens[significant[j]].text;
            // (anything inside the list but a lone `void` is an argument: `log2((x))` has one)
            if(level >= 1 && x !== ")" && !(level === 1 && x === "void")) empty = false;
            if(x === "(" || x === "[") level++;
            else if(x === ")" || x === "]") { if(--level === 0) break; }
            else if(level === 1 && x === ",") count++;
        }
        const before = k > 0 ? tokens[significant[k - 1]] : null;
        uses.push({ token: t, arity: empty ? 0 : count + 1, declaration: depth === 0 && !!before && before.kind === "name" });
    }
    const own = new Map();
    for(const u of uses) if(u.declaration) own.set(u.token.text, (own.get(u.token.text) || new Set()).add(u.arity));
    for(const u of uses)
    {
        const arities = own.get(u.token.text);
        if(arities && arities.has(u.arity) && !BUILTINS_100.get(u.token.text).includes(u.arity)) u.token.overload = true;
    }
}

/**
 * The source's tokens: identifiers, numbers and everything else, comments
 * and white space kept as they are
 * @param {string} source
 * @return {!Array<{kind: string, text: string, line: number}>}
 */
function tokenize(source)
{
    const tokens = [];
    let line = 1;
    const pattern = /(\/\/[^\n]*)|(\/\*[\s\S]*?\*\/)|([A-Za-z_][A-Za-z0-9_]*)|(\d+\.?\d*(?:[eE][+-]?\d+)?[uUfF]?|\.\d+(?:[eE][+-]?\d+)?[fF]?)|(\n)|([ \t\r\f\v]+)|([\s\S])/g;
    for(let m; (m = pattern.exec(source));)
    {
        const kind = m[1] || m[2] ? "comment" : m[3] ? "name" : m[4] ? "number" : m[5] ? "newline" : m[6] ? "space" : "punct";
        tokens.push({ kind, text: m[0], line });
        line += (m[0].match(/\n/g) || []).length;
    }
    return tokens;
}

/**
 * A GLSL ES 3.x source whose shared and packed interface blocks are std140
 * (uniform blocks) or std430 (buffer blocks), the default layouts too:
 * GLSL ES lets an implementation choose those layouts, glslang's reflection
 * packs them as std430 while the page reads uniform blocks as std140; the
 * offsets, strides and the code then agree. Each block's packing is written
 * on the block (glslang's reflection packs arrays in a block's structs as
 * std430 where a default statement gave the block std140); the defaults go
 * after the #version and #extension lines.
 * @param {string} source
 * @param {boolean=} buffers false: buffer blocks' packings as they are
 *     (glslang's reflection packs shared and packed ones as std430 and, as
 *     GL, keeps a shared one nothing uses)
 * @return {string}
 */
export function std_blocks(source, buffers = true)
{
    const version = glsl_version(source);
    if(version < 300) return source;
    const tokens = tokenize(source);
    const significant = tokens.map((t, i) => i).filter(i => !["space", "comment", "newline"].includes(tokens[i].kind));
    const at_k = k => tokens[significant[k]] || { text: "", kind: "" };
    const QUALIFIERS = new Set(["readonly", "writeonly", "coherent", "volatile", "restrict", "highp", "mediump", "lowp"]);
    const PACKINGS = new Set(["shared", "packed", "std140", "std430"]);
    const packing_of = (storage, packing) => storage === "uniform" ? (packing === "std430" ? packing : "std140") :
        buffers && (packing === "shared" || packing === "packed") ? "std430" : packing;
    const defaults = { uniform: "shared", buffer: "shared" };
    for(let k = 0; k < significant.length; k++)
    {
        // (a declaration of uniform or buffer storage: its layout, qualifiers, the storage, then ";" for a default, a block's name and "{")
        let open = -1, close = -1, storage_at = k;
        if(at_k(k).text === "layout" && at_k(k + 1).text === "(")
        {
            open = k + 1;
            close = open;
            while(close < significant.length && at_k(close).text !== ")") close++;
            storage_at = close + 1;
        }
        else if(at_k(k).text !== "uniform" && at_k(k).text !== "buffer") continue;
        while(storage_at < significant.length && QUALIFIERS.has(at_k(storage_at).text)) storage_at++;
        const storage = at_k(storage_at).text;
        if(storage !== "uniform" && storage !== "buffer") continue;
        let given = null;
        for(let j = open + 1; open >= 0 && j < close; j++) if(at_k(j).kind === "name" && PACKINGS.has(at_k(j).text)) given = at_k(j);
        const block = at_k(storage_at + 1).kind === "name" && at_k(storage_at + 2).text === "{";
        if(at_k(storage_at + 1).text === ";" && given) defaults[storage] = given.text;
        if(given) given.text = packing_of(storage, given.text);
        else if(block && open >= 0) at_k(open).text = "(" + packing_of(storage, defaults[storage]) + ", ";
        else if(block) at_k(storage_at).text = "layout(" + packing_of(storage, defaults[storage]) + ") " + storage;
        k = storage_at;
    }
    // (after the last #version or #extension line)
    let end = 0, at_line_start = true;
    for(let i = 0; i < tokens.length; i++)
    {
        const t = tokens[i];
        if(t.kind === "newline") { at_line_start = true; continue; }
        if(t.kind === "space" || t.kind === "comment") continue;
        if(at_line_start && t.text === "#")
        {
            const name = tokens.slice(i + 1).find(x => x.kind !== "space");
            let j = i;
            while(j < tokens.length && tokens[j].kind !== "newline") j++;
            if(name && (name.text === "version" || name.text === "extension")) end = j + 1;
            i = j - 1;
            continue;
        }
        at_line_start = false;
    }
    const before = tokens.slice(0, end).map(t => t.text).join(""), rest = tokens.slice(end).map(t => t.text).join("");
    const statements = "layout(std140) uniform;\n" + (version >= 310 && buffers ? "layout(std430) buffer;\n" : "");
    return before + (before && !before.endsWith("\n") ? "\n" : "") + statements + rest;
}

/**
 * Each interface block's packing as its source gives it (std_blocks makes
 * shared and packed std140, so a link compares them first): the layout's
 * shared, packed, std140 or std430, else the default a `layout(...)
 * uniform;` statement before it set, else shared
 * @param {string} source
 * @return {!Map<string, string>} by "uniform:Name" or "buffer:Name"
 */
export function block_packings(source)
{
    const packings = new Map();
    if(glsl_version(source) < 300) return packings;
    const tokens = tokenize(source).filter(t => !["space", "comment", "newline"].includes(t.kind));
    const PACKINGS = new Set(["shared", "packed", "std140", "std430"]);
    const QUALIFIERS = new Set(["readonly", "writeonly", "coherent", "volatile", "restrict", "highp", "mediump", "lowp"]);
    const defaults = { uniform: "shared", buffer: "shared" };
    for(let k = 0; k < tokens.length; k++)
    {
        let packing = null, at = k;
        if(tokens[k].text === "layout" && tokens[k + 1] && tokens[k + 1].text === "(")
        {
            at = k + 2;
            while(at < tokens.length && tokens[at].text !== ")") { if(PACKINGS.has(tokens[at].text)) packing = tokens[at].text; at++; }
            at++;
        }
        else if(tokens[k].text !== "uniform" && tokens[k].text !== "buffer") continue;
        while(at < tokens.length && QUALIFIERS.has(tokens[at].text)) at++;
        const storage = tokens[at] && tokens[at].text;
        if(storage !== "uniform" && storage !== "buffer") { k = at - 1; continue; }
        const next = tokens[at + 1];
        if(next && next.text === ";") { if(packing) defaults[storage] = packing; }
        else if(next && next.kind === "name" && tokens[at + 2] && tokens[at + 2].text === "{") packings.set(storage + ":" + next.text, packing || defaults[storage]);
        k = at;
    }
    return packings;
}

/** GLSL ES 3.x's reserved words glslang takes as names (3.00 3.7) */
const RESERVED_300 = new Set(["image1DShadow", "image2DShadow", "image1DArrayShadow", "image2DArrayShadow"]);

/** A reserved word of GLSL ES 3.x the source uses (one glslang takes), or null */
export function reserved_word(source)
{
    const t = tokenize(source).find(t => t.kind === "name" && RESERVED_300.has(t.text));
    return t ? t.text : null;
}

/**
 * Whether an #extension directive comes after a token that is not the
 * preprocessor's, which GLSL ES (3.00 3.4, 1.00 3.4) refuses and glslang
 * takes
 * @param {string} source
 */
export function extension_after_code(source)
{
    let code = false, line_start = true;
    const tokens = tokenize(source);
    for(let i = 0; i < tokens.length; i++)
    {
        const t = tokens[i];
        if(t.kind === "newline") { line_start = true; continue; }
        if(t.kind === "space" || t.kind === "comment") continue;
        if(line_start && t.text === "#")
        {
            let j = i + 1;
            while(j < tokens.length && tokens[j].kind === "space") j++;
            if(code && tokens[j] && tokens[j].text === "extension") return true;
            while(i < tokens.length && tokens[i].kind !== "newline") i++;
            i--;
            line_start = false;
            continue;
        }
        line_start = false;
        code = true;
    }
    return false;
}

/**
 * The rules of GLSL ES 3.x glslang's relaxed check lets through (an
 * #extension after the code, the reserved image shadow types): the error
 * a compile gives, or null
 * @param {string} source
 */
export function es3_rules(source)
{
    if(glsl_version(source) < 300) return null;
    if(extension_after_code(source)) return "ERROR: '#extension' : must occur before any non-preprocessor tokens\n";
    const reserved = reserved_word(source);
    return reserved ? "ERROR: '" + reserved + "' : Reserved word.\n" : null;
}

/** @return {number} the shader's #version (100 when it has none) */
export function glsl_version(source)
{
    const m = /^\s*(?:(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/)\s*)*#\s*version\s+(\d+)/.exec(source);
    return m ? +m[1] : 100;
}

/**
 * @param {string} source a shader the check pass compiled
 * @param {string} stage "vertex", "fragment", "compute", ...
 * @param {{maxVaryingVectors: number, maxDrawBuffers: number}} limits
 * @return {{source: string, renames: !Map<string, string>, version: number}}
 *     renames: the new names, by GL's
 */
export function rewrite_for_spirv(source, stage, limits)
{
    const version = glsl_version(source);
    const es100 = version === 100;
    const tokens = tokenize(source);
    const renames = new Map();
    const rename = name =>
    {
        const renamed = name + SUFFIX;
        renames.set(name, renamed);
        return renamed;
    };
    let frag_color = false, frag_data = false, at_line_start = true;
    let version_line_end = -1;
    // (where the sample functions' helpers go: after the #version and #extension lines)
    let directives_end = -1;
    const sample_uses = new Set();
    const extended_uses = new Set();
    if(es100) mark_overloads(tokens);
    for(let i = 0; i < tokens.length; i++)
    {
        const t = tokens[i];
        if(t.kind === "newline") { at_line_start = true; continue; }
        if(t.kind === "space" || t.kind === "comment") continue;
        if(at_line_start && t.text === "#")
        {
            // a directive: #version and #extension rewritten, the rest as they are
            let j = i + 1;
            while(j < tokens.length && tokens[j].kind === "space") j++;
            const directive = tokens[j] && tokens[j].text;
            let end = j;
            while(end < tokens.length && tokens[end].kind !== "newline") end++;
            if(directive === "version" || directive === "extension") directives_end = end;
            if(directive === "version")
            {
                if(es100) for(let k = i; k < end; k++) tokens[k].text = k === i ? "#version 300 es" : "";
                version_line_end = end;
            }
            else if(directive === "extension" && (es100 || tokens.slice(j, end).some(t => /^GL_OES_EGL_image_external/.test(t.text))))
            {
                for(let k = i; k < end; k++) tokens[k].text = "";
            }
            else
            {
                // (#define and #if lines name the user's identifiers too)
                for(let k = j + 1; k < end; k++) if(tokens[k].kind === "name") rename_token(tokens[k]);
            }
            i = end - 1;
            at_line_start = false;
            continue;
        }
        at_line_start = false;
        if(t.kind === "name" && t.text === "invariant" && es100 && stage === "fragment")
        {
            // invariance of a fragment shader's inputs: 1.00 has it, 3.00
            // refuses it, and it changes nothing; `invariant varying` loses
            // the qualifier, `invariant name;` the statement
            const next = tokens.slice(i + 1).find(n => n.kind !== "space" && n.kind !== "comment" && n.kind !== "newline");
            if(next && next.text === "varying") { t.text = ""; continue; }
            if(next && next.kind === "name" && !/^gl_Frag/.test(next.text))
            {
                let j = i;
                while(j < tokens.length && tokens[j].text !== ";") tokens[j++].text = "";
                if(j < tokens.length) tokens[j].text = "";
                i = j;
                continue;
            }
        }
        if(t.kind === "name") rename_token(t);
    }

    function rename_token(t)
    {
        const name = t.text;
        if(VULKAN_NAMES.has(name) && !(es100 && TEXTURE_FUNCTIONS.has(name)))
        {
            t.text = rename(name);
            return;
        }
        if(name === "samplerExternalOES") t.text = "sampler2D";
        if(!es100 && EXTENDED_FUNCTIONS.has(name))
        {
            extended_uses.add(name);
            t.text = "_v86_" + name;
            return;
        }
        if(stage === "fragment" && name === "gl_HelperInvocation")
        {
            t.text = "false";
            return;
        }
        if(stage === "fragment" && !es100 && SAMPLE_FUNCTIONS.has(name))
        {
            sample_uses.add(name);
            t.text = name === "gl_SamplePosition" ? "_v86_SamplePosition()" : "_v86_" + name;
            return;
        }
        if(!es100) return;
        if(t.overload) t.text = rename(name);
        else if(TEXTURE_FUNCTIONS.has(name)) t.text = TEXTURE_FUNCTIONS.get(name);
        else if(ES300_NAMES.has(name)) t.text = rename(name);
        else if(name === "attribute") t.text = "in";
        else if(name === "varying") t.text = stage === "vertex" ? "out" : "in";
        else if(name === "gl_FragColor") { t.text = "_v86_FragColor"; frag_color = true; }
        else if(name === "gl_FragData") { t.text = "_v86_FragData"; frag_data = true; }
        else if(name === "gl_FragDepthEXT") t.text = "gl_FragDepth";
        else if(name === "gl_MaxVaryingVectors") t.text = String(limits.maxVaryingVectors);
    }

    const blend = stage === "fragment" && !es100 && tokens.some(t => t.kind === "name" && /^blend_support_/.test(t.text)) ? rewrite_blend(tokens) : null;
    let text = tokens.map(t => t.text).join("");
    if(blend) text += "\n" + blend;
    // (glslang's relaxed rules write atomicCounterDecrement(c) as atomicAdd(c, -1) - 1, a uint minus an int: GLSL ES
    // refuses it without the implicit conversions, which change nothing the check pass accepted)
    const conversions = version >= 310 && tokens.some(t => t.kind === "name" && t.text === "atomicCounterDecrement") ?
        "#extension GL_EXT_shader_implicit_conversions : enable\n" : "";
    if((sample_uses.size || extended_uses.size || conversions) && directives_end >= 0)
    {
        const at = tokens.slice(0, directives_end).reduce((n, t) => n + t.text.length, 0);
        text = text.slice(0, at) + "\n" + conversions + sample_helpers(sample_uses) + extended_helpers(extended_uses) + text.slice(at);
    }
    if(es100)
    {
        const outputs = (frag_color ? "layout(location = 0) out mediump vec4 _v86_FragColor; " : "") +
            (frag_data ? "layout(location = 0) out mediump vec4 _v86_FragData[" + limits.maxDrawBuffers + "]; " : "");
        if(version_line_end < 0)
        {
            text = "#version 300 es\n" + (outputs ? outputs + "\n" : "") + text;
        }
        else if(outputs)
        {
            // after the #version line
            const end = tokens.slice(0, version_line_end).reduce((n, t) => n + t.text.length, 0);
            text = text.slice(0, end) + "\n" + outputs + text.slice(end);
        }
    }
    return { source: text, renames, version };
}
          source/v64/src/gles/glsl_program.js                                                                 0000644 0000000 0000000 00000144635 00000000000 014450  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A GLSL ES program linked with glslang (docs/gles3-plan.md, "着色器的数据流"):
// GL's view of it from the check pass (the active attributes, uniforms and
// blocks with GL's names, types and sizes; the locations, by GL's rules),
// and each stage's SPIR-V from the code pass with the interface and the
// bindings the host decides:
// - vertex inputs at their attribute locations (layout(location), else
//   glBindAttribLocation, else the lowest free);
// - each stage's outputs and the next stage's inputs at the same
//   locations, by name, unless the shaders place them;
// - resources in group 0: the default uniform block at 0, samplers from 1,
//   uniform blocks from 17, shader storage blocks from 42, atomic counter
//   blocks from 60 (by binding point), images from 70. vx_naga makes
//   binding b WGSL's 2b (2b + 1 for a combined sampler's sampler).
// The result has the shape glsl_es.js's link_program gives the shadow
// (ProgramInfo), with `spirv`, `blocks` and `bindings` added.

import { GL_STATE } from "./gles_caps.js";
import { STAGE } from "./glslang.js";
import { BLEND_DESTINATION, blend_support, block_packings, glsl_version, rewrite_for_spirv, std_blocks } from "./glsl_es_rewrite.js";
import { DECORATION, EXECUTION_MODEL, OP, STORAGE, add_xfb, array_length, block_layout, get_decoration, innermost, is_builtin, location_count, parse_spirv,
    set_decoration, variable_name } from "./spirv_patch.js";

/** GL_MAX_VERTEX_ATTRIBS */
const MAX_VERTEX_ATTRIBS = GL_STATE.get(0x8869)[0];

export const BINDING = { DEFAULT_BLOCK: 0, SAMPLERS: 1, UNIFORM_BLOCKS: 17, STORAGE_BLOCKS: 42, ATOMIC_COUNTERS: 60, IMAGES: 70 };

/** GL's uniform types: components, matrix columns and rows, base, and the opaque kinds */
const TYPES = new Map();
for(const [base, enums] of [["float", [0x1406, 0x8B50, 0x8B51, 0x8B52]], ["int", [0x1404, 0x8B53, 0x8B54, 0x8B55]],
    ["uint", [0x1405, 0x8DC6, 0x8DC7, 0x8DC8]], ["bool", [0x8B56, 0x8B57, 0x8B58, 0x8B59]]])
{
    enums.forEach((e, i) => TYPES.set(e, { base, components: i + 1, columns: 0, rows: i + 1 }));
}
for(const [e, columns, rows] of [[0x8B5A, 2, 2], [0x8B5B, 3, 3], [0x8B5C, 4, 4], [0x8B65, 2, 3], [0x8B66, 2, 4], [0x8B67, 3, 2],
    [0x8B68, 3, 4], [0x8B69, 4, 2], [0x8B6A, 4, 3]])
{
    TYPES.set(e, { base: "float", components: columns * rows, columns, rows });
}
const SAMPLERS = [0x8B5E, 0x8B5F, 0x8B60, 0x8B62, 0x8DC1, 0x8DC4, 0x8DC5, 0x8DCA, 0x8DCB, 0x8DCC, 0x8DCF, 0x8DD2, 0x8DD3, 0x8DD4,
    0x8DD7, 0x8D66, 0x9108, 0x9109, 0x910A, 0x900C, 0x900D, 0x900E, 0x900F, 0x8DC2, 0x8DD0, 0x8DD8, 0x910B, 0x910C, 0x910D];
const IMAGES = [0x904D, 0x904E, 0x9050, 0x9053, 0x9058, 0x9059, 0x905B, 0x905E, 0x9063, 0x9064, 0x9066, 0x9069, 0x9051, 0x905C,
    0x9067, 0x9054, 0x905F, 0x906A];
for(const e of SAMPLERS) TYPES.set(e, { base: "int", components: 1, columns: 0, rows: 1, opaque: "sampler" });
for(const e of IMAGES) TYPES.set(e, { base: "int", components: 1, columns: 0, rows: 1, opaque: "image" });
TYPES.set(0x92DB, { base: "uint", components: 1, columns: 0, rows: 1, opaque: "atomic" });

/** @param {number} type GL's @return {!Object} its TYPES entry */
export function gl_type(type)
{
    return TYPES.get(type) || { base: "float", components: 1, columns: 0, rows: 1 };
}

const STAGE_NAME = ["vertex", "tess_control", "tess_evaluation", "geometry", "fragment", "compute"];
const MODEL_OF_STAGE = [EXECUTION_MODEL.Vertex, EXECUTION_MODEL.TessellationControl, EXECUTION_MODEL.TessellationEvaluation,
    EXECUTION_MODEL.Geometry, EXECUTION_MODEL.Fragment, EXECUTION_MODEL.GLCompute];

/** @param {string} name a block's ("B[1]", "B[0][2]") @return {string} its instance array's ("B") */
function instance_array_name(name)
{
    return name.replace(/(?:\[\d+\])+$/, "");
}

/** @param {string} name GL's ("a[0].b") @param {!Map<string, string>} renames @return {string} the code pass's */
function renamed(name, renames)
{
    return name.replace(/[A-Za-z_][A-Za-z0-9_]*/g, id => renames.get(id) || id);
}

/** @param {string} name @return {string} without its last "[0]" */
function base_name(name)
{
    return name.endsWith("[0]") ? name.slice(0, -3) : name;
}

/**
 * Link a program's shaders
 * @param {!Object} glslang src/gles/glslang.js's Glslang
 * @param {!Array<{stage: string, source: string}>} shaders stage: STAGE_NAME's
 * @param {{bindings: (!Map<string, number>|undefined), separable: (boolean|undefined),
 *     limits: {maxVaryingVectors: number, maxDrawBuffers: number}}} options bindings: glBindAttribLocation's
 * @return {!Object} ProgramInfo and spirv, blocks, bindings
 */
export function link_glslang_program(glslang, shaders, options)
{
    const empty = log => ({ ok: false, log, attributes: [], uniforms: [], locations: new Map(), by_location: [], reflection: null,
        blocks: [], bindings: [], spirv: [] });
    const flags = options.separable ? 1 : 0;
    // (a block of other packings in two stages: refused before std_blocks makes shared and packed one)
    const packings = new Map();
    for(const s of shaders)
    {
        for(const [block, packing] of block_packings(s.source))
        {
            if(packings.has(block) && packings.get(block) !== packing) return empty("ERROR: Linking: the layouts of block " + block.split(":")[1] + " differ");
            packings.set(block, packing);
        }
    }
    // (shared and packed blocks as std140 and std430: the reflection's offsets, the code's and the page's agree; the check
    // pass's buffer blocks as they are, so that a shared one nothing uses stays active)
    const check_sources = shaders.map(s => std_blocks(s.source, false));
    shaders = shaders.map(s => Object.assign({}, s, { source: std_blocks(s.source) }));
    let check;
    try
    {
        check = glslang.check_program(shaders.map((s, i) => ({ stage: STAGE[s.stage], source: check_sources[i] })), flags);
    }
    catch(e)
    {
        return empty("ERROR: internal linker error: " + (e && e.message || e));
    }
    if(!check.ok) return empty(check.log || "ERROR: link failed");

    // the attributes: layout(location), else glBindAttribLocation's, else the lowest free
    const attributes = [];
    const used = new Set();
    const vertex_inputs = check.inputs.filter(i => !i.builtIn && (i.stages & 1 << STAGE.vertex));
    const span = i => Math.max(1, gl_type(i.type).columns) * Math.max(1, i.size);
    const take = (location, n) => { for(let k = 0; k < n; k++) used.add(location + k); };
    for(const i of vertex_inputs)
    {
        const bound = options.bindings && options.bindings.get(i.name);
        const location = i.location >= 0 ? i.location : bound !== undefined ? bound : -1;
        attributes.push({ name: i.name, size: Math.max(1, i.size), type: i.type, location });
        if(location >= 0) take(location, span(i));
    }
    for(const a of attributes)
    {
        if(a.location >= 0) continue;
        const n = span(vertex_inputs.find(i => i.name === a.name));
        let location = 0;
        while([...Array(n).keys()].some(k => used.has(location + k))) location++;
        a.location = location;
        take(location, n);
    }
    // (GL_MAX_VERTEX_ATTRIBS, a link error past it)
    if([...used].some(location => location >= MAX_VERTEX_ATTRIBS)) return empty("ERROR: the vertex shader's inputs need more than " + MAX_VERTEX_ATTRIBS + " locations");

    // the uniforms GL lists: the default block's, the blocks' members, the opaque ones
    const blocks = check.uniformBlocks.map((b, index) => ({ name: b.name, index, size: b.size, binding: element_binding(check.uniformBlocks, b),
        stages: b.stages, members: [] }));
    const uniforms = [];
    for(const u of check.uniforms)
    {
        const t = gl_type(u.type);
        const size = Math.max(1, u.size);
        // (a matrix's alone: GL's UNIFORM_IS_ROW_MAJOR of any other uniform is false, in a row_major block too)
        const row_major = !!u.rowMajor && !!t.columns;
        const matrix_stride = !t.columns ? 0 : u.packing === "std430" ? ((row_major ? t.columns : t.rows) === 2 ? 8 : 16) : 16;
        uniforms.push({
            name: u.name, base: base_name(u.name), size, type: u.type, location: -1, explicit_location: u.location,
            components: t.components, columns: t.columns, rows: t.rows, sampler: t.opaque === "sampler", opaque: t.opaque || null,
            int: t.base !== "float", bool: t.base === "bool", uint: t.base === "uint", block_index: u.index, offset: u.offset,
            array_stride: u.arrayStride, matrix_stride, row_major, binding: u.binding, stages: u.stages,
        });
        if(u.index >= 0 && blocks[u.index]) blocks[u.index].members.push(uniforms.length - 1);
    }
    // (an instance array's elements each have the array's members, which glslang gives its first element)
    for(const b of blocks)
    {
        const first = blocks.find(x => instance_array_name(x.name) === instance_array_name(b.name));
        if(first !== b && !b.members.length) b.members = first.members.slice();
    }
    // layout(location) on uniforms: GL refuses two at one location even
    // when they are not active, which the reflection leaves out
    // (the declarations with a location: glslang reflects none for a
    // struct's members, nor for a uniform with one in one stage only, and
    // each inner array of an array of arrays at the array's)
    const declared = new Map(), located = new Map();
    const structs = struct_declarations(shaders);
    for(const s of shaders)
    {
        const pattern = /(?:layout\s*\(([^)]*)\)\s*uniform|uniform\s+layout\s*\(([^)]*)\))\s+(?:(?:lowp|mediump|highp)\s+)?(\w+)\s+(\w+)\s*((?:\[\s*\d+\s*\])*)/g;
        for(let m; (m = pattern.exec(s.source));)
        {
            const at = /\blocation\s*=\s*(\d+)/.exec(m[1] || m[2]);
            if(!at) continue;
            const dims = (m[5].match(/\d+/g) || []).map(Number);
            const location = +at[1], size = dims.reduce((n, d) => n * d, 1) * uniform_locations(m[3], structs);
            located.set(m[4], { location, type: m[3], dims });
            for(let i = 0; i < size; i++)
            {
                const owner = declared.get(location + i);
                if(owner !== undefined && owner !== m[4] + "[" + i + "]")
                {
                    return empty("ERROR: uniform location " + (location + i) + " is used by two uniforms");
                }
                declared.set(location + i, m[4] + "[" + i + "]");
            }
        }
    }
    // locations: the default block's and the opaque uniforms; layout(location) first
    const taken = new Set();
    const default_uniforms = uniforms.filter(u => u.block_index < 0 && u.opaque !== "atomic");
    for(const u of default_uniforms)
    {
        const declaration = located.get(u.name.replace(/[[.].*$/, ""));
        const offset = declaration ? location_offset(declaration, u.name, structs) : -1;
        if(offset >= 0) u.explicit_location = declaration.location + offset;
        if(u.explicit_location < 0) continue;
        u.location = u.explicit_location;
        for(let i = 0; i < u.size; i++)
        {
            // (two uniforms at one location: a link error, which glslang leaves to GL)
            if(taken.has(u.location + i)) return empty("ERROR: uniform location " + (u.location + i) + " is used by two uniforms");
            taken.add(u.location + i);
        }
    }
    let next = 0;
    for(const u of default_uniforms)
    {
        if(u.location >= 0) continue;
        while([...Array(u.size).keys()].some(k => taken.has(next + k))) next++;
        u.location = next;
        for(let i = 0; i < u.size; i++) taken.add(next + i);
        next += u.size;
    }
    const locations = new Map();
    const by_location = [];
    for(const u of default_uniforms)
    {
        locations.set(u.base, u.location);
        for(let i = 0; i < u.size; i++)
        {
            if(u.size > 1 || u.name !== u.base) locations.set(u.base + "[" + i + "]", u.location + i);
            by_location[u.location + i] = { uniform: u, element: i };
        }
    }

    // the code pass
    const rewritten = shaders.map(s => rewrite_for_spirv(s.source, s.stage, options.limits));
    const renames = new Map();
    for(const r of rewritten) for(const [from, to] of r.renames) renames.set(from, to);
    let code;
    try
    {
        code = glslang.program_spirv(shaders.map((s, i) => ({ stage: STAGE[s.stage], source: rewritten[i].source })), flags);
    }
    catch(e)
    {
        return empty("ERROR: internal compiler error: " + (e && e.message || e));
    }
    if(!code.ok) return empty("ERROR: internal compiler error (SPIR-V): " + code.log);
    // transform feedback of array elements and struct members ("v[1]",
    // "s.a"): the last stage before the fragment shader copies each into an
    // output of its own after its main (_v86_xfb<i>, captured whole)
    const parts = options.tf ? options.tf.names.filter(n => /[[.]/.test(n) && !n.startsWith("gl_")) : [];
    if(parts.length)
    {
        let index = shaders.length - 1;
        while(index >= 0 && (shaders[index].stage === "fragment" || shaders[index].stage === "compute")) index--;
        const module = index >= 0 && code.modules.find(x => x.stage === STAGE[shaders[index].stage]);
        const m = module && parse_spirv(new Uint32Array(module.words));
        const explicit = /\blayout\s*\([^)]*\blocation\b[^)]*\)\s*(?:(?:flat|smooth|centroid|highp|mediump|lowp|invariant)\s+)*out\b/.test(shaders[index].source);
        let source = rewritten[index].source.replace(/\bmain\b(?=\s*\()/g, "_v86_main");
        let copies = "";
        for(const [i, name] of parts.entries())
        {
            const type = m && element_type(m, renamed(name, renames));
            if(!type) return empty("ERROR: transform feedback varying " + name + " is not an output of the vertex shader");
            source += `\n${explicit ? `layout(location = ${15 - i}) ` : ""}${type.integer ? "flat " : ""}out highp ${type.glsl} _v86_xfb${i};`;
            copies += ` _v86_xfb${i} = ${renamed(name, renames)};`;
        }
        rewritten[index] = Object.assign({}, rewritten[index], { source: source + "\nvoid main() { _v86_main();" + copies + " }\n" });
        try
        {
            code = glslang.program_spirv(shaders.map((s, i) => ({ stage: STAGE[s.stage], source: rewritten[i].source })), flags);
        }
        catch(e)
        {
            return empty("ERROR: internal compiler error: " + (e && e.message || e));
        }
        if(!code.ok) return empty("ERROR: transform feedback varyings " + parts.join(", ") + ": " + code.log);
    }
    const refused = link_rules(code.modules, shaders, !!options.separable);
    if(refused) return empty(refused);

    // the default block's layout: each uniform's offset and strides in it,
    // from the SPIR-V (the code pass's reflection differs from it); the
    // block is the same in every stage (glslang merges it when linking)
    const default_block = code.uniformBlocks.findIndex(b => b.name === "gl_DefaultUniformBlock");
    const layout = new Map();
    for(const module of code.modules)
    {
        const words = new Uint32Array(module.words);
        for(const [name, leaf] of block_layout(words, parse_spirv(words), "gl_DefaultUniformBlock")) layout.set(name, leaf);
    }
    for(const u of default_uniforms)
    {
        if(u.opaque) continue;
        const leaf = layout.get(renamed(u.name, renames));
        if(!leaf) continue;
        u.offset = leaf.offset;
        u.array_stride = leaf.array_stride;
        u.matrix_stride = leaf.matrix_stride;
    }
    // the atomic counters' offsets (their layout(offset)s, which the check
    // pass's reflection leaves out): their members' in the code pass's
    // gl_AtomicCounterBlock_<binding>, an array's element by its indices and
    // the arrays' strides; each binding's buffer size, the declared counters'
    const counters = new Map();
    const counter_buffers = new Map();
    for(const module of code.modules)
    {
        const words = new Uint32Array(module.words);
        const m = parse_spirv(words);
        for(const [id, name] of m.names)
        {
            const t = m.types.get(id);
            const binding = /^gl_AtomicCounterBlock_(\d+)$/.exec(name);
            if(!binding || !t || t.kind !== "struct") continue;
            const names = m.member_names.get(id) || [];
            t.members.forEach((member, i) =>
            {
                const d = m.member_decorations.get(id);
                const at = d && d.get(i) && d.get(i).get(DECORATION.Offset);
                const offset = at === undefined || at < 0 ? 0 : words[at];
                const strides = [];
                let count = 1;
                for(let e = member; m.types.get(e) && m.types.get(e).kind === "array"; e = m.types.get(e).element)
                {
                    strides.push(get_decoration(words, m, e, DECORATION.ArrayStride) || 4);
                    count *= array_length(m, m.types.get(e));
                }
                counters.set(binding[1] + ":" + names[i], { offset, strides });
                counter_buffers.set(+binding[1], Math.max(counter_buffers.get(+binding[1]) || 0, offset + 4 * count));
            });
        }
    }
    for(const u of uniforms)
    {
        if(u.opaque !== "atomic") continue;
        const parts = /^(\w+)((?:\[\d+\])*)$/.exec(u.name);
        const counter = parts && counters.get(u.binding + ":" + renamed(parts[1], renames));
        if(!counter) continue;
        const indices = (parts[2].match(/\d+/g) || []).map(Number);
        u.offset = indices.reduce((offset, index, k) => offset + index * (counter.strides[k] || 4), counter.offset);
        u.array_stride = counter.strides.length ? counter.strides[counter.strides.length - 1] : 0;
    }

    // the resources' bindings
    const bindings = [{ binding: BINDING.DEFAULT_BLOCK, kind: "default", size: default_block >= 0 ? code.uniformBlocks[default_block].size : 0 }];
    // samplers and images: one binding a SPIR-V variable, the same in every
    // stage (an array in a struct is a variable an element there)
    const gl_names = new Map([...renames].map(([from, to]) => [to, from]));
    const gl_name = name => name.replace(/[A-Za-z_][A-Za-z0-9_]*/g, id => gl_names.get(id) || id);
    const opaque = new Map();
    let next_sampler = BINDING.SAMPLERS, next_image = BINDING.IMAGES;
    const opaque_binding = (name, image) =>
    {
        if(opaque.has(name)) return opaque.get(name);
        const gl = gl_name(name);
        const location = locations.has(gl) ? locations.get(gl) : -1;
        const at = by_location[location];
        const binding = image ? next_image++ : next_sampler++;
        opaque.set(name, binding);
        bindings.push({ binding, kind: image ? "image" : "sampler", location, size: at && gl === at.uniform.base ? at.uniform.size : 1,
            type: at ? at.uniform.type : 0, unit: at && image ? at.uniform.binding : undefined,
            // (the draw's destination, an advanced blend's: glsl_es_rewrite.js's)
            ...(gl === BLEND_DESTINATION ? { blend_destination: true } : {}) });
        return binding;
    };
    blocks.forEach((b, i) => bindings.push({ binding: BINDING.UNIFORM_BLOCKS + i, kind: "uniform_block", block: i, size: b.size }));
    const storage_blocks = check.bufferBlocks.map((b, index) => ({ name: b.name, index, size: b.size, binding: element_binding(check.bufferBlocks, b) }));
    storage_blocks.forEach((b, i) => bindings.push({ binding: BINDING.STORAGE_BLOCKS + i, kind: "storage_block", block: i, size: b.size }));

    // each stage's SPIR-V with them; the vertex inputs GL does not list
    // (unused: the draw gives them (0, 0, 0, 1)) at locations of their own
    const spirv = [];
    const unused_inputs = [];
    const stages = code.modules.map(m => m.stage).sort((a, b) => a - b);
    /** @type {!Map<string, number>} the previous stage's outputs' locations, by name */
    let previous = null;
    const explicit_io = shaders.some(s => /\blayout\s*\([^)]*\blocation\b[^)]*\)\s*(?:(?:flat|smooth|centroid|highp|mediump|lowp|invariant|patch)\s+)*(?:in|out)\b/.test(s.source));
    for(const stage of stages)
    {
        const module = code.modules.find(m => m.stage === stage);
        const words = new Uint32Array(module.words);
        const m = parse_spirv(words);
        const arrayed_inputs = stage === STAGE.tess_control || stage === STAGE.tess_evaluation || stage === STAGE.geometry;
        const arrayed_outputs = stage === STAGE.tess_control;
        const count = (v, arrayed) =>
        {
            let t = m.types.get(m.types.get(v.type).pointee);
            const id = arrayed && t.kind === "array" ? t.element : m.types.get(v.type).pointee;
            return location_count(m, id);
        };
        const outputs = new Map();
        let next_output = 0;
        for(const v of m.variables)
        {
            const name = variable_name(m, v);
            if(v.storage === STORAGE.Input && !is_builtin(m, v))
            {
                if(stage === STAGE.vertex)
                {
                    const gl = [...renames].find(([, to]) => to === name);
                    const a = attributes.find(x => x.name === (gl ? gl[0] : name));
                    if(a) set_decoration(words, m, v.id, DECORATION.Location, a.location);
                    else
                    {
                        const pointee = m.types.get(v.type).pointee;
                        const n = location_count(m, pointee);
                        let location = 0;
                        while([...Array(n).keys()].some(k => used.has(location + k))) location++;
                        take(location, n);
                        set_decoration(words, m, v.id, DECORATION.Location, location);
                        // (each location's: a matrix's columns, an array's elements)
                        let t = m.types.get(pointee);
                        while(t && t.kind === "array") t = m.types.get(t.element);
                        if(t && t.kind === "matrix") t = m.types.get(t.column);
                        const scalar = t && t.kind === "vector" ? m.types.get(t.component) : t;
                        const kind = scalar && scalar.kind === "int" ? (scalar.signed ? "i" : "u") : "f";
                        for(let k = 0; k < n; k++) unused_inputs.push({ location: location + k, kind, components: t && t.kind === "vector" ? t.size : 1 });
                    }
                }
                else if(!explicit_io && previous && previous.has(name))
                {
                    set_decoration(words, m, v.id, DECORATION.Location, previous.get(name));
                }
            }
            else if(v.storage === STORAGE.Output && !is_builtin(m, v) && stage !== STAGE.fragment)
            {
                if(!explicit_io)
                {
                    set_decoration(words, m, v.id, DECORATION.Location, next_output);
                    outputs.set(name, next_output);
                    next_output += count(v, arrayed_outputs);
                }
                else outputs.set(name, get_decoration(words, m, v.id, DECORATION.Location));
            }
            else if(v.storage === STORAGE.Uniform || v.storage === STORAGE.UniformConstant || v.storage === STORAGE.StorageBuffer)
            {
                let binding;
                let inner = m.types.get(m.types.get(v.type).pointee);
                while(inner && (inner.kind === "array" || inner.kind === "runtime_array")) inner = m.types.get(inner.element);
                if(name === "gl_DefaultUniformBlock") binding = BINDING.DEFAULT_BLOCK;
                else if(inner && (inner.kind === "sampled_image" || inner.kind === "sampler")) binding = opaque_binding(name, false);
                else if(inner && inner.kind === "image") binding = opaque_binding(name, inner.sampled === 2);
                else if(/^gl_AtomicCounterBlock/.test(name))
                {
                    binding = BINDING.ATOMIC_COUNTERS + (+(/_(\d+)$/.exec(name) || [0, 0])[1]);
                    if(!bindings.some(b => b.binding === binding)) bindings.push({ binding, kind: "atomic_counters", unit: binding - BINDING.ATOMIC_COUNTERS });
                }
                else
                {
                    // (a block's variable by its instance's name or its block's; an instance array's, its first element: GL lists
                    // "B[0]", "B[1]"..., the array's elements a binding each from the first's)
                    const type_name = m.names.get(innermost(m, m.types.get(v.type).pointee)) || "";
                    const of = b => [name, type_name].some(n => n && [b.name, renamed(b.name, renames)].some(x => x === n || x === n + "[0]"));
                    const block = blocks.findIndex(of);
                    const storage = storage_blocks.findIndex(of);
                    if(block >= 0) binding = BINDING.UNIFORM_BLOCKS + block;
                    else if(storage >= 0) binding = BINDING.STORAGE_BLOCKS + storage;
                }
                if(binding !== undefined)
                {
                    // (a separable program's fragment stage in set 1: a pipeline's vertex and fragment programs each have a set,
                    // their default blocks the same binding)
                    set_decoration(words, m, v.id, DECORATION.DescriptorSet, options.separable && stage === STAGE.fragment ? 1 : 0);
                    set_decoration(words, m, v.id, DECORATION.Binding, binding);
                }
            }
        }
        void arrayed_inputs;
        previous = outputs;
        naga_decorations(words, m);
        spirv.push({ stage: STAGE_NAME[stage], words: consecutive_elements(words), model: MODEL_OF_STAGE[stage] });
    }

    // transform feedback's varyings: outputs of the last stage before the
    // fragment shader, whole (or gl_Position, gl_PointSize)
    let tf_varyings = [];
    if(options.tf && options.tf.names.length)
    {
        const last = spirv.filter(m => m.stage !== "fragment" && m.stage !== "compute").pop();
        const m = last && parse_spirv(last.words);
        let components = 0;
        for(const name of options.tf.names)
        {
            // (an element or member: its copy's output)
            const variable = parts.includes(name) ? "_v86_xfb" + parts.indexOf(name) : renamed(name, renames);
            const v = m && varying_of(m, variable, name);
            if(v) v.variable = variable;
            if(!v) return empty("ERROR: transform feedback varying " + name + " is not an output of the vertex shader");
            if(tf_varyings.some(x => x.name === name)) return empty("ERROR: transform feedback varying " + name + " is named twice");
            components += v.components * v.size;
            if(options.tf.mode === 0x8C8D && v.components * v.size > 4) return empty("ERROR: " + name + " has too many components to capture alone");
            tf_varyings.push(v);
        }
        if(options.tf.mode === 0x8C8C && components > 64) return empty("ERROR: too many components to capture interleaved");
        // (the decorations the page's capture reads: interleaved into buffer 0, else each into its own)
        const interleaved = options.tf.mode === 0x8C8C;
        const stride = tf_varyings.reduce((n, v) => n + v.bytes, 0);
        let offset = 0;
        last.words = add_xfb(last.words, tf_varyings.map((v, i) =>
        {
            const capture = { name: v.name.startsWith("gl_") ? v.name : v.variable, buffer: interleaved ? 0 : i,
                offset: interleaved ? offset : 0, stride: interleaved ? stride : v.bytes };
            offset += v.bytes;
            return capture;
        }));
    }

    const geometry_module = spirv.find(m => m.stage === "geometry");
    const tessellation_modules = spirv.filter(m => m.stage === "tess_control" || m.stage === "tess_evaluation");
    return { ok: true, log: check.log, attributes, uniforms, locations, by_location, reflection: check, blocks, storage_blocks,
        bindings, spirv, renames, local_size: check.localSize, default_block_size: bindings[0].size, tf_varyings,
        counter_buffers: Object.fromEntries(counter_buffers),
        tf_mode: options.tf ? options.tf.mode : 0x8C8C, outputs: check.outputs, geometry: geometry_module ? geometry_layout(geometry_module.words) : null,
        unused_inputs, blend_support: shaders.filter(s => s.stage === "fragment").flatMap(s => blend_support(s.source)),
        tessellation: tessellation_modules.length ? tessellation_layout(tessellation_modules) : null };
}

/**
 * The tessellation shaders' layout from their SPIR-V's execution modes, as
 * GL's program queries answer it: the control shader's output vertices
 * (0 without one), the evaluation shader's mode, spacing, vertex order and
 * point mode (0 without one)
 * @param {!Array<{stage: string, words: !Uint32Array}>} modules
 */
export function tessellation_layout(modules)
{
    const layout = { control: false, evaluation: false, vertices: 0, mode: 0, spacing: 0x0202, order: 0x0901, point_mode: 0 };
    const MODES = { 22: ["mode", 0x0004], 24: ["mode", 0x0007], 25: ["mode", 0x8E7A], 1: ["spacing", 0x0202], 2: ["spacing", 0x8E7C],
        3: ["spacing", 0x8E7B], 4: ["order", 0x0900], 5: ["order", 0x0901], 10: ["point_mode", 1] };
    for(const m of modules)
    {
        layout[m.stage === "tess_control" ? "control" : "evaluation"] = true;
        const words = m.words;
        for(let at = 5; at < words.length;)
        {
            const count = words[at] >>> 16;
            if(!count) break;
            if((words[at] & 0xFFFF) === 16 && count >= 3)
            {
                const mode = words[at + 2];
                if(mode === 26) layout.vertices = words[at + 3];
                else if(m.stage === "tess_evaluation" && mode in MODES) layout[MODES[mode][0]] = MODES[mode][1];
            }
            at += count;
        }
    }
    return layout;
}

/**
 * A geometry shader's layout from its SPIR-V's execution modes, as GL's
 * program queries answer it: the input and output primitive types (GL's
 * enums), max_vertices and invocations
 * @param {!Uint32Array} words
 * @return {{input: number, output: number, vertices: number, invocations: number}}
 */
export function geometry_layout(words)
{
    const layout = { input: 0x0004, output: 0x0005, vertices: 0, invocations: 1 };
    const INPUT = { 19: 0x0000, 20: 0x0001, 21: 0x000A, 22: 0x0004, 23: 0x000C };
    const OUTPUT = { 27: 0x0000, 28: 0x0003, 29: 0x0005 };
    for(let at = 5; at < words.length;)
    {
        const count = words[at] >>> 16;
        if(!count) break;
        // (OpExecutionMode: the entry point, the mode, its operand)
        if((words[at] & 0xFFFF) === 16 && count >= 3)
        {
            const mode = words[at + 2];
            if(mode in INPUT) layout.input = INPUT[mode];
            else if(mode in OUTPUT) layout.output = OUTPUT[mode];
            else if(mode === 26) layout.vertices = words[at + 3];
            else if(mode === 0) layout.invocations = words[at + 3];
        }
        at += count;
    }
    return layout;
}

/** The precisions GLSL ES gives a type when the shader declares none (4.5.4): float has none in a fragment shader */
const DEFAULT_PRECISIONS = { vertex: { float: "highp", int: "highp", sampler2D: "lowp", samplerCube: "lowp" },
    fragment: { int: "mediump", sampler2D: "lowp", samplerCube: "lowp" } };

/**
 * A shader's default block uniforms' precisions, a leaf's path to its
 * precision (GLSL ES: a qualifier of its own, else the default in effect
 * where it, or its struct's member, is declared); the SPIR-V does not keep
 * them. Blocks and the types without precision (bool) are left out.
 * @param {string} source
 * @param {string} stage
 * @return {!Map<string, string>}
 */
export function uniform_precisions(source, stage)
{
    const text = source.replace(/\/\*[^]*?\*\//g, " ").replace(/\/\/[^\n]*/g, "").replace(/^\s*#[^\n]*/gm, "");
    const tokens = text.match(/[A-Za-z_][A-Za-z0-9_]*|\d+|[^\s\w]/g) || [];
    const defaults = Object.assign({}, DEFAULT_PRECISIONS[stage] || {});
    const QUALIFIERS = new Set(["lowp", "mediump", "highp"]);
    const category = type => /^(float|vec\d|mat\d(x\d)?)$/.test(type) ? "float" : /^(int|uint|[iu]vec\d)$/.test(type) ? "int" : type;
    const structs = new Map();
    const out = new Map();
    let i = 0;
    /** a struct's body from tokens[i] ("{"): its members [{name, type, precision}], i after "}" */
    const struct_body = () =>
    {
        const members = [];
        i++;
        while(i < tokens.length && tokens[i] !== "}")
        {
            let precision = null;
            if(QUALIFIERS.has(tokens[i])) precision = tokens[i++];
            let type = tokens[i++];
            if(type === "struct")
            {
                const name = tokens[i] !== "{" ? tokens[i++] : null;
                const nested = struct_body();
                if(name) structs.set(name, nested);
                type = { members: nested };
            }
            while(i < tokens.length && tokens[i] !== ";")
            {
                const name = tokens[i++];
                while(tokens[i] === "[") { while(tokens[i] !== "]") i++; i++; }
                members.push({ name, type, precision: precision || (typeof type === "string" ? defaults[category(type)] || null : null) });
                if(tokens[i] === ",") i++;
            }
            i++;
        }
        i++;
        return members;
    };
    const leaves = (path, type, precision) =>
    {
        const members = typeof type === "object" ? type.members : structs.get(type);
        if(members) for(const m of members) leaves(path + "." + m.name, m.type, m.precision);
        else if(type !== "bool" && !/^bvec/.test(type) && precision) out.set(path, precision);
    };
    let depth = 0;
    while(i < tokens.length)
    {
        const t = tokens[i];
        if(t === "{") { depth++; i++; continue; }
        if(t === "}") { depth--; i++; continue; }
        if(depth > 0) { i++; continue; }
        if(t === "precision" && QUALIFIERS.has(tokens[i + 1]))
        {
            defaults[category(tokens[i + 2])] = tokens[i + 1];
            i += 3;
            continue;
        }
        if(t === "struct" && tokens[i + 2] === "{")
        {
            const name = tokens[i + 1];
            i += 2;
            structs.set(name, struct_body());
            continue;
        }
        if(t !== "uniform") { i++; continue; }
        i++;
        // (a default layout's statement, `layout(std140) uniform;`: no uniform)
        if(tokens[i] === ";") { i++; continue; }
        if(tokens[i] === "layout") { while(tokens[i] !== ")") i++; i++; }
        let precision = null;
        if(QUALIFIERS.has(tokens[i])) precision = tokens[i++];
        let type = tokens[i++];
        if(type === "struct")
        {
            const name = tokens[i] !== "{" ? tokens[i++] : null;
            const members = struct_body();
            if(name) structs.set(name, members);
            type = { members };
        }
        else if(tokens[i] === "{") { depth++; i++; continue; }
        while(i < tokens.length && tokens[i] !== ";")
        {
            const name = tokens[i++];
            while(tokens[i] === "[") { while(tokens[i] !== "]") i++; i++; }
            leaves(name, type, precision || (typeof type === "string" ? defaults[category(type)] || null : null));
            if(tokens[i] === ",") i++;
            else if(tokens[i] !== ";") i++;
        }
        i++;
    }
    return out;
}

/**
 * The link errors of GLSL ES that glslang's relaxed link leaves out:
 * - a uniform of other precisions in two stages (uniform_precisions);
 * - an input the next stage uses that the stage before it does not write
 *   (not in a separable program: a pipeline's stages are checked apart);
 * - in GLSL ES 3.00, an input of other interpolation (flat, noperspective)
 *   than its output (3.10 lets them differ)
 * @param {!Array<{stage: number, words: !Array<number>}>} modules the code pass's
 * @param {!Array<{stage: string, source: string}>} shaders
 * @return {?string} the link's error
 */
function link_rules(modules, shaders, separable)
{
    const precisions = new Map();
    for(const shader of shaders)
    {
        for(const [path, precision] of uniform_precisions(shader.source, shader.stage))
        {
            if(precisions.has(path) && precisions.get(path) !== precision) return "ERROR: Linking: precision of uniform " + path + " differs between shaders";
            precisions.set(path, precision);
        }
    }
    if(separable) return null;
    const parsed = modules.map(module => { const words = new Uint32Array(module.words); return { stage: module.stage, words, m: parse_spirv(words) }; })
        .sort((a, b) => a.stage - b.stage);
    const FLAT = 14, NO_PERSPECTIVE = 13;
    // each stage's inputs against the outputs of the stage before it
    const decorated = (m, id, d) => !!(m.decorations.get(id) && m.decorations.get(id).has(d));
    // (an interface block matches by its block's name, not its instance's)
    const interface_name = (m, v) =>
    {
        let id = m.types.get(v.type).pointee;
        while(m.types.get(id) && m.types.get(id).kind === "array") id = m.types.get(id).element;
        return m.types.get(id) && m.types.get(id).kind === "struct" && decorated(m, id, DECORATION.Block) ? "block " + m.names.get(id) : variable_name(m, v);
    };
    for(let k = 1; k < parsed.length; k++)
    {
        const before = parsed[k - 1], after = parsed[k];
        if(after.stage === STAGE.compute) continue;
        const outputs = new Map(before.m.variables.filter(v => v.storage === STORAGE.Output && !is_builtin(before.m, v)).map(v => [interface_name(before.m, v), v]));
        // (what the stage's code reads: loads, access chains, the interpolation functions)
        const used = new Set();
        const words = after.words;
        let in_functions = false;
        for(let at = 5; at < words.length;)
        {
            const count = words[at] >>> 16, op = words[at] & 0xFFFF;
            if(!count) break;
            if(op === 54) in_functions = true;
            if(in_functions && (op === 61 || op === 65 || op === 66) && count >= 4) used.add(words[at + 3]);
            if(in_functions && op === 12 && count >= 6) used.add(words[at + 5]);
            at += count;
        }
        const es300 = [before, after].every(x => shaders.some(s => STAGE[s.stage] === x.stage && glsl_version(s.source) === 300));
        for(const v of after.m.variables)
        {
            if(v.storage !== STORAGE.Input || is_builtin(after.m, v)) continue;
            const name = interface_name(after.m, v);
            const output = outputs.get(name);
            if(!output)
            {
                if(used.has(v.id)) return "ERROR: Linking " + STAGE_NAME[after.stage] + " stage: input " + name + " is not written by the " + STAGE_NAME[before.stage] + " stage";
                continue;
            }
            if(es300 && (decorated(before.m, output.id, FLAT) !== decorated(after.m, v.id, FLAT) ||
                decorated(before.m, output.id, NO_PERSPECTIVE) !== decorated(after.m, v.id, NO_PERSPECTIVE)))
            {
                return "ERROR: Linking " + STAGE_NAME[after.stage] + " stage: interpolation of " + name + " differs from the " + STAGE_NAME[before.stage] + " stage's";
            }
        }
    }
    return null;
}

/** SPIR-V's numeric types as GL's: the base's enums of 1 to 4 components, matrices by [columns][rows] */
const GL_OF = { float: [0x1406, 0x8B50, 0x8B51, 0x8B52], int: [0x1404, 0x8B53, 0x8B54, 0x8B55], uint: [0x1405, 0x8DC6, 0x8DC7, 0x8DC8],
    bool: [0x8B56, 0x8B57, 0x8B58, 0x8B59] };
const GL_MATRICES = { 2: { 2: 0x8B5A, 3: 0x8B65, 4: 0x8B66 }, 3: { 2: 0x8B67, 3: 0x8B5B, 4: 0x8B68 }, 4: { 2: 0x8B69, 3: 0x8B6A, 4: 0x8B5C } };

/**
 * The GLSL type of an output's element or member ("v[1]", "s.a", "s[2].b"
 * by the code pass's names), and whether it is an integer's, or null
 * @return {?{glsl: string, integer: boolean}}
 */
function element_type(m, path)
{
    const steps = path.match(/^\w+|\[\d+\]|\.\w+/g);
    if(!steps || steps.join("") !== path) return null;
    const v = m.variables.find(x => x.storage === STORAGE.Output && variable_name(m, x) === steps[0] && !is_builtin(m, x));
    if(!v) return null;
    let id = m.types.get(v.type).pointee;
    for(const step of steps.slice(1))
    {
        const t = m.types.get(id);
        if(step[0] === "[")
        {
            if(!t || t.kind !== "array" || +step.slice(1, -1) >= array_length(m, t)) return null;
            id = t.element;
        }
        else
        {
            const member = t && t.kind === "struct" ? (m.member_names.get(id) || []).indexOf(step.slice(1)) : -1;
            if(member < 0) return null;
            id = t.members[member];
        }
    }
    const t = m.types.get(id);
    const scalar = s => s.kind === "float" ? "" : s.signed ? "i" : "u";
    if(t.kind === "matrix")
    {
        const column = m.types.get(t.column);
        return { glsl: t.columns === column.size ? `mat${t.columns}` : `mat${t.columns}x${column.size}`, integer: false };
    }
    if(t.kind === "vector")
    {
        const s = m.types.get(t.component);
        return s.kind === "bool" ? null : { glsl: `${scalar(s)}vec${t.size}`, integer: s.kind === "int" };
    }
    if(t.kind === "float") return { glsl: "float", integer: false };
    if(t.kind === "int") return { glsl: t.signed ? "int" : "uint", integer: true };
    return null;
}

/** An output of a module as a transform feedback varying (type, size, components, bytes), or null */
function varying_of(m, name, gl_name)
{
    const builtin = { gl_Position: [0x8B52, 4], gl_PointSize: [0x1406, 1] }[gl_name];
    if(builtin) return { name: gl_name, type: builtin[0], size: 1, components: builtin[1], bytes: 4 * builtin[1] };
    const v = m.variables.find(x => x.storage === STORAGE.Output && variable_name(m, x) === name && !is_builtin(m, x));
    if(!v) return null;
    let t = m.types.get(m.types.get(v.type).pointee), size = 1;
    if(t.kind === "array") { size = m.constants.get(t.length_id) || 1; t = m.types.get(t.element); }
    const scalar = id => { const s = m.types.get(id); return s.kind === "float" ? "float" : s.kind === "bool" ? "bool" : s.signed ? "int" : "uint"; };
    let type, components;
    if(t.kind === "matrix")
    {
        const column = m.types.get(t.column);
        type = GL_MATRICES[t.columns][column.size];
        components = t.columns * column.size;
    }
    else if(t.kind === "vector") { type = GL_OF[scalar(t.component)][t.size - 1]; components = t.size; }
    else if(t.kind === "struct") return null;
    else { type = GL_OF[t.kind === "float" ? "float" : t.kind === "bool" ? "bool" : t.signed ? "int" : "uint"][0]; components = 1; }
    return { name: gl_name, type, size, components, bytes: 4 * components * size };
}

/** What of a link's result the page needs (it has no glslang): the GL view, the bindings, the SPIR-V */
const PACKED_FIELDS = ["ok", "log", "attributes", "uniforms", "blocks", "storage_blocks", "bindings", "local_size", "default_block_size",
    "tf_varyings", "tf_mode", "outputs", "geometry", "unused_inputs", "blend_support", "tessellation"];

/**
 * A link's result as bytes (GLES.PROGRAM_LINK's): a u32 JSON length, the
 * JSON, padding to 4, then each stage's u32 word count and words
 * @param {!Object} info link_glslang_program's
 * @return {!Uint8Array}
 */
export function pack_program(info)
{
    const json = new TextEncoder().encode(JSON.stringify(Object.assign(Object.fromEntries(PACKED_FIELDS.map(f => [f, info[f]])),
        { stages: info.spirv.map(m => [m.stage, m.model]) })));
    const head = 4 + (json.length + 3 & ~3);
    const bytes = new Uint8Array(head + info.spirv.reduce((n, m) => n + 4 + 4 * m.words.length, 0));
    const view = new DataView(bytes.buffer);
    view.setUint32(0, json.length, true);
    bytes.set(json, 4);
    let at = head;
    for(const m of info.spirv)
    {
        view.setUint32(at, m.words.length, true);
        bytes.set(new Uint8Array(m.words.buffer, m.words.byteOffset, m.words.byteLength), at + 4);
        at += 4 + 4 * m.words.length;
    }
    return bytes;
}

/**
 * The module marked for vx_naga's blockarrays.rs (its CONSECUTIVE): an
 * instance array's elements have SPIR-V bindings of their own here, the
 * array's plus the index (BINDING's ranges, a block each), which its
 * elements' variables take (any binding, any length)
 * @param {!Uint32Array} words
 * @return {!Uint32Array}
 */
function consecutive_elements(words)
{
    const text = new TextEncoder().encode("vx consecutive block elements");
    const marker = new Uint32Array(1 + (text.length >> 2) + 1);
    new Uint8Array(marker.buffer).set(text, 4);
    marker[0] = marker.length << 16 | 330; // OpModuleProcessed
    // (with the debug instructions: before the first annotation, type, constant or variable)
    let at = 5;
    while(at < words.length)
    {
        const op = words[at] & 0xFFFF;
        if(op >= 71 && op <= 75 || op === 332 || op >= 19 && op <= 59) break;
        at += words[at] >>> 16 || 1;
    }
    const out = new Uint32Array(words.length + marker.length);
    out.set(words.subarray(0, at));
    out.set(marker, at);
    out.set(words.subarray(at), at + marker.length);
    return out;
}

/**
 * The shaders' struct declarations: each one's members (type, name,
 * array dimensions) in order
 * @return {!Map<string, !Array<{type: string, name: string, dims: !Array<number>}>>}
 */
function struct_declarations(shaders)
{
    const structs = new Map();
    for(const s of shaders)
    {
        const source = s.source.replace(/\/\/[^\n]*|\/\*[\s\S]*?\*\//g, "");
        for(const m of source.matchAll(/\bstruct\s+(\w+)\s*\{([^}]*)\}/g))
        {
            const members = [];
            for(const declaration of m[2].split(";"))
            {
                const words = declaration.replace(/\b(?:lowp|mediump|highp)\b/g, "").trim().match(/^(\w+)\s+([\s\S]+)$/);
                if(!words) continue;
                for(const d of words[2].split(","))
                {
                    const one = /^\s*(\w+)\s*((?:\[\s*\d+\s*\])*)\s*$/.exec(d);
                    if(one) members.push({ type: words[1], name: one[1], dims: (one[2].match(/\d+/g) || []).map(Number) });
                }
            }
            structs.set(m[1], members);
        }
    }
    return structs;
}

/** The uniform locations a value of a type takes: a basic type's one, a struct's its members' */
function uniform_locations(type, structs)
{
    const members = structs.get(type);
    if(!members) return 1;
    return members.reduce((n, m) => n + m.dims.reduce((k, d) => k * d, 1) * uniform_locations(m.type, structs), 0);
}

/**
 * A reflected uniform's location past its declaration's ("s.b[1]", "a[2][0]"):
 * the elements and members before it, in order; -1 where the declarations
 * do not say
 * @param {{type: string, dims: !Array<number>}} declaration
 * @return {number}
 */
function location_offset(declaration, name, structs)
{
    const steps = name.match(/^\w+|\[\d+\]|\.\w+/g);
    if(!steps || steps.join("") !== name) return -1;
    let type = declaration.type, dims = declaration.dims, offset = 0;
    for(const step of steps.slice(1))
    {
        if(step[0] === "[")
        {
            if(!dims.length) return -1;
            offset += +step.slice(1, -1) * dims.slice(1).reduce((n, d) => n * d, 1) * uniform_locations(type, structs);
            dims = dims.slice(1);
            continue;
        }
        const members = structs.get(type);
        const at = members ? members.findIndex(m => m.name === step.slice(1)) : -1;
        if(at < 0 || dims.length) return -1;
        for(const m of members.slice(0, at)) offset += m.dims.reduce((n, d) => n * d, 1) * uniform_locations(m.type, structs);
        type = members[at].type;
        dims = members[at].dims;
    }
    return offset;
}

/**
 * A block's binding point: its layout(binding)'s (or 0); an instance
 * array's element, the array's plus the element's index (glslang reflects
 * each element with the array's), its place among the elements for an
 * array of arrays
 * @param {!Array<{name: string, binding: number}>} list the reflection's blocks of its kind
 * @param {{name: string, binding: number}} b
 */
function element_binding(list, b)
{
    if(b.binding < 0) return 0;
    const parts = /^([^[]+)((?:\[\d+\])+)$/.exec(b.name);
    if(!parts) return b.binding;
    const indices = parts[2].match(/\d+/g);
    if(indices.length === 1) return b.binding + +indices[0];
    return b.binding + list.filter(x => x.name.startsWith(parts[1] + "[")).indexOf(b);
}

/**
 * Decorations naga refuses or writes as WGSL that is not, the decoration
 * RelaxedPrecision in their place (which it ignores):
 * - writeonly storage blocks (NonReadable on their members or variables),
 *   which naga refuses: readable (a shader GL took never reads them);
 * - coherent and volatile variables (buffers, images), which naga writes
 *   as @coherent and @volatile: WebGPU's storage is coherent within a
 *   dispatch, its barriers order it
 * @param {!Uint32Array} words
 * @param {!Object} m parse_spirv's
 */
function naga_decorations(words, m)
{
    const NON_READABLE = 25, COHERENT = 23, VOLATILE = 21, RELAXED_PRECISION = 0;
    const blocks = new Set(), buffers = new Set(), variables = new Set(m.variables.map(v => v.id));
    for(const v of m.variables)
    {
        if(v.storage !== STORAGE.StorageBuffer && v.storage !== STORAGE.Uniform) continue;
        buffers.add(v.id);
        blocks.add(innermost(m, m.types.get(v.type).pointee));
    }
    for(let at = 5; at < words.length;)
    {
        const count = words[at] >>> 16, op = words[at] & 0xFFFF;
        if(!count) break;
        if(op === OP.Decorate && count === 3 && (words[at + 2] === NON_READABLE && buffers.has(words[at + 1]) ||
            (words[at + 2] === COHERENT || words[at + 2] === VOLATILE) && variables.has(words[at + 1])))
        {
            words[at + 2] = RELAXED_PRECISION;
        }
        if(op === OP.MemberDecorate && count === 4 && words[at + 3] === NON_READABLE && blocks.has(words[at + 1])) words[at + 3] = RELAXED_PRECISION;
        at += count;
    }
}

/**
 * pack_program's bytes as the result again (the locations' maps made anew)
 * @param {!Uint8Array} bytes
 * @return {!Object}
 */
export function unpack_program(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const length = view.getUint32(0, true);
    const info = JSON.parse(new TextDecoder().decode(bytes.subarray(4, 4 + length)));
    let at = 4 + (length + 3 & ~3);
    info.spirv = info.stages.map(([stage, model]) =>
    {
        const count = view.getUint32(at, true);
        const words = new Uint32Array(bytes.slice(at + 4, at + 4 + 4 * count).buffer);
        at += 4 + 4 * count;
        return { stage, model, words };
    });
    delete info.stages;
    info.locations = new Map();
    info.by_location = [];
    for(const u of info.uniforms)
    {
        if(u.location < 0) continue;
        info.locations.set(u.base, u.location);
        for(let i = 0; i < u.size; i++)
        {
            if(u.size > 1 || u.name !== u.base) info.locations.set(u.base + "[" + i + "]", u.location + i);
            info.by_location[u.location + i] = { uniform: u, element: i };
        }
    }
    return info;
}
                                                                                                   source/v64/src/gles/glslang.js                                                                      0000644 0000000 0000000 00000015365 00000000000 013404  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // glslang for the GLES host (docs/gles3-plan.md, "着色器的数据流"): the
// module tools/glslang/build.sh builds (bios/glslang.wasm; its interface
// tools/glslang/v86_glslang.cpp), synchronous once instantiated, as the
// shadow state answers glCompileShader and glLinkProgram at once.
//
// check_shader, check_program: OpenGL ES's rules at the shader's own
// version; the info logs and GL's reflection. program_spirv: each stage's
// SPIR-V under Vulkan's relaxed rules, with that program's reflection.

/** glslang's EShLanguage, by GL's shader type */
export const STAGE = { vertex: 0, tess_control: 1, tess_evaluation: 2, geometry: 3, fragment: 4, compute: 5 };
export const STAGE_OF_GL_TYPE = new Map([[0x8B31, 0], [0x8E88, 1], [0x8E87, 2], [0x8DD9, 3], [0x8B30, 4], [0x91B9, 5]]);

const ERRNO_NOSYS = 52;

/**
 * Compile the module (asynchronously: browsers refuse large modules
 * compiled synchronously on the page's thread)
 * @param {!ArrayBuffer|!Uint8Array} bytes
 * @return {!Promise<!WebAssembly.Module>}
 */
export function compile_glslang(bytes)
{
    return WebAssembly.compile(bytes);
}

/**
 * An instance of the module
 * @param {!WebAssembly.Module} module
 * @return {!Promise<!Glslang>}
 */
export async function create_glslang(module)
{
    const glslang = new Glslang();
    const instance = await WebAssembly.instantiate(/** @type {?} */ (module), glslang.imports());
    glslang.exports = instance.exports;
    glslang.exports["_initialize"]();
    return glslang;
}

/** @constructor */
export function Glslang()
{
    /** @type {!Object} */
    this.exports = {};
    /** what glslang printed (it should print nothing) */
    this.printed = "";
    /** @type {Object<string, number>} the limits set last */
    this.limits = null;
}

/** @return {!Uint8Array} the module's memory as it is (it may grow) */
Glslang.prototype.memory = function()
{
    return new Uint8Array(this.exports["memory"].buffer);
};

Glslang.prototype.imports = function()
{
    const view = () => new DataView(this.exports["memory"].buffer);
    return {
        "env": {
            "emscripten_notify_memory_growth": () => {},
            "__syscall_getcwd": () => -ERRNO_NOSYS,
        },
        "wasi_snapshot_preview1": {
            "fd_write": (fd, iovs, count, written) =>
            {
                let total = 0;
                for(let i = 0; i < count; i++)
                {
                    const pointer = view().getUint32(iovs + 8 * i, true), length = view().getUint32(iovs + 8 * i + 4, true);
                    this.printed += new TextDecoder().decode(this.memory().subarray(pointer, pointer + length));
                    total += length;
                }
                view().setUint32(written, total, true);
                return 0;
            },
            "fd_close": () => 0,
            "fd_seek": () => ERRNO_NOSYS,
            "environ_sizes_get": (count, size) => { view().setUint32(count, 0, true); view().setUint32(size, 0, true); return 0; },
            "environ_get": () => 0,
        },
    };
};

/**
 * Bytes into the module's memory, for one call
 * @param {!Uint8Array} bytes
 * @param {function(number):*} call with the pointer
 */
Glslang.prototype.with_bytes = function(bytes, call)
{
    const pointer = this.exports["v86_glslang_alloc"](Math.max(1, bytes.length));
    this.memory().set(bytes, pointer);
    try
    {
        return call(pointer);
    }
    finally
    {
        this.exports["v86_glslang_free"](pointer);
    }
};

/** @return {!Uint8Array} the last call's output (a copy) */
Glslang.prototype.output = function()
{
    const pointer = this.exports["v86_glslang_output"](), size = this.exports["v86_glslang_output_size"]();
    return this.memory().slice(pointer, pointer + size);
};

/**
 * The limits gl_Max* and the checks see
 * @param {!Object<string, number>} limits by glslangValidator's names ("MaxDrawBuffers")
 */
Glslang.prototype.set_limits = function(limits)
{
    if(limits === this.limits) return;
    this.limits = limits;
    const text = Object.entries(limits).map(([name, value]) => name + " " + value).join("\n") + "\n";
    this.with_bytes(new TextEncoder().encode(text + "\0"), pointer => this.exports["v86_glslang_limits"](pointer));
};

/**
 * @param {!Array<{stage: number, source: string}>} shaders
 * @return {!Uint8Array} as the module takes them
 */
function pack(shaders)
{
    const encoded = shaders.map(s => new TextEncoder().encode(s.source));
    const bytes = new Uint8Array(encoded.reduce((n, e) => n + 8 + (e.length + 3 & ~3), 0));
    const view = new DataView(bytes.buffer);
    let at = 0;
    shaders.forEach((s, i) =>
    {
        view.setUint32(at, s.stage, true);
        view.setUint32(at + 4, encoded[i].length, true);
        bytes.set(encoded[i], at + 8);
        at += 8 + (encoded[i].length + 3 & ~3);
    });
    return bytes;
}

/**
 * One shader, OpenGL ES's rules
 * @param {number} stage STAGE's
 * @param {string} source
 * @return {{ok: boolean, log: string}}
 */
Glslang.prototype.check_shader = function(stage, source)
{
    const packed = pack([{ stage, source }]);
    const ok = this.with_bytes(packed, pointer => this.exports["v86_glslang_compile"](pointer, packed.length));
    return { ok: !!ok, log: new TextDecoder().decode(this.output()) };
};

/**
 * A program, OpenGL ES's rules
 * @param {!Array<{stage: number, source: string}>} shaders
 * @param {number=} flags
 * @return {!Object} {ok, log} and GL's reflection: uniforms, uniformBlocks,
 *     bufferVariables, bufferBlocks, inputs, outputs, atomicCounters, localSize
 */
Glslang.prototype.check_program = function(shaders, flags)
{
    const packed = pack(shaders);
    this.with_bytes(packed, pointer => this.exports["v86_glslang_link"](pointer, packed.length, flags || 0));
    return JSON.parse(new TextDecoder().decode(this.output()));
};

/**
 * A program's SPIR-V, Vulkan's relaxed rules
 * @param {!Array<{stage: number, source: string}>} shaders
 * @param {number=} flags
 * @return {!Object} {ok, log, reflection fields as check_program's, modules: [{stage, words}]}
 */
Glslang.prototype.program_spirv = function(shaders, flags)
{
    const packed = pack(shaders);
    this.with_bytes(packed, pointer => this.exports["v86_glslang_spirv"](pointer, packed.length, flags || 0));
    const out = this.output();
    const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
    const json_length = view.getUint32(0, true);
    const result = JSON.parse(new TextDecoder().decode(out.subarray(4, 4 + json_length)));
    result.modules = [];
    for(let at = 4 + json_length + 3 & ~3; at + 8 <= out.length;)
    {
        const stage = view.getUint32(at, true), count = view.getUint32(at + 4, true);
        result.modules.push({ stage, words: new Uint32Array(out.slice(at + 8, at + 8 + 4 * count).buffer) });
        at += 8 + 4 * count;
    }
    return result;
};
                                                                                                                                                                                                                                                                           source/v64/src/gles/page/entry.js                                                                   0000644 0000000 0000000 00000000637 00000000000 014026  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GLES executor in the page's WebGPU bundle (libv86-webgpu.js, built by
// tools/build_glbridge.mjs with esbuild): the SVGA renderer runs stream
// "gles" with it (src/browser/glbridge/svga_renderer.js). gl-webgpu's GLSL
// front end is the bundle's own (GLShaderTranslator, GLStateLayout).

import { GLESExecutor } from "./gles_executor.js";

globalThis["V86GLESExecutor"] = { "GLESExecutor": GLESExecutor };
                                                                                                 source/v64/src/gles/page/gles1_draw.js                                                              0000644 0000000 0000000 00000022407 00000000000 014714  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 1.1's draws on the page (docs/gles-proxy-plan.md E4): the shadow's
// fixed-function state (src/gles/gles1_state.js) turned into gl-webgpu's
// fixed-function signature and state block (gl_fixed_function.js,
// gl_state_layout.js: the XP path's generator, shared as it is), and the
// draw's vertices from the client arrays or the current values; the
// draw_texture extension's rectangles.

import { GL } from "../gles_formats.js";
import { UNITS, mat_inverse, mat_mul } from "../gles1_state.js";

const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
const ENV_MODES = { 0x2100: "MODULATE", 0x2101: "DECAL", 0x0BE2: "BLEND", 0x0104: "ADD", 0x1E01: "REPLACE", 0x8570: "COMBINE" };
const COMBINE = { 0x1E01: "REPLACE", 0x2100: "MODULATE", 0x0104: "ADD", 0x8574: "ADD_SIGNED", 0x8575: "INTERPOLATE", 0x84E7: "SUBTRACT",
    0x86AE: "DOT3_RGB", 0x86AF: "DOT3_RGBA" };
const SOURCES = { 0x1702: "TEXTURE", 0x8576: "CONSTANT", 0x8577: "PRIMARY_COLOR", 0x8578: "PREVIOUS" };
const OPERANDS = { 0x0300: "SRC_COLOR", 0x0301: "ONE_MINUS_SRC_COLOR", 0x0302: "SRC_ALPHA", 0x0303: "ONE_MINUS_SRC_ALPHA" };
const ALPHA_FUNCS = { 0x0200: "never", 0x0201: "less", 0x0202: "equal", 0x0203: "lequal", 0x0204: "greater", 0x0205: "notequal",
    0x0206: "gequal", 0x0207: "always" };
const FORMATS = { [GL.RGBA]: "RGBA", [GL.BGRA_EXT]: "RGBA", [GL.RGB]: "RGB", [GL.ETC1_RGB8_OES]: "RGB", [GL.ALPHA]: "ALPHA",
    [GL.LUMINANCE]: "LUMINANCE", [GL.LUMINANCE_ALPHA]: "LUMINANCE_ALPHA" };

/** @param {!Array<number>} m @return {boolean} */
const is_identity = m => m.every((v, i) => v === IDENTITY[i]);

/** The bound texture a fixed-function unit samples, if the unit is enabled and has one */
export function unit_texture(c, unit)
{
    const enabled = c.ff.texture_enabled[unit];
    const target = enabled[GL.TEXTURE_EXTERNAL_OES] ? GL.TEXTURE_EXTERNAL_OES : enabled[GL.TEXTURE_2D] ? GL.TEXTURE_2D : 0;
    if(!target) return null;
    const name = c.textures[unit][target === GL.TEXTURE_2D ? 0 : 2];
    const texture = name ? c.group.textures.get(name) : c.defaults && c.defaults.get(target);
    return texture && texture.images.get(0) ? texture : null;
}

/**
 * The fixed-function signature of the context's state for a draw
 * @param {!Object} c
 * @param {boolean} points a draw of points (sprites)
 * @param {?Array<!Object>} textures by unit (unit_texture's)
 */
export function ff_signature(c, points, textures)
{
    const ff = c.ff;
    const on = cap => c.enabled.has(cap);
    const lighting = on(0x0B50);
    const signature = {
        attributes: {
            position: { components: ff.arrays.vertex.enabled ? ff.arrays.vertex.size : 4 },
            normal: lighting, color: true, secondaryColor: false, fogCoord: false,
            texCoord: textures.map(t => t ? { components: 4 } : null),
        },
        lighting: {
            enabled: lighting, twoSide: !!ff.light_model.two_side, localViewer: false, separateSpecular: false,
            normalMode: on(0x0BA1) ? "normalize" : on(0x803A) ? "rescale" : "none",
            colorMaterial: on(0x0B57) ? { enabled: true, face: "FRONT_AND_BACK", mode: "AMBIENT_AND_DIFFUSE" } : { enabled: false },
            lights: ff.lights.map((l, i) => ({ enabled: on(0x4000 + i), positional: l.position[3] !== 0, spot: l.spot_cutoff !== 180 })),
        },
        fog: on(0x0B60) ? { enabled: true, mode: { 0x2601: "linear", 0x0800: "exp", 0x0801: "exp2" }[ff.fog.mode], coordSource: "depth" } :
            { enabled: false },
        texture: textures.map((t, i) =>
        {
            if(!t) return { enabled: false };
            const e = ff.env[i];
            const env = { mode: ENV_MODES[e.mode], coordReplace: !!e.coord_replace };
            if(e.mode === 0x8570)
            {
                Object.assign(env, { combineRGB: COMBINE[e.combine_rgb], combineAlpha: COMBINE[e.combine_alpha],
                    srcRGB: e.src_rgb.map(s => SOURCES[s]), operandRGB: e.operand_rgb.map(o => OPERANDS[o]),
                    srcAlpha: e.src_alpha.map(s => SOURCES[s]), operandAlpha: e.operand_alpha.map(o => OPERANDS[o]),
                    rgbScale: e.rgb_scale, alphaScale: e.alpha_scale });
            }
            const base = t.images.get(0);
            return { enabled: true, target: "2D", shadow: false, format: FORMATS[base.format] || "RGBA",
                matrix: !is_identity(ff.stacks[0x1702][i].at(-1)), texGen: [null, null, null, null], env };
        }),
        alphaTest: on(0x0BC0) ? ALPHA_FUNCS[ff.alpha_func] : "always",
        clipPlaneCount: ff.clip_planes.reduce((n, p, i) => on(0x3000 + i) ? i + 1 : n, 0),
        pointSprite: points && on(0x8861),
        flatShading: ff.shade_model === 0x1D00,
        colorTargets: 1,
    };
    return signature;
}

/** The state block's snapshot (gl_state_layout.js's fields) of a GLES 1.1 context */
export function ff_snapshot(c, viewport)
{
    const ff = c.ff;
    const modelview = ff.stacks[0x1700].at(-1), projection = ff.stacks[0x1701].at(-1);
    const mv_inverse = mat_inverse(modelview);
    // the normal matrix: the inverse transpose of the modelview's upper 3 by 3
    const normal = [mv_inverse[0], mv_inverse[4], mv_inverse[8], mv_inverse[1], mv_inverse[5], mv_inverse[9], mv_inverse[2], mv_inverse[6], mv_inverse[10]];
    const textures = Array.from({ length: 8 }, (_, i) => i < UNITS ? ff.stacks[0x1702][i].at(-1) : IDENTITY);
    const material = { emission: ff.material.emission, ambient: ff.material.ambient, diffuse: ff.material.diffuse, specular: ff.material.specular,
        shininess: ff.material.shininess };
    const lights = ff.lights.map(l =>
    {
        const [px, py, pz] = l.position;
        const length = Math.hypot(px, py, pz) || 1;
        const h = [px / length, py / length, pz / length + 1];
        const hl = Math.hypot(...h) || 1;
        return { ambient: l.ambient, diffuse: l.diffuse, specular: l.specular, position: l.position, halfVector: [h[0] / hl, h[1] / hl, h[2] / hl, 0],
            spotDirection: l.spot_direction, spotExponent: l.spot_exponent, spotCutoff: l.spot_cutoff,
            spotCosCutoff: l.spot_cutoff === 180 ? -1 : Math.cos(l.spot_cutoff * Math.PI / 180),
            constantAttenuation: l.attenuation[0], linearAttenuation: l.attenuation[1], quadraticAttenuation: l.attenuation[2] };
    });
    const scene = [0, 1, 2].map(i => material.emission[i] + material.ambient[i] * ff.light_model.ambient[i]).concat([material.diffuse[3]]);
    const products = ff.lights.map(l => ({ ambient: material.ambient.map((v, i) => v * l.ambient[i]),
        diffuse: material.diffuse.map((v, i) => v * l.diffuse[i]), specular: material.specular.map((v, i) => v * l.specular[i]) }));
    const zero = () => [0, 0, 0, 0];
    return {
        matrices: { modelview, projection, mvp: mat_mul(projection, modelview), normal, modelviewInverse: mv_inverse,
            texture: textures, textureInverse: textures, textureTranspose: textures, textureInverseTranspose: textures,
            modelviewTranspose: IDENTITY, modelviewInverseTranspose: IDENTITY, projectionInverse: IDENTITY, projectionTranspose: IDENTITY,
            projectionInverseTranspose: IDENTITY, mvpInverse: IDENTITY, mvpTranspose: IDENTITY, mvpInverseTranspose: IDENTITY },
        lights, material: { front: material, back: material }, lightModel: { ambient: ff.light_model.ambient },
        derived: { frontSceneColor: scene, backSceneColor: scene, frontLightProduct: products, backLightProduct: products },
        fog: { color: ff.fog.color, density: ff.fog.density, start: ff.fog.start, end: ff.fog.end },
        texEnvColor: Array.from({ length: 8 }, (_, i) => i < UNITS ? ff.env[i].color : zero()),
        texGen: Array.from({ length: 8 }, () => Array.from({ length: 4 }, () => ({ objectPlane: zero(), eyePlane: zero() }))),
        clipPlanes: ff.clip_planes.map((p, i) => c.enabled.has(0x3000 + i) ? p : zero()),
        depthRange: { near: c.depth_range[0], far: c.depth_range[1] },
        point: { size: ff.point.size, sizeMin: ff.point.min, sizeMax: Math.max(ff.point.min, Math.min(ff.point.max, 256)),
            fadeThreshold: ff.point.fade, attenuation: ff.point.attenuation },
        alphaRef: ff.alpha_ref,
        viewport: { x: viewport[0], y: viewport[1], width: viewport[2], height: viewport[3] },
        lineWidth: c.line_width, lineStipple: { pattern: 0xFFFF, factor: 1 }, polygonStippleEnabled: false, polygonStipple: new Uint8Array(128),
    };
}

/**
 * The vertex inputs of a fixed-function draw: [location, the array or a
 * constant value, its normalization] by the generator's attributes
 * @param {!Object} c
 * @param {!Array<{name: string, location: number, components: number}>} attributes the generator's
 */
export function ff_inputs(c, attributes)
{
    const ff = c.ff;
    return attributes.map(a =>
    {
        if(a.name === "position") return { location: a.location, components: a.components, array: ff.arrays.vertex, normalized: false, current: [0, 0, 0, 1] };
        if(a.name === "normal") return { location: a.location, components: 3, array: ff.arrays.normal, normalized: true, current: ff.normal };
        if(a.name === "color") return { location: a.location, components: 4, array: ff.arrays.color, normalized: true, current: ff.color };
        const unit = +a.name.replace("texCoord", "");
        return { location: a.location, components: a.components, array: ff.arrays.texcoord[unit], normalized: false, current: ff.texcoord[unit] };
    });
}
                                                                                                                                                                                                                                                         source/v64/src/gles/page/gles3_executor.js                                                          0000644 0000000 0000000 00000627263 00000000000 015632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.x's draws on the page (docs/gles3-plan.md L3): what a context of
// api 3 does on the GPU, as methods of the GLES executor (gles_executor.js
// installs them). Its programs are glslang's (the CPU side links them and
// sends the link, PROGRAM_LINK): each stage's SPIR-V becomes WGSL through
// vx_naga (vx/naga, the Venus executor's translator) with GL's clip space
// depth and the translator's Y flip, so the orientation is GLES 2.0's
// (framebuffer row 0 is GL's bottom row).
//
// - Buffers live on the GPU (a GPUBuffer each, made at first use) with
//   their bytes on the CPU side too (the shadow's `bytes`): the guest's
//   writes go to the bytes and reach the GPU buffer before a draw needs it
//   (`dirty`); a buffer the GPU wrote (`gpu_newer`, transform feedback,
//   copies) takes the guest's writes directly.
// - Vertex arrays in buffers are the draw's vertex buffers where WebGPU has
//   their format and alignment; the others (client arrays, packed and
//   three-component types, divisors past 1) are assembled on the CPU, the
//   indices then too (from the vertex range's first). Fans and loops become
//   lists; a fixed restart index ends a list's primitive or restarts a strip.
// - Textures have their sized format's WebGPU format (gles_formats3.js), all
//   levels of one GPU texture from the lowest level given; 3D and array
//   textures, sampler objects, base and max levels, depth comparison;
//   integer textures are fetched (vx_naga's intsample.rs, with the sampler's
//   wraps). An incomplete texture samples as (0, 0, 0, 1).
// - The draw framebuffer's draw buffers are the pass's color attachments (of
//   their own formats), multisampled renderbuffers 4 samples.

import { COMPRESSED_FORMATS, F, format_info, tex_image_format } from "../gles_formats3.js";
import { GL3 } from "../gles3_state.js";
import { ADVANCED_BLEND, BLEND_CONSTANT, SAMPLES_CONSTANT } from "../glsl_es_rewrite.js";
import { BINDING, gl_type } from "../glsl_program.js";
import { DRAWN_DEPTH, RENDERABLE, TEXEL_BYTES, decode_texels, depth_values, from_half, pack_pixels, to_texels, unpack_image } from "./gles3_pixels.js";
import { decode_etc1 } from "./gles_textures.js";
import { B, COLOR_FORMAT, COMPARE, STENCIL_OPS, U, WRAPS, align4, blend_component } from "./gles_gpu_tables.js";

const SCRIPT = typeof document !== "undefined" && document.currentScript ? document.currentScript.src : null;
/** vx_naga.wasm: next to the page's WebGPU bundle (tools/build_glbridge.mjs) */
const NAGA_URL = SCRIPT ? new URL("vx_naga.wasm", SCRIPT).href : "vx_naga.wasm";
/** vx_naga's translation flags (vx_executor.js's TRANSLATE): the fragment depth dropped, GL's clip space depth */
const NO_DEPTH = 2, GL_DEPTH = 8;
/** WGSL's bindings of SPIR-V's: 2b (2b + 1 a combined sampler's sampler), element e > 0 of an array ELEMENTS + 2 (16b + e) */
const ELEMENTS = 300, ELEMENTS_END = 960;

const NEAREST = 0x2600, LINEAR = 0x2601, NEAREST_MIPMAP_NEAREST = 0x2700;
const RESTART = 0x8D69, CULL_FACE = 0x0B44, BLEND = 0x0BE2, DEPTH_TEST = 0x0B71, STENCIL_TEST = 0x0B90, SCISSOR_TEST = 0x0C11;
const POLYGON_OFFSET_FILL = 0x8037;
const COMPARE_REF_TO_TEXTURE = 0x884E;
/**
 * The format a compressed texture of blocks WebGPU will not take (not whole
 * blocks) is decoded into: sRGB's, EAC's 11 signed or unsigned bits in
 * halves, the rest 8 bits a channel
 */
const decoded_format = compressed => compressed.webgpu.endsWith("-srgb") ? "rgba8unorm-srgb" : compressed.webgpu.startsWith("eac-") ? "rgba16float" : "rgba8unorm";
/**
 * Whether a color format GL reads with alpha 1 (RGB8, RGB565: none of its
 * own) is kept in a WebGPU format with an alpha (rgba8unorm): such a texture
 * starts with alpha 1 and draws, clears and blits leave its alpha alone
 */
const alpha_less = (internal, webgpu) =>
{
    const info = format_info(internal);
    return !!info && info.bits[3] === 0 && info.bits[0] > 0 && info.kind !== "depth" && info.kind !== "depth_stencil" && /^(rgba|bgra)/.test(webgpu);
};
/** GLES 3.1's DEPTH_STENCIL_TEXTURE_MODE: the stencil of a depth and stencil texture sampled */
const STENCIL_INDEX = 0x1901;
const TOPOLOGY = ["point-list", "line-list", "line-list", "line-strip", "triangle-list", "triangle-strip", "triangle-list"];
const INDEX_BYTES = { 0x1401: 1, 0x1403: 2, 0x1405: 4 };
const STRIP_END = 0xFFFFFFFF;

/** The texture slot (gles3_state.js's SLOT) of a sampler type, and each slot's target */
const SAMPLER_SLOT = new Map([[0x8B5E, 0], [0x8B62, 0], [0x8DCA, 0], [0x8DD2, 0], [0x8B60, 1], [0x8DC5, 1], [0x8DCC, 1], [0x8DD4, 1],
    [0x8D66, 2], [0x8B5F, 3], [0x8DCB, 3], [0x8DD3, 3], [0x8DC1, 4], [0x8DC4, 4], [0x8DCF, 4], [0x8DD7, 4], [0x9108, 5], [0x9109, 5], [0x910A, 5],
    [0x900C, 6], [0x900D, 6], [0x900E, 6], [0x900F, 6]]);
const SLOT_TARGET = [GL3.TEXTURE_2D, GL3.TEXTURE_CUBE_MAP, GL3.TEXTURE_EXTERNAL_OES, GL3.TEXTURE_3D, GL3.TEXTURE_2D_ARRAY, 0x9100, 0x9009];
/** What a texture unit samples with nothing bound */
const NO_SAMPLER = { min_filter: NEAREST, mag_filter: NEAREST, wrap_s: 0x812F, wrap_t: 0x812F, wrap_r: 0x812F, compare_func: 0x0203 };
/** Vulkan's address modes (vx_naga's int_wraps): repeat 0, mirrored repeat 1, clamp to edge 2 */
const VK_WRAP = { 0x2901: 0, 0x8370: 1, 0x812F: 2, 0x812D: 3 };
/** GLES 3.2's advanced blend equations: their index (glsl_es_rewrite.js's BLEND_CONSTANT) */
const ADVANCED_INDEX = new Map(ADVANCED_BLEND.map(([e], i) => [e, i]));
/** The advanced blend equation's index a draw blends by, or -1 */
const advanced_blend = c => c.version >= 32 && c.enabled.has(BLEND) && ADVANCED_INDEX.has(c.blend_equation[0]) ? ADVANCED_INDEX.get(c.blend_equation[0]) : -1;
/** vx_naga's border.rs: a border color component's entry in the wraps list */
const BORDER_COLOR = 0x80000000;

/** WebGPU's storage texture formats (GLES 3.1's image formats as WebGPU has them) */
const STORAGE_FORMATS = new Set(["rgba8unorm", "rgba8snorm", "rgba8uint", "rgba8sint", "rgba16uint", "rgba16sint", "rgba16float", "r32uint", "r32sint",
    "r32float", "rg32uint", "rg32sint", "rg32float", "rgba32uint", "rgba32sint", "rgba32float"]);

/** The renderbuffer formats that are no sized texture format */
const RENDERBUFFER_WEBGPU = { 0x8D48: "stencil8", 0x81A7: "depth32float" };

/** WebGPU's vertex formats as VkFormats (vx_naga's xfb.rs reads vertex buffers by them) */
const VK_FORMAT = {
    "float32": 100, "float32x2": 103, "float32x3": 106, "float32x4": 109, "sint32": 99, "sint32x2": 102, "sint32x3": 105, "sint32x4": 108,
    "uint32": 98, "uint32x2": 101, "uint32x3": 104, "uint32x4": 107, "unorm8x2": 16, "snorm8x2": 17, "uint8x2": 20, "sint8x2": 21,
    "unorm8x4": 37, "snorm8x4": 38, "uint8x4": 41, "sint8x4": 42, "unorm16x2": 77, "snorm16x2": 78, "uint16x2": 81, "sint16x2": 82,
    "float16x2": 83, "unorm16x4": 91, "snorm16x4": 92, "uint16x4": 95, "sint16x4": 96, "float16x4": 97,
};

/** Vertex attribute types: their bytes */
const TYPE_BYTES = { 0x1400: 1, 0x1401: 1, 0x1402: 2, 0x1403: 2, 0x1404: 4, 0x1405: 4, 0x1406: 4, 0x140C: 4, 0x140B: 2, 0x8D61: 2, 0x8D9F: 4,
    0x8368: 4 };
const INT_2_10_10_10_REV = 0x8D9F, UNSIGNED_INT_2_10_10_10_REV = 0x8368;
const packed_attribute = type => type === INT_2_10_10_10_REV || type === UNSIGNED_INT_2_10_10_10_REV;
/** The vertex formats of CPU-assembled attributes, by the shader's input kind */
const CPU_FORMAT = { f: "float32", i: "sint32", u: "uint32" };

/** GLES 2.0's unsized images of OES_texture_float, _half_float and OES_depth_texture as sized formats */
const UNSIZED_EXTENSIONS = { [F.RGBA]: { [F.FLOAT]: 0x8814, [F.HALF_FLOAT_OES]: 0x881A }, [F.RGB]: { [F.FLOAT]: 0x8815, [F.HALF_FLOAT_OES]: 0x881B },
    [F.DEPTH_COMPONENT]: { [F.UNSIGNED_SHORT]: 0x81A5, [F.UNSIGNED_INT]: 0x81A6 }, [F.DEPTH_STENCIL]: { [F.UNSIGNED_INT_24_8]: 0x88F0 } };

/**
 * An image's format as a sized one (or a legacy or compressed one): GLES
 * 3.0's images say it (`internal`), GLES 2.0's have their format and type
 */
function image_internal(image)
{
    if(image.internal) return image.internal;
    const own = UNSIZED_EXTENSIONS[image.format] && UNSIZED_EXTENSIONS[image.format][image.type];
    if(own) return own;
    const sized = tex_image_format(image.format, image.format, image.type);
    return sized.error ? image.format : sized.internal;
}

/** An unused vertex input's attribute (glsl_program.js's unused_inputs): its array disabled, its value (0, 0, 0, 1) */
const UNUSED_INPUT = { enabled: false, current: [0, 0, 0, 1] };

/** The pixel store's state a GLES 2.0 context lacks */
const NO_STORE = { row_length: 0, image_height: 0, skip_pixels: 0, skip_rows: 0, skip_images: 0 };

/** @return {?Uint8Array} a buffer's bytes on the page (GLES 3.0's `bytes`, GLES 2.0's `data`) */
const cpu_bytes = buffer => buffer.bytes || buffer.data || null;

/**
 * The WebGPU vertex format that reads an attribute's array as the shader's
 * input wants it, or null for one assembled on the CPU
 * @param {!Object} a the attribute's state
 * @param {string} kind the input's: "f", "i", "u"
 */
function direct_format(a, kind)
{
    const n = a.size, t = a.type;
    if(kind === "f")
    {
        if(a.integer) return null;
        if(t === 0x1406) return n === 1 ? "float32" : "float32x" + n;
        if(t === 0x140B || t === 0x8D61) return n === 2 || n === 4 ? "float16x" + n : null;
        if(!a.normalized) return null;
        const name = { 0x1401: "unorm8", 0x1400: "snorm8", 0x1403: "unorm16", 0x1402: "snorm16" }[t];
        return name && (n === 2 || n === 4) ? name + "x" + n : null;
    }
    if(!a.integer) return null;
    const signed = t === 0x1400 || t === 0x1402 || t === 0x1404;
    if(signed !== (kind === "i")) return null;
    const prefix = signed ? "sint" : "uint";
    if(t === 0x1404 || t === 0x1405) return n === 1 ? prefix + "32" : prefix + "32x" + n;
    return n === 2 || n === 4 ? prefix + (t === 0x1400 || t === 0x1401 ? "8x" : "16x") + n : null;
}

/** One component of a vertex array as GLES 3.0 reads it (2.9.1: normalized ones by equation 2.2) */
function read_component(view, p, type, normalized)
{
    switch(type)
    {
        case 0x1406: return view.getFloat32(p, true);
        case 0x140C: return view.getInt32(p, true) / 65536;
        case 0x140B: case 0x8D61: return from_half(view.getUint16(p, true));
        case 0x1401: return normalized ? view.getUint8(p) / 255 : view.getUint8(p);
        case 0x1400: return normalized ? Math.max(-1, view.getInt8(p) / 127) : view.getInt8(p);
        case 0x1403: return normalized ? view.getUint16(p, true) / 65535 : view.getUint16(p, true);
        case 0x1402: return normalized ? Math.max(-1, view.getInt16(p, true) / 32767) : view.getInt16(p, true);
        case 0x1405: return normalized ? view.getUint32(p, true) / 4294967295 : view.getUint32(p, true);
        case 0x1404: return normalized ? Math.max(-1, view.getInt32(p, true) / 2147483647) : view.getInt32(p, true);
    }
    return 0;
}

/** The four components of a packed 2_10_10_10 vertex */
function read_packed(view, p, type, normalized)
{
    const v = view.getUint32(p, true);
    const parts = [v & 1023, v >>> 10 & 1023, v >>> 20 & 1023, v >>> 30];
    if(type === UNSIGNED_INT_2_10_10_10_REV) return normalized ? parts.map((x, i) => x / (i === 3 ? 3 : 1023)) : parts;
    const signed = parts.map((x, i) => i === 3 ? (x >= 2 ? x - 4 : x) : x >= 512 ? x - 1024 : x);
    return normalized ? signed.map((x, i) => Math.max(-1, x / (i === 3 ? 1 : 511))) : signed;
}

/** A WGSL texture type's dimension and sample kind */
function texture_type(type)
{
    const m = /^texture_(depth_)?(multisampled_)?(1d|2d_array|2d|3d|cube_array|cube)(?:<(\w+)>)?/.exec(type || "");
    if(!m) return { dimension: "2d", sample: "float", multisampled: false };
    return { dimension: m[3].replace("_", "-"), multisampled: !!m[2], sample: m[1] ? "depth" : m[4] === "i32" ? "sint" : m[4] === "u32" ? "uint" : "float" };
}

/** The resource variables of naga's WGSL: binding to type */
function wgsl_declarations(wgsl)
{
    const declarations = new Map();
    for(const m of wgsl.matchAll(/@group\((\d+)\)\s*@binding\((\d+)\)\s*var(?:<[^>]*>)?\s+\w+\s*:\s*([^;]+);/g))
    {
        declarations.set(m[1] + ":" + m[2], m[3].trim());
    }
    return declarations;
}

/** A fragment entry point's color outputs: location to WGSL type */
function fragment_outputs(wgsl)
{
    const outputs = new Map();
    const at = wgsl.indexOf("@fragment");
    const signature = at < 0 ? null : /->\s*([^{]+)\{/.exec(wgsl.slice(at));
    if(!signature) return outputs;
    const result = signature[1].trim();
    const single = /^@location\((\d+)\)\s*(?:@\w+(?:\([^)]*\))?\s*)*([\w<>]+)/.exec(result);
    if(single)
    {
        outputs.set(+single[1], single[2]);
        return outputs;
    }
    const body = new RegExp("struct\\s+" + result + "\\s*\\{([^}]*)\\}").exec(wgsl);
    for(const m of body ? body[1].matchAll(/@location\((\d+)\)\s*(?:@\w+(?:\([^)]*\))?\s*)*\w+\s*:\s*([\w<>]+)/g) : [])
    {
        outputs.set(+m[1], m[2]);
    }
    return outputs;
}

/** SPIR-V's binding and element of a WGSL binding (vx/naga's wgsl_binding, backwards) */
function spirv_binding(binding)
{
    if(binding >= ELEMENTS && binding < ELEMENTS_END) return { b: binding - ELEMENTS >> 5, e: binding - ELEMENTS >> 1 & 15 };
    return { b: binding >> 1, e: 0 };
}

/**
 * Whether a dispatch's bind groups bind a buffer range or an image view to
 * write and also name it in another binding (GLSL's aliased buffers and
 * images, which WebGPU refuses in a dispatch)
 */
function writable_aliases(group)
{
    const ranges = [], views = [];
    for(const g of group.groups)
    {
        g.entries.forEach((entry, i) =>
        {
            const resource = g.resources[i].resource;
            if(entry.buffer && entry.buffer.type !== "uniform") ranges.push({ resource, writable: entry.buffer.type === "storage" });
            if(entry.storageTexture) views.push({ resource, writable: entry.storageTexture.access !== "read-only" });
        });
    }
    const overlap = (a, b) => a.resource.buffer === b.resource.buffer && a.resource.offset < b.resource.offset + b.resource.size &&
        b.resource.offset < a.resource.offset + a.resource.size;
    return ranges.some((a, i) => ranges.some((b, k) => k > i && (a.writable || b.writable) && overlap(a, b))) ||
        views.some((a, i) => views.some((b, k) => k > i && (a.writable || b.writable) && a.resource === b.resource));
}

/** The framebuffer a context reads (GLES 2.0's: the one it draws to) */
const read_framebuffer = c => c.read_framebuffer === undefined ? c.framebuffer : c.read_framebuffer;

/** A WebGPU format's kind for shader outputs and blending */
function format_kind(format)
{
    if(format.startsWith("depth") || format.startsWith("stencil")) return "depth";
    return format.includes("uint") ? "u" : format.includes("sint") ? "i" : "f";
}

/** @return {boolean} whether WebGPU blends into the format (no integer, no 32-bit float formats) */
const blendable = format => format_kind(format) === "f" && !format.includes("32float");

/**
 * What a copy into an image of the format keeps of the source's channels
 * (GLES 3.0 table 3.15), as a matrix (columns: each source channel's
 * weights) and an offset: luminance from red, a format without alpha's
 * alpha 1; null where the channels go as they are
 * @return {?{m: !Array<number>, b: !Array<number>}}
 */
function copy_map(info)
{
    const [r, , , a] = info.bits;
    if(info.value === F.LUMINANCE) return { m: [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], b: [0, 0, 0, 1] };
    if(info.value === F.ALPHA) return { m: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], b: [0, 0, 0, 0] };
    if(info.value === F.LUMINANCE_ALPHA) return { m: [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], b: [0, 0, 0, 0] };
    if(r && !a && info.kind !== "int" && info.kind !== "uint") return { m: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], b: [0, 0, 0, 1] };
    return null;
}

/**
 * A draw's indices as WebGPU draws them: fans as triangle lists, loops as
 * line lists, each piece between restart indices on its own (a strip's
 * restarted, a list's last primitive ended), from the lowest vertex
 * @param {!ArrayLike<number>} indices
 * @param {number} restart the restart index, -1 for none
 * @return {?{list: !Uint32Array, low: number, high: number, topology: string, strip: boolean}}
 */
function index_list(indices, mode, restart)
{
    let low = Infinity, high = -1;
    for(const v of indices) if(v !== restart) { if(v < low) low = v; if(v > high) high = v; }
    if(high < 0) return null;
    const strip = mode === 3 || mode === 5;
    const out = [];
    const piece = (from, to) =>
    {
        const n = to - from;
        const at = i => indices[from + i] - low;
        switch(mode)
        {
            case 0: case 1: case 4:
            {
                const per = mode === 0 ? 1 : mode === 1 ? 2 : 3;
                for(let i = 0; i < n - n % per; i++) out.push(at(i));
                break;
            }
            case 3: case 5:
                if(n < (mode === 3 ? 2 : 3)) break;
                if(out.length) out.push(STRIP_END);
                for(let i = 0; i < n; i++) out.push(at(i));
                break;
            case 2:
                if(n < 2) break;
                for(let i = 0; i < n; i++) out.push(at(i), at((i + 1) % n));
                break;
            case 6:
                for(let i = 1; i + 1 < n; i++) out.push(at(0), at(i), at(i + 1));
                break;
        }
    };
    let start = 0;
    for(let i = 0; i <= indices.length; i++)
    {
        if(i === indices.length || indices[i] === restart)
        {
            piece(start, i);
            start = i + 1;
        }
    }
    return { list: new Uint32Array(out), low, high, topology: TOPOLOGY[mode], strip };
}

/** GLES 3.2's PATCHES, and the vertices a patch (GL's default PATCH_VERTICES: glPatchParameteri is not on the guest's wire) */
const PATCHES = 0xE, PATCH_VERTICES = 3;

/** Vertices an input primitive of each mode (GLES 3.2 11.3.4.1: a geometry shader's input) */
const PRIMITIVE_VERTICES = { 0: 1, 1: 2, 2: 2, 3: 2, 4: 3, 5: 3, 6: 3, 0xA: 4, 0xB: 4, 0xC: 6, 0xD: 6 };

/**
 * A draw's primitives as a geometry shader takes them (GLES 3.2 10.1 and
 * table 10.1 for strips with adjacency): `per` vertices each, the adjacent
 * ones in their places; a restart index ends a strip, loop or fan
 * @param {!ArrayLike<number>} indices the draw's vertices in order
 * @param {number} restart the restart index, -1 for none
 * @return {{vertices: !Uint32Array, per: number}}
 */
function primitives_of(indices, mode, restart)
{
    const per = PRIMITIVE_VERTICES[mode];
    const out = [];
    const piece = v =>
    {
        const n = v.length;
        switch(mode)
        {
            case 0: case 1: case 4: case 0xA: case 0xC:
                for(let i = 0; i + per <= n; i += per) for(let k = 0; k < per; k++) out.push(v[i + k]);
                break;
            case 3: for(let i = 0; i + 1 < n; i++) out.push(v[i], v[i + 1]); break;
            case 2: if(n >= 2) for(let i = 0; i < n; i++) out.push(v[i], v[(i + 1) % n]); break;
            case 5: for(let i = 0; i + 2 < n; i++) i % 2 ? out.push(v[i + 1], v[i], v[i + 2]) : out.push(v[i], v[i + 1], v[i + 2]); break;
            case 6: for(let i = 1; i + 1 < n; i++) out.push(v[0], v[i], v[i + 1]); break;
            case 0xB: for(let i = 1; i + 2 < n; i++) out.push(v[i - 1], v[i], v[i + 1], v[i + 2]); break;
            case 0xD:
            {
                // (1-based as the table: the triangle's vertices and each edge's adjacent one, in the shader's order)
                const m = n >= 6 ? n - 4 >> 1 : 0;
                const at = k => v[k - 1];
                for(let i = 0; i < m; i++)
                {
                    const last = i === m - 1, even = i % 2 === 0;
                    const [a, b, c] = even ? [2 * i + 1, 2 * i + 3, 2 * i + 5] : [2 * i + 3, 2 * i + 1, 2 * i + 5];
                    const ab = i === 0 ? 2 : 2 * i - 1;
                    const bc = even ? (last ? 2 * i + 6 : 2 * i + 7) : 2 * i + 4;
                    const ca = even ? 2 * i + 4 : (last ? 2 * i + 6 : 2 * i + 7);
                    out.push(at(a), at(ab), at(b), at(bc), at(c), at(ca));
                }
                break;
            }
        }
    };
    let start = 0;
    for(let i = 0; i <= indices.length; i++)
    {
        if(i === indices.length || indices[i] === restart)
        {
            piece(Array.prototype.slice.call(indices, start, i));
            start = i + 1;
        }
    }
    return { vertices: new Uint32Array(out), per };
}

/**
 * A vertex shader's WGSL with its outputs' interpolation the fragment
 * inputs' at their locations: WebGPU wants them the same, GLSL ES 3.10
 * lets centroid and sample differ between the stages
 */
function matched_interpolation(vertex_wgsl, inputs)
{
    // (the output struct's members: lines of their own; the entry point's inputs are on its line)
    return vertex_wgsl.replace(/^(\s+@location\((\d+)\)\s*)(?:@interpolate\([^)]*\)\s*)?/gm,
        (all, head, location) => inputs.has(+location) ? head + (inputs.get(+location) ? inputs.get(+location) + " " : "") : all);
}

/** A fragment entry point's inputs: location to their attributes (interpolation) */
function fragment_inputs(wgsl)
{
    const inputs = new Map();
    const at = wgsl.indexOf("@fragment");
    const signature = at < 0 ? null : /\(([^{]*)\)\s*(?:->[^{]*)?\{/.exec(wgsl.slice(at));
    for(const m of signature ? signature[1].matchAll(/@location\((\d+)\)\s*((?:@\w+(?:\([^)]*\))?\s*)*)\w+\s*:/g) : [])
    {
        inputs.set(+m[1], m[2].trim());
    }
    return inputs;
}

export const GLES3 = {
    // ---- vx_naga

    /** vx_naga.wasm, fetched once (a batch with a program link waits for it) */
    async load_naga()
    {
        if(this.naga) return this.naga;
        this.naga_loading = this.naga_loading || (async () =>
        {
            const response = await fetch(this.naga_url || globalThis["V86VenusNagaUrl"] || NAGA_URL);
            if(!response.ok) throw new Error("vx_naga.wasm: " + response.status);
            const { instance } = await WebAssembly.instantiate(await response.arrayBuffer(), {});
            this.naga = instance.exports;
        })();
        await this.naga_loading;
        return this.naga;
    },

    /** SPIR-V words as vx_naga's answer: {wgsl, entries, intsamples} or {error} */
    translate_spirv(words, flags, wraps)
    {
        const naga = this.naga;
        const bytes = new Uint8Array(words.buffer, words.byteOffset, words.byteLength);
        const input = naga.vx_alloc(bytes.length);
        new Uint8Array(naga.memory.buffer, input, bytes.length).set(bytes);
        const list = wraps.length ? naga.vx_alloc(wraps.length * 8) : 0;
        if(list) new Uint32Array(naga.memory.buffer, list, wraps.length * 2).set(wraps.flat());
        let out;
        try
        {
            out = naga.vx_translate(input, bytes.length, 1, 0, flags, 0, 0, list, wraps.length);
        }
        finally
        {
            naga.vx_free(input, bytes.length);
            if(list) naga.vx_free(list, wraps.length * 8);
        }
        const length = new DataView(naga.memory.buffer).getUint32(out, true);
        const json = new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length));
        naga.vx_free(out, length + 4);
        return JSON.parse(json);
    },

    /** A note of what a draw could not do (the stats' `gles3`: each kind counted) */
    note3(what)
    {
        const notes = this.stats.gles3 = this.stats.gles3 || {};
        notes[what] = (notes[what] || 0) + 1;
        return null;
    },

    /** The program's GPU side (its `gpu`, which snapshots leave out): made again after each link */
    program_gpu(program)
    {
        if(!program.gpu || program.gpu.info !== program.info)
        {
            program.gpu = { info: program.info, translations: new Map(), shaders: new Map(), inputs: null, uniforms: null };
        }
        return program.gpu;
    },

    translation3(program, index, flags, wraps)
    {
        const gpu = this.program_gpu(program);
        const key = index + ":" + flags + ":" + wraps.flat().join(",");
        let t = gpu.translations.get(key);
        if(!t)
        {
            // (the stats' translations and their time: vx_naga's work, cached by the program, stage, flags and wraps)
            const start = performance.now();
            t = this.translate_spirv(program.info.spirv[index].words, flags, wraps);
            this.stats.translations = (this.stats.translations || 0) + 1;
            this.stats.translate_ms = (this.stats.translate_ms || 0) + performance.now() - start;
            gpu.translations.set(key, t);
        }
        return t;
    },

    /** A shader module of WGSL (cached by its code) */
    module3(code)
    {
        let m = this.shaders.get(code);
        if(!m) this.shaders.set(code, m = this.device.createShaderModule({ label: "GLES 3 program", code: "diagnostic(off, derivative_uniformity);\n" + code }));
        return m;
    },

    /**
     * The programs of a draw's stages: the current program for both, or the
     * bound pipeline's (GLES 3.1's separable programs), or null
     * @return {?{vertex: !Object, fragment: !Object}}
     */
    stages3(c)
    {
        const ok = p => p && p.kind === "program" && p.info && p.info.ok && p.info.spirv ? p : null;
        if(c.program) return ok(c.group.objects.get(c.program)) && { vertex: c.group.objects.get(c.program), fragment: c.group.objects.get(c.program) };
        const pipeline = c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
        if(!pipeline) return null;
        const vertex = ok(c.group.objects.get(pipeline.stages[1])), fragment = ok(c.group.objects.get(pipeline.stages[2]));
        return vertex && fragment ? { vertex, fragment } : null;
    },

    /**
     * The bindings translations use: by group and binding, with their WGSL
     * types, the stages that see them (`visibility`) and the program whose
     * state they bind
     * @param {!Array<!Array<*>>} list [translation, visibility, program]
     */
    bindings3(list)
    {
        const bindings = new Map();
        for(const [t, visibility, program] of list)
        {
            const declarations = wgsl_declarations(t.wgsl);
            for(const [group, binding, kind, size] of t.entries[0].bindings)
            {
                const key = group + ":" + binding;
                const b = bindings.get(key) || { group, binding, kind, size: 0, visibility: 0, type: declarations.get(key), program };
                b.size = Math.max(b.size, size);
                b.visibility |= visibility;
                bindings.set(key, b);
            }
        }
        return [...bindings.values()].sort((a, b) => a.group - b.group || a.binding - b.binding);
    },

    /**
     * The shader modules of a draw's stages (one program's, or a pipeline's):
     * the fragment depth output kept only with a depth attachment, integer
     * textures fetched by their samplers' wraps
     * @param {{vertex: !Object, fragment: !Object}} stages stages3's
     * @return {?{vertex: !Object, fragment: !Object, bindings: !Array<!Object>, outputs: !Map<number, string>, id: string}}
     */
    program3(c, stages, target)
    {
        if(!this.naga) return this.note3("vx_naga not loaded");
        const v = stages.vertex.info.spirv.findIndex(m => m.stage === "vertex"), f = stages.fragment.info.spirv.findIndex(m => m.stage === "fragment");
        if(v < 0 || f < 0) return this.note3("a program without a vertex or fragment shader");
        const fragment_flags = target.depth ? 0 : NO_DEPTH;
        const translate = (vw, fw) => [this.translation3(stages.vertex, v, GL_DEPTH, vw), this.translation3(stages.fragment, f, fragment_flags, fw)];
        // (the samplers that clamp to the border: their axes and colors, the translations' constants)
        const borders = [this.border_wraps3(c, stages.vertex, 0), this.border_wraps3(c, stages.fragment, stages.fragment.separable ? 1 : 0)];
        let ts = translate(borders[0], borders[1]);
        const failed = ts.find(t => t.error);
        if(failed) return this.note3("vx_naga: " + failed.error.slice(0, 160));
        const wraps = ts.map((t, i) => t.intsamples && t.intsamples.length ? this.int_wraps3(c, i ? stages.fragment : stages.vertex, t.intsamples) : []);
        const gpu = this.program_gpu(stages.vertex);
        const key = this.id_of(stages.fragment) + ":" + fragment_flags + ":" + wraps.concat(borders).map(w => w.flat().join(",")).join("/");
        let shaders = gpu.shaders.get(key);
        if(shaders) return shaders;
        if(wraps.some(w => w.length)) ts = translate(wraps[0].concat(borders[0]), wraps[1].concat(borders[1]));
        if(ts.some(t => t.error)) return this.note3("vx_naga: " + ts.find(t => t.error).error.slice(0, 160));
        shaders = {
            vertex: { module: this.module3(matched_interpolation(ts[0].wgsl, fragment_inputs(ts[1].wgsl))), entry: ts[0].entries[0].name },
            // (flat inputs: draws reorder their primitives for GL's provoking vertex, draw3)
            flat: [...fragment_inputs(ts[1].wgsl).values()].some(i => /\bflat\b/.test(i)),
            fragment: { module: this.module3(ts[1].wgsl), entry: ts[1].entries[0].name, wgsl: ts[1].wgsl,
                // (the sample count, specialization constant 71: glsl_es_rewrite.js's sample functions)
                samples_constant: (ts[1].overrides || []).some(o => o[0] === SAMPLES_CONSTANT),
                blend_constant: (ts[1].overrides || []).some(o => o[0] === BLEND_CONSTANT) },
            bindings: this.bindings3([[ts[0], 1, stages.vertex], [ts[1], 2, stages.fragment]]),
            outputs: fragment_outputs(ts[1].wgsl),
        };
        shaders.id = this.id_of(shaders.vertex.module) + ":" + this.id_of(shaders.fragment.module);
        gpu.shaders.set(key, shaders);
        return shaders;
    },

    /** The vertex shader's inputs: location, kind ("f", "i", "u") and components, matrices by column */
    inputs3(program)
    {
        const gpu = this.program_gpu(program);
        if(gpu.inputs) return gpu.inputs;
        const inputs = [];
        for(const a of program.info.attributes)
        {
            if(a.location < 0) continue;
            const t = gl_type(a.type);
            const kind = t.base === "int" ? "i" : t.base === "uint" ? "u" : "f";
            const columns = t.columns || 1, components = t.columns ? t.rows : t.components;
            for(let e = 0; e < a.size; e++)
            {
                for(let k = 0; k < columns; k++) inputs.push({ location: a.location + e * columns + k, kind, components });
            }
        }
        // (the inputs GL does not list, unused: (0, 0, 0, 1) at the locations the link gave them)
        for(const u of program.info.unused_inputs || []) inputs.push(Object.assign({ unused: true }, u));
        return gpu.inputs = inputs;
    },

    // ---- buffers

    /**
     * A GL buffer's GPU buffer, the CPU side's changes copied in first
     * @param {number=} minimum the bytes it holds at least (a binding's
     *     least size past the GL buffer's end)
     */
    gpu_buffer(buffer, minimum = 0)
    {
        const size = Math.max(16, Math.ceil(Math.max(buffer.size, minimum) / 16) * 16);
        let gpu = buffer.gpu;
        if(!gpu || gpu.size < size)
        {
            const created = this.device.createBuffer({ label: "GL buffer", size,
                usage: B.VERTEX | B.INDEX | B.UNIFORM | B.STORAGE | B.COPY_SRC | B.COPY_DST | B.INDIRECT });
            if(gpu)
            {
                if(buffer.gpu_newer)
                {
                    this.end_pass();
                    this.encoder.copyBufferToBuffer(gpu.buffer, 0, created, 0, gpu.size);
                }
                this.staging.push(gpu.buffer);
            }
            // (a first GPU buffer starts as the CPU side's bytes: nothing on the GPU is newer yet)
            if(!gpu || !buffer.gpu_newer) buffer.dirty = [0, buffer.size];
            buffer.gpu = gpu = { buffer: created, size, destroy: () => created.destroy() };
        }
        if(buffer.dirty)
        {
            const [low, high] = buffer.dirty;
            buffer.dirty = null;
            const bytes = cpu_bytes(buffer);
            if(bytes && high > low) this.write_gpu_buffer(gpu.buffer, low, high - low, bytes, low, buffer.size);
        }
        return gpu;
    },

    /**
     * Bytes into a GPU buffer, in order with the draws (a staging buffer
     * copied in the encoder); the range widened to whole words from
     * `source`, and past the GL buffer's end (a size not a whole number of
     * words: a 6-byte index buffer) with zeros
     * @param {!Uint8Array} source holds the bytes, `at` the first's index
     * @param {number} end the GL buffer's size
     */
    write_gpu_buffer(target, offset, length, source, at, end)
    {
        const low = offset & ~3, high = align4(offset + length);
        const before = offset - low, after = offset + length >= end ? 0 : high - offset - length;
        if(at - before < 0 || at + length + after > source.length) return this.note3("an unaligned buffer write");
        this.end_pass();
        const staging = this.device.createBuffer({ label: "GLES buffer upload", size: Math.max(4, high - low), usage: B.COPY_SRC, mappedAtCreation: true });
        new Uint8Array(staging.getMappedRange()).set(source.subarray(at - before, at + length + after));
        staging.unmap();
        this.encoder.copyBufferToBuffer(staging, 0, target, low, high - low);
        this.staging.push(staging);
        return undefined;
    },

    /**
     * The guest wrote `length` bytes of a buffer at `offset` (`data`: them):
     * the CPU side's copy has them, the GPU buffer gets them before its next
     * use, or now if the GPU's copy is the newer one
     */
    buffer_written(buffer, offset, length, data)
    {
        if(!buffer || length <= 0) return;
        if(buffer.gpu_newer)
        {
            const gpu = this.gpu_buffer(buffer);
            if(data) this.write_gpu_buffer(gpu.buffer, offset, length, data, 0, buffer.size);
            return;
        }
        if(!buffer.gpu) return;
        buffer.dirty = buffer.dirty ? [Math.min(buffer.dirty[0], offset), Math.max(buffer.dirty[1], offset + length)] : [offset, offset + length];
    },

    /** The buffer bound to a target (GLES 3.0's targets and 3.1's) */
    buffer_of3(c, target)
    {
        const which = { 0x8892: "array", 0x8893: "element", 0x8F36: "copy_read", 0x8F37: "copy_write", 0x88EB: "pixel_pack", 0x88EC: "pixel_unpack",
            0x8C8E: "transform_feedback", 0x8A11: "uniform", 0x90D2: "shader_storage", 0x92C0: "atomic_counter", 0x90EE: "dispatch_indirect",
            0x8F3F: "draw_indirect" }[target];
        const name = which === "array" ? c.array_buffer : which === "element" ? c.element_array_buffer : which ? c.buffers[which] : 0;
        return name ? c.group.buffers.get(name) || null : null;
    },

    /** A zero buffer of at least `size` bytes (what an unbound uniform block reads) */
    zeros3(size)
    {
        size = Math.max(256, Math.ceil(size / 256) * 256);
        if(!this.zero_buffer || this.zero_buffer.size < size)
        {
            if(this.zero_buffer) this.staging.push(this.zero_buffer);
            this.zero_buffer = this.device.createBuffer({ label: "GLES zeros", size, usage: B.UNIFORM | B.STORAGE | B.VERTEX });
        }
        return this.zero_buffer;
    },

    /**
     * A buffer of at least `size` bytes that writes go to and nothing reads
     * (an unbound storage block's or atomic counters'), one of its own each:
     * WebGPU refuses two writable bindings of one buffer's range
     */
    discard3(size)
    {
        const buffer = this.device.createBuffer({ label: "GLES discarded writes", size: Math.max(16, align4(size)), usage: B.STORAGE });
        this.staging.push(buffer);
        return buffer;
    },

    // ---- textures

    /**
     * A texture's GPU texture: its format's, as large as the lowest level
     * given (GPU level 0 is that GL level, `first`) with a full chain (an
     * immutable texture's levels); made again when those change, the levels
     * that still fit copied over
     */
    gpu_texture3(texture)
    {
        const cube = texture.target === GL3.TEXTURE_CUBE_MAP, three = texture.target === GL3.TEXTURE_3D;
        // (GLES 3.2's cube map arrays: their layer-faces a 2D array's layers)
        const array = texture.target === GL3.TEXTURE_2D_ARRAY || texture.target === 0x9009;
        let first = -1, base = null;
        for(let level = 0; level < 32 && !base; level++)
        {
            for(let face = 0; face < (cube ? 6 : 1) && !base; face++)
            {
                const image = texture.images.get(face * 32 + level);
                if(image && image.width && image.height) { first = level; base = image; }
            }
        }
        if(!base) return null;
        const internal = image_internal(base);
        const compressed = COMPRESSED_FORMATS.get(internal);
        const info = format_info(internal);
        const width = base.width, height = base.height;
        const feature = compressed && this.device.features && this.device.features.has(compressed.astc ? "texture-compression-astc" : "texture-compression-etc2");
        // (WebGPU's compressed textures are whole blocks: one of another size is its blocks decoded by the GPU, decode_compressed3)
        const whole = compressed && width % compressed.block_width === 0 && height % compressed.block_height === 0;
        const native = feature && whole;
        const decoded = feature && !whole ? decoded_format(compressed) : null;
        const format = compressed ? (native ? compressed.webgpu : decoded || COLOR_FORMAT) : info ? info.webgpu : COLOR_FORMAT;
        const depth = three || array ? Math.max(1, base.depth || 1) : cube ? 6 : 1;
        const largest = Math.max(width, height, three ? depth : 1);
        const levels = texture.immutable ? Math.max(1, texture.immutable_levels - first) : Math.floor(Math.log2(largest)) + 1;
        // (GLES 3.1: a multisampled texture's 4 samples; an immutable texture of a storage format is an image's too)
        const samples = base.samples > 1 ? 4 : 1;
        const storage = samples === 1 && !!texture.immutable && STORAGE_FORMATS.has(format);
        const old = texture.gpu;
        if(old && old.es3 && old.format === format && old.width === width && old.height === height && old.depth === depth && old.first === first &&
            old.levels >= levels && old.samples === samples && old.storage === storage)
        {
            return old;
        }
        const usage = U.TEXTURE_BINDING | (samples > 1 ? 0 : U.COPY_DST | U.COPY_SRC) | (RENDERABLE.has(format) ? U.RENDER_ATTACHMENT : 0) |
            (storage ? U.STORAGE_BINDING : 0);
        const created = this.device.createTexture({ label: "GL texture", size: [width, height, depth], dimension: three ? "3d" : "2d", format,
            mipLevelCount: samples > 1 ? 1 : levels, sampleCount: samples, usage });
        if(RENDERABLE.has(format) && alpha_less(internal, format)) this.alpha_one3(created, samples > 1 ? 1 : levels, depth, three);
        const gpu = { es3: true, texture: created, format, width, height, depth, first, levels: samples > 1 ? 1 : levels, three, cube, array, samples,
            storage, views: new Map(), block: native ? compressed.block_width : 1, block_height: native ? compressed.block_height : 1,
            block_bytes: native ? compressed.block_bytes : 0, decode: decoded ? compressed : null, proxies: null,
            destroy: () => { created.destroy(); for(const proxy of gpu.proxies ? gpu.proxies.values() : []) proxy.texture.destroy(); } };
        if(old && old.texture)
        {
            // (the levels that keep their size: a level given below the others, a chain made longer)
            if(old.es3 && old.format === format && !DRAWN_DEPTH.has(format) && format !== "stencil8" && samples === 1 && old.samples === 1)
            {
                this.end_pass();
                for(let mip = 0; mip < old.levels; mip++)
                {
                    const to = mip + old.first - first;
                    const w = Math.max(1, old.width >> mip), h = Math.max(1, old.height >> mip);
                    if(to < 0 || to >= levels || Math.max(1, width >> to) !== w || Math.max(1, height >> to) !== h) continue;
                    const d = old.three ? Math.max(1, old.depth >> mip) : old.depth;
                    if(d !== (three ? Math.max(1, depth >> to) : depth)) continue;
                    if(gpu.block > 1 && (w % gpu.block || h % gpu.block_height)) continue;
                    this.encoder.copyTextureToTexture({ texture: old.texture, mipLevel: mip }, { texture: created, mipLevel: to }, [w, h, d]);
                }
            }
            this.staging.push(old.texture);
        }
        texture.gpu = gpu;
        return gpu;
    },

    /**
     * Texels into a level of a GPU texture, in order with the draws:
     * `origin` and `size` in texels (x, y, and the layer, face or slice)
     * @return {boolean} whether the level is there to write
     */
    upload3(gpu, level, origin, size, texels)
    {
        const mip = level - gpu.first;
        if(mip < 0 || mip >= gpu.levels) return false;
        const mip_width = Math.max(1, gpu.width >> mip), mip_height = Math.max(1, gpu.height >> mip);
        const mip_depth = gpu.three ? Math.max(1, gpu.depth >> mip) : gpu.depth;
        const [x, y, z] = origin, [w, h, d] = size;
        if(x + w > mip_width || y + h > mip_height || z + d > mip_depth || !w || !h || !d) return false;
        const block = gpu.block, block_height = gpu.block_height || 1;
        const texel = block > 1 ? gpu.block_bytes : TEXEL_BYTES[gpu.format];
        const columns = Math.ceil(w / block), rows = Math.ceil(h / block_height);
        const row = columns * texel, stride = Math.ceil(row / 256) * 256;
        this.end_pass();
        const staging = this.device.createBuffer({ label: "GLES upload", size: Math.max(4, stride * rows * d), usage: B.COPY_SRC, mappedAtCreation: true });
        const mapped = new Uint8Array(staging.getMappedRange());
        for(let k = 0; k < rows * d; k++)
        {
            const from = k * row;
            if(from >= texels.length) break;
            mapped.set(texels.subarray(from, Math.min(texels.length, from + row)), k * stride);
        }
        staging.unmap();
        this.encoder.copyBufferToTexture({ buffer: staging, bytesPerRow: stride, rowsPerImage: rows },
            { texture: gpu.texture, mipLevel: mip, origin: [x, y, z] }, [columns * block, rows * block_height, d]);
        this.staging.push(staging);
        this.stats.uploads++;
        return true;
    },

    /** The texture bound to a target of the active unit, the face of a cube face's target */
    bound3(c, target)
    {
        const face = target >= 0x8515 && target <= 0x851A ? target - 0x8515 : 0;
        const slot_target = face || target === 0x8515 ? GL3.TEXTURE_CUBE_MAP : target;
        const slot = SLOT_TARGET.indexOf(slot_target);
        if(slot < 0) return { texture: null, face };
        const name = c.textures[c.active_texture][slot];
        return { texture: name ? c.group.textures.get(name) : c.defaults && c.defaults.get(slot_target), face };
    },

    /** glTexImage2D/3D, glTexSubImage2D/3D and their Offset forms (the data from the pixel unpack buffer) */
    tex_image3(c, name, args)
    {
        const three = name.includes("3D"), sub = name.includes("Sub");
        let target, level, x = 0, y = 0, z = 0, width, height, depth = 1, format, type, data;
        if(sub && three) [target, level, x, y, z, width, height, depth, format, type, data] = args;
        else if(sub) [target, level, x, y, width, height, format, type, data] = args;
        else if(three) [target, level, , width, height, depth, , format, type, data] = args;
        else [target, level, , width, height, , format, type, data] = args;
        const { texture, face } = this.bound3(c, target);
        if(!texture || !width || !height || !depth) return;
        const image = texture.images.get((three ? 0 : face) * 32 + level);
        if(!image) return;
        const base = texture.images.get(0);
        if(!three && base && (base.image || base.color_buffer))
        {
            // (an EGL image's: the writes go to its color buffer, GLES 2.0's way)
            if(typeof data !== "number") this.tex_image(c, args, sub);
            return;
        }
        const gpu = this.gpu_texture3(texture);
        if(!gpu) return;
        if(typeof data === "number")
        {
            const pbo = c.group.buffers.get(c.buffers.pixel_unpack);
            if(!pbo || pbo.gpu_newer) return void this.note3("an unpack buffer the GPU wrote");
            data = cpu_bytes(pbo) && cpu_bytes(pbo).subarray(data);
        }
        if(!data) return;
        const info = format_info(image_internal(image));
        if(!info) return;
        const unpack = c.unpack || NO_STORE;
        const store = { alignment: c.unpack_alignment, row_length: unpack.row_length, image_height: unpack.image_height,
            skip_pixels: unpack.skip_pixels, skip_rows: unpack.skip_rows, skip_images: unpack.skip_images };
        const tight = unpack_image(data, width, height, depth, format, type, store, three);
        const texels = to_texels(tight, width * height * depth, format, type, info);
        if(!texels) return void this.depth_image3(gpu, level, [x, y, three ? z : face], [width, height, depth],
            depth_values(tight, width * height * depth, format, type));
        if(!this.upload3(gpu, level, [x, y, three ? z : face], [width, height, depth], texels)) this.note3("an image of a level the texture lacks");
    },

    /** glCompressedTexImage2D/3D, glCompressedTexSubImage2D/3D (and Offset forms) */
    compressed_image3(c, name, args)
    {
        const three = name.includes("3D"), sub = name.includes("Sub");
        let target, level, x = 0, y = 0, z = 0, width, height, depth = 1, data;
        if(sub && three) [target, level, x, y, z, width, height, depth, , , data] = args;
        else if(sub) [target, level, x, y, width, height, , , data] = args;
        else if(three) [target, level, , width, height, depth, , , data] = args;
        else [target, level, , width, height, , , data] = args;
        const { texture, face } = this.bound3(c, target);
        const gpu = texture && this.gpu_texture3(texture);
        if(!gpu) return;
        if(typeof data === "number")
        {
            const pbo = c.group.buffers.get(c.buffers.pixel_unpack);
            data = pbo && !pbo.gpu_newer && cpu_bytes(pbo) ? cpu_bytes(pbo).subarray(data) : null;
        }
        if(!data) return;
        const image = texture.images.get((three ? 0 : face) * 32 + level);
        const internal = image ? image_internal(image) : 0;
        const layer = three ? z : face;
        if(gpu.block > 1)
        {
            this.upload3(gpu, level, [x, y, layer], [width, height, depth], data);
            return;
        }
        if(gpu.decode)
        {
            const blocks = Math.ceil(width / gpu.decode.block_width) * Math.ceil(height / gpu.decode.block_height) * gpu.decode.block_bytes;
            for(let k = 0; k < depth; k++) this.decode_compressed3(gpu, level, [x, y, layer + k], [width, height], data.subarray(k * blocks, (k + 1) * blocks));
            return;
        }
        // (without WebGPU's ETC2: ETC1's blocks decoded; the others' not yet, nor ASTC without its feature)
        if(internal !== 0x8D64 && internal !== 0x9274) return void this.note3("ETC2/EAC or ASTC without WebGPU's compression feature");
        const blocks = Math.ceil(width / 4) * Math.ceil(height / 4) * 8;
        for(let k = 0; k < depth; k++)
        {
            this.upload3(gpu, level, [x, y, layer + k], [width, height, 1], decode_etc1(width, height, data.subarray(k * blocks, (k + 1) * blocks)));
        }
    },

    /** glCopyTexImage2D, glCopyTexSubImage2D/3D: from the read framebuffer's read buffer, of the same format */
    copy_tex_image3(c, name, args)
    {
        let target, level, xoffset = 0, yoffset = 0, zoffset = 0, x, y, width, height;
        if(name === "glCopyTexImage2D") [target, level, , x, y, width, height] = args;
        else if(name === "glCopyTexSubImage2D") [target, level, xoffset, yoffset, x, y, width, height] = args;
        else [target, level, xoffset, yoffset, zoffset, x, y, width, height] = args;
        const { texture, face } = this.bound3(c, target);
        const gpu = texture && this.gpu_texture3(texture);
        const source = this.read_target3(c);
        if(!gpu || !source || source.texture === gpu.texture) return;
        const mip = level - gpu.first;
        if(mip < 0 || mip >= gpu.levels || source.samples > 1) return;
        const sx = Math.max(0, x), sy = Math.max(0, y);
        const w = Math.min(width - (sx - x), source.width - sx), h = Math.min(height - (sy - y), source.height - sy);
        if(w <= 0 || h <= 0) return;
        const layer = gpu.three || gpu.array ? zoffset : face;
        const [dx, dy] = [xoffset + sx - x, yoffset + sy - y];
        // (the level's own format: what GLES 3.0 table 3.15 keeps of the source's channels)
        const image = texture.images.get((gpu.three || gpu.array ? 0 : face) * 32 + level);
        const info = image && format_info(image_internal(image));
        const map = info && copy_map(info);
        const no_alpha = !!image && alpha_less(image_internal(image), gpu.format);
        if(!map && source.format === gpu.format && (!no_alpha || source.no_alpha))
        {
            this.end_pass();
            this.encoder.copyTextureToTexture({ texture: source.texture, mipLevel: source.mip, origin: [sx, sy, source.layer] },
                { texture: gpu.texture, mipLevel: mip, origin: [dx, dy, layer] }, [w, h, 1]);
            return;
        }
        if(!RENDERABLE.has(gpu.format)) return void this.note3("a copy into a texture WebGPU draws no " + gpu.format + " to");
        const view = gpu.three ? gpu.texture.createView({ dimension: "3d", baseMipLevel: mip, mipLevelCount: 1 }) :
            gpu.texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
        const dest = { texture: gpu.texture, view, format: gpu.format, mip, layer, depth_slice: gpu.three ? layer : undefined, no_alpha };
        this.blit3(source, dest, { src: [sx, sy, sx + w, sy + h], dst: [dx, dy, dx + w, dy + h], rect: [dx, dy, w, h], linear: false, map }, false);
    },

    /** glGenerateMipmap: each level drawn from the one before (2D, cube and array textures) */
    generate_mipmap3(c, target)
    {
        const { texture } = this.bound3(c, target);
        const gpu = texture && this.gpu_texture3(texture);
        if(!gpu) return;
        if(!RENDERABLE.has(gpu.format) || format_kind(gpu.format) !== "f" || gpu.format.includes("32float")) return void this.note3("glGenerateMipmap of that format");
        const base = Math.max(0, (texture.base_level || 0) - gpu.first);
        if(gpu.three)
        {
            for(let mip = base + 1; mip < gpu.levels; mip++) this.downsample3d(gpu, mip);
            return;
        }
        for(let layer = 0; layer < gpu.depth; layer++)
        {
            for(let mip = base + 1; mip < gpu.levels; mip++)
            {
                const view = m => gpu.texture.createView({ dimension: "2d", baseMipLevel: m, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
                this.downsample3(view(mip - 1), view(mip), gpu.format);
            }
        }
    },

    /** A full-size draw of one view into another of the format (filtered linearly) */
    downsample3(source, target, format)
    {
        this.blits3 = this.blits3 || new Map();
        let blit = this.blits3.get(format);
        if(!blit)
        {
            const module = this.device.createShaderModule({ code: `
                struct VOut { @builtin(position) p : vec4<f32>, @location(0) uv : vec2<f32> };
                @group(0) @binding(0) var t : texture_2d<f32>;
                @group(0) @binding(1) var s : sampler;
                @vertex fn vs(@builtin(vertex_index) i : u32) -> VOut {
                    let p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    var o : VOut;
                    o.p = vec4<f32>(p[i], 0.0, 1.0);
                    o.uv = vec2<f32>(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
                    return o;
                }
                @fragment fn fs(i : VOut) -> @location(0) vec4<f32> { return textureSampleLevel(t, s, i.uv, 0.0); }` });
            blit = { pipeline: this.device.createRenderPipeline({ label: "GLES 3 blit", layout: "auto", vertex: { module, entryPoint: "vs" },
                fragment: { module, entryPoint: "fs", targets: [{ format }] }, primitive: { topology: "triangle-list" } }),
            sampler: this.device.createSampler({ magFilter: "linear", minFilter: "linear" }) };
            this.blits3.set(format, blit);
        }
        this.end_pass();
        const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view: target, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 0 }, storeOp: "store" }] });
        pass.setPipeline(blit.pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: blit.pipeline.getBindGroupLayout(0), entries: [
            { binding: 0, resource: source }, { binding: 1, resource: blit.sampler }] }));
        pass.draw(3);
        pass.end();
    },

    /** A 3D texture's level drawn from the one before, a slice at a time (linear filtering: each texel the mean of eight) */
    downsample3d(gpu, mip)
    {
        const key = "downsample3d:" + gpu.format;
        this.blits3 = this.blits3 || new Map();
        let blit = this.blits3.get(key);
        if(!blit)
        {
            const module = this.device.createShaderModule({ code: `
                @group(0) @binding(0) var t : texture_3d<f32>;
                @group(0) @binding(1) var s : sampler;
                @group(0) @binding(2) var<uniform> p : vec4<f32>;
                @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                    let v = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    return vec4<f32>(v[i], 0.0, 1.0);
                }
                @fragment fn fs(@builtin(position) q : vec4<f32>) -> @location(0) vec4<f32> {
                    return textureSampleLevel(t, s, vec3<f32>(q.xy / p.xy, p.z), 0.0);
                }` });
            blit = { pipeline: this.device.createRenderPipeline({ label: "GLES 3 3D mipmap", layout: "auto", vertex: { module, entryPoint: "vs" },
                fragment: { module, entryPoint: "fs", targets: [{ format: gpu.format }] }, primitive: { topology: "triangle-list" } }),
            sampler: this.device.createSampler({ magFilter: "linear", minFilter: "linear" }) };
            this.blits3.set(key, blit);
        }
        const w = Math.max(1, gpu.width >> mip), h = Math.max(1, gpu.height >> mip), d = Math.max(1, gpu.depth >> mip);
        const source = gpu.texture.createView({ dimension: "3d", baseMipLevel: mip - 1, mipLevelCount: 1 });
        const target = gpu.texture.createView({ dimension: "3d", baseMipLevel: mip, mipLevelCount: 1 });
        this.end_pass();
        for(let z = 0; z < d; z++)
        {
            const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view: target, depthSlice: z, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 0 },
                storeOp: "store" }] });
            pass.setPipeline(blit.pipeline);
            pass.setBindGroup(0, this.device.createBindGroup({ layout: blit.pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: source },
                { binding: 1, resource: blit.sampler }, { binding: 2, resource: { buffer: this.uniform_buffer(new Float32Array([w, h, (z + 0.5) / d, 0]).buffer) } }] }));
            pass.draw(3);
            pass.end();
        }
    },

    /**
     * A depth image's values written by a draw (WebGPU copies no buffer into
     * depth24plus or depth32float): the depths as an r32float texture, each
     * layer drawn with frag_depth; the stencil values copied into the
     * stencil aspect (WebGPU copies into stencil8's)
     */
    depth_image3(gpu, level, origin, size, values)
    {
        const mip = level - gpu.first;
        if(mip < 0 || mip >= gpu.levels) return;
        const [x, y, z] = origin, [w, h, d] = size;
        const source = this.device.createTexture({ label: "GLES depth image", size: [w, h, d], format: "r32float", usage: U.TEXTURE_BINDING | U.COPY_DST });
        this.device.queue.writeTexture({ texture: source }, values.depth, { bytesPerRow: w * 4, rowsPerImage: h }, [w, h, d]);
        this.staging.push(source);
        const key = "depth_image:" + gpu.format;
        this.blits3 = this.blits3 || new Map();
        let blit = this.blits3.get(key);
        if(!blit)
        {
            const module = this.device.createShaderModule({ code: `
                @group(0) @binding(0) var t : texture_2d_array<f32>;
                @group(0) @binding(1) var<uniform> p : vec4<i32>;
                @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                    let v = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    return vec4<f32>(v[i], 0.0, 1.0);
                }
                @fragment fn fs(@builtin(position) q : vec4<f32>) -> @builtin(frag_depth) f32 {
                    return textureLoad(t, vec2<i32>(q.xy) - p.xy, p.z, 0).x;
                }` });
            const group = this.device.createBindGroupLayout({ entries: [{ binding: 0, visibility: 2, texture: { sampleType: "unfilterable-float", viewDimension: "2d-array" } },
                { binding: 1, visibility: 2, buffer: { type: "uniform" } }] });
            blit = { group, pipeline: this.device.createRenderPipeline({ label: "GLES 3 depth image", layout: this.device.createPipelineLayout({ bindGroupLayouts: [group] }),
                vertex: { module, entryPoint: "vs" }, fragment: { module, entryPoint: "fs", targets: [] }, primitive: { topology: "triangle-list" },
                depthStencil: { format: gpu.format, depthWriteEnabled: true, depthCompare: "always" } }) };
            this.blits3.set(key, blit);
        }
        const stencil = gpu.format.includes("stencil");
        this.end_pass();
        for(let k = 0; k < d; k++)
        {
            const view = gpu.texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1, baseArrayLayer: z + k, arrayLayerCount: 1 });
            const pass = this.encoder.beginRenderPass({ colorAttachments: [], depthStencilAttachment: Object.assign({ view, depthLoadOp: "load", depthStoreOp: "store" },
                stencil ? { stencilLoadOp: "load", stencilStoreOp: "store" } : {}) });
            pass.setPipeline(blit.pipeline);
            pass.setBindGroup(0, this.device.createBindGroup({ layout: blit.group, entries: [{ binding: 0, resource: source.createView({ dimension: "2d-array" }) },
                { binding: 1, resource: { buffer: this.uniform_buffer(new Int32Array([x, y, k, 0]).buffer) } }] }));
            pass.setScissorRect(x, y, w, h);
            pass.draw(3);
            pass.end();
        }
        if(stencil && values.stencil) this.stencil_image3(gpu, mip, origin, size, values.stencil);
    },

    /**
     * Stencil values into a rectangle of a depth stencil texture's level:
     * WebGPU copies the stencil aspect of whole levels (layers) only, so a
     * rectangle of less goes through a buffer of the levels' stencil, the
     * rectangle's bytes set in it by a compute pass, copied back whole
     */
    stencil_image3(gpu, mip, origin, size, stencil)
    {
        const [x, y, z] = origin, [w, h, d] = size;
        const width = Math.max(1, gpu.width >> mip), height = Math.max(1, gpu.height >> mip);
        const whole = x === 0 && y === 0 && w === width && h === height;
        const stride = Math.ceil((whole ? w : width) / 256) * 256;
        const rows = whole ? h : height;
        const level = { texture: gpu.texture, mipLevel: mip, origin: [0, 0, z], aspect: "stencil-only" };
        if(whole)
        {
            const staging = this.device.createBuffer({ label: "GLES stencil upload", size: stride * h * d, usage: B.COPY_SRC, mappedAtCreation: true });
            const mapped = new Uint8Array(staging.getMappedRange());
            for(let k = 0; k < h * d; k++) mapped.set(stencil.subarray(k * w, k * w + w), k * stride);
            staging.unmap();
            this.staging.push(staging);
            this.encoder.copyBufferToTexture({ buffer: staging, bytesPerRow: stride, rowsPerImage: h }, level, [w, h, d]);
            return;
        }
        const levels = this.device.createBuffer({ label: "GLES stencil levels", size: stride * rows * d, usage: B.STORAGE | B.COPY_SRC | B.COPY_DST });
        const values = this.device.createBuffer({ label: "GLES stencil values", size: Math.max(16, align4(w * h * d)), usage: B.STORAGE, mappedAtCreation: true });
        new Uint8Array(values.getMappedRange()).set(stencil.subarray(0, w * h * d));
        values.unmap();
        this.staging.push(levels, values);
        if(!this.stencil_patch3)
        {
            const module = this.device.createShaderModule({ code: `
                @group(0) @binding(0) var<storage, read_write> levels : array<u32>;
                @group(0) @binding(1) var<storage, read> values : array<u32>;
                @group(0) @binding(2) var<uniform> p : array<vec4<u32>, 2>;
                @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id : vec3<u32>) {
                    // p[0]: x, y, w, h; p[1]: stride, rows, the words
                    if(id.x >= p[1].z) { return; }
                    var word = levels[id.x];
                    for(var b = 0u; b < 4u; b++) {
                        let at = id.x * 4u + b;
                        let layer = at / (p[1].x * p[1].y);
                        let row = at % (p[1].x * p[1].y) / p[1].x;
                        let column = at % p[1].x;
                        if(column >= p[0].x && column < p[0].x + p[0].z && row >= p[0].y && row < p[0].y + p[0].w) {
                            let i = (layer * p[0].w + row - p[0].y) * p[0].z + column - p[0].x;
                            let value = (values[i / 4u] >> (i % 4u * 8u)) & 0xFFu;
                            word = (word & ~(0xFFu << (b * 8u))) | (value << (b * 8u));
                        }
                    }
                    levels[id.x] = word;
                }` });
            this.stencil_patch3 = this.device.createComputePipeline({ label: "GLES stencil patch", layout: "auto", compute: { module, entryPoint: "main" } });
        }
        const words = stride * rows * d / 4;
        const parameters = this.uniform_buffer(new Uint32Array([x, y, w, h, stride, rows, words, 0]).buffer);
        this.end_pass();
        this.encoder.copyTextureToBuffer(level, { buffer: levels, bytesPerRow: stride, rowsPerImage: rows }, [width, height, d]);
        const pass = this.encoder.beginComputePass({ label: "GLES stencil patch" });
        pass.setPipeline(this.stencil_patch3);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: this.stencil_patch3.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: levels } },
            { binding: 1, resource: { buffer: values } }, { binding: 2, resource: { buffer: parameters } }] }));
        pass.dispatchWorkgroups(Math.ceil(words / 64));
        pass.end();
        this.encoder.copyBufferToTexture({ buffer: levels, bytesPerRow: stride, rowsPerImage: rows }, level, [width, height, d]);
    },

    /**
     * A compressed image's blocks into a texture of their decoded format
     * (WebGPU makes compressed textures of whole blocks alone): the blocks
     * into a compressed texture of whole blocks, its texels drawn into the
     * level's rectangle by textureLoad
     * @param {!Array<number>} origin x, y and the layer, face or slice
     * @param {!Array<number>} size width and height
     */
    decode_compressed3(gpu, level, origin, size, data)
    {
        const mip = level - gpu.first;
        if(mip < 0 || mip >= gpu.levels) return;
        const c = gpu.decode, [x, y, layer] = origin, [w, h] = size;
        if(!w || !h) return;
        const columns = Math.ceil(w / c.block_width), rows = Math.ceil(h / c.block_height);
        const row = columns * c.block_bytes, stride = Math.ceil(row / 256) * 256;
        const blocks = this.device.createTexture({ label: "GLES compressed blocks", size: [columns * c.block_width, rows * c.block_height], format: c.webgpu,
            usage: U.TEXTURE_BINDING | U.COPY_DST });
        this.staging.push(blocks);
        this.end_pass();
        const staging = this.device.createBuffer({ label: "GLES compressed upload", size: Math.max(4, stride * rows), usage: B.COPY_SRC, mappedAtCreation: true });
        const mapped = new Uint8Array(staging.getMappedRange());
        for(let k = 0; k < rows && k * row < data.length; k++) mapped.set(data.subarray(k * row, Math.min(data.length, (k + 1) * row)), k * stride);
        staging.unmap();
        this.staging.push(staging);
        this.encoder.copyBufferToTexture({ buffer: staging, bytesPerRow: stride, rowsPerImage: rows }, { texture: blocks }, [columns * c.block_width, rows * c.block_height, 1]);
        this.blits3 = this.blits3 || new Map();
        const key = "decode:" + gpu.format;
        let decode = this.blits3.get(key);
        if(!decode)
        {
            const module = this.device.createShaderModule({ code: `
                @group(0) @binding(0) var t : texture_2d<f32>;
                @group(0) @binding(1) var<uniform> p : vec4<i32>;
                @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                    let v = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    return vec4<f32>(v[i], 0.0, 1.0);
                }
                @fragment fn fs(@builtin(position) q : vec4<f32>) -> @location(0) vec4<f32> {
                    return textureLoad(t, vec2<i32>(q.xy) - p.xy, 0);
                }` });
            const group = this.device.createBindGroupLayout({ entries: [{ binding: 0, visibility: 2, texture: { sampleType: "unfilterable-float" } },
                { binding: 1, visibility: 2, buffer: { type: "uniform" } }] });
            decode = { group, pipeline: this.device.createRenderPipeline({ label: "GLES 3 compressed decode", layout: this.device.createPipelineLayout({ bindGroupLayouts: [group] }),
                vertex: { module, entryPoint: "vs" }, fragment: { module, entryPoint: "fs", targets: [{ format: gpu.format }] }, primitive: { topology: "triangle-list" } }) };
            this.blits3.set(key, decode);
        }
        const view = gpu.texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
        const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view, loadOp: "load", storeOp: "store" }] });
        pass.setPipeline(decode.pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: decode.group, entries: [{ binding: 0, resource: blocks.createView() },
            { binding: 1, resource: { buffer: this.uniform_buffer(new Int32Array([x, y, 0, 0]).buffer) } }] }));
        pass.setScissorRect(x, y, w, h);
        pass.draw(3);
        pass.end();
        this.stats.uploads++;
    },

    /** glRenderbufferStorage(Multisample): a texture of the format (4 samples for any multisampled one) */
    renderbuffer_storage3(c)
    {
        const rb = c.group.renderbuffers.get(c.renderbuffer);
        if(!rb) return;
        if(rb.gpu) this.staging.push(rb.gpu);
        rb.gpu = null;
        this.make_renderbuffer3(rb);
    },

    /** A renderbuffer's texture, of its format and samples */
    make_renderbuffer3(rb)
    {
        if(!rb.width || !rb.height || rb.image) return;
        const info = format_info(rb.format);
        const format = info ? info.webgpu : RENDERBUFFER_WEBGPU[rb.format] || COLOR_FORMAT;
        if(!RENDERABLE.has(format)) return void this.note3("a renderbuffer of a format WebGPU draws no " + format);
        const samples = rb.samples > 1 ? 4 : 1;
        const texture = this.device.createTexture({ label: "GL renderbuffer", size: [rb.width, rb.height], format, sampleCount: samples,
            usage: U.RENDER_ATTACHMENT | U.TEXTURE_BINDING | (samples === 1 ? U.COPY_SRC | U.COPY_DST : 0) });
        rb.gpu = { es3: true, texture, format, samples, view: texture.createView(), destroy: () => texture.destroy() };
        if(alpha_less(rb.format, format)) this.alpha_one3(texture, 1, 1, false);
    },

    /**
     * A new texture of a format GL reads with alpha 1 (alpha_less): every
     * level and layer cleared to (0, 0, 0, 1), draws leaving alpha alone after
     */
    alpha_one3(texture, levels, layers, three)
    {
        this.end_pass();
        for(let mip = 0; mip < levels; mip++)
        {
            const count = three ? Math.max(1, layers >> mip) : layers;
            for(let layer = 0; layer < count; layer++)
            {
                const view = three ? texture.createView({ dimension: "3d", baseMipLevel: mip, mipLevelCount: 1 }) :
                    texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
                this.encoder.beginRenderPass({ colorAttachments: [Object.assign({ view, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" },
                    three ? { depthSlice: layer } : {})] }).end();
            }
        }
    },

    // ---- snapshots (L7's; the textures' and renderbuffers' contents)

    /**
     * A texture's levels and layers as save() reads them: rows of texels
     * (of blocks for a compressed format); the depth formats WebGPU copies
     * nothing out of, and multisampled textures (nothing copies them), are
     * left out (they read as undefined after a restore)
     */
    save_texture3(t, reads)
    {
        const gpu = t.gpu;
        if(gpu.samples > 1 || DRAWN_DEPTH.has(gpu.format) || gpu.format === "stencil8") return;
        t.saved = [];
        t.saved3 = true;
        const texel = gpu.block > 1 ? gpu.block_bytes : TEXEL_BYTES[gpu.format];
        for(let mip = 0; mip < gpu.levels; mip++)
        {
            const width = Math.max(1, gpu.width >> mip), height = Math.max(1, gpu.height >> mip);
            const layers = gpu.three ? Math.max(1, gpu.depth >> mip) : gpu.depth;
            const columns = Math.ceil(width / gpu.block), rows = Math.ceil(height / (gpu.block_height || 1));
            for(let layer = 0; layer < layers; layer++)
            {
                reads.push({ owner: t, texture: gpu.texture, level: mip, gl_level: mip + gpu.first, layer, width, height, row: columns * texel, rows,
                    extent: [columns * gpu.block, rows * (gpu.block_height || 1), 1] });
            }
        }
    },

    /** A texture's saved levels and layers put back (save_texture3's) */
    restore_texture3(t)
    {
        const gpu = this.gpu_texture3(t);
        for(const [level, layer, width, height, bytes] of gpu ? t.saved : []) this.upload3(gpu, level, [0, 0, layer], [width, height, 1], bytes);
    },

    /** A renderbuffer of one sample and a color or depth16 format: its texels */
    save_renderbuffer3(rb, reads)
    {
        rb.saved3 = true;
        const texel = TEXEL_BYTES[rb.gpu.format];
        if(rb.gpu.samples > 1 || !texel || DRAWN_DEPTH.has(rb.gpu.format) || rb.gpu.format === "stencil8") return;
        rb.saved = [];
        reads.push({ owner: rb, texture: rb.gpu.texture, level: 0, layer: 0, width: rb.width, height: rb.height, row: rb.width * texel, rows: rb.height });
    },

    restore_renderbuffer3(rb)
    {
        this.make_renderbuffer3(rb);
        for(const [, , width, height, bytes] of rb.gpu ? rb.saved || [] : [])
        {
            this.upload3({ texture: rb.gpu.texture, format: rb.gpu.format, first: 0, levels: 1, width, height, depth: 1, three: false, block: 1 }, 0,
                [0, 0, 0], [width, height, 1], bytes);
        }
        delete rb.saved;
        delete rb.saved3;
    },

    /**
     * The buffers the GPU wrote (`gpu_newer`: storage writes, transform
     * feedback, copies, pack buffers) copied out in save's encoder: their
     * bytes become the shadow's, which a restore's GPU buffer starts from
     * (gpu_buffer)
     * @return {!Array<!Object>} the reads, for saved_buffers3 once submitted
     */
    save_buffers3(encoder)
    {
        const reads = [];
        for(const group of this.shadow.groups.values())
        {
            for(const buffer of group.buffers.values())
            {
                if(!buffer.gpu || !buffer.gpu_newer || !buffer.size) continue;
                const size = Math.min(buffer.gpu.size, align4(buffer.size));
                const read = this.device.createBuffer({ label: "GLES buffer save", size, usage: B.COPY_DST | B.MAP_READ });
                encoder.copyBufferToBuffer(buffer.gpu.buffer, 0, read, 0, size);
                reads.push({ buffer, read, size });
            }
        }
        return reads;
    },

    /** save_buffers3's reads, once submitted: the buffers' bytes */
    async saved_buffers3(reads)
    {
        for(const { buffer, read, size } of reads)
        {
            await read.mapAsync(globalThis.GPUMapMode ? globalThis.GPUMapMode.READ : 1);
            const bytes = new Uint8Array(buffer.size);
            bytes.set(new Uint8Array(read.getMappedRange()).subarray(0, Math.min(size, buffer.size)));
            buffer.bytes = bytes;
            read.unmap();
            read.destroy();
        }
    },

    // ---- what is drawn to and read from

    /** An attachment as a pass's: texture, view, format, level and layer, size, samples */
    attachment3(c, a)
    {
        if(!a) return null;
        const color_buffer = t => t && { texture: t.texture, view: t.texture.createView(), format: COLOR_FORMAT, mip: 0, layer: 0, samples: 1,
            width: t.texture.width, height: t.texture.height };
        if(a.type === GL3.RENDERBUFFER)
        {
            const rb = c.group.renderbuffers.get(a.name);
            if(rb && rb.image) return color_buffer(this.image_texture(rb.image));
            if(!rb || !rb.gpu) return null;
            return { texture: rb.gpu.texture, view: rb.gpu.view, format: rb.gpu.format, mip: 0, layer: 0, samples: rb.gpu.samples, width: rb.width,
                height: rb.height, no_alpha: alpha_less(rb.format, rb.gpu.format) };
        }
        const texture = c.group.textures.get(a.name);
        const image = texture && texture.images.get(a.face * 32 + a.level);
        if(image && image.image) return color_buffer(this.image_texture(image.image));
        if(image && image.color_buffer) return color_buffer(this.color_buffer_texture(image.color_buffer));
        const gpu = texture && this.gpu_texture3(texture);
        if(!gpu || !RENDERABLE.has(gpu.format)) return null;
        const mip = a.level - gpu.first;
        if(mip < 0 || mip >= gpu.levels) return null;
        const layer = gpu.cube ? a.face : gpu.three || gpu.array ? a.layer || 0 : 0;
        const key = "attachment" + mip + ":" + (gpu.three ? 0 : layer);
        let view = gpu.views.get(key);
        if(!view)
        {
            view = gpu.three ? gpu.texture.createView({ dimension: "3d", baseMipLevel: mip, mipLevelCount: 1 }) :
                gpu.texture.createView({ dimension: "2d", baseMipLevel: mip, mipLevelCount: 1, baseArrayLayer: layer, arrayLayerCount: 1 });
            gpu.views.set(key, view);
        }
        return { texture: gpu.texture, view, format: gpu.format, mip, layer, depth_slice: gpu.three ? layer : undefined, samples: gpu.samples || 1,
            width: Math.max(1, gpu.width >> mip), height: Math.max(1, gpu.height >> mip), no_alpha: !!image && alpha_less(image_internal(image), gpu.format) };
    },

    /**
     * The draw framebuffer as a pass's attachments: a color attachment each
     * draw buffer (null for none), the depth-stencil one; null when there is
     * nothing to draw to or WebGPU cannot (sizes or samples differ)
     */
    target3(c)
    {
        if(!c.framebuffer)
        {
            const t = this.surface_target(c);
            if(!t) return null;
            const color = c.default_draw_buffer === GL3.NONE ? null :
                { texture: t.color, view: t.color_view, format: COLOR_FORMAT, mip: 0, layer: 0, samples: 1, width: t.width, height: t.height };
            return { colors: color ? [color] : [], depth: t.depth ? { view: t.depth, format: t.depth_format, texture: t.depth_texture, mip: 0, layer: 0,
                samples: 1, width: t.width, height: t.height } : null, width: t.width,
                height: t.height, samples: 1, alpha: t.alpha, key: t.key + (color ? "" : "n"), textures: new Set([t.color]) };
        }
        const fbo = c.framebuffers.get(c.framebuffer);
        if(!fbo) return null;
        const colors = (fbo.draw_buffers || [GL3.COLOR_ATTACHMENT0]).map(b => b === GL3.NONE ? null : this.attachment3(c, fbo.attachments.get(b)));
        while(colors.length && !colors[colors.length - 1]) colors.pop();
        const depth = this.attachment3(c, fbo.attachments.get(GL3.DEPTH_ATTACHMENT)) || this.attachment3(c, fbo.attachments.get(GL3.STENCIL_ATTACHMENT));
        // (a depth and stencil image attached at one point alone: the framebuffer has no buffer of the other, whose test passes)
        if(depth) Object.assign(depth, { gl_depth: !!fbo.attachments.get(GL3.DEPTH_ATTACHMENT), gl_stencil: !!fbo.attachments.get(GL3.STENCIL_ATTACHMENT) });
        const all = [...colors.filter(Boolean), ...depth ? [depth] : []];
        if(!all.length)
        {
            // (GLES 3.1: no attachments, a default size; a pass has one: a color attachment nothing is written to)
            if(!(fbo.default_width > 0 && fbo.default_height > 0)) return null;
            const samples = fbo.default_samples > 0 ? 4 : 1;
            const size = fbo.default_width + "x" + fbo.default_height + "x" + samples;
            this.empty_targets3 = this.empty_targets3 || new Map();
            let empty = this.empty_targets3.get(size);
            if(!empty)
            {
                const texture = this.device.createTexture({ label: "GLES no attachments", size: [fbo.default_width, fbo.default_height], format: "r8unorm",
                    sampleCount: samples, usage: U.RENDER_ATTACHMENT });
                empty = { texture, view: texture.createView(), format: "r8unorm", mip: 0, layer: 0, samples, width: fbo.default_width,
                    height: fbo.default_height, unwritten: true };
                this.empty_targets3.set(size, empty);
            }
            return { colors: [empty], depth: null, width: empty.width, height: empty.height, samples, alpha: true, key: "3:empty:" + size, textures: new Set() };
        }
        const { width, height, samples } = all[0];
        if(all.some(a => a.width !== width || a.height !== height)) return this.note3("attachments of different sizes");
        if(all.some(a => a.samples !== samples)) return this.note3("attachments of different samples");
        const key = "3:" + colors.map(a => a ? this.id_of(a.texture) + "." + a.mip + "." + a.layer : "-").join(",") + "/" +
            (depth ? this.id_of(depth.texture) + "." + depth.mip + "." + depth.layer : "-");
        return { colors, depth, width, height, samples, alpha: true, key, textures: new Set(all.map(a => a.texture)) };
    },

    /** What glReadPixels and the copies read: the read framebuffer's read buffer, or null */
    read_target3(c)
    {
        if(!read_framebuffer(c))
        {
            if(c.default_read_buffer === GL3.NONE) return null;
            const t = this.surface_target(c);
            return t && t.color ? { texture: t.color, format: COLOR_FORMAT, mip: 0, layer: 0, samples: 1, width: t.width, height: t.height, no_alpha: t.alpha === false } : null;
        }
        const fbo = c.framebuffers.get(read_framebuffer(c));
        if(!fbo || fbo.read_buffer === GL3.NONE) return null;
        return this.attachment3(c, fbo.attachments.get(fbo.read_buffer === undefined ? GL3.COLOR_ATTACHMENT0 : fbo.read_buffer));
    },

    /** The read framebuffer's depth (or depth and stencil) attachment */
    read_depth3(c)
    {
        if(!read_framebuffer(c))
        {
            const t = this.surface_target(c);
            return t && t.depth ? { texture: t.depth_texture, view: t.depth, format: t.depth_format, mip: 0, layer: 0, samples: 1, width: t.width,
                height: t.height } : null;
        }
        const fbo = c.framebuffers.get(read_framebuffer(c));
        return fbo ? this.attachment3(c, fbo.attachments.get(GL3.DEPTH_ATTACHMENT)) || this.attachment3(c, fbo.attachments.get(GL3.STENCIL_ATTACHMENT)) : null;
    },

    /**
     * glBlitFramebuffer: the read buffer into each draw buffer, the depth
     * buffer into the depth buffer (frag_depth); a multisampled source
     * resolved first; what keeps size, format and place a copy. The stencil
     * buffer is not copied (WebGPU writes no stencil values, gpu-deviations.md).
     */
    blit_framebuffer3(c, [sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, filter])
    {
        const target = this.target3(c);
        if(!target) return;
        let [x0, y0, x1, y1] = [Math.min(dx0, dx1), Math.min(dy0, dy1), Math.max(dx0, dx1), Math.max(dy0, dy1)];
        if(c.enabled.has(SCISSOR_TEST))
        {
            const [x, y, w, h] = c.scissor;
            [x0, y0, x1, y1] = [Math.max(x0, x), Math.max(y0, y), Math.min(x1, x + w), Math.min(y1, y + h)];
        }
        [x0, y0, x1, y1] = [Math.max(0, x0), Math.max(0, y0), Math.min(target.width, x1), Math.min(target.height, y1)];
        if(x1 <= x0 || y1 <= y0 || sx0 === sx1 || sy0 === sy1 || dx0 === dx1 || dy0 === dy1) return;
        const blit = { src: [sx0, sy0, sx1, sy1], dst: [dx0, dy0, dx1, dy1], rect: [x0, y0, x1 - x0, y1 - y0], linear: filter === LINEAR };
        if(mask & 0x4000)
        {
            let source = this.read_target3(c);
            if(source && source.samples > 1) source = this.resolve3(source);
            for(const a of source ? target.colors : []) if(a) this.blit3(source, a, blit, false);
        }
        if(mask & 0x0100 && target.depth && target.depth.format !== "stencil8")
        {
            const source = this.read_depth3(c);
            if(source && source.format !== "stencil8") this.blit3(source, target.depth, Object.assign({}, blit, { linear: false }), true);
        }
        if(mask & 0x0400) this.note3("glBlitFramebuffer's stencil (not copied)");
    },

    /** A multisampled color attachment resolved into a texture of its own (gone after the batch) */
    resolve3(source)
    {
        if(format_kind(source.format) !== "f") return this.note3("a multisampled integer read buffer resolved");
        this.end_pass();
        const texture = this.device.createTexture({ label: "GLES resolve", size: [source.width, source.height], format: source.format,
            usage: U.RENDER_ATTACHMENT | U.TEXTURE_BINDING | U.COPY_SRC });
        const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view: source.view, resolveTarget: texture.createView(), loadOp: "load", storeOp: "store" }] });
        pass.end();
        this.staging.push(texture);
        return { texture, view: texture.createView(), format: source.format, mip: 0, layer: 0, samples: 1, width: source.width, height: source.height };
    },

    /**
     * One blit of a source image into a destination attachment: a copy when
     * nothing scales, flips, clips or converts, else a draw sampling the
     * source (GL's mapping of destination pixel centers into the source)
     * @param {{src: !Array<number>, dst: !Array<number>, rect: !Array<number>, linear: boolean}} blit
     */
    blit3(source, dest, blit, depth)
    {
        const [sx0, sy0, sx1, sy1] = blit.src, [dx0, dy0, dx1, dy1] = blit.dst, [x, y, w, h] = blit.rect;
        const three = source.texture.dimension === "3d";
        // (a copy when nothing changes, but alpha into a target GL reads with alpha 1)
        if(!depth && !blit.map && source.format === dest.format && source.samples === 1 && (!dest.no_alpha || source.no_alpha) &&
            sx1 - sx0 === dx1 - dx0 && sy1 - sy0 === dy1 - dy0 && sx1 > sx0 && sy1 > sy0 &&
            x === dx0 && y === dy0 && w === dx1 - dx0 && h === dy1 - dy0 && sx0 >= 0 && sy0 >= 0 && sx1 <= source.width && sy1 <= source.height && dest.texture)
        {
            this.end_pass();
            this.encoder.copyTextureToTexture({ texture: source.texture, mipLevel: source.mip, origin: [sx0, sy0, source.layer] },
                { texture: dest.texture, mipLevel: dest.mip, origin: [dx0, dy0, dest.layer] }, [w, h, 1]);
            return;
        }
        const kind = format_kind(source.format);
        const out_kind = depth ? "depth" : format_kind(dest.format);
        if(!depth && kind === "depth") return;
        const scalar = { f: "f32", i: "i32", u: "u32" }[kind] || "f32";
        const ms = source.samples > 1;
        const linear = blit.linear && kind === "f" && !source.format.includes("32float") && !ms;
        const key = ["blit3", source.format, three ? 3 : 2, ms ? "m" : "", linear ? "l" : "n", depth ? dest.format : dest.format + ":" + out_kind,
            dest.no_alpha ? "~" : ""].join("|");
        this.blit_pipelines3 = this.blit_pipelines3 || new Map();
        let entry = this.blit_pipelines3.get(key);
        if(!entry)
        {
            const texture = kind === "depth" ? (ms ? "texture_depth_multisampled_2d" : "texture_depth_2d") : (three ? "texture_3d<" : "texture_2d<") + scalar + ">";
            const at = three ? "vec3<i32>(k, i32(p.layer))" : "k";
            const fetch = ms ? "textureLoad(t, k, 0)" : "textureLoad(t, " + at + ", 0)";
            const sample = three ? "textureSampleLevel(t, s, vec3<f32>(c / p.size, (p.layer + 0.5) / p.depth), 0.0)" : "textureSampleLevel(t, s, c / p.size, 0.0)";
            const out_type = { f: "vec4<f32>", i: "vec4<i32>", u: "vec4<u32>" }[out_kind];
            const value = kind === "depth" ? fetch : linear ? sample : fetch;
            const code = `
                struct P { src0 : vec2<f32>, scale : vec2<f32>, dst0 : vec2<f32>, size : vec2<f32>, layer : f32, depth : f32,
                    m : mat4x4<f32>, b : vec4<f32> };
                @group(0) @binding(0) var<uniform> p : P;
                @group(0) @binding(1) var t : ${texture};
                ${linear ? "@group(0) @binding(2) var s : sampler;" : ""}
                @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                    let v = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    return vec4<f32>(v[i], 0.0, 1.0);
                }
                @fragment fn fs(@builtin(position) q : vec4<f32>) -> ${depth ? "@builtin(frag_depth) f32" : "@location(0) " + out_type} {
                    let c = p.src0 + (q.xy - p.dst0) * p.scale;
                    // (a destination pixel whose source is outside the source rectangle's image: left as it is)
                    if(any(c < vec2<f32>(0.0)) || any(c >= p.size)) { discard; }
                    let k = clamp(vec2<i32>(floor(c)), vec2<i32>(0), vec2<i32>(p.size) - vec2<i32>(1));
                    ${depth ? "return " + value + ";" : out_kind === "f" ? "return p.m * vec4<f32>(" + value + ") + p.b;" : "return " + out_type + "(" + value + ");"}
                }`;
            const module = this.device.createShaderModule({ label: "GLES 3 blit", code });
            const group = this.device.createBindGroupLayout({ entries: [
                { binding: 0, visibility: 2, buffer: { type: "uniform" } },
                { binding: 1, visibility: 2, texture: { sampleType: kind === "depth" ? "depth" : kind === "i" ? "sint" : kind === "u" ? "uint" :
                    linear ? "float" : "unfilterable-float", viewDimension: three ? "3d" : "2d", multisampled: ms } },
                ...linear ? [{ binding: 2, visibility: 2, sampler: { type: "filtering" } }] : []] });
            const descriptor = { label: "GLES 3 blit", layout: this.device.createPipelineLayout({ bindGroupLayouts: [group] }),
                vertex: { module, entryPoint: "vs" }, fragment: { module, entryPoint: "fs", targets: depth ? [] : [{ format: dest.format, writeMask: dest.no_alpha ? 7 : 15 }] },
                primitive: { topology: "triangle-list" } };
            if(depth) descriptor.depthStencil = { format: dest.format, depthWriteEnabled: true, depthCompare: "always" };
            entry = { pipeline: this.device.createRenderPipeline(descriptor), group,
                sampler: linear ? this.device.createSampler({ magFilter: "linear", minFilter: "linear" }) : null };
            this.blit_pipelines3.set(key, entry);
        }
        const uniforms = new Float32Array(36);
        uniforms.set([sx0, sy0, (sx1 - sx0) / (dx1 - dx0), (sy1 - sy0) / (dy1 - dy0), dx0, dy0, source.width, source.height,
            source.layer || 0, three ? Math.max(1, source.texture.depthOrArrayLayers >> source.mip) : 1]);
        uniforms.set(blit.map ? blit.map.m : [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 12);
        uniforms.set(blit.map ? blit.map.b : [0, 0, 0, 0], 28);
        const view = three ? source.texture.createView({ dimension: "3d", baseMipLevel: source.mip, mipLevelCount: 1 }) :
            source.texture.createView({ dimension: "2d", baseMipLevel: source.mip, mipLevelCount: 1, baseArrayLayer: source.layer, arrayLayerCount: 1,
                aspect: kind === "depth" && source.format.includes("stencil") ? "depth-only" : "all" });
        this.end_pass();
        const pass = this.encoder.beginRenderPass(depth ? { colorAttachments: [], depthStencilAttachment: Object.assign({ view: dest.view,
            depthLoadOp: "load", depthStoreOp: "store" }, dest.format.includes("stencil") ? { stencilLoadOp: "load", stencilStoreOp: "store" } : {}) } :
            { colorAttachments: [Object.assign({ view: dest.view, loadOp: "load", storeOp: "store" }, dest.depth_slice !== undefined ? { depthSlice: dest.depth_slice } : {})] });
        pass.setPipeline(entry.pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: entry.group, entries: [
            { binding: 0, resource: { buffer: this.uniform_buffer(uniforms.buffer) } }, { binding: 1, resource: view },
            ...entry.sampler ? [{ binding: 2, resource: entry.sampler }] : []] }));
        pass.setScissorRect(x, y, w, h);
        pass.draw(3);
        pass.end();
    },

    /**
     * glReadPixels of a GLES 3.x context: the read buffer's texels, decoded
     * and packed by the call's format and type and the pack state (taken
     * now: later commands of the batch may change it)
     */
    read_pixels3(c, record)
    {
        if(!this.read_region3(c, record, (bytes, sink) => this.answer(sink, record.request, bytes))) this.answer_failed(record.request);
    },

    /**
     * glReadPixelsOffsetAEMU: the pixels into the pixel pack buffer, once the
     * batch's reads are back (the CPU side asks for them later, a map:
     * BUFFER_READ comes in a batch after this one)
     */
    read_pixels_pack3(c, [x, y, width, height, format, type, offset])
    {
        const buffer = c.group.buffers.get(c.buffers.pixel_pack);
        if(!buffer) return;
        const gpu = this.gpu_buffer(buffer);
        this.read_region3(c, { x, y, width, height, format, type }, bytes =>
        {
            const n = Math.min(bytes.length, buffer.size - offset);
            const copy = cpu_bytes(buffer);
            if(n <= 0 || !copy) return;
            copy.set(bytes.subarray(0, n), offset);
            // (a map in this batch read the GPU buffer before these bytes came: buffer_read3 lays them over it)
            (buffer.packed = buffer.packed || []).push([offset, n]);
            this.packed3 = this.packed3 || new Set();
            this.packed3.add(buffer);
            const low = offset & ~3, high = Math.min(gpu.size, align4(offset + n));
            this.device.queue.writeBuffer(gpu.buffer, low, copy.buffer, copy.byteOffset + low, high - low);
        });
    },

    /**
     * A rectangle of the read buffer, decoded and packed by a format and
     * type and the pack state (taken now: later commands of the batch may
     * change it), handed to `done` once read
     * @return {boolean} whether there is a read buffer to read
     */
    read_region3(c, record, done)
    {
        const source = this.read_target3(c);
        if(!source || source.samples > 1 || !TEXEL_BYTES[source.format] || format_kind(source.format) === "depth") return false;
        const pack = c.pack || NO_STORE;
        const store = { alignment: c.pack_alignment, row_length: pack.row_length, skip_pixels: pack.skip_pixels, skip_rows: pack.skip_rows };
        const x0 = Math.max(0, record.x), y0 = Math.max(0, record.y);
        const x1 = Math.min(source.width, record.x + record.width), y1 = Math.min(source.height, record.y + record.height);
        const packed = values => pack_pixels(values, record.width, record.height, record.format, record.type, store);
        if(x1 <= x0 || y1 <= y0)
        {
            this.reads.push({ buffer: null, done: (_, sink) => done(packed(new Float64Array(record.width * record.height * 4)), sink) });
            return true;
        }
        this.read_texture(source.texture, x0, y0, x1 - x0, y1 - y0, false, (raw, sink) =>
        {
            // (the part outside the read buffer: zeros)
            const w = x1 - x0;
            const decoded = decode_texels(raw, w * (y1 - y0), source.format);
            const values = new Float64Array(record.width * record.height * 4);
            for(let y = 0; y < y1 - y0; y++)
            {
                values.set(decoded.subarray(y * w * 4, (y + 1) * w * 4), ((y + y0 - record.y) * record.width + (x0 - record.x)) * 4);
            }
            done(packed(values), sink);
        }, source.mip, source.layer, TEXEL_BYTES[source.format]);
        return true;
    },

    /**
     * The render pass on a target (the open one if it is the same);
     * `clear`: {colors (values by draw buffer), depth, stencil};
     * `occlusion`: the pass counts samples (the batch's occlusion queries)
     */
    begin_pass3(target, clear, occlusion)
    {
        if(this.pass && this.pass_target === target.key && !clear && (!occlusion || this.pass_occlusion)) return this.pass;
        this.end_pass();
        const colors = target.colors.map((a, i) =>
        {
            if(!a) return null;
            const value = clear && clear.colors && clear.colors[i];
            return Object.assign({ view: a.view, storeOp: "store", loadOp: value ? "clear" : "load" },
                value ? { clearValue: { r: value[0], g: value[1], b: value[2], a: a.no_alpha ? 1 : value[3] } } : {},
                a.depth_slice !== undefined ? { depthSlice: a.depth_slice } : {});
        });
        const descriptor = { label: "GLES 3 pass", colorAttachments: colors };
        if(target.depth)
        {
            const format = target.depth.format;
            const has_depth = format !== "stencil8", has_stencil = format.includes("stencil");
            descriptor.depthStencilAttachment = Object.assign({ view: target.depth.view },
                has_depth ? { depthLoadOp: clear && clear.depth !== undefined ? "clear" : "load", depthStoreOp: "store",
                    depthClearValue: clear && clear.depth !== undefined ? clear.depth : 1 } : {},
                has_stencil ? { stencilLoadOp: clear && clear.stencil !== undefined ? "clear" : "load", stencilStoreOp: "store",
                    stencilClearValue: clear && clear.stencil !== undefined ? clear.stencil : 0 } : {});
        }
        if(occlusion) descriptor.occlusionQuerySet = this.occlusion3().set;
        this.pass = this.encoder.beginRenderPass(descriptor);
        this.pass_target = target.key;
        this.pass_occlusion = !!occlusion;
        return this.pass;
    },

    // ---- occlusion queries

    /**
     * The batch's occlusion queries: a WebGPU query a draw while a GL one is
     * active (`owners`: the GL query each, the shadow's object), summed at
     * the batch's end into the GL query's `passed` (whether any sample did;
     * a snapshot keeps it with the shadow)
     */
    occlusion3()
    {
        if(!this.occlusion) this.occlusion = { set: this.device.createQuerySet({ label: "GLES occlusion", type: "occlusion", count: 4096 }), owners: [],
            answers: [] };
        return this.occlusion;
    },

    /** The context's occlusion query in progress (the shadow's object; begun again, a new one), or null */
    occlusion_query3(c)
    {
        if(!c.active_queries) return null;
        const name = c.active_queries.get(GL3.ANY_SAMPLES_PASSED) || c.active_queries.get(GL3.ANY_SAMPLES_PASSED_CONSERVATIVE);
        return name && c.queries.get(name) || null;
    },

    /** The batch's end: the occlusion queries resolved and summed, then the results asked for answered */
    batch_end3()
    {
        // (the pack buffers' bytes that came after the last batch's maps are on the GPU now)
        for(const buffer of this.packed3 || []) buffer.packed = null;
        if(this.packed3) this.packed3.clear();
        const o = this.occlusion;
        if(!o || !o.owners.length && !o.answers.length) return;
        const owners = o.owners;
        o.owners = [];
        if(owners.length)
        {
            this.end_pass();
            const resolved = this.device.createBuffer({ label: "GLES occlusion", size: 8 * owners.length, usage: B.QUERY_RESOLVE | B.COPY_SRC });
            const read = this.device.createBuffer({ label: "GLES occlusion read", size: 8 * owners.length, usage: B.COPY_DST | B.MAP_READ });
            this.encoder.resolveQuerySet(o.set, 0, owners.length, resolved, 0);
            this.encoder.copyBufferToBuffer(resolved, 0, read, 0, 8 * owners.length);
            this.staging.push(resolved);
            this.reads.push({ buffer: read, bytes: 8 * owners.length, done: bytes =>
            {
                owners.forEach((query, i) => { if(bytes.subarray(8 * i, 8 * i + 8).some(Boolean)) query.passed = 1; });
            } });
        }
        for(const { request, query } of o.answers)
        {
            this.reads.push({ buffer: null, done: (_, sink) => this.answer(sink, request, new Uint8Array(new Uint32Array([query && query.passed || 0]).buffer)) });
        }
        o.answers = [];
    },

    /** QUERY_READ: an occlusion query's result, after the batch's own draws are counted */
    query_read3(record)
    {
        const conn = this.conns.get(record.conn);
        const c = conn && this.shadow.context(conn.context);
        if(!c) return this.answer_failed(record.request);
        this.occlusion3().answers.push({ request: record.request, query: c.queries ? c.queries.get(record.query) : null });
        return undefined;
    },

    // ---- clears

    /** glClear: every draw buffer, the depth and stencil buffers (none while RASTERIZER_DISCARD is on) */
    clear3(c, mask)
    {
        if(c.enabled.has(GL3.RASTERIZER_DISCARD)) return;
        const target = this.target3(c);
        if(!target) return;
        const color = c.clear_color.slice();
        this.clear_target3(c, target, { colors: mask & 0x4000 ? target.colors.map(a => a ? color : null) : [],
            depth: mask & 0x0100 ? c.clear_depth : undefined, stencil: mask & 0x0400 ? c.clear_stencil : undefined });
    },

    /** glClearBuffer{iv,uiv,fv,fi} (none while RASTERIZER_DISCARD is on) */
    clear_buffer3(c, name, args)
    {
        if(c.enabled.has(GL3.RASTERIZER_DISCARD)) return;
        const target = this.target3(c);
        if(!target) return;
        const [buffer, drawbuffer, value] = args;
        const bytes = value instanceof Uint8Array ? value.slice() : null;
        const words = bytes ? bytes.buffer : null;
        if(buffer === 0x1800)
        {
            if(!words || words.byteLength < 16 || !target.colors[drawbuffer]) return;
            const values = Array.from(name === "glClearBufferfv" ? new Float32Array(words, 0, 4) : name === "glClearBufferuiv" ? new Uint32Array(words, 0, 4) :
                new Int32Array(words, 0, 4));
            const colors = [];
            colors[drawbuffer] = values;
            this.clear_target3(c, target, { colors, typed: true });
        }
        else if(buffer === 0x1801 && words) this.clear_target3(c, target, { colors: [], depth: new Float32Array(words, 0, 1)[0] });
        else if(buffer === 0x1802 && words) this.clear_target3(c, target, { colors: [], stencil: new Int32Array(words, 0, 1)[0] });
        else if(buffer === 0x84F9) this.clear_target3(c, target, { colors: [], depth: args[2], stencil: args[3] });
    },

    /**
     * Clear what `want` says (colors by draw buffer, depth, stencil) by the
     * masks and the scissor: the pass's clears when nothing limits them,
     * else a quad
     */
    clear_target3(c, target, want)
    {
        const has = format => target.depth && (format === "depth" ? target.depth.format !== "stencil8" && target.depth.gl_depth !== false :
            target.depth.format.includes("stencil") && target.depth.gl_stencil !== false);
        const depth = want.depth !== undefined && c.depth_mask && has("depth") ? Math.min(1, Math.max(0, want.depth)) : undefined;
        const stencil = want.stencil !== undefined && has("stencil") ? want.stencil & 0xFF : undefined;
        const colors = want.colors.map((v, i) => v && target.colors[i] ? (target.alpha ? v : [v[0], v[1], v[2], 1]) : null);
        const any_color = colors.some(Boolean);
        if(!any_color && depth === undefined && stencil === undefined) return;
        const scissor = c.enabled.has(SCISSOR_TEST) && !(c.scissor[0] <= 0 && c.scissor[1] <= 0 && c.scissor[0] + c.scissor[2] >= target.width &&
            c.scissor[1] + c.scissor[3] >= target.height);
        const simple = !scissor && (!any_color || c.color_mask.every(Boolean)) && (stencil === undefined || (c.stencil_writemask[0] & 0xFF) === 0xFF);
        if(simple)
        {
            this.begin_pass3(target, { colors, depth, stencil });
            return;
        }
        this.clear_quad3(c, target, colors, depth, stencil);
    },

    clear_quad3(c, target, colors, depth, stencil)
    {
        const types = target.colors.map(a => a ? { f: "f32", i: "i32", u: "u32" }[format_kind(a.format)] : null);
        const mask = (c.color_mask[0] ? 1 : 0) | (c.color_mask[1] ? 2 : 0) | (c.color_mask[2] ? 4 : 0) | (c.color_mask[3] && target.alpha ? 8 : 0);
        const key = ["clear3", target.colors.map((a, i) => a ? a.format + (colors[i] ? mask : 0) : "-").join(","), target.depth ? target.depth.format : "",
            depth !== undefined ? 1 : 0, stencil !== undefined ? c.stencil_writemask[0] & 0xFF : 0, target.samples].join("|");
        let pipeline = this.pipelines.get(key);
        if(!pipeline)
        {
            const outputs = types.map((t, i) => t ? `@location(${i}) c${i} : vec4<${t}>,` : "").join("\n");
            const writes = types.map((t, i) => t ? `o.c${i} = bitcast<vec4<${t}>>(u[${i}]);` : "").join("\n");
            const code = `
                struct Out { ${outputs || "@location(0) unused : vec4<f32>,"} };
                @group(0) @binding(0) var<uniform> u : array<vec4<u32>, 5>;
                @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                    let p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                    return vec4<f32>(p[i], bitcast<f32>(u[4].x), 1.0);
                }
                @fragment fn fs() -> Out { var o : Out; ${writes} return o; }`;
            const module = this.device.createShaderModule({ label: "GLES 3 clear", code });
            const descriptor = {
                label: "GLES 3 clear", layout: "auto", vertex: { module, entryPoint: "vs" },
                fragment: { module, entryPoint: "fs", targets: target.colors.map((a, i) => a ? { format: a.format, writeMask: colors[i] ? mask & (a.no_alpha ? 7 : 15) : 0 } : null) },
                primitive: { topology: "triangle-list" }, multisample: { count: target.samples },
            };
            if(target.depth)
            {
                const format = target.depth.format;
                descriptor.depthStencil = Object.assign({ format },
                    format !== "stencil8" ? { depthWriteEnabled: depth !== undefined, depthCompare: "always" } : {},
                    format.includes("stencil") ? { stencilFront: { compare: "always", passOp: "replace" }, stencilBack: { compare: "always", passOp: "replace" },
                        stencilWriteMask: stencil !== undefined ? c.stencil_writemask[0] & 0xFF : 0 } : {});
            }
            pipeline = this.device.createRenderPipeline(descriptor);
            this.pipelines.set(key, pipeline);
        }
        const values = new ArrayBuffer(80);
        target.colors.forEach((a, i) =>
        {
            if(!a || !colors[i]) return;
            const kind = format_kind(a.format);
            (kind === "f" ? new Float32Array(values, i * 16, 4) : kind === "u" ? new Uint32Array(values, i * 16, 4) : new Int32Array(values, i * 16, 4)).set(colors[i]);
        });
        new Float32Array(values, 64, 1)[0] = depth === undefined ? 0 : depth;
        const pass = this.begin_pass3(target, null);
        pass.setPipeline(pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0),
            entries: [{ binding: 0, resource: { buffer: this.uniform_buffer(values) } }] }));
        this.apply_scissor(pass, c, target);
        pass.setViewport(0, 0, target.width, target.height, 0, 1);
        if(stencil !== undefined) pass.setStencilReference(stencil);
        pass.draw(3);
    },

    // ---- draws

    /**
     * A draw of a GLES 3.x context
     * @param {?{type: number, bytes: (Uint8Array|undefined), offset: (number|undefined), provoking: (boolean|undefined)}} elements
     *     (provoking: a list already ordered for GL's provoking vertex)
     * @param {number=} base_vertex added to each index (GLES 3.1's indirect draws of elements)
     * @param {?{buffer: !Object, offset: number}=} indirect the draw's parameters in a buffer the GPU wrote (GLES 3.1):
     *     the GPU reads them, where the draw's arrays and indices can be bound as they are
     */
    draw3(c, mode, first, count, elements, instances, base_vertex = 0, indirect = null)
    {
        if(!indirect && (count <= 0 || instances <= 0)) return;
        const stages = this.stages3(c);
        if(!stages) return;
        if(c.enabled.has(CULL_FACE) && c.cull_face === 0x0408 && mode >= 4) return;
        const target = this.target3(c);
        if(!target) return;
        this.blend_destination3(c, target);
        const shaders = this.program3(c, stages, target);
        if(!shaders) return;
        // (GLES 3.2: a draw of patches, its tessellation shaders'; a geometry shader's; lines and triangles with adjacency drawn
        // without one, the adjacent vertices left out)
        if(mode === PATCHES)
        {
            if(indirect) return void this.note3("an indirect draw of patches");
            if(stages.vertex !== stages.fragment) return void this.note3("a pipeline's tessellation shaders");
            return void this.tessellation_draw3(c, stages.vertex, shaders, target, first, count, elements, instances, base_vertex);
        }
        if(stages.vertex.info.geometry && stages.vertex === stages.fragment)
        {
            if(indirect) return void this.note3("an indirect draw of a geometry shader");
            return void this.geometry_draw3(c, stages.vertex, shaders, target, mode, first, count, elements, instances, base_vertex);
        }
        if(mode >= 0xA)
        {
            const drawn = !indirect && this.draw_vertices3(c, first, count, elements, base_vertex);
            if(!drawn) return void (indirect && this.note3("an indirect draw with adjacency"));
            const { vertices, per } = primitives_of(drawn.indices, mode, drawn.restart);
            const keep = per === 4 ? [1, 2] : [0, 2, 4];
            const list = new Uint32Array(vertices.length / per * keep.length);
            for(let p = 0, k = 0; p < vertices.length; p += per) for(const i of keep) list[k++] = vertices[p + i];
            return void this.draw3(c, per === 4 ? 1 : 4, 0, list.length, { type: 0x1405, bytes: new Uint8Array(list.buffer) }, instances);
        }
        // (GL's provoking vertex is a primitive's last, WebGPU's its first: a draw with flat varyings as a list whose primitives
        // start with their last vertex, a rotation that keeps triangles' winding; G-17's. A draw transform feedback captures
        // captures first as it is, in GL's order, without drawing; not an indirect draw: G-77)
        const tf = c.tfs && c.tfs.get(c.tf);
        if(!indirect && !(elements && elements.provoking) && mode >= 1 && mode <= 6 && shaders.flat && !this.capture_only3)
        {
            if(tf && tf.active && !tf.paused && !elements)
            {
                this.capture_only3 = true;
                try
                {
                    this.draw3(c, mode, first, count, elements, instances, base_vertex, indirect);
                }
                finally
                {
                    this.capture_only3 = false;
                }
            }
            const drawn = this.draw_vertices3(c, first, count, elements, base_vertex);
            if(drawn)
            {
                const { vertices, per } = primitives_of(drawn.indices, mode, drawn.restart);
                if(!vertices.length) return;
                const list = new Uint32Array(vertices.length);
                for(let p = 0; p < vertices.length; p += per)
                {
                    list[p] = vertices[p + per - 1];
                    for(let k = 0; k + 1 < per; k++) list[p + 1 + k] = vertices[p + k];
                }
                return void this.draw3(c, per === 2 ? 1 : 4, 0, list.length, { type: 0x1405, bytes: new Uint8Array(list.buffer), provoking: true }, instances);
            }
        }
        const plan = this.vertex_plan3(c, this.inputs3(stages.vertex), indirect ? 1 : instances);
        if(!plan) return;
        if(indirect && (plan.cpu.length || mode === 2 || mode === 6 || elements && INDEX_BYTES[elements.type] < 2)) {
            return void this.note3("an indirect draw whose arrays or indices are converted");
        }
        // the indices: the element buffer's as they are where they can be, else a list from the vertex range's first
        let list = null, low = 0, high = -1, rebase = false, topology = TOPOLOGY[mode], strip = mode === 3 || mode === 5, direct = null;
        const fan_or_loop = mode === 2 || mode === 6;
        if(elements)
        {
            const size = INDEX_BYTES[elements.type];
            const buffer = elements.bytes ? null : c.group.buffers.get(c.element_array_buffer);
            if(!size || !elements.bytes && !buffer) return;
            if(buffer && !fan_or_loop && !plan.cpu_vertex && size > 1 && (indirect || elements.offset % size === 0))
            {
                direct = { buffer: this.gpu_buffer(buffer).buffer, format: size === 2 ? "uint16" : "uint32", offset: indirect ? 0 : elements.offset };
            }
            else
            {
                const source = elements.bytes || (buffer.gpu_newer ? null : cpu_bytes(buffer));
                if(!source) return void this.note3("indices the GPU wrote, converted");
                const offset = elements.bytes ? 0 : elements.offset;
                if(offset + count * size > source.length) return;
                const view = new DataView(source.buffer, source.byteOffset + offset, count * size);
                const indices = new Uint32Array(count);
                for(let i = 0; i < count; i++) indices[i] = size === 1 ? view.getUint8(i) : size === 2 ? view.getUint16(2 * i, true) : view.getUint32(4 * i, true);
                // (a base vertex: GLES 3.1's indirect draws; the restart index stays one)
                const restart_index = size === 1 ? 0xFF : size === 2 ? 0xFFFF : 0xFFFFFFFF;
                if(base_vertex) for(let i = 0; i < count; i++) if(!c.enabled.has(RESTART) || indices[i] !== restart_index) indices[i] += base_vertex;
                const r = index_list(indices, mode, c.enabled.has(RESTART) ? (size === 1 ? 0xFF : size === 2 ? 0xFFFF : 0xFFFFFFFF) : -1);
                this.stats.index_lists = (this.stats.index_lists || 0) + 1;
                if(!r || !r.list.length) return;
                ({ list, low, high, topology, strip } = r);
                rebase = true;
            }
        }
        else if(fan_or_loop)
        {
            const r = index_list(Uint32Array.from({ length: count }, (_, i) => first + i), mode, -1);
            this.stats.index_lists = (this.stats.index_lists || 0) + 1;
            if(!r || !r.list.length) return;
            ({ list, low, high, topology, strip } = r);
            rebase = true;
        }
        else if(plan.cpu_vertex)
        {
            low = first;
            high = first + count - 1;
            rebase = true;
        }
        if(rebase && high - low >= 1 << 24) return void this.note3("a vertex range past 2^24");
        const vertex = this.vertex_buffers3(c, plan, { low, high, rebase, instances: indirect ? 0 : instances, indexed: !!(list || direct || indirect), first,
            count });
        if(!vertex) return;
        const group = this.bind_groups3(c, shaders.bindings, target);
        if(!group) return;
        if(!elements && !indirect) this.capture3(c, stages.vertex, group, vertex, mode, first, count, instances, rebase);
        // (rasterizer discard: what transform feedback captured, nothing drawn; a capture before a reordered draw, the same)
        if(c.enabled.has(GL3.RASTERIZER_DISCARD) || this.capture_only3) return;
        if(c.viewport[2] <= 0 || c.viewport[3] <= 0) return;
        let index_buffer = null;
        if(list)
        {
            index_buffer = this.device.createBuffer({ label: "GLES indices", size: align4(Math.max(4, list.byteLength)), usage: B.INDEX, mappedAtCreation: true });
            new Uint32Array(index_buffer.getMappedRange()).set(list);
            index_buffer.unmap();
            this.staging.push(index_buffer);
        }
        const strip_format = strip && (list || direct) ? (direct ? direct.format : "uint32") : undefined;
        // (the parameters' GPU buffer before the pass: its bytes may go up first)
        const parameters = indirect && this.gpu_buffer(indirect.buffer).buffer;
        this.render3(c, target, shaders, vertex, group, topology, strip_format, mode, pass =>
        {
            if(indirect)
            {
                if(direct)
                {
                    pass.setIndexBuffer(direct.buffer, direct.format, 0);
                    pass.drawIndexedIndirect(parameters, indirect.offset);
                }
                else pass.drawIndirect(parameters, indirect.offset);
            }
            else if(index_buffer)
            {
                pass.setIndexBuffer(index_buffer, "uint32");
                pass.drawIndexed(list.length, instances);
            }
            else if(direct)
            {
                pass.setIndexBuffer(direct.buffer, direct.format, direct.offset);
                pass.drawIndexed(count, instances, 0, base_vertex);
            }
            else pass.draw(count, instances, rebase ? 0 : first, 0);
        });
    },

    /**
     * A draw's render passes (one a stencil face where they differ): the
     * pipeline, the resources, vertex buffers, viewport, scissor, the blend
     * and stencil references, the occlusion query; `draw` draws in the pass
     * @param {function(!GPURenderPassEncoder)} draw
     */
    render3(c, target, shaders, vertex, group, topology, strip_format, mode, draw)
    {
        const [vx, vy, vw, vh] = c.viewport;
        const occlusion = this.occlusion_query3(c);
        for(const face of this.stencil_faces3(c, target, mode))
        {
            const pipeline = this.pipeline3(c, shaders, vertex, group, topology, strip_format, target, face);
            if(!pipeline) return;
            const pass = this.begin_pass3(target, null, !!occlusion);

            pass.setPipeline(pipeline);
            for(const g of group.groups) pass.setBindGroup(g.index, this.device.createBindGroup({ layout: g.layout, entries: g.resources }));
            vertex.slots.forEach((s, i) => pass.setVertexBuffer(i, s.gpu, s.offset));
            pass.setViewport(vx, vy, vw, vh, Math.min(c.depth_range[0], c.depth_range[1]), Math.max(c.depth_range[0], c.depth_range[1]));
            if(!this.apply_scissor(pass, c, target)) return;
            // (CONSTANT_ALPHA's factors are WebGPU's constant ones of the alpha in every channel: G-70)
            pass.setBlendConstant(c.blend_func.some(f => f === 0x8003 || f === 0x8004) ?
                { r: c.blend_color[3], g: c.blend_color[3], b: c.blend_color[3], a: c.blend_color[3] } :
                { r: c.blend_color[0], g: c.blend_color[1], b: c.blend_color[2], a: c.blend_color[3] });
            if(c.enabled.has(STENCIL_TEST)) pass.setStencilReference(c.stencil_func[face === undefined ? 0 : face][1] & 0xFF);
            const o = occlusion && this.occlusion3();
            const query = o && o.owners.length < 4096 ? o.owners.push(occlusion) - 1 : -1;
            if(query >= 0) pass.beginOcclusionQuery(query);
            draw(pass);
            if(query >= 0) pass.endOcclusionQuery();
        }
        this.stats.draws++;
    },

    /**
     * An advanced blend's destination (GLES 3.2): the draw's color target
     * copied before it, which the fragment shader reads and blends with
     * (glsl_es_rewrite.js), in `blend_dst3`; null for a draw that does not
     * blend so
     */
    blend_destination3(c, target)
    {
        this.blend_dst3 = null;
        if(advanced_blend(c) < 0) return;
        const color = target.colors[0];
        if(!color || color.unwritten) return;
        if(color.samples > 1) return void this.note3("an advanced blend into a multisampled target");
        const copy = this.device.createTexture({ label: "GLES blend destination", size: [target.width, target.height], format: color.format,
            usage: U.TEXTURE_BINDING | U.COPY_DST });
        this.end_pass();
        this.encoder.copyTextureToTexture({ texture: color.texture, mipLevel: color.mip, origin: [0, 0, color.layer || 0] }, { texture: copy },
            [target.width, target.height, 1]);
        this.staging.push(copy);
        this.blend_dst3 = { view: copy.createView(), format: color.format };
    },

    /**
     * A draw's vertices in order (its indices, a base vertex added but not to
     * the restart index), from client memory or the element buffer's bytes
     * @return {?{indices: !Uint32Array, restart: number}} (restart: the restart index, -1 for none)
     */
    draw_vertices3(c, first, count, elements, base_vertex)
    {
        if(!elements) return { indices: Uint32Array.from({ length: count }, (_, i) => first + i), restart: -1 };
        const size = INDEX_BYTES[elements.type];
        const buffer = elements.bytes ? null : c.group.buffers.get(c.element_array_buffer);
        const source = elements.bytes || buffer && (buffer.gpu_newer ? null : cpu_bytes(buffer));
        if(!size || !source) return this.note3("indices the GPU wrote, converted");
        const offset = elements.bytes ? 0 : elements.offset;
        if(offset + count * size > source.length) return null;
        const view = new DataView(source.buffer, source.byteOffset + offset, count * size);
        const restart = c.enabled.has(RESTART) ? (size === 1 ? 0xFF : size === 2 ? 0xFFFF : 0xFFFFFFFF) : -1;
        const indices = new Uint32Array(count);
        for(let i = 0; i < count; i++)
        {
            const v = size === 1 ? view.getUint8(i) : size === 2 ? view.getUint16(2 * i, true) : view.getUint32(4 * i, true);
            indices[i] = v === restart ? v : v + base_vertex;
        }
        return { indices, restart };
    },

    // ---- geometry shaders (GLES 3.2; vx_naga's geometry.rs)

    /** vx_naga's JSON answer of `call` (input, its length) with the SPIR-V words in its memory */
    naga_json3(words, call)
    {
        const naga = this.naga;
        const bytes = new Uint8Array(words.buffer, words.byteOffset, words.byteLength);
        const input = naga.vx_alloc(bytes.length);
        new Uint8Array(naga.memory.buffer, input, bytes.length).set(bytes);
        let out;
        try
        {
            out = call(input, bytes.length);
        }
        finally
        {
            naga.vx_free(input, bytes.length);
        }
        const length = new DataView(naga.memory.buffer).getUint32(out, true);
        const t = JSON.parse(new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length)));
        naga.vx_free(out, length + 4);
        return t;
    },

    /** A program's geometry shader through vx_naga (cached with the program's GPU side), or null (noted) */
    geometry3(program)
    {
        const gpu = this.program_gpu(program);
        if(gpu.geometry !== undefined) return gpu.geometry;
        gpu.geometry = null;
        const m = program.info.spirv.find(x => x.stage === "geometry");
        if(!m || !this.naga.vx_translate_geometry) return this.note3("a geometry shader vx_naga cannot translate");
        const t = this.naga_json3(m.words, (input, length) => this.naga.vx_translate_geometry(input, length, 1, 0, 0));
        if(t.error) return this.note3("vx_naga's geometry shader: " + t.error.slice(0, 160));
        gpu.geometry = { translation: t, layout: t.geometry, passes: new Map(), pipelines: new Map(),
            module: this.device.createShaderModule({ label: "GLES 3 geometry", code: "diagnostic(off, derivative_uniformity);\n" + t.wgsl }) };
        return gpu.geometry;
    },

    /**
     * The vertex shader that passes a geometry shader's list on to the
     * fragment shader: the record's position in WebGPU's clip space (GL's
     * depth halved, Y flipped as vx_naga's), each output the fragment shader
     * reads at its location with the fragment input's interpolation; the
     * list's vertex attributes
     */
    pass_shader3(g, shaders)
    {
        const key = this.id_of(shaders.fragment.module);
        let pass = g.passes.get(key);
        if(pass) return pass;
        const inputs = fragment_inputs(shaders.fragment.wgsl);
        const scalar = { f: "f32", i: "i32", u: "u32" };
        const outputs = g.layout.outputs.filter(o => inputs.has(o[0]));
        const type = o => o[2] === 1 ? scalar[o[1]] : "vec" + o[2] + "<" + scalar[o[1]] + ">";
        const code = "struct VxPassOut {\n    @builtin(position) position: vec4<f32>,\n" +
            outputs.map((o, i) => `    @location(${o[0]}) ${inputs.get(o[0])} o${i}: ${type(o)},\n`).join("") + "}\n" +
            "@vertex fn vx_pass(@location(0) p: vec4<f32>" + outputs.map((o, i) => `, @location(${i + 1}) a${i}: ${type(o)}`).join("") + ") -> VxPassOut {\n" +
            "    var o: VxPassOut;\n    o.position = vec4<f32>(p.x, -p.y, (p.z + p.w) * 0.5, p.w);\n" +
            outputs.map((o, i) => `    o.o${i} = a${i};\n`).join("") + "    return o;\n}\n";
        const format = o => ({ f: "float32", i: "sint32", u: "uint32" })[o[1]] + (o[2] > 1 ? "x" + o[2] : "");
        pass = { module: this.device.createShaderModule({ label: "GLES 3 geometry pass", code }), attributes: [{ shaderLocation: 0, offset: 0, format: "float32x4" },
            ...outputs.map((o, i) => ({ shaderLocation: i + 1, offset: 4 * (8 + 4 * o[0]), format: format(o) }))] };
        g.passes.set(key, pass);
        return pass;
    },

    /** The largest buffer a compute pass binds */
    most3()
    {
        return this.device.limits ? Math.min(this.device.limits.maxStorageBufferBindingSize, this.device.limits.maxBufferSize) : 1 << 27;
    },

    /**
     * The resources of a draw whose stages run as compute shaders too (a
     * geometry or tessellation shader's): the fragment shader's, the vertex
     * shader's seen by compute shaders as well, and the translations'
     */
    stages_group3(c, program, shaders, translations, target)
    {
        const merged = new Map(shaders.bindings.map(b => [b.group + ":" + b.binding, Object.assign({}, b, { visibility: b.visibility | (b.visibility & 1 ? 4 : 0) })]));
        for(const b of this.bindings3(translations.map(t => [t, 4, program])))
        {
            const key = b.group + ":" + b.binding;
            if(merged.has(key)) merged.get(key).visibility |= 4;
            else merged.set(key, b);
        }
        return this.bind_groups3(c, [...merged.values()].sort((a, b) => a.group - b.group || a.binding - b.binding), target);
    },

    /**
     * The vertex shader run as a compute shader over the vertices a draw's
     * primitives or patches use, every output captured (xfb3's `all`): the
     * records, a record's bytes, and each primitive's vertices' record
     * indices (each instance's after the last's), in a buffer
     * @param {!Uint32Array} vertices the primitives' vertices in order
     * @return {?{records: !GPUBuffer, record: number, ids_buffer: !GPUBuffer}}
     */
    vertex_records3(c, program, group, vertices, instances)
    {
        let low = Infinity, high = -1;
        for(const v of vertices) { if(v < low) low = v; if(v > high) high = v; }
        if(high - low >= 1 << 24) return this.note3("a vertex range past 2^24");
        const plan = this.vertex_plan3(c, this.inputs3(program), instances);
        if(!plan) return null;
        const vcount = high - low + 1, rebase = plan.cpu_vertex;
        const vertex = this.vertex_buffers3(c, plan, { low, high, rebase, instances, indexed: false, first: low, count: vcount });
        if(!vertex) return null;
        const capture = this.xfb3(program, vertex, true);
        if(!capture) return null;
        const record = capture.xfb.strides[0];
        if(vcount * instances * record > this.most3()) return this.note3("a draw's vertex records too large");
        const records = this.device.createBuffer({ label: "GLES vertex records", size: Math.max(16, align4(vcount * instances * record)), usage: B.STORAGE });
        this.staging.push(records);
        this.capture_pass3(capture, group, vertex, rebase ? 0 : low, vcount, instances, [records]);
        const ids = new Uint32Array(Math.max(4, vertices.length * instances));
        for(let i = 0; i < instances; i++) for(let k = 0; k < vertices.length; k++) ids[i * vertices.length + k] = i * vcount + vertices[k] - low;
        const ids_buffer = this.device.createBuffer({ label: "GLES primitives' vertices", size: ids.byteLength, usage: B.STORAGE, mappedAtCreation: true });
        new Uint32Array(ids_buffer.getMappedRange()).set(ids);
        ids_buffer.unmap();
        this.staging.push(ids_buffer);
        return { records, record, ids_buffer };
    },

    /** A program's tessellation shaders through vx_naga (cached with the program's GPU side), or null (noted) */
    tessellation3(program)
    {
        const gpu = this.program_gpu(program);
        if(gpu.tessellation !== undefined) return gpu.tessellation;
        gpu.tessellation = null;
        const stage = name => program.info.spirv.find(x => x.stage === name);
        const control = stage("tess_control"), evaluation = stage("tess_evaluation");
        if(!control || !evaluation) return this.note3("patches without tessellation shaders");
        if(!this.naga.vx_translate_tessellation) return this.note3("tessellation shaders vx_naga cannot translate");
        const [tc, te] = [[control, 1], [evaluation, 0]].map(([m, is_control]) =>
            this.naga_json3(m.words, (input, length) => this.naga.vx_translate_tessellation(input, length, is_control, 1)));
        const failed = [tc, te].find(t => t.error);
        if(failed) return this.note3("vx_naga's tessellation shader: " + failed.error.slice(0, 160));
        const module = t => this.device.createShaderModule({ label: "GLES 3 tessellation", code: "diagnostic(off, derivative_uniformity);\n" + t.wgsl });
        gpu.tessellation = { tc, te, control: module(tc), evaluation: module(te), pipelines: new Map(),
            // (pass_shader3's: the evaluation shader's outputs as a geometry shader's)
            pass: { layout: te.tessellation, passes: new Map() } };
        return gpu.tessellation;
    },

    /** GX's tessellator (tessellator_wgsl.js): its count, scan and generate pipelines, made once */
    tessellator3()
    {
        if(this.tessellator) return this.tessellator;
        // (a script of the page's WebGPU bundle before this one: tools/build_glbridge.mjs)
        const module = this.device.createShaderModule({ label: "GLES tessellator", code: globalThis["V86TessellatorWGSL"].TESSELLATOR_WGSL });
        const layout = this.device.createBindGroupLayout({ entries: [
            { binding: 0, visibility: 4, buffer: { type: "uniform" } },
            { binding: 1, visibility: 4, buffer: { type: "read-only-storage" } },
            ...[2, 3, 4, 5, 6].map(binding => ({ binding, visibility: 4, buffer: { type: "storage" } })),
        ] });
        const pipeline_layout = this.device.createPipelineLayout({ bindGroupLayouts: [layout] });
        const make = entryPoint => this.device.createComputePipeline({ label: "GLES tessellator " + entryPoint, layout: pipeline_layout,
            compute: { module, entryPoint } });
        this.tessellator = { layout, count: make("count"), scan: make("scan"), generate: make("generate") };
        return this.tessellator;
    },

    /** A compute pipeline of a stage's module and entry point: the draw's resources in group 0, its own in group 1 (`own`'s entries) */
    stage_pipeline3(cache, group, module, entry, own)
    {
        const key = entry + ":" + group.key;
        let p = cache.get(key);
        if(!p)
        {
            const layouts = [group.groups[0].layout, this.device.createBindGroupLayout({ entries: own })];
            p = { layouts, pipeline: this.device.createComputePipeline({ label: "GLES 3 " + entry, layout: this.device.createPipelineLayout({ bindGroupLayouts: layouts }),
                compute: { module, entryPoint: entry } }) };
            cache.set(key, p);
        }
        return p;
    },

    /**
     * A draw of patches (GLES 3.2's tessellation; the guest's wire has no
     * glPatchParameteri: 3 vertices a patch): the vertex shader as a
     * compute shader over the patches' vertices; the control shader a
     * workgroup a patch (vx_naga's tessellation.rs); GX's tessellator (its
     * counts, their sums and the indirect arguments, the points and
     * indices); the evaluation shader an invocation a point (an indirect
     * dispatch); the points drawn by the indices (an indirect draw) through
     * the pass shader with the fragment shader
     */
    tessellation_draw3(c, program, shaders, target, first, count, elements, instances, base_vertex)
    {
        if(count <= 0 || instances <= 0) return;
        const t = this.tessellation3(program);
        if(!t) return;
        const tf = c.tfs && c.tfs.get(c.tf);
        if(tf && tf.active && !tf.paused) this.note3("transform feedback of tessellation's output");
        if(program.info.geometry) this.note3("a geometry shader after tessellation: left out");
        const drawn = this.draw_vertices3(c, first, count, elements, base_vertex);
        if(!drawn) return;
        const per = PATCH_VERTICES;
        const per_instance = Math.floor(drawn.indices.length / per);
        if(!per_instance) return;
        const vertices = drawn.indices.subarray(0, per_instance * per);
        const group = this.stages_group3(c, program, shaders, [t.tc, t.te], target);
        if(!group) return;
        const control = t.tc.tessellation, evaluation = t.te.tessellation;
        const total = per_instance * instances;
        // (room for what the tessellator makes, at the largest level: GX's bounds)
        const points_most = Math.min(total * 65 * 66, 1 << 18), indices_most = Math.min(total * (6 * 64 * 64 + 12 * 64), 3 << 19);
        const sizes = [total * control.vertices * control.cp_stride * 4, total * control.patch_stride * 4, points_most * evaluation.stride * 4,
            points_most * 16, indices_most * 4];
        if(sizes.some(n => n > this.most3()) || total > 65535 * 65535) return void this.note3("a draw of patches too large");
        const captured = this.vertex_records3(c, program, group, vertices, instances);
        if(!captured) return;
        const buffer = (size, usage) => { const b = this.device.createBuffer({ label: "GLES tessellation", size: Math.max(32, align4(size)), usage }); this.staging.push(b); return b; };
        const control_points = buffer(sizes[0], B.STORAGE), patches = buffer(sizes[1], B.STORAGE), vertices_out = buffer(sizes[2], B.STORAGE | B.VERTEX);
        const points = buffer(sizes[3], B.STORAGE), indices = buffer(sizes[4], B.STORAGE | B.INDEX);
        const counts = buffer(total * 8, B.STORAGE), offsets = buffer(total * 8, B.STORAGE);
        const args = buffer(32, B.STORAGE | B.INDIRECT | B.COPY_SRC), draw_args = buffer(32, B.INDIRECT | B.COPY_DST);
        const read = { buffer: { type: "read-only-storage" } }, write = { buffer: { type: "storage" } }, uniform = { buffer: { type: "uniform" } };
        const entries = list => list.map((resource, i) => ({ binding: 960 + i, resource: resource.buffer ? resource : { buffer: resource } }));
        const layout_of = list => list.map((type, i) => Object.assign({ binding: 960 + i, visibility: 4 }, type));
        const tc = this.stage_pipeline3(t.pipelines, group, t.control, "vx_tess_control", layout_of([uniform, read, read, write, write]));
        const te = this.stage_pipeline3(t.pipelines, group, t.evaluation, "vx_tess_eval", layout_of([uniform, read, read, read, read, write]));
        const tess = this.tessellator3();
        const group0 = layout => this.device.createBindGroup({ layout, entries: group.groups[0].resources });
        this.end_pass();
        const pass = this.encoder.beginComputePass({ label: "GLES 3 tessellation" });
        // the control shader: a workgroup a patch
        pass.setPipeline(tc.pipeline);
        pass.setBindGroup(0, group0(tc.layouts[0]));
        pass.setBindGroup(1, this.device.createBindGroup({ layout: tc.layouts[1], entries: entries([
            { buffer: this.uniform_buffer(new Uint32Array([total, captured.record / 4, per, per_instance, evaluation.domain, 0, 0, 0]).buffer) },
            captured.records, captured.ids_buffer, control_points, patches]) }));
        pass.dispatchWorkgroups(Math.min(total, 65535), Math.ceil(total / 65535));
        // the tessellator: counts, sums, points and indices
        const groups = Math.ceil(total / 64);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: tess.layout, entries: [
            { buffer: this.uniform_buffer(new Uint32Array([total, evaluation.domain, evaluation.spacing, evaluation.primitive, control.patch_stride / 4, 0,
                points_most, indices_most]).buffer) },
            { buffer: patches }, { buffer: counts }, { buffer: offsets }, { buffer: points }, { buffer: indices }, { buffer: args },
        ].map((resource, binding) => ({ binding, resource })) }));
        for(const [pipeline, n] of [[tess.count, groups], [tess.scan, 1], [tess.generate, groups]])
        {
            pass.setPipeline(pipeline);
            pass.dispatchWorkgroups(Math.min(n, 65535), Math.ceil(n / 65535));
        }
        pass.end();
        // the evaluation shader: an invocation a point (the dispatch the scan wrote: a pass of its own)
        const evaluate = this.encoder.beginComputePass({ label: "GLES 3 tessellation evaluation" });
        evaluate.setPipeline(te.pipeline);
        evaluate.setBindGroup(0, group0(te.layouts[0]));
        evaluate.setBindGroup(1, this.device.createBindGroup({ layout: te.layouts[1], entries: entries([
            { buffer: this.uniform_buffer(new Uint32Array([per_instance, control.cp_stride, control.patch_stride, control.vertices, evaluation.domain, 0, 0, 0]).buffer) },
            control_points, patches, points, args, vertices_out]) }));
        evaluate.dispatchWorkgroupsIndirect(args, 0);
        evaluate.end();
        // (the draw's arguments: the scan's index count, one instance, the first instance 0, which indirect-first-instance would want otherwise)
        this.encoder.copyBufferToBuffer(args, 12, draw_args, 0, 16);
        this.stats.tessellation = (this.stats.tessellation || 0) + 1;
        if(c.enabled.has(GL3.RASTERIZER_DISCARD) || c.viewport[2] <= 0 || c.viewport[3] <= 0) return;
        const through = this.pass_shader3(t.pass, shaders);
        const pass_shaders = { vertex: { module: through.module, entry: "vx_pass" }, fragment: shaders.fragment, outputs: shaders.outputs,
            id: this.id_of(through.module) + ":" + this.id_of(shaders.fragment.module) };
        const stride = 4 * evaluation.stride;
        const list_vertex = { slots: [{ gpu: vertices_out, offset: 0, stride, step: "vertex", attributes: through.attributes }],
            key: "t" + stride + ":" + JSON.stringify(through.attributes) };
        const topology = ["point-list", "point-list", "line-list", "triangle-list", "triangle-list"][evaluation.primitive];
        this.render3(c, target, pass_shaders, list_vertex, group, topology, undefined, [0, 0, 1, 4, 4][evaluation.primitive], render =>
        {
            render.setIndexBuffer(indices, "uint32");
            render.drawIndexedIndirect(draw_args, 0);
        });
    },

    /**
     * A draw of a program with a geometry shader: the draw's primitives
     * assembled on the CPU; the vertex shader run as a compute shader over
     * the vertices they use, every output captured (xfb3's `all`); the
     * geometry shader as one, an invocation an input primitive and
     * invocation, into a list of primitives; the list drawn through the pass
     * shader with the fragment shader
     */
    geometry_draw3(c, program, shaders, target, mode, first, count, elements, instances, base_vertex)
    {
        if(count <= 0 || instances <= 0) return;
        const g = this.geometry3(program);
        if(!g) return;
        const tf = c.tfs && c.tfs.get(c.tf);
        if(tf && tf.active && !tf.paused) this.note3("transform feedback of a geometry shader's output");
        const drawn = this.draw_vertices3(c, first, count, elements, base_vertex);
        if(!drawn) return;
        const { vertices, per } = primitives_of(drawn.indices, mode, drawn.restart);
        if(per !== g.layout.input || !vertices.length) return;
        const group = this.stages_group3(c, program, shaders, [g.translation], target);
        if(!group) return;
        const layout = g.layout;
        const prims = vertices.length / per, total = prims * instances, invocations = total * layout.invocations;
        const out_record = 4 * layout.stride;
        const sizes = [invocations * layout.max_vertices * out_record, invocations * layout.list * out_record];
        if(sizes.some(n => n > this.most3()) || Math.ceil(invocations / 64) > 65535) return void this.note3("a geometry shader's draw too large");
        const captured = this.vertex_records3(c, program, group, vertices, instances);
        if(!captured) return;
        const { records, record, ids_buffer } = captured;
        const [emitted, list] = sizes.map((n, i) => this.device.createBuffer({ label: "GLES geometry", size: Math.max(16, align4(n)),
            usage: B.STORAGE | (i === 1 ? B.VERTEX : 0) }));
        this.staging.push(emitted, list);
        const own = [{ binding: 960, visibility: 4, buffer: { type: "uniform" } }, { binding: 961, visibility: 4, buffer: { type: "read-only-storage" } },
            { binding: 962, visibility: 4, buffer: { type: "read-only-storage" } }, { binding: 963, visibility: 4, buffer: { type: "storage" } },
            { binding: 964, visibility: 4, buffer: { type: "storage" } }];
        const key = group.key;
        let p = g.pipelines.get(key);
        if(!p)
        {
            const layouts = [group.groups[0].layout, this.device.createBindGroupLayout({ entries: own })];
            p = { layouts, pipeline: this.device.createComputePipeline({ label: "GLES 3 geometry", layout: this.device.createPipelineLayout({ bindGroupLayouts: layouts }),
                compute: { module: g.module, entryPoint: "vx_geometry" } }) };
            g.pipelines.set(key, p);
        }
        const params = new Uint32Array([total, record / 4, prims, 0]);
        this.end_pass();
        const pass = this.encoder.beginComputePass({ label: "GLES 3 geometry" });
        pass.setPipeline(p.pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: p.layouts[0], entries: group.groups[0].resources }));
        pass.setBindGroup(1, this.device.createBindGroup({ layout: p.layouts[1], entries: [{ binding: 960, resource: { buffer: this.uniform_buffer(params.buffer) } },
            ...[records, ids_buffer, emitted, list].map((buffer, i) => ({ binding: 961 + i, resource: { buffer } }))] }));
        pass.dispatchWorkgroups(Math.ceil(invocations / 64));
        pass.end();
        this.stats.geometry = (this.stats.geometry || 0) + 1;
        // the list drawn
        if(c.enabled.has(GL3.RASTERIZER_DISCARD)) return;
        if(c.viewport[2] <= 0 || c.viewport[3] <= 0) return;
        const through = this.pass_shader3(g, shaders);
        const pass_shaders = { vertex: { module: through.module, entry: "vx_pass" }, fragment: shaders.fragment, outputs: shaders.outputs,
            id: this.id_of(through.module) + ":" + this.id_of(shaders.fragment.module) };
        const list_vertex = { slots: [{ gpu: list, offset: 0, stride: out_record, step: "vertex", attributes: through.attributes }],
            key: "g" + out_record + ":" + JSON.stringify(through.attributes) };
        const topology = ["point-list", "line-list", "triangle-list"][layout.output];
        this.render3(c, target, pass_shaders, list_vertex, group, topology, undefined, [0, 1, 4][layout.output], pass => pass.draw(invocations * layout.list));
    },

    /** The stencil faces a draw is made of (gles_executor.js's stencil_faces, with the target's depth format) */
    stencil_faces3(c, target, mode)
    {
        const format = target.depth ? target.depth.format : "";
        return this.stencil_faces(c, { depth: !!target.depth, depth_format: format }, mode);
    },

    /**
     * How each vertex input is read: from its buffer directly, assembled on
     * the CPU, or its current value
     * @return {?{direct: !Array<!Object>, cpu: !Array<!Object>, constants: !Array<!Object>, cpu_vertex: boolean}}
     */
    vertex_plan3(c, inputs, instances)
    {
        const direct = [], cpu = [], constants = [];
        for(const input of inputs)
        {
            const a = input.unused ? UNUSED_INPUT : c.attribs[input.location];
            if(!a) return this.note3("an input past the attributes");
            if(!a.enabled)
            {
                // (its current value: the context's, not the vertex array's, GLES 3.0 table 6.6)
                const current = !input.unused && c.current_values && c.current_values[input.location];
                constants.push({ input, a: current ? { current: current.values } : a });
                continue;
            }
            const step = a.divisor ? "instance" : "vertex";
            const buffer = !a.data && a.buffer ? c.group.buffers.get(a.buffer) : null;
            const format = buffer && buffer.size && !(a.divisor > 1 && instances > 1) ? direct_format(a, input.kind) : null;
            if(format)
            {
                const component = packed_attribute(a.type) ? 4 : TYPE_BYTES[a.type];
                const element = packed_attribute(a.type) ? 4 : a.size * component;
                const stride = a.stride || element;
                if(stride % 4 === 0 && stride <= 2048 && a.offset % Math.min(4, component) === 0 && (a.offset & 3) + element <= stride)
                {
                    direct.push({ input, a, buffer, format, stride, step, element });
                    continue;
                }
            }
            if(buffer && buffer.gpu_newer) return this.note3("a vertex array the GPU wrote, converted");
            cpu.push({ input, a, step });
        }
        return { direct, cpu, constants, cpu_vertex: cpu.some(x => x.step === "vertex") };
    },

    /**
     * The draw's vertex buffers by the plan: direct arrays sharing a slot
     * where their buffer, stride and step agree and their offsets fit in one
     * vertex; the CPU's in one buffer a step; the current values in one
     * @param {{low: number, high: number, rebase: boolean, instances: number, indexed: boolean, first: number, count: number}} range
     * @return {?{slots: !Array<!Object>, key: string}}
     */
    vertex_buffers3(c, plan, range)
    {
        const slots = [];
        const groups = new Map();
        for(const d of plan.direct)
        {
            const key = d.a.buffer + ":" + d.stride + ":" + d.step;
            if(!groups.has(key)) groups.set(key, []);
            groups.get(key).push(d);
        }
        for(const list of groups.values())
        {
            list.sort((x, y) => x.a.offset - y.a.offset);
            let slot = null;
            for(const d of list)
            {
                if(!slot || d.a.offset - slot.base + d.element > d.stride)
                {
                    slot = { buffer: d.buffer, base: d.a.offset & ~3, stride: d.stride, step: d.step, attributes: [], end: 0 };
                    slots.push(slot);
                }
                slot.attributes.push({ shaderLocation: d.input.location, offset: d.a.offset - slot.base, format: d.format });
                slot.end = Math.max(slot.end, d.a.offset - slot.base + d.element);
            }
        }
        for(const slot of slots)
        {
            const gpu = this.gpu_buffer(slot.buffer);
            slot.gpu = gpu.buffer;
            slot.offset = slot.base + (slot.step === "vertex" && range.rebase ? range.low * slot.stride : 0);
            // (what WebGPU checks of a draw's vertex and instance ranges: GL leaves reads past a buffer undefined)
            const last = slot.step === "instance" ? range.instances - 1 : range.indexed ? -1 : range.rebase ? range.count - 1 : range.first + range.count - 1;
            if(slot.offset > slot.buffer.size || last >= 0 && slot.offset + last * slot.stride + slot.end > slot.buffer.size)
            {
                return this.note3("a vertex array past its buffer");
            }
        }
        for(const step of ["vertex", "instance"])
        {
            const list = plan.cpu.filter(x => x.step === step);
            if(!list.length) continue;
            const n = step === "vertex" ? range.high - range.low + 1 : range.instances;
            if(n <= 0) return null;
            const stride = list.reduce((s, x) => s + x.input.components * 4, 0);
            const words = new Uint32Array(n * stride / 4);
            const attributes = [];
            let offset = 0;
            for(const x of list)
            {
                const components = x.input.components;
                const values = this.values3(c, x.a, step === "vertex" ? range.low : 0, n, components, x.input.kind,
                    step === "vertex" ? 0 : Math.max(1, x.a.divisor));
                if(!values) return this.note3("a vertex array with no data");
                const raw = new Uint32Array(values.buffer);
                for(let v = 0; v < n; v++) for(let k = 0; k < components; k++) words[(v * stride + offset) / 4 + k] = raw[v * components + k];
                attributes.push({ shaderLocation: x.input.location, offset, format: CPU_FORMAT[x.input.kind] + (components > 1 ? "x" + components : "") });
                offset += components * 4;
            }
            slots.push({ gpu: this.vertex_data3(words), offset: 0, stride, step, attributes });
            // (the stats' vertex arrays assembled on the CPU: client arrays, formats WebGPU lacks)
            this.stats.cpu_arrays = (this.stats.cpu_arrays || 0) + list.length;
        }
        if(plan.constants.length)
        {
            const values = new ArrayBuffer(plan.constants.length * 16);
            const attributes = plan.constants.map(({ input, a }, i) =>
            {
                const current = [0, 1, 2, 3].map(k => a.current[k] === undefined ? (k === 3 ? 1 : 0) : a.current[k]);
                (input.kind === "f" ? new Float32Array(values, 16 * i, 4) : input.kind === "u" ? new Uint32Array(values, 16 * i, 4) :
                    new Int32Array(values, 16 * i, 4)).set(current);
                return { shaderLocation: input.location, offset: 16 * i, format: CPU_FORMAT[input.kind] + (input.components > 1 ? "x" + input.components : "") };
            });
            slots.push({ gpu: this.vertex_data3(new Uint32Array(values)), offset: 0, stride: 0, step: "instance", attributes });
        }
        if(slots.length > (this.device.limits ? this.device.limits.maxVertexBuffers : 8)) return this.note3("more vertex buffers than WebGPU binds");
        const key = slots.map(s => s.stride + s.step[0] + s.attributes.map(x => x.shaderLocation + "@" + x.offset + x.format).join(".")).join("/");
        return { slots, key };
    },

    /** A vertex buffer holding the words */
    vertex_data3(words)
    {
        const buffer = this.device.createBuffer({ label: "GLES vertices", size: Math.max(16, words.byteLength), usage: B.VERTEX | B.STORAGE,
            mappedAtCreation: true });
        new Uint32Array(buffer.getMappedRange(), 0, words.length).set(words);
        buffer.unmap();
        this.staging.push(buffer);
        return buffer;
    },

    /**
     * An enabled array's values, `components` each (missing ones 0, w 1) as
     * the input's kind: vertices from `first` (absolute; a client array's
     * element 0 is vertex 0), or instances by the divisor
     * @return {?(Float32Array|Int32Array|Uint32Array)}
     */
    values3(c, a, first, n, components, kind, divisor)
    {
        const packed = packed_attribute(a.type);
        const type_bytes = TYPE_BYTES[a.type] || 4;
        const element = packed ? 4 : a.size * type_bytes;
        let source, base, stride;
        if(a.data)
        {
            source = a.data;
            stride = element;
            base = 0;
        }
        else
        {
            const buffer = c.group.buffers.get(a.buffer);
            source = buffer && cpu_bytes(buffer);
            if(!source) return null;
            stride = a.stride || element;
            base = a.offset;
        }
        const out = kind === "f" ? new Float32Array(n * components) : kind === "i" ? new Int32Array(n * components) : new Uint32Array(n * components);
        const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
        const convert = kind === "f" ? v => v : v => Math.trunc(v);
        for(let k = 0; k < n; k++)
        {
            const at = base + (divisor ? Math.floor(k / divisor) : first + k) * stride;
            const fits = at + element <= source.length;
            const parts = fits && packed ? read_packed(view, at, a.type, a.normalized) : null;
            for(let i = 0; i < components; i++)
            {
                let value = i === 3 ? 1 : 0;
                if(fits && i < (packed ? 4 : a.size)) value = packed ? parts[i] : read_component(view, at + i * type_bytes, a.type, a.normalized && !a.integer);
                out[k * components + i] = convert(value);
            }
        }
        return out;
    },

    // ---- compute (GLES 3.1)

    /**
     * glDispatchCompute(Indirect): the compute program's shader through
     * vx_naga, its resources, a compute pass (between render passes: what it
     * writes is there for the draws after it)
     * @param {?Array<number>} groups the work groups, or null for `indirect`'s
     * @param {?{buffer: !Object, offset: number}} indirect the dispatch indirect buffer's parameters
     */
    dispatch3(c, groups, indirect)
    {
        const pipeline_object = !c.program && c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
        const program = c.group.objects.get(c.program || pipeline_object && pipeline_object.stages[0x20]);
        if(!program || !program.info || !program.info.ok || !program.info.spirv) return;
        if(!this.naga) return void this.note3("vx_naga not loaded");
        const index = program.info.spirv.findIndex(m => m.stage === "compute");
        if(index < 0) return;
        let t = this.translation3(program, index, 0, []);
        if(!t.error && t.intsamples && t.intsamples.length)
        {
            const wraps = this.int_wraps3(c, program, t.intsamples);
            if(wraps.length) t = this.translation3(program, index, 0, wraps);
        }
        if(t.error) return void this.note3("vx_naga: " + t.error.slice(0, 160));
        const module = this.module3(t.wgsl);
        // (the images' copies back to their textures, image_proxy3's: after the pass)
        const image_writes = this.image_writes3 = [];
        const group = this.bind_groups3(c, this.bindings3([[t, 4, program]]), { textures: new Set() });
        this.image_writes3 = null;
        if(!group) return;
        // (WebGPU refuses it, and with it the batch: gpu-deviations.md G-78)
        if(writable_aliases(group)) return void this.note3("a dispatch writing a buffer range or an image two bindings name");
        this.computes3 = this.computes3 || new Map();
        const key = this.id_of(module) + "|" + group.key;
        let pipeline = this.computes3.get(key);
        if(!pipeline)
        {
            try
            {
                pipeline = this.device.createComputePipeline({ label: "GLES 3 compute", layout: group.pipeline_layout,
                    compute: { module, entryPoint: t.entries[0].name } });
            }
            catch(error)
            {
                if(this.stats.errors.length < 20) this.stats.errors.push("compute pipeline: " + error.message);
                return;
            }
            this.computes3.set(key, pipeline);
        }
        // (the parameters' GPU buffer before the pass: its bytes may go up first)
        const parameters = indirect && this.gpu_buffer(indirect.buffer);
        this.end_pass();
        const pass = this.encoder.beginComputePass({ label: "GLES 3 dispatch" });
        pass.setPipeline(pipeline);
        for(const g of group.groups) pass.setBindGroup(g.index, this.device.createBindGroup({ layout: g.layout, entries: g.resources }));
        if(parameters) pass.dispatchWorkgroupsIndirect(parameters.buffer, indirect.offset);
        else pass.dispatchWorkgroups(groups[0], groups[1], groups[2]);
        pass.end();
        for(const write of image_writes) write();
        this.stats.dispatches = (this.stats.dispatches || 0) + 1;
    },

    /**
     * An indirect draw (GLES 3.1): its parameters with the command, or in the
     * draw indirect buffer: read there where the CPU side has them, else the
     * GPU's (a buffer a dispatch wrote)
     * @param {?Uint8Array} data the parameters, the Data forms'
     */
    draw_indirect3(c, mode, type, data, offset)
    {
        const elements = type !== 0;
        const words = 4 + (elements ? 1 : 0);
        let parameters = null;
        if(data && data.length >= 4 * words) parameters = new DataView(data.buffer, data.byteOffset, 4 * words);
        const buffer = !data ? c.group.buffers.get(c.buffers.draw_indirect) : null;
        if(buffer && !buffer.gpu_newer && cpu_bytes(buffer) && offset + 4 * words <= cpu_bytes(buffer).length)
        {
            const bytes = cpu_bytes(buffer);
            parameters = new DataView(bytes.buffer, bytes.byteOffset + offset, 4 * words);
        }
        if(!parameters)
        {
            if(!buffer) return;
            if(elements) this.draw3(c, mode, 0, 0, { type, offset: 0 }, 0, 0, { buffer, offset });
            else this.draw3(c, mode, 0, 0, null, 0, 0, { buffer, offset });
            return;
        }
        const count = parameters.getUint32(0, true), instances = parameters.getUint32(4, true);
        if(elements)
        {
            const first_index = parameters.getUint32(8, true), base_vertex = parameters.getInt32(12, true);
            this.draw3(c, mode, 0, count, { type, offset: first_index * INDEX_BYTES[type] }, instances, base_vertex);
        }
        else this.draw3(c, mode, parameters.getUint32(8, true), count, null, instances);
    },

    // ---- transform feedback

    /** vx_naga's capture translation of SPIR-V words (vx_translate_xfb) for a vertex layout's words */
    translate_xfb_spirv(words, desc)
    {
        const naga = this.naga;
        const bytes = new Uint8Array(words.buffer, words.byteOffset, words.byteLength);
        const input = naga.vx_alloc(bytes.length);
        new Uint8Array(naga.memory.buffer, input, bytes.length).set(bytes);
        const list = naga.vx_alloc(desc.length * 4);
        new Uint32Array(naga.memory.buffer, list, desc.length).set(desc);
        let out;
        try
        {
            out = naga.vx_translate_xfb(input, bytes.length, 1, 0, 0, 0, list, desc.length);
        }
        finally
        {
            naga.vx_free(input, bytes.length);
            naga.vx_free(list, desc.length * 4);
        }
        const length = new DataView(naga.memory.buffer).getUint32(out, true);
        const json = new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length));
        naga.vx_free(out, length + 4);
        return JSON.parse(json);
    },

    /**
     * The compute shader of a capturing draw (vx_naga's xfb.rs: the vertex
     * shader run a vertex an invocation, reading the vertex buffers as
     * storage) for the program and the draw's vertex buffers, or null
     */
    xfb3(program, vertex, all = false)
    {
        const gpu = this.program_gpu(program);
        gpu.xfb = gpu.xfb || new Map();
        const key = (all ? "all:" : "") + vertex.key;
        if(gpu.xfb.has(key)) return gpu.xfb.get(key);
        let entry = null;
        // (the group of its own resources, 1; bit 31: every output captured, a geometry shader's input)
        const desc = [all ? 0x80000001 : 1, 0];
        vertex.slots.forEach((s, slot) =>
        {
            for(const a of s.attributes)
            {
                desc.push(a.shaderLocation, slot, VK_FORMAT[a.format] || 0, a.offset);
                desc[1]++;
            }
        });
        desc.push(vertex.slots.length);
        vertex.slots.forEach((s, slot) => desc.push(slot, s.stride, s.step === "instance" ? 1 : 0));
        const v = program.info.spirv.find(m => m.stage === "vertex");
        if(vertex.slots.some(s => s.attributes.some(a => !VK_FORMAT[a.format]))) this.note3("a captured vertex array of a packed type");
        else
        {
            const t = this.translate_xfb_spirv(v.words, desc);
            if(t.error) this.note3("vx_naga's capture: " + t.error.slice(0, 160));
            else if(!t.xfb) this.note3("a capture of no varying");
            else
            {
                entry = { module: this.device.createShaderModule({ label: "GLES 3 capture", code: "diagnostic(off, derivative_uniformity);\n" + t.wgsl }),
                    bindings: new Set(t.entries[0].bindings.filter(b => b[0] === 0).map(b => b[1])), xfb: t.xfb, pipelines: new Map() };
            }
        }
        gpu.xfb.set(key, entry);
        return entry;
    },

    /**
     * A capture's compute pass (xfb3's entry): `vertex_count` vertices from
     * `first_vertex` of each of the instances into the scratch buffers
     * (one a transform feedback buffer the shader writes)
     */
    capture_pass3(entry, group, vertex, first_vertex, vertex_count, instances, scratch)
    {
        const { buffers, slots } = entry.xfb;
        const own = group.groups[0].entries.filter(e => entry.bindings.has(e.binding)).map(e => Object.assign({}, e, { visibility: 4 }));
        const capture = [{ binding: 960, visibility: 4, buffer: { type: "uniform" } },
            ...slots.map(s => ({ binding: 961 + s, visibility: 4, buffer: { type: "read-only-storage" } })),
            ...buffers.map(b => ({ binding: 970 + b, visibility: 4, buffer: { type: "storage" } }))];
        const key = JSON.stringify(own) + JSON.stringify(capture);
        let p = entry.pipelines.get(key);
        if(!p)
        {
            const layouts = [this.device.createBindGroupLayout({ entries: own }), this.device.createBindGroupLayout({ entries: capture })];
            p = { layouts, pipeline: this.device.createComputePipeline({ label: "GLES 3 capture",
                layout: this.device.createPipelineLayout({ bindGroupLayouts: layouts }), compute: { module: entry.module, entryPoint: "vx_xfb" } }) };
            entry.pipelines.set(key, p);
        }
        // (VxXfbParams: first vertex, vertices an instance, first instance, instances, first capture, the vertices captured,
        // pads, the buffers' offsets, each slot's offset)
        const total = vertex_count * instances;
        const params = new Uint32Array(20);
        params.set([first_vertex, vertex_count, 0, instances, 0, total]);
        vertex.slots.forEach((s, slot) => { params[12 + slot] = s.offset; });
        const resources = [{ binding: 960, resource: { buffer: this.uniform_buffer(params.buffer) } },
            ...slots.map(s => ({ binding: 961 + s, resource: { buffer: vertex.slots[s].gpu } })),
            ...buffers.map((b, i) => ({ binding: 970 + b, resource: { buffer: scratch[i] } }))];
        this.end_pass();
        const pass = this.encoder.beginComputePass({ label: "GLES 3 capture" });
        pass.setPipeline(p.pipeline);
        pass.setBindGroup(0, this.device.createBindGroup({ layout: p.layouts[0], entries: group.groups[0].resources.filter(r => entry.bindings.has(r.binding)) }));
        pass.setBindGroup(1, this.device.createBindGroup({ layout: p.layouts[1], entries: resources }));
        pass.dispatchWorkgroups(Math.ceil(total / 64));
        pass.end();
    },

    /**
     * A draw's vertices captured while transform feedback is active (not
     * paused): the vertex shader run as a compute shader into scratch
     * buffers, copied after what the bound buffers hold already (the
     * shadow counted the draw's vertices into the feedback's)
     */
    capture3(c, program, group, vertex, mode, first, count, instances, rebase)
    {
        const tf = c.tfs && c.tfs.get(c.tf);
        if(!tf || !tf.active || tf.paused) return;
        const per = mode === 0 ? 1 : mode === 1 ? 2 : 3;
        const each = Math.floor(count / per) * per, total = each * instances;
        if(!total) return;
        const entry = this.xfb3(program, vertex);
        if(!entry) return;
        const { buffers, strides } = entry.xfb;
        const scratch = buffers.map(b => this.device.createBuffer({ label: "GLES capture", size: Math.max(16, align4(total * strides[b])),
            usage: B.STORAGE | B.COPY_SRC }));
        this.staging.push(...scratch);
        this.capture_pass3(entry, group, vertex, rebase ? 0 : first, each, instances, scratch);
        buffers.forEach((b, i) =>
        {
            const binding = tf.bindings[b];
            const buffer = binding && c.group.buffers.get(binding.buffer);
            if(!buffer) return;
            const gpu = this.gpu_buffer(buffer);
            const at = binding.offset + (tf.vertices[b] - total) * strides[b];
            const bytes = Math.min(total * strides[b], gpu.size - at);
            if(at >= 0 && bytes > 0) this.encoder.copyBufferToBuffer(scratch[i], 0, gpu.buffer, at, bytes);
        });
        this.stats.captures = (this.stats.captures || 0) + 1;
    },

    /** BUFFER_READ: a buffer's bytes (a map of one the GPU wrote) read back for the CPU side */
    buffer_read3(record)
    {
        const conn = this.conns.get(record.conn);
        const c = conn && this.shadow.context(conn.context);
        const buffer = c && c.group.buffers.get(record.buffer);
        if(!buffer || record.offset + record.length > buffer.size) return this.answer_failed(record.request);
        const gpu = this.gpu_buffer(buffer);
        const low = record.offset & ~3, high = align4(record.offset + record.length);
        this.end_pass();
        const read = this.device.createBuffer({ label: "GLES buffer read", size: Math.max(4, high - low), usage: B.COPY_DST | B.MAP_READ });
        if(high > low) this.encoder.copyBufferToBuffer(gpu.buffer, low, read, 0, high - low);
        this.reads.push({ buffer: read, bytes: record.length, skip: record.offset - low, done: (bytes, sink) =>
        {
            const copy = cpu_bytes(buffer);
            for(const [offset, n] of copy ? buffer.packed || [] : [])
            {
                const from = Math.max(offset, record.offset), to = Math.min(offset + n, record.offset + record.length);
                if(to > from) bytes.set(copy.subarray(from, to), from - record.offset);
            }
            this.answer(sink, record.request, bytes);
        } });
        return undefined;
    },

    // ---- bind groups

    /** The texture unit a sampler's element samples: the texture bound to its type's target, the sampler state */
    texture_unit3(c, program, b, e)
    {
        const binding = program.info.bindings.find(x => x.binding === b && x.kind === "sampler");
        const values = binding && binding.location >= 0 ? program.values.get(binding.location + e) : null;
        const unit = Math.max(0, Math.min(c.textures.length - 1, values ? values[0] : 0));
        const slot = binding && SAMPLER_SLOT.has(binding.type) ? SAMPLER_SLOT.get(binding.type) : 0;
        const name = c.textures[unit][slot];
        const texture = name ? c.group.textures.get(name) : c.defaults ? c.defaults.get(SLOT_TARGET[slot]) : null;
        const sampler = c.samplers && c.samplers[unit] ? c.group.samplers.get(c.samplers[unit]) : null;
        return { texture: texture || null, state: sampler || texture || NO_SAMPLER };
    },

    /**
     * The program's samplers that clamp to the border (GLES 3.2), as
     * vx_naga's border.rs takes them in the wraps list: [image key, address
     * modes], and each border color component [BORDER_COLOR | k << 24 | key, its bits]
     */
    border_wraps3(c, program, group)
    {
        const entries = [];
        if(c.version < 32) return entries;
        const mode = w => w in VK_WRAP ? VK_WRAP[w] : 0;
        for(const binding of program.info.bindings)
        {
            if(binding.kind !== "sampler") continue;
            for(let e = 0; e < Math.max(1, binding.size); e++)
            {
                const { state } = this.texture_unit3(c, program, binding.binding, e);
                if(state.wrap_s !== 0x812D && state.wrap_t !== 0x812D && state.wrap_r !== 0x812D) continue;
                const key = group << 16 | (e ? ELEMENTS + 2 * (16 * binding.binding + e) : 2 * binding.binding);
                entries.push([key, mode(state.wrap_s) | mode(state.wrap_t) << 4 | mode(state.wrap_r || 0x2901) << 8]);
                const bits = new Uint32Array(new Float32Array(state.border_color || [0, 0, 0, 0]).buffer);
                bits.forEach((b, k) => entries.push([(BORDER_COLOR | k << 24 | key) >>> 0, b]));
            }
        }
        return entries;
    },

    /** The wraps of the samplers of a program's integer textures (vx_naga's int_wraps: [group << 16 | binding, modes]) */
    int_wraps3(c, program, fetched)
    {
        const wraps = [];
        for(const key of fetched)
        {
            const { b, e } = spirv_binding(key & 0xFFFF);
            const { state } = this.texture_unit3(c, program, b, e);
            const mode = w => w in VK_WRAP ? VK_WRAP[w] : 0;
            const modes = mode(state.wrap_s) | mode(state.wrap_t) << 4 | mode(state.wrap_r || 0x2901) << 8;
            if(modes !== 0x222) wraps.push([key, modes]);
        }
        return wraps.sort((x, y) => x[0] - y[0]);
    },

    /**
     * A draw's or a dispatch's bind groups: each binding's resource by its
     * kind and its program's state (the default uniform block, samplers'
     * textures and samplers, uniform blocks, storage blocks, atomic counter
     * buffers, image units), the layouts by the resources' types
     * @param {!Array<!Object>} bindings bindings3's
     * @return {?{groups: !Array<{index: number, layout: !GPUBindGroupLayout, entries: !Array<!Object>, resources: !Array<!Object>}>,
     *     pipeline_layout: !GPUPipelineLayout, key: string}}
     */
    bind_groups3(c, bindings, target)
    {
        const by_group = new Map();
        const samplings = new Map();
        const declarations = new Map(bindings.map(b => [b.group + ":" + b.binding, b.type]));
        for(const b of bindings)
        {
            if(!by_group.has(b.group)) by_group.set(b.group, { entries: [], resources: [] });
            const got = this.binding3(c, b, target, samplings, declarations);
            if(!got) return null;
            by_group.get(b.group).entries.push(Object.assign({ binding: b.binding, visibility: b.visibility }, got.entry));
            by_group.get(b.group).resources.push({ binding: b.binding, resource: got.resource });
        }
        // (the groups up to the last one used; one used by no stage has no entries)
        const count = by_group.size ? Math.max(...by_group.keys()) + 1 : 1;
        this.layouts3 = this.layouts3 || new Map();
        const layout_of = entries =>
        {
            const key = JSON.stringify(entries);
            let layout = this.layouts3.get(key);
            if(!layout) this.layouts3.set(key, layout = { group: this.device.createBindGroupLayout({ label: "GLES 3 resources", entries }),
                id: this.layouts3.size + 1 });
            return layout;
        };
        const groups = [];
        for(let index = 0; index < count; index++)
        {
            const g = by_group.get(index) || { entries: [], resources: [] };
            const layout = layout_of(g.entries);
            groups.push({ index, layout: layout.group, entries: g.entries, resources: g.resources, id: layout.id });
        }
        const key = groups.map(g => g.id).join(".");
        this.pipeline_layouts3 = this.pipeline_layouts3 || new Map();
        let pipeline_layout = this.pipeline_layouts3.get(key);
        if(!pipeline_layout) this.pipeline_layouts3.set(key, pipeline_layout = this.device.createPipelineLayout({ bindGroupLayouts: groups.map(g => g.layout) }));
        return { groups, pipeline_layout, key };
    },

    /** One binding's layout entry (without its binding and visibility) and resource, or null (noted) */
    binding3(c, b, target, samplings, declarations)
    {
        const { binding, kind, program } = b;
        const buffer_type = kind === "uniform" ? "uniform" : kind === "storage" ? "read-only-storage" : "storage";
        if(binding === 0) return { entry: { buffer: { type: buffer_type } }, resource: { buffer: this.default_block3(program, b.size) } };
        const { b: spirv, e } = spirv_binding(binding);
        if(spirv >= BINDING.SAMPLERS && spirv < BINDING.UNIFORM_BLOCKS)
        {
            const key = this.id_of(program) + ":" + b.group + ":" + spirv + ":" + e;
            let sampling = samplings.get(key);
            const destination = !sampling && program.info.bindings.some(x => x.binding === spirv && x.kind === "sampler" && x.blend_destination);
            if(destination)
            {
                // (an advanced blend's destination, texelFetch's: the draw's copy, or a texel of zeros)
                const tex = texture_type(declarations.get(b.group + ":" + (binding & ~1)));
                const view = this.blend_dst3 ? this.blend_dst3.view : this.fallback3(tex).view;
                sampling = { view, sample_type: "float", filtering: false, state: NO_SAMPLER, tex };
                samplings.set(key, sampling);
            }
            if(!sampling)
            {
                const unit = this.texture_unit3(c, program, spirv, e);
                const tex = texture_type(declarations.get(b.group + ":" + (binding & ~1)));
                sampling = Object.assign(this.texture_view3(unit.texture, unit.state, tex, target), { state: unit.state, tex });
                samplings.set(key, sampling);
            }
            if(kind.startsWith("texture"))
            {
                return { entry: { texture: { sampleType: sampling.sample_type, viewDimension: sampling.tex.dimension, multisampled: sampling.tex.multisampled } },
                    resource: sampling.view };
            }
            const comparison = kind === "sampler-comparison";
            return { entry: { sampler: { type: comparison ? "comparison" : sampling.filtering ? "filtering" : "non-filtering" } },
                resource: this.sampler3(sampling.state, sampling.filtering, comparison) };
        }
        if(spirv >= BINDING.UNIFORM_BLOCKS && spirv < BINDING.STORAGE_BLOCKS && kind !== "storage-rw")
        {
            return { entry: { buffer: { type: buffer_type } }, resource: this.block3(c, program, spirv - BINDING.UNIFORM_BLOCKS + e, b.size) };
        }
        if(spirv >= BINDING.STORAGE_BLOCKS && spirv < BINDING.ATOMIC_COUNTERS)
        {
            const block = (program.info.storage_blocks || [])[spirv - BINDING.STORAGE_BLOCKS + e];
            return { entry: { buffer: { type: buffer_type } }, resource: this.storage3(c, c.storage_bindings, block ? block.binding : 0, b.size, buffer_type === "storage") };
        }
        if(spirv >= BINDING.ATOMIC_COUNTERS && spirv < BINDING.IMAGES)
        {
            return { entry: { buffer: { type: "storage" } }, resource: this.storage3(c, c.atomic_bindings, spirv - BINDING.ATOMIC_COUNTERS, b.size, true) };
        }
        if(spirv >= BINDING.IMAGES && kind === "storage-texture")
        {
            const image = program.info.bindings.find(x => x.binding === spirv && x.kind === "image");
            return this.image3(c, (image && image.unit || 0) + e, declarations.get(b.group + ":" + binding));
        }
        return this.note3("a binding of " + kind);
    },

    /**
     * A storage block's or an atomic counter buffer's range: what its binding
     * point holds (for nothing: zeros to read, or a buffer nothing reads to
     * write); a range shorter than the binding's least size (its WGSL
     * type's: an unsized array of no elements, the padding after the last)
     * is that size, of the buffer's memory after it (G-81)
     * @param {!Array<{buffer: number, offset: number, size: number}>} points the context's binding points of the kind
     */
    storage3(c, points, point, size, writable)
    {
        const zeros = () => ({ buffer: writable ? this.discard3(size) : this.zeros3(size), offset: 0, size: Math.max(16, align4(size)) });
        const b = points ? points[point] : null;
        const buffer = b && b.buffer ? c.group.buffers.get(b.buffer) : null;
        if(!buffer || !buffer.size || b.offset % 256 || b.offset >= buffer.size) return zeros();
        let length = b.size ? Math.min(b.size, buffer.size - b.offset) : buffer.size - b.offset;
        length = align4(Math.max(length, size));
        const gpu = this.gpu_buffer(buffer, b.offset + length);
        return { buffer: gpu.buffer, offset: b.offset, size: length };
    },

    /**
     * An image unit's texture as a storage texture of the WGSL type's
     * format, access and dimension: the unit's level, its layer unless it is
     * bound layered; a texture of another format binds a texture of nothing
     */
    image3(c, unit, type)
    {
        const m = /^texture_storage_(2d_array|2d|3d)<(\w+),\s*(\w+)>/.exec(type || "");
        if(!m) return this.note3("an image of a WGSL type " + type);
        const dimension = m[1].replace("_", "-"), format = m[2];
        const access = { read: "read-only", write: "write-only", read_write: "read-write" }[m[3]];
        const entry = { storageTexture: { access, format, viewDimension: dimension } };
        const u = c.image_units && c.image_units[unit];
        const texture = u && u.texture ? c.group.textures.get(u.texture) : null;
        const gpu = texture && this.gpu_texture3(texture);
        // (a texture of another format, or a 3D texture's layer as a 2D image: a copy, image_proxy3's)
        const proxy = gpu && (gpu.format !== format || !gpu.storage || gpu.three && dimension === "2d") ?
            this.image_proxy3(gpu, u, format, dimension, access) : null;
        if(proxy) return { entry, resource: proxy };
        if(!gpu || gpu.format !== format || !gpu.storage || gpu.three && dimension === "2d")
        {
            if(gpu) this.note3("an image unit's texture of a format or size the image cannot take");
            // (one to read for all, one of its own each to write: WebGPU refuses a texture bound to write with another binding)
            this.empty_images3 = this.empty_images3 || new Map();
            const key = format + ":" + dimension;
            let view = access === "read-only" ? this.empty_images3.get(key) : null;
            if(!view)
            {
                const empty = this.device.createTexture({ label: "GLES empty image", size: [1, 1, 1], dimension: dimension === "3d" ? "3d" : "2d", format,
                    usage: U.STORAGE_BINDING });
                view = empty.createView({ dimension });
                if(access === "read-only") this.empty_images3.set(key, view);
                else this.staging.push(empty);
            }
            return { entry, resource: view };
        }
        const mip = Math.max(0, u.level - gpu.first);
        const key = "image:" + dimension + ":" + mip + ":" + (u.layered ? "all" : u.layer);
        let view = gpu.views.get(key);
        if(!view)
        {
            view = gpu.texture.createView({ dimension, baseMipLevel: mip, mipLevelCount: 1,
                ...(dimension === "2d" ? { baseArrayLayer: gpu.three ? 0 : u.layer, arrayLayerCount: 1 } : {}) });
            gpu.views.set(key, view);
        }
        return { entry, resource: view };
    },

    /**
     * An image unit's level (its layer, or all of them for a layered unit)
     * where the texture cannot be the image itself: another format of the
     * same texel size (GL reinterprets the bits, WebGPU views no other
     * format), a 3D texture's layer as a 2D image (WebGPU views no 2D
     * slice), a format WebGPU stores no texels of. A texture of the image's
     * format and size gets the texels (through a buffer: the bits as they
     * are) before the pass, and gives them back after it unless the image
     * is read-only (image_writes3, dispatch3's)
     * @return {?GPUTextureView} null where the sizes differ
     */
    image_proxy3(gpu, u, format, dimension, access)
    {
        const texel = TEXEL_BYTES[format];
        const mip = u.level - gpu.first;
        if(!texel || TEXEL_BYTES[gpu.format] !== texel || gpu.samples > 1 || gpu.block > 1 || mip < 0 || mip >= gpu.levels) return null;
        const width = Math.max(1, gpu.width >> mip), height = Math.max(1, gpu.height >> mip);
        const layers = gpu.three ? Math.max(1, gpu.depth >> mip) : gpu.depth;
        const first = dimension === "2d" ? u.layer : 0, count = dimension === "2d" ? 1 : layers;
        if(first + count > layers) return null;
        gpu.proxies = gpu.proxies || new Map();
        const key = format + ":" + dimension + ":" + mip + ":" + first;
        let proxy = gpu.proxies.get(key);
        if(!proxy)
        {
            const created = this.device.createTexture({ label: "GLES image proxy", size: [width, height, count], dimension: dimension === "3d" ? "3d" : "2d",
                format, usage: U.STORAGE_BINDING | U.COPY_SRC | U.COPY_DST });
            proxy = { texture: created, view: created.createView({ dimension }) };
            gpu.proxies.set(key, proxy);
        }
        const bytes_per_row = Math.ceil(width * texel / 256) * 256;
        const buffer = this.device.createBuffer({ label: "GLES image proxy copy", size: bytes_per_row * height * count, usage: B.COPY_SRC | B.COPY_DST });
        this.staging.push(buffer);
        const layout = { buffer, bytesPerRow: bytes_per_row, rowsPerImage: height };
        const size = [width, height, count];
        const own = { texture: gpu.texture, mipLevel: mip, origin: [0, 0, first] };
        this.end_pass();
        this.encoder.copyTextureToBuffer(own, layout, size);
        this.encoder.copyBufferToTexture(layout, { texture: proxy.texture }, size);
        if(access !== "read-only" && this.image_writes3)
        {
            this.image_writes3.push(() =>
            {
                this.encoder.copyTextureToBuffer({ texture: proxy.texture }, layout, size);
                this.encoder.copyBufferToTexture(layout, own, size);
            });
        }
        return proxy.view;
    },

    /** The default uniform block's buffer: the program's values by their offsets (made again when they change) */
    default_block3(program, size)
    {
        const gpu = this.program_gpu(program);
        const version = program.values_version || 0;
        if(gpu.uniforms && gpu.uniforms.version === version && gpu.uniforms.size >= size) return gpu.uniforms.buffer;
        const info = program.info;
        const bytes = new ArrayBuffer(Math.ceil(Math.max(16, size, info.default_block_size || 0) / 16) * 16);
        const view = new DataView(bytes);
        for(const u of info.uniforms)
        {
            if(u.block_index >= 0 || u.opaque || u.location < 0 || u.offset < 0) continue;
            for(let e = 0; e < u.size; e++)
            {
                const values = program.values.get(u.location + e);
                if(!values) continue;
                const base = u.offset + e * (u.array_stride || 0);
                if(u.columns)
                {
                    for(let col = 0; col < u.columns; col++)
                    {
                        for(let row = 0; row < u.rows; row++)
                        {
                            const at = base + (u.row_major ? row * u.matrix_stride + col * 4 : col * u.matrix_stride + row * 4);
                            if(at + 4 <= bytes.byteLength) view.setFloat32(at, values[col * u.rows + row] || 0, true);
                        }
                    }
                    continue;
                }
                for(let i = 0; i < u.components && base + 4 * i + 4 <= bytes.byteLength; i++)
                {
                    const v = values[i] || 0;
                    if(!u.int) view.setFloat32(base + 4 * i, v, true);
                    else if(u.uint || u.bool) view.setUint32(base + 4 * i, v >>> 0, true);
                    else view.setInt32(base + 4 * i, v | 0, true);
                }
            }
        }
        const buffer = this.device.createBuffer({ label: "GLES default uniforms", size: bytes.byteLength, usage: B.UNIFORM | B.STORAGE, mappedAtCreation: true });
        new Uint8Array(buffer.getMappedRange()).set(new Uint8Array(bytes));
        buffer.unmap();
        if(gpu.uniforms) this.staging.push(gpu.uniforms.buffer);
        gpu.uniforms = { version, size: bytes.byteLength, buffer };
        return buffer;
    },

    /** A uniform block's buffer range: what its binding point holds (zeros for nothing; at least the block's WGSL size) */
    block3(c, program, index, size)
    {
        const block = program.info.blocks[index];
        const point = program.block_bindings ? program.block_bindings[index] : block ? block.binding : 0;
        const b = c.uniform_bindings[point];
        const buffer = b && b.buffer ? c.group.buffers.get(b.buffer) : null;
        const zeros = () => ({ buffer: this.zeros3(size), offset: 0, size: Math.max(16, align4(size)) });
        const offset = b ? b.offset : 0;
        if(!buffer || !buffer.size || offset % 256 || offset >= buffer.size) return zeros();
        // (a range shorter than the block's WGSL size: that size, of the buffer's memory after it, as storage3's)
        let length = b.size ? Math.min(b.size, buffer.size - offset) : buffer.size - offset;
        length = align4(Math.max(length, size));
        const gpu = this.gpu_buffer(buffer, offset + length);
        return { buffer: gpu.buffer, offset, size: length };
    },

    /**
     * A texture's view as a sampler of the WGSL type samples it, by GLES
     * 3.0's completeness (3.8.13: levels base to max, cube faces, filters of
     * formats that filter no texels), or the fallback's
     * @return {{view: !GPUTextureView, sample_type: string, filtering: boolean}}
     */
    texture_view3(texture, state, tex, target)
    {
        const fallback = () => this.fallback3(tex);
        if(!texture) return fallback();
        const level0 = texture.images.get(0);
        if(level0 && (level0.image || level0.color_buffer))
        {
            const t = level0.image ? this.image_texture(level0.image) : this.color_buffer_texture(level0.color_buffer);
            if(!t || tex.sample !== "float" || tex.dimension !== "2d" || target.textures.has(t.texture)) return fallback();
            return { view: t.texture.createView(), sample_type: "float", filtering: true };
        }
        const gpu = this.gpu_texture3(texture);
        if(!gpu || target.textures.has(gpu.texture)) return fallback();
        if(tex.multisampled !== (gpu.samples > 1)) return fallback();
        if(tex.multisampled)
        {
            // (GLES 3.1's multisampled textures: texelFetch of a sample, no sampler state)
            const kind = format_kind(gpu.format);
            const sample_type = kind === "depth" ? (tex.sample === "depth" ? "depth" : "unfilterable-float") : kind === "i" ? "sint" : kind === "u" ? "uint" :
                "unfilterable-float";
            if((tex.sample === "sint") !== (kind === "i") || (tex.sample === "uint") !== (kind === "u")) return fallback();
            let view = gpu.views.get("ms");
            if(!view) gpu.views.set("ms", view = gpu.texture.createView({ dimension: "2d", aspect: gpu.format.includes("stencil") ? "depth-only" : "all" }));
            return { view, sample_type, filtering: false };
        }
        const three = gpu.three, cube = gpu.cube;
        let base = texture.base_level || 0;
        if(texture.immutable) base = Math.min(base, texture.immutable_levels - 1);
        const first = texture.images.get(base);
        if(!first || !first.width || !first.height) return fallback();
        const internal = image_internal(first);
        const info = format_info(internal);
        const kind = info ? info.kind : "unorm";
        // (GLES 3.1's DEPTH_STENCIL_TEXTURE_MODE STENCIL_INDEX: a depth and stencil texture's stencil, unsigned integers)
        const stencil = kind === "depth_stencil" && texture.depth_stencil_mode === STENCIL_INDEX;
        const depth = !stencil && (kind === "depth" || kind === "depth_stencil");
        const mipmapped = state.min_filter !== NEAREST && state.min_filter !== LINEAR;
        const max_level = texture.max_level === undefined ? 1000 : texture.max_level;
        const chain = base + Math.floor(Math.log2(Math.max(first.width, first.height, three ? first.depth || 1 : 1)));
        const top = !mipmapped ? base : Math.min(max_level, texture.immutable ? texture.immutable_levels - 1 : chain);
        if(top < base) return fallback();
        if(cube && first.width !== first.height) return fallback();
        for(let level = base; level <= top; level++)
        {
            const w = Math.max(1, first.width >> level - base), h = Math.max(1, first.height >> level - base);
            const d = three ? Math.max(1, (first.depth || 1) >> level - base) : first.depth || 1;
            for(let face = 0; face < (cube ? 6 : 1); face++)
            {
                const image = texture.images.get(face * 32 + level);
                if(!image || image.width !== w || image.height !== h || (image.depth || 1) !== d || image_internal(image) !== internal) return fallback();
            }
        }
        const compare = depth && state.compare_mode === COMPARE_REF_TO_TEXTURE;
        const filterable = !stencil && (!info || info.filterable || compare);
        const linear = state.mag_filter !== NEAREST || state.min_filter !== NEAREST && state.min_filter !== NEAREST_MIPMAP_NEAREST;
        if(!filterable && linear) return fallback();
        let sample_type;
        if(tex.sample === "depth") sample_type = depth ? "depth" : null;
        else if(tex.sample === "sint") sample_type = kind === "int" ? "sint" : null;
        else if(tex.sample === "uint") sample_type = kind === "uint" || stencil ? "uint" : null;
        else sample_type = kind === "int" || kind === "uint" ? null : depth || !filterable || info && !info.filterable ? "unfilterable-float" : "float";
        if(!sample_type) return fallback();
        const mip = base - gpu.first, count = top - base + 1;
        if(mip < 0 || mip + count > gpu.levels) return fallback();
        const aspect = stencil ? "stencil-only" : gpu.format.includes("stencil") && gpu.format !== "stencil8" ? "depth-only" : "all";
        const dimension = tex.dimension;
        if((dimension === "3d") !== three || dimension === "cube" && !cube || dimension === "cube-array" && !(gpu.array && gpu.depth % 6 === 0)) return fallback();
        // (TEXTURE_SWIZZLE_*: the view's, with WebGPU's texture-component-swizzle)
        let swizzle = (texture.swizzle || [0x1903, 0x1904, 0x1905, 0x1906]).map(v => ({ 0x1903: "r", 0x1904: "g", 0x1905: "b", 0x1906: "a", 0: "0", 1: "1" })[v]).join("");
        if(swizzle !== "rgba" && !this.device.features.has("texture-component-swizzle"))
        {
            this.note3("TEXTURE_SWIZZLE without WebGPU's texture-component-swizzle");
            swizzle = "rgba";
        }
        const key = dimension + ":" + mip + ":" + count + ":" + aspect + ":" + swizzle;
        let view = gpu.views.get(key);
        if(!view)
        {
            view = gpu.texture.createView({ dimension, baseMipLevel: mip, mipLevelCount: count, aspect,
                ...(dimension === "2d" ? { arrayLayerCount: 1 } : {}), ...(swizzle !== "rgba" ? { swizzle } : {}) });
            gpu.views.set(key, view);
        }
        return { view, sample_type, filtering: sample_type === "float" };
    },

    /** What an incomplete texture samples as, of the WGSL type's dimension and kind: (0, 0, 0, 1) */
    fallback3(tex)
    {
        const key = tex.dimension + ":" + tex.sample + (tex.multisampled ? ":ms" : "");
        this.fallbacks3 = this.fallbacks3 || new Map();
        let fallback = this.fallbacks3.get(key);
        if(fallback) return fallback;
        if(tex.multisampled)
        {
            // (4 samples, cleared by a pass of its own: no copy reaches a multisampled texture)
            const depth = tex.sample === "depth";
            const format = depth ? "depth16unorm" : tex.sample === "sint" ? "rgba8sint" : tex.sample === "uint" ? "rgba8uint" : COLOR_FORMAT;
            const texture = this.device.createTexture({ label: "GLES incomplete texture", size: [1, 1], format, sampleCount: 4,
                usage: U.TEXTURE_BINDING | U.RENDER_ATTACHMENT });
            const view = texture.createView();
            const encoder = this.device.createCommandEncoder();
            encoder.beginRenderPass(depth ? { colorAttachments: [], depthStencilAttachment: { view, depthLoadOp: "clear", depthClearValue: 0, depthStoreOp: "store" } } :
                { colorAttachments: [{ view, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" }] }).end();
            this.device.queue.submit([encoder.finish()]);
            fallback = { view, sample_type: tex.sample === "float" ? "unfilterable-float" : tex.sample, filtering: false };
            this.fallbacks3.set(key, fallback);
            return fallback;
        }
        const format = tex.sample === "depth" ? "depth16unorm" : tex.sample === "sint" ? "rgba8sint" : tex.sample === "uint" ? "rgba8uint" : COLOR_FORMAT;
        const layers = tex.dimension === "cube" ? 6 : 1;
        const texture = this.device.createTexture({ label: "GLES incomplete texture", size: [1, 1, layers], dimension: tex.dimension === "3d" ? "3d" : "2d",
            format, usage: U.TEXTURE_BINDING | U.COPY_DST });
        const texel = format === "depth16unorm" ? [0, 0] : format === COLOR_FORMAT ? [0, 0, 0, 255] : [0, 0, 0, 1];
        const data = new Uint8Array(texel.length * layers);
        for(let i = 0; i < layers; i++) data.set(texel, i * texel.length);
        this.device.queue.writeTexture({ texture }, data, { bytesPerRow: texel.length, rowsPerImage: 1 }, [1, 1, layers]);
        fallback = { view: texture.createView({ dimension: tex.dimension }), sample_type: tex.sample === "float" ? "float" : tex.sample,
            filtering: tex.sample === "float" };
        this.fallbacks3.set(key, fallback);
        return fallback;
    },

    /** A sampler of a sampler object's (or texture's) state; nearest only for a texture that filters no texels */
    sampler3(state, filtering, comparison)
    {
        const min = state.min_filter, mag = state.mag_filter;
        const lod_min = Math.min(32, Math.max(0, state.min_lod === undefined ? -1000 : state.min_lod));
        const lod_max = Math.min(32, Math.max(lod_min, state.max_lod === undefined ? 1000 : state.max_lod));
        const compare = comparison ? COMPARE[state.compare_func || 0x0203] : undefined;
        const key = [min, mag, state.wrap_s, state.wrap_t, state.wrap_r, lod_min, lod_max, filtering, compare].join("|");
        let sampler = this.samplers.get(key);
        if(!sampler)
        {
            const linear = f => filtering && (f === LINEAR || f === 0x2701 || f === 0x2703);
            sampler = this.device.createSampler(Object.assign({
                addressModeU: WRAPS[state.wrap_s] || "repeat", addressModeV: WRAPS[state.wrap_t] || "repeat", addressModeW: WRAPS[state.wrap_r] || "repeat",
                magFilter: filtering && mag === LINEAR ? "linear" : "nearest", minFilter: linear(min) ? "linear" : "nearest",
                mipmapFilter: filtering && (min === 0x2702 || min === 0x2703) ? "linear" : "nearest", lodMinClamp: lod_min, lodMaxClamp: lod_max,
            }, compare ? { compare } : {}));
            this.samplers.set(key, sampler);
        }
        return sampler;
    },

    /** The pipeline for the program, the vertex buffers, the resources, the state and the target */
    pipeline3(c, shaders, vertex, group, topology, strip_format, target, face)
    {
        // (an advanced equation: the fragment shader blends, glsl_es_rewrite.js's; its index the constant)
        const advanced = shaders.fragment.blend_constant ? advanced_blend(c) : -1;
        const blend = c.enabled.has(BLEND) && advanced < 0;
        const depth_test = c.enabled.has(DEPTH_TEST) && !(target.depth && target.depth.gl_depth === false);
        const stencil_test = c.enabled.has(STENCIL_TEST) && !(target.depth && target.depth.gl_stencil === false);
        const cull = face === 0 ? "back" : face === 1 ? "front" : c.enabled.has(CULL_FACE) ? (c.cull_face === 0x0404 ? "front" : "back") : "none";
        const masks = face === undefined ? 0 : face;
        const depth_format = target.depth ? target.depth.format : "";
        const key = ["3", shaders.id, vertex.key, group.key, topology, strip_format || "", c.front_face, cull, masks,
            target.colors.map(a => a ? a.format + (a.unwritten ? "!" : "") + (a.no_alpha ? "~" : "") : "-").join(","), target.alpha ? "a" : "x", depth_format, target.samples,
            c.enabled.has(0x8E51) ? c.sample_mask : "-", c.enabled.has(0x809E) ? "c" : "-",
            blend ? c.blend_func.join(",") + "/" + c.blend_equation.join(",") : advanced >= 0 ? "advanced" + advanced : "-", c.color_mask.join(""),
            depth_test ? c.depth_func + ":" + c.depth_mask : "-",
            stencil_test ? JSON.stringify([c.stencil_func, c.stencil_op, c.stencil_writemask]) : "-",
            c.enabled.has(POLYGON_OFFSET_FILL) ? c.polygon_offset.join(",") : "-"].join("|");
        let pipeline = this.pipelines.get(key);
        if(pipeline) return pipeline;
        const write_mask = (c.color_mask[0] ? 1 : 0) | (c.color_mask[1] ? 2 : 0) | (c.color_mask[2] ? 4 : 0) | (c.color_mask[3] && target.alpha ? 8 : 0);
        const targets = target.colors.map((a, i) =>
        {
            if(!a) return null;
            // (an output the shader lacks or of another kind: nothing written, GL leaves it undefined)
            const output = shaders.outputs.get(i);
            const kind = format_kind(a.format);
            const fits = !a.unwritten && output && (kind === "f" ? !/[iu]32/.test(output) : output.includes(kind === "i" ? "i32" : "u32"));
            return { format: a.format, writeMask: fits ? write_mask & (a.no_alpha ? 7 : 15) : 0, blend: blend && fits && blendable(a.format) ? {
                color: blend_component(c.blend_equation[0], c.blend_func[0], c.blend_func[1]),
                alpha: blend_component(c.blend_equation[1], c.blend_func[2], c.blend_func[3]),
            } : undefined };
        });
        const descriptor = {
            label: "GLES 3 pipeline", layout: group.pipeline_layout,
            vertex: { module: shaders.vertex.module, entryPoint: shaders.vertex.entry,
                buffers: vertex.slots.map(s => ({ arrayStride: s.stride, stepMode: s.step, attributes: s.attributes })) },
            fragment: { module: shaders.fragment.module, entryPoint: shaders.fragment.entry, targets,
                constants: Object.assign({}, shaders.fragment.samples_constant ? { [SAMPLES_CONSTANT]: target.samples } : {},
                    shaders.fragment.blend_constant ? { [BLEND_CONSTANT]: Math.max(0, advanced) } : {}) },
            // (the Y flip reverses the winding: GL's CCW is WebGPU's CW)
            primitive: { topology, frontFace: c.front_face === 0x0901 ? "cw" : "ccw", cullMode: cull, ...(strip_format ? { stripIndexFormat: strip_format } : {}) },
            // (the sample mask, GLES 3.1's; alpha to coverage, of multisampled targets)
            multisample: { count: target.samples, mask: c.enabled.has(0x8E51) ? c.sample_mask >>> 0 : 0xFFFFFFFF,
                alphaToCoverageEnabled: c.enabled.has(0x809E) && target.samples > 1 && shaders.outputs.has(0) },
        };
        if(target.depth)
        {
            const stencil = depth_format.includes("stencil");
            const face_state = i => ({ compare: COMPARE[c.stencil_func[i][0]], failOp: STENCIL_OPS[c.stencil_op[i][0]],
                depthFailOp: STENCIL_OPS[c.stencil_op[i][1]], passOp: STENCIL_OPS[c.stencil_op[i][2]] });
            descriptor.depthStencil = Object.assign({ format: depth_format },
                depth_format !== "stencil8" ? { depthWriteEnabled: depth_test && !!c.depth_mask, depthCompare: depth_test ? COMPARE[c.depth_func] : "always" } : {},
                stencil && stencil_test ? { stencilFront: face_state(0), stencilBack: face_state(1), stencilReadMask: c.stencil_func[masks][2] & 0xFF,
                    stencilWriteMask: c.stencil_writemask[masks] & 0xFF } : {},
                c.enabled.has(POLYGON_OFFSET_FILL) && depth_format !== "stencil8" ? { depthBias: Math.round(c.polygon_offset[1]),
                    depthBiasSlopeScale: c.polygon_offset[0] } : {});
        }
        try
        {
            pipeline = this.device.createRenderPipeline(descriptor);
        }
        catch(error)
        {
            if(this.stats.errors.length < 20) this.stats.errors.push("pipeline: " + error.message);
            return null;
        }
        this.stats.pipelines++;
        this.pipelines.set(key, pipeline);
        return pipeline;
    },

    // ---- commands

    /**
     * A command of a GLES 3.x context after the shadow took it: what the GPU
     * does of it
     * @return {boolean} whether it was this one's (else GLES 2.0's handles it)
     */
    command3(c, name, args)
    {
        switch(name)
        {
            case "glTexImage2D": case "glTexImage2DOffsetAEMU": case "glTexImage3D": case "glTexImage3DOffsetAEMU":
            case "glTexSubImage2D": case "glTexSubImage2DOffsetAEMU": case "glTexSubImage3D": case "glTexSubImage3DOffsetAEMU":
                this.tex_image3(c, name, args);
                return true;
            case "glTexStorage2D": case "glTexStorage3D":
            {
                const { texture } = this.bound3(c, args[0]);
                if(texture) this.gpu_texture3(texture);
                return true;
            }
            case "glCompressedTexImage2D": case "glCompressedTexImage2DOffsetAEMU": case "glCompressedTexImage3D": case "glCompressedTexImage3DOffsetAEMU":
            case "glCompressedTexSubImage2D": case "glCompressedTexSubImage2DOffsetAEMU": case "glCompressedTexSubImage3D":
            case "glCompressedTexSubImage3DOffsetAEMU":
                this.compressed_image3(c, name, args);
                return true;
            case "glCopyTexImage2D": case "glCopyTexSubImage2D": case "glCopyTexSubImage3D":
                this.copy_tex_image3(c, name, args);
                return true;
            case "glGenerateMipmap": this.generate_mipmap3(c, args[0]); return true;
            case "glBufferData":
            {
                // (GLES 2.0's shadow keeps no bytes: the executor's own, `data`)
                if(c.api === 2) this.buffer_data(c, args, false);
                const buffer = this.buffer_of3(c, args[0]);
                if(buffer) buffer.dirty = [0, buffer.size];
                return true;
            }
            case "glBufferSubData":
                if(c.api === 2) this.buffer_data(c, args, true);
                this.buffer_written(this.buffer_of3(c, args[0]), args[1], args[2], args[3]);
                return true;
            case "glUnmapBufferAEMU":
            {
                const [target, offset, length, access, data] = args;
                if(access & GL3.MAP_WRITE_BIT && !(access & GL3.MAP_FLUSH_EXPLICIT_BIT)) this.buffer_written(this.buffer_of3(c, target), offset, length, data);
                return true;
            }
            case "glFlushMappedBufferRangeAEMU":
                // (the buffer's offset: gfxstream's decoder's)
                this.buffer_written(this.buffer_of3(c, args[0]), args[1], args[2], args[4]);
                return true;
            case "glCopyBufferSubData":
            {
                const [read_target, write_target, read_offset, write_offset, size] = args;
                const from = this.buffer_of3(c, read_target), to = this.buffer_of3(c, write_target);
                if(!from || !to || size <= 0) return true;
                if(!from.gpu_newer)
                {
                    const bytes = cpu_bytes(to);
                    this.buffer_written(to, write_offset, size, bytes && bytes.subarray(write_offset, write_offset + size));
                    return true;
                }
                if(read_offset % 4 || write_offset % 4 || size % 4)
                {
                    this.note3("an unaligned copy of a buffer the GPU wrote");
                    return true;
                }
                const a = this.gpu_buffer(from), b = this.gpu_buffer(to);
                this.end_pass();
                this.encoder.copyBufferToBuffer(a.buffer, read_offset, b.buffer, write_offset, size);
                return true;
            }
            case "glRenderbufferStorage": case "glRenderbufferStorageMultisample": this.renderbuffer_storage3(c); return true;
            case "glEGLImageTargetRenderbufferStorage":
            {
                const rb = c.group.renderbuffers.get(c.renderbuffer);
                if(rb && rb.gpu) this.staging.push(rb.gpu);
                if(rb) rb.gpu = null;
                return true;
            }
            case "glVertexAttribPointerData": c.attribs[args[0]].data = args[5]; return true;
            case "glVertexAttribIPointerDataAEMU": c.attribs[args[0]].data = args[4]; return true;
            case "glVertexAttribPointerOffset": case "glVertexAttribIPointerOffsetAEMU": c.attribs[args[0]].data = null; return true;
            case "glClear": this.clear3(c, args[0]); return true;
            case "glBlitFramebuffer": this.blit_framebuffer3(c, args); return true;
            case "glReadPixelsOffsetAEMU": this.read_pixels_pack3(c, args); return true;
            case "glClearBufferiv": case "glClearBufferuiv": case "glClearBufferfv": case "glClearBufferfi": this.clear_buffer3(c, name, args); return true;
            case "glDrawArrays": this.draw3(c, args[0], args[1], args[2], null, 1); return true;
            case "glDrawArraysInstanced": this.draw3(c, args[0], args[1], args[2], null, args[3]); return true;
            case "glDrawElementsData": this.draw3(c, args[0], 0, args[1], { type: args[2], bytes: args[3] }, 1); return true;
            case "glDrawElementsOffset": this.draw3(c, args[0], 0, args[1], { type: args[2], offset: args[3] }, 1); return true;
            case "glDrawElementsInstancedDataAEMU": this.draw3(c, args[0], 0, args[1], { type: args[2], bytes: args[3] }, args[4]); return true;
            case "glDrawElementsInstancedOffsetAEMU": this.draw3(c, args[0], 0, args[1], { type: args[2], offset: args[3] }, args[4]); return true;
            case "glDrawRangeElementsDataAEMU": this.draw3(c, args[0], 0, args[3], { type: args[4], bytes: args[5] }, 1); return true;
            case "glDrawRangeElementsOffsetAEMU": this.draw3(c, args[0], 0, args[3], { type: args[4], offset: args[5] }, 1); return true;
            // (GLES 3.1)
            case "glDispatchCompute": this.dispatch3(c, args, null); return true;
            case "glDispatchComputeIndirect": this.dispatch3(c, null, { buffer: c.group.buffers.get(c.buffers.dispatch_indirect), offset: args[0] }); return true;
            case "glMemoryBarrier": case "glMemoryBarrierByRegion": this.end_pass(); return true;
            case "glDrawArraysIndirectDataAEMU": this.draw_indirect3(c, args[0], 0, args[1], 0); return true;
            case "glDrawArraysIndirectOffsetAEMU": this.draw_indirect3(c, args[0], 0, null, args[1]); return true;
            case "glDrawElementsIndirectDataAEMU": this.draw_indirect3(c, args[0], args[1], args[2], 0); return true;
            case "glDrawElementsIndirectOffsetAEMU": this.draw_indirect3(c, args[0], args[1], null, args[2]); return true;
        }
        if(/^gl(Program)?Uniform(?!BlockBinding)/.test(name))
        {
            // (glProgramUniform*'s program; glUniform*'s: the current one, else the bound pipeline's active one)
            const pipeline = !c.program && c.program_pipelines && c.program_pipelines.get(c.program_pipeline);
            const program = c.group.objects.get(name.startsWith("glProgram") ? args[0] : c.program || pipeline && pipeline.active);
            if(program) program.values_version = (program.values_version || 0) + 1;
            return true;
        }
        return false;
    },
};
                                                                                                                                                                                                                                                                                                                                             source/v64/src/gles/page/gles3_pixels.js                                                            0000644 0000000 0000000 00000044266 00000000000 015274  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.0's pixels on the page (docs/gles3-plan.md L3): an image of client
// memory unpacked by the pixel store's state (GLES 3.0, 3.7.1) and turned
// into the texels of its texture's WebGPU format (gles_formats3.js's
// `webgpu`): the same bytes where the layouts agree, a fourth channel where
// WebGPU has no three-channel format, floats as halves, the packed types
// expanded or packed, the legacy formats as RGBA8 (gles_textures.js).

import { F, pixel_bytes } from "../gles_formats3.js";
import { to_rgba8 } from "./gles_textures.js";

/** The bytes of a texel of the WebGPU formats textures have here */
export const TEXEL_BYTES = {
    "r8unorm": 1, "r8snorm": 1, "r8uint": 1, "r8sint": 1, "stencil8": 1,
    "r16uint": 2, "r16sint": 2, "r16float": 2, "rg8unorm": 2, "rg8snorm": 2, "rg8uint": 2, "rg8sint": 2, "depth16unorm": 2,
    "r32uint": 4, "r32sint": 4, "r32float": 4, "rg16uint": 4, "rg16sint": 4, "rg16float": 4, "rgba8unorm": 4, "rgba8unorm-srgb": 4,
    "rgba8snorm": 4, "rgba8uint": 4, "rgba8sint": 4, "rgb10a2unorm": 4, "rgb10a2uint": 4, "rg11b10ufloat": 4, "rgb9e5ufloat": 4,
    "depth24plus": 4, "depth32float": 4, "depth24plus-stencil8": 4,
    "rg32uint": 8, "rg32sint": 8, "rg32float": 8, "rgba16uint": 8, "rgba16sint": 8, "rgba16float": 8, "depth32float-stencil8": 8,
    "rgba32uint": 16, "rgba32sint": 16, "rgba32float": 16,
};

/** The formats a render pass can draw to (WebGPU's, without optional features) */
export const RENDERABLE = new Set(["r8unorm", "r8uint", "r8sint", "rg8unorm", "rg8uint", "rg8sint", "rgba8unorm", "rgba8unorm-srgb", "rgba8uint",
    "rgba8sint", "r16uint", "r16sint", "r16float", "rg16uint", "rg16sint", "rg16float", "rgba16uint", "rgba16sint", "rgba16float", "r32uint",
    "r32sint", "r32float", "rg32uint", "rg32sint", "rg32float", "rgba32uint", "rgba32sint", "rgba32float", "rgb10a2unorm", "rgb10a2uint",
    "depth16unorm", "depth24plus", "depth32float", "depth24plus-stencil8", "depth32float-stencil8", "stencil8"]);

/** The depth and stencil formats WebGPU copies no buffer into: their images are drawn (gles3_executor.js) */
export const DRAWN_DEPTH = new Set(["depth24plus", "depth32float", "depth24plus-stencil8", "depth32float-stencil8"]);

const PACKED = new Set([F.UNSIGNED_SHORT_4_4_4_4, F.UNSIGNED_SHORT_5_5_5_1, F.UNSIGNED_SHORT_5_6_5, F.UNSIGNED_INT_2_10_10_10_REV,
    F.UNSIGNED_INT_10F_11F_11F_REV, F.UNSIGNED_INT_5_9_9_9_REV, F.UNSIGNED_INT_24_8, F.FLOAT_32_UNSIGNED_INT_24_8_REV]);
/** The packed types whose words are the WebGPU format's texels as they are */
const SAME_PACKING = { [F.UNSIGNED_INT_2_10_10_10_REV]: ["rgb10a2unorm", "rgb10a2uint"], [F.UNSIGNED_INT_10F_11F_11F_REV]: ["rg11b10ufloat"],
    [F.UNSIGNED_INT_5_9_9_9_REV]: ["rgb9e5ufloat"] };

/**
 * An image of client memory as tight rows: rows of row_length (or width)
 * pixels aligned, image_height (or height) rows an image (3D images), after
 * the skips; what lies past the data reads as zeros
 * @param {!Uint8Array} data from the client's pointer
 * @param {{alignment: number, row_length: number, image_height: number, skip_pixels: number, skip_rows: number, skip_images: number}} store
 * @param {boolean} three a three-dimensional image's (IMAGE_HEIGHT and SKIP_IMAGES apply)
 * @return {!Uint8Array}
 */
export function unpack_image(data, width, height, depth, format, type, store, three)
{
    const pixel = pixel_bytes(format, type);
    const tight = width * pixel;
    const row = Math.ceil((store.row_length > 0 ? store.row_length : width) * pixel / store.alignment) * store.alignment;
    const image = row * (three && store.image_height > 0 ? store.image_height : height);
    const start = (three ? store.skip_images * image : 0) + store.skip_rows * row + store.skip_pixels * pixel;
    if(start === 0 && row === tight && image === tight * height && data.length >= tight * height * depth)
    {
        return data.subarray(0, tight * height * depth);
    }
    const out = new Uint8Array(tight * height * depth);
    for(let z = 0; z < depth; z++)
    {
        for(let y = 0; y < height; y++)
        {
            const from = start + z * image + y * row;
            if(from >= data.length) return out;
            out.set(data.subarray(from, Math.min(data.length, from + tight)), (z * height + y) * tight);
        }
    }
    return out;
}

const f32 = new Float32Array(1), u32 = new Uint32Array(f32.buffer);

/** @param {number} value @return {number} the IEEE half nearest it */
export function to_half(value)
{
    f32[0] = value;
    const x = u32[0];
    const sign = x >>> 16 & 0x8000;
    const exponent = x >>> 23 & 0xFF, mantissa = x & 0x7FFFFF;
    if(exponent === 0xFF) return sign | 0x7C00 | (mantissa ? 0x200 : 0);
    const e = exponent - 127 + 15;
    if(e >= 31) return sign | 0x7C00;
    if(e <= 0)
    {
        if(e < -10) return sign;
        const m = (mantissa | 0x800000) >> (1 - e);
        return sign | (m + 0x1000 >> 13);
    }
    const half = sign | e << 10 | mantissa >> 13;
    // (round to nearest: a carry into the exponent is right)
    return half + (mantissa >> 12 & 1);
}

/** @param {number} h @return {number} */
export function from_half(h)
{
    const s = h & 0x8000 ? -1 : 1, e = h >> 10 & 31, m = h & 1023;
    if(e === 0) return s * m * 2 ** -24;
    if(e === 31) return m ? NaN : s * Infinity;
    return s * (1 + m / 1024) * 2 ** (e - 15);
}

/** An unsigned float of `bits` mantissa bits and 5 exponent bits (R11F_G11F_B10F's) */
function to_ufloat(value, mantissa_bits)
{
    if(!(value > 0)) return 0;
    const max_exponent = 30;
    if(value >= 2 ** 15 * (2 - 2 ** -mantissa_bits)) return max_exponent << mantissa_bits | (1 << mantissa_bits) - 1;
    let e = Math.floor(Math.log2(value));
    if(e < -14) return Math.round(value / 2 ** -14 * (1 << mantissa_bits)) & (1 << mantissa_bits) - 1;
    let m = Math.round((value / 2 ** e - 1) * (1 << mantissa_bits));
    if(m === 1 << mantissa_bits) { m = 0; e++; }
    return e + 15 << mantissa_bits | m;
}

/** RGB as RGB9_E5's shared exponent (GLES 3.0, 3.8.3.2) */
function to_rgb9e5(r, g, b)
{
    const max = 65408;
    const clamp = v => Math.min(max, Math.max(0, v || 0));
    r = clamp(r); g = clamp(g); b = clamp(b);
    const largest = Math.max(r, g, b);
    let e = Math.max(-16, Math.floor(Math.log2(largest || 2 ** -16))) + 1 + 15;
    let scale = 2 ** (e - 15 - 9);
    if(Math.round(largest / scale) === 512) { e++; scale *= 2; }
    return (Math.round(b / scale) << 18 | Math.round(g / scale) << 9 | Math.round(r / scale) | e << 27) >>> 0;
}

/**
 * Tight pixels of the format and type as the texels of the image's WebGPU
 * format
 * @param {!Uint8Array} tight unpack_image's
 * @param {number} count the pixels
 * @param {!Object} info the image's format (format_info's)
 * @return {?Uint8Array} null for a depth or stencil format drawn (DRAWN_DEPTH)
 */
export function to_texels(tight, count, format, type, info)
{
    const target = info.webgpu;
    if(!info.sized) return to_rgba8(format, type, count, 1, 1, tight);
    if(DRAWN_DEPTH.has(target)) return null;
    const texel = TEXEL_BYTES[target];
    const pixel = pixel_bytes(format, type);
    if(PACKED.has(type) ? (SAME_PACKING[type] || []).includes(target) : pixel === texel) return tight;
    const view = new DataView(tight.buffer, tight.byteOffset, tight.byteLength);
    const out = new Uint8Array(count * texel);
    const o = new DataView(out.buffer);
    const channels = { [F.RED]: 1, [F.RED_INTEGER]: 1, [F.RG]: 2, [F.RG_INTEGER]: 2, [F.RGB]: 3, [F.RGB_INTEGER]: 3, [F.RGBA]: 4,
        [F.RGBA_INTEGER]: 4, [F.DEPTH_COMPONENT]: 1 }[format] || 4;
    const out_channels = target.startsWith("rgba") ? 4 : target.startsWith("rg") && !target.startsWith("rgb") ? 2 : target.startsWith("r") ? 1 : 4;
    switch(type)
    {
        case F.UNSIGNED_SHORT_5_6_5: case F.UNSIGNED_SHORT_4_4_4_4: case F.UNSIGNED_SHORT_5_5_5_1: case F.UNSIGNED_INT_2_10_10_10_REV:
        {
            // (into RGBA8: RGB565, RGBA4, RGB5_A1)
            const rgba = type === F.UNSIGNED_INT_2_10_10_10_REV ? null : to_rgba8(F.RGBA, type, count, 1, 1, tight);
            if(rgba) return rgba;
            for(let i = 0; i < count; i++)
            {
                const v = view.getUint32(4 * i, true);
                out.set([Math.round((v & 1023) * 255 / 1023), Math.round((v >> 10 & 1023) * 255 / 1023), Math.round((v >> 20 & 1023) * 255 / 1023),
                    (v >>> 30) * 85], 4 * i);
            }
            return out;
        }
    }
    if(format === F.DEPTH_COMPONENT && target === "depth16unorm")
    {
        // (UNSIGNED_INT's high half)
        for(let i = 0; i < count; i++) o.setUint16(2 * i, view.getUint32(4 * i, true) >>> 16, true);
        return out;
    }
    if(target === "rg11b10ufloat" || target === "rgb9e5ufloat")
    {
        const read = type === F.FLOAT ? (i, k) => view.getFloat32(12 * i + 4 * k, true) : (i, k) => from_half(view.getUint16(6 * i + 2 * k, true));
        for(let i = 0; i < count; i++)
        {
            const [r, g, b] = [read(i, 0), read(i, 1), read(i, 2)];
            o.setUint32(4 * i, target === "rgb9e5ufloat" ? to_rgb9e5(r, g, b) : (to_ufloat(r, 6) | to_ufloat(g, 6) << 11 | to_ufloat(b, 5) << 22) >>> 0, true);
        }
        return out;
    }
    // floats as halves; a missing alpha one (by the component's kind)
    const half = target.includes("16float");
    const size = type === F.FLOAT ? 4 : type === F.HALF_FLOAT || type === F.HALF_FLOAT_OES || type === F.SHORT || type === F.UNSIGNED_SHORT ? 2 :
        type === F.INT || type === F.UNSIGNED_INT ? 4 : 1;
    const out_size = texel / out_channels;
    const one = info.kind === "float" ? (half ? [0x00, 0x3C] : [0, 0, 0x80, 0x3F]) : info.kind === "unorm" ? [255] : info.kind === "snorm" ? [127] :
        [1, 0, 0, 0].slice(0, out_size);
    for(let i = 0; i < count; i++)
    {
        for(let k = 0; k < out_channels; k++)
        {
            const at = (i * out_channels + k) * out_size;
            if(k >= channels)
            {
                if(k === 3) out.set(one, at);
                continue;
            }
            const from = (i * channels + k) * size;
            if(half && size === 4) o.setUint16(at, to_half(view.getFloat32(from, true)), true);
            else out.set(tight.subarray(from, from + out_size), at);
        }
    }
    return out;
}

/**
 * Depth (and stencil) values of a depth format's pixels, for an image that is
 * drawn: depths from 0 to 1, stencils as bytes
 * @return {{depth: !Float32Array, stencil: ?Uint8Array}}
 */
export function depth_values(tight, count, format, type)
{
    const view = new DataView(tight.buffer, tight.byteOffset, tight.byteLength);
    const depth = new Float32Array(count);
    const stencil = format === F.DEPTH_STENCIL ? new Uint8Array(count) : null;
    for(let i = 0; i < count; i++)
    {
        switch(type)
        {
            case F.UNSIGNED_SHORT: depth[i] = view.getUint16(2 * i, true) / 65535; break;
            case F.UNSIGNED_INT: depth[i] = view.getUint32(4 * i, true) / 4294967295; break;
            case F.FLOAT: depth[i] = Math.min(1, Math.max(0, view.getFloat32(4 * i, true))); break;
            case F.UNSIGNED_INT_24_8:
            {
                const v = view.getUint32(4 * i, true);
                depth[i] = (v >>> 8) / 0xFFFFFF;
                stencil[i] = v & 0xFF;
                break;
            }
            case F.FLOAT_32_UNSIGNED_INT_24_8_REV:
                depth[i] = Math.min(1, Math.max(0, view.getFloat32(8 * i, true)));
                stencil[i] = view.getUint32(8 * i + 4, true) & 0xFF;
                break;
        }
    }
    return { depth, stencil };
}

/** An unsigned float of 5 exponent bits and `bits` mantissa bits */
function from_ufloat(v, bits)
{
    const e = v >> bits & 31, m = v & (1 << bits) - 1;
    if(e === 0) return m * 2 ** -14 / (1 << bits);
    if(e === 31) return m ? NaN : Infinity;
    return (1 + m / (1 << bits)) * 2 ** (e - 15);
}

/**
 * Texels of a WebGPU color format as four values each (normalized ones as
 * GL reads them, from 0 or -1 to 1; integers as they are; a missing
 * channel 0, alpha 1)
 * @param {!Uint8Array} raw tight texels
 * @return {!Float64Array}
 */
export function decode_texels(raw, count, format)
{
    const view = new DataView(raw.buffer, raw.byteOffset, raw.byteLength);
    const out = new Float64Array(count * 4);
    const texel = TEXEL_BYTES[format];
    const channels = format.startsWith("rgba") ? 4 : format.startsWith("rg") && !format.startsWith("rgb") ? 2 : 1;
    const size = texel / channels;
    const kind = format.includes("uint") ? "u" : format.includes("sint") ? "i" : format.includes("float") ? "f" : format.includes("snorm") ? "s" : "n";
    for(let i = 0; i < count; i++)
    {
        const at = i * texel, o = i * 4;
        out[o + 3] = 1;
        if(format === "rgb10a2unorm" || format === "rgb10a2uint")
        {
            const v = view.getUint32(at, true);
            const parts = [v & 1023, v >>> 10 & 1023, v >>> 20 & 1023, v >>> 30];
            for(let k = 0; k < 4; k++) out[o + k] = format === "rgb10a2uint" ? parts[k] : parts[k] / (k === 3 ? 3 : 1023);
            continue;
        }
        if(format === "rg11b10ufloat")
        {
            const v = view.getUint32(at, true);
            out[o] = from_ufloat(v & 2047, 6);
            out[o + 1] = from_ufloat(v >>> 11 & 2047, 6);
            out[o + 2] = from_ufloat(v >>> 22, 5);
            continue;
        }
        if(format === "rgb9e5ufloat")
        {
            const v = view.getUint32(at, true);
            const scale = 2 ** ((v >>> 27) - 15 - 9);
            out[o] = (v & 511) * scale;
            out[o + 1] = (v >>> 9 & 511) * scale;
            out[o + 2] = (v >>> 18 & 511) * scale;
            continue;
        }
        for(let k = 0; k < channels; k++)
        {
            const p = at + k * size;
            let value;
            if(kind === "f") value = size === 2 ? from_half(view.getUint16(p, true)) : view.getFloat32(p, true);
            else if(size === 1) value = kind === "i" || kind === "s" ? view.getInt8(p) : view.getUint8(p);
            else if(size === 2) value = kind === "i" || kind === "s" ? view.getInt16(p, true) : view.getUint16(p, true);
            else value = kind === "i" ? view.getInt32(p, true) : view.getUint32(p, true);
            if(kind === "n") value /= 2 ** (8 * size) - 1;
            else if(kind === "s") value = Math.max(-1, value / (2 ** (8 * size - 1) - 1));
            out[o + k] = value;
        }
    }
    return out;
}

/**
 * Four values a pixel (decode_texels') as client memory holds them by
 * glReadPixels' format and type and the pack state (GLES 3.0, 4.3.2): rows
 * of row_length (or width) pixels aligned, after the skips; the bytes the
 * read does not write stay zero
 * @param {{alignment: number, row_length: number, skip_pixels: number, skip_rows: number}} store
 * @return {!Uint8Array}
 */
export function pack_pixels(values, width, height, format, type, store)
{
    const pixel = pixel_bytes(format, type);
    const row = Math.ceil((store.row_length > 0 ? store.row_length : width) * pixel / store.alignment) * store.alignment;
    const start = store.skip_rows * row + store.skip_pixels * pixel;
    const out = new Uint8Array(width && height ? start + (height - 1) * row + width * pixel : 0);
    const view = new DataView(out.buffer);
    const order = { [F.RED]: [0], [F.RED_INTEGER]: [0], [F.RG]: [0, 1], [F.RG_INTEGER]: [0, 1], [F.RGB]: [0, 1, 2], [F.RGB_INTEGER]: [0, 1, 2],
        [F.RGBA]: [0, 1, 2, 3], [F.RGBA_INTEGER]: [0, 1, 2, 3], [F.ALPHA]: [3], [F.LUMINANCE]: [0], [F.LUMINANCE_ALPHA]: [0, 3],
        [F.BGRA_EXT]: [2, 1, 0, 3] }[format] || [0, 1, 2, 3];
    const integer = format === F.RED_INTEGER || format === F.RG_INTEGER || format === F.RGB_INTEGER || format === F.RGBA_INTEGER;
    const clamp = (v, low) => Math.min(1, Math.max(low, v));
    const unorm = (v, bits) => Math.round(clamp(v, 0) * (2 ** bits - 1));
    for(let y = 0; y < height; y++)
    {
        for(let x = 0; x < width; x++)
        {
            const v = values.subarray((y * width + x) * 4, (y * width + x) * 4 + 4);
            const at = start + y * row + x * pixel;
            switch(type)
            {
                case F.UNSIGNED_SHORT_5_6_5: view.setUint16(at, unorm(v[0], 5) << 11 | unorm(v[1], 6) << 5 | unorm(v[2], 5), true); continue;
                case F.UNSIGNED_SHORT_4_4_4_4:
                    view.setUint16(at, unorm(v[0], 4) << 12 | unorm(v[1], 4) << 8 | unorm(v[2], 4) << 4 | unorm(v[3], 4), true);
                    continue;
                case F.UNSIGNED_SHORT_5_5_5_1:
                    view.setUint16(at, unorm(v[0], 5) << 11 | unorm(v[1], 5) << 6 | unorm(v[2], 5) << 1 | unorm(v[3], 1), true);
                    continue;
                case F.UNSIGNED_INT_2_10_10_10_REV:
                {
                    const p = integer ? v.map((c, k) => Math.min(k === 3 ? 3 : 1023, Math.max(0, c))) : v.map((c, k) => unorm(c, k === 3 ? 2 : 10));
                    view.setUint32(at, (p[0] | p[1] << 10 | p[2] << 20 | p[3] << 30) >>> 0, true);
                    continue;
                }
                case F.UNSIGNED_INT_10F_11F_11F_REV:
                    view.setUint32(at, (to_ufloat(v[0], 6) | to_ufloat(v[1], 6) << 11 | to_ufloat(v[2], 5) << 22) >>> 0, true);
                    continue;
                case F.UNSIGNED_INT_5_9_9_9_REV: view.setUint32(at, to_rgb9e5(v[0], v[1], v[2]), true); continue;
            }
            order.forEach((channel, k) =>
            {
                const c = v[channel];
                switch(type)
                {
                    case F.UNSIGNED_BYTE: view.setUint8(at + k, integer ? c : unorm(c, 8)); break;
                    case F.BYTE: view.setInt8(at + k, integer ? c : Math.round(clamp(c, -1) * 127)); break;
                    case F.UNSIGNED_SHORT: view.setUint16(at + 2 * k, integer ? c : unorm(c, 16), true); break;
                    case F.SHORT: view.setInt16(at + 2 * k, integer ? c : Math.round(clamp(c, -1) * 32767), true); break;
                    case F.UNSIGNED_INT: view.setUint32(at + 4 * k, integer ? c >>> 0 : unorm(c, 32), true); break;
                    case F.INT: view.setInt32(at + 4 * k, integer ? c | 0 : Math.round(clamp(c, -1) * 2147483647), true); break;
                    case F.HALF_FLOAT: case F.HALF_FLOAT_OES: view.setUint16(at + 2 * k, to_half(c), true); break;
                    case F.FLOAT: view.setFloat32(at + 4 * k, c, true); break;
                }
            });
        }
    }
    return out;
}
                                                                                                                                                                                                                                                                                                                                          source/v64/src/gles/page/gles_executor.js                                                           0000644 0000000 0000000 00000235731 00000000000 015542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GLES executor (docs/gles-proxy-plan.md "执行器", E3): GLES batches
// (src/gles/gles_batch.js) on WebGPU, on the page. It runs the same state
// machine as the CPU side (src/gles/gles_shadow.js) over the commands it
// receives, so names, bindings, uniforms and locations agree, and keeps the
// GPU's part beside the shadow's objects: a texture's GPU texture, a
// buffer's bytes, a renderbuffer's attachment, a program's WGSL (the
// translator's ES mode, linked by the shadow).
//
// Orientation: GL's rendering keeps the translator's flip (framebuffer row
// 0 is GL's bottom row: viewport, scissor, readback and render-to-texture
// need no conversion). Color buffers hold Android's memory order (row 0 the
// top, as gralloc's CPU writes and SurfaceFlinger's texture transform
// expect), so a window surface draws into a texture of its own (gfxstream's
// pbuffer) which rcFlushWindowColorBuffer copies into its color buffer,
// flipped; reads and writes of color buffers are then plain copies.
//
// Each draw assembles its vertices on the CPU (client arrays come with the
// draw; buffers' bytes are kept here), converted to f32 where WebGPU has no
// format, with its indices as u32 (fans and loops expanded). Uploads go
// through staging buffers copied in the command encoder, in order with the
// draws. A post (rcFBPost) shows the color buffer: in the compositor's layer
// when there is one, otherwise read back and handed to the CPU side
// ("frame"). Points are WebGPU's, one pixel each.

import { GLESShadow } from "../gles_shadow.js";
import { read_gles_batch } from "../gles_batch.js";
import { GL, RENDERBUFFER_FORMATS } from "../gles_formats.js";
import { CONFIGS, CONFIG_ATTRIBUTES, EGL } from "../gles_caps.js";
import { decode_etc1, pack_rgba8, to_rgba8 } from "./gles_textures.js";
import { ff_inputs, ff_signature, ff_snapshot, unit_texture } from "./gles1_draw.js";
import { UNITS } from "../gles1_state.js";
import { SHADOW_CLASSES } from "../gles_shadow.js";
import { pack, shadow_skip, unpack } from "../gles_snapshot.js";
import { unpack_program } from "../glsl_program.js";
import { B, COLOR_FORMAT, COMPARE, STENCIL_OPS, U, WRAPS, align4, blend_component } from "./gles_gpu_tables.js";
import { GLES3 } from "./gles3_executor.js";

const TEXTURE_USAGE = U.TEXTURE_BINDING | U.COPY_DST | U.COPY_SRC | U.RENDER_ATTACHMENT;
const READBACK_HEADER = 16;

const DEPTH_FORMATS = {
    [GL.DEPTH_COMPONENT16]: "depth16unorm", [GL.DEPTH_COMPONENT24_OES]: "depth24plus", [GL.STENCIL_INDEX8]: "stencil8",
    [GL.DEPTH24_STENCIL8_OES]: "depth24plus-stencil8",
};
/** The vertex types: their bytes and how they read */
const TYPE_BYTES = { [GL.BYTE]: 1, [GL.UNSIGNED_BYTE]: 1, [GL.SHORT]: 2, [GL.UNSIGNED_SHORT]: 2, [GL.FLOAT]: 4, [GL.FIXED]: 4, [GL.HALF_FLOAT_OES]: 2 };

/** IEEE half to a float */
function half_to_float(h)
{
    const s = h & 0x8000 ? -1 : 1, e = h >> 10 & 31, m = h & 1023;
    if(e === 0) return s * m * 2 ** -24;
    if(e === 31) return m ? NaN : s * Infinity;
    return s * (1 + m / 1024) * 2 ** (e - 15);
}

/**
 * The WGSL bindings an entry point reaches ("group:binding"): an "auto"
 * layout has only those (gl_executor.js's collectReachableWgslBindings, the
 * same walk: the entry point's body, then the functions it calls)
 * @param {string} source
 * @param {string} entry
 * @param {!Set<string>} result
 */
function reachable_bindings(source, entry, result)
{
    const text = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\r\n]*/g, "");
    const bindings = new Map();
    for(const m of text.matchAll(/@group\s*\(\s*(\d+)\s*\)\s*@binding\s*\(\s*(\d+)\s*\)\s*var(?:\s*<[^>]*>)?\s+([A-Za-z_][A-Za-z0-9_]*)\s*:/g))
    {
        bindings.set(m[3], m[1] + ":" + m[2]);
    }
    const functions = new Map();
    const pattern = /\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/g;
    for(let m; (m = pattern.exec(text));)
    {
        const open = text.indexOf("{", pattern.lastIndex);
        if(open < 0) break;
        let depth = 1, end = open + 1;
        while(end < text.length && depth)
        {
            if(text[end] === "{") depth++;
            else if(text[end] === "}") depth--;
            end++;
        }
        functions.set(m[1], text.slice(open + 1, end - 1));
        pattern.lastIndex = end;
    }
    const pending = [entry], visited = new Set();
    while(pending.length)
    {
        const name = pending.pop();
        if(visited.has(name)) continue;
        visited.add(name);
        const body = functions.get(name);
        if(body === undefined) continue;
        for(const [variable, key] of bindings) if(new RegExp("\\b" + variable + "\\b").test(body)) result.add(key);
        for(const call of body.matchAll(/\b([A-Za-z_][A-Za-z0-9_]*)\s*\(/g)) if(functions.has(call[1]) && !visited.has(call[1])) pending.push(call[1]);
    }
}

/**
 * @constructor
 * @param {{device: !GPUDevice, layer: ?Object, features: (Object|undefined)}} options
 */
export function GLESExecutor(options)
{
    this.device = options.device;
    this.layer = options.layer || null;
    this.reset();
}

GLESExecutor.prototype.reset = function()
{
    // what the shadow state asks of renderControl: images and color buffers
    this.rc = { images: new Map(), color_buffers: new Map() };
    this.shadow = new GLESShadow(this.rc);
    // (GLES 3.0's buffers keep their bytes here too: the GPU buffers' source, gles3_executor.js)
    this.shadow.keep_bytes = true;
    // (names the CPU side made with glGen*, which it keeps to itself, are made here)
    this.shadow.trusted = true;
    /** @type {!Map<number, {context: number, draw: number, read: number}>} */
    this.conns = new Map();
    /** @type {!Map<number, {config: number, width: number, height: number, color_buffer: number, texture: ?GPUTexture, depth: ?GPUTexture, depth_format: string}>} */
    this.surfaces = new Map();
    this.shaders = new Map();
    this.pipelines = new Map();
    this.samplers = new Map();
    this.fallback = null;
    this.blit = null;
    /** the frame to show, a read of it in flight */
    this.posted = 0;
    this.stats = { batches: 0, records: 0, draws: 0, refused: 0, pipelines: 0, uploads: 0, posts: 0, errors: [] };
    this.pass = null;
    this.pass_target = null;
};

// ---- batches

/**
 * Run a batch
 * @param {!Uint8Array} bytes
 * @param {{writeResponse: function(number, !Uint8Array), frame: (function(!Uint8Array, number, number)|undefined)}} sink
 *     the answers to reads (the readback header, then the pixels), and the
 *     posted frames when there is no layer (RGBA, rows from the top)
 */
GLESExecutor.prototype.submit = async function(bytes, sink)
{
    const records = read_gles_batch(bytes, true);
    this.stats.batches++;
    // (glslang's programs draw through vx_naga: loaded before the batch with the first link, or the first after a restore)
    if(!this.naga && (records.some(r => r.name === "PROGRAM_LINK") || [...this.shadow.contexts.values()].some(c => c.glslang)))
    {
        try
        {
            await this.load_naga();
        }
        catch(error)
        {
            if(this.stats.errors.length < 20) this.stats.errors.push("vx_naga: " + (error && error.message || error));
        }
    }
    this.encoder = this.device.createCommandEncoder({ label: "GLES batch" });
    this.reads = [];
    this.staging = [];
    for(const record of records)
    {
        this.stats.records++;
        try
        {
            this.run(record);
        }
        catch(error)
        {
            // (one command's failure is reported; the batch goes on)
            if(this.stats.errors.length < 20) this.stats.errors.push((record.command ? record.command.name : record.name) + ": " + (error && error.message || error));
        }
    }
    this.batch_end3();
    this.end_pass();
    this.device.queue.submit([this.encoder.finish()]);
    this.encoder = null;
    // (what the batch used and dropped goes only now: its commands were recorded with it)
    for(const object of this.staging) object.destroy();
    this.staging = [];
    const reads = this.reads;
    this.reads = [];
    for(const read of reads)
    {
        // (an answer with nothing to read: a failed read, an empty rectangle)
        if(!read.buffer)
        {
            read.done(null, sink);
            continue;
        }
        await read.buffer.mapAsync(globalThis.GPUMapMode ? globalThis.GPUMapMode.READ : 1);
        const mapped = new Uint8Array(read.buffer.getMappedRange());
        // (rows of texels, or a buffer's bytes as they are: `bytes`)
        const row = read.bytes || read.width * (read.texel || 4);
        const rows = new Uint8Array(row * (read.bytes ? 1 : read.height));
        if(read.bytes) rows.set(mapped.subarray(read.skip || 0, (read.skip || 0) + read.bytes));
        else for(let y = 0; y < read.height; y++)
        {
            const from = read.flip ? read.height - 1 - y : y;
            rows.set(mapped.subarray(from * read.stride, from * read.stride + row), y * row);
        }
        read.buffer.unmap();
        read.buffer.destroy();
        read.done(rows, sink);
    }
};

/** @param {!Object} record */
GLESExecutor.prototype.run = function(record)
{
    switch(record.name)
    {
        case "COMMAND": return this.command(record);
        case "CONTEXT_CREATE": return this.shadow.create_context(record.context, record.api, record.share);
        case "CONTEXT_DESTROY": return this.shadow.destroy_context(record.context);
        case "SURFACE_CREATE":
            this.surfaces.set(record.surface, { config: record.config, width: record.width, height: record.height, color_buffer: 0,
                texture: null, depth: null, depth_format: "" });
            return undefined;
        case "SURFACE_DESTROY":
        {
            const s = this.surfaces.get(record.surface);
            if(s && s.texture) this.staging.push(s.texture);
            if(s && s.depth) this.staging.push(s.depth);
            this.surfaces.delete(record.surface);
            return undefined;
        }
        case "SURFACE_COLOR_BUFFER":
        {
            const s = this.surfaces.get(record.surface);
            if(s) s.color_buffer = record.color_buffer;
            return undefined;
        }
        case "MAKE_CURRENT":
        {
            this.conns.set(record.conn, { context: record.context, draw: record.draw, read: record.read });
            const s = this.surfaces.get(record.draw);
            this.shadow.make_current(record.context, s ? { width: s.width, height: s.height, config: CONFIGS[s.config] } : null);
            return undefined;
        }
        case "CONNECTION_CLOSE": this.conns.delete(record.conn); return undefined;
        case "PROGRAM_LINK":
        {
            // (glslang's link of a program, for the glLinkProgram after it: the page has no glslang)
            const conn = this.conns.get(record.conn);
            const c = conn && this.shadow.context(conn.context);
            const program = c && c.group.objects.get(record.program);
            if(program && program.kind === "program") program.provided = unpack_program(record.bytes);
            // (glCreateShaderProgramv's: its program is made by the command after, which takes it)
            else if(c) (this.shadow.pending_links = this.shadow.pending_links || new Map()).set(record.program, unpack_program(record.bytes));
            return undefined;
        }
        case "COLOR_BUFFER_CREATE":
        {
            const texture = this.device.createTexture({ label: "color buffer " + record.color_buffer, size: [record.width, record.height],
                format: COLOR_FORMAT, usage: TEXTURE_USAGE });
            this.rc.color_buffers.set(record.color_buffer, { width: record.width, height: record.height, format: record.format, texture });
            // (an RGB buffer reads as opaque until written)
            if(record.format === GL.RGB) this.clear_texture(texture, [0, 0, 0, 1]);
            return undefined;
        }
        case "COLOR_BUFFER_DESTROY":
        {
            const cb = this.rc.color_buffers.get(record.color_buffer);
            if(cb) this.staging.push(cb.texture);
            this.rc.color_buffers.delete(record.color_buffer);
            return undefined;
        }
        case "COLOR_BUFFER_UPDATE":
        {
            const cb = this.rc.color_buffers.get(record.color_buffer);
            if(!cb || !record.width || !record.height) return undefined;
            const rgba = to_rgba8(record.format, record.type, record.width, record.height, 1, record.bytes);
            this.upload(cb.texture, 0, 0, record.x, record.y, record.width, record.height, rgba);
            return undefined;
        }
        case "COLOR_BUFFER_READ":
        {
            const cb = this.rc.color_buffers.get(record.color_buffer);
            if(!cb) return this.answer_failed(record.request);
            return this.read_texture(cb.texture, record.x, record.y, record.width, record.height, false,
                (rgba, sink) => this.answer(sink, record.request, rgba));
        }
        case "COLOR_BUFFER_BIND":
        {
            const conn = this.conns.get(record.conn);
            if(conn) this.shadow.bind_color_buffer(conn.context, record.color_buffer, !!record.texture);
            return undefined;
        }
        case "IMAGE_CREATE":
            this.rc.images.set(record.image, { context: record.context, target: record.target, buffer: record.buffer });
            return undefined;
        case "IMAGE_DESTROY": this.rc.images.delete(record.image); return undefined;
        case "FLUSH_SURFACE": return this.flush_surface(record.surface);
        case "POST": return this.post(record.color_buffer);
        case "READ_PIXELS": return this.read_pixels(record);
        case "BUFFER_READ": return this.buffer_read3(record);
        case "QUERY_READ": return this.query_read3(record);
    }
    return undefined;
};

// ---- commands

/** A GLES command: the shadow state, then what the GPU does of it */
GLESExecutor.prototype.command = function(record)
{
    const conn = this.conns.get(record.conn);
    const context = conn ? conn.context : 0;
    const c = this.shadow.context(context);
    if(!c) return;
    const name = record.command.name.replace(/OES$/, "");
    const args = record.args;
    // (what a deletion takes away: its GPU objects with it)
    const before = name === "glDeleteTextures" || name === "glDeleteRenderbuffers" || name === "glDeleteBuffers" ?
        new Int32Array(args[1].buffer.slice(args[1].byteOffset, args[1].byteOffset + args[1].length)) : null;
    const objects = name === "glDeleteTextures" ? c.group.textures : name === "glDeleteRenderbuffers" ? c.group.renderbuffers :
        name === "glDeleteBuffers" ? c.group.buffers : null;
    const gone = before ? [...before].map(n => objects.get(n)).filter(Boolean) : [];
    this.shadow.given_name = name === "glCreateShader" || name === "glCreateProgram" || name === "glCreateShaderProgramvAEMU" ? record.ret : 0;
    const { keep } = this.shadow.call(context, record.command, args);
    this.shadow.given_name = 0;
    if(!keep)
    {
        // (what the CPU side took and this shadow refuses: the two disagree)
        this.stats.refused++;
        const by = this.stats.refused_by = this.stats.refused_by || {};
        const key = name + ":0x" + c.error.toString(16);
        if(key in by || Object.keys(by).length < 20) by[key] = (by[key] || 0) + 1;
        return;
    }
    for(const object of gone) if(object.gpu && object.gpu.destroy && ![...objects.values()].includes(object)) this.staging.push(object.gpu);
    // (GLES 3.x's, and GLES 2.0's of a host with glslang: gles3_executor.js)
    if(c.glslang && this.command3(c, name, args)) return undefined;
    switch(name)
    {
        case "glTexImage2D": return this.tex_image(c, args, false);
        case "glTexSubImage2D": return this.tex_image(c, args, true);
        case "glCompressedTexImage2D": return this.compressed_tex_image(c, args);
        case "glCopyTexImage2D": return this.copy_tex_image(c, args, false);
        case "glCopyTexSubImage2D": return this.copy_tex_image(c, args, true);
        case "glGenerateMipmap": return this.generate_mipmap(c, args[0]);
        case "glEGLImageTargetTexture2D": return this.invalidate_texture(c, args[0]);
        case "glBufferData": return this.buffer_data(c, args, false);
        case "glBufferSubData": return this.buffer_data(c, args, true);
        case "glRenderbufferStorage": case "glEGLImageTargetRenderbufferStorage": return this.renderbuffer_storage(c);
        case "glVertexAttribPointerData":
            // (the client array's data, tight, from the draw's first vertex: the encoder's)
            c.attribs[args[0]].data = args[5];
            return undefined;
        case "glVertexAttribPointerOffset":
            c.attribs[args[0]].data = null;
            return undefined;
        case "glClear": return this.clear(c, args[0]);
        case "glDrawArrays": return this.draw(c, args[0], args[1], args[2], null);
        case "glDrawElementsData": return this.draw(c, args[0], 0, args[1], { type: args[2], bytes: args[3] });
        case "glDrawElementsOffset": return this.draw(c, args[0], 0, args[1], { type: args[2], offset: args[3] });
        case "glDrawTexs": case "glDrawTexi": case "glDrawTexf": return this.draw_tex(c, args);
        case "glDrawTexx": return this.draw_tex(c, args.map(v => v / 65536));
        case "glDrawTexsv": return this.draw_tex(c, Array.from(new Int16Array(args[0].slice().buffer)));
        case "glDrawTexiv": return this.draw_tex(c, Array.from(new Int32Array(args[0].slice().buffer)));
        case "glDrawTexfv": return this.draw_tex(c, Array.from(new Float32Array(args[0].slice().buffer)));
        case "glDrawTexxv": return this.draw_tex(c, Array.from(new Int32Array(args[0].slice().buffer), v => v / 65536));
    }
    return undefined;
};

// ---- textures

/** The bound texture of a target (TexImage2D's: 2D or a face) and the face's layer */
function bound(c, target)
{
    const face = target === GL.TEXTURE_2D ? 0 : target - GL.TEXTURE_CUBE_MAP_POSITIVE_X;
    const slot = target === GL.TEXTURE_2D ? 0 : target === GL.TEXTURE_EXTERNAL_OES ? 2 : 1;
    const name = c.textures[c.active_texture][slot];
    const texture = name ? c.group.textures.get(name) : c.defaults && c.defaults.get(slot === 0 ? GL.TEXTURE_2D : slot === 2 ? GL.TEXTURE_EXTERNAL_OES : GL.TEXTURE_CUBE_MAP);
    return { texture, face: face >= 0 && face < 6 ? face : 0 };
}

/**
 * A texture's GPU texture, made (again) to hold its level 0's size with a
 * full mip chain: images come one level at a time, and the levels already
 * sent are copied over when the size stays
 */
GLESExecutor.prototype.gpu_texture = function(texture)
{
    const cube = texture.target === GL.TEXTURE_CUBE_MAP;
    // (a cube map's size from whichever face's level 0 came first: dEQP gives -X before +X)
    const base = cube ? [0, 1, 2, 3, 4, 5].map(face => texture.images.get(face * 32)).find(image => image && image.width) :
        texture.images.get(0);
    if(!base || !base.width || !base.height) return null;
    const levels = Math.floor(Math.log2(Math.max(base.width, base.height))) + 1;
    const gpu = texture.gpu;
    if(gpu && gpu.width === base.width && gpu.height === base.height && gpu.cube === cube) return gpu;
    const created = this.device.createTexture({ label: "GL texture", size: [base.width, base.height, cube ? 6 : 1],
        format: COLOR_FORMAT, usage: TEXTURE_USAGE, mipLevelCount: levels });
    if(gpu && gpu.texture) this.staging.push(gpu.texture);
    texture.gpu = { texture: created, width: base.width, height: base.height, cube, levels, views: new Map(),
        destroy: () => created.destroy() };
    return texture.gpu;
};

/**
 * Where a texture's level is written: a color buffer's texture when level 0
 * is one (rcBindTexture's, an EGL image's: writes go to that color buffer,
 * as gfxstream's do), otherwise the texture's own
 * @return {?{texture: !GPUTexture, levels: number}}
 */
GLESExecutor.prototype.write_target = function(texture, level)
{
    const base = texture.images.get(0);
    if(base && (base.image || base.color_buffer))
    {
        if(level) return null;
        const t = base.image ? this.image_texture(base.image) : this.color_buffer_texture(base.color_buffer);
        return t ? { texture: t.texture, levels: 1 } : null;
    }
    const gpu = this.gpu_texture(texture);
    return gpu ? { texture: gpu.texture, levels: gpu.levels } : null;
};

GLESExecutor.prototype.invalidate_texture = function(c, target)
{
    const { texture } = bound(c, target);
    if(texture && texture.gpu && texture.gpu.texture) this.staging.push(texture.gpu.texture);
    if(texture) texture.gpu = null;
};

GLESExecutor.prototype.tex_image = function(c, args, sub)
{
    const [target, level] = args;
    const { texture, face } = bound(c, target);
    if(!texture) return;
    const image = texture.images.get(face * 32 + level);
    let x = 0, y = 0, width, height, format, type, pixels;
    if(sub) [, , x, y, width, height, format, type, pixels] = args;
    else [, , , width, height, , format, type, pixels] = args;
    if(!width || !height) return;
    const target_texture = this.write_target(texture, level);
    if(!target_texture || level >= target_texture.levels || (target_texture.texture.width >> level || 1) < x + width) return;
    void image;
    const rgba = to_rgba8(format, type, width, height, c.unpack_alignment, pixels);
    this.upload(target_texture.texture, level, face, x, y, width, height, rgba);
};

GLESExecutor.prototype.compressed_tex_image = function(c, args)
{
    const [target, level, , width, height, , , data] = args;
    const { texture, face } = bound(c, target);
    const t = texture && this.write_target(texture, level);
    if(!t || level >= t.levels) return;
    this.upload(t.texture, level, face, 0, 0, width, height, decode_etc1(width, height, data));
};

/** glCopyTex(Sub)Image2D: from what is read (the read framebuffer's color) into a level */
GLESExecutor.prototype.copy_tex_image = function(c, args, sub)
{
    const [target, level] = args;
    let xoffset = 0, yoffset = 0, x, y, width, height;
    if(sub) [, , xoffset, yoffset, x, y, width, height] = args;
    else [, , , x, y, width, height] = args;
    const { texture, face } = bound(c, target);
    const gpu = texture && this.write_target(texture, level);
    const source = this.target_of(c);
    if(!gpu || !source || !source.color || level >= gpu.levels || gpu.texture === source.color) return;
    // (the part inside the source: the rest stays undefined, as GL says)
    const sx = Math.max(0, x), sy = Math.max(0, y);
    const w = Math.min(width - (sx - x), source.width - sx), h = Math.min(height - (sy - y), source.height - sy);
    if(w <= 0 || h <= 0) return;
    this.end_pass();
    this.encoder.copyTextureToTexture({ texture: source.color, origin: [sx, sy, 0] },
        { texture: gpu.texture, mipLevel: level, origin: [xoffset + sx - x, yoffset + sy - y, face] }, [w, h, 1]);
};

GLESExecutor.prototype.generate_mipmap = function(c, target)
{
    const { texture } = bound(c, target === GL.TEXTURE_2D ? GL.TEXTURE_2D : GL.TEXTURE_CUBE_MAP);
    const gpu = texture && this.gpu_texture(texture);
    if(!gpu) return;
    this.end_pass();
    for(let face = 0; face < (gpu.cube ? 6 : 1); face++)
    {
        for(let level = 1; level < gpu.levels; level++)
        {
            const view = l => gpu.texture.createView({ dimension: "2d", baseMipLevel: l, mipLevelCount: 1, baseArrayLayer: face, arrayLayerCount: 1 });
            this.blit_into(view(level - 1), view(level), false, true);
        }
    }
};

/**
 * Pixels into a texture's level and layer, in order with the draws: a
 * staging buffer copied in the encoder
 */
GLESExecutor.prototype.upload = function(texture, level, layer, x, y, width, height, rgba)
{
    this.end_pass();
    const stride = Math.ceil(width * 4 / 256) * 256;
    const staging = this.device.createBuffer({ label: "GLES upload", size: stride * height, usage: B.COPY_SRC, mappedAtCreation: true });
    const mapped = new Uint8Array(staging.getMappedRange());
    for(let row = 0; row < height; row++) mapped.set(rgba.subarray(row * width * 4, (row + 1) * width * 4), row * stride);
    staging.unmap();
    this.encoder.copyBufferToTexture({ buffer: staging, bytesPerRow: stride, rowsPerImage: height },
        { texture, mipLevel: level, origin: [x, y, layer] }, [width, height, 1]);
    this.staging.push(staging);
    this.stats.uploads++;
};

GLESExecutor.prototype.clear_texture = function(texture, rgba)
{
    this.end_pass();
    const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view: texture.createView(), loadOp: "clear",
        clearValue: { r: rgba[0], g: rgba[1], b: rgba[2], a: rgba[3] }, storeOp: "store" }] });
    pass.end();
};

// ---- buffers and renderbuffers

GLESExecutor.prototype.buffer_data = function(c, args, sub)
{
    const target = args[0];
    const name = target === GL.ARRAY_BUFFER ? c.array_buffer : c.element_array_buffer;
    const buffer = c.group.buffers.get(name);
    if(!buffer) return;
    if(!sub)
    {
        const [, size, data] = args;
        buffer.data = new Uint8Array(size);
        if(data) buffer.data.set(data.subarray(0, size));
        return;
    }
    const [, offset, size, data] = args;
    if(!buffer.data) buffer.data = new Uint8Array(buffer.size);
    if(data) buffer.data.set(data.subarray(0, size), offset);
};

GLESExecutor.prototype.renderbuffer_storage = function(c)
{
    const rb = c.group.renderbuffers.get(c.renderbuffer);
    if(!rb) return;
    if(rb.gpu) this.staging.push(rb.gpu);
    rb.gpu = null;
    if(!rb.width || !rb.height) return;
    const format = DEPTH_FORMATS[rb.format] || COLOR_FORMAT;
    const texture = this.device.createTexture({ label: "GL renderbuffer", size: [rb.width, rb.height], format,
        usage: U.RENDER_ATTACHMENT | U.COPY_SRC | U.COPY_DST | (format === COLOR_FORMAT ? U.TEXTURE_BINDING : 0) });
    rb.gpu = { texture, format, destroy: () => texture.destroy() };
};

// ---- what is drawn to

/**
 * The context's framebuffer as WebGPU attachments: color, depth-stencil,
 * size; null when there is nothing to draw to
 * @return {?{color: ?GPUTexture, color_view: ?GPUTextureView, depth: ?GPUTextureView, depth_format: string, width: number, height: number, key: string, alpha: boolean}}
 */
GLESExecutor.prototype.target_of = function(c)
{
    if(!c.framebuffer) return this.surface_target(c);
    const fbo = c.framebuffers.get(c.framebuffer);
    const view_of = a =>
    {
        if(!a) return null;
        if(a.type === GL.RENDERBUFFER)
        {
            const rb = c.group.renderbuffers.get(a.name);
            if(rb && rb.image) return this.image_texture(rb.image);
            return rb && rb.gpu ? { texture: rb.gpu.texture, format: rb.gpu.format, layer: 0, level: 0 } : null;
        }
        const texture = c.group.textures.get(a.name);
        const image = texture && texture.images.get(a.face * 32 + a.level);
        if(image && image.image) return this.image_texture(image.image);
        if(image && image.color_buffer) return this.color_buffer_texture(image.color_buffer);
        const gpu = texture && this.gpu_texture(texture);
        return gpu ? { texture: gpu.texture, format: COLOR_FORMAT, layer: a.face, level: a.level } : null;
    };
    const color = view_of(fbo.attachments.get(GL.COLOR_ATTACHMENT0));
    const depth = view_of(fbo.attachments.get(GL.DEPTH_ATTACHMENT)) || view_of(fbo.attachments.get(GL.STENCIL_ATTACHMENT));
    const any = color || depth;
    if(!any) return null;
    const view = t => t.texture.createView({ dimension: "2d", baseMipLevel: t.level, mipLevelCount: 1, baseArrayLayer: t.layer, arrayLayerCount: 1 });
    const width = Math.max(1, any.texture.width >> any.level), height = Math.max(1, any.texture.height >> any.level);
    return { color: color ? color.texture : null, color_view: color ? view(color) : null, depth: depth ? view(depth) : null,
        depth_format: depth ? depth.format : "", width, height, alpha: true,
        key: "f" + (color ? this.id_of(color.texture) + ":" + color.level + ":" + color.layer : "-") + "/" + (depth ? this.id_of(depth.texture) : "-") };
};

/** The context's window surface as a target_of's */
GLESExecutor.prototype.surface_target = function(c)
{
    const surface = c.surface && [...this.surfaces.values()].find(s => s.width === c.surface.width && s.height === c.surface.height &&
        CONFIGS[s.config] === c.surface.config && this.current_surface_of(c) === s);
    const s = surface || this.current_surface_of(c);
    if(!s) return null;
    this.surface_textures(s);
    return { color: s.texture, color_view: s.view, depth: s.depth_view, depth_format: s.depth_format, depth_texture: s.depth, width: s.width,
        height: s.height, key: "s" + s.id, alpha: CONFIGS[s.config][CONFIG_ATTRIBUTES.indexOf(EGL.ALPHA_SIZE)] > 0 };
};

/** A stable id of a GPU object (pass and bind group keys) */
GLESExecutor.prototype.id_of = function(object)
{
    this.ids = this.ids || new WeakMap();
    let id = this.ids.get(object);
    if(!id) this.ids.set(object, id = (this.next_id = (this.next_id || 0) + 1));
    return id;
};

/** The window surface a context draws to: the one its connection made current */
GLESExecutor.prototype.current_surface_of = function(c)
{
    for(const conn of this.conns.values())
    {
        if(this.shadow.context(conn.context) === c) return this.surfaces.get(conn.draw) || null;
    }
    return null;
};

/** A window surface's own color and depth textures (made at first use) */
GLESExecutor.prototype.surface_textures = function(s)
{
    if(s.texture) return;
    const config = CONFIGS[s.config];
    s.id = s.id || this.id_of(s);
    s.texture = this.device.createTexture({ label: "window surface", size: [s.width, s.height], format: COLOR_FORMAT, usage: TEXTURE_USAGE });
    s.view = s.texture.createView();
    const depth = config[CONFIG_ATTRIBUTES.indexOf(EGL.DEPTH_SIZE)], stencil = config[CONFIG_ATTRIBUTES.indexOf(EGL.STENCIL_SIZE)];
    s.depth_format = stencil ? "depth24plus-stencil8" : depth ? "depth24plus" : "";
    if(s.depth_format)
    {
        s.depth = this.device.createTexture({ label: "window depth", size: [s.width, s.height], format: s.depth_format, usage: U.RENDER_ATTACHMENT });
        s.depth_view = s.depth.createView();
    }
    // (no alpha bits: alpha reads 1)
    this.clear_texture(s.texture, [0, 0, 0, config[CONFIG_ATTRIBUTES.indexOf(EGL.ALPHA_SIZE)] ? 0 : 1]);
};

/** An EGL image's texture: its color buffer's */
GLESExecutor.prototype.image_texture = function(image)
{
    const object = this.rc.images.get(image);
    return object ? this.color_buffer_texture(object.buffer) : null;
};

GLESExecutor.prototype.color_buffer_texture = function(handle)
{
    const cb = this.rc.color_buffers.get(handle);
    return cb ? { texture: cb.texture, format: COLOR_FORMAT, layer: 0, level: 0 } : null;
};

/** The render pass on the context's target (the one open, if it is the same) */
GLESExecutor.prototype.begin_pass = function(target, clear)
{
    if(this.pass && this.pass_target === target.key && !clear) return this.pass;
    this.end_pass();
    const color = target.color_view ? [{ view: target.color_view, loadOp: clear && clear.color ? "clear" : "load", storeOp: "store",
        clearValue: clear && clear.color ? { r: clear.color[0], g: clear.color[1], b: clear.color[2], a: clear.color[3] } : undefined }] : [];
    const descriptor = { label: "GLES pass", colorAttachments: color };
    if(target.depth)
    {
        const has_depth = target.depth_format !== "stencil8", has_stencil = target.depth_format.includes("stencil");
        descriptor.depthStencilAttachment = Object.assign({ view: target.depth },
            has_depth ? { depthLoadOp: clear && clear.depth !== undefined ? "clear" : "load", depthStoreOp: "store", depthClearValue: clear ? clear.depth : 1 } : {},
            has_stencil ? { stencilLoadOp: clear && clear.stencil !== undefined ? "clear" : "load", stencilStoreOp: "store", stencilClearValue: clear ? clear.stencil : 0 } : {});
    }
    this.pass = this.encoder.beginRenderPass(descriptor);
    this.pass_target = target.key;
    return this.pass;
};

GLESExecutor.prototype.end_pass = function()
{
    if(!this.pass) return;
    this.pass.end();
    this.pass = null;
    this.pass_target = null;
};

// ---- clears

GLESExecutor.prototype.clear = function(c, mask)
{
    const target = this.target_of(c);
    if(!target) return;
    const scissor = c.enabled.has(0x0C11) && !(c.scissor[0] <= 0 && c.scissor[1] <= 0 && c.scissor[0] + c.scissor[2] >= target.width &&
        c.scissor[1] + c.scissor[3] >= target.height);
    const full_color = c.color_mask.every(Boolean) && (target.alpha || true);
    const want = { color: mask & 0x4000 && target.color_view, depth: mask & 0x0100 && target.depth && target.depth_format !== "stencil8",
        stencil: mask & 0x0400 && target.depth && target.depth_format.includes("stencil") };
    // (the whole target, all channels: the pass's clear)
    const simple = !scissor && (!want.color || full_color) && (!want.depth || c.depth_mask) && (!want.stencil || (c.stencil_writemask[0] & 0xFF) === 0xFF);
    if(simple)
    {
        const color = c.clear_color.slice();
        if(!target.alpha) color[3] = 1;
        this.begin_pass(target, { color: want.color ? color : null, depth: want.depth ? c.clear_depth : undefined, stencil: want.stencil ? c.clear_stencil & 0xFF : undefined });
        return;
    }
    this.clear_quad(c, target, want);
};

/** A clear that is a quad: the scissor and the masks apply */
GLESExecutor.prototype.clear_quad = function(c, target, want)
{
    const key = ["clear", target.color_view ? COLOR_FORMAT : "-", target.depth_format, want.color ? c.color_mask.join("") : "0000",
        want.depth ? 1 : 0, want.stencil ? c.stencil_writemask[0] & 0xFF : 0].join("|");
    let pipeline = this.pipelines.get(key);
    if(!pipeline)
    {
        const module = this.device.createShaderModule({ code: `
            @group(0) @binding(0) var<uniform> u : vec4<f32>;
            @group(0) @binding(1) var<uniform> d : vec4<f32>;
            @vertex fn vs(@builtin(vertex_index) i : u32) -> @builtin(position) vec4<f32> {
                let p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                return vec4<f32>(p[i], d.x, 1.0);
            }
            @fragment fn fs() -> @location(0) vec4<f32> { return u; }` });
        const descriptor = {
            label: "GLES clear", layout: "auto",
            vertex: { module, entryPoint: "vs" },
            fragment: { module, entryPoint: "fs", targets: target.color_view ? [{ format: COLOR_FORMAT,
                writeMask: want.color ? (c.color_mask[0] ? 1 : 0) | (c.color_mask[1] ? 2 : 0) | (c.color_mask[2] ? 4 : 0) | (c.color_mask[3] ? 8 : 0) : 0 }] : [] },
            primitive: { topology: "triangle-list" },
        };
        if(target.depth)
        {
            const stencil = target.depth_format.includes("stencil");
            descriptor.depthStencil = Object.assign({ format: target.depth_format },
                target.depth_format !== "stencil8" ? { depthWriteEnabled: !!want.depth, depthCompare: "always" } : {},
                stencil ? { stencilFront: { compare: "always", passOp: "replace" }, stencilBack: { compare: "always", passOp: "replace" },
                    stencilWriteMask: want.stencil ? c.stencil_writemask[0] & 0xFF : 0 } : {});
        }
        pipeline = this.device.createRenderPipeline(descriptor);
        this.pipelines.set(key, pipeline);
    }
    const pass = this.begin_pass(target, null);
    const uniforms = new Float32Array([...c.clear_color, c.clear_depth * 2 - 1, 0, 0, 0]);
    if(!target.alpha) uniforms[3] = 1;
    const buffer = this.device.createBuffer({ size: 256 + 16, usage: B.UNIFORM, mappedAtCreation: true });
    const mapped = new Float32Array(buffer.getMappedRange());
    mapped.set(uniforms.subarray(0, 4), 0);
    mapped.set(uniforms.subarray(4, 8), 64);
    buffer.unmap();
    this.staging.push(buffer);
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
        { binding: 0, resource: { buffer, offset: 0, size: 16 } }, { binding: 1, resource: { buffer, offset: 256, size: 16 } }] }));
    this.apply_scissor(pass, c, target);
    pass.setViewport(0, 0, target.width, target.height, 0, 1);
    if(want.stencil) pass.setStencilReference(c.clear_stencil & 0xFF);
    pass.draw(3);
};

GLESExecutor.prototype.apply_scissor = function(pass, c, target)
{
    let [x, y, w, h] = c.enabled.has(0x0C11) ? c.scissor : [0, 0, target.width, target.height];
    const x0 = Math.max(0, Math.min(target.width, x)), y0 = Math.max(0, Math.min(target.height, y));
    const x1 = Math.max(x0, Math.min(target.width, x + w)), y1 = Math.max(y0, Math.min(target.height, y + h));
    pass.setScissorRect(x0, y0, x1 - x0, y1 - y0);
    return x1 > x0 && y1 > y0;
};

// ---- draws

/**
 * A draw: vertices assembled on the CPU, the program's pipeline for the
 * state, its uniforms and textures
 * @param {?{type: number, bytes: (Uint8Array|undefined), offset: (number|undefined)}} elements
 */
GLESExecutor.prototype.draw = function(c, mode, first, count, elements)
{
    if(!count) return;
    const program = c.api === 1 ? null : c.group.objects.get(c.program);
    if(c.api !== 1 && (!program || !program.info || !program.info.ok)) return;
    if(c.enabled.has(0x0B44) && c.cull_face === 0x0408 && mode >= GL.TRIANGLES) return;
    const target = this.target_of(c);
    if(!target) return;
    // the indices (u32, from 0 for the vertices assembled) and the vertex range
    let indices = null, low = first, high = first + count - 1;
    if(elements)
    {
        const source = elements.bytes || (c.group.buffers.get(c.element_array_buffer) || {}).data;
        if(!source) return;
        const size = elements.type === GL.UNSIGNED_BYTE ? 1 : elements.type === GL.UNSIGNED_SHORT ? 2 : 4;
        const offset = elements.bytes ? 0 : elements.offset;
        if(offset + count * size > source.length) return;
        const view = new DataView(source.buffer, source.byteOffset + offset, count * size);
        indices = new Uint32Array(count);
        low = Infinity; high = 0;
        for(let i = 0; i < count; i++)
        {
            const v = size === 1 ? view.getUint8(i) : size === 2 ? view.getUint16(2 * i, true) : view.getUint32(4 * i, true);
            indices[i] = v;
            if(v < low) low = v;
            if(v > high) high = v;
        }
    }
    const vertices = high - low + 1;
    if(vertices <= 0 || vertices > 1 << 24) return;
    // (fans and loops as lists and strips; strips with indices keep u32, which never restarts)
    // (points: WebGPU's, one pixel each; gl_PointSize and glPointSize are not applied, gpu-deviations.md)
    let topology = { [GL.POINTS]: "point-list", [GL.LINES]: "line-list", [GL.LINE_STRIP]: "line-strip", [GL.LINE_LOOP]: "line-strip", [GL.TRIANGLES]: "triangle-list",
        [GL.TRIANGLE_STRIP]: "triangle-strip", [GL.TRIANGLE_FAN]: "triangle-list" }[mode];
    let list = indices ? Array.from(indices, v => v - low) : null;
    if(mode === GL.TRIANGLE_FAN || mode === GL.LINE_LOOP)
    {
        const order = list || Array.from({ length: count }, (_, i) => i);
        if(mode === GL.TRIANGLE_FAN)
        {
            list = [];
            for(let i = 1; i + 1 < order.length; i++) list.push(order[0], order[i], order[i + 1]);
        }
        else list = [...order, order[0]];
    }
    const index_count = list ? list.length : count;
    if(!index_count) return;
    // (GLES 1.1: the fixed function's shaders for the state; GLES 2.0: the program's)
    const ff = c.api === 1 ? this.ff_shaders(c, mode === GL.POINTS) : null;
    const shaders = ff ? ff.shaders : this.program_shaders(program);
    if(!shaders) return;
    const layout = ff ? this.ff_layout(c, ff.generated, low, vertices) : this.vertex_layout(c, program, low, vertices);
    if(!layout) return;
    const [vx, vy, vw, vh] = c.viewport;
    if(vw <= 0 || vh <= 0) return;
    let index_buffer = null;
    if(list)
    {
        const data = new Uint32Array(list);
        index_buffer = this.device.createBuffer({ size: align4(data.byteLength), usage: B.INDEX, mappedAtCreation: true });
        new Uint32Array(index_buffer.getMappedRange()).set(data);
        index_buffer.unmap();
        this.staging.push(index_buffer);
    }
    for(const face of this.stencil_faces(c, target, mode))
    {
        const pipeline = this.pipeline(c, program, shaders, layout, topology, target, !!list, face);
        if(!pipeline) return;
        const pass = this.begin_pass(target, null);
        pass.setPipeline(pipeline);
        const groups = ff ? this.ff_bind_groups(c, ff, pipeline, target, c.viewport) : this.bind_groups(c, program, shaders, pipeline, target);
        for(const [index, group] of groups) pass.setBindGroup(index, group);
        layout.buffers.forEach((buffer, slot) => pass.setVertexBuffer(slot, buffer));
        pass.setViewport(vx, vy, vw, vh, Math.min(c.depth_range[0], c.depth_range[1]), Math.max(c.depth_range[0], c.depth_range[1]));
        if(!this.apply_scissor(pass, c, target)) return;
        pass.setBlendConstant(c.blend_func.some(f => f === 0x8003 || f === 0x8004) ?
            { r: c.blend_color[3], g: c.blend_color[3], b: c.blend_color[3], a: c.blend_color[3] } :
            { r: c.blend_color[0], g: c.blend_color[1], b: c.blend_color[2], a: c.blend_color[3] });
        if(c.enabled.has(0x0B90)) pass.setStencilReference(c.stencil_func[face === undefined ? 0 : face][1] & 0xFF);
        if(index_buffer)
        {
            pass.setIndexBuffer(index_buffer, "uint32");
            pass.drawIndexed(index_count);
        }
        else pass.draw(count);
    }
    this.stats.draws++;
};

/**
 * The faces a draw is made of for the stencil test: WebGPU has one
 * reference and one pair of masks for both faces, GL each face its own;
 * when they differ, a draw of triangles goes twice, culled to each face,
 * with that face's (undefined: one draw, the front face's, as for points
 * and lines, which are front-facing)
 * @return {!Array<(number|undefined)>} 0 the front faces, 1 the back faces
 */
GLESExecutor.prototype.stencil_faces = function(c, target, mode)
{
    if(!c.enabled.has(0x0B90) || !target.depth || !target.depth_format.includes("stencil") || mode < GL.TRIANGLES) return [undefined];
    const same = c.stencil_func[0][1] === c.stencil_func[1][1] && c.stencil_func[0][2] === c.stencil_func[1][2] &&
        c.stencil_writemask[0] === c.stencil_writemask[1];
    if(same) return [undefined];
    // (culling leaves one face: its own state)
    if(c.enabled.has(0x0B44)) return c.cull_face === 0x0404 ? [1] : [0];
    return [0, 1];
};

/**
 * GLES 1.1: gl-webgpu's fixed-function shaders for the context's state (and
 * the draw_texture rectangle's: no lighting, fog or matrices), cached by
 * their signature
 */
GLESExecutor.prototype.ff_shaders = function(c, rectangle)
{
    const textures = Array.from({ length: UNITS }, (_, i) => unit_texture(c, i));
    const signature = ff_signature(c, false, textures);
    if(rectangle)
    {
        signature.lighting = { enabled: false, lights: [] };
        signature.fog = { enabled: false };
        signature.attributes.normal = false;
        signature.attributes.position = { components: 4 };
        signature.clipPlaneCount = 0;
        signature.texture.forEach(t => { if(t.enabled) t.matrix = false; });
    }
    const FF = globalThis["GLFixedFunction"];
    const key = FF.signatureKey(signature);
    this.ff_cache = this.ff_cache || new Map();
    let entry = this.ff_cache.get(key);
    if(!entry)
    {
        const generated = FF.generate(signature);
        const module = code =>
        {
            let m = this.shaders.get(code);
            if(!m) this.shaders.set(code, m = this.device.createShaderModule({ label: "GLES 1.1 fixed function", code }));
            return m;
        };
        const bindings = new Set();
        reachable_bindings(generated.wgslVertex, "vs_main", bindings);
        reachable_bindings(generated.wgslFragment, "fs_main", bindings);
        entry = { generated, shaders: { vertex: module(generated.wgslVertex), fragment: module(generated.wgslFragment), bindings } };
        this.ff_cache.set(key, entry);
    }
    return { generated: entry.generated, shaders: entry.shaders, textures };
};

/** A fixed-function draw's vertex buffers: each input from its client array or its current value */
GLESExecutor.prototype.ff_layout = function(c, generated, low, vertices)
{
    const buffers = [], formats = [];
    for(const input of ff_inputs(c, generated.attributes))
    {
        const a = input.array;
        let values;
        if(a.enabled) values = this.attribute_values(c, Object.assign({}, a, { normalized: input.normalized && a.type !== GL.FLOAT && a.type !== GL.FIXED }),
            low, vertices, input.components);
        else values = new Float32Array([...input.current, 0, 0, 0, 1].slice(0, input.components).map((v, i) => i < input.current.length ? v : i === 3 ? 1 : 0));
        if(!values) return null;
        const buffer = this.device.createBuffer({ size: align4(Math.max(4, values.byteLength)), usage: B.VERTEX, mappedAtCreation: true });
        new Float32Array(buffer.getMappedRange()).set(values);
        buffer.unmap();
        this.staging.push(buffer);
        buffers.push(buffer);
        formats.push({ location: input.location, components: input.components, stride: a.enabled ? input.components * 4 : 0 });
    }
    return { buffers, formats, key: "ff:" + formats.map(f => f.location + ":" + f.components + ":" + f.stride).join(",") };
};

/** A fixed-function draw's bind groups: the GL state block (group 1), the units' textures (group 2) */
GLESExecutor.prototype.ff_bind_groups = function(c, ff, pipeline, target, viewport, snapshot)
{
    const groups = [];
    const generated = ff.generated;
    if(ff.shaders.bindings.has("1:0"))
    {
        const layout = globalThis["GLStateLayout"].buildLayout(generated.stateFields);
        const floats = new Float32Array(Math.max(4, layout.floats));
        globalThis["GLStateLayout"].writeLayout(layout, snapshot || ff_snapshot(c, viewport), floats, 0);
        groups.push([1, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(1), entries: [{ binding: 0, resource: { buffer: this.uniform_buffer(floats.buffer) } }] })]);
    }
    const entries = [];
    for(const t of generated.textures)
    {
        const texture = ff.textures[t.unit];
        if(ff.shaders.bindings.has("2:" + t.textureBinding)) entries.push({ binding: t.textureBinding, resource: this.texture_view(texture, false, target.color) });
        if(ff.shaders.bindings.has("2:" + t.samplerBinding)) entries.push({ binding: t.samplerBinding, resource: this.sampler(texture) });
    }
    if(entries.length) groups.push([2, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(2), entries })]);
    return groups;
};

/**
 * glDrawTex*OES: a rectangle at window coordinates (x, y) of width by
 * height, at depth z (0 to 1, in the depth range), each enabled unit's
 * texture by its crop rectangle, the current color; no lighting, fog,
 * matrices or viewport
 */
GLESExecutor.prototype.draw_tex = function(c, [x, y, z, w, h])
{
    if(c.api !== 1 || !(w > 0) || !(h > 0)) return;
    const target = this.target_of(c);
    if(!target) return;
    const ff = this.ff_shaders(c, true);
    const W = target.width, H = target.height;
    const zw = c.depth_range[0] + Math.min(1, Math.max(0, z)) * (c.depth_range[1] - c.depth_range[0]);
    const ndc_z = zw * 2 - 1;
    const corners = [[x, y], [x + w, y], [x + w, y + h], [x, y], [x + w, y + h], [x, y + h]];
    const values = new Map();
    for(const a of ff.generated.attributes)
    {
        if(a.name === "position") values.set(a.location, corners.flatMap(([px, py]) => [px / W * 2 - 1, py / H * 2 - 1, ndc_z, 1]));
        else if(a.name === "color") values.set(a.location, corners.flatMap(() => c.ff.color));
        else if(a.name.startsWith("texCoord"))
        {
            const texture = ff.textures[+a.name.slice(8)];
            const base = texture && texture.images.get(0);
            const [u, v, cw, ch] = texture ? texture.crop : [0, 0, 1, 1];
            const tw = base ? base.width : 1, th = base ? base.height : 1;
            values.set(a.location, corners.flatMap(([px, py]) => [(u + (px - x) / w * cw) / tw, (v + (py - y) / h * ch) / th, 0, 1].slice(0, a.components)));
        }
        else values.set(a.location, corners.flatMap(() => new Array(a.components).fill(0)));
    }
    const buffers = [], formats = [];
    for(const a of ff.generated.attributes)
    {
        const data = new Float32Array(values.get(a.location));
        const buffer = this.device.createBuffer({ size: align4(data.byteLength), usage: B.VERTEX, mappedAtCreation: true });
        new Float32Array(buffer.getMappedRange()).set(data);
        buffer.unmap();
        this.staging.push(buffer);
        buffers.push(buffer);
        formats.push({ location: a.location, components: a.components, stride: a.components * 4 });
    }
    const layout = { buffers, formats, key: "tex:" + formats.map(f => f.location + ":" + f.components).join(",") };
    const pipeline = this.pipeline(c, null, ff.shaders, layout, "triangle-list", target, false);
    if(!pipeline) return;
    const pass = this.begin_pass(target, null);
    pass.setPipeline(pipeline);
    const snapshot = ff_snapshot(c, [0, 0, W, H]);
    const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
    Object.assign(snapshot.matrices, { modelview: identity, projection: identity, mvp: identity });
    snapshot.depthRange = { near: 0, far: 1 };
    for(const [index, group] of this.ff_bind_groups(c, ff, pipeline, target, [0, 0, W, H], snapshot)) pass.setBindGroup(index, group);
    buffers.forEach((buffer, slot) => pass.setVertexBuffer(slot, buffer));
    pass.setViewport(0, 0, W, H, 0, 1);
    if(!this.apply_scissor(pass, c, target)) return;
    if(c.enabled.has(0x0B90)) pass.setStencilReference(c.stencil_func[0][1] & 0xFF);
    pass.draw(6);
    this.stats.draws++;
};

/** The program's WGSL as shader modules (linked by the shadow state) */
GLESExecutor.prototype.program_shaders = function(program)
{
    const info = program.info;
    if(info.gpu) return info.gpu;
    if(!info.wgsl) return null;
    const module = code =>
    {
        let m = this.shaders.get(code);
        if(!m) this.shaders.set(code, m = this.device.createShaderModule({ label: "GLES program", code }));
        return m;
    };
    const bindings = new Set();
    reachable_bindings(info.wgsl.vertex, "vs_main", bindings);
    reachable_bindings(info.wgsl.fragment, "fs_main", bindings);
    info.gpu = { vertex: module(info.wgsl.vertex), fragment: module(info.wgsl.fragment), bindings };
    return info.gpu;
};

/**
 * The draw's vertex buffers: each active attribute's values for the vertex
 * range, from its array (client data or a buffer) or its current value,
 * as f32 (or the format WebGPU reads directly)
 * @return {?{buffers: !Array<!GPUBuffer>, formats: !Array<!Object>, key: string}}
 */
GLESExecutor.prototype.vertex_layout = function(c, program, low, vertices)
{
    const buffers = [], formats = [];
    for(const attribute of program.info.reflection.attributes)
    {
        for(let slot = 0; slot < attribute.slots; slot++)
        {
            const location = attribute.location + slot;
            const a = c.attribs[location];
            const components = attribute.slots > 1 ? attribute.components / attribute.slots : attribute.components;
            let values;
            if(a.enabled)
            {
                values = this.attribute_values(c, a, low, vertices, components);
                if(!values) return null;
            }
            else values = new Float32Array(a.current.slice(0, components));
            const buffer = this.device.createBuffer({ size: align4(Math.max(4, values.byteLength)), usage: B.VERTEX, mappedAtCreation: true });
            new Float32Array(buffer.getMappedRange()).set(values);
            buffer.unmap();
            this.staging.push(buffer);
            buffers.push(buffer);
            formats.push({ location, components, stride: a.enabled ? components * 4 : 0 });
        }
    }
    return { buffers, formats, key: formats.map(f => f.location + ":" + f.components + ":" + f.stride).join(",") };
};

/** An enabled attribute's values for the vertex range, as f32 (`components` each: missing ones 0, w 1) */
GLESExecutor.prototype.attribute_values = function(c, a, low, vertices, components)
{
    const type_bytes = TYPE_BYTES[a.type];
    const element = a.size * type_bytes;
    let source, base, stride;
    if(a.data)
    {
        // (client data: tight, element 0 the draw's first: low is 0 for those draws)
        source = a.data;
        stride = element;
        base = low * element;
    }
    else
    {
        const buffer = c.group.buffers.get(a.buffer);
        if(!buffer || !buffer.data) return null;
        source = buffer.data;
        stride = a.stride || element;
        base = a.offset + low * stride;
    }
    const out = new Float32Array(vertices * components);
    const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
    const normalized = a.normalized;
    for(let v = 0; v < vertices; v++)
    {
        const at = base + v * stride;
        for(let i = 0; i < components; i++)
        {
            let value = i === 3 ? 1 : 0;
            if(i < a.size && at + (i + 1) * type_bytes <= source.length)
            {
                const p = at + i * type_bytes;
                switch(a.type)
                {
                    case GL.FLOAT: value = view.getFloat32(p, true); break;
                    case GL.FIXED: value = view.getInt32(p, true) / 65536; break;
                    case GL.HALF_FLOAT_OES: value = half_to_float(view.getUint16(p, true)); break;
                    case GL.UNSIGNED_BYTE: value = view.getUint8(p); if(normalized) value /= 255; break;
                    case GL.BYTE: value = view.getInt8(p); if(normalized) value = Math.max(-1, value / 127); break;
                    case GL.UNSIGNED_SHORT: value = view.getUint16(p, true); if(normalized) value /= 65535; break;
                    case GL.SHORT: value = view.getInt16(p, true); if(normalized) value = Math.max(-1, value / 32767); break;
                }
            }
            out[v * components + i] = value;
        }
    }
    return out;
};

/** The pipeline for the program, the vertex layout, the state and the target */
GLESExecutor.prototype.pipeline = function(c, program, shaders, layout, topology, target, indexed, face)
{
    const blend = c.enabled.has(0x0BE2);
    const depth_test = c.enabled.has(0x0B71), stencil_test = c.enabled.has(0x0B90);
    // (one face's draw, stencil_faces: the other culled, that face's masks)
    const cull = face === 0 ? "back" : face === 1 ? "front" : c.enabled.has(0x0B44) ? (c.cull_face === 0x0404 ? "front" : "back") : "none";
    const masks = face === undefined ? 0 : face;
    const key = [this.id_of(shaders.vertex), this.id_of(shaders.fragment), layout.key, topology, indexed ? 1 : 0, c.front_face, cull, masks,
        target.color_view ? (target.alpha ? "a" : "x") : "-", target.depth_format,
        blend ? c.blend_func.join(",") + "/" + c.blend_equation.join(",") : "-", c.color_mask.join(""),
        depth_test ? c.depth_func + ":" + c.depth_mask : "-",
        stencil_test ? JSON.stringify([c.stencil_func, c.stencil_op, c.stencil_writemask]) : "-",
        c.enabled.has(0x8037) ? c.polygon_offset.join(",") : "-"].join("|");
    let pipeline = this.pipelines.get(key);
    if(pipeline) return pipeline;
    const write_mask = (c.color_mask[0] ? 1 : 0) | (c.color_mask[1] ? 2 : 0) | (c.color_mask[2] ? 4 : 0) | (c.color_mask[3] && target.alpha ? 8 : 0);
    const descriptor = {
        label: "GLES pipeline", layout: "auto",
        vertex: { module: shaders.vertex, entryPoint: "vs_main", buffers: layout.formats.map(f => ({
            arrayStride: f.stride, stepMode: "vertex",
            attributes: [{ shaderLocation: f.location, offset: 0, format: f.components === 1 ? "float32" : "float32x" + f.components }],
        })) },
        fragment: { module: shaders.fragment, entryPoint: "fs_main", targets: target.color_view ? [{ format: COLOR_FORMAT, writeMask: write_mask,
            blend: blend ? {
                color: blend_component(c.blend_equation[0], c.blend_func[0], c.blend_func[1]),
                alpha: blend_component(c.blend_equation[1], c.blend_func[2], c.blend_func[3]),
            } : undefined }] : [] },
        // (the translator's Y flip reverses the winding: GL's CCW is WebGPU's CW)
        primitive: { topology, frontFace: c.front_face === 0x0901 ? "cw" : "ccw", cullMode: cull,
            ...(indexed && topology.endsWith("strip") ? { stripIndexFormat: "uint32" } : {}) },
    };
    if(target.depth)
    {
        const stencil = target.depth_format.includes("stencil");
        const face_state = i => ({ compare: COMPARE[c.stencil_func[i][0]], failOp: STENCIL_OPS[c.stencil_op[i][0]],
            depthFailOp: STENCIL_OPS[c.stencil_op[i][1]], passOp: STENCIL_OPS[c.stencil_op[i][2]] });
        descriptor.depthStencil = Object.assign({ format: target.depth_format },
            target.depth_format !== "stencil8" ? { depthWriteEnabled: depth_test && !!c.depth_mask, depthCompare: depth_test ? COMPARE[c.depth_func] : "always" } : {},
            stencil && stencil_test ? { stencilFront: face_state(0), stencilBack: face_state(1), stencilReadMask: c.stencil_func[masks][2] & 0xFF,
                stencilWriteMask: c.stencil_writemask[masks] & 0xFF } : {},
            c.enabled.has(0x8037) && target.depth_format !== "stencil8" ? { depthBias: Math.round(c.polygon_offset[1]), depthBiasSlopeScale: c.polygon_offset[0] } : {});
    }
    try
    {
        pipeline = this.device.createRenderPipeline(descriptor);
    }
    catch(error)
    {
        if(this.stats.errors.length < 20) this.stats.errors.push("pipeline: " + error.message);
        return null;
    }
    this.stats.pipelines++;
    this.pipelines.set(key, pipeline);
    return pipeline;
};

/** The draw's bind groups: the GL state block and the uniforms (group 1), the textures (group 2) */
GLESExecutor.prototype.bind_groups = function(c, program, shaders, pipeline, target)
{
    const reflection = program.info.reflection;
    const groups = [];
    const active = shaders.bindings;
    const group1 = [];
    if(active.has("1:0"))
    {
        const layout = globalThis["GLStateLayout"].buildLayout(reflection.stateFields);
        const floats = new Float32Array(Math.max(4, layout.floats));
        globalThis["GLStateLayout"].writeLayout(layout, { depthRange: { near: c.depth_range[0], far: c.depth_range[1] },
            viewport: { x: c.viewport[0], y: c.viewport[1], width: c.viewport[2], height: c.viewport[3] },
            point: { size: 1, sizeMin: 1, sizeMax: 256, fadeThreshold: 1, attenuation: [1, 0, 0] } }, floats, 0);
        group1.push({ binding: 0, resource: { buffer: this.uniform_buffer(floats.buffer) } });
    }
    if(active.has("1:1"))
    {
        group1.push({ binding: 1, resource: { buffer: this.uniform_buffer(this.uniform_block(program)) } });
    }
    if(group1.length) groups.push([1, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(1), entries: group1 })]);
    const textures = [];
    for(const sampler of reflection.samplers)
    {
        const count = Math.max(1, sampler.arraySize);
        for(let i = 0; i < count; i++)
        {
            const values = program.values.get(sampler.location + i);
            const unit = Math.max(0, Math.min(31, values ? values[0] : 0));
            const slot = sampler.external ? 2 : sampler.dim === "Cube" ? 1 : 0;
            const name = c.textures[unit][slot];
            const texture = name ? c.group.textures.get(name) : null;
            // (a texture drawn to while it is sampled: GL's feedback loop is undefined, WebGPU refuses it; it samples as black)
            const view = this.texture_view(texture, sampler.dim === "Cube", target.color);
            if(active.has("2:" + (sampler.binding + i * 2))) textures.push({ binding: sampler.binding + i * 2, resource: view });
            if(active.has("2:" + (sampler.binding + i * 2 + 1))) textures.push({ binding: sampler.binding + i * 2 + 1, resource: this.sampler(texture) });
        }
    }
    if(textures.length) groups.push([2, this.device.createBindGroup({ layout: pipeline.getBindGroupLayout(2), entries: textures })]);
    return groups;
};

/** A uniform buffer holding the bytes */
GLESExecutor.prototype.uniform_buffer = function(bytes)
{
    const size = Math.max(16, align4(bytes.byteLength));
    const buffer = this.device.createBuffer({ size: Math.ceil(size / 16) * 16, usage: B.UNIFORM, mappedAtCreation: true });
    new Uint8Array(buffer.getMappedRange()).set(new Uint8Array(bytes));
    buffer.unmap();
    this.staging.push(buffer);
    return buffer;
};

/** The program's uniform block from the shadow's values (the reflection's offsets and strides) */
GLESExecutor.prototype.uniform_block = function(program)
{
    const reflection = program.info.reflection;
    const block = new ArrayBuffer(Math.max(16, reflection.uniformBlockBytes));
    const floats = new Float32Array(block), ints = new Int32Array(block);
    for(const u of reflection.uniforms)
    {
        const count = Math.max(1, u.arraySize);
        const stride = u.arraySize ? u.arrayStrideBytes : 0;
        for(let e = 0; e < count; e++)
        {
            const values = program.values.get(u.location + e);
            if(!values) continue;
            const base = u.offsetBytes + e * stride;
            if(u.kind === "matrix")
            {
                const column_stride = u.matrixColumnStrideBytes || (u.rows === 2 ? 8 : 16);
                for(let col = 0; col < u.columns; col++)
                {
                    for(let row = 0; row < u.rows; row++) floats[(base + col * column_stride) / 4 + row] = values[col * u.rows + row];
                }
                continue;
            }
            for(let i = 0; i < u.components; i++)
            {
                if(u.baseType === "float") floats[base / 4 + i] = values[i];
                else ints[base / 4 + i] = values[i];
            }
        }
    }
    return block;
};

/** A texture's view, or the fallback's (an incomplete texture samples as (0, 0, 0, 1)) */
GLESExecutor.prototype.texture_view = function(texture, cube, drawn_to)
{
    const fallback = () =>
    {
        if(!this.fallback)
        {
            this.fallback = this.device.createTexture({ size: [1, 1, 6], format: COLOR_FORMAT, usage: U.TEXTURE_BINDING | U.COPY_DST });
            this.device.queue.writeTexture({ texture: this.fallback }, new Uint8Array([0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255]),
                { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 6]);
            this.fallback_views = { "2d": this.fallback.createView({ dimension: "2d", arrayLayerCount: 1 }), cube: this.fallback.createView({ dimension: "cube" }) };
        }
        return this.fallback_views[cube ? "cube" : "2d"];
    };
    if(!texture) return fallback();
    const base = texture.images.get(0);
    // (an EGL image's or a bound color buffer's: that color buffer's texture)
    if(base && (base.image || base.color_buffer))
    {
        const t = base.image ? this.image_texture(base.image) : this.color_buffer_texture(base.color_buffer);
        return t && t.texture !== drawn_to ? t.texture.createView() : fallback();
    }
    const gpu = this.gpu_texture(texture);
    if(!gpu || gpu.texture === drawn_to) return fallback();
    // (cube complete: six square faces of one size and format at level 0)
    const first = [0, 1, 2, 3, 4, 5].map(face => texture.images.get(face * 32)).find(Boolean);
    if(gpu.cube && (gpu.width !== gpu.height || [0, 1, 2, 3, 4, 5].some(face =>
    {
        const i = texture.images.get(face * 32);
        return !i || i.width !== gpu.width || i.height !== gpu.height || i.format !== first.format;
    })))
    {
        return fallback();
    }
    // completeness: a mipmapped filter needs every level
    const mipmapped = texture.min_filter !== GL.NEAREST && texture.min_filter !== GL.LINEAR;
    let levels = 1;
    if(mipmapped)
    {
        for(levels = 1; levels < gpu.levels; levels++)
        {
            const w = Math.max(1, gpu.width >> levels), h = Math.max(1, gpu.height >> levels);
            for(let face = 0; face < (gpu.cube ? 6 : 1); face++)
            {
                const image = texture.images.get(face * 32 + levels);
                // (every level of the same format as level 0's)
                if(!image || image.width !== w || image.height !== h || image.format !== first.format) return fallback();
            }
        }
    }
    const key = (cube ? "cube" : "2d") + levels;
    let view = gpu.views.get(key);
    if(!view) gpu.views.set(key, view = gpu.texture.createView({ dimension: cube ? "cube" : "2d", mipLevelCount: levels,
        ...(cube ? {} : { arrayLayerCount: 1 }) }));
    return view;
};

GLESExecutor.prototype.sampler = function(texture)
{
    const t = texture || { min_filter: GL.NEAREST, mag_filter: GL.NEAREST, wrap_s: GL.CLAMP_TO_EDGE, wrap_t: GL.CLAMP_TO_EDGE };
    const key = [t.min_filter, t.mag_filter, t.wrap_s, t.wrap_t].join("|");
    let sampler = this.samplers.get(key);
    if(!sampler)
    {
        const min_linear = t.min_filter === GL.LINEAR || t.min_filter === GL.LINEAR_MIPMAP_NEAREST || t.min_filter === GL.LINEAR_MIPMAP_LINEAR;
        const mip_linear = t.min_filter === GL.NEAREST_MIPMAP_LINEAR || t.min_filter === GL.LINEAR_MIPMAP_LINEAR;
        const mipmapped = t.min_filter !== GL.NEAREST && t.min_filter !== GL.LINEAR;
        sampler = this.device.createSampler({
            addressModeU: WRAPS[t.wrap_s] || "repeat", addressModeV: WRAPS[t.wrap_t] || "repeat",
            magFilter: t.mag_filter === GL.LINEAR ? "linear" : "nearest", minFilter: min_linear ? "linear" : "nearest",
            mipmapFilter: mip_linear ? "linear" : "nearest", lodMaxClamp: mipmapped ? 32 : 0,
        });
        this.samplers.set(key, sampler);
    }
    return sampler;
};

Object.assign(GLESExecutor.prototype, GLES3);

// ---- surfaces, posts, reads

/** A window surface's frame into its color buffer (flipped: memory order) */
GLESExecutor.prototype.flush_surface = function(id)
{
    const s = this.surfaces.get(id);
    const cb = s && this.rc.color_buffers.get(s.color_buffer);
    if(!s || !cb || !s.texture)
    {
        this.stats.flush_skipped = this.stats.flush_skipped || {};
        const why = !s ? "no surface" : !cb ? "no color buffer " + s.color_buffer : "nothing drawn";
        this.stats.flush_skipped[why] = (this.stats.flush_skipped[why] || 0) + 1;
        return;
    }
    this.stats.flushes = (this.stats.flushes || 0) + 1;
    this.end_pass();
    this.blit_into(s.view, cb.texture.createView(), true, true);
};

/**
 * A full-size copy of one view into another, drawn (sizes may differ),
 * flipped vertically or not
 */
GLESExecutor.prototype.blit_into = function(source, target, flip, linear)
{
    if(!this.blit)
    {
        const module = this.device.createShaderModule({ code: `
            struct VOut { @builtin(position) p : vec4<f32>, @location(0) uv : vec2<f32> };
            @group(0) @binding(0) var t : texture_2d<f32>;
            @group(0) @binding(1) var s : sampler;
            @group(0) @binding(2) var<uniform> flip : vec4<f32>;
            @vertex fn vs(@builtin(vertex_index) i : u32) -> VOut {
                let p = array<vec2<f32>, 3>(vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0));
                var o : VOut;
                o.p = vec4<f32>(p[i], 0.0, 1.0);
                let uv = vec2<f32>(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
                o.uv = vec2<f32>(uv.x, select(uv.y, 1.0 - uv.y, flip.x > 0.5));
                return o;
            }
            @fragment fn fs(i : VOut) -> @location(0) vec4<f32> { return textureSampleLevel(t, s, i.uv, 0.0); }` });
        this.blit = { module, pipeline: this.device.createRenderPipeline({ label: "GLES blit", layout: "auto",
            vertex: { module, entryPoint: "vs" }, fragment: { module, entryPoint: "fs", targets: [{ format: COLOR_FORMAT }] },
            primitive: { topology: "triangle-list" } }),
            linear: this.device.createSampler({ magFilter: "linear", minFilter: "linear" }), nearest: this.device.createSampler({}) };
        this.blit.flip = [0, 1].map(f =>
        {
            const buffer = this.device.createBuffer({ size: 16, usage: B.UNIFORM, mappedAtCreation: true });
            new Float32Array(buffer.getMappedRange()).set([f, 0, 0, 0]);
            buffer.unmap();
            return buffer;
        });
    }
    this.end_pass();
    const pass = this.encoder.beginRenderPass({ colorAttachments: [{ view: target, loadOp: "clear", clearValue: { r: 0, g: 0, b: 0, a: 1 }, storeOp: "store" }] });
    pass.setPipeline(this.blit.pipeline);
    pass.setBindGroup(0, this.device.createBindGroup({ layout: this.blit.pipeline.getBindGroupLayout(0), entries: [
        { binding: 0, resource: source }, { binding: 1, resource: linear ? this.blit.linear : this.blit.nearest },
        { binding: 2, resource: { buffer: this.blit.flip[flip ? 1 : 0] } }] }));
    pass.draw(3);
    pass.end();
};

/** rcFBPost: the color buffer is the screen */
GLESExecutor.prototype.post = function(handle)
{
    const cb = this.rc.color_buffers.get(handle);
    if(!cb) return;
    this.stats.posts++;
    if(this.layer)
    {
        this.end_pass();
        const layer = this.layer;
        const configuration = layer.context.getConfiguration && layer.context.getConfiguration();
        if(!configuration || configuration.format !== COLOR_FORMAT) layer.context.configure({ device: this.device, format: COLOR_FORMAT });
        layer.canvas.width = cb.width;
        layer.canvas.height = cb.height;
        this.encoder.copyTextureToTexture({ texture: cb.texture }, { texture: layer.context.getCurrentTexture() }, [cb.width, cb.height, 1]);
        layer.place(0, 0, cb.width, cb.height, true);
        return;
    }
    // (read back: the newest post wins, one read at a time)
    if(this.post_pending)
    {
        this.post_next = handle;
        return;
    }
    this.post_pending = true;
    this.read_texture(cb.texture, 0, 0, cb.width, cb.height, false, (rgba, sink) =>
    {
        this.post_pending = false;
        if(sink.frame) sink.frame(rgba, cb.width, cb.height);
    });
};

/** glReadPixels: from what the connection's context reads (row 0 GL's bottom: the target's row 0) */
GLESExecutor.prototype.read_pixels = function(record)
{
    const conn = this.conns.get(record.conn);
    const c = conn && this.shadow.context(conn.context);
    if(c && c.glslang) return this.read_pixels3(c, record);
    const target = c && this.target_of(c);
    if(!target || !target.color) return this.answer_failed(record.request);
    const x0 = Math.max(0, record.x), y0 = Math.max(0, record.y);
    const x1 = Math.min(target.width, record.x + record.width), y1 = Math.min(target.height, record.y + record.height);
    const alignment = c.pack_alignment;
    if(x1 <= x0 || y1 <= y0) return this.answer(null, record.request, new Uint8Array(0), true);
    return this.read_texture(target.color, x0, y0, x1 - x0, y1 - y0, false, (rgba, sink) =>
    {
        // (the part outside the framebuffer is left as it was: zeros here)
        const full = new Uint8Array(record.width * record.height * 4);
        const w = x1 - x0;
        for(let y = 0; y < y1 - y0; y++)
        {
            full.set(rgba.subarray(y * w * 4, (y + 1) * w * 4), ((y + y0 - record.y) * record.width + (x0 - record.x)) * 4);
        }
        this.answer(sink, record.request, pack_rgba8(full, record.width, record.height, alignment));
    });
};

/** A rectangle of a texture copied for reading once the batch has run */
GLESExecutor.prototype.read_texture = function(texture, x, y, width, height, flip, done, mip = 0, layer = 0, texel = 4)
{
    this.end_pass();
    const stride = Math.ceil(width * texel / 256) * 256;
    const buffer = this.device.createBuffer({ size: stride * height, usage: B.COPY_DST | B.MAP_READ });
    this.encoder.copyTextureToBuffer({ texture, mipLevel: mip, origin: [x, y, layer] }, { buffer, bytesPerRow: stride, rowsPerImage: height }, [width, height, 1]);
    this.reads.push({ buffer, stride, width, height, flip, done, texel });
};

/** A read's answer: the readback header (id, length, 0, status OK), then the bytes */
GLESExecutor.prototype.answer = function(sink, request, bytes, later)
{
    const answer = new Uint8Array(READBACK_HEADER + bytes.length);
    const view = new DataView(answer.buffer);
    view.setUint32(0, request, true);
    view.setUint32(4, bytes.length, true);
    view.setUint32(12, 1, true);
    answer.set(bytes, READBACK_HEADER);
    if(later || !sink) this.reads.push({ buffer: null, done: (_, s) => s.writeResponse(0, answer), immediate: true });
    else sink.writeResponse(0, answer);
};

GLESExecutor.prototype.answer_failed = function(request)
{
    const answer = new Uint8Array(READBACK_HEADER);
    new DataView(answer.buffer).setUint32(0, request, true);
    new DataView(answer.buffer).setUint32(12, 2, true);
    this.reads.push({ buffer: null, done: (_, sink) => sink.writeResponse(0, answer), immediate: true });
};

// ---- snapshots (E5)

/** Every texture object of the shadow (the share groups' and the contexts' defaults) */
function all_textures(shadow)
{
    const textures = new Set();
    for(const group of shadow.groups.values()) for(const t of group.textures.values()) textures.add(t);
    for(const c of shadow.contexts.values()) for(const t of c.defaults ? c.defaults.values() : []) textures.add(t);
    return textures;
}

/**
 * The page's part of a snapshot (docs/gles-proxy-plan.md E5): the
 * executor's objects, and the GPU's contents read back into them (their
 * `saved`: [level, layer, width, height, RGBA]): the color buffers, the
 * window surfaces' own textures, the textures' levels, the color
 * renderbuffers; the buffers the GPU wrote (their bytes). A depth or
 * stencil buffer's contents are not kept (WebGPU cannot copy depth24plus
 * out); they read as cleared after a restore.
 * @return {!Promise<!Array<*>>} [json, buffers] (gles_snapshot.js)
 */
GLESExecutor.prototype.save = async function()
{
    const reads = [];
    const read = (owner, texture, levels, layers, width, height) =>
    {
        owner.saved = [];
        for(let level = 0; level < levels; level++)
        {
            for(let layer = 0; layer < layers; layer++)
            {
                reads.push({ owner, texture, level, layer, width: Math.max(1, width >> level), height: Math.max(1, height >> level) });
            }
        }
    };
    for(const cb of this.rc.color_buffers.values()) read(cb, cb.texture, 1, 1, cb.width, cb.height);
    for(const s of this.surfaces.values()) if(s.texture) read(s, s.texture, 1, 1, s.width, s.height);
    for(const t of all_textures(this.shadow))
    {
        // (GLES 3.x's textures, and GLES 2.0's through glslang: their own formats, layers and blocks, gles3_executor.js)
        if(t.gpu && t.gpu.es3) this.save_texture3(t, reads);
        else if(t.gpu && t.gpu.texture) read(t, t.gpu.texture, t.gpu.levels, t.gpu.cube ? 6 : 1, t.gpu.width, t.gpu.height);
    }
    for(const group of this.shadow.groups.values())
    {
        for(const rb of group.renderbuffers.values())
        {
            if(rb.gpu && rb.gpu.es3) this.save_renderbuffer3(rb, reads);
            else if(rb.gpu && rb.gpu.format === COLOR_FORMAT) read(rb, rb.gpu.texture, 1, 1, rb.width, rb.height);
        }
    }
    const encoder = this.device.createCommandEncoder({ label: "GLES save" });
    const buffer_reads = this.save_buffers3(encoder);
    for(const r of reads)
    {
        // (rows of texels, 4 bytes unless the read says: `row` bytes a row of blocks, `rows` of them)
        r.row = r.row || r.width * 4;
        r.rows = r.rows || r.height;
        r.stride = Math.ceil(r.row / 256) * 256;
        r.buffer = this.device.createBuffer({ size: r.stride * r.rows, usage: B.COPY_DST | B.MAP_READ });
        encoder.copyTextureToBuffer({ texture: r.texture, mipLevel: r.level, origin: [0, 0, r.layer] },
            { buffer: r.buffer, bytesPerRow: r.stride, rowsPerImage: r.rows }, r.extent || [r.width, r.height, 1]);
    }
    this.device.queue.submit([encoder.finish()]);
    for(const r of reads)
    {
        await r.buffer.mapAsync(globalThis.GPUMapMode ? globalThis.GPUMapMode.READ : 1);
        const mapped = new Uint8Array(r.buffer.getMappedRange());
        const rgba = new Uint8Array(r.row * r.rows);
        for(let y = 0; y < r.rows; y++) rgba.set(mapped.subarray(y * r.stride, y * r.stride + r.row), y * r.row);
        r.buffer.unmap();
        r.buffer.destroy();
        r.owner.saved.push([r.gl_level === undefined ? r.level : r.gl_level, r.layer, r.width, r.height, rgba]);
    }
    await this.saved_buffers3(buffer_reads);
    const state = { shadow: this.shadow.get_state(), rc: this.rc, conns: this.conns, surfaces: this.surfaces, posted: this.posted };
    // (the GPU's objects are left out: instances of no class the packing knows, and the textures' "gpu")
    const packed = pack(state, { classes: SHADOW_CLASSES, skip: shadow_skip });
    for(const r of reads)
    {
        delete r.owner.saved;
        delete r.owner.saved3;
    }
    return packed;
};

/**
 * A snapshot's page state on this executor (after a reset): the objects
 * back, their GPU textures made again with the contents saved
 * @param {!Array<*>} packed save's
 */
GLESExecutor.prototype.restore = function(packed)
{
    this.reset();
    const state = unpack(packed, SHADOW_CLASSES);
    this.rc.images = state.rc.images;
    this.rc.color_buffers = state.rc.color_buffers;
    this.shadow.set_state(state.shadow);
    this.conns = state.conns;
    this.surfaces = state.surfaces;
    this.posted = state.posted;
    this.encoder = this.device.createCommandEncoder({ label: "GLES restore" });
    this.staging = [];
    const put = (owner, texture) =>
    {
        for(const [level, layer, width, height, rgba] of owner.saved || []) this.upload(texture, level, layer, 0, 0, width, height, rgba);
        delete owner.saved;
    };
    for(const [handle, cb] of this.rc.color_buffers)
    {
        cb.texture = this.device.createTexture({ label: "color buffer " + handle, size: [cb.width, cb.height], format: COLOR_FORMAT, usage: TEXTURE_USAGE });
        if(cb.saved) put(cb, cb.texture);
        else if(cb.format === GL.RGB) this.clear_texture(cb.texture, [0, 0, 0, 1]);
    }
    for(const s of this.surfaces.values())
    {
        // (a surface drawn to before had its textures: made again, its picture back)
        if(!s.saved) continue;
        s.texture = null;
        this.surface_textures(s);
        put(s, s.texture);
    }
    for(const t of all_textures(this.shadow))
    {
        if(!t.saved) continue;
        t.gpu = null;
        if(t.saved3) this.restore_texture3(t);
        else
        {
            const gpu = this.gpu_texture(t);
            if(gpu) put(t, gpu.texture);
        }
        delete t.saved;
        delete t.saved3;
    }
    for(const group of this.shadow.groups.values())
    {
        for(const rb of group.renderbuffers.values())
        {
            rb.gpu = null;
            if(!rb.width || !rb.height || rb.image) continue;
            if(rb.saved3)
            {
                this.restore_renderbuffer3(rb);
                continue;
            }
            const format = DEPTH_FORMATS[rb.format] || COLOR_FORMAT;
            const texture = this.device.createTexture({ label: "GL renderbuffer", size: [rb.width, rb.height], format,
                usage: U.RENDER_ATTACHMENT | U.COPY_SRC | U.COPY_DST | (format === COLOR_FORMAT ? U.TEXTURE_BINDING : 0) });
            rb.gpu = { texture, format, destroy: () => texture.destroy() };
            put(rb, texture);
        }
    }
    this.device.queue.submit([this.encoder.finish()]);
    this.encoder = null;
    for(const object of this.staging) object.destroy();
    this.staging = [];
};
                                       source/v64/src/gles/page/gles_gpu_tables.js                                                         0000644 0000000 0000000 00000004350 00000000000 016020  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GL's state as WebGPU's, for the GLES executor's draws (gles_executor.js,
// GLES 2.0's and 1.1's; gles3_executor.js, GLES 3.x's)

export const U = globalThis.GPUTextureUsage || { COPY_SRC: 1, COPY_DST: 2, TEXTURE_BINDING: 4, STORAGE_BINDING: 8, RENDER_ATTACHMENT: 16 };
export const B = globalThis.GPUBufferUsage || { MAP_READ: 1, MAP_WRITE: 2, COPY_SRC: 4, COPY_DST: 8, INDEX: 16, VERTEX: 32, UNIFORM: 64,
    STORAGE: 128, INDIRECT: 256, QUERY_RESOLVE: 512 };
/** The format of color buffers, window surfaces and GLES 2.0's textures */
export const COLOR_FORMAT = "rgba8unorm";

export const BLEND_FACTORS = {
    0: "zero", 1: "one", 0x0300: "src", 0x0301: "one-minus-src", 0x0302: "src-alpha", 0x0303: "one-minus-src-alpha",
    0x0304: "dst-alpha", 0x0305: "one-minus-dst-alpha", 0x0306: "dst", 0x0307: "one-minus-dst", 0x0308: "src-alpha-saturated",
    0x8001: "constant", 0x8002: "one-minus-constant", 0x8003: "constant", 0x8004: "one-minus-constant",
};
/** (MIN and MAX: GLES 3.0's, EXT_blend_minmax's) */
export const BLEND_OPS = { 0x8006: "add", 0x800A: "subtract", 0x800B: "reverse-subtract", 0x8007: "min", 0x8008: "max" };
export const COMPARE = { 0x0200: "never", 0x0201: "less", 0x0202: "equal", 0x0203: "less-equal", 0x0204: "greater", 0x0205: "not-equal",
    0x0206: "greater-equal", 0x0207: "always" };
export const STENCIL_OPS = { 0: "zero", 0x1E00: "keep", 0x1E01: "replace", 0x1E02: "increment-clamp", 0x1E03: "decrement-clamp",
    0x150A: "invert", 0x8507: "increment-wrap", 0x8508: "decrement-wrap" };
/** (GLES 3.2's clamp to border: the edge's, the shader choosing the border color outside the image: vx_naga's border.rs) */
export const WRAPS = { 0x2901: "repeat", 0x812F: "clamp-to-edge", 0x8370: "mirror-repeat", 0x812D: "clamp-to-edge" };

/** @param {number} n @return {number} n rounded up to a multiple of 4 */
export const align4 = n => n + 3 & ~3;

/** A blend component's state (MIN and MAX take no factors: WebGPU's must be one) */
export function blend_component(equation, src, dst)
{
    const operation = BLEND_OPS[equation] || "add";
    if(operation === "min" || operation === "max") return { operation, srcFactor: "one", dstFactor: "one" };
    return { operation, srcFactor: BLEND_FACTORS[src], dstFactor: BLEND_FACTORS[dst] };
}
                                                                                                                                                                                                                                                                                        source/v64/src/gles/page/gles_textures.js                                                           0000644 0000000 0000000 00000015453 00000000000 015564  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GLES executor's texels (docs/gles-proxy-plan.md "执行器", E3): every
// color image is held as RGBA8 (WebGPU has no packed or luminance formats),
// so what the guest sends is expanded here: RGBA, RGB, LUMINANCE_ALPHA,
// LUMINANCE, ALPHA and BGRA_EXT bytes, the 4444, 5551 and 565 packings, and
// ETC1 blocks (OES_compressed_ETC1_RGB8_texture), decoded. Rows come padded
// to the unpack alignment; they leave tightly packed.

import { GL } from "../gles_formats.js";

/** @return {number} the bytes of one texel the guest sends */
function source_bytes(format, type)
{
    if(type !== GL.UNSIGNED_BYTE) return 2;
    switch(format)
    {
        case GL.RGBA: case GL.BGRA_EXT: return 4;
        case GL.RGB: return 3;
        case GL.LUMINANCE_ALPHA: return 2;
    }
    return 1;
}

/**
 * The guest's texels as RGBA8, rows tight
 * @param {number} format
 * @param {number} type
 * @param {number} width
 * @param {number} height
 * @param {number} alignment the unpack alignment
 * @param {?Uint8Array} bytes null: a defined image with no data (zeros)
 * @return {!Uint8Array}
 */
export function to_rgba8(format, type, width, height, alignment, bytes)
{
    const out = new Uint8Array(width * height * 4);
    if(!bytes) return out;
    const texel = source_bytes(format, type);
    const stride = Math.ceil(width * texel / alignment) * alignment;
    if(format === GL.RGBA && type === GL.UNSIGNED_BYTE && stride === width * 4)
    {
        out.set(bytes.subarray(0, Math.min(bytes.length, out.length)));
        return out;
    }
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    for(let y = 0; y < height; y++)
    {
        let src = y * stride, dst = y * width * 4;
        if(src + width * texel > bytes.length) break;
        for(let x = 0; x < width; x++, src += texel, dst += 4)
        {
            let r, g, b, a;
            if(type === GL.UNSIGNED_SHORT_4_4_4_4)
            {
                const p = view.getUint16(src, true);
                r = (p >> 12) * 17; g = (p >> 8 & 15) * 17; b = (p >> 4 & 15) * 17; a = (p & 15) * 17;
            }
            else if(type === GL.UNSIGNED_SHORT_5_5_5_1)
            {
                const p = view.getUint16(src, true);
                r = (p >> 11) * 255 / 31 + 0.5 | 0; g = (p >> 6 & 31) * 255 / 31 + 0.5 | 0; b = (p >> 1 & 31) * 255 / 31 + 0.5 | 0;
                a = p & 1 ? 255 : 0;
            }
            else if(type === GL.UNSIGNED_SHORT_5_6_5)
            {
                const p = view.getUint16(src, true);
                r = (p >> 11) * 255 / 31 + 0.5 | 0; g = (p >> 5 & 63) * 255 / 63 + 0.5 | 0; b = (p & 31) * 255 / 31 + 0.5 | 0; a = 255;
            }
            else switch(format)
            {
                case GL.RGBA: r = bytes[src]; g = bytes[src + 1]; b = bytes[src + 2]; a = bytes[src + 3]; break;
                case GL.BGRA_EXT: b = bytes[src]; g = bytes[src + 1]; r = bytes[src + 2]; a = bytes[src + 3]; break;
                case GL.RGB: r = bytes[src]; g = bytes[src + 1]; b = bytes[src + 2]; a = 255; break;
                case GL.LUMINANCE_ALPHA: r = g = b = bytes[src]; a = bytes[src + 1]; break;
                case GL.LUMINANCE: r = g = b = bytes[src]; a = 255; break;
                case GL.ALPHA: r = g = b = 0; a = bytes[src]; break;
                default: r = g = b = 0; a = 255;
            }
            out[dst] = r; out[dst + 1] = g; out[dst + 2] = b; out[dst + 3] = a;
        }
    }
    return out;
}

/** ETC1's modifier tables (the "intensity modifier" sets, OES_compressed_ETC1_RGB8_texture) */
const ETC1_MODIFIERS = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]];

/**
 * ETC1 blocks as RGBA8 (alpha 255), rows tight
 * @param {number} width
 * @param {number} height
 * @param {!Uint8Array} bytes 8 per 4 by 4 block, row by row of blocks
 * @return {!Uint8Array}
 */
export function decode_etc1(width, height, bytes)
{
    const out = new Uint8Array(width * height * 4);
    const blocks_x = Math.ceil(width / 4), blocks_y = Math.ceil(height / 4);
    const clamp = v => v < 0 ? 0 : v > 255 ? 255 : v;
    for(let by = 0; by < blocks_y; by++)
    {
        for(let bx = 0; bx < blocks_x; bx++)
        {
            const at = (by * blocks_x + bx) * 8;
            if(at + 8 > bytes.length) return out;
            const hi = (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
            const lo = (bytes[at + 4] << 24 | bytes[at + 5] << 16 | bytes[at + 6] << 8 | bytes[at + 7]) >>> 0;
            const diff = hi >>> 1 & 1, flip = hi & 1;
            const table = [hi >>> 5 & 7, hi >>> 2 & 7];
            let base;
            if(diff)
            {
                // (5-bit colors, the second a 3-bit signed difference from the first)
                const five = shift => hi >>> shift & 31;
                const delta = shift => { const d = hi >>> shift & 7; return d >= 4 ? d - 8 : d; };
                const expand5 = v => v << 3 | v >> 2;
                const c1 = [five(27), five(19), five(11)];
                const c2 = [c1[0] + delta(24), c1[1] + delta(16), c1[2] + delta(8)];
                base = [c1.map(expand5), c2.map(v => expand5(v & 31))];
            }
            else
            {
                const four = shift => (hi >>> shift & 15) * 17;
                base = [[four(28), four(20), four(12)], [four(24), four(16), four(8)]];
            }
            for(let i = 0; i < 16; i++)
            {
                // (pixel indices run down the columns)
                const x = i >> 2, y = i & 3;
                const sub = flip ? (y >= 2 ? 1 : 0) : (x >= 2 ? 1 : 0);
                const msb = lo >>> (i + 16) & 1, lsb = lo >>> i & 1;
                const modifier = ETC1_MODIFIERS[table[sub]][lsb];
                const delta = msb ? -modifier : modifier;
                const px = bx * 4 + x, py = by * 4 + y;
                if(px >= width || py >= height) continue;
                const o = (py * width + px) * 4;
                out[o] = clamp(base[sub][0] + delta);
                out[o + 1] = clamp(base[sub][1] + delta);
                out[o + 2] = clamp(base[sub][2] + delta);
                out[o + 3] = 255;
            }
        }
    }
    return out;
}

/**
 * RGBA8 pixels as the guest reads them in a format and type: GLES 2.0 reads
 * RGBA and UNSIGNED_BYTE only (the implementation's format is the same),
 * rows padded to the pack alignment
 * @param {!Uint8Array} rgba tight rows
 * @param {number} width
 * @param {number} height
 * @param {number} alignment
 * @return {!Uint8Array}
 */
export function pack_rgba8(rgba, width, height, alignment)
{
    const row = width * 4, stride = Math.ceil(row / alignment) * alignment;
    if(stride === row) return rgba;
    const out = new Uint8Array(stride * (height - 1) + row);
    for(let y = 0; y < height; y++) out.set(rgba.subarray(y * row, y * row + row), y * stride);
    return out;
}
                                                                                                                                                                                                                     source/v64/src/gles/plugin.js                                                                       0000644 0000000 0000000 00000004576 00000000000 013255  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // ranchu_gpu: "host" -- the GLES host (docs/gles-proxy-plan.md): the
// emulator's GLES protocol decoded on the machine's thread, its services
// handed to the ranchu machine's goldfish pipe ("opengles",
// "GLProcessPipe"). Built into build/v86-gles.js; from the source tree,
// src/device_plugin.js imports this file directly.
//
// The shadow state answers the guest; GLES batches go to the renderer
// channel (options "renderer": the page's, stream "gles"). The device's
// "summary" gives the counts (tests, the plan's review). Built by esbuild,
// not Closure: it brings gl-webgpu's GLSL front end (CommonJS scripts).

import { register_device_plugin } from "../device_machine.js";
import { GLESHost } from "./gles_host.js";
import { compile_glslang, create_glslang } from "./glslang.js";

register_device_plugin("V86GlesHosts", {
    "name": "gles",

    /**
     * Before the machine: glslang compiled and instantiated (asynchronous;
     * docs/gles3-plan.md)
     * @param {!Object} options "glslang": build/glslang.wasm's bytes
     * @return {!Promise<?Object>}
     */
    "prepare": async options => options["glslang"] ? create_glslang(await compile_glslang(options["glslang"])) : null,

    /**
     * @param {!Object} handle
     * @param {!Object} options "display": the screen's width, height and
     *     dpi; "renderer": the renderer channel, or null; "present": the
     *     screen's (RGBA, width, height), for frames read back
     */
    "create": (handle, options) =>
    {
        const display = options["display"];
        const host = new GLESHost({ width: display["width"], height: display["height"], dpi: display["dpi"] }, options["renderer"] || null,
            options["present"], { glslang: options["prepared"] || null, max_version: options["max_version"] || "2.0" });
        return {
            // (a service as src/virt/goldfish.js takes one; with a snapshot's state of it)
            "service": (name, wake, saved) => host.service(name, wake, saved),
            "summary": () => host.summary(),
            "reset": () => host.reset(),
            // (E5: the calls waiting for the page answered, the page's state fetched;
            // then the snapshot's slot, restored after the pipe's channels)
            "prepare_save": () => host.prepare_save(),
            "get_state": () => host.get_state(),
            "set_state": state => host.set_state(state),
        };
    },
});
                                                                                                                                  source/v64/src/gles/render_control.js                                                               0000644 0000000 0000000 00000044752 00000000000 014776  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // renderControl (opcodes 10000 on: docs/gles-proxy-plan.md, E1): the
// emulator's EGL on the host, as gfxstream's host/RenderControl.cpp and
// FrameBuffer answer the guest's libEGL_emulation and gralloc: the
// renderer's version and strings, the EGL configurations, contexts, window
// surfaces, color buffers (gralloc's buffers: created, opened and closed
// by reference, updated from the CPU, read back, bound as a texture or a
// renderbuffer, posted), client images, sync objects, the multi-display
// commands. Each object belongs to the process that made it (its puid,
// rcSetPuid; a connection without one owns its own): when the process's
// GLProcessPipe closes, what it made and its references go, as gfxstream's
// cleanupProcGLObjects.
//
// What the page needs to know of these comes out through `events` (an
// object made or gone, a frame flushed or posted, pixels written): the GLES
// host makes them GLES records (src/gles/gles_host.js). Reads back are the
// host's: here they give nothing.

import { CONFIGS, CONFIG_ATTRIBUTES, EGL, EGL_STRINGS, choose_configs, configs_for, gl_string } from "./gles_caps.js";

/** rcGetFBParam's parameters (gfxstream's host/FrameBuffer.h) */
const FB_WIDTH = 1;
const FB_HEIGHT = 2;
const FB_XDPI = 3;
const FB_YDPI = 4;
const FB_FPS = 5;
const FB_MIN_SWAP_INTERVAL = 6;
const FB_MAX_SWAP_INTERVAL = 7;
/** rcCreateContext's API (gfxstream's GLESApi): 1 GLES 1.1, 2 GLES 2.0, 3 and up GLES 3.x */
const GLES_API_CM = 1;
/** EGL_GL_TEXTURE_2D_KHR, EGL_NATIVE_BUFFER_ANDROID: rcCreateClientImage's targets */
const EGL_GL_TEXTURE_2D_KHR = 0x30B1;
const EGL_NATIVE_BUFFER_ANDROID = 0x3140;

/**
 * One connection's view: its process and what it made current
 * @typedef {{id: number, puid: ?number, context: number, draw: number, read: number}}
 */
export let RCConnection;

/**
 * @constructor
 * @param {{width: number, height: number, dpi: number}} display the screen (rcGetFBParam)
 */
export function RenderControl(display)
{
    this.display = display;
    /** @type {function(string, ...*)} what happened: "context_create", ... (gles_host.js) */
    this.events = () => {};
    this.reset();
}

RenderControl.prototype.reset = function()
{
    /** handles of every kind come from one counter, as gfxstream's genHandle */
    this.next_handle = 1;
    /** @type {!Map<number, {config: number, share: number, api: number, owner: string}>} */
    this.contexts = new Map();
    /** @type {!Map<number, {config: number, width: number, height: number, color_buffer: number, owner: string}>} */
    this.surfaces = new Map();
    /** @type {!Map<number, {width: number, height: number, format: number, refs: !Map<string, number>, updates: number}>} */
    this.color_buffers = new Map();
    /** @type {!Map<number, {context: number, target: number, buffer: number, owner: string}>} */
    this.images = new Map();
    /** @type {!Map<number, {owner: string}>} sync objects, by their 64-bit handle (below 2^53) */
    this.syncs = new Map();
    /** @type {!Map<number, {color_buffer: number, x: number, y: number, w: number, h: number, dpi: number}>} displays besides 0 */
    this.displays = new Map();
    /** @type {!Map<number, {size: number, owner: string}>} rcCreateBuffer's (Vulkan's; never used by a GLES guest) */
    this.buffers = new Map();
    this.posted = 0;
    this.posts = 0;
    this.swap_interval = 1;
    /** the bytes rcUpdateColorBuffer brought (E1: counted) */
    this.update_bytes = 0;
};

/** @param {!RCConnection} conn @return {string} the owner of what the connection makes */
function owner_of(conn)
{
    return conn.puid !== null ? "p" + conn.puid : "c" + conn.id;
}

RenderControl.prototype.handle = function()
{
    return this.next_handle++;
};

/**
 * The API of the connection's current context, for rcGetGLString (none: 2)
 * @param {!RCConnection} conn
 * @return {number}
 */
RenderControl.prototype.current_api = function(conn)
{
    const context = this.contexts.get(conn.context);
    return context ? context.api : 2;
};

/**
 * The configuration of the connection's draw surface (gles_defaults.js:
 * the GL_*_BITS queries)
 * @param {!RCConnection} conn
 * @return {?{width: number, height: number, config: !Array<number>}}
 */
RenderControl.prototype.draw_surface = function(conn)
{
    const surface = this.surfaces.get(conn.draw);
    if(!surface) return null;
    return { width: surface.width, height: surface.height, config: CONFIGS[surface.config] };
};

/**
 * A NUL-terminated string into an out buffer, as rcQueryEGLString answers:
 * its length with the NUL, or minus that when the buffer is too small
 * @param {string} text
 * @param {!Object} out an OutBuffer
 * @return {number}
 */
function string_reply(text, out)
{
    const bytes = new TextEncoder().encode(text + "\0");
    if(bytes.length > out.size) return -bytes.length;
    out.data.set(bytes);
    return bytes.length;
}

/** @param {!Object} out an OutBuffer @param {!Array<number>} values written as u32s while they fit */
function put_u32s(out, values)
{
    for(let i = 0; i < values.length && 4 * i + 4 <= out.size; i++) out.view.setUint32(4 * i, values[i] >>> 0, true);
}

/**
 * The commands, by name: (rc, conn, args) to the return value
 * @type {!Object<string, function(!RenderControl, !RCConnection, !Array<*>): *>}
 */
const HANDLERS = {
    "rcGetRendererVersion": () => 1,
    "rcGetEGLVersion": (rc, conn, [major, minor]) =>
    {
        put_u32s(major, [1]);
        put_u32s(minor, [4]);
        return EGL.TRUE;
    },
    "rcQueryEGLString": (rc, conn, [name, buffer]) =>
    {
        const text = EGL_STRINGS.get(name);
        return text === undefined ? 0 : string_reply(text, buffer);
    },
    "rcGetGLString": (rc, conn, [name, buffer]) => string_reply(gl_string(name, rc.current_api(conn), rc.max_version), buffer),
    "rcGetNumConfigs": (rc, conn, [num_attribs]) =>
    {
        put_u32s(num_attribs, [CONFIG_ATTRIBUTES.length]);
        return CONFIGS.length;
    },
    // (the attributes' ids, then each configuration's values)
    "rcGetConfigs": (rc, conn, [size, buffer]) =>
    {
        const needed = (CONFIGS.length + 1) * CONFIG_ATTRIBUTES.length * 4;
        if(buffer.size < needed) return -needed;
        put_u32s(buffer, [...CONFIG_ATTRIBUTES, ...configs_for(rc.max_version).flat()]);
        return CONFIGS.length;
    },
    "rcChooseConfig": (rc, conn, [attribs, attribs_size, configs, configs_size]) =>
    {
        const view = attribs && new DataView(attribs.buffer, attribs.byteOffset, attribs.byteLength);
        const list = [];
        for(let at = 0; view && at + 4 <= view.byteLength; at += 4) list.push(view.getInt32(at, true));
        const chosen = choose_configs(list, configs_for(rc.max_version));
        // (with room for some, as many as fit; without, how many there are)
        if(configs && configs_size > 0)
        {
            const n = Math.min(chosen.length, configs_size);
            put_u32s(configs, chosen.slice(0, n));
            return n;
        }
        return chosen.length;
    },
    "rcGetFBParam": (rc, conn, [param]) =>
    {
        switch(param)
        {
            case FB_WIDTH: return rc.display.width;
            case FB_HEIGHT: return rc.display.height;
            case FB_XDPI: case FB_YDPI: return rc.display.dpi;
            case FB_FPS: return 60;
            case FB_MIN_SWAP_INTERVAL: case FB_MAX_SWAP_INTERVAL: return 1;
        }
        return -1;
    },
    "rcCreateContext": (rc, conn, [config, share, api]) =>
    {
        // (the guest asks 3 for GLES 3.0, 4 for 3.1 and 3.2: such a context is
        // the highest version announced, which EGL allows; its "api" is that
        // version, 30 to 32, past GLES 1.1's 1 and 2.0's 2)
        if(!CONFIGS[config] || share && !rc.contexts.has(share) || api < GLES_API_CM || api > (rc.max_version >= 30 ? 4 : 2)) return 0;
        const level = api >= 3 ? rc.max_version : api;
        const handle = rc.handle();
        const group = share ? rc.contexts.get(share).share || share : 0;
        rc.contexts.set(handle, { config, share: group, api: level, owner: owner_of(conn) });
        rc.events("context_create", handle, config, group, level);
        return handle;
    },
    "rcDestroyContext": (rc, conn, [context]) => { if(rc.contexts.delete(context)) rc.events("context_destroy", context); },
    "rcCreateWindowSurface": (rc, conn, [config, width, height]) =>
    {
        if(!CONFIGS[config]) return 0;
        const handle = rc.handle();
        rc.surfaces.set(handle, { config, width, height, color_buffer: 0, owner: owner_of(conn) });
        rc.events("surface_create", handle, config, width, height);
        return handle;
    },
    "rcDestroyWindowSurface": (rc, conn, [surface]) => { if(rc.surfaces.delete(surface)) rc.events("surface_destroy", surface); },
    "rcCreateColorBuffer": (rc, conn, [width, height, format]) => rc.create_color_buffer(conn, width, height, format, 0),
    "rcCreateColorBufferDMA": (rc, conn, [width, height, format]) => rc.create_color_buffer(conn, width, height, format, 0),
    "rcCreateColorBufferWithHandle": (rc, conn, [width, height, format, handle]) => { rc.create_color_buffer(conn, width, height, format, handle); },
    "rcOpenColorBuffer": (rc, conn, [color_buffer]) => { rc.open_color_buffer(conn, color_buffer); },
    "rcOpenColorBuffer2": (rc, conn, [color_buffer]) => rc.open_color_buffer(conn, color_buffer),
    "rcCloseColorBuffer": (rc, conn, [color_buffer]) => { rc.close_color_buffer(owner_of(conn), color_buffer); },
    "rcSetWindowColorBuffer": (rc, conn, [surface, color_buffer]) =>
    {
        const s = rc.surfaces.get(surface);
        if(!s || !rc.color_buffers.has(color_buffer)) return;
        s.color_buffer = color_buffer;
        rc.events("surface_color_buffer", surface, color_buffer);
    },
    "rcFlushWindowColorBuffer": (rc, conn, [surface]) => rc.flush_surface(surface) ? 0 : -1,
    "rcFlushWindowColorBufferAsync": (rc, conn, [surface]) => { rc.flush_surface(surface); },
    "rcFlushWindowColorBufferAsyncWithFrameNumber": (rc, conn, [surface]) => { rc.flush_surface(surface); },
    "rcMakeCurrent": (rc, conn, [context, draw, read]) => rc.make_current(conn, context, draw, read),
    "rcMakeCurrentAsync": (rc, conn, [context, draw, read]) => { rc.make_current(conn, context, draw, read); },
    "rcFBPost": (rc, conn, [color_buffer]) =>
    {
        if(!rc.color_buffers.has(color_buffer)) return;
        rc.posted = color_buffer;
        rc.posts++;
        rc.events("post", color_buffer);
    },
    "rcFBSetSwapInterval": (rc, conn, [interval]) => { rc.swap_interval = interval; },
    "rcBindTexture": (rc, conn, [color_buffer]) => { if(rc.color_buffers.has(color_buffer)) rc.events("bind", conn, color_buffer, true); },
    "rcBindRenderbuffer": (rc, conn, [color_buffer]) => { if(rc.color_buffers.has(color_buffer)) rc.events("bind", conn, color_buffer, false); },
    "rcColorBufferCacheFlush": () => 0,
    // (E1: nothing drawn, zeros read back)
    "rcReadColorBuffer": () => {},
    "rcReadColorBufferYUV": () => {},
    "rcReadColorBufferDMA": () => -1,
    "rcUpdateColorBuffer": (rc, conn, [color_buffer, x, y, width, height, format, type, pixels]) =>
    {
        const cb = rc.color_buffers.get(color_buffer);
        if(!cb) return -1;
        cb.updates++;
        rc.update_bytes += pixels.length;
        rc.events("color_buffer_update", color_buffer, x, y, width, height, format, type, pixels);
        return 0;
    },
    "rcUpdateColorBufferDMA": () => -1,
    "rcCreateClientImage": (rc, conn, [context, target, buffer]) =>
    {
        // (a texture of a context; or a gralloc buffer, by its color buffer)
        if(target === EGL_NATIVE_BUFFER_ANDROID ? !rc.color_buffers.has(buffer) : target !== EGL_GL_TEXTURE_2D_KHR || !rc.contexts.has(context)) return 0;
        const handle = rc.handle();
        rc.images.set(handle, { context, target, buffer, owner: owner_of(conn) });
        rc.events("image_create", handle, context, target, buffer);
        return handle;
    },
    "rcDestroyClientImage": (rc, conn, [image]) =>
    {
        if(!rc.images.delete(image)) return 0;
        rc.events("image_destroy", image);
        return 1;
    },
    "rcSelectChecksumHelper": () => {},
    // (fences signal when the commands before them ran: in the order of
    // the channel, so at once here; docs/gles-proxy-plan.md "影子状态")
    "rcCreateSyncKHR": (rc, conn, [type, attribs, num_attribs, destroy_when_signaled, glsync_out, syncthread_out]) =>
    {
        const handle = rc.handle();
        if(!destroy_when_signaled) rc.syncs.set(handle, { owner: owner_of(conn) });
        put_u32s(glsync_out, [handle, 0]);
        put_u32s(syncthread_out, [0, 0]);
    },
    "rcClientWaitSyncKHR": () => EGL.CONDITION_SATISFIED_KHR,
    "rcWaitSyncKHR": () => {},
    "rcDestroySyncKHR": (rc, conn, [sync]) => { rc.syncs.delete(sync); return 0; },
    "rcDestroySyncKHRAsync": (rc, conn, [sync]) => { rc.syncs.delete(sync); },
    "rcIsSyncSignaled": () => 1,
    "rcSetPuid": (rc, conn, [puid]) =>
    {
        // (all ones, as the wire's u64 reads: virtio-gpu's, whose context is the process; not this transport's)
        if(puid !== 0xFFFFFFFF * 0x100000000 + 0xFFFFFFFF) conn.puid = puid;
    },
    // (hardware composer 2 and multi-display: an API 25 guest sends none of
    // them; answered as a host without them)
    "rcCompose": () => -1,
    "rcComposeWithoutPost": () => -1,
    "rcComposeAsync": () => {},
    "rcComposeAsyncWithoutPost": () => {},
    "rcCreateDisplay": () => -1,
    "rcCreateDisplayById": () => -1,
    "rcDestroyDisplay": () => -1,
    "rcSetDisplayColorBuffer": () => -1,
    "rcGetDisplayColorBuffer": () => -1,
    "rcGetColorBufferDisplay": () => -1,
    "rcGetDisplayPose": () => -1,
    "rcSetDisplayPose": () => -1,
    "rcSetDisplayPoseDpi": () => -1,
    "rcGetDisplayColorTransform": () => -1,
    "rcSetDisplayColorTransform": () => -1,
    "rcGetFBDisplayConfigsCount": () => 1,
    "rcGetFBDisplayConfigsParam": (rc, conn, [config, param]) => config === 0 ? HANDLERS["rcGetFBParam"](rc, conn, [param]) : -1,
    "rcGetFBDisplayActiveConfig": () => 0,
    // (Vulkan's: no Vulkan on this host)
    "rcSetColorBufferVulkanMode": () => -1,
    "rcSetColorBufferVulkanMode2": () => -1,
    "rcCreateBuffer": () => 0,
    "rcCreateBuffer2": () => 0,
    "rcCloseBuffer": () => {},
    "rcMapGpaToBufferHandle": () => -1,
    "rcMapGpaToBufferHandle2": () => -1,
    "rcSetTracingForPuid": () => {},
    "rcSetProcessMetadata": () => {},
    "rcGetHostExtensionsString": (rc, conn, [size, buffer]) => string_reply("", buffer),
};

/**
 * @param {!RCConnection} conn
 * @param {!Object} command (gles_wire.js)
 * @param {!Array<*>} args
 * @return {*} the return value
 */
RenderControl.prototype.call = function(conn, command, args)
{
    const handler = HANDLERS[command.name];
    return handler ? handler(this, conn, args) : 0;
};

/** @param {string} name @return {boolean} whether renderControl knows the command */
export function rc_handles(name)
{
    return Object.prototype.hasOwnProperty.call(HANDLERS, name);
}

/**
 * @param {!RCConnection} conn
 * @param {number} width
 * @param {number} height
 * @param {number} format
 * @param {number} handle the guest's (0: one of the host's)
 * @return {number}
 */
RenderControl.prototype.create_color_buffer = function(conn, width, height, format, handle)
{
    if(!width || !height || width > 0x4000 || height > 0x4000) return 0;
    handle = handle || this.handle();
    this.color_buffers.set(handle, { width, height, format, refs: new Map([[owner_of(conn), 1]]), updates: 0 });
    this.events("color_buffer_create", handle, width, height, format);
    return handle;
};

/** @param {!RCConnection} conn @param {number} handle @return {number} 0, or -1 for no such color buffer */
RenderControl.prototype.open_color_buffer = function(conn, handle)
{
    const cb = this.color_buffers.get(handle);
    if(!cb) return -1;
    const owner = owner_of(conn);
    cb.refs.set(owner, (cb.refs.get(owner) || 0) + 1);
    return 0;
};

/** @param {string} owner @param {number} handle */
RenderControl.prototype.close_color_buffer = function(owner, handle)
{
    const cb = this.color_buffers.get(handle);
    if(!cb) return;
    // (a reference of another process: gralloc frees a buffer it imported)
    const from = cb.refs.has(owner) ? owner : cb.refs.keys().next().value;
    const count = cb.refs.get(from) - 1;
    if(count > 0) cb.refs.set(from, count);
    else cb.refs.delete(from);
    if(!cb.refs.size)
    {
        this.color_buffers.delete(handle);
        this.events("color_buffer_destroy", handle);
    }
};

/** @param {number} surface @return {boolean} whether there is one: what was drawn to it goes to its color buffer */
RenderControl.prototype.flush_surface = function(surface)
{
    if(!this.surfaces.has(surface)) return false;
    this.events("flush_surface", surface);
    return true;
};

/** @return {number} EGL_TRUE or EGL_FALSE */
RenderControl.prototype.make_current = function(conn, context, draw, read)
{
    // (no context: no surfaces; a context: surfaces that exist, or none, EGL_KHR_surfaceless_context's)
    const known = surface => !surface || this.surfaces.has(surface);
    if(context ? !this.contexts.has(context) || !known(draw) || !known(read) : draw || read) return EGL.FALSE;
    conn.context = context;
    conn.draw = draw;
    conn.read = read;
    this.events("make_current", conn, context, draw, read);
    return EGL.TRUE;
};

/**
 * A connection or a process went: what it owned goes
 * @param {string} owner "p" + puid, or "c" + a connection's id
 */
RenderControl.prototype.release = function(owner)
{
    for(const [map, gone] of [[this.images, "image_destroy"], [this.surfaces, "surface_destroy"], [this.contexts, "context_destroy"], [this.syncs, ""]])
    {
        map.forEach((object, handle) =>
        {
            if(object.owner !== owner) return;
            map.delete(handle);
            if(gone) this.events(gone, handle);
        });
    }
    this.color_buffers.forEach((cb, handle) =>
    {
        cb.refs.delete(owner);
        if(cb.refs.size) return;
        this.color_buffers.delete(handle);
        this.events("color_buffer_destroy", handle);
    });
};

/** @param {!RCConnection} conn the connection closed */
RenderControl.prototype.disconnect = function(conn)
{
    // (a process's objects stay until its GLProcessPipe closes)
    if(conn.puid === null) this.release(owner_of(conn));
};

/** @return {!Object} the counts for reports */
RenderControl.prototype.summary = function()
{
    return {
        contexts: this.contexts.size, surfaces: this.surfaces.size, color_buffers: this.color_buffers.size,
        images: this.images.size, syncs: this.syncs.size, posts: this.posts, posted: this.posted, update_bytes: this.update_bytes,
    };
};
                      source/v64/src/gles/spirv_patch.js                                                                  0000644 0000000 0000000 00000033111 00000000000 014264  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SPIR-V as glslang's code pass writes it, read and changed in place
// (docs/gles3-plan.md, "着色器的数据流"): the module's names, types,
// variables and decorations, and the decorations the host decides itself:
// the locations of the interface (by GL's rules and names, across stages)
// and the bindings of the resources, which glslang maps per stage.

export const OP = {
    Name: 5, MemberName: 6, EntryPoint: 15, ExecutionMode: 16, TypeBool: 20, TypeInt: 21, TypeFloat: 22, TypeVector: 23,
    TypeMatrix: 24, TypeImage: 25, TypeSampler: 26, TypeSampledImage: 27, TypeArray: 28, TypeRuntimeArray: 29,
    TypeStruct: 30, TypePointer: 32, Constant: 43, Variable: 59, Decorate: 71, MemberDecorate: 72,
};
export const DECORATION = { Block: 2, BufferBlock: 3, RowMajor: 4, ColMajor: 5, ArrayStride: 6, MatrixStride: 7,
    BuiltIn: 11, Flat: 14, Location: 30, Component: 31, Index: 32, Binding: 33, DescriptorSet: 34, Offset: 35,
    XfbBuffer: 36, XfbStride: 37 };
export const STORAGE = { UniformConstant: 0, Input: 1, Uniform: 2, Output: 3, Workgroup: 4, Private: 6, Function: 7,
    PushConstant: 9, Image: 11, StorageBuffer: 12 };
export const EXECUTION_MODEL = { Vertex: 0, TessellationControl: 1, TessellationEvaluation: 2, Geometry: 3, Fragment: 4, GLCompute: 5 };

/** @param {!Uint32Array} words @param {number} at a literal string's first word @return {string} */
function string_at(words, at)
{
    const bytes = [];
    for(let i = at; i < words.length; i++)
    {
        for(let b = 0; b < 4; b++)
        {
            const c = words[i] >>> 8 * b & 0xFF;
            if(!c) return new TextDecoder().decode(new Uint8Array(bytes));
            bytes.push(c);
        }
    }
    return new TextDecoder().decode(new Uint8Array(bytes));
}

/**
 * A module's parts the host reads
 * @param {!Uint32Array} words
 * @return {!Object} {names, member_names, types, constants, variables, decorations, member_decorations, entry}
 */
export function parse_spirv(words)
{
    const m = {
        /** @type {!Map<number, string>} */ names: new Map(),
        /** @type {!Map<number, !Array<string>>} */ member_names: new Map(),
        /** @type {!Map<number, !Object>} */ types: new Map(),
        /** @type {!Map<number, number>} */ constants: new Map(),
        /** @type {!Array<{id: number, type: number, storage: number}>} */ variables: [],
        /** id -> decoration -> the word index of its first operand (-1: none) */
        /** @type {!Map<number, !Map<number, number>>} */ decorations: new Map(),
        /** @type {!Map<number, !Map<number, !Map<number, number>>>} */ member_decorations: new Map(),
        entry: null,
    };
    for(let at = 5; at < words.length;)
    {
        const count = words[at] >>> 16, op = words[at] & 0xFFFF;
        if(!count) break;
        const w = i => words[at + i];
        switch(op)
        {
            case OP.Name: m.names.set(w(1), string_at(words, at + 2)); break;
            case OP.MemberName:
            {
                if(!m.member_names.has(w(1))) m.member_names.set(w(1), []);
                m.member_names.get(w(1))[w(2)] = string_at(words, at + 3);
                break;
            }
            case OP.EntryPoint: m.entry = { model: w(1), id: w(2) }; break;
            case OP.TypeBool: m.types.set(w(1), { kind: "bool" }); break;
            case OP.TypeInt: m.types.set(w(1), { kind: "int", width: w(2), signed: !!w(3) }); break;
            case OP.TypeFloat: m.types.set(w(1), { kind: "float", width: w(2) }); break;
            case OP.TypeVector: m.types.set(w(1), { kind: "vector", component: w(2), size: w(3) }); break;
            case OP.TypeMatrix: m.types.set(w(1), { kind: "matrix", column: w(2), columns: w(3) }); break;
            case OP.TypeImage: m.types.set(w(1), { kind: "image", sampled_type: w(2), dim: w(3), depth: w(4), arrayed: w(5), ms: w(6), sampled: w(7), format: w(8) }); break;
            case OP.TypeSampler: m.types.set(w(1), { kind: "sampler" }); break;
            case OP.TypeSampledImage: m.types.set(w(1), { kind: "sampled_image", image: w(2) }); break;
            case OP.TypeArray: m.types.set(w(1), { kind: "array", element: w(2), length_id: w(3) }); break;
            case OP.TypeRuntimeArray: m.types.set(w(1), { kind: "runtime_array", element: w(2) }); break;
            case OP.TypeStruct: m.types.set(w(1), { kind: "struct", members: Array.from(words.subarray(at + 2, at + count)) }); break;
            case OP.TypePointer: m.types.set(w(1), { kind: "pointer", storage: w(2), pointee: w(3) }); break;
            case OP.Constant: m.constants.set(w(2), w(3)); break;
            case OP.Variable: if(w(3) !== STORAGE.Function) m.variables.push({ id: w(2), type: w(1), storage: w(3) }); break;
            case OP.Decorate:
            {
                if(!m.decorations.has(w(1))) m.decorations.set(w(1), new Map());
                m.decorations.get(w(1)).set(w(2), count > 3 ? at + 3 : -1);
                break;
            }
            case OP.MemberDecorate:
            {
                if(!m.member_decorations.has(w(1))) m.member_decorations.set(w(1), new Map());
                const members = m.member_decorations.get(w(1));
                if(!members.has(w(2))) members.set(w(2), new Map());
                members.get(w(2)).set(w(3), count > 4 ? at + 4 : -1);
                break;
            }
        }
        at += count;
    }
    return m;
}

/** @return {!Object} the type a variable points to */
export function variable_type(m, v)
{
    return m.types.get(m.types.get(v.type).pointee);
}

/** @return {number} an array type's length */
export function array_length(m, type)
{
    return m.constants.get(type.length_id) || 1;
}

/**
 * The locations a value of the type takes in an interface (a matrix's
 * columns, an array's elements, a struct's members, one each)
 * @param {!Object} m parse_spirv's
 * @param {number} id the type
 * @return {number}
 */
export function location_count(m, id)
{
    const t = m.types.get(id);
    switch(t && t.kind)
    {
        case "matrix": return t.columns;
        case "array": return array_length(m, t) * location_count(m, t.element);
        case "struct": return t.members.reduce((n, member) => n + location_count(m, member), 0);
        default: return 1;
    }
}

/** @return {boolean} whether the variable is a built-in (or a block of them: gl_PerVertex) */
export function is_builtin(m, v)
{
    const d = m.decorations.get(v.id);
    if(d && d.has(DECORATION.BuiltIn)) return true;
    const members = m.member_decorations.get(innermost(m, m.types.get(v.type).pointee));
    return !!members && [...members.values()].some(member => member.has(DECORATION.BuiltIn));
}

/** @return {number} the type an array type is an array of, arrays of arrays too (the id itself for any other) */
export function innermost(m, id)
{
    let t = m.types.get(id);
    while(t && t.kind === "array") { id = t.element; t = m.types.get(id); }
    return id;
}

/**
 * A decoration's operand set (the decoration is there: glslang decorated
 * every interface variable and resource, the maps on)
 * @return {boolean} whether it was there
 */
export function set_decoration(words, m, id, decoration, value)
{
    const d = m.decorations.get(id);
    const at = d && d.get(decoration);
    if(at === undefined || at < 0) return false;
    words[at] = value >>> 0;
    return true;
}

/** @return {number|undefined} a decoration's operand */
export function get_decoration(words, m, id, decoration)
{
    const d = m.decorations.get(id);
    const at = d && d.get(decoration);
    return at === undefined || at < 0 ? undefined : words[at];
}

/** @return {string} a variable's name: the variable's own, else its (block) type's */
export function variable_name(m, v)
{
    const own = m.names.get(v.id);
    if(own) return own;
    return m.names.get(innermost(m, m.types.get(v.type).pointee)) || "";
}

/**
 * A block's leaves as GL names them ("a", "k[0]", "s.l[1].c"): each one's
 * offset, array stride and matrix stride, from the module's decorations
 * (glslang's reflection of the code pass gives other offsets for its
 * default uniform block than the SPIR-V has)
 * @param {!Uint32Array} words
 * @param {!Object} m parse_spirv's
 * @param {string} block_name the block type's name ("gl_DefaultUniformBlock")
 * @return {!Map<string, {offset: number, array_stride: number, matrix_stride: number, row_major: boolean}>}
 */
export function block_layout(words, m, block_name)
{
    const leaves = new Map();
    const block = [...m.names].find(([id, name]) => name === block_name && m.types.has(id) && m.types.get(id).kind === "struct");
    if(!block) return leaves;
    const member_word = (id, index, decoration) =>
    {
        const members = m.member_decorations.get(id);
        const d = members && members.get(index);
        const at = d && d.get(decoration);
        return at === undefined || at < 0 ? undefined : words[at];
    };
    const has_member = (id, index, decoration) =>
    {
        const members = m.member_decorations.get(id);
        const d = members && members.get(index);
        return !!d && d.has(decoration);
    };
    const walk = (type_id, name, offset, matrix_stride, row_major) =>
    {
        const t = m.types.get(type_id);
        if(t.kind === "struct")
        {
            const names = m.member_names.get(type_id) || [];
            t.members.forEach((member, i) =>
            {
                walk(member, (name ? name + "." : "") + names[i], offset + (member_word(type_id, i, DECORATION.Offset) || 0),
                    member_word(type_id, i, DECORATION.MatrixStride) || 0, has_member(type_id, i, DECORATION.RowMajor));
            });
            return;
        }
        if(t.kind === "array")
        {
            const stride = get_decoration(words, m, type_id, DECORATION.ArrayStride) || 0;
            const element = m.types.get(t.element);
            if(element.kind === "struct" || element.kind === "array")
            {
                for(let i = 0; i < array_length(m, t); i++) walk(t.element, name + "[" + i + "]", offset + i * stride, matrix_stride, row_major);
                return;
            }
            leaves.set(name + "[0]", { offset, array_stride: stride, matrix_stride, row_major });
            return;
        }
        leaves.set(name, { offset, array_stride: 0, matrix_stride, row_major });
    };
    walk(block[0], "", 0, 0, false);
    return leaves;
}

/**
 * Transform feedback's decorations (VK_EXT_transform_feedback's, which
 * vx_naga's xfb.rs reads): the TransformFeedback capability, the entry
 * point's Xfb mode, and each captured output's XfbBuffer, XfbStride and
 * Offset (a gl_PerVertex member's on the member)
 * @param {!Uint32Array} words
 * @param {!Array<{name: string, buffer: number, offset: number, stride: number}>} captures by variable name, or gl_Position, gl_PointSize
 * @return {!Uint32Array} the module with them
 */
export function add_xfb(words, captures)
{
    const m = parse_spirv(words);
    const decorations = [];
    const instruction = (op, ...operands) => [(operands.length + 1) << 16 | op, ...operands];
    for(const c of captures)
    {
        const builtin = { gl_Position: 0, gl_PointSize: 1 }[c.name];
        if(builtin !== undefined)
        {
            for(const v of m.variables.filter(x => x.storage === STORAGE.Output))
            {
                const type = m.types.get(v.type).pointee;
                const members = m.member_decorations.get(type);
                const member = members && [...members].find(([, d]) => d.has(DECORATION.BuiltIn) && words[d.get(DECORATION.BuiltIn)] === builtin);
                if(member)
                {
                    decorations.push(instruction(OP.MemberDecorate, type, member[0], DECORATION.Offset, c.offset),
                        instruction(OP.MemberDecorate, type, member[0], DECORATION.XfbBuffer, c.buffer),
                        instruction(OP.MemberDecorate, type, member[0], DECORATION.XfbStride, c.stride));
                }
                else if(get_decoration(words, m, v.id, DECORATION.BuiltIn) === builtin)
                {
                    decorations.push(instruction(OP.Decorate, v.id, DECORATION.Offset, c.offset), instruction(OP.Decorate, v.id, DECORATION.XfbBuffer, c.buffer),
                        instruction(OP.Decorate, v.id, DECORATION.XfbStride, c.stride));
                }
            }
            continue;
        }
        const v = m.variables.find(x => x.storage === STORAGE.Output && variable_name(m, x) === c.name && !is_builtin(m, x));
        if(!v) continue;
        decorations.push(instruction(OP.Decorate, v.id, DECORATION.XfbBuffer, c.buffer), instruction(OP.Decorate, v.id, DECORATION.XfbStride, c.stride),
            instruction(OP.Decorate, v.id, DECORATION.Offset, c.offset));
    }
    // (the capability first; the mode after the entry points and modes; the decorations after the others)
    let modes = 5, debug = 5, annotations = 5;
    for(let at = 5; at < words.length;)
    {
        const count = words[at] >>> 16, op = words[at] & 0xFFFF;
        if(!count) break;
        if(op === OP.EntryPoint || op === OP.ExecutionMode || op === 17 || op === 10 || op === 11 || op === 14) modes = at + count;
        if(op >= 3 && op <= 7 || op === 330) debug = at + count;
        if(op === OP.Decorate || op === OP.MemberDecorate || op === 332 || op === 333) annotations = at + count;
        at += count;
    }
    annotations = Math.max(annotations, debug, modes);
    const head = Array.from(words.subarray(0, modes));
    const mode = m.entry ? instruction(OP.ExecutionMode, m.entry.id, 11) : [];
    const out = [...head.slice(0, 5), ...instruction(17, 53), ...head.slice(5), ...mode, ...words.subarray(modes, annotations), ...decorations.flat(),
        ...words.subarray(annotations)];
    return new Uint32Array(out);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/graphics_adapter.js                                                                  0000644 0000000 0000000 00000037552 00000000000 014325  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Display adapters (the graphics_adapter option) are plugins: each lives in its
// own file and is loaded only when it is configured. v86 owns the VGA slot,
// the PCI bus, the port and memory maps, device memory (mmio_ram), the display
// hub and the adapter's place in a snapshot; the plugin owns the device.
// Plugins are not compiled with v86 (an ADVANCED build renames properties), so the
// handle a plugin gets and the descriptor and device it gives back use quoted
// names only. src/graphics_adapters/machine.js is the plugin's end of it.
// See docs/gpu-devices.md, "Adapter plugins".

import { LOG_PCI, FLAG_VM } from "./const.js";
import { dbg_log } from "./log.js";
import { pci_functions } from "./platform.js";
import { DisplaySource } from "./display.js";
import { create_adapter_virtio_device } from "./virtio_devices.js";
import { GRAPHICS_ADAPTERS, MAX_VRAM_SIZE, is_arm } from "./machine_options.js";
import { GRAPHICS_PLUGINS, default_plugin_path, resolve_plugin_path, load_device_plugin, allocate_io_ports,
    device_handle, plugin_pci_device } from "./device_plugin.js";

// For Types Only
import { CPU } from "./cpu.js";

/** Every value graphics_adapter may name */
const ADAPTERS = GRAPHICS_ADAPTERS;

// (MAX_VRAM_SIZE, the largest vram_size, is in machine_options.js with the other option rules)
export { MAX_VRAM_SIZE };

/** state[52] is [STATE_TAG, STATE_VERSION, adapter name, device state] */
const STATE_TAG = GRAPHICS_PLUGINS.tag;
const STATE_VERSION = 1;

/**
 * Check the display options of new V86(): graphics_adapter is required
 * @param {!Object} options
 * @return {string} the adapter's name
 */
export function check_graphics_adapter_options(options)
{
    const adapter = options["graphics_adapter"];
    const supported = ADAPTERS.map(name => "\"" + name + "\"").join(", ");

    if(typeof adapter === "function")
    {
        throw new Error("graphics_adapter now selects the display hardware; use graphics_proxy: true instead of installV86GLGraphicsAdapter");
    }
    if(adapter === undefined)
    {
        throw new Error("graphics_adapter is required; supported: " + supported +
            " (\"bochs_vga\" is the display v86 always had)");
    }
    if(typeof adapter !== "string" || !ADAPTERS.includes(adapter))
    {
        throw new Error("Unknown graphics_adapter " + JSON.stringify(adapter) + "; supported: " + supported);
    }

    if(options["vga_memory_size"] !== undefined)
    {
        throw new Error("vga_memory_size was renamed to vram_size");
    }
    const vram_size = options["vram_size"];
    if(vram_size !== undefined && !(Number.isSafeInteger(vram_size) && vram_size > 0 && (vram_size & (vram_size - 1)) === 0))
    {
        throw new Error("vram_size must be a power of two (in bytes)");
    }
    if(vram_size > MAX_VRAM_SIZE)
    {
        throw new Error("vram_size must be at most " + (MAX_VRAM_SIZE >> 20) + " MiB");
    }
    if(adapter === "none" && vram_size !== undefined)
    {
        console.warn("vram_size is ignored: graphics_adapter is \"none\"");
    }

    const path = options["graphics_adapter_path"];
    if(path !== undefined && (typeof path !== "string" || !path))
    {
        throw new Error("graphics_adapter_path must be the path or URL of the plugin file");
    }

    return adapter;
}

/**
 * Where a bundle looks for a plugin without graphics_adapter_path (see
 * default_plugin_path)
 * @param {string} name
 * @return {string}
 */
export function default_graphics_adapter_path(name)
{
    return default_plugin_path(name);
}

/**
 * An absolute URL of a plugin file
 * @param {string} path
 * @return {string}
 */
export function resolve_graphics_adapter_path(path)
{
    return resolve_plugin_path(path);
}

/**
 * Load a display adapter plugin, unless the page already did
 * @param {string} name
 * @param {string|undefined} path graphics_adapter_path
 * @return {!Promise<!Object>} its descriptor
 */
export async function load_graphics_adapter(name, path)
{
    const descriptor = await load_device_plugin(GRAPHICS_PLUGINS, name, path, "graphics_adapter_path");
    if(!Number.isInteger(descriptor["pci_vendor"]) || !Number.isInteger(descriptor["pci_device"]))
    {
        throw new Error("graphics_adapter \"" + name + "\": invalid plugin descriptor");
    }
    return descriptor;
}

/**
 * Make the PCI ROM header of a SeaBIOS-built VGA BIOS name the adapter's
 * device: SeaBIOS only runs a PCI ROM whose vendor and device match
 * (src/optionroms.c, map_pcirom). The code reads the real IDs from the
 * device itself, so SeaVGABIOS's per-device builds differ only in this
 * header. Its checksum byte is byte 6 (scripts/buildrom.py).
 * @param {!Uint8Array} rom
 * @param {number} vendor
 * @param {number} device
 */
export function patch_vga_bios_ids(rom, vendor, device)
{
    if(rom.length < 0x1C || rom[0] !== 0x55 || rom[1] !== 0xAA) return;
    const pcir = rom[0x18] | rom[0x19] << 8;
    if(pcir + 8 > rom.length ||
        rom[pcir] !== 0x50 || rom[pcir + 1] !== 0x43 || rom[pcir + 2] !== 0x49 || rom[pcir + 3] !== 0x52)
    {
        return;
    }
    if((rom[pcir + 4] | rom[pcir + 5] << 8) === vendor && (rom[pcir + 6] | rom[pcir + 7] << 8) === device)
    {
        return;
    }
    const seabios = new TextDecoder("latin1").decode(rom).includes("SeaBIOS");
    if(!seabios)
    {
        console.warn("The VGA BIOS is not a SeaBIOS build and does not name the display adapter's PCI device; SeaBIOS may not run it");
        return;
    }

    const size = Math.min(rom[2] * 512, rom.length);
    rom[pcir + 4] = vendor & 0xFF;
    rom[pcir + 5] = vendor >> 8;
    rom[pcir + 6] = device & 0xFF;
    rom[pcir + 7] = device >> 8;
    rom[6] = 0;
    let sum = 0;
    for(let i = 0; i < size; i++) sum += rom[i];
    rom[6] = -sum & 0xFF;
    dbg_log("VGA BIOS patched for PCI device " + vendor.toString(16) + ":" + device.toString(16), LOG_PCI);
}

/**
 * A plugin's scanout, as the display hub sees it
 * @constructor
 * @implements {DisplaySource}
 * @param {!Object} source quoted { vblank_period, on_vblank, render, invalidate }
 */
function PluginDisplaySource(source)
{
    this.source = source;
}

PluginDisplaySource.prototype.vblank_period = function()
{
    return this.source["vblank_period"]();
};

PluginDisplaySource.prototype.on_vblank = function()
{
    this.source["on_vblank"]();
};

PluginDisplaySource.prototype.render = function()
{
    this.source["render"]();
};

PluginDisplaySource.prototype.invalidate = function()
{
    this.source["invalidate"]();
};

/**
 * The configured display adapter: v86's side of a plugin's device. On the
 * virt machine (docs/arm64-virt-android16-plan.md P7.1) there is no VGA and
 * no port I/O: the device is a function of the PCIe host at
 * options.pci_id, or on a virtio-mmio slot (options.transport).
 * @constructor
 * @param {CPU} cpu
 * @param {!Object} descriptor from load_graphics_adapter
 * @param {!Object} options { vram_size, test, renderer, pci_id, transport }
 */
export function GraphicsAdapter(cpu, descriptor, options)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    this.descriptor = descriptor;

    /** @const @type {string} */
    this.name = descriptor["name"];

    /** the virt machine's: no VGA */
    this.virt = is_arm(/** @type {?} */ (cpu).cpu_type);
    /** The VGA slot: other devices keep their addresses whichever adapter is used (virt: given) */
    this.pci_id = options.pci_id !== undefined ? options.pci_id : pci_functions(cpu.platform).vga;
    /** the virt machine's virtio-mmio slot, if the device is there */
    this.transport = options.transport || null;

    this.pci_device = null;

    this.device = descriptor["create"](this.create_handle(), {
        "vram_size": options.vram_size,
        // graphics_adapter_test: internal, for tests that pin what the
        // adapter declares (its level); not part of the public options
        "test": options.test,
        // the channel to the adapter's 3D renderer, if the page made one
        "renderer": options.renderer || null,
    });
    if(!this.device || typeof this.device["get_state"] !== "function" || typeof this.device["set_state"] !== "function")
    {
        throw new Error("graphics_adapter \"" + this.name + "\": the plugin made no device");
    }
}

/**
 * For the VMware backdoor: a VMware SVGA device's capabilities and 3D
 * hardware version, or null for the other adapters
 * @return {?{capabilities: number, hardware_version: number}}
 */
GraphicsAdapter.prototype.svga_capabilities = function()
{
    const get = this.device["svga_capabilities"];
    const result = get ? get() : null;
    return result ? { capabilities: result["capabilities"] >>> 0, hardware_version: result["hardware_version"] >>> 0 } : null;
};

/**
 * Whether the device keeps state outside of the machine (a GPU) that a
 * snapshot has to fetch first, with prepare_save
 * @return {boolean}
 */
GraphicsAdapter.prototype.has_host_state = function()
{
    return !!this.device["has_host_state"] && this.device["has_host_state"]();
};

/**
 * @return {!Promise<undefined>}
 */
GraphicsAdapter.prototype.prepare_save = function()
{
    return this.has_host_state() ? this.device["prepare_save"]() : Promise.resolve(undefined);
};

/**
 * What the plugin gets to work with (src/graphics_adapters/machine.js)
 */
GraphicsAdapter.prototype.create_handle = function()
{
    const cpu = this.cpu;
    const io = cpu.io;
    const hub = cpu.devices.display;
    // Port and memory map entries are owned by this object; the plugin's
    // handlers come bound to its own device
    const owner = this;

    return Object.assign(device_handle(cpu, owner), {
        "qemu_compatible": !this.virt && !!cpu.platform.qemu_compatible,
        // (the virt machine: no VGA core, no ROM, no ports)
        "has_vga": !this.virt,

        "mmio_ram_allocate": size => cpu.mmio_ram_allocate(size),
        "mmio_ram_backing": region => cpu.mmio_ram_backing(region),
        "mmio_ram_map": (region, address) => cpu.mmio_ram_map(region, address),
        "mmio_ram_read8": (region, offset) => cpu.mmio_ram_read8(region, offset),
        "mmio_ram_write8": (region, offset, value) => cpu.mmio_ram_write8(region, offset, value),
        "mmio_ram_mark_dirty": region => cpu.mmio_ram_mark_dirty(region),
        "mmio_ram_take_dirty": region => cpu.mmio_ram_take_dirty(region),
        "mmio_ram_unmap": region => cpu.mmio_ram_unmap(region),
        "mmio_ram_allocate_pixels": (region, pixels) => cpu.mmio_ram_allocate_pixels(region, pixels),
        "mmio_ram_fill_pixels": (region, bpp, offset) => cpu.mmio_ram_fill_pixels(region, bpp, offset),
        "dirty_min_offset": () => cpu.svga_dirty_bitmap_min_offset[0],
        "dirty_max_offset": () => cpu.svga_dirty_bitmap_max_offset[0],

        // virtio-vga: the adapter's PCI function is a virtio device (the
        // descriptor as for virtio_devices, see create_adapter_virtio_device)
        "create_virtio": descriptor => this.create_virtio(descriptor),

        // The size the page would like the guest's display to have
        // (V86.set_display_size): width, height, the display's index
        "on_host_display_size": handler =>
            cpu.bus.register("display-host-size", data => handler(data[0], data[1], data[2] || 0), this),
        "in_vm86": () => !this.virt && !!(cpu.flags[0] & FLAG_VM),

        "display": {
            "set_mode": graphical => hub.set_mode(graphical),
            "set_size_text": (cols, rows) => hub.set_size_text(cols, rows),
            "set_size_graphical": (width, height, buffer_width, buffer_height, bpp) =>
                hub.set_size_graphical(width, height, buffer_width, buffer_height, bpp),
            "put_char": (row, col, chr, flags, bg_color, fg_color) =>
                hub.put_char(row, col, chr, flags, bg_color, fg_color),
            "update_cursor": (row, col) => hub.update_cursor(row, col),
            "update_cursor_scanline": (start, end, enabled) => hub.update_cursor_scanline(start, end, enabled),
            "set_font_bitmap": (height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed) =>
                hub.set_font_bitmap(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed),
            "set_font_page": (page_a, page_b) => hub.set_font_page(page_a, page_b),
            "clear_screen": () => hub.clear_screen(),
            "clear_text_state": () => hub.clear_text_state(),
            "update_buffer": layers => hub.update_buffer(layers.map(layer => ({
                pixels: {
                    data: layer["pixels"]["data"],
                    width: layer["pixels"]["width"],
                    height: layer["pixels"]["height"],
                },
                screen_x: layer["screen_x"],
                screen_y: layer["screen_y"],
                buffer_x: layer["buffer_x"],
                buffer_y: layer["buffer_y"],
                buffer_width: layer["buffer_width"],
                buffer_height: layer["buffer_height"],
            }))),
            "time_since_vblank": now => hub.time_since_vblank(now),
            "add_source": source => hub.add_source(new PluginDisplaySource(source)),
            "add_timer": timer => hub.add_timer(timer),
        },
    });
};

/**
 * A free window of I/O ports for an I/O BAR (allocate_io_ports)
 * @param {number} size a power of two
 * @return {number}
 */
GraphicsAdapter.prototype.allocate_io = function(size)
{
    return allocate_io_ports(this.cpu, size, "graphics_adapter \"" + this.name + "\"");
};

/**
 * @param {!Object} description quoted { pci_space, pci_bars, pci_rom_size, pci_rom_address }
 */
GraphicsAdapter.prototype.register_pci = function(description)
{
    if(this.pci_device)
    {
        throw new Error("graphics_adapter \"" + this.name + "\" registered its PCI function twice");
    }
    this.pci_device = plugin_pci_device(this, description);
    this.cpu.devices.pci.register_device(this.pci_device);
};

/**
 * @param {*} descriptor
 * @return {!Object} the device's quoted handle
 */
GraphicsAdapter.prototype.create_virtio = function(descriptor)
{
    if(this.pci_device)
    {
        throw new Error("graphics_adapter \"" + this.name + "\" registered its PCI function twice");
    }
    const device = create_adapter_virtio_device(this.cpu, descriptor, this.pci_id, this.transport || undefined);
    this.pci_device = device.virtio;
    return device.handle;
};

/**
 * The plugin's own object for tests and debugging (cpu.devices.vga): the
 * VGA core of every adapter that has one
 */
GraphicsAdapter.prototype.vga = function()
{
    return this.device["vga"];
};

/**
 * A machine reset (PCIRST#): the plugin's optional reset hook
 */
GraphicsAdapter.prototype.reset = function()
{
    const reset = this.device["reset"];
    if(typeof reset === "function") reset();
};

GraphicsAdapter.prototype.get_state = function()
{
    return [STATE_TAG, STATE_VERSION, this.name, this.device["get_state"]()];
};

/**
 * Throws if a snapshot's state[52] does not belong to this adapter. Changes
 * nothing, so that CPU.validate_state can call it before restoring anything.
 * @param {*} state
 */
GraphicsAdapter.prototype.check_state = function(state)
{
    const saved = graphics_adapter_of_state(state);
    if(saved !== this.name)
    {
        throw new Error("The snapshot is from a machine with graphics_adapter: " +
            JSON.stringify(saved) + ", this one has \"" + this.name + "\"");
    }
    if(state[0] === STATE_TAG && state[1] !== STATE_VERSION)
    {
        throw new Error("Unsupported graphics adapter state version " + state[1]);
    }
};

/** @param {*} state */
GraphicsAdapter.prototype.set_state = function(state)
{
    this.check_state(state);
    // Before plugins, state[52] was the Bochs VGA's own state
    this.device["set_state"](state[0] === STATE_TAG ? state[3] : state);
};

/**
 * Which adapter a snapshot's state[52] belongs to
 * @param {*} state
 * @return {string}
 */
export function graphics_adapter_of_state(state)
{
    if(state === undefined || state === null) return "none";
    if(Array.isArray(state) && state[0] === STATE_TAG) return state[2];
    // Older snapshots: the Bochs VGA, the only display v86 had
    return "bochs_vga";
}
                                                                                                                                                      source/v64/src/graphics_adapters/bochs_vga/plugin.js                                                0000644 0000000 0000000 00000001721 00000000000 017726  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // graphics_adapter: "bochs_vga" -- the Bochs/QEMU standard VGA (1234:1111):
// VGA plus the Bochs VBE interface and a linear frame buffer in BAR0.
// Built into build/v86-bochs-vga.js; from the source tree, src/graphics_adapter.js
// imports this file directly.

import { VGAScreen } from "../vga_core.js";
import { GraphicsMachine, register_graphics_adapter } from "../machine.js";

/** Without vram_size: the size v86 always had */
const DEFAULT_VRAM_SIZE = 8 * 1024 * 1024;

register_graphics_adapter({
    "name": "bochs_vga",
    // The VGA BIOS's PCI ROM header must name the device (SeaBIOS checks it)
    "pci_vendor": 0x1234,
    "pci_device": 0x1111,
    "create": (handle, options) =>
    {
        const vga = new VGAScreen(new GraphicsMachine(handle), options["vram_size"] || DEFAULT_VRAM_SIZE);
        return {
            "vga": vga,
            "get_state": () => vga.get_state(),
            "set_state": state => vga.set_state(state),
        };
    },
});
                                               source/v64/src/graphics_adapters/machine.js                                                         0000644 0000000 0000000 00000021361 00000000000 016103  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The display adapter's view of the machine (plugin side). The machine
// handle's common part (ports, memory maps, PCI, guest memory, the clock) is
// src/device_machine.js; this adds device memory (mmio_ram), virtio-vga and
// the display hub, and converts display layers between plugin names and
// quoted names. v86's side is src/graphics_adapter.js.
// See docs/gpu-devices.md, "Adapter plugins".

import { DeviceMachine, register_device_plugin } from "../device_machine.js";

/**
 * Make a display adapter known to v86. Plugin files call this when they load.
 * @param {!Object} descriptor { "name", "pci_vendor", "pci_device", "create" }
 */
export function register_graphics_adapter(descriptor)
{
    register_device_plugin("V86GraphicsAdapters", descriptor);
}

/**
 * What a display device drives on the presenter side (DisplayHub)
 * @constructor
 * @param {!Object} handle the quoted display handle
 */
function GraphicsDisplay(handle)
{
    this.handle = handle;
}

/** @param {boolean} graphical */
GraphicsDisplay.prototype.set_mode = function(graphical)
{
    this.handle["set_mode"](graphical);
};

/**
 * @param {number} cols
 * @param {number} rows
 */
GraphicsDisplay.prototype.set_size_text = function(cols, rows)
{
    this.handle["set_size_text"](cols, rows);
};

/**
 * @param {number} width
 * @param {number} height
 * @param {number} buffer_width
 * @param {number} buffer_height
 * @param {number} bpp
 */
GraphicsDisplay.prototype.set_size_graphical = function(width, height, buffer_width, buffer_height, bpp)
{
    this.handle["set_size_graphical"](width, height, buffer_width, buffer_height, bpp);
};

/**
 * @param {number} row
 * @param {number} col
 * @param {number} chr
 * @param {number} flags
 * @param {number} bg_color
 * @param {number} fg_color
 */
GraphicsDisplay.prototype.put_char = function(row, col, chr, flags, bg_color, fg_color)
{
    this.handle["put_char"](row, col, chr, flags, bg_color, fg_color);
};

/**
 * @param {number} row
 * @param {number} col
 */
GraphicsDisplay.prototype.update_cursor = function(row, col)
{
    this.handle["update_cursor"](row, col);
};

/**
 * @param {number} start
 * @param {number} end
 * @param {boolean} enabled
 */
GraphicsDisplay.prototype.update_cursor_scanline = function(start, end, enabled)
{
    this.handle["update_cursor_scanline"](start, end, enabled);
};

/**
 * @param {number} height
 * @param {boolean} width_9px
 * @param {boolean} width_dbl
 * @param {boolean} copy_8th_col
 * @param {Uint8Array} bitmap
 * @param {boolean} bitmap_changed
 */
GraphicsDisplay.prototype.set_font_bitmap = function(height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed)
{
    this.handle["set_font_bitmap"](height, width_9px, width_dbl, copy_8th_col, bitmap, bitmap_changed);
};

/**
 * @param {number} page_a
 * @param {number} page_b
 */
GraphicsDisplay.prototype.set_font_page = function(page_a, page_b)
{
    this.handle["set_font_page"](page_a, page_b);
};

GraphicsDisplay.prototype.clear_screen = function()
{
    this.handle["clear_screen"]();
};

GraphicsDisplay.prototype.clear_text_state = function()
{
    this.handle["clear_text_state"]();
};

/**
 * Each layer is { pixels: { data, width, height }, screen_x, screen_y,
 * buffer_x, buffer_y, buffer_width, buffer_height }, as DisplaySink takes it
 * @param {!Array<!Object>} layers
 */
GraphicsDisplay.prototype.update_buffer = function(layers)
{
    this.handle["update_buffer"](layers.map(layer => ({
        "pixels": {
            "data": layer.pixels.data,
            "width": layer.pixels.width,
            "height": layer.pixels.height,
        },
        "screen_x": layer.screen_x,
        "screen_y": layer.screen_y,
        "buffer_x": layer.buffer_x,
        "buffer_y": layer.buffer_y,
        "buffer_width": layer.buffer_width,
        "buffer_height": layer.buffer_height,
    })));
};

/**
 * @param {number} now
 * @return {number}
 */
GraphicsDisplay.prototype.time_since_vblank = function(now)
{
    return this.handle["time_since_vblank"](now);
};

/**
 * Called whenever the machine's timers run (each slice of the CPU's): a
 * device's own polling. Returns milliseconds until it needs to run again.
 * @param {function(number):number} timer
 */
GraphicsDisplay.prototype.add_timer = function(timer)
{
    this.handle["add_timer"](timer);
};

/**
 * A device with a scanout: { vblank_period(), on_vblank(), render(), invalidate() }
 * @param {!Object} source
 */
GraphicsDisplay.prototype.add_source = function(source)
{
    this.handle["add_source"]({
        "vblank_period": () => source.vblank_period(),
        "on_vblank": () => source.on_vblank(),
        "render": () => source.render(),
        "invalidate": () => source.invalidate(),
    });
};

/**
 * @constructor
 * @extends {DeviceMachine}
 * @param {!Object} handle the quoted machine handle from src/graphics_adapter.js
 */
export function GraphicsMachine(handle)
{
    DeviceMachine.call(this, handle);

    /** @const @type {boolean} whether the machine has a VGA (not the virt machine: no legacy VGA, ROM or ports) */
    this.has_vga = handle["has_vga"] !== false;

    /** @const */
    this.display = new GraphicsDisplay(handle["display"]);
}
GraphicsMachine.prototype = Object.create(DeviceMachine.prototype);
GraphicsMachine.prototype.constructor = GraphicsMachine;

/**
 * Device memory (src/rust/cpu/mmio_ram.rs)
 * @param {number} size
 * @return {number} the region, or -1
 */
GraphicsMachine.prototype.mmio_ram_allocate = function(size)
{
    return this.handle["mmio_ram_allocate"](size);
};

/**
 * @param {number} region
 * @return {number} the offset of its memory in wasm memory
 */
GraphicsMachine.prototype.mmio_ram_backing = function(region)
{
    return this.handle["mmio_ram_backing"](region);
};

/**
 * @param {number} region
 * @param {number} address
 */
GraphicsMachine.prototype.mmio_ram_map = function(region, address)
{
    this.handle["mmio_ram_map"](region, address);
};

/**
 * @param {number} region
 * @param {number} offset
 * @return {number}
 */
GraphicsMachine.prototype.mmio_ram_read8 = function(region, offset)
{
    return this.handle["mmio_ram_read8"](region, offset);
};

/**
 * @param {number} region
 * @param {number} offset
 * @param {number} value
 */
GraphicsMachine.prototype.mmio_ram_write8 = function(region, offset, value)
{
    this.handle["mmio_ram_write8"](region, offset, value);
};

/** @param {number} region */
GraphicsMachine.prototype.mmio_ram_mark_dirty = function(region)
{
    this.handle["mmio_ram_mark_dirty"](region);
};

/**
 * Take the region's bitmap of written pages (a bit a page, 64 a word)
 * @param {number} region
 * @return {number} the offset of the words in wasm memory (0: none)
 */
GraphicsMachine.prototype.mmio_ram_take_dirty = function(region)
{
    return this.handle["mmio_ram_take_dirty"](region);
};

/** @param {number} region */
GraphicsMachine.prototype.mmio_ram_unmap = function(region)
{
    this.handle["mmio_ram_unmap"](region);
};

/**
 * @param {number} region
 * @param {number} pixels
 * @return {number} the offset of the RGBA picture in wasm memory
 */
GraphicsMachine.prototype.mmio_ram_allocate_pixels = function(region, pixels)
{
    return this.handle["mmio_ram_allocate_pixels"](region, pixels);
};

/**
 * Convert the region's dirty pages into its RGBA picture
 * @param {number} region
 * @param {number} bpp
 * @param {number} offset
 */
GraphicsMachine.prototype.mmio_ram_fill_pixels = function(region, bpp, offset)
{
    this.handle["mmio_ram_fill_pixels"](region, bpp, offset);
};

/**
 * The byte range the last mmio_ram_fill_pixels converted
 * @return {number}
 */
GraphicsMachine.prototype.dirty_min_offset = function()
{
    return this.handle["dirty_min_offset"]();
};

/** @return {number} */
GraphicsMachine.prototype.dirty_max_offset = function()
{
    return this.handle["dirty_max_offset"]();
};

/**
 * Make the device's PCI function a virtio device (virtio-vga), in place of
 * register_pci. The descriptor uses quoted names, as for the virtio_devices
 * option, with "class_code", "revision", "bars" and "capability_bar"
 * (src/virtio_devices.js, create_adapter_virtio_device).
 * @param {!Object} descriptor
 * @return {!Object} the quoted handle: has_request, pop_request, request_at, flush,
 *     read_memory, write_memory, config_changed, transport, set_transport, reset, ...
 */
GraphicsMachine.prototype.create_virtio = function(descriptor)
{
    return this.handle["create_virtio"](descriptor);
};

/**
 * The size the page would like a display to have (V86.set_display_size)
 * @param {function(number, number, number)} handler width, height, display
 */
GraphicsMachine.prototype.on_host_display_size = function(handler)
{
    this.handle["on_host_display_size"](handler);
};

/** @return {boolean} whether the CPU runs a virtual 8086 task (Win9x DOS boxes) */
GraphicsMachine.prototype.in_vm86 = function()
{
    return this.handle["in_vm86"]();
};
                                                                                                                                                                                                                                                                               source/v64/src/graphics_adapters/renderer_protocol.js                                               0000644 0000000 0000000 00000031352 00000000000 020227  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the display adapters' devices and their renderer
// (src/browser/glbridge/svga_renderer.js) share: GX batches (the GX writer
// and opcodes; gx/gx_executor.js runs them) and the response region the
// renderer writes answers into (query results, readbacks). vmware_svga and
// virtio_gpu both write GX; the GLES host (ranchu_gpu "host") writes GLES
// batches with the same writer.

/** Where the executor writes answers: offsets into a 16 MiB arena whose last
 * 4 MiB are the response region (query slots first, then readbacks) */
export const RESPONSE_REGION_OFFSET = 12 << 20;
export const RESPONSE_REGION_BYTES = 4 << 20;
export const QUERY_SLOT_BYTES = 16;
export const QUERY_REGION_BYTES = 16 * 1024;
export const READBACK_HEADER_BYTES = 16;
/** The largest readback payload one request may carry */
export const READBACK_MAX_BYTES = RESPONSE_REGION_BYTES - QUERY_REGION_BYTES - READBACK_HEADER_BYTES - 16;
export const RESPONSE_OK = 1;
export const RESPONSE_FAILED = 2;

/** GX batch header magic: "GX10" */
export const GX_MAGIC = 0x30315847;

/** GX opcodes (gx_executor.js has the same) */
export const GX = {
    SURFACE_DEFINE: 1,      // sid, format, flags (64 bits), width, height, depth, mips, layers, samples, cube
    SURFACE_DESTROY: 2,     // sid
    SURFACE_UPLOAD: 3,      // sid, layer, mip, x, y, z, w, h, d, row pitch, slice pitch, then the bytes
    SURFACE_READBACK: 4,    // sid, layer, mip, x, y, z, w, h, d, request id
    CONTEXT_DEFINE: 5,      // cid
    CONTEXT_DESTROY: 6,     // cid
    SHADER_CODE: 7,         // cid, shid, type, then the tokens
    DX: 8,                  // cid, SVGA_3D_CMD_DX_*, then the command's body
    SURFACE_COPY: 9,        // src sid, layer, mip, x, y, z, dst sid, layer, mip, x, y, z, w, h, d
    QUERY_END: 10,          // cid, qid, type, request id
    COTABLE_RESET: 11,      // cid, SVGACOTableType: forget the objects of a type
    SURFACE_STRETCH: 12,    // src sid, layer, mip, l, t, r, b, dst sid, layer, mip, l, t, r, b, linear
    // a surface both GX and D9WG have (D3D9 apps' and DWM's): every image of
    // the D9WG resource into GX's surface, or back
    SURFACE_IMPORT: 13,     // sid, D9WG handle
    SURFACE_EXPORT: 14,     // sid, D9WG handle
    CLEAR_RTV_INTEGER: 15,  // cid, render target view, signed, 4 values (DX's clear has floats)
    // a scanout shown without a readback (docs/gfxstream-plan.md G4): the
    // surface's rectangle copied on the GPU into the page's screen, at (dx, dy)
    // of a screen of width x height; sid 0 hides it again
    SURFACE_PRESENT: 16,    // sid, x, y, w, h, dx, dy, width, height
};

/** VX batch header magic: "VX10" (Venus's Vulkan, on WebGPU: vx/vx_executor.js) */
export const VX_MAGIC = 0x30315856;

/**
 * VX opcodes (vx_executor.js has the same). Objects are the renderer's ids
 * the device gives them; 64-bit values are two dwords (low, high). A
 * VkDeviceMemory is a GPU buffer, a VkImage a texture; buffers are ranges
 * of memory, named by (memory, offset) in each command.
 */
export const VX = {
    MEMORY_CREATE: 1,       // id, size (64)
    DESTROY: 2,             // id
    MEMORY_WRITE: 3,        // id, offset (64), length, then the bytes
    MEMORY_READ: 4,         // id, offset (64), length, request id: answered by a "read" message
    TEXTURE_CREATE: 5,      // id, VkFormat, VkImageType, width, height, depth, mips, layers, samples, VkImageUsageFlags, VkImageCreateFlags
    VIEW_CREATE: 6,         // id, texture, VkImageViewType, VkFormat, aspect, base mip, mips, base layer, layers, swizzle r g b a
    SAMPLER_CREATE: 7,      // id, mag, min, mipmap, u, v, w, lod bias (f32), anisotropy (f32), compare, compare op, min lod (f32), max lod (f32)
    BEGIN: 8,               // (a command buffer's commands follow, into one encoder)
    END: 9,                 // (submitted)
    COPY_BUFFER: 10,        // src, src offset (64), dst, dst offset (64), size (64)
    FILL_BUFFER: 11,        // dst, offset (64), size (64), data
    UPDATE_BUFFER: 12,      // dst, offset (64), length, then the bytes
    COPY_BUFFER_IMAGE: 13,  // to image (1) or from it (0), memory, offset (64), row length, image height,
                            // texture, aspect, mip, base layer, layers, x, y, z, width, height, depth
    COPY_IMAGE: 14,         // src texture, aspect, mip, base layer, x, y, z, dst texture, aspect, mip, base layer, x, y, z, width, height, depth, layers
    BLIT_IMAGE: 15,         // src texture, mip, layer, x0, y0, z0, x1, y1, z1, dst texture, mip, layer, x0, y0, z0, x1, y1, z1, layers, linear
    CLEAR_IMAGE: 16,        // texture, aspect, base mip, mips, base layer, layers, 4 values (color bits; or depth f32, stencil)
    RESOLVE_IMAGE: 17,      // src texture, mip, layer, x, y, dst texture, mip, layer, x, y, width, height, layers
    SHADER_CREATE: 18,      // id, byte length, then the SPIR-V
    PIPELINE_CREATE: 19,    // id, then the pipeline's state as JSON (UTF-8)
    BEGIN_PASS: 20,         // then the pass as JSON: colors [{view, load, store, clear, resolve}], depth {...}, width, height
    END_PASS: 21,
    BIND_PIPELINE: 22,      // pipeline
    SET_BIND_GROUP: 23,     // group, count, then per descriptor: binding, element, VkDescriptorType, view or memory, sampler,
                            // offset (64), size
    SET_VERTEX_BUFFER: 24,  // slot, memory, offset (64), size (64)
    SET_INDEX_BUFFER: 25,   // memory, offset (64), size (64), VkIndexType
    SET_PUSH_CONSTANTS: 26, // offset, length, then the bytes
    SET_VIEWPORT: 27,       // x, y, width, height, min depth, max depth (f32)
    SET_SCISSOR: 28,        // x, y, width, height
    SET_BLEND_CONSTANTS: 29, // 4 f32
    SET_STENCIL_REFERENCE: 30, // faces, reference
    DRAW: 31,               // vertices, instances, first vertex, first instance
    DRAW_INDEXED: 32,       // indices, instances, first index, vertex offset, first instance
    DRAW_INDIRECT: 33,      // memory, offset (64), draws, stride, indexed
    DISPATCH: 34,           // x, y, z
    DISPATCH_INDIRECT: 35,  // memory, offset (64)
    CLEAR_ATTACHMENTS: 36,  // then JSON: attachments [{aspect, index, clear}], rects [{x, y, width, height}]
    QUERY_POOL_CREATE: 37,  // id, VkQueryType, count (occlusion queries: a query set)
    BEGIN_QUERY: 38,        // pool, query (in a render pass begun with the pool as its occlusion queries)
    END_QUERY: 39,          // pool, query, memory: the result (u64) into the memory at query * 8 when the pass ends
    COPY_QUERY_RESULTS: 40, // results memory, first, count, dst memory, dst offset (64), stride, VkQueryResultFlags
    TEXTURE_READ: 41,       // texture, aspect, mip, layer or slice, request id: answered with the image's texels, rows packed
    TEXTURE_WRITE: 42,      // texture, aspect, mip, layer or slice, length, then the texels (rows packed): a snapshot's contents
    TEXTURE_IMPORT: 43,     // texture, virtio-gpu resource id: the image becomes the texture of that resource's GX surface
                            // (a gralloc buffer imported by Venus: VkImportMemoryResourceInfoMESA), which GX keeps owning
    // transform feedback (VK_EXT_transform_feedback): a draw in an active one
    // runs its vertex shader as a compute shader first (vx/naga/src/xfb.rs)
    XFB_BIND: 44,           // buffer, memory, offset (64), size (64)
    XFB_BEGIN: 45,          // first counter, count, then per counter buffer: memory (0: none), offset (64)
    XFB_END: 46,            // as XFB_BEGIN: the bytes captured into each buffer go to its counter (u32)
    // the dynamic stencil masks (VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
    // _WRITE_MASK): WebGPU's are the pipeline's, so a variant per pair
    SET_STENCIL_COMPARE_MASK: 47, // faces, mask
    SET_STENCIL_WRITE_MASK: 48, // faces, mask
    // the dynamic depth bias (VK_DYNAMIC_STATE_DEPTH_BIAS: GL's glPolygonOffset): a variant per bias
    SET_DEPTH_BIAS: 49,     // constant factor, clamp, slope factor (f32)
};

/** GLES batch header magic: "GE10" (the GLES host's, src/gles/, docs/gles-proxy-plan.md) */
export const GLES_MAGIC = 0x30314547;

/**
 * GLES records (the GLES executor has the same). A command is the guest's
 * GLESv1 or GLESv2 command as it encoded it (opcode, size, parameters: its
 * data travels with it), for the connection's current context, with the
 * answer the CPU side gave (glCreateShader's and glCreateProgram's names);
 * only calls the shadow state accepted, no queries. renderControl's objects
 * come as records of their own: what a color buffer, a surface or a
 * context is, not the guest's reference counting. A read is answered by a
 * "write" message: the readback header (request id, length, 0, status),
 * then the pixels, rows packed.
 */
export const GLES = {
    COMMAND: 1,             // connection, answer, byte length, then the command's bytes
    CONTEXT_CREATE: 2,      // context, config, share group (its first context), API (1 or 2)
    CONTEXT_DESTROY: 3,     // context
    SURFACE_CREATE: 4,      // surface, config, width, height
    SURFACE_DESTROY: 5,     // surface
    SURFACE_COLOR_BUFFER: 6, // surface, color buffer (rcSetWindowColorBuffer)
    MAKE_CURRENT: 7,        // connection, context, draw surface, read surface
    COLOR_BUFFER_CREATE: 8, // color buffer, width, height, internal format
    COLOR_BUFFER_DESTROY: 9, // color buffer (its last reference went)
    COLOR_BUFFER_UPDATE: 10, // color buffer, x, y, width, height, format, type, byte length, then the pixels
    COLOR_BUFFER_READ: 11,  // color buffer, x, y, width, height, format, type, request id
    COLOR_BUFFER_BIND: 12,  // connection, color buffer, as a texture (1) or a renderbuffer (0) of its context
    IMAGE_CREATE: 13,       // image, context, target (EGL_GL_TEXTURE_2D_KHR, EGL_NATIVE_BUFFER_ANDROID), texture or color buffer
    IMAGE_DESTROY: 14,      // image
    POST: 15,               // color buffer: the screen (rcFBPost)
    FLUSH_SURFACE: 16,      // surface: what was drawn to it is its color buffer's (rcFlushWindowColorBuffer)
    READ_PIXELS: 17,        // connection, request id, x, y, width, height, format, type (glReadPixels)
    CONNECTION_CLOSE: 18,   // connection (nothing is current on it any more)
    PROGRAM_LINK: 19,       // connection, program, byte length, then the link's result (glsl_program.js's pack_program):
                            // before its glLinkProgram, which the page then links with it (it has no glslang)
    BUFFER_READ: 20,        // connection, request id, buffer, offset, length: a buffer's bytes the GPU wrote (glMapBufferRange's)
    QUERY_READ: 21,         // connection, request id, query: an occlusion query's result (a u32: whether a sample passed)
};

/**
 * A GX (or VX) batch being written: dwords
 * @constructor
 * @param {number=} magic GX_MAGIC unless given
 */
export function GXWriter(magic)
{
    this.magic = magic || GX_MAGIC;
    this.words = new Uint32Array(1 << 14);
    this.length = 4;
    this.count = 0;
    /** @type {?function()} called before each command: the other stream is sent first */
    this.before = null;
    /** @type {?function(number, !IArrayLike<number>, (Uint8Array|undefined))} sees each command (Venus keeps its creations for snapshots) */
    this.listener = null;
}

GXWriter.prototype.empty = function()
{
    return this.count === 0;
};

/** @return {number} bytes so far */
GXWriter.prototype.size = function()
{
    return this.length * 4;
};

GXWriter.prototype.reserve = function(dwords)
{
    if(this.length + dwords <= this.words.length) return;
    let capacity = this.words.length;
    while(capacity < this.length + dwords) capacity *= 2;
    const bigger = new Uint32Array(capacity);
    bigger.set(this.words.subarray(0, this.length));
    this.words = bigger;
};

/**
 * A command: its opcode, its dwords, then maybe bytes (padded to dwords)
 * @param {number} op
 * @param {!IArrayLike<number>} dwords
 * @param {Uint8Array=} bytes
 */
GXWriter.prototype.command = function(op, dwords, bytes)
{
    if(this.before) this.before();
    if(this.listener) this.listener(op, dwords, bytes);
    const byte_count = bytes ? bytes.length : 0;
    const body = dwords.length + (byte_count + 3 >> 2);
    this.reserve(2 + body);
    const w = this.words;
    w[this.length++] = op;
    w[this.length++] = body;
    for(let i = 0; i < dwords.length; i++) w[this.length++] = dwords[i];
    if(bytes)
    {
        const tail = new Uint8Array(w.buffer, this.length * 4, body * 4 - dwords.length * 4);
        tail.fill(0);
        tail.set(bytes);
        this.length += byte_count + 3 >> 2;
    }
    this.count++;
};

/**
 * The batch: header (magic, version, dwords, commands), then the commands
 * @return {!Uint8Array}
 */
GXWriter.prototype.finish = function()
{
    const w = this.words;
    w[0] = this.magic;
    w[1] = 1;
    w[2] = this.length;
    w[3] = this.count;
    const bytes = new Uint8Array(w.buffer.slice(0, this.length * 4));
    this.length = 4;
    this.count = 0;
    return bytes;
};
                                                                                                                                                                                                                                                                                      source/v64/src/graphics_adapters/vga_core.js                                                        0000644 0000000 0000000 00000260443 00000000000 016272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The VGA core shared by the display adapter plugins: the VGA registers and
// memory, the Bochs VBE (dispi) interface and the linear frame buffer. The
// bochs_vga plugin is this core on its own; the SVGA II and virtio-vga
// adapters embed it for the BIOS, DOS and boot screens.
import { LOG_VGA } from "../const.js";
import { h } from "../lib.js";
import { dbg_assert, dbg_log } from "../log.js";
import { DISPLAY_FLAG_BLINKING, DISPLAY_FLAG_FONT_PAGE_B } from "../display.js";
import { round_up_to_next_power_of_2, view } from "../lib.js";

// For Types Only
import { DisplaySource } from "../display.js";
import { GraphicsMachine } from "./machine.js";

// Always 64k
const VGA_BANK_SIZE = 64 * 1024;

const MAX_XRES = 2560;
const MAX_YRES = 1600;
const MAX_BPP = 32;

// Where the linear frame buffer starts out; the guest may move it (BAR0)
const VGA_LFB_ADDRESS = 0xE0000000;

/**
 * Equals the maximum number of pixels for non svga.
 * 8 pixels per byte.
 */
const VGA_PIXEL_BUFFER_SIZE = 8 * VGA_BANK_SIZE;

const VGA_MIN_MEMORY_SIZE = 4 * VGA_BANK_SIZE;

/**
 * Avoid wrapping past VGA_LFB_ADDRESS
 */
const VGA_MAX_MEMORY_SIZE = 256 * 1024 * 1024;

/**
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#06}
 */
const VGA_HOST_MEMORY_SPACE_START = Uint32Array.from([
    0xA0000,
    0xA0000,
    0xB0000,
    0xB8000,
]);

/**
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#06}
 */
const VGA_HOST_MEMORY_SPACE_SIZE = Uint32Array.from([
    0x20000, // 128K
    0x10000, // 64K
    0x8000, // 32K
    0x8000, // 32K
]);

/**
 * @constructor
 * @implements {DisplaySource}
 * @param {GraphicsMachine} machine
 * @param {number} vga_memory_size
 * @param {{pci: (boolean|undefined), display_source: (boolean|undefined)}=} options
 *     An adapter that embeds the core (SVGA II, virtio-vga) describes the PCI
 *     function and owns the scanout itself: pci: false, display_source: false
 */
export function VGAScreen(machine, vga_memory_size, options)
{
    /** @const */
    this.machine = machine;

    /** @const */
    this.display = machine.display;

    this.vga_memory_size = vga_memory_size;

    /** @type {number} */
    this.cursor_address = 0;

    /** @type {number} */
    this.cursor_scanline_start = 0xE;

    /** @type {number} */
    this.cursor_scanline_end = 0xF;

    /**
     * Number of columns in text mode
     * @type {number}
     */
    this.max_cols = 80;

    /**
     * Number of rows in text mode
     * @type {number}
     */
    this.max_rows = 25;

    /**
     * Width in pixels in graphical mode
     * @type {number}
     */
    this.screen_width = 0;

    /**
     * Height in pixels in graphical mode
     * @type {number}
     */
    this.screen_height = 0;

    /**
     * Logical width in pixels of virtual buffer available for panning
     * @type {number}
     */
    this.virtual_width = 0;

    /**
     * Logical height in pixels of virtual buffer available for panning
     * @type {number}
     */
    this.virtual_height = 0;

    /**
     * The rectangular fragments of the image buffer, and their destination
     * locations, to be drawn every render during VGA modes.
     * @type {!Array<!Object>}
     */
    this.layers = [];

    /**
     * video memory start address
     * @type {number}
     */
    this.start_address = 0;

    /**
     * Start address - a copy of start_address that only gets updated
     * during VSync, used for panning and page flipping
     * @type {number}
     */
    this.start_address_latched = 0;

    /**
     * The text screen is sent to the display again at the next vertical
     * retrace: a mode set or a palette load changes many registers in a row,
     * and each would otherwise send every character again
     * @type {boolean}
     */
    this.text_redraw_pending = false;

    /**
     * Unimplemented CRTC registers go here
     */
    this.crtc = new Uint8Array(0x19);

    // Implemented CRTC registers:

    /** @type {number} */
    this.crtc_mode = 0;

    /** @type {number} */
    this.horizontal_display_enable_end = 0;

    /** @type {number} */
    this.horizontal_blank_start = 0;

    /** @type {number} */
    this.vertical_display_enable_end = 0;

    /** @type {number} */
    this.vertical_blank_start = 0;

    /** @type {number} */
    this.underline_location_register = 0;

    /** @type {number} */
    this.preset_row_scan = 0;

    /** @type {number} */
    this.offset_register = 0;

    /** @type {number} */
    this.line_compare = 0;

    // End of CRTC registers

    /** @type {boolean} */
    this.graphical_mode = false;

    // Whether the sink has this graphics mode's size: showing text in between
    // may have taken its canvas, and then it is sent again
    this.size_reported = false;

    /*
     * VGA palette containing 256 colors for video mode 13, svga 8bpp, etc.
     * Needs to be initialised by the BIOS
     */
    this.vga256_palette = new Int32Array(256);

    /**
     * VGA read latches
     * @type{number}
     */
    this.latch_dword = 0;

    /** @type {number} */
    this.svga_version = 0xB0C5;

    /** @type {number} */
    this.svga_width = 0;

    /** @type {number} */
    this.svga_height = 0;

    this.svga_enabled = false;

    /** @type {number} */
    this.svga_bpp = 32;

    /** @type {number} */
    this.svga_bank_offset = 0;

    /**
     * The video buffer offset created by VBE_DISPI_INDEX_Y_OFFSET
     * In bytes
     * @type {number}
     */
    this.svga_offset = 0;
    this.svga_offset_x = 0;
    this.svga_offset_y = 0;

    if(this.vga_memory_size === undefined || this.vga_memory_size < VGA_MIN_MEMORY_SIZE)
    {
        this.vga_memory_size = VGA_MIN_MEMORY_SIZE;
    }
    else if(this.vga_memory_size > VGA_MAX_MEMORY_SIZE)
    {
        this.vga_memory_size = VGA_MAX_MEMORY_SIZE;
    }
    else
    {
        // required for pci code
        this.vga_memory_size = round_up_to_next_power_of_2(this.vga_memory_size);
    }
    dbg_log("effective vga memory size: " + this.vga_memory_size, LOG_VGA);

    // 2 announces QEMU's extended registers (BAR2), which are not implemented;
    // QEMU's revision, so that a guest installed there knows the device
    const pci_revision = machine.qemu_compatible ? 2 : 0;

    // Experimental, could probably need some changes
    // 01:00.0 VGA compatible controller: NVIDIA Corporation GT216 [GeForce GT 220] (rev a2)
    this.pci_space = [
        0x34, 0x12, 0x11, 0x11, 0x03, 0x01, 0x00, 0x00, pci_revision, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
        0x08, VGA_LFB_ADDRESS >>> 8, VGA_LFB_ADDRESS >>> 16, VGA_LFB_ADDRESS >>> 24,
                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xbf, 0xfe, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf4, 0x1a, 0x00, 0x11,
        0x00, 0x00, 0xbe, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    ];
    this.pci_bars = [
        {
            size: this.vga_memory_size,
            // the linear frame buffer follows BAR0 (see PCI.prototype.pci_write32)
            on_move: base => this.move_lfb(base),
        },
    ];

    // TODO: Should be matched with vga bios size and mapping address
    // Seabios config for this device:
    // CONFIG_VGA_PCI=y
    // CONFIG_OVERRIDE_PCI_ID=y
    // CONFIG_VGA_VID=0x10de
    // CONFIG_VGA_DID=0x0a20

    this.pci_rom_size = 0x10000;
    this.pci_rom_address = 0xFEB00000;

    this.name = "vga";

    this.index_crtc = 0;

    // index for setting colors through port 3C9h
    this.dac_color_index_write = 0;
    this.dac_color_index_read = 0;
    this.dac_state = 0;

    this.dac_mask = 0xFF;

    this.dac_map = new Uint8Array(0x10);

    this.attribute_controller_index = -1;
    this.palette_source = 0x20;
    this.attribute_mode = 0;
    this.color_plane_enable = 0;
    this.horizontal_panning = 0;
    this.color_select = 0;

    this.sequencer_index = -1;

    // bitmap of planes 0-3
    this.plane_write_bm = 0xF;
    this.sequencer_memory_mode = 0;
    this.clocking_mode = 0;
    this.graphics_index = -1;
    this.character_map_select = 0;

    this.plane_read = 0; // value 0-3, which plane to read
    this.planar_mode = 0;
    this.planar_rotate_reg = 0;
    this.planar_bitmap = 0xFF;
    this.planar_setreset = 0;
    this.planar_setreset_enable = 0;
    this.miscellaneous_graphics_register = 0;

    this.color_compare = 0;
    this.color_dont_care = 0;

    this.max_scan_line = 0;

    this.miscellaneous_output_register = 0xff;

    // Bit 0 of input status register 1 (0x3DA), which toggles on every read
    this.port_3DA_value = 0xFF;

    // A vertical retrace has started that no 0x3DA read has seen yet
    this.retrace_pending = false;

    this.font_page_ab_enabled = false;

    var io = machine;

    io.register_write(0x3C0, this, this.port3C0_write);
    io.register_read(0x3C0, this, this.port3C0_read, this.port3C0_read16);

    io.register_read(0x3C1, this, this.port3C1_read);
    io.register_write(0x3C2, this, this.port3C2_write);

    io.register_write_consecutive(0x3C4, this, this.port3C4_write, this.port3C5_write);

    io.register_read(0x3C4, this, this.port3C4_read);
    io.register_read(0x3C5, this, this.port3C5_read);

    io.register_write_consecutive(0x3CE, this, this.port3CE_write, this.port3CF_write);

    io.register_read(0x3CE, this, this.port3CE_read);
    io.register_read(0x3CF, this, this.port3CF_read);

    io.register_read(0x3C6, this, this.port3C6_read);
    io.register_write(0x3C6, this, this.port3C6_write);
    io.register_write(0x3C7, this, this.port3C7_write);
    io.register_read(0x3C7, this, this.port3C7_read);
    io.register_write(0x3C8, this, this.port3C8_write, this.port3C8_write16);
    io.register_read(0x3C8, this, this.port3C8_read);
    io.register_write(0x3C9, this, this.port3C9_write);
    io.register_read(0x3C9, this, this.port3C9_read);

    io.register_read(0x3CC, this, this.port3CC_read);

    io.register_write(0x3D4, this, this.port3D4_write, this.port3D4_write16);
    io.register_write(0x3D5, this, this.port3D5_write, this.port3D5_write16);

    io.register_read(0x3D4, this, this.port3D4_read);
    io.register_read(0x3D5, this, this.port3D5_read, this.port3D5_read16);

    // use same handlers for monochrome text-mode's alternate port addresses 0x3B4/0x3B5 as for the regular addresses (0x3D4/0x3D5)
    io.register_write(0x3B4, this, this.port3D4_write, this.port3D4_write16);
    io.register_write(0x3B5, this, this.port3D5_write, this.port3D5_write16);

    io.register_read(0x3B4, this, this.port3D4_read);
    io.register_read(0x3B5, this, this.port3D5_read, this.port3D5_read16);

    io.register_read(0x3CA, this, function() { dbg_log("3CA read", LOG_VGA); return 0; });

    // use same handler for monochrome text-mode's alternate port address 0x3BA as for its regular address (0x3DA)
    io.register_read(0x3DA, this, this.port3DA_read);
    io.register_read(0x3BA, this, this.port3DA_read);


    // Bochs VBE Extensions
    // http://wiki.osdev.org/Bochs_VBE_Extensions
    this.dispi_index = 0;
    this.dispi_enable_value = 0;

    io.register_write(0x1CE, this, undefined, this.port1CE_write);
    io.register_read(0x1CE, this, undefined, this.port1CE_read);

    io.register_write(0x1CF, this, undefined, this.port1CF_write);
    io.register_read(0x1CF, this, undefined, this.port1CF_read);
    // (the data register's aligned alias, as QEMU decodes it on x86: OVMF's
    // QemuVideoDxe uses it when the adapter has no MMIO BAR)
    io.register_write(0x1D0, this, undefined, this.port1CF_write);
    io.register_read(0x1D0, this, undefined, this.port1CF_read);


    // The frame buffer is device memory in the Rust core, which the guest
    // reaches at memory speed through the LFB, wherever BAR0 puts it
    this.lfb_region = machine.mmio_ram_allocate(this.vga_memory_size);
    dbg_assert(this.lfb_region >= 0, "no device memory for the VGA frame buffer");
    const vga_offset = machine.mmio_ram_backing(this.lfb_region) >>> 0;
    this.svga_memory = view(Uint8Array, machine.wasm_memory, vga_offset, this.vga_memory_size);
    this.lfb_address = 0;
    this.move_lfb(VGA_LFB_ADDRESS);

    this.diff_addr_min = this.vga_memory_size;
    this.diff_addr_max = 0;
    this.diff_plot_min = this.vga_memory_size;
    this.diff_plot_max = 0;

    /**
     * The RGBA picture in wasm memory, as { data, width, height }
     * @type {Object}
     */
    this.pixels = null;
    this.dest_buffer_offset = 0;

    this.vga_memory = new Uint8Array(4 * VGA_BANK_SIZE);
    this.plane0 = new Uint8Array(this.vga_memory.buffer, 0 * VGA_BANK_SIZE, VGA_BANK_SIZE);
    this.plane1 = new Uint8Array(this.vga_memory.buffer, 1 * VGA_BANK_SIZE, VGA_BANK_SIZE);
    this.plane2 = new Uint8Array(this.vga_memory.buffer, 2 * VGA_BANK_SIZE, VGA_BANK_SIZE);
    this.plane3 = new Uint8Array(this.vga_memory.buffer, 3 * VGA_BANK_SIZE, VGA_BANK_SIZE);
    this.pixel_buffer = new Uint8Array(VGA_PIXEL_BUFFER_SIZE);

    io.mmap_register(0xA0000, 0x20000,
        addr => this.vga_memory_read(addr),
        (addr, value) => this.vga_memory_write(addr, value),
    );

    if(!options || options.pci !== false)
    {
        machine.register_pci({
            pci_space: this.pci_space,
            pci_bars: this.pci_bars,
            pci_rom_size: this.pci_rom_size,
            pci_rom_address: this.pci_rom_address,
        });
    }
    if(!options || options.display_source !== false)
    {
        this.display.add_source(this);
    }
}

VGAScreen.prototype.get_state = function()
{
    var state = [];

    state[0] = this.vga_memory_size;
    state[1] = this.cursor_address;
    state[2] = this.cursor_scanline_start;
    state[3] = this.cursor_scanline_end;
    state[4] = this.max_cols;
    state[5] = this.max_rows;
    state[6] = this.vga_memory;
    state[7] = this.dac_state;
    state[8] = this.start_address;
    state[9] = this.graphical_mode;
    state[10] = this.vga256_palette;
    state[11] = this.latch_dword;
    state[12] = this.color_compare;
    state[13] = this.color_dont_care;
    state[14] = this.miscellaneous_graphics_register;
    state[15] = this.svga_width;
    state[16] = this.svga_height;
    state[17] = this.crtc_mode;
    state[18] = this.svga_enabled;
    state[19] = this.svga_bpp;
    state[20] = this.svga_bank_offset;
    state[21] = this.svga_offset;
    state[22] = this.index_crtc;
    state[23] = this.dac_color_index_write;
    state[24] = this.dac_color_index_read;
    state[25] = this.dac_map;
    state[26] = this.sequencer_index;
    state[27] = this.plane_write_bm;
    state[28] = this.sequencer_memory_mode;
    state[29] = this.graphics_index;
    state[30] = this.plane_read;
    state[31] = this.planar_mode;
    state[32] = this.planar_rotate_reg;
    state[33] = this.planar_bitmap;
    state[34] = this.max_scan_line;
    state[35] = this.miscellaneous_output_register;
    state[36] = this.port_3DA_value;
    state[37] = this.dispi_index;
    state[38] = this.dispi_enable_value;
    state[39] = this.svga_memory;
    // this.graphical_mode_is_linear
    state[41] = this.attribute_controller_index;
    state[42] = this.offset_register;
    state[43] = this.planar_setreset;
    state[44] = this.planar_setreset_enable;
    state[45] = this.start_address_latched;
    state[46] = this.crtc;
    state[47] = this.horizontal_display_enable_end;
    state[48] = this.horizontal_blank_start;
    state[49] = this.vertical_display_enable_end;
    state[50] = this.vertical_blank_start;
    state[51] = this.underline_location_register;
    state[52] = this.preset_row_scan;
    state[53] = this.offset_register;
    state[54] = this.palette_source;
    state[55] = this.attribute_mode;
    state[56] = this.color_plane_enable;
    state[57] = this.horizontal_panning;
    state[58] = this.color_select;
    state[59] = this.clocking_mode;
    state[60] = this.line_compare;
    state[61] = this.pixel_buffer;
    state[62] = this.dac_mask;
    state[63] = this.character_map_select;
    state[64] = this.font_page_ab_enabled;

    return state;
};

VGAScreen.prototype.set_state = function(state)
{
    this.vga_memory_size = state[0];
    this.cursor_address = state[1];
    this.cursor_scanline_start = state[2];
    this.cursor_scanline_end = state[3];
    this.max_cols = state[4];
    this.max_rows = state[5];
    state[6] && this.vga_memory.set(state[6]);
    this.dac_state = state[7];
    this.start_address = state[8];
    this.graphical_mode = state[9];
    this.vga256_palette = state[10];
    this.latch_dword = state[11];
    this.color_compare = state[12];
    this.color_dont_care = state[13];
    this.miscellaneous_graphics_register = state[14];
    this.svga_width = state[15];
    this.svga_height = state[16];
    this.crtc_mode = state[17];
    this.svga_enabled = state[18];
    this.svga_bpp = state[19];
    this.svga_bank_offset = state[20];
    this.svga_offset = state[21];
    this.index_crtc = state[22];
    this.dac_color_index_write = state[23];
    this.dac_color_index_read = state[24];
    this.dac_map = state[25];
    this.sequencer_index = state[26];
    this.plane_write_bm = state[27];
    this.sequencer_memory_mode = state[28];
    this.graphics_index = state[29];
    this.plane_read = state[30];
    this.planar_mode = state[31];
    this.planar_rotate_reg = state[32];
    this.planar_bitmap = state[33];
    this.max_scan_line = state[34];
    this.miscellaneous_output_register = state[35];
    this.port_3DA_value = state[36];
    this.dispi_index = state[37];
    this.dispi_enable_value = state[38];
    this.svga_memory.set(state[39]);
    // state[40];
    this.attribute_controller_index = state[41];
    this.offset_register = state[42];
    this.planar_setreset = state[43];
    this.planar_setreset_enable = state[44];
    this.start_address_latched = state[45];
    this.crtc.set(state[46]);
    this.horizontal_display_enable_end = state[47];
    this.horizontal_blank_start = state[48];
    this.vertical_display_enable_end = state[49];
    this.vertical_blank_start = state[50];
    this.underline_location_register = state[51];
    this.preset_row_scan = state[52];
    this.offset_register = state[53];
    this.palette_source = state[54];
    this.attribute_mode = state[55];
    this.color_plane_enable = state[56];
    this.horizontal_panning = state[57];
    this.color_select = state[58];
    this.clocking_mode = state[59];
    this.line_compare = state[60];
    state[61] && this.pixel_buffer.set(state[61]);
    this.dac_mask = state[62] === undefined ? 0xFF : state[62];
    this.character_map_select = state[63] === undefined ? 0 : state[63];
    this.font_page_ab_enabled = state[64] === undefined ? 0 : state[64];

    this.redisplay();
};

/**
 * Send the current mode, size, font and picture to the display again: after
 * a restore, or when an adapter that embeds the core hands the scanout back
 */
VGAScreen.prototype.redisplay = function()
{
    this.set_graphical_mode(this.graphical_mode);

    // Ensure set_size_graphical/set_size_graphical_text will update
    this.screen_width = 0;
    this.screen_height = 0;

    if(this.graphical_mode)
    {
        if(this.svga_enabled)
        {
            this.set_size_graphical(this.svga_width, this.svga_height, this.svga_width, this.svga_height, this.svga_bpp);
            this.update_layers();
        }
        else
        {
            this.update_vga_size();
            this.update_layers();
            this.complete_replot();
        }
    }
    else
    {
        this.display.clear_text_state();
        this.set_font_bitmap(true);
        this.set_size_text(this.max_cols, this.max_rows);
        this.set_font_page();
        this.update_cursor_scanline();
        this.update_cursor();
    }
    this.complete_redraw();
    // (now, not at the next vblank: a restored machine may stay stopped)
    this.flush_text_redraw();
};

/**
 * Decode the linear frame buffer at `base`, where the guest put BAR0 (the
 * core leaves it unmapped over RAM or below 1 MiB: a cleared BAR)
 * @param {number} base
 */
VGAScreen.prototype.move_lfb = function(base)
{
    this.lfb_address = base >>> 0;
    this.machine.mmio_ram_map(this.lfb_region, this.lfb_address);
};

VGAScreen.prototype.vga_memory_read = function(addr)
{
    if(this.svga_enabled)
    {
        // vbe banked mode (accessing svga memory through the regular vga memory range)
        return this.machine.mmio_ram_read8(this.lfb_region, (addr - 0xA0000 | this.svga_bank_offset) >>> 0);
    }

    var memory_space_select = this.miscellaneous_graphics_register >> 2 & 0x3;
    addr -= VGA_HOST_MEMORY_SPACE_START[memory_space_select];

    // VGA chip only decodes addresses within the selected memory space.
    if(addr < 0 || addr >= VGA_HOST_MEMORY_SPACE_SIZE[memory_space_select])
    {
        dbg_log("vga read outside memory space: addr:" + h(addr >>> 0), LOG_VGA);
        return 0;
    }

    this.latch_dword = this.plane0[addr];
    this.latch_dword |= this.plane1[addr] << 8;
    this.latch_dword |= this.plane2[addr] << 16;
    this.latch_dword |= this.plane3[addr] << 24;

    if(this.planar_mode & 0x08)
    {
        // read mode 1
        var reading = 0xFF;

        if(this.color_dont_care & 0x1)
        {
            reading &= this.plane0[addr] ^ ~(this.color_compare & 0x1 ? 0xFF : 0x00);
        }
        if(this.color_dont_care & 0x2)
        {
            reading &= this.plane1[addr] ^ ~(this.color_compare & 0x2 ? 0xFF : 0x00);
        }
        if(this.color_dont_care & 0x4)
        {
            reading &= this.plane2[addr] ^ ~(this.color_compare & 0x4 ? 0xFF : 0x00);
        }
        if(this.color_dont_care & 0x8)
        {
            reading &= this.plane3[addr] ^ ~(this.color_compare & 0x8 ? 0xFF : 0x00);
        }

        return reading;
    }
    else
    {
        // read mode 0

        var plane = this.plane_read;
        if(!this.graphical_mode)
        {
            // We store all text data linearly and font data in plane 2.
            // TODO: works well for planes 0 and 2, but what about plane 1?
            plane &= 0x3;
        }
        else if(this.sequencer_memory_mode & 0x8)
        {
            // Chain 4
            plane = addr & 0x3;
            addr &= ~0x3;
        }
        else if(this.planar_mode & 0x10)
        {
            // Odd/Even host read
            plane = addr & 0x1;
            addr &= ~0x1;
        }
        return this.vga_memory[plane << 16 | addr];
    }
};

VGAScreen.prototype.vga_memory_write = function(addr, value)
{
    if(this.svga_enabled)
    {
        // vbe banked mode (accessing svga memory through the regular vga memory range)
        this.machine.mmio_ram_write8(this.lfb_region, (addr - 0xA0000 | this.svga_bank_offset) >>> 0, value);
        return;
    }

    var memory_space_select = this.miscellaneous_graphics_register >> 2 & 0x3;
    addr -= VGA_HOST_MEMORY_SPACE_START[memory_space_select];

    if(addr < 0 || addr >= VGA_HOST_MEMORY_SPACE_SIZE[memory_space_select])
    {
        dbg_log("vga write outside memory space: addr:" + h(addr >>> 0) + ", value:" + h(value), LOG_VGA);
        return;
    }

    if(this.graphical_mode)
    {
        this.vga_memory_write_graphical(addr, value);
    }
    else if(!(this.plane_write_bm & 0x3))
    {
        if(this.plane_write_bm & 0x4)
        {
            // write to plane 2 (font-bitmap)
            this.plane2[addr] = value;
        }
    }
    else
    {
        this.vga_memory_write_text_mode(addr, value);
    }
};

VGAScreen.prototype.vga_memory_write_graphical = function(addr, value)
{
    var plane_dword;
    var write_mode = this.planar_mode & 3;
    var bitmask = this.apply_feed(this.planar_bitmap);
    var setreset_dword = this.apply_expand(this.planar_setreset);
    var setreset_enable_dword = this.apply_expand(this.planar_setreset_enable);

    // Write modes - see http://www.osdever.net/FreeVGA/vga/graphreg.htm#05
    switch(write_mode)
    {
        case 0:
            value = this.apply_rotate(value);
            plane_dword = this.apply_feed(value);
            plane_dword = this.apply_setreset(plane_dword, setreset_enable_dword);
            plane_dword = this.apply_logical(plane_dword, this.latch_dword);
            plane_dword = this.apply_bitmask(plane_dword, bitmask);
            break;
        case 1:
            plane_dword = this.latch_dword;
            break;
        case 2:
            plane_dword = this.apply_expand(value);
            plane_dword = this.apply_logical(plane_dword, this.latch_dword);
            plane_dword = this.apply_bitmask(plane_dword, bitmask);
            break;
        case 3:
            value = this.apply_rotate(value);
            bitmask &= this.apply_feed(value);
            plane_dword = setreset_dword;
            plane_dword = this.apply_bitmask(plane_dword, bitmask);
            break;
    }

    var plane_select = 0xF;

    switch(this.sequencer_memory_mode & 0xC)
    {
        // Odd/Even (aka chain 2)
        case 0x0:
            plane_select = 0x5 << (addr & 0x1);
            addr &= ~0x1;
            break;

        // Chain 4
        // Note: FreeVGA may have mistakenly stated that this bit field is
        // for system read only, yet the IBM Open Source Graphics Programmer's
        // Reference Manual explicitly states "both read and write".
        case 0x8:
        case 0xC:
            plane_select = 1 << (addr & 0x3);
            addr &= ~0x3;
            break;
    }

    // Plane masks take precedence
    // See: http://www.osdever.net/FreeVGA/vga/seqreg.htm#02
    plane_select &= this.plane_write_bm;

    if(plane_select & 0x1) this.plane0[addr] = (plane_dword >> 0) & 0xFF;
    if(plane_select & 0x2) this.plane1[addr] = (plane_dword >> 8) & 0xFF;
    if(plane_select & 0x4) this.plane2[addr] = (plane_dword >> 16) & 0xFF;
    if(plane_select & 0x8) this.plane3[addr] = (plane_dword >> 24) & 0xFF;

    var pixel_addr = this.vga_addr_to_pixel(addr);
    this.partial_replot(pixel_addr, pixel_addr + 7);
};

/**
 * Copies data_byte into the four planes, with each plane
 * represented by an 8-bit field inside the dword.
 * @param {number} data_byte
 * @return {number} 32-bit number representing the bytes for each plane.
 */
VGAScreen.prototype.apply_feed = function(data_byte)
{
    var dword = data_byte;
    dword |= data_byte << 8;
    dword |= data_byte << 16;
    dword |= data_byte << 24;
    return dword;
};

/**
 * Expands bits 0 to 3 to ocupy bits 0 to 31. Each
 * bit is expanded to 0xFF if set or 0x00 if clear.
 * @param {number} data_byte
 * @return {number} 32-bit number representing the bytes for each plane.
 */
VGAScreen.prototype.apply_expand = function(data_byte)
{
    var dword = data_byte & 0x1 ? 0xFF : 0x00;
    dword |= (data_byte & 0x2 ? 0xFF : 0x00) << 8;
    dword |= (data_byte & 0x4 ? 0xFF : 0x00) << 16;
    dword |= (data_byte & 0x8 ? 0xFF : 0x00) << 24;
    return dword;
};

/**
 * Planar Write - Barrel Shifter
 * @param {number} data_byte
 * @return {number}
 * @see {@link http://www.phatcode.net/res/224/files/html/ch25/25-01.html#Heading3}
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#03}
 */
VGAScreen.prototype.apply_rotate = function(data_byte)
{
    var wrapped = data_byte | (data_byte << 8);
    var count = this.planar_rotate_reg & 0x7;
    var shifted = wrapped >>> count;
    return shifted & 0xFF;
};

/**
 * Planar Write - Set / Reset Circuitry
 * @param {number} data_dword
 * @param {number} enable_dword
 * @return {number}
 * @see {@link http://www.phatcode.net/res/224/files/html/ch25/25-03.html#Heading5}
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#00}
 */
VGAScreen.prototype.apply_setreset = function(data_dword, enable_dword)
{
    var setreset_dword = this.apply_expand(this.planar_setreset);
    data_dword |= enable_dword & setreset_dword;
    data_dword &= ~enable_dword | setreset_dword;
    return data_dword;
};

/**
 * Planar Write - ALU Unit
 * @param {number} data_dword
 * @param {number} latch_dword
 * @return {number}
 * @see {@link http://www.phatcode.net/res/224/files/html/ch24/24-01.html#Heading3}
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#03}
 */
VGAScreen.prototype.apply_logical = function(data_dword, latch_dword)
{
    switch(this.planar_rotate_reg & 0x18)
    {
        case 0x08:
            return data_dword & latch_dword;
        case 0x10:
            return data_dword | latch_dword;
        case 0x18:
            return data_dword ^ latch_dword;
    }
    return data_dword;
};

/**
 * Planar Write - Bitmask Unit
 * @param {number} data_dword
 * @param {number} bitmask_dword
 * @return {number}
 * @see {@link http://www.phatcode.net/res/224/files/html/ch25/25-01.html#Heading2}
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm#08}
 */
VGAScreen.prototype.apply_bitmask = function(data_dword, bitmask_dword)
{
    var plane_dword = bitmask_dword & data_dword;
    plane_dword |= ~bitmask_dword & this.latch_dword;
    return plane_dword;
};

VGAScreen.prototype.text_mode_redraw = function()
{
    this.text_redraw_pending = false;

    const split_screen_row = this.scan_line_to_screen_row(this.line_compare);
    const row_offset = Math.max(0, (this.offset_register * 2 - this.max_cols) * 2);
    const blink_enabled = this.attribute_mode & 1 << 3;
    const fg_color_mask = this.font_page_ab_enabled ? 7 : 0xF;
    const bg_color_mask = blink_enabled ? 7 : 0xF;
    const FLAG_BLINKING = DISPLAY_FLAG_BLINKING;
    const FLAG_FONT_PAGE_B = DISPLAY_FLAG_FONT_PAGE_B;

    let addr = this.start_address << 1;

    for(let row = 0; row < this.max_rows; row++)
    {
        if(row === split_screen_row)
        {
            addr = 0;
        }

        for(let col = 0; col < this.max_cols; col++)
        {
            const chr = this.vga_memory[addr];
            const color = this.vga_memory[addr | 1];
            const blinking = blink_enabled && (color & 1 << 7);
            const font_page_b = this.font_page_ab_enabled && !(color & 1 << 3);
            const flags = (blinking ? FLAG_BLINKING : 0) | (font_page_b ? FLAG_FONT_PAGE_B : 0);

            this.display.put_char(row, col, chr, flags,
                this.vga256_palette[this.dac_mask & this.dac_map[color >> 4 & bg_color_mask]],
                this.vga256_palette[this.dac_mask & this.dac_map[color & fg_color_mask]]);

            addr += 2;
        }

        addr += row_offset;
    }
};

/** The text screen's redraw that is pending, now */
VGAScreen.prototype.flush_text_redraw = function()
{
    if(this.text_redraw_pending && !this.graphical_mode)
    {
        this.text_mode_redraw();
    }
};

VGAScreen.prototype.vga_memory_write_text_mode = function(addr, value)
{
    if(this.vga_memory[addr] === value)
    {
        // The display has this cell already: scrolling and programs that
        // draw the whole screen write many bytes that stay the same
        return;
    }

    this.vga_memory[addr] = value;

    const max_cols = Math.max(this.max_cols, this.offset_register * 2);
    let row;
    let col;

    if((addr >> 1) >= this.start_address)
    {
        const memory_start = (addr >> 1) - this.start_address;
        row = memory_start / max_cols | 0;
        col = memory_start % max_cols;
    }
    else
    {
        const memory_start = addr >> 1;
        row = (memory_start / max_cols | 0) + this.scan_line_to_screen_row(this.line_compare);
        col = memory_start % max_cols;
    }

    dbg_assert(row >= 0 && col >= 0);

    if(col >= this.max_cols || row >= this.max_rows)
    {
        return;
    }

    let chr;
    let color;

    // XXX: Should handle 16 bit write if possible
    if(addr & 1)
    {
        color = value;
        chr = this.vga_memory[addr & ~1];
    }
    else
    {
        chr = value;
        color = this.vga_memory[addr | 1];
    }
    const blink_enabled = this.attribute_mode & 1 << 3;
    const blinking = blink_enabled && (color & 1 << 7);
    const font_page_b = this.font_page_ab_enabled && !(color & 1 << 3);
    const flags = (blinking ? DISPLAY_FLAG_BLINKING : 0) | (font_page_b ? DISPLAY_FLAG_FONT_PAGE_B : 0);
    const fg_color_mask = this.font_page_ab_enabled ? 7 : 0xF;
    const bg_color_mask = blink_enabled ? 7 : 0xF;

    this.display.put_char(row, col, chr, flags,
        this.vga256_palette[this.dac_mask & this.dac_map[color >> 4 & bg_color_mask]],
        this.vga256_palette[this.dac_mask & this.dac_map[color & fg_color_mask]]);
};

VGAScreen.prototype.update_cursor = function()
{
    const max_cols = Math.max(this.max_cols, this.offset_register * 2);
    let row;
    let col;

    if(this.cursor_address >= this.start_address)
    {
        row = (this.cursor_address - this.start_address) / max_cols | 0;
        col = (this.cursor_address - this.start_address) % max_cols;
    }
    else
    {
        row = (this.cursor_address / max_cols | 0) + this.scan_line_to_screen_row(this.line_compare);
        col = this.cursor_address % max_cols;
    }

    dbg_assert(row >= 0 && col >= 0);

    // NOTE: is allowed to be out of bounds
    this.display.update_cursor(row, col);
};

VGAScreen.prototype.complete_redraw = function()
{
    dbg_log("complete redraw", LOG_VGA);

    if(this.graphical_mode)
    {
        if(this.svga_enabled)
        {
            this.machine.mmio_ram_mark_dirty(this.lfb_region);
        }
        else
        {
            this.diff_addr_min = 0;
            this.diff_addr_max = VGA_PIXEL_BUFFER_SIZE;
        }
    }
    else
    {
        this.text_redraw_pending = true;
    }
};

VGAScreen.prototype.complete_replot = function()
{
    dbg_log("complete replot", LOG_VGA);

    if(!this.graphical_mode || this.svga_enabled)
    {
        return;
    }

    this.diff_plot_min = 0;
    this.diff_plot_max = VGA_PIXEL_BUFFER_SIZE;

    this.complete_redraw();
};

VGAScreen.prototype.partial_redraw = function(min, max)
{
    if(min < this.diff_addr_min) this.diff_addr_min = min;
    if(max > this.diff_addr_max) this.diff_addr_max = max;
};

VGAScreen.prototype.partial_replot = function(min, max)
{
    if(min < this.diff_plot_min) this.diff_plot_min = min;
    if(max > this.diff_plot_max) this.diff_plot_max = max;

    this.partial_redraw(min, max);
};

VGAScreen.prototype.reset_diffs = function()
{
    this.diff_addr_min = this.vga_memory_size;
    this.diff_addr_max = 0;
    this.diff_plot_min = this.vga_memory_size;
    this.diff_plot_max = 0;
};

VGAScreen.prototype.destroy = function()
{

};

VGAScreen.prototype.vga_bytes_per_line = function()
{
    var bytes_per_line = this.offset_register << 2;
    if(this.underline_location_register & 0x40) bytes_per_line <<= 1;
    else if(this.crtc_mode & 0x40) bytes_per_line >>>= 1;
    return bytes_per_line;
};

VGAScreen.prototype.vga_addr_shift_count = function()
{
    // Count in multiples of 0x40 for convenience
    // Left shift 2 for word mode - 2 bytes per dot clock
    var shift_count = 0x80;

    // Left shift 3 for byte mode - 1 byte per dot clock
    shift_count += ~this.underline_location_register & this.crtc_mode & 0x40;

    // Left shift 1 for doubleword mode - 4 bytes per dot clock
    shift_count -= this.underline_location_register & 0x40;

    // But shift one less if PEL width mode - 2 dot clocks per pixel
    shift_count -= this.attribute_mode & 0x40;

    return shift_count >>> 6;
};

VGAScreen.prototype.vga_addr_to_pixel = function(addr)
{
    var shift_count = this.vga_addr_shift_count();

    // Undo effects of substituted bits 13 and 14
    // Assumptions:
    //  - max_scan_line register is set to the values shown below
    //  - Each scan line stays within the offset alignment
    //  - No panning and no page flipping after drawing
    if(~this.crtc_mode & 0x3)
    {
        var pixel_addr = addr - this.start_address;

        // Remove substituted bits
        pixel_addr &= this.crtc_mode << 13 | ~0x6000;

        // Convert to 1 pixel per address
        pixel_addr <<= shift_count;

        // Decompose address
        var row = pixel_addr / this.virtual_width | 0;
        var col = pixel_addr % this.virtual_width;

        switch(this.crtc_mode & 0x3)
        {
            case 0x2:
                // Alternating rows using bit 13
                // Assumes max scan line = 1
                row = row << 1 | (addr >> 13 & 0x1);
                break;
            case 0x1:
                // Alternating rows using bit 14
                // Assumes max scan line = 3
                row = row << 1 | (addr >> 14 & 0x1);
                break;
            case 0x0:
                // Cycling through rows using bit 13 and 14
                // Assumes max scan line = 3
                row = row << 2 | (addr >> 13 & 0x3);
                break;
        }

        // Reassemble address
        return row * this.virtual_width + col + (this.start_address << shift_count);
    }
    else
    {
        // Convert to 1 pixel per address
        return addr << shift_count;
    }
};

VGAScreen.prototype.scan_line_to_screen_row = function(scan_line)
{
    // Double scanning. The clock to the row scan counter is halved
    // so it is not affected by the memory address bit substitutions below
    if(this.max_scan_line & 0x80)
    {
        scan_line >>>= 1;
    }

    // Maximum scan line, aka scan lines per character row
    // This is the number of repeats - 1 for graphic modes
    var repeat_factor = 1 + (this.max_scan_line & 0x1F);
    scan_line = Math.ceil(scan_line / repeat_factor);

    // Odd and Even Row Scan Counter
    // Despite repeated address counter values, because bit 13 of the shifted
    // address is substituted with bit 0 of the row scan counter, a different
    // display buffer address is generated instead of repeated
    // Assumes maximum scan line register is set to 2 or 4.
    // Note: can't assert this as register values may not be fully programmed.
    if(!(this.crtc_mode & 0x1))
    {
        scan_line <<= 1;
    }

    // Undo effects of substituted bit 14
    // Assumes maximum scan line register is set to 2 or 4
    // Note: can't assert this as register values may not be fully programmed.
    // Other maximum scan line register values would result in weird addressing
    // anyway
    if(!(this.crtc_mode & 0x2))
    {
        scan_line <<= 1;
    }

    return scan_line;
};

/**
 * @param {number} cols_count
 * @param {number} rows_count
 */
VGAScreen.prototype.set_size_text = function(cols_count, rows_count)
{
    dbg_assert(!this.graphical_mode);
    this.max_cols = cols_count;
    this.max_rows = rows_count;

    this.display.set_size_text(cols_count, rows_count);
    // A new size empties the display's screen, and the rows' layout follows
    // the geometry (writes of unchanged cells do not send them again)
    this.text_redraw_pending = true;
};

VGAScreen.prototype.set_size_graphical = function(width, height, virtual_width, virtual_height, bpp)
{
    dbg_assert(this.graphical_mode);

    virtual_width = Math.max(virtual_width, 1);
    virtual_height = Math.max(virtual_height, 1);

    const needs_update =
        this.screen_width !== width ||
        this.screen_height !== height ||
        this.virtual_width !== virtual_width ||
        this.virtual_height !== virtual_height;

    if(needs_update)
    {
        this.screen_width = width;
        this.screen_height = height;
        this.virtual_width = virtual_width;
        this.virtual_height = virtual_height;

        const size = virtual_width * virtual_height;
        this.dest_buffer_offset = this.machine.mmio_ram_allocate_pixels(this.lfb_region, size) >>> 0;
        this.create_pixel_view();
        this.machine.mmio_ram_mark_dirty(this.lfb_region);
    }

    if(needs_update || !this.size_reported)
    {
        this.size_reported = true;
        this.display.set_size_graphical(width, height, virtual_width, virtual_height, bpp);
    }
};

/**
 * Text or graphics, as far as the sink is concerned. After text, a graphics
 * mode owes the sink its size and all of its pixels again: showing the text
 * may have taken the canvas.
 * @param {boolean} graphical
 */
VGAScreen.prototype.set_graphical_mode = function(graphical)
{
    this.graphical_mode = graphical;
    if(!graphical)
    {
        this.size_reported = false;
    }
    this.display.set_mode(graphical);
};

/**
 * The picture the sink draws from: a view of the RGBA buffer in wasm memory
 * (possibly shared memory, which the sink has to copy out of)
 */
VGAScreen.prototype.create_pixel_view = function()
{
    this.pixels = {
        data: new Uint8ClampedArray(this.machine.wasm_memory.buffer, this.dest_buffer_offset,
            4 * this.virtual_width * this.virtual_height),
        width: this.virtual_width,
        height: this.virtual_height,
    };
};

VGAScreen.prototype.update_vga_size = function()
{
    if(this.svga_enabled)
    {
        return;
    }

    var horizontal_characters = Math.min(1 + this.horizontal_display_enable_end,
        this.horizontal_blank_start);
    var vertical_scans = Math.min(1 + this.vertical_display_enable_end,
        this.vertical_blank_start);

    if(!horizontal_characters || !vertical_scans)
    {
        // Don't update if width or height is zero.
        // These happen when registers are not fully configured yet.
        return;
    }

    if(this.graphical_mode)
    {
        var screen_width = horizontal_characters << 3;

        // Offset is half the number of bytes/words/dwords (depending on clocking mode)
        // of display memory that each logical line occupies.
        // However, the number of pixels latched, regardless of addressing mode,
        // should always 8 pixels per character clock (except for 8 bit PEL width, in which
        // case 4 pixels).
        var virtual_width = this.offset_register << 4;
        var bpp = 4;

        // Pixel Width / PEL Width / Clock Select
        if(this.attribute_mode & 0x40)
        {
            screen_width >>>= 1;
            virtual_width >>>= 1;
            bpp = 8;
        }
        else if(this.attribute_mode & 0x2)
        {
            bpp = 1;
        }

        var screen_height = this.scan_line_to_screen_row(vertical_scans);

        // The virtual buffer height is however many rows of data that can fit.
        // Previously drawn graphics outside of current memory address space can
        // still be drawn by setting start_address. The address at
        // VGA_HOST_MEMORY_SPACE_START[memory_space_select] is mapped to the first
        // byte of the frame buffer. Verified on some hardware.
        // Depended on by: Windows 98 start screen
        var available_bytes = VGA_HOST_MEMORY_SPACE_SIZE[0];

        const bytes_per_line = this.vga_bytes_per_line();
        const virtual_height = bytes_per_line ? Math.ceil(available_bytes / bytes_per_line) : screen_height;

        this.set_size_graphical(screen_width, screen_height, virtual_width, virtual_height, bpp);

        this.latch_start_address();
        this.update_layers();
    }
    else
    {
        if(this.max_scan_line & 0x80)
        {
            // Double scanning means that half of those scan lines
            // are just repeats
            vertical_scans >>>= 1;
        }

        var height = vertical_scans / (1 + (this.max_scan_line & 0x1F)) | 0;

        if(horizontal_characters && height)
        {
            this.set_size_text(horizontal_characters, height);
        }
    }
};

VGAScreen.prototype.update_layers = function()
{
    if(!this.graphical_mode)
    {
        this.text_redraw_pending = true;
    }

    if(this.svga_enabled)
    {
        this.layers = [];
        return;
    }

    if(!this.virtual_width || !this.screen_width)
    {
        // Avoid division by zero
        return;
    }

    if(!this.palette_source || (this.clocking_mode & 0x20))
    {
        // Palette source and screen disable bits = draw nothing
        // See http://www.phatcode.net/res/224/files/html/ch29/29-05.html#Heading6
        // and http://www.osdever.net/FreeVGA/vga/seqreg.htm#01
        this.layers = [];
        this.display.clear_screen();
        return;
    }

    var start_addr = this.start_address_latched;

    var pixel_panning = this.horizontal_panning;
    if(this.attribute_mode & 0x40)
    {
        pixel_panning >>>= 1;
    }

    var byte_panning = this.preset_row_scan >> 5 & 0x3;
    var pixel_addr_start = this.vga_addr_to_pixel(start_addr + byte_panning);

    var start_buffer_row = pixel_addr_start / this.virtual_width | 0;
    var start_buffer_col = pixel_addr_start % this.virtual_width + pixel_panning;

    var split_screen_row = this.scan_line_to_screen_row(1 + this.line_compare);
    split_screen_row = Math.min(split_screen_row, this.screen_height);

    var split_buffer_height = this.screen_height - split_screen_row;

    this.layers = [];

    for(var x = -start_buffer_col, y = 0; x < this.screen_width; x += this.virtual_width, y++)
    {
        this.layers.push({
            pixels: this.pixels,
            screen_x: x,
            screen_y: 0,
            buffer_x: 0,
            buffer_y: start_buffer_row + y,
            buffer_width: this.virtual_width,
            buffer_height: split_screen_row,
        });
    }

    var start_split_col = 0;
    if(!(this.attribute_mode & 0x20))
    {
        // Pixel panning mode. Allow panning for the lower split screen
        start_split_col = this.vga_addr_to_pixel(byte_panning) + pixel_panning;
    }

    for(var x = -start_split_col, y = 0; x < this.screen_width; x += this.virtual_width, y++)
    {
        this.layers.push({
            pixels: this.pixels,
            screen_x: x,
            screen_y: split_screen_row,
            buffer_x: 0,
            buffer_y: y,
            buffer_width: this.virtual_width,
            buffer_height: split_buffer_height,
        });
    }
};

/**
 * The start address takes effect at the next vertical retrace (page flipping)
 */
VGAScreen.prototype.latch_start_address = function()
{
    if(this.start_address_latched !== this.start_address)
    {
        this.start_address_latched = this.start_address;
        this.update_layers();
    }
};

/** @override */
VGAScreen.prototype.invalidate = function()
{
    this.complete_redraw();
    this.flush_text_redraw();
};

/** @override */
VGAScreen.prototype.on_vblank = function()
{
    this.retrace_pending = true;
    this.latch_start_address();
    this.flush_text_redraw();
};

/**
 * The refresh period the CRTC is programmed for: the dot clock (misc output
 * bits 2-3, halved by clocking mode bit 3) over horizontal total times
 * character width times vertical total. 70 Hz for 400-line modes, 60 Hz for
 * 480-line ones.
 * @override
 */
VGAScreen.prototype.vblank_period = function()
{
    if(this.svga_enabled)
    {
        return 1000 / 60;
    }
    const clock = (this.miscellaneous_output_register >> 2 & 3) === 1 ? 28.322e6 : 25.175e6;
    const dot_clock = this.clocking_mode & 0x08 ? clock / 2 : clock;
    const char_width = this.clocking_mode & 0x01 ? 8 : 9;
    const hz = dot_clock / ((this.crtc[0] + 5) * char_width * this.vertical_total());
    // not programmed yet
    return hz >= 40 && hz <= 120 ? 1000 / hz : 1000 / 70;
};

/**
 * @return {number} scanlines per frame
 */
VGAScreen.prototype.vertical_total = function()
{
    const overflow = this.crtc[7];
    return (this.crtc[6] | (overflow & 0x01) << 8 | (overflow & 0x20) << 4) + 2;
};

/**
 * How long bit 3 of 0x3DA reads as set after a retrace starts: vertical
 * retrace start to end, 2 scanlines in the standard modes
 * @return {number} milliseconds
 */
VGAScreen.prototype.retrace_duration = function()
{
    const period = this.vblank_period();
    if(this.svga_enabled)
    {
        return period * 2 / 449;
    }
    const overflow = this.crtc[7];
    const start = this.crtc[0x10] | (overflow & 0x04) << 6 | (overflow & 0x80) << 2;
    const lines = (this.crtc[0x11] - start) & 0xF || 16;
    return period * lines / this.vertical_total();
};

VGAScreen.prototype.update_cursor_scanline = function()
{
    const disabled = this.cursor_scanline_start & 0x20;
    const max = this.max_scan_line & 0x1F;
    const start = Math.min(max, this.cursor_scanline_start & 0x1F);
    const end = Math.min(max, this.cursor_scanline_end & 0x1F);
    const visible = !disabled && start < end;
    this.display.update_cursor_scanline(start, end, visible);
};

/**
 * Attribute controller register / index write
 * @see {@link http://www.osdever.net/FreeVGA/vga/attrreg.htm}
 * @see {@link http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf} page 89
 * @see {@link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-hsw-display_0.pdf} page 48
 */
VGAScreen.prototype.port3C0_write = function(value)
{
    if(this.attribute_controller_index === -1)
    {
        dbg_log("attribute controller index register: " + h(value), LOG_VGA);
        this.attribute_controller_index = value & 0x1F;
        dbg_log("attribute actual index: " + h(this.attribute_controller_index), LOG_VGA);

        if(this.palette_source !== (value & 0x20))
        {
            // A method of blanking the screen.
            // See http://www.phatcode.net/res/224/files/html/ch29/29-05.html#Heading6
            this.palette_source = value & 0x20;
            this.update_layers();
        }
    }
    else
    {
        if(this.attribute_controller_index < 0x10)
        {
            dbg_log("internal palette: " + h(this.attribute_controller_index) + " -> " + h(value), LOG_VGA);
            this.dac_map[this.attribute_controller_index] = value;

            if(!(this.attribute_mode & 0x40))
            {
                this.complete_redraw();
            }
        }
        else
        switch(this.attribute_controller_index)
        {
            case 0x10:
                dbg_log("3C0 / attribute mode control: " + h(value), LOG_VGA);
                if(this.attribute_mode !== value)
                {
                    var previous_mode = this.attribute_mode;
                    this.attribute_mode = value;

                    if(this.svga_enabled && !(this.dispi_enable_value & 1))
                    {
                        // Commit the deferred VBE disable (see port1CF_write case 4)
                        this.svga_enabled = false;
                        this.svga_bank_offset = 0;
                    }

                    const was_graphical = this.graphical_mode;
                    const is_graphical = (value & 0x1) !== 0;
                    if(!this.svga_enabled && this.graphical_mode !== is_graphical)
                    {
                        this.set_graphical_mode(is_graphical);
                    }

                    if((previous_mode ^ value) & 0x40)
                    {
                        // PEL width changed. Pixel Buffer now invalidated
                        this.complete_replot();
                    }

                    this.update_vga_size();

                    // Data stored in image buffer are invalidated
                    this.complete_redraw();

                    // Graphics modes draw into plane 2, where the font lives
                    this.set_font_bitmap(was_graphical && !this.graphical_mode);
                }
                break;
            case 0x12:
                dbg_log("3C0 / color plane enable: " + h(value), LOG_VGA);
                if(this.color_plane_enable !== value)
                {
                    this.color_plane_enable = value;

                    // Data stored in image buffer are invalidated
                    this.complete_redraw();
                }
                break;
            case 0x13:
                dbg_log("3C0 / horizontal panning: " + h(value), LOG_VGA);
                if(this.horizontal_panning !== value)
                {
                    this.horizontal_panning = value & 0xF;
                    this.update_layers();
                }
                break;
            case 0x14:
                dbg_log("3C0 / color select: " + h(value), LOG_VGA);
                if(this.color_select !== value)
                {
                    this.color_select = value;

                    // Data stored in image buffer are invalidated
                    this.complete_redraw();
                }
                break;
            default:
                dbg_log("3C0 / attribute controller write " + h(this.attribute_controller_index) + ": " + h(value), LOG_VGA);
        }

        this.attribute_controller_index = -1;
    }
};

VGAScreen.prototype.port3C0_read = function()
{
    dbg_log("3C0 read", LOG_VGA);
    return (this.attribute_controller_index | this.palette_source) & 0xFF;
};

VGAScreen.prototype.port3C0_read16 = function()
{
    dbg_log("3C0 read16", LOG_VGA);
    return this.port3C0_read() | this.port3C1_read() << 8 & 0xFF00;
};

VGAScreen.prototype.port3C1_read = function()
{
    if(this.attribute_controller_index < 0x10)
    {
        dbg_log("3C1 / internal palette read: " + h(this.attribute_controller_index) +
            " -> " + h(this.dac_map[this.attribute_controller_index]), LOG_VGA);
        return this.dac_map[this.attribute_controller_index] & 0xFF;
    }

    switch(this.attribute_controller_index)
    {
        case 0x10:
            dbg_log("3C1 / attribute mode read: " + h(this.attribute_mode), LOG_VGA);
            return this.attribute_mode;
        case 0x12:
            dbg_log("3C1 / color plane enable read: " + h(this.color_plane_enable), LOG_VGA);
            return this.color_plane_enable;
        case 0x13:
            dbg_log("3C1 / horizontal panning read: " + h(this.horizontal_panning), LOG_VGA);
            return this.horizontal_panning;
        case 0x14:
            dbg_log("3C1 / color select read: " + h(this.color_select), LOG_VGA);
            return this.color_select;
        default:
            dbg_log("3C1 / attribute controller read " + h(this.attribute_controller_index), LOG_VGA);
    }
    return 0xFF;

};

VGAScreen.prototype.port3C2_write = function(value)
{
    dbg_log("3C2 / miscellaneous output register = " + h(value), LOG_VGA);
    this.miscellaneous_output_register = value;
};

VGAScreen.prototype.port3C4_write = function(value)
{
    this.sequencer_index = value;
};

VGAScreen.prototype.port3C4_read = function()
{
    return this.sequencer_index;
};

/**
 * Sequencer register writes
 * @see {@link http://www.osdever.net/FreeVGA/vga/seqreg.htm}
 * @see {@link http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf} page 47
 * @see {@link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-hsw-display_0.pdf} page 19
 */
VGAScreen.prototype.port3C5_write = function(value)
{
    switch(this.sequencer_index)
    {
        case 0x01:
            dbg_log("clocking mode: " + h(value), LOG_VGA);
            var previous_clocking_mode = this.clocking_mode;
            this.clocking_mode = value;
            if((previous_clocking_mode ^ value) & 0x20)
            {
                // Screen disable bit modified
                this.update_layers();
            }
            this.set_font_bitmap(false);
            break;
        case 0x02:
            dbg_log("plane write mask: " + h(value), LOG_VGA);
            var previous_plane_write_bm = this.plane_write_bm;
            this.plane_write_bm = value;
            if(!this.graphical_mode && previous_plane_write_bm & 0x4 && !(this.plane_write_bm & 0x4))
            {
                // End of font plane 2 write access
                this.set_font_bitmap(true);
            }
            break;
        case 0x03:
            dbg_log("character map select: " + h(value), LOG_VGA);
            var previous_character_map_select = this.character_map_select;
            this.character_map_select = value;
            if(!this.graphical_mode && previous_character_map_select !== value)
            {
                this.set_font_page();
            }
            break;
        case 0x04:
            dbg_log("sequencer memory mode: " + h(value), LOG_VGA);
            this.sequencer_memory_mode = value;
            break;
        default:
            dbg_log("3C5 / sequencer write " + h(this.sequencer_index) + ": " + h(value), LOG_VGA);
    }
};

VGAScreen.prototype.port3C5_read = function()
{
    dbg_log("3C5 / sequencer read " + h(this.sequencer_index), LOG_VGA);

    switch(this.sequencer_index)
    {
        case 0x01:
            return this.clocking_mode;
        case 0x02:
            return this.plane_write_bm;
        case 0x03:
            return this.character_map_select;
        case 0x04:
            return this.sequencer_memory_mode;
        case 0x06:
            return 0x12;
        default:
    }
    return 0;
};

VGAScreen.prototype.port3C6_write = function(data)
{
    if(this.dac_mask !== data)
    {
        this.dac_mask = data;
        this.complete_redraw();
    }
};

VGAScreen.prototype.port3C6_read = function()
{
    return this.dac_mask;
};

VGAScreen.prototype.port3C7_write = function(index)
{
    // index for reading the DAC
    dbg_log("3C7 write: " + h(index), LOG_VGA);
    this.dac_color_index_read = index * 3;
    this.dac_state &= 0x0;
};

VGAScreen.prototype.port3C7_read = function()
{
    // prepared to accept reads or writes
    return this.dac_state;
};

VGAScreen.prototype.port3C8_write = function(index)
{
    this.dac_color_index_write = (index & 0xFF) * 3;
    this.dac_state |= 0x3;
};

VGAScreen.prototype.port3C8_write16 = function(data)
{
    this.port3C8_write(data & 0xFF);
    this.port3C9_write(data >> 8 & 0xFF);
};

VGAScreen.prototype.port3C8_read = function()
{
    return this.dac_color_index_write / 3 & 0xFF;
};

/**
 * DAC color palette register writes
 * @see {@link http://www.osdever.net/FreeVGA/vga/colorreg.htm}
 * @see {@link http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf} page 104
 * @see {@link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-hsw-display_0.pdf} page 57
 */
VGAScreen.prototype.port3C9_write = function(color_byte)
{
    var index = this.dac_color_index_write / 3 & 0xFF,
        offset = this.dac_color_index_write % 3,
        color = this.vga256_palette[index];

    if((this.dispi_enable_value & 0x20) === 0)
    {
        color_byte &= 0x3F;
        const b = color_byte & 1;
        color_byte = color_byte << 2 | b << 1 | b;
    }

    if(offset === 0)
    {
        color = color & ~0xFF0000 | color_byte << 16;
    }
    else if(offset === 1)
    {
        color = color & ~0xFF00 | color_byte << 8;
    }
    else
    {
        color = color & ~0xFF | color_byte;
        dbg_log("dac set color, index=" + h(index) + " value=" + h(color), LOG_VGA);
    }

    if(this.vga256_palette[index] !== color)
    {
        this.vga256_palette[index] = color;
        this.complete_redraw();
    }
    this.dac_color_index_write = (this.dac_color_index_write + 1) % (256 * 3);
};

VGAScreen.prototype.port3C9_read = function()
{
    dbg_log("3C9 read", LOG_VGA);

    var index = this.dac_color_index_read / 3 & 0xFF;
    var offset = this.dac_color_index_read % 3;
    var color = this.vga256_palette[index];
    var color8 = color >> (2 - offset) * 8 & 0xFF;

    this.dac_color_index_read = (this.dac_color_index_read + 1) % (256 * 3);

    if(this.dispi_enable_value & 0x20)
    {
        return color8;
    }
    else
    {
        return color8 >> 2;
    }
};

VGAScreen.prototype.port3CC_read = function()
{
    dbg_log("3CC read", LOG_VGA);
    return this.miscellaneous_output_register;
};

VGAScreen.prototype.port3CE_write = function(value)
{
    this.graphics_index = value;
};

VGAScreen.prototype.port3CE_read = function()
{
    return this.graphics_index;
};

/**
 * Graphics controller register writes
 * @see {@link http://www.osdever.net/FreeVGA/vga/graphreg.htm}
 * @see {@link http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf} page 78
 * @see {@link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-hsw-display_0.pdf} page 29
 */
VGAScreen.prototype.port3CF_write = function(value)
{
    switch(this.graphics_index)
    {
        case 0:
            this.planar_setreset = value;
            dbg_log("plane set/reset: " + h(value), LOG_VGA);
            break;
        case 1:
            this.planar_setreset_enable = value;
            dbg_log("plane set/reset enable: " + h(value), LOG_VGA);
            break;
        case 2:
            this.color_compare = value;
            dbg_log("color compare: " + h(value), LOG_VGA);
            break;
        case 3:
            this.planar_rotate_reg = value;
            dbg_log("plane rotate: " + h(value), LOG_VGA);
            break;
        case 4:
            this.plane_read = value;
            dbg_log("plane read: " + h(value), LOG_VGA);
            break;
        case 5:
            var previous_planar_mode = this.planar_mode;
            this.planar_mode = value;
            dbg_log("planar mode: " + h(value), LOG_VGA);
            if((previous_planar_mode ^ value) & 0x60)
            {
                // Shift mode modified. Pixel buffer invalidated
                this.complete_replot();
            }
            break;
        case 6:
            dbg_log("miscellaneous graphics register: " + h(value), LOG_VGA);
            if(this.miscellaneous_graphics_register !== value)
            {
                this.miscellaneous_graphics_register = value;
                this.update_vga_size();
            }
            break;
        case 7:
            this.color_dont_care = value;
            dbg_log("color don't care: " + h(value), LOG_VGA);
            break;
        case 8:
            this.planar_bitmap = value;
            dbg_log("planar bitmap: " + h(value), LOG_VGA);
            break;
        default:
            dbg_log("3CF / graphics write " + h(this.graphics_index) + ": " + h(value), LOG_VGA);
    }
};

VGAScreen.prototype.port3CF_read = function()
{
    dbg_log("3CF / graphics read " + h(this.graphics_index), LOG_VGA);

    switch(this.graphics_index)
    {
        case 0:
            return this.planar_setreset;
        case 1:
            return this.planar_setreset_enable;
        case 2:
            return this.color_compare;
        case 3:
            return this.planar_rotate_reg;
        case 4:
            return this.plane_read;
        case 5:
            return this.planar_mode;
        case 6:
            return this.miscellaneous_graphics_register;
        case 7:
            return this.color_dont_care;
        case 8:
            return this.planar_bitmap;
        default:
    }
    return 0;
};

VGAScreen.prototype.port3D4_write = function(register)
{
    dbg_log("3D4 / crtc index: " + register, LOG_VGA);
    this.index_crtc = register;
};

VGAScreen.prototype.port3D4_write16 = function(register)
{
    this.port3D4_write(register & 0xFF);
    this.port3D5_write(register >> 8 & 0xFF);
};

VGAScreen.prototype.port3D4_read = function()
{
    dbg_log("3D4 read / crtc index: " + this.index_crtc, LOG_VGA);
    return this.index_crtc;
};

/**
 * CRT controller register writes
 * @see {@link http://www.osdever.net/FreeVGA/vga/crtcreg.htm}
 * @see {@link http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf} page 55
 * @see {@link https://01.org/sites/default/files/documentation/intel-gfx-prm-osrc-hsw-display_0.pdf} page 63
 */
VGAScreen.prototype.port3D5_write = function(value)
{
    switch(this.index_crtc)
    {
        case 0x1:
            dbg_log("3D5 / hdisp enable end write: " + h(value), LOG_VGA);
            if(this.horizontal_display_enable_end !== value)
            {
                this.horizontal_display_enable_end = value;
                this.update_vga_size();
            }
            break;
        case 0x2:
            if(this.horizontal_blank_start !== value)
            {
                this.horizontal_blank_start = value;
                this.update_vga_size();
            }
            break;
        case 0x7:
            dbg_log("3D5 / overflow register write: " + h(value), LOG_VGA);
            // bits 0, 2, 5 and 7 are vertical total and retrace start bits 8 and 9 (vblank_period)
            this.crtc[7] = value;
            var previous_vertical_display_enable_end = this.vertical_display_enable_end;
            this.vertical_display_enable_end &= 0xFF;
            this.vertical_display_enable_end |= (value << 3 & 0x200) | (value << 7 & 0x100);
            if(previous_vertical_display_enable_end !== this.vertical_display_enable_end)
            {
                this.update_vga_size();
            }
            this.line_compare = (this.line_compare & 0x2FF) | (value << 4 & 0x100);

            var previous_vertical_blank_start = this.vertical_blank_start;
            this.vertical_blank_start = (this.vertical_blank_start & 0x2FF) | (value << 5 & 0x100);
            if(previous_vertical_blank_start !== this.vertical_blank_start)
            {
                this.update_vga_size();
            }
            this.update_layers();
            break;
        case 0x8:
            dbg_log("3D5 / preset row scan write: " + h(value), LOG_VGA);
            this.preset_row_scan = value;
            this.update_layers();
            break;
        case 0x9:
            dbg_log("3D5 / max scan line write: " + h(value), LOG_VGA);
            var previous_max_scan_line = this.max_scan_line;
            this.max_scan_line = value;
            this.line_compare = (this.line_compare & 0x1FF) | (value << 3 & 0x200);

            var previous_vertical_blank_start = this.vertical_blank_start;
            this.vertical_blank_start = (this.vertical_blank_start & 0x1FF) | (value << 4 & 0x200);
            if(((previous_max_scan_line ^ this.max_scan_line) & 0x9F) || previous_vertical_blank_start !== this.vertical_blank_start)
            {
                this.update_vga_size();
            }

            this.update_cursor_scanline();
            this.update_layers();

            this.set_font_bitmap(false);
            break;
        case 0xA:
            dbg_log("3D5 / cursor scanline start write: " + h(value), LOG_VGA);
            this.cursor_scanline_start = value;
            this.update_cursor_scanline();
            break;
        case 0xB:
            dbg_log("3D5 / cursor scanline end write: " + h(value), LOG_VGA);
            this.cursor_scanline_end = value;
            this.update_cursor_scanline();
            break;
        case 0xC:
            if((this.start_address >> 8 & 0xFF) !== value)
            {
                this.start_address = this.start_address & 0xff | value << 8;
                this.update_layers();
                if(~this.crtc_mode &  0x3)
                {
                    // Address substitution implementation depends on the
                    // starting row and column, so the pixel buffer is invalidated.
                    this.complete_replot();
                }
            }
            dbg_log("3D5 / start addr hi write: " + h(value) + " -> " + h(this.start_address, 4), LOG_VGA);
            break;
        case 0xD:
            if((this.start_address & 0xFF) !== value)
            {
                this.start_address = this.start_address & 0xff00 | value;
                this.update_layers();
                if(~this.crtc_mode &  0x3)
                {
                    // Address substitution implementation depends on the
                    // starting row and column, so the pixel buffer is invalidated.
                    this.complete_replot();
                }
            }
            dbg_log("3D5 / start addr lo write: " + h(value) + " -> " + h(this.start_address, 4), LOG_VGA);
            break;
        case 0xE:
            dbg_log("3D5 / cursor address hi write: " + h(value), LOG_VGA);
            this.cursor_address = this.cursor_address & 0xFF | value << 8;
            this.update_cursor();
            break;
        case 0xF:
            dbg_log("3D5 / cursor address lo write: " + h(value), LOG_VGA);
            this.cursor_address = this.cursor_address & 0xFF00 | value;
            this.update_cursor();
            break;
        case 0x12:
            dbg_log("3D5 / vdisp enable end write: " + h(value), LOG_VGA);
            if((this.vertical_display_enable_end & 0xFF) !== value)
            {
                this.vertical_display_enable_end = (this.vertical_display_enable_end & 0x300) | value;
                this.update_vga_size();
            }
            break;
        case 0x13:
            dbg_log("3D5 / offset register write: " + h(value), LOG_VGA);
            if(this.offset_register !== value)
            {
                this.offset_register = value;
                this.update_vga_size();

                if(~this.crtc_mode & 0x3)
                {
                    // Address substitution implementation depends on the
                    // virtual width, so the pixel buffer is invalidated.
                    this.complete_replot();
                }
            }
            break;
        case 0x14:
            dbg_log("3D5 / underline location write: " + h(value), LOG_VGA);
            if(this.underline_location_register !== value)
            {
                var previous_underline = this.underline_location_register;

                this.underline_location_register = value;
                this.update_vga_size();

                if((previous_underline ^ value) & 0x40)
                {
                    // Doubleword addressing changed. Pixel buffer invalidated.
                    this.complete_replot();
                }
            }
            break;
        case 0x15:
            dbg_log("3D5 / vertical blank start write: " + h(value), LOG_VGA);
            if((this.vertical_blank_start & 0xFF) !== value)
            {
                this.vertical_blank_start = (this.vertical_blank_start & 0x300) | value;
                this.update_vga_size();
            }
            break;
        case 0x17:
            dbg_log("3D5 / crtc mode write: " + h(value), LOG_VGA);
            if(this.crtc_mode !== value)
            {
                var previous_mode = this.crtc_mode;

                this.crtc_mode = value;
                this.update_vga_size();

                if((previous_mode ^ value) & 0x43)
                {
                    // Word/byte addressing changed or address substitution changed.
                    // Pixel buffer invalidated.
                    this.complete_replot();
                }
            }
            break;
        case 0x18:
            dbg_log("3D5 / line compare write: " + h(value), LOG_VGA);
            this.line_compare = (this.line_compare & 0x300) | value;
            this.update_layers();
            break;
        default:
            if(this.index_crtc < this.crtc.length)
            {
                this.crtc[this.index_crtc] = value;
            }
            dbg_log("3D5 / CRTC write " + h(this.index_crtc) + ": " + h(value), LOG_VGA);
    }

};

VGAScreen.prototype.port3D5_write16 = function(register)
{
    dbg_log("16-bit write to 3D5: " + h(register, 4), LOG_VGA);
    this.port3D5_write(register & 0xFF);
};

VGAScreen.prototype.port3D5_read = function()
{
    dbg_log("3D5 read " + h(this.index_crtc), LOG_VGA);

    switch(this.index_crtc)
    {
        case 0x1:
            return this.horizontal_display_enable_end;
        case 0x2:
            return this.horizontal_blank_start;
        case 0x7:
            return (this.vertical_display_enable_end >> 7 & 0x2) |
                (this.vertical_blank_start >> 5 & 0x8) |
                (this.line_compare >> 4 & 0x10) |
                (this.vertical_display_enable_end >> 3 & 0x40) |
                (this.crtc[7] & 0xA5);
        case 0x8:
            return this.preset_row_scan;
        case 0x9:
            return this.max_scan_line;
        case 0xA:
            return this.cursor_scanline_start;
        case 0xB:
            return this.cursor_scanline_end;
        case 0xC:
            return this.start_address & 0xFF;
        case 0xD:
            return this.start_address >> 8;
        case 0xE:
            return this.cursor_address >> 8;
        case 0xF:
            return this.cursor_address & 0xFF;
        case 0x12:
            return this.vertical_display_enable_end & 0xFF;
        case 0x13:
            return this.offset_register;
        case 0x14:
            return this.underline_location_register;
        case 0x15:
            return this.vertical_blank_start & 0xFF;
        case 0x17:
            return this.crtc_mode;
        case 0x18:
            return this.line_compare & 0xFF;
    }

    if(this.index_crtc < this.crtc.length)
    {
        return this.crtc[this.index_crtc];
    }
    else
    {
        return 0;
    }
};

VGAScreen.prototype.port3D5_read16 = function()
{
    dbg_log("Warning: 16-bit read from 3D5", LOG_VGA);
    return this.port3D5_read();
};

/**
 * Input status register 1. Bit 3 is the vertical retrace, timed on the machine
 * clock from the CRTC registers, and it reads as set at least once after each
 * retrace starts, however coarse the clock. Bit 0 (display disabled) toggles
 * on every read: a stand-in for the horizontal retrace, and set throughout the
 * vertical one.
 */
VGAScreen.prototype.port3DA_read = function()
{
    dbg_log("3DA read - status 1 and clear attr index", LOG_VGA);

    const in_retrace = this.display.time_since_vblank(this.machine.now()) < this.retrace_duration();

    this.port_3DA_value = (this.port_3DA_value ^ 1) & 1;
    let value = this.port_3DA_value;
    if(in_retrace || this.retrace_pending)
    {
        value |= 0x09;
    }
    this.retrace_pending = false;

    this.attribute_controller_index = -1;
    return value;
};

VGAScreen.prototype.port1CE_read = function()
{
    return this.dispi_index;
};

VGAScreen.prototype.port1CE_write = function(value)
{
    this.dispi_index = value;
};

VGAScreen.prototype.port1CF_write = function(value)
{
    dbg_log("1CF / dispi write " + h(this.dispi_index) + ": " + h(value), LOG_VGA);

    const was_enabled = this.svga_enabled;

    switch(this.dispi_index)
    {
        case 0:
            if(value >= 0xB0C0 && value <= 0xB0C5)
            {
                this.svga_version = value;
            }
            else
            {
                dbg_log("Invalid version value: " + h(value), LOG_VGA);
            }
            break;
        case 1:
            this.svga_width = value;
            if(this.svga_width > MAX_XRES)
            {
                dbg_log("svga_width reduced from " + this.svga_width + " to " + MAX_XRES, LOG_VGA);
                this.svga_width = MAX_XRES;
            }
            break;
        case 2:
            this.svga_height = value;
            if(this.svga_height > MAX_YRES)
            {
                dbg_log("svga_height reduced from " + this.svga_height + " to " + MAX_YRES, LOG_VGA);
                this.svga_height = MAX_YRES;
            }
            break;
        case 3:
            this.svga_bpp = value;
            break;
        case 4:
            // enable, options
            this.dispi_enable_value = value;
            if(!(value & 1) && this.svga_enabled && this.machine.in_vm86())
            {
                // XXX: hack to make cmd.exe work on Win9x with vbemp driver:
                // Win9x's VDD virtualises the legacy VGA ports for a windowed
                // DOS VM but not the dispi ports, so vgabios's VBE disable
                // leaks through while the rest of its mode-set is virtualised.
                // Defer the actual disable until a legacy mode register write
                // reaches us (see port3C0_write); if it never does, the
                // protected-mode display driver still owns the framebuffer.
            }
            else
            {
                this.svga_enabled = (value & 1) === 1;
                if(this.svga_enabled && (value & 0x80) === 0)
                {
                    this.svga_memory.fill(0);
                }
            }
            break;
        case 5:
            dbg_log("SVGA bank offset: " + h(value << 16), LOG_VGA);
            this.svga_bank_offset = value << 16;
            break;
        case 8:
            // x offset
            dbg_log("SVGA X offset: " + h(value), LOG_VGA);
            if(this.svga_offset_x !== value)
            {
                this.svga_offset_x = value;
                this.svga_offset = this.svga_offset_y * this.svga_width + this.svga_offset_x;
                this.complete_redraw();
            }
            break;
        case 9:
            // y offset
            dbg_log("SVGA Y offset: " + h(value * this.svga_width) + " y=" + h(value), LOG_VGA);
            if(this.svga_offset_y !== value)
            {
                this.svga_offset_y = value;
                this.svga_offset = this.svga_offset_y * this.svga_width + this.svga_offset_x;
                this.complete_redraw();
            }
            break;
        default:
            dbg_log("Unimplemented dispi write index: " + h(this.dispi_index), LOG_VGA);
    }

    if(this.svga_enabled && (!this.svga_width || !this.svga_height))
    {
        dbg_log("SVGA: disabled because of invalid width/height: " + this.svga_width + "x" + this.svga_height, LOG_VGA);
        this.svga_enabled = false;
    }

    dbg_assert(this.svga_bpp !== 4, "unimplemented svga bpp: 4");
    dbg_assert(this.svga_bpp === 4 || this.svga_bpp === 8 ||
               this.svga_bpp === 15 || this.svga_bpp === 16 ||
               this.svga_bpp === 24 || this.svga_bpp === 32,
               "unexpected svga bpp: " + this.svga_bpp);

    if(this.svga_enabled)
    {
        dbg_log("SVGA: enabled, " + this.svga_width + "x" + this.svga_height + "x" + this.svga_bpp, LOG_VGA);
    }
    else
    {
        dbg_log("SVGA: disabled", LOG_VGA);
    }

    if(this.svga_enabled && this.dispi_index === 4)
    {
        if(!was_enabled)
        {
            this.svga_offset = 0;
            this.svga_offset_x = 0;
            this.svga_offset_y = 0;
        }

        const was_graphical = this.graphical_mode;
        this.set_graphical_mode(true);
        this.set_size_graphical(this.svga_width, this.svga_height, this.svga_width, this.svga_height, this.svga_bpp);
        if(!was_graphical)
        {
            this.complete_redraw();
        }
    }

    if(was_enabled && !this.svga_enabled)
    {
        const is_graphical = (this.attribute_mode & 0x1) !== 0;
        this.set_graphical_mode(is_graphical);
        this.update_vga_size();
        this.set_font_bitmap(!is_graphical);
        this.complete_redraw();
    }

    if(!this.svga_enabled)
    {
        this.svga_bank_offset = 0;
    }

    this.update_layers();
};

VGAScreen.prototype.port1CF_read = function()
{
    dbg_log("1CF / dispi read " + h(this.dispi_index), LOG_VGA);
    return this.svga_register_read(this.dispi_index);
};

VGAScreen.prototype.svga_register_read = function(n)
{
    switch(n)
    {
        case 0:
            return this.svga_version;
        case 1:
            return this.dispi_enable_value & 2 ? MAX_XRES : this.svga_width;
        case 2:
            return this.dispi_enable_value & 2 ? MAX_YRES : this.svga_height;
        case 3:
            return this.dispi_enable_value & 2 ? MAX_BPP : this.svga_bpp;
        case 4:
            return this.dispi_enable_value;
        case 5:
            return this.svga_bank_offset >>> 16;
        case 6:
            // virtual width
            if(this.screen_width)
            {
                return this.screen_width;
            }
            else
            {
                return 1; // seabios/windows98 divide exception
            }
            break;

        case 8:
            // x offset
            return this.svga_offset_x;
        case 9:
            return this.svga_offset_y;
        case 0x0A:
            // memory size in 64 kilobyte banks
            return this.vga_memory_size / VGA_BANK_SIZE | 0;
        default:
            dbg_log("Unimplemented dispi read index: " + h(this.dispi_index), LOG_VGA);
    }

    return 0xFF;
};

/**
 * Transfers graphics from VGA Planes to the Pixel Buffer
 * VGA Planes represent data stored on actual hardware.
 * Pixel Buffer caches the 4-bit or 8-bit color indices for each pixel.
 */
VGAScreen.prototype.vga_replot = function()
{
    // Round to multiple of 8 towards extreme
    var start = this.diff_plot_min & ~0xF;
    var end = Math.min((this.diff_plot_max | 0xF), VGA_PIXEL_BUFFER_SIZE - 1);

    var addr_shift = this.vga_addr_shift_count();
    var addr_substitution = ~this.crtc_mode & 0x3;

    var shift_mode = this.planar_mode & 0x60;
    var pel_width = this.attribute_mode & 0x40;

    for(var pixel_addr = start; pixel_addr <= end;)
    {
        var addr = pixel_addr >>> addr_shift;
        if(addr_substitution)
        {
            var row = pixel_addr / this.virtual_width | 0;
            var col = pixel_addr - this.virtual_width * row;

            switch(addr_substitution)
            {
                case 0x1:
                    // Alternating rows using bit 13
                    // Assumes max scan line = 1
                    addr = (row & 0x1) << 13;
                    row >>>= 1;
                    break;
                case 0x2:
                    // Alternating rows using bit 14
                    // Assumes max scan line = 3
                    addr = (row & 0x1) << 14;
                    row >>>= 1;
                    break;
                case 0x3:
                    // Cycling through rows using bit 13 and 14
                    // Assumes max scan line = 3
                    addr = (row & 0x3) << 13;
                    row >>>= 2;
                    break;
            }

            addr |= (row * this.virtual_width + col >>> addr_shift) + this.start_address;
        }

        var byte0 = this.plane0[addr];
        var byte1 = this.plane1[addr];
        var byte2 = this.plane2[addr];
        var byte3 = this.plane3[addr];

        var shift_loads = new Uint8Array(8);
        switch(shift_mode)
        {
            // Planar Shift Mode
            // See http://www.osdever.net/FreeVGA/vga/vgaseq.htm
            case 0x00:
                // Shift these, so that the bits for the color are in
                // the correct position in the for loop
                byte0 <<= 0;
                byte1 <<= 1;
                byte2 <<= 2;
                byte3 <<= 3;

                for(var i = 7; i >= 0; i--)
                {
                    shift_loads[7 - i] =
                            byte0 >> i & 1 |
                            byte1 >> i & 2 |
                            byte2 >> i & 4 |
                            byte3 >> i & 8;
                }
                break;

            // Packed Shift Mode, aka Interleaved Shift Mode
            // Video Modes 4h and 5h
            case 0x20:
                shift_loads[0] = (byte0 >> 6 & 0x3) | (byte2 >> 4 & 0xC);
                shift_loads[1] = (byte0 >> 4 & 0x3) | (byte2 >> 2 & 0xC);
                shift_loads[2] = (byte0 >> 2 & 0x3) | (byte2 >> 0 & 0xC);
                shift_loads[3] = (byte0 >> 0 & 0x3) | (byte2 << 2 & 0xC);

                shift_loads[4] = (byte1 >> 6 & 0x3) | (byte3 >> 4 & 0xC);
                shift_loads[5] = (byte1 >> 4 & 0x3) | (byte3 >> 2 & 0xC);
                shift_loads[6] = (byte1 >> 2 & 0x3) | (byte3 >> 0 & 0xC);
                shift_loads[7] = (byte1 >> 0 & 0x3) | (byte3 << 2 & 0xC);
                break;

            // 256-Color Shift Mode
            // Video Modes 13h and unchained 256 color
            case 0x40:
            case 0x60:
                shift_loads[0] = byte0 >> 4 & 0xF;
                shift_loads[1] = byte0 >> 0 & 0xF;
                shift_loads[2] = byte1 >> 4 & 0xF;
                shift_loads[3] = byte1 >> 0 & 0xF;
                shift_loads[4] = byte2 >> 4 & 0xF;
                shift_loads[5] = byte2 >> 0 & 0xF;
                shift_loads[6] = byte3 >> 4 & 0xF;
                shift_loads[7] = byte3 >> 0 & 0xF;
                break;
        }

        if(pel_width)
        {
            // Assemble from two sets of 4 bits.
            for(var i = 0, j = 0; i < 4; i++, pixel_addr++, j += 2)
            {
                this.pixel_buffer[pixel_addr] = (shift_loads[j] << 4) | shift_loads[j + 1];
            }
        }
        else
        {
            for(var i = 0; i < 8; i++, pixel_addr++)
            {
                this.pixel_buffer[pixel_addr] = shift_loads[i];
            }
        }
    }
};

/**
 * Transfers graphics from Pixel Buffer to Destination Image Buffer.
 * The 4-bit/8-bit color indices in the Pixel Buffer are passed through
 * the internal palette (dac_map) and the DAC palette (vga256_palette) to
 * obtain the final 32 bit color that the Canvas API uses.
 */
VGAScreen.prototype.vga_redraw = function()
{
    var start = this.diff_addr_min;
    var end = Math.min(this.diff_addr_max, VGA_PIXEL_BUFFER_SIZE - 1);
    const buffer = new Int32Array(this.machine.wasm_memory.buffer, this.dest_buffer_offset, this.virtual_width * this.virtual_height);

    var mask = 0xFF;
    var colorset = 0x00;
    if(this.attribute_mode & 0x80)
    {
        // Palette bits 5/4 select
        mask &= 0xCF;
        colorset |= this.color_select << 4 & 0x30;
    }

    if(this.attribute_mode & 0x40)
    {
        // 8 bit mode

        for(var pixel_addr = start; pixel_addr <= end; pixel_addr++)
        {
            var color256 = (this.pixel_buffer[pixel_addr] & mask) | colorset;
            var color = this.vga256_palette[color256];

            buffer[pixel_addr] = color & 0xFF00 | color << 16 | color >> 16 | 0xFF000000;
        }
    }
    else
    {
        // 4 bit mode

        // Palette bits 7/6 select
        mask &= 0x3F;
        colorset |= this.color_select << 4 & 0xC0;

        for(var pixel_addr = start; pixel_addr <= end; pixel_addr++)
        {
            var color16 = this.pixel_buffer[pixel_addr] & this.color_plane_enable;
            var color256 = (this.dac_map[color16] & mask) | colorset;
            var color = this.vga256_palette[color256];

            buffer[pixel_addr] = color & 0xFF00 | color << 16 | color >> 16 | 0xFF000000;
        }
    }
};

/** @override */
VGAScreen.prototype.render = function()
{
    if(!this.graphical_mode || !this.pixels)
    {
        return;
    }

    if(this.pixels.data.byteLength === 0)
    {
        // wasm memory resized
        this.create_pixel_view();
        this.update_layers();
    }

    if(this.svga_enabled)
    {
        let min_y = 0;
        let max_y = this.svga_height;

        if(this.svga_bpp === 8)
        {
            // XXX: Slow, should be ported to rust, but it doesn't have access to vga256_palette
            const buffer = new Int32Array(this.machine.wasm_memory.buffer, this.dest_buffer_offset, this.screen_width * this.screen_height);
            const svga_memory = new Uint8Array(this.machine.wasm_memory.buffer, this.svga_memory.byteOffset, this.vga_memory_size);
            // svga_offset selects the visible part of svga_memory, used for page flipping (e.g. Master of Orion 2)
            const base = this.svga_offset;
            const end = Math.min(buffer.length, this.vga_memory_size - base);

            for(var i = 0; i < end; i++)
            {
                var color = this.vga256_palette[svga_memory[base + i]];
                buffer[i] = color & 0xFF00 | color << 16 | color >> 16 | 0xFF000000;
            }
        }
        else
        {
            this.machine.mmio_ram_fill_pixels(this.lfb_region, this.svga_bpp, this.svga_offset);

            const bytes_per_pixel = this.svga_bpp === 15 ? 2 : this.svga_bpp / 8;
            // (floor: rows above the shown page are negative)
            min_y = Math.floor(((this.machine.dirty_min_offset() / bytes_per_pixel | 0) - this.svga_offset) / this.svga_width);
            max_y = Math.floor(((this.machine.dirty_max_offset() / bytes_per_pixel | 0) - this.svga_offset) / this.svga_width) + 1;
        }

        // (the dirty rows on the screen: a page flipped away, e.g. DirectDraw's
        // back buffer in video memory, can be dirty with none of them shown)
        min_y = Math.max(min_y, 0);
        max_y = Math.min(max_y, this.svga_height);

        if(min_y < max_y)
        {
            this.display.update_buffer([{
                pixels: this.pixels,
                screen_x: 0, screen_y: min_y,
                buffer_x: 0, buffer_y: min_y,
                buffer_width: this.svga_width,
                buffer_height: max_y - min_y,
            }]);
        }
    }
    else
    {
        this.vga_replot();
        this.vga_redraw();
        this.display.update_buffer(this.layers);
    }

    this.reset_diffs();
};

VGAScreen.prototype.set_font_bitmap = function(font_plane_dirty)
{
    const height = this.max_scan_line & 0x1f;
    if(height && !this.graphical_mode)
    {
        const width_dbl = !!(this.clocking_mode & 0x08);
        const width_9px = !width_dbl && !(this.clocking_mode & 0x01);
        const copy_8th_col = !!(this.attribute_mode & 0x04);
        this.display.set_font_bitmap(
            height + 1,         // int height, font height 1..32px
            width_9px,          // bool width_9px, True: font width 9px, else 8px
            width_dbl,          // bool width_dbl, True: font width 16px (overrides width_9px)
            copy_8th_col,       // bool copy_8th_col, True: duplicate 8th into 9th column in ASCII chars 0xC0-0xDF
            this.plane2,        // Uint8Array font_bitmap[64k], static
            font_plane_dirty    // bool bitmap_changed, True: content of this.plane2 has changed
        );
    }
};

VGAScreen.prototype.set_font_page = function()
{
    // bits 2, 3 and 5 (LSB to MSB): VGA font page index of font A
    // bits 0, 1 and 4: VGA font page index of font B
    // linear_index_map[] maps VGA's non-liner font page index to linear index
    const linear_index_map = [0, 2, 4, 6, 1, 3, 5, 7];
    const vga_index_a = ((this.character_map_select & 0b1100) >> 2) | ((this.character_map_select & 0b100000) >> 3);
    const vga_index_b = (this.character_map_select & 0b11) | ((this.character_map_select & 0b10000) >> 2);
    this.font_page_ab_enabled = vga_index_a !== vga_index_b;
    this.display.set_font_page(linear_index_map[vga_index_a], linear_index_map[vga_index_b]);
    this.complete_redraw();
};
                                                                                                                                                                                                                             source/v64/src/graphics_adapters/virtio_gpu/edid.js                                                 0000644 0000000 0000000 00000011505 00000000000 017572  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The EDID virtio-gpu gives the guest for a display (GET_EDID): an EDID 1.4
// base block whose preferred timing is the display's size, plus the usual
// established and standard timings, a range limits descriptor wide enough for
// custom resolutions, and a name.

/** EDID's limit for the preferred mode's active pixels (12 bits) */
const MAX_ACTIVE = 4095;

// Standard timings: width, aspect code (0 16:10, 1 4:3, 2 5:4, 3 16:9), at 60 Hz
const STANDARD_TIMINGS = [
    [1280, 3], [1280, 0], [1280, 2], [1440, 0], [1600, 3], [1680, 0], [1920, 3], [1600, 1],
];

/**
 * Three letters as EDID's manufacturer ID
 * @param {string} name
 * @return {number}
 */
function manufacturer(name)
{
    const letter = i => name.charCodeAt(i) - 64;
    return letter(0) << 10 | letter(1) << 5 | letter(2);
}

/**
 * A detailed timing descriptor (reduced blanking, 60 Hz)
 * @param {!Uint8Array} out
 * @param {number} at
 * @param {number} width
 * @param {number} height
 * @param {number} width_mm
 * @param {number} height_mm
 */
function detailed_timing(out, at, width, height, width_mm, height_mm)
{
    const h_front = 48, h_sync = 32, h_blank = 160;
    const v_front = 3, v_sync = 6, v_blank = Math.max(23, Math.ceil(height * 0.0083 / (1 - 0.0083)) + 9);
    // in 10 kHz
    const clock = Math.round((width + h_blank) * (height + v_blank) * 60 / 10000);
    out[at] = clock & 0xFF;
    out[at + 1] = clock >> 8;
    out[at + 2] = width & 0xFF;
    out[at + 3] = h_blank & 0xFF;
    out[at + 4] = (width >> 8) << 4 | h_blank >> 8;
    out[at + 5] = height & 0xFF;
    out[at + 6] = v_blank & 0xFF;
    out[at + 7] = (height >> 8) << 4 | v_blank >> 8;
    out[at + 8] = h_front & 0xFF;
    out[at + 9] = h_sync & 0xFF;
    out[at + 10] = (v_front & 0xF) << 4 | v_sync & 0xF;
    out[at + 11] = (h_front >> 8) << 6 | (h_sync >> 8) << 4 | (v_front >> 4) << 2 | v_sync >> 4;
    out[at + 12] = width_mm & 0xFF;
    out[at + 13] = height_mm & 0xFF;
    out[at + 14] = (width_mm >> 8) << 4 | height_mm >> 8;
    // digital separate sync, +hsync -vsync (CVT reduced blanking)
    out[at + 17] = 0x1A;
}

/**
 * A text descriptor (name 0xFC, serial 0xFF)
 * @param {!Uint8Array} out
 * @param {number} at
 * @param {number} tag
 * @param {string} text
 */
function text_descriptor(out, at, tag, text)
{
    out[at + 3] = tag;
    const bytes = Array.from(text.slice(0, 13), c => c.charCodeAt(0));
    if(bytes.length < 13) bytes.push(0x0A);
    while(bytes.length < 13) bytes.push(0x20);
    out.set(bytes, at + 5);
}

/**
 * @param {number} width the preferred mode
 * @param {number} height
 * @param {number} serial
 * @return {!Uint8Array} 128 bytes
 */
export function make_edid(width, height, serial)
{
    width = Math.max(640, Math.min(MAX_ACTIVE, width));
    height = Math.max(480, Math.min(MAX_ACTIVE, height));
    const out = new Uint8Array(128);
    out.set([0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00]);
    // manufacturer "VEM" (big-endian), product 0x1050, serial
    const id = manufacturer("VEM");
    out[8] = id >> 8;
    out[9] = id & 0xFF;
    out[10] = 0x50;
    out[11] = 0x10;
    out[12] = serial & 0xFF;
    out[13] = serial >> 8 & 0xFF;
    out[14] = serial >> 16 & 0xFF;
    out[15] = serial >>> 24;
    // week 0, 2026; EDID 1.4
    out[16] = 0;
    out[17] = 2026 - 1990;
    out[18] = 1;
    out[19] = 4;
    // digital, 8 bits per colour, DisplayPort
    out[20] = 0xA5;
    // the size, in cm, at 96 pixels per inch
    const width_mm = Math.round(width * 25.4 / 96), height_mm = Math.round(height * 25.4 / 96);
    out[21] = Math.min(255, Math.round(width_mm / 10));
    out[22] = Math.min(255, Math.round(height_mm / 10));
    // gamma 2.2
    out[23] = 120;
    // RGB 4:4:4, sRGB, the preferred timing is native, continuous frequency
    out[24] = 0x07;
    // sRGB chromaticity (10-bit coordinates)
    const [rx, ry, gx, gy, bx, by, wx, wy] = [0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290].map(v => Math.round(v * 1024));
    out[25] = (rx & 3) << 6 | (ry & 3) << 4 | (gx & 3) << 2 | gy & 3;
    out[26] = (bx & 3) << 6 | (by & 3) << 4 | (wx & 3) << 2 | wy & 3;
    out.set([rx >> 2, ry >> 2, gx >> 2, gy >> 2, bx >> 2, by >> 2, wx >> 2, wy >> 2], 27);
    // established: 640x480@60, 800x600@60, 1024x768@60
    out[35] = 0x21;
    out[36] = 0x08;
    out[37] = 0;
    STANDARD_TIMINGS.forEach(([w, aspect], i) => {
        out[38 + 2 * i] = w / 8 - 31;
        out[39 + 2 * i] = aspect << 6;
    });
    detailed_timing(out, 54, width, height, width_mm, height_mm);
    // range limits: 50-75 Hz, 30-250 kHz, up to 1270 MHz (default GTF)
    out.set([0, 0, 0, 0xFD, 0, 50, 75, 30, 250, 127, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20], 72);
    text_descriptor(out, 90, 0xFC, "v86 virtio");
    text_descriptor(out, 108, 0xFF, "V86-" + serial.toString(16).toUpperCase());
    let sum = 0;
    for(let i = 0; i < 127; i++) sum += out[i];
    out[127] = -sum & 0xFF;
    return out;
}
                                                                                                                                                                                           source/v64/src/graphics_adapters/virtio_gpu/gfxstream.js                                            0000644 0000000 0000000 00000074460 00000000000 020676  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-gpu's gfxstream contexts (docs/gfxstream-plan.md G1, the protocol
// in docs/gfxstream-protocol.md): the capsets of gfxstream's Vulkan and
// composer; a context (a guest process) has an ASG ring per stream (a
// thread's connection), each in a HOST3D blob that CONTEXT_CREATE names and
// PING runs; on a ring, the stream (the client's flags, then commands of an
// opcode and a size, each to the decoder of its range: renderControl's,
// Vulkan's) and the replies back through it; the sync commands as tasks on
// the context's timeline, and the process pipe (pipe resources:
// GLProcessPipe) that renderControl's guest opens first; snapshots of all
// that (G6).

import { GfxstreamVulkan } from "./gfxstream_vk.js";

const VULKAN_CAPSET_WORDS = 27, SMALL_CAPSET_WORDS = 4;
export const CAPSET_GFXSTREAM_VULKAN = 3;
export const CAPSET_GFXSTREAM_COMPOSER = 9;

// the host's ring parameters (gfxstream's host/VirtioGpuFrontend.cpp fillCaps)
const RING_SIZE = 12288;
const BUFFER_SIZE = 1 << 20;
const PAGE = 4096;
/** the guest's write step (asg_ring_config.flush_interval; the emulator's writeStepSize) */
const FLUSH_INTERVAL = 4096;

// execbuffer commands (virtgpu_gfxstream_protocol.h): opcode -> size
const CONTEXT_CREATE = 0x1001, CONTEXT_PING = 0x1002, CONTEXT_PING_WITH_RESPONSE = 0x1003;
const CREATE_EXPORT_SYNC = 0x9000, CREATE_IMPORT_SYNC = 0x9001;
const CREATE_EXPORT_SYNC_VK = 0xa000, CREATE_IMPORT_SYNC_VK = 0xa001, CREATE_QSRI_EXPORT_VK = 0xa002;
const RESOURCE_CREATE_3D = 0xa003, ACQUIRE_SYNC = 0xa004, PLACEHOLDER_COMMAND_VK = 0xf002;
const COMMAND_SIZE = {
    [CONTEXT_CREATE]: 8, [CONTEXT_PING]: 8, [CONTEXT_PING_WITH_RESPONSE]: 8,
    [CREATE_EXPORT_SYNC]: 12, [CREATE_IMPORT_SYNC]: 12,
    [CREATE_EXPORT_SYNC_VK]: 20, [CREATE_IMPORT_SYNC_VK]: 20, [CREATE_QSRI_EXPORT_VK]: 12,
    [RESOURCE_CREATE_3D]: 56, [ACQUIRE_SYNC]: 16, [PLACEHOLDER_COMMAND_VK]: 12,
};

// the ring storage (asg_ring_storage): three pages of ring_buffer
const TO_HOST = 0, TO_HOST_LARGE = PAGE, FROM_HOST_LARGE = 2 * PAGE;
// ring_buffer's fields
const WRITE_POS = 8, READ_POS = 64, RING_BUF = 128, RING_BUF_SIZE = 2048, STATE = 2176, CONFIG = 2180;
// asg_ring_config's, from CONFIG of the to-host page
const BUFFER_SIZE_FIELD = 0, FLUSH_INTERVAL_FIELD = 4, HOST_CONSUMED_POS = 8, GUEST_WRITE_POS = 12, TRANSFER_MODE = 16,
    TRANSFER_SIZE = 20, IN_ERROR = 24;
// asg_host_state
const HOST_NEED_NOTIFY = 0, HOST_CAN_CONSUME = 1, HOST_RENDERING = 4;

/** a resource of the process pipe (PIPE_BUFFER with VIRGL_BIND_CUSTOM) */
const PIPE_BUFFER = 0;
const BIND_CUSTOM = 1 << 17;

/**
 * A HOST3D blob of a gfxstream context: shared memory (blob id 0: an ASG
 * ring, or memory the guest maps)
 * @constructor
 */
export function GfxstreamBlob(id, ctx_id, blob_id, flags, size)
{
    this.id = id;
    this.ctx_id = ctx_id;
    this.blob_id = blob_id;
    this.blob_flags = flags;
    this.blob_size = size;
    /** where it is mapped in the host visible memory, -1 when it is not */
    this.map_offset = -1;
    this.memory = null;
}

/** a decoder's answer: the command is not decoded yet (decode it again later) */
export const AGAIN = {};

/**
 * An ASG ring: a stream of the context's (gfxstream's render thread), in
 * the blob that holds its storage and buffer
 * @constructor
 * @param {!GfxstreamBlob} blob
 */
function Ring(blob)
{
    this.blob = blob;
    /** its config written (the blob mapped once) */
    this.ready = false;
    /** @type {!Array<!Uint8Array>} what came in the stream and was not decoded yet */
    this.input = [];
    this.input_length = 0;
    /** the client's flags (4 bytes before the commands) read */
    this.flags_read = false;
    /** a decoder waits (the GPU's work): decoding resumes when it is done */
    this.waiting = false;
    /** @type {Uint8Array} the command it waits in (a snapshot decodes it again: the waits are idempotent) */
    this.waiting_command = null;
    /** a command waits for another ring's (its sequence number): decoded again when one is */
    this.blocked = false;
    /** per decoder, its state for this stream */
    this.decoder_state = new Map();
}

/**
 * A gfxstream context: the guest process's
 * @constructor
 * @param {number} id
 * @param {number} capset
 */
function GfxstreamContext(id, capset)
{
    this.id = id;
    this.capset = capset;
    /** @type {!Map<number, !Ring>} its streams' rings, by the blob's resource id */
    this.rings = new Map();
    this.destroyed = false;
    /** RESOURCE_CREATE_3D's templates by blob id (G3: color buffers) */
    this.pending_blobs = new Map();
    /** ACQUIRE_SYNC's sync id */
    this.sync = 0;
    /** per decoder, its state for this context (the process's: Vulkan objects, sequence numbers) */
    this.decoder_state = new Map();
}

/**
 * A pipe resource: a goldfish pipe over virtio-gpu transfers (the guest's
 * VirtioGpuPipeStream): its first bytes name the service
 * @constructor
 */
function Pipe()
{
    this.service = null;
    this.name = [];
    /** @type {!Array<number>} bytes the service has for the guest */
    this.output = [];
    this.confirmed = false;
}

/**
 * @constructor
 * @param {!Object} gpu the VirtioGPU
 * @param {Object=} vk the Vulkan model (venus_vk.js) its Vulkan streams run on
 */
export function Gfxstream(gpu, vk)
{
    this.gpu = gpu;
    this.vk = vk || null;
    /** @type {!Map<number, !GfxstreamContext>} */
    this.contexts = new Map();
    /**
     * the decoders of the stream's commands, each of its opcodes
     * [first, last]: decode(ctx, ring, opcode, payload, reply) answers null
     * (done), a wait(done) when the command waits (the GPU's work), or
     * AGAIN: not decoded yet (another ring's command comes first), decoded
     * again when a ring of the context has decoded one
     * @type {!Array<{name: string, first: number, last: number, decode: function(!Object, !Object, number, !Uint8Array, function(!Uint8Array)): *}>}
     */
    this.decoders = [];
    /** a decoder's answer: not decoded yet (exported for decoders outside the module) */
    this.AGAIN = AGAIN;
    /** Vulkan's streams (G2) */
    this.vulkan = vk ? new GfxstreamVulkan(this, vk) : null;
    if(this.vulkan) this.decoders.push(...this.vulkan.decoders());
    /** the process pipe's ids (GLProcessPipe) */
    this.next_puid = 1;
    this.stats = { pings: 0, transfers: 0, bytes: 0, commands: 0, replies: 0, unknown: {}, errors: 0, last_error: "",
        /** the sync commands by opcode: [given, waited, done] */
        syncs: {},
        /** the execbuffers' commands by context and opcode */
        execbuffer: {} };
}

/** its capsets, [id, version, size] (the device's kinds of context) */
Gfxstream.prototype.capsets = [[CAPSET_GFXSTREAM_VULKAN, 0, VULKAN_CAPSET_WORDS * 4], [CAPSET_GFXSTREAM_COMPOSER, 0, SMALL_CAPSET_WORDS * 4]];

/**
 * A capset's contents, as gfxstream's host fills them
 * @param {number} id
 * @return {!Uint8Array}
 */
Gfxstream.prototype.capset = function(id)
{
    const words = new Uint32Array(id === CAPSET_GFXSTREAM_VULKAN ? VULKAN_CAPSET_WORDS : SMALL_CAPSET_WORDS);
    // protocolVersion, ringSize, bufferSize
    words[0] = 1;
    words[1] = RING_SIZE;
    words[2] = BUFFER_SIZE;
    if(id !== CAPSET_GFXSTREAM_VULKAN)
    {
        // blobAlignment
        words[3] = PAGE;
        return new Uint8Array(words.buffer);
    }
    // colorBufferMemoryIndex, deferredMapping, blobAlignment, noRenderControlEnc,
    // alwaysBlob, externalSync, virglSupportedFormats[16], batched descriptor
    // set updates, hasTraceAsyncCommand (G2: the color buffers' memory type,
    // the formats)
    words[3] = 0;
    words[4] = 1;
    words[5] = PAGE;
    words[6] = 1;
    words[26] = 1;
    return new Uint8Array(words.buffer);
};

Gfxstream.prototype.reset = function()
{
    for(const ctx of this.contexts.values()) ctx.destroyed = true;
    this.contexts.clear();
};

/**
 * @param {number} id
 * @param {number} capset
 */
Gfxstream.prototype.create_context = function(id, capset)
{
    this.destroy_context(id);
    this.contexts.set(id, new GfxstreamContext(id, capset));
};

/** @param {number} id */
Gfxstream.prototype.destroy_context = function(id)
{
    const ctx = this.contexts.get(id);
    if(!ctx) return;
    ctx.destroyed = true;
    for(const decoder of this.decoders) if(decoder.destroy) decoder.destroy(ctx);
    this.contexts.delete(id);
};

/**
 * RESOURCE_CREATE_BLOB of a gfxstream context: shared memory (blob id 0)
 * @return {GfxstreamBlob}
 */
Gfxstream.prototype.create_blob = function(id, ctx_id, flags, blob_id, size)
{
    const ctx = this.contexts.get(ctx_id);
    if(!ctx || !size) return null;
    const blob = new GfxstreamBlob(id, ctx_id, blob_id, flags, size);
    // (a blob id: a Vulkan memory's export; G3: a color buffer's)
    if(blob_id !== 0 && !(this.vulkan && this.vulkan.export_memory(ctx, blob))) return null;
    return blob;
};

/**
 * The blob was mapped: a ring waiting for its storage gets its config
 * @param {!GfxstreamBlob} blob
 * @return {?function(function())}
 */
Gfxstream.prototype.mapped = function(blob)
{
    // (a memory's: its contents, maybe from the GPU)
    if(blob.memory) return this.vk.map_memory(blob.memory, blob);
    const ctx = this.contexts.get(blob.ctx_id);
    const ring = ctx && ctx.rings.get(blob.id);
    if(ring && !ring.ready) this.init_ring(ctx, ring);
    return null;
};

/** the guest's writes: a memory's go to the GPU (shared memory's are read where they are) */
Gfxstream.prototype.upload_blob = function(blob, x, data)
{
    if(blob.memory) this.vk.upload_blob(blob, x, data);
};

/** @param {!GfxstreamBlob} blob */
Gfxstream.prototype.unref_blob = function(blob)
{
    if(blob.memory) this.vk.unexport_memory(blob.memory, blob);
    const ctx = this.contexts.get(blob.ctx_id);
    if(ctx) ctx.rings.delete(blob.id);
};

/** @return {!DataView} the host visible memory */
Gfxstream.prototype.view = function()
{
    const bytes = this.gpu.hostmem_bytes();
    return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
};

/**
 * The ring's config, as the host sets it before the guest reads it
 * @param {!GfxstreamContext} ctx
 * @param {!Ring} ring
 */
Gfxstream.prototype.init_ring = function(ctx, ring)
{
    if(ring.blob.map_offset < 0) return;
    const view = this.view(), base = ring.blob.map_offset;
    if(ring.blob.blob_size < RING_SIZE + BUFFER_SIZE)
    {
        this.error(ctx, "the ring's blob is " + ring.blob.blob_size + " bytes");
        return;
    }
    const config = base + TO_HOST + CONFIG;
    view.setUint32(config + BUFFER_SIZE_FIELD, BUFFER_SIZE, true);
    view.setUint32(config + FLUSH_INTERVAL_FIELD, FLUSH_INTERVAL, true);
    view.setUint32(config + HOST_CONSUMED_POS, 0, true);
    view.setUint32(config + TRANSFER_MODE, 1, true);
    view.setUint32(config + IN_ERROR, 0, true);
    view.setUint32(base + TO_HOST + STATE, HOST_NEED_NOTIFY, true);
    ring.ready = true;
};

/**
 * SUBMIT_3D of a gfxstream context: its commands (virtgpu_gfxstream_protocol.h)
 * @param {number} ctx_id
 * @param {!Uint8Array} bytes
 * @param {number=} ring_idx
 * @return {?function(function())} the answer waits until it calls back
 */
Gfxstream.prototype.submit = function(ctx_id, bytes, ring_idx)
{
    const ctx = this.contexts.get(ctx_id);
    if(!ctx) return null;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    /** @type {!Array<function(function())>} the tasks the answer waits for (the GPU's) */
    const tasks = [];
    /** @type {!Array<!Uint8Array>} their commands (a snapshot gives them again) */
    const waited = [];
    for(let at = 0; at + 4 <= bytes.length;)
    {
        const op = view.getUint32(at, true), size = COMMAND_SIZE[op];
        if(!size || at + size > bytes.length)
        {
            this.error(ctx, "execbuffer command 0x" + op.toString(16) + " of " + (bytes.length - at) + " bytes");
            break;
        }
        const u32 = i => view.getUint32(at + 4 + 4 * i, true);
        const key = ctx_id + ":" + op.toString(16) + (ring_idx ? "@" + ring_idx : "");
        this.stats.execbuffer[key] = (this.stats.execbuffer[key] || 0) + 1;
        switch(op)
        {
            case CONTEXT_CREATE:
            {
                const blob = this.gpu.resources.get(u32(0));
                if(!blob || !(blob instanceof GfxstreamBlob) || blob.ctx_id !== ctx_id)
                {
                    this.error(ctx, "CONTEXT_CREATE: resource " + u32(0) + " is not this context's blob");
                    break;
                }
                const ring = new Ring(blob);
                ctx.rings.set(blob.id, ring);
                if(blob.map_offset >= 0) this.init_ring(ctx, ring);
                break;
            }
            case CONTEXT_PING:
            case CONTEXT_PING_WITH_RESPONSE:
            {
                this.stats.pings++;
                const ring = ctx.rings.get(u32(0));
                if(ring) this.run(ctx, ring);
                else this.error(ctx, "PING of resource " + u32(0) + ", no ring of this context's");
                break;
            }
            case CREATE_EXPORT_SYNC:
            case CREATE_IMPORT_SYNC:
            case CREATE_EXPORT_SYNC_VK:
            case CREATE_IMPORT_SYNC_VK:
            case CREATE_QSRI_EXPORT_VK:
            {
                // a task on the context's timeline: done when the GPU's work
                // it names is (G2: the Vulkan fence's, the image's)
                // (the command's own words: QSRI's has two)
                const words = [];
                for(let i = 0; 8 + 4 * i <= size; i++) words.push(u32(i));
                const task = this.sync_task(ctx, op, words);
                const counts = this.stats.syncs[op] = this.stats.syncs[op] || [0, 0, 0];
                counts[0]++;
                if(task)
                {
                    counts[1]++;
                    tasks.push(done => task(() => { counts[2]++; done(); }));
                    waited.push(bytes.subarray(at, at + size));
                }
                break;
            }
            case RESOURCE_CREATE_3D:
                ctx.pending_blobs.set(view.getUint32(at + 48, true) + view.getUint32(at + 52, true) * 0x100000000,
                    [u32(0), u32(1), u32(2), u32(3), u32(4), u32(5), u32(6), u32(7), u32(8), u32(9)]);
                break;
            case ACQUIRE_SYNC:
                ctx.sync = view.getUint32(at + 8, true) + view.getUint32(at + 12, true) * 0x100000000;
                break;
            case PLACEHOLDER_COMMAND_VK:
                break;
        }
        at += size;
    }
    if(!tasks.length) return null;
    // (the fence waits for them all: the timeline's tasks before it)
    const wait = done => {
        let left = tasks.length;
        for(const task of tasks) task(() => { if(--left === 0) done(); });
    };
    // (for a snapshot: save_submission)
    wait.submission = { ctx_id, bytes: waited, ring_idx: ring_idx || 0 };
    return wait;
};

/**
 * A submission whose answer waits, for a snapshot: its sync commands (they
 * wait again for what they name, done already or not)
 * @param {{ctx_id: number, bytes: !Array<!Uint8Array>, ring_idx: number}} submission
 * @return {!Array}
 */
Gfxstream.prototype.save_submission = function(submission)
{
    const { ctx_id, bytes, ring_idx } = submission;
    const all = new Uint8Array(bytes.reduce((n, b) => n + b.length, 0));
    bytes.reduce((at, b) => { all.set(b, at); return at + b.length; }, 0);
    return [ctx_id, all, ring_idx];
};

/**
 * A snapshot's submission, submitted again (after the contexts are restored)
 * @param {!Array} saved from save_submission
 * @return {?function(function())} as submit
 */
Gfxstream.prototype.resubmit = function(saved)
{
    const [ctx_id, bytes, ring_idx] = saved;
    return this.submit(ctx_id, Uint8Array.from(bytes), ring_idx);
};

/**
 * A sync command's task: a decoder (Vulkan's) that knows the fence or
 * image says when its work is done; none: done at once
 * @param {!GfxstreamContext} ctx
 * @param {number} op
 * @param {!Array<number>} words
 * @return {?function(function())}
 */
Gfxstream.prototype.sync_task = function(ctx, op, words)
{
    for(const decoder of this.decoders)
    {
        if(decoder.sync_task)
        {
            const task = decoder.sync_task(ctx, op, words);
            if(task !== undefined) return task;
        }
    }
    return null;
};

/** The machine's timers: the rings whose decoding waited, again */
Gfxstream.prototype.timer = function(now)
{
    if(this.vk) this.vk.timer(now);
    for(const ctx of this.contexts.values())
    {
        for(const ring of ctx.rings.values()) if(!ring.waiting && ring.input_length) this.run(ctx, ring);
    }
};

/**
 * PING: what the guest wrote on the ring, into its stream, then decoded
 * @param {!GfxstreamContext} ctx
 * @param {!Ring} asg
 */
Gfxstream.prototype.run = function(ctx, asg)
{
    // (as gfxstream's render thread: after it says it needs a ping, what the
    // guest wrote meanwhile, without one, is read too)
    for(let pass = 0; pass < 8 && this.run_once(ctx, asg); pass++) {}
};

/** @return {boolean} whether the guest wrote more once the host said it needs a ping */
Gfxstream.prototype.run_once = function(ctx, asg)
{
    if(!asg.ready || asg.blob.map_offset < 0) return false;
    const view = this.view(), bytes = this.gpu.hostmem_bytes(), base = asg.blob.map_offset, buffer = base + RING_SIZE;
    const config = base + TO_HOST + CONFIG;
    view.setUint32(base + TO_HOST + STATE, HOST_CAN_CONSUME, true);
    // type 1: { offset, size } of the buffer, on the to-host ring
    const ring = base + TO_HOST;
    let read = view.getUint32(ring + READ_POS, true);
    const write = view.getUint32(ring + WRITE_POS, true);
    while((write - read >>> 0) >= 8)
    {
        const entry = ring + RING_BUF + (read & RING_BUF_SIZE - 1);
        const offset = view.getUint32(entry, true), size = view.getUint32(entry + 4, true);
        if(offset + size > BUFFER_SIZE)
        {
            this.error(ctx, "a transfer of [" + offset + ", +" + size + ") past the buffer");
            this.fail_ring(asg);
            break;
        }
        this.take(asg, bytes.slice(buffer + offset, buffer + offset + size));
        read = read + 8 >>> 0;
        view.setUint32(ring + READ_POS, read, true);
        view.setUint32(config + HOST_CONSUMED_POS, view.getUint32(config + HOST_CONSUMED_POS, true) + size >>> 0, true);
    }
    // type 3: a large transfer through its ring's view of the buffer
    const large = base + TO_HOST_LARGE;
    let large_read = view.getUint32(large + READ_POS, true);
    const large_write = view.getUint32(large + WRITE_POS, true);
    const available = large_write - large_read >>> 0;
    if(available && available <= BUFFER_SIZE)
    {
        const at = large_read & BUFFER_SIZE - 1, first = Math.min(available, BUFFER_SIZE - at);
        const data = new Uint8Array(available);
        data.set(bytes.subarray(buffer + at, buffer + at + first));
        if(first < available) data.set(bytes.subarray(buffer, buffer + available - first), first);
        this.take(asg, data);
        large_read = large_read + available >>> 0;
        view.setUint32(large + READ_POS, large_read, true);
    }
    this.decode(ctx, asg);
    this.set_host_state(asg);
    return !asg.waiting && !ctx.destroyed && asg.blob.map_offset === base &&
        (view.getUint32(ring + WRITE_POS, true) !== read || view.getUint32(large + WRITE_POS, true) !== large_read);
};

/** The host's state on a ring: rendering while a command waits, else waiting for a ping */
Gfxstream.prototype.set_host_state = function(ring)
{
    if(ring.blob.map_offset >= 0) this.view().setUint32(ring.blob.map_offset + TO_HOST + STATE, ring.waiting ? HOST_RENDERING : HOST_NEED_NOTIFY, true);
};

/**
 * Bytes of a ring's stream
 * @param {!Ring} ring
 * @param {!Uint8Array} data
 */
Gfxstream.prototype.take = function(ring, data)
{
    if(!data.length) return;
    ring.input.push(data);
    ring.input_length += data.length;
    this.stats.transfers++;
    this.stats.bytes += data.length;
};

/**
 * A ring's commands decoded, each whole one in order; a command that waits
 * stops this ring's decoding until it is done, one that comes later (AGAIN)
 * until another ring of the context has decoded a command
 * @param {!GfxstreamContext} ctx
 * @param {!Ring} ring
 */
Gfxstream.prototype.decode = function(ctx, ring)
{
    if(ring.waiting || ctx.destroyed) return;
    ring.blocked = false;
    if(ring.input.length > 1)
    {
        const all = new Uint8Array(ring.input_length);
        let at = 0;
        for(const part of ring.input) { all.set(part, at); at += part.length; }
        ring.input = [all];
    }
    let data = ring.input[0] || new Uint8Array(0), p = 0;
    if(!ring.flags_read)
    {
        // the client's flags, not used any more (gfxstream's RenderThread)
        if(data.length < 4) return;
        ring.flags_read = true;
        p = 4;
    }
    let decoded = false;
    while(data.length - p >= 8)
    {
        const view = new DataView(data.buffer, data.byteOffset + p, data.length - p);
        const opcode = view.getUint32(0, true), size = view.getUint32(4, true);
        if(size < 8)
        {
            this.error(ctx, "command " + opcode + " of " + size + " bytes");
            this.fail_ring(ring);
            p = data.length;
            break;
        }
        if(data.length - p < size) break;
        const command = data.subarray(p, p + size);
        const payload = data.subarray(p + 8, p + size);
        const decoder = this.decoders.find(d => opcode >= d.first && opcode <= d.last);
        if(!decoder)
        {
            p += size;
            this.stats.commands++;
            this.stats.unknown[opcode] = (this.stats.unknown[opcode] || 0) + 1;
            continue;
        }
        let wait = null;
        try
        {
            wait = decoder.decode(ctx, ring, opcode, payload, reply => this.reply(ctx, ring, reply));
        }
        catch(e)
        {
            this.error(ctx, decoder.name + " " + opcode + ": " + (e && e.message || e));
        }
        if(wait === AGAIN)
        {
            // (later: another ring's command first)
            ring.blocked = true;
            break;
        }
        p += size;
        this.stats.commands++;
        decoded = true;
        if(wait)
        {
            ring.waiting = true;
            ring.waiting_command = command;
            ring.input = [data.subarray(p)];
            ring.input_length = data.length - p;
            /** @type {function(function())} */ (wait)(() => {
                // (a restored snapshot's ring is another)
                if(ring.waiting_command !== command) return;
                ring.waiting = false;
                ring.waiting_command = null;
                if(ctx.destroyed) return;
                this.run(ctx, ring);
                // (rings whose commands came after it)
                this.wake_blocked(ctx, ring);
            });
            this.wake_blocked(ctx, ring);
            return;
        }
    }
    data = data.subarray(p);
    ring.input = data.length ? [data] : [];
    ring.input_length = data.length;
    if(decoded) this.wake_blocked(ctx, ring);
};

/**
 * A ring decoded a command: the context's rings whose command waited for
 * another's, decoded again
 * @param {!GfxstreamContext} ctx
 * @param {!Ring} by
 */
Gfxstream.prototype.wake_blocked = function(ctx, by)
{
    for(const ring of ctx.rings.values())
    {
        if(ring !== by && ring.blocked && !ring.waiting)
        {
            this.decode(ctx, ring);
            this.set_host_state(ring);
        }
    }
};

/**
 * A reply into the from-host ring's view of the buffer
 * @param {!GfxstreamContext} ctx
 * @param {!Ring} asg
 * @param {!Uint8Array} reply
 */
Gfxstream.prototype.reply = function(ctx, asg, reply)
{
    if(asg.blob.map_offset < 0 || !reply.length) return;
    const view = this.view(), bytes = this.gpu.hostmem_bytes(), base = asg.blob.map_offset, buffer = base + RING_SIZE;
    const ring = base + FROM_HOST_LARGE;
    const write = view.getUint32(ring + WRITE_POS, true), read = view.getUint32(ring + READ_POS, true);
    if((write - read >>> 0) + reply.length > BUFFER_SIZE)
    {
        this.error(ctx, "a reply of " + reply.length + " bytes with the guest's unread");
        return;
    }
    const at = write & BUFFER_SIZE - 1, first = Math.min(reply.length, BUFFER_SIZE - at);
    bytes.set(reply.subarray(0, first), buffer + at);
    if(first < reply.length) bytes.set(reply.subarray(first), buffer);
    view.setUint32(ring + WRITE_POS, write + reply.length >>> 0, true);
    this.stats.replies++;
};

/** The ring in error: the guest's reads and writes fail (in_error) */
Gfxstream.prototype.fail_ring = function(ring)
{
    if(ring.blob.map_offset >= 0) this.view().setUint32(ring.blob.map_offset + TO_HOST + CONFIG + IN_ERROR, 1, true);
};

/**
 * @param {!GfxstreamContext} ctx
 * @param {string} message
 */
Gfxstream.prototype.error = function(ctx, message)
{
    this.stats.errors++;
    this.stats.last_error = "context " + ctx.id + ": " + message;
};

// The process pipe (pipe resources)

/**
 * Whether RESOURCE_CREATE_3D's arguments are a pipe's (the guest's
 * VirtioGpuPipeStream: a PIPE_BUFFER bound VIRGL_BIND_CUSTOM)
 * @param {number} target
 * @param {number} bind
 * @return {boolean}
 */
Gfxstream.prototype.is_pipe = function(target, bind)
{
    return target === PIPE_BUFFER && !!(bind & BIND_CUSTOM);
};

/** @return {!Pipe} a new pipe */
Gfxstream.prototype.create_pipe = function()
{
    return new Pipe();
};

/**
 * TRANSFER_TO_HOST_3D of a pipe: the guest's writes (its service's name first)
 * @param {!Object} pipe a Pipe
 * @param {!Uint8Array} data
 */
Gfxstream.prototype.pipe_write = function(pipe, data)
{
    let p = 0;
    if(pipe.service === null)
    {
        for(; p < data.length && pipe.service === null; p++)
        {
            if(data[p] === 0) pipe.service = String.fromCharCode(...pipe.name);
            else pipe.name.push(data[p]);
        }
    }
    if(pipe.service === "pipe:GLProcessPipe" && !pipe.confirmed && data.length - p >= 4)
    {
        // a confirmation (100), answered with the process's unique id
        pipe.confirmed = true;
        const puid = this.next_puid++;
        for(let i = 0; i < 8; i++) pipe.output.push(i < 4 ? puid >>> 8 * i & 0xFF : 0);
    }
};

/**
 * TRANSFER_FROM_HOST_3D of a pipe: what the service has, at most length bytes
 * @param {!Object} pipe a Pipe
 * @param {number} length
 * @return {!Uint8Array}
 */
Gfxstream.prototype.pipe_read = function(pipe, length)
{
    return Uint8Array.from(pipe.output.splice(0, length));
};

// ---------------------------------------------------------------------------
// Snapshots: the contexts (rings, what their streams had not decoded yet,
// the decoders' state: Vulkan's objects), the process pipes; a command that
// waited is decoded again from its ring (gfxstream's waits are idempotent:
// queue and device idles, fences, semaphores, query results)

/** @return {!Array} */
Gfxstream.prototype.get_state = function()
{
    const contexts = [];
    for(const ctx of this.contexts.values())
    {
        const rings = [...ctx.rings.values()].map(r => {
            const parts = r.waiting && r.waiting_command ? [r.waiting_command, ...r.input] : r.input;
            const input = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
            parts.reduce((at, p) => { input.set(p, at); return at + p.length; }, 0);
            return [r.blob.id, r.ready, r.flags_read, input];
        });
        contexts.push([ctx.id, ctx.capset, rings, [...ctx.pending_blobs], ctx.sync,
            this.vulkan ? this.vulkan.save_context(ctx, o => o instanceof GfxstreamBlob ? ["blob", o.id] : null) : null]);
    }
    return [this.next_puid, contexts, this.vulkan ? this.vulkan.get_state() : null];
};

/**
 * @param {!Array} state from get_state
 * @param {function(number): GfxstreamBlob} blob_of the restored blob of a resource id
 */
Gfxstream.prototype.set_state = function(state, blob_of)
{
    // (the renderer was reset: the old contexts' waits never go on)
    for(const ctx of this.contexts.values())
    {
        ctx.destroyed = true;
        for(const ring of ctx.rings.values()) ring.waiting_command = null;
    }
    this.contexts.clear();
    const [next_puid, contexts, vulkan] = state;
    this.next_puid = next_puid;
    const restored = [];
    for(const [id, capset, rings, pending_blobs, sync, vulkan_context] of contexts)
    {
        const ctx = new GfxstreamContext(id, capset);
        this.contexts.set(id, ctx);
        for(const [blob_id, ready, flags_read, input] of rings)
        {
            const blob = blob_of(blob_id);
            if(!blob) continue;
            const ring = new Ring(blob);
            ring.ready = ready;
            ring.flags_read = flags_read;
            if(input.length)
            {
                // (decoded again by the timer, or once another ring's command is)
                ring.input = [Uint8Array.from(input)];
                ring.input_length = input.length;
                ring.blocked = true;
            }
            ctx.rings.set(blob_id, ring);
        }
        ctx.pending_blobs = new Map(pending_blobs);
        ctx.sync = sync;
        if(vulkan_context && this.vulkan) restored.push(this.vulkan.restore_context(ctx, vulkan_context, blob_of));
    }
    if(this.vulkan && vulkan) this.vulkan.set_state(vulkan, restored);
};

/**
 * Before a save: the rings run (the machine is stopped: nothing pings them)
 * until no command waits and `idle` says the device's requests are done,
 * for a while at most
 * @param {function(): boolean} idle
 * @return {!Promise}
 */
Gfxstream.prototype.settle = function(idle)
{
    const deadline = Date.now() + 5000;
    const waiting = () => [...this.contexts.values()].some(ctx => [...ctx.rings.values()].some(r => r.waiting));
    return new Promise(resolve => {
        const step = () => {
            if(this.vk) this.vk.wake();
            for(const ctx of this.contexts.values())
            {
                for(const ring of ctx.rings.values()) if(!ring.waiting) this.run(ctx, ring);
            }
            if(idle() && !waiting() || Date.now() > deadline) resolve(undefined);
            else setTimeout(step, 5);
        };
        step();
    });
};

/**
 * A pipe, for a snapshot
 * @param {!Object} pipe a Pipe
 * @return {!Array}
 */
Gfxstream.prototype.save_pipe = function(pipe)
{
    return [pipe.service, pipe.name, pipe.output, pipe.confirmed];
};

/**
 * @param {!Array} saved from save_pipe
 * @return {!Pipe}
 */
Gfxstream.prototype.restore_pipe = function(saved)
{
    const pipe = new Pipe();
    [pipe.service, pipe.name, pipe.output, pipe.confirmed] = saved;
    pipe.name = Array.from(pipe.name);
    pipe.output = Array.from(pipe.output);
    return pipe;
};
                                                                                                                                                                                                                source/v64/src/graphics_adapters/virtio_gpu/gfxstream_protocol.js                                   0000644 0000000 0000000 00001625017 00000000000 022620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/gfxstream_protocol_gen.mjs from gfxstream's guest
// encoder (mesa src/gfxstream/guest/vulkan_enc, the build pinned in
// docs/gfxstream-protocol.md); do not edit.
//
// gfxstream's Vulkan wire format: d_* read a request the guest's driver
// encoded, into objects with the C names (structs) or an object of the
// parameters (commands); e_* write a reply the driver decodes, from such
// objects (what is missing is written as zeros, an empty array or a null
// pointer).

/* eslint-disable */

// (tools/gfxstream_protocol_runtime.js, copied into gfxstream_protocol.js)
//
// gfxstream's Vulkan encoding (its cereal marshaling, "reserved" for
// requests): little endian, each value in its C size, no padding; 64-bit
// values (sizes, handles, VkDeviceSize, 64-bit flags) are numbers here, exact
// below 2**53; a pointer's presence and a size_t are 8 bytes big endian, a
// string's length and a string array's count 4 bytes big endian.

const MAX_COUNT = 1 << 24;

/**
 * Reads a command's parameters
 * @constructor
 * @param {!Uint8Array} bytes
 * @param {number=} start
 * @param {number=} end
 */
export function GfxReader(bytes, start, end)
{
    this.bytes = bytes;
    this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    this.p = start || 0;
    this.end = end === undefined ? bytes.length : end;
}

/** @param {number} n */
GfxReader.prototype.take = function(n)
{
    const at = this.p;
    if(at + n > this.end) throw new Error("gfxstream: read past the end of the command");
    this.p = at + n;
    return at;
};

GfxReader.prototype.u8 = function() { return this.view.getUint8(this.take(1)); };
GfxReader.prototype.i8 = function() { return this.view.getInt8(this.take(1)); };
GfxReader.prototype.u16 = function() { return this.view.getUint16(this.take(2), true); };
GfxReader.prototype.i16 = function() { return this.view.getInt16(this.take(2), true); };
GfxReader.prototype.u32 = function() { return this.view.getUint32(this.take(4), true); };
GfxReader.prototype.i32 = function() { return this.view.getInt32(this.take(4), true); };
GfxReader.prototype.f32 = function() { return this.view.getFloat32(this.take(4), true); };
GfxReader.prototype.f64 = function() { return this.view.getFloat64(this.take(8), true); };
GfxReader.prototype.u64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getUint32(at + 4, true) * 0x100000000;
};
GfxReader.prototype.i64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getInt32(at + 4, true) * 0x100000000;
};
/** a handle (the host's: the device allocates them) */
GfxReader.prototype.h = GfxReader.prototype.u64;
GfxReader.prototype.be32 = function() { return this.view.getUint32(this.take(4), false); };
GfxReader.prototype.be64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, false) * 0x100000000 + this.view.getUint32(at + 4, false);
};
/** a pointer's presence (the guest's pointer, big endian): whether it is not null */
GfxReader.prototype.ptr = function()
{
    const at = this.take(8);
    // (tests: where the guest's pointers are)
    if(this.presences) this.presences.push(at);
    return (this.view.getUint32(at, false) | this.view.getUint32(at + 4, false)) !== 0;
};
/** a 32-bit value the guest wrote without moving on (what comes next overwrites it) */
GfxReader.prototype.peek_u32 = function()
{
    return this.p + 4 <= this.end ? this.view.getUint32(this.p, true) : 0;
};
/** @param {number} n */
GfxReader.prototype.count = function(n)
{
    if(!(n >= 0 && n <= MAX_COUNT)) throw new Error("gfxstream: a count of " + n);
    return n;
};
/** n bytes as a string (latin1), up to the first NUL */
GfxReader.prototype.str = function(n)
{
    const at = this.take(this.count(n));
    let s = "";
    for(let i = 0; i < n; i++)
    {
        const c = this.bytes[at + i];
        if(!c) break;
        s += String.fromCharCode(c);
    }
    return s;
};
/** a string: its length (big endian), then its bytes */
GfxReader.prototype.string = function() { return this.str(this.be32()); };
/** strings: their count (big endian), then each */
GfxReader.prototype.strings = function()
{
    const out = new Array(this.count(this.be32()));
    for(let i = 0; i < out.length; i++) out[i] = this.string();
    return out;
};
/**
 * @param {Function} type
 * @param {number} size
 * @param {number} n
 */
GfxReader.prototype.typed = function(type, size, n)
{
    const at = this.take(this.count(n) * size);
    const out = new type(n);
    for(let i = 0; i < n; i++)
    {
        const p = at + i * size;
        out[i] = size === 1 ? this.bytes[p] : size === 2 ? this.view.getUint16(p, true) :
            type === Float32Array ? this.view.getFloat32(p, true) : type === Int32Array ? this.view.getInt32(p, true) : this.view.getUint32(p, true);
    }
    return out;
};
GfxReader.prototype.u8s = function(n) { return this.typed(Uint8Array, 1, n); };
GfxReader.prototype.u16s = function(n) { return this.typed(Uint16Array, 2, n); };
GfxReader.prototype.u32s = function(n) { return this.typed(Uint32Array, 4, n); };
GfxReader.prototype.i32s = function(n) { return this.typed(Int32Array, 4, n); };
GfxReader.prototype.f32s = function(n) { return this.typed(Float32Array, 4, n); };
GfxReader.prototype.u64s = function(n)
{
    const out = new Array(this.count(n));
    for(let i = 0; i < n; i++) out[i] = this.u64();
    return out;
};
GfxReader.prototype.i64s = GfxReader.prototype.u64s;
/** n bytes (a copy) */
GfxReader.prototype.bytes_of = function(n)
{
    const at = this.take(this.count(n));
    return this.bytes.slice(at, at + n);
};

/**
 * Writes a reply
 * @constructor
 * @param {number=} size to start with
 */
export function GfxWriter(size)
{
    this.bytes = new Uint8Array(size || 256);
    this.view = new DataView(this.bytes.buffer);
    this.p = 0;
}

/** @param {number} n */
GfxWriter.prototype.room = function(n)
{
    const at = this.p;
    if(at + n > this.bytes.length)
    {
        const bigger = new Uint8Array(Math.max(this.bytes.length * 2, at + n));
        bigger.set(this.bytes);
        this.bytes = bigger;
        this.view = new DataView(bigger.buffer);
    }
    this.p = at + n;
    return at;
};

/** @return {!Uint8Array} what was written */
GfxWriter.prototype.result = function() { return this.bytes.subarray(0, this.p); };

GfxWriter.prototype.u8 = function(v) { const at = this.room(1); this.view.setUint8(at, v & 0xFF); };
GfxWriter.prototype.i8 = GfxWriter.prototype.u8;
GfxWriter.prototype.u16 = function(v) { const at = this.room(2); this.view.setUint16(at, v & 0xFFFF, true); };
GfxWriter.prototype.i16 = GfxWriter.prototype.u16;
GfxWriter.prototype.u32 = function(v) { const at = this.room(4); this.view.setUint32(at, v >>> 0, true); };
GfxWriter.prototype.i32 = function(v) { const at = this.room(4); this.view.setInt32(at, v | 0, true); };
GfxWriter.prototype.f32 = function(v) { const at = this.room(4); this.view.setFloat32(at, v || 0, true); };
GfxWriter.prototype.f64 = function(v) { const at = this.room(8); this.view.setFloat64(at, v || 0, true); };
GfxWriter.prototype.u64 = function(v)
{
    const at = this.room(8);
    v = v || 0;
    // (~0ULL, VK_WHOLE_SIZE: 2**64 as a number)
    if(v >= 2 ** 64)
    {
        this.view.setUint32(at, 0xFFFFFFFF, true);
        this.view.setUint32(at + 4, 0xFFFFFFFF, true);
        return;
    }
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setUint32(at + 4, high, true);
};
GfxWriter.prototype.i64 = function(v)
{
    v = v || 0;
    if(v >= 0) return this.u64(v);
    const at = this.room(8);
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setInt32(at + 4, high, true);
};
GfxWriter.prototype.h = GfxWriter.prototype.u64;
GfxWriter.prototype.be32 = function(v) { const at = this.room(4); this.view.setUint32(at, v >>> 0, false); };
GfxWriter.prototype.be64 = function(v)
{
    const at = this.room(8);
    v = v || 0;
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, high, false);
    this.view.setUint32(at + 4, v - high * 0x100000000, false);
};
/** a pointer's presence: what the guest compares with null */
GfxWriter.prototype.ptr = function(present) { this.be64(present ? 1 : 0); };
/** a string (latin1) in n bytes, NUL padded */
GfxWriter.prototype.str = function(s, n)
{
    const at = this.room(n);
    s = s || "";
    for(let i = 0; i < n; i++) this.bytes[at + i] = i < s.length && i < n - 1 ? s.charCodeAt(i) & 0xFF : 0;
};
/** a string's bytes, without its length */
GfxWriter.prototype.chars = function(s, n)
{
    s = s || "";
    const at = this.room(n);
    for(let i = 0; i < n; i++) this.bytes[at + i] = s.charCodeAt(i) & 0xFF;
};
/** a string: its length (big endian), then its bytes */
GfxWriter.prototype.string = function(s)
{
    s = s || "";
    this.be32(s.length);
    this.chars(s, s.length);
};
/** strings: their count (big endian), then each */
GfxWriter.prototype.strings = function(a)
{
    a = a || [];
    this.be32(a.length);
    for(const s of a) this.string(s);
};
GfxWriter.prototype.u8s = function(a, n) { for(let i = 0; i < n; i++) this.u8(a ? a[i] : 0); };
GfxWriter.prototype.u16s = function(a, n) { for(let i = 0; i < n; i++) this.u16(a ? a[i] : 0); };
GfxWriter.prototype.u32s = function(a, n) { for(let i = 0; i < n; i++) this.u32(a ? a[i] : 0); };
GfxWriter.prototype.i32s = function(a, n) { for(let i = 0; i < n; i++) this.i32(a ? a[i] : 0); };
GfxWriter.prototype.f32s = function(a, n) { for(let i = 0; i < n; i++) this.f32(a ? a[i] : 0); };
GfxWriter.prototype.u64s = function(a, n) { for(let i = 0; i < n; i++) this.u64(a ? a[i] : 0); };
GfxWriter.prototype.i64s = GfxWriter.prototype.u64s;
GfxWriter.prototype.bytes_of = function(a, n)
{
    const at = this.room(n);
    if(a) this.bytes.set(a.length > n ? a.subarray(0, n) : a, at);
};

/** VK_STRUCTURE_TYPE_MAX_ENUM: a chain's root not set yet */
const ROOT_NONE = 2147483647;

function pnext_struct(table, stype, root)
{
    const v = table[stype];
    if(!v || Array.isArray(v)) return v || null;
    return v[root] || v["default"] || null;
}
/** whether one of a[start, end) holds */
function arrayany(a, start, end, f)
{
    for(let i = start; i < end; i++) if(a && f(a[i])) return true;
    return false;
}

function d_VkInstanceCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    const p0 = r.ptr();
    o.pApplicationInfo = null;
    if(p0)
    {
        o.pApplicationInfo = d_VkApplicationInfo(r, root);
    }
    o.enabledLayerCount = r.u32();
    let c1 = 0;
    c1 = r.be32();
    o.ppEnabledLayerNames = new Array(r.count(c1));
    for(let i = 0; i < c1; i++)
    {
        const l2 = r.be32();
        o.ppEnabledLayerNames[i] = "";
        if(l2)
        {
            o.ppEnabledLayerNames[i] = r.str(l2);
        }
    }
    o.enabledExtensionCount = r.u32();
    let c3 = 0;
    c3 = r.be32();
    o.ppEnabledExtensionNames = new Array(r.count(c3));
    for(let i = 0; i < c3; i++)
    {
        const l4 = r.be32();
        o.ppEnabledExtensionNames[i] = "";
        if(l4)
        {
            o.ppEnabledExtensionNames[i] = r.str(l4);
        }
    }
    return o;
}

function d_VkAllocationCallbacks(r, root)
{
    const o = {};
    const p0 = r.ptr();
    o.pUserData = null;
    if(p0)
    {
        o.pUserData = r.void();
    }
    o.pfnAllocation = r.be64();
    o.pfnReallocation = r.be64();
    o.pfnFree = r.be64();
    o.pfnInternalAllocation = r.be64();
    o.pfnInternalFree = r.be64();
    return o;
}

function d_VkPhysicalDeviceFeatures(r, root)
{
    const o = {};
    o.robustBufferAccess = r.u32();
    o.fullDrawIndexUint32 = r.u32();
    o.imageCubeArray = r.u32();
    o.independentBlend = r.u32();
    o.geometryShader = r.u32();
    o.tessellationShader = r.u32();
    o.sampleRateShading = r.u32();
    o.dualSrcBlend = r.u32();
    o.logicOp = r.u32();
    o.multiDrawIndirect = r.u32();
    o.drawIndirectFirstInstance = r.u32();
    o.depthClamp = r.u32();
    o.depthBiasClamp = r.u32();
    o.fillModeNonSolid = r.u32();
    o.depthBounds = r.u32();
    o.wideLines = r.u32();
    o.largePoints = r.u32();
    o.alphaToOne = r.u32();
    o.multiViewport = r.u32();
    o.samplerAnisotropy = r.u32();
    o.textureCompressionETC2 = r.u32();
    o.textureCompressionASTC_LDR = r.u32();
    o.textureCompressionBC = r.u32();
    o.occlusionQueryPrecise = r.u32();
    o.pipelineStatisticsQuery = r.u32();
    o.vertexPipelineStoresAndAtomics = r.u32();
    o.fragmentStoresAndAtomics = r.u32();
    o.shaderTessellationAndGeometryPointSize = r.u32();
    o.shaderImageGatherExtended = r.u32();
    o.shaderStorageImageExtendedFormats = r.u32();
    o.shaderStorageImageMultisample = r.u32();
    o.shaderStorageImageReadWithoutFormat = r.u32();
    o.shaderStorageImageWriteWithoutFormat = r.u32();
    o.shaderUniformBufferArrayDynamicIndexing = r.u32();
    o.shaderSampledImageArrayDynamicIndexing = r.u32();
    o.shaderStorageBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageImageArrayDynamicIndexing = r.u32();
    o.shaderClipDistance = r.u32();
    o.shaderCullDistance = r.u32();
    o.shaderFloat64 = r.u32();
    o.shaderInt64 = r.u32();
    o.shaderInt16 = r.u32();
    o.shaderResourceResidency = r.u32();
    o.shaderResourceMinLod = r.u32();
    o.sparseBinding = r.u32();
    o.sparseResidencyBuffer = r.u32();
    o.sparseResidencyImage2D = r.u32();
    o.sparseResidencyImage3D = r.u32();
    o.sparseResidency2Samples = r.u32();
    o.sparseResidency4Samples = r.u32();
    o.sparseResidency8Samples = r.u32();
    o.sparseResidency16Samples = r.u32();
    o.sparseResidencyAliased = r.u32();
    o.variableMultisampleRate = r.u32();
    o.inheritedQueries = r.u32();
    return o;
}

function e_VkPhysicalDeviceFeatures(w, o, root)
{
    o = o || {};
    w.u32(o.robustBufferAccess);
    w.u32(o.fullDrawIndexUint32);
    w.u32(o.imageCubeArray);
    w.u32(o.independentBlend);
    w.u32(o.geometryShader);
    w.u32(o.tessellationShader);
    w.u32(o.sampleRateShading);
    w.u32(o.dualSrcBlend);
    w.u32(o.logicOp);
    w.u32(o.multiDrawIndirect);
    w.u32(o.drawIndirectFirstInstance);
    w.u32(o.depthClamp);
    w.u32(o.depthBiasClamp);
    w.u32(o.fillModeNonSolid);
    w.u32(o.depthBounds);
    w.u32(o.wideLines);
    w.u32(o.largePoints);
    w.u32(o.alphaToOne);
    w.u32(o.multiViewport);
    w.u32(o.samplerAnisotropy);
    w.u32(o.textureCompressionETC2);
    w.u32(o.textureCompressionASTC_LDR);
    w.u32(o.textureCompressionBC);
    w.u32(o.occlusionQueryPrecise);
    w.u32(o.pipelineStatisticsQuery);
    w.u32(o.vertexPipelineStoresAndAtomics);
    w.u32(o.fragmentStoresAndAtomics);
    w.u32(o.shaderTessellationAndGeometryPointSize);
    w.u32(o.shaderImageGatherExtended);
    w.u32(o.shaderStorageImageExtendedFormats);
    w.u32(o.shaderStorageImageMultisample);
    w.u32(o.shaderStorageImageReadWithoutFormat);
    w.u32(o.shaderStorageImageWriteWithoutFormat);
    w.u32(o.shaderUniformBufferArrayDynamicIndexing);
    w.u32(o.shaderSampledImageArrayDynamicIndexing);
    w.u32(o.shaderStorageBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageImageArrayDynamicIndexing);
    w.u32(o.shaderClipDistance);
    w.u32(o.shaderCullDistance);
    w.u32(o.shaderFloat64);
    w.u32(o.shaderInt64);
    w.u32(o.shaderInt16);
    w.u32(o.shaderResourceResidency);
    w.u32(o.shaderResourceMinLod);
    w.u32(o.sparseBinding);
    w.u32(o.sparseResidencyBuffer);
    w.u32(o.sparseResidencyImage2D);
    w.u32(o.sparseResidencyImage3D);
    w.u32(o.sparseResidency2Samples);
    w.u32(o.sparseResidency4Samples);
    w.u32(o.sparseResidency8Samples);
    w.u32(o.sparseResidency16Samples);
    w.u32(o.sparseResidencyAliased);
    w.u32(o.variableMultisampleRate);
    w.u32(o.inheritedQueries);
}

function d_VkFormatProperties(r, root)
{
    const o = {};
    o.linearTilingFeatures = r.u32();
    o.optimalTilingFeatures = r.u32();
    o.bufferFeatures = r.u32();
    return o;
}

function e_VkFormatProperties(w, o, root)
{
    o = o || {};
    w.u32(o.linearTilingFeatures);
    w.u32(o.optimalTilingFeatures);
    w.u32(o.bufferFeatures);
}

function d_VkImageFormatProperties(r, root)
{
    const o = {};
    o.maxExtent = d_VkExtent3D(r, root);
    o.maxMipLevels = r.u32();
    o.maxArrayLayers = r.u32();
    o.sampleCounts = r.u32();
    o.maxResourceSize = r.u64();
    return o;
}

function e_VkImageFormatProperties(w, o, root)
{
    o = o || {};
    e_VkExtent3D(w, o.maxExtent, root);
    w.u32(o.maxMipLevels);
    w.u32(o.maxArrayLayers);
    w.u32(o.sampleCounts);
    w.u64(o.maxResourceSize);
}

function d_VkPhysicalDeviceProperties(r, root)
{
    const o = {};
    o.apiVersion = r.u32();
    o.driverVersion = r.u32();
    o.vendorID = r.u32();
    o.deviceID = r.u32();
    o.deviceType = r.i32();
    o.deviceName = r.str(256);
    o.pipelineCacheUUID = r.u8s(16);
    o.limits = d_VkPhysicalDeviceLimits(r, root);
    o.sparseProperties = d_VkPhysicalDeviceSparseProperties(r, root);
    return o;
}

function e_VkPhysicalDeviceProperties(w, o, root)
{
    o = o || {};
    w.u32(o.apiVersion);
    w.u32(o.driverVersion);
    w.u32(o.vendorID);
    w.u32(o.deviceID);
    w.i32(o.deviceType);
    w.str(o.deviceName, 256);
    w.u8s(o.pipelineCacheUUID, 16);
    e_VkPhysicalDeviceLimits(w, o.limits, root);
    e_VkPhysicalDeviceSparseProperties(w, o.sparseProperties, root);
}

function d_VkQueueFamilyProperties(r, root)
{
    const o = {};
    o.queueFlags = r.u32();
    o.queueCount = r.u32();
    o.timestampValidBits = r.u32();
    o.minImageTransferGranularity = d_VkExtent3D(r, root);
    return o;
}

function e_VkQueueFamilyProperties(w, o, root)
{
    o = o || {};
    w.u32(o.queueFlags);
    w.u32(o.queueCount);
    w.u32(o.timestampValidBits);
    e_VkExtent3D(w, o.minImageTransferGranularity, root);
}

function d_VkPhysicalDeviceMemoryProperties(r, root)
{
    const o = {};
    o.memoryTypeCount = r.u32();
    o.memoryTypes = new Array(r.count(32));
    for(let i = 0; i < 32; i++)
    {
        o.memoryTypes[i] = d_VkMemoryType(r, root);
    }
    o.memoryHeapCount = r.u32();
    o.memoryHeaps = new Array(r.count(16));
    for(let i = 0; i < 16; i++)
    {
        o.memoryHeaps[i] = d_VkMemoryHeap(r, root);
    }
    return o;
}

function e_VkPhysicalDeviceMemoryProperties(w, o, root)
{
    o = o || {};
    w.u32(o.memoryTypeCount);
    for(let i = 0; i < 32; i++)
    {
        e_VkMemoryType(w, o.memoryTypes?.[i], root);
    }
    w.u32(o.memoryHeapCount);
    for(let i = 0; i < 16; i++)
    {
        e_VkMemoryHeap(w, o.memoryHeaps?.[i], root);
    }
}

function d_VkDeviceCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.queueCreateInfoCount = r.u32();
    o.pQueueCreateInfos = new Array(r.count(o.queueCreateInfoCount));
    for(let i = 0; i < o.queueCreateInfoCount; i++)
    {
        o.pQueueCreateInfos[i] = d_VkDeviceQueueCreateInfo(r, root);
    }
    o.enabledLayerCount = r.u32();
    let c0 = 0;
    c0 = r.be32();
    o.ppEnabledLayerNames = new Array(r.count(c0));
    for(let i = 0; i < c0; i++)
    {
        const l1 = r.be32();
        o.ppEnabledLayerNames[i] = "";
        if(l1)
        {
            o.ppEnabledLayerNames[i] = r.str(l1);
        }
    }
    o.enabledExtensionCount = r.u32();
    let c2 = 0;
    c2 = r.be32();
    o.ppEnabledExtensionNames = new Array(r.count(c2));
    for(let i = 0; i < c2; i++)
    {
        const l3 = r.be32();
        o.ppEnabledExtensionNames[i] = "";
        if(l3)
        {
            o.ppEnabledExtensionNames[i] = r.str(l3);
        }
    }
    const p4 = r.ptr();
    o.pEnabledFeatures = null;
    if(p4)
    {
        o.pEnabledFeatures = d_VkPhysicalDeviceFeatures(r, root);
    }
    return o;
}

function d_VkExtensionProperties(r, root)
{
    const o = {};
    o.extensionName = r.str(256);
    o.specVersion = r.u32();
    return o;
}

function e_VkExtensionProperties(w, o, root)
{
    o = o || {};
    w.str(o.extensionName, 256);
    w.u32(o.specVersion);
}

function d_VkLayerProperties(r, root)
{
    const o = {};
    o.layerName = r.str(256);
    o.specVersion = r.u32();
    o.implementationVersion = r.u32();
    o.description = r.str(256);
    return o;
}

function e_VkLayerProperties(w, o, root)
{
    o = o || {};
    w.str(o.layerName, 256);
    w.u32(o.specVersion);
    w.u32(o.implementationVersion);
    w.str(o.description, 256);
}

function d_VkSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.waitSemaphoreCount = r.u32();
    if(o.waitSemaphoreCount)
    {
        o.pWaitSemaphores = new Array(r.count(o.waitSemaphoreCount));
        for(let k = 0; k < o.waitSemaphoreCount; k++)
        {
            o.pWaitSemaphores[k] = r.h();
        }
    }
    if((o.waitSemaphoreCount > 0))
    {
        o.pWaitDstStageMask = r.u32s(o.waitSemaphoreCount);
    }
    o.commandBufferCount = r.u32();
    if(o.commandBufferCount)
    {
        o.pCommandBuffers = new Array(r.count(o.commandBufferCount));
        for(let k = 0; k < o.commandBufferCount; k++)
        {
            o.pCommandBuffers[k] = r.h();
        }
    }
    o.signalSemaphoreCount = r.u32();
    if(o.signalSemaphoreCount)
    {
        o.pSignalSemaphores = new Array(r.count(o.signalSemaphoreCount));
        for(let k = 0; k < o.signalSemaphoreCount; k++)
        {
            o.pSignalSemaphores[k] = r.h();
        }
    }
    return o;
}

function d_VkMemoryAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.allocationSize = r.u64();
    o.memoryTypeIndex = r.u32();
    return o;
}

function d_VkMappedMemoryRange(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.memory = r.h();
    o.offset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkMemoryRequirements(r, root)
{
    const o = {};
    o.size = r.u64();
    o.alignment = r.u64();
    o.memoryTypeBits = r.u32();
    return o;
}

function e_VkMemoryRequirements(w, o, root)
{
    o = o || {};
    w.u64(o.size);
    w.u64(o.alignment);
    w.u32(o.memoryTypeBits);
}

function d_VkSparseImageMemoryRequirements(r, root)
{
    const o = {};
    o.formatProperties = d_VkSparseImageFormatProperties(r, root);
    o.imageMipTailFirstLod = r.u32();
    o.imageMipTailSize = r.u64();
    o.imageMipTailOffset = r.u64();
    o.imageMipTailStride = r.u64();
    return o;
}

function e_VkSparseImageMemoryRequirements(w, o, root)
{
    o = o || {};
    e_VkSparseImageFormatProperties(w, o.formatProperties, root);
    w.u32(o.imageMipTailFirstLod);
    w.u64(o.imageMipTailSize);
    w.u64(o.imageMipTailOffset);
    w.u64(o.imageMipTailStride);
}

function d_VkSparseImageFormatProperties(r, root)
{
    const o = {};
    o.aspectMask = r.u32();
    o.imageGranularity = d_VkExtent3D(r, root);
    o.flags = r.u32();
    return o;
}

function e_VkSparseImageFormatProperties(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    e_VkExtent3D(w, o.imageGranularity, root);
    w.u32(o.flags);
}

function d_VkBindSparseInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.waitSemaphoreCount = r.u32();
    if(o.waitSemaphoreCount)
    {
        o.pWaitSemaphores = new Array(r.count(o.waitSemaphoreCount));
        for(let k = 0; k < o.waitSemaphoreCount; k++)
        {
            o.pWaitSemaphores[k] = r.h();
        }
    }
    o.bufferBindCount = r.u32();
    o.pBufferBinds = new Array(r.count(o.bufferBindCount));
    for(let i = 0; i < o.bufferBindCount; i++)
    {
        o.pBufferBinds[i] = d_VkSparseBufferMemoryBindInfo(r, root);
    }
    o.imageOpaqueBindCount = r.u32();
    o.pImageOpaqueBinds = new Array(r.count(o.imageOpaqueBindCount));
    for(let i = 0; i < o.imageOpaqueBindCount; i++)
    {
        o.pImageOpaqueBinds[i] = d_VkSparseImageOpaqueMemoryBindInfo(r, root);
    }
    o.imageBindCount = r.u32();
    o.pImageBinds = new Array(r.count(o.imageBindCount));
    for(let i = 0; i < o.imageBindCount; i++)
    {
        o.pImageBinds[i] = d_VkSparseImageMemoryBindInfo(r, root);
    }
    o.signalSemaphoreCount = r.u32();
    if(o.signalSemaphoreCount)
    {
        o.pSignalSemaphores = new Array(r.count(o.signalSemaphoreCount));
        for(let k = 0; k < o.signalSemaphoreCount; k++)
        {
            o.pSignalSemaphores[k] = r.h();
        }
    }
    return o;
}

function d_VkFenceCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    return o;
}

function d_VkSemaphoreCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    return o;
}

function d_VkEventCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    return o;
}

function d_VkQueryPoolCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.queryType = r.i32();
    o.queryCount = r.u32();
    o.pipelineStatistics = r.u32();
    return o;
}

function d_VkBufferCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.size = r.u64();
    o.usage = r.u32();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    const p0 = r.ptr();
    o.pQueueFamilyIndices = null;
    if(p0)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            o.pQueueFamilyIndices = r.u32s(o.queueFamilyIndexCount);
        }
    }
    return o;
}

function d_VkBufferViewCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.buffer = r.h();
    o.format = r.i32();
    o.offset = r.u64();
    o.range = r.u64();
    return o;
}

function d_VkImageCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.imageType = r.i32();
    o.format = r.i32();
    o.extent = d_VkExtent3D(r, root);
    o.mipLevels = r.u32();
    o.arrayLayers = r.u32();
    o.samples = r.i32();
    o.tiling = r.i32();
    o.usage = r.u32();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    const p0 = r.ptr();
    o.pQueueFamilyIndices = null;
    if(p0)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            o.pQueueFamilyIndices = r.u32s(o.queueFamilyIndexCount);
        }
    }
    o.initialLayout = r.i32();
    return o;
}

function d_VkImageSubresource(r, root)
{
    const o = {};
    o.aspectMask = r.u32();
    o.mipLevel = r.u32();
    o.arrayLayer = r.u32();
    return o;
}

function d_VkSubresourceLayout(r, root)
{
    const o = {};
    o.offset = r.u64();
    o.size = r.u64();
    o.rowPitch = r.u64();
    o.arrayPitch = r.u64();
    o.depthPitch = r.u64();
    return o;
}

function e_VkSubresourceLayout(w, o, root)
{
    o = o || {};
    w.u64(o.offset);
    w.u64(o.size);
    w.u64(o.rowPitch);
    w.u64(o.arrayPitch);
    w.u64(o.depthPitch);
}

function d_VkImageViewCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.image = r.h();
    o.viewType = r.i32();
    o.format = r.i32();
    o.components = d_VkComponentMapping(r, root);
    o.subresourceRange = d_VkImageSubresourceRange(r, root);
    return o;
}

function d_VkShaderModuleCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.codeSize = r.be64();
    if((Math.trunc(o.codeSize / 4) > 0))
    {
        o.pCode = r.u32s(Math.trunc(o.codeSize / 4));
    }
    return o;
}

function d_VkPipelineCacheCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.initialDataSize = r.be64();
    if((o.initialDataSize > 0))
    {
        o.pInitialData = r.bytes_of(o.initialDataSize);
    }
    return o;
}

function d_VkGraphicsPipelineCreateInfo(r, root)
{
    const o = {};
    let hasRasterization = 1;
    hasRasterization = r.be32();
    let hasTessellation = 1;
    hasTessellation = r.be32();
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.stageCount = r.u32();
    o.pStages = new Array(r.count(o.stageCount));
    for(let i = 0; i < o.stageCount; i++)
    {
        o.pStages[i] = d_VkPipelineShaderStageCreateInfo(r, root);
    }
    const p0 = r.ptr();
    o.pVertexInputState = null;
    if(p0)
    {
        o.pVertexInputState = d_VkPipelineVertexInputStateCreateInfo(r, root);
    }
    const p1 = r.ptr();
    o.pInputAssemblyState = null;
    if(p1)
    {
        o.pInputAssemblyState = d_VkPipelineInputAssemblyStateCreateInfo(r, root);
    }
    const p2 = r.ptr();
    o.pTessellationState = null;
    if(p2)
    {
        if(hasTessellation)
        {
            o.pTessellationState = d_VkPipelineTessellationStateCreateInfo(r, root);
        }
    }
    const p3 = r.ptr();
    o.pViewportState = null;
    if(p3)
    {
        if(hasRasterization)
        {
            o.pViewportState = d_VkPipelineViewportStateCreateInfo(r, root);
        }
    }
    const p4 = r.ptr();
    o.pRasterizationState = null;
    if(p4)
    {
        o.pRasterizationState = d_VkPipelineRasterizationStateCreateInfo(r, root);
    }
    const p5 = r.ptr();
    o.pMultisampleState = null;
    if(p5)
    {
        if(hasRasterization)
        {
            o.pMultisampleState = d_VkPipelineMultisampleStateCreateInfo(r, root);
        }
    }
    const p6 = r.ptr();
    o.pDepthStencilState = null;
    if(p6)
    {
        if(hasRasterization)
        {
            o.pDepthStencilState = d_VkPipelineDepthStencilStateCreateInfo(r, root);
        }
    }
    const p7 = r.ptr();
    o.pColorBlendState = null;
    if(p7)
    {
        if(hasRasterization)
        {
            o.pColorBlendState = d_VkPipelineColorBlendStateCreateInfo(r, root);
        }
    }
    const p8 = r.ptr();
    o.pDynamicState = null;
    if(p8)
    {
        o.pDynamicState = d_VkPipelineDynamicStateCreateInfo(r, root);
    }
    o.layout = r.h();
    o.renderPass = r.h();
    o.subpass = r.u32();
    o.basePipelineHandle = r.h();
    o.basePipelineIndex = r.i32();
    return o;
}

function d_VkComputePipelineCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.stage = d_VkPipelineShaderStageCreateInfo(r, root);
    o.layout = r.h();
    o.basePipelineHandle = r.h();
    o.basePipelineIndex = r.i32();
    return o;
}

function d_VkPipelineLayoutCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.setLayoutCount = r.u32();
    if(o.setLayoutCount)
    {
        o.pSetLayouts = new Array(r.count(o.setLayoutCount));
        for(let k = 0; k < o.setLayoutCount; k++)
        {
            o.pSetLayouts[k] = r.h();
        }
    }
    o.pushConstantRangeCount = r.u32();
    o.pPushConstantRanges = new Array(r.count(o.pushConstantRangeCount));
    for(let i = 0; i < o.pushConstantRangeCount; i++)
    {
        o.pPushConstantRanges[i] = d_VkPushConstantRange(r, root);
    }
    return o;
}

function d_VkSamplerCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.magFilter = r.i32();
    o.minFilter = r.i32();
    o.mipmapMode = r.i32();
    o.addressModeU = r.i32();
    o.addressModeV = r.i32();
    o.addressModeW = r.i32();
    o.mipLodBias = r.f32();
    o.anisotropyEnable = r.u32();
    o.maxAnisotropy = r.f32();
    o.compareEnable = r.u32();
    o.compareOp = r.i32();
    o.minLod = r.f32();
    o.maxLod = r.f32();
    o.borderColor = r.i32();
    o.unnormalizedCoordinates = r.u32();
    return o;
}

function d_VkDescriptorSetLayoutCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.bindingCount = r.u32();
    o.pBindings = new Array(r.count(o.bindingCount));
    for(let i = 0; i < o.bindingCount; i++)
    {
        o.pBindings[i] = d_VkDescriptorSetLayoutBinding(r, root);
    }
    return o;
}

function d_VkDescriptorPoolCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.maxSets = r.u32();
    o.poolSizeCount = r.u32();
    o.pPoolSizes = new Array(r.count(o.poolSizeCount));
    for(let i = 0; i < o.poolSizeCount; i++)
    {
        o.pPoolSizes[i] = d_VkDescriptorPoolSize(r, root);
    }
    return o;
}

function d_VkDescriptorSetAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.descriptorPool = r.h();
    o.descriptorSetCount = r.u32();
    if(o.descriptorSetCount)
    {
        o.pSetLayouts = new Array(r.count(o.descriptorSetCount));
        for(let k = 0; k < o.descriptorSetCount; k++)
        {
            o.pSetLayouts[k] = r.h();
        }
    }
    return o;
}

function d_VkWriteDescriptorSet(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.dstSet = r.h();
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
    o.descriptorType = r.i32();
    const p0 = r.ptr();
    o.pImageInfo = null;
    if(p0)
    {
        o.pImageInfo = [];
        if((((((0 === o.descriptorType) || (1 === o.descriptorType)) || (2 === o.descriptorType)) || (3 === o.descriptorType)) || (10 === o.descriptorType)))
        {
            o.pImageInfo = new Array(r.count(o.descriptorCount));
            for(let i = 0; i < o.descriptorCount; i++)
            {
                o.pImageInfo[i] = d_VkDescriptorImageInfo(r, root);
            }
        }
    }
    const p1 = r.ptr();
    o.pBufferInfo = null;
    if(p1)
    {
        o.pBufferInfo = [];
        if(((((6 === o.descriptorType) || (8 === o.descriptorType)) || (7 === o.descriptorType)) || (9 === o.descriptorType)))
        {
            o.pBufferInfo = new Array(r.count(o.descriptorCount));
            for(let i = 0; i < o.descriptorCount; i++)
            {
                o.pBufferInfo[i] = d_VkDescriptorBufferInfo(r, root);
            }
        }
    }
    const p2 = r.ptr();
    o.pTexelBufferView = null;
    if(p2)
    {
        o.pTexelBufferView = [];
        if(((4 === o.descriptorType) || (5 === o.descriptorType)))
        {
            if(o.descriptorCount)
            {
                o.pTexelBufferView = new Array(r.count(o.descriptorCount));
                for(let k = 0; k < o.descriptorCount; k++)
                {
                    o.pTexelBufferView[k] = r.h();
                }
            }
        }
    }
    return o;
}

function d_VkCopyDescriptorSet(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcSet = r.h();
    o.srcBinding = r.u32();
    o.srcArrayElement = r.u32();
    o.dstSet = r.h();
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
    return o;
}

function d_VkFramebufferCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.renderPass = r.h();
    o.attachmentCount = r.u32();
    if(((o.flags & 1) === 0))
    {
        if(o.attachmentCount)
        {
            o.pAttachments = new Array(r.count(o.attachmentCount));
            for(let k = 0; k < o.attachmentCount; k++)
            {
                o.pAttachments[k] = r.h();
            }
        }
    }
    o.width = r.u32();
    o.height = r.u32();
    o.layers = r.u32();
    return o;
}

function d_VkRenderPassCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.attachmentCount = r.u32();
    o.pAttachments = new Array(r.count(o.attachmentCount));
    for(let i = 0; i < o.attachmentCount; i++)
    {
        o.pAttachments[i] = d_VkAttachmentDescription(r, root);
    }
    o.subpassCount = r.u32();
    o.pSubpasses = new Array(r.count(o.subpassCount));
    for(let i = 0; i < o.subpassCount; i++)
    {
        o.pSubpasses[i] = d_VkSubpassDescription(r, root);
    }
    o.dependencyCount = r.u32();
    o.pDependencies = new Array(r.count(o.dependencyCount));
    for(let i = 0; i < o.dependencyCount; i++)
    {
        o.pDependencies[i] = d_VkSubpassDependency(r, root);
    }
    return o;
}

function d_VkExtent2D(r, root)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    return o;
}

function e_VkExtent2D(w, o, root)
{
    o = o || {};
    w.u32(o.width);
    w.u32(o.height);
}

function d_VkCommandPoolCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
    return o;
}

function d_VkCommandBufferAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.commandPool = r.h();
    o.level = r.i32();
    o.commandBufferCount = r.u32();
    return o;
}

function d_VkCommandBufferBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    const p0 = r.ptr();
    o.pInheritanceInfo = null;
    if(p0)
    {
        o.pInheritanceInfo = d_VkCommandBufferInheritanceInfo(r, root);
    }
    return o;
}

function d_VkViewport(r, root)
{
    const o = {};
    o.x = r.f32();
    o.y = r.f32();
    o.width = r.f32();
    o.height = r.f32();
    o.minDepth = r.f32();
    o.maxDepth = r.f32();
    return o;
}

function d_VkRect2D(r, root)
{
    const o = {};
    o.offset = d_VkOffset2D(r, root);
    o.extent = d_VkExtent2D(r, root);
    return o;
}

function d_VkBufferCopy(r, root)
{
    const o = {};
    o.srcOffset = r.u64();
    o.dstOffset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkImageCopy(r, root)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffset = d_VkOffset3D(r, root);
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffset = d_VkOffset3D(r, root);
    o.extent = d_VkExtent3D(r, root);
    return o;
}

function d_VkImageBlit(r, root)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffsets = new Array(r.count(2));
    for(let i = 0; i < 2; i++)
    {
        o.srcOffsets[i] = d_VkOffset3D(r, root);
    }
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffsets = new Array(r.count(2));
    for(let i = 0; i < 2; i++)
    {
        o.dstOffsets[i] = d_VkOffset3D(r, root);
    }
    return o;
}

function d_VkBufferImageCopy(r, root)
{
    const o = {};
    o.bufferOffset = r.u64();
    o.bufferRowLength = r.u32();
    o.bufferImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r, root);
    o.imageOffset = d_VkOffset3D(r, root);
    o.imageExtent = d_VkExtent3D(r, root);
    return o;
}

function d_VkClearColorValue(r, root)
{
    const o = {};
    o.uint32 = r.u32s(4);
    o.int32 = new Int32Array(o.uint32.buffer);
    o.float32 = new Float32Array(o.uint32.buffer);
    return o;
}

function d_VkImageSubresourceRange(r, root)
{
    const o = {};
    o.aspectMask = r.u32();
    o.baseMipLevel = r.u32();
    o.levelCount = r.u32();
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}

function d_VkClearDepthStencilValue(r, root)
{
    const o = {};
    o.depth = r.f32();
    o.stencil = r.u32();
    return o;
}

function d_VkClearAttachment(r, root)
{
    const o = {};
    o.aspectMask = r.u32();
    o.colorAttachment = r.u32();
    o.clearValue = d_VkClearValue(r, root);
    return o;
}

function d_VkClearRect(r, root)
{
    const o = {};
    o.rect = d_VkRect2D(r, root);
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}

function d_VkImageResolve(r, root)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffset = d_VkOffset3D(r, root);
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffset = d_VkOffset3D(r, root);
    o.extent = d_VkExtent3D(r, root);
    return o;
}

function d_VkMemoryBarrier(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    return o;
}

function d_VkBufferMemoryBarrier(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.buffer = r.h();
    o.offset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkImageMemoryBarrier(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.image = r.h();
    o.subresourceRange = d_VkImageSubresourceRange(r, root);
    return o;
}

function d_VkRenderPassBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.renderPass = r.h();
    o.framebuffer = r.h();
    o.renderArea = d_VkRect2D(r, root);
    o.clearValueCount = r.u32();
    const p0 = r.ptr();
    o.pClearValues = null;
    if(p0)
    {
        o.pClearValues = [];
        o.pClearValues = new Array(r.count(o.clearValueCount));
        for(let i = 0; i < o.clearValueCount; i++)
        {
            o.pClearValues[i] = d_VkClearValue(r, root);
        }
    }
    return o;
}

function d_VkBindBufferMemoryInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.buffer = r.h();
    o.memory = r.h();
    o.memoryOffset = r.u64();
    return o;
}

function d_VkBindImageMemoryInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.image = r.h();
    o.memory = r.h();
    o.memoryOffset = r.u64();
    return o;
}

function d_VkPhysicalDeviceGroupProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.physicalDeviceCount = r.u32();
    o.physicalDevices = r.u64s(32);
    o.subsetAllocation = r.u32();
    return o;
}

function e_VkPhysicalDeviceGroupProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.physicalDeviceCount);
    w.u64s(o.physicalDevices, 32);
    w.u32(o.subsetAllocation);
}

function d_VkImageMemoryRequirementsInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.image = r.h();
    return o;
}

function d_VkMemoryRequirements2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.memoryRequirements = d_VkMemoryRequirements(r, root);
    return o;
}

function e_VkMemoryRequirements2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkMemoryRequirements(w, o.memoryRequirements, root);
}

function d_VkBufferMemoryRequirementsInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.buffer = r.h();
    return o;
}

function d_VkImageSparseMemoryRequirementsInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.image = r.h();
    return o;
}

function d_VkSparseImageMemoryRequirements2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.memoryRequirements = d_VkSparseImageMemoryRequirements(r, root);
    return o;
}

function e_VkSparseImageMemoryRequirements2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkSparseImageMemoryRequirements(w, o.memoryRequirements, root);
}

function d_VkPhysicalDeviceFeatures2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.features = d_VkPhysicalDeviceFeatures(r, root);
    return o;
}

function e_VkPhysicalDeviceFeatures2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkPhysicalDeviceFeatures(w, o.features, root);
}

function d_VkPhysicalDeviceProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.properties = d_VkPhysicalDeviceProperties(r, root);
    return o;
}

function e_VkPhysicalDeviceProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkPhysicalDeviceProperties(w, o.properties, root);
}

function d_VkFormatProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.formatProperties = d_VkFormatProperties(r, root);
    return o;
}

function e_VkFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkFormatProperties(w, o.formatProperties, root);
}

function d_VkPhysicalDeviceImageFormatInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.format = r.i32();
    o.type = r.i32();
    o.tiling = r.i32();
    o.usage = r.u32();
    o.flags = r.u32();
    return o;
}

function d_VkImageFormatProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageFormatProperties = d_VkImageFormatProperties(r, root);
    return o;
}

function e_VkImageFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkImageFormatProperties(w, o.imageFormatProperties, root);
}

function d_VkQueueFamilyProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.queueFamilyProperties = d_VkQueueFamilyProperties(r, root);
    return o;
}

function e_VkQueueFamilyProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkQueueFamilyProperties(w, o.queueFamilyProperties, root);
}

function d_VkPhysicalDeviceMemoryProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.memoryProperties = d_VkPhysicalDeviceMemoryProperties(r, root);
    return o;
}

function e_VkPhysicalDeviceMemoryProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkPhysicalDeviceMemoryProperties(w, o.memoryProperties, root);
}

function d_VkPhysicalDeviceSparseImageFormatInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.format = r.i32();
    o.type = r.i32();
    o.samples = r.i32();
    o.usage = r.u32();
    o.tiling = r.i32();
    return o;
}

function d_VkSparseImageFormatProperties2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.properties = d_VkSparseImageFormatProperties(r, root);
    return o;
}

function e_VkSparseImageFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkSparseImageFormatProperties(w, o.properties, root);
}

function d_VkDeviceQueueInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
    o.queueIndex = r.u32();
    return o;
}

function d_VkSamplerYcbcrConversionCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.format = r.i32();
    o.ycbcrModel = r.i32();
    o.ycbcrRange = r.i32();
    o.components = d_VkComponentMapping(r, root);
    o.xChromaOffset = r.i32();
    o.yChromaOffset = r.i32();
    o.chromaFilter = r.i32();
    o.forceExplicitReconstruction = r.u32();
    return o;
}

function d_VkDescriptorUpdateTemplateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.descriptorUpdateEntryCount = r.u32();
    o.pDescriptorUpdateEntries = new Array(r.count(o.descriptorUpdateEntryCount));
    for(let i = 0; i < o.descriptorUpdateEntryCount; i++)
    {
        o.pDescriptorUpdateEntries[i] = d_VkDescriptorUpdateTemplateEntry(r, root);
    }
    o.templateType = r.i32();
    o.descriptorSetLayout = r.h();
    o.pipelineBindPoint = r.i32();
    o.pipelineLayout = r.h();
    o.set = r.u32();
    return o;
}

function d_VkPhysicalDeviceExternalBufferInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.usage = r.u32();
    o.handleType = r.i32();
    return o;
}

function d_VkExternalBufferProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.externalMemoryProperties = d_VkExternalMemoryProperties(r, root);
    return o;
}

function e_VkExternalBufferProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkExternalMemoryProperties(w, o.externalMemoryProperties, root);
}

function d_VkPhysicalDeviceExternalFenceInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleType = r.i32();
    return o;
}

function d_VkExternalFenceProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalFenceFeatures = r.u32();
    return o;
}

function e_VkExternalFenceProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalFenceFeatures);
}

function d_VkPhysicalDeviceExternalSemaphoreInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleType = r.i32();
    return o;
}

function d_VkExternalSemaphoreProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalSemaphoreFeatures = r.u32();
    return o;
}

function e_VkExternalSemaphoreProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalSemaphoreFeatures);
}

function d_VkDescriptorSetLayoutSupport(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.supported = r.u32();
    return o;
}

function e_VkDescriptorSetLayoutSupport(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.supported);
}

function d_VkRenderPassCreateInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.attachmentCount = r.u32();
    o.pAttachments = new Array(r.count(o.attachmentCount));
    for(let i = 0; i < o.attachmentCount; i++)
    {
        o.pAttachments[i] = d_VkAttachmentDescription2(r, root);
    }
    o.subpassCount = r.u32();
    o.pSubpasses = new Array(r.count(o.subpassCount));
    for(let i = 0; i < o.subpassCount; i++)
    {
        o.pSubpasses[i] = d_VkSubpassDescription2(r, root);
    }
    o.dependencyCount = r.u32();
    o.pDependencies = new Array(r.count(o.dependencyCount));
    for(let i = 0; i < o.dependencyCount; i++)
    {
        o.pDependencies[i] = d_VkSubpassDependency2(r, root);
    }
    o.correlatedViewMaskCount = r.u32();
    if((o.correlatedViewMaskCount > 0))
    {
        o.pCorrelatedViewMasks = r.u32s(o.correlatedViewMaskCount);
    }
    return o;
}

function d_VkSubpassBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.contents = r.i32();
    return o;
}

function d_VkSubpassEndInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    return o;
}

function d_VkSemaphoreWaitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.semaphoreCount = r.u32();
    if(o.semaphoreCount)
    {
        o.pSemaphores = new Array(r.count(o.semaphoreCount));
        for(let k = 0; k < o.semaphoreCount; k++)
        {
            o.pSemaphores[k] = r.h();
        }
    }
    if((o.semaphoreCount > 0))
    {
        o.pValues = r.u64s(o.semaphoreCount);
    }
    return o;
}

function d_VkSemaphoreSignalInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.semaphore = r.h();
    o.value = r.u64();
    return o;
}

function d_VkBufferDeviceAddressInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.buffer = r.h();
    return o;
}

function d_VkDeviceMemoryOpaqueCaptureAddressInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.memory = r.h();
    return o;
}

function d_VkPhysicalDeviceToolProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.name = r.str(256);
    o.version = r.str(256);
    o.purposes = r.u32();
    o.description = r.str(256);
    o.layer = r.str(256);
    return o;
}

function e_VkPhysicalDeviceToolProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.version, 256);
    w.u32(o.purposes);
    w.str(o.description, 256);
    w.str(o.layer, 256);
}

function d_VkPrivateDataSlotCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    return o;
}

function d_VkDependencyInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.dependencyFlags = r.u32();
    o.memoryBarrierCount = r.u32();
    o.pMemoryBarriers = new Array(r.count(o.memoryBarrierCount));
    for(let i = 0; i < o.memoryBarrierCount; i++)
    {
        o.pMemoryBarriers[i] = d_VkMemoryBarrier2(r, root);
    }
    o.bufferMemoryBarrierCount = r.u32();
    o.pBufferMemoryBarriers = new Array(r.count(o.bufferMemoryBarrierCount));
    for(let i = 0; i < o.bufferMemoryBarrierCount; i++)
    {
        o.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier2(r, root);
    }
    o.imageMemoryBarrierCount = r.u32();
    o.pImageMemoryBarriers = new Array(r.count(o.imageMemoryBarrierCount));
    for(let i = 0; i < o.imageMemoryBarrierCount; i++)
    {
        o.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier2(r, root);
    }
    return o;
}

function d_VkSubmitInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.waitSemaphoreInfoCount = r.u32();
    o.pWaitSemaphoreInfos = new Array(r.count(o.waitSemaphoreInfoCount));
    for(let i = 0; i < o.waitSemaphoreInfoCount; i++)
    {
        o.pWaitSemaphoreInfos[i] = d_VkSemaphoreSubmitInfo(r, root);
    }
    o.commandBufferInfoCount = r.u32();
    o.pCommandBufferInfos = new Array(r.count(o.commandBufferInfoCount));
    for(let i = 0; i < o.commandBufferInfoCount; i++)
    {
        o.pCommandBufferInfos[i] = d_VkCommandBufferSubmitInfo(r, root);
    }
    o.signalSemaphoreInfoCount = r.u32();
    o.pSignalSemaphoreInfos = new Array(r.count(o.signalSemaphoreInfoCount));
    for(let i = 0; i < o.signalSemaphoreInfoCount; i++)
    {
        o.pSignalSemaphoreInfos[i] = d_VkSemaphoreSubmitInfo(r, root);
    }
    return o;
}

function d_VkCopyBufferInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcBuffer = r.h();
    o.dstBuffer = r.h();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkBufferCopy2(r, root);
    }
    return o;
}

function d_VkCopyImageInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkImageCopy2(r, root);
    }
    return o;
}

function d_VkCopyBufferToImageInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcBuffer = r.h();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkBufferImageCopy2(r, root);
    }
    return o;
}

function d_VkCopyImageToBufferInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstBuffer = r.h();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkBufferImageCopy2(r, root);
    }
    return o;
}

function d_VkBlitImageInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkImageBlit2(r, root);
    }
    o.filter = r.i32();
    return o;
}

function d_VkResolveImageInfo2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkImageResolve2(r, root);
    }
    return o;
}

function d_VkRenderingInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.renderArea = d_VkRect2D(r, root);
    o.layerCount = r.u32();
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    o.pColorAttachments = new Array(r.count(o.colorAttachmentCount));
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        o.pColorAttachments[i] = d_VkRenderingAttachmentInfo(r, root);
    }
    const p0 = r.ptr();
    o.pDepthAttachment = null;
    if(p0)
    {
        o.pDepthAttachment = d_VkRenderingAttachmentInfo(r, root);
    }
    const p1 = r.ptr();
    o.pStencilAttachment = null;
    if(p1)
    {
        o.pStencilAttachment = d_VkRenderingAttachmentInfo(r, root);
    }
    return o;
}

function d_VkDeviceBufferMemoryRequirements(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pCreateInfo = d_VkBufferCreateInfo(r, root);
    return o;
}

function d_VkDeviceImageMemoryRequirements(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pCreateInfo = d_VkImageCreateInfo(r, root);
    o.planeAspect = r.i32();
    return o;
}

function d_VkMemoryMapInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.memory = r.h();
    o.offset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkMemoryUnmapInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.memory = r.h();
    return o;
}

function d_VkRenderingAreaInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const p0 = r.ptr();
    o.pColorAttachmentFormats = null;
    if(p0)
    {
        if((o.colorAttachmentCount > 0))
        {
            o.pColorAttachmentFormats = r.i32s(o.colorAttachmentCount);
        }
    }
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    return o;
}

function d_VkDeviceImageSubresourceInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pCreateInfo = d_VkImageCreateInfo(r, root);
    o.pSubresource = d_VkImageSubresource2(r, root);
    return o;
}

function d_VkSubresourceLayout2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.subresourceLayout = d_VkSubresourceLayout(r, root);
    return o;
}

function e_VkSubresourceLayout2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkSubresourceLayout(w, o.subresourceLayout, root);
}

function d_VkImageSubresource2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageSubresource = d_VkImageSubresource(r, root);
    return o;
}

function d_VkRenderingAttachmentLocationInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.colorAttachmentCount = r.u32();
    const p0 = r.ptr();
    o.pColorAttachmentLocations = null;
    if(p0)
    {
        if((o.colorAttachmentCount > 0))
        {
            o.pColorAttachmentLocations = r.u32s(o.colorAttachmentCount);
        }
    }
    return o;
}

function d_VkRenderingInputAttachmentIndexInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.colorAttachmentCount = r.u32();
    const p0 = r.ptr();
    o.pColorAttachmentInputIndices = null;
    if(p0)
    {
        if((o.colorAttachmentCount > 0))
        {
            o.pColorAttachmentInputIndices = r.u32s(o.colorAttachmentCount);
        }
    }
    const p1 = r.ptr();
    o.pDepthInputAttachmentIndex = null;
    if(p1)
    {
        o.pDepthInputAttachmentIndex = r.u32();
    }
    const p2 = r.ptr();
    o.pStencilInputAttachmentIndex = null;
    if(p2)
    {
        o.pStencilInputAttachmentIndex = r.u32();
    }
    return o;
}

function d_VkBindDescriptorSetsInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stageFlags = r.u32();
    o.layout = r.h();
    o.firstSet = r.u32();
    o.descriptorSetCount = r.u32();
    if(o.descriptorSetCount)
    {
        o.pDescriptorSets = new Array(r.count(o.descriptorSetCount));
        for(let k = 0; k < o.descriptorSetCount; k++)
        {
            o.pDescriptorSets[k] = r.h();
        }
    }
    o.dynamicOffsetCount = r.u32();
    const p0 = r.ptr();
    o.pDynamicOffsets = null;
    if(p0)
    {
        if((o.dynamicOffsetCount > 0))
        {
            o.pDynamicOffsets = r.u32s(o.dynamicOffsetCount);
        }
    }
    return o;
}

function d_VkPushConstantsInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.layout = r.h();
    o.stageFlags = r.u32();
    o.offset = r.u32();
    o.size = r.u32();
    if((o.size > 0))
    {
        o.pValues = r.bytes_of(o.size);
    }
    return o;
}

function d_VkPushDescriptorSetInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stageFlags = r.u32();
    o.layout = r.h();
    o.set = r.u32();
    o.descriptorWriteCount = r.u32();
    o.pDescriptorWrites = new Array(r.count(o.descriptorWriteCount));
    for(let i = 0; i < o.descriptorWriteCount; i++)
    {
        o.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r, root);
    }
    return o;
}

function d_VkPushDescriptorSetWithTemplateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.descriptorUpdateTemplate = r.h();
    o.layout = r.h();
    o.set = r.u32();
    o.pData = r.void();
    return o;
}

function d_VkCopyMemoryToImageInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkMemoryToImageCopy(r, root);
    }
    return o;
}

function d_VkCopyImageToMemoryInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkImageToMemoryCopy(r, root);
    }
    return o;
}

function d_VkCopyImageToImageInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    o.pRegions = new Array(r.count(o.regionCount));
    for(let i = 0; i < o.regionCount; i++)
    {
        o.pRegions[i] = d_VkImageCopy2(r, root);
    }
    return o;
}

function d_VkHostImageLayoutTransitionInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.image = r.h();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.subresourceRange = d_VkImageSubresourceRange(r, root);
    return o;
}

function d_VkImportSemaphoreFdInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.semaphore = r.h();
    o.flags = r.u32();
    o.handleType = r.i32();
    o.fd = r.i32();
    return o;
}

function d_VkSemaphoreGetFdInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.semaphore = r.h();
    o.handleType = r.i32();
    return o;
}

function d_VkImportFenceFdInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.fence = r.h();
    o.flags = r.u32();
    o.handleType = r.i32();
    o.fd = r.i32();
    return o;
}

function d_VkFenceGetFdInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.fence = r.h();
    o.handleType = r.i32();
    return o;
}

function d_VkPipelineInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipeline = r.h();
    return o;
}

function d_VkPipelineExecutablePropertiesKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stages = r.u32();
    o.name = r.str(256);
    o.description = r.str(256);
    o.subgroupSize = r.u32();
    return o;
}

function e_VkPipelineExecutablePropertiesKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.stages);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.u32(o.subgroupSize);
}

function d_VkPipelineExecutableInfoKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipeline = r.h();
    o.executableIndex = r.u32();
    return o;
}

function d_VkPipelineExecutableStatisticKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.name = r.str(256);
    o.description = r.str(256);
    o.format = r.i32();
    o.value = d_VkPipelineExecutableStatisticValueKHR(r, root);
    return o;
}

function e_VkPipelineExecutableStatisticKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.i32(o.format);
    e_VkPipelineExecutableStatisticValueKHR(w, o.value, root);
}

function d_VkPipelineExecutableInternalRepresentationKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.name = r.str(256);
    o.description = r.str(256);
    o.isText = r.u32();
    o.dataSize = r.be64();
    const p0 = r.ptr();
    o.pData = null;
    if(p0)
    {
        if((o.dataSize > 0))
        {
            o.pData = r.bytes_of(o.dataSize);
        }
    }
    return o;
}

function e_VkPipelineExecutableInternalRepresentationKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.u32(o.isText);
    w.be64(o.dataSize);
    w.ptr(o.pData != null);
    if(o.pData != null)
    {
        w.bytes_of(o.pData, o.dataSize);
    }
}

function d_VkImageDrmFormatModifierPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifier = r.u64();
    return o;
}

function e_VkImageDrmFormatModifierPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
}

function d_VkDescriptorImageInfo(r, root)
{
    const o = {};
    o.sampler = r.h();
    o.imageView = r.h();
    o.imageLayout = r.i32();
    return o;
}

function d_VkDescriptorBufferInfo(r, root)
{
    const o = {};
    o.buffer = r.h();
    o.offset = r.u64();
    o.range = r.u64();
    return o;
}

function d_VkPhysicalDeviceSubgroupProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.subgroupSize = r.u32();
    o.supportedStages = r.u32();
    o.supportedOperations = r.u32();
    o.quadOperationsInAllStages = r.u32();
    return o;
}

function d_VkPhysicalDevice16BitStorageFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    return o;
}

function d_VkMemoryDedicatedRequirements(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.prefersDedicatedAllocation = r.u32();
    o.requiresDedicatedAllocation = r.u32();
    return o;
}

function d_VkMemoryDedicatedAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.image = r.h();
    o.buffer = r.h();
    return o;
}

function d_VkMemoryAllocateFlagsInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.deviceMask = r.u32();
    return o;
}

function d_VkDeviceGroupRenderPassBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceMask = r.u32();
    o.deviceRenderAreaCount = r.u32();
    o.pDeviceRenderAreas = new Array(r.count(o.deviceRenderAreaCount));
    for(let i = 0; i < o.deviceRenderAreaCount; i++)
    {
        o.pDeviceRenderAreas[i] = d_VkRect2D(r, root);
    }
    return o;
}

function d_VkDeviceGroupCommandBufferBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceMask = r.u32();
    return o;
}

function d_VkDeviceGroupSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.waitSemaphoreCount = r.u32();
    if((o.waitSemaphoreCount > 0))
    {
        o.pWaitSemaphoreDeviceIndices = r.u32s(o.waitSemaphoreCount);
    }
    o.commandBufferCount = r.u32();
    if((o.commandBufferCount > 0))
    {
        o.pCommandBufferDeviceMasks = r.u32s(o.commandBufferCount);
    }
    o.signalSemaphoreCount = r.u32();
    if((o.signalSemaphoreCount > 0))
    {
        o.pSignalSemaphoreDeviceIndices = r.u32s(o.signalSemaphoreCount);
    }
    return o;
}

function d_VkDeviceGroupBindSparseInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.resourceDeviceIndex = r.u32();
    o.memoryDeviceIndex = r.u32();
    return o;
}

function d_VkBindBufferMemoryDeviceGroupInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceIndexCount = r.u32();
    if((o.deviceIndexCount > 0))
    {
        o.pDeviceIndices = r.u32s(o.deviceIndexCount);
    }
    return o;
}

function d_VkBindImageMemoryDeviceGroupInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceIndexCount = r.u32();
    if((o.deviceIndexCount > 0))
    {
        o.pDeviceIndices = r.u32s(o.deviceIndexCount);
    }
    o.splitInstanceBindRegionCount = r.u32();
    o.pSplitInstanceBindRegions = new Array(r.count(o.splitInstanceBindRegionCount));
    for(let i = 0; i < o.splitInstanceBindRegionCount; i++)
    {
        o.pSplitInstanceBindRegions[i] = d_VkRect2D(r, root);
    }
    return o;
}

function d_VkDeviceGroupDeviceCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.physicalDeviceCount = r.u32();
    if(o.physicalDeviceCount)
    {
        o.pPhysicalDevices = new Array(r.count(o.physicalDeviceCount));
        for(let k = 0; k < o.physicalDeviceCount; k++)
        {
            o.pPhysicalDevices[k] = r.h();
        }
    }
    return o;
}

function d_VkPhysicalDevicePointClippingProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pointClippingBehavior = r.i32();
    return o;
}

function d_VkRenderPassInputAttachmentAspectCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.aspectReferenceCount = r.u32();
    o.pAspectReferences = new Array(r.count(o.aspectReferenceCount));
    for(let i = 0; i < o.aspectReferenceCount; i++)
    {
        o.pAspectReferences[i] = d_VkInputAttachmentAspectReference(r, root);
    }
    return o;
}

function d_VkImageViewUsageCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.usage = r.u32();
    return o;
}

function d_VkPipelineTessellationDomainOriginStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.domainOrigin = r.i32();
    return o;
}

function d_VkRenderPassMultiviewCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.subpassCount = r.u32();
    if((o.subpassCount > 0))
    {
        o.pViewMasks = r.u32s(o.subpassCount);
    }
    o.dependencyCount = r.u32();
    if((o.dependencyCount > 0))
    {
        o.pViewOffsets = r.i32s(o.dependencyCount);
    }
    o.correlationMaskCount = r.u32();
    if((o.correlationMaskCount > 0))
    {
        o.pCorrelationMasks = r.u32s(o.correlationMaskCount);
    }
    return o;
}

function d_VkPhysicalDeviceMultiviewFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    return o;
}

function d_VkPhysicalDeviceMultiviewProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
    return o;
}

function d_VkPhysicalDeviceVariablePointersFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    return o;
}

function d_VkPhysicalDeviceProtectedMemoryFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.protectedMemory = r.u32();
    return o;
}

function d_VkPhysicalDeviceProtectedMemoryProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.protectedNoFault = r.u32();
    return o;
}

function d_VkProtectedSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.protectedSubmit = r.u32();
    return o;
}

function d_VkSamplerYcbcrConversionInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.conversion = r.h();
    return o;
}

function d_VkBindImagePlaneMemoryInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.planeAspect = r.i32();
    return o;
}

function d_VkImagePlaneMemoryRequirementsInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.planeAspect = r.i32();
    return o;
}

function d_VkPhysicalDeviceSamplerYcbcrConversionFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.samplerYcbcrConversion = r.u32();
    return o;
}

function d_VkSamplerYcbcrConversionImageFormatProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.combinedImageSamplerDescriptorCount = r.u32();
    return o;
}

function d_VkPhysicalDeviceExternalImageFormatInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleType = r.i32();
    return o;
}

function d_VkExternalImageFormatProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.externalMemoryProperties = d_VkExternalMemoryProperties(r, root);
    return o;
}

function d_VkPhysicalDeviceIDProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceUUID = r.u8s(16);
    o.driverUUID = r.u8s(16);
    o.deviceLUID = r.u8s(8);
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
    return o;
}

function d_VkExternalMemoryImageCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleTypes = r.u32();
    return o;
}

function d_VkExternalMemoryBufferCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleTypes = r.u32();
    return o;
}

function d_VkExportMemoryAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleTypes = r.u32();
    return o;
}

function d_VkExportFenceCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleTypes = r.u32();
    return o;
}

function d_VkExportSemaphoreCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.handleTypes = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance3Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
    return o;
}

function d_VkPhysicalDeviceShaderDrawParametersFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderDrawParameters = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkan11Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    o.protectedMemory = r.u32();
    o.samplerYcbcrConversion = r.u32();
    o.shaderDrawParameters = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkan11Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceUUID = r.u8s(16);
    o.driverUUID = r.u8s(16);
    o.deviceLUID = r.u8s(8);
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
    o.subgroupSize = r.u32();
    o.subgroupSupportedStages = r.u32();
    o.subgroupSupportedOperations = r.u32();
    o.subgroupQuadOperationsInAllStages = r.u32();
    o.pointClippingBehavior = r.i32();
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
    o.protectedNoFault = r.u32();
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
    return o;
}

function d_VkPhysicalDeviceVulkan12Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.samplerMirrorClampToEdge = r.u32();
    o.drawIndirectCount = r.u32();
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    o.descriptorIndexing = r.u32();
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    o.samplerFilterMinmax = r.u32();
    o.scalarBlockLayout = r.u32();
    o.imagelessFramebuffer = r.u32();
    o.uniformBufferStandardLayout = r.u32();
    o.shaderSubgroupExtendedTypes = r.u32();
    o.separateDepthStencilLayouts = r.u32();
    o.hostQueryReset = r.u32();
    o.timelineSemaphore = r.u32();
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    o.shaderOutputViewportIndex = r.u32();
    o.shaderOutputLayer = r.u32();
    o.subgroupBroadcastDynamicId = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkan12Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.driverID = r.i32();
    o.driverName = r.str(256);
    o.driverInfo = r.str(256);
    o.conformanceVersion = d_VkConformanceVersion(r, root);
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
    o.maxTimelineSemaphoreValueDifference = r.u64();
    o.framebufferIntegerColorSampleCounts = r.u32();
    return o;
}

function d_VkImageFormatListCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.viewFormatCount = r.u32();
    if((o.viewFormatCount > 0))
    {
        o.pViewFormats = r.i32s(o.viewFormatCount);
    }
    return o;
}

function d_VkPhysicalDevice8BitStorageFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    return o;
}

function d_VkPhysicalDeviceDriverProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.driverID = r.i32();
    o.driverName = r.str(256);
    o.driverInfo = r.str(256);
    o.conformanceVersion = d_VkConformanceVersion(r, root);
    return o;
}

function d_VkPhysicalDeviceShaderAtomicInt64Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderFloat16Int8Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    return o;
}

function d_VkPhysicalDeviceFloatControlsProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
    return o;
}

function d_VkDescriptorSetLayoutBindingFlagsCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.bindingCount = r.u32();
    const p0 = r.ptr();
    o.pBindingFlags = null;
    if(p0)
    {
        if((o.bindingCount > 0))
        {
            o.pBindingFlags = r.u32s(o.bindingCount);
        }
    }
    return o;
}

function d_VkPhysicalDeviceDescriptorIndexingFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    return o;
}

function d_VkPhysicalDeviceDescriptorIndexingProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
    return o;
}

function d_VkDescriptorSetVariableDescriptorCountAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.descriptorSetCount = r.u32();
    if((o.descriptorSetCount > 0))
    {
        o.pDescriptorCounts = r.u32s(o.descriptorSetCount);
    }
    return o;
}

function d_VkDescriptorSetVariableDescriptorCountLayoutSupport(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxVariableDescriptorCount = r.u32();
    return o;
}

function d_VkSubpassDescriptionDepthStencilResolve(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.depthResolveMode = r.i32();
    o.stencilResolveMode = r.i32();
    const p0 = r.ptr();
    o.pDepthStencilResolveAttachment = null;
    if(p0)
    {
        o.pDepthStencilResolveAttachment = d_VkAttachmentReference2(r, root);
    }
    return o;
}

function d_VkPhysicalDeviceDepthStencilResolveProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
    return o;
}

function d_VkPhysicalDeviceScalarBlockLayoutFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.scalarBlockLayout = r.u32();
    return o;
}

function d_VkImageStencilUsageCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stencilUsage = r.u32();
    return o;
}

function d_VkSamplerReductionModeCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.reductionMode = r.i32();
    return o;
}

function d_VkPhysicalDeviceSamplerFilterMinmaxProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkanMemoryModelFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    return o;
}

function d_VkPhysicalDeviceImagelessFramebufferFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imagelessFramebuffer = r.u32();
    return o;
}

function d_VkFramebufferAttachmentsCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.attachmentImageInfoCount = r.u32();
    o.pAttachmentImageInfos = new Array(r.count(o.attachmentImageInfoCount));
    for(let i = 0; i < o.attachmentImageInfoCount; i++)
    {
        o.pAttachmentImageInfos[i] = d_VkFramebufferAttachmentImageInfo(r, root);
    }
    return o;
}

function d_VkRenderPassAttachmentBeginInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.attachmentCount = r.u32();
    if(o.attachmentCount)
    {
        o.pAttachments = new Array(r.count(o.attachmentCount));
        for(let k = 0; k < o.attachmentCount; k++)
        {
            o.pAttachments[k] = r.h();
        }
    }
    return o;
}

function d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.uniformBufferStandardLayout = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderSubgroupExtendedTypes = r.u32();
    return o;
}

function d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.separateDepthStencilLayouts = r.u32();
    return o;
}

function d_VkAttachmentReferenceStencilLayout(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stencilLayout = r.i32();
    return o;
}

function d_VkAttachmentDescriptionStencilLayout(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.stencilInitialLayout = r.i32();
    o.stencilFinalLayout = r.i32();
    return o;
}

function d_VkPhysicalDeviceHostQueryResetFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.hostQueryReset = r.u32();
    return o;
}

function d_VkPhysicalDeviceTimelineSemaphoreFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.timelineSemaphore = r.u32();
    return o;
}

function d_VkPhysicalDeviceTimelineSemaphoreProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxTimelineSemaphoreValueDifference = r.u64();
    return o;
}

function d_VkSemaphoreTypeCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.semaphoreType = r.i32();
    o.initialValue = r.u64();
    return o;
}

function d_VkTimelineSemaphoreSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.waitSemaphoreValueCount = r.u32();
    const p0 = r.ptr();
    o.pWaitSemaphoreValues = null;
    if(p0)
    {
        if((o.waitSemaphoreValueCount > 0))
        {
            o.pWaitSemaphoreValues = r.u64s(o.waitSemaphoreValueCount);
        }
    }
    o.signalSemaphoreValueCount = r.u32();
    const p1 = r.ptr();
    o.pSignalSemaphoreValues = null;
    if(p1)
    {
        if((o.signalSemaphoreValueCount > 0))
        {
            o.pSignalSemaphoreValues = r.u64s(o.signalSemaphoreValueCount);
        }
    }
    return o;
}

function d_VkPhysicalDeviceBufferDeviceAddressFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    return o;
}

function d_VkBufferOpaqueCaptureAddressCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.opaqueCaptureAddress = r.u64();
    return o;
}

function d_VkMemoryOpaqueCaptureAddressAllocateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.opaqueCaptureAddress = r.u64();
    return o;
}

function d_VkPhysicalDeviceVulkan13Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.robustImageAccess = r.u32();
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    o.pipelineCreationCacheControl = r.u32();
    o.privateData = r.u32();
    o.shaderDemoteToHelperInvocation = r.u32();
    o.shaderTerminateInvocation = r.u32();
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    o.synchronization2 = r.u32();
    o.textureCompressionASTC_HDR = r.u32();
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    o.dynamicRendering = r.u32();
    o.shaderIntegerDotProduct = r.u32();
    o.maintenance4 = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkan13Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxInlineUniformTotalSize = r.u32();
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.maxBufferSize = r.u64();
    return o;
}

function d_VkPipelineCreationFeedbackCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pPipelineCreationFeedback = d_VkPipelineCreationFeedback(r, root);
    o.pipelineStageCreationFeedbackCount = r.u32();
    o.pPipelineStageCreationFeedbacks = new Array(r.count(o.pipelineStageCreationFeedbackCount));
    for(let i = 0; i < o.pipelineStageCreationFeedbackCount; i++)
    {
        o.pPipelineStageCreationFeedbacks[i] = d_VkPipelineCreationFeedback(r, root);
    }
    return o;
}

function d_VkPhysicalDeviceShaderTerminateInvocationFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderTerminateInvocation = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderDemoteToHelperInvocation = r.u32();
    return o;
}

function d_VkPhysicalDevicePrivateDataFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.privateData = r.u32();
    return o;
}

function d_VkDevicePrivateDataCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.privateDataSlotRequestCount = r.u32();
    return o;
}

function d_VkPhysicalDevicePipelineCreationCacheControlFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipelineCreationCacheControl = r.u32();
    return o;
}

function d_VkMemoryBarrier2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    return o;
}

function d_VkPhysicalDeviceSynchronization2Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.synchronization2 = r.u32();
    return o;
}

function d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    return o;
}

function d_VkPhysicalDeviceImageRobustnessFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.robustImageAccess = r.u32();
    return o;
}

function d_VkPhysicalDeviceSubgroupSizeControlFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    return o;
}

function d_VkPhysicalDeviceSubgroupSizeControlProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
    return o;
}

function d_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.requiredSubgroupSize = r.u32();
    return o;
}

function d_VkPhysicalDeviceInlineUniformBlockFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    return o;
}

function d_VkPhysicalDeviceInlineUniformBlockProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
    return o;
}

function d_VkWriteDescriptorSetInlineUniformBlock(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.dataSize = r.u32();
    if((o.dataSize > 0))
    {
        o.pData = r.bytes_of(o.dataSize);
    }
    return o;
}

function d_VkDescriptorPoolInlineUniformBlockCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxInlineUniformBlockBindings = r.u32();
    return o;
}

function d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.textureCompressionASTC_HDR = r.u32();
    return o;
}

function d_VkPipelineRenderingCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const p0 = r.ptr();
    o.pColorAttachmentFormats = null;
    if(p0)
    {
        if((o.colorAttachmentCount > 0))
        {
            o.pColorAttachmentFormats = r.i32s(o.colorAttachmentCount);
        }
    }
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    return o;
}

function d_VkPhysicalDeviceDynamicRenderingFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.dynamicRendering = r.u32();
    return o;
}

function d_VkCommandBufferInheritanceRenderingInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    if((o.colorAttachmentCount > 0))
    {
        o.pColorAttachmentFormats = r.i32s(o.colorAttachmentCount);
    }
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    o.rasterizationSamples = r.i32();
    return o;
}

function d_VkPhysicalDeviceShaderIntegerDotProductFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderIntegerDotProduct = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderIntegerDotProductProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
    return o;
}

function d_VkPhysicalDeviceTexelBufferAlignmentProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
    return o;
}

function d_VkFormatProperties3(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.linearTilingFeatures = r.u64();
    o.optimalTilingFeatures = r.u64();
    o.bufferFeatures = r.u64();
    return o;
}

function d_VkPhysicalDeviceMaintenance4Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maintenance4 = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance4Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxBufferSize = r.u64();
    return o;
}

function d_VkPhysicalDeviceVulkan14Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.globalPriorityQuery = r.u32();
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    o.shaderFloatControls2 = r.u32();
    o.shaderExpectAssume = r.u32();
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    o.indexTypeUint8 = r.u32();
    o.dynamicRenderingLocalRead = r.u32();
    o.maintenance5 = r.u32();
    o.maintenance6 = r.u32();
    o.pipelineProtectedAccess = r.u32();
    o.pipelineRobustness = r.u32();
    o.hostImageCopy = r.u32();
    o.pushDescriptor = r.u32();
    return o;
}

function d_VkPhysicalDeviceVulkan14Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.lineSubPixelPrecisionBits = r.u32();
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
    o.maxPushDescriptors = r.u32();
    o.dynamicRenderingLocalReadDepthStencilAttachments = r.u32();
    o.dynamicRenderingLocalReadMultisampledAttachments = r.u32();
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
    o.copySrcLayoutCount = r.u32();
    const p0 = r.ptr();
    o.pCopySrcLayouts = null;
    if(p0)
    {
        if((o.copySrcLayoutCount > 0))
        {
            o.pCopySrcLayouts = r.i32s(o.copySrcLayoutCount);
        }
    }
    o.copyDstLayoutCount = r.u32();
    const p1 = r.ptr();
    o.pCopyDstLayouts = null;
    if(p1)
    {
        if((o.copyDstLayoutCount > 0))
        {
            o.pCopyDstLayouts = r.i32s(o.copyDstLayoutCount);
        }
    }
    o.optimalTilingLayoutUUID = r.u8s(16);
    o.identicalMemoryTypeRequirements = r.u32();
    return o;
}

function d_VkDeviceQueueGlobalPriorityCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.globalPriority = r.i32();
    return o;
}

function d_VkPhysicalDeviceGlobalPriorityQueryFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.globalPriorityQuery = r.u32();
    return o;
}

function d_VkQueueFamilyGlobalPriorityProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.priorityCount = r.u32();
    o.priorities = r.i32s(16);
    return o;
}

function d_VkPhysicalDeviceShaderSubgroupRotateFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderFloatControls2Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderFloatControls2 = r.u32();
    return o;
}

function d_VkPhysicalDeviceShaderExpectAssumeFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.shaderExpectAssume = r.u32();
    return o;
}

function d_VkPhysicalDeviceLineRasterizationFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    return o;
}

function d_VkPhysicalDeviceLineRasterizationProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.lineSubPixelPrecisionBits = r.u32();
    return o;
}

function d_VkPipelineRasterizationLineStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.lineRasterizationMode = r.i32();
    o.stippledLineEnable = r.u32();
    o.lineStippleFactor = r.u32();
    o.lineStipplePattern = r.u16();
    return o;
}

function d_VkPhysicalDeviceVertexAttributeDivisorProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
    return o;
}

function d_VkPipelineVertexInputDivisorStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.vertexBindingDivisorCount = r.u32();
    o.pVertexBindingDivisors = new Array(r.count(o.vertexBindingDivisorCount));
    for(let i = 0; i < o.vertexBindingDivisorCount; i++)
    {
        o.pVertexBindingDivisors[i] = d_VkVertexInputBindingDivisorDescription(r, root);
    }
    return o;
}

function d_VkPhysicalDeviceVertexAttributeDivisorFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    return o;
}

function d_VkPhysicalDeviceIndexTypeUint8Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.indexTypeUint8 = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance5Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maintenance5 = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance5Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
    return o;
}

function d_VkPipelineCreateFlags2CreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u64();
    return o;
}

function d_VkBufferUsageFlags2CreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.usage = r.u64();
    return o;
}

function d_VkPhysicalDevicePushDescriptorProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxPushDescriptors = r.u32();
    return o;
}

function d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.dynamicRenderingLocalRead = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance6Features(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maintenance6 = r.u32();
    return o;
}

function d_VkPhysicalDeviceMaintenance6Properties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
    return o;
}

function d_VkBindMemoryStatus(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pResult = r.i32();
    return o;
}

function d_VkPhysicalDevicePipelineProtectedAccessFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipelineProtectedAccess = r.u32();
    return o;
}

function d_VkPhysicalDevicePipelineRobustnessFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipelineRobustness = r.u32();
    return o;
}

function d_VkPhysicalDevicePipelineRobustnessProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
    return o;
}

function d_VkPipelineRobustnessCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.storageBuffers = r.i32();
    o.uniformBuffers = r.i32();
    o.vertexInputs = r.i32();
    o.images = r.i32();
    return o;
}

function d_VkPhysicalDeviceHostImageCopyFeatures(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.hostImageCopy = r.u32();
    return o;
}

function d_VkPhysicalDeviceHostImageCopyProperties(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.copySrcLayoutCount = r.u32();
    const p0 = r.ptr();
    o.pCopySrcLayouts = null;
    if(p0)
    {
        if((o.copySrcLayoutCount > 0))
        {
            o.pCopySrcLayouts = r.i32s(o.copySrcLayoutCount);
        }
    }
    o.copyDstLayoutCount = r.u32();
    const p1 = r.ptr();
    o.pCopyDstLayouts = null;
    if(p1)
    {
        if((o.copyDstLayoutCount > 0))
        {
            o.pCopyDstLayouts = r.i32s(o.copyDstLayoutCount);
        }
    }
    o.optimalTilingLayoutUUID = r.u8s(16);
    o.identicalMemoryTypeRequirements = r.u32();
    return o;
}

function d_VkSubresourceHostMemcpySize(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.size = r.u64();
    return o;
}

function d_VkHostImageCopyDevicePerformanceQuery(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.optimalDeviceAccess = r.u32();
    o.identicalMemoryLayout = r.u32();
    return o;
}

function d_VkPresentRegionsKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.swapchainCount = r.u32();
    const p0 = r.ptr();
    o.pRegions = null;
    if(p0)
    {
        o.pRegions = [];
        o.pRegions = new Array(r.count(o.swapchainCount));
        for(let i = 0; i < o.swapchainCount; i++)
        {
            o.pRegions[i] = d_VkPresentRegionKHR(r, root);
        }
    }
    return o;
}

function d_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pipelineExecutableInfo = r.u32();
    return o;
}

function d_VkNativeBufferANDROID(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    const p0 = r.ptr();
    o.handle = null;
    if(p0)
    {
        o.handle = r.u32();
    }
    o.stride = r.i32();
    o.format = r.i32();
    o.usage = r.i32();
    o.usage2 = d_VkNativeBufferUsage2ANDROID(r, root);
    return o;
}

function d_VkPhysicalDeviceTransformFeedbackFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.transformFeedback = r.u32();
    o.geometryStreams = r.u32();
    return o;
}

function d_VkPhysicalDeviceTransformFeedbackPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxTransformFeedbackStreams = r.u32();
    o.maxTransformFeedbackBuffers = r.u32();
    o.maxTransformFeedbackBufferSize = r.u64();
    o.maxTransformFeedbackStreamDataSize = r.u32();
    o.maxTransformFeedbackBufferDataSize = r.u32();
    o.maxTransformFeedbackBufferDataStride = r.u32();
    o.transformFeedbackQueries = r.u32();
    o.transformFeedbackStreamsLinesTriangles = r.u32();
    o.transformFeedbackRasterizationStreamSelect = r.u32();
    o.transformFeedbackDraw = r.u32();
    return o;
}

function d_VkPipelineRasterizationStateStreamCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.rasterizationStream = r.u32();
    return o;
}

function d_VkPhysicalDeviceDepthClipEnableFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.depthClipEnable = r.u32();
    return o;
}

function d_VkPipelineRasterizationDepthClipStateCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.depthClipEnable = r.u32();
    return o;
}

function d_VkDrmFormatModifierPropertiesListEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifierCount = r.u32();
    const p0 = r.ptr();
    o.pDrmFormatModifierProperties = null;
    if(p0)
    {
        o.pDrmFormatModifierProperties = [];
        o.pDrmFormatModifierProperties = new Array(r.count(o.drmFormatModifierCount));
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            o.pDrmFormatModifierProperties[i] = d_VkDrmFormatModifierPropertiesEXT(r, root);
        }
    }
    return o;
}

function d_VkPhysicalDeviceImageDrmFormatModifierInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifier = r.u64();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    const p0 = r.ptr();
    o.pQueueFamilyIndices = null;
    if(p0)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            o.pQueueFamilyIndices = r.u32s(o.queueFamilyIndexCount);
        }
    }
    return o;
}

function d_VkImageDrmFormatModifierListCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifierCount = r.u32();
    if((o.drmFormatModifierCount > 0))
    {
        o.pDrmFormatModifiers = r.u64s(o.drmFormatModifierCount);
    }
    return o;
}

function d_VkImageDrmFormatModifierExplicitCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.pPlaneLayouts = new Array(r.count(o.drmFormatModifierPlaneCount));
    for(let i = 0; i < o.drmFormatModifierPlaneCount; i++)
    {
        o.pPlaneLayouts[i] = d_VkSubresourceLayout(r, root);
    }
    return o;
}

function d_VkDrmFormatModifierPropertiesList2EXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.drmFormatModifierCount = r.u32();
    const p0 = r.ptr();
    o.pDrmFormatModifierProperties = null;
    if(p0)
    {
        o.pDrmFormatModifierProperties = [];
        o.pDrmFormatModifierProperties = new Array(r.count(o.drmFormatModifierCount));
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            o.pDrmFormatModifierProperties[i] = d_VkDrmFormatModifierProperties2EXT(r, root);
        }
    }
    return o;
}

function d_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxVertexAttribDivisor = r.u32();
    return o;
}

function d_VkPhysicalDeviceFragmentDensityMapFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.fragmentDensityMap = r.u32();
    o.fragmentDensityMapDynamic = r.u32();
    o.fragmentDensityMapNonSubsampledImages = r.u32();
    return o;
}

function d_VkImportColorBufferGOOGLE(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.colorBuffer = r.u32();
    return o;
}

function d_VkPhysicalDeviceFragmentDensityMapPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.minFragmentDensityTexelSize = d_VkExtent2D(r, root);
    o.maxFragmentDensityTexelSize = d_VkExtent2D(r, root);
    o.fragmentDensityInvocations = r.u32();
    return o;
}

function d_VkCreateBlobGOOGLE(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.blobMem = r.u32();
    o.blobFlags = r.u32();
    o.blobId = r.u64();
    return o;
}

function d_VkRenderPassFragmentDensityMapCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.fragmentDensityMapAttachment = d_VkAttachmentReference(r, root);
    return o;
}

function d_VkImportBufferGOOGLE(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.buffer = r.u32();
    return o;
}

function d_VkRenderingFragmentDensityMapAttachmentInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageView = r.h();
    o.imageLayout = r.i32();
    return o;
}

function d_VkPhysicalDeviceMemoryBudgetPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.heapBudget = r.u64s(16);
    o.heapUsage = r.u64s(16);
    return o;
}

function d_VkPhysicalDeviceProvokingVertexFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.provokingVertexLast = r.u32();
    o.transformFeedbackPreservesProvokingVertex = r.u32();
    return o;
}

function d_VkPhysicalDeviceProvokingVertexPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.provokingVertexModePerPipeline = r.u32();
    o.transformFeedbackPreservesTriangleFanProvokingVertex = r.u32();
    return o;
}

function d_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.provokingVertexMode = r.i32();
    return o;
}

function d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.extendedDynamicState = r.u32();
    return o;
}

function d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.texelBufferAlignment = r.u32();
    return o;
}

function d_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.deviceMemoryReport = r.u32();
    return o;
}

function d_VkDeviceDeviceMemoryReportCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.pfnUserCallback = r.be64();
    o.pUserData = r.void();
    return o;
}

function d_VkSamplerCustomBorderColorCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.customBorderColor = d_VkClearColorValue(r, root);
    o.format = r.i32();
    return o;
}

function d_VkPhysicalDeviceCustomBorderColorPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.maxCustomBorderColorSamplers = r.u32();
    return o;
}

function d_VkPhysicalDeviceCustomBorderColorFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.customBorderColors = r.u32();
    o.customBorderColorWithoutFormat = r.u32();
    return o;
}

function d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.graphicsPipelineLibrary = r.u32();
    return o;
}

function d_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.graphicsPipelineLibraryFastLinking = r.u32();
    o.graphicsPipelineLibraryIndependentInterpolationDecoration = r.u32();
    return o;
}

function d_VkGraphicsPipelineLibraryCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    return o;
}

function d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.ycbcr2plane444Formats = r.u32();
    return o;
}

function d_VkPhysicalDeviceImageCompressionControlFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageCompressionControl = r.u32();
    return o;
}

function d_VkImageCompressionControlEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.compressionControlPlaneCount = r.u32();
    const p0 = r.ptr();
    o.pFixedRateFlags = null;
    if(p0)
    {
        if((o.compressionControlPlaneCount > 0))
        {
            o.pFixedRateFlags = r.u32s(o.compressionControlPlaneCount);
        }
    }
    return o;
}

function d_VkImageCompressionPropertiesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageCompressionFlags = r.u32();
    o.imageCompressionFixedRateFlags = r.u32();
    return o;
}

function d_VkPhysicalDevice4444FormatsFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.formatA4R4G4B4 = r.u32();
    o.formatA4B4G4R4 = r.u32();
    return o;
}

function d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.primitiveTopologyListRestart = r.u32();
    o.primitiveTopologyPatchListRestart = r.u32();
    return o;
}

function d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.extendedDynamicState2 = r.u32();
    o.extendedDynamicState2LogicOp = r.u32();
    o.extendedDynamicState2PatchControlPoints = r.u32();
    return o;
}

function d_VkPhysicalDeviceColorWriteEnableFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.colorWriteEnable = r.u32();
    return o;
}

function d_VkPipelineColorWriteCreateInfoEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.attachmentCount = r.u32();
    if((o.attachmentCount > 0))
    {
        o.pColorWriteEnables = r.u32s(o.attachmentCount);
    }
    return o;
}

function d_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageCompressionControlSwapchain = r.u32();
    return o;
}

function e_VkShaderModuleCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.be64(o.codeSize);
    w.u32s(o.pCode, Math.trunc(o.codeSize / 4));
}

function e_VkPipelineLayoutCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.setLayoutCount);
    if(o.setLayoutCount)
    {
        w.u64s(o.pSetLayouts, o.setLayoutCount);
    }
    w.u32(o.pushConstantRangeCount);
    for(let i = 0; i < o.pushConstantRangeCount; i++)
    {
        e_VkPushConstantRange(w, o.pPushConstantRanges?.[i], root);
    }
}

function e_VkPhysicalDeviceSubgroupProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.subgroupSize);
    w.u32(o.supportedStages);
    w.u32(o.supportedOperations);
    w.u32(o.quadOperationsInAllStages);
}

function e_VkPhysicalDevice16BitStorageFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
}

function e_VkMemoryDedicatedRequirements(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.prefersDedicatedAllocation);
    w.u32(o.requiresDedicatedAllocation);
}

function e_VkMemoryDedicatedAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.h(o.image);
    w.h(o.buffer);
}

function e_VkMemoryAllocateFlagsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.deviceMask);
}

function e_VkDeviceGroupRenderPassBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.deviceMask);
    w.u32(o.deviceRenderAreaCount);
    for(let i = 0; i < o.deviceRenderAreaCount; i++)
    {
        e_VkRect2D(w, o.pDeviceRenderAreas?.[i], root);
    }
}

function e_VkDeviceGroupCommandBufferBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.deviceMask);
}

function e_VkDeviceGroupSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreCount);
    w.u32s(o.pWaitSemaphoreDeviceIndices, o.waitSemaphoreCount);
    w.u32(o.commandBufferCount);
    w.u32s(o.pCommandBufferDeviceMasks, o.commandBufferCount);
    w.u32(o.signalSemaphoreCount);
    w.u32s(o.pSignalSemaphoreDeviceIndices, o.signalSemaphoreCount);
}

function e_VkDeviceGroupBindSparseInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.resourceDeviceIndex);
    w.u32(o.memoryDeviceIndex);
}

function e_VkBindBufferMemoryDeviceGroupInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.deviceIndexCount);
    w.u32s(o.pDeviceIndices, o.deviceIndexCount);
}

function e_VkBindImageMemoryDeviceGroupInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.deviceIndexCount);
    w.u32s(o.pDeviceIndices, o.deviceIndexCount);
    w.u32(o.splitInstanceBindRegionCount);
    for(let i = 0; i < o.splitInstanceBindRegionCount; i++)
    {
        e_VkRect2D(w, o.pSplitInstanceBindRegions?.[i], root);
    }
}

function e_VkDeviceGroupDeviceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.physicalDeviceCount);
    if(o.physicalDeviceCount)
    {
        w.u64s(o.pPhysicalDevices, o.physicalDeviceCount);
    }
}

function e_VkPhysicalDevicePointClippingProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.pointClippingBehavior);
}

function e_VkRenderPassInputAttachmentAspectCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.aspectReferenceCount);
    for(let i = 0; i < o.aspectReferenceCount; i++)
    {
        e_VkInputAttachmentAspectReference(w, o.pAspectReferences?.[i], root);
    }
}

function e_VkImageViewUsageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.usage);
}

function e_VkPipelineTessellationDomainOriginStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.domainOrigin);
}

function e_VkRenderPassMultiviewCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.subpassCount);
    w.u32s(o.pViewMasks, o.subpassCount);
    w.u32(o.dependencyCount);
    w.i32s(o.pViewOffsets, o.dependencyCount);
    w.u32(o.correlationMaskCount);
    w.u32s(o.pCorrelationMasks, o.correlationMaskCount);
}

function e_VkPhysicalDeviceMultiviewFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
}

function e_VkPhysicalDeviceMultiviewProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
}

function e_VkPhysicalDeviceVariablePointersFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
}

function e_VkPhysicalDeviceProtectedMemoryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.protectedMemory);
}

function e_VkPhysicalDeviceProtectedMemoryProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.protectedNoFault);
}

function e_VkProtectedSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.protectedSubmit);
}

function e_VkSamplerYcbcrConversionInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.h(o.conversion);
}

function e_VkBindImagePlaneMemoryInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.planeAspect);
}

function e_VkImagePlaneMemoryRequirementsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.planeAspect);
}

function e_VkPhysicalDeviceSamplerYcbcrConversionFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.samplerYcbcrConversion);
}

function e_VkSamplerYcbcrConversionImageFormatProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.combinedImageSamplerDescriptorCount);
}

function e_VkPhysicalDeviceExternalImageFormatInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.handleType);
}

function e_VkExternalImageFormatProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkExternalMemoryProperties(w, o.externalMemoryProperties, root);
}

function e_VkPhysicalDeviceIDProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u8s(o.deviceUUID, 16);
    w.u8s(o.driverUUID, 16);
    w.u8s(o.deviceLUID, 8);
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
}

function e_VkExternalMemoryImageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function e_VkExternalMemoryBufferCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function e_VkExportMemoryAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function e_VkExportFenceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function e_VkExportSemaphoreCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function e_VkPhysicalDeviceMaintenance3Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}

function e_VkPhysicalDeviceShaderDrawParametersFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderDrawParameters);
}

function e_VkPhysicalDeviceVulkan11Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
    w.u32(o.protectedMemory);
    w.u32(o.samplerYcbcrConversion);
    w.u32(o.shaderDrawParameters);
}

function e_VkPhysicalDeviceVulkan11Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u8s(o.deviceUUID, 16);
    w.u8s(o.driverUUID, 16);
    w.u8s(o.deviceLUID, 8);
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
    w.u32(o.subgroupSize);
    w.u32(o.subgroupSupportedStages);
    w.u32(o.subgroupSupportedOperations);
    w.u32(o.subgroupQuadOperationsInAllStages);
    w.i32(o.pointClippingBehavior);
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
    w.u32(o.protectedNoFault);
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}

function e_VkPhysicalDeviceVulkan12Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.samplerMirrorClampToEdge);
    w.u32(o.drawIndirectCount);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
    w.u32(o.descriptorIndexing);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
    w.u32(o.samplerFilterMinmax);
    w.u32(o.scalarBlockLayout);
    w.u32(o.imagelessFramebuffer);
    w.u32(o.uniformBufferStandardLayout);
    w.u32(o.shaderSubgroupExtendedTypes);
    w.u32(o.separateDepthStencilLayouts);
    w.u32(o.hostQueryReset);
    w.u32(o.timelineSemaphore);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
    w.u32(o.shaderOutputViewportIndex);
    w.u32(o.shaderOutputLayer);
    w.u32(o.subgroupBroadcastDynamicId);
}

function e_VkPhysicalDeviceVulkan12Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.driverID);
    w.str(o.driverName, 256);
    w.str(o.driverInfo, 256);
    e_VkConformanceVersion(w, o.conformanceVersion, root);
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
    w.u64(o.maxTimelineSemaphoreValueDifference);
    w.u32(o.framebufferIntegerColorSampleCounts);
}

function e_VkImageFormatListCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.viewFormatCount);
    w.i32s(o.pViewFormats, o.viewFormatCount);
}

function e_VkPhysicalDevice8BitStorageFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
}

function e_VkPhysicalDeviceDriverProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.driverID);
    w.str(o.driverName, 256);
    w.str(o.driverInfo, 256);
    e_VkConformanceVersion(w, o.conformanceVersion, root);
}

function e_VkPhysicalDeviceShaderAtomicInt64Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
}

function e_VkPhysicalDeviceShaderFloat16Int8Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
}

function e_VkPhysicalDeviceFloatControlsProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
}

function e_VkDescriptorSetLayoutBindingFlagsCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.bindingCount);
    w.ptr(o.pBindingFlags != null);
    if(o.pBindingFlags != null)
    {
        w.u32s(o.pBindingFlags, o.bindingCount);
    }
}

function e_VkPhysicalDeviceDescriptorIndexingFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
}

function e_VkPhysicalDeviceDescriptorIndexingProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
}

function e_VkDescriptorSetVariableDescriptorCountAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.descriptorSetCount);
    w.u32s(o.pDescriptorCounts, o.descriptorSetCount);
}

function e_VkDescriptorSetVariableDescriptorCountLayoutSupport(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxVariableDescriptorCount);
}

function e_VkSubpassDescriptionDepthStencilResolve(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.depthResolveMode);
    w.i32(o.stencilResolveMode);
    w.ptr(o.pDepthStencilResolveAttachment != null);
    if(o.pDepthStencilResolveAttachment != null)
    {
        e_VkAttachmentReference2(w, o.pDepthStencilResolveAttachment, root);
    }
}

function e_VkPhysicalDeviceDepthStencilResolveProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
}

function e_VkPhysicalDeviceScalarBlockLayoutFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.scalarBlockLayout);
}

function e_VkImageStencilUsageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.stencilUsage);
}

function e_VkSamplerReductionModeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.reductionMode);
}

function e_VkPhysicalDeviceSamplerFilterMinmaxProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
}

function e_VkPhysicalDeviceVulkanMemoryModelFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
}

function e_VkPhysicalDeviceImagelessFramebufferFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.imagelessFramebuffer);
}

function e_VkFramebufferAttachmentsCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.attachmentImageInfoCount);
    for(let i = 0; i < o.attachmentImageInfoCount; i++)
    {
        e_VkFramebufferAttachmentImageInfo(w, o.pAttachmentImageInfos?.[i], root);
    }
}

function e_VkRenderPassAttachmentBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.attachmentCount);
    if(o.attachmentCount)
    {
        w.u64s(o.pAttachments, o.attachmentCount);
    }
}

function e_VkPhysicalDeviceUniformBufferStandardLayoutFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.uniformBufferStandardLayout);
}

function e_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderSubgroupExtendedTypes);
}

function e_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.separateDepthStencilLayouts);
}

function e_VkAttachmentReferenceStencilLayout(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.stencilLayout);
}

function e_VkAttachmentDescriptionStencilLayout(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.stencilInitialLayout);
    w.i32(o.stencilFinalLayout);
}

function e_VkPhysicalDeviceHostQueryResetFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.hostQueryReset);
}

function e_VkPhysicalDeviceTimelineSemaphoreFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.timelineSemaphore);
}

function e_VkPhysicalDeviceTimelineSemaphoreProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.maxTimelineSemaphoreValueDifference);
}

function e_VkSemaphoreTypeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.semaphoreType);
    w.u64(o.initialValue);
}

function e_VkTimelineSemaphoreSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreValueCount);
    w.ptr(o.pWaitSemaphoreValues != null);
    if(o.pWaitSemaphoreValues != null)
    {
        w.u64s(o.pWaitSemaphoreValues, o.waitSemaphoreValueCount);
    }
    w.u32(o.signalSemaphoreValueCount);
    w.ptr(o.pSignalSemaphoreValues != null);
    if(o.pSignalSemaphoreValues != null)
    {
        w.u64s(o.pSignalSemaphoreValues, o.signalSemaphoreValueCount);
    }
}

function e_VkPhysicalDeviceBufferDeviceAddressFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}

function e_VkBufferOpaqueCaptureAddressCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.opaqueCaptureAddress);
}

function e_VkMemoryOpaqueCaptureAddressAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.opaqueCaptureAddress);
}

function e_VkPhysicalDeviceVulkan13Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.robustImageAccess);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
    w.u32(o.pipelineCreationCacheControl);
    w.u32(o.privateData);
    w.u32(o.shaderDemoteToHelperInvocation);
    w.u32(o.shaderTerminateInvocation);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
    w.u32(o.synchronization2);
    w.u32(o.textureCompressionASTC_HDR);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
    w.u32(o.dynamicRendering);
    w.u32(o.shaderIntegerDotProduct);
    w.u32(o.maintenance4);
}

function e_VkPhysicalDeviceVulkan13Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxInlineUniformTotalSize);
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.maxBufferSize);
}

function e_VkPipelineCreationFeedbackCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkPipelineCreationFeedback(w, o.pPipelineCreationFeedback, root);
    w.u32(o.pipelineStageCreationFeedbackCount);
    for(let i = 0; i < o.pipelineStageCreationFeedbackCount; i++)
    {
        e_VkPipelineCreationFeedback(w, o.pPipelineStageCreationFeedbacks?.[i], root);
    }
}

function e_VkPhysicalDeviceShaderTerminateInvocationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderTerminateInvocation);
}

function e_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderDemoteToHelperInvocation);
}

function e_VkPhysicalDevicePrivateDataFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.privateData);
}

function e_VkDevicePrivateDataCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.privateDataSlotRequestCount);
}

function e_VkPhysicalDevicePipelineCreationCacheControlFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.pipelineCreationCacheControl);
}

function e_VkMemoryBarrier2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
}

function e_VkPhysicalDeviceSynchronization2Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.synchronization2);
}

function e_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
}

function e_VkPhysicalDeviceImageRobustnessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.robustImageAccess);
}

function e_VkPhysicalDeviceSubgroupSizeControlFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
}

function e_VkPhysicalDeviceSubgroupSizeControlProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
}

function e_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.requiredSubgroupSize);
}

function e_VkPhysicalDeviceInlineUniformBlockFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
}

function e_VkPhysicalDeviceInlineUniformBlockProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
}

function e_VkWriteDescriptorSetInlineUniformBlock(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.dataSize);
    w.bytes_of(o.pData, o.dataSize);
}

function e_VkDescriptorPoolInlineUniformBlockCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxInlineUniformBlockBindings);
}

function e_VkPhysicalDeviceTextureCompressionASTCHDRFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.textureCompressionASTC_HDR);
}

function e_VkPipelineRenderingCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentFormats != null);
    if(o.pColorAttachmentFormats != null)
    {
        w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
}

function e_VkPhysicalDeviceDynamicRenderingFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.dynamicRendering);
}

function e_VkCommandBufferInheritanceRenderingInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
    w.i32(o.rasterizationSamples);
}

function e_VkPhysicalDeviceShaderIntegerDotProductFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderIntegerDotProduct);
}

function e_VkPhysicalDeviceShaderIntegerDotProductProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
}

function e_VkPhysicalDeviceTexelBufferAlignmentProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
}

function e_VkFormatProperties3(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.linearTilingFeatures);
    w.u64(o.optimalTilingFeatures);
    w.u64(o.bufferFeatures);
}

function e_VkPhysicalDeviceMaintenance4Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maintenance4);
}

function e_VkPhysicalDeviceMaintenance4Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.maxBufferSize);
}

function e_VkPhysicalDeviceVulkan14Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.globalPriorityQuery);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
    w.u32(o.shaderFloatControls2);
    w.u32(o.shaderExpectAssume);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
    w.u32(o.indexTypeUint8);
    w.u32(o.dynamicRenderingLocalRead);
    w.u32(o.maintenance5);
    w.u32(o.maintenance6);
    w.u32(o.pipelineProtectedAccess);
    w.u32(o.pipelineRobustness);
    w.u32(o.hostImageCopy);
    w.u32(o.pushDescriptor);
}

function e_VkPhysicalDeviceVulkan14Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.lineSubPixelPrecisionBits);
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
    w.u32(o.maxPushDescriptors);
    w.u32(o.dynamicRenderingLocalReadDepthStencilAttachments);
    w.u32(o.dynamicRenderingLocalReadMultisampledAttachments);
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
    w.u32(o.copySrcLayoutCount);
    w.ptr(o.pCopySrcLayouts != null);
    if(o.pCopySrcLayouts != null)
    {
        w.i32s(o.pCopySrcLayouts, o.copySrcLayoutCount);
    }
    w.u32(o.copyDstLayoutCount);
    w.ptr(o.pCopyDstLayouts != null);
    if(o.pCopyDstLayouts != null)
    {
        w.i32s(o.pCopyDstLayouts, o.copyDstLayoutCount);
    }
    w.u8s(o.optimalTilingLayoutUUID, 16);
    w.u32(o.identicalMemoryTypeRequirements);
}

function e_VkDeviceQueueGlobalPriorityCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.globalPriority);
}

function e_VkPhysicalDeviceGlobalPriorityQueryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.globalPriorityQuery);
}

function e_VkQueueFamilyGlobalPriorityProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.priorityCount);
    w.i32s(o.priorities, 16);
}

function e_VkPhysicalDeviceShaderSubgroupRotateFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
}

function e_VkPhysicalDeviceShaderFloatControls2Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderFloatControls2);
}

function e_VkPhysicalDeviceShaderExpectAssumeFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.shaderExpectAssume);
}

function e_VkPhysicalDeviceLineRasterizationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
}

function e_VkPhysicalDeviceLineRasterizationProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.lineSubPixelPrecisionBits);
}

function e_VkPipelineRasterizationLineStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.lineRasterizationMode);
    w.u32(o.stippledLineEnable);
    w.u32(o.lineStippleFactor);
    w.u16(o.lineStipplePattern);
}

function e_VkPhysicalDeviceVertexAttributeDivisorProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
}

function e_VkPipelineVertexInputDivisorStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.vertexBindingDivisorCount);
    for(let i = 0; i < o.vertexBindingDivisorCount; i++)
    {
        e_VkVertexInputBindingDivisorDescription(w, o.pVertexBindingDivisors?.[i], root);
    }
}

function e_VkPhysicalDeviceVertexAttributeDivisorFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
}

function e_VkPhysicalDeviceIndexTypeUint8Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.indexTypeUint8);
}

function e_VkPhysicalDeviceMaintenance5Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maintenance5);
}

function e_VkPhysicalDeviceMaintenance5Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
}

function e_VkPipelineCreateFlags2CreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.flags);
}

function e_VkBufferUsageFlags2CreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.usage);
}

function e_VkPhysicalDevicePushDescriptorProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxPushDescriptors);
}

function e_VkPhysicalDeviceDynamicRenderingLocalReadFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.dynamicRenderingLocalRead);
}

function e_VkRenderingAttachmentLocationInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentLocations != null);
    if(o.pColorAttachmentLocations != null)
    {
        w.u32s(o.pColorAttachmentLocations, o.colorAttachmentCount);
    }
}

function e_VkRenderingInputAttachmentIndexInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentInputIndices != null);
    if(o.pColorAttachmentInputIndices != null)
    {
        w.u32s(o.pColorAttachmentInputIndices, o.colorAttachmentCount);
    }
    w.ptr(o.pDepthInputAttachmentIndex != null);
    if(o.pDepthInputAttachmentIndex != null)
    {
        w.u32(o.pDepthInputAttachmentIndex);
    }
    w.ptr(o.pStencilInputAttachmentIndex != null);
    if(o.pStencilInputAttachmentIndex != null)
    {
        w.u32(o.pStencilInputAttachmentIndex);
    }
}

function e_VkPhysicalDeviceMaintenance6Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maintenance6);
}

function e_VkPhysicalDeviceMaintenance6Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
}

function e_VkBindMemoryStatus(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.pResult);
}

function e_VkPhysicalDevicePipelineProtectedAccessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.pipelineProtectedAccess);
}

function e_VkPhysicalDevicePipelineRobustnessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.pipelineRobustness);
}

function e_VkPhysicalDevicePipelineRobustnessProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
}

function e_VkPipelineRobustnessCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.storageBuffers);
    w.i32(o.uniformBuffers);
    w.i32(o.vertexInputs);
    w.i32(o.images);
}

function e_VkPhysicalDeviceHostImageCopyFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.hostImageCopy);
}

function e_VkPhysicalDeviceHostImageCopyProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.copySrcLayoutCount);
    w.ptr(o.pCopySrcLayouts != null);
    if(o.pCopySrcLayouts != null)
    {
        w.i32s(o.pCopySrcLayouts, o.copySrcLayoutCount);
    }
    w.u32(o.copyDstLayoutCount);
    w.ptr(o.pCopyDstLayouts != null);
    if(o.pCopyDstLayouts != null)
    {
        w.i32s(o.pCopyDstLayouts, o.copyDstLayoutCount);
    }
    w.u8s(o.optimalTilingLayoutUUID, 16);
    w.u32(o.identicalMemoryTypeRequirements);
}

function e_VkSubresourceHostMemcpySize(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.size);
}

function e_VkHostImageCopyDevicePerformanceQuery(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.optimalDeviceAccess);
    w.u32(o.identicalMemoryLayout);
}

function e_VkPresentRegionsKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.swapchainCount);
    w.ptr(o.pRegions != null);
    if(o.pRegions != null)
    {
        for(let i = 0; i < o.swapchainCount; i++)
        {
            e_VkPresentRegionKHR(w, o.pRegions?.[i], root);
        }
    }
}

function e_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.pipelineExecutableInfo);
}

function e_VkNativeBufferANDROID(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.ptr(o.handle != null);
    if(o.handle != null)
    {
        w.u32(o.handle);
    }
    w.i32(o.stride);
    w.i32(o.format);
    w.i32(o.usage);
    e_VkNativeBufferUsage2ANDROID(w, o.usage2, root);
}

function e_VkPhysicalDeviceTransformFeedbackFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.transformFeedback);
    w.u32(o.geometryStreams);
}

function e_VkPhysicalDeviceTransformFeedbackPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxTransformFeedbackStreams);
    w.u32(o.maxTransformFeedbackBuffers);
    w.u64(o.maxTransformFeedbackBufferSize);
    w.u32(o.maxTransformFeedbackStreamDataSize);
    w.u32(o.maxTransformFeedbackBufferDataSize);
    w.u32(o.maxTransformFeedbackBufferDataStride);
    w.u32(o.transformFeedbackQueries);
    w.u32(o.transformFeedbackStreamsLinesTriangles);
    w.u32(o.transformFeedbackRasterizationStreamSelect);
    w.u32(o.transformFeedbackDraw);
}

function e_VkPipelineRasterizationStateStreamCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.rasterizationStream);
}

function e_VkPhysicalDeviceDepthClipEnableFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.depthClipEnable);
}

function e_VkPipelineRasterizationDepthClipStateCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.depthClipEnable);
}

function e_VkDrmFormatModifierPropertiesListEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    w.ptr(o.pDrmFormatModifierProperties != null);
    if(o.pDrmFormatModifierProperties != null)
    {
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            e_VkDrmFormatModifierPropertiesEXT(w, o.pDrmFormatModifierProperties?.[i], root);
        }
    }
}

function e_VkPhysicalDeviceImageDrmFormatModifierInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    w.ptr(o.pQueueFamilyIndices != null);
    if(o.pQueueFamilyIndices != null)
    {
        w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
    }
}

function e_VkImageDrmFormatModifierListCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    w.u64s(o.pDrmFormatModifiers, o.drmFormatModifierCount);
}

function e_VkImageDrmFormatModifierExplicitCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    for(let i = 0; i < o.drmFormatModifierPlaneCount; i++)
    {
        e_VkSubresourceLayout(w, o.pPlaneLayouts?.[i], root);
    }
}

function e_VkDrmFormatModifierPropertiesList2EXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    w.ptr(o.pDrmFormatModifierProperties != null);
    if(o.pDrmFormatModifierProperties != null)
    {
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            e_VkDrmFormatModifierProperties2EXT(w, o.pDrmFormatModifierProperties?.[i], root);
        }
    }
}

function e_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxVertexAttribDivisor);
}

function e_VkPhysicalDeviceFragmentDensityMapFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.fragmentDensityMap);
    w.u32(o.fragmentDensityMapDynamic);
    w.u32(o.fragmentDensityMapNonSubsampledImages);
}

function e_VkImportColorBufferGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.colorBuffer);
}

function e_VkPhysicalDeviceFragmentDensityMapPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkExtent2D(w, o.minFragmentDensityTexelSize, root);
    e_VkExtent2D(w, o.maxFragmentDensityTexelSize, root);
    w.u32(o.fragmentDensityInvocations);
}

function e_VkCreateBlobGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.blobMem);
    w.u32(o.blobFlags);
    w.u64(o.blobId);
}

function e_VkRenderPassFragmentDensityMapCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkAttachmentReference(w, o.fragmentDensityMapAttachment, root);
}

function e_VkImportBufferGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.buffer);
}

function e_VkRenderingFragmentDensityMapAttachmentInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.h(o.imageView);
    w.i32(o.imageLayout);
}

function e_VkPhysicalDeviceMemoryBudgetPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u64s(o.heapBudget, 16);
    w.u64s(o.heapUsage, 16);
}

function e_VkPhysicalDeviceProvokingVertexFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.provokingVertexLast);
    w.u32(o.transformFeedbackPreservesProvokingVertex);
}

function e_VkPhysicalDeviceProvokingVertexPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.provokingVertexModePerPipeline);
    w.u32(o.transformFeedbackPreservesTriangleFanProvokingVertex);
}

function e_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.i32(o.provokingVertexMode);
}

function e_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.extendedDynamicState);
}

function e_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.texelBufferAlignment);
}

function e_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.deviceMemoryReport);
}

function e_VkDeviceDeviceMemoryReportCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.be64(o.pfnUserCallback);
    w.void(o.pUserData);
}

function e_VkSamplerCustomBorderColorCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    e_VkClearColorValue(w, o.customBorderColor, root);
    w.i32(o.format);
}

function e_VkPhysicalDeviceCustomBorderColorPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.maxCustomBorderColorSamplers);
}

function e_VkPhysicalDeviceCustomBorderColorFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.customBorderColors);
    w.u32(o.customBorderColorWithoutFormat);
}

function e_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.graphicsPipelineLibrary);
}

function e_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.graphicsPipelineLibraryFastLinking);
    w.u32(o.graphicsPipelineLibraryIndependentInterpolationDecoration);
}

function e_VkGraphicsPipelineLibraryCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function e_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.ycbcr2plane444Formats);
}

function e_VkPhysicalDeviceImageCompressionControlFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionControl);
}

function e_VkImageCompressionControlEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.compressionControlPlaneCount);
    w.ptr(o.pFixedRateFlags != null);
    if(o.pFixedRateFlags != null)
    {
        w.u32s(o.pFixedRateFlags, o.compressionControlPlaneCount);
    }
}

function e_VkImageCompressionPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionFlags);
    w.u32(o.imageCompressionFixedRateFlags);
}

function e_VkPhysicalDevice4444FormatsFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.formatA4R4G4B4);
    w.u32(o.formatA4B4G4R4);
}

function e_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.primitiveTopologyListRestart);
    w.u32(o.primitiveTopologyPatchListRestart);
}

function e_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.extendedDynamicState2);
    w.u32(o.extendedDynamicState2LogicOp);
    w.u32(o.extendedDynamicState2PatchControlPoints);
}

function e_VkPhysicalDeviceColorWriteEnableFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.colorWriteEnable);
}

function e_VkPipelineColorWriteCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.attachmentCount);
    w.u32s(o.pColorWriteEnables, o.attachmentCount);
}

function e_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionControlSwapchain);
}

function d_VkApplicationInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    const p0 = r.ptr();
    o.pApplicationName = null;
    if(p0)
    {
        const l1 = r.be32();
        o.pApplicationName = "";
        o.pApplicationName = r.str(l1);
    }
    o.applicationVersion = r.u32();
    const p2 = r.ptr();
    o.pEngineName = null;
    if(p2)
    {
        const l3 = r.be32();
        o.pEngineName = "";
        o.pEngineName = r.str(l3);
    }
    o.engineVersion = r.u32();
    o.apiVersion = r.u32();
    return o;
}

function d_VkExtent3D(r, root)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    o.depth = r.u32();
    return o;
}

function e_VkExtent3D(w, o, root)
{
    o = o || {};
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.depth);
}

function d_VkPhysicalDeviceLimits(r, root)
{
    const o = {};
    o.maxImageDimension1D = r.u32();
    o.maxImageDimension2D = r.u32();
    o.maxImageDimension3D = r.u32();
    o.maxImageDimensionCube = r.u32();
    o.maxImageArrayLayers = r.u32();
    o.maxTexelBufferElements = r.u32();
    o.maxUniformBufferRange = r.u32();
    o.maxStorageBufferRange = r.u32();
    o.maxPushConstantsSize = r.u32();
    o.maxMemoryAllocationCount = r.u32();
    o.maxSamplerAllocationCount = r.u32();
    o.bufferImageGranularity = r.u64();
    o.sparseAddressSpaceSize = r.u64();
    o.maxBoundDescriptorSets = r.u32();
    o.maxPerStageDescriptorSamplers = r.u32();
    o.maxPerStageDescriptorUniformBuffers = r.u32();
    o.maxPerStageDescriptorStorageBuffers = r.u32();
    o.maxPerStageDescriptorSampledImages = r.u32();
    o.maxPerStageDescriptorStorageImages = r.u32();
    o.maxPerStageDescriptorInputAttachments = r.u32();
    o.maxPerStageResources = r.u32();
    o.maxDescriptorSetSamplers = r.u32();
    o.maxDescriptorSetUniformBuffers = r.u32();
    o.maxDescriptorSetUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetStorageBuffers = r.u32();
    o.maxDescriptorSetStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetSampledImages = r.u32();
    o.maxDescriptorSetStorageImages = r.u32();
    o.maxDescriptorSetInputAttachments = r.u32();
    o.maxVertexInputAttributes = r.u32();
    o.maxVertexInputBindings = r.u32();
    o.maxVertexInputAttributeOffset = r.u32();
    o.maxVertexInputBindingStride = r.u32();
    o.maxVertexOutputComponents = r.u32();
    o.maxTessellationGenerationLevel = r.u32();
    o.maxTessellationPatchSize = r.u32();
    o.maxTessellationControlPerVertexInputComponents = r.u32();
    o.maxTessellationControlPerVertexOutputComponents = r.u32();
    o.maxTessellationControlPerPatchOutputComponents = r.u32();
    o.maxTessellationControlTotalOutputComponents = r.u32();
    o.maxTessellationEvaluationInputComponents = r.u32();
    o.maxTessellationEvaluationOutputComponents = r.u32();
    o.maxGeometryShaderInvocations = r.u32();
    o.maxGeometryInputComponents = r.u32();
    o.maxGeometryOutputComponents = r.u32();
    o.maxGeometryOutputVertices = r.u32();
    o.maxGeometryTotalOutputComponents = r.u32();
    o.maxFragmentInputComponents = r.u32();
    o.maxFragmentOutputAttachments = r.u32();
    o.maxFragmentDualSrcAttachments = r.u32();
    o.maxFragmentCombinedOutputResources = r.u32();
    o.maxComputeSharedMemorySize = r.u32();
    o.maxComputeWorkGroupCount = r.u32s(3);
    o.maxComputeWorkGroupInvocations = r.u32();
    o.maxComputeWorkGroupSize = r.u32s(3);
    o.subPixelPrecisionBits = r.u32();
    o.subTexelPrecisionBits = r.u32();
    o.mipmapPrecisionBits = r.u32();
    o.maxDrawIndexedIndexValue = r.u32();
    o.maxDrawIndirectCount = r.u32();
    o.maxSamplerLodBias = r.f32();
    o.maxSamplerAnisotropy = r.f32();
    o.maxViewports = r.u32();
    o.maxViewportDimensions = r.u32s(2);
    o.viewportBoundsRange = r.f32s(2);
    o.viewportSubPixelBits = r.u32();
    o.minMemoryMapAlignment = r.be64();
    o.minTexelBufferOffsetAlignment = r.u64();
    o.minUniformBufferOffsetAlignment = r.u64();
    o.minStorageBufferOffsetAlignment = r.u64();
    o.minTexelOffset = r.i32();
    o.maxTexelOffset = r.u32();
    o.minTexelGatherOffset = r.i32();
    o.maxTexelGatherOffset = r.u32();
    o.minInterpolationOffset = r.f32();
    o.maxInterpolationOffset = r.f32();
    o.subPixelInterpolationOffsetBits = r.u32();
    o.maxFramebufferWidth = r.u32();
    o.maxFramebufferHeight = r.u32();
    o.maxFramebufferLayers = r.u32();
    o.framebufferColorSampleCounts = r.u32();
    o.framebufferDepthSampleCounts = r.u32();
    o.framebufferStencilSampleCounts = r.u32();
    o.framebufferNoAttachmentsSampleCounts = r.u32();
    o.maxColorAttachments = r.u32();
    o.sampledImageColorSampleCounts = r.u32();
    o.sampledImageIntegerSampleCounts = r.u32();
    o.sampledImageDepthSampleCounts = r.u32();
    o.sampledImageStencilSampleCounts = r.u32();
    o.storageImageSampleCounts = r.u32();
    o.maxSampleMaskWords = r.u32();
    o.timestampComputeAndGraphics = r.u32();
    o.timestampPeriod = r.f32();
    o.maxClipDistances = r.u32();
    o.maxCullDistances = r.u32();
    o.maxCombinedClipAndCullDistances = r.u32();
    o.discreteQueuePriorities = r.u32();
    o.pointSizeRange = r.f32s(2);
    o.lineWidthRange = r.f32s(2);
    o.pointSizeGranularity = r.f32();
    o.lineWidthGranularity = r.f32();
    o.strictLines = r.u32();
    o.standardSampleLocations = r.u32();
    o.optimalBufferCopyOffsetAlignment = r.u64();
    o.optimalBufferCopyRowPitchAlignment = r.u64();
    o.nonCoherentAtomSize = r.u64();
    return o;
}

function d_VkPhysicalDeviceSparseProperties(r, root)
{
    const o = {};
    o.residencyStandard2DBlockShape = r.u32();
    o.residencyStandard2DMultisampleBlockShape = r.u32();
    o.residencyStandard3DBlockShape = r.u32();
    o.residencyAlignedMipSize = r.u32();
    o.residencyNonResidentStrict = r.u32();
    return o;
}

function e_VkPhysicalDeviceLimits(w, o, root)
{
    o = o || {};
    w.u32(o.maxImageDimension1D);
    w.u32(o.maxImageDimension2D);
    w.u32(o.maxImageDimension3D);
    w.u32(o.maxImageDimensionCube);
    w.u32(o.maxImageArrayLayers);
    w.u32(o.maxTexelBufferElements);
    w.u32(o.maxUniformBufferRange);
    w.u32(o.maxStorageBufferRange);
    w.u32(o.maxPushConstantsSize);
    w.u32(o.maxMemoryAllocationCount);
    w.u32(o.maxSamplerAllocationCount);
    w.u64(o.bufferImageGranularity);
    w.u64(o.sparseAddressSpaceSize);
    w.u32(o.maxBoundDescriptorSets);
    w.u32(o.maxPerStageDescriptorSamplers);
    w.u32(o.maxPerStageDescriptorUniformBuffers);
    w.u32(o.maxPerStageDescriptorStorageBuffers);
    w.u32(o.maxPerStageDescriptorSampledImages);
    w.u32(o.maxPerStageDescriptorStorageImages);
    w.u32(o.maxPerStageDescriptorInputAttachments);
    w.u32(o.maxPerStageResources);
    w.u32(o.maxDescriptorSetSamplers);
    w.u32(o.maxDescriptorSetUniformBuffers);
    w.u32(o.maxDescriptorSetUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetStorageBuffers);
    w.u32(o.maxDescriptorSetStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetSampledImages);
    w.u32(o.maxDescriptorSetStorageImages);
    w.u32(o.maxDescriptorSetInputAttachments);
    w.u32(o.maxVertexInputAttributes);
    w.u32(o.maxVertexInputBindings);
    w.u32(o.maxVertexInputAttributeOffset);
    w.u32(o.maxVertexInputBindingStride);
    w.u32(o.maxVertexOutputComponents);
    w.u32(o.maxTessellationGenerationLevel);
    w.u32(o.maxTessellationPatchSize);
    w.u32(o.maxTessellationControlPerVertexInputComponents);
    w.u32(o.maxTessellationControlPerVertexOutputComponents);
    w.u32(o.maxTessellationControlPerPatchOutputComponents);
    w.u32(o.maxTessellationControlTotalOutputComponents);
    w.u32(o.maxTessellationEvaluationInputComponents);
    w.u32(o.maxTessellationEvaluationOutputComponents);
    w.u32(o.maxGeometryShaderInvocations);
    w.u32(o.maxGeometryInputComponents);
    w.u32(o.maxGeometryOutputComponents);
    w.u32(o.maxGeometryOutputVertices);
    w.u32(o.maxGeometryTotalOutputComponents);
    w.u32(o.maxFragmentInputComponents);
    w.u32(o.maxFragmentOutputAttachments);
    w.u32(o.maxFragmentDualSrcAttachments);
    w.u32(o.maxFragmentCombinedOutputResources);
    w.u32(o.maxComputeSharedMemorySize);
    w.u32s(o.maxComputeWorkGroupCount, 3);
    w.u32(o.maxComputeWorkGroupInvocations);
    w.u32s(o.maxComputeWorkGroupSize, 3);
    w.u32(o.subPixelPrecisionBits);
    w.u32(o.subTexelPrecisionBits);
    w.u32(o.mipmapPrecisionBits);
    w.u32(o.maxDrawIndexedIndexValue);
    w.u32(o.maxDrawIndirectCount);
    w.f32(o.maxSamplerLodBias);
    w.f32(o.maxSamplerAnisotropy);
    w.u32(o.maxViewports);
    w.u32s(o.maxViewportDimensions, 2);
    w.f32s(o.viewportBoundsRange, 2);
    w.u32(o.viewportSubPixelBits);
    w.be64(o.minMemoryMapAlignment);
    w.u64(o.minTexelBufferOffsetAlignment);
    w.u64(o.minUniformBufferOffsetAlignment);
    w.u64(o.minStorageBufferOffsetAlignment);
    w.i32(o.minTexelOffset);
    w.u32(o.maxTexelOffset);
    w.i32(o.minTexelGatherOffset);
    w.u32(o.maxTexelGatherOffset);
    w.f32(o.minInterpolationOffset);
    w.f32(o.maxInterpolationOffset);
    w.u32(o.subPixelInterpolationOffsetBits);
    w.u32(o.maxFramebufferWidth);
    w.u32(o.maxFramebufferHeight);
    w.u32(o.maxFramebufferLayers);
    w.u32(o.framebufferColorSampleCounts);
    w.u32(o.framebufferDepthSampleCounts);
    w.u32(o.framebufferStencilSampleCounts);
    w.u32(o.framebufferNoAttachmentsSampleCounts);
    w.u32(o.maxColorAttachments);
    w.u32(o.sampledImageColorSampleCounts);
    w.u32(o.sampledImageIntegerSampleCounts);
    w.u32(o.sampledImageDepthSampleCounts);
    w.u32(o.sampledImageStencilSampleCounts);
    w.u32(o.storageImageSampleCounts);
    w.u32(o.maxSampleMaskWords);
    w.u32(o.timestampComputeAndGraphics);
    w.f32(o.timestampPeriod);
    w.u32(o.maxClipDistances);
    w.u32(o.maxCullDistances);
    w.u32(o.maxCombinedClipAndCullDistances);
    w.u32(o.discreteQueuePriorities);
    w.f32s(o.pointSizeRange, 2);
    w.f32s(o.lineWidthRange, 2);
    w.f32(o.pointSizeGranularity);
    w.f32(o.lineWidthGranularity);
    w.u32(o.strictLines);
    w.u32(o.standardSampleLocations);
    w.u64(o.optimalBufferCopyOffsetAlignment);
    w.u64(o.optimalBufferCopyRowPitchAlignment);
    w.u64(o.nonCoherentAtomSize);
}

function e_VkPhysicalDeviceSparseProperties(w, o, root)
{
    o = o || {};
    w.u32(o.residencyStandard2DBlockShape);
    w.u32(o.residencyStandard2DMultisampleBlockShape);
    w.u32(o.residencyStandard3DBlockShape);
    w.u32(o.residencyAlignedMipSize);
    w.u32(o.residencyNonResidentStrict);
}

function d_VkMemoryType(r, root)
{
    const o = {};
    o.propertyFlags = r.u32();
    o.heapIndex = r.u32();
    return o;
}

function d_VkMemoryHeap(r, root)
{
    const o = {};
    o.size = r.u64();
    o.flags = r.u32();
    return o;
}

function e_VkMemoryType(w, o, root)
{
    o = o || {};
    w.u32(o.propertyFlags);
    w.u32(o.heapIndex);
}

function e_VkMemoryHeap(w, o, root)
{
    o = o || {};
    w.u64(o.size);
    w.u32(o.flags);
}

function d_VkDeviceQueueCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
    o.queueCount = r.u32();
    if((o.queueCount > 0))
    {
        o.pQueuePriorities = r.f32s(o.queueCount);
    }
    return o;
}

function d_VkSparseBufferMemoryBindInfo(r, root)
{
    const o = {};
    o.buffer = r.h();
    o.bindCount = r.u32();
    o.pBinds = new Array(r.count(o.bindCount));
    for(let i = 0; i < o.bindCount; i++)
    {
        o.pBinds[i] = d_VkSparseMemoryBind(r, root);
    }
    return o;
}

function d_VkSparseImageOpaqueMemoryBindInfo(r, root)
{
    const o = {};
    o.image = r.h();
    o.bindCount = r.u32();
    o.pBinds = new Array(r.count(o.bindCount));
    for(let i = 0; i < o.bindCount; i++)
    {
        o.pBinds[i] = d_VkSparseMemoryBind(r, root);
    }
    return o;
}

function d_VkSparseImageMemoryBindInfo(r, root)
{
    const o = {};
    o.image = r.h();
    o.bindCount = r.u32();
    o.pBinds = new Array(r.count(o.bindCount));
    for(let i = 0; i < o.bindCount; i++)
    {
        o.pBinds[i] = d_VkSparseImageMemoryBind(r, root);
    }
    return o;
}

function d_VkComponentMapping(r, root)
{
    const o = {};
    o.r = r.i32();
    o.g = r.i32();
    o.b = r.i32();
    o.a = r.i32();
    return o;
}

function d_VkPipelineShaderStageCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.stage = r.i32();
    o.module = r.h();
    const l0 = r.be32();
    o.pName = "";
    o.pName = r.str(l0);
    const p1 = r.ptr();
    o.pSpecializationInfo = null;
    if(p1)
    {
        o.pSpecializationInfo = d_VkSpecializationInfo(r, root);
    }
    return o;
}

function d_VkPipelineVertexInputStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.vertexBindingDescriptionCount = r.u32();
    o.pVertexBindingDescriptions = new Array(r.count(o.vertexBindingDescriptionCount));
    for(let i = 0; i < o.vertexBindingDescriptionCount; i++)
    {
        o.pVertexBindingDescriptions[i] = d_VkVertexInputBindingDescription(r, root);
    }
    o.vertexAttributeDescriptionCount = r.u32();
    o.pVertexAttributeDescriptions = new Array(r.count(o.vertexAttributeDescriptionCount));
    for(let i = 0; i < o.vertexAttributeDescriptionCount; i++)
    {
        o.pVertexAttributeDescriptions[i] = d_VkVertexInputAttributeDescription(r, root);
    }
    return o;
}

function d_VkPipelineInputAssemblyStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.topology = r.i32();
    o.primitiveRestartEnable = r.u32();
    return o;
}

function d_VkPipelineTessellationStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.patchControlPoints = r.u32();
    return o;
}

function d_VkPipelineViewportStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.viewportCount = r.u32();
    const p0 = r.ptr();
    o.pViewports = null;
    if(p0)
    {
        o.pViewports = [];
        o.pViewports = new Array(r.count(o.viewportCount));
        for(let i = 0; i < o.viewportCount; i++)
        {
            o.pViewports[i] = d_VkViewport(r, root);
        }
    }
    o.scissorCount = r.u32();
    const p1 = r.ptr();
    o.pScissors = null;
    if(p1)
    {
        o.pScissors = [];
        o.pScissors = new Array(r.count(o.scissorCount));
        for(let i = 0; i < o.scissorCount; i++)
        {
            o.pScissors[i] = d_VkRect2D(r, root);
        }
    }
    return o;
}

function d_VkPipelineRasterizationStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.depthClampEnable = r.u32();
    o.rasterizerDiscardEnable = r.u32();
    o.polygonMode = r.i32();
    o.cullMode = r.u32();
    o.frontFace = r.i32();
    o.depthBiasEnable = r.u32();
    o.depthBiasConstantFactor = r.f32();
    o.depthBiasClamp = r.f32();
    o.depthBiasSlopeFactor = r.f32();
    o.lineWidth = r.f32();
    return o;
}

function d_VkPipelineMultisampleStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.rasterizationSamples = r.i32();
    o.sampleShadingEnable = r.u32();
    o.minSampleShading = r.f32();
    const p0 = r.ptr();
    o.pSampleMask = null;
    if(p0)
    {
        if((Math.trunc((o.rasterizationSamples + 31) / 32) > 0))
        {
            o.pSampleMask = r.u32s(Math.trunc((o.rasterizationSamples + 31) / 32));
        }
    }
    o.alphaToCoverageEnable = r.u32();
    o.alphaToOneEnable = r.u32();
    return o;
}

function d_VkPipelineDepthStencilStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.depthTestEnable = r.u32();
    o.depthWriteEnable = r.u32();
    o.depthCompareOp = r.i32();
    o.depthBoundsTestEnable = r.u32();
    o.stencilTestEnable = r.u32();
    o.front = d_VkStencilOpState(r, root);
    o.back = d_VkStencilOpState(r, root);
    o.minDepthBounds = r.f32();
    o.maxDepthBounds = r.f32();
    return o;
}

function d_VkPipelineColorBlendStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.logicOpEnable = r.u32();
    o.logicOp = r.i32();
    o.attachmentCount = r.u32();
    o.pAttachments = new Array(r.count(o.attachmentCount));
    for(let i = 0; i < o.attachmentCount; i++)
    {
        o.pAttachments[i] = d_VkPipelineColorBlendAttachmentState(r, root);
    }
    o.blendConstants = r.f32s(4);
    return o;
}

function d_VkPipelineDynamicStateCreateInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.dynamicStateCount = r.u32();
    if((o.dynamicStateCount > 0))
    {
        o.pDynamicStates = r.i32s(o.dynamicStateCount);
    }
    return o;
}

function d_VkPushConstantRange(r, root)
{
    const o = {};
    o.stageFlags = r.u32();
    o.offset = r.u32();
    o.size = r.u32();
    return o;
}

function d_VkDescriptorSetLayoutBinding(r, root)
{
    const o = {};
    o.binding = r.u32();
    o.descriptorType = r.i32();
    o.descriptorCount = r.u32();
    o.stageFlags = r.u32();
    const p0 = r.ptr();
    o.pImmutableSamplers = null;
    if(p0)
    {
        o.pImmutableSamplers = [];
        if(o.descriptorCount)
        {
            o.pImmutableSamplers = new Array(r.count(o.descriptorCount));
            for(let k = 0; k < o.descriptorCount; k++)
            {
                o.pImmutableSamplers[k] = r.h();
            }
        }
    }
    return o;
}

function d_VkDescriptorPoolSize(r, root)
{
    const o = {};
    o.type = r.i32();
    o.descriptorCount = r.u32();
    return o;
}

function d_VkAttachmentDescription(r, root)
{
    const o = {};
    o.flags = r.u32();
    o.format = r.i32();
    o.samples = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.stencilLoadOp = r.i32();
    o.stencilStoreOp = r.i32();
    o.initialLayout = r.i32();
    o.finalLayout = r.i32();
    return o;
}

function d_VkSubpassDescription(r, root)
{
    const o = {};
    o.flags = r.u32();
    o.pipelineBindPoint = r.i32();
    o.inputAttachmentCount = r.u32();
    o.pInputAttachments = new Array(r.count(o.inputAttachmentCount));
    for(let i = 0; i < o.inputAttachmentCount; i++)
    {
        o.pInputAttachments[i] = d_VkAttachmentReference(r, root);
    }
    o.colorAttachmentCount = r.u32();
    o.pColorAttachments = new Array(r.count(o.colorAttachmentCount));
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        o.pColorAttachments[i] = d_VkAttachmentReference(r, root);
    }
    const p0 = r.ptr();
    o.pResolveAttachments = null;
    if(p0)
    {
        o.pResolveAttachments = [];
        o.pResolveAttachments = new Array(r.count(o.colorAttachmentCount));
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            o.pResolveAttachments[i] = d_VkAttachmentReference(r, root);
        }
    }
    const p1 = r.ptr();
    o.pDepthStencilAttachment = null;
    if(p1)
    {
        o.pDepthStencilAttachment = d_VkAttachmentReference(r, root);
    }
    o.preserveAttachmentCount = r.u32();
    if((o.preserveAttachmentCount > 0))
    {
        o.pPreserveAttachments = r.u32s(o.preserveAttachmentCount);
    }
    return o;
}

function d_VkSubpassDependency(r, root)
{
    const o = {};
    o.srcSubpass = r.u32();
    o.dstSubpass = r.u32();
    o.srcStageMask = r.u32();
    o.dstStageMask = r.u32();
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.dependencyFlags = r.u32();
    return o;
}

function d_VkCommandBufferInheritanceInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.renderPass = r.h();
    o.subpass = r.u32();
    o.framebuffer = r.h();
    o.occlusionQueryEnable = r.u32();
    o.queryFlags = r.u32();
    o.pipelineStatistics = r.u32();
    return o;
}

function d_VkOffset2D(r, root)
{
    const o = {};
    o.x = r.i32();
    o.y = r.i32();
    return o;
}

function d_VkImageSubresourceLayers(r, root)
{
    const o = {};
    o.aspectMask = r.u32();
    o.mipLevel = r.u32();
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}

function d_VkOffset3D(r, root)
{
    const o = {};
    o.x = r.i32();
    o.y = r.i32();
    o.z = r.i32();
    return o;
}

function d_VkClearValue(r, root)
{
    const o = {};
    o.color = d_VkClearColorValue(r, root);
    return o;
}

function d_VkDescriptorUpdateTemplateEntry(r, root)
{
    const o = {};
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
    o.descriptorType = r.i32();
    o.offset = r.be64();
    o.stride = r.be64();
    return o;
}

function d_VkExternalMemoryProperties(r, root)
{
    const o = {};
    o.externalMemoryFeatures = r.u32();
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    return o;
}

function e_VkExternalMemoryProperties(w, o, root)
{
    o = o || {};
    w.u32(o.externalMemoryFeatures);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
}

function d_VkAttachmentDescription2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.format = r.i32();
    o.samples = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.stencilLoadOp = r.i32();
    o.stencilStoreOp = r.i32();
    o.initialLayout = r.i32();
    o.finalLayout = r.i32();
    return o;
}

function d_VkSubpassDescription2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.pipelineBindPoint = r.i32();
    o.viewMask = r.u32();
    o.inputAttachmentCount = r.u32();
    o.pInputAttachments = new Array(r.count(o.inputAttachmentCount));
    for(let i = 0; i < o.inputAttachmentCount; i++)
    {
        o.pInputAttachments[i] = d_VkAttachmentReference2(r, root);
    }
    o.colorAttachmentCount = r.u32();
    o.pColorAttachments = new Array(r.count(o.colorAttachmentCount));
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        o.pColorAttachments[i] = d_VkAttachmentReference2(r, root);
    }
    const p0 = r.ptr();
    o.pResolveAttachments = null;
    if(p0)
    {
        o.pResolveAttachments = [];
        o.pResolveAttachments = new Array(r.count(o.colorAttachmentCount));
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            o.pResolveAttachments[i] = d_VkAttachmentReference2(r, root);
        }
    }
    const p1 = r.ptr();
    o.pDepthStencilAttachment = null;
    if(p1)
    {
        o.pDepthStencilAttachment = d_VkAttachmentReference2(r, root);
    }
    o.preserveAttachmentCount = r.u32();
    if((o.preserveAttachmentCount > 0))
    {
        o.pPreserveAttachments = r.u32s(o.preserveAttachmentCount);
    }
    return o;
}

function d_VkSubpassDependency2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcSubpass = r.u32();
    o.dstSubpass = r.u32();
    o.srcStageMask = r.u32();
    o.dstStageMask = r.u32();
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.dependencyFlags = r.u32();
    o.viewOffset = r.i32();
    return o;
}

function d_VkBufferMemoryBarrier2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.buffer = r.h();
    o.offset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkImageMemoryBarrier2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.image = r.h();
    o.subresourceRange = d_VkImageSubresourceRange(r, root);
    return o;
}

function d_VkSemaphoreSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.semaphore = r.h();
    o.value = r.u64();
    o.stageMask = r.u64();
    o.deviceIndex = r.u32();
    return o;
}

function d_VkCommandBufferSubmitInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.commandBuffer = r.h();
    o.deviceMask = r.u32();
    return o;
}

function d_VkBufferCopy2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcOffset = r.u64();
    o.dstOffset = r.u64();
    o.size = r.u64();
    return o;
}

function d_VkImageCopy2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffset = d_VkOffset3D(r, root);
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffset = d_VkOffset3D(r, root);
    o.extent = d_VkExtent3D(r, root);
    return o;
}

function d_VkBufferImageCopy2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.bufferOffset = r.u64();
    o.bufferRowLength = r.u32();
    o.bufferImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r, root);
    o.imageOffset = d_VkOffset3D(r, root);
    o.imageExtent = d_VkExtent3D(r, root);
    return o;
}

function d_VkImageBlit2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffsets = new Array(r.count(2));
    for(let i = 0; i < 2; i++)
    {
        o.srcOffsets[i] = d_VkOffset3D(r, root);
    }
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffsets = new Array(r.count(2));
    for(let i = 0; i < 2; i++)
    {
        o.dstOffsets[i] = d_VkOffset3D(r, root);
    }
    return o;
}

function d_VkImageResolve2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.srcSubresource = d_VkImageSubresourceLayers(r, root);
    o.srcOffset = d_VkOffset3D(r, root);
    o.dstSubresource = d_VkImageSubresourceLayers(r, root);
    o.dstOffset = d_VkOffset3D(r, root);
    o.extent = d_VkExtent3D(r, root);
    return o;
}

function d_VkRenderingAttachmentInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.imageView = r.h();
    o.imageLayout = r.i32();
    o.resolveMode = r.i32();
    o.resolveImageView = r.h();
    o.resolveImageLayout = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.clearValue = d_VkClearValue(r, root);
    return o;
}

function d_VkMemoryToImageCopy(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pHostPointer = r.void();
    o.memoryRowLength = r.u32();
    o.memoryImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r, root);
    o.imageOffset = d_VkOffset3D(r, root);
    o.imageExtent = d_VkExtent3D(r, root);
    return o;
}

function d_VkImageToMemoryCopy(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.pHostPointer = r.void();
    o.memoryRowLength = r.u32();
    o.memoryImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r, root);
    o.imageOffset = d_VkOffset3D(r, root);
    o.imageExtent = d_VkExtent3D(r, root);
    return o;
}

function d_VkPipelineExecutableStatisticValueKHR(r, root)
{
    const o = {};
    o.b32 = r.u32();
    return o;
}

function e_VkPipelineExecutableStatisticValueKHR(w, o, root)
{
    o = o || {};
    w.u32(o.b32);
}

function d_VkInputAttachmentAspectReference(r, root)
{
    const o = {};
    o.subpass = r.u32();
    o.inputAttachmentIndex = r.u32();
    o.aspectMask = r.u32();
    return o;
}

function d_VkConformanceVersion(r, root)
{
    const o = {};
    o.major = r.u8();
    o.minor = r.u8();
    o.subminor = r.u8();
    o.patch = r.u8();
    return o;
}

function d_VkAttachmentReference2(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.attachment = r.u32();
    o.layout = r.i32();
    o.aspectMask = r.u32();
    return o;
}

function d_VkFramebufferAttachmentImageInfo(r, root)
{
    const o = {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = d_pnext(r, root);
    o.flags = r.u32();
    o.usage = r.u32();
    o.width = r.u32();
    o.height = r.u32();
    o.layerCount = r.u32();
    o.viewFormatCount = r.u32();
    if((o.viewFormatCount > 0))
    {
        o.pViewFormats = r.i32s(o.viewFormatCount);
    }
    return o;
}

function d_VkPipelineCreationFeedback(r, root)
{
    const o = {};
    o.flags = r.u32();
    o.duration = r.u64();
    return o;
}

function d_VkVertexInputBindingDivisorDescription(r, root)
{
    const o = {};
    o.binding = r.u32();
    o.divisor = r.u32();
    return o;
}

function d_VkPresentRegionKHR(r, root)
{
    const o = {};
    o.rectangleCount = r.u32();
    const p0 = r.ptr();
    o.pRectangles = null;
    if(p0)
    {
        o.pRectangles = [];
        o.pRectangles = new Array(r.count(o.rectangleCount));
        for(let i = 0; i < o.rectangleCount; i++)
        {
            o.pRectangles[i] = d_VkRectLayerKHR(r, root);
        }
    }
    return o;
}

function d_VkNativeBufferUsage2ANDROID(r, root)
{
    const o = {};
    o.consumer = r.u64();
    o.producer = r.u64();
    return o;
}

function d_VkDrmFormatModifierPropertiesEXT(r, root)
{
    const o = {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u32();
    return o;
}

function d_VkDrmFormatModifierProperties2EXT(r, root)
{
    const o = {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u64();
    return o;
}

function d_VkAttachmentReference(r, root)
{
    const o = {};
    o.attachment = r.u32();
    o.layout = r.i32();
    return o;
}

function e_VkPushConstantRange(w, o, root)
{
    o = o || {};
    w.u32(o.stageFlags);
    w.u32(o.offset);
    w.u32(o.size);
}

function e_VkRect2D(w, o, root)
{
    o = o || {};
    e_VkOffset2D(w, o.offset, root);
    e_VkExtent2D(w, o.extent, root);
}

function e_VkInputAttachmentAspectReference(w, o, root)
{
    o = o || {};
    w.u32(o.subpass);
    w.u32(o.inputAttachmentIndex);
    w.u32(o.aspectMask);
}

function e_VkConformanceVersion(w, o, root)
{
    o = o || {};
    w.u8(o.major);
    w.u8(o.minor);
    w.u8(o.subminor);
    w.u8(o.patch);
}

function e_VkAttachmentReference2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.attachment);
    w.i32(o.layout);
    w.u32(o.aspectMask);
}

function e_VkFramebufferAttachmentImageInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    e_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.usage);
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.layerCount);
    w.u32(o.viewFormatCount);
    w.i32s(o.pViewFormats, o.viewFormatCount);
}

function e_VkPipelineCreationFeedback(w, o, root)
{
    o = o || {};
    w.u32(o.flags);
    w.u64(o.duration);
}

function e_VkVertexInputBindingDivisorDescription(w, o, root)
{
    o = o || {};
    w.u32(o.binding);
    w.u32(o.divisor);
}

function e_VkPresentRegionKHR(w, o, root)
{
    o = o || {};
    w.u32(o.rectangleCount);
    w.ptr(o.pRectangles != null);
    if(o.pRectangles != null)
    {
        for(let i = 0; i < o.rectangleCount; i++)
        {
            e_VkRectLayerKHR(w, o.pRectangles?.[i], root);
        }
    }
}

function e_VkNativeBufferUsage2ANDROID(w, o, root)
{
    o = o || {};
    w.u64(o.consumer);
    w.u64(o.producer);
}

function e_VkDrmFormatModifierPropertiesEXT(w, o, root)
{
    o = o || {};
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u32(o.drmFormatModifierTilingFeatures);
}

function e_VkDrmFormatModifierProperties2EXT(w, o, root)
{
    o = o || {};
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u64(o.drmFormatModifierTilingFeatures);
}

function e_VkAttachmentReference(w, o, root)
{
    o = o || {};
    w.u32(o.attachment);
    w.i32(o.layout);
}

function e_VkClearColorValue(w, o, root)
{
    o = o || {};
    w.f32s(o.float32, 4);
}

function d_VkSparseMemoryBind(r, root)
{
    const o = {};
    o.resourceOffset = r.u64();
    o.size = r.u64();
    o.memory = r.h();
    o.memoryOffset = r.u64();
    o.flags = r.u32();
    return o;
}

function d_VkSparseImageMemoryBind(r, root)
{
    const o = {};
    o.subresource = d_VkImageSubresource(r, root);
    o.offset = d_VkOffset3D(r, root);
    o.extent = d_VkExtent3D(r, root);
    o.memory = r.h();
    o.memoryOffset = r.u64();
    o.flags = r.u32();
    return o;
}

function d_VkSpecializationInfo(r, root)
{
    const o = {};
    o.mapEntryCount = r.u32();
    o.pMapEntries = new Array(r.count(o.mapEntryCount));
    for(let i = 0; i < o.mapEntryCount; i++)
    {
        o.pMapEntries[i] = d_VkSpecializationMapEntry(r, root);
    }
    o.dataSize = r.be64();
    if((o.dataSize > 0))
    {
        o.pData = r.bytes_of(o.dataSize);
    }
    return o;
}

function d_VkVertexInputBindingDescription(r, root)
{
    const o = {};
    o.binding = r.u32();
    o.stride = r.u32();
    o.inputRate = r.i32();
    return o;
}

function d_VkVertexInputAttributeDescription(r, root)
{
    const o = {};
    o.location = r.u32();
    o.binding = r.u32();
    o.format = r.i32();
    o.offset = r.u32();
    return o;
}

function d_VkStencilOpState(r, root)
{
    const o = {};
    o.failOp = r.i32();
    o.passOp = r.i32();
    o.depthFailOp = r.i32();
    o.compareOp = r.i32();
    o.compareMask = r.u32();
    o.writeMask = r.u32();
    o.reference = r.u32();
    return o;
}

function d_VkPipelineColorBlendAttachmentState(r, root)
{
    const o = {};
    o.blendEnable = r.u32();
    o.srcColorBlendFactor = r.i32();
    o.dstColorBlendFactor = r.i32();
    o.colorBlendOp = r.i32();
    o.srcAlphaBlendFactor = r.i32();
    o.dstAlphaBlendFactor = r.i32();
    o.alphaBlendOp = r.i32();
    o.colorWriteMask = r.u32();
    return o;
}

function d_VkRectLayerKHR(r, root)
{
    const o = {};
    o.offset = d_VkOffset2D(r, root);
    o.extent = d_VkExtent2D(r, root);
    o.layer = r.u32();
    return o;
}

function e_VkOffset2D(w, o, root)
{
    o = o || {};
    w.i32(o.x);
    w.i32(o.y);
}

function e_VkRectLayerKHR(w, o, root)
{
    o = o || {};
    e_VkOffset2D(w, o.offset, root);
    e_VkExtent2D(w, o.extent, root);
    w.u32(o.layer);
}

function d_VkSpecializationMapEntry(r, root)
{
    const o = {};
    o.constantID = r.u32();
    o.offset = r.u32();
    o.size = r.be64();
    return o;
}

/** pNext's structs (requests), by sType (some by the chain's root too): [its function, its C size] */
const PNEXT_REQUEST = {
    16: [d_VkShaderModuleCreateInfo, 40],
    30: [d_VkPipelineLayoutCreateInfo, 48],
    1000094000: [d_VkPhysicalDeviceSubgroupProperties, 32],
    1000083000: [d_VkPhysicalDevice16BitStorageFeatures, 32],
    1000127000: [d_VkMemoryDedicatedRequirements, 24],
    1000127001: [d_VkMemoryDedicatedAllocateInfo, 32],
    1000060000: [d_VkMemoryAllocateFlagsInfo, 24],
    1000060003: [d_VkDeviceGroupRenderPassBeginInfo, 32],
    1000060004: [d_VkDeviceGroupCommandBufferBeginInfo, 24],
    1000060005: [d_VkDeviceGroupSubmitInfo, 64],
    1000060006: [d_VkDeviceGroupBindSparseInfo, 24],
    1000060013: [d_VkBindBufferMemoryDeviceGroupInfo, 32],
    1000060014: [d_VkBindImageMemoryDeviceGroupInfo, 48],
    1000070001: [d_VkDeviceGroupDeviceCreateInfo, 32],
    1000059000: [d_VkPhysicalDeviceFeatures2, 240],
    1000117000: [d_VkPhysicalDevicePointClippingProperties, 24],
    1000117001: [d_VkRenderPassInputAttachmentAspectCreateInfo, 32],
    1000117002: [d_VkImageViewUsageCreateInfo, 24],
    1000117003: [d_VkPipelineTessellationDomainOriginStateCreateInfo, 24],
    1000053000: [d_VkRenderPassMultiviewCreateInfo, 64],
    1000053001: [d_VkPhysicalDeviceMultiviewFeatures, 32],
    1000053002: [d_VkPhysicalDeviceMultiviewProperties, 24],
    1000120000: [d_VkPhysicalDeviceVariablePointersFeatures, 24],
    1000145001: [d_VkPhysicalDeviceProtectedMemoryFeatures, 24],
    1000145002: [d_VkPhysicalDeviceProtectedMemoryProperties, 24],
    1000145000: [d_VkProtectedSubmitInfo, 24],
    1000156001: [d_VkSamplerYcbcrConversionInfo, 24],
    1000156002: [d_VkBindImagePlaneMemoryInfo, 24],
    1000156003: [d_VkImagePlaneMemoryRequirementsInfo, 24],
    1000156004: [d_VkPhysicalDeviceSamplerYcbcrConversionFeatures, 24],
    1000156005: [d_VkSamplerYcbcrConversionImageFormatProperties, 24],
    1000071000: [d_VkPhysicalDeviceExternalImageFormatInfo, 24],
    1000071001: [d_VkExternalImageFormatProperties, 32],
    1000071004: [d_VkPhysicalDeviceIDProperties, 64],
    1000072001: [d_VkExternalMemoryImageCreateInfo, 24],
    1000072000: [d_VkExternalMemoryBufferCreateInfo, 24],
    1000072002: [d_VkExportMemoryAllocateInfo, 24],
    1000113000: [d_VkExportFenceCreateInfo, 24],
    1000077000: [d_VkExportSemaphoreCreateInfo, 24],
    1000168000: [d_VkPhysicalDeviceMaintenance3Properties, 32],
    1000063000: [d_VkPhysicalDeviceShaderDrawParametersFeatures, 24],
    49: [d_VkPhysicalDeviceVulkan11Features, 64],
    50: [d_VkPhysicalDeviceVulkan11Properties, 112],
    51: [d_VkPhysicalDeviceVulkan12Features, 208],
    52: [d_VkPhysicalDeviceVulkan12Properties, 736],
    1000147000: [d_VkImageFormatListCreateInfo, 32],
    1000177000: [d_VkPhysicalDevice8BitStorageFeatures, 32],
    1000196000: [d_VkPhysicalDeviceDriverProperties, 536],
    1000180000: [d_VkPhysicalDeviceShaderAtomicInt64Features, 24],
    1000082000: [d_VkPhysicalDeviceShaderFloat16Int8Features, 24],
    1000197000: [d_VkPhysicalDeviceFloatControlsProperties, 88],
    1000161000: [d_VkDescriptorSetLayoutBindingFlagsCreateInfo, 32],
    1000161001: [d_VkPhysicalDeviceDescriptorIndexingFeatures, 96],
    1000161002: [d_VkPhysicalDeviceDescriptorIndexingProperties, 112],
    1000161003: [d_VkDescriptorSetVariableDescriptorCountAllocateInfo, 32],
    1000161004: [d_VkDescriptorSetVariableDescriptorCountLayoutSupport, 24],
    1000199001: [d_VkSubpassDescriptionDepthStencilResolve, 32],
    1000199000: [d_VkPhysicalDeviceDepthStencilResolveProperties, 32],
    1000221000: [d_VkPhysicalDeviceScalarBlockLayoutFeatures, 24],
    1000246000: [d_VkImageStencilUsageCreateInfo, 24],
    1000130001: [d_VkSamplerReductionModeCreateInfo, 24],
    1000130000: [d_VkPhysicalDeviceSamplerFilterMinmaxProperties, 24],
    1000211000: [d_VkPhysicalDeviceVulkanMemoryModelFeatures, 32],
    1000108000: [d_VkPhysicalDeviceImagelessFramebufferFeatures, 24],
    1000108001: [d_VkFramebufferAttachmentsCreateInfo, 32],
    1000108003: [d_VkRenderPassAttachmentBeginInfo, 32],
    1000253000: [d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, 24],
    1000175000: [d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, 24],
    1000241000: [d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, 24],
    1000241001: [d_VkAttachmentReferenceStencilLayout, 24],
    1000241002: [d_VkAttachmentDescriptionStencilLayout, 24],
    1000261000: [d_VkPhysicalDeviceHostQueryResetFeatures, 24],
    1000207000: [d_VkPhysicalDeviceTimelineSemaphoreFeatures, 24],
    1000207001: [d_VkPhysicalDeviceTimelineSemaphoreProperties, 24],
    1000207002: [d_VkSemaphoreTypeCreateInfo, 32],
    1000207003: [d_VkTimelineSemaphoreSubmitInfo, 48],
    1000257000: [d_VkPhysicalDeviceBufferDeviceAddressFeatures, 32],
    1000257002: [d_VkBufferOpaqueCaptureAddressCreateInfo, 24],
    1000257003: [d_VkMemoryOpaqueCaptureAddressAllocateInfo, 24],
    53: [d_VkPhysicalDeviceVulkan13Features, 80],
    54: [d_VkPhysicalDeviceVulkan13Properties, 216],
    1000192000: [d_VkPipelineCreationFeedbackCreateInfo, 40],
    1000215000: [d_VkPhysicalDeviceShaderTerminateInvocationFeatures, 24],
    1000276000: [d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, 24],
    1000295000: [d_VkPhysicalDevicePrivateDataFeatures, 24],
    1000295001: [d_VkDevicePrivateDataCreateInfo, 24],
    1000297000: [d_VkPhysicalDevicePipelineCreationCacheControlFeatures, 24],
    1000314000: [d_VkMemoryBarrier2, 48],
    1000314007: [d_VkPhysicalDeviceSynchronization2Features, 24],
    1000325000: [d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, 24],
    1000335000: [d_VkPhysicalDeviceImageRobustnessFeatures, 24],
    1000225002: [d_VkPhysicalDeviceSubgroupSizeControlFeatures, 24],
    1000225000: [d_VkPhysicalDeviceSubgroupSizeControlProperties, 32],
    1000225001: [d_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, 24],
    1000138000: [d_VkPhysicalDeviceInlineUniformBlockFeatures, 24],
    1000138001: [d_VkPhysicalDeviceInlineUniformBlockProperties, 40],
    1000138002: [d_VkWriteDescriptorSetInlineUniformBlock, 32],
    1000138003: [d_VkDescriptorPoolInlineUniformBlockCreateInfo, 24],
    1000066000: [d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, 24],
    1000044002: [d_VkPipelineRenderingCreateInfo, 40],
    1000044003: [d_VkPhysicalDeviceDynamicRenderingFeatures, 24],
    1000044004: [d_VkCommandBufferInheritanceRenderingInfo, 56],
    1000280000: [d_VkPhysicalDeviceShaderIntegerDotProductFeatures, 24],
    1000280001: [d_VkPhysicalDeviceShaderIntegerDotProductProperties, 136],
    1000281001: [d_VkPhysicalDeviceTexelBufferAlignmentProperties, 48],
    1000360000: [d_VkFormatProperties3, 40],
    1000413000: [d_VkPhysicalDeviceMaintenance4Features, 24],
    1000413001: [d_VkPhysicalDeviceMaintenance4Properties, 24],
    55: [d_VkPhysicalDeviceVulkan14Features, 104],
    56: [d_VkPhysicalDeviceVulkan14Properties, 144],
    1000174000: [d_VkDeviceQueueGlobalPriorityCreateInfo, 24],
    1000388000: [d_VkPhysicalDeviceGlobalPriorityQueryFeatures, 24],
    1000388001: [d_VkQueueFamilyGlobalPriorityProperties, 88],
    1000416000: [d_VkPhysicalDeviceShaderSubgroupRotateFeatures, 24],
    1000528000: [d_VkPhysicalDeviceShaderFloatControls2Features, 24],
    1000544000: [d_VkPhysicalDeviceShaderExpectAssumeFeatures, 24],
    1000259000: [d_VkPhysicalDeviceLineRasterizationFeatures, 40],
    1000259002: [d_VkPhysicalDeviceLineRasterizationProperties, 24],
    1000259001: [d_VkPipelineRasterizationLineStateCreateInfo, 32],
    1000525000: [d_VkPhysicalDeviceVertexAttributeDivisorProperties, 24],
    1000190001: [d_VkPipelineVertexInputDivisorStateCreateInfo, 32],
    1000190002: [d_VkPhysicalDeviceVertexAttributeDivisorFeatures, 24],
    1000265000: [d_VkPhysicalDeviceIndexTypeUint8Features, 24],
    1000470000: [d_VkPhysicalDeviceMaintenance5Features, 24],
    1000470001: [d_VkPhysicalDeviceMaintenance5Properties, 40],
    1000470005: [d_VkPipelineCreateFlags2CreateInfo, 24],
    1000470006: [d_VkBufferUsageFlags2CreateInfo, 24],
    1000080000: [d_VkPhysicalDevicePushDescriptorProperties, 24],
    1000232000: [d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, 24],
    1000232001: [d_VkRenderingAttachmentLocationInfo, 32],
    1000232002: [d_VkRenderingInputAttachmentIndexInfo, 48],
    1000545000: [d_VkPhysicalDeviceMaintenance6Features, 24],
    1000545001: [d_VkPhysicalDeviceMaintenance6Properties, 32],
    1000545002: [d_VkBindMemoryStatus, 24],
    1000466000: [d_VkPhysicalDevicePipelineProtectedAccessFeatures, 24],
    1000068001: [d_VkPhysicalDevicePipelineRobustnessFeatures, 24],
    1000068002: [d_VkPhysicalDevicePipelineRobustnessProperties, 32],
    1000068000: [d_VkPipelineRobustnessCreateInfo, 32],
    1000270000: [d_VkPhysicalDeviceHostImageCopyFeatures, 24],
    1000270001: [d_VkPhysicalDeviceHostImageCopyProperties, 72],
    1000270008: [d_VkSubresourceHostMemcpySize, 24],
    1000270009: [d_VkHostImageCopyDevicePerformanceQuery, 24],
    1000084000: [d_VkPresentRegionsKHR, 32],
    1000269000: [d_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, 24],
    1000010000: [d_VkNativeBufferANDROID, 64],
    1000028000: [d_VkPhysicalDeviceTransformFeedbackFeaturesEXT, 24],
    1000028001: [d_VkPhysicalDeviceTransformFeedbackPropertiesEXT, 64],
    1000028002: [d_VkPipelineRasterizationStateStreamCreateInfoEXT, 24],
    1000102000: [d_VkPhysicalDeviceDepthClipEnableFeaturesEXT, 24],
    1000102001: [d_VkPipelineRasterizationDepthClipStateCreateInfoEXT, 24],
    1000158000: [d_VkDrmFormatModifierPropertiesListEXT, 32],
    1000158002: [d_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, 40],
    1000158003: [d_VkImageDrmFormatModifierListCreateInfoEXT, 32],
    1000158004: [d_VkImageDrmFormatModifierExplicitCreateInfoEXT, 40],
    1000158006: [d_VkDrmFormatModifierPropertiesList2EXT, 32],
    1000190000: [d_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, 24],
    1000218000: { 1000059000: [d_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 3: [d_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 5: [d_VkImportColorBufferGOOGLE, 24], default: [d_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32] },
    1000218001: { 1000059001: [d_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40], 5: [d_VkCreateBlobGOOGLE, 32], default: [d_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40] },
    1000218002: { 38: [d_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 1000109004: [d_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 5: [d_VkImportBufferGOOGLE, 24], default: [d_VkRenderPassFragmentDensityMapCreateInfoEXT, 24] },
    1000044007: [d_VkRenderingFragmentDensityMapAttachmentInfoEXT, 32],
    1000237000: [d_VkPhysicalDeviceMemoryBudgetPropertiesEXT, 272],
    1000254000: [d_VkPhysicalDeviceProvokingVertexFeaturesEXT, 24],
    1000254002: [d_VkPhysicalDeviceProvokingVertexPropertiesEXT, 24],
    1000254001: [d_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, 24],
    1000267000: [d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, 24],
    1000281000: [d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, 24],
    1000284000: [d_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, 24],
    1000284001: [d_VkDeviceDeviceMemoryReportCreateInfoEXT, 40],
    1000287000: [d_VkSamplerCustomBorderColorCreateInfoEXT, 40],
    1000287001: [d_VkPhysicalDeviceCustomBorderColorPropertiesEXT, 24],
    1000287002: [d_VkPhysicalDeviceCustomBorderColorFeaturesEXT, 24],
    1000320000: [d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, 24],
    1000320001: [d_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, 24],
    1000320002: [d_VkGraphicsPipelineLibraryCreateInfoEXT, 24],
    1000330000: [d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, 24],
    1000338000: [d_VkPhysicalDeviceImageCompressionControlFeaturesEXT, 24],
    1000338001: [d_VkImageCompressionControlEXT, 32],
    1000338004: [d_VkImageCompressionPropertiesEXT, 24],
    1000340000: [d_VkPhysicalDevice4444FormatsFeaturesEXT, 24],
    1000356000: [d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, 24],
    1000377000: [d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, 32],
    1000381000: [d_VkPhysicalDeviceColorWriteEnableFeaturesEXT, 24],
    1000381001: [d_VkPipelineColorWriteCreateInfoEXT, 32],
    1000385000: [d_VkImportColorBufferGOOGLE, 24],
    1000385001: [d_VkImportBufferGOOGLE, 24],
    1000385002: [d_VkCreateBlobGOOGLE, 32],
    1000437000: [d_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, 24],
};
/** pNext's structs (replies) */
const PNEXT_REPLY = {
    16: [e_VkShaderModuleCreateInfo, 40],
    30: [e_VkPipelineLayoutCreateInfo, 48],
    1000094000: [e_VkPhysicalDeviceSubgroupProperties, 32],
    1000083000: [e_VkPhysicalDevice16BitStorageFeatures, 32],
    1000127000: [e_VkMemoryDedicatedRequirements, 24],
    1000127001: [e_VkMemoryDedicatedAllocateInfo, 32],
    1000060000: [e_VkMemoryAllocateFlagsInfo, 24],
    1000060003: [e_VkDeviceGroupRenderPassBeginInfo, 32],
    1000060004: [e_VkDeviceGroupCommandBufferBeginInfo, 24],
    1000060005: [e_VkDeviceGroupSubmitInfo, 64],
    1000060006: [e_VkDeviceGroupBindSparseInfo, 24],
    1000060013: [e_VkBindBufferMemoryDeviceGroupInfo, 32],
    1000060014: [e_VkBindImageMemoryDeviceGroupInfo, 48],
    1000070001: [e_VkDeviceGroupDeviceCreateInfo, 32],
    1000059000: [e_VkPhysicalDeviceFeatures2, 240],
    1000117000: [e_VkPhysicalDevicePointClippingProperties, 24],
    1000117001: [e_VkRenderPassInputAttachmentAspectCreateInfo, 32],
    1000117002: [e_VkImageViewUsageCreateInfo, 24],
    1000117003: [e_VkPipelineTessellationDomainOriginStateCreateInfo, 24],
    1000053000: [e_VkRenderPassMultiviewCreateInfo, 64],
    1000053001: [e_VkPhysicalDeviceMultiviewFeatures, 32],
    1000053002: [e_VkPhysicalDeviceMultiviewProperties, 24],
    1000120000: [e_VkPhysicalDeviceVariablePointersFeatures, 24],
    1000145001: [e_VkPhysicalDeviceProtectedMemoryFeatures, 24],
    1000145002: [e_VkPhysicalDeviceProtectedMemoryProperties, 24],
    1000145000: [e_VkProtectedSubmitInfo, 24],
    1000156001: [e_VkSamplerYcbcrConversionInfo, 24],
    1000156002: [e_VkBindImagePlaneMemoryInfo, 24],
    1000156003: [e_VkImagePlaneMemoryRequirementsInfo, 24],
    1000156004: [e_VkPhysicalDeviceSamplerYcbcrConversionFeatures, 24],
    1000156005: [e_VkSamplerYcbcrConversionImageFormatProperties, 24],
    1000071000: [e_VkPhysicalDeviceExternalImageFormatInfo, 24],
    1000071001: [e_VkExternalImageFormatProperties, 32],
    1000071004: [e_VkPhysicalDeviceIDProperties, 64],
    1000072001: [e_VkExternalMemoryImageCreateInfo, 24],
    1000072000: [e_VkExternalMemoryBufferCreateInfo, 24],
    1000072002: [e_VkExportMemoryAllocateInfo, 24],
    1000113000: [e_VkExportFenceCreateInfo, 24],
    1000077000: [e_VkExportSemaphoreCreateInfo, 24],
    1000168000: [e_VkPhysicalDeviceMaintenance3Properties, 32],
    1000063000: [e_VkPhysicalDeviceShaderDrawParametersFeatures, 24],
    49: [e_VkPhysicalDeviceVulkan11Features, 64],
    50: [e_VkPhysicalDeviceVulkan11Properties, 112],
    51: [e_VkPhysicalDeviceVulkan12Features, 208],
    52: [e_VkPhysicalDeviceVulkan12Properties, 736],
    1000147000: [e_VkImageFormatListCreateInfo, 32],
    1000177000: [e_VkPhysicalDevice8BitStorageFeatures, 32],
    1000196000: [e_VkPhysicalDeviceDriverProperties, 536],
    1000180000: [e_VkPhysicalDeviceShaderAtomicInt64Features, 24],
    1000082000: [e_VkPhysicalDeviceShaderFloat16Int8Features, 24],
    1000197000: [e_VkPhysicalDeviceFloatControlsProperties, 88],
    1000161000: [e_VkDescriptorSetLayoutBindingFlagsCreateInfo, 32],
    1000161001: [e_VkPhysicalDeviceDescriptorIndexingFeatures, 96],
    1000161002: [e_VkPhysicalDeviceDescriptorIndexingProperties, 112],
    1000161003: [e_VkDescriptorSetVariableDescriptorCountAllocateInfo, 32],
    1000161004: [e_VkDescriptorSetVariableDescriptorCountLayoutSupport, 24],
    1000199001: [e_VkSubpassDescriptionDepthStencilResolve, 32],
    1000199000: [e_VkPhysicalDeviceDepthStencilResolveProperties, 32],
    1000221000: [e_VkPhysicalDeviceScalarBlockLayoutFeatures, 24],
    1000246000: [e_VkImageStencilUsageCreateInfo, 24],
    1000130001: [e_VkSamplerReductionModeCreateInfo, 24],
    1000130000: [e_VkPhysicalDeviceSamplerFilterMinmaxProperties, 24],
    1000211000: [e_VkPhysicalDeviceVulkanMemoryModelFeatures, 32],
    1000108000: [e_VkPhysicalDeviceImagelessFramebufferFeatures, 24],
    1000108001: [e_VkFramebufferAttachmentsCreateInfo, 32],
    1000108003: [e_VkRenderPassAttachmentBeginInfo, 32],
    1000253000: [e_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, 24],
    1000175000: [e_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, 24],
    1000241000: [e_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, 24],
    1000241001: [e_VkAttachmentReferenceStencilLayout, 24],
    1000241002: [e_VkAttachmentDescriptionStencilLayout, 24],
    1000261000: [e_VkPhysicalDeviceHostQueryResetFeatures, 24],
    1000207000: [e_VkPhysicalDeviceTimelineSemaphoreFeatures, 24],
    1000207001: [e_VkPhysicalDeviceTimelineSemaphoreProperties, 24],
    1000207002: [e_VkSemaphoreTypeCreateInfo, 32],
    1000207003: [e_VkTimelineSemaphoreSubmitInfo, 48],
    1000257000: [e_VkPhysicalDeviceBufferDeviceAddressFeatures, 32],
    1000257002: [e_VkBufferOpaqueCaptureAddressCreateInfo, 24],
    1000257003: [e_VkMemoryOpaqueCaptureAddressAllocateInfo, 24],
    53: [e_VkPhysicalDeviceVulkan13Features, 80],
    54: [e_VkPhysicalDeviceVulkan13Properties, 216],
    1000192000: [e_VkPipelineCreationFeedbackCreateInfo, 40],
    1000215000: [e_VkPhysicalDeviceShaderTerminateInvocationFeatures, 24],
    1000276000: [e_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, 24],
    1000295000: [e_VkPhysicalDevicePrivateDataFeatures, 24],
    1000295001: [e_VkDevicePrivateDataCreateInfo, 24],
    1000297000: [e_VkPhysicalDevicePipelineCreationCacheControlFeatures, 24],
    1000314000: [e_VkMemoryBarrier2, 48],
    1000314007: [e_VkPhysicalDeviceSynchronization2Features, 24],
    1000325000: [e_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, 24],
    1000335000: [e_VkPhysicalDeviceImageRobustnessFeatures, 24],
    1000225002: [e_VkPhysicalDeviceSubgroupSizeControlFeatures, 24],
    1000225000: [e_VkPhysicalDeviceSubgroupSizeControlProperties, 32],
    1000225001: [e_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, 24],
    1000138000: [e_VkPhysicalDeviceInlineUniformBlockFeatures, 24],
    1000138001: [e_VkPhysicalDeviceInlineUniformBlockProperties, 40],
    1000138002: [e_VkWriteDescriptorSetInlineUniformBlock, 32],
    1000138003: [e_VkDescriptorPoolInlineUniformBlockCreateInfo, 24],
    1000066000: [e_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, 24],
    1000044002: [e_VkPipelineRenderingCreateInfo, 40],
    1000044003: [e_VkPhysicalDeviceDynamicRenderingFeatures, 24],
    1000044004: [e_VkCommandBufferInheritanceRenderingInfo, 56],
    1000280000: [e_VkPhysicalDeviceShaderIntegerDotProductFeatures, 24],
    1000280001: [e_VkPhysicalDeviceShaderIntegerDotProductProperties, 136],
    1000281001: [e_VkPhysicalDeviceTexelBufferAlignmentProperties, 48],
    1000360000: [e_VkFormatProperties3, 40],
    1000413000: [e_VkPhysicalDeviceMaintenance4Features, 24],
    1000413001: [e_VkPhysicalDeviceMaintenance4Properties, 24],
    55: [e_VkPhysicalDeviceVulkan14Features, 104],
    56: [e_VkPhysicalDeviceVulkan14Properties, 144],
    1000174000: [e_VkDeviceQueueGlobalPriorityCreateInfo, 24],
    1000388000: [e_VkPhysicalDeviceGlobalPriorityQueryFeatures, 24],
    1000388001: [e_VkQueueFamilyGlobalPriorityProperties, 88],
    1000416000: [e_VkPhysicalDeviceShaderSubgroupRotateFeatures, 24],
    1000528000: [e_VkPhysicalDeviceShaderFloatControls2Features, 24],
    1000544000: [e_VkPhysicalDeviceShaderExpectAssumeFeatures, 24],
    1000259000: [e_VkPhysicalDeviceLineRasterizationFeatures, 40],
    1000259002: [e_VkPhysicalDeviceLineRasterizationProperties, 24],
    1000259001: [e_VkPipelineRasterizationLineStateCreateInfo, 32],
    1000525000: [e_VkPhysicalDeviceVertexAttributeDivisorProperties, 24],
    1000190001: [e_VkPipelineVertexInputDivisorStateCreateInfo, 32],
    1000190002: [e_VkPhysicalDeviceVertexAttributeDivisorFeatures, 24],
    1000265000: [e_VkPhysicalDeviceIndexTypeUint8Features, 24],
    1000470000: [e_VkPhysicalDeviceMaintenance5Features, 24],
    1000470001: [e_VkPhysicalDeviceMaintenance5Properties, 40],
    1000470005: [e_VkPipelineCreateFlags2CreateInfo, 24],
    1000470006: [e_VkBufferUsageFlags2CreateInfo, 24],
    1000080000: [e_VkPhysicalDevicePushDescriptorProperties, 24],
    1000232000: [e_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, 24],
    1000232001: [e_VkRenderingAttachmentLocationInfo, 32],
    1000232002: [e_VkRenderingInputAttachmentIndexInfo, 48],
    1000545000: [e_VkPhysicalDeviceMaintenance6Features, 24],
    1000545001: [e_VkPhysicalDeviceMaintenance6Properties, 32],
    1000545002: [e_VkBindMemoryStatus, 24],
    1000466000: [e_VkPhysicalDevicePipelineProtectedAccessFeatures, 24],
    1000068001: [e_VkPhysicalDevicePipelineRobustnessFeatures, 24],
    1000068002: [e_VkPhysicalDevicePipelineRobustnessProperties, 32],
    1000068000: [e_VkPipelineRobustnessCreateInfo, 32],
    1000270000: [e_VkPhysicalDeviceHostImageCopyFeatures, 24],
    1000270001: [e_VkPhysicalDeviceHostImageCopyProperties, 72],
    1000270008: [e_VkSubresourceHostMemcpySize, 24],
    1000270009: [e_VkHostImageCopyDevicePerformanceQuery, 24],
    1000084000: [e_VkPresentRegionsKHR, 32],
    1000269000: [e_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, 24],
    1000010000: [e_VkNativeBufferANDROID, 64],
    1000028000: [e_VkPhysicalDeviceTransformFeedbackFeaturesEXT, 24],
    1000028001: [e_VkPhysicalDeviceTransformFeedbackPropertiesEXT, 64],
    1000028002: [e_VkPipelineRasterizationStateStreamCreateInfoEXT, 24],
    1000102000: [e_VkPhysicalDeviceDepthClipEnableFeaturesEXT, 24],
    1000102001: [e_VkPipelineRasterizationDepthClipStateCreateInfoEXT, 24],
    1000158000: [e_VkDrmFormatModifierPropertiesListEXT, 32],
    1000158002: [e_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, 40],
    1000158003: [e_VkImageDrmFormatModifierListCreateInfoEXT, 32],
    1000158004: [e_VkImageDrmFormatModifierExplicitCreateInfoEXT, 40],
    1000158006: [e_VkDrmFormatModifierPropertiesList2EXT, 32],
    1000190000: [e_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, 24],
    1000218000: { 1000059000: [e_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 3: [e_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 5: [e_VkImportColorBufferGOOGLE, 24], default: [e_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32] },
    1000218001: { 1000059001: [e_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40], 5: [e_VkCreateBlobGOOGLE, 32], default: [e_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40] },
    1000218002: { 38: [e_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 1000109004: [e_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 5: [e_VkImportBufferGOOGLE, 24], default: [e_VkRenderPassFragmentDensityMapCreateInfoEXT, 24] },
    1000044007: [e_VkRenderingFragmentDensityMapAttachmentInfoEXT, 32],
    1000237000: [e_VkPhysicalDeviceMemoryBudgetPropertiesEXT, 272],
    1000254000: [e_VkPhysicalDeviceProvokingVertexFeaturesEXT, 24],
    1000254002: [e_VkPhysicalDeviceProvokingVertexPropertiesEXT, 24],
    1000254001: [e_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, 24],
    1000267000: [e_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, 24],
    1000281000: [e_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, 24],
    1000284000: [e_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, 24],
    1000284001: [e_VkDeviceDeviceMemoryReportCreateInfoEXT, 40],
    1000287000: [e_VkSamplerCustomBorderColorCreateInfoEXT, 40],
    1000287001: [e_VkPhysicalDeviceCustomBorderColorPropertiesEXT, 24],
    1000287002: [e_VkPhysicalDeviceCustomBorderColorFeaturesEXT, 24],
    1000320000: [e_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, 24],
    1000320001: [e_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, 24],
    1000320002: [e_VkGraphicsPipelineLibraryCreateInfoEXT, 24],
    1000330000: [e_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, 24],
    1000338000: [e_VkPhysicalDeviceImageCompressionControlFeaturesEXT, 24],
    1000338001: [e_VkImageCompressionControlEXT, 32],
    1000338004: [e_VkImageCompressionPropertiesEXT, 24],
    1000340000: [e_VkPhysicalDevice4444FormatsFeaturesEXT, 24],
    1000356000: [e_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, 24],
    1000377000: [e_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, 32],
    1000381000: [e_VkPhysicalDeviceColorWriteEnableFeaturesEXT, 24],
    1000381001: [e_VkPipelineColorWriteCreateInfoEXT, 32],
    1000385000: [e_VkImportColorBufferGOOGLE, 24],
    1000385001: [e_VkImportBufferGOOGLE, 24],
    1000385002: [e_VkCreateBlobGOOGLE, 32],
    1000437000: [e_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, 24],
};
function d_pnext(r, root)
{
    if(!r.be32()) return null;
    const stype = r.u32();
    const d = pnext_struct(PNEXT_REQUEST, stype, root);
    if(!d) throw new Error("gfxstream: struct " + stype + " in a chain");
    return d[0](r, root);
}
function e_pnext(w, o, root)
{
    if(!o) { w.be32(0); return; }
    const e = pnext_struct(PNEXT_REPLY, o.sType, root);
    if(!e) throw new Error("gfxstream: struct " + o.sType + " in a reply's chain");
    w.be32(e[1]);
    w.u32(o.sType);
    e[0](w, o, root);
}
function d_vkCreateInstance(r)
{
    const a = {};
    a.pCreateInfo = d_VkInstanceCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pInstance = r.h();
    return a;
}
function e_vkCreateInstance(w, a)
{
    w.h(a.pInstance);
    w.i32(a.ret);
}
function d_vkDestroyInstance(r)
{
    const a = {};
    a.instance = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkEnumeratePhysicalDevices(r)
{
    const a = {};
    a.instance = r.h();
    const p0 = r.ptr();
    a.pPhysicalDeviceCount = null;
    if(p0)
    {
        a.pPhysicalDeviceCount = r.u32();
    }
    const p1 = r.ptr();
    a.pPhysicalDevices = null;
    if(p1)
    {
        a.pPhysicalDevices = [];
        if(a.pPhysicalDeviceCount)
        {
            if(p0)
            {
                a.pPhysicalDevices = new Array(r.count(a.pPhysicalDeviceCount));
                for(let k = 0; k < a.pPhysicalDeviceCount; k++)
                {
                    a.pPhysicalDevices[k] = r.h();
                }
            }
        }
    }
    return a;
}
function e_vkEnumeratePhysicalDevices(w, a)
{
    w.ptr(a.pPhysicalDeviceCount != null);
    if(a.pPhysicalDeviceCount != null)
    {
        w.u32(a.pPhysicalDeviceCount);
    }
    w.ptr(a.pPhysicalDevices != null);
    if(a.pPhysicalDevices != null)
    {
        if(a.pPhysicalDeviceCount)
        {
            w.u64s(a.pPhysicalDevices, a.pPhysicalDeviceCount);
        }
    }
    w.i32(a.ret);
}
function d_vkGetPhysicalDeviceFeatures(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pFeatures = d_VkPhysicalDeviceFeatures(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFeatures(w, a)
{
    e_VkPhysicalDeviceFeatures(w, a.pFeatures, 2147483647);
}
function d_vkGetPhysicalDeviceFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.pFormatProperties = d_VkFormatProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFormatProperties(w, a)
{
    e_VkFormatProperties(w, a.pFormatProperties, 2147483647);
}
function d_vkGetPhysicalDeviceImageFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.type = r.i32();
    a.tiling = r.i32();
    a.usage = r.u32();
    a.flags = r.u32();
    a.pImageFormatProperties = d_VkImageFormatProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceImageFormatProperties(w, a)
{
    e_VkImageFormatProperties(w, a.pImageFormatProperties, 2147483647);
    w.i32(a.ret);
}
function d_vkGetPhysicalDeviceProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pProperties = d_VkPhysicalDeviceProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceProperties(w, a)
{
    e_VkPhysicalDeviceProperties(w, a.pProperties, 2147483647);
}
function d_vkGetPhysicalDeviceQueueFamilyProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pQueueFamilyPropertyCount = null;
    if(p0)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pQueueFamilyProperties = null;
    if(p1)
    {
        a.pQueueFamilyProperties = [];
        a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            a.pQueueFamilyProperties[i] = d_VkQueueFamilyProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceQueueFamilyProperties(w, a)
{
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                e_VkQueueFamilyProperties(w, a.pQueueFamilyProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkGetPhysicalDeviceMemoryProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pMemoryProperties = d_VkPhysicalDeviceMemoryProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceMemoryProperties(w, a)
{
    e_VkPhysicalDeviceMemoryProperties(w, a.pMemoryProperties, 2147483647);
}
function d_vkGetInstanceProcAddr(r)
{
    const a = {};
    a.instance = r.h();
    const l0 = r.be32();
    a.pName = "";
    a.pName = r.str(l0);
    return a;
}
function e_vkGetInstanceProcAddr(w, a)
{
    w.u64(a.ret);
}
function d_vkGetDeviceProcAddr(r)
{
    const a = {};
    a.device = r.h();
    const l0 = r.be32();
    a.pName = "";
    a.pName = r.str(l0);
    return a;
}
function e_vkGetDeviceProcAddr(w, a)
{
    w.u64(a.ret);
}
function d_vkCreateDevice(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pCreateInfo = d_VkDeviceCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pDevice = r.h();
    return a;
}
function e_vkCreateDevice(w, a)
{
    w.h(a.pDevice);
    w.i32(a.ret);
}
function d_vkDestroyDevice(r)
{
    const a = {};
    a.device = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkEnumerateInstanceExtensionProperties(r)
{
    const a = {};
    const p0 = r.ptr();
    a.pLayerName = null;
    if(p0)
    {
        const l1 = r.be32();
        a.pLayerName = "";
        a.pLayerName = r.str(l1);
    }
    const p2 = r.ptr();
    a.pPropertyCount = null;
    if(p2)
    {
        a.pPropertyCount = r.u32();
    }
    const p3 = r.ptr();
    a.pProperties = null;
    if(p3)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkExtensionProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkEnumerateInstanceExtensionProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkExtensionProperties(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkEnumerateDeviceExtensionProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pLayerName = null;
    if(p0)
    {
        const l1 = r.be32();
        a.pLayerName = "";
        a.pLayerName = r.str(l1);
    }
    const p2 = r.ptr();
    a.pPropertyCount = null;
    if(p2)
    {
        a.pPropertyCount = r.u32();
    }
    const p3 = r.ptr();
    a.pProperties = null;
    if(p3)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkExtensionProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkEnumerateDeviceExtensionProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkExtensionProperties(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkEnumerateInstanceLayerProperties(r)
{
    const a = {};
    const p0 = r.ptr();
    a.pPropertyCount = null;
    if(p0)
    {
        a.pPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkLayerProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkEnumerateInstanceLayerProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkLayerProperties(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkEnumerateDeviceLayerProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pPropertyCount = null;
    if(p0)
    {
        a.pPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkLayerProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkEnumerateDeviceLayerProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkLayerProperties(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkGetDeviceQueue(r)
{
    const a = {};
    a.device = r.h();
    a.queueFamilyIndex = r.u32();
    a.queueIndex = r.u32();
    a.pQueue = r.h();
    return a;
}
function e_vkGetDeviceQueue(w, a)
{
    w.h(a.pQueue);
}
function d_vkQueueSubmit(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    a.pSubmits = new Array(r.count(a.submitCount));
    for(let i = 0; i < a.submitCount; i++)
    {
        a.pSubmits[i] = d_VkSubmitInfo(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function e_vkQueueSubmit(w, a)
{
    w.i32(a.ret);
}
function d_vkQueueWaitIdle(r)
{
    const a = {};
    a.queue = r.h();
    return a;
}
function e_vkQueueWaitIdle(w, a)
{
    w.i32(a.ret);
}
function d_vkDeviceWaitIdle(r)
{
    const a = {};
    a.device = r.h();
    return a;
}
function e_vkDeviceWaitIdle(w, a)
{
    w.i32(a.ret);
}
function d_vkAllocateMemory(r)
{
    const a = {};
    a.device = r.h();
    a.pAllocateInfo = d_VkMemoryAllocateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pMemory = r.h();
    return a;
}
function e_vkAllocateMemory(w, a)
{
    w.h(a.pMemory);
    w.i32(a.ret);
}
function d_vkFreeMemory(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkFlushMappedMemoryRanges(r)
{
    const a = {};
    a.device = r.h();
    a.memoryRangeCount = r.u32();
    a.pMemoryRanges = new Array(r.count(a.memoryRangeCount));
    for(let i = 0; i < a.memoryRangeCount; i++)
    {
        a.pMemoryRanges[i] = d_VkMappedMemoryRange(r, 2147483647);
    }
    return a;
}
function e_vkFlushMappedMemoryRanges(w, a)
{
    w.i32(a.ret);
}
function d_vkInvalidateMappedMemoryRanges(r)
{
    const a = {};
    a.device = r.h();
    a.memoryRangeCount = r.u32();
    a.pMemoryRanges = new Array(r.count(a.memoryRangeCount));
    for(let i = 0; i < a.memoryRangeCount; i++)
    {
        a.pMemoryRanges[i] = d_VkMappedMemoryRange(r, 2147483647);
    }
    return a;
}
function e_vkInvalidateMappedMemoryRanges(w, a)
{
    w.i32(a.ret);
}
function d_vkGetDeviceMemoryCommitment(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    a.pCommittedMemoryInBytes = r.u64();
    return a;
}
function e_vkGetDeviceMemoryCommitment(w, a)
{
    w.u64(a.pCommittedMemoryInBytes);
}
function d_vkBindBufferMemory(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    a.memory = r.h();
    a.memoryOffset = r.u64();
    return a;
}
function e_vkBindBufferMemory(w, a)
{
    w.i32(a.ret);
}
function d_vkBindImageMemory(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.memory = r.h();
    a.memoryOffset = r.u64();
    return a;
}
function e_vkBindImageMemory(w, a)
{
    w.i32(a.ret);
}
function d_vkGetBufferMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    a.pMemoryRequirements = d_VkMemoryRequirements(r, 2147483647);
    return a;
}
function e_vkGetBufferMemoryRequirements(w, a)
{
    e_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetImageMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pMemoryRequirements = d_VkMemoryRequirements(r, 2147483647);
    return a;
}
function e_vkGetImageMemoryRequirements(w, a)
{
    e_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetImageSparseMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    const p0 = r.ptr();
    a.pSparseMemoryRequirementCount = null;
    if(p0)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    const p1 = r.ptr();
    a.pSparseMemoryRequirements = null;
    if(p1)
    {
        a.pSparseMemoryRequirements = [];
        a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetImageSparseMemoryRequirements(w, a)
{
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                e_VkSparseImageMemoryRequirements(w, a.pSparseMemoryRequirements?.[i], 2147483647);
            }
        }
    }
}
function d_vkGetPhysicalDeviceSparseImageFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.type = r.i32();
    a.samples = r.i32();
    a.usage = r.u32();
    a.tiling = r.i32();
    const p0 = r.ptr();
    a.pPropertyCount = null;
    if(p0)
    {
        a.pPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkSparseImageFormatProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceSparseImageFormatProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkSparseImageFormatProperties(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkQueueBindSparse(r)
{
    const a = {};
    a.queue = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfo = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfo[i] = d_VkBindSparseInfo(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function e_vkQueueBindSparse(w, a)
{
    w.i32(a.ret);
}
function d_vkCreateFence(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkFenceCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pFence = r.h();
    return a;
}
function e_vkCreateFence(w, a)
{
    w.h(a.pFence);
    w.i32(a.ret);
}
function d_vkDestroyFence(r)
{
    const a = {};
    a.device = r.h();
    a.fence = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkResetFences(r)
{
    const a = {};
    a.device = r.h();
    a.fenceCount = r.u32();
    if(a.fenceCount)
    {
        a.pFences = new Array(r.count(a.fenceCount));
        for(let k = 0; k < a.fenceCount; k++)
        {
            a.pFences[k] = r.h();
        }
    }
    return a;
}
function e_vkResetFences(w, a)
{
    w.i32(a.ret);
}
function d_vkGetFenceStatus(r)
{
    const a = {};
    a.device = r.h();
    a.fence = r.h();
    return a;
}
function e_vkGetFenceStatus(w, a)
{
    w.i32(a.ret);
}
function d_vkWaitForFences(r)
{
    const a = {};
    a.device = r.h();
    a.fenceCount = r.u32();
    if(a.fenceCount)
    {
        a.pFences = new Array(r.count(a.fenceCount));
        for(let k = 0; k < a.fenceCount; k++)
        {
            a.pFences[k] = r.h();
        }
    }
    a.waitAll = r.u32();
    a.timeout = r.u64();
    return a;
}
function e_vkWaitForFences(w, a)
{
    w.i32(a.ret);
}
function d_vkCreateSemaphore(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkSemaphoreCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pSemaphore = r.h();
    return a;
}
function e_vkCreateSemaphore(w, a)
{
    w.h(a.pSemaphore);
    w.i32(a.ret);
}
function d_vkDestroySemaphore(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateEvent(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkEventCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pEvent = r.h();
    return a;
}
function e_vkCreateEvent(w, a)
{
    w.h(a.pEvent);
    w.i32(a.ret);
}
function d_vkDestroyEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkGetEventStatus(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function e_vkGetEventStatus(w, a)
{
    w.i32(a.ret);
}
function d_vkSetEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function e_vkSetEvent(w, a)
{
    w.i32(a.ret);
}
function d_vkResetEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function e_vkResetEvent(w, a)
{
    w.i32(a.ret);
}
function d_vkCreateQueryPool(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkQueryPoolCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pQueryPool = r.h();
    return a;
}
function e_vkCreateQueryPool(w, a)
{
    w.h(a.pQueryPool);
    w.i32(a.ret);
}
function d_vkDestroyQueryPool(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkGetQueryPoolResults(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    a.dataSize = r.be64();
    if((a.dataSize > 0))
    {
        a.pData = r.bytes_of(a.dataSize);
    }
    a.stride = r.u64();
    a.flags = r.u32();
    return a;
}
function e_vkGetQueryPoolResults(w, a)
{
    w.bytes_of(a.pData, a.dataSize);
    w.i32(a.ret);
}
function d_vkCreateBuffer(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkBufferCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pBuffer = r.h();
    return a;
}
function e_vkCreateBuffer(w, a)
{
    w.h(a.pBuffer);
    w.i32(a.ret);
}
function d_vkDestroyBuffer(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateBufferView(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkBufferViewCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pView = r.h();
    return a;
}
function e_vkCreateBufferView(w, a)
{
    w.h(a.pView);
    w.i32(a.ret);
}
function d_vkDestroyBufferView(r)
{
    const a = {};
    a.device = r.h();
    a.bufferView = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateImage(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkImageCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pImage = r.h();
    return a;
}
function e_vkCreateImage(w, a)
{
    w.h(a.pImage);
    w.i32(a.ret);
}
function d_vkDestroyImage(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkGetImageSubresourceLayout(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pSubresource = d_VkImageSubresource(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout(r, 2147483647);
    return a;
}
function e_vkGetImageSubresourceLayout(w, a)
{
    e_VkSubresourceLayout(w, a.pLayout, 2147483647);
}
function d_vkCreateImageView(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkImageViewCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pView = r.h();
    return a;
}
function e_vkCreateImageView(w, a)
{
    w.h(a.pView);
    w.i32(a.ret);
}
function d_vkDestroyImageView(r)
{
    const a = {};
    a.device = r.h();
    a.imageView = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateShaderModule(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkShaderModuleCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pShaderModule = r.h();
    return a;
}
function e_vkCreateShaderModule(w, a)
{
    w.h(a.pShaderModule);
    w.i32(a.ret);
}
function d_vkDestroyShaderModule(r)
{
    const a = {};
    a.device = r.h();
    a.shaderModule = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreatePipelineCache(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkPipelineCacheCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pPipelineCache = r.h();
    return a;
}
function e_vkCreatePipelineCache(w, a)
{
    w.h(a.pPipelineCache);
    w.i32(a.ret);
}
function d_vkDestroyPipelineCache(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkGetPipelineCacheData(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    const p0 = r.ptr();
    a.pDataSize = null;
    if(p0)
    {
        a.pDataSize = r.be64();
    }
    const p1 = r.ptr();
    a.pData = null;
    if(p1)
    {
        if((a.pDataSize > 0))
        {
            a.pData = r.bytes_of(a.pDataSize);
        }
    }
    return a;
}
function e_vkGetPipelineCacheData(w, a)
{
    w.ptr(a.pDataSize != null);
    if(a.pDataSize != null)
    {
        w.be64(a.pDataSize);
    }
    w.ptr(a.pData != null);
    if(a.pData != null)
    {
        w.bytes_of(a.pData, a.pDataSize);
    }
    w.i32(a.ret);
}
function d_vkMergePipelineCaches(r)
{
    const a = {};
    a.device = r.h();
    a.dstCache = r.h();
    a.srcCacheCount = r.u32();
    if(a.srcCacheCount)
    {
        a.pSrcCaches = new Array(r.count(a.srcCacheCount));
        for(let k = 0; k < a.srcCacheCount; k++)
        {
            a.pSrcCaches[k] = r.h();
        }
    }
    return a;
}
function e_vkMergePipelineCaches(w, a)
{
    w.i32(a.ret);
}
function d_vkCreateGraphicsPipelines(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    a.createInfoCount = r.u32();
    a.pCreateInfos = new Array(r.count(a.createInfoCount));
    for(let i = 0; i < a.createInfoCount; i++)
    {
        a.pCreateInfos[i] = d_VkGraphicsPipelineCreateInfo(r, 2147483647);
    }
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    if(a.createInfoCount)
    {
        a.pPipelines = new Array(r.count(a.createInfoCount));
        for(let k = 0; k < a.createInfoCount; k++)
        {
            a.pPipelines[k] = r.h();
        }
    }
    return a;
}
function e_vkCreateGraphicsPipelines(w, a)
{
    if(a.createInfoCount)
    {
        w.u64s(a.pPipelines, a.createInfoCount);
    }
    w.i32(a.ret);
}
function d_vkCreateComputePipelines(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    a.createInfoCount = r.u32();
    a.pCreateInfos = new Array(r.count(a.createInfoCount));
    for(let i = 0; i < a.createInfoCount; i++)
    {
        a.pCreateInfos[i] = d_VkComputePipelineCreateInfo(r, 2147483647);
    }
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    if(a.createInfoCount)
    {
        a.pPipelines = new Array(r.count(a.createInfoCount));
        for(let k = 0; k < a.createInfoCount; k++)
        {
            a.pPipelines[k] = r.h();
        }
    }
    return a;
}
function e_vkCreateComputePipelines(w, a)
{
    if(a.createInfoCount)
    {
        w.u64s(a.pPipelines, a.createInfoCount);
    }
    w.i32(a.ret);
}
function d_vkDestroyPipeline(r)
{
    const a = {};
    a.device = r.h();
    a.pipeline = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreatePipelineLayout(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkPipelineLayoutCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pPipelineLayout = r.h();
    return a;
}
function e_vkCreatePipelineLayout(w, a)
{
    w.h(a.pPipelineLayout);
    w.i32(a.ret);
}
function d_vkDestroyPipelineLayout(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineLayout = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateSampler(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkSamplerCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pSampler = r.h();
    return a;
}
function e_vkCreateSampler(w, a)
{
    w.h(a.pSampler);
    w.i32(a.ret);
}
function d_vkDestroySampler(r)
{
    const a = {};
    a.device = r.h();
    a.sampler = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateDescriptorSetLayout(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorSetLayoutCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pSetLayout = r.h();
    return a;
}
function e_vkCreateDescriptorSetLayout(w, a)
{
    w.h(a.pSetLayout);
    w.i32(a.ret);
}
function d_vkDestroyDescriptorSetLayout(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSetLayout = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorPoolCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pDescriptorPool = r.h();
    return a;
}
function e_vkCreateDescriptorPool(w, a)
{
    w.h(a.pDescriptorPool);
    w.i32(a.ret);
}
function d_vkDestroyDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkResetDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    a.flags = r.u32();
    return a;
}
function e_vkResetDescriptorPool(w, a)
{
    w.i32(a.ret);
}
function d_vkAllocateDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    a.pAllocateInfo = d_VkDescriptorSetAllocateInfo(r, 2147483647);
    if(a.pAllocateInfo.descriptorSetCount)
    {
        a.pDescriptorSets = new Array(r.count(a.pAllocateInfo.descriptorSetCount));
        for(let k = 0; k < a.pAllocateInfo.descriptorSetCount; k++)
        {
            a.pDescriptorSets[k] = r.h();
        }
    }
    return a;
}
function e_vkAllocateDescriptorSets(w, a)
{
    if(a.pAllocateInfo.descriptorSetCount)
    {
        w.u64s(a.pDescriptorSets, a.pAllocateInfo.descriptorSetCount);
    }
    w.i32(a.ret);
}
function d_vkFreeDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    a.descriptorSetCount = r.u32();
    const p0 = r.ptr();
    a.pDescriptorSets = null;
    if(p0)
    {
        a.pDescriptorSets = [];
        if(a.descriptorSetCount)
        {
            a.pDescriptorSets = new Array(r.count(a.descriptorSetCount));
            for(let k = 0; k < a.descriptorSetCount; k++)
            {
                a.pDescriptorSets[k] = r.h();
            }
        }
    }
    return a;
}
function e_vkFreeDescriptorSets(w, a)
{
    w.i32(a.ret);
}
function d_vkUpdateDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorWriteCount = r.u32();
    a.pDescriptorWrites = new Array(r.count(a.descriptorWriteCount));
    for(let i = 0; i < a.descriptorWriteCount; i++)
    {
        a.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r, 2147483647);
    }
    a.descriptorCopyCount = r.u32();
    a.pDescriptorCopies = new Array(r.count(a.descriptorCopyCount));
    for(let i = 0; i < a.descriptorCopyCount; i++)
    {
        a.pDescriptorCopies[i] = d_VkCopyDescriptorSet(r, 2147483647);
    }
    return a;
}
function d_vkCreateFramebuffer(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkFramebufferCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pFramebuffer = r.h();
    return a;
}
function e_vkCreateFramebuffer(w, a)
{
    w.h(a.pFramebuffer);
    w.i32(a.ret);
}
function d_vkDestroyFramebuffer(r)
{
    const a = {};
    a.device = r.h();
    a.framebuffer = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateRenderPass(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkRenderPassCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pRenderPass = r.h();
    return a;
}
function e_vkCreateRenderPass(w, a)
{
    w.h(a.pRenderPass);
    w.i32(a.ret);
}
function d_vkDestroyRenderPass(r)
{
    const a = {};
    a.device = r.h();
    a.renderPass = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkGetRenderAreaGranularity(r)
{
    const a = {};
    a.device = r.h();
    a.renderPass = r.h();
    a.pGranularity = d_VkExtent2D(r, 2147483647);
    return a;
}
function e_vkGetRenderAreaGranularity(w, a)
{
    e_VkExtent2D(w, a.pGranularity, 2147483647);
}
function d_vkCreateCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkCommandPoolCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pCommandPool = r.h();
    return a;
}
function e_vkCreateCommandPool(w, a)
{
    w.h(a.pCommandPool);
    w.i32(a.ret);
}
function d_vkDestroyCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkResetCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.flags = r.u32();
    return a;
}
function e_vkResetCommandPool(w, a)
{
    w.i32(a.ret);
}
function d_vkAllocateCommandBuffers(r)
{
    const a = {};
    a.device = r.h();
    a.pAllocateInfo = d_VkCommandBufferAllocateInfo(r, 2147483647);
    if(a.pAllocateInfo.commandBufferCount)
    {
        a.pCommandBuffers = new Array(r.count(a.pAllocateInfo.commandBufferCount));
        for(let k = 0; k < a.pAllocateInfo.commandBufferCount; k++)
        {
            a.pCommandBuffers[k] = r.h();
        }
    }
    return a;
}
function e_vkAllocateCommandBuffers(w, a)
{
    if(a.pAllocateInfo.commandBufferCount)
    {
        w.u64s(a.pCommandBuffers, a.pAllocateInfo.commandBufferCount);
    }
    w.i32(a.ret);
}
function d_vkFreeCommandBuffers(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.commandBufferCount = r.u32();
    const p0 = r.ptr();
    a.pCommandBuffers = null;
    if(p0)
    {
        a.pCommandBuffers = [];
        if(a.commandBufferCount)
        {
            a.pCommandBuffers = new Array(r.count(a.commandBufferCount));
            for(let k = 0; k < a.commandBufferCount; k++)
            {
                a.pCommandBuffers[k] = r.h();
            }
        }
    }
    return a;
}
function d_vkBeginCommandBuffer(r)
{
    const a = {};
    a.pBeginInfo = d_VkCommandBufferBeginInfo(r, 2147483647);
    return a;
}
function e_vkBeginCommandBuffer(w, a)
{
    w.i32(a.ret);
}
function d_vkEndCommandBuffer(r)
{
    const a = {};
    return a;
}
function e_vkEndCommandBuffer(w, a)
{
    w.i32(a.ret);
}
function d_vkResetCommandBuffer(r)
{
    const a = {};
    a.flags = r.u32();
    return a;
}
function e_vkResetCommandBuffer(w, a)
{
    w.i32(a.ret);
}
function d_vkCmdBindPipeline(r)
{
    const a = {};
    a.pipelineBindPoint = r.i32();
    a.pipeline = r.h();
    return a;
}
function d_vkCmdSetViewport(r)
{
    const a = {};
    a.firstViewport = r.u32();
    a.viewportCount = r.u32();
    a.pViewports = new Array(r.count(a.viewportCount));
    for(let i = 0; i < a.viewportCount; i++)
    {
        a.pViewports[i] = d_VkViewport(r, 2147483647);
    }
    return a;
}
function d_vkCmdSetScissor(r)
{
    const a = {};
    a.firstScissor = r.u32();
    a.scissorCount = r.u32();
    a.pScissors = new Array(r.count(a.scissorCount));
    for(let i = 0; i < a.scissorCount; i++)
    {
        a.pScissors[i] = d_VkRect2D(r, 2147483647);
    }
    return a;
}
function d_vkCmdSetLineWidth(r)
{
    const a = {};
    a.lineWidth = r.f32();
    return a;
}
function d_vkCmdSetDepthBias(r)
{
    const a = {};
    a.depthBiasConstantFactor = r.f32();
    a.depthBiasClamp = r.f32();
    a.depthBiasSlopeFactor = r.f32();
    return a;
}
function d_vkCmdSetBlendConstants(r)
{
    const a = {};
    a.blendConstants = r.f32s(4);
    return a;
}
function d_vkCmdSetDepthBounds(r)
{
    const a = {};
    a.minDepthBounds = r.f32();
    a.maxDepthBounds = r.f32();
    return a;
}
function d_vkCmdSetStencilCompareMask(r)
{
    const a = {};
    a.faceMask = r.u32();
    a.compareMask = r.u32();
    return a;
}
function d_vkCmdSetStencilWriteMask(r)
{
    const a = {};
    a.faceMask = r.u32();
    a.writeMask = r.u32();
    return a;
}
function d_vkCmdSetStencilReference(r)
{
    const a = {};
    a.faceMask = r.u32();
    a.reference = r.u32();
    return a;
}
function d_vkCmdBindDescriptorSets(r)
{
    const a = {};
    a.pipelineBindPoint = r.i32();
    a.layout = r.h();
    a.firstSet = r.u32();
    a.descriptorSetCount = r.u32();
    if(a.descriptorSetCount)
    {
        a.pDescriptorSets = new Array(r.count(a.descriptorSetCount));
        for(let k = 0; k < a.descriptorSetCount; k++)
        {
            a.pDescriptorSets[k] = r.h();
        }
    }
    a.dynamicOffsetCount = r.u32();
    if((a.dynamicOffsetCount > 0))
    {
        a.pDynamicOffsets = r.u32s(a.dynamicOffsetCount);
    }
    return a;
}
function d_vkCmdBindIndexBuffer(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.indexType = r.i32();
    return a;
}
function d_vkCmdBindVertexBuffers(r)
{
    const a = {};
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    if(a.bindingCount)
    {
        a.pBuffers = new Array(r.count(a.bindingCount));
        for(let k = 0; k < a.bindingCount; k++)
        {
            a.pBuffers[k] = r.h();
        }
    }
    if((a.bindingCount > 0))
    {
        a.pOffsets = r.u64s(a.bindingCount);
    }
    return a;
}
function d_vkCmdDraw(r)
{
    const a = {};
    a.vertexCount = r.u32();
    a.instanceCount = r.u32();
    a.firstVertex = r.u32();
    a.firstInstance = r.u32();
    return a;
}
function d_vkCmdDrawIndexed(r)
{
    const a = {};
    a.indexCount = r.u32();
    a.instanceCount = r.u32();
    a.firstIndex = r.u32();
    a.vertexOffset = r.i32();
    a.firstInstance = r.u32();
    return a;
}
function d_vkCmdDrawIndirect(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.drawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawIndexedIndirect(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.drawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDispatch(r)
{
    const a = {};
    a.groupCountX = r.u32();
    a.groupCountY = r.u32();
    a.groupCountZ = r.u32();
    return a;
}
function d_vkCmdDispatchIndirect(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    return a;
}
function d_vkCmdCopyBuffer(r)
{
    const a = {};
    a.srcBuffer = r.h();
    a.dstBuffer = r.h();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkBufferCopy(r, 2147483647);
    }
    return a;
}
function d_vkCmdCopyImage(r)
{
    const a = {};
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkImageCopy(r, 2147483647);
    }
    return a;
}
function d_vkCmdBlitImage(r)
{
    const a = {};
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkImageBlit(r, 2147483647);
    }
    a.filter = r.i32();
    return a;
}
function d_vkCmdCopyBufferToImage(r)
{
    const a = {};
    a.srcBuffer = r.h();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkBufferImageCopy(r, 2147483647);
    }
    return a;
}
function d_vkCmdCopyImageToBuffer(r)
{
    const a = {};
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstBuffer = r.h();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkBufferImageCopy(r, 2147483647);
    }
    return a;
}
function d_vkCmdUpdateBuffer(r)
{
    const a = {};
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.dataSize = r.u64();
    if((a.dataSize > 0))
    {
        a.pData = r.bytes_of(a.dataSize);
    }
    return a;
}
function d_vkCmdFillBuffer(r)
{
    const a = {};
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.size = r.u64();
    a.data = r.u32();
    return a;
}
function d_vkCmdClearColorImage(r)
{
    const a = {};
    a.image = r.h();
    a.imageLayout = r.i32();
    a.pColor = d_VkClearColorValue(r, 2147483647);
    a.rangeCount = r.u32();
    a.pRanges = new Array(r.count(a.rangeCount));
    for(let i = 0; i < a.rangeCount; i++)
    {
        a.pRanges[i] = d_VkImageSubresourceRange(r, 2147483647);
    }
    return a;
}
function d_vkCmdClearDepthStencilImage(r)
{
    const a = {};
    a.image = r.h();
    a.imageLayout = r.i32();
    a.pDepthStencil = d_VkClearDepthStencilValue(r, 2147483647);
    a.rangeCount = r.u32();
    a.pRanges = new Array(r.count(a.rangeCount));
    for(let i = 0; i < a.rangeCount; i++)
    {
        a.pRanges[i] = d_VkImageSubresourceRange(r, 2147483647);
    }
    return a;
}
function d_vkCmdClearAttachments(r)
{
    const a = {};
    a.attachmentCount = r.u32();
    a.pAttachments = new Array(r.count(a.attachmentCount));
    for(let i = 0; i < a.attachmentCount; i++)
    {
        a.pAttachments[i] = d_VkClearAttachment(r, 2147483647);
    }
    a.rectCount = r.u32();
    a.pRects = new Array(r.count(a.rectCount));
    for(let i = 0; i < a.rectCount; i++)
    {
        a.pRects[i] = d_VkClearRect(r, 2147483647);
    }
    return a;
}
function d_vkCmdResolveImage(r)
{
    const a = {};
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    a.pRegions = new Array(r.count(a.regionCount));
    for(let i = 0; i < a.regionCount; i++)
    {
        a.pRegions[i] = d_VkImageResolve(r, 2147483647);
    }
    return a;
}
function d_vkCmdSetEvent(r)
{
    const a = {};
    a.event = r.h();
    a.stageMask = r.u32();
    return a;
}
function d_vkCmdResetEvent(r)
{
    const a = {};
    a.event = r.h();
    a.stageMask = r.u32();
    return a;
}
function d_vkCmdWaitEvents(r)
{
    const a = {};
    a.eventCount = r.u32();
    if(a.eventCount)
    {
        a.pEvents = new Array(r.count(a.eventCount));
        for(let k = 0; k < a.eventCount; k++)
        {
            a.pEvents[k] = r.h();
        }
    }
    a.srcStageMask = r.u32();
    a.dstStageMask = r.u32();
    a.memoryBarrierCount = r.u32();
    a.pMemoryBarriers = new Array(r.count(a.memoryBarrierCount));
    for(let i = 0; i < a.memoryBarrierCount; i++)
    {
        a.pMemoryBarriers[i] = d_VkMemoryBarrier(r, 2147483647);
    }
    a.bufferMemoryBarrierCount = r.u32();
    a.pBufferMemoryBarriers = new Array(r.count(a.bufferMemoryBarrierCount));
    for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
    {
        a.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier(r, 2147483647);
    }
    a.imageMemoryBarrierCount = r.u32();
    a.pImageMemoryBarriers = new Array(r.count(a.imageMemoryBarrierCount));
    for(let i = 0; i < a.imageMemoryBarrierCount; i++)
    {
        a.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier(r, 2147483647);
    }
    return a;
}
function d_vkCmdPipelineBarrier(r)
{
    const a = {};
    a.srcStageMask = r.u32();
    a.dstStageMask = r.u32();
    a.dependencyFlags = r.u32();
    a.memoryBarrierCount = r.u32();
    a.pMemoryBarriers = new Array(r.count(a.memoryBarrierCount));
    for(let i = 0; i < a.memoryBarrierCount; i++)
    {
        a.pMemoryBarriers[i] = d_VkMemoryBarrier(r, 2147483647);
    }
    a.bufferMemoryBarrierCount = r.u32();
    a.pBufferMemoryBarriers = new Array(r.count(a.bufferMemoryBarrierCount));
    for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
    {
        a.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier(r, 2147483647);
    }
    a.imageMemoryBarrierCount = r.u32();
    a.pImageMemoryBarriers = new Array(r.count(a.imageMemoryBarrierCount));
    for(let i = 0; i < a.imageMemoryBarrierCount; i++)
    {
        a.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier(r, 2147483647);
    }
    return a;
}
function d_vkCmdBeginQuery(r)
{
    const a = {};
    a.queryPool = r.h();
    a.query = r.u32();
    a.flags = r.u32();
    return a;
}
function d_vkCmdEndQuery(r)
{
    const a = {};
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkCmdResetQueryPool(r)
{
    const a = {};
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    return a;
}
function d_vkCmdWriteTimestamp(r)
{
    const a = {};
    a.pipelineStage = r.i32();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkCmdCopyQueryPoolResults(r)
{
    const a = {};
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.stride = r.u64();
    a.flags = r.u32();
    return a;
}
function d_vkCmdPushConstants(r)
{
    const a = {};
    a.layout = r.h();
    a.stageFlags = r.u32();
    a.offset = r.u32();
    a.size = r.u32();
    if((a.size > 0))
    {
        a.pValues = r.bytes_of(a.size);
    }
    return a;
}
function d_vkCmdBeginRenderPass(r)
{
    const a = {};
    a.pRenderPassBegin = d_VkRenderPassBeginInfo(r, 2147483647);
    a.contents = r.i32();
    return a;
}
function d_vkCmdNextSubpass(r)
{
    const a = {};
    a.contents = r.i32();
    return a;
}
function d_vkCmdEndRenderPass(r)
{
    const a = {};
    return a;
}
function d_vkCmdExecuteCommands(r)
{
    const a = {};
    a.commandBufferCount = r.u32();
    if(a.commandBufferCount)
    {
        a.pCommandBuffers = new Array(r.count(a.commandBufferCount));
        for(let k = 0; k < a.commandBufferCount; k++)
        {
            a.pCommandBuffers[k] = r.h();
        }
    }
    return a;
}
function d_vkEnumerateInstanceVersion(r)
{
    const a = {};
    a.pApiVersion = r.u32();
    return a;
}
function e_vkEnumerateInstanceVersion(w, a)
{
    w.u32(a.pApiVersion);
    w.i32(a.ret);
}
function d_vkBindBufferMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfos = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfos[i] = d_VkBindBufferMemoryInfo(r, 2147483647);
    }
    return a;
}
function e_vkBindBufferMemory2(w, a)
{
    w.i32(a.ret);
}
function d_vkBindImageMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfos = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfos[i] = d_VkBindImageMemoryInfo(r, 2147483647);
    }
    return a;
}
function e_vkBindImageMemory2(w, a)
{
    w.i32(a.ret);
}
function d_vkGetDeviceGroupPeerMemoryFeatures(r)
{
    const a = {};
    a.device = r.h();
    a.heapIndex = r.u32();
    a.localDeviceIndex = r.u32();
    a.remoteDeviceIndex = r.u32();
    a.pPeerMemoryFeatures = r.u32();
    return a;
}
function e_vkGetDeviceGroupPeerMemoryFeatures(w, a)
{
    w.u32(a.pPeerMemoryFeatures);
}
function d_vkCmdSetDeviceMask(r)
{
    const a = {};
    a.deviceMask = r.u32();
    return a;
}
function d_vkCmdDispatchBase(r)
{
    const a = {};
    a.baseGroupX = r.u32();
    a.baseGroupY = r.u32();
    a.baseGroupZ = r.u32();
    a.groupCountX = r.u32();
    a.groupCountY = r.u32();
    a.groupCountZ = r.u32();
    return a;
}
function d_vkEnumeratePhysicalDeviceGroups(r)
{
    const a = {};
    a.instance = r.h();
    const p0 = r.ptr();
    a.pPhysicalDeviceGroupCount = null;
    if(p0)
    {
        a.pPhysicalDeviceGroupCount = r.u32();
    }
    const p1 = r.ptr();
    a.pPhysicalDeviceGroupProperties = null;
    if(p1)
    {
        a.pPhysicalDeviceGroupProperties = [];
        a.pPhysicalDeviceGroupProperties = new Array(r.count(a.pPhysicalDeviceGroupCount));
        for(let i = 0; i < a.pPhysicalDeviceGroupCount; i++)
        {
            a.pPhysicalDeviceGroupProperties[i] = d_VkPhysicalDeviceGroupProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkEnumeratePhysicalDeviceGroups(w, a)
{
    w.ptr(a.pPhysicalDeviceGroupCount != null);
    if(a.pPhysicalDeviceGroupCount != null)
    {
        w.u32(a.pPhysicalDeviceGroupCount);
    }
    w.ptr(a.pPhysicalDeviceGroupProperties != null);
    if(a.pPhysicalDeviceGroupProperties != null)
    {
        if(a.pPhysicalDeviceGroupCount != null)
        {
            for(let i = 0; i < a.pPhysicalDeviceGroupCount; i++)
            {
                e_VkPhysicalDeviceGroupProperties(w, a.pPhysicalDeviceGroupProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkGetImageMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkImageMemoryRequirementsInfo2(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetImageMemoryRequirements2(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetBufferMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferMemoryRequirementsInfo2(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetBufferMemoryRequirements2(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetImageSparseMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkImageSparseMemoryRequirementsInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pSparseMemoryRequirementCount = null;
    if(p0)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    const p1 = r.ptr();
    a.pSparseMemoryRequirements = null;
    if(p1)
    {
        a.pSparseMemoryRequirements = [];
        a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetImageSparseMemoryRequirements2(w, a)
{
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                e_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
            }
        }
    }
}
function d_vkGetPhysicalDeviceFeatures2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pFeatures = d_VkPhysicalDeviceFeatures2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFeatures2(w, a)
{
    e_VkPhysicalDeviceFeatures2(w, a.pFeatures, 2147483647);
}
function d_vkGetPhysicalDeviceProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pProperties = d_VkPhysicalDeviceProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceProperties2(w, a)
{
    e_VkPhysicalDeviceProperties2(w, a.pProperties, 2147483647);
}
function d_vkGetPhysicalDeviceFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.pFormatProperties = d_VkFormatProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFormatProperties2(w, a)
{
    e_VkFormatProperties2(w, a.pFormatProperties, 2147483647);
}
function d_vkGetPhysicalDeviceImageFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pImageFormatInfo = d_VkPhysicalDeviceImageFormatInfo2(r, 2147483647);
    a.pImageFormatProperties = d_VkImageFormatProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceImageFormatProperties2(w, a)
{
    e_VkImageFormatProperties2(w, a.pImageFormatProperties, 2147483647);
    w.i32(a.ret);
}
function d_vkGetPhysicalDeviceQueueFamilyProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pQueueFamilyPropertyCount = null;
    if(p0)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pQueueFamilyProperties = null;
    if(p1)
    {
        a.pQueueFamilyProperties = [];
        a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            a.pQueueFamilyProperties[i] = d_VkQueueFamilyProperties2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceQueueFamilyProperties2(w, a)
{
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                e_VkQueueFamilyProperties2(w, a.pQueueFamilyProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkGetPhysicalDeviceMemoryProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pMemoryProperties = d_VkPhysicalDeviceMemoryProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceMemoryProperties2(w, a)
{
    e_VkPhysicalDeviceMemoryProperties2(w, a.pMemoryProperties, 2147483647);
}
function d_vkGetPhysicalDeviceSparseImageFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pFormatInfo = d_VkPhysicalDeviceSparseImageFormatInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pPropertyCount = null;
    if(p0)
    {
        a.pPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkSparseImageFormatProperties2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceSparseImageFormatProperties2(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkSparseImageFormatProperties2(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkTrimCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkGetDeviceQueue2(r)
{
    const a = {};
    a.device = r.h();
    a.pQueueInfo = d_VkDeviceQueueInfo2(r, 2147483647);
    a.pQueue = r.h();
    return a;
}
function e_vkGetDeviceQueue2(w, a)
{
    w.h(a.pQueue);
}
function d_vkCreateSamplerYcbcrConversion(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkSamplerYcbcrConversionCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pYcbcrConversion = r.h();
    return a;
}
function e_vkCreateSamplerYcbcrConversion(w, a)
{
    w.h(a.pYcbcrConversion);
    w.i32(a.ret);
}
function d_vkDestroySamplerYcbcrConversion(r)
{
    const a = {};
    a.device = r.h();
    a.ycbcrConversion = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkCreateDescriptorUpdateTemplate(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorUpdateTemplateCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pDescriptorUpdateTemplate = r.h();
    return a;
}
function e_vkCreateDescriptorUpdateTemplate(w, a)
{
    w.h(a.pDescriptorUpdateTemplate);
    w.i32(a.ret);
}
function d_vkDestroyDescriptorUpdateTemplate(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorUpdateTemplate = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkUpdateDescriptorSetWithTemplate(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSet = r.h();
    a.descriptorUpdateTemplate = r.h();
    const p0 = r.ptr();
    a.pData = null;
    if(p0)
    {
        a.pData = r.void();
    }
    return a;
}
function d_vkGetPhysicalDeviceExternalBufferProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalBufferInfo = d_VkPhysicalDeviceExternalBufferInfo(r, 2147483647);
    a.pExternalBufferProperties = d_VkExternalBufferProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalBufferProperties(w, a)
{
    e_VkExternalBufferProperties(w, a.pExternalBufferProperties, 2147483647);
}
function d_vkGetPhysicalDeviceExternalFenceProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalFenceInfo = d_VkPhysicalDeviceExternalFenceInfo(r, 2147483647);
    a.pExternalFenceProperties = d_VkExternalFenceProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalFenceProperties(w, a)
{
    e_VkExternalFenceProperties(w, a.pExternalFenceProperties, 2147483647);
}
function d_vkGetPhysicalDeviceExternalSemaphoreProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalSemaphoreInfo = d_VkPhysicalDeviceExternalSemaphoreInfo(r, 2147483647);
    a.pExternalSemaphoreProperties = d_VkExternalSemaphoreProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalSemaphoreProperties(w, a)
{
    e_VkExternalSemaphoreProperties(w, a.pExternalSemaphoreProperties, 2147483647);
}
function d_vkGetDescriptorSetLayoutSupport(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorSetLayoutCreateInfo(r, 2147483647);
    a.pSupport = d_VkDescriptorSetLayoutSupport(r, 2147483647);
    return a;
}
function e_vkGetDescriptorSetLayoutSupport(w, a)
{
    e_VkDescriptorSetLayoutSupport(w, a.pSupport, 2147483647);
}
function d_vkCmdDrawIndirectCount(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.countBuffer = r.h();
    a.countBufferOffset = r.u64();
    a.maxDrawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawIndexedIndirectCount(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.countBuffer = r.h();
    a.countBufferOffset = r.u64();
    a.maxDrawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCreateRenderPass2(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkRenderPassCreateInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pRenderPass = r.h();
    return a;
}
function e_vkCreateRenderPass2(w, a)
{
    w.h(a.pRenderPass);
    w.i32(a.ret);
}
function d_vkCmdBeginRenderPass2(r)
{
    const a = {};
    a.pRenderPassBegin = d_VkRenderPassBeginInfo(r, 2147483647);
    a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r, 2147483647);
    return a;
}
function d_vkCmdNextSubpass2(r)
{
    const a = {};
    a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r, 2147483647);
    a.pSubpassEndInfo = d_VkSubpassEndInfo(r, 2147483647);
    return a;
}
function d_vkCmdEndRenderPass2(r)
{
    const a = {};
    a.pSubpassEndInfo = d_VkSubpassEndInfo(r, 2147483647);
    return a;
}
function d_vkResetQueryPool(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    return a;
}
function d_vkGetSemaphoreCounterValue(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    a.pValue = r.u64();
    return a;
}
function e_vkGetSemaphoreCounterValue(w, a)
{
    w.u64(a.pValue);
    w.i32(a.ret);
}
function d_vkWaitSemaphores(r)
{
    const a = {};
    a.device = r.h();
    a.pWaitInfo = d_VkSemaphoreWaitInfo(r, 2147483647);
    a.timeout = r.u64();
    return a;
}
function e_vkWaitSemaphores(w, a)
{
    w.i32(a.ret);
}
function d_vkSignalSemaphore(r)
{
    const a = {};
    a.device = r.h();
    a.pSignalInfo = d_VkSemaphoreSignalInfo(r, 2147483647);
    return a;
}
function e_vkSignalSemaphore(w, a)
{
    w.i32(a.ret);
}
function d_vkGetBufferDeviceAddress(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferDeviceAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetBufferDeviceAddress(w, a)
{
    w.u64(a.ret);
}
function d_vkGetBufferOpaqueCaptureAddress(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferDeviceAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetBufferOpaqueCaptureAddress(w, a)
{
    w.u64(a.ret);
}
function d_vkGetDeviceMemoryOpaqueCaptureAddress(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceMemoryOpaqueCaptureAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetDeviceMemoryOpaqueCaptureAddress(w, a)
{
    w.u64(a.ret);
}
function d_vkGetPhysicalDeviceToolProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pToolCount = null;
    if(p0)
    {
        a.pToolCount = r.u32();
    }
    const p1 = r.ptr();
    a.pToolProperties = null;
    if(p1)
    {
        a.pToolProperties = [];
        a.pToolProperties = new Array(r.count(a.pToolCount));
        for(let i = 0; i < a.pToolCount; i++)
        {
            a.pToolProperties[i] = d_VkPhysicalDeviceToolProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceToolProperties(w, a)
{
    w.ptr(a.pToolCount != null);
    if(a.pToolCount != null)
    {
        w.u32(a.pToolCount);
    }
    w.ptr(a.pToolProperties != null);
    if(a.pToolProperties != null)
    {
        if(a.pToolCount != null)
        {
            for(let i = 0; i < a.pToolCount; i++)
            {
                e_VkPhysicalDeviceToolProperties(w, a.pToolProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkCreatePrivateDataSlot(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkPrivateDataSlotCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pPrivateDataSlot = r.h();
    return a;
}
function e_vkCreatePrivateDataSlot(w, a)
{
    w.h(a.pPrivateDataSlot);
    w.i32(a.ret);
}
function d_vkDestroyPrivateDataSlot(r)
{
    const a = {};
    a.device = r.h();
    a.privateDataSlot = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkSetPrivateData(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.data = r.u64();
    return a;
}
function e_vkSetPrivateData(w, a)
{
    w.i32(a.ret);
}
function d_vkGetPrivateData(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.pData = r.u64();
    return a;
}
function e_vkGetPrivateData(w, a)
{
    w.u64(a.pData);
}
function d_vkCmdSetEvent2(r)
{
    const a = {};
    a.event = r.h();
    a.pDependencyInfo = d_VkDependencyInfo(r, 2147483647);
    return a;
}
function d_vkCmdResetEvent2(r)
{
    const a = {};
    a.event = r.h();
    a.stageMask = r.u64();
    return a;
}
function d_vkCmdWaitEvents2(r)
{
    const a = {};
    a.eventCount = r.u32();
    if(a.eventCount)
    {
        a.pEvents = new Array(r.count(a.eventCount));
        for(let k = 0; k < a.eventCount; k++)
        {
            a.pEvents[k] = r.h();
        }
    }
    a.pDependencyInfos = new Array(r.count(a.eventCount));
    for(let i = 0; i < a.eventCount; i++)
    {
        a.pDependencyInfos[i] = d_VkDependencyInfo(r, 2147483647);
    }
    return a;
}
function d_vkCmdPipelineBarrier2(r)
{
    const a = {};
    a.pDependencyInfo = d_VkDependencyInfo(r, 2147483647);
    return a;
}
function d_vkCmdWriteTimestamp2(r)
{
    const a = {};
    a.stage = r.u64();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkQueueSubmit2(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    a.pSubmits = new Array(r.count(a.submitCount));
    for(let i = 0; i < a.submitCount; i++)
    {
        a.pSubmits[i] = d_VkSubmitInfo2(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function e_vkQueueSubmit2(w, a)
{
    w.i32(a.ret);
}
function d_vkCmdCopyBuffer2(r)
{
    const a = {};
    a.pCopyBufferInfo = d_VkCopyBufferInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyImage2(r)
{
    const a = {};
    a.pCopyImageInfo = d_VkCopyImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyBufferToImage2(r)
{
    const a = {};
    a.pCopyBufferToImageInfo = d_VkCopyBufferToImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyImageToBuffer2(r)
{
    const a = {};
    a.pCopyImageToBufferInfo = d_VkCopyImageToBufferInfo2(r, 2147483647);
    return a;
}
function d_vkCmdBlitImage2(r)
{
    const a = {};
    a.pBlitImageInfo = d_VkBlitImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdResolveImage2(r)
{
    const a = {};
    a.pResolveImageInfo = d_VkResolveImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdBeginRendering(r)
{
    const a = {};
    a.pRenderingInfo = d_VkRenderingInfo(r, 2147483647);
    return a;
}
function d_vkCmdEndRendering(r)
{
    const a = {};
    return a;
}
function d_vkCmdSetCullMode(r)
{
    const a = {};
    a.cullMode = r.u32();
    return a;
}
function d_vkCmdSetFrontFace(r)
{
    const a = {};
    a.frontFace = r.i32();
    return a;
}
function d_vkCmdSetPrimitiveTopology(r)
{
    const a = {};
    a.primitiveTopology = r.i32();
    return a;
}
function d_vkCmdSetViewportWithCount(r)
{
    const a = {};
    a.viewportCount = r.u32();
    a.pViewports = new Array(r.count(a.viewportCount));
    for(let i = 0; i < a.viewportCount; i++)
    {
        a.pViewports[i] = d_VkViewport(r, 2147483647);
    }
    return a;
}
function d_vkCmdSetScissorWithCount(r)
{
    const a = {};
    a.scissorCount = r.u32();
    a.pScissors = new Array(r.count(a.scissorCount));
    for(let i = 0; i < a.scissorCount; i++)
    {
        a.pScissors[i] = d_VkRect2D(r, 2147483647);
    }
    return a;
}
function d_vkCmdBindVertexBuffers2(r)
{
    const a = {};
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    const p0 = r.ptr();
    a.pBuffers = null;
    if(p0)
    {
        a.pBuffers = [];
        if(a.bindingCount)
        {
            a.pBuffers = new Array(r.count(a.bindingCount));
            for(let k = 0; k < a.bindingCount; k++)
            {
                a.pBuffers[k] = r.h();
            }
        }
    }
    if((a.bindingCount > 0))
    {
        a.pOffsets = r.u64s(a.bindingCount);
    }
    const p1 = r.ptr();
    a.pSizes = null;
    if(p1)
    {
        if((a.bindingCount > 0))
        {
            a.pSizes = r.u64s(a.bindingCount);
        }
    }
    const p2 = r.ptr();
    a.pStrides = null;
    if(p2)
    {
        if((a.bindingCount > 0))
        {
            a.pStrides = r.u64s(a.bindingCount);
        }
    }
    return a;
}
function d_vkCmdSetDepthTestEnable(r)
{
    const a = {};
    a.depthTestEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthWriteEnable(r)
{
    const a = {};
    a.depthWriteEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthCompareOp(r)
{
    const a = {};
    a.depthCompareOp = r.i32();
    return a;
}
function d_vkCmdSetDepthBoundsTestEnable(r)
{
    const a = {};
    a.depthBoundsTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilTestEnable(r)
{
    const a = {};
    a.stencilTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilOp(r)
{
    const a = {};
    a.faceMask = r.u32();
    a.failOp = r.i32();
    a.passOp = r.i32();
    a.depthFailOp = r.i32();
    a.compareOp = r.i32();
    return a;
}
function d_vkCmdSetRasterizerDiscardEnable(r)
{
    const a = {};
    a.rasterizerDiscardEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthBiasEnable(r)
{
    const a = {};
    a.depthBiasEnable = r.u32();
    return a;
}
function d_vkCmdSetPrimitiveRestartEnable(r)
{
    const a = {};
    a.primitiveRestartEnable = r.u32();
    return a;
}
function d_vkGetDeviceBufferMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceBufferMemoryRequirements(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetDeviceBufferMemoryRequirements(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetDeviceImageMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageMemoryRequirements(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetDeviceImageMemoryRequirements(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetDeviceImageSparseMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageMemoryRequirements(r, 2147483647);
    const p0 = r.ptr();
    a.pSparseMemoryRequirementCount = null;
    if(p0)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    const p1 = r.ptr();
    a.pSparseMemoryRequirements = null;
    if(p1)
    {
        a.pSparseMemoryRequirements = [];
        a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetDeviceImageSparseMemoryRequirements(w, a)
{
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                e_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
            }
        }
    }
}
function d_vkCmdSetLineStipple(r)
{
    const a = {};
    a.lineStippleFactor = r.u32();
    a.lineStipplePattern = r.u16();
    return a;
}
function d_vkMapMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.pMemoryMapInfo = d_VkMemoryMapInfo(r, 2147483647);
    const p0 = r.ptr();
    a.ppData = null;
    if(p0)
    {
        a.ppData = r.void();
    }
    return a;
}
function e_vkMapMemory2(w, a)
{
    w.ptr(a.ppData != null);
    if(a.ppData != null)
    {
        w.void(a.ppData);
    }
    w.i32(a.ret);
}
function d_vkUnmapMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.pMemoryUnmapInfo = d_VkMemoryUnmapInfo(r, 2147483647);
    return a;
}
function e_vkUnmapMemory2(w, a)
{
    w.i32(a.ret);
}
function d_vkCmdBindIndexBuffer2(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.size = r.u64();
    a.indexType = r.i32();
    return a;
}
function d_vkGetRenderingAreaGranularity(r)
{
    const a = {};
    a.device = r.h();
    a.pRenderingAreaInfo = d_VkRenderingAreaInfo(r, 2147483647);
    a.pGranularity = d_VkExtent2D(r, 2147483647);
    return a;
}
function e_vkGetRenderingAreaGranularity(w, a)
{
    e_VkExtent2D(w, a.pGranularity, 2147483647);
}
function d_vkGetDeviceImageSubresourceLayout(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageSubresourceInfo(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout2(r, 2147483647);
    return a;
}
function e_vkGetDeviceImageSubresourceLayout(w, a)
{
    e_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function d_vkGetImageSubresourceLayout2(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pSubresource = d_VkImageSubresource2(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout2(r, 2147483647);
    return a;
}
function e_vkGetImageSubresourceLayout2(w, a)
{
    e_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function d_vkCmdPushDescriptorSet(r)
{
    const a = {};
    a.pipelineBindPoint = r.i32();
    a.layout = r.h();
    a.set = r.u32();
    a.descriptorWriteCount = r.u32();
    a.pDescriptorWrites = new Array(r.count(a.descriptorWriteCount));
    for(let i = 0; i < a.descriptorWriteCount; i++)
    {
        a.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r, 2147483647);
    }
    return a;
}
function d_vkCmdPushDescriptorSetWithTemplate(r)
{
    const a = {};
    a.descriptorUpdateTemplate = r.h();
    a.layout = r.h();
    a.set = r.u32();
    const p0 = r.ptr();
    a.pData = null;
    if(p0)
    {
        a.pData = r.void();
    }
    return a;
}
function d_vkCmdSetRenderingAttachmentLocations(r)
{
    const a = {};
    a.pLocationInfo = d_VkRenderingAttachmentLocationInfo(r, 2147483647);
    return a;
}
function d_vkCmdSetRenderingInputAttachmentIndices(r)
{
    const a = {};
    a.pInputAttachmentIndexInfo = d_VkRenderingInputAttachmentIndexInfo(r, 2147483647);
    return a;
}
function d_vkCmdBindDescriptorSets2(r)
{
    const a = {};
    a.pBindDescriptorSetsInfo = d_VkBindDescriptorSetsInfo(r, 2147483647);
    return a;
}
function d_vkCmdPushConstants2(r)
{
    const a = {};
    a.pPushConstantsInfo = d_VkPushConstantsInfo(r, 2147483647);
    return a;
}
function d_vkCmdPushDescriptorSet2(r)
{
    const a = {};
    a.pPushDescriptorSetInfo = d_VkPushDescriptorSetInfo(r, 2147483647);
    return a;
}
function d_vkCmdPushDescriptorSetWithTemplate2(r)
{
    const a = {};
    a.pPushDescriptorSetWithTemplateInfo = d_VkPushDescriptorSetWithTemplateInfo(r, 2147483647);
    return a;
}
function d_vkCopyMemoryToImage(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyMemoryToImageInfo = d_VkCopyMemoryToImageInfo(r, 2147483647);
    return a;
}
function e_vkCopyMemoryToImage(w, a)
{
    w.i32(a.ret);
}
function d_vkCopyImageToMemory(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyImageToMemoryInfo = d_VkCopyImageToMemoryInfo(r, 2147483647);
    return a;
}
function e_vkCopyImageToMemory(w, a)
{
    w.i32(a.ret);
}
function d_vkCopyImageToImage(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyImageToImageInfo = d_VkCopyImageToImageInfo(r, 2147483647);
    return a;
}
function e_vkCopyImageToImage(w, a)
{
    w.i32(a.ret);
}
function d_vkTransitionImageLayout(r)
{
    const a = {};
    a.device = r.h();
    a.transitionCount = r.u32();
    a.pTransitions = new Array(r.count(a.transitionCount));
    for(let i = 0; i < a.transitionCount; i++)
    {
        a.pTransitions[i] = d_VkHostImageLayoutTransitionInfo(r, 2147483647);
    }
    return a;
}
function e_vkTransitionImageLayout(w, a)
{
    w.i32(a.ret);
}
function d_vkCmdBeginRenderingKHR(r)
{
    const a = {};
    a.pRenderingInfo = d_VkRenderingInfo(r, 2147483647);
    return a;
}
function d_vkCmdEndRenderingKHR(r)
{
    const a = {};
    return a;
}
function d_vkGetPhysicalDeviceFeatures2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pFeatures = d_VkPhysicalDeviceFeatures2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFeatures2KHR(w, a)
{
    e_VkPhysicalDeviceFeatures2(w, a.pFeatures, 2147483647);
}
function d_vkGetPhysicalDeviceProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pProperties = d_VkPhysicalDeviceProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceProperties2KHR(w, a)
{
    e_VkPhysicalDeviceProperties2(w, a.pProperties, 2147483647);
}
function d_vkGetPhysicalDeviceFormatProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.pFormatProperties = d_VkFormatProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceFormatProperties2KHR(w, a)
{
    e_VkFormatProperties2(w, a.pFormatProperties, 2147483647);
}
function d_vkGetPhysicalDeviceImageFormatProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pImageFormatInfo = d_VkPhysicalDeviceImageFormatInfo2(r, 2147483647);
    a.pImageFormatProperties = d_VkImageFormatProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceImageFormatProperties2KHR(w, a)
{
    e_VkImageFormatProperties2(w, a.pImageFormatProperties, 2147483647);
    w.i32(a.ret);
}
function d_vkGetPhysicalDeviceQueueFamilyProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pQueueFamilyPropertyCount = null;
    if(p0)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pQueueFamilyProperties = null;
    if(p1)
    {
        a.pQueueFamilyProperties = [];
        a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            a.pQueueFamilyProperties[i] = d_VkQueueFamilyProperties2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceQueueFamilyProperties2KHR(w, a)
{
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                e_VkQueueFamilyProperties2(w, a.pQueueFamilyProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkGetPhysicalDeviceMemoryProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pMemoryProperties = d_VkPhysicalDeviceMemoryProperties2(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceMemoryProperties2KHR(w, a)
{
    e_VkPhysicalDeviceMemoryProperties2(w, a.pMemoryProperties, 2147483647);
}
function d_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pFormatInfo = d_VkPhysicalDeviceSparseImageFormatInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pPropertyCount = null;
    if(p0)
    {
        a.pPropertyCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pPropertyCount));
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            a.pProperties[i] = d_VkSparseImageFormatProperties2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                e_VkSparseImageFormatProperties2(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
}
function d_vkTrimCommandPoolKHR(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkGetPhysicalDeviceExternalBufferPropertiesKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalBufferInfo = d_VkPhysicalDeviceExternalBufferInfo(r, 2147483647);
    a.pExternalBufferProperties = d_VkExternalBufferProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalBufferPropertiesKHR(w, a)
{
    e_VkExternalBufferProperties(w, a.pExternalBufferProperties, 2147483647);
}
function d_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalSemaphoreInfo = d_VkPhysicalDeviceExternalSemaphoreInfo(r, 2147483647);
    a.pExternalSemaphoreProperties = d_VkExternalSemaphoreProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(w, a)
{
    e_VkExternalSemaphoreProperties(w, a.pExternalSemaphoreProperties, 2147483647);
}
function d_vkImportSemaphoreFdKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pImportSemaphoreFdInfo = d_VkImportSemaphoreFdInfoKHR(r, 2147483647);
    return a;
}
function e_vkImportSemaphoreFdKHR(w, a)
{
    w.i32(a.ret);
}
function d_vkGetSemaphoreFdKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pGetFdInfo = d_VkSemaphoreGetFdInfoKHR(r, 2147483647);
    a.pFd = r.i32();
    return a;
}
function e_vkGetSemaphoreFdKHR(w, a)
{
    w.i32(a.pFd);
    w.i32(a.ret);
}
function d_vkCreateDescriptorUpdateTemplateKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorUpdateTemplateCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pDescriptorUpdateTemplate = r.h();
    return a;
}
function e_vkCreateDescriptorUpdateTemplateKHR(w, a)
{
    w.h(a.pDescriptorUpdateTemplate);
    w.i32(a.ret);
}
function d_vkDestroyDescriptorUpdateTemplateKHR(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorUpdateTemplate = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkUpdateDescriptorSetWithTemplateKHR(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSet = r.h();
    a.descriptorUpdateTemplate = r.h();
    const p0 = r.ptr();
    a.pData = null;
    if(p0)
    {
        a.pData = r.void();
    }
    return a;
}
function d_vkCreateRenderPass2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkRenderPassCreateInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pRenderPass = r.h();
    return a;
}
function e_vkCreateRenderPass2KHR(w, a)
{
    w.h(a.pRenderPass);
    w.i32(a.ret);
}
function d_vkCmdBeginRenderPass2KHR(r)
{
    const a = {};
    a.pRenderPassBegin = d_VkRenderPassBeginInfo(r, 2147483647);
    a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r, 2147483647);
    return a;
}
function d_vkCmdNextSubpass2KHR(r)
{
    const a = {};
    a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r, 2147483647);
    a.pSubpassEndInfo = d_VkSubpassEndInfo(r, 2147483647);
    return a;
}
function d_vkCmdEndRenderPass2KHR(r)
{
    const a = {};
    a.pSubpassEndInfo = d_VkSubpassEndInfo(r, 2147483647);
    return a;
}
function d_vkGetPhysicalDeviceExternalFencePropertiesKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.pExternalFenceInfo = d_VkPhysicalDeviceExternalFenceInfo(r, 2147483647);
    a.pExternalFenceProperties = d_VkExternalFenceProperties(r, 2147483647);
    return a;
}
function e_vkGetPhysicalDeviceExternalFencePropertiesKHR(w, a)
{
    e_VkExternalFenceProperties(w, a.pExternalFenceProperties, 2147483647);
}
function d_vkImportFenceFdKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pImportFenceFdInfo = d_VkImportFenceFdInfoKHR(r, 2147483647);
    return a;
}
function e_vkImportFenceFdKHR(w, a)
{
    w.i32(a.ret);
}
function d_vkGetFenceFdKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pGetFdInfo = d_VkFenceGetFdInfoKHR(r, 2147483647);
    a.pFd = r.i32();
    return a;
}
function e_vkGetFenceFdKHR(w, a)
{
    w.i32(a.pFd);
    w.i32(a.ret);
}
function d_vkGetImageMemoryRequirements2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkImageMemoryRequirementsInfo2(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetImageMemoryRequirements2KHR(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetBufferMemoryRequirements2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferMemoryRequirementsInfo2(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetBufferMemoryRequirements2KHR(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetImageSparseMemoryRequirements2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkImageSparseMemoryRequirementsInfo2(r, 2147483647);
    const p0 = r.ptr();
    a.pSparseMemoryRequirementCount = null;
    if(p0)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    const p1 = r.ptr();
    a.pSparseMemoryRequirements = null;
    if(p1)
    {
        a.pSparseMemoryRequirements = [];
        a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetImageSparseMemoryRequirements2KHR(w, a)
{
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                e_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
            }
        }
    }
}
function d_vkCreateSamplerYcbcrConversionKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkSamplerYcbcrConversionCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pYcbcrConversion = r.h();
    return a;
}
function e_vkCreateSamplerYcbcrConversionKHR(w, a)
{
    w.h(a.pYcbcrConversion);
    w.i32(a.ret);
}
function d_vkDestroySamplerYcbcrConversionKHR(r)
{
    const a = {};
    a.device = r.h();
    a.ycbcrConversion = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkBindBufferMemory2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfos = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfos[i] = d_VkBindBufferMemoryInfo(r, 2147483647);
    }
    return a;
}
function e_vkBindBufferMemory2KHR(w, a)
{
    w.i32(a.ret);
}
function d_vkBindImageMemory2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfos = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfos[i] = d_VkBindImageMemoryInfo(r, 2147483647);
    }
    return a;
}
function e_vkBindImageMemory2KHR(w, a)
{
    w.i32(a.ret);
}
function d_vkGetDescriptorSetLayoutSupportKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkDescriptorSetLayoutCreateInfo(r, 2147483647);
    a.pSupport = d_VkDescriptorSetLayoutSupport(r, 2147483647);
    return a;
}
function e_vkGetDescriptorSetLayoutSupportKHR(w, a)
{
    e_VkDescriptorSetLayoutSupport(w, a.pSupport, 2147483647);
}
function d_vkGetBufferDeviceAddressKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferDeviceAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetBufferDeviceAddressKHR(w, a)
{
    w.u64(a.ret);
}
function d_vkGetBufferOpaqueCaptureAddressKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkBufferDeviceAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetBufferOpaqueCaptureAddressKHR(w, a)
{
    w.u64(a.ret);
}
function d_vkGetDeviceMemoryOpaqueCaptureAddressKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceMemoryOpaqueCaptureAddressInfo(r, 2147483647);
    return a;
}
function e_vkGetDeviceMemoryOpaqueCaptureAddressKHR(w, a)
{
    w.u64(a.ret);
}
function d_vkGetPipelineExecutablePropertiesKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pPipelineInfo = d_VkPipelineInfoKHR(r, 2147483647);
    const p0 = r.ptr();
    a.pExecutableCount = null;
    if(p0)
    {
        a.pExecutableCount = r.u32();
    }
    const p1 = r.ptr();
    a.pProperties = null;
    if(p1)
    {
        a.pProperties = [];
        a.pProperties = new Array(r.count(a.pExecutableCount));
        for(let i = 0; i < a.pExecutableCount; i++)
        {
            a.pProperties[i] = d_VkPipelineExecutablePropertiesKHR(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPipelineExecutablePropertiesKHR(w, a)
{
    w.ptr(a.pExecutableCount != null);
    if(a.pExecutableCount != null)
    {
        w.u32(a.pExecutableCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        if(a.pExecutableCount != null)
        {
            for(let i = 0; i < a.pExecutableCount; i++)
            {
                e_VkPipelineExecutablePropertiesKHR(w, a.pProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkGetPipelineExecutableStatisticsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pExecutableInfo = d_VkPipelineExecutableInfoKHR(r, 2147483647);
    const p0 = r.ptr();
    a.pStatisticCount = null;
    if(p0)
    {
        a.pStatisticCount = r.u32();
    }
    const p1 = r.ptr();
    a.pStatistics = null;
    if(p1)
    {
        a.pStatistics = [];
        a.pStatistics = new Array(r.count(a.pStatisticCount));
        for(let i = 0; i < a.pStatisticCount; i++)
        {
            a.pStatistics[i] = d_VkPipelineExecutableStatisticKHR(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPipelineExecutableStatisticsKHR(w, a)
{
    w.ptr(a.pStatisticCount != null);
    if(a.pStatisticCount != null)
    {
        w.u32(a.pStatisticCount);
    }
    w.ptr(a.pStatistics != null);
    if(a.pStatistics != null)
    {
        if(a.pStatisticCount != null)
        {
            for(let i = 0; i < a.pStatisticCount; i++)
            {
                e_VkPipelineExecutableStatisticKHR(w, a.pStatistics?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkGetPipelineExecutableInternalRepresentationsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pExecutableInfo = d_VkPipelineExecutableInfoKHR(r, 2147483647);
    const p0 = r.ptr();
    a.pInternalRepresentationCount = null;
    if(p0)
    {
        a.pInternalRepresentationCount = r.u32();
    }
    const p1 = r.ptr();
    a.pInternalRepresentations = null;
    if(p1)
    {
        a.pInternalRepresentations = [];
        a.pInternalRepresentations = new Array(r.count(a.pInternalRepresentationCount));
        for(let i = 0; i < a.pInternalRepresentationCount; i++)
        {
            a.pInternalRepresentations[i] = d_VkPipelineExecutableInternalRepresentationKHR(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPipelineExecutableInternalRepresentationsKHR(w, a)
{
    w.ptr(a.pInternalRepresentationCount != null);
    if(a.pInternalRepresentationCount != null)
    {
        w.u32(a.pInternalRepresentationCount);
    }
    w.ptr(a.pInternalRepresentations != null);
    if(a.pInternalRepresentations != null)
    {
        if(a.pInternalRepresentationCount != null)
        {
            for(let i = 0; i < a.pInternalRepresentationCount; i++)
            {
                e_VkPipelineExecutableInternalRepresentationKHR(w, a.pInternalRepresentations?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkCmdSetEvent2KHR(r)
{
    const a = {};
    a.event = r.h();
    a.pDependencyInfo = d_VkDependencyInfo(r, 2147483647);
    return a;
}
function d_vkCmdResetEvent2KHR(r)
{
    const a = {};
    a.event = r.h();
    a.stageMask = r.u64();
    return a;
}
function d_vkCmdWaitEvents2KHR(r)
{
    const a = {};
    a.eventCount = r.u32();
    if(a.eventCount)
    {
        a.pEvents = new Array(r.count(a.eventCount));
        for(let k = 0; k < a.eventCount; k++)
        {
            a.pEvents[k] = r.h();
        }
    }
    a.pDependencyInfos = new Array(r.count(a.eventCount));
    for(let i = 0; i < a.eventCount; i++)
    {
        a.pDependencyInfos[i] = d_VkDependencyInfo(r, 2147483647);
    }
    return a;
}
function d_vkCmdPipelineBarrier2KHR(r)
{
    const a = {};
    a.pDependencyInfo = d_VkDependencyInfo(r, 2147483647);
    return a;
}
function d_vkCmdWriteTimestamp2KHR(r)
{
    const a = {};
    a.stage = r.u64();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkQueueSubmit2KHR(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    a.pSubmits = new Array(r.count(a.submitCount));
    for(let i = 0; i < a.submitCount; i++)
    {
        a.pSubmits[i] = d_VkSubmitInfo2(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function e_vkQueueSubmit2KHR(w, a)
{
    w.i32(a.ret);
}
function d_vkCmdCopyBuffer2KHR(r)
{
    const a = {};
    a.pCopyBufferInfo = d_VkCopyBufferInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyImage2KHR(r)
{
    const a = {};
    a.pCopyImageInfo = d_VkCopyImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyBufferToImage2KHR(r)
{
    const a = {};
    a.pCopyBufferToImageInfo = d_VkCopyBufferToImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdCopyImageToBuffer2KHR(r)
{
    const a = {};
    a.pCopyImageToBufferInfo = d_VkCopyImageToBufferInfo2(r, 2147483647);
    return a;
}
function d_vkCmdBlitImage2KHR(r)
{
    const a = {};
    a.pBlitImageInfo = d_VkBlitImageInfo2(r, 2147483647);
    return a;
}
function d_vkCmdResolveImage2KHR(r)
{
    const a = {};
    a.pResolveImageInfo = d_VkResolveImageInfo2(r, 2147483647);
    return a;
}
function d_vkGetDeviceBufferMemoryRequirementsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceBufferMemoryRequirements(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetDeviceBufferMemoryRequirementsKHR(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetDeviceImageMemoryRequirementsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageMemoryRequirements(r, 2147483647);
    a.pMemoryRequirements = d_VkMemoryRequirements2(r, 2147483647);
    return a;
}
function e_vkGetDeviceImageMemoryRequirementsKHR(w, a)
{
    e_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function d_vkGetDeviceImageSparseMemoryRequirementsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageMemoryRequirements(r, 2147483647);
    const p0 = r.ptr();
    a.pSparseMemoryRequirementCount = null;
    if(p0)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    const p1 = r.ptr();
    a.pSparseMemoryRequirements = null;
    if(p1)
    {
        a.pSparseMemoryRequirements = [];
        a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetDeviceImageSparseMemoryRequirementsKHR(w, a)
{
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                e_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
            }
        }
    }
}
function d_vkCmdBindIndexBuffer2KHR(r)
{
    const a = {};
    a.buffer = r.h();
    a.offset = r.u64();
    a.size = r.u64();
    a.indexType = r.i32();
    return a;
}
function d_vkGetRenderingAreaGranularityKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pRenderingAreaInfo = d_VkRenderingAreaInfo(r, 2147483647);
    a.pGranularity = d_VkExtent2D(r, 2147483647);
    return a;
}
function e_vkGetRenderingAreaGranularityKHR(w, a)
{
    e_VkExtent2D(w, a.pGranularity, 2147483647);
}
function d_vkGetDeviceImageSubresourceLayoutKHR(r)
{
    const a = {};
    a.device = r.h();
    a.pInfo = d_VkDeviceImageSubresourceInfo(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout2(r, 2147483647);
    return a;
}
function e_vkGetDeviceImageSubresourceLayoutKHR(w, a)
{
    e_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function d_vkGetImageSubresourceLayout2KHR(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pSubresource = d_VkImageSubresource2(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout2(r, 2147483647);
    return a;
}
function e_vkGetImageSubresourceLayout2KHR(w, a)
{
    e_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function d_vkCmdSetLineStippleKHR(r)
{
    const a = {};
    a.lineStippleFactor = r.u32();
    a.lineStipplePattern = r.u16();
    return a;
}
function d_vkGetSwapchainGrallocUsageANDROID(r)
{
    const a = {};
    a.device = r.h();
    a.format = r.i32();
    a.imageUsage = r.u32();
    a.grallocUsage = r.i32();
    return a;
}
function e_vkGetSwapchainGrallocUsageANDROID(w, a)
{
    w.i32(a.grallocUsage);
    w.i32(a.ret);
}
function d_vkAcquireImageANDROID(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.nativeFenceFd = r.i32();
    a.semaphore = r.h();
    a.fence = r.h();
    return a;
}
function e_vkAcquireImageANDROID(w, a)
{
    w.i32(a.ret);
}
function d_vkQueueSignalReleaseImageANDROID(r)
{
    const a = {};
    a.queue = r.h();
    a.waitSemaphoreCount = r.u32();
    const p0 = r.ptr();
    a.pWaitSemaphores = null;
    if(p0)
    {
        a.pWaitSemaphores = [];
        if(a.waitSemaphoreCount)
        {
            a.pWaitSemaphores = new Array(r.count(a.waitSemaphoreCount));
            for(let k = 0; k < a.waitSemaphoreCount; k++)
            {
                a.pWaitSemaphores[k] = r.h();
            }
        }
    }
    a.image = r.h();
    a.pNativeFenceFd = r.i32();
    return a;
}
function e_vkQueueSignalReleaseImageANDROID(w, a)
{
    w.i32(a.pNativeFenceFd);
    w.i32(a.ret);
}
function d_vkGetSwapchainGrallocUsage2ANDROID(r)
{
    const a = {};
    a.device = r.h();
    a.format = r.i32();
    a.imageUsage = r.u32();
    a.swapchainImageUsage = r.u32();
    a.grallocConsumerUsage = r.u64();
    a.grallocProducerUsage = r.u64();
    return a;
}
function e_vkGetSwapchainGrallocUsage2ANDROID(w, a)
{
    w.u64(a.grallocConsumerUsage);
    w.u64(a.grallocProducerUsage);
    w.i32(a.ret);
}
function d_vkCmdBindTransformFeedbackBuffersEXT(r)
{
    const a = {};
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    if(a.bindingCount)
    {
        a.pBuffers = new Array(r.count(a.bindingCount));
        for(let k = 0; k < a.bindingCount; k++)
        {
            a.pBuffers[k] = r.h();
        }
    }
    if((a.bindingCount > 0))
    {
        a.pOffsets = r.u64s(a.bindingCount);
    }
    const p0 = r.ptr();
    a.pSizes = null;
    if(p0)
    {
        if((a.bindingCount > 0))
        {
            a.pSizes = r.u64s(a.bindingCount);
        }
    }
    return a;
}
function d_vkCmdBeginTransformFeedbackEXT(r)
{
    const a = {};
    a.firstCounterBuffer = r.u32();
    a.counterBufferCount = r.u32();
    const p0 = r.ptr();
    a.pCounterBuffers = null;
    if(p0)
    {
        a.pCounterBuffers = [];
        if(a.counterBufferCount)
        {
            a.pCounterBuffers = new Array(r.count(a.counterBufferCount));
            for(let k = 0; k < a.counterBufferCount; k++)
            {
                a.pCounterBuffers[k] = r.h();
            }
        }
    }
    const p1 = r.ptr();
    a.pCounterBufferOffsets = null;
    if(p1)
    {
        if((a.counterBufferCount > 0))
        {
            a.pCounterBufferOffsets = r.u64s(a.counterBufferCount);
        }
    }
    return a;
}
function d_vkCmdEndTransformFeedbackEXT(r)
{
    const a = {};
    a.firstCounterBuffer = r.u32();
    a.counterBufferCount = r.u32();
    const p0 = r.ptr();
    a.pCounterBuffers = null;
    if(p0)
    {
        a.pCounterBuffers = [];
        if(a.counterBufferCount)
        {
            a.pCounterBuffers = new Array(r.count(a.counterBufferCount));
            for(let k = 0; k < a.counterBufferCount; k++)
            {
                a.pCounterBuffers[k] = r.h();
            }
        }
    }
    const p1 = r.ptr();
    a.pCounterBufferOffsets = null;
    if(p1)
    {
        if((a.counterBufferCount > 0))
        {
            a.pCounterBufferOffsets = r.u64s(a.counterBufferCount);
        }
    }
    return a;
}
function d_vkCmdBeginQueryIndexedEXT(r)
{
    const a = {};
    a.queryPool = r.h();
    a.query = r.u32();
    a.flags = r.u32();
    a.index = r.u32();
    return a;
}
function d_vkCmdEndQueryIndexedEXT(r)
{
    const a = {};
    a.queryPool = r.h();
    a.query = r.u32();
    a.index = r.u32();
    return a;
}
function d_vkCmdDrawIndirectByteCountEXT(r)
{
    const a = {};
    a.instanceCount = r.u32();
    a.firstInstance = r.u32();
    a.counterBuffer = r.h();
    a.counterBufferOffset = r.u64();
    a.counterOffset = r.u32();
    a.vertexStride = r.u32();
    return a;
}
function d_vkGetImageDrmFormatModifierPropertiesEXT(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pProperties = d_VkImageDrmFormatModifierPropertiesEXT(r, 2147483647);
    return a;
}
function e_vkGetImageDrmFormatModifierPropertiesEXT(w, a)
{
    e_VkImageDrmFormatModifierPropertiesEXT(w, a.pProperties, 2147483647);
    w.i32(a.ret);
}
function d_vkGetPhysicalDeviceToolPropertiesEXT(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const p0 = r.ptr();
    a.pToolCount = null;
    if(p0)
    {
        a.pToolCount = r.u32();
    }
    const p1 = r.ptr();
    a.pToolProperties = null;
    if(p1)
    {
        a.pToolProperties = [];
        a.pToolProperties = new Array(r.count(a.pToolCount));
        for(let i = 0; i < a.pToolCount; i++)
        {
            a.pToolProperties[i] = d_VkPhysicalDeviceToolProperties(r, 2147483647);
        }
    }
    return a;
}
function e_vkGetPhysicalDeviceToolPropertiesEXT(w, a)
{
    w.ptr(a.pToolCount != null);
    if(a.pToolCount != null)
    {
        w.u32(a.pToolCount);
    }
    w.ptr(a.pToolProperties != null);
    if(a.pToolProperties != null)
    {
        if(a.pToolCount != null)
        {
            for(let i = 0; i < a.pToolCount; i++)
            {
                e_VkPhysicalDeviceToolProperties(w, a.pToolProperties?.[i], 2147483647);
            }
        }
    }
    w.i32(a.ret);
}
function d_vkCmdSetLineStippleEXT(r)
{
    const a = {};
    a.lineStippleFactor = r.u32();
    a.lineStipplePattern = r.u16();
    return a;
}
function d_vkCmdSetCullModeEXT(r)
{
    const a = {};
    a.cullMode = r.u32();
    return a;
}
function d_vkCmdSetFrontFaceEXT(r)
{
    const a = {};
    a.frontFace = r.i32();
    return a;
}
function d_vkCmdSetPrimitiveTopologyEXT(r)
{
    const a = {};
    a.primitiveTopology = r.i32();
    return a;
}
function d_vkCmdSetViewportWithCountEXT(r)
{
    const a = {};
    a.viewportCount = r.u32();
    a.pViewports = new Array(r.count(a.viewportCount));
    for(let i = 0; i < a.viewportCount; i++)
    {
        a.pViewports[i] = d_VkViewport(r, 2147483647);
    }
    return a;
}
function d_vkCmdSetScissorWithCountEXT(r)
{
    const a = {};
    a.scissorCount = r.u32();
    a.pScissors = new Array(r.count(a.scissorCount));
    for(let i = 0; i < a.scissorCount; i++)
    {
        a.pScissors[i] = d_VkRect2D(r, 2147483647);
    }
    return a;
}
function d_vkCmdBindVertexBuffers2EXT(r)
{
    const a = {};
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    const p0 = r.ptr();
    a.pBuffers = null;
    if(p0)
    {
        a.pBuffers = [];
        if(a.bindingCount)
        {
            a.pBuffers = new Array(r.count(a.bindingCount));
            for(let k = 0; k < a.bindingCount; k++)
            {
                a.pBuffers[k] = r.h();
            }
        }
    }
    if((a.bindingCount > 0))
    {
        a.pOffsets = r.u64s(a.bindingCount);
    }
    const p1 = r.ptr();
    a.pSizes = null;
    if(p1)
    {
        if((a.bindingCount > 0))
        {
            a.pSizes = r.u64s(a.bindingCount);
        }
    }
    const p2 = r.ptr();
    a.pStrides = null;
    if(p2)
    {
        if((a.bindingCount > 0))
        {
            a.pStrides = r.u64s(a.bindingCount);
        }
    }
    return a;
}
function d_vkCmdSetDepthTestEnableEXT(r)
{
    const a = {};
    a.depthTestEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthWriteEnableEXT(r)
{
    const a = {};
    a.depthWriteEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthCompareOpEXT(r)
{
    const a = {};
    a.depthCompareOp = r.i32();
    return a;
}
function d_vkCmdSetDepthBoundsTestEnableEXT(r)
{
    const a = {};
    a.depthBoundsTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilTestEnableEXT(r)
{
    const a = {};
    a.stencilTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilOpEXT(r)
{
    const a = {};
    a.faceMask = r.u32();
    a.failOp = r.i32();
    a.passOp = r.i32();
    a.depthFailOp = r.i32();
    a.compareOp = r.i32();
    return a;
}
function d_vkCopyMemoryToImageEXT(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyMemoryToImageInfo = d_VkCopyMemoryToImageInfo(r, 2147483647);
    return a;
}
function e_vkCopyMemoryToImageEXT(w, a)
{
    w.i32(a.ret);
}
function d_vkCopyImageToMemoryEXT(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyImageToMemoryInfo = d_VkCopyImageToMemoryInfo(r, 2147483647);
    return a;
}
function e_vkCopyImageToMemoryEXT(w, a)
{
    w.i32(a.ret);
}
function d_vkCopyImageToImageEXT(r)
{
    const a = {};
    a.device = r.h();
    a.pCopyImageToImageInfo = d_VkCopyImageToImageInfo(r, 2147483647);
    return a;
}
function e_vkCopyImageToImageEXT(w, a)
{
    w.i32(a.ret);
}
function d_vkTransitionImageLayoutEXT(r)
{
    const a = {};
    a.device = r.h();
    a.transitionCount = r.u32();
    a.pTransitions = new Array(r.count(a.transitionCount));
    for(let i = 0; i < a.transitionCount; i++)
    {
        a.pTransitions[i] = d_VkHostImageLayoutTransitionInfo(r, 2147483647);
    }
    return a;
}
function e_vkTransitionImageLayoutEXT(w, a)
{
    w.i32(a.ret);
}
function d_vkGetImageSubresourceLayout2EXT(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.pSubresource = d_VkImageSubresource2(r, 2147483647);
    a.pLayout = d_VkSubresourceLayout2(r, 2147483647);
    return a;
}
function e_vkGetImageSubresourceLayout2EXT(w, a)
{
    e_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function d_vkCreatePrivateDataSlotEXT(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkPrivateDataSlotCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pPrivateDataSlot = r.h();
    return a;
}
function e_vkCreatePrivateDataSlotEXT(w, a)
{
    w.h(a.pPrivateDataSlot);
    w.i32(a.ret);
}
function d_vkDestroyPrivateDataSlotEXT(r)
{
    const a = {};
    a.device = r.h();
    a.privateDataSlot = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function d_vkSetPrivateDataEXT(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.data = r.u64();
    return a;
}
function e_vkSetPrivateDataEXT(w, a)
{
    w.i32(a.ret);
}
function d_vkGetPrivateDataEXT(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.pData = r.u64();
    return a;
}
function e_vkGetPrivateDataEXT(w, a)
{
    w.u64(a.pData);
}
function d_vkCmdSetPatchControlPointsEXT(r)
{
    const a = {};
    a.patchControlPoints = r.u32();
    return a;
}
function d_vkCmdSetRasterizerDiscardEnableEXT(r)
{
    const a = {};
    a.rasterizerDiscardEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthBiasEnableEXT(r)
{
    const a = {};
    a.depthBiasEnable = r.u32();
    return a;
}
function d_vkCmdSetLogicOpEXT(r)
{
    const a = {};
    a.logicOp = r.i32();
    return a;
}
function d_vkCmdSetPrimitiveRestartEnableEXT(r)
{
    const a = {};
    a.primitiveRestartEnable = r.u32();
    return a;
}
function d_vkCmdSetColorWriteEnableEXT(r)
{
    const a = {};
    a.attachmentCount = r.u32();
    if((a.attachmentCount > 0))
    {
        a.pColorWriteEnables = r.u32s(a.attachmentCount);
    }
    return a;
}
function d_vkMapMemoryIntoAddressSpaceGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    const p0 = r.ptr();
    a.pAddress = null;
    if(p0)
    {
        a.pAddress = r.u64();
    }
    return a;
}
function e_vkMapMemoryIntoAddressSpaceGOOGLE(w, a)
{
    w.ptr(a.pAddress != null);
    if(a.pAddress != null)
    {
        w.u64(a.pAddress);
    }
    w.i32(a.ret);
}
function d_vkUpdateDescriptorSetWithTemplateSizedGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSet = r.h();
    a.descriptorUpdateTemplate = r.h();
    a.imageInfoCount = r.u32();
    a.bufferInfoCount = r.u32();
    a.bufferViewCount = r.u32();
    const p0 = r.ptr();
    a.pImageInfoEntryIndices = null;
    if(p0)
    {
        if((a.imageInfoCount > 0))
        {
            a.pImageInfoEntryIndices = r.u32s(a.imageInfoCount);
        }
    }
    const p1 = r.ptr();
    a.pBufferInfoEntryIndices = null;
    if(p1)
    {
        if((a.bufferInfoCount > 0))
        {
            a.pBufferInfoEntryIndices = r.u32s(a.bufferInfoCount);
        }
    }
    const p2 = r.ptr();
    a.pBufferViewEntryIndices = null;
    if(p2)
    {
        if((a.bufferViewCount > 0))
        {
            a.pBufferViewEntryIndices = r.u32s(a.bufferViewCount);
        }
    }
    const p3 = r.ptr();
    a.pImageInfos = null;
    if(p3)
    {
        a.pImageInfos = [];
        a.pImageInfos = new Array(r.count(a.imageInfoCount));
        for(let i = 0; i < a.imageInfoCount; i++)
        {
            a.pImageInfos[i] = d_VkDescriptorImageInfo(r, 2147483647);
        }
    }
    const p4 = r.ptr();
    a.pBufferInfos = null;
    if(p4)
    {
        a.pBufferInfos = [];
        a.pBufferInfos = new Array(r.count(a.bufferInfoCount));
        for(let i = 0; i < a.bufferInfoCount; i++)
        {
            a.pBufferInfos[i] = d_VkDescriptorBufferInfo(r, 2147483647);
        }
    }
    const p5 = r.ptr();
    a.pBufferViews = null;
    if(p5)
    {
        a.pBufferViews = [];
        if(a.bufferViewCount)
        {
            a.pBufferViews = new Array(r.count(a.bufferViewCount));
            for(let k = 0; k < a.bufferViewCount; k++)
            {
                a.pBufferViews[k] = r.h();
            }
        }
    }
    return a;
}
function d_vkBeginCommandBufferAsyncGOOGLE(r)
{
    const a = {};
    a.pBeginInfo = d_VkCommandBufferBeginInfo(r, 2147483647);
    return a;
}
function d_vkEndCommandBufferAsyncGOOGLE(r)
{
    const a = {};
    return a;
}
function d_vkResetCommandBufferAsyncGOOGLE(r)
{
    const a = {};
    a.flags = r.u32();
    return a;
}
function d_vkCommandBufferHostSyncGOOGLE(r)
{
    const a = {};
    a.needHostSync = r.u32();
    a.sequenceNumber = r.u32();
    return a;
}
function d_vkCreateImageWithRequirementsGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkImageCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pImage = r.h();
    a.pMemoryRequirements = d_VkMemoryRequirements(r, 2147483647);
    return a;
}
function e_vkCreateImageWithRequirementsGOOGLE(w, a)
{
    w.h(a.pImage);
    e_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
    w.i32(a.ret);
}
function d_vkCreateBufferWithRequirementsGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkBufferCreateInfo(r, 2147483647);
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    a.pBuffer = r.h();
    a.pMemoryRequirements = d_VkMemoryRequirements(r, 2147483647);
    return a;
}
function e_vkCreateBufferWithRequirementsGOOGLE(w, a)
{
    w.h(a.pBuffer);
    e_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
    w.i32(a.ret);
}
function d_vkGetMemoryHostAddressInfoGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    const p0 = r.ptr();
    a.pAddress = null;
    if(p0)
    {
        a.pAddress = r.u64();
    }
    const p1 = r.ptr();
    a.pSize = null;
    if(p1)
    {
        a.pSize = r.u64();
    }
    const p2 = r.ptr();
    a.pHostmemId = null;
    if(p2)
    {
        a.pHostmemId = r.u64();
    }
    return a;
}
function e_vkGetMemoryHostAddressInfoGOOGLE(w, a)
{
    w.ptr(a.pAddress != null);
    if(a.pAddress != null)
    {
        w.u64(a.pAddress);
    }
    w.ptr(a.pSize != null);
    if(a.pSize != null)
    {
        w.u64(a.pSize);
    }
    w.ptr(a.pHostmemId != null);
    if(a.pHostmemId != null)
    {
        w.u64(a.pHostmemId);
    }
    w.i32(a.ret);
}
function d_vkFreeMemorySyncGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    const p0 = r.ptr();
    a.pAllocator = null;
    if(p0)
    {
        a.pAllocator = d_VkAllocationCallbacks(r, 2147483647);
    }
    return a;
}
function e_vkFreeMemorySyncGOOGLE(w, a)
{
    w.i32(a.ret);
}
function d_vkQueueHostSyncGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.needHostSync = r.u32();
    a.sequenceNumber = r.u32();
    return a;
}
function d_vkQueueSubmitAsyncGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    a.pSubmits = new Array(r.count(a.submitCount));
    for(let i = 0; i < a.submitCount; i++)
    {
        a.pSubmits[i] = d_VkSubmitInfo(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function d_vkQueueWaitIdleAsyncGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    return a;
}
function d_vkQueueBindSparseAsyncGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.bindInfoCount = r.u32();
    a.pBindInfo = new Array(r.count(a.bindInfoCount));
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        a.pBindInfo[i] = d_VkBindSparseInfo(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function d_vkGetLinearImageLayoutGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.format = r.i32();
    a.pOffset = r.u64();
    a.pRowPitchAlignment = r.u64();
    return a;
}
function e_vkGetLinearImageLayoutGOOGLE(w, a)
{
    w.u64(a.pOffset);
    w.u64(a.pRowPitchAlignment);
}
function d_vkGetLinearImageLayout2GOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.pCreateInfo = d_VkImageCreateInfo(r, 2147483647);
    a.pOffset = r.u64();
    a.pRowPitchAlignment = r.u64();
    return a;
}
function e_vkGetLinearImageLayout2GOOGLE(w, a)
{
    w.u64(a.pOffset);
    w.u64(a.pRowPitchAlignment);
}
function d_vkQueueFlushCommandsGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.commandBuffer = r.h();
    a.dataSize = r.u64();
    a.pData = r.bytes_of(a.dataSize);
    return a;
}
function d_vkQueueCommitDescriptorSetUpdatesGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.descriptorPoolCount = r.u32();
    if(a.descriptorPoolCount)
    {
        a.pDescriptorPools = new Array(r.count(a.descriptorPoolCount));
        for(let k = 0; k < a.descriptorPoolCount; k++)
        {
            a.pDescriptorPools[k] = r.h();
        }
    }
    a.descriptorSetCount = r.u32();
    if(a.descriptorSetCount)
    {
        a.pSetLayouts = new Array(r.count(a.descriptorSetCount));
        for(let k = 0; k < a.descriptorSetCount; k++)
        {
            a.pSetLayouts[k] = r.h();
        }
    }
    if((a.descriptorSetCount > 0))
    {
        a.pDescriptorSetPoolIds = r.u64s(a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        a.pDescriptorSetWhichPool = r.u32s(a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        a.pDescriptorSetPendingAllocation = r.u32s(a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        a.pDescriptorWriteStartingIndices = r.u32s(a.descriptorSetCount);
    }
    a.pendingDescriptorWriteCount = r.u32();
    a.pPendingDescriptorWrites = new Array(r.count(a.pendingDescriptorWriteCount));
    for(let i = 0; i < a.pendingDescriptorWriteCount; i++)
    {
        a.pPendingDescriptorWrites[i] = d_VkWriteDescriptorSet(r, 2147483647);
    }
    return a;
}
function d_vkCollectDescriptorPoolIdsGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    a.pPoolIdCount = r.u32();
    const p0 = r.ptr();
    a.pPoolIds = null;
    if(p0)
    {
        if((a.pPoolIdCount > 0))
        {
            a.pPoolIds = r.u64s(a.pPoolIdCount);
        }
    }
    return a;
}
function e_vkCollectDescriptorPoolIdsGOOGLE(w, a)
{
    w.u32(a.pPoolIdCount);
    w.ptr(a.pPoolIds != null);
    if(a.pPoolIds != null)
    {
        w.u64s(a.pPoolIds, a.pPoolIdCount);
    }
}
function d_vkQueueSignalReleaseImageANDROIDAsyncGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.waitSemaphoreCount = r.u32();
    const p0 = r.ptr();
    a.pWaitSemaphores = null;
    if(p0)
    {
        a.pWaitSemaphores = [];
        if(a.waitSemaphoreCount)
        {
            a.pWaitSemaphores = new Array(r.count(a.waitSemaphoreCount));
            for(let k = 0; k < a.waitSemaphoreCount; k++)
            {
                a.pWaitSemaphores[k] = r.h();
            }
        }
    }
    a.image = r.h();
    return a;
}
function d_vkQueueFlushCommandsFromAuxMemoryGOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.commandBuffer = r.h();
    a.deviceMemory = r.h();
    a.dataOffset = r.u64();
    a.dataSize = r.u64();
    return a;
}
function d_vkGetBlobGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    return a;
}
function e_vkGetBlobGOOGLE(w, a)
{
    w.i32(a.ret);
}
function d_vkUpdateDescriptorSetWithTemplateSized2GOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSet = r.h();
    a.descriptorUpdateTemplate = r.h();
    a.imageInfoCount = r.u32();
    a.bufferInfoCount = r.u32();
    a.bufferViewCount = r.u32();
    a.inlineUniformBlockCount = r.u32();
    const p0 = r.ptr();
    a.pImageInfoEntryIndices = null;
    if(p0)
    {
        if((a.imageInfoCount > 0))
        {
            a.pImageInfoEntryIndices = r.u32s(a.imageInfoCount);
        }
    }
    const p1 = r.ptr();
    a.pBufferInfoEntryIndices = null;
    if(p1)
    {
        if((a.bufferInfoCount > 0))
        {
            a.pBufferInfoEntryIndices = r.u32s(a.bufferInfoCount);
        }
    }
    const p2 = r.ptr();
    a.pBufferViewEntryIndices = null;
    if(p2)
    {
        if((a.bufferViewCount > 0))
        {
            a.pBufferViewEntryIndices = r.u32s(a.bufferViewCount);
        }
    }
    const p3 = r.ptr();
    a.pImageInfos = null;
    if(p3)
    {
        a.pImageInfos = [];
        a.pImageInfos = new Array(r.count(a.imageInfoCount));
        for(let i = 0; i < a.imageInfoCount; i++)
        {
            a.pImageInfos[i] = d_VkDescriptorImageInfo(r, 2147483647);
        }
    }
    const p4 = r.ptr();
    a.pBufferInfos = null;
    if(p4)
    {
        a.pBufferInfos = [];
        a.pBufferInfos = new Array(r.count(a.bufferInfoCount));
        for(let i = 0; i < a.bufferInfoCount; i++)
        {
            a.pBufferInfos[i] = d_VkDescriptorBufferInfo(r, 2147483647);
        }
    }
    const p5 = r.ptr();
    a.pBufferViews = null;
    if(p5)
    {
        a.pBufferViews = [];
        if(a.bufferViewCount)
        {
            a.pBufferViews = new Array(r.count(a.bufferViewCount));
            for(let k = 0; k < a.bufferViewCount; k++)
            {
                a.pBufferViews[k] = r.h();
            }
        }
    }
    const p6 = r.ptr();
    a.pInlineUniformBlockData = null;
    if(p6)
    {
        if((a.inlineUniformBlockCount > 0))
        {
            a.pInlineUniformBlockData = r.u8s(a.inlineUniformBlockCount);
        }
    }
    return a;
}
function d_vkQueueSubmitAsync2GOOGLE(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    a.pSubmits = new Array(r.count(a.submitCount));
    for(let i = 0; i < a.submitCount; i++)
    {
        a.pSubmits[i] = d_VkSubmitInfo2(r, 2147483647);
    }
    a.fence = r.h();
    return a;
}
function d_vkGetSemaphoreGOOGLE(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    a.syncId = r.u64();
    return a;
}
function e_vkGetSemaphoreGOOGLE(w, a)
{
    w.i32(a.ret);
}
function d_vkTraceAsyncGOOGLE(r)
{
    const a = {};
    a.id = r.u64();
    return a;
}

/** the commands by opcode: [name, decode the request, encode the reply (or null), in a command buffer's stream, the output handles] */
export const COMMANDS = {
    20000: ["vkCreateInstance", d_vkCreateInstance, e_vkCreateInstance, 0, ["pInstance"]],
    20001: ["vkDestroyInstance", d_vkDestroyInstance, null, 0],
    20002: ["vkEnumeratePhysicalDevices", d_vkEnumeratePhysicalDevices, e_vkEnumeratePhysicalDevices, 0, ["pPhysicalDevices"]],
    20003: ["vkGetPhysicalDeviceFeatures", d_vkGetPhysicalDeviceFeatures, e_vkGetPhysicalDeviceFeatures, 0],
    20004: ["vkGetPhysicalDeviceFormatProperties", d_vkGetPhysicalDeviceFormatProperties, e_vkGetPhysicalDeviceFormatProperties, 0],
    20005: ["vkGetPhysicalDeviceImageFormatProperties", d_vkGetPhysicalDeviceImageFormatProperties, e_vkGetPhysicalDeviceImageFormatProperties, 0],
    20006: ["vkGetPhysicalDeviceProperties", d_vkGetPhysicalDeviceProperties, e_vkGetPhysicalDeviceProperties, 0],
    20007: ["vkGetPhysicalDeviceQueueFamilyProperties", d_vkGetPhysicalDeviceQueueFamilyProperties, e_vkGetPhysicalDeviceQueueFamilyProperties, 0],
    20008: ["vkGetPhysicalDeviceMemoryProperties", d_vkGetPhysicalDeviceMemoryProperties, e_vkGetPhysicalDeviceMemoryProperties, 0],
    20009: ["vkGetInstanceProcAddr", d_vkGetInstanceProcAddr, e_vkGetInstanceProcAddr, 0],
    20010: ["vkGetDeviceProcAddr", d_vkGetDeviceProcAddr, e_vkGetDeviceProcAddr, 0],
    20011: ["vkCreateDevice", d_vkCreateDevice, e_vkCreateDevice, 0, ["pDevice"]],
    20012: ["vkDestroyDevice", d_vkDestroyDevice, null, 0],
    20013: ["vkEnumerateInstanceExtensionProperties", d_vkEnumerateInstanceExtensionProperties, e_vkEnumerateInstanceExtensionProperties, 0],
    20014: ["vkEnumerateDeviceExtensionProperties", d_vkEnumerateDeviceExtensionProperties, e_vkEnumerateDeviceExtensionProperties, 0],
    20015: ["vkEnumerateInstanceLayerProperties", d_vkEnumerateInstanceLayerProperties, e_vkEnumerateInstanceLayerProperties, 0],
    20016: ["vkEnumerateDeviceLayerProperties", d_vkEnumerateDeviceLayerProperties, e_vkEnumerateDeviceLayerProperties, 0],
    20017: ["vkGetDeviceQueue", d_vkGetDeviceQueue, e_vkGetDeviceQueue, 0, ["pQueue"]],
    20018: ["vkQueueSubmit", d_vkQueueSubmit, e_vkQueueSubmit, 0],
    20019: ["vkQueueWaitIdle", d_vkQueueWaitIdle, e_vkQueueWaitIdle, 0],
    20020: ["vkDeviceWaitIdle", d_vkDeviceWaitIdle, e_vkDeviceWaitIdle, 0],
    20021: ["vkAllocateMemory", d_vkAllocateMemory, e_vkAllocateMemory, 0, ["pMemory"]],
    20022: ["vkFreeMemory", d_vkFreeMemory, null, 0],
    20025: ["vkFlushMappedMemoryRanges", d_vkFlushMappedMemoryRanges, e_vkFlushMappedMemoryRanges, 0],
    20026: ["vkInvalidateMappedMemoryRanges", d_vkInvalidateMappedMemoryRanges, e_vkInvalidateMappedMemoryRanges, 0],
    20027: ["vkGetDeviceMemoryCommitment", d_vkGetDeviceMemoryCommitment, e_vkGetDeviceMemoryCommitment, 0],
    20028: ["vkBindBufferMemory", d_vkBindBufferMemory, e_vkBindBufferMemory, 0],
    20029: ["vkBindImageMemory", d_vkBindImageMemory, e_vkBindImageMemory, 0],
    20030: ["vkGetBufferMemoryRequirements", d_vkGetBufferMemoryRequirements, e_vkGetBufferMemoryRequirements, 0],
    20031: ["vkGetImageMemoryRequirements", d_vkGetImageMemoryRequirements, e_vkGetImageMemoryRequirements, 0],
    20032: ["vkGetImageSparseMemoryRequirements", d_vkGetImageSparseMemoryRequirements, e_vkGetImageSparseMemoryRequirements, 0],
    20033: ["vkGetPhysicalDeviceSparseImageFormatProperties", d_vkGetPhysicalDeviceSparseImageFormatProperties, e_vkGetPhysicalDeviceSparseImageFormatProperties, 0],
    20034: ["vkQueueBindSparse", d_vkQueueBindSparse, e_vkQueueBindSparse, 0],
    20035: ["vkCreateFence", d_vkCreateFence, e_vkCreateFence, 0, ["pFence"]],
    20036: ["vkDestroyFence", d_vkDestroyFence, null, 0],
    20037: ["vkResetFences", d_vkResetFences, e_vkResetFences, 0],
    20038: ["vkGetFenceStatus", d_vkGetFenceStatus, e_vkGetFenceStatus, 0],
    20039: ["vkWaitForFences", d_vkWaitForFences, e_vkWaitForFences, 0],
    20040: ["vkCreateSemaphore", d_vkCreateSemaphore, e_vkCreateSemaphore, 0, ["pSemaphore"]],
    20041: ["vkDestroySemaphore", d_vkDestroySemaphore, null, 0],
    20042: ["vkCreateEvent", d_vkCreateEvent, e_vkCreateEvent, 0, ["pEvent"]],
    20043: ["vkDestroyEvent", d_vkDestroyEvent, null, 0],
    20044: ["vkGetEventStatus", d_vkGetEventStatus, e_vkGetEventStatus, 0],
    20045: ["vkSetEvent", d_vkSetEvent, e_vkSetEvent, 0],
    20046: ["vkResetEvent", d_vkResetEvent, e_vkResetEvent, 0],
    20047: ["vkCreateQueryPool", d_vkCreateQueryPool, e_vkCreateQueryPool, 0, ["pQueryPool"]],
    20048: ["vkDestroyQueryPool", d_vkDestroyQueryPool, null, 0],
    20049: ["vkGetQueryPoolResults", d_vkGetQueryPoolResults, e_vkGetQueryPoolResults, 0],
    20050: ["vkCreateBuffer", d_vkCreateBuffer, e_vkCreateBuffer, 0, ["pBuffer"]],
    20051: ["vkDestroyBuffer", d_vkDestroyBuffer, null, 0],
    20052: ["vkCreateBufferView", d_vkCreateBufferView, e_vkCreateBufferView, 0, ["pView"]],
    20053: ["vkDestroyBufferView", d_vkDestroyBufferView, null, 0],
    20054: ["vkCreateImage", d_vkCreateImage, e_vkCreateImage, 0, ["pImage"]],
    20055: ["vkDestroyImage", d_vkDestroyImage, null, 0],
    20056: ["vkGetImageSubresourceLayout", d_vkGetImageSubresourceLayout, e_vkGetImageSubresourceLayout, 0],
    20057: ["vkCreateImageView", d_vkCreateImageView, e_vkCreateImageView, 0, ["pView"]],
    20058: ["vkDestroyImageView", d_vkDestroyImageView, null, 0],
    20059: ["vkCreateShaderModule", d_vkCreateShaderModule, e_vkCreateShaderModule, 0, ["pShaderModule"]],
    20060: ["vkDestroyShaderModule", d_vkDestroyShaderModule, null, 0],
    20061: ["vkCreatePipelineCache", d_vkCreatePipelineCache, e_vkCreatePipelineCache, 0, ["pPipelineCache"]],
    20062: ["vkDestroyPipelineCache", d_vkDestroyPipelineCache, null, 0],
    20063: ["vkGetPipelineCacheData", d_vkGetPipelineCacheData, e_vkGetPipelineCacheData, 0],
    20064: ["vkMergePipelineCaches", d_vkMergePipelineCaches, e_vkMergePipelineCaches, 0],
    20065: ["vkCreateGraphicsPipelines", d_vkCreateGraphicsPipelines, e_vkCreateGraphicsPipelines, 0, ["pPipelines"]],
    20066: ["vkCreateComputePipelines", d_vkCreateComputePipelines, e_vkCreateComputePipelines, 0, ["pPipelines"]],
    20067: ["vkDestroyPipeline", d_vkDestroyPipeline, null, 0],
    20068: ["vkCreatePipelineLayout", d_vkCreatePipelineLayout, e_vkCreatePipelineLayout, 0, ["pPipelineLayout"]],
    20069: ["vkDestroyPipelineLayout", d_vkDestroyPipelineLayout, null, 0],
    20070: ["vkCreateSampler", d_vkCreateSampler, e_vkCreateSampler, 0, ["pSampler"]],
    20071: ["vkDestroySampler", d_vkDestroySampler, null, 0],
    20072: ["vkCreateDescriptorSetLayout", d_vkCreateDescriptorSetLayout, e_vkCreateDescriptorSetLayout, 0, ["pSetLayout"]],
    20073: ["vkDestroyDescriptorSetLayout", d_vkDestroyDescriptorSetLayout, null, 0],
    20074: ["vkCreateDescriptorPool", d_vkCreateDescriptorPool, e_vkCreateDescriptorPool, 0, ["pDescriptorPool"]],
    20075: ["vkDestroyDescriptorPool", d_vkDestroyDescriptorPool, null, 0],
    20076: ["vkResetDescriptorPool", d_vkResetDescriptorPool, e_vkResetDescriptorPool, 0],
    20077: ["vkAllocateDescriptorSets", d_vkAllocateDescriptorSets, e_vkAllocateDescriptorSets, 0, ["pDescriptorSets"]],
    20078: ["vkFreeDescriptorSets", d_vkFreeDescriptorSets, e_vkFreeDescriptorSets, 0],
    20079: ["vkUpdateDescriptorSets", d_vkUpdateDescriptorSets, null, 0],
    20080: ["vkCreateFramebuffer", d_vkCreateFramebuffer, e_vkCreateFramebuffer, 0, ["pFramebuffer"]],
    20081: ["vkDestroyFramebuffer", d_vkDestroyFramebuffer, null, 0],
    20082: ["vkCreateRenderPass", d_vkCreateRenderPass, e_vkCreateRenderPass, 0, ["pRenderPass"]],
    20083: ["vkDestroyRenderPass", d_vkDestroyRenderPass, null, 0],
    20084: ["vkGetRenderAreaGranularity", d_vkGetRenderAreaGranularity, e_vkGetRenderAreaGranularity, 0],
    20085: ["vkCreateCommandPool", d_vkCreateCommandPool, e_vkCreateCommandPool, 0, ["pCommandPool"]],
    20086: ["vkDestroyCommandPool", d_vkDestroyCommandPool, null, 0],
    20087: ["vkResetCommandPool", d_vkResetCommandPool, e_vkResetCommandPool, 0],
    20088: ["vkAllocateCommandBuffers", d_vkAllocateCommandBuffers, e_vkAllocateCommandBuffers, 0, ["pCommandBuffers"]],
    20089: ["vkFreeCommandBuffers", d_vkFreeCommandBuffers, null, 0],
    20090: ["vkBeginCommandBuffer", d_vkBeginCommandBuffer, e_vkBeginCommandBuffer, 1],
    20091: ["vkEndCommandBuffer", d_vkEndCommandBuffer, e_vkEndCommandBuffer, 1],
    20092: ["vkResetCommandBuffer", d_vkResetCommandBuffer, e_vkResetCommandBuffer, 1],
    20093: ["vkCmdBindPipeline", d_vkCmdBindPipeline, null, 1],
    20094: ["vkCmdSetViewport", d_vkCmdSetViewport, null, 1],
    20095: ["vkCmdSetScissor", d_vkCmdSetScissor, null, 1],
    20096: ["vkCmdSetLineWidth", d_vkCmdSetLineWidth, null, 1],
    20097: ["vkCmdSetDepthBias", d_vkCmdSetDepthBias, null, 1],
    20098: ["vkCmdSetBlendConstants", d_vkCmdSetBlendConstants, null, 1],
    20099: ["vkCmdSetDepthBounds", d_vkCmdSetDepthBounds, null, 1],
    20100: ["vkCmdSetStencilCompareMask", d_vkCmdSetStencilCompareMask, null, 1],
    20101: ["vkCmdSetStencilWriteMask", d_vkCmdSetStencilWriteMask, null, 1],
    20102: ["vkCmdSetStencilReference", d_vkCmdSetStencilReference, null, 1],
    20103: ["vkCmdBindDescriptorSets", d_vkCmdBindDescriptorSets, null, 1],
    20104: ["vkCmdBindIndexBuffer", d_vkCmdBindIndexBuffer, null, 1],
    20105: ["vkCmdBindVertexBuffers", d_vkCmdBindVertexBuffers, null, 1],
    20106: ["vkCmdDraw", d_vkCmdDraw, null, 1],
    20107: ["vkCmdDrawIndexed", d_vkCmdDrawIndexed, null, 1],
    20108: ["vkCmdDrawIndirect", d_vkCmdDrawIndirect, null, 1],
    20109: ["vkCmdDrawIndexedIndirect", d_vkCmdDrawIndexedIndirect, null, 1],
    20110: ["vkCmdDispatch", d_vkCmdDispatch, null, 1],
    20111: ["vkCmdDispatchIndirect", d_vkCmdDispatchIndirect, null, 1],
    20112: ["vkCmdCopyBuffer", d_vkCmdCopyBuffer, null, 1],
    20113: ["vkCmdCopyImage", d_vkCmdCopyImage, null, 1],
    20114: ["vkCmdBlitImage", d_vkCmdBlitImage, null, 1],
    20115: ["vkCmdCopyBufferToImage", d_vkCmdCopyBufferToImage, null, 1],
    20116: ["vkCmdCopyImageToBuffer", d_vkCmdCopyImageToBuffer, null, 1],
    20117: ["vkCmdUpdateBuffer", d_vkCmdUpdateBuffer, null, 1],
    20118: ["vkCmdFillBuffer", d_vkCmdFillBuffer, null, 1],
    20119: ["vkCmdClearColorImage", d_vkCmdClearColorImage, null, 1],
    20120: ["vkCmdClearDepthStencilImage", d_vkCmdClearDepthStencilImage, null, 1],
    20121: ["vkCmdClearAttachments", d_vkCmdClearAttachments, null, 1],
    20122: ["vkCmdResolveImage", d_vkCmdResolveImage, null, 1],
    20123: ["vkCmdSetEvent", d_vkCmdSetEvent, null, 1],
    20124: ["vkCmdResetEvent", d_vkCmdResetEvent, null, 1],
    20125: ["vkCmdWaitEvents", d_vkCmdWaitEvents, null, 1],
    20126: ["vkCmdPipelineBarrier", d_vkCmdPipelineBarrier, null, 1],
    20127: ["vkCmdBeginQuery", d_vkCmdBeginQuery, null, 1],
    20128: ["vkCmdEndQuery", d_vkCmdEndQuery, null, 1],
    20129: ["vkCmdResetQueryPool", d_vkCmdResetQueryPool, null, 1],
    20130: ["vkCmdWriteTimestamp", d_vkCmdWriteTimestamp, null, 1],
    20131: ["vkCmdCopyQueryPoolResults", d_vkCmdCopyQueryPoolResults, null, 1],
    20132: ["vkCmdPushConstants", d_vkCmdPushConstants, null, 1],
    20133: ["vkCmdBeginRenderPass", d_vkCmdBeginRenderPass, null, 1],
    20134: ["vkCmdNextSubpass", d_vkCmdNextSubpass, null, 1],
    20135: ["vkCmdEndRenderPass", d_vkCmdEndRenderPass, null, 1],
    20136: ["vkCmdExecuteCommands", d_vkCmdExecuteCommands, null, 1],
    20137: ["vkEnumerateInstanceVersion", d_vkEnumerateInstanceVersion, e_vkEnumerateInstanceVersion, 0],
    20138: ["vkBindBufferMemory2", d_vkBindBufferMemory2, e_vkBindBufferMemory2, 0],
    20139: ["vkBindImageMemory2", d_vkBindImageMemory2, e_vkBindImageMemory2, 0],
    20140: ["vkGetDeviceGroupPeerMemoryFeatures", d_vkGetDeviceGroupPeerMemoryFeatures, e_vkGetDeviceGroupPeerMemoryFeatures, 0],
    20141: ["vkCmdSetDeviceMask", d_vkCmdSetDeviceMask, null, 1],
    20142: ["vkCmdDispatchBase", d_vkCmdDispatchBase, null, 1],
    20143: ["vkEnumeratePhysicalDeviceGroups", d_vkEnumeratePhysicalDeviceGroups, e_vkEnumeratePhysicalDeviceGroups, 0],
    20144: ["vkGetImageMemoryRequirements2", d_vkGetImageMemoryRequirements2, e_vkGetImageMemoryRequirements2, 0],
    20145: ["vkGetBufferMemoryRequirements2", d_vkGetBufferMemoryRequirements2, e_vkGetBufferMemoryRequirements2, 0],
    20146: ["vkGetImageSparseMemoryRequirements2", d_vkGetImageSparseMemoryRequirements2, e_vkGetImageSparseMemoryRequirements2, 0],
    20147: ["vkGetPhysicalDeviceFeatures2", d_vkGetPhysicalDeviceFeatures2, e_vkGetPhysicalDeviceFeatures2, 0],
    20148: ["vkGetPhysicalDeviceProperties2", d_vkGetPhysicalDeviceProperties2, e_vkGetPhysicalDeviceProperties2, 0],
    20149: ["vkGetPhysicalDeviceFormatProperties2", d_vkGetPhysicalDeviceFormatProperties2, e_vkGetPhysicalDeviceFormatProperties2, 0],
    20150: ["vkGetPhysicalDeviceImageFormatProperties2", d_vkGetPhysicalDeviceImageFormatProperties2, e_vkGetPhysicalDeviceImageFormatProperties2, 0],
    20151: ["vkGetPhysicalDeviceQueueFamilyProperties2", d_vkGetPhysicalDeviceQueueFamilyProperties2, e_vkGetPhysicalDeviceQueueFamilyProperties2, 0],
    20152: ["vkGetPhysicalDeviceMemoryProperties2", d_vkGetPhysicalDeviceMemoryProperties2, e_vkGetPhysicalDeviceMemoryProperties2, 0],
    20153: ["vkGetPhysicalDeviceSparseImageFormatProperties2", d_vkGetPhysicalDeviceSparseImageFormatProperties2, e_vkGetPhysicalDeviceSparseImageFormatProperties2, 0],
    20154: ["vkTrimCommandPool", d_vkTrimCommandPool, null, 0],
    20155: ["vkGetDeviceQueue2", d_vkGetDeviceQueue2, e_vkGetDeviceQueue2, 0, ["pQueue"]],
    20156: ["vkCreateSamplerYcbcrConversion", d_vkCreateSamplerYcbcrConversion, e_vkCreateSamplerYcbcrConversion, 0, ["pYcbcrConversion"]],
    20157: ["vkDestroySamplerYcbcrConversion", d_vkDestroySamplerYcbcrConversion, null, 0],
    20158: ["vkCreateDescriptorUpdateTemplate", d_vkCreateDescriptorUpdateTemplate, e_vkCreateDescriptorUpdateTemplate, 0, ["pDescriptorUpdateTemplate"]],
    20159: ["vkDestroyDescriptorUpdateTemplate", d_vkDestroyDescriptorUpdateTemplate, null, 0],
    20160: ["vkUpdateDescriptorSetWithTemplate", d_vkUpdateDescriptorSetWithTemplate, null, 0],
    20161: ["vkGetPhysicalDeviceExternalBufferProperties", d_vkGetPhysicalDeviceExternalBufferProperties, e_vkGetPhysicalDeviceExternalBufferProperties, 0],
    20162: ["vkGetPhysicalDeviceExternalFenceProperties", d_vkGetPhysicalDeviceExternalFenceProperties, e_vkGetPhysicalDeviceExternalFenceProperties, 0],
    20163: ["vkGetPhysicalDeviceExternalSemaphoreProperties", d_vkGetPhysicalDeviceExternalSemaphoreProperties, e_vkGetPhysicalDeviceExternalSemaphoreProperties, 0],
    20164: ["vkGetDescriptorSetLayoutSupport", d_vkGetDescriptorSetLayoutSupport, e_vkGetDescriptorSetLayoutSupport, 0],
    282774587: ["vkCmdDrawIndirectCount", d_vkCmdDrawIndirectCount, null, 1],
    245204359: ["vkCmdDrawIndexedIndirectCount", d_vkCmdDrawIndexedIndirectCount, null, 1],
    279590827: ["vkCreateRenderPass2", d_vkCreateRenderPass2, e_vkCreateRenderPass2, 0, ["pRenderPass"]],
    235222847: ["vkCmdBeginRenderPass2", d_vkCmdBeginRenderPass2, null, 1],
    244873750: ["vkCmdNextSubpass2", d_vkCmdNextSubpass2, null, 1],
    221297834: ["vkCmdEndRenderPass2", d_vkCmdEndRenderPass2, null, 1],
    252097672: ["vkResetQueryPool", d_vkResetQueryPool, null, 0],
    267066974: ["vkGetSemaphoreCounterValue", d_vkGetSemaphoreCounterValue, e_vkGetSemaphoreCounterValue, 0],
    224777382: ["vkWaitSemaphores", d_vkWaitSemaphores, e_vkWaitSemaphores, 0],
    271024127: ["vkSignalSemaphore", d_vkSignalSemaphore, e_vkSignalSemaphore, 0],
    222632266: ["vkGetBufferDeviceAddress", d_vkGetBufferDeviceAddress, e_vkGetBufferDeviceAddress, 0],
    230188231: ["vkGetBufferOpaqueCaptureAddress", d_vkGetBufferOpaqueCaptureAddress, e_vkGetBufferOpaqueCaptureAddress, 0],
    260620079: ["vkGetDeviceMemoryOpaqueCaptureAddress", d_vkGetDeviceMemoryOpaqueCaptureAddress, e_vkGetDeviceMemoryOpaqueCaptureAddress, 0],
    286895278: ["vkGetPhysicalDeviceToolProperties", d_vkGetPhysicalDeviceToolProperties, e_vkGetPhysicalDeviceToolProperties, 0],
    262776916: ["vkCreatePrivateDataSlot", d_vkCreatePrivateDataSlot, e_vkCreatePrivateDataSlot, 0, ["pPrivateDataSlot"]],
    224520231: ["vkDestroyPrivateDataSlot", d_vkDestroyPrivateDataSlot, null, 0],
    242146991: ["vkSetPrivateData", d_vkSetPrivateData, e_vkSetPrivateData, 0],
    237052348: ["vkGetPrivateData", d_vkGetPrivateData, e_vkGetPrivateData, 0],
    232259114: ["vkCmdSetEvent2", d_vkCmdSetEvent2, null, 1],
    271973131: ["vkCmdResetEvent2", d_vkCmdResetEvent2, null, 1],
    244672720: ["vkCmdWaitEvents2", d_vkCmdWaitEvents2, null, 1],
    296709912: ["vkCmdPipelineBarrier2", d_vkCmdPipelineBarrier2, null, 1],
    246322283: ["vkCmdWriteTimestamp2", d_vkCmdWriteTimestamp2, null, 1],
    275454371: ["vkQueueSubmit2", d_vkQueueSubmit2, e_vkQueueSubmit2, 0],
    236505336: ["vkCmdCopyBuffer2", d_vkCmdCopyBuffer2, null, 1],
    247540368: ["vkCmdCopyImage2", d_vkCmdCopyImage2, null, 1],
    267966219: ["vkCmdCopyBufferToImage2", d_vkCmdCopyBufferToImage2, null, 1],
    215156661: ["vkCmdCopyImageToBuffer2", d_vkCmdCopyImageToBuffer2, null, 1],
    275239053: ["vkCmdBlitImage2", d_vkCmdBlitImage2, null, 1],
    282440329: ["vkCmdResolveImage2", d_vkCmdResolveImage2, null, 1],
    294618673: ["vkCmdBeginRendering", d_vkCmdBeginRendering, null, 1],
    220725158: ["vkCmdEndRendering", d_vkCmdEndRendering, null, 1],
    224605861: ["vkCmdSetCullMode", d_vkCmdSetCullMode, null, 1],
    223122493: ["vkCmdSetFrontFace", d_vkCmdSetFrontFace, null, 1],
    263054804: ["vkCmdSetPrimitiveTopology", d_vkCmdSetPrimitiveTopology, null, 1],
    267390210: ["vkCmdSetViewportWithCount", d_vkCmdSetViewportWithCount, null, 1],
    219934891: ["vkCmdSetScissorWithCount", d_vkCmdSetScissorWithCount, null, 1],
    258656493: ["vkCmdBindVertexBuffers2", d_vkCmdBindVertexBuffers2, null, 1],
    209714588: ["vkCmdSetDepthTestEnable", d_vkCmdSetDepthTestEnable, null, 1],
    240260392: ["vkCmdSetDepthWriteEnable", d_vkCmdSetDepthWriteEnable, null, 1],
    245341736: ["vkCmdSetDepthCompareOp", d_vkCmdSetDepthCompareOp, null, 1],
    219709826: ["vkCmdSetDepthBoundsTestEnable", d_vkCmdSetDepthBoundsTestEnable, null, 1],
    286845216: ["vkCmdSetStencilTestEnable", d_vkCmdSetStencilTestEnable, null, 1],
    235751186: ["vkCmdSetStencilOp", d_vkCmdSetStencilOp, null, 1],
    276298238: ["vkCmdSetRasterizerDiscardEnable", d_vkCmdSetRasterizerDiscardEnable, null, 1],
    267154733: ["vkCmdSetDepthBiasEnable", d_vkCmdSetDepthBiasEnable, null, 1],
    230252008: ["vkCmdSetPrimitiveRestartEnable", d_vkCmdSetPrimitiveRestartEnable, null, 1],
    294177590: ["vkGetDeviceBufferMemoryRequirements", d_vkGetDeviceBufferMemoryRequirements, e_vkGetDeviceBufferMemoryRequirements, 0],
    282480635: ["vkGetDeviceImageMemoryRequirements", d_vkGetDeviceImageMemoryRequirements, e_vkGetDeviceImageMemoryRequirements, 0],
    233707261: ["vkGetDeviceImageSparseMemoryRequirements", d_vkGetDeviceImageSparseMemoryRequirements, e_vkGetDeviceImageSparseMemoryRequirements, 0],
    235403148: ["vkCmdSetLineStipple", d_vkCmdSetLineStipple, null, 1],
    269932043: ["vkMapMemory2", d_vkMapMemory2, e_vkMapMemory2, 0],
    229872812: ["vkUnmapMemory2", d_vkUnmapMemory2, e_vkUnmapMemory2, 0],
    206158434: ["vkCmdBindIndexBuffer2", d_vkCmdBindIndexBuffer2, null, 1],
    214660941: ["vkGetRenderingAreaGranularity", d_vkGetRenderingAreaGranularity, e_vkGetRenderingAreaGranularity, 0],
    216549053: ["vkGetDeviceImageSubresourceLayout", d_vkGetDeviceImageSubresourceLayout, e_vkGetDeviceImageSubresourceLayout, 0],
    269545412: ["vkGetImageSubresourceLayout2", d_vkGetImageSubresourceLayout2, e_vkGetImageSubresourceLayout2, 0],
    246922559: ["vkCmdPushDescriptorSet", d_vkCmdPushDescriptorSet, null, 1],
    229886695: ["vkCmdPushDescriptorSetWithTemplate", d_vkCmdPushDescriptorSetWithTemplate, null, 1],
    204730753: ["vkCmdSetRenderingAttachmentLocations", d_vkCmdSetRenderingAttachmentLocations, null, 1],
    285610580: ["vkCmdSetRenderingInputAttachmentIndices", d_vkCmdSetRenderingInputAttachmentIndices, null, 1],
    281461882: ["vkCmdBindDescriptorSets2", d_vkCmdBindDescriptorSets2, null, 1],
    275905655: ["vkCmdPushConstants2", d_vkCmdPushConstants2, null, 1],
    269912858: ["vkCmdPushDescriptorSet2", d_vkCmdPushDescriptorSet2, null, 1],
    285015421: ["vkCmdPushDescriptorSetWithTemplate2", d_vkCmdPushDescriptorSetWithTemplate2, null, 1],
    263029492: ["vkCopyMemoryToImage", d_vkCopyMemoryToImage, e_vkCopyMemoryToImage, 0],
    204990977: ["vkCopyImageToMemory", d_vkCopyImageToMemory, e_vkCopyImageToMemory, 0],
    223491795: ["vkCopyImageToImage", d_vkCopyImageToImage, e_vkCopyImageToImage, 0],
    252133608: ["vkTransitionImageLayout", d_vkTransitionImageLayout, e_vkTransitionImageLayout, 0],
    298092805: ["vkCmdBeginRenderingKHR", d_vkCmdBeginRenderingKHR, null, 1],
    200651584: ["vkCmdEndRenderingKHR", d_vkCmdEndRenderingKHR, null, 1],
    20198: ["vkGetPhysicalDeviceFeatures2KHR", d_vkGetPhysicalDeviceFeatures2KHR, e_vkGetPhysicalDeviceFeatures2KHR, 0],
    20199: ["vkGetPhysicalDeviceProperties2KHR", d_vkGetPhysicalDeviceProperties2KHR, e_vkGetPhysicalDeviceProperties2KHR, 0],
    20200: ["vkGetPhysicalDeviceFormatProperties2KHR", d_vkGetPhysicalDeviceFormatProperties2KHR, e_vkGetPhysicalDeviceFormatProperties2KHR, 0],
    20201: ["vkGetPhysicalDeviceImageFormatProperties2KHR", d_vkGetPhysicalDeviceImageFormatProperties2KHR, e_vkGetPhysicalDeviceImageFormatProperties2KHR, 0],
    20202: ["vkGetPhysicalDeviceQueueFamilyProperties2KHR", d_vkGetPhysicalDeviceQueueFamilyProperties2KHR, e_vkGetPhysicalDeviceQueueFamilyProperties2KHR, 0],
    20203: ["vkGetPhysicalDeviceMemoryProperties2KHR", d_vkGetPhysicalDeviceMemoryProperties2KHR, e_vkGetPhysicalDeviceMemoryProperties2KHR, 0],
    20204: ["vkGetPhysicalDeviceSparseImageFormatProperties2KHR", d_vkGetPhysicalDeviceSparseImageFormatProperties2KHR, e_vkGetPhysicalDeviceSparseImageFormatProperties2KHR, 0],
    20208: ["vkTrimCommandPoolKHR", d_vkTrimCommandPoolKHR, null, 0],
    20210: ["vkGetPhysicalDeviceExternalBufferPropertiesKHR", d_vkGetPhysicalDeviceExternalBufferPropertiesKHR, e_vkGetPhysicalDeviceExternalBufferPropertiesKHR, 0],
    20215: ["vkGetPhysicalDeviceExternalSemaphorePropertiesKHR", d_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR, e_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR, 0],
    20218: ["vkImportSemaphoreFdKHR", d_vkImportSemaphoreFdKHR, e_vkImportSemaphoreFdKHR, 0],
    20219: ["vkGetSemaphoreFdKHR", d_vkGetSemaphoreFdKHR, e_vkGetSemaphoreFdKHR, 0],
    20222: ["vkCreateDescriptorUpdateTemplateKHR", d_vkCreateDescriptorUpdateTemplateKHR, e_vkCreateDescriptorUpdateTemplateKHR, 0, ["pDescriptorUpdateTemplate"]],
    20223: ["vkDestroyDescriptorUpdateTemplateKHR", d_vkDestroyDescriptorUpdateTemplateKHR, null, 0],
    20224: ["vkUpdateDescriptorSetWithTemplateKHR", d_vkUpdateDescriptorSetWithTemplateKHR, null, 0],
    20225: ["vkCreateRenderPass2KHR", d_vkCreateRenderPass2KHR, e_vkCreateRenderPass2KHR, 0, ["pRenderPass"]],
    20226: ["vkCmdBeginRenderPass2KHR", d_vkCmdBeginRenderPass2KHR, null, 1],
    20227: ["vkCmdNextSubpass2KHR", d_vkCmdNextSubpass2KHR, null, 1],
    20228: ["vkCmdEndRenderPass2KHR", d_vkCmdEndRenderPass2KHR, null, 1],
    20230: ["vkGetPhysicalDeviceExternalFencePropertiesKHR", d_vkGetPhysicalDeviceExternalFencePropertiesKHR, e_vkGetPhysicalDeviceExternalFencePropertiesKHR, 0],
    20233: ["vkImportFenceFdKHR", d_vkImportFenceFdKHR, e_vkImportFenceFdKHR, 0],
    20234: ["vkGetFenceFdKHR", d_vkGetFenceFdKHR, e_vkGetFenceFdKHR, 0],
    20241: ["vkGetImageMemoryRequirements2KHR", d_vkGetImageMemoryRequirements2KHR, e_vkGetImageMemoryRequirements2KHR, 0],
    20242: ["vkGetBufferMemoryRequirements2KHR", d_vkGetBufferMemoryRequirements2KHR, e_vkGetBufferMemoryRequirements2KHR, 0],
    20243: ["vkGetImageSparseMemoryRequirements2KHR", d_vkGetImageSparseMemoryRequirements2KHR, e_vkGetImageSparseMemoryRequirements2KHR, 0],
    20244: ["vkCreateSamplerYcbcrConversionKHR", d_vkCreateSamplerYcbcrConversionKHR, e_vkCreateSamplerYcbcrConversionKHR, 0, ["pYcbcrConversion"]],
    20245: ["vkDestroySamplerYcbcrConversionKHR", d_vkDestroySamplerYcbcrConversionKHR, null, 0],
    20246: ["vkBindBufferMemory2KHR", d_vkBindBufferMemory2KHR, e_vkBindBufferMemory2KHR, 0],
    20247: ["vkBindImageMemory2KHR", d_vkBindImageMemory2KHR, e_vkBindImageMemory2KHR, 0],
    20248: ["vkGetDescriptorSetLayoutSupportKHR", d_vkGetDescriptorSetLayoutSupportKHR, e_vkGetDescriptorSetLayoutSupportKHR, 0],
    219261480: ["vkGetBufferDeviceAddressKHR", d_vkGetBufferDeviceAddressKHR, e_vkGetBufferDeviceAddressKHR, 0],
    285631711: ["vkGetBufferOpaqueCaptureAddressKHR", d_vkGetBufferOpaqueCaptureAddressKHR, e_vkGetBufferOpaqueCaptureAddressKHR, 0],
    294671624: ["vkGetDeviceMemoryOpaqueCaptureAddressKHR", d_vkGetDeviceMemoryOpaqueCaptureAddressKHR, e_vkGetDeviceMemoryOpaqueCaptureAddressKHR, 0],
    269458798: ["vkGetPipelineExecutablePropertiesKHR", d_vkGetPipelineExecutablePropertiesKHR, e_vkGetPipelineExecutablePropertiesKHR, 0],
    271191699: ["vkGetPipelineExecutableStatisticsKHR", d_vkGetPipelineExecutableStatisticsKHR, e_vkGetPipelineExecutableStatisticsKHR, 0],
    274148497: ["vkGetPipelineExecutableInternalRepresentationsKHR", d_vkGetPipelineExecutableInternalRepresentationsKHR, e_vkGetPipelineExecutableInternalRepresentationsKHR, 0],
    270411360: ["vkCmdSetEvent2KHR", d_vkCmdSetEvent2KHR, null, 1],
    283215906: ["vkCmdResetEvent2KHR", d_vkCmdResetEvent2KHR, null, 1],
    244967758: ["vkCmdWaitEvents2KHR", d_vkCmdWaitEvents2KHR, null, 1],
    201310066: ["vkCmdPipelineBarrier2KHR", d_vkCmdPipelineBarrier2KHR, null, 1],
    252552241: ["vkCmdWriteTimestamp2KHR", d_vkCmdWriteTimestamp2KHR, null, 1],
    293024240: ["vkQueueSubmit2KHR", d_vkQueueSubmit2KHR, e_vkQueueSubmit2KHR, 0],
    247893766: ["vkCmdCopyBuffer2KHR", d_vkCmdCopyBuffer2KHR, null, 1],
    227008250: ["vkCmdCopyImage2KHR", d_vkCmdCopyImage2KHR, null, 1],
    248841963: ["vkCmdCopyBufferToImage2KHR", d_vkCmdCopyBufferToImage2KHR, null, 1],
    252249060: ["vkCmdCopyImageToBuffer2KHR", d_vkCmdCopyImageToBuffer2KHR, null, 1],
    259838288: ["vkCmdBlitImage2KHR", d_vkCmdBlitImage2KHR, null, 1],
    254857232: ["vkCmdResolveImage2KHR", d_vkCmdResolveImage2KHR, null, 1],
    201613635: ["vkGetDeviceBufferMemoryRequirementsKHR", d_vkGetDeviceBufferMemoryRequirementsKHR, e_vkGetDeviceBufferMemoryRequirementsKHR, 0],
    243155021: ["vkGetDeviceImageMemoryRequirementsKHR", d_vkGetDeviceImageMemoryRequirementsKHR, e_vkGetDeviceImageMemoryRequirementsKHR, 0],
    275585477: ["vkGetDeviceImageSparseMemoryRequirementsKHR", d_vkGetDeviceImageSparseMemoryRequirementsKHR, e_vkGetDeviceImageSparseMemoryRequirementsKHR, 0],
    202856085: ["vkCmdBindIndexBuffer2KHR", d_vkCmdBindIndexBuffer2KHR, null, 1],
    238658496: ["vkGetRenderingAreaGranularityKHR", d_vkGetRenderingAreaGranularityKHR, e_vkGetRenderingAreaGranularityKHR, 0],
    252830318: ["vkGetDeviceImageSubresourceLayoutKHR", d_vkGetDeviceImageSubresourceLayoutKHR, e_vkGetDeviceImageSubresourceLayoutKHR, 0],
    243334937: ["vkGetImageSubresourceLayout2KHR", d_vkGetImageSubresourceLayout2KHR, e_vkGetImageSubresourceLayout2KHR, 0],
    219923286: ["vkCmdSetLineStippleKHR", d_vkCmdSetLineStippleKHR, null, 1],
    20251: ["vkGetSwapchainGrallocUsageANDROID", d_vkGetSwapchainGrallocUsageANDROID, e_vkGetSwapchainGrallocUsageANDROID, 0],
    20252: ["vkAcquireImageANDROID", d_vkAcquireImageANDROID, e_vkAcquireImageANDROID, 0],
    20253: ["vkQueueSignalReleaseImageANDROID", d_vkQueueSignalReleaseImageANDROID, e_vkQueueSignalReleaseImageANDROID, 0],
    287960452: ["vkGetSwapchainGrallocUsage2ANDROID", d_vkGetSwapchainGrallocUsage2ANDROID, e_vkGetSwapchainGrallocUsage2ANDROID, 0],
    267779978: ["vkCmdBindTransformFeedbackBuffersEXT", d_vkCmdBindTransformFeedbackBuffersEXT, null, 1],
    294396901: ["vkCmdBeginTransformFeedbackEXT", d_vkCmdBeginTransformFeedbackEXT, null, 1],
    272333731: ["vkCmdEndTransformFeedbackEXT", d_vkCmdEndTransformFeedbackEXT, null, 1],
    275810601: ["vkCmdBeginQueryIndexedEXT", d_vkCmdBeginQueryIndexedEXT, null, 1],
    279821337: ["vkCmdEndQueryIndexedEXT", d_vkCmdEndQueryIndexedEXT, null, 1],
    285235943: ["vkCmdDrawIndirectByteCountEXT", d_vkCmdDrawIndirectByteCountEXT, null, 1],
    251301237: ["vkGetImageDrmFormatModifierPropertiesEXT", d_vkGetImageDrmFormatModifierPropertiesEXT, e_vkGetImageDrmFormatModifierPropertiesEXT, 0],
    282247593: ["vkGetPhysicalDeviceToolPropertiesEXT", d_vkGetPhysicalDeviceToolPropertiesEXT, e_vkGetPhysicalDeviceToolPropertiesEXT, 0],
    263855692: ["vkCmdSetLineStippleEXT", d_vkCmdSetLineStippleEXT, null, 1],
    266285895: ["vkCmdSetCullModeEXT", d_vkCmdSetCullModeEXT, null, 1],
    212644406: ["vkCmdSetFrontFaceEXT", d_vkCmdSetFrontFaceEXT, null, 1],
    260783979: ["vkCmdSetPrimitiveTopologyEXT", d_vkCmdSetPrimitiveTopologyEXT, null, 1],
    257105245: ["vkCmdSetViewportWithCountEXT", d_vkCmdSetViewportWithCountEXT, null, 1],
    204588120: ["vkCmdSetScissorWithCountEXT", d_vkCmdSetScissorWithCountEXT, null, 1],
    243419921: ["vkCmdBindVertexBuffers2EXT", d_vkCmdBindVertexBuffers2EXT, null, 1],
    233771166: ["vkCmdSetDepthTestEnableEXT", d_vkCmdSetDepthTestEnableEXT, null, 1],
    218663304: ["vkCmdSetDepthWriteEnableEXT", d_vkCmdSetDepthWriteEnableEXT, null, 1],
    247761589: ["vkCmdSetDepthCompareOpEXT", d_vkCmdSetDepthCompareOpEXT, null, 1],
    223213519: ["vkCmdSetDepthBoundsTestEnableEXT", d_vkCmdSetDepthBoundsTestEnableEXT, null, 1],
    286438749: ["vkCmdSetStencilTestEnableEXT", d_vkCmdSetStencilTestEnableEXT, null, 1],
    277159578: ["vkCmdSetStencilOpEXT", d_vkCmdSetStencilOpEXT, null, 1],
    218832495: ["vkCopyMemoryToImageEXT", d_vkCopyMemoryToImageEXT, e_vkCopyMemoryToImageEXT, 0],
    204695490: ["vkCopyImageToMemoryEXT", d_vkCopyImageToMemoryEXT, e_vkCopyImageToMemoryEXT, 0],
    223534798: ["vkCopyImageToImageEXT", d_vkCopyImageToImageEXT, e_vkCopyImageToImageEXT, 0],
    242817558: ["vkTransitionImageLayoutEXT", d_vkTransitionImageLayoutEXT, e_vkTransitionImageLayoutEXT, 0],
    296152177: ["vkGetImageSubresourceLayout2EXT", d_vkGetImageSubresourceLayout2EXT, e_vkGetImageSubresourceLayout2EXT, 0],
    236374049: ["vkCreatePrivateDataSlotEXT", d_vkCreatePrivateDataSlotEXT, e_vkCreatePrivateDataSlotEXT, 0, ["pPrivateDataSlot"]],
    208891309: ["vkDestroyPrivateDataSlotEXT", d_vkDestroyPrivateDataSlotEXT, null, 0],
    225259406: ["vkSetPrivateDataEXT", d_vkSetPrivateDataEXT, e_vkSetPrivateDataEXT, 0],
    291399427: ["vkGetPrivateDataEXT", d_vkGetPrivateDataEXT, e_vkGetPrivateDataEXT, 0],
    208680354: ["vkCmdSetPatchControlPointsEXT", d_vkCmdSetPatchControlPointsEXT, null, 1],
    245221405: ["vkCmdSetRasterizerDiscardEnableEXT", d_vkCmdSetRasterizerDiscardEnableEXT, null, 1],
    259472348: ["vkCmdSetDepthBiasEnableEXT", d_vkCmdSetDepthBiasEnableEXT, null, 1],
    267481927: ["vkCmdSetLogicOpEXT", d_vkCmdSetLogicOpEXT, null, 1],
    299567883: ["vkCmdSetPrimitiveRestartEnableEXT", d_vkCmdSetPrimitiveRestartEnableEXT, null, 1],
    202223297: ["vkCmdSetColorWriteEnableEXT", d_vkCmdSetColorWriteEnableEXT, null, 1],
    20317: ["vkMapMemoryIntoAddressSpaceGOOGLE", d_vkMapMemoryIntoAddressSpaceGOOGLE, e_vkMapMemoryIntoAddressSpaceGOOGLE, 0],
    20320: ["vkUpdateDescriptorSetWithTemplateSizedGOOGLE", d_vkUpdateDescriptorSetWithTemplateSizedGOOGLE, null, 0],
    20321: ["vkBeginCommandBufferAsyncGOOGLE", d_vkBeginCommandBufferAsyncGOOGLE, null, 1],
    20322: ["vkEndCommandBufferAsyncGOOGLE", d_vkEndCommandBufferAsyncGOOGLE, null, 1],
    20323: ["vkResetCommandBufferAsyncGOOGLE", d_vkResetCommandBufferAsyncGOOGLE, null, 1],
    20324: ["vkCommandBufferHostSyncGOOGLE", d_vkCommandBufferHostSyncGOOGLE, null, 1],
    20325: ["vkCreateImageWithRequirementsGOOGLE", d_vkCreateImageWithRequirementsGOOGLE, e_vkCreateImageWithRequirementsGOOGLE, 0, ["pImage"]],
    20326: ["vkCreateBufferWithRequirementsGOOGLE", d_vkCreateBufferWithRequirementsGOOGLE, e_vkCreateBufferWithRequirementsGOOGLE, 0, ["pBuffer"]],
    20327: ["vkGetMemoryHostAddressInfoGOOGLE", d_vkGetMemoryHostAddressInfoGOOGLE, e_vkGetMemoryHostAddressInfoGOOGLE, 0],
    20328: ["vkFreeMemorySyncGOOGLE", d_vkFreeMemorySyncGOOGLE, e_vkFreeMemorySyncGOOGLE, 0],
    20329: ["vkQueueHostSyncGOOGLE", d_vkQueueHostSyncGOOGLE, null, 0],
    20330: ["vkQueueSubmitAsyncGOOGLE", d_vkQueueSubmitAsyncGOOGLE, null, 0],
    20331: ["vkQueueWaitIdleAsyncGOOGLE", d_vkQueueWaitIdleAsyncGOOGLE, null, 0],
    20332: ["vkQueueBindSparseAsyncGOOGLE", d_vkQueueBindSparseAsyncGOOGLE, null, 0],
    20333: ["vkGetLinearImageLayoutGOOGLE", d_vkGetLinearImageLayoutGOOGLE, e_vkGetLinearImageLayoutGOOGLE, 0],
    282325414: ["vkGetLinearImageLayout2GOOGLE", d_vkGetLinearImageLayout2GOOGLE, e_vkGetLinearImageLayout2GOOGLE, 0],
    20340: ["vkQueueFlushCommandsGOOGLE", d_vkQueueFlushCommandsGOOGLE, null, 0],
    267932433: ["vkQueueCommitDescriptorSetUpdatesGOOGLE", d_vkQueueCommitDescriptorSetUpdatesGOOGLE, null, 0],
    213659202: ["vkCollectDescriptorPoolIdsGOOGLE", d_vkCollectDescriptorPoolIdsGOOGLE, e_vkCollectDescriptorPoolIdsGOOGLE, 0],
    243985229: ["vkQueueSignalReleaseImageANDROIDAsyncGOOGLE", d_vkQueueSignalReleaseImageANDROIDAsyncGOOGLE, null, 0],
    290633483: ["vkQueueFlushCommandsFromAuxMemoryGOOGLE", d_vkQueueFlushCommandsFromAuxMemoryGOOGLE, null, 0],
    20341: ["vkGetBlobGOOGLE", d_vkGetBlobGOOGLE, e_vkGetBlobGOOGLE, 0],
    244782974: ["vkUpdateDescriptorSetWithTemplateSized2GOOGLE", d_vkUpdateDescriptorSetWithTemplateSized2GOOGLE, null, 0],
    292092830: ["vkQueueSubmitAsync2GOOGLE", d_vkQueueSubmitAsync2GOOGLE, null, 0],
    20342: ["vkGetSemaphoreGOOGLE", d_vkGetSemaphoreGOOGLE, e_vkGetSemaphoreGOOGLE, 0],
    286553566: ["vkTraceAsyncGOOGLE", d_vkTraceAsyncGOOGLE, null, 0],
};

/** the structs by name (tests): [decode in a request, encode in a reply] */
export const STRUCTS = {
    VkAllocationCallbacks: [d_VkAllocationCallbacks, null],
    VkApplicationInfo: [d_VkApplicationInfo, null],
    VkAttachmentDescription: [d_VkAttachmentDescription, null],
    VkAttachmentDescription2: [d_VkAttachmentDescription2, null],
    VkAttachmentDescriptionStencilLayout: [d_VkAttachmentDescriptionStencilLayout, e_VkAttachmentDescriptionStencilLayout],
    VkAttachmentReference: [d_VkAttachmentReference, e_VkAttachmentReference],
    VkAttachmentReference2: [d_VkAttachmentReference2, e_VkAttachmentReference2],
    VkAttachmentReferenceStencilLayout: [d_VkAttachmentReferenceStencilLayout, e_VkAttachmentReferenceStencilLayout],
    VkBindBufferMemoryDeviceGroupInfo: [d_VkBindBufferMemoryDeviceGroupInfo, e_VkBindBufferMemoryDeviceGroupInfo],
    VkBindBufferMemoryInfo: [d_VkBindBufferMemoryInfo, null],
    VkBindDescriptorSetsInfo: [d_VkBindDescriptorSetsInfo, null],
    VkBindImageMemoryDeviceGroupInfo: [d_VkBindImageMemoryDeviceGroupInfo, e_VkBindImageMemoryDeviceGroupInfo],
    VkBindImageMemoryInfo: [d_VkBindImageMemoryInfo, null],
    VkBindImagePlaneMemoryInfo: [d_VkBindImagePlaneMemoryInfo, e_VkBindImagePlaneMemoryInfo],
    VkBindMemoryStatus: [d_VkBindMemoryStatus, e_VkBindMemoryStatus],
    VkBindSparseInfo: [d_VkBindSparseInfo, null],
    VkBlitImageInfo2: [d_VkBlitImageInfo2, null],
    VkBufferCopy: [d_VkBufferCopy, null],
    VkBufferCopy2: [d_VkBufferCopy2, null],
    VkBufferCreateInfo: [d_VkBufferCreateInfo, null],
    VkBufferDeviceAddressInfo: [d_VkBufferDeviceAddressInfo, null],
    VkBufferImageCopy: [d_VkBufferImageCopy, null],
    VkBufferImageCopy2: [d_VkBufferImageCopy2, null],
    VkBufferMemoryBarrier: [d_VkBufferMemoryBarrier, null],
    VkBufferMemoryBarrier2: [d_VkBufferMemoryBarrier2, null],
    VkBufferMemoryRequirementsInfo2: [d_VkBufferMemoryRequirementsInfo2, null],
    VkBufferOpaqueCaptureAddressCreateInfo: [d_VkBufferOpaqueCaptureAddressCreateInfo, e_VkBufferOpaqueCaptureAddressCreateInfo],
    VkBufferUsageFlags2CreateInfo: [d_VkBufferUsageFlags2CreateInfo, e_VkBufferUsageFlags2CreateInfo],
    VkBufferViewCreateInfo: [d_VkBufferViewCreateInfo, null],
    VkClearAttachment: [d_VkClearAttachment, null],
    VkClearColorValue: [d_VkClearColorValue, e_VkClearColorValue],
    VkClearDepthStencilValue: [d_VkClearDepthStencilValue, null],
    VkClearRect: [d_VkClearRect, null],
    VkClearValue: [d_VkClearValue, null],
    VkCommandBufferAllocateInfo: [d_VkCommandBufferAllocateInfo, null],
    VkCommandBufferBeginInfo: [d_VkCommandBufferBeginInfo, null],
    VkCommandBufferInheritanceInfo: [d_VkCommandBufferInheritanceInfo, null],
    VkCommandBufferInheritanceRenderingInfo: [d_VkCommandBufferInheritanceRenderingInfo, e_VkCommandBufferInheritanceRenderingInfo],
    VkCommandBufferSubmitInfo: [d_VkCommandBufferSubmitInfo, null],
    VkCommandPoolCreateInfo: [d_VkCommandPoolCreateInfo, null],
    VkComponentMapping: [d_VkComponentMapping, null],
    VkComputePipelineCreateInfo: [d_VkComputePipelineCreateInfo, null],
    VkConformanceVersion: [d_VkConformanceVersion, e_VkConformanceVersion],
    VkCopyBufferInfo2: [d_VkCopyBufferInfo2, null],
    VkCopyBufferToImageInfo2: [d_VkCopyBufferToImageInfo2, null],
    VkCopyDescriptorSet: [d_VkCopyDescriptorSet, null],
    VkCopyImageInfo2: [d_VkCopyImageInfo2, null],
    VkCopyImageToBufferInfo2: [d_VkCopyImageToBufferInfo2, null],
    VkCopyImageToImageInfo: [d_VkCopyImageToImageInfo, null],
    VkCopyImageToMemoryInfo: [d_VkCopyImageToMemoryInfo, null],
    VkCopyMemoryToImageInfo: [d_VkCopyMemoryToImageInfo, null],
    VkCreateBlobGOOGLE: [d_VkCreateBlobGOOGLE, e_VkCreateBlobGOOGLE],
    VkDependencyInfo: [d_VkDependencyInfo, null],
    VkDescriptorBufferInfo: [d_VkDescriptorBufferInfo, null],
    VkDescriptorImageInfo: [d_VkDescriptorImageInfo, null],
    VkDescriptorPoolCreateInfo: [d_VkDescriptorPoolCreateInfo, null],
    VkDescriptorPoolInlineUniformBlockCreateInfo: [d_VkDescriptorPoolInlineUniformBlockCreateInfo, e_VkDescriptorPoolInlineUniformBlockCreateInfo],
    VkDescriptorPoolSize: [d_VkDescriptorPoolSize, null],
    VkDescriptorSetAllocateInfo: [d_VkDescriptorSetAllocateInfo, null],
    VkDescriptorSetLayoutBinding: [d_VkDescriptorSetLayoutBinding, null],
    VkDescriptorSetLayoutBindingFlagsCreateInfo: [d_VkDescriptorSetLayoutBindingFlagsCreateInfo, e_VkDescriptorSetLayoutBindingFlagsCreateInfo],
    VkDescriptorSetLayoutCreateInfo: [d_VkDescriptorSetLayoutCreateInfo, null],
    VkDescriptorSetLayoutSupport: [d_VkDescriptorSetLayoutSupport, e_VkDescriptorSetLayoutSupport],
    VkDescriptorSetVariableDescriptorCountAllocateInfo: [d_VkDescriptorSetVariableDescriptorCountAllocateInfo, e_VkDescriptorSetVariableDescriptorCountAllocateInfo],
    VkDescriptorSetVariableDescriptorCountLayoutSupport: [d_VkDescriptorSetVariableDescriptorCountLayoutSupport, e_VkDescriptorSetVariableDescriptorCountLayoutSupport],
    VkDescriptorUpdateTemplateCreateInfo: [d_VkDescriptorUpdateTemplateCreateInfo, null],
    VkDescriptorUpdateTemplateEntry: [d_VkDescriptorUpdateTemplateEntry, null],
    VkDeviceBufferMemoryRequirements: [d_VkDeviceBufferMemoryRequirements, null],
    VkDeviceCreateInfo: [d_VkDeviceCreateInfo, null],
    VkDeviceDeviceMemoryReportCreateInfoEXT: [d_VkDeviceDeviceMemoryReportCreateInfoEXT, e_VkDeviceDeviceMemoryReportCreateInfoEXT],
    VkDeviceGroupBindSparseInfo: [d_VkDeviceGroupBindSparseInfo, e_VkDeviceGroupBindSparseInfo],
    VkDeviceGroupCommandBufferBeginInfo: [d_VkDeviceGroupCommandBufferBeginInfo, e_VkDeviceGroupCommandBufferBeginInfo],
    VkDeviceGroupDeviceCreateInfo: [d_VkDeviceGroupDeviceCreateInfo, e_VkDeviceGroupDeviceCreateInfo],
    VkDeviceGroupRenderPassBeginInfo: [d_VkDeviceGroupRenderPassBeginInfo, e_VkDeviceGroupRenderPassBeginInfo],
    VkDeviceGroupSubmitInfo: [d_VkDeviceGroupSubmitInfo, e_VkDeviceGroupSubmitInfo],
    VkDeviceImageMemoryRequirements: [d_VkDeviceImageMemoryRequirements, null],
    VkDeviceImageSubresourceInfo: [d_VkDeviceImageSubresourceInfo, null],
    VkDeviceMemoryOpaqueCaptureAddressInfo: [d_VkDeviceMemoryOpaqueCaptureAddressInfo, null],
    VkDevicePrivateDataCreateInfo: [d_VkDevicePrivateDataCreateInfo, e_VkDevicePrivateDataCreateInfo],
    VkDeviceQueueCreateInfo: [d_VkDeviceQueueCreateInfo, null],
    VkDeviceQueueGlobalPriorityCreateInfo: [d_VkDeviceQueueGlobalPriorityCreateInfo, e_VkDeviceQueueGlobalPriorityCreateInfo],
    VkDeviceQueueInfo2: [d_VkDeviceQueueInfo2, null],
    VkDrmFormatModifierProperties2EXT: [d_VkDrmFormatModifierProperties2EXT, e_VkDrmFormatModifierProperties2EXT],
    VkDrmFormatModifierPropertiesEXT: [d_VkDrmFormatModifierPropertiesEXT, e_VkDrmFormatModifierPropertiesEXT],
    VkDrmFormatModifierPropertiesList2EXT: [d_VkDrmFormatModifierPropertiesList2EXT, e_VkDrmFormatModifierPropertiesList2EXT],
    VkDrmFormatModifierPropertiesListEXT: [d_VkDrmFormatModifierPropertiesListEXT, e_VkDrmFormatModifierPropertiesListEXT],
    VkEventCreateInfo: [d_VkEventCreateInfo, null],
    VkExportFenceCreateInfo: [d_VkExportFenceCreateInfo, e_VkExportFenceCreateInfo],
    VkExportMemoryAllocateInfo: [d_VkExportMemoryAllocateInfo, e_VkExportMemoryAllocateInfo],
    VkExportSemaphoreCreateInfo: [d_VkExportSemaphoreCreateInfo, e_VkExportSemaphoreCreateInfo],
    VkExtensionProperties: [d_VkExtensionProperties, e_VkExtensionProperties],
    VkExtent2D: [d_VkExtent2D, e_VkExtent2D],
    VkExtent3D: [d_VkExtent3D, e_VkExtent3D],
    VkExternalBufferProperties: [d_VkExternalBufferProperties, e_VkExternalBufferProperties],
    VkExternalFenceProperties: [d_VkExternalFenceProperties, e_VkExternalFenceProperties],
    VkExternalImageFormatProperties: [d_VkExternalImageFormatProperties, e_VkExternalImageFormatProperties],
    VkExternalMemoryBufferCreateInfo: [d_VkExternalMemoryBufferCreateInfo, e_VkExternalMemoryBufferCreateInfo],
    VkExternalMemoryImageCreateInfo: [d_VkExternalMemoryImageCreateInfo, e_VkExternalMemoryImageCreateInfo],
    VkExternalMemoryProperties: [d_VkExternalMemoryProperties, e_VkExternalMemoryProperties],
    VkExternalSemaphoreProperties: [d_VkExternalSemaphoreProperties, e_VkExternalSemaphoreProperties],
    VkFenceCreateInfo: [d_VkFenceCreateInfo, null],
    VkFenceGetFdInfoKHR: [d_VkFenceGetFdInfoKHR, null],
    VkFormatProperties: [d_VkFormatProperties, e_VkFormatProperties],
    VkFormatProperties2: [d_VkFormatProperties2, e_VkFormatProperties2],
    VkFormatProperties3: [d_VkFormatProperties3, e_VkFormatProperties3],
    VkFramebufferAttachmentImageInfo: [d_VkFramebufferAttachmentImageInfo, e_VkFramebufferAttachmentImageInfo],
    VkFramebufferAttachmentsCreateInfo: [d_VkFramebufferAttachmentsCreateInfo, e_VkFramebufferAttachmentsCreateInfo],
    VkFramebufferCreateInfo: [d_VkFramebufferCreateInfo, null],
    VkGraphicsPipelineCreateInfo: [d_VkGraphicsPipelineCreateInfo, null],
    VkGraphicsPipelineLibraryCreateInfoEXT: [d_VkGraphicsPipelineLibraryCreateInfoEXT, e_VkGraphicsPipelineLibraryCreateInfoEXT],
    VkHostImageCopyDevicePerformanceQuery: [d_VkHostImageCopyDevicePerformanceQuery, e_VkHostImageCopyDevicePerformanceQuery],
    VkHostImageLayoutTransitionInfo: [d_VkHostImageLayoutTransitionInfo, null],
    VkImageBlit: [d_VkImageBlit, null],
    VkImageBlit2: [d_VkImageBlit2, null],
    VkImageCompressionControlEXT: [d_VkImageCompressionControlEXT, e_VkImageCompressionControlEXT],
    VkImageCompressionPropertiesEXT: [d_VkImageCompressionPropertiesEXT, e_VkImageCompressionPropertiesEXT],
    VkImageCopy: [d_VkImageCopy, null],
    VkImageCopy2: [d_VkImageCopy2, null],
    VkImageCreateInfo: [d_VkImageCreateInfo, null],
    VkImageDrmFormatModifierExplicitCreateInfoEXT: [d_VkImageDrmFormatModifierExplicitCreateInfoEXT, e_VkImageDrmFormatModifierExplicitCreateInfoEXT],
    VkImageDrmFormatModifierListCreateInfoEXT: [d_VkImageDrmFormatModifierListCreateInfoEXT, e_VkImageDrmFormatModifierListCreateInfoEXT],
    VkImageDrmFormatModifierPropertiesEXT: [d_VkImageDrmFormatModifierPropertiesEXT, e_VkImageDrmFormatModifierPropertiesEXT],
    VkImageFormatListCreateInfo: [d_VkImageFormatListCreateInfo, e_VkImageFormatListCreateInfo],
    VkImageFormatProperties: [d_VkImageFormatProperties, e_VkImageFormatProperties],
    VkImageFormatProperties2: [d_VkImageFormatProperties2, e_VkImageFormatProperties2],
    VkImageMemoryBarrier: [d_VkImageMemoryBarrier, null],
    VkImageMemoryBarrier2: [d_VkImageMemoryBarrier2, null],
    VkImageMemoryRequirementsInfo2: [d_VkImageMemoryRequirementsInfo2, null],
    VkImagePlaneMemoryRequirementsInfo: [d_VkImagePlaneMemoryRequirementsInfo, e_VkImagePlaneMemoryRequirementsInfo],
    VkImageResolve: [d_VkImageResolve, null],
    VkImageResolve2: [d_VkImageResolve2, null],
    VkImageSparseMemoryRequirementsInfo2: [d_VkImageSparseMemoryRequirementsInfo2, null],
    VkImageStencilUsageCreateInfo: [d_VkImageStencilUsageCreateInfo, e_VkImageStencilUsageCreateInfo],
    VkImageSubresource: [d_VkImageSubresource, null],
    VkImageSubresource2: [d_VkImageSubresource2, null],
    VkImageSubresourceLayers: [d_VkImageSubresourceLayers, null],
    VkImageSubresourceRange: [d_VkImageSubresourceRange, null],
    VkImageToMemoryCopy: [d_VkImageToMemoryCopy, null],
    VkImageViewCreateInfo: [d_VkImageViewCreateInfo, null],
    VkImageViewUsageCreateInfo: [d_VkImageViewUsageCreateInfo, e_VkImageViewUsageCreateInfo],
    VkImportBufferGOOGLE: [d_VkImportBufferGOOGLE, e_VkImportBufferGOOGLE],
    VkImportColorBufferGOOGLE: [d_VkImportColorBufferGOOGLE, e_VkImportColorBufferGOOGLE],
    VkImportFenceFdInfoKHR: [d_VkImportFenceFdInfoKHR, null],
    VkImportSemaphoreFdInfoKHR: [d_VkImportSemaphoreFdInfoKHR, null],
    VkInputAttachmentAspectReference: [d_VkInputAttachmentAspectReference, e_VkInputAttachmentAspectReference],
    VkInstanceCreateInfo: [d_VkInstanceCreateInfo, null],
    VkLayerProperties: [d_VkLayerProperties, e_VkLayerProperties],
    VkMappedMemoryRange: [d_VkMappedMemoryRange, null],
    VkMemoryAllocateFlagsInfo: [d_VkMemoryAllocateFlagsInfo, e_VkMemoryAllocateFlagsInfo],
    VkMemoryAllocateInfo: [d_VkMemoryAllocateInfo, null],
    VkMemoryBarrier: [d_VkMemoryBarrier, null],
    VkMemoryBarrier2: [d_VkMemoryBarrier2, e_VkMemoryBarrier2],
    VkMemoryDedicatedAllocateInfo: [d_VkMemoryDedicatedAllocateInfo, e_VkMemoryDedicatedAllocateInfo],
    VkMemoryDedicatedRequirements: [d_VkMemoryDedicatedRequirements, e_VkMemoryDedicatedRequirements],
    VkMemoryHeap: [d_VkMemoryHeap, e_VkMemoryHeap],
    VkMemoryMapInfo: [d_VkMemoryMapInfo, null],
    VkMemoryOpaqueCaptureAddressAllocateInfo: [d_VkMemoryOpaqueCaptureAddressAllocateInfo, e_VkMemoryOpaqueCaptureAddressAllocateInfo],
    VkMemoryRequirements: [d_VkMemoryRequirements, e_VkMemoryRequirements],
    VkMemoryRequirements2: [d_VkMemoryRequirements2, e_VkMemoryRequirements2],
    VkMemoryToImageCopy: [d_VkMemoryToImageCopy, null],
    VkMemoryType: [d_VkMemoryType, e_VkMemoryType],
    VkMemoryUnmapInfo: [d_VkMemoryUnmapInfo, null],
    VkNativeBufferANDROID: [d_VkNativeBufferANDROID, e_VkNativeBufferANDROID],
    VkNativeBufferUsage2ANDROID: [d_VkNativeBufferUsage2ANDROID, e_VkNativeBufferUsage2ANDROID],
    VkOffset2D: [d_VkOffset2D, e_VkOffset2D],
    VkOffset3D: [d_VkOffset3D, null],
    VkPhysicalDevice16BitStorageFeatures: [d_VkPhysicalDevice16BitStorageFeatures, e_VkPhysicalDevice16BitStorageFeatures],
    VkPhysicalDevice4444FormatsFeaturesEXT: [d_VkPhysicalDevice4444FormatsFeaturesEXT, e_VkPhysicalDevice4444FormatsFeaturesEXT],
    VkPhysicalDevice8BitStorageFeatures: [d_VkPhysicalDevice8BitStorageFeatures, e_VkPhysicalDevice8BitStorageFeatures],
    VkPhysicalDeviceBufferDeviceAddressFeatures: [d_VkPhysicalDeviceBufferDeviceAddressFeatures, e_VkPhysicalDeviceBufferDeviceAddressFeatures],
    VkPhysicalDeviceColorWriteEnableFeaturesEXT: [d_VkPhysicalDeviceColorWriteEnableFeaturesEXT, e_VkPhysicalDeviceColorWriteEnableFeaturesEXT],
    VkPhysicalDeviceCustomBorderColorFeaturesEXT: [d_VkPhysicalDeviceCustomBorderColorFeaturesEXT, e_VkPhysicalDeviceCustomBorderColorFeaturesEXT],
    VkPhysicalDeviceCustomBorderColorPropertiesEXT: [d_VkPhysicalDeviceCustomBorderColorPropertiesEXT, e_VkPhysicalDeviceCustomBorderColorPropertiesEXT],
    VkPhysicalDeviceDepthClipEnableFeaturesEXT: [d_VkPhysicalDeviceDepthClipEnableFeaturesEXT, e_VkPhysicalDeviceDepthClipEnableFeaturesEXT],
    VkPhysicalDeviceDepthStencilResolveProperties: [d_VkPhysicalDeviceDepthStencilResolveProperties, e_VkPhysicalDeviceDepthStencilResolveProperties],
    VkPhysicalDeviceDescriptorIndexingFeatures: [d_VkPhysicalDeviceDescriptorIndexingFeatures, e_VkPhysicalDeviceDescriptorIndexingFeatures],
    VkPhysicalDeviceDescriptorIndexingProperties: [d_VkPhysicalDeviceDescriptorIndexingProperties, e_VkPhysicalDeviceDescriptorIndexingProperties],
    VkPhysicalDeviceDeviceMemoryReportFeaturesEXT: [d_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, e_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT],
    VkPhysicalDeviceDriverProperties: [d_VkPhysicalDeviceDriverProperties, e_VkPhysicalDeviceDriverProperties],
    VkPhysicalDeviceDynamicRenderingFeatures: [d_VkPhysicalDeviceDynamicRenderingFeatures, e_VkPhysicalDeviceDynamicRenderingFeatures],
    VkPhysicalDeviceDynamicRenderingLocalReadFeatures: [d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, e_VkPhysicalDeviceDynamicRenderingLocalReadFeatures],
    VkPhysicalDeviceExtendedDynamicState2FeaturesEXT: [d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, e_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT],
    VkPhysicalDeviceExtendedDynamicStateFeaturesEXT: [d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, e_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT],
    VkPhysicalDeviceExternalBufferInfo: [d_VkPhysicalDeviceExternalBufferInfo, null],
    VkPhysicalDeviceExternalFenceInfo: [d_VkPhysicalDeviceExternalFenceInfo, null],
    VkPhysicalDeviceExternalImageFormatInfo: [d_VkPhysicalDeviceExternalImageFormatInfo, e_VkPhysicalDeviceExternalImageFormatInfo],
    VkPhysicalDeviceExternalSemaphoreInfo: [d_VkPhysicalDeviceExternalSemaphoreInfo, null],
    VkPhysicalDeviceFeatures: [d_VkPhysicalDeviceFeatures, e_VkPhysicalDeviceFeatures],
    VkPhysicalDeviceFeatures2: [d_VkPhysicalDeviceFeatures2, e_VkPhysicalDeviceFeatures2],
    VkPhysicalDeviceFloatControlsProperties: [d_VkPhysicalDeviceFloatControlsProperties, e_VkPhysicalDeviceFloatControlsProperties],
    VkPhysicalDeviceFragmentDensityMapFeaturesEXT: [d_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, e_VkPhysicalDeviceFragmentDensityMapFeaturesEXT],
    VkPhysicalDeviceFragmentDensityMapPropertiesEXT: [d_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, e_VkPhysicalDeviceFragmentDensityMapPropertiesEXT],
    VkPhysicalDeviceGlobalPriorityQueryFeatures: [d_VkPhysicalDeviceGlobalPriorityQueryFeatures, e_VkPhysicalDeviceGlobalPriorityQueryFeatures],
    VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT: [d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, e_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT],
    VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT: [d_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, e_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT],
    VkPhysicalDeviceGroupProperties: [d_VkPhysicalDeviceGroupProperties, e_VkPhysicalDeviceGroupProperties],
    VkPhysicalDeviceHostImageCopyFeatures: [d_VkPhysicalDeviceHostImageCopyFeatures, e_VkPhysicalDeviceHostImageCopyFeatures],
    VkPhysicalDeviceHostImageCopyProperties: [d_VkPhysicalDeviceHostImageCopyProperties, e_VkPhysicalDeviceHostImageCopyProperties],
    VkPhysicalDeviceHostQueryResetFeatures: [d_VkPhysicalDeviceHostQueryResetFeatures, e_VkPhysicalDeviceHostQueryResetFeatures],
    VkPhysicalDeviceIDProperties: [d_VkPhysicalDeviceIDProperties, e_VkPhysicalDeviceIDProperties],
    VkPhysicalDeviceImageCompressionControlFeaturesEXT: [d_VkPhysicalDeviceImageCompressionControlFeaturesEXT, e_VkPhysicalDeviceImageCompressionControlFeaturesEXT],
    VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT: [d_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, e_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT],
    VkPhysicalDeviceImageDrmFormatModifierInfoEXT: [d_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, e_VkPhysicalDeviceImageDrmFormatModifierInfoEXT],
    VkPhysicalDeviceImageFormatInfo2: [d_VkPhysicalDeviceImageFormatInfo2, null],
    VkPhysicalDeviceImageRobustnessFeatures: [d_VkPhysicalDeviceImageRobustnessFeatures, e_VkPhysicalDeviceImageRobustnessFeatures],
    VkPhysicalDeviceImagelessFramebufferFeatures: [d_VkPhysicalDeviceImagelessFramebufferFeatures, e_VkPhysicalDeviceImagelessFramebufferFeatures],
    VkPhysicalDeviceIndexTypeUint8Features: [d_VkPhysicalDeviceIndexTypeUint8Features, e_VkPhysicalDeviceIndexTypeUint8Features],
    VkPhysicalDeviceInlineUniformBlockFeatures: [d_VkPhysicalDeviceInlineUniformBlockFeatures, e_VkPhysicalDeviceInlineUniformBlockFeatures],
    VkPhysicalDeviceInlineUniformBlockProperties: [d_VkPhysicalDeviceInlineUniformBlockProperties, e_VkPhysicalDeviceInlineUniformBlockProperties],
    VkPhysicalDeviceLimits: [d_VkPhysicalDeviceLimits, e_VkPhysicalDeviceLimits],
    VkPhysicalDeviceLineRasterizationFeatures: [d_VkPhysicalDeviceLineRasterizationFeatures, e_VkPhysicalDeviceLineRasterizationFeatures],
    VkPhysicalDeviceLineRasterizationProperties: [d_VkPhysicalDeviceLineRasterizationProperties, e_VkPhysicalDeviceLineRasterizationProperties],
    VkPhysicalDeviceMaintenance3Properties: [d_VkPhysicalDeviceMaintenance3Properties, e_VkPhysicalDeviceMaintenance3Properties],
    VkPhysicalDeviceMaintenance4Features: [d_VkPhysicalDeviceMaintenance4Features, e_VkPhysicalDeviceMaintenance4Features],
    VkPhysicalDeviceMaintenance4Properties: [d_VkPhysicalDeviceMaintenance4Properties, e_VkPhysicalDeviceMaintenance4Properties],
    VkPhysicalDeviceMaintenance5Features: [d_VkPhysicalDeviceMaintenance5Features, e_VkPhysicalDeviceMaintenance5Features],
    VkPhysicalDeviceMaintenance5Properties: [d_VkPhysicalDeviceMaintenance5Properties, e_VkPhysicalDeviceMaintenance5Properties],
    VkPhysicalDeviceMaintenance6Features: [d_VkPhysicalDeviceMaintenance6Features, e_VkPhysicalDeviceMaintenance6Features],
    VkPhysicalDeviceMaintenance6Properties: [d_VkPhysicalDeviceMaintenance6Properties, e_VkPhysicalDeviceMaintenance6Properties],
    VkPhysicalDeviceMemoryBudgetPropertiesEXT: [d_VkPhysicalDeviceMemoryBudgetPropertiesEXT, e_VkPhysicalDeviceMemoryBudgetPropertiesEXT],
    VkPhysicalDeviceMemoryProperties: [d_VkPhysicalDeviceMemoryProperties, e_VkPhysicalDeviceMemoryProperties],
    VkPhysicalDeviceMemoryProperties2: [d_VkPhysicalDeviceMemoryProperties2, e_VkPhysicalDeviceMemoryProperties2],
    VkPhysicalDeviceMultiviewFeatures: [d_VkPhysicalDeviceMultiviewFeatures, e_VkPhysicalDeviceMultiviewFeatures],
    VkPhysicalDeviceMultiviewProperties: [d_VkPhysicalDeviceMultiviewProperties, e_VkPhysicalDeviceMultiviewProperties],
    VkPhysicalDevicePipelineCreationCacheControlFeatures: [d_VkPhysicalDevicePipelineCreationCacheControlFeatures, e_VkPhysicalDevicePipelineCreationCacheControlFeatures],
    VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR: [d_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, e_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR],
    VkPhysicalDevicePipelineProtectedAccessFeatures: [d_VkPhysicalDevicePipelineProtectedAccessFeatures, e_VkPhysicalDevicePipelineProtectedAccessFeatures],
    VkPhysicalDevicePipelineRobustnessFeatures: [d_VkPhysicalDevicePipelineRobustnessFeatures, e_VkPhysicalDevicePipelineRobustnessFeatures],
    VkPhysicalDevicePipelineRobustnessProperties: [d_VkPhysicalDevicePipelineRobustnessProperties, e_VkPhysicalDevicePipelineRobustnessProperties],
    VkPhysicalDevicePointClippingProperties: [d_VkPhysicalDevicePointClippingProperties, e_VkPhysicalDevicePointClippingProperties],
    VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT: [d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, e_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT],
    VkPhysicalDevicePrivateDataFeatures: [d_VkPhysicalDevicePrivateDataFeatures, e_VkPhysicalDevicePrivateDataFeatures],
    VkPhysicalDeviceProperties: [d_VkPhysicalDeviceProperties, e_VkPhysicalDeviceProperties],
    VkPhysicalDeviceProperties2: [d_VkPhysicalDeviceProperties2, e_VkPhysicalDeviceProperties2],
    VkPhysicalDeviceProtectedMemoryFeatures: [d_VkPhysicalDeviceProtectedMemoryFeatures, e_VkPhysicalDeviceProtectedMemoryFeatures],
    VkPhysicalDeviceProtectedMemoryProperties: [d_VkPhysicalDeviceProtectedMemoryProperties, e_VkPhysicalDeviceProtectedMemoryProperties],
    VkPhysicalDeviceProvokingVertexFeaturesEXT: [d_VkPhysicalDeviceProvokingVertexFeaturesEXT, e_VkPhysicalDeviceProvokingVertexFeaturesEXT],
    VkPhysicalDeviceProvokingVertexPropertiesEXT: [d_VkPhysicalDeviceProvokingVertexPropertiesEXT, e_VkPhysicalDeviceProvokingVertexPropertiesEXT],
    VkPhysicalDevicePushDescriptorProperties: [d_VkPhysicalDevicePushDescriptorProperties, e_VkPhysicalDevicePushDescriptorProperties],
    VkPhysicalDeviceSamplerFilterMinmaxProperties: [d_VkPhysicalDeviceSamplerFilterMinmaxProperties, e_VkPhysicalDeviceSamplerFilterMinmaxProperties],
    VkPhysicalDeviceSamplerYcbcrConversionFeatures: [d_VkPhysicalDeviceSamplerYcbcrConversionFeatures, e_VkPhysicalDeviceSamplerYcbcrConversionFeatures],
    VkPhysicalDeviceScalarBlockLayoutFeatures: [d_VkPhysicalDeviceScalarBlockLayoutFeatures, e_VkPhysicalDeviceScalarBlockLayoutFeatures],
    VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures: [d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, e_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures],
    VkPhysicalDeviceShaderAtomicInt64Features: [d_VkPhysicalDeviceShaderAtomicInt64Features, e_VkPhysicalDeviceShaderAtomicInt64Features],
    VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures: [d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, e_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures],
    VkPhysicalDeviceShaderDrawParametersFeatures: [d_VkPhysicalDeviceShaderDrawParametersFeatures, e_VkPhysicalDeviceShaderDrawParametersFeatures],
    VkPhysicalDeviceShaderExpectAssumeFeatures: [d_VkPhysicalDeviceShaderExpectAssumeFeatures, e_VkPhysicalDeviceShaderExpectAssumeFeatures],
    VkPhysicalDeviceShaderFloat16Int8Features: [d_VkPhysicalDeviceShaderFloat16Int8Features, e_VkPhysicalDeviceShaderFloat16Int8Features],
    VkPhysicalDeviceShaderFloatControls2Features: [d_VkPhysicalDeviceShaderFloatControls2Features, e_VkPhysicalDeviceShaderFloatControls2Features],
    VkPhysicalDeviceShaderIntegerDotProductFeatures: [d_VkPhysicalDeviceShaderIntegerDotProductFeatures, e_VkPhysicalDeviceShaderIntegerDotProductFeatures],
    VkPhysicalDeviceShaderIntegerDotProductProperties: [d_VkPhysicalDeviceShaderIntegerDotProductProperties, e_VkPhysicalDeviceShaderIntegerDotProductProperties],
    VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures: [d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, e_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures],
    VkPhysicalDeviceShaderSubgroupRotateFeatures: [d_VkPhysicalDeviceShaderSubgroupRotateFeatures, e_VkPhysicalDeviceShaderSubgroupRotateFeatures],
    VkPhysicalDeviceShaderTerminateInvocationFeatures: [d_VkPhysicalDeviceShaderTerminateInvocationFeatures, e_VkPhysicalDeviceShaderTerminateInvocationFeatures],
    VkPhysicalDeviceSparseImageFormatInfo2: [d_VkPhysicalDeviceSparseImageFormatInfo2, null],
    VkPhysicalDeviceSparseProperties: [d_VkPhysicalDeviceSparseProperties, e_VkPhysicalDeviceSparseProperties],
    VkPhysicalDeviceSubgroupProperties: [d_VkPhysicalDeviceSubgroupProperties, e_VkPhysicalDeviceSubgroupProperties],
    VkPhysicalDeviceSubgroupSizeControlFeatures: [d_VkPhysicalDeviceSubgroupSizeControlFeatures, e_VkPhysicalDeviceSubgroupSizeControlFeatures],
    VkPhysicalDeviceSubgroupSizeControlProperties: [d_VkPhysicalDeviceSubgroupSizeControlProperties, e_VkPhysicalDeviceSubgroupSizeControlProperties],
    VkPhysicalDeviceSynchronization2Features: [d_VkPhysicalDeviceSynchronization2Features, e_VkPhysicalDeviceSynchronization2Features],
    VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT: [d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, e_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT],
    VkPhysicalDeviceTexelBufferAlignmentProperties: [d_VkPhysicalDeviceTexelBufferAlignmentProperties, e_VkPhysicalDeviceTexelBufferAlignmentProperties],
    VkPhysicalDeviceTextureCompressionASTCHDRFeatures: [d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, e_VkPhysicalDeviceTextureCompressionASTCHDRFeatures],
    VkPhysicalDeviceTimelineSemaphoreFeatures: [d_VkPhysicalDeviceTimelineSemaphoreFeatures, e_VkPhysicalDeviceTimelineSemaphoreFeatures],
    VkPhysicalDeviceTimelineSemaphoreProperties: [d_VkPhysicalDeviceTimelineSemaphoreProperties, e_VkPhysicalDeviceTimelineSemaphoreProperties],
    VkPhysicalDeviceToolProperties: [d_VkPhysicalDeviceToolProperties, e_VkPhysicalDeviceToolProperties],
    VkPhysicalDeviceTransformFeedbackFeaturesEXT: [d_VkPhysicalDeviceTransformFeedbackFeaturesEXT, e_VkPhysicalDeviceTransformFeedbackFeaturesEXT],
    VkPhysicalDeviceTransformFeedbackPropertiesEXT: [d_VkPhysicalDeviceTransformFeedbackPropertiesEXT, e_VkPhysicalDeviceTransformFeedbackPropertiesEXT],
    VkPhysicalDeviceUniformBufferStandardLayoutFeatures: [d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, e_VkPhysicalDeviceUniformBufferStandardLayoutFeatures],
    VkPhysicalDeviceVariablePointersFeatures: [d_VkPhysicalDeviceVariablePointersFeatures, e_VkPhysicalDeviceVariablePointersFeatures],
    VkPhysicalDeviceVertexAttributeDivisorFeatures: [d_VkPhysicalDeviceVertexAttributeDivisorFeatures, e_VkPhysicalDeviceVertexAttributeDivisorFeatures],
    VkPhysicalDeviceVertexAttributeDivisorProperties: [d_VkPhysicalDeviceVertexAttributeDivisorProperties, e_VkPhysicalDeviceVertexAttributeDivisorProperties],
    VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT: [d_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, e_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT],
    VkPhysicalDeviceVulkan11Features: [d_VkPhysicalDeviceVulkan11Features, e_VkPhysicalDeviceVulkan11Features],
    VkPhysicalDeviceVulkan11Properties: [d_VkPhysicalDeviceVulkan11Properties, e_VkPhysicalDeviceVulkan11Properties],
    VkPhysicalDeviceVulkan12Features: [d_VkPhysicalDeviceVulkan12Features, e_VkPhysicalDeviceVulkan12Features],
    VkPhysicalDeviceVulkan12Properties: [d_VkPhysicalDeviceVulkan12Properties, e_VkPhysicalDeviceVulkan12Properties],
    VkPhysicalDeviceVulkan13Features: [d_VkPhysicalDeviceVulkan13Features, e_VkPhysicalDeviceVulkan13Features],
    VkPhysicalDeviceVulkan13Properties: [d_VkPhysicalDeviceVulkan13Properties, e_VkPhysicalDeviceVulkan13Properties],
    VkPhysicalDeviceVulkan14Features: [d_VkPhysicalDeviceVulkan14Features, e_VkPhysicalDeviceVulkan14Features],
    VkPhysicalDeviceVulkan14Properties: [d_VkPhysicalDeviceVulkan14Properties, e_VkPhysicalDeviceVulkan14Properties],
    VkPhysicalDeviceVulkanMemoryModelFeatures: [d_VkPhysicalDeviceVulkanMemoryModelFeatures, e_VkPhysicalDeviceVulkanMemoryModelFeatures],
    VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT: [d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, e_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT],
    VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures: [d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, e_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures],
    VkPipelineCacheCreateInfo: [d_VkPipelineCacheCreateInfo, null],
    VkPipelineColorBlendAttachmentState: [d_VkPipelineColorBlendAttachmentState, null],
    VkPipelineColorBlendStateCreateInfo: [d_VkPipelineColorBlendStateCreateInfo, null],
    VkPipelineColorWriteCreateInfoEXT: [d_VkPipelineColorWriteCreateInfoEXT, e_VkPipelineColorWriteCreateInfoEXT],
    VkPipelineCreateFlags2CreateInfo: [d_VkPipelineCreateFlags2CreateInfo, e_VkPipelineCreateFlags2CreateInfo],
    VkPipelineCreationFeedback: [d_VkPipelineCreationFeedback, e_VkPipelineCreationFeedback],
    VkPipelineCreationFeedbackCreateInfo: [d_VkPipelineCreationFeedbackCreateInfo, e_VkPipelineCreationFeedbackCreateInfo],
    VkPipelineDepthStencilStateCreateInfo: [d_VkPipelineDepthStencilStateCreateInfo, null],
    VkPipelineDynamicStateCreateInfo: [d_VkPipelineDynamicStateCreateInfo, null],
    VkPipelineExecutableInfoKHR: [d_VkPipelineExecutableInfoKHR, null],
    VkPipelineExecutableInternalRepresentationKHR: [d_VkPipelineExecutableInternalRepresentationKHR, e_VkPipelineExecutableInternalRepresentationKHR],
    VkPipelineExecutablePropertiesKHR: [d_VkPipelineExecutablePropertiesKHR, e_VkPipelineExecutablePropertiesKHR],
    VkPipelineExecutableStatisticKHR: [d_VkPipelineExecutableStatisticKHR, e_VkPipelineExecutableStatisticKHR],
    VkPipelineExecutableStatisticValueKHR: [d_VkPipelineExecutableStatisticValueKHR, e_VkPipelineExecutableStatisticValueKHR],
    VkPipelineInfoKHR: [d_VkPipelineInfoKHR, null],
    VkPipelineInputAssemblyStateCreateInfo: [d_VkPipelineInputAssemblyStateCreateInfo, null],
    VkPipelineLayoutCreateInfo: [d_VkPipelineLayoutCreateInfo, e_VkPipelineLayoutCreateInfo],
    VkPipelineMultisampleStateCreateInfo: [d_VkPipelineMultisampleStateCreateInfo, null],
    VkPipelineRasterizationDepthClipStateCreateInfoEXT: [d_VkPipelineRasterizationDepthClipStateCreateInfoEXT, e_VkPipelineRasterizationDepthClipStateCreateInfoEXT],
    VkPipelineRasterizationLineStateCreateInfo: [d_VkPipelineRasterizationLineStateCreateInfo, e_VkPipelineRasterizationLineStateCreateInfo],
    VkPipelineRasterizationProvokingVertexStateCreateInfoEXT: [d_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, e_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT],
    VkPipelineRasterizationStateCreateInfo: [d_VkPipelineRasterizationStateCreateInfo, null],
    VkPipelineRasterizationStateStreamCreateInfoEXT: [d_VkPipelineRasterizationStateStreamCreateInfoEXT, e_VkPipelineRasterizationStateStreamCreateInfoEXT],
    VkPipelineRenderingCreateInfo: [d_VkPipelineRenderingCreateInfo, e_VkPipelineRenderingCreateInfo],
    VkPipelineRobustnessCreateInfo: [d_VkPipelineRobustnessCreateInfo, e_VkPipelineRobustnessCreateInfo],
    VkPipelineShaderStageCreateInfo: [d_VkPipelineShaderStageCreateInfo, null],
    VkPipelineShaderStageRequiredSubgroupSizeCreateInfo: [d_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, e_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo],
    VkPipelineTessellationDomainOriginStateCreateInfo: [d_VkPipelineTessellationDomainOriginStateCreateInfo, e_VkPipelineTessellationDomainOriginStateCreateInfo],
    VkPipelineTessellationStateCreateInfo: [d_VkPipelineTessellationStateCreateInfo, null],
    VkPipelineVertexInputDivisorStateCreateInfo: [d_VkPipelineVertexInputDivisorStateCreateInfo, e_VkPipelineVertexInputDivisorStateCreateInfo],
    VkPipelineVertexInputStateCreateInfo: [d_VkPipelineVertexInputStateCreateInfo, null],
    VkPipelineViewportStateCreateInfo: [d_VkPipelineViewportStateCreateInfo, null],
    VkPresentRegionKHR: [d_VkPresentRegionKHR, e_VkPresentRegionKHR],
    VkPresentRegionsKHR: [d_VkPresentRegionsKHR, e_VkPresentRegionsKHR],
    VkPrivateDataSlotCreateInfo: [d_VkPrivateDataSlotCreateInfo, null],
    VkProtectedSubmitInfo: [d_VkProtectedSubmitInfo, e_VkProtectedSubmitInfo],
    VkPushConstantRange: [d_VkPushConstantRange, e_VkPushConstantRange],
    VkPushConstantsInfo: [d_VkPushConstantsInfo, null],
    VkPushDescriptorSetInfo: [d_VkPushDescriptorSetInfo, null],
    VkPushDescriptorSetWithTemplateInfo: [d_VkPushDescriptorSetWithTemplateInfo, null],
    VkQueryPoolCreateInfo: [d_VkQueryPoolCreateInfo, null],
    VkQueueFamilyGlobalPriorityProperties: [d_VkQueueFamilyGlobalPriorityProperties, e_VkQueueFamilyGlobalPriorityProperties],
    VkQueueFamilyProperties: [d_VkQueueFamilyProperties, e_VkQueueFamilyProperties],
    VkQueueFamilyProperties2: [d_VkQueueFamilyProperties2, e_VkQueueFamilyProperties2],
    VkRect2D: [d_VkRect2D, e_VkRect2D],
    VkRectLayerKHR: [d_VkRectLayerKHR, e_VkRectLayerKHR],
    VkRenderPassAttachmentBeginInfo: [d_VkRenderPassAttachmentBeginInfo, e_VkRenderPassAttachmentBeginInfo],
    VkRenderPassBeginInfo: [d_VkRenderPassBeginInfo, null],
    VkRenderPassCreateInfo: [d_VkRenderPassCreateInfo, null],
    VkRenderPassCreateInfo2: [d_VkRenderPassCreateInfo2, null],
    VkRenderPassFragmentDensityMapCreateInfoEXT: [d_VkRenderPassFragmentDensityMapCreateInfoEXT, e_VkRenderPassFragmentDensityMapCreateInfoEXT],
    VkRenderPassInputAttachmentAspectCreateInfo: [d_VkRenderPassInputAttachmentAspectCreateInfo, e_VkRenderPassInputAttachmentAspectCreateInfo],
    VkRenderPassMultiviewCreateInfo: [d_VkRenderPassMultiviewCreateInfo, e_VkRenderPassMultiviewCreateInfo],
    VkRenderingAreaInfo: [d_VkRenderingAreaInfo, null],
    VkRenderingAttachmentInfo: [d_VkRenderingAttachmentInfo, null],
    VkRenderingAttachmentLocationInfo: [d_VkRenderingAttachmentLocationInfo, e_VkRenderingAttachmentLocationInfo],
    VkRenderingFragmentDensityMapAttachmentInfoEXT: [d_VkRenderingFragmentDensityMapAttachmentInfoEXT, e_VkRenderingFragmentDensityMapAttachmentInfoEXT],
    VkRenderingInfo: [d_VkRenderingInfo, null],
    VkRenderingInputAttachmentIndexInfo: [d_VkRenderingInputAttachmentIndexInfo, e_VkRenderingInputAttachmentIndexInfo],
    VkResolveImageInfo2: [d_VkResolveImageInfo2, null],
    VkSamplerCreateInfo: [d_VkSamplerCreateInfo, null],
    VkSamplerCustomBorderColorCreateInfoEXT: [d_VkSamplerCustomBorderColorCreateInfoEXT, e_VkSamplerCustomBorderColorCreateInfoEXT],
    VkSamplerReductionModeCreateInfo: [d_VkSamplerReductionModeCreateInfo, e_VkSamplerReductionModeCreateInfo],
    VkSamplerYcbcrConversionCreateInfo: [d_VkSamplerYcbcrConversionCreateInfo, null],
    VkSamplerYcbcrConversionImageFormatProperties: [d_VkSamplerYcbcrConversionImageFormatProperties, e_VkSamplerYcbcrConversionImageFormatProperties],
    VkSamplerYcbcrConversionInfo: [d_VkSamplerYcbcrConversionInfo, e_VkSamplerYcbcrConversionInfo],
    VkSemaphoreCreateInfo: [d_VkSemaphoreCreateInfo, null],
    VkSemaphoreGetFdInfoKHR: [d_VkSemaphoreGetFdInfoKHR, null],
    VkSemaphoreSignalInfo: [d_VkSemaphoreSignalInfo, null],
    VkSemaphoreSubmitInfo: [d_VkSemaphoreSubmitInfo, null],
    VkSemaphoreTypeCreateInfo: [d_VkSemaphoreTypeCreateInfo, e_VkSemaphoreTypeCreateInfo],
    VkSemaphoreWaitInfo: [d_VkSemaphoreWaitInfo, null],
    VkShaderModuleCreateInfo: [d_VkShaderModuleCreateInfo, e_VkShaderModuleCreateInfo],
    VkSparseBufferMemoryBindInfo: [d_VkSparseBufferMemoryBindInfo, null],
    VkSparseImageFormatProperties: [d_VkSparseImageFormatProperties, e_VkSparseImageFormatProperties],
    VkSparseImageFormatProperties2: [d_VkSparseImageFormatProperties2, e_VkSparseImageFormatProperties2],
    VkSparseImageMemoryBind: [d_VkSparseImageMemoryBind, null],
    VkSparseImageMemoryBindInfo: [d_VkSparseImageMemoryBindInfo, null],
    VkSparseImageMemoryRequirements: [d_VkSparseImageMemoryRequirements, e_VkSparseImageMemoryRequirements],
    VkSparseImageMemoryRequirements2: [d_VkSparseImageMemoryRequirements2, e_VkSparseImageMemoryRequirements2],
    VkSparseImageOpaqueMemoryBindInfo: [d_VkSparseImageOpaqueMemoryBindInfo, null],
    VkSparseMemoryBind: [d_VkSparseMemoryBind, null],
    VkSpecializationInfo: [d_VkSpecializationInfo, null],
    VkSpecializationMapEntry: [d_VkSpecializationMapEntry, null],
    VkStencilOpState: [d_VkStencilOpState, null],
    VkSubmitInfo: [d_VkSubmitInfo, null],
    VkSubmitInfo2: [d_VkSubmitInfo2, null],
    VkSubpassBeginInfo: [d_VkSubpassBeginInfo, null],
    VkSubpassDependency: [d_VkSubpassDependency, null],
    VkSubpassDependency2: [d_VkSubpassDependency2, null],
    VkSubpassDescription: [d_VkSubpassDescription, null],
    VkSubpassDescription2: [d_VkSubpassDescription2, null],
    VkSubpassDescriptionDepthStencilResolve: [d_VkSubpassDescriptionDepthStencilResolve, e_VkSubpassDescriptionDepthStencilResolve],
    VkSubpassEndInfo: [d_VkSubpassEndInfo, null],
    VkSubresourceHostMemcpySize: [d_VkSubresourceHostMemcpySize, e_VkSubresourceHostMemcpySize],
    VkSubresourceLayout: [d_VkSubresourceLayout, e_VkSubresourceLayout],
    VkSubresourceLayout2: [d_VkSubresourceLayout2, e_VkSubresourceLayout2],
    VkTimelineSemaphoreSubmitInfo: [d_VkTimelineSemaphoreSubmitInfo, e_VkTimelineSemaphoreSubmitInfo],
    VkVertexInputAttributeDescription: [d_VkVertexInputAttributeDescription, null],
    VkVertexInputBindingDescription: [d_VkVertexInputBindingDescription, null],
    VkVertexInputBindingDivisorDescription: [d_VkVertexInputBindingDivisorDescription, e_VkVertexInputBindingDivisorDescription],
    VkViewport: [d_VkViewport, null],
    VkWriteDescriptorSet: [d_VkWriteDescriptorSet, null],
    VkWriteDescriptorSetInlineUniformBlock: [d_VkWriteDescriptorSetInlineUniformBlock, e_VkWriteDescriptorSetInlineUniformBlock],
};

/** the guest's stream features (all four for virtio-gpu) */
export const STREAM_FEATURES = 15;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/src/graphics_adapters/virtio_gpu/gfxstream_vk.js                                         0000644 0000000 0000000 00000073405 00000000000 021374  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // gfxstream's Vulkan streams (docs/gfxstream-plan.md G2): the commands of
// a context's rings in the Vulkan opcode ranges, decoded with
// gfxstream_protocol.js (generated from the guest's encoder) and run on the
// Vulkan model Venus has (venus_vk.js: its handlers take objects with the C
// names). What gfxstream does differently is here: the host allocates the
// handles (gfxstream's boxed handles), the commands of a process run in the
// order of their sequence numbers whatever ring they come on, command
// buffers are recorded by the guest and flushed as one command
// (vkQueueFlushCommandsGOOGLE), and the VK_GOOGLE_gfxstream commands
// (asynchronous submits, creation with memory requirements, host syncs,
// blobs of host visible memory, sized template updates) map onto the
// model's.

import { COMMANDS, GfxReader, GfxWriter } from "./gfxstream_protocol.js";
import { DEVICE_EXTENSIONS } from "./venus_device_info.js";
import { encode_objects, decode_objects } from "./venus_state.js";
import { dbg_log } from "../../log.js";
import { LOG_VIRTIO } from "../../const.js";

// the Vulkan opcodes (goldfish_vk_marshaling_guest.h: OP_vkFirst_old, OP_vkFirst)
export const VK_FIRST_OLD = 20000, VK_LAST_OLD = 29999, VK_FIRST = 200000000, VK_LAST = 299999999;

const VK_SUCCESS = 0, VK_ERROR_INITIALIZATION_FAILED = -3, VK_ERROR_MEMORY_MAP_FAILED = -5, VK_ERROR_FEATURE_NOT_PRESENT = -8;
// VkStructureType
const STYPE_WRITE_DESCRIPTOR_SET = 35;
const STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA = 1000384002;
const STYPE_IMPORT_COLOR_BUFFER_GOOGLE = 1000385000, STYPE_IMPORT_BUFFER_GOOGLE = 1000385001, STYPE_CREATE_BLOB_GOOGLE = 1000385002;
const STYPE_MEMORY_ALLOCATE_INFO = 5, STYPE_NATIVE_BUFFER_ANDROID = 1000010000;
const STYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO = 1000071000, STYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES = 1000071001;
// VkExternalMemoryHandleTypeFlagBits: dma-bufs (the model's imports), Android hardware buffers (the guest's)
const HANDLE_DMA_BUF = 0x200, HANDLE_AHB = 0x400;
// VkExternalMemoryFeatureFlagBits: dedicated only, exportable, importable
const EXTERNAL_MEMORY_FEATURES_AHB = 1 | 2 | 4;
/** the model's device local memory type (venus_device_info.js MEMORY_DEVICE_LOCAL): imports are of it */
const MEMORY_DEVICE_LOCAL = 0;
// VkDescriptorType: images (sampler, combined, sampled, storage, input attachment), texel buffers, buffers
const IMAGE_DESCRIPTORS = new Set([0, 1, 2, 3, 10]), TEXEL_DESCRIPTORS = new Set([4, 5]), BUFFER_DESCRIPTORS = new Set([6, 7, 8, 9]);
// execbuffer commands with a Vulkan object (gfxstream.js runs them as sync tasks)
const CREATE_EXPORT_SYNC_VK = 0xa000, CREATE_QSRI_EXPORT_VK = 0xa002;
/** a host sync's longest wait (gfxstream's host: 5 s) */
const HOST_SYNC_TIMEOUT = 5000;
// VkFormat's of the swapchain's gralloc usage (GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE)
const GRALLOC_USAGE_HW = 0x200 | 0x100;

/**
 * Device extensions the host says it has though the model does not: the
 * guest takes VK_KHR_external_memory_fd for the host's external memory, and
 * offers VK_ANDROID_external_memory_android_hardware_buffer then (its own:
 * color buffer imports, the model's resource imports); it does not enable it
 * on the host
 */
const HOST_EXTENSIONS = [["VK_KHR_external_memory_fd", 1]];

/** the gfxstream commands that are a model's under another name */
const SAME_AS = {
    vkQueueSubmitAsyncGOOGLE: "vkQueueSubmit",
    vkQueueSubmitAsync2GOOGLE: "vkQueueSubmit2",
    vkQueueWaitIdleAsyncGOOGLE: "vkQueueWaitIdle",
    vkQueueBindSparseAsyncGOOGLE: "vkQueueBindSparse",
    vkBeginCommandBufferAsyncGOOGLE: "vkBeginCommandBuffer",
    vkEndCommandBufferAsyncGOOGLE: "vkEndCommandBuffer",
    vkResetCommandBufferAsyncGOOGLE: "vkResetCommandBuffer",
    vkFreeMemorySyncGOOGLE: "vkFreeMemory",
};

/**
 * @constructor
 * @param {!Object} gfxstream the transport (gfxstream.js)
 * @param {!Object} vk the Vulkan model (venus_vk.js)
 */
export function GfxstreamVulkan(gfxstream, vk)
{
    this.gfxstream = gfxstream;
    this.vk = vk;
    /** the host's handles: any context's unique (gfxstream's boxed handles are the host's) */
    this.next_handle = 0x1000;
    this.stats = { commands: 0, flushed: 0, unknown: {}, unimplemented: {}, failures: {}, errors: 0, last_error: "",
        /** @type {!Array<{name: string, payload: !Uint8Array}>} the first commands that did not decode (a harness keeps them) */
        undecoded: [] };
    /** @type {?function(string, !Object)} a harness's hook: each command and its parameters */
    this.on_command = null;
}

/** its decoders for the transport: the two ranges of Vulkan's opcodes */
GfxstreamVulkan.prototype.decoders = function()
{
    const decode = (ctx, ring, opcode, payload, reply) => this.decode(ctx, ring, opcode, payload, reply);
    return [
        { name: "vulkan", first: VK_FIRST_OLD, last: VK_LAST_OLD, decode,
            sync_task: (ctx, op, words) => this.sync_task(ctx, op, words), destroy: ctx => this.destroy(ctx) },
        { name: "vulkan", first: VK_FIRST, last: VK_LAST, decode },
    ];
};

/**
 * The context's Vulkan state (the model's context: its objects): a process's
 * @param {!Object} ctx
 */
GfxstreamVulkan.prototype.state = function(ctx)
{
    let st = ctx.decoder_state.get("vulkan");
    if(!st)
    {
        st = {
            ctx_id: ctx.id,
            objects: new Map(),
            physical_device: 0,
            /** the last sequence number run (QUEUE_SUBMIT_WITH_COMMANDS: the process's commands in order) */
            seqno: 0,
            /** the guest's blob ids (VkCreateBlobGOOGLE) -> its memory */
            blobs: new Map(),
            /** device:family:index -> the queue's handle */
            queues: new Map(),
            /** descriptor update templates: their entries */
            templates: new Map(),
            /** the host syncs' sequence numbers, by queue or command buffer */
            order: new Map(),
            /** images of gralloc buffers (VkNativeBufferANDROID) -> the memory imported for them */
            native_images: new Map(),
            since: new Map(),
        };
        this.vk.create_context(st);
        ctx.decoder_state.set("vulkan", st);
    }
    return st;
};

GfxstreamVulkan.prototype.new_handle = function()
{
    return this.next_handle++;
};

GfxstreamVulkan.prototype.error = function(what)
{
    this.stats.errors++;
    this.stats.last_error = what;
    if(this.stats.errors <= 20) dbg_log("gfxstream vulkan: " + what, LOG_VIRTIO);
};

/**
 * A command of a ring's stream: its sequence number, then its parameters
 * @return {*} null, a wait, or the transport's AGAIN (a command of another
 *     ring comes first)
 */
GfxstreamVulkan.prototype.decode = function(ctx, ring, opcode, payload, reply)
{
    const st = this.state(ctx);
    if(payload.length < 4) { this.error("command " + opcode + " without its sequence number"); return null; }
    const seqno = (payload[0] | payload[1] << 8 | payload[2] << 16 | payload[3] << 24) >>> 0;
    const ahead = seqno - st.seqno >>> 0;
    if(ahead !== 1)
    {
        // (a number already run: the guest's mistake, run it anyway)
        if(ahead === 0 || ahead > 0x80000000) this.error("sequence number " + seqno + " after " + st.seqno);
        else return this.gfxstream.AGAIN;
    }
    const entry = COMMANDS[opcode];
    if(!entry)
    {
        this.stats.unknown[opcode] = (this.stats.unknown[opcode] || 0) + 1;
        st.seqno = seqno;
        return null;
    }
    const name = entry[0];
    let a;
    try
    {
        const r = new GfxReader(payload, 4);
        a = entry[1](r);
    }
    catch(e)
    {
        this.error(name + ": " + (e && e.message || e));
        if(this.stats.undecoded.length < 4) this.stats.undecoded.push({ name, payload: payload.slice() });
        st.seqno = seqno;
        return null;
    }
    this.stats.commands++;
    let wait = null;
    try
    {
        wait = this.run(st, name, entry, a);
    }
    catch(e)
    {
        this.error(name + ": " + (e && e.message || e));
    }
    if(wait === this.gfxstream.AGAIN) return wait;
    if(this.on_command) this.on_command(name, a);
    const finish = () => {
        st.seqno = seqno;
        if(typeof a.ret === "number" && a.ret < 0) this.stats.failures[name] = a.ret;
        if(!entry[2]) return;
        const w = new GfxWriter(64);
        try
        {
            entry[2](w, a);
            reply(w.result());
        }
        catch(e)
        {
            this.error(name + "'s reply: " + (e && e.message || e));
        }
    };
    if(!wait)
    {
        finish();
        return null;
    }
    return done => /** @type {function(function())} */ (wait)(() => { finish(); done(); });
};

/**
 * A command on the model: its output handles allocated, gfxstream's own
 * commands as the model's
 * @param {!Object} st
 * @param {string} name
 * @param {!Array} entry
 * @param {!Object} a
 * @return {*}
 */
GfxstreamVulkan.prototype.run = function(st, name, entry, a)
{
    switch(name)
    {
        case "vkEnumeratePhysicalDevices":
            // (one, the same each time)
            if(a.pPhysicalDevices) a.pPhysicalDevices = a.pPhysicalDevices.map(() => st.physical_device || (st.physical_device = this.new_handle()));
            return this.model(st, name, a);
        case "vkEnumerateDeviceExtensionProperties":
        {
            // (the guest's array before the model answers into it)
            const asked = a.pProperties ? a.pProperties.length : 0;
            const wait = this.model(st, name, a);
            if(a.ret < 0 || a.pLayerName) return wait;
            const extra = HOST_EXTENSIONS.filter(([n]) => !DEVICE_EXTENSIONS[n]);
            const total = Object.keys(DEVICE_EXTENSIONS).length + extra.length;
            if(!a.pProperties) { a.pPropertyCount = total; a.ret = VK_SUCCESS; return wait; }
            const all = Object.entries(DEVICE_EXTENSIONS).concat(extra).map(([extensionName, specVersion]) => ({ extensionName, specVersion }));
            a.pProperties = all.slice(0, asked);
            a.pPropertyCount = a.pProperties.length;
            a.ret = asked < total ? 5 /* VK_INCOMPLETE */ : VK_SUCCESS;
            return wait;
        }
        case "vkCreateDevice":
        {
            // (what the guest emulates, or gfxstream's host does: not the model's)
            const info = a.pCreateInfo;
            const names = info.ppEnabledExtensionNames || [];
            const kept = names.filter(n => DEVICE_EXTENSIONS[n]);
            if(kept.length !== names.length)
            {
                for(const n of names) if(!DEVICE_EXTENSIONS[n]) this.stats.unimplemented["(extension) " + n] = 1;
                a.pCreateInfo = Object.assign({}, info, { enabledExtensionCount: kept.length, ppEnabledExtensionNames: kept });
            }
            a.pDevice = this.new_handle();
            const wait = this.model(st, name, a);
            a.pCreateInfo = info;
            return wait;
        }
        case "vkGetDeviceQueue":
        case "vkGetDeviceQueue2":
        {
            const info = name === "vkGetDeviceQueue" ? a : a.pQueueInfo;
            const key = a.device + ":" + info.queueFamilyIndex + ":" + info.queueIndex;
            if(st.queues.has(key)) { a.pQueue = st.queues.get(key); return null; }
            a.pQueue = this.new_handle();
            st.queues.set(key, a.pQueue);
            return this.model(st, name, a);
        }
        case "vkCreateImage":
            a.pImage = this.new_handle();
            this.create_image(st, a);
            return null;
        case "vkBindImageMemory2":
        case "vkBindImageMemory2KHR":
        {
            // (a swapchain image: Android's libvulkan binds it to its gralloc
            // buffer with VkNativeBufferANDROID in the bind's chain, no memory)
            const binds = [];
            for(const bind of a.pBindInfos || [])
            {
                let native = null;
                for(let c = bind.pNext; c; c = c.pNext) if(c.sType === STYPE_NATIVE_BUFFER_ANDROID) native = c;
                if(!native) { binds.push(bind); continue; }
                const ret = this.bind_native(st, a.device, bind.image, native.handle);
                if(ret !== VK_SUCCESS) { a.ret = ret; return null; }
            }
            if(!binds.length) { a.ret = VK_SUCCESS; return null; }
            const rest = Object.assign({}, a, { bindInfoCount: binds.length, pBindInfos: binds });
            const wait = this.model(st, "vkBindImageMemory2", rest);
            a.ret = rest.ret;
            return wait;
        }
        case "vkDestroyImage":
        {
            const memory = st.native_images.get(a.image);
            this.model(st, name, a);
            if(memory) { st.native_images.delete(a.image); this.model(st, "vkFreeMemory", { device: a.device, memory, pAllocator: null }); }
            return null;
        }
        case "vkCreateImageWithRequirementsGOOGLE":
        case "vkCreateBufferWithRequirementsGOOGLE":
        {
            const image = name === "vkCreateImageWithRequirementsGOOGLE";
            if(image) { a.pImage = this.new_handle(); this.create_image(st, a); }
            else { a.pBuffer = this.new_handle(); this.model(st, "vkCreateBuffer", a); }
            if(a.ret !== VK_SUCCESS) return null;
            const q = image ? { device: a.device, image: a.pImage, pMemoryRequirements: {} } : { device: a.device, buffer: a.pBuffer, pMemoryRequirements: {} };
            this.model(st, image ? "vkGetImageMemoryRequirements" : "vkGetBufferMemoryRequirements", q);
            a.pMemoryRequirements = q.pMemoryRequirements;
            return null;
        }
        case "vkAllocateMemory":
        {
            a.pMemory = this.new_handle();
            // (gfxstream's imports are of virtio-gpu resources: the model's)
            let blob = null;
            const chain = [];
            for(let s = a.pAllocateInfo.pNext; s; s = s.pNext)
            {
                if(s.sType === STYPE_CREATE_BLOB_GOOGLE) blob = s;
                else if(s.sType === STYPE_IMPORT_COLOR_BUFFER_GOOGLE) chain.push({ sType: STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA, resourceId: s.colorBuffer });
                else if(s.sType === STYPE_IMPORT_BUFFER_GOOGLE) chain.push({ sType: STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA, resourceId: s.buffer });
                else chain.push(Object.assign({}, s));
            }
            for(let i = 0; i < chain.length; i++) chain[i].pNext = chain[i + 1] || null;
            a.pAllocateInfo = Object.assign({}, a.pAllocateInfo, { pNext: chain[0] || null });
            this.model(st, name, a);
            if(a.ret === VK_SUCCESS && blob) st.blobs.set(blob.blobId, a.pMemory);
            return null;
        }
        case "vkFreeMemory":
        case "vkFreeMemorySyncGOOGLE":
            for(const [blob_id, memory] of st.blobs) if(memory === a.memory) st.blobs.delete(blob_id);
            this.model(st, "vkFreeMemory", a);
            a.ret = VK_SUCCESS;
            return null;
        case "vkGetBlobGOOGLE":
        {
            // (the memory, mappable: RESOURCE_CREATE_BLOB of its blob id next)
            const memory = st.objects.get(a.memory);
            a.ret = memory && memory.host_visible ? VK_SUCCESS : VK_ERROR_MEMORY_MAP_FAILED;
            return null;
        }
        case "vkMapMemoryIntoAddressSpaceGOOGLE":
        case "vkGetMemoryHostAddressInfoGOOGLE":
            // (the goldfish address space: not with deferred mapping)
            a.ret = VK_ERROR_MEMORY_MAP_FAILED;
            return null;
        case "vkQueueHostSyncGOOGLE":
            return this.host_sync(st, "queue " + a.queue, a.needHostSync, a.sequenceNumber, true);
        case "vkQueueFlushCommandsGOOGLE":
            this.flush_commands(st, a.commandBuffer, a.pData);
            return null;
        case "vkCreateDescriptorUpdateTemplate":
        case "vkCreateDescriptorUpdateTemplateKHR":
            a.pDescriptorUpdateTemplate = this.new_handle();
            st.templates.set(a.pDescriptorUpdateTemplate, a.pCreateInfo);
            a.ret = VK_SUCCESS;
            return null;
        case "vkDestroyDescriptorUpdateTemplate":
        case "vkDestroyDescriptorUpdateTemplateKHR":
            st.templates.delete(a.descriptorUpdateTemplate);
            return null;
        case "vkUpdateDescriptorSetWithTemplateSizedGOOGLE":
        case "vkUpdateDescriptorSetWithTemplateSized2GOOGLE":
            return this.template_update(st, a);
        case "vkGetLinearImageLayoutGOOGLE":
        case "vkGetLinearImageLayout2GOOGLE":
            // (the model's linear images: rows of the texels, no padding)
            a.pOffset = 0;
            a.pRowPitchAlignment = 1;
            return null;
        case "vkGetSwapchainGrallocUsageANDROID":
            a.grallocUsage = GRALLOC_USAGE_HW;
            a.ret = VK_SUCCESS;
            return null;
        case "vkGetSwapchainGrallocUsage2ANDROID":
            a.grallocConsumerUsage = GRALLOC_USAGE_HW;
            a.grallocProducerUsage = GRALLOC_USAGE_HW;
            a.ret = VK_SUCCESS;
            return null;
        case "vkAcquireImageANDROID":
        {
            // (the guest waits for the buffer's fence; the host signals what it was given)
            const semaphore = st.objects.get(a.semaphore), fence = st.objects.get(a.fence);
            if(semaphore) { semaphore.signaled = true; if(semaphore.timeline) semaphore.value++; }
            if(fence) fence.signaled = true;
            this.vk.wake();
            a.ret = VK_SUCCESS;
            return null;
        }
        case "vkQueueSignalReleaseImageANDROID":
        case "vkQueueSignalReleaseImageANDROIDAsyncGOOGLE":
            // (the image's work is the queue's: CREATE_QSRI_EXPORT_VK waits for it)
            a.pNativeFenceFd = -1;
            a.ret = VK_SUCCESS;
            return null;
        case "vkGetPhysicalDeviceImageFormatProperties2":
        case "vkGetPhysicalDeviceImageFormatProperties2KHR":
        {
            // Android hardware buffers: gralloc's, virtio-gpu resources the
            // model imports as it imports dma-bufs (the guest keeps only AHB's
            // bits of what the host says)
            let ahb = false;
            const chain = [];
            for(let s = a.pImageFormatInfo.pNext; s; s = s.pNext)
            {
                const copy = Object.assign({}, s);
                if(s.sType === STYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO && s.handleType === HANDLE_AHB) { copy.handleType = HANDLE_DMA_BUF; ahb = true; }
                chain.push(copy);
            }
            if(!ahb) return this.model(st, "vkGetPhysicalDeviceImageFormatProperties2", a);
            for(let i = 0; i < chain.length; i++) chain[i].pNext = chain[i + 1] || null;
            const info = a.pImageFormatInfo;
            a.pImageFormatInfo = Object.assign({}, info, { pNext: chain[0] || null });
            this.model(st, "vkGetPhysicalDeviceImageFormatProperties2", a);
            a.pImageFormatInfo = info;
            for(let s = a.pImageFormatProperties.pNext; s; s = s.pNext)
            {
                if(s.sType !== STYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES || a.ret !== VK_SUCCESS) continue;
                s.externalMemoryProperties = { externalMemoryFeatures: EXTERNAL_MEMORY_FEATURES_AHB,
                    exportFromImportedHandleTypes: HANDLE_AHB, compatibleHandleTypes: HANDLE_AHB };
            }
            return null;
        }
        case "vkGetSemaphoreGOOGLE":
        case "vkTraceAsyncGOOGLE":
            a.ret = VK_SUCCESS;
            return null;
    }
    for(const p of entry[4] || [])
    {
        if(Array.isArray(a[p])) a[p] = a[p].map(() => this.new_handle());
        else if(a[p] !== null) a[p] = this.new_handle();
    }
    return this.model(st, SAME_AS[name] || name, a);
};

/**
 * vkCreateImage: an image of a gralloc buffer (VkNativeBufferANDROID: the
 * guest put its virtio-gpu resource's id in the handle) is the model's
 * image bound to the resource, imported as memory
 * @param {!Object} st
 * @param {!Object} a vkCreateImage's parameters, pImage allocated
 */
GfxstreamVulkan.prototype.create_image = function(st, a)
{
    let native = null;
    const chain = [];
    for(let s = a.pCreateInfo.pNext; s; s = s.pNext)
    {
        if(s.sType === STYPE_NATIVE_BUFFER_ANDROID) native = s;
        else chain.push(Object.assign({}, s));
    }
    if(!native)
    {
        this.model(st, "vkCreateImage", a);
        return;
    }
    for(let i = 0; i < chain.length; i++) chain[i].pNext = chain[i + 1] || null;
    a.pCreateInfo = Object.assign({}, a.pCreateInfo, { pNext: chain[0] || null });
    this.model(st, "vkCreateImage", a);
    if(a.ret !== VK_SUCCESS) return;
    a.ret = this.bind_native(st, a.device, a.pImage, native.handle);
    if(a.ret !== VK_SUCCESS) this.model(st, "vkDestroyImage", { device: a.device, image: a.pImage, pAllocator: null });
};

/**
 * An image of a gralloc buffer (VkNativeBufferANDROID, its handle the
 * virtio-gpu resource): memory imported from the resource, bound to it,
 * freed with the image
 * @return {number} the VkResult
 */
GfxstreamVulkan.prototype.bind_native = function(st, device, image, resource_id)
{
    if(st.native_images.has(image)) return VK_SUCCESS;
    const q = { device, image, pMemoryRequirements: {} };
    this.model(st, "vkGetImageMemoryRequirements", q);
    const memory = this.new_handle();
    const alloc = { device, pAllocator: null, pMemory: memory, pAllocateInfo: { sType: STYPE_MEMORY_ALLOCATE_INFO,
        pNext: { sType: STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA, pNext: null, resourceId: resource_id },
        allocationSize: q.pMemoryRequirements.size || 1, memoryTypeIndex: MEMORY_DEVICE_LOCAL } };
    this.model(st, "vkAllocateMemory", alloc);
    if(alloc.ret !== VK_SUCCESS)
    {
        this.error("the gralloc buffer of resource " + resource_id + ": not importable (" + alloc.ret + ")");
        return alloc.ret;
    }
    const bind = { device, image, memory, memoryOffset: 0 };
    this.model(st, "vkBindImageMemory", bind);
    st.native_images.set(image, memory);
    return bind.ret === undefined ? VK_SUCCESS : bind.ret;
};

/**
 * The model's command (its core name for an extension's alias)
 * @return {?function(function())}
 */
GfxstreamVulkan.prototype.model = function(st, name, a)
{
    if(!this.vk.handles(name))
    {
        const core = name.replace(/(KHR|EXT)$/, "");
        if(core !== name && this.vk.handles(core)) name = core;
        else if(!name.startsWith("vkCmd")) this.stats.unimplemented[name] = (this.stats.unimplemented[name] || 0) + 1;
    }
    return this.vk.handle(st, name, a);
};

/**
 * vkQueueHostSyncGOOGLE, vkCommandBufferHostSyncGOOGLE: an encoder's work
 * on a queue or a command buffer after another's (their sequence numbers);
 * waits for the one before it at most 5 s
 * @param {boolean} can_wait (a command buffer's, in a flush: not)
 */
GfxstreamVulkan.prototype.host_sync = function(st, key, need, sequence, can_wait)
{
    const last = st.order.get(key) || 0;
    if(need && (sequence - last >>> 0) !== 1 && can_wait)
    {
        const since = st.since.get(key);
        if(since === undefined) st.since.set(key, this.vk.now);
        if(since === undefined || this.vk.now - since < HOST_SYNC_TIMEOUT) return this.gfxstream.AGAIN;
    }
    st.since.delete(key);
    st.order.set(key, sequence);
    return null;
};

/**
 * vkQueueFlushCommandsGOOGLE: a command buffer's commands as the guest
 * recorded them (opcode, size, parameters; no sequence numbers, no handle)
 * @param {!Object} st
 * @param {number} cb the command buffer
 * @param {!Uint8Array} data
 */
GfxstreamVulkan.prototype.flush_commands = function(st, cb, data)
{
    const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    let p = 0;
    while(p + 8 <= data.length)
    {
        const opcode = view.getUint32(p, true), size = view.getUint32(p + 4, true);
        if(size < 8 || p + size > data.length)
        {
            this.error("a command buffer's command " + opcode + " of " + size + " bytes");
            return;
        }
        const entry = COMMANDS[opcode];
        if(!entry)
        {
            this.stats.unknown[opcode] = (this.stats.unknown[opcode] || 0) + 1;
            p += size;
            continue;
        }
        const name = entry[0];
        try
        {
            const a = entry[1](new GfxReader(data, p + 8, p + size));
            a.commandBuffer = cb;
            this.stats.flushed++;
            if(this.on_command) this.on_command(name, a);
            if(name === "vkCommandBufferHostSyncGOOGLE") this.host_sync(st, "cb " + cb, a.needHostSync, a.sequenceNumber, false);
            else this.model(st, SAME_AS[name] || name, a);
        }
        catch(e)
        {
            this.error(name + " (in a command buffer): " + (e && e.message || e));
        }
        p += size;
    }
};

/**
 * vkUpdateDescriptorSetWithTemplateSized(2)GOOGLE: the template's entries'
 * descriptors in their order (image infos, buffer infos, buffer views: the
 * host's linearized template), as descriptor writes
 */
GfxstreamVulkan.prototype.template_update = function(st, a)
{
    const info = st.templates.get(a.descriptorUpdateTemplate);
    if(!info) { this.error("an update of template " + a.descriptorUpdateTemplate); return null; }
    let images = 0, buffers = 0, views = 0;
    const writes = [];
    for(const entry of info.pDescriptorUpdateEntries || [])
    {
        const type = entry.descriptorType, n = entry.descriptorCount;
        const w = { sType: STYPE_WRITE_DESCRIPTOR_SET, pNext: null, dstSet: a.descriptorSet, dstBinding: entry.dstBinding,
            dstArrayElement: entry.dstArrayElement, descriptorCount: n, descriptorType: type, pImageInfo: null, pBufferInfo: null, pTexelBufferView: null };
        if(IMAGE_DESCRIPTORS.has(type)) { w.pImageInfo = (a.pImageInfos || []).slice(images, images + n); images += n; }
        else if(BUFFER_DESCRIPTORS.has(type)) { w.pBufferInfo = (a.pBufferInfos || []).slice(buffers, buffers + n); buffers += n; }
        else if(TEXEL_DESCRIPTORS.has(type)) { w.pTexelBufferView = (a.pBufferViews || []).slice(views, views + n); views += n; }
        else continue;
        writes.push(w);
    }
    return this.model(st, "vkUpdateDescriptorSets", { device: a.device, descriptorWriteCount: writes.length, pDescriptorWrites: writes,
        descriptorCopyCount: 0, pDescriptorCopies: null });
};

/**
 * The execbuffer commands on Vulkan objects: CREATE_EXPORT_SYNC_VK (a
 * fence's signal), CREATE_QSRI_EXPORT_VK (an image's release: its queue's
 * work); their fence on the context's timeline waits for it
 * @return {(?function(function())|undefined)} undefined: not one of these
 */
GfxstreamVulkan.prototype.sync_task = function(ctx, op, words)
{
    if(op !== CREATE_EXPORT_SYNC_VK && op !== CREATE_QSRI_EXPORT_VK) return undefined;
    const st = this.state(ctx);
    const vk = this.vk;
    let check;
    if(op === CREATE_EXPORT_SYNC_VK)
    {
        const id = words[2] + words[3] * 0x100000000;
        const fence = st.objects.get(id);
        if(!fence || fence.signaled) return null;
        check = () => fence.signaled || st.objects.get(id) !== fence;
    }
    else
    {
        // (the queues' work so far)
        const queues = [...st.objects.values()].filter(o => o.type === "queue");
        if(queues.every(q => !q.pending.length && !q.inflight)) return null;
        check = () => queues.every(q => !q.pending.length && !q.inflight);
    }
    return done => {
        if(check()) done();
        else vk.add_waiter(check, Infinity, () => done());
    };
};

// Snapshots (G6): a context's objects and tables as Venus's are saved
// (venus_state.js); the model makes the renderer's objects again

/** the key of a context's own tables among its objects in a snapshot (handles start at 0x1000) */
const TABLES = -1;

/** @return {!Array} */
GfxstreamVulkan.prototype.get_state = function()
{
    return [this.next_handle, this.vk.get_state()];
};

/**
 * @param {!Array} state from get_state
 * @param {!Array<!Object>} contexts the contexts' Vulkan states, restored (restore_context)
 */
GfxstreamVulkan.prototype.set_state = function(state, contexts)
{
    const [next_handle, model] = state;
    this.next_handle = next_handle;
    this.vk.set_state(model, contexts);
};

/**
 * A context's Vulkan state for a snapshot: its objects, its tables
 * @param {!Object} ctx
 * @param {function(!Object): Array} outside [kind, id] of an object owned elsewhere (a blob)
 * @return {?string}
 */
GfxstreamVulkan.prototype.save_context = function(ctx, outside)
{
    const st = ctx.decoder_state.get("vulkan");
    if(!st) return null;
    const objects = new Map(st.objects);
    objects.set(TABLES, { physical_device: st.physical_device, seqno: st.seqno, blobs: st.blobs, queues: st.queues,
        templates: st.templates, order: st.order, native_images: st.native_images });
    return encode_objects(objects, o => o === st ? ["ctx", ctx.id] : outside(o));
};

/**
 * @param {!Object} ctx the restored context
 * @param {string} json from save_context
 * @param {function(number): Object} blob_of the restored blob of a resource id
 * @return {!Object} its Vulkan state
 */
GfxstreamVulkan.prototype.restore_context = function(ctx, json, blob_of)
{
    const st = this.state(ctx);
    const objects = decode_objects(json, ([kind, x]) => kind === "ctx" ? st : kind === "blob" ? blob_of(x) : null);
    const tables = objects.get(TABLES);
    objects.delete(TABLES);
    st.objects = objects;
    st.physical_device = tables.physical_device;
    st.seqno = tables.seqno;
    for(const key of ["blobs", "queues", "templates", "order", "native_images"]) st[key] = tables[key];
    st.since = new Map();
    return st;
};

/** CTX_DESTROY: the process's objects go */
GfxstreamVulkan.prototype.destroy = function(ctx)
{
    const st = ctx.decoder_state.get("vulkan");
    if(st) this.vk.destroy_context(st);
};

/**
 * RESOURCE_CREATE_BLOB of a blob id: a memory's (vkAllocateMemory's
 * VkCreateBlobGOOGLE, after vkGetBlobGOOGLE)
 * @return {boolean}
 */
GfxstreamVulkan.prototype.export_memory = function(ctx, blob)
{
    const st = this.state(ctx);
    const memory = st.objects.get(st.blobs.get(blob.blob_id));
    if(!memory || !this.vk.export_memory(st, memory, blob)) return false;
    blob.memory = memory;
    return true;
};
                                                                                                                                                                                                                                                           source/v64/src/graphics_adapters/virtio_gpu/plugin.js                                               0000644 0000000 0000000 00000003440 00000000000 020162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // graphics_adapter: "virtio_gpu" -- virtio-gpu as virtio-vga (1AF4:1050).
// Built into build/v86-virtio-gpu.js; from the source tree,
// src/graphics_adapter.js imports this file directly.

import { GraphicsMachine, register_graphics_adapter } from "../machine.js";
import { VirtioGPU, host_visible_size } from "./virtio_gpu_device.js";

register_graphics_adapter({
    "name": "virtio_gpu",
    // The VGA BIOS's PCI ROM header must name the device (SeaBIOS checks it)
    "pci_vendor": 0x1AF4,
    "pci_device": 0x1050,
    // the device memory a pinned level's host visible memory needs (0: the
    // machine's own amount; the ARM core reserves it after RAM)
    "device_memory_size": options => host_visible_size((options["test"] || {})["level"] || ""),
    "create": (handle, options) =>
    {
        const test = options["test"] || {};
        const device = new VirtioGPU(new GraphicsMachine(handle), {
            vram_size: options["vram_size"],
            // without it, the highest level there is
            level: test["level"],
            // how many displays the guest gets (tests; 1 otherwise)
            scanouts: test["scanouts"],
            // the channel to GX (the page's; tests bring their own): 3D
            renderer: options["renderer"] || test["renderer"],
        });
        return {
            // (none on a machine without VGA)
            "vga": device.has_vga ? device.vga : null,
            "virtio_gpu": device,
            "get_state": () => device.get_state(),
            "set_state": state => device.set_state(state),
            "reset": () => device.reset(),
            // what the GPU has of the guest's 3D (a snapshot reads it back first)
            "has_host_state": () => !!device.virgl,
            "prepare_save": () => device.prepare_save(),
        };
    },
});
                                                                                                                                                                                                                                source/v64/src/graphics_adapters/virtio_gpu/tgsi.js                                                 0000644 0000000 0000000 00000031063 00000000000 017634  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // TGSI as Mesa's virgl driver sends it: the text tgsi_dump() writes
// (virgl_encode_shader_state), parsed into a program tgsi_vgpu10.js
// translates. The syntax is tgsi_dump.c's: a processor line, PROPERTY
// lines, DCL lines, IMM lines, then numbered instructions.
//
//   VERT
//   PROPERTY NEXT_SHADER FRAG
//   DCL IN[0]
//   DCL OUT[1].xyz, GENERIC[0]
//   DCL CONST[1][0..3]
//   DCL TEMP[0..3], ARRAY(1)
//   DCL SVIEW[0], 2D, FLOAT
//   IMM[0] UINT32 {1065353216, 0, 0, 0}
//     0: MAD_SAT TEMP[0].xy, -|IN[0].xyxx|, CONST[0][ADDR[0].x+3], IMM[0].xxxx
//     1: TEX TEMP[1], TEMP[0], SAMP[0], 2D, IMM[1].xyz
//     2: UIF TEMP[2].xxxx :4
//     3: END

/** The processors, by their names in the text: [name, the program type of struct virgl's shader stages] */
export const PROCESSOR = { VERT: 0, FRAG: 1, GEOM: 2, TESS_CTRL: 3, TESS_EVAL: 4, COMP: 5 };

export class TGSIParseError extends Error {}

const SWIZZLE = { x: 0, y: 1, z: 2, w: 3 };

/**
 * One bracket of a register: "[3]", "[ADDR[0].x+3]", "[TEMP[1].y-2]", "[]"
 * @return {{index: number, rel: ?Object, empty: boolean}}
 */
function parse_index(text)
{
    if(text === "") return { index: 0, rel: null, empty: true };
    if(/^-?\d+$/.test(text)) return { index: +text, rel: null, empty: false };
    const m = /^([A-Z_]+)\[(\d+)\]\.([xyzw0-3])([+-]\d+)?$/.exec(text);
    if(!m) throw new TGSIParseError("index " + text);
    const comp = m[3] in SWIZZLE ? SWIZZLE[m[3]] : +m[3];
    return { index: m[4] ? +m[4] : 0, rel: { file: m[1], index: +m[2], comp }, empty: false };
}

/**
 * The bracket groups after a file name: "[1][ADDR[0].x+2](3)" -> ["1", "ADDR[0].x+2"], array 3
 * @return {{groups: !Array<string>, array: number, rest: string}}
 */
function brackets(text)
{
    const groups = [];
    let array = 0;
    let at = 0;
    while(text[at] === "[")
    {
        let depth = 0, end = at;
        for(; end < text.length; end++)
        {
            if(text[end] === "[") depth++;
            else if(text[end] === "]" && --depth === 0) break;
        }
        if(end >= text.length) throw new TGSIParseError("unclosed bracket in " + text);
        groups.push(text.slice(at + 1, end));
        at = end + 1;
        const m = /^\((\d+)\)/.exec(text.slice(at));
        if(m)
        {
            array = +m[1];
            at += m[0].length;
        }
    }
    return { groups, array, rest: text.slice(at) };
}

/**
 * A register operand without its modifiers: FILE[..][..] and the rest
 * (".xyzw"): its file, dimension and index (each an immediate or relative to
 * an address register: {file, index, comp}), its array id
 * @return {{reg: !Object, rest: string}}
 */
function parse_register(text)
{
    const m = /^([A-Z_]+)/.exec(text);
    if(!m) throw new TGSIParseError("operand " + text);
    const file = m[1];
    const { groups, array, rest } = brackets(text.slice(file.length));
    if(!groups.length) throw new TGSIParseError("operand without an index: " + text);
    const last = parse_index(groups[groups.length - 1]);
    const reg = { file, index: last.index, rel: last.rel, dim: 0, dim_rel: null, has_dim: groups.length > 1, array };
    if(groups.length > 1)
    {
        const first = parse_index(groups[0]);
        reg.dim = first.index;
        reg.dim_rel = first.rel;
    }
    return { reg, rest };
}

/** ".xyz" -> 0b0111 */
function parse_mask(text)
{
    if(!text) return 0xF;
    if(!/^\.[xyzw]+$/.test(text)) throw new TGSIParseError("write mask " + text);
    let mask = 0;
    for(const c of text.slice(1)) mask |= 1 << SWIZZLE[c];
    return mask;
}

/** ".xyzx" -> [0, 1, 2, 0]; ".x" -> [0, 0, 0, 0] */
function parse_swizzle(text)
{
    if(!text) return [0, 1, 2, 3];
    if(!/^\.[xyzw]{1,4}$/.test(text)) throw new TGSIParseError("swizzle " + text);
    const s = Array.from(text.slice(1), c => SWIZZLE[c]);
    while(s.length < 4) s.push(s[s.length - 1]);
    return s;
}

/** A destination: "TEMP[0].xy" */
function parse_dst(text)
{
    const { reg, rest } = parse_register(text);
    return Object.assign(reg, { mask: parse_mask(rest) });
}

/** A source: "-|CONST[0][3].xyzw|" */
function parse_src(text)
{
    let neg = false, abs = false;
    if(text[0] === "-")
    {
        neg = true;
        text = text.slice(1);
    }
    if(text[0] === "|")
    {
        if(text[text.length - 1] !== "|") throw new TGSIParseError("absolute value " + text);
        abs = true;
        text = text.slice(1, -1);
    }
    const { reg, rest } = parse_register(text);
    return Object.assign(reg, { swizzle: parse_swizzle(rest), neg, abs });
}

/** Split at the commas outside of brackets and braces */
function split_operands(text)
{
    const parts = [];
    let depth = 0, start = 0;
    for(let i = 0; i < text.length; i++)
    {
        const c = text[i];
        if(c === "[" || c === "{" || c === "(") depth++;
        else if(c === "]" || c === "}" || c === ")") depth--;
        else if(c === "," && depth === 0)
        {
            parts.push(text.slice(start, i).trim());
            start = i + 1;
        }
    }
    const last = text.slice(start).trim();
    if(last) parts.push(last);
    return parts;
}

// how many destinations an opcode has (1 if not here)
const NO_DST = new Set(["END", "RET", "KILL", "KILL_IF", "IF", "UIF", "ELSE", "ENDIF", "BGNLOOP", "ENDLOOP", "BRK", "CONT",
    "BRK", "SWITCH", "CASE", "DEFAULT", "ENDSWITCH", "EMIT", "ENDPRIM", "NOP", "BARRIER", "MEMBAR", "CAL", "BGNSUB", "ENDSUB",
    "FENCE", "STORE", "DEMOTE", "BREAKC"]);
const TWO_DST = new Set(["DFRACEXP"]);

const TEXTURE_TARGETS = new Set(["BUFFER", "1D", "2D", "3D", "CUBE", "RECT", "SHADOW1D", "SHADOW2D", "SHADOWRECT", "1D_ARRAY",
    "2D_ARRAY", "SHADOW1D_ARRAY", "SHADOW2D_ARRAY", "SHADOWCUBE", "2D_MSAA", "2D_ARRAY_MSAA", "CUBE_ARRAY", "SHADOWCUBE_ARRAY",
    "UNKNOWN"]);
const MEMORY_QUALIFIERS = new Set(["COHERENT", "RESTRICT", "VOLATILE", "STREAM_CACHE_POLICY"]);

/**
 * A declaration line, without "DCL "
 * @return {!Object}
 */
function parse_declaration(text)
{
    const parts = split_operands(text);
    const head = parts.shift();
    const m = /^([A-Z_]+)((?:\[[^\]]*\])+)(\.[xyzw]+)?$/.exec(head);
    if(!m) throw new TGSIParseError("declaration " + text);
    const file = m[1];
    const groups = m[2].slice(1, -1).split("][");
    const range = groups[groups.length - 1].split("..");
    const decl = {
        file,
        first: +range[0], last: range.length > 1 ? +range[1] : +range[0],
        // CONST[1][0..3]: the buffer; IN[][0] (2D inputs): -1
        dim: groups.length > 1 ? (groups[0] === "" ? -1 : +groups[0]) : 0,
        two_d: groups.length > 1,
        mask: parse_mask(m[3] || ""),
        array: 0, local: false, invariant: false,
        semantic: null, semantic_index: 0, stream: null,
        interpolate: null, location: "CENTER",
        // SVIEW: the target and the return types; IMAGE: target, format, writable
        target: null, return_types: null, format: null, writable: false, raw: false, atomic: false, memory: null,
    };
    for(const part of parts)
    {
        let a;
        if((a = /^ARRAY\((\d+)\)$/.exec(part))) decl.array = +a[1];
        else if(part === "LOCAL") decl.local = true;
        else if(part === "INVARIANT") decl.invariant = true;
        else if(part === "WR") decl.writable = true;
        else if(part === "RAW") decl.raw = true;
        else if(part === "ATOMIC") decl.atomic = true;
        else if(/^(GLOBAL|SHARED|PRIVATE|INPUT)$/.test(part) && file === "MEMORY") decl.memory = part;
        else if((a = /^STREAM\((.*)\)$/.exec(part))) decl.stream = a[1].split(",").map(s => +s.trim());
        else if(/^(CONSTANT|LINEAR|PERSPECTIVE|COLOR)$/.test(part) && decl.semantic !== null && file === "IN") decl.interpolate = part;
        else if(/^(CENTER|CENTROID|SAMPLE)$/.test(part) && file === "IN") decl.location = part;
        else if((file === "SVIEW" || file === "IMAGE") && decl.target === null && TEXTURE_TARGETS.has(part)) decl.target = part;
        else if(file === "SVIEW" && /^(UNORM|SNORM|SINT|UINT|FLOAT)$/.test(part)) (decl.return_types = decl.return_types || []).push(part);
        else if(file === "IMAGE" && part.startsWith("PIPE_FORMAT_")) decl.format = part;
        else if((a = /^([A-Z_0-9]+)(?:\[(\d+)\])?$/.exec(part)) && decl.semantic === null)
        {
            decl.semantic = a[1];
            decl.semantic_index = a[2] ? +a[2] : 0;
        }
        else if(/^(CONSTANT|LINEAR|PERSPECTIVE|COLOR)$/.test(part)) decl.interpolate = part;
        else throw new TGSIParseError("declaration part " + part + " in " + text);
    }
    if(decl.return_types)
    {
        while(decl.return_types.length < 4) decl.return_types.push(decl.return_types[decl.return_types.length - 1]);
    }
    return decl;
}

/** An immediate line, without "IMM[n] " */
function parse_immediate(text)
{
    const m = /^(UINT32|INT32|FLT32|FLT64|UINT64|INT64)\s*\{(.*)\}$/.exec(text.trim());
    if(!m) throw new TGSIParseError("immediate " + text);
    const type = m[1];
    const values = new Uint32Array(4);
    const f = new Float32Array(1), u = new Uint32Array(f.buffer);
    m[2].split(",").map(s => s.trim()).filter(s => s.length).forEach((s, i) => {
        if(i >= 4) return;
        if(type === "FLT32")
        {
            if(/^0x/i.test(s)) values[i] = parseInt(s, 16) >>> 0;
            else
            {
                f[0] = parseFloat(s);
                values[i] = u[0];
            }
        }
        else if(/^0x/i.test(s)) values[i] = parseInt(s, 16) >>> 0;
        else values[i] = (+s) >>> 0;
    });
    return { type, values };
}

/**
 * An instruction line, without its number
 * @return {!Object}
 */
function parse_instruction(text)
{
    let label = -1;
    const lm = /\s:(\d+)$/.exec(text);
    if(lm)
    {
        label = +lm[1];
        text = text.slice(0, lm.index);
    }
    const sp = text.search(/\s/);
    let name = sp < 0 ? text : text.slice(0, sp);
    const rest = sp < 0 ? "" : text.slice(sp + 1);
    let saturate = false, precise = false;
    if(name.endsWith("_PRECISE"))
    {
        precise = true;
        name = name.slice(0, -8);
    }
    if(name.endsWith("_SAT"))
    {
        saturate = true;
        name = name.slice(0, -4);
    }
    const parts = split_operands(rest);
    const ins = { op: name, saturate, precise, label, dst: [], src: [], target: null, offsets: [], memory: [], format: null };
    // the texture target, offsets, memory qualifiers come after the registers
    const registers = [];
    for(const part of parts)
    {
        if(TEXTURE_TARGETS.has(part) && registers.length) ins.target = part;
        else if(MEMORY_QUALIFIERS.has(part)) ins.memory.push(part);
        else if(part.startsWith("PIPE_FORMAT_")) ins.format = part;
        else if(ins.target !== null) ins.offsets.push(parse_src(part));
        else registers.push(part);
    }
    const dsts = NO_DST.has(name) ? 0 : TWO_DST.has(name) ? 2 : 1;
    // stores write their first operand (a buffer, an image, memory)
    if(name === "STORE")
    {
        ins.dst.push(parse_dst(registers[0]));
        for(const r of registers.slice(1)) ins.src.push(parse_src(r));
        return ins;
    }
    for(let i = 0; i < registers.length; i++)
    {
        if(i < dsts) ins.dst.push(parse_dst(registers[i]));
        else ins.src.push(parse_src(registers[i]));
    }
    return ins;
}

/**
 * The text of one shader
 * @param {string} text
 * @return {{processor: number, properties: !Object<string, !Array<string>>, decls: !Array<!Object>,
 *     imms: !Array<{type: string, values: !Uint32Array}>, code: !Array<!Object>}}
 */
export function parse_tgsi(text)
{
    const lines = text.split("\n");
    const program = { processor: -1, properties: {}, decls: [], imms: [], code: [] };
    for(let raw of lines)
    {
        const line = raw.trim();
        if(!line) continue;
        if(program.processor < 0)
        {
            if(!(line in PROCESSOR)) throw new TGSIParseError("processor " + line);
            program.processor = PROCESSOR[line];
            continue;
        }
        let m;
        if(line.startsWith("PROPERTY "))
        {
            const [name, ...values] = line.slice(9).trim().split(/\s+/);
            program.properties[name] = values;
        }
        else if(line.startsWith("DCL "))
        {
            program.decls.push(parse_declaration(line.slice(4).trim()));
        }
        else if((m = /^IMM\[(\d+)\]\s+(.*)$/.exec(line)))
        {
            program.imms[+m[1]] = parse_immediate(m[2]);
        }
        else if((m = /^(\d+):\s*(.*)$/.exec(line)))
        {
            program.code.push(parse_instruction(m[2].trim()));
        }
        else
        {
            throw new TGSIParseError("line " + line);
        }
    }
    if(program.processor < 0) throw new TGSIParseError("no processor");
    return program;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/graphics_adapters/virtio_gpu/tgsi_vgpu10.js                                          0000644 0000000 0000000 00000216104 00000000000 021037  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // TGSI (tgsi.js parses virgl's text) into VGPU10 tokens, the shaders GX
// runs (src/browser/glbridge/shader_ir/dxbc_frontend.js decodes them), as
// Mesa's svga driver does on VMware (svga_tgsi_vgpu10.c), for the subset
// of TGSI Mesa's nir_to_tgsi makes for GL 3.3 / GLES 3.0.
//
// What GL wants and D3D does not have is put in here, so that GX stays a
// D3D renderer; each is part of the variant key a program is translated for:
// - linkage: D3D matches a stage's outputs to the next one's inputs by
//   register, GL by semantic (GENERIC[3]): the next stage's input registers
//   (key.outputs, semantic -> register) say where a stage writes each;
// - the viewport: gallium's may flip Y (GL's framebuffer objects) and map
//   depth from [-1, 1] (clip_halfz off); D3D's cannot, so the last vertex
//   stage flips Y (key.flip_y) and moves Z into [0, 1] (key.halfz off);
// - sampler views have swizzles (GL's texture swizzle, the luminance and
//   alpha formats): applied after each sample (key.swizzles);
// - gl_FragColor into every bound color buffer (FS_COLOR0_WRITES_ALL_CBUFS,
//   key.color_buffers), flat shaded COLOR inputs (key.flatshade), the
//   fragment position GL sees (1/w, integer pixel centers), FACE as +-1.
//
// Registers: TGSI TEMP n is r n, TEMP arrays indexable x(array id), ADDR n
// a temp after those, then the temps the translation needs. VS inputs are
// their vertex elements' registers; FS inputs keep their TGSI index (which
// the previous stage's outputs are moved to).

// VGPU10 opcodes (VGPU10_OPCODE_TYPE)
const OP = {
    ADD: 0, AND: 1, BREAK: 2, CASE: 6, CONTINUE: 7, CUT: 9, DEFAULT: 10, DERIV_RTX: 11, DERIV_RTY: 12,
    DISCARD: 13, DIV: 14, DP2: 15, DP3: 16, DP4: 17, ELSE: 18, EMIT: 19, ENDIF: 21, ENDLOOP: 22, ENDSWITCH: 23,
    EQ: 24, EXP: 25, FRC: 26, FTOI: 27, FTOU: 28, GE: 29, IADD: 30, IF: 31, IEQ: 32, IGE: 33, ILT: 34,
    IMAD: 35, IMAX: 36, IMIN: 37, IMUL: 38, INE: 39, INEG: 40, ISHL: 41, ISHR: 42, ITOF: 43, LD: 45, LD_MS: 46,
    LOG: 47, LOOP: 48, LT: 49, MAD: 50, MIN: 51, MAX: 52, CUSTOMDATA: 53, MOV: 54, MOVC: 55, MUL: 56, NE: 57,
    NOP: 58, NOT: 59, OR: 60, RESINFO: 61, RET: 62, ROUND_NE: 64, ROUND_NI: 65, ROUND_PI: 66, ROUND_Z: 67,
    RSQ: 68, SAMPLE: 69, SAMPLE_C: 70, SAMPLE_C_LZ: 71, SAMPLE_L: 72, SAMPLE_D: 73, SAMPLE_B: 74, SQRT: 75,
    SWITCH: 76, SINCOS: 77, UDIV: 78, ULT: 79, UGE: 80, UMUL: 81, UMAD: 82, UMAX: 83, UMIN: 84, USHR: 85,
    UTOF: 86, XOR: 87, DCL_RESOURCE: 88, DCL_CONSTANT_BUFFER: 89, DCL_SAMPLER: 90,
    DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY: 92, DCL_GS_INPUT_PRIMITIVE: 93, DCL_MAX_OUTPUT_VERTEX_COUNT: 94,
    DCL_INPUT: 95, DCL_INPUT_SGV: 96, DCL_INPUT_SIV: 97, DCL_INPUT_PS: 98, DCL_INPUT_PS_SGV: 99,
    DCL_INPUT_PS_SIV: 100, DCL_OUTPUT: 101, DCL_OUTPUT_SGV: 102, DCL_OUTPUT_SIV: 103, DCL_TEMPS: 104,
    DCL_INDEXABLE_TEMP: 105, VMWARE: 107, LOD: 108, GATHER4: 109, SAMPLE_INFO: 111, BUFINFO: 121,
    DERIV_RTX_COARSE: 122, DERIV_RTX_FINE: 123, DERIV_RTY_COARSE: 124, DERIV_RTY_FINE: 125, GATHER4_C: 126,
    GATHER4_PO: 127, GATHER4_PO_C: 128, RCP: 129, F32TOF16: 130, F16TOF32: 131, COUNTBITS: 134,
    FIRSTBIT_HI: 135, FIRSTBIT_LO: 136, FIRSTBIT_SHI: 137, UBFE: 138, IBFE: 139, BFI: 140, BFREV: 141,
    EVAL_SNAPPED: 203, EVAL_SAMPLE_INDEX: 204, EVAL_CENTROID: 205,
    DCL_THREAD_GROUP: 155, DCL_UAV_TYPED: 156, DCL_UAV_RAW: 157, DCL_TGSM_RAW: 159, LD_UAV_TYPED: 163,
    STORE_UAV_TYPED: 164, LD_RAW: 165, STORE_RAW: 166, IMM_ATOMIC_IADD: 180, IMM_ATOMIC_AND: 181, IMM_ATOMIC_OR: 182,
    IMM_ATOMIC_XOR: 183, IMM_ATOMIC_EXCH: 184, IMM_ATOMIC_CMP_EXCH: 185, IMM_ATOMIC_IMAX: 186, IMM_ATOMIC_IMIN: 187,
    IMM_ATOMIC_UMAX: 188, IMM_ATOMIC_UMIN: 189, SYNC: 190,
    DADD: 191, DMAX: 192, DMIN: 193, DMUL: 194, DEQ: 195, DGE: 196, DLT: 197, DNE: 198, DMOV: 199, DMOVC: 200,
    DTOF: 201, FTOD: 202, DDIV: 210, DFMA: 211, DRCP: 212, DTOI: 214, DTOU: 215, ITOD: 216, UTOD: 217,
    HS_DECLS: 113, HS_CONTROL_POINT_PHASE: 114, HS_FORK_PHASE: 115, DCL_INPUT_CONTROL_POINT_COUNT: 147,
    DCL_OUTPUT_CONTROL_POINT_COUNT: 148, DCL_TESS_DOMAIN: 149, DCL_TESS_PARTITIONING: 150, DCL_TESS_OUTPUT_PRIMITIVE: 151,
    DCL_HS_MAX_TESSFACTOR: 152,
};
/** TGSI atomics: VGPU10's returning their old value */
const ATOMICS = { ATOMUADD: OP.IMM_ATOMIC_IADD, ATOMAND: OP.IMM_ATOMIC_AND, ATOMOR: OP.IMM_ATOMIC_OR,
    ATOMXOR: OP.IMM_ATOMIC_XOR, ATOMXCHG: OP.IMM_ATOMIC_EXCH, ATOMCAS: OP.IMM_ATOMIC_CMP_EXCH,
    ATOMIMAX: OP.IMM_ATOMIC_IMAX, ATOMIMIN: OP.IMM_ATOMIC_IMIN, ATOMUMAX: OP.IMM_ATOMIC_UMAX, ATOMUMIN: OP.IMM_ATOMIC_UMIN };
/** Where GL's shader storage buffers and images are among the UAVs: buffer n is u n, image n u (IMAGE_UAV + n) */
export const IMAGE_UAV = 8;
/** The constant buffer of a compute shader's grid size (gl_NumWorkGroups), the device's */
export const GRID_CONSTANT_BUFFER = 15;
const VMWARE_IDIV = 0;

// operand types (VGPU10_OPERAND_TYPE)
const T = {
    TEMP: 0, INPUT: 1, OUTPUT: 2, INDEXABLE_TEMP: 3, IMMEDIATE32: 4, SAMPLER: 6, RESOURCE: 7, CONSTANT_BUFFER: 8,
    IMMEDIATE_CONSTANT_BUFFER: 9, INPUT_PRIMITIVEID: 11, OUTPUT_DEPTH: 12, NULL: 13, OUTPUT_COVERAGE_MASK: 15,
    UAV: 30, THREAD_GROUP_SHARED_MEMORY: 31, INPUT_THREAD_ID: 32, INPUT_THREAD_GROUP_ID: 33, INPUT_THREAD_ID_IN_GROUP: 34,
    INPUT_COVERAGE_MASK: 35, OUTPUT_CONTROL_POINT_ID: 22, INPUT_CONTROL_POINT: 25, INPUT_PATCH_CONSTANT: 27, INPUT_DOMAIN_POINT: 28,
};
// the tess factors (VGPU10_NAME_FINAL_*_TESSFACTOR) by domain: GL's outer levels, then inner
const TESS_FACTORS = {
    quad: { outer: [11, 12, 13, 14], inner: [15, 16] },
    tri: { outer: [17, 18, 19], inner: [20] },
    // (GL: outer[0] the number of lines, outer[1] their segments)
    isoline: { outer: [22, 21], inner: [] },
};
/** Where patch constants are (vpc): the tess factors, then GL's patch varyings */
const PATCH_VARYINGS = 6;
/** TES_PRIM_MODE (PIPE_PRIM_*) -> the domain (VGPU10_TESSELLATOR_DOMAIN) */
const TESS_DOMAIN = { 1: [1, "isoline"], 4: [2, "tri"], 7: [3, "quad"] };
// system value names (VGPU10_SYSTEM_NAME)
const NAME = { POSITION: 1, CLIP_DISTANCE: 2, RENDER_TARGET_ARRAY_INDEX: 4, VIEWPORT_ARRAY_INDEX: 5, VERTEX_ID: 6,
    PRIMITIVE_ID: 7, INSTANCE_ID: 8, IS_FRONT_FACE: 9, SAMPLE_INDEX: 10 };
// interpolation modes (VGPU10_INTERPOLATION_MODE)
const INTERP = { CONSTANT: 1, LINEAR: 2, LINEAR_CENTROID: 3, LINEAR_NOPERSPECTIVE: 4, LINEAR_NOPERSPECTIVE_CENTROID: 5,
    LINEAR_SAMPLE: 6, LINEAR_NOPERSPECTIVE_SAMPLE: 7 };
// resource dimensions (VGPU10_RESOURCE_DIMENSION)
const DIM = { BUFFER: 1, TEXTURE1D: 2, TEXTURE2D: 3, TEXTURE2DMS: 4, TEXTURE3D: 5, TEXTURECUBE: 6, TEXTURE1DARRAY: 7,
    TEXTURE2DARRAY: 8, TEXTURE2DMSARRAY: 9, TEXTURECUBEARRAY: 10 };
// resource return types (VGPU10_RESOURCE_RETURN_TYPE)
const RETURN = { UNORM: 1, SNORM: 2, SINT: 3, UINT: 4, FLOAT: 5 };
// VGPU10_PRIMITIVE and VGPU10_PRIMITIVE_TOPOLOGY
const GS_INPUT = { POINTS: 1, LINES: 2, TRIANGLES: 3, LINES_ADJACENCY: 6, TRIANGLES_ADJACENCY: 7 };
const GS_INPUT_VERTICES = { POINTS: 1, LINES: 2, TRIANGLES: 3, LINES_ADJACENCY: 4, TRIANGLES_ADJACENCY: 6 };
const GS_OUTPUT = { POINTS: 1, LINE_STRIP: 3, TRIANGLE_STRIP: 5 };

/** The program types of VGPU10 (VGPU10_PROGRAM_TYPE), by TGSI processor */
const PROGRAM = [1, 0, 2, 3, 4, 5];
/** ... and SVGA3D shader types (SVGA3D_SHADERTYPE_*), as GX's SET_SHADER takes them */
export const SVGA_SHADER_TYPE = [1, 2, 3, 4, 5, 6];

const PIPE_SWIZZLE_0 = 4, PIPE_SWIZZLE_1 = 5;

/** The resource dimension of a TGSI texture target, and how many coordinates it reads */
const TARGETS = {
    BUFFER: [DIM.BUFFER, 1], "1D": [DIM.TEXTURE1D, 1], "2D": [DIM.TEXTURE2D, 2], "3D": [DIM.TEXTURE3D, 3],
    CUBE: [DIM.TEXTURECUBE, 3], RECT: [DIM.TEXTURE2D, 2], SHADOW1D: [DIM.TEXTURE1D, 1], SHADOW2D: [DIM.TEXTURE2D, 2],
    SHADOWRECT: [DIM.TEXTURE2D, 2], "1D_ARRAY": [DIM.TEXTURE1DARRAY, 2], "2D_ARRAY": [DIM.TEXTURE2DARRAY, 3],
    SHADOW1D_ARRAY: [DIM.TEXTURE1DARRAY, 2], SHADOW2D_ARRAY: [DIM.TEXTURE2DARRAY, 3], SHADOWCUBE: [DIM.TEXTURECUBE, 3],
    "2D_MSAA": [DIM.TEXTURE2DMS, 2], "2D_ARRAY_MSAA": [DIM.TEXTURE2DMSARRAY, 3], CUBE_ARRAY: [DIM.TEXTURECUBEARRAY, 4],
    SHADOWCUBE_ARRAY: [DIM.TEXTURECUBEARRAY, 4],
};
/** Where a shadow target's reference value is in the coordinates (-1: the second source's x) */
const SHADOW_REF = { SHADOW1D: 2, SHADOW2D: 2, SHADOWRECT: 2, SHADOW1D_ARRAY: 2, SHADOW2D_ARRAY: 3, SHADOWCUBE: 3,
    SHADOWCUBE_ARRAY: -1 };

export class TGSITranslateError extends Error {}

const f32_bits = (() => {
    const f = new Float32Array(1), u = new Uint32Array(f.buffer);
    return x => { f[0] = x; return u[0]; };
})();
const ONE_F = 0x3F800000;

// ---------------------------------------------------------------------------
// Operands: { type, idx: [{imm, rel}], ncomp: 0 | 1 | 4, mode: "mask" |
// "swizzle" | "select", mask, swz, mod (1 neg, 2 abs, 3 both), imm }

/**
 * @param {number} type
 * @param {!Array} indices numbers, or {imm, rel}
 * @param {number=} ncomp 0, 1 or 4 (the default)
 * @return {!Object}
 */
function operand(type, indices, ncomp)
{
    return { type, idx: indices.map(i => typeof i === "number" ? { imm: i, rel: null } : i), ncomp: ncomp === undefined ? 4 : ncomp,
        mode: "swizzle", mask: 0xF, swz: [0, 1, 2, 3], mod: 0, imm: null };
}

/**
 * A 4-component immediate
 * @return {!Object}
 */
function imm4(a, b, c, d)
{
    const o = operand(T.IMMEDIATE32, [], 4);
    o.imm = [a >>> 0, b >>> 0, c >>> 0, d >>> 0];
    return o;
}
/** @param {number} a @param {number=} b @param {number=} c @param {number=} d */
const immf = (a, b, c, d) => imm4(f32_bits(a), f32_bits(b === undefined ? a : b), f32_bits(c === undefined ? a : c), f32_bits(d === undefined ? a : d));
/** @param {number} a @param {number=} b @param {number=} c @param {number=} d */
const immu = (a, b, c, d) => imm4(a, b === undefined ? a : b, c === undefined ? a : c, d === undefined ? a : d);

/**
 * A copy as a destination with a write mask
 * @param {!Object} o
 * @param {number=} mask
 * @return {!Object}
 */
function as_dst(o, mask)
{
    return Object.assign({}, o, { mode: "mask", mask: mask === undefined ? 0xF : mask, mod: 0 });
}

/**
 * A copy as a source with a swizzle
 * @param {!Object} o
 * @param {Array<number>=} swz
 * @param {number=} mod
 * @return {!Object}
 */
function as_src(o, swz, mod)
{
    if(o.type === T.IMMEDIATE32)
    {
        const s = swz || [0, 1, 2, 3];
        return Object.assign({}, o, { imm: s.map(c => o.imm[c]), mod: mod || 0 });
    }
    return Object.assign({}, o, { mode: "swizzle", swz: swz || [0, 1, 2, 3], mod: mod || 0 });
}

/** One component of a source (after its swizzle), replicated */
const scalar = (o, c) => o.type === T.IMMEDIATE32 ? as_src(o, [c, c, c, c], o.mod) :
    as_src(o, [o.swz[c], o.swz[c], o.swz[c], o.swz[c]], o.mod);

/** A swizzle composed after another: s2 picks from what s1 gave */
const compose = (s1, s2) => s2.map(c => s1[c]);

function encode_operand(o, out)
{
    if(o.type === T.IMMEDIATE32)
    {
        const one = o.ncomp === 1;
        let token = (one ? 1 : 2) | T.IMMEDIATE32 << 12;
        const words = one ? [o.imm[0]] : o.imm;
        if(o.mod)
        {
            out.push((token | 1 << 31) >>> 0, 1 | o.mod << 6);
        }
        else out.push(token >>> 0);
        for(const w of words) out.push(w >>> 0);
        return;
    }
    let token = o.ncomp === 0 ? 0 : o.ncomp === 1 ? 1 : 2;
    if(o.ncomp === 4)
    {
        if(o.mode === "mask") token |= 0 << 2 | (o.mask & 0xF) << 4;
        else if(o.mode === "select") token |= 2 << 2 | (o.swz[0] & 3) << 4;
        else token |= 1 << 2 | o.swz[0] << 4 | o.swz[1] << 6 | o.swz[2] << 8 | o.swz[3] << 10;
    }
    token |= o.type << 12 | o.idx.length << 20;
    o.idx.forEach((index, d) => {
        const representation = index.rel ? (index.imm ? 3 : 2) : 0;
        token |= representation << (22 + 3 * d);
    });
    if(o.mod) token |= 1 << 31;
    out.push(token >>> 0);
    if(o.mod) out.push(1 | o.mod << 6);
    for(const index of o.idx)
    {
        if(!index.rel || index.imm) out.push(index.imm >>> 0);
        if(index.rel) encode_operand(index.rel, out);
    }
}

// ---------------------------------------------------------------------------

/**
 * @constructor
 * @param {!Object} program from parse_tgsi
 * @param {!Object} key the variant
 */
function Translator(program, key)
{
    this.p = program;
    this.key = key;
    this.processor = program.processor;
    this.vs = program.processor === 0;
    this.fs = program.processor === 1;
    this.gs = program.processor === 2;
    this.cs = program.processor === 5;
    this.tcs = program.processor === 3;
    this.tes = program.processor === 4;
    /** a tessellation control shader's phase: "cp" (each output control point) or "fork" (the patch's constants) */
    this.phase = key.hs_phase || null;
    /** @type {!Array<number>} the instructions */
    this.code = [];
    /** @type {!Array<number>} the declarations */
    this.decls = [];
    /** @type {!Array<string>} what could not be translated */
    this.problems = [];
}

Translator.prototype.problem = function(text)
{
    if(!this.problems.includes(text)) this.problems.push(text);
};

/**
 * An instruction: opcode, operands, controls (saturate: 1 << 2, test nonzero: 1 << 7)
 * @param {number} op
 * @param {!Array<!Object>} operands
 * @param {number=} controls
 * @param {Array<number>=} extended
 */
Translator.prototype.emit = function(op, operands, controls, extended)
{
    const body = [];
    for(const o of operands) encode_operand(o, body);
    const ext = extended || [];
    const length = 1 + ext.length + body.length;
    this.code.push((op | (controls || 0) << 11 | length << 24 | (ext.length ? 1 << 31 : 0)) >>> 0, ...ext, ...body);
};

/**
 * @param {number} op
 * @param {!Array<!Object>} operands
 * @param {number=} controls
 * @param {Array<number>=} words
 */
Translator.prototype.decl = function(op, operands, controls, words)
{
    const body = [];
    for(const o of operands) encode_operand(o, body);
    if(words) body.push(...words);
    this.decls.push((op | (controls || 0) << 11 | (1 + body.length) << 24) >>> 0, ...body);
};

/** A temp for this instruction */
Translator.prototype.scratch = function()
{
    const r = this.scratch_base + this.scratch_used++;
    this.temps = Math.max(this.temps, r + 1);
    return operand(T.TEMP, [r]);
};

/** A temp for the whole program */
Translator.prototype.reserve = function()
{
    const r = this.next_temp++;
    this.temps = Math.max(this.temps, r + 1);
    return operand(T.TEMP, [r]);
};

// ---------------------------------------------------------------------------
// Declarations

Translator.prototype.scan = function()
{
    const p = this.p;
    let temps = 0, addrs = 0;
    this.arrays = new Map();    // TGSI array id -> { first, last }
    this.inputs = [];           // IN declarations, by index
    this.outputs = [];
    this.svs = [];
    this.cbuffers = new Map();  // slot -> size (vec4s)
    this.sviews = new Map();    // slot -> { target, return_types }
    this.samplers = new Map();  // slot -> { shadow }
    this.indirect_imm = false;
    /** shader storage buffers, images, shared memory */
    this.buffers = new Set();
    this.images = new Map();
    this.shared = false;
    for(const d of p.decls)
    {
        switch(d.file)
        {
            case "TEMP":
                if(d.array) this.arrays.set(d.array, { first: d.first, last: d.last });
                else temps = Math.max(temps, d.last + 1);
                break;
            case "ADDR": addrs = Math.max(addrs, d.last + 1); break;
            case "IN": for(let i = d.first; i <= d.last; i++) this.inputs[i] = Object.assign({}, d, { semantic_index: d.semantic_index + i - d.first }); break;
            case "OUT": for(let i = d.first; i <= d.last; i++) this.outputs[i] = Object.assign({}, d, { semantic_index: d.semantic_index + i - d.first }); break;
            case "SV": for(let i = d.first; i <= d.last; i++) this.svs[i] = d; break;
            case "CONST": this.cbuffers.set(d.two_d ? d.dim : 0, Math.max(this.cbuffers.get(d.two_d ? d.dim : 0) || 0, d.last + 1)); break;
            case "SVIEW": for(let i = d.first; i <= d.last; i++) this.sviews.set(i, { target: d.target, return_types: d.return_types }); break;
            case "SAMP": for(let i = d.first; i <= d.last; i++) this.samplers.set(i, { shadow: false, used: false }); break;
            case "IMM": break;
            case "BUFFER": for(let i = d.first; i <= d.last; i++) this.buffers.add(i); break;
            case "IMAGE": for(let i = d.first; i <= d.last; i++) this.images.set(i, { target: d.target, format: d.format }); break;
            case "MEMORY":
                if(d.memory === "SHARED") this.shared = true;
                else this.problem("memory of type " + d.memory);
                break;
            default: this.problem("declarations of " + d.file);
        }
    }
    // what the code uses: the arrays' indirect accesses, immediates read
    // indirectly (an immediate constant buffer then), the sampler targets
    for(const ins of p.code)
    {
        for(const o of [...ins.src, ...ins.dst])
        {
            if(o.file === "IMM" && o.rel) this.indirect_imm = true;
            if(o.file === "CONST" && o.rel) this.cbuffers.set(o.has_dim ? o.dim : 0, Math.max(this.cbuffers.get(o.has_dim ? o.dim : 0) || 0, 4096));
            if(o.file === "TEMP" && !o.array) temps = Math.max(temps, o.index + 1);
        }
        if(ins.target)
        {
            const samp = ins.src.find(o => o.file === "SAMP");
            if(samp)
            {
                const s = this.samplers.get(samp.index) || { shadow: false };
                s.used = true;
                if(ins.target.startsWith("SHADOW") && ins.op !== "TXQ" && ins.op !== "TXF") s.shadow = true;
                this.samplers.set(samp.index, s);
                if(!this.sviews.has(samp.index)) this.sviews.set(samp.index, { target: ins.target, return_types: null });
                const view = this.sviews.get(samp.index);
                if(!view.target) view.target = ins.target;
                view.used_target = ins.target;
            }
        }
    }
    this.temp_count = temps;
    this.addr_base = temps;
    this.next_temp = temps + addrs;
    this.temps = this.next_temp;
};

/** The VGPU10 interpolation of a TGSI fragment input */
Translator.prototype.interpolation = function(d)
{
    let mode = d.interpolate || "PERSPECTIVE";
    if(mode === "COLOR") mode = this.key.flatshade ? "CONSTANT" : "PERSPECTIVE";
    if(mode === "CONSTANT") return INTERP.CONSTANT;
    const linear = mode === "LINEAR";
    if(d.location === "CENTROID") return linear ? INTERP.LINEAR_NOPERSPECTIVE_CENTROID : INTERP.LINEAR_CENTROID;
    if(d.location === "SAMPLE") return linear ? INTERP.LINEAR_NOPERSPECTIVE_SAMPLE : INTERP.LINEAR_SAMPLE;
    return linear ? INTERP.LINEAR_NOPERSPECTIVE : INTERP.LINEAR;
};

/** "GENERIC3": how stages name a varying to each other */
export function semantic_key(name, index)
{
    return name + index;
}

/**
 * Inputs, outputs, buffers, views, samplers; and what reading or writing
 * each TGSI register means (this.in_map, this.out_map, this.sv_map)
 */
Translator.prototype.declare = function()
{
    const key = this.key;
    const reg_in = i => operand(T.INPUT, [i]);
    /** the varyings a stage reads: semantic key -> register (where the previous stage writes them) */
    this.link_inputs = {};
    /** @type {!Object<number, number>} the vertex stages' TGSI outputs -> registers */
    this.output_regs = {};
    this.in_map = [];
    this.out_map = [];
    this.sv_map = [];
    /** what the epilogue copies: [temp, function(temp) emitting the copy] */
    this.epilogue = [];
    const input_count = this.inputs.length;

    // inputs
    if(this.vs)
    {
        this.inputs.forEach((d, i) => {
            if(!d) return;
            this.decl(OP.DCL_INPUT, [as_dst(reg_in(i))]);
            this.in_map[i] = reg_in(i);
        });
    }
    else if(this.fs)
    {
        this.inputs.forEach((d, i) => {
            if(!d) return;
            this.fs_input(d, i, i);
        });
    }
    else if(this.tcs || this.tes)
    {
        // control points (vicp, a domain shader's vcp) and a domain shader's
        // patch constants from the fixed layout (vpc)
        const cps = this.tcs ? key.in_cps || 1 : key.cps || 1;
        const domain = this.tes ? (TESS_DOMAIN[+(this.p.properties.TES_PRIM_MODE || [7])[0]] || TESS_DOMAIN[7]) : null;
        if(this.tes)
        {
            this.decl(OP.DCL_TESS_DOMAIN, [], domain[0]);
            this.decl(OP.DCL_INPUT_CONTROL_POINT_COUNT, [], cps);
        }
        this.inputs.forEach((d, i) => {
            if(!d) return;
            const name = d.semantic;
            if(this.tes && (name === "TESSOUTER" || name === "TESSINNER"))
            {
                // the levels from the factors' constants
                const regs = TESS_FACTORS[domain[1]][name === "TESSOUTER" ? "outer" : "inner"].map((_, k) =>
                    (name === "TESSOUTER" ? 0 : TESS_FACTORS[domain[1]].outer.length) + k);
                const temp = this.reserve();
                this.prologue_ops.push(() => {
                    this.emit(OP.MOV, [as_dst(temp), immf(0)]);
                    regs.forEach((reg, k) => {
                        const v = operand(T.INPUT_PATCH_CONSTANT, [reg]);
                        this.emit(OP.MOV, [as_dst(temp, 1 << k), scalar(v, 0)]);
                    });
                });
                regs.forEach(reg => this.decl(OP.DCL_INPUT, [as_dst(operand(T.INPUT_PATCH_CONSTANT, [reg]), 1)]));
                this.in_map[i] = temp;
                return;
            }
            if(this.tes && name === "PATCH")
            {
                const v = operand(T.INPUT_PATCH_CONSTANT, [PATCH_VARYINGS + d.semantic_index]);
                this.decl(OP.DCL_INPUT, [as_dst(v)]);
                this.in_map[i] = v;
                return;
            }
            if(name === "PRIMID") { this.in_map[i] = operand(T.INPUT_PRIMITIVEID, [], 1); return; }
            // (vicp in each phase, as D3D11 writes them)
            this.decl(OP.DCL_INPUT, [as_dst(operand(T.INPUT_CONTROL_POINT, [cps, i]))]);
            this.in_map[i] = "cp";
            this.link_inputs[semantic_key(name, d.semantic_index)] = i;
        });
    }
    else if(this.gs)
    {
        const prim = (this.p.properties.GS_INPUT_PRIMITIVE || ["TRIANGLES"])[0];
        this.gs_vertices = GS_INPUT_VERTICES[prim] || 3;
        this.decl(OP.DCL_GS_INPUT_PRIMITIVE, [], GS_INPUT[prim] || GS_INPUT.TRIANGLES);
        const topology = (this.p.properties.GS_OUTPUT_PRIMITIVE || ["TRIANGLE_STRIP"])[0];
        this.decl(OP.DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, [], GS_OUTPUT[topology] || GS_OUTPUT.TRIANGLE_STRIP);
        this.decl(OP.DCL_MAX_OUTPUT_VERTEX_COUNT, [], 0, [+(this.p.properties.GS_MAX_OUTPUT_VERTICES || [1])[0]]);
        this.inputs.forEach((d, i) => {
            if(!d) return;
            const o = operand(T.INPUT, [this.gs_vertices, i]);
            if(d.semantic === "POSITION") this.decl(OP.DCL_INPUT_SIV, [as_dst(o)], 0, [NAME.POSITION]);
            else if(d.semantic === "PRIMID") { this.in_map[i] = operand(T.INPUT_PRIMITIVEID, [], 1); return; }
            else this.decl(OP.DCL_INPUT, [as_dst(o)]);
            this.in_map[i] = "gs";
            this.link_inputs[semantic_key(d.semantic, d.semantic_index)] = i;
        });
    }
    if(this.cs)
    {
        const size = n => +((this.p.properties["CS_FIXED_BLOCK_" + n] || [1])[0]) || 1;
        this.block = [size("WIDTH"), size("HEIGHT"), size("DEPTH")];
        this.decl(OP.DCL_THREAD_GROUP, [], 0, this.block);
    }
    // system values: after the inputs
    this.svs.forEach((d, i) => {
        if(!d) return;
        const reg = input_count + i;
        const name = d.semantic;
        if(this.tcs || this.tes)
        {
            if(name === "INVOCATIONID" && this.phase === "cp")
            {
                this.decl(OP.DCL_INPUT, [operand(T.OUTPUT_CONTROL_POINT_ID, [], 0)]);
                this.sv_map[i] = operand(T.OUTPUT_CONTROL_POINT_ID, [], 1);
            }
            // (the patch's constants: computed once, as by invocation 0)
            else if(name === "INVOCATIONID") this.sv_map[i] = immu(0);
            else if(name === "VERTICESIN") this.sv_map[i] = immu(this.tcs ? key.in_cps || 1 : key.cps || 1);
            else if(name === "TESSCOORD")
            {
                this.decl(OP.DCL_INPUT, [as_dst(operand(T.INPUT_DOMAIN_POINT, [], 4), 0b0111)]);
                this.sv_map[i] = operand(T.INPUT_DOMAIN_POINT, [], 4);
            }
            else if(name === "PRIMID")
            {
                this.decl(OP.DCL_INPUT, [operand(T.INPUT_PRIMITIVEID, [], 0)]);
                this.sv_map[i] = operand(T.INPUT_PRIMITIVEID, [], 1);
            }
            else
            {
                this.problem("system value " + name);
                this.sv_map[i] = immu(0);
            }
            return;
        }
        if(this.cs)
        {
            const kinds = { BLOCK_ID: T.INPUT_THREAD_GROUP_ID, THREAD_ID: T.INPUT_THREAD_ID_IN_GROUP };
            if(name in kinds)
            {
                this.decl(OP.DCL_INPUT, [as_dst(operand(kinds[name], [], 4), 0b0111)]);
                this.sv_map[i] = operand(kinds[name], [], 4);
            }
            else if(name === "BLOCK_SIZE") this.sv_map[i] = immu(this.block[0], this.block[1], this.block[2], 0);
            else if(name === "GRID_SIZE")
            {
                this.cbuffers.set(GRID_CONSTANT_BUFFER, 1);
                this.sv_map[i] = operand(T.CONSTANT_BUFFER, [GRID_CONSTANT_BUFFER, 0]);
            }
            else
            {
                this.problem("system value " + name);
                this.sv_map[i] = immu(0);
            }
            return;
        }
        if(this.vs && (name === "VERTEXID" || name === "INSTANCEID"))
        {
            this.decl(OP.DCL_INPUT_SGV, [as_dst(reg_in(reg), 1)], 0, [name === "VERTEXID" ? NAME.VERTEX_ID : NAME.INSTANCE_ID]);
            this.sv_map[i] = scalar(reg_in(reg), 0);
        }
        else if(this.fs && (name === "FACE" || name === "POSITION" || name === "SAMPLEID"))
        {
            this.fs_input(d, reg, -1);
            this.sv_map[i] = this.in_map[reg];
        }
        else if(this.fs && name === "SAMPLEMASK")
        {
            this.sv_map[i] = operand(T.INPUT_COVERAGE_MASK, [], 1);
            this.decl(OP.DCL_INPUT, [as_dst(operand(T.INPUT_COVERAGE_MASK, [], 1), 1)]);
        }
        else if(name === "PRIMID")
        {
            this.sv_map[i] = operand(T.INPUT_PRIMITIVEID, [], 1);
            this.decl(OP.DCL_INPUT, [operand(T.INPUT_PRIMITIVEID, [], 0)]);
        }
        else if(name === "HELPER_INVOCATION")
        {
            this.sv_map[i] = immu(0);
        }
        else
        {
            this.problem("system value " + name);
            this.sv_map[i] = immu(0);
        }
    });

    // GL's clip distances (key.clip_enable, a bit each): varyings from the
    // last vertex stage, and fragments where one is below zero discarded
    if(this.fs && key.clip_enable)
    {
        const base = input_count + this.svs.length;
        for(let k = 0; k < 2; k++)
        {
            const mask = key.clip_enable >> 4 * k & 0xF;
            if(!mask) continue;
            const v = operand(T.INPUT, [base + k]);
            this.decl(OP.DCL_INPUT_PS, [as_dst(v)], INTERP.LINEAR);
            this.link_inputs[semantic_key("CLIPDIST", k)] = base + k;
            this.prologue_ops.push(() => {
                const t = this.reserve();
                this.emit(OP.LT, [as_dst(t, mask), as_src(v), immf(0)]);
                this.emit(OP.OR, [as_dst(t, 0b0011), as_src(t, [0, 1, 0, 0]), as_src(t, [2, 3, 0, 0])]);
                this.emit(OP.OR, [as_dst(t, 1), scalar(t, 0), scalar(t, 1)]);
                this.emit(OP.DISCARD, [scalar(t, 0)], 1 << 7);
            });
        }
    }

    // outputs
    if(this.fs)
    {
        const broadcast = (this.p.properties.FS_COLOR0_WRITES_ALL_CBUFS || [])[0] === "1";
        const buffers = broadcast ? Math.max(1, key.color_buffers || 1) : 1;
        // GL's alpha test (compatibility profiles) reads color 0 at the end
        const alpha_test = key.alpha_func !== undefined && key.alpha_func !== 7;
        this.outputs.forEach((d, i) => {
            if(!d) return;
            if(d.semantic === "COLOR")
            {
                const o = operand(T.OUTPUT, [d.semantic_index]);
                if((broadcast || alpha_test) && d.semantic_index === 0)
                {
                    const temp = this.reserve();
                    this.out_map[i] = temp;
                    for(let b = 0; b < buffers; b++)
                    {
                        this.decl(OP.DCL_OUTPUT, [as_dst(operand(T.OUTPUT, [b]))]);
                        this.epilogue.push(() => this.emit(OP.MOV, [as_dst(operand(T.OUTPUT, [b])), as_src(temp)]));
                    }
                    this.color0 = temp;
                    return;
                }
                this.decl(OP.DCL_OUTPUT, [as_dst(o)]);
                this.out_map[i] = o;
                if(d.semantic_index === 0) this.color0 = o;
            }
            else if(d.semantic === "POSITION")
            {
                // depth: what TGSI writes into z
                const temp = this.reserve();
                this.out_map[i] = temp;
                this.decl(OP.DCL_OUTPUT, [operand(T.OUTPUT_DEPTH, [], 1)]);
                this.epilogue.push(() => this.emit(OP.MOV, [operand(T.OUTPUT_DEPTH, [], 1), scalar(temp, 2)]));
            }
            else if(d.semantic === "SAMPLEMASK")
            {
                const temp = this.reserve();
                this.out_map[i] = temp;
                this.decl(OP.DCL_OUTPUT, [operand(T.OUTPUT_COVERAGE_MASK, [], 1)]);
                this.epilogue.push(() => this.emit(OP.MOV, [operand(T.OUTPUT_COVERAGE_MASK, [], 1), scalar(temp, 0)]));
            }
            else
            {
                this.problem("fragment output " + d.semantic);
                this.out_map[i] = this.junk();
            }
        });
        // GL's alpha test (compatibility profiles), after the color is known
        if(alpha_test && this.color0)
        {
            const color0 = this.color0;
            this.epilogue.unshift(() => this.alpha_test(color0));
        }
    }
    else if(this.tcs)
    {
        const outputs = key.outputs || {};
        const used = new Set(Object.values(outputs));
        let next = 0;
        const free = () => { while(used.has(next)) next++; used.add(next); return next; };
        const factors = TESS_FACTORS[key.domain || "quad"];
        this.outputs.forEach((d, i) => {
            if(!d) return;
            const name = d.semantic;
            if(name === "TESSOUTER" || name === "TESSINNER" || name === "PATCH")
            {
                // the patch's constants: in temps, into their registers at the end of the fork phase
                if(this.phase !== "fork") { this.out_map[i] = this.junk(); return; }
                const temp = this.reserve();
                this.out_map[i] = temp;
                if(name === "PATCH")
                {
                    const o = operand(T.OUTPUT, [PATCH_VARYINGS + d.semantic_index]);
                    this.decl(OP.DCL_OUTPUT, [as_dst(o)]);
                    this.epilogue.push(() => this.emit(OP.MOV, [as_dst(o), as_src(temp)]));
                    return;
                }
                const names = factors[name === "TESSOUTER" ? "outer" : "inner"];
                const base = name === "TESSOUTER" ? 0 : factors.outer.length;
                names.forEach((siv, k) => {
                    const o = operand(T.OUTPUT, [base + k]);
                    this.decl(OP.DCL_OUTPUT_SIV, [as_dst(o, 1)], 0, [siv]);
                    this.epilogue.push(() => this.emit(OP.MOV, [as_dst(o, 1), scalar(temp, k)]));
                });
                return;
            }
            // a control point's outputs: the control point phase's
            if(this.phase !== "cp") { this.out_map[i] = this.junk(); return; }
            const k = semantic_key(name, d.semantic_index);
            const reg = k in outputs ? outputs[k] : free();
            const o = operand(T.OUTPUT, [reg]);
            this.decl(OP.DCL_OUTPUT, [as_dst(o)]);
            this.out_map[i] = o;
        });
    }
    else if(this.vs || this.gs || this.tes)
    {
        const outputs = key.outputs || {};
        const used = new Set(Object.values(outputs));
        let next = 0;
        const free = () => { while(used.has(next)) next++; used.add(next); return next; };
        this.outputs.forEach((d, i) => {
            if(!d) return;
            const name = d.semantic;
            if(name === "POSITION")
            {
                // (where a geometry shader reads it, else anywhere: the rasterizer takes it)
                const k = semantic_key(name, d.semantic_index);
                const reg = k in outputs ? outputs[k] : free();
                this.output_regs[i] = reg;
                const o = operand(T.OUTPUT, [reg]);
                this.decl(OP.DCL_OUTPUT_SIV, [as_dst(o)], 0, [NAME.POSITION]);
                // into a temp: the viewport's fixes are made at the end (at each vertex of a GS)
                const temp = this.reserve();
                this.out_map[i] = temp;
                this.epilogue.push(() => this.position_out(o, temp));
                return;
            }
            const k = semantic_key(name, d.semantic_index);
            // (stream output wants every output, read by the next stage or not)
            if(k in outputs || key.all_outputs)
            {
                const reg = k in outputs ? outputs[k] : free();
                this.output_regs[i] = reg;
                const o = operand(T.OUTPUT, [reg]);
                if(name === "LAYER") this.decl(OP.DCL_OUTPUT_SIV, [as_dst(o, 1)], 0, [NAME.RENDER_TARGET_ARRAY_INDEX]);
                else if(name === "VIEWPORT_INDEX") this.decl(OP.DCL_OUTPUT_SIV, [as_dst(o, 1)], 0, [NAME.VIEWPORT_ARRAY_INDEX]);
                else if(name === "PRIMID" && this.gs) this.decl(OP.DCL_OUTPUT_SGV, [as_dst(o, 1)], 0, [NAME.PRIMITIVE_ID]);
                else this.decl(OP.DCL_OUTPUT, [as_dst(o)]);
                this.out_map[i] = o;
                return;
            }
            // what nothing after reads (or D3D has no place for: point
            // sizes, clip vertices, edge flags) goes nowhere
            this.out_map[i] = this.junk();
        });
    }

    // constant buffers, samplers, views
    for(const [slot, size] of [...this.cbuffers.entries()].sort((a, b) => a[0] - b[0]))
    {
        const dynamic = size >= 4096 ? 1 : 0;
        this.decl(OP.DCL_CONSTANT_BUFFER, [operand(T.CONSTANT_BUFFER, [slot, Math.min(size, 4096)])], dynamic);
    }
    for(const [slot, s] of this.samplers)
    {
        if(!s.used) continue;
        this.decl(OP.DCL_SAMPLER, [operand(T.SAMPLER, [slot], 0)], s.shadow ? 1 : 0);
    }
    for(const [slot, v] of this.sviews)
    {
        const target = v.target || v.used_target || "2D";
        const dimension = (TARGETS[target] || TARGETS["2D"])[0];
        const types = (v.return_types || ["FLOAT", "FLOAT", "FLOAT", "FLOAT"]).map(t => RETURN[t] || RETURN.FLOAT);
        this.decl(OP.DCL_RESOURCE, [operand(T.RESOURCE, [slot], 0)], dimension, [types[0] | types[1] << 4 | types[2] << 8 | types[3] << 12]);
        v.integer = types[0] === RETURN.SINT || types[0] === RETURN.UINT;
    }
    // GL's shader storage buffers (raw UAVs), images (typed UAVs), shared memory
    for(const n of this.buffers) this.decl(OP.DCL_UAV_RAW, [operand(T.UAV, [n], 0)]);
    for(const [n, image] of this.images)
    {
        const dimension = (TARGETS[image.target] || TARGETS["2D"])[0];
        const type = image_return_type(image.format);
        this.decl(OP.DCL_UAV_TYPED, [operand(T.UAV, [IMAGE_UAV + n], 0)], dimension, [type | type << 4 | type << 8 | type << 12]);
    }
    if(this.shared)
    {
        this.decl(OP.DCL_TGSM_RAW, [operand(T.THREAD_GROUP_SHARED_MEMORY, [0], 0)], 0, [Math.max(4, (this.p.shared || 4) + 3 & ~3)]);
    }
    // indexable temps
    for(const [id, a] of this.arrays)
    {
        this.decls.push((OP.DCL_INDEXABLE_TEMP | 4 << 24) >>> 0, id, a.last - a.first + 1, 4);
    }
};

/** A temp nothing reads: the place of outputs that go nowhere */
Translator.prototype.junk = function()
{
    if(!this.junk_temp) this.junk_temp = this.reserve();
    return this.junk_temp;
};

/**
 * A fragment input at register `reg`, TGSI's IN `index` (-1: a system value)
 */
Translator.prototype.fs_input = function(d, reg, index)
{
    const v = operand(T.INPUT, [reg]);
    switch(d.semantic)
    {
        case "POSITION":
        {
            // GL's fragment position: 1/w, maybe integer pixel centers
            this.decl(OP.DCL_INPUT_PS_SIV, [as_dst(v)], INTERP.LINEAR_NOPERSPECTIVE, [NAME.POSITION]);
            const temp = this.reserve();
            this.prologue_ops.push(() => {
                this.emit(OP.MOV, [as_dst(temp, 0b0111), as_src(v)]);
                this.emit(OP.RCP, [as_dst(temp, 0b1000), scalar(v, 3)]);
                if((this.p.properties.FS_COORD_PIXEL_CENTER || [])[0] === "INTEGER")
                {
                    this.emit(OP.ADD, [as_dst(temp, 0b0011), as_src(temp), immf(-0.5)]);
                }
            });
            this.in_map[reg] = temp;
            return;
        }
        case "FACE":
        {
            this.decl(OP.DCL_INPUT_PS_SGV, [as_dst(v, 1)], INTERP.CONSTANT, [NAME.IS_FRONT_FACE]);
            const temp = this.reserve();
            this.prologue_ops.push(() => this.emit(OP.MOVC, [as_dst(temp), scalar(v, 0), immf(1), immf(-1)]));
            this.in_map[reg] = temp;
            return;
        }
        case "SAMPLEID":
            this.decl(OP.DCL_INPUT_PS_SGV, [as_dst(v, 1)], INTERP.CONSTANT, [NAME.SAMPLE_INDEX]);
            this.in_map[reg] = scalar(v, 0);
            return;
        case "PRIMID":
            this.decl(OP.DCL_INPUT_PS_SGV, [as_dst(v, 1)], INTERP.CONSTANT, [NAME.PRIMITIVE_ID]);
            this.in_map[reg] = scalar(v, 0);
            return;
    }
    this.decl(OP.DCL_INPUT_PS, [as_dst(v)], this.interpolation(d));
    this.in_map[reg] = v;
    if(index >= 0) this.link_inputs[semantic_key(d.semantic, d.semantic_index)] = reg;
};

/** The position as D3D wants it: Y flipped, Z from [-w, w] into [0, w] */
Translator.prototype.position_out = function(o, temp)
{
    const key = this.key;
    this.emit(OP.MOV, [as_dst(o, key.flip_y ? 0b1101 : 0b1111), as_src(temp)]);
    if(key.flip_y) this.emit(OP.MOV, [as_dst(o, 0b0010), as_src(temp, [1, 1, 1, 1], 1)]);
    if(!key.halfz)
    {
        const t = this.scratch();
        this.emit(OP.ADD, [as_dst(t, 0b0100), as_src(temp, [2, 2, 2, 2]), as_src(temp, [3, 3, 3, 3])]);
        this.emit(OP.MUL, [as_dst(o, 0b0100), as_src(t, [2, 2, 2, 2]), immf(0.5)]);
    }
};

/** GL's alpha test: discard what fails (key.alpha_func: PIPE_FUNC_*, key.alpha_ref) */
Translator.prototype.alpha_test = function(color)
{
    const f = this.key.alpha_func;
    const t = this.scratch();
    const a = as_src(color, [3, 3, 3, 3]), ref = immf(this.key.alpha_ref || 0);
    if(f === 0)
    {
        this.emit(OP.DISCARD, [immu(0xFFFFFFFF)], 1 << 7);
        return;
    }
    // the passing condition, then discard where it is zero
    const tests = { 1: [OP.LT, a, ref], 2: [OP.EQ, a, ref], 3: [OP.GE, ref, a], 4: [OP.LT, ref, a], 5: [OP.NE, a, ref], 6: [OP.GE, a, ref] };
    const [op, x, y] = tests[f];
    this.emit(op, [as_dst(t, 1), x, y]);
    this.emit(OP.DISCARD, [scalar(t, 0)], 0);
};

// ---------------------------------------------------------------------------
// Registers of instructions

/** A TGSI register's VGPU10 operand (its indices), before the swizzle or mask */
Translator.prototype.register = function(r, write)
{
    const rel = r.rel ? this.addr(r.rel) : null;
    switch(r.file)
    {
        case "TEMP":
        {
            if(r.array && this.arrays.has(r.array))
            {
                const a = this.arrays.get(r.array);
                return operand(T.INDEXABLE_TEMP, [r.array, { imm: r.index - (rel ? 0 : a.first), rel }]);
            }
            if(rel)
            {
                this.problem("indirect temps outside of arrays");
                return operand(T.TEMP, [r.index]);
            }
            return operand(T.TEMP, [r.index]);
        }
        case "ADDR":
            return operand(T.TEMP, [this.addr_base + r.index]);
        case "IN":
        {
            if((this.tcs || this.tes) && r.has_dim)
            {
                const m = this.in_map[r.index];
                if(m && m !== "cp") return m;
                const vertex = r.dim_rel ? { imm: r.dim, rel: this.addr(r.dim_rel) } : r.dim;
                return operand(T.INPUT_CONTROL_POINT, [vertex, rel ? { imm: r.index, rel } : r.index]);
            }
            if(this.gs)
            {
                const vertex = r.dim_rel ? { imm: r.dim, rel: this.addr(r.dim_rel) } : r.dim;
                const m = this.in_map[r.index];
                if(m && m !== "gs") return m;
                return operand(T.INPUT, [vertex, rel ? { imm: r.index, rel } : r.index]);
            }
            if(rel) return operand(T.INPUT, [{ imm: r.index, rel }]);
            const m = this.in_map[r.index];
            if(!m)
            {
                this.problem("an undeclared input");
                return immu(0);
            }
            return m;
        }
        case "OUT":
        {
            const m = this.out_map[r.index];
            // a control point's own outputs (GLSL writes only gl_InvocationID's)
            if(this.tcs && r.has_dim)
            {
                if(!write && m && m.type === T.OUTPUT) this.problem("reading a control point's outputs");
                return m || this.junk();
            }
            if(rel)
            {
                // an output array: the registers after the first's
                if(m && m.type === T.OUTPUT) return operand(T.OUTPUT, [{ imm: m.idx[0].imm, rel }]);
                this.problem("indirect outputs");
            }
            if(!m)
            {
                this.problem("an undeclared output");
                return this.junk();
            }
            if(!write && m.type === T.OUTPUT) this.problem("reading an output");
            return m;
        }
        case "CONST":
        {
            const slot = r.has_dim ? r.dim : 0;
            return operand(T.CONSTANT_BUFFER, [slot, rel ? { imm: r.index, rel } : r.index]);
        }
        case "IMM":
        {
            if(rel) return operand(T.IMMEDIATE_CONSTANT_BUFFER, [{ imm: r.index, rel }]);
            const imm = this.p.imms[r.index];
            if(!imm)
            {
                this.problem("an undeclared immediate");
                return immu(0);
            }
            return imm4(imm.values[0], imm.values[1], imm.values[2], imm.values[3]);
        }
        case "SV":
        {
            const m = this.sv_map[r.index];
            return m || immu(0);
        }
    }
    this.problem("registers of " + r.file);
    return immu(0);
};

/** An address register's component, as a relative index */
Translator.prototype.addr = function(rel)
{
    if(rel.file === "ADDR") return Object.assign(operand(T.TEMP, [this.addr_base + rel.index]), { mode: "select", swz: [rel.comp, rel.comp, rel.comp, rel.comp] });
    if(rel.file === "TEMP") return Object.assign(operand(T.TEMP, [rel.index]), { mode: "select", swz: [rel.comp, rel.comp, rel.comp, rel.comp] });
    this.problem("relative addressing by " + rel.file);
    return Object.assign(operand(T.TEMP, [this.addr_base]), { mode: "select", swz: [0, 0, 0, 0] });
};

/** A TGSI source */
Translator.prototype.src = function(s)
{
    const o = this.register(s, false);
    const mod = (s.neg ? 1 : 0) | (s.abs ? 2 : 0);
    if(o.type === T.IMMEDIATE32) return as_src(o, s.swizzle, mod);
    // registers that are scalars already (1 component)
    if(o.ncomp === 1) return Object.assign({}, o, { mod: (o.mod || 0) | mod });
    return as_src(o, compose(o.swz || [0, 1, 2, 3], s.swizzle), mod);
};

/** A TGSI destination */
Translator.prototype.dst = function(d)
{
    const o = this.register(d, true);
    if(o.ncomp === 1) return Object.assign({}, o, { mod: 0 });
    return as_dst(o, d.mask);
};

// ---------------------------------------------------------------------------
// Instructions

/** The simple ones: TGSI opcode -> VGPU10 opcode, with the same operands */
const SIMPLE = {
    MOV: OP.MOV, ADD: OP.ADD, MUL: OP.MUL, MAD: OP.MAD, FMA: OP.MAD, DP2: OP.DP2, DP3: OP.DP3, DP4: OP.DP4,
    MIN: OP.MIN, MAX: OP.MAX, FRC: OP.FRC, FLR: OP.ROUND_NI, CEIL: OP.ROUND_PI, TRUNC: OP.ROUND_Z,
    ROUND: OP.ROUND_NE, DIV: OP.DIV, FSEQ: OP.EQ, FSNE: OP.NE, FSLT: OP.LT, FSGE: OP.GE,
    DDX: OP.DERIV_RTX, DDY: OP.DERIV_RTY, DDX_FINE: OP.DERIV_RTX_FINE, DDY_FINE: OP.DERIV_RTY_FINE,
    F2I: OP.FTOI, F2U: OP.FTOU, I2F: OP.ITOF, U2F: OP.UTOF, UADD: OP.IADD, UMAD: OP.UMAD,
    INEG: OP.INEG, AND: OP.AND, OR: OP.OR, XOR: OP.XOR, NOT: OP.NOT, SHL: OP.ISHL, ISHR: OP.ISHR,
    USHR: OP.USHR, IMAX: OP.IMAX, IMIN: OP.IMIN, UMAX: OP.UMAX, UMIN: OP.UMIN, USEQ: OP.IEQ, USNE: OP.INE,
    ISLT: OP.ILT, ISGE: OP.IGE, USLT: OP.ULT, USGE: OP.UGE, UCMP: OP.MOVC, BREV: OP.BFREV,
    POPC: OP.COUNTBITS, LSB: OP.FIRSTBIT_LO,
    // doubles (a register holds two, .xy and .zw: GX computes them as floats)
    DADD: OP.DADD, DMUL: OP.DMUL, DMAX: OP.DMAX, DMIN: OP.DMIN, DFMA: OP.DFMA, DMAD: OP.DFMA, DDIV: OP.DDIV,
    DRCP: OP.DRCP, DSLT: OP.DLT, DSGE: OP.DGE, DSEQ: OP.DEQ, DSNE: OP.DNE, F2D: OP.FTOD, D2F: OP.DTOF,
    D2I: OP.DTOI, D2U: OP.DTOU, I2D: OP.ITOD, U2D: OP.UTOD,
};
/** Those of one source whose result is that of the source's first component, replicated */
const SCALAR = { RCP: OP.RCP, RSQ: OP.RSQ, SQRT: OP.SQRT, EX2: OP.EXP, LG2: OP.LOG };

Translator.prototype.instruction = function(ins)
{
    this.scratch_used = 0;
    const sat = ins.saturate ? 1 << 2 : 0;
    const op = ins.op;
    if(op in SIMPLE)
    {
        this.emit(SIMPLE[op], [this.dst(ins.dst[0]), ...ins.src.map(s => this.src(s))], sat);
        return;
    }
    if(op in SCALAR)
    {
        const s = this.src(ins.src[0]);
        this.emit(SCALAR[op], [this.dst(ins.dst[0]), as_src(s, [s.swz[0], s.swz[0], s.swz[0], s.swz[0]], s.mod)], sat);
        return;
    }
    const d = () => this.dst(ins.dst[0]);
    const s = i => this.src(ins.src[i]);
    const first = o => as_src(o, [o.swz[0], o.swz[0], o.swz[0], o.swz[0]], o.mod);
    switch(op)
    {
        case "NOP":
            return;
        case "END":
        case "RET":
            this.finish();
            if(op === "END") this.ended = true;
            return;
        case "SIN":
        case "COS":
        {
            const null_dst = operand(T.NULL, [], 0);
            const out = d();
            this.emit(OP.SINCOS, op === "SIN" ? [out, null_dst, first(s(0))] : [null_dst, out, first(s(0))], sat);
            return;
        }
        case "POW":
        {
            const t = this.scratch();
            this.emit(OP.LOG, [as_dst(t, 1), first(s(0))]);
            this.emit(OP.MUL, [as_dst(t, 1), scalar(t, 0), first(s(1))]);
            this.emit(OP.EXP, [d(), scalar(t, 0)], sat);
            return;
        }
        case "LRP":
        {
            // src0 * src1 + (1 - src0) * src2 = src0 * (src1 - src2) + src2
            const t = this.scratch();
            const c = s(2);
            this.emit(OP.ADD, [as_dst(t), s(1), Object.assign({}, c, { mod: c.mod ^ 1 })]);
            this.emit(OP.MAD, [d(), s(0), as_src(t), c], sat);
            return;
        }
        case "SLT": case "SGE": case "SEQ": case "SNE": case "SGT": case "SLE":
        {
            const t = this.scratch();
            const [cmp, x, y] = { SLT: [OP.LT, 0, 1], SGE: [OP.GE, 0, 1], SEQ: [OP.EQ, 0, 1], SNE: [OP.NE, 0, 1],
                SGT: [OP.LT, 1, 0], SLE: [OP.GE, 1, 0] }[op];
            this.emit(cmp, [as_dst(t), s(x), s(y)]);
            this.emit(OP.AND, [d(), as_src(t), immu(ONE_F)], sat);
            return;
        }
        case "CMP":
        {
            // src0 < 0 ? src1 : src2
            const t = this.scratch();
            this.emit(OP.LT, [as_dst(t), s(0), immf(0)]);
            this.emit(OP.MOVC, [d(), as_src(t), s(1), s(2)], sat);
            return;
        }
        case "SSG":
        case "ISSG":
        {
            // (x > 0) - (x < 0)
            const a = this.scratch(), b = this.scratch();
            const lt = op === "SSG" ? OP.LT : OP.ILT, zero = op === "SSG" ? immf(0) : immu(0);
            this.emit(lt, [as_dst(a), zero, s(0)]);
            this.emit(lt, [as_dst(b), s(0), zero]);
            this.emit(OP.IADD, [as_dst(a), as_src(b), as_src(a, null, 1)]);
            if(op === "SSG") this.emit(OP.ITOF, [d(), as_src(a)], sat);
            else this.emit(OP.MOV, [d(), as_src(a)]);
            return;
        }
        case "IABS":
        {
            const x = s(0);
            this.emit(OP.IMAX, [d(), x, Object.assign({}, x, { mod: x.mod ^ 1 })]);
            return;
        }
        case "UMUL":
            this.emit(OP.UMUL, [operand(T.NULL, [], 0), d(), s(0), s(1)]);
            return;
        case "IMUL_HI":
            this.emit(OP.IMUL, [d(), operand(T.NULL, [], 0), s(0), s(1)]);
            return;
        case "UMUL_HI":
            this.emit(OP.UMUL, [d(), operand(T.NULL, [], 0), s(0), s(1)]);
            return;
        case "UDIV":
            this.emit(OP.UDIV, [d(), operand(T.NULL, [], 0), s(0), s(1)]);
            return;
        case "UMOD":
            this.emit(OP.UDIV, [operand(T.NULL, [], 0), d(), s(0), s(1)]);
            return;
        case "IDIV":
            this.emit(OP.VMWARE, [d(), operand(T.NULL, [], 0), s(0), s(1)], VMWARE_IDIV);
            return;
        case "MOD":
            this.emit(OP.VMWARE, [operand(T.NULL, [], 0), d(), s(0), s(1)], VMWARE_IDIV);
            return;
        case "IBFE":
        case "UBFE":
            // TGSI: value, offset, bits; VGPU10: bits, offset, value
            this.emit(op === "IBFE" ? OP.IBFE : OP.UBFE, [d(), s(2), s(1), s(0)]);
            return;
        case "BFI":
            // TGSI: base, insert, offset, bits; VGPU10: bits, offset, insert, base
            this.emit(OP.BFI, [d(), s(3), s(2), s(1), s(0)]);
            return;
        case "IMSB":
        case "UMSB":
        {
            // the bit's index from the bottom, -1 for none (D3D counts from the top)
            const t = this.scratch(), none = this.scratch();
            this.emit(op === "IMSB" ? OP.FIRSTBIT_SHI : OP.FIRSTBIT_HI, [as_dst(t), s(0)]);
            this.emit(OP.IEQ, [as_dst(none), as_src(t), immu(0xFFFFFFFF)]);
            this.emit(OP.IADD, [as_dst(t), immu(31), as_src(t, null, 1)]);
            this.emit(OP.MOVC, [d(), as_src(none), immu(0xFFFFFFFF), as_src(t)]);
            return;
        }
        case "ARL":
        {
            const t = this.scratch();
            this.emit(OP.ROUND_NI, [as_dst(t), s(0)]);
            this.emit(OP.FTOI, [d(), as_src(t)]);
            return;
        }
        case "UARL":
            this.emit(OP.MOV, [d(), s(0)]);
            return;
        case "KILL":
            this.emit(OP.DISCARD, [immu(0xFFFFFFFF)], 1 << 7);
            return;
        case "KILL_IF":
        {
            // discard if any component is below zero
            const x = s(0);
            const t = this.scratch();
            const same = x.type === T.IMMEDIATE32 ? false : x.swz.every(c => c === x.swz[0]);
            this.emit(OP.LT, [as_dst(t, same ? 1 : 0xF), x, immf(0)]);
            if(!same)
            {
                this.emit(OP.OR, [as_dst(t, 0b0011), as_src(t, [0, 1, 0, 0]), as_src(t, [2, 3, 0, 0])]);
                this.emit(OP.OR, [as_dst(t, 1), scalar(t, 0), scalar(t, 1)]);
            }
            this.emit(OP.DISCARD, [scalar(t, 0)], 1 << 7);
            return;
        }
        case "IF":
        {
            const t = this.scratch();
            this.emit(OP.NE, [as_dst(t, 1), first(s(0)), immf(0)]);
            this.emit(OP.IF, [scalar(t, 0)], 1 << 7);
            return;
        }
        case "UIF":
            this.emit(OP.IF, [first(s(0))], 1 << 7);
            return;
        case "ELSE": this.emit(OP.ELSE, []); return;
        case "ENDIF": this.emit(OP.ENDIF, []); return;
        case "BGNLOOP": this.emit(OP.LOOP, []); return;
        case "ENDLOOP": this.emit(OP.ENDLOOP, []); return;
        case "BRK": this.emit(OP.BREAK, []); return;
        case "CONT": this.emit(OP.CONTINUE, []); return;
        case "SWITCH": this.emit(OP.SWITCH, [first(s(0))]); return;
        case "CASE":
        {
            const x = s(0);
            this.emit(OP.CASE, [x.type === T.IMMEDIATE32 ? Object.assign({}, x, { ncomp: 1 }) : first(x)]);
            return;
        }
        case "DEFAULT": this.emit(OP.DEFAULT, []); return;
        case "ENDSWITCH": this.emit(OP.ENDSWITCH, []); return;
        case "EMIT":
            // a vertex: the viewport's fixes first
            for(const run of this.epilogue) run();
            this.emit(OP.EMIT, []);
            return;
        case "ENDPRIM":
            this.emit(OP.CUT, []);
            return;
        case "PK2H":
        {
            const t = this.scratch();
            this.emit(OP.F32TOF16, [as_dst(t, 0b0011), s(0)]);
            this.emit(OP.ISHL, [as_dst(t, 0b0010), scalar(t, 1), immu(16)]);
            this.emit(OP.OR, [d(), scalar(t, 0), scalar(t, 1)]);
            return;
        }
        case "UP2H":
        {
            const t = this.scratch();
            const x = first(s(0));
            this.emit(OP.AND, [as_dst(t, 1), x, immu(0xFFFF)]);
            this.emit(OP.USHR, [as_dst(t, 2), x, immu(16)]);
            this.emit(OP.F16TOF32, [d(), as_src(t, [0, 1, 0, 1])]);
            return;
        }

        case "DABS":
        case "DNEG":
        {
            const x = s(0);
            this.emit(OP.DMOV, [d(), Object.assign({}, x, { mod: op === "DABS" ? 2 : x.mod ^ 1 })]);
            return;
        }
        case "DTRUNC": case "DCEIL": case "DFLR": case "DROUND": case "DFRAC": case "DRSQ": case "DSQRT":
        {
            // (through a float: GX's doubles are floats anyway)
            const t = this.scratch();
            const out = d();
            this.emit(OP.DTOF, [as_dst(t, 0b0011), s(0)]);
            this.emit({ DTRUNC: OP.ROUND_Z, DCEIL: OP.ROUND_PI, DFLR: OP.ROUND_NI, DROUND: OP.ROUND_NE, DFRAC: OP.FRC,
                DRSQ: OP.RSQ, DSQRT: OP.SQRT }[op], [as_dst(t, 0b0011), as_src(t)]);
            this.emit(OP.FTOD, [out, as_src(t, [0, 1, 0, 1])]);
            return;
        }
        case "DSSG":
        {
            // (x > 0) - (x < 0), as a double
            const a = this.scratch(), b = this.scratch(), zero = immu(0, 0, 0, 0);
            const out = d();
            this.emit(OP.DLT, [as_dst(a, 0b0011), zero, s(0)]);
            this.emit(OP.DLT, [as_dst(b, 0b0011), s(0), zero]);
            this.emit(OP.IADD, [as_dst(a, 0b0011), as_src(b), as_src(a, null, 1)]);
            this.emit(OP.ITOF, [as_dst(a, 0b0011), as_src(a)]);
            this.emit(OP.FTOD, [out, as_src(a, [0, 1, 0, 1])]);
            return;
        }
        case "LOAD":
        case "STORE":
        case "RESQ":
            this.memory(ins);
            return;
        case "MEMBAR":
            // (shared memory and UAVs)
            this.emit(OP.SYNC, [], 2 | 8);
            return;
        case "BARRIER":
            this.emit(OP.SYNC, [], 1 | 2);
            return;
        case "TEX": case "TXP": case "TXB": case "TXL": case "TXD": case "TXF": case "TXQ": case "TG4":
        case "LODQ": case "TEX2": case "TXB2": case "TXL2": case "TEX_LZ": case "TXF_LZ": case "TXQS":
            this.texture(ins);
            return;
    }
    if(op in ATOMICS)
    {
        this.atomic(ins);
        return;
    }
    this.problem("TGSI " + op);
};

/** The UAV or shared memory of a TGSI BUFFER, IMAGE or MEMORY register */
Translator.prototype.memory_operand = function(r)
{
    if(r.file === "BUFFER") return operand(T.UAV, [r.index]);
    if(r.file === "IMAGE") return operand(T.UAV, [IMAGE_UAV + r.index]);
    if(r.file === "MEMORY") return operand(T.THREAD_GROUP_SHARED_MEMORY, [0]);
    this.problem("memory of " + r.file);
    return null;
};

/**
 * LOAD, STORE (buffers and shared memory by byte offsets, a component each
 * 4 bytes on; images by coordinates), RESQ (a buffer's size)
 */
Translator.prototype.memory = function(ins)
{
    const op = ins.op;
    if(op === "RESQ")
    {
        const r = ins.src[0];
        const m = this.memory_operand(r);
        if(!m) return;
        if(r.file === "BUFFER") this.emit(OP.BUFINFO, [this.dst(ins.dst[0]), as_src(m)]);
        else
        {
            this.problem("sizes of images");
            this.emit(OP.MOV, [this.dst(ins.dst[0]), immu(0)]);
        }
        return;
    }
    if(op === "LOAD")
    {
        const r = ins.src[0];
        const m = this.memory_operand(r);
        if(!m) return;
        const out = this.dst(ins.dst[0]);
        if(r.file === "IMAGE") this.emit(OP.LD_UAV_TYPED, [out, this.src(ins.src[1]), as_src(m)]);
        else this.emit(OP.LD_RAW, [out, first_of(this.src(ins.src[1])), as_src(m)]);
        return;
    }
    // STORE: the first register is where
    const r = ins.dst[0];
    const m = this.memory_operand(r);
    if(!m) return;
    const address = this.src(ins.src[0]), value = this.src(ins.src[1]);
    if(r.file === "IMAGE")
    {
        this.emit(OP.STORE_UAV_TYPED, [as_dst(m, 0xF), address, value]);
        return;
    }
    // raw stores write their components one after another: a run of the
    // mask at a time, from its first component's place
    const mask = r.mask;
    for(let c = 0; c < 4; c++)
    {
        if(!(mask >> c & 1)) continue;
        let end = c;
        while(end + 1 < 4 && mask >> end + 1 & 1) end++;
        let where = first_of(address);
        if(c)
        {
            const t = this.scratch();
            this.emit(OP.IADD, [as_dst(t, 1), where, immu(4 * c)]);
            where = scalar(t, 0);
        }
        this.emit(OP.STORE_RAW, [as_dst(m, (1 << end + 1) - (1 << c)), where, value]);
        c = end;
    }
};

/** ATOM*: the old value into the destination */
Translator.prototype.atomic = function(ins)
{
    const r = ins.src[0];
    const m = this.memory_operand(r);
    if(!m) return;
    const address = r.file === "IMAGE" ? this.src(ins.src[1]) : first_of(this.src(ins.src[1]));
    const values = ins.src.slice(2).map(s => first_of(this.src(s)));
    this.emit(ATOMICS[ins.op], [this.dst(ins.dst[0]), as_src(m), address, ...values]);
};

/** Before a return: what the outputs need (the epilogue), then RET */
Translator.prototype.finish = function()
{
    if(!this.gs) for(const run of this.epilogue) run();
    this.emit(OP.RET, []);
};

// ---------------------------------------------------------------------------
// Textures

Translator.prototype.texture = function(ins)
{
    const op = ins.op;
    const samp = ins.src.find(o => o.file === "SAMP");
    if(!samp)
    {
        this.problem(op + " without a sampler");
        return;
    }
    const slot = samp.index;
    const target = ins.target || "2D";
    const [dimension, coords] = TARGETS[target] || TARGETS["2D"];
    const view = this.sviews.get(slot) || {};
    const resource = operand(T.RESOURCE, [slot]);
    const sampler = operand(T.SAMPLER, [slot], 0);
    const out = this.dst(ins.dst[0]);
    const sat = ins.saturate ? 1 << 2 : 0;
    const swizzle = (this.key.swizzles || [])[slot];
    const needs_swizzle = swizzle && !(swizzle[0] === 0 && swizzle[1] === 1 && swizzle[2] === 2 && swizzle[3] === 3);
    // into a temp when the view's swizzle comes after
    const result = needs_swizzle ? this.scratch() : null;
    const into = result ? as_dst(result) : out;
    const controls = result ? 0 : sat;

    if(op === "TXQ")
    {
        if(dimension === DIM.BUFFER) this.emit(OP.BUFINFO, [into, resource]);
        // (return type uint: controls 2)
        else this.emit(OP.RESINFO, [into, first_of(this.src(ins.src[0])), as_src(resource)], 2);
        if(result) this.view_swizzle(result, out, swizzle, true, sat);
        return;
    }
    if(op === "TXQS")
    {
        this.emit(OP.SAMPLE_INFO, [into, as_src(resource)], 1);
        return;
    }

    let coord = this.src(ins.src[0]);
    // offsets: immediates (VGPU10 takes those in the instruction), or for
    // gathers any (gather4_po)
    let extended = null, offset = null;
    if(ins.offsets.length)
    {
        const o = ins.offsets[0];
        const imm = o.file === "IMM" ? this.p.imms[o.index] : null;
        if(imm && o.swizzle.slice(0, 3).every(c => (imm.values[c] | 0) >= -8 && (imm.values[c] | 0) <= 7))
        {
            const v = o.swizzle.slice(0, 3).map(c => imm.values[c] & 0xF);
            extended = [(1 | v[0] << 9 | v[1] << 13 | v[2] << 17) >>> 0];
        }
        else if(op === "TG4") offset = this.src(o);
        else this.problem("texture offsets that are not immediates");
    }

    if(op === "TXF" || op === "TXF_LZ")
    {
        let address = coord;
        if(op === "TXF_LZ" || dimension === DIM.BUFFER)
        {
            const t = this.scratch();
            this.emit(OP.MOV, [as_dst(t), coord]);
            this.emit(OP.MOV, [as_dst(t, 0b1000), immu(0)]);
            address = as_src(t);
        }
        if(dimension === DIM.TEXTURE2DMS || dimension === DIM.TEXTURE2DMSARRAY)
        {
            this.emit(OP.LD_MS, [into, address, as_src(resource), scalar(coord, 3)], controls, extended);
        }
        else this.emit(OP.LD, [into, address, as_src(resource)], controls, extended);
        if(result) this.view_swizzle(result, out, swizzle, view.integer, sat);
        return;
    }

    // texture() of an integer texture (D3D samples only floats): the texel
    // under the coordinates, by a fetch from the level (clamped to its edges)
    if(view.integer && !SHADOW_REF[target] && (op === "TEX" || op === "TXP" || op === "TXB" || op === "TXL" || op === "TEX_LZ") &&
        dimension !== DIM.TEXTURECUBE && dimension !== DIM.TEXTURECUBEARRAY && dimension !== DIM.BUFFER)
    {
        const t = this.scratch(), size = this.scratch(), at = this.scratch();
        if(op === "TXP") this.emit(OP.DIV, [as_dst(t, 0b0111), coord, scalar(coord, 3)]);
        else this.emit(OP.MOV, [as_dst(t), coord]);
        if(op === "TXL") this.emit(OP.FTOI, [as_dst(at, 0b1000), scalar(coord, 3)]);
        else this.emit(OP.MOV, [as_dst(at, 0b1000), immu(0)]);
        this.emit(OP.RESINFO, [as_dst(size), scalar(at, 3), as_src(resource)], 2);
        // the dimensions scaled (an array's layer is not)
        const scaled = { [DIM.TEXTURE1D]: 1, [DIM.TEXTURE1DARRAY]: 1, [DIM.TEXTURE2D]: 2, [DIM.TEXTURE2DARRAY]: 2, [DIM.TEXTURE3D]: 3 }[dimension] || 2;
        const mask = (1 << scaled) - 1;
        const fsize = this.scratch();
        this.emit(OP.UTOF, [as_dst(fsize, mask), as_src(size)]);
        this.emit(OP.MUL, [as_dst(t, mask), as_src(t), as_src(fsize)]);
        this.emit(OP.ROUND_NI, [as_dst(t, mask), as_src(t)]);
        if(scaled < coords) this.emit(OP.ROUND_NE, [as_dst(t, 1 << scaled), as_src(t)]);
        this.emit(OP.FTOI, [as_dst(at, (1 << coords) - 1), as_src(t)]);
        this.emit(OP.IADD, [as_dst(size, mask), as_src(size), immu(0xFFFFFFFF)]);
        this.emit(OP.IMAX, [as_dst(at, mask), as_src(at), immu(0)]);
        this.emit(OP.IMIN, [as_dst(at, mask), as_src(at), as_src(size)]);
        this.emit(OP.LD, [into, as_src(at), as_src(resource)], controls, extended);
        if(result) this.view_swizzle(result, out, swizzle, true, sat);
        return;
    }

    // projective: divided by w first
    if(op === "TXP")
    {
        const t = this.scratch();
        this.emit(OP.DIV, [as_dst(t, 0b0111), coord, scalar(coord, 3)]);
        coord = as_src(t);
    }
    // rectangles: coordinates in texels
    if(target === "RECT" || target === "SHADOWRECT")
    {
        const size = this.scratch(), t = this.scratch();
        this.emit(OP.RESINFO, [as_dst(size), immu(0), as_src(resource)], 0);
        this.emit(OP.MOV, [as_dst(t), coord]);
        this.emit(OP.DIV, [as_dst(t, 0b0011), as_src(t), as_src(size)]);
        coord = as_src(t);
    }
    const shadow = SHADOW_REF[target];
    let ref = null;
    if(shadow !== undefined) ref = shadow < 0 ? first_of(this.src(ins.src[1])) : scalar(coord, shadow);

    switch(op)
    {
        case "TEX":
        case "TXP":
        case "TEX2":
            if(ref) this.emit(OP.SAMPLE_C, [into, coord, as_src(resource), sampler, ref], controls, extended);
            else this.emit(OP.SAMPLE, [into, coord, as_src(resource), sampler], controls, extended);
            break;
        case "TEX_LZ":
            if(ref) this.emit(OP.SAMPLE_C_LZ, [into, coord, as_src(resource), sampler, ref], controls, extended);
            else this.emit(OP.SAMPLE_L, [into, coord, as_src(resource), sampler, immf(0)], controls, extended);
            break;
        case "TXB":
        case "TXB2":
        {
            const bias = op === "TXB2" ? first_of(this.src(ins.src[1])) : scalar(coord, 3);
            if(ref) this.emit(OP.SAMPLE_C, [into, coord, as_src(resource), sampler, ref], controls, extended);
            else this.emit(OP.SAMPLE_B, [into, coord, as_src(resource), sampler, bias], controls, extended);
            break;
        }
        case "TXL":
        case "TXL2":
        {
            const lod = op === "TXL2" ? first_of(this.src(ins.src[1])) : scalar(coord, 3);
            // (D3D compares at level 0 only)
            if(ref) this.emit(OP.SAMPLE_C_LZ, [into, coord, as_src(resource), sampler, ref], controls, extended);
            else this.emit(OP.SAMPLE_L, [into, coord, as_src(resource), sampler, lod], controls, extended);
            break;
        }
        case "TXD":
        {
            const ddx = this.src(ins.src[1]), ddy = this.src(ins.src[2]);
            if(ref) this.emit(OP.SAMPLE_C, [into, coord, as_src(resource), sampler, ref], controls, extended);
            else this.emit(OP.SAMPLE_D, [into, coord, as_src(resource), sampler, ddx, ddy], controls, extended);
            break;
        }
        case "TG4":
        {
            // the component: the second source's x (an immediate)
            const c = ins.src[1] && ins.src[1].file === "IMM" ? this.p.imms[ins.src[1].index].values[ins.src[1].swizzle[0]] & 3 : 0;
            const s = Object.assign({}, sampler, { ncomp: 4, mode: "select", swz: [c, c, c, c] });
            if(offset)
            {
                if(ref) this.emit(OP.GATHER4_PO_C, [into, coord, offset, as_src(resource), s, ref], controls);
                else this.emit(OP.GATHER4_PO, [into, coord, offset, as_src(resource), s], controls);
            }
            else if(ref) this.emit(OP.GATHER4_C, [into, coord, as_src(resource), s, ref], controls, extended);
            else this.emit(OP.GATHER4, [into, coord, as_src(resource), s], controls, extended);
            break;
        }
        case "LODQ":
            this.emit(OP.LOD, [into, coord, as_src(resource), sampler], controls);
            break;
    }
    if(result) this.view_swizzle(result, out, swizzle, view.integer, sat);
};

/** The VGPU10 return type of an image's format (PIPE_FORMAT_*) */
function image_return_type(format)
{
    if(!format) return RETURN.FLOAT;
    if(/_UINT$/.test(format)) return RETURN.UINT;
    if(/_SINT$/.test(format)) return RETURN.SINT;
    if(/_UNORM$/.test(format)) return RETURN.UNORM;
    if(/_SNORM$/.test(format)) return RETURN.SNORM;
    return RETURN.FLOAT;
}

function first_of(o)
{
    return as_src(o, [o.swz[0], o.swz[0], o.swz[0], o.swz[0]], o.mod);
}

/** A sampler view's swizzle (PIPE_SWIZZLE_*) on what was sampled into `result` */
Translator.prototype.view_swizzle = function(result, out, swizzle, integer, sat)
{
    const mask = out.mask;
    const picks = [], constants = [];
    for(let c = 0; c < 4; c++)
    {
        if(!(mask >> c & 1)) continue;
        if(swizzle[c] <= 3) picks.push(c);
        else constants.push(c);
    }
    if(picks.length)
    {
        let m = 0;
        for(const c of picks) m |= 1 << c;
        this.emit(OP.MOV, [Object.assign({}, out, { mask: m }), as_src(result, [0, 1, 2, 3].map(c => swizzle[c] <= 3 ? swizzle[c] : 0))], sat);
    }
    if(constants.length)
    {
        let m = 0;
        for(const c of constants) m |= 1 << c;
        const v = [0, 1, 2, 3].map(c => swizzle[c] === PIPE_SWIZZLE_1 ? (integer ? 1 : ONE_F) : 0);
        this.emit(OP.MOV, [Object.assign({}, out, { mask: m }), immu(v[0], v[1], v[2], v[3])]);
    }
};

// ---------------------------------------------------------------------------

/**
 * One TGSI program, for a variant
 * @param {!Object} program from parse_tgsi
 * @param {!Object} key outputs (semantic key -> register), all_outputs
 *     (stream output: every output in a register), flip_y, halfz, swizzles
 *     (per view: 4 PIPE_SWIZZLE_*), color_buffers, flatshade, alpha_func, alpha_ref,
 *     clip_enable (GL's clip distances in use: discarded where below zero)
 * @return {{tokens: !Uint32Array, inputs: !Object<string, number>, outputs: !Object<number, number>,
 *     problems: !Array<string>, type: number}}
 */
export function tgsi_to_vgpu10(program, key)
{
    if(program.processor === 3) return tcs_to_hull(program, key);
    return translate(program, key);
}

/**
 * A tessellation control shader as a hull shader: its declarations (the
 * tessellator's, from key: domain, partitioning, output primitive, input
 * and output control points), then the shader twice, as the control point
 * phase and as the fork phase (the patch constants)
 */
function tcs_to_hull(program, key)
{
    const cp = translate(program, Object.assign({}, key, { hs_phase: "cp" }), true);
    const fork = translate(program, Object.assign({}, key, { hs_phase: "fork" }), true);
    const out_cps = +((program.properties.TCS_VERTICES_OUT || [1])[0]) || 1;
    const head = [
        (OP.HS_DECLS | 1 << 24) >>> 0,
        (OP.DCL_INPUT_CONTROL_POINT_COUNT | (key.in_cps || 1) << 11 | 1 << 24) >>> 0,
        (OP.DCL_OUTPUT_CONTROL_POINT_COUNT | out_cps << 11 | 1 << 24) >>> 0,
        (OP.DCL_TESS_DOMAIN | { isoline: 1, tri: 2, quad: 3 }[key.domain || "quad"] << 11 | 1 << 24) >>> 0,
        (OP.DCL_TESS_PARTITIONING | (key.partitioning || 1) << 11 | 1 << 24) >>> 0,
        (OP.DCL_TESS_OUTPUT_PRIMITIVE | (key.output_primitive || 3) << 11 | 1 << 24) >>> 0,
        (OP.DCL_HS_MAX_TESSFACTOR | 2 << 24) >>> 0, f32_bits(64),
    ];
    const phase = (marker, part) => [(marker | 1 << 24) >>> 0, (OP.DCL_TEMPS | 2 << 24) >>> 0, part.temps, ...part.decls, ...part.code];
    const body = [...head, ...phase(OP.HS_CONTROL_POINT_PHASE, cp), ...phase(OP.HS_FORK_PHASE, fork)];
    const tokens = new Uint32Array(2 + body.length);
    tokens[0] = (3 << 16 | 5 << 4 | 0) >>> 0;
    tokens[1] = tokens.length;
    tokens.set(body, 2);
    return { tokens, inputs: cp.inputs, outputs: cp.outputs, problems: [...new Set([...cp.problems, ...fork.problems])], type: 3 };
}

/**
 * @param {boolean=} parts the declarations and code apart (a hull shader's phase)
 */
function translate(program, key, parts)
{
    const t = new Translator(program, key);
    t.prologue_ops = [];
    t.scan();
    t.declare();
    for(const run of t.prologue_ops) run();
    t.scratch_base = t.next_temp;
    for(const ins of program.code)
    {
        if(t.ended) break;
        t.instruction(ins);
    }
    if(!t.ended) t.finish();
    if(t.indirect_imm)
    {
        // the immediates as an immediate constant buffer
        const data = [];
        for(const imm of program.imms) data.push(...(imm ? imm.values : [0, 0, 0, 0]));
        t.decls.unshift((OP.CUSTOMDATA | 3 << 11) >>> 0, 2 + data.length, ...data);
    }
    if(parts) return { decls: t.decls, code: t.code, temps: t.temps, inputs: t.link_inputs, outputs: t.output_regs, problems: t.problems };
    const decls = [(OP.DCL_TEMPS | 2 << 24) >>> 0, t.temps, ...t.decls];
    const type = PROGRAM[program.processor];
    const length = 2 + decls.length + t.code.length;
    const tokens = new Uint32Array(length);
    tokens[0] = (type << 16 | 5 << 4 | 0) >>> 0;
    tokens[1] = length;
    tokens.set(decls, 2);
    tokens.set(t.code, 2 + decls.length);
    return { tokens, inputs: t.link_inputs, outputs: t.output_regs, problems: t.problems, type };
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/graphics_adapters/virtio_gpu/venus.js                                                0000644 0000000 0000000 00000070510 00000000000 020026  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Venus: Vulkan for the guest's Mesa venus driver, over virtio-gpu (capset 4,
// level "venus"). This is the transport: the capset, Venus contexts, the
// shared memory the driver allocates (HOST3D blobs of blob id 0, in the host
// visible memory, BAR4), the command rings in it, reply streams and the
// MESA transport commands. The Vulkan commands themselves go to the Vulkan
// model (venus_vk.js). See docs/gpu-devices.md, "Venus (Vulkan)".
//
// The driver writes commands into a ring and moves its tail; this device
// reads them on its timer (every time the machine's timers run) and when the
// driver submits anything, moves the head past each command it has done, and
// writes replies into the reply stream the driver set. A command whose answer
// waits for the GPU stops its ring (or its submission) until it is answered.
// Rings never go idle: the driver need not notify, and the status keeps the
// ALIVE bit, which the driver's watchdog clears while it waits.

import { COMMANDS, EXTENSIONS, VenusReader, VenusWriter, VK_XML_VERSION, WIRE_FORMAT_VERSION } from "./venus_protocol.js";
import { dbg_log } from "../../log.js";
import { encode_objects, decode_objects } from "./venus_state.js";
import { LOG_VIRTIO } from "../../const.js";

export const CAPSET_VENUS = 4;
/** virgl_renderer_capset_venus: 5 dwords, the extension mask (32), 3 dwords */
export const CAPSET_VENUS_SIZE = 40 * 4;

const COMMAND_GENERATE_REPLY = 1;

const RING_STATUS_FATAL = 2;
const RING_STATUS_ALIVE = 4;

/** what may be written into a ring's buffer between two reads (the driver's limit is the buffer) */
const MAX_DIRECT = 1 << 20;

/** the start of the key of a ring restored from a snapshot whose ring ids were numbers (ring_key) */
const ROUNDED = "~";

/**
 * The capset: the protocol of venus_protocol.js (Mesa 26.1.6's), every
 * extension of it (the extension mask's bit 0 clear says so); what the
 * device supports is what it enumerates
 * @return {!Uint8Array}
 */
export function venus_capset()
{
    const words = new Uint32Array(CAPSET_VENUS_SIZE / 4);
    words[0] = WIRE_FORMAT_VERSION;
    words[1] = VK_XML_VERSION;
    words[2] = EXTENSIONS["VK_EXT_command_serialization"][1];
    words[3] = EXTENSIONS["VK_MESA_venus_protocol"][1];
    // supports_blob_id_0: shared memory is HOST3D, blob id 0
    words[4] = 1;
    // allow_vk_wait_syncs, supports_multiple_timelines; not use_guest_vram
    words[37] = 1;
    words[38] = 1;
    words[39] = 0;
    return new Uint8Array(words.buffer);
}

/**
 * A blob of a Venus context: shared memory (blob id 0) or the export of
 * a VkDeviceMemory (blob id: the memory's object id)
 * @constructor
 */
export function VenusBlob(id, ctx_id, blob_id, flags, size)
{
    this.id = id;
    this.venus = true;
    this.ctx_id = ctx_id;
    this.blob_id = blob_id;
    this.blob_flags = flags;
    this.blob_size = size;
    /** where it is mapped in the host visible memory, -1 when it is not */
    this.map_offset = -1;
    /** @type {Object} the VkDeviceMemory it exports */
    this.memory = null;
    this.backing = null;
}

/**
 * A command ring in shared memory
 * @constructor
 * @param {string} id its key in its context's rings (ring_key)
 */
function Ring(id, blob, info)
{
    this.id = id;
    this.blob = blob;
    this.head_offset = info.headOffset;
    this.tail_offset = info.tailOffset;
    this.status_offset = info.statusOffset;
    this.buffer_offset = info.bufferOffset;
    this.buffer_size = info.bufferSize;
    this.extra_offset = info.extraOffset;
    this.extra_size = info.extraSize;
    /** where this device has read to (the driver's seqnos are these positions) */
    this.head = 0;
    /** @type {Run} the commands in progress, when one waits */
    this.run = null;
    this.fatal = false;
}

/**
 * Commands being run: a ring's (between its head and tail) or a
 * submission's; stopped at a command that waits
 * @constructor
 * @param {!VenusReader} reader
 * @param {function(number)} on_command after each command, its length
 * @param {function()} on_end
 */
function Run(reader, on_command, on_end)
{
    this.reader = reader;
    this.on_command = on_command;
    this.on_end = on_end;
    this.waiting = false;
    /** the command it waits in (for debugging) */
    this.waiting_on = "";
    /** where that command starts */
    this.at = 0;
}

/**
 * A Venus context: the guest process's driver instance
 * @constructor
 * @param {!Venus} venus
 * @param {number} id
 */
function VenusContext(venus, id)
{
    this.venus = venus;
    this.id = id;
    /** @type {!Map<string, !Ring>} by ring_key */
    this.rings = new Map();
    /** @type {?{blob: !VenusBlob, offset: number, size: number, position: number}} the reply stream */
    this.reply = null;
    /** the last vkSubmitVirtqueueSeqnoMESA, by ring */
    this.virtqueue_seqnos = new Map();
    /** @type {!Array<!Run>} submissions (SUBMIT_3D) waiting for the one before them */
    this.submissions = [];
    /** @type {!Array<function()>} commands waiting for a virtqueue or ring seqno */
    this.seqno_waits = [];
    /** a wake of the seqno waits is due (Venus.run_ring) */
    this.wake_pending = false;
    /** the Vulkan objects of this context, by the ids the driver gave them */
    this.objects = new Map();
    this.destroyed = false;
}

/**
 * @constructor
 * @param {!Object} gpu the VirtioGPU
 * @param {!Object} vk the Vulkan model: handle(ctx, name, args) -> wait or null
 */
export function Venus(gpu, vk)
{
    this.gpu = gpu;
    this.vk = vk;
    /** @type {!Map<number, !VenusContext>} */
    this.contexts = new Map();
    // failures: the commands that answered an error, with the last one (VkResult)
    // last_error: what made the last command fail (decoding, a handler), and in which command
    this.stats = { commands: 0, replies: 0, rings: 0, waits: 0, errors: 0, unknown: {}, failures: {}, last_error: "" };
    /** the command being run, for errors */
    this.current = "";
    /** @type {?function(string, !Object)} a harness's hook: each command as decoded */
    this.on_command = null;
    this.last_alive = 0;
}

/** its capsets, [id, version, size], and their contents (the device's kinds of context) */
Venus.prototype.capsets = [[CAPSET_VENUS, 0, CAPSET_VENUS_SIZE]];
/** @param {number} id @return {!Uint8Array} */
Venus.prototype.capset = function(id)
{
    return venus_capset();
};

/** the bytes [x, x + data.length) of a mapped blob, as the guest wrote them */
Venus.prototype.upload_blob = function(blob, x, data)
{
    this.vk.upload_blob(blob, x, data);
};

Venus.prototype.reset = function()
{
    for(const ctx of this.contexts.values())
    {
        ctx.destroyed = true;
        this.vk.destroy_context(ctx);
    }
    this.contexts.clear();
};

// ---------------------------------------------------------------------------
// Snapshots: the contexts (rings, reply streams, the model's objects); the
// commands that waited are read again from where their rings stopped

/** @return {!Array} */
Venus.prototype.get_state = function()
{
    const contexts = [];
    for(const ctx of this.contexts.values())
    {
        const rings = [...ctx.rings.values()].map(r => [r.id, r.blob.id, r.head_offset, r.tail_offset, r.status_offset, r.buffer_offset,
            r.buffer_size, r.extra_offset, r.extra_size, r.head, r.fatal]);
        const reply = ctx.reply ? [ctx.reply.blob.id, ctx.reply.offset, ctx.reply.size, ctx.reply.position] : null;
        const objects = encode_objects(ctx.objects, o => o instanceof VenusContext ? ["ctx", o.id] : o instanceof VenusBlob ? ["blob", o.id] : null);
        contexts.push([ctx.id, rings, reply, [...ctx.virtqueue_seqnos], objects, ctx.physical_device]);
    }
    return [contexts, this.vk.get_state()];
};

/**
 * @param {!Array} state from get_state
 * @param {function(number): VenusBlob} blob_of the restored blob of a resource id
 */
Venus.prototype.set_state = function(state, blob_of)
{
    // (the renderer was reset: its objects are gone already; the old
    // contexts' commands that wait never go on, nor write their replies)
    for(const ctx of this.contexts.values()) ctx.destroyed = true;
    this.contexts.clear();
    const [contexts, vk_state] = state;
    for(const [id, rings, reply, seqnos, objects, physical_device] of contexts)
    {
        const ctx = new VenusContext(this, id);
        this.contexts.set(id, ctx);
        ctx.physical_device = physical_device;
        ctx.objects = decode_objects(objects, ([kind, x]) => kind === "ctx" ? this.contexts.get(x) || null : kind === "blob" ? blob_of(x) : null);
        for(const [saved_id, blob_id, head_offset, tail_offset, status_offset, buffer_offset, buffer_size, extra_offset, extra_size, head, fatal] of rings)
        {
            const blob = blob_of(blob_id);
            if(!blob) continue;
            // (a snapshot of before the ids were exact: its id is a number
            // the driver's pointer rounded to, under which ring_key finds it)
            const ring_id = typeof saved_id === "number" ? ROUNDED + saved_id : saved_id;
            const ring = new Ring(ring_id, blob, { headOffset: head_offset, tailOffset: tail_offset, statusOffset: status_offset,
                bufferOffset: buffer_offset, bufferSize: buffer_size, extraOffset: extra_offset, extraSize: extra_size });
            ring.head = head;
            ring.fatal = fatal;
            ctx.rings.set(ring_id, ring);
        }
        const reply_blob = reply && blob_of(reply[0]);
        if(reply_blob) ctx.reply = { blob: reply_blob, offset: reply[1], size: reply[2], position: reply[3] };
        ctx.virtqueue_seqnos = new Map(seqnos);
    }
    this.vk.set_state(vk_state, [...this.contexts.values()]);
};

/**
 * Before a save: the rings run (the machine is stopped: nothing else runs
 * them) until `idle` says the device's requests are done, for a while at most
 * @param {function(): boolean} idle
 * @return {!Promise}
 */
Venus.prototype.settle = function(idle)
{
    const deadline = Date.now() + 5000;
    return new Promise(resolve => {
        const step = () => {
            for(const ctx of this.contexts.values()) this.run_rings(ctx);
            this.vk.wake();
            if(idle() || Date.now() > deadline) resolve(undefined);
            else setTimeout(step, 5);
        };
        step();
    });
};

/** @param {number} id */
Venus.prototype.create_context = function(id)
{
    const old = this.contexts.get(id);
    if(old) this.destroy_context(id);
    const ctx = new VenusContext(this, id);
    this.contexts.set(id, ctx);
    this.vk.create_context(ctx);
};

/** @param {number} id */
Venus.prototype.destroy_context = function(id)
{
    const ctx = this.contexts.get(id);
    if(!ctx) return;
    ctx.destroyed = true;
    this.vk.destroy_context(ctx);
    this.contexts.delete(id);
};

/** @return {!Uint8Array} the host visible memory */
Venus.prototype.bytes = function()
{
    return this.gpu.hostmem_bytes();
};

/**
 * RESOURCE_CREATE_BLOB of a Venus context
 * @return {VenusBlob} null when it cannot be made
 */
Venus.prototype.create_blob = function(id, ctx_id, flags, blob_id, size)
{
    const ctx = this.contexts.get(ctx_id);
    if(!ctx || !size) return null;
    const blob = new VenusBlob(id, ctx_id, blob_id, flags, size);
    if(blob_id !== 0)
    {
        // a VkDeviceMemory's export
        const memory = ctx.objects.get(blob_id);
        if(!memory || !this.vk.export_memory(ctx, memory, blob))
        {
            if(this.vk.debug) this.vk.debug("blob " + id + " of object " + blob_id + " (" + (memory ? memory.type + " of " + memory.size +
                (memory.blob ? ", exported as " + memory.blob.id : "") : "none") + "), " + size + " bytes: refused");
            return null;
        }
        blob.memory = memory;
    }
    return blob;
};

/**
 * The blob was mapped at `offset`; shared memory needs nothing, memory gets
 * its contents
 * @param {!VenusBlob} blob
 * @return {?function(function())} when the contents come later
 */
Venus.prototype.mapped = function(blob)
{
    return blob.memory ? this.vk.map_memory(blob.memory, blob) : null;
};

/** @param {!VenusBlob} blob */
Venus.prototype.unref_blob = function(blob)
{
    if(blob.memory) this.vk.unexport_memory(blob.memory, blob);
    const ctx = this.contexts.get(blob.ctx_id);
    if(!ctx) return;
    for(const ring of [...ctx.rings.values()]) if(ring.blob === blob) ctx.rings.delete(ring.id);
    if(ctx.reply && ctx.reply.blob === blob) ctx.reply = null;
};

/**
 * SUBMIT_3D of a Venus context: commands, run in order after the context's
 * earlier submissions
 * @param {number} ctx_id
 * @param {!Uint8Array} bytes
 * @param {number=} ring_idx a fence on this timeline (a queue's): answered after the queue's work
 * @return {?function(function())} the answer waits until it calls back
 */
Venus.prototype.submit = function(ctx_id, bytes, ring_idx)
{
    const ctx = this.contexts.get(ctx_id);
    if(!ctx) return null;
    // (the driver sends commands it waits for through its rings first)
    this.run_rings(ctx);
    let finished = false, finish = null;
    const run = new Run(new VenusReader(bytes), () => {}, () => {
        const done = () => {
            finished = true;
            ctx.submissions.shift();
            if(finish) finish();
            if(ctx.submissions.length) this.resume(ctx, ctx.submissions[0]);
        };
        if(ring_idx && !this.vk.timeline_idle(ctx, ring_idx)) this.vk.add_waiter(() => this.vk.timeline_idle(ctx, ring_idx), Infinity, done);
        else done();
    });
    ctx.submissions.push(run);
    if(ctx.submissions.length === 1) this.resume(ctx, run);
    if(finished) return null;
    const wait = done => { if(finished) done(); else finish = done; };
    // (for a snapshot: save_submission)
    wait.submission = { ctx_id, run, ring_idx: ring_idx || 0 };
    return wait;
};

/**
 * A submission whose answer waits, for a snapshot: its commands from the one
 * it waits in (those before it are done), or all of them when it has not
 * started (it waits for the one before it)
 * @param {{ctx_id: number, run: !Run, ring_idx: number}} submission
 * @return {!Array}
 */
Venus.prototype.save_submission = function(submission)
{
    const { ctx_id, run, ring_idx } = submission;
    const r = run.reader;
    return [ctx_id, r.bytes.slice(run.waiting ? run.at : r.p, r.end), ring_idx];
};

/**
 * A snapshot's submission, submitted again (after the contexts are restored)
 * @param {!Array} saved from save_submission
 * @return {?function(function())} as submit
 */
Venus.prototype.resubmit = function(saved)
{
    const [ctx_id, bytes, ring_idx] = saved;
    return this.submit(ctx_id, Uint8Array.from(bytes), ring_idx);
};

/**
 * Run commands until they end or one waits
 * @param {!VenusContext} ctx
 * @param {!Run} run
 */
Venus.prototype.resume = function(ctx, run)
{
    const r = run.reader;
    run.waiting = false;
    if(ctx.destroyed) return;
    while(r.p < r.end)
    {
        if(ctx.destroyed) return;
        const start = r.p;
        let wait;
        try
        {
            wait = this.command(ctx, r);
        }
        catch(e)
        {
            this.stats.errors++;
            this.stats.last_error = (this.current || "decoding") + ": " + String(e && e.message || e).slice(0, 200);
            dbg_log("venus: " + this.stats.last_error, LOG_VIRTIO);
            this.fatal(ctx, run);
            return;
        }
        if(wait)
        {
            this.stats.waits++;
            run.waiting = true;
            run.waiting_on = this.current;
            run.at = start;
            wait(() => {
                // (a context of before a restore or a reset: its ring's head is not this machine's)
                if(ctx.destroyed) return;
                run.on_command(r.p - start);
                this.resume(ctx, run);
            });
            return;
        }
        run.on_command(r.p - start);
    }
    run.on_end();
};

/**
 * A ring's commands cannot go on: its status says so, and the driver aborts
 * @param {!VenusContext} ctx
 * @param {!Run} run
 */
Venus.prototype.fatal = function(ctx, run)
{
    for(const ring of ctx.rings.values())
    {
        if(ring.run !== run) continue;
        ring.fatal = true;
        this.set_status(ring, RING_STATUS_FATAL);
    }
    // (a submission: what follows it still runs)
    if(ctx.submissions[0] === run) run.on_end();
};

/**
 * One command
 * @param {!VenusContext} ctx
 * @param {!VenusReader} r
 * @return {?function(function())} the command's reply waits
 */
Venus.prototype.command = function(ctx, r)
{
    const type = r.u32(), flags = r.u32();
    const entry = COMMANDS[type];
    this.current = "";
    if(!entry) throw new Error("unknown command " + type);
    const name = entry[0];
    this.current = name;
    const args = entry[1](r);
    this.stats.commands++;
    if(this.on_command) this.on_command(name, args);
    const transport = TRANSPORT[name];
    const wait = transport ? transport(this, ctx, args) : this.vk.handle(ctx, name, args);
    if(!(flags & COMMAND_GENERATE_REPLY)) return wait;
    if(!entry[2]) throw new Error(name + " has no reply");
    if(!wait)
    {
        this.note_result(name, args);
        this.write_reply(ctx, entry[2], args);
        return null;
    }
    // the reply goes to the stream set for it (a ring sets one before each
    // command with a reply; another ring's may be set while this one waits)
    const stream = ctx.reply;
    return done => wait(() => {
        if(ctx.destroyed) return;
        try
        {
            this.note_result(name, args);
            this.write_reply(ctx, entry[2], args, stream);
        }
        catch(e)
        {
            this.stats.errors++;
            dbg_log("venus: " + name + ": " + (e && e.message || e), LOG_VIRTIO);
        }
        done();
    });
};

/** an error a command answers, in the stats (VK_NOT_READY and VK_TIMEOUT are no errors) */
Venus.prototype.note_result = function(name, args)
{
    if(typeof args.ret === "number" && args.ret < 0) this.stats.failures[name] = args.ret;
};

/**
 * @param {!VenusContext} ctx
 * @param {function(!VenusWriter, !Object)} encode
 * @param {!Object} args
 * @param {?{blob: !VenusBlob, offset: number, size: number, position: number}=} stream the context's when not given
 */
Venus.prototype.write_reply = function(ctx, encode, args, stream)
{
    if(stream === undefined) stream = ctx.reply;
    if(!stream || stream.blob.map_offset < 0) throw new Error("a reply without a reply stream");
    const w = new VenusWriter(256);
    encode(w, args);
    const out = w.result();
    if(stream.position + out.length > stream.size) throw new Error("the reply does not fit its stream");
    this.bytes().set(out, stream.blob.map_offset + stream.offset + stream.position);
    stream.position += out.length;
    this.stats.replies++;
};

/**
 * @param {!VenusContext} ctx
 * @param {number} id
 * @return {!VenusBlob}
 */
Venus.prototype.shared_memory = function(ctx, id)
{
    const r = this.gpu.resources.get(id);
    if(!r || !r.venus || r.map_offset < 0) throw new Error("resource " + id + " is not mapped shared memory");
    return r;
};

// ---------------------------------------------------------------------------
// Rings

/** Run every context's rings; set their ALIVE bits now and then */
Venus.prototype.timer = function(now)
{
    this.vk.timer(now);
    const alive = now - this.last_alive >= 500 || now < this.last_alive;
    if(alive) this.last_alive = now;
    for(const ctx of this.contexts.values())
    {
        this.run_rings(ctx);
        if(alive) for(const ring of ctx.rings.values()) this.set_status(ring, RING_STATUS_ALIVE);
    }
};

/** @param {!VenusContext} ctx */
Venus.prototype.run_rings = function(ctx)
{
    for(const ring of ctx.rings.values()) this.run_ring(ctx, ring);
};

/**
 * @param {!VenusContext} ctx
 * @param {!Ring} ring
 */
Venus.prototype.run_ring = function(ctx, ring)
{
    if(ring.run || ring.fatal || ring.blob.map_offset < 0) return;
    const bytes = this.bytes();
    const base = ring.blob.map_offset;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const tail = view.getUint32(base + ring.tail_offset, true);
    const size = (tail - ring.head) >>> 0;
    if(!size) return;
    if(size > ring.buffer_size || size > MAX_DIRECT || size & 3)
    {
        ring.fatal = true;
        this.set_status(ring, RING_STATUS_FATAL);
        return;
    }
    // the commands, in one piece (the buffer wraps)
    const commands = new Uint8Array(size);
    const at = ring.head & ring.buffer_size - 1, buffer = base + ring.buffer_offset;
    const first = Math.min(size, ring.buffer_size - at);
    commands.set(bytes.subarray(buffer + at, buffer + at + first));
    if(first < size) commands.set(bytes.subarray(buffer, buffer + size - first), first);
    this.stats.rings++;
    ring.run = new Run(new VenusReader(commands), length => {
        ring.head = ring.head + length >>> 0;
        if(ring.blob.map_offset >= 0)
        {
            const now = this.bytes();
            new DataView(now.buffer, now.byteOffset, now.byteLength).setUint32(ring.blob.map_offset + ring.head_offset, ring.head, true);
        }
        // (rings waiting for this one's head: not only when its run ends,
        // which can wait on them; after this turn, so that no ring runs
        // between another's reply stream and its command)
        if(ctx.seqno_waits.length && !ctx.wake_pending)
        {
            ctx.wake_pending = true;
            Promise.resolve().then(() => { ctx.wake_pending = false; this.wake_seqno_waits(ctx); });
        }
    }, () => {
        ring.run = null;
        this.wake_seqno_waits(ctx);
        // (more may have come meanwhile)
        if(!ring.fatal && !ctx.destroyed) this.run_ring(ctx, ring);
    });
    this.resume(ctx, ring.run);
};

/**
 * @param {!Ring} ring
 * @param {number} bits
 */
Venus.prototype.set_status = function(ring, bits)
{
    if(ring.blob.map_offset < 0) return;
    const bytes = this.bytes();
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const at = ring.blob.map_offset + ring.status_offset;
    view.setUint32(at, view.getUint32(at, true) | bits, true);
};

/** @param {!VenusContext} ctx */
Venus.prototype.wake_seqno_waits = function(ctx)
{
    const waits = ctx.seqno_waits;
    ctx.seqno_waits = [];
    for(const check of waits) check();
};

/**
 * Whether ring position a is at or past b (positions wrap at 2**32; the
 * driver's seqnos are positions)
 */
function seqno_passed(a, b)
{
    return (a - b | 0) >= 0;
}

/**
 * The key of the ring the driver names `id` (VenusReader.ring_id: its
 * pointer's 16 hex digits). Until 2026-10-19 the ids were numbers, which
 * round the driver's pointers to multiples of 2048 (Android's heap pointers
 * have a tag in the top byte), so that two threads' rings could get one id
 * and the second replaced the first, whose thread then waited for good; a
 * snapshot of then has its rings under the rounded number (set_state)
 * @param {!VenusContext} ctx
 * @param {string} id
 * @return {string}
 */
function ring_key(ctx, id)
{
    if(ctx.rings.has(id)) return id;
    const rounded = ROUNDED + Number(BigInt("0x" + id));
    return ctx.rings.has(rounded) ? rounded : id;
}

// ---------------------------------------------------------------------------
// The transport commands

/** @type {!Object<string, function(!Venus, !VenusContext, !Object): ?function(function())>} */
const TRANSPORT = {
    "vkCreateRingMESA": function(venus, ctx, a)
    {
        const info = a.pCreateInfo;
        const blob = venus.shared_memory(ctx, info.resourceId);
        const end = info.offset + info.size;
        if(info.bufferSize & info.bufferSize - 1 || end > blob.blob_size ||
            info.bufferOffset + info.bufferSize > info.size || info.extraOffset + info.extraSize > info.size)
        {
            throw new Error("vkCreateRingMESA: bad layout");
        }
        // (offsets within the resource: the ring may start inside it)
        const ring = new Ring(a.ring, blob, {
            headOffset: info.offset + info.headOffset, tailOffset: info.offset + info.tailOffset,
            statusOffset: info.offset + info.statusOffset, bufferOffset: info.offset + info.bufferOffset,
            bufferSize: info.bufferSize, extraOffset: info.offset + info.extraOffset, extraSize: info.extraSize,
        });
        ctx.rings.set(a.ring, ring);
        venus.set_status(ring, RING_STATUS_ALIVE);
        return null;
    },
    "vkDestroyRingMESA": function(venus, ctx, a)
    {
        ctx.rings.delete(ring_key(ctx, a.ring));
        return null;
    },
    "vkNotifyRingMESA": function(venus, ctx, a)
    {
        const ring = ctx.rings.get(ring_key(ctx, a.ring));
        if(ring) venus.run_ring(ctx, ring);
        return null;
    },
    "vkWriteRingExtraMESA": function(venus, ctx, a)
    {
        const ring = ctx.rings.get(ring_key(ctx, a.ring));
        if(!ring || a.offset + 4 > ring.extra_size) throw new Error("vkWriteRingExtraMESA: bad ring or offset");
        const bytes = venus.bytes();
        new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
            .setUint32(ring.blob.map_offset + ring.extra_offset + a.offset, a.value, true);
        return null;
    },
    "vkSetReplyCommandStreamMESA": function(venus, ctx, a)
    {
        const stream = a.pStream;
        const blob = venus.shared_memory(ctx, stream.resourceId);
        if(stream.offset + stream.size > blob.blob_size) throw new Error("vkSetReplyCommandStreamMESA: past the resource");
        ctx.reply = { blob, offset: stream.offset, size: stream.size, position: 0 };
        return null;
    },
    "vkSeekReplyCommandStreamMESA": function(venus, ctx, a)
    {
        if(!ctx.reply || a.position > ctx.reply.size) throw new Error("vkSeekReplyCommandStreamMESA: no stream or past it");
        ctx.reply.position = a.position;
        return null;
    },
    "vkExecuteCommandStreamsMESA": function(venus, ctx, a)
    {
        // (run here, inline: a stream that waits makes the whole command wait)
        const streams = a.pStreams || [];
        let index = 0, finished = false, finish = null;
        const end = () => { finished = true; if(finish) finish(); };
        // the streams from `index` on; true when one waits (the rest runs after it)
        const next = () => {
            while(index < streams.length)
            {
                const i = index++, stream = streams[i];
                if(a.pReplyPositions) TRANSPORT["vkSeekReplyCommandStreamMESA"](venus, ctx, { position: a.pReplyPositions[i] });
                const blob = venus.shared_memory(ctx, stream.resourceId);
                if(stream.offset + stream.size > blob.blob_size) throw new Error("vkExecuteCommandStreamsMESA: past the resource");
                const start = blob.map_offset + stream.offset;
                const r = new VenusReader(venus.bytes().slice(start, start + stream.size));
                if(venus.run_inline(ctx, r, () => { if(!next()) end(); })) return true;
            }
            return false;
        };
        if(!next()) return null;
        return done => { if(finished) done(); else finish = done; };
    },
    "vkSubmitVirtqueueSeqnoMESA": function(venus, ctx, a)
    {
        ctx.virtqueue_seqnos.set(a.ring, a.seqno);
        venus.wake_seqno_waits(ctx);
        return null;
    },
    "vkWaitVirtqueueSeqnoMESA": function(venus, ctx, a)
    {
        // (the driver's roundtrip: the seqno arrives with a submission)
        const reached = () => [...ctx.virtqueue_seqnos.values()].some(seqno => seqno >= a.seqno);
        if(reached()) return null;
        return done => {
            const check = () => { if(reached()) done(); else ctx.seqno_waits.push(check); };
            check();
        };
    },
    "vkWaitRingSeqnoMESA": function(venus, ctx, a)
    {
        const key = ring_key(ctx, a.ring), ring = ctx.rings.get(key);
        if(!ring) return null;
        venus.run_ring(ctx, ring);
        const reached = () => !ctx.rings.has(key) || seqno_passed(ring.head, a.seqno);
        if(reached()) return null;
        return done => {
            const check = () => { if(reached()) done(); else ctx.seqno_waits.push(check); };
            check();
        };
    },
};

/**
 * Commands run inside another (vkExecuteCommandStreamsMESA)
 * @param {!VenusContext} ctx
 * @param {!VenusReader} r
 * @param {function()} then when a waiting command is done and the rest has run
 * @return {boolean} whether a command waits (then is called later)
 */
Venus.prototype.run_inline = function(ctx, r, then)
{
    while(r.p < r.end)
    {
        const wait = this.command(ctx, r);
        if(wait)
        {
            wait(() => {
                if(!this.run_inline(ctx, r, then)) then();
            });
            return true;
        }
    }
    return false;
};
                                                                                                                                                                                        source/v64/src/graphics_adapters/virtio_gpu/venus_device_info.js                                    0000644 0000000 0000000 00000062622 00000000000 022365  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the Venus device says it is (venus_vk.js): Vulkan 1.1 on WebGPU's
// guaranteed limits and formats. Each capability is one the WebGPU
// executor backs; docs/gpu-deviations.md lists where Vulkan asks for more.

// VkResult
export const VK_SUCCESS = 0;
export const VK_NOT_READY = 1;
export const VK_TIMEOUT = 2;
export const VK_EVENT_SET = 3;
export const VK_EVENT_RESET = 4;
export const VK_INCOMPLETE = 5;
export const VK_ERROR_OUT_OF_HOST_MEMORY = -1;
export const VK_ERROR_OUT_OF_DEVICE_MEMORY = -2;
export const VK_ERROR_INITIALIZATION_FAILED = -3;
export const VK_ERROR_DEVICE_LOST = -4;
export const VK_ERROR_MEMORY_MAP_FAILED = -5;
export const VK_ERROR_LAYER_NOT_PRESENT = -6;
export const VK_ERROR_EXTENSION_NOT_PRESENT = -7;
export const VK_ERROR_FEATURE_NOT_PRESENT = -8;
export const VK_ERROR_FORMAT_NOT_SUPPORTED = -11;
export const VK_ERROR_INVALID_EXTERNAL_HANDLE = -1000072003;

/** VK_WHOLE_SIZE, VK_REMAINING_*: all ones (2**64 as a number) */
export const WHOLE = 2 ** 64;
export const REMAINING = 0xFFFFFFFF;

/**
 * Fill an output array the way Vulkan's two-call idiom wants: the count
 * when there is no array, else as many as fit, VK_INCOMPLETE when not all
 * @param {!Object} a the command's parameters
 * @param {string} count_name
 * @param {string} array_name
 * @param {!Array} items
 * @param {function(!Object, *)=} fill an output struct from an item
 */
export function out_array(a, count_name, array_name, items, fill)
{
    if(!a[array_name])
    {
        a[count_name] = items.length;
        a.ret = VK_SUCCESS;
        return;
    }
    const n = Math.min(a[count_name] || 0, items.length);
    const out = a[array_name];
    for(let i = 0; i < n; i++)
    {
        if(fill) fill(out[i] || (out[i] = {}), items[i]);
        else out[i] = items[i];
    }
    out.length = n;
    a[count_name] = n;
    a.ret = n < items.length ? VK_INCOMPLETE : VK_SUCCESS;
}

export const VK_API_VERSION = (1 << 22 | 1 << 12 | 0) >>> 0;
export const VK_DRIVER_VERSION = 1;
export const VENDOR_ID = 0x10005;        // VK_VENDOR_ID_MESA
export const DEVICE_ID = 0x5686;
export const DEVICE_NAME = "v86 WebGPU";
const PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU = 3;

// sTypes of the chain structs filled here
export const STYPE = {
    PHYSICAL_DEVICE_FEATURES_2: 1000059000,
    PHYSICAL_DEVICE_PROPERTIES_2: 1000059001,
    VULKAN_1_1_FEATURES: 49,
    VULKAN_1_1_PROPERTIES: 50,
    VULKAN_1_2_FEATURES: 51,
    VULKAN_1_2_PROPERTIES: 52,
    ID_PROPERTIES: 1000071004,
    SUBGROUP_PROPERTIES: 1000094000,
    POINT_CLIPPING_PROPERTIES: 1000117000,
    MULTIVIEW_PROPERTIES: 1000053002,
    PROTECTED_MEMORY_PROPERTIES: 1000145002,
    MAINTENANCE_3_PROPERTIES: 1000168000,
    DRIVER_PROPERTIES: 1000196000,
    TIMELINE_SEMAPHORE_FEATURES: 1000207000,
    TIMELINE_SEMAPHORE_PROPERTIES: 1000207001,
    QUEUE_FAMILY_PROPERTIES_2: 1000059005,
    MEMORY_PROPERTIES_2: 1000059006,
    FORMAT_PROPERTIES_2: 1000059002,
    IMAGE_FORMAT_PROPERTIES_2: 1000059003,
    EXTERNAL_IMAGE_FORMAT_PROPERTIES: 1000071001,
    PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO: 1000071000,
    DRM_FORMAT_MODIFIER_PROPERTIES_LIST: 1000158000,
    DRM_FORMAT_MODIFIER_PROPERTIES_LIST_2: 1000158006,
    PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO: 1000158002,
    IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO: 1000158004,
    SAMPLER_YCBCR_CONVERSION_IMAGE_FORMAT_PROPERTIES: 1000156005,
    SEMAPHORE_TYPE_CREATE_INFO: 1000207002,
    DYNAMIC_RENDERING_FEATURES: 1000044003,
    DEPTH_STENCIL_RESOLVE_PROPERTIES: 1000199000,
    TRANSFORM_FEEDBACK_FEATURES: 1000028000,
    TRANSFORM_FEEDBACK_PROPERTIES: 1000028001,
    PROVOKING_VERTEX_FEATURES: 1000254000,
    PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO: 1000254001,
    PROVOKING_VERTEX_PROPERTIES: 1000254002,
};
/** VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT: two values a query, primitives written and needed */
export const QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM = 1000028004;

const KB = 1024, MB = 1024 * 1024;

/** VkPhysicalDeviceLimits: WebGPU's default limits, Vulkan's minimums where it asks for more */
const LIMITS = {
    maxImageDimension1D: 8192,
    maxImageDimension2D: 8192,
    maxImageDimension3D: 2048,
    maxImageDimensionCube: 8192,
    maxImageArrayLayers: 256,
    maxTexelBufferElements: 65536,
    maxUniformBufferRange: 65536,
    maxStorageBufferRange: 128 * MB,
    maxPushConstantsSize: 128,
    maxMemoryAllocationCount: 4096,
    maxSamplerAllocationCount: 4000,
    bufferImageGranularity: 1,
    sparseAddressSpaceSize: 0,
    maxBoundDescriptorSets: 4,
    maxPerStageDescriptorSamplers: 16,
    // (WebGPU has 12 a stage; VX makes the rest read-only storage buffers,
    // which leaves 8 + 2 of WebGPU's 10: GL ES 3.0 needs 12 besides ANGLE's own)
    maxPerStageDescriptorUniformBuffers: 14,
    maxPerStageDescriptorStorageBuffers: 8,
    maxPerStageDescriptorSampledImages: 16,
    maxPerStageDescriptorStorageImages: 4,
    maxPerStageDescriptorInputAttachments: 4,
    maxPerStageResources: 128,
    maxDescriptorSetSamplers: 96,
    maxDescriptorSetUniformBuffers: 72,
    maxDescriptorSetUniformBuffersDynamic: 8,
    maxDescriptorSetStorageBuffers: 24,
    maxDescriptorSetStorageBuffersDynamic: 4,
    maxDescriptorSetSampledImages: 96,
    maxDescriptorSetStorageImages: 24,
    maxDescriptorSetInputAttachments: 4,
    maxVertexInputAttributes: 16,
    maxVertexInputBindings: 16,
    maxVertexInputAttributeOffset: 2047,
    maxVertexInputBindingStride: 2048,
    // (17 of WebGPU's inter-stage variables, one past its default: ANGLE keeps
    // 4 components for capturing gl_Position, GL ES 3.0 needs 64 besides)
    maxVertexOutputComponents: 68,
    maxTessellationGenerationLevel: 0,
    maxTessellationPatchSize: 0,
    maxTessellationControlPerVertexInputComponents: 0,
    maxTessellationControlPerVertexOutputComponents: 0,
    maxTessellationControlPerPatchOutputComponents: 0,
    maxTessellationControlTotalOutputComponents: 0,
    maxTessellationEvaluationInputComponents: 0,
    maxTessellationEvaluationOutputComponents: 0,
    maxGeometryShaderInvocations: 0,
    maxGeometryInputComponents: 0,
    maxGeometryOutputComponents: 0,
    maxGeometryOutputVertices: 0,
    maxGeometryTotalOutputComponents: 0,
    maxFragmentInputComponents: 68,
    maxFragmentOutputAttachments: 8,
    maxFragmentDualSrcAttachments: 0,
    maxFragmentCombinedOutputResources: 16,
    maxComputeSharedMemorySize: 16 * KB,
    maxComputeWorkGroupCount: [65535, 65535, 65535],
    maxComputeWorkGroupInvocations: 256,
    maxComputeWorkGroupSize: [256, 256, 64],
    subPixelPrecisionBits: 8,
    subTexelPrecisionBits: 8,
    mipmapPrecisionBits: 8,
    maxDrawIndexedIndexValue: 0xFFFFFFFF,
    maxDrawIndirectCount: 1 << 30,
    maxSamplerLodBias: 2,
    maxSamplerAnisotropy: 16,
    maxViewports: 1,
    maxViewportDimensions: [8192, 8192],
    viewportBoundsRange: [-16384, 16383],
    viewportSubPixelBits: 0,
    minMemoryMapAlignment: 64,
    minTexelBufferOffsetAlignment: 256,
    minUniformBufferOffsetAlignment: 256,
    minStorageBufferOffsetAlignment: 256,
    minTexelOffset: -8,
    maxTexelOffset: 7,
    minTexelGatherOffset: -8,
    maxTexelGatherOffset: 7,
    minInterpolationOffset: -0.5,
    maxInterpolationOffset: 0.4375,
    subPixelInterpolationOffsetBits: 4,
    maxFramebufferWidth: 8192,
    maxFramebufferHeight: 8192,
    maxFramebufferLayers: 256,
    // (1 and 4 samples: WebGPU's)
    framebufferColorSampleCounts: 5,
    framebufferDepthSampleCounts: 5,
    framebufferStencilSampleCounts: 5,
    framebufferNoAttachmentsSampleCounts: 5,
    maxColorAttachments: 8,
    sampledImageColorSampleCounts: 5,
    sampledImageIntegerSampleCounts: 1,
    sampledImageDepthSampleCounts: 5,
    sampledImageStencilSampleCounts: 5,
    storageImageSampleCounts: 1,
    maxSampleMaskWords: 1,
    timestampComputeAndGraphics: 0,
    timestampPeriod: 1,
    maxClipDistances: 0,
    maxCullDistances: 0,
    maxCombinedClipAndCullDistances: 0,
    discreteQueuePriorities: 2,
    pointSizeRange: [1, 1],
    lineWidthRange: [1, 1],
    pointSizeGranularity: 0,
    lineWidthGranularity: 0,
    strictLines: 0,
    // (1 and 4 samples: WebGPU's four are Vulkan's standard positions)
    standardSampleLocations: 1,
    optimalBufferCopyOffsetAlignment: 4,
    optimalBufferCopyRowPitchAlignment: 256,
    nonCoherentAtomSize: 64,
};

/** @return {!Object} VkPhysicalDeviceProperties */
export function properties()
{
    return {
        apiVersion: VK_API_VERSION,
        driverVersion: VK_DRIVER_VERSION,
        vendorID: VENDOR_ID,
        deviceID: DEVICE_ID,
        deviceType: PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU,
        deviceName: DEVICE_NAME,
        pipelineCacheUUID: PIPELINE_CACHE_UUID,
        limits: LIMITS,
        sparseProperties: {},
    };
}

const PIPELINE_CACHE_UUID = [0x76, 0x38, 0x36, 0x2d, 0x76, 0x65, 0x6e, 0x75, 0x73, 0x2d, 0x77, 0x67, 0x70, 0x75, 0x00, 0x01];
const DEVICE_UUID = [0x76, 0x38, 0x36, 0x2d, 0x77, 0x65, 0x62, 0x67, 0x70, 0x75, 0x2d, 0x64, 0x65, 0x76, 0x00, 0x01];
const DRIVER_UUID = [0x76, 0x38, 0x36, 0x2d, 0x77, 0x65, 0x62, 0x67, 0x70, 0x75, 0x2d, 0x64, 0x72, 0x76, 0x00, 0x01];

/** VkPhysicalDeviceFeatures: what the executor does */
const FEATURES = {
    robustBufferAccess: 1,
    fullDrawIndexUint32: 1,
    imageCubeArray: 1,
    independentBlend: 1,
    multiDrawIndirect: 1,
    depthBiasClamp: 1,
    samplerAnisotropy: 1,
    fragmentStoresAndAtomics: 1,
    // (not occlusionQueryPrecise: WebGPU promises only zero or not, and
    // Chrome's Metal backend answers 1)
};

// VK_SUBGROUP_FEATURE_BASIC_BIT, VK_SHADER_STAGE_COMPUTE_BIT
const SUBGROUP = { subgroupSize: 1, subgroupSupportedStages: 0x20, subgroupSupportedOperations: 1, subgroupQuadOperationsInAllStages: 0 };

const VULKAN_1_1_PROPERTIES = {
    deviceUUID: DEVICE_UUID, driverUUID: DRIVER_UUID, deviceLUID: [0, 0, 0, 0, 0, 0, 0, 0], deviceNodeMask: 0, deviceLUIDValid: 0,
    ...SUBGROUP,
    pointClippingBehavior: 0,
    maxMultiviewViewCount: 6, maxMultiviewInstanceIndex: (1 << 27) - 1,
    protectedNoFault: 0,
    maxPerSetDescriptors: 1024, maxMemoryAllocationSize: 1024 * MB,
};

/** Properties of chain structs, by sType */
const CHAIN_PROPERTIES = {
    // (VK_RESOLVE_MODE_SAMPLE_ZERO_BIT, as required: WebGPU resolves no depth, see the deviations)
    [STYPE.DEPTH_STENCIL_RESOLVE_PROPERTIES]: { supportedDepthResolveModes: 1, supportedStencilResolveModes: 1, independentResolveNone: 0, independentResolve: 0 },
    [STYPE.VULKAN_1_1_PROPERTIES]: VULKAN_1_1_PROPERTIES,
    [STYPE.ID_PROPERTIES]: { deviceUUID: DEVICE_UUID, driverUUID: DRIVER_UUID, deviceLUID: [0, 0, 0, 0, 0, 0, 0, 0], deviceNodeMask: 0, deviceLUIDValid: 0 },
    [STYPE.SUBGROUP_PROPERTIES]: { subgroupSize: SUBGROUP.subgroupSize, supportedStages: SUBGROUP.subgroupSupportedStages,
        supportedOperations: SUBGROUP.subgroupSupportedOperations, quadOperationsInAllStages: 0 },
    [STYPE.POINT_CLIPPING_PROPERTIES]: { pointClippingBehavior: 0 },
    [STYPE.MULTIVIEW_PROPERTIES]: { maxMultiviewViewCount: 6, maxMultiviewInstanceIndex: (1 << 27) - 1 },
    [STYPE.PROTECTED_MEMORY_PROPERTIES]: { protectedNoFault: 0 },
    [STYPE.MAINTENANCE_3_PROPERTIES]: { maxPerSetDescriptors: 1024, maxMemoryAllocationSize: 1024 * MB },
    // VK_DRIVER_ID_MESA_VENUS is the guest's; this is the renderer's
    [STYPE.TIMELINE_SEMAPHORE_PROPERTIES]: { maxTimelineSemaphoreValueDifference: 0xFFFFFFFF },
    [STYPE.DRIVER_PROPERTIES]: { driverID: 0, driverName: "v86 WebGPU", driverInfo: "WebGPU through the v86 renderer",
        conformanceVersion: { major: 0, minor: 0, subminor: 0, patch: 0 } },
    // (VX captures in a compute pass: one stream, 4 buffers, GL ES's interleaved 64 components and more)
    [STYPE.TRANSFORM_FEEDBACK_PROPERTIES]: { maxTransformFeedbackStreams: 1, maxTransformFeedbackBuffers: 4,
        maxTransformFeedbackBufferSize: 1024 * MB, maxTransformFeedbackStreamDataSize: 512, maxTransformFeedbackBufferDataSize: 512,
        maxTransformFeedbackBufferDataStride: 512, transformFeedbackQueries: 1, transformFeedbackStreamsLinesTriangles: 0,
        transformFeedbackRasterizationStreamSelect: 0, transformFeedbackDraw: 0 },
    // (VX draws a pipeline of the last vertex with flat varyings reordered, the last first)
    [STYPE.PROVOKING_VERTEX_PROPERTIES]: { provokingVertexModePerPipeline: 1, transformFeedbackPreservesTriangleFanProvokingVertex: 0 },
};

/** Features of chain structs, by sType (absent: all false) */
const CHAIN_FEATURES = {
    [STYPE.TIMELINE_SEMAPHORE_FEATURES]: { timelineSemaphore: 1 },
    [STYPE.DYNAMIC_RENDERING_FEATURES]: { dynamicRendering: 1 },
    [STYPE.TRANSFORM_FEEDBACK_FEATURES]: { transformFeedback: 1, geometryStreams: 0 },
    [STYPE.PROVOKING_VERTEX_FEATURES]: { provokingVertexLast: 1, transformFeedbackPreservesProvokingVertex: 0 },
};

/**
 * Fill what a request's chain asks for
 * @param {Object} chain
 * @param {!Object} table by sType
 */
function fill_chain(chain, table)
{
    for(let s = chain; s; s = s.pNext)
    {
        const values = table[s.sType];
        if(values) Object.assign(s, values);
    }
}

/** @param {!Object} out VkPhysicalDeviceFeatures2 (its chain) */
export function features2(out)
{
    out.features = FEATURES;
    fill_chain(out.pNext, CHAIN_FEATURES);
}

/** @param {!Object} out VkPhysicalDeviceProperties2 (its chain) */
export function properties2(out)
{
    out.properties = properties();
    fill_chain(out.pNext, CHAIN_PROPERTIES);
}

export function features()
{
    return FEATURES;
}

// ---------------------------------------------------------------------------
// Queues and memory

// VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT
export const QUEUE_FAMILIES = [
    // (timestamps: the time the device makes the batch, in ns)
    { queueFlags: 7, queueCount: 1, timestampValidBits: 64, minImageTransferGranularity: { width: 1, height: 1, depth: 1 } },
];

const DEVICE_LOCAL = 1, HOST_VISIBLE = 2, HOST_COHERENT = 4, HOST_CACHED = 8;
export const MEMORY_DEVICE_LOCAL = 0, MEMORY_HOST = 1, MEMORY_HOST_CACHED = 2;

/**
 * Device memory is GPU buffers; host visible memory is also mapped into
 * the guest from the host visible memory region (BAR4) while it is mapped
 * @param {number} host_visible_size bytes of the host visible region for memory
 */
export function memory_properties(host_visible_size)
{
    return {
        memoryTypeCount: 3,
        memoryTypes: [
            { propertyFlags: DEVICE_LOCAL, heapIndex: 0 },
            { propertyFlags: HOST_VISIBLE | HOST_COHERENT, heapIndex: 1 },
            { propertyFlags: HOST_VISIBLE | HOST_COHERENT | HOST_CACHED, heapIndex: 1 },
        ],
        memoryHeapCount: 2,
        memoryHeaps: [
            // VK_MEMORY_HEAP_DEVICE_LOCAL_BIT
            { size: 1024 * MB, flags: 1 },
            { size: host_visible_size, flags: 0 },
        ],
    };
}

// ---------------------------------------------------------------------------
// Formats

// VkFormatFeatureFlagBits
const F = {
    SAMPLED: 0x1, STORAGE: 0x2, UNIFORM_TEXEL: 0x8, STORAGE_TEXEL: 0x10, VERTEX: 0x40, COLOR: 0x80, BLEND: 0x100,
    DEPTH: 0x200, BLIT_SRC: 0x400, BLIT_DST: 0x800, LINEAR: 0x1000, TRANSFER_SRC: 0x4000, TRANSFER_DST: 0x8000,
};

/**
 * VkFormat: [WebGPU texture format or null, capabilities, WebGPU vertex
 * format or null, texel block bytes]. Capabilities: f filterable float,
 * x unfilterable float, i integer, r renderable, b blendable, m 4x
 * multisampled, s storage, d depth/stencil, c copies through buffers, p
 * 16-bit packed texels stored as the texture format's (VX converts them in
 * copies through buffers)
 */
export const FORMATS = {
    // (Vulkan's required color attachment formats, and GL ES 3.0's RGB565
    // and RGB5_A1, which ANGLE gives no other format)
    4: ["rgba8unorm", "frbmcp", null, 2],              // R5G6B5_UNORM_PACK16
    6: ["rgba8unorm", "frbmcp", null, 2],              // R5G5B5A1_UNORM_PACK16
    8: ["rgba8unorm", "frbmcp", null, 2],              // A1R5G5B5_UNORM_PACK16
    9: ["r8unorm", "frbmc", "unorm8", 1],              // R8_UNORM
    10: ["r8snorm", "fc", "snorm8", 1],                // R8_SNORM
    13: ["r8uint", "irmc", "uint8", 1],                // R8_UINT
    14: ["r8sint", "irmc", "sint8", 1],                // R8_SINT
    16: ["rg8unorm", "frbmc", "unorm8x2", 2],          // R8G8_UNORM
    17: ["rg8snorm", "fc", "snorm8x2", 2],             // R8G8_SNORM
    20: ["rg8uint", "irmc", "uint8x2", 2],             // R8G8_UINT
    21: ["rg8sint", "irmc", "sint8x2", 2],             // R8G8_SINT
    37: ["rgba8unorm", "frbmsc", "unorm8x4", 4],       // R8G8B8A8_UNORM
    38: ["rgba8snorm", "fsc", "snorm8x4", 4],          // R8G8B8A8_SNORM
    41: ["rgba8uint", "irmsc", "uint8x4", 4],          // R8G8B8A8_UINT
    42: ["rgba8sint", "irmsc", "sint8x4", 4],          // R8G8B8A8_SINT
    43: ["rgba8unorm-srgb", "frbmc", null, 4],         // R8G8B8A8_SRGB
    44: ["bgra8unorm", "frbmc", "unorm8x4-bgra", 4],   // B8G8R8A8_UNORM
    50: ["bgra8unorm-srgb", "frbmc", null, 4],         // B8G8R8A8_SRGB
    51: ["rgba8unorm", "frbmsc", "unorm8x4", 4],       // A8B8G8R8_UNORM_PACK32
    52: ["rgba8snorm", "fsc", "snorm8x4", 4],          // A8B8G8R8_SNORM_PACK32
    55: ["rgba8uint", "irmsc", "uint8x4", 4],          // A8B8G8R8_UINT_PACK32
    56: ["rgba8sint", "irmsc", "sint8x4", 4],          // A8B8G8R8_SINT_PACK32
    57: ["rgba8unorm-srgb", "frbmc", null, 4],         // A8B8G8R8_SRGB_PACK32
    64: ["rgb10a2unorm", "frbmc", "unorm10-10-10-2", 4], // A2B10G10R10_UNORM_PACK32
    68: ["rgb10a2uint", "irmc", null, 4],              // A2B10G10R10_UINT_PACK32
    70: [null, "", "unorm16", 2],                      // R16_UNORM
    71: [null, "", "snorm16", 2],                      // R16_SNORM
    74: ["r16uint", "irmc", "uint16", 2],              // R16_UINT
    75: ["r16sint", "irmc", "sint16", 2],              // R16_SINT
    76: ["r16float", "frbmc", "float16", 2],           // R16_SFLOAT
    77: [null, "", "unorm16x2", 4],                    // R16G16_UNORM
    78: [null, "", "snorm16x2", 4],                    // R16G16_SNORM
    81: ["rg16uint", "irmc", "uint16x2", 4],           // R16G16_UINT
    82: ["rg16sint", "irmc", "sint16x2", 4],           // R16G16_SINT
    83: ["rg16float", "frbmc", "float16x2", 4],        // R16G16_SFLOAT
    91: [null, "", "unorm16x4", 8],                    // R16G16B16A16_UNORM
    92: [null, "", "snorm16x4", 8],                    // R16G16B16A16_SNORM
    95: ["rgba16uint", "irmsc", "uint16x4", 8],        // R16G16B16A16_UINT
    96: ["rgba16sint", "irmsc", "sint16x4", 8],        // R16G16B16A16_SINT
    97: ["rgba16float", "frbmsc", "float16x4", 8],     // R16G16B16A16_SFLOAT
    98: ["r32uint", "irmsc", "uint32", 4],             // R32_UINT
    99: ["r32sint", "irmsc", "sint32", 4],             // R32_SINT
    100: ["r32float", "xrmsc", "float32", 4],          // R32_SFLOAT
    101: ["rg32uint", "irsc", "uint32x2", 8],          // R32G32_UINT
    102: ["rg32sint", "irsc", "sint32x2", 8],          // R32G32_SINT
    103: ["rg32float", "xrsc", "float32x2", 8],        // R32G32_SFLOAT
    104: [null, "", "uint32x3", 12],                   // R32G32B32_UINT
    105: [null, "", "sint32x3", 12],                   // R32G32B32_SINT
    106: [null, "", "float32x3", 12],                  // R32G32B32_SFLOAT
    107: ["rgba32uint", "irsc", "uint32x4", 16],       // R32G32B32A32_UINT
    108: ["rgba32sint", "irsc", "sint32x4", 16],       // R32G32B32A32_SINT
    109: ["rgba32float", "xrsc", "float32x4", 16],     // R32G32B32A32_SFLOAT
    122: ["rg11b10ufloat", "fc", null, 4],             // B10G11R11_UFLOAT_PACK32
    123: ["rgb9e5ufloat", "fc", null, 4],              // E5B9G9R9_UFLOAT_PACK32
    124: ["depth16unorm", "dmc", null, 2],             // D16_UNORM
    // (24-bit depth: WebGPU copies none to or from a buffer; VX does it by a
    // draw and a dispatch, as depth into depth32float)
    125: ["depth24plus", "dmc", null, 4],              // X8_D24_UNORM_PACK32
    126: ["depth32float", "dmc", null, 4],             // D32_SFLOAT
    127: ["stencil8", "dmc", null, 1],                 // S8_UINT
    129: ["depth24plus-stencil8", "dmc", null, 4],     // D24_UNORM_S8_UINT
    // (GL ES 3.0's DEPTH32F_STENCIL8: WebGPU's optional depth32float-stencil8,
    // which VX makes depth24plus-stencil8 on a device without it)
    130: ["depth32float-stencil8", "dmc", null, 8],    // D32_SFLOAT_S8_UINT
};

/**
 * VkFormatProperties of a format
 * @param {number} format
 * @return {{linearTilingFeatures: number, optimalTilingFeatures: number, bufferFeatures: number}}
 */
export function format_properties(format)
{
    const entry = FORMATS[format];
    if(!entry) return { linearTilingFeatures: 0, optimalTilingFeatures: 0, bufferFeatures: 0 };
    const [texture, caps, vertex] = entry;
    let optimal = 0;
    if(texture)
    {
        optimal |= F.SAMPLED | F.BLIT_SRC;
        if(caps.includes("f")) optimal |= F.LINEAR;
        if(caps.includes("r")) optimal |= F.COLOR | F.BLIT_DST;
        if(caps.includes("b")) optimal |= F.BLEND;
        if(caps.includes("s")) optimal |= F.STORAGE;
        if(caps.includes("d")) optimal = F.SAMPLED | F.DEPTH | F.BLIT_SRC;
        if(caps.includes("c")) optimal |= F.TRANSFER_SRC | F.TRANSFER_DST;
    }
    return { linearTilingFeatures: 0, optimalTilingFeatures: optimal, bufferFeatures: vertex ? F.VERTEX : 0 };
}

// VkImageUsageFlagBits -> the format features they need
const USAGE_FEATURES = [
    [0x1, F.TRANSFER_SRC],      // TRANSFER_SRC
    [0x2, F.TRANSFER_DST],      // TRANSFER_DST
    [0x4, F.SAMPLED],           // SAMPLED
    [0x8, F.STORAGE],           // STORAGE
    [0x10, F.COLOR],            // COLOR_ATTACHMENT
    [0x20, F.DEPTH],            // DEPTH_STENCIL_ATTACHMENT
    [0x80, F.COLOR | F.DEPTH],  // INPUT_ATTACHMENT: one of them
];

/**
 * VkImageFormatProperties, or null when the combination is not supported
 * @param {number} format
 * @param {number} type VkImageType
 * @param {number} tiling VkImageTiling
 * @param {number} usage
 * @param {number} flags VkImageCreateFlags
 */
export function image_format_properties(format, type, tiling, usage, flags)
{
    const entry = FORMATS[format];
    // (optimal tiling, and the linear modifier's: an image is a texture either way)
    if(!entry || !entry[0] || tiling !== 0 && tiling !== TILING_DRM_FORMAT_MODIFIER) return null;
    const features = format_properties(format).optimalTilingFeatures;
    for(const [bit, need] of USAGE_FEATURES)
    {
        if(usage & bit && !(features & need)) return null;
    }
    // VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT and the others need nothing more
    const depth = entry[1].includes("d");
    if(type === 2 && depth) return null;
    // mutable format, cube and 2D array compatible, block texel view
    // compatible, extended usage, alias (swapchain images have it: their
    // memory is theirs alone here); sparse, protected and the like are not
    // offered
    if(flags & ~(0x8 | 0x10 | 0x20 | 0x80 | 0x100 | 0x400)) return null;
    const max = type === 0 ? [8192, 1, 1] : type === 1 ? [8192, 8192, 1] : [2048, 2048, 2048];
    const levels = Math.floor(Math.log2(Math.max(...max))) + 1;
    const multisample = type === 1 && entry[1].includes("m") && !(flags & 0x10) && !(usage & 0x8);
    return {
        maxExtent: { width: max[0], height: max[1], depth: max[2] },
        maxMipLevels: levels,
        maxArrayLayers: type === 2 ? 1 : 256,
        sampleCounts: multisample ? 5 : 1,
        maxResourceSize: 2 * 1024 * MB,
    };
}

/** Device extensions, name: spec version (each one the executor backs) */
export const DEVICE_EXTENSIONS = {
    "VK_KHR_driver_properties": 1,
    // (the device keeps the values; one queue runs in order)
    "VK_KHR_timeline_semaphore": 2,
    // sync files: the driver makes them itself (a SUBMIT_3D on the queue's
    // timeline) and tells the device what they mean for the semaphore or
    // fence (vkImportSemaphoreResourceMESA and friends); Venus offers
    // VK_KHR_swapchain only when semaphores import them
    "VK_KHR_external_semaphore_fd": 1,
    "VK_KHR_external_fence_fd": 1,
    // render passes without render pass objects (and what it needs)
    "VK_KHR_create_renderpass2": 1,
    "VK_KHR_depth_stencil_resolve": 1,
    "VK_KHR_dynamic_rendering": 1,
    // gralloc's buffers on Android (P11.4 of docs/arm64-virt-android16-plan.md):
    // the driver imports a dma-buf as its virtio-gpu resource
    // (VkImportMemoryResourceInfoMESA), whose GX surface the image then is;
    // one modifier, linear (images are textures here, with no layout of
    // their own); the foreign queue family is the CPU and the display.
    // Not VK_EXT_external_memory_dma_buf (nor VK_KHR_external_memory_fd):
    // nothing here becomes a dma-buf, and Mesa's venus on Linux takes it for
    // dma-buf swapchain images (its software WSI only without it); the
    // Android driver (tools/a64_venus/venus-android.patch) imports without it
    "VK_KHR_image_format_list": 1,
    "VK_EXT_image_drm_format_modifier": 2,
    "VK_EXT_queue_family_foreign": 1,
    // (captured in a compute pass, VX: what GL ES 3.0 needs, so that ANGLE gives it)
    "VK_EXT_transform_feedback": 1,
    // (GL's last vertex for flat shading, which ANGLE takes from it: VX reorders
    // the vertices of draws with flat varyings, G-51 of docs/gpu-deviations.md)
    "VK_EXT_provoking_vertex": 1,
};

// VkExternalMemoryHandleTypeFlagBits, VkExternalMemoryFeatureFlagBits
export const MEMORY_HANDLE_DMA_BUF = 0x200;
export const MEMORY_DEDICATED_ONLY = 1, MEMORY_IMPORTABLE = 4;
/** VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, and the one modifier offered */
export const TILING_DRM_FORMAT_MODIFIER = 1000158000;
export const DRM_FORMAT_MOD_LINEAR = 0;

// VkExternalSemaphoreHandleTypeFlagBits, VkExternalFenceHandleTypeFlagBits
export const SEMAPHORE_SYNC_FD = 0x10;
export const FENCE_SYNC_FD = 0x8;
                                                                                                              source/v64/src/graphics_adapters/virtio_gpu/venus_protocol.js                                       0000644 0000000 0000000 00001513703 00000000000 021756  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/venus_protocol_gen.mjs from Mesa's venus-protocol
// (src/virtio/venus-protocol, Mesa 26.1.6); do not edit.
//
// The Venus wire format: d_* read a request the guest's driver encoded, into
// objects with the C names (structs) or an object of the parameters
// (commands); e_* write a reply the driver decodes, from such objects (what
// is missing is written as zeros, an empty array or a null pointer).

/* eslint-disable */

// (tools/venus_protocol_runtime.js, copied into venus_protocol.js)
//
// Venus's encoding: little endian, everything a multiple of 4 bytes; 64-bit
// values (sizes, handles, VkDeviceSize, 64-bit flags) are numbers here, exact
// below 2**53, except a ring's id (ring_id); arrays, strings and pointers
// start with a 64-bit count (1 or 0 for a pointer to one value).

const MAX_COUNT = 1 << 24;

/**
 * Reads a command stream
 * @constructor
 * @param {!Uint8Array} bytes
 * @param {number=} start
 * @param {number=} end
 */
export function VenusReader(bytes, start, end)
{
    this.bytes = bytes;
    this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    this.p = start || 0;
    this.end = end === undefined ? bytes.length : end;
}

/** @param {number} n */
VenusReader.prototype.take = function(n)
{
    const at = this.p;
    if(at + n > this.end) throw new Error("venus: read past the end of the stream");
    this.p = at + n;
    return at;
};

VenusReader.prototype.u32 = function() { return this.view.getUint32(this.take(4), true); };
VenusReader.prototype.i32 = function() { return this.view.getInt32(this.take(4), true); };
VenusReader.prototype.u8 = function() { return this.view.getUint8(this.take(4)); };
VenusReader.prototype.u16 = function() { return this.view.getUint16(this.take(4), true); };
VenusReader.prototype.i16 = function() { return this.view.getInt16(this.take(4), true); };
VenusReader.prototype.f32 = function() { return this.view.getFloat32(this.take(4), true); };
VenusReader.prototype.f64 = function() { return this.view.getFloat64(this.take(8), true); };
VenusReader.prototype.u64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getUint32(at + 4, true) * 0x100000000;
};
VenusReader.prototype.i64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getInt32(at + 4, true) * 0x100000000;
};
/** a handle: the object id the driver gave it */
VenusReader.prototype.h = VenusReader.prototype.u64;
/**
 * A ring's id (the `ring` of the transport commands): the driver's pointer
 * to its ring, which a number would round to a multiple of 2048 (Android's
 * heap pointers have a tag in their top byte), so that the rings of two
 * threads could have the same id: 16 hex digits
 * @return {string}
 */
VenusReader.prototype.ring_id = function()
{
    const at = this.take(8);
    return this.view.getUint32(at + 4, true).toString(16).padStart(8, "0") + this.view.getUint32(at, true).toString(16).padStart(8, "0");
};

/** an array's size */
VenusReader.prototype.size = function()
{
    const n = this.u64();
    if(n > MAX_COUNT) throw new Error("venus: array of " + n);
    return n;
};

/** @param {number} n bytes */
VenusReader.prototype.blob = function(n)
{
    const at = this.take(n + 3 & ~3);
    return this.bytes.slice(at, at + n);
};

/** @param {number} n bytes, with the terminating NUL */
VenusReader.prototype.str = function(n)
{
    const at = this.take(n + 3 & ~3);
    let s = "";
    for(let i = at; i < at + n && this.bytes[i]; i++) s += String.fromCharCode(this.bytes[i]);
    return s;
};

/**
 * @param {Function} type
 * @param {number} size of an element
 * @param {number} n
 */
VenusReader.prototype.typed = function(type, size, n)
{
    const at = this.take(n * size + 3 & ~3);
    const out = new type(n);
    new Uint8Array(out.buffer).set(this.bytes.subarray(at, at + n * size));
    return out;
};
VenusReader.prototype.u32s = function(n) { return this.typed(Uint32Array, 4, n); };
VenusReader.prototype.i32s = function(n) { return this.typed(Int32Array, 4, n); };
VenusReader.prototype.f32s = function(n) { return this.typed(Float32Array, 4, n); };
VenusReader.prototype.u8s = function(n) { return this.typed(Uint8Array, 1, n); };
VenusReader.prototype.u64s = function(n)
{
    const out = new Array(n);
    for(let i = 0; i < n; i++) out[i] = this.u64();
    return out;
};

/**
 * A pNext chain, as objects linked by pNext
 * @param {!Object<number, function(!VenusReader, !Object)>} table
 * @return {Object}
 */
VenusReader.prototype.pnext = function(table)
{
    if(!this.u64()) return null;
    const stype = this.u32();
    const next = this.pnext(table);
    const self = table[stype];
    if(!self) throw new Error("venus: struct " + stype + " in a chain");
    const o = { sType: stype, pNext: next };
    self(this, o);
    return o;
};

/**
 * Writes a reply
 * @constructor
 * @param {number=} size to start with
 */
export function VenusWriter(size)
{
    this.bytes = new Uint8Array(size || 256);
    this.view = new DataView(this.bytes.buffer);
    this.p = 0;
}

/** @param {number} n */
VenusWriter.prototype.room = function(n)
{
    const at = this.p;
    if(at + n > this.bytes.length)
    {
        const bigger = new Uint8Array(Math.max(this.bytes.length * 2, at + n));
        bigger.set(this.bytes);
        this.bytes = bigger;
        this.view = new DataView(bigger.buffer);
    }
    this.p = at + n;
    return at;
};

/** @return {!Uint8Array} what was written */
VenusWriter.prototype.result = function() { return this.bytes.subarray(0, this.p); };

VenusWriter.prototype.u32 = function(v) { const at = this.room(4); this.view.setUint32(at, v >>> 0, true); };
VenusWriter.prototype.i32 = function(v) { const at = this.room(4); this.view.setInt32(at, v | 0, true); };
VenusWriter.prototype.u8 = function(v) { const at = this.room(4); this.view.setUint32(at, v & 0xFF, true); };
VenusWriter.prototype.u16 = function(v) { const at = this.room(4); this.view.setUint32(at, v & 0xFFFF, true); };
VenusWriter.prototype.i16 = function(v) { const at = this.room(4); this.view.setInt32(at, v << 16 >> 16, true); };
VenusWriter.prototype.f32 = function(v) { const at = this.room(4); this.view.setFloat32(at, v || 0, true); };
VenusWriter.prototype.f64 = function(v) { const at = this.room(8); this.view.setFloat64(at, v || 0, true); };
VenusWriter.prototype.u64 = function(v)
{
    const at = this.room(8);
    v = v || 0;
    // (~0ULL, VK_WHOLE_SIZE: 2**64 as a number)
    if(v >= 2 ** 64)
    {
        this.view.setUint32(at, 0xFFFFFFFF, true);
        this.view.setUint32(at + 4, 0xFFFFFFFF, true);
        return;
    }
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setUint32(at + 4, high, true);
};
VenusWriter.prototype.i64 = function(v)
{
    v = v || 0;
    if(v >= 0) return this.u64(v);
    const at = this.room(8);
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setInt32(at + 4, high, true);
};
VenusWriter.prototype.h = VenusWriter.prototype.u64;
VenusWriter.prototype.size = VenusWriter.prototype.u64;
/** @param {(string|number)} v a ring's id: VenusReader.ring_id's 16 hex digits, or a number below 2**53 */
VenusWriter.prototype.ring_id = function(v)
{
    if(typeof v !== "string") return this.u64(v);
    const at = this.room(8);
    this.view.setUint32(at, parseInt(v.slice(-8), 16) >>> 0, true);
    this.view.setUint32(at + 4, parseInt(v.slice(0, -8) || "0", 16) >>> 0, true);
};

/**
 * @param {Uint8Array|undefined} data
 * @param {number} n bytes
 */
VenusWriter.prototype.blob = function(data, n)
{
    const at = this.room(n + 3 & ~3);
    this.bytes.fill(0, at, at + (n + 3 & ~3));
    if(data) this.bytes.set(data.length > n ? data.subarray(0, n) : data, at);
};

/**
 * A string in n bytes (a fixed array: the rest zeros)
 * @param {string|undefined} s
 * @param {number} n
 */
VenusWriter.prototype.str = function(s, n)
{
    const at = this.room(n + 3 & ~3);
    this.bytes.fill(0, at, at + (n + 3 & ~3));
    s = s || "";
    for(let i = 0; i < s.length && i < n - 1; i++) this.bytes[at + i] = s.charCodeAt(i);
};

VenusWriter.prototype.u32s = function(a, n) { for(let i = 0; i < n; i++) this.u32(a ? a[i] : 0); };
VenusWriter.prototype.i32s = function(a, n) { for(let i = 0; i < n; i++) this.i32(a ? a[i] : 0); };
VenusWriter.prototype.f32s = function(a, n) { for(let i = 0; i < n; i++) this.f32(a ? a[i] : 0); };
VenusWriter.prototype.u64s = function(a, n) { for(let i = 0; i < n; i++) this.u64(a ? a[i] : 0); };
VenusWriter.prototype.u8s = function(a, n) { this.blob(a, n); };

/**
 * A pNext chain: the structs the request's chain had, in its order (the
 * driver looks for each further along its own chain); those this cannot
 * write are left out
 * @param {Object} o
 * @param {!Object<number, function(!VenusWriter, !Object)>} table
 */
VenusWriter.prototype.pnext = function(o, table)
{
    while(o && !table[o.sType]) o = o.pNext;
    if(!o) return this.u64(0);
    this.u64(1);
    this.u32(o.sType);
    this.pnext(o.pNext, table);
    table[o.sType](this, o);
};

/** the next array size, not taken */
VenusReader.prototype.peek_size = function()
{
    const p = this.p;
    const n = this.u64();
    this.p = p;
    return n;
};

/** @const {!Object<number, function(!VenusReader, !Object)>} chain structs of requests, by sType */
const PNEXT = {1000470006: d_VkBufferUsageFlags2CreateInfo_self, 1000072000: d_VkExternalMemoryBufferCreateInfo_self, 1000257002: d_VkBufferOpaqueCaptureAddressCreateInfo_self, 1000244002: d_VkBufferDeviceAddressCreateInfoEXT_self, 1000060013: d_VkBindBufferMemoryDeviceGroupInfo_self, 1000545002: d_VkBindMemoryStatus_self, 1000081000: d_VkCommandBufferInheritanceConditionalRenderingInfoEXT_self, 1000044004: d_VkCommandBufferInheritanceRenderingInfo_self, 1000232001: d_VkRenderingAttachmentLocationInfo_self, 1000232002: d_VkRenderingInputAttachmentIndexInfo_self, 1000135010: d_VkCommandBufferInheritanceDescriptorHeapInfoEXT_self, 1000060004: d_VkDeviceGroupCommandBufferBeginInfo_self, 1000453000: d_VkExternalMemoryAcquireUnmodifiedEXT_self, 1000143000: d_VkSampleLocationsInfoEXT_self, 1000060003: d_VkDeviceGroupRenderPassBeginInfo_self, 1000143001: d_VkRenderPassSampleLocationsBeginInfoEXT_self, 1000108003: d_VkRenderPassAttachmentBeginInfo_self, 1000376002: d_VkMultisampledRenderToSingleSampledInfoEXT_self, 1000044006: d_VkRenderingFragmentShadingRateAttachmentInfoKHR_self, 1000283002: d_VkDepthBiasRepresentationInfoEXT_self, 30: d_VkPipelineLayoutCreateInfo_self, 1000138003: d_VkDescriptorPoolInlineUniformBlockCreateInfo_self, 1000351002: d_VkMutableDescriptorTypeCreateInfoEXT_self, 1000161003: d_VkDescriptorSetVariableDescriptorCountAllocateInfo_self, 1000161000: d_VkDescriptorSetLayoutBindingFlagsCreateInfo_self, 1000174000: d_VkDeviceQueueGlobalPriorityCreateInfo_self, 1000295000: d_VkPhysicalDevicePrivateDataFeatures_self, 1000120000: d_VkPhysicalDeviceVariablePointersFeatures_self, 1000053001: d_VkPhysicalDeviceMultiviewFeatures_self, 1000083000: d_VkPhysicalDevice16BitStorageFeatures_self, 1000175000: d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self, 1000156004: d_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self, 1000145001: d_VkPhysicalDeviceProtectedMemoryFeatures_self, 1000148000: d_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self, 1000392000: d_VkPhysicalDeviceMultiDrawFeaturesEXT_self, 1000138000: d_VkPhysicalDeviceInlineUniformBlockFeatures_self, 1000413000: d_VkPhysicalDeviceMaintenance4Features_self, 1000470000: d_VkPhysicalDeviceMaintenance5Features_self, 1000545000: d_VkPhysicalDeviceMaintenance6Features_self, 1000562000: d_VkPhysicalDeviceMaintenance7FeaturesKHR_self, 1000063000: d_VkPhysicalDeviceShaderDrawParametersFeatures_self, 1000082000: d_VkPhysicalDeviceShaderFloat16Int8Features_self, 1000261000: d_VkPhysicalDeviceHostQueryResetFeatures_self, 1000388000: d_VkPhysicalDeviceGlobalPriorityQueryFeatures_self, 1000161001: d_VkPhysicalDeviceDescriptorIndexingFeatures_self, 1000207000: d_VkPhysicalDeviceTimelineSemaphoreFeatures_self, 1000177000: d_VkPhysicalDevice8BitStorageFeatures_self, 1000081001: d_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self, 1000211000: d_VkPhysicalDeviceVulkanMemoryModelFeatures_self, 1000180000: d_VkPhysicalDeviceShaderAtomicInt64Features_self, 1000260000: d_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self, 1000273000: d_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self, 1000190002: d_VkPhysicalDeviceVertexAttributeDivisorFeatures_self, 1000028000: d_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self, 1000201000: d_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self, 1000203000: d_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self, 1000328000: d_VkPhysicalDeviceMeshShaderFeaturesEXT_self, 1000150013: d_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self, 1000347000: d_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self, 1000348013: d_VkPhysicalDeviceRayQueryFeaturesKHR_self, 1000386000: d_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self, 1000221000: d_VkPhysicalDeviceScalarBlockLayoutFeatures_self, 1000253000: d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self, 1000102000: d_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self, 1000257000: d_VkPhysicalDeviceBufferDeviceAddressFeatures_self, 1000244000: d_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self, 1000108000: d_VkPhysicalDeviceImagelessFramebufferFeatures_self, 1000066000: d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self, 1000252000: d_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self, 1000181000: d_VkPhysicalDeviceShaderClockFeaturesKHR_self, 1000265000: d_VkPhysicalDeviceIndexTypeUint8Features_self, 1000251000: d_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self, 1000241000: d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self, 1000356000: d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self, 1000276000: d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self, 1000281000: d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self, 1000225002: d_VkPhysicalDeviceSubgroupSizeControlFeatures_self, 1000259000: d_VkPhysicalDeviceLineRasterizationFeatures_self, 1000297000: d_VkPhysicalDevicePipelineCreationCacheControlFeatures_self, 49: d_VkPhysicalDeviceVulkan11Features_self, 51: d_VkPhysicalDeviceVulkan12Features_self, 53: d_VkPhysicalDeviceVulkan13Features_self, 55: d_VkPhysicalDeviceVulkan14Features_self, 1000287002: d_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self, 1000411000: d_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self, 1000267000: d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self, 1000377000: d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self, 1000455000: d_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self, 1000325000: d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self, 1000323000: d_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self, 1000286000: d_VkPhysicalDeviceRobustness2FeaturesKHR_self, 1000335000: d_VkPhysicalDeviceImageRobustnessFeatures_self, 1000336000: d_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self, 1000340000: d_VkPhysicalDevice4444FormatsFeaturesEXT_self, 1000234000: d_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self, 1000226003: d_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self, 1000215000: d_VkPhysicalDeviceShaderTerminateInvocationFeatures_self, 1000393000: d_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self, 1000418000: d_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self, 1000524000: d_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self, 1000495000: d_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self, 1000351000: d_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self, 1000355000: d_VkPhysicalDeviceDepthClipControlFeaturesEXT_self, 1000582000: d_VkPhysicalDeviceDepthClampControlFeaturesEXT_self, 1000352000: d_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self, 1000558000: d_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self, 1000381000: d_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self, 1000314007: d_VkPhysicalDeviceSynchronization2Features_self, 1000270000: d_VkPhysicalDeviceHostImageCopyFeatures_self, 1000382000: d_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self, 1000465000: d_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self, 1000376000: d_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self, 1000466000: d_VkPhysicalDevicePipelineProtectedAccessFeatures_self, 1000330000: d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self, 1000254000: d_VkPhysicalDeviceProvokingVertexFeaturesEXT_self, 1000280000: d_VkPhysicalDeviceShaderIntegerDotProductFeatures_self, 1000579000: d_VkPhysicalDeviceShaderFmaFeaturesKHR_self, 1000044003: d_VkPhysicalDeviceDynamicRenderingFeatures_self, 1000391000: d_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self, 1000342000: d_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self, 1000320000: d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self, 1000451000: d_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self, 1000422000: d_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self, 1000068001: d_VkPhysicalDevicePipelineRobustnessFeatures_self, 1000339000: d_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self, 1000421000: d_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self, 1000498000: d_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self, 1000499000: d_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self, 1000283000: d_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self, 1000481000: d_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self, 1000506000: d_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self, 1000434000: d_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self, 1000416000: d_VkPhysicalDeviceShaderSubgroupRotateFeatures_self, 1000544000: d_VkPhysicalDeviceShaderExpectAssumeFeatures_self, 1000528000: d_VkPhysicalDeviceShaderFloatControls2Features_self, 1000232000: d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self, 1000235000: d_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self, 1000141000: d_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self, 1000564000: d_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self, 1000642000: d_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self, 1000567000: d_VkPhysicalDeviceShaderFloat8FeaturesEXT_self, 1000387000: d_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self, 1000135009: d_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self, 1000295001: d_VkDevicePrivateDataCreateInfo_self, 1000059000: d_VkPhysicalDeviceFeatures2_self, 1000070001: d_VkDeviceGroupDeviceCreateInfo_self, 1000071000: d_VkPhysicalDeviceExternalImageFormatInfo_self, 1000147000: d_VkImageFormatListCreateInfo_self, 1000158002: d_VkPhysicalDeviceImageDrmFormatModifierInfoEXT_self, 1000246000: d_VkImageStencilUsageCreateInfo_self, 1000170000: d_VkPhysicalDeviceImageViewImageFormatInfoEXT_self, 1000207002: d_VkSemaphoreTypeCreateInfo_self, 1000384005: d_VkDeviceQueueTimelineInfoMESA_self, 1000072002: d_VkExportMemoryAllocateInfo_self, 1000060000: d_VkMemoryAllocateFlagsInfo_self, 1000127001: d_VkMemoryDedicatedAllocateInfo_self, 1000257003: d_VkMemoryOpaqueCaptureAddressAllocateInfo_self, 1000384002: d_VkImportMemoryResourceInfoMESA_self, 1000113000: d_VkExportFenceCreateInfo_self, 1000108001: d_VkFramebufferAttachmentsCreateInfo_self, 1000072001: d_VkExternalMemoryImageCreateInfo_self, 1000158003: d_VkImageDrmFormatModifierListCreateInfoEXT_self, 1000158004: d_VkImageDrmFormatModifierExplicitCreateInfoEXT_self, 1000135007: d_VkOpaqueCaptureDataCreateInfoEXT_self, 1000060014: d_VkBindImageMemoryDeviceGroupInfo_self, 1000156002: d_VkBindImagePlaneMemoryInfo_self, 1000156003: d_VkImagePlaneMemoryRequirementsInfo_self, 16: d_VkShaderModuleCreateInfo_self, 1000225001: d_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo_self, 1000068000: d_VkPipelineRobustnessCreateInfo_self, 1000135006: d_VkShaderDescriptorSetAndBindingMappingInfoEXT_self, 1000190001: d_VkPipelineVertexInputDivisorStateCreateInfo_self, 1000117003: d_VkPipelineTessellationDomainOriginStateCreateInfo_self, 1000355001: d_VkPipelineViewportDepthClipControlCreateInfoEXT_self, 1000582001: d_VkPipelineViewportDepthClampControlCreateInfoEXT_self, 1000101001: d_VkPipelineRasterizationConservativeStateCreateInfoEXT_self, 1000028002: d_VkPipelineRasterizationStateStreamCreateInfoEXT_self, 1000102001: d_VkPipelineRasterizationDepthClipStateCreateInfoEXT_self, 1000259001: d_VkPipelineRasterizationLineStateCreateInfo_self, 1000254001: d_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT_self, 1000143002: d_VkPipelineSampleLocationsStateCreateInfoEXT_self, 1000148002: d_VkPipelineColorBlendAdvancedStateCreateInfoEXT_self, 1000381001: d_VkPipelineColorWriteCreateInfoEXT_self, 1000470005: d_VkPipelineCreateFlags2CreateInfo_self, 1000290000: d_VkPipelineLibraryCreateInfoKHR_self, 1000192000: d_VkPipelineCreationFeedbackCreateInfo_self, 1000226001: d_VkPipelineFragmentShadingRateStateCreateInfoKHR_self, 1000044002: d_VkPipelineRenderingCreateInfo_self, 1000320002: d_VkGraphicsPipelineLibraryCreateInfoEXT_self, 1000060005: d_VkDeviceGroupSubmitInfo_self, 1000145000: d_VkProtectedSubmitInfo_self, 1000207003: d_VkTimelineSemaphoreSubmitInfo_self, 1000060006: d_VkDeviceGroupBindSparseInfo_self, 1000053000: d_VkRenderPassMultiviewCreateInfo_self, 1000117001: d_VkRenderPassInputAttachmentAspectCreateInfo_self, 1000241002: d_VkAttachmentDescriptionStencilLayout_self, 1000241001: d_VkAttachmentReferenceStencilLayout_self, 1000199001: d_VkSubpassDescriptionDepthStencilResolve_self, 1000226000: d_VkFragmentShadingRateAttachmentInfoKHR_self, 1000314000: d_VkMemoryBarrier2_self, 1000077000: d_VkExportSemaphoreCreateInfo_self, 1000117002: d_VkImageViewUsageCreateInfo_self, 1000418001: d_VkImageViewSlicedCreateInfoEXT_self, 1000156001: d_VkSamplerYcbcrConversionInfo_self, 1000391001: d_VkImageViewMinLodCreateInfoEXT_self, 1000130001: d_VkSamplerReductionModeCreateInfo_self, 1000287000: d_VkSamplerCustomBorderColorCreateInfoEXT_self, 1000411001: d_VkSamplerBorderColorComponentMappingCreateInfoEXT_self, 1000135011: d_VkSamplerCustomBorderColorIndexCreateInfoEXT_self, 1000138002: d_VkWriteDescriptorSetInlineUniformBlock_self, 1000150007: d_VkWriteDescriptorSetAccelerationStructureKHR_self, 1000384006: d_VkRingMonitorInfoMESA_self, 1000384007: d_VkRingPriorityInfoMESA_self};
/** @const {!Object<number, function(!VenusReader, !Object)>} chain structs of output structs in requests, by sType */
const PNEXT_PARTIAL = {1000161004: d_VkDescriptorSetVariableDescriptorCountLayoutSupport_self_partial, 1000295000: d_VkPhysicalDevicePrivateDataFeatures_self_partial, 1000120000: d_VkPhysicalDeviceVariablePointersFeatures_self_partial, 1000053001: d_VkPhysicalDeviceMultiviewFeatures_self_partial, 1000083000: d_VkPhysicalDevice16BitStorageFeatures_self_partial, 1000175000: d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self_partial, 1000156004: d_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self_partial, 1000145001: d_VkPhysicalDeviceProtectedMemoryFeatures_self_partial, 1000148000: d_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self_partial, 1000392000: d_VkPhysicalDeviceMultiDrawFeaturesEXT_self_partial, 1000138000: d_VkPhysicalDeviceInlineUniformBlockFeatures_self_partial, 1000413000: d_VkPhysicalDeviceMaintenance4Features_self_partial, 1000470000: d_VkPhysicalDeviceMaintenance5Features_self_partial, 1000545000: d_VkPhysicalDeviceMaintenance6Features_self_partial, 1000562000: d_VkPhysicalDeviceMaintenance7FeaturesKHR_self_partial, 1000063000: d_VkPhysicalDeviceShaderDrawParametersFeatures_self_partial, 1000082000: d_VkPhysicalDeviceShaderFloat16Int8Features_self_partial, 1000261000: d_VkPhysicalDeviceHostQueryResetFeatures_self_partial, 1000388000: d_VkPhysicalDeviceGlobalPriorityQueryFeatures_self_partial, 1000161001: d_VkPhysicalDeviceDescriptorIndexingFeatures_self_partial, 1000207000: d_VkPhysicalDeviceTimelineSemaphoreFeatures_self_partial, 1000177000: d_VkPhysicalDevice8BitStorageFeatures_self_partial, 1000081001: d_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self_partial, 1000211000: d_VkPhysicalDeviceVulkanMemoryModelFeatures_self_partial, 1000180000: d_VkPhysicalDeviceShaderAtomicInt64Features_self_partial, 1000260000: d_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self_partial, 1000273000: d_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self_partial, 1000190002: d_VkPhysicalDeviceVertexAttributeDivisorFeatures_self_partial, 1000028000: d_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self_partial, 1000201000: d_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self_partial, 1000203000: d_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self_partial, 1000328000: d_VkPhysicalDeviceMeshShaderFeaturesEXT_self_partial, 1000150013: d_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self_partial, 1000347000: d_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self_partial, 1000348013: d_VkPhysicalDeviceRayQueryFeaturesKHR_self_partial, 1000386000: d_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self_partial, 1000221000: d_VkPhysicalDeviceScalarBlockLayoutFeatures_self_partial, 1000253000: d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self_partial, 1000102000: d_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self_partial, 1000257000: d_VkPhysicalDeviceBufferDeviceAddressFeatures_self_partial, 1000244000: d_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self_partial, 1000108000: d_VkPhysicalDeviceImagelessFramebufferFeatures_self_partial, 1000066000: d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self_partial, 1000252000: d_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self_partial, 1000181000: d_VkPhysicalDeviceShaderClockFeaturesKHR_self_partial, 1000265000: d_VkPhysicalDeviceIndexTypeUint8Features_self_partial, 1000251000: d_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self_partial, 1000241000: d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self_partial, 1000356000: d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self_partial, 1000276000: d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self_partial, 1000281000: d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self_partial, 1000225002: d_VkPhysicalDeviceSubgroupSizeControlFeatures_self_partial, 1000259000: d_VkPhysicalDeviceLineRasterizationFeatures_self_partial, 1000297000: d_VkPhysicalDevicePipelineCreationCacheControlFeatures_self_partial, 49: d_VkPhysicalDeviceVulkan11Features_self_partial, 51: d_VkPhysicalDeviceVulkan12Features_self_partial, 53: d_VkPhysicalDeviceVulkan13Features_self_partial, 55: d_VkPhysicalDeviceVulkan14Features_self_partial, 1000287002: d_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self_partial, 1000411000: d_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self_partial, 1000267000: d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self_partial, 1000377000: d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self_partial, 1000455000: d_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self_partial, 1000325000: d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self_partial, 1000323000: d_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self_partial, 1000286000: d_VkPhysicalDeviceRobustness2FeaturesKHR_self_partial, 1000335000: d_VkPhysicalDeviceImageRobustnessFeatures_self_partial, 1000336000: d_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self_partial, 1000340000: d_VkPhysicalDevice4444FormatsFeaturesEXT_self_partial, 1000234000: d_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self_partial, 1000226003: d_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self_partial, 1000215000: d_VkPhysicalDeviceShaderTerminateInvocationFeatures_self_partial, 1000393000: d_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self_partial, 1000418000: d_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self_partial, 1000524000: d_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self_partial, 1000495000: d_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self_partial, 1000351000: d_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self_partial, 1000355000: d_VkPhysicalDeviceDepthClipControlFeaturesEXT_self_partial, 1000582000: d_VkPhysicalDeviceDepthClampControlFeaturesEXT_self_partial, 1000352000: d_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self_partial, 1000558000: d_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self_partial, 1000381000: d_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self_partial, 1000314007: d_VkPhysicalDeviceSynchronization2Features_self_partial, 1000270000: d_VkPhysicalDeviceHostImageCopyFeatures_self_partial, 1000382000: d_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self_partial, 1000465000: d_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self_partial, 1000376000: d_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self_partial, 1000466000: d_VkPhysicalDevicePipelineProtectedAccessFeatures_self_partial, 1000330000: d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self_partial, 1000254000: d_VkPhysicalDeviceProvokingVertexFeaturesEXT_self_partial, 1000280000: d_VkPhysicalDeviceShaderIntegerDotProductFeatures_self_partial, 1000579000: d_VkPhysicalDeviceShaderFmaFeaturesKHR_self_partial, 1000044003: d_VkPhysicalDeviceDynamicRenderingFeatures_self_partial, 1000391000: d_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self_partial, 1000342000: d_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self_partial, 1000320000: d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self_partial, 1000451000: d_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self_partial, 1000422000: d_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self_partial, 1000068001: d_VkPhysicalDevicePipelineRobustnessFeatures_self_partial, 1000339000: d_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self_partial, 1000421000: d_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self_partial, 1000498000: d_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self_partial, 1000499000: d_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self_partial, 1000283000: d_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self_partial, 1000481000: d_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self_partial, 1000506000: d_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self_partial, 1000434000: d_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self_partial, 1000416000: d_VkPhysicalDeviceShaderSubgroupRotateFeatures_self_partial, 1000544000: d_VkPhysicalDeviceShaderExpectAssumeFeatures_self_partial, 1000528000: d_VkPhysicalDeviceShaderFloatControls2Features_self_partial, 1000232000: d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self_partial, 1000235000: d_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self_partial, 1000141000: d_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self_partial, 1000564000: d_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self_partial, 1000642000: d_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self_partial, 1000567000: d_VkPhysicalDeviceShaderFloat8FeaturesEXT_self_partial, 1000387000: d_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self_partial, 1000135009: d_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self_partial, 1000392001: d_VkPhysicalDeviceMultiDrawPropertiesEXT_self_partial, 1000080000: d_VkPhysicalDevicePushDescriptorProperties_self_partial, 1000196000: d_VkPhysicalDeviceDriverProperties_self_partial, 1000071004: d_VkPhysicalDeviceIDProperties_self_partial, 1000053002: d_VkPhysicalDeviceMultiviewProperties_self_partial, 1000094000: d_VkPhysicalDeviceSubgroupProperties_self_partial, 1000117000: d_VkPhysicalDevicePointClippingProperties_self_partial, 1000145002: d_VkPhysicalDeviceProtectedMemoryProperties_self_partial, 1000130000: d_VkPhysicalDeviceSamplerFilterMinmaxProperties_self_partial, 1000143003: d_VkPhysicalDeviceSampleLocationsPropertiesEXT_self_partial, 1000148001: d_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self_partial, 1000138001: d_VkPhysicalDeviceInlineUniformBlockProperties_self_partial, 1000168000: d_VkPhysicalDeviceMaintenance3Properties_self_partial, 1000413001: d_VkPhysicalDeviceMaintenance4Properties_self_partial, 1000470001: d_VkPhysicalDeviceMaintenance5Properties_self_partial, 1000545001: d_VkPhysicalDeviceMaintenance6Properties_self_partial, 1000562001: d_VkPhysicalDeviceMaintenance7PropertiesKHR_self_partial, 1000197000: d_VkPhysicalDeviceFloatControlsProperties_self_partial, 1000101000: d_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self_partial, 1000161002: d_VkPhysicalDeviceDescriptorIndexingProperties_self_partial, 1000207001: d_VkPhysicalDeviceTimelineSemaphoreProperties_self_partial, 1000190000: d_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self_partial, 1000525000: d_VkPhysicalDeviceVertexAttributeDivisorProperties_self_partial, 1000212000: d_VkPhysicalDevicePCIBusInfoPropertiesEXT_self_partial, 1000199000: d_VkPhysicalDeviceDepthStencilResolveProperties_self_partial, 1000028001: d_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self_partial, 1000511000: d_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self_partial, 1000328001: d_VkPhysicalDeviceMeshShaderPropertiesEXT_self_partial, 1000150014: d_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self_partial, 1000347001: d_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self_partial, 1000281001: d_VkPhysicalDeviceTexelBufferAlignmentProperties_self_partial, 1000225000: d_VkPhysicalDeviceSubgroupSizeControlProperties_self_partial, 1000259002: d_VkPhysicalDeviceLineRasterizationProperties_self_partial, 50: d_VkPhysicalDeviceVulkan11Properties_self_partial, 52: d_VkPhysicalDeviceVulkan12Properties_self_partial, 54: d_VkPhysicalDeviceVulkan13Properties_self_partial, 56: d_VkPhysicalDeviceVulkan14Properties_self_partial, 1000287001: d_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self_partial, 1000455001: d_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self_partial, 1000286001: d_VkPhysicalDeviceRobustness2PropertiesKHR_self_partial, 1000226002: d_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self_partial, 1000495001: d_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self_partial, 1000270001: d_VkPhysicalDeviceHostImageCopyProperties_self_partial, 1000254002: d_VkPhysicalDeviceProvokingVertexPropertiesEXT_self_partial, 1000280001: d_VkPhysicalDeviceShaderIntegerDotProductProperties_self_partial, 1000322000: d_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self_partial, 1000320001: d_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self_partial, 1000451001: d_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self_partial, 1000068002: d_VkPhysicalDevicePipelineRobustnessProperties_self_partial, 1000506002: d_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self_partial, 1000135008: d_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self_partial, 1000158000: d_VkDrmFormatModifierPropertiesListEXT_self_partial, 1000376001: d_VkSubpassResolvePerformanceQueryEXT_self_partial, 1000360000: d_VkFormatProperties3_self_partial, 1000158006: d_VkDrmFormatModifierPropertiesList2EXT_self_partial, 1000071001: d_VkExternalImageFormatProperties_self_partial, 1000156005: d_VkSamplerYcbcrConversionImageFormatProperties_self_partial, 1000170001: d_VkFilterCubicImageViewImageFormatPropertiesEXT_self_partial, 1000270009: d_VkHostImageCopyDevicePerformanceQuery_self_partial, 1000388001: d_VkQueueFamilyGlobalPriorityProperties_self_partial, 1000237000: d_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self_partial, 1000384003: d_VkMemoryResourceAllocationSizePropertiesMESA_self_partial, 1000270008: d_VkSubresourceHostMemcpySize_self_partial, 1000127000: d_VkMemoryDedicatedRequirements_self_partial};
/** @const {!Object<number, function(!VenusWriter, !Object)>} chain structs of replies, by sType */
const PNEXT_REPLY = {1000161004: e_VkDescriptorSetVariableDescriptorCountLayoutSupport_self, 1000295000: e_VkPhysicalDevicePrivateDataFeatures_self, 1000120000: e_VkPhysicalDeviceVariablePointersFeatures_self, 1000053001: e_VkPhysicalDeviceMultiviewFeatures_self, 1000083000: e_VkPhysicalDevice16BitStorageFeatures_self, 1000175000: e_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self, 1000156004: e_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self, 1000145001: e_VkPhysicalDeviceProtectedMemoryFeatures_self, 1000148000: e_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self, 1000392000: e_VkPhysicalDeviceMultiDrawFeaturesEXT_self, 1000138000: e_VkPhysicalDeviceInlineUniformBlockFeatures_self, 1000413000: e_VkPhysicalDeviceMaintenance4Features_self, 1000470000: e_VkPhysicalDeviceMaintenance5Features_self, 1000545000: e_VkPhysicalDeviceMaintenance6Features_self, 1000562000: e_VkPhysicalDeviceMaintenance7FeaturesKHR_self, 1000063000: e_VkPhysicalDeviceShaderDrawParametersFeatures_self, 1000082000: e_VkPhysicalDeviceShaderFloat16Int8Features_self, 1000261000: e_VkPhysicalDeviceHostQueryResetFeatures_self, 1000388000: e_VkPhysicalDeviceGlobalPriorityQueryFeatures_self, 1000161001: e_VkPhysicalDeviceDescriptorIndexingFeatures_self, 1000207000: e_VkPhysicalDeviceTimelineSemaphoreFeatures_self, 1000177000: e_VkPhysicalDevice8BitStorageFeatures_self, 1000081001: e_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self, 1000211000: e_VkPhysicalDeviceVulkanMemoryModelFeatures_self, 1000180000: e_VkPhysicalDeviceShaderAtomicInt64Features_self, 1000260000: e_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self, 1000273000: e_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self, 1000190002: e_VkPhysicalDeviceVertexAttributeDivisorFeatures_self, 1000028000: e_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self, 1000201000: e_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self, 1000203000: e_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self, 1000328000: e_VkPhysicalDeviceMeshShaderFeaturesEXT_self, 1000150013: e_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self, 1000347000: e_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self, 1000348013: e_VkPhysicalDeviceRayQueryFeaturesKHR_self, 1000386000: e_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self, 1000221000: e_VkPhysicalDeviceScalarBlockLayoutFeatures_self, 1000253000: e_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self, 1000102000: e_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self, 1000257000: e_VkPhysicalDeviceBufferDeviceAddressFeatures_self, 1000244000: e_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self, 1000108000: e_VkPhysicalDeviceImagelessFramebufferFeatures_self, 1000066000: e_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self, 1000252000: e_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self, 1000181000: e_VkPhysicalDeviceShaderClockFeaturesKHR_self, 1000265000: e_VkPhysicalDeviceIndexTypeUint8Features_self, 1000251000: e_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self, 1000241000: e_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self, 1000356000: e_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self, 1000276000: e_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self, 1000281000: e_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self, 1000225002: e_VkPhysicalDeviceSubgroupSizeControlFeatures_self, 1000259000: e_VkPhysicalDeviceLineRasterizationFeatures_self, 1000297000: e_VkPhysicalDevicePipelineCreationCacheControlFeatures_self, 49: e_VkPhysicalDeviceVulkan11Features_self, 51: e_VkPhysicalDeviceVulkan12Features_self, 53: e_VkPhysicalDeviceVulkan13Features_self, 55: e_VkPhysicalDeviceVulkan14Features_self, 1000287002: e_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self, 1000411000: e_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self, 1000267000: e_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self, 1000377000: e_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self, 1000455000: e_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self, 1000325000: e_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self, 1000323000: e_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self, 1000286000: e_VkPhysicalDeviceRobustness2FeaturesKHR_self, 1000335000: e_VkPhysicalDeviceImageRobustnessFeatures_self, 1000336000: e_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self, 1000340000: e_VkPhysicalDevice4444FormatsFeaturesEXT_self, 1000234000: e_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self, 1000226003: e_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self, 1000215000: e_VkPhysicalDeviceShaderTerminateInvocationFeatures_self, 1000393000: e_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self, 1000418000: e_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self, 1000524000: e_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self, 1000495000: e_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self, 1000351000: e_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self, 1000355000: e_VkPhysicalDeviceDepthClipControlFeaturesEXT_self, 1000582000: e_VkPhysicalDeviceDepthClampControlFeaturesEXT_self, 1000352000: e_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self, 1000558000: e_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self, 1000381000: e_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self, 1000314007: e_VkPhysicalDeviceSynchronization2Features_self, 1000270000: e_VkPhysicalDeviceHostImageCopyFeatures_self, 1000382000: e_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self, 1000465000: e_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self, 1000376000: e_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self, 1000466000: e_VkPhysicalDevicePipelineProtectedAccessFeatures_self, 1000330000: e_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self, 1000254000: e_VkPhysicalDeviceProvokingVertexFeaturesEXT_self, 1000280000: e_VkPhysicalDeviceShaderIntegerDotProductFeatures_self, 1000579000: e_VkPhysicalDeviceShaderFmaFeaturesKHR_self, 1000044003: e_VkPhysicalDeviceDynamicRenderingFeatures_self, 1000391000: e_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self, 1000342000: e_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self, 1000320000: e_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self, 1000451000: e_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self, 1000422000: e_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self, 1000068001: e_VkPhysicalDevicePipelineRobustnessFeatures_self, 1000339000: e_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self, 1000421000: e_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self, 1000498000: e_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self, 1000499000: e_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self, 1000283000: e_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self, 1000481000: e_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self, 1000506000: e_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self, 1000434000: e_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self, 1000416000: e_VkPhysicalDeviceShaderSubgroupRotateFeatures_self, 1000544000: e_VkPhysicalDeviceShaderExpectAssumeFeatures_self, 1000528000: e_VkPhysicalDeviceShaderFloatControls2Features_self, 1000232000: e_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self, 1000235000: e_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self, 1000141000: e_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self, 1000564000: e_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self, 1000642000: e_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self, 1000567000: e_VkPhysicalDeviceShaderFloat8FeaturesEXT_self, 1000387000: e_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self, 1000135009: e_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self, 1000392001: e_VkPhysicalDeviceMultiDrawPropertiesEXT_self, 1000080000: e_VkPhysicalDevicePushDescriptorProperties_self, 1000196000: e_VkPhysicalDeviceDriverProperties_self, 1000071004: e_VkPhysicalDeviceIDProperties_self, 1000053002: e_VkPhysicalDeviceMultiviewProperties_self, 1000094000: e_VkPhysicalDeviceSubgroupProperties_self, 1000117000: e_VkPhysicalDevicePointClippingProperties_self, 1000145002: e_VkPhysicalDeviceProtectedMemoryProperties_self, 1000130000: e_VkPhysicalDeviceSamplerFilterMinmaxProperties_self, 1000143003: e_VkPhysicalDeviceSampleLocationsPropertiesEXT_self, 1000148001: e_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self, 1000138001: e_VkPhysicalDeviceInlineUniformBlockProperties_self, 1000168000: e_VkPhysicalDeviceMaintenance3Properties_self, 1000413001: e_VkPhysicalDeviceMaintenance4Properties_self, 1000470001: e_VkPhysicalDeviceMaintenance5Properties_self, 1000545001: e_VkPhysicalDeviceMaintenance6Properties_self, 1000562001: e_VkPhysicalDeviceMaintenance7PropertiesKHR_self, 1000197000: e_VkPhysicalDeviceFloatControlsProperties_self, 1000101000: e_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self, 1000161002: e_VkPhysicalDeviceDescriptorIndexingProperties_self, 1000207001: e_VkPhysicalDeviceTimelineSemaphoreProperties_self, 1000190000: e_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self, 1000525000: e_VkPhysicalDeviceVertexAttributeDivisorProperties_self, 1000212000: e_VkPhysicalDevicePCIBusInfoPropertiesEXT_self, 1000199000: e_VkPhysicalDeviceDepthStencilResolveProperties_self, 1000028001: e_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self, 1000511000: e_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self, 1000328001: e_VkPhysicalDeviceMeshShaderPropertiesEXT_self, 1000150014: e_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self, 1000347001: e_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self, 1000281001: e_VkPhysicalDeviceTexelBufferAlignmentProperties_self, 1000225000: e_VkPhysicalDeviceSubgroupSizeControlProperties_self, 1000259002: e_VkPhysicalDeviceLineRasterizationProperties_self, 50: e_VkPhysicalDeviceVulkan11Properties_self, 52: e_VkPhysicalDeviceVulkan12Properties_self, 54: e_VkPhysicalDeviceVulkan13Properties_self, 56: e_VkPhysicalDeviceVulkan14Properties_self, 1000287001: e_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self, 1000455001: e_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self, 1000286001: e_VkPhysicalDeviceRobustness2PropertiesKHR_self, 1000226002: e_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self, 1000495001: e_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self, 1000270001: e_VkPhysicalDeviceHostImageCopyProperties_self, 1000254002: e_VkPhysicalDeviceProvokingVertexPropertiesEXT_self, 1000280001: e_VkPhysicalDeviceShaderIntegerDotProductProperties_self, 1000322000: e_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self, 1000320001: e_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self, 1000451001: e_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self, 1000068002: e_VkPhysicalDevicePipelineRobustnessProperties_self, 1000506002: e_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self, 1000135008: e_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self, 1000158000: e_VkDrmFormatModifierPropertiesListEXT_self, 1000376001: e_VkSubpassResolvePerformanceQueryEXT_self, 1000360000: e_VkFormatProperties3_self, 1000158006: e_VkDrmFormatModifierPropertiesList2EXT_self, 1000071001: e_VkExternalImageFormatProperties_self, 1000156005: e_VkSamplerYcbcrConversionImageFormatProperties_self, 1000170001: e_VkFilterCubicImageViewImageFormatPropertiesEXT_self, 1000270009: e_VkHostImageCopyDevicePerformanceQuery_self, 1000388001: e_VkQueueFamilyGlobalPriorityProperties_self, 1000237000: e_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self, 1000384003: e_VkMemoryResourceAllocationSizePropertiesMESA_self, 1000270008: e_VkSubresourceHostMemcpySize_self, 1000127000: e_VkMemoryDedicatedRequirements_self};
const EMPTY = {};

/** @const {!Object<number, !Array>} command type: [name, request decoder, reply encoder or null] */
export const COMMANDS = {
    0: ["vkCreateInstance", d_vkCreateInstance, e_vkCreateInstance_reply],
    1: ["vkDestroyInstance", d_vkDestroyInstance, e_vkDestroyInstance_reply],
    2: ["vkEnumeratePhysicalDevices", d_vkEnumeratePhysicalDevices, e_vkEnumeratePhysicalDevices_reply],
    3: ["vkGetPhysicalDeviceFeatures", d_vkGetPhysicalDeviceFeatures, e_vkGetPhysicalDeviceFeatures_reply],
    4: ["vkGetPhysicalDeviceFormatProperties", d_vkGetPhysicalDeviceFormatProperties, e_vkGetPhysicalDeviceFormatProperties_reply],
    5: ["vkGetPhysicalDeviceImageFormatProperties", d_vkGetPhysicalDeviceImageFormatProperties, e_vkGetPhysicalDeviceImageFormatProperties_reply],
    6: ["vkGetPhysicalDeviceProperties", d_vkGetPhysicalDeviceProperties, e_vkGetPhysicalDeviceProperties_reply],
    7: ["vkGetPhysicalDeviceQueueFamilyProperties", d_vkGetPhysicalDeviceQueueFamilyProperties, e_vkGetPhysicalDeviceQueueFamilyProperties_reply],
    8: ["vkGetPhysicalDeviceMemoryProperties", d_vkGetPhysicalDeviceMemoryProperties, e_vkGetPhysicalDeviceMemoryProperties_reply],
    11: ["vkCreateDevice", d_vkCreateDevice, e_vkCreateDevice_reply],
    12: ["vkDestroyDevice", d_vkDestroyDevice, e_vkDestroyDevice_reply],
    13: ["vkEnumerateInstanceExtensionProperties", d_vkEnumerateInstanceExtensionProperties, e_vkEnumerateInstanceExtensionProperties_reply],
    14: ["vkEnumerateDeviceExtensionProperties", d_vkEnumerateDeviceExtensionProperties, e_vkEnumerateDeviceExtensionProperties_reply],
    15: ["vkEnumerateInstanceLayerProperties", d_vkEnumerateInstanceLayerProperties, e_vkEnumerateInstanceLayerProperties_reply],
    16: ["vkEnumerateDeviceLayerProperties", d_vkEnumerateDeviceLayerProperties, e_vkEnumerateDeviceLayerProperties_reply],
    17: ["vkGetDeviceQueue", d_vkGetDeviceQueue, e_vkGetDeviceQueue_reply],
    18: ["vkQueueSubmit", d_vkQueueSubmit, e_vkQueueSubmit_reply],
    19: ["vkQueueWaitIdle", d_vkQueueWaitIdle, e_vkQueueWaitIdle_reply],
    20: ["vkDeviceWaitIdle", d_vkDeviceWaitIdle, e_vkDeviceWaitIdle_reply],
    21: ["vkAllocateMemory", d_vkAllocateMemory, e_vkAllocateMemory_reply],
    22: ["vkFreeMemory", d_vkFreeMemory, e_vkFreeMemory_reply],
    24: ["vkUnmapMemory", d_vkUnmapMemory, e_vkUnmapMemory_reply],
    25: ["vkFlushMappedMemoryRanges", d_vkFlushMappedMemoryRanges, e_vkFlushMappedMemoryRanges_reply],
    26: ["vkInvalidateMappedMemoryRanges", d_vkInvalidateMappedMemoryRanges, e_vkInvalidateMappedMemoryRanges_reply],
    27: ["vkGetDeviceMemoryCommitment", d_vkGetDeviceMemoryCommitment, e_vkGetDeviceMemoryCommitment_reply],
    28: ["vkBindBufferMemory", d_vkBindBufferMemory, e_vkBindBufferMemory_reply],
    29: ["vkBindImageMemory", d_vkBindImageMemory, e_vkBindImageMemory_reply],
    30: ["vkGetBufferMemoryRequirements", d_vkGetBufferMemoryRequirements, e_vkGetBufferMemoryRequirements_reply],
    31: ["vkGetImageMemoryRequirements", d_vkGetImageMemoryRequirements, e_vkGetImageMemoryRequirements_reply],
    32: ["vkGetImageSparseMemoryRequirements", d_vkGetImageSparseMemoryRequirements, e_vkGetImageSparseMemoryRequirements_reply],
    33: ["vkGetPhysicalDeviceSparseImageFormatProperties", d_vkGetPhysicalDeviceSparseImageFormatProperties, e_vkGetPhysicalDeviceSparseImageFormatProperties_reply],
    34: ["vkQueueBindSparse", d_vkQueueBindSparse, e_vkQueueBindSparse_reply],
    35: ["vkCreateFence", d_vkCreateFence, e_vkCreateFence_reply],
    36: ["vkDestroyFence", d_vkDestroyFence, e_vkDestroyFence_reply],
    37: ["vkResetFences", d_vkResetFences, e_vkResetFences_reply],
    38: ["vkGetFenceStatus", d_vkGetFenceStatus, e_vkGetFenceStatus_reply],
    39: ["vkWaitForFences", d_vkWaitForFences, e_vkWaitForFences_reply],
    40: ["vkCreateSemaphore", d_vkCreateSemaphore, e_vkCreateSemaphore_reply],
    41: ["vkDestroySemaphore", d_vkDestroySemaphore, e_vkDestroySemaphore_reply],
    42: ["vkCreateEvent", d_vkCreateEvent, e_vkCreateEvent_reply],
    43: ["vkDestroyEvent", d_vkDestroyEvent, e_vkDestroyEvent_reply],
    44: ["vkGetEventStatus", d_vkGetEventStatus, e_vkGetEventStatus_reply],
    45: ["vkSetEvent", d_vkSetEvent, e_vkSetEvent_reply],
    46: ["vkResetEvent", d_vkResetEvent, e_vkResetEvent_reply],
    47: ["vkCreateQueryPool", d_vkCreateQueryPool, e_vkCreateQueryPool_reply],
    48: ["vkDestroyQueryPool", d_vkDestroyQueryPool, e_vkDestroyQueryPool_reply],
    49: ["vkGetQueryPoolResults", d_vkGetQueryPoolResults, e_vkGetQueryPoolResults_reply],
    50: ["vkCreateBuffer", d_vkCreateBuffer, e_vkCreateBuffer_reply],
    51: ["vkDestroyBuffer", d_vkDestroyBuffer, e_vkDestroyBuffer_reply],
    52: ["vkCreateBufferView", d_vkCreateBufferView, e_vkCreateBufferView_reply],
    53: ["vkDestroyBufferView", d_vkDestroyBufferView, e_vkDestroyBufferView_reply],
    54: ["vkCreateImage", d_vkCreateImage, e_vkCreateImage_reply],
    55: ["vkDestroyImage", d_vkDestroyImage, e_vkDestroyImage_reply],
    56: ["vkGetImageSubresourceLayout", d_vkGetImageSubresourceLayout, e_vkGetImageSubresourceLayout_reply],
    57: ["vkCreateImageView", d_vkCreateImageView, e_vkCreateImageView_reply],
    58: ["vkDestroyImageView", d_vkDestroyImageView, e_vkDestroyImageView_reply],
    59: ["vkCreateShaderModule", d_vkCreateShaderModule, e_vkCreateShaderModule_reply],
    60: ["vkDestroyShaderModule", d_vkDestroyShaderModule, e_vkDestroyShaderModule_reply],
    61: ["vkCreatePipelineCache", d_vkCreatePipelineCache, e_vkCreatePipelineCache_reply],
    62: ["vkDestroyPipelineCache", d_vkDestroyPipelineCache, e_vkDestroyPipelineCache_reply],
    63: ["vkGetPipelineCacheData", d_vkGetPipelineCacheData, e_vkGetPipelineCacheData_reply],
    64: ["vkMergePipelineCaches", d_vkMergePipelineCaches, e_vkMergePipelineCaches_reply],
    65: ["vkCreateGraphicsPipelines", d_vkCreateGraphicsPipelines, e_vkCreateGraphicsPipelines_reply],
    66: ["vkCreateComputePipelines", d_vkCreateComputePipelines, e_vkCreateComputePipelines_reply],
    67: ["vkDestroyPipeline", d_vkDestroyPipeline, e_vkDestroyPipeline_reply],
    68: ["vkCreatePipelineLayout", d_vkCreatePipelineLayout, e_vkCreatePipelineLayout_reply],
    69: ["vkDestroyPipelineLayout", d_vkDestroyPipelineLayout, e_vkDestroyPipelineLayout_reply],
    70: ["vkCreateSampler", d_vkCreateSampler, e_vkCreateSampler_reply],
    71: ["vkDestroySampler", d_vkDestroySampler, e_vkDestroySampler_reply],
    72: ["vkCreateDescriptorSetLayout", d_vkCreateDescriptorSetLayout, e_vkCreateDescriptorSetLayout_reply],
    73: ["vkDestroyDescriptorSetLayout", d_vkDestroyDescriptorSetLayout, e_vkDestroyDescriptorSetLayout_reply],
    74: ["vkCreateDescriptorPool", d_vkCreateDescriptorPool, e_vkCreateDescriptorPool_reply],
    75: ["vkDestroyDescriptorPool", d_vkDestroyDescriptorPool, e_vkDestroyDescriptorPool_reply],
    76: ["vkResetDescriptorPool", d_vkResetDescriptorPool, e_vkResetDescriptorPool_reply],
    77: ["vkAllocateDescriptorSets", d_vkAllocateDescriptorSets, e_vkAllocateDescriptorSets_reply],
    78: ["vkFreeDescriptorSets", d_vkFreeDescriptorSets, e_vkFreeDescriptorSets_reply],
    79: ["vkUpdateDescriptorSets", d_vkUpdateDescriptorSets, e_vkUpdateDescriptorSets_reply],
    80: ["vkCreateFramebuffer", d_vkCreateFramebuffer, e_vkCreateFramebuffer_reply],
    81: ["vkDestroyFramebuffer", d_vkDestroyFramebuffer, e_vkDestroyFramebuffer_reply],
    82: ["vkCreateRenderPass", d_vkCreateRenderPass, e_vkCreateRenderPass_reply],
    83: ["vkDestroyRenderPass", d_vkDestroyRenderPass, e_vkDestroyRenderPass_reply],
    84: ["vkGetRenderAreaGranularity", d_vkGetRenderAreaGranularity, e_vkGetRenderAreaGranularity_reply],
    85: ["vkCreateCommandPool", d_vkCreateCommandPool, e_vkCreateCommandPool_reply],
    86: ["vkDestroyCommandPool", d_vkDestroyCommandPool, e_vkDestroyCommandPool_reply],
    87: ["vkResetCommandPool", d_vkResetCommandPool, e_vkResetCommandPool_reply],
    88: ["vkAllocateCommandBuffers", d_vkAllocateCommandBuffers, e_vkAllocateCommandBuffers_reply],
    89: ["vkFreeCommandBuffers", d_vkFreeCommandBuffers, e_vkFreeCommandBuffers_reply],
    90: ["vkBeginCommandBuffer", d_vkBeginCommandBuffer, e_vkBeginCommandBuffer_reply],
    91: ["vkEndCommandBuffer", d_vkEndCommandBuffer, e_vkEndCommandBuffer_reply],
    92: ["vkResetCommandBuffer", d_vkResetCommandBuffer, e_vkResetCommandBuffer_reply],
    93: ["vkCmdBindPipeline", d_vkCmdBindPipeline, e_vkCmdBindPipeline_reply],
    94: ["vkCmdSetViewport", d_vkCmdSetViewport, e_vkCmdSetViewport_reply],
    95: ["vkCmdSetScissor", d_vkCmdSetScissor, e_vkCmdSetScissor_reply],
    96: ["vkCmdSetLineWidth", d_vkCmdSetLineWidth, e_vkCmdSetLineWidth_reply],
    97: ["vkCmdSetDepthBias", d_vkCmdSetDepthBias, e_vkCmdSetDepthBias_reply],
    98: ["vkCmdSetBlendConstants", d_vkCmdSetBlendConstants, e_vkCmdSetBlendConstants_reply],
    99: ["vkCmdSetDepthBounds", d_vkCmdSetDepthBounds, e_vkCmdSetDepthBounds_reply],
    100: ["vkCmdSetStencilCompareMask", d_vkCmdSetStencilCompareMask, e_vkCmdSetStencilCompareMask_reply],
    101: ["vkCmdSetStencilWriteMask", d_vkCmdSetStencilWriteMask, e_vkCmdSetStencilWriteMask_reply],
    102: ["vkCmdSetStencilReference", d_vkCmdSetStencilReference, e_vkCmdSetStencilReference_reply],
    103: ["vkCmdBindDescriptorSets", d_vkCmdBindDescriptorSets, e_vkCmdBindDescriptorSets_reply],
    104: ["vkCmdBindIndexBuffer", d_vkCmdBindIndexBuffer, e_vkCmdBindIndexBuffer_reply],
    105: ["vkCmdBindVertexBuffers", d_vkCmdBindVertexBuffers, e_vkCmdBindVertexBuffers_reply],
    106: ["vkCmdDraw", d_vkCmdDraw, e_vkCmdDraw_reply],
    107: ["vkCmdDrawIndexed", d_vkCmdDrawIndexed, e_vkCmdDrawIndexed_reply],
    108: ["vkCmdDrawIndirect", d_vkCmdDrawIndirect, e_vkCmdDrawIndirect_reply],
    109: ["vkCmdDrawIndexedIndirect", d_vkCmdDrawIndexedIndirect, e_vkCmdDrawIndexedIndirect_reply],
    110: ["vkCmdDispatch", d_vkCmdDispatch, e_vkCmdDispatch_reply],
    111: ["vkCmdDispatchIndirect", d_vkCmdDispatchIndirect, e_vkCmdDispatchIndirect_reply],
    112: ["vkCmdCopyBuffer", d_vkCmdCopyBuffer, e_vkCmdCopyBuffer_reply],
    113: ["vkCmdCopyImage", d_vkCmdCopyImage, e_vkCmdCopyImage_reply],
    114: ["vkCmdBlitImage", d_vkCmdBlitImage, e_vkCmdBlitImage_reply],
    115: ["vkCmdCopyBufferToImage", d_vkCmdCopyBufferToImage, e_vkCmdCopyBufferToImage_reply],
    116: ["vkCmdCopyImageToBuffer", d_vkCmdCopyImageToBuffer, e_vkCmdCopyImageToBuffer_reply],
    117: ["vkCmdUpdateBuffer", d_vkCmdUpdateBuffer, e_vkCmdUpdateBuffer_reply],
    118: ["vkCmdFillBuffer", d_vkCmdFillBuffer, e_vkCmdFillBuffer_reply],
    119: ["vkCmdClearColorImage", d_vkCmdClearColorImage, e_vkCmdClearColorImage_reply],
    120: ["vkCmdClearDepthStencilImage", d_vkCmdClearDepthStencilImage, e_vkCmdClearDepthStencilImage_reply],
    121: ["vkCmdClearAttachments", d_vkCmdClearAttachments, e_vkCmdClearAttachments_reply],
    122: ["vkCmdResolveImage", d_vkCmdResolveImage, e_vkCmdResolveImage_reply],
    123: ["vkCmdSetEvent", d_vkCmdSetEvent, e_vkCmdSetEvent_reply],
    124: ["vkCmdResetEvent", d_vkCmdResetEvent, e_vkCmdResetEvent_reply],
    125: ["vkCmdWaitEvents", d_vkCmdWaitEvents, e_vkCmdWaitEvents_reply],
    126: ["vkCmdPipelineBarrier", d_vkCmdPipelineBarrier, e_vkCmdPipelineBarrier_reply],
    127: ["vkCmdBeginQuery", d_vkCmdBeginQuery, e_vkCmdBeginQuery_reply],
    128: ["vkCmdEndQuery", d_vkCmdEndQuery, e_vkCmdEndQuery_reply],
    129: ["vkCmdResetQueryPool", d_vkCmdResetQueryPool, e_vkCmdResetQueryPool_reply],
    130: ["vkCmdWriteTimestamp", d_vkCmdWriteTimestamp, e_vkCmdWriteTimestamp_reply],
    131: ["vkCmdCopyQueryPoolResults", d_vkCmdCopyQueryPoolResults, e_vkCmdCopyQueryPoolResults_reply],
    132: ["vkCmdPushConstants", d_vkCmdPushConstants, e_vkCmdPushConstants_reply],
    133: ["vkCmdBeginRenderPass", d_vkCmdBeginRenderPass, e_vkCmdBeginRenderPass_reply],
    134: ["vkCmdNextSubpass", d_vkCmdNextSubpass, e_vkCmdNextSubpass_reply],
    135: ["vkCmdEndRenderPass", d_vkCmdEndRenderPass, e_vkCmdEndRenderPass_reply],
    136: ["vkCmdExecuteCommands", d_vkCmdExecuteCommands, e_vkCmdExecuteCommands_reply],
    137: ["vkEnumerateInstanceVersion", d_vkEnumerateInstanceVersion, e_vkEnumerateInstanceVersion_reply],
    138: ["vkBindBufferMemory2", d_vkBindBufferMemory2, e_vkBindBufferMemory2_reply],
    139: ["vkBindImageMemory2", d_vkBindImageMemory2, e_vkBindImageMemory2_reply],
    140: ["vkGetDeviceGroupPeerMemoryFeatures", d_vkGetDeviceGroupPeerMemoryFeatures, e_vkGetDeviceGroupPeerMemoryFeatures_reply],
    141: ["vkCmdSetDeviceMask", d_vkCmdSetDeviceMask, e_vkCmdSetDeviceMask_reply],
    142: ["vkCmdDispatchBase", d_vkCmdDispatchBase, e_vkCmdDispatchBase_reply],
    143: ["vkEnumeratePhysicalDeviceGroups", d_vkEnumeratePhysicalDeviceGroups, e_vkEnumeratePhysicalDeviceGroups_reply],
    144: ["vkGetImageMemoryRequirements2", d_vkGetImageMemoryRequirements2, e_vkGetImageMemoryRequirements2_reply],
    145: ["vkGetBufferMemoryRequirements2", d_vkGetBufferMemoryRequirements2, e_vkGetBufferMemoryRequirements2_reply],
    146: ["vkGetImageSparseMemoryRequirements2", d_vkGetImageSparseMemoryRequirements2, e_vkGetImageSparseMemoryRequirements2_reply],
    147: ["vkGetPhysicalDeviceFeatures2", d_vkGetPhysicalDeviceFeatures2, e_vkGetPhysicalDeviceFeatures2_reply],
    148: ["vkGetPhysicalDeviceProperties2", d_vkGetPhysicalDeviceProperties2, e_vkGetPhysicalDeviceProperties2_reply],
    149: ["vkGetPhysicalDeviceFormatProperties2", d_vkGetPhysicalDeviceFormatProperties2, e_vkGetPhysicalDeviceFormatProperties2_reply],
    150: ["vkGetPhysicalDeviceImageFormatProperties2", d_vkGetPhysicalDeviceImageFormatProperties2, e_vkGetPhysicalDeviceImageFormatProperties2_reply],
    151: ["vkGetPhysicalDeviceQueueFamilyProperties2", d_vkGetPhysicalDeviceQueueFamilyProperties2, e_vkGetPhysicalDeviceQueueFamilyProperties2_reply],
    152: ["vkGetPhysicalDeviceMemoryProperties2", d_vkGetPhysicalDeviceMemoryProperties2, e_vkGetPhysicalDeviceMemoryProperties2_reply],
    153: ["vkGetPhysicalDeviceSparseImageFormatProperties2", d_vkGetPhysicalDeviceSparseImageFormatProperties2, e_vkGetPhysicalDeviceSparseImageFormatProperties2_reply],
    154: ["vkTrimCommandPool", d_vkTrimCommandPool, e_vkTrimCommandPool_reply],
    155: ["vkGetDeviceQueue2", d_vkGetDeviceQueue2, e_vkGetDeviceQueue2_reply],
    156: ["vkCreateSamplerYcbcrConversion", d_vkCreateSamplerYcbcrConversion, e_vkCreateSamplerYcbcrConversion_reply],
    157: ["vkDestroySamplerYcbcrConversion", d_vkDestroySamplerYcbcrConversion, e_vkDestroySamplerYcbcrConversion_reply],
    158: ["vkCreateDescriptorUpdateTemplate", d_vkCreateDescriptorUpdateTemplate, e_vkCreateDescriptorUpdateTemplate_reply],
    159: ["vkDestroyDescriptorUpdateTemplate", d_vkDestroyDescriptorUpdateTemplate, e_vkDestroyDescriptorUpdateTemplate_reply],
    161: ["vkGetPhysicalDeviceExternalBufferProperties", d_vkGetPhysicalDeviceExternalBufferProperties, e_vkGetPhysicalDeviceExternalBufferProperties_reply],
    162: ["vkGetPhysicalDeviceExternalFenceProperties", d_vkGetPhysicalDeviceExternalFenceProperties, e_vkGetPhysicalDeviceExternalFenceProperties_reply],
    163: ["vkGetPhysicalDeviceExternalSemaphoreProperties", d_vkGetPhysicalDeviceExternalSemaphoreProperties, e_vkGetPhysicalDeviceExternalSemaphoreProperties_reply],
    164: ["vkGetDescriptorSetLayoutSupport", d_vkGetDescriptorSetLayoutSupport, e_vkGetDescriptorSetLayoutSupport_reply],
    165: ["vkCmdDrawIndirectCount", d_vkCmdDrawIndirectCount, e_vkCmdDrawIndirectCount_reply],
    166: ["vkCmdDrawIndexedIndirectCount", d_vkCmdDrawIndexedIndirectCount, e_vkCmdDrawIndexedIndirectCount_reply],
    167: ["vkCreateRenderPass2", d_vkCreateRenderPass2, e_vkCreateRenderPass2_reply],
    168: ["vkCmdBeginRenderPass2", d_vkCmdBeginRenderPass2, e_vkCmdBeginRenderPass2_reply],
    169: ["vkCmdNextSubpass2", d_vkCmdNextSubpass2, e_vkCmdNextSubpass2_reply],
    170: ["vkCmdEndRenderPass2", d_vkCmdEndRenderPass2, e_vkCmdEndRenderPass2_reply],
    171: ["vkResetQueryPool", d_vkResetQueryPool, e_vkResetQueryPool_reply],
    172: ["vkGetSemaphoreCounterValue", d_vkGetSemaphoreCounterValue, e_vkGetSemaphoreCounterValue_reply],
    173: ["vkWaitSemaphores", d_vkWaitSemaphores, e_vkWaitSemaphores_reply],
    174: ["vkSignalSemaphore", d_vkSignalSemaphore, e_vkSignalSemaphore_reply],
    175: ["vkGetBufferDeviceAddress", d_vkGetBufferDeviceAddress, e_vkGetBufferDeviceAddress_reply],
    176: ["vkGetBufferOpaqueCaptureAddress", d_vkGetBufferOpaqueCaptureAddress, e_vkGetBufferOpaqueCaptureAddress_reply],
    177: ["vkGetDeviceMemoryOpaqueCaptureAddress", d_vkGetDeviceMemoryOpaqueCaptureAddress, e_vkGetDeviceMemoryOpaqueCaptureAddress_reply],
    178: ["vkSetReplyCommandStreamMESA", d_vkSetReplyCommandStreamMESA, e_vkSetReplyCommandStreamMESA_reply],
    179: ["vkSeekReplyCommandStreamMESA", d_vkSeekReplyCommandStreamMESA, e_vkSeekReplyCommandStreamMESA_reply],
    180: ["vkExecuteCommandStreamsMESA", d_vkExecuteCommandStreamsMESA, e_vkExecuteCommandStreamsMESA_reply],
    181: ["vkCmdBindTransformFeedbackBuffersEXT", d_vkCmdBindTransformFeedbackBuffersEXT, e_vkCmdBindTransformFeedbackBuffersEXT_reply],
    182: ["vkCmdBeginTransformFeedbackEXT", d_vkCmdBeginTransformFeedbackEXT, e_vkCmdBeginTransformFeedbackEXT_reply],
    183: ["vkCmdEndTransformFeedbackEXT", d_vkCmdEndTransformFeedbackEXT, e_vkCmdEndTransformFeedbackEXT_reply],
    184: ["vkCmdBeginQueryIndexedEXT", d_vkCmdBeginQueryIndexedEXT, e_vkCmdBeginQueryIndexedEXT_reply],
    185: ["vkCmdEndQueryIndexedEXT", d_vkCmdEndQueryIndexedEXT, e_vkCmdEndQueryIndexedEXT_reply],
    186: ["vkCmdDrawIndirectByteCountEXT", d_vkCmdDrawIndirectByteCountEXT, e_vkCmdDrawIndirectByteCountEXT_reply],
    187: ["vkGetImageDrmFormatModifierPropertiesEXT", d_vkGetImageDrmFormatModifierPropertiesEXT, e_vkGetImageDrmFormatModifierPropertiesEXT_reply],
    188: ["vkCreateRingMESA", d_vkCreateRingMESA, e_vkCreateRingMESA_reply],
    189: ["vkDestroyRingMESA", d_vkDestroyRingMESA, e_vkDestroyRingMESA_reply],
    190: ["vkNotifyRingMESA", d_vkNotifyRingMESA, e_vkNotifyRingMESA_reply],
    191: ["vkWriteRingExtraMESA", d_vkWriteRingExtraMESA, e_vkWriteRingExtraMESA_reply],
    192: ["vkGetMemoryResourcePropertiesMESA", d_vkGetMemoryResourcePropertiesMESA, e_vkGetMemoryResourcePropertiesMESA_reply],
    196: ["vkGetPhysicalDeviceToolProperties", d_vkGetPhysicalDeviceToolProperties, e_vkGetPhysicalDeviceToolProperties_reply],
    197: ["vkCreatePrivateDataSlot", d_vkCreatePrivateDataSlot, e_vkCreatePrivateDataSlot_reply],
    198: ["vkDestroyPrivateDataSlot", d_vkDestroyPrivateDataSlot, e_vkDestroyPrivateDataSlot_reply],
    199: ["vkSetPrivateData", d_vkSetPrivateData, e_vkSetPrivateData_reply],
    200: ["vkGetPrivateData", d_vkGetPrivateData, e_vkGetPrivateData_reply],
    201: ["vkCmdSetEvent2", d_vkCmdSetEvent2, e_vkCmdSetEvent2_reply],
    202: ["vkCmdResetEvent2", d_vkCmdResetEvent2, e_vkCmdResetEvent2_reply],
    203: ["vkCmdWaitEvents2", d_vkCmdWaitEvents2, e_vkCmdWaitEvents2_reply],
    204: ["vkCmdPipelineBarrier2", d_vkCmdPipelineBarrier2, e_vkCmdPipelineBarrier2_reply],
    205: ["vkCmdWriteTimestamp2", d_vkCmdWriteTimestamp2, e_vkCmdWriteTimestamp2_reply],
    206: ["vkQueueSubmit2", d_vkQueueSubmit2, e_vkQueueSubmit2_reply],
    207: ["vkCmdCopyBuffer2", d_vkCmdCopyBuffer2, e_vkCmdCopyBuffer2_reply],
    208: ["vkCmdCopyImage2", d_vkCmdCopyImage2, e_vkCmdCopyImage2_reply],
    209: ["vkCmdCopyBufferToImage2", d_vkCmdCopyBufferToImage2, e_vkCmdCopyBufferToImage2_reply],
    210: ["vkCmdCopyImageToBuffer2", d_vkCmdCopyImageToBuffer2, e_vkCmdCopyImageToBuffer2_reply],
    211: ["vkCmdBlitImage2", d_vkCmdBlitImage2, e_vkCmdBlitImage2_reply],
    212: ["vkCmdResolveImage2", d_vkCmdResolveImage2, e_vkCmdResolveImage2_reply],
    213: ["vkCmdBeginRendering", d_vkCmdBeginRendering, e_vkCmdBeginRendering_reply],
    214: ["vkCmdEndRendering", d_vkCmdEndRendering, e_vkCmdEndRendering_reply],
    215: ["vkCmdSetCullMode", d_vkCmdSetCullMode, e_vkCmdSetCullMode_reply],
    216: ["vkCmdSetFrontFace", d_vkCmdSetFrontFace, e_vkCmdSetFrontFace_reply],
    217: ["vkCmdSetPrimitiveTopology", d_vkCmdSetPrimitiveTopology, e_vkCmdSetPrimitiveTopology_reply],
    218: ["vkCmdSetViewportWithCount", d_vkCmdSetViewportWithCount, e_vkCmdSetViewportWithCount_reply],
    219: ["vkCmdSetScissorWithCount", d_vkCmdSetScissorWithCount, e_vkCmdSetScissorWithCount_reply],
    220: ["vkCmdBindVertexBuffers2", d_vkCmdBindVertexBuffers2, e_vkCmdBindVertexBuffers2_reply],
    221: ["vkCmdSetDepthTestEnable", d_vkCmdSetDepthTestEnable, e_vkCmdSetDepthTestEnable_reply],
    222: ["vkCmdSetDepthWriteEnable", d_vkCmdSetDepthWriteEnable, e_vkCmdSetDepthWriteEnable_reply],
    223: ["vkCmdSetDepthCompareOp", d_vkCmdSetDepthCompareOp, e_vkCmdSetDepthCompareOp_reply],
    224: ["vkCmdSetDepthBoundsTestEnable", d_vkCmdSetDepthBoundsTestEnable, e_vkCmdSetDepthBoundsTestEnable_reply],
    225: ["vkCmdSetStencilTestEnable", d_vkCmdSetStencilTestEnable, e_vkCmdSetStencilTestEnable_reply],
    226: ["vkCmdSetStencilOp", d_vkCmdSetStencilOp, e_vkCmdSetStencilOp_reply],
    227: ["vkCmdSetRasterizerDiscardEnable", d_vkCmdSetRasterizerDiscardEnable, e_vkCmdSetRasterizerDiscardEnable_reply],
    228: ["vkCmdSetDepthBiasEnable", d_vkCmdSetDepthBiasEnable, e_vkCmdSetDepthBiasEnable_reply],
    229: ["vkCmdSetPrimitiveRestartEnable", d_vkCmdSetPrimitiveRestartEnable, e_vkCmdSetPrimitiveRestartEnable_reply],
    230: ["vkGetDeviceBufferMemoryRequirements", d_vkGetDeviceBufferMemoryRequirements, e_vkGetDeviceBufferMemoryRequirements_reply],
    231: ["vkGetDeviceImageMemoryRequirements", d_vkGetDeviceImageMemoryRequirements, e_vkGetDeviceImageMemoryRequirements_reply],
    232: ["vkGetDeviceImageSparseMemoryRequirements", d_vkGetDeviceImageSparseMemoryRequirements, e_vkGetDeviceImageSparseMemoryRequirements_reply],
    233: ["vkCmdSetPatchControlPointsEXT", d_vkCmdSetPatchControlPointsEXT, e_vkCmdSetPatchControlPointsEXT_reply],
    234: ["vkCmdSetLogicOpEXT", d_vkCmdSetLogicOpEXT, e_vkCmdSetLogicOpEXT_reply],
    235: ["vkGetPhysicalDeviceCalibrateableTimeDomainsKHR", d_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR, e_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR_reply],
    236: ["vkGetCalibratedTimestampsKHR", d_vkGetCalibratedTimestampsKHR, e_vkGetCalibratedTimestampsKHR_reply],
    237: ["vkCmdSetLineStipple", d_vkCmdSetLineStipple, e_vkCmdSetLineStipple_reply],
    240: ["vkCmdBeginConditionalRenderingEXT", d_vkCmdBeginConditionalRenderingEXT, e_vkCmdBeginConditionalRenderingEXT_reply],
    241: ["vkCmdEndConditionalRenderingEXT", d_vkCmdEndConditionalRenderingEXT, e_vkCmdEndConditionalRenderingEXT_reply],
    244: ["vkResetFenceResourceMESA", d_vkResetFenceResourceMESA, e_vkResetFenceResourceMESA_reply],
    245: ["vkWaitSemaphoreResourceMESA", d_vkWaitSemaphoreResourceMESA, e_vkWaitSemaphoreResourceMESA_reply],
    246: ["vkImportSemaphoreResourceMESA", d_vkImportSemaphoreResourceMESA, e_vkImportSemaphoreResourceMESA_reply],
    247: ["vkCmdDrawMultiEXT", d_vkCmdDrawMultiEXT, e_vkCmdDrawMultiEXT_reply],
    248: ["vkCmdDrawMultiIndexedEXT", d_vkCmdDrawMultiIndexedEXT, e_vkCmdDrawMultiIndexedEXT_reply],
    249: ["vkCmdPushDescriptorSet", d_vkCmdPushDescriptorSet, e_vkCmdPushDescriptorSet_reply],
    251: ["vkSubmitVirtqueueSeqnoMESA", d_vkSubmitVirtqueueSeqnoMESA, e_vkSubmitVirtqueueSeqnoMESA_reply],
    252: ["vkWaitVirtqueueSeqnoMESA", d_vkWaitVirtqueueSeqnoMESA, e_vkWaitVirtqueueSeqnoMESA_reply],
    253: ["vkWaitRingSeqnoMESA", d_vkWaitRingSeqnoMESA, e_vkWaitRingSeqnoMESA_reply],
    254: ["vkCmdSetColorWriteEnableEXT", d_vkCmdSetColorWriteEnableEXT, e_vkCmdSetColorWriteEnableEXT_reply],
    255: ["vkCmdSetVertexInputEXT", d_vkCmdSetVertexInputEXT, e_vkCmdSetVertexInputEXT_reply],
    256: ["vkCmdSetTessellationDomainOriginEXT", d_vkCmdSetTessellationDomainOriginEXT, e_vkCmdSetTessellationDomainOriginEXT_reply],
    257: ["vkCmdSetDepthClampEnableEXT", d_vkCmdSetDepthClampEnableEXT, e_vkCmdSetDepthClampEnableEXT_reply],
    258: ["vkCmdSetPolygonModeEXT", d_vkCmdSetPolygonModeEXT, e_vkCmdSetPolygonModeEXT_reply],
    259: ["vkCmdSetRasterizationSamplesEXT", d_vkCmdSetRasterizationSamplesEXT, e_vkCmdSetRasterizationSamplesEXT_reply],
    260: ["vkCmdSetSampleMaskEXT", d_vkCmdSetSampleMaskEXT, e_vkCmdSetSampleMaskEXT_reply],
    261: ["vkCmdSetAlphaToCoverageEnableEXT", d_vkCmdSetAlphaToCoverageEnableEXT, e_vkCmdSetAlphaToCoverageEnableEXT_reply],
    262: ["vkCmdSetAlphaToOneEnableEXT", d_vkCmdSetAlphaToOneEnableEXT, e_vkCmdSetAlphaToOneEnableEXT_reply],
    263: ["vkCmdSetLogicOpEnableEXT", d_vkCmdSetLogicOpEnableEXT, e_vkCmdSetLogicOpEnableEXT_reply],
    264: ["vkCmdSetColorBlendEnableEXT", d_vkCmdSetColorBlendEnableEXT, e_vkCmdSetColorBlendEnableEXT_reply],
    265: ["vkCmdSetColorBlendEquationEXT", d_vkCmdSetColorBlendEquationEXT, e_vkCmdSetColorBlendEquationEXT_reply],
    266: ["vkCmdSetColorWriteMaskEXT", d_vkCmdSetColorWriteMaskEXT, e_vkCmdSetColorWriteMaskEXT_reply],
    267: ["vkCmdSetRasterizationStreamEXT", d_vkCmdSetRasterizationStreamEXT, e_vkCmdSetRasterizationStreamEXT_reply],
    268: ["vkCmdSetConservativeRasterizationModeEXT", d_vkCmdSetConservativeRasterizationModeEXT, e_vkCmdSetConservativeRasterizationModeEXT_reply],
    269: ["vkCmdSetExtraPrimitiveOverestimationSizeEXT", d_vkCmdSetExtraPrimitiveOverestimationSizeEXT, e_vkCmdSetExtraPrimitiveOverestimationSizeEXT_reply],
    270: ["vkCmdSetDepthClipEnableEXT", d_vkCmdSetDepthClipEnableEXT, e_vkCmdSetDepthClipEnableEXT_reply],
    271: ["vkCmdSetSampleLocationsEnableEXT", d_vkCmdSetSampleLocationsEnableEXT, e_vkCmdSetSampleLocationsEnableEXT_reply],
    272: ["vkCmdSetColorBlendAdvancedEXT", d_vkCmdSetColorBlendAdvancedEXT, e_vkCmdSetColorBlendAdvancedEXT_reply],
    273: ["vkCmdSetProvokingVertexModeEXT", d_vkCmdSetProvokingVertexModeEXT, e_vkCmdSetProvokingVertexModeEXT_reply],
    274: ["vkCmdSetLineRasterizationModeEXT", d_vkCmdSetLineRasterizationModeEXT, e_vkCmdSetLineRasterizationModeEXT_reply],
    275: ["vkCmdSetLineStippleEnableEXT", d_vkCmdSetLineStippleEnableEXT, e_vkCmdSetLineStippleEnableEXT_reply],
    276: ["vkCmdSetDepthClipNegativeOneToOneEXT", d_vkCmdSetDepthClipNegativeOneToOneEXT, e_vkCmdSetDepthClipNegativeOneToOneEXT_reply],
    277: ["vkGetPhysicalDeviceFragmentShadingRatesKHR", d_vkGetPhysicalDeviceFragmentShadingRatesKHR, e_vkGetPhysicalDeviceFragmentShadingRatesKHR_reply],
    278: ["vkCmdSetFragmentShadingRateKHR", d_vkCmdSetFragmentShadingRateKHR, e_vkCmdSetFragmentShadingRateKHR_reply],
    279: ["vkCmdBindIndexBuffer2", d_vkCmdBindIndexBuffer2, e_vkCmdBindIndexBuffer2_reply],
    280: ["vkGetRenderingAreaGranularity", d_vkGetRenderingAreaGranularity, e_vkGetRenderingAreaGranularity_reply],
    281: ["vkGetDeviceImageSubresourceLayout", d_vkGetDeviceImageSubresourceLayout, e_vkGetDeviceImageSubresourceLayout_reply],
    282: ["vkGetImageSubresourceLayout2", d_vkGetImageSubresourceLayout2, e_vkGetImageSubresourceLayout2_reply],
    283: ["vkCmdSetSampleLocationsEXT", d_vkCmdSetSampleLocationsEXT, e_vkCmdSetSampleLocationsEXT_reply],
    284: ["vkGetPhysicalDeviceMultisamplePropertiesEXT", d_vkGetPhysicalDeviceMultisamplePropertiesEXT, e_vkGetPhysicalDeviceMultisamplePropertiesEXT_reply],
    286: ["vkUnmapMemory2", d_vkUnmapMemory2, e_vkUnmapMemory2_reply],
    287: ["vkCmdSetRenderingAttachmentLocations", d_vkCmdSetRenderingAttachmentLocations, e_vkCmdSetRenderingAttachmentLocations_reply],
    288: ["vkCmdSetRenderingInputAttachmentIndices", d_vkCmdSetRenderingInputAttachmentIndices, e_vkCmdSetRenderingInputAttachmentIndices_reply],
    289: ["vkCmdBindDescriptorSets2", d_vkCmdBindDescriptorSets2, e_vkCmdBindDescriptorSets2_reply],
    290: ["vkCmdPushConstants2", d_vkCmdPushConstants2, e_vkCmdPushConstants2_reply],
    291: ["vkCmdPushDescriptorSet2", d_vkCmdPushDescriptorSet2, e_vkCmdPushDescriptorSet2_reply],
    295: ["vkCopyImageToImage", d_vkCopyImageToImage, e_vkCopyImageToImage_reply],
    296: ["vkTransitionImageLayout", d_vkTransitionImageLayout, e_vkTransitionImageLayout_reply],
    297: ["vkCopyImageToMemoryMESA", d_vkCopyImageToMemoryMESA, e_vkCopyImageToMemoryMESA_reply],
    298: ["vkCopyMemoryToImageMESA", d_vkCopyMemoryToImageMESA, e_vkCopyMemoryToImageMESA_reply],
    299: ["vkCreateDeferredOperationKHR", d_vkCreateDeferredOperationKHR, e_vkCreateDeferredOperationKHR_reply],
    300: ["vkDestroyDeferredOperationKHR", d_vkDestroyDeferredOperationKHR, e_vkDestroyDeferredOperationKHR_reply],
    301: ["vkGetDeferredOperationMaxConcurrencyKHR", d_vkGetDeferredOperationMaxConcurrencyKHR, e_vkGetDeferredOperationMaxConcurrencyKHR_reply],
    302: ["vkGetDeferredOperationResultKHR", d_vkGetDeferredOperationResultKHR, e_vkGetDeferredOperationResultKHR_reply],
    303: ["vkDeferredOperationJoinKHR", d_vkDeferredOperationJoinKHR, e_vkDeferredOperationJoinKHR_reply],
    328: ["vkCmdSetDepthBias2EXT", d_vkCmdSetDepthBias2EXT, e_vkCmdSetDepthBias2EXT_reply],
    329: ["vkCmdSetAttachmentFeedbackLoopEnableEXT", d_vkCmdSetAttachmentFeedbackLoopEnableEXT, e_vkCmdSetAttachmentFeedbackLoopEnableEXT_reply],
    330: ["vkCmdSetDepthClampRangeEXT", d_vkCmdSetDepthClampRangeEXT, e_vkCmdSetDepthClampRangeEXT_reply],
    331: ["vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR", d_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR, e_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR_reply],
    332: ["vkCmdDrawMeshTasksEXT", d_vkCmdDrawMeshTasksEXT, e_vkCmdDrawMeshTasksEXT_reply],
    333: ["vkCmdDrawMeshTasksIndirectEXT", d_vkCmdDrawMeshTasksIndirectEXT, e_vkCmdDrawMeshTasksIndirectEXT_reply],
    334: ["vkCmdDrawMeshTasksIndirectCountEXT", d_vkCmdDrawMeshTasksIndirectCountEXT, e_vkCmdDrawMeshTasksIndirectCountEXT_reply],
    335: ["vkWriteSamplerDescriptorMESA", d_vkWriteSamplerDescriptorMESA, e_vkWriteSamplerDescriptorMESA_reply],
    336: ["vkWriteResourceDescriptorMESA", d_vkWriteResourceDescriptorMESA, e_vkWriteResourceDescriptorMESA_reply],
    339: ["vkCmdBindSamplerHeapEXT", d_vkCmdBindSamplerHeapEXT, e_vkCmdBindSamplerHeapEXT_reply],
    340: ["vkCmdBindResourceHeapEXT", d_vkCmdBindResourceHeapEXT, e_vkCmdBindResourceHeapEXT_reply],
    341: ["vkCmdPushDataEXT", d_vkCmdPushDataEXT, e_vkCmdPushDataEXT_reply],
    342: ["vkGetImageOpaqueCaptureDataEXT", d_vkGetImageOpaqueCaptureDataEXT, e_vkGetImageOpaqueCaptureDataEXT_reply],
    343: ["vkGetPhysicalDeviceDescriptorSizeEXT", d_vkGetPhysicalDeviceDescriptorSizeEXT, e_vkGetPhysicalDeviceDescriptorSizeEXT_reply],
    344: ["vkRegisterCustomBorderColorEXT", d_vkRegisterCustomBorderColorEXT, e_vkRegisterCustomBorderColorEXT_reply],
    345: ["vkUnregisterCustomBorderColorEXT", d_vkUnregisterCustomBorderColorEXT, e_vkUnregisterCustomBorderColorEXT_reply],
};

/** @const {!Object<string, !Array<number>>} the extensions of the protocol: [number, spec version] */
export const EXTENSIONS = {
    "VK_ARM_rasterization_order_attachment_access": [343, 1],
    "VK_EXT_4444_formats": [341, 1],
    "VK_EXT_attachment_feedback_loop_dynamic_state": [525, 1],
    "VK_EXT_attachment_feedback_loop_layout": [340, 2],
    "VK_EXT_blend_operation_advanced": [149, 2],
    "VK_EXT_border_color_swizzle": [412, 1],
    "VK_EXT_buffer_device_address": [245, 2],
    "VK_EXT_calibrated_timestamps": [185, 2],
    "VK_EXT_color_write_enable": [382, 1],
    "VK_EXT_command_serialization": [384, 1],
    "VK_EXT_conditional_rendering": [82, 2],
    "VK_EXT_conservative_rasterization": [102, 1],
    "VK_EXT_custom_border_color": [288, 12],
    "VK_EXT_depth_bias_control": [284, 1],
    "VK_EXT_depth_clamp_control": [583, 1],
    "VK_EXT_depth_clamp_zero_one": [422, 1],
    "VK_EXT_depth_clip_control": [356, 1],
    "VK_EXT_depth_clip_enable": [103, 1],
    "VK_EXT_depth_range_unrestricted": [14, 1],
    "VK_EXT_descriptor_heap": [136, 1],
    "VK_EXT_descriptor_indexing": [162, 2],
    "VK_EXT_dynamic_rendering_unused_attachments": [500, 1],
    "VK_EXT_extended_dynamic_state": [268, 1],
    "VK_EXT_extended_dynamic_state2": [378, 1],
    "VK_EXT_extended_dynamic_state3": [456, 2],
    "VK_EXT_external_memory_acquire_unmodified": [454, 1],
    "VK_EXT_external_memory_dma_buf": [126, 1],
    "VK_EXT_filter_cubic": [171, 3],
    "VK_EXT_fragment_shader_interlock": [252, 1],
    "VK_EXT_global_priority": [175, 2],
    "VK_EXT_global_priority_query": [389, 1],
    "VK_EXT_graphics_pipeline_library": [321, 1],
    "VK_EXT_host_image_copy": [271, 1],
    "VK_EXT_host_query_reset": [262, 1],
    "VK_EXT_image_2d_view_of_3d": [394, 1],
    "VK_EXT_image_drm_format_modifier": [159, 2],
    "VK_EXT_image_robustness": [336, 1],
    "VK_EXT_image_sliced_view_of_3d": [419, 1],
    "VK_EXT_image_view_min_lod": [392, 1],
    "VK_EXT_index_type_uint8": [266, 1],
    "VK_EXT_inline_uniform_block": [139, 1],
    "VK_EXT_legacy_dithering": [466, 2],
    "VK_EXT_legacy_vertex_attributes": [496, 1],
    "VK_EXT_line_rasterization": [260, 1],
    "VK_EXT_load_store_op_none": [401, 1],
    "VK_EXT_memory_budget": [238, 1],
    "VK_EXT_mesh_shader": [329, 1],
    "VK_EXT_multi_draw": [393, 1],
    "VK_EXT_multisampled_render_to_single_sampled": [377, 1],
    "VK_EXT_mutable_descriptor_type": [495, 1],
    "VK_EXT_nested_command_buffer": [452, 1],
    "VK_EXT_non_seamless_cube_map": [423, 1],
    "VK_EXT_pci_bus_info": [213, 2],
    "VK_EXT_pipeline_creation_cache_control": [298, 3],
    "VK_EXT_pipeline_creation_feedback": [193, 1],
    "VK_EXT_pipeline_library_group_handles": [499, 1],
    "VK_EXT_pipeline_protected_access": [467, 1],
    "VK_EXT_pipeline_robustness": [69, 1],
    "VK_EXT_post_depth_coverage": [156, 1],
    "VK_EXT_primitive_topology_list_restart": [357, 1],
    "VK_EXT_primitives_generated_query": [383, 1],
    "VK_EXT_private_data": [296, 1],
    "VK_EXT_provoking_vertex": [255, 1],
    "VK_EXT_queue_family_foreign": [127, 1],
    "VK_EXT_rasterization_order_attachment_access": [464, 1],
    "VK_EXT_robustness2": [287, 1],
    "VK_EXT_sample_locations": [144, 1],
    "VK_EXT_sampler_filter_minmax": [131, 2],
    "VK_EXT_scalar_block_layout": [222, 1],
    "VK_EXT_separate_stencil_usage": [247, 1],
    "VK_EXT_shader_atomic_float": [261, 1],
    "VK_EXT_shader_atomic_float2": [274, 1],
    "VK_EXT_shader_demote_to_helper_invocation": [277, 1],
    "VK_EXT_shader_float8": [568, 1],
    "VK_EXT_shader_image_atomic_int64": [235, 1],
    "VK_EXT_shader_replicated_composites": [565, 1],
    "VK_EXT_shader_stencil_export": [141, 1],
    "VK_EXT_shader_subgroup_ballot": [65, 1],
    "VK_EXT_shader_subgroup_vote": [66, 1],
    "VK_EXT_shader_uniform_buffer_unsized_array": [643, 1],
    "VK_EXT_shader_viewport_index_layer": [163, 1],
    "VK_EXT_subgroup_size_control": [226, 2],
    "VK_EXT_texel_buffer_alignment": [282, 1],
    "VK_EXT_texture_compression_astc_hdr": [67, 1],
    "VK_EXT_tooling_info": [246, 1],
    "VK_EXT_transform_feedback": [29, 1],
    "VK_EXT_vertex_attribute_divisor": [191, 3],
    "VK_EXT_vertex_input_dynamic_state": [353, 2],
    "VK_EXT_ycbcr_2plane_444_formats": [331, 1],
    "VK_EXT_ycbcr_image_arrays": [253, 1],
    "VK_GOOGLE_decorate_string": [225, 1],
    "VK_GOOGLE_hlsl_functionality1": [224, 1],
    "VK_GOOGLE_user_type": [290, 1],
    "VK_IMG_filter_cubic": [16, 1],
    "VK_KHR_16bit_storage": [84, 1],
    "VK_KHR_8bit_storage": [178, 1],
    "VK_KHR_acceleration_structure": [151, 13],
    "VK_KHR_bind_memory2": [158, 1],
    "VK_KHR_buffer_device_address": [258, 1],
    "VK_KHR_calibrated_timestamps": [544, 1],
    "VK_KHR_compute_shader_derivatives": [512, 1],
    "VK_KHR_cooperative_matrix": [507, 2],
    "VK_KHR_copy_commands2": [338, 1],
    "VK_KHR_create_renderpass2": [110, 1],
    "VK_KHR_dedicated_allocation": [128, 3],
    "VK_KHR_deferred_host_operations": [269, 4],
    "VK_KHR_depth_clamp_zero_one": [605, 1],
    "VK_KHR_depth_stencil_resolve": [200, 1],
    "VK_KHR_descriptor_update_template": [86, 1],
    "VK_KHR_device_group": [61, 4],
    "VK_KHR_device_group_creation": [71, 1],
    "VK_KHR_draw_indirect_count": [170, 1],
    "VK_KHR_driver_properties": [197, 1],
    "VK_KHR_dynamic_rendering": [45, 1],
    "VK_KHR_dynamic_rendering_local_read": [233, 1],
    "VK_KHR_external_fence": [114, 1],
    "VK_KHR_external_fence_capabilities": [113, 1],
    "VK_KHR_external_fence_fd": [116, 1],
    "VK_KHR_external_memory": [73, 1],
    "VK_KHR_external_memory_capabilities": [72, 1],
    "VK_KHR_external_memory_fd": [75, 1],
    "VK_KHR_external_semaphore": [78, 1],
    "VK_KHR_external_semaphore_capabilities": [77, 1],
    "VK_KHR_external_semaphore_fd": [80, 1],
    "VK_KHR_format_feature_flags2": [361, 2],
    "VK_KHR_fragment_shader_barycentric": [323, 1],
    "VK_KHR_fragment_shading_rate": [227, 2],
    "VK_KHR_get_memory_requirements2": [147, 1],
    "VK_KHR_get_physical_device_properties2": [60, 2],
    "VK_KHR_global_priority": [189, 1],
    "VK_KHR_image_format_list": [148, 1],
    "VK_KHR_imageless_framebuffer": [109, 1],
    "VK_KHR_index_type_uint8": [534, 1],
    "VK_KHR_line_rasterization": [535, 1],
    "VK_KHR_load_store_op_none": [527, 1],
    "VK_KHR_maintenance1": [70, 2],
    "VK_KHR_maintenance2": [118, 1],
    "VK_KHR_maintenance3": [169, 1],
    "VK_KHR_maintenance4": [414, 2],
    "VK_KHR_maintenance5": [471, 1],
    "VK_KHR_maintenance6": [546, 1],
    "VK_KHR_maintenance7": [563, 1],
    "VK_KHR_map_memory2": [272, 1],
    "VK_KHR_multiview": [54, 1],
    "VK_KHR_pipeline_library": [291, 1],
    "VK_KHR_push_descriptor": [81, 2],
    "VK_KHR_ray_query": [349, 1],
    "VK_KHR_ray_tracing_maintenance1": [387, 1],
    "VK_KHR_ray_tracing_pipeline": [348, 1],
    "VK_KHR_ray_tracing_position_fetch": [482, 1],
    "VK_KHR_relaxed_block_layout": [145, 1],
    "VK_KHR_robustness2": [613, 1],
    "VK_KHR_sampler_mirror_clamp_to_edge": [15, 3],
    "VK_KHR_sampler_ycbcr_conversion": [157, 14],
    "VK_KHR_separate_depth_stencil_layouts": [242, 1],
    "VK_KHR_shader_atomic_int64": [181, 1],
    "VK_KHR_shader_bfloat16": [142, 1],
    "VK_KHR_shader_clock": [182, 1],
    "VK_KHR_shader_draw_parameters": [64, 1],
    "VK_KHR_shader_expect_assume": [545, 1],
    "VK_KHR_shader_float16_int8": [83, 1],
    "VK_KHR_shader_float_controls": [198, 4],
    "VK_KHR_shader_float_controls2": [529, 1],
    "VK_KHR_shader_fma": [580, 1],
    "VK_KHR_shader_integer_dot_product": [281, 1],
    "VK_KHR_shader_maximal_reconvergence": [435, 1],
    "VK_KHR_shader_non_semantic_info": [294, 1],
    "VK_KHR_shader_quad_control": [236, 1],
    "VK_KHR_shader_relaxed_extended_instruction": [559, 1],
    "VK_KHR_shader_subgroup_extended_types": [176, 1],
    "VK_KHR_shader_subgroup_rotate": [417, 2],
    "VK_KHR_shader_subgroup_uniform_control_flow": [324, 1],
    "VK_KHR_shader_terminate_invocation": [216, 1],
    "VK_KHR_shader_untyped_pointers": [388, 1],
    "VK_KHR_spirv_1_4": [237, 1],
    "VK_KHR_storage_buffer_storage_class": [132, 1],
    "VK_KHR_synchronization2": [315, 1],
    "VK_KHR_timeline_semaphore": [208, 2],
    "VK_KHR_uniform_buffer_standard_layout": [254, 1],
    "VK_KHR_variable_pointers": [121, 1],
    "VK_KHR_vertex_attribute_divisor": [526, 1],
    "VK_KHR_vulkan_memory_model": [212, 3],
    "VK_KHR_workgroup_memory_explicit_layout": [337, 1],
    "VK_KHR_zero_initialize_workgroup_memory": [326, 1],
    "VK_MESA_venus_protocol": [385, 4],
    "VK_NV_compute_shader_derivatives": [202, 1],
    "VK_VALVE_mutable_descriptor_type": [352, 1],
};
/** the protocol's Vulkan version (vk.xml) */
export const VK_XML_VERSION = 4211031;
export const WIRE_FORMAT_VERSION = 1;

function d_vkCreateInstance(r)
{
    const a = {};
    if(r.u64())
    {
        a.pCreateInfo = d_VkInstanceCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pInstance = r.h();
    }
    else a.pInstance = null;
    return a;
}
function d_vkDestroyInstance(r)
{
    const a = {};
    a.instance = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkEnumeratePhysicalDevices(r)
{
    const a = {};
    a.instance = r.h();
    if(r.u64())
    {
        a.pPhysicalDeviceCount = r.u32();
    }
    else a.pPhysicalDeviceCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pPhysicalDevices = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pPhysicalDevices[i] = r.h();
        }
    }
    else a.pPhysicalDevices = null;
    return a;
}
function d_vkGetPhysicalDeviceFeatures(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pFeatures = d_VkPhysicalDeviceFeatures_partial(r);
    }
    else a.pFeatures = null;
    return a;
}
function d_vkGetPhysicalDeviceFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    if(r.u64())
    {
        a.pFormatProperties = d_VkFormatProperties_partial(r);
    }
    else a.pFormatProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceImageFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.type = r.i32();
    a.tiling = r.i32();
    a.usage = r.u32();
    a.flags = r.u32();
    if(r.u64())
    {
        a.pImageFormatProperties = d_VkImageFormatProperties_partial(r);
    }
    else a.pImageFormatProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pProperties = d_VkPhysicalDeviceProperties_partial(r);
    }
    else a.pProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceQueueFamilyProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    else a.pQueueFamilyPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pQueueFamilyProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pQueueFamilyProperties[i] = d_VkQueueFamilyProperties_partial(r);
        }
    }
    else a.pQueueFamilyProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceMemoryProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pMemoryProperties = d_VkPhysicalDeviceMemoryProperties_partial(r);
    }
    else a.pMemoryProperties = null;
    return a;
}
function d_vkCreateDevice(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkDeviceCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pDevice = r.h();
    }
    else a.pDevice = null;
    return a;
}
function d_vkDestroyDevice(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkEnumerateInstanceExtensionProperties(r)
{
    const a = {};
    const n0 = r.size();
    if(n0)
    {
        a.pLayerName = r.str(n0);
    }
    else a.pLayerName = null;
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n1 = r.size();
    if(n1)
    {
        a.pProperties = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pProperties[i] = d_VkExtensionProperties_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkEnumerateDeviceExtensionProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    const n0 = r.size();
    if(n0)
    {
        a.pLayerName = r.str(n0);
    }
    else a.pLayerName = null;
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n1 = r.size();
    if(n1)
    {
        a.pProperties = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pProperties[i] = d_VkExtensionProperties_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkEnumerateInstanceLayerProperties(r)
{
    const a = {};
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pProperties[i] = d_VkLayerProperties_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkEnumerateDeviceLayerProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pProperties[i] = d_VkLayerProperties_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkGetDeviceQueue(r)
{
    const a = {};
    a.device = r.h();
    a.queueFamilyIndex = r.u32();
    a.queueIndex = r.u32();
    if(r.u64())
    {
        a.pQueue = r.h();
    }
    else a.pQueue = null;
    return a;
}
function d_vkQueueSubmit(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pSubmits = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSubmits[i] = d_VkSubmitInfo(r);
        }
    }
    else a.pSubmits = null;
    a.fence = r.h();
    return a;
}
function d_vkQueueWaitIdle(r)
{
    const a = {};
    a.queue = r.h();
    return a;
}
function d_vkDeviceWaitIdle(r)
{
    const a = {};
    a.device = r.h();
    return a;
}
function d_vkAllocateMemory(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pAllocateInfo = d_VkMemoryAllocateInfo(r);
    }
    else a.pAllocateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pMemory = r.h();
    }
    else a.pMemory = null;
    return a;
}
function d_vkFreeMemory(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkUnmapMemory(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    return a;
}
function d_vkFlushMappedMemoryRanges(r)
{
    const a = {};
    a.device = r.h();
    a.memoryRangeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pMemoryRanges = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pMemoryRanges[i] = d_VkMappedMemoryRange(r);
        }
    }
    else a.pMemoryRanges = null;
    return a;
}
function d_vkInvalidateMappedMemoryRanges(r)
{
    const a = {};
    a.device = r.h();
    a.memoryRangeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pMemoryRanges = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pMemoryRanges[i] = d_VkMappedMemoryRange(r);
        }
    }
    else a.pMemoryRanges = null;
    return a;
}
function d_vkGetDeviceMemoryCommitment(r)
{
    const a = {};
    a.device = r.h();
    a.memory = r.h();
    a.pCommittedMemoryInBytes = r.u64() ? 0 : null;
    return a;
}
function d_vkBindBufferMemory(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    a.memory = r.h();
    a.memoryOffset = r.u64();
    return a;
}
function d_vkBindImageMemory(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    a.memory = r.h();
    a.memoryOffset = r.u64();
    return a;
}
function d_vkGetBufferMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetImageMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetImageSparseMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else a.pSparseMemoryRequirementCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pSparseMemoryRequirements = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements_partial(r);
        }
    }
    else a.pSparseMemoryRequirements = null;
    return a;
}
function d_vkGetPhysicalDeviceSparseImageFormatProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    a.type = r.i32();
    a.samples = r.i32();
    a.usage = r.u32();
    a.tiling = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pProperties[i] = d_VkSparseImageFormatProperties_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkQueueBindSparse(r)
{
    const a = {};
    a.queue = r.h();
    a.bindInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBindInfo = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBindInfo[i] = d_VkBindSparseInfo(r);
        }
    }
    else a.pBindInfo = null;
    a.fence = r.h();
    return a;
}
function d_vkCreateFence(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkFenceCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pFence = r.h();
    }
    else a.pFence = null;
    return a;
}
function d_vkDestroyFence(r)
{
    const a = {};
    a.device = r.h();
    a.fence = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkResetFences(r)
{
    const a = {};
    a.device = r.h();
    a.fenceCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pFences = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pFences[i] = r.h();
        }
    }
    else a.pFences = null;
    return a;
}
function d_vkGetFenceStatus(r)
{
    const a = {};
    a.device = r.h();
    a.fence = r.h();
    return a;
}
function d_vkWaitForFences(r)
{
    const a = {};
    a.device = r.h();
    a.fenceCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pFences = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pFences[i] = r.h();
        }
    }
    else a.pFences = null;
    a.waitAll = r.u32();
    a.timeout = r.u64();
    return a;
}
function d_vkCreateSemaphore(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkSemaphoreCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pSemaphore = r.h();
    }
    else a.pSemaphore = null;
    return a;
}
function d_vkDestroySemaphore(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateEvent(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkEventCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pEvent = r.h();
    }
    else a.pEvent = null;
    return a;
}
function d_vkDestroyEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetEventStatus(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function d_vkSetEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function d_vkResetEvent(r)
{
    const a = {};
    a.device = r.h();
    a.event = r.h();
    return a;
}
function d_vkCreateQueryPool(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkQueryPoolCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pQueryPool = r.h();
    }
    else a.pQueryPool = null;
    return a;
}
function d_vkDestroyQueryPool(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetQueryPoolResults(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    a.dataSize = r.u64();
    const n0 = r.size();
    a.stride = r.u64();
    a.flags = r.u32();
    return a;
}
function d_vkCreateBuffer(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkBufferCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pBuffer = r.h();
    }
    else a.pBuffer = null;
    return a;
}
function d_vkDestroyBuffer(r)
{
    const a = {};
    a.device = r.h();
    a.buffer = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateBufferView(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkBufferViewCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pView = r.h();
    }
    else a.pView = null;
    return a;
}
function d_vkDestroyBufferView(r)
{
    const a = {};
    a.device = r.h();
    a.bufferView = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateImage(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkImageCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pImage = r.h();
    }
    else a.pImage = null;
    return a;
}
function d_vkDestroyImage(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetImageSubresourceLayout(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
        a.pSubresource = d_VkImageSubresource(r);
    }
    else a.pSubresource = null;
    if(r.u64())
    {
        a.pLayout = d_VkSubresourceLayout_partial(r);
    }
    else a.pLayout = null;
    return a;
}
function d_vkCreateImageView(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkImageViewCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pView = r.h();
    }
    else a.pView = null;
    return a;
}
function d_vkDestroyImageView(r)
{
    const a = {};
    a.device = r.h();
    a.imageView = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateShaderModule(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkShaderModuleCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pShaderModule = r.h();
    }
    else a.pShaderModule = null;
    return a;
}
function d_vkDestroyShaderModule(r)
{
    const a = {};
    a.device = r.h();
    a.shaderModule = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreatePipelineCache(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkPipelineCacheCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pPipelineCache = r.h();
    }
    else a.pPipelineCache = null;
    return a;
}
function d_vkDestroyPipelineCache(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetPipelineCacheData(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    if(r.u64())
    {
        a.pDataSize = r.u64();
    }
    else a.pDataSize = null;
    const n0 = r.size();
    return a;
}
function d_vkMergePipelineCaches(r)
{
    const a = {};
    a.device = r.h();
    a.dstCache = r.h();
    a.srcCacheCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pSrcCaches = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSrcCaches[i] = r.h();
        }
    }
    else a.pSrcCaches = null;
    return a;
}
function d_vkCreateGraphicsPipelines(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    a.createInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCreateInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCreateInfos[i] = d_VkGraphicsPipelineCreateInfo(r);
        }
    }
    else a.pCreateInfos = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    const n1 = r.size();
    if(n1)
    {
        a.pPipelines = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pPipelines[i] = r.h();
        }
    }
    else a.pPipelines = null;
    return a;
}
function d_vkCreateComputePipelines(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineCache = r.h();
    a.createInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCreateInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCreateInfos[i] = d_VkComputePipelineCreateInfo(r);
        }
    }
    else a.pCreateInfos = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    const n1 = r.size();
    if(n1)
    {
        a.pPipelines = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pPipelines[i] = r.h();
        }
    }
    else a.pPipelines = null;
    return a;
}
function d_vkDestroyPipeline(r)
{
    const a = {};
    a.device = r.h();
    a.pipeline = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreatePipelineLayout(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkPipelineLayoutCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pPipelineLayout = r.h();
    }
    else a.pPipelineLayout = null;
    return a;
}
function d_vkDestroyPipelineLayout(r)
{
    const a = {};
    a.device = r.h();
    a.pipelineLayout = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateSampler(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkSamplerCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pSampler = r.h();
    }
    else a.pSampler = null;
    return a;
}
function d_vkDestroySampler(r)
{
    const a = {};
    a.device = r.h();
    a.sampler = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateDescriptorSetLayout(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkDescriptorSetLayoutCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pSetLayout = r.h();
    }
    else a.pSetLayout = null;
    return a;
}
function d_vkDestroyDescriptorSetLayout(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorSetLayout = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkDescriptorPoolCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pDescriptorPool = r.h();
    }
    else a.pDescriptorPool = null;
    return a;
}
function d_vkDestroyDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkResetDescriptorPool(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkAllocateDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pAllocateInfo = d_VkDescriptorSetAllocateInfo(r);
    }
    else a.pAllocateInfo = null;
    const n0 = r.size();
    if(n0)
    {
        a.pDescriptorSets = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pDescriptorSets[i] = r.h();
        }
    }
    else a.pDescriptorSets = null;
    return a;
}
function d_vkFreeDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorPool = r.h();
    a.descriptorSetCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pDescriptorSets = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pDescriptorSets[i] = r.h();
        }
    }
    else a.pDescriptorSets = null;
    return a;
}
function d_vkUpdateDescriptorSets(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorWriteCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pDescriptorWrites = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r);
        }
    }
    else a.pDescriptorWrites = null;
    a.descriptorCopyCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pDescriptorCopies = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pDescriptorCopies[i] = d_VkCopyDescriptorSet(r);
        }
    }
    else a.pDescriptorCopies = null;
    return a;
}
function d_vkCreateFramebuffer(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkFramebufferCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pFramebuffer = r.h();
    }
    else a.pFramebuffer = null;
    return a;
}
function d_vkDestroyFramebuffer(r)
{
    const a = {};
    a.device = r.h();
    a.framebuffer = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateRenderPass(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkRenderPassCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pRenderPass = r.h();
    }
    else a.pRenderPass = null;
    return a;
}
function d_vkDestroyRenderPass(r)
{
    const a = {};
    a.device = r.h();
    a.renderPass = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetRenderAreaGranularity(r)
{
    const a = {};
    a.device = r.h();
    a.renderPass = r.h();
    if(r.u64())
    {
        a.pGranularity = d_VkExtent2D_partial(r);
    }
    else a.pGranularity = null;
    return a;
}
function d_vkCreateCommandPool(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkCommandPoolCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pCommandPool = r.h();
    }
    else a.pCommandPool = null;
    return a;
}
function d_vkDestroyCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkResetCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkAllocateCommandBuffers(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pAllocateInfo = d_VkCommandBufferAllocateInfo(r);
    }
    else a.pAllocateInfo = null;
    const n0 = r.size();
    if(n0)
    {
        a.pCommandBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCommandBuffers[i] = r.h();
        }
    }
    else a.pCommandBuffers = null;
    return a;
}
function d_vkFreeCommandBuffers(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.commandBufferCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCommandBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCommandBuffers[i] = r.h();
        }
    }
    else a.pCommandBuffers = null;
    return a;
}
function d_vkBeginCommandBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pBeginInfo = d_VkCommandBufferBeginInfo(r);
    }
    else a.pBeginInfo = null;
    return a;
}
function d_vkEndCommandBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    return a;
}
function d_vkResetCommandBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkCmdBindPipeline(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.pipelineBindPoint = r.i32();
    a.pipeline = r.h();
    return a;
}
function d_vkCmdSetViewport(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstViewport = r.u32();
    a.viewportCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pViewports = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pViewports[i] = d_VkViewport(r);
        }
    }
    else a.pViewports = null;
    return a;
}
function d_vkCmdSetScissor(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstScissor = r.u32();
    a.scissorCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pScissors = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pScissors[i] = d_VkRect2D(r);
        }
    }
    else a.pScissors = null;
    return a;
}
function d_vkCmdSetLineWidth(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.lineWidth = r.f32();
    return a;
}
function d_vkCmdSetDepthBias(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthBiasConstantFactor = r.f32();
    a.depthBiasClamp = r.f32();
    a.depthBiasSlopeFactor = r.f32();
    return a;
}
function d_vkCmdSetBlendConstants(r)
{
    const a = {};
    a.commandBuffer = r.h();
    const n0 = r.size();
    a.blendConstants = r.f32s(n0);
    return a;
}
function d_vkCmdSetDepthBounds(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.minDepthBounds = r.f32();
    a.maxDepthBounds = r.f32();
    return a;
}
function d_vkCmdSetStencilCompareMask(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.faceMask = r.u32();
    a.compareMask = r.u32();
    return a;
}
function d_vkCmdSetStencilWriteMask(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.faceMask = r.u32();
    a.writeMask = r.u32();
    return a;
}
function d_vkCmdSetStencilReference(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.faceMask = r.u32();
    a.reference = r.u32();
    return a;
}
function d_vkCmdBindDescriptorSets(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.pipelineBindPoint = r.i32();
    a.layout = r.h();
    a.firstSet = r.u32();
    a.descriptorSetCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pDescriptorSets = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pDescriptorSets[i] = r.h();
        }
    }
    else a.pDescriptorSets = null;
    a.dynamicOffsetCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pDynamicOffsets = r.u32s(n1);
    }
    else a.pDynamicOffsets = null;
    return a;
}
function d_vkCmdBindIndexBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.indexType = r.i32();
    return a;
}
function d_vkCmdBindVertexBuffers(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBuffers[i] = r.h();
        }
    }
    else a.pBuffers = null;
    const n1 = r.size();
    if(n1)
    {
        a.pOffsets = r.u64s(n1);
    }
    else a.pOffsets = null;
    return a;
}
function d_vkCmdDraw(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.vertexCount = r.u32();
    a.instanceCount = r.u32();
    a.firstVertex = r.u32();
    a.firstInstance = r.u32();
    return a;
}
function d_vkCmdDrawIndexed(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.indexCount = r.u32();
    a.instanceCount = r.u32();
    a.firstIndex = r.u32();
    a.vertexOffset = r.i32();
    a.firstInstance = r.u32();
    return a;
}
function d_vkCmdDrawIndirect(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.drawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawIndexedIndirect(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.drawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDispatch(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.groupCountX = r.u32();
    a.groupCountY = r.u32();
    a.groupCountZ = r.u32();
    return a;
}
function d_vkCmdDispatchIndirect(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    return a;
}
function d_vkCmdCopyBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcBuffer = r.h();
    a.dstBuffer = r.h();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkBufferCopy(r);
        }
    }
    else a.pRegions = null;
    return a;
}
function d_vkCmdCopyImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkImageCopy(r);
        }
    }
    else a.pRegions = null;
    return a;
}
function d_vkCmdBlitImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkImageBlit(r);
        }
    }
    else a.pRegions = null;
    a.filter = r.i32();
    return a;
}
function d_vkCmdCopyBufferToImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcBuffer = r.h();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkBufferImageCopy(r);
        }
    }
    else a.pRegions = null;
    return a;
}
function d_vkCmdCopyImageToBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstBuffer = r.h();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkBufferImageCopy(r);
        }
    }
    else a.pRegions = null;
    return a;
}
function d_vkCmdUpdateBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.dataSize = r.u64();
    const n0 = r.size();
    if(n0)
    {
        a.pData = r.blob(n0);
    }
    else a.pData = null;
    return a;
}
function d_vkCmdFillBuffer(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.size = r.u64();
    a.data = r.u32();
    return a;
}
function d_vkCmdClearColorImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.image = r.h();
    a.imageLayout = r.i32();
    if(r.u64())
    {
        a.pColor = d_VkClearColorValue(r);
    }
    else a.pColor = null;
    a.rangeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRanges = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRanges[i] = d_VkImageSubresourceRange(r);
        }
    }
    else a.pRanges = null;
    return a;
}
function d_vkCmdClearDepthStencilImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.image = r.h();
    a.imageLayout = r.i32();
    if(r.u64())
    {
        a.pDepthStencil = d_VkClearDepthStencilValue(r);
    }
    else a.pDepthStencil = null;
    a.rangeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRanges = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRanges[i] = d_VkImageSubresourceRange(r);
        }
    }
    else a.pRanges = null;
    return a;
}
function d_vkCmdClearAttachments(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pAttachments[i] = d_VkClearAttachment(r);
        }
    }
    else a.pAttachments = null;
    a.rectCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pRects = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pRects[i] = d_VkClearRect(r);
        }
    }
    else a.pRects = null;
    return a;
}
function d_vkCmdResolveImage(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcImage = r.h();
    a.srcImageLayout = r.i32();
    a.dstImage = r.h();
    a.dstImageLayout = r.i32();
    a.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pRegions[i] = d_VkImageResolve(r);
        }
    }
    else a.pRegions = null;
    return a;
}
function d_vkCmdSetEvent(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.event = r.h();
    a.stageMask = r.u32();
    return a;
}
function d_vkCmdResetEvent(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.event = r.h();
    a.stageMask = r.u32();
    return a;
}
function d_vkCmdWaitEvents(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.eventCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pEvents = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pEvents[i] = r.h();
        }
    }
    else a.pEvents = null;
    a.srcStageMask = r.u32();
    a.dstStageMask = r.u32();
    a.memoryBarrierCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pMemoryBarriers = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pMemoryBarriers[i] = d_VkMemoryBarrier(r);
        }
    }
    else a.pMemoryBarriers = null;
    a.bufferMemoryBarrierCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        a.pBufferMemoryBarriers = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            a.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier(r);
        }
    }
    else a.pBufferMemoryBarriers = null;
    a.imageMemoryBarrierCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        a.pImageMemoryBarriers = new Array(n3);
        for(let i = 0; i < n3; i++)
        {
            a.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier(r);
        }
    }
    else a.pImageMemoryBarriers = null;
    return a;
}
function d_vkCmdPipelineBarrier(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.srcStageMask = r.u32();
    a.dstStageMask = r.u32();
    a.dependencyFlags = r.u32();
    a.memoryBarrierCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pMemoryBarriers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pMemoryBarriers[i] = d_VkMemoryBarrier(r);
        }
    }
    else a.pMemoryBarriers = null;
    a.bufferMemoryBarrierCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pBufferMemoryBarriers = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier(r);
        }
    }
    else a.pBufferMemoryBarriers = null;
    a.imageMemoryBarrierCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        a.pImageMemoryBarriers = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            a.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier(r);
        }
    }
    else a.pImageMemoryBarriers = null;
    return a;
}
function d_vkCmdBeginQuery(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.query = r.u32();
    a.flags = r.u32();
    return a;
}
function d_vkCmdEndQuery(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkCmdResetQueryPool(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    return a;
}
function d_vkCmdWriteTimestamp(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.pipelineStage = r.i32();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkCmdCopyQueryPoolResults(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    a.dstBuffer = r.h();
    a.dstOffset = r.u64();
    a.stride = r.u64();
    a.flags = r.u32();
    return a;
}
function d_vkCmdPushConstants(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.layout = r.h();
    a.stageFlags = r.u32();
    a.offset = r.u32();
    a.size = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pValues = r.blob(n0);
    }
    else a.pValues = null;
    return a;
}
function d_vkCmdBeginRenderPass(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pRenderPassBegin = d_VkRenderPassBeginInfo(r);
    }
    else a.pRenderPassBegin = null;
    a.contents = r.i32();
    return a;
}
function d_vkCmdNextSubpass(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.contents = r.i32();
    return a;
}
function d_vkCmdEndRenderPass(r)
{
    const a = {};
    a.commandBuffer = r.h();
    return a;
}
function d_vkCmdExecuteCommands(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.commandBufferCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCommandBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCommandBuffers[i] = r.h();
        }
    }
    else a.pCommandBuffers = null;
    return a;
}
function d_vkEnumerateInstanceVersion(r)
{
    const a = {};
    a.pApiVersion = r.u64() ? 0 : null;
    return a;
}
function d_vkBindBufferMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBindInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBindInfos[i] = d_VkBindBufferMemoryInfo(r);
        }
    }
    else a.pBindInfos = null;
    return a;
}
function d_vkBindImageMemory2(r)
{
    const a = {};
    a.device = r.h();
    a.bindInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBindInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBindInfos[i] = d_VkBindImageMemoryInfo(r);
        }
    }
    else a.pBindInfos = null;
    return a;
}
function d_vkGetDeviceGroupPeerMemoryFeatures(r)
{
    const a = {};
    a.device = r.h();
    a.heapIndex = r.u32();
    a.localDeviceIndex = r.u32();
    a.remoteDeviceIndex = r.u32();
    a.pPeerMemoryFeatures = r.u64() ? 0 : null;
    return a;
}
function d_vkCmdSetDeviceMask(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.deviceMask = r.u32();
    return a;
}
function d_vkCmdDispatchBase(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.baseGroupX = r.u32();
    a.baseGroupY = r.u32();
    a.baseGroupZ = r.u32();
    a.groupCountX = r.u32();
    a.groupCountY = r.u32();
    a.groupCountZ = r.u32();
    return a;
}
function d_vkEnumeratePhysicalDeviceGroups(r)
{
    const a = {};
    a.instance = r.h();
    if(r.u64())
    {
        a.pPhysicalDeviceGroupCount = r.u32();
    }
    else a.pPhysicalDeviceGroupCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pPhysicalDeviceGroupProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pPhysicalDeviceGroupProperties[i] = d_VkPhysicalDeviceGroupProperties_partial(r);
        }
    }
    else a.pPhysicalDeviceGroupProperties = null;
    return a;
}
function d_vkGetImageMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkImageMemoryRequirementsInfo2(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements2_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetBufferMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkBufferMemoryRequirementsInfo2(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements2_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetImageSparseMemoryRequirements2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkImageSparseMemoryRequirementsInfo2(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else a.pSparseMemoryRequirementCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pSparseMemoryRequirements = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2_partial(r);
        }
    }
    else a.pSparseMemoryRequirements = null;
    return a;
}
function d_vkGetPhysicalDeviceFeatures2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pFeatures = d_VkPhysicalDeviceFeatures2_partial(r);
    }
    else a.pFeatures = null;
    return a;
}
function d_vkGetPhysicalDeviceProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pProperties = d_VkPhysicalDeviceProperties2_partial(r);
    }
    else a.pProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.format = r.i32();
    if(r.u64())
    {
        a.pFormatProperties = d_VkFormatProperties2_partial(r);
    }
    else a.pFormatProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceImageFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pImageFormatInfo = d_VkPhysicalDeviceImageFormatInfo2(r);
    }
    else a.pImageFormatInfo = null;
    if(r.u64())
    {
        a.pImageFormatProperties = d_VkImageFormatProperties2_partial(r);
    }
    else a.pImageFormatProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceQueueFamilyProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    else a.pQueueFamilyPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pQueueFamilyProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pQueueFamilyProperties[i] = d_VkQueueFamilyProperties2_partial(r);
        }
    }
    else a.pQueueFamilyProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceMemoryProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pMemoryProperties = d_VkPhysicalDeviceMemoryProperties2_partial(r);
    }
    else a.pMemoryProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceSparseImageFormatProperties2(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pFormatInfo = d_VkPhysicalDeviceSparseImageFormatInfo2(r);
    }
    else a.pFormatInfo = null;
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pProperties[i] = d_VkSparseImageFormatProperties2_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkTrimCommandPool(r)
{
    const a = {};
    a.device = r.h();
    a.commandPool = r.h();
    a.flags = r.u32();
    return a;
}
function d_vkGetDeviceQueue2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pQueueInfo = d_VkDeviceQueueInfo2(r);
    }
    else a.pQueueInfo = null;
    if(r.u64())
    {
        a.pQueue = r.h();
    }
    else a.pQueue = null;
    return a;
}
function d_vkCreateSamplerYcbcrConversion(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkSamplerYcbcrConversionCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pYcbcrConversion = r.h();
    }
    else a.pYcbcrConversion = null;
    return a;
}
function d_vkDestroySamplerYcbcrConversion(r)
{
    const a = {};
    a.device = r.h();
    a.ycbcrConversion = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkCreateDescriptorUpdateTemplate(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkDescriptorUpdateTemplateCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pDescriptorUpdateTemplate = r.h();
    }
    else a.pDescriptorUpdateTemplate = null;
    return a;
}
function d_vkDestroyDescriptorUpdateTemplate(r)
{
    const a = {};
    a.device = r.h();
    a.descriptorUpdateTemplate = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetPhysicalDeviceExternalBufferProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pExternalBufferInfo = d_VkPhysicalDeviceExternalBufferInfo(r);
    }
    else a.pExternalBufferInfo = null;
    if(r.u64())
    {
        a.pExternalBufferProperties = d_VkExternalBufferProperties_partial(r);
    }
    else a.pExternalBufferProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceExternalFenceProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pExternalFenceInfo = d_VkPhysicalDeviceExternalFenceInfo(r);
    }
    else a.pExternalFenceInfo = null;
    if(r.u64())
    {
        a.pExternalFenceProperties = d_VkExternalFenceProperties_partial(r);
    }
    else a.pExternalFenceProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceExternalSemaphoreProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pExternalSemaphoreInfo = d_VkPhysicalDeviceExternalSemaphoreInfo(r);
    }
    else a.pExternalSemaphoreInfo = null;
    if(r.u64())
    {
        a.pExternalSemaphoreProperties = d_VkExternalSemaphoreProperties_partial(r);
    }
    else a.pExternalSemaphoreProperties = null;
    return a;
}
function d_vkGetDescriptorSetLayoutSupport(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkDescriptorSetLayoutCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
        a.pSupport = d_VkDescriptorSetLayoutSupport_partial(r);
    }
    else a.pSupport = null;
    return a;
}
function d_vkCmdDrawIndirectCount(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.countBuffer = r.h();
    a.countBufferOffset = r.u64();
    a.maxDrawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawIndexedIndirectCount(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.countBuffer = r.h();
    a.countBufferOffset = r.u64();
    a.maxDrawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCreateRenderPass2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkRenderPassCreateInfo2(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pRenderPass = r.h();
    }
    else a.pRenderPass = null;
    return a;
}
function d_vkCmdBeginRenderPass2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pRenderPassBegin = d_VkRenderPassBeginInfo(r);
    }
    else a.pRenderPassBegin = null;
    if(r.u64())
    {
        a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r);
    }
    else a.pSubpassBeginInfo = null;
    return a;
}
function d_vkCmdNextSubpass2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pSubpassBeginInfo = d_VkSubpassBeginInfo(r);
    }
    else a.pSubpassBeginInfo = null;
    if(r.u64())
    {
        a.pSubpassEndInfo = d_VkSubpassEndInfo(r);
    }
    else a.pSubpassEndInfo = null;
    return a;
}
function d_vkCmdEndRenderPass2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pSubpassEndInfo = d_VkSubpassEndInfo(r);
    }
    else a.pSubpassEndInfo = null;
    return a;
}
function d_vkResetQueryPool(r)
{
    const a = {};
    a.device = r.h();
    a.queryPool = r.h();
    a.firstQuery = r.u32();
    a.queryCount = r.u32();
    return a;
}
function d_vkGetSemaphoreCounterValue(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    a.pValue = r.u64() ? 0 : null;
    return a;
}
function d_vkWaitSemaphores(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pWaitInfo = d_VkSemaphoreWaitInfo(r);
    }
    else a.pWaitInfo = null;
    a.timeout = r.u64();
    return a;
}
function d_vkSignalSemaphore(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pSignalInfo = d_VkSemaphoreSignalInfo(r);
    }
    else a.pSignalInfo = null;
    return a;
}
function d_vkGetBufferDeviceAddress(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkBufferDeviceAddressInfo(r);
    }
    else a.pInfo = null;
    return a;
}
function d_vkGetBufferOpaqueCaptureAddress(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkBufferDeviceAddressInfo(r);
    }
    else a.pInfo = null;
    return a;
}
function d_vkGetDeviceMemoryOpaqueCaptureAddress(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkDeviceMemoryOpaqueCaptureAddressInfo(r);
    }
    else a.pInfo = null;
    return a;
}
function d_vkSetReplyCommandStreamMESA(r)
{
    const a = {};
    if(r.u64())
    {
        a.pStream = d_VkCommandStreamDescriptionMESA(r);
    }
    else a.pStream = null;
    return a;
}
function d_vkSeekReplyCommandStreamMESA(r)
{
    const a = {};
    a.position = r.u64();
    return a;
}
function d_vkExecuteCommandStreamsMESA(r)
{
    const a = {};
    a.streamCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pStreams = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pStreams[i] = d_VkCommandStreamDescriptionMESA(r);
        }
    }
    else a.pStreams = null;
    const n1 = r.size();
    if(n1)
    {
        a.pReplyPositions = r.u64s(n1);
    }
    else a.pReplyPositions = null;
    a.dependencyCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        a.pDependencies = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            a.pDependencies[i] = d_VkCommandStreamDependencyMESA(r);
        }
    }
    else a.pDependencies = null;
    a.flags = r.u32();
    return a;
}
function d_vkCmdBindTransformFeedbackBuffersEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBuffers[i] = r.h();
        }
    }
    else a.pBuffers = null;
    const n1 = r.size();
    if(n1)
    {
        a.pOffsets = r.u64s(n1);
    }
    else a.pOffsets = null;
    const n2 = r.size();
    if(n2)
    {
        a.pSizes = r.u64s(n2);
    }
    else a.pSizes = null;
    return a;
}
function d_vkCmdBeginTransformFeedbackEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstCounterBuffer = r.u32();
    a.counterBufferCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCounterBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCounterBuffers[i] = r.h();
        }
    }
    else a.pCounterBuffers = null;
    const n1 = r.size();
    if(n1)
    {
        a.pCounterBufferOffsets = r.u64s(n1);
    }
    else a.pCounterBufferOffsets = null;
    return a;
}
function d_vkCmdEndTransformFeedbackEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstCounterBuffer = r.u32();
    a.counterBufferCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pCounterBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pCounterBuffers[i] = r.h();
        }
    }
    else a.pCounterBuffers = null;
    const n1 = r.size();
    if(n1)
    {
        a.pCounterBufferOffsets = r.u64s(n1);
    }
    else a.pCounterBufferOffsets = null;
    return a;
}
function d_vkCmdBeginQueryIndexedEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.query = r.u32();
    a.flags = r.u32();
    a.index = r.u32();
    return a;
}
function d_vkCmdEndQueryIndexedEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.queryPool = r.h();
    a.query = r.u32();
    a.index = r.u32();
    return a;
}
function d_vkCmdDrawIndirectByteCountEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.instanceCount = r.u32();
    a.firstInstance = r.u32();
    a.counterBuffer = r.h();
    a.counterBufferOffset = r.u64();
    a.counterOffset = r.u32();
    a.vertexStride = r.u32();
    return a;
}
function d_vkGetImageDrmFormatModifierPropertiesEXT(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
        a.pProperties = d_VkImageDrmFormatModifierPropertiesEXT_partial(r);
    }
    else a.pProperties = null;
    return a;
}
function d_vkCreateRingMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    if(r.u64())
    {
        a.pCreateInfo = d_VkRingCreateInfoMESA(r);
    }
    else a.pCreateInfo = null;
    return a;
}
function d_vkDestroyRingMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    return a;
}
function d_vkNotifyRingMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    a.seqno = r.u32();
    a.flags = r.u32();
    return a;
}
function d_vkWriteRingExtraMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    a.offset = r.u64();
    a.value = r.u32();
    return a;
}
function d_vkGetMemoryResourcePropertiesMESA(r)
{
    const a = {};
    a.device = r.h();
    a.resourceId = r.u32();
    if(r.u64())
    {
        a.pMemoryResourceProperties = d_VkMemoryResourcePropertiesMESA_partial(r);
    }
    else a.pMemoryResourceProperties = null;
    return a;
}
function d_vkGetPhysicalDeviceToolProperties(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pToolCount = r.u32();
    }
    else a.pToolCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pToolProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pToolProperties[i] = d_VkPhysicalDeviceToolProperties_partial(r);
        }
    }
    else a.pToolProperties = null;
    return a;
}
function d_vkCreatePrivateDataSlot(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCreateInfo = d_VkPrivateDataSlotCreateInfo(r);
    }
    else a.pCreateInfo = null;
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pPrivateDataSlot = r.h();
    }
    else a.pPrivateDataSlot = null;
    return a;
}
function d_vkDestroyPrivateDataSlot(r)
{
    const a = {};
    a.device = r.h();
    a.privateDataSlot = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkSetPrivateData(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.data = r.u64();
    return a;
}
function d_vkGetPrivateData(r)
{
    const a = {};
    a.device = r.h();
    a.objectType = r.i32();
    a.objectHandle = r.u64();
    a.privateDataSlot = r.h();
    a.pData = r.u64() ? 0 : null;
    return a;
}
function d_vkCmdSetEvent2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.event = r.h();
    if(r.u64())
    {
        a.pDependencyInfo = d_VkDependencyInfo(r);
    }
    else a.pDependencyInfo = null;
    return a;
}
function d_vkCmdResetEvent2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.event = r.h();
    a.stageMask = r.u64();
    return a;
}
function d_vkCmdWaitEvents2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.eventCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pEvents = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pEvents[i] = r.h();
        }
    }
    else a.pEvents = null;
    const n1 = r.size();
    if(n1)
    {
        a.pDependencyInfos = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pDependencyInfos[i] = d_VkDependencyInfo(r);
        }
    }
    else a.pDependencyInfos = null;
    return a;
}
function d_vkCmdPipelineBarrier2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pDependencyInfo = d_VkDependencyInfo(r);
    }
    else a.pDependencyInfo = null;
    return a;
}
function d_vkCmdWriteTimestamp2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.stage = r.u64();
    a.queryPool = r.h();
    a.query = r.u32();
    return a;
}
function d_vkQueueSubmit2(r)
{
    const a = {};
    a.queue = r.h();
    a.submitCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pSubmits = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSubmits[i] = d_VkSubmitInfo2(r);
        }
    }
    else a.pSubmits = null;
    a.fence = r.h();
    return a;
}
function d_vkCmdCopyBuffer2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pCopyBufferInfo = d_VkCopyBufferInfo2(r);
    }
    else a.pCopyBufferInfo = null;
    return a;
}
function d_vkCmdCopyImage2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pCopyImageInfo = d_VkCopyImageInfo2(r);
    }
    else a.pCopyImageInfo = null;
    return a;
}
function d_vkCmdCopyBufferToImage2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pCopyBufferToImageInfo = d_VkCopyBufferToImageInfo2(r);
    }
    else a.pCopyBufferToImageInfo = null;
    return a;
}
function d_vkCmdCopyImageToBuffer2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pCopyImageToBufferInfo = d_VkCopyImageToBufferInfo2(r);
    }
    else a.pCopyImageToBufferInfo = null;
    return a;
}
function d_vkCmdBlitImage2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pBlitImageInfo = d_VkBlitImageInfo2(r);
    }
    else a.pBlitImageInfo = null;
    return a;
}
function d_vkCmdResolveImage2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pResolveImageInfo = d_VkResolveImageInfo2(r);
    }
    else a.pResolveImageInfo = null;
    return a;
}
function d_vkCmdBeginRendering(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pRenderingInfo = d_VkRenderingInfo(r);
    }
    else a.pRenderingInfo = null;
    return a;
}
function d_vkCmdEndRendering(r)
{
    const a = {};
    a.commandBuffer = r.h();
    return a;
}
function d_vkCmdSetCullMode(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.cullMode = r.u32();
    return a;
}
function d_vkCmdSetFrontFace(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.frontFace = r.i32();
    return a;
}
function d_vkCmdSetPrimitiveTopology(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.primitiveTopology = r.i32();
    return a;
}
function d_vkCmdSetViewportWithCount(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.viewportCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pViewports = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pViewports[i] = d_VkViewport(r);
        }
    }
    else a.pViewports = null;
    return a;
}
function d_vkCmdSetScissorWithCount(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.scissorCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pScissors = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pScissors[i] = d_VkRect2D(r);
        }
    }
    else a.pScissors = null;
    return a;
}
function d_vkCmdBindVertexBuffers2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstBinding = r.u32();
    a.bindingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pBuffers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pBuffers[i] = r.h();
        }
    }
    else a.pBuffers = null;
    const n1 = r.size();
    if(n1)
    {
        a.pOffsets = r.u64s(n1);
    }
    else a.pOffsets = null;
    const n2 = r.size();
    if(n2)
    {
        a.pSizes = r.u64s(n2);
    }
    else a.pSizes = null;
    const n3 = r.size();
    if(n3)
    {
        a.pStrides = r.u64s(n3);
    }
    else a.pStrides = null;
    return a;
}
function d_vkCmdSetDepthTestEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthTestEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthWriteEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthWriteEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthCompareOp(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthCompareOp = r.i32();
    return a;
}
function d_vkCmdSetDepthBoundsTestEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthBoundsTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilTestEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.stencilTestEnable = r.u32();
    return a;
}
function d_vkCmdSetStencilOp(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.faceMask = r.u32();
    a.failOp = r.i32();
    a.passOp = r.i32();
    a.depthFailOp = r.i32();
    a.compareOp = r.i32();
    return a;
}
function d_vkCmdSetRasterizerDiscardEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.rasterizerDiscardEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthBiasEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthBiasEnable = r.u32();
    return a;
}
function d_vkCmdSetPrimitiveRestartEnable(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.primitiveRestartEnable = r.u32();
    return a;
}
function d_vkGetDeviceBufferMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkDeviceBufferMemoryRequirements(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements2_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetDeviceImageMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkDeviceImageMemoryRequirements(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pMemoryRequirements = d_VkMemoryRequirements2_partial(r);
    }
    else a.pMemoryRequirements = null;
    return a;
}
function d_vkGetDeviceImageSparseMemoryRequirements(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkDeviceImageMemoryRequirements(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else a.pSparseMemoryRequirementCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pSparseMemoryRequirements = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pSparseMemoryRequirements[i] = d_VkSparseImageMemoryRequirements2_partial(r);
        }
    }
    else a.pSparseMemoryRequirements = null;
    return a;
}
function d_vkCmdSetPatchControlPointsEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.patchControlPoints = r.u32();
    return a;
}
function d_vkCmdSetLogicOpEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.logicOp = r.i32();
    return a;
}
function d_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pTimeDomainCount = r.u32();
    }
    else a.pTimeDomainCount = null;
    const n0 = r.size();
    return a;
}
function d_vkGetCalibratedTimestampsKHR(r)
{
    const a = {};
    a.device = r.h();
    a.timestampCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pTimestampInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pTimestampInfos[i] = d_VkCalibratedTimestampInfoKHR(r);
        }
    }
    else a.pTimestampInfos = null;
    const n1 = r.size();
    a.pMaxDeviation = r.u64() ? 0 : null;
    return a;
}
function d_vkCmdSetLineStipple(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.lineStippleFactor = r.u32();
    a.lineStipplePattern = r.u16();
    return a;
}
function d_vkCmdBeginConditionalRenderingEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pConditionalRenderingBegin = d_VkConditionalRenderingBeginInfoEXT(r);
    }
    else a.pConditionalRenderingBegin = null;
    return a;
}
function d_vkCmdEndConditionalRenderingEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    return a;
}
function d_vkResetFenceResourceMESA(r)
{
    const a = {};
    a.device = r.h();
    a.fence = r.h();
    return a;
}
function d_vkWaitSemaphoreResourceMESA(r)
{
    const a = {};
    a.device = r.h();
    a.semaphore = r.h();
    return a;
}
function d_vkImportSemaphoreResourceMESA(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pImportSemaphoreResourceInfo = d_VkImportSemaphoreResourceInfoMESA(r);
    }
    else a.pImportSemaphoreResourceInfo = null;
    return a;
}
function d_vkCmdDrawMultiEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.drawCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pVertexInfo = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pVertexInfo[i] = d_VkMultiDrawInfoEXT(r);
        }
    }
    else a.pVertexInfo = null;
    a.instanceCount = r.u32();
    a.firstInstance = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawMultiIndexedEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.drawCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pIndexInfo = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pIndexInfo[i] = d_VkMultiDrawIndexedInfoEXT(r);
        }
    }
    else a.pIndexInfo = null;
    a.instanceCount = r.u32();
    a.firstInstance = r.u32();
    a.stride = r.u32();
    if(r.u64())
    {
        a.pVertexOffset = r.i32();
    }
    else a.pVertexOffset = null;
    return a;
}
function d_vkCmdPushDescriptorSet(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.pipelineBindPoint = r.i32();
    a.layout = r.h();
    a.set = r.u32();
    a.descriptorWriteCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pDescriptorWrites = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r);
        }
    }
    else a.pDescriptorWrites = null;
    return a;
}
function d_vkSubmitVirtqueueSeqnoMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    a.seqno = r.u64();
    return a;
}
function d_vkWaitVirtqueueSeqnoMESA(r)
{
    const a = {};
    a.seqno = r.u64();
    return a;
}
function d_vkWaitRingSeqnoMESA(r)
{
    const a = {};
    a.ring = r.ring_id();
    a.seqno = r.u64();
    return a;
}
function d_vkCmdSetColorWriteEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pColorWriteEnables = r.u32s(n0);
    }
    else a.pColorWriteEnables = null;
    return a;
}
function d_vkCmdSetVertexInputEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.vertexBindingDescriptionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pVertexBindingDescriptions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pVertexBindingDescriptions[i] = d_VkVertexInputBindingDescription2EXT(r);
        }
    }
    else a.pVertexBindingDescriptions = null;
    a.vertexAttributeDescriptionCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        a.pVertexAttributeDescriptions = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pVertexAttributeDescriptions[i] = d_VkVertexInputAttributeDescription2EXT(r);
        }
    }
    else a.pVertexAttributeDescriptions = null;
    return a;
}
function d_vkCmdSetTessellationDomainOriginEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.domainOrigin = r.i32();
    return a;
}
function d_vkCmdSetDepthClampEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthClampEnable = r.u32();
    return a;
}
function d_vkCmdSetPolygonModeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.polygonMode = r.i32();
    return a;
}
function d_vkCmdSetRasterizationSamplesEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.rasterizationSamples = r.i32();
    return a;
}
function d_vkCmdSetSampleMaskEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.samples = r.i32();
    const n0 = r.size();
    if(n0)
    {
        a.pSampleMask = r.u32s(n0);
    }
    else a.pSampleMask = null;
    return a;
}
function d_vkCmdSetAlphaToCoverageEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.alphaToCoverageEnable = r.u32();
    return a;
}
function d_vkCmdSetAlphaToOneEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.alphaToOneEnable = r.u32();
    return a;
}
function d_vkCmdSetLogicOpEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.logicOpEnable = r.u32();
    return a;
}
function d_vkCmdSetColorBlendEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstAttachment = r.u32();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pColorBlendEnables = r.u32s(n0);
    }
    else a.pColorBlendEnables = null;
    return a;
}
function d_vkCmdSetColorBlendEquationEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstAttachment = r.u32();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pColorBlendEquations = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pColorBlendEquations[i] = d_VkColorBlendEquationEXT(r);
        }
    }
    else a.pColorBlendEquations = null;
    return a;
}
function d_vkCmdSetColorWriteMaskEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstAttachment = r.u32();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pColorWriteMasks = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pColorWriteMasks[i] = r.u32();
        }
    }
    else a.pColorWriteMasks = null;
    return a;
}
function d_vkCmdSetRasterizationStreamEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.rasterizationStream = r.u32();
    return a;
}
function d_vkCmdSetConservativeRasterizationModeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.conservativeRasterizationMode = r.i32();
    return a;
}
function d_vkCmdSetExtraPrimitiveOverestimationSizeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.extraPrimitiveOverestimationSize = r.f32();
    return a;
}
function d_vkCmdSetDepthClipEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthClipEnable = r.u32();
    return a;
}
function d_vkCmdSetSampleLocationsEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.sampleLocationsEnable = r.u32();
    return a;
}
function d_vkCmdSetColorBlendAdvancedEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.firstAttachment = r.u32();
    a.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pColorBlendAdvanced = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pColorBlendAdvanced[i] = d_VkColorBlendAdvancedEXT(r);
        }
    }
    else a.pColorBlendAdvanced = null;
    return a;
}
function d_vkCmdSetProvokingVertexModeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.provokingVertexMode = r.i32();
    return a;
}
function d_vkCmdSetLineRasterizationModeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.lineRasterizationMode = r.i32();
    return a;
}
function d_vkCmdSetLineStippleEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.stippledLineEnable = r.u32();
    return a;
}
function d_vkCmdSetDepthClipNegativeOneToOneEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.negativeOneToOne = r.u32();
    return a;
}
function d_vkGetPhysicalDeviceFragmentShadingRatesKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pFragmentShadingRateCount = r.u32();
    }
    else a.pFragmentShadingRateCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pFragmentShadingRates = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pFragmentShadingRates[i] = d_VkPhysicalDeviceFragmentShadingRateKHR_partial(r);
        }
    }
    else a.pFragmentShadingRates = null;
    return a;
}
function d_vkCmdSetFragmentShadingRateKHR(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pFragmentSize = d_VkExtent2D(r);
    }
    else a.pFragmentSize = null;
    const n0 = r.size();
    a.combinerOps = r.i32s(n0);
    return a;
}
function d_vkCmdBindIndexBuffer2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.size = r.u64();
    a.indexType = r.i32();
    return a;
}
function d_vkGetRenderingAreaGranularity(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pRenderingAreaInfo = d_VkRenderingAreaInfo(r);
    }
    else a.pRenderingAreaInfo = null;
    if(r.u64())
    {
        a.pGranularity = d_VkExtent2D_partial(r);
    }
    else a.pGranularity = null;
    return a;
}
function d_vkGetDeviceImageSubresourceLayout(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pInfo = d_VkDeviceImageSubresourceInfo(r);
    }
    else a.pInfo = null;
    if(r.u64())
    {
        a.pLayout = d_VkSubresourceLayout2_partial(r);
    }
    else a.pLayout = null;
    return a;
}
function d_vkGetImageSubresourceLayout2(r)
{
    const a = {};
    a.device = r.h();
    a.image = r.h();
    if(r.u64())
    {
        a.pSubresource = d_VkImageSubresource2(r);
    }
    else a.pSubresource = null;
    if(r.u64())
    {
        a.pLayout = d_VkSubresourceLayout2_partial(r);
    }
    else a.pLayout = null;
    return a;
}
function d_vkCmdSetSampleLocationsEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pSampleLocationsInfo = d_VkSampleLocationsInfoEXT(r);
    }
    else a.pSampleLocationsInfo = null;
    return a;
}
function d_vkGetPhysicalDeviceMultisamplePropertiesEXT(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.samples = r.i32();
    if(r.u64())
    {
        a.pMultisampleProperties = d_VkMultisamplePropertiesEXT_partial(r);
    }
    else a.pMultisampleProperties = null;
    return a;
}
function d_vkUnmapMemory2(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pMemoryUnmapInfo = d_VkMemoryUnmapInfo(r);
    }
    else a.pMemoryUnmapInfo = null;
    return a;
}
function d_vkCmdSetRenderingAttachmentLocations(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pLocationInfo = d_VkRenderingAttachmentLocationInfo(r);
    }
    else a.pLocationInfo = null;
    return a;
}
function d_vkCmdSetRenderingInputAttachmentIndices(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pInputAttachmentIndexInfo = d_VkRenderingInputAttachmentIndexInfo(r);
    }
    else a.pInputAttachmentIndexInfo = null;
    return a;
}
function d_vkCmdBindDescriptorSets2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pBindDescriptorSetsInfo = d_VkBindDescriptorSetsInfo(r);
    }
    else a.pBindDescriptorSetsInfo = null;
    return a;
}
function d_vkCmdPushConstants2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pPushConstantsInfo = d_VkPushConstantsInfo(r);
    }
    else a.pPushConstantsInfo = null;
    return a;
}
function d_vkCmdPushDescriptorSet2(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pPushDescriptorSetInfo = d_VkPushDescriptorSetInfo(r);
    }
    else a.pPushDescriptorSetInfo = null;
    return a;
}
function d_vkCopyImageToImage(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCopyImageToImageInfo = d_VkCopyImageToImageInfo(r);
    }
    else a.pCopyImageToImageInfo = null;
    return a;
}
function d_vkTransitionImageLayout(r)
{
    const a = {};
    a.device = r.h();
    a.transitionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pTransitions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pTransitions[i] = d_VkHostImageLayoutTransitionInfo(r);
        }
    }
    else a.pTransitions = null;
    return a;
}
function d_vkCopyImageToMemoryMESA(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCopyImageToMemoryInfo = d_VkCopyImageToMemoryInfoMESA(r);
    }
    else a.pCopyImageToMemoryInfo = null;
    a.dataSize = r.u64();
    const n0 = r.size();
    return a;
}
function d_vkCopyMemoryToImageMESA(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pCopyMemoryToImageInfo = d_VkCopyMemoryToImageInfoMESA(r);
    }
    else a.pCopyMemoryToImageInfo = null;
    return a;
}
function d_vkCreateDeferredOperationKHR(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    if(r.u64())
    {
        a.pDeferredOperation = r.h();
    }
    else a.pDeferredOperation = null;
    return a;
}
function d_vkDestroyDeferredOperationKHR(r)
{
    const a = {};
    a.device = r.h();
    a.operation = r.h();
    if(r.u64())
    {
    }
    else a.pAllocator = null;
    return a;
}
function d_vkGetDeferredOperationMaxConcurrencyKHR(r)
{
    const a = {};
    a.device = r.h();
    a.operation = r.h();
    return a;
}
function d_vkGetDeferredOperationResultKHR(r)
{
    const a = {};
    a.device = r.h();
    a.operation = r.h();
    return a;
}
function d_vkDeferredOperationJoinKHR(r)
{
    const a = {};
    a.device = r.h();
    a.operation = r.h();
    return a;
}
function d_vkCmdSetDepthBias2EXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pDepthBiasInfo = d_VkDepthBiasInfoEXT(r);
    }
    else a.pDepthBiasInfo = null;
    return a;
}
function d_vkCmdSetAttachmentFeedbackLoopEnableEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.aspectMask = r.u32();
    return a;
}
function d_vkCmdSetDepthClampRangeEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.depthClampMode = r.i32();
    if(r.u64())
    {
        a.pDepthClampRange = d_VkDepthClampRangeEXT(r);
    }
    else a.pDepthClampRange = null;
    return a;
}
function d_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(r)
{
    const a = {};
    a.physicalDevice = r.h();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else a.pPropertyCount = null;
    const n0 = r.size();
    if(n0)
    {
        a.pProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pProperties[i] = d_VkCooperativeMatrixPropertiesKHR_partial(r);
        }
    }
    else a.pProperties = null;
    return a;
}
function d_vkCmdDrawMeshTasksEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.groupCountX = r.u32();
    a.groupCountY = r.u32();
    a.groupCountZ = r.u32();
    return a;
}
function d_vkCmdDrawMeshTasksIndirectEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.drawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkCmdDrawMeshTasksIndirectCountEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    a.buffer = r.h();
    a.offset = r.u64();
    a.countBuffer = r.h();
    a.countBufferOffset = r.u64();
    a.maxDrawCount = r.u32();
    a.stride = r.u32();
    return a;
}
function d_vkWriteSamplerDescriptorMESA(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pSampler = d_VkSamplerCreateInfo(r);
    }
    else a.pSampler = null;
    a.dataSize = r.u64();
    const n0 = r.size();
    return a;
}
function d_vkWriteResourceDescriptorMESA(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pResource = d_VkResourceDescriptorInfoEXT(r);
    }
    else a.pResource = null;
    a.dataSize = r.u64();
    const n0 = r.size();
    return a;
}
function d_vkCmdBindSamplerHeapEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pBindInfo = d_VkBindHeapInfoEXT(r);
    }
    else a.pBindInfo = null;
    return a;
}
function d_vkCmdBindResourceHeapEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pBindInfo = d_VkBindHeapInfoEXT(r);
    }
    else a.pBindInfo = null;
    return a;
}
function d_vkCmdPushDataEXT(r)
{
    const a = {};
    a.commandBuffer = r.h();
    if(r.u64())
    {
        a.pPushDataInfo = d_VkPushDataInfoEXT(r);
    }
    else a.pPushDataInfo = null;
    return a;
}
function d_vkGetImageOpaqueCaptureDataEXT(r)
{
    const a = {};
    a.device = r.h();
    a.imageCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        a.pImages = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            a.pImages[i] = r.h();
        }
    }
    else a.pImages = null;
    const n1 = r.size();
    if(n1)
    {
        a.pDatas = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            a.pDatas[i] = d_VkHostAddressRangeEXT_partial(r);
        }
    }
    else a.pDatas = null;
    return a;
}
function d_vkGetPhysicalDeviceDescriptorSizeEXT(r)
{
    const a = {};
    a.physicalDevice = r.h();
    a.descriptorType = r.i32();
    return a;
}
function d_vkRegisterCustomBorderColorEXT(r)
{
    const a = {};
    a.device = r.h();
    if(r.u64())
    {
        a.pBorderColor = d_VkSamplerCustomBorderColorCreateInfoEXT(r);
    }
    else a.pBorderColor = null;
    a.requestIndex = r.u32();
    if(r.u64())
    {
        a.pIndex = r.u32();
    }
    else a.pIndex = null;
    return a;
}
function d_vkUnregisterCustomBorderColorEXT(r)
{
    const a = {};
    a.device = r.h();
    a.index = r.u32();
    return a;
}
function d_VkBufferUsageFlags2CreateInfo_self(r, o)
{
    o.usage = r.u64();
}
function d_VkExternalMemoryBufferCreateInfo_self(r, o)
{
    o.handleTypes = r.u32();
}
function d_VkBufferOpaqueCaptureAddressCreateInfo_self(r, o)
{
    o.opaqueCaptureAddress = r.u64();
}
function d_VkBufferDeviceAddressCreateInfoEXT_self(r, o)
{
    o.deviceAddress = r.u64();
}
function d_VkBindBufferMemoryDeviceGroupInfo_self(r, o)
{
    o.deviceIndexCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDeviceIndices = r.u32s(n0);
    }
    else o.pDeviceIndices = null;
}
function d_VkBindMemoryStatus_self(r, o)
{
    if(r.u64())
    {
        o.pResult = r.i32();
    }
    else o.pResult = null;
}
function d_VkCommandBufferInheritanceConditionalRenderingInfoEXT_self(r, o)
{
    o.conditionalRenderingEnable = r.u32();
}
function d_VkCommandBufferInheritanceRenderingInfo_self(r, o)
{
    o.flags = r.u32();
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachmentFormats = r.i32s(n0);
    }
    else o.pColorAttachmentFormats = null;
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    o.rasterizationSamples = r.i32();
}
function d_VkRenderingAttachmentLocationInfo_self(r, o)
{
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachmentLocations = r.u32s(n0);
    }
    else o.pColorAttachmentLocations = null;
}
function d_VkRenderingInputAttachmentIndexInfo_self(r, o)
{
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachmentInputIndices = r.u32s(n0);
    }
    else o.pColorAttachmentInputIndices = null;
    if(r.u64())
    {
        o.pDepthInputAttachmentIndex = r.u32();
    }
    else o.pDepthInputAttachmentIndex = null;
    if(r.u64())
    {
        o.pStencilInputAttachmentIndex = r.u32();
    }
    else o.pStencilInputAttachmentIndex = null;
}
function d_VkCommandBufferInheritanceDescriptorHeapInfoEXT_self(r, o)
{
    if(r.u64())
    {
        o.pSamplerHeapBindInfo = d_VkBindHeapInfoEXT(r);
    }
    else o.pSamplerHeapBindInfo = null;
    if(r.u64())
    {
        o.pResourceHeapBindInfo = d_VkBindHeapInfoEXT(r);
    }
    else o.pResourceHeapBindInfo = null;
}
function d_VkDeviceGroupCommandBufferBeginInfo_self(r, o)
{
    o.deviceMask = r.u32();
}
function d_VkExternalMemoryAcquireUnmodifiedEXT_self(r, o)
{
    o.acquireUnmodifiedMemory = r.u32();
}
function d_VkSampleLocationsInfoEXT_self(r, o)
{
    o.sampleLocationsPerPixel = r.i32();
    o.sampleLocationGridSize = d_VkExtent2D(r);
    o.sampleLocationsCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pSampleLocations = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pSampleLocations[i] = d_VkSampleLocationEXT(r);
        }
    }
    else o.pSampleLocations = null;
}
function d_VkDeviceGroupRenderPassBeginInfo_self(r, o)
{
    o.deviceMask = r.u32();
    o.deviceRenderAreaCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDeviceRenderAreas = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDeviceRenderAreas[i] = d_VkRect2D(r);
        }
    }
    else o.pDeviceRenderAreas = null;
}
function d_VkRenderPassSampleLocationsBeginInfoEXT_self(r, o)
{
    o.attachmentInitialSampleLocationsCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachmentInitialSampleLocations = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachmentInitialSampleLocations[i] = d_VkAttachmentSampleLocationsEXT(r);
        }
    }
    else o.pAttachmentInitialSampleLocations = null;
    o.postSubpassSampleLocationsCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pPostSubpassSampleLocations = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pPostSubpassSampleLocations[i] = d_VkSubpassSampleLocationsEXT(r);
        }
    }
    else o.pPostSubpassSampleLocations = null;
}
function d_VkRenderPassAttachmentBeginInfo_self(r, o)
{
    o.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachments[i] = r.h();
        }
    }
    else o.pAttachments = null;
}
function d_VkMultisampledRenderToSingleSampledInfoEXT_self(r, o)
{
    o.multisampledRenderToSingleSampledEnable = r.u32();
    o.rasterizationSamples = r.i32();
}
function d_VkRenderingFragmentShadingRateAttachmentInfoKHR_self(r, o)
{
    o.imageView = r.h();
    o.imageLayout = r.i32();
    o.shadingRateAttachmentTexelSize = d_VkExtent2D(r);
}
function d_VkDepthBiasRepresentationInfoEXT_self(r, o)
{
    o.depthBiasRepresentation = r.i32();
    o.depthBiasExact = r.u32();
}
function d_VkPipelineLayoutCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.setLayoutCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pSetLayouts = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pSetLayouts[i] = r.h();
        }
    }
    else o.pSetLayouts = null;
    o.pushConstantRangeCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pPushConstantRanges = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pPushConstantRanges[i] = d_VkPushConstantRange(r);
        }
    }
    else o.pPushConstantRanges = null;
}
function d_VkDescriptorPoolInlineUniformBlockCreateInfo_self(r, o)
{
    o.maxInlineUniformBlockBindings = r.u32();
}
function d_VkMutableDescriptorTypeCreateInfoEXT_self(r, o)
{
    o.mutableDescriptorTypeListCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pMutableDescriptorTypeLists = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pMutableDescriptorTypeLists[i] = d_VkMutableDescriptorTypeListEXT(r);
        }
    }
    else o.pMutableDescriptorTypeLists = null;
}
function d_VkDescriptorSetVariableDescriptorCountAllocateInfo_self(r, o)
{
    o.descriptorSetCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDescriptorCounts = r.u32s(n0);
    }
    else o.pDescriptorCounts = null;
}
function d_VkDescriptorSetLayoutBindingFlagsCreateInfo_self(r, o)
{
    o.bindingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pBindingFlags = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pBindingFlags[i] = r.u32();
        }
    }
    else o.pBindingFlags = null;
}
function d_VkDeviceQueueGlobalPriorityCreateInfo_self(r, o)
{
    o.globalPriority = r.i32();
}
function d_VkPhysicalDevicePrivateDataFeatures_self(r, o)
{
    o.privateData = r.u32();
}
function d_VkPhysicalDeviceVariablePointersFeatures_self(r, o)
{
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
}
function d_VkPhysicalDeviceMultiviewFeatures_self(r, o)
{
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
}
function d_VkPhysicalDevice16BitStorageFeatures_self(r, o)
{
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
}
function d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self(r, o)
{
    o.shaderSubgroupExtendedTypes = r.u32();
}
function d_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self(r, o)
{
    o.samplerYcbcrConversion = r.u32();
}
function d_VkPhysicalDeviceProtectedMemoryFeatures_self(r, o)
{
    o.protectedMemory = r.u32();
}
function d_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self(r, o)
{
    o.advancedBlendCoherentOperations = r.u32();
}
function d_VkPhysicalDeviceMultiDrawFeaturesEXT_self(r, o)
{
    o.multiDraw = r.u32();
}
function d_VkPhysicalDeviceInlineUniformBlockFeatures_self(r, o)
{
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
}
function d_VkPhysicalDeviceMaintenance4Features_self(r, o)
{
    o.maintenance4 = r.u32();
}
function d_VkPhysicalDeviceMaintenance5Features_self(r, o)
{
    o.maintenance5 = r.u32();
}
function d_VkPhysicalDeviceMaintenance6Features_self(r, o)
{
    o.maintenance6 = r.u32();
}
function d_VkPhysicalDeviceMaintenance7FeaturesKHR_self(r, o)
{
    o.maintenance7 = r.u32();
}
function d_VkPhysicalDeviceShaderDrawParametersFeatures_self(r, o)
{
    o.shaderDrawParameters = r.u32();
}
function d_VkPhysicalDeviceShaderFloat16Int8Features_self(r, o)
{
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
}
function d_VkPhysicalDeviceHostQueryResetFeatures_self(r, o)
{
    o.hostQueryReset = r.u32();
}
function d_VkPhysicalDeviceGlobalPriorityQueryFeatures_self(r, o)
{
    o.globalPriorityQuery = r.u32();
}
function d_VkPhysicalDeviceDescriptorIndexingFeatures_self(r, o)
{
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
}
function d_VkPhysicalDeviceTimelineSemaphoreFeatures_self(r, o)
{
    o.timelineSemaphore = r.u32();
}
function d_VkPhysicalDevice8BitStorageFeatures_self(r, o)
{
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
}
function d_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self(r, o)
{
    o.conditionalRendering = r.u32();
    o.inheritedConditionalRendering = r.u32();
}
function d_VkPhysicalDeviceVulkanMemoryModelFeatures_self(r, o)
{
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
}
function d_VkPhysicalDeviceShaderAtomicInt64Features_self(r, o)
{
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
}
function d_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self(r, o)
{
    o.shaderBufferFloat32Atomics = r.u32();
    o.shaderBufferFloat32AtomicAdd = r.u32();
    o.shaderBufferFloat64Atomics = r.u32();
    o.shaderBufferFloat64AtomicAdd = r.u32();
    o.shaderSharedFloat32Atomics = r.u32();
    o.shaderSharedFloat32AtomicAdd = r.u32();
    o.shaderSharedFloat64Atomics = r.u32();
    o.shaderSharedFloat64AtomicAdd = r.u32();
    o.shaderImageFloat32Atomics = r.u32();
    o.shaderImageFloat32AtomicAdd = r.u32();
    o.sparseImageFloat32Atomics = r.u32();
    o.sparseImageFloat32AtomicAdd = r.u32();
}
function d_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self(r, o)
{
    o.shaderBufferFloat16Atomics = r.u32();
    o.shaderBufferFloat16AtomicAdd = r.u32();
    o.shaderBufferFloat16AtomicMinMax = r.u32();
    o.shaderBufferFloat32AtomicMinMax = r.u32();
    o.shaderBufferFloat64AtomicMinMax = r.u32();
    o.shaderSharedFloat16Atomics = r.u32();
    o.shaderSharedFloat16AtomicAdd = r.u32();
    o.shaderSharedFloat16AtomicMinMax = r.u32();
    o.shaderSharedFloat32AtomicMinMax = r.u32();
    o.shaderSharedFloat64AtomicMinMax = r.u32();
    o.shaderImageFloat32AtomicMinMax = r.u32();
    o.sparseImageFloat32AtomicMinMax = r.u32();
}
function d_VkPhysicalDeviceVertexAttributeDivisorFeatures_self(r, o)
{
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
}
function d_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self(r, o)
{
    o.transformFeedback = r.u32();
    o.geometryStreams = r.u32();
}
function d_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self(r, o)
{
    o.computeDerivativeGroupQuads = r.u32();
    o.computeDerivativeGroupLinear = r.u32();
}
function d_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self(r, o)
{
    o.fragmentShaderBarycentric = r.u32();
}
function d_VkPhysicalDeviceMeshShaderFeaturesEXT_self(r, o)
{
    o.taskShader = r.u32();
    o.meshShader = r.u32();
    o.multiviewMeshShader = r.u32();
    o.primitiveFragmentShadingRateMeshShader = r.u32();
    o.meshShaderQueries = r.u32();
}
function d_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self(r, o)
{
    o.accelerationStructure = r.u32();
    o.accelerationStructureCaptureReplay = r.u32();
    o.accelerationStructureIndirectBuild = r.u32();
    o.accelerationStructureHostCommands = r.u32();
    o.descriptorBindingAccelerationStructureUpdateAfterBind = r.u32();
}
function d_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self(r, o)
{
    o.rayTracingPipeline = r.u32();
    o.rayTracingPipelineShaderGroupHandleCaptureReplay = r.u32();
    o.rayTracingPipelineShaderGroupHandleCaptureReplayMixed = r.u32();
    o.rayTracingPipelineTraceRaysIndirect = r.u32();
    o.rayTraversalPrimitiveCulling = r.u32();
}
function d_VkPhysicalDeviceRayQueryFeaturesKHR_self(r, o)
{
    o.rayQuery = r.u32();
}
function d_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self(r, o)
{
    o.rayTracingMaintenance1 = r.u32();
    o.rayTracingPipelineTraceRaysIndirect2 = r.u32();
}
function d_VkPhysicalDeviceScalarBlockLayoutFeatures_self(r, o)
{
    o.scalarBlockLayout = r.u32();
}
function d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self(r, o)
{
    o.uniformBufferStandardLayout = r.u32();
}
function d_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self(r, o)
{
    o.depthClipEnable = r.u32();
}
function d_VkPhysicalDeviceBufferDeviceAddressFeatures_self(r, o)
{
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
}
function d_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self(r, o)
{
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
}
function d_VkPhysicalDeviceImagelessFramebufferFeatures_self(r, o)
{
    o.imagelessFramebuffer = r.u32();
}
function d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self(r, o)
{
    o.textureCompressionASTC_HDR = r.u32();
}
function d_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self(r, o)
{
    o.ycbcrImageArrays = r.u32();
}
function d_VkPhysicalDeviceShaderClockFeaturesKHR_self(r, o)
{
    o.shaderSubgroupClock = r.u32();
    o.shaderDeviceClock = r.u32();
}
function d_VkPhysicalDeviceIndexTypeUint8Features_self(r, o)
{
    o.indexTypeUint8 = r.u32();
}
function d_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self(r, o)
{
    o.fragmentShaderSampleInterlock = r.u32();
    o.fragmentShaderPixelInterlock = r.u32();
    o.fragmentShaderShadingRateInterlock = r.u32();
}
function d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self(r, o)
{
    o.separateDepthStencilLayouts = r.u32();
}
function d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self(r, o)
{
    o.primitiveTopologyListRestart = r.u32();
    o.primitiveTopologyPatchListRestart = r.u32();
}
function d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self(r, o)
{
    o.shaderDemoteToHelperInvocation = r.u32();
}
function d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self(r, o)
{
    o.texelBufferAlignment = r.u32();
}
function d_VkPhysicalDeviceSubgroupSizeControlFeatures_self(r, o)
{
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
}
function d_VkPhysicalDeviceLineRasterizationFeatures_self(r, o)
{
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
}
function d_VkPhysicalDevicePipelineCreationCacheControlFeatures_self(r, o)
{
    o.pipelineCreationCacheControl = r.u32();
}
function d_VkPhysicalDeviceVulkan11Features_self(r, o)
{
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    o.protectedMemory = r.u32();
    o.samplerYcbcrConversion = r.u32();
    o.shaderDrawParameters = r.u32();
}
function d_VkPhysicalDeviceVulkan12Features_self(r, o)
{
    o.samplerMirrorClampToEdge = r.u32();
    o.drawIndirectCount = r.u32();
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    o.descriptorIndexing = r.u32();
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    o.samplerFilterMinmax = r.u32();
    o.scalarBlockLayout = r.u32();
    o.imagelessFramebuffer = r.u32();
    o.uniformBufferStandardLayout = r.u32();
    o.shaderSubgroupExtendedTypes = r.u32();
    o.separateDepthStencilLayouts = r.u32();
    o.hostQueryReset = r.u32();
    o.timelineSemaphore = r.u32();
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    o.shaderOutputViewportIndex = r.u32();
    o.shaderOutputLayer = r.u32();
    o.subgroupBroadcastDynamicId = r.u32();
}
function d_VkPhysicalDeviceVulkan13Features_self(r, o)
{
    o.robustImageAccess = r.u32();
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    o.pipelineCreationCacheControl = r.u32();
    o.privateData = r.u32();
    o.shaderDemoteToHelperInvocation = r.u32();
    o.shaderTerminateInvocation = r.u32();
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    o.synchronization2 = r.u32();
    o.textureCompressionASTC_HDR = r.u32();
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    o.dynamicRendering = r.u32();
    o.shaderIntegerDotProduct = r.u32();
    o.maintenance4 = r.u32();
}
function d_VkPhysicalDeviceVulkan14Features_self(r, o)
{
    o.globalPriorityQuery = r.u32();
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    o.shaderFloatControls2 = r.u32();
    o.shaderExpectAssume = r.u32();
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    o.indexTypeUint8 = r.u32();
    o.dynamicRenderingLocalRead = r.u32();
    o.maintenance5 = r.u32();
    o.maintenance6 = r.u32();
    o.pipelineProtectedAccess = r.u32();
    o.pipelineRobustness = r.u32();
    o.hostImageCopy = r.u32();
    o.pushDescriptor = r.u32();
}
function d_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self(r, o)
{
    o.customBorderColors = r.u32();
    o.customBorderColorWithoutFormat = r.u32();
}
function d_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self(r, o)
{
    o.borderColorSwizzle = r.u32();
    o.borderColorSwizzleFromImage = r.u32();
}
function d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self(r, o)
{
    o.extendedDynamicState = r.u32();
}
function d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self(r, o)
{
    o.extendedDynamicState2 = r.u32();
    o.extendedDynamicState2LogicOp = r.u32();
    o.extendedDynamicState2PatchControlPoints = r.u32();
}
function d_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self(r, o)
{
    o.extendedDynamicState3TessellationDomainOrigin = r.u32();
    o.extendedDynamicState3DepthClampEnable = r.u32();
    o.extendedDynamicState3PolygonMode = r.u32();
    o.extendedDynamicState3RasterizationSamples = r.u32();
    o.extendedDynamicState3SampleMask = r.u32();
    o.extendedDynamicState3AlphaToCoverageEnable = r.u32();
    o.extendedDynamicState3AlphaToOneEnable = r.u32();
    o.extendedDynamicState3LogicOpEnable = r.u32();
    o.extendedDynamicState3ColorBlendEnable = r.u32();
    o.extendedDynamicState3ColorBlendEquation = r.u32();
    o.extendedDynamicState3ColorWriteMask = r.u32();
    o.extendedDynamicState3RasterizationStream = r.u32();
    o.extendedDynamicState3ConservativeRasterizationMode = r.u32();
    o.extendedDynamicState3ExtraPrimitiveOverestimationSize = r.u32();
    o.extendedDynamicState3DepthClipEnable = r.u32();
    o.extendedDynamicState3SampleLocationsEnable = r.u32();
    o.extendedDynamicState3ColorBlendAdvanced = r.u32();
    o.extendedDynamicState3ProvokingVertexMode = r.u32();
    o.extendedDynamicState3LineRasterizationMode = r.u32();
    o.extendedDynamicState3LineStippleEnable = r.u32();
    o.extendedDynamicState3DepthClipNegativeOneToOne = r.u32();
    o.extendedDynamicState3ViewportWScalingEnable = r.u32();
    o.extendedDynamicState3ViewportSwizzle = r.u32();
    o.extendedDynamicState3CoverageToColorEnable = r.u32();
    o.extendedDynamicState3CoverageToColorLocation = r.u32();
    o.extendedDynamicState3CoverageModulationMode = r.u32();
    o.extendedDynamicState3CoverageModulationTableEnable = r.u32();
    o.extendedDynamicState3CoverageModulationTable = r.u32();
    o.extendedDynamicState3CoverageReductionMode = r.u32();
    o.extendedDynamicState3RepresentativeFragmentTestEnable = r.u32();
    o.extendedDynamicState3ShadingRateImageEnable = r.u32();
}
function d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self(r, o)
{
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
}
function d_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self(r, o)
{
    o.shaderSubgroupUniformControlFlow = r.u32();
}
function d_VkPhysicalDeviceRobustness2FeaturesKHR_self(r, o)
{
    o.robustBufferAccess2 = r.u32();
    o.robustImageAccess2 = r.u32();
    o.nullDescriptor = r.u32();
}
function d_VkPhysicalDeviceImageRobustnessFeatures_self(r, o)
{
    o.robustImageAccess = r.u32();
}
function d_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self(r, o)
{
    o.workgroupMemoryExplicitLayout = r.u32();
    o.workgroupMemoryExplicitLayoutScalarBlockLayout = r.u32();
    o.workgroupMemoryExplicitLayout8BitAccess = r.u32();
    o.workgroupMemoryExplicitLayout16BitAccess = r.u32();
}
function d_VkPhysicalDevice4444FormatsFeaturesEXT_self(r, o)
{
    o.formatA4R4G4B4 = r.u32();
    o.formatA4B4G4R4 = r.u32();
}
function d_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self(r, o)
{
    o.shaderImageInt64Atomics = r.u32();
    o.sparseImageInt64Atomics = r.u32();
}
function d_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self(r, o)
{
    o.pipelineFragmentShadingRate = r.u32();
    o.primitiveFragmentShadingRate = r.u32();
    o.attachmentFragmentShadingRate = r.u32();
}
function d_VkPhysicalDeviceShaderTerminateInvocationFeatures_self(r, o)
{
    o.shaderTerminateInvocation = r.u32();
}
function d_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self(r, o)
{
    o.image2DViewOf3D = r.u32();
    o.sampler2DViewOf3D = r.u32();
}
function d_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self(r, o)
{
    o.imageSlicedViewOf3D = r.u32();
}
function d_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self(r, o)
{
    o.attachmentFeedbackLoopDynamicState = r.u32();
}
function d_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self(r, o)
{
    o.legacyVertexAttributes = r.u32();
}
function d_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self(r, o)
{
    o.mutableDescriptorType = r.u32();
}
function d_VkPhysicalDeviceDepthClipControlFeaturesEXT_self(r, o)
{
    o.depthClipControl = r.u32();
}
function d_VkPhysicalDeviceDepthClampControlFeaturesEXT_self(r, o)
{
    o.depthClampControl = r.u32();
}
function d_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self(r, o)
{
    o.vertexInputDynamicState = r.u32();
}
function d_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self(r, o)
{
    o.shaderRelaxedExtendedInstruction = r.u32();
}
function d_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self(r, o)
{
    o.colorWriteEnable = r.u32();
}
function d_VkPhysicalDeviceSynchronization2Features_self(r, o)
{
    o.synchronization2 = r.u32();
}
function d_VkPhysicalDeviceHostImageCopyFeatures_self(r, o)
{
    o.hostImageCopy = r.u32();
}
function d_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self(r, o)
{
    o.primitivesGeneratedQuery = r.u32();
    o.primitivesGeneratedQueryWithRasterizerDiscard = r.u32();
    o.primitivesGeneratedQueryWithNonZeroStreams = r.u32();
}
function d_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self(r, o)
{
    o.legacyDithering = r.u32();
}
function d_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self(r, o)
{
    o.multisampledRenderToSingleSampled = r.u32();
}
function d_VkPhysicalDevicePipelineProtectedAccessFeatures_self(r, o)
{
    o.pipelineProtectedAccess = r.u32();
}
function d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self(r, o)
{
    o.ycbcr2plane444Formats = r.u32();
}
function d_VkPhysicalDeviceProvokingVertexFeaturesEXT_self(r, o)
{
    o.provokingVertexLast = r.u32();
    o.transformFeedbackPreservesProvokingVertex = r.u32();
}
function d_VkPhysicalDeviceShaderIntegerDotProductFeatures_self(r, o)
{
    o.shaderIntegerDotProduct = r.u32();
}
function d_VkPhysicalDeviceShaderFmaFeaturesKHR_self(r, o)
{
    o.shaderFmaFloat16 = r.u32();
    o.shaderFmaFloat32 = r.u32();
    o.shaderFmaFloat64 = r.u32();
}
function d_VkPhysicalDeviceDynamicRenderingFeatures_self(r, o)
{
    o.dynamicRendering = r.u32();
}
function d_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self(r, o)
{
    o.minLod = r.u32();
}
function d_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self(r, o)
{
    o.rasterizationOrderColorAttachmentAccess = r.u32();
    o.rasterizationOrderDepthAttachmentAccess = r.u32();
    o.rasterizationOrderStencilAttachmentAccess = r.u32();
}
function d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self(r, o)
{
    o.graphicsPipelineLibrary = r.u32();
}
function d_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self(r, o)
{
    o.nestedCommandBuffer = r.u32();
    o.nestedCommandBufferRendering = r.u32();
    o.nestedCommandBufferSimultaneousUse = r.u32();
}
function d_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self(r, o)
{
    o.nonSeamlessCubeMap = r.u32();
}
function d_VkPhysicalDevicePipelineRobustnessFeatures_self(r, o)
{
    o.pipelineRobustness = r.u32();
}
function d_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self(r, o)
{
    o.attachmentFeedbackLoopLayout = r.u32();
}
function d_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self(r, o)
{
    o.depthClampZeroOne = r.u32();
}
function d_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self(r, o)
{
    o.pipelineLibraryGroupHandles = r.u32();
}
function d_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self(r, o)
{
    o.dynamicRenderingUnusedAttachments = r.u32();
}
function d_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self(r, o)
{
    o.depthBiasControl = r.u32();
    o.leastRepresentableValueForceUnormRepresentation = r.u32();
    o.floatRepresentation = r.u32();
    o.depthBiasExact = r.u32();
}
function d_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self(r, o)
{
    o.rayTracingPositionFetch = r.u32();
}
function d_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self(r, o)
{
    o.cooperativeMatrix = r.u32();
    o.cooperativeMatrixRobustBufferAccess = r.u32();
}
function d_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self(r, o)
{
    o.shaderMaximalReconvergence = r.u32();
}
function d_VkPhysicalDeviceShaderSubgroupRotateFeatures_self(r, o)
{
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
}
function d_VkPhysicalDeviceShaderExpectAssumeFeatures_self(r, o)
{
    o.shaderExpectAssume = r.u32();
}
function d_VkPhysicalDeviceShaderFloatControls2Features_self(r, o)
{
    o.shaderFloatControls2 = r.u32();
}
function d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self(r, o)
{
    o.dynamicRenderingLocalRead = r.u32();
}
function d_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self(r, o)
{
    o.shaderQuadControl = r.u32();
}
function d_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self(r, o)
{
    o.shaderBFloat16Type = r.u32();
    o.shaderBFloat16DotProduct = r.u32();
    o.shaderBFloat16CooperativeMatrix = r.u32();
}
function d_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self(r, o)
{
    o.shaderReplicatedComposites = r.u32();
}
function d_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self(r, o)
{
    o.shaderUniformBufferUnsizedArray = r.u32();
}
function d_VkPhysicalDeviceShaderFloat8FeaturesEXT_self(r, o)
{
    o.shaderFloat8 = r.u32();
    o.shaderFloat8CooperativeMatrix = r.u32();
}
function d_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self(r, o)
{
    o.shaderUntypedPointers = r.u32();
}
function d_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self(r, o)
{
    o.descriptorHeap = r.u32();
    o.descriptorHeapCaptureReplay = r.u32();
}
function d_VkDevicePrivateDataCreateInfo_self(r, o)
{
    o.privateDataSlotRequestCount = r.u32();
}
function d_VkPhysicalDeviceFeatures2_self(r, o)
{
    o.features = d_VkPhysicalDeviceFeatures(r);
}
function d_VkDeviceGroupDeviceCreateInfo_self(r, o)
{
    o.physicalDeviceCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pPhysicalDevices = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pPhysicalDevices[i] = r.h();
        }
    }
    else o.pPhysicalDevices = null;
}
function d_VkPhysicalDeviceExternalImageFormatInfo_self(r, o)
{
    o.handleType = r.i32();
}
function d_VkImageFormatListCreateInfo_self(r, o)
{
    o.viewFormatCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pViewFormats = r.i32s(n0);
    }
    else o.pViewFormats = null;
}
function d_VkPhysicalDeviceImageDrmFormatModifierInfoEXT_self(r, o)
{
    o.drmFormatModifier = r.u64();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    if(o.sharingMode === 1)
    {
        const n0 = r.size();
        o.pQueueFamilyIndices = r.u32s(n0);
    }
    else
    {
        const n1 = r.size();
    }
}
function d_VkImageStencilUsageCreateInfo_self(r, o)
{
    o.stencilUsage = r.u32();
}
function d_VkPhysicalDeviceImageViewImageFormatInfoEXT_self(r, o)
{
    o.imageViewType = r.i32();
}
function d_VkSemaphoreTypeCreateInfo_self(r, o)
{
    o.semaphoreType = r.i32();
    o.initialValue = r.u64();
}
function d_VkDeviceQueueTimelineInfoMESA_self(r, o)
{
    o.ringIdx = r.u32();
}
function d_VkExportMemoryAllocateInfo_self(r, o)
{
    o.handleTypes = r.u32();
}
function d_VkMemoryAllocateFlagsInfo_self(r, o)
{
    o.flags = r.u32();
    o.deviceMask = r.u32();
}
function d_VkMemoryDedicatedAllocateInfo_self(r, o)
{
    o.image = r.h();
    o.buffer = r.h();
}
function d_VkMemoryOpaqueCaptureAddressAllocateInfo_self(r, o)
{
    o.opaqueCaptureAddress = r.u64();
}
function d_VkImportMemoryResourceInfoMESA_self(r, o)
{
    o.resourceId = r.u32();
}
function d_VkExportFenceCreateInfo_self(r, o)
{
    o.handleTypes = r.u32();
}
function d_VkFramebufferAttachmentsCreateInfo_self(r, o)
{
    o.attachmentImageInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachmentImageInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachmentImageInfos[i] = d_VkFramebufferAttachmentImageInfo(r);
        }
    }
    else o.pAttachmentImageInfos = null;
}
function d_VkExternalMemoryImageCreateInfo_self(r, o)
{
    o.handleTypes = r.u32();
}
function d_VkImageDrmFormatModifierListCreateInfoEXT_self(r, o)
{
    o.drmFormatModifierCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDrmFormatModifiers = r.u64s(n0);
    }
    else o.pDrmFormatModifiers = null;
}
function d_VkImageDrmFormatModifierExplicitCreateInfoEXT_self(r, o)
{
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pPlaneLayouts = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pPlaneLayouts[i] = d_VkSubresourceLayout(r);
        }
    }
    else o.pPlaneLayouts = null;
}
function d_VkOpaqueCaptureDataCreateInfoEXT_self(r, o)
{
    if(r.u64())
    {
        o.pData = d_VkHostAddressRangeConstEXT(r);
    }
    else o.pData = null;
}
function d_VkBindImageMemoryDeviceGroupInfo_self(r, o)
{
    o.deviceIndexCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDeviceIndices = r.u32s(n0);
    }
    else o.pDeviceIndices = null;
    o.splitInstanceBindRegionCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pSplitInstanceBindRegions = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pSplitInstanceBindRegions[i] = d_VkRect2D(r);
        }
    }
    else o.pSplitInstanceBindRegions = null;
}
function d_VkBindImagePlaneMemoryInfo_self(r, o)
{
    o.planeAspect = r.i32();
}
function d_VkImagePlaneMemoryRequirementsInfo_self(r, o)
{
    o.planeAspect = r.i32();
}
function d_VkShaderModuleCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.codeSize = r.u64();
    const n0 = r.size();
    if(n0)
    {
        o.pCode = r.u32s(n0);
    }
    else o.pCode = null;
}
function d_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo_self(r, o)
{
    o.requiredSubgroupSize = r.u32();
}
function d_VkPipelineRobustnessCreateInfo_self(r, o)
{
    o.storageBuffers = r.i32();
    o.uniformBuffers = r.i32();
    o.vertexInputs = r.i32();
    o.images = r.i32();
}
function d_VkShaderDescriptorSetAndBindingMappingInfoEXT_self(r, o)
{
    o.mappingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pMappings = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pMappings[i] = d_VkDescriptorSetAndBindingMappingEXT(r);
        }
    }
    else o.pMappings = null;
}
function d_VkPipelineVertexInputDivisorStateCreateInfo_self(r, o)
{
    o.vertexBindingDivisorCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pVertexBindingDivisors = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pVertexBindingDivisors[i] = d_VkVertexInputBindingDivisorDescription(r);
        }
    }
    else o.pVertexBindingDivisors = null;
}
function d_VkPipelineTessellationDomainOriginStateCreateInfo_self(r, o)
{
    o.domainOrigin = r.i32();
}
function d_VkPipelineViewportDepthClipControlCreateInfoEXT_self(r, o)
{
    o.negativeOneToOne = r.u32();
}
function d_VkPipelineViewportDepthClampControlCreateInfoEXT_self(r, o)
{
    o.depthClampMode = r.i32();
    if(r.u64())
    {
        o.pDepthClampRange = d_VkDepthClampRangeEXT(r);
    }
    else o.pDepthClampRange = null;
}
function d_VkPipelineRasterizationConservativeStateCreateInfoEXT_self(r, o)
{
    o.flags = r.u32();
    o.conservativeRasterizationMode = r.i32();
    o.extraPrimitiveOverestimationSize = r.f32();
}
function d_VkPipelineRasterizationStateStreamCreateInfoEXT_self(r, o)
{
    o.flags = r.u32();
    o.rasterizationStream = r.u32();
}
function d_VkPipelineRasterizationDepthClipStateCreateInfoEXT_self(r, o)
{
    o.flags = r.u32();
    o.depthClipEnable = r.u32();
}
function d_VkPipelineRasterizationLineStateCreateInfo_self(r, o)
{
    o.lineRasterizationMode = r.i32();
    o.stippledLineEnable = r.u32();
    o.lineStippleFactor = r.u32();
    o.lineStipplePattern = r.u16();
}
function d_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT_self(r, o)
{
    o.provokingVertexMode = r.i32();
}
function d_VkPipelineSampleLocationsStateCreateInfoEXT_self(r, o)
{
    o.sampleLocationsEnable = r.u32();
    o.sampleLocationsInfo = d_VkSampleLocationsInfoEXT(r);
}
function d_VkPipelineColorBlendAdvancedStateCreateInfoEXT_self(r, o)
{
    o.srcPremultiplied = r.u32();
    o.dstPremultiplied = r.u32();
    o.blendOverlap = r.i32();
}
function d_VkPipelineColorWriteCreateInfoEXT_self(r, o)
{
    o.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorWriteEnables = r.u32s(n0);
    }
    else o.pColorWriteEnables = null;
}
function d_VkPipelineCreateFlags2CreateInfo_self(r, o)
{
    o.flags = r.u64();
}
function d_VkPipelineLibraryCreateInfoKHR_self(r, o)
{
    o.libraryCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pLibraries = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pLibraries[i] = r.h();
        }
    }
    else o.pLibraries = null;
}
function d_VkPipelineCreationFeedbackCreateInfo_self(r, o)
{
    if(r.u64())
    {
        o.pPipelineCreationFeedback = d_VkPipelineCreationFeedback(r);
    }
    else o.pPipelineCreationFeedback = null;
    o.pipelineStageCreationFeedbackCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pPipelineStageCreationFeedbacks = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pPipelineStageCreationFeedbacks[i] = d_VkPipelineCreationFeedback(r);
        }
    }
    else o.pPipelineStageCreationFeedbacks = null;
}
function d_VkPipelineFragmentShadingRateStateCreateInfoKHR_self(r, o)
{
    o.fragmentSize = d_VkExtent2D(r);
    const n0 = r.size();
    o.combinerOps = r.i32s(n0);
}
function d_VkPipelineRenderingCreateInfo_self(r, o)
{
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachmentFormats = r.i32s(n0);
    }
    else o.pColorAttachmentFormats = null;
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
}
function d_VkGraphicsPipelineLibraryCreateInfoEXT_self(r, o)
{
    o.flags = r.u32();
}
function d_VkDeviceGroupSubmitInfo_self(r, o)
{
    o.waitSemaphoreCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pWaitSemaphoreDeviceIndices = r.u32s(n0);
    }
    else o.pWaitSemaphoreDeviceIndices = null;
    o.commandBufferCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pCommandBufferDeviceMasks = r.u32s(n1);
    }
    else o.pCommandBufferDeviceMasks = null;
    o.signalSemaphoreCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pSignalSemaphoreDeviceIndices = r.u32s(n2);
    }
    else o.pSignalSemaphoreDeviceIndices = null;
}
function d_VkProtectedSubmitInfo_self(r, o)
{
    o.protectedSubmit = r.u32();
}
function d_VkTimelineSemaphoreSubmitInfo_self(r, o)
{
    o.waitSemaphoreValueCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pWaitSemaphoreValues = r.u64s(n0);
    }
    else o.pWaitSemaphoreValues = null;
    o.signalSemaphoreValueCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pSignalSemaphoreValues = r.u64s(n1);
    }
    else o.pSignalSemaphoreValues = null;
}
function d_VkDeviceGroupBindSparseInfo_self(r, o)
{
    o.resourceDeviceIndex = r.u32();
    o.memoryDeviceIndex = r.u32();
}
function d_VkRenderPassMultiviewCreateInfo_self(r, o)
{
    o.subpassCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pViewMasks = r.u32s(n0);
    }
    else o.pViewMasks = null;
    o.dependencyCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pViewOffsets = r.i32s(n1);
    }
    else o.pViewOffsets = null;
    o.correlationMaskCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pCorrelationMasks = r.u32s(n2);
    }
    else o.pCorrelationMasks = null;
}
function d_VkRenderPassInputAttachmentAspectCreateInfo_self(r, o)
{
    o.aspectReferenceCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAspectReferences = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAspectReferences[i] = d_VkInputAttachmentAspectReference(r);
        }
    }
    else o.pAspectReferences = null;
}
function d_VkAttachmentDescriptionStencilLayout_self(r, o)
{
    o.stencilInitialLayout = r.i32();
    o.stencilFinalLayout = r.i32();
}
function d_VkAttachmentReferenceStencilLayout_self(r, o)
{
    o.stencilLayout = r.i32();
}
function d_VkSubpassDescriptionDepthStencilResolve_self(r, o)
{
    o.depthResolveMode = r.i32();
    o.stencilResolveMode = r.i32();
    if(r.u64())
    {
        o.pDepthStencilResolveAttachment = d_VkAttachmentReference2(r);
    }
    else o.pDepthStencilResolveAttachment = null;
}
function d_VkFragmentShadingRateAttachmentInfoKHR_self(r, o)
{
    if(r.u64())
    {
        o.pFragmentShadingRateAttachment = d_VkAttachmentReference2(r);
    }
    else o.pFragmentShadingRateAttachment = null;
    o.shadingRateAttachmentTexelSize = d_VkExtent2D(r);
}
function d_VkMemoryBarrier2_self(r, o)
{
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
}
function d_VkExportSemaphoreCreateInfo_self(r, o)
{
    o.handleTypes = r.u32();
}
function d_VkImageViewUsageCreateInfo_self(r, o)
{
    o.usage = r.u32();
}
function d_VkImageViewSlicedCreateInfoEXT_self(r, o)
{
    o.sliceOffset = r.u32();
    o.sliceCount = r.u32();
}
function d_VkSamplerYcbcrConversionInfo_self(r, o)
{
    o.conversion = r.h();
}
function d_VkImageViewMinLodCreateInfoEXT_self(r, o)
{
    o.minLod = r.f32();
}
function d_VkSamplerReductionModeCreateInfo_self(r, o)
{
    o.reductionMode = r.i32();
}
function d_VkSamplerCustomBorderColorCreateInfoEXT_self(r, o)
{
    o.customBorderColor = d_VkClearColorValue(r);
    o.format = r.i32();
}
function d_VkSamplerBorderColorComponentMappingCreateInfoEXT_self(r, o)
{
    o.components = d_VkComponentMapping(r);
    o.srgb = r.u32();
}
function d_VkSamplerCustomBorderColorIndexCreateInfoEXT_self(r, o)
{
    o.index = r.u32();
}
function d_VkWriteDescriptorSetInlineUniformBlock_self(r, o)
{
    o.dataSize = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pData = r.blob(n0);
    }
    else o.pData = null;
}
function d_VkWriteDescriptorSetAccelerationStructureKHR_self(r, o)
{
    o.accelerationStructureCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAccelerationStructures = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAccelerationStructures[i] = r.h();
        }
    }
    else o.pAccelerationStructures = null;
}
function d_VkRingMonitorInfoMESA_self(r, o)
{
    o.maxReportingPeriodMicroseconds = r.u32();
}
function d_VkRingPriorityInfoMESA_self(r, o)
{
    o.priority = r.i32();
}
function d_VkDescriptorSetVariableDescriptorCountLayoutSupport_self_partial(r, o)
{
}
function d_VkPhysicalDevicePrivateDataFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVariablePointersFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMultiviewFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDevice16BitStorageFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceProtectedMemoryFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMultiDrawFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceInlineUniformBlockFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance4Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance5Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance6Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance7FeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderDrawParametersFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderFloat16Int8Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceHostQueryResetFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceGlobalPriorityQueryFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDescriptorIndexingFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTimelineSemaphoreFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDevice8BitStorageFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkanMemoryModelFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderAtomicInt64Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVertexAttributeDivisorFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMeshShaderFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRayQueryFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceScalarBlockLayoutFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceBufferDeviceAddressFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceImagelessFramebufferFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderClockFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceIndexTypeUint8Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSubgroupSizeControlFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceLineRasterizationFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDevicePipelineCreationCacheControlFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan11Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan12Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan13Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan14Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRobustness2FeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceImageRobustnessFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDevice4444FormatsFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderTerminateInvocationFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthClipControlFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthClampControlFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSynchronization2Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceHostImageCopyFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDevicePipelineProtectedAccessFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceProvokingVertexFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderIntegerDotProductFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderFmaFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDynamicRenderingFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDevicePipelineRobustnessFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderSubgroupRotateFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderExpectAssumeFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderFloatControls2Features_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderFloat8FeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMultiDrawPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDevicePushDescriptorProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDriverProperties_self_partial(r, o)
{
    o.conformanceVersion = d_VkConformanceVersion_partial(r);
}
function d_VkPhysicalDeviceIDProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMultiviewProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSubgroupProperties_self_partial(r, o)
{
}
function d_VkPhysicalDevicePointClippingProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceProtectedMemoryProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSamplerFilterMinmaxProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSampleLocationsPropertiesEXT_self_partial(r, o)
{
    o.maxSampleLocationGridSize = d_VkExtent2D_partial(r);
}
function d_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceInlineUniformBlockProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance3Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance4Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance5Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance6Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMaintenance7PropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFloatControlsProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDescriptorIndexingProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTimelineSemaphoreProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVertexAttributeDivisorProperties_self_partial(r, o)
{
}
function d_VkPhysicalDevicePCIBusInfoPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDepthStencilResolveProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMeshShaderPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceTexelBufferAlignmentProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceSubgroupSizeControlProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceLineRasterizationProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan11Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan12Properties_self_partial(r, o)
{
    o.conformanceVersion = d_VkConformanceVersion_partial(r);
}
function d_VkPhysicalDeviceVulkan13Properties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceVulkan14Properties_self_partial(r, o)
{
    o.copySrcLayoutCount = r.u32();
    const n0 = r.size();
    o.copyDstLayoutCount = r.u32();
    const n1 = r.size();
}
function d_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceRobustness2PropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self_partial(r, o)
{
    o.minFragmentShadingRateAttachmentTexelSize = d_VkExtent2D_partial(r);
    o.maxFragmentShadingRateAttachmentTexelSize = d_VkExtent2D_partial(r);
    o.maxFragmentSize = d_VkExtent2D_partial(r);
}
function d_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceHostImageCopyProperties_self_partial(r, o)
{
    o.copySrcLayoutCount = r.u32();
    const n0 = r.size();
    o.copyDstLayoutCount = r.u32();
    const n1 = r.size();
}
function d_VkPhysicalDeviceProvokingVertexPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceShaderIntegerDotProductProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self_partial(r, o)
{
}
function d_VkPhysicalDevicePipelineRobustnessProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self_partial(r, o)
{
}
function d_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self_partial(r, o)
{
}
function d_VkDrmFormatModifierPropertiesListEXT_self_partial(r, o)
{
    o.drmFormatModifierCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDrmFormatModifierProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDrmFormatModifierProperties[i] = d_VkDrmFormatModifierPropertiesEXT_partial(r);
        }
    }
    else o.pDrmFormatModifierProperties = null;
}
function d_VkSubpassResolvePerformanceQueryEXT_self_partial(r, o)
{
}
function d_VkFormatProperties3_self_partial(r, o)
{
}
function d_VkDrmFormatModifierPropertiesList2EXT_self_partial(r, o)
{
    o.drmFormatModifierCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDrmFormatModifierProperties = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDrmFormatModifierProperties[i] = d_VkDrmFormatModifierProperties2EXT_partial(r);
        }
    }
    else o.pDrmFormatModifierProperties = null;
}
function d_VkExternalImageFormatProperties_self_partial(r, o)
{
    o.externalMemoryProperties = d_VkExternalMemoryProperties_partial(r);
}
function d_VkSamplerYcbcrConversionImageFormatProperties_self_partial(r, o)
{
}
function d_VkFilterCubicImageViewImageFormatPropertiesEXT_self_partial(r, o)
{
}
function d_VkHostImageCopyDevicePerformanceQuery_self_partial(r, o)
{
}
function d_VkQueueFamilyGlobalPriorityProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self_partial(r, o)
{
}
function d_VkMemoryResourceAllocationSizePropertiesMESA_self_partial(r, o)
{
}
function d_VkSubresourceHostMemcpySize_self_partial(r, o)
{
}
function d_VkMemoryDedicatedRequirements_self_partial(r, o)
{
}
function d_VkInstanceCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkInstanceCreateInfo_self(r, o);
    return o;
}
function d_VkPhysicalDeviceFeatures_partial(r)
{
    const o = {};
    return o;
}
function d_VkFormatProperties_partial(r)
{
    const o = {};
    return o;
}
function d_VkImageFormatProperties_partial(r)
{
    const o = {};
    o.maxExtent = d_VkExtent3D_partial(r);
    return o;
}
function d_VkPhysicalDeviceProperties_partial(r)
{
    const o = {};
    o.limits = d_VkPhysicalDeviceLimits_partial(r);
    o.sparseProperties = d_VkPhysicalDeviceSparseProperties_partial(r);
    return o;
}
function d_VkQueueFamilyProperties_partial(r)
{
    const o = {};
    o.minImageTransferGranularity = d_VkExtent3D_partial(r);
    return o;
}
function d_VkPhysicalDeviceMemoryProperties_partial(r)
{
    const o = {};
    const n0 = r.size();
    o.memoryTypes = new Array(n0);
    for(let i = 0; i < n0; i++)
    {
        o.memoryTypes[i] = d_VkMemoryType_partial(r);
    }
    const n1 = r.size();
    o.memoryHeaps = new Array(n1);
    for(let i = 0; i < n1; i++)
    {
        o.memoryHeaps[i] = d_VkMemoryHeap_partial(r);
    }
    return o;
}
function d_VkDeviceCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceCreateInfo_self(r, o);
    return o;
}
function d_VkExtensionProperties_partial(r)
{
    const o = {};
    return o;
}
function d_VkLayerProperties_partial(r)
{
    const o = {};
    return o;
}
function d_VkSubmitInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubmitInfo_self(r, o);
    return o;
}
function d_VkMemoryAllocateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMemoryAllocateInfo_self(r, o);
    return o;
}
function d_VkMappedMemoryRange(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMappedMemoryRange_self(r, o);
    return o;
}
function d_VkMemoryRequirements_partial(r)
{
    const o = {};
    return o;
}
function d_VkSparseImageMemoryRequirements_partial(r)
{
    const o = {};
    o.formatProperties = d_VkSparseImageFormatProperties_partial(r);
    return o;
}
function d_VkSparseImageFormatProperties_partial(r)
{
    const o = {};
    o.imageGranularity = d_VkExtent3D_partial(r);
    return o;
}
function d_VkBindSparseInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBindSparseInfo_self(r, o);
    return o;
}
function d_VkFenceCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkFenceCreateInfo_self(r, o);
    return o;
}
function d_VkSemaphoreCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSemaphoreCreateInfo_self(r, o);
    return o;
}
function d_VkEventCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkEventCreateInfo_self(r, o);
    return o;
}
function d_VkQueryPoolCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkQueryPoolCreateInfo_self(r, o);
    return o;
}
function d_VkBufferCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferCreateInfo_self(r, o);
    return o;
}
function d_VkBufferViewCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferViewCreateInfo_self(r, o);
    return o;
}
function d_VkImageCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageCreateInfo_self(r, o);
    return o;
}
function d_VkImageSubresource(r)
{
    const o = {};
    o.aspectMask = r.u32();
    o.mipLevel = r.u32();
    o.arrayLayer = r.u32();
    return o;
}
function d_VkSubresourceLayout_partial(r)
{
    const o = {};
    return o;
}
function d_VkImageViewCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageViewCreateInfo_self(r, o);
    return o;
}
function d_VkShaderModuleCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkShaderModuleCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineCacheCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineCacheCreateInfo_self(r, o);
    return o;
}
function d_VkGraphicsPipelineCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkGraphicsPipelineCreateInfo_self(r, o);
    return o;
}
function d_VkComputePipelineCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkComputePipelineCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineLayoutCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineLayoutCreateInfo_self(r, o);
    return o;
}
function d_VkSamplerCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSamplerCreateInfo_self(r, o);
    return o;
}
function d_VkDescriptorSetLayoutCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDescriptorSetLayoutCreateInfo_self(r, o);
    return o;
}
function d_VkDescriptorPoolCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDescriptorPoolCreateInfo_self(r, o);
    return o;
}
function d_VkDescriptorSetAllocateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDescriptorSetAllocateInfo_self(r, o);
    return o;
}
function d_VkWriteDescriptorSet(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkWriteDescriptorSet_self(r, o);
    return o;
}
function d_VkCopyDescriptorSet(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyDescriptorSet_self(r, o);
    return o;
}
function d_VkFramebufferCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkFramebufferCreateInfo_self(r, o);
    return o;
}
function d_VkRenderPassCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderPassCreateInfo_self(r, o);
    return o;
}
function d_VkExtent2D_partial(r)
{
    const o = {};
    return o;
}
function d_VkCommandPoolCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCommandPoolCreateInfo_self(r, o);
    return o;
}
function d_VkCommandBufferAllocateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCommandBufferAllocateInfo_self(r, o);
    return o;
}
function d_VkCommandBufferBeginInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCommandBufferBeginInfo_self(r, o);
    return o;
}
function d_VkViewport(r)
{
    const o = {};
    o.x = r.f32();
    o.y = r.f32();
    o.width = r.f32();
    o.height = r.f32();
    o.minDepth = r.f32();
    o.maxDepth = r.f32();
    return o;
}
function d_VkRect2D(r)
{
    const o = {};
    o.offset = d_VkOffset2D(r);
    o.extent = d_VkExtent2D(r);
    return o;
}
function d_VkBufferCopy(r)
{
    const o = {};
    o.srcOffset = r.u64();
    o.dstOffset = r.u64();
    o.size = r.u64();
    return o;
}
function d_VkImageCopy(r)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    o.srcOffset = d_VkOffset3D(r);
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    o.dstOffset = d_VkOffset3D(r);
    o.extent = d_VkExtent3D(r);
    return o;
}
function d_VkImageBlit(r)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    const n0 = r.size();
    o.srcOffsets = new Array(n0);
    for(let i = 0; i < n0; i++)
    {
        o.srcOffsets[i] = d_VkOffset3D(r);
    }
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    const n1 = r.size();
    o.dstOffsets = new Array(n1);
    for(let i = 0; i < n1; i++)
    {
        o.dstOffsets[i] = d_VkOffset3D(r);
    }
    return o;
}
function d_VkBufferImageCopy(r)
{
    const o = {};
    o.bufferOffset = r.u64();
    o.bufferRowLength = r.u32();
    o.bufferImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r);
    o.imageOffset = d_VkOffset3D(r);
    o.imageExtent = d_VkExtent3D(r);
    return o;
}
function d_VkClearColorValue(r)
{
    const o = {};
    const tag = r.u32();
    o._tag = tag;
    switch(tag)
    {
    case 0:
        const n0 = r.size();
        o.float32 = r.f32s(n0);
        break;
    case 1:
        const n1 = r.size();
        o.int32 = r.i32s(n1);
        break;
    case 2:
        const n2 = r.size();
        o.uint32 = r.u32s(n2);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
    return o;
}
function d_VkImageSubresourceRange(r)
{
    const o = {};
    o.aspectMask = r.u32();
    o.baseMipLevel = r.u32();
    o.levelCount = r.u32();
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}
function d_VkClearDepthStencilValue(r)
{
    const o = {};
    o.depth = r.f32();
    o.stencil = r.u32();
    return o;
}
function d_VkClearAttachment(r)
{
    const o = {};
    o.aspectMask = r.u32();
    o.colorAttachment = r.u32();
    o.clearValue = d_VkClearValue(r);
    return o;
}
function d_VkClearRect(r)
{
    const o = {};
    o.rect = d_VkRect2D(r);
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}
function d_VkImageResolve(r)
{
    const o = {};
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    o.srcOffset = d_VkOffset3D(r);
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    o.dstOffset = d_VkOffset3D(r);
    o.extent = d_VkExtent3D(r);
    return o;
}
function d_VkMemoryBarrier(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMemoryBarrier_self(r, o);
    return o;
}
function d_VkBufferMemoryBarrier(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferMemoryBarrier_self(r, o);
    return o;
}
function d_VkImageMemoryBarrier(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageMemoryBarrier_self(r, o);
    return o;
}
function d_VkRenderPassBeginInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderPassBeginInfo_self(r, o);
    return o;
}
function d_VkBindBufferMemoryInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBindBufferMemoryInfo_self(r, o);
    return o;
}
function d_VkBindImageMemoryInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBindImageMemoryInfo_self(r, o);
    return o;
}
function d_VkPhysicalDeviceGroupProperties_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceGroupProperties_self_partial(r, o);
    return o;
}
function d_VkImageMemoryRequirementsInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageMemoryRequirementsInfo2_self(r, o);
    return o;
}
function d_VkMemoryRequirements2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkMemoryRequirements2_self_partial(r, o);
    return o;
}
function d_VkBufferMemoryRequirementsInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferMemoryRequirementsInfo2_self(r, o);
    return o;
}
function d_VkImageSparseMemoryRequirementsInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageSparseMemoryRequirementsInfo2_self(r, o);
    return o;
}
function d_VkSparseImageMemoryRequirements2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkSparseImageMemoryRequirements2_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceFeatures2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceFeatures2_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceProperties2_self_partial(r, o);
    return o;
}
function d_VkFormatProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkFormatProperties2_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceImageFormatInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPhysicalDeviceImageFormatInfo2_self(r, o);
    return o;
}
function d_VkImageFormatProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkImageFormatProperties2_self_partial(r, o);
    return o;
}
function d_VkQueueFamilyProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkQueueFamilyProperties2_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceMemoryProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceMemoryProperties2_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceSparseImageFormatInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPhysicalDeviceSparseImageFormatInfo2_self(r, o);
    return o;
}
function d_VkSparseImageFormatProperties2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkSparseImageFormatProperties2_self_partial(r, o);
    return o;
}
function d_VkDeviceQueueInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceQueueInfo2_self(r, o);
    return o;
}
function d_VkSamplerYcbcrConversionCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSamplerYcbcrConversionCreateInfo_self(r, o);
    return o;
}
function d_VkDescriptorUpdateTemplateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDescriptorUpdateTemplateCreateInfo_self(r, o);
    return o;
}
function d_VkPhysicalDeviceExternalBufferInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPhysicalDeviceExternalBufferInfo_self(r, o);
    return o;
}
function d_VkExternalBufferProperties_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkExternalBufferProperties_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceExternalFenceInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPhysicalDeviceExternalFenceInfo_self(r, o);
    return o;
}
function d_VkExternalFenceProperties_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkExternalFenceProperties_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceExternalSemaphoreInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPhysicalDeviceExternalSemaphoreInfo_self(r, o);
    return o;
}
function d_VkExternalSemaphoreProperties_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkExternalSemaphoreProperties_self_partial(r, o);
    return o;
}
function d_VkDescriptorSetLayoutSupport_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkDescriptorSetLayoutSupport_self_partial(r, o);
    return o;
}
function d_VkRenderPassCreateInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderPassCreateInfo2_self(r, o);
    return o;
}
function d_VkSubpassBeginInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubpassBeginInfo_self(r, o);
    return o;
}
function d_VkSubpassEndInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubpassEndInfo_self(r, o);
    return o;
}
function d_VkSemaphoreWaitInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSemaphoreWaitInfo_self(r, o);
    return o;
}
function d_VkSemaphoreSignalInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSemaphoreSignalInfo_self(r, o);
    return o;
}
function d_VkBufferDeviceAddressInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferDeviceAddressInfo_self(r, o);
    return o;
}
function d_VkDeviceMemoryOpaqueCaptureAddressInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceMemoryOpaqueCaptureAddressInfo_self(r, o);
    return o;
}
function d_VkCommandStreamDescriptionMESA(r)
{
    const o = {};
    o.resourceId = r.u32();
    o.offset = r.u64();
    o.size = r.u64();
    return o;
}
function d_VkCommandStreamDependencyMESA(r)
{
    const o = {};
    o.srcCommandStream = r.u32();
    o.dstCommandStream = r.u32();
    return o;
}
function d_VkImageDrmFormatModifierPropertiesEXT_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkImageDrmFormatModifierPropertiesEXT_self_partial(r, o);
    return o;
}
function d_VkRingCreateInfoMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRingCreateInfoMESA_self(r, o);
    return o;
}
function d_VkMemoryResourcePropertiesMESA_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkMemoryResourcePropertiesMESA_self_partial(r, o);
    return o;
}
function d_VkPhysicalDeviceToolProperties_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceToolProperties_self_partial(r, o);
    return o;
}
function d_VkPrivateDataSlotCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPrivateDataSlotCreateInfo_self(r, o);
    return o;
}
function d_VkDependencyInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDependencyInfo_self(r, o);
    return o;
}
function d_VkSubmitInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubmitInfo2_self(r, o);
    return o;
}
function d_VkCopyBufferInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyBufferInfo2_self(r, o);
    return o;
}
function d_VkCopyImageInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyImageInfo2_self(r, o);
    return o;
}
function d_VkCopyBufferToImageInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyBufferToImageInfo2_self(r, o);
    return o;
}
function d_VkCopyImageToBufferInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyImageToBufferInfo2_self(r, o);
    return o;
}
function d_VkBlitImageInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBlitImageInfo2_self(r, o);
    return o;
}
function d_VkResolveImageInfo2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkResolveImageInfo2_self(r, o);
    return o;
}
function d_VkRenderingInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderingInfo_self(r, o);
    return o;
}
function d_VkDeviceBufferMemoryRequirements(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceBufferMemoryRequirements_self(r, o);
    return o;
}
function d_VkDeviceImageMemoryRequirements(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceImageMemoryRequirements_self(r, o);
    return o;
}
function d_VkCalibratedTimestampInfoKHR(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCalibratedTimestampInfoKHR_self(r, o);
    return o;
}
function d_VkConditionalRenderingBeginInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkConditionalRenderingBeginInfoEXT_self(r, o);
    return o;
}
function d_VkImportSemaphoreResourceInfoMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImportSemaphoreResourceInfoMESA_self(r, o);
    return o;
}
function d_VkMultiDrawInfoEXT(r)
{
    const o = {};
    o.firstVertex = r.u32();
    o.vertexCount = r.u32();
    return o;
}
function d_VkMultiDrawIndexedInfoEXT(r)
{
    const o = {};
    o.firstIndex = r.u32();
    o.indexCount = r.u32();
    o.vertexOffset = r.i32();
    return o;
}
function d_VkVertexInputBindingDescription2EXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkVertexInputBindingDescription2EXT_self(r, o);
    return o;
}
function d_VkVertexInputAttributeDescription2EXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkVertexInputAttributeDescription2EXT_self(r, o);
    return o;
}
function d_VkColorBlendEquationEXT(r)
{
    const o = {};
    o.srcColorBlendFactor = r.i32();
    o.dstColorBlendFactor = r.i32();
    o.colorBlendOp = r.i32();
    o.srcAlphaBlendFactor = r.i32();
    o.dstAlphaBlendFactor = r.i32();
    o.alphaBlendOp = r.i32();
    return o;
}
function d_VkColorBlendAdvancedEXT(r)
{
    const o = {};
    o.advancedBlendOp = r.i32();
    o.srcPremultiplied = r.u32();
    o.dstPremultiplied = r.u32();
    o.blendOverlap = r.i32();
    o.clampResults = r.u32();
    return o;
}
function d_VkPhysicalDeviceFragmentShadingRateKHR_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkPhysicalDeviceFragmentShadingRateKHR_self_partial(r, o);
    return o;
}
function d_VkExtent2D(r)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    return o;
}
function d_VkRenderingAreaInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderingAreaInfo_self(r, o);
    return o;
}
function d_VkDeviceImageSubresourceInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceImageSubresourceInfo_self(r, o);
    return o;
}
function d_VkSubresourceLayout2_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkSubresourceLayout2_self_partial(r, o);
    return o;
}
function d_VkImageSubresource2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageSubresource2_self(r, o);
    return o;
}
function d_VkSampleLocationsInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSampleLocationsInfoEXT_self(r, o);
    return o;
}
function d_VkMultisamplePropertiesEXT_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkMultisamplePropertiesEXT_self_partial(r, o);
    return o;
}
function d_VkMemoryUnmapInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMemoryUnmapInfo_self(r, o);
    return o;
}
function d_VkRenderingAttachmentLocationInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderingAttachmentLocationInfo_self(r, o);
    return o;
}
function d_VkRenderingInputAttachmentIndexInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderingInputAttachmentIndexInfo_self(r, o);
    return o;
}
function d_VkBindDescriptorSetsInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBindDescriptorSetsInfo_self(r, o);
    return o;
}
function d_VkPushConstantsInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPushConstantsInfo_self(r, o);
    return o;
}
function d_VkPushDescriptorSetInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPushDescriptorSetInfo_self(r, o);
    return o;
}
function d_VkCopyImageToImageInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyImageToImageInfo_self(r, o);
    return o;
}
function d_VkHostImageLayoutTransitionInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkHostImageLayoutTransitionInfo_self(r, o);
    return o;
}
function d_VkCopyImageToMemoryInfoMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyImageToMemoryInfoMESA_self(r, o);
    return o;
}
function d_VkCopyMemoryToImageInfoMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCopyMemoryToImageInfoMESA_self(r, o);
    return o;
}
function d_VkDepthBiasInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDepthBiasInfoEXT_self(r, o);
    return o;
}
function d_VkDepthClampRangeEXT(r)
{
    const o = {};
    o.minDepthClamp = r.f32();
    o.maxDepthClamp = r.f32();
    return o;
}
function d_VkCooperativeMatrixPropertiesKHR_partial(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT_PARTIAL);
    d_VkCooperativeMatrixPropertiesKHR_self_partial(r, o);
    return o;
}
function d_VkResourceDescriptorInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkResourceDescriptorInfoEXT_self(r, o);
    return o;
}
function d_VkBindHeapInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBindHeapInfoEXT_self(r, o);
    return o;
}
function d_VkPushDataInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPushDataInfoEXT_self(r, o);
    return o;
}
function d_VkHostAddressRangeEXT_partial(r)
{
    const o = {};
    o.size = r.u64();
    const n0 = r.size();
    return o;
}
function d_VkSamplerCustomBorderColorCreateInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSamplerCustomBorderColorCreateInfoEXT_self(r, o);
    return o;
}
function d_VkSampleLocationEXT(r)
{
    const o = {};
    o.x = r.f32();
    o.y = r.f32();
    return o;
}
function d_VkAttachmentSampleLocationsEXT(r)
{
    const o = {};
    o.attachmentIndex = r.u32();
    o.sampleLocationsInfo = d_VkSampleLocationsInfoEXT(r);
    return o;
}
function d_VkSubpassSampleLocationsEXT(r)
{
    const o = {};
    o.subpassIndex = r.u32();
    o.sampleLocationsInfo = d_VkSampleLocationsInfoEXT(r);
    return o;
}
function d_VkPushConstantRange(r)
{
    const o = {};
    o.stageFlags = r.u32();
    o.offset = r.u32();
    o.size = r.u32();
    return o;
}
function d_VkMutableDescriptorTypeListEXT(r)
{
    const o = {};
    o.descriptorTypeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDescriptorTypes = r.i32s(n0);
    }
    else o.pDescriptorTypes = null;
    return o;
}
function d_VkPhysicalDeviceFeatures(r)
{
    const o = {};
    o.robustBufferAccess = r.u32();
    o.fullDrawIndexUint32 = r.u32();
    o.imageCubeArray = r.u32();
    o.independentBlend = r.u32();
    o.geometryShader = r.u32();
    o.tessellationShader = r.u32();
    o.sampleRateShading = r.u32();
    o.dualSrcBlend = r.u32();
    o.logicOp = r.u32();
    o.multiDrawIndirect = r.u32();
    o.drawIndirectFirstInstance = r.u32();
    o.depthClamp = r.u32();
    o.depthBiasClamp = r.u32();
    o.fillModeNonSolid = r.u32();
    o.depthBounds = r.u32();
    o.wideLines = r.u32();
    o.largePoints = r.u32();
    o.alphaToOne = r.u32();
    o.multiViewport = r.u32();
    o.samplerAnisotropy = r.u32();
    o.textureCompressionETC2 = r.u32();
    o.textureCompressionASTC_LDR = r.u32();
    o.textureCompressionBC = r.u32();
    o.occlusionQueryPrecise = r.u32();
    o.pipelineStatisticsQuery = r.u32();
    o.vertexPipelineStoresAndAtomics = r.u32();
    o.fragmentStoresAndAtomics = r.u32();
    o.shaderTessellationAndGeometryPointSize = r.u32();
    o.shaderImageGatherExtended = r.u32();
    o.shaderStorageImageExtendedFormats = r.u32();
    o.shaderStorageImageMultisample = r.u32();
    o.shaderStorageImageReadWithoutFormat = r.u32();
    o.shaderStorageImageWriteWithoutFormat = r.u32();
    o.shaderUniformBufferArrayDynamicIndexing = r.u32();
    o.shaderSampledImageArrayDynamicIndexing = r.u32();
    o.shaderStorageBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageImageArrayDynamicIndexing = r.u32();
    o.shaderClipDistance = r.u32();
    o.shaderCullDistance = r.u32();
    o.shaderFloat64 = r.u32();
    o.shaderInt64 = r.u32();
    o.shaderInt16 = r.u32();
    o.shaderResourceResidency = r.u32();
    o.shaderResourceMinLod = r.u32();
    o.sparseBinding = r.u32();
    o.sparseResidencyBuffer = r.u32();
    o.sparseResidencyImage2D = r.u32();
    o.sparseResidencyImage3D = r.u32();
    o.sparseResidency2Samples = r.u32();
    o.sparseResidency4Samples = r.u32();
    o.sparseResidency8Samples = r.u32();
    o.sparseResidency16Samples = r.u32();
    o.sparseResidencyAliased = r.u32();
    o.variableMultisampleRate = r.u32();
    o.inheritedQueries = r.u32();
    return o;
}
function d_VkFramebufferAttachmentImageInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkFramebufferAttachmentImageInfo_self(r, o);
    return o;
}
function d_VkSubresourceLayout(r)
{
    const o = {};
    o.offset = r.u64();
    o.size = r.u64();
    o.rowPitch = r.u64();
    o.arrayPitch = r.u64();
    o.depthPitch = r.u64();
    return o;
}
function d_VkHostAddressRangeConstEXT(r)
{
    const o = {};
    o.size = r.u64();
    if(o.address)
    {
        const n0 = r.size();
        o.address = r.blob(n0);
    }
    else
    {
        const n1 = r.size();
    }
    return o;
}
function d_VkDescriptorSetAndBindingMappingEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDescriptorSetAndBindingMappingEXT_self(r, o);
    return o;
}
function d_VkVertexInputBindingDivisorDescription(r)
{
    const o = {};
    o.binding = r.u32();
    o.divisor = r.u32();
    return o;
}
function d_VkPipelineCreationFeedback(r)
{
    const o = {};
    o.flags = r.u32();
    o.duration = r.u64();
    return o;
}
function d_VkInputAttachmentAspectReference(r)
{
    const o = {};
    o.subpass = r.u32();
    o.inputAttachmentIndex = r.u32();
    o.aspectMask = r.u32();
    return o;
}
function d_VkAttachmentReference2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkAttachmentReference2_self(r, o);
    return o;
}
function d_VkComponentMapping(r)
{
    const o = {};
    o.r = r.i32();
    o.g = r.i32();
    o.b = r.i32();
    o.a = r.i32();
    return o;
}
function d_VkConformanceVersion_partial(r)
{
    const o = {};
    return o;
}
function d_VkDrmFormatModifierPropertiesEXT_partial(r)
{
    const o = {};
    return o;
}
function d_VkDrmFormatModifierProperties2EXT_partial(r)
{
    const o = {};
    return o;
}
function d_VkExternalMemoryProperties_partial(r)
{
    const o = {};
    return o;
}
function d_VkInstanceCreateInfo_self(r, o)
{
    o.flags = r.u32();
    if(r.u64())
    {
        o.pApplicationInfo = d_VkApplicationInfo(r);
    }
    else o.pApplicationInfo = null;
    o.enabledLayerCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.ppEnabledLayerNames = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            const n1 = r.size();
            o.ppEnabledLayerNames[i] = r.str(n1);
        }
    }
    else o.ppEnabledLayerNames = null;
    o.enabledExtensionCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.ppEnabledExtensionNames = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            const n3 = r.size();
            o.ppEnabledExtensionNames[i] = r.str(n3);
        }
    }
    else o.ppEnabledExtensionNames = null;
}
function d_VkExtent3D_partial(r)
{
    const o = {};
    return o;
}
function d_VkPhysicalDeviceLimits_partial(r)
{
    const o = {};
    return o;
}
function d_VkPhysicalDeviceSparseProperties_partial(r)
{
    const o = {};
    return o;
}
function d_VkMemoryType_partial(r)
{
    const o = {};
    return o;
}
function d_VkMemoryHeap_partial(r)
{
    const o = {};
    return o;
}
function d_VkDeviceCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.queueCreateInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pQueueCreateInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pQueueCreateInfos[i] = d_VkDeviceQueueCreateInfo(r);
        }
    }
    else o.pQueueCreateInfos = null;
    o.enabledLayerCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.ppEnabledLayerNames = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            const n2 = r.size();
            o.ppEnabledLayerNames[i] = r.str(n2);
        }
    }
    else o.ppEnabledLayerNames = null;
    o.enabledExtensionCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.ppEnabledExtensionNames = new Array(n3);
        for(let i = 0; i < n3; i++)
        {
            const n4 = r.size();
            o.ppEnabledExtensionNames[i] = r.str(n4);
        }
    }
    else o.ppEnabledExtensionNames = null;
    if(r.u64())
    {
        o.pEnabledFeatures = d_VkPhysicalDeviceFeatures(r);
    }
    else o.pEnabledFeatures = null;
}
function d_VkSubmitInfo_self(r, o)
{
    o.waitSemaphoreCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pWaitSemaphores = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pWaitSemaphores[i] = r.h();
        }
    }
    else o.pWaitSemaphores = null;
    const n1 = r.size();
    if(n1)
    {
        o.pWaitDstStageMask = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pWaitDstStageMask[i] = r.u32();
        }
    }
    else o.pWaitDstStageMask = null;
    o.commandBufferCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pCommandBuffers = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pCommandBuffers[i] = r.h();
        }
    }
    else o.pCommandBuffers = null;
    o.signalSemaphoreCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.pSignalSemaphores = new Array(n3);
        for(let i = 0; i < n3; i++)
        {
            o.pSignalSemaphores[i] = r.h();
        }
    }
    else o.pSignalSemaphores = null;
}
function d_VkMemoryAllocateInfo_self(r, o)
{
    o.allocationSize = r.u64();
    o.memoryTypeIndex = r.u32();
}
function d_VkMappedMemoryRange_self(r, o)
{
    o.memory = r.h();
    o.offset = r.u64();
    o.size = r.u64();
}
function d_VkBindSparseInfo_self(r, o)
{
    o.waitSemaphoreCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pWaitSemaphores = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pWaitSemaphores[i] = r.h();
        }
    }
    else o.pWaitSemaphores = null;
    o.bufferBindCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pBufferBinds = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pBufferBinds[i] = d_VkSparseBufferMemoryBindInfo(r);
        }
    }
    else o.pBufferBinds = null;
    o.imageOpaqueBindCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pImageOpaqueBinds = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pImageOpaqueBinds[i] = d_VkSparseImageOpaqueMemoryBindInfo(r);
        }
    }
    else o.pImageOpaqueBinds = null;
    o.imageBindCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.pImageBinds = new Array(n3);
        for(let i = 0; i < n3; i++)
        {
            o.pImageBinds[i] = d_VkSparseImageMemoryBindInfo(r);
        }
    }
    else o.pImageBinds = null;
    o.signalSemaphoreCount = r.u32();
    const n4 = r.size();
    if(n4)
    {
        o.pSignalSemaphores = new Array(n4);
        for(let i = 0; i < n4; i++)
        {
            o.pSignalSemaphores[i] = r.h();
        }
    }
    else o.pSignalSemaphores = null;
}
function d_VkFenceCreateInfo_self(r, o)
{
    o.flags = r.u32();
}
function d_VkSemaphoreCreateInfo_self(r, o)
{
    o.flags = r.u32();
}
function d_VkEventCreateInfo_self(r, o)
{
    o.flags = r.u32();
}
function d_VkQueryPoolCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.queryType = r.i32();
    o.queryCount = r.u32();
    o.pipelineStatistics = r.u32();
}
function d_VkBufferCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.size = r.u64();
    o.usage = r.u32();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    if(o.sharingMode === 1)
    {
        const n0 = r.size();
        o.pQueueFamilyIndices = r.u32s(n0);
    }
    else
    {
        const n1 = r.size();
    }
}
function d_VkBufferViewCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.buffer = r.h();
    o.format = r.i32();
    o.offset = r.u64();
    o.range = r.u64();
}
function d_VkImageCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.imageType = r.i32();
    o.format = r.i32();
    o.extent = d_VkExtent3D(r);
    o.mipLevels = r.u32();
    o.arrayLayers = r.u32();
    o.samples = r.i32();
    o.tiling = r.i32();
    o.usage = r.u32();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    if(o.sharingMode === 1)
    {
        const n0 = r.size();
        o.pQueueFamilyIndices = r.u32s(n0);
    }
    else
    {
        const n1 = r.size();
    }
    o.initialLayout = r.i32();
}
function d_VkImageViewCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.image = r.h();
    o.viewType = r.i32();
    o.format = r.i32();
    o.components = d_VkComponentMapping(r);
    o.subresourceRange = d_VkImageSubresourceRange(r);
}
function d_VkPipelineCacheCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.initialDataSize = r.u64();
    const n0 = r.size();
    if(n0)
    {
        o.pInitialData = r.blob(n0);
    }
    else o.pInitialData = null;
}
function d_VkGraphicsPipelineCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.stageCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pStages = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pStages[i] = d_VkPipelineShaderStageCreateInfo(r);
        }
    }
    else o.pStages = null;
    if(r.u64())
    {
        o.pVertexInputState = d_VkPipelineVertexInputStateCreateInfo(r);
    }
    else o.pVertexInputState = null;
    if(r.u64())
    {
        o.pInputAssemblyState = d_VkPipelineInputAssemblyStateCreateInfo(r);
    }
    else o.pInputAssemblyState = null;
    if(r.u64())
    {
        o.pTessellationState = d_VkPipelineTessellationStateCreateInfo(r);
    }
    else o.pTessellationState = null;
    if(r.u64())
    {
        o.pViewportState = d_VkPipelineViewportStateCreateInfo(r);
    }
    else o.pViewportState = null;
    if(r.u64())
    {
        o.pRasterizationState = d_VkPipelineRasterizationStateCreateInfo(r);
    }
    else o.pRasterizationState = null;
    if(r.u64())
    {
        o.pMultisampleState = d_VkPipelineMultisampleStateCreateInfo(r);
    }
    else o.pMultisampleState = null;
    if(r.u64())
    {
        o.pDepthStencilState = d_VkPipelineDepthStencilStateCreateInfo(r);
    }
    else o.pDepthStencilState = null;
    if(r.u64())
    {
        o.pColorBlendState = d_VkPipelineColorBlendStateCreateInfo(r);
    }
    else o.pColorBlendState = null;
    if(r.u64())
    {
        o.pDynamicState = d_VkPipelineDynamicStateCreateInfo(r);
    }
    else o.pDynamicState = null;
    o.layout = r.h();
    o.renderPass = r.h();
    o.subpass = r.u32();
    o.basePipelineHandle = r.h();
    o.basePipelineIndex = r.i32();
}
function d_VkComputePipelineCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.stage = d_VkPipelineShaderStageCreateInfo(r);
    o.layout = r.h();
    o.basePipelineHandle = r.h();
    o.basePipelineIndex = r.i32();
}
function d_VkSamplerCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.magFilter = r.i32();
    o.minFilter = r.i32();
    o.mipmapMode = r.i32();
    o.addressModeU = r.i32();
    o.addressModeV = r.i32();
    o.addressModeW = r.i32();
    o.mipLodBias = r.f32();
    o.anisotropyEnable = r.u32();
    o.maxAnisotropy = r.f32();
    o.compareEnable = r.u32();
    o.compareOp = r.i32();
    o.minLod = r.f32();
    o.maxLod = r.f32();
    o.borderColor = r.i32();
    o.unnormalizedCoordinates = r.u32();
}
function d_VkDescriptorSetLayoutCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.bindingCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pBindings = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pBindings[i] = d_VkDescriptorSetLayoutBinding(r);
        }
    }
    else o.pBindings = null;
}
function d_VkDescriptorPoolCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.maxSets = r.u32();
    o.poolSizeCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pPoolSizes = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pPoolSizes[i] = d_VkDescriptorPoolSize(r);
        }
    }
    else o.pPoolSizes = null;
}
function d_VkDescriptorSetAllocateInfo_self(r, o)
{
    o.descriptorPool = r.h();
    o.descriptorSetCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pSetLayouts = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pSetLayouts[i] = r.h();
        }
    }
    else o.pSetLayouts = null;
}
function d_VkWriteDescriptorSet_self(r, o)
{
    o.dstSet = r.h();
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
    o.descriptorType = r.i32();
    const n0 = r.size();
    if(n0)
    {
        o.pImageInfo = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pImageInfo[i] = d_VkDescriptorImageInfo(r);
        }
    }
    else o.pImageInfo = null;
    const n1 = r.size();
    if(n1)
    {
        o.pBufferInfo = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pBufferInfo[i] = d_VkDescriptorBufferInfo(r);
        }
    }
    else o.pBufferInfo = null;
    const n2 = r.size();
    if(n2)
    {
        o.pTexelBufferView = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pTexelBufferView[i] = r.h();
        }
    }
    else o.pTexelBufferView = null;
}
function d_VkCopyDescriptorSet_self(r, o)
{
    o.srcSet = r.h();
    o.srcBinding = r.u32();
    o.srcArrayElement = r.u32();
    o.dstSet = r.h();
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
}
function d_VkFramebufferCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.renderPass = r.h();
    o.attachmentCount = r.u32();
    if(!(o.flags & 1))
    {
        const n0 = r.size();
        o.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachments[i] = r.h();
        }
    }
    else
    {
        const n1 = r.size();
    }
    o.width = r.u32();
    o.height = r.u32();
    o.layers = r.u32();
}
function d_VkRenderPassCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachments[i] = d_VkAttachmentDescription(r);
        }
    }
    else o.pAttachments = null;
    o.subpassCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pSubpasses = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pSubpasses[i] = d_VkSubpassDescription(r);
        }
    }
    else o.pSubpasses = null;
    o.dependencyCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pDependencies = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pDependencies[i] = d_VkSubpassDependency(r);
        }
    }
    else o.pDependencies = null;
}
function d_VkCommandPoolCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
}
function d_VkCommandBufferAllocateInfo_self(r, o)
{
    o.commandPool = r.h();
    o.level = r.i32();
    o.commandBufferCount = r.u32();
}
function d_VkCommandBufferBeginInfo_self(r, o)
{
    o.flags = r.u32();
    if(r.u64())
    {
        o.pInheritanceInfo = d_VkCommandBufferInheritanceInfo(r);
    }
    else o.pInheritanceInfo = null;
}
function d_VkOffset2D(r)
{
    const o = {};
    o.x = r.i32();
    o.y = r.i32();
    return o;
}
function d_VkImageSubresourceLayers(r)
{
    const o = {};
    o.aspectMask = r.u32();
    o.mipLevel = r.u32();
    o.baseArrayLayer = r.u32();
    o.layerCount = r.u32();
    return o;
}
function d_VkOffset3D(r)
{
    const o = {};
    o.x = r.i32();
    o.y = r.i32();
    o.z = r.i32();
    return o;
}
function d_VkExtent3D(r)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    o.depth = r.u32();
    return o;
}
function d_VkClearValue(r)
{
    const o = {};
    const tag = r.u32();
    o._tag = tag;
    switch(tag)
    {
    case 0:
        o.color = d_VkClearColorValue(r);
        break;
    case 1:
        o.depthStencil = d_VkClearDepthStencilValue(r);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
    return o;
}
function d_VkMemoryBarrier_self(r, o)
{
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
}
function d_VkBufferMemoryBarrier_self(r, o)
{
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.buffer = r.h();
    o.offset = r.u64();
    o.size = r.u64();
}
function d_VkImageMemoryBarrier_self(r, o)
{
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.image = r.h();
    o.subresourceRange = d_VkImageSubresourceRange(r);
}
function d_VkRenderPassBeginInfo_self(r, o)
{
    o.renderPass = r.h();
    o.framebuffer = r.h();
    o.renderArea = d_VkRect2D(r);
    o.clearValueCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pClearValues = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pClearValues[i] = d_VkClearValue(r);
        }
    }
    else o.pClearValues = null;
}
function d_VkBindBufferMemoryInfo_self(r, o)
{
    o.buffer = r.h();
    o.memory = r.h();
    o.memoryOffset = r.u64();
}
function d_VkBindImageMemoryInfo_self(r, o)
{
    o.image = r.h();
    o.memory = r.h();
    o.memoryOffset = r.u64();
}
function d_VkPhysicalDeviceGroupProperties_self_partial(r, o)
{
    const n0 = r.size();
    o.physicalDevices = new Array(n0);
    for(let i = 0; i < n0; i++)
    {
        o.physicalDevices[i] = r.h();
    }
}
function d_VkImageMemoryRequirementsInfo2_self(r, o)
{
    o.image = r.h();
}
function d_VkMemoryRequirements2_self_partial(r, o)
{
    o.memoryRequirements = d_VkMemoryRequirements_partial(r);
}
function d_VkBufferMemoryRequirementsInfo2_self(r, o)
{
    o.buffer = r.h();
}
function d_VkImageSparseMemoryRequirementsInfo2_self(r, o)
{
    o.image = r.h();
}
function d_VkSparseImageMemoryRequirements2_self_partial(r, o)
{
    o.memoryRequirements = d_VkSparseImageMemoryRequirements_partial(r);
}
function d_VkPhysicalDeviceFeatures2_self_partial(r, o)
{
    o.features = d_VkPhysicalDeviceFeatures_partial(r);
}
function d_VkPhysicalDeviceProperties2_self_partial(r, o)
{
    o.properties = d_VkPhysicalDeviceProperties_partial(r);
}
function d_VkFormatProperties2_self_partial(r, o)
{
    o.formatProperties = d_VkFormatProperties_partial(r);
}
function d_VkPhysicalDeviceImageFormatInfo2_self(r, o)
{
    o.format = r.i32();
    o.type = r.i32();
    o.tiling = r.i32();
    o.usage = r.u32();
    o.flags = r.u32();
}
function d_VkImageFormatProperties2_self_partial(r, o)
{
    o.imageFormatProperties = d_VkImageFormatProperties_partial(r);
}
function d_VkQueueFamilyProperties2_self_partial(r, o)
{
    o.queueFamilyProperties = d_VkQueueFamilyProperties_partial(r);
}
function d_VkPhysicalDeviceMemoryProperties2_self_partial(r, o)
{
    o.memoryProperties = d_VkPhysicalDeviceMemoryProperties_partial(r);
}
function d_VkPhysicalDeviceSparseImageFormatInfo2_self(r, o)
{
    o.format = r.i32();
    o.type = r.i32();
    o.samples = r.i32();
    o.usage = r.u32();
    o.tiling = r.i32();
}
function d_VkSparseImageFormatProperties2_self_partial(r, o)
{
    o.properties = d_VkSparseImageFormatProperties_partial(r);
}
function d_VkDeviceQueueInfo2_self(r, o)
{
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
    o.queueIndex = r.u32();
}
function d_VkSamplerYcbcrConversionCreateInfo_self(r, o)
{
    o.format = r.i32();
    o.ycbcrModel = r.i32();
    o.ycbcrRange = r.i32();
    o.components = d_VkComponentMapping(r);
    o.xChromaOffset = r.i32();
    o.yChromaOffset = r.i32();
    o.chromaFilter = r.i32();
    o.forceExplicitReconstruction = r.u32();
}
function d_VkDescriptorUpdateTemplateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.descriptorUpdateEntryCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDescriptorUpdateEntries = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDescriptorUpdateEntries[i] = d_VkDescriptorUpdateTemplateEntry(r);
        }
    }
    else o.pDescriptorUpdateEntries = null;
    o.templateType = r.i32();
    o.descriptorSetLayout = r.h();
    o.pipelineBindPoint = r.i32();
    o.pipelineLayout = r.h();
    o.set = r.u32();
}
function d_VkPhysicalDeviceExternalBufferInfo_self(r, o)
{
    o.flags = r.u32();
    o.usage = r.u32();
    o.handleType = r.i32();
}
function d_VkExternalBufferProperties_self_partial(r, o)
{
    o.externalMemoryProperties = d_VkExternalMemoryProperties_partial(r);
}
function d_VkPhysicalDeviceExternalFenceInfo_self(r, o)
{
    o.handleType = r.i32();
}
function d_VkExternalFenceProperties_self_partial(r, o)
{
}
function d_VkPhysicalDeviceExternalSemaphoreInfo_self(r, o)
{
    o.handleType = r.i32();
}
function d_VkExternalSemaphoreProperties_self_partial(r, o)
{
}
function d_VkDescriptorSetLayoutSupport_self_partial(r, o)
{
}
function d_VkRenderPassCreateInfo2_self(r, o)
{
    o.flags = r.u32();
    o.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachments[i] = d_VkAttachmentDescription2(r);
        }
    }
    else o.pAttachments = null;
    o.subpassCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pSubpasses = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pSubpasses[i] = d_VkSubpassDescription2(r);
        }
    }
    else o.pSubpasses = null;
    o.dependencyCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pDependencies = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pDependencies[i] = d_VkSubpassDependency2(r);
        }
    }
    else o.pDependencies = null;
    o.correlatedViewMaskCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.pCorrelatedViewMasks = r.u32s(n3);
    }
    else o.pCorrelatedViewMasks = null;
}
function d_VkSubpassBeginInfo_self(r, o)
{
    o.contents = r.i32();
}
function d_VkSubpassEndInfo_self(r, o)
{
}
function d_VkSemaphoreWaitInfo_self(r, o)
{
    o.flags = r.u32();
    o.semaphoreCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pSemaphores = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pSemaphores[i] = r.h();
        }
    }
    else o.pSemaphores = null;
    const n1 = r.size();
    if(n1)
    {
        o.pValues = r.u64s(n1);
    }
    else o.pValues = null;
}
function d_VkSemaphoreSignalInfo_self(r, o)
{
    o.semaphore = r.h();
    o.value = r.u64();
}
function d_VkBufferDeviceAddressInfo_self(r, o)
{
    o.buffer = r.h();
}
function d_VkDeviceMemoryOpaqueCaptureAddressInfo_self(r, o)
{
    o.memory = r.h();
}
function d_VkImageDrmFormatModifierPropertiesEXT_self_partial(r, o)
{
}
function d_VkRingCreateInfoMESA_self(r, o)
{
    o.flags = r.u32();
    o.resourceId = r.u32();
    o.offset = r.u64();
    o.size = r.u64();
    o.idleTimeout = r.u64();
    o.headOffset = r.u64();
    o.tailOffset = r.u64();
    o.statusOffset = r.u64();
    o.bufferOffset = r.u64();
    o.bufferSize = r.u64();
    o.extraOffset = r.u64();
    o.extraSize = r.u64();
}
function d_VkMemoryResourcePropertiesMESA_self_partial(r, o)
{
}
function d_VkPhysicalDeviceToolProperties_self_partial(r, o)
{
}
function d_VkPrivateDataSlotCreateInfo_self(r, o)
{
    o.flags = r.u32();
}
function d_VkDependencyInfo_self(r, o)
{
    o.dependencyFlags = r.u32();
    o.memoryBarrierCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pMemoryBarriers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pMemoryBarriers[i] = d_VkMemoryBarrier2(r);
        }
    }
    else o.pMemoryBarriers = null;
    o.bufferMemoryBarrierCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pBufferMemoryBarriers = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pBufferMemoryBarriers[i] = d_VkBufferMemoryBarrier2(r);
        }
    }
    else o.pBufferMemoryBarriers = null;
    o.imageMemoryBarrierCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pImageMemoryBarriers = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pImageMemoryBarriers[i] = d_VkImageMemoryBarrier2(r);
        }
    }
    else o.pImageMemoryBarriers = null;
}
function d_VkSubmitInfo2_self(r, o)
{
    o.flags = r.u32();
    o.waitSemaphoreInfoCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pWaitSemaphoreInfos = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pWaitSemaphoreInfos[i] = d_VkSemaphoreSubmitInfo(r);
        }
    }
    else o.pWaitSemaphoreInfos = null;
    o.commandBufferInfoCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pCommandBufferInfos = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pCommandBufferInfos[i] = d_VkCommandBufferSubmitInfo(r);
        }
    }
    else o.pCommandBufferInfos = null;
    o.signalSemaphoreInfoCount = r.u32();
    const n2 = r.size();
    if(n2)
    {
        o.pSignalSemaphoreInfos = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pSignalSemaphoreInfos[i] = d_VkSemaphoreSubmitInfo(r);
        }
    }
    else o.pSignalSemaphoreInfos = null;
}
function d_VkCopyBufferInfo2_self(r, o)
{
    o.srcBuffer = r.h();
    o.dstBuffer = r.h();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkBufferCopy2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkCopyImageInfo2_self(r, o)
{
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkImageCopy2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkCopyBufferToImageInfo2_self(r, o)
{
    o.srcBuffer = r.h();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkBufferImageCopy2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkCopyImageToBufferInfo2_self(r, o)
{
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstBuffer = r.h();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkBufferImageCopy2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkBlitImageInfo2_self(r, o)
{
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkImageBlit2(r);
        }
    }
    else o.pRegions = null;
    o.filter = r.i32();
}
function d_VkResolveImageInfo2_self(r, o)
{
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkImageResolve2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkRenderingInfo_self(r, o)
{
    o.flags = r.u32();
    o.renderArea = d_VkRect2D(r);
    o.layerCount = r.u32();
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pColorAttachments[i] = d_VkRenderingAttachmentInfo(r);
        }
    }
    else o.pColorAttachments = null;
    if(r.u64())
    {
        o.pDepthAttachment = d_VkRenderingAttachmentInfo(r);
    }
    else o.pDepthAttachment = null;
    if(r.u64())
    {
        o.pStencilAttachment = d_VkRenderingAttachmentInfo(r);
    }
    else o.pStencilAttachment = null;
}
function d_VkDeviceBufferMemoryRequirements_self(r, o)
{
    if(r.u64())
    {
        o.pCreateInfo = d_VkBufferCreateInfo(r);
    }
    else o.pCreateInfo = null;
}
function d_VkDeviceImageMemoryRequirements_self(r, o)
{
    if(r.u64())
    {
        o.pCreateInfo = d_VkImageCreateInfo(r);
    }
    else o.pCreateInfo = null;
    o.planeAspect = r.i32();
}
function d_VkCalibratedTimestampInfoKHR_self(r, o)
{
    o.timeDomain = r.i32();
}
function d_VkConditionalRenderingBeginInfoEXT_self(r, o)
{
    o.buffer = r.h();
    o.offset = r.u64();
    o.flags = r.u32();
}
function d_VkImportSemaphoreResourceInfoMESA_self(r, o)
{
    o.semaphore = r.h();
    o.resourceId = r.u32();
}
function d_VkVertexInputBindingDescription2EXT_self(r, o)
{
    o.binding = r.u32();
    o.stride = r.u32();
    o.inputRate = r.i32();
    o.divisor = r.u32();
}
function d_VkVertexInputAttributeDescription2EXT_self(r, o)
{
    o.location = r.u32();
    o.binding = r.u32();
    o.format = r.i32();
    o.offset = r.u32();
}
function d_VkPhysicalDeviceFragmentShadingRateKHR_self_partial(r, o)
{
    o.fragmentSize = d_VkExtent2D_partial(r);
}
function d_VkRenderingAreaInfo_self(r, o)
{
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pColorAttachmentFormats = r.i32s(n0);
    }
    else o.pColorAttachmentFormats = null;
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
}
function d_VkDeviceImageSubresourceInfo_self(r, o)
{
    if(r.u64())
    {
        o.pCreateInfo = d_VkImageCreateInfo(r);
    }
    else o.pCreateInfo = null;
    if(r.u64())
    {
        o.pSubresource = d_VkImageSubresource2(r);
    }
    else o.pSubresource = null;
}
function d_VkSubresourceLayout2_self_partial(r, o)
{
    o.subresourceLayout = d_VkSubresourceLayout_partial(r);
}
function d_VkImageSubresource2_self(r, o)
{
    o.imageSubresource = d_VkImageSubresource(r);
}
function d_VkMultisamplePropertiesEXT_self_partial(r, o)
{
    o.maxSampleLocationGridSize = d_VkExtent2D_partial(r);
}
function d_VkMemoryUnmapInfo_self(r, o)
{
    o.flags = r.u32();
    o.memory = r.h();
}
function d_VkBindDescriptorSetsInfo_self(r, o)
{
    o.stageFlags = r.u32();
    o.layout = r.h();
    o.firstSet = r.u32();
    o.descriptorSetCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDescriptorSets = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDescriptorSets[i] = r.h();
        }
    }
    else o.pDescriptorSets = null;
    o.dynamicOffsetCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pDynamicOffsets = r.u32s(n1);
    }
    else o.pDynamicOffsets = null;
}
function d_VkPushConstantsInfo_self(r, o)
{
    o.layout = r.h();
    o.stageFlags = r.u32();
    o.offset = r.u32();
    o.size = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pValues = r.blob(n0);
    }
    else o.pValues = null;
}
function d_VkPushDescriptorSetInfo_self(r, o)
{
    o.stageFlags = r.u32();
    o.layout = r.h();
    o.set = r.u32();
    o.descriptorWriteCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDescriptorWrites = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pDescriptorWrites[i] = d_VkWriteDescriptorSet(r);
        }
    }
    else o.pDescriptorWrites = null;
}
function d_VkCopyImageToImageInfo_self(r, o)
{
    o.flags = r.u32();
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkImageCopy2(r);
        }
    }
    else o.pRegions = null;
}
function d_VkHostImageLayoutTransitionInfo_self(r, o)
{
    o.image = r.h();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.subresourceRange = d_VkImageSubresourceRange(r);
}
function d_VkCopyImageToMemoryInfoMESA_self(r, o)
{
    o.flags = r.u32();
    o.srcImage = r.h();
    o.srcImageLayout = r.i32();
    o.memoryRowLength = r.u32();
    o.memoryImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r);
    o.imageOffset = d_VkOffset3D(r);
    o.imageExtent = d_VkExtent3D(r);
}
function d_VkCopyMemoryToImageInfoMESA_self(r, o)
{
    o.flags = r.u32();
    o.dstImage = r.h();
    o.dstImageLayout = r.i32();
    o.regionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pRegions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pRegions[i] = d_VkMemoryToImageCopyMESA(r);
        }
    }
    else o.pRegions = null;
}
function d_VkDepthBiasInfoEXT_self(r, o)
{
    o.depthBiasConstantFactor = r.f32();
    o.depthBiasClamp = r.f32();
    o.depthBiasSlopeFactor = r.f32();
}
function d_VkCooperativeMatrixPropertiesKHR_self_partial(r, o)
{
}
function d_VkResourceDescriptorInfoEXT_self(r, o)
{
    o.type = r.i32();
    o.data = d_VkResourceDescriptorDataEXT(r);
}
function d_VkBindHeapInfoEXT_self(r, o)
{
    o.heapRange = d_VkDeviceAddressRangeEXT(r);
    o.reservedRangeOffset = r.u64();
    o.reservedRangeSize = r.u64();
}
function d_VkPushDataInfoEXT_self(r, o)
{
    o.offset = r.u32();
    o.data = d_VkHostAddressRangeConstEXT(r);
}
function d_VkFramebufferAttachmentImageInfo_self(r, o)
{
    o.flags = r.u32();
    o.usage = r.u32();
    o.width = r.u32();
    o.height = r.u32();
    o.layerCount = r.u32();
    o.viewFormatCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pViewFormats = r.i32s(n0);
    }
    else o.pViewFormats = null;
}
function d_VkDescriptorSetAndBindingMappingEXT_self(r, o)
{
    o.descriptorSet = r.u32();
    o.firstBinding = r.u32();
    o.bindingCount = r.u32();
    o.resourceMask = r.u32();
    o.source = r.i32();
    o.sourceData = d_VkDescriptorMappingSourceDataEXT(r);
}
function d_VkAttachmentReference2_self(r, o)
{
    o.attachment = r.u32();
    o.layout = r.i32();
    o.aspectMask = r.u32();
}
function d_VkApplicationInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkApplicationInfo_self(r, o);
    return o;
}
function d_VkDeviceQueueCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkDeviceQueueCreateInfo_self(r, o);
    return o;
}
function d_VkSparseBufferMemoryBindInfo(r)
{
    const o = {};
    o.buffer = r.h();
    o.bindCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pBinds = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pBinds[i] = d_VkSparseMemoryBind(r);
        }
    }
    else o.pBinds = null;
    return o;
}
function d_VkSparseImageOpaqueMemoryBindInfo(r)
{
    const o = {};
    o.image = r.h();
    o.bindCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pBinds = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pBinds[i] = d_VkSparseMemoryBind(r);
        }
    }
    else o.pBinds = null;
    return o;
}
function d_VkSparseImageMemoryBindInfo(r)
{
    const o = {};
    o.image = r.h();
    o.bindCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pBinds = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pBinds[i] = d_VkSparseImageMemoryBind(r);
        }
    }
    else o.pBinds = null;
    return o;
}
function d_VkPipelineShaderStageCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineShaderStageCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineVertexInputStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineVertexInputStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineInputAssemblyStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineInputAssemblyStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineTessellationStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineTessellationStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineViewportStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineViewportStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineRasterizationStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineRasterizationStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineMultisampleStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineMultisampleStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineDepthStencilStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineDepthStencilStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineColorBlendStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineColorBlendStateCreateInfo_self(r, o);
    return o;
}
function d_VkPipelineDynamicStateCreateInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkPipelineDynamicStateCreateInfo_self(r, o);
    return o;
}
function d_VkDescriptorSetLayoutBinding(r)
{
    const o = {};
    o.binding = r.u32();
    o.descriptorType = r.i32();
    o.descriptorCount = r.u32();
    o.stageFlags = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pImmutableSamplers = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pImmutableSamplers[i] = r.h();
        }
    }
    else o.pImmutableSamplers = null;
    return o;
}
function d_VkDescriptorPoolSize(r)
{
    const o = {};
    o.type = r.i32();
    o.descriptorCount = r.u32();
    return o;
}
function d_VkDescriptorImageInfo(r)
{
    const o = {};
    o.sampler = r.h();
    o.imageView = r.h();
    o.imageLayout = r.i32();
    return o;
}
function d_VkDescriptorBufferInfo(r)
{
    const o = {};
    o.buffer = r.h();
    o.offset = r.u64();
    o.range = r.u64();
    return o;
}
function d_VkAttachmentDescription(r)
{
    const o = {};
    o.flags = r.u32();
    o.format = r.i32();
    o.samples = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.stencilLoadOp = r.i32();
    o.stencilStoreOp = r.i32();
    o.initialLayout = r.i32();
    o.finalLayout = r.i32();
    return o;
}
function d_VkSubpassDescription(r)
{
    const o = {};
    o.flags = r.u32();
    o.pipelineBindPoint = r.i32();
    o.inputAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pInputAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pInputAttachments[i] = d_VkAttachmentReference(r);
        }
    }
    else o.pInputAttachments = null;
    o.colorAttachmentCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pColorAttachments = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pColorAttachments[i] = d_VkAttachmentReference(r);
        }
    }
    else o.pColorAttachments = null;
    const n2 = r.size();
    if(n2)
    {
        o.pResolveAttachments = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pResolveAttachments[i] = d_VkAttachmentReference(r);
        }
    }
    else o.pResolveAttachments = null;
    if(r.u64())
    {
        o.pDepthStencilAttachment = d_VkAttachmentReference(r);
    }
    else o.pDepthStencilAttachment = null;
    o.preserveAttachmentCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.pPreserveAttachments = r.u32s(n3);
    }
    else o.pPreserveAttachments = null;
    return o;
}
function d_VkSubpassDependency(r)
{
    const o = {};
    o.srcSubpass = r.u32();
    o.dstSubpass = r.u32();
    o.srcStageMask = r.u32();
    o.dstStageMask = r.u32();
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.dependencyFlags = r.u32();
    return o;
}
function d_VkCommandBufferInheritanceInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCommandBufferInheritanceInfo_self(r, o);
    return o;
}
function d_VkDescriptorUpdateTemplateEntry(r)
{
    const o = {};
    o.dstBinding = r.u32();
    o.dstArrayElement = r.u32();
    o.descriptorCount = r.u32();
    o.descriptorType = r.i32();
    o.offset = r.u64();
    o.stride = r.u64();
    return o;
}
function d_VkAttachmentDescription2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkAttachmentDescription2_self(r, o);
    return o;
}
function d_VkSubpassDescription2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubpassDescription2_self(r, o);
    return o;
}
function d_VkSubpassDependency2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSubpassDependency2_self(r, o);
    return o;
}
function d_VkMemoryBarrier2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMemoryBarrier2_self(r, o);
    return o;
}
function d_VkBufferMemoryBarrier2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferMemoryBarrier2_self(r, o);
    return o;
}
function d_VkImageMemoryBarrier2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageMemoryBarrier2_self(r, o);
    return o;
}
function d_VkSemaphoreSubmitInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkSemaphoreSubmitInfo_self(r, o);
    return o;
}
function d_VkCommandBufferSubmitInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkCommandBufferSubmitInfo_self(r, o);
    return o;
}
function d_VkBufferCopy2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferCopy2_self(r, o);
    return o;
}
function d_VkImageCopy2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageCopy2_self(r, o);
    return o;
}
function d_VkBufferImageCopy2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkBufferImageCopy2_self(r, o);
    return o;
}
function d_VkImageBlit2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageBlit2_self(r, o);
    return o;
}
function d_VkImageResolve2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageResolve2_self(r, o);
    return o;
}
function d_VkRenderingAttachmentInfo(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkRenderingAttachmentInfo_self(r, o);
    return o;
}
function d_VkMemoryToImageCopyMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkMemoryToImageCopyMESA_self(r, o);
    return o;
}
function d_VkResourceDescriptorDataEXT(r)
{
    const o = {};
    const tag = r.i32();
    o._tag = tag;
    switch(tag)
    {
    case 2:
        if(r.u64())
        {
            o.pImage = d_VkImageDescriptorInfoEXT(r);
        }
        else o.pImage = null;
        break;
    case 3:
        if(r.u64())
        {
            o.pImage = d_VkImageDescriptorInfoEXT(r);
        }
        else o.pImage = null;
        break;
    case 10:
        if(r.u64())
        {
            o.pImage = d_VkImageDescriptorInfoEXT(r);
        }
        else o.pImage = null;
        break;
    case 1000440001:
        if(r.u64())
        {
            o.pImage = d_VkImageDescriptorInfoEXT(r);
        }
        else o.pImage = null;
        break;
    case 1000440000:
        if(r.u64())
        {
            o.pImage = d_VkImageDescriptorInfoEXT(r);
        }
        else o.pImage = null;
        break;
    case 4:
        if(r.u64())
        {
            o.pTexelBuffer = d_VkTexelBufferDescriptorInfoEXT(r);
        }
        else o.pTexelBuffer = null;
        break;
    case 5:
        if(r.u64())
        {
            o.pTexelBuffer = d_VkTexelBufferDescriptorInfoEXT(r);
        }
        else o.pTexelBuffer = null;
        break;
    case 1000150000:
        if(r.u64())
        {
            o.pAddressRange = d_VkDeviceAddressRangeEXT(r);
        }
        else o.pAddressRange = null;
        break;
    case 6:
        if(r.u64())
        {
            o.pAddressRange = d_VkDeviceAddressRangeEXT(r);
        }
        else o.pAddressRange = null;
        break;
    case 7:
        if(r.u64())
        {
            o.pAddressRange = d_VkDeviceAddressRangeEXT(r);
        }
        else o.pAddressRange = null;
        break;
    case 1000460000:
        if(r.u64())
        {
            o.pTensorARM = d_VkTensorViewCreateInfoARM(r);
        }
        else o.pTensorARM = null;
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
    return o;
}
function d_VkDeviceAddressRangeEXT(r)
{
    const o = {};
    o.address = r.u64();
    o.size = r.u64();
    return o;
}
function d_VkDescriptorMappingSourceDataEXT(r)
{
    const o = {};
    const tag = r.i32();
    o._tag = tag;
    switch(tag)
    {
    case 0:
        o.constantOffset = d_VkDescriptorMappingSourceConstantOffsetEXT(r);
        break;
    case 1:
        o.pushIndex = d_VkDescriptorMappingSourcePushIndexEXT(r);
        break;
    case 2:
        o.indirectIndex = d_VkDescriptorMappingSourceIndirectIndexEXT(r);
        break;
    case 3:
        o.indirectIndexArray = d_VkDescriptorMappingSourceIndirectIndexArrayEXT(r);
        break;
    case 4:
        o.heapData = d_VkDescriptorMappingSourceHeapDataEXT(r);
        break;
    case 5:
        o.pushDataOffset = r.u32();
        break;
    case 6:
        o.pushAddressOffset = r.u32();
        break;
    case 7:
        o.indirectAddress = d_VkDescriptorMappingSourceIndirectAddressEXT(r);
        break;
    case 8:
        o.shaderRecordIndex = d_VkDescriptorMappingSourceShaderRecordIndexEXT(r);
        break;
    case 9:
        o.shaderRecordDataOffset = r.u32();
        break;
    case 10:
        o.shaderRecordAddressOffset = r.u32();
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
    return o;
}
function d_VkApplicationInfo_self(r, o)
{
    const n0 = r.size();
    if(n0)
    {
        o.pApplicationName = r.str(n0);
    }
    else o.pApplicationName = null;
    o.applicationVersion = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pEngineName = r.str(n1);
    }
    else o.pEngineName = null;
    o.engineVersion = r.u32();
    o.apiVersion = r.u32();
}
function d_VkDeviceQueueCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.queueFamilyIndex = r.u32();
    o.queueCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pQueuePriorities = r.f32s(n0);
    }
    else o.pQueuePriorities = null;
}
function d_VkSparseMemoryBind(r)
{
    const o = {};
    o.resourceOffset = r.u64();
    o.size = r.u64();
    o.memory = r.h();
    o.memoryOffset = r.u64();
    o.flags = r.u32();
    return o;
}
function d_VkSparseImageMemoryBind(r)
{
    const o = {};
    o.subresource = d_VkImageSubresource(r);
    o.offset = d_VkOffset3D(r);
    o.extent = d_VkExtent3D(r);
    o.memory = r.h();
    o.memoryOffset = r.u64();
    o.flags = r.u32();
    return o;
}
function d_VkPipelineShaderStageCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.stage = r.i32();
    o.module = r.h();
    const n0 = r.size();
    if(n0)
    {
        o.pName = r.str(n0);
    }
    else o.pName = null;
    if(r.u64())
    {
        o.pSpecializationInfo = d_VkSpecializationInfo(r);
    }
    else o.pSpecializationInfo = null;
}
function d_VkPipelineVertexInputStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.vertexBindingDescriptionCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pVertexBindingDescriptions = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pVertexBindingDescriptions[i] = d_VkVertexInputBindingDescription(r);
        }
    }
    else o.pVertexBindingDescriptions = null;
    o.vertexAttributeDescriptionCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pVertexAttributeDescriptions = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pVertexAttributeDescriptions[i] = d_VkVertexInputAttributeDescription(r);
        }
    }
    else o.pVertexAttributeDescriptions = null;
}
function d_VkPipelineInputAssemblyStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.topology = r.i32();
    o.primitiveRestartEnable = r.u32();
}
function d_VkPipelineTessellationStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.patchControlPoints = r.u32();
}
function d_VkPipelineViewportStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.viewportCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pViewports = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pViewports[i] = d_VkViewport(r);
        }
    }
    else o.pViewports = null;
    o.scissorCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pScissors = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pScissors[i] = d_VkRect2D(r);
        }
    }
    else o.pScissors = null;
}
function d_VkPipelineRasterizationStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.depthClampEnable = r.u32();
    o.rasterizerDiscardEnable = r.u32();
    o.polygonMode = r.i32();
    o.cullMode = r.u32();
    o.frontFace = r.i32();
    o.depthBiasEnable = r.u32();
    o.depthBiasConstantFactor = r.f32();
    o.depthBiasClamp = r.f32();
    o.depthBiasSlopeFactor = r.f32();
    o.lineWidth = r.f32();
}
function d_VkPipelineMultisampleStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.rasterizationSamples = r.i32();
    o.sampleShadingEnable = r.u32();
    o.minSampleShading = r.f32();
    const n0 = r.size();
    if(n0)
    {
        o.pSampleMask = r.u32s(n0);
    }
    else o.pSampleMask = null;
    o.alphaToCoverageEnable = r.u32();
    o.alphaToOneEnable = r.u32();
}
function d_VkPipelineDepthStencilStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.depthTestEnable = r.u32();
    o.depthWriteEnable = r.u32();
    o.depthCompareOp = r.i32();
    o.depthBoundsTestEnable = r.u32();
    o.stencilTestEnable = r.u32();
    o.front = d_VkStencilOpState(r);
    o.back = d_VkStencilOpState(r);
    o.minDepthBounds = r.f32();
    o.maxDepthBounds = r.f32();
}
function d_VkPipelineColorBlendStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.logicOpEnable = r.u32();
    o.logicOp = r.i32();
    o.attachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pAttachments[i] = d_VkPipelineColorBlendAttachmentState(r);
        }
    }
    else o.pAttachments = null;
    const n1 = r.size();
    o.blendConstants = r.f32s(n1);
}
function d_VkPipelineDynamicStateCreateInfo_self(r, o)
{
    o.flags = r.u32();
    o.dynamicStateCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pDynamicStates = r.i32s(n0);
    }
    else o.pDynamicStates = null;
}
function d_VkAttachmentReference(r)
{
    const o = {};
    o.attachment = r.u32();
    o.layout = r.i32();
    return o;
}
function d_VkCommandBufferInheritanceInfo_self(r, o)
{
    o.renderPass = r.h();
    o.subpass = r.u32();
    o.framebuffer = r.h();
    o.occlusionQueryEnable = r.u32();
    o.queryFlags = r.u32();
    o.pipelineStatistics = r.u32();
}
function d_VkAttachmentDescription2_self(r, o)
{
    o.flags = r.u32();
    o.format = r.i32();
    o.samples = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.stencilLoadOp = r.i32();
    o.stencilStoreOp = r.i32();
    o.initialLayout = r.i32();
    o.finalLayout = r.i32();
}
function d_VkSubpassDescription2_self(r, o)
{
    o.flags = r.u32();
    o.pipelineBindPoint = r.i32();
    o.viewMask = r.u32();
    o.inputAttachmentCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pInputAttachments = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pInputAttachments[i] = d_VkAttachmentReference2(r);
        }
    }
    else o.pInputAttachments = null;
    o.colorAttachmentCount = r.u32();
    const n1 = r.size();
    if(n1)
    {
        o.pColorAttachments = new Array(n1);
        for(let i = 0; i < n1; i++)
        {
            o.pColorAttachments[i] = d_VkAttachmentReference2(r);
        }
    }
    else o.pColorAttachments = null;
    const n2 = r.size();
    if(n2)
    {
        o.pResolveAttachments = new Array(n2);
        for(let i = 0; i < n2; i++)
        {
            o.pResolveAttachments[i] = d_VkAttachmentReference2(r);
        }
    }
    else o.pResolveAttachments = null;
    if(r.u64())
    {
        o.pDepthStencilAttachment = d_VkAttachmentReference2(r);
    }
    else o.pDepthStencilAttachment = null;
    o.preserveAttachmentCount = r.u32();
    const n3 = r.size();
    if(n3)
    {
        o.pPreserveAttachments = r.u32s(n3);
    }
    else o.pPreserveAttachments = null;
}
function d_VkSubpassDependency2_self(r, o)
{
    o.srcSubpass = r.u32();
    o.dstSubpass = r.u32();
    o.srcStageMask = r.u32();
    o.dstStageMask = r.u32();
    o.srcAccessMask = r.u32();
    o.dstAccessMask = r.u32();
    o.dependencyFlags = r.u32();
    o.viewOffset = r.i32();
}
function d_VkBufferMemoryBarrier2_self(r, o)
{
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.buffer = r.h();
    o.offset = r.u64();
    o.size = r.u64();
}
function d_VkImageMemoryBarrier2_self(r, o)
{
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    o.oldLayout = r.i32();
    o.newLayout = r.i32();
    o.srcQueueFamilyIndex = r.u32();
    o.dstQueueFamilyIndex = r.u32();
    o.image = r.h();
    o.subresourceRange = d_VkImageSubresourceRange(r);
}
function d_VkSemaphoreSubmitInfo_self(r, o)
{
    o.semaphore = r.h();
    o.value = r.u64();
    o.stageMask = r.u64();
    o.deviceIndex = r.u32();
}
function d_VkCommandBufferSubmitInfo_self(r, o)
{
    o.commandBuffer = r.h();
    o.deviceMask = r.u32();
}
function d_VkBufferCopy2_self(r, o)
{
    o.srcOffset = r.u64();
    o.dstOffset = r.u64();
    o.size = r.u64();
}
function d_VkImageCopy2_self(r, o)
{
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    o.srcOffset = d_VkOffset3D(r);
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    o.dstOffset = d_VkOffset3D(r);
    o.extent = d_VkExtent3D(r);
}
function d_VkBufferImageCopy2_self(r, o)
{
    o.bufferOffset = r.u64();
    o.bufferRowLength = r.u32();
    o.bufferImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r);
    o.imageOffset = d_VkOffset3D(r);
    o.imageExtent = d_VkExtent3D(r);
}
function d_VkImageBlit2_self(r, o)
{
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    const n0 = r.size();
    o.srcOffsets = new Array(n0);
    for(let i = 0; i < n0; i++)
    {
        o.srcOffsets[i] = d_VkOffset3D(r);
    }
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    const n1 = r.size();
    o.dstOffsets = new Array(n1);
    for(let i = 0; i < n1; i++)
    {
        o.dstOffsets[i] = d_VkOffset3D(r);
    }
}
function d_VkImageResolve2_self(r, o)
{
    o.srcSubresource = d_VkImageSubresourceLayers(r);
    o.srcOffset = d_VkOffset3D(r);
    o.dstSubresource = d_VkImageSubresourceLayers(r);
    o.dstOffset = d_VkOffset3D(r);
    o.extent = d_VkExtent3D(r);
}
function d_VkRenderingAttachmentInfo_self(r, o)
{
    o.imageView = r.h();
    o.imageLayout = r.i32();
    o.resolveMode = r.i32();
    o.resolveImageView = r.h();
    o.resolveImageLayout = r.i32();
    o.loadOp = r.i32();
    o.storeOp = r.i32();
    o.clearValue = d_VkClearValue(r);
}
function d_VkMemoryToImageCopyMESA_self(r, o)
{
    o.dataSize = r.u64();
    const n0 = r.size();
    if(n0)
    {
        o.pData = r.blob(n0);
    }
    else o.pData = null;
    o.memoryRowLength = r.u32();
    o.memoryImageHeight = r.u32();
    o.imageSubresource = d_VkImageSubresourceLayers(r);
    o.imageOffset = d_VkOffset3D(r);
    o.imageExtent = d_VkExtent3D(r);
}
function d_VkImageDescriptorInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkImageDescriptorInfoEXT_self(r, o);
    return o;
}
function d_VkTexelBufferDescriptorInfoEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkTexelBufferDescriptorInfoEXT_self(r, o);
    return o;
}
function d_VkTensorViewCreateInfoARM(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(PNEXT);
    d_VkTensorViewCreateInfoARM_self(r, o);
    return o;
}
function d_VkDescriptorMappingSourceConstantOffsetEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.heapArrayStride = r.u32();
    if(r.u64())
    {
        o.pEmbeddedSampler = d_VkSamplerCreateInfo(r);
    }
    else o.pEmbeddedSampler = null;
    o.samplerHeapOffset = r.u32();
    o.samplerHeapArrayStride = r.u32();
    return o;
}
function d_VkDescriptorMappingSourcePushIndexEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.pushOffset = r.u32();
    o.heapIndexStride = r.u32();
    o.heapArrayStride = r.u32();
    if(r.u64())
    {
        o.pEmbeddedSampler = d_VkSamplerCreateInfo(r);
    }
    else o.pEmbeddedSampler = null;
    o.useCombinedImageSamplerIndex = r.u32();
    o.samplerHeapOffset = r.u32();
    o.samplerPushOffset = r.u32();
    o.samplerHeapIndexStride = r.u32();
    o.samplerHeapArrayStride = r.u32();
    return o;
}
function d_VkDescriptorMappingSourceIndirectIndexEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.pushOffset = r.u32();
    o.addressOffset = r.u32();
    o.heapIndexStride = r.u32();
    o.heapArrayStride = r.u32();
    if(r.u64())
    {
        o.pEmbeddedSampler = d_VkSamplerCreateInfo(r);
    }
    else o.pEmbeddedSampler = null;
    o.useCombinedImageSamplerIndex = r.u32();
    o.samplerHeapOffset = r.u32();
    o.samplerPushOffset = r.u32();
    o.samplerAddressOffset = r.u32();
    o.samplerHeapIndexStride = r.u32();
    o.samplerHeapArrayStride = r.u32();
    return o;
}
function d_VkDescriptorMappingSourceIndirectIndexArrayEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.pushOffset = r.u32();
    o.addressOffset = r.u32();
    o.heapIndexStride = r.u32();
    if(r.u64())
    {
        o.pEmbeddedSampler = d_VkSamplerCreateInfo(r);
    }
    else o.pEmbeddedSampler = null;
    o.useCombinedImageSamplerIndex = r.u32();
    o.samplerHeapOffset = r.u32();
    o.samplerPushOffset = r.u32();
    o.samplerAddressOffset = r.u32();
    o.samplerHeapIndexStride = r.u32();
    return o;
}
function d_VkDescriptorMappingSourceHeapDataEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.pushOffset = r.u32();
    return o;
}
function d_VkDescriptorMappingSourceIndirectAddressEXT(r)
{
    const o = {};
    o.pushOffset = r.u32();
    o.addressOffset = r.u32();
    return o;
}
function d_VkDescriptorMappingSourceShaderRecordIndexEXT(r)
{
    const o = {};
    o.heapOffset = r.u32();
    o.shaderRecordOffset = r.u32();
    o.heapIndexStride = r.u32();
    o.heapArrayStride = r.u32();
    if(r.u64())
    {
        o.pEmbeddedSampler = d_VkSamplerCreateInfo(r);
    }
    else o.pEmbeddedSampler = null;
    o.useCombinedImageSamplerIndex = r.u32();
    o.samplerHeapOffset = r.u32();
    o.samplerShaderRecordOffset = r.u32();
    o.samplerHeapIndexStride = r.u32();
    o.samplerHeapArrayStride = r.u32();
    return o;
}
function d_VkSpecializationInfo(r)
{
    const o = {};
    o.mapEntryCount = r.u32();
    const n0 = r.size();
    if(n0)
    {
        o.pMapEntries = new Array(n0);
        for(let i = 0; i < n0; i++)
        {
            o.pMapEntries[i] = d_VkSpecializationMapEntry(r);
        }
    }
    else o.pMapEntries = null;
    o.dataSize = r.u64();
    const n1 = r.size();
    if(n1)
    {
        o.pData = r.blob(n1);
    }
    else o.pData = null;
    return o;
}
function d_VkVertexInputBindingDescription(r)
{
    const o = {};
    o.binding = r.u32();
    o.stride = r.u32();
    o.inputRate = r.i32();
    return o;
}
function d_VkVertexInputAttributeDescription(r)
{
    const o = {};
    o.location = r.u32();
    o.binding = r.u32();
    o.format = r.i32();
    o.offset = r.u32();
    return o;
}
function d_VkStencilOpState(r)
{
    const o = {};
    o.failOp = r.i32();
    o.passOp = r.i32();
    o.depthFailOp = r.i32();
    o.compareOp = r.i32();
    o.compareMask = r.u32();
    o.writeMask = r.u32();
    o.reference = r.u32();
    return o;
}
function d_VkPipelineColorBlendAttachmentState(r)
{
    const o = {};
    o.blendEnable = r.u32();
    o.srcColorBlendFactor = r.i32();
    o.dstColorBlendFactor = r.i32();
    o.colorBlendOp = r.i32();
    o.srcAlphaBlendFactor = r.i32();
    o.dstAlphaBlendFactor = r.i32();
    o.alphaBlendOp = r.i32();
    o.colorWriteMask = r.u32();
    return o;
}
function d_VkImageDescriptorInfoEXT_self(r, o)
{
    if(r.u64())
    {
        o.pView = d_VkImageViewCreateInfo(r);
    }
    else o.pView = null;
    o.layout = r.i32();
}
function d_VkTexelBufferDescriptorInfoEXT_self(r, o)
{
    o.format = r.i32();
    o.addressRange = d_VkDeviceAddressRangeEXT(r);
}
function d_VkTensorViewCreateInfoARM_self(r, o)
{
    o.flags = r.u64();
    o.tensor = r.h();
    o.format = r.i32();
}
function d_VkSpecializationMapEntry(r)
{
    const o = {};
    o.constantID = r.u32();
    o.offset = r.u32();
    o.size = r.u64();
    return o;
}
function e_vkCreateInstance_reply(w, a)
{
    w.u32(0);
    w.i32(a.ret);
    if(a.pInstance != null)
    {
        w.u64(1);
        w.h(a.pInstance);
    }
    else w.u64(0);
}
function e_vkDestroyInstance_reply(w, a)
{
    w.u32(1);
}
function e_vkEnumeratePhysicalDevices_reply(w, a)
{
    w.u32(2);
    w.i32(a.ret);
    if(a.pPhysicalDeviceCount != null)
    {
        w.u64(1);
        w.u32(a.pPhysicalDeviceCount);
    }
    else w.u64(0);
    if(a.pPhysicalDevices)
    {
        const n0 = (a.pPhysicalDeviceCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pPhysicalDevices ? a.pPhysicalDevices[i] : undefined;
            w.h(item);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceFeatures_reply(w, a)
{
    w.u32(3);
    if(a.pFeatures != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceFeatures(w, a.pFeatures || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceFormatProperties_reply(w, a)
{
    w.u32(4);
    if(a.pFormatProperties != null)
    {
        w.u64(1);
        e_VkFormatProperties(w, a.pFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceImageFormatProperties_reply(w, a)
{
    w.u32(5);
    w.i32(a.ret);
    if(a.pImageFormatProperties != null)
    {
        w.u64(1);
        e_VkImageFormatProperties(w, a.pImageFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceProperties_reply(w, a)
{
    w.u32(6);
    if(a.pProperties != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceProperties(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceQueueFamilyProperties_reply(w, a)
{
    w.u32(7);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pQueueFamilyPropertyCount);
    }
    else w.u64(0);
    if(a.pQueueFamilyProperties)
    {
        const n0 = (a.pQueueFamilyPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pQueueFamilyProperties ? a.pQueueFamilyProperties[i] : undefined;
            e_VkQueueFamilyProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceMemoryProperties_reply(w, a)
{
    w.u32(8);
    if(a.pMemoryProperties != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceMemoryProperties(w, a.pMemoryProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkCreateDevice_reply(w, a)
{
    w.u32(11);
    w.i32(a.ret);
    if(a.pDevice != null)
    {
        w.u64(1);
        w.h(a.pDevice);
    }
    else w.u64(0);
}
function e_vkDestroyDevice_reply(w, a)
{
    w.u32(12);
}
function e_vkEnumerateInstanceExtensionProperties_reply(w, a)
{
    w.u32(13);
    w.i32(a.ret);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkExtensionProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkEnumerateDeviceExtensionProperties_reply(w, a)
{
    w.u32(14);
    w.i32(a.ret);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkExtensionProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkEnumerateInstanceLayerProperties_reply(w, a)
{
    w.u32(15);
    w.i32(a.ret);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkLayerProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkEnumerateDeviceLayerProperties_reply(w, a)
{
    w.u32(16);
    w.i32(a.ret);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkLayerProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetDeviceQueue_reply(w, a)
{
    w.u32(17);
    if(a.pQueue != null)
    {
        w.u64(1);
        w.h(a.pQueue);
    }
    else w.u64(0);
}
function e_vkQueueSubmit_reply(w, a)
{
    w.u32(18);
    w.i32(a.ret);
}
function e_vkQueueWaitIdle_reply(w, a)
{
    w.u32(19);
    w.i32(a.ret);
}
function e_vkDeviceWaitIdle_reply(w, a)
{
    w.u32(20);
    w.i32(a.ret);
}
function e_vkAllocateMemory_reply(w, a)
{
    w.u32(21);
    w.i32(a.ret);
    if(a.pMemory != null)
    {
        w.u64(1);
        w.h(a.pMemory);
    }
    else w.u64(0);
}
function e_vkFreeMemory_reply(w, a)
{
    w.u32(22);
}
function e_vkUnmapMemory_reply(w, a)
{
    w.u32(24);
}
function e_vkFlushMappedMemoryRanges_reply(w, a)
{
    w.u32(25);
    w.i32(a.ret);
}
function e_vkInvalidateMappedMemoryRanges_reply(w, a)
{
    w.u32(26);
    w.i32(a.ret);
}
function e_vkGetDeviceMemoryCommitment_reply(w, a)
{
    w.u32(27);
    if(a.pCommittedMemoryInBytes != null)
    {
        w.u64(1);
        w.u64(a.pCommittedMemoryInBytes);
    }
    else w.u64(0);
}
function e_vkBindBufferMemory_reply(w, a)
{
    w.u32(28);
    w.i32(a.ret);
}
function e_vkBindImageMemory_reply(w, a)
{
    w.u32(29);
    w.i32(a.ret);
}
function e_vkGetBufferMemoryRequirements_reply(w, a)
{
    w.u32(30);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetImageMemoryRequirements_reply(w, a)
{
    w.u32(31);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetImageSparseMemoryRequirements_reply(w, a)
{
    w.u32(32);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        const n0 = (a.pSparseMemoryRequirementCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pSparseMemoryRequirements ? a.pSparseMemoryRequirements[i] : undefined;
            e_VkSparseImageMemoryRequirements(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceSparseImageFormatProperties_reply(w, a)
{
    w.u32(33);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkSparseImageFormatProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkQueueBindSparse_reply(w, a)
{
    w.u32(34);
    w.i32(a.ret);
}
function e_vkCreateFence_reply(w, a)
{
    w.u32(35);
    w.i32(a.ret);
    if(a.pFence != null)
    {
        w.u64(1);
        w.h(a.pFence);
    }
    else w.u64(0);
}
function e_vkDestroyFence_reply(w, a)
{
    w.u32(36);
}
function e_vkResetFences_reply(w, a)
{
    w.u32(37);
    w.i32(a.ret);
}
function e_vkGetFenceStatus_reply(w, a)
{
    w.u32(38);
    w.i32(a.ret);
}
function e_vkWaitForFences_reply(w, a)
{
    w.u32(39);
    w.i32(a.ret);
}
function e_vkCreateSemaphore_reply(w, a)
{
    w.u32(40);
    w.i32(a.ret);
    if(a.pSemaphore != null)
    {
        w.u64(1);
        w.h(a.pSemaphore);
    }
    else w.u64(0);
}
function e_vkDestroySemaphore_reply(w, a)
{
    w.u32(41);
}
function e_vkCreateEvent_reply(w, a)
{
    w.u32(42);
    w.i32(a.ret);
    if(a.pEvent != null)
    {
        w.u64(1);
        w.h(a.pEvent);
    }
    else w.u64(0);
}
function e_vkDestroyEvent_reply(w, a)
{
    w.u32(43);
}
function e_vkGetEventStatus_reply(w, a)
{
    w.u32(44);
    w.i32(a.ret);
}
function e_vkSetEvent_reply(w, a)
{
    w.u32(45);
    w.i32(a.ret);
}
function e_vkResetEvent_reply(w, a)
{
    w.u32(46);
    w.i32(a.ret);
}
function e_vkCreateQueryPool_reply(w, a)
{
    w.u32(47);
    w.i32(a.ret);
    if(a.pQueryPool != null)
    {
        w.u64(1);
        w.h(a.pQueryPool);
    }
    else w.u64(0);
}
function e_vkDestroyQueryPool_reply(w, a)
{
    w.u32(48);
}
function e_vkGetQueryPoolResults_reply(w, a)
{
    w.u32(49);
    w.i32(a.ret);
    if(a.pData)
    {
        const n0 = a.dataSize;
        w.size(n0);
        w.blob(a.pData, n0);
    }
    else w.size(0);
}
function e_vkCreateBuffer_reply(w, a)
{
    w.u32(50);
    w.i32(a.ret);
    if(a.pBuffer != null)
    {
        w.u64(1);
        w.h(a.pBuffer);
    }
    else w.u64(0);
}
function e_vkDestroyBuffer_reply(w, a)
{
    w.u32(51);
}
function e_vkCreateBufferView_reply(w, a)
{
    w.u32(52);
    w.i32(a.ret);
    if(a.pView != null)
    {
        w.u64(1);
        w.h(a.pView);
    }
    else w.u64(0);
}
function e_vkDestroyBufferView_reply(w, a)
{
    w.u32(53);
}
function e_vkCreateImage_reply(w, a)
{
    w.u32(54);
    w.i32(a.ret);
    if(a.pImage != null)
    {
        w.u64(1);
        w.h(a.pImage);
    }
    else w.u64(0);
}
function e_vkDestroyImage_reply(w, a)
{
    w.u32(55);
}
function e_vkGetImageSubresourceLayout_reply(w, a)
{
    w.u32(56);
    if(a.pLayout != null)
    {
        w.u64(1);
        e_VkSubresourceLayout(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function e_vkCreateImageView_reply(w, a)
{
    w.u32(57);
    w.i32(a.ret);
    if(a.pView != null)
    {
        w.u64(1);
        w.h(a.pView);
    }
    else w.u64(0);
}
function e_vkDestroyImageView_reply(w, a)
{
    w.u32(58);
}
function e_vkCreateShaderModule_reply(w, a)
{
    w.u32(59);
    w.i32(a.ret);
    if(a.pShaderModule != null)
    {
        w.u64(1);
        w.h(a.pShaderModule);
    }
    else w.u64(0);
}
function e_vkDestroyShaderModule_reply(w, a)
{
    w.u32(60);
}
function e_vkCreatePipelineCache_reply(w, a)
{
    w.u32(61);
    w.i32(a.ret);
    if(a.pPipelineCache != null)
    {
        w.u64(1);
        w.h(a.pPipelineCache);
    }
    else w.u64(0);
}
function e_vkDestroyPipelineCache_reply(w, a)
{
    w.u32(62);
}
function e_vkGetPipelineCacheData_reply(w, a)
{
    w.u32(63);
    w.i32(a.ret);
    if(a.pDataSize != null)
    {
        w.u64(1);
        w.u64(a.pDataSize);
    }
    else w.u64(0);
    if(a.pData)
    {
        const n0 = (a.pDataSize || 0);
        w.size(n0);
        w.blob(a.pData, n0);
    }
    else w.size(0);
}
function e_vkMergePipelineCaches_reply(w, a)
{
    w.u32(64);
    w.i32(a.ret);
}
function e_vkCreateGraphicsPipelines_reply(w, a)
{
    w.u32(65);
    w.i32(a.ret);
    if(a.pPipelines)
    {
        const n0 = a.createInfoCount;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pPipelines ? a.pPipelines[i] : undefined;
            w.h(item);
        }
    }
    else w.size(0);
}
function e_vkCreateComputePipelines_reply(w, a)
{
    w.u32(66);
    w.i32(a.ret);
    if(a.pPipelines)
    {
        const n0 = a.createInfoCount;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pPipelines ? a.pPipelines[i] : undefined;
            w.h(item);
        }
    }
    else w.size(0);
}
function e_vkDestroyPipeline_reply(w, a)
{
    w.u32(67);
}
function e_vkCreatePipelineLayout_reply(w, a)
{
    w.u32(68);
    w.i32(a.ret);
    if(a.pPipelineLayout != null)
    {
        w.u64(1);
        w.h(a.pPipelineLayout);
    }
    else w.u64(0);
}
function e_vkDestroyPipelineLayout_reply(w, a)
{
    w.u32(69);
}
function e_vkCreateSampler_reply(w, a)
{
    w.u32(70);
    w.i32(a.ret);
    if(a.pSampler != null)
    {
        w.u64(1);
        w.h(a.pSampler);
    }
    else w.u64(0);
}
function e_vkDestroySampler_reply(w, a)
{
    w.u32(71);
}
function e_vkCreateDescriptorSetLayout_reply(w, a)
{
    w.u32(72);
    w.i32(a.ret);
    if(a.pSetLayout != null)
    {
        w.u64(1);
        w.h(a.pSetLayout);
    }
    else w.u64(0);
}
function e_vkDestroyDescriptorSetLayout_reply(w, a)
{
    w.u32(73);
}
function e_vkCreateDescriptorPool_reply(w, a)
{
    w.u32(74);
    w.i32(a.ret);
    if(a.pDescriptorPool != null)
    {
        w.u64(1);
        w.h(a.pDescriptorPool);
    }
    else w.u64(0);
}
function e_vkDestroyDescriptorPool_reply(w, a)
{
    w.u32(75);
}
function e_vkResetDescriptorPool_reply(w, a)
{
    w.u32(76);
    w.i32(a.ret);
}
function e_vkAllocateDescriptorSets_reply(w, a)
{
    w.u32(77);
    w.i32(a.ret);
    if(a.pDescriptorSets)
    {
        const n0 = (a.pAllocateInfo ? a.pAllocateInfo.descriptorSetCount : 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pDescriptorSets ? a.pDescriptorSets[i] : undefined;
            w.h(item);
        }
    }
    else w.size(0);
}
function e_vkFreeDescriptorSets_reply(w, a)
{
    w.u32(78);
    w.i32(a.ret);
}
function e_vkUpdateDescriptorSets_reply(w, a)
{
    w.u32(79);
}
function e_vkCreateFramebuffer_reply(w, a)
{
    w.u32(80);
    w.i32(a.ret);
    if(a.pFramebuffer != null)
    {
        w.u64(1);
        w.h(a.pFramebuffer);
    }
    else w.u64(0);
}
function e_vkDestroyFramebuffer_reply(w, a)
{
    w.u32(81);
}
function e_vkCreateRenderPass_reply(w, a)
{
    w.u32(82);
    w.i32(a.ret);
    if(a.pRenderPass != null)
    {
        w.u64(1);
        w.h(a.pRenderPass);
    }
    else w.u64(0);
}
function e_vkDestroyRenderPass_reply(w, a)
{
    w.u32(83);
}
function e_vkGetRenderAreaGranularity_reply(w, a)
{
    w.u32(84);
    if(a.pGranularity != null)
    {
        w.u64(1);
        e_VkExtent2D(w, a.pGranularity || EMPTY);
    }
    else w.u64(0);
}
function e_vkCreateCommandPool_reply(w, a)
{
    w.u32(85);
    w.i32(a.ret);
    if(a.pCommandPool != null)
    {
        w.u64(1);
        w.h(a.pCommandPool);
    }
    else w.u64(0);
}
function e_vkDestroyCommandPool_reply(w, a)
{
    w.u32(86);
}
function e_vkResetCommandPool_reply(w, a)
{
    w.u32(87);
    w.i32(a.ret);
}
function e_vkAllocateCommandBuffers_reply(w, a)
{
    w.u32(88);
    w.i32(a.ret);
    if(a.pCommandBuffers)
    {
        const n0 = (a.pAllocateInfo ? a.pAllocateInfo.commandBufferCount : 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pCommandBuffers ? a.pCommandBuffers[i] : undefined;
            w.h(item);
        }
    }
    else w.size(0);
}
function e_vkFreeCommandBuffers_reply(w, a)
{
    w.u32(89);
}
function e_vkBeginCommandBuffer_reply(w, a)
{
    w.u32(90);
    w.i32(a.ret);
}
function e_vkEndCommandBuffer_reply(w, a)
{
    w.u32(91);
    w.i32(a.ret);
}
function e_vkResetCommandBuffer_reply(w, a)
{
    w.u32(92);
    w.i32(a.ret);
}
function e_vkCmdBindPipeline_reply(w, a)
{
    w.u32(93);
}
function e_vkCmdSetViewport_reply(w, a)
{
    w.u32(94);
}
function e_vkCmdSetScissor_reply(w, a)
{
    w.u32(95);
}
function e_vkCmdSetLineWidth_reply(w, a)
{
    w.u32(96);
}
function e_vkCmdSetDepthBias_reply(w, a)
{
    w.u32(97);
}
function e_vkCmdSetBlendConstants_reply(w, a)
{
    w.u32(98);
}
function e_vkCmdSetDepthBounds_reply(w, a)
{
    w.u32(99);
}
function e_vkCmdSetStencilCompareMask_reply(w, a)
{
    w.u32(100);
}
function e_vkCmdSetStencilWriteMask_reply(w, a)
{
    w.u32(101);
}
function e_vkCmdSetStencilReference_reply(w, a)
{
    w.u32(102);
}
function e_vkCmdBindDescriptorSets_reply(w, a)
{
    w.u32(103);
}
function e_vkCmdBindIndexBuffer_reply(w, a)
{
    w.u32(104);
}
function e_vkCmdBindVertexBuffers_reply(w, a)
{
    w.u32(105);
}
function e_vkCmdDraw_reply(w, a)
{
    w.u32(106);
}
function e_vkCmdDrawIndexed_reply(w, a)
{
    w.u32(107);
}
function e_vkCmdDrawIndirect_reply(w, a)
{
    w.u32(108);
}
function e_vkCmdDrawIndexedIndirect_reply(w, a)
{
    w.u32(109);
}
function e_vkCmdDispatch_reply(w, a)
{
    w.u32(110);
}
function e_vkCmdDispatchIndirect_reply(w, a)
{
    w.u32(111);
}
function e_vkCmdCopyBuffer_reply(w, a)
{
    w.u32(112);
}
function e_vkCmdCopyImage_reply(w, a)
{
    w.u32(113);
}
function e_vkCmdBlitImage_reply(w, a)
{
    w.u32(114);
}
function e_vkCmdCopyBufferToImage_reply(w, a)
{
    w.u32(115);
}
function e_vkCmdCopyImageToBuffer_reply(w, a)
{
    w.u32(116);
}
function e_vkCmdUpdateBuffer_reply(w, a)
{
    w.u32(117);
}
function e_vkCmdFillBuffer_reply(w, a)
{
    w.u32(118);
}
function e_vkCmdClearColorImage_reply(w, a)
{
    w.u32(119);
}
function e_vkCmdClearDepthStencilImage_reply(w, a)
{
    w.u32(120);
}
function e_vkCmdClearAttachments_reply(w, a)
{
    w.u32(121);
}
function e_vkCmdResolveImage_reply(w, a)
{
    w.u32(122);
}
function e_vkCmdSetEvent_reply(w, a)
{
    w.u32(123);
}
function e_vkCmdResetEvent_reply(w, a)
{
    w.u32(124);
}
function e_vkCmdWaitEvents_reply(w, a)
{
    w.u32(125);
}
function e_vkCmdPipelineBarrier_reply(w, a)
{
    w.u32(126);
}
function e_vkCmdBeginQuery_reply(w, a)
{
    w.u32(127);
}
function e_vkCmdEndQuery_reply(w, a)
{
    w.u32(128);
}
function e_vkCmdResetQueryPool_reply(w, a)
{
    w.u32(129);
}
function e_vkCmdWriteTimestamp_reply(w, a)
{
    w.u32(130);
}
function e_vkCmdCopyQueryPoolResults_reply(w, a)
{
    w.u32(131);
}
function e_vkCmdPushConstants_reply(w, a)
{
    w.u32(132);
}
function e_vkCmdBeginRenderPass_reply(w, a)
{
    w.u32(133);
}
function e_vkCmdNextSubpass_reply(w, a)
{
    w.u32(134);
}
function e_vkCmdEndRenderPass_reply(w, a)
{
    w.u32(135);
}
function e_vkCmdExecuteCommands_reply(w, a)
{
    w.u32(136);
}
function e_vkEnumerateInstanceVersion_reply(w, a)
{
    w.u32(137);
    w.i32(a.ret);
    if(a.pApiVersion != null)
    {
        w.u64(1);
        w.u32(a.pApiVersion);
    }
    else w.u64(0);
}
function e_vkBindBufferMemory2_reply(w, a)
{
    w.u32(138);
    w.i32(a.ret);
}
function e_vkBindImageMemory2_reply(w, a)
{
    w.u32(139);
    w.i32(a.ret);
}
function e_vkGetDeviceGroupPeerMemoryFeatures_reply(w, a)
{
    w.u32(140);
    if(a.pPeerMemoryFeatures != null)
    {
        w.u64(1);
        w.u32(a.pPeerMemoryFeatures);
    }
    else w.u64(0);
}
function e_vkCmdSetDeviceMask_reply(w, a)
{
    w.u32(141);
}
function e_vkCmdDispatchBase_reply(w, a)
{
    w.u32(142);
}
function e_vkEnumeratePhysicalDeviceGroups_reply(w, a)
{
    w.u32(143);
    w.i32(a.ret);
    if(a.pPhysicalDeviceGroupCount != null)
    {
        w.u64(1);
        w.u32(a.pPhysicalDeviceGroupCount);
    }
    else w.u64(0);
    if(a.pPhysicalDeviceGroupProperties)
    {
        const n0 = (a.pPhysicalDeviceGroupCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pPhysicalDeviceGroupProperties ? a.pPhysicalDeviceGroupProperties[i] : undefined;
            e_VkPhysicalDeviceGroupProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetImageMemoryRequirements2_reply(w, a)
{
    w.u32(144);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements2(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetBufferMemoryRequirements2_reply(w, a)
{
    w.u32(145);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements2(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetImageSparseMemoryRequirements2_reply(w, a)
{
    w.u32(146);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        const n0 = (a.pSparseMemoryRequirementCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pSparseMemoryRequirements ? a.pSparseMemoryRequirements[i] : undefined;
            e_VkSparseImageMemoryRequirements2(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceFeatures2_reply(w, a)
{
    w.u32(147);
    if(a.pFeatures != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceFeatures2(w, a.pFeatures || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceProperties2_reply(w, a)
{
    w.u32(148);
    if(a.pProperties != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceProperties2(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceFormatProperties2_reply(w, a)
{
    w.u32(149);
    if(a.pFormatProperties != null)
    {
        w.u64(1);
        e_VkFormatProperties2(w, a.pFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceImageFormatProperties2_reply(w, a)
{
    w.u32(150);
    w.i32(a.ret);
    if(a.pImageFormatProperties != null)
    {
        w.u64(1);
        e_VkImageFormatProperties2(w, a.pImageFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceQueueFamilyProperties2_reply(w, a)
{
    w.u32(151);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pQueueFamilyPropertyCount);
    }
    else w.u64(0);
    if(a.pQueueFamilyProperties)
    {
        const n0 = (a.pQueueFamilyPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pQueueFamilyProperties ? a.pQueueFamilyProperties[i] : undefined;
            e_VkQueueFamilyProperties2(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceMemoryProperties2_reply(w, a)
{
    w.u32(152);
    if(a.pMemoryProperties != null)
    {
        w.u64(1);
        e_VkPhysicalDeviceMemoryProperties2(w, a.pMemoryProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceSparseImageFormatProperties2_reply(w, a)
{
    w.u32(153);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkSparseImageFormatProperties2(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkTrimCommandPool_reply(w, a)
{
    w.u32(154);
}
function e_vkGetDeviceQueue2_reply(w, a)
{
    w.u32(155);
    if(a.pQueue != null)
    {
        w.u64(1);
        w.h(a.pQueue);
    }
    else w.u64(0);
}
function e_vkCreateSamplerYcbcrConversion_reply(w, a)
{
    w.u32(156);
    w.i32(a.ret);
    if(a.pYcbcrConversion != null)
    {
        w.u64(1);
        w.h(a.pYcbcrConversion);
    }
    else w.u64(0);
}
function e_vkDestroySamplerYcbcrConversion_reply(w, a)
{
    w.u32(157);
}
function e_vkCreateDescriptorUpdateTemplate_reply(w, a)
{
    w.u32(158);
    w.i32(a.ret);
    if(a.pDescriptorUpdateTemplate != null)
    {
        w.u64(1);
        w.h(a.pDescriptorUpdateTemplate);
    }
    else w.u64(0);
}
function e_vkDestroyDescriptorUpdateTemplate_reply(w, a)
{
    w.u32(159);
}
function e_vkGetPhysicalDeviceExternalBufferProperties_reply(w, a)
{
    w.u32(161);
    if(a.pExternalBufferProperties != null)
    {
        w.u64(1);
        e_VkExternalBufferProperties(w, a.pExternalBufferProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceExternalFenceProperties_reply(w, a)
{
    w.u32(162);
    if(a.pExternalFenceProperties != null)
    {
        w.u64(1);
        e_VkExternalFenceProperties(w, a.pExternalFenceProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceExternalSemaphoreProperties_reply(w, a)
{
    w.u32(163);
    if(a.pExternalSemaphoreProperties != null)
    {
        w.u64(1);
        e_VkExternalSemaphoreProperties(w, a.pExternalSemaphoreProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetDescriptorSetLayoutSupport_reply(w, a)
{
    w.u32(164);
    if(a.pSupport != null)
    {
        w.u64(1);
        e_VkDescriptorSetLayoutSupport(w, a.pSupport || EMPTY);
    }
    else w.u64(0);
}
function e_vkCmdDrawIndirectCount_reply(w, a)
{
    w.u32(165);
}
function e_vkCmdDrawIndexedIndirectCount_reply(w, a)
{
    w.u32(166);
}
function e_vkCreateRenderPass2_reply(w, a)
{
    w.u32(167);
    w.i32(a.ret);
    if(a.pRenderPass != null)
    {
        w.u64(1);
        w.h(a.pRenderPass);
    }
    else w.u64(0);
}
function e_vkCmdBeginRenderPass2_reply(w, a)
{
    w.u32(168);
}
function e_vkCmdNextSubpass2_reply(w, a)
{
    w.u32(169);
}
function e_vkCmdEndRenderPass2_reply(w, a)
{
    w.u32(170);
}
function e_vkResetQueryPool_reply(w, a)
{
    w.u32(171);
}
function e_vkGetSemaphoreCounterValue_reply(w, a)
{
    w.u32(172);
    w.i32(a.ret);
    if(a.pValue != null)
    {
        w.u64(1);
        w.u64(a.pValue);
    }
    else w.u64(0);
}
function e_vkWaitSemaphores_reply(w, a)
{
    w.u32(173);
    w.i32(a.ret);
}
function e_vkSignalSemaphore_reply(w, a)
{
    w.u32(174);
    w.i32(a.ret);
}
function e_vkGetBufferDeviceAddress_reply(w, a)
{
    w.u32(175);
    w.u64(a.ret);
}
function e_vkGetBufferOpaqueCaptureAddress_reply(w, a)
{
    w.u32(176);
    w.u64(a.ret);
}
function e_vkGetDeviceMemoryOpaqueCaptureAddress_reply(w, a)
{
    w.u32(177);
    w.u64(a.ret);
}
function e_vkSetReplyCommandStreamMESA_reply(w, a)
{
    w.u32(178);
}
function e_vkSeekReplyCommandStreamMESA_reply(w, a)
{
    w.u32(179);
}
function e_vkExecuteCommandStreamsMESA_reply(w, a)
{
    w.u32(180);
}
function e_vkCmdBindTransformFeedbackBuffersEXT_reply(w, a)
{
    w.u32(181);
}
function e_vkCmdBeginTransformFeedbackEXT_reply(w, a)
{
    w.u32(182);
}
function e_vkCmdEndTransformFeedbackEXT_reply(w, a)
{
    w.u32(183);
}
function e_vkCmdBeginQueryIndexedEXT_reply(w, a)
{
    w.u32(184);
}
function e_vkCmdEndQueryIndexedEXT_reply(w, a)
{
    w.u32(185);
}
function e_vkCmdDrawIndirectByteCountEXT_reply(w, a)
{
    w.u32(186);
}
function e_vkGetImageDrmFormatModifierPropertiesEXT_reply(w, a)
{
    w.u32(187);
    w.i32(a.ret);
    if(a.pProperties != null)
    {
        w.u64(1);
        e_VkImageDrmFormatModifierPropertiesEXT(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkCreateRingMESA_reply(w, a)
{
    w.u32(188);
}
function e_vkDestroyRingMESA_reply(w, a)
{
    w.u32(189);
}
function e_vkNotifyRingMESA_reply(w, a)
{
    w.u32(190);
}
function e_vkWriteRingExtraMESA_reply(w, a)
{
    w.u32(191);
}
function e_vkGetMemoryResourcePropertiesMESA_reply(w, a)
{
    w.u32(192);
    w.i32(a.ret);
    if(a.pMemoryResourceProperties != null)
    {
        w.u64(1);
        e_VkMemoryResourcePropertiesMESA(w, a.pMemoryResourceProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetPhysicalDeviceToolProperties_reply(w, a)
{
    w.u32(196);
    w.i32(a.ret);
    if(a.pToolCount != null)
    {
        w.u64(1);
        w.u32(a.pToolCount);
    }
    else w.u64(0);
    if(a.pToolProperties)
    {
        const n0 = (a.pToolCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pToolProperties ? a.pToolProperties[i] : undefined;
            e_VkPhysicalDeviceToolProperties(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkCreatePrivateDataSlot_reply(w, a)
{
    w.u32(197);
    w.i32(a.ret);
    if(a.pPrivateDataSlot != null)
    {
        w.u64(1);
        w.h(a.pPrivateDataSlot);
    }
    else w.u64(0);
}
function e_vkDestroyPrivateDataSlot_reply(w, a)
{
    w.u32(198);
}
function e_vkSetPrivateData_reply(w, a)
{
    w.u32(199);
    w.i32(a.ret);
}
function e_vkGetPrivateData_reply(w, a)
{
    w.u32(200);
    if(a.pData != null)
    {
        w.u64(1);
        w.u64(a.pData);
    }
    else w.u64(0);
}
function e_vkCmdSetEvent2_reply(w, a)
{
    w.u32(201);
}
function e_vkCmdResetEvent2_reply(w, a)
{
    w.u32(202);
}
function e_vkCmdWaitEvents2_reply(w, a)
{
    w.u32(203);
}
function e_vkCmdPipelineBarrier2_reply(w, a)
{
    w.u32(204);
}
function e_vkCmdWriteTimestamp2_reply(w, a)
{
    w.u32(205);
}
function e_vkQueueSubmit2_reply(w, a)
{
    w.u32(206);
    w.i32(a.ret);
}
function e_vkCmdCopyBuffer2_reply(w, a)
{
    w.u32(207);
}
function e_vkCmdCopyImage2_reply(w, a)
{
    w.u32(208);
}
function e_vkCmdCopyBufferToImage2_reply(w, a)
{
    w.u32(209);
}
function e_vkCmdCopyImageToBuffer2_reply(w, a)
{
    w.u32(210);
}
function e_vkCmdBlitImage2_reply(w, a)
{
    w.u32(211);
}
function e_vkCmdResolveImage2_reply(w, a)
{
    w.u32(212);
}
function e_vkCmdBeginRendering_reply(w, a)
{
    w.u32(213);
}
function e_vkCmdEndRendering_reply(w, a)
{
    w.u32(214);
}
function e_vkCmdSetCullMode_reply(w, a)
{
    w.u32(215);
}
function e_vkCmdSetFrontFace_reply(w, a)
{
    w.u32(216);
}
function e_vkCmdSetPrimitiveTopology_reply(w, a)
{
    w.u32(217);
}
function e_vkCmdSetViewportWithCount_reply(w, a)
{
    w.u32(218);
}
function e_vkCmdSetScissorWithCount_reply(w, a)
{
    w.u32(219);
}
function e_vkCmdBindVertexBuffers2_reply(w, a)
{
    w.u32(220);
}
function e_vkCmdSetDepthTestEnable_reply(w, a)
{
    w.u32(221);
}
function e_vkCmdSetDepthWriteEnable_reply(w, a)
{
    w.u32(222);
}
function e_vkCmdSetDepthCompareOp_reply(w, a)
{
    w.u32(223);
}
function e_vkCmdSetDepthBoundsTestEnable_reply(w, a)
{
    w.u32(224);
}
function e_vkCmdSetStencilTestEnable_reply(w, a)
{
    w.u32(225);
}
function e_vkCmdSetStencilOp_reply(w, a)
{
    w.u32(226);
}
function e_vkCmdSetRasterizerDiscardEnable_reply(w, a)
{
    w.u32(227);
}
function e_vkCmdSetDepthBiasEnable_reply(w, a)
{
    w.u32(228);
}
function e_vkCmdSetPrimitiveRestartEnable_reply(w, a)
{
    w.u32(229);
}
function e_vkGetDeviceBufferMemoryRequirements_reply(w, a)
{
    w.u32(230);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements2(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetDeviceImageMemoryRequirements_reply(w, a)
{
    w.u32(231);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        e_VkMemoryRequirements2(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetDeviceImageSparseMemoryRequirements_reply(w, a)
{
    w.u32(232);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        const n0 = (a.pSparseMemoryRequirementCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pSparseMemoryRequirements ? a.pSparseMemoryRequirements[i] : undefined;
            e_VkSparseImageMemoryRequirements2(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkCmdSetPatchControlPointsEXT_reply(w, a)
{
    w.u32(233);
}
function e_vkCmdSetLogicOpEXT_reply(w, a)
{
    w.u32(234);
}
function e_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR_reply(w, a)
{
    w.u32(235);
    w.i32(a.ret);
    if(a.pTimeDomainCount != null)
    {
        w.u64(1);
        w.u32(a.pTimeDomainCount);
    }
    else w.u64(0);
    if(a.pTimeDomains)
    {
        const n0 = (a.pTimeDomainCount || 0);
        w.size(n0);
        w.i32s(a.pTimeDomains, n0);
    }
    else w.size(0);
}
function e_vkGetCalibratedTimestampsKHR_reply(w, a)
{
    w.u32(236);
    w.i32(a.ret);
    if(a.pTimestamps)
    {
        const n0 = a.timestampCount;
        w.size(n0);
        w.u64s(a.pTimestamps, n0);
    }
    else w.size(0);
    if(a.pMaxDeviation != null)
    {
        w.u64(1);
        w.u64(a.pMaxDeviation);
    }
    else w.u64(0);
}
function e_vkCmdSetLineStipple_reply(w, a)
{
    w.u32(237);
}
function e_vkCmdBeginConditionalRenderingEXT_reply(w, a)
{
    w.u32(240);
}
function e_vkCmdEndConditionalRenderingEXT_reply(w, a)
{
    w.u32(241);
}
function e_vkResetFenceResourceMESA_reply(w, a)
{
    w.u32(244);
}
function e_vkWaitSemaphoreResourceMESA_reply(w, a)
{
    w.u32(245);
}
function e_vkImportSemaphoreResourceMESA_reply(w, a)
{
    w.u32(246);
}
function e_vkCmdDrawMultiEXT_reply(w, a)
{
    w.u32(247);
}
function e_vkCmdDrawMultiIndexedEXT_reply(w, a)
{
    w.u32(248);
}
function e_vkCmdPushDescriptorSet_reply(w, a)
{
    w.u32(249);
}
function e_vkSubmitVirtqueueSeqnoMESA_reply(w, a)
{
    w.u32(251);
}
function e_vkWaitVirtqueueSeqnoMESA_reply(w, a)
{
    w.u32(252);
}
function e_vkWaitRingSeqnoMESA_reply(w, a)
{
    w.u32(253);
}
function e_vkCmdSetColorWriteEnableEXT_reply(w, a)
{
    w.u32(254);
}
function e_vkCmdSetVertexInputEXT_reply(w, a)
{
    w.u32(255);
}
function e_vkCmdSetTessellationDomainOriginEXT_reply(w, a)
{
    w.u32(256);
}
function e_vkCmdSetDepthClampEnableEXT_reply(w, a)
{
    w.u32(257);
}
function e_vkCmdSetPolygonModeEXT_reply(w, a)
{
    w.u32(258);
}
function e_vkCmdSetRasterizationSamplesEXT_reply(w, a)
{
    w.u32(259);
}
function e_vkCmdSetSampleMaskEXT_reply(w, a)
{
    w.u32(260);
}
function e_vkCmdSetAlphaToCoverageEnableEXT_reply(w, a)
{
    w.u32(261);
}
function e_vkCmdSetAlphaToOneEnableEXT_reply(w, a)
{
    w.u32(262);
}
function e_vkCmdSetLogicOpEnableEXT_reply(w, a)
{
    w.u32(263);
}
function e_vkCmdSetColorBlendEnableEXT_reply(w, a)
{
    w.u32(264);
}
function e_vkCmdSetColorBlendEquationEXT_reply(w, a)
{
    w.u32(265);
}
function e_vkCmdSetColorWriteMaskEXT_reply(w, a)
{
    w.u32(266);
}
function e_vkCmdSetRasterizationStreamEXT_reply(w, a)
{
    w.u32(267);
}
function e_vkCmdSetConservativeRasterizationModeEXT_reply(w, a)
{
    w.u32(268);
}
function e_vkCmdSetExtraPrimitiveOverestimationSizeEXT_reply(w, a)
{
    w.u32(269);
}
function e_vkCmdSetDepthClipEnableEXT_reply(w, a)
{
    w.u32(270);
}
function e_vkCmdSetSampleLocationsEnableEXT_reply(w, a)
{
    w.u32(271);
}
function e_vkCmdSetColorBlendAdvancedEXT_reply(w, a)
{
    w.u32(272);
}
function e_vkCmdSetProvokingVertexModeEXT_reply(w, a)
{
    w.u32(273);
}
function e_vkCmdSetLineRasterizationModeEXT_reply(w, a)
{
    w.u32(274);
}
function e_vkCmdSetLineStippleEnableEXT_reply(w, a)
{
    w.u32(275);
}
function e_vkCmdSetDepthClipNegativeOneToOneEXT_reply(w, a)
{
    w.u32(276);
}
function e_vkGetPhysicalDeviceFragmentShadingRatesKHR_reply(w, a)
{
    w.u32(277);
    w.i32(a.ret);
    if(a.pFragmentShadingRateCount != null)
    {
        w.u64(1);
        w.u32(a.pFragmentShadingRateCount);
    }
    else w.u64(0);
    if(a.pFragmentShadingRates)
    {
        const n0 = (a.pFragmentShadingRateCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pFragmentShadingRates ? a.pFragmentShadingRates[i] : undefined;
            e_VkPhysicalDeviceFragmentShadingRateKHR(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkCmdSetFragmentShadingRateKHR_reply(w, a)
{
    w.u32(278);
}
function e_vkCmdBindIndexBuffer2_reply(w, a)
{
    w.u32(279);
}
function e_vkGetRenderingAreaGranularity_reply(w, a)
{
    w.u32(280);
    if(a.pGranularity != null)
    {
        w.u64(1);
        e_VkExtent2D(w, a.pGranularity || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetDeviceImageSubresourceLayout_reply(w, a)
{
    w.u32(281);
    if(a.pLayout != null)
    {
        w.u64(1);
        e_VkSubresourceLayout2(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function e_vkGetImageSubresourceLayout2_reply(w, a)
{
    w.u32(282);
    if(a.pLayout != null)
    {
        w.u64(1);
        e_VkSubresourceLayout2(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function e_vkCmdSetSampleLocationsEXT_reply(w, a)
{
    w.u32(283);
}
function e_vkGetPhysicalDeviceMultisamplePropertiesEXT_reply(w, a)
{
    w.u32(284);
    if(a.pMultisampleProperties != null)
    {
        w.u64(1);
        e_VkMultisamplePropertiesEXT(w, a.pMultisampleProperties || EMPTY);
    }
    else w.u64(0);
}
function e_vkUnmapMemory2_reply(w, a)
{
    w.u32(286);
    w.i32(a.ret);
}
function e_vkCmdSetRenderingAttachmentLocations_reply(w, a)
{
    w.u32(287);
}
function e_vkCmdSetRenderingInputAttachmentIndices_reply(w, a)
{
    w.u32(288);
}
function e_vkCmdBindDescriptorSets2_reply(w, a)
{
    w.u32(289);
}
function e_vkCmdPushConstants2_reply(w, a)
{
    w.u32(290);
}
function e_vkCmdPushDescriptorSet2_reply(w, a)
{
    w.u32(291);
}
function e_vkCopyImageToImage_reply(w, a)
{
    w.u32(295);
    w.i32(a.ret);
}
function e_vkTransitionImageLayout_reply(w, a)
{
    w.u32(296);
    w.i32(a.ret);
}
function e_vkCopyImageToMemoryMESA_reply(w, a)
{
    w.u32(297);
    w.i32(a.ret);
    if(a.pData)
    {
        const n0 = a.dataSize;
        w.size(n0);
        w.blob(a.pData, n0);
    }
    else w.size(0);
}
function e_vkCopyMemoryToImageMESA_reply(w, a)
{
    w.u32(298);
    w.i32(a.ret);
}
function e_vkCreateDeferredOperationKHR_reply(w, a)
{
    w.u32(299);
    w.i32(a.ret);
    if(a.pDeferredOperation != null)
    {
        w.u64(1);
        w.h(a.pDeferredOperation);
    }
    else w.u64(0);
}
function e_vkDestroyDeferredOperationKHR_reply(w, a)
{
    w.u32(300);
}
function e_vkGetDeferredOperationMaxConcurrencyKHR_reply(w, a)
{
    w.u32(301);
    w.u32(a.ret);
}
function e_vkGetDeferredOperationResultKHR_reply(w, a)
{
    w.u32(302);
    w.i32(a.ret);
}
function e_vkDeferredOperationJoinKHR_reply(w, a)
{
    w.u32(303);
    w.i32(a.ret);
}
function e_vkCmdSetDepthBias2EXT_reply(w, a)
{
    w.u32(328);
}
function e_vkCmdSetAttachmentFeedbackLoopEnableEXT_reply(w, a)
{
    w.u32(329);
}
function e_vkCmdSetDepthClampRangeEXT_reply(w, a)
{
    w.u32(330);
}
function e_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR_reply(w, a)
{
    w.u32(331);
    w.i32(a.ret);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        const n0 = (a.pPropertyCount || 0);
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pProperties ? a.pProperties[i] : undefined;
            e_VkCooperativeMatrixPropertiesKHR(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkCmdDrawMeshTasksEXT_reply(w, a)
{
    w.u32(332);
}
function e_vkCmdDrawMeshTasksIndirectEXT_reply(w, a)
{
    w.u32(333);
}
function e_vkCmdDrawMeshTasksIndirectCountEXT_reply(w, a)
{
    w.u32(334);
}
function e_vkWriteSamplerDescriptorMESA_reply(w, a)
{
    w.u32(335);
    w.i32(a.ret);
    if(a.pData)
    {
        const n0 = a.dataSize;
        w.size(n0);
        w.blob(a.pData, n0);
    }
    else w.size(0);
}
function e_vkWriteResourceDescriptorMESA_reply(w, a)
{
    w.u32(336);
    w.i32(a.ret);
    if(a.pData)
    {
        const n0 = a.dataSize;
        w.size(n0);
        w.blob(a.pData, n0);
    }
    else w.size(0);
}
function e_vkCmdBindSamplerHeapEXT_reply(w, a)
{
    w.u32(339);
}
function e_vkCmdBindResourceHeapEXT_reply(w, a)
{
    w.u32(340);
}
function e_vkCmdPushDataEXT_reply(w, a)
{
    w.u32(341);
}
function e_vkGetImageOpaqueCaptureDataEXT_reply(w, a)
{
    w.u32(342);
    w.i32(a.ret);
    if(a.pDatas)
    {
        const n0 = a.imageCount;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = a.pDatas ? a.pDatas[i] : undefined;
            e_VkHostAddressRangeEXT(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_vkGetPhysicalDeviceDescriptorSizeEXT_reply(w, a)
{
    w.u32(343);
    w.u64(a.ret);
}
function e_vkRegisterCustomBorderColorEXT_reply(w, a)
{
    w.u32(344);
    w.i32(a.ret);
    if(a.pIndex != null)
    {
        w.u64(1);
        w.u32(a.pIndex);
    }
    else w.u64(0);
}
function e_vkUnregisterCustomBorderColorEXT_reply(w, a)
{
    w.u32(345);
}
function e_VkDescriptorSetVariableDescriptorCountLayoutSupport_self(w, o)
{
    w.u32(o.maxVariableDescriptorCount);
}
function e_VkPhysicalDevicePrivateDataFeatures_self(w, o)
{
    w.u32(o.privateData);
}
function e_VkPhysicalDeviceVariablePointersFeatures_self(w, o)
{
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
}
function e_VkPhysicalDeviceMultiviewFeatures_self(w, o)
{
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
}
function e_VkPhysicalDevice16BitStorageFeatures_self(w, o)
{
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
}
function e_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self(w, o)
{
    w.u32(o.shaderSubgroupExtendedTypes);
}
function e_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self(w, o)
{
    w.u32(o.samplerYcbcrConversion);
}
function e_VkPhysicalDeviceProtectedMemoryFeatures_self(w, o)
{
    w.u32(o.protectedMemory);
}
function e_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self(w, o)
{
    w.u32(o.advancedBlendCoherentOperations);
}
function e_VkPhysicalDeviceMultiDrawFeaturesEXT_self(w, o)
{
    w.u32(o.multiDraw);
}
function e_VkPhysicalDeviceInlineUniformBlockFeatures_self(w, o)
{
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
}
function e_VkPhysicalDeviceMaintenance4Features_self(w, o)
{
    w.u32(o.maintenance4);
}
function e_VkPhysicalDeviceMaintenance5Features_self(w, o)
{
    w.u32(o.maintenance5);
}
function e_VkPhysicalDeviceMaintenance6Features_self(w, o)
{
    w.u32(o.maintenance6);
}
function e_VkPhysicalDeviceMaintenance7FeaturesKHR_self(w, o)
{
    w.u32(o.maintenance7);
}
function e_VkPhysicalDeviceShaderDrawParametersFeatures_self(w, o)
{
    w.u32(o.shaderDrawParameters);
}
function e_VkPhysicalDeviceShaderFloat16Int8Features_self(w, o)
{
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
}
function e_VkPhysicalDeviceHostQueryResetFeatures_self(w, o)
{
    w.u32(o.hostQueryReset);
}
function e_VkPhysicalDeviceGlobalPriorityQueryFeatures_self(w, o)
{
    w.u32(o.globalPriorityQuery);
}
function e_VkPhysicalDeviceDescriptorIndexingFeatures_self(w, o)
{
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
}
function e_VkPhysicalDeviceTimelineSemaphoreFeatures_self(w, o)
{
    w.u32(o.timelineSemaphore);
}
function e_VkPhysicalDevice8BitStorageFeatures_self(w, o)
{
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
}
function e_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self(w, o)
{
    w.u32(o.conditionalRendering);
    w.u32(o.inheritedConditionalRendering);
}
function e_VkPhysicalDeviceVulkanMemoryModelFeatures_self(w, o)
{
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
}
function e_VkPhysicalDeviceShaderAtomicInt64Features_self(w, o)
{
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
}
function e_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self(w, o)
{
    w.u32(o.shaderBufferFloat32Atomics);
    w.u32(o.shaderBufferFloat32AtomicAdd);
    w.u32(o.shaderBufferFloat64Atomics);
    w.u32(o.shaderBufferFloat64AtomicAdd);
    w.u32(o.shaderSharedFloat32Atomics);
    w.u32(o.shaderSharedFloat32AtomicAdd);
    w.u32(o.shaderSharedFloat64Atomics);
    w.u32(o.shaderSharedFloat64AtomicAdd);
    w.u32(o.shaderImageFloat32Atomics);
    w.u32(o.shaderImageFloat32AtomicAdd);
    w.u32(o.sparseImageFloat32Atomics);
    w.u32(o.sparseImageFloat32AtomicAdd);
}
function e_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self(w, o)
{
    w.u32(o.shaderBufferFloat16Atomics);
    w.u32(o.shaderBufferFloat16AtomicAdd);
    w.u32(o.shaderBufferFloat16AtomicMinMax);
    w.u32(o.shaderBufferFloat32AtomicMinMax);
    w.u32(o.shaderBufferFloat64AtomicMinMax);
    w.u32(o.shaderSharedFloat16Atomics);
    w.u32(o.shaderSharedFloat16AtomicAdd);
    w.u32(o.shaderSharedFloat16AtomicMinMax);
    w.u32(o.shaderSharedFloat32AtomicMinMax);
    w.u32(o.shaderSharedFloat64AtomicMinMax);
    w.u32(o.shaderImageFloat32AtomicMinMax);
    w.u32(o.sparseImageFloat32AtomicMinMax);
}
function e_VkPhysicalDeviceVertexAttributeDivisorFeatures_self(w, o)
{
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
}
function e_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self(w, o)
{
    w.u32(o.transformFeedback);
    w.u32(o.geometryStreams);
}
function e_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self(w, o)
{
    w.u32(o.computeDerivativeGroupQuads);
    w.u32(o.computeDerivativeGroupLinear);
}
function e_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self(w, o)
{
    w.u32(o.fragmentShaderBarycentric);
}
function e_VkPhysicalDeviceMeshShaderFeaturesEXT_self(w, o)
{
    w.u32(o.taskShader);
    w.u32(o.meshShader);
    w.u32(o.multiviewMeshShader);
    w.u32(o.primitiveFragmentShadingRateMeshShader);
    w.u32(o.meshShaderQueries);
}
function e_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self(w, o)
{
    w.u32(o.accelerationStructure);
    w.u32(o.accelerationStructureCaptureReplay);
    w.u32(o.accelerationStructureIndirectBuild);
    w.u32(o.accelerationStructureHostCommands);
    w.u32(o.descriptorBindingAccelerationStructureUpdateAfterBind);
}
function e_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingPipeline);
    w.u32(o.rayTracingPipelineShaderGroupHandleCaptureReplay);
    w.u32(o.rayTracingPipelineShaderGroupHandleCaptureReplayMixed);
    w.u32(o.rayTracingPipelineTraceRaysIndirect);
    w.u32(o.rayTraversalPrimitiveCulling);
}
function e_VkPhysicalDeviceRayQueryFeaturesKHR_self(w, o)
{
    w.u32(o.rayQuery);
}
function e_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingMaintenance1);
    w.u32(o.rayTracingPipelineTraceRaysIndirect2);
}
function e_VkPhysicalDeviceScalarBlockLayoutFeatures_self(w, o)
{
    w.u32(o.scalarBlockLayout);
}
function e_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self(w, o)
{
    w.u32(o.uniformBufferStandardLayout);
}
function e_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self(w, o)
{
    w.u32(o.depthClipEnable);
}
function e_VkPhysicalDeviceBufferDeviceAddressFeatures_self(w, o)
{
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}
function e_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self(w, o)
{
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}
function e_VkPhysicalDeviceImagelessFramebufferFeatures_self(w, o)
{
    w.u32(o.imagelessFramebuffer);
}
function e_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self(w, o)
{
    w.u32(o.textureCompressionASTC_HDR);
}
function e_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self(w, o)
{
    w.u32(o.ycbcrImageArrays);
}
function e_VkPhysicalDeviceShaderClockFeaturesKHR_self(w, o)
{
    w.u32(o.shaderSubgroupClock);
    w.u32(o.shaderDeviceClock);
}
function e_VkPhysicalDeviceIndexTypeUint8Features_self(w, o)
{
    w.u32(o.indexTypeUint8);
}
function e_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self(w, o)
{
    w.u32(o.fragmentShaderSampleInterlock);
    w.u32(o.fragmentShaderPixelInterlock);
    w.u32(o.fragmentShaderShadingRateInterlock);
}
function e_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self(w, o)
{
    w.u32(o.separateDepthStencilLayouts);
}
function e_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self(w, o)
{
    w.u32(o.primitiveTopologyListRestart);
    w.u32(o.primitiveTopologyPatchListRestart);
}
function e_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self(w, o)
{
    w.u32(o.shaderDemoteToHelperInvocation);
}
function e_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self(w, o)
{
    w.u32(o.texelBufferAlignment);
}
function e_VkPhysicalDeviceSubgroupSizeControlFeatures_self(w, o)
{
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
}
function e_VkPhysicalDeviceLineRasterizationFeatures_self(w, o)
{
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
}
function e_VkPhysicalDevicePipelineCreationCacheControlFeatures_self(w, o)
{
    w.u32(o.pipelineCreationCacheControl);
}
function e_VkPhysicalDeviceVulkan11Features_self(w, o)
{
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
    w.u32(o.protectedMemory);
    w.u32(o.samplerYcbcrConversion);
    w.u32(o.shaderDrawParameters);
}
function e_VkPhysicalDeviceVulkan12Features_self(w, o)
{
    w.u32(o.samplerMirrorClampToEdge);
    w.u32(o.drawIndirectCount);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
    w.u32(o.descriptorIndexing);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
    w.u32(o.samplerFilterMinmax);
    w.u32(o.scalarBlockLayout);
    w.u32(o.imagelessFramebuffer);
    w.u32(o.uniformBufferStandardLayout);
    w.u32(o.shaderSubgroupExtendedTypes);
    w.u32(o.separateDepthStencilLayouts);
    w.u32(o.hostQueryReset);
    w.u32(o.timelineSemaphore);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
    w.u32(o.shaderOutputViewportIndex);
    w.u32(o.shaderOutputLayer);
    w.u32(o.subgroupBroadcastDynamicId);
}
function e_VkPhysicalDeviceVulkan13Features_self(w, o)
{
    w.u32(o.robustImageAccess);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
    w.u32(o.pipelineCreationCacheControl);
    w.u32(o.privateData);
    w.u32(o.shaderDemoteToHelperInvocation);
    w.u32(o.shaderTerminateInvocation);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
    w.u32(o.synchronization2);
    w.u32(o.textureCompressionASTC_HDR);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
    w.u32(o.dynamicRendering);
    w.u32(o.shaderIntegerDotProduct);
    w.u32(o.maintenance4);
}
function e_VkPhysicalDeviceVulkan14Features_self(w, o)
{
    w.u32(o.globalPriorityQuery);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
    w.u32(o.shaderFloatControls2);
    w.u32(o.shaderExpectAssume);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
    w.u32(o.indexTypeUint8);
    w.u32(o.dynamicRenderingLocalRead);
    w.u32(o.maintenance5);
    w.u32(o.maintenance6);
    w.u32(o.pipelineProtectedAccess);
    w.u32(o.pipelineRobustness);
    w.u32(o.hostImageCopy);
    w.u32(o.pushDescriptor);
}
function e_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self(w, o)
{
    w.u32(o.customBorderColors);
    w.u32(o.customBorderColorWithoutFormat);
}
function e_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self(w, o)
{
    w.u32(o.borderColorSwizzle);
    w.u32(o.borderColorSwizzleFromImage);
}
function e_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState);
}
function e_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState2);
    w.u32(o.extendedDynamicState2LogicOp);
    w.u32(o.extendedDynamicState2PatchControlPoints);
}
function e_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState3TessellationDomainOrigin);
    w.u32(o.extendedDynamicState3DepthClampEnable);
    w.u32(o.extendedDynamicState3PolygonMode);
    w.u32(o.extendedDynamicState3RasterizationSamples);
    w.u32(o.extendedDynamicState3SampleMask);
    w.u32(o.extendedDynamicState3AlphaToCoverageEnable);
    w.u32(o.extendedDynamicState3AlphaToOneEnable);
    w.u32(o.extendedDynamicState3LogicOpEnable);
    w.u32(o.extendedDynamicState3ColorBlendEnable);
    w.u32(o.extendedDynamicState3ColorBlendEquation);
    w.u32(o.extendedDynamicState3ColorWriteMask);
    w.u32(o.extendedDynamicState3RasterizationStream);
    w.u32(o.extendedDynamicState3ConservativeRasterizationMode);
    w.u32(o.extendedDynamicState3ExtraPrimitiveOverestimationSize);
    w.u32(o.extendedDynamicState3DepthClipEnable);
    w.u32(o.extendedDynamicState3SampleLocationsEnable);
    w.u32(o.extendedDynamicState3ColorBlendAdvanced);
    w.u32(o.extendedDynamicState3ProvokingVertexMode);
    w.u32(o.extendedDynamicState3LineRasterizationMode);
    w.u32(o.extendedDynamicState3LineStippleEnable);
    w.u32(o.extendedDynamicState3DepthClipNegativeOneToOne);
    w.u32(o.extendedDynamicState3ViewportWScalingEnable);
    w.u32(o.extendedDynamicState3ViewportSwizzle);
    w.u32(o.extendedDynamicState3CoverageToColorEnable);
    w.u32(o.extendedDynamicState3CoverageToColorLocation);
    w.u32(o.extendedDynamicState3CoverageModulationMode);
    w.u32(o.extendedDynamicState3CoverageModulationTableEnable);
    w.u32(o.extendedDynamicState3CoverageModulationTable);
    w.u32(o.extendedDynamicState3CoverageReductionMode);
    w.u32(o.extendedDynamicState3RepresentativeFragmentTestEnable);
    w.u32(o.extendedDynamicState3ShadingRateImageEnable);
}
function e_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self(w, o)
{
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
}
function e_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self(w, o)
{
    w.u32(o.shaderSubgroupUniformControlFlow);
}
function e_VkPhysicalDeviceRobustness2FeaturesKHR_self(w, o)
{
    w.u32(o.robustBufferAccess2);
    w.u32(o.robustImageAccess2);
    w.u32(o.nullDescriptor);
}
function e_VkPhysicalDeviceImageRobustnessFeatures_self(w, o)
{
    w.u32(o.robustImageAccess);
}
function e_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self(w, o)
{
    w.u32(o.workgroupMemoryExplicitLayout);
    w.u32(o.workgroupMemoryExplicitLayoutScalarBlockLayout);
    w.u32(o.workgroupMemoryExplicitLayout8BitAccess);
    w.u32(o.workgroupMemoryExplicitLayout16BitAccess);
}
function e_VkPhysicalDevice4444FormatsFeaturesEXT_self(w, o)
{
    w.u32(o.formatA4R4G4B4);
    w.u32(o.formatA4B4G4R4);
}
function e_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self(w, o)
{
    w.u32(o.shaderImageInt64Atomics);
    w.u32(o.sparseImageInt64Atomics);
}
function e_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self(w, o)
{
    w.u32(o.pipelineFragmentShadingRate);
    w.u32(o.primitiveFragmentShadingRate);
    w.u32(o.attachmentFragmentShadingRate);
}
function e_VkPhysicalDeviceShaderTerminateInvocationFeatures_self(w, o)
{
    w.u32(o.shaderTerminateInvocation);
}
function e_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self(w, o)
{
    w.u32(o.image2DViewOf3D);
    w.u32(o.sampler2DViewOf3D);
}
function e_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self(w, o)
{
    w.u32(o.imageSlicedViewOf3D);
}
function e_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.attachmentFeedbackLoopDynamicState);
}
function e_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self(w, o)
{
    w.u32(o.legacyVertexAttributes);
}
function e_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self(w, o)
{
    w.u32(o.mutableDescriptorType);
}
function e_VkPhysicalDeviceDepthClipControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthClipControl);
}
function e_VkPhysicalDeviceDepthClampControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthClampControl);
}
function e_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.vertexInputDynamicState);
}
function e_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self(w, o)
{
    w.u32(o.shaderRelaxedExtendedInstruction);
}
function e_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self(w, o)
{
    w.u32(o.colorWriteEnable);
}
function e_VkPhysicalDeviceSynchronization2Features_self(w, o)
{
    w.u32(o.synchronization2);
}
function e_VkPhysicalDeviceHostImageCopyFeatures_self(w, o)
{
    w.u32(o.hostImageCopy);
}
function e_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self(w, o)
{
    w.u32(o.primitivesGeneratedQuery);
    w.u32(o.primitivesGeneratedQueryWithRasterizerDiscard);
    w.u32(o.primitivesGeneratedQueryWithNonZeroStreams);
}
function e_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self(w, o)
{
    w.u32(o.legacyDithering);
}
function e_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self(w, o)
{
    w.u32(o.multisampledRenderToSingleSampled);
}
function e_VkPhysicalDevicePipelineProtectedAccessFeatures_self(w, o)
{
    w.u32(o.pipelineProtectedAccess);
}
function e_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self(w, o)
{
    w.u32(o.ycbcr2plane444Formats);
}
function e_VkPhysicalDeviceProvokingVertexFeaturesEXT_self(w, o)
{
    w.u32(o.provokingVertexLast);
    w.u32(o.transformFeedbackPreservesProvokingVertex);
}
function e_VkPhysicalDeviceShaderIntegerDotProductFeatures_self(w, o)
{
    w.u32(o.shaderIntegerDotProduct);
}
function e_VkPhysicalDeviceShaderFmaFeaturesKHR_self(w, o)
{
    w.u32(o.shaderFmaFloat16);
    w.u32(o.shaderFmaFloat32);
    w.u32(o.shaderFmaFloat64);
}
function e_VkPhysicalDeviceDynamicRenderingFeatures_self(w, o)
{
    w.u32(o.dynamicRendering);
}
function e_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self(w, o)
{
    w.u32(o.minLod);
}
function e_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self(w, o)
{
    w.u32(o.rasterizationOrderColorAttachmentAccess);
    w.u32(o.rasterizationOrderDepthAttachmentAccess);
    w.u32(o.rasterizationOrderStencilAttachmentAccess);
}
function e_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self(w, o)
{
    w.u32(o.graphicsPipelineLibrary);
}
function e_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self(w, o)
{
    w.u32(o.nestedCommandBuffer);
    w.u32(o.nestedCommandBufferRendering);
    w.u32(o.nestedCommandBufferSimultaneousUse);
}
function e_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self(w, o)
{
    w.u32(o.nonSeamlessCubeMap);
}
function e_VkPhysicalDevicePipelineRobustnessFeatures_self(w, o)
{
    w.u32(o.pipelineRobustness);
}
function e_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self(w, o)
{
    w.u32(o.attachmentFeedbackLoopLayout);
}
function e_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self(w, o)
{
    w.u32(o.depthClampZeroOne);
}
function e_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self(w, o)
{
    w.u32(o.pipelineLibraryGroupHandles);
}
function e_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self(w, o)
{
    w.u32(o.dynamicRenderingUnusedAttachments);
}
function e_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthBiasControl);
    w.u32(o.leastRepresentableValueForceUnormRepresentation);
    w.u32(o.floatRepresentation);
    w.u32(o.depthBiasExact);
}
function e_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingPositionFetch);
}
function e_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self(w, o)
{
    w.u32(o.cooperativeMatrix);
    w.u32(o.cooperativeMatrixRobustBufferAccess);
}
function e_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self(w, o)
{
    w.u32(o.shaderMaximalReconvergence);
}
function e_VkPhysicalDeviceShaderSubgroupRotateFeatures_self(w, o)
{
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
}
function e_VkPhysicalDeviceShaderExpectAssumeFeatures_self(w, o)
{
    w.u32(o.shaderExpectAssume);
}
function e_VkPhysicalDeviceShaderFloatControls2Features_self(w, o)
{
    w.u32(o.shaderFloatControls2);
}
function e_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self(w, o)
{
    w.u32(o.dynamicRenderingLocalRead);
}
function e_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self(w, o)
{
    w.u32(o.shaderQuadControl);
}
function e_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self(w, o)
{
    w.u32(o.shaderBFloat16Type);
    w.u32(o.shaderBFloat16DotProduct);
    w.u32(o.shaderBFloat16CooperativeMatrix);
}
function e_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self(w, o)
{
    w.u32(o.shaderReplicatedComposites);
}
function e_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self(w, o)
{
    w.u32(o.shaderUniformBufferUnsizedArray);
}
function e_VkPhysicalDeviceShaderFloat8FeaturesEXT_self(w, o)
{
    w.u32(o.shaderFloat8);
    w.u32(o.shaderFloat8CooperativeMatrix);
}
function e_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self(w, o)
{
    w.u32(o.shaderUntypedPointers);
}
function e_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self(w, o)
{
    w.u32(o.descriptorHeap);
    w.u32(o.descriptorHeapCaptureReplay);
}
function e_VkPhysicalDeviceMultiDrawPropertiesEXT_self(w, o)
{
    w.u32(o.maxMultiDrawCount);
}
function e_VkPhysicalDevicePushDescriptorProperties_self(w, o)
{
    w.u32(o.maxPushDescriptors);
}
function e_VkPhysicalDeviceDriverProperties_self(w, o)
{
    w.i32(o.driverID);
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.driverName, n0);
    }
    {
        const n1 = 256;
        w.size(n1);
        w.str(o.driverInfo, n1);
    }
    e_VkConformanceVersion(w, o.conformanceVersion || EMPTY);
}
function e_VkPhysicalDeviceIDProperties_self(w, o)
{
    {
        const n0 = 16;
        w.size(n0);
        w.u8s(o.deviceUUID, n0);
    }
    {
        const n1 = 16;
        w.size(n1);
        w.u8s(o.driverUUID, n1);
    }
    {
        const n2 = 8;
        w.size(n2);
        w.u8s(o.deviceLUID, n2);
    }
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
}
function e_VkPhysicalDeviceMultiviewProperties_self(w, o)
{
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
}
function e_VkPhysicalDeviceSubgroupProperties_self(w, o)
{
    w.u32(o.subgroupSize);
    w.u32(o.supportedStages);
    w.u32(o.supportedOperations);
    w.u32(o.quadOperationsInAllStages);
}
function e_VkPhysicalDevicePointClippingProperties_self(w, o)
{
    w.i32(o.pointClippingBehavior);
}
function e_VkPhysicalDeviceProtectedMemoryProperties_self(w, o)
{
    w.u32(o.protectedNoFault);
}
function e_VkPhysicalDeviceSamplerFilterMinmaxProperties_self(w, o)
{
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
}
function e_VkPhysicalDeviceSampleLocationsPropertiesEXT_self(w, o)
{
    w.u32(o.sampleLocationSampleCounts);
    e_VkExtent2D(w, o.maxSampleLocationGridSize || EMPTY);
    {
        const n0 = 2;
        w.size(n0);
        w.f32s(o.sampleLocationCoordinateRange, n0);
    }
    w.u32(o.sampleLocationSubPixelBits);
    w.u32(o.variableSampleLocations);
}
function e_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self(w, o)
{
    w.u32(o.advancedBlendMaxColorAttachments);
    w.u32(o.advancedBlendIndependentBlend);
    w.u32(o.advancedBlendNonPremultipliedSrcColor);
    w.u32(o.advancedBlendNonPremultipliedDstColor);
    w.u32(o.advancedBlendCorrelatedOverlap);
    w.u32(o.advancedBlendAllOperations);
}
function e_VkPhysicalDeviceInlineUniformBlockProperties_self(w, o)
{
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
}
function e_VkPhysicalDeviceMaintenance3Properties_self(w, o)
{
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}
function e_VkPhysicalDeviceMaintenance4Properties_self(w, o)
{
    w.u64(o.maxBufferSize);
}
function e_VkPhysicalDeviceMaintenance5Properties_self(w, o)
{
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
}
function e_VkPhysicalDeviceMaintenance6Properties_self(w, o)
{
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
}
function e_VkPhysicalDeviceMaintenance7PropertiesKHR_self(w, o)
{
    w.u32(o.robustFragmentShadingRateAttachmentAccess);
    w.u32(o.separateDepthStencilAttachmentAccess);
    w.u32(o.maxDescriptorSetTotalUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetTotalStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetTotalBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindTotalUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindTotalStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindTotalBuffersDynamic);
}
function e_VkPhysicalDeviceFloatControlsProperties_self(w, o)
{
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
}
function e_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self(w, o)
{
    w.f32(o.primitiveOverestimationSize);
    w.f32(o.maxExtraPrimitiveOverestimationSize);
    w.f32(o.extraPrimitiveOverestimationSizeGranularity);
    w.u32(o.primitiveUnderestimation);
    w.u32(o.conservativePointAndLineRasterization);
    w.u32(o.degenerateTrianglesRasterized);
    w.u32(o.degenerateLinesRasterized);
    w.u32(o.fullyCoveredFragmentShaderInputVariable);
    w.u32(o.conservativeRasterizationPostDepthCoverage);
}
function e_VkPhysicalDeviceDescriptorIndexingProperties_self(w, o)
{
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
}
function e_VkPhysicalDeviceTimelineSemaphoreProperties_self(w, o)
{
    w.u64(o.maxTimelineSemaphoreValueDifference);
}
function e_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self(w, o)
{
    w.u32(o.maxVertexAttribDivisor);
}
function e_VkPhysicalDeviceVertexAttributeDivisorProperties_self(w, o)
{
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
}
function e_VkPhysicalDevicePCIBusInfoPropertiesEXT_self(w, o)
{
    w.u32(o.pciDomain);
    w.u32(o.pciBus);
    w.u32(o.pciDevice);
    w.u32(o.pciFunction);
}
function e_VkPhysicalDeviceDepthStencilResolveProperties_self(w, o)
{
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
}
function e_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self(w, o)
{
    w.u32(o.maxTransformFeedbackStreams);
    w.u32(o.maxTransformFeedbackBuffers);
    w.u64(o.maxTransformFeedbackBufferSize);
    w.u32(o.maxTransformFeedbackStreamDataSize);
    w.u32(o.maxTransformFeedbackBufferDataSize);
    w.u32(o.maxTransformFeedbackBufferDataStride);
    w.u32(o.transformFeedbackQueries);
    w.u32(o.transformFeedbackStreamsLinesTriangles);
    w.u32(o.transformFeedbackRasterizationStreamSelect);
    w.u32(o.transformFeedbackDraw);
}
function e_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self(w, o)
{
    w.u32(o.meshAndTaskShaderDerivatives);
}
function e_VkPhysicalDeviceMeshShaderPropertiesEXT_self(w, o)
{
    w.u32(o.maxTaskWorkGroupTotalCount);
    {
        const n0 = 3;
        w.size(n0);
        w.u32s(o.maxTaskWorkGroupCount, n0);
    }
    w.u32(o.maxTaskWorkGroupInvocations);
    {
        const n1 = 3;
        w.size(n1);
        w.u32s(o.maxTaskWorkGroupSize, n1);
    }
    w.u32(o.maxTaskPayloadSize);
    w.u32(o.maxTaskSharedMemorySize);
    w.u32(o.maxTaskPayloadAndSharedMemorySize);
    w.u32(o.maxMeshWorkGroupTotalCount);
    {
        const n2 = 3;
        w.size(n2);
        w.u32s(o.maxMeshWorkGroupCount, n2);
    }
    w.u32(o.maxMeshWorkGroupInvocations);
    {
        const n3 = 3;
        w.size(n3);
        w.u32s(o.maxMeshWorkGroupSize, n3);
    }
    w.u32(o.maxMeshSharedMemorySize);
    w.u32(o.maxMeshPayloadAndSharedMemorySize);
    w.u32(o.maxMeshOutputMemorySize);
    w.u32(o.maxMeshPayloadAndOutputMemorySize);
    w.u32(o.maxMeshOutputComponents);
    w.u32(o.maxMeshOutputVertices);
    w.u32(o.maxMeshOutputPrimitives);
    w.u32(o.maxMeshOutputLayers);
    w.u32(o.maxMeshMultiviewViewCount);
    w.u32(o.meshOutputPerVertexGranularity);
    w.u32(o.meshOutputPerPrimitiveGranularity);
    w.u32(o.maxPreferredTaskWorkGroupInvocations);
    w.u32(o.maxPreferredMeshWorkGroupInvocations);
    w.u32(o.prefersLocalInvocationVertexOutput);
    w.u32(o.prefersLocalInvocationPrimitiveOutput);
    w.u32(o.prefersCompactVertexOutput);
    w.u32(o.prefersCompactPrimitiveOutput);
}
function e_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self(w, o)
{
    w.u64(o.maxGeometryCount);
    w.u64(o.maxInstanceCount);
    w.u64(o.maxPrimitiveCount);
    w.u32(o.maxPerStageDescriptorAccelerationStructures);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindAccelerationStructures);
    w.u32(o.maxDescriptorSetAccelerationStructures);
    w.u32(o.maxDescriptorSetUpdateAfterBindAccelerationStructures);
    w.u32(o.minAccelerationStructureScratchOffsetAlignment);
}
function e_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self(w, o)
{
    w.u32(o.shaderGroupHandleSize);
    w.u32(o.maxRayRecursionDepth);
    w.u32(o.maxShaderGroupStride);
    w.u32(o.shaderGroupBaseAlignment);
    w.u32(o.shaderGroupHandleCaptureReplaySize);
    w.u32(o.maxRayDispatchInvocationCount);
    w.u32(o.shaderGroupHandleAlignment);
    w.u32(o.maxRayHitAttributeSize);
}
function e_VkPhysicalDeviceTexelBufferAlignmentProperties_self(w, o)
{
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
}
function e_VkPhysicalDeviceSubgroupSizeControlProperties_self(w, o)
{
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
}
function e_VkPhysicalDeviceLineRasterizationProperties_self(w, o)
{
    w.u32(o.lineSubPixelPrecisionBits);
}
function e_VkPhysicalDeviceVulkan11Properties_self(w, o)
{
    {
        const n0 = 16;
        w.size(n0);
        w.u8s(o.deviceUUID, n0);
    }
    {
        const n1 = 16;
        w.size(n1);
        w.u8s(o.driverUUID, n1);
    }
    {
        const n2 = 8;
        w.size(n2);
        w.u8s(o.deviceLUID, n2);
    }
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
    w.u32(o.subgroupSize);
    w.u32(o.subgroupSupportedStages);
    w.u32(o.subgroupSupportedOperations);
    w.u32(o.subgroupQuadOperationsInAllStages);
    w.i32(o.pointClippingBehavior);
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
    w.u32(o.protectedNoFault);
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}
function e_VkPhysicalDeviceVulkan12Properties_self(w, o)
{
    w.i32(o.driverID);
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.driverName, n0);
    }
    {
        const n1 = 256;
        w.size(n1);
        w.str(o.driverInfo, n1);
    }
    e_VkConformanceVersion(w, o.conformanceVersion || EMPTY);
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
    w.u64(o.maxTimelineSemaphoreValueDifference);
    w.u32(o.framebufferIntegerColorSampleCounts);
}
function e_VkPhysicalDeviceVulkan13Properties_self(w, o)
{
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxInlineUniformTotalSize);
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.maxBufferSize);
}
function e_VkPhysicalDeviceVulkan14Properties_self(w, o)
{
    w.u32(o.lineSubPixelPrecisionBits);
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
    w.u32(o.maxPushDescriptors);
    w.u32(o.dynamicRenderingLocalReadDepthStencilAttachments);
    w.u32(o.dynamicRenderingLocalReadMultisampledAttachments);
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
    w.u32(o.copySrcLayoutCount);
    if(o.pCopySrcLayouts)
    {
        const n0 = o.copySrcLayoutCount;
        w.size(n0);
        w.i32s(o.pCopySrcLayouts, n0);
    }
    else w.size(0);
    w.u32(o.copyDstLayoutCount);
    if(o.pCopyDstLayouts)
    {
        const n1 = o.copyDstLayoutCount;
        w.size(n1);
        w.i32s(o.pCopyDstLayouts, n1);
    }
    else w.size(0);
    {
        const n2 = 16;
        w.size(n2);
        w.u8s(o.optimalTilingLayoutUUID, n2);
    }
    w.u32(o.identicalMemoryTypeRequirements);
}
function e_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self(w, o)
{
    w.u32(o.maxCustomBorderColorSamplers);
}
function e_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self(w, o)
{
    w.u32(o.dynamicPrimitiveTopologyUnrestricted);
}
function e_VkPhysicalDeviceRobustness2PropertiesKHR_self(w, o)
{
    w.u64(o.robustStorageBufferAccessSizeAlignment);
    w.u64(o.robustUniformBufferAccessSizeAlignment);
}
function e_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self(w, o)
{
    e_VkExtent2D(w, o.minFragmentShadingRateAttachmentTexelSize || EMPTY);
    e_VkExtent2D(w, o.maxFragmentShadingRateAttachmentTexelSize || EMPTY);
    w.u32(o.maxFragmentShadingRateAttachmentTexelSizeAspectRatio);
    w.u32(o.primitiveFragmentShadingRateWithMultipleViewports);
    w.u32(o.layeredShadingRateAttachments);
    w.u32(o.fragmentShadingRateNonTrivialCombinerOps);
    e_VkExtent2D(w, o.maxFragmentSize || EMPTY);
    w.u32(o.maxFragmentSizeAspectRatio);
    w.u32(o.maxFragmentShadingRateCoverageSamples);
    w.i32(o.maxFragmentShadingRateRasterizationSamples);
    w.u32(o.fragmentShadingRateWithShaderDepthStencilWrites);
    w.u32(o.fragmentShadingRateWithSampleMask);
    w.u32(o.fragmentShadingRateWithShaderSampleMask);
    w.u32(o.fragmentShadingRateWithConservativeRasterization);
    w.u32(o.fragmentShadingRateWithFragmentShaderInterlock);
    w.u32(o.fragmentShadingRateWithCustomSampleLocations);
    w.u32(o.fragmentShadingRateStrictMultiplyCombiner);
}
function e_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self(w, o)
{
    w.u32(o.nativeUnalignedPerformance);
}
function e_VkPhysicalDeviceHostImageCopyProperties_self(w, o)
{
    w.u32(o.copySrcLayoutCount);
    if(o.pCopySrcLayouts)
    {
        const n0 = o.copySrcLayoutCount;
        w.size(n0);
        w.i32s(o.pCopySrcLayouts, n0);
    }
    else w.size(0);
    w.u32(o.copyDstLayoutCount);
    if(o.pCopyDstLayouts)
    {
        const n1 = o.copyDstLayoutCount;
        w.size(n1);
        w.i32s(o.pCopyDstLayouts, n1);
    }
    else w.size(0);
    {
        const n2 = 16;
        w.size(n2);
        w.u8s(o.optimalTilingLayoutUUID, n2);
    }
    w.u32(o.identicalMemoryTypeRequirements);
}
function e_VkPhysicalDeviceProvokingVertexPropertiesEXT_self(w, o)
{
    w.u32(o.provokingVertexModePerPipeline);
    w.u32(o.transformFeedbackPreservesTriangleFanProvokingVertex);
}
function e_VkPhysicalDeviceShaderIntegerDotProductProperties_self(w, o)
{
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
}
function e_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self(w, o)
{
    w.u32(o.triStripVertexOrderIndependentOfProvokingVertex);
}
function e_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self(w, o)
{
    w.u32(o.graphicsPipelineLibraryFastLinking);
    w.u32(o.graphicsPipelineLibraryIndependentInterpolationDecoration);
}
function e_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self(w, o)
{
    w.u32(o.maxCommandBufferNestingLevel);
}
function e_VkPhysicalDevicePipelineRobustnessProperties_self(w, o)
{
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
}
function e_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self(w, o)
{
    w.u32(o.cooperativeMatrixSupportedStages);
}
function e_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self(w, o)
{
    w.u64(o.samplerHeapAlignment);
    w.u64(o.resourceHeapAlignment);
    w.u64(o.maxSamplerHeapSize);
    w.u64(o.maxResourceHeapSize);
    w.u64(o.minSamplerHeapReservedRange);
    w.u64(o.minSamplerHeapReservedRangeWithEmbedded);
    w.u64(o.minResourceHeapReservedRange);
    w.u64(o.samplerDescriptorSize);
    w.u64(o.imageDescriptorSize);
    w.u64(o.bufferDescriptorSize);
    w.u64(o.samplerDescriptorAlignment);
    w.u64(o.imageDescriptorAlignment);
    w.u64(o.bufferDescriptorAlignment);
    w.u64(o.maxPushDataSize);
    w.u64(o.imageCaptureReplayOpaqueDataSize);
    w.u32(o.maxDescriptorHeapEmbeddedSamplers);
    w.u32(o.samplerYcbcrConversionCount);
    w.u32(o.sparseDescriptorHeaps);
    w.u32(o.protectedDescriptorHeaps);
}
function e_VkDrmFormatModifierPropertiesListEXT_self(w, o)
{
    w.u32(o.drmFormatModifierCount);
    if(o.pDrmFormatModifierProperties)
    {
        const n0 = o.drmFormatModifierCount;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = o.pDrmFormatModifierProperties ? o.pDrmFormatModifierProperties[i] : undefined;
            e_VkDrmFormatModifierPropertiesEXT(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_VkSubpassResolvePerformanceQueryEXT_self(w, o)
{
    w.u32(o.optimal);
}
function e_VkFormatProperties3_self(w, o)
{
    w.u64(o.linearTilingFeatures);
    w.u64(o.optimalTilingFeatures);
    w.u64(o.bufferFeatures);
}
function e_VkDrmFormatModifierPropertiesList2EXT_self(w, o)
{
    w.u32(o.drmFormatModifierCount);
    if(o.pDrmFormatModifierProperties)
    {
        const n0 = o.drmFormatModifierCount;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = o.pDrmFormatModifierProperties ? o.pDrmFormatModifierProperties[i] : undefined;
            e_VkDrmFormatModifierProperties2EXT(w, item || EMPTY);
        }
    }
    else w.size(0);
}
function e_VkExternalImageFormatProperties_self(w, o)
{
    e_VkExternalMemoryProperties(w, o.externalMemoryProperties || EMPTY);
}
function e_VkSamplerYcbcrConversionImageFormatProperties_self(w, o)
{
    w.u32(o.combinedImageSamplerDescriptorCount);
}
function e_VkFilterCubicImageViewImageFormatPropertiesEXT_self(w, o)
{
    w.u32(o.filterCubic);
    w.u32(o.filterCubicMinmax);
}
function e_VkHostImageCopyDevicePerformanceQuery_self(w, o)
{
    w.u32(o.optimalDeviceAccess);
    w.u32(o.identicalMemoryLayout);
}
function e_VkQueueFamilyGlobalPriorityProperties_self(w, o)
{
    w.u32(o.priorityCount);
    {
        const n0 = 16;
        w.size(n0);
        w.i32s(o.priorities, n0);
    }
}
function e_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self(w, o)
{
    {
        const n0 = 16;
        w.size(n0);
        w.u64s(o.heapBudget, n0);
    }
    {
        const n1 = 16;
        w.size(n1);
        w.u64s(o.heapUsage, n1);
    }
}
function e_VkMemoryResourceAllocationSizePropertiesMESA_self(w, o)
{
    w.u64(o.allocationSize);
}
function e_VkSubresourceHostMemcpySize_self(w, o)
{
    w.u64(o.size);
}
function e_VkMemoryDedicatedRequirements_self(w, o)
{
    w.u32(o.prefersDedicatedAllocation);
    w.u32(o.requiresDedicatedAllocation);
}
function e_VkPhysicalDeviceFeatures(w, o)
{
    w.u32(o.robustBufferAccess);
    w.u32(o.fullDrawIndexUint32);
    w.u32(o.imageCubeArray);
    w.u32(o.independentBlend);
    w.u32(o.geometryShader);
    w.u32(o.tessellationShader);
    w.u32(o.sampleRateShading);
    w.u32(o.dualSrcBlend);
    w.u32(o.logicOp);
    w.u32(o.multiDrawIndirect);
    w.u32(o.drawIndirectFirstInstance);
    w.u32(o.depthClamp);
    w.u32(o.depthBiasClamp);
    w.u32(o.fillModeNonSolid);
    w.u32(o.depthBounds);
    w.u32(o.wideLines);
    w.u32(o.largePoints);
    w.u32(o.alphaToOne);
    w.u32(o.multiViewport);
    w.u32(o.samplerAnisotropy);
    w.u32(o.textureCompressionETC2);
    w.u32(o.textureCompressionASTC_LDR);
    w.u32(o.textureCompressionBC);
    w.u32(o.occlusionQueryPrecise);
    w.u32(o.pipelineStatisticsQuery);
    w.u32(o.vertexPipelineStoresAndAtomics);
    w.u32(o.fragmentStoresAndAtomics);
    w.u32(o.shaderTessellationAndGeometryPointSize);
    w.u32(o.shaderImageGatherExtended);
    w.u32(o.shaderStorageImageExtendedFormats);
    w.u32(o.shaderStorageImageMultisample);
    w.u32(o.shaderStorageImageReadWithoutFormat);
    w.u32(o.shaderStorageImageWriteWithoutFormat);
    w.u32(o.shaderUniformBufferArrayDynamicIndexing);
    w.u32(o.shaderSampledImageArrayDynamicIndexing);
    w.u32(o.shaderStorageBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageImageArrayDynamicIndexing);
    w.u32(o.shaderClipDistance);
    w.u32(o.shaderCullDistance);
    w.u32(o.shaderFloat64);
    w.u32(o.shaderInt64);
    w.u32(o.shaderInt16);
    w.u32(o.shaderResourceResidency);
    w.u32(o.shaderResourceMinLod);
    w.u32(o.sparseBinding);
    w.u32(o.sparseResidencyBuffer);
    w.u32(o.sparseResidencyImage2D);
    w.u32(o.sparseResidencyImage3D);
    w.u32(o.sparseResidency2Samples);
    w.u32(o.sparseResidency4Samples);
    w.u32(o.sparseResidency8Samples);
    w.u32(o.sparseResidency16Samples);
    w.u32(o.sparseResidencyAliased);
    w.u32(o.variableMultisampleRate);
    w.u32(o.inheritedQueries);
}
function e_VkFormatProperties(w, o)
{
    w.u32(o.linearTilingFeatures);
    w.u32(o.optimalTilingFeatures);
    w.u32(o.bufferFeatures);
}
function e_VkImageFormatProperties(w, o)
{
    e_VkExtent3D(w, o.maxExtent || EMPTY);
    w.u32(o.maxMipLevels);
    w.u32(o.maxArrayLayers);
    w.u32(o.sampleCounts);
    w.u64(o.maxResourceSize);
}
function e_VkPhysicalDeviceProperties(w, o)
{
    w.u32(o.apiVersion);
    w.u32(o.driverVersion);
    w.u32(o.vendorID);
    w.u32(o.deviceID);
    w.i32(o.deviceType);
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.deviceName, n0);
    }
    {
        const n1 = 16;
        w.size(n1);
        w.u8s(o.pipelineCacheUUID, n1);
    }
    e_VkPhysicalDeviceLimits(w, o.limits || EMPTY);
    e_VkPhysicalDeviceSparseProperties(w, o.sparseProperties || EMPTY);
}
function e_VkQueueFamilyProperties(w, o)
{
    w.u32(o.queueFlags);
    w.u32(o.queueCount);
    w.u32(o.timestampValidBits);
    e_VkExtent3D(w, o.minImageTransferGranularity || EMPTY);
}
function e_VkPhysicalDeviceMemoryProperties(w, o)
{
    w.u32(o.memoryTypeCount);
    {
        const n0 = 32;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = o.memoryTypes ? o.memoryTypes[i] : undefined;
            e_VkMemoryType(w, item || EMPTY);
        }
    }
    w.u32(o.memoryHeapCount);
    {
        const n1 = 16;
        w.size(n1);
        for(let i = 0; i < n1; i++)
        {
            const item = o.memoryHeaps ? o.memoryHeaps[i] : undefined;
            e_VkMemoryHeap(w, item || EMPTY);
        }
    }
}
function e_VkExtensionProperties(w, o)
{
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.extensionName, n0);
    }
    w.u32(o.specVersion);
}
function e_VkLayerProperties(w, o)
{
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.layerName, n0);
    }
    w.u32(o.specVersion);
    w.u32(o.implementationVersion);
    {
        const n1 = 256;
        w.size(n1);
        w.str(o.description, n1);
    }
}
function e_VkMemoryRequirements(w, o)
{
    w.u64(o.size);
    w.u64(o.alignment);
    w.u32(o.memoryTypeBits);
}
function e_VkSparseImageMemoryRequirements(w, o)
{
    e_VkSparseImageFormatProperties(w, o.formatProperties || EMPTY);
    w.u32(o.imageMipTailFirstLod);
    w.u64(o.imageMipTailSize);
    w.u64(o.imageMipTailOffset);
    w.u64(o.imageMipTailStride);
}
function e_VkSparseImageFormatProperties(w, o)
{
    w.u32(o.aspectMask);
    e_VkExtent3D(w, o.imageGranularity || EMPTY);
    w.u32(o.flags);
}
function e_VkSubresourceLayout(w, o)
{
    w.u64(o.offset);
    w.u64(o.size);
    w.u64(o.rowPitch);
    w.u64(o.arrayPitch);
    w.u64(o.depthPitch);
}
function e_VkExtent2D(w, o)
{
    w.u32(o.width);
    w.u32(o.height);
}
function e_VkPhysicalDeviceGroupProperties(w, o)
{
    w.u32(1000070000);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceGroupProperties_self(w, o);
}
function e_VkMemoryRequirements2(w, o)
{
    w.u32(1000146003);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkMemoryRequirements2_self(w, o);
}
function e_VkSparseImageMemoryRequirements2(w, o)
{
    w.u32(1000146004);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkSparseImageMemoryRequirements2_self(w, o);
}
function e_VkPhysicalDeviceFeatures2(w, o)
{
    w.u32(1000059000);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceFeatures2_self(w, o);
}
function e_VkPhysicalDeviceProperties2(w, o)
{
    w.u32(1000059001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceProperties2_self(w, o);
}
function e_VkFormatProperties2(w, o)
{
    w.u32(1000059002);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkFormatProperties2_self(w, o);
}
function e_VkImageFormatProperties2(w, o)
{
    w.u32(1000059003);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkImageFormatProperties2_self(w, o);
}
function e_VkQueueFamilyProperties2(w, o)
{
    w.u32(1000059005);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkQueueFamilyProperties2_self(w, o);
}
function e_VkPhysicalDeviceMemoryProperties2(w, o)
{
    w.u32(1000059006);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceMemoryProperties2_self(w, o);
}
function e_VkSparseImageFormatProperties2(w, o)
{
    w.u32(1000059007);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkSparseImageFormatProperties2_self(w, o);
}
function e_VkExternalBufferProperties(w, o)
{
    w.u32(1000071003);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkExternalBufferProperties_self(w, o);
}
function e_VkExternalFenceProperties(w, o)
{
    w.u32(1000112001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkExternalFenceProperties_self(w, o);
}
function e_VkExternalSemaphoreProperties(w, o)
{
    w.u32(1000076001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkExternalSemaphoreProperties_self(w, o);
}
function e_VkDescriptorSetLayoutSupport(w, o)
{
    w.u32(1000168001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkDescriptorSetLayoutSupport_self(w, o);
}
function e_VkImageDrmFormatModifierPropertiesEXT(w, o)
{
    w.u32(1000158005);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkImageDrmFormatModifierPropertiesEXT_self(w, o);
}
function e_VkMemoryResourcePropertiesMESA(w, o)
{
    w.u32(1000384001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkMemoryResourcePropertiesMESA_self(w, o);
}
function e_VkPhysicalDeviceToolProperties(w, o)
{
    w.u32(1000245000);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceToolProperties_self(w, o);
}
function e_VkPhysicalDeviceFragmentShadingRateKHR(w, o)
{
    w.u32(1000226004);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkPhysicalDeviceFragmentShadingRateKHR_self(w, o);
}
function e_VkSubresourceLayout2(w, o)
{
    w.u32(1000338002);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkSubresourceLayout2_self(w, o);
}
function e_VkMultisamplePropertiesEXT(w, o)
{
    w.u32(1000143004);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkMultisamplePropertiesEXT_self(w, o);
}
function e_VkCooperativeMatrixPropertiesKHR(w, o)
{
    w.u32(1000506001);
    w.pnext(o.pNext, PNEXT_REPLY);
    e_VkCooperativeMatrixPropertiesKHR_self(w, o);
}
function e_VkHostAddressRangeEXT(w, o)
{
    w.u64(o.size);
    if(o.address)
    {
        const n0 = o.size;
        w.size(n0);
        w.blob(o.address, n0);
    }
    else w.size(0);
}
function e_VkConformanceVersion(w, o)
{
    w.u8(o.major);
    w.u8(o.minor);
    w.u8(o.subminor);
    w.u8(o.patch);
}
function e_VkDrmFormatModifierPropertiesEXT(w, o)
{
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u32(o.drmFormatModifierTilingFeatures);
}
function e_VkDrmFormatModifierProperties2EXT(w, o)
{
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u64(o.drmFormatModifierTilingFeatures);
}
function e_VkExternalMemoryProperties(w, o)
{
    w.u32(o.externalMemoryFeatures);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
}
function e_VkExtent3D(w, o)
{
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.depth);
}
function e_VkPhysicalDeviceLimits(w, o)
{
    w.u32(o.maxImageDimension1D);
    w.u32(o.maxImageDimension2D);
    w.u32(o.maxImageDimension3D);
    w.u32(o.maxImageDimensionCube);
    w.u32(o.maxImageArrayLayers);
    w.u32(o.maxTexelBufferElements);
    w.u32(o.maxUniformBufferRange);
    w.u32(o.maxStorageBufferRange);
    w.u32(o.maxPushConstantsSize);
    w.u32(o.maxMemoryAllocationCount);
    w.u32(o.maxSamplerAllocationCount);
    w.u64(o.bufferImageGranularity);
    w.u64(o.sparseAddressSpaceSize);
    w.u32(o.maxBoundDescriptorSets);
    w.u32(o.maxPerStageDescriptorSamplers);
    w.u32(o.maxPerStageDescriptorUniformBuffers);
    w.u32(o.maxPerStageDescriptorStorageBuffers);
    w.u32(o.maxPerStageDescriptorSampledImages);
    w.u32(o.maxPerStageDescriptorStorageImages);
    w.u32(o.maxPerStageDescriptorInputAttachments);
    w.u32(o.maxPerStageResources);
    w.u32(o.maxDescriptorSetSamplers);
    w.u32(o.maxDescriptorSetUniformBuffers);
    w.u32(o.maxDescriptorSetUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetStorageBuffers);
    w.u32(o.maxDescriptorSetStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetSampledImages);
    w.u32(o.maxDescriptorSetStorageImages);
    w.u32(o.maxDescriptorSetInputAttachments);
    w.u32(o.maxVertexInputAttributes);
    w.u32(o.maxVertexInputBindings);
    w.u32(o.maxVertexInputAttributeOffset);
    w.u32(o.maxVertexInputBindingStride);
    w.u32(o.maxVertexOutputComponents);
    w.u32(o.maxTessellationGenerationLevel);
    w.u32(o.maxTessellationPatchSize);
    w.u32(o.maxTessellationControlPerVertexInputComponents);
    w.u32(o.maxTessellationControlPerVertexOutputComponents);
    w.u32(o.maxTessellationControlPerPatchOutputComponents);
    w.u32(o.maxTessellationControlTotalOutputComponents);
    w.u32(o.maxTessellationEvaluationInputComponents);
    w.u32(o.maxTessellationEvaluationOutputComponents);
    w.u32(o.maxGeometryShaderInvocations);
    w.u32(o.maxGeometryInputComponents);
    w.u32(o.maxGeometryOutputComponents);
    w.u32(o.maxGeometryOutputVertices);
    w.u32(o.maxGeometryTotalOutputComponents);
    w.u32(o.maxFragmentInputComponents);
    w.u32(o.maxFragmentOutputAttachments);
    w.u32(o.maxFragmentDualSrcAttachments);
    w.u32(o.maxFragmentCombinedOutputResources);
    w.u32(o.maxComputeSharedMemorySize);
    {
        const n0 = 3;
        w.size(n0);
        w.u32s(o.maxComputeWorkGroupCount, n0);
    }
    w.u32(o.maxComputeWorkGroupInvocations);
    {
        const n1 = 3;
        w.size(n1);
        w.u32s(o.maxComputeWorkGroupSize, n1);
    }
    w.u32(o.subPixelPrecisionBits);
    w.u32(o.subTexelPrecisionBits);
    w.u32(o.mipmapPrecisionBits);
    w.u32(o.maxDrawIndexedIndexValue);
    w.u32(o.maxDrawIndirectCount);
    w.f32(o.maxSamplerLodBias);
    w.f32(o.maxSamplerAnisotropy);
    w.u32(o.maxViewports);
    {
        const n2 = 2;
        w.size(n2);
        w.u32s(o.maxViewportDimensions, n2);
    }
    {
        const n3 = 2;
        w.size(n3);
        w.f32s(o.viewportBoundsRange, n3);
    }
    w.u32(o.viewportSubPixelBits);
    w.u64(o.minMemoryMapAlignment);
    w.u64(o.minTexelBufferOffsetAlignment);
    w.u64(o.minUniformBufferOffsetAlignment);
    w.u64(o.minStorageBufferOffsetAlignment);
    w.i32(o.minTexelOffset);
    w.u32(o.maxTexelOffset);
    w.i32(o.minTexelGatherOffset);
    w.u32(o.maxTexelGatherOffset);
    w.f32(o.minInterpolationOffset);
    w.f32(o.maxInterpolationOffset);
    w.u32(o.subPixelInterpolationOffsetBits);
    w.u32(o.maxFramebufferWidth);
    w.u32(o.maxFramebufferHeight);
    w.u32(o.maxFramebufferLayers);
    w.u32(o.framebufferColorSampleCounts);
    w.u32(o.framebufferDepthSampleCounts);
    w.u32(o.framebufferStencilSampleCounts);
    w.u32(o.framebufferNoAttachmentsSampleCounts);
    w.u32(o.maxColorAttachments);
    w.u32(o.sampledImageColorSampleCounts);
    w.u32(o.sampledImageIntegerSampleCounts);
    w.u32(o.sampledImageDepthSampleCounts);
    w.u32(o.sampledImageStencilSampleCounts);
    w.u32(o.storageImageSampleCounts);
    w.u32(o.maxSampleMaskWords);
    w.u32(o.timestampComputeAndGraphics);
    w.f32(o.timestampPeriod);
    w.u32(o.maxClipDistances);
    w.u32(o.maxCullDistances);
    w.u32(o.maxCombinedClipAndCullDistances);
    w.u32(o.discreteQueuePriorities);
    {
        const n4 = 2;
        w.size(n4);
        w.f32s(o.pointSizeRange, n4);
    }
    {
        const n5 = 2;
        w.size(n5);
        w.f32s(o.lineWidthRange, n5);
    }
    w.f32(o.pointSizeGranularity);
    w.f32(o.lineWidthGranularity);
    w.u32(o.strictLines);
    w.u32(o.standardSampleLocations);
    w.u64(o.optimalBufferCopyOffsetAlignment);
    w.u64(o.optimalBufferCopyRowPitchAlignment);
    w.u64(o.nonCoherentAtomSize);
}
function e_VkPhysicalDeviceSparseProperties(w, o)
{
    w.u32(o.residencyStandard2DBlockShape);
    w.u32(o.residencyStandard2DMultisampleBlockShape);
    w.u32(o.residencyStandard3DBlockShape);
    w.u32(o.residencyAlignedMipSize);
    w.u32(o.residencyNonResidentStrict);
}
function e_VkMemoryType(w, o)
{
    w.u32(o.propertyFlags);
    w.u32(o.heapIndex);
}
function e_VkMemoryHeap(w, o)
{
    w.u64(o.size);
    w.u32(o.flags);
}
function e_VkPhysicalDeviceGroupProperties_self(w, o)
{
    w.u32(o.physicalDeviceCount);
    {
        const n0 = 32;
        w.size(n0);
        for(let i = 0; i < n0; i++)
        {
            const item = o.physicalDevices ? o.physicalDevices[i] : undefined;
            w.h(item);
        }
    }
    w.u32(o.subsetAllocation);
}
function e_VkMemoryRequirements2_self(w, o)
{
    e_VkMemoryRequirements(w, o.memoryRequirements || EMPTY);
}
function e_VkSparseImageMemoryRequirements2_self(w, o)
{
    e_VkSparseImageMemoryRequirements(w, o.memoryRequirements || EMPTY);
}
function e_VkPhysicalDeviceFeatures2_self(w, o)
{
    e_VkPhysicalDeviceFeatures(w, o.features || EMPTY);
}
function e_VkPhysicalDeviceProperties2_self(w, o)
{
    e_VkPhysicalDeviceProperties(w, o.properties || EMPTY);
}
function e_VkFormatProperties2_self(w, o)
{
    e_VkFormatProperties(w, o.formatProperties || EMPTY);
}
function e_VkImageFormatProperties2_self(w, o)
{
    e_VkImageFormatProperties(w, o.imageFormatProperties || EMPTY);
}
function e_VkQueueFamilyProperties2_self(w, o)
{
    e_VkQueueFamilyProperties(w, o.queueFamilyProperties || EMPTY);
}
function e_VkPhysicalDeviceMemoryProperties2_self(w, o)
{
    e_VkPhysicalDeviceMemoryProperties(w, o.memoryProperties || EMPTY);
}
function e_VkSparseImageFormatProperties2_self(w, o)
{
    e_VkSparseImageFormatProperties(w, o.properties || EMPTY);
}
function e_VkExternalBufferProperties_self(w, o)
{
    e_VkExternalMemoryProperties(w, o.externalMemoryProperties || EMPTY);
}
function e_VkExternalFenceProperties_self(w, o)
{
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalFenceFeatures);
}
function e_VkExternalSemaphoreProperties_self(w, o)
{
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalSemaphoreFeatures);
}
function e_VkDescriptorSetLayoutSupport_self(w, o)
{
    w.u32(o.supported);
}
function e_VkImageDrmFormatModifierPropertiesEXT_self(w, o)
{
    w.u64(o.drmFormatModifier);
}
function e_VkMemoryResourcePropertiesMESA_self(w, o)
{
    w.u32(o.memoryTypeBits);
}
function e_VkPhysicalDeviceToolProperties_self(w, o)
{
    {
        const n0 = 256;
        w.size(n0);
        w.str(o.name, n0);
    }
    {
        const n1 = 256;
        w.size(n1);
        w.str(o.version, n1);
    }
    w.u32(o.purposes);
    {
        const n2 = 256;
        w.size(n2);
        w.str(o.description, n2);
    }
    {
        const n3 = 256;
        w.size(n3);
        w.str(o.layer, n3);
    }
}
function e_VkPhysicalDeviceFragmentShadingRateKHR_self(w, o)
{
    w.u32(o.sampleCounts);
    e_VkExtent2D(w, o.fragmentSize || EMPTY);
}
function e_VkSubresourceLayout2_self(w, o)
{
    e_VkSubresourceLayout(w, o.subresourceLayout || EMPTY);
}
function e_VkMultisamplePropertiesEXT_self(w, o)
{
    e_VkExtent2D(w, o.maxSampleLocationGridSize || EMPTY);
}
function e_VkCooperativeMatrixPropertiesKHR_self(w, o)
{
    w.u32(o.MSize);
    w.u32(o.NSize);
    w.u32(o.KSize);
    w.i32(o.AType);
    w.i32(o.BType);
    w.i32(o.CType);
    w.i32(o.ResultType);
    w.u32(o.saturatingAccumulation);
    w.i32(o.scope);
}
                                                             source/v64/src/graphics_adapters/virtio_gpu/venus_state.js                                          0000644 0000000 0000000 00000005771 00000000000 021235  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Snapshots of Venus contexts: the Vulkan model's objects as JSON (a v86
// snapshot holds arrays, numbers, strings and typed arrays, not objects).
// An object that points at another of the context's objects keeps its id;
// what the graph points at but does not own (the context, a blob) becomes
// [kind, id] for the caller to find again.

const TYPED = {
    "Uint8Array": Uint8Array, "Int8Array": Int8Array, "Uint16Array": Uint16Array, "Int16Array": Int16Array,
    "Uint32Array": Uint32Array, "Int32Array": Int32Array, "Float32Array": Float32Array, "Float64Array": Float64Array,
};

/**
 * @param {!Map<number, !Object>} objects by id
 * @param {function(!Object): Array} outside [kind, id] of an object owned elsewhere, else null
 * @return {string}
 */
export function encode_objects(objects, outside)
{
    const ids = new Map();
    for(const [id, o] of objects) ids.set(o, id);
    const value = (v, top) => {
        if(v === undefined || typeof v === "function") return null;
        if(typeof v === "number" && !Number.isFinite(v)) return { "$n": String(v) };
        if(v === null || typeof v !== "object") return v;
        const o = /** @type {!Object} */ (v);
        if(!top && ids.has(o)) return { "$r": ids.get(o) };
        const other = outside(o);
        if(other) return { "$o": other };
        if(ArrayBuffer.isView(o)) return { "$t": o.constructor.name, "d": Array.from(/** @type {!IArrayLike<number>} */ (o)) };
        if(o instanceof Map) return { "$m": [...o].map(([k, x]) => [value(k, false), value(x, false)]) };
        if(o instanceof Set) return { "$s": [...o].map(x => value(x, false)) };
        if(Array.isArray(o)) return o.map(x => value(x, false));
        const out = {};
        for(const key of Object.keys(o)) out[key] = value(o[key], false);
        return out;
    };
    return JSON.stringify([...objects].map(([id, o]) => [id, value(o, true)]));
}

/**
 * @param {string} json from encode_objects
 * @param {function(!Array): *} resolve what [kind, id] was
 * @return {!Map<number, !Object>} by id
 */
export function decode_objects(json, resolve)
{
    const entries = /** @type {!Array<!Array>} */ (JSON.parse(json));
    // the objects first, empty, so that references find them
    const objects = new Map();
    for(const [id] of entries) objects.set(id, {});
    const value = v => {
        if(v === null || typeof v !== "object") return v;
        if(Array.isArray(v)) return v.map(value);
        const o = /** @type {!Object} */ (v);
        if("$r" in o) return objects.get(o["$r"]) || null;
        if("$o" in o) return resolve(o["$o"]);
        if("$n" in o) return Number(o["$n"]);
        if("$t" in o) return new TYPED[o["$t"]](o["d"]);
        if("$m" in o) return new Map(o["$m"].map(([k, x]) => [value(k), value(x)]));
        if("$s" in o) return new Set(o["$s"].map(value));
        const out = {};
        for(const key of Object.keys(o)) out[key] = value(o[key]);
        return out;
    };
    for(const [id, o] of entries) Object.assign(objects.get(id), value(o));
    return objects;
}
       source/v64/src/graphics_adapters/virtio_gpu/venus_vk.js                                             0000644 0000000 0000000 00000105121 00000000000 020523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Vulkan model of the Venus device (venus.js runs the transport): the
// guest driver's Vulkan objects, by the ids it gives them, and the commands
// on them. Queries are answered here, from venus_device_info.js; what
// draws and copies goes to the WebGPU executor (the renderer).

import * as INFO from "./venus_device_info.js";
import { GXWriter, VX, VX_MAGIC } from "../renderer_protocol.js";
import { RESOURCE_HANDLERS, lo, hi } from "./venus_vk_resources.js";
import { COMMAND_HANDLERS, translate, command_state } from "./venus_vk_commands.js";
import { PIPELINE_HANDLERS } from "./venus_vk_pipeline.js";
import { dbg_log } from "../../log.js";
import { LOG_VIRTIO } from "../../const.js";

import { VK_SUCCESS, VK_NOT_READY, VK_TIMEOUT, VK_INCOMPLETE, VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY,
    VK_ERROR_INITIALIZATION_FAILED, VK_ERROR_DEVICE_LOST, VK_ERROR_LAYER_NOT_PRESENT, VK_ERROR_EXTENSION_NOT_PRESENT,
    VK_ERROR_FEATURE_NOT_PRESENT, VK_ERROR_FORMAT_NOT_SUPPORTED, out_array } from "./venus_device_info.js";

const PAGE = 4096;
/** the VX commands that make renderer objects (what a snapshot makes again) */
const CREATIONS = new Set([VX.MEMORY_CREATE, VX.TEXTURE_CREATE, VX.VIEW_CREATE, VX.SAMPLER_CREATE, VX.SHADER_CREATE,
    VX.PIPELINE_CREATE, VX.QUERY_POOL_CREATE]);
const STYPE_DEVICE_QUEUE_TIMELINE_INFO_MESA = 1000384005;
// VkExternal{Semaphore,Fence}FeatureFlagBits
const EXTERNAL_EXPORTABLE = 1, EXTERNAL_IMPORTABLE = 2;

/**
 * @constructor
 * @param {!Object} options { host_visible_size, gpu: the VirtioGPU (its renderer channel and host visible memory) }
 */
export function VulkanModel(options)
{
    this.host_visible_size = options.host_visible_size || 0;
    this.gpu = options.gpu || null;
    this.stats = { unimplemented: {}, submissions: 0, batches: 0, readbacks: 0 };
    this.warned = new Set();
    /** @type {!Array<string>} the first warnings, for test harnesses */
    this.warnings = [];
    /** the VX batch being written: object creations, then a submission's commands */
    this.vx = new GXWriter(VX_MAGIC);
    /** @type {!Map<number, !Array>} the renderer's objects as made: rid -> [op, dwords, bytes], for snapshots */
    this.created = new Map();
    /** @type {!Map<number, !Array>} shaders destroyed while pipelines made of them may live (they are made again for those) */
    this.retired = new Map();
    /** @type {!Map<number, !Array<number>>} images that are virtio-gpu resources' GX surfaces: rid -> [rid, resource id] */
    this.imports = new Map();
    this.vx.listener = (op, dwords, bytes) => {
        if(CREATIONS.has(op)) this.created.set(dwords[0], [op, Array.from(dwords), bytes ? bytes.slice() : null]);
        else if(op === VX.TEXTURE_IMPORT) this.imports.set(dwords[0], Array.from(dwords));
        else if(op === VX.DESTROY)
        {
            this.imports.delete(dwords[0]);
            const entry = this.created.get(dwords[0]);
            if(entry && entry[0] === VX.SHADER_CREATE)
            {
                this.retired.set(dwords[0], entry);
                if(this.retired.size > 256) this.prune_retired();
            }
            this.created.delete(dwords[0]);
        }
    };
    this.next_rid = 1;
    this.host_allocated = 0;
    this.device_allocated = 0;
    /** @type {!Set<!Object>} queues with submissions */
    this.queues = new Set();
    /** @type {!Array<{check: function():boolean, deadline: number, then: function(boolean)}>} */
    this.waiters = [];
    /** the machine's time (ms), from the last timer */
    this.now = 0;
    /** @type {?function(string)} a harness's hook: uploads, submissions, readbacks */
    this.debug = null;
}

// ---------------------------------------------------------------------------
// Snapshots: the renderer's objects are made again from their creation
// commands, with the contents the GPU had (read back before the save)

/**
 * The contents of the renderer's memories and images, read back (the GPU
 * has done its work)
 * @return {!Promise}
 */
VulkanModel.prototype.save_contents = function()
{
    const saved = this.saved = new Map();
    const reads = [];
    const read = (op, words, then) => reads.push(new Promise(resolve => {
        const id = this.gpu.virgl.request(bytes => { then(bytes); resolve(undefined); });
        this.vx.command(op, [...words, id]);
    }));
    for(const [rid, entry] of this.created)
    {
        const op = entry[0], words = entry[1];
        if(op === VX.MEMORY_CREATE)
        {
            const size = words[1] + words[2] * 0x100000000;
            if(size) read(VX.MEMORY_READ, [rid, 0, 0, size], data => { if(data) saved.set(rid, data); });
        }
        // (an imported image's texels are its resource's: virgl saves them)
        else if(op === VX.TEXTURE_CREATE && !this.imports.has(/** @type {number} */ (rid)))
        {
            const [, format, type, , , depth, mips, layers, samples] = words;
            const entry = INFO.FORMATS[format];
            if(samples > 1 || !entry || !entry[0]) continue;
            const gpu_format = entry[0];
            // VkImageAspectFlagBits: color, depth, stencil
            const aspects = /^depth/.test(gpu_format) ? (/stencil/.test(gpu_format) ? [2, 4] : [2]) : gpu_format === "stencil8" ? [4] : [1];
            const images = [];
            saved.set(rid, images);
            for(let mip = 0; mip < mips; mip++)
            {
                const count = type === 2 ? Math.max(1, depth >> mip) : layers;
                for(let layer = 0; layer < count; layer++)
                {
                    for(const aspect of aspects)
                    {
                        read(VX.TEXTURE_READ, [rid, aspect, mip, layer], data => { if(data) images.push([aspect, mip, layer, data]); });
                    }
                }
            }
        }
    }
    this.send();
    return Promise.all(reads);
};

/** The shaders the live pipelines are made of, by rid */
VulkanModel.prototype.pipeline_shaders = function()
{
    const used = new Set();
    for(const [op, , bytes] of this.created.values())
    {
        if(op !== VX.PIPELINE_CREATE || !bytes) continue;
        let end = bytes.length;
        while(end && !bytes[end - 1]) end--;
        for(const stage of JSON.parse(new TextDecoder().decode(bytes.subarray(0, end)))["stages"] || []) used.add(stage["shader"]);
    }
    return used;
};

/** Forget the destroyed shaders no live pipeline is made of */
VulkanModel.prototype.prune_retired = function()
{
    const used = this.pipeline_shaders();
    for(const rid of [...this.retired.keys()]) if(!used.has(rid)) this.retired.delete(rid);
};

/** @return {!Array} */
VulkanModel.prototype.get_state = function()
{
    this.prune_retired();
    // (the destroyed shaders of live pipelines first, destroyed again once the pipelines are made)
    const retired = [...this.retired.values()];
    const created = retired.concat([...this.created.values()]).map(([op, dwords, bytes]) => [op, dwords, bytes])
        .concat(retired.map(([, dwords]) => [VX.DESTROY, [dwords[0]], null]));
    const contents = this.saved ? [...this.saved] : [];
    this.saved = null;
    return [this.next_rid, this.host_allocated, this.device_allocated, created, contents, [...this.imports.values()]];
};

/**
 * The renderer's objects again (it was reset), then the contexts' objects
 * fixed up: nothing on its way any more
 * @param {!Array} state from get_state
 * @param {!Array<!Object>} contexts the Venus contexts, their objects restored
 */
VulkanModel.prototype.set_state = function(state, contexts)
{
    const [next_rid, host_allocated, device_allocated, created, contents, imports] = state;
    this.next_rid = next_rid;
    this.host_allocated = host_allocated;
    this.device_allocated = device_allocated;
    this.created.clear();
    this.retired.clear();
    this.imports.clear();
    this.queues.clear();
    this.waiters = [];
    if(!this.vx.empty()) this.vx.finish();
    for(const [op, dwords, bytes] of created) this.vx.command(op, dwords, bytes || undefined);
    const CHUNK = 16 << 20;
    for(const [rid, content] of contents)
    {
        if(ArrayBuffer.isView(content))
        {
            const bytes = /** @type {!Uint8Array} */ (content);
            for(let at = 0; at < bytes.length; at += CHUNK)
            {
                const piece = bytes.subarray(at, Math.min(bytes.length, at + CHUNK));
                this.vx.command(VX.MEMORY_WRITE, [rid, at, 0, piece.length], piece);
            }
        }
        else
        {
            for(const [aspect, mip, layer, bytes] of content) this.vx.command(VX.TEXTURE_WRITE, [rid, aspect, mip, layer, bytes.length], bytes);
        }
    }
    // (the resources' GX surfaces are back: virgl's state comes first)
    for(const dwords of imports || []) this.vx.command(VX.TEXTURE_IMPORT, dwords);
    for(const ctx of contexts)
    {
        for(const object of ctx.objects.values())
        {
            if(object.type === "memory")
            {
                object.pending = [];
                if(object.blob) object.blob.memory = object;
            }
            else if(object.type === "queue")
            {
                object.inflight = 0;
                if(object.pending && object.pending.length) this.queues.add(object);
            }
        }
    }
    this.send();
};

/** @return {number} a renderer object's id */
VulkanModel.prototype.new_rid = function()
{
    return this.next_rid++;
};

VulkanModel.prototype.warn_once = function(key, text)
{
    if(this.warned.has(key)) return;
    this.warned.add(key);
    if(this.warnings.length < 100) this.warnings.push(text);
    dbg_log("venus: " + text, LOG_VIRTIO);
};

VulkanModel.prototype.create_context = function(ctx)
{
    ctx.physical_device = 0;
};

VulkanModel.prototype.destroy_context = function(ctx)
{
    // (the renderer's objects of the context go too)
    for(const object of ctx.objects.values())
    {
        if(object.rid) this.vx.command(VX.DESTROY, [object.rid]);
        if(object.type === "queue") this.queues.delete(object);
        if(object.type === "memory")
        {
            if(object.host_visible) this.host_allocated -= object.size; else this.device_allocated -= object.size;
            if(object.blob) object.blob.memory = null;
        }
    }
    ctx.objects.clear();
    this.send();
};

/** whether a command has its handler (gfxstream: an alias's core command) */
VulkanModel.prototype.handles = function(name)
{
    return !!HANDLERS[name];
};

/**
 * A Vulkan command
 * @param {!Object} ctx
 * @param {string} name
 * @param {!Object} a its parameters (outputs and `ret` are set here)
 * @return {?function(function())} when its reply waits
 */
VulkanModel.prototype.handle = function(ctx, name, a)
{
    const handler = HANDLERS[name];
    if(handler) return handler(this, ctx, a) || null;
    if(name.startsWith("vkCmd"))
    {
        // recorded; the submission turns it into VX
        const cb = ctx.objects.get(a.commandBuffer);
        if(cb) cb.commands.push([name, a]);
        return null;
    }
    this.stats.unimplemented[name] = (this.stats.unimplemented[name] || 0) + 1;
    if(this.stats.unimplemented[name] === 1) dbg_log("venus: " + name + " is not implemented", LOG_VIRTIO);
    a.ret = VK_ERROR_FEATURE_NOT_PRESENT;
    return null;
};

// ---------------------------------------------------------------------------
// The renderer

/** Send the VX batch written so far */
VulkanModel.prototype.send = function()
{
    if(this.vx.empty() || !this.gpu || !this.gpu.virgl) return;
    this.stats.batches++;
    this.gpu.virgl.submit_stream(this.vx.finish(), "vx");
};

/**
 * Read a memory's bytes back from the GPU (in the batch, after what is before it)
 * @param {!Object} memory
 * @param {number} offset
 * @param {number} length
 * @param {function(Uint8Array)} answer
 */
VulkanModel.prototype.read = function(memory, offset, length, answer)
{
    const virgl = this.gpu.virgl;
    const id = virgl.request((bytes, status) => answer(bytes));
    this.stats.readbacks++;
    this.vx.command(VX.MEMORY_READ, [memory.rid, lo(offset), hi(offset), length, id]);
};

/**
 * Run `then` when everything sent so far has run
 * @param {function()} then
 */
VulkanModel.prototype.after = function(then)
{
    this.send();
    this.gpu.virgl.after_work(then);
};

// ---------------------------------------------------------------------------
// Host visible memory: the guest's mappings

/** the largest page a guest's kernel may round a blob to (Arm's 64 KiB granule) */
const GUEST_PAGE_MAX = 65536;

/** RESOURCE_CREATE_BLOB of a VkDeviceMemory: host visible memory only */
VulkanModel.prototype.export_memory = function(ctx, memory, blob)
{
    // (the guest's kernel makes blobs of whole pages: 4, 16 or 64 KiB)
    if(memory.type !== "memory" || !memory.host_visible || memory.blob || blob.blob_size > Math.ceil(memory.size / GUEST_PAGE_MAX) * GUEST_PAGE_MAX) return false;
    memory.blob = blob;
    return true;
};

/**
 * MAP_BLOB: the mapping gets the memory's contents (zeros when nothing wrote it)
 * @return {?function(function())}
 */
VulkanModel.prototype.map_memory = function(memory, blob)
{
    const gpu = this.gpu;
    gpu.take_hostmem_dirty();
    gpu.for_pages(blob.map_offset, blob.blob_size, page => { gpu.hostmem_pending[page >>> 5] &= ~(1 << (page & 31)); });
    if(memory.fresh !== false)
    {
        gpu.hostmem_bytes().fill(0, blob.map_offset, blob.map_offset + blob.blob_size);
        return null;
    }
    // (the GPU wrote it: what it has now)
    let finished = false, finish = null;
    gpu.hostmem_bytes().fill(0, blob.map_offset, blob.map_offset + blob.blob_size);
    this.read(memory, 0, Math.min(blob.blob_size, memory.size), data => {
        if(data && blob.memory === memory && blob.map_offset >= 0) gpu.hostmem_bytes().set(data, blob.map_offset);
        finished = true;
        if(finish) finish();
    });
    this.send();
    return done => { if(finished) done(); else finish = done; };
};

/** The blob goes away (its mapping's last writes were uploaded before) */
VulkanModel.prototype.unexport_memory = function(memory, blob)
{
    if(memory.blob === blob) memory.blob = null;
};

/**
 * Pages the guest wrote through a mapping (VirtioGPU.upload_hostmem):
 * except the bytes the GPU has written and the device has not read back
 * yet (they would be older than the GPU's)
 * @param {!Object} blob
 * @param {number} x where in the blob
 * @param {!Uint8Array} bytes
 */
VulkanModel.prototype.upload_blob = function(blob, x, bytes)
{
    const memory = blob.memory;
    // (past the memory: the rest of the blob's last page)
    if(!memory || x >= memory.size) return;
    if(x + bytes.length > memory.size) bytes = bytes.subarray(0, memory.size - x);
    memory.fresh = false;
    let runs = [[x, x + bytes.length]];
    for(const [start, end] of memory.pending || [])
    {
        runs = runs.flatMap(([a, b]) => end <= a || start >= b ? [[a, b]] : [[a, Math.min(b, start)], [Math.max(a, end), b]].filter(r => r[1] > r[0]));
    }
    for(const [a, b] of runs)
    {
        // (whole dwords: the GPU buffer's writes are of them)
        const from = a & ~3, to = Math.min(memory.size, b + 3 & ~3);
        if(this.debug) this.debug("upload memory " + memory.rid + " [" + from + ", " + to + ") " + Array.from(bytes.subarray(from - x, Math.min(to - x, from - x + 16))).join(","));
        this.vx.command(VX.MEMORY_WRITE, [memory.rid, lo(from), hi(from), to - from], bytes.subarray(from - x, to - x));
    }
};

/**
 * After a submission: the ranges the GPU wrote come back into their
 * mappings (the guest may have written other bytes of their pages)
 * @param {!Map<!Object, !Array<!Array<number>>>} written memory -> [start, end) ranges
 */
VulkanModel.prototype.read_back = function(written)
{
    const gpu = this.gpu;
    for(const [memory, ranges] of written)
    {
        memory.fresh = false;
        const blob = memory.blob;
        if(!memory.host_visible || !blob || blob.map_offset < 0)
        {
            if(this.debug && memory.host_visible) this.debug("readback skipped memory " + memory.rid + " " + JSON.stringify(ranges.slice(0, 4)) +
                (blob ? " (not mapped)" : " (no blob)"));
            continue;
        }
        // merged, in whole dwords, within the memory
        const sorted = ranges.map(([a, b]) => [a & ~3, Math.min(memory.size, b + 3 & ~3)]).filter(r => r[1] > r[0]).sort((p, q) => p[0] - q[0]);
        const merged = [];
        for(const r of sorted)
        {
            const last = merged[merged.length - 1];
            if(last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
            else merged.push(r.slice());
        }
        if(!memory.pending) memory.pending = [];
        const offset = blob.map_offset;
        for(const range of merged)
        {
            memory.pending.push(range);
            this.read(memory, range[0], range[1] - range[0], data => {
                if(this.debug) this.debug("readback memory " + memory.rid + " [" + range + ") " + (data ? Array.from(data.subarray(0, 16)).join(",") : "failed") +
                    " mapped at " + blob.map_offset + (memory.blob === blob ? "" : " (not the blob's any more)"));
                memory.pending.splice(memory.pending.indexOf(range), 1);
                if(data && memory.blob === blob && blob.map_offset === offset) gpu.hostmem_bytes().set(data, offset + range[0]);
            });
        }
    }
};

// ---------------------------------------------------------------------------
// Submissions and waits

/**
 * vkQueueSubmit(2): in the queue's order, when its timeline waits are met
 * @param {!Object} ctx
 * @param {number} queue_id
 * @param {!Array<{waits: !Array, command_buffers: !Array<number>, signals: !Array}>} submits
 * @param {number} fence_id
 */
VulkanModel.prototype.submit = function(ctx, queue_id, submits, fence_id)
{
    const queue = ctx.objects.get(queue_id);
    if(!queue) return;
    const fence = fence_id ? ctx.objects.get(fence_id) : null;
    if(fence) { fence.signaled = false; fence.pending++; }
    queue.pending.push({ ctx, submits, fence, generation: fence ? fence.generation : 0 });
    queue.ctx = ctx;
    this.queues.add(queue);
    this.pump();
};

/** Send the submissions whose waits are met */
VulkanModel.prototype.pump = function()
{
    for(const queue of this.queues)
    {
        while(queue.pending.length)
        {
            const entry = queue.pending[0];
            const ready = entry.submits.every(s => s.waits.every(([id, value]) => {
                const semaphore = entry.ctx.objects.get(id);
                return !semaphore || !semaphore.timeline || timeline_ready(semaphore, value);
            }));
            if(!ready) break;
            queue.pending.shift();
            this.run_submission(queue, entry);
        }
    }
};

function timeline_ready(semaphore, value)
{
    return semaphore.value >= value || semaphore.submitted >= value;
}

VulkanModel.prototype.run_submission = function(queue, entry)
{
    const ctx = entry.ctx;
    this.stats.submissions++;
    // the guest's writes through its mappings first
    this.gpu.upload_hostmem();
    const state = { written: new Map(), after: [], queries: new Map() };
    const signals = [];
    for(const submit of entry.submits)
    {
        for(const [id] of submit.waits)
        {
            const semaphore = ctx.objects.get(id);
            if(semaphore && !semaphore.timeline) semaphore.signaled = false;
        }
        // (a WebGPU command buffer for each: one WebGPU refuses drops only its own
        // commands, not the next one's, as Mesa's fence and semaphore feedback)
        for(const id of submit.command_buffers)
        {
            const cb = ctx.objects.get(id);
            state.cb = command_state();
            this.vx.command(VX.BEGIN, []);
            if(cb) translate(this, ctx, cb.commands, state);
            this.vx.command(VX.END, []);
        }
        for(const [id, value] of submit.signals)
        {
            const semaphore = ctx.objects.get(id);
            if(!semaphore) continue;
            if(semaphore.timeline) semaphore.submitted = Math.max(semaphore.submitted, value);
            signals.push([semaphore, value, semaphore.generation]);
        }
    }
    this.read_back(state.written);
    this.read_queries(state.queries);
    // (the resources Venus draws into: what the GPU has is newer than what
    // the device last copied, for the display and the guest's transfers)
    for(const [, resource_id] of this.imports.values())
    {
        const resource = this.gpu && this.gpu.resources ? this.gpu.resources.get(resource_id) : null;
        if(resource && resource.three_d) this.gpu.virgl.wrote(resource);
    }
    if(this.debug) this.debug("submission of " + entry.submits.map(s => s.command_buffers.join("+")).join(", ") + ": writes " +
        [...state.written].map(([m, r]) => m.rid + ":" + JSON.stringify(r)).join(" "));
    queue.inflight++;
    this.after(() => {
        queue.inflight--;
        for(const run of state.after) run();
        // (not the signals a sync file took: their objects' generation moved on)
        for(const [semaphore, value, generation] of signals)
        {
            if(semaphore.timeline) semaphore.value = Math.max(semaphore.value, value);
            else if(semaphore.generation === generation) semaphore.signaled = true;
        }
        if(entry.fence && entry.fence.generation === entry.generation && !--entry.fence.pending) entry.fence.signaled = true;
        this.wake();
    });
};

/**
 * The results of the queries a submission touched, into their pools (before
 * its fence: the answers come before the batch's completion)
 * @param {!Map} queries pool -> Set of queries
 */
VulkanModel.prototype.read_queries = function(queries)
{
    for(const [pool, set] of queries)
    {
        const list = [...set].sort((p, q) => p - q), first = list[0], count = list[list.length - 1] - first + 1;
        // (values a query: two for transform feedback's)
        const values = pool.values || 1, bytes = 8 * values;
        this.read(pool.memory, first * bytes, count * bytes, data => {
            const view = data && data.length >= count * bytes ? new DataView(data.buffer, data.byteOffset, data.length) : null;
            for(const q of list)
            {
                for(let k = 0; k < values && view; k++)
                {
                    const at = (q - first) * bytes + 8 * k;
                    pool.results[q * values + k] = view.getUint32(at, true) + view.getUint32(at + 4, true) * 0x100000000;
                }
                pool.available[q] = 1;
            }
        });
    }
};

/** Milliseconds, for timestamps */
VulkanModel.prototype.clock = function()
{
    return typeof performance !== "undefined" ? performance.now() : Date.now();
};

/**
 * Whether the GPU has done all of a timeline's (a queue's) submissions
 * @param {!Object} ctx
 * @param {number} ring_idx
 */
VulkanModel.prototype.timeline_idle = function(ctx, ring_idx)
{
    for(const queue of this.queues)
    {
        if(queue.ring_idx === ring_idx && queue.ctx === ctx && (queue.pending.length || queue.inflight)) return false;
    }
    return true;
};

/**
 * A command waits until `check` holds or `timeout` (ns) passes
 * @param {function():boolean} check
 * @param {number} timeout
 * @param {function(boolean)} then
 */
VulkanModel.prototype.add_waiter = function(check, timeout, then)
{
    const deadline = timeout >= 2 ** 63 ? Infinity : this.now + timeout / 1e6;
    this.waiters.push({ check, deadline, then });
};

/** Something completed or was signaled: the waits it ends, the submissions it lets go */
VulkanModel.prototype.wake = function()
{
    const waiters = this.waiters;
    this.waiters = [];
    for(const w of waiters)
    {
        if(w.check()) w.then(true);
        else this.waiters.push(w);
    }
    this.pump();
};

/** The machine's time: waits time out */
VulkanModel.prototype.timer = function(now)
{
    this.now = now;
    if(!this.waiters.length) return;
    const waiters = this.waiters;
    this.waiters = [];
    for(const w of waiters)
    {
        if(w.check()) w.then(true);
        else if(now >= w.deadline) w.then(false);
        else this.waiters.push(w);
    }
};

// ---------------------------------------------------------------------------
// The handlers

/** @type {!Object<string, function(!VulkanModel, !Object, !Object): ?function(function())>} */
const HANDLERS = {
    // The device and its queues

    "vkCreateDevice": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        for(const name of info.ppEnabledExtensionNames || [])
        {
            if(!INFO.DEVICE_EXTENSIONS[name]) { a.ret = VK_ERROR_EXTENSION_NOT_PRESENT; return null; }
        }
        // the features asked for: VkPhysicalDeviceFeatures (or its Features2), the others false
        const supported = INFO.features();
        let asked = info.pEnabledFeatures;
        for(let s = info.pNext; s; s = s.pNext) if(s.sType === INFO.STYPE.PHYSICAL_DEVICE_FEATURES_2) asked = s.features;
        for(const name in asked || {})
        {
            if(asked[name] && !supported[name]) { a.ret = VK_ERROR_FEATURE_NOT_PRESENT; return null; }
        }
        ctx.objects.set(a.pDevice, { type: "device" });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyDevice": function(vk, ctx, a)
    {
        for(const [id, object] of ctx.objects)
        {
            if(object.type === "queue" && object.device === a.device) { vk.queues.delete(object); ctx.objects.delete(id); }
        }
        ctx.objects.delete(a.device);
        return null;
    },
    "vkGetDeviceQueue": function(vk, ctx, a)
    {
        ctx.objects.set(a.pQueue, { type: "queue", device: a.device, family: a.queueFamilyIndex, index: a.queueIndex,
            ring_idx: 0, pending: [], inflight: 0 });
        return null;
    },
    "vkGetDeviceQueue2": function(vk, ctx, a)
    {
        const info = a.pQueueInfo;
        let ring_idx = 0;
        for(let s = info.pNext; s; s = s.pNext) if(s.sType === STYPE_DEVICE_QUEUE_TIMELINE_INFO_MESA) ring_idx = s.ringIdx;
        ctx.objects.set(a.pQueue, { type: "queue", device: a.device, family: info.queueFamilyIndex, index: info.queueIndex,
            ring_idx, pending: [], inflight: 0 });
        return null;
    },
    "vkGetDeviceGroupPeerMemoryFeatures": function(vk, ctx, a)
    {
        // (one device: copy, generic src and dst)
        a.pPeerMemoryFeatures = 0xF;
        return null;
    },

    // The instance

    "vkEnumerateInstanceVersion": function(vk, ctx, a)
    {
        a.pApiVersion = INFO.VK_API_VERSION;
        a.ret = VK_SUCCESS;
    },
    "vkEnumerateInstanceExtensionProperties": function(vk, ctx, a)
    {
        if(a.pLayerName) { a.ret = VK_ERROR_LAYER_NOT_PRESENT; return; }
        out_array(a, "pPropertyCount", "pProperties", []);
    },
    "vkEnumerateInstanceLayerProperties": function(vk, ctx, a)
    {
        out_array(a, "pPropertyCount", "pProperties", []);
    },
    "vkCreateInstance": function(vk, ctx, a)
    {
        // (the driver enables no instance extension of the renderer's)
        if(a.pCreateInfo.enabledExtensionCount) { a.ret = VK_ERROR_EXTENSION_NOT_PRESENT; return; }
        ctx.objects.set(a.pInstance, { type: "instance" });
        a.ret = VK_SUCCESS;
    },
    "vkDestroyInstance": function(vk, ctx, a)
    {
        ctx.objects.delete(a.instance);
    },
    "vkEnumeratePhysicalDevices": function(vk, ctx, a)
    {
        // one; the driver names it (its id is in the array)
        if(!a.pPhysicalDevices)
        {
            a.pPhysicalDeviceCount = 1;
            a.ret = VK_SUCCESS;
            return;
        }
        a.pPhysicalDevices.length = Math.min(1, a.pPhysicalDevices.length);
        a.pPhysicalDeviceCount = a.pPhysicalDevices.length;
        a.ret = a.pPhysicalDevices.length ? VK_SUCCESS : VK_INCOMPLETE;
        if(a.pPhysicalDevices.length)
        {
            ctx.physical_device = a.pPhysicalDevices[0];
            ctx.objects.set(ctx.physical_device, { type: "physical_device" });
        }
    },
    "vkEnumeratePhysicalDeviceGroups": function(vk, ctx, a)
    {
        out_array(a, "pPhysicalDeviceGroupCount", "pPhysicalDeviceGroupProperties", [ctx.physical_device], (group, id) => {
            group.physicalDeviceCount = 1;
            group.physicalDevices = [id];
            group.subsetAllocation = 0;
        });
    },

    // The physical device

    "vkGetPhysicalDeviceProperties": function(vk, ctx, a)
    {
        a.pProperties = INFO.properties();
    },
    "vkGetPhysicalDeviceProperties2": function(vk, ctx, a)
    {
        INFO.properties2(a.pProperties);
    },
    "vkGetPhysicalDeviceFeatures": function(vk, ctx, a)
    {
        a.pFeatures = INFO.features();
    },
    "vkGetPhysicalDeviceFeatures2": function(vk, ctx, a)
    {
        INFO.features2(a.pFeatures);
    },
    "vkEnumerateDeviceExtensionProperties": function(vk, ctx, a)
    {
        if(a.pLayerName) { a.ret = VK_ERROR_LAYER_NOT_PRESENT; return; }
        const names = Object.keys(INFO.DEVICE_EXTENSIONS);
        out_array(a, "pPropertyCount", "pProperties", names, (out, name) => {
            out.extensionName = name;
            out.specVersion = INFO.DEVICE_EXTENSIONS[name];
        });
    },
    "vkEnumerateDeviceLayerProperties": function(vk, ctx, a)
    {
        out_array(a, "pPropertyCount", "pProperties", []);
    },
    "vkGetPhysicalDeviceQueueFamilyProperties": function(vk, ctx, a)
    {
        out_array(a, "pQueueFamilyPropertyCount", "pQueueFamilyProperties", INFO.QUEUE_FAMILIES, (out, family) => Object.assign(out, /** @type {!Object} */ (family)));
    },
    "vkGetPhysicalDeviceQueueFamilyProperties2": function(vk, ctx, a)
    {
        out_array(a, "pQueueFamilyPropertyCount", "pQueueFamilyProperties", INFO.QUEUE_FAMILIES, (out, family) => {
            out.queueFamilyProperties = family;
        });
    },
    "vkGetPhysicalDeviceMemoryProperties": function(vk, ctx, a)
    {
        a.pMemoryProperties = INFO.memory_properties(vk.host_visible_size);
    },
    "vkGetPhysicalDeviceMemoryProperties2": function(vk, ctx, a)
    {
        a.pMemoryProperties.memoryProperties = INFO.memory_properties(vk.host_visible_size);
    },
    "vkGetPhysicalDeviceFormatProperties": function(vk, ctx, a)
    {
        a.pFormatProperties = INFO.format_properties(a.format);
    },
    "vkGetPhysicalDeviceFormatProperties2": function(vk, ctx, a)
    {
        const props = INFO.format_properties(a.format);
        a.pFormatProperties.formatProperties = props;
        for(let s = a.pFormatProperties.pNext; s; s = s.pNext)
        {
            if(s.sType !== INFO.STYPE.DRM_FORMAT_MODIFIER_PROPERTIES_LIST && s.sType !== INFO.STYPE.DRM_FORMAT_MODIFIER_PROPERTIES_LIST_2) continue;
            // (the linear modifier, with optimal tiling's features)
            const modifiers = props.optimalTilingFeatures ? [{ drmFormatModifier: INFO.DRM_FORMAT_MOD_LINEAR, drmFormatModifierPlaneCount: 1,
                drmFormatModifierTilingFeatures: props.optimalTilingFeatures }] : [];
            if(s.pDrmFormatModifierProperties)
            {
                s.drmFormatModifierCount = Math.min(s.drmFormatModifierCount, modifiers.length);
                s.pDrmFormatModifierProperties = modifiers.slice(0, s.drmFormatModifierCount);
            }
            else s.drmFormatModifierCount = modifiers.length;
        }
    },
    "vkGetPhysicalDeviceImageFormatProperties": function(vk, ctx, a)
    {
        const props = INFO.image_format_properties(a.format, a.type, a.tiling, a.usage, a.flags);
        a.pImageFormatProperties = props || {};
        a.ret = props ? VK_SUCCESS : VK_ERROR_FORMAT_NOT_SUPPORTED;
    },
    "vkGetPhysicalDeviceImageFormatProperties2": function(vk, ctx, a)
    {
        const info = a.pImageFormatInfo;
        // (external memory: dma-bufs, imported as their virtio-gpu
        // resources, dedicated; with the linear modifier)
        let handle_type = 0, modifier = INFO.DRM_FORMAT_MOD_LINEAR;
        for(let s = info.pNext; s; s = s.pNext)
        {
            if(s.sType === INFO.STYPE.PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO) handle_type = s.handleType;
            else if(s.sType === INFO.STYPE.PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO) modifier = Number(s.drmFormatModifier);
        }
        if(handle_type && handle_type !== INFO.MEMORY_HANDLE_DMA_BUF || modifier !== INFO.DRM_FORMAT_MOD_LINEAR)
        {
            a.ret = VK_ERROR_FORMAT_NOT_SUPPORTED;
            return;
        }
        const props = INFO.image_format_properties(info.format, info.type, info.tiling, info.usage, info.flags);
        a.pImageFormatProperties.imageFormatProperties = props || {};
        for(let s = a.pImageFormatProperties.pNext; s; s = s.pNext)
        {
            if(s.sType !== INFO.STYPE.EXTERNAL_IMAGE_FORMAT_PROPERTIES) continue;
            s.externalMemoryProperties = handle_type ? { externalMemoryFeatures: INFO.MEMORY_DEDICATED_ONLY | INFO.MEMORY_IMPORTABLE,
                exportFromImportedHandleTypes: 0, compatibleHandleTypes: INFO.MEMORY_HANDLE_DMA_BUF } :
                { externalMemoryFeatures: 0, exportFromImportedHandleTypes: 0, compatibleHandleTypes: 0 };
        }
        a.ret = props ? VK_SUCCESS : VK_ERROR_FORMAT_NOT_SUPPORTED;
    },
    "vkGetPhysicalDeviceSparseImageFormatProperties": function(vk, ctx, a)
    {
        out_array(a, "pPropertyCount", "pProperties", []);
    },
    "vkGetPhysicalDeviceSparseImageFormatProperties2": function(vk, ctx, a)
    {
        out_array(a, "pPropertyCount", "pProperties", []);
    },
    "vkGetPhysicalDeviceExternalBufferProperties": function(vk, ctx, a)
    {
        a.pExternalBufferProperties.externalMemoryProperties = { externalMemoryFeatures: 0, exportFromImportedHandleTypes: 0, compatibleHandleTypes: 0 };
    },
    // sync files of binary semaphores and of fences: exportable and importable
    "vkGetPhysicalDeviceExternalSemaphoreProperties": function(vk, ctx, a)
    {
        const info = a.pExternalSemaphoreInfo;
        let timeline = false;
        for(let s = info.pNext; s; s = s.pNext)
        {
            if(s.sType === INFO.STYPE.SEMAPHORE_TYPE_CREATE_INFO && s.semaphoreType === 1) timeline = true;
        }
        const types = info.handleType === INFO.SEMAPHORE_SYNC_FD && !timeline ? INFO.SEMAPHORE_SYNC_FD : 0;
        Object.assign(a.pExternalSemaphoreProperties, { exportFromImportedHandleTypes: types, compatibleHandleTypes: types,
            externalSemaphoreFeatures: types ? EXTERNAL_EXPORTABLE | EXTERNAL_IMPORTABLE : 0 });
    },
    "vkGetPhysicalDeviceExternalFenceProperties": function(vk, ctx, a)
    {
        const types = a.pExternalFenceInfo.handleType === INFO.FENCE_SYNC_FD ? INFO.FENCE_SYNC_FD : 0;
        Object.assign(a.pExternalFenceProperties, { exportFromImportedHandleTypes: types, compatibleHandleTypes: types,
            externalFenceFeatures: types ? EXTERNAL_EXPORTABLE | EXTERNAL_IMPORTABLE : 0 });
    },
    "vkGetPhysicalDeviceToolProperties": function(vk, ctx, a)
    {
        out_array(a, "pToolCount", "pToolProperties", []);
    },
};

Object.assign(HANDLERS, RESOURCE_HANDLERS, COMMAND_HANDLERS, PIPELINE_HANDLERS);
                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/graphics_adapters/virtio_gpu/venus_vk_commands.js                                    0000644 0000000 0000000 00000127045 00000000000 022415  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Venus device's command buffers, queues and synchronization
// (venus_vk.js runs them). Command buffers record the commands as decoded;
// a submission turns them into one VX batch (BEGIN, the commands, END), sent
// when its timeline waits are met. When the renderer has run it, what it
// wrote into mapped memory is back in the guest's mappings, then its
// semaphores and fence signal. One renderer queue runs everything in order,
// so binary semaphores need no wait.

import { VX } from "../renderer_protocol.js";
import { VK_SUCCESS, VK_NOT_READY, VK_TIMEOUT, VK_EVENT_SET, VK_EVENT_RESET, VK_ERROR_FEATURE_NOT_PRESENT,
    REMAINING, QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM } from "./venus_device_info.js";
import { lo, hi, range_size } from "./venus_vk_resources.js";

const STYPE_SEMAPHORE_TYPE_CREATE_INFO = 1000207002;
const STYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO = 1000207003;
const SEMAPHORE_TYPE_TIMELINE = 1;
const SEMAPHORE_WAIT_ANY = 1;
const FENCE_CREATE_SIGNALED = 1;
const QUERY_RESULT_64 = 1, QUERY_RESULT_WAIT = 2, QUERY_RESULT_WITH_AVAILABILITY = 4;
const QUERY_TYPE_OCCLUSION = 0;

/**
 * The occlusion query pool a render pass uses (WebGPU's passes name theirs
 * when they begin): the first one begun before the pass ends
 * @return {Object} the pool or null
 */
function occlusion_pool(ctx, commands, from)
{
    for(let i = from; i < commands.length; i++)
    {
        const [name, a] = commands[i];
        if(name === "vkCmdEndRenderPass" || name === "vkCmdEndRenderPass2" || name === "vkCmdEndRendering") break;
        if(name === "vkCmdBeginQuery" || name === "vkCmdBeginQueryIndexedEXT")
        {
            const pool = ctx.objects.get(a.queryPool);
            if(pool && pool.query_type === QUERY_TYPE_OCCLUSION) return pool;
        }
        if(name === "vkCmdExecuteCommands")
        {
            for(const id of a.pCommandBuffers || [])
            {
                const secondary = ctx.objects.get(id), pool = secondary && occlusion_pool(ctx, secondary.commands, 0);
                if(pool) return pool;
            }
        }
    }
    return null;
}

/** a timeline value's wait can go to the renderer: it is signaled, or a signal of it went first */
function timeline_ready(semaphore, value)
{
    return semaphore.value >= value || semaphore.submitted >= value;
}

/**
 * Wait until `check` holds or `timeout` (ns, of the machine's time) passes
 * @param {!Object} vk the model
 * @param {function():boolean} check
 * @param {number} timeout
 * @param {function(boolean)} then called with whether it holds
 * @return {?function(function())}
 */
function wait_until(vk, check, timeout, then)
{
    if(check()) { then(true); return null; }
    if(!timeout) { then(false); return null; }
    return done => vk.add_waiter(check, timeout, ok => { then(ok); done(); });
}

/** @type {!Object<string, function(!Object, !Object, !Object): ?function(function())>} */
export const COMMAND_HANDLERS = {
    // Command pools and buffers

    "vkCreateCommandPool": function(vk, ctx, a)
    {
        ctx.objects.set(a.pCommandPool, { type: "command_pool", buffers: new Set() });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyCommandPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.commandPool);
        if(pool) for(const id of pool.buffers) ctx.objects.delete(id);
        ctx.objects.delete(a.commandPool);
        return null;
    },
    "vkResetCommandPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.commandPool);
        if(pool) for(const id of pool.buffers) { const cb = ctx.objects.get(id); if(cb) cb.commands = []; }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkTrimCommandPool": function(vk, ctx, a) { return null; },
    "vkAllocateCommandBuffers": function(vk, ctx, a)
    {
        const info = a.pAllocateInfo;
        const pool = ctx.objects.get(info.commandPool);
        for(const id of a.pCommandBuffers || [])
        {
            ctx.objects.set(id, { type: "command_buffer", pool: info.commandPool, level: info.level, commands: [] });
            if(pool) pool.buffers.add(id);
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkFreeCommandBuffers": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.commandPool);
        for(const id of a.pCommandBuffers || [])
        {
            ctx.objects.delete(id);
            if(pool) pool.buffers.delete(id);
        }
        return null;
    },
    "vkBeginCommandBuffer": function(vk, ctx, a)
    {
        const cb = ctx.objects.get(a.commandBuffer);
        if(cb) { cb.commands = []; cb.begin = a.pBeginInfo; }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkEndCommandBuffer": function(vk, ctx, a) { a.ret = VK_SUCCESS; return null; },
    "vkResetCommandBuffer": function(vk, ctx, a)
    {
        const cb = ctx.objects.get(a.commandBuffer);
        if(cb) cb.commands = [];
        a.ret = VK_SUCCESS;
        return null;
    },

    // Queues

    "vkQueueSubmit": function(vk, ctx, a)
    {
        const submits = (a.pSubmits || []).map(s => {
            let wait_values = null, signal_values = null;
            for(let n = s.pNext; n; n = n.pNext)
            {
                if(n.sType === STYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO) { wait_values = n.pWaitSemaphoreValues; signal_values = n.pSignalSemaphoreValues; }
            }
            return {
                waits: (s.pWaitSemaphores || []).map((id, i) => [id, wait_values ? wait_values[i] : 0]),
                command_buffers: s.pCommandBuffers || [],
                signals: (s.pSignalSemaphores || []).map((id, i) => [id, signal_values ? signal_values[i] : 0]),
            };
        });
        vk.submit(ctx, a.queue, submits, a.fence);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkQueueSubmit2": function(vk, ctx, a)
    {
        const submits = (a.pSubmits || []).map(s => ({
            waits: (s.pWaitSemaphoreInfos || []).map(w => [w.semaphore, w.value]),
            command_buffers: (s.pCommandBufferInfos || []).map(c => c.commandBuffer),
            signals: (s.pSignalSemaphoreInfos || []).map(w => [w.semaphore, w.value]),
        }));
        vk.submit(ctx, a.queue, submits, a.fence);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkQueueBindSparse": function(vk, ctx, a)
    {
        a.ret = VK_ERROR_FEATURE_NOT_PRESENT;
        return null;
    },
    "vkQueueWaitIdle": function(vk, ctx, a)
    {
        const queue = ctx.objects.get(a.queue);
        return wait_until(vk, () => !queue || !queue.pending.length && !queue.inflight, Infinity, () => { a.ret = VK_SUCCESS; });
    },
    "vkDeviceWaitIdle": function(vk, ctx, a)
    {
        const queues = [...ctx.objects.values()].filter(o => o.type === "queue" && o.device === a.device);
        return wait_until(vk, () => queues.every(q => !q.pending.length && !q.inflight), Infinity, () => { a.ret = VK_SUCCESS; });
    },

    // Fences

    "vkCreateFence": function(vk, ctx, a)
    {
        ctx.objects.set(a.pFence, { type: "fence", signaled: !!(a.pCreateInfo.flags & FENCE_CREATE_SIGNALED), pending: 0, generation: 0 });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyFence": function(vk, ctx, a) { ctx.objects.delete(a.fence); return null; },
    "vkResetFences": function(vk, ctx, a)
    {
        for(const id of a.pFences || []) { const fence = ctx.objects.get(id); if(fence) fence.signaled = false; }
        a.ret = VK_SUCCESS;
        return null;
    },
    // vkGetFenceFdKHR: the driver made the sync file (its signal pending or
    // done); the fence is unsignaled, as an export of a sync file leaves it,
    // and its pending signal is the sync file's now
    "vkResetFenceResourceMESA": function(vk, ctx, a)
    {
        const fence = ctx.objects.get(a.fence);
        if(fence) { fence.signaled = false; fence.pending = 0; fence.generation++; }
        return null;
    },
    "vkGetFenceStatus": function(vk, ctx, a)
    {
        const fence = ctx.objects.get(a.fence);
        a.ret = !fence || fence.signaled ? VK_SUCCESS : VK_NOT_READY;
        return null;
    },
    "vkWaitForFences": function(vk, ctx, a)
    {
        const fences = (a.pFences || []).map(id => ctx.objects.get(id)).filter(f => f);
        const check = () => a.waitAll ? fences.every(f => f.signaled) : fences.some(f => f.signaled);
        return wait_until(vk, check, a.timeout, ok => { a.ret = ok ? VK_SUCCESS : VK_TIMEOUT; });
    },

    // Semaphores

    "vkCreateSemaphore": function(vk, ctx, a)
    {
        let timeline = false, value = 0;
        for(let s = a.pCreateInfo.pNext; s; s = s.pNext)
        {
            if(s.sType === STYPE_SEMAPHORE_TYPE_CREATE_INFO) { timeline = s.semaphoreType === SEMAPHORE_TYPE_TIMELINE; value = s.initialValue; }
        }
        ctx.objects.set(a.pSemaphore, { type: "semaphore", timeline, value, submitted: value, signaled: false, generation: 0 });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroySemaphore": function(vk, ctx, a) { ctx.objects.delete(a.semaphore); return null; },
    "vkGetSemaphoreCounterValue": function(vk, ctx, a)
    {
        const semaphore = ctx.objects.get(a.semaphore);
        a.pValue = semaphore ? semaphore.value : 0;
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkSignalSemaphore": function(vk, ctx, a)
    {
        const semaphore = ctx.objects.get(a.pSignalInfo.semaphore);
        if(semaphore)
        {
            semaphore.value = Math.max(semaphore.value, a.pSignalInfo.value);
            semaphore.submitted = Math.max(semaphore.submitted, semaphore.value);
            vk.wake();
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkWaitSemaphores": function(vk, ctx, a)
    {
        const info = a.pWaitInfo;
        const pairs = (info.pSemaphores || []).map((id, i) => [ctx.objects.get(id), info.pValues[i]]).filter(p => p[0]);
        const reached = ([semaphore, value]) => semaphore.value >= value;
        const check = () => info.flags & SEMAPHORE_WAIT_ANY ? pairs.some(reached) : pairs.every(reached);
        return wait_until(vk, check, a.timeout, ok => { a.ret = ok ? VK_SUCCESS : VK_TIMEOUT; });
    },
    // vkGetSemaphoreFdKHR: the sync file took the semaphore's payload (a
    // wait, as the export of a sync file is)
    "vkWaitSemaphoreResourceMESA": function(vk, ctx, a)
    {
        const semaphore = ctx.objects.get(a.semaphore);
        if(semaphore && !semaphore.timeline) { semaphore.signaled = false; semaphore.generation++; }
        return null;
    },
    // a sync file the driver waited for (resource 0): signaled
    "vkImportSemaphoreResourceMESA": function(vk, ctx, a)
    {
        const info = a.pImportSemaphoreResourceInfo, semaphore = info && ctx.objects.get(info.semaphore);
        if(semaphore && !semaphore.timeline) semaphore.signaled = true;
        return null;
    },

    // Events

    "vkCreateEvent": function(vk, ctx, a)
    {
        ctx.objects.set(a.pEvent, { type: "event", set: false });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyEvent": function(vk, ctx, a) { ctx.objects.delete(a.event); return null; },
    "vkGetEventStatus": function(vk, ctx, a)
    {
        const event = ctx.objects.get(a.event);
        a.ret = event && event.set ? VK_EVENT_SET : VK_EVENT_RESET;
        return null;
    },
    "vkSetEvent": function(vk, ctx, a)
    {
        const event = ctx.objects.get(a.event);
        if(event) event.set = true;
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkResetEvent": function(vk, ctx, a)
    {
        const event = ctx.objects.get(a.event);
        if(event) event.set = false;
        a.ret = VK_SUCCESS;
        return null;
    },

    // Queries

    // a pool's results (u64 each) are a VX memory: occlusion queries resolve
    // into it, timestamps are written into it; read back after a submission
    // that touches them, before its fence
    "vkCreateQueryPool": function(vk, ctx, a)
    {
        const info = a.pCreateInfo, count = info.queryCount;
        // (transform feedback's: two values a query, the primitives written and needed)
        const values = info.queryType === QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM ? 2 : 1;
        const pool = { type: "query_pool", query_type: info.queryType, count, values, rid: vk.new_rid(),
            memory: { rid: vk.new_rid(), size: count * 8 * values }, results: new Float64Array(count * values), available: new Uint8Array(count) };
        vk.vx.command(VX.MEMORY_CREATE, [pool.memory.rid, count * 8 * values, 0]);
        vk.vx.command(VX.QUERY_POOL_CREATE, [pool.rid, info.queryType, count]);
        ctx.objects.set(a.pQueryPool, pool);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyQueryPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.queryPool);
        if(pool && pool.type === "query_pool")
        {
            vk.vx.command(VX.DESTROY, [pool.rid]);
            vk.vx.command(VX.DESTROY, [pool.memory.rid]);
        }
        ctx.objects.delete(a.queryPool);
        return null;
    },
    "vkResetQueryPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.queryPool);
        if(pool) pool.available.fill(0, a.firstQuery, a.firstQuery + a.queryCount);
        return null;
    },
    "vkGetQueryPoolResults": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.queryPool);
        const answer = () => {
            const out = new Uint8Array(a.dataSize), view = new DataView(out.buffer);
            let all = true;
            for(let i = 0; i < a.queryCount; i++)
            {
                const q = a.firstQuery + i, at = i * a.stride, available = pool && pool.available[q];
                if(!available) all = false;
                const values = pool ? pool.values : 1, width = a.flags & QUERY_RESULT_64 ? 8 : 4;
                const write = (offset, v) => {
                    if(a.flags & QUERY_RESULT_64)
                    {
                        if(offset + 8 > out.length) return;
                        view.setUint32(offset, lo(v), true);
                        view.setUint32(offset + 4, hi(v), true);
                    }
                    else if(offset + 4 <= out.length) view.setUint32(offset, Math.min(v, 0xFFFFFFFF), true);
                };
                if(available) for(let k = 0; k < values; k++) write(at + k * width, pool.results[q * values + k]);
                if(a.flags & QUERY_RESULT_WITH_AVAILABILITY) write(at + values * width, available ? 1 : 0);
            }
            a.pData = out;
            a.ret = all ? VK_SUCCESS : VK_NOT_READY;
        };
        if(!(a.flags & QUERY_RESULT_WAIT) || !pool) { answer(); return null; }
        const available = () => pool.available.subarray(a.firstQuery, a.firstQuery + a.queryCount).every(x => x);
        return wait_until(vk, available, Infinity, () => answer());
    },
};

// ---------------------------------------------------------------------------
// Commands into VX

/**
 * A buffer's memory and where in it
 * @return {Array} [memory, offset] or null when it has none
 */
function at(ctx, id, offset)
{
    const buffer = ctx.objects.get(id);
    if(!buffer || !buffer.memory) return null;
    return [buffer.memory, buffer.offset + offset, buffer];
}

const f32_bits = v => new Uint32Array(new Float32Array([v]).buffer)[0];
// VkDescriptorType
const UNIFORM_BUFFER = 6, STORAGE_BUFFER = 7, UNIFORM_BUFFER_DYNAMIC = 8, STORAGE_BUFFER_DYNAMIC = 9;
const STORAGE_IMAGE = 3;

/** A command buffer's state as its commands are translated */
export function command_state()
{
    return {
        // the render pass: { pass, framebuffer, subpass, clears, used: Set of attachments }
        pass: null,
        // the bound descriptor sets, by bind point: group -> [set, dynamic offsets]
        sets: [new Map(), new Map()],
        // the transform feedback buffers: [memory, offset, size] by binding
        xfb: [],
    };
}

/**
 * BEGIN_PASS of a subpass: its attachments, their loads (the first use of
 * an attachment in the render pass loads as the render pass says, later
 * ones keep what is there) and clear values
 */
// VkRenderingFlagBits
const RENDERING_RESUMING = 4;
// VkAttachmentLoadOp, VkAttachmentStoreOp
const LOAD_OP_LOAD = 0, STORE_OP_STORE = 0;

/**
 * vkCmdBeginRendering: a render pass of the views it names (as begin_subpass's)
 * @param {!Object} vk
 * @param {!Object} ctx
 * @param {!Object} info VkRenderingInfo
 * @param {!Object} p the pass's state
 */
function begin_rendering(vk, ctx, info, p)
{
    // (Venus encodes each VkClearValue as a color: a depth clear is its bits)
    const bits = c => c && c.color ? Array.from(c.color.uint32 || c.color.int32 || [0, 0, 0, 0], x => x >>> 0) : [0, 0, 0, 0];
    const resuming = info.flags & RENDERING_RESUMING;
    let size = null;
    const view = id => {
        const v = id ? ctx.objects.get(id) : null;
        if(v && !size) size = v;
        return v;
    };
    const colors = (info.pColorAttachments || []).map(c => {
        const v = view(c.imageView);
        if(!v) return null;
        const resolve = c.resolveMode && c.resolveImageView ? (ctx.objects.get(c.resolveImageView) || { rid: 0 }).rid : 0;
        return { view: v.rid, load: resuming ? LOAD_OP_LOAD : c.loadOp, store: c.storeOp, clear: bits(c.clearValue), resolve, format: v.format };
    });
    let depth = null;
    const d = info.pDepthAttachment && view(info.pDepthAttachment.imageView) ? info.pDepthAttachment : null;
    const st = info.pStencilAttachment && view(info.pStencilAttachment.imageView) ? info.pStencilAttachment : null;
    if(d || st)
    {
        const v = ctx.objects.get((d || st).imageView);
        // (the depth and stencil resolved, sample zero, into the resolve views)
        const resolve_of = a => a && a.resolveMode && a.resolveImageView ? (ctx.objects.get(a.resolveImageView) || { rid: 0 }).rid : 0;
        const resolve = resolve_of(d) || resolve_of(st);
        depth = { view: v.rid, load: d && !resuming ? d.loadOp : LOAD_OP_LOAD, store: d ? d.storeOp : STORE_OP_STORE,
            stencil_load: st && !resuming ? st.loadOp : LOAD_OP_LOAD, stencil_store: st ? st.storeOp : STORE_OP_STORE,
            clear_depth: d ? new Float32Array(new Uint32Array([bits(d.clearValue)[0]]).buffer)[0] : 1,
            clear_stencil: st ? bits(st.clearValue)[1] : 0, format: v.format,
            resolve, resolve_depth: !!resolve_of(d), resolve_stencil: !!resolve_of(st) };
    }
    const area = info.renderArea;
    const width = size ? size.width : area.offset.x + area.extent.width, height = size ? size.height : area.offset.y + area.extent.height;
    const occlusion = p.occlusion ? p.occlusion.rid : 0;
    vk.vx.command(VX.BEGIN_PASS, [], new TextEncoder().encode(JSON.stringify({ colors, depth, width, height, occlusion })));
}

function begin_subpass(vk, ctx, p)
{
    const sub = p.pass.subpasses[p.subpass];
    if(!sub) return;
    const fb = p.framebuffer;
    const view = i => { const v = ctx.objects.get(fb.attachments[i]); return v ? v.rid : 0; };
    const clear = i => {
        const c = p.clears[i];
        const bits = c && c.color ? Array.from(c.color.uint32 || c.color.int32 || [0, 0, 0, 0], x => x >>> 0) : [0, 0, 0, 0];
        return bits;
    };
    const load = (i, op) => p.used.has(i) ? 0 : op;
    const colors = sub.colors.map((r, k) => {
        if(!r || r.attachment === REMAINING) return null;
        const a = p.pass.attachments[r.attachment];
        const resolve = sub.resolves && sub.resolves[k] && sub.resolves[k].attachment !== REMAINING ? view(sub.resolves[k].attachment) : 0;
        return { view: view(r.attachment), load: load(r.attachment, a.load), store: a.store, clear: clear(r.attachment), resolve, format: a.format };
    });
    let depth = null;
    if(sub.depth && sub.depth.attachment !== REMAINING)
    {
        const i = sub.depth.attachment, a = p.pass.attachments[i];
        const bits = clear(i);
        const r = sub.depth_resolve && sub.depth_resolve.attachment !== REMAINING ? sub.depth_resolve : null;
        depth = { view: view(i), load: load(i, a.load), store: a.store, stencil_load: load(i, a.stencil_load), stencil_store: a.stencil_store,
            clear_depth: new Float32Array(new Uint32Array([bits[0]]).buffer)[0], clear_stencil: bits[1], format: a.format,
            resolve: r ? view(r.attachment) : 0, resolve_depth: !!(r && r.depth), resolve_stencil: !!(r && r.stencil) };
    }
    for(const r of sub.colors.concat([sub.depth], sub.resolves || [])) if(r && r.attachment !== REMAINING) p.used.add(r.attachment);
    const occlusion = p.occlusion ? p.occlusion.rid : 0;
    vk.vx.command(VX.BEGIN_PASS, [], new TextEncoder().encode(JSON.stringify({ colors, depth, width: fb.width, height: fb.height, occlusion })));
}

/**
 * SET_BIND_GROUP of a descriptor set: its descriptors resolved to the
 * renderer's objects; dynamic offsets from `dynamic` in binding order.
 * Storage buffers the shaders may write are noted by `write`.
 */
function bind_set(vk, ctx, bind_point, group, set, dynamic, storage)
{
    const words = [];
    const keys = [...set.descriptors.keys()].sort((p, q) => p - q);
    let d_index = 0;
    for(const key of keys)
    {
        const d = set.descriptors.get(key);
        const binding = Math.floor(key / 1024), element = key % 1024;
        let rid = 0, sampler = 0, offset = 0, size = 0;
        if(d.type === UNIFORM_BUFFER || d.type === STORAGE_BUFFER || d.type === UNIFORM_BUFFER_DYNAMIC || d.type === STORAGE_BUFFER_DYNAMIC)
        {
            const buffer = ctx.objects.get(d.buffer);
            if(!buffer || !buffer.memory) continue;
            const extra = d.type === UNIFORM_BUFFER_DYNAMIC || d.type === STORAGE_BUFFER_DYNAMIC ? dynamic[d_index++] || 0 : 0;
            rid = buffer.memory.rid;
            offset = buffer.offset + d.offset + extra;
            size = range_size(buffer, d.offset, d.range);
            if(d.type === STORAGE_BUFFER || d.type === STORAGE_BUFFER_DYNAMIC) storage.push([buffer.memory, offset, size]);
        }
        else
        {
            const view = d.view ? ctx.objects.get(d.view) : null, s = d.sampler ? ctx.objects.get(d.sampler) : null;
            rid = view ? view.rid : 0;
            sampler = s ? s.rid : 0;
        }
        words.push(binding, element, d.type, rid, sampler, lo(offset), hi(offset), size >>> 0);
    }
    vk.vx.command(VX.SET_BIND_GROUP, [group | bind_point << 16, words.length / 8, ...words]);
}

/**
 * A submission's command buffers, written into the VX batch
 * @param {!Object} vk the model
 * @param {!Object} ctx
 * @param {!Array} commands [name, parameters] of a command buffer
 * @param {!Object} state { written: Set of memory the GPU writes, after: run on completion }
 */
export function translate(vk, ctx, commands, state)
{
    const vx = vk.vx;
    const image = id => ctx.objects.get(id);
    /** the GPU writes [offset, offset + size) of the memory */
    const write = (memory, offset, size) => {
        let ranges = state.written.get(memory);
        if(!ranges) state.written.set(memory, ranges = []);
        ranges.push([offset, offset + size]);
    };
    const cb = state.cb || (state.cb = command_state());
    /** before a draw or dispatch: the storage buffers of the bound sets are the GPU's to write */
    const storage_writes = bind_point => {
        for(const [, [set, dynamic]] of cb.sets[bind_point])
        {
            const storage = [];
            for(const d of set.descriptors.values())
            {
                if(d.type !== STORAGE_BUFFER && d.type !== STORAGE_BUFFER_DYNAMIC) continue;
                const buffer = ctx.objects.get(d.buffer);
                if(buffer && buffer.memory) write(buffer.memory, buffer.offset + d.offset, range_size(buffer, d.offset, d.range));
            }
        }
    };
    /** a query the submission touches: its result comes back before the fence */
    const touch = (pool, query) => {
        let set = state.queries.get(pool);
        if(!set) state.queries.set(pool, set = new Set());
        set.add(query);
    };
    for(let index = 0; index < commands.length; index++)
    {
        const [name, a] = commands[index];
        switch(name)
        {
            // Render passes
            case "vkCmdBeginRenderPass":
            case "vkCmdBeginRenderPass2":
            {
                const info = a.pRenderPassBegin;
                const pass = ctx.objects.get(info.renderPass), framebuffer = ctx.objects.get(info.framebuffer);
                if(!pass || !framebuffer) break;
                cb.pass = { pass, framebuffer, subpass: 0, clears: info.pClearValues || [], used: new Set(),
                    occlusion: occlusion_pool(ctx, commands, index + 1) };
                begin_subpass(vk, ctx, cb.pass);
                break;
            }
            case "vkCmdNextSubpass":
            case "vkCmdNextSubpass2":
                if(!cb.pass) break;
                vx.command(VX.END_PASS, []);
                cb.pass.subpass++;
                begin_subpass(vk, ctx, cb.pass);
                break;
            case "vkCmdEndRenderPass":
            case "vkCmdEndRenderPass2":
                if(!cb.pass) break;
                vx.command(VX.END_PASS, []);
                cb.pass = null;
                break;
            // Dynamic rendering (VK_KHR_dynamic_rendering)
            case "vkCmdBeginRendering":
            {
                const info = a.pRenderingInfo;
                if(!info) break;
                cb.pass = { dynamic: true, occlusion: occlusion_pool(ctx, commands, index + 1) };
                begin_rendering(vk, ctx, info, cb.pass);
                break;
            }
            case "vkCmdEndRendering":
                if(!cb.pass) break;
                vx.command(VX.END_PASS, []);
                cb.pass = null;
                break;
            case "vkCmdClearAttachments":
            {
                const attachments = (a.pAttachments || []).map(c => ({ aspect: c.aspectMask, index: c.colorAttachment,
                    clear: Array.from(c.clearValue.color.uint32 || c.clearValue.color.int32 || [0, 0, 0, 0], x => x >>> 0) }));
                const rects = (a.pRects || []).map(r => ({ x: r.rect.offset.x, y: r.rect.offset.y, width: r.rect.extent.width, height: r.rect.extent.height }));
                vx.command(VX.CLEAR_ATTACHMENTS, [], new TextEncoder().encode(JSON.stringify({ attachments, rects })));
                break;
            }

            // State
            case "vkCmdBindPipeline":
            {
                const pipeline = ctx.objects.get(a.pipeline);
                if(pipeline) vx.command(VX.BIND_PIPELINE, [pipeline.rid]);
                break;
            }
            case "vkCmdBindDescriptorSets":
            {
                const point = a.pipelineBindPoint === 1 ? 1 : 0;
                let dynamic = Array.from(a.pDynamicOffsets || []);
                (a.pDescriptorSets || []).forEach((id, k) => {
                    const set = ctx.objects.get(id);
                    if(!set) return;
                    const count = [...set.descriptors.values()].filter(d => d.type === UNIFORM_BUFFER_DYNAMIC || d.type === STORAGE_BUFFER_DYNAMIC).length;
                    const mine = dynamic.slice(0, count);
                    dynamic = dynamic.slice(count);
                    cb.sets[point].set(a.firstSet + k, [set, mine]);
                    bind_set(vk, ctx, point, a.firstSet + k, set, mine, []);
                });
                break;
            }
            case "vkCmdBindVertexBuffers":
                (a.pBuffers || []).forEach((id, i) => {
                    const place = at(ctx, id, a.pOffsets[i]);
                    if(!place) return;
                    const size = place[2].size - a.pOffsets[i];
                    vx.command(VX.SET_VERTEX_BUFFER, [a.firstBinding + i, place[0].rid, lo(place[1]), hi(place[1]), lo(size), hi(size)]);
                });
                break;
            case "vkCmdBindIndexBuffer":
            {
                const place = at(ctx, a.buffer, a.offset);
                if(!place) break;
                const size = place[2].size - a.offset;
                vx.command(VX.SET_INDEX_BUFFER, [place[0].rid, lo(place[1]), hi(place[1]), lo(size), hi(size), a.indexType]);
                break;
            }
            case "vkCmdPushConstants":
                if(a.pValues) vx.command(VX.SET_PUSH_CONSTANTS, [a.offset, a.size], a.pValues);
                break;
            case "vkCmdSetViewport":
            {
                const v = (a.pViewports || [])[0];
                if(v) vx.command(VX.SET_VIEWPORT, [v.x, v.y, v.width, v.height, v.minDepth, v.maxDepth].map(f32_bits));
                break;
            }
            case "vkCmdSetScissor":
            {
                const r = (a.pScissors || [])[0];
                if(r) vx.command(VX.SET_SCISSOR, [r.offset.x >>> 0, r.offset.y >>> 0, r.extent.width, r.extent.height]);
                break;
            }
            case "vkCmdSetBlendConstants":
                vx.command(VX.SET_BLEND_CONSTANTS, Array.from(a.blendConstants, f32_bits));
                break;
            case "vkCmdSetStencilReference":
                vx.command(VX.SET_STENCIL_REFERENCE, [a.faceMask, a.reference]);
                break;
            case "vkCmdSetStencilCompareMask":
                vx.command(VX.SET_STENCIL_COMPARE_MASK, [a.faceMask, a.compareMask]);
                break;
            case "vkCmdSetStencilWriteMask":
                vx.command(VX.SET_STENCIL_WRITE_MASK, [a.faceMask, a.writeMask]);
                break;
            case "vkCmdSetDepthBias":
                vx.command(VX.SET_DEPTH_BIAS, [a.depthBiasConstantFactor, a.depthBiasClamp, a.depthBiasSlopeFactor].map(f32_bits));
                break;
            case "vkCmdSetLineWidth":
            case "vkCmdSetDepthBounds":
                vk.warn_once(name, name + " is kept from the pipeline (WebGPU's is static)");
                break;

            // Draws and dispatches
            case "vkCmdDraw":
                storage_writes(0);
                vx.command(VX.DRAW, [a.vertexCount, a.instanceCount, a.firstVertex, a.firstInstance]);
                break;
            case "vkCmdDrawIndexed":
                storage_writes(0);
                vx.command(VX.DRAW_INDEXED, [a.indexCount, a.instanceCount, a.firstIndex, a.vertexOffset >>> 0, a.firstInstance]);
                break;
            case "vkCmdDrawIndirect":
            case "vkCmdDrawIndexedIndirect":
            {
                const place = at(ctx, a.buffer, a.offset);
                if(!place) break;
                storage_writes(0);
                vx.command(VX.DRAW_INDIRECT, [place[0].rid, lo(place[1]), hi(place[1]), a.drawCount, a.stride, name === "vkCmdDrawIndexedIndirect" ? 1 : 0]);
                break;
            }
            case "vkCmdDispatch":
                storage_writes(1);
                vx.command(VX.DISPATCH, [a.groupCountX, a.groupCountY, a.groupCountZ]);
                break;
            case "vkCmdDispatchIndirect":
            {
                const place = at(ctx, a.buffer, a.offset);
                if(!place) break;
                storage_writes(1);
                vx.command(VX.DISPATCH_INDIRECT, [place[0].rid, lo(place[1]), hi(place[1])]);
                break;
            }

            case "vkCmdCopyBuffer":
            case "vkCmdCopyBuffer2":
            {
                const info = name === "vkCmdCopyBuffer2" ? a.pCopyBufferInfo : a;
                for(const region of info.pRegions || [])
                {
                    const src = at(ctx, info.srcBuffer, region.srcOffset), dst = at(ctx, info.dstBuffer, region.dstOffset);
                    if(!src || !dst || !region.size) continue;
                    vx.command(VX.COPY_BUFFER, [src[0].rid, lo(src[1]), hi(src[1]), dst[0].rid, lo(dst[1]), hi(dst[1]), lo(region.size), hi(region.size)]);
                    write(dst[0], dst[1], region.size);
                }
                break;
            }
            case "vkCmdFillBuffer":
            {
                const dst = at(ctx, a.dstBuffer, a.dstOffset);
                if(!dst) break;
                const size = range_size(dst[2], a.dstOffset, a.size) & ~3;
                if(size <= 0) break;
                vx.command(VX.FILL_BUFFER, [dst[0].rid, lo(dst[1]), hi(dst[1]), lo(size), hi(size), a.data]);
                write(dst[0], dst[1], size);
                break;
            }
            case "vkCmdUpdateBuffer":
            {
                const dst = at(ctx, a.dstBuffer, a.dstOffset);
                if(!dst || !a.pData) break;
                vx.command(VX.UPDATE_BUFFER, [dst[0].rid, lo(dst[1]), hi(dst[1]), a.dataSize], a.pData);
                write(dst[0], dst[1], a.dataSize);
                break;
            }
            case "vkCmdCopyBufferToImage":
            case "vkCmdCopyBufferToImage2":
            case "vkCmdCopyImageToBuffer":
            case "vkCmdCopyImageToBuffer2":
            {
                const to_image = name.startsWith("vkCmdCopyBufferToImage");
                const info = name.endsWith("2") ? (to_image ? a.pCopyBufferToImageInfo : a.pCopyImageToBufferInfo) : a;
                const buffer = to_image ? info.srcBuffer : info.dstBuffer;
                const img = image(to_image ? info.dstImage : info.srcImage);
                if(!img) break;
                for(const region of info.pRegions || [])
                {
                    const place = at(ctx, buffer, region.bufferOffset);
                    if(!place) continue;
                    const s = region.imageSubresource, o = region.imageOffset, e = region.imageExtent;
                    const layers = s.layerCount === REMAINING ? img.layers - s.baseArrayLayer : s.layerCount;
                    vx.command(VX.COPY_BUFFER_IMAGE, [to_image ? 1 : 0, place[0].rid, lo(place[1]), hi(place[1]),
                        region.bufferRowLength, region.bufferImageHeight, img.rid, s.aspectMask, s.mipLevel, s.baseArrayLayer, layers,
                        o.x, o.y, o.z, e.width, e.height, e.depth]);
                    if(!to_image)
                    {
                        // rows of the region (texels of the format's size; whole rows: a little more is no harm)
                        const texel = s.aspectMask === 4 ? 1 : s.aspectMask === 2 && img.format === 124 ? 2 : s.aspectMask === 2 ? 4 : img.texel_bytes;
                        const pitch = (region.bufferRowLength || e.width) * texel, rows = region.bufferImageHeight || e.height;
                        write(place[0], place[1], pitch * rows * Math.max(layers, e.depth));
                    }
                }
                break;
            }
            case "vkCmdCopyImage":
            case "vkCmdCopyImage2":
            {
                const info = name === "vkCmdCopyImage2" ? a.pCopyImageInfo : a;
                const src = image(info.srcImage), dst = image(info.dstImage);
                if(!src || !dst) break;
                for(const r of info.pRegions || [])
                {
                    const s = r.srcSubresource, d = r.dstSubresource;
                    const layers = s.layerCount === REMAINING ? src.layers - s.baseArrayLayer : s.layerCount;
                    vx.command(VX.COPY_IMAGE, [src.rid, s.aspectMask, s.mipLevel, s.baseArrayLayer, r.srcOffset.x, r.srcOffset.y, r.srcOffset.z,
                        dst.rid, d.aspectMask, d.mipLevel, d.baseArrayLayer, r.dstOffset.x, r.dstOffset.y, r.dstOffset.z,
                        r.extent.width, r.extent.height, r.extent.depth, layers]);
                }
                break;
            }
            case "vkCmdBlitImage":
            case "vkCmdBlitImage2":
            {
                const info = name === "vkCmdBlitImage2" ? a.pBlitImageInfo : a;
                const src = image(info.srcImage), dst = image(info.dstImage);
                if(!src || !dst) break;
                for(const r of info.pRegions || [])
                {
                    const s = r.srcSubresource, d = r.dstSubresource, so = r.srcOffsets, dof = r.dstOffsets;
                    const layers = s.layerCount === REMAINING ? src.layers - s.baseArrayLayer : s.layerCount;
                    vx.command(VX.BLIT_IMAGE, [src.rid, s.mipLevel, s.baseArrayLayer, so[0].x, so[0].y, so[0].z, so[1].x, so[1].y, so[1].z,
                        dst.rid, d.mipLevel, d.baseArrayLayer, dof[0].x, dof[0].y, dof[0].z, dof[1].x, dof[1].y, dof[1].z,
                        layers, info.filter === 1 ? 1 : 0]);
                }
                break;
            }
            case "vkCmdClearColorImage":
            case "vkCmdClearDepthStencilImage":
            {
                const img = image(a.image);
                if(!img) break;
                const color = name === "vkCmdClearColorImage";
                let values;
                if(color) values = Array.from(a.pColor.uint32 || a.pColor.int32 || [0, 0, 0, 0], v => v >>> 0);
                else
                {
                    const f = new Float32Array([a.pDepthStencil.depth]);
                    values = [new Uint32Array(f.buffer)[0], a.pDepthStencil.stencil, 0, 0];
                }
                for(const r of a.pRanges || [])
                {
                    const mips = r.levelCount === REMAINING ? img.mips - r.baseMipLevel : r.levelCount;
                    const layers = r.layerCount === REMAINING ? img.layers - r.baseArrayLayer : r.layerCount;
                    vx.command(VX.CLEAR_IMAGE, [img.rid, r.aspectMask, r.baseMipLevel, mips, r.baseArrayLayer, layers, ...values]);
                }
                break;
            }
            case "vkCmdResolveImage":
            case "vkCmdResolveImage2":
            {
                const info = name === "vkCmdResolveImage2" ? a.pResolveImageInfo : a;
                const src = image(info.srcImage), dst = image(info.dstImage);
                if(!src || !dst) break;
                for(const r of info.pRegions || [])
                {
                    const s = r.srcSubresource, d = r.dstSubresource;
                    vx.command(VX.RESOLVE_IMAGE, [src.rid, s.mipLevel, s.baseArrayLayer, r.srcOffset.x, r.srcOffset.y,
                        dst.rid, d.mipLevel, d.baseArrayLayer, r.dstOffset.x, r.dstOffset.y, r.extent.width, r.extent.height,
                        s.layerCount === REMAINING ? src.layers - s.baseArrayLayer : s.layerCount]);
                }
                break;
            }
            case "vkCmdExecuteCommands":
                for(const id of a.pCommandBuffers || [])
                {
                    const secondary = ctx.objects.get(id);
                    if(secondary) translate(vk, ctx, secondary.commands, state);
                }
                break;
            case "vkCmdSetEvent":
            case "vkCmdSetEvent2":
            case "vkCmdResetEvent":
            case "vkCmdResetEvent2":
            {
                const event = ctx.objects.get(a.event), set = name.startsWith("vkCmdSet");
                if(event) state.after.push(() => { event.set = set; });
                break;
            }
            case "vkCmdResetQueryPool":
            {
                const pool = ctx.objects.get(a.queryPool);
                if(pool) pool.available.fill(0, a.firstQuery, a.firstQuery + a.queryCount);
                break;
            }
            case "vkCmdBeginQuery":
            case "vkCmdBeginQueryIndexedEXT":
            {
                const pool = ctx.objects.get(a.queryPool);
                if(!pool) break;
                if(pool.query_type === QUERY_TYPE_OCCLUSION)
                {
                    if(cb.pass && cb.pass.occlusion === pool) vx.command(VX.BEGIN_QUERY, [pool.rid, a.query]);
                    else vk.warn_once("query-outside", "an occlusion query outside of a render pass is 0");
                }
                // (transform feedback's: VX counts the primitives of the draws that capture)
                else if(pool.query_type === QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM) vx.command(VX.BEGIN_QUERY, [pool.rid, a.query]);
                touch(pool, a.query);
                break;
            }
            case "vkCmdEndQuery":
            case "vkCmdEndQueryIndexedEXT":
            {
                const pool = ctx.objects.get(a.queryPool);
                if(pool && pool.query_type === QUERY_TYPE_OCCLUSION && cb.pass && cb.pass.occlusion === pool)
                    vx.command(VX.END_QUERY, [pool.rid, a.query, pool.memory.rid]);
                if(pool && pool.query_type === QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM) vx.command(VX.END_QUERY, [pool.rid, a.query, pool.memory.rid]);
                break;
            }
            // Transform feedback (VK_EXT_transform_feedback): the bytes a
            // capture writes are the GPU's (read back where mapped), and so
            // are the counters End writes
            case "vkCmdBindTransformFeedbackBuffersEXT":
            {
                for(let i = 0; i < a.bindingCount; i++)
                {
                    const offset = Number(a.pOffsets[i]), place = at(ctx, a.pBuffers[i], offset);
                    const buffer = ctx.objects.get(a.pBuffers[i]);
                    if(!place || !buffer) continue;
                    const size = range_size(buffer, offset, a.pSizes ? Number(a.pSizes[i]) : 2 ** 64);
                    cb.xfb[a.firstBinding + i] = [place[0], place[1], size];
                    vx.command(VX.XFB_BIND, [a.firstBinding + i, place[0].rid, lo(place[1]), hi(place[1]), lo(size), hi(size)]);
                }
                break;
            }
            case "vkCmdBeginTransformFeedbackEXT":
            case "vkCmdEndTransformFeedbackEXT":
            {
                const words = [a.firstCounterBuffer, a.counterBufferCount];
                for(let i = 0; i < a.counterBufferCount; i++)
                {
                    const id = a.pCounterBuffers && a.pCounterBuffers[i];
                    const offset = a.pCounterBufferOffsets ? Number(a.pCounterBufferOffsets[i]) : 0;
                    const place = id ? at(ctx, id, offset) : null;
                    words.push(place ? place[0].rid : 0, place ? lo(place[1]) : 0, place ? hi(place[1]) : 0);
                    if(place && name === "vkCmdEndTransformFeedbackEXT") write(place[0], place[1], 4);
                }
                if(name === "vkCmdEndTransformFeedbackEXT") for(const bound of cb.xfb) if(bound) write(bound[0], bound[1], bound[2]);
                vx.command(name === "vkCmdBeginTransformFeedbackEXT" ? VX.XFB_BEGIN : VX.XFB_END, words);
                break;
            }
            case "vkCmdWriteTimestamp":
            case "vkCmdWriteTimestamp2":
            {
                // (WebGPU has no timestamps in encoders: the time the batch is made, in ns)
                const pool = ctx.objects.get(a.queryPool);
                if(!pool) break;
                const ns = Math.floor(vk.clock() * 1e6), bytes = new Uint8Array(8), view = new DataView(bytes.buffer);
                view.setUint32(0, lo(ns), true);
                view.setUint32(4, hi(ns), true);
                vx.command(VX.UPDATE_BUFFER, [pool.memory.rid, a.query * 8, 0, 8], bytes);
                touch(pool, a.query);
                break;
            }
            case "vkCmdCopyQueryPoolResults":
            {
                const pool = ctx.objects.get(a.queryPool), dst = at(ctx, a.dstBuffer, a.dstOffset);
                if(!pool || !dst || !a.queryCount) break;
                vx.command(VX.COPY_QUERY_RESULTS, [pool.memory.rid, a.firstQuery, a.queryCount, dst[0].rid, lo(dst[1]), hi(dst[1]), a.stride, a.flags,
                    pool.values]);
                const size = (a.flags & QUERY_RESULT_64 ? 8 : 4) * (pool.values + (a.flags & QUERY_RESULT_WITH_AVAILABILITY ? 1 : 0));
                write(dst[0], dst[1], a.stride * (a.queryCount - 1) + size);
                break;
            }
            // (one queue, in order: barriers and event waits are kept already)
            case "vkCmdPipelineBarrier":
            case "vkCmdPipelineBarrier2":
            case "vkCmdWaitEvents":
            case "vkCmdWaitEvents2":
                break;
            default:
                vk.warn_once(name, name + " is not done yet");
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/graphics_adapters/virtio_gpu/venus_vk_pipeline.js                                    0000644 0000000 0000000 00000040662 00000000000 022420  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Venus device's shaders, pipelines, descriptor sets, render passes and
// framebuffers (venus_vk.js runs them). Shader modules go to the renderer
// as SPIR-V (it translates them with naga); pipelines as a description of
// their state, which the renderer turns into WebGPU pipelines; descriptor
// sets stay here and are sent, resolved, when a submission binds them.

import { VX } from "../renderer_protocol.js";
import { VK_SUCCESS, VK_ERROR_OUT_OF_HOST_MEMORY, REMAINING, out_array } from "./venus_device_info.js";

const STYPE_RENDER_PASS_MULTIVIEW = 1000053000;
const STYPE_PIPELINE_RENDERING_CREATE_INFO = 1000044002;
// VkPipelineRasterizationProvokingVertexStateCreateInfoEXT
const STYPE_PROVOKING_VERTEX_STATE = 1000254001;
// VkSubpassDescriptionDepthStencilResolve
const STYPE_DEPTH_STENCIL_RESOLVE = 1000199001;

/** UTF-8 of a JSON description, for the renderer */
function json_bytes(object)
{
    return new TextEncoder().encode(JSON.stringify(object));
}

/** VkSpecializationInfo: constant id -> its bytes as the shader reads them (u32 bits) */
function specialization(info)
{
    if(!info || !info.pMapEntries || !info.pData) return {};
    const out = {};
    const view = new DataView(info.pData.buffer, info.pData.byteOffset, info.pData.byteLength);
    for(const entry of info.pMapEntries)
    {
        if(entry.offset + 4 <= view.byteLength) out[entry.constantID] = view.getUint32(entry.offset, true);
        else if(entry.size === 1 && entry.offset < view.byteLength) out[entry.constantID] = view.getUint8(entry.offset);
    }
    return out;
}

/**
 * A render pass from VkRenderPassCreateInfo or ...2 (the fields both have)
 * @param {!Object} info
 * @param {boolean} two
 */
function render_pass(info, two)
{
    const ref = r => r ? { attachment: r.attachment, layout: r.layout, aspect: r.aspectMask || 0 } : null;
    return {
        type: "render_pass",
        attachments: (info.pAttachments || []).map(a => ({
            format: a.format, samples: a.samples, load: a.loadOp, store: a.storeOp,
            stencil_load: a.stencilLoadOp, stencil_store: a.stencilStoreOp,
        })),
        subpasses: (info.pSubpasses || []).map(s => ({
            colors: (s.pColorAttachments || []).map(ref),
            resolves: s.pResolveAttachments ? s.pResolveAttachments.map(ref) : null,
            inputs: (s.pInputAttachments || []).map(ref),
            depth: ref(s.pDepthStencilAttachment),
            // (VkSubpassDescriptionDepthStencilResolve: the depth and stencil resolved, sample zero)
            depth_resolve: (() => {
                for(let n = s.pNext; n; n = n.pNext)
                {
                    if(n.sType === STYPE_DEPTH_STENCIL_RESOLVE && n.pDepthStencilResolveAttachment)
                    {
                        return { attachment: n.pDepthStencilResolveAttachment.attachment, depth: n.depthResolveMode, stencil: n.stencilResolveMode };
                    }
                }
                return null;
            })(),
            view_mask: two ? s.viewMask : 0,
        })),
    };
}

/**
 * A graphics pipeline's state, as the renderer wants it
 * @param {!Object} ctx
 * @param {!Object} info VkGraphicsPipelineCreateInfo
 */
function graphics_pipeline(ctx, info)
{
    const pass = ctx.objects.get(info.renderPass);
    const subpass = pass && pass.subpasses[info.subpass] || { colors: [], depth: null };
    const layout = ctx.objects.get(info.layout) || { sets: [], push_size: 0 };
    const vi = info.pVertexInputState || {}, ia = info.pInputAssemblyState || {}, rs = info.pRasterizationState || {};
    const ms = info.pMultisampleState || {}, ds = info.pDepthStencilState, cb = info.pColorBlendState || {};
    let formats, depth, samples;
    if(pass)
    {
        formats = subpass.colors.map(r => r && r.attachment !== REMAINING && pass.attachments[r.attachment] ? pass.attachments[r.attachment].format : 0);
        depth = subpass.depth && subpass.depth.attachment !== REMAINING && pass.attachments[subpass.depth.attachment];
        samples = subpass.colors.concat([subpass.depth]).map(r => r && r.attachment !== REMAINING && pass.attachments[r.attachment])
            .filter(a => a).map(a => a.samples)[0] || 1;
    }
    else
    {
        // dynamic rendering: the formats are the pipeline's (VkPipelineRenderingCreateInfo)
        let rendering = null;
        for(let s = info.pNext; s; s = s.pNext) if(s.sType === STYPE_PIPELINE_RENDERING_CREATE_INFO) rendering = s;
        formats = rendering ? Array.from(rendering.pColorAttachmentFormats || []) : [];
        const depth_format = rendering ? rendering.depthAttachmentFormat || rendering.stencilAttachmentFormat : 0;
        depth = depth_format ? { format: depth_format } : null;
        samples = ms.rasterizationSamples || 1;
    }
    // VK_EXT_provoking_vertex: the last vertex of a primitive (GL's) for flat varyings
    let provoking_last = false;
    for(let s = rs.pNext; s; s = s.pNext) if(s.sType === STYPE_PROVOKING_VERTEX_STATE) provoking_last = s.provokingVertexMode === 1;
    const stencil = s => s && { fail: s.failOp, pass: s.passOp, depth_fail: s.depthFailOp, compare: s.compareOp,
        read_mask: s.compareMask, write_mask: s.writeMask, reference: s.reference };
    return {
        kind: "graphics",
        stages: (info.pStages || []).map(s => ({ shader: (ctx.objects.get(s.module) || {}).rid || 0, stage: s.stage, entry: s.pName,
            constants: specialization(s.pSpecializationInfo) })),
        buffers: (vi.pVertexBindingDescriptions || []).map(b => ({ binding: b.binding, stride: b.stride, rate: b.inputRate })),
        attributes: (vi.pVertexAttributeDescriptions || []).map(a => ({ location: a.location, binding: a.binding, format: a.format, offset: a.offset })),
        topology: ia.topology || 0, restart: !!ia.primitiveRestartEnable,
        cull: rs.cullMode || 0, front: rs.frontFace || 0, polygon: rs.polygonMode || 0, depth_clamp: !!rs.depthClampEnable, provoking_last,
        discard: !!rs.rasterizerDiscardEnable,
        depth_bias: rs.depthBiasEnable ? { constant: rs.depthBiasConstantFactor, clamp: rs.depthBiasClamp, slope: rs.depthBiasSlopeFactor } : null,
        samples, sample_mask: ms.pSampleMask ? ms.pSampleMask[0] : 0xFFFFFFFF, alpha_to_coverage: !!ms.alphaToCoverageEnable,
        depth: ds && depth ? { test: !!ds.depthTestEnable, write: !!ds.depthWriteEnable, compare: ds.depthCompareOp,
            stencil: !!ds.stencilTestEnable, front: stencil(ds.front), back: stencil(ds.back) } : null,
        depth_format: depth ? depth.format : 0,
        targets: formats.map((format, i) => {
            const a = (cb.pAttachments || [])[i] || {};
            return { format, blend: !!a.blendEnable, src_color: a.srcColorBlendFactor, dst_color: a.dstColorBlendFactor, color_op: a.colorBlendOp,
                src_alpha: a.srcAlphaBlendFactor, dst_alpha: a.dstAlphaBlendFactor, alpha_op: a.alphaBlendOp,
                write_mask: a.colorWriteMask === undefined ? 0xF : a.colorWriteMask };
        }),
        blend_constants: cb.blendConstants ? Array.from(cb.blendConstants) : [0, 0, 0, 0],
        dynamic: info.pDynamicState && info.pDynamicState.pDynamicStates ? Array.from(info.pDynamicState.pDynamicStates) : [],
        viewport: info.pViewportState && info.pViewportState.pViewports ? info.pViewportState.pViewports[0] : null,
        scissor: info.pViewportState && info.pViewportState.pScissors ? info.pViewportState.pScissors[0] : null,
        set_count: layout.sets.length, push_size: layout.push_size,
    };
}

/** @type {!Object<string, function(!Object, !Object, !Object): ?function(function())>} */
export const PIPELINE_HANDLERS = {
    // Shaders

    "vkCreateShaderModule": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        const module = { type: "shader_module", rid: vk.new_rid() };
        const code = info.pCode;
        const bytes = new Uint8Array(code.buffer, code.byteOffset, Math.min(info.codeSize, code.byteLength));
        vk.vx.command(VX.SHADER_CREATE, [module.rid, bytes.length], bytes);
        ctx.objects.set(a.pShaderModule, module);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyShaderModule": function(vk, ctx, a)
    {
        const module = ctx.objects.get(a.shaderModule);
        if(module) vk.vx.command(VX.DESTROY, [module.rid]);
        ctx.objects.delete(a.shaderModule);
        return null;
    },

    // Descriptor set layouts, pipeline layouts

    "vkCreateDescriptorSetLayout": function(vk, ctx, a)
    {
        const bindings = new Map();
        for(const b of a.pCreateInfo.pBindings || [])
        {
            bindings.set(b.binding, { type: b.descriptorType, count: b.descriptorCount, stages: b.stageFlags,
                immutable: b.pImmutableSamplers ? Array.from(b.pImmutableSamplers) : null });
        }
        ctx.objects.set(a.pSetLayout, { type: "set_layout", bindings });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyDescriptorSetLayout": function(vk, ctx, a) { ctx.objects.delete(a.descriptorSetLayout); return null; },
    "vkGetDescriptorSetLayoutSupport": function(vk, ctx, a)
    {
        const count = (a.pCreateInfo.pBindings || []).reduce((n, b) => n + b.descriptorCount, 0);
        a.pSupport.supported = count <= 1024 ? 1 : 0;
        return null;
    },
    "vkCreatePipelineLayout": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        const push = (info.pPushConstantRanges || []).reduce((n, r) => Math.max(n, r.offset + r.size), 0);
        ctx.objects.set(a.pPipelineLayout, { type: "pipeline_layout", sets: Array.from(info.pSetLayouts || []), push_size: push });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyPipelineLayout": function(vk, ctx, a) { ctx.objects.delete(a.pipelineLayout); return null; },

    // Descriptor pools and sets

    "vkCreateDescriptorPool": function(vk, ctx, a)
    {
        ctx.objects.set(a.pDescriptorPool, { type: "descriptor_pool", sets: new Set() });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyDescriptorPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.descriptorPool);
        if(pool) for(const id of pool.sets) ctx.objects.delete(id);
        ctx.objects.delete(a.descriptorPool);
        return null;
    },
    "vkResetDescriptorPool": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.descriptorPool);
        if(pool) { for(const id of pool.sets) ctx.objects.delete(id); pool.sets.clear(); }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkAllocateDescriptorSets": function(vk, ctx, a)
    {
        const info = a.pAllocateInfo;
        const pool = ctx.objects.get(info.descriptorPool);
        (a.pDescriptorSets || []).forEach((id, i) => {
            const layout = ctx.objects.get(info.pSetLayouts[i]) || { bindings: new Map() };
            const set = { type: "descriptor_set", layout, descriptors: new Map(), version: 0 };
            // immutable samplers are there from the start
            for(const [binding, b] of layout.bindings)
            {
                if(b.immutable) b.immutable.forEach((sampler, e) => set.descriptors.set(binding * 1024 + e, { type: b.type, sampler }));
            }
            ctx.objects.set(id, set);
            if(pool) pool.sets.add(id);
        });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkFreeDescriptorSets": function(vk, ctx, a)
    {
        const pool = ctx.objects.get(a.descriptorPool);
        for(const id of a.pDescriptorSets || []) { ctx.objects.delete(id); if(pool) pool.sets.delete(id); }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkUpdateDescriptorSets": function(vk, ctx, a)
    {
        for(const w of a.pDescriptorWrites || [])
        {
            const set = ctx.objects.get(w.dstSet);
            if(!set) continue;
            set.version++;
            // (a write past a binding's count goes on into the next binding)
            let binding = w.dstBinding, element = w.dstArrayElement;
            for(let i = 0; i < w.descriptorCount; i++)
            {
                const b = set.layout.bindings.get(binding);
                if(b && element >= b.count) { binding++; element = 0; }
                const d = { type: w.descriptorType };
                if(w.pImageInfo && w.pImageInfo[i])
                {
                    d.view = w.pImageInfo[i].imageView;
                    d.sampler = w.pImageInfo[i].sampler;
                    const lb = set.layout.bindings.get(binding);
                    if(lb && lb.immutable) d.sampler = lb.immutable[element];
                }
                if(w.pBufferInfo && w.pBufferInfo[i]) { d.buffer = w.pBufferInfo[i].buffer; d.offset = w.pBufferInfo[i].offset; d.range = w.pBufferInfo[i].range; }
                if(w.pTexelBufferView && w.pTexelBufferView[i]) d.texel = w.pTexelBufferView[i];
                set.descriptors.set(binding * 1024 + element, d);
                element++;
            }
        }
        for(const c of a.pDescriptorCopies || [])
        {
            const src = ctx.objects.get(c.srcSet), dst = ctx.objects.get(c.dstSet);
            if(!src || !dst) continue;
            dst.version++;
            for(let i = 0; i < c.descriptorCount; i++)
            {
                const d = src.descriptors.get(c.srcBinding * 1024 + c.srcArrayElement + i);
                if(d) dst.descriptors.set(c.dstBinding * 1024 + c.dstArrayElement + i, Object.assign({}, d));
            }
        }
        return null;
    },

    // Render passes, framebuffers

    "vkCreateRenderPass": function(vk, ctx, a)
    {
        ctx.objects.set(a.pRenderPass, render_pass(a.pCreateInfo, false));
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkCreateRenderPass2": function(vk, ctx, a)
    {
        ctx.objects.set(a.pRenderPass, render_pass(a.pCreateInfo, true));
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyRenderPass": function(vk, ctx, a) { ctx.objects.delete(a.renderPass); return null; },
    "vkGetRenderAreaGranularity": function(vk, ctx, a)
    {
        a.pGranularity = { width: 1, height: 1 };
        return null;
    },
    "vkCreateFramebuffer": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        ctx.objects.set(a.pFramebuffer, { type: "framebuffer", attachments: Array.from(info.pAttachments || []),
            width: info.width, height: info.height, layers: info.layers });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyFramebuffer": function(vk, ctx, a) { ctx.objects.delete(a.framebuffer); return null; },

    // Pipelines

    "vkCreateGraphicsPipelines": function(vk, ctx, a)
    {
        (a.pCreateInfos || []).forEach((info, i) => {
            const id = a.pPipelines[i];
            const pipeline = { type: "pipeline", rid: vk.new_rid(), bind_point: 0, layout: info.layout };
            vk.vx.command(VX.PIPELINE_CREATE, [pipeline.rid], json_bytes(graphics_pipeline(ctx, info)));
            ctx.objects.set(id, pipeline);
        });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkCreateComputePipelines": function(vk, ctx, a)
    {
        (a.pCreateInfos || []).forEach((info, i) => {
            const id = a.pPipelines[i];
            const layout = ctx.objects.get(info.layout) || { sets: [], push_size: 0 };
            const pipeline = { type: "pipeline", rid: vk.new_rid(), bind_point: 1, layout: info.layout };
            const s = info.stage;
            vk.vx.command(VX.PIPELINE_CREATE, [pipeline.rid], json_bytes({ kind: "compute",
                stages: [{ shader: (ctx.objects.get(s.module) || {}).rid || 0, stage: s.stage, entry: s.pName, constants: specialization(s.pSpecializationInfo) }],
                set_count: layout.sets.length, push_size: layout.push_size }));
            ctx.objects.set(id, pipeline);
        });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyPipeline": function(vk, ctx, a)
    {
        const pipeline = ctx.objects.get(a.pipeline);
        if(pipeline) vk.vx.command(VX.DESTROY, [pipeline.rid]);
        ctx.objects.delete(a.pipeline);
        return null;
    },
    "vkCreatePipelineCache": function(vk, ctx, a)
    {
        ctx.objects.set(a.pPipelineCache, { type: "pipeline_cache" });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyPipelineCache": function(vk, ctx, a) { ctx.objects.delete(a.pipelineCache); return null; },
    "vkGetPipelineCacheData": function(vk, ctx, a)
    {
        // (nothing kept: an empty cache's header is still the app's to read; none)
        a.pDataSize = 0;
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkMergePipelineCaches": function(vk, ctx, a) { a.ret = VK_SUCCESS; return null; },
};
                                                                              source/v64/src/graphics_adapters/virtio_gpu/venus_vk_resources.js                                   0000644 0000000 0000000 00000040200 00000000000 022611  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Venus device's memory and the objects in it (venus_vk.js runs them):
// a VkDeviceMemory is a GPU buffer of the renderer's (VX), and while the
// guest maps it, also pages of the host visible memory (BAR4) -- the pages
// the guest writes go to the GPU buffer before each submission, what the GPU
// writes comes back before the submission completes. A VkBuffer is a range
// of its memory; a VkImage is a texture of its own (its memory only counts).

import { VX } from "../renderer_protocol.js";
import * as INFO from "./venus_device_info.js";
import { VK_SUCCESS, VK_ERROR_OUT_OF_DEVICE_MEMORY, VK_ERROR_FORMAT_NOT_SUPPORTED, VK_ERROR_INVALID_EXTERNAL_HANDLE,
    WHOLE, REMAINING, out_array } from "./venus_device_info.js";

const STYPE_MEMORY_DEDICATED_REQUIREMENTS = 1000127000;
const STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA = 1000384002;
const STYPE_MEMORY_RESOURCE_ALLOCATION_SIZE_PROPERTIES_MESA = 1000384003;

/** what memory of buffers and images is aligned to (WebGPU's binding offsets) */
const ALIGNMENT = 256;

const align = (value, to) => Math.ceil(value / to) * to;
const lo = value => value % 0x100000000 >>> 0;
const hi = value => Math.floor(value / 0x100000000) >>> 0;

/**
 * A VkDeviceMemory
 * @constructor
 */
export function Memory(rid, size, type_index)
{
    this.type = "memory";
    this.rid = rid;
    this.size = size;
    this.type_index = type_index;
    this.host_visible = type_index !== INFO.MEMORY_DEVICE_LOCAL;
    /** @type {Object} the blob exporting it (mapped by the guest at its map_offset) */
    this.blob = null;
    /** the GPU wrote it since the guest last saw it */
    this.gpu_written = false;
}

/**
 * The bytes an image's memory says it has: every mip of every layer
 * @param {!Object} image
 */
export function image_size(image)
{
    const texel = INFO.FORMATS[image.format] ? INFO.FORMATS[image.format][3] : 4;
    let size = 0;
    for(let mip = 0; mip < image.mips; mip++)
    {
        const w = Math.max(1, image.width >> mip), h = Math.max(1, image.height >> mip), d = Math.max(1, image.depth >> mip);
        size += w * h * d * texel;
    }
    return align(size * image.layers * image.samples, ALIGNMENT);
}

/** @return {Object} VkMemoryRequirements of a buffer */
function buffer_requirements(size)
{
    return { size: align(size, 4), alignment: ALIGNMENT, memoryTypeBits: 7 };
}

/**
 * An image bound to its memory; memory imported from a virtio-gpu resource
 * makes the image that resource's GX surface (VX.TEXTURE_IMPORT)
 */
function bind_image(vk, image, memory, offset)
{
    image.memory = memory;
    image.offset = offset;
    if(memory && memory.resource_id && !image.resource_id)
    {
        image.resource_id = memory.resource_id;
        vk.vx.command(VX.TEXTURE_IMPORT, [image.rid, memory.resource_id]);
    }
}

/** VkMemoryRequirements of an image: device local memory (images are textures) */
function image_requirements(image)
{
    return { size: image_size(image), alignment: ALIGNMENT, memoryTypeBits: 1 << INFO.MEMORY_DEVICE_LOCAL };
}

/** fill VkMemoryRequirements2's chain */
function requirements2(out, requirements)
{
    out.memoryRequirements = requirements;
    for(let s = out.pNext; s; s = s.pNext)
    {
        if(s.sType === STYPE_MEMORY_DEDICATED_REQUIREMENTS)
        {
            s.prefersDedicatedAllocation = 0;
            s.requiresDedicatedAllocation = 0;
        }
    }
}

/**
 * The bytes a virtio-gpu resource Venus imports holds: its blob's size, or
 * its texels (the bits in its virgl format's name), aligned as images' memory
 * @param {!Object} resource a virgl Resource3D
 */
function resource_size(resource)
{
    if(resource.blob_size > 0) return resource.blob_size;
    // (the name is the SVGA3D format's: SVGA3D_R8G8B8A8_UNORM)
    const bits = resource.info ? (resource.info.name.replace(/^SVGA3D_/, "").match(/\d+/g) || []).reduce((sum, n) => sum + +n, 0) : 32;
    const texel = Math.max(1, Math.ceil((bits || 32) / 8));
    return align(Math.max(1, resource.width) * Math.max(1, resource.height) * Math.max(1, resource.depth) *
        Math.max(1, resource.array_size) * texel, ALIGNMENT);
}

/** the virtio-gpu resource an import names, when Venus can import it: a virgl resource with a GX surface */
function importable_resource(vk, id)
{
    const resource = vk.gpu && vk.gpu.resources ? vk.gpu.resources.get(id) : null;
    return resource && resource.three_d && resource.info ? resource : null;
}

/** an image from its create info */
function image_of(rid, info)
{
    return {
        type: "image", rid,
        format: info.format, image_type: info.imageType,
        width: info.extent.width, height: info.extent.height, depth: info.extent.depth,
        mips: info.mipLevels, layers: info.arrayLayers, samples: info.samples,
        texel_bytes: INFO.FORMATS[info.format] ? INFO.FORMATS[info.format][3] : 4,
        tiling: info.tiling, usage: info.usage, flags: info.flags,
        memory: null, offset: 0,
    };
}

/** @type {!Object<string, function(!Object, !Object, !Object): ?function(function())>} */
export const RESOURCE_HANDLERS = {
    // Memory

    "vkAllocateMemory": function(vk, ctx, a)
    {
        const info = a.pAllocateInfo;
        const type = info.memoryTypeIndex, size = info.allocationSize;
        for(let s = info.pNext; s; s = s.pNext)
        {
            // (a dma-buf: its virtio-gpu resource, whose GX surface the image
            // bound to it becomes; no GPU buffer of its own)
            if(s.sType !== STYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA) continue;
            if(type !== INFO.MEMORY_DEVICE_LOCAL || !importable_resource(vk, s.resourceId)) { a.ret = VK_ERROR_INVALID_EXTERNAL_HANDLE; return null; }
            const memory = new Memory(vk.new_rid(), size, type);
            memory.resource_id = s.resourceId;
            ctx.objects.set(a.pMemory, memory);
            a.ret = VK_SUCCESS;
            return null;
        }
        if(type > INFO.MEMORY_HOST_CACHED || !size || size > 1 << 30) { a.ret = VK_ERROR_OUT_OF_DEVICE_MEMORY; return null; }
        const host = type !== INFO.MEMORY_DEVICE_LOCAL;
        const heap = host ? vk.host_visible_size : 1 << 30;
        if((host ? vk.host_allocated : vk.device_allocated) + size > heap) { a.ret = VK_ERROR_OUT_OF_DEVICE_MEMORY; return null; }
        if(host) vk.host_allocated += size; else vk.device_allocated += size;
        const memory = new Memory(vk.new_rid(), size, type);
        vk.vx.command(VX.MEMORY_CREATE, [memory.rid, lo(align(size, 4)), hi(align(size, 4))]);
        ctx.objects.set(a.pMemory, memory);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkFreeMemory": function(vk, ctx, a)
    {
        const memory = ctx.objects.get(a.memory);
        if(!memory) return null;
        if(memory.resource_id)
        {
            ctx.objects.delete(a.memory);
            return null;
        }
        if(memory.host_visible) vk.host_allocated -= memory.size; else vk.device_allocated -= memory.size;
        vk.vx.command(VX.DESTROY, [memory.rid]);
        if(memory.blob) memory.blob.memory = null;
        ctx.objects.delete(a.memory);
        return null;
    },
    "vkGetDeviceMemoryCommitment": function(vk, ctx, a)
    {
        const memory = ctx.objects.get(a.memory);
        a.pCommittedMemoryInBytes = memory ? memory.size : 0;
        return null;
    },
    "vkGetMemoryResourcePropertiesMESA": function(vk, ctx, a)
    {
        const resource = importable_resource(vk, a.resourceId);
        if(!resource)
        {
            a.ret = VK_ERROR_INVALID_EXTERNAL_HANDLE;
            return null;
        }
        const props = a.pMemoryResourceProperties;
        props.memoryTypeBits = 1 << INFO.MEMORY_DEVICE_LOCAL;
        for(let s = props.pNext; s; s = s.pNext)
        {
            if(s.sType === STYPE_MEMORY_RESOURCE_ALLOCATION_SIZE_PROPERTIES_MESA) s.allocationSize = resource_size(resource);
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    // (coherent memory: nothing to do)
    "vkFlushMappedMemoryRanges": function(vk, ctx, a) { a.ret = VK_SUCCESS; return null; },
    "vkInvalidateMappedMemoryRanges": function(vk, ctx, a) { a.ret = VK_SUCCESS; return null; },

    // Buffers

    "vkCreateBuffer": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        ctx.objects.set(a.pBuffer, { type: "buffer", size: info.size, usage: info.usage, flags: info.flags, memory: null, offset: 0 });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyBuffer": function(vk, ctx, a)
    {
        ctx.objects.delete(a.buffer);
        return null;
    },
    "vkGetBufferMemoryRequirements": function(vk, ctx, a)
    {
        const buffer = ctx.objects.get(a.buffer);
        a.pMemoryRequirements = buffer_requirements(buffer ? buffer.size : 0);
        return null;
    },
    "vkGetBufferMemoryRequirements2": function(vk, ctx, a)
    {
        const buffer = ctx.objects.get(a.pInfo.buffer);
        requirements2(a.pMemoryRequirements, buffer_requirements(buffer ? buffer.size : 0));
        return null;
    },
    "vkGetDeviceBufferMemoryRequirements": function(vk, ctx, a)
    {
        requirements2(a.pMemoryRequirements, buffer_requirements(a.pInfo.pCreateInfo.size));
        return null;
    },
    "vkBindBufferMemory": function(vk, ctx, a)
    {
        const buffer = ctx.objects.get(a.buffer);
        if(buffer)
        {
            buffer.memory = ctx.objects.get(a.memory) || null;
            buffer.offset = a.memoryOffset;
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkBindBufferMemory2": function(vk, ctx, a)
    {
        for(const bind of a.pBindInfos || [])
        {
            const buffer = ctx.objects.get(bind.buffer);
            if(!buffer) continue;
            buffer.memory = ctx.objects.get(bind.memory) || null;
            buffer.offset = bind.memoryOffset;
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkCreateBufferView": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        ctx.objects.set(a.pView, { type: "buffer_view", buffer: info.buffer, format: info.format, offset: info.offset, range: info.range });
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyBufferView": function(vk, ctx, a)
    {
        ctx.objects.delete(a.bufferView);
        return null;
    },

    // Images

    "vkCreateImage": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        if(!INFO.image_format_properties(info.format, info.imageType, info.tiling, info.usage, info.flags))
        {
            a.ret = VK_ERROR_FORMAT_NOT_SUPPORTED;
            return null;
        }
        const image = image_of(vk.new_rid(), info);
        for(let s = info.pNext; s; s = s.pNext)
        {
            // (the layout the guest's buffer has, for vkGetImageSubresourceLayout)
            if(s.sType === INFO.STYPE.IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO && s.pPlaneLayouts) image.layout = s.pPlaneLayouts[0];
        }
        vk.vx.command(VX.TEXTURE_CREATE, [image.rid, image.format, image.image_type, image.width, image.height, image.depth,
            image.mips, image.layers, image.samples, image.usage, image.flags]);
        ctx.objects.set(a.pImage, image);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyImage": function(vk, ctx, a)
    {
        const image = ctx.objects.get(a.image);
        if(image) vk.vx.command(VX.DESTROY, [image.rid]);
        ctx.objects.delete(a.image);
        return null;
    },
    "vkGetImageMemoryRequirements": function(vk, ctx, a)
    {
        const image = ctx.objects.get(a.image);
        a.pMemoryRequirements = image ? image_requirements(image) : {};
        return null;
    },
    "vkGetImageMemoryRequirements2": function(vk, ctx, a)
    {
        const image = ctx.objects.get(a.pInfo.image);
        requirements2(a.pMemoryRequirements, image ? image_requirements(image) : {});
        return null;
    },
    "vkGetDeviceImageMemoryRequirements": function(vk, ctx, a)
    {
        requirements2(a.pMemoryRequirements, image_requirements(image_of(0, a.pInfo.pCreateInfo)));
        return null;
    },
    "vkGetImageSparseMemoryRequirements": function(vk, ctx, a)
    {
        out_array(a, "pSparseMemoryRequirementCount", "pSparseMemoryRequirements", []);
        return null;
    },
    "vkGetImageSparseMemoryRequirements2": function(vk, ctx, a)
    {
        out_array(a, "pSparseMemoryRequirementCount", "pSparseMemoryRequirements", []);
        return null;
    },
    "vkGetDeviceImageSparseMemoryRequirements": function(vk, ctx, a)
    {
        out_array(a, "pSparseMemoryRequirementCount", "pSparseMemoryRequirements", []);
        return null;
    },
    "vkBindImageMemory": function(vk, ctx, a)
    {
        const image = ctx.objects.get(a.image);
        if(image) bind_image(vk, image, ctx.objects.get(a.memory) || null, a.memoryOffset);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkBindImageMemory2": function(vk, ctx, a)
    {
        for(const bind of a.pBindInfos || [])
        {
            const image = ctx.objects.get(bind.image);
            if(image) bind_image(vk, image, ctx.objects.get(bind.memory) || null, bind.memoryOffset);
        }
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkGetImageSubresourceLayout": function(vk, ctx, a)
    {
        // (optimal tiling: no layout to speak of; an imported buffer's is the guest's)
        const image = ctx.objects.get(a.image);
        a.pLayout = image && image.layout ? image.layout : { offset: 0, size: 0, rowPitch: 0, arrayPitch: 0, depthPitch: 0 };
        return null;
    },
    "vkGetImageDrmFormatModifierPropertiesEXT": function(vk, ctx, a)
    {
        a.pProperties.drmFormatModifier = INFO.DRM_FORMAT_MOD_LINEAR;
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkCreateImageView": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        const image = ctx.objects.get(info.image);
        if(!image) { a.ret = VK_ERROR_OUT_OF_DEVICE_MEMORY; return null; }
        const range = info.subresourceRange;
        const mips = range.levelCount === REMAINING ? image.mips - range.baseMipLevel : range.levelCount;
        const layers = range.layerCount === REMAINING ? image.layers - range.baseArrayLayer : range.layerCount;
        const view = { type: "image_view", rid: vk.new_rid(), image: info.image, image_rid: image.rid, view_type: info.viewType,
            format: info.format, aspect: range.aspectMask, base_mip: range.baseMipLevel, mips, base_layer: range.baseArrayLayer, layers,
            width: Math.max(1, image.width >> range.baseMipLevel), height: Math.max(1, image.height >> range.baseMipLevel),
            samples: image.samples };
        const c = info.components;
        vk.vx.command(VX.VIEW_CREATE, [view.rid, image.rid, info.viewType, info.format, range.aspectMask, range.baseMipLevel, mips,
            range.baseArrayLayer, layers, c.r, c.g, c.b, c.a]);
        ctx.objects.set(a.pView, view);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroyImageView": function(vk, ctx, a)
    {
        const view = ctx.objects.get(a.imageView);
        if(view) vk.vx.command(VX.DESTROY, [view.rid]);
        ctx.objects.delete(a.imageView);
        return null;
    },
    "vkCreateSampler": function(vk, ctx, a)
    {
        const info = a.pCreateInfo;
        const sampler = { type: "sampler", rid: vk.new_rid() };
        const f32 = new Float32Array(4);
        f32[0] = info.mipLodBias;
        f32[1] = info.anisotropyEnable ? info.maxAnisotropy : 1;
        f32[2] = info.minLod;
        f32[3] = info.maxLod;
        const bits = new Uint32Array(f32.buffer);
        vk.vx.command(VX.SAMPLER_CREATE, [sampler.rid, info.magFilter, info.minFilter, info.mipmapMode, info.addressModeU,
            info.addressModeV, info.addressModeW, bits[0], bits[1], info.compareEnable, info.compareOp, bits[2], bits[3]]);
        ctx.objects.set(a.pSampler, sampler);
        a.ret = VK_SUCCESS;
        return null;
    },
    "vkDestroySampler": function(vk, ctx, a)
    {
        const sampler = ctx.objects.get(a.sampler);
        if(sampler) vk.vx.command(VX.DESTROY, [sampler.rid]);
        ctx.objects.delete(a.sampler);
        return null;
    },
};

/** The size of a buffer range (VK_WHOLE_SIZE: to its end) */
export function range_size(buffer, offset, size)
{
    return size >= WHOLE ? buffer.size - offset : size;
}

export { lo, hi, align };
                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/graphics_adapters/virtio_gpu/virgl.js                                                0000644 0000000 0000000 00000055531 00000000000 020017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-gpu's 3D (virgl; docs/gpu-devices.md, "virtio-gpu"): the device
// side. Mesa's virgl driver sends gallium's state and draws as the virgl
// command stream (third_party/virgl/virgl_protocol.h) in SUBMIT_3D; it is
// translated here into what GX runs (src/browser/glbridge/gx/gx_executor.js),
// as SVGA's DX does: 3D resources are GX surfaces, and the context's state
// becomes the DX commands of a GX context (virgl_context.js), with TGSI
// shaders turned into VGPU10 programs (tgsi_vgpu10.js).
//
// GX runs in the renderer (the page's WebGPU device, or a headless
// Chrome's in tests), batch by batch; the device completes what waits for
// the GPU (fenced commands, readbacks) once the renderer says a batch is done.

import { LOG_VGA } from "../../const.js";
import { dbg_log } from "../../log.js";
import { GX, GXWriter, QUERY_REGION_BYTES, READBACK_HEADER_BYTES, READBACK_MAX_BYTES, RESPONSE_OK } from "../renderer_protocol.js";
import { virgl_format, TARGET } from "./virgl_caps.js";
import { VirglContext } from "./virgl_context.js";
import * as C from "../vmware_svga/svga_constants.js";

const VIRGL_BIND_SHADER_BUFFER = 1 << 14;
/** SVGA3D_SURFACE_BIND_UAVIEW, in a surface's high flags */
const SURFACE2_BIND_UAVIEW = 2;

/** A batch is sent at the latest when it is this big */
const BATCH_FLUSH_BYTES = 8 << 20;


/**
 * A 3D resource: a GX surface (the resource id is its sid) and, as for 2D
 * resources, the guest pages transfers copy from and to
 * @constructor
 */
export function Resource3D(id, target, format, bind, width, height, depth, array_size, last_level, nr_samples, flags)
{
    this.id = id;
    this.three_d = true;
    this.target = target;
    this.format = format;
    this.bind = bind;
    this.width = Math.max(1, width);
    this.height = Math.max(1, height);
    this.depth = Math.max(1, depth);
    this.array_size = Math.max(1, array_size);
    this.last_level = last_level;
    this.nr_samples = nr_samples;
    this.flags = flags;
    this.info = target === TARGET.BUFFER ? null : virgl_format(format);
    /** @type {Uint8Array} the picture as last read back, for the screen (a scanout's) */
    this.data = null;
    /** `data` is newer than the GPU's copy's picture (2D transfers wrote it,
     * nothing has drawn into it since) */
    this.host_newer = false;
    this.backing = null;
    this.backing_starts = null;
    this.backing_length = 0;
    /** @type {Object} gfxstream's process pipe, when the resource is one (gfxstream.js) */
    this.pipe = null;
    this.uuid = null;
    /** @type {Array<Uint8Array>} the contents, for a snapshot (save_contents) */
    this.saved = null;
    /** A blob of the host's (BLOB_MEM_HOST3D): its flags, else -1 */
    this.blob_flags = -1;
    this.blob_size = 0;
    /** Where the blob is mapped in the host visible memory (MAP_BLOB), else -1 */
    this.map_offset = -1;
    /** Readbacks of the mapping on their way, and the pages the guest wrote
     * (and were uploaded) since they were asked for: they keep the guest's */
    this.readbacks = 0;
    /** @type {!Set<number>} */
    this.fresh = new Set();
}

Resource3D.prototype.is_buffer = function()
{
    return this.target === TARGET.BUFFER;
};

/** Bytes per block, and the block size, of the resource's format (1 x 1 for buffers) */
Resource3D.prototype.block = function()
{
    if(this.is_buffer() || !this.info) return { bytes: 1, bw: 1, bh: 1 };
    const compressed = /^SVGA3D_BC/.test(this.info.name);
    const bytes = compressed ? (/BC1|BC4/.test(this.info.name) ? 8 : 16) : bytes_per_pixel(this.info.name);
    return { bytes, bw: compressed ? 4 : 1, bh: compressed ? 4 : 1 };
};

/**
 * @param {string} name SVGA3D format
 * @return {number}
 */
function bytes_per_pixel(name)
{
    if(/R32G32B32A32|D32_FLOAT_S8X24/.test(name)) return name.includes("D32") ? 8 : 16;
    if(/R32G32B32_/.test(name)) return 12;
    if(/R16G16B16A16|R32G32_/.test(name)) return 8;
    if(/R8G8B8A8|B8G8R8|R10G10B10A2|R11G11B10|R9G9B9E5|R16G16_|R32_|D32_FLOAT$|D24/.test(name)) return 4;
    if(/R8G8_|R16_|D16|B5G6R5|B5G5R5A1|B4G4R4A4/.test(name)) return 2;
    return 1;
}

/**
 * @constructor
 * @param {!Object} gpu the VirtioGPU
 * @param {!Object} renderer the channel: post(message, transfer), listen(handler)
 * @param {boolean=} images shader images exist (GL 4.3): any texture may be one
 */
export function Virgl(gpu, renderer, images)
{
    this.gpu = gpu;
    this.renderer = renderer;
    this.images = !!images;
    this.gxw = new GXWriter();
    /** @type {!Map<number, !VirglContext>} */
    this.contexts = new Map();
    // batches sent and run
    this.submitted = 0;
    this.completed = 0;
    /** @type {!Array<{seq: number, run: function()}>} waiting for batches, in order */
    this.completions = [];
    /** @type {!Map<number, function(Uint8Array, number)>} request id -> answer */
    this.requests = new Map();
    this.next_request = 1;
    this.warned = new Set();
    /** @type {!Array<string>} the first warnings, for test harnesses */
    this.warnings = [];
    /** @type {!Object<number, number>} virgl commands seen, by VIRGL_CCMD_* (for the harnesses) */
    this.counts = {};
    /** GX contexts (one per sub-context of a virgl context) */
    this.next_cid = 1;
    /** GX surfaces of the device's own (above the guest's resource ids) */
    this.next_private_sid = 0xF0000000;
    /** @type {?function(number, string)} a test's hook: each shader's TGSI (type, text) */
    this.shader_log = null;
    /** @type {?function(string)} a test's hook: what draws do */
    this.debug_log = null;
    /** @type {!Map<string, !Array<number>>} PIPE_RESOURCE_CREATE's templates of
     * HOST3D blobs, by context and blob id, until RESOURCE_CREATE_BLOB */
    this.blob_templates = new Map();
    /** @type {!Set<!Resource3D>} mapped blobs the GPU has written since the
     * device last read them back into their mappings */
    this.written = new Set();
    /** whether the renderer shows a scanout's picture itself (SURFACE_PRESENT, its "caps") */
    this.direct_present = false;
    renderer.listen(message => this.receive(message));
    renderer.post({ "type": "hello" });
}

Virgl.prototype.warn_once = function(key, text)
{
    if(this.warned.has(key)) return;
    this.warned.add(key);
    if(this.warnings.length < 100) this.warnings.push(text);
    dbg_log("virgl: " + text, LOG_VGA);
};

/** A device reset: no contexts, nothing waits */
Virgl.prototype.reset = function()
{
    this.contexts.clear();
    this.gxw = new GXWriter();
    this.completions = [];
    this.blob_templates.clear();
    this.written.clear();
    for(const answer of this.requests.values()) answer(null, 0);
    this.requests.clear();
    this.completed = this.submitted;
    this.renderer.post({ "type": "reset" });
};

// ---------------------------------------------------------------------------
// Batches and completion

/** @return {boolean} whether something sent to the renderer has not run yet */
Virgl.prototype.busy = function()
{
    return !this.gxw.empty() || this.submitted > this.completed;
};

/** Send the batch being written */
Virgl.prototype.flush = function()
{
    if(this.gxw.empty()) return;
    const bytes = this.gxw.finish();
    const seq = ++this.submitted;
    this.renderer.post({ "type": "submit", "seq": seq, "bytes": bytes, "stream": "gx" }, [bytes.buffer]);
};

/**
 * Another stream's batch (Venus's VX), in order with GX's: the same
 * sequence numbers, the same answers
 * @param {!Uint8Array} bytes
 * @param {string} stream
 * @return {number} its sequence number
 */
Virgl.prototype.submit_stream = function(bytes, stream)
{
    this.flush();
    const seq = ++this.submitted;
    this.renderer.post({ "type": "submit", "seq": seq, "bytes": bytes, "stream": stream }, [bytes.buffer]);
    return seq;
};

Virgl.prototype.flush_big = function()
{
    if(this.gxw.size() > BATCH_FLUSH_BYTES) this.flush();
};

/**
 * Run `run` once everything written so far has run (now, if it has)
 * @param {function()} run
 */
Virgl.prototype.after_work = function(run)
{
    this.flush();
    if(this.submitted > this.completed) this.completions.push({ seq: this.submitted, run });
    else run();
};

/**
 * A request for an answer from the renderer (a readback)
 * @param {function(Uint8Array, number)} answer
 * @return {number} its id
 */
Virgl.prototype.request = function(answer)
{
    const id = this.next_request++;
    this.requests.set(id, answer);
    return id;
};

/** @param {!Object} message from the renderer */
Virgl.prototype.receive = function(message)
{
    switch(message["type"])
    {
        case "write":
            this.answer(message["offset"], message["bytes"]);
            break;
        case "done":
            this.completed = Math.max(this.completed, message["seq"]);
            while(this.completions.length && this.completions[0].seq <= this.completed)
            {
                this.completions.shift().run();
            }
            break;
        case "caps":
            this.direct_present = !!message["present"];
            break;
        case "lost":
            // The renderer is gone: let nothing wait (the guest's next
            // commands draw nothing)
            this.direct_present = false;
            dbg_log("virgl: the renderer was lost: " + message["reason"], LOG_VGA);
            this.completed = this.submitted;
            for(const answer of this.requests.values()) answer(null, 0);
            this.requests.clear();
            while(this.completions.length) this.completions.shift().run();
            break;
    }
};

/**
 * A readback's answer in the response region
 * @param {number} offset
 * @param {!Uint8Array} bytes
 */
Virgl.prototype.answer = function(offset, bytes)
{
    if(bytes.length < READBACK_HEADER_BYTES || offset < QUERY_REGION_BYTES) return;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const id = view.getUint32(0, true), count = view.getUint32(4, true), status = view.getUint32(12, true);
    const answer = this.requests.get(id);
    if(!answer) return;
    this.requests.delete(id);
    answer(status === RESPONSE_OK ? bytes.subarray(READBACK_HEADER_BYTES, READBACK_HEADER_BYTES + count) : null, status);
};

// ---------------------------------------------------------------------------
// Resources

/**
 * RESOURCE_CREATE_3D: a GX surface
 * @param {!Resource3D} r
 * @return {boolean} whether the format is one GX has
 */
Virgl.prototype.create_resource = function(r)
{
    if(r.is_buffer())
    {
        this.gxw.command(GX.SURFACE_DEFINE, [r.id, C.SVGA3D_BUFFER, 0, 0, r.width, 1, 1, 1, 1, 0, 0]);
        return true;
    }
    if(!r.info)
    {
        this.warn_once("format" + r.format, "virgl format " + r.format + " has no GX surface");
        return false;
    }
    const cube = r.target === TARGET.TEXTURE_CUBE || r.target === TARGET.TEXTURE_CUBE_ARRAY;
    // shader images: GX makes them storage textures (SVGA3D_SURFACE_BIND_UAVIEW,
    // where WebGPU lets the format be one); Mesa's virgl does not say which
    // textures will be bound as images, so with images any may be
    const flags2 = this.images || r.bind & VIRGL_BIND_SHADER_BUFFER ? SURFACE2_BIND_UAVIEW : 0;
    // (a cube's array size is 6 already, a cube array's 6 per cube)
    const layers = r.target === TARGET.TEXTURE_3D ? 1 : r.array_size;
    const flags = r.target === TARGET.TEXTURE_3D ? C.SVGA3D_SURFACE_VOLUME : 0;
    this.gxw.command(GX.SURFACE_DEFINE, [r.id, r.info.svga, flags, flags2, r.width, r.height,
        r.target === TARGET.TEXTURE_3D ? r.depth : 1, r.last_level + 1, layers, r.nr_samples > 1 ? r.nr_samples : 0, cube ? 1 : 0]);
    return true;
};

/**
 * The GPU writes a resource (draws, copies, stream output, UA views): the
 * screen's picture of it is old, and so is its mapping, if it has one
 * @param {!Resource3D} r
 */
Virgl.prototype.wrote = function(r)
{
    r.host_newer = false;
    if(r.map_offset >= 0) this.written.add(r);
};

/**
 * Bytes of a buffer from GX: `done` with them (null if GX could not)
 * @param {!Resource3D} r
 * @param {number} x
 * @param {number} w
 * @param {function(Uint8Array)} done
 */
Virgl.prototype.read_buffer = function(r, x, w, done)
{
    const out = new Uint8Array(w);
    let waiting = 0, failed = false;
    for(let at = 0; at < w; at += READBACK_MAX_BYTES)
    {
        const count = Math.min(READBACK_MAX_BYTES, w - at);
        waiting++;
        const id = this.request(bytes => {
            if(bytes) out.set(bytes.subarray(0, count), at);
            else failed = true;
            if(--waiting === 0) done(failed ? null : out);
        });
        this.gxw.command(GX.SURFACE_READBACK, [r.id, 0, 0, x + at, 0, 0, count, 1, 1, id]);
    }
    if(!w) done(out);
};

/** @param {!Resource3D} r */
Virgl.prototype.destroy_resource = function(r)
{
    this.gxw.command(GX.SURFACE_DESTROY, [r.id]);
    for(const context of this.contexts.values()) context.forget_resource(r.id);
};

/**
 * TRANSFER_TO_HOST_3D: a box of a level from the guest's backing (rows of
 * `stride` bytes, layers or slices `layer_stride` apart, from `offset`) into GX
 * @param {!Resource3D} r
 * @param {function(number, !Uint8Array, number, number):boolean} read_backing (from, out, at, length)
 */
Virgl.prototype.transfer_to_host = function(r, box, level, offset, stride, layer_stride, read_backing)
{
    const [x, y, z, w, h, d] = box;
    if(r.is_buffer())
    {
        const bytes = new Uint8Array(w);
        if(!read_backing(offset, bytes, 0, w)) return false;
        this.gxw.command(GX.SURFACE_UPLOAD, [r.id, 0, 0, x, 0, 0, w, 1, 1, w, w], bytes);
        this.flush_big();
        return true;
    }
    const { bytes: block_bytes, bw, bh } = r.block();
    const row_bytes = Math.ceil(w / bw) * block_bytes, rows = Math.ceil(h / bh);
    const volume = r.target === TARGET.TEXTURE_3D;
    const pitch = stride || row_bytes;
    const slice = layer_stride || pitch * rows;
    for(let i = 0; i < Math.max(1, d); i++)
    {
        const data = new Uint8Array(row_bytes * rows);
        for(let row = 0; row < rows; row++)
        {
            if(!read_backing(offset + i * slice + row * pitch, data, row * row_bytes, row_bytes)) return false;
        }
        this.gxw.command(GX.SURFACE_UPLOAD, [r.id, volume ? 0 : z + i, level, x, y, volume ? z + i : 0, w, h, 1,
            row_bytes, row_bytes * rows], data);
    }
    this.flush_big();
    return true;
};

/**
 * TRANSFER_FROM_HOST_3D: a box of a level from GX into the guest's backing;
 * `done` once its bytes are there
 * @param {!Resource3D} r
 * @param {function(number, !Uint8Array):boolean} write_backing (at, bytes)
 * @param {function()} done
 */
Virgl.prototype.transfer_from_host = function(r, box, level, offset, stride, layer_stride, write_backing, done)
{
    const [x, y, z, w, h, d] = box;
    if(r.is_buffer())
    {
        for(let at = 0; at < w; at += READBACK_MAX_BYTES)
        {
            const count = Math.min(READBACK_MAX_BYTES, w - at);
            const id = this.request(bytes => { if(bytes) write_backing(offset + at, bytes.subarray(0, count)); });
            this.gxw.command(GX.SURFACE_READBACK, [r.id, 0, 0, x + at, 0, 0, count, 1, 1, id]);
        }
        this.after_work(done);
        return;
    }
    const { bytes: block_bytes, bw, bh } = r.block();
    const row_bytes = Math.ceil(w / bw) * block_bytes, rows = Math.ceil(h / bh);
    const volume = r.target === TARGET.TEXTURE_3D;
    const pitch = stride || row_bytes;
    const slice = layer_stride || pitch * rows;
    const per_request = Math.max(1, Math.floor(READBACK_MAX_BYTES / row_bytes));
    for(let i = 0; i < Math.max(1, d); i++)
    {
        for(let first = 0; first < rows; first += per_request)
        {
            const count = Math.min(per_request, rows - first);
            const at = offset + i * slice + first * pitch;
            const id = this.request(bytes => {
                if(!bytes) return;
                for(let row = 0; row < count; row++) write_backing(at + row * pitch, bytes.subarray(row * row_bytes, (row + 1) * row_bytes));
            });
            this.gxw.command(GX.SURFACE_READBACK, [r.id, volume ? 0 : z + i, level, x, y + first * bh, volume ? z + i : 0,
                w, Math.min(count * bh, h - first * bh), 1, id]);
        }
    }
    this.after_work(done);
};

/**
 * A scanout's picture shown by the renderer (SURFACE_PRESENT): the
 * resource's rectangle (x, y, w, h) to (dx, dy) of a screen of width x
 * height; null takes it away
 * @param {?Resource3D} r
 */
Virgl.prototype.present_surface = function(r, x, y, w, h, dx, dy, width, height)
{
    this.gxw.command(GX.SURFACE_PRESENT, r ? [r.id, x, y, w, h, dx, dy, width, height] : [0, 0, 0, 0, 0, 0, 0, 0, 0]);
    this.flush();
};

/**
 * The picture of a scanout's resource (level 0, layer 0) into its `data`,
 * then `done` (the rows that came)
 * @param {!Resource3D} r
 * @param {function(number, number)} done first row, rows
 */
Virgl.prototype.read_picture = function(r, x, y, w, h, done)
{
    const { bytes: block_bytes } = r.block();
    const pitch = r.width * block_bytes;
    if(!r.data || r.data.length !== pitch * r.height) r.data = new Uint8Array(pitch * r.height);
    const row_bytes = w * block_bytes;
    const per_request = Math.max(1, Math.floor(READBACK_MAX_BYTES / row_bytes));
    for(let first = y; first < y + h; first += per_request)
    {
        const count = Math.min(per_request, y + h - first);
        const id = this.request(bytes => {
            if(!bytes) return;
            for(let row = 0; row < count; row++)
            {
                r.data.set(bytes.subarray(row * row_bytes, (row + 1) * row_bytes), (first + row) * pitch + x * block_bytes);
            }
            done(first, count);
        });
        this.gxw.command(GX.SURFACE_READBACK, [r.id, 0, 0, x, first, 0, w, count, 1, id]);
    }
    this.flush();
};

// ---------------------------------------------------------------------------
// Contexts

/** CTX_CREATE */
Virgl.prototype.create_context = function(ctx_id)
{
    if(this.contexts.has(ctx_id)) this.destroy_context(ctx_id);
    this.contexts.set(ctx_id, new VirglContext(this, ctx_id));
};

/** CTX_DESTROY */
Virgl.prototype.destroy_context = function(ctx_id)
{
    const context = this.contexts.get(ctx_id);
    if(!context) return;
    context.destroy();
    this.contexts.delete(ctx_id);
};

/**
 * SUBMIT_3D: a context's command stream
 * @param {number} ctx_id
 * @param {!Uint32Array} words
 * @param {function(number):?Object} resource by id
 */
Virgl.prototype.submit = function(ctx_id, words, resource)
{
    const context = this.contexts.get(ctx_id);
    if(!context)
    {
        this.warn_once("ctx" + ctx_id, "SUBMIT_3D for context " + ctx_id + ", which does not exist");
        return;
    }
    context.run(words, resource);
    this.flush_big();
};

// ---------------------------------------------------------------------------
// Snapshots: the resources' contents come back from GX before a save (a
// level's image per layer or slice), and go to GX again with the contexts

/**
 * The images of a resource, as save_contents reads them: [layer or slice,
 * level, width, height] each
 * @param {!Resource3D} r
 * @return {!Array<!Array<number>>}
 */
function images(r)
{
    const out = [];
    if(r.is_buffer()) return [[0, 0, r.width, 1]];
    const volume = r.target === TARGET.TEXTURE_3D;
    const layers = r.array_size;
    for(let level = 0; level <= r.last_level; level++)
    {
        const w = Math.max(1, r.width >> level), h = Math.max(1, r.height >> level);
        const count = volume ? Math.max(1, r.depth >> level) : layers;
        for(let i = 0; i < count; i++) out.push([i, level, w, h]);
    }
    return out;
}

/**
 * Every 3D resource's contents into `r.saved` (null where GX has none to
 * give: multisampled, depth), once the GPU has them
 * @param {!Array<!Resource3D>} resources
 * @return {!Promise}
 */
Virgl.prototype.save_contents = function(resources)
{
    for(const r of resources)
    {
        r.saved = [];
        if(r.nr_samples > 1 || !r.is_buffer() && !r.info) continue;
        const volume = r.target === TARGET.TEXTURE_3D;
        images(r).forEach(([i, level, w, h], k) => {
            if(r.is_buffer())
            {
                const bytes = new Uint8Array(w);
                r.saved[k] = bytes;
                for(let at = 0; at < w; at += READBACK_MAX_BYTES)
                {
                    const count = Math.min(READBACK_MAX_BYTES, w - at);
                    const id = this.request(data => { if(data) bytes.set(data.subarray(0, count), at); else r.saved[k] = null; });
                    this.gxw.command(GX.SURFACE_READBACK, [r.id, 0, 0, at, 0, 0, count, 1, 1, id]);
                }
                return;
            }
            const { bytes: block_bytes, bw, bh } = r.block();
            const row_bytes = Math.ceil(w / bw) * block_bytes, rows = Math.ceil(h / bh);
            const image = new Uint8Array(row_bytes * rows);
            r.saved[k] = image;
            const per_request = Math.max(1, Math.floor(READBACK_MAX_BYTES / row_bytes));
            for(let first = 0; first < rows; first += per_request)
            {
                const count = Math.min(per_request, rows - first);
                const id = this.request(data => {
                    if(data) image.set(data.subarray(0, count * row_bytes), first * row_bytes);
                    else r.saved[k] = null;
                });
                this.gxw.command(GX.SURFACE_READBACK, [r.id, volume ? 0 : i, level, 0, first * bh, volume ? i : 0,
                    w, Math.min(count * bh, h - first * bh), 1, id]);
            }
        });
    }
    return new Promise(resolve => this.after_work(() => resolve(undefined)));
};

/**
 * A resource from a snapshot: made in GX again, with what it had
 * @param {!Resource3D} r with `saved`
 */
Virgl.prototype.restore_resource = function(r)
{
    if(!this.create_resource(r)) return;
    const volume = r.target === TARGET.TEXTURE_3D;
    images(r).forEach(([i, level, w, h], k) => {
        const data = r.saved && r.saved[k];
        if(!data) return;
        if(r.is_buffer())
        {
            this.gxw.command(GX.SURFACE_UPLOAD, [r.id, 0, 0, 0, 0, 0, w, 1, 1, w, w], data);
            return;
        }
        const { bytes: block_bytes, bw } = r.block();
        const row_bytes = Math.ceil(w / bw) * block_bytes;
        this.gxw.command(GX.SURFACE_UPLOAD, [r.id, volume ? 0 : i, level, 0, 0, volume ? i : 0, w, h, 1, row_bytes, data.length], data);
        this.flush_big();
    });
};

Virgl.prototype.get_state = function()
{
    const contexts = [];
    for(const context of this.contexts.values()) contexts.push(context.get_state());
    return [contexts, [...this.blob_templates]];
};

/**
 * @param {!Array} state from get_state
 * @param {function(number):?Object} resource by id
 */
Virgl.prototype.set_state = function(state, resource)
{
    this.contexts.clear();
    this.next_cid = 1;
    this.next_private_sid = 0xF0000000;
    this.blob_templates = new Map(state[1] || []);
    for(const saved of state[0])
    {
        const context = new VirglContext(this, saved[0]);
        context.set_state(saved, resource);
        this.contexts.set(saved[0], context);
    }
    this.flush();
};
                                                                                                                                                                       source/v64/src/graphics_adapters/virtio_gpu/virgl_caps.js                                           0000644 0000000 0000000 00000034557 00000000000 021032  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What virtio-gpu's 3D (virgl) tells the guest it can do: the formats, as
// SVGA3D formats GX has (src/graphics_adapters/vmware_svga/svga_dx_formats.js
// says what GX can do with each), and the capsets VIRGL (1) and VIRGL2 (2),
// struct virgl_caps_v1 and v2 of third_party/virgl/virgl_hw.h. Mesa's virgl
// driver derives its GL version from them (virgl_screen.c): GLSL 3.30, so
// OpenGL 3.3 and OpenGL ES 3.0.

import { DX_FORMATS } from "../vmware_svga/svga_dx_formats.js";
import * as C from "../vmware_svga/svga_constants.js";

// PIPE_TEXTURE_* (struct virtio_gpu_resource_create_3d's target)
export const TARGET = { BUFFER: 0, TEXTURE_1D: 1, TEXTURE_2D: 2, TEXTURE_3D: 3, TEXTURE_CUBE: 4, TEXTURE_RECT: 5,
    TEXTURE_1D_ARRAY: 6, TEXTURE_2D_ARRAY: 7, TEXTURE_CUBE_ARRAY: 8 };

/** The renderer's name in the capset (Mesa shows "virgl (<it>)") */
const RENDERER = "v86 GX on WebGPU";

// Swizzles (PIPE_SWIZZLE_*): what a sampler view of a format reads
const X = 0, Y = 1, Z = 2, W = 3, ZERO = 4, ONE = 5;

/**
 * virgl format (VIRGL_FORMAT_*) -> [SVGA3D format name, swizzle or null].
 * The legacy luminance/alpha/intensity formats are red (red and green)
 * formats read through a swizzle.
 * @type {!Object<number, !Array>}
 */
export const VIRGL_FORMATS = {
    1: ["SVGA3D_B8G8R8A8_UNORM", null],
    2: ["SVGA3D_B8G8R8X8_UNORM", null],
    5: ["SVGA3D_B5G5R5A1_UNORM", null],
    6: ["SVGA3D_B4G4R4A4_UNORM", null],
    7: ["SVGA3D_B5G6R5_UNORM", null],
    8: ["SVGA3D_R10G10B10A2_UNORM", null],
    9: ["SVGA3D_R8_UNORM", [X, X, X, ONE]],        // L8
    10: ["SVGA3D_R8_UNORM", [ZERO, ZERO, ZERO, X]], // A8
    11: ["SVGA3D_R8_UNORM", [X, X, X, X]],          // I8
    12: ["SVGA3D_R8G8_UNORM", [X, X, X, Y]],        // L8A8
    13: ["SVGA3D_R16_UNORM", [X, X, X, ONE]],       // L16
    16: ["SVGA3D_D16_UNORM", null],
    18: ["SVGA3D_D32_FLOAT", null],
    19: ["SVGA3D_D24_UNORM_S8_UINT", null],
    21: ["SVGA3D_D24_UNORM_S8_UINT", null],         // Z24X8
    28: ["SVGA3D_R32_FLOAT", null],
    29: ["SVGA3D_R32G32_FLOAT", null],
    30: ["SVGA3D_R32G32B32_FLOAT", null],
    31: ["SVGA3D_R32G32B32A32_FLOAT", null],
    48: ["SVGA3D_R16_UNORM", null],
    49: ["SVGA3D_R16G16_UNORM", null],
    51: ["SVGA3D_R16G16B16A16_UNORM", null],
    56: ["SVGA3D_R16_SNORM", null],
    57: ["SVGA3D_R16G16_SNORM", null],
    59: ["SVGA3D_R16G16B16A16_SNORM", null],
    64: ["SVGA3D_R8_UNORM", null],
    65: ["SVGA3D_R8G8_UNORM", null],
    67: ["SVGA3D_R8G8B8A8_UNORM", null],
    74: ["SVGA3D_R8_SNORM", null],
    75: ["SVGA3D_R8G8_SNORM", null],
    77: ["SVGA3D_R8G8B8A8_SNORM", null],
    91: ["SVGA3D_R16_FLOAT", null],
    92: ["SVGA3D_R16G16_FLOAT", null],
    94: ["SVGA3D_R16G16B16A16_FLOAT", null],
    95: ["SVGA3D_R8_UNORM", [X, X, X, ONE]],        // L8_SRGB (not decoded)
    100: ["SVGA3D_B8G8R8A8_UNORM_SRGB", null],
    101: ["SVGA3D_B8G8R8X8_UNORM_SRGB", null],
    104: ["SVGA3D_R8G8B8A8_UNORM_SRGB", null],
    105: ["SVGA3D_BC1_UNORM", [X, Y, Z, ONE]],      // DXT1_RGB
    106: ["SVGA3D_BC1_UNORM", null],
    107: ["SVGA3D_BC2_UNORM", null],
    108: ["SVGA3D_BC3_UNORM", null],
    109: ["SVGA3D_BC1_UNORM_SRGB", [X, Y, Z, ONE]],
    110: ["SVGA3D_BC1_UNORM_SRGB", null],
    111: ["SVGA3D_BC2_UNORM_SRGB", null],
    112: ["SVGA3D_BC3_UNORM_SRGB", null],
    113: ["SVGA3D_BC4_UNORM", null],
    114: ["SVGA3D_BC4_SNORM", null],
    115: ["SVGA3D_BC5_UNORM", null],
    116: ["SVGA3D_BC5_SNORM", null],
    124: ["SVGA3D_R11G11B10_FLOAT", null],
    125: ["SVGA3D_R9G9B9E5_SHAREDEXP", null],
    126: ["SVGA3D_D32_FLOAT_S8X24_UINT", null],
    134: ["SVGA3D_R8G8B8A8_UNORM", [X, Y, Z, ONE]],  // R8G8B8X8
    136: ["SVGA3D_X24_G8_UINT", [Y, ZERO, ZERO, ONE]],        // X24S8_UINT: the stencil of Z24_UNORM_S8_UINT
    138: ["SVGA3D_X32_G8X24_UINT", [Y, ZERO, ZERO, ONE]],     // X32_S8X24_UINT
    177: ["SVGA3D_R8_UINT", null],
    178: ["SVGA3D_R8G8_UINT", null],
    180: ["SVGA3D_R8G8B8A8_UINT", null],
    181: ["SVGA3D_R8_SINT", null],
    182: ["SVGA3D_R8G8_SINT", null],
    184: ["SVGA3D_R8G8B8A8_SINT", null],
    185: ["SVGA3D_R16_UINT", null],
    186: ["SVGA3D_R16G16_UINT", null],
    188: ["SVGA3D_R16G16B16A16_UINT", null],
    189: ["SVGA3D_R16_SINT", null],
    190: ["SVGA3D_R16G16_SINT", null],
    192: ["SVGA3D_R16G16B16A16_SINT", null],
    193: ["SVGA3D_R32_UINT", null],
    194: ["SVGA3D_R32G32_UINT", null],
    195: ["SVGA3D_R32G32B32_UINT", null],
    196: ["SVGA3D_R32G32B32A32_UINT", null],
    197: ["SVGA3D_R32_SINT", null],
    198: ["SVGA3D_R32G32_SINT", null],
    199: ["SVGA3D_R32G32B32_SINT", null],
    200: ["SVGA3D_R32G32B32A32_SINT", null],
    253: ["SVGA3D_R10G10B10A2_UINT", null],
    255: ["SVGA3D_BC7_UNORM", null],
    256: ["SVGA3D_BC7_UNORM_SRGB", null],
    257: ["SVGA3D_BC6H_SF16", null],
    258: ["SVGA3D_BC6H_UF16", null],
};

/** The formats a scanout (a page flip, a cursor) may have */
const SCANOUT_FORMATS = [1, 2, 67, 134];

/**
 * @param {number} format VIRGL_FORMAT_*
 * @return {?{svga: number, name: string, swizzle: Array<number>, can: string, vertex: string}}
 */
export function virgl_format(format)
{
    const entry = VIRGL_FORMATS[format];
    if(!entry) return null;
    const [name, swizzle] = entry;
    const gx = DX_FORMATS[name];
    if(!gx || !gx[0] && !gx[2]) return null;
    return { svga: C[name], name, swizzle, can: gx[1], vertex: gx[2] };
}

/**
 * The format bitmasks (struct virgl_supported_format_mask): bit n is format n
 * @param {function(?Object, number):boolean} test
 * @return {!Uint32Array} 16 dwords
 */
function format_mask(test)
{
    const mask = new Uint32Array(16);
    for(const key of Object.keys(VIRGL_FORMATS))
    {
        const n = +key;
        if(test(virgl_format(n), n)) mask[n >> 5] |= 1 << (n & 31);
    }
    return mask;
}

// struct virgl_caps_bool_set1, bit by bit
const BSET = {
    indep_blend_enable: 0, indep_blend_func: 1, cube_map_array: 2, shader_stencil_export: 3,
    conditional_render: 4, start_instance: 5, primitive_restart: 6, blend_eq_sep: 7, instanceid: 8,
    vertex_element_instance_divisor: 9, seamless_cube_map: 10, occlusion_query: 11, timer_query: 12,
    streamout_pause_resume: 13, texture_multisample: 14, fragment_coord_conventions: 15,
    depth_clip_disable: 16, seamless_cube_map_per_texture: 17, ubo: 18, color_clamping: 19,
    poly_stipple: 20, mirror_clamp: 21, texture_query_lod: 22, has_fp64: 23,
    has_tessellation_shaders: 24, has_indirect_draw: 25, has_sample_shading: 26, has_cull: 27,
    conditional_render_inverted: 28, derivative_control: 29, polygon_offset_clamp: 30,
    transform_feedback_overflow_query: 31,
};

// capability_bits
const VIRGL_CAP_TGSI_INVARIANT = 1 << 0;
const VIRGL_CAP_TEXTURE_VIEW = 1 << 1;
const VIRGL_CAP_COPY_IMAGE = 1 << 3;
const VIRGL_CAP_TXQS = 1 << 5;
const VIRGL_CAP_MEMORY_BARRIER = 1 << 6;
const VIRGL_CAP_COMPUTE_SHADER = 1 << 7;
const VIRGL_CAP_FB_NO_ATTACH = 1 << 8;
const VIRGL_CAP_ROBUST_BUFFER_ACCESS = 1 << 9;
// a surface's format says whether it encodes sRGB (GL_FRAMEBUFFER_SRGB)
const VIRGL_CAP_SRGB_WRITE_CONTROL = 1 << 15;
const VIRGL_CAP_FBO_MIXED_COLOR_FORMATS = 1 << 18;
const VIRGL_CAP_CLIP_HALFZ = 1 << 27;
// persistent, coherent mappings: HOST3D blobs in host visible memory
const VIRGL_CAP_ARB_BUFFER_STORAGE = 1 << 31;

// PIPE_PRIM_*: points, lines, line strip, triangles, triangle strip, and
// the adjacency ones (the rest Mesa converts: line loops, fans, quads, polygons)
const PRIM_MASK = 1 << 0 | 1 << 1 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13;

/** sizeof(struct virgl_caps_v1), sizeof(struct virgl_caps_v2) */
export const CAPS_V1_BYTES = 308;
export const CAPS_V2_BYTES = 1408;

/** The capsets: [id, max version, bytes] */
export const CAPSETS = [[1, 1, CAPS_V1_BYTES], [2, 2, CAPS_V2_BYTES]];

/**
 * A capset's contents: VIRGL (1) is virgl_caps_v1, VIRGL2 (2) virgl_caps_v2.
 * Level virgl is GL 3.3 / GLES 3.0; virgl43 GL 4.3 / GLES 3.2 (compute,
 * shader storage and images in fragment and compute shaders, tessellation,
 * doubles as GX does them (f32), indirect draws, 16 viewports, texture
 * views). A level's capsets never change (snapshots keep the level).
 * Level virgl43-hostmem adds persistent, coherent buffer mappings.
 * @param {number} id
 * @param {boolean=} gl43
 * @param {boolean=} buffer_storage
 * @return {!Uint8Array}
 */
export function capset(id, gl43, buffer_storage)
{
    const bytes = new Uint8Array(CAPS_V2_BYTES);
    const view = new DataView(bytes.buffer);
    const u32 = (at, value) => view.setUint32(at, value >>> 0, true);
    const i32 = (at, value) => view.setInt32(at, value, true);
    const f32 = (at, value) => view.setFloat32(at, value, true);
    const mask = (at, words) => words.forEach((w, i) => u32(at + i * 4, w));

    const sampler = format_mask(f => !!f && /[su]/.test(f.can));
    // (not through a swizzle: an A8 target is R8, where alpha would land in
    // red; RGBX only drops its alpha)
    const render = format_mask((f, n) => !!f && f.can.includes("r") && (!f.swizzle || n === 134));
    const depth = format_mask(f => !!f && f.can.includes("d"));
    const vertex = format_mask(f => !!f && !!f.vertex);
    // (no fragment_coord_conventions: D3D's fragment position is GL's upper
    // left, and Mesa moves it for the rest itself)
    let bset = 0;
    for(const name of ["indep_blend_enable", "indep_blend_func", "conditional_render", "primitive_restart",
        "blend_eq_sep", "instanceid", "vertex_element_instance_divisor", "seamless_cube_map", "occlusion_query",
        "timer_query", "texture_multisample", "depth_clip_disable", "ubo"])
    {
        bset |= 1 << BSET[name];
    }
    if(gl43)
    {
        for(const name of ["cube_map_array", "start_instance", "streamout_pause_resume", "texture_query_lod", "has_fp64",
            "has_tessellation_shaders", "has_indirect_draw", "has_sample_shading", "conditional_render_inverted",
            "derivative_control"])
        {
            bset |= 1 << BSET[name];
        }
    }

    // virgl_caps_v1
    u32(0, id === 1 ? 1 : 2);   // max_version
    mask(4, sampler);
    mask(68, render);
    mask(132, depth);
    mask(196, vertex);
    u32(260, bset);
    u32(264, gl43 ? 430 : 330); // glsl_level
    u32(268, 2048);             // max_texture_array_layers
    u32(272, 4);                // max_streamout_buffers
    u32(276, 1);                // max_dual_source_render_targets
    u32(280, 8);                // max_render_targets
    u32(284, 4);                // max_samples
    // (with tessellation: patches, else Mesa's primitive converter takes them, endlessly)
    u32(288, PRIM_MASK | (gl43 ? 1 << 14 : 0));
    u32(292, 1 << 16);          // max_tbo_size
    // the default uniform block and 13 UBOs: the 14 constant buffers of a D3D11 stage
    // (GL 4.3 wants 14 UBOs a stage: slots 0 to 14)
    u32(296, gl43 ? 15 : 14);   // max_uniform_blocks
    u32(300, gl43 ? 16 : 1);    // max_viewports
    u32(304, gl43 ? 4 : 0);     // max_texture_gather_components
    if(id === 1) return bytes.slice(0, CAPS_V1_BYTES);

    // virgl_caps_v2
    f32(308, 1); f32(312, 1);   // aliased point sizes (WebGPU draws 1-pixel points)
    f32(316, 1); f32(320, 1);   // smooth point sizes
    f32(324, 1); f32(328, 1);   // aliased line widths
    f32(332, 1); f32(336, 1);   // smooth line widths
    f32(340, 16);               // max_texture_lod_bias
    u32(344, 256);              // max_geom_output_vertices
    u32(348, 1024);             // max_geom_total_output_components
    u32(352, 16);               // max_vertex_outputs
    u32(356, 16);               // max_vertex_attribs
    u32(360, gl43 ? 30 : 0);    // max_shader_patch_varyings
    i32(364, -8); i32(368, 7);  // texel offsets
    if(gl43) { i32(372, -32); i32(376, 31); }  // texture gather offsets
    u32(380, 16);               // texture_buffer_offset_alignment
    u32(384, 256);              // uniform_buffer_offset_alignment
    u32(388, 256);              // shader_buffer_offset_alignment
    u32(392, VIRGL_CAP_TGSI_INVARIANT | VIRGL_CAP_SRGB_WRITE_CONTROL | VIRGL_CAP_FBO_MIXED_COLOR_FORMATS |
        VIRGL_CAP_CLIP_HALFZ | (gl43 ? VIRGL_CAP_TEXTURE_VIEW | VIRGL_CAP_COPY_IMAGE | VIRGL_CAP_TXQS | VIRGL_CAP_MEMORY_BARRIER |
        VIRGL_CAP_COMPUTE_SHADER | VIRGL_CAP_FB_NO_ATTACH | VIRGL_CAP_ROBUST_BUFFER_ACCESS : 0) |
        (buffer_storage ? VIRGL_CAP_ARB_BUFFER_STORAGE : 0));
    // sample_locations[1] is 4x (Mesa's virgl_get_sample_position): a byte
    // per sample, x and y in 16ths; GX supersamples it, the centres of a 2x2 block
    u32(396 + 4, 0xCC4CC444);
    u32(428, 2048);             // max_vertex_attrib_stride
    if(gl43)
    {
        // shader storage and images: fragment and compute shaders (D3D11's UAVs)
        u32(432, 8);            // max_shader_buffer_frag_compute
        u32(436, 0);            // max_shader_buffer_other_stages
        u32(440, 8);            // max_shader_image_frag_compute
        u32(444, 0);            // max_shader_image_other_stages
        u32(448, 0);            // max_image_samples
        u32(452, 1024);         // max_compute_work_group_invocations
        u32(456, 32768);        // max_compute_shared_memory_size
        for(let i = 0; i < 3; i++) u32(460 + 4 * i, 65535);   // max_compute_grid_size
        [1024, 1024, 64].forEach((n, i) => u32(472 + 4 * i, n)); // max_compute_block_size
    }
    u32(484, gl43 ? 16384 : 8192);  // max_texture_2d_size
    u32(488, 2048);             // max_texture_3d_size
    u32(492, gl43 ? 16384 : 8192);  // max_texture_cube_size
    if(gl43) u32(496, 8);       // max_combined_shader_buffers
    u32(556, 15);               // host_feature_check_version
    mask(560, format_mask(f => !!f && /[sud]/.test(f.can)));   // supported_readback_formats
    mask(624, format_mask((f, n) => SCANOUT_FORMATS.includes(n)));
    u32(688, 0);                // capability_bits_v2
    u32(692, 256);              // max_video_memory, in MiB
    const name = new TextEncoder().encode(RENDERER);
    bytes.set(name.subarray(0, 63), 696);
    f32(760, 16);               // max_anisotropy
    u32(764, 16);               // max_texture_samplers
    mask(768, render);          // supported_multisample_formats
    for(let i = 0; i < 6; i++) u32(832 + i * 4, 65536);  // max_const_buffer_size
    u32(856, 0);                // num_video_caps
    u32(1372, 65536);           // max_uniform_block_size
    // max_shader_storage_blocks by stage (vertex, fragment, geometry, tessellation control, evaluation, compute)
    if(gl43) [0, 8, 0, 0, 0, 8].forEach((n, i) => u32(1384 + 4 * i, n));
    u32(1372, 65536);           // max_uniform_block_size
    return bytes;
}
                                                                                                                                                 source/v64/src/graphics_adapters/virtio_gpu/virgl_context.js                                        0000644 0000000 0000000 00000174275 00000000000 021572  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // One virgl context: its command stream (VIRGL_CCMD_*, third_party/virgl/
// virgl_protocol.h) decoded command by command, and gallium's state turned
// into the SVGA DX commands GX runs, as Mesa's svga driver would send them:
//
// - each sub-context (one per GL context of the guest) is a GX context;
// - objects become DX objects with their handle as id (blend, depth-stencil,
//   samplers, element layouts, shader resource views, render target and
//   depth-stencil views, queries); rasterizer states and shaders have
//   variants, made when a draw needs them, with ids from VARIANT_ID up;
// - shaders are TGSI text, translated by tgsi_vgpu10.js for what a draw has
//   bound: the next stage's inputs (GL links by semantic, D3D by register),
//   the viewport's Y direction and depth range, sampler view swizzles;
// - state (viewports, framebuffer, buffers, views) is kept as gallium's and
//   sent at draws, the DX commands that changed only;
// - user constants (SET_CONSTANT_BUFFER) go into a buffer of the device's.
//
// Each command is a header dword (command, object type, length in dwords)
// and its payload.

import { GX } from "../renderer_protocol.js";
import { virgl_format, TARGET } from "./virgl_caps.js";
import { parse_tgsi } from "./tgsi.js";
import { tgsi_to_vgpu10, SVGA_SHADER_TYPE, IMAGE_UAV, GRID_CONSTANT_BUFFER } from "./tgsi_vgpu10.js";
import * as C from "../vmware_svga/svga_constants.js";

// VIRGL_CCMD_*
export const CCMD = {
    NOP: 0, CREATE_OBJECT: 1, BIND_OBJECT: 2, DESTROY_OBJECT: 3, SET_VIEWPORT_STATE: 4, SET_FRAMEBUFFER_STATE: 5,
    SET_VERTEX_BUFFERS: 6, CLEAR: 7, DRAW_VBO: 8, RESOURCE_INLINE_WRITE: 9, SET_SAMPLER_VIEWS: 10,
    SET_INDEX_BUFFER: 11, SET_CONSTANT_BUFFER: 12, SET_STENCIL_REF: 13, SET_BLEND_COLOR: 14, SET_SCISSOR_STATE: 15,
    BLIT: 16, RESOURCE_COPY_REGION: 17, BIND_SAMPLER_STATES: 18, BEGIN_QUERY: 19, END_QUERY: 20,
    GET_QUERY_RESULT: 21, SET_POLYGON_STIPPLE: 22, SET_CLIP_STATE: 23, SET_SAMPLE_MASK: 24,
    SET_STREAMOUT_TARGETS: 25, SET_RENDER_CONDITION: 26, SET_UNIFORM_BUFFER: 27, SET_SUB_CTX: 28,
    CREATE_SUB_CTX: 29, DESTROY_SUB_CTX: 30, BIND_SHADER: 31, SET_TESS_STATE: 32, SET_MIN_SAMPLES: 33,
    SET_SHADER_BUFFERS: 34, SET_SHADER_IMAGES: 35, MEMORY_BARRIER: 36, LAUNCH_GRID: 37,
    SET_FRAMEBUFFER_STATE_NO_ATTACH: 38, TEXTURE_BARRIER: 39, SET_ATOMIC_BUFFERS: 40, SET_DEBUG_FLAGS: 41,
    GET_QUERY_RESULT_QBO: 42, TRANSFER3D: 43, END_TRANSFERS: 44, COPY_TRANSFER3D: 45, SET_TWEAKS: 46,
    CLEAR_TEXTURE: 47, PIPE_RESOURCE_CREATE: 48, PIPE_RESOURCE_SET_TYPE: 49, GET_MEMORY_INFO: 50,
    SEND_STRING_MARKER: 51, LINK_SHADER: 52,
};
const CCMD_NAMES = [];
for(const name of Object.keys(CCMD)) CCMD_NAMES[CCMD[name]] = name;

// VIRGL_OBJECT_*
export const OBJECT = {
    NULL: 0, BLEND: 1, RASTERIZER: 2, DSA: 3, SHADER: 4, VERTEX_ELEMENTS: 5, SAMPLER_VIEW: 6, SAMPLER_STATE: 7,
    SURFACE: 8, QUERY: 9, STREAMOUT_TARGET: 10, MSAA_SURFACE: 11,
};

const INVALID = 0xFFFFFFFF;
/** The ids of DX objects that are variants (rasterizer states, shaders): above the guest's handles */
const VARIANT_ID = 0x80000000;
const CONSTANT_BUFFER_BYTES = 65536;
const STAGES = 6;
const PIPE_PRIM_PATCHES = 14;
const PIPE_SHADER = { VERTEX: 0, FRAGMENT: 1, GEOMETRY: 2, TESS_CTRL: 3, TESS_EVAL: 4, COMPUTE: 5 };

const f32 = (() => {
    const u = new Uint32Array(1), f = new Float32Array(u.buffer);
    return { from: bits => { u[0] = bits; return f[0]; }, bits: value => { f[0] = value; return u[0]; } };
})();

// gallium -> SVGA3D enums
// PIPE_BLENDFACTOR_* -> SVGA3D_BLENDOP_*
const BLEND_FACTOR = { 0x01: 2, 0x02: 3, 0x03: 5, 0x04: 7, 0x05: 9, 0x06: 11, 0x07: 12, 0x08: 18, 0x09: 14, 0x0A: 16,
    0x11: 1, 0x12: 4, 0x13: 6, 0x14: 8, 0x15: 10, 0x17: 13, 0x18: 19, 0x19: 15, 0x1A: 17 };
// PIPE_STENCIL_OP_* -> SVGA3D_STENCILOP_*
const STENCIL_OP = [1, 2, 3, 4, 5, 7, 8, 6];
// PIPE_TEX_WRAP_* -> SVGA3D_TEX_ADDRESS_*
const WRAP = [1, 3, 3, 4, 2, 5, 5, 5];
// PIPE_PRIM_* -> SVGA3dPrimitiveType (0: Mesa converts them)
const PRIMITIVE = [2, 3, 0, 4, 1, 5, 0, 0, 0, 0, 7, 8, 9, 10];
// PIPE_POLYGON_MODE_* -> SVGA3D_FILLMODE_*
const FILL = [3, 2, 1, 3];
const QUERY_PRIMITIVES_GENERATED = 6, QUERY_PRIMITIVES_EMITTED = 7;
// PIPE_QUERY_* -> SVGA3dQueryType (the others are answered by the device)
const QUERY_TYPE = { 0: C.SVGA3D_QUERYTYPE_OCCLUSION64, 1: C.SVGA3D_QUERYTYPE_OCCLUSIONPREDICATE, 2: C.SVGA3D_QUERYTYPE_OCCLUSIONPREDICATE,
    3: C.SVGA3D_QUERYTYPE_TIMESTAMP };

/**
 * One sub-context (a guest GL context): a GX context and gallium's state
 * @constructor
 */
function SubContext(context, cid)
{
    this.context = context;
    this.virgl = context.virgl;
    this.cid = cid;
    /** @type {!Map<number, !Object>} handle -> object ({kind: OBJECT.*, ...}) */
    this.objects = new Map();
    this.next_variant = VARIANT_ID;
    // gallium's state
    this.fb = { cbufs: [], zsurf: 0 };
    this.viewport = { scale: [1, 1, 1], translate: [0, 0, 0] };
    this.scissor = [0, 0, 0, 0];
    this.blend = 0;
    this.dsa = 0;
    this.rasterizer = 0;
    this.elements = 0;
    this.blend_color = [0, 0, 0, 0];
    this.stencil_ref = 0;
    this.sample_mask = INVALID;
    /** @type {!Array<?{stride: number, offset: number, res: number}>} */
    this.vertex_buffers = [];
    /** @type {?{res: number, size: number, offset: number}} */
    this.index_buffer = null;
    this.shaders = new Array(STAGES).fill(0);
    /** per stage: sampler view handles, sampler state handles */
    this.views = Array.from({ length: STAGES }, () => []);
    this.samplers = Array.from({ length: STAGES }, () => []);
    /** per stage and slot: {user: Uint32Array} or {res, offset, length} */
    this.cbs = Array.from({ length: STAGES }, () => []);
    /** the device's user constant buffers, per stage: {sid, data} */
    this.user_buffers = [];
    /** the device's buffer of widened 8-bit indices */
    this.index_scratch = null;
    /** the stream output targets (STREAMOUT_TARGET handles) */
    this.so_targets = [];
    /** @type {!Set<!Object>} the queries counting primitives that are running */
    this.counting = new Set();
    /** @type {Array<number>} the render condition (SET_PREDICATION's words) */
    this.predication = null;
    /** per stage: shader storage buffers ({res, offset, length}) and images ({res, format, ...}) */
    this.buffers = Array.from({ length: STAGES }, () => []);
    this.images = Array.from({ length: STAGES }, () => []);
    /** @type {!Map<string, number>} the UA views made of them, by what they view */
    this.ua_views = new Map();
    /** the device's buffer of a dispatch's grid size (gl_NumWorkGroups) */
    this.grid_buffer = 0;
    /** @type {!Map<string, string>} what was last sent, by command */
    this.sent = new Map();
    this.gx(GX.CONTEXT_DEFINE, [cid]);
}

/**
 * @param {number} op
 * @param {!IArrayLike<number>} words
 * @param {Uint8Array=} bytes
 */
SubContext.prototype.gx = function(op, words, bytes)
{
    this.virgl.gxw.command(op, words, bytes);
};

/** A DX command of this context */
SubContext.prototype.dx = function(id, words)
{
    const w = new Uint32Array(2 + words.length);
    w[0] = this.cid;
    w[1] = id;
    for(let i = 0; i < words.length; i++) w[2 + i] = words[i] >>> 0;
    this.gx(GX.DX, w);
};

/** ... sent only when it differs from what was sent last time under `key` */
SubContext.prototype.dx_changed = function(key, id, words)
{
    const text = words.join(",");
    if(this.sent.get(key) === text) return;
    this.sent.set(key, text);
    this.dx(id, words);
};

SubContext.prototype.destroy = function()
{
    this.gx(GX.CONTEXT_DESTROY, [this.cid]);
    for(const b of this.user_buffers) if(b) this.gx(GX.SURFACE_DESTROY, [b.sid]);
    if(this.index_scratch) this.gx(GX.SURFACE_DESTROY, [this.index_scratch.sid]);
};

SubContext.prototype.warn = function(key, text)
{
    this.virgl.warn_once(key, text);
};

// ---------------------------------------------------------------------------

/**
 * @constructor
 * @param {!Object} virgl the Virgl device side
 * @param {number} ctx_id
 */
export function VirglContext(virgl, ctx_id)
{
    this.virgl = virgl;
    this.ctx_id = ctx_id;
    /** @type {!Map<number, !SubContext>} */
    this.subs = new Map();
    /** a shader whose text comes in parts */
    this.pending_shader = null;
    /** @type {function(number):?Object} resources by id (during run) */
    this.resource = () => null;
    this.sub = this.sub_context(0);
}

VirglContext.prototype.sub_context = function(id)
{
    let sub = this.subs.get(id);
    if(!sub)
    {
        sub = new SubContext(this, this.virgl.next_cid++);
        this.subs.set(id, sub);
    }
    return sub;
};

VirglContext.prototype.destroy = function()
{
    for(const sub of this.subs.values()) sub.destroy();
    this.subs.clear();
};

/** A resource is gone: nothing of this context may name it any more */
VirglContext.prototype.forget_resource = function(id)
{
    for(const sub of this.subs.values())
    {
        sub.vertex_buffers = sub.vertex_buffers.map(b => b && b.res === id ? null : b);
        if(sub.index_buffer && sub.index_buffer.res === id) sub.index_buffer = null;
        for(const cbs of sub.cbs) for(let i = 0; i < cbs.length; i++) if(cbs[i] && cbs[i].res === id) cbs[i] = null;
    }
};

/**
 * A command stream
 * @param {!Uint32Array} words
 * @param {function(number):?Object} resource by id
 */
VirglContext.prototype.run = function(words, resource)
{
    this.resource = resource;
    let at = 0;
    while(at < words.length)
    {
        const header = words[at];
        const command = header & 0xFF, object = header >>> 8 & 0xFF, length = header >>> 16;
        if(at + 1 + length > words.length)
        {
            this.virgl.warn_once("truncated", "a virgl command (" + command + ") runs past its stream");
            break;
        }
        const p = words.subarray(at + 1, at + 1 + length);
        this.virgl.counts[command] = (this.virgl.counts[command] || 0) + 1;
        this.command(command, object, p);
        at += 1 + length;
    }
};

/**
 * @param {number} command VIRGL_CCMD_*
 * @param {number} object VIRGL_OBJECT_* (CREATE, BIND, DESTROY)
 * @param {!Uint32Array} p the payload
 */
VirglContext.prototype.command = function(command, object, p)
{
    const sub = this.sub;
    switch(command)
    {
        case CCMD.NOP:
        case CCMD.SET_DEBUG_FLAGS:
        case CCMD.SET_TWEAKS:
        case CCMD.SEND_STRING_MARKER:
        case CCMD.LINK_SHADER:
        case CCMD.END_TRANSFERS:
        case CCMD.TEXTURE_BARRIER:
        case CCMD.MEMORY_BARRIER:
        case CCMD.SET_MIN_SAMPLES:
        case CCMD.SET_POLYGON_STIPPLE:
        case CCMD.SET_CLIP_STATE:
            return;
        case CCMD.CREATE_SUB_CTX:
            this.sub_context(p[0]);
            return;
        case CCMD.SET_SUB_CTX:
            this.sub = this.sub_context(p[0]);
            return;
        case CCMD.DESTROY_SUB_CTX:
        {
            const gone = this.subs.get(p[0]);
            if(!gone || p[0] === 0) return;
            gone.destroy();
            this.subs.delete(p[0]);
            if(this.sub === gone) this.sub = this.sub_context(0);
            return;
        }
        case CCMD.RESOURCE_INLINE_WRITE:
            this.inline_write(p);
            return;
        case CCMD.CREATE_OBJECT:
            if(object === OBJECT.SHADER) this.create_shader(p);
            else this.create_object(sub, object, p);
            return;
        case CCMD.BIND_OBJECT:
            switch(object)
            {
                case OBJECT.BLEND: sub.blend = p[0]; return;
                case OBJECT.DSA: sub.dsa = p[0]; return;
                case OBJECT.RASTERIZER: sub.rasterizer = p[0]; return;
                case OBJECT.VERTEX_ELEMENTS: sub.elements = p[0]; return;
            }
            break;
        case CCMD.DESTROY_OBJECT:
            this.destroy_object(sub, p[0]);
            return;
        case CCMD.BIND_SHADER:
            if(p[1] < STAGES) sub.shaders[p[1]] = p[0];
            return;
        case CCMD.SET_VIEWPORT_STATE:
            // (one viewport: virgl's caps say so)
            if(p[0] === 0 && p.length >= 7)
            {
                sub.viewport = { scale: [0, 1, 2].map(i => f32.from(p[1 + i])), translate: [0, 1, 2].map(i => f32.from(p[4 + i])) };
            }
            return;
        case CCMD.SET_SCISSOR_STATE:
            if(p[0] === 0 && p.length >= 3) sub.scissor = [p[1] & 0xFFFF, p[1] >>> 16, p[2] & 0xFFFF, p[2] >>> 16];
            return;
        case CCMD.SET_FRAMEBUFFER_STATE:
            sub.fb = { zsurf: p[1], cbufs: Array.from(p.subarray(2, 2 + Math.min(p[0], 8))) };
            return;
        case CCMD.SET_FRAMEBUFFER_STATE_NO_ATTACH:
            // the size of drawing without attachments (Mesa sends it with
            // every framebuffer; GX takes the viewport's then)
            return;
        case CCMD.SET_VERTEX_BUFFERS:
            sub.vertex_buffers = [];
            for(let i = 0; 3 * i + 2 < p.length; i++)
            {
                sub.vertex_buffers.push(p[3 * i + 2] ? { stride: p[3 * i], offset: p[3 * i + 1], res: p[3 * i + 2] } : null);
            }
            return;
        case CCMD.SET_INDEX_BUFFER:
            sub.index_buffer = p.length >= 3 && p[0] ? { res: p[0], size: p[1], offset: p[2] } : null;
            return;
        case CCMD.SET_SAMPLER_VIEWS:
            if(p[0] < STAGES) p.subarray(2).forEach((handle, i) => { sub.views[p[0]][p[1] + i] = handle; });
            return;
        case CCMD.BIND_SAMPLER_STATES:
            if(p[0] < STAGES) p.subarray(2).forEach((handle, i) => { sub.samplers[p[0]][p[1] + i] = handle; });
            return;
        case CCMD.SET_CONSTANT_BUFFER:
            if(p[0] < STAGES) sub.cbs[p[0]][p[1]] = p.length > 2 ? { user: p.slice(2) } : null;
            return;
        case CCMD.SET_UNIFORM_BUFFER:
            if(p[0] < STAGES) sub.cbs[p[0]][p[1]] = p[4] ? { res: p[4], offset: p[2], length: p[3] } : null;
            return;
        case CCMD.SET_STENCIL_REF:
            sub.stencil_ref = p[0] & 0xFF;
            return;
        case CCMD.SET_BLEND_COLOR:
            sub.blend_color = [0, 1, 2, 3].map(i => f32.from(p[i]));
            return;
        case CCMD.SET_SAMPLE_MASK:
            sub.sample_mask = p[0];
            return;
        case CCMD.CLEAR:
            this.clear(sub, p);
            return;
        case CCMD.DRAW_VBO:
            this.draw(sub, p);
            return;
        case CCMD.BLIT:
            this.blit(sub, p);
            return;
        case CCMD.RESOURCE_COPY_REGION:
            this.copy_region(p);
            return;
        case CCMD.BEGIN_QUERY:
            this.begin_query(sub, p[0]);
            return;
        case CCMD.END_QUERY:
            this.end_query(sub, p[0]);
            return;
        case CCMD.GET_QUERY_RESULT:
            // (end_query writes the result once the GPU has it, and SUBMIT_3D
            // completes after that)
            return;
        case CCMD.SET_STREAMOUT_TARGETS:
            this.set_streamout_targets(sub, p);
            return;
        case CCMD.SET_SHADER_BUFFERS:
            // stage, first slot, then (offset, length, resource) each
            if(p[0] < STAGES)
            {
                for(let i = 0; 2 + 3 * i + 2 < p.length; i++)
                {
                    const w = 2 + 3 * i;
                    sub.buffers[p[0]][p[1] + i] = p[w + 2] ? { res: p[w + 2], offset: p[w], length: p[w + 1] } : null;
                }
            }
            return;
        case CCMD.SET_SHADER_IMAGES:
            // stage, first slot, then (format, access, first layer | last << 16 or buffer offset, level or buffer size, resource) each
            if(p[0] < STAGES)
            {
                for(let i = 0; 2 + 5 * i + 4 < p.length; i++)
                {
                    const w = 2 + 5 * i;
                    sub.images[p[0]][p[1] + i] = p[w + 4] ? { res: p[w + 4], format: p[w], layers: p[w + 2], level: p[w + 3] } : null;
                }
            }
            return;
        case CCMD.LAUNCH_GRID:
            this.launch_grid(sub, p);
            return;
        case CCMD.SET_TESS_STATE:
            // the default tessellation levels (a control shader always sets its own)
            return;
        case CCMD.PIPE_RESOURCE_CREATE:
            // a HOST3D blob's template (target, format, bind, width, height,
            // depth, array size, last level, samples, flags), which
            // RESOURCE_CREATE_BLOB takes by the blob id
            if(p.length >= 11) this.virgl.blob_templates.set(this.ctx_id + ":" + p[10], Array.from(p.subarray(0, 10)));
            return;
        case CCMD.SET_RENDER_CONDITION:
        {
            const q = p[0] && sub.objects.get(p[0]);
            sub.predication = q && q.defined ? [p[0], p[1] ? 1 : 0] : null;
            sub.dx_changed("predication", C.SVGA_3D_CMD_DX_SET_PREDICATION, sub.predication || [INVALID, 0]);
            return;
        }
    }
    this.virgl.warn_once("ccmd" + command, "virgl command " + (CCMD_NAMES[command] || command) + " is not supported yet");
};

// ---------------------------------------------------------------------------
// Objects

VirglContext.prototype.create_object = function(sub, kind, p)
{
    const handle = p[0];
    if(sub.objects.has(handle)) this.destroy_object(sub, handle);
    this.create_kind(sub, kind, p);
    // (what made it: a snapshot makes it again so)
    const o = sub.objects.get(handle);
    if(o)
    {
        o.create_kind = kind;
        o.create_words = Array.from(p);
    }
};

VirglContext.prototype.create_kind = function(sub, kind, p)
{
    const handle = p[0];
    switch(kind)
    {
        case OBJECT.BLEND: return this.create_blend(sub, p);
        case OBJECT.DSA: return this.create_dsa(sub, p);
        case OBJECT.RASTERIZER:
            sub.objects.set(handle, { kind, words: Array.from(p.subarray(1, 9)), variants: new Map() });
            return;
        case OBJECT.SAMPLER_STATE: return this.create_sampler(sub, p);
        case OBJECT.VERTEX_ELEMENTS: return this.create_elements(sub, p);
        case OBJECT.SAMPLER_VIEW: return this.create_view(sub, p);
        case OBJECT.SURFACE:
        case OBJECT.MSAA_SURFACE:
            return this.create_surface(sub, p);
        case OBJECT.QUERY: return this.create_query(sub, p);
        case OBJECT.STREAMOUT_TARGET:
            sub.objects.set(handle, { kind, res: p[1], offset: p[2], size: p[3] });
            return;
    }
    sub.warn("object" + kind, "virgl object type " + kind + " is not supported yet");
};

VirglContext.prototype.destroy_object = function(sub, handle)
{
    const o = sub.objects.get(handle);
    if(!o) return;
    sub.objects.delete(handle);
    switch(o.kind)
    {
        case OBJECT.BLEND: sub.dx(C.SVGA_3D_CMD_DX_DESTROY_BLEND_STATE, [handle]); break;
        case OBJECT.DSA: sub.dx(C.SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_STATE, [handle]); break;
        case OBJECT.RASTERIZER:
            for(const id of o.variants.values()) sub.dx(C.SVGA_3D_CMD_DX_DESTROY_RASTERIZER_STATE, [id]);
            break;
        case OBJECT.SAMPLER_STATE: sub.dx(C.SVGA_3D_CMD_DX_DESTROY_SAMPLER_STATE, [handle]); break;
        case OBJECT.VERTEX_ELEMENTS: sub.dx(C.SVGA_3D_CMD_DX_DESTROY_ELEMENTLAYOUT, [handle]); break;
        case OBJECT.SAMPLER_VIEW: if(o.defined) sub.dx(C.SVGA_3D_CMD_DX_DESTROY_SHADERRESOURCE_VIEW, [handle]); break;
        case OBJECT.SURFACE:
            if(o.defined) sub.dx(o.depth ? C.SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_VIEW : C.SVGA_3D_CMD_DX_DESTROY_RENDERTARGET_VIEW, [handle]);
            break;
        case OBJECT.QUERY: if(o.defined) sub.dx(C.SVGA_3D_CMD_DX_DESTROY_QUERY, [handle]); break;
        case OBJECT.SHADER:
            for(const v of o.variants.values())
            {
                sub.dx(C.SVGA_3D_CMD_DX_DESTROY_SHADER, [v.shid]);
                for(const soid of v.soids.values()) sub.dx(C.SVGA_3D_CMD_DX_DESTROY_STREAMOUTPUT, [soid]);
            }
            break;
    }
    // what named it is sent again (the same handle may come back as another object)
    sub.sent.clear();
};

/** BLEND: handle, S0 (independent, logic op, dither, alpha to coverage, alpha to one), S1 (logic op), S2 per render target */
VirglContext.prototype.create_blend = function(sub, p)
{
    const handle = p[0], s0 = p[1];
    const independent = s0 & 1, a2c = s0 >>> 3 & 1;
    if(s0 & 2) sub.warn("logicop", "virgl: blend logic ops are not supported yet");
    const factor = f => BLEND_FACTOR[f] || 2;
    const words = [handle, a2c | independent << 8];
    for(let i = 0; i < 8; i++)
    {
        const rt = p[3 + (independent ? i : 0)] || 0;
        words.push((rt & 1) | factor(rt >>> 4 & 0x1F) << 8 | factor(rt >>> 9 & 0x1F) << 16 | ((rt >>> 1 & 7) + 1) << 24,
            factor(rt >>> 17 & 0x1F) | factor(rt >>> 22 & 0x1F) << 8 | ((rt >>> 14 & 7) + 1) << 16 | (rt >>> 27 & 0xF) << 24,
            0);
    }
    sub.objects.set(handle, { kind: OBJECT.BLEND });
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_BLEND_STATE, words);
};

/** DSA: handle, S0 (depth; alpha test), S1 (front stencil), S2 (back stencil), alpha ref */
VirglContext.prototype.create_dsa = function(sub, p)
{
    const handle = p[0], s0 = p[1], front = p[2], back = p[3];
    const stencil = s => ({ enabled: s & 1, func: (s >>> 1 & 7) + 1, fail: STENCIL_OP[s >>> 4 & 7], zpass: STENCIL_OP[s >>> 7 & 7],
        zfail: STENCIL_OP[s >>> 10 & 7], read: s >>> 13 & 0xFF, write: s >>> 21 & 0xFF });
    // (a disabled back face stencil means the front's for both)
    const f = stencil(front), b = back & 1 ? stencil(back) : f;
    const words = [handle,
        (s0 & 1) | (s0 >>> 1 & 1) << 8 | ((s0 >>> 2 & 7) + 1) << 16 | f.enabled << 24,
        f.enabled | f.enabled << 8 | f.read << 16 | f.write << 24,
        f.fail | f.zfail << 8 | f.zpass << 16 | f.func << 24,
        b.fail | b.zfail << 8 | b.zpass << 16 | b.func << 24];
    sub.objects.set(handle, { kind: OBJECT.DSA, alpha: s0 >>> 8 & 1 ? { func: s0 >>> 9 & 7, ref: f32.from(p[4] || 0) } : null });
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE, words);
};

/** SAMPLER_STATE: handle, S0 (wraps, filters, compare, anisotropy), lod bias, min lod, max lod, border color */
VirglContext.prototype.create_sampler = function(sub, p)
{
    const handle = p[0], s0 = p[1];
    const min_linear = s0 >>> 9 & 1, mip = s0 >>> 11 & 3, mag_linear = s0 >>> 13 & 1, compare = s0 >>> 15 & 1;
    const anisotropy = s0 >>> 20 & 0x1F;
    let filter = (mip === 1 ? 1 : 0) | (mag_linear ? 4 : 0) | (min_linear ? 16 : 0);
    if(anisotropy > 1) filter |= 64;
    if(compare) filter |= 128;
    let min_lod = f32.from(p[3]), max_lod = f32.from(p[4]);
    // no mipmapping: the view's first level only
    if(mip === 2)
    {
        min_lod = 0;
        max_lod = 0;
    }
    const words = [handle, filter,
        WRAP[s0 & 7] | WRAP[s0 >>> 3 & 7] << 8 | WRAP[s0 >>> 6 & 7] << 16,
        p[2], Math.max(1, anisotropy) | ((s0 >>> 16 & 7) + 1) << 8,
        p[5], p[6], p[7], p[8], f32.bits(min_lod), f32.bits(max_lod)];
    sub.objects.set(handle, { kind: OBJECT.SAMPLER_STATE });
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE, words);
};

/** VERTEX_ELEMENTS: handle, then per element: offset, instance divisor, vertex buffer, format */
VirglContext.prototype.create_elements = function(sub, p)
{
    const handle = p[0];
    const words = [handle];
    for(let i = 0; 1 + 4 * i + 3 < p.length; i++)
    {
        const e = 1 + 4 * i;
        const info = virgl_format(p[e + 3]);
        if(!info || !info.vertex) sub.warn("vformat" + p[e + 3], "virgl vertex format " + p[e + 3] + " is not supported");
        words.push(p[e + 2], p[e], info ? info.svga : 0, p[e + 1] ? C.SVGA3D_INPUT_PER_INSTANCE_DATA : 0, p[e + 1], i);
    }
    sub.objects.set(handle, { kind: OBJECT.VERTEX_ELEMENTS });
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, words);
};

/** The SVGA3dResourceType of a resource */
function resource_dimension(r)
{
    switch(r.target)
    {
        case TARGET.BUFFER: return C.SVGA3D_RESOURCE_BUFFER;
        case TARGET.TEXTURE_1D:
        case TARGET.TEXTURE_1D_ARRAY: return C.SVGA3D_RESOURCE_TEXTURE1D;
        case TARGET.TEXTURE_3D: return C.SVGA3D_RESOURCE_TEXTURE3D;
        case TARGET.TEXTURE_CUBE:
        case TARGET.TEXTURE_CUBE_ARRAY: return C.SVGA3D_RESOURCE_TEXTURECUBE;
    }
    return C.SVGA3D_RESOURCE_TEXTURE2D;
}

/** The bytes of an element of a buffer view's format */
function element_bytes(name)
{
    if(/R32G32B32A32/.test(name)) return 16;
    if(/R32G32B32_/.test(name)) return 12;
    if(/R32G32_|R16G16B16A16/.test(name)) return 8;
    if(/R32_|R16G16_|R8G8B8A8|B8G8R8|R10G10B10A2|R11G11B10/.test(name)) return 4;
    if(/R16_|R8G8_/.test(name)) return 2;
    return 1;
}

/**
 * SAMPLER_VIEW: handle, resource, format (the target in the high byte),
 * layers (first | last << 16) or first element, levels (first | last << 8)
 * or last element, swizzle (3 bits each)
 */
VirglContext.prototype.create_view = function(sub, p)
{
    const handle = p[0];
    const r = this.resource(p[1]);
    const format = p[2] & 0xFFFFFF;
    const info = virgl_format(format);
    const view_swizzle = [0, 3, 6, 9].map(s => p[5] >>> s & 7);
    // the format's swizzle (L8 is R8 read as RRR1), then the view's
    const base = info && info.swizzle || [0, 1, 2, 3];
    const swizzle = view_swizzle.map(c => c <= 3 ? base[c] : c);
    const o = { kind: OBJECT.SAMPLER_VIEW, res: p[1], swizzle, defined: false };
    sub.objects.set(handle, o);
    if(!r || !r.three_d || !info)
    {
        sub.warn("view-format" + format, "virgl: a sampler view of format " + format + " or of an unknown resource");
        return;
    }
    let desc;
    if(r.is_buffer())
    {
        // first and last element (of the view's format)
        desc = [p[3], Math.max(0, p[4] - p[3] + 1), 0, 0];
    }
    else
    {
        const first_level = p[4] & 0xFF, last_level = p[4] >>> 8 & 0xFF;
        const first_layer = p[3] & 0xFFFF, last_layer = p[3] >>> 16;
        // (SVGA3dShaderResourceViewDesc: most detailed mip, first slice, mips, slices)
        desc = [first_level, first_layer, last_level - first_level + 1, Math.max(1, last_layer - first_layer + 1)];
    }
    o.defined = true;
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW, [handle, p[1], info.svga, resource_dimension(r), ...desc]);
};

/** SURFACE: handle, resource, format, level (or first element), layers (first | last << 16, or last element) */
VirglContext.prototype.create_surface = function(sub, p)
{
    const handle = p[0];
    const r = this.resource(p[1]);
    const info = virgl_format(p[2]);
    const o = { kind: OBJECT.SURFACE, res: p[1], depth: false, defined: false, integer: false, signed: false };
    sub.objects.set(handle, o);
    if(!r || !r.three_d || !info)
    {
        sub.warn("surface-format" + p[2], "virgl: a surface of format " + p[2] + " or of an unknown resource");
        return;
    }
    o.depth = info.can.includes("d");
    o.integer = /_[US]INT$/.test(info.name) && !o.depth;
    o.signed = /_SINT$/.test(info.name);
    const level = p[3], first = p[4] & 0xFFFF, last = p[4] >>> 16;
    const words = [handle, p[1], info.svga, resource_dimension(r), level, first, Math.max(1, last - first + 1)];
    o.defined = true;
    sub.dx(o.depth ? C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW : C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, words);
};

/** QUERY: handle, type | index << 16, offset, resource (where the result goes) */
VirglContext.prototype.create_query = function(sub, p)
{
    const handle = p[0], type = p[1] & 0xFFFF;
    const svga = QUERY_TYPE[type];
    const o = { kind: OBJECT.QUERY, type, svga: svga === undefined ? -1 : svga, offset: p[2], res: p[3], defined: false };
    sub.objects.set(handle, o);
    if(o.svga < 0) return;
    o.defined = true;
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_QUERY, [handle, o.svga, 0]);
};

/**
 * CREATE_OBJECT SHADER: handle, type, offlen (the text's length, or with
 * bit 31 where this part goes), number of tokens, stream output (count,
 * then with outputs 4 strides and 2 dwords per output), then the TGSI
 * text, maybe over several commands
 */
VirglContext.prototype.create_shader = function(p)
{
    const handle = p[0], type = p[1], offlen = p[2];
    // (a compute shader has its shared memory's size where the others have
    // their stream output)
    const compute = type === PIPE_SHADER.COMPUTE;
    const so_count = compute ? 0 : p[4];
    const header = 5 + (so_count && !(offlen >>> 31) ? 4 + 2 * so_count : 0);
    const text = new Uint8Array(p.buffer, p.byteOffset + header * 4, Math.max(0, p.length - header) * 4);
    let pending;
    if(offlen >>> 31)
    {
        pending = this.pending_shader;
        if(!pending || pending.handle !== handle) return;
        const at = offlen & 0x7FFFFFFF;
        pending.bytes.set(text.subarray(0, Math.max(0, pending.bytes.length - at)), at);
        pending.got = at + text.length;
    }
    else
    {
        pending = { handle, type, bytes: new Uint8Array(offlen), got: text.length,
            so: so_count ? Array.from(p.subarray(5, 5 + 4 + 2 * so_count)) : null, shared: compute ? p[4] : 0, sub: this.sub };
        pending.bytes.set(text.subarray(0, offlen));
        this.pending_shader = pending;
    }
    if(pending.got < pending.bytes.length) return;
    this.pending_shader = null;
    let end = pending.bytes.indexOf(0);
    if(end < 0) end = pending.bytes.length;
    const source = new TextDecoder().decode(pending.bytes.subarray(0, end));
    if(this.virgl.shader_log) this.virgl.shader_log(pending.type, source);
    this.define_shader(pending.sub, handle, pending.type, source, pending.so, pending.shared);
};

/**
 * A shader object: its TGSI parsed (variants are made at draws)
 * @param {Array<number>} so_words its stream output
 * @param {number=} shared a compute shader's shared memory, in bytes
 */
VirglContext.prototype.define_shader = function(sub, handle, type, source, so_words, shared)
{
    if(sub.objects.has(handle)) this.destroy_object(sub, handle);
    let program = null;
    try
    {
        program = parse_tgsi(source);
    }
    catch(e)
    {
        sub.warn("tgsi:" + e.message, "virgl: a shader does not parse: " + e.message);
    }
    if(program) program.shared = shared || 0;
    sub.objects.set(handle, { kind: OBJECT.SHADER, stage: type, program, variants: new Map(), so: stream_output_info(so_words),
        source, so_words, shared: shared || 0 });
};

/**
 * RESOURCE_INLINE_WRITE: res, level, usage, stride, layer_stride, box
 * (x, y, z, w, h, d), then the bytes
 */
VirglContext.prototype.inline_write = function(p)
{
    const r = this.resource(p[0]);
    if(!r || !r.three_d || p.length < 11) return;
    const bytes = new Uint8Array(p.buffer, p.byteOffset + 11 * 4, (p.length - 11) * 4);
    const [level, , stride, layer_stride, x, y, z, w, h, d] = p.subarray(1, 11);
    this.virgl.transfer_to_host(r, [x, y, z, w, h, d], level, 0, stride, layer_stride, (from, out, to, length) => {
        if(from + length > bytes.length) return false;
        out.set(bytes.subarray(from, from + length), to);
        return true;
    });
    this.virgl.wrote(r);
};

// ---------------------------------------------------------------------------
// Drawing

/** The 3D resources of the framebuffer's surfaces: the GPU has written them */
VirglContext.prototype.written = function(sub)
{
    for(const handle of [...sub.fb.cbufs, sub.fb.zsurf])
    {
        const s = handle && sub.objects.get(handle);
        const r = s && this.resource(s.res);
        if(r && r.three_d) this.virgl.wrote(r);
    }
};

/** CLEAR: buffers (PIPE_CLEAR_*), color (4 dwords), depth (a double), stencil */
VirglContext.prototype.clear = function(sub, p)
{
    const buffers = p[0];
    sub.fb.cbufs.forEach((handle, i) => {
        if(!(buffers & 4 << i) || !handle) return;
        const s = sub.objects.get(handle);
        if(!s || !s.defined || s.depth) return;
        // integer targets get their values as integers
        if(s.integer) sub.gx(GX.CLEAR_RTV_INTEGER, [sub.cid, handle, s.signed ? 1 : 0, p[1], p[2], p[3], p[4]]);
        else sub.dx(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, [handle, p[1], p[2], p[3], p[4]]);
    });
    if(buffers & 3 && sub.fb.zsurf)
    {
        const s = sub.objects.get(sub.fb.zsurf);
        if(s && s.defined && s.depth)
        {
            const depth = new Float64Array(new Uint32Array([p[5], p[6]]).buffer)[0];
            sub.dx(C.SVGA_3D_CMD_DX_CLEAR_DEPTHSTENCIL_VIEW, [(buffers & 3) | (p[7] & 0xFF) << 16, sub.fb.zsurf, f32.bits(depth)]);
        }
    }
    this.written(sub);
};

/**
 * A shader's variant for `key`: translated, defined in GX
 * @return {?{shid: number, inputs: !Object<string, number>}}
 */
VirglContext.prototype.variant = function(sub, handle, key)
{
    const o = sub.objects.get(handle);
    if(!o || o.kind !== OBJECT.SHADER || !o.program) return null;
    const text = JSON.stringify(key);
    let v = o.variants.get(text);
    if(v) return v;
    const result = tgsi_to_vgpu10(o.program, key);
    for(const problem of result.problems) sub.warn("tgsi-" + problem, "virgl: shaders with " + problem + " are not supported yet");
    const shid = sub.next_variant++;
    const type = SVGA_SHADER_TYPE[o.program.processor];
    const bytes = new Uint8Array(result.tokens.buffer, result.tokens.byteOffset, result.tokens.byteLength);
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_SHADER, [shid, type, bytes.length]);
    sub.gx(GX.SHADER_CODE, [sub.cid, shid, type], bytes);
    v = { shid, inputs: result.inputs, outputs: result.outputs, soids: new Map() };
    o.variants.set(text, v);
    return v;
};

/**
 * The tessellator's settings, from the evaluation shader's properties (and
 * the control shader's output control points)
 * @return {?{domain: string, partitioning: number, output_primitive: number, in_cps: number, out_cps: number}}
 */
VirglContext.prototype.tessellator = function(sub, tes, tcs, in_cps)
{
    const e = sub.objects.get(tes), c = sub.objects.get(tcs);
    if(!e || !e.program || !c || !c.program) return null;
    const prop = (o, name, value) => +((o.program.properties[name] || [value])[0]);
    const domain = { 1: "isoline", 4: "tri", 7: "quad" }[prop(e, "TES_PRIM_MODE", 7)] || "quad";
    // PIPE_TESS_SPACING_* (fractional odd, fractional even, equal) -> VGPU10's partitioning
    const partitioning = [3, 4, 1][prop(e, "TES_SPACING", 2)] || 1;
    // (GL's clockwise is D3D's counter-clockwise: Mesa's svga does so)
    const output_primitive = prop(e, "TES_POINT_MODE", 0) ? 1 : domain === "isoline" ? 2 : prop(e, "TES_VERTEX_ORDER_CW", 0) ? 4 : 3;
    return { domain, partitioning, output_primitive, in_cps, out_cps: prop(c, "TCS_VERTICES_OUT", in_cps) };
};

/** The swizzles of a stage's sampler views (for its shader's key) */
function view_swizzles(sub, stage)
{
    return sub.views[stage].map(handle => {
        const v = handle && sub.objects.get(handle);
        return v && v.swizzle || [0, 1, 2, 3];
    });
}

/**
 * The rasterizer state's DX object, made at its first draw. (Its front face
 * is right as it is: Mesa flips it for framebuffer objects, whose Y the
 * vertex stage flips, and so gallium's window coordinates are D3D's.)
 */
VirglContext.prototype.rasterizer_variant = function(sub)
{
    const o = sub.objects.get(sub.rasterizer);
    if(!o || o.kind !== OBJECT.RASTERIZER) return INVALID;
    let id = o.variants.get("dx");
    if(id !== undefined) return id;
    const [s0, , , s3, line_width, units, scale, clamp] = o.words;
    const cull = s0 >>> 8 & 3;
    if(cull === 3) sub.warn("cull-both", "virgl: culling both faces is not supported");
    const front_ccw = s0 >>> 15 & 1;
    const offset = s0 >>> 20 & 1;
    id = sub.next_variant++;
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE_V2, [id,
        FILL[s0 >>> 10 & 3] | [1, 2, 3, 2][cull] << 8 | front_ccw << 16 | (s0 >>> 4 & 1 ? 0 : 1) << 24,
        offset ? Math.round(f32.from(units)) : 0, offset ? clamp : 0, offset ? scale : 0,
        (s0 >>> 1 & 1) | (s0 >>> 14 & 1) << 8 | (s0 >>> 25 & 1) << 16 | (s0 >>> 26 & 1) << 24,
        line_width, (s0 >>> 27 & 1) | (s3 >>> 16 & 0xFF) << 8 | (s3 & 0xFFFF) << 16, 0]);
    o.variants.set("dx", id);
    return id;
};

/** A stage's user constants, in the device's buffer for them */
VirglContext.prototype.user_constants = function(sub, stage, data)
{
    let b = sub.user_buffers[stage];
    if(!b)
    {
        b = sub.user_buffers[stage] = { sid: this.virgl.next_private_sid++, data: null };
        sub.gx(GX.SURFACE_DEFINE, [b.sid, C.SVGA3D_BUFFER, 0, 0, CONSTANT_BUFFER_BYTES, 1, 1, 1, 1, 0, 0]);
    }
    if(b.data !== data)
    {
        b.data = data;
        const bytes = new Uint8Array(data.buffer, data.byteOffset, Math.min(data.byteLength, CONSTANT_BUFFER_BYTES));
        sub.gx(GX.SURFACE_UPLOAD, [b.sid, 0, 0, 0, 0, 0, bytes.length, 1, 1, bytes.length, bytes.length], bytes);
    }
    return b.sid;
};

/** A stage's bindings: constant buffers, sampler views, samplers */
VirglContext.prototype.bind_stage = function(sub, stage)
{
    const type = stage + 1;
    const cbs = sub.cbs[stage];
    for(let slot = 0; slot < 15; slot++)
    {
        const cb = cbs[slot];
        const key = "cb" + stage + ":" + slot;
        if(!cb && !sub.sent.has(key)) continue;
        let words;
        if(!cb) words = [slot, type, INVALID, 0, 0];
        else if(cb.user) words = [slot, type, this.user_constants(sub, stage, cb.user), 0, CONSTANT_BUFFER_BYTES];
        else words = [slot, type, cb.res, cb.offset, cb.length];
        sub.dx_changed(key, C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER, words);
    }
    const views = sub.views[stage].map(handle => {
        const v = handle && sub.objects.get(handle);
        return v && v.defined ? handle : INVALID;
    });
    if(views.length) sub.dx_changed("srv" + stage, C.SVGA_3D_CMD_DX_SET_SHADER_RESOURCES, [0, type, ...views]);
    const samplers = sub.samplers[stage].map(handle => handle && sub.objects.has(handle) ? handle : INVALID);
    if(samplers.length) sub.dx_changed("sampler" + stage, C.SVGA_3D_CMD_DX_SET_SAMPLERS, [0, type, ...samplers]);
};

/**
 * DRAW_VBO: start, count, mode, indexed, instance count, index bias, start
 * instance, primitive restart, restart index, min and max index, count from
 * stream output (then tessellation and indirect draws)
 */
VirglContext.prototype.draw = function(sub, p)
{
    const [start, count, mode, indexed, instances, index_bias, start_instance] = p;
    // (patches: SVGA's patch lists, by the vertices a patch has)
    const topology = mode === PIPE_PRIM_PATCHES ? 10 + Math.max(1, Math.min(32, p[12] || 1)) : PRIMITIVE[mode];
    if(!topology)
    {
        sub.warn("prim" + mode, "virgl: primitive " + mode + " is not supported");
        return;
    }
    // indirect: a buffer of D3D's arguments too (GL's are the same), count draws stride apart
    const indirect = p.length > 14 && p[14] ? { res: p[14], offset: p[15], stride: p[16], count: p[17], count_res: p[19] } : null;
    if(indirect && indirect.count_res) sub.warn("indirect-count", "virgl: indirect draw counts are not supported yet");
    const vs = sub.shaders[PIPE_SHADER.VERTEX], fs = sub.shaders[PIPE_SHADER.FRAGMENT], gs = sub.shaders[PIPE_SHADER.GEOMETRY];
    const tes = mode === PIPE_PRIM_PATCHES ? sub.shaders[PIPE_SHADER.TESS_EVAL] : 0;
    const tcs = tes ? sub.shaders[PIPE_SHADER.TESS_CTRL] : 0;
    if(this.virgl.debug_log && mode === PIPE_PRIM_PATCHES) this.virgl.debug_log("patches " + JSON.stringify({ tes, tcs, p: Array.from(p) }));
    if(tes && !tcs)
    {
        sub.warn("no-tcs", "virgl: tessellation without a control shader is not supported yet");
        return;
    }
    if(!vs) return;
    const rs = sub.objects.get(sub.rasterizer);
    const s0 = rs && rs.kind === OBJECT.RASTERIZER ? rs.words[0] : 0;
    const halfz = !!(s0 >>> 2 & 1);
    // gallium's Y scale: positive draws GL's way up (framebuffer objects)
    const flip_y = sub.viewport.scale[1] > 0;
    const dsa = sub.objects.get(sub.dsa);
    const fs_key = {
        color_buffers: sub.fb.cbufs.length,
        swizzles: view_swizzles(sub, PIPE_SHADER.FRAGMENT),
        flatshade: !!(s0 & 1),
    };
    // GL's clip distances (the rasterizer state's clip_plane_enable)
    const clip_enable = rs && rs.kind === OBJECT.RASTERIZER ? rs.words[3] >>> 24 & 0xFF : 0;
    if(clip_enable) fs_key.clip_enable = clip_enable;
    if(dsa && dsa.alpha)
    {
        fs_key.alpha_func = dsa.alpha.func;
        fs_key.alpha_ref = dsa.alpha.ref;
    }
    const fsv = fs ? this.variant(sub, fs, fs_key) : null;
    const fs_inputs = fsv ? fsv.inputs : {};
    let vsv, gsv = null;
    // (what stream output captures must be in output registers)
    const streaming = sub.so_targets.some(t => t);
    const all_outputs = handle => streaming && !!this.shader_so(sub, handle);
    let tesv = null, tcsv = null;
    // the stages from the last to the first: each writes where the next reads
    let next = fs_inputs;
    if(gs)
    {
        gsv = this.variant(sub, gs, { outputs: next, all_outputs: all_outputs(gs), flip_y, halfz,
            swizzles: view_swizzles(sub, PIPE_SHADER.GEOMETRY) });
        next = gsv ? gsv.inputs : {};
    }
    if(tes)
    {
        const t = this.tessellator(sub, tes, tcs, p[12] || 1);
        if(!t) return;
        tesv = this.variant(sub, tes, { outputs: next, all_outputs: !gs && all_outputs(tes), flip_y: !gs && flip_y, halfz: gs ? true : halfz,
            cps: t.out_cps, swizzles: view_swizzles(sub, PIPE_SHADER.TESS_EVAL) });
        tcsv = tesv && this.variant(sub, tcs, { outputs: tesv.inputs, in_cps: t.in_cps, domain: t.domain, partitioning: t.partitioning,
            output_primitive: t.output_primitive, swizzles: view_swizzles(sub, PIPE_SHADER.TESS_CTRL) });
        if(!tcsv) return;
        next = tcsv.inputs;
    }
    const last = !gs && !tes;
    vsv = this.variant(sub, vs, { outputs: next, all_outputs: last && all_outputs(vs), flip_y: last && flip_y, halfz: last ? halfz : true,
        swizzles: view_swizzles(sub, PIPE_SHADER.VERTEX) });
    if(!vsv) return;
    // primitives counted for the queries running (before rasterizer discard)
    if(sub.counting.size)
    {
        const prims = primitive_count(mode, count) * Math.max(1, instances);
        for(const q of sub.counting) q.count += prims;
    }
    // stream output: of the last vertex stage, into the targets bound
    const discard = !!(s0 >>> 3 & 1);
    const soid = this.stream_output(sub, gs ? gs : tes ? tes : vs, gs ? gsv : tes ? tesv : vsv, discard);
    if(discard && soid === INVALID) return;
    sub.dx_changed("soid", C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT, [soid]);
    sub.dx_changed("vs", C.SVGA_3D_CMD_DX_SET_SHADER, [vsv.shid, C.SVGA3D_SHADERTYPE_VS]);
    sub.dx_changed("gs", C.SVGA_3D_CMD_DX_SET_SHADER, [gsv ? gsv.shid : INVALID, C.SVGA3D_SHADERTYPE_GS]);
    sub.dx_changed("hs", C.SVGA_3D_CMD_DX_SET_SHADER, [tcsv ? tcsv.shid : INVALID, C.SVGA3D_SHADERTYPE_HS]);
    sub.dx_changed("ds", C.SVGA_3D_CMD_DX_SET_SHADER, [tesv ? tesv.shid : INVALID, C.SVGA3D_SHADERTYPE_DS]);
    sub.dx_changed("ps", C.SVGA_3D_CMD_DX_SET_SHADER, [fsv ? fsv.shid : INVALID, C.SVGA3D_SHADERTYPE_PS]);
    this.bind_stage(sub, PIPE_SHADER.VERTEX);
    this.bind_stage(sub, PIPE_SHADER.FRAGMENT);
    if(gs) this.bind_stage(sub, PIPE_SHADER.GEOMETRY);
    if(tes)
    {
        this.bind_stage(sub, PIPE_SHADER.TESS_CTRL);
        this.bind_stage(sub, PIPE_SHADER.TESS_EVAL);
    }
    // (UAVs: the fragment stage's; D3D11 has them there and in compute)
    sub.dx_changed("uavs", C.SVGA_3D_CMD_DX_SET_UA_VIEWS, [0, ...this.ua_views(sub, PIPE_SHADER.FRAGMENT)]);

    // fixed function
    sub.dx_changed("rasterizer", C.SVGA_3D_CMD_DX_SET_RASTERIZER_STATE, [this.rasterizer_variant(sub)]);
    sub.dx_changed("blend", C.SVGA_3D_CMD_DX_SET_BLEND_STATE, [sub.objects.has(sub.blend) ? sub.blend : INVALID,
        ...sub.blend_color.map(f32.bits), sub.sample_mask]);
    sub.dx_changed("depth", C.SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE, [sub.objects.has(sub.dsa) ? sub.dsa : INVALID, sub.stencil_ref]);
    const rtvs = sub.fb.cbufs.map(handle => {
        const s = handle && sub.objects.get(handle);
        return s && s.defined && !s.depth ? handle : INVALID;
    });
    const z = sub.fb.zsurf && sub.objects.get(sub.fb.zsurf);
    sub.dx_changed("targets", C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, [z && z.defined && z.depth ? sub.fb.zsurf : INVALID, ...rtvs]);
    // the viewport as D3D's (Y down, depth from min to max)
    const [sx, sy, sz] = sub.viewport.scale, [tx, ty, tz] = sub.viewport.translate;
    const ax = Math.abs(sx), ay = Math.abs(sy);
    const near = halfz ? tz : tz - sz, far = tz + sz;
    sub.dx_changed("viewport", C.SVGA_3D_CMD_DX_SET_VIEWPORTS, [0,
        f32.bits(tx - ax), f32.bits(ty - ay), f32.bits(2 * ax), f32.bits(2 * ay),
        f32.bits(Math.max(0, Math.min(near, far))), f32.bits(Math.min(1, Math.max(near, far)))]);
    sub.dx_changed("scissor", C.SVGA_3D_CMD_DX_SET_SCISSORRECTS, [0, ...sub.scissor]);

    // vertices
    sub.dx_changed("layout", C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, [sub.objects.has(sub.elements) ? sub.elements : INVALID]);
    const buffers = [0];
    for(const b of sub.vertex_buffers)
    {
        if(b && this.resource(b.res)) buffers.push(b.res, b.stride, b.offset);
        else buffers.push(INVALID, 0, 0);
    }
    if(buffers.length > 1) sub.dx_changed("vbs", C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, buffers);
    sub.dx_changed("topology", C.SVGA_3D_CMD_DX_SET_TOPOLOGY, [topology]);

    const n = Math.max(1, instances);
    if(this.virgl.debug_log) this.virgl.debug_log("draw " + JSON.stringify({ mode, topology, count, start, indexed, n, indirect,
        vs: vsv && vsv.shid, tcs: tcsv && tcsv.shid, tes: tesv && tesv.shid, gs: gsv && gsv.shid, fs: fsv && fsv.shid, flip_y, halfz }));
    if(indirect)
    {
        if(indexed)
        {
            const ib = sub.index_buffer;
            if(!ib || ib.size === 1) return;
            sub.dx_changed("ib", C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER, [ib.res, ib.size === 4 ? C.SVGA3D_R32_UINT : C.SVGA3D_R16_UINT, ib.offset]);
        }
        const id = indexed ? C.SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED_INDIRECT : C.SVGA_3D_CMD_DX_DRAW_INSTANCED_INDIRECT;
        const size = indexed ? 20 : 16;
        for(let i = 0; i < Math.max(1, indirect.count); i++)
        {
            sub.dx(id, [indirect.res, indirect.offset + i * (indirect.stride || size)]);
        }
    }
    else if(p.length > 11 && p[11])
    {
        // as many vertices as stream output wrote into vertex buffer 0
        sub.dx(C.SVGA_3D_CMD_DX_DRAW_AUTO, []);
    }
    else if(indexed)
    {
        const ib = sub.index_buffer;
        if(!ib) return;
        let sid = ib.res, offset = ib.offset, format = ib.size === 4 ? C.SVGA3D_R32_UINT : C.SVGA3D_R16_UINT;
        if(ib.size === 1)
        {
            // D3D has no 8-bit indices: the guest's copy, widened
            sid = this.widen_indices(sub, ib, count, !!p[7]);
            if(!sid) return;
            offset = 0;
            format = C.SVGA3D_R16_UINT;
        }
        sub.dx_changed("ib", C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER, [sid, format, offset]);
        // (the index buffer's offset has the first index already)
        if(n > 1 || start_instance) sub.dx(C.SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED, [count, n, 0, index_bias, start_instance]);
        else sub.dx(C.SVGA_3D_CMD_DX_DRAW_INDEXED, [count, 0, index_bias]);
    }
    else
    {
        if(n > 1 || start_instance) sub.dx(C.SVGA_3D_CMD_DX_DRAW_INSTANCED, [count, n, start, start_instance]);
        else sub.dx(C.SVGA_3D_CMD_DX_DRAW, [count, start]);
    }
    this.written(sub);
    this.virgl.flush_big();
};

/**
 * A stage's shader storage buffers and images as UA views (raw buffers at
 * u0 on, typed images at u8 on): 64 view ids
 * @return {!Array<number>}
 */
VirglContext.prototype.ua_views = function(sub, stage)
{
    const ids = new Array(64).fill(INVALID);
    const view = (key, words) => {
        let id = sub.ua_views.get(key);
        if(id === undefined)
        {
            id = sub.next_variant++;
            sub.ua_views.set(key, id);
            sub.dx(C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW, [id, ...words]);
        }
        return id;
    };
    sub.buffers[stage].forEach((b, slot) => {
        const r = b && this.resource(b.res);
        if(!r || !r.three_d) return;
        // raw: in dwords
        ids[slot] = view("b" + [b.res, b.offset, b.length], [b.res, C.SVGA3D_R32_TYPELESS, C.SVGA3D_RESOURCE_BUFFER,
            b.offset >>> 2, Math.max(1, b.length >>> 2), C.SVGA3D_UABUFFER_RAW, 0]);
        this.virgl.wrote(r);
    });
    sub.images[stage].forEach((image, slot) => {
        const r = image && this.resource(image.res);
        const info = image && virgl_format(image.format);
        if(!r || !r.three_d || !info || IMAGE_UAV + slot >= 64) return;
        const first = image.layers & 0xFFFF, last = image.layers >>> 16;
        const desc = r.is_buffer() ? [image.layers, Math.max(1, image.level), 0, 0] :
            [image.level, first, Math.max(1, last - first + 1), 0];
        ids[IMAGE_UAV + slot] = view("i" + [image.res, image.format, image.layers, image.level],
            [image.res, info.svga, resource_dimension(r), ...desc]);
        this.virgl.wrote(r);
    });
    return ids;
};

/**
 * LAUNCH_GRID: block size, grid size, then an indirect buffer and offset
 * (the grid size from there)
 */
VirglContext.prototype.launch_grid = function(sub, p)
{
    const cs = sub.shaders[PIPE_SHADER.COMPUTE];
    const v = cs && this.variant(sub, cs, { swizzles: view_swizzles(sub, PIPE_SHADER.COMPUTE) });
    if(!v) return;
    sub.dx_changed("cs", C.SVGA_3D_CMD_DX_SET_SHADER, [v.shid, C.SVGA3D_SHADERTYPE_CS]);
    this.bind_stage(sub, PIPE_SHADER.COMPUTE);
    sub.dx_changed("csuavs", C.SVGA_3D_CMD_DX_SET_CS_UA_VIEWS, [0, ...this.ua_views(sub, PIPE_SHADER.COMPUTE)]);
    // the grid size, for gl_NumWorkGroups
    if(!sub.grid_buffer)
    {
        sub.grid_buffer = this.virgl.next_private_sid++;
        sub.gx(GX.SURFACE_DEFINE, [sub.grid_buffer, C.SVGA3D_BUFFER, 0, 0, 256, 1, 1, 1, 1, 0, 0]);
    }
    const indirect = p.length > 6 && p[6] ? this.resource(p[6]) : null;
    if(indirect) sub.gx(GX.SURFACE_COPY, [p[6], 0, 0, p[7], 0, 0, sub.grid_buffer, 0, 0, 0, 0, 0, 12, 1, 1]);
    else
    {
        const grid = new Uint8Array(Uint32Array.of(p[3], p[4], p[5], 0).buffer);
        sub.gx(GX.SURFACE_UPLOAD, [sub.grid_buffer, 0, 0, 0, 0, 0, 16, 1, 1, 16, 16], grid);
    }
    sub.dx_changed("cb5:" + GRID_CONSTANT_BUFFER, C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER,
        [GRID_CONSTANT_BUFFER, C.SVGA3D_SHADERTYPE_CS, sub.grid_buffer, 0, 256]);
    if(indirect) sub.dx(C.SVGA_3D_CMD_DX_DISPATCH_INDIRECT, [p[6], p[7]]);
    else sub.dx(C.SVGA_3D_CMD_DX_DISPATCH, [p[3], p[4], p[5]]);
    this.virgl.flush_big();
};

/**
 * 8-bit indices as 16-bit ones in a buffer of the device's, from the
 * guest's copy (with primitive restart, 0xFF restarts as 0xFFFF)
 */
VirglContext.prototype.widen_indices = function(sub, ib, count, restart)
{
    const r = this.resource(ib.res);
    if(!r || !r.backing) return 0;
    const bytes = new Uint8Array(count);
    if(!this.virgl.gpu.read_backing(r, ib.offset, bytes, 0, count)) return 0;
    const wide = new Uint16Array(count + 1 & ~1);
    wide.set(bytes);
    if(restart) for(let i = 0; i < count; i++) if(wide[i] === 0xFF) wide[i] = 0xFFFF;
    if(!sub.index_scratch || sub.index_scratch.bytes < wide.byteLength)
    {
        if(sub.index_scratch) sub.gx(GX.SURFACE_DESTROY, [sub.index_scratch.sid]);
        const size = Math.max(4096, wide.byteLength * 2);
        sub.index_scratch = { sid: this.virgl.next_private_sid++, bytes: size };
        sub.gx(GX.SURFACE_DEFINE, [sub.index_scratch.sid, C.SVGA3D_BUFFER, 0, 0, size, 1, 1, 1, 1, 0, 0]);
    }
    const data = new Uint8Array(wide.buffer);
    sub.gx(GX.SURFACE_UPLOAD, [sub.index_scratch.sid, 0, 0, 0, 0, 0, data.length, 1, 1, data.length, data.length], data);
    return sub.index_scratch.sid;
};

/** How many primitives a draw of `count` vertices of mode `mode` (PIPE_PRIM_*) makes */
function primitive_count(mode, count)
{
    switch(mode)
    {
        case 0: return count;
        case 1: return count >> 1;
        case 3: return Math.max(0, count - 1);
        case 4: return Math.floor(count / 3);
        case 5: return Math.max(0, count - 2);
        case 10: return count >> 2;
        case 11: return Math.max(0, count - 3);
        case 12: return Math.floor(count / 6);
        case 13: return Math.max(0, (count - 4) >> 1);
    }
    return 0;
}

/**
 * A shader's stream output (CREATE_OBJECT SHADER's): 4 strides in dwords,
 * then per output: register | start component << 8 | components << 10 |
 * buffer << 13 | offset in dwords << 16, and the stream
 * @return {?{strides: !Array<number>, outputs: !Array<!Object>}}
 */
function stream_output_info(words)
{
    if(!words) return null;
    const outputs = [];
    for(let at = 4; at + 1 < words.length; at += 2)
    {
        const w = words[at];
        outputs.push({ register: w & 0xFF, start: w >>> 8 & 3, components: w >>> 10 & 7, buffer: w >>> 13 & 7,
            offset: w >>> 16, stream: words[at + 1] & 3 });
    }
    return { strides: words.slice(0, 4), outputs };
}

/** A shader's stream output, if it has one */
VirglContext.prototype.shader_so = function(sub, handle)
{
    const o = sub.objects.get(handle);
    return o && o.kind === OBJECT.SHADER && o.so && o.so.outputs.length ? o.so : null;
};

/**
 * SET_STREAMOUT_TARGETS: the append mask, then the targets (STREAMOUT_TARGET
 * handles); an appended target goes on from where stream output got to
 */
VirglContext.prototype.set_streamout_targets = function(sub, p)
{
    const append = p[0];
    sub.so_targets = Array.from(p.subarray(1, 5));
    const words = [0];
    for(let i = 0; i < 4; i++)
    {
        const t = sub.so_targets[i] && sub.objects.get(sub.so_targets[i]);
        const r = t && t.kind === OBJECT.STREAMOUT_TARGET && this.resource(t.res);
        if(r)
        {
            words.push(t.res, append >> i & 1 ? INVALID : t.offset, t.size);
            if(r.three_d) this.virgl.wrote(r);
        }
        else words.push(INVALID, 0, 0);
    }
    // (sent each time: targets set again start from their offsets again)
    sub.dx(C.SVGA_3D_CMD_DX_SET_SOTARGETS, words);
};

/**
 * The stream output declaration of a shader variant (its outputs' registers),
 * defined once: INVALID without stream output
 * @param {boolean} discard nothing is rasterized
 */
VirglContext.prototype.stream_output = function(sub, handle, variant, discard)
{
    const so = sub.so_targets.some(t => t) && variant ? this.shader_so(sub, handle) : null;
    if(!so) return INVALID;
    // (the draw writes the targets)
    for(const target of sub.so_targets)
    {
        const t = target && sub.objects.get(target);
        const r = t && t.kind === OBJECT.STREAMOUT_TARGET && this.resource(t.res);
        if(r && r.three_d) this.virgl.wrote(r);
    }
    let soid = variant.soids.get(discard);
    if(soid !== undefined) return soid;
    // SVGA3dStreamOutputDeclarationEntry: buffer, register, mask, stream; gaps
    // (where nothing is written) as registers no shader has
    const entries = [], filled = [0, 0, 0, 0];
    const sorted = so.outputs.slice().sort((a, b) => a.buffer - b.buffer || a.offset - b.offset);
    for(const o of sorted)
    {
        while(filled[o.buffer] < o.offset)
        {
            const gap = Math.min(4, o.offset - filled[o.buffer]);
            entries.push([o.buffer, 0xFFFF, (1 << gap) - 1, o.stream]);
            filled[o.buffer] += gap;
        }
        const reg = variant.outputs[o.register];
        entries.push([o.buffer, reg === undefined ? 0xFFFF : reg, ((1 << o.components) - 1) << o.start, o.stream]);
        filled[o.buffer] += o.components;
    }
    soid = sub.next_variant++;
    const words = [soid, Math.min(entries.length, 64)];
    for(let i = 0; i < 64; i++) words.push(...(entries[i] || [0, 0, 0, 0]));
    words.push(...so.strides.map(s => s * 4), discard ? INVALID : 0);
    sub.dx(C.SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT, words);
    variant.soids.set(discard, soid);
    return soid;
};

// ---------------------------------------------------------------------------
// Copies

/**
 * BLIT: S0 (mask, filter, scissor, render condition, alpha blend), scissor,
 * destination (resource, level, format, x, y, z, w, h, d), source (same)
 */
VirglContext.prototype.blit = function(sub, p)
{
    const linear = (p[0] >>> 8 & 3) === 1;
    const dst = this.resource(p[3]), src = this.resource(p[12]);
    if(!dst || !src || !dst.three_d || !src.three_d) return;
    const [dx, dy, dz, dw, dh, dd] = Array.from(p.subarray(6, 12), v => v | 0);
    const [sx, sy, sz, sw, sh, sd] = Array.from(p.subarray(15, 21), v => v | 0);
    const dst_level = p[4], src_level = p[13];
    if(src.nr_samples > 1 && dst.nr_samples <= 1)
    {
        // a multisample resolve
        const info = virgl_format(p[5]);
        sub.dx(C.SVGA_3D_CMD_DX_RESOLVE_COPY, [p[3], dst_level, p[12], src_level, info ? info.svga : 0]);
    }
    else
    {
        const layers = Math.max(1, Math.min(Math.abs(dd), Math.abs(sd)));
        const volume_src = src.target === TARGET.TEXTURE_3D, volume_dst = dst.target === TARGET.TEXTURE_3D;
        for(let i = 0; i < layers; i++)
        {
            if(sw === dw && sh === dh && sw > 0 && sh > 0)
            {
                sub.gx(GX.SURFACE_COPY, [p[12], volume_src ? 0 : sz + i, src_level, sx, sy, volume_src ? sz + i : 0,
                    p[3], volume_dst ? 0 : dz + i, dst_level, dx, dy, volume_dst ? dz + i : 0, sw, sh, 1]);
            }
            else
            {
                sub.gx(GX.SURFACE_STRETCH, [p[12], volume_src ? 0 : sz + i, src_level, sx, sy, sx + sw, sy + sh,
                    p[3], volume_dst ? 0 : dz + i, dst_level, dx, dy, dx + dw, dy + dh, linear ? 1 : 0]);
            }
        }
    }
    this.virgl.wrote(dst);
};

/** RESOURCE_COPY_REGION: destination (resource, level, x, y, z), source (resource, level, x, y, z), size */
VirglContext.prototype.copy_region = function(p)
{
    const dst = this.resource(p[0]), src = this.resource(p[5]);
    if(!dst || !src || !dst.three_d || !src.three_d) return;
    const [dx, dy, dz] = [p[2], p[3], p[4]], [sx, sy, sz] = [p[7], p[8], p[9]], [w, h, d] = [p[10], p[11], p[12]];
    const gxw = this.virgl.gxw;
    if(src.is_buffer())
    {
        gxw.command(GX.SURFACE_COPY, [p[5], 0, 0, sx, 0, 0, p[0], 0, 0, dx, 0, 0, w, 1, 1]);
    }
    else if(src.target === TARGET.TEXTURE_3D)
    {
        gxw.command(GX.SURFACE_COPY, [p[5], 0, p[6], sx, sy, sz, p[0], 0, p[1], dx, dy, dz, w, h, d]);
    }
    else
    {
        for(let i = 0; i < Math.max(1, d); i++)
        {
            gxw.command(GX.SURFACE_COPY, [p[5], sz + i, p[6], sx, sy, 0, p[0], dz + i, p[1], dx, dy, 0, w, h, 1]);
        }
    }
    this.virgl.wrote(dst);
};

// ---------------------------------------------------------------------------
// Queries: the result goes into the query's resource, in guest memory
// (struct virgl_host_query_state: state, result size, result)

VirglContext.prototype.begin_query = function(sub, handle)
{
    const q = sub.objects.get(handle);
    if(!q || q.kind !== OBJECT.QUERY) return;
    if(q.defined) sub.dx(C.SVGA_3D_CMD_DX_BEGIN_QUERY, [handle]);
    else if(q.type === QUERY_PRIMITIVES_GENERATED || q.type === QUERY_PRIMITIVES_EMITTED)
    {
        q.count = 0;
        sub.counting.add(q);
    }
};

VirglContext.prototype.end_query = function(sub, handle)
{
    const q = sub.objects.get(handle);
    if(!q || q.kind !== OBJECT.QUERY) return;
    const r = this.resource(q.res);
    const write = value => {
        if(!r || !r.backing) return;
        const bytes = new Uint8Array(16);
        const view = new DataView(bytes.buffer);
        view.setUint32(0, 1, true);     // VIRGL_QUERY_STATE_DONE
        view.setUint32(4, 8, true);
        view.setUint32(8, value % 0x100000000, true);
        view.setUint32(12, Math.floor(value / 0x100000000), true);
        this.virgl.gpu.write_backing(r, q.offset, bytes);
    };
    if(!q.defined)
    {
        // primitives counted here; GPU_FINISHED is true, the rest 0
        sub.counting.delete(q);
        write(q.type === QUERY_PRIMITIVES_GENERATED || q.type === QUERY_PRIMITIVES_EMITTED ? q.count : q.type === 11 ? 1 : 0);
        return;
    }
    const id = this.virgl.request(bytes => {
        let value = 0;
        if(bytes && bytes.length >= 8)
        {
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            value = view.getUint32(0, true) + view.getUint32(4, true) * 0x100000000;
            if(q.type === 1 || q.type === 2) value = value ? 1 : 0;
        }
        write(value);
    });
    sub.gx(GX.QUERY_END, [sub.cid, handle, q.svga, id, 0]);
};

// ---------------------------------------------------------------------------
// Snapshots: each sub-context's objects (as the commands that made them, or
// a shader's text) and gallium's state; GX gets them again from these

/** The state of the sub-contexts that a snapshot keeps */
const SAVED_STATE = ["fb", "viewport", "scissor", "blend", "dsa", "rasterizer", "elements", "blend_color", "stencil_ref",
    "sample_mask", "vertex_buffers", "index_buffer", "shaders", "views", "samplers", "so_targets", "predication", "buffers", "images"];

VirglContext.prototype.get_state = function()
{
    const subs = [];
    let active = 0;
    for(const [id, sub] of this.subs)
    {
        if(sub === this.sub) active = id;
        const objects = [];
        for(const [handle, o] of sub.objects)
        {
            if(o.kind === OBJECT.SHADER) objects.push([OBJECT.SHADER, handle, o.stage, o.source, o.so_words || null, o.shared]);
            else if(o.create_words) objects.push([o.create_kind, handle, o.create_words]);
        }
        const state = {};
        for(const name of SAVED_STATE) state[name] = sub[name];
        state.cbs = sub.cbs.map(stage => stage.map(cb => cb ? (cb.user ? { user: Array.from(cb.user) } : cb) : null));
        subs.push([id, objects, JSON.stringify(state)]);
    }
    return [this.ctx_id, active, subs];
};

/**
 * @param {!Array} state from get_state
 * @param {function(number):?Object} resource by id
 */
VirglContext.prototype.set_state = function(state, resource)
{
    const [, active, subs] = state;
    this.resource = resource;
    for(const sub of this.subs.values()) sub.destroy();
    this.subs.clear();
    for(const [id, objects, json] of subs)
    {
        const sub = this.sub_context(id);
        for(const o of objects)
        {
            if(o[0] === OBJECT.SHADER) this.define_shader(sub, o[1], o[2], o[3], o[4], o[5]);
            else this.create_object(sub, o[0], Uint32Array.from(o[2], v => v >>> 0));
        }
        const saved = JSON.parse(json);
        for(const name of SAVED_STATE) if(saved[name] !== undefined) sub[name] = saved[name];
        sub.cbs = saved.cbs.map(stage => stage.map(cb => cb && cb.user ? { user: Uint32Array.from(cb.user) } : cb));
        sub.sent.clear();
        // what is sent when it is set, not at draws
        if(sub.so_targets.some(t => t)) this.set_streamout_targets(sub, Uint32Array.from([0xF, ...sub.so_targets]));
        if(sub.predication) sub.dx(C.SVGA_3D_CMD_DX_SET_PREDICATION, sub.predication);
    }
    this.sub = this.sub_context(active);
};
                                                                                                                                                                                                                                                                                                                                   source/v64/src/graphics_adapters/virtio_gpu/virtio_gpu_device.js                                    0000644 0000000 0000000 00000246365 00000000000 022411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-gpu as virtio-vga (1AF4:1050, class 0300): the VGA core for the
// BIOS, boot loaders and VBE (its frame buffer is BAR0), and the virtio-gpu
// device on the same function, its four capabilities in the memory BAR2
// (as QEMU's virtio-vga: viogpudo maps no I/O BARs).
// See docs/gpu-devices.md, "virtio-gpu"; the protocol is
// third_party/virtio/virtio_gpu.h.
//
// This file is the device: the control and cursor queues, 2D resources in
// host memory, filled from their guest backing by TRANSFER_TO_HOST_2D and
// shown on a scanout by RESOURCE_FLUSH, EDID, display events when the page's
// size changes (V86.set_display_size), guest and HOST3D blobs, the host
// visible memory (BAR4) and snapshots. 3D contexts are virgl.js's (virgl)
// and venus.js's (Venus). The screen shows the VGA core until the driver's
// first control command, and again after a device reset.
//
// On a machine without VGA (the virt machine's, machine.has_vga false;
// docs/arm64-virt-android16-plan.md P7.1) it is virtio-gpu-pci (class 0380)
// or a virtio-mmio device: no VGA core, no frame buffer BAR or ROM; until the
// driver's first command the screen is blank. The host visible memory is
// then BAR 2, 64 bits wide (the capabilities are in BAR 4, as QEMU's).

import { VGAScreen } from "../vga_core.js";
import { SoftwareCursor } from "../vmware_svga/svga_cursor.js";
import { make_edid } from "./edid.js";
import { Virgl, Resource3D } from "./virgl.js";
import { CAPSETS, capset } from "./virgl_caps.js";
import { Venus, VenusBlob } from "./venus.js";
import { Gfxstream, GfxstreamBlob } from "./gfxstream.js";
import { VulkanModel } from "./venus_vk.js";
import { GX } from "../renderer_protocol.js";

// For Types Only
import { GraphicsMachine } from "../machine.js";
import { DisplaySource } from "../../display.js";

const DEFAULT_VRAM_SIZE = 32 << 20;
// viogpudo only uses BAR0 as its frame buffer from 16 MiB
const MIN_VRAM_SIZE = 16 << 20;

const VIRTIO_GPU_DEVICE_ID = 0x1050;
const VIRTIO_GPU_SUBSYSTEM_ID = 0x1100;
const VGA_CLASS = 0x030000;
/** without VGA: a display controller of another kind, as QEMU's virtio-gpu-pci */
const DISPLAY_OTHER_CLASS = 0x038000;

// Feature bits
const VIRTIO_GPU_F_VIRGL = 0;
const VIRTIO_GPU_F_EDID = 1;
const VIRTIO_GPU_F_RESOURCE_UUID = 2;
const VIRTIO_GPU_F_RESOURCE_BLOB = 3;
const VIRTIO_GPU_F_CONTEXT_INIT = 4;
const VIRTIO_F_RING_INDIRECT_DESC = 28;

const CONTROLQ = 0;
const CURSORQ = 1;

// What the device declares, chosen at power-on and kept by snapshots, as
// vmware_svga's levels: a new feature needs a new level
const LEVELS = {
    "2d": { features: [VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_F_RING_INDIRECT_DESC] },
    // 3D: virgl contexts (Mesa's virgl driver), drawn by GX; needs a renderer
    "virgl": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_F_RING_INDIRECT_DESC], three_d: true },
    // ... and the capsets of OpenGL 4.3 / GLES 3.2 (virgl_caps.js)
    "virgl43": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_F_RING_INDIRECT_DESC], three_d: true,
        gl43: true },
    // blob resources in guest memory (scanouts straight from it), and
    // contexts of a capset (CONTEXT_INIT: virgl's)
    "2d-blob": { features: [VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_RESOURCE_BLOB, VIRTIO_F_RING_INDIRECT_DESC], blob: true },
    "virgl43-blob": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_RESOURCE_BLOB,
        VIRTIO_GPU_F_CONTEXT_INIT, VIRTIO_F_RING_INDIRECT_DESC], three_d: true, gl43: true, blob: true },
    // ... and blobs of the host's (HOST3D) mapped into host visible memory
    // (BAR4): persistent, coherent buffer mappings (ARB_buffer_storage)
    "virgl43-hostmem": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_RESOURCE_BLOB,
        VIRTIO_GPU_F_CONTEXT_INIT, VIRTIO_F_RING_INDIRECT_DESC], three_d: true, gl43: true, blob: true, hostmem: true },
    // ... and Vulkan: Venus contexts (Mesa's venus driver; venus.js)
    "venus": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_RESOURCE_BLOB,
        VIRTIO_GPU_F_CONTEXT_INIT, VIRTIO_F_RING_INDIRECT_DESC], three_d: true, gl43: true, blob: true, hostmem: true, venus: true },
    // gfxstream's contexts in place of virgl's (gfxstream.js; Android's
    // official images: docs/gfxstream-plan.md): its capsets only, as
    // rutabaga's gfxstream component offers them; a context without a
    // capset is gfxstream's too, and a pipe resource its process pipe
    "gfxstream": { features: [VIRTIO_GPU_F_VIRGL, VIRTIO_GPU_F_EDID, VIRTIO_GPU_F_RESOURCE_UUID, VIRTIO_GPU_F_RESOURCE_BLOB,
        VIRTIO_GPU_F_CONTEXT_INIT, VIRTIO_F_RING_INDIRECT_DESC], three_d: true, gl43: true, blob: true, hostmem: true, gfxstream: true },
};
const LEVEL_ORDER = ["2d", "2d-blob", "virgl", "virgl43", "virgl43-blob", "virgl43-hostmem", "venus", "gfxstream"];
/** Without a pinned level: the highest, with a renderer or without */
const DEFAULT_3D_LEVEL = "virgl43-hostmem";
const DEFAULT_LEVEL = "2d-blob";

// Commands
const CMD_GET_DISPLAY_INFO = 0x0100;
const CMD_RESOURCE_CREATE_2D = 0x0101;
const CMD_RESOURCE_UNREF = 0x0102;
const CMD_SET_SCANOUT = 0x0103;
const CMD_RESOURCE_FLUSH = 0x0104;
const CMD_TRANSFER_TO_HOST_2D = 0x0105;
const CMD_RESOURCE_ATTACH_BACKING = 0x0106;
const CMD_RESOURCE_DETACH_BACKING = 0x0107;
const CMD_GET_CAPSET_INFO = 0x0108;
const CMD_GET_CAPSET = 0x0109;
const CMD_GET_EDID = 0x010A;
const CMD_RESOURCE_ASSIGN_UUID = 0x010B;
const CMD_RESOURCE_CREATE_BLOB = 0x010C;
const CMD_SET_SCANOUT_BLOB = 0x010D;
const CMD_RESOURCE_MAP_BLOB = 0x0208;
const CMD_RESOURCE_UNMAP_BLOB = 0x0209;
const CMD_CTX_CREATE = 0x0200;
const CMD_CTX_DESTROY = 0x0201;
const CMD_CTX_ATTACH_RESOURCE = 0x0202;
const CMD_CTX_DETACH_RESOURCE = 0x0203;
const CMD_RESOURCE_CREATE_3D = 0x0204;
const CMD_TRANSFER_TO_HOST_3D = 0x0205;
const CMD_TRANSFER_FROM_HOST_3D = 0x0206;
const CMD_SUBMIT_3D = 0x0207;
const CMD_UPDATE_CURSOR = 0x0300;
const CMD_MOVE_CURSOR = 0x0301;

// Responses
const RESP_OK_NODATA = 0x1100;
const RESP_OK_DISPLAY_INFO = 0x1101;
const RESP_OK_CAPSET_INFO = 0x1102;
const RESP_OK_CAPSET = 0x1103;
const RESP_OK_EDID = 0x1104;
const RESP_OK_RESOURCE_UUID = 0x1105;
const RESP_OK_MAP_INFO = 0x1106;
const RESP_ERR_UNSPEC = 0x1200;
const RESP_ERR_OUT_OF_MEMORY = 0x1201;
const RESP_ERR_INVALID_SCANOUT_ID = 0x1202;
const RESP_ERR_INVALID_RESOURCE_ID = 0x1203;
const RESP_ERR_INVALID_CONTEXT_ID = 0x1204;
const RESP_ERR_INVALID_PARAMETER = 0x1205;

const FLAG_FENCE = 1;
const FLAG_INFO_RING_IDX = 2;

const EVENT_DISPLAY = 1;

const HEADER_SIZE = 24;
const MAX_SCANOUTS = 16;
const MAX_BACKING_ENTRIES = 16384;
// What resources may take of host memory (as QEMU's max_hostmem)
const MAX_HOST_MEMORY = 256 << 20;

const DEFAULT_WIDTH = 1024;
const DEFAULT_HEIGHT = 768;

/**
 * The formats (all 4 bytes per pixel, named in memory order): how a pixel,
 * read as a little-endian word, becomes RGBA (opaque)
 * @type {!Object<number, function(number):number>}
 */
const TO_RGBA = {
    // B8G8R8A8, B8G8R8X8
    1: w => w >>> 16 & 0xFF | w & 0xFF00 | (w & 0xFF) << 16 | 0xFF000000,
    2: w => w >>> 16 & 0xFF | w & 0xFF00 | (w & 0xFF) << 16 | 0xFF000000,
    // A8R8G8B8, X8R8G8B8
    3: w => w >>> 8 | 0xFF000000,
    4: w => w >>> 8 | 0xFF000000,
    // R8G8B8A8, R8G8B8X8
    67: w => w | 0xFF000000,
    134: w => w | 0xFF000000,
    // X8B8G8R8, A8B8G8R8
    68: w => w >>> 24 | (w >>> 16 & 0xFF) << 8 | (w >>> 8 & 0xFF) << 16 | 0xFF000000,
    121: w => w >>> 24 | (w >>> 16 & 0xFF) << 8 | (w >>> 8 & 0xFF) << 16 | 0xFF000000,
};

/**
 * The formats with alpha: the byte that holds it, in the little-endian word
 * @type {!Object<number, number>}
 */
const ALPHA_SHIFT = { 1: 24, 67: 24, 3: 0, 121: 0 };

/**
 * A resource: a 2D image in host memory, and the guest pages it is copied from
 * @constructor
 */
function Resource(id, format, width, height)
{
    this.id = id;
    this.format = format;
    this.width = width;
    this.height = height;
    this.data = new Uint8Array(width * height * 4);
    /** @type {Float64Array} the backing: address, length, ... */
    this.backing = null;
    /** @type {Float64Array} where each entry starts in the backing */
    this.backing_starts = null;
    this.backing_length = 0;
    /** @type {Uint8Array} RESOURCE_ASSIGN_UUID's */
    this.uuid = null;
}

Resource.prototype.set_backing = function(entries)
{
    this.backing = entries;
    this.backing_starts = new Float64Array(entries.length / 2);
    let length = 0;
    for(let i = 0; i < entries.length; i += 2)
    {
        this.backing_starts[i / 2] = length;
        length += entries[i + 1];
    }
    this.backing_length = length;
};

/** BLOB_MEM_GUEST: a blob's storage is guest memory; HOST3D: a 3D resource
 * of the host's, from a template of PIPE_RESOURCE_CREATE */
const BLOB_MEM_GUEST = 1;
const BLOB_MEM_HOST3D = 2;
const BLOB_FLAG_USE_MAPPABLE = 1;
/** MAP_BLOB's answer: the guest may cache the mapping */
const MAP_CACHE_CACHED = 1;

/** The host visible memory (BAR4, shared memory region 1), at level hostmem;
 * at level venus, mapped Vulkan memory lives there too; at gfxstream also
 * each guest thread's ring, a MiB each (Cuttlefish's hostmem=256M: with 128
 * MiB, 30 minutes of monkey left the guest's kernel without room for new
 * threads' rings, and their first Vulkan call crashed) */
const HOST_VISIBLE_SIZE = 64 << 20;
const VENUS_HOST_VISIBLE_SIZE = 128 << 20;
const GFXSTREAM_HOST_VISIBLE_SIZE = 256 << 20;
/** what of it Vulkan's host visible heap says it has (the rest: rings, replies) */
const VENUS_MEMORY_SIZE = VENUS_HOST_VISIBLE_SIZE - (16 << 20);
const HOST_VISIBLE_SHMID = 1;

/**
 * The host visible memory of a level (0: none), the device memory the
 * machine reserves for it
 * @param {string} level
 * @return {number}
 */
export function host_visible_size(level)
{
    const l = LEVELS[level];
    return !l || !l.hostmem ? 0 : l.gfxstream ? GFXSTREAM_HOST_VISIBLE_SIZE : l.venus ? VENUS_HOST_VISIBLE_SIZE : HOST_VISIBLE_SIZE;
}
const PAGE = 4096;

/**
 * A blob resource in guest memory (RESOURCE_CREATE_BLOB, BLOB_MEM_GUEST):
 * no copy of the host's; a scanout shows it as SET_SCANOUT_BLOB describes
 * @constructor
 */
function BlobResource(id, flags, size)
{
    this.id = id;
    this.blob = true;
    this.flags = flags;
    this.size = size;
    this.backing = null;
    this.backing_starts = null;
    this.backing_length = 0;
    this.uuid = null;
}
BlobResource.prototype.set_backing = Resource.prototype.set_backing;

/**
 * A display of the guest's
 * @constructor
 */
function Scanout(index)
{
    this.index = index;
    // what the page would like (GET_DISPLAY_INFO, the EDID); scanout 0 is always on
    this.enabled = index === 0;
    this.host_width = DEFAULT_WIDTH;
    this.host_height = DEFAULT_HEIGHT;
    // SET_SCANOUT: the resource (0: none) and the rectangle of it shown
    this.resource_id = 0;
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
    // where it is on the page's picture
    this.screen_x = 0;
    this.screen_y = 0;
    /** SET_SCANOUT_BLOB: the blob's picture (format, width, height, stride, offset) */
    this.blob = null;
    /** @type {Uint8ClampedArray} the flushed picture, RGBA */
    this.rgba = null;
    /** @type {Array<number>} the part of it not yet sent: x0, y0, x1, y1 */
    this.dirty = null;
    /** the resource the renderer shows itself (SURFACE_PRESENT), 0 when the
     * picture is the device's: `rgba` is then behind the GPU's */
    this.direct = 0;
}

Scanout.prototype.add_dirty = function(x0, y0, x1, y1)
{
    if(x0 >= x1 || y0 >= y1) return;
    const d = this.dirty;
    this.dirty = d ? [Math.min(d[0], x0), Math.min(d[1], y0), Math.max(d[2], x1), Math.max(d[3], y1)] : [x0, y0, x1, y1];
};

/**
 * In place of the VGA core on a machine without VGA: a blank text screen
 * while the driver has not taken over, nothing else
 * @constructor
 * @param {GraphicsMachine} machine
 */
function NoVGA(machine)
{
    this.display = machine.display;
    /** (no frame buffer: no address is in it) */
    this.lfb_address = Infinity;
    this.lfb_region = -1;
    this.svga_memory = new Uint8Array(0);
}
NoVGA.prototype.redisplay = function()
{
    this.display.set_mode(false);
    this.display.set_size_text(80, 25);
    this.display.clear_screen();
};
NoVGA.prototype.vblank_period = function() { return 1000 / 60; };
NoVGA.prototype.on_vblank = function() {};
NoVGA.prototype.invalidate = function() {};
NoVGA.prototype.render = function() {};
NoVGA.prototype.get_state = function() { return null; };
NoVGA.prototype.set_state = function(state) {};

/**
 * @constructor
 * @implements {DisplaySource}
 * @param {GraphicsMachine} machine
 * @param {{vram_size: (number|undefined), level: (string|undefined), scanouts: (number|undefined), renderer: (Object|undefined)}} options
 *     renderer: the channel to GX (the page's or a test's), which 3D needs
 */
export function VirtioGPU(machine, options)
{
    /** @const */
    this.machine = machine;
    /** @const */
    this.display = machine.display;

    /** @const the machine has VGA: the device is virtio-vga (else virtio-gpu, without VGA) */
    this.has_vga = machine.has_vga;
    const vram_size = options.vram_size || DEFAULT_VRAM_SIZE;
    if(this.has_vga && (vram_size < MIN_VRAM_SIZE || (vram_size & (vram_size - 1))))
    {
        throw new Error("virtio_gpu: vram_size must be a power of two of at least " + (MIN_VRAM_SIZE >> 20) + " MiB");
    }
    /** @const */
    this.vram_size = vram_size;

    this.level = options.level || (options.renderer ? DEFAULT_3D_LEVEL : DEFAULT_LEVEL);
    if(!LEVELS[this.level])
    {
        throw new Error("virtio_gpu: unknown level " + JSON.stringify(this.level) + "; levels: " + LEVEL_ORDER.join(", "));
    }
    if(LEVELS[this.level].three_d && !options.renderer)
    {
        throw new Error("virtio_gpu: level " + this.level + " needs a renderer (WebGPU)");
    }
    this.num_scanouts = Math.max(1, Math.min(MAX_SCANOUTS, options.scanouts || 1));

    // The VGA core: legacy VGA, VBE and the frame buffer (BAR0); this device
    // is the PCI function and the display source
    /** @const */
    this.vga = this.has_vga ? new VGAScreen(machine, vram_size, { pci: false, display_source: false }) :
        /** @type {?} */ (new NoVGA(machine));

    /** @type {!Map<number, (!Resource|!Resource3D|!BlobResource|!VenusBlob)>} 2D, 3D and blob resources */
    this.resources = new Map();
    this.host_memory = 0;
    /** @type {!Array<!Scanout>} */
    this.scanouts = [];
    for(let i = 0; i < this.num_scanouts; i++) this.scanouts.push(new Scanout(i));
    /** @const */
    this.cursor = new SoftwareCursor();
    this.events_read = 0;
    // the driver has sent a control command since the last reset: its
    // scanouts, not the VGA core, are on screen
    this.active = false;
    this.layout_key = "";
    /** a new layout went to the display: the next render sends all of the picture */
    this.layout_all = false;
    /** @type {Uint8ClampedArray} black, for displays that show nothing yet */
    this.blank = null;
    this.serial = 0x0086;
    /** What the driver has done, for harnesses and debugging */
    this.stats = { commands: {}, errors: 0, last_error: 0, transfers: 0, flushes: 0, cursor_updates: 0, cursor_moves: 0,
        /** the fences answered by lane ("" the global timeline, else ctx:ring): [count, the last fence id, its command] */
        fences: {},
        /** the first command the device failed on (an exception), answered with an error */
        failed_command: "" };
    /** @type {Virgl} 3D, at the virgl level */
    this.virgl = LEVELS[this.level].three_d ? new Virgl(this, /** @type {!Object} */ (options.renderer), !!LEVELS[this.level].gl43) : null;
    /** @type {Venus} Vulkan, at level venus */
    this.venus = LEVELS[this.level].venus ? new Venus(this, new VulkanModel({ host_visible_size: VENUS_MEMORY_SIZE, gpu: this })) : null;
    /** @type {!Array<!Object>} the kinds of context besides virgl's, each of
     * its capsets (CONTEXT_INIT): Venus (docs/gfxstream-plan.md G1) */
    /** @type {Gfxstream} gfxstream's contexts, at level gfxstream */
    this.gfxstream = LEVELS[this.level].gfxstream ? new Gfxstream(this, new VulkanModel({ host_visible_size: VENUS_MEMORY_SIZE, gpu: this })) : null;
    this.kinds = [this.venus, this.gfxstream].filter(Boolean);
    /** the capsets: [id, version, size] (gfxstream's alone at its level) */
    this.capsets = this.gfxstream ? this.gfxstream.capsets.slice() : this.virgl ? CAPSETS.concat(...this.kinds.map(kind => kind.capsets)) : [];
    /** @type {!Array<{request: !Object, bytes: !Uint8Array, response: !Uint8Array, ready: boolean}>}
     * control requests answered in the order they came: some wait for the GPU */
    this.pending = [];
    /** @type {?function(function())} set by a command whose answer waits */
    this.deferred = null;
    /** set with `deferred` by a command the ones after it wait for (virglrenderer runs
     * them in order: Venus's vkWaitRingSeqnoMESA before the blob of what the ring makes) */
    this.hold = false;
    this.held = false;
    /** a reset or a restore: answers and holds of the requests before it are not this machine's */
    this.generation = 0;
    /** @type {Array} a restored snapshot's requests not answered yet (get_state), queued again once its guest RAM is back */
    this.restored_requests = null;

    // The host visible memory: device memory of the core's, which the guest
    // reads and writes at memory speed; the pages it writes are uploaded into
    // the mapped blobs before each SUBMIT_3D, and blobs the GPU wrote are
    // read back into it before their fences complete
    this.hostmem_region = -1;
    this.hostmem_backing = 0;
    this.hostmem_size = host_visible_size(this.level) || HOST_VISIBLE_SIZE;
    /** @type {Uint32Array} pages written and not yet uploaded, as taken from the core */
    this.hostmem_pending = null;
    /** @type {!Map<number, (!Resource3D|!VenusBlob)>} the mapped blobs, by resource id */
    this.mapped = new Map();
    const bars = this.has_vga ? [{
        "bar": 0,
        "size": vram_size,
        "address": this.vga.lfb_address,
        "prefetchable": true,
        "on_move": base => this.vga.move_lfb(base),
    }] : [];
    // (without VGA, as QEMU's virtio-gpu-pci: BAR 2, 64 bits wide on the PCIe host)
    const hostmem_bar = this.has_vga ? 4 : 2;
    const shared_memory = [];
    if(LEVELS[this.level].hostmem)
    {
        this.hostmem_region = machine.mmio_ram_allocate(this.hostmem_size);
        if(this.hostmem_region < 0) throw new Error("virtio_gpu: no device memory for the host visible memory");
        this.hostmem_backing = machine.mmio_ram_backing(this.hostmem_region) >>> 0;
        this.hostmem_pending = new Uint32Array(Math.ceil(this.hostmem_size / PAGE / 64) * 2);
        // (a 32-bit BAR: the core decodes device memory below 4 GiB; the
        // firmware places it)
        bars.push({
            "bar": hostmem_bar,
            "size": this.hostmem_size,
            "address": 0,
            "prefetchable": true,
            "on_move": base => machine.mmio_ram_map(this.hostmem_region, base),
        });
        shared_memory.push({ "id": HOST_VISIBLE_SHMID, "bar": hostmem_bar, "offset": 0, "length": this.hostmem_size });
    }

    const features = LEVELS[this.level].features;
    this.virtio = machine.create_virtio({
        "name": "virtio-gpu",
        "device_id": VIRTIO_GPU_DEVICE_ID,
        "subsystem_device_id": VIRTIO_GPU_SUBSYSTEM_ID,
        "class_code": this.has_vga ? VGA_CLASS : DISPLAY_OTHER_CLASS,
        "revision": 1,
        "bars": bars,
        "shared_memory": shared_memory,
        // (as QEMU's virtio-vga; viogpudo maps only memory BARs)
        "capability_bar": 2,
        "pci_rom_size": this.has_vga ? this.vga.pci_rom_size : 0,
        "pci_rom_address": this.has_vga ? this.vga.pci_rom_address : 0,
        // (viogpudo needs QEMU's vector registers and ISR bits)
        "qemu_compatible": this.has_vga,
        "features": features,
        "queues": [{ "size": 256 }, { "size": 16 }],
        "config": [
            { "bytes": 4, "name": "events_read", "read": () => this.events_read },
            { "bytes": 4, "name": "events_clear", "read": () => 0, "write": value => { this.events_read &= ~value; } },
            { "bytes": 4, "name": "num_scanouts", "read": () => this.num_scanouts },
            { "bytes": 4, "name": "num_capsets", "read": () => this.capsets.length },
        ],
        "notify": queue => this.notify(queue),
        "reset": () => this.reset_device(),
    });

    machine.on_host_display_size((width, height, index) => this.set_host_size(index, width, height));
    // (Venus reads its rings whenever the machine's timers run)
    machine.display.add_timer(now => {
        if(this.restored_requests) this.requeue_restored();
        for(const kind of this.kinds) kind.timer(now);
        return 100;
    });
    this.display.add_source(this);
}

/**
 * The kind of context (Venus, ...) that has context ctx_id, or null (virgl's, or none)
 * @param {number} ctx_id
 * @return {Object}
 */
VirtioGPU.prototype.kind_of = function(ctx_id)
{
    return this.kinds.find(kind => kind.contexts.has(ctx_id)) || null;
};

/**
 * The kind of context of a capset, or null (virgl's)
 * @param {number} id
 * @return {Object}
 */
VirtioGPU.prototype.kind_of_capset = function(id)
{
    return this.kinds.find(kind => kind.capsets.some(c => c[0] === id)) || null;
};

/** A machine reset */
VirtioGPU.prototype.reset = function()
{
    this.virtio["reset"]();
};

/**
 * The driver reset the device (or the machine was reset): no resources, and
 * the VGA core is on screen again
 */
VirtioGPU.prototype.reset_device = function()
{
    // (requests popped before are stale: the transport drops their answers)
    this.forget_requests();
    if(this.virgl) this.virgl.reset();
    for(const kind of this.kinds) kind.reset();
    this.unmap_all();
    this.resources.clear();
    this.host_memory = 0;
    this.mapped.clear();
    if(this.hostmem_pending)
    {
        this.take_hostmem_dirty();
        this.hostmem_pending.fill(0);
    }
    for(const scanout of this.scanouts)
    {
        scanout.resource_id = 0;
        scanout.rgba = null;
        scanout.dirty = null;
    }
    this.cursor.reset();
    this.events_read = 0;
    this.set_active(false);
};

/** @param {boolean} active */
VirtioGPU.prototype.set_active = function(active)
{
    if(active === this.active) return;
    this.active = active;
    this.layout_key = "";
    if(!active)
    {
        // the core sends its mode and picture again
        this.vga.redisplay();
    }
};

/**
 * The page's size for a display: the guest learns it from GET_DISPLAY_INFO
 * and the EDID after a display event
 */
VirtioGPU.prototype.set_host_size = function(index, width, height)
{
    const scanout = this.scanouts[index];
    if(!scanout) return;
    const enabled = index === 0 || width > 0 && height > 0;
    if(width > 0 && height > 0)
    {
        width = Math.max(320, Math.min(8192, width));
        height = Math.max(200, Math.min(8192, height));
    }
    else
    {
        width = scanout.host_width;
        height = scanout.host_height;
    }
    if(enabled === scanout.enabled && width === scanout.host_width && height === scanout.host_height) return;
    scanout.enabled = enabled;
    scanout.host_width = width;
    scanout.host_height = height;
    this.events_read |= EVENT_DISPLAY;
    this.virtio["config_changed"]();
};

// ---------------------------------------------------------------------------
// The queues

VirtioGPU.prototype.notify = function(queue)
{
    let request;
    if(queue === CONTROLQ && this.restored_requests) this.requeue_restored();
    // (a request that holds the queue: the ones after it wait, unread)
    while(!(queue === CONTROLQ && this.held) && (request = this.virtio["pop_request"](queue)))
    {
        const bytes = request["read"]();
        if(queue === CONTROLQ)
        {
            this.set_active(true);
            // (a command the device fails on is answered, with an error: a
            // request left unanswered would hold its fence, and the guest, forever)
            let response;
            try
            {
                response = this.control(bytes);
            }
            catch(e)
            {
                if(!this.stats.failed_command) console.warn("virtio-gpu: a command failed:", e);
                this.stats.failed_command = String(e && e.stack || e);
                this.deferred = null;
                this.hold = false;
                response = this.error(RESP_ERR_UNSPEC, bytes.length >= 4 ? bytes[0] | bytes[1] << 8 : 0);
            }
            const wait = this.deferred, hold = this.hold;
            this.deferred = null;
            this.hold = false;
            this.enqueue(request, bytes, response, wait, hold);
        }
        else if(queue === CURSORQ)
        {
            this.cursor_command(bytes);
            request["complete"]();
        }
    }
    if(queue === CONTROLQ) this.drain();
    else this.virtio["flush"](queue);
};

/**
 * A control request's answer, after the ones before it: now, or once `wait`
 * calls back
 * @param {!Object} request
 * @param {!Uint8Array} bytes the request (its header, at least)
 * @param {!Uint8Array} response
 * @param {?function(function())} wait
 * @param {boolean} hold the requests after it wait, unread, until then
 */
VirtioGPU.prototype.enqueue = function(request, bytes, response, wait, hold)
{
    const entry = { request, bytes, response, ready: !wait, hold: !!wait && hold,
        /** a Venus or gfxstream submission's answer (their submit) */
        submission: wait && wait.submission || null,
        /** its lane of answers (timeline_of) */
        timeline: timeline_of(bytes) };
    this.pending.push(entry);
    if(!wait) return;
    if(entry.hold) this.held = true;
    const generation = this.generation;
    wait(() => {
        // (a request of before a reset or a restore: not this machine's)
        if(generation !== this.generation) return;
        entry.ready = true;
        this.drain();
        if(entry.hold && this.held)
        {
            this.held = false;
            this.notify(CONTROLQ);
        }
    });
};

/** A reset or a restore: the requests in progress are not answered, nor waited for */
VirtioGPU.prototype.forget_requests = function()
{
    this.generation++;
    this.pending = [];
    this.held = false;
    this.restored_requests = null;
};

/**
 * The requests a restored snapshot's machine had not answered, after the
 * restore (the device's state comes before the guest's RAM): answered again
 * in their order, a Venus submission run again from the command it waited
 * in (gfxstream's: its sync commands); those it held back are still in the
 * queue
 */
VirtioGPU.prototype.requeue_restored = function()
{
    const saved = /** @type {!Array} */ (this.restored_requests);
    this.restored_requests = null;
    for(const [head, header, response, ready, hold, submission] of saved)
    {
        const request = this.virtio["request_at"] && this.virtio["request_at"](CONTROLQ, head);
        if(!request) continue;
        const kind = this.venus || this.gfxstream;
        const wait = !ready && submission && kind ? kind.resubmit(submission) : null;
        this.enqueue(request, Uint8Array.from(header), Uint8Array.from(response), wait, hold);
    }
    this.drain();
};

/**
 * Before the resources go (a reset, a restore): the blobs are not mapped any
 * more, so that GPU reads still on their way do not land in the host visible
 * memory (a restored blob may be mapped where one of them was)
 */
VirtioGPU.prototype.unmap_all = function()
{
    for(const r of this.resources.values()) if(r.map_offset !== undefined) r.map_offset = -1;
};

/**
 * A request's lane of answers: a fence on a context's ring its own (that
 * timeline's, as rutabaga's fence contexts), the rest one lane in order
 * (docs/gfxstream-plan.md G1)
 * @param {!Uint8Array} bytes the request
 * @return {string}
 */
function timeline_of(bytes)
{
    const flags = bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24;
    if(!(flags & FLAG_FENCE && flags & FLAG_INFO_RING_IDX)) return "";
    const ctx_id = (bytes[16] | bytes[17] << 8 | bytes[18] << 16 | bytes[19] << 24) >>> 0;
    return ctx_id + ":" + bytes[20];
}

/**
 * Answer the control requests that are ready, in order within each lane (a
 * fence must not pass the GPU work before it on its timeline; another
 * timeline's does not wait for it)
 */
VirtioGPU.prototype.drain = function()
{
    let answered = false;
    /** the lanes with a request waiting before */
    const blocked = new Set();
    for(let i = 0; i < this.pending.length;)
    {
        const entry = this.pending[i];
        if(!entry.ready || blocked.has(entry.timeline))
        {
            blocked.add(entry.timeline);
            i++;
            continue;
        }
        this.pending.splice(i, 1);
        this.respond(entry.request, entry.bytes, entry.response);
        entry.request["complete"]();
        answered = true;
    }
    if(answered) this.virtio["flush"](CONTROLQ);
};

/**
 * The response's header: its type, and the request's fence when it has one
 * @param {!Object} request
 * @param {!Uint8Array} bytes the request
 * @param {!Uint8Array} response with room for its header
 */
VirtioGPU.prototype.respond = function(request, bytes, response)
{
    if(bytes.length >= HEADER_SIZE)
    {
        const flags = bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24;
        if(flags & FLAG_FENCE)
        {
            // fence_id, ctx_id, ring_idx
            response[4] = FLAG_FENCE | flags & FLAG_INFO_RING_IDX;
            response.set(bytes.subarray(8, 21), 8);
            const lane = timeline_of(bytes);
            const counts = this.stats.fences[lane] = this.stats.fences[lane] || [0, 0, 0];
            counts[0]++;
            counts[1] = bytes[8] | bytes[9] << 8 | bytes[10] << 16 | bytes[11] << 24;
            counts[2] = bytes[0] | bytes[1] << 8;
        }
    }
    request["write"](response);
};

/**
 * @param {number} type
 * @param {number=} size of the whole response
 * @return {!Uint8Array}
 */
function response(type, size)
{
    const out = new Uint8Array(size || HEADER_SIZE);
    out[0] = type & 0xFF;
    out[1] = type >> 8;
    return out;
}

/**
 * A control command
 * @param {!Uint8Array} bytes
 * @return {!Uint8Array} the response
 */
VirtioGPU.prototype.control = function(bytes)
{
    if(bytes.length < HEADER_SIZE) return this.error(RESP_ERR_UNSPEC, 0);
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const type = view.getUint32(0, true);
    this.stats.commands[type] = (this.stats.commands[type] || 0) + 1;
    const u32 = at => HEADER_SIZE + at + 4 <= bytes.length ? view.getUint32(HEADER_SIZE + at, true) : 0;
    const need = size => HEADER_SIZE + size <= bytes.length;

    switch(type)
    {
        case CMD_GET_DISPLAY_INFO:
            return this.display_info();
        case CMD_GET_EDID:
            if(!need(8)) break;
            return this.edid(u32(0));
        case CMD_RESOURCE_CREATE_2D:
            if(!need(16)) break;
            return this.create_2d(u32(0), u32(4), u32(8), u32(12));
        case CMD_RESOURCE_UNREF:
            if(!need(8)) break;
            return this.unref(u32(0));
        case CMD_SET_SCANOUT:
            if(!need(24)) break;
            return this.set_scanout(u32(16), u32(20), u32(0), u32(4), u32(8), u32(12));
        case CMD_RESOURCE_FLUSH:
            if(!need(24)) break;
            return this.flush(u32(16), u32(0), u32(4), u32(8), u32(12));
        case CMD_TRANSFER_TO_HOST_2D:
            if(!need(32)) break;
            return this.transfer_to_host(u32(24), u32(0), u32(4), u32(8), u32(12), u32(16) + u32(20) * 0x100000000);
        case CMD_RESOURCE_ATTACH_BACKING:
        {
            if(!need(8)) break;
            const count = u32(4);
            if(count > MAX_BACKING_ENTRIES || !need(8 + count * 16)) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            const entries = new Float64Array(count * 2);
            for(let i = 0; i < count; i++)
            {
                entries[i * 2] = u32(8 + i * 16) + u32(12 + i * 16) * 0x100000000;
                entries[i * 2 + 1] = u32(16 + i * 16);
            }
            return this.attach_backing(u32(0), entries);
        }
        case CMD_RESOURCE_DETACH_BACKING:
            if(!need(8)) break;
            return this.detach_backing(u32(0));
        case CMD_RESOURCE_ASSIGN_UUID:
            if(!need(8)) break;
            return this.assign_uuid(u32(0));
        case CMD_RESOURCE_CREATE_BLOB:
        {
            // resource, memory, flags, entries, blob id (64), size (64), then the entries
            if(!LEVELS[this.level].blob || !need(32)) break;
            const count = u32(12);
            if(count > MAX_BACKING_ENTRIES || !need(32 + count * 16)) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            const entries = new Float64Array(count * 2);
            for(let i = 0; i < count; i++)
            {
                entries[i * 2] = u32(32 + i * 16) + u32(36 + i * 16) * 0x100000000;
                entries[i * 2 + 1] = u32(40 + i * 16);
            }
            return this.create_blob(u32(0), u32(4), u32(8), u32(24) + u32(28) * 0x100000000, entries,
                view.getUint32(16, true), u32(16) + u32(20) * 0x100000000);
        }
        case CMD_RESOURCE_MAP_BLOB:
            // resource, padding, offset (64)
            if(!LEVELS[this.level].hostmem || !need(16)) break;
            return this.map_blob(u32(0), u32(8) + u32(12) * 0x100000000);
        case CMD_RESOURCE_UNMAP_BLOB:
            if(!LEVELS[this.level].hostmem || !need(8)) break;
            return this.unmap_blob(u32(0));
        case CMD_SET_SCANOUT_BLOB:
            // rectangle, scanout, resource, width, height, format, padding, strides[4], offsets[4]
            if(!LEVELS[this.level].blob || !need(72)) break;
            return this.set_scanout_blob(u32(16), u32(20), u32(0), u32(4), u32(8), u32(12),
                { width: u32(24), height: u32(28), format: u32(32), stride: u32(40), offset: u32(56) });
        case CMD_GET_CAPSET_INFO:
        {
            if(!need(8)) break;
            const entry = this.capsets[u32(0)];
            if(!entry) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            const out = response(RESP_OK_CAPSET_INFO, HEADER_SIZE + 16);
            const v = new DataView(out.buffer);
            v.setUint32(HEADER_SIZE, entry[0], true);
            v.setUint32(HEADER_SIZE + 4, entry[1], true);
            v.setUint32(HEADER_SIZE + 8, entry[2], true);
            return out;
        }
        case CMD_GET_CAPSET:
        {
            if(!need(8)) break;
            const entry = this.capsets.find(c => c[0] === u32(0));
            if(!entry || u32(4) > entry[1]) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            const kind = this.kind_of_capset(entry[0]);
            const data = kind ? kind.capset(entry[0]) : capset(entry[0], !!LEVELS[this.level].gl43, !!LEVELS[this.level].hostmem);
            const out = response(RESP_OK_CAPSET, HEADER_SIZE + data.length);
            out.set(data, HEADER_SIZE);
            return out;
        }
        case CMD_CTX_CREATE:
        case CMD_CTX_DESTROY:
        case CMD_CTX_ATTACH_RESOURCE:
        case CMD_CTX_DETACH_RESOURCE:
        case CMD_RESOURCE_CREATE_3D:
        case CMD_TRANSFER_TO_HOST_3D:
        case CMD_TRANSFER_FROM_HOST_3D:
        case CMD_SUBMIT_3D:
            if(!this.virgl) break;
            return this.command_3d(type, view.getUint32(16, true), bytes, u32, need);
    }
    return this.error(RESP_ERR_UNSPEC, type);
};

VirtioGPU.prototype.error = function(code, command)
{
    this.stats.errors++;
    this.stats.last_error = command << 16 | code & 0xFFFF;
    return response(code);
};

VirtioGPU.prototype.ok = function()
{
    return response(RESP_OK_NODATA);
};

/**
 * Where each enabled display is on the page: side by side, left to right
 */
VirtioGPU.prototype.place_scanouts = function()
{
    let x = 0;
    for(const scanout of this.scanouts)
    {
        scanout.screen_x = x;
        scanout.screen_y = 0;
        if(scanout.enabled) x += scanout.host_width;
    }
};

VirtioGPU.prototype.display_info = function()
{
    const out = response(RESP_OK_DISPLAY_INFO, HEADER_SIZE + MAX_SCANOUTS * 24);
    const view = new DataView(out.buffer);
    this.place_scanouts();
    for(const scanout of this.scanouts)
    {
        if(!scanout.enabled) continue;
        const at = HEADER_SIZE + scanout.index * 24;
        view.setUint32(at, scanout.screen_x, true);
        view.setUint32(at + 4, scanout.screen_y, true);
        view.setUint32(at + 8, scanout.host_width, true);
        view.setUint32(at + 12, scanout.host_height, true);
        view.setUint32(at + 16, 1, true);
    }
    return out;
};

VirtioGPU.prototype.edid = function(index)
{
    const scanout = this.scanouts[index];
    if(!scanout) return this.error(RESP_ERR_INVALID_PARAMETER, CMD_GET_EDID);
    const edid = make_edid(scanout.host_width, scanout.host_height, this.serial + index);
    const out = response(RESP_OK_EDID, HEADER_SIZE + 8 + 1024);
    new DataView(out.buffer).setUint32(HEADER_SIZE, edid.length, true);
    out.set(edid, HEADER_SIZE + 8);
    return out;
};

VirtioGPU.prototype.create_2d = function(id, format, width, height)
{
    if(id === 0 || this.resources.has(id)) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_CREATE_2D);
    if(!TO_RGBA[format] || !width || !height || width > 16384 || height > 16384)
    {
        return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_2D);
    }
    const bytes = width * height * 4;
    if(this.host_memory + bytes > MAX_HOST_MEMORY) return this.error(RESP_ERR_OUT_OF_MEMORY, CMD_RESOURCE_CREATE_2D);
    this.host_memory += bytes;
    this.resources.set(id, new Resource(id, format, width, height));
    return this.ok();
};

VirtioGPU.prototype.unref = function(id)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_UNREF);
    // (as QEMU: the displays that show it are switched off)
    for(const scanout of this.scanouts)
    {
        if(scanout.resource_id === id) this.disable_scanout(scanout);
    }
    if(resource.kind)
    {
        // (what the guest wrote through its mapping stays in the memory)
        if(resource.map_offset >= 0) this.upload_hostmem();
        this.mapped.delete(id);
        resource.kind.unref_blob(resource);
        resource.map_offset = -1;
    }
    else if(resource.three_d)
    {
        this.mapped.delete(id);
        resource.map_offset = -1;
        if(!resource.pipe) this.virgl.destroy_resource(/** @type {!Resource3D} */ (resource));
    }
    else if(!resource.blob) this.host_memory -= resource.data.length;
    this.resources.delete(id);
    return this.ok();
};

/**
 * RESOURCE_CREATE_BLOB: in guest memory, or (level hostmem) a 3D resource of
 * the template that the context's PIPE_RESOURCE_CREATE gave the blob id
 */
VirtioGPU.prototype.create_blob = function(id, mem, flags, size, entries, ctx_id, blob_id)
{
    if(id === 0 || this.resources.has(id)) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_CREATE_BLOB);
    const kind = this.kind_of(ctx_id);
    if(kind)
    {
        // (Venus: shared memory (blob id 0) or a VkDeviceMemory's export, mappable)
        const blob = mem === BLOB_MEM_HOST3D ? kind.create_blob(id, ctx_id, flags, blob_id, size) : null;
        if(!blob) return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_BLOB);
        blob.kind = kind;
        this.resources.set(id, blob);
        return this.ok();
    }
    if(mem === BLOB_MEM_HOST3D && LEVELS[this.level].hostmem)
    {
        const virgl = /** @type {!Virgl} */ (this.virgl);
        const key = ctx_id + ":" + blob_id;
        const t = virgl.blob_templates.get(key);
        if(!t) return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_BLOB);
        virgl.blob_templates.delete(key);
        const r = new Resource3D(id, t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9]);
        r.set_backing = Resource.prototype.set_backing;
        r.blob_flags = flags;
        r.blob_size = size;
        if(r.is_buffer() && size < r.width || !virgl.create_resource(r))
        {
            return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_BLOB);
        }
        this.resources.set(id, r);
        return this.ok();
    }
    if(mem !== BLOB_MEM_GUEST) return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_BLOB);
    const r = new BlobResource(id, flags, size);
    r.set_backing(entries);
    if(r.backing_length < size) return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_CREATE_BLOB);
    this.resources.set(id, r);
    return this.ok();
};

/**
 * MAP_BLOB: a HOST3D blob's place in the host visible memory (the guest's
 * kernel allocates it). Buffers only: their mapping is their bytes.
 */
VirtioGPU.prototype.map_blob = function(id, offset)
{
    const found = this.resources.get(id);
    if(found && found.kind)
    {
        // (a blob of a kind of context's: Venus's)
        const blob = /** @type {!VenusBlob} */ (found);
        if(!(blob.blob_flags & BLOB_FLAG_USE_MAPPABLE)) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_MAP_BLOB);
        if(blob.map_offset >= 0 || offset % PAGE || offset + blob.blob_size > this.hostmem_size)
        {
            return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_MAP_BLOB);
        }
        blob.map_offset = offset;
        this.mapped.set(id, blob);
        // (memory's contents may come from the GPU first)
        this.deferred = blob.kind.mapped(blob);
        const out = response(RESP_OK_MAP_INFO, HEADER_SIZE + 8);
        out[HEADER_SIZE] = MAP_CACHE_CACHED;
        return out;
    }
    if(!found || !found.three_d || found.blob_flags < 0 || !(found.blob_flags & BLOB_FLAG_USE_MAPPABLE))
    {
        return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_MAP_BLOB);
    }
    const r = /** @type {!Resource3D} */ (found);
    if(!r.is_buffer() || r.map_offset >= 0 || offset % PAGE || offset + r.blob_size > this.hostmem_size)
    {
        return this.error(RESP_ERR_INVALID_PARAMETER, CMD_RESOURCE_MAP_BLOB);
    }
    // the new buffer's bytes are zeros, as GX's
    this.take_hostmem_dirty();
    this.hostmem_bytes().fill(0, offset, offset + r.blob_size);
    this.for_pages(offset, r.blob_size, page => { this.hostmem_pending[page >>> 5] &= ~(1 << (page & 31)); });
    r.map_offset = offset;
    this.mapped.set(id, r);
    const out = response(RESP_OK_MAP_INFO, HEADER_SIZE + 8);
    out[HEADER_SIZE] = MAP_CACHE_CACHED;
    return out;
};

VirtioGPU.prototype.unmap_blob = function(id)
{
    const r = this.mapped.get(id);
    if(!r) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_UNMAP_BLOB);
    this.mapped.delete(id);
    r.map_offset = -1;
    return this.ok();
};

/** @return {!Uint8Array} the host visible memory, in the wasm memory */
VirtioGPU.prototype.hostmem_bytes = function()
{
    return new Uint8Array(this.machine.wasm_memory.buffer, this.hostmem_backing, this.hostmem_size);
};

/** @param {function(number)} f each page of [offset, offset + length) */
VirtioGPU.prototype.for_pages = function(offset, length, f)
{
    for(let page = Math.floor(offset / PAGE); page < Math.ceil((offset + length) / PAGE); page++) f(page);
};

/** The pages the guest wrote, from the core's bitmap into hostmem_pending */
VirtioGPU.prototype.take_hostmem_dirty = function()
{
    if(this.hostmem_region < 0) return;
    const at = this.machine.mmio_ram_take_dirty(this.hostmem_region) >>> 0;
    if(!at) return;
    const pending = this.hostmem_pending;
    // (64-bit words, little endian: the low dword's bits are the first pages)
    const words = new Uint32Array(this.machine.wasm_memory.buffer, at, pending.length);
    for(let i = 0; i < pending.length; i++) pending[i] |= words[i];
};

/**
 * Before the GPU runs what the guest sent: the pages of mappings the guest
 * wrote go into their blobs
 */
VirtioGPU.prototype.upload_hostmem = function()
{
    if(this.hostmem_region < 0) return;
    this.take_hostmem_dirty();
    const pending = this.hostmem_pending;
    if(!this.mapped.size || !pending.some(word => word !== 0))
    {
        pending.fill(0);
        return;
    }
    const bytes = this.hostmem_bytes();
    const gxw = /** @type {!Virgl} */ (this.virgl).gxw;
    for(const r of this.mapped.values())
    {
        const size = r.kind ? r.blob_size : r.width;
        const first = r.map_offset / PAGE, end = Math.ceil((r.map_offset + size) / PAGE);
        let run = -1;
        for(let page = first; page <= end; page++)
        {
            if(page < end && (pending[page >>> 5] >>> (page & 31) & 1))
            {
                if(r.readbacks) r.fresh.add(page);
                if(run < 0) run = page;
                continue;
            }
            if(run < 0) continue;
            // the run's bytes, as the buffer's (Venus: the memory's)
            const x = run * PAGE - r.map_offset, w = Math.min(size, page * PAGE - r.map_offset) - x;
            const data = bytes.subarray(r.map_offset + x, r.map_offset + x + w);
            if(r.kind) r.kind.upload_blob(r, x, data);
            else gxw.command(GX.SURFACE_UPLOAD, [r.id, 0, 0, x, 0, 0, w, 1, 1, w, w], data);
            run = -1;
        }
    }
    // (and the pages of no mapping are of no blob)
    pending.fill(0);
    /** @type {!Virgl} */ (this.virgl).flush_big();
};

/**
 * After the GPU work sent: the mapped blobs it wrote come back into their
 * mappings (before the fence completes), except for the pages the guest has
 * written since
 */
VirtioGPU.prototype.read_back_hostmem = function()
{
    const virgl = /** @type {!Virgl} */ (this.virgl);
    if(!virgl.written.size) return;
    for(const r of virgl.written)
    {
        if(r.map_offset < 0 || this.resources.get(r.id) !== r) continue;
        const offset = r.map_offset;
        r.readbacks++;
        virgl.read_buffer(r, 0, r.width, data => {
            r.readbacks--;
            if(data && r.map_offset === offset && this.resources.get(r.id) === r)
            {
                this.take_hostmem_dirty();
                const bytes = this.hostmem_bytes(), pending = this.hostmem_pending;
                for(let x = 0; x < data.length; x += PAGE)
                {
                    const page = (offset + x) / PAGE;
                    if(pending[page >>> 5] >>> (page & 31) & 1 || r.fresh.has(page)) continue;
                    bytes.set(data.subarray(x, Math.min(data.length, x + PAGE)), offset + x);
                }
            }
            if(!r.readbacks) r.fresh.clear();
        });
    }
    virgl.written.clear();
};

/**
 * SET_SCANOUT_BLOB: a scanout shows part of a blob, a picture of the given
 * format, size and stride from an offset
 */
VirtioGPU.prototype.set_scanout_blob = function(index, id, x, y, width, height, blob)
{
    const scanout = this.scanouts[index];
    if(!scanout) return this.error(RESP_ERR_INVALID_SCANOUT_ID, CMD_SET_SCANOUT_BLOB);
    if(id === 0)
    {
        this.disable_scanout(scanout);
        return this.ok();
    }
    const resource = this.resources.get(id);
    if(!resource || !resource.blob) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_SET_SCANOUT_BLOB);
    if(!TO_RGBA[blob.format] || width < 16 || height < 16 || x + width > blob.width || y + height > blob.height ||
        blob.stride < blob.width * 4 || blob.offset + blob.stride * (blob.height - 1) + blob.width * 4 > resource.backing_length)
    {
        return this.error(RESP_ERR_INVALID_PARAMETER, CMD_SET_SCANOUT_BLOB);
    }
    if(scanout.width !== width || scanout.height !== height || !scanout.rgba)
    {
        scanout.rgba = new Uint8ClampedArray(width * height * 4);
        this.layout_key = "";
    }
    Object.assign(scanout, { resource_id: id, x, y, width, height, blob });
    this.present(scanout, resource, 0, 0, width, height);
    return this.ok();
};

VirtioGPU.prototype.disable_scanout = function(scanout)
{
    if(scanout.direct) this.leave_direct(scanout);
    scanout.resource_id = 0;
    scanout.blob = null;
    scanout.width = scanout.height = 0;
    scanout.rgba = null;
    scanout.dirty = null;
    this.layout_key = "";
};

VirtioGPU.prototype.set_scanout = function(index, id, x, y, width, height)
{
    const scanout = this.scanouts[index];
    if(!scanout) return this.error(RESP_ERR_INVALID_SCANOUT_ID, CMD_SET_SCANOUT);
    if(id === 0)
    {
        this.disable_scanout(scanout);
        return this.ok();
    }
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_SET_SCANOUT);
    if(width < 16 || height < 16 || x + width > resource.width || y + height > resource.height)
    {
        return this.error(RESP_ERR_INVALID_PARAMETER, CMD_SET_SCANOUT);
    }
    if(scanout.width !== width || scanout.height !== height || !scanout.rgba)
    {
        scanout.rgba = new Uint8ClampedArray(width * height * 4);
        this.layout_key = "";
    }
    if(resource.blob) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_SET_SCANOUT);
    scanout.resource_id = id;
    scanout.x = x;
    scanout.y = y;
    scanout.width = width;
    scanout.height = height;
    scanout.blob = null;
    this.present(scanout, resource, 0, 0, width, height);
    return this.ok();
};

VirtioGPU.prototype.flush = function(id, x, y, width, height)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_FLUSH);
    this.stats.flushes++;
    for(const scanout of this.scanouts)
    {
        if(scanout.resource_id !== id) continue;
        // the rectangle, in the scanout's coordinates
        const x0 = Math.max(x - scanout.x, 0), y0 = Math.max(y - scanout.y, 0);
        const x1 = Math.min(x + width - scanout.x, scanout.width), y1 = Math.min(y + height - scanout.y, scanout.height);
        if(x0 < x1 && y0 < y1) this.present(scanout, resource, x0, y0, x1 - x0, y1 - y0);
    }
    return this.ok();
};

/**
 * A rectangle of a scanout from its resource into its picture
 */
VirtioGPU.prototype.present = function(scanout, resource, x, y, width, height)
{
    const direct = resource.three_d && !(resource.host_newer && resource.data) && this.direct_scanout(scanout);
    if(scanout.direct && (!direct || scanout.direct !== resource.id))
    {
        // (back to the device's picture, or another resource: all of it again)
        this.leave_direct(scanout);
        x = 0;
        y = 0;
        width = scanout.width;
        height = scanout.height;
    }
    if(direct)
    {
        // (the renderer copies it to the page's screen on the GPU: no
        // readback, docs/gfxstream-plan.md G4)
        scanout.direct = resource.id;
        this.virgl.present_surface(/** @type {!Resource3D} */ (resource), scanout.x + x, scanout.y + y, width, height, x, y, scanout.width, scanout.height);
        return;
    }
    if(resource.blob)
    {
        // straight from guest memory, a row at a time
        const b = scanout.blob;
        if(!b) return;
        const convert = TO_RGBA[b.format];
        const row = new Uint8Array(width * 4), words = new Int32Array(row.buffer);
        const dst = new Int32Array(scanout.rgba.buffer);
        for(let r = y; r < y + height; r++)
        {
            const from = b.offset + (scanout.y + r) * b.stride + (scanout.x + x) * 4;
            if(!this.read_backing(resource, from, row, 0, row.length)) return;
            for(let i = 0, to = r * scanout.width + x; i < width; i++, to++) dst[to] = convert(words[i]);
        }
        scanout.add_dirty(x, y, x + width, y + height);
        return;
    }
    if(resource.three_d && !(resource.host_newer && resource.data))
    {
        // (its picture is on the GPU: read back, then converted)
        if(!TO_RGBA[resource.format]) return;
        this.virgl.read_picture(resource, scanout.x + x, scanout.y + y, width, height, (first, count) => {
            if(this.scanouts[scanout.index].resource_id !== resource.id || !scanout.rgba) return;
            this.convert(scanout, resource, x, first - scanout.y, width, count);
        });
        return;
    }
    this.convert(scanout, resource, x, y, width, height);
};

/**
 * Whether the renderer shows the scanout's 3D picture itself: it can (its
 * page's compositor), the scanout is the only one, and no cursor is drawn
 * over the device's picture
 * @param {!Scanout} scanout
 */
VirtioGPU.prototype.direct_scanout = function(scanout)
{
    return !!this.virgl && this.virgl.direct_present && !this.cursor.visible &&
        this.scanouts.every(s => s === scanout || !s.resource_id);
};

/** The renderer's picture of the scanout goes: the device's shows again */
VirtioGPU.prototype.leave_direct = function(scanout)
{
    scanout.direct = 0;
    this.virgl.present_surface(null, 0, 0, 0, 0, 0, 0, 0, 0);
};

/**
 * A rectangle of a scanout from its resource's host copy into its picture
 */
VirtioGPU.prototype.convert = function(scanout, resource, x, y, width, height)
{
    const convert = TO_RGBA[resource.format];
    const src = new Int32Array(resource.data.buffer);
    const dst = new Int32Array(scanout.rgba.buffer);
    for(let row = y; row < y + height; row++)
    {
        let from = (scanout.y + row) * resource.width + scanout.x + x;
        let to = row * scanout.width + x;
        for(const end = to + width; to < end; to++, from++) dst[to] = convert(src[from]);
    }
    scanout.add_dirty(x, y, x + width, y + height);
};

VirtioGPU.prototype.transfer_to_host = function(id, x, y, width, height, offset)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_TRANSFER_TO_HOST_2D);
    // (a blob in guest memory has no host copy to fill)
    if(resource.blob) return this.ok();
    if(!resource.backing) return this.error(RESP_ERR_UNSPEC, CMD_TRANSFER_TO_HOST_2D);
    if(x + width > resource.width || y + height > resource.height || x + width < x || y + height < y)
    {
        return this.error(RESP_ERR_INVALID_PARAMETER, CMD_TRANSFER_TO_HOST_2D);
    }
    this.stats.transfers++;
    if(resource.three_d)
    {
        // a 3D resource the kernel treats as 2D (a dumb buffer: fbcon, KMS
        // clients): a host copy for the screen, and GX's copy for drawing
        if(!resource.data) resource.data = new Uint8Array(resource.width * resource.height * resource.block().bytes);
        const pitch = resource.width * resource.block().bytes;
        const read = (from, out, at, length) => this.read_backing(resource, from, out, at, length);
        if(!this.virgl.transfer_to_host(/** @type {!Resource3D} */ (resource), [x, y, 0, width, height, 1], 0, offset, pitch, 0, read))
        {
            return this.error(RESP_ERR_INVALID_PARAMETER, CMD_TRANSFER_TO_HOST_2D);
        }
        const bytes = resource.block().bytes;
        for(let h = 0; h < height; h++)
        {
            this.read_backing(resource, offset + pitch * h, resource.data, (y + h) * pitch + x * bytes, width * bytes);
        }
        resource.host_newer = true;
        return this.ok();
    }
    const stride = resource.width * 4, row = width * 4;
    if(offset === 0 && x === 0 && y === 0 && width === resource.width)
    {
        // (the whole of the first rows, in one go)
        if(!this.read_backing(resource, 0, resource.data, 0, stride * height))
        {
            return this.error(RESP_ERR_INVALID_PARAMETER, CMD_TRANSFER_TO_HOST_2D);
        }
        return this.ok();
    }
    for(let h = 0; h < height; h++)
    {
        if(!this.read_backing(resource, offset + stride * h, resource.data, (y + h) * stride + x * 4, row))
        {
            return this.error(RESP_ERR_INVALID_PARAMETER, CMD_TRANSFER_TO_HOST_2D);
        }
    }
    return this.ok();
};

/**
 * Bytes of a resource's backing (guest RAM, or the frame buffer in BAR0)
 * @param {(!Resource|!Resource3D|!BlobResource|!VenusBlob)} resource
 * @param {number} from the offset in the backing
 * @param {Uint8Array} out
 * @param {number} at
 * @param {number} length
 * @return {boolean} whether the backing has them
 */
VirtioGPU.prototype.read_backing = function(resource, from, out, at, length)
{
    if(from + length > resource.backing_length) return false;
    const starts = resource.backing_starts, entries = resource.backing;
    // the entry that holds `from`
    let low = 0, high = starts.length - 1;
    while(low < high)
    {
        const mid = low + high + 1 >> 1;
        if(starts[mid] <= from) low = mid;
        else high = mid - 1;
    }
    for(let i = low; length > 0; i++)
    {
        const skip = from - starts[i];
        const count = Math.min(entries[i * 2 + 1] - skip, length);
        if(count > 0)
        {
            const bytes = this.read_guest(entries[i * 2] + skip, count);
            if(!bytes) return false;
            out.set(bytes, at);
            at += count;
            from += count;
            length -= count;
        }
    }
    return true;
};

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array} a view or a copy, null if it is neither RAM nor the frame buffer
 */
VirtioGPU.prototype.read_guest = function(address, length)
{
    const lfb = this.vga.lfb_address;
    if(address >= lfb && address + length <= lfb + this.vram_size)
    {
        return this.vga.svga_memory.subarray(address - lfb, address - lfb + length);
    }
    if(!this.virtio["is_ram"](address, length)) return null;
    return this.virtio["read_memory"](address, length);
};

/**
 * Bytes into a resource's backing (a 3D readback)
 * @param {!Object} resource
 * @param {number} at the offset in the backing
 * @param {!Uint8Array} bytes
 */
VirtioGPU.prototype.write_backing = function(resource, at, bytes)
{
    if(!resource.backing || at + bytes.length > resource.backing_length) return;
    const starts = resource.backing_starts, entries = resource.backing;
    let low = 0, high = starts.length - 1;
    while(low < high)
    {
        const mid = low + high + 1 >> 1;
        if(starts[mid] <= at) low = mid;
        else high = mid - 1;
    }
    let done = 0;
    for(let i = low; done < bytes.length; i++)
    {
        const skip = at + done - starts[i];
        const count = Math.min(entries[i * 2 + 1] - skip, bytes.length - done);
        if(count <= 0) continue;
        const address = entries[i * 2] + skip, piece = bytes.subarray(done, done + count);
        const lfb = this.vga.lfb_address;
        if(address >= lfb && address + count <= lfb + this.vram_size)
        {
            this.vga.svga_memory.set(piece, address - lfb);
            this.machine.mmio_ram_mark_dirty(this.vga.lfb_region);
        }
        else if(this.virtio["is_ram"](address, count))
        {
            this.virtio["write_memory"](piece, address);
        }
        done += count;
    }
};

/**
 * The 3D commands (level virgl)
 * @param {number} type
 * @param {number} ctx_id from the request's header
 * @param {!Uint8Array} bytes the request
 * @param {function(number):number} u32 a dword after the header
 * @param {function(number):boolean} need
 * @return {!Uint8Array}
 */
VirtioGPU.prototype.command_3d = function(type, ctx_id, bytes, u32, need)
{
    const virgl = /** @type {!Virgl} */ (this.virgl);
    // the answer once the GPU has done what was sent so far (and `work`)
    const after_work = () => {
        let finish = null, finished = false;
        virgl.after_work(() => { finished = true; if(finish) finish(); });
        this.deferred = done => { if(finished) done(); else finish = done; };
    };
    switch(type)
    {
        case CMD_CTX_CREATE:
        {
            // name length, context_init (the capset in its low byte: virgl's or none), name
            const capset = LEVELS[this.level].features.includes(VIRTIO_GPU_F_CONTEXT_INIT) ? u32(4) & 0xFF : 0;
            if(capset && !this.capsets.some(c => c[0] === capset)) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            // (a context of one kind: the others' of that id go; without a
            // capset, gfxstream's at its level)
            const kind = capset ? this.kind_of_capset(capset) : this.gfxstream;
            for(const other of this.kinds) if(other !== kind) other.destroy_context(ctx_id);
            if(kind)
            {
                virgl.destroy_context(ctx_id);
                kind.create_context(ctx_id, capset);
                return this.ok();
            }
            virgl.create_context(ctx_id);
            return this.ok();
        }
        case CMD_CTX_DESTROY:
            for(const kind of this.kinds) kind.destroy_context(ctx_id);
            virgl.destroy_context(ctx_id);
            return this.ok();
        case CMD_CTX_ATTACH_RESOURCE:
        case CMD_CTX_DETACH_RESOURCE:
            // (every context sees every resource)
            if(!need(8)) break;
            return this.resources.has(u32(0)) ? this.ok() : this.error(RESP_ERR_INVALID_RESOURCE_ID, type);
        case CMD_RESOURCE_CREATE_3D:
        {
            if(!need(48)) break;
            const id = u32(0);
            if(id === 0 || this.resources.has(id)) return this.error(RESP_ERR_INVALID_RESOURCE_ID, type);
            const r = new Resource3D(id, u32(4), u32(8), u32(12), u32(16), u32(20), u32(24), u32(28), u32(32), u32(36), u32(40));
            r.set_backing = Resource.prototype.set_backing;
            // (gfxstream's process pipe: a buffer of transfers, no texture of the GPU's)
            if(this.gfxstream && this.gfxstream.is_pipe(r.target, r.bind)) r.pipe = this.gfxstream.create_pipe();
            else if(!virgl.create_resource(r)) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            this.resources.set(id, r);
            return this.ok();
        }
        case CMD_TRANSFER_TO_HOST_3D:
        case CMD_TRANSFER_FROM_HOST_3D:
        {
            if(!need(48)) break;
            const box = [u32(0), u32(4), u32(8), u32(12), u32(16), u32(20)];
            const offset = u32(24) + u32(28) * 0x100000000;
            const found = this.resources.get(u32(32));
            if(!found || !found.three_d) return this.error(RESP_ERR_INVALID_RESOURCE_ID, type);
            const r = /** @type {!Resource3D} */ (found);
            if(!r.backing) return this.error(RESP_ERR_UNSPEC, type);
            const level = u32(36), stride = u32(40), layer_stride = u32(44);
            if(r.pipe)
            {
                // a pipe: box x and width are the bytes of its buffer
                const gfxstream = /** @type {!Gfxstream} */ (this.gfxstream);
                if(type === CMD_TRANSFER_TO_HOST_3D)
                {
                    const data = new Uint8Array(box[3]);
                    if(!this.read_backing(r, box[0], data, 0, box[3])) return this.error(RESP_ERR_INVALID_PARAMETER, type);
                    gfxstream.pipe_write(r.pipe, data);
                }
                else this.write_backing(r, box[0], gfxstream.pipe_read(r.pipe, box[3]));
                return this.ok();
            }
            if(type === CMD_TRANSFER_TO_HOST_3D)
            {
                const read = (from, out, at, length) => this.read_backing(r, from, out, at, length);
                if(!virgl.transfer_to_host(r, box, level, offset, stride, layer_stride, read))
                {
                    return this.error(RESP_ERR_INVALID_PARAMETER, type);
                }
                return this.ok();
            }
            let finish = null, finished = false;
            virgl.transfer_from_host(r, box, level, offset, stride, layer_stride, (at, data) => { this.write_backing(r, at, data); return true; },
                () => { finished = true; if(finish) finish(); });
            this.deferred = done => { if(finished) done(); else finish = done; };
            return this.ok();
        }
        case CMD_SUBMIT_3D:
        {
            if(!need(8)) break;
            const size = u32(0);
            if(size & 3 || HEADER_SIZE + 8 + size > bytes.length) return this.error(RESP_ERR_INVALID_PARAMETER, type);
            const start = bytes.byteOffset + HEADER_SIZE + 8;
            const kind = this.kind_of(ctx_id);
            if(kind)
            {
                // (Venus's own commands: rings, waits; Vulkan work is in the rings)
                // (a fence on a queue's timeline: after the queue's work, as virglrenderer's)
                const flags = bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24;
                const ring_idx = flags & FLAG_FENCE && flags & FLAG_INFO_RING_IDX ? bytes[20] : 0;
                this.deferred = kind.submit(ctx_id, new Uint8Array(bytes.buffer.slice(start, start + size)), ring_idx);
                // (Venus: the requests after it wait for it, as virglrenderer's;
                // gfxstream's sync tasks hold their fence only)
                this.hold = !!this.deferred && kind === this.venus;
                return this.ok();
            }
            if(!virgl.contexts.has(ctx_id)) return this.error(RESP_ERR_INVALID_CONTEXT_ID, type);
            const words = new Uint32Array(bytes.buffer.slice(start, start + size));
            this.upload_hostmem();
            virgl.submit(ctx_id, words, id => this.resources.get(id) || null);
            this.read_back_hostmem();
            after_work();
            return this.ok();
        }
    }
    return this.error(RESP_ERR_UNSPEC, type);
};

VirtioGPU.prototype.attach_backing = function(id, entries)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_ATTACH_BACKING);
    if(resource.backing) return this.error(RESP_ERR_UNSPEC, CMD_RESOURCE_ATTACH_BACKING);
    resource.set_backing(entries);
    return this.ok();
};

VirtioGPU.prototype.detach_backing = function(id)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_DETACH_BACKING);
    if(!resource.backing) return this.error(RESP_ERR_UNSPEC, CMD_RESOURCE_DETACH_BACKING);
    resource.backing = null;
    resource.backing_starts = null;
    resource.backing_length = 0;
    return this.ok();
};

VirtioGPU.prototype.assign_uuid = function(id)
{
    const resource = this.resources.get(id);
    if(!resource) return this.error(RESP_ERR_INVALID_RESOURCE_ID, CMD_RESOURCE_ASSIGN_UUID);
    if(!resource.uuid)
    {
        // a version 4 UUID
        resource.uuid = new Uint8Array(16);
        for(let i = 0; i < 16; i++) resource.uuid[i] = Math.random() * 256;
        resource.uuid[6] = resource.uuid[6] & 0x0F | 0x40;
        resource.uuid[8] = resource.uuid[8] & 0x3F | 0x80;
    }
    const out = response(RESP_OK_RESOURCE_UUID, HEADER_SIZE + 16);
    out.set(resource.uuid, HEADER_SIZE);
    return out;
};

/**
 * UPDATE_CURSOR, MOVE_CURSOR: pos (scanout, x, y), resource, hot_x, hot_y
 * @param {!Uint8Array} bytes
 */
VirtioGPU.prototype.cursor_command = function(bytes)
{
    if(bytes.length < HEADER_SIZE + 16) return;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const type = view.getUint32(0, true);
    const scanout = this.scanouts[view.getUint32(HEADER_SIZE, true)] || this.scanouts[0];
    this.place_scanouts();
    const x = scanout.screen_x + view.getInt32(HEADER_SIZE + 4, true), y = scanout.screen_y + view.getInt32(HEADER_SIZE + 8, true);
    if(type === CMD_UPDATE_CURSOR && bytes.length >= HEADER_SIZE + 28)
    {
        this.stats.cursor_updates++;
        const id = view.getUint32(HEADER_SIZE + 16, true);
        let resource = this.resources.get(id);
        if(!resource)
        {
            this.cursor.move(x, y, false);
            return;
        }
        if(resource.blob)
        {
            // a cursor in guest memory: 64 x 64, ARGB (DRM's cursor planes)
            const data = new Uint8Array(64 * 64 * 4);
            if(!this.read_backing(resource, 0, data, 0, data.length)) return;
            resource = { format: 1, width: 64, height: 64, data, three_d: false };
        }
        const convert = TO_RGBA[resource.format], shift = ALPHA_SHIFT[resource.format];
        if(!convert) return;
        const hot_x = view.getUint32(HEADER_SIZE + 20, true), hot_y = view.getUint32(HEADER_SIZE + 24, true);
        const define = () => {
            const pixels = new Int32Array(resource.data.buffer);
            // premultiplied 0xAARRGGBB (as DRM's cursor planes are by default)
            this.cursor.define_alpha(hot_x, hot_y, resource.width, resource.height, i => {
                const rgba = convert(pixels[i]), alpha = shift === undefined ? 0xFF : pixels[i] >>> shift & 0xFF;
                return alpha << 24 | (rgba & 0xFF) << 16 | rgba & 0xFF00 | rgba >>> 16 & 0xFF;
            });
            this.cursor.move(x, y, true);
            this.cursor_shown();
        };
        if(resource.three_d && !(resource.host_newer && resource.data))
        {
            // (drawn on the GPU: read back first)
            this.virgl.read_picture(/** @type {!Resource3D} */ (resource), 0, 0, resource.width, resource.height, (first, count) => {
                if(first + count === resource.height && this.resources.get(id) === resource) define();
            });
            return;
        }
        define();
    }
    else if(type === CMD_MOVE_CURSOR)
    {
        this.stats.cursor_moves++;
        this.cursor.move(x, y, this.cursor.visible);
    }
    this.cursor_shown();
};

/** A cursor over a picture the renderer shows: the device's picture again, read back */
VirtioGPU.prototype.cursor_shown = function()
{
    if(!this.cursor.visible) return;
    for(const s of this.scanouts)
    {
        const r = s.direct && this.resources.get(s.resource_id);
        if(r) this.present(s, r, 0, 0, s.width, s.height);
    }
};

// ---------------------------------------------------------------------------
// The scanout

/** @override */
VirtioGPU.prototype.vblank_period = function()
{
    return this.active ? 1000 / 60 : this.vga.vblank_period();
};

/** @override */
VirtioGPU.prototype.on_vblank = function()
{
    this.vga.on_vblank();
    // (a new layout goes to the display now, not with the next render: a
    // page still in text mode asks for no frames, and without VGA nothing
    // else takes it out of it; a 3D scanout shown by the renderer needs the
    // screen at its size too)
    if(this.active)
    {
        this.place_scanouts();
        const shown = this.scanouts.filter(s => s.enabled || s.rgba);
        if(shown.some(s => s.rgba)) this.layout(shown);
    }
};

/** @override */
VirtioGPU.prototype.invalidate = function()
{
    if(this.active)
    {
        this.layout_key = "";
        this.cursor.drawn = null;
    }
    else
    {
        this.vga.invalidate();
    }
};

/**
 * The page's picture: the displays side by side (each the size it shows, or
 * the size the page asked for while it shows nothing). A new layout goes to
 * the display at once, and the next render sends all of the picture.
 * @param {!Array<!Scanout>} shown
 * @return {!Array<!Array<number>>} each display's box: x, y, width, height
 */
VirtioGPU.prototype.layout = function(shown)
{
    let width = 0, height = 0;
    const boxes = shown.map(s => {
        const w = s.rgba ? s.width : s.host_width, h = s.rgba ? s.height : s.host_height;
        const box = [width, 0, w, h];
        width += w;
        height = Math.max(height, h);
        return box;
    });
    const key = boxes.join(";");
    if(key !== this.layout_key)
    {
        this.layout_key = key;
        this.display.set_mode(true);
        this.display.set_size_graphical(width, height, width, height, 32);
        this.cursor.drawn = null;
        this.layout_all = true;
        if(!this.blank || this.blank.length < width * height * 4) this.blank = new Uint8ClampedArray(width * height * 4);
    }
    return boxes;
};

/** @override */
VirtioGPU.prototype.render = function()
{
    if(!this.active)
    {
        this.vga.render();
        return;
    }
    this.place_scanouts();
    const shown = this.scanouts.filter(s => s.enabled || s.rgba);
    const boxes = this.layout(shown);
    const all = this.layout_all;
    this.layout_all = false;
    const layers = [];
    shown.forEach((s, i) => {
        const [bx, by, bw, bh] = boxes[i];
        if(!s.rgba)
        {
            if(all) layers.push({ pixels: { data: this.blank, width: bw, height: bh }, screen_x: bx, screen_y: by,
                buffer_x: 0, buffer_y: 0, buffer_width: bw, buffer_height: bh });
            return;
        }
        const d = all ? [0, 0, s.width, s.height] : s.dirty;
        s.dirty = null;
        if(!d) return;
        layers.push({ pixels: { data: s.rgba, width: s.width, height: s.height }, screen_x: bx + d[0], screen_y: by + d[1],
            buffer_x: d[0], buffer_y: d[1], buffer_width: d[2] - d[0], buffer_height: d[3] - d[1] });
    });
    // the cursor, over whatever display it is on
    const at = (px, py) => {
        for(let i = 0; i < shown.length; i++)
        {
            const s = shown[i], [bx, , bw, bh] = boxes[i];
            if(s.rgba && px >= bx && py >= 0 && px < bx + bw && py < bh) return { s, sx: px - bx, sy: py, bx };
        }
        return null;
    };
    layers.push(...this.cursor.layers(
        (px, py) => {
            const hit = at(px, py);
            return hit ? { data: hit.s.rgba, at: (hit.sy * hit.s.width + hit.sx) * 4 } : null;
        },
        (rx, ry, w, h) => {
            const out = [];
            shown.forEach((s, i) => {
                if(!s.rgba) return;
                const [bx, , bw, bh] = boxes[i];
                const x0 = Math.max(rx, bx), y0 = Math.max(ry, 0), x1 = Math.min(rx + w, bx + bw), y1 = Math.min(ry + h, bh);
                if(x0 < x1 && y0 < y1)
                {
                    out.push({ pixels: { data: s.rgba, width: s.width, height: s.height }, screen_x: x0, screen_y: y0,
                        buffer_x: x0 - bx, buffer_y: y0, buffer_width: x1 - x0, buffer_height: y1 - y0 });
                }
            });
            return out;
        }));
    if(layers.length) this.display.update_buffer(layers);
};

// ---------------------------------------------------------------------------
// Snapshots

/**
 * Before a save: the GPU's work done, then the 3D resources' contents read
 * back (a snapshot keeps them: they are the host's, not in guest memory)
 */
VirtioGPU.prototype.prepare_save = function()
{
    const virgl = this.virgl;
    if(!virgl) return Promise.resolve(undefined);
    const resources = /** @type {!Array<!Resource3D>} */ ([...this.resources.values()].filter(r => r.three_d && !r.pipe));
    // (the mappings' newest bytes into their blobs, and back)
    this.upload_hostmem();
    const kind = this.venus || this.gfxstream;
    const done = () => new Promise(resolve => virgl.after_work(() => resolve(undefined)));
    return done().then(() => virgl.save_contents(resources)).then(() => {
        if(!kind) return undefined;
        // Venus, gfxstream: the requests that wait (SUBMIT_3D) answered, the
        // GPU's work done, then its memories' and images' contents read back
        return kind.settle(() => !this.pending.length).then(done).then(() => kind.vk.save_contents());
    });
};

/** 2: with the 3D resources and virgl's contexts; 3: with Venus's (and, since 2026-10-20, the requests not answered yet;
 * since 2026-10-24, at level gfxstream, gfxstream's in Venus's places and its process pipes) */
const STATE_VERSION = 3;

VirtioGPU.prototype.get_state = function()
{
    // (Venus's blobs and state, or at level gfxstream gfxstream's)
    const kind = this.venus || this.gfxstream;
    const resources = [], resources_3d = [], blobs = [], kind_blobs = [], pipes = [];
    for(const found of this.resources.values())
    {
        if(found.kind)
        {
            const b = /** @type {!VenusBlob} */ (found);
            kind_blobs.push([b.id, b.ctx_id, b.blob_id, b.blob_flags, b.blob_size, b.map_offset,
                b.map_offset >= 0 ? this.hostmem_bytes().slice(b.map_offset, b.map_offset + b.blob_size) : null]);
            continue;
        }
        if(found.pipe)
        {
            // (gfxstream's process pipes: a process keeps its own open)
            const r = /** @type {!Resource3D} */ (found);
            pipes.push([r.id, r.target, r.format, r.bind, r.width, r.height, r.depth, r.array_size, r.last_level, r.nr_samples, r.flags,
                r.backing, r.uuid, /** @type {!Gfxstream} */ (this.gfxstream).save_pipe(/** @type {!Object} */ (r.pipe))]);
            continue;
        }
        if(found.three_d)
        {
            const r = /** @type {!Resource3D} */ (found);
            resources_3d.push([r.id, r.target, r.format, r.bind, r.width, r.height, r.depth, r.array_size, r.last_level,
                r.nr_samples, r.flags, r.backing, r.uuid, r.saved || [], r.data, r.host_newer, r.blob_flags, r.blob_size,
                r.map_offset, r.map_offset >= 0 ? this.hostmem_bytes().slice(r.map_offset, r.map_offset + r.blob_size) : null]);
            continue;
        }
        if(found.blob)
        {
            blobs.push([found.id, found.flags, found.size, found.backing, found.uuid]);
            continue;
        }
        const r = /** @type {!Resource} */ (found);
        resources.push([r.id, r.format, r.width, r.height, r.data, r.backing, r.uuid]);
    }
    return [
        STATE_VERSION,
        this.level,
        this.num_scanouts,
        this.vga.get_state(),
        // (v86's own object: v86 saves and restores it)
        this.virtio["transport"](),
        resources,
        this.scanouts.map(s => [s.enabled, s.host_width, s.host_height, s.resource_id, s.x, s.y, s.width, s.height]),
        this.cursor.get_state(),
        this.events_read,
        this.active,
        resources_3d,
        this.virgl ? this.virgl.get_state() : null,
        blobs,
        this.scanouts.map(s => s.blob ? [s.blob.width, s.blob.height, s.blob.format, s.blob.stride, s.blob.offset] : null),
        kind_blobs,
        kind ? kind.get_state() : null,
        // the control requests not answered yet, in order: their heads in the
        // queue, headers and answers; a Venus submission's commands from the
        // one it waits in, a gfxstream one's sync commands (prepare_save
        // waits for them, a while at most)
        this.restored_requests || this.pending.filter(e => typeof e.request["head"] === "number").map(e => [e.request["head"],
            e.bytes.slice(0, HEADER_SIZE), e.response, e.ready, e.hold, e.submission && kind ? kind.save_submission(e.submission) : null]),
        pipes,
    ];
};

VirtioGPU.prototype.set_state = function(state)
{
    if(state[0] !== 1 && state[0] !== 2 && state[0] !== STATE_VERSION)
    {
        throw new Error("virtio_gpu: unsupported state version " + state[0]);
    }
    if(state[1] !== this.level || state[2] !== this.num_scanouts)
    {
        throw new Error("virtio_gpu: the snapshot is from level " + state[1] + " with " + state[2] +
            " displays; this device has level " + this.level + " with " + this.num_scanouts);
    }
    this.vga.set_state(state[3]);
    this.virtio["set_transport"](state[4]);
    this.forget_requests();
    this.unmap_all();
    this.resources.clear();
    this.host_memory = 0;
    this.mapped.clear();
    if(this.hostmem_pending)
    {
        // (what the guest wrote before belongs to the old machine)
        this.take_hostmem_dirty();
        this.hostmem_pending.fill(0);
    }
    for(const [id, format, width, height, data, backing, uuid] of state[5])
    {
        const r = new Resource(id, format, width, height);
        r.data.set(data);
        if(backing) r.set_backing(Float64Array.from(backing));
        r.uuid = uuid ? Uint8Array.from(uuid) : null;
        this.resources.set(id, r);
        this.host_memory += r.data.length;
    }
    for(const [id, flags, size, backing, uuid] of state[12] || [])
    {
        const r = new BlobResource(id, flags, size);
        if(backing) r.set_backing(Float64Array.from(backing));
        r.uuid = uuid ? Uint8Array.from(uuid) : null;
        this.resources.set(id, r);
    }
    (state[13] || []).forEach((b, i) => {
        if(b && this.scanouts[i]) this.scanouts[i].pending_blob = { width: b[0], height: b[1], format: b[2], stride: b[3], offset: b[4] };
    });
    // 3D: GX starts again from the resources and contexts saved
    if(this.virgl)
    {
        this.virgl.reset();
        for(const [id, target, format, bind, width, height, depth, array_size, last_level, nr_samples, flags, backing, uuid,
            saved, data, host_newer, blob_flags, blob_size, map_offset, mapping] of state[10] || [])
        {
            const r = new Resource3D(id, target, format, bind, width, height, depth, array_size, last_level, nr_samples, flags);
            if(blob_flags !== undefined && blob_flags >= 0)
            {
                r.blob_flags = blob_flags;
                r.blob_size = blob_size;
                if(map_offset >= 0 && mapping && this.hostmem_region >= 0)
                {
                    r.map_offset = map_offset;
                    this.hostmem_bytes().set(mapping, map_offset);
                    this.mapped.set(id, r);
                }
            }
            r.set_backing = Resource.prototype.set_backing;
            if(backing) r.set_backing(Float64Array.from(backing));
            r.uuid = uuid ? Uint8Array.from(uuid) : null;
            r.saved = saved;
            r.data = data ? Uint8Array.from(data) : null;
            r.host_newer = !!host_newer;
            this.resources.set(id, r);
            this.virgl.restore_resource(r);
            r.saved = null;
        }
        if(state[11]) this.virgl.set_state(state[11], id => this.resources.get(id) || null);
    }
    // Venus (or gfxstream): its blobs, mapped where they were, then its contexts
    const kind = this.venus || this.gfxstream;
    for(const [id, ctx_id, blob_id, flags, size, map_offset, mapping] of state[14] || [])
    {
        // (gfxstream's blobs are as Venus's to the device)
        const blob = /** @type {?} */ (this.venus ? new VenusBlob(id, ctx_id, blob_id, flags, size) : new GfxstreamBlob(id, ctx_id, blob_id, flags, size));
        blob.kind = kind;
        if(map_offset >= 0 && mapping && this.hostmem_region >= 0)
        {
            blob.map_offset = map_offset;
            this.hostmem_bytes().set(mapping, map_offset);
            this.mapped.set(id, blob);
        }
        this.resources.set(id, blob);
    }
    if(this.venus)
    {
        if(state[15]) this.venus.set_state(state[15], id => { const r = this.resources.get(id); return r && r.venus ? /** @type {!VenusBlob} */ (r) : null; });
        else this.venus.reset();
    }
    if(this.gfxstream)
    {
        const gfxstream = this.gfxstream;
        for(const [id, target, format, bind, width, height, depth, array_size, last_level, nr_samples, flags, backing, uuid, pipe] of state[17] || [])
        {
            const r = new Resource3D(id, target, format, bind, width, height, depth, array_size, last_level, nr_samples, flags);
            r.set_backing = Resource.prototype.set_backing;
            if(backing) r.set_backing(Float64Array.from(backing));
            r.uuid = uuid ? Uint8Array.from(uuid) : null;
            r.pipe = gfxstream.restore_pipe(pipe);
            this.resources.set(id, r);
        }
        if(state[15]) gfxstream.set_state(state[15], id => { const r = this.resources.get(id); return r instanceof GfxstreamBlob ? r : null; });
        else gfxstream.reset();
    }
    state[6].forEach(([enabled, host_width, host_height, resource_id, x, y, width, height], i) => {
        const s = this.scanouts[i];
        Object.assign(s, { enabled, host_width, host_height, resource_id: 0, x, y, width: 0, height: 0, rgba: null, dirty: null,
            blob: s.pending_blob || null });
        s.pending_blob = null;
        const resource = resource_id && this.resources.get(resource_id);
        if(resource)
        {
            s.rgba = new Uint8ClampedArray(width * height * 4);
            Object.assign(s, { resource_id, width, height });
            this.present(s, resource, 0, 0, width, height);
        }
    });
    this.cursor.set_state(state[7]);
    this.events_read = state[8];
    this.active = state[9];
    this.layout_key = "";
    if(!this.active) this.vga.redisplay();
    this.restored_requests = state[16] && state[16].length ? state[16] : null;
};
                                                                                                                                                                                                                                                                           source/v64/src/graphics_adapters/vmware_svga/plugin.js                                              0000644 0000000 0000000 00000003303 00000000000 020312  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // graphics_adapter: "vmware_svga" -- VMware SVGA II (15AD:0405).
// Built into build/v86-vmware-svga.js; from the source tree,
// src/graphics_adapter.js imports this file directly.

import { GraphicsMachine, register_graphics_adapter } from "../machine.js";
import { SVGADevice } from "./svga_device.js";
import { SVGA3D_HWVERSION_WS8_B1 as SVGA3D_HWVERSION } from "./svga_constants.js";

register_graphics_adapter({
    "name": "vmware_svga",
    // The VGA BIOS's PCI ROM header must name the device (SeaBIOS checks it)
    "pci_vendor": 0x15AD,
    "pci_device": 0x0405,
    "create": (handle, options) =>
    {
        const test = options["test"] || {};
        const device = new SVGADevice(new GraphicsMachine(handle), {
            vram_size: options["vram_size"],
            // without it, the highest level there is a renderer for
            level: test["level"],
            // the channel to the 3D renderer (svga_renderer.js); tests bring their own
            renderer: options["renderer"] || test["renderer"],
        });
        return {
            "vga": device.vga,
            "svga": device,
            "get_state": () => device.get_state(),
            "set_state": state => device.set_state(state),
            "reset": () => device.reset(),
            // a snapshot of the 3D levels needs the GPU's contents first
            "has_host_state": () => !!device.svga3d,
            // for the VMware backdoor (src/vmware.js, GET_SVGA_CAPABILITIES)
            "svga_capabilities": () => ({
                "capabilities": device.caps,
                "hardware_version": device.svga3d ? SVGA3D_HWVERSION : 0,
            }),
            "prepare_save": () => device.prepare_save(),
        };
    },
});
                                                                                                                                                                                                                                                                                                                             source/v64/src/graphics_adapters/vmware_svga/svga3d.js                                              0000644 0000000 0000000 00000335437 00000000000 020223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Legacy 3D (level vgpu9; docs/gpu-devices.md, "VMware SVGA II"): the SVGA3D
// commands of VMware's pre-guest-backed 3D, the D3D9-shaped API that Windows'
// vm3d and Mesa's svga driver speak to a device without SVGA_CAP_GBOBJECTS.
//
// The CPU side (this file) validates commands, reads the guest memory they
// refer to, and writes self-contained D9WG batches (svga3d_d9wg.js) for the
// renderer, which runs them through the D3D9 executor on WebGPU
// (src/browser/glbridge/svga_renderer.js). Nothing here touches WebGPU.
//
// - Each SVGA3D context is a D9WG device of its own: the executor keeps the
//   whole D3D9 state per device, so switching contexts needs no shadowing.
//   Surfaces, shaders and declarations are resources every device can use.
// - A surface is a D9WG texture (2D, cube, volume or depth), created when it
//   is defined. A buffer surface (SVGA3D_BUFFER) is a vertex buffer, a 16-bit
//   index buffer or a 32-bit one depending on how a draw uses it, each made
//   the first time; their bytes are kept here so a new role starts complete.
// - Pictures leave the GPU through readbacks: SURFACE_DMA to the guest, and
//   PRESENT / BLIT_SURFACE_TO_SCREEN, whose rows are read back and drawn into
//   the screens' pictures (or the legacy frame buffer). So the screen, the
//   cursor, screenshots and snapshots stay where the 2D levels have them.
// - Completion: fences and command buffers that follow GPU work complete
//   when the renderer has run every batch before them (after_work).
// - Snapshots (docs/gpu-devices.md, "Snapshots"): the GPU's objects have no
//   guest backing, so before a save every surface is read back
//   (prepare_save). The snapshot keeps each surface's definition and
//   contents, and each context's shaders and the last command for each piece
//   of its state; restoring replays them.

import { LOG_VGA } from "../../const.js";
import { dbg_log } from "../../log.js";
import * as C from "./svga_constants.js";
import { D9WGWriter, OP, KIND } from "./svga3d_d9wg.js";
import { RESPONSE_REGION_OFFSET, QUERY_REGION_BYTES, QUERY_SLOT_BYTES, READBACK_HEADER_BYTES, READBACK_MAX_BYTES,
    RESPONSE_OK, GXWriter, GX } from "../renderer_protocol.js";
import { DXDevice } from "./svga3d_dx.js";
import { SURFACE_DESCS, SVGA3DBLOCKDESC_BUFFER, SVGA3DBLOCKDESC_DEPTH } from "./svga_formats.js";
import { FORMATS, D3DFMT, VGPU9_DEVCAPS, PRIMITIVES, primitive_vertices, d3d_transform, d3d_light_type,
    D3DRS, SAME_RENDER_STATES, d3d_blend, D3DTSS, D3DSAMP, TEXTURE_OPS, d3d_texture_argument,
    d3d_texture_transform_flags, d3d_address, d3d_texcoord_generation } from "./svga3d_tables.js";

const INVALID = 0xFFFFFFFF;

const D3DUSAGE_RENDERTARGET = 0x1;
const D3DUSAGE_DEPTHSTENCIL = 0x2;
const D3DUSAGE_DYNAMIC = 0x200;
const D3DUSAGE_AUTOGENMIPMAP = 0x400;
const D3DQUERYTYPE_OCCLUSION = 9;
const D3DFOG_NONE = 0;
const D3DCULL_NONE = 1;
const D3DCULL_CW = 2;
const D3DCULL_CCW = 3;

/** The D9WG device for work that belongs to no context (copies, readbacks) */
const UTILITY_DEVICE = 0x7FFF0001;
/** The executor's first shader handle (D9WG_SHADER_HANDLE_BASE) */
const SHADER_HANDLE_BASE = 0x40000001;
/** Texture stages from here on are the vertex shader's samplers */
const SAMPLERS_PS = 16;
const D3DVERTEXTEXTURESAMPLER0 = 257;
const MAX_STREAMS = 16;
/** A batch is sent at the latest when it is this big */
const BATCH_FLUSH_BYTES = 8 << 20;
/** Query result slots in the response region */
const QUERY_SLOTS = QUERY_REGION_BYTES / QUERY_SLOT_BYTES;

/** SVGA3dDeclType -> bytes */
const DECL_SIZES = [4, 8, 12, 16, 4, 4, 4, 8, 4, 4, 8, 4, 8, 4, 4, 4, 8];

/** Which D9WG resources a buffer surface may have: vertex, index16, index32 */
const ROLE_VERTEX = 0;
const ROLE_INDEX16 = 1;
const ROLE_INDEX32 = 2;

/**
 * @constructor
 */
function Surface(sid, flags, format, faces, sizes, samples)
{
    this.sid = sid;
    this.flags = flags;
    this.format = format;
    /** @type {?Object} its D3D9 format, for D9WG */
    this.info = FORMATS[format] || null;
    const desc = SURFACE_DESCS[format] || SURFACE_DESCS[0];
    /** how its texels are stored: blocks of block x block_h texels, `bytes` each */
    this.layout = { block: /** @type {number} */ (desc[1]) || 1, block_h: /** @type {number} */ (desc[2]) || 1,
        bytes: /** @type {number} */ (desc[4]) };
    this.buffer = format === C.SVGA3D_BUFFER || !!(/** @type {number} */ (desc[0]) & SVGA3DBLOCKDESC_BUFFER);
    this.depth = !!(/** @type {number} */ (desc[0]) & SVGA3DBLOCKDESC_DEPTH);
    /** where its newest contents are on the GPU: "" (nowhere yet: a GB
     * surface's MOB has them), "d9wg", "gx" */
    this.home = "";
    /** it has a D9WG resource (legacy 3D used it) and a GX one (DX used it);
     * the D3D9 driver and DWM share surfaces, so it can have both */
    this.in_d9 = false;
    this.in_gx = false;
    /** the copy that is not at home is older (when it has both) */
    this.stale = false;
    this.faces = faces;
    /** [width, height, depth] of each mip level */
    this.sizes = sizes;
    this.samples = samples;
    this.handle = 0;
    this.kind = 0;
    /** @type {Uint8Array} a buffer's bytes */
    this.data = null;
    /** a buffer's D9WG buffers, by role */
    this.roles = [0, 0, 0];
    /** @type {Int32Array} the SURFACE_DEFINE(_V2) body, for snapshots */
    this.definition = null;
    this.definition_id = 0;
    /** @type {Array<Uint8Array>} contents read back for a snapshot: (face or slice, mip) */
    this.saved = null;
    // guest-backed surfaces: the MOB with their image, and the pitch of
    // its first level there if the driver gave one
    this.mob = INVALID;
    this.mob_pitch = 0;
    /** @type {?{format: number, flags: number, flags2: number, filter: number, array_size: number, pattern: number, quality: number, stride: number, layers: number}} a GB surface's definition */
    this.gb = null;
    /** the GPU may have what the MOB does not: drawn into, copied into */
    this.host_newer = false;
}

/**
 * @constructor
 */
function Context(cid, device)
{
    this.cid = cid;
    /** its D9WG device */
    this.device = device;
    /** "type:shid" -> D9WG shader handle */
    this.shaders = new Map();
    this.viewport = null;
    this.zrange = [0, 1];
    this.scissor = null;
    this.cull = C.SVGA3D_FACE_NONE;
    this.winding = C.SVGA3D_FRONTWINDING_CW;
    this.texcoord_index = new Int32Array(SAMPLERS_PS);
    this.texcoord_gen = new Int32Array(SAMPLERS_PS);
    for(let i = 0; i < SAMPLERS_PS; i++) this.texcoord_index[i] = i;
    /** streams given a frequency other than 1 by the last draw */
    this.instanced = 0;
    /** the color target 0 surface, for the clear and viewport sizes */
    this.target = null;
    /** @type {!Map<number, !Surface>} the bound targets by SVGA3dRenderTargetType: draws write them */
    this.targets = new Map();
    /** @type {!Map<string, !Int32Array>} SHADER_DEFINE bodies by "type:shid", for snapshots */
    this.shader_definitions = new Map();
    /** @type {!Map<string, !Array>} the last command setting each piece of state: [id, body] */
    this.state = new Map();
    /** @type {number|undefined} a GB context's MOB */
    this.mob = undefined;
}

/**
 * @constructor
 * @param {!Object} device the SVGADevice
 * @param {!Object} renderer the channel: post(message, transfer), listen(handler)
 */
export function SVGA3D(device, renderer)
{
    this.device = device;
    this.renderer = renderer;
    this.writer = new D9WGWriter();
    /** @type {!Map<number, !Surface>} */
    this.surfaces = new Map();
    /** @type {!Set<!Surface>} surfaces both D9WG and GX have (the D3D9 driver's and DWM's) */
    this.duals = new Set();
    /** @type {!Map<number, !Context>} */
    this.contexts = new Map();
    this.declarations = new Map();
    this.next_handle = 1;
    this.next_shader = 0;
    this.next_device = 1;
    this.next_request = 1;
    this.frame = 0;
    // batches sent and run
    this.submitted = 0;
    this.completed = 0;
    /** @type {!Array<{seq: number, run: function()}>} waiting for batches, in order */
    this.completions = [];
    /** @type {!Map<number, function(Uint8Array, number)>} request id -> answer */
    this.requests = new Map();
    this.warned = new Set();
    /** @type {?function(number, !Int32Array)} sees each command (for test harnesses) */
    this.command_log = null;
    /** @type {?function(number, number, !Uint8Array)} tests: each DX shader bound (shid, type, tokens) */
    this.shader_log = null;
    /** @type {!Array<string>} the first warnings, for test harnesses */
    this.warnings = [];
    /** @type {!Object<number, number>} how often each command came (for the harnesses) */
    this.counts = {};
    /** @type {!Object<number, number>} the batch bytes each command made (for the harnesses) */
    this.bytes = {};
    /** batch bytes sent so far */
    this.bytes_sent = 0;
    /** guest-backed objects (level gb9 and up) */
    this.gb = !!(device.caps & C.SVGA_CAP_GBOBJECTS);
    /** @type {!Map<number, {type: number, size: number, mob: number, offset: number, handle: number, code: Uint8Array}>} GB shaders by shid */
    this.gb_shaders = new Map();
    /** @type {!Map<number, {width: number, height: number, x: number, y: number, flags: number, dpi: number, image: Array<number>}>} screen targets */
    this.targets = new Map();
    /** @type {?{mob: number, maps: !Map<number, number>}} the GART: its MOB, and MOBs by page offset */
    this.gart = null;
    /** @type {DXDevice} DX contexts (level dx10 and up), drawn by GX */
    this.dx = (device.caps & C.SVGA_CAP_DX) ? new DXDevice(this) : null;
    /** @type {GXWriter} GX batches, for DX and the surfaces it uses */
    this.gxw = null;
    /** the DX context of the command buffer being run */
    this.dx_context = INVALID;
    this.streams();
    renderer.listen(message => this.receive(message));
}

/**
 * The two batch streams, D9WG and GX, go to the renderer in the order they
 * were written: starting to write one sends what the other has
 */
SVGA3D.prototype.streams = function()
{
    this.writer.before = () => { if(this.gxw && !this.gxw.empty()) this.flush(); };
    if(this.dx)
    {
        this.gxw = new GXWriter();
        this.gxw.before = () => { if(!this.writer.empty()) this.flush(); };
    }
};

/** @return {!GXWriter} */
SVGA3D.prototype.gx_writer = function()
{
    return /** @type {!GXWriter} */ (this.gxw);
};

SVGA3D.prototype.reset = function()
{
    this.writer = new D9WGWriter();
    this.streams();
    if(this.dx) this.dx.reset();
    this.dx_context = INVALID;
    this.surfaces.clear();
    this.duals.clear();
    this.contexts.clear();
    this.declarations.clear();
    this.gb_shaders.clear();
    this.targets.clear();
    this.gart = null;
    this.completions = [];
    this.requests.clear();
    this.completed = this.submitted;
    this.renderer.post({ "type": "reset" });
};

SVGA3D.prototype.warn_once = function(key, text)
{
    if(this.warned.has(key)) return;
    this.warned.add(key);
    if(this.warnings.length < 100) this.warnings.push(text);
    dbg_log("svga3d: " + text, LOG_VGA);
};

// ---------------------------------------------------------------------------
// The FIFO's 3D registers

/**
 * The 3D hardware version and the devcaps record
 * @param {!Int32Array} fifo
 */
SVGA3D.write_fifo_caps = function(fifo)
{
    fifo[C.SVGA_FIFO_3D_HWVERSION] = C.SVGA3D_HWVERSION_WS8_B1;
    fifo[C.SVGA_FIFO_3D_HWVERSION_REVISED] = C.SVGA3D_HWVERSION_WS8_B1;
    let at = C.SVGA_FIFO_3D_CAPS;
    // SVGA3dFifoCapsRecordHeader: length in dwords with itself, type
    fifo[at] = 2 + 2 * VGPU9_DEVCAPS.length;
    fifo[at + 1] = C.SVGA3D_FIFO_CAPS_RECORD_DEVCAPS;
    at += 2;
    for(const [index, value] of VGPU9_DEVCAPS)
    {
        fifo[at++] = index;
        fifo[at++] = value;
    }
    // a record of length 0 ends the list
    fifo[at] = 0;
};

// ---------------------------------------------------------------------------
// Batches and completion

/** @return {boolean} whether something sent to the renderer has not run yet */
SVGA3D.prototype.busy = function()
{
    return !this.writer.empty() || !!this.gxw && !this.gxw.empty() || this.submitted > this.completed;
};

/**
 * Send the batch being written (of either stream; one is empty)
 */
SVGA3D.prototype.flush = function()
{
    if(!this.writer.empty())
    {
        this.bytes_sent += this.writer.size();
        const bytes = this.writer.finish(++this.frame, 0);
        const seq = ++this.submitted;
        this.renderer.post({ "type": "submit", "seq": seq, "bytes": bytes }, [bytes.buffer]);
    }
    if(this.gxw && !this.gxw.empty())
    {
        this.bytes_sent += this.gxw.size();
        const bytes = this.gxw.finish();
        const seq = ++this.submitted;
        this.renderer.post({ "type": "submit", "seq": seq, "bytes": bytes, "stream": "gx" }, [bytes.buffer]);
    }
};

/** Send the batch being written if it is big */
SVGA3D.prototype.flush_big = function()
{
    if(this.writer.size() > BATCH_FLUSH_BYTES || this.gxw && this.gxw.size() > BATCH_FLUSH_BYTES) this.flush();
};

/**
 * A request for an answer from the renderer (a query result, a readback)
 * @param {function(Uint8Array, number)} answer
 * @return {{id: number, slot: number}} its id, and its query slot
 */
SVGA3D.prototype.request = function(answer)
{
    const id = this.next_request++;
    this.requests.set(id, answer);
    return { id, slot: id % QUERY_SLOTS * QUERY_SLOT_BYTES };
};

/**
 * Run `run` once everything sent so far has run (now, if it has)
 * @param {function()} run
 */
SVGA3D.prototype.after_work = function(run)
{
    this.flush();
    if(this.submitted > this.completed)
    {
        this.completions.push({ seq: this.submitted, run });
    }
    else
    {
        run();
    }
};

/**
 * @param {!Object} message from the renderer
 */
SVGA3D.prototype.receive = function(message)
{
    switch(message["type"])
    {
        case "write":
            this.answer(message["offset"], message["bytes"]);
            break;
        case "done":
            this.completed = Math.max(this.completed, message["seq"]);
            while(this.completions.length && this.completions[0].seq <= this.completed)
            {
                this.completions.shift().run();
            }
            break;
        case "lost":
            // The renderer is gone: tell the driver, and let nothing wait
            dbg_log("svga3d: the renderer was lost: " + message["reason"], LOG_VGA);
            this.device.set_irq(C.SVGA_IRQFLAG_ERROR);
            this.completed = this.submitted;
            for(const request of this.requests.values()) request(null, 0);
            this.requests.clear();
            while(this.completions.length) this.completions.shift().run();
            break;
    }
};

/**
 * A write into the response region: a query result or a readback
 * @param {number} offset from the start of the response region
 * @param {!Uint8Array} bytes
 */
SVGA3D.prototype.answer = function(offset, bytes)
{
    if(bytes.length < 16) return;
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const id = view.getUint32(0, true), status = view.getUint32(12, true);
    const request = this.requests.get(id);
    if(!request) return;
    this.requests.delete(id);
    if(offset < QUERY_REGION_BYTES)
    {
        // D9WGQueryResponse: request id, value (64 bits), status
        request(bytes.subarray(4, 12), status);
    }
    else
    {
        // D9WGReadbackResponse: request id, byte count, reserved, status, bytes
        const count = view.getUint32(4, true);
        request(status === RESPONSE_OK ? bytes.subarray(READBACK_HEADER_BYTES, READBACK_HEADER_BYTES + count) : null, status);
    }
};

// ---------------------------------------------------------------------------
// Commands

/**
 * One 3D command
 * @param {number} id SVGA_3D_CMD_*
 * @param {!Int32Array} p its body, after SVGA3dCmdHeader
 */
SVGA3D.prototype.command = function(id, p)
{
    const before = this.bytes_written();
    this.run_command(id, p);
    this.bytes[id] = (this.bytes[id] || 0) + this.bytes_written() - before;
};

/** @return {number} batch bytes written so far (sent, and being written) */
SVGA3D.prototype.bytes_written = function()
{
    return this.bytes_sent + this.writer.size() + (this.gxw ? this.gxw.size() : 0);
};

/**
 * @param {number} id SVGA_3D_CMD_*
 * @param {!Int32Array} p its body, after SVGA3dCmdHeader
 */
SVGA3D.prototype.run_command = function(id, p)
{
    const f = new Float32Array(p.buffer, p.byteOffset, p.length);
    this.counts[id] = (this.counts[id] || 0) + 1;
    if(this.command_log) this.command_log(id, p);
    if(this.dx && this.dx.command(id, p, this.dx_context))
    {
        this.flush_big();
        return;
    }
    this.record(id, p);
    switch(id)
    {
        case C.SVGA_3D_CMD_SURFACE_DEFINE: this.define_surface(p, false); break;
        case C.SVGA_3D_CMD_SURFACE_DEFINE_V2: this.define_surface(p, true); break;
        case C.SVGA_3D_CMD_SURFACE_DESTROY: if(p.length >= 1) this.destroy_surface(p[0] >>> 0); break;
        case C.SVGA_3D_CMD_SURFACE_DMA: this.surface_dma(p); break;
        case C.SVGA_3D_CMD_SURFACE_COPY: this.surface_copy(p); break;
        case C.SVGA_3D_CMD_SURFACE_STRETCHBLT: this.surface_stretch(p); break;
        case C.SVGA_3D_CMD_CONTEXT_DEFINE: if(p.length >= 1) this.define_context(p[0] >>> 0); break;
        case C.SVGA_3D_CMD_CONTEXT_DESTROY: if(p.length >= 1) this.destroy_context(p[0] >>> 0); break;
        case C.SVGA_3D_CMD_SETTRANSFORM: this.set_transform(p, f); break;
        case C.SVGA_3D_CMD_SETZRANGE: this.set_zrange(p, f); break;
        case C.SVGA_3D_CMD_SETRENDERSTATE: this.set_render_states(p, f); break;
        case C.SVGA_3D_CMD_SETRENDERTARGET: this.set_render_target(p); break;
        case C.SVGA_3D_CMD_SETTEXTURESTATE: this.set_texture_states(p, f); break;
        case C.SVGA_3D_CMD_SETMATERIAL: this.set_material(p, f); break;
        case C.SVGA_3D_CMD_SETLIGHTDATA: this.set_light(p, f); break;
        case C.SVGA_3D_CMD_SETLIGHTENABLED: this.set_light_enabled(p); break;
        case C.SVGA_3D_CMD_SETVIEWPORT: this.set_viewport(p); break;
        case C.SVGA_3D_CMD_SETCLIPPLANE: this.set_clip_plane(p, f); break;
        case C.SVGA_3D_CMD_CLEAR: this.clear(p, f); break;
        case C.SVGA_3D_CMD_PRESENT: this.present(p); break;
        case C.SVGA_3D_CMD_SHADER_DEFINE: this.define_shader(p); break;
        case C.SVGA_3D_CMD_SHADER_DESTROY: this.destroy_shader(p); break;
        case C.SVGA_3D_CMD_SET_SHADER: this.set_shader(p); break;
        case C.SVGA_3D_CMD_SET_SHADER_CONST: this.set_shader_const(p); break;
        case C.SVGA_3D_CMD_DRAW_PRIMITIVES: this.draw_primitives(p); break;
        case C.SVGA_3D_CMD_SETSCISSORRECT: this.set_scissor(p); break;
        case C.SVGA_3D_CMD_BEGIN_QUERY: this.begin_query(p); break;
        case C.SVGA_3D_CMD_END_QUERY: this.end_query(p, this.device.gmrs); break;
        case C.SVGA_3D_CMD_WAIT_FOR_QUERY:
            // the result is written when it is known; the driver polls it
            break;
        case C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN: this.blit_surface_to_screen(p); break;
        case C.SVGA_3D_CMD_GENERATE_MIPMAPS: this.generate_mipmaps(p); break;
        case C.SVGA_3D_CMD_ACTIVATE_SURFACE:
        case C.SVGA_3D_CMD_DEACTIVATE_SURFACE:
            // residency hints
            break;
        case C.SVGA_3D_CMD_PRESENT_READBACK:
        case C.SVGA_3D_CMD_SCREEN_DMA:
            this.warn_once("cmd" + id, "command " + id + " is not implemented");
            break;
        default:
            if(!(this.gb && this.gb_command(id, p)))
            {
                this.warn_once("cmd" + id, "command " + id + " ignored at level " + this.device.level);
            }
    }
    this.flush_big();
};

/**
 * Keep what a snapshot needs to set a context's state again: per piece of
 * state, the last command (split into one per state where a command sets several)
 * @param {number} id
 * @param {!Int32Array} p
 */
SVGA3D.prototype.record = function(id, p)
{
    if(!p.length) return;
    const context = this.contexts.get(p[0] >>> 0);
    if(!context) return;
    const state = context.state, cid = p[0];
    const keep = (key, body) => state.set(key, [id, body]);
    switch(id)
    {
        case C.SVGA_3D_CMD_SETTRANSFORM: keep("xf" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETZRANGE: keep("zr", p.slice()); break;
        case C.SVGA_3D_CMD_SETRENDERTARGET: keep("rt" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETMATERIAL: keep("mat" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETLIGHTDATA: keep("ld" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETLIGHTENABLED: keep("le" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETVIEWPORT: keep("vp", p.slice()); break;
        case C.SVGA_3D_CMD_SETCLIPPLANE: keep("cp" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETSCISSORRECT: keep("sc", p.slice()); break;
        case C.SVGA_3D_CMD_SET_SHADER: keep("sh" + p[1], p.slice()); break;
        case C.SVGA_3D_CMD_SETRENDERSTATE:
            for(let at = 1; at + 2 <= p.length; at += 2) keep("rs" + p[at], Int32Array.of(cid, p[at], p[at + 1]));
            break;
        case C.SVGA_3D_CMD_SETTEXTURESTATE:
            for(let at = 1; at + 3 <= p.length; at += 3) keep("ts" + p[at] + ":" + p[at + 1], Int32Array.of(cid, p[at], p[at + 1], p[at + 2]));
            break;
        case C.SVGA_3D_CMD_SET_SHADER_CONST:
            for(let r = 0; 4 + 4 * r + 4 <= p.length; r++)
            {
                const body = Int32Array.of(cid, p[1] + r, p[2], p[3], p[4 + 4 * r], p[5 + 4 * r], p[6 + 4 * r], p[7 + 4 * r]);
                keep("c" + p[2] + ":" + p[3] + ":" + (p[1] + r), body);
            }
            break;
        case C.SVGA_3D_CMD_SHADER_DEFINE:
            if(p.length >= 3) context.shader_definitions.set(p[2] + ":" + (p[1] >>> 0), p.slice());
            break;
        case C.SVGA_3D_CMD_SHADER_DESTROY:
            if(p.length >= 3) context.shader_definitions.delete(p[2] + ":" + (p[1] >>> 0));
            break;
    }
};

// ---------------------------------------------------------------------------
// Snapshots

/**
 * Before a save: the batches sent so far run, and every surface's contents
 * come back from the GPU
 * @return {!Promise<undefined>}
 */
SVGA3D.prototype.prepare_save = function()
{
    for(const surface of this.surfaces.values())
    {
        surface.saved = null;
        if(surface.gb)
        {
            // what the GPU has goes into the MOB, which is guest memory and
            // so in the snapshot; after a restore it comes from there
            if(surface.home && surface.host_newer) this.readback_gb_surface(surface);
            continue;
        }
        // depth and multisampled surfaces cannot be read back: they come back cleared
        if(!surface.handle || surface.info.depth || surface.samples > 1) continue;
        const saved = surface.saved = [];
        const volume = surface.kind === KIND.TEXTURE_VOLUME;
        for(let face = 0; face < surface.faces; face++)
        {
            for(let mip = 0; mip < surface.sizes.length; mip++)
            {
                const level = level_layout(surface, mip);
                const layers = volume ? level.depth : 1;
                const bytes = new Uint8Array(level.pitch * level.rows * layers);
                saved.push(bytes);
                for(let layer = 0; layer < layers; layer++)
                {
                    const base = layer * level.pitch * level.rows;
                    this.read_rows(surface, volume ? layer : face, mip, 0, level.rows, (data, first, count, pitch) => {
                        bytes.set(data.subarray(0, count * pitch), base + first * pitch);
                    });
                }
            }
        }
    }
    return new Promise(resolve => this.after_work(resolve));
};

SVGA3D.prototype.get_state = function()
{
    const surfaces = [];
    for(const s of this.surfaces.values())
    {
        surfaces.push([s.definition_id, s.definition, s.data, s.saved || [], s.mob, s.mob_pitch]);
    }
    const contexts = [];
    for(const c of this.contexts.values())
    {
        contexts.push([c.cid, [...c.shader_definitions.values()], [...c.state.values()].map(([id, body]) => [id, body]),
            c.mob === undefined ? null : c.mob]);
    }
    // GB shaders keep their bytecode: the MOB it came from may have changed since
    const shaders = [];
    for(const [shid, sh] of this.gb_shaders)
    {
        shaders.push([shid, sh.type, sh.size, sh.mob, sh.offset, sh.code || null]);
    }
    const targets = [];
    for(const [stid, t] of this.targets) targets.push([stid, t.width, t.height, t.x, t.y, t.flags, t.dpi, t.image]);
    return [3, surfaces, contexts, shaders, targets, this.dx ? this.dx.get_state() : null];
};

/**
 * Make the GPU's objects again, in a fresh renderer
 */
SVGA3D.prototype.set_state = function(state)
{
    this.reset();
    if(!state || state[0] < 1 || state[0] > 3) return;
    for(const [id, definition, data, saved, mob, mob_pitch] of state[1])
    {
        const body = Int32Array.from(definition);
        this.command(id, body);
        const surface = this.surfaces.get(body[0] >>> 0);
        if(!surface) continue;
        if(mob !== undefined)
        {
            surface.mob = mob;
            surface.mob_pitch = mob_pitch;
        }
        if(surface.data && data) surface.data.set(data);
        if(!surface.handle || !saved.length) continue;
        const volume = surface.kind === KIND.TEXTURE_VOLUME;
        let i = 0;
        for(let face = 0; face < surface.faces; face++)
        {
            for(let mip = 0; mip < surface.sizes.length; mip++)
            {
                const bytes = saved[i++];
                if(!bytes) continue;
                const level = level_layout(surface, mip);
                const w = this.writer.begin(OP.UPDATE_TEXTURE).u32(surface.handle).u32(mip).u32(0).u32(0)
                    .u32(volume ? 0 : surface.kind === KIND.TEXTURE_CUBE ? face : 0)
                    .u32(level.width).u32(level.height).u32(volume ? level.depth : 1)
                    .u32(level.pitch).u32(level.pitch * level.rows).u32(bytes.length);
                w.patch(w.placeholder(), w.data(bytes));
                if(this.writer.size() > BATCH_FLUSH_BYTES) this.flush();
            }
        }
    }
    if(state[0] >= 2)
    {
        for(const [shid, type, size, mob, offset, code] of state[3])
        {
            this.gb_shaders.set(shid, { type, size, mob, offset, handle: 0, code: null });
            if(code) this.create_gb_shader(this.gb_shaders.get(shid), new Uint8Array(code));
        }
        for(const [stid, width, height, x, y, flags, dpi, image] of state[4])
        {
            // (the screens keep their pictures themselves)
            this.targets.set(stid, { width, height, x, y, flags, dpi, image: image && Array.from(image) });
        }
    }
    for(const [cid, shaders, entries, mob] of state[2])
    {
        this.command(C.SVGA_3D_CMD_CONTEXT_DEFINE, Int32Array.of(cid));
        if(mob !== null && mob !== undefined) this.contexts.get(cid).mob = mob;
        for(const body of shaders) this.command(C.SVGA_3D_CMD_SHADER_DEFINE, Int32Array.from(body));
        for(const [id, body] of entries) this.command(id, Int32Array.from(body));
    }
    if(state[0] >= 3 && this.dx) this.dx.set_state(state[5]);
    this.flush();
};

/**
 * An object in a table the driver set up again (SET_OTABLE_BASE with valid
 * entries, after a reset): defined again from its entry
 * @param {!Uint32Array} e the entry
 */
SVGA3D.prototype.load_entry = function(type, index, e)
{
    switch(type)
    {
        case C.SVGA_OTABLE_SURFACE:
        {
            // as DEFINE_GB_SURFACE_V4, then its image from the MOB
            this.define_gb_surface(Int32Array.of(index, e[1], e[11], e[0], e[2], e[3], e[12] & 0xFF, e[12] >>> 8 & 0xFF,
                e[4], e[5], e[6], e[7], e[9], e[12] >>> 16), 4);
            const surface = this.surfaces.get(index);
            if(surface && e[8] !== INVALID)
            {
                this.bind_gb_surface(surface, e[8], e[10]);
                this.update_gb_surface(surface);
            }
            break;
        }
        case C.SVGA_OTABLE_CONTEXT:
            this.define_gb_context(e[0]);
            this.bind_gb_context(e[0], e[1], 0);
            break;
        case C.SVGA_OTABLE_SHADER:
            this.define_gb_shader(index, e[0], e[1]);
            this.bind_gb_shader(index, e[3], e[2]);
            break;
        case C.SVGA_OTABLE_SCREENTARGET:
            this.define_screen_target(index, e[3], e[4], e[5] | 0, e[6] | 0, e[7], e[8]);
            if(e[0] !== INVALID) this.bind_screen_target(index, e[0], e[1], e[2]);
            break;
    }
};

// ---------------------------------------------------------------------------
// Surfaces

/**
 * SURFACE_DEFINE(_V2): sid, flags, format, face[6].numMipLevels
 * (V2: multisampleCount, autogenFilter), then an SVGA3dSize per mip of each face
 */
SVGA3D.prototype.define_surface = function(p, v2)
{
    const head = v2 ? 11 : 9;
    if(p.length < head) return;
    const sid = p[0] >>> 0, flags = p[1] >>> 0, format = p[2] >>> 0;
    const mips = p[3] >>> 0;
    let faces = 0;
    for(let i = 0; i < 6; i++) if(p[3 + i]) faces++;
    const samples = v2 ? p[9] >>> 0 : 0;
    if(!mips || !faces || p.length < head + 3 * mips * faces)
    {
        this.warn_once("define", "a surface definition without sizes");
        return;
    }
    const sizes = [];
    for(let i = 0; i < mips; i++)
    {
        const at = head + 3 * i;
        sizes.push([p[at] >>> 0, p[at + 1] >>> 0, Math.max(1, p[at + 2] >>> 0)]);
    }
    const surface = this.create_surface(sid, flags, format, faces, sizes, samples, false);
    surface.definition = p.slice();
    surface.definition_id = v2 ? C.SVGA_3D_CMD_SURFACE_DEFINE_V2 : C.SVGA_3D_CMD_SURFACE_DEFINE;
};

/**
 * A surface and its D9WG resource (a buffer gets its resources as draws use it)
 * @param {!Array<!Array<number>>} sizes [width, height, depth] of each mip level
 * @return {!Surface}
 */
SVGA3D.prototype.create_surface = function(sid, flags, format, faces, sizes, samples, lazy)
{
    if(this.surfaces.has(sid)) this.destroy_surface(sid);
    const surface = new Surface(sid, flags, format, faces, sizes, samples);
    this.surfaces.set(sid, surface);
    // a legacy surface lives in D9WG from the start; a GB one where it is used first
    if(!lazy) this.make_d9wg(surface);
    return surface;
};

/**
 * The D9WG resource of a surface (a buffer: its bytes here; its D9WG buffers
 * are made as draws use it)
 */
SVGA3D.prototype.make_d9wg = function(surface)
{
    const info = surface.info, flags = surface.flags, sizes = surface.sizes, faces = surface.faces;
    const mips = sizes.length, samples = surface.samples;
    // (the caller copies what GX has, if it has the newest contents)
    const fill = !surface.home;
    if(fill) surface.home = "d9wg";
    surface.in_d9 = true;
    if(!info)
    {
        this.warn_once("format" + surface.format, "surface format " + surface.format + " is not supported by legacy 3D");
        return;
    }
    const [width, height, depth] = sizes[0];
    if(!info.d3d)
    {
        surface.data = new Uint8Array(width * height * depth);
        if(fill && surface.gb && surface.mob !== INVALID)
        {
            const bytes = this.device.mobs.read(surface.mob, 0, surface.data.length);
            if(bytes) surface.data.set(bytes);
        }
        return;
    }

    const handle = surface.handle = this.next_handle++;
    const w = this.writer;
    let usage = 0;
    if(info.depth) usage |= D3DUSAGE_DEPTHSTENCIL;
    else if(info.target && info.block === 1) usage |= D3DUSAGE_RENDERTARGET;
    if(flags & C.SVGA3D_SURFACE_AUTOGENMIPMAPS) usage |= D3DUSAGE_AUTOGENMIPMAP;
    if(faces === 6 && (flags & C.SVGA3D_SURFACE_CUBEMAP))
    {
        surface.kind = KIND.TEXTURE_CUBE;
        w.begin(OP.CREATE_TEXTURE_CUBE).u32(UTILITY_DEVICE).u32(handle).u32(width).u32(mips)
            .u32(info.d3d).u32(usage).u32(0).u32(0);
    }
    else if(depth > 1 || (flags & C.SVGA3D_SURFACE_VOLUME))
    {
        surface.kind = KIND.TEXTURE_VOLUME;
        w.begin(OP.CREATE_TEXTURE_VOLUME).u32(UTILITY_DEVICE).u32(handle).u32(width).u32(height).u32(depth)
            .u32(mips).u32(info.d3d).u32(usage).u32(0).u32(0);
    }
    else
    {
        surface.kind = KIND.TEXTURE_2D;
        // D3DMULTISAMPLE_n_SAMPLES is n
        w.begin(OP.CREATE_TEXTURE_2D).u32(UTILITY_DEVICE).u32(handle).u32(width).u32(height).u32(mips)
            .u32(info.d3d).u32(usage).u32(0).u32(samples > 1 ? samples : 0).u32(0);
    }
    // a GB surface brings what its MOB has
    if(fill && surface.gb && surface.mob !== INVALID && !surface.host_newer) this.update_gb_surface(surface);
};

/**
 * A surface's D9WG handle, made the first time legacy 3D uses it, with the
 * newest contents (copied on the GPU from GX if DX has them)
 * @param {boolean=} write whether legacy 3D will change it
 * @return {number} 0 if it has none (a buffer, or no D3D9 format)
 */
SVGA3D.prototype.d9 = function(surface, write)
{
    const made = !surface.in_d9;
    if(made)
    {
        this.make_d9wg(surface);
        if(surface.in_gx) this.duals.add(surface);
    }
    if(surface.home === "gx")
    {
        if(surface.buffer)
        {
            // (its bytes would have to come back from the GPU first)
            this.warn_once("homes", "a buffer written by DX is read by legacy 3D");
            return 0;
        }
        if((made || surface.stale) && surface.handle) this.gxw.command(GX.SURFACE_EXPORT, [surface.sid, surface.handle]);
        surface.home = "d9wg";
        surface.stale = false;
    }
    if(write && surface.in_gx) surface.stale = true;
    return surface.handle;
};

/**
 * Before a legacy draw or clear: surfaces DX changed since come over, and the
 * bound targets are written
 */
SVGA3D.prototype.drawing = function(context)
{
    if(!this.duals.size) return;
    for(const surface of this.duals) if(surface.home === "gx" && surface.stale) this.d9(surface);
    for(const surface of context.targets.values())
    {
        if(surface.in_gx && this.surfaces.get(surface.sid) === surface) this.d9(surface, true);
    }
};

/**
 * Make a surface in GX the first time DX (or a copy into a DX surface) uses
 * it, with the newest contents (copied on the GPU from D9WG if legacy 3D has them)
 * @param {boolean=} write whether DX will change it
 */
SVGA3D.prototype.gx_surface = function(surface, write)
{
    if(!this.gxw) return;
    const made = !surface.in_gx;
    if(made)
    {
        const [width, height, depth] = surface.sizes[0];
        const g = surface.gb;
        const cube = !!(surface.flags & C.SVGA3D_SURFACE_CUBEMAP);
        const layers = g ? g.layers : surface.faces;
        this.gxw.command(GX.SURFACE_DEFINE, [surface.sid, surface.format, surface.flags, g ? g.flags2 : 0,
            width, height, depth, surface.sizes.length, layers, surface.samples, cube ? 1 : 0]);
        surface.in_gx = true;
        if(surface.in_d9) this.duals.add(surface);
        if(!surface.home)
        {
            surface.home = "gx";
            if(surface.gb && surface.mob !== INVALID && !surface.host_newer) this.update_gb_surface(surface);
        }
    }
    if(surface.home === "d9wg")
    {
        if(made || surface.stale)
        {
            // a buffer's bytes are here; a texture is copied on the GPU
            if(surface.data) this.gxw.command(GX.SURFACE_UPLOAD, [surface.sid, 0, 0, 0, 0, 0,
                surface.data.length, 1, 1, surface.data.length, surface.data.length], surface.data);
            else if(surface.handle) this.gxw.command(GX.SURFACE_IMPORT, [surface.sid, surface.handle]);
        }
        surface.home = "gx";
        surface.stale = false;
    }
    if(write && surface.in_d9) surface.stale = true;
};

/**
 * Bytes for a box of an image, in its home: D9WG or GX. Rows are packed:
 * `pitch` bytes each, `rows` rows per slice.
 */
SVGA3D.prototype.upload = function(surface, layer, mip, x, y, z, w, h, d, pitch, rows, data)
{
    if(surface.in_d9 && surface.in_gx) surface.stale = true;
    if(surface.home === "gx")
    {
        this.gxw.command(GX.SURFACE_UPLOAD, [surface.sid, layer, mip, x, y, z, w, h, d, pitch, pitch * rows], data);
        return;
    }
    if(surface.buffer && surface.data)
    {
        surface.data.set(data.subarray(0, Math.min(data.length, surface.data.length - x)), x);
        for(const handle of surface.roles) if(handle) this.update_buffer(handle, x, data);
        return;
    }
    if(!surface.handle) return;
    const wr = this.writer.begin(OP.UPDATE_TEXTURE).u32(surface.handle).u32(mip)
        .u32(x).u32(y).u32(surface.kind === KIND.TEXTURE_VOLUME ? z : layer).u32(w).u32(h).u32(d)
        .u32(pitch).u32(pitch * rows).u32(data.length);
    wr.patch(wr.placeholder(), wr.data(data));
};

SVGA3D.prototype.destroy_surface = function(sid)
{
    const surface = this.surfaces.get(sid);
    if(!surface) return;
    this.surfaces.delete(sid);
    this.duals.delete(surface);
    if(surface.in_gx) this.gxw.command(GX.SURFACE_DESTROY, [sid]);
    if(!surface.in_d9) return;
    const w = this.writer;
    if(surface.handle) w.begin(OP.DESTROY_RESOURCE).u32(surface.handle).u32(surface.kind);
    for(let role = 0; role < 3; role++)
    {
        if(surface.roles[role]) w.begin(OP.DESTROY_RESOURCE).u32(surface.roles[role]).u32(role === ROLE_VERTEX ? KIND.VERTEX_BUFFER : KIND.INDEX_BUFFER);
    }
};

/**
 * The D9WG buffer of a buffer surface in a role, made (and filled) the first time
 * @return {number} 0 if the surface is not a buffer
 */
SVGA3D.prototype.buffer_role = function(surface, role)
{
    this.d9(surface);
    if(!surface.data || surface.home !== "d9wg") return 0;
    if(surface.roles[role]) return surface.roles[role];
    const handle = surface.roles[role] = this.next_handle++;
    const w = this.writer;
    const index = role !== ROLE_VERTEX;
    w.begin(OP.CREATE_BUFFER).u32(UTILITY_DEVICE).u32(handle).u32(index ? KIND.INDEX_BUFFER : KIND.VERTEX_BUFFER)
        .u32(surface.data.length).u32(D3DUSAGE_DYNAMIC)
        .u32(role === ROLE_INDEX16 ? D3DFMT.INDEX16 : role === ROLE_INDEX32 ? D3DFMT.INDEX32 : 0).u32(0).u32(0);
    this.update_buffer(handle, 0, surface.data);
    return handle;
};

SVGA3D.prototype.update_buffer = function(handle, offset, bytes)
{
    const w = this.writer.begin(OP.UPDATE_BUFFER).u32(handle).u32(offset).u32(bytes.length);
    const data_offset = w.placeholder();
    w.u32(0).u32(0);
    w.patch(data_offset, w.data(bytes));
};

/**
 * The size of a mip level in blocks, and its bytes per row
 */
function level_layout(surface, mip)
{
    const [width, height, depth] = surface.sizes[mip];
    const { block, block_h, bytes } = surface.layout;
    const columns = Math.ceil(width / block), rows = Math.ceil(height / block_h);
    return { width, height, depth, columns, rows, pitch: columns * bytes };
}

/**
 * SURFACE_DMA: guest image (gmrId, offset, pitch), host image (sid, face,
 * mipmap), transfer, then SVGA3dCopyBox[] and maybe SVGA3dCmdSurfaceDMASuffix
 */
SVGA3D.prototype.surface_dma = function(p)
{
    if(p.length < 7) return;
    const gmr = p[0] >>> 0, offset = p[1] >>> 0, pitch = p[2] >>> 0;
    const surface = this.surfaces.get(p[3] >>> 0);
    const face = p[4] >>> 0, mip = p[5] >>> 0, transfer = p[6] >>> 0;
    if(!surface || mip >= surface.sizes.length) return;
    if(!surface.home)
    {
        if(this.dx) this.gx_surface(surface);
        else this.d9(surface);
    }
    let rest = p.length - 7;
    // the suffix, if there is one, ends the command and says its own size
    if(rest % 9 === 3 && (p[p.length - 3] >>> 0) === 12) rest -= 3;
    const boxes = Math.floor(rest / 9);
    for(let i = 0; i < boxes; i++)
    {
        const b = 7 + 9 * i;
        const box = [p[b] >>> 0, p[b + 1] >>> 0, p[b + 2] >>> 0, p[b + 3] >>> 0, p[b + 4] >>> 0, p[b + 5] >>> 0,
            p[b + 6] >>> 0, p[b + 7] >>> 0, p[b + 8] >>> 0];
        const gmrs = this.device.gmrs;
        if(transfer === C.SVGA3D_WRITE_HOST_VRAM) this.dma_to_host(surface, face, mip, gmrs, gmr, offset, pitch, box);
        else if(transfer === C.SVGA3D_READ_HOST_VRAM) this.dma_to_guest(surface, face, mip, gmrs, gmr, offset, pitch, box);
    }
};

/**
 * One box from guest memory (a GMR or a MOB) into a surface
 * @param {{read: function(number, number, number):Uint8Array, write: function(number, number, !Uint8Array):boolean}} gmrs
 *     the GMRs or the MOBs
 * @param {!Array<number>} box x, y, z, w, h, d (host), srcx, srcy, srcz (guest)
 */
SVGA3D.prototype.dma_to_host = function(surface, face, mip, gmrs, gmr, offset, pitch, box)
{
    let [x, y, z, w, h, d, sx, sy, sz] = box;
    // a GB surface not on the GPU yet: its MOB is where its contents are
    if(!surface.home) return;
    if(surface.buffer)
    {
        // a buffer: bytes x..x+w from the guest's srcx
        w = Math.min(w, buffer_bytes(surface) - x);
        if(w <= 0) return;
        const bytes = gmrs.read(gmr, offset + sx, w);
        if(!bytes) return this.warn_once("dma-gmr", "SURFACE_DMA outside of its GMR");
        this.upload(surface, 0, 0, x, 0, 0, w, 1, 1, w, 1, bytes);
        return;
    }
    if(surface.home === "d9wg")
    {
        if(!surface.handle) return;
        if(surface.info.depth) return this.warn_once("dma-depth", "SURFACE_DMA into a depth surface is not supported");
    }
    const level = level_layout(surface, mip);
    const { block, block_h, bytes: bytes_per } = surface.layout;
    const volume = is_volume(surface);
    x = Math.min(x, level.width); y = Math.min(y, level.height);
    w = Math.min(w, level.width - x); h = Math.min(h, level.height - y);
    if(volume) d = Math.min(d, level.depth - z);
    else { z = 0; d = 1; sz = 0; }
    if(w <= 0 || h <= 0 || d <= 0) return;
    // in blocks
    const bx = Math.floor(x / block), by = Math.floor(y / block_h);
    const columns = Math.ceil((x + w) / block) - bx, rows = Math.ceil((y + h) / block_h) - by;
    const row_bytes = columns * bytes_per;
    const guest_slice = pitch * level.rows;
    const data = new Uint8Array(row_bytes * rows * d);
    for(let slice = 0; slice < d; slice++)
    {
        const start = offset + (sz + slice) * guest_slice + Math.floor(sy / block_h) * pitch + Math.floor(sx / block) * bytes_per;
        const span = gmrs.read(gmr, start, (rows - 1) * pitch + row_bytes);
        if(!span) return this.warn_once("dma-gmr", "SURFACE_DMA outside of its GMR");
        for(let row = 0; row < rows; row++)
        {
            data.set(span.subarray(row * pitch, row * pitch + row_bytes), (slice * rows + row) * row_bytes);
        }
    }
    this.upload(surface, volume ? 0 : face, mip, bx * block, by * block_h, z, w, h, d, row_bytes, rows, data);
};

/** The bytes of a buffer surface */
function buffer_bytes(surface)
{
    const [width, height, depth] = surface.sizes[0];
    return width * height * depth;
}

/** Whether a surface is a volume: its slices are in its levels, not its layers */
function is_volume(surface)
{
    return surface.sizes[0][2] > 1 || !!(surface.flags & C.SVGA3D_SURFACE_VOLUME);
}

/**
 * One box from a surface into guest memory (a GMR or a MOB)
 * @param {{read: function(number, number, number):Uint8Array, write: function(number, number, !Uint8Array):boolean}} gmrs
 */
SVGA3D.prototype.dma_to_guest = function(surface, face, mip, gmrs, gmr, offset, pitch, box)
{
    let [x, y, z, w, h, d, sx, sy, sz] = box;
    // a GB surface not on the GPU: its MOB already has it all
    if(!surface.home) return;
    if(surface.buffer)
    {
        w = Math.min(w, buffer_bytes(surface) - x);
        if(w <= 0) return;
        if(surface.data)
        {
            // legacy buffers only change through DMA: their bytes are here
            gmrs.write(gmr, offset + sx, surface.data.subarray(x, x + w));
            return;
        }
        const request = this.request((bytes, status) => {
            if(bytes) gmrs.write(gmr, offset + sx, bytes.subarray(0, w));
        });
        this.gxw.command(GX.SURFACE_READBACK, [surface.sid, 0, 0, x, 0, 0, w, 1, 1, request.id]);
        return;
    }
    if(surface.home === "d9wg" && (!surface.handle || surface.info.depth)) return;
    const level = level_layout(surface, mip);
    const { block, block_h, bytes: bytes_per } = surface.layout;
    const volume = is_volume(surface);
    w = Math.min(w, level.width - x); h = Math.min(h, level.height - y);
    if(!volume) { d = 1; sz = 0; z = face; }
    if(w <= 0 || h <= 0) return;
    const bx = Math.floor(x / block), by = Math.floor(y / block_h);
    const columns = Math.ceil((x + w) / block) - bx, rows = Math.ceil((y + h) / block_h) - by;
    const guest_slice = pitch * level.rows;
    for(let slice = 0; slice < d; slice++)
    {
        const layer = volume ? z + slice : z;
        const guest = offset + (sz + slice) * guest_slice + Math.floor(sy / block_h) * pitch + Math.floor(sx / block) * bytes_per;
        this.read_rows(surface, layer, mip, by, rows, (data, first, count, data_pitch) => {
            for(let row = 0; row < count; row++)
            {
                const from = row * data_pitch + bx * bytes_per;
                gmrs.write(gmr, guest + (first - by + row) * pitch, data.subarray(from, from + columns * bytes_per));
            }
        });
    }
};

/**
 * Read rows (of blocks) of a mip level of a layer (a face or array element;
 * a slice of a volume) from where the surface is: the GPU, in pieces that fit
 * the response region, or its MOB; `done` gets each piece as it arrives
 * @param {function(!Uint8Array, number, number, number, number)} done (bytes,
 *     first row, rows, pitch, first column the bytes start at)
 * @param {number=} x columns x .. x + w only, where the GPU has the surface
 *     (GX; uncompressed formats), else whole rows
 * @param {number=} w
 */
SVGA3D.prototype.read_rows = function(surface, layer, mip, first, rows, done, x, w)
{
    const level = level_layout(surface, mip);
    const block_h = surface.layout.block_h;
    // (part of the rows: GX reads back a box)
    const part = surface.home === "gx" && block_h === 1 && surface.layout.block === 1 && w !== undefined && w > 0 && w < level.width;
    const x0 = part ? /** @type {number} */ (x) : 0, width = part ? w : level.width, pitch = part ? w * surface.layout.bytes : level.pitch;
    const volume = is_volume(surface);
    if(!surface.home)
    {
        if(surface.mob === INVALID) return;
        const image = this.mob_image(surface, volume ? 0 : layer, mip);
        const start = image.offset + (volume ? layer * image.pitch * level.rows : 0) + first * image.pitch;
        const bytes = this.device.mobs.read(surface.mob, start, rows * image.pitch);
        if(bytes) done(bytes, first, rows, image.pitch, 0);
        return;
    }
    const per_request = Math.max(1, Math.floor(READBACK_MAX_BYTES / pitch));
    for(let row = first; row < first + rows; row += per_request)
    {
        const count = Math.min(per_request, first + rows - row);
        const request = this.request((bytes, status) => {
            if(bytes) done(bytes, row, count, pitch, x0);
        });
        const top = row * block_h, height = Math.min(count * block_h, level.height - row * block_h);
        if(surface.home === "gx")
        {
            this.gxw.command(GX.SURFACE_READBACK, [surface.sid, volume ? 0 : layer, mip, x0, top, volume ? layer : 0,
                width, height, 1, request.id]);
            continue;
        }
        this.writer.begin(OP.READBACK_SURFACE).u32(UTILITY_DEVICE).u32(surface.handle).u32(mip)
            .u32(surface.info.d3d).u32(level.width).u32(level.height)
            .u32(top).u32(height)
            .u32(level.pitch).u32(count * level.pitch).u32(QUERY_REGION_BYTES).u32(request.id).u32(layer);
    }
};

/** An SVGA3dSurfaceImageId: its surface */
SVGA3D.prototype.image = function(p, at)
{
    return this.surfaces.get(p[at] >>> 0) || null;
};

/**
 * Where two surfaces meet for a copy: where the destination's contents are
 * (else the source's; GX if neither has any yet, at a DX level). Both get
 * their newest contents there.
 * @return {string}
 */
SVGA3D.prototype.meet = function(src, dst)
{
    const where = dst.home || src.home || (this.dx ? "gx" : "d9wg");
    const home = where === "gx" && this.gxw ? "gx" : "d9wg";
    if(home === "gx")
    {
        this.gx_surface(src);
        this.gx_surface(dst, true);
    }
    else
    {
        this.d9(src);
        this.d9(dst, true);
    }
    return home;
};

/**
 * SURFACE_COPY: src image, dest image, then SVGA3dCopyBox[]
 */
SVGA3D.prototype.surface_copy = function(p)
{
    const src = this.image(p, 0), dst = this.image(p, 3);
    if(!src || !dst || p.length < 6) return;
    if(this.meet(src, dst) === "gx")
    {
        dst.host_newer = true;
        for(let b = 6; b + 9 <= p.length; b += 9)
        {
            // box: x, y, z, w, h, d (destination), srcx, srcy, srcz
            this.gxw.command(GX.SURFACE_COPY, [src.sid, p[1], p[2], p[b + 6], p[b + 7], p[b + 8],
                dst.sid, p[4], p[5], p[b], p[b + 1], p[b + 2], p[b + 3], p[b + 4], p[b + 5]]);
        }
        return;
    }
    for(let b = 6; b + 9 <= p.length; b += 9)
    {
        const x = p[b] >>> 0, y = p[b + 1] >>> 0, w = p[b + 3] >>> 0, h = p[b + 4] >>> 0;
        const sx = p[b + 6] >>> 0, sy = p[b + 7] >>> 0;
        if(src.data && dst.data)
        {
            const count = Math.min(w, src.data.length - sx, dst.data.length - x);
            if(count <= 0) continue;
            dst.data.set(src.data.subarray(sx, sx + count), x);
            for(const handle of dst.roles) if(handle) this.update_buffer(handle, x, dst.data.subarray(x, x + count));
            continue;
        }
        if(!src.handle || !dst.handle) continue;
        this.stretch(src, p[1] >>> 0, p[2] >>> 0, sx, sy, sx + w, sy + h, dst, p[4] >>> 0, p[5] >>> 0, x, y, x + w, y + h, true);
    }
};

/**
 * SURFACE_STRETCHBLT: src, dest, boxSrc, boxDest (x, y, z, w, h, d), mode
 */
SVGA3D.prototype.surface_stretch = function(p)
{
    const src = this.image(p, 0), dst = this.image(p, 3);
    if(!src || !dst || p.length < 18) return;
    const sx = p[6] >>> 0, sy = p[7] >>> 0, dx = p[12] >>> 0, dy = p[13] >>> 0;
    if(this.meet(src, dst) === "gx")
    {
        dst.host_newer = true;
        this.gxw.command(GX.SURFACE_STRETCH, [src.sid, p[1], p[2], sx, sy, sx + (p[9] >>> 0), sy + (p[10] >>> 0),
            dst.sid, p[4], p[5], dx, dy, dx + (p[15] >>> 0), dy + (p[16] >>> 0), (p[18] >>> 0) === C.SVGA3D_STRETCH_BLT_POINT ? 0 : 1]);
        return;
    }
    if(!src.handle || !dst.handle) return;
    this.stretch(src, p[1] >>> 0, p[2] >>> 0, sx, sy, sx + (p[9] >>> 0), sy + (p[10] >>> 0),
        dst, p[4] >>> 0, p[5] >>> 0, dx, dy, dx + (p[15] >>> 0), dy + (p[16] >>> 0), (p[18] >>> 0) === C.SVGA3D_STRETCH_BLT_POINT);
};

SVGA3D.prototype.stretch = function(src, src_face, src_mip, sl, st, sr, sb, dst, dst_face, dst_mip, dl, dt, dr, db, point)
{
    dst.host_newer = true;
    this.writer.begin(OP.STRETCH_RECT).u32(UTILITY_DEVICE)
        .u32(src.handle).u32(src_mip).i32(sl).i32(st).i32(sr).i32(sb)
        .u32(dst.handle).u32(dst_mip).i32(dl).i32(dt).i32(dr).i32(db)
        .u32(point ? 1 : 0).u32(src_face).u32(dst_face);
};

/**
 * GENERATE_MIPMAPS: sid, filter
 */
SVGA3D.prototype.generate_mipmaps = function(p)
{
    const surface = this.image(p, 0);
    if(!surface) return;
    if(!this.d9(surface, true)) return;
    surface.host_newer = true;
    this.writer.begin(OP.GENERATE_MIPS).u32(UTILITY_DEVICE).u32(surface.handle);
};

// ---------------------------------------------------------------------------
// Contexts and their state

SVGA3D.prototype.define_context = function(cid)
{
    if(this.contexts.has(cid)) this.destroy_context(cid);
    // a new D9WG device: a fresh, default D3D9 state
    this.contexts.set(cid, new Context(cid, this.next_device++));
};

SVGA3D.prototype.destroy_context = function(cid)
{
    const context = this.contexts.get(cid);
    if(!context) return;
    this.contexts.delete(cid);
    for(const [key, handle] of context.shaders)
    {
        this.writer.begin(OP.DESTROY_RESOURCE).u32(handle).u32(key.startsWith(C.SVGA3D_SHADERTYPE_VS + ":") ? KIND.VERTEX_SHADER : KIND.PIXEL_SHADER);
    }
};

/** @return {Context} the context a command names in its first dword */
SVGA3D.prototype.context = function(p)
{
    const context = p.length ? this.contexts.get(p[0] >>> 0) : undefined;
    if(!context) this.warn_once("cid", "a command for an undefined context");
    return context || null;
};

SVGA3D.prototype.set_transform = function(p, f)
{
    const context = this.context(p);
    const state = p.length >= 18 ? d3d_transform(p[1] >>> 0) : -1;
    if(!context || state < 0) return;
    const w = this.writer.begin(OP.SET_TRANSFORM).u32(context.device).u32(state);
    for(let i = 0; i < 16; i++) w.f32(f[2 + i]);
};

SVGA3D.prototype.set_zrange = function(p, f)
{
    const context = this.context(p);
    if(!context || p.length < 3) return;
    context.zrange = [f[1], f[2]];
    this.emit_viewport(context);
};

SVGA3D.prototype.set_viewport = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 5) return;
    context.viewport = [p[1] >>> 0, p[2] >>> 0, p[3] >>> 0, p[4] >>> 0];
    this.emit_viewport(context);
};

SVGA3D.prototype.emit_viewport = function(context)
{
    if(!context.viewport) return;
    const [x, y, width, height] = context.viewport;
    this.writer.begin(OP.SET_VIEWPORT).u32(context.device).u32(x).u32(y).u32(width).u32(height)
        .f32(context.zrange[0]).f32(context.zrange[1]).u32(0);
};

SVGA3D.prototype.set_scissor = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 5) return;
    const x = p[1] | 0, y = p[2] | 0;
    context.scissor = [x, y, x + (p[3] | 0), y + (p[4] | 0)];
    this.emit_scissor(context);
};

SVGA3D.prototype.emit_scissor = function(context)
{
    if(!context.scissor) return;
    const [l, t, r, b] = context.scissor;
    this.writer.begin(OP.SET_SCISSOR_RECT).u32(context.device).i32(l).i32(t).i32(r).i32(b);
};

SVGA3D.prototype.render_state = function(context, state, value)
{
    this.writer.begin(OP.SET_RENDER_STATE).u32(context.device).u32(state).u32(value).u32(0);
};

/**
 * SETRENDERSTATE: cid, then SVGA3dRenderState[] (state, value)
 */
SVGA3D.prototype.set_render_states = function(p, f)
{
    const context = this.context(p);
    if(!context) return;
    for(let at = 1; at + 2 <= p.length; at += 2)
    {
        const state = p[at] >>> 0, value = p[at + 1] >>> 0;
        const same = SAME_RENDER_STATES[state];
        if(same !== undefined)
        {
            this.render_state(context, same, value);
            continue;
        }
        switch(state)
        {
            case C.SVGA3D_RS_SRCBLEND: this.render_state(context, D3DRS.SRCBLEND, d3d_blend(value)); break;
            case C.SVGA3D_RS_DSTBLEND: this.render_state(context, D3DRS.DESTBLEND, d3d_blend(value)); break;
            case C.SVGA3D_RS_SRCBLENDALPHA: this.render_state(context, D3DRS.SRCBLENDALPHA, d3d_blend(value)); break;
            case C.SVGA3D_RS_DSTBLENDALPHA: this.render_state(context, D3DRS.DESTBLENDALPHA, d3d_blend(value)); break;
            case C.SVGA3D_RS_FILLMODE:
                // SVGA3dFillMode: mode, face (D3D9 fills both faces alike)
                this.render_state(context, D3DRS.FILLMODE, value & 0xFFFF);
                break;
            case C.SVGA3D_RS_CULLMODE:
                context.cull = value;
                this.emit_cull(context);
                break;
            case C.SVGA3D_RS_FRONTWINDING:
                context.winding = value;
                this.emit_cull(context);
                break;
            case C.SVGA3D_RS_ALPHAREF:
                // a float in [0, 1]; D3D9's is 0..255
                this.render_state(context, D3DRS.ALPHAREF, Math.max(0, Math.min(255, Math.round(f[at + 1] * 255))));
                break;
            case C.SVGA3D_RS_FOGMODE:
            {
                // SVGA3dFogMode: function (16 bits), type, base
                const fn = value & 0xFFFF, type = value >>> 16 & 0xFF, base = value >>> 24 & 0xFF;
                const mode = fn >= C.SVGA3D_FOGFUNC_EXP && fn <= C.SVGA3D_FOGFUNC_LINEAR ? fn : D3DFOG_NONE;
                this.render_state(context, D3DRS.FOGTABLEMODE, type === C.SVGA3D_FOGTYPE_PIXEL ? mode : D3DFOG_NONE);
                this.render_state(context, D3DRS.FOGVERTEXMODE, type === C.SVGA3D_FOGTYPE_VERTEX ? mode : D3DFOG_NONE);
                this.render_state(context, D3DRS.RANGEFOGENABLE, base === C.SVGA3D_FOGBASE_RANGEBASED ? 1 : 0);
                break;
            }
            case C.SVGA3D_RS_RANGEFOGENABLE:
                this.render_state(context, D3DRS.RANGEFOGENABLE, value);
                break;
            case C.SVGA3D_RS_OUTPUTGAMMA:
                // the output's gamma: 2.2 is sRGB
                this.render_state(context, D3DRS.SRGBWRITEENABLE, f[at + 1] > 1.5 ? 1 : 0);
                break;
            default:
                if(state >= C.SVGA3D_RS_WRAP0 && state <= C.SVGA3D_RS_WRAP15)
                {
                    const i = state - C.SVGA3D_RS_WRAP0;
                    this.render_state(context, i < 8 ? D3DRS.WRAP0 + i : D3DRS.WRAP8 + i - 8, value);
                }
                // LINEPATTERN, ZBIAS, ZVISIBLE, COORDINATETYPE, LINEWIDTH,
                // TRANSPARENCYANTIALIAS: nothing in D3D9 or WebGPU
                break;
        }
    }
};

/**
 * CULLMODE says which face is culled, FRONTWINDING which winding is front;
 * D3D9 says which winding is culled
 */
SVGA3D.prototype.emit_cull = function(context)
{
    let cull = D3DCULL_NONE;
    if(context.cull === C.SVGA3D_FACE_FRONT || context.cull === C.SVGA3D_FACE_BACK)
    {
        const front_cw = context.winding !== C.SVGA3D_FRONTWINDING_CCW;
        const cull_cw = (context.cull === C.SVGA3D_FACE_FRONT) === front_cw;
        cull = cull_cw ? D3DCULL_CW : D3DCULL_CCW;
    }
    this.render_state(context, D3DRS.CULLMODE, cull);
};

/**
 * SETRENDERTARGET: cid, type, target (sid, face, mipmap)
 */
SVGA3D.prototype.set_render_target = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 5) return;
    const type = p[1] >>> 0, sid = p[2] >>> 0, face = p[3] >>> 0, mip = p[4] >>> 0;
    const surface = sid === INVALID ? null : this.surfaces.get(sid) || null;
    const handle = surface && this.d9(surface, true) || 0;
    // drawn into from now on: the MOB is behind
    if(surface) surface.host_newer = true;
    if(surface) context.targets.set(type, surface);
    else context.targets.delete(type);
    if(type === C.SVGA3D_RT_DEPTH)
    {
        const size = surface ? surface.sizes[Math.min(mip, surface.sizes.length - 1)] : [0, 0];
        this.writer.begin(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL).u32(context.device).u32(handle).u32(mip).u32(size[0]).u32(size[1]);
    }
    else if(type === C.SVGA3D_RT_STENCIL)
    {
        // the depth surface carries the stencil too
    }
    else if(type >= C.SVGA3D_RT_COLOR0 && type <= C.SVGA3D_RT_COLOR3)
    {
        const index = type - C.SVGA3D_RT_COLOR0;
        this.writer.begin(OP.SET_RENDER_TARGET).u32(context.device).u32(index).u32(handle).u32(mip).u32(face);
        if(index === 0)
        {
            context.target = surface;
            // D3D9 resets the viewport and scissor with target 0; SVGA3D does not
            this.emit_viewport(context);
            this.emit_scissor(context);
        }
    }
};

/**
 * SETTEXTURESTATE: cid, then SVGA3dTextureState[] (stage, name, value)
 */
SVGA3D.prototype.set_texture_states = function(p, f)
{
    const context = this.context(p);
    if(!context) return;
    const w = this.writer, device = context.device;
    const stage_state = (stage, state, value) => {
        if(stage < 8) w.begin(OP.SET_TEXTURE_STAGE_STATE).u32(device).u32(stage).u32(state).u32(value);
    };
    for(let at = 1; at + 3 <= p.length; at += 3)
    {
        const stage = p[at] >>> 0, name = p[at + 1] >>> 0, value = p[at + 2] >>> 0;
        const sampler = stage < SAMPLERS_PS ? stage : D3DVERTEXTEXTURESAMPLER0 + stage - SAMPLERS_PS;
        const sampler_state = (state, v) => w.begin(OP.SET_SAMPLER_STATE).u32(device).u32(sampler).u32(state).u32(v);
        switch(name)
        {
            case C.SVGA3D_TS_BIND_TEXTURE:
            {
                const surface = value === INVALID ? null : this.surfaces.get(value);
                // (first: making its D9WG texture writes commands of its own)
                const handle = surface && this.d9(surface) || 0;
                w.begin(OP.SET_TEXTURE).u32(device).u32(sampler).u32(handle).u32(0);
                break;
            }
            case C.SVGA3D_TS_COLOROP: stage_state(stage, D3DTSS.COLOROP, TEXTURE_OPS[value] || 1); break;
            case C.SVGA3D_TS_ALPHAOP: stage_state(stage, D3DTSS.ALPHAOP, TEXTURE_OPS[value] || 1); break;
            case C.SVGA3D_TS_COLORARG0: stage_state(stage, D3DTSS.COLORARG0, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_COLORARG1: stage_state(stage, D3DTSS.COLORARG1, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_COLORARG2: stage_state(stage, D3DTSS.COLORARG2, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_ALPHAARG0: stage_state(stage, D3DTSS.ALPHAARG0, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_ALPHAARG1: stage_state(stage, D3DTSS.ALPHAARG1, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_ALPHAARG2: stage_state(stage, D3DTSS.ALPHAARG2, d3d_texture_argument(value)); break;
            case C.SVGA3D_TS_BUMPENVMAT00: stage_state(stage, D3DTSS.BUMPENVMAT00, value); break;
            case C.SVGA3D_TS_BUMPENVMAT01: stage_state(stage, D3DTSS.BUMPENVMAT01, value); break;
            case C.SVGA3D_TS_BUMPENVMAT10: stage_state(stage, D3DTSS.BUMPENVMAT10, value); break;
            case C.SVGA3D_TS_BUMPENVMAT11: stage_state(stage, D3DTSS.BUMPENVMAT11, value); break;
            case C.SVGA3D_TS_BUMPENVLSCALE: stage_state(stage, D3DTSS.BUMPENVLSCALE, value); break;
            case C.SVGA3D_TS_BUMPENVLOFFSET: stage_state(stage, D3DTSS.BUMPENVLOFFSET, value); break;
            case C.SVGA3D_TS_CONSTANT: stage_state(stage, D3DTSS.CONSTANT, value); break;
            case C.SVGA3D_TS_TEXTURETRANSFORMFLAGS: stage_state(stage, D3DTSS.TEXTURETRANSFORMFLAGS, d3d_texture_transform_flags(value)); break;
            case C.SVGA3D_TS_TEXCOORDINDEX:
            case C.SVGA3D_TS_TEXCOORDGEN:
                // one D3D9 state: the index, with the generation in its high bits
                if(stage >= SAMPLERS_PS) break;
                if(name === C.SVGA3D_TS_TEXCOORDINDEX) context.texcoord_index[stage] = value;
                else context.texcoord_gen[stage] = value;
                stage_state(stage, D3DTSS.TEXCOORDINDEX, context.texcoord_index[stage] | d3d_texcoord_generation(context.texcoord_gen[stage]));
                break;
            case C.SVGA3D_TS_ADDRESSU: sampler_state(D3DSAMP.ADDRESSU, d3d_address(value)); break;
            case C.SVGA3D_TS_ADDRESSV: sampler_state(D3DSAMP.ADDRESSV, d3d_address(value)); break;
            case C.SVGA3D_TS_ADDRESSW: sampler_state(D3DSAMP.ADDRESSW, d3d_address(value)); break;
            case C.SVGA3D_TS_MIPFILTER: sampler_state(D3DSAMP.MIPFILTER, value); break;
            case C.SVGA3D_TS_MAGFILTER: sampler_state(D3DSAMP.MAGFILTER, value); break;
            case C.SVGA3D_TS_MINFILTER: sampler_state(D3DSAMP.MINFILTER, value); break;
            case C.SVGA3D_TS_BORDERCOLOR: sampler_state(D3DSAMP.BORDERCOLOR, value); break;
            case C.SVGA3D_TS_TEXTURE_MIPMAP_LEVEL: sampler_state(D3DSAMP.MAXMIPLEVEL, value); break;
            case C.SVGA3D_TS_TEXTURE_LOD_BIAS: sampler_state(D3DSAMP.MIPMAPLODBIAS, value); break;
            case C.SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL: sampler_state(D3DSAMP.MAXANISOTROPY, value); break;
            case C.SVGA3D_TS_GAMMA:
                // the texture's gamma: 2.2 is sRGB
                sampler_state(D3DSAMP.SRGBTEXTURE, f[at + 2] > 1.5 ? 1 : 0);
                break;
            default:
                // the colour key states: not in D3D9
                break;
        }
    }
};

/**
 * SETMATERIAL: cid, face, SVGA3dMaterial (diffuse, ambient, specular, emissive, shininess)
 */
SVGA3D.prototype.set_material = function(p, f)
{
    const context = this.context(p);
    if(!context || p.length < 19) return;
    // D3D9 has one material, for both faces
    if((p[1] >>> 0) === C.SVGA3D_FACE_BACK) return;
    const w = this.writer.begin(OP.SET_MATERIAL).u32(context.device);
    for(let i = 0; i < 17; i++) w.f32(f[2 + i]);
};

/**
 * SETLIGHTDATA: cid, index, SVGA3dLightData
 */
SVGA3D.prototype.set_light = function(p, f)
{
    const context = this.context(p);
    if(!context || p.length < 31) return;
    const w = this.writer.begin(OP.SET_LIGHT).u32(context.device).u32(p[1] >>> 0).u32(d3d_light_type(p[2] >>> 0));
    // diffuse, specular, ambient (4 each), position, direction (3 of 4 each)
    for(let i = 4; i < 16; i++) w.f32(f[i]);
    for(let i = 16; i < 19; i++) w.f32(f[i]);
    for(let i = 20; i < 23; i++) w.f32(f[i]);
    // range, falloff, attenuation 0-2, theta, phi
    for(let i = 24; i < 31; i++) w.f32(f[i]);
};

SVGA3D.prototype.set_light_enabled = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 3) return;
    this.writer.begin(OP.LIGHT_ENABLE).u32(context.device).u32(p[1] >>> 0).u32(p[2] ? 1 : 0).u32(0);
};

SVGA3D.prototype.set_clip_plane = function(p, f)
{
    const context = this.context(p);
    if(!context || p.length < 6) return;
    this.writer.begin(OP.SET_CLIP_PLANE).u32(context.device).u32(p[1] >>> 0).f32(f[2]).f32(f[3]).f32(f[4]).f32(f[5]);
};

/**
 * CLEAR: cid, flags, color, depth, stencil, then SVGA3dRect[] (x, y, w, h)
 */
SVGA3D.prototype.clear = function(p, f)
{
    const context = this.context(p);
    if(!context || p.length < 5) return;
    this.drawing(context);
    const rects = Math.floor((p.length - 5) / 4);
    // the flag bits are D3DCLEAR's
    const w = this.writer.begin(OP.CLEAR).u32(context.device).u32(p[1] & 7).u32(p[2] >>> 0).f32(f[3]).u32(p[4] >>> 0).u32(rects);
    for(let i = 0; i < rects; i++)
    {
        const at = 5 + 4 * i, x = p[at] | 0, y = p[at + 1] | 0;
        w.i32(x).i32(y).i32(x + (p[at + 2] | 0)).i32(y + (p[at + 3] | 0));
    }
};

// ---------------------------------------------------------------------------
// Shaders

/** 64-bit FNV-1a over the tokens' bytes (d3d9_shader_pipeline.js hashTokens) */
function hash_tokens(tokens)
{
    let low = 0x84222325, high = 0xcbf29ce4;
    for(let i = 0; i < tokens.length * 4; i++)
    {
        low = (low ^ tokens[i >> 2] >>> 8 * (i & 3) & 0xFF) >>> 0;
        // times 0x100000001b3, in 16-bit limbs
        const l0 = low & 0xFFFF, l1 = low >>> 16, h0 = high & 0xFFFF, h1 = high >>> 16;
        const r0 = l0 * 0x1b3;
        const r1 = l1 * 0x1b3 + (r0 >>> 16);
        const r2 = h0 * 0x1b3 + (r1 >>> 16) + l0;
        const r3 = h1 * 0x1b3 + (r2 >>> 16) + l1;
        low = ((r1 & 0xFFFF) << 16 | r0 & 0xFFFF) >>> 0;
        high = ((r3 & 0xFFFF) << 16 | r2 & 0xFFFF) >>> 0;
    }
    return [low, high];
}

/**
 * SHADER_DEFINE: cid, shid, type, then D3D9 shader tokens
 */
SVGA3D.prototype.define_shader = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 4) return;
    const shid = p[1] >>> 0, type = p[2] >>> 0;
    if(type !== C.SVGA3D_SHADERTYPE_VS && type !== C.SVGA3D_SHADERTYPE_PS) return;
    const key = type + ":" + shid;
    if(context.shaders.has(key)) this.destroy_shader(p);
    const handle = SHADER_HANDLE_BASE + 2 * this.next_shader++;
    context.shaders.set(key, handle);
    const tokens = p.subarray(3);
    const [low, high] = hash_tokens(tokens);
    const w = this.writer.begin(type === C.SVGA3D_SHADERTYPE_VS ? OP.CREATE_VERTEX_SHADER : OP.CREATE_PIXEL_SHADER)
        .u32(context.device).u32(handle).u32(tokens.length);
    const code = w.placeholder();
    w.u32(low).u32(high);
    w.patch(code, w.data(new Uint8Array(tokens.buffer, tokens.byteOffset, tokens.byteLength)));
};

SVGA3D.prototype.destroy_shader = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 3) return;
    const type = p[2] >>> 0, key = type + ":" + (p[1] >>> 0);
    const handle = context.shaders.get(key);
    if(!handle) return;
    context.shaders.delete(key);
    this.writer.begin(OP.DESTROY_RESOURCE).u32(handle).u32(type === C.SVGA3D_SHADERTYPE_VS ? KIND.VERTEX_SHADER : KIND.PIXEL_SHADER);
};

/**
 * SET_SHADER: cid, type, shid (SVGA3D_INVALID_ID: fixed function)
 */
SVGA3D.prototype.set_shader = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 3) return;
    const type = p[1] >>> 0, shid = p[2] >>> 0;
    const gb = this.gb_shaders.get(shid);
    const handle = shid === INVALID ? 0 : context.shaders.get(type + ":" + shid) || gb && gb.type === type && gb.handle || 0;
    if(type === C.SVGA3D_SHADERTYPE_VS) this.writer.begin(OP.SET_VERTEX_SHADER).u32(context.device).u32(handle);
    else if(type === C.SVGA3D_SHADERTYPE_PS) this.writer.begin(OP.SET_PIXEL_SHADER).u32(context.device).u32(handle);
};

/**
 * SET_SHADER_CONST: cid, reg, type, ctype, then four values per register
 */
SVGA3D.prototype.set_shader_const = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 8) return;
    const reg = p[1] >>> 0, type = p[2] >>> 0, ctype = p[3] >>> 0;
    const count = Math.floor((p.length - 4) / 4);
    const vs = type === C.SVGA3D_SHADERTYPE_VS;
    if(!vs && type !== C.SVGA3D_SHADERTYPE_PS) return;
    let op, data;
    if(ctype === C.SVGA3D_CONST_TYPE_BOOL)
    {
        op = vs ? OP.SET_VERTEX_SHADER_CONSTANT_B : OP.SET_PIXEL_SHADER_CONSTANT_B;
        const bools = new Uint32Array(count);
        for(let i = 0; i < count; i++) bools[i] = p[4 + 4 * i] ? 1 : 0;
        data = new Uint8Array(bools.buffer);
    }
    else
    {
        op = ctype === C.SVGA3D_CONST_TYPE_INT ?
            (vs ? OP.SET_VERTEX_SHADER_CONSTANT_I : OP.SET_PIXEL_SHADER_CONSTANT_I) :
            (vs ? OP.SET_VERTEX_SHADER_CONSTANT_F : OP.SET_PIXEL_SHADER_CONSTANT_F);
        data = new Uint8Array(p.buffer, p.byteOffset + 16, count * 16);
    }
    const w = this.writer.begin(op).u32(context.device).u32(reg).u32(count);
    w.patch(w.placeholder(), w.data(data));
};

// ---------------------------------------------------------------------------
// Drawing

/**
 * DRAW_PRIMITIVES: cid, numVertexDecls, numRanges, then SVGA3dVertexDecl[]
 * (type, method, usage, usageIndex, surfaceId, offset, stride, first, last),
 * SVGA3dPrimitiveRange[] (primType, primitiveCount, indexArray surfaceId,
 * offset, stride, indexWidth, indexBias) and maybe SVGA3dVertexDivisor[]
 */
SVGA3D.prototype.draw_primitives = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 3) return;
    const decls = p[1] >>> 0, ranges = p[2] >>> 0;
    const ranges_at = 3 + 9 * decls, divisors_at = ranges_at + 7 * ranges;
    if(decls > 32 || ranges > 32 || p.length < divisors_at) return;
    this.drawing(context);
    const has_divisors = p.length >= divisors_at + decls;
    const w = this.writer, device = context.device;

    // Elements into streams: one per buffer and stride, split where an
    // element would not fit inside the stride from the stream's start
    const elements = [];
    for(let i = 0; i < decls; i++)
    {
        const at = 3 + 9 * i;
        elements.push({
            type: p[at] >>> 0, method: p[at + 1] >>> 0, usage: p[at + 2] >>> 0, usage_index: p[at + 3] >>> 0,
            sid: p[at + 4] >>> 0, offset: p[at + 5] >>> 0, stride: p[at + 6] >>> 0,
            divisor: has_divisors ? p[divisors_at + i] >>> 0 : 0,
        });
    }
    const order = elements.slice().sort((a, b) => a.sid - b.sid || a.stride - b.stride || a.divisor - b.divisor || a.offset - b.offset);
    const streams = [];
    for(const e of order)
    {
        const size = DECL_SIZES[e.type] || 4;
        let stream = streams[streams.length - 1];
        if(!stream || stream.sid !== e.sid || stream.stride !== e.stride || stream.divisor !== e.divisor ||
            e.stride && e.offset + size - stream.base > e.stride || e.offset - stream.base > 0xFFFF)
        {
            stream = { sid: e.sid, stride: e.stride, divisor: e.divisor, base: e.offset };
            streams.push(stream);
        }
        e.stream = streams.length - 1;
    }
    if(streams.length > MAX_STREAMS) return this.warn_once("streams", "a draw with more than 16 vertex streams");

    // the declaration, in the guest's element order (D3DVERTEXELEMENT9)
    const declaration = new Uint8Array(8 * elements.length);
    const view = new DataView(declaration.buffer);
    elements.forEach((e, i) => {
        view.setUint16(8 * i, e.stream, true);
        view.setUint16(8 * i + 2, e.offset - streams[e.stream].base, true);
        declaration.set([e.type, e.method, e.usage, e.usage_index], 8 * i + 4);
    });
    const key = declaration.join(",");
    let handle = this.declarations.get(key);
    if(!handle)
    {
        handle = this.next_handle++;
        this.declarations.set(key, handle);
        w.begin(OP.CREATE_VERTEX_DECLARATION).u32(UTILITY_DEVICE).u32(handle).u32(elements.length).u32(0);
        w.data(declaration);
    }
    w.begin(OP.SET_VERTEX_DECLARATION).u32(device).u32(handle);

    let instanced = 0;
    for(let i = 0; i < streams.length; i++)
    {
        const s = streams[i], surface = this.surfaces.get(s.sid);
        const buffer = surface ? this.buffer_role(surface, ROLE_VERTEX) : 0;
        w.begin(OP.SET_STREAM_SOURCE).u32(device).u32(i).u32(buffer).u32(s.stride).u32(s.base).u32(0);
        // SVGA3dVertexDivisor has D3DSTREAMSOURCE_INDEXEDDATA's and _INSTANCEDATA's bits
        if(s.divisor)
        {
            w.begin(OP.SET_STREAM_SOURCE_FREQ).u32(device).u32(i).u32(s.divisor);
            instanced |= 1 << i;
        }
    }
    // streams that had a frequency and now do not
    for(let i = 0; i < MAX_STREAMS; i++)
    {
        if(context.instanced & ~instanced & 1 << i) w.begin(OP.SET_STREAM_SOURCE_FREQ).u32(device).u32(i).u32(1);
    }
    context.instanced = instanced;

    for(let r = 0; r < ranges; r++)
    {
        const at = ranges_at + 7 * r;
        const type = PRIMITIVES[p[at] >>> 0], count = p[at + 1] >>> 0;
        const index_sid = p[at + 2] >>> 0, index_offset = p[at + 3] >>> 0;
        const index_width = p[at + 5] >>> 0, bias = p[at + 6] | 0;
        if(!type || !count) continue;
        if(index_sid === INVALID)
        {
            // not indexed: indexBias is the first vertex
            w.begin(OP.DRAW_PRIMITIVE).u32(device).u32(type).u32(bias).u32(count);
            continue;
        }
        const surface = this.surfaces.get(index_sid);
        if(!surface || (index_width !== 2 && index_width !== 4) || index_offset % index_width) continue;
        const buffer = this.buffer_role(surface, index_width === 2 ? ROLE_INDEX16 : ROLE_INDEX32);
        w.begin(OP.SET_INDICES).u32(device).u32(buffer);
        w.begin(OP.DRAW_INDEXED_PRIMITIVE).u32(device).u32(type).i32(bias).u32(0)
            .u32(primitive_vertices(type, count)).u32(index_offset / index_width).u32(count);
    }
};

// ---------------------------------------------------------------------------
// Queries

/**
 * BEGIN_QUERY: cid, type. Only occlusion is declared.
 */
SVGA3D.prototype.begin_query = function(p)
{
    const context = this.context(p);
    if(!context || p.length < 2 || (p[1] >>> 0) !== C.SVGA3D_QUERYTYPE_OCCLUSION) return;
    // a D9WG query per BEGIN/END pair: results can overlap
    const handle = context.query = this.next_handle++;
    this.writer.begin(OP.CREATE_QUERY).u32(context.device).u32(handle).u32(D3DQUERYTYPE_OCCLUSION).u32(0);
    this.writer.begin(OP.BEGIN_QUERY).u32(context.device).u32(handle).u32(0).u32(0);
};

/**
 * END_QUERY: cid, type, guestResult (gmrId, offset); END_GB_QUERY: cid,
 * type, mobid, offset. The result is pending until the renderer has the count.
 * @param {{write: function(number, number, !Uint8Array):boolean}} memory the GMRs or the MOBs
 */
SVGA3D.prototype.end_query = function(p, memory)
{
    const context = this.context(p);
    if(!context || p.length < 4) return;
    const gmr = p[2] >>> 0, offset = p[3] >>> 0;
    const result = (state, value) => {
        const bytes = new Uint32Array([12, state, value]);
        memory.write(gmr, offset, new Uint8Array(bytes.buffer));
    };
    const handle = context.query;
    if((p[1] >>> 0) !== C.SVGA3D_QUERYTYPE_OCCLUSION || !handle)
    {
        result(C.SVGA3D_QUERYSTATE_FAILED, 0);
        return;
    }
    context.query = 0;
    result(C.SVGA3D_QUERYSTATE_PENDING, 0);
    const id = this.next_request++;
    const slot = id % QUERY_SLOTS * QUERY_SLOT_BYTES;
    this.requests.set(id, (value, status) => {
        const count = value ? value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24 : 0;
        result(status === RESPONSE_OK ? C.SVGA3D_QUERYSTATE_SUCCEEDED : C.SVGA3D_QUERYSTATE_FAILED, count >>> 0);
    });
    this.writer.begin(OP.END_QUERY).u32(context.device).u32(handle).u32(slot).u32(id);
    this.writer.begin(OP.DESTROY_RESOURCE).u32(handle).u32(KIND.QUERY);
};

// ---------------------------------------------------------------------------
// Guest-backed objects (level gb9; docs/gpu-devices.md, "VMware SVGA II")
//
// The objects are the same as at vgpu9 (svga_gb.js has the MOBs and object
// tables); what changes is where their contents live between uses: a
// surface's image in its MOB, moved by UPDATE (MOB to GPU) and READBACK
// (GPU to MOB); a shader's bytecode in a MOB; a query's result in a MOB.
// Screen targets are screens whose picture is a surface.

/**
 * Write an object's entry in its object table
 * @param {Array<number>} dwords null clears it
 */
SVGA3D.prototype.otable = function(type, index, dwords)
{
    const tables = this.device.otables;
    if(!tables) return;
    tables.write_entry(type, index, dwords && new Uint8Array(Uint32Array.from(dwords, v => v >>> 0).buffer));
};

/**
 * The entry of a surface (SVGAOTableSurfaceEntry)
 */
SVGA3D.prototype.surface_otable = function(surface)
{
    const g = surface.gb;
    if(!g) return;
    const [width, height, depth] = surface.sizes[0];
    this.otable(C.SVGA_OTABLE_SURFACE, surface.sid, [g.format, g.flags, surface.sizes.length, surface.samples, g.filter,
        width, height, depth, surface.mob, g.array_size, surface.mob_pitch, g.flags2,
        g.pattern | g.quality << 8 | g.stride << 16, 0, 0, 0]);
};

/**
 * DEFINE_GB_SURFACE (v1 to v4)
 * @param {number} version 1 to 4
 */
SVGA3D.prototype.define_gb_surface = function(p, version)
{
    const wide = version >= 3;
    if(p.length < [9, 11, 13, 14][version - 1]) return;
    const at = wide ? 1 : 0;
    const sid = p[0] >>> 0, flags = p[1] >>> 0, flags2 = wide ? p[2] >>> 0 : 0;
    const format = p[2 + at] >>> 0, mips = Math.max(1, p[3 + at] >>> 0), samples = p[4 + at] >>> 0;
    const pattern = wide ? p[6] >>> 0 : 0, quality = wide ? p[7] >>> 0 : 0;
    const rest = wide ? 8 : 5;
    const filter = p[rest] >>> 0;
    const width = p[rest + 1] >>> 0, height = p[rest + 2] >>> 0, depth = Math.max(1, p[rest + 3] >>> 0);
    const array_size = version >= 2 ? p[rest + 4] >>> 0 : 0;
    const stride = version === 4 ? p[13] & 0xFFFF : 0;
    const cube = !!(flags & C.SVGA3D_SURFACE_CUBEMAP);
    const layers = cube ? Math.max(6, array_size) : Math.max(1, array_size);
    if(layers > (cube ? 6 : 1) && !this.dx) this.warn_once("gb-array", "surface arrays need DX (level dx10)");
    const sizes = [];
    for(let i = 0; i < mips; i++) sizes.push([Math.max(1, width >> i), Math.max(1, height >> i), Math.max(1, depth >> i)]);
    // at the DX levels a surface is made on the GPU where it is first used
    const surface = this.create_surface(sid, flags, format, cube ? 6 : 1, sizes, samples, !!this.dx);
    surface.gb = { format, flags, flags2, filter, array_size, pattern, quality, stride, layers };
    surface.definition = p.slice();
    surface.definition_id = [C.SVGA_3D_CMD_DEFINE_GB_SURFACE, C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2,
        C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V4][version - 1];
    this.surface_otable(surface);
};

SVGA3D.prototype.destroy_gb_surface = function(sid)
{
    const surface = this.surfaces.get(sid);
    if(!surface || !surface.gb) return;
    this.destroy_surface(sid);
    this.otable(C.SVGA_OTABLE_SURFACE, sid, null);
};

/**
 * Where an image of a surface is in its MOB: layer after layer, each a
 * chain of mip levels, each level packed (vmw_surf_get_image_offset)
 * @return {{offset: number, pitch: number}}
 */
SVGA3D.prototype.mob_image = function(surface, layer, mip)
{
    let chain = 0, before = 0;
    for(let i = 0; i < surface.sizes.length; i++)
    {
        const level = level_layout(surface, i);
        const pitch = i === 0 && surface.mob_pitch ? surface.mob_pitch : level.pitch;
        const bytes = pitch * level.rows * level.depth;
        if(i < mip) before += bytes;
        chain += bytes;
    }
    const pitch = mip === 0 && surface.mob_pitch ? surface.mob_pitch : level_layout(surface, mip).pitch;
    return { offset: layer * chain + before, pitch };
};

/** The layers of a surface's MOB image: cube faces (volumes keep slices in their levels) */
function layers_of(surface)
{
    return surface.gb ? surface.gb.layers : surface.faces;
}

/**
 * UPDATE_GB_IMAGE: a box of an image from the MOB to the GPU
 * @param {Array<number>} box x, y, z, w, h, d; null for all of it
 */
SVGA3D.prototype.update_gb_image = function(surface, face, mip, box)
{
    if(surface.mob === INVALID || mip >= surface.sizes.length || face >= layers_of(surface)) return;
    const { offset, pitch } = this.mob_image(surface, face, mip);
    const [width, height, depth] = surface.sizes[mip];
    const [x, y, z, w, h, d] = box || [0, 0, 0, width, height, depth];
    this.dma_to_host(surface, face, mip, this.device.mobs, surface.mob, offset, pitch, [x, y, z, w, h, d, x, y, z]);
};

SVGA3D.prototype.update_gb_surface = function(surface)
{
    if(surface.mob === INVALID) return;
    for(let face = 0; face < layers_of(surface); face++)
    {
        for(let mip = 0; mip < surface.sizes.length; mip++) this.update_gb_image(surface, face, mip, null);
    }
    surface.host_newer = false;
};

/**
 * UPDATE_ZERO_SURFACE: the surface's images become zeros (its MOB is not
 * read, VMware's DX driver sends it for resources made without contents);
 * WRITE_ZERO_SURFACE: and its MOB too
 */
SVGA3D.prototype.zero_gb_surface = function(surface, write_mob)
{
    const zeros = {
        read: /** @type {function(number, number, number): Uint8Array} */ ((id, offset, length) => new Uint8Array(length)),
        write: /** @type {function(number, number, Uint8Array): boolean} */ ((id, offset, bytes) => false),
    };
    for(let face = 0; face < layers_of(surface); face++)
    {
        for(let mip = 0; mip < surface.sizes.length; mip++)
        {
            const { offset, pitch } = this.mob_image(surface, face, mip);
            const level = level_layout(surface, mip);
            if(write_mob && surface.mob !== INVALID)
            {
                this.device.mobs.write(surface.mob, offset, new Uint8Array(pitch * level.rows * level.depth));
            }
            // (a new texture is zeros already; a multisampled one takes no upload)
            if(surface.samples > 1) continue;
            this.dma_to_host(surface, face, mip, zeros, 0, offset, pitch,
                [0, 0, 0, level.width, level.height, level.depth, 0, 0, 0]);
        }
    }
    surface.host_newer = false;
};

/**
 * READBACK_GB_IMAGE(_PARTIAL): an image from the GPU into the MOB, written
 * when the renderer has read it (fences and command buffers after it wait)
 */
SVGA3D.prototype.readback_gb_image = function(surface, face, mip, box)
{
    if(surface.mob === INVALID || mip >= surface.sizes.length || face >= layers_of(surface)) return;
    if(surface.depth || surface.samples > 1)
    {
        return this.warn_once("gb-readback-depth", "depth and multisampled surfaces are not read back");
    }
    const { offset, pitch } = this.mob_image(surface, face, mip);
    const [width, height, depth] = surface.sizes[mip];
    const [x, y, z, w, h, d] = box || [0, 0, 0, width, height, depth];
    this.dma_to_guest(surface, face, mip, this.device.mobs, surface.mob, offset, pitch, [x, y, z, w, h, d, x, y, z]);
};

/**
 * DX_UPDATE_SUBRESOURCE, DX_BUFFER_UPDATE: a box of a subresource (mip
 * levels, then array layers) from the MOB to the GPU
 * @param {Array<number>} box x, y, z, w, h, d
 */
SVGA3D.prototype.update_subresource = function(surface, subresource, box)
{
    const mips = surface.sizes.length;
    this.update_gb_image(surface, Math.floor(subresource / mips), subresource % mips, box);
};

/** DX_READBACK_SUBRESOURCE: a subresource into the MOB */
SVGA3D.prototype.readback_subresource = function(surface, subresource)
{
    const mips = surface.sizes.length;
    this.readback_gb_image(surface, Math.floor(subresource / mips), subresource % mips, null);
};

/** A whole surface into its MOB (copies that end in a readback) */
SVGA3D.prototype.readback_surface = function(surface)
{
    if(surface) this.readback_gb_surface(surface);
};

SVGA3D.prototype.readback_gb_surface = function(surface)
{
    if(surface.mob === INVALID) return;
    for(let face = 0; face < layers_of(surface); face++)
    {
        for(let mip = 0; mip < surface.sizes.length; mip++) this.readback_gb_image(surface, face, mip, null);
    }
    surface.host_newer = false;
};

/**
 * BIND_GB_SURFACE(_WITH_PITCH), COND_BIND_GB_SURFACE
 */
SVGA3D.prototype.bind_gb_surface = function(surface, mob, pitch)
{
    surface.mob = mob;
    surface.mob_pitch = pitch;
    this.surface_otable(surface);
};

/** An SVGA3dSurfaceImageId: [surface, face, mip], the surface null if it is not defined */
SVGA3D.prototype.image_id = function(p, at)
{
    return [this.surfaces.get(p[at] >>> 0) || null, p[at + 1] >>> 0, p[at + 2] >>> 0];
};

/**
 * DEFINE/BIND_GB_CONTEXT. A context's state stays with its D9WG device,
 * so its MOB is only remembered (READBACK and INVALIDATE have nothing to do)
 */
SVGA3D.prototype.define_gb_context = function(cid)
{
    this.define_context(cid);
    this.contexts.get(cid).mob = INVALID;
    this.otable(C.SVGA_OTABLE_CONTEXT, cid, [cid, INVALID]);
};

SVGA3D.prototype.bind_gb_context = function(cid, mob, valid)
{
    const context = this.contexts.get(cid);
    if(!context) return;
    context.mob = mob;
    this.otable(C.SVGA_OTABLE_CONTEXT, cid, [cid, mob]);
};

/**
 * DEFINE_GB_SHADER: shid, type, sizeInBytes. GB shaders belong to no
 * context; their bytecode comes with BIND_GB_SHADER.
 */
SVGA3D.prototype.define_gb_shader = function(shid, type, size)
{
    this.destroy_gb_shader(shid);
    this.gb_shaders.set(shid, { type, size, mob: INVALID, offset: 0, handle: 0, code: null });
    this.otable(C.SVGA_OTABLE_SHADER, shid, [type, size, 0, INVALID]);
};

SVGA3D.prototype.destroy_gb_shader = function(shid)
{
    const shader = this.gb_shaders.get(shid);
    if(!shader) return;
    if(shader.handle)
    {
        this.writer.begin(OP.DESTROY_RESOURCE).u32(shader.handle)
            .u32(shader.type === C.SVGA3D_SHADERTYPE_VS ? KIND.VERTEX_SHADER : KIND.PIXEL_SHADER);
    }
    this.gb_shaders.delete(shid);
    this.otable(C.SVGA_OTABLE_SHADER, shid, null);
};

/**
 * BIND_GB_SHADER: shid, mobid, offsetInBytes: the bytecode is read now
 */
SVGA3D.prototype.bind_gb_shader = function(shid, mob, offset)
{
    const shader = this.gb_shaders.get(shid);
    if(!shader) return;
    shader.mob = mob;
    shader.offset = offset;
    this.otable(C.SVGA_OTABLE_SHADER, shid, [shader.type, shader.size, offset, mob]);
    if(mob === INVALID) return;
    const bytes = this.device.mobs.read(mob, offset, shader.size & ~3);
    if(!bytes || shader.size < 4) return this.warn_once("gb-shader", "a shader outside of its MOB");
    if(shader.type !== C.SVGA3D_SHADERTYPE_VS && shader.type !== C.SVGA3D_SHADERTYPE_PS)
    {
        return this.warn_once("gb-shader-type", "shader type " + shader.type + " needs DX (level dx10)");
    }
    this.create_gb_shader(shader, bytes);
};

/**
 * The D9WG shader of a GB shader, from its bytecode
 * @param {!Uint8Array} bytes
 */
SVGA3D.prototype.create_gb_shader = function(shader, bytes)
{
    const kind = shader.type === C.SVGA3D_SHADERTYPE_VS ? KIND.VERTEX_SHADER : KIND.PIXEL_SHADER;
    if(shader.handle) this.writer.begin(OP.DESTROY_RESOURCE).u32(shader.handle).u32(kind);
    shader.code = bytes;
    const handle = shader.handle = SHADER_HANDLE_BASE + 2 * this.next_shader++;
    const tokens = new Int32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2);
    const [low, high] = hash_tokens(tokens);
    const w = this.writer.begin(shader.type === C.SVGA3D_SHADERTYPE_VS ? OP.CREATE_VERTEX_SHADER : OP.CREATE_PIXEL_SHADER)
        .u32(UTILITY_DEVICE).u32(handle).u32(tokens.length);
    const code = w.placeholder();
    w.u32(low).u32(high);
    w.patch(code, w.data(bytes));
};

/**
 * SET_GB_SHADERCONSTS_INLINE: cid, regStart, shaderType, constType, then
 * the values: four dwords per float or int register, one per bool. Run as
 * SET_SHADER_CONST, which has four dwords for every type.
 */
SVGA3D.prototype.set_gb_shader_consts = function(p)
{
    if(p.length < 4) return;
    if((p[3] >>> 0) !== C.SVGA3D_CONST_TYPE_BOOL)
    {
        this.command(C.SVGA_3D_CMD_SET_SHADER_CONST, p);
        return;
    }
    const count = p.length - 4;
    const body = new Int32Array(4 + 4 * count);
    body.set(p.subarray(0, 4));
    for(let i = 0; i < count; i++) body[4 + 4 * i] = p[4 + i];
    this.command(C.SVGA_3D_CMD_SET_SHADER_CONST, body);
};

/**
 * GB_MOB_FENCE: value, mobId, mobOffset: written once the work before it is done
 */
SVGA3D.prototype.mob_fence = function(value, mob, offset)
{
    this.after_work(() => {
        this.device.mobs.write32(mob, offset, value);
        this.device.set_irq(C.SVGA_IRQFLAG_MOB_FENCE);
    });
};

/**
 * The commands of guest-backed objects
 * @return {boolean} whether it was one
 */
SVGA3D.prototype.gb_command = function(id, p)
{
    const device = this.device, mobs = device.mobs;
    const u = i => p[i] >>> 0;
    const enough = n => {
        if(p.length >= n) return true;
        this.warn_once("short" + id, "command " + id + " is too short");
        return false;
    };
    switch(id)
    {
        case C.SVGA_3D_CMD_SET_OTABLE_BASE:
            if(enough(5)) device.set_otable(u(0), u(4), u(1), u(2), u(3));
            return true;
        case C.SVGA_3D_CMD_SET_OTABLE_BASE64:
            if(enough(6)) device.set_otable(u(0), u(5), u(1) + u(2) * 0x100000000, u(3), u(4));
            return true;
        case C.SVGA_3D_CMD_GROW_OTABLE:
            if(enough(6)) device.grow_otable(u(0), u(5), u(1) + u(2) * 0x100000000, u(3), u(4));
            return true;
        case C.SVGA_3D_CMD_READBACK_OTABLE:
            // the entries are written as objects change
            return true;
        case C.SVGA_3D_CMD_DEFINE_GB_MOB:
            if(enough(4)) device.define_mob(u(0), u(1), u(2), u(3));
            return true;
        case C.SVGA_3D_CMD_DEFINE_GB_MOB64:
        case C.SVGA_3D_CMD_REDEFINE_GB_MOB64:
            if(enough(5)) device.define_mob(u(0), u(1), u(2) + u(3) * 0x100000000, u(4));
            return true;
        case C.SVGA_3D_CMD_DESTROY_GB_MOB:
            if(enough(1)) device.destroy_mob(u(0));
            return true;
        case C.SVGA_3D_CMD_UPDATE_GB_MOB_MAPPING:
        {
            // the page table changed: walk it again
            const mob = enough(1) && mobs.mobs.get(u(0));
            if(mob) device.define_mob(u(0), mob.format, mob.base, mob.size);
            return true;
        }
        case C.SVGA_3D_CMD_DEFINE_GB_SURFACE: this.define_gb_surface(p, 1); return true;
        case C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2: this.define_gb_surface(p, 2); return true;
        case C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3: this.define_gb_surface(p, 3); return true;
        case C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V4: this.define_gb_surface(p, 4); return true;
        case C.SVGA_3D_CMD_DESTROY_GB_SURFACE:
            if(enough(1)) this.destroy_gb_surface(u(0));
            return true;
        case C.SVGA_3D_CMD_BIND_GB_SURFACE:
        case C.SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH:
        {
            const surface = enough(2) && this.surfaces.get(u(0));
            if(surface) this.bind_gb_surface(surface, u(1), id === C.SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH && p.length >= 3 ? u(2) : 0);
            return true;
        }
        case C.SVGA_3D_CMD_COND_BIND_GB_SURFACE:
        {
            // sid, testMobid, mobid, flags: only if it is bound to testMobid
            const surface = enough(4) && this.surfaces.get(u(0));
            if(!surface || surface.mob !== u(1)) return true;
            if(u(3) & C.SVGA3D_COND_BIND_GB_SURFACE_FLAG_READBACK) this.readback_gb_surface(surface);
            this.bind_gb_surface(surface, u(2), 0);
            if(u(3) & C.SVGA3D_COND_BIND_GB_SURFACE_FLAG_UPDATE) this.update_gb_surface(surface);
            return true;
        }
        case C.SVGA_3D_CMD_UPDATE_GB_IMAGE:
        {
            const [surface, face, mip] = enough(9) ? this.image_id(p, 0) : [null, 0, 0];
            if(surface) this.update_gb_image(surface, face, mip, [u(3), u(4), u(5), u(6), u(7), u(8)]);
            return true;
        }
        case C.SVGA_3D_CMD_UPDATE_GB_SURFACE:
        {
            const surface = enough(1) && this.surfaces.get(u(0));
            if(surface) this.update_gb_surface(surface);
            return true;
        }
        case C.SVGA_3D_CMD_UPDATE_ZERO_SURFACE:
        case C.SVGA_3D_CMD_WRITE_ZERO_SURFACE:
        {
            const surface = enough(1) && this.surfaces.get(u(0));
            if(surface) this.zero_gb_surface(surface, id === C.SVGA_3D_CMD_WRITE_ZERO_SURFACE);
            return true;
        }
        case C.SVGA_3D_CMD_READBACK_GB_IMAGE:
        {
            const [surface, face, mip] = enough(3) ? this.image_id(p, 0) : [null, 0, 0];
            if(surface) this.readback_gb_image(surface, face, mip, null);
            return true;
        }
        case C.SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL:
        {
            // (invertBox: the box is what not to read; reading all of it is as good)
            const [surface, face, mip] = enough(10) ? this.image_id(p, 0) : [null, 0, 0];
            if(surface) this.readback_gb_image(surface, face, mip, u(9) ? null : [u(3), u(4), u(5), u(6), u(7), u(8)]);
            return true;
        }
        case C.SVGA_3D_CMD_READBACK_GB_SURFACE:
        {
            const surface = enough(1) && this.surfaces.get(u(0));
            if(surface) this.readback_gb_surface(surface);
            return true;
        }
        case C.SVGA_3D_CMD_INVALIDATE_GB_IMAGE:
        case C.SVGA_3D_CMD_INVALIDATE_GB_SURFACE:
        case C.SVGA_3D_CMD_INVALIDATE_GB_IMAGE_PARTIAL:
            // the GPU's copy may be dropped; keeping it is as good
            return true;
        case C.SVGA_3D_CMD_DEFINE_GB_CONTEXT:
            if(enough(1)) this.define_gb_context(u(0));
            return true;
        case C.SVGA_3D_CMD_DESTROY_GB_CONTEXT:
            if(enough(1))
            {
                this.destroy_context(u(0));
                this.otable(C.SVGA_OTABLE_CONTEXT, u(0), null);
            }
            return true;
        case C.SVGA_3D_CMD_BIND_GB_CONTEXT:
            if(enough(3)) this.bind_gb_context(u(0), u(1), u(2));
            return true;
        case C.SVGA_3D_CMD_READBACK_GB_CONTEXT:
        case C.SVGA_3D_CMD_INVALIDATE_GB_CONTEXT:
            return true;
        case C.SVGA_3D_CMD_DEFINE_GB_SHADER:
            if(enough(3)) this.define_gb_shader(u(0), u(1), u(2));
            return true;
        case C.SVGA_3D_CMD_DESTROY_GB_SHADER:
            if(enough(1)) this.destroy_gb_shader(u(0));
            return true;
        case C.SVGA_3D_CMD_BIND_GB_SHADER:
            if(enough(3)) this.bind_gb_shader(u(0), u(1), u(2));
            return true;
        case C.SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE:
            this.set_gb_shader_consts(p);
            return true;
        case C.SVGA_3D_CMD_BEGIN_GB_QUERY:
            this.begin_query(p);
            return true;
        case C.SVGA_3D_CMD_END_GB_QUERY:
            this.end_query(p, mobs);
            return true;
        case C.SVGA_3D_CMD_WAIT_FOR_GB_QUERY:
            // the result is written when it is known: what follows waits for it
            return true;
        case C.SVGA_3D_CMD_NOP:
            return true;
        case C.SVGA_3D_CMD_GB_MOB_FENCE:
            if(enough(3)) this.mob_fence(u(0), u(1), u(2));
            return true;
        case C.SVGA_3D_CMD_DEFINE_GB_SCREENTARGET:
            if(enough(7)) this.define_screen_target(u(0), u(1), u(2), p[3], p[4], u(5), u(6));
            return true;
        case C.SVGA_3D_CMD_DESTROY_GB_SCREENTARGET:
            if(enough(1)) this.destroy_screen_target(u(0));
            return true;
        case C.SVGA_3D_CMD_BIND_GB_SCREENTARGET:
            if(enough(4)) this.bind_screen_target(u(0), u(1), u(2), u(3));
            return true;
        case C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET:
        case C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_V2:
            if(enough(5)) this.update_screen_target(u(0), p[1], p[2], u(3), u(4), p[1], p[2]);
            return true;
        case C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_MOVE:
            // stid, rect, type, srcPoint: the rectangle comes from elsewhere in the surface
            if(enough(8)) this.update_screen_target(u(0), p[1], p[2], u(3), u(4), p[6], p[7]);
            return true;
        case C.SVGA_3D_CMD_GB_SCREEN_DMA:
            if(enough(5)) this.screen_dma(u(0), u(2), u(3));
            return true;
        // The GART: an aperture of MOB pages Windows' vm3d keeps for its
        // memory segment. Commands name MOBs, not GART offsets, so the
        // mappings are only kept.
        case C.SVGA_3D_CMD_ENABLE_GART:
            if(enough(1)) this.gart = { mob: u(0), maps: new Map() };
            return true;
        case C.SVGA_3D_CMD_DISABLE_GART:
            this.gart = null;
            return true;
        case C.SVGA_3D_CMD_MAP_MOB_INTO_GART:
            if(enough(2) && this.gart) this.gart.maps.set(u(1), u(0));
            return true;
        case C.SVGA_3D_CMD_UNMAP_GART_RANGE:
            if(enough(2) && this.gart)
            {
                for(const offset of this.gart.maps.keys())
                {
                    if(offset >= u(0) && offset < u(0) + u(1)) this.gart.maps.delete(offset);
                }
            }
            return true;
    }
    return false;
};

// ---------------------------------------------------------------------------
// Screen targets: screens (svga_screens.js) whose picture is a surface image,
// copied into them by UPDATE_GB_SCREENTARGET

SVGA3D.prototype.target_otable = function(stid)
{
    const t = this.targets.get(stid);
    if(!t) return this.otable(C.SVGA_OTABLE_SCREENTARGET, stid, null);
    const image = t.image || [INVALID, 0, 0];
    this.otable(C.SVGA_OTABLE_SCREENTARGET, stid, [image[0], image[1], image[2], t.width, t.height, t.x, t.y, t.flags, t.dpi]);
};

SVGA3D.prototype.define_screen_target = function(stid, width, height, x, y, flags, dpi)
{
    if(!this.device.screens.define_target(stid, flags, width, height, x, y))
    {
        this.warn_once("target", "an invalid screen target");
        return;
    }
    this.targets.set(stid, { width, height, x, y, flags, dpi, image: null });
    this.target_otable(stid);
};

SVGA3D.prototype.destroy_screen_target = function(stid)
{
    this.targets.delete(stid);
    this.device.screens.destroy(stid);
    this.target_otable(stid);
};

SVGA3D.prototype.bind_screen_target = function(stid, sid, face, mip)
{
    const target = this.targets.get(stid);
    if(!target) return;
    target.image = sid === INVALID ? null : [sid, face, mip];
    this.target_otable(stid);
    if(!target.image) this.device.screens.blank(stid);
};

/**
 * UPDATE_GB_SCREENTARGET: rectangle (x, y, w, h) of a screen target from its
 * image, at (sx, sy) in it. An image the GPU has nothing newer of is read
 * from its MOB; otherwise from the GPU.
 */
SVGA3D.prototype.update_screen_target = function(stid, x, y, w, h, sx, sy)
{
    const target = this.targets.get(stid);
    const screen = this.device.screens.screens.get(stid);
    if(!target || !target.image || !screen) return;
    const surface = this.surfaces.get(target.image[0]);
    if(!surface) return;
    const [, face, mip] = target.image;
    x = Math.max(0, x); y = Math.max(0, y);
    w = Math.min(w, screen.width - x); h = Math.min(h, screen.height - y);
    const [width, height] = surface.sizes[Math.min(mip, surface.sizes.length - 1)];
    w = Math.min(w, width - sx); h = Math.min(h, height - sy);
    if(w <= 0 || h <= 0 || sx < 0 || sy < 0) return;
    if(surface.host_newer || surface.mob === INVALID)
    {
        if(surface.home && (surface.home === "gx" || surface.handle)) this.to_desktop(surface, sx, sy, w, h, screen.x + x, screen.y + y, w, h, null);
        return;
    }
    const pixel = surface_pixel_reader(surface);
    if(!pixel) return this.warn_once("present-format" + surface.format, "presenting format " + surface.format + " is not supported");
    const { offset, pitch } = this.mob_image(surface, face, mip);
    const bytes_per = surface.layout.bytes;
    const rows = this.device.mobs.read(surface.mob, offset + sy * pitch, (h - 1) * pitch + (sx + w) * bytes_per);
    if(!rows) return this.warn_once("target-mob", "a screen target image outside of its MOB");
    const word = surface_word_converter(surface);
    for(let row = 0; row < h; row++)
    {
        const at = ((y + row) * screen.width + x) * 4;
        if(word && convert_row_32(word, rows, row * pitch + sx * 4, screen.rgba, at, w)) continue;
        for(let column = 0; column < w; column++)
        {
            pixel(rows, row * pitch + (sx + column) * bytes_per, screen.rgba, at + column * 4);
        }
    }
    screen.mark(y, y + h);
};

/**
 * GB_SCREEN_DMA: screenId, (dead), destMobID, destPitch: the screen's
 * picture into a MOB, as BGRX
 */
SVGA3D.prototype.screen_dma = function(id, mob, pitch)
{
    const screen = this.device.screens.screens.get(id);
    if(!screen || pitch < screen.width * 4) return;
    const row = new Uint8Array(screen.width * 4);
    for(let y = 0; y < screen.height; y++)
    {
        for(let x = 0; x < screen.width; x++)
        {
            const at = (y * screen.width + x) * 4;
            row[x * 4] = screen.rgba[at + 2]; row[x * 4 + 1] = screen.rgba[at + 1]; row[x * 4 + 2] = screen.rgba[at]; row[x * 4 + 3] = 0;
        }
        if(!this.device.mobs.write(mob, y * pitch, row)) return;
    }
};

// ---------------------------------------------------------------------------
// Pictures to the screen

/**
 * PRESENT: sid, then SVGA3dCopyRect[] (x, y, w, h, srcx, srcy): the
 * surface's rectangles to the desktop
 */
SVGA3D.prototype.present = function(p)
{
    const surface = this.image(p, 0);
    if(!surface || surface.home === "d9wg" && !surface.handle) return;
    const rects = [];
    for(let at = 1; at + 6 <= p.length; at += 6)
    {
        rects.push({ dx: p[at] | 0, dy: p[at + 1] | 0, w: p[at + 2] | 0, h: p[at + 3] | 0, sx: p[at + 4] | 0, sy: p[at + 5] | 0 });
    }
    if(!rects.length)
    {
        const [width, height] = surface.sizes[0];
        rects.push({ dx: 0, dy: 0, w: width, h: height, sx: 0, sy: 0 });
    }
    for(const r of rects)
    {
        this.to_desktop(surface, r.sx, r.sy, r.w, r.h, r.dx, r.dy, r.w, r.h, null);
    }
};

/**
 * BLIT_SURFACE_TO_SCREEN: srcImage, srcRect (l, t, r, b), destScreenId,
 * destRect (l, t, r, b, in the screen), then clip rectangles in the screen
 */
SVGA3D.prototype.blit_surface_to_screen = function(p)
{
    const surface = this.image(p, 0);
    if(!surface || surface.home === "d9wg" && !surface.handle || p.length < 12) return;
    const screen = this.device.screens.screens.get(p[7] >>> 0);
    if(!screen) return;
    const sl = p[3] | 0, st = p[4] | 0, sw = (p[5] | 0) - sl, sh = (p[6] | 0) - st;
    const dl = p[8] | 0, dt = p[9] | 0, dw = (p[10] | 0) - dl, dh = (p[11] | 0) - dt;
    if(sw <= 0 || sh <= 0 || dw <= 0 || dh <= 0) return;
    let clips = null;
    if(p.length >= 16)
    {
        clips = [];
        for(let at = 12; at + 4 <= p.length; at += 4) clips.push([p[at] | 0, p[at + 1] | 0, p[at + 2] | 0, p[at + 3] | 0]);
    }
    this.to_desktop(surface, sl, st, sw, sh, screen.x + dl, screen.y + dt, dw, dh,
        clips && clips.map(([l, t, r, b]) => [screen.x + l, screen.y + t, screen.x + r, screen.y + b]));
};

/**
 * Read a rectangle of a surface back and draw it, scaled, on the desktop:
 * into the screens it covers, or into the frame buffer without screens
 * @param {Array<!Array<number>>} clips rectangles (l, t, r, b) on the desktop it is limited to
 */
SVGA3D.prototype.to_desktop = function(surface, sx, sy, sw, sh, dx, dy, dw, dh, clips)
{
    const [width, height] = surface.sizes[0];
    if(sx < 0 || sy < 0 || sx + sw > width || sy + sh > height)
    {
        this.warn_once("present-bounds", "a present outside of its surface");
        return;
    }
    const pixel = surface_pixel_reader(surface);
    if(!pixel) return this.warn_once("present-format" + surface.format, "presenting format " + surface.format + " is not supported");
    const device = this.device;
    const bytes_per = surface.layout.bytes;
    // (unscaled 32-bit pixels: a row at a time, as words)
    const word = sw === dw && sh === dh ? surface_word_converter(surface) : null;
    this.read_rows(surface, 0, 0, sy, sh, (data, first, count, pitch, x0) => {
        // the destination rows this piece of source rows makes
        const top = dy + Math.ceil((first - sy) * dh / sh), bottom = dy + Math.ceil((first - sy + count) * dh / sh);
        const put = (rgba, row_at, left, right, y) => {
            const source_row = sy + Math.floor((y - dy) * sh / dh) - first;
            if(word && convert_row_32(word, data, source_row * pitch + (sx + left - dx - x0) * 4, rgba, row_at + left * 4, right - left)) return;
            for(let x = left; x < right; x++)
            {
                const column = sx + Math.floor((x - dx) * sw / dw) - x0;
                pixel(data, source_row * pitch + column * bytes_per, rgba, row_at + x * 4);
            }
        };
        const screens = device.screens.screens;
        if(screens.size)
        {
            for(const screen of screens.values())
            {
                for(const [l, t, r, b] of clips || [[dx, dy, dx + dw, dy + dh]])
                {
                    const left = Math.max(l, dx, screen.x), right = Math.min(r, dx + dw, screen.x + screen.width);
                    const y0 = Math.max(t, top, screen.y), y1 = Math.min(b, bottom, screen.y + screen.height);
                    if(left >= right || y0 >= y1) continue;
                    for(let y = y0; y < y1; y++)
                    {
                        // the screen's own coordinates
                        const row_at = ((y - screen.y) * screen.width - screen.x) * 4;
                        put(screen.rgba, row_at, left, right, y);
                    }
                    if(screen.backing) device.screens.copy_to_backing(screen, left - screen.x, y0 - screen.y, right - screen.x, y1 - screen.y);
                    screen.mark(y0 - screen.y, y1 - screen.y);
                }
            }
        }
        else if(device.svga_active() && device.bpp === 32)
        {
            // the frame buffer of the register mode: BGRX
            const vram = device.vram(), pitch_fb = device.pitch(), row = new Uint8ClampedArray(device.width * 4);
            for(const [l, t, r, b] of clips || [[dx, dy, dx + dw, dy + dh]])
            {
                const left = Math.max(l, dx, 0), right = Math.min(r, dx + dw, device.width);
                for(let y = Math.max(t, top, 0); y < Math.min(b, bottom, device.height); y++)
                {
                    put(row, 0, left, right, y);
                    for(let x = left; x < right; x++)
                    {
                        const at = y * pitch_fb + x * 4;
                        vram[at] = row[x * 4 + 2]; vram[at + 1] = row[x * 4 + 1]; vram[at + 2] = row[x * 4]; vram[at + 3] = 0;
                    }
                }
            }
            device.machine.mmio_ram_mark_dirty(device.vga.lfb_region);
        }
    }, sx, sw);
};

/**
 * How to turn a 32-bit pixel of a surface, as a little-endian word, into an
 * RGBA one (opaque): for the formats presents mostly have, else null
 * @return {?function(number):number}
 */
function surface_word_converter(surface)
{
    const d3d = surface.info && surface.info.d3d;
    if(d3d === D3DFMT.X8R8G8B8 || d3d === D3DFMT.A8R8G8B8) return bgra_to_rgba;
    if(d3d === D3DFMT.A8B8G8R8) return rgba_opaque;
    if(d3d) return null;
    switch(surface.format)
    {
        case C.SVGA3D_B8G8R8A8_UNORM: case C.SVGA3D_B8G8R8X8_UNORM: case C.SVGA3D_B8G8R8A8_UNORM_SRGB:
        case C.SVGA3D_B8G8R8X8_UNORM_SRGB: case C.SVGA3D_B8G8R8A8_TYPELESS: case C.SVGA3D_B8G8R8X8_TYPELESS:
            return bgra_to_rgba;
        case C.SVGA3D_R8G8B8A8_UNORM: case C.SVGA3D_R8G8B8A8_UNORM_SRGB: case C.SVGA3D_R8G8B8A8_TYPELESS:
            return rgba_opaque;
    }
    return null;
}

const bgra_to_rgba = v => 0xFF000000 | (v & 0xFF) << 16 | v & 0xFF00 | v >>> 16 & 0xFF;
const rgba_opaque = v => v | 0xFF000000;

/**
 * `count` 32-bit pixels from `source` (at byte `from`) into `rgba` (at byte
 * `to`), converted by `word`
 * @return {boolean} false where the bytes are not word aligned (the caller
 *     converts pixel by pixel)
 */
function convert_row_32(word, source, from, rgba, to, count)
{
    if(((source.byteOffset + from) & 3) || ((rgba.byteOffset + to) & 3) || count <= 0) return count <= 0;
    const s = new Int32Array(source.buffer, source.byteOffset + from, count);
    const d = new Int32Array(rgba.buffer, rgba.byteOffset + to, count);
    for(let i = 0; i < count; i++) d[i] = word(s[i]);
    return true;
}

/**
 * How to turn a pixel of a surface into RGBA: its D3D9 format, or a DX one
 * @return {?function(!Uint8Array, number, !Uint8ClampedArray, number)}
 */
function surface_pixel_reader(surface)
{
    if(surface.info && surface.info.d3d) return pixel_reader(surface.info.d3d);
    switch(surface.format)
    {
        case C.SVGA3D_B8G8R8A8_UNORM: case C.SVGA3D_B8G8R8X8_UNORM: case C.SVGA3D_B8G8R8A8_UNORM_SRGB:
        case C.SVGA3D_B8G8R8X8_UNORM_SRGB: case C.SVGA3D_B8G8R8A8_TYPELESS: case C.SVGA3D_B8G8R8X8_TYPELESS:
            return pixel_reader(D3DFMT.X8R8G8B8);
        case C.SVGA3D_R8G8B8A8_UNORM: case C.SVGA3D_R8G8B8A8_UNORM_SRGB: case C.SVGA3D_R8G8B8A8_TYPELESS:
            return pixel_reader(D3DFMT.A8B8G8R8);
        case C.SVGA3D_B5G6R5_UNORM:
            return pixel_reader(D3DFMT.R5G6B5);
        case C.SVGA3D_B5G5R5A1_UNORM:
            return pixel_reader(D3DFMT.A1R5G5B5);
        case C.SVGA3D_R10G10B10A2_UNORM: case C.SVGA3D_R10G10B10A2_TYPELESS:
            return (s, i, t, o) => {
                const v = (s[i] | s[i + 1] << 8 | s[i + 2] << 16 | s[i + 3] << 24) >>> 0;
                t[o] = (v & 1023) >> 2; t[o + 1] = (v >> 10 & 1023) >> 2; t[o + 2] = (v >> 20 & 1023) >> 2; t[o + 3] = 255;
            };
    }
    return null;
}

/**
 * How to turn a pixel of a format into RGBA
 * @return {?function(!Uint8Array, number, !Uint8ClampedArray, number)}
 */
function pixel_reader(d3d)
{
    switch(d3d)
    {
        case D3DFMT.X8R8G8B8:
        case D3DFMT.A8R8G8B8:
            return (s, i, t, o) => { t[o] = s[i + 2]; t[o + 1] = s[i + 1]; t[o + 2] = s[i]; t[o + 3] = 255; };
        case D3DFMT.A8B8G8R8:
            return (s, i, t, o) => { t[o] = s[i]; t[o + 1] = s[i + 1]; t[o + 2] = s[i + 2]; t[o + 3] = 255; };
        case D3DFMT.R5G6B5:
            return (s, i, t, o) => {
                const v = s[i] | s[i + 1] << 8;
                t[o] = (v >> 11 & 31) * 255 / 31; t[o + 1] = (v >> 5 & 63) * 255 / 63; t[o + 2] = (v & 31) * 255 / 31; t[o + 3] = 255;
            };
        case D3DFMT.X1R5G5B5:
        case D3DFMT.A1R5G5B5:
            return (s, i, t, o) => {
                const v = s[i] | s[i + 1] << 8;
                t[o] = (v >> 10 & 31) * 255 / 31; t[o + 1] = (v >> 5 & 31) * 255 / 31; t[o + 2] = (v & 31) * 255 / 31; t[o + 3] = 255;
            };
        case D3DFMT.A2R10G10B10:
            return (s, i, t, o) => {
                const v = (s[i] | s[i + 1] << 8 | s[i + 2] << 16 | s[i + 3] << 24) >>> 0;
                t[o] = (v >> 20 & 1023) >> 2; t[o + 1] = (v >> 10 & 1023) >> 2; t[o + 2] = (v & 1023) >> 2; t[o + 3] = 255;
            };
    }
    return null;
}
                                                                                                                                                                                                                                 source/v64/src/graphics_adapters/vmware_svga/svga3d_d9wg.js                                         0000644 0000000 0000000 00000016277 00000000000 021153  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // D9WG batches, the renderer's input. The SVGA3D layer (svga3d.js) turns the
// guest's legacy 3D commands into the protocol the D3D9 executor
// (src/browser/glbridge/d3d9-webgpu/d3d9_executor.js) already runs for the
// guest D3D9 proxy: glbridge/d3d9proxy/d3d9_protocol.h, version 1.7. A batch
// is self-contained (inline data travels in it), so it can be recorded and
// replayed without the guest.

export const D9WG_MAGIC = 0x47573944;
const VERSION_MAJOR = 1;
const VERSION_MINOR = 7;
const BATCH_HEADER_BYTES = 32;
const COMMAND_HEADER_BYTES = 16;

/** The batch flag that makes the executor submit the frame's GPU work */
export const D9WG_BATCH_FLAG_PRESENT = 1;

// Every batch carries this session: one guest device, one resource namespace
const SESSION_LOW = 0x41475653;     // "SVGA"
const SESSION_HIGH = 0;

/** Opcodes (enum D9WGOpcode) */
export const OP = {
    CLEAR: 5,
    STRETCH_RECT: 8,
    COLOR_FILL: 9,
    READBACK_SURFACE: 12,
    CREATE_BUFFER: 0x100,
    UPDATE_BUFFER: 0x101,
    DESTROY_RESOURCE: 0x103,
    CREATE_TEXTURE_2D: 0x110,
    CREATE_TEXTURE_CUBE: 0x111,
    CREATE_TEXTURE_VOLUME: 0x112,
    UPDATE_TEXTURE: 0x113,
    CREATE_VERTEX_DECLARATION: 0x120,
    CREATE_VERTEX_SHADER: 0x121,
    CREATE_PIXEL_SHADER: 0x122,
    CREATE_QUERY: 0x123,
    SET_RENDER_STATE: 0x200,
    SET_SAMPLER_STATE: 0x201,
    SET_TEXTURE_STAGE_STATE: 0x202,
    SET_TEXTURE: 0x203,
    SET_VIEWPORT: 0x204,
    SET_SCISSOR_RECT: 0x205,
    SET_TRANSFORM: 0x206,
    SET_MATERIAL: 0x207,
    SET_LIGHT: 0x208,
    LIGHT_ENABLE: 0x209,
    SET_STREAM_SOURCE: 0x20A,
    SET_STREAM_SOURCE_FREQ: 0x20B,
    SET_INDICES: 0x20C,
    SET_VERTEX_DECLARATION: 0x20D,
    SET_RENDER_TARGET: 0x20F,
    SET_VERTEX_SHADER: 0x211,
    SET_PIXEL_SHADER: 0x212,
    SET_VERTEX_SHADER_CONSTANT_F: 0x213,
    SET_VERTEX_SHADER_CONSTANT_I: 0x214,
    SET_VERTEX_SHADER_CONSTANT_B: 0x215,
    SET_PIXEL_SHADER_CONSTANT_F: 0x216,
    SET_PIXEL_SHADER_CONSTANT_I: 0x217,
    SET_PIXEL_SHADER_CONSTANT_B: 0x218,
    SET_CLIP_PLANE: 0x219,
    SET_DEPTH_STENCIL_SURFACE_LEVEL: 0x21E,
    GENERATE_MIPS: 0x221,
    DRAW_PRIMITIVE: 0x300,
    DRAW_INDEXED_PRIMITIVE: 0x301,
    BEGIN_QUERY: 0x400,
    END_QUERY: 0x401,
};

/** D9WG resource kinds (D9WG_RESOURCE_*) */
export const KIND = {
    VERTEX_BUFFER: 1,
    INDEX_BUFFER: 2,
    TEXTURE_2D: 3,
    TEXTURE_CUBE: 4,
    TEXTURE_VOLUME: 5,
    VERTEX_DECLARATION: 6,
    VERTEX_SHADER: 7,
    PIXEL_SHADER: 8,
    QUERY: 9,
};

// (the response region's layout: ../renderer_protocol.js)

/**
 * Builds one batch at a time
 * @constructor
 */
export function D9WGWriter()
{
    this.bytes = new Uint8Array(1 << 16);
    this.view = new DataView(this.bytes.buffer);
    this.length = BATCH_HEADER_BYTES;
    this.count = 0;
    this.sequence = 0;
    // the command being written: where its header is
    this.command_at = -1;
    /** @type {?function()} called before each command: the other stream is sent first */
    this.before = null;
}

/** @return {boolean} */
D9WGWriter.prototype.empty = function()
{
    return this.count === 0;
};

/** @return {number} bytes so far */
D9WGWriter.prototype.size = function()
{
    return this.length;
};

D9WGWriter.prototype.reserve = function(bytes)
{
    if(this.length + bytes <= this.bytes.length) return;
    let capacity = this.bytes.length;
    while(capacity < this.length + bytes) capacity *= 2;
    const bigger = new Uint8Array(capacity);
    bigger.set(this.bytes.subarray(0, this.length));
    this.bytes = bigger;
    this.view = new DataView(bigger.buffer);
};

/**
 * Start a command; its fields follow with u32/i32/f32/data
 * @param {number} opcode
 */
D9WGWriter.prototype.begin = function(opcode)
{
    if(this.before) this.before();
    this.end();
    this.reserve(COMMAND_HEADER_BYTES);
    this.command_at = this.length;
    const v = this.view, at = this.length;
    v.setUint16(at, opcode, true);
    v.setUint16(at + 2, 0, true);
    v.setUint32(at + 4, 0, true);
    v.setUint32(at + 8, ++this.sequence, true);
    v.setUint32(at + 12, 0, true);
    this.length += COMMAND_HEADER_BYTES;
    this.count++;
    return this;
};

/** Finish the command being written: its size, padded to 8 bytes */
D9WGWriter.prototype.end = function()
{
    if(this.command_at < 0) return;
    const padded = this.length + 7 & ~7;
    this.reserve(padded - this.length);
    this.bytes.fill(0, this.length, padded);
    this.length = padded;
    this.view.setUint32(this.command_at + 4, this.length - this.command_at, true);
    this.command_at = -1;
};

D9WGWriter.prototype.u32 = function(value)
{
    this.reserve(4);
    this.view.setUint32(this.length, value >>> 0, true);
    this.length += 4;
    return this;
};

D9WGWriter.prototype.i32 = function(value)
{
    this.reserve(4);
    this.view.setInt32(this.length, value | 0, true);
    this.length += 4;
    return this;
};

D9WGWriter.prototype.f32 = function(value)
{
    this.reserve(4);
    this.view.setFloat32(this.length, value, true);
    this.length += 4;
    return this;
};

/**
 * Raw bytes inside the current command
 * @param {!Uint8Array} bytes
 * @return {number} their offset from the start of the batch (data_offset)
 */
D9WGWriter.prototype.data = function(bytes)
{
    const at = this.length + 3 & ~3;
    this.reserve(at - this.length + bytes.length);
    this.bytes.fill(0, this.length, at);
    this.bytes.set(bytes, at);
    this.length = at + bytes.length;
    return at;
};

/**
 * A field whose value is known only later (a data_offset before its data)
 * @return {number} where to patch
 */
D9WGWriter.prototype.placeholder = function()
{
    const at = this.length;
    this.u32(0);
    return at;
};

D9WGWriter.prototype.patch = function(at, value)
{
    this.view.setUint32(at, value >>> 0, true);
};

/**
 * Close the batch
 * @param {number} frame_id
 * @param {number} flags D9WG_BATCH_FLAG_*
 * @return {!Uint8Array} the batch, owned by the caller
 */
D9WGWriter.prototype.finish = function(frame_id, flags)
{
    this.end();
    const v = this.view;
    v.setUint32(0, D9WG_MAGIC, true);
    v.setUint16(4, VERSION_MAJOR, true);
    v.setUint16(6, VERSION_MINOR, true);
    v.setUint32(8, frame_id >>> 0, true);
    v.setUint32(12, flags, true);
    v.setUint32(16, this.count, true);
    v.setUint32(20, this.length - BATCH_HEADER_BYTES, true);
    v.setUint32(24, SESSION_LOW, true);
    v.setUint32(28, SESSION_HIGH, true);
    const batch = this.bytes.slice(0, this.length);
    this.length = BATCH_HEADER_BYTES;
    this.count = 0;
    return batch;
};

/**
 * The commands of a batch, for tests and traces
 * @param {!Uint8Array} batch
 * @return {!Array<{opcode: number, view: !DataView, at: number, size: number}>}
 *     at: the payload's offset in the batch
 */
export function d9wg_commands(batch)
{
    const view = new DataView(batch.buffer, batch.byteOffset, batch.byteLength);
    if(view.getUint32(0, true) !== D9WG_MAGIC) throw new Error("not a D9WG batch");
    const end = BATCH_HEADER_BYTES + view.getUint32(20, true);
    const commands = [];
    for(let at = BATCH_HEADER_BYTES; at < end;)
    {
        const size = view.getUint32(at + 4, true);
        commands.push({ opcode: view.getUint16(at, true), view, at: at + COMMAND_HEADER_BYTES, size: size - COMMAND_HEADER_BYTES });
        at += size;
    }
    return commands;
}
                                                                                                                                                                                                                                                                                                                                 source/v64/src/graphics_adapters/vmware_svga/svga3d_dx.js                                           0000644 0000000 0000000 00000123634 00000000000 020710  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // DX (SVGA_CAP_DX, level dx10 and up; docs/gpu-devices.md,
// "VMware SVGA II"): the device side of VMware's VGPU10 contexts. The
// renderer side is GX
// (src/browser/glbridge/gx/gx_executor.js); between them go GX batches
// (GXWriter, src/graphics_adapters/renderer_protocol.js).
//
// What the device keeps, in the formats the guest knows:
// - each DX context's state as SVGADXContextMobFormat (2048 dwords), which
//   DX_READBACK_CONTEXT writes to the context's MOB and DX_BIND_CONTEXT with
//   valid contents reads back;
// - the object definitions in the context's COTables, guest memory written
//   as objects are defined (and read again when a COTable is set with valid
//   entries, which is how Windows' driver moves and restores them).
// So a snapshot of guest memory holds the DX state; the renderer's objects
// are made again from it.
//
// Commands go to GX nearly as they are: GX.DX carries the context, the
// command id and its body. Definitions loaded from a COTable go as the
// DX_DEFINE_* command they came from. Surfaces a command names are made in
// GX first (svga3d.js gx_surface), filled from their MOB.

import { LOG_VGA } from "../../const.js";
import { dbg_log } from "../../log.js";
import * as C from "./svga_constants.js";

const INVALID = 0xFFFFFFFF;

import { GX, GXWriter } from "../renderer_protocol.js";

/** Bytes of a COTable entry, per SVGACOTableType */
export const COTABLE_ENTRY_BYTES = [32, 32, 32, 1024, 128, 16, 32, 64, 2048, 16, 32, 64];

/** SVGADXContextMobFormat: dword offsets */
export const DXCTX = {
    LAYOUT: 0, VERTEX_BUFFERS: 1, INDEX_SID: 97, INDEX_OFFSET: 99, INDEX_FORMAT: 100, TOPOLOGY: 101,
    BLEND: 102, BLEND_FACTOR: 103, SAMPLE_MASK: 107, DEPTH_STENCIL: 108, STENCIL_REF: 109, RASTERIZER: 110,
    DSV: 111, RTVS: 112, SO_TARGETS: 128, SOID: 132, UAV_SPLICE: 143, VIEWPORT_COUNTS: 144,
    VIEWPORTS: 148, SCISSORS: 276, PREDICATION: 404, IFACE_MOB: 406, IFACE_OFFSET: 407,
    SHADER_STATE: 408, SHADER_STATE_DWORDS: 193, QUERIES: 1592, COTABLES: 1656, UAVS: 1732, CS_UAVS: 1796,
    DWORDS: 2048,
};
// within a shader stage's state: shaderId, constantBuffers[16] (sid, offset, size), shaderResources[128], samplers[16]
const STAGE_SHADER = 0, STAGE_CBS = 1, STAGE_SRVS = 49, STAGE_SAMPLERS = 177;

/** The commands among the DX ones' ids that are not DX commands */
const NOT_DX = new Set([
    C.SVGA_3D_CMD_SCREEN_COPY, C.SVGA_3D_CMD_GROW_OTABLE, C.SVGA_3D_CMD_INTRA_SURFACE_COPY,
    C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, C.SVGA_3D_CMD_WHOLE_SURFACE_COPY, C.SVGA_3D_CMD_WRITE_ZERO_SURFACE,
    C.SVGA_3D_CMD_UPDATE_ZERO_SURFACE, C.SVGA_3D_CMD_LOGICOPS_BITBLT, C.SVGA_3D_CMD_LOGICOPS_TRANSBLT,
    C.SVGA_3D_CMD_LOGICOPS_STRETCHBLT, C.SVGA_3D_CMD_LOGICOPS_COLORFILL, C.SVGA_3D_CMD_LOGICOPS_ALPHABLEND,
    C.SVGA_3D_CMD_LOGICOPS_CLEARTYPEBLEND, C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_V2, C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V4,
    C.SVGA_3D_CMD_SURFACE_STRETCHBLT_NON_MS_TO_MS, C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_MOVE,
    C.SVGA_3D_CMD_RESERVED1, C.SVGA_3D_CMD_RESERVED2, C.SVGA_3D_CMD_RESERVED3, C.SVGA_3D_CMD_RESERVED4,
    C.SVGA_3D_CMD_RESERVED5, C.SVGA_3D_CMD_RESERVED6, C.SVGA_3D_CMD_RESERVED7, C.SVGA_3D_CMD_RESERVED8,
]);

/**
 * The DX commands that only move surfaces' contents: Windows' kernel driver
 * sends them outside of DX contexts (present blits to the screen targets)
 */
const SURFACE_ONLY = new Set([
    C.SVGA_3D_CMD_DX_PRESENTBLT, C.SVGA_3D_CMD_DX_PRED_COPY_REGION, C.SVGA_3D_CMD_DX_PRED_COPY,
    C.SVGA_3D_CMD_DX_BUFFER_COPY, C.SVGA_3D_CMD_DX_TRANSFER_FROM_BUFFER, C.SVGA_3D_CMD_DX_PRED_TRANSFER_FROM_BUFFER,
    C.SVGA_3D_CMD_DX_SURFACE_COPY_AND_READBACK, C.SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE, C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE,
    C.SVGA_3D_CMD_DX_INVALIDATE_SUBRESOURCE, C.SVGA_3D_CMD_DX_BUFFER_UPDATE, C.SVGA_3D_CMD_DX_RESOLVE_COPY,
    C.SVGA_3D_CMD_DX_PRED_RESOLVE_COPY, C.SVGA_3D_CMD_DX_PRED_CONVERT_REGION, C.SVGA_3D_CMD_DX_PRED_CONVERT,
    C.SVGA_3D_CMD_DX_PRED_STAGING_COPY, C.SVGA_3D_CMD_DX_STAGING_COPY, C.SVGA_3D_CMD_DX_PRED_STAGING_COPY_REGION,
    C.SVGA_3D_CMD_DX_PRED_STAGING_CONVERT_REGION, C.SVGA_3D_CMD_DX_PRED_STAGING_CONVERT,
    C.SVGA_3D_CMD_DX_STAGING_BUFFER_COPY, C.SVGA_3D_CMD_DX_TRANSFER_TO_BUFFER,
]);

/** Query results (SVGADXQueryResultUnion member sizes), by type */
const QUERY_RESULT_BYTES = [4, 8, 12, 88, 4, 16, 4, 8, 16, 16, 16, 16, 4, 4, 4, 4];

/**
 * One DX context
 * @constructor
 */
function DXContext(cid)
{
    this.cid = cid;
    this.mob = INVALID;
    /** SVGADXContextMobFormat */
    this.state = new Uint32Array(DXCTX.DWORDS);
    for(let i = 0; i < C.SVGA_COTABLE_MAX; i++) this.state[DXCTX.COTABLES + i] = INVALID;
    this.state[DXCTX.SAMPLE_MASK] = INVALID;
    /** @type {!Array<!Map<number, number>>} view id -> sid, for RTVs, DSVs, SRVs, UAVs */
    this.views = [new Map(), new Map(), new Map(), new Map()];
    /** @type {!Map<number, !Array<number>>} shader id -> [type, size], also without a COTable */
    this.shaders = new Map();
}

const VIEW_RTV = 0, VIEW_DSV = 1, VIEW_SRV = 2, VIEW_UAV = 3;

/**
 * @constructor
 * @param {!Object} svga3d the SVGA3D that owns the surfaces and the renderer channel
 */
export function DXDevice(svga3d)
{
    this.s = svga3d;
    /** @type {!Map<number, !DXContext>} */
    this.contexts = new Map();
    /** @type {DXContext} */
    this.device_dx = null;
}

DXDevice.prototype.reset = function()
{
    this.contexts.clear();
    this.device_dx = null;
};

DXDevice.prototype.warn = function(key, text)
{
    this.s.warn_once("dx-" + key, text);
};

/** The GX writer, as the stream now being written */
DXDevice.prototype.gx = function()
{
    return this.s.gx_writer();
};

DXDevice.prototype.forward = function(cid, id, p)
{
    const words = new Uint32Array(2 + p.length);
    words[0] = cid;
    words[1] = id;
    words.set(new Uint32Array(p.buffer, p.byteOffset, p.length), 2);
    this.gx().command(GX.DX, words);
};

/**
 * A staging copy: written to GX, then, when it says readback, its
 * destination's subresource (-1: all of them) into the destination's MOB
 */
DXDevice.prototype.staging_copy = function(cid, id, p, dst_sid, subresource, readback)
{
    this.written(dst_sid);
    this.forward(cid, id, p);
    const dst = readback && this.s.surfaces.get(dst_sid);
    if(!dst) return;
    if(subresource < 0) this.s.readback_surface(dst);
    else this.s.readback_subresource(dst, subresource);
};

/**
 * Make sure a surface a command names is in GX, with its newest contents (0
 * or INVALID name none)
 * @param {boolean=} write whether DX will change it
 */
DXDevice.prototype.surface = function(sid, write)
{
    if(sid === INVALID || sid === 0 && !this.s.surfaces.has(0)) return null;
    const surface = this.s.surfaces.get(sid);
    if(!surface)
    {
        this.warn("sid", "a DX command names an undefined surface");
        return null;
    }
    this.s.gx_surface(surface, write);
    return surface;
};

/** ... and that the GPU will write it */
DXDevice.prototype.written = function(sid)
{
    const surface = this.surface(sid, true);
    if(surface) surface.host_newer = true;
};

/**
 * Before a draw: surfaces legacy 3D changed since come over, and the bound
 * targets are written (the D3D9 driver and DWM share surfaces)
 */
DXDevice.prototype.drawing = function(context)
{
    const s = this.s;
    if(!s.duals.size) return;
    for(const surface of s.duals) if(surface.home === "d9wg" && surface.stale) s.gx_surface(surface);
    const st = context.state;
    const mark = (kind, view) => {
        const sid = context.views[kind].get(view);
        const surface = sid === undefined ? null : s.surfaces.get(sid);
        if(surface && surface.in_d9) s.gx_surface(surface, true);
    };
    mark(VIEW_DSV, st[DXCTX.DSV]);
    for(let i = 0; i < 8; i++) mark(VIEW_RTV, st[DXCTX.RTVS + i]);
};

// ---------------------------------------------------------------------------
// COTables

/** The COTable entry of an object, in guest memory */
DXDevice.prototype.write_entry = function(context, type, id, dwords)
{
    const mob = context.state[DXCTX.COTABLES + type];
    if(mob === INVALID) return;
    const size = COTABLE_ENTRY_BYTES[type];
    const bytes = new Uint8Array(size);
    if(dwords) bytes.set(new Uint8Array(Uint32Array.from(dwords, v => v >>> 0).buffer).subarray(0, size));
    this.s.device.mobs.write(mob, id * size, bytes);
};

DXDevice.prototype.read_entry = function(context, type, id)
{
    const mob = context.state[DXCTX.COTABLES + type];
    const size = COTABLE_ENTRY_BYTES[type];
    const bytes = mob === INVALID ? null : this.s.device.mobs.read(mob, id * size, size);
    return bytes ? new Uint32Array(bytes.buffer, bytes.byteOffset, size >> 2) : null;
};

/**
 * The DX_DEFINE_* command (id, body) that makes an object a COTable entry
 * describes, or null for an empty entry
 * @param {!Uint32Array} e
 * @return {Array}
 */
function entry_command(type, id, e)
{
    if(e.every(v => v === 0)) return null;
    switch(type)
    {
        case C.SVGA_COTABLE_RTVIEW:
            return [C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, [id, e[0], e[1], e[2], e[3], e[4], e[5]]];
        case C.SVGA_COTABLE_DSVIEW:
            return [C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW_V2, [id, e[0], e[1], e[2], e[3], e[4], e[5], e[6]]];
        case C.SVGA_COTABLE_SRVIEW:
            return [C.SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW, [id, e[0], e[1], e[2], e[3], e[4], e[5], e[6]]];
        case C.SVGA_COTABLE_ELEMENTLAYOUT:
        {
            const count = Math.min(e[1], 32);
            return [C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, [id, ...e.subarray(2, 2 + 6 * count)]];
        }
        case C.SVGA_COTABLE_BLENDSTATE:
            return [C.SVGA_3D_CMD_DX_DEFINE_BLEND_STATE, [id, ...e.subarray(0, 25)]];
        case C.SVGA_COTABLE_DEPTHSTENCIL:
            return [C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE, [id, ...e.subarray(0, 4)]];
        case C.SVGA_COTABLE_RASTERIZERSTATE:
            return [C.SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE_V2, [id, ...e.subarray(0, 7), e[7] & 0xFF]];
        case C.SVGA_COTABLE_SAMPLER:
            return [C.SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE, [id, ...e.subarray(0, 10)]];
        case C.SVGA_COTABLE_DXQUERY:
            return [C.SVGA_3D_CMD_DX_DEFINE_QUERY, [id, e[0] & 0xFF, e[1]]];
        case C.SVGA_COTABLE_UAVIEW:
            return [C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW, [id, ...e.subarray(0, 8)]];
        case C.SVGA_COTABLE_STREAMOUTPUT:
            return [C.SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT, [id, ...e.subarray(0, 1 + 256 + 4 + 1)]];
    }
    return null;
}

/**
 * The objects a COTable holds (its first `count` entries) are defined in GX
 */
DXDevice.prototype.load_cotable = function(context, type, count)
{
    const gx = this.gx();
    gx.command(GX.COTABLE_RESET, [context.cid, type]);
    const view = { [C.SVGA_COTABLE_RTVIEW]: VIEW_RTV, [C.SVGA_COTABLE_DSVIEW]: VIEW_DSV,
        [C.SVGA_COTABLE_SRVIEW]: VIEW_SRV, [C.SVGA_COTABLE_UAVIEW]: VIEW_UAV }[type];
    if(view !== undefined) context.views[view].clear();
    for(let id = 0; id < count; id++)
    {
        const e = this.read_entry(context, type, id);
        if(!e) break;
        if(type === C.SVGA_COTABLE_DXSHADER)
        {
            // type, size, offset, mob: defined, and bound if it has a MOB
            if(!e[0] && !e[1]) continue;
            context.shaders.set(id, [e[0], e[1]]);
            this.forward(context.cid, C.SVGA_3D_CMD_DX_DEFINE_SHADER, Uint32Array.of(id, e[0], e[1]));
            if(e[3] !== INVALID) this.shader_code(context, id, e[0], e[1], e[3], e[2]);
            continue;
        }
        const command = entry_command(type, id, e);
        if(!command) continue;
        this.define(context, command[0], Uint32Array.from(command[1], v => v >>> 0), false);
    }
};

// ---------------------------------------------------------------------------
// Commands

/**
 * One DX command
 * @param {number} id
 * @param {!Int32Array} body
 * @param {number} cid the context of the command buffer it came in
 * @return {boolean} whether it was one of these
 */
DXDevice.prototype.command = function(id, body, cid)
{
    if(id < C.SVGA_3D_CMD_DX_MIN || id > C.SVGA_3D_CMD_DX_STAGING_BUFFER_COPY || NOT_DX.has(id)) return false;
    const p = new Uint32Array(body.buffer, body.byteOffset, body.length);
    // the commands that name their context themselves
    switch(id)
    {
        case C.SVGA_3D_CMD_DX_DEFINE_CONTEXT: this.define_context(p[0]); return true;
        case C.SVGA_3D_CMD_DX_DESTROY_CONTEXT: this.destroy_context(p[0]); return true;
        case C.SVGA_3D_CMD_DX_BIND_CONTEXT: this.bind_context(p[0], p[1], p[2]); return true;
        case C.SVGA_3D_CMD_DX_READBACK_CONTEXT: this.readback_context(p[0]); return true;
        case C.SVGA_3D_CMD_DX_INVALIDATE_CONTEXT: return true;
        case C.SVGA_3D_CMD_DX_SET_COTABLE:
        case C.SVGA_3D_CMD_DX_GROW_COTABLE:
            this.set_cotable(p[0], p[1], p[2], p[3], id === C.SVGA_3D_CMD_DX_GROW_COTABLE);
            return true;
        case C.SVGA_3D_CMD_DX_READBACK_COTABLE: return true;
        case C.SVGA_3D_CMD_DX_COPY_COTABLE_INTO_MOB: this.copy_cotable(p[0], p[1], p[2]); return true;
        case C.SVGA_3D_CMD_DX_BIND_SHADER: this.bind_shader(p[0], p[1], p[2], p[3]); return true;
        case C.SVGA_3D_CMD_DX_BIND_ALL_SHADER: this.bind_all_shaders(p[0], INVALID, p[1], false); return true;
        case C.SVGA_3D_CMD_DX_COND_BIND_ALL_SHADER: this.bind_all_shaders(p[0], p[1], p[2], true); return true;
        case C.SVGA_3D_CMD_DX_BIND_ALL_QUERY: this.bind_all_queries(p[0], p[1]); return true;
        case C.SVGA_3D_CMD_DX_READBACK_ALL_QUERY: return true;
        case C.SVGA_3D_CMD_DX_MOB_FENCE_64: this.mob_fence(p[0], p[1], p[2], p[3]); return true;
        case C.SVGA_3D_CMD_DX_BIND_SHADER_IFACE: return true;
        case C.SVGA_3D_CMD_DX_HINT: return true;
    }
    let context = this.contexts.get(cid);
    if(!context && SURFACE_ONLY.has(id)) context = this.device_context();
    if(!context)
    {
        this.warn("cid", "a DX command (" + id + ") outside of a DX context");
        return true;
    }
    if(this.define(context, id, p, true)) return true;
    this.state_command(context, id, p);
    return true;
};

/** The context of the surface-only commands that come without one */
DXDevice.prototype.device_context = function()
{
    if(!this.device_dx)
    {
        this.device_dx = new DXContext(INVALID);
        this.gx().command(GX.CONTEXT_DEFINE, [INVALID]);
    }
    return this.device_dx;
};

DXDevice.prototype.define_context = function(cid)
{
    this.contexts.set(cid, new DXContext(cid));
    this.s.otable(C.SVGA_OTABLE_DXCONTEXT, cid, [cid, INVALID]);
    this.gx().command(GX.CONTEXT_DEFINE, [cid]);
};

DXDevice.prototype.destroy_context = function(cid)
{
    this.contexts.delete(cid);
    this.s.otable(C.SVGA_OTABLE_DXCONTEXT, cid, null);
    this.gx().command(GX.CONTEXT_DESTROY, [cid]);
};

DXDevice.prototype.bind_context = function(cid, mob, valid)
{
    let context = this.contexts.get(cid);
    if(!context)
    {
        this.warn("bind-undefined", "binding an undefined DX context");
        return;
    }
    context.mob = mob;
    this.s.otable(C.SVGA_OTABLE_DXCONTEXT, cid, [cid, mob]);
    if(!valid || mob === INVALID) return;
    // the guest gives the context back (after it lost the device, or moved
    // it): its state from the MOB, its objects from its COTables
    const bytes = this.s.device.mobs.read(mob, 0, DXCTX.DWORDS * 4);
    if(!bytes) return this.warn("context-mob", "a DX context MOB too small");
    context.state.set(new Uint32Array(bytes.buffer, bytes.byteOffset, DXCTX.DWORDS));
    this.restore(context);
};

DXDevice.prototype.readback_context = function(cid)
{
    const context = this.contexts.get(cid);
    if(!context || context.mob === INVALID) return;
    this.s.device.mobs.write(context.mob, 0, new Uint8Array(context.state.buffer));
};

/**
 * GX gets a context again: the objects of its COTables, then its state
 */
DXDevice.prototype.restore = function(context)
{
    const st = context.state, cid = context.cid;
    for(let type = 0; type < C.SVGA_COTABLE_MAX; type++)
    {
        const mob = st[DXCTX.COTABLES + type];
        if(mob === INVALID) continue;
        const size = this.s.device.mobs.size(mob);
        this.load_cotable(context, type, Math.max(0, Math.floor(size / COTABLE_ENTRY_BYTES[type])));
    }
    const send = (id, words) => this.state_command(context, id, Uint32Array.from(words, v => v >>> 0));
    send(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, [st[DXCTX.LAYOUT]]);
    const buffers = [0];
    for(let i = 0; i < 32; i++) buffers.push(...st.subarray(DXCTX.VERTEX_BUFFERS + 3 * i, DXCTX.VERTEX_BUFFERS + 3 * i + 3));
    send(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, buffers);
    send(C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER, [st[DXCTX.INDEX_SID], st[DXCTX.INDEX_FORMAT], st[DXCTX.INDEX_OFFSET]]);
    send(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, [st[DXCTX.TOPOLOGY]]);
    send(C.SVGA_3D_CMD_DX_SET_BLEND_STATE, [st[DXCTX.BLEND], ...st.subarray(DXCTX.BLEND_FACTOR, DXCTX.BLEND_FACTOR + 4), st[DXCTX.SAMPLE_MASK]]);
    send(C.SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE, [st[DXCTX.DEPTH_STENCIL], st[DXCTX.STENCIL_REF]]);
    send(C.SVGA_3D_CMD_DX_SET_RASTERIZER_STATE, [st[DXCTX.RASTERIZER]]);
    send(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, [st[DXCTX.DSV], ...st.subarray(DXCTX.RTVS, DXCTX.RTVS + 8)]);
    const viewports = st[DXCTX.VIEWPORT_COUNTS] & 0xFF, scissors = st[DXCTX.VIEWPORT_COUNTS] >> 8 & 0xFF;
    send(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, [0, ...st.subarray(DXCTX.VIEWPORTS, DXCTX.VIEWPORTS + 6 * viewports)]);
    send(C.SVGA_3D_CMD_DX_SET_SCISSORRECTS, [0, ...st.subarray(DXCTX.SCISSORS, DXCTX.SCISSORS + 4 * scissors)]);
    for(let type = C.SVGA3D_SHADERTYPE_MIN; type < C.SVGA3D_SHADERTYPE_MAX; type++)
    {
        const at = DXCTX.SHADER_STATE + (type - C.SVGA3D_SHADERTYPE_MIN) * DXCTX.SHADER_STATE_DWORDS;
        send(C.SVGA_3D_CMD_DX_SET_SHADER, [st[at + STAGE_SHADER], type]);
        for(let slot = 0; slot < 16; slot++)
        {
            const cb = at + STAGE_CBS + 3 * slot;
            send(C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER, [slot, type, st[cb], st[cb + 1], st[cb + 2]]);
        }
        send(C.SVGA_3D_CMD_DX_SET_SHADER_RESOURCES, [0, type, ...st.subarray(at + STAGE_SRVS, at + STAGE_SRVS + 128)]);
        send(C.SVGA_3D_CMD_DX_SET_SAMPLERS, [0, type, ...st.subarray(at + STAGE_SAMPLERS, at + STAGE_SAMPLERS + 16)]);
    }
    send(C.SVGA_3D_CMD_DX_SET_SOTARGETS, [0, ...[0, 1, 2, 3].flatMap(i => [st[DXCTX.SO_TARGETS + i], 0, INVALID])]);
    send(C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT, [st[DXCTX.SOID]]);
    send(C.SVGA_3D_CMD_DX_SET_PREDICATION, [st[DXCTX.PREDICATION], st[DXCTX.PREDICATION + 1]]);
    send(C.SVGA_3D_CMD_DX_SET_UA_VIEWS, [st[DXCTX.UAV_SPLICE], ...st.subarray(DXCTX.UAVS, DXCTX.UAVS + 64)]);
    send(C.SVGA_3D_CMD_DX_SET_CS_UA_VIEWS, [0, ...st.subarray(DXCTX.CS_UAVS, DXCTX.CS_UAVS + 64)]);
};

DXDevice.prototype.set_cotable = function(cid, mob, type, valid, grow)
{
    const context = this.contexts.get(cid);
    if(!context || type >= C.SVGA_COTABLE_MAX) return;
    const old = context.state[DXCTX.COTABLES + type];
    if(grow && old !== INVALID && mob !== INVALID)
    {
        // the device moves the valid entries into the new table
        const bytes = this.s.device.mobs.read(old, 0, Math.min(valid, this.s.device.mobs.size(old)));
        if(bytes) this.s.device.mobs.write(mob, 0, bytes);
    }
    context.state[DXCTX.COTABLES + type] = mob;
    if(grow) return;
    this.load_cotable(context, type, mob === INVALID ? 0 : Math.floor(valid / COTABLE_ENTRY_BYTES[type]));
};

DXDevice.prototype.copy_cotable = function(cid, type, mob)
{
    const context = this.contexts.get(cid);
    const from = context ? context.state[DXCTX.COTABLES + type] : INVALID;
    if(from === INVALID) return;
    const bytes = this.s.device.mobs.read(from, 0, Math.min(this.s.device.mobs.size(from), this.s.device.mobs.size(mob)));
    if(bytes) this.s.device.mobs.write(mob, 0, bytes);
};

/**
 * DX_DEFINE_* and DX_DESTROY_* of the objects in COTables
 * @param {boolean} entry whether to write the COTable entry (not when it came from there)
 * @return {boolean} whether it was one
 */
DXDevice.prototype.define = function(context, id, p, entry)
{
    const cid = context.cid;
    const write = (type, object, dwords) => { if(entry) this.write_entry(context, type, object, dwords); };
    switch(id)
    {
        case C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW:
            context.views[VIEW_RTV].set(p[0], p[1]);
            this.written(p[1]);
            write(C.SVGA_COTABLE_RTVIEW, p[0], p.subarray(1, 7));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW:
        case C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW_V2:
            context.views[VIEW_DSV].set(p[0], p[1]);
            this.written(p[1]);
            write(C.SVGA_COTABLE_DSVIEW, p[0], [...p.subarray(1, 7), p[7] & 0xFF]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW:
            context.views[VIEW_SRV].set(p[0], p[1]);
            this.surface(p[1]);
            write(C.SVGA_COTABLE_SRVIEW, p[0], p.subarray(1, 8));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW:
            context.views[VIEW_UAV].set(p[0], p[1]);
            this.written(p[1]);
            write(C.SVGA_COTABLE_UAVIEW, p[0], p.subarray(1, 9));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT:
        {
            const count = Math.min(32, Math.floor((p.length - 1) / 6));
            write(C.SVGA_COTABLE_ELEMENTLAYOUT, p[0], [p[0], count, ...p.subarray(1, 1 + 6 * count)]);
            break;
        }
        case C.SVGA_3D_CMD_DX_DEFINE_BLEND_STATE:
            write(C.SVGA_COTABLE_BLENDSTATE, p[0], p.subarray(1, 26));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE:
            write(C.SVGA_COTABLE_DEPTHSTENCIL, p[0], p.subarray(1, 5));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE:
            write(C.SVGA_COTABLE_RASTERIZERSTATE, p[0], [...p.subarray(1, 8), 0]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE_V2:
            write(C.SVGA_COTABLE_RASTERIZERSTATE, p[0], [...p.subarray(1, 8), p[8] & 0xFF]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE:
            write(C.SVGA_COTABLE_SAMPLER, p[0], p.subarray(1, 11));
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_QUERY:
            // type, state (new), flags, no MOB yet
            write(C.SVGA_COTABLE_DXQUERY, p[0], [p[1] & 0xFF | C.SVGADX_QDSTATE_IDLE << 24, p[2], INVALID, 0]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_SHADER:
            context.shaders.set(p[0], [p[1], p[2]]);
            write(C.SVGA_COTABLE_DXSHADER, p[0], [p[1], p[2], 0, INVALID]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT:
            write(C.SVGA_COTABLE_STREAMOUTPUT, p[0], [...p.subarray(1, 1 + 1 + 256 + 4 + 1), 4, INVALID, 0, 0]);
            break;
        case C.SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT_WITH_MOB:
            // decls come with DX_BIND_STREAMOUTPUT
            write(C.SVGA_COTABLE_STREAMOUTPUT, p[0], [p[1], ...new Array(256).fill(0), ...p.subarray(3, 8), p[2], INVALID, 0, 1]);
            break;
        case C.SVGA_3D_CMD_DX_BIND_STREAMOUTPUT:
        {
            // soid, mobid, offset, size: the declarations are in the MOB
            const bytes = this.s.device.mobs.read(p[1], p[2], p[3]);
            if(!bytes) break;
            const decls = new Uint32Array(bytes.slice().buffer);
            this.forward(cid, id, Uint32Array.of(p[0], p[1], p[2], p[3], ...decls));
            return true;
        }
        case C.SVGA_3D_CMD_DX_DESTROY_RENDERTARGET_VIEW:
            context.views[VIEW_RTV].delete(p[0]);
            write(C.SVGA_COTABLE_RTVIEW, p[0], null);
            break;
        case C.SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_VIEW:
            context.views[VIEW_DSV].delete(p[0]);
            write(C.SVGA_COTABLE_DSVIEW, p[0], null);
            break;
        case C.SVGA_3D_CMD_DX_DESTROY_SHADERRESOURCE_VIEW:
            context.views[VIEW_SRV].delete(p[0]);
            write(C.SVGA_COTABLE_SRVIEW, p[0], null);
            break;
        case C.SVGA_3D_CMD_DX_DESTROY_UA_VIEW:
            context.views[VIEW_UAV].delete(p[0]);
            write(C.SVGA_COTABLE_UAVIEW, p[0], null);
            break;
        case C.SVGA_3D_CMD_DX_DESTROY_ELEMENTLAYOUT: write(C.SVGA_COTABLE_ELEMENTLAYOUT, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_BLEND_STATE: write(C.SVGA_COTABLE_BLENDSTATE, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_STATE: write(C.SVGA_COTABLE_DEPTHSTENCIL, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_RASTERIZER_STATE: write(C.SVGA_COTABLE_RASTERIZERSTATE, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_SAMPLER_STATE: write(C.SVGA_COTABLE_SAMPLER, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_QUERY: write(C.SVGA_COTABLE_DXQUERY, p[0], null); break;
        case C.SVGA_3D_CMD_DX_DESTROY_SHADER:
            context.shaders.delete(p[0]);
            write(C.SVGA_COTABLE_DXSHADER, p[0], null);
            break;
        case C.SVGA_3D_CMD_DX_DESTROY_STREAMOUTPUT: write(C.SVGA_COTABLE_STREAMOUTPUT, p[0], null); break;
        default:
            return false;
    }
    this.forward(cid, id, p);
    return true;
};

/**
 * DX_BIND_SHADER: cid, shid, mobid, offset: the tokens are read now
 */
DXDevice.prototype.bind_shader = function(cid, shid, mob, offset)
{
    const context = this.contexts.get(cid);
    if(!context) return;
    const e = this.read_entry(context, C.SVGA_COTABLE_DXSHADER, shid);
    const known = context.shaders.get(shid);
    const type = e && e[1] ? e[0] : known ? known[0] : 0, size = e && e[1] ? e[1] : known ? known[1] : 0;
    this.write_entry(context, C.SVGA_COTABLE_DXSHADER, shid, [type, size, offset, mob]);
    if(mob !== INVALID) this.shader_code(context, shid, type, size, mob, offset);
};

DXDevice.prototype.shader_code = function(context, shid, type, size, mob, offset)
{
    const bytes = size ? this.s.device.mobs.read(mob, offset, size & ~3) : null;
    if(!bytes) return this.warn("shader-mob", "a DX shader outside of its MOB");
    // (a test's hook: tests/x64/windows_boot.mjs, "dxshaders")
    if(this.s.shader_log) this.s.shader_log(shid, type, bytes);
    this.gx().command(GX.SHADER_CODE, [context.cid, shid, type], bytes);
};

/** DX_(COND_)BIND_ALL_SHADER: every shader (bound to test_mob) moves to a MOB */
DXDevice.prototype.bind_all_shaders = function(cid, test_mob, mob, conditional)
{
    const context = this.contexts.get(cid);
    const table = context ? context.state[DXCTX.COTABLES + C.SVGA_COTABLE_DXSHADER] : INVALID;
    if(table === INVALID) return;
    const count = Math.floor(this.s.device.mobs.size(table) / COTABLE_ENTRY_BYTES[C.SVGA_COTABLE_DXSHADER]);
    for(let shid = 0; shid < count; shid++)
    {
        const e = this.read_entry(context, C.SVGA_COTABLE_DXSHADER, shid);
        if(!e || !e[1] || e[3] === INVALID || conditional && e[3] !== test_mob) continue;
        this.bind_shader(cid, shid, mob, e[2]);
    }
};

// ---------------------------------------------------------------------------
// Queries: results in MOBs (SVGA3dQueryState, then the result)

DXDevice.prototype.query_entry = function(context, qid)
{
    return this.read_entry(context, C.SVGA_COTABLE_DXQUERY, qid);
};

DXDevice.prototype.end_query = function(context, qid)
{
    const e = this.query_entry(context, qid);
    if(!e) return this.warn("query", "a query without a COTable entry");
    const type = e[0] & 0xFF, mob = e[2], offset = e[3];
    const result_bytes = QUERY_RESULT_BYTES[type] || 4;
    const write = (state, value) => {
        if(mob === INVALID) return;
        const bytes = new Uint8Array(4 + result_bytes);
        const view = new DataView(bytes.buffer);
        view.setUint32(0, state, true);
        if(value) bytes.set(value.subarray(0, Math.min(result_bytes, value.length)), 4);
        this.s.device.mobs.write(mob, offset, bytes);
    };
    write(C.SVGA3D_QUERYSTATE_PENDING, null);
    const request = this.s.request((value, status) => {
        write(status === 1 ? C.SVGA3D_QUERYSTATE_SUCCEEDED : C.SVGA3D_QUERYSTATE_FAILED, value);
    });
    this.gx().command(GX.QUERY_END, [context.cid, qid, type, request.id, request.slot]);
};

DXDevice.prototype.bind_all_queries = function(cid, mob)
{
    const context = this.contexts.get(cid);
    const table = context ? context.state[DXCTX.COTABLES + C.SVGA_COTABLE_DXQUERY] : INVALID;
    if(table === INVALID) return;
    const count = Math.floor(this.s.device.mobs.size(table) / 16);
    for(let qid = 0; qid < count; qid++)
    {
        const e = this.query_entry(context, qid);
        if(!e || e.every(v => v === 0)) continue;
        e[2] = mob;
        this.write_entry(context, C.SVGA_COTABLE_DXQUERY, qid, e);
    }
};

/** DX_MOB_FENCE_64: a 64-bit value into a MOB once the work before it is done */
DXDevice.prototype.mob_fence = function(low, high, mob, offset)
{
    this.s.after_work(() => {
        this.s.device.mobs.write(mob, offset, new Uint8Array(Uint32Array.of(low, high).buffer));
        this.s.device.set_irq(C.SVGA_IRQFLAG_MOB_FENCE);
    });
};

// ---------------------------------------------------------------------------
// State, draws, copies, transfers

DXDevice.prototype.stage = function(type)
{
    return type >= C.SVGA3D_SHADERTYPE_MIN && type < C.SVGA3D_SHADERTYPE_MAX ?
        DXCTX.SHADER_STATE + (type - C.SVGA3D_SHADERTYPE_MIN) * DXCTX.SHADER_STATE_DWORDS : -1;
};

DXDevice.prototype.state_command = function(context, id, p)
{
    const st = context.state, cid = context.cid;
    const view_sid = (kind, view) => context.views[kind].get(view);
    switch(id)
    {
        case C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER:
        {
            // slot, type, sid, offset, size
            const at = this.stage(p[1]);
            if(at < 0 || p[0] >= 16) return;
            st.set([p[2], p[3], p[4]], at + STAGE_CBS + 3 * p[0]);
            this.surface(p[2]);
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_SHADER_RESOURCES:
        {
            const at = this.stage(p[1]);
            if(at < 0) return;
            const ids = p.subarray(2, 2 + Math.max(0, Math.min(p.length - 2, 128 - p[0])));
            st.set(ids, at + STAGE_SRVS + p[0]);
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_SAMPLERS:
        {
            const at = this.stage(p[1]);
            if(at < 0) return;
            st.set(p.subarray(2, 2 + Math.max(0, Math.min(p.length - 2, 16 - p[0]))), at + STAGE_SAMPLERS + p[0]);
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_SHADER:
        {
            const at = this.stage(p[1]);
            if(at < 0) return;
            st[at + STAGE_SHADER] = p[0];
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT:
            st[DXCTX.LAYOUT] = p[0];
            break;
        case C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS:
        case C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_V2:
        {
            // startBuffer, then (sid, stride, offset[, size]) each
            const each = id === C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS ? 3 : 4;
            for(let i = 0; 1 + each * (i + 1) <= p.length && p[0] + i < 32; i++)
            {
                const b = 1 + each * i;
                st.set([p[b], p[b + 1], p[b + 2]], DXCTX.VERTEX_BUFFERS + 3 * (p[0] + i));
                this.surface(p[b]);
            }
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_OFFSET_AND_SIZE:
            for(let i = 0; 1 + 3 * (i + 1) <= p.length && p[0] + i < 32; i++)
            {
                const b = 1 + 3 * i;
                st.set([p[b], p[b + 1]], DXCTX.VERTEX_BUFFERS + 3 * (p[0] + i) + 1);
            }
            break;
        case C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER:
        case C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER_V2:
            st[DXCTX.INDEX_SID] = p[0];
            st[DXCTX.INDEX_FORMAT] = p[1];
            st[DXCTX.INDEX_OFFSET] = p[2];
            this.surface(p[0]);
            break;
        case C.SVGA_3D_CMD_DX_SET_INDEX_BUFFER_OFFSET_AND_SIZE:
            st[DXCTX.INDEX_FORMAT] = p[0];
            st[DXCTX.INDEX_OFFSET] = p[1];
            break;
        case C.SVGA_3D_CMD_DX_SET_TOPOLOGY:
            st[DXCTX.TOPOLOGY] = p[0];
            break;
        case C.SVGA_3D_CMD_DX_SET_RENDERTARGETS:
        {
            // dsv, then render target views
            st[DXCTX.DSV] = p[0];
            const rtvs = p.subarray(1, Math.min(p.length, 9));
            for(let i = 0; i < 8; i++) st[DXCTX.RTVS + i] = i < rtvs.length ? rtvs[i] : INVALID;
            const dsv = view_sid(VIEW_DSV, p[0]);
            if(dsv !== undefined) this.written(dsv);
            for(const rtv of rtvs)
            {
                const sid = view_sid(VIEW_RTV, rtv);
                if(sid !== undefined) this.written(sid);
            }
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_BLEND_STATE:
            st[DXCTX.BLEND] = p[0];
            st.set(p.subarray(1, 5), DXCTX.BLEND_FACTOR);
            st[DXCTX.SAMPLE_MASK] = p[5];
            break;
        case C.SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE:
            st[DXCTX.DEPTH_STENCIL] = p[0];
            st[DXCTX.STENCIL_REF] = p[1];
            break;
        case C.SVGA_3D_CMD_DX_SET_RASTERIZER_STATE:
            st[DXCTX.RASTERIZER] = p[0];
            break;
        case C.SVGA_3D_CMD_DX_SET_VIEWPORTS:
        {
            const count = Math.min(16, Math.floor((p.length - 1) / 6));
            st.set(p.subarray(1, 1 + 6 * count), DXCTX.VIEWPORTS);
            st[DXCTX.VIEWPORT_COUNTS] = st[DXCTX.VIEWPORT_COUNTS] & ~0xFF | count;
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_SCISSORRECTS:
        {
            const count = Math.min(16, Math.floor((p.length - 1) / 4));
            st.set(p.subarray(1, 1 + 4 * count), DXCTX.SCISSORS);
            st[DXCTX.VIEWPORT_COUNTS] = st[DXCTX.VIEWPORT_COUNTS] & ~0xFF00 | count << 8;
            break;
        }
        case C.SVGA_3D_CMD_DX_SET_SOTARGETS:
            for(let i = 0; i < 4; i++)
            {
                const sid = 1 + 3 * i < p.length ? p[1 + 3 * i] : INVALID;
                st[DXCTX.SO_TARGETS + i] = sid;
                this.written(sid);
            }
            break;
        case C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT:
            st[DXCTX.SOID] = p[0];
            break;
        case C.SVGA_3D_CMD_DX_SET_PREDICATION:
            st[DXCTX.PREDICATION] = p[0];
            st[DXCTX.PREDICATION + 1] = p[1];
            break;
        case C.SVGA_3D_CMD_DX_SET_UA_VIEWS:
            st[DXCTX.UAV_SPLICE] = p[0];
            st.set(p.subarray(1, Math.min(p.length, 65)), DXCTX.UAVS);
            for(const uav of p.subarray(1))
            {
                const sid = view_sid(VIEW_UAV, uav);
                if(sid !== undefined) this.written(sid);
            }
            break;
        case C.SVGA_3D_CMD_DX_SET_CS_UA_VIEWS:
            st.set(p.subarray(1, Math.min(p.length, 65 - p[0])), DXCTX.CS_UAVS + p[0]);
            for(const uav of p.subarray(1))
            {
                const sid = view_sid(VIEW_UAV, uav);
                if(sid !== undefined) this.written(sid);
            }
            break;
        case C.SVGA_3D_CMD_DX_SET_VS_CONSTANT_BUFFER_OFFSET:
        case C.SVGA_3D_CMD_DX_SET_PS_CONSTANT_BUFFER_OFFSET:
        case C.SVGA_3D_CMD_DX_SET_GS_CONSTANT_BUFFER_OFFSET:
        case C.SVGA_3D_CMD_DX_SET_HS_CONSTANT_BUFFER_OFFSET:
        case C.SVGA_3D_CMD_DX_SET_DS_CONSTANT_BUFFER_OFFSET:
        case C.SVGA_3D_CMD_DX_SET_CS_CONSTANT_BUFFER_OFFSET:
        {
            const type = C.SVGA3D_SHADERTYPE_VS + id - C.SVGA_3D_CMD_DX_SET_VS_CONSTANT_BUFFER_OFFSET;
            const at = this.stage(type);
            if(at >= 0 && p[0] < 16) st[at + STAGE_CBS + 3 * p[0] + 1] = p[1];
            break;
        }
        case C.SVGA_3D_CMD_DX_BIND_QUERY:
        case C.SVGA_3D_CMD_DX_SET_QUERY_OFFSET:
        case C.SVGA_3D_CMD_DX_MOVE_QUERY:
        {
            const e = this.query_entry(context, p[0]);
            if(!e) return;
            if(id === C.SVGA_3D_CMD_DX_BIND_QUERY) e[2] = p[1];
            else if(id === C.SVGA_3D_CMD_DX_SET_QUERY_OFFSET) e[3] = p[1];
            else { e[2] = p[1]; e[3] = p[2]; }
            this.write_entry(context, C.SVGA_COTABLE_DXQUERY, p[0], e);
            return;
        }
        case C.SVGA_3D_CMD_DX_END_QUERY:
            this.end_query(context, p[0]);
            return;
        case C.SVGA_3D_CMD_DX_READBACK_QUERY:
            return;

        // the surfaces these name are made in GX first; copies' destinations are written
        case C.SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED_INDIRECT:
        case C.SVGA_3D_CMD_DX_DRAW_INSTANCED_INDIRECT:
        case C.SVGA_3D_CMD_DX_DISPATCH_INDIRECT:
        case C.SVGA_3D_CMD_DX_SET_MIN_LOD:
            this.surface(p[0]);
            break;
        case C.SVGA_3D_CMD_DX_PRED_COPY_REGION:
        case C.SVGA_3D_CMD_DX_RESOLVE_COPY:
        case C.SVGA_3D_CMD_DX_PRED_RESOLVE_COPY:
            this.surface(p[2]);
            this.written(p[0]);
            break;
        case C.SVGA_3D_CMD_DX_PRED_COPY:
        case C.SVGA_3D_CMD_DX_PRED_CONVERT:
            this.surface(p[1]);
            this.written(p[0]);
            break;
        case C.SVGA_3D_CMD_DX_PRED_CONVERT_REGION:
            this.surface(p[8]);
            this.written(p[0]);
            break;
        // the staging copies (FL11's readbacks): a copy, then, with their
        // readback byte, the destination (subresource) into its MOB
        case C.SVGA_3D_CMD_DX_PRED_STAGING_COPY_REGION:
            this.surface(p[2]);
            return this.staging_copy(cid, id, p, p[0], p[1], (p[13] & 0xFF) !== 0);
        case C.SVGA_3D_CMD_DX_PRED_STAGING_COPY:
        case C.SVGA_3D_CMD_DX_STAGING_COPY:
        case C.SVGA_3D_CMD_DX_PRED_STAGING_CONVERT:
            this.surface(p[1]);
            return this.staging_copy(cid, id, p, p[0], -1, (p[2] & 0xFF) !== 0);
        case C.SVGA_3D_CMD_DX_PRED_STAGING_CONVERT_REGION:
            this.surface(p[8]);
            return this.staging_copy(cid, id, p, p[0], p[1], (p[16] & 0xFF) !== 0);
        case C.SVGA_3D_CMD_DX_BUFFER_COPY:
        case C.SVGA_3D_CMD_DX_STAGING_BUFFER_COPY:
            this.surface(p[1]);
            this.written(p[0]);
            break;
        case C.SVGA_3D_CMD_DX_PRESENTBLT:
            this.surface(p[0]);
            this.written(p[2]);
            break;
        case C.SVGA_3D_CMD_DX_TRANSFER_FROM_BUFFER:
        case C.SVGA_3D_CMD_DX_PRED_TRANSFER_FROM_BUFFER:
            this.surface(p[0]);
            this.written(p[4]);
            break;
        case C.SVGA_3D_CMD_DX_TRANSFER_TO_BUFFER:
            this.surface(p[0]);
            this.written(p[9]);
            if(p[13] & C.SVGA3D_TRANSFER_TO_BUFFER_READBACK)
            {
                this.forward(cid, id, p);
                this.s.readback_surface(this.s.surfaces.get(p[9]));
                return;
            }
            break;
        case C.SVGA_3D_CMD_DX_SURFACE_COPY_AND_READBACK:
        {
            // srcSid, destSid, box: a copy, then the destination into its MOB
            this.surface(p[0]);
            this.written(p[1]);
            this.forward(cid, id, p);
            const dst = this.s.surfaces.get(p[1]);
            if(dst) this.s.readback_surface(dst);
            return;
        }
        case C.SVGA_3D_CMD_DX_GENMIPS:
        {
            const sid = view_sid(VIEW_SRV, p[0]);
            if(sid !== undefined) this.written(sid);
            break;
        }
        case C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW:
        {
            const sid = view_sid(VIEW_RTV, p[0]);
            if(sid !== undefined) this.written(sid);
            break;
        }
        case C.SVGA_3D_CMD_DX_CLEAR_DEPTHSTENCIL_VIEW:
        {
            const sid = view_sid(VIEW_DSV, p[1]);
            if(sid !== undefined) this.written(sid);
            break;
        }
        case C.SVGA_3D_CMD_DX_CLEAR_UA_VIEW_UINT:
        case C.SVGA_3D_CMD_DX_CLEAR_UA_VIEW_FLOAT:
        {
            const sid = view_sid(VIEW_UAV, p[0]);
            if(sid !== undefined) this.written(sid);
            break;
        }
        case C.SVGA_3D_CMD_DX_COPY_STRUCTURE_COUNT:
            // srcUAViewId, destSid, destByteOffset
            this.written(p[1]);
            break;

        // moving contents between MOBs and the GPU
        case C.SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE:
        {
            // sid, subResource, box (x, y, z, w, h, d)
            const surface = this.s.surfaces.get(p[0]);
            if(surface) this.s.update_subresource(surface, p[1], [p[2], p[3], p[4], p[5], p[6], p[7]]);
            return;
        }
        case C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE:
        {
            const surface = this.s.surfaces.get(p[0]);
            if(surface) this.s.readback_subresource(surface, p[1]);
            return;
        }
        case C.SVGA_3D_CMD_DX_INVALIDATE_SUBRESOURCE:
            return;
        case C.SVGA_3D_CMD_DX_BUFFER_UPDATE:
        {
            // sid, x, width
            const surface = this.s.surfaces.get(p[0]);
            if(surface) this.s.update_subresource(surface, 0, [p[1], 0, 0, p[2], 1, 1]);
            return;
        }
        case C.SVGA_3D_CMD_DX_DRAW:
        case C.SVGA_3D_CMD_DX_DRAW_INDEXED:
        case C.SVGA_3D_CMD_DX_DRAW_INSTANCED:
        case C.SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED:
        case C.SVGA_3D_CMD_DX_DRAW_AUTO:
        case C.SVGA_3D_CMD_DX_DISPATCH:
            this.drawing(context);
            break;
        case C.SVGA_3D_CMD_DX_BEGIN_QUERY:
        case C.SVGA_3D_CMD_DX_SET_SHADER_IFACE:
        case C.SVGA_3D_CMD_DX_SET_STRUCTURE_COUNT:
            break;
        default:
            this.warn("cmd" + id, "DX command " + id + " is not supported");
            return;
    }
    this.forward(cid, id, p);
};

DXDevice.prototype.get_state = function()
{
    const contexts = [];
    for(const c of this.contexts.values()) contexts.push([c.cid, c.mob, c.state]);
    return contexts;
};

/**
 * After a restore: the contexts again, their objects from their COTables
 * (guest memory, restored), their state
 */
DXDevice.prototype.set_state = function(state)
{
    this.contexts.clear();
    this.device_dx = null;
    for(const [cid, mob, saved] of state || [])
    {
        this.define_context(cid);
        const context = this.contexts.get(cid);
        context.mob = mob;
        context.state.set(saved);
        this.restore(context);
    }
};

/** For dbg_log users that only have the module */
export function dx_log(text)
{
    dbg_log("svga-dx: " + text, LOG_VGA);
}
                                                                                                    source/v64/src/graphics_adapters/vmware_svga/svga3d_tables.js                                       0000644 0000000 0000000 00000063353 00000000000 021550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the legacy SVGA3D names mean in Direct3D 9 terms: the D3D9 executor
// takes D3D9 enums. VMware designed SVGA3D's legacy commands after D3D9, so
// most of this is renumbering; the exceptions (cull mode and winding, fog
// mode, alpha reference, gamma, texture arguments) are noted where they are.

import * as C from "./svga_constants.js";
import { DX_FORMATS, AFTER_DX10 } from "./svga_dx_formats.js";

// D3DFORMAT values
const D3DFMT = {
    A8R8G8B8: 21, X8R8G8B8: 22, R5G6B5: 23, X1R5G5B5: 24, A1R5G5B5: 25, A4R4G4B4: 26,
    A8: 28, A2B10G10R10: 31, A8B8G8R8: 32, G16R16: 34, A2R10G10B10: 35, A16B16G16R16: 36,
    P8: 41, L8: 50, A8L8: 51, A4L4: 52, V8U8: 60, L6V5U5: 61, X8L8V8U8: 62, Q8W8V8U8: 63,
    V16U16: 64, A2W10V10U10: 67, D32: 71, D15S1: 73, D24S8: 75, D24X8: 77, D16: 80, L16: 81,
    D32F_LOCKABLE: 82, R16F: 111, G16R16F: 112, A16B16G16R16F: 113, R32F: 114, G32R32F: 115,
    A32B32G32R32F: 116, CxV8U8: 117,
    UYVY: 0x59565955, YUY2: 0x32595559,
    DXT1: 0x31545844, DXT2: 0x32545844, DXT3: 0x33545844, DXT4: 0x34545844, DXT5: 0x35545844,
    DF16: 0x36314644, DF24: 0x34324644, INTZ: 0x5A544E49, ATI1: 0x31495441, ATI2: 0x32495441,
    INDEX16: 101, INDEX32: 102,
};
export { D3DFMT };

/**
 * One surface format: its D3D9 format, its bytes per pixel or per 4x4 block,
 * and what it is good for
 * @typedef {{d3d: number, bytes: number, block: number, depth: boolean, target: boolean}}
 */
let FormatInfo;

/**
 * @param {number} d3d
 * @param {number} bytes
 * @param {Object=} extra
 * @return {FormatInfo}
 */
function f(d3d, bytes, extra)
{
    return /** @type {FormatInfo} */ (Object.assign({ d3d, bytes, block: 1, depth: false, target: false }, extra || {}));
}
const target = { target: true };
const depth = { depth: true };
const block = { block: 4 };

/** @type {!Object<number, FormatInfo>} SVGA3dSurfaceFormat -> */
export const FORMATS = {
    [C.SVGA3D_X8R8G8B8]: f(D3DFMT.X8R8G8B8, 4, target),
    [C.SVGA3D_A8R8G8B8]: f(D3DFMT.A8R8G8B8, 4, target),
    [C.SVGA3D_R5G6B5]: f(D3DFMT.R5G6B5, 2, target),
    [C.SVGA3D_X1R5G5B5]: f(D3DFMT.X1R5G5B5, 2, target),
    [C.SVGA3D_A1R5G5B5]: f(D3DFMT.A1R5G5B5, 2, target),
    [C.SVGA3D_A4R4G4B4]: f(D3DFMT.A4R4G4B4, 2),
    [C.SVGA3D_Z_D32]: f(D3DFMT.D32, 4, depth),
    [C.SVGA3D_Z_D16]: f(D3DFMT.D16, 2, depth),
    [C.SVGA3D_Z_D24S8]: f(D3DFMT.D24S8, 4, depth),
    [C.SVGA3D_Z_D15S1]: f(D3DFMT.D15S1, 2, depth),
    [C.SVGA3D_LUMINANCE8]: f(D3DFMT.L8, 1),
    [C.SVGA3D_LUMINANCE4_ALPHA4]: f(D3DFMT.A4L4, 1),
    [C.SVGA3D_LUMINANCE16]: f(D3DFMT.L16, 2),
    [C.SVGA3D_LUMINANCE8_ALPHA8]: f(D3DFMT.A8L8, 2),
    [C.SVGA3D_DXT1]: f(D3DFMT.DXT1, 8, block),
    [C.SVGA3D_DXT2]: f(D3DFMT.DXT2, 16, block),
    [C.SVGA3D_DXT3]: f(D3DFMT.DXT3, 16, block),
    [C.SVGA3D_DXT4]: f(D3DFMT.DXT4, 16, block),
    [C.SVGA3D_DXT5]: f(D3DFMT.DXT5, 16, block),
    [C.SVGA3D_BUMPU8V8]: f(D3DFMT.V8U8, 2),
    [C.SVGA3D_BUMPL6V5U5]: f(D3DFMT.L6V5U5, 2),
    [C.SVGA3D_BUMPX8L8V8U8]: f(D3DFMT.X8L8V8U8, 4),
    [C.SVGA3D_ARGB_S10E5]: f(D3DFMT.A16B16G16R16F, 8, target),
    [C.SVGA3D_ARGB_S23E8]: f(D3DFMT.A32B32G32R32F, 16, target),
    [C.SVGA3D_A2R10G10B10]: f(D3DFMT.A2R10G10B10, 4, target),
    [C.SVGA3D_V8U8]: f(D3DFMT.V8U8, 2),
    [C.SVGA3D_Q8W8V8U8]: f(D3DFMT.Q8W8V8U8, 4),
    [C.SVGA3D_CxV8U8]: f(D3DFMT.CxV8U8, 2),
    [C.SVGA3D_X8L8V8U8]: f(D3DFMT.X8L8V8U8, 4),
    [C.SVGA3D_A2W10V10U10]: f(D3DFMT.A2W10V10U10, 4),
    [C.SVGA3D_ALPHA8]: f(D3DFMT.A8, 1),
    [C.SVGA3D_R_S10E5]: f(D3DFMT.R16F, 2, target),
    [C.SVGA3D_R_S23E8]: f(D3DFMT.R32F, 4, target),
    [C.SVGA3D_RG_S10E5]: f(D3DFMT.G16R16F, 4, target),
    [C.SVGA3D_RG_S23E8]: f(D3DFMT.G32R32F, 8, target),
    [C.SVGA3D_BUFFER]: f(0, 1),
    [C.SVGA3D_Z_D24X8]: f(D3DFMT.D24X8, 4, depth),
    [C.SVGA3D_V16U16]: f(D3DFMT.V16U16, 4),
    [C.SVGA3D_G16R16]: f(D3DFMT.G16R16, 4, target),
    [C.SVGA3D_A16B16G16R16]: f(D3DFMT.A16B16G16R16, 8, target),
    [C.SVGA3D_UYVY]: f(D3DFMT.UYVY, 2),
    [C.SVGA3D_YUY2]: f(D3DFMT.YUY2, 2),
    [C.SVGA3D_P8]: f(D3DFMT.P8, 1),
    [C.SVGA3D_Z_DF16]: f(D3DFMT.DF16, 2, depth),
    [C.SVGA3D_Z_DF24]: f(D3DFMT.DF24, 4, depth),
    [C.SVGA3D_Z_D24S8_INT]: f(D3DFMT.INTZ, 4, depth),
    [C.SVGA3D_ATI1]: f(D3DFMT.ATI1, 8, block),
    [C.SVGA3D_ATI2]: f(D3DFMT.ATI2, 16, block),
    // DX names some guests use for the same storage
    [C.SVGA3D_B8G8R8A8_UNORM]: f(D3DFMT.A8R8G8B8, 4, target),
    [C.SVGA3D_B8G8R8X8_UNORM]: f(D3DFMT.X8R8G8B8, 4, target),
    [C.SVGA3D_R8G8B8A8_UNORM]: f(D3DFMT.A8B8G8R8, 4, target),
    [C.SVGA3D_B5G6R5_UNORM]: f(D3DFMT.R5G6B5, 2, target),
    [C.SVGA3D_B5G5R5A1_UNORM]: f(D3DFMT.A1R5G5B5, 2, target),
    [C.SVGA3D_R10G10B10A2_UNORM]: f(D3DFMT.A2B10G10R10, 4, target),
    [C.SVGA3D_R16G16B16A16_FLOAT]: f(D3DFMT.A16B16G16R16F, 8, target),
    [C.SVGA3D_R32G32B32A32_FLOAT]: f(D3DFMT.A32B32G32R32F, 16, target),
    [C.SVGA3D_R16G16_FLOAT]: f(D3DFMT.G16R16F, 4, target),
    [C.SVGA3D_R32G32_FLOAT]: f(D3DFMT.G32R32F, 8, target),
    [C.SVGA3D_R16_FLOAT]: f(D3DFMT.R16F, 2, target),
    [C.SVGA3D_R32_FLOAT]: f(D3DFMT.R32F, 4, target),
    [C.SVGA3D_R16G16_UNORM]: f(D3DFMT.G16R16, 4, target),
    [C.SVGA3D_R16G16B16A16_UNORM]: f(D3DFMT.A16B16G16R16, 8, target),
    [C.SVGA3D_A8_UNORM]: f(D3DFMT.A8, 1),
    [C.SVGA3D_BC1_UNORM]: f(D3DFMT.DXT1, 8, block),
    [C.SVGA3D_BC2_UNORM]: f(D3DFMT.DXT3, 16, block),
    [C.SVGA3D_BC3_UNORM]: f(D3DFMT.DXT5, 16, block),
    [C.SVGA3D_BC4_UNORM]: f(D3DFMT.ATI1, 8, block),
    [C.SVGA3D_BC5_UNORM]: f(D3DFMT.ATI2, 16, block),
    [C.SVGA3D_D16_UNORM]: f(D3DFMT.D16, 2, depth),
    [C.SVGA3D_D24_UNORM_S8_UINT]: f(D3DFMT.D24S8, 4, depth),
    [C.SVGA3D_D32_FLOAT]: f(D3DFMT.D32F_LOCKABLE, 4, depth),
};

// SVGA3dSurfaceFormatCaps, what D3D9 calls format operations
const TEXTURE = C.SVGA3DFORMAT_OP_TEXTURE | C.SVGA3DFORMAT_OP_VOLUMETEXTURE | C.SVGA3DFORMAT_OP_CUBETEXTURE;
const RENDER = C.SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET | C.SVGA3DFORMAT_OP_SAME_FORMAT_RENDERTARGET;
const ZSTENCIL = C.SVGA3DFORMAT_OP_ZSTENCIL | C.SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH;
// The D3D9 runtime disables the whole driver (no HAL, D3DERR_NOTAVAILABLE)
// if the format list breaks one of its rules (d3d9 ddcreate.cpp): 3D
// acceleration only on display modes without alpha, not both R5G6B5 and
// X1R5G5B5 as display modes, and the ARGB group only on the 8-bit and
// 16-bit RGB formats, A2R10G10B10, A16B16G16R16 and their float versions.
const DISPLAY = C.SVGA3DFORMAT_OP_DISPLAYMODE | C.SVGA3DFORMAT_OP_3DACCELERATION;
const COLOR_TARGET = TEXTURE | RENDER | C.SVGA3DFORMAT_OP_OFFSCREENPLAIN | C.SVGA3DFORMAT_OP_CONVERT_TO_ARGB |
    C.SVGA3DFORMAT_OP_AUTOGENMIPMAP;
const ARGB = COLOR_TARGET | C.SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB;
const PLAIN = TEXTURE | C.SVGA3DFORMAT_OP_OFFSCREENPLAIN;
const BUMP = PLAIN | C.SVGA3DFORMAT_OP_BUMPMAP;

/**
 * The devcaps the device reports at level vgpu9: shader model 3.0, the
 * formats the executor implements. 3DMark06 checks VS/PS 3.0, four render
 * targets, fp16 targets that blend and filter, and depth textures.
 * @type {!Array<!Array<number>>} [SVGA3D_DEVCAP_*, value]
 */
export const VGPU9_DEVCAPS = [
    [C.SVGA3D_DEVCAP_3D, 1],
    [C.SVGA3D_DEVCAP_MAX_LIGHTS, 8],
    [C.SVGA3D_DEVCAP_MAX_TEXTURES, 8],
    [C.SVGA3D_DEVCAP_MAX_CLIP_PLANES, 6],
    [C.SVGA3D_DEVCAP_VERTEX_SHADER_VERSION, C.SVGA3DVSVERSION_30],
    [C.SVGA3D_DEVCAP_VERTEX_SHADER, 1],
    [C.SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION, C.SVGA3DPSVERSION_30],
    [C.SVGA3D_DEVCAP_FRAGMENT_SHADER, 1],
    [C.SVGA3D_DEVCAP_MAX_RENDER_TARGETS, 4],
    [C.SVGA3D_DEVCAP_S23E8_TEXTURES, 1],
    [C.SVGA3D_DEVCAP_S10E5_TEXTURES, 1],
    [C.SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND, 4],
    [C.SVGA3D_DEVCAP_D16_BUFFER_FORMAT, 1],
    [C.SVGA3D_DEVCAP_D24S8_BUFFER_FORMAT, 1],
    [C.SVGA3D_DEVCAP_D24X8_BUFFER_FORMAT, 1],
    [C.SVGA3D_DEVCAP_QUERY_TYPES, 1 << C.SVGA3D_QUERYTYPE_OCCLUSION],
    [C.SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING, 1],
    [C.SVGA3D_DEVCAP_MAX_POINT_SIZE, f32_bits(64)],
    [C.SVGA3D_DEVCAP_MAX_SHADER_TEXTURES, 16],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH, 8192],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT, 8192],
    [C.SVGA3D_DEVCAP_MAX_VOLUME_EXTENT, 2048],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT, 8192],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO, 8192],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY, 16],
    [C.SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT, 0xFFFFF],
    [C.SVGA3D_DEVCAP_MAX_VERTEX_INDEX, 0xFFFFFF],
    [C.SVGA3D_DEVCAP_MAX_VERTEX_SHADER_INSTRUCTIONS, 0xFFFF],
    [C.SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS, 0xFFFF],
    [C.SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS, 32],
    [C.SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS, 32],
    // every combiner of SVGA3dTextureCombiner
    [C.SVGA3D_DEVCAP_TEXTURE_OPS, (1 << C.SVGA3D_TC_MAX - 1) - 1],
    [C.SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8, ARGB | DISPLAY | C.SVGA3DFORMAT_OP_SRGBREAD | C.SVGA3DFORMAT_OP_SRGBWRITE | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8, ARGB | C.SVGA3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET |
        C.SVGA3DFORMAT_OP_SRGBREAD | C.SVGA3DFORMAT_OP_SRGBWRITE | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10, ARGB],
    [C.SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5, ARGB],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5, ARGB | C.SVGA3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4, PLAIN | C.SVGA3DFORMAT_OP_CONVERT_TO_ARGB],
    [C.SVGA3D_DEVCAP_SURFACEFMT_R5G6B5, ARGB | DISPLAY],
    [C.SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_ALPHA8, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_D16, ZSTENCIL],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8, ZSTENCIL | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8, ZSTENCIL | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_DXT1, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_DXT2, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_DXT3, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_DXT4, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_DXT5, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_CxV8U8, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_R_S10E5, COLOR_TARGET | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_R_S23E8, COLOR_TARGET | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5, COLOR_TARGET],
    [C.SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8, COLOR_TARGET],
    [C.SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5, ARGB | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8, ARGB | C.SVGA3DFORMAT_OP_VERTEXTEXTURE],
    [C.SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES, 4],
    [C.SVGA3D_DEVCAP_MAX_SIMULTANEOUS_RENDER_TARGETS, 4],
    [C.SVGA3D_DEVCAP_SURFACEFMT_V16U16, BUMP],
    [C.SVGA3D_DEVCAP_SURFACEFMT_G16R16, COLOR_TARGET],
    [C.SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16, ARGB],
    [C.SVGA3D_DEVCAP_SURFACEFMT_UYVY, C.SVGA3DFORMAT_OP_OFFSCREENPLAIN | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_YUY2, C.SVGA3DFORMAT_OP_OFFSCREENPLAIN | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_AUTOGENMIPMAPS, 1],
    [C.SVGA3D_DEVCAP_MAX_CONTEXT_IDS, 256],
    [C.SVGA3D_DEVCAP_MAX_SURFACE_IDS, 32768],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_DF16, ZSTENCIL | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_DF24, ZSTENCIL | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT, ZSTENCIL | C.SVGA3DFORMAT_OP_TEXTURE],
    [C.SVGA3D_DEVCAP_SURFACEFMT_ATI1, PLAIN],
    [C.SVGA3D_DEVCAP_SURFACEFMT_ATI2, PLAIN],
    [C.SVGA3D_DEVCAP_LINE_AA, 1],
    [C.SVGA3D_DEVCAP_LINE_STIPPLE, 0],
    [C.SVGA3D_DEVCAP_MAX_LINE_WIDTH, f32_bits(1)],
    [C.SVGA3D_DEVCAP_MAX_AA_LINE_WIDTH, f32_bits(1)],
];

/**
 * The devcaps at level dx10: those of vgpu9, DX contexts, and per format what
 * GX does with it (svga_dx_formats.js)
 * @type {!Array<!Array<number>>}
 */
export const DX10_DEVCAPS = [
    ...VGPU9_DEVCAPS,
    [C.SVGA3D_DEVCAP_DXCONTEXT, 1],
    [C.SVGA3D_DEVCAP_DX_MAX_VERTEXBUFFERS, 16],
    [C.SVGA3D_DEVCAP_DX_MAX_CONSTANT_BUFFERS, 14],
    // the first vertex provokes (WebGPU's), not chosen per draw
    [C.SVGA3D_DEVCAP_DX_PROVOKING_VERTEX, 0],
    [C.SVGA3D_DEVCAP_MULTISAMPLE_2X, 0],
    [C.SVGA3D_DEVCAP_MULTISAMPLE_4X, 1],
    [C.SVGA3D_DEVCAP_MS_FULL_QUALITY, 0],
    [C.SVGA3D_DEVCAP_SM41, 0],
    [C.SVGA3D_DEVCAP_SM5, 0],
    ...dx_format_caps("dx10"),
];

/**
 * The devcaps at level dx10.1: dx10's and shader model 4.1, with what
 * VMware's driver wants before it offers feature level 10_1 (its table,
 * vm3dum64_10.dll at 0x180060a20): 4x multisampling of every target format
 * (GX supersamples), and from Direct3D 11.1 on NV12 and YUY2 surfaces,
 * R10G10B10_XR_BIAS_A2_UNORM ones and B8G8R8X8_UNORM vertices. GX keeps
 * the NV12 and YUY2 surfaces in guest memory only: they are made and copied,
 * never sampled or drawn into.
 * @type {!Array<!Array<number>>}
 */
export const DX10_1_DEVCAPS = with_devcaps(DX10_DEVCAPS, [
    [C.SVGA3D_DEVCAP_SM41, 1],
    ...dx_format_caps("dx10.1"),
    [C.SVGA3D_DEVCAP_DXFMT_YUY2, C.SVGA3D_DXFMT_SUPPORTED],
    [C.SVGA3D_DEVCAP_DXFMT_NV12, C.SVGA3D_DXFMT_SUPPORTED],
]);

/**
 * The devcaps at level dx11: dx10.1's and shader model 5 (compute, UAVs,
 * tessellation: GX emulates the stages WebGPU lacks), 8x multisampling
 * (supersampled 4 x 2), 16384-texel textures, and what Linux's vmwgfx and
 * Mesa want for GL 4.3: the GL43 devcap and a forced sample count of at
 * least 4 (draws without targets)
 * @type {!Array<!Array<number>>}
 */
export const DX11_DEVCAPS = with_devcaps(DX10_1_DEVCAPS, [
    [C.SVGA3D_DEVCAP_SM5, 1],
    [C.SVGA3D_DEVCAP_MULTISAMPLE_8X, 1],
    [C.SVGA3D_DEVCAP_MAX_FORCED_SAMPLE_COUNT, 8],
    [C.SVGA3D_DEVCAP_GL43, 1],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH, 16384],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT, 16384],
    [C.SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT, 16384],
]);

/**
 * The devcaps at level dx11-full: dx11's, and the last vertex provoking where
 * the rasterizer state asks (GX reorders: GL's flat shading, which Mesa's
 * svga otherwise converts in the guest)
 * @type {!Array<!Array<number>>}
 */
export const DX11_FULL_DEVCAPS = with_devcaps(DX11_DEVCAPS, [
    [C.SVGA3D_DEVCAP_DX_PROVOKING_VERTEX, 1],
]);

/** A level's devcaps from the one below's, some of them changed */
function with_devcaps(base, changes)
{
    const caps = new Map(base);
    for(const [index, value] of changes) caps.set(index, value);
    return Array.from(caps);
}

/**
 * SVGA3D_DEVCAP_DXFMT_* from svga_dx_formats.js, at a level: dx10 leaves out
 * what came later (AFTER_DX10) and multisamples the "m" formats only
 * @param {string} level
 */
function dx_format_caps(level)
{
    const dx10 = level === "dx10";
    const caps = [];
    for(const name of Object.keys(DX_FORMATS))
    {
        const index = C["SVGA3D_DEVCAP_DXFMT_" + name.slice("SVGA3D_".length)];
        if(index === undefined || dx10 && AFTER_DX10.formats.has(name)) continue;
        const [texture, can] = DX_FORMATS[name];
        const vertex = dx10 && AFTER_DX10.vertex.has(name) ? "" : DX_FORMATS[name][2];
        let value = 0;
        if(texture || vertex) value |= C.SVGA3D_DXFMT_SUPPORTED;
        if(can.includes("s") || can.includes("u")) value |= C.SVGA3D_DXFMT_SHADER_SAMPLE;
        if(can.includes("r")) value |= C.SVGA3D_DXFMT_COLOR_RENDERTARGET;
        if(can.includes("d")) value |= C.SVGA3D_DXFMT_DEPTH_RENDERTARGET;
        if(can.includes("b")) value |= C.SVGA3D_DXFMT_BLENDABLE;
        if(texture) value |= C.SVGA3D_DXFMT_MIPS | C.SVGA3D_DXFMT_ARRAY;
        if(texture && !can.includes("d")) value |= C.SVGA3D_DXFMT_VOLUME;
        if(vertex) value |= C.SVGA3D_DXFMT_DX_VERTEX_BUFFER;
        if(dx10 ? can.includes("m") : texture && (can.includes("r") || can.includes("d"))) value |= C.SVGA3D_DXFMT_MULTISAMPLE;
        caps.push([index, value]);
    }
    // a buffer is supported as one
    caps.push([C.SVGA3D_DEVCAP_DXFMT_BUFFER, C.SVGA3D_DXFMT_SUPPORTED]);
    return caps;
}

function f32_bits(value)
{
    return new Uint32Array(new Float32Array([value]).buffer)[0];
}

/** SVGA3dPrimitiveType -> D3DPRIMITIVETYPE, and the vertices of n primitives */
export const PRIMITIVES = {
    [C.SVGA3D_PRIMITIVE_TRIANGLELIST]: 4,
    [C.SVGA3D_PRIMITIVE_POINTLIST]: 1,
    [C.SVGA3D_PRIMITIVE_LINELIST]: 2,
    [C.SVGA3D_PRIMITIVE_LINESTRIP]: 3,
    [C.SVGA3D_PRIMITIVE_TRIANGLESTRIP]: 5,
    [C.SVGA3D_PRIMITIVE_TRIANGLEFAN]: 6,
};

/** @return {number} the vertices (or indices) n primitives of a D3DPRIMITIVETYPE take */
export function primitive_vertices(d3d_type, count)
{
    switch(d3d_type)
    {
        case 1: return count;
        case 2: return count * 2;
        case 3: return count + 1;
        case 4: return count * 3;
        default: return count + 2;
    }
}

/** SVGA3dTransformType -> D3DTRANSFORMSTATETYPE */
export function d3d_transform(type)
{
    if(type === C.SVGA3D_TRANSFORM_WORLD) return 256;
    if(type === C.SVGA3D_TRANSFORM_VIEW) return 2;
    if(type === C.SVGA3D_TRANSFORM_PROJECTION) return 3;
    if(type >= C.SVGA3D_TRANSFORM_TEXTURE0 && type <= C.SVGA3D_TRANSFORM_TEXTURE7) return 16 + type - C.SVGA3D_TRANSFORM_TEXTURE0;
    if(type >= C.SVGA3D_TRANSFORM_WORLD1 && type <= C.SVGA3D_TRANSFORM_WORLD3) return 257 + type - C.SVGA3D_TRANSFORM_WORLD1;
    return -1;
}

/** SVGA3dLightType -> D3DLIGHTTYPE (both spot models are D3D's one) */
export function d3d_light_type(type)
{
    return type === C.SVGA3D_LIGHTTYPE_POINT ? 1 : type === C.SVGA3D_LIGHTTYPE_DIRECTIONAL ? 3 : 2;
}

// D3DRENDERSTATETYPE
export const D3DRS = {
    ZENABLE: 7, FILLMODE: 8, SHADEMODE: 9, ZWRITEENABLE: 14, ALPHATESTENABLE: 15, LASTPIXEL: 16,
    SRCBLEND: 19, DESTBLEND: 20, CULLMODE: 22, ZFUNC: 23, ALPHAREF: 24, ALPHAFUNC: 25,
    DITHERENABLE: 26, ALPHABLENDENABLE: 27, FOGENABLE: 28, SPECULARENABLE: 29, FOGCOLOR: 34,
    FOGTABLEMODE: 35, FOGSTART: 36, FOGEND: 37, FOGDENSITY: 38, RANGEFOGENABLE: 48,
    STENCILENABLE: 52, STENCILFAIL: 53, STENCILZFAIL: 54, STENCILPASS: 55, STENCILFUNC: 56,
    STENCILREF: 57, STENCILMASK: 58, STENCILWRITEMASK: 59, TEXTUREFACTOR: 60, WRAP0: 128,
    CLIPPING: 136, LIGHTING: 137, AMBIENT: 139, FOGVERTEXMODE: 140, COLORVERTEX: 141,
    LOCALVIEWER: 142, NORMALIZENORMALS: 143, DIFFUSEMATERIALSOURCE: 145,
    SPECULARMATERIALSOURCE: 146, AMBIENTMATERIALSOURCE: 147, EMISSIVEMATERIALSOURCE: 148,
    VERTEXBLEND: 151, CLIPPLANEENABLE: 152, POINTSIZE: 154, POINTSIZE_MIN: 155,
    POINTSPRITEENABLE: 156, POINTSCALEENABLE: 157, POINTSCALE_A: 158, POINTSCALE_B: 159,
    POINTSCALE_C: 160, MULTISAMPLEANTIALIAS: 161, MULTISAMPLEMASK: 162, POINTSIZE_MAX: 166,
    INDEXEDVERTEXBLENDENABLE: 167, COLORWRITEENABLE: 168, TWEENFACTOR: 170, BLENDOP: 171,
    SCISSORTESTENABLE: 174, SLOPESCALEDEPTHBIAS: 175, ANTIALIASEDLINEENABLE: 176,
    TWOSIDEDSTENCILMODE: 185, CCW_STENCILFAIL: 186, CCW_STENCILZFAIL: 187, CCW_STENCILPASS: 188,
    CCW_STENCILFUNC: 189, COLORWRITEENABLE1: 190, COLORWRITEENABLE2: 191, COLORWRITEENABLE3: 192,
    BLENDFACTOR: 193, SRGBWRITEENABLE: 194, DEPTHBIAS: 195, WRAP8: 198,
    SEPARATEALPHABLENDENABLE: 206, SRCBLENDALPHA: 207, DESTBLENDALPHA: 208, BLENDOPALPHA: 209,
};

/** Render states whose values D3D9 spells the same way: SVGA3D_RS_* -> D3DRS_* */
export const SAME_RENDER_STATES = {
    [C.SVGA3D_RS_ZENABLE]: D3DRS.ZENABLE,
    [C.SVGA3D_RS_ZWRITEENABLE]: D3DRS.ZWRITEENABLE,
    [C.SVGA3D_RS_ALPHATESTENABLE]: D3DRS.ALPHATESTENABLE,
    [C.SVGA3D_RS_DITHERENABLE]: D3DRS.DITHERENABLE,
    [C.SVGA3D_RS_BLENDENABLE]: D3DRS.ALPHABLENDENABLE,
    [C.SVGA3D_RS_FOGENABLE]: D3DRS.FOGENABLE,
    [C.SVGA3D_RS_SPECULARENABLE]: D3DRS.SPECULARENABLE,
    [C.SVGA3D_RS_STENCILENABLE]: D3DRS.STENCILENABLE,
    [C.SVGA3D_RS_LIGHTINGENABLE]: D3DRS.LIGHTING,
    [C.SVGA3D_RS_NORMALIZENORMALS]: D3DRS.NORMALIZENORMALS,
    [C.SVGA3D_RS_POINTSPRITEENABLE]: D3DRS.POINTSPRITEENABLE,
    [C.SVGA3D_RS_POINTSCALEENABLE]: D3DRS.POINTSCALEENABLE,
    [C.SVGA3D_RS_STENCILREF]: D3DRS.STENCILREF,
    [C.SVGA3D_RS_STENCILMASK]: D3DRS.STENCILMASK,
    [C.SVGA3D_RS_STENCILWRITEMASK]: D3DRS.STENCILWRITEMASK,
    [C.SVGA3D_RS_FOGSTART]: D3DRS.FOGSTART,
    [C.SVGA3D_RS_FOGEND]: D3DRS.FOGEND,
    [C.SVGA3D_RS_FOGDENSITY]: D3DRS.FOGDENSITY,
    [C.SVGA3D_RS_POINTSIZE]: D3DRS.POINTSIZE,
    [C.SVGA3D_RS_POINTSIZEMIN]: D3DRS.POINTSIZE_MIN,
    [C.SVGA3D_RS_POINTSIZEMAX]: D3DRS.POINTSIZE_MAX,
    [C.SVGA3D_RS_POINTSCALE_A]: D3DRS.POINTSCALE_A,
    [C.SVGA3D_RS_POINTSCALE_B]: D3DRS.POINTSCALE_B,
    [C.SVGA3D_RS_POINTSCALE_C]: D3DRS.POINTSCALE_C,
    [C.SVGA3D_RS_FOGCOLOR]: D3DRS.FOGCOLOR,
    [C.SVGA3D_RS_AMBIENT]: D3DRS.AMBIENT,
    [C.SVGA3D_RS_CLIPPLANEENABLE]: D3DRS.CLIPPLANEENABLE,
    [C.SVGA3D_RS_SHADEMODE]: D3DRS.SHADEMODE,
    [C.SVGA3D_RS_BLENDEQUATION]: D3DRS.BLENDOP,
    [C.SVGA3D_RS_ZFUNC]: D3DRS.ZFUNC,
    [C.SVGA3D_RS_ALPHAFUNC]: D3DRS.ALPHAFUNC,
    [C.SVGA3D_RS_STENCILFUNC]: D3DRS.STENCILFUNC,
    [C.SVGA3D_RS_STENCILFAIL]: D3DRS.STENCILFAIL,
    [C.SVGA3D_RS_STENCILZFAIL]: D3DRS.STENCILZFAIL,
    [C.SVGA3D_RS_STENCILPASS]: D3DRS.STENCILPASS,
    [C.SVGA3D_RS_COLORWRITEENABLE]: D3DRS.COLORWRITEENABLE,
    [C.SVGA3D_RS_VERTEXMATERIALENABLE]: D3DRS.COLORVERTEX,
    [C.SVGA3D_RS_DIFFUSEMATERIALSOURCE]: D3DRS.DIFFUSEMATERIALSOURCE,
    [C.SVGA3D_RS_SPECULARMATERIALSOURCE]: D3DRS.SPECULARMATERIALSOURCE,
    [C.SVGA3D_RS_AMBIENTMATERIALSOURCE]: D3DRS.AMBIENTMATERIALSOURCE,
    [C.SVGA3D_RS_EMISSIVEMATERIALSOURCE]: D3DRS.EMISSIVEMATERIALSOURCE,
    [C.SVGA3D_RS_TEXTUREFACTOR]: D3DRS.TEXTUREFACTOR,
    [C.SVGA3D_RS_LOCALVIEWER]: D3DRS.LOCALVIEWER,
    [C.SVGA3D_RS_SCISSORTESTENABLE]: D3DRS.SCISSORTESTENABLE,
    [C.SVGA3D_RS_BLENDCOLOR]: D3DRS.BLENDFACTOR,
    [C.SVGA3D_RS_STENCILENABLE2SIDED]: D3DRS.TWOSIDEDSTENCILMODE,
    [C.SVGA3D_RS_CCWSTENCILFUNC]: D3DRS.CCW_STENCILFUNC,
    [C.SVGA3D_RS_CCWSTENCILFAIL]: D3DRS.CCW_STENCILFAIL,
    [C.SVGA3D_RS_CCWSTENCILZFAIL]: D3DRS.CCW_STENCILZFAIL,
    [C.SVGA3D_RS_CCWSTENCILPASS]: D3DRS.CCW_STENCILPASS,
    [C.SVGA3D_RS_VERTEXBLEND]: D3DRS.VERTEXBLEND,
    [C.SVGA3D_RS_SLOPESCALEDEPTHBIAS]: D3DRS.SLOPESCALEDEPTHBIAS,
    [C.SVGA3D_RS_DEPTHBIAS]: D3DRS.DEPTHBIAS,
    [C.SVGA3D_RS_LASTPIXEL]: D3DRS.LASTPIXEL,
    [C.SVGA3D_RS_CLIPPING]: D3DRS.CLIPPING,
    [C.SVGA3D_RS_MULTISAMPLEANTIALIAS]: D3DRS.MULTISAMPLEANTIALIAS,
    [C.SVGA3D_RS_MULTISAMPLEMASK]: D3DRS.MULTISAMPLEMASK,
    [C.SVGA3D_RS_INDEXEDVERTEXBLENDENABLE]: D3DRS.INDEXEDVERTEXBLENDENABLE,
    [C.SVGA3D_RS_TWEENFACTOR]: D3DRS.TWEENFACTOR,
    [C.SVGA3D_RS_ANTIALIASEDLINEENABLE]: D3DRS.ANTIALIASEDLINEENABLE,
    [C.SVGA3D_RS_COLORWRITEENABLE1]: D3DRS.COLORWRITEENABLE1,
    [C.SVGA3D_RS_COLORWRITEENABLE2]: D3DRS.COLORWRITEENABLE2,
    [C.SVGA3D_RS_COLORWRITEENABLE3]: D3DRS.COLORWRITEENABLE3,
    [C.SVGA3D_RS_SEPARATEALPHABLENDENABLE]: D3DRS.SEPARATEALPHABLENDENABLE,
    [C.SVGA3D_RS_BLENDEQUATIONALPHA]: D3DRS.BLENDOPALPHA,
};

/** SVGA3dBlendOp -> D3DBLEND: the same up to SRCALPHASAT; D3D9 has BOTHSRCALPHA in between */
export function d3d_blend(value)
{
    if(value === C.SVGA3D_BLENDOP_BLENDFACTOR) return 14;
    if(value === C.SVGA3D_BLENDOP_INVBLENDFACTOR) return 15;
    return value;
}

// D3DTEXTURESTAGESTATETYPE and D3DSAMPLERSTATETYPE
export const D3DTSS = {
    COLOROP: 1, COLORARG1: 2, COLORARG2: 3, ALPHAOP: 4, ALPHAARG1: 5, ALPHAARG2: 6,
    BUMPENVMAT00: 7, BUMPENVMAT01: 8, BUMPENVMAT10: 9, BUMPENVMAT11: 10, TEXCOORDINDEX: 11,
    BUMPENVLSCALE: 22, BUMPENVLOFFSET: 23, TEXTURETRANSFORMFLAGS: 24, COLORARG0: 26,
    ALPHAARG0: 27, CONSTANT: 32,
};
export const D3DSAMP = {
    ADDRESSU: 1, ADDRESSV: 2, ADDRESSW: 3, BORDERCOLOR: 4, MAGFILTER: 5, MINFILTER: 6,
    MIPFILTER: 7, MIPMAPLODBIAS: 8, MAXMIPLEVEL: 9, MAXANISOTROPY: 10, SRGBTEXTURE: 11,
};

/** SVGA3dTextureCombiner -> D3DTEXTUREOP */
export const TEXTURE_OPS = {
    [C.SVGA3D_TC_DISABLE]: 1, [C.SVGA3D_TC_SELECTARG1]: 2, [C.SVGA3D_TC_SELECTARG2]: 3,
    [C.SVGA3D_TC_MODULATE]: 4, [C.SVGA3D_TC_ADD]: 7, [C.SVGA3D_TC_ADDSIGNED]: 8,
    [C.SVGA3D_TC_SUBTRACT]: 10, [C.SVGA3D_TC_BLENDTEXTUREALPHA]: 13,
    [C.SVGA3D_TC_BLENDDIFFUSEALPHA]: 12, [C.SVGA3D_TC_BLENDCURRENTALPHA]: 16,
    [C.SVGA3D_TC_BLENDFACTORALPHA]: 14, [C.SVGA3D_TC_MODULATE2X]: 5, [C.SVGA3D_TC_MODULATE4X]: 6,
    [C.SVGA3D_TC_DSDT]: 22, [C.SVGA3D_TC_DOTPRODUCT3]: 24, [C.SVGA3D_TC_BLENDTEXTUREALPHAPM]: 15,
    [C.SVGA3D_TC_ADDSIGNED2X]: 9, [C.SVGA3D_TC_ADDSMOOTH]: 11, [C.SVGA3D_TC_PREMODULATE]: 17,
    [C.SVGA3D_TC_MODULATEALPHA_ADDCOLOR]: 18, [C.SVGA3D_TC_MODULATECOLOR_ADDALPHA]: 19,
    [C.SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR]: 20, [C.SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA]: 21,
    [C.SVGA3D_TC_BUMPENVMAPLUMINANCE]: 23, [C.SVGA3D_TC_MULTIPLYADD]: 25, [C.SVGA3D_TC_LERP]: 26,
};

/**
 * SVGA3dTextureArgData plus modifiers -> D3DTA_*: the sources are numbered
 * differently, and SVGA3D's ALPHA and ONE_MINUS bits are D3D's
 * ALPHAREPLICATE and COMPLEMENT the other way round
 */
export function d3d_texture_argument(value)
{
    const source = { [C.SVGA3D_TA_TFACTOR]: 3, [C.SVGA3D_TA_PREVIOUS]: 1, [C.SVGA3D_TA_DIFFUSE]: 0,
        [C.SVGA3D_TA_TEXTURE]: 2, [C.SVGA3D_TA_SPECULAR]: 4, [C.SVGA3D_TA_CONSTANT]: 6 }[value & 0xF];
    return (source === undefined ? 1 : source) |
        (value & C.SVGA3D_TM_ALPHA ? 0x20 : 0) | (value & C.SVGA3D_TM_ONE_MINUS ? 0x10 : 0);
}

/** SVGA3dTexTransformFlags -> D3DTEXTURETRANSFORMFLAGS: a coordinate count */
export function d3d_texture_transform_flags(value)
{
    const count = (value & 1) + (value >> 1 & 1) + (value >> 2 & 1) + (value >> 3 & 1);
    return count | (value & C.SVGA3D_TEX_PROJECTED ? 256 : 0);
}

/** SVGA3D_TEX_ADDRESS_EDGE is D3D's clamp; the rest are numbered alike */
export function d3d_address(value)
{
    return value === C.SVGA3D_TEX_ADDRESS_EDGE ? 3 : value;
}

/** SVGA3dTextureCoordGen -> the D3DTSS_TCI_* bits of TEXCOORDINDEX */
export function d3d_texcoord_generation(value)
{
    return {
        [C.SVGA3D_TEXCOORD_GEN_EYE_POSITION]: 0x20000,
        [C.SVGA3D_TEXCOORD_GEN_EYE_NORMAL]: 0x10000,
        [C.SVGA3D_TEXCOORD_GEN_REFLECTIONVECTOR]: 0x30000,
        [C.SVGA3D_TEXCOORD_GEN_SPHERE]: 0x40000,
    }[value] || 0;
}
                                                                                                                                                                                                                                                                                     source/v64/src/graphics_adapters/vmware_svga/svga_constants.js                                      0000644 0000000 0000000 00000355022 00000000000 022060  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/gen_svga_constants.js from third_party/vmware-svga
// (VMware SVGA II and SVGA3D, GPL-2.0 OR MIT, used under MIT). Do not edit.

// vm_basic_types.h
export const MBYTES_SHIFT = 0x14;

// svga_reg.h
export const SVGA_REG_ENABLE_DISABLE = 0;
export const SVGA_REG_ENABLE_ENABLE = 1;
export const SVGA_REG_ENABLE_HIDE = 2;
export const SVGA_MAX_WIDTH = 0xA00;
export const SVGA_MAX_HEIGHT = 0x640;
export const SVGA_MAX_BITS_PER_PIXEL = 0x20;
export const SVGA_MAX_DEPTH = 0x18;
export const SVGA_MAX_DISPLAYS = 0xA;
export const SVGA_MAX_SCREEN_SIZE = 0x2000;
export const SVGA_SCREEN_ROOT_LIMIT = 0x14000;
export const SVGA_CURSOR_ON_HIDE = 0;
export const SVGA_CURSOR_ON_SHOW = 1;
export const SVGA_CURSOR_ON_REMOVE_FROM_FB = 2;
export const SVGA_CURSOR_ON_RESTORE_TO_FB = 3;
export const SVGA_FB_MAX_TRACEABLE_SIZE = 0x1000000;
export const SVGA_MAX_PSEUDOCOLOR_DEPTH = 8;
export const SVGA_MAX_PSEUDOCOLORS = 0x100;
export const SVGA_NUM_PALETTE_REGS = 0x300;
export const SVGA_MAGIC = 0x900000;
export const SVGA_VERSION_3 = 3;
export const SVGA_ID_3 = 0x90000003;
export const SVGA_VERSION_2 = 2;
export const SVGA_ID_2 = 0x90000002;
export const SVGA_VERSION_1 = 1;
export const SVGA_ID_1 = 0x90000001;
export const SVGA_VERSION_0 = 0;
export const SVGA_ID_0 = 0x90000000;
export const SVGA_ID_INVALID = 0xFFFFFFFF;
export const SVGA_INDEX_PORT = 0;
export const SVGA_VALUE_PORT = 1;
export const SVGA_BIOS_PORT = 2;
export const SVGA_IRQSTATUS_PORT = 8;
export const SVGA_IRQFLAG_ANY_FENCE = 1;
export const SVGA_IRQFLAG_FIFO_PROGRESS = 2;
export const SVGA_IRQFLAG_FENCE_GOAL = 4;
export const SVGA_IRQFLAG_COMMAND_BUFFER = 8;
export const SVGA_IRQFLAG_ERROR = 0x10;
export const SVGA_IRQFLAG_REG_FENCE_GOAL = 0x20;
export const SVGA_IRQFLAG_MOB_FENCE = 0x40;
export const SVGA_IRQFLAG_MAX = 0x80;
export const SVGA_MAX_CURSOR_CMD_BYTES = 0xA000;
export const SVGA_MAX_CURSOR_CMD_DIMENSION = 0x400;
export const SVGA_REG_ID = 0;
export const SVGA_REG_ENABLE = 1;
export const SVGA_REG_WIDTH = 2;
export const SVGA_REG_HEIGHT = 3;
export const SVGA_REG_MAX_WIDTH = 4;
export const SVGA_REG_MAX_HEIGHT = 5;
export const SVGA_REG_DEPTH = 6;
export const SVGA_REG_BITS_PER_PIXEL = 7;
export const SVGA_REG_PSEUDOCOLOR = 8;
export const SVGA_REG_RED_MASK = 9;
export const SVGA_REG_GREEN_MASK = 0xA;
export const SVGA_REG_BLUE_MASK = 0xB;
export const SVGA_REG_BYTES_PER_LINE = 0xC;
export const SVGA_REG_FB_START = 0xD;
export const SVGA_REG_FB_OFFSET = 0xE;
export const SVGA_REG_VRAM_SIZE = 0xF;
export const SVGA_REG_FB_SIZE = 0x10;
export const SVGA_REG_ID_0_TOP = 0x11;
export const SVGA_REG_CAPABILITIES = 0x11;
export const SVGA_REG_MEM_START = 0x12;
export const SVGA_REG_MEM_SIZE = 0x13;
export const SVGA_REG_CONFIG_DONE = 0x14;
export const SVGA_REG_SYNC = 0x15;
export const SVGA_REG_BUSY = 0x16;
export const SVGA_REG_GUEST_ID = 0x17;
export const SVGA_REG_DEAD = 0x18;
export const SVGA_REG_CURSOR_X = 0x19;
export const SVGA_REG_CURSOR_Y = 0x1A;
export const SVGA_REG_CURSOR_ON = 0x1B;
export const SVGA_REG_HOST_BITS_PER_PIXEL = 0x1C;
export const SVGA_REG_SCRATCH_SIZE = 0x1D;
export const SVGA_REG_MEM_REGS = 0x1E;
export const SVGA_REG_NUM_DISPLAYS = 0x1F;
export const SVGA_REG_PITCHLOCK = 0x20;
export const SVGA_REG_IRQMASK = 0x21;
export const SVGA_REG_NUM_GUEST_DISPLAYS = 0x22;
export const SVGA_REG_DISPLAY_ID = 0x23;
export const SVGA_REG_DISPLAY_IS_PRIMARY = 0x24;
export const SVGA_REG_DISPLAY_POSITION_X = 0x25;
export const SVGA_REG_DISPLAY_POSITION_Y = 0x26;
export const SVGA_REG_DISPLAY_WIDTH = 0x27;
export const SVGA_REG_DISPLAY_HEIGHT = 0x28;
export const SVGA_REG_GMR_ID = 0x29;
export const SVGA_REG_GMR_DESCRIPTOR = 0x2A;
export const SVGA_REG_GMR_MAX_IDS = 0x2B;
export const SVGA_REG_GMR_MAX_DESCRIPTOR_LENGTH = 0x2C;
export const SVGA_REG_TRACES = 0x2D;
export const SVGA_REG_GMRS_MAX_PAGES = 0x2E;
export const SVGA_REG_MEMORY_SIZE = 0x2F;
export const SVGA_REG_COMMAND_LOW = 0x30;
export const SVGA_REG_COMMAND_HIGH = 0x31;
export const SVGA_REG_MAX_PRIMARY_MEM = 0x32;
export const SVGA_REG_SUGGESTED_GBOBJECT_MEM_SIZE_KB = 0x33;
export const SVGA_REG_DEV_CAP = 0x34;
export const SVGA_REG_CMD_PREPEND_LOW = 0x35;
export const SVGA_REG_CMD_PREPEND_HIGH = 0x36;
export const SVGA_REG_SCREENTARGET_MAX_WIDTH = 0x37;
export const SVGA_REG_SCREENTARGET_MAX_HEIGHT = 0x38;
export const SVGA_REG_MOB_MAX_SIZE = 0x39;
export const SVGA_REG_BLANK_SCREEN_TARGETS = 0x3A;
export const SVGA_REG_CAP2 = 0x3B;
export const SVGA_REG_DEVEL_CAP = 0x3C;
export const SVGA_REG_GUEST_DRIVER_ID = 0x3D;
export const SVGA_REG_GUEST_DRIVER_VERSION1 = 0x3E;
export const SVGA_REG_GUEST_DRIVER_VERSION2 = 0x3F;
export const SVGA_REG_GUEST_DRIVER_VERSION3 = 0x40;
export const SVGA_REG_CURSOR_MOBID = 0x41;
export const SVGA_REG_CURSOR_MAX_BYTE_SIZE = 0x42;
export const SVGA_REG_CURSOR_MAX_DIMENSION = 0x43;
export const SVGA_REG_FIFO_CAPS = 0x44;
export const SVGA_REG_FENCE = 0x45;
export const SVGA_REG_CURSOR4_ON = 0x46;
export const SVGA_REG_CURSOR4_X = 0x47;
export const SVGA_REG_CURSOR4_Y = 0x48;
export const SVGA_REG_CURSOR4_SCREEN_ID = 0x49;
export const SVGA_REG_CURSOR4_SUBMIT = 0x4A;
export const SVGA_REG_SCREENDMA = 0x4B;
export const SVGA_REG_GBOBJECT_MEM_SIZE_KB = 0x4C;
export const SVGA_REG_REGS_START_HIGH32 = 0x4D;
export const SVGA_REG_REGS_START_LOW32 = 0x4E;
export const SVGA_REG_FB_START_HIGH32 = 0x4F;
export const SVGA_REG_FB_START_LOW32 = 0x50;
export const SVGA_REG_MSHINT = 0x51;
export const SVGA_REG_IRQ_STATUS = 0x52;
export const SVGA_REG_DIRTY_TRACKING = 0x53;
export const SVGA_REG_FENCE_GOAL = 0x54;
export const SVGA_REG_TOP = 0x55;
export const SVGA_PALETTE_BASE = 0x400;
export const SVGA_SCRATCH_BASE = 0x700;
export const SVGA_REG_GUEST_DRIVER_ID_UNKNOWN = 0;
export const SVGA_REG_GUEST_DRIVER_ID_WDDM = 1;
export const SVGA_REG_GUEST_DRIVER_ID_LINUX = 2;
export const SVGA_REG_GUEST_DRIVER_ID_MAX = 3;
export const SVGA_REG_MSHINT_DISABLED = 0;
export const SVGA_REG_MSHINT_FULL = 1;
export const SVGA_REG_MSHINT_RESOLVED = 2;
export const SVGA_REG_DIRTY_TRACKING_PER_IMAGE = 0;
export const SVGA_REG_DIRTY_TRACKING_PER_SURFACE = 1;
export const SVGA_GMR_NULL = 0xFFFFFFFF;
export const SVGA_GMR_FRAMEBUFFER = 0xFFFFFFFE;
export const SVGA_CB_MAX_SIZE_DEFAULT = 0x80000;
export const SVGA_CB_MAX_SIZE_4MB = 0x400000;
export const SVGA_CB_MAX_SIZE = 0x400000;
export const SVGA_CB_MAX_QUEUED_PER_CONTEXT = 0x20;
export const SVGA_CB_MAX_COMMAND_SIZE = 0x8000;
export const SVGA_CB_CONTEXT_MASK = 0x3F;
export const SVGA_CB_CONTEXT_DEVICE = 0x3F;
export const SVGA_CB_CONTEXT_0 = 0;
export const SVGA_CB_CONTEXT_1 = 1;
export const SVGA_CB_CONTEXT_MAX = 2;
export const SVGA_CB_STATUS_NONE = 0;
export const SVGA_CB_STATUS_COMPLETED = 1;
export const SVGA_CB_STATUS_QUEUE_FULL = 2;
export const SVGA_CB_STATUS_COMMAND_ERROR = 3;
export const SVGA_CB_STATUS_CB_HEADER_ERROR = 4;
export const SVGA_CB_STATUS_PREEMPTED = 5;
export const SVGA_CB_STATUS_SUBMISSION_ERROR = 6;
export const SVGA_CB_STATUS_PARTIAL_COMPLETE = 7;
export const SVGA_CB_FLAG_NONE = 0;
export const SVGA_CB_FLAG_NO_IRQ = 1;
export const SVGA_CB_FLAG_DX_CONTEXT = 2;
export const SVGA_CB_FLAG_MOB = 4;
export const SVGA_DC_CMD_NOP = 0;
export const SVGA_DC_CMD_START_STOP_CONTEXT = 1;
export const SVGA_DC_CMD_PREEMPT = 2;
export const SVGA_DC_CMD_START_QUEUE = 3;
export const SVGA_DC_CMD_ASYNC_STOP_QUEUE = 4;
export const SVGA_DC_CMD_EMPTY_CONTEXT_QUEUE = 5;
export const SVGA_DC_CMD_MAX = 6;
export const SVGA_CAP_NONE = 0;
export const SVGA_CAP_RECT_COPY = 2;
export const SVGA_CAP_CURSOR = 0x20;
export const SVGA_CAP_CURSOR_BYPASS = 0x40;
export const SVGA_CAP_CURSOR_BYPASS_2 = 0x80;
export const SVGA_CAP_8BIT_EMULATION = 0x100;
export const SVGA_CAP_ALPHA_CURSOR = 0x200;
export const SVGA_CAP_3D = 0x4000;
export const SVGA_CAP_EXTENDED_FIFO = 0x8000;
export const SVGA_CAP_MULTIMON = 0x10000;
export const SVGA_CAP_PITCHLOCK = 0x20000;
export const SVGA_CAP_IRQMASK = 0x40000;
export const SVGA_CAP_DISPLAY_TOPOLOGY = 0x80000;
export const SVGA_CAP_GMR = 0x100000;
export const SVGA_CAP_TRACES = 0x200000;
export const SVGA_CAP_GMR2 = 0x400000;
export const SVGA_CAP_SCREEN_OBJECT_2 = 0x800000;
export const SVGA_CAP_COMMAND_BUFFERS = 0x1000000;
export const SVGA_CAP_DEAD1 = 0x2000000;
export const SVGA_CAP_CMD_BUFFERS_2 = 0x4000000;
export const SVGA_CAP_GBOBJECTS = 0x8000000;
export const SVGA_CAP_DX = 0x10000000;
export const SVGA_CAP_HP_CMD_QUEUE = 0x20000000;
export const SVGA_CAP_NO_BB_RESTRICTION = 0x40000000;
export const SVGA_CAP_CAP2_REGISTER = 0x80000000;
export const SVGA_CAP2_NONE = 0;
export const SVGA_CAP2_GROW_OTABLE = 1;
export const SVGA_CAP2_INTRA_SURFACE_COPY = 2;
export const SVGA_CAP2_DX2 = 4;
export const SVGA_CAP2_GB_MEMSIZE_2 = 8;
export const SVGA_CAP2_SCREENDMA_REG = 0x10;
export const SVGA_CAP2_OTABLE_PTDEPTH_2 = 0x20;
export const SVGA_CAP2_NON_MS_TO_MS_STRETCHBLT = 0x40;
export const SVGA_CAP2_CURSOR_MOB = 0x80;
export const SVGA_CAP2_MSHINT = 0x100;
export const SVGA_CAP2_CB_MAX_SIZE_4MB = 0x200;
export const SVGA_CAP2_DX3 = 0x400;
export const SVGA_CAP2_FRAME_TYPE = 0x800;
export const SVGA_CAP2_COTABLE_COPY = 0x1000;
export const SVGA_CAP2_TRACE_FULL_FB = 0x2000;
export const SVGA_CAP2_EXTRA_REGS = 0x4000;
export const SVGA_CAP2_LO_STAGING = 0x8000;
export const SVGA_CAP2_VIDEO_BLT = 0x10000;
export const SVGA_CAP2_MOBFMT_16K_PT64 = 0x20000;
export const SVGA_CAP2_MOB_FENCE_WITH_FLAGS = 0x40000;
export const SVGA_CAP2_DIRTY_TRACKING_REG = 0x80000;
export const SVGA_CAP2_CURSOR_MOB_ALPHA3D = 0x100000;
export const SVGA_CAP2_RESERVED = 0x80000000;
export const SVGABackdoorCapDeviceCaps = 0;
export const SVGABackdoorCapFifoCaps = 1;
export const SVGABackdoorCap3dHWVersion = 2;
export const SVGABackdoorCapDeviceCaps2 = 3;
export const SVGABackdoorCapDevelCaps = 4;
export const SVGABackdoorCapDevCaps = 5;
export const SVGABackdoorDevelRenderer = 6;
export const SVGABackdoorDevelUsingISB = 7;
export const SVGABackdoorCapMax = 8;
export const SVGA_FIFO_MIN = 0;
export const SVGA_FIFO_MAX = 1;
export const SVGA_FIFO_NEXT_CMD = 2;
export const SVGA_FIFO_STOP = 3;
export const SVGA_FIFO_CAPABILITIES = 4;
export const SVGA_FIFO_FLAGS = 5;
export const SVGA_FIFO_FENCE = 6;
export const SVGA_FIFO_3D_HWVERSION = 7;
export const SVGA_FIFO_PITCHLOCK = 8;
export const SVGA_FIFO_CURSOR_ON = 9;
export const SVGA_FIFO_CURSOR_X = 0xA;
export const SVGA_FIFO_CURSOR_Y = 0xB;
export const SVGA_FIFO_CURSOR_COUNT = 0xC;
export const SVGA_FIFO_CURSOR_LAST_UPDATED = 0xD;
export const SVGA_FIFO_RESERVED = 0xE;
export const SVGA_FIFO_CURSOR_SCREEN_ID = 0xF;
export const SVGA_FIFO_DEAD = 0x10;
export const SVGA_FIFO_3D_HWVERSION_REVISED = 0x11;
export const SVGA_FIFO_3D_CAPS = 0x20;
export const SVGA_FIFO_3D_CAPS_LAST = 0x11F;
export const SVGA_FIFO_GUEST_3D_HWVERSION = 0x120;
export const SVGA_FIFO_FENCE_GOAL = 0x121;
export const SVGA_FIFO_BUSY = 0x122;
export const SVGA_FIFO_NUM_REGS = 0x123;
export const SVGA_FIFO_3D_CAPS_SIZE = 0x100;
export const SVGA3D_FIFO_CAPS_RECORD_DEVCAPS = 0x100;
export const SVGA_FIFO_EXTENDED_MANDATORY_REGS = 0x120;
export const SVGA_FIFO_CAP_NONE = 0;
export const SVGA_FIFO_CAP_FENCE = 1;
export const SVGA_FIFO_CAP_ACCELFRONT = 2;
export const SVGA_FIFO_CAP_PITCHLOCK = 4;
export const SVGA_FIFO_CAP_VIDEO = 8;
export const SVGA_FIFO_CAP_CURSOR_BYPASS_3 = 0x10;
export const SVGA_FIFO_CAP_ESCAPE = 0x20;
export const SVGA_FIFO_CAP_RESERVE = 0x40;
export const SVGA_FIFO_CAP_SCREEN_OBJECT = 0x80;
export const SVGA_FIFO_CAP_GMR2 = 0x100;
export const SVGA_FIFO_CAP_3D_HWVERSION_REVISED = 0x100;
export const SVGA_FIFO_CAP_SCREEN_OBJECT_2 = 0x200;
export const SVGA_FIFO_CAP_DEAD = 0x400;
export const SVGA_FIFO_FLAG_NONE = 0;
export const SVGA_FIFO_FLAG_ACCELFRONT = 1;
export const SVGA_FIFO_FLAG_RESERVED = 0x80000000;
export const SVGA_FIFO_RESERVED_UNKNOWN = 0xFFFFFFFF;
export const SVGA_SCREENDMA_REG_UNDEFINED = 0;
export const SVGA_SCREENDMA_REG_NOT_PRESENT = 1;
export const SVGA_SCREENDMA_REG_PRESENT = 2;
export const SVGA_SCREENDMA_REG_MAX = 3;
export const SVGA_NUM_OVERLAY_UNITS = 0x20;
export const SVGA_VIDEO_FLAG_COLORKEY = 1;
export const SVGA_VIDEO_ENABLED = 0;
export const SVGA_VIDEO_FLAGS = 1;
export const SVGA_VIDEO_DATA_OFFSET = 2;
export const SVGA_VIDEO_FORMAT = 3;
export const SVGA_VIDEO_COLORKEY = 4;
export const SVGA_VIDEO_SIZE = 5;
export const SVGA_VIDEO_WIDTH = 6;
export const SVGA_VIDEO_HEIGHT = 7;
export const SVGA_VIDEO_SRC_X = 8;
export const SVGA_VIDEO_SRC_Y = 9;
export const SVGA_VIDEO_SRC_WIDTH = 0xA;
export const SVGA_VIDEO_SRC_HEIGHT = 0xB;
export const SVGA_VIDEO_DST_X = 0xC;
export const SVGA_VIDEO_DST_Y = 0xD;
export const SVGA_VIDEO_DST_WIDTH = 0xE;
export const SVGA_VIDEO_DST_HEIGHT = 0xF;
export const SVGA_VIDEO_PITCH_1 = 0x10;
export const SVGA_VIDEO_PITCH_2 = 0x11;
export const SVGA_VIDEO_PITCH_3 = 0x12;
export const SVGA_VIDEO_DATA_GMRID = 0x13;
export const SVGA_VIDEO_DST_SCREEN_ID = 0x14;
export const SVGA_VIDEO_NUM_REGS = 0x15;
export const SVGA_INVALID_DISPLAY_ID = 0xFFFFFFFF;
export const SVGA_SCREEN_MUST_BE_SET = 1;
export const SVGA_SCREEN_HAS_ROOT = 1;
export const SVGA_SCREEN_IS_PRIMARY = 2;
export const SVGA_SCREEN_FULLSCREEN_HINT = 4;
export const SVGA_SCREEN_DEACTIVATE = 8;
export const SVGA_SCREEN_BLANKING = 0x10;
export const SVGA_CMD_INVALID_CMD = 0;
export const SVGA_CMD_UPDATE = 1;
export const SVGA_CMD_RECT_COPY = 3;
export const SVGA_CMD_RECT_ROP_COPY = 0xE;
export const SVGA_CMD_DEFINE_CURSOR = 0x13;
export const SVGA_CMD_DEFINE_ALPHA_CURSOR = 0x16;
export const SVGA_CMD_UPDATE_VERBOSE = 0x19;
export const SVGA_CMD_FRONT_ROP_FILL = 0x1D;
export const SVGA_CMD_FENCE = 0x1E;
export const SVGA_CMD_ESCAPE = 0x21;
export const SVGA_CMD_DEFINE_SCREEN = 0x22;
export const SVGA_CMD_DESTROY_SCREEN = 0x23;
export const SVGA_CMD_DEFINE_GMRFB = 0x24;
export const SVGA_CMD_BLIT_GMRFB_TO_SCREEN = 0x25;
export const SVGA_CMD_BLIT_SCREEN_TO_GMRFB = 0x26;
export const SVGA_CMD_ANNOTATION_FILL = 0x27;
export const SVGA_CMD_ANNOTATION_COPY = 0x28;
export const SVGA_CMD_DEFINE_GMR2 = 0x29;
export const SVGA_CMD_REMAP_GMR2 = 0x2A;
export const SVGA_CMD_DEAD = 0x2B;
export const SVGA_CMD_DEAD_2 = 0x2C;
export const SVGA_CMD_NOP = 0x2D;
export const SVGA_CMD_NOP_ERROR = 0x2E;
export const SVGA_CMD_MAX = 0x2F;
export const SVGA_CMD_MAX_DATASIZE = 0x40000;
export const SVGA_CMD_MAX_ARGS = 0x40;
export const SVGA_COLOR_CURSOR = 0;
export const SVGA_ALPHA_CURSOR = 1;
export const SVGA_ALPHA3D_CURSOR = 2;
export const SVGA_REMAP_GMR2_PPN32 = 0;
export const SVGA_REMAP_GMR2_VIA_GMR = 1;
export const SVGA_REMAP_GMR2_PPN64 = 2;
export const SVGA_REMAP_GMR2_SINGLE_PPN = 4;
export const SVGA_VRAM_MIN_SIZE = 0x12C000;
export const SVGA_VRAM_MIN_SIZE_3D = 0x1000000;
export const SVGA_VRAM_MAX_SIZE = 0x8000000;
export const SVGA_MEMORY_SIZE_MAX = 0x40000000;
export const SVGA_FIFO_SIZE_MAX = 0x200000;
export const SVGA_GRAPHICS_MEMORY_KB_MIN = 0x8000;
export const SVGA_GRAPHICS_MEMORY_KB_MAX_2GB = 0x200000;
export const SVGA_GRAPHICS_MEMORY_KB_MAX_3GB = 0x300000;
export const SVGA_GRAPHICS_MEMORY_KB_MAX_4GB = 0x400000;
export const SVGA_GRAPHICS_MEMORY_KB_MAX_8GB = 0x800000;
export const SVGA_GRAPHICS_MEMORY_KB_DEFAULT = 0x40000;
export const SVGA_VRAM_SIZE_W2K = 0x4000000;
export const SVGA_VRAM_SIZE = 0x1000000;
export const SVGA_VRAM_SIZE_3D = 0x8000000;
export const SVGA_FIFO_SIZE = 0x200000;
export const SVGA_FIFO_SIZE_3D = 0x200000;
export const SVGA_MEMORY_SIZE_DEFAULT = 0x30000000;
export const SVGA_FIFO_SIZE_GBOBJECTS = 0x40000;
export const SVGA_VRAM_SIZE_GBOBJECTS = 0x400000;

// svga_escape.h
export const SVGA_ESCAPE_NSID_VMWARE = 0;
export const SVGA_ESCAPE_NSID_DEVEL = 0xFFFFFFFF;
export const SVGA_ESCAPE_VMWARE_MAJOR_MASK = 0xFFFF0000;
export const SVGA_ESCAPE_VMWARE_HINT = 0x30000;
export const SVGA_ESCAPE_VMWARE_HINT_FULLSCREEN = 0x30001;

// svga_overlay.h
export const VMWARE_FOURCC_YV12 = 0x32315659;
export const VMWARE_FOURCC_YUY2 = 0x32595559;
export const VMWARE_FOURCC_UYVY = 0x59565955;
export const SVGA_OVERLAY_FORMAT_INVALID = 0;
export const SVGA_OVERLAY_FORMAT_YV12 = 0x32315659;
export const SVGA_OVERLAY_FORMAT_YUY2 = 0x32595559;
export const SVGA_OVERLAY_FORMAT_UYVY = 0x59565955;
export const SVGA_VIDEO_COLORKEY_MASK = 0xFFFFFF;
export const SVGA_ESCAPE_VMWARE_VIDEO = 0x20000;
export const SVGA_ESCAPE_VMWARE_VIDEO_SET_REGS = 0x20001;
export const SVGA_ESCAPE_VMWARE_VIDEO_FLUSH = 0x20002;

// svga3d_limits.h
export const SVGA3D_HB_MAX_CONTEXT_IDS = 0x100;
export const SVGA3D_HB_MAX_SURFACE_IDS = 0x8000;
export const SVGA3D_DX_MAX_RENDER_TARGETS = 8;
export const SVGA3D_DX11_MAX_UAVIEWS = 8;
export const SVGA3D_DX11_1_MAX_UAVIEWS = 0x40;
export const SVGA3D_MAX_UAVIEWS = 0x40;
export const SVGA3D_DX11_MAX_SIMULTANEOUS_RTUAV = 8;
export const SVGA3D_DX11_1_MAX_SIMULTANEOUS_RTUAV = 0x40;
export const SVGA3D_MAX_SIMULTANEOUS_RTUAV = 0x40;
export const SVGA3D_HB_MAX_SURFACE_SIZE = 0x8000000;
export const SVGA3D_MAX_SHADERIDS = 0x1388;
export const SVGA3D_MAX_SIMULTANEOUS_SHADERS = 0x4E20;
export const SVGA3D_NUM_TEXTURE_UNITS = 0x20;
export const SVGA3D_NUM_LIGHTS = 8;
export const SVGA3D_MAX_VIDEOPROCESSOR_SAMPLERS = 0x20;
export const SVGA3D_MAX_SHADER_MEMORY_BYTES = 0x800000;
export const SVGA3D_MAX_SHADER_THREAD_GROUPS = 0xFFFF;
export const SVGA3D_MAX_CLIP_PLANES = 6;
export const SVGA3D_MAX_TEXTURE_COORDS = 8;
export const SVGA3D_MAX_SURFACE_FACES = 6;
export const SVGA3D_SM4_MAX_SURFACE_ARRAYSIZE = 0x200;
export const SVGA3D_SM5_MAX_SURFACE_ARRAYSIZE = 0x800;
export const SVGA3D_MAX_SURFACE_ARRAYSIZE = 0x800;
export const SVGA3D_MAX_VERTEX_ARRAYS = 0x20;
export const SVGA3D_MAX_DRAW_PRIMITIVE_RANGES = 0x20;
export const SVGA3D_MAX_SAMPLES = 8;

// svga3d_types.h
export const SVGA3D_INVALID_ID = 0xFFFFFFFF;
export const SVGA3D_RESERVED_ID = 0xFFFFFFFE;
export const SVGA3D_RESOURCE_TYPE_MIN = 1;
export const SVGA3D_RESOURCE_BUFFER = 1;
export const SVGA3D_RESOURCE_TEXTURE1D = 2;
export const SVGA3D_RESOURCE_TEXTURE2D = 3;
export const SVGA3D_RESOURCE_TEXTURE3D = 4;
export const SVGA3D_RESOURCE_TEXTURECUBE = 5;
export const SVGA3D_RESOURCE_TYPE_DX10_MAX = 6;
export const SVGA3D_RESOURCE_BUFFEREX = 6;
export const SVGA3D_RESOURCE_TYPE_MAX = 7;
export const SVGA3D_FORMAT_INVALID = 0;
export const SVGA3D_X8R8G8B8 = 1;
export const SVGA3D_FORMAT_MIN = 1;
export const SVGA3D_A8R8G8B8 = 2;
export const SVGA3D_R5G6B5 = 3;
export const SVGA3D_X1R5G5B5 = 4;
export const SVGA3D_A1R5G5B5 = 5;
export const SVGA3D_A4R4G4B4 = 6;
export const SVGA3D_Z_D32 = 7;
export const SVGA3D_Z_D16 = 8;
export const SVGA3D_Z_D24S8 = 9;
export const SVGA3D_Z_D15S1 = 0xA;
export const SVGA3D_LUMINANCE8 = 0xB;
export const SVGA3D_LUMINANCE4_ALPHA4 = 0xC;
export const SVGA3D_LUMINANCE16 = 0xD;
export const SVGA3D_LUMINANCE8_ALPHA8 = 0xE;
export const SVGA3D_DXT1 = 0xF;
export const SVGA3D_DXT2 = 0x10;
export const SVGA3D_DXT3 = 0x11;
export const SVGA3D_DXT4 = 0x12;
export const SVGA3D_DXT5 = 0x13;
export const SVGA3D_BUMPU8V8 = 0x14;
export const SVGA3D_BUMPL6V5U5 = 0x15;
export const SVGA3D_BUMPX8L8V8U8 = 0x16;
export const SVGA3D_FORMAT_DEAD1 = 0x17;
export const SVGA3D_ARGB_S10E5 = 0x18;
export const SVGA3D_ARGB_S23E8 = 0x19;
export const SVGA3D_A2R10G10B10 = 0x1A;
export const SVGA3D_V8U8 = 0x1B;
export const SVGA3D_Q8W8V8U8 = 0x1C;
export const SVGA3D_CxV8U8 = 0x1D;
export const SVGA3D_X8L8V8U8 = 0x1E;
export const SVGA3D_A2W10V10U10 = 0x1F;
export const SVGA3D_ALPHA8 = 0x20;
export const SVGA3D_R_S10E5 = 0x21;
export const SVGA3D_R_S23E8 = 0x22;
export const SVGA3D_RG_S10E5 = 0x23;
export const SVGA3D_RG_S23E8 = 0x24;
export const SVGA3D_BUFFER = 0x25;
export const SVGA3D_Z_D24X8 = 0x26;
export const SVGA3D_V16U16 = 0x27;
export const SVGA3D_G16R16 = 0x28;
export const SVGA3D_A16B16G16R16 = 0x29;
export const SVGA3D_UYVY = 0x2A;
export const SVGA3D_YUY2 = 0x2B;
export const SVGA3D_NV12 = 0x2C;
export const SVGA3D_FORMAT_DEAD2 = 0x2D;
export const SVGA3D_R32G32B32A32_TYPELESS = 0x2E;
export const SVGA3D_R32G32B32A32_UINT = 0x2F;
export const SVGA3D_R32G32B32A32_SINT = 0x30;
export const SVGA3D_R32G32B32_TYPELESS = 0x31;
export const SVGA3D_R32G32B32_FLOAT = 0x32;
export const SVGA3D_R32G32B32_UINT = 0x33;
export const SVGA3D_R32G32B32_SINT = 0x34;
export const SVGA3D_R16G16B16A16_TYPELESS = 0x35;
export const SVGA3D_R16G16B16A16_UINT = 0x36;
export const SVGA3D_R16G16B16A16_SNORM = 0x37;
export const SVGA3D_R16G16B16A16_SINT = 0x38;
export const SVGA3D_R32G32_TYPELESS = 0x39;
export const SVGA3D_R32G32_UINT = 0x3A;
export const SVGA3D_R32G32_SINT = 0x3B;
export const SVGA3D_R32G8X24_TYPELESS = 0x3C;
export const SVGA3D_D32_FLOAT_S8X24_UINT = 0x3D;
export const SVGA3D_R32_FLOAT_X8X24 = 0x3E;
export const SVGA3D_X32_G8X24_UINT = 0x3F;
export const SVGA3D_R10G10B10A2_TYPELESS = 0x40;
export const SVGA3D_R10G10B10A2_UINT = 0x41;
export const SVGA3D_R11G11B10_FLOAT = 0x42;
export const SVGA3D_R8G8B8A8_TYPELESS = 0x43;
export const SVGA3D_R8G8B8A8_UNORM = 0x44;
export const SVGA3D_R8G8B8A8_UNORM_SRGB = 0x45;
export const SVGA3D_R8G8B8A8_UINT = 0x46;
export const SVGA3D_R8G8B8A8_SINT = 0x47;
export const SVGA3D_R16G16_TYPELESS = 0x48;
export const SVGA3D_R16G16_UINT = 0x49;
export const SVGA3D_R16G16_SINT = 0x4A;
export const SVGA3D_R32_TYPELESS = 0x4B;
export const SVGA3D_D32_FLOAT = 0x4C;
export const SVGA3D_R32_UINT = 0x4D;
export const SVGA3D_R32_SINT = 0x4E;
export const SVGA3D_R24G8_TYPELESS = 0x4F;
export const SVGA3D_D24_UNORM_S8_UINT = 0x50;
export const SVGA3D_R24_UNORM_X8 = 0x51;
export const SVGA3D_X24_G8_UINT = 0x52;
export const SVGA3D_R8G8_TYPELESS = 0x53;
export const SVGA3D_R8G8_UNORM = 0x54;
export const SVGA3D_R8G8_UINT = 0x55;
export const SVGA3D_R8G8_SINT = 0x56;
export const SVGA3D_R16_TYPELESS = 0x57;
export const SVGA3D_R16_UNORM = 0x58;
export const SVGA3D_R16_UINT = 0x59;
export const SVGA3D_R16_SNORM = 0x5A;
export const SVGA3D_R16_SINT = 0x5B;
export const SVGA3D_R8_TYPELESS = 0x5C;
export const SVGA3D_R8_UNORM = 0x5D;
export const SVGA3D_R8_UINT = 0x5E;
export const SVGA3D_R8_SNORM = 0x5F;
export const SVGA3D_R8_SINT = 0x60;
export const SVGA3D_P8 = 0x61;
export const SVGA3D_R9G9B9E5_SHAREDEXP = 0x62;
export const SVGA3D_R8G8_B8G8_UNORM = 0x63;
export const SVGA3D_G8R8_G8B8_UNORM = 0x64;
export const SVGA3D_BC1_TYPELESS = 0x65;
export const SVGA3D_BC1_UNORM_SRGB = 0x66;
export const SVGA3D_BC2_TYPELESS = 0x67;
export const SVGA3D_BC2_UNORM_SRGB = 0x68;
export const SVGA3D_BC3_TYPELESS = 0x69;
export const SVGA3D_BC3_UNORM_SRGB = 0x6A;
export const SVGA3D_BC4_TYPELESS = 0x6B;
export const SVGA3D_ATI1 = 0x6C;
export const SVGA3D_BC4_SNORM = 0x6D;
export const SVGA3D_BC5_TYPELESS = 0x6E;
export const SVGA3D_ATI2 = 0x6F;
export const SVGA3D_BC5_SNORM = 0x70;
export const SVGA3D_R10G10B10_XR_BIAS_A2_UNORM = 0x71;
export const SVGA3D_B8G8R8A8_TYPELESS = 0x72;
export const SVGA3D_B8G8R8A8_UNORM_SRGB = 0x73;
export const SVGA3D_B8G8R8X8_TYPELESS = 0x74;
export const SVGA3D_B8G8R8X8_UNORM_SRGB = 0x75;
export const SVGA3D_Z_DF16 = 0x76;
export const SVGA3D_Z_DF24 = 0x77;
export const SVGA3D_Z_D24S8_INT = 0x78;
export const SVGA3D_YV12 = 0x79;
export const SVGA3D_R32G32B32A32_FLOAT = 0x7A;
export const SVGA3D_R16G16B16A16_FLOAT = 0x7B;
export const SVGA3D_R16G16B16A16_UNORM = 0x7C;
export const SVGA3D_R32G32_FLOAT = 0x7D;
export const SVGA3D_R10G10B10A2_UNORM = 0x7E;
export const SVGA3D_R8G8B8A8_SNORM = 0x7F;
export const SVGA3D_R16G16_FLOAT = 0x80;
export const SVGA3D_R16G16_UNORM = 0x81;
export const SVGA3D_R16G16_SNORM = 0x82;
export const SVGA3D_R32_FLOAT = 0x83;
export const SVGA3D_R8G8_SNORM = 0x84;
export const SVGA3D_R16_FLOAT = 0x85;
export const SVGA3D_D16_UNORM = 0x86;
export const SVGA3D_A8_UNORM = 0x87;
export const SVGA3D_BC1_UNORM = 0x88;
export const SVGA3D_BC2_UNORM = 0x89;
export const SVGA3D_BC3_UNORM = 0x8A;
export const SVGA3D_B5G6R5_UNORM = 0x8B;
export const SVGA3D_B5G5R5A1_UNORM = 0x8C;
export const SVGA3D_B8G8R8A8_UNORM = 0x8D;
export const SVGA3D_B8G8R8X8_UNORM = 0x8E;
export const SVGA3D_BC4_UNORM = 0x8F;
export const SVGA3D_BC5_UNORM = 0x90;
export const SVGA3D_B4G4R4A4_UNORM = 0x91;
export const SVGA3D_BC6H_TYPELESS = 0x92;
export const SVGA3D_BC6H_UF16 = 0x93;
export const SVGA3D_BC6H_SF16 = 0x94;
export const SVGA3D_BC7_TYPELESS = 0x95;
export const SVGA3D_BC7_UNORM = 0x96;
export const SVGA3D_BC7_UNORM_SRGB = 0x97;
export const SVGA3D_AYUV = 0x98;
export const SVGA3D_R11G11B10_TYPELESS = 0x99;
export const SVGA3D_FORMAT_MAX = 0x9A;
export const SVGA3D_SURFACE_CUBEMAP = 1;
export const SVGA3D_SURFACE_HINT_STATIC = 2;
export const SVGA3D_SURFACE_HINT_DYNAMIC = 4;
export const SVGA3D_SURFACE_HINT_INDEXBUFFER = 8;
export const SVGA3D_SURFACE_HINT_VERTEXBUFFER = 0x10;
export const SVGA3D_SURFACE_HINT_TEXTURE = 0x20;
export const SVGA3D_SURFACE_HINT_RENDERTARGET = 0x40;
export const SVGA3D_SURFACE_HINT_DEPTHSTENCIL = 0x80;
export const SVGA3D_SURFACE_HINT_WRITEONLY = 0x100;
export const SVGA3D_SURFACE_DEAD2 = 0x200;
export const SVGA3D_SURFACE_AUTOGENMIPMAPS = 0x400;
export const SVGA3D_SURFACE_DEAD1 = 0x800;
export const SVGA3D_SURFACE_MOB_PITCH = 0x1000;
export const SVGA3D_SURFACE_INACTIVE = 0x2000;
export const SVGA3D_SURFACE_HINT_RT_LOCKABLE = 0x4000;
export const SVGA3D_SURFACE_VOLUME = 0x8000;
export const SVGA3D_SURFACE_SCREENTARGET = 0x10000;
export const SVGA3D_SURFACE_ALIGN16 = 0x20000;
export const SVGA3D_SURFACE_1D = 0x40000;
export const SVGA3D_SURFACE_ARRAY = 0x80000;
export const SVGA3D_SURFACE_BIND_VERTEX_BUFFER = 0x100000;
export const SVGA3D_SURFACE_BIND_INDEX_BUFFER = 0x200000;
export const SVGA3D_SURFACE_BIND_CONSTANT_BUFFER = 0x400000;
export const SVGA3D_SURFACE_BIND_SHADER_RESOURCE = 0x800000;
export const SVGA3D_SURFACE_BIND_RENDER_TARGET = 0x1000000;
export const SVGA3D_SURFACE_BIND_DEPTH_STENCIL = 0x2000000;
export const SVGA3D_SURFACE_BIND_STREAM_OUTPUT = 0x4000000;
export const SVGA3D_SURFACE_STAGING_UPLOAD = 0x8000000;
export const SVGA3D_SURFACE_STAGING_DOWNLOAD = 0x10000000;
export const SVGA3D_SURFACE_HINT_INDIRECT_UPDATE = 0x20000000;
export const SVGA3D_SURFACE_TRANSFER_FROM_BUFFER = 0x40000000;
export const SVGA3D_SURFACE_RESERVED1 = 0x80000000;
export const SVGA3D_SURFACE_MULTISAMPLE = 0x100000000;
export const SVGA3D_SURFACE_BIND_UAVIEW = 0x200000000;
export const SVGA3D_SURFACE_TRANSFER_TO_BUFFER = 0x400000000;
export const SVGA3D_SURFACE_BIND_LOGICOPS = 0x800000000;
export const SVGA3D_SURFACE_BIND_RAW_VIEWS = 0x1000000000;
export const SVGA3D_SURFACE_BUFFER_STRUCTURED = 0x2000000000;
export const SVGA3D_SURFACE_DRAWINDIRECT_ARGS = 0x4000000000;
export const SVGA3D_SURFACE_RESOURCE_CLAMP = 0x8000000000;
export const SVGA3D_SURFACE_STAGING_COPY = 0x10000000000;
export const SVGA3D_SURFACE_FLAG_MAX = 0x100000000000;
export const SVGA3D_SURFACE_HB_PRESENT_DISALLOWED_MASK = 0x10100040000;
export const SVGA3D_SURFACE_BASICOPS_DISALLOWED_MASK = 0x100048401;
export const SVGA3D_SURFACE_BUFFER_DISALLOWED_MASK = 0x81000C9601;
export const SVGA3D_SURFACE_MULTISAMPLE_DISALLOWED_MASK = 0x17E40059401;
export const SVGA3D_SURFACE_DX_ONLY_MASK = 0x45C000000;
export const SVGA3D_SURFACE_LOGICOPS_DISALLOWED_MASK = 0x1F746748601;
export const SVGA3D_SURFACE_SM5_MASK = 0xF200000000;
export const SVGA3D_BUFFER_STRUCTURED_STRIDE_MAX = 0x800;
export const SVGA3DFORMAT_OP_TEXTURE = 1;
export const SVGA3DFORMAT_OP_VOLUMETEXTURE = 2;
export const SVGA3DFORMAT_OP_CUBETEXTURE = 4;
export const SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET = 8;
export const SVGA3DFORMAT_OP_SAME_FORMAT_RENDERTARGET = 0x10;
export const SVGA3DFORMAT_OP_ZSTENCIL = 0x40;
export const SVGA3DFORMAT_OP_ZSTENCIL_WITH_ARBITRARY_COLOR_DEPTH = 0x80;
export const SVGA3DFORMAT_OP_SAME_FORMAT_UP_TO_ALPHA_RENDERTARGET = 0x100;
export const SVGA3DFORMAT_OP_DISPLAYMODE = 0x400;
export const SVGA3DFORMAT_OP_3DACCELERATION = 0x800;
export const SVGA3DFORMAT_OP_PIXELSIZE = 0x1000;
export const SVGA3DFORMAT_OP_CONVERT_TO_ARGB = 0x2000;
export const SVGA3DFORMAT_OP_OFFSCREENPLAIN = 0x4000;
export const SVGA3DFORMAT_OP_SRGBREAD = 0x8000;
export const SVGA3DFORMAT_OP_BUMPMAP = 0x10000;
export const SVGA3DFORMAT_OP_DMAP = 0x20000;
export const SVGA3DFORMAT_OP_NOFILTER = 0x40000;
export const SVGA3DFORMAT_OP_MEMBEROFGROUP_ARGB = 0x80000;
export const SVGA3DFORMAT_OP_SRGBWRITE = 0x100000;
export const SVGA3DFORMAT_OP_NOALPHABLEND = 0x200000;
export const SVGA3DFORMAT_OP_AUTOGENMIPMAP = 0x400000;
export const SVGA3DFORMAT_OP_VERTEXTEXTURE = 0x800000;
export const SVGA3DFORMAT_OP_NOTEXCOORDWRAPNORMIP = 0x1000000;
export const SVGA3D_FORMAT_POSITIVE = 0xDBFDDF;
export const SVGA3D_FORMAT_NEGATIVE = 0x1240000;
export const SVGA3D_RS_INVALID = 0;
export const SVGA3D_RS_MIN = 1;
export const SVGA3D_RS_ZENABLE = 1;
export const SVGA3D_RS_ZWRITEENABLE = 2;
export const SVGA3D_RS_ALPHATESTENABLE = 3;
export const SVGA3D_RS_DITHERENABLE = 4;
export const SVGA3D_RS_BLENDENABLE = 5;
export const SVGA3D_RS_FOGENABLE = 6;
export const SVGA3D_RS_SPECULARENABLE = 7;
export const SVGA3D_RS_STENCILENABLE = 8;
export const SVGA3D_RS_LIGHTINGENABLE = 9;
export const SVGA3D_RS_NORMALIZENORMALS = 0xA;
export const SVGA3D_RS_POINTSPRITEENABLE = 0xB;
export const SVGA3D_RS_POINTSCALEENABLE = 0xC;
export const SVGA3D_RS_STENCILREF = 0xD;
export const SVGA3D_RS_STENCILMASK = 0xE;
export const SVGA3D_RS_STENCILWRITEMASK = 0xF;
export const SVGA3D_RS_FOGSTART = 0x10;
export const SVGA3D_RS_FOGEND = 0x11;
export const SVGA3D_RS_FOGDENSITY = 0x12;
export const SVGA3D_RS_POINTSIZE = 0x13;
export const SVGA3D_RS_POINTSIZEMIN = 0x14;
export const SVGA3D_RS_POINTSIZEMAX = 0x15;
export const SVGA3D_RS_POINTSCALE_A = 0x16;
export const SVGA3D_RS_POINTSCALE_B = 0x17;
export const SVGA3D_RS_POINTSCALE_C = 0x18;
export const SVGA3D_RS_FOGCOLOR = 0x19;
export const SVGA3D_RS_AMBIENT = 0x1A;
export const SVGA3D_RS_CLIPPLANEENABLE = 0x1B;
export const SVGA3D_RS_FOGMODE = 0x1C;
export const SVGA3D_RS_FILLMODE = 0x1D;
export const SVGA3D_RS_SHADEMODE = 0x1E;
export const SVGA3D_RS_LINEPATTERN = 0x1F;
export const SVGA3D_RS_SRCBLEND = 0x20;
export const SVGA3D_RS_DSTBLEND = 0x21;
export const SVGA3D_RS_BLENDEQUATION = 0x22;
export const SVGA3D_RS_CULLMODE = 0x23;
export const SVGA3D_RS_ZFUNC = 0x24;
export const SVGA3D_RS_ALPHAFUNC = 0x25;
export const SVGA3D_RS_STENCILFUNC = 0x26;
export const SVGA3D_RS_STENCILFAIL = 0x27;
export const SVGA3D_RS_STENCILZFAIL = 0x28;
export const SVGA3D_RS_STENCILPASS = 0x29;
export const SVGA3D_RS_ALPHAREF = 0x2A;
export const SVGA3D_RS_FRONTWINDING = 0x2B;
export const SVGA3D_RS_COORDINATETYPE = 0x2C;
export const SVGA3D_RS_ZBIAS = 0x2D;
export const SVGA3D_RS_RANGEFOGENABLE = 0x2E;
export const SVGA3D_RS_COLORWRITEENABLE = 0x2F;
export const SVGA3D_RS_VERTEXMATERIALENABLE = 0x30;
export const SVGA3D_RS_DIFFUSEMATERIALSOURCE = 0x31;
export const SVGA3D_RS_SPECULARMATERIALSOURCE = 0x32;
export const SVGA3D_RS_AMBIENTMATERIALSOURCE = 0x33;
export const SVGA3D_RS_EMISSIVEMATERIALSOURCE = 0x34;
export const SVGA3D_RS_TEXTUREFACTOR = 0x35;
export const SVGA3D_RS_LOCALVIEWER = 0x36;
export const SVGA3D_RS_SCISSORTESTENABLE = 0x37;
export const SVGA3D_RS_BLENDCOLOR = 0x38;
export const SVGA3D_RS_STENCILENABLE2SIDED = 0x39;
export const SVGA3D_RS_CCWSTENCILFUNC = 0x3A;
export const SVGA3D_RS_CCWSTENCILFAIL = 0x3B;
export const SVGA3D_RS_CCWSTENCILZFAIL = 0x3C;
export const SVGA3D_RS_CCWSTENCILPASS = 0x3D;
export const SVGA3D_RS_VERTEXBLEND = 0x3E;
export const SVGA3D_RS_SLOPESCALEDEPTHBIAS = 0x3F;
export const SVGA3D_RS_DEPTHBIAS = 0x40;
export const SVGA3D_RS_OUTPUTGAMMA = 0x41;
export const SVGA3D_RS_ZVISIBLE = 0x42;
export const SVGA3D_RS_LASTPIXEL = 0x43;
export const SVGA3D_RS_CLIPPING = 0x44;
export const SVGA3D_RS_WRAP0 = 0x45;
export const SVGA3D_RS_WRAP1 = 0x46;
export const SVGA3D_RS_WRAP2 = 0x47;
export const SVGA3D_RS_WRAP3 = 0x48;
export const SVGA3D_RS_WRAP4 = 0x49;
export const SVGA3D_RS_WRAP5 = 0x4A;
export const SVGA3D_RS_WRAP6 = 0x4B;
export const SVGA3D_RS_WRAP7 = 0x4C;
export const SVGA3D_RS_WRAP8 = 0x4D;
export const SVGA3D_RS_WRAP9 = 0x4E;
export const SVGA3D_RS_WRAP10 = 0x4F;
export const SVGA3D_RS_WRAP11 = 0x50;
export const SVGA3D_RS_WRAP12 = 0x51;
export const SVGA3D_RS_WRAP13 = 0x52;
export const SVGA3D_RS_WRAP14 = 0x53;
export const SVGA3D_RS_WRAP15 = 0x54;
export const SVGA3D_RS_MULTISAMPLEANTIALIAS = 0x55;
export const SVGA3D_RS_MULTISAMPLEMASK = 0x56;
export const SVGA3D_RS_INDEXEDVERTEXBLENDENABLE = 0x57;
export const SVGA3D_RS_TWEENFACTOR = 0x58;
export const SVGA3D_RS_ANTIALIASEDLINEENABLE = 0x59;
export const SVGA3D_RS_COLORWRITEENABLE1 = 0x5A;
export const SVGA3D_RS_COLORWRITEENABLE2 = 0x5B;
export const SVGA3D_RS_COLORWRITEENABLE3 = 0x5C;
export const SVGA3D_RS_SEPARATEALPHABLENDENABLE = 0x5D;
export const SVGA3D_RS_SRCBLENDALPHA = 0x5E;
export const SVGA3D_RS_DSTBLENDALPHA = 0x5F;
export const SVGA3D_RS_BLENDEQUATIONALPHA = 0x60;
export const SVGA3D_RS_TRANSPARENCYANTIALIAS = 0x61;
export const SVGA3D_RS_LINEWIDTH = 0x62;
export const SVGA3D_RS_MAX = 0x63;
export const SVGA3D_TRANSPARENCYANTIALIAS_NORMAL = 0;
export const SVGA3D_TRANSPARENCYANTIALIAS_ALPHATOCOVERAGE = 1;
export const SVGA3D_TRANSPARENCYANTIALIAS_SUPERSAMPLE = 2;
export const SVGA3D_TRANSPARENCYANTIALIAS_MAX = 3;
export const SVGA3D_VERTEXMATERIAL_NONE = 0;
export const SVGA3D_VERTEXMATERIAL_DIFFUSE = 1;
export const SVGA3D_VERTEXMATERIAL_SPECULAR = 2;
export const SVGA3D_VERTEXMATERIAL_MAX = 3;
export const SVGA3D_FILLMODE_INVALID = 0;
export const SVGA3D_FILLMODE_MIN = 1;
export const SVGA3D_FILLMODE_POINT = 1;
export const SVGA3D_FILLMODE_LINE = 2;
export const SVGA3D_FILLMODE_FILL = 3;
export const SVGA3D_FILLMODE_MAX = 4;
export const SVGA3D_SHADEMODE_INVALID = 0;
export const SVGA3D_SHADEMODE_FLAT = 1;
export const SVGA3D_SHADEMODE_SMOOTH = 2;
export const SVGA3D_SHADEMODE_PHONG = 3;
export const SVGA3D_SHADEMODE_MAX = 4;
export const SVGA3D_BLENDOP_INVALID = 0;
export const SVGA3D_BLENDOP_MIN = 1;
export const SVGA3D_BLENDOP_ZERO = 1;
export const SVGA3D_BLENDOP_ONE = 2;
export const SVGA3D_BLENDOP_SRCCOLOR = 3;
export const SVGA3D_BLENDOP_INVSRCCOLOR = 4;
export const SVGA3D_BLENDOP_SRCALPHA = 5;
export const SVGA3D_BLENDOP_INVSRCALPHA = 6;
export const SVGA3D_BLENDOP_DESTALPHA = 7;
export const SVGA3D_BLENDOP_INVDESTALPHA = 8;
export const SVGA3D_BLENDOP_DESTCOLOR = 9;
export const SVGA3D_BLENDOP_INVDESTCOLOR = 0xA;
export const SVGA3D_BLENDOP_SRCALPHASAT = 0xB;
export const SVGA3D_BLENDOP_BLENDFACTOR = 0xC;
export const SVGA3D_BLENDOP_INVBLENDFACTOR = 0xD;
export const SVGA3D_BLENDOP_SRC1COLOR = 0xE;
export const SVGA3D_BLENDOP_INVSRC1COLOR = 0xF;
export const SVGA3D_BLENDOP_SRC1ALPHA = 0x10;
export const SVGA3D_BLENDOP_INVSRC1ALPHA = 0x11;
export const SVGA3D_BLENDOP_BLENDFACTORALPHA = 0x12;
export const SVGA3D_BLENDOP_INVBLENDFACTORALPHA = 0x13;
export const SVGA3D_BLENDOP_MAX = 0x14;
export const SVGA3D_BLENDEQ_INVALID = 0;
export const SVGA3D_BLENDEQ_MIN = 1;
export const SVGA3D_BLENDEQ_ADD = 1;
export const SVGA3D_BLENDEQ_SUBTRACT = 2;
export const SVGA3D_BLENDEQ_REVSUBTRACT = 3;
export const SVGA3D_BLENDEQ_MINIMUM = 4;
export const SVGA3D_BLENDEQ_MAXIMUM = 5;
export const SVGA3D_BLENDEQ_MAX = 6;
export const SVGA3D_DX11_LOGICOP_MIN = 0;
export const SVGA3D_DX11_LOGICOP_CLEAR = 0;
export const SVGA3D_DX11_LOGICOP_SET = 1;
export const SVGA3D_DX11_LOGICOP_COPY = 2;
export const SVGA3D_DX11_LOGICOP_COPY_INVERTED = 3;
export const SVGA3D_DX11_LOGICOP_NOOP = 4;
export const SVGA3D_DX11_LOGICOP_INVERT = 5;
export const SVGA3D_DX11_LOGICOP_AND = 6;
export const SVGA3D_DX11_LOGICOP_NAND = 7;
export const SVGA3D_DX11_LOGICOP_OR = 8;
export const SVGA3D_DX11_LOGICOP_NOR = 9;
export const SVGA3D_DX11_LOGICOP_XOR = 0xA;
export const SVGA3D_DX11_LOGICOP_EQUIV = 0xB;
export const SVGA3D_DX11_LOGICOP_AND_REVERSE = 0xC;
export const SVGA3D_DX11_LOGICOP_AND_INVERTED = 0xD;
export const SVGA3D_DX11_LOGICOP_OR_REVERSE = 0xE;
export const SVGA3D_DX11_LOGICOP_OR_INVERTED = 0xF;
export const SVGA3D_DX11_LOGICOP_MAX = 0x10;
export const SVGA3D_FRONTWINDING_INVALID = 0;
export const SVGA3D_FRONTWINDING_CW = 1;
export const SVGA3D_FRONTWINDING_MIN = 1;
export const SVGA3D_FRONTWINDING_CCW = 2;
export const SVGA3D_FRONTWINDING_MAX = 3;
export const SVGA3D_FACE_INVALID = 0;
export const SVGA3D_FACE_NONE = 1;
export const SVGA3D_FACE_MIN = 1;
export const SVGA3D_FACE_FRONT = 2;
export const SVGA3D_FACE_BACK = 3;
export const SVGA3D_FACE_FRONT_BACK = 4;
export const SVGA3D_FACE_MAX = 5;
export const SVGA3D_CMP_INVALID = 0;
export const SVGA3D_CMP_NEVER = 1;
export const SVGA3D_CMP_LESS = 2;
export const SVGA3D_CMP_EQUAL = 3;
export const SVGA3D_CMP_LESSEQUAL = 4;
export const SVGA3D_CMP_GREATER = 5;
export const SVGA3D_CMP_NOTEQUAL = 6;
export const SVGA3D_CMP_GREATEREQUAL = 7;
export const SVGA3D_CMP_ALWAYS = 8;
export const SVGA3D_CMP_MAX = 9;
export const SVGA3D_FOGFUNC_INVALID = 0;
export const SVGA3D_FOGFUNC_EXP = 1;
export const SVGA3D_FOGFUNC_EXP2 = 2;
export const SVGA3D_FOGFUNC_LINEAR = 3;
export const SVGA3D_FOGFUNC_PER_VERTEX = 4;
export const SVGA3D_FOGTYPE_INVALID = 0;
export const SVGA3D_FOGTYPE_VERTEX = 1;
export const SVGA3D_FOGTYPE_PIXEL = 2;
export const SVGA3D_FOGTYPE_MAX = 3;
export const SVGA3D_FOGBASE_INVALID = 0;
export const SVGA3D_FOGBASE_DEPTHBASED = 1;
export const SVGA3D_FOGBASE_RANGEBASED = 2;
export const SVGA3D_FOGBASE_MAX = 3;
export const SVGA3D_STENCILOP_INVALID = 0;
export const SVGA3D_STENCILOP_MIN = 1;
export const SVGA3D_STENCILOP_KEEP = 1;
export const SVGA3D_STENCILOP_ZERO = 2;
export const SVGA3D_STENCILOP_REPLACE = 3;
export const SVGA3D_STENCILOP_INCRSAT = 4;
export const SVGA3D_STENCILOP_DECRSAT = 5;
export const SVGA3D_STENCILOP_INVERT = 6;
export const SVGA3D_STENCILOP_INCR = 7;
export const SVGA3D_STENCILOP_DECR = 8;
export const SVGA3D_STENCILOP_MAX = 9;
export const SVGA3D_CLIPPLANE_0 = 1;
export const SVGA3D_CLIPPLANE_1 = 2;
export const SVGA3D_CLIPPLANE_2 = 4;
export const SVGA3D_CLIPPLANE_3 = 8;
export const SVGA3D_CLIPPLANE_4 = 0x10;
export const SVGA3D_CLIPPLANE_5 = 0x20;
export const SVGA3D_CLEAR_COLOR = 1;
export const SVGA3D_CLEAR_DEPTH = 2;
export const SVGA3D_CLEAR_STENCIL = 4;
export const SVGA3D_CLEAR_COLORFILL = 8;
export const SVGA3D_RT_DEPTH = 0;
export const SVGA3D_RT_MIN = 0;
export const SVGA3D_RT_STENCIL = 1;
export const SVGA3D_RT_COLOR0 = 2;
export const SVGA3D_RT_COLOR1 = 3;
export const SVGA3D_RT_COLOR2 = 4;
export const SVGA3D_RT_COLOR3 = 5;
export const SVGA3D_RT_COLOR4 = 6;
export const SVGA3D_RT_COLOR5 = 7;
export const SVGA3D_RT_COLOR6 = 8;
export const SVGA3D_RT_COLOR7 = 9;
export const SVGA3D_RT_MAX = 0xA;
export const SVGA3D_RT_INVALID = 0xFFFFFFFF;
export const SVGA3D_MAX_RT_COLOR = 8;
export const SVGA3D_VBLEND_DISABLE = 0;
export const SVGA3D_VBLEND_1WEIGHT = 1;
export const SVGA3D_VBLEND_2WEIGHT = 2;
export const SVGA3D_VBLEND_3WEIGHT = 3;
export const SVGA3D_VBLEND_MAX = 4;
export const SVGA3D_WRAPCOORD_0 = 1;
export const SVGA3D_WRAPCOORD_1 = 2;
export const SVGA3D_WRAPCOORD_2 = 4;
export const SVGA3D_WRAPCOORD_3 = 8;
export const SVGA3D_WRAPCOORD_ALL = 0xF;
export const SVGA3D_TS_INVALID = 0;
export const SVGA3D_TS_MIN = 1;
export const SVGA3D_TS_BIND_TEXTURE = 1;
export const SVGA3D_TS_COLOROP = 2;
export const SVGA3D_TS_COLORARG1 = 3;
export const SVGA3D_TS_COLORARG2 = 4;
export const SVGA3D_TS_ALPHAOP = 5;
export const SVGA3D_TS_ALPHAARG1 = 6;
export const SVGA3D_TS_ALPHAARG2 = 7;
export const SVGA3D_TS_ADDRESSU = 8;
export const SVGA3D_TS_ADDRESSV = 9;
export const SVGA3D_TS_MIPFILTER = 0xA;
export const SVGA3D_TS_MAGFILTER = 0xB;
export const SVGA3D_TS_MINFILTER = 0xC;
export const SVGA3D_TS_BORDERCOLOR = 0xD;
export const SVGA3D_TS_TEXCOORDINDEX = 0xE;
export const SVGA3D_TS_TEXTURETRANSFORMFLAGS = 0xF;
export const SVGA3D_TS_TEXCOORDGEN = 0x10;
export const SVGA3D_TS_BUMPENVMAT00 = 0x11;
export const SVGA3D_TS_BUMPENVMAT01 = 0x12;
export const SVGA3D_TS_BUMPENVMAT10 = 0x13;
export const SVGA3D_TS_BUMPENVMAT11 = 0x14;
export const SVGA3D_TS_TEXTURE_MIPMAP_LEVEL = 0x15;
export const SVGA3D_TS_TEXTURE_LOD_BIAS = 0x16;
export const SVGA3D_TS_TEXTURE_ANISOTROPIC_LEVEL = 0x17;
export const SVGA3D_TS_ADDRESSW = 0x18;
export const SVGA3D_TS_GAMMA = 0x19;
export const SVGA3D_TS_BUMPENVLSCALE = 0x1A;
export const SVGA3D_TS_BUMPENVLOFFSET = 0x1B;
export const SVGA3D_TS_COLORARG0 = 0x1C;
export const SVGA3D_TS_ALPHAARG0 = 0x1D;
export const SVGA3D_TS_PREGB_MAX = 0x1E;
export const SVGA3D_TS_CONSTANT = 0x1E;
export const SVGA3D_TS_COLOR_KEY_ENABLE = 0x1F;
export const SVGA3D_TS_COLOR_KEY = 0x20;
export const SVGA3D_TS_MAX = 0x21;
export const SVGA3D_TC_INVALID = 0;
export const SVGA3D_TC_DISABLE = 1;
export const SVGA3D_TC_SELECTARG1 = 2;
export const SVGA3D_TC_SELECTARG2 = 3;
export const SVGA3D_TC_MODULATE = 4;
export const SVGA3D_TC_ADD = 5;
export const SVGA3D_TC_ADDSIGNED = 6;
export const SVGA3D_TC_SUBTRACT = 7;
export const SVGA3D_TC_BLENDTEXTUREALPHA = 8;
export const SVGA3D_TC_BLENDDIFFUSEALPHA = 9;
export const SVGA3D_TC_BLENDCURRENTALPHA = 0xA;
export const SVGA3D_TC_BLENDFACTORALPHA = 0xB;
export const SVGA3D_TC_MODULATE2X = 0xC;
export const SVGA3D_TC_MODULATE4X = 0xD;
export const SVGA3D_TC_DSDT = 0xE;
export const SVGA3D_TC_DOTPRODUCT3 = 0xF;
export const SVGA3D_TC_BLENDTEXTUREALPHAPM = 0x10;
export const SVGA3D_TC_ADDSIGNED2X = 0x11;
export const SVGA3D_TC_ADDSMOOTH = 0x12;
export const SVGA3D_TC_PREMODULATE = 0x13;
export const SVGA3D_TC_MODULATEALPHA_ADDCOLOR = 0x14;
export const SVGA3D_TC_MODULATECOLOR_ADDALPHA = 0x15;
export const SVGA3D_TC_MODULATEINVALPHA_ADDCOLOR = 0x16;
export const SVGA3D_TC_MODULATEINVCOLOR_ADDALPHA = 0x17;
export const SVGA3D_TC_BUMPENVMAPLUMINANCE = 0x18;
export const SVGA3D_TC_MULTIPLYADD = 0x19;
export const SVGA3D_TC_LERP = 0x1A;
export const SVGA3D_TC_MAX = 0x1B;
export const SVGA3D_TEX_ADDRESS_INVALID = 0;
export const SVGA3D_TEX_ADDRESS_MIN = 1;
export const SVGA3D_TEX_ADDRESS_WRAP = 1;
export const SVGA3D_TEX_ADDRESS_MIRROR = 2;
export const SVGA3D_TEX_ADDRESS_CLAMP = 3;
export const SVGA3D_TEX_ADDRESS_BORDER = 4;
export const SVGA3D_TEX_ADDRESS_MIRRORONCE = 5;
export const SVGA3D_TEX_ADDRESS_EDGE = 6;
export const SVGA3D_TEX_ADDRESS_MAX = 7;
export const SVGA3D_TEX_FILTER_NONE = 0;
export const SVGA3D_TEX_FILTER_MIN = 0;
export const SVGA3D_TEX_FILTER_NEAREST = 1;
export const SVGA3D_TEX_FILTER_LINEAR = 2;
export const SVGA3D_TEX_FILTER_ANISOTROPIC = 3;
export const SVGA3D_TEX_FILTER_FLATCUBIC = 4;
export const SVGA3D_TEX_FILTER_GAUSSIANCUBIC = 5;
export const SVGA3D_TEX_FILTER_PYRAMIDALQUAD = 6;
export const SVGA3D_TEX_FILTER_GAUSSIANQUAD = 7;
export const SVGA3D_TEX_FILTER_MAX = 8;
export const SVGA3D_TEX_TRANSFORM_OFF = 0;
export const SVGA3D_TEX_TRANSFORM_S = 1;
export const SVGA3D_TEX_TRANSFORM_T = 2;
export const SVGA3D_TEX_TRANSFORM_R = 4;
export const SVGA3D_TEX_TRANSFORM_Q = 8;
export const SVGA3D_TEX_PROJECTED = 0x8000;
export const SVGA3D_TEXCOORD_GEN_OFF = 0;
export const SVGA3D_TEXCOORD_GEN_EYE_POSITION = 1;
export const SVGA3D_TEXCOORD_GEN_EYE_NORMAL = 2;
export const SVGA3D_TEXCOORD_GEN_REFLECTIONVECTOR = 3;
export const SVGA3D_TEXCOORD_GEN_SPHERE = 4;
export const SVGA3D_TEXCOORD_GEN_MAX = 5;
export const SVGA3D_TA_INVALID = 0;
export const SVGA3D_TA_TFACTOR = 1;
export const SVGA3D_TA_PREVIOUS = 2;
export const SVGA3D_TA_DIFFUSE = 3;
export const SVGA3D_TA_TEXTURE = 4;
export const SVGA3D_TA_SPECULAR = 5;
export const SVGA3D_TA_CONSTANT = 6;
export const SVGA3D_TA_MAX = 7;
export const SVGA3D_TM_MASK_LEN = 4;
export const SVGA3D_TM_NONE = 0;
export const SVGA3D_TM_ALPHA = 0x10;
export const SVGA3D_TM_ONE_MINUS = 0x20;
export const SVGA3D_DECLUSAGE_POSITION = 0;
export const SVGA3D_DECLUSAGE_BLENDWEIGHT = 1;
export const SVGA3D_DECLUSAGE_BLENDINDICES = 2;
export const SVGA3D_DECLUSAGE_NORMAL = 3;
export const SVGA3D_DECLUSAGE_PSIZE = 4;
export const SVGA3D_DECLUSAGE_TEXCOORD = 5;
export const SVGA3D_DECLUSAGE_TANGENT = 6;
export const SVGA3D_DECLUSAGE_BINORMAL = 7;
export const SVGA3D_DECLUSAGE_TESSFACTOR = 8;
export const SVGA3D_DECLUSAGE_POSITIONT = 9;
export const SVGA3D_DECLUSAGE_COLOR = 0xA;
export const SVGA3D_DECLUSAGE_FOG = 0xB;
export const SVGA3D_DECLUSAGE_DEPTH = 0xC;
export const SVGA3D_DECLUSAGE_SAMPLE = 0xD;
export const SVGA3D_DECLUSAGE_MAX = 0xE;
export const SVGA3D_DECLMETHOD_DEFAULT = 0;
export const SVGA3D_DECLMETHOD_PARTIALU = 1;
export const SVGA3D_DECLMETHOD_PARTIALV = 2;
export const SVGA3D_DECLMETHOD_CROSSUV = 3;
export const SVGA3D_DECLMETHOD_UV = 4;
export const SVGA3D_DECLMETHOD_LOOKUP = 5;
export const SVGA3D_DECLMETHOD_LOOKUPPRESAMPLED = 6;
export const SVGA3D_DECLTYPE_FLOAT1 = 0;
export const SVGA3D_DECLTYPE_FLOAT2 = 1;
export const SVGA3D_DECLTYPE_FLOAT3 = 2;
export const SVGA3D_DECLTYPE_FLOAT4 = 3;
export const SVGA3D_DECLTYPE_D3DCOLOR = 4;
export const SVGA3D_DECLTYPE_UBYTE4 = 5;
export const SVGA3D_DECLTYPE_SHORT2 = 6;
export const SVGA3D_DECLTYPE_SHORT4 = 7;
export const SVGA3D_DECLTYPE_UBYTE4N = 8;
export const SVGA3D_DECLTYPE_SHORT2N = 9;
export const SVGA3D_DECLTYPE_SHORT4N = 0xA;
export const SVGA3D_DECLTYPE_USHORT2N = 0xB;
export const SVGA3D_DECLTYPE_USHORT4N = 0xC;
export const SVGA3D_DECLTYPE_UDEC3 = 0xD;
export const SVGA3D_DECLTYPE_DEC3N = 0xE;
export const SVGA3D_DECLTYPE_FLOAT16_2 = 0xF;
export const SVGA3D_DECLTYPE_FLOAT16_4 = 0x10;
export const SVGA3D_DECLTYPE_MAX = 0x11;
export const SVGA3D_PRIMITIVE_INVALID = 0;
export const SVGA3D_PRIMITIVE_MIN = 0;
export const SVGA3D_PRIMITIVE_TRIANGLELIST = 1;
export const SVGA3D_PRIMITIVE_POINTLIST = 2;
export const SVGA3D_PRIMITIVE_LINELIST = 3;
export const SVGA3D_PRIMITIVE_LINESTRIP = 4;
export const SVGA3D_PRIMITIVE_TRIANGLESTRIP = 5;
export const SVGA3D_PRIMITIVE_TRIANGLEFAN = 6;
export const SVGA3D_PRIMITIVE_LINELIST_ADJ = 7;
export const SVGA3D_PRIMITIVE_PREDX_MAX = 7;
export const SVGA3D_PRIMITIVE_LINESTRIP_ADJ = 8;
export const SVGA3D_PRIMITIVE_TRIANGLELIST_ADJ = 9;
export const SVGA3D_PRIMITIVE_TRIANGLESTRIP_ADJ = 0xA;
export const SVGA3D_PRIMITIVE_DX10_MAX = 0xB;
export const SVGA3D_PRIMITIVE_1_CONTROL_POINT_PATCH = 0xB;
export const SVGA3D_PRIMITIVE_2_CONTROL_POINT_PATCH = 0xC;
export const SVGA3D_PRIMITIVE_3_CONTROL_POINT_PATCH = 0xD;
export const SVGA3D_PRIMITIVE_4_CONTROL_POINT_PATCH = 0xE;
export const SVGA3D_PRIMITIVE_5_CONTROL_POINT_PATCH = 0xF;
export const SVGA3D_PRIMITIVE_6_CONTROL_POINT_PATCH = 0x10;
export const SVGA3D_PRIMITIVE_7_CONTROL_POINT_PATCH = 0x11;
export const SVGA3D_PRIMITIVE_8_CONTROL_POINT_PATCH = 0x12;
export const SVGA3D_PRIMITIVE_9_CONTROL_POINT_PATCH = 0x13;
export const SVGA3D_PRIMITIVE_10_CONTROL_POINT_PATCH = 0x14;
export const SVGA3D_PRIMITIVE_11_CONTROL_POINT_PATCH = 0x15;
export const SVGA3D_PRIMITIVE_12_CONTROL_POINT_PATCH = 0x16;
export const SVGA3D_PRIMITIVE_13_CONTROL_POINT_PATCH = 0x17;
export const SVGA3D_PRIMITIVE_14_CONTROL_POINT_PATCH = 0x18;
export const SVGA3D_PRIMITIVE_15_CONTROL_POINT_PATCH = 0x19;
export const SVGA3D_PRIMITIVE_16_CONTROL_POINT_PATCH = 0x1A;
export const SVGA3D_PRIMITIVE_17_CONTROL_POINT_PATCH = 0x1B;
export const SVGA3D_PRIMITIVE_18_CONTROL_POINT_PATCH = 0x1C;
export const SVGA3D_PRIMITIVE_19_CONTROL_POINT_PATCH = 0x1D;
export const SVGA3D_PRIMITIVE_20_CONTROL_POINT_PATCH = 0x1E;
export const SVGA3D_PRIMITIVE_21_CONTROL_POINT_PATCH = 0x1F;
export const SVGA3D_PRIMITIVE_22_CONTROL_POINT_PATCH = 0x20;
export const SVGA3D_PRIMITIVE_23_CONTROL_POINT_PATCH = 0x21;
export const SVGA3D_PRIMITIVE_24_CONTROL_POINT_PATCH = 0x22;
export const SVGA3D_PRIMITIVE_25_CONTROL_POINT_PATCH = 0x23;
export const SVGA3D_PRIMITIVE_26_CONTROL_POINT_PATCH = 0x24;
export const SVGA3D_PRIMITIVE_27_CONTROL_POINT_PATCH = 0x25;
export const SVGA3D_PRIMITIVE_28_CONTROL_POINT_PATCH = 0x26;
export const SVGA3D_PRIMITIVE_29_CONTROL_POINT_PATCH = 0x27;
export const SVGA3D_PRIMITIVE_30_CONTROL_POINT_PATCH = 0x28;
export const SVGA3D_PRIMITIVE_31_CONTROL_POINT_PATCH = 0x29;
export const SVGA3D_PRIMITIVE_32_CONTROL_POINT_PATCH = 0x2A;
export const SVGA3D_PRIMITIVE_MAX = 0x2B;
export const SVGA3D_COORDINATE_INVALID = 0;
export const SVGA3D_COORDINATE_LEFTHANDED = 1;
export const SVGA3D_COORDINATE_RIGHTHANDED = 2;
export const SVGA3D_COORDINATE_MAX = 3;
export const SVGA3D_TRANSFORM_INVALID = 0;
export const SVGA3D_TRANSFORM_WORLD = 1;
export const SVGA3D_TRANSFORM_MIN = 1;
export const SVGA3D_TRANSFORM_VIEW = 2;
export const SVGA3D_TRANSFORM_PROJECTION = 3;
export const SVGA3D_TRANSFORM_TEXTURE0 = 4;
export const SVGA3D_TRANSFORM_TEXTURE1 = 5;
export const SVGA3D_TRANSFORM_TEXTURE2 = 6;
export const SVGA3D_TRANSFORM_TEXTURE3 = 7;
export const SVGA3D_TRANSFORM_TEXTURE4 = 8;
export const SVGA3D_TRANSFORM_TEXTURE5 = 9;
export const SVGA3D_TRANSFORM_TEXTURE6 = 0xA;
export const SVGA3D_TRANSFORM_TEXTURE7 = 0xB;
export const SVGA3D_TRANSFORM_WORLD1 = 0xC;
export const SVGA3D_TRANSFORM_WORLD2 = 0xD;
export const SVGA3D_TRANSFORM_WORLD3 = 0xE;
export const SVGA3D_TRANSFORM_MAX = 0xF;
export const SVGA3D_LIGHTTYPE_INVALID = 0;
export const SVGA3D_LIGHTTYPE_MIN = 1;
export const SVGA3D_LIGHTTYPE_POINT = 1;
export const SVGA3D_LIGHTTYPE_SPOT1 = 2;
export const SVGA3D_LIGHTTYPE_SPOT2 = 3;
export const SVGA3D_LIGHTTYPE_DIRECTIONAL = 4;
export const SVGA3D_LIGHTTYPE_MAX = 5;
export const SVGA3D_CUBEFACE_POSX = 0;
export const SVGA3D_CUBEFACE_NEGX = 1;
export const SVGA3D_CUBEFACE_POSY = 2;
export const SVGA3D_CUBEFACE_NEGY = 3;
export const SVGA3D_CUBEFACE_POSZ = 4;
export const SVGA3D_CUBEFACE_NEGZ = 5;
export const SVGA3D_SHADERTYPE_INVALID = 0;
export const SVGA3D_SHADERTYPE_MIN = 1;
export const SVGA3D_SHADERTYPE_VS = 1;
export const SVGA3D_SHADERTYPE_PS = 2;
export const SVGA3D_SHADERTYPE_PREDX_MAX = 3;
export const SVGA3D_SHADERTYPE_GS = 3;
export const SVGA3D_SHADERTYPE_DX10_MAX = 4;
export const SVGA3D_SHADERTYPE_HS = 4;
export const SVGA3D_SHADERTYPE_DS = 5;
export const SVGA3D_SHADERTYPE_CS = 6;
export const SVGA3D_SHADERTYPE_MAX = 7;
export const SVGA3D_NUM_SHADERTYPE_PREDX = 2;
export const SVGA3D_NUM_SHADERTYPE_DX10 = 3;
export const SVGA3D_NUM_SHADERTYPE = 6;
export const SVGA3D_CONST_TYPE_MIN = 0;
export const SVGA3D_CONST_TYPE_FLOAT = 0;
export const SVGA3D_CONST_TYPE_INT = 1;
export const SVGA3D_CONST_TYPE_BOOL = 2;
export const SVGA3D_CONST_TYPE_MAX = 3;
export const SVGA3D_CONSTREG_MAX = 0x100;
export const SVGA3D_CONSTINTREG_MAX = 0x10;
export const SVGA3D_CONSTBOOLREG_MAX = 0x10;
export const SVGA3D_STRETCH_BLT_POINT = 0;
export const SVGA3D_STRETCH_BLT_LINEAR = 1;
export const SVGA3D_STRETCH_BLT_MAX = 2;
export const SVGA3D_QUERYTYPE_INVALID = -1;
export const SVGA3D_QUERYTYPE_MIN = 0;
export const SVGA3D_QUERYTYPE_OCCLUSION = 0;
export const SVGA3D_QUERYTYPE_TIMESTAMP = 1;
export const SVGA3D_QUERYTYPE_TIMESTAMPDISJOINT = 2;
export const SVGA3D_QUERYTYPE_PIPELINESTATS = 3;
export const SVGA3D_QUERYTYPE_OCCLUSIONPREDICATE = 4;
export const SVGA3D_QUERYTYPE_STREAMOUTPUTSTATS = 5;
export const SVGA3D_QUERYTYPE_STREAMOVERFLOWPREDICATE = 6;
export const SVGA3D_QUERYTYPE_OCCLUSION64 = 7;
export const SVGA3D_QUERYTYPE_DX10_MAX = 8;
export const SVGA3D_QUERYTYPE_SOSTATS_STREAM0 = 8;
export const SVGA3D_QUERYTYPE_SOSTATS_STREAM1 = 9;
export const SVGA3D_QUERYTYPE_SOSTATS_STREAM2 = 0xA;
export const SVGA3D_QUERYTYPE_SOSTATS_STREAM3 = 0xB;
export const SVGA3D_QUERYTYPE_SOP_STREAM0 = 0xC;
export const SVGA3D_QUERYTYPE_SOP_STREAM1 = 0xD;
export const SVGA3D_QUERYTYPE_SOP_STREAM2 = 0xE;
export const SVGA3D_QUERYTYPE_SOP_STREAM3 = 0xF;
export const SVGA3D_QUERYTYPE_MAX = 0x10;
export const SVGA3D_NUM_QUERYTYPE = 0x10;
export const SVGA3D_MAX_QUERY = 0x40;
export const SVGA3D_QUERYSTATE_PENDING = 0;
export const SVGA3D_QUERYSTATE_SUCCEEDED = 1;
export const SVGA3D_QUERYSTATE_FAILED = 2;
export const SVGA3D_QUERYSTATE_NEW = 3;
export const SVGA3D_WRITE_HOST_VRAM = 1;
export const SVGA3D_READ_HOST_VRAM = 2;
export const SVGA3D_LOGICOP_INVALID = 0;
export const SVGA3D_LOGICOP_COPY = 1;
export const SVGA3D_LOGICOP_MIN = 1;
export const SVGA3D_LOGICOP_NOT = 2;
export const SVGA3D_LOGICOP_AND = 3;
export const SVGA3D_LOGICOP_OR = 4;
export const SVGA3D_LOGICOP_XOR = 5;
export const SVGA3D_LOGICOP_NXOR = 6;
export const SVGA3D_LOGICOP_ROP3 = 7;
export const SVGA3D_LOGICOP_MAX = 8;
export const SVGA3D_LOGICOP_ROP3_INVALID = -1;
export const SVGA3D_LOGICOP_ROP3_MIN = 0;
export const SVGA3D_LOGICOP_ROP3_MAX = 0x100;
export const SVGA_OTABLE_MOB = 0;
export const SVGA_OTABLE_MIN = 0;
export const SVGA_OTABLE_SURFACE = 1;
export const SVGA_OTABLE_CONTEXT = 2;
export const SVGA_OTABLE_SHADER = 3;
export const SVGA_OTABLE_SCREENTARGET = 4;
export const SVGA_OTABLE_DX9_MAX = 5;
export const SVGA_OTABLE_DXCONTEXT = 5;
export const SVGA_OTABLE_DX_MAX = 6;
export const SVGA_OTABLE_DEVEL_MAX = 6;
export const SVGA_OTABLE_MAX = 6;
export const SVGA_OTABLE_RESERVED1 = 6;
export const SVGA_OTABLE_RESERVED2 = 7;
export const SVGA_OTABLE_BUG_1952836_MAX = 8;
export const SVGA_COTABLE_MIN = 0;
export const SVGA_COTABLE_RTVIEW = 0;
export const SVGA_COTABLE_DSVIEW = 1;
export const SVGA_COTABLE_SRVIEW = 2;
export const SVGA_COTABLE_ELEMENTLAYOUT = 3;
export const SVGA_COTABLE_BLENDSTATE = 4;
export const SVGA_COTABLE_DEPTHSTENCIL = 5;
export const SVGA_COTABLE_RASTERIZERSTATE = 6;
export const SVGA_COTABLE_SAMPLER = 7;
export const SVGA_COTABLE_STREAMOUTPUT = 8;
export const SVGA_COTABLE_DXQUERY = 9;
export const SVGA_COTABLE_DXSHADER = 0xA;
export const SVGA_COTABLE_DX10_MAX = 0xB;
export const SVGA_COTABLE_UAVIEW = 0xB;
export const SVGA_COTABLE_MAX = 0xC;
export const SVGA3D_MOBFMT_INVALID = 0xFFFFFFFF;
export const SVGA3D_MOBFMT_PT_0 = 0;
export const SVGA3D_MOBFMT_MIN = 0;
export const SVGA3D_MOBFMT_PT_1 = 1;
export const SVGA3D_MOBFMT_PT_2 = 2;
export const SVGA3D_MOBFMT_RANGE = 3;
export const SVGA3D_MOBFMT_PT64_0 = 4;
export const SVGA3D_MOBFMT_PT64_1 = 5;
export const SVGA3D_MOBFMT_PT64_2 = 6;
export const SVGA3D_MOBFMT_PREDX_MAX = 7;
export const SVGA3D_MOBFMT_EMPTY = 7;
export const SVGA3D_MOBFMT_MAX = 8;
export const SVGA3D_MOB_EMPTY_BASE = 1;
export const SVGA3D_MS_PATTERN_NONE = 0;
export const SVGA3D_MS_PATTERN_MIN = 0;
export const SVGA3D_MS_PATTERN_STANDARD = 1;
export const SVGA3D_MS_PATTERN_CENTER = 2;
export const SVGA3D_MS_PATTERN_MAX = 3;
export const SVGA3D_MS_QUALITY_NONE = 0;
export const SVGA3D_MS_QUALITY_MIN = 0;
export const SVGA3D_MS_QUALITY_FULL = 1;
export const SVGA3D_MS_QUALITY_RESOLVED = 2;
export const SVGA3D_MS_QUALITY_MAX = 3;
export const SVGA3D_FRAME_END = 0;
export const SVGA3D_FRAME_MIN = 0;
export const SVGA3D_FRAME_PARTIAL = 1;
export const SVGA3D_FRAME_UNKNOWN = 2;
export const SVGA3D_FRAME_MAX = 3;

// svga3d_devcaps.h
export const SVGA3D_HWVERSION_WS5_RC1 = 1;
export const SVGA3D_HWVERSION_WS5_RC2 = 2;
export const SVGA3D_HWVERSION_WS51_RC1 = 3;
export const SVGA3D_HWVERSION_WS6_B1 = 0x10001;
export const SVGA3D_HWVERSION_FUSION_11 = 0x10004;
export const SVGA3D_HWVERSION_WS65_B1 = 0x20000;
export const SVGA3D_HWVERSION_WS8_B1 = 0x20001;
export const SVGA3D_HWVERSION_CURRENT = 0x20001;
export const SVGA3D_DEVCAP_INVALID = 0xFFFFFFFF;
export const SVGA3D_DEVCAP_3D = 0;
export const SVGA3D_DEVCAP_MAX_LIGHTS = 1;
export const SVGA3D_DEVCAP_MAX_TEXTURES = 2;
export const SVGA3D_DEVCAP_MAX_CLIP_PLANES = 3;
export const SVGA3D_DEVCAP_VERTEX_SHADER_VERSION = 4;
export const SVGA3D_DEVCAP_VERTEX_SHADER = 5;
export const SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION = 6;
export const SVGA3D_DEVCAP_FRAGMENT_SHADER = 7;
export const SVGA3D_DEVCAP_MAX_RENDER_TARGETS = 8;
export const SVGA3D_DEVCAP_S23E8_TEXTURES = 9;
export const SVGA3D_DEVCAP_S10E5_TEXTURES = 0xA;
export const SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND = 0xB;
export const SVGA3D_DEVCAP_D16_BUFFER_FORMAT = 0xC;
export const SVGA3D_DEVCAP_D24S8_BUFFER_FORMAT = 0xD;
export const SVGA3D_DEVCAP_D24X8_BUFFER_FORMAT = 0xE;
export const SVGA3D_DEVCAP_QUERY_TYPES = 0xF;
export const SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING = 0x10;
export const SVGA3D_DEVCAP_MAX_POINT_SIZE = 0x11;
export const SVGA3D_DEVCAP_MAX_SHADER_TEXTURES = 0x12;
export const SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH = 0x13;
export const SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT = 0x14;
export const SVGA3D_DEVCAP_MAX_VOLUME_EXTENT = 0x15;
export const SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT = 0x16;
export const SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO = 0x17;
export const SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY = 0x18;
export const SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT = 0x19;
export const SVGA3D_DEVCAP_MAX_VERTEX_INDEX = 0x1A;
export const SVGA3D_DEVCAP_MAX_VERTEX_SHADER_INSTRUCTIONS = 0x1B;
export const SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS = 0x1C;
export const SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS = 0x1D;
export const SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS = 0x1E;
export const SVGA3D_DEVCAP_TEXTURE_OPS = 0x1F;
export const SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8 = 0x20;
export const SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8 = 0x21;
export const SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10 = 0x22;
export const SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5 = 0x23;
export const SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5 = 0x24;
export const SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4 = 0x25;
export const SVGA3D_DEVCAP_SURFACEFMT_R5G6B5 = 0x26;
export const SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16 = 0x27;
export const SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8 = 0x28;
export const SVGA3D_DEVCAP_SURFACEFMT_ALPHA8 = 0x29;
export const SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8 = 0x2A;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_D16 = 0x2B;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8 = 0x2C;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8 = 0x2D;
export const SVGA3D_DEVCAP_SURFACEFMT_DXT1 = 0x2E;
export const SVGA3D_DEVCAP_SURFACEFMT_DXT2 = 0x2F;
export const SVGA3D_DEVCAP_SURFACEFMT_DXT3 = 0x30;
export const SVGA3D_DEVCAP_SURFACEFMT_DXT4 = 0x31;
export const SVGA3D_DEVCAP_SURFACEFMT_DXT5 = 0x32;
export const SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8 = 0x33;
export const SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10 = 0x34;
export const SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8 = 0x35;
export const SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8 = 0x36;
export const SVGA3D_DEVCAP_SURFACEFMT_CxV8U8 = 0x37;
export const SVGA3D_DEVCAP_SURFACEFMT_R_S10E5 = 0x38;
export const SVGA3D_DEVCAP_SURFACEFMT_R_S23E8 = 0x39;
export const SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5 = 0x3A;
export const SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8 = 0x3B;
export const SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5 = 0x3C;
export const SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8 = 0x3D;
export const SVGA3D_DEVCAP_MISSING62 = 0x3E;
export const SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES = 0x3F;
export const SVGA3D_DEVCAP_MAX_SIMULTANEOUS_RENDER_TARGETS = 0x40;
export const SVGA3D_DEVCAP_SURFACEFMT_V16U16 = 0x41;
export const SVGA3D_DEVCAP_SURFACEFMT_G16R16 = 0x42;
export const SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16 = 0x43;
export const SVGA3D_DEVCAP_SURFACEFMT_UYVY = 0x44;
export const SVGA3D_DEVCAP_SURFACEFMT_YUY2 = 0x45;
export const SVGA3D_DEVCAP_DEAD4 = 0x46;
export const SVGA3D_DEVCAP_DEAD5 = 0x47;
export const SVGA3D_DEVCAP_DEAD7 = 0x48;
export const SVGA3D_DEVCAP_DEAD6 = 0x49;
export const SVGA3D_DEVCAP_AUTOGENMIPMAPS = 0x4A;
export const SVGA3D_DEVCAP_SURFACEFMT_NV12 = 0x4B;
export const SVGA3D_DEVCAP_DEAD10 = 0x4C;
export const SVGA3D_DEVCAP_MAX_CONTEXT_IDS = 0x4D;
export const SVGA3D_DEVCAP_MAX_SURFACE_IDS = 0x4E;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_DF16 = 0x4F;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_DF24 = 0x50;
export const SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT = 0x51;
export const SVGA3D_DEVCAP_SURFACEFMT_ATI1 = 0x52;
export const SVGA3D_DEVCAP_SURFACEFMT_ATI2 = 0x53;
export const SVGA3D_DEVCAP_DEAD1 = 0x54;
export const SVGA3D_DEVCAP_DEAD8 = 0x55;
export const SVGA3D_DEVCAP_DEAD9 = 0x56;
export const SVGA3D_DEVCAP_LINE_AA = 0x57;
export const SVGA3D_DEVCAP_LINE_STIPPLE = 0x58;
export const SVGA3D_DEVCAP_MAX_LINE_WIDTH = 0x59;
export const SVGA3D_DEVCAP_MAX_AA_LINE_WIDTH = 0x5A;
export const SVGA3D_DEVCAP_SURFACEFMT_YV12 = 0x5B;
export const SVGA3D_DEVCAP_DEAD3 = 0x5C;
export const SVGA3D_DEVCAP_TS_COLOR_KEY = 0x5D;
export const SVGA3D_DEVCAP_DEAD2 = 0x5E;
export const SVGA3D_DEVCAP_DXCONTEXT = 0x5F;
export const SVGA3D_DEVCAP_DEAD11 = 0x60;
export const SVGA3D_DEVCAP_DX_MAX_VERTEXBUFFERS = 0x61;
export const SVGA3D_DEVCAP_DX_MAX_CONSTANT_BUFFERS = 0x62;
export const SVGA3D_DEVCAP_DX_PROVOKING_VERTEX = 0x63;
export const SVGA3D_DEVCAP_DXFMT_X8R8G8B8 = 0x64;
export const SVGA3D_DEVCAP_DXFMT_A8R8G8B8 = 0x65;
export const SVGA3D_DEVCAP_DXFMT_R5G6B5 = 0x66;
export const SVGA3D_DEVCAP_DXFMT_X1R5G5B5 = 0x67;
export const SVGA3D_DEVCAP_DXFMT_A1R5G5B5 = 0x68;
export const SVGA3D_DEVCAP_DXFMT_A4R4G4B4 = 0x69;
export const SVGA3D_DEVCAP_DXFMT_Z_D32 = 0x6A;
export const SVGA3D_DEVCAP_DXFMT_Z_D16 = 0x6B;
export const SVGA3D_DEVCAP_DXFMT_Z_D24S8 = 0x6C;
export const SVGA3D_DEVCAP_DXFMT_Z_D15S1 = 0x6D;
export const SVGA3D_DEVCAP_DXFMT_LUMINANCE8 = 0x6E;
export const SVGA3D_DEVCAP_DXFMT_LUMINANCE4_ALPHA4 = 0x6F;
export const SVGA3D_DEVCAP_DXFMT_LUMINANCE16 = 0x70;
export const SVGA3D_DEVCAP_DXFMT_LUMINANCE8_ALPHA8 = 0x71;
export const SVGA3D_DEVCAP_DXFMT_DXT1 = 0x72;
export const SVGA3D_DEVCAP_DXFMT_DXT2 = 0x73;
export const SVGA3D_DEVCAP_DXFMT_DXT3 = 0x74;
export const SVGA3D_DEVCAP_DXFMT_DXT4 = 0x75;
export const SVGA3D_DEVCAP_DXFMT_DXT5 = 0x76;
export const SVGA3D_DEVCAP_DXFMT_BUMPU8V8 = 0x77;
export const SVGA3D_DEVCAP_DXFMT_BUMPL6V5U5 = 0x78;
export const SVGA3D_DEVCAP_DXFMT_BUMPX8L8V8U8 = 0x79;
export const SVGA3D_DEVCAP_DXFMT_FORMAT_DEAD1 = 0x7A;
export const SVGA3D_DEVCAP_DXFMT_ARGB_S10E5 = 0x7B;
export const SVGA3D_DEVCAP_DXFMT_ARGB_S23E8 = 0x7C;
export const SVGA3D_DEVCAP_DXFMT_A2R10G10B10 = 0x7D;
export const SVGA3D_DEVCAP_DXFMT_V8U8 = 0x7E;
export const SVGA3D_DEVCAP_DXFMT_Q8W8V8U8 = 0x7F;
export const SVGA3D_DEVCAP_DXFMT_CxV8U8 = 0x80;
export const SVGA3D_DEVCAP_DXFMT_X8L8V8U8 = 0x81;
export const SVGA3D_DEVCAP_DXFMT_A2W10V10U10 = 0x82;
export const SVGA3D_DEVCAP_DXFMT_ALPHA8 = 0x83;
export const SVGA3D_DEVCAP_DXFMT_R_S10E5 = 0x84;
export const SVGA3D_DEVCAP_DXFMT_R_S23E8 = 0x85;
export const SVGA3D_DEVCAP_DXFMT_RG_S10E5 = 0x86;
export const SVGA3D_DEVCAP_DXFMT_RG_S23E8 = 0x87;
export const SVGA3D_DEVCAP_DXFMT_BUFFER = 0x88;
export const SVGA3D_DEVCAP_DXFMT_Z_D24X8 = 0x89;
export const SVGA3D_DEVCAP_DXFMT_V16U16 = 0x8A;
export const SVGA3D_DEVCAP_DXFMT_G16R16 = 0x8B;
export const SVGA3D_DEVCAP_DXFMT_A16B16G16R16 = 0x8C;
export const SVGA3D_DEVCAP_DXFMT_UYVY = 0x8D;
export const SVGA3D_DEVCAP_DXFMT_YUY2 = 0x8E;
export const SVGA3D_DEVCAP_DXFMT_NV12 = 0x8F;
export const SVGA3D_DEVCAP_DXFMT_FORMAT_DEAD2 = 0x90;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32A32_TYPELESS = 0x91;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32A32_UINT = 0x92;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32A32_SINT = 0x93;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32_TYPELESS = 0x94;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32_FLOAT = 0x95;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32_UINT = 0x96;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32_SINT = 0x97;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_TYPELESS = 0x98;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_UINT = 0x99;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_SNORM = 0x9A;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_SINT = 0x9B;
export const SVGA3D_DEVCAP_DXFMT_R32G32_TYPELESS = 0x9C;
export const SVGA3D_DEVCAP_DXFMT_R32G32_UINT = 0x9D;
export const SVGA3D_DEVCAP_DXFMT_R32G32_SINT = 0x9E;
export const SVGA3D_DEVCAP_DXFMT_R32G8X24_TYPELESS = 0x9F;
export const SVGA3D_DEVCAP_DXFMT_D32_FLOAT_S8X24_UINT = 0xA0;
export const SVGA3D_DEVCAP_DXFMT_R32_FLOAT_X8X24 = 0xA1;
export const SVGA3D_DEVCAP_DXFMT_X32_G8X24_UINT = 0xA2;
export const SVGA3D_DEVCAP_DXFMT_R10G10B10A2_TYPELESS = 0xA3;
export const SVGA3D_DEVCAP_DXFMT_R10G10B10A2_UINT = 0xA4;
export const SVGA3D_DEVCAP_DXFMT_R11G11B10_FLOAT = 0xA5;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_TYPELESS = 0xA6;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UNORM = 0xA7;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UNORM_SRGB = 0xA8;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UINT = 0xA9;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_SINT = 0xAA;
export const SVGA3D_DEVCAP_DXFMT_R16G16_TYPELESS = 0xAB;
export const SVGA3D_DEVCAP_DXFMT_R16G16_UINT = 0xAC;
export const SVGA3D_DEVCAP_DXFMT_R16G16_SINT = 0xAD;
export const SVGA3D_DEVCAP_DXFMT_R32_TYPELESS = 0xAE;
export const SVGA3D_DEVCAP_DXFMT_D32_FLOAT = 0xAF;
export const SVGA3D_DEVCAP_DXFMT_R32_UINT = 0xB0;
export const SVGA3D_DEVCAP_DXFMT_R32_SINT = 0xB1;
export const SVGA3D_DEVCAP_DXFMT_R24G8_TYPELESS = 0xB2;
export const SVGA3D_DEVCAP_DXFMT_D24_UNORM_S8_UINT = 0xB3;
export const SVGA3D_DEVCAP_DXFMT_R24_UNORM_X8 = 0xB4;
export const SVGA3D_DEVCAP_DXFMT_X24_G8_UINT = 0xB5;
export const SVGA3D_DEVCAP_DXFMT_R8G8_TYPELESS = 0xB6;
export const SVGA3D_DEVCAP_DXFMT_R8G8_UNORM = 0xB7;
export const SVGA3D_DEVCAP_DXFMT_R8G8_UINT = 0xB8;
export const SVGA3D_DEVCAP_DXFMT_R8G8_SINT = 0xB9;
export const SVGA3D_DEVCAP_DXFMT_R16_TYPELESS = 0xBA;
export const SVGA3D_DEVCAP_DXFMT_R16_UNORM = 0xBB;
export const SVGA3D_DEVCAP_DXFMT_R16_UINT = 0xBC;
export const SVGA3D_DEVCAP_DXFMT_R16_SNORM = 0xBD;
export const SVGA3D_DEVCAP_DXFMT_R16_SINT = 0xBE;
export const SVGA3D_DEVCAP_DXFMT_R8_TYPELESS = 0xBF;
export const SVGA3D_DEVCAP_DXFMT_R8_UNORM = 0xC0;
export const SVGA3D_DEVCAP_DXFMT_R8_UINT = 0xC1;
export const SVGA3D_DEVCAP_DXFMT_R8_SNORM = 0xC2;
export const SVGA3D_DEVCAP_DXFMT_R8_SINT = 0xC3;
export const SVGA3D_DEVCAP_DXFMT_P8 = 0xC4;
export const SVGA3D_DEVCAP_DXFMT_R9G9B9E5_SHAREDEXP = 0xC5;
export const SVGA3D_DEVCAP_DXFMT_R8G8_B8G8_UNORM = 0xC6;
export const SVGA3D_DEVCAP_DXFMT_G8R8_G8B8_UNORM = 0xC7;
export const SVGA3D_DEVCAP_DXFMT_BC1_TYPELESS = 0xC8;
export const SVGA3D_DEVCAP_DXFMT_BC1_UNORM_SRGB = 0xC9;
export const SVGA3D_DEVCAP_DXFMT_BC2_TYPELESS = 0xCA;
export const SVGA3D_DEVCAP_DXFMT_BC2_UNORM_SRGB = 0xCB;
export const SVGA3D_DEVCAP_DXFMT_BC3_TYPELESS = 0xCC;
export const SVGA3D_DEVCAP_DXFMT_BC3_UNORM_SRGB = 0xCD;
export const SVGA3D_DEVCAP_DXFMT_BC4_TYPELESS = 0xCE;
export const SVGA3D_DEVCAP_DXFMT_ATI1 = 0xCF;
export const SVGA3D_DEVCAP_DXFMT_BC4_SNORM = 0xD0;
export const SVGA3D_DEVCAP_DXFMT_BC5_TYPELESS = 0xD1;
export const SVGA3D_DEVCAP_DXFMT_ATI2 = 0xD2;
export const SVGA3D_DEVCAP_DXFMT_BC5_SNORM = 0xD3;
export const SVGA3D_DEVCAP_DXFMT_R10G10B10_XR_BIAS_A2_UNORM = 0xD4;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8A8_TYPELESS = 0xD5;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8A8_UNORM_SRGB = 0xD6;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8X8_TYPELESS = 0xD7;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM_SRGB = 0xD8;
export const SVGA3D_DEVCAP_DXFMT_Z_DF16 = 0xD9;
export const SVGA3D_DEVCAP_DXFMT_Z_DF24 = 0xDA;
export const SVGA3D_DEVCAP_DXFMT_Z_D24S8_INT = 0xDB;
export const SVGA3D_DEVCAP_DXFMT_YV12 = 0xDC;
export const SVGA3D_DEVCAP_DXFMT_R32G32B32A32_FLOAT = 0xDD;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_FLOAT = 0xDE;
export const SVGA3D_DEVCAP_DXFMT_R16G16B16A16_UNORM = 0xDF;
export const SVGA3D_DEVCAP_DXFMT_R32G32_FLOAT = 0xE0;
export const SVGA3D_DEVCAP_DXFMT_R10G10B10A2_UNORM = 0xE1;
export const SVGA3D_DEVCAP_DXFMT_R8G8B8A8_SNORM = 0xE2;
export const SVGA3D_DEVCAP_DXFMT_R16G16_FLOAT = 0xE3;
export const SVGA3D_DEVCAP_DXFMT_R16G16_UNORM = 0xE4;
export const SVGA3D_DEVCAP_DXFMT_R16G16_SNORM = 0xE5;
export const SVGA3D_DEVCAP_DXFMT_R32_FLOAT = 0xE6;
export const SVGA3D_DEVCAP_DXFMT_R8G8_SNORM = 0xE7;
export const SVGA3D_DEVCAP_DXFMT_R16_FLOAT = 0xE8;
export const SVGA3D_DEVCAP_DXFMT_D16_UNORM = 0xE9;
export const SVGA3D_DEVCAP_DXFMT_A8_UNORM = 0xEA;
export const SVGA3D_DEVCAP_DXFMT_BC1_UNORM = 0xEB;
export const SVGA3D_DEVCAP_DXFMT_BC2_UNORM = 0xEC;
export const SVGA3D_DEVCAP_DXFMT_BC3_UNORM = 0xED;
export const SVGA3D_DEVCAP_DXFMT_B5G6R5_UNORM = 0xEE;
export const SVGA3D_DEVCAP_DXFMT_B5G5R5A1_UNORM = 0xEF;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8A8_UNORM = 0xF0;
export const SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM = 0xF1;
export const SVGA3D_DEVCAP_DXFMT_BC4_UNORM = 0xF2;
export const SVGA3D_DEVCAP_DXFMT_BC5_UNORM = 0xF3;
export const SVGA3D_DEVCAP_SM41 = 0xF4;
export const SVGA3D_DEVCAP_MULTISAMPLE_2X = 0xF5;
export const SVGA3D_DEVCAP_MULTISAMPLE_4X = 0xF6;
export const SVGA3D_DEVCAP_MS_FULL_QUALITY = 0xF7;
export const SVGA3D_DEVCAP_LOGICOPS = 0xF8;
export const SVGA3D_DEVCAP_LOGIC_BLENDOPS = 0xF9;
export const SVGA3D_DEVCAP_DEAD12 = 0xFA;
export const SVGA3D_DEVCAP_DXFMT_BC6H_TYPELESS = 0xFB;
export const SVGA3D_DEVCAP_DXFMT_BC6H_UF16 = 0xFC;
export const SVGA3D_DEVCAP_DXFMT_BC6H_SF16 = 0xFD;
export const SVGA3D_DEVCAP_DXFMT_BC7_TYPELESS = 0xFE;
export const SVGA3D_DEVCAP_DXFMT_BC7_UNORM = 0xFF;
export const SVGA3D_DEVCAP_DXFMT_BC7_UNORM_SRGB = 0x100;
export const SVGA3D_DEVCAP_DEAD13 = 0x101;
export const SVGA3D_DEVCAP_SM5 = 0x102;
export const SVGA3D_DEVCAP_MULTISAMPLE_8X = 0x103;
export const SVGA3D_DEVCAP_MAX_FORCED_SAMPLE_COUNT = 0x104;
export const SVGA3D_DEVCAP_GL43 = 0x105;
export const SVGA3D_DEVCAP_MAX = 0x106;
export const SVGA3D_DXFMT_SUPPORTED = 1;
export const SVGA3D_DXFMT_SHADER_SAMPLE = 2;
export const SVGA3D_DXFMT_COLOR_RENDERTARGET = 4;
export const SVGA3D_DXFMT_DEPTH_RENDERTARGET = 8;
export const SVGA3D_DXFMT_BLENDABLE = 0x10;
export const SVGA3D_DXFMT_MIPS = 0x20;
export const SVGA3D_DXFMT_ARRAY = 0x40;
export const SVGA3D_DXFMT_VOLUME = 0x80;
export const SVGA3D_DXFMT_DX_VERTEX_BUFFER = 0x100;
export const SVGA3D_DXFMT_MULTISAMPLE = 0x200;
export const SVGA3D_DXFMT_MAX = 0x400;

// svga3d_shaderdefs.h
export const SVGA3D_INPUTREG_MAX = 0x10;
export const SVGA3D_OUTPUTREG_MAX = 0xC;
export const SVGA3D_VERTEX_SAMPLERREG_MAX = 4;
export const SVGA3D_PIXEL_SAMPLERREG_MAX = 0x10;
export const SVGA3D_SAMPLERREG_MAX = 0x14;
export const SVGA3D_TEMPREG_MAX = 0x20;
export const SVGA3D_ADDRREG_MAX = 1;
export const SVGA3D_PREDREG_MAX = 1;
export const SVGA3D_MAX_SRC_REGS = 4;
export const SVGA3D_MAX_NESTING_LEVEL = 0x20;
export const SVGA3D_VS_TYPE = 0xFFFE;
export const SVGA3D_PS_TYPE = 0xFFFF;
export const SVGA3D_VS_10 = 0xFFFE0100;
export const SVGA3D_VS_11 = 0xFFFE0101;
export const SVGA3D_VS_20 = 0xFFFE0200;
export const SVGA3D_VS_21 = 0xFFFE0201;
export const SVGA3D_VS_30 = 0xFFFE0300;
export const SVGA3D_PS_10 = 0xFFFF0100;
export const SVGA3D_PS_11 = 0xFFFF0101;
export const SVGA3D_PS_12 = 0xFFFF0102;
export const SVGA3D_PS_13 = 0xFFFF0103;
export const SVGA3D_PS_14 = 0xFFFF0104;
export const SVGA3D_PS_20 = 0xFFFF0200;
export const SVGA3D_PS_21 = 0xFFFF0201;
export const SVGA3D_PS_30 = 0xFFFF0300;
export const SVGA3DPSVERSION_NONE = 0;
export const SVGA3DPSVERSION_ENABLED = 1;
export const SVGA3DPSVERSION_11 = 3;
export const SVGA3DPSVERSION_12 = 5;
export const SVGA3DPSVERSION_13 = 7;
export const SVGA3DPSVERSION_14 = 9;
export const SVGA3DPSVERSION_20 = 0xB;
export const SVGA3DPSVERSION_30 = 0xD;
export const SVGA3DPSVERSION_40 = 0xF;
export const SVGA3DPSVERSION_MAX = 0x10;
export const SVGA3DVSVERSION_NONE = 0;
export const SVGA3DVSVERSION_ENABLED = 1;
export const SVGA3DVSVERSION_11 = 3;
export const SVGA3DVSVERSION_20 = 5;
export const SVGA3DVSVERSION_30 = 7;
export const SVGA3DVSVERSION_40 = 9;
export const SVGA3DVSVERSION_MAX = 0xA;
export const SVGA3DOP_NOP = 0;
export const SVGA3DOP_MOV = 1;
export const SVGA3DOP_ADD = 2;
export const SVGA3DOP_SUB = 3;
export const SVGA3DOP_MAD = 4;
export const SVGA3DOP_MUL = 5;
export const SVGA3DOP_RCP = 6;
export const SVGA3DOP_RSQ = 7;
export const SVGA3DOP_DP3 = 8;
export const SVGA3DOP_DP4 = 9;
export const SVGA3DOP_MIN = 0xA;
export const SVGA3DOP_MAX = 0xB;
export const SVGA3DOP_SLT = 0xC;
export const SVGA3DOP_SGE = 0xD;
export const SVGA3DOP_EXP = 0xE;
export const SVGA3DOP_LOG = 0xF;
export const SVGA3DOP_LIT = 0x10;
export const SVGA3DOP_DST = 0x11;
export const SVGA3DOP_LRP = 0x12;
export const SVGA3DOP_FRC = 0x13;
export const SVGA3DOP_M4x4 = 0x14;
export const SVGA3DOP_M4x3 = 0x15;
export const SVGA3DOP_M3x4 = 0x16;
export const SVGA3DOP_M3x3 = 0x17;
export const SVGA3DOP_M3x2 = 0x18;
export const SVGA3DOP_CALL = 0x19;
export const SVGA3DOP_CALLNZ = 0x1A;
export const SVGA3DOP_LOOP = 0x1B;
export const SVGA3DOP_RET = 0x1C;
export const SVGA3DOP_ENDLOOP = 0x1D;
export const SVGA3DOP_LABEL = 0x1E;
export const SVGA3DOP_DCL = 0x1F;
export const SVGA3DOP_POW = 0x20;
export const SVGA3DOP_CRS = 0x21;
export const SVGA3DOP_SGN = 0x22;
export const SVGA3DOP_ABS = 0x23;
export const SVGA3DOP_NRM = 0x24;
export const SVGA3DOP_SINCOS = 0x25;
export const SVGA3DOP_REP = 0x26;
export const SVGA3DOP_ENDREP = 0x27;
export const SVGA3DOP_IF = 0x28;
export const SVGA3DOP_IFC = 0x29;
export const SVGA3DOP_ELSE = 0x2A;
export const SVGA3DOP_ENDIF = 0x2B;
export const SVGA3DOP_BREAK = 0x2C;
export const SVGA3DOP_BREAKC = 0x2D;
export const SVGA3DOP_MOVA = 0x2E;
export const SVGA3DOP_DEFB = 0x2F;
export const SVGA3DOP_DEFI = 0x30;
export const SVGA3DOP_TEXCOORD = 0x40;
export const SVGA3DOP_TEXKILL = 0x41;
export const SVGA3DOP_TEX = 0x42;
export const SVGA3DOP_TEXBEM = 0x43;
export const SVGA3DOP_TEXBEML = 0x44;
export const SVGA3DOP_TEXREG2AR = 0x45;
export const SVGA3DOP_TEXREG2GB = 0x46;
export const SVGA3DOP_TEXM3x2PAD = 0x47;
export const SVGA3DOP_TEXM3x2TEX = 0x48;
export const SVGA3DOP_TEXM3x3PAD = 0x49;
export const SVGA3DOP_TEXM3x3TEX = 0x4A;
export const SVGA3DOP_RESERVED0 = 0x4B;
export const SVGA3DOP_TEXM3x3SPEC = 0x4C;
export const SVGA3DOP_TEXM3x3VSPEC = 0x4D;
export const SVGA3DOP_EXPP = 0x4E;
export const SVGA3DOP_LOGP = 0x4F;
export const SVGA3DOP_CND = 0x50;
export const SVGA3DOP_DEF = 0x51;
export const SVGA3DOP_TEXREG2RGB = 0x52;
export const SVGA3DOP_TEXDP3TEX = 0x53;
export const SVGA3DOP_TEXM3x2DEPTH = 0x54;
export const SVGA3DOP_TEXDP3 = 0x55;
export const SVGA3DOP_TEXM3x3 = 0x56;
export const SVGA3DOP_TEXDEPTH = 0x57;
export const SVGA3DOP_CMP = 0x58;
export const SVGA3DOP_BEM = 0x59;
export const SVGA3DOP_DP2ADD = 0x5A;
export const SVGA3DOP_DSX = 0x5B;
export const SVGA3DOP_DSY = 0x5C;
export const SVGA3DOP_TEXLDD = 0x5D;
export const SVGA3DOP_SETP = 0x5E;
export const SVGA3DOP_TEXLDL = 0x5F;
export const SVGA3DOP_BREAKP = 0x60;
export const SVGA3DOP_LAST_INST = 0x61;
export const SVGA3DOP_PHASE = 0xFFFD;
export const SVGA3DOP_COMMENT = 0xFFFE;
export const SVGA3DOP_END = 0xFFFF;
export const SVGA3DOPCONT_NONE = 0;
export const SVGA3DOPCONT_PROJECT = 1;
export const SVGA3DOPCONT_BIAS = 2;
export const SVGA3DOPCOMP_RESERVED0 = 0;
export const SVGA3DOPCOMP_GT = 1;
export const SVGA3DOPCOMP_EQ = 2;
export const SVGA3DOPCOMP_GE = 3;
export const SVGA3DOPCOMP_LT = 4;
export const SVGA3DOPCOMP_NE = 5;
export const SVGA3DOPCOMP_LE = 6;
export const SVGA3DOPCOMP_RESERVED1 = 7;
export const SVGA3DREG_TEMP = 0;
export const SVGA3DREG_INPUT = 1;
export const SVGA3DREG_CONST = 2;
export const SVGA3DREG_ADDR = 3;
export const SVGA3DREG_TEXTURE = 3;
export const SVGA3DREG_RASTOUT = 4;
export const SVGA3DREG_ATTROUT = 5;
export const SVGA3DREG_TEXCRDOUT = 6;
export const SVGA3DREG_OUTPUT = 6;
export const SVGA3DREG_CONSTINT = 7;
export const SVGA3DREG_COLOROUT = 8;
export const SVGA3DREG_DEPTHOUT = 9;
export const SVGA3DREG_SAMPLER = 0xA;
export const SVGA3DREG_CONST2 = 0xB;
export const SVGA3DREG_CONST3 = 0xC;
export const SVGA3DREG_CONST4 = 0xD;
export const SVGA3DREG_CONSTBOOL = 0xE;
export const SVGA3DREG_LOOP = 0xF;
export const SVGA3DREG_TEMPFLOAT16 = 0x10;
export const SVGA3DREG_MISCTYPE = 0x11;
export const SVGA3DREG_LABEL = 0x12;
export const SVGA3DREG_PREDICATE = 0x13;
export const SVGA3DRASTOUT_POSITION = 0;
export const SVGA3DRASTOUT_FOG = 1;
export const SVGA3DRASTOUT_PSIZE = 2;
export const SVGA3DMISCREG_POSITION = 0;
export const SVGA3DMISCREG_FACE = 1;
export const SVGA3DSAMP_UNKNOWN = 0;
export const SVGA3DSAMP_2D = 2;
export const SVGA3DSAMP_CUBE = 3;
export const SVGA3DSAMP_VOLUME = 4;
export const SVGA3DSAMP_2D_SHADOW = 5;
export const SVGA3DSAMP_MAX = 6;
export const SVGA3DWRITEMASK_0 = 1;
export const SVGA3DWRITEMASK_1 = 2;
export const SVGA3DWRITEMASK_2 = 4;
export const SVGA3DWRITEMASK_3 = 8;
export const SVGA3DWRITEMASK_ALL = 0xF;
export const SVGA3DDSTMOD_NONE = 0;
export const SVGA3DDSTMOD_SATURATE = 1;
export const SVGA3DDSTMOD_PARTIALPRECISION = 2;
export const SVGA3DDSTMOD_MSAMPCENTROID = 4;
export const SVGA3DDSTSHFSCALE_X1 = 0;
export const SVGA3DDSTSHFSCALE_X2 = 1;
export const SVGA3DDSTSHFSCALE_X4 = 2;
export const SVGA3DDSTSHFSCALE_X8 = 3;
export const SVGA3DDSTSHFSCALE_D8 = 0xD;
export const SVGA3DDSTSHFSCALE_D4 = 0xE;
export const SVGA3DDSTSHFSCALE_D2 = 0xF;
export const SVGA3DSWIZZLE_REPLICATEX = 0;
export const SVGA3DSWIZZLE_REPLICATEY = 0x55;
export const SVGA3DSWIZZLE_REPLICATEZ = 0xAA;
export const SVGA3DSWIZZLE_REPLICATEW = 0xFF;
export const SVGA3DSWIZZLE_NONE = 0xE4;
export const SVGA3DSWIZZLE_YZXW = 0xC9;
export const SVGA3DSWIZZLE_ZXYW = 0xD2;
export const SVGA3DSWIZZLE_WXYZ = 0x1B;
export const SVGA3DSRCMOD_NONE = 0;
export const SVGA3DSRCMOD_NEG = 1;
export const SVGA3DSRCMOD_BIAS = 2;
export const SVGA3DSRCMOD_BIASNEG = 3;
export const SVGA3DSRCMOD_SIGN = 4;
export const SVGA3DSRCMOD_SIGNNEG = 5;
export const SVGA3DSRCMOD_COMP = 6;
export const SVGA3DSRCMOD_X2 = 7;
export const SVGA3DSRCMOD_X2NEG = 8;
export const SVGA3DSRCMOD_DZ = 9;
export const SVGA3DSRCMOD_DW = 0xA;
export const SVGA3DSRCMOD_ABS = 0xB;
export const SVGA3DSRCMOD_ABSNEG = 0xC;
export const SVGA3DSRCMOD_NOT = 0xD;

// svga3d_cmd.h
export const SVGA_3D_CMD_LEGACY_BASE = 0x3E8;
export const SVGA_3D_CMD_BASE = 0x410;
export const SVGA_3D_CMD_SURFACE_DEFINE = 0x410;
export const SVGA_3D_CMD_SURFACE_DESTROY = 0x411;
export const SVGA_3D_CMD_SURFACE_COPY = 0x412;
export const SVGA_3D_CMD_SURFACE_STRETCHBLT = 0x413;
export const SVGA_3D_CMD_SURFACE_DMA = 0x414;
export const SVGA_3D_CMD_CONTEXT_DEFINE = 0x415;
export const SVGA_3D_CMD_CONTEXT_DESTROY = 0x416;
export const SVGA_3D_CMD_SETTRANSFORM = 0x417;
export const SVGA_3D_CMD_SETZRANGE = 0x418;
export const SVGA_3D_CMD_SETRENDERSTATE = 0x419;
export const SVGA_3D_CMD_SETRENDERTARGET = 0x41A;
export const SVGA_3D_CMD_SETTEXTURESTATE = 0x41B;
export const SVGA_3D_CMD_SETMATERIAL = 0x41C;
export const SVGA_3D_CMD_SETLIGHTDATA = 0x41D;
export const SVGA_3D_CMD_SETLIGHTENABLED = 0x41E;
export const SVGA_3D_CMD_SETVIEWPORT = 0x41F;
export const SVGA_3D_CMD_SETCLIPPLANE = 0x420;
export const SVGA_3D_CMD_CLEAR = 0x421;
export const SVGA_3D_CMD_PRESENT = 0x422;
export const SVGA_3D_CMD_SHADER_DEFINE = 0x423;
export const SVGA_3D_CMD_SHADER_DESTROY = 0x424;
export const SVGA_3D_CMD_SET_SHADER = 0x425;
export const SVGA_3D_CMD_SET_SHADER_CONST = 0x426;
export const SVGA_3D_CMD_DRAW_PRIMITIVES = 0x427;
export const SVGA_3D_CMD_SETSCISSORRECT = 0x428;
export const SVGA_3D_CMD_BEGIN_QUERY = 0x429;
export const SVGA_3D_CMD_END_QUERY = 0x42A;
export const SVGA_3D_CMD_WAIT_FOR_QUERY = 0x42B;
export const SVGA_3D_CMD_PRESENT_READBACK = 0x42C;
export const SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN = 0x42D;
export const SVGA_3D_CMD_SURFACE_DEFINE_V2 = 0x42E;
export const SVGA_3D_CMD_GENERATE_MIPMAPS = 0x42F;
export const SVGA_3D_CMD_DEAD4 = 0x430;
export const SVGA_3D_CMD_DEAD5 = 0x431;
export const SVGA_3D_CMD_DEAD6 = 0x432;
export const SVGA_3D_CMD_DEAD7 = 0x433;
export const SVGA_3D_CMD_DEAD8 = 0x434;
export const SVGA_3D_CMD_DEAD9 = 0x435;
export const SVGA_3D_CMD_DEAD10 = 0x436;
export const SVGA_3D_CMD_DEAD11 = 0x437;
export const SVGA_3D_CMD_ACTIVATE_SURFACE = 0x438;
export const SVGA_3D_CMD_DEACTIVATE_SURFACE = 0x439;
export const SVGA_3D_CMD_SCREEN_DMA = 0x43A;
export const SVGA_3D_CMD_DEAD1 = 0x43B;
export const SVGA_3D_CMD_DEAD2 = 0x43C;
export const SVGA_3D_CMD_DEAD12 = 0x43D;
export const SVGA_3D_CMD_DEAD13 = 0x43E;
export const SVGA_3D_CMD_DEAD14 = 0x43F;
export const SVGA_3D_CMD_DEAD15 = 0x440;
export const SVGA_3D_CMD_DEAD16 = 0x441;
export const SVGA_3D_CMD_DEAD17 = 0x442;
export const SVGA_3D_CMD_SET_OTABLE_BASE = 0x443;
export const SVGA_3D_CMD_READBACK_OTABLE = 0x444;
export const SVGA_3D_CMD_DEFINE_GB_MOB = 0x445;
export const SVGA_3D_CMD_DESTROY_GB_MOB = 0x446;
export const SVGA_3D_CMD_DEAD3 = 0x447;
export const SVGA_3D_CMD_UPDATE_GB_MOB_MAPPING = 0x448;
export const SVGA_3D_CMD_DEFINE_GB_SURFACE = 0x449;
export const SVGA_3D_CMD_DESTROY_GB_SURFACE = 0x44A;
export const SVGA_3D_CMD_BIND_GB_SURFACE = 0x44B;
export const SVGA_3D_CMD_COND_BIND_GB_SURFACE = 0x44C;
export const SVGA_3D_CMD_UPDATE_GB_IMAGE = 0x44D;
export const SVGA_3D_CMD_UPDATE_GB_SURFACE = 0x44E;
export const SVGA_3D_CMD_READBACK_GB_IMAGE = 0x44F;
export const SVGA_3D_CMD_READBACK_GB_SURFACE = 0x450;
export const SVGA_3D_CMD_INVALIDATE_GB_IMAGE = 0x451;
export const SVGA_3D_CMD_INVALIDATE_GB_SURFACE = 0x452;
export const SVGA_3D_CMD_DEFINE_GB_CONTEXT = 0x453;
export const SVGA_3D_CMD_DESTROY_GB_CONTEXT = 0x454;
export const SVGA_3D_CMD_BIND_GB_CONTEXT = 0x455;
export const SVGA_3D_CMD_READBACK_GB_CONTEXT = 0x456;
export const SVGA_3D_CMD_INVALIDATE_GB_CONTEXT = 0x457;
export const SVGA_3D_CMD_DEFINE_GB_SHADER = 0x458;
export const SVGA_3D_CMD_DESTROY_GB_SHADER = 0x459;
export const SVGA_3D_CMD_BIND_GB_SHADER = 0x45A;
export const SVGA_3D_CMD_SET_OTABLE_BASE64 = 0x45B;
export const SVGA_3D_CMD_BEGIN_GB_QUERY = 0x45C;
export const SVGA_3D_CMD_END_GB_QUERY = 0x45D;
export const SVGA_3D_CMD_WAIT_FOR_GB_QUERY = 0x45E;
export const SVGA_3D_CMD_NOP = 0x45F;
export const SVGA_3D_CMD_ENABLE_GART = 0x460;
export const SVGA_3D_CMD_DISABLE_GART = 0x461;
export const SVGA_3D_CMD_MAP_MOB_INTO_GART = 0x462;
export const SVGA_3D_CMD_UNMAP_GART_RANGE = 0x463;
export const SVGA_3D_CMD_DEFINE_GB_SCREENTARGET = 0x464;
export const SVGA_3D_CMD_DESTROY_GB_SCREENTARGET = 0x465;
export const SVGA_3D_CMD_BIND_GB_SCREENTARGET = 0x466;
export const SVGA_3D_CMD_UPDATE_GB_SCREENTARGET = 0x467;
export const SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL = 0x468;
export const SVGA_3D_CMD_INVALIDATE_GB_IMAGE_PARTIAL = 0x469;
export const SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE = 0x46A;
export const SVGA_3D_CMD_GB_SCREEN_DMA = 0x46B;
export const SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH = 0x46C;
export const SVGA_3D_CMD_GB_MOB_FENCE = 0x46D;
export const SVGA_3D_CMD_DEFINE_GB_SURFACE_V2 = 0x46E;
export const SVGA_3D_CMD_DEFINE_GB_MOB64 = 0x46F;
export const SVGA_3D_CMD_REDEFINE_GB_MOB64 = 0x470;
export const SVGA_3D_CMD_NOP_ERROR = 0x471;
export const SVGA_3D_CMD_SET_VERTEX_STREAMS = 0x472;
export const SVGA_3D_CMD_SET_VERTEX_DECLS = 0x473;
export const SVGA_3D_CMD_SET_VERTEX_DIVISORS = 0x474;
export const SVGA_3D_CMD_DRAW = 0x475;
export const SVGA_3D_CMD_DRAW_INDEXED = 0x476;
export const SVGA_3D_CMD_DX_MIN = 0x477;
export const SVGA_3D_CMD_DX_DEFINE_CONTEXT = 0x477;
export const SVGA_3D_CMD_DX_DESTROY_CONTEXT = 0x478;
export const SVGA_3D_CMD_DX_BIND_CONTEXT = 0x479;
export const SVGA_3D_CMD_DX_READBACK_CONTEXT = 0x47A;
export const SVGA_3D_CMD_DX_INVALIDATE_CONTEXT = 0x47B;
export const SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER = 0x47C;
export const SVGA_3D_CMD_DX_SET_SHADER_RESOURCES = 0x47D;
export const SVGA_3D_CMD_DX_SET_SHADER = 0x47E;
export const SVGA_3D_CMD_DX_SET_SAMPLERS = 0x47F;
export const SVGA_3D_CMD_DX_DRAW = 0x480;
export const SVGA_3D_CMD_DX_DRAW_INDEXED = 0x481;
export const SVGA_3D_CMD_DX_DRAW_INSTANCED = 0x482;
export const SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED = 0x483;
export const SVGA_3D_CMD_DX_DRAW_AUTO = 0x484;
export const SVGA_3D_CMD_DX_SET_INPUT_LAYOUT = 0x485;
export const SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS = 0x486;
export const SVGA_3D_CMD_DX_SET_INDEX_BUFFER = 0x487;
export const SVGA_3D_CMD_DX_SET_TOPOLOGY = 0x488;
export const SVGA_3D_CMD_DX_SET_RENDERTARGETS = 0x489;
export const SVGA_3D_CMD_DX_SET_BLEND_STATE = 0x48A;
export const SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE = 0x48B;
export const SVGA_3D_CMD_DX_SET_RASTERIZER_STATE = 0x48C;
export const SVGA_3D_CMD_DX_DEFINE_QUERY = 0x48D;
export const SVGA_3D_CMD_DX_DESTROY_QUERY = 0x48E;
export const SVGA_3D_CMD_DX_BIND_QUERY = 0x48F;
export const SVGA_3D_CMD_DX_SET_QUERY_OFFSET = 0x490;
export const SVGA_3D_CMD_DX_BEGIN_QUERY = 0x491;
export const SVGA_3D_CMD_DX_END_QUERY = 0x492;
export const SVGA_3D_CMD_DX_READBACK_QUERY = 0x493;
export const SVGA_3D_CMD_DX_SET_PREDICATION = 0x494;
export const SVGA_3D_CMD_DX_SET_SOTARGETS = 0x495;
export const SVGA_3D_CMD_DX_SET_VIEWPORTS = 0x496;
export const SVGA_3D_CMD_DX_SET_SCISSORRECTS = 0x497;
export const SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW = 0x498;
export const SVGA_3D_CMD_DX_CLEAR_DEPTHSTENCIL_VIEW = 0x499;
export const SVGA_3D_CMD_DX_PRED_COPY_REGION = 0x49A;
export const SVGA_3D_CMD_DX_PRED_COPY = 0x49B;
export const SVGA_3D_CMD_DX_PRESENTBLT = 0x49C;
export const SVGA_3D_CMD_DX_GENMIPS = 0x49D;
export const SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE = 0x49E;
export const SVGA_3D_CMD_DX_READBACK_SUBRESOURCE = 0x49F;
export const SVGA_3D_CMD_DX_INVALIDATE_SUBRESOURCE = 0x4A0;
export const SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW = 0x4A1;
export const SVGA_3D_CMD_DX_DESTROY_SHADERRESOURCE_VIEW = 0x4A2;
export const SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW = 0x4A3;
export const SVGA_3D_CMD_DX_DESTROY_RENDERTARGET_VIEW = 0x4A4;
export const SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW = 0x4A5;
export const SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_VIEW = 0x4A6;
export const SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT = 0x4A7;
export const SVGA_3D_CMD_DX_DESTROY_ELEMENTLAYOUT = 0x4A8;
export const SVGA_3D_CMD_DX_DEFINE_BLEND_STATE = 0x4A9;
export const SVGA_3D_CMD_DX_DESTROY_BLEND_STATE = 0x4AA;
export const SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE = 0x4AB;
export const SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_STATE = 0x4AC;
export const SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE = 0x4AD;
export const SVGA_3D_CMD_DX_DESTROY_RASTERIZER_STATE = 0x4AE;
export const SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE = 0x4AF;
export const SVGA_3D_CMD_DX_DESTROY_SAMPLER_STATE = 0x4B0;
export const SVGA_3D_CMD_DX_DEFINE_SHADER = 0x4B1;
export const SVGA_3D_CMD_DX_DESTROY_SHADER = 0x4B2;
export const SVGA_3D_CMD_DX_BIND_SHADER = 0x4B3;
export const SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT = 0x4B4;
export const SVGA_3D_CMD_DX_DESTROY_STREAMOUTPUT = 0x4B5;
export const SVGA_3D_CMD_DX_SET_STREAMOUTPUT = 0x4B6;
export const SVGA_3D_CMD_DX_SET_COTABLE = 0x4B7;
export const SVGA_3D_CMD_DX_READBACK_COTABLE = 0x4B8;
export const SVGA_3D_CMD_DX_BUFFER_COPY = 0x4B9;
export const SVGA_3D_CMD_DX_TRANSFER_FROM_BUFFER = 0x4BA;
export const SVGA_3D_CMD_DX_SURFACE_COPY_AND_READBACK = 0x4BB;
export const SVGA_3D_CMD_DX_MOVE_QUERY = 0x4BC;
export const SVGA_3D_CMD_DX_BIND_ALL_QUERY = 0x4BD;
export const SVGA_3D_CMD_DX_READBACK_ALL_QUERY = 0x4BE;
export const SVGA_3D_CMD_DX_PRED_TRANSFER_FROM_BUFFER = 0x4BF;
export const SVGA_3D_CMD_DX_MOB_FENCE_64 = 0x4C0;
export const SVGA_3D_CMD_DX_BIND_ALL_SHADER = 0x4C1;
export const SVGA_3D_CMD_DX_HINT = 0x4C2;
export const SVGA_3D_CMD_DX_BUFFER_UPDATE = 0x4C3;
export const SVGA_3D_CMD_DX_SET_VS_CONSTANT_BUFFER_OFFSET = 0x4C4;
export const SVGA_3D_CMD_DX_SET_PS_CONSTANT_BUFFER_OFFSET = 0x4C5;
export const SVGA_3D_CMD_DX_SET_GS_CONSTANT_BUFFER_OFFSET = 0x4C6;
export const SVGA_3D_CMD_DX_SET_HS_CONSTANT_BUFFER_OFFSET = 0x4C7;
export const SVGA_3D_CMD_DX_SET_DS_CONSTANT_BUFFER_OFFSET = 0x4C8;
export const SVGA_3D_CMD_DX_SET_CS_CONSTANT_BUFFER_OFFSET = 0x4C9;
export const SVGA_3D_CMD_DX_COND_BIND_ALL_SHADER = 0x4CA;
export const SVGA_3D_CMD_DX_MAX = 0x4CB;
export const SVGA_3D_CMD_SCREEN_COPY = 0x4CB;
export const SVGA_3D_CMD_RESERVED1 = 0x4CC;
export const SVGA_3D_CMD_RESERVED2 = 0x4CD;
export const SVGA_3D_CMD_RESERVED3 = 0x4CE;
export const SVGA_3D_CMD_RESERVED4 = 0x4CF;
export const SVGA_3D_CMD_RESERVED5 = 0x4D0;
export const SVGA_3D_CMD_RESERVED6 = 0x4D1;
export const SVGA_3D_CMD_RESERVED7 = 0x4D2;
export const SVGA_3D_CMD_RESERVED8 = 0x4D3;
export const SVGA_3D_CMD_GROW_OTABLE = 0x4D4;
export const SVGA_3D_CMD_DX_GROW_COTABLE = 0x4D5;
export const SVGA_3D_CMD_INTRA_SURFACE_COPY = 0x4D6;
export const SVGA_3D_CMD_DEFINE_GB_SURFACE_V3 = 0x4D7;
export const SVGA_3D_CMD_DX_RESOLVE_COPY = 0x4D8;
export const SVGA_3D_CMD_DX_PRED_RESOLVE_COPY = 0x4D9;
export const SVGA_3D_CMD_DX_PRED_CONVERT_REGION = 0x4DA;
export const SVGA_3D_CMD_DX_PRED_CONVERT = 0x4DB;
export const SVGA_3D_CMD_WHOLE_SURFACE_COPY = 0x4DC;
export const SVGA_3D_CMD_DX_DEFINE_UA_VIEW = 0x4DD;
export const SVGA_3D_CMD_DX_DESTROY_UA_VIEW = 0x4DE;
export const SVGA_3D_CMD_DX_CLEAR_UA_VIEW_UINT = 0x4DF;
export const SVGA_3D_CMD_DX_CLEAR_UA_VIEW_FLOAT = 0x4E0;
export const SVGA_3D_CMD_DX_COPY_STRUCTURE_COUNT = 0x4E1;
export const SVGA_3D_CMD_DX_SET_UA_VIEWS = 0x4E2;
export const SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED_INDIRECT = 0x4E3;
export const SVGA_3D_CMD_DX_DRAW_INSTANCED_INDIRECT = 0x4E4;
export const SVGA_3D_CMD_DX_DISPATCH = 0x4E5;
export const SVGA_3D_CMD_DX_DISPATCH_INDIRECT = 0x4E6;
export const SVGA_3D_CMD_WRITE_ZERO_SURFACE = 0x4E7;
export const SVGA_3D_CMD_UPDATE_ZERO_SURFACE = 0x4E8;
export const SVGA_3D_CMD_DX_TRANSFER_TO_BUFFER = 0x4E9;
export const SVGA_3D_CMD_DX_SET_STRUCTURE_COUNT = 0x4EA;
export const SVGA_3D_CMD_LOGICOPS_BITBLT = 0x4EB;
export const SVGA_3D_CMD_LOGICOPS_TRANSBLT = 0x4EC;
export const SVGA_3D_CMD_LOGICOPS_STRETCHBLT = 0x4ED;
export const SVGA_3D_CMD_LOGICOPS_COLORFILL = 0x4EE;
export const SVGA_3D_CMD_LOGICOPS_ALPHABLEND = 0x4EF;
export const SVGA_3D_CMD_LOGICOPS_CLEARTYPEBLEND = 0x4F0;
export const SVGA_3D_CMD_DX_COPY_COTABLE_INTO_MOB = 0x4F1;
export const SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_V2 = 0x4F2;
export const SVGA_3D_CMD_DEFINE_GB_SURFACE_V4 = 0x4F3;
export const SVGA_3D_CMD_DX_SET_CS_UA_VIEWS = 0x4F4;
export const SVGA_3D_CMD_DX_SET_MIN_LOD = 0x4F5;
export const SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW_V2 = 0x4F8;
export const SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT_WITH_MOB = 0x4F9;
export const SVGA_3D_CMD_DX_SET_SHADER_IFACE = 0x4FA;
export const SVGA_3D_CMD_DX_BIND_STREAMOUTPUT = 0x4FB;
export const SVGA_3D_CMD_SURFACE_STRETCHBLT_NON_MS_TO_MS = 0x4FC;
export const SVGA_3D_CMD_DX_BIND_SHADER_IFACE = 0x4FD;
export const SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_MOVE = 0x4FE;
export const SVGA_3D_CMD_DX_PRED_STAGING_COPY = 0x501;
export const SVGA_3D_CMD_DX_STAGING_COPY = 0x502;
export const SVGA_3D_CMD_DX_PRED_STAGING_COPY_REGION = 0x503;
export const SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_V2 = 0x504;
export const SVGA_3D_CMD_DX_SET_INDEX_BUFFER_V2 = 0x505;
export const SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_OFFSET_AND_SIZE = 0x506;
export const SVGA_3D_CMD_DX_SET_INDEX_BUFFER_OFFSET_AND_SIZE = 0x507;
export const SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE_V2 = 0x508;
export const SVGA_3D_CMD_DX_PRED_STAGING_CONVERT_REGION = 0x509;
export const SVGA_3D_CMD_DX_PRED_STAGING_CONVERT = 0x50A;
export const SVGA_3D_CMD_DX_STAGING_BUFFER_COPY = 0x50B;
export const SVGA_3D_CMD_MAX = 0x518;
export const SVGA_3D_CMD_FUTURE_MAX = 0xBB8;
export const SVGA_NUM_3D_CMD = 0x108;
export const SVGA3D_VERTEX_ELEMENT_RESPECT_STREAM = 0x80;
export const SVGA3D_LOTRANSBLT_HONORALPHA = 1;
export const SVGA3D_LOSTRETCHBLT_MIRRORX = 1;
export const SVGA3D_LOSTRETCHBLT_MIRRORY = 2;
export const SVGA3D_LOALPHABLEND_SRCHASALPHA = 1;
export const SVGA3D_CLEARTYPE_INVALID_GAMMA_INDEX = 0xFFFFFFFF;
export const SVGA3D_CLEARTYPE_GAMMA_WIDTH = 0x200;
export const SVGA3D_CLEARTYPE_GAMMA_HEIGHT = 0x10;
export const SVGA_STFLAG_PRIMARY = 1;
export const SVGA_STFLAG_RESERVED = 2;
export const SVGA3D_COND_BIND_GB_SURFACE_FLAG_READBACK = 1;
export const SVGA3D_COND_BIND_GB_SURFACE_FLAG_UPDATE = 2;
export const SVGA_SCREEN_COPY_STATUS_FAILURE = 0;
export const SVGA_SCREEN_COPY_STATUS_SUCCESS = 1;
export const SVGA_SCREEN_COPY_STATUS_INVALID = 0xFFFFFFFF;

// svga3d_dx.h
export const SVGA3D_INPUT_MIN = 0;
export const SVGA3D_INPUT_PER_VERTEX_DATA = 0;
export const SVGA3D_INPUT_PER_INSTANCE_DATA = 1;
export const SVGA3D_INPUT_MAX = 2;
export const SVGA3D_COLOR_WRITE_ENABLE_RED = 1;
export const SVGA3D_COLOR_WRITE_ENABLE_GREEN = 2;
export const SVGA3D_COLOR_WRITE_ENABLE_BLUE = 4;
export const SVGA3D_COLOR_WRITE_ENABLE_ALPHA = 8;
export const SVGA3D_COLOR_WRITE_ENABLE_ALL = 0xF;
export const SVGA3D_DEPTH_WRITE_MASK_ZERO = 0;
export const SVGA3D_DEPTH_WRITE_MASK_ALL = 1;
export const SVGA3D_FILTER_MIP_LINEAR = 1;
export const SVGA3D_FILTER_MAG_LINEAR = 4;
export const SVGA3D_FILTER_MIN_LINEAR = 0x10;
export const SVGA3D_FILTER_ANISOTROPIC = 0x40;
export const SVGA3D_FILTER_COMPARE = 0x80;
export const SVGA3D_CULL_INVALID = 0;
export const SVGA3D_CULL_MIN = 1;
export const SVGA3D_CULL_NONE = 1;
export const SVGA3D_CULL_FRONT = 2;
export const SVGA3D_CULL_BACK = 3;
export const SVGA3D_CULL_MAX = 4;
export const SVGA3D_COMPARISON_INVALID = 0;
export const SVGA3D_COMPARISON_MIN = 1;
export const SVGA3D_COMPARISON_NEVER = 1;
export const SVGA3D_COMPARISON_LESS = 2;
export const SVGA3D_COMPARISON_EQUAL = 3;
export const SVGA3D_COMPARISON_LESS_EQUAL = 4;
export const SVGA3D_COMPARISON_GREATER = 5;
export const SVGA3D_COMPARISON_NOT_EQUAL = 6;
export const SVGA3D_COMPARISON_GREATER_EQUAL = 7;
export const SVGA3D_COMPARISON_ALWAYS = 8;
export const SVGA3D_COMPARISON_MAX = 9;
export const SVGA3D_MULTISAMPLE_RAST_DISABLE = 0;
export const SVGA3D_MULTISAMPLE_RAST_ENABLE = 1;
export const SVGA3D_MULTISAMPLE_RAST_DX_MAX = 1;
export const SVGA3D_MULTISAMPLE_RAST_DISABLE_LINE = 2;
export const SVGA3D_MULTISAMPLE_RAST_MAX = 2;
export const SVGA3D_DX_MAX_VERTEXBUFFERS = 0x20;
export const SVGA3D_DX_MAX_VERTEXINPUTREGISTERS = 0x10;
export const SVGA3D_DX_SM41_MAX_VERTEXINPUTREGISTERS = 0x20;
export const SVGA3D_DX_MAX_SOTARGETS = 4;
export const SVGA3D_DX_MAX_SRVIEWS = 0x80;
export const SVGA3D_DX_MAX_CONSTBUFFERS = 0x10;
export const SVGA3D_DX_MAX_SAMPLERS = 0x10;
export const SVGA3D_DX_MAX_CLASS_INSTANCES = 0xFD;
export const SVGA3D_DXQUERY_FLAG_PREDICATEHINT = 1;
export const SVGADX_QDSTATE_INVALID = -1;
export const SVGADX_QDSTATE_MIN = 0;
export const SVGADX_QDSTATE_IDLE = 0;
export const SVGADX_QDSTATE_ACTIVE = 1;
export const SVGADX_QDSTATE_PENDING = 2;
export const SVGADX_QDSTATE_FINISHED = 3;
export const SVGADX_QDSTATE_MAX = 4;
export const SVGA3D_DX_SO_OFFSET_APPEND = 0xFFFFFFFF;
export const SVGA3D_DX_MAX_VIEWPORTS = 0x10;
export const SVGA3D_DX_MAX_SCISSORRECTS = 0x10;
export const SVGADX_PRESENTBLT_LINEAR = 1;
export const SVGADX_PRESENTBLT_FORCE_SRC_SRGB = 2;
export const SVGADX_PRESENTBLT_FORCE_SRC_XRBIAS = 4;
export const SVGADX_PRESENTBLT_MODE_MAX = 8;
export const SVGA3D_TRANSFER_TO_BUFFER_READBACK = 1;
export const SVGA3D_TRANSFER_TO_BUFFER_FLAGS_MASK = 1;
export const SVGA_DX_HINT_NONE = 0;
export const SVGA_DX_HINT_PREFETCH_OBJECT = 1;
export const SVGA_DX_HINT_PREEVICT_OBJECT = 2;
export const SVGA_DX_HINT_PREFETCH_COBJECT = 3;
export const SVGA_DX_HINT_PREEVICT_COBJECT = 4;
export const SVGA_DX_HINT_MAX = 5;
export const SVGA3D_BUFFEREX_SRV_RAW = 1;
export const SVGA3D_BUFFEREX_SRV_FLAGS_MAX = 2;
export const SVGA3D_BUFFEREX_SRV_FLAGS_MASK = 1;
export const SVGA3D_DXDSVIEW_CREATE_READ_ONLY_DEPTH = 1;
export const SVGA3D_DXDSVIEW_CREATE_READ_ONLY_STENCIL = 2;
export const SVGA3D_DXDSVIEW_CREATE_FLAG_MASK = 3;
export const SVGA3D_UABUFFER_RAW = 1;
export const SVGA3D_UABUFFER_APPEND = 2;
export const SVGA3D_UABUFFER_COUNTER = 4;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_UNDEFINED = 0;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_POSITION = 1;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_CLIP_DISTANCE = 2;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_CULL_DISTANCE = 3;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_RENDER_TARGET_ARRAY_INDEX = 4;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_VIEWPORT_ARRAY_INDEX = 5;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_VERTEX_ID = 6;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_PRIMITIVE_ID = 7;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_INSTANCE_ID = 8;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_IS_FRONT_FACE = 9;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_SAMPLE_INDEX = 0xA;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR = 0xB;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR = 0xC;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR = 0xD;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR = 0xE;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_INSIDE_TESSFACTOR = 0xF;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_INSIDE_TESSFACTOR = 0x10;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR = 0x11;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR = 0x12;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR = 0x13;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 0x14;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 0x15;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 0x16;
export const SVGADX_SIGNATURE_SEMANTIC_NAME_MAX = 0x17;
export const SVGADX_SIGNATURE_REGISTER_COMPONENT_UNKNOWN = 0;
export const SVGADX_SIGNATURE_REGISTER_COMPONENT_UINT32 = 1;
export const SVGADX_SIGNATURE_REGISTER_COMPONENT_INT32 = 2;
export const SVGADX_SIGNATURE_REGISTER_COMPONENT_FLOAT = 3;
export const SVGADX_SIGNATURE_MIN_PRECISION_DEFAULT = 0;
export const SVGADX_SIGNATURE_HEADER_VERSION_0 = 0x8A92D12;
export const SVGA3D_MAX_DX10_STREAMOUT_DECLS = 0x40;
export const SVGA3D_MAX_STREAMOUT_DECLS = 0x200;
export const SVGA3D_DX_SO_NO_RASTERIZED_STREAM = 0xFFFFFFFF;
export const SVGA3D_DX_MAX_CLASS_INSTANCES_PADDED = 0x100;
export const SVGA_MOB_FENCE_FLAG_IRQ = 1;
export const SVGA_MOB_FENCE_MASK = 1;

// VGPU10ShaderTokens.h
export const VGPU10_MAX_VS_INPUTS = 0x10;
export const VGPU10_MAX_VS_OUTPUTS = 0x10;
export const VGPU10_MAX_GS_INPUTS = 0x10;
export const VGPU10_MAX_GS_OUTPUTS = 0x20;
export const VGPU10_MAX_PS_INPUTS = 0x20;
export const VGPU10_MAX_PS_OUTPUTS = 8;
export const VGPU10_MAX_TEMPS = 0x1000;
export const VGPU10_MAX_CONSTANT_BUFFERS = 0xF;
export const VGPU10_MAX_CONSTANT_BUFFER_ELEMENT_COUNT = 0x1000;
export const VGPU10_MAX_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT = 0x1000;
export const VGPU10_MAX_SAMPLERS = 0x10;
export const VGPU10_MAX_RESOURCES = 0x80;
export const VGPU10_MIN_TEXEL_FETCH_OFFSET = -8;
export const VGPU10_MAX_TEXEL_FETCH_OFFSET = 7;
export const VGPU10_1_MAX_VS_INPUTS = 0x20;
export const VGPU10_1_MAX_VS_OUTPUTS = 0x20;
export const VGPU10_1_MAX_GS_INPUTS = 0x20;
export const VGPU11_MAX_HS_INPUT_CONTROL_POINTS = 0x20;
export const VGPU11_MAX_HS_INPUT_PATCH_CONSTANTS = 0x20;
export const VGPU11_MAX_HS_OUTPUT_CP_PHASE_ELEMENTS = 0x20;
export const VGPU11_MAX_HS_OUTPUT_CONTROL_POINTS = 0x20;
export const VGPU11_MAX_HS_OUTPUTS = 0x20;
export const VGPU11_MAX_DS_INPUT_CONTROL_POINTS = 0x20;
export const VGPU11_MAX_DS_INPUT_PATCH_CONSTANTS = 0x20;
export const VGPU11_MAX_DS_OUTPUTS = 0x20;
export const VGPU11_MAX_GS_STREAMS = 4;
export const VGPU11_MAX_FUNCTION_BODIES = 0x100;
export const VGPU11_MAX_FUNCTION_TABLES = 0x100;
export const VGPU11_MAX_INTERFACES = 0xFD;
export const VGPU10_MAX_INPUTS = 0x20;
export const VGPU10_MAX_OUTPUTS = 0x20;
export const VGPU10_MAX_INPUT_PATCH_CONSTANTS = 0x20;
export const VGPU10_PIXEL_SHADER = 0;
export const VGPU10_VERTEX_SHADER = 1;
export const VGPU10_GEOMETRY_SHADER = 2;
export const VGPU10_HULL_SHADER = 3;
export const VGPU10_DOMAIN_SHADER = 4;
export const VGPU10_COMPUTE_SHADER = 5;
export const VGPU10_OPCODE_ADD = 0;
export const VGPU10_OPCODE_AND = 1;
export const VGPU10_OPCODE_BREAK = 2;
export const VGPU10_OPCODE_BREAKC = 3;
export const VGPU10_OPCODE_CALL = 4;
export const VGPU10_OPCODE_CALLC = 5;
export const VGPU10_OPCODE_CASE = 6;
export const VGPU10_OPCODE_CONTINUE = 7;
export const VGPU10_OPCODE_CONTINUEC = 8;
export const VGPU10_OPCODE_CUT = 9;
export const VGPU10_OPCODE_DEFAULT = 0xA;
export const VGPU10_OPCODE_DERIV_RTX = 0xB;
export const VGPU10_OPCODE_DERIV_RTY = 0xC;
export const VGPU10_OPCODE_DISCARD = 0xD;
export const VGPU10_OPCODE_DIV = 0xE;
export const VGPU10_OPCODE_DP2 = 0xF;
export const VGPU10_OPCODE_DP3 = 0x10;
export const VGPU10_OPCODE_DP4 = 0x11;
export const VGPU10_OPCODE_ELSE = 0x12;
export const VGPU10_OPCODE_EMIT = 0x13;
export const VGPU10_OPCODE_EMITTHENCUT = 0x14;
export const VGPU10_OPCODE_ENDIF = 0x15;
export const VGPU10_OPCODE_ENDLOOP = 0x16;
export const VGPU10_OPCODE_ENDSWITCH = 0x17;
export const VGPU10_OPCODE_EQ = 0x18;
export const VGPU10_OPCODE_EXP = 0x19;
export const VGPU10_OPCODE_FRC = 0x1A;
export const VGPU10_OPCODE_FTOI = 0x1B;
export const VGPU10_OPCODE_FTOU = 0x1C;
export const VGPU10_OPCODE_GE = 0x1D;
export const VGPU10_OPCODE_IADD = 0x1E;
export const VGPU10_OPCODE_IF = 0x1F;
export const VGPU10_OPCODE_IEQ = 0x20;
export const VGPU10_OPCODE_IGE = 0x21;
export const VGPU10_OPCODE_ILT = 0x22;
export const VGPU10_OPCODE_IMAD = 0x23;
export const VGPU10_OPCODE_IMAX = 0x24;
export const VGPU10_OPCODE_IMIN = 0x25;
export const VGPU10_OPCODE_IMUL = 0x26;
export const VGPU10_OPCODE_INE = 0x27;
export const VGPU10_OPCODE_INEG = 0x28;
export const VGPU10_OPCODE_ISHL = 0x29;
export const VGPU10_OPCODE_ISHR = 0x2A;
export const VGPU10_OPCODE_ITOF = 0x2B;
export const VGPU10_OPCODE_LABEL = 0x2C;
export const VGPU10_OPCODE_LD = 0x2D;
export const VGPU10_OPCODE_LD_MS = 0x2E;
export const VGPU10_OPCODE_LOG = 0x2F;
export const VGPU10_OPCODE_LOOP = 0x30;
export const VGPU10_OPCODE_LT = 0x31;
export const VGPU10_OPCODE_MAD = 0x32;
export const VGPU10_OPCODE_MIN = 0x33;
export const VGPU10_OPCODE_MAX = 0x34;
export const VGPU10_OPCODE_CUSTOMDATA = 0x35;
export const VGPU10_OPCODE_MOV = 0x36;
export const VGPU10_OPCODE_MOVC = 0x37;
export const VGPU10_OPCODE_MUL = 0x38;
export const VGPU10_OPCODE_NE = 0x39;
export const VGPU10_OPCODE_NOP = 0x3A;
export const VGPU10_OPCODE_NOT = 0x3B;
export const VGPU10_OPCODE_OR = 0x3C;
export const VGPU10_OPCODE_RESINFO = 0x3D;
export const VGPU10_OPCODE_RET = 0x3E;
export const VGPU10_OPCODE_RETC = 0x3F;
export const VGPU10_OPCODE_ROUND_NE = 0x40;
export const VGPU10_OPCODE_ROUND_NI = 0x41;
export const VGPU10_OPCODE_ROUND_PI = 0x42;
export const VGPU10_OPCODE_ROUND_Z = 0x43;
export const VGPU10_OPCODE_RSQ = 0x44;
export const VGPU10_OPCODE_SAMPLE = 0x45;
export const VGPU10_OPCODE_SAMPLE_C = 0x46;
export const VGPU10_OPCODE_SAMPLE_C_LZ = 0x47;
export const VGPU10_OPCODE_SAMPLE_L = 0x48;
export const VGPU10_OPCODE_SAMPLE_D = 0x49;
export const VGPU10_OPCODE_SAMPLE_B = 0x4A;
export const VGPU10_OPCODE_SQRT = 0x4B;
export const VGPU10_OPCODE_SWITCH = 0x4C;
export const VGPU10_OPCODE_SINCOS = 0x4D;
export const VGPU10_OPCODE_UDIV = 0x4E;
export const VGPU10_OPCODE_ULT = 0x4F;
export const VGPU10_OPCODE_UGE = 0x50;
export const VGPU10_OPCODE_UMUL = 0x51;
export const VGPU10_OPCODE_UMAD = 0x52;
export const VGPU10_OPCODE_UMAX = 0x53;
export const VGPU10_OPCODE_UMIN = 0x54;
export const VGPU10_OPCODE_USHR = 0x55;
export const VGPU10_OPCODE_UTOF = 0x56;
export const VGPU10_OPCODE_XOR = 0x57;
export const VGPU10_OPCODE_DCL_RESOURCE = 0x58;
export const VGPU10_OPCODE_DCL_CONSTANT_BUFFER = 0x59;
export const VGPU10_OPCODE_DCL_SAMPLER = 0x5A;
export const VGPU10_OPCODE_DCL_INDEX_RANGE = 0x5B;
export const VGPU10_OPCODE_DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY = 0x5C;
export const VGPU10_OPCODE_DCL_GS_INPUT_PRIMITIVE = 0x5D;
export const VGPU10_OPCODE_DCL_MAX_OUTPUT_VERTEX_COUNT = 0x5E;
export const VGPU10_OPCODE_DCL_INPUT = 0x5F;
export const VGPU10_OPCODE_DCL_INPUT_SGV = 0x60;
export const VGPU10_OPCODE_DCL_INPUT_SIV = 0x61;
export const VGPU10_OPCODE_DCL_INPUT_PS = 0x62;
export const VGPU10_OPCODE_DCL_INPUT_PS_SGV = 0x63;
export const VGPU10_OPCODE_DCL_INPUT_PS_SIV = 0x64;
export const VGPU10_OPCODE_DCL_OUTPUT = 0x65;
export const VGPU10_OPCODE_DCL_OUTPUT_SGV = 0x66;
export const VGPU10_OPCODE_DCL_OUTPUT_SIV = 0x67;
export const VGPU10_OPCODE_DCL_TEMPS = 0x68;
export const VGPU10_OPCODE_DCL_INDEXABLE_TEMP = 0x69;
export const VGPU10_OPCODE_DCL_GLOBAL_FLAGS = 0x6A;
export const VGPU10_OPCODE_VMWARE = 0x6B;
export const VGPU10_OPCODE_LOD = 0x6C;
export const VGPU10_OPCODE_GATHER4 = 0x6D;
export const VGPU10_OPCODE_SAMPLE_POS = 0x6E;
export const VGPU10_OPCODE_SAMPLE_INFO = 0x6F;
export const VGPU10_OPCODE_RESERVED1 = 0x70;
export const VGPU10_OPCODE_HS_DECLS = 0x71;
export const VGPU10_OPCODE_HS_CONTROL_POINT_PHASE = 0x72;
export const VGPU10_OPCODE_HS_FORK_PHASE = 0x73;
export const VGPU10_OPCODE_HS_JOIN_PHASE = 0x74;
export const VGPU10_OPCODE_EMIT_STREAM = 0x75;
export const VGPU10_OPCODE_CUT_STREAM = 0x76;
export const VGPU10_OPCODE_EMITTHENCUT_STREAM = 0x77;
export const VGPU10_OPCODE_INTERFACE_CALL = 0x78;
export const VGPU10_OPCODE_BUFINFO = 0x79;
export const VGPU10_OPCODE_DERIV_RTX_COARSE = 0x7A;
export const VGPU10_OPCODE_DERIV_RTX_FINE = 0x7B;
export const VGPU10_OPCODE_DERIV_RTY_COARSE = 0x7C;
export const VGPU10_OPCODE_DERIV_RTY_FINE = 0x7D;
export const VGPU10_OPCODE_GATHER4_C = 0x7E;
export const VGPU10_OPCODE_GATHER4_PO = 0x7F;
export const VGPU10_OPCODE_GATHER4_PO_C = 0x80;
export const VGPU10_OPCODE_RCP = 0x81;
export const VGPU10_OPCODE_F32TOF16 = 0x82;
export const VGPU10_OPCODE_F16TOF32 = 0x83;
export const VGPU10_OPCODE_UADDC = 0x84;
export const VGPU10_OPCODE_USUBB = 0x85;
export const VGPU10_OPCODE_COUNTBITS = 0x86;
export const VGPU10_OPCODE_FIRSTBIT_HI = 0x87;
export const VGPU10_OPCODE_FIRSTBIT_LO = 0x88;
export const VGPU10_OPCODE_FIRSTBIT_SHI = 0x89;
export const VGPU10_OPCODE_UBFE = 0x8A;
export const VGPU10_OPCODE_IBFE = 0x8B;
export const VGPU10_OPCODE_BFI = 0x8C;
export const VGPU10_OPCODE_BFREV = 0x8D;
export const VGPU10_OPCODE_SWAPC = 0x8E;
export const VGPU10_OPCODE_DCL_STREAM = 0x8F;
export const VGPU10_OPCODE_DCL_FUNCTION_BODY = 0x90;
export const VGPU10_OPCODE_DCL_FUNCTION_TABLE = 0x91;
export const VGPU10_OPCODE_DCL_INTERFACE = 0x92;
export const VGPU10_OPCODE_DCL_INPUT_CONTROL_POINT_COUNT = 0x93;
export const VGPU10_OPCODE_DCL_OUTPUT_CONTROL_POINT_COUNT = 0x94;
export const VGPU10_OPCODE_DCL_TESS_DOMAIN = 0x95;
export const VGPU10_OPCODE_DCL_TESS_PARTITIONING = 0x96;
export const VGPU10_OPCODE_DCL_TESS_OUTPUT_PRIMITIVE = 0x97;
export const VGPU10_OPCODE_DCL_HS_MAX_TESSFACTOR = 0x98;
export const VGPU10_OPCODE_DCL_HS_FORK_PHASE_INSTANCE_COUNT = 0x99;
export const VGPU10_OPCODE_DCL_HS_JOIN_PHASE_INSTANCE_COUNT = 0x9A;
export const VGPU10_OPCODE_DCL_THREAD_GROUP = 0x9B;
export const VGPU10_OPCODE_DCL_UAV_TYPED = 0x9C;
export const VGPU10_OPCODE_DCL_UAV_RAW = 0x9D;
export const VGPU10_OPCODE_DCL_UAV_STRUCTURED = 0x9E;
export const VGPU10_OPCODE_DCL_TGSM_RAW = 0x9F;
export const VGPU10_OPCODE_DCL_TGSM_STRUCTURED = 0xA0;
export const VGPU10_OPCODE_DCL_RESOURCE_RAW = 0xA1;
export const VGPU10_OPCODE_DCL_RESOURCE_STRUCTURED = 0xA2;
export const VGPU10_OPCODE_LD_UAV_TYPED = 0xA3;
export const VGPU10_OPCODE_STORE_UAV_TYPED = 0xA4;
export const VGPU10_OPCODE_LD_RAW = 0xA5;
export const VGPU10_OPCODE_STORE_RAW = 0xA6;
export const VGPU10_OPCODE_LD_STRUCTURED = 0xA7;
export const VGPU10_OPCODE_STORE_STRUCTURED = 0xA8;
export const VGPU10_OPCODE_ATOMIC_AND = 0xA9;
export const VGPU10_OPCODE_ATOMIC_OR = 0xAA;
export const VGPU10_OPCODE_ATOMIC_XOR = 0xAB;
export const VGPU10_OPCODE_ATOMIC_CMP_STORE = 0xAC;
export const VGPU10_OPCODE_ATOMIC_IADD = 0xAD;
export const VGPU10_OPCODE_ATOMIC_IMAX = 0xAE;
export const VGPU10_OPCODE_ATOMIC_IMIN = 0xAF;
export const VGPU10_OPCODE_ATOMIC_UMAX = 0xB0;
export const VGPU10_OPCODE_ATOMIC_UMIN = 0xB1;
export const VGPU10_OPCODE_IMM_ATOMIC_ALLOC = 0xB2;
export const VGPU10_OPCODE_IMM_ATOMIC_CONSUME = 0xB3;
export const VGPU10_OPCODE_IMM_ATOMIC_IADD = 0xB4;
export const VGPU10_OPCODE_IMM_ATOMIC_AND = 0xB5;
export const VGPU10_OPCODE_IMM_ATOMIC_OR = 0xB6;
export const VGPU10_OPCODE_IMM_ATOMIC_XOR = 0xB7;
export const VGPU10_OPCODE_IMM_ATOMIC_EXCH = 0xB8;
export const VGPU10_OPCODE_IMM_ATOMIC_CMP_EXCH = 0xB9;
export const VGPU10_OPCODE_IMM_ATOMIC_IMAX = 0xBA;
export const VGPU10_OPCODE_IMM_ATOMIC_IMIN = 0xBB;
export const VGPU10_OPCODE_IMM_ATOMIC_UMAX = 0xBC;
export const VGPU10_OPCODE_IMM_ATOMIC_UMIN = 0xBD;
export const VGPU10_OPCODE_SYNC = 0xBE;
export const VGPU10_OPCODE_DADD = 0xBF;
export const VGPU10_OPCODE_DMAX = 0xC0;
export const VGPU10_OPCODE_DMIN = 0xC1;
export const VGPU10_OPCODE_DMUL = 0xC2;
export const VGPU10_OPCODE_DEQ = 0xC3;
export const VGPU10_OPCODE_DGE = 0xC4;
export const VGPU10_OPCODE_DLT = 0xC5;
export const VGPU10_OPCODE_DNE = 0xC6;
export const VGPU10_OPCODE_DMOV = 0xC7;
export const VGPU10_OPCODE_DMOVC = 0xC8;
export const VGPU10_OPCODE_DTOF = 0xC9;
export const VGPU10_OPCODE_FTOD = 0xCA;
export const VGPU10_OPCODE_EVAL_SNAPPED = 0xCB;
export const VGPU10_OPCODE_EVAL_SAMPLE_INDEX = 0xCC;
export const VGPU10_OPCODE_EVAL_CENTROID = 0xCD;
export const VGPU10_OPCODE_DCL_GS_INSTANCE_COUNT = 0xCE;
export const VGPU10_OPCODE_ABORT = 0xCF;
export const VGPU10_OPCODE_DEBUG_BREAK = 0xD0;
export const VGPU10_OPCODE_RESERVED0 = 0xD1;
export const VGPU10_OPCODE_DDIV = 0xD2;
export const VGPU10_OPCODE_DFMA = 0xD3;
export const VGPU10_OPCODE_DRCP = 0xD4;
export const VGPU10_OPCODE_MSAD = 0xD5;
export const VGPU10_OPCODE_DTOI = 0xD6;
export const VGPU10_OPCODE_DTOU = 0xD7;
export const VGPU10_OPCODE_ITOD = 0xD8;
export const VGPU10_OPCODE_UTOD = 0xD9;
export const VGPU10_NUM_OPCODES = 0xDA;
export const VGPU10_VMWARE_OPCODE_IDIV = 0;
export const VGPU10_VMWARE_OPCODE_DFRC = 1;
export const VGPU10_VMWARE_OPCODE_DRSQ = 2;
export const VGPU10_VMWARE_NUM_OPCODES = 3;
export const VGPU10_INTERPOLATION_UNDEFINED = 0;
export const VGPU10_INTERPOLATION_CONSTANT = 1;
export const VGPU10_INTERPOLATION_LINEAR = 2;
export const VGPU10_INTERPOLATION_LINEAR_CENTROID = 3;
export const VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE = 4;
export const VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE_CENTROID = 5;
export const VGPU10_INTERPOLATION_LINEAR_SAMPLE = 6;
export const VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE_SAMPLE = 7;
export const VGPU10_RESOURCE_DIMENSION_UNKNOWN = 0;
export const VGPU10_RESOURCE_DIMENSION_BUFFER = 1;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE1D = 2;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE2D = 3;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE2DMS = 4;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE3D = 5;
export const VGPU10_RESOURCE_DIMENSION_TEXTURECUBE = 6;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE1DARRAY = 7;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE2DARRAY = 8;
export const VGPU10_RESOURCE_DIMENSION_TEXTURE2DMSARRAY = 9;
export const VGPU10_RESOURCE_DIMENSION_TEXTURECUBEARRAY = 0xA;
export const VGPU10_RESOURCE_DIMENSION_RAW_BUFFER = 0xB;
export const VGPU10_RESOURCE_DIMENSION_STRUCTURED_BUFFER = 0xC;
export const VGPU10_RESOURCE_DIMENSION_MAX = 0xC;
export const VGPU10_SAMPLER_MODE_DEFAULT = 0;
export const VGPU10_SAMPLER_MODE_COMPARISON = 1;
export const VGPU10_SAMPLER_MODE_MONO = 2;
export const VGPU10_INSTRUCTION_TEST_ZERO = 0;
export const VGPU10_INSTRUCTION_TEST_NONZERO = 1;
export const VGPU10_CB_IMMEDIATE_INDEXED = 0;
export const VGPU10_CB_DYNAMIC_INDEXED = 1;
export const VGPU10_PRIMITIVE_UNDEFINED = 0;
export const VGPU10_PRIMITIVE_POINT = 1;
export const VGPU10_PRIMITIVE_LINE = 2;
export const VGPU10_PRIMITIVE_TRIANGLE = 3;
export const VGPU10_PRIMITIVE_LINE_ADJ = 6;
export const VGPU10_PRIMITIVE_TRIANGLE_ADJ = 7;
export const VGPU10_PRIMITIVE_SM40_MAX = 7;
export const VGPU10_PRIMITIVE_1_CONTROL_POINT_PATCH = 8;
export const VGPU10_PRIMITIVE_2_CONTROL_POINT_PATCH = 9;
export const VGPU10_PRIMITIVE_3_CONTROL_POINT_PATCH = 0xA;
export const VGPU10_PRIMITIVE_4_CONTROL_POINT_PATCH = 0xB;
export const VGPU10_PRIMITIVE_5_CONTROL_POINT_PATCH = 0xC;
export const VGPU10_PRIMITIVE_6_CONTROL_POINT_PATCH = 0xD;
export const VGPU10_PRIMITIVE_7_CONTROL_POINT_PATCH = 0xE;
export const VGPU10_PRIMITIVE_8_CONTROL_POINT_PATCH = 0xF;
export const VGPU10_PRIMITIVE_9_CONTROL_POINT_PATCH = 0x10;
export const VGPU10_PRIMITIVE_10_CONTROL_POINT_PATCH = 0x11;
export const VGPU10_PRIMITIVE_11_CONTROL_POINT_PATCH = 0x12;
export const VGPU10_PRIMITIVE_12_CONTROL_POINT_PATCH = 0x13;
export const VGPU10_PRIMITIVE_13_CONTROL_POINT_PATCH = 0x14;
export const VGPU10_PRIMITIVE_14_CONTROL_POINT_PATCH = 0x15;
export const VGPU10_PRIMITIVE_15_CONTROL_POINT_PATCH = 0x16;
export const VGPU10_PRIMITIVE_16_CONTROL_POINT_PATCH = 0x17;
export const VGPU10_PRIMITIVE_17_CONTROL_POINT_PATCH = 0x18;
export const VGPU10_PRIMITIVE_18_CONTROL_POINT_PATCH = 0x19;
export const VGPU10_PRIMITIVE_19_CONTROL_POINT_PATCH = 0x1A;
export const VGPU10_PRIMITIVE_20_CONTROL_POINT_PATCH = 0x1B;
export const VGPU10_PRIMITIVE_21_CONTROL_POINT_PATCH = 0x1C;
export const VGPU10_PRIMITIVE_22_CONTROL_POINT_PATCH = 0x1D;
export const VGPU10_PRIMITIVE_23_CONTROL_POINT_PATCH = 0x1E;
export const VGPU10_PRIMITIVE_24_CONTROL_POINT_PATCH = 0x1F;
export const VGPU10_PRIMITIVE_25_CONTROL_POINT_PATCH = 0x20;
export const VGPU10_PRIMITIVE_26_CONTROL_POINT_PATCH = 0x21;
export const VGPU10_PRIMITIVE_27_CONTROL_POINT_PATCH = 0x22;
export const VGPU10_PRIMITIVE_28_CONTROL_POINT_PATCH = 0x23;
export const VGPU10_PRIMITIVE_29_CONTROL_POINT_PATCH = 0x24;
export const VGPU10_PRIMITIVE_30_CONTROL_POINT_PATCH = 0x25;
export const VGPU10_PRIMITIVE_31_CONTROL_POINT_PATCH = 0x26;
export const VGPU10_PRIMITIVE_32_CONTROL_POINT_PATCH = 0x27;
export const VGPU10_PRIMITIVE_MAX = 0x27;
export const VGPU10_PRIMITIVE_TOPOLOGY_UNDEFINED = 0;
export const VGPU10_PRIMITIVE_TOPOLOGY_POINTLIST = 1;
export const VGPU10_PRIMITIVE_TOPOLOGY_LINELIST = 2;
export const VGPU10_PRIMITIVE_TOPOLOGY_LINESTRIP = 3;
export const VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4;
export const VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5;
export const VGPU10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 0xA;
export const VGPU10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 0xB;
export const VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 0xC;
export const VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 0xD;
export const VGPU10_CUSTOMDATA_COMMENT = 0;
export const VGPU10_CUSTOMDATA_DEBUGINFO = 1;
export const VGPU10_CUSTOMDATA_OPAQUE = 2;
export const VGPU10_CUSTOMDATA_DCL_IMMEDIATE_CONSTANT_BUFFER = 3;
export const VGPU10_RESINFO_RETURN_FLOAT = 0;
export const VGPU10_RESINFO_RETURN_RCPFLOAT = 1;
export const VGPU10_RESINFO_RETURN_UINT = 2;
export const VGPU10_INSTRUCTION_RETURN_FLOAT = 0;
export const VGPU10_INSTRUCTION_RETURN_UINT = 1;
export const VGPU10_TESSELLATOR_DOMAIN_UNDEFINED = 0;
export const VGPU10_TESSELLATOR_DOMAIN_ISOLINE = 1;
export const VGPU10_TESSELLATOR_DOMAIN_TRI = 2;
export const VGPU10_TESSELLATOR_DOMAIN_QUAD = 3;
export const VGPU10_TESSELLATOR_DOMAIN_MAX = 3;
export const VGPU10_TESSELLATOR_PARTITIONING_UNDEFINED = 0;
export const VGPU10_TESSELLATOR_PARTITIONING_INTEGER = 1;
export const VGPU10_TESSELLATOR_PARTITIONING_POW2 = 2;
export const VGPU10_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD = 3;
export const VGPU10_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN = 4;
export const VGPU10_TESSELLATOR_PARTITIONING_MAX = 4;
export const VGPU10_TESSELLATOR_OUTPUT_UNDEFINED = 0;
export const VGPU10_TESSELLATOR_OUTPUT_POINT = 1;
export const VGPU10_TESSELLATOR_OUTPUT_LINE = 2;
export const VGPU10_TESSELLATOR_OUTPUT_TRIANGLE_CW = 3;
export const VGPU10_TESSELLATOR_OUTPUT_TRIANGLE_CCW = 4;
export const VGPU10_TESSELLATOR_OUTPUT_MAX = 4;
export const VGPU10_EXTENDED_OPCODE_EMPTY = 0;
export const VGPU10_EXTENDED_OPCODE_SAMPLE_CONTROLS = 1;
export const VGPU10_EXTENDED_OPCODE_RESOURCE_DIM = 2;
export const VGPU10_EXTENDED_OPCODE_RESOURCE_RETURN_TYPE = 3;
export const VGPU10_OPERAND_0_COMPONENT = 0;
export const VGPU10_OPERAND_1_COMPONENT = 1;
export const VGPU10_OPERAND_4_COMPONENT = 2;
export const VGPU10_OPERAND_N_COMPONENT = 3;
export const VGPU10_OPERAND_4_COMPONENT_MASK_MODE = 0;
export const VGPU10_OPERAND_4_COMPONENT_SWIZZLE_MODE = 1;
export const VGPU10_OPERAND_4_COMPONENT_SELECT_1_MODE = 2;
export const VGPU10_OPERAND_4_COMPONENT_MASK_X = 1;
export const VGPU10_OPERAND_4_COMPONENT_MASK_Y = 2;
export const VGPU10_OPERAND_4_COMPONENT_MASK_Z = 4;
export const VGPU10_OPERAND_4_COMPONENT_MASK_W = 8;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XY = 3;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XZ = 5;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XW = 9;
export const VGPU10_OPERAND_4_COMPONENT_MASK_YZ = 6;
export const VGPU10_OPERAND_4_COMPONENT_MASK_YW = 0xA;
export const VGPU10_OPERAND_4_COMPONENT_MASK_ZW = 0xC;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XYZ = 7;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XYW = 0xB;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XZW = 0xD;
export const VGPU10_OPERAND_4_COMPONENT_MASK_YZW = 0xE;
export const VGPU10_OPERAND_4_COMPONENT_MASK_XYZW = 0xF;
export const VGPU10_OPERAND_4_COMPONENT_MASK_ALL = 0xF;
export const VGPU10_REGISTER_INDEX_FROM_SEMANTIC = 0xFFFFFFFF;
export const VGPU10_COMPONENT_X = 0;
export const VGPU10_COMPONENT_Y = 1;
export const VGPU10_COMPONENT_Z = 2;
export const VGPU10_COMPONENT_W = 3;
export const VGPU10_OPERAND_TYPE_TEMP = 0;
export const VGPU10_OPERAND_TYPE_INPUT = 1;
export const VGPU10_OPERAND_TYPE_OUTPUT = 2;
export const VGPU10_OPERAND_TYPE_INDEXABLE_TEMP = 3;
export const VGPU10_OPERAND_TYPE_IMMEDIATE32 = 4;
export const VGPU10_OPERAND_TYPE_IMMEDIATE64 = 5;
export const VGPU10_OPERAND_TYPE_SAMPLER = 6;
export const VGPU10_OPERAND_TYPE_RESOURCE = 7;
export const VGPU10_OPERAND_TYPE_CONSTANT_BUFFER = 8;
export const VGPU10_OPERAND_TYPE_IMMEDIATE_CONSTANT_BUFFER = 9;
export const VGPU10_OPERAND_TYPE_LABEL = 0xA;
export const VGPU10_OPERAND_TYPE_INPUT_PRIMITIVEID = 0xB;
export const VGPU10_OPERAND_TYPE_OUTPUT_DEPTH = 0xC;
export const VGPU10_OPERAND_TYPE_NULL = 0xD;
export const VGPU10_OPERAND_TYPE_SM40_MAX = 0xD;
export const VGPU10_OPERAND_TYPE_RASTERIZER = 0xE;
export const VGPU10_OPERAND_TYPE_OUTPUT_COVERAGE_MASK = 0xF;
export const VGPU10_OPERAND_TYPE_SM41_MAX = 0xF;
export const VGPU10_OPERAND_TYPE_STREAM = 0x10;
export const VGPU10_OPERAND_TYPE_FUNCTION_BODY = 0x11;
export const VGPU10_OPERAND_TYPE_FUNCTION_TABLE = 0x12;
export const VGPU10_OPERAND_TYPE_INTERFACE = 0x13;
export const VGPU10_OPERAND_TYPE_FUNCTION_INPUT = 0x14;
export const VGPU10_OPERAND_TYPE_FUNCTION_OUTPUT = 0x15;
export const VGPU10_OPERAND_TYPE_OUTPUT_CONTROL_POINT_ID = 0x16;
export const VGPU10_OPERAND_TYPE_INPUT_FORK_INSTANCE_ID = 0x17;
export const VGPU10_OPERAND_TYPE_INPUT_JOIN_INSTANCE_ID = 0x18;
export const VGPU10_OPERAND_TYPE_INPUT_CONTROL_POINT = 0x19;
export const VGPU10_OPERAND_TYPE_OUTPUT_CONTROL_POINT = 0x1A;
export const VGPU10_OPERAND_TYPE_INPUT_PATCH_CONSTANT = 0x1B;
export const VGPU10_OPERAND_TYPE_INPUT_DOMAIN_POINT = 0x1C;
export const VGPU10_OPERAND_TYPE_THIS_POINTER = 0x1D;
export const VGPU10_OPERAND_TYPE_UAV = 0x1E;
export const VGPU10_OPERAND_TYPE_THREAD_GROUP_SHARED_MEMORY = 0x1F;
export const VGPU10_OPERAND_TYPE_INPUT_THREAD_ID = 0x20;
export const VGPU10_OPERAND_TYPE_INPUT_THREAD_GROUP_ID = 0x21;
export const VGPU10_OPERAND_TYPE_INPUT_THREAD_ID_IN_GROUP = 0x22;
export const VGPU10_OPERAND_TYPE_INPUT_COVERAGE_MASK = 0x23;
export const VGPU10_OPERAND_TYPE_INPUT_THREAD_ID_IN_GROUP_FLATTENED = 0x24;
export const VGPU10_OPERAND_TYPE_INPUT_GS_INSTANCE_ID = 0x25;
export const VGPU10_OPERAND_TYPE_OUTPUT_DEPTH_GREATER_EQUAL = 0x26;
export const VGPU10_OPERAND_TYPE_OUTPUT_DEPTH_LESS_EQUAL = 0x27;
export const VGPU10_OPERAND_TYPE_CYCLE_COUNTER = 0x28;
export const VGPU10_OPERAND_TYPE_SM50_MAX = 0x28;
export const VGPU10_NUM_OPERANDS = 0x29;
export const VGPU10_OPERAND_INDEX_0D = 0;
export const VGPU10_OPERAND_INDEX_1D = 1;
export const VGPU10_OPERAND_INDEX_2D = 2;
export const VGPU10_OPERAND_INDEX_3D = 3;
export const VGPU10_OPERAND_INDEX_IMMEDIATE32 = 0;
export const VGPU10_OPERAND_INDEX_IMMEDIATE64 = 1;
export const VGPU10_OPERAND_INDEX_RELATIVE = 2;
export const VGPU10_OPERAND_INDEX_IMMEDIATE32_PLUS_RELATIVE = 3;
export const VGPU10_OPERAND_INDEX_IMMEDIATE64_PLUS_RELATIVE = 4;
export const VGPU10_EXTENDED_OPERAND_EMPTY = 0;
export const VGPU10_EXTENDED_OPERAND_MODIFIER = 1;
export const VGPU10_OPERAND_MODIFIER_NONE = 0;
export const VGPU10_OPERAND_MODIFIER_NEG = 1;
export const VGPU10_OPERAND_MODIFIER_ABS = 2;
export const VGPU10_OPERAND_MODIFIER_ABSNEG = 3;
export const VGPU10_RETURN_TYPE_MIN = 1;
export const VGPU10_RETURN_TYPE_UNORM = 1;
export const VGPU10_RETURN_TYPE_SNORM = 2;
export const VGPU10_RETURN_TYPE_SINT = 3;
export const VGPU10_RETURN_TYPE_UINT = 4;
export const VGPU10_RETURN_TYPE_FLOAT = 5;
export const VGPU10_RETURN_TYPE_MIXED = 6;
export const VGPU10_RETURN_TYPE_SM40_MAX = 6;
export const VGPU10_RETURN_TYPE_DOUBLE = 7;
export const VGPU10_RETURN_TYPE_CONTINUED = 8;
export const VGPU10_RETURN_TYPE_UNUSED = 9;
export const VGPU10_RETURN_TYPE_MAX = 9;
export const VGPU10_NAME_MIN = 0;
export const VGPU10_NAME_UNDEFINED = 0;
export const VGPU10_NAME_POSITION = 1;
export const VGPU10_NAME_CLIP_DISTANCE = 2;
export const VGPU10_NAME_CULL_DISTANCE = 3;
export const VGPU10_NAME_RENDER_TARGET_ARRAY_INDEX = 4;
export const VGPU10_NAME_VIEWPORT_ARRAY_INDEX = 5;
export const VGPU10_NAME_VERTEX_ID = 6;
export const VGPU10_NAME_PRIMITIVE_ID = 7;
export const VGPU10_NAME_INSTANCE_ID = 8;
export const VGPU10_NAME_IS_FRONT_FACE = 9;
export const VGPU10_NAME_SAMPLE_INDEX = 0xA;
export const VGPU10_NAME_SM40_MAX = 0xA;
export const VGPU10_NAME_FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR = 0xB;
export const VGPU10_NAME_FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR = 0xC;
export const VGPU10_NAME_FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR = 0xD;
export const VGPU10_NAME_FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR = 0xE;
export const VGPU10_NAME_FINAL_QUAD_U_INSIDE_TESSFACTOR = 0xF;
export const VGPU10_NAME_FINAL_QUAD_V_INSIDE_TESSFACTOR = 0x10;
export const VGPU10_NAME_FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR = 0x11;
export const VGPU10_NAME_FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR = 0x12;
export const VGPU10_NAME_FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR = 0x13;
export const VGPU10_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 0x14;
export const VGPU10_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 0x15;
export const VGPU10_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 0x16;
export const VGPU10_NAME_MAX = 0x16;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/graphics_adapters/vmware_svga/svga_cursor.js                                         0000644 0000000 0000000 00000016026 00000000000 021357  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The hardware cursor (SVGA_CAP_CURSOR, ALPHA_CURSOR, CURSOR_BYPASS_3),
// drawn by the device: every render sends, after the picture, a small layer
// with the cursor composed over what is under it, and the picture under its
// old place when it moved. The pictures themselves are never written, so
// blits that land under the cursor need no care.
//
// A monochrome or colour cursor (DEFINE_CURSOR) is an AND mask and an XOR
// mask: shown = (under AND and) XOR xor, which inverts where both are set.
// An alpha cursor (DEFINE_ALPHA_CURSOR) is premultiplied BGRA.

/**
 * @constructor
 */
export function SoftwareCursor()
{
    this.reset();
}

SoftwareCursor.prototype.reset = function()
{
    this.width = 0;
    this.height = 0;
    this.hot_x = 0;
    this.hot_y = 0;
    /** @type {Int32Array} per pixel: AND mask (0 or -1), or null for an alpha cursor */
    this.and = null;
    /** @type {Int32Array} XOR mask as 0xBBGGRR (DEFINE_CURSOR) or premultiplied 0xAARRGGBB */
    this.image = null;
    this.alpha = false;
    this.visible = false;
    this.x = 0;
    this.y = 0;
    // the rectangle drawn last time, in desktop coordinates: erased when it moves
    this.drawn = null;
    this.patch = null;
};

/**
 * DEFINE_CURSOR
 * @param {number} hot_x
 * @param {number} hot_y
 * @param {number} width
 * @param {number} height
 * @param {number} and_depth bits per pixel of the AND mask (1 or 32)
 * @param {number} xor_depth bits per pixel of the XOR mask (1, 8, 24 or 32)
 * @param {function(number):number} read the masks' dwords, AND mask first
 * @param {!Uint8Array} palette 256 RGB entries, for an 8-bit XOR mask
 */
SoftwareCursor.prototype.define = function(hot_x, hot_y, width, height, and_depth, xor_depth, read, palette)
{
    const and_pitch = (width * and_depth + 31) >>> 5;
    const xor_pitch = (width * xor_depth + 31) >>> 5;
    const bit = (offset, pitch, x, y, depth) => {
        const position = x * depth;
        const dword = read(offset + y * pitch + (position >>> 5)) >>> 0;
        if(depth === 1)
        {
            // most significant bit first within each byte
            const byte = dword >>> 8 * (position >>> 3 & 3) & 0xFF;
            return byte >> 7 - (x & 7) & 1;
        }
        if(depth === 8) return dword >>> 8 * (x & 3) & 0xFF;
        return dword;
    };
    this.width = width;
    this.height = height;
    this.hot_x = hot_x;
    this.hot_y = hot_y;
    this.alpha = false;
    this.and = new Int32Array(width * height);
    this.image = new Int32Array(width * height);
    const xor_offset = and_pitch * height;
    for(let y = 0; y < height; y++)
    {
        for(let x = 0; x < width; x++)
        {
            const i = y * width + x;
            const and = bit(0, and_pitch, x, y, and_depth);
            this.and[i] = and_depth === 1 ? (and ? -1 : 0) : and | 0;
            const xor = bit(xor_offset, xor_pitch, x, y, xor_depth);
            if(xor_depth === 1) this.image[i] = xor ? 0xFFFFFF : 0;
            else if(xor_depth === 8) this.image[i] = palette[xor * 3] << 16 | palette[xor * 3 + 1] << 8 | palette[xor * 3 + 2];
            else this.image[i] = xor & 0xFFFFFF;
        }
    }
};

/**
 * The number of dwords of DEFINE_CURSOR's masks
 */
export function cursor_masks_length(width, height, and_depth, xor_depth)
{
    return ((width * and_depth + 31) >>> 5) * height + ((width * xor_depth + 31) >>> 5) * height;
}

/**
 * DEFINE_ALPHA_CURSOR: width * height premultiplied 0xAARRGGBB dwords
 * @param {function(number):number} read
 */
SoftwareCursor.prototype.define_alpha = function(hot_x, hot_y, width, height, read)
{
    this.width = width;
    this.height = height;
    this.hot_x = hot_x;
    this.hot_y = hot_y;
    this.alpha = true;
    this.and = null;
    this.image = new Int32Array(width * height);
    for(let i = 0; i < width * height; i++) this.image[i] = read(i);
};

/**
 * @param {number} x of the hotspot, on the desktop
 * @param {number} y
 * @param {boolean} visible
 */
SoftwareCursor.prototype.move = function(x, y, visible)
{
    this.x = x;
    this.y = y;
    this.visible = visible && this.width > 0;
};

/**
 * The layers to send after the picture's own
 * @param {function(number, number):?{data: !Uint8ClampedArray, at: number}} under where the
 *     picture's pixel at a desktop point is, or null outside of it
 * @param {function(number, number, number, number):!Array<!Object>} region the picture's
 *     layers that cover a desktop rectangle (to erase the cursor)
 * @return {!Array<!Object>}
 */
SoftwareCursor.prototype.layers = function(under, region)
{
    const layers = [];
    const left = this.x - this.hot_x, top = this.y - this.hot_y;
    const moved = !this.drawn || this.drawn[0] !== left || this.drawn[1] !== top || !this.visible;
    if(this.drawn && moved)
    {
        layers.push(...region(this.drawn[0], this.drawn[1], this.drawn[2], this.drawn[3]));
        this.drawn = null;
    }
    if(!this.visible) return layers;

    const width = this.width, height = this.height;
    if(!this.patch || this.patch.length !== width * height * 4)
    {
        this.patch = new Uint8ClampedArray(width * height * 4);
    }
    const patch = this.patch;
    let x0 = width, y0 = height, x1 = 0, y1 = 0;
    for(let y = 0; y < height; y++)
    {
        for(let x = 0; x < width; x++)
        {
            const pixel = under(left + x, top + y);
            if(!pixel) continue;
            x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + 1); y1 = Math.max(y1, y + 1);
            const { data, at } = pixel, i = y * width + x, p = i * 4;
            let r = data[at], g = data[at + 1], b = data[at + 2];
            if(this.alpha)
            {
                const argb = this.image[i], a = argb >>> 24, keep = 255 - a;
                r = (argb >>> 16 & 0xFF) + (r * keep / 255 | 0);
                g = (argb >>> 8 & 0xFF) + (g * keep / 255 | 0);
                b = (argb & 0xFF) + (b * keep / 255 | 0);
            }
            else
            {
                const and = this.and[i], xor = this.image[i];
                r = r & and ^ xor >>> 16 & 0xFF;
                g = g & and ^ xor >>> 8 & 0xFF;
                b = b & and ^ xor & 0xFF;
            }
            patch[p] = r; patch[p + 1] = g; patch[p + 2] = b; patch[p + 3] = 255;
        }
    }
    if(x0 >= x1 || y0 >= y1) return layers;
    layers.push({
        pixels: { data: patch, width, height },
        screen_x: left + x0, screen_y: top + y0,
        buffer_x: x0, buffer_y: y0,
        buffer_width: x1 - x0, buffer_height: y1 - y0,
    });
    this.drawn = [left + x0, top + y0, x1 - x0, y1 - y0];
    return layers;
};

SoftwareCursor.prototype.get_state = function()
{
    return [this.width, this.height, this.hot_x, this.hot_y, this.alpha, this.and, this.image, this.visible, this.x, this.y];
};

SoftwareCursor.prototype.set_state = function(state)
{
    [this.width, this.height, this.hot_x, this.hot_y, this.alpha, this.and, this.image, this.visible, this.x, this.y] = state;
    this.and = this.and && Int32Array.from(this.and);
    this.image = this.image && Int32Array.from(this.image);
    this.drawn = null;
    this.patch = null;
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/graphics_adapters/vmware_svga/svga_device.js                                         0000644 0000000 0000000 00000201262 00000000000 021277  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The VMware SVGA II adapter (15AD:0405), the device side: the register
// interface, the command FIFO, the 2D commands and interrupts, on top of the
// VGA core for the BIOS, DOS and boot screens. What it declares is set by its
// level (LEVELS); see docs/gpu-devices.md, "VMware SVGA II".
//
// PCI: BAR0 I/O (index +0, value +1, BIOS +2, IRQ status +8), BAR1 the frame
// buffer (the VGA core's LFB region), BAR2 the FIFO (its own device memory).

import { LOG_VGA } from "../../const.js";
import { h } from "../../lib.js";
import { dbg_log } from "../../log.js";
import { VGAScreen } from "../vga_core.js";
import * as C from "./svga_constants.js";
import { GMRTable, GMR_MAX_IDS, GMR_MAX_PAGES, GMR_MAX_DESCRIPTOR_LENGTH, remap_gmr2_payload, read_pages, write_pages } from "./svga_gmr.js";
import { ScreenObjects } from "./svga_screens.js";
import { SoftwareCursor, cursor_masks_length } from "./svga_cursor.js";
import { SVGA3D } from "./svga3d.js";
import { MOBTable, OTables, OTABLE_ENTRY_BYTES, MOB_MAX_SIZE, GB_MEMORY_KB } from "./svga_gb.js";
import { VGPU9_DEVCAPS, DX10_DEVCAPS, DX10_1_DEVCAPS, DX11_DEVCAPS, DX11_FULL_DEVCAPS } from "./svga3d_tables.js";
import { VideoOverlay } from "./svga_video.js";

// For Types Only
import { DisplaySource } from "../../display.js";
import { GraphicsMachine } from "../machine.js";

const DEFAULT_VRAM_SIZE = 32 << 20;
const MIN_VRAM_SIZE = 4 << 20;
const FIFO_SIZE = 2 << 20;
const IO_SIZE = 16;

// Where the BARs start out; SeaBIOS assigns them
const FIFO_INITIAL_ADDRESS = 0xFD000000;

const MAX_WIDTH = 2560;
const MAX_HEIGHT = 1600;
const SCRATCH_SIZE = 64;
/** Displays the guest may define with MULTIMON / screen objects */
const MAX_DISPLAYS = 4;
/** The largest command buffer taken (SVGA_CB_MAX_SIZE) */
const CB_MAX_SIZE = C.SVGA_CB_MAX_SIZE;

/** The FIFO's register area, in dwords, that the driver must leave free */
const FIFO_REGS = C.SVGA_FIFO_NUM_REGS;

/** The cursor a cursor MOB may hold (SVGA_CAP2_CURSOR_MOB) */
const CURSOR_MAX_DIMENSION = 256;
const CURSOR_HEADER_BYTES = 32;
const CURSOR_MAX_BYTE_SIZE = CURSOR_HEADER_BYTES + CURSOR_MAX_DIMENSION * CURSOR_MAX_DIMENSION * 4;

/**
 * What each level declares. A level is fixed once chosen: a snapshot keeps it.
 * @type {!Object<string, {caps: number, fifo_caps: number, cap2: (number|undefined), devcaps: (!Array<!Array<number>>|undefined)}>}
 */
export const LEVELS = {
    // modes through the registers, the FIFO with UPDATE/RECT_COPY/FENCE,
    // interrupts. No hardware cursor (the guest draws its own).
    "2d": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE,
    },
    // the whole 2D device: guest memory regions, screen objects,
    // multiple displays, the hardware cursor, command buffers
    "2d-full": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
    },
    // legacy 3D (svga3d.js), what Windows 8.1's vm3d uses without
    // guest-backed objects; needs a renderer
    "vgpu9": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
    },
    // the same 3D with guest-backed objects (svga_gb.js): MOBs, object
    // tables, screen targets, the cursor in a MOB
    "gb9": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D |
            C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_CAP2_REGISTER,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
        cap2: C.SVGA_CAP2_GROW_OTABLE | C.SVGA_CAP2_OTABLE_PTDEPTH_2 | C.SVGA_CAP2_GB_MEMSIZE_2 |
            C.SVGA_CAP2_CURSOR_MOB | C.SVGA_CAP2_SCREENDMA_REG,
    },
    // DX contexts (VGPU10, shader model 4.0), drawn by GX
    "dx10": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D |
            C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_CAP2_REGISTER | C.SVGA_CAP_DX,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
        cap2: C.SVGA_CAP2_GROW_OTABLE | C.SVGA_CAP2_OTABLE_PTDEPTH_2 | C.SVGA_CAP2_GB_MEMSIZE_2 |
            C.SVGA_CAP2_CURSOR_MOB | C.SVGA_CAP2_SCREENDMA_REG,
        devcaps: DX10_DEVCAPS,
    },
    // shader model 4.1 (feature level 10_1; Linux's vmwgfx wants
    // SVGA_CAP2_DX2 and the SM41 devcap, and Mesa then multisamples)
    "dx10.1": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D |
            C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_CAP2_REGISTER | C.SVGA_CAP_DX,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
        cap2: C.SVGA_CAP2_GROW_OTABLE | C.SVGA_CAP2_OTABLE_PTDEPTH_2 | C.SVGA_CAP2_GB_MEMSIZE_2 |
            C.SVGA_CAP2_CURSOR_MOB | C.SVGA_CAP2_SCREENDMA_REG | C.SVGA_CAP2_DX2,
        devcaps: DX10_1_DEVCAPS,
    },
    // shader model 5 (feature level 11_0, GL 4.3): SVGA_CAP2_DX3 with
    // the SM5 devcap is what both VMware's Windows driver and Linux's
    // vmwgfx look for
    "dx11": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D |
            C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_CAP2_REGISTER | C.SVGA_CAP_DX,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2,
        cap2: C.SVGA_CAP2_GROW_OTABLE | C.SVGA_CAP2_OTABLE_PTDEPTH_2 | C.SVGA_CAP2_GB_MEMSIZE_2 |
            C.SVGA_CAP2_CURSOR_MOB | C.SVGA_CAP2_SCREENDMA_REG | C.SVGA_CAP2_DX2 | C.SVGA_CAP2_DX3,
        devcaps: DX11_DEVCAPS,
    },
    // the video overlay (svga_video.js) and GL's provoking vertex
    "dx11-full": {
        caps: C.SVGA_CAP_RECT_COPY | C.SVGA_CAP_EXTENDED_FIFO | C.SVGA_CAP_PITCHLOCK |
            C.SVGA_CAP_IRQMASK | C.SVGA_CAP_TRACES |
            C.SVGA_CAP_CURSOR | C.SVGA_CAP_CURSOR_BYPASS | C.SVGA_CAP_CURSOR_BYPASS_2 | C.SVGA_CAP_ALPHA_CURSOR |
            C.SVGA_CAP_8BIT_EMULATION | C.SVGA_CAP_MULTIMON | C.SVGA_CAP_DISPLAY_TOPOLOGY |
            C.SVGA_CAP_GMR | C.SVGA_CAP_GMR2 | C.SVGA_CAP_SCREEN_OBJECT_2 |
            C.SVGA_CAP_COMMAND_BUFFERS | C.SVGA_CAP_CMD_BUFFERS_2 | C.SVGA_CAP_HP_CMD_QUEUE | C.SVGA_CAP_3D |
            C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_CAP2_REGISTER | C.SVGA_CAP_DX,
        fifo_caps: C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE |
            C.SVGA_FIFO_CAP_CURSOR_BYPASS_3 | C.SVGA_FIFO_CAP_ESCAPE |
            C.SVGA_FIFO_CAP_SCREEN_OBJECT | C.SVGA_FIFO_CAP_SCREEN_OBJECT_2 | C.SVGA_FIFO_CAP_GMR2 |
            C.SVGA_FIFO_CAP_VIDEO,
        cap2: C.SVGA_CAP2_GROW_OTABLE | C.SVGA_CAP2_OTABLE_PTDEPTH_2 | C.SVGA_CAP2_GB_MEMSIZE_2 |
            C.SVGA_CAP2_CURSOR_MOB | C.SVGA_CAP2_SCREENDMA_REG | C.SVGA_CAP2_DX2 | C.SVGA_CAP2_DX3,
        devcaps: DX11_FULL_DEVCAPS,
    },
};

/** Lowest to highest; without a pinned level the highest one there is a renderer for */
export const LEVEL_ORDER = ["2d", "2d-full", "vgpu9", "gb9", "dx10", "dx10.1", "dx11", "dx11-full"];

/** The level without a pinned one: the highest implemented, or 2D without a renderer */
export const DEFAULT_3D_LEVEL = "dx11-full";
export const DEFAULT_2D_LEVEL = "2d-full";

/**
 * @param {number} bpp
 * @return {number}
 */
function bytes_per_pixel(bpp)
{
    return bpp === 15 ? 2 : bpp >> 3;
}

/**
 * @constructor
 * @implements {DisplaySource}
 * @param {GraphicsMachine} machine
 * @param {{vram_size: (number|undefined), level: (string|undefined), renderer: (Object|undefined)}} options
 *     renderer: the channel to the 3D renderer ({post, listen}), if there is one
 */
export function SVGADevice(machine, options)
{
    /** @const */
    this.machine = machine;

    /** @const */
    this.display = machine.display;

    /** @const the channel to the 3D renderer, if there is one */
    this.renderer = options.renderer || null;
    const level = options.level || (options.renderer ? DEFAULT_3D_LEVEL : DEFAULT_2D_LEVEL);
    this.check_level(level);
    /** @type {string} what the device declares (a restore may change it to the snapshot's) */
    this.level = level;
    this.caps = LEVELS[level].caps;
    this.fifo_caps = LEVELS[level].fifo_caps;
    this.cap2 = LEVELS[level].cap2 || 0;

    const vram_size = options.vram_size || DEFAULT_VRAM_SIZE;
    if(vram_size < MIN_VRAM_SIZE)
    {
        throw new Error("vmware_svga: vram_size must be at least " + (MIN_VRAM_SIZE >> 20) + " MiB");
    }
    /** @const @type {number} */
    this.vram_size = vram_size;

    // The VGA core: legacy VGA, VBE and the frame buffer memory (BAR1). This
    // device is the PCI function and the display source.
    /** @const */
    this.vga = new VGAScreen(machine, vram_size, { pci: false, display_source: false });

    // The FIFO: device memory the guest writes at memory speed
    this.fifo_region = machine.mmio_ram_allocate(FIFO_SIZE);
    if(this.fifo_region < 0)
    {
        throw new Error("vmware_svga: no device memory for the FIFO");
    }
    this.fifo_backing = machine.mmio_ram_backing(this.fifo_region) >>> 0;
    this.fifo_address = 0;
    /** @type {Int32Array} */
    this.fifo_view = null;
    this.move_fifo(FIFO_INITIAL_ADDRESS);

    this.io_base = machine.allocate_io(IO_SIZE);

    this.palette = new Uint8Array(3 * 256);
    this.scratch = new Int32Array(SCRATCH_SIZE);

    /** @const */
    this.gmrs = new GMRTable(machine, () => this.vram());
    /** @const */
    this.screens = new ScreenObjects(this.gmrs);
    /** @const */
    this.cursor = new SoftwareCursor();
    /** @const the video overlay's units (SVGA_FIFO_CAP_VIDEO) */
    this.video = new VideoOverlay((id, offset, length) => this.gmrs.read(id, offset, length), id => {
        const s = this.screens.screens.get(id);
        return s ? { x: s.x, y: s.y } : null;
    });
    /** SVGA_REG_DISPLAY_*: [id, primary, x, y, width, height] each */
    this.topology = [];
    /** What the driver has done, for harnesses and debugging */
    this.stats = { fifo_commands: 0, command_buffers: 0, unknown_commands: 0, last_unknown: 0, errors: 0, commands: {}, contexts: {}, statuses: {},
        irq_raised: 0, irq_status_reads: 0, irq_acks: 0 };
    /** @type {MOBTable} guest-backed objects, at the levels that have them */
    this.mobs = null;
    /** @type {OTables} */
    this.otables = null;
    /** @type {!Map<number, number>} SVGA3D_DEVCAP_* through SVGA_REG_DEV_CAP */
    this.devcaps = new Map();
    /** @type {SVGA3D} 3D, at the levels that have it */
    this.svga3d = null;
    this.configure_objects();

    // The picture of the SVGA mode, in wasm memory (mmio_ram_allocate_pixels)
    this.pixels = null;
    this.pixels_offset = 0;
    this.mode_key = "";
    this.showing = false;
    this.pci_registered = false;

    this.reset();

    this.register_ports();
    machine.register_pci({
        pci_space: this.create_pci_space(),
        pci_bars: [
            { size: IO_SIZE, on_move: undefined },
            { size: vram_size, on_move: base => this.vga.move_lfb(base) },
            { size: FIFO_SIZE, on_move: base => this.move_fifo(base) },
        ],
        pci_rom_size: this.vga.pci_rom_size,
        pci_rom_address: this.vga.pci_rom_address,
    });
    this.pci_registered = true;
    this.display.add_source(this);
}

/**
 * Whether this device can declare a level: one that exists, with a renderer
 * if it has 3D
 */
SVGADevice.prototype.check_level = function(level)
{
    if(!LEVELS[level])
    {
        throw new Error("vmware_svga: unknown level " + JSON.stringify(level) + "; levels: " + LEVEL_ORDER.join(", "));
    }
    if((LEVELS[level].caps & C.SVGA_CAP_3D) && !this.renderer)
    {
        throw new Error("vmware_svga: level " + level + " needs a 3D renderer (WebGPU and libv86-webgpu.js)");
    }
};

/**
 * The objects the declared capabilities need: MOBs and object tables, the
 * devcaps, 3D
 */
SVGADevice.prototype.configure_objects = function()
{
    const gb = !!(this.caps & C.SVGA_CAP_GBOBJECTS);
    this.mobs = gb ? new MOBTable(this.machine) : null;
    this.otables = gb ? new OTables(this.machine) : null;
    this.devcaps = new Map(LEVELS[this.level].devcaps || VGPU9_DEVCAPS);
    // (a new one takes over the renderer's channel)
    this.svga3d = this.caps & C.SVGA_CAP_3D ? new SVGA3D(this, /** @type {!Object} */ (this.renderer)) : null;
};

/**
 * The frame buffer (BAR1), as a view taken now: growing wasm memory detaches
 * older views
 * @return {!Uint8Array}
 */
SVGADevice.prototype.vram = function()
{
    return new Uint8Array(this.machine.wasm_memory.buffer, this.vga.svga_memory.byteOffset, this.vram_size);
};

/**
 * A machine reset: back to VGA, the FIFO not configured
 */
SVGADevice.prototype.reset = function()
{
    this.index = 0;
    this.id = C.SVGA_ID_2;
    this.enable = 0;
    this.width = 1024;
    this.height = 768;
    this.bpp = 32;
    this.pitchlock = 0;
    this.guest_id = 0;
    this.config_done = false;
    this.traces = 0;
    this.irq_mask = 0;
    this.irq_status = 0;
    this.num_guest_displays = 0;
    this.display_id = 0;
    this.topology = [];
    this.gmr_id = 0;
    this.command_high = 0;
    this.prepend_low = 0;
    this.prepend_high = 0;
    // the guest's place in SVGA_FIFO_CURSOR_COUNT: a change moves the cursor
    this.cursor_count = 0;
    this.cursor_on = 0;
    this.cursor_x = 0;
    this.cursor_y = 0;
    this.palette.fill(0);
    this.scratch.fill(0);
    this.devcap_index = 0;
    this.guest_driver = [0, 0, 0, 0];
    this.cursor_mob = C.SVGA_ID_INVALID;
    if(this.mobs) this.mobs.reset();
    if(this.otables) this.otables.reset();
    this.gmrs.reset();
    this.video.reset();
    this.screens.reset();
    this.cursor.reset();
    if(this.svga3d) this.svga3d.reset();
    this.update_irq();
    this.init_fifo_registers();
    this.update_scanout();
};

/**
 * @return {!Array<number>}
 */
SVGADevice.prototype.create_pci_space = function()
{
    const io = this.io_base | 1;
    const lfb = this.vga.lfb_address | 0x08;  // prefetchable
    const fifo = this.fifo_address;
    const pci_space = [
        0xAD, 0x15, 0x05, 0x04,     // VMware, SVGA II
        0x03, 0x00, 0x00, 0x00,     // command: I/O and memory; status
        0x00, 0x00, 0x00, 0x03,     // revision 0 (vm3d.inf: REV_00), VGA controller
        0x00, 0x00, 0x00, 0x00,
        io & 0xFF, io >> 8 & 0xFF, 0x00, 0x00,                                  // BAR0
        lfb & 0xFF, lfb >> 8 & 0xFF, lfb >> 16 & 0xFF, lfb >>> 24,              // BAR1
        fifo & 0xFF, fifo >> 8 & 0xFF, fifo >> 16 & 0xFF, fifo >>> 24,          // BAR2
        0x00, 0x00, 0x00, 0x00,     // BAR3
        0x00, 0x00, 0x00, 0x00,     // BAR4
        0x00, 0x00, 0x00, 0x00,     // BAR5
        0x00, 0x00, 0x00, 0x00,
        0xAD, 0x15, 0x05, 0x04,     // subsystem 15AD:0405 (vm3d.inf: SUBSYS_040515AD)
        0x00, 0x00, 0x00, 0x00,     // expansion ROM (v86's ROM BAR)
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x01, 0x00, 0x00,     // interrupt pin A
    ];
    return pci_space;
};

SVGADevice.prototype.register_ports = function()
{
    const machine = this.machine;
    const base = this.io_base;
    machine.register_read(base + C.SVGA_INDEX_PORT, this,
        function(port) { return this.index & 0xFF; }, undefined, function(port) { return this.index; });
    machine.register_write(base + C.SVGA_INDEX_PORT, this,
        function(value) { this.index = value; }, undefined, function(value) { this.index = value >>> 0; });
    machine.register_read(base + C.SVGA_VALUE_PORT, this,
        function(port) { return this.read_register(this.index) & 0xFF; }, undefined,
        function(port) { return this.read_register(this.index) | 0; });
    machine.register_write(base + C.SVGA_VALUE_PORT, this,
        undefined, undefined, function(value) { this.write_register(this.index, value >>> 0); });
    machine.register_read(base + C.SVGA_BIOS_PORT, this,
        function(port) { return 0; }, undefined, function(port) { return 0; });
    machine.register_write(base + C.SVGA_BIOS_PORT, this,
        function(value) {}, undefined, function(value) {});
    machine.register_read(base + C.SVGA_IRQSTATUS_PORT, this,
        function(port) { this.stats.irq_status_reads++; return this.irq_status & 0xFF; }, undefined,
        function(port) { this.stats.irq_status_reads++; return this.irq_status; });
    machine.register_write(base + C.SVGA_IRQSTATUS_PORT, this,
        function(value) { this.stats.irq_acks++; this.clear_irq(value); }, undefined, function(value) { this.stats.irq_acks++; this.clear_irq(value); });
};

/**
 * @param {number} base
 */
SVGADevice.prototype.move_fifo = function(base)
{
    this.fifo_address = base >>> 0;
    this.machine.mmio_ram_map(this.fifo_region, this.fifo_address);
};

/**
 * The FIFO as dwords (a view of wasm memory, made again after it grows)
 * @return {!Int32Array}
 */
SVGADevice.prototype.fifo = function()
{
    const buffer = this.machine.wasm_memory.buffer;
    if(!this.fifo_view || this.fifo_view.buffer !== buffer)
    {
        this.fifo_view = new Int32Array(buffer, this.fifo_backing, FIFO_SIZE >> 2);
    }
    return this.fifo_view;
};

/**
 * What the device writes into the FIFO register area for the driver
 */
SVGADevice.prototype.init_fifo_registers = function()
{
    const fifo = this.fifo();
    fifo[C.SVGA_FIFO_CAPABILITIES] = this.fifo_caps;
    fifo[C.SVGA_FIFO_FLAGS] = 0;
    fifo[C.SVGA_FIFO_3D_HWVERSION] = 0;
    fifo[C.SVGA_FIFO_3D_HWVERSION_REVISED] = 0;
    if(this.svga3d) SVGA3D.write_fifo_caps(fifo);
    Atomics.store(fifo, C.SVGA_FIFO_BUSY, 0);
};

// ---------------------------------------------------------------------------
// Registers

/**
 * @param {number} index
 * @return {number}
 */
SVGADevice.prototype.read_register = function(index)
{
    switch(index)
    {
        case C.SVGA_REG_ID: return this.id;
        case C.SVGA_REG_ENABLE: return this.enable;
        case C.SVGA_REG_WIDTH: return this.width;
        case C.SVGA_REG_HEIGHT: return this.height;
        case C.SVGA_REG_MAX_WIDTH: return MAX_WIDTH;
        case C.SVGA_REG_MAX_HEIGHT: return MAX_HEIGHT;
        case C.SVGA_REG_DEPTH: return this.bpp === 32 ? 24 : this.bpp;
        case C.SVGA_REG_BITS_PER_PIXEL: return this.bpp;
        case C.SVGA_REG_HOST_BITS_PER_PIXEL: return 32;
        case C.SVGA_REG_PSEUDOCOLOR: return this.bpp === 8 ? 1 : 0;
        case C.SVGA_REG_RED_MASK: return this.bpp === 16 ? 0xF800 : this.bpp === 15 ? 0x7C00 : 0xFF0000;
        case C.SVGA_REG_GREEN_MASK: return this.bpp === 16 ? 0x07E0 : this.bpp === 15 ? 0x03E0 : 0x00FF00;
        case C.SVGA_REG_BLUE_MASK: return this.bpp === 16 || this.bpp === 15 ? 0x001F : 0x0000FF;
        case C.SVGA_REG_BYTES_PER_LINE: return this.pitch();
        case C.SVGA_REG_FB_START: return this.vga.lfb_address;
        case C.SVGA_REG_FB_OFFSET: return 0;
        case C.SVGA_REG_VRAM_SIZE: return this.vram_size;
        case C.SVGA_REG_FB_SIZE: return this.pitch() * this.height;
        case C.SVGA_REG_CAPABILITIES: return this.caps;
        case C.SVGA_REG_MEM_START: return this.fifo_address;
        case C.SVGA_REG_MEM_SIZE: return FIFO_SIZE;
        case C.SVGA_REG_CONFIG_DONE: return +this.config_done;
        case C.SVGA_REG_SYNC: return 0;
        case C.SVGA_REG_BUSY:
            // The FIFO is processed synchronously: it is idle once processed
            this.process_fifo();
            return 0;
        case C.SVGA_REG_GUEST_ID: return this.guest_id;
        case C.SVGA_REG_SCRATCH_SIZE: return SCRATCH_SIZE;
        case C.SVGA_REG_MEM_REGS: return FIFO_REGS;
        case C.SVGA_REG_NUM_DISPLAYS: return this.caps & C.SVGA_CAP_MULTIMON ? MAX_DISPLAYS : 1;
        case C.SVGA_REG_PITCHLOCK: return this.pitchlock;
        case C.SVGA_REG_IRQMASK: return this.irq_mask;
        case C.SVGA_REG_NUM_GUEST_DISPLAYS: return this.num_guest_displays;
        case C.SVGA_REG_DISPLAY_ID: return this.display_id;
        case C.SVGA_REG_TRACES: return this.traces;
        case C.SVGA_REG_GMR_ID: return this.gmr_id;
        case C.SVGA_REG_GMR_MAX_IDS: return this.caps & C.SVGA_CAP_GMR ? GMR_MAX_IDS : 0;
        case C.SVGA_REG_GMR_MAX_DESCRIPTOR_LENGTH: return this.caps & C.SVGA_CAP_GMR ? GMR_MAX_DESCRIPTOR_LENGTH : 0;
        case C.SVGA_REG_GMRS_MAX_PAGES: return this.caps & C.SVGA_CAP_GMR2 ? GMR_MAX_PAGES : 0;
        case C.SVGA_REG_MEMORY_SIZE: return this.caps & C.SVGA_CAP_GMR2 ? GMR_MAX_PAGES * 4096 : 0;
        case C.SVGA_REG_COMMAND_HIGH: return this.command_high;
        case C.SVGA_REG_CMD_PREPEND_LOW: return this.prepend_low;
        case C.SVGA_REG_CMD_PREPEND_HIGH: return this.prepend_high;
        case C.SVGA_REG_CURSOR_X: return this.cursor_x;
        case C.SVGA_REG_CURSOR_Y: return this.cursor_y;
        case C.SVGA_REG_CURSOR_ON: return this.cursor_on;
        case C.SVGA_REG_CAP2: return this.caps & C.SVGA_CAP_CAP2_REGISTER ? this.cap2 : 0;
        case C.SVGA_REG_FIFO_CAPS: return this.fifo_caps;
        case C.SVGA_REG_FENCE: return this.fifo()[C.SVGA_FIFO_FENCE] >>> 0;
        case C.SVGA_REG_SCREENDMA:
            // there is no picture a guest could read that it did not send
            return this.cap2 & C.SVGA_CAP2_SCREENDMA_REG ? C.SVGA_SCREENDMA_REG_NOT_PRESENT : 0;
        case C.SVGA_REG_GUEST_DRIVER_ID:
        case C.SVGA_REG_GUEST_DRIVER_VERSION1:
        case C.SVGA_REG_GUEST_DRIVER_VERSION2:
        case C.SVGA_REG_GUEST_DRIVER_VERSION3:
            return this.guest_driver[index - C.SVGA_REG_GUEST_DRIVER_ID];
        case C.SVGA_REG_DISPLAY_IS_PRIMARY:
        case C.SVGA_REG_DISPLAY_POSITION_X:
        case C.SVGA_REG_DISPLAY_POSITION_Y:
        case C.SVGA_REG_DISPLAY_WIDTH:
        case C.SVGA_REG_DISPLAY_HEIGHT:
        {
            const entry = this.topology[this.display_id];
            return entry ? entry[index - C.SVGA_REG_DISPLAY_IS_PRIMARY + 1] : 0;
        }
    }
    if(this.mobs)
    {
        switch(index)
        {
            case C.SVGA_REG_DEV_CAP: return this.devcaps.get(this.devcap_index) >>> 0 || 0;
            case C.SVGA_REG_MAX_PRIMARY_MEM: return this.vram_size;
            case C.SVGA_REG_SUGGESTED_GBOBJECT_MEM_SIZE_KB:
            case C.SVGA_REG_GBOBJECT_MEM_SIZE_KB:
                return GB_MEMORY_KB;
            case C.SVGA_REG_SCREENTARGET_MAX_WIDTH: return MAX_WIDTH;
            case C.SVGA_REG_SCREENTARGET_MAX_HEIGHT: return MAX_HEIGHT;
            case C.SVGA_REG_MOB_MAX_SIZE: return MOB_MAX_SIZE;
            case C.SVGA_REG_BLANK_SCREEN_TARGETS: return 0;
            case C.SVGA_REG_CURSOR_MOBID: return this.cursor_mob;
            case C.SVGA_REG_CURSOR_MAX_BYTE_SIZE: return this.cap2 & C.SVGA_CAP2_CURSOR_MOB ? CURSOR_MAX_BYTE_SIZE : 0;
            case C.SVGA_REG_CURSOR_MAX_DIMENSION: return this.cap2 & C.SVGA_CAP2_CURSOR_MOB ? CURSOR_MAX_DIMENSION : 0;
        }
    }
    if(index >= C.SVGA_PALETTE_BASE && index < C.SVGA_PALETTE_BASE + C.SVGA_NUM_PALETTE_REGS)
    {
        return this.palette[index - C.SVGA_PALETTE_BASE];
    }
    if(index >= C.SVGA_SCRATCH_BASE && index < C.SVGA_SCRATCH_BASE + SCRATCH_SIZE)
    {
        return this.scratch[index - C.SVGA_SCRATCH_BASE] >>> 0;
    }
    dbg_log("svga: read of unimplemented register " + index, LOG_VGA);
    return 0;
};

/**
 * @param {number} index
 * @param {number} value
 */
SVGADevice.prototype.write_register = function(index, value)
{
    switch(index)
    {
        case C.SVGA_REG_ID:
            // The driver offers the highest version it knows and reads back
            // what the device takes
            if(value >= C.SVGA_ID_0 && value <= C.SVGA_ID_2) this.id = value;
            break;
        case C.SVGA_REG_ENABLE:
            this.enable = value & (C.SVGA_REG_ENABLE_ENABLE | C.SVGA_REG_ENABLE_HIDE);
            this.update_scanout();
            break;
        case C.SVGA_REG_WIDTH:
            if(value > 0 && value <= MAX_WIDTH) this.width = value;
            this.update_scanout();
            break;
        case C.SVGA_REG_HEIGHT:
            if(value > 0 && value <= MAX_HEIGHT) this.height = value;
            this.update_scanout();
            break;
        case C.SVGA_REG_BITS_PER_PIXEL:
            if(value === 8 || value === 15 || value === 16 || value === 24 || value === 32) this.bpp = value;
            this.update_scanout();
            break;
        case C.SVGA_REG_CONFIG_DONE:
            this.config_done = !!value;
            if(this.config_done)
            {
                // the driver has set MIN/MAX/NEXT/STOP; the capabilities it
                // reads next are the device's
                this.init_fifo_registers();
            }
            break;
        case C.SVGA_REG_SYNC:
            this.process_fifo();
            break;
        case C.SVGA_REG_GUEST_ID:
            this.guest_id = value;
            break;
        case C.SVGA_REG_PITCHLOCK:
            this.pitchlock = value;
            this.update_scanout();
            break;
        case C.SVGA_REG_IRQMASK:
            this.irq_mask = value;
            this.update_irq();
            break;
        case C.SVGA_REG_NUM_GUEST_DISPLAYS:
            this.num_guest_displays = value;
            break;
        case C.SVGA_REG_DISPLAY_ID:
            this.display_id = value;
            break;
        case C.SVGA_REG_TRACES:
            this.traces = value;
            break;
        case C.SVGA_REG_GMR_ID:
            this.gmr_id = value;
            break;
        case C.SVGA_REG_GMR_DESCRIPTOR:
            if(this.caps & C.SVGA_CAP_GMR && !this.gmrs.define_gmr1(this.gmr_id, value))
            {
                dbg_log("svga: invalid GMR descriptor for GMR " + this.gmr_id, LOG_VGA);
            }
            break;
        case C.SVGA_REG_COMMAND_HIGH:
            this.command_high = value;
            break;
        case C.SVGA_REG_COMMAND_LOW:
            if(this.caps & C.SVGA_CAP_COMMAND_BUFFERS)
            {
                this.submit_command_buffer(this.command_high * 0x100000000 + (value & ~0x3F), value & 0x3F);
            }
            break;
        case C.SVGA_REG_CMD_PREPEND_LOW:
            this.prepend_low = value;
            break;
        case C.SVGA_REG_DEV_CAP:
            this.devcap_index = value;
            break;
        case C.SVGA_REG_GUEST_DRIVER_ID:
        case C.SVGA_REG_GUEST_DRIVER_VERSION1:
        case C.SVGA_REG_GUEST_DRIVER_VERSION2:
        case C.SVGA_REG_GUEST_DRIVER_VERSION3:
            // which driver this is; SUBMIT ends the list
            if(index !== C.SVGA_REG_GUEST_DRIVER_ID || value !== 0xFFFFFFFF)
            {
                this.guest_driver[index - C.SVGA_REG_GUEST_DRIVER_ID] = value;
            }
            break;
        case C.SVGA_REG_CURSOR_MOBID:
            if(this.cap2 & C.SVGA_CAP2_CURSOR_MOB) this.define_cursor_mob(value);
            break;
        case C.SVGA_REG_CMD_PREPEND_HIGH:
            this.prepend_high = value;
            break;
        case C.SVGA_REG_CURSOR_X:
            this.cursor_x = value | 0;
            this.cursor.move(this.cursor_x, this.cursor_y, this.cursor_on === C.SVGA_CURSOR_ON_SHOW);
            break;
        case C.SVGA_REG_CURSOR_Y:
            this.cursor_y = value | 0;
            this.cursor.move(this.cursor_x, this.cursor_y, this.cursor_on === C.SVGA_CURSOR_ON_SHOW);
            break;
        case C.SVGA_REG_CURSOR_ON:
            this.cursor_on = value;
            this.cursor.move(this.cursor_x, this.cursor_y, this.cursor_on === C.SVGA_CURSOR_ON_SHOW);
            break;
        case C.SVGA_REG_DISPLAY_IS_PRIMARY:
        case C.SVGA_REG_DISPLAY_POSITION_X:
        case C.SVGA_REG_DISPLAY_POSITION_Y:
        case C.SVGA_REG_DISPLAY_WIDTH:
        case C.SVGA_REG_DISPLAY_HEIGHT:
            if(this.display_id < MAX_DISPLAYS)
            {
                const entry = this.topology[this.display_id] || (this.topology[this.display_id] = [this.display_id, 0, 0, 0, 0, 0]);
                entry[index - C.SVGA_REG_DISPLAY_IS_PRIMARY + 1] = value | 0;
            }
            break;
        default:
            if(index >= C.SVGA_PALETTE_BASE && index < C.SVGA_PALETTE_BASE + C.SVGA_NUM_PALETTE_REGS)
            {
                this.palette[index - C.SVGA_PALETTE_BASE] = value;
                this.mode_key = "";
            }
            else if(index >= C.SVGA_SCRATCH_BASE && index < C.SVGA_SCRATCH_BASE + SCRATCH_SIZE)
            {
                this.scratch[index - C.SVGA_SCRATCH_BASE] = value;
            }
            else
            {
                dbg_log("svga: write of unimplemented register " + index + " = " + h(value), LOG_VGA);
            }
    }
};

/**
 * Bytes per line of the SVGA mode
 * @return {number}
 */
SVGADevice.prototype.pitch = function()
{
    if(this.pitchlock) return this.pitchlock;
    const fifo_pitchlock = this.config_done ? this.fifo()[C.SVGA_FIFO_PITCHLOCK] : 0;
    if(fifo_pitchlock > 0) return fifo_pitchlock;
    return this.width * bytes_per_pixel(this.bpp) + 3 & ~3;
};

// ---------------------------------------------------------------------------
// Interrupts

SVGADevice.prototype.update_irq = function()
{
    // (the PCI function, and so its interrupt line, comes after the first reset)
    if(!this.pci_registered) return;
    if(this.irq_status & this.irq_mask)
    {
        this.stats.irq_raised++;
        this.machine.raise_irq();
    }
    else this.machine.lower_irq();
};

/** @param {number} flags */
SVGADevice.prototype.set_irq = function(flags)
{
    if(flags & C.SVGA_IRQFLAG_ERROR) this.stats.errors++;
    this.irq_status |= flags;
    this.update_irq();
};

/** @param {number} flags written to the IRQ status port */
SVGADevice.prototype.clear_irq = function(flags)
{
    this.irq_status &= ~flags;
    this.update_irq();
};

// ---------------------------------------------------------------------------
// The FIFO

/**
 * Run the commands between STOP and NEXT_CMD. The ring is [MIN, MAX) in
 * bytes; a command may wrap around its end.
 */
SVGADevice.prototype.process_fifo = function()
{
    if(!this.config_done || !(this.enable & C.SVGA_REG_ENABLE_ENABLE)) return;

    const fifo = this.fifo();
    const min = fifo[C.SVGA_FIFO_MIN], max = fifo[C.SVGA_FIFO_MAX];
    let stop = fifo[C.SVGA_FIFO_STOP];
    if(min < FIFO_REGS * 4 || max > FIFO_SIZE || min >= max || (min | max | stop) & 3 || stop < min || stop >= max)
    {
        dbg_log("svga: FIFO misconfigured: min=" + h(min) + " max=" + h(max) + " stop=" + h(stop), LOG_VGA);
        return;
    }

    let progress = false;
    for(;;)
    {
        // NEXT_CMD is published after the command: read it first
        const next = Atomics.load(fifo, C.SVGA_FIFO_NEXT_CMD);
        if(next === stop) break;
        if(next < min || next >= max || next & 3)
        {
            dbg_log("svga: FIFO NEXT_CMD out of range: " + h(next), LOG_VGA);
            break;
        }
        const available = (next - stop + (max - min)) % (max - min) >> 2;
        const read = n => fifo[(stop - min + 4 * n) % (max - min) + min >> 2];
        const length = this.run_command(read, available);
        if(length === 0) break;       // incomplete: the rest is not written yet
        this.stats.fifo_commands++;
        if(length < 0)
        {
            // unknown command: its length is unknown, nothing after it can be parsed
            this.set_irq(C.SVGA_IRQFLAG_ERROR);
            stop = next;
            Atomics.store(fifo, C.SVGA_FIFO_STOP, stop);
            break;
        }
        stop = (stop - min + 4 * length) % (max - min) + min;
        Atomics.store(fifo, C.SVGA_FIFO_STOP, stop);
        progress = true;
    }

    Atomics.store(fifo, C.SVGA_FIFO_BUSY, 0);
    if(progress) this.set_irq(C.SVGA_IRQFLAG_FIFO_PROGRESS);
};

/**
 * Run one command
 * @param {function(number):number} read the command's dwords, from 0 (the id)
 * @param {number} available dwords written
 * @return {number} its length in dwords, 0 if not all of it is there, -1 if unknown
 */
SVGADevice.prototype.run_command = function(read, available)
{
    const id = read(0) >>> 0;
    this.stats.commands[id] = (this.stats.commands[id] || 0) + 1;
    const need = n => available >= n;

    switch(id)
    {
        case C.SVGA_CMD_UPDATE:
            if(!need(5)) return 0;
            // the frame buffer's dirty pages already show every write; screens
            // backed by it need converting
            this.screens.update(read(1) >>> 0, read(2) >>> 0, read(3) >>> 0, read(4) >>> 0);
            return 5;
        case C.SVGA_CMD_UPDATE_VERBOSE:
            if(!need(6)) return 0;
            this.screens.update(read(1) >>> 0, read(2) >>> 0, read(3) >>> 0, read(4) >>> 0);
            return 6;
        case C.SVGA_CMD_RECT_COPY:
            if(!need(7)) return 0;
            this.rect_copy(read(1), read(2), read(3), read(4), read(5), read(6));
            return 7;
        case C.SVGA_CMD_FENCE:
            if(!need(2)) return 0;
            this.fence(read(1) >>> 0);
            return 2;
        case C.SVGA_CMD_NOP:
            return 1;
        case C.SVGA_CMD_NOP_ERROR:
            this.set_irq(C.SVGA_IRQFLAG_ERROR);
            return 1;
        case C.SVGA_CMD_ESCAPE:
        {
            if(!need(3)) return 0;
            const size = read(2) >>> 0;
            const length = 3 + (size + 3 >> 2);
            if(!need(length)) return 0;
            // the video overlay's commands (VMware's namespace)
            if((read(1) >>> 0) === C.SVGA_ESCAPE_NSID_VMWARE && (this.fifo_caps & C.SVGA_FIFO_CAP_VIDEO) && size >= 8)
            {
                const words = new Uint32Array(size >> 2);
                for(let i = 0; i < words.length; i++) words[i] = read(3 + i);
                if(this.video.escape(words)) return length;
            }
            dbg_log("svga: escape nsid=" + h(read(1) >>> 0) + " size=" + size + " ignored", LOG_VGA);
            return length;
        }
        case C.SVGA_CMD_DEFINE_CURSOR:
        {
            if(!need(8)) return 0;
            const width = read(4) >>> 0, height = read(5) >>> 0, and_depth = read(6) >>> 0, xor_depth = read(7) >>> 0;
            if(width > 256 || height > 256 || ![1, 32].includes(and_depth) || ![1, 8, 24, 32].includes(xor_depth)) return -1;
            const length = 8 + cursor_masks_length(width, height, and_depth, xor_depth);
            if(!need(length)) return 0;
            if(this.caps & C.SVGA_CAP_CURSOR)
            {
                this.cursor.define(read(2) >>> 0, read(3) >>> 0, width, height, and_depth, xor_depth,
                    i => read(8 + i), this.palette);
            }
            return length;
        }
        case C.SVGA_CMD_DEFINE_ALPHA_CURSOR:
        {
            if(!need(6)) return 0;
            const width = read(4) >>> 0, height = read(5) >>> 0;
            if(width > 256 || height > 256) return -1;
            const length = 6 + width * height;
            if(!need(length)) return 0;
            if(this.caps & C.SVGA_CAP_ALPHA_CURSOR)
            {
                this.cursor.define_alpha(read(2) >>> 0, read(3) >>> 0, width, height, i => read(6 + i));
            }
            return length;
        }
        case C.SVGA_CMD_DEFINE_SCREEN:
        {
            if(!need(2)) return 0;
            const size = read(1) >>> 0;
            if(size < 28 || size & 3 || size > 256) return -1;
            const length = 1 + size / 4;
            if(!need(length)) return 0;
            if(!this.screens.define(i => read(1 + i), size / 4)) this.set_irq(C.SVGA_IRQFLAG_ERROR);
            return length;
        }
        case C.SVGA_CMD_DESTROY_SCREEN:
            if(!need(2)) return 0;
            this.screens.destroy(read(1) >>> 0);
            return 2;
        case C.SVGA_CMD_DEFINE_GMRFB:
            if(!need(5)) return 0;
            this.screens.define_gmrfb(read(1) >>> 0, read(2) >>> 0, read(3) >>> 0, read(4) >>> 0);
            return 5;
        case C.SVGA_CMD_BLIT_GMRFB_TO_SCREEN:
            if(!need(8)) return 0;
            if(!this.screens.blit_to_screen(read(1) | 0, read(2) | 0, read(3) | 0, read(4) | 0, read(5) | 0, read(6) | 0, read(7) >>> 0))
            {
                dbg_log("svga: BLIT_GMRFB_TO_SCREEN failed", LOG_VGA);
            }
            return 8;
        case C.SVGA_CMD_BLIT_SCREEN_TO_GMRFB:
            if(!need(8)) return 0;
            if(!this.screens.blit_from_screen(read(1) | 0, read(2) | 0, read(3) | 0, read(4) | 0, read(5) | 0, read(6) | 0, read(7) >>> 0))
            {
                dbg_log("svga: BLIT_SCREEN_TO_GMRFB failed", LOG_VGA);
            }
            return 8;
        case C.SVGA_CMD_ANNOTATION_FILL:
            // (a hint about the next blit, whose pixels come anyway)
            return need(2) ? 2 : 0;
        case C.SVGA_CMD_ANNOTATION_COPY:
            return need(4) ? 4 : 0;
        case C.SVGA_CMD_DEFINE_GMR2:
            if(!need(3)) return 0;
            if(!(this.caps & C.SVGA_CAP_GMR2) || !this.gmrs.define_gmr2(read(1) >>> 0, read(2) >>> 0))
            {
                this.set_irq(C.SVGA_IRQFLAG_ERROR);
            }
            return 3;
        case C.SVGA_CMD_REMAP_GMR2:
        {
            if(!need(5)) return 0;
            const id = read(1) >>> 0, flags = read(2) >>> 0, offset = read(3) >>> 0, count = read(4) >>> 0;
            const length = 5 + remap_gmr2_payload(flags, count);
            if(!need(length)) return 0;
            let ppn;
            if(flags & C.SVGA_REMAP_GMR2_VIA_GMR)
            {
                // the page numbers are in another region
                const entry = flags & C.SVGA_REMAP_GMR2_PPN64 ? 8 : 4;
                const list = this.gmrs.read(read(5) >>> 0, read(6) >>> 0, entry * (flags & C.SVGA_REMAP_GMR2_SINGLE_PPN ? 1 : count));
                const view = list && new DataView(list.buffer);
                ppn = !view ? () => 0 : entry === 8 ?
                    i => view.getUint32(i * 8, true) + view.getUint32(i * 8 + 4, true) * 0x100000000 :
                    i => view.getUint32(i * 4, true);
            }
            else
            {
                ppn = flags & C.SVGA_REMAP_GMR2_PPN64 ?
                    i => (read(5 + 2 * i) >>> 0) + (read(6 + 2 * i) >>> 0) * 0x100000000 :
                    i => read(5 + i) >>> 0;
            }
            if(!this.gmrs.remap_gmr2(id, flags, offset, count, ppn)) this.set_irq(C.SVGA_IRQFLAG_ERROR);
            return length;
        }
    }

    if(id >= C.SVGA_3D_CMD_LEGACY_BASE && id < C.SVGA_3D_CMD_MAX)
    {
        // SVGA3dCmdHeader: id, size in bytes
        if(!need(2)) return 0;
        const size = read(1) >>> 0;
        const length = 2 + (size + 3 >> 2);
        if(!need(length)) return 0;
        if(this.svga3d)
        {
            const body = new Int32Array(size >> 2);
            for(let i = 0; i < body.length; i++) body[i] = read(2 + i);
            this.svga3d.command(id, body);
        }
        else
        {
            dbg_log("svga: 3D command " + id + " ignored (no 3D at level " + this.level + ")", LOG_VGA);
        }
        return length;
    }

    dbg_log("svga: unknown FIFO command " + id, LOG_VGA);
    this.stats.unknown_commands++;
    this.stats.last_unknown = id;
    return -1;
};

// ---------------------------------------------------------------------------
// Command buffers (SVGA_CAP_COMMAND_BUFFERS, CMD_BUFFERS_2)

/**
 * COMMAND_LOW written: run the command buffer whose SVGACBHeader is at
 * `address` (64-byte aligned) on a context, now, and complete it
 * @param {number} address guest physical
 * @param {number} context SVGA_CB_CONTEXT_0, _1 or _DEVICE
 */
SVGADevice.prototype.submit_command_buffer = function(address, context)
{
    this.stats.command_buffers++;
    this.stats.contexts[context] = (this.stats.contexts[context] || 0) + 1;
    const header = new DataView(this.machine.read_physical(address, 64).slice().buffer);
    const flags = header.getUint32(16, true), length = header.getUint32(20, true);
    const pa = header.getUint32(24, true) + header.getUint32(28, true) * 0x100000000;
    const offset = header.getUint32(32, true);
    let status = C.SVGA_CB_STATUS_COMPLETED, error_offset = 0;

    // a buffer in a MOB (guest-backed objects): ptr is mobid, mobOffset
    const in_mob = !!(flags & C.SVGA_CB_FLAG_MOB);
    const bytes = length > CB_MAX_SIZE || offset > length || length & 3 || offset & 3 ? null :
        in_mob ? this.mobs && this.mobs.read(header.getUint32(24, true), header.getUint32(28, true) + offset, length - offset) :
        this.machine.read_physical(pa + offset, length - offset).slice();
    if(!bytes || context !== C.SVGA_CB_CONTEXT_DEVICE && context >= C.SVGA_CB_CONTEXT_MAX)
    {
        status = C.SVGA_CB_STATUS_CB_HEADER_ERROR;
    }
    else
    {
        const dwords = new Int32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2);
        // DX commands act on the context the buffer names
        if(this.svga3d) this.svga3d.dx_context = flags & C.SVGA_CB_FLAG_DX_CONTEXT ? header.getUint32(36, true) : 0xFFFFFFFF;
        for(let at = 0; at < dwords.length;)
        {
            const read = i => dwords[at + i];
            const run = context === C.SVGA_CB_CONTEXT_DEVICE ?
                this.run_device_command(read, dwords.length - at) : this.run_command(read, dwords.length - at);
            if(run <= 0)
            {
                // unknown, or longer than the buffer
                status = C.SVGA_CB_STATUS_COMMAND_ERROR;
                error_offset = offset + at * 4;
                break;
            }
            at += run;
        }
    }

    this.stats.statuses[status] = (this.stats.statuses[status] || 0) + 1;
    const complete = () => {
        const done = new DataView(new ArrayBuffer(8));
        done.setUint32(0, status, true);
        done.setUint32(4, error_offset, true);
        this.machine.write_physical(new Uint8Array(done.buffer), address);
        if(status !== C.SVGA_CB_STATUS_COMPLETED)
        {
            dbg_log("svga: command buffer at " + h(address) + " failed: status " + status + " at " + error_offset, LOG_VGA);
            this.set_irq(C.SVGA_IRQFLAG_ERROR);
        }
        if(!(flags & C.SVGA_CB_FLAG_NO_IRQ) || status !== C.SVGA_CB_STATUS_COMPLETED)
        {
            this.set_irq(C.SVGA_IRQFLAG_COMMAND_BUFFER);
        }
    };
    // a buffer is complete when the GPU work before it is (readbacks have landed)
    if(this.svga3d) this.svga3d.after_work(complete);
    else complete();
};

/**
 * One command of the device context: queues are run as they are submitted,
 * so starting, stopping, preempting and emptying them have nothing to do
 * @param {function(number):number} read
 * @param {number} available
 * @return {number} its length in dwords, or -1
 */
SVGADevice.prototype.run_device_command = function(read, available)
{
    switch(read(0) >>> 0)
    {
        case C.SVGA_DC_CMD_NOP: return 1;
        case C.SVGA_DC_CMD_START_STOP_CONTEXT: return available >= 3 ? 3 : -1;
        case C.SVGA_DC_CMD_PREEMPT: return available >= 3 ? 3 : -1;
        case C.SVGA_DC_CMD_START_QUEUE: return available >= 2 ? 2 : -1;
        case C.SVGA_DC_CMD_ASYNC_STOP_QUEUE: return available >= 2 ? 2 : -1;
        case C.SVGA_DC_CMD_EMPTY_CONTEXT_QUEUE: return available >= 2 ? 2 : -1;
    }
    return -1;
};

// ---------------------------------------------------------------------------
// Guest-backed objects: MOBs and object tables (svga_gb.js); the objects in
// them are svga3d.js's

/**
 * DEFINE_GB_MOB(64), REDEFINE_GB_MOB64
 */
SVGADevice.prototype.define_mob = function(id, format, base, size)
{
    if(!this.mobs.define(id, format, base, size))
    {
        this.set_irq(C.SVGA_IRQFLAG_ERROR);
        return;
    }
    // SVGAOTableMobEntry: ptDepth, sizeInBytes, base (64 bits)
    this.otables.write_entry(C.SVGA_OTABLE_MOB, id,
        new Uint8Array(Uint32Array.of(format, size, base % 0x100000000, Math.floor(base / 0x100000000)).buffer));
};

SVGADevice.prototype.destroy_mob = function(id)
{
    this.mobs.destroy(id);
    this.otables.write_entry(C.SVGA_OTABLE_MOB, id, null);
    if(id === this.cursor_mob) this.cursor_mob = C.SVGA_ID_INVALID;
};

/**
 * SET_OTABLE_BASE(64): where a table is. Entries the driver says are valid
 * (after a reset, to get its objects back) are taken as defined.
 */
SVGADevice.prototype.set_otable = function(type, format, base, size, valid)
{
    if(!this.otables.set(type, format, base, size))
    {
        dbg_log("svga: invalid object table " + type, LOG_VGA);
        this.set_irq(C.SVGA_IRQFLAG_ERROR);
        return;
    }
    const entries = Math.min(this.otables.capacity(type), Math.floor(valid / OTABLE_ENTRY_BYTES[type]));
    if(entries) this.load_otable(type, entries);
};

/**
 * GROW_OTABLE: a bigger table; the device moves the valid entries into it
 */
SVGADevice.prototype.grow_otable = function(type, format, base, size, valid)
{
    const old = this.otables.tables[type];
    const keep = old ? Math.min(valid, old.size, size) : 0;
    const bytes = keep ? read_pages(this.machine, old.pages, 0, keep) : null;
    if(!this.otables.set(type, format, base, size))
    {
        this.set_irq(C.SVGA_IRQFLAG_ERROR);
        return;
    }
    if(bytes) write_pages(this.machine, this.otables.tables[type].pages, 0, bytes);
};

/**
 * The objects in the first `count` entries of a table: MOBs are walked
 * again, the others are svga3d's
 */
SVGADevice.prototype.load_otable = function(type, count)
{
    for(let index = 0; index < count; index++)
    {
        const bytes = this.otables.read_entry(type, index);
        if(!bytes || bytes.every(b => b === 0)) continue;
        const entry = new Uint32Array(bytes.slice().buffer);
        if(type === C.SVGA_OTABLE_MOB)
        {
            if(entry[1]) this.mobs.define(index, entry[0], entry[2] + entry[3] * 0x100000000, entry[1]);
        }
        else if(this.svga3d)
        {
            this.svga3d.load_entry(type, index, entry);
        }
    }
};

/**
 * SVGA_REG_CURSOR_MOBID: the cursor is an SVGAGBCursorHeader and its image
 * in this MOB
 */
SVGADevice.prototype.define_cursor_mob = function(id)
{
    this.cursor_mob = id;
    const header = this.mobs.read(id, 0, CURSOR_HEADER_BYTES);
    if(!header) return;
    const h = new Uint32Array(header.slice().buffer);
    const type = h[0], hot_x = h[1], hot_y = h[2], width = h[3], height = h[4];
    if(!width || !height || width > CURSOR_MAX_DIMENSION || height > CURSOR_MAX_DIMENSION) return;
    if(type === C.SVGA_ALPHA_CURSOR)
    {
        const image = this.mobs.read(id, CURSOR_HEADER_BYTES, width * height * 4);
        if(!image) return;
        const dwords = new Int32Array(image.buffer, image.byteOffset, width * height);
        this.cursor.define_alpha(hot_x, hot_y, width, height, i => dwords[i]);
    }
    else if(type === C.SVGA_COLOR_CURSOR)
    {
        const and_depth = h[5], xor_depth = h[6];
        if(![1, 32].includes(and_depth) || ![1, 8, 24, 32].includes(xor_depth)) return;
        const image = this.mobs.read(id, CURSOR_HEADER_BYTES, cursor_masks_length(width, height, and_depth, xor_depth) * 4);
        if(!image) return;
        const dwords = new Int32Array(image.buffer, image.byteOffset, image.length >> 2);
        this.cursor.define(hot_x, hot_y, width, height, and_depth, xor_depth, i => dwords[i], this.palette);
    }
};

/**
 * @param {number} fence
 */
SVGADevice.prototype.fence = function(fence)
{
    // 2D commands complete as they are read; 3D ones when the renderer has run them
    const pass = () => {
        Atomics.store(this.fifo(), C.SVGA_FIFO_FENCE, fence | 0);
        this.set_irq(C.SVGA_IRQFLAG_ANY_FENCE);
    };
    if(this.svga3d) this.svga3d.after_work(pass);
    else pass();
};

/**
 * Copy a rectangle of the SVGA frame buffer onto itself
 */
SVGADevice.prototype.rect_copy = function(src_x, src_y, dst_x, dst_y, width, height)
{
    const bpp = bytes_per_pixel(this.bpp), pitch = this.pitch();
    if(width <= 0 || height <= 0 ||
        Math.max(src_x, dst_x) + width > this.width || Math.max(src_y, dst_y) + height > this.height)
    {
        dbg_log("svga: RECT_COPY out of bounds", LOG_VGA);
        return;
    }
    const vram = this.vram();
    const row = width * bpp;
    // overlapping rectangles: copy rows in the direction that keeps the source
    const downward = dst_y > src_y;
    for(let i = 0; i < height; i++)
    {
        const y = downward ? height - 1 - i : i;
        const from = (src_y + y) * pitch + src_x * bpp;
        vram.copyWithin((dst_y + y) * pitch + dst_x * bpp, from, from + row);
    }
    // (writes from here do not go through the dirty bitmap)
    this.machine.mmio_ram_mark_dirty(this.vga.lfb_region);
};

// ---------------------------------------------------------------------------
// The scanout

/**
 * Whether the SVGA mode, not the VGA core, is on screen
 * @return {boolean}
 */
SVGADevice.prototype.svga_active = function()
{
    return (this.enable & (C.SVGA_REG_ENABLE_ENABLE | C.SVGA_REG_ENABLE_HIDE)) === C.SVGA_REG_ENABLE_ENABLE;
};

/**
 * After a change of ENABLE or of the mode: hand the screen to the right side
 */
SVGADevice.prototype.update_scanout = function()
{
    const active = this.svga_active();
    if(active)
    {
        this.mode_key = "";
    }
    else if(this.showing)
    {
        // back to VGA: the core sends its mode and picture again
        this.vga.redisplay();
    }
    this.showing = active;
};

/** @override */
SVGADevice.prototype.vblank_period = function()
{
    return this.svga_active() ? 1000 / 60 : this.vga.vblank_period();
};

/** @override */
SVGADevice.prototype.on_vblank = function()
{
    this.vga.on_vblank();
    // A driver may write commands without SYNC while the device is busy
    this.process_fifo();
};

/** @override */
SVGADevice.prototype.invalidate = function()
{
    if(this.svga_active())
    {
        this.mode_key = "";
        this.cursor.drawn = null;
    }
    else
    {
        this.vga.invalidate();
    }
};

/** @override */
SVGADevice.prototype.render = function()
{
    if(!this.svga_active())
    {
        this.vga.render();
        return;
    }
    this.poll_cursor();
    if(this.screens.screens.size)
    {
        this.render_screens();
    }
    else
    {
        this.render_legacy();
    }
};

/**
 * SVGA_FIFO_CURSOR_*: the guest moved the cursor when CURSOR_COUNT changed
 */
SVGADevice.prototype.poll_cursor = function()
{
    if(!this.config_done || !(this.fifo_caps & C.SVGA_FIFO_CAP_CURSOR_BYPASS_3)) return;
    const fifo = this.fifo();
    const count = Atomics.load(fifo, C.SVGA_FIFO_CURSOR_COUNT);
    if(count === this.cursor_count) return;
    this.cursor_count = count;
    let x = fifo[C.SVGA_FIFO_CURSOR_X], y = fifo[C.SVGA_FIFO_CURSOR_Y];
    // with screen objects, the position may be in a screen's coordinates
    const screen = this.screens.screens.get(fifo[C.SVGA_FIFO_CURSOR_SCREEN_ID] >>> 0);
    if(screen && fifo[C.SVGA_FIFO_CURSOR_SCREEN_ID] >>> 0 !== C.SVGA_ID_INVALID)
    {
        x += screen.x;
        y += screen.y;
    }
    this.cursor.move(x, y, fifo[C.SVGA_FIFO_CURSOR_ON] === C.SVGA_CURSOR_ON_SHOW);
};

/**
 * The register mode: WIDTH x HEIGHT x BITS_PER_PIXEL in the frame buffer
 */
SVGADevice.prototype.render_legacy = function()
{
    const bpp = this.bpp, bytes = bytes_per_pixel(bpp), pitch = this.pitch();
    const buffer_width = pitch / bytes | 0;
    const key = this.width + "x" + this.height + "x" + bpp + "/" + pitch;
    if(key !== this.mode_key)
    {
        this.mode_key = key;
        this.display.set_mode(true);
        this.display.set_size_graphical(this.width, this.height, buffer_width, this.height, bpp);
        this.pixels_offset = this.machine.mmio_ram_allocate_pixels(this.vga.lfb_region, buffer_width * this.height) >>> 0;
        this.pixels = null;
        this.machine.mmio_ram_mark_dirty(this.vga.lfb_region);
        this.cursor.drawn = null;
    }
    // (after the allocation above, which may grow wasm memory)
    const memory = this.machine.wasm_memory.buffer;
    if(!this.pixels || this.pixels.data.buffer !== memory)
    {
        this.pixels = {
            data: new Uint8ClampedArray(memory, this.pixels_offset, 4 * buffer_width * this.height),
            width: buffer_width,
            height: this.height,
        };
    }

    let min_y = 0, max_y = this.height;
    if(bpp === 8)
    {
        // (rare: converted whole, through the palette)
        const out = new Int32Array(memory, this.pixels_offset, buffer_width * this.height);
        const vram = this.vga.svga_memory;
        const source = new Uint8Array(memory, vram.byteOffset, Math.min(this.vram_size, out.length));
        const palette = this.palette;
        for(let i = 0; i < source.length; i++)
        {
            const c = source[i] * 3;
            out[i] = palette[c] | palette[c + 1] << 8 | palette[c + 2] << 16 | 0xFF000000;
        }
    }
    else
    {
        this.machine.mmio_ram_fill_pixels(this.vga.lfb_region, bpp, 0);
        min_y = (this.machine.dirty_min_offset() / bytes | 0) / buffer_width | 0;
        max_y = ((this.machine.dirty_max_offset() / bytes | 0) / buffer_width | 0) + 1;
    }

    const layers = [];
    min_y = Math.max(min_y, 0);
    max_y = Math.min(max_y, this.height);
    const width = this.width, height = this.height, pixels = this.pixels;
    const layer = (x, y, w, h) => ({
        pixels, screen_x: x, screen_y: y, buffer_x: x, buffer_y: y, buffer_width: w, buffer_height: h,
    });
    if(min_y < max_y) layers.push(layer(0, min_y, width, max_y - min_y));
    const under = (x, y) => x >= 0 && y >= 0 && x < width && y < height ? { data: pixels.data, at: (y * buffer_width + x) * 4 } : null;
    const region = (x, y, w, h) => {
        const x0 = Math.max(x, 0), y0 = Math.max(y, 0), x1 = Math.min(x + w, width), y1 = Math.min(y + h, height);
        return x0 < x1 && y0 < y1 ? [layer(x0, y0, x1 - x0, y1 - y0)] : [];
    };
    this.push_overlay_and_cursor(layers, under, region, 0, 0);
    if(layers.length) this.display.update_buffer(layers);
};

/**
 * Screen objects: each screen a layer where it is on the virtual desktop
 */
SVGADevice.prototype.render_screens = function()
{
    let all = false;
    if(this.screens.layout_changed || this.mode_key !== "screens")
    {
        const box = this.screens.bounds();
        this.mode_key = "screens";
        this.screens.layout_changed = false;
        this.display.set_mode(true);
        this.display.set_size_graphical(box.width, box.height, box.width, box.height, 32);
        this.cursor.drawn = null;
        all = true;
    }
    const box = this.screens.bounds();
    const layers = this.screens.take_layers(all);
    const screen_at = (x, y) => {
        for(const s of this.screens.screens.values())
        {
            const sx = x + box.x - s.x, sy = y + box.y - s.y;
            if(sx >= 0 && sy >= 0 && sx < s.width && sy < s.height) return { s, sx, sy };
        }
        return null;
    };
    // the cursor's position is on the virtual desktop; layers are relative to the box
    const cursor = this.cursor, x = cursor.x, y = cursor.y;
    cursor.x -= box.x;
    cursor.y -= box.y;
    this.push_overlay_and_cursor(layers,
        (px, py) => {
            const hit = screen_at(px, py);
            return hit ? { data: hit.s.rgba, at: (hit.sy * hit.s.width + hit.sx) * 4 } : null;
        },
        (rx, ry, w, h) => {
            const out = [];
            for(const s of this.screens.screens.values())
            {
                const x0 = Math.max(rx, s.x - box.x), y0 = Math.max(ry, s.y - box.y);
                const x1 = Math.min(rx + w, s.x - box.x + s.width), y1 = Math.min(ry + h, s.y - box.y + s.height);
                if(x0 < x1 && y0 < y1)
                {
                    out.push({
                        pixels: { data: s.rgba, width: s.width, height: s.height },
                        screen_x: x0, screen_y: y0,
                        buffer_x: x0 - (s.x - box.x), buffer_y: y0 - (s.y - box.y),
                        buffer_width: x1 - x0, buffer_height: y1 - y0,
                    });
                }
            }
            return out;
        }, box.x, box.y);
    cursor.x = x;
    cursor.y = y;
    if(layers.length) this.display.update_buffer(layers);
};

/**
 * After the picture's layers: the video overlay's (where it changed, or the
 * picture under it did), then the cursor over both
 * @param {!Array<!Object>} layers the picture's, added to
 * @param {function(number, number):?{data: !Uint8ClampedArray, at: number}} under
 * @param {function(number, number, number, number):!Array<!Object>} region
 * @param {number} ox where the layers' origin is on the desktop
 * @param {number} oy
 */
SVGADevice.prototype.push_overlay_and_cursor = function(layers, under, region, ox, oy)
{
    if(this.video.active())
    {
        const overlay = this.video.layers(under, region, layers, ox, oy);
        layers.push(...overlay);
        under = this.video.under(under, ox, oy);
        region = this.video.region(region, ox, oy);
        // (drawn over the cursor: where it was is put back, with the
        // overlay, and it is drawn again)
        const d = this.cursor.drawn;
        if(d && overlay.some(l => l.screen_x < d[0] + d[2] && d[0] < l.screen_x + l.buffer_width &&
            l.screen_y < d[1] + d[3] && d[1] < l.screen_y + l.buffer_height))
        {
            layers.push(...region(d[0], d[1], d[2], d[3]));
            this.cursor.drawn = null;
        }
    }
    layers.push(...this.cursor.layers(under, region));
};

// ---------------------------------------------------------------------------
// Snapshots

// The device's ABI (levels; docs/gpu-devices.md, "Configuration"): a
// snapshot keeps the level and every capability the guest's driver read at
// boot (caps, FIFO caps, CAP2, the devcaps), and a restore declares those
// again, whatever this version would choose or its tables now say. A new
// capability therefore needs a new level; what a level once declared keeps
// working.
const STATE_VERSION = 6;

SVGADevice.prototype.get_state = function()
{
    const fifo = this.fifo();
    return [
        STATE_VERSION, this.level, this.vram_size,
        this.vga.get_state(),
        [this.index, this.id, this.enable, this.width, this.height, this.bpp, this.pitchlock, this.guest_id,
            +this.config_done, this.traces, this.irq_mask, this.irq_status, this.num_guest_displays, this.display_id],
        this.palette, this.scratch,
        new Uint8Array(fifo.buffer, fifo.byteOffset, FIFO_SIZE),
        // version 2
        this.gmrs.get_state(), this.screens.get_state(), this.cursor.get_state(),
        [this.gmr_id, this.command_high, this.prepend_low, this.prepend_high, this.cursor_count,
            this.cursor_on, this.cursor_x, this.cursor_y],
        this.topology.map(entry => entry || null),
        // version 3: the 3D objects (svga3d.js; prepare_save read their contents back)
        this.svga3d ? this.svga3d.get_state() : null,
        // version 4: guest-backed objects
        this.mobs ? this.mobs.get_state() : null, this.otables ? this.otables.get_state() : null,
        [this.devcap_index, this.cursor_mob, ...this.guest_driver],
        // version 5: the capabilities declared
        [this.caps, this.fifo_caps, this.cap2, Array.from(this.devcaps)],
        // version 6: the video overlay's units
        this.video.get_state(),
    ];
};

/**
 * Before a snapshot: what only the GPU has comes back
 * @return {!Promise<undefined>}
 */
SVGADevice.prototype.prepare_save = function()
{
    return this.svga3d ? this.svga3d.prepare_save() : Promise.resolve(undefined);
};

SVGADevice.prototype.set_state = function(state)
{
    if(state[0] < 1 || state[0] > STATE_VERSION) throw new Error("vmware_svga: unsupported state version " + state[0]);
    // the snapshot's level and capabilities, not this machine's choice
    this.check_level(state[1]);
    const declared = state[0] >= 5 ? state[17] : null;
    const caps = declared ? declared[0] : LEVELS[state[1]].caps;
    this.level = state[1];
    this.fifo_caps = declared ? declared[1] : LEVELS[state[1]].fifo_caps;
    this.cap2 = declared ? declared[2] : LEVELS[state[1]].cap2 || 0;
    if(caps !== this.caps)
    {
        this.caps = caps;
        this.configure_objects();
    }
    this.devcaps = new Map(declared ? declared[3] : LEVELS[this.level].devcaps || VGPU9_DEVCAPS);
    if(state[2] !== this.vram_size)
    {
        throw new Error("vmware_svga: the snapshot has vram_size " + state[2] + ", this machine " + this.vram_size);
    }
    this.vga.set_state(state[3]);
    [this.index, this.id, this.enable, this.width, this.height, this.bpp, this.pitchlock, this.guest_id,
        this.config_done, this.traces, this.irq_mask, this.irq_status, this.num_guest_displays, this.display_id] = state[4];
    this.config_done = !!this.config_done;
    this.palette.set(state[5]);
    this.scratch.set(state[6]);
    const fifo = this.fifo();
    new Uint8Array(fifo.buffer, fifo.byteOffset, FIFO_SIZE).set(state[7]);
    if(state[0] >= 2)
    {
        this.gmrs.set_state(state[8]);
        this.screens.set_state(state[9]);
        this.cursor.set_state(state[10]);
        [this.gmr_id, this.command_high, this.prepend_low, this.prepend_high, this.cursor_count,
            this.cursor_on, this.cursor_x, this.cursor_y] = state[11];
        this.topology = state[12].map(entry => entry && Array.from(entry));
    }
    else
    {
        this.gmrs.reset();
        this.screens.reset();
        this.cursor.reset();
    }
    // the MOBs first: restoring the 3D objects reads them
    if(this.mobs) this.mobs.set_state(state[0] >= 4 && state[14] || []);
    if(this.otables)
    {
        if(state[0] >= 4 && state[15]) this.otables.set_state(state[15]);
        else this.otables.reset();
    }
    if(state[0] >= 4)
    {
        const registers = state[16];
        this.devcap_index = registers[0];
        this.cursor_mob = registers[1];
        this.guest_driver = Array.from(registers.slice(2, 6));
    }
    if(this.svga3d) this.svga3d.set_state(state[0] >= 3 ? state[13] : null);
    // (after the GMRs: the frames are read again)
    this.video.set_state(state[0] >= 6 ? state[18] : null);
    this.mode_key = "";
    this.showing = false;
    this.update_scanout();
    this.update_irq();
};
                                                                                                                                                                                                                                                                                                                                              source/v64/src/graphics_adapters/vmware_svga/svga_dx_formats.js                                     0000644 0000000 0000000 00000022453 00000000000 022211  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What GX (src/browser/glbridge/gx/) does with each SVGA3dSurfaceFormat, for
// both halves: the device declares it (the DXFMT devcaps, which the guest's
// drivers read to decide what they may create), and GX creates textures,
// views and vertex attributes from it. tools/build_glbridge.mjs copies this
// table into the renderer's bundle, so the two cannot disagree.
//
// Per format: [WebGPU texture format or "" (none), what it can do, WebGPU
// vertex format or ""]. What it can do, as letters:
//   s  sampled, filtered            u  sampled, not filtered (integers)
//   r  color render target          b  blendable
//   d  depth (stencil) target       m  4x multisample at level dx10
//   (from dx10.1 on every target format multisamples: GX supersamples)
//   x  its alpha is "X": reads as 1 (GX forces it when writing)
//   e  emulated: stored as the WebGPU format, converted on the way in and out
// A vertex format "pull:..." has no WebGPU vertex format; GX would read it
// from the buffer in the shader (D3D10 requires it of feature level 10_0).
//
// What feature level 10_0 asks of each format is VMware's driver's table
// (vm3dum64_10.dll), the bits of SVGA3D_DXFMT_*; the 32-bit float formats
// blend with WebGPU's float32-blendable, BC volumes need
// texture-compression-bc-sliced-3d.

/** @type {!Object<string, !Array<string>>} */
export const DX_FORMATS = {
    "SVGA3D_X8R8G8B8": ["bgra8unorm", "srbmx", ""],
    "SVGA3D_A8R8G8B8": ["bgra8unorm", "srbm", "unorm8x4-bgra"],
    "SVGA3D_R5G6B5": ["rgba8unorm", "srbme", ""],
    "SVGA3D_X1R5G5B5": ["rgba8unorm", "srbmxe", ""],
    "SVGA3D_A1R5G5B5": ["rgba8unorm", "srbme", ""],
    "SVGA3D_A4R4G4B4": ["rgba8unorm", "srbme", ""],
    "SVGA3D_Z_D32": ["depth32float", "dum", ""],
    "SVGA3D_Z_D16": ["depth16unorm", "dum", ""],
    "SVGA3D_Z_D24S8": ["depth24plus-stencil8", "dum", ""],
    "SVGA3D_Z_D24X8": ["depth24plus", "dum", ""],
    "SVGA3D_LUMINANCE8": ["rgba8unorm", "se", ""],
    "SVGA3D_LUMINANCE8_ALPHA8": ["rgba8unorm", "se", ""],
    "SVGA3D_DXT1": ["bc1-rgba-unorm", "s", ""],
    "SVGA3D_DXT2": ["bc2-rgba-unorm", "s", ""],
    "SVGA3D_DXT3": ["bc2-rgba-unorm", "s", ""],
    "SVGA3D_DXT4": ["bc3-rgba-unorm", "s", ""],
    "SVGA3D_DXT5": ["bc3-rgba-unorm", "s", ""],
    "SVGA3D_ARGB_S10E5": ["rgba16float", "srbm", "float16x4"],
    "SVGA3D_ARGB_S23E8": ["rgba32float", "srb", "float32x4"],
    "SVGA3D_A2R10G10B10": ["rgb10a2unorm", "srbme", ""],
    "SVGA3D_ALPHA8": ["rgba8unorm", "srbe", ""],
    "SVGA3D_R_S10E5": ["r16float", "srbm", "float16"],
    "SVGA3D_R_S23E8": ["r32float", "srb", "float32"],
    "SVGA3D_RG_S10E5": ["rg16float", "srbm", "float16x2"],
    "SVGA3D_RG_S23E8": ["rg32float", "srb", "float32x2"],
    "SVGA3D_G16R16": ["rg16uint", "ue", ""],
    "SVGA3D_A16B16G16R16": ["rgba16uint", "ue", ""],

    "SVGA3D_R32G32B32A32_TYPELESS": ["rgba32float", "srb", "float32x4"],
    "SVGA3D_R32G32B32A32_FLOAT": ["rgba32float", "srb", "float32x4"],
    "SVGA3D_R32G32B32A32_UINT": ["rgba32uint", "ur", "uint32x4"],
    "SVGA3D_R32G32B32A32_SINT": ["rgba32sint", "ur", "sint32x4"],
    "SVGA3D_R32G32B32_TYPELESS": ["rgba32float", "se", "float32x3"],
    "SVGA3D_R32G32B32_FLOAT": ["rgba32float", "se", "float32x3"],
    "SVGA3D_R32G32B32_UINT": ["rgba32uint", "ue", "uint32x3"],
    "SVGA3D_R32G32B32_SINT": ["rgba32sint", "ue", "sint32x3"],
    "SVGA3D_R16G16B16A16_TYPELESS": ["rgba16float", "srbm", "float16x4"],
    "SVGA3D_R16G16B16A16_FLOAT": ["rgba16float", "srbm", "float16x4"],
    "SVGA3D_R16G16B16A16_UNORM": ["rgba32float", "srbe", "unorm16x4"],
    "SVGA3D_R16G16B16A16_SNORM": ["rgba32float", "srbe", "snorm16x4"],
    "SVGA3D_R16G16B16A16_UINT": ["rgba16uint", "urm", "uint16x4"],
    "SVGA3D_R16G16B16A16_SINT": ["rgba16sint", "urm", "sint16x4"],
    "SVGA3D_R32G32_TYPELESS": ["rg32float", "srb", "float32x2"],
    "SVGA3D_R32G32_FLOAT": ["rg32float", "srb", "float32x2"],
    "SVGA3D_R32G32_UINT": ["rg32uint", "ur", "uint32x2"],
    "SVGA3D_R32G32_SINT": ["rg32sint", "ur", "sint32x2"],
    "SVGA3D_R32G8X24_TYPELESS": ["depth32float-stencil8", "du", ""],
    "SVGA3D_D32_FLOAT_S8X24_UINT": ["depth32float-stencil8", "du", ""],
    "SVGA3D_R32_FLOAT_X8X24": ["depth32float-stencil8", "u", ""],
    "SVGA3D_X32_G8X24_UINT": ["depth32float-stencil8", "u", ""],
    "SVGA3D_R10G10B10A2_TYPELESS": ["rgb10a2unorm", "srbm", "unorm10-10-10-2"],
    "SVGA3D_R10G10B10A2_UNORM": ["rgb10a2unorm", "srbm", "unorm10-10-10-2"],
    "SVGA3D_R10G10B10A2_UINT": ["rgb10a2uint", "urm", "pull:uint10-10-10-2"],
    "SVGA3D_R11G11B10_FLOAT": ["rg11b10ufloat", "srb", "pull:ufloat11-11-10"],
    "SVGA3D_R11G11B10_TYPELESS": ["rg11b10ufloat", "srb", ""],
    "SVGA3D_R8G8B8A8_TYPELESS": ["rgba8unorm", "srbm", "unorm8x4"],
    "SVGA3D_R8G8B8A8_UNORM": ["rgba8unorm", "srbm", "unorm8x4"],
    "SVGA3D_R8G8B8A8_UNORM_SRGB": ["rgba8unorm-srgb", "srbm", ""],
    "SVGA3D_R8G8B8A8_SNORM": ["rgba16float", "srbe", "snorm8x4"],
    "SVGA3D_R8G8B8A8_UINT": ["rgba8uint", "urm", "uint8x4"],
    "SVGA3D_R8G8B8A8_SINT": ["rgba8sint", "urm", "sint8x4"],
    "SVGA3D_R16G16_TYPELESS": ["rg16float", "srbm", "float16x2"],
    "SVGA3D_R16G16_FLOAT": ["rg16float", "srbm", "float16x2"],
    "SVGA3D_R16G16_UNORM": ["rg32float", "srbe", "unorm16x2"],
    "SVGA3D_R16G16_SNORM": ["rg32float", "srbe", "snorm16x2"],
    "SVGA3D_R16G16_UINT": ["rg16uint", "urm", "uint16x2"],
    "SVGA3D_R16G16_SINT": ["rg16sint", "urm", "sint16x2"],
    "SVGA3D_R32_TYPELESS": ["r32float", "srb", "float32"],
    "SVGA3D_R32_FLOAT": ["r32float", "srbm", "float32"],
    "SVGA3D_D32_FLOAT": ["depth32float", "dum", ""],
    "SVGA3D_R32_UINT": ["r32uint", "urm", "uint32"],
    "SVGA3D_R32_SINT": ["r32sint", "urm", "sint32"],
    "SVGA3D_R24G8_TYPELESS": ["depth24plus-stencil8", "dum", ""],
    "SVGA3D_D24_UNORM_S8_UINT": ["depth24plus-stencil8", "dum", ""],
    "SVGA3D_R24_UNORM_X8": ["depth24plus-stencil8", "u", ""],
    "SVGA3D_X24_G8_UINT": ["depth24plus-stencil8", "u", ""],
    "SVGA3D_R8G8_TYPELESS": ["rg8unorm", "srbm", "unorm8x2"],
    "SVGA3D_R8G8_UNORM": ["rg8unorm", "srbm", "unorm8x2"],
    "SVGA3D_R8G8_SNORM": ["rg16float", "srbe", "snorm8x2"],
    "SVGA3D_R8G8_UINT": ["rg8uint", "urm", "uint8x2"],
    "SVGA3D_R8G8_SINT": ["rg8sint", "urm", "sint8x2"],
    "SVGA3D_R16_TYPELESS": ["r16float", "srbm", "float16"],
    "SVGA3D_R16_FLOAT": ["r16float", "srbm", "float16"],
    "SVGA3D_R16_UNORM": ["r32float", "srbe", "unorm16"],
    "SVGA3D_R16_SNORM": ["r32float", "srbe", "snorm16"],
    "SVGA3D_R16_UINT": ["r16uint", "urm", "uint16"],
    "SVGA3D_R16_SINT": ["r16sint", "urm", "sint16"],
    "SVGA3D_D16_UNORM": ["depth16unorm", "dum", ""],
    "SVGA3D_R8_TYPELESS": ["r8unorm", "srbm", "unorm8"],
    "SVGA3D_R8_UNORM": ["r8unorm", "srbm", "unorm8"],
    "SVGA3D_R8_SNORM": ["r16float", "srbe", "snorm8"],
    "SVGA3D_R8_UINT": ["r8uint", "urm", "uint8"],
    "SVGA3D_R8_SINT": ["r8sint", "urm", "sint8"],
    "SVGA3D_A8_UNORM": ["rgba8unorm", "srbe", ""],
    "SVGA3D_R9G9B9E5_SHAREDEXP": ["rgb9e5ufloat", "s", ""],
    "SVGA3D_R8G8_B8G8_UNORM": ["rgba8unorm", "se", ""],
    "SVGA3D_G8R8_G8B8_UNORM": ["rgba8unorm", "se", ""],
    "SVGA3D_BC1_TYPELESS": ["bc1-rgba-unorm", "s", ""],
    "SVGA3D_BC1_UNORM": ["bc1-rgba-unorm", "s", ""],
    "SVGA3D_BC1_UNORM_SRGB": ["bc1-rgba-unorm-srgb", "s", ""],
    "SVGA3D_BC2_TYPELESS": ["bc2-rgba-unorm", "s", ""],
    "SVGA3D_BC2_UNORM": ["bc2-rgba-unorm", "s", ""],
    "SVGA3D_BC2_UNORM_SRGB": ["bc2-rgba-unorm-srgb", "s", ""],
    "SVGA3D_BC3_TYPELESS": ["bc3-rgba-unorm", "s", ""],
    "SVGA3D_BC3_UNORM": ["bc3-rgba-unorm", "s", ""],
    "SVGA3D_BC3_UNORM_SRGB": ["bc3-rgba-unorm-srgb", "s", ""],
    "SVGA3D_BC4_TYPELESS": ["bc4-r-unorm", "s", ""],
    "SVGA3D_BC4_UNORM": ["bc4-r-unorm", "s", ""],
    "SVGA3D_BC4_SNORM": ["bc4-r-snorm", "s", ""],
    "SVGA3D_ATI1": ["bc4-r-unorm", "s", ""],
    "SVGA3D_BC5_TYPELESS": ["bc5-rg-unorm", "s", ""],
    "SVGA3D_BC5_UNORM": ["bc5-rg-unorm", "s", ""],
    "SVGA3D_BC5_SNORM": ["bc5-rg-snorm", "s", ""],
    "SVGA3D_ATI2": ["bc5-rg-unorm", "s", ""],
    "SVGA3D_BC6H_TYPELESS": ["bc6h-rgb-ufloat", "s", ""],
    "SVGA3D_BC6H_UF16": ["bc6h-rgb-ufloat", "s", ""],
    "SVGA3D_BC6H_SF16": ["bc6h-rgb-float", "s", ""],
    "SVGA3D_BC7_TYPELESS": ["bc7-rgba-unorm", "s", ""],
    "SVGA3D_BC7_UNORM": ["bc7-rgba-unorm", "s", ""],
    "SVGA3D_BC7_UNORM_SRGB": ["bc7-rgba-unorm-srgb", "s", ""],
    "SVGA3D_B8G8R8A8_TYPELESS": ["bgra8unorm", "srbm", "unorm8x4-bgra"],
    "SVGA3D_B8G8R8A8_UNORM": ["bgra8unorm", "srbm", "unorm8x4-bgra"],
    "SVGA3D_B8G8R8A8_UNORM_SRGB": ["bgra8unorm-srgb", "srbm", ""],
    "SVGA3D_B8G8R8X8_TYPELESS": ["bgra8unorm", "srbmx", ""],
    "SVGA3D_B8G8R8X8_UNORM": ["bgra8unorm", "srbmx", "pull:unorm8x4-bgrx"],
    "SVGA3D_B8G8R8X8_UNORM_SRGB": ["bgra8unorm-srgb", "srbmx", ""],
    "SVGA3D_B5G6R5_UNORM": ["rgba8unorm", "srbme", ""],
    "SVGA3D_B5G5R5A1_UNORM": ["rgba8unorm", "srbme", ""],
    "SVGA3D_B4G4R4A4_UNORM": ["rgba8unorm", "srbme", ""],
    "SVGA3D_Z_DF16": ["depth16unorm", "dum", ""],
    "SVGA3D_Z_DF24": ["depth24plus", "dum", ""],
    "SVGA3D_Z_D24S8_INT": ["depth24plus-stencil8", "dum", ""],
    // (made and copied only)
    "SVGA3D_R10G10B10_XR_BIAS_A2_UNORM": ["rgb10a2unorm", "", ""],
};

/**
 * What the table gained after level dx10 declared it: dx10 goes on not
 * offering it (its devcaps are fixed, see svga_device.js)
 */
export const AFTER_DX10 = {
    formats: new Set(["SVGA3D_R10G10B10_XR_BIAS_A2_UNORM"]),
    vertex: new Set(["SVGA3D_B8G8R8X8_UNORM"]),
};
                                                                                                                                                                                                                     source/v64/src/graphics_adapters/vmware_svga/svga_formats.js                                        0000644 0000000 0000000 00000037722 00000000000 021523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/gen_svga_formats.js from third_party/vmware-svga/svga3d_surfacedefs.h
// (VMware SVGA3D, GPL-2.0 OR MIT, used under MIT). Do not edit.

export const SVGA3DBLOCKDESC_NONE = 0x0;
export const SVGA3DBLOCKDESC_BLUE = 0x1;
export const SVGA3DBLOCKDESC_W = 0x1;
export const SVGA3DBLOCKDESC_BUMP_L = 0x1;
export const SVGA3DBLOCKDESC_GREEN = 0x2;
export const SVGA3DBLOCKDESC_V = 0x2;
export const SVGA3DBLOCKDESC_RED = 0x4;
export const SVGA3DBLOCKDESC_U = 0x4;
export const SVGA3DBLOCKDESC_LUMINANCE = 0x4;
export const SVGA3DBLOCKDESC_ALPHA = 0x8;
export const SVGA3DBLOCKDESC_Q = 0x8;
export const SVGA3DBLOCKDESC_BUFFER = 0x10;
export const SVGA3DBLOCKDESC_COMPRESSED = 0x20;
export const SVGA3DBLOCKDESC_FP = 0x40;
export const SVGA3DBLOCKDESC_PLANAR_YUV = 0x80;
export const SVGA3DBLOCKDESC_2PLANAR_YUV = 0x100;
export const SVGA3DBLOCKDESC_3PLANAR_YUV = 0x200;
export const SVGA3DBLOCKDESC_STENCIL = 0x800;
export const SVGA3DBLOCKDESC_TYPELESS = 0x1000;
export const SVGA3DBLOCKDESC_SINT = 0x2000;
export const SVGA3DBLOCKDESC_UINT = 0x4000;
export const SVGA3DBLOCKDESC_NORM = 0x8000;
export const SVGA3DBLOCKDESC_SRGB = 0x10000;
export const SVGA3DBLOCKDESC_EXP = 0x20000;
export const SVGA3DBLOCKDESC_COLOR = 0x40000;
export const SVGA3DBLOCKDESC_DEPTH = 0x80000;
export const SVGA3DBLOCKDESC_BUMP = 0x100000;
export const SVGA3DBLOCKDESC_YUV_VIDEO = 0x200000;
export const SVGA3DBLOCKDESC_MIXED = 0x400000;
export const SVGA3DBLOCKDESC_CX = 0x800000;
export const SVGA3DBLOCKDESC_BC1 = 0x1000000;
export const SVGA3DBLOCKDESC_BC2 = 0x2000000;
export const SVGA3DBLOCKDESC_BC3 = 0x4000000;
export const SVGA3DBLOCKDESC_BC4 = 0x8000000;
export const SVGA3DBLOCKDESC_BC5 = 0x10000000;
export const SVGA3DBLOCKDESC_BC6H = 0x20000000;
export const SVGA3DBLOCKDESC_BC7 = 0x40000000;
export const SVGA3DBLOCKDESC_COMPRESSED_MASK = 0x7F000000;
export const SVGA3DBLOCKDESC_A_UINT = 0x44008;
export const SVGA3DBLOCKDESC_A_UNORM = 0x4C008;
export const SVGA3DBLOCKDESC_R_UINT = 0x44004;
export const SVGA3DBLOCKDESC_R_UNORM = 0x4C004;
export const SVGA3DBLOCKDESC_R_SINT = 0x42004;
export const SVGA3DBLOCKDESC_R_SNORM = 0x4A004;
export const SVGA3DBLOCKDESC_G_UINT = 0x44002;
export const SVGA3DBLOCKDESC_RG_UINT = 0x44006;
export const SVGA3DBLOCKDESC_RG_UNORM = 0x4C006;
export const SVGA3DBLOCKDESC_RG_SINT = 0x42006;
export const SVGA3DBLOCKDESC_RG_SNORM = 0x4A006;
export const SVGA3DBLOCKDESC_RGB_UINT = 0x44007;
export const SVGA3DBLOCKDESC_RGB_SINT = 0x42007;
export const SVGA3DBLOCKDESC_RGB_UNORM = 0x4C007;
export const SVGA3DBLOCKDESC_RGB_UNORM_SRGB = 0x5C007;
export const SVGA3DBLOCKDESC_RGBA_UINT = 0x4400F;
export const SVGA3DBLOCKDESC_RGBA_UNORM = 0x4C00F;
export const SVGA3DBLOCKDESC_RGBA_UNORM_SRGB = 0x5C00F;
export const SVGA3DBLOCKDESC_RGBA_SINT = 0x4200F;
export const SVGA3DBLOCKDESC_RGBA_SNORM = 0x4A00F;
export const SVGA3DBLOCKDESC_RGBA_FP = 0x4004F;
export const SVGA3DBLOCKDESC_UV = 0x100006;
export const SVGA3DBLOCKDESC_UVL = 0x500007;
export const SVGA3DBLOCKDESC_UVW = 0x100007;
export const SVGA3DBLOCKDESC_UVWA = 0x50000F;
export const SVGA3DBLOCKDESC_UVWQ = 0x10000F;
export const SVGA3DBLOCKDESC_L_UNORM = 0x4C004;
export const SVGA3DBLOCKDESC_LA_UNORM = 0x4C00C;
export const SVGA3DBLOCKDESC_R_FP = 0x40044;
export const SVGA3DBLOCKDESC_RG_FP = 0x40046;
export const SVGA3DBLOCKDESC_RGB_FP = 0x40047;
export const SVGA3DBLOCKDESC_YUV = 0x240000;
export const SVGA3DBLOCKDESC_AYUV = 0x240008;
export const SVGA3DBLOCKDESC_RGB_EXP = 0x60007;
export const SVGA3DBLOCKDESC_COMP_TYPELESS = 0x1020;
export const SVGA3DBLOCKDESC_COMP_UNORM = 0x4C020;
export const SVGA3DBLOCKDESC_COMP_SNORM = 0x4A020;
export const SVGA3DBLOCKDESC_COMP_UNORM_SRGB = 0x5C020;
export const SVGA3DBLOCKDESC_BC1_COMP_TYPELESS = 0x1001020;
export const SVGA3DBLOCKDESC_BC1_COMP_UNORM = 0x104C020;
export const SVGA3DBLOCKDESC_BC1_COMP_UNORM_SRGB = 0x105C020;
export const SVGA3DBLOCKDESC_BC2_COMP_TYPELESS = 0x2001020;
export const SVGA3DBLOCKDESC_BC2_COMP_UNORM = 0x204C020;
export const SVGA3DBLOCKDESC_BC2_COMP_UNORM_SRGB = 0x205C020;
export const SVGA3DBLOCKDESC_BC3_COMP_TYPELESS = 0x4001020;
export const SVGA3DBLOCKDESC_BC3_COMP_UNORM = 0x404C020;
export const SVGA3DBLOCKDESC_BC3_COMP_UNORM_SRGB = 0x405C020;
export const SVGA3DBLOCKDESC_BC4_COMP_TYPELESS = 0x8001020;
export const SVGA3DBLOCKDESC_BC4_COMP_UNORM = 0x804C020;
export const SVGA3DBLOCKDESC_BC4_COMP_SNORM = 0x804A020;
export const SVGA3DBLOCKDESC_BC5_COMP_TYPELESS = 0x10001020;
export const SVGA3DBLOCKDESC_BC5_COMP_UNORM = 0x1004C020;
export const SVGA3DBLOCKDESC_BC5_COMP_SNORM = 0x1004A020;
export const SVGA3DBLOCKDESC_BC6H_COMP_TYPELESS = 0x20001020;
export const SVGA3DBLOCKDESC_BC6H_COMP_UF16 = 0x20000020;
export const SVGA3DBLOCKDESC_BC6H_COMP_SF16 = 0x20000020;
export const SVGA3DBLOCKDESC_BC7_COMP_TYPELESS = 0x40001020;
export const SVGA3DBLOCKDESC_BC7_COMP_UNORM = 0x4004C020;
export const SVGA3DBLOCKDESC_BC7_COMP_UNORM_SRGB = 0x4005C020;
export const SVGA3DBLOCKDESC_NV12 = 0x240180;
export const SVGA3DBLOCKDESC_YV12 = 0x240280;
export const SVGA3DBLOCKDESC_DEPTH_UINT = 0x84000;
export const SVGA3DBLOCKDESC_DEPTH_UNORM = 0x8C000;
export const SVGA3DBLOCKDESC_DS = 0x80800;
export const SVGA3DBLOCKDESC_DS_UINT = 0x84800;
export const SVGA3DBLOCKDESC_DS_UNORM = 0x8C800;
export const SVGA3DBLOCKDESC_DEPTH_FP = 0x80040;
export const SVGA3DBLOCKDESC_UV_UINT = 0x104006;
export const SVGA3DBLOCKDESC_UV_SNORM = 0x10A006;
export const SVGA3DBLOCKDESC_UVCX_SNORM = 0x90A006;
export const SVGA3DBLOCKDESC_UVWQ_SNORM = 0x10A00F;

/**
 * For each SVGA3dSurfaceFormat: [SVGA3DBLOCKDESC_* bits, block width,
 * height and depth in texels, bytes per block, bytes per block in a pitch,
 * bits of the R, G, B, A channels (or of the depth, stencil ones)]
 * @type {!Array<!Array<(number|!Array<number>)>>}
 */
export const SURFACE_DESCS = [
    [0x0, 1, 1, 1, 0, 0, [0, 0, 0, 0]], // SVGA3D_FORMAT_INVALID
    [0x4c007, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_X8R8G8B8
    [0x4c00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_A8R8G8B8
    [0x4c007, 1, 1, 1, 2, 2, [5, 6, 5, 0]], // SVGA3D_R5G6B5
    [0x4c007, 1, 1, 1, 2, 2, [5, 5, 5, 0]], // SVGA3D_X1R5G5B5
    [0x4c00f, 1, 1, 1, 2, 2, [5, 5, 5, 1]], // SVGA3D_A1R5G5B5
    [0x4c00f, 1, 1, 1, 2, 2, [4, 4, 4, 4]], // SVGA3D_A4R4G4B4
    [0x8c000, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_Z_D32
    [0x8c000, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_Z_D16
    [0x8c800, 1, 1, 1, 4, 4, [0, 8, 24, 0]], // SVGA3D_Z_D24S8
    [0x8c800, 1, 1, 1, 2, 2, [0, 1, 15, 0]], // SVGA3D_Z_D15S1
    [0x4c004, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_LUMINANCE8
    [0x4c00c, 1, 1, 1, 1, 1, [0, 0, 4, 4]], // SVGA3D_LUMINANCE4_ALPHA4
    [0x4c004, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_LUMINANCE16
    [0x4c00c, 1, 1, 1, 2, 2, [0, 0, 8, 8]], // SVGA3D_LUMINANCE8_ALPHA8
    [0x104c020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_DXT1
    [0x204c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_DXT2
    [0x204c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_DXT3
    [0x404c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_DXT4
    [0x404c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_DXT5
    [0x10a006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_BUMPU8V8
    [0x500007, 1, 1, 1, 2, 2, [6, 5, 5, 0]], // SVGA3D_BUMPL6V5U5
    [0x500007, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_BUMPX8L8V8U8
    [0x0, 1, 1, 1, 3, 3, [8, 8, 8, 0]], // SVGA3D_FORMAT_DEAD1
    [0x4004f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_ARGB_S10E5
    [0x4004f, 1, 1, 1, 16, 16, [32, 32, 32, 32]], // SVGA3D_ARGB_S23E8
    [0x4c00f, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_A2R10G10B10
    [0x10a006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_V8U8
    [0x10a00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_Q8W8V8U8
    [0x90a006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_CxV8U8
    [0x500007, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_X8L8V8U8
    [0x50000f, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_A2W10V10U10
    [0x4c008, 1, 1, 1, 1, 1, [0, 0, 0, 8]], // SVGA3D_ALPHA8
    [0x40044, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R_S10E5
    [0x40044, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_R_S23E8
    [0x40046, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_RG_S10E5
    [0x40046, 1, 1, 1, 8, 8, [0, 32, 32, 0]], // SVGA3D_RG_S23E8
    [0x10, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_BUFFER
    [0x8c000, 1, 1, 1, 4, 4, [0, 0, 24, 0]], // SVGA3D_Z_D24X8
    [0x10a006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_V16U16
    [0x4c006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_G16R16
    [0x4c00f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_A16B16G16R16
    [0x240000, 2, 1, 1, 4, 4, [8, 0, 8, 0]], // SVGA3D_UYVY
    [0x240000, 2, 1, 1, 4, 4, [8, 0, 8, 0]], // SVGA3D_YUY2
    [0x240180, 2, 2, 1, 6, 2, [0, 0, 48, 0]], // SVGA3D_NV12
    [0x0, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_FORMAT_DEAD2
    [0x1000, 1, 1, 1, 16, 16, [32, 32, 32, 32]], // SVGA3D_R32G32B32A32_TYPELESS
    [0x4400f, 1, 1, 1, 16, 16, [32, 32, 32, 32]], // SVGA3D_R32G32B32A32_UINT
    [0x4200f, 1, 1, 1, 16, 16, [32, 32, 32, 32]], // SVGA3D_R32G32B32A32_SINT
    [0x1000, 1, 1, 1, 12, 12, [32, 32, 32, 0]], // SVGA3D_R32G32B32_TYPELESS
    [0x40047, 1, 1, 1, 12, 12, [32, 32, 32, 0]], // SVGA3D_R32G32B32_FLOAT
    [0x44007, 1, 1, 1, 12, 12, [32, 32, 32, 0]], // SVGA3D_R32G32B32_UINT
    [0x42007, 1, 1, 1, 12, 12, [32, 32, 32, 0]], // SVGA3D_R32G32B32_SINT
    [0x1000, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_TYPELESS
    [0x4400f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_UINT
    [0x4a00f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_SNORM
    [0x4200f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_SINT
    [0x1000, 1, 1, 1, 8, 8, [0, 32, 32, 0]], // SVGA3D_R32G32_TYPELESS
    [0x44006, 1, 1, 1, 8, 8, [0, 32, 32, 0]], // SVGA3D_R32G32_UINT
    [0x42006, 1, 1, 1, 8, 8, [0, 32, 32, 0]], // SVGA3D_R32G32_SINT
    [0x1000, 1, 1, 1, 8, 8, [0, 8, 32, 0]], // SVGA3D_R32G8X24_TYPELESS
    [0x80800, 1, 1, 1, 8, 8, [0, 8, 32, 0]], // SVGA3D_D32_FLOAT_S8X24_UINT
    [0x40044, 1, 1, 1, 8, 8, [0, 0, 32, 0]], // SVGA3D_R32_FLOAT_X8X24
    [0x44002, 1, 1, 1, 8, 8, [0, 8, 0, 0]], // SVGA3D_X32_G8X24_UINT
    [0x1000, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_R10G10B10A2_TYPELESS
    [0x4400f, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_R10G10B10A2_UINT
    [0x40047, 1, 1, 1, 4, 4, [10, 11, 11, 0]], // SVGA3D_R11G11B10_FLOAT
    [0x1000, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_TYPELESS
    [0x4c00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_UNORM
    [0x5c00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_UNORM_SRGB
    [0x4400f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_UINT
    [0x4200f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_SINT
    [0x1000, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_TYPELESS
    [0x44006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_UINT
    [0x42006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_SINT
    [0x1000, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_R32_TYPELESS
    [0x80040, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_D32_FLOAT
    [0x44004, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_R32_UINT
    [0x42004, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_R32_SINT
    [0x1000, 1, 1, 1, 4, 4, [0, 8, 24, 0]], // SVGA3D_R24G8_TYPELESS
    [0x8c800, 1, 1, 1, 4, 4, [0, 8, 24, 0]], // SVGA3D_D24_UNORM_S8_UINT
    [0x4c004, 1, 1, 1, 4, 4, [0, 0, 24, 0]], // SVGA3D_R24_UNORM_X8
    [0x44002, 1, 1, 1, 4, 4, [0, 8, 0, 0]], // SVGA3D_X24_G8_UINT
    [0x1000, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_R8G8_TYPELESS
    [0x4c006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_R8G8_UNORM
    [0x44006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_R8G8_UINT
    [0x42006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_R8G8_SINT
    [0x1000, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_TYPELESS
    [0x4c004, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_UNORM
    [0x44004, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_UINT
    [0x4a004, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_SNORM
    [0x42004, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_SINT
    [0x1000, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_R8_TYPELESS
    [0x4c004, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_R8_UNORM
    [0x44004, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_R8_UINT
    [0x4a004, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_R8_SNORM
    [0x42004, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_R8_SINT
    [0x0, 1, 1, 1, 1, 1, [0, 0, 8, 0]], // SVGA3D_P8
    [0x60007, 1, 1, 1, 4, 4, [9, 9, 9, 5]], // SVGA3D_R9G9B9E5_SHAREDEXP
    [0x0, 2, 1, 1, 4, 4, [0, 8, 8, 0]], // SVGA3D_R8G8_B8G8_UNORM
    [0x0, 2, 1, 1, 4, 4, [0, 8, 8, 0]], // SVGA3D_G8R8_G8B8_UNORM
    [0x1001020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC1_TYPELESS
    [0x105c020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC1_UNORM_SRGB
    [0x2001020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC2_TYPELESS
    [0x205c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC2_UNORM_SRGB
    [0x4001020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC3_TYPELESS
    [0x405c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC3_UNORM_SRGB
    [0x8001020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC4_TYPELESS
    [0x804c020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_ATI1
    [0x804a020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC4_SNORM
    [0x10001020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC5_TYPELESS
    [0x1004c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_ATI2
    [0x1004a020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC5_SNORM
    [0x4c00f, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_R10G10B10_XR_BIAS_A2_UNORM
    [0x1000, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_B8G8R8A8_TYPELESS
    [0x5c00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_B8G8R8A8_UNORM_SRGB
    [0x1000, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_B8G8R8X8_TYPELESS
    [0x5c007, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_B8G8R8X8_UNORM_SRGB
    [0x8c000, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_Z_DF16
    [0x8c000, 1, 1, 1, 4, 4, [0, 0, 24, 0]], // SVGA3D_Z_DF24
    [0x8c800, 1, 1, 1, 4, 4, [0, 8, 24, 0]], // SVGA3D_Z_D24S8_INT
    [0x240280, 2, 2, 1, 6, 2, [0, 0, 48, 0]], // SVGA3D_YV12
    [0x4004f, 1, 1, 1, 16, 16, [32, 32, 32, 32]], // SVGA3D_R32G32B32A32_FLOAT
    [0x4004f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_FLOAT
    [0x4c00f, 1, 1, 1, 8, 8, [16, 16, 16, 16]], // SVGA3D_R16G16B16A16_UNORM
    [0x40046, 1, 1, 1, 8, 8, [0, 32, 32, 0]], // SVGA3D_R32G32_FLOAT
    [0x4c00f, 1, 1, 1, 4, 4, [10, 10, 10, 2]], // SVGA3D_R10G10B10A2_UNORM
    [0x4a00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_R8G8B8A8_SNORM
    [0x40046, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_FLOAT
    [0x4c006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_UNORM
    [0x4a006, 1, 1, 1, 4, 4, [0, 16, 16, 0]], // SVGA3D_R16G16_SNORM
    [0x40044, 1, 1, 1, 4, 4, [0, 0, 32, 0]], // SVGA3D_R32_FLOAT
    [0x4a006, 1, 1, 1, 2, 2, [0, 8, 8, 0]], // SVGA3D_R8G8_SNORM
    [0x40044, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_R16_FLOAT
    [0x8c000, 1, 1, 1, 2, 2, [0, 0, 16, 0]], // SVGA3D_D16_UNORM
    [0x4c008, 1, 1, 1, 1, 1, [0, 0, 0, 8]], // SVGA3D_A8_UNORM
    [0x104c020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC1_UNORM
    [0x204c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC2_UNORM
    [0x404c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC3_UNORM
    [0x4c007, 1, 1, 1, 2, 2, [5, 6, 5, 0]], // SVGA3D_B5G6R5_UNORM
    [0x4c00f, 1, 1, 1, 2, 2, [5, 5, 5, 1]], // SVGA3D_B5G5R5A1_UNORM
    [0x4c00f, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_B8G8R8A8_UNORM
    [0x4c007, 1, 1, 1, 4, 4, [8, 8, 8, 0]], // SVGA3D_B8G8R8X8_UNORM
    [0x804c020, 4, 4, 1, 8, 8, [0, 0, 64, 0]], // SVGA3D_BC4_UNORM
    [0x1004c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC5_UNORM
    [0x4c00f, 1, 1, 1, 2, 2, [4, 4, 4, 4]], // SVGA3D_B4G4R4A4_UNORM
    [0x20001020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC6H_TYPELESS
    [0x20000020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC6H_UF16
    [0x20000020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC6H_SF16
    [0x40001020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC7_TYPELESS
    [0x4004c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC7_UNORM
    [0x4005c020, 4, 4, 1, 16, 16, [0, 0, 128, 0]], // SVGA3D_BC7_UNORM_SRGB
    [0x240008, 1, 1, 1, 4, 4, [8, 8, 8, 8]], // SVGA3D_AYUV
    [0x1000, 1, 1, 1, 4, 4, [10, 11, 11, 0]], // SVGA3D_R11G11B10_TYPELESS
];
                                              source/v64/src/graphics_adapters/vmware_svga/svga_gb.js                                             0000644 0000000 0000000 00000020741 00000000000 020431  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Guest-backed objects (SVGA_CAP_GBOBJECTS, level gb9 and up;
// docs/gpu-devices.md, "VMware SVGA II"): memory objects (MOBs) and the
// object tables that list the guest's MOBs, surfaces, contexts, shaders and
// screen targets.
//
// A MOB is guest memory the driver names by an id: a page table of one of
// the SVGAMobFormat shapes, walked once when the MOB is defined. Objects
// keep their contents in MOBs (a surface's image, a shader's bytecode, a
// query's result); svga3d.js moves them between the MOBs and the GPU.
//
// The object tables are guest memory too, but the device owns their
// contents: it writes an entry when an object is defined and clears it when
// the object goes. A driver that set a table up again after a reset, with
// validSizeInBytes covering entries, gets those objects back (load_otable).

import { LOG_VGA } from "../../const.js";
import { dbg_log } from "../../log.js";
import * as C from "./svga_constants.js";
import { read_pages, write_pages } from "./svga_gmr.js";

// For Types Only
import { GraphicsMachine } from "../machine.js";

const PAGE = 4096;

/** The largest MOB taken (SVGA_REG_MOB_MAX_SIZE) */
export const MOB_MAX_SIZE = 256 << 20;
/** How much guest memory the driver should give GB objects, in KiB */
export const GB_MEMORY_KB = 1 << 20;

/** Bytes per entry of each SVGAOTableType */
export const OTABLE_ENTRY_BYTES = [16, 64, 8, 16, 64, 8];
export const OTABLE_TYPES = OTABLE_ENTRY_BYTES.length;

/**
 * The pages behind a page table (SVGAMobFormat)
 * @param {GraphicsMachine} machine
 * @param {number} format
 * @param {number} base page number: of the data (PT_0, RANGE) or of the table
 * @param {number} size in bytes
 * @return {Float64Array} null if the format or size is invalid
 */
export function mob_pages(machine, format, base, size)
{
    if(size > MOB_MAX_SIZE) return null;
    const count = Math.ceil(size / PAGE);
    const pages = new Float64Array(count);
    switch(format)
    {
        case C.SVGA3D_MOBFMT_EMPTY:
            return count === 0 ? pages : null;
        case C.SVGA3D_MOBFMT_RANGE:
        case C.SVGA3D_MOBFMT_PT_0:
        case C.SVGA3D_MOBFMT_PT64_0:
            // the data itself (depth 0 is one page; more is taken as a run)
            for(let i = 0; i < count; i++) pages[i] = base + i;
            return pages;
        case C.SVGA3D_MOBFMT_PT_1:
        case C.SVGA3D_MOBFMT_PT64_1:
        case C.SVGA3D_MOBFMT_PT_2:
        case C.SVGA3D_MOBFMT_PT64_2:
        {
            const wide = format >= C.SVGA3D_MOBFMT_PT64_0;
            const per_page = wide ? PAGE / 8 : PAGE / 4;
            const depth = format === C.SVGA3D_MOBFMT_PT_1 || format === C.SVGA3D_MOBFMT_PT64_1 ? 1 : 2;
            if(count > (depth === 1 ? per_page : per_page * per_page)) return null;
            const table = ppn => {
                const view = new DataView(machine.read_physical(ppn * PAGE, PAGE).slice().buffer);
                return wide ? i => view.getUint32(i * 8, true) + view.getUint32(i * 8 + 4, true) * 0x100000000 :
                    i => view.getUint32(i * 4, true);
            };
            if(depth === 1)
            {
                const entry = table(base);
                for(let i = 0; i < count; i++) pages[i] = entry(i);
            }
            else
            {
                const top = table(base);
                for(let t = 0; t * per_page < count; t++)
                {
                    const entry = table(top(t));
                    for(let i = t * per_page; i < Math.min(count, (t + 1) * per_page); i++) pages[i] = entry(i - t * per_page);
                }
            }
            return pages;
        }
    }
    return null;
}

/**
 * The guest's MOBs, by id. read and write are those of GMRTable, so the
 * code that copies images works on either.
 * @constructor
 * @param {GraphicsMachine} machine
 */
export function MOBTable(machine)
{
    this.machine = machine;
    /** @type {!Map<number, {format: number, base: number, size: number, pages: !Float64Array}>} */
    this.mobs = new Map();
}

MOBTable.prototype.reset = function()
{
    this.mobs.clear();
};

/**
 * @return {boolean} whether the page table was valid
 */
MOBTable.prototype.define = function(id, format, base, size)
{
    const pages = mob_pages(this.machine, format, base, size);
    if(!pages)
    {
        dbg_log("svga: invalid MOB " + id + " (format " + format + ", " + size + " bytes)", LOG_VGA);
        return false;
    }
    this.mobs.set(id, { format, base, size, pages });
    return true;
};

MOBTable.prototype.destroy = function(id)
{
    this.mobs.delete(id);
};

/**
 * @return {number} the size of a MOB in bytes, -1 if there is none
 */
MOBTable.prototype.size = function(id)
{
    const mob = this.mobs.get(id);
    return mob ? mob.size : -1;
};

/**
 * @return {Uint8Array} a copy, or null if not inside the MOB
 */
MOBTable.prototype.read = function(id, offset, length)
{
    const mob = this.mobs.get(id);
    if(!mob || offset < 0 || offset + length > mob.size) return null;
    return read_pages(this.machine, mob.pages, offset, length);
};

/**
 * @param {!Uint8Array} bytes
 * @return {boolean}
 */
MOBTable.prototype.write = function(id, offset, bytes)
{
    const mob = this.mobs.get(id);
    if(!mob || offset < 0 || offset + bytes.length > mob.size) return false;
    return write_pages(this.machine, mob.pages, offset, bytes);
};

/**
 * A dword of a MOB (0 outside of it)
 */
MOBTable.prototype.read32 = function(id, offset)
{
    const bytes = this.read(id, offset, 4);
    return bytes ? (bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) >>> 0 : 0;
};

MOBTable.prototype.write32 = function(id, offset, value)
{
    return this.write(id, offset, new Uint8Array(Uint32Array.of(value).buffer));
};

MOBTable.prototype.get_state = function()
{
    const state = [];
    for(const [id, mob] of this.mobs) state.push([id, mob.format, mob.base, mob.size, mob.pages]);
    return state;
};

MOBTable.prototype.set_state = function(state)
{
    this.mobs.clear();
    for(const [id, format, base, size, pages] of state)
    {
        this.mobs.set(id, { format, base, size, pages: Float64Array.from(pages) });
    }
};

/**
 * The object tables (SET_OTABLE_BASE): where each is, in guest memory
 * @constructor
 * @param {GraphicsMachine} machine
 */
export function OTables(machine)
{
    this.machine = machine;
    /** @type {!Array<?{format: number, base: number, size: number, pages: !Float64Array}>} */
    this.tables = [];
    this.reset();
}

OTables.prototype.reset = function()
{
    this.tables = new Array(OTABLE_TYPES).fill(null);
};

/**
 * SET_OTABLE_BASE(64) and GROW_OTABLE
 * @return {boolean}
 */
OTables.prototype.set = function(type, format, base, size)
{
    if(type >= OTABLE_TYPES) return false;
    if(!size)
    {
        this.tables[type] = null;
        return true;
    }
    const pages = mob_pages(this.machine, format, base, size);
    if(!pages) return false;
    this.tables[type] = { format, base, size, pages };
    return true;
};

/**
 * The number of entries a table has room for
 */
OTables.prototype.capacity = function(type)
{
    const table = this.tables[type];
    return table ? Math.floor(table.size / OTABLE_ENTRY_BYTES[type]) : 0;
};

/**
 * @return {Uint8Array} the entry, or null if the table is not that big
 */
OTables.prototype.read_entry = function(type, index)
{
    const table = this.tables[type], bytes = OTABLE_ENTRY_BYTES[type];
    if(!table || (index + 1) * bytes > table.size) return null;
    return read_pages(this.machine, table.pages, index * bytes, bytes);
};

/**
 * Write an entry (shorter `bytes` are padded with zeros); a cleared entry is
 * all zeros
 * @param {Uint8Array} bytes null to clear it
 */
OTables.prototype.write_entry = function(type, index, bytes)
{
    const table = this.tables[type], size = OTABLE_ENTRY_BYTES[type];
    if(!table || (index + 1) * size > table.size) return false;
    const entry = new Uint8Array(size);
    if(bytes) entry.set(bytes.subarray(0, size));
    return write_pages(this.machine, table.pages, index * size, entry);
};

OTables.prototype.get_state = function()
{
    return this.tables.map(t => t && [t.format, t.base, t.size, t.pages]);
};

OTables.prototype.set_state = function(state)
{
    this.reset();
    state.forEach((t, type) => {
        if(t) this.tables[type] = { format: t[0], base: t[1], size: t[2], pages: Float64Array.from(t[3]) };
    });
};

/**
 * The dwords of an entry, as a little-endian view
 * @param {!Uint8Array} bytes
 * @return {!DataView}
 */
export function entry_view(bytes)
{
    return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
}
                               source/v64/src/graphics_adapters/vmware_svga/svga_gmr.js                                            0000644 0000000 0000000 00000016203 00000000000 020624  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Guest Memory Regions: guest RAM the driver lends the device, as lists of
// physical pages. GMR1 is defined through registers (a chain of
// SVGAGuestMemDescriptor pages), GMR2 through FIFO commands (DEFINE_GMR2,
// REMAP_GMR2). SVGAGuestPtr { gmrId, offset } addresses them; two ids are
// special: SVGA_GMR_FRAMEBUFFER (the frame buffer) and SVGA_GMR_NULL.

import * as C from "./svga_constants.js";

// For Types Only
import { GraphicsMachine } from "../machine.js";

const PAGE = 4096;

/** What the device reports and enforces */
export const GMR_MAX_IDS = 64;
export const GMR_MAX_PAGES = 1 << 18;           // 1 GiB of 4 KiB pages
export const GMR_MAX_DESCRIPTOR_LENGTH = 4096;

/**
 * @constructor
 * @param {GraphicsMachine} machine
 * @param {function():!Uint8Array} vram the frame buffer's memory
 */
export function GMRTable(machine, vram)
{
    this.machine = machine;
    this.vram = vram;
    /** @type {!Map<number, !Float64Array>} the guest physical page number of each page */
    this.regions = new Map();
}

GMRTable.prototype.reset = function()
{
    this.regions.clear();
};

/**
 * GMR1: SVGA_REG_GMR_DESCRIPTOR written for the id in SVGA_REG_GMR_ID
 * @param {number} id
 * @param {number} ppn of the first descriptor page, 0 to undefine
 * @return {boolean} whether the descriptor was valid
 */
GMRTable.prototype.define_gmr1 = function(id, ppn)
{
    if(id >= GMR_MAX_IDS) return false;
    if(!ppn)
    {
        this.regions.delete(id);
        return true;
    }
    const pages = [];
    for(let descriptor_pages = 0; ppn && descriptor_pages < GMR_MAX_DESCRIPTOR_LENGTH; descriptor_pages++)
    {
        const page = new DataView(this.machine.read_physical(ppn * PAGE, PAGE).slice().buffer);
        let next = 0;
        for(let at = 0; at < PAGE; at += 8)
        {
            const entry_ppn = page.getUint32(at, true), count = page.getUint32(at + 4, true);
            if(!count)
            {
                // no pages: the next descriptor page, or (ppn 0) the end
                next = entry_ppn;
                break;
            }
            if(pages.length + count > GMR_MAX_PAGES) return false;
            for(let i = 0; i < count; i++) pages.push(entry_ppn + i);
        }
        ppn = next;
    }
    this.regions.set(id, Float64Array.from(pages));
    return true;
};

/**
 * DEFINE_GMR2: a region of num_pages unmapped pages (0 undefines it)
 * @param {number} id
 * @param {number} num_pages
 */
GMRTable.prototype.define_gmr2 = function(id, num_pages)
{
    if(id >= GMR_MAX_IDS || num_pages > GMR_MAX_PAGES) return false;
    if(!num_pages) this.regions.delete(id);
    else this.regions.set(id, new Float64Array(num_pages));
    return true;
};

/**
 * REMAP_GMR2: pages offset..offset+count of a region get the given PPNs
 * @param {number} id
 * @param {number} flags SVGA_REMAP_GMR2_*
 * @param {number} offset first page
 * @param {number} count pages
 * @param {function(number):number} ppn the i-th page number of the command
 * @return {boolean}
 */
GMRTable.prototype.remap_gmr2 = function(id, flags, offset, count, ppn)
{
    const region = this.regions.get(id);
    if(!region || offset + count > region.length) return false;
    for(let i = 0; i < count; i++)
    {
        region[offset + i] = flags & C.SVGA_REMAP_GMR2_SINGLE_PPN ? ppn(0) : ppn(i);
    }
    return true;
};

/**
 * The number of dwords of a REMAP_GMR2 command after its header
 * @param {number} flags
 * @param {number} count
 * @return {number}
 */
export function remap_gmr2_payload(flags, count)
{
    if(flags & C.SVGA_REMAP_GMR2_VIA_GMR) return 2;     // an SVGAGuestPtr to the list
    const entry = flags & C.SVGA_REMAP_GMR2_PPN64 ? 2 : 1;
    return flags & C.SVGA_REMAP_GMR2_SINGLE_PPN ? entry : entry * count;
}

/**
 * The guest physical runs behind [offset, offset + length) of a list of pages
 * @param {!Float64Array} pages guest physical page numbers
 * @param {number} offset
 * @param {number} length
 * @return {Array<{address: number, length: number}>} null if out of the pages
 */
export function page_runs(pages, offset, length)
{
    if(offset < 0 || length < 0 || offset + length > pages.length * PAGE) return null;
    const runs = [];
    let at = offset, left = length;
    while(left > 0)
    {
        const page = Math.floor(at / PAGE), within = at % PAGE;
        const take = Math.min(left, PAGE - within);
        const address = pages[page] * PAGE + within;
        const last = runs[runs.length - 1];
        if(last && last.address + last.length === address) last.length += take;
        else runs.push({ address, length: take });
        at += take;
        left -= take;
    }
    return runs;
}

/**
 * Read from a list of pages
 * @param {GraphicsMachine} machine
 * @param {!Float64Array} pages
 * @param {number} offset
 * @param {number} length
 * @return {Uint8Array} a copy, or null if the range is not in the pages
 */
export function read_pages(machine, pages, offset, length)
{
    const runs = page_runs(pages, offset, length);
    if(!runs) return null;
    if(runs.length === 1) return machine.read_physical(runs[0].address, length).slice();
    const out = new Uint8Array(length);
    let at = 0;
    for(const run of runs)
    {
        out.set(machine.read_physical(run.address, run.length), at);
        at += run.length;
    }
    return out;
}

/**
 * Write into a list of pages
 * @param {GraphicsMachine} machine
 * @param {!Float64Array} pages
 * @param {number} offset
 * @param {!Uint8Array} bytes
 * @return {boolean}
 */
export function write_pages(machine, pages, offset, bytes)
{
    const runs = page_runs(pages, offset, bytes.length);
    if(!runs) return false;
    let at = 0;
    for(const run of runs)
    {
        machine.write_physical(bytes.subarray(at, at + run.length), run.address);
        at += run.length;
    }
    return true;
}

/**
 * Read through an SVGAGuestPtr
 * @param {number} id
 * @param {number} offset
 * @param {number} length
 * @return {Uint8Array} a copy, or null if the range is not in the region
 */
GMRTable.prototype.read = function(id, offset, length)
{
    if(id === C.SVGA_GMR_FRAMEBUFFER)
    {
        const vram = this.vram();
        if(offset < 0 || offset + length > vram.length) return null;
        return vram.slice(offset, offset + length);
    }
    const region = this.regions.get(id);
    return region ? read_pages(this.machine, region, offset, length) : null;
};

/**
 * Write through an SVGAGuestPtr
 * @param {number} id
 * @param {number} offset
 * @param {!Uint8Array} bytes
 * @return {boolean}
 */
GMRTable.prototype.write = function(id, offset, bytes)
{
    if(id === C.SVGA_GMR_FRAMEBUFFER)
    {
        const vram = this.vram();
        if(offset < 0 || offset + bytes.length > vram.length) return false;
        vram.set(bytes, offset);
        return true;
    }
    const region = this.regions.get(id);
    return region ? write_pages(this.machine, region, offset, bytes) : false;
};

GMRTable.prototype.get_state = function()
{
    const state = [];
    for(const [id, pages] of this.regions) state.push(id, pages);
    return state;
};

GMRTable.prototype.set_state = function(state)
{
    this.regions.clear();
    for(let i = 0; i < state.length; i += 2) this.regions.set(state[i], Float64Array.from(state[i + 1]));
};
                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/graphics_adapters/vmware_svga/svga_screens.js                                        0000644 0000000 0000000 00000032147 00000000000 021506  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Screen Objects (SVGA_FIFO_CAP_SCREEN_OBJECT, SVGA_CAP_SCREEN_OBJECT_2):
// monitors the driver defines, each with a position on the virtual desktop.
// A screen with no backing store (screen object 2) keeps its picture here;
// the driver fills it with BLIT_GMRFB_TO_SCREEN from a GMRFB (an image in a
// GMR) and reads it back with BLIT_SCREEN_TO_GMRFB. A screen backed by the
// frame buffer shows VRAM, converted when UPDATE covers it.

import * as C from "./svga_constants.js";

/**
 * One screen object
 * @constructor
 */
function Screen(id, flags, width, height, x, y, backing)
{
    this.id = id;
    this.flags = flags;
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    /** @type {?{gmr: number, offset: number, pitch: number}} */
    this.backing = backing;
    /** RGBA, row after row */
    this.rgba = new Uint8ClampedArray(width * height * 4);
    // rows changed since the last render
    this.dirty_min = 0;
    this.dirty_max = height;
}

/**
 * @param {number} top
 * @param {number} bottom (exclusive)
 */
Screen.prototype.mark = function(top, bottom)
{
    if(this.dirty_min >= this.dirty_max)
    {
        this.dirty_min = top;
        this.dirty_max = bottom;
    }
    else
    {
        this.dirty_min = Math.min(this.dirty_min, top);
        this.dirty_max = Math.max(this.dirty_max, bottom);
    }
};

/**
 * @constructor
 * @param {{read: function(number, number, number):Uint8Array, write: function(number, number, !Uint8Array):boolean}} gmrs
 */
export function ScreenObjects(gmrs)
{
    this.gmrs = gmrs;
    /** @type {!Map<number, !Screen>} */
    this.screens = new Map();
    /** The image BLIT_* commands read and write: SVGA_CMD_DEFINE_GMRFB */
    this.gmrfb = { gmr: C.SVGA_GMR_NULL, offset: 0, pitch: 0, bpp: 32, depth: 24 };
    // The desktop's bounding box changed: the display needs a new size
    this.layout_changed = true;
}

ScreenObjects.prototype.reset = function()
{
    this.screens.clear();
    this.gmrfb = { gmr: C.SVGA_GMR_NULL, offset: 0, pitch: 0, bpp: 32, depth: 24 };
    this.layout_changed = true;
};

/**
 * DEFINE_SCREEN: an SVGAScreenObject, structSize bytes from its first dword
 * @param {function(number):number} read the structure's dwords
 * @param {number} dwords how many there are
 * @return {boolean}
 */
ScreenObjects.prototype.define = function(read, dwords)
{
    const id = read(1) >>> 0, flags = read(2) >>> 0;
    const width = read(3) >>> 0, height = read(4) >>> 0;
    const x = read(5) | 0, y = read(6) | 0;
    if(!width || !height || width > C.SVGA_MAX_SCREEN_SIZE || height > C.SVGA_MAX_SCREEN_SIZE ||
        id >= C.SVGA_MAX_DISPLAYS)
    {
        return false;
    }
    let backing = null;
    if(dwords >= 10)
    {
        const gmr = read(7) >>> 0;
        if(gmr !== C.SVGA_GMR_NULL) backing = { gmr, offset: read(8) >>> 0, pitch: read(9) >>> 0 };
    }
    if(flags & C.SVGA_SCREEN_DEACTIVATE)
    {
        this.screens.delete(id);
    }
    else
    {
        const old = this.screens.get(id);
        const screen = new Screen(id, flags, width, height, x, y, backing);
        // a moved or resized screen keeps what it can of its picture
        if(old && !backing)
        {
            const w = Math.min(old.width, width) * 4;
            for(let row = 0; row < Math.min(old.height, height); row++)
            {
                screen.rgba.set(old.rgba.subarray(row * old.width * 4, row * old.width * 4 + w), row * width * 4);
            }
        }
        if(backing) this.convert_backing(screen, 0, 0, width, height);
        this.screens.set(id, screen);
    }
    this.layout_changed = true;
    return true;
};

/**
 * DEFINE_GB_SCREENTARGET: a screen whose picture comes from a surface
 * (svga3d.js); like a screen object without backing store
 * @return {boolean}
 */
ScreenObjects.prototype.define_target = function(id, flags, width, height, x, y)
{
    if(!width || !height || width > C.SVGA_MAX_SCREEN_SIZE || height > C.SVGA_MAX_SCREEN_SIZE || id >= C.SVGA_MAX_DISPLAYS)
    {
        return false;
    }
    const old = this.screens.get(id);
    const screen = new Screen(id, flags & C.SVGA_STFLAG_PRIMARY ? C.SVGA_SCREEN_IS_PRIMARY : 0, width, height, x, y, null);
    if(old)
    {
        const w = Math.min(old.width, width) * 4;
        for(let row = 0; row < Math.min(old.height, height); row++)
        {
            screen.rgba.set(old.rgba.subarray(row * old.width * 4, row * old.width * 4 + w), row * width * 4);
        }
    }
    this.screens.set(id, screen);
    this.layout_changed = true;
    return true;
};

/**
 * A screen target without an image shows black
 * @param {number} id
 */
ScreenObjects.prototype.blank = function(id)
{
    const screen = this.screens.get(id);
    if(!screen) return;
    screen.rgba.fill(0);
    for(let i = 3; i < screen.rgba.length; i += 4) screen.rgba[i] = 255;
    screen.mark(0, screen.height);
};

/** @param {number} id */
ScreenObjects.prototype.destroy = function(id)
{
    this.screens.delete(id);
    this.layout_changed = true;
};

ScreenObjects.prototype.define_gmrfb = function(gmr, offset, pitch, format)
{
    this.gmrfb = { gmr, offset, pitch, bpp: format & 0xFF, depth: format >> 8 & 0xFF };
};

/**
 * Bytes of one GMRFB pixel, or 0 for a format this device does not take
 * @return {number}
 */
ScreenObjects.prototype.gmrfb_bytes = function()
{
    const { bpp } = this.gmrfb;
    return bpp === 32 ? 4 : bpp === 16 ? 2 : 0;
};

/**
 * Convert one row of GMRFB pixels into RGBA
 * @param {!Uint8Array} source
 * @param {!Uint8ClampedArray} target
 * @param {number} at in target
 * @param {number} count pixels
 */
ScreenObjects.prototype.to_rgba = function(source, target, at, count)
{
    if(this.gmrfb.bpp === 32)
    {
        for(let i = 0, s = 0; i < count; i++, s += 4)
        {
            target[at++] = source[s + 2];
            target[at++] = source[s + 1];
            target[at++] = source[s];
            target[at++] = 255;
        }
    }
    else
    {
        const r5g6b5 = this.gmrfb.depth !== 15;
        for(let i = 0, s = 0; i < count; i++, s += 2)
        {
            const v = source[s] | source[s + 1] << 8;
            if(r5g6b5)
            {
                target[at++] = (v >> 11 & 31) * 255 / 31;
                target[at++] = (v >> 5 & 63) * 255 / 63;
            }
            else
            {
                target[at++] = (v >> 10 & 31) * 255 / 31;
                target[at++] = (v >> 5 & 31) * 255 / 31;
            }
            target[at++] = (v & 31) * 255 / 31;
            target[at++] = 255;
        }
    }
};

/**
 * Clip a rectangle to a screen: [left, top, right, bottom) or null
 */
function clip(screen, left, top, right, bottom)
{
    left = Math.max(left, 0);
    top = Math.max(top, 0);
    right = Math.min(right, screen.width);
    bottom = Math.min(bottom, screen.height);
    return left < right && top < bottom ? [left, top, right, bottom] : null;
}

/**
 * BLIT_GMRFB_TO_SCREEN: destRect is in the screen's coordinates, the source
 * starts at srcOrigin of the GMRFB
 * @return {boolean}
 */
ScreenObjects.prototype.blit_to_screen = function(src_x, src_y, left, top, right, bottom, screen_id)
{
    const screen = this.screens.get(screen_id);
    const bytes = this.gmrfb_bytes();
    if(!screen || !bytes) return false;
    const rect = clip(screen, left, top, right, bottom);
    if(!rect) return true;
    const [l, t, r, b] = rect;
    src_x += l - left;
    src_y += t - top;
    const { gmr, offset, pitch } = this.gmrfb;
    for(let row = t; row < b; row++)
    {
        const from = offset + (src_y + row - t) * pitch + src_x * bytes;
        const pixels = this.gmrs.read(gmr, from, (r - l) * bytes);
        if(!pixels) return false;
        this.to_rgba(pixels, screen.rgba, (row * screen.width + l) * 4, r - l);
    }
    if(screen.backing)
    {
        // the backing store holds the screen's picture too
        this.copy_to_backing(screen, l, t, r, b);
    }
    screen.mark(t, b);
    return true;
};

/**
 * BLIT_SCREEN_TO_GMRFB: srcRect in the screen's coordinates, into the GMRFB
 * at destOrigin (32 bpp only)
 * @return {boolean}
 */
ScreenObjects.prototype.blit_from_screen = function(dst_x, dst_y, left, top, right, bottom, screen_id)
{
    const screen = this.screens.get(screen_id);
    if(!screen || this.gmrfb.bpp !== 32) return false;
    const rect = clip(screen, left, top, right, bottom);
    if(!rect) return true;
    const [l, t, r, b] = rect;
    dst_x += l - left;
    dst_y += t - top;
    const { gmr, offset, pitch } = this.gmrfb;
    const row_bytes = new Uint8Array((r - l) * 4);
    for(let row = t; row < b; row++)
    {
        const from = (row * screen.width + l) * 4;
        for(let i = 0; i < r - l; i++)
        {
            row_bytes[i * 4] = screen.rgba[from + i * 4 + 2];
            row_bytes[i * 4 + 1] = screen.rgba[from + i * 4 + 1];
            row_bytes[i * 4 + 2] = screen.rgba[from + i * 4];
            row_bytes[i * 4 + 3] = 0;
        }
        if(!this.gmrs.write(gmr, offset + (dst_y + row - t) * pitch + dst_x * 4, row_bytes)) return false;
    }
    return true;
};

/**
 * Screens backed by the frame buffer (or a GMR): bring the picture in a
 * rectangle of the screen up to date from the backing store
 */
ScreenObjects.prototype.convert_backing = function(screen, left, top, right, bottom)
{
    const rect = clip(screen, left, top, right, bottom);
    if(!rect) return;
    const [l, t, r, b] = rect;
    const { gmr, offset, pitch } = screen.backing;
    for(let row = t; row < b; row++)
    {
        const pixels = this.gmrs.read(gmr, offset + row * pitch + l * 4, (r - l) * 4);
        if(!pixels) return;
        let at = (row * screen.width + l) * 4;
        for(let i = 0; i < pixels.length; i += 4)
        {
            screen.rgba[at++] = pixels[i + 2];
            screen.rgba[at++] = pixels[i + 1];
            screen.rgba[at++] = pixels[i];
            screen.rgba[at++] = 255;
        }
    }
    screen.mark(t, b);
};

/**
 * The opposite, after a blit into a backed screen
 */
ScreenObjects.prototype.copy_to_backing = function(screen, l, t, r, b)
{
    const { gmr, offset, pitch } = screen.backing;
    const row_bytes = new Uint8Array((r - l) * 4);
    for(let row = t; row < b; row++)
    {
        const from = (row * screen.width + l) * 4;
        for(let i = 0; i < r - l; i++)
        {
            row_bytes[i * 4] = screen.rgba[from + i * 4 + 2];
            row_bytes[i * 4 + 1] = screen.rgba[from + i * 4 + 1];
            row_bytes[i * 4 + 2] = screen.rgba[from + i * 4];
        }
        this.gmrs.write(gmr, offset + row * pitch + l * 4, row_bytes);
    }
};

/**
 * UPDATE in screen object mode: a rectangle of the virtual desktop
 */
ScreenObjects.prototype.update = function(x, y, width, height)
{
    for(const screen of this.screens.values())
    {
        if(screen.backing)
        {
            this.convert_backing(screen, x - screen.x, y - screen.y, x - screen.x + width, y - screen.y + height);
        }
    }
};

/**
 * The bounding box of all screens on the virtual desktop
 * @return {{x: number, y: number, width: number, height: number}}
 */
ScreenObjects.prototype.bounds = function()
{
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
    for(const s of this.screens.values())
    {
        x0 = Math.min(x0, s.x); y0 = Math.min(y0, s.y);
        x1 = Math.max(x1, s.x + s.width); y1 = Math.max(y1, s.y + s.height);
    }
    return x0 === Infinity ? { x: 0, y: 0, width: 0, height: 0 } : { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
};

/**
 * The layers of everything that changed, for DisplaySink.update_buffer, and
 * forget the changes
 * @param {boolean} all every row, not only changed ones
 * @return {!Array<!Object>}
 */
ScreenObjects.prototype.take_layers = function(all)
{
    const box = this.bounds();
    const layers = [];
    for(const s of this.screens.values())
    {
        const top = all ? 0 : s.dirty_min, bottom = all ? s.height : s.dirty_max;
        if(top < bottom)
        {
            layers.push({
                pixels: { data: s.rgba, width: s.width, height: s.height },
                screen_x: s.x - box.x, screen_y: s.y - box.y + top,
                buffer_x: 0, buffer_y: top,
                buffer_width: s.width, buffer_height: bottom - top,
            });
        }
        s.dirty_min = s.dirty_max = 0;
    }
    return layers;
};

ScreenObjects.prototype.get_state = function()
{
    const screens = [];
    for(const s of this.screens.values())
    {
        screens.push([s.id, s.flags, s.width, s.height, s.x, s.y,
            s.backing ? [s.backing.gmr, s.backing.offset, s.backing.pitch] : null,
            new Uint8Array(s.rgba.buffer, s.rgba.byteOffset, s.rgba.length)]);
    }
    const g = this.gmrfb;
    return [screens, [g.gmr, g.offset, g.pitch, g.bpp, g.depth]];
};

ScreenObjects.prototype.set_state = function(state)
{
    this.screens.clear();
    for(const [id, flags, width, height, x, y, backing, rgba] of state[0])
    {
        const screen = new Screen(id, flags, width, height, x, y,
            backing ? { gmr: backing[0], offset: backing[1], pitch: backing[2] } : null);
        screen.rgba.set(rgba);
        this.screens.set(id, screen);
    }
    const [gmr, offset, pitch, bpp, depth] = state[1];
    this.gmrfb = { gmr, offset, pitch, bpp, depth };
    this.layout_changed = true;
};
                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/graphics_adapters/vmware_svga/svga_video.js                                          0000644 0000000 0000000 00000026607 00000000000 021156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VMware SVGA II's video overlay (SVGA_FIFO_CAP_VIDEO; svga_overlay.h):
// 32 overlay units, set by SVGA_CMD_ESCAPE's SVGA_ESCAPE_VMWARE_VIDEO_SET_REGS
// and shown by SVGA_ESCAPE_VMWARE_VIDEO_FLUSH. A unit shows a YV12, YUY2 or
// UYVY frame from a GMR (or VRAM), its source rectangle scaled to a
// destination rectangle of the desktop, where the desktop has the unit's
// color key if it has one. Like the cursor, the overlay is drawn over the
// device's picture, never into guest memory: each unit keeps a patch, the
// desktop under its rectangle with the video where it shows, made again when
// a frame comes or the picture under it changes.

import * as C from "./svga_constants.js";

const NUM_UNITS = 32;
const REG = {
    ENABLED: 0, FLAGS: 1, DATA_OFFSET: 2, FORMAT: 3, COLORKEY: 4, SIZE: 5, WIDTH: 6, HEIGHT: 7,
    SRC_X: 8, SRC_Y: 9, SRC_WIDTH: 10, SRC_HEIGHT: 11, DST_X: 12, DST_Y: 13, DST_WIDTH: 14, DST_HEIGHT: 15,
    PITCH_1: 16, PITCH_2: 17, PITCH_3: 18, DATA_GMRID: 19, DST_SCREEN_ID: 20,
};
const NUM_REGS = 21;
const FLAG_COLORKEY = 1;
const COLORKEY_MASK = 0x00FFFFFF;
export const ESCAPE_VIDEO = 0x00020000;
const ESCAPE_VIDEO_SET_REGS = 0x00020001;
const ESCAPE_VIDEO_FLUSH = 0x00020002;
const FOURCC_YV12 = 0x32315659, FOURCC_YUY2 = 0x32595559, FOURCC_UYVY = 0x59565955;
/** The largest destination rectangle a unit draws (pixels) */
const MAX_PIXELS = 4096 * 4096;

/**
 * @constructor
 * @param {function(number, number, number):Uint8Array} read guest memory
 *     through an SVGAGuestPtr (GMR id, offset, length)
 * @param {function(number):?{x: number, y: number}} screen a screen's place on
 *     the desktop, by id
 */
export function VideoOverlay(read, screen)
{
    this.read = read;
    this.screen = screen;
    /** @type {!Array<!Uint32Array>} */
    this.units = [];
    /** @type {!Array<?{x: number, y: number, w: number, h: number, video: !Uint8ClampedArray, key: number, patch: Uint8ClampedArray}>}
     * each unit's frame as last flushed: RGBA of the destination rectangle */
    this.frames = [];
    /** @type {!Array<!Array<number>>} the rectangles drawn last, to put the picture back */
    this.drawn = [];
    this.changed = false;
    this.stats = { flushes: 0, escapes: 0 };
    this.reset();
}

VideoOverlay.prototype.reset = function()
{
    this.units = [];
    for(let i = 0; i < NUM_UNITS; i++)
    {
        const regs = new Uint32Array(NUM_REGS);
        regs[REG.DATA_GMRID] = C.SVGA_GMR_FRAMEBUFFER;
        regs[REG.DST_SCREEN_ID] = C.SVGA_ID_INVALID;
        this.units.push(regs);
    }
    this.frames = new Array(NUM_UNITS).fill(null);
    this.changed = this.drawn.length > 0;
};

/** Whether any unit shows something */
VideoOverlay.prototype.active = function()
{
    return this.frames.some(f => f) || this.drawn.length > 0;
};

/**
 * SVGA_CMD_ESCAPE in the VMware namespace: a video command (command, unit,
 * then for SET_REGS register and value pairs)
 * @param {!Uint32Array} words the escape's payload
 * @return {boolean} whether it was one
 */
VideoOverlay.prototype.escape = function(words)
{
    if(words.length < 2 || (words[0] & 0xFFFF0000) !== ESCAPE_VIDEO) return false;
    const command = words[0], unit = words[1];
    this.stats.escapes++;
    if(unit >= NUM_UNITS) return true;
    const regs = this.units[unit];
    if(command === ESCAPE_VIDEO_SET_REGS)
    {
        for(let i = 2; i + 1 < words.length; i += 2)
        {
            if(words[i] < NUM_REGS) regs[words[i]] = words[i + 1];
        }
        // (switched off: gone at once; on: from the next flush)
        if(!regs[REG.ENABLED] && this.frames[unit])
        {
            this.frames[unit] = null;
            this.changed = true;
        }
    }
    else if(command === ESCAPE_VIDEO_FLUSH)
    {
        this.flush(unit);
    }
    return true;
};

/** FLUSH: the unit's frame, read and converted now */
VideoOverlay.prototype.flush = function(unit)
{
    const r = this.units[unit];
    this.stats.flushes++;
    this.changed = true;
    this.frames[unit] = null;
    if(!r[REG.ENABLED]) return;
    const w = r[REG.DST_WIDTH], h = r[REG.DST_HEIGHT], width = r[REG.WIDTH], height = r[REG.HEIGHT];
    if(!w || !h || !width || !height || w * h > MAX_PIXELS) return;
    const data = r[REG.SIZE] ? this.read(r[REG.DATA_GMRID], r[REG.DATA_OFFSET], r[REG.SIZE]) : null;
    if(!data) return;
    const sx = Math.min(r[REG.SRC_X], width - 1), sy = Math.min(r[REG.SRC_Y], height - 1);
    const sw = Math.max(1, Math.min(r[REG.SRC_WIDTH] || width, width - sx));
    const sh = Math.max(1, Math.min(r[REG.SRC_HEIGHT] || height, height - sy));
    const sample = sampler(r[REG.FORMAT], data, width, height, r[REG.PITCH_1], r[REG.PITCH_2], r[REG.PITCH_3]);
    if(!sample) return;
    const video = new Uint8ClampedArray(w * h * 4);
    const yuv = [0, 0, 0];
    for(let y = 0; y < h; y++)
    {
        const row = sy + Math.floor(y * sh / h);
        for(let x = 0; x < w; x++)
        {
            sample(sx + Math.floor(x * sw / w), row, yuv);
            // BT.601, video range
            const c = 1.164 * (yuv[0] - 16), d = yuv[1] - 128, e = yuv[2] - 128, at = (y * w + x) * 4;
            video[at] = c + 1.596 * e;
            video[at + 1] = c - 0.391 * d - 0.813 * e;
            video[at + 2] = c + 2.018 * d;
            video[at + 3] = 255;
        }
    }
    // (on a screen: its coordinates; else the desktop's)
    const place = r[REG.DST_SCREEN_ID] !== C.SVGA_ID_INVALID ? this.screen(r[REG.DST_SCREEN_ID]) : null;
    this.frames[unit] = {
        x: (r[REG.DST_X] | 0) + (place ? place.x : 0), y: (r[REG.DST_Y] | 0) + (place ? place.y : 0), w, h, video,
        key: r[REG.FLAGS] & FLAG_COLORKEY ? r[REG.COLORKEY] & COLORKEY_MASK : -1, patch: null,
    };
};

/**
 * How to read a pixel's Y, U and V from a frame in its format
 * @return {?function(number, number, !Array<number>)}
 */
function sampler(format, data, width, height, pitch1, pitch2, pitch3)
{
    const at = i => i < data.length ? data[i] : 0;
    switch(format)
    {
        case FOURCC_YUY2:
        case FOURCC_UYVY:
        {
            const pitch = pitch1 || width * 2, uyvy = format === FOURCC_UYVY;
            return (x, y, out) => {
                const pair = y * pitch + (x & ~1) * 2;
                out[0] = at(pair + (uyvy ? 1 : 0) + (x & 1) * 2);
                out[1] = at(pair + (uyvy ? 0 : 1));
                out[2] = at(pair + (uyvy ? 2 : 3));
            };
        }
        case FOURCC_YV12:
        {
            // Y, then V, then U (half size each way)
            const py = pitch1 || width, pv = pitch2 || (width + 1 >> 1), pu = pitch3 || pv;
            const v_at = py * height, u_at = v_at + pv * (height + 1 >> 1);
            return (x, y, out) => {
                out[0] = at(y * py + x);
                out[1] = at(u_at + (y >> 1) * pu + (x >> 1));
                out[2] = at(v_at + (y >> 1) * pv + (x >> 1));
            };
        }
    }
    return null;
}

const intersects = (a, x, y, w, h) => a[0] < x + w && x < a[0] + a[2] && a[1] < y + h && y < a[1] + a[3];

/**
 * The layers to send after the picture's own, before the cursor's: the units'
 * patches, made again where a frame came or the picture changed under them,
 * and the picture again where a unit no longer shows
 * @param {function(number, number):?{data: !Uint8ClampedArray, at: number}} under the
 *     picture's pixel at a point (the layers' coordinates)
 * @param {function(number, number, number, number):!Array<!Object>} region the
 *     picture's layers that cover a rectangle
 * @param {!Array<!Object>} sent the picture's layers this time
 * @param {number} ox where the layers' origin is on the desktop
 * @param {number} oy
 * @return {!Array<!Object>}
 */
VideoOverlay.prototype.layers = function(under, region, sent, ox, oy)
{
    const out = [];
    const rects = [];
    for(const f of this.frames) if(f) rects.push([f.x - ox, f.y - oy, f.w, f.h]);
    // where units were and are no more (or moved): the picture again
    if(this.changed)
    {
        for(const d of this.drawn)
        {
            if(!rects.some(r => r[0] === d[0] && r[1] === d[1] && r[2] === d[2] && r[3] === d[3])) out.push(...region(d[0], d[1], d[2], d[3]));
        }
    }
    for(const f of this.frames)
    {
        if(!f) continue;
        const x = f.x - ox, y = f.y - oy;
        const stale = !f.patch || this.changed || sent.some(l => intersects([l.screen_x, l.screen_y, l.buffer_width, l.buffer_height], x, y, f.w, f.h));
        if(!stale) continue;
        if(!f.patch) f.patch = new Uint8ClampedArray(f.w * f.h * 4);
        const patch = f.patch, video = f.video, key = f.key;
        const kr = key >> 16 & 0xFF, kg = key >> 8 & 0xFF, kb = key & 0xFF;
        for(let py = 0; py < f.h; py++)
        {
            for(let px = 0; px < f.w; px++)
            {
                const p = (py * f.w + px) * 4;
                const pixel = under(x + px, y + py);
                if(!pixel)
                {
                    patch[p + 3] = 0;
                    continue;
                }
                const { data, at } = pixel;
                // (a color key: the video only where the picture has it)
                const show = key < 0 || data[at] === kr && data[at + 1] === kg && data[at + 2] === kb;
                const source = show ? video : data, s = show ? p : at;
                patch[p] = source[s]; patch[p + 1] = source[s + 1]; patch[p + 2] = source[s + 2]; patch[p + 3] = 255;
            }
        }
        out.push(...this.patch_layers(f, x, y, x, y, f.w, f.h));
    }
    this.drawn = rects;
    this.changed = false;
    return out;
};

/**
 * A unit's patch where it covers a rectangle (layer coordinates)
 * @return {!Array<!Object>}
 */
VideoOverlay.prototype.patch_layers = function(f, x, y, rx, ry, rw, rh)
{
    const x0 = Math.max(x, rx), y0 = Math.max(y, ry), x1 = Math.min(x + f.w, rx + rw), y1 = Math.min(y + f.h, ry + rh);
    if(!f.patch || x0 >= x1 || y0 >= y1) return [];
    return [{
        pixels: { data: f.patch, width: f.w, height: f.h },
        screen_x: x0, screen_y: y0, buffer_x: x0 - x, buffer_y: y0 - y, buffer_width: x1 - x0, buffer_height: y1 - y0,
    }];
};

/**
 * The picture with the overlay, for the cursor: a unit's patch pixel at a
 * point (layer coordinates), else the picture's
 */
VideoOverlay.prototype.under = function(under, ox, oy)
{
    return (x, y) => {
        for(let i = this.frames.length - 1; i >= 0; i--)
        {
            const f = this.frames[i];
            if(!f || !f.patch) continue;
            const px = x - (f.x - ox), py = y - (f.y - oy);
            if(px >= 0 && py >= 0 && px < f.w && py < f.h && f.patch[(py * f.w + px) * 4 + 3]) return { data: f.patch, at: (py * f.w + px) * 4 };
        }
        return under(x, y);
    };
};

/** The picture's layers of a rectangle, with the overlay over them (to erase the cursor) */
VideoOverlay.prototype.region = function(region, ox, oy)
{
    return (x, y, w, h) => {
        const out = region(x, y, w, h);
        for(const f of this.frames) if(f) out.push(...this.patch_layers(f, f.x - ox, f.y - oy, x, y, w, h));
        return out;
    };
};

VideoOverlay.prototype.get_state = function()
{
    // (the frames are read again from guest memory on a restore)
    return [this.units.map(r => Array.from(r)), this.frames.map(f => f ? 1 : 0)];
};

VideoOverlay.prototype.set_state = function(state)
{
    this.reset();
    if(!state) return;
    state[0].forEach((regs, i) => { if(this.units[i]) this.units[i].set(regs.slice(0, NUM_REGS)); });
    state[1].forEach((shown, i) => { if(shown) this.flush(i); });
    this.stats.flushes = 0;
};
                                                                                                                         source/v64/src/hpet.js                                                                              0000644 0000000 0000000 00000042333 00000000000 011756  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The High Precision Event Timer of the Q35 machine's ICH9 (settings.hpet):
// a 64-bit main counter at 14.31818 MHz and three timers at 0xFED00000.
// IA-PC HPET (High Precision Event Timers) Specification 1.0a.
//
// Each timer compares the main counter with its comparator, one-shot or
// periodic, in 64-bit or 32-bit mode, and interrupts edge or level
// triggered: through an FSB message (MSI), the legacy replacement route
// (timer 0 on IRQ 0, timer 1 on IRQ 8; the PIT and the RTC then no longer
// reach those), or an I/O APIC input (20-23, as ICH9's). As in QEMU, FSB
// delivery goes before the legacy replacement route: Windows sets both, and
// takes its clock interrupt from timer 0's message. The comparator and
// period registers behave as QEMU's (hw/timer/hpet.c): in periodic mode a
// comparator write sets the period, and with Tn_VAL_SET_CNF the comparator
// (a 64-bit timer's Tn_VAL_SET_CNF clears after its upper half is written).
// The ACPI HPET table and a PNP0103 device describe it (acpi_tables.js).

import { LOG_PIT } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";

export const HPET_ADDRESS = 0xFED00000;
export const HPET_SIZE = 0x400;
/** The main counter's period in femtoseconds: 14.31818 MHz */
const PERIOD_FS = 69841279;
const TICKS_PER_MS = 1e12 / PERIOD_FS;
const TIMER_COUNT = 3;

/**
 * GCAP_ID bits 31:0, also the ACPI HPET table's event timer block ID:
 * revision 1, three timers, 64-bit counter, legacy replacement route
 * capable, vendor Intel
 */
export const HPET_BLOCK_ID = 0x8086A201;

const GCAP_ID = 0x000;
const GEN_CONF = 0x010;
const GINTR_STA = 0x020;
const MAIN_CNT = 0x0F0;
const TIMER_BASE = 0x100;
const TIMER_STRIDE = 0x20;
const TN_CONF = 0x00;
const TN_COMPARATOR = 0x08;
const TN_FSB_ROUTE = 0x10;

const ENABLE_CNF = 1 << 0;
const LEG_RT_CNF = 1 << 1;

const TN_INT_TYPE_LEVEL = 1 << 1;
const TN_INT_ENB = 1 << 2;
const TN_TYPE_PERIODIC = 1 << 3;
const TN_PER_INT_CAP = 1 << 4;
const TN_SIZE_CAP = 1 << 5;
const TN_VAL_SET = 1 << 6;
const TN_32MODE = 1 << 8;
const TN_INT_ROUTE_SHIFT = 9;
const TN_FSB_EN = 1 << 14;
const TN_FSB_INT_DEL_CAP = 1 << 15;
/** Software-writable bits of Tn_CONF_CAP (31:0) */
const TN_CONF_WRITABLE = TN_INT_TYPE_LEVEL | TN_INT_ENB | TN_TYPE_PERIODIC | TN_VAL_SET | TN_32MODE |
    0x1F << TN_INT_ROUTE_SHIFT | TN_FSB_EN;
/** Tn_INT_ROUTE_CAP (Tn_CONF_CAP 63:32): I/O APIC inputs 20-23, as on ICH9 */
const TN_INT_ROUTE_CAP = 0x00F00000;

const STATE_FORMAT = 1;

/** The source of timer n on a shared I/O APIC input is HPET_SOURCE + n (beyond any pci_id) */
const HPET_SOURCE = 0x10000;

/**
 * @constructor
 * @param {CPU} cpu
 */
export function HPET(cpu)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.name = "hpet";

    this.config = 0;
    /** GINTR_STA: level-triggered interrupts active */
    this.isr = 0;
    /** The main counter: its value at base_time (clock ms); it counts while enabled */
    this.counter_base = 0;
    this.base_time = 0;

    /**
     * Comparator and period as 32-bit halves (the comparator resets to all
     * ones, beyond what a double holds exactly); deadline: the main counter
     * value of the next match
     * @type {!Array<{config: number, comparator: !Uint32Array, period: !Uint32Array, fsb_value: number,
     *     fsb_address: number, deadline: number, line: ?{irq: number, gsi: number}}>}
     */
    this.timers = [];
    for(let i = 0; i < TIMER_COUNT; i++)
    {
        this.timers.push({ config: 0, comparator: new Uint32Array(2), period: new Uint32Array(2),
            fsb_value: 0, fsb_address: 0, deadline: Infinity, line: null });
    }

    cpu.io.mmap_register_range(HPET_ADDRESS, HPET_SIZE, this,
        addr => {
            this.note_read();
            return this.read32(addr - HPET_ADDRESS & ~3) >>> ((addr & 3) << 3) & 0xFF;
        },
        (addr, value) => {
            const shift = (addr & 3) << 3;
            const offset = addr - HPET_ADDRESS & ~3;
            // (the other bytes as they are; of the write-one-to-clear status, none)
            const others = (offset & ~4) === GINTR_STA ? 0 : this.read32(offset) & ~(0xFF << shift);
            this.write32(offset, others | (value & 0xFF) << shift);
        },
        addr => {
            this.note_read();
            return this.read32(addr - HPET_ADDRESS);
        },
        (addr, value) => this.write32(addr - HPET_ADDRESS, value));

    this.reset();
}

/** A register read, for the step profile (docs/jit-unification-plan.md P4.0: what QueryPerformanceCounter reads) */
HPET.prototype.note_read = function()
{
    const note = this.cpu.wm?.exports["step_profile_note_event"];
    if(note) note(10, 0); // step_profile::event::HPET_READ
};

HPET.prototype.reset = function()
{
    for(let i = 0; i < TIMER_COUNT; i++)
    {
        this.set_line(i, false);
    }
    this.config = 0;
    this.isr = 0;
    this.counter_base = 0;
    this.base_time = 0;
    this.timers.forEach(timer => {
        timer.config = 0;
        timer.comparator.fill(0xFFFFFFFF);
        timer.period.fill(0);
        timer.fsb_value = 0;
        timer.fsb_address = 0;
        timer.deadline = Infinity;
    });
};

/** Legacy replacement route: the PIT does not reach IRQ 0, the RTC not IRQ 8 */
HPET.prototype.legacy_replacement = function()
{
    return (this.config & LEG_RT_CNF) !== 0;
};

/**
 * The main counter
 * @param {number} now machine clock, ms
 * @return {number}
 */
HPET.prototype.counter = function(now)
{
    if(!(this.config & ENABLE_CNF))
    {
        return this.counter_base;
    }
    return this.counter_base + Math.floor((now - this.base_time) * TICKS_PER_MS);
};

/**
 * 2^64, or 2^32 for a timer in 32-bit mode
 * @param {Object} timer
 * @return {number}
 */
HPET.prototype.width = function(timer)
{
    return timer.config & TN_32MODE ? 0x100000000 : 0x10000000000000000;
};

/**
 * A 64-bit register's halves as a number (exact below 2^53)
 * @param {!Uint32Array} halves
 * @return {number}
 */
function value64(halves)
{
    return halves[1] * 0x100000000 + halves[0];
}

/**
 * @param {!Uint32Array} halves
 * @param {number} value below 2^64
 */
function set64(halves, value)
{
    halves[0] = value % 0x100000000;
    halves[1] = Math.floor(value / 0x100000000) % 0x100000000;
}

/**
 * The next counter value at which a timer matches: where the counter (in
 * the timer's width) reaches its comparator
 * @param {number} i
 * @param {number} counter
 */
HPET.prototype.arm = function(i, counter)
{
    const timer = this.timers[i];
    if(!(this.config & ENABLE_CNF))
    {
        timer.deadline = Infinity;
        return;
    }
    const width = this.width(timer);
    let delta = value64(timer.comparator) - counter % width;
    if(delta < 0)
    {
        delta += width;
    }
    timer.deadline = counter + delta;
};

/**
 * Comparator matches up to now: interrupts, periodic timers move their
 * comparator on (missed periods coalesce)
 * @param {number} now machine clock, ms
 * @return {number} ms until the next match (at most 100)
 */
HPET.prototype.timer = function(now)
{
    if(!(this.config & ENABLE_CNF))
    {
        return 100;
    }
    const counter = this.counter(now);
    let next = Infinity;
    for(let i = 0; i < TIMER_COUNT; i++)
    {
        const timer = this.timers[i];
        if(timer.deadline <= counter)
        {
            this.fire(i);
            const width = this.width(timer);
            const period = value64(timer.period);
            if(timer.config & TN_TYPE_PERIODIC && period)
            {
                const periods = Math.floor((counter - timer.deadline) / period) + 1;
                timer.deadline += periods * period;
                set64(timer.comparator, (value64(timer.comparator) + periods * period) % width);
            }
            else
            {
                // (one-shot: again when the counter comes round)
                timer.deadline += width;
            }
        }
        next = Math.min(next, timer.deadline);
    }
    return Math.min(100, Math.max(0, (next - counter) / TICKS_PER_MS));
};

/**
 * A comparator match: the timer's interrupt, if enabled
 * @param {number} i
 */
HPET.prototype.fire = function(i)
{
    const timer = this.timers[i];
    if(!(timer.config & TN_INT_ENB))
    {
        return;
    }
    if(timer.config & TN_INT_TYPE_LEVEL && !this.fsb(i))
    {
        this.isr |= 1 << i;
        this.set_line(i, true);
    }
    else
    {
        // an edge
        this.set_line(i, true);
        this.set_line(i, false);
    }
};

/**
 * @param {number} i
 * @return {boolean} whether the timer interrupts by FSB messages (also
 * timers 0 and 1 with the legacy replacement route)
 */
HPET.prototype.fsb = function(i)
{
    return (this.timers[i].config & TN_FSB_EN) !== 0;
};

/**
 * The line a timer interrupts on: legacy replacement (timers 0 and 1: IRQ 0
 * and 8, PIC and I/O APIC), or the I/O APIC input of its route; null for
 * FSB delivery or a route it does not have
 * @param {number} i
 * @return {?{irq: number, gsi: number}}
 */
HPET.prototype.route = function(i)
{
    if(this.fsb(i))
    {
        return null;
    }
    if(this.config & LEG_RT_CNF && i < 2)
    {
        return { irq: i === 0 ? 0 : 8, gsi: -1 };
    }
    const gsi = this.timers[i].config >> TN_INT_ROUTE_SHIFT & 0x1F;
    return TN_INT_ROUTE_CAP & 1 << gsi ? { irq: -1, gsi } : null;
};

/**
 * Drive a timer's interrupt: its line (released where it was asserted), or
 * for FSB delivery a message on the rising edge
 * @param {number} i
 * @param {boolean} level
 */
HPET.prototype.set_line = function(i, level)
{
    const timer = this.timers[i];
    if(level)
    {
        if(this.fsb(i))
        {
            this.cpu.apic_msi && this.cpu.apic_msi(timer.fsb_address | 0, timer.fsb_value | 0);
            return;
        }
        const line = this.route(i);
        if(!line)
        {
            return;
        }
        if(timer.line && timer.line.irq === line.irq && timer.line.gsi === line.gsi)
        {
            // (already asserted there)
            return;
        }
        if(timer.line)
        {
            this.set_line(i, false);
        }
        timer.line = line;
        if(line.irq >= 0)
        {
            this.cpu.device_raise_irq(line.irq);
        }
        else
        {
            this.cpu.set_shared_gsi_level(line.gsi, HPET_SOURCE + i, true);
        }
    }
    else if(timer.line)
    {
        const line = timer.line;
        timer.line = null;
        if(line.irq >= 0)
        {
            this.cpu.device_lower_irq(line.irq);
        }
        else
        {
            this.cpu.set_shared_gsi_level(line.gsi, HPET_SOURCE + i, false);
        }
    }
};

/**
 * Level-triggered interrupts follow the status and the configuration: an
 * active one moves with its route or ends when disabled
 * @param {number} i
 */
HPET.prototype.update_level = function(i)
{
    const timer = this.timers[i];
    const active = (this.isr & 1 << i) !== 0 && (timer.config & (TN_INT_ENB | TN_INT_TYPE_LEVEL)) === (TN_INT_ENB | TN_INT_TYPE_LEVEL) &&
        !this.fsb(i);
    if(!active)
    {
        this.set_line(i, false);
    }
    else
    {
        this.set_line(i, true);
    }
};

/**
 * @param {number} offset
 * @return {number}
 */
HPET.prototype.read32 = function(offset)
{
    offset >>>= 0;
    const high = (offset & 4) !== 0;
    let value = 0;

    if(offset >= TIMER_BASE && offset < TIMER_BASE + TIMER_COUNT * TIMER_STRIDE)
    {
        const timer = this.timers[offset - TIMER_BASE >> 5];
        switch(offset & (TIMER_STRIDE - 1) & ~4)
        {
            case TN_CONF:
                value = high ? TN_INT_ROUTE_CAP :
                    timer.config | TN_PER_INT_CAP | TN_SIZE_CAP | TN_FSB_INT_DEL_CAP;
                break;
            case TN_COMPARATOR:
                value = timer.comparator[high ? 1 : 0];
                break;
            case TN_FSB_ROUTE:
                value = high ? timer.fsb_address : timer.fsb_value;
                break;
        }
    }
    else
    {
        switch(offset & ~4)
        {
            case GCAP_ID:
                value = high ? PERIOD_FS : HPET_BLOCK_ID;
                break;
            case GEN_CONF:
                value = high ? 0 : this.config;
                break;
            case GINTR_STA:
                value = high ? 0 : this.isr;
                break;
            case MAIN_CNT:
            {
                const counter = this.counter(this.cpu.clock.now());
                value = high ? Math.floor(counter / 0x100000000) : counter % 0x100000000;
                break;
            }
        }
    }
    return value | 0;
};

/**
 * @param {number} offset
 * @param {number} value
 */
HPET.prototype.write32 = function(offset, value)
{
    offset >>>= 0;
    value >>>= 0;
    const high = (offset & 4) !== 0;
    const now = this.cpu.clock.now();
    const counter = this.counter(now);
    dbg_log("HPET write " + h(offset, 3) + " <- " + h(value, 8), LOG_PIT);

    if(offset >= TIMER_BASE && offset < TIMER_BASE + TIMER_COUNT * TIMER_STRIDE)
    {
        const i = offset - TIMER_BASE >> 5;
        const timer = this.timers[i];
        switch(offset & (TIMER_STRIDE - 1) & ~4)
        {
            case TN_CONF:
                if(!high)
                {
                    timer.config = value & TN_CONF_WRITABLE;
                    if(timer.config & TN_32MODE)
                    {
                        timer.comparator[1] = timer.period[1] = 0;
                    }
                    this.update_level(i);
                    this.arm(i, counter);
                }
                break;
            case TN_COMPARATOR:
            {
                if(high && timer.config & TN_32MODE)
                {
                    break;
                }
                const half = high ? 1 : 0;
                if(!(timer.config & TN_TYPE_PERIODIC) || timer.config & TN_VAL_SET)
                {
                    timer.comparator[half] = value;
                }
                if(timer.config & TN_TYPE_PERIODIC)
                {
                    timer.period[half] = value;
                }
                // (cleared by the write of the last half: the upper one in 64-bit mode)
                if(high || timer.config & TN_32MODE)
                {
                    timer.config &= ~TN_VAL_SET;
                }
                this.arm(i, counter);
                break;
            }
            case TN_FSB_ROUTE:
                if(high) timer.fsb_address = value;
                else timer.fsb_value = value;
                break;
        }
        return;
    }

    switch(offset & ~4)
    {
        case GEN_CONF:
            if(!high)
            {
                const old = this.config;
                this.config = value & (ENABLE_CNF | LEG_RT_CNF);
                if((old ^ this.config) & ENABLE_CNF)
                {
                    // the counter stops where it is, or goes on from there
                    this.counter_base = counter;
                    this.base_time = now;
                    for(let i = 0; i < TIMER_COUNT; i++) this.arm(i, counter);
                }
                if((old ^ this.config) & LEG_RT_CNF)
                {
                    dbg_log("HPET: legacy replacement route " + (this.config & LEG_RT_CNF ? "on" : "off"), LOG_PIT);
                    // timers 0 and 1 change lines; the PIT and the RTC lose
                    // or get back IRQ 0 and 8
                    this.set_line(0, false);
                    this.set_line(1, false);
                    this.cpu.device_lower_irq(0);
                    this.cpu.device_lower_irq(8);
                    this.update_level(0);
                    this.update_level(1);
                }
            }
            break;
        case GINTR_STA:
            if(!high)
            {
                // write one to clear (level-triggered interrupts)
                this.isr &= ~value;
                for(let i = 0; i < TIMER_COUNT; i++) this.update_level(i);
            }
            break;
        case MAIN_CNT:
            // (only while the counter is stopped)
            if(!(this.config & ENABLE_CNF))
            {
                this.counter_base = high ?
                    this.counter_base % 0x100000000 + value * 0x100000000 :
                    Math.floor(this.counter_base / 0x100000000) * 0x100000000 + value;
            }
            break;
    }
};

HPET.prototype.get_state = function()
{
    const state = [];
    state[0] = STATE_FORMAT;
    state[1] = this.config;
    state[2] = this.isr;
    state[3] = this.counter_base;
    state[4] = this.base_time;
    state[5] = this.timers.map(t => [t.config, t.comparator[0], t.comparator[1], t.period[0], t.period[1],
        t.fsb_value, t.fsb_address, t.deadline === Infinity ? -1 : t.deadline,
        t.line ? t.line.irq : -2, t.line ? t.line.gsi : -2]);
    return state;
};

HPET.prototype.set_state = function(state)
{
    this.config = state[1];
    this.isr = state[2];
    this.counter_base = state[3];
    this.base_time = state[4];
    state[5].forEach((s, i) => {
        const timer = this.timers[i];
        timer.config = s[0];
        timer.comparator.set([s[1], s[2]]);
        timer.period.set([s[3], s[4]]);
        timer.fsb_value = s[5];
        timer.fsb_address = s[6];
        timer.deadline = s[7] === -1 ? Infinity : s[7];
        // (the interrupt controllers restore the lines themselves)
        timer.line = s[8] === -2 ? null : { irq: s[8], gsi: s[9] };
    });
};
                                                                                                                                                                                                                                                                                                     source/v64/src/ich9_tco.js                                                                          0000644 0000000 0000000 00000017660 00000000000 012524  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The TCO watchdog of the Q35 machine's ICH9: registers at PMBASE + 0x60
// (src/acpi.js forwards them), a timer that counts down in 0.6 s ticks. Its
// first timeout sets TCO1_STS.TIMEOUT (and SMI_STS.TCO_STS); the second, if
// software did not reload the timer in between, sets TCO2_STS.SECOND_TO_STS
// and BOOT_STS and resets the machine unless NO_REBOOT (RCBA GCS bit 5,
// set at reset) forbids it. Linux's iTCO_wdt clears NO_REBOOT, programs
// TCO_TMR and reloads through TCO_RLD.
// ICH9 datasheet (316972), 13.9; QEMU hw/acpi/tco.c, whose behaviour this
// follows (the timer does not run until software reloads it or clears
// TCO_TMR_HLT), except that the status registers are write-one-to-clear as
// on the hardware.

import { LOG_ACPI } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";

/** The TCO registers' offset in the ICH9 PM I/O block */
export const ICH9_PM_TCO = 0x60;
export const ICH9_TCO_LENGTH = 0x20;

const TICK_MS = 600;

const TCO_RLD = 0x00;
const TCO_DAT_IN = 0x02;
const TCO_DAT_OUT = 0x03;
const TCO1_STS = 0x04;
const TCO2_STS = 0x06;
const TCO1_CNT = 0x08;
const TCO2_CNT = 0x0A;
const TCO_MESSAGE1 = 0x0C;
const TCO_MESSAGE2 = 0x0D;
const TCO_WDCNT = 0x0E;
const SW_IRQ_GEN = 0x10;
const TCO_TMR = 0x12;

// TCO1_STS
const TCO_INT_STS = 1 << 2;
const SW_TCO_SMI = 1 << 1;
const TCO_TIMEOUT = 1 << 3;
// TCO2_STS
const SECOND_TO_STS = 1 << 1;
const BOOT_STS = 1 << 2;
// TCO1_CNT
const TCO_TMR_HLT = 1 << 11;
const TCO_LOCK = 1 << 12;
const TCO1_CNT_WRITABLE = 0x1F00;

/** SMI_STS.TCO_STS and SMI_EN.TCO_EN */
export const SMI_TCO = 1 << 13;

/** RCBA GCS: NO_REBOOT */
const RCBA_GCS = 0x3410;
const GCS_NO_REBOOT = 1 << 5;

const STATE_FORMAT = 1;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {function()} smi a TCO SMI (SMI_STS.TCO_STS)
 */
export function TCO(cpu, smi)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.smi = smi;
    this.reset();
}

TCO.prototype.reset = function()
{
    /** TCO_RLD while the timer is stopped */
    this.rld = 0;
    this.dat_in = 0;
    this.dat_out = 0;
    this.sts1 = 0;
    this.sts2 = 0;
    this.cnt1 = 0;
    this.cnt2 = 0x0008;
    this.message1 = 0;
    this.message2 = 0;
    this.wdcnt = 0;
    this.sw_irq_gen = 0x03;
    this.tmr = 0x0004;
    /** Machine clock time of the next timeout, or -1: stopped */
    this.expire_time = -1;
    /** Timeouts since the last reload */
    this.timeouts = 0;
};

/** The timer may run: not halted, and no second timeout pending (BOOT_STS) */
TCO.prototype.can_start = function()
{
    return !(this.cnt1 & TCO_TMR_HLT) && !(this.sts2 & BOOT_STS);
};

/** TCO_RLD: the timer starts again from TCO_TMR, if it may run */
TCO.prototype.reload = function()
{
    this.timeouts = 0;
    if(this.can_start())
    {
        this.rld = this.tmr & 0x3FF;
        this.expire_time = this.cpu.clock.now() + this.rld * TICK_MS;
    }
    else
    {
        this.expire_time = -1;
    }
};

/**
 * @param {number} now machine clock, ms
 * @return {number} ms until the next timeout (at most 100)
 */
TCO.prototype.timer = function(now)
{
    if(this.expire_time === -1)
    {
        return 100;
    }
    if(now >= this.expire_time)
    {
        this.timeout();
        if(this.expire_time === -1)
        {
            return 100;
        }
    }
    return Math.min(100, Math.max(0, this.expire_time - now));
};

/** The timer reached zero */
TCO.prototype.timeout = function()
{
    this.rld = 0;
    this.sts1 |= TCO_TIMEOUT;
    this.timeouts++;
    dbg_log("TCO timeout " + this.timeouts, LOG_ACPI);
    if(this.timeouts === 2)
    {
        this.sts2 |= SECOND_TO_STS | BOOT_STS;
        this.timeouts = 0;
        const q35 = this.cpu.devices.q35;
        if(q35 && !(q35.rcba[RCBA_GCS] & GCS_NO_REBOOT))
        {
            dbg_log("TCO: second timeout, reset", LOG_ACPI);
            this.expire_time = -1;
            this.cpu.reboot_internal("tco");
            return;
        }
    }
    this.smi();
    // (it goes on from TCO_TMR; BOOT_STS keeps it stopped)
    if(this.can_start())
    {
        this.rld = this.tmr & 0x3FF;
        this.expire_time += this.rld * TICK_MS;
    }
    else
    {
        this.expire_time = -1;
    }
};

/**
 * @param {number} offset in the TCO block
 * @return {number}
 */
TCO.prototype.read_byte = function(offset)
{
    const word = (value, at) => value >> ((offset - at) << 3) & 0xFF;
    switch(offset)
    {
        case TCO_RLD: case TCO_RLD + 1:
        {
            // the ticks left
            const rld = this.expire_time === -1 ? this.rld :
                Math.max(0, Math.floor((this.expire_time - this.cpu.clock.now()) / TICK_MS));
            return word(rld, TCO_RLD);
        }
        case TCO_DAT_IN: return this.dat_in;
        case TCO_DAT_OUT: return this.dat_out;
        case TCO1_STS: case TCO1_STS + 1: return word(this.sts1, TCO1_STS);
        case TCO2_STS: case TCO2_STS + 1: return word(this.sts2, TCO2_STS);
        case TCO1_CNT: case TCO1_CNT + 1: return word(this.cnt1, TCO1_CNT);
        case TCO2_CNT: case TCO2_CNT + 1: return word(this.cnt2, TCO2_CNT);
        case TCO_MESSAGE1: return this.message1;
        case TCO_MESSAGE2: return this.message2;
        case TCO_WDCNT: return this.wdcnt;
        case SW_IRQ_GEN: return this.sw_irq_gen;
        case TCO_TMR: case TCO_TMR + 1: return word(this.tmr, TCO_TMR);
    }
    return 0;
};

/**
 * @param {number} offset in the TCO block
 * @param {number} byte
 */
TCO.prototype.write_byte = function(offset, byte)
{
    dbg_log("TCO write " + h(offset, 2) + " <- " + h(byte, 2), LOG_ACPI);
    const shift = (offset & 1) << 3;
    const merge = old => old & ~(0xFF << shift) | byte << shift;
    switch(offset)
    {
        case TCO_RLD: case TCO_RLD + 1:
            // any write reloads the timer (and restarts the count of timeouts)
            this.reload();
            break;
        case TCO_DAT_IN:
            this.dat_in = byte;
            this.sts1 |= SW_TCO_SMI;
            this.smi();
            break;
        case TCO_DAT_OUT:
            this.dat_out = byte;
            this.sts1 |= TCO_INT_STS;
            break;
        case TCO1_STS: case TCO1_STS + 1:
            this.sts1 &= ~(byte << shift);
            break;
        case TCO2_STS: case TCO2_STS + 1:
            this.sts2 &= ~(byte << shift);
            break;
        case TCO1_CNT: case TCO1_CNT + 1:
        {
            // TCO_LOCK, once set, stays until a reset
            const old = this.cnt1;
            this.cnt1 = merge(this.cnt1) & TCO1_CNT_WRITABLE | old & TCO_LOCK;
            if((old ^ this.cnt1) & TCO_TMR_HLT)
            {
                if(this.can_start())
                {
                    this.reload();
                }
                else if(this.expire_time !== -1)
                {
                    // halted: TCO_RLD keeps the ticks that were left
                    this.rld = Math.max(0, Math.floor((this.expire_time - this.cpu.clock.now()) / TICK_MS));
                    this.expire_time = -1;
                }
            }
            break;
        }
        case TCO2_CNT: case TCO2_CNT + 1:
            this.cnt2 = merge(this.cnt2);
            break;
        case TCO_MESSAGE1: this.message1 = byte; break;
        case TCO_MESSAGE2: this.message2 = byte; break;
        case TCO_WDCNT: this.wdcnt = byte; break;
        case SW_IRQ_GEN: this.sw_irq_gen = byte & 3; break;
        case TCO_TMR: case TCO_TMR + 1:
            this.tmr = merge(this.tmr) & 0x3FF;
            break;
    }
};

TCO.prototype.get_state = function()
{
    return [STATE_FORMAT, this.rld, this.dat_in, this.dat_out, this.sts1, this.sts2, this.cnt1, this.cnt2,
        this.message1, this.message2, this.wdcnt, this.sw_irq_gen, this.tmr, this.expire_time, this.timeouts];
};

TCO.prototype.set_state = function(state)
{
    [, this.rld, this.dat_in, this.dat_out, this.sts1, this.sts2, this.cnt1, this.cnt2,
        this.message1, this.message2, this.wdcnt, this.sw_irq_gen, this.tmr, this.expire_time, this.timeouts] = state;
};
                                                                                source/v64/src/ide.js                                                                               0000644 0000000 0000000 00000336336 00000000000 011570  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { init_block_io, block_read, block_write, block_when_writes_done, block_cancel_reads, block_drop_holds } from "./block_backend.js";
import { restore_disk_state } from "./disk_writeback.js";
import { LOG_DISK } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";
import { CMOS_BIOS_DISKTRANSFLAG, CMOS_DISK_DATA, CMOS_DISK_DRIVE1_CYL, CMOS_DISK_DRIVE1_TYPE, CMOS_DISK_DRIVE2_CYL, CMOS_DISK_DRIVE2_TYPE } from "./rtc.js";
import { QEMU_PCI_SUBSYSTEM, pci_functions } from "./platform.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

// ATA/ATAPI-6/8 IDE Controller
//
// References
// - [ATA8-ACS]
//   ATA/ATAPI Command Set - 3 (ACS-3) (Rev. 5, Oct. 28, 2013)
//   https://read.seas.harvard.edu/cs161/2019/pdf/ata-atapi-8.pdf
// - [ATA-6]
//   AT Attachment with Packet Interface - 6 (ATA/ATAPI-6) (Rev. 3a; Dec. 14, 2001)
//   https://technion-csl.github.io/ose/readings/hardware/ATA-d1410r3a.pdf
// - [CD-SCSI-2]
//   PROPOSAL FOR CD-ROM IN SCSI-2 (X3T9.2/87) (Rev. 0, Jun. 30, 1987)
//   https://www.t10.org/ftp/x3t9.2/document.87/87-106r0.txt
//   https://www.t10.org/ftp/x3t9.2/document.87/87-106r1.txt (errata to r0)
// - [SAM-3]
//   SCSI Architecture Model - 3 (SAM-3) (Sep. 21, 2004)
//   https://dn790004.ca.archive.org/0/items/SCSISpecificationDocumentsSCSIDocuments/SCSI%20Architecture%20Model/SCSI%20Architecture%20Model%203%20rev%2014.pdf
// - [SPC-3]
//   SCSI Primary Commands - 3 (SPC-3) (July 20, 2008)
//   https://www.t10.org/ftp/t10/document.08/08-309r0.pdf
// - [MMC-3]
//   SCSI Multimedia Commands - 3 (MMC-3) (Rev. 10g, Nov. 12, 2001)
//   https://ia902808.us.archive.org/33/items/mmc3r10g/mmc3r10g.pdf
// - [MMC-2]
//   Packet Commands for C/DVD Devices (1997)
//   https://www.t10.org/ftp/t10/document.97/97-108r0.pdf
// - [BMI-1]
//   Programming Interface for Bus Master IDE Controller, Revision 1.0, 5/16/94
//   https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/u9proj/idems100.pdf
// - [SFF-8020]
//   ATA Packet Interface for CD-ROMs (Rev. 1.2, Feb. 12, 1994)
//   https://dn790009.ca.archive.org/0/items/SCSISpecificationDocumentsATAATAPI/SFF-8020_%20ATA%20Packet%20Interface%20for%20CD-ROMs%20-%20SFF.pdf
// - [AACS]
//   Advanced Access Control System (AACS) (Rev. 0.953, Oct. 26, 2012)
//   https://aacsla.com/wp-content/uploads/2019/02/AACS_Spec_Common_Final_0953.pdf

const CDROM_SECTOR_SIZE = 2048;
const HD_SECTOR_SIZE = 512;

const BUS_MASTER_BASE = 0xB400;

// Per-channel ATA register offsets, legend:
//   (*1*) Control block register (BAR1/3), else: Command block register (BAR0/2)
// Read-only registers:
const ATA_REG_ERROR      = 0x01;  // Error register, see [ATA-6] 7.9
const ATA_REG_STATUS     = 0x07;  // Status register, see [ATA-6] 7.15
const ATA_REG_ALT_STATUS = 0x00;  // (*1*) Alternate Status register, see [ATA-6] 7.3
// Read-/writable registers:
const ATA_REG_DATA       = 0x00;  // Data register, see [ATA-6] 7.6
const ATA_REG_SECTOR     = 0x02;  // Sector Count register, see [ATA-6] 7.14
const ATA_REG_LBA_LOW    = 0x03;  // LBA Low register, see [ATA-6] 7.12
const ATA_REG_LBA_MID    = 0x04;  // LBA Mid register, see [ATA-6] 7.13
const ATA_REG_LBA_HIGH   = 0x05;  // LBA High register, see [ATA-6] 7.11
const ATA_REG_DEVICE     = 0x06;  // Device register, see [ATA-6] 7.7
// Write-only registers:
const ATA_REG_FEATURES   = 0x01;  // Features register, see [ATA-6] 7.10
const ATA_REG_COMMAND    = 0x07;  // Command register, see [ATA-6] 7.4
const ATA_REG_CONTROL    = 0x00;  // (*1*) Device Control register, see [ATA-6] 7.8

// Per-channel Bus Master IDE register offsets (BAR4), see [BMI-1] 2.0
// these are the primary channel's offsets, add 8 for secondary
const BMI_REG_COMMAND = 0x00;     // Bus Master IDE Command register
const BMI_REG_STATUS = 0x02;      // Bus Master IDE Status register
const BMI_REG_PRDT = 0x04;        // Bus Master IDE PRD Table Address register

// Error register bits:
// All bits except for bit 0x04 are command dependent.
const ATA_ER_ABRT = 0x04;  // Command aborted
const ATA_ER_IDNF = 0x10;  // ID not found: the address is beyond the end of the disk

// Status register bits:
const ATA_SR_ERR  = 0x01;  // Error (ATA)
const ATA_SR_COND = 0x01;  // Check Condition (ATAPI)
const ATA_SR_SENS = 0x02;  // Sense Available (ATAPI)
const ATA_SR_AERR = 0x04;  // Alignment Error
const ATA_SR_DRQ  = 0x08;  // Data Request
const ATA_SR_DSC  = 0x10;  // Drive Seek Complete / Deferred Write Error
const ATA_SR_DF   = 0x20;  // Device Fault / Stream Error
const ATA_SR_DRDY = 0x40;  // Drive Ready
const ATA_SR_BSY  = 0x80;  // Busy

// Device register bits:
// Bits 0x20/0x80 are obsolete and 0x01/0x02/0x04/0x08/0x40 are command dependent.
const ATA_DR_DEV = 0x10;   // Device select; slave device if set, else master device

// Device Control register bits:
// Bits 0x08/0x10/0x20/0x40 are reserved and bit 0x01 is always zero.
const ATA_CR_NIEN = 0x02;  // Interrupt disable (not Interrupt ENable)
const ATA_CR_SRST = 0x04;  // Software reset
const ATA_CR_HOB = 0x80;   // 48-bit Address feature set

// ATA commands
const ATA_CMD_DEVICE_RESET = 0x08;                    // see [ATA8-ACS] 7.6
const ATA_CMD_EXECUTE_DEVICE_DIAGNOSTIC = 0x90;       // see [ATA8-ACS] 7.9
const ATA_CMD_FLUSH_CACHE = 0xE7;                     // see [ATA8-ACS] 7.10
const ATA_CMD_FLUSH_CACHE_EXT = 0xEA;                 // see [ATA8-ACS] 7.11
const ATA_CMD_GET_MEDIA_STATUS = 0xDA;                // see [ATA-6] 8.14
const ATA_CMD_IDENTIFY_DEVICE = 0xEC;                 // see [ATA8-ACS] 7.12
const ATA_CMD_IDENTIFY_PACKET_DEVICE = 0xA1;          // see [ATA8-ACS] 7.13
const ATA_CMD_IDLE_IMMEDIATE = 0xE1;                  // see [ATA8-ACS] 7.15
const ATA_CMD_INITIALIZE_DEVICE_PARAMETERS = 0x91;    // not mentioned in [ATA-6] or [ATA8-ACS]
const ATA_CMD_MEDIA_LOCK = 0xDE;                      // see [ATA-6] 8.20
const ATA_CMD_NOP = 0x00;                             // see [ATA8-ACS] 7.17
const ATA_CMD_PACKET = 0xA0;                          // see [ATA8-ACS] 7.18
const ATA_CMD_READ_DMA = 0xC8;                        // see [ATA8-ACS] 7.21
const ATA_CMD_READ_DMA_EXT = 0x25;                    // see [ATA8-ACS] 7.22
const ATA_CMD_READ_MULTIPLE = 0x29;                   // see [ATA8-ACS] 7.26
const ATA_CMD_READ_MULTIPLE_EXT = 0xC4;               // see [ATA8-ACS] 7.27
const ATA_CMD_READ_NATIVE_MAX_ADDRESS = 0xF8;         // see [ATA-6] 8.32
const ATA_CMD_READ_NATIVE_MAX_ADDRESS_EXT = 0x27;     // see [ATA-6] 8.33
const ATA_CMD_READ_SECTORS = 0x20;                    // see [ATA8-ACS] 7.28
const ATA_CMD_READ_SECTORS_EXT = 0x24;                // see [ATA8-ACS] 7.29
const ATA_CMD_READ_VERIFY_SECTORS = 0x40;             // see [ATA8-ACS] 7.32
const ATA_CMD_SECURITY_FREEZE_LOCK = 0xF5;            // see [ATA8-ACS] 7.40
const ATA_CMD_SET_FEATURES = 0xEF;                    // see [ATA8-ACS] 7.45
const ATA_CMD_SET_MAX = 0xF9;                         // see [ATA-6] 8.47
const ATA_CMD_SET_MULTIPLE_MODE = 0xC6;               // see [ATA8-ACS] 7.46
const ATA_CMD_STANDBY_IMMEDIATE = 0xE0;               // see [ATA8-ACS] 7.50
const ATA_CMD_WRITE_DMA = 0xCA;                       // see [ATA8-ACS] 7.58
const ATA_CMD_WRITE_DMA_EXT = 0x35;                   // see [ATA8-ACS] 7.59
const ATA_CMD_WRITE_MULTIPLE = 0x39;                  // see [ATA8-ACS] 7.64
const ATA_CMD_WRITE_MULTIPLE_EXT = 0xC5;              // see [ATA8-ACS] 7.65
const ATA_CMD_WRITE_SECTORS = 0x30;                   // see [ATA8-ACS] 7.67
const ATA_CMD_WRITE_SECTORS_EXT = 0x34;               // see [ATA8-ACS] 7.68
const ATA_CMD_10h = 0x10;                             // command obsolete/unknown, see [ATA-6] Table E.2
const ATA_CMD_F0h = 0xF0;                             // vendor-specific

const ATA_CMD_NAME =
{
    [ATA_CMD_DEVICE_RESET]:                 "DEVICE RESET",
    [ATA_CMD_EXECUTE_DEVICE_DIAGNOSTIC]:    "EXECUTE DEVICE DIAGNOSTIC",
    [ATA_CMD_FLUSH_CACHE]:                  "FLUSH CACHE",
    [ATA_CMD_FLUSH_CACHE_EXT]:              "FLUSH CACHE EXT",
    [ATA_CMD_GET_MEDIA_STATUS]:             "GET MEDIA STATUS",
    [ATA_CMD_IDENTIFY_DEVICE]:              "IDENTIFY DEVICE",
    [ATA_CMD_IDENTIFY_PACKET_DEVICE]:       "IDENTIFY PACKET DEVICE",
    [ATA_CMD_IDLE_IMMEDIATE]:               "IDLE IMMEDIATE",
    [ATA_CMD_INITIALIZE_DEVICE_PARAMETERS]: "INITIALIZE DEVICE PARAMETERS",
    [ATA_CMD_MEDIA_LOCK]:                   "MEDIA LOCK",
    [ATA_CMD_NOP]:                          "NOP",
    [ATA_CMD_PACKET]:                       "PACKET",
    [ATA_CMD_READ_DMA]:                     "READ DMA",
    [ATA_CMD_READ_DMA_EXT]:                 "READ DMA EXT",
    [ATA_CMD_READ_MULTIPLE]:                "READ MULTIPLE",
    [ATA_CMD_READ_MULTIPLE_EXT]:            "READ MULTIPLE EXT",
    [ATA_CMD_READ_NATIVE_MAX_ADDRESS]:      "READ NATIVE MAX ADDRESS",
    [ATA_CMD_READ_NATIVE_MAX_ADDRESS_EXT]:  "READ NATIVE MAX ADDRESS EXT",
    [ATA_CMD_READ_SECTORS]:                 "READ SECTORS",
    [ATA_CMD_READ_SECTORS_EXT]:             "READ SECTORS EXT",
    [ATA_CMD_READ_VERIFY_SECTORS]:          "READ VERIFY SECTORS",
    [ATA_CMD_SECURITY_FREEZE_LOCK]:         "SECURITY FREEZE LOCK",
    [ATA_CMD_SET_FEATURES]:                 "SET FEATURES",
    [ATA_CMD_SET_MAX]:                      "SET MAX",
    [ATA_CMD_SET_MULTIPLE_MODE]:            "SET MULTIPLE MODE",
    [ATA_CMD_STANDBY_IMMEDIATE]:            "STANDBY IMMEDIATE",
    [ATA_CMD_WRITE_DMA]:                    "WRITE DMA",
    [ATA_CMD_WRITE_DMA_EXT]:                "WRITE DMA EXT",
    [ATA_CMD_WRITE_MULTIPLE]:               "WRITE MULTIPLE",
    [ATA_CMD_WRITE_MULTIPLE_EXT]:           "WRITE MULTIPLE EXT",
    [ATA_CMD_WRITE_SECTORS]:                "WRITE SECTORS",
    [ATA_CMD_WRITE_SECTORS_EXT]:            "WRITE SECTORS EXT",
    [ATA_CMD_10h]:                          "<UNKNOWN 10h>",
    [ATA_CMD_F0h]:                          "<VENDOR-SPECIFIC F0h>",
};

// ATAPI (SCSI-2/MMC-2) commands
const ATAPI_CMD_GET_CONFIGURATION = 0x46;             // see [CD-SCSI-2]
const ATAPI_CMD_GET_EVENT_STATUS_NOTIFICATION = 0x4A; // see [MMC-2] 9.1.2
const ATAPI_CMD_INQUIRY = 0x12;                       // see [MMC-2] 9.1.3
const ATAPI_CMD_MECHANISM_STATUS = 0xBD;              // see [MMC-2] 9.1.5
const ATAPI_CMD_MODE_SENSE_6 = 0x1A;                  // see [CD-SCSI-2]
const ATAPI_CMD_MODE_SENSE_10 = 0x5A;                 // see [MMC-2] 9.1.7
const ATAPI_CMD_PAUSE = 0x45;                         // see [CD-SCSI-2]
const ATAPI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E;  // see [MMC-2] 9.1.9
const ATAPI_CMD_READ_10 = 0x28;                       // see [CD-SCSI-2]
const ATAPI_CMD_READ_12 = 0xA8;                       // see [SFF-8020] 9.8.14
const ATAPI_CMD_READ_CAPACITY = 0x25;                 // see [MMC-2] 9.1.12
const ATAPI_CMD_READ_FORMAT_CAPACITIES = 0x23;        // see [MMC-3] 5.21
const ATAPI_CMD_READ_CD = 0xBE;                       // see [CD-SCSI-2]
const ATAPI_CMD_READ_DISK_INFORMATION = 0x51;         // see [CD-SCSI-2]
const ATAPI_CMD_READ_SUBCHANNEL = 0x42;               // see [CD-SCSI-2]
const ATAPI_CMD_READ_TOC_PMA_ATIP = 0x43;             // see [CD-SCSI-2]
const ATAPI_CMD_READ_TRACK_INFORMATION = 0x52;        // see [CD-SCSI-2]
const ATAPI_CMD_REQUEST_SENSE = 0x03;                 // see [MMC-2] 9.1.18
const ATAPI_CMD_START_STOP_UNIT = 0x1B;               // see [CD-SCSI-2]
const ATAPI_CMD_TEST_UNIT_READY = 0x00;               // see [MMC-2] 9.1.20
const ATAPI_CMD_REPORT_KEY = 0xA4;                    // see [MMC-3] 5.26
const ATAPI_CMD_READ_DISC_STRUCTURE = 0xAD;           // see [AASC] 4.14.3

// ATAPI command flags
const ATAPI_CF_NONE = 0x00;         // no flags
const ATAPI_CF_NEEDS_DISK = 0x01;   // command needs inserted disk
const ATAPI_CF_UNIT_ATTN = 0x02;    // bounce command if unit attention condition is active

// ATAPI commands, for flags see [MMC-3] 4.2.6
const ATAPI_CMD =
{
    [ATAPI_CMD_GET_CONFIGURATION]:             {name: "GET CONFIGURATION",             flags: ATAPI_CF_NONE},
    [ATAPI_CMD_GET_EVENT_STATUS_NOTIFICATION]: {name: "GET EVENT STATUS NOTIFICATION", flags: ATAPI_CF_NONE},
    [ATAPI_CMD_INQUIRY]:                       {name: "INQUIRY",                       flags: ATAPI_CF_NONE},
    [ATAPI_CMD_MECHANISM_STATUS]:              {name: "MECHANISM STATUS",              flags: ATAPI_CF_NONE},
    [ATAPI_CMD_MODE_SENSE_6]:                  {name: "MODE SENSE (6)",                flags: ATAPI_CF_NONE},
    [ATAPI_CMD_MODE_SENSE_10]:                 {name: "MODE SENSE (10)",               flags: ATAPI_CF_NONE},
    [ATAPI_CMD_PAUSE]:                         {name: "PAUSE",                         flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL]:  {name: "PREVENT ALLOW MEDIUM REMOVAL",  flags: ATAPI_CF_NONE},
    [ATAPI_CMD_READ_10]:                       {name: "READ (10)",                     flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_12]:                       {name: "READ (12)",                     flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_CAPACITY]:                 {name: "READ CAPACITY",                 flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_FORMAT_CAPACITIES]:        {name: "READ FORMAT CAPACITIES",        flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_CD]:                       {name: "READ CD",                       flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_DISK_INFORMATION]:         {name: "READ DISK INFORMATION",         flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_SUBCHANNEL]:               {name: "READ SUBCHANNEL",               flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_TOC_PMA_ATIP]:             {name: "READ TOC PMA ATIP",             flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_READ_TRACK_INFORMATION]:        {name: "READ TRACK INFORMATION",        flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_REQUEST_SENSE]:                 {name: "REQUEST SENSE",                 flags: ATAPI_CF_NONE},
    [ATAPI_CMD_START_STOP_UNIT]:               {name: "START STOP UNIT",               flags: ATAPI_CF_NONE},
    [ATAPI_CMD_TEST_UNIT_READY]:               {name: "TEST UNIT READY",               flags: ATAPI_CF_NEEDS_DISK},
    [ATAPI_CMD_REPORT_KEY]:                    {name: "REPORT KEY",                    flags: ATAPI_CF_NONE},
    [ATAPI_CMD_READ_DISC_STRUCTURE]:           {name: "READ DISC STRUCTURE",           flags: ATAPI_CF_NEEDS_DISK},
};

// ATAPI device signature
const ATAPI_SIGNATURE_LO = 0x14;
const ATAPI_SIGNATURE_HI = 0xEB;

// ATAPI 4-bit Sense Keys, see [MMC-2] 9.1.18.3, Table 123
const ATAPI_SK_NO_SENSE = 0;
const ATAPI_SK_RECOVERED_ERROR = 1;
const ATAPI_SK_NOT_READY = 2;
const ATAPI_SK_MEDIUM_ERROR = 3;
const ATAPI_SK_HARDWARE_ERROR = 4;
const ATAPI_SK_ILLEGAL_REQUEST = 5;
const ATAPI_SK_UNIT_ATTENTION = 6;
const ATAPI_SK_DATA_PROTECT = 7;
const ATAPI_SK_BLANK_CHECK = 8;
const ATAPI_SK_ABORTED_COMMAND = 11;

// ATAPI 8-bit Additional Sense Codes, see [MMC-2] 9.1.18.3, Table 124
// https://github.com/qemu/qemu/blob/3c5a5e213e5f08fbfe70728237f7799ac70f5b99/hw/ide/ide-internal.h#L288
const ATAPI_ASC_UNRECOVERED_READ_ERROR = 0x11;
const ATAPI_ASC_LBA_OUT_OF_RANGE = 0x21;
const ATAPI_ASC_INV_FIELD_IN_CMD_PACKET = 0x24;
const ATAPI_ASC_MEDIUM_MAY_HAVE_CHANGED = 0x28;
const ATAPI_ASC_MEDIUM_NOT_PRESENT = 0x3A;

// Pending media-change state, reported to the guest in order on a swap.
const MEDIUM_CHANGED_NONE = 0;
const MEDIUM_CHANGED_UNIT_ATTENTION = 1;
const MEDIUM_CHANGED_NOT_PRESENT = 2;

// Debug log detail bits (internal to this module)
const LOG_DETAIL_NONE = 0x00;   // disable debug logging of details
const LOG_DETAIL_REG_IO = 0x01; // log register read/write access
const LOG_DETAIL_IRQ = 0x02;    // log IRQ raise/lower events
const LOG_DETAIL_RW = 0x04;     // log data read/write-related events
const LOG_DETAIL_RW_DMA = 0x08; // log DMA data read/write-related events
const LOG_DETAIL_CHS = 0x10;    // log register-CHS to LBA conversions
const LOG_DETAIL_ALL = 0xFF;    // log all details
// the bitset of active log details (should be 0 when not in DEBUG mode)
const LOG_DETAILS = DEBUG ? LOG_DETAIL_NONE : 0;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 *
 * ide_config: [ [primary-master, primary-slave], [secondary-master, secondary-slave] ]
 *
 *   Each of the four arguments (primary-master, primary-slave, ...) is either
 *   undefined or an object of the form:
 *
 *       { buffer: Uint8Array, is_cdrom: bool }
 *
 *   If is_cdrom is defined and true:
 *   - If buffer is defined: create an ATAPI CD-ROM device using buffer as inserted disk
 *   - If buffer is undefined: create an ATAPI CD-ROM device with ejectd disk
 *   If is_cdrom is undefined or false:
 *   - If buffer is defined: create an ATA Hard-Disk device using buffer as disk image
 *   - If buffer is undefined: represents a missing device
 *
 *   A slave drive can only exist if a master drive also exists.
 * */
export function IDEController(cpu, bus, ide_config)
{
    this.cpu = cpu;
    this.bus = bus;

    this.primary = undefined;
    this.secondary = undefined;

    const has_primary = ide_config && ide_config[0][0];
    const has_secondary = ide_config && ide_config[1][0];
    if(has_primary || has_secondary)
    {
        if(has_primary)
        {
            this.primary = new IDEChannel(this, 0, ide_config[0], 0x1F0, 0x3F6, 14);
        }
        if(has_secondary)
        {
            this.secondary = new IDEChannel(this, 1, ide_config[1], 0x170, 0x376, 15);
        }

        const vendor_id = 0x8086;    // Intel Corporation
        const device_id = 0x7010;    // 82371SB PIIX3 IDE [Natoma/Triton II]
        const class_code = 0x01;     // Mass Storage Controller
        const subclass = 0x01;       // IDE Controller
        const prog_if = 0x80;        // ISA Compatibility mode-only controller, supports bus mastering
        const interrupt_line = 0x00; // IRQs 14 and 15 are predefined in Compatibility mode and this field is ignored
        const command_base0 = has_primary ? this.primary.command_base : 0;
        const control_base0 = has_primary ? this.primary.control_base : 0;
        const command_base1 = has_secondary ? this.secondary.command_base : 0;
        const control_base1 = has_secondary ? this.secondary.control_base : 0;

        this.name = "ide";
        this.pci_id = pci_functions(cpu.platform).ide;
        const subsystem = cpu.platform.qemu_compatible ? QEMU_PCI_SUBSYSTEM : [0x43, 0x10, 0xD4, 0x82];
        this.pci_space = [
            vendor_id & 0xFF, vendor_id >> 8, device_id & 0xFF, device_id >> 8, 0x05, 0x00, 0xA0, 0x02,
            0x00, prog_if, subclass, class_code, 0x00, 0x00, 0x00, 0x00,
            command_base0 & 0xFF   | 1, command_base0 >> 8,   0x00, 0x00,
            control_base0 & 0xFF   | 1, control_base0 >> 8,   0x00, 0x00,
            command_base1 & 0xFF   | 1, command_base1 >> 8,   0x00, 0x00,
            control_base1 & 0xFF   | 1, control_base1 >> 8,   0x00, 0x00,
            BUS_MASTER_BASE & 0xFF | 1, BUS_MASTER_BASE >> 8, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            ...subsystem,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, interrupt_line, 0x01, 0x00, 0x00,
            // 0x40
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            // 0x80
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        this.pci_bars = [
            has_primary ? { size: 8 } : undefined,   // BAR0: Command block register address of primary channel
            has_primary ? { size: 1 } : undefined,   // BAR1: Control block register address of primary channel
            has_secondary ? { size: 8 } : undefined, // BAR2: Command block register address of secondary channel
            has_secondary ? { size: 1 } : undefined, // BAR3: Control block register address of secondary channel
            { size: 16 }                             // BAR4: Bus Master I/O register address of both channels (8+8)
        ];
        cpu.devices.pci.register_device(this);
    }

    Object.seal(this);
}

/**
 * Machine reset or power-on (PCIRST#): both channels return to their power-on
 * state and I/O still in flight is dropped (its completion must not reach the
 * machine that starts now)
 */
IDEController.prototype.reset = function()
{
    this.primary && this.primary.hardware_reset();
    this.secondary && this.secondary.hardware_reset();
};

IDEController.prototype.get_state = function()
{
    const state = [];
    state[0] = this.primary;
    state[1] = this.secondary;
    return state;
};

IDEController.prototype.set_state = function(state)
{
    this.primary && this.primary.set_state(state[0]);
    this.secondary && this.secondary.set_state(state[1]);
};

/**
 * @constructor
 * @param {IDEController} controller
 * @param {number} channel_nr
 * */
function IDEChannel(controller, channel_nr, channel_config, command_base, control_base, irq)
{
    this.controller = controller;
    this.channel_nr = channel_nr;
    this.cpu = controller.cpu;
    this.bus = controller.bus;
    this.command_base = command_base;
    this.control_base = control_base;
    this.irq = irq;
    this.name = "ide" + channel_nr;
    /** The drives of channel 0 have their geometry in the CMOS */
    this.cmos_geometry = true;
    /** Parallel ATA (IDENTIFY reports the transport) */
    this.sata = false;
    /** No native command queuing */
    this.ncq_depth = 0;

    const master_cfg = channel_config ? channel_config[0] : undefined;
    const slave_cfg = channel_config ? channel_config[1] : undefined;
    this.master = new IDEInterface(this, 0, master_cfg?.buffer, master_cfg?.is_cdrom);
    this.slave = new IDEInterface(this, 1, slave_cfg?.buffer, slave_cfg?.is_cdrom);

    this.current_interface = this.master;

    /** @type {number} */
    this.device_control_reg = ATA_CR_NIEN;

    /** @type {number} */
    this.prdt_addr = 0;

    /** @type {number} */
    this.dma_status = 0;

    /** @type {number} */
    this.dma_command = 0;

    const cpu = controller.cpu;

    //
    // Command Block Registers: command_base + 0...7 (BAR0: 1F0h, BAR2: 170h)
    //

    cpu.io.register_read(this.command_base | ATA_REG_DATA, this, function()
    {
        return this.current_interface.read_data(1);
    }, function()
    {
        return this.current_interface.read_data(2);
    }, function()
    {
        return this.current_interface.read_data(4);
    });

    cpu.io.register_read(this.command_base | ATA_REG_ERROR, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read Error register: " +
                h(this.current_interface.error_reg & 0xFF), LOG_DISK);
        }
        return this.current_interface.error_reg & 0xFF;
    });

    cpu.io.register_read(this.command_base | ATA_REG_SECTOR, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read Sector Count register: " +
                h(this.current_interface.sector_count_reg & 0xFF), LOG_DISK);
        }
        return this.read_hob_register(this.current_interface.sector_count_reg);
    });

    cpu.io.register_read(this.command_base | ATA_REG_LBA_LOW, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read LBA Low register: " +
                h(this.current_interface.lba_low_reg & 0xFF), LOG_DISK);
        }
        return this.read_hob_register(this.current_interface.lba_low_reg);
    });

    cpu.io.register_read(this.command_base | ATA_REG_LBA_MID, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read LBA Mid register: " +
                h(this.current_interface.lba_mid_reg & 0xFF), LOG_DISK);
        }
        return this.read_hob_register(this.current_interface.lba_mid_reg);
    });

    cpu.io.register_read(this.command_base | ATA_REG_LBA_HIGH, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read LBA High register: " +
                h(this.current_interface.lba_high_reg & 0xFF), LOG_DISK);
        }
        return this.read_hob_register(this.current_interface.lba_high_reg);
    });

    cpu.io.register_read(this.command_base | ATA_REG_DEVICE, this, function()
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": read Device register", LOG_DISK);
        }
        return this.current_interface.device_reg & 0xFF;
    });

    cpu.io.register_read(this.command_base | ATA_REG_STATUS, this, function()
    {
        const status = this.read_status();
        if(LOG_DETAILS & (LOG_DETAIL_REG_IO | LOG_DETAIL_IRQ))
        {
            dbg_log(`${this.current_interface.name}: read Status register: ${h(status, 2)} (lower IRQ ${this.irq})`, LOG_DISK);
        }
        this.cpu.device_lower_irq(this.irq);
        return status;
    });

    cpu.io.register_write(this.command_base | ATA_REG_DATA, this, function(data)
    {
        this.current_interface.write_data_port8(data);
    }, function(data)
    {
        this.current_interface.write_data_port16(data);
    }, function(data)
    {
        this.current_interface.write_data_port32(data);
    });

    cpu.io.register_write(this.command_base | ATA_REG_FEATURES, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write Features register: " + h(data), LOG_DISK);
        }
        this.master.features_reg = (this.master.features_reg << 8 | data) & 0xFFFF;
        this.slave.features_reg = (this.slave.features_reg << 8 | data) & 0xFFFF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_SECTOR, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write Sector Count register: " + h(data), LOG_DISK);
        }
        this.master.sector_count_reg = (this.master.sector_count_reg << 8 | data) & 0xFFFF;
        this.slave.sector_count_reg = (this.slave.sector_count_reg << 8 | data) & 0xFFFF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_LBA_LOW, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write LBA Low register: " + h(data), LOG_DISK);
        }
        this.master.lba_low_reg = (this.master.lba_low_reg << 8 | data) & 0xFFFF;
        this.slave.lba_low_reg = (this.slave.lba_low_reg << 8 | data) & 0xFFFF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_LBA_MID, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write LBA Mid register: " + h(data), LOG_DISK);
        }
        this.master.lba_mid_reg = (this.master.lba_mid_reg << 8 | data) & 0xFFFF;
        this.slave.lba_mid_reg = (this.slave.lba_mid_reg << 8 | data) & 0xFFFF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_LBA_HIGH, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write LBA High register: " + h(data), LOG_DISK);
        }
        this.master.lba_high_reg = (this.master.lba_high_reg << 8 | data) & 0xFFFF;
        this.slave.lba_high_reg = (this.slave.lba_high_reg << 8 | data) & 0xFFFF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_DEVICE, this, function(data)
    {
        const select_slave = data & ATA_DR_DEV;
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write Device register: " + h(data, 2), LOG_DISK);
        }
        if((select_slave && this.current_interface === this.master) || (!select_slave && this.current_interface === this.slave))
        {
            if(select_slave)
            {
                dbg_log(`${this.current_interface.name}: select slave device (${this.channel_nr ? "secondary" : "primary"})`, LOG_DISK);
                this.current_interface = this.slave;
            }
            else
            {
                dbg_log(`${this.current_interface.name}: select master device (${this.channel_nr ? "secondary" : "primary"})`, LOG_DISK);
                this.current_interface = this.master;
            }
        }
        this.master.device_reg = data;
        this.slave.device_reg = data;
        this.master.is_lba = data >> 6 & 1; // TODO: where does this definition of bit 6 come from? not in [ATA-6] or [ATA-4]!
        this.slave.is_lba = data >> 6 & 1;
        this.master.head = data & 0xF;      // TODO: same for lower nibble?
        this.slave.head = data & 0xF;
    });

    cpu.io.register_write(this.command_base | ATA_REG_COMMAND, this, function(data)
    {
        if(LOG_DETAILS & LOG_DETAIL_REG_IO)
        {
            dbg_log(this.current_interface.name + ": write Command register", LOG_DISK);
        }
        this.current_interface.status_reg &= ~(ATA_SR_ERR|ATA_SR_DF);
        this.current_interface.ata_command(data);
        if(LOG_DETAILS & LOG_DETAIL_IRQ)
        {
            dbg_log(this.current_interface.name + ": lower IRQ " + this.irq, LOG_DISK);
        }
        this.cpu.device_lower_irq(this.irq);
    });

    //
    // Control Block Register: control_base (BAR1: 3F6h, BAR3: 376h)
    //

    // read Alternate Status register
    cpu.io.register_read(this.control_base | ATA_REG_ALT_STATUS, this, this.read_status);

    // write Device Control register
    cpu.io.register_write(this.control_base | ATA_REG_CONTROL, this, this.write_control);

    //
    // Bus Master Registers: bus_master_base + 0...15 (BAR4: B400h)
    // primary channel: bus_master_base + 0...7, secondary: bus_master_base + 8...15
    //

    const bus_master_base = BUS_MASTER_BASE + channel_nr * 8;

    // read/write Bus Master IDE Command register
    cpu.io.register_read(bus_master_base | BMI_REG_COMMAND,
        this, this.dma_read_command8, undefined, this.dma_read_command);
    cpu.io.register_write(bus_master_base | BMI_REG_COMMAND,
        this, this.dma_write_command8, undefined, this.dma_write_command);

    // read/write Bus Master IDE Status register
    cpu.io.register_read(bus_master_base | BMI_REG_STATUS,
        this, this.dma_read_status);
    cpu.io.register_write(bus_master_base | BMI_REG_STATUS,
        this, this.dma_write_status);

    // read/write Bus Master IDE PRD Table Address register
    cpu.io.register_read(bus_master_base | BMI_REG_PRDT,
        this, undefined, undefined, this.dma_read_addr);
    cpu.io.register_write(bus_master_base | BMI_REG_PRDT,
        this, undefined, undefined, this.dma_set_addr);

    DEBUG && Object.seal(this);
}

IDEChannel.prototype.read_status = function()
{
    return this.current_interface.drive_connected ? this.current_interface.status_reg : 0;
};

// Device Control HOB (48-bit feature set): reads return the previously
// written (high order) byte of Sector Count and LBA Low/Mid/High
IDEChannel.prototype.read_hob_register = function(value)
{
    return (this.device_control_reg & ATA_CR_HOB ? value >> 8 : value) & 0xFF;
};

IDEChannel.prototype.write_control = function(data)
{
    if(LOG_DETAILS & (LOG_DETAIL_REG_IO | LOG_DETAIL_IRQ))
    {
        dbg_log(this.current_interface.name + ": write Device Control register: " +
            h(data, 2) + " interrupts " + ((data & ATA_CR_NIEN) ? "disabled" : "enabled"), LOG_DISK);
    }
    if(data & ATA_CR_SRST)
    {
        dbg_log(`${this.current_interface.name}: soft reset via control port (lower IRQ ${this.irq})`, LOG_DISK);
        this.cpu.device_lower_irq(this.irq);
        this.master.device_reset();
        this.slave.device_reset();
    }
    this.device_control_reg = data;
};

IDEChannel.prototype.hardware_reset = function()
{
    this.cpu.device_lower_irq(this.irq);
    this.master.device_reset();
    this.slave.device_reset();
    this.current_interface = this.master;
    this.device_control_reg = ATA_CR_NIEN;
    this.prdt_addr = 0;
    this.dma_status = 0;
    this.dma_command = 0;
};

IDEChannel.prototype.dma_read_addr = function()
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA get address: " + h(this.prdt_addr, 8), LOG_DISK);
    }
    return this.prdt_addr;
};

IDEChannel.prototype.dma_set_addr = function(data)
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA set address: " + h(data, 8), LOG_DISK);
    }
    this.prdt_addr = data;
};

IDEChannel.prototype.dma_read_status = function()
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA read status: " + h(this.dma_status), LOG_DISK);
    }
    return this.dma_status;
};

IDEChannel.prototype.dma_write_status = function(value)
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA write status: " + h(value), LOG_DISK);
    }
    this.dma_status &= ~(value & 6);
};

IDEChannel.prototype.dma_read_command = function()
{
    return this.dma_read_command8() | this.dma_read_status() << 16;
};

IDEChannel.prototype.dma_read_command8 = function()
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA read command: " + h(this.dma_command), LOG_DISK);
    }
    return this.dma_command;
};

IDEChannel.prototype.dma_write_command = function(value)
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA write command: " + h(value), LOG_DISK);
    }
    this.dma_write_command8(value & 0xFF);
    this.dma_write_status(value >> 16 & 0xFF);
};

IDEChannel.prototype.dma_write_command8 = function(value)
{
    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.current_interface.name + ": DMA write command8: " + h(value), LOG_DISK);
    }

    const old_command = this.dma_command;
    this.dma_command = value & 0x09;

    if((old_command & 1) === (value & 1))
    {
        return;
    }

    if((value & 1) === 0)
    {
        this.dma_status &= ~1;
        return;
    }

    this.dma_status |= 1;

    switch(this.current_interface.current_command)
    {
        case ATA_CMD_READ_DMA:
        case ATA_CMD_READ_DMA_EXT:
            this.current_interface.do_ata_read_sectors_dma();
            break;
        case ATA_CMD_WRITE_DMA:
        case ATA_CMD_WRITE_DMA_EXT:
            this.current_interface.do_ata_write_sectors_dma();
            break;
        case ATA_CMD_PACKET:
            this.current_interface.do_atapi_dma();
            break;
        default:
            dbg_log(this.current_interface.name + ": spurious DMA command write, current command: " +
                    h(this.current_interface.current_command), LOG_DISK);
            dbg_log(this.current_interface.name + ": DMA clear status bit 1h, set status bit 2h", LOG_DISK);
            this.dma_status &= ~1;
            this.dma_status |= 2;
            this.push_irq();
            break;
    }
};

IDEChannel.prototype.push_irq = function()
{
    if((this.device_control_reg & ATA_CR_NIEN) === 0)
    {
        if(LOG_DETAILS & LOG_DETAIL_IRQ)
        {
            dbg_log(this.current_interface.name + ": push IRQ " + this.irq, LOG_DISK);
        }
        this.dma_status |= 4;
        this.cpu.device_raise_irq(this.irq);
    }
};

IDEChannel.prototype.get_state = function()
{
    var state = [];
    state[0] = this.master;
    state[1] = this.slave;
    state[2] = this.command_base;
    state[3] = this.irq;
    // state[4] = this.pci_id;
    state[5] = this.control_base;
    // state[6] = this.bus_master_base;
    state[7] = this.name;
    state[8] = this.device_control_reg;
    state[9] = this.prdt_addr;
    state[10] = this.dma_status;
    state[11] = this.current_interface === this.master;
    state[12] = this.dma_command;
    return state;
};

IDEChannel.prototype.set_state = function(state)
{
    this.master.set_state(state[0]);
    this.slave.set_state(state[1]);
    this.command_base = state[2];
    this.irq = state[3];
    // this.pci_id = state[4];
    this.control_base = state[5];
    // this.bus_master_base = state[6];
    this.name = state[7];
    this.device_control_reg = state[8];
    this.prdt_addr = state[9];
    this.dma_status = state[10];
    this.current_interface = state[11] ? this.master : this.slave;
    this.dma_command = state[12];
};

/**
 * An ATA or ATAPI device. Its transport (channel) is an IDEChannel or an AHCI
 * port (src/ahci.js), which provide: push_irq() (the device signals an
 * interrupt or a new phase), dma_status (bit 0: a DMA transfer may run),
 * dma_segments(byte_count), master/slave (the devices of the transport),
 * channel_nr (with interface_nr: the drive's IDE position, for names and
 * events), cmos_geometry, sata, ncq_depth, cpu, bus and name.
 * @constructor
 * @param {?} channel
 * @param {number} interface_nr
 * @param {boolean} is_cd
 */
export function IDEInterface(channel, interface_nr, buffer, is_cd)
{
    this.channel = channel;
    this.name = channel.name + "." + interface_nr;

    /** @const @type {BusConnector} */
    this.bus = channel.bus;

    /** @const @type {number} */
    this.channel_nr = channel.channel_nr;

    /** @const @type {number} */
    this.interface_nr = interface_nr;

    /** @const @type {CPU} */
    this.cpu = channel.cpu;

    this.buffer = null;

    /** @type {boolean} */
    this.drive_connected = is_cd || !!buffer;

    /** @type {number} */
    this.sector_size = is_cd ? CDROM_SECTOR_SIZE : HD_SECTOR_SIZE;

    /** @type {boolean} */
    this.is_atapi = is_cd;

    /** @type {number} */
    this.sector_count = 0;

    /** @type {number} */
    this.head_count = this.is_atapi ? 1 : 0;

    /** @type {number} */
    this.sectors_per_track = 0;

    /** @type {number} */
    this.cylinder_count = 0;

    /** @type {number} */
    this.is_lba = 0;

    /** @type {number} */
    this.sector_count_reg = 0;

    /** @type {number} */
    this.lba_low_reg = 0;

    /** @type {number} */
    this.features_reg = 0;

    /** @type {number} */
    this.lba_mid_reg = 0;

    /** @type {number} */
    this.lba_high_reg = 0;

    /** @type {number} */
    this.head = 0;

    /** @type {number} */
    this.device_reg = 0;

    /** @type {number} */
    this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;

    /** @type {number} */
    this.sectors_per_drq = 0x80;

    /** @type {number} */
    this.error_reg = 0;

    /** @type {number} */
    this.data_pointer = 0;

    this.data = new Uint8Array(64 * 1024);
    this.data16 = new Uint16Array(this.data.buffer);
    this.data32 = new Int32Array(this.data.buffer);

    /** @type {number} */
    this.data_length = 0;

    /** @type {number} */
    this.data_end = 0;

    /** @type {number} */
    this.current_command = -1;

    /** @type {number} */
    this.write_dest = 0;

    // cancellation support, writes in flight and FLUSH CACHE: the block I/O
    // every disk controller shares (src/block_backend.js): reset_epoch counts
    // the device's resets, a write completing after one is dropped
    init_block_io(this);
    /** a write-back disk's write cache (has_write_cache): SET FEATURES 02h/82h */
    this.write_cache_enabled = true;

    // ATAPI-only
    /** @type {number} */
    this.current_atapi_command = -1;

    /** @type {number} */
    this.atapi_sense_key = 0;

    /** @type {number} */
    this.atapi_add_sense = 0;

    /** @type {number} */
    this.medium_changed = MEDIUM_CHANGED_NONE;

    this.set_disk_buffer(buffer);

    if(this.drive_connected)
    {
        dbg_log(`${this.name}: ${this.is_atapi ? "ATAPI CD-ROM" : "ATA HD"} device ready`, LOG_DISK);
    }

    Object.seal(this);
}

IDEInterface.prototype.has_disk = function()
{
    return !!this.buffer;
};

IDEInterface.prototype.eject = function()
{
    if(this.is_atapi && this.buffer)
    {
        this.medium_changed = MEDIUM_CHANGED_NOT_PRESENT;
        this.buffer = null;
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ|ATA_SR_COND;
        this.push_irq();
    }
};

IDEInterface.prototype.set_cdrom = function(buffer)
{
    if(this.is_atapi && buffer)
    {
        this.set_disk_buffer(buffer);
        this.medium_changed = MEDIUM_CHANGED_NOT_PRESENT;
    }
};

// values for CMOS_BIOS_DISKTRANSFLAG
const TRANSLATION_NONE = 0;
const TRANSLATION_LBA = 1;
const TRANSLATION_LARGE = 2;

IDEInterface.prototype.get_disk_geometry = function()
{
    // try calculating the geometry from the mbr (should be filled in starter.js)
    const mbr = this.buffer.byteLength >= 512 ? this.buffer.get_from_cache(0, 512) : undefined;

    let geometry_mbr;

    if(!mbr)
    {
        dbg_log(this.name + ": warning: first sector not available, guessing the geometry from the disk size", LOG_DISK);
    }
    else if(mbr[510] === 0x55 && mbr[511] === 0xAA)
    {
        for(let i = 0; i < 4; i++)
        {
            const offset = 0x1BE + i * 16;
            const end_head = mbr[offset + 5];
            const sectors = mbr[offset + 6] & 63;
            const sector_count = (mbr[offset + 12] | mbr[offset + 13] << 8 | mbr[offset + 14] << 16 | mbr[offset + 15] << 24) >>> 0;

            if(sector_count && end_head && sectors)
            {
                const heads = end_head + 1;
                const cylinders = this.sector_count / (heads * sectors) | 0;

                if(cylinders >= 1 && cylinders <= 16383)
                {
                    geometry_mbr = { cylinders, heads, sectors };
                    break;
                }
            }
        }
    }

    let cylinders;
    let heads;
    let sectors;
    let translation;

    // match qemu's behaviour to make sure disks are interchangeable

    if(geometry_mbr && geometry_mbr.heads <= 16)
    {
        ({ cylinders, heads, sectors } = geometry_mbr);
        translation = TRANSLATION_NONE;
    }
    else
    {
        // "standard" disk geometry
        heads = 16;
        sectors = 63;
        cylinders = this.sector_count / (heads * sectors) | 0;

        if(cylinders > 16383)
        {
            cylinders = 16383;
        }
        else if(cylinders < 2)
        {
            cylinders = 2;
        }

        if(!geometry_mbr && cylinders <= 1024)
        {
            translation = TRANSLATION_NONE;
        }
        else if(geometry_mbr && cylinders * 16 <= 131072)
        {
            translation = TRANSLATION_LARGE;
        }
        else
        {
            translation = TRANSLATION_LBA;
        }
    }

    dbg_log(this.name + ": geometry " + cylinders + "/" + heads + "/" +
            sectors + " translation " + ["none", "lba", "large"][translation], LOG_DISK);

    return { cylinders, heads, sectors, translation };
};

IDEInterface.prototype.set_disk_buffer = function(buffer)
{
    if(!buffer)
    {
        return;
    }

    this.buffer = buffer;
    if(this.is_atapi)
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ|ATA_SR_COND;
        this.error_reg = ATAPI_SK_UNIT_ATTENTION << 4;
    }
    else
    {
        // the disk's logical sectors: 512 bytes, or 4096 where its image
        // says so (logical_sector_size, docs/disk-image-formats-plan.md);
        // LBAs, counts, the capacity and each PIO data block are in them
        this.sector_size = buffer.logical_sector_size || HD_SECTOR_SIZE;
    }
    this.sector_count = this.buffer.byteLength / this.sector_size;

    if(!Number.isInteger(this.sector_count))
    {
        dbg_log(this.name + ": warning: disk size not aligned with sector size", LOG_DISK);
        this.sector_count = Math.ceil(this.sector_count);
    }

    if(this.is_atapi)
    {
        // default values: 1/2048
        this.head_count = 1;
        this.sectors_per_track = 2048;
        this.cylinder_count = this.sector_count / this.head_count / this.sectors_per_track;

        if(!Number.isInteger(this.cylinder_count))
        {
            dbg_log(this.name + ": warning: rounding up cylinder count, choose different head number", LOG_DISK);
            this.cylinder_count = Math.floor(this.cylinder_count);
        }
    }
    else
    {
        const { cylinders, heads, sectors, translation } = this.get_disk_geometry();

        this.cylinder_count = cylinders;
        this.head_count = heads;
        this.sectors_per_track = sectors;

        // for CMOS see:
        //   src/rtc.js
        //   https://github.com/coreboot/seabios/blob/master/src/hw/rtc.h
        //   https://web.archive.org/web/20240119203005/http://www.bioscentral.com/misc/cmosmap.htm
        // (IDE drives only: SeaBIOS takes the geometry of AHCI disks from IDENTIFY)
        const rtc = this.channel.cmos_geometry ? this.cpu.devices.rtc : undefined;

        // two bits per drive, the drive index is channel_nr * 2 + interface_nr
        const shift = (this.channel_nr * 2 + this.interface_nr) * 2;
        rtc && rtc.cmos_write(CMOS_BIOS_DISKTRANSFLAG,
                       rtc.cmos_read(CMOS_BIOS_DISKTRANSFLAG) & ~(3 << shift) |
                       translation << shift);

        if(rtc && this.channel_nr === 0)
        {
            const is_drive1 = this.interface_nr === 0;

            // set hard disk type (CMOS_DISK_DATA = 0x12) of C: or D: to 0b1111
            //   bits 0-3: hard disk type of D:
            //   bits 4-7: hard disk type of C:
            rtc.cmos_write(CMOS_DISK_DATA, rtc.cmos_read(CMOS_DISK_DATA) | (is_drive1 ? 0xF0 : 0x0F));
            rtc.cmos_write(is_drive1 ? CMOS_DISK_DRIVE1_TYPE : CMOS_DISK_DRIVE2_TYPE, 47);

            const drive_reg = is_drive1 ? CMOS_DISK_DRIVE1_CYL : CMOS_DISK_DRIVE2_CYL;  // 0x1B : 0x24 (drive C: or D:)
            rtc.cmos_write(drive_reg + 0, this.cylinder_count & 0xFF);        // number of cylinders least significant byte
            rtc.cmos_write(drive_reg + 1, this.cylinder_count >> 8 & 0xFF);   // number of cylinders most significant byte
            rtc.cmos_write(drive_reg + 2, this.head_count & 0xFF);            // number of heads
            rtc.cmos_write(drive_reg + 3, 0xFF);                              // write precomp cylinder least significant byte
            rtc.cmos_write(drive_reg + 4, 0xFF);                              // write precomp cylinder most significant byte
            rtc.cmos_write(drive_reg + 5, 0xC0 | (this.head_count > 8 ? 1 : 0) << 3); // control byte
            rtc.cmos_write(drive_reg + 6, this.cylinder_count & 0xFF);        // landing zone least significant byte
            rtc.cmos_write(drive_reg + 7, this.cylinder_count >> 8 & 0xFF);   // landing zone most significant byte
            rtc.cmos_write(drive_reg + 8, this.sectors_per_track & 0xFF);     // number of sectors
        }
    }

    if(this.channel.cpu)
    {
        this.push_irq();
    }
};

/**
 * The device's signature in the command block registers, as after a reset
 * ([ATA8-ACS] 4.3): a packet device's in LBA mid and high
 */
IDEInterface.prototype.set_signature = function()
{
    this.sector_count_reg = 1;
    this.lba_low_reg = 1;
    this.lba_mid_reg = this.is_atapi ? ATAPI_SIGNATURE_LO : 0;
    this.lba_high_reg = this.is_atapi ? ATAPI_SIGNATURE_HI : 0;
};

IDEInterface.prototype.device_reset = function()
{
    if(this.is_atapi)
    {
        this.status_reg = 0;
        this.sector_count_reg = 1;
        this.error_reg = 1;
        this.lba_low_reg = 1;
        this.lba_mid_reg = ATAPI_SIGNATURE_LO;  // TODO: missing documentation
        this.lba_high_reg = ATAPI_SIGNATURE_HI;
    }
    else
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_ERR;
        this.sector_count_reg = 1;
        this.error_reg = 1;
        this.lba_low_reg = 1;
        this.lba_mid_reg = 0;
        this.lba_high_reg = 0;
    }
    this.cancel_io_operations();
    // (completions of writes started before are dropped)
    this.reset_epoch++;
};

IDEInterface.prototype.push_irq = function()
{
    this.channel.push_irq();
};

IDEInterface.prototype.ata_abort_command = function()
{
    this.error_reg = ATA_ER_ABRT;
    this.status_reg = ATA_SR_DRDY|ATA_SR_ERR;
    this.push_irq();
};

/** The sectors of a read or write are beyond the end of the disk */
IDEInterface.prototype.ata_id_not_found = function()
{
    this.current_command = -1;
    this.error_reg = ATA_ER_IDNF;
    this.status_reg = ATA_SR_DRDY|ATA_SR_ERR;
    this.push_irq();
};

IDEInterface.prototype.dma_abort = function()
{
    this.channel.dma_status = this.channel.dma_status & ~1 | 2;
    this.current_command = -1;
    this.ata_abort_command();
};

/**
 * The guest memory a DMA transfer of byte_count bytes goes to or comes from,
 * as described by the transport (an IDE channel's bus master PRD table, an
 * AHCI command's PRDT). Throws a RangeError for a table that doesn't cover
 * the transfer or points outside guest RAM.
 * @param {number} byte_count
 * @return {!Array<{address: number, offset: number, length: number}>}
 */
IDEInterface.prototype.dma_segments = function(byte_count)
{
    return this.channel.dma_segments(byte_count);
};

// Bus-master IDE has 32-bit PRDT and buffer addresses. Validate every segment
// before any payload transfer, including holes created by RAM relocation.
IDEChannel.prototype.dma_segments = function(byte_count)
{
    let table = this.prdt_addr >>> 0;
    let offset = 0;
    const segments = [];
    while(offset < byte_count)
    {
        if(table + 8 > 0x100000000) throw new RangeError("IDE PRDT exceeds 32-bit address width");
        this.cpu.validate_physical_range(table, 8);
        const address = this.cpu.read32_physical(table);
        const count = this.cpu.read16_physical(table + 4) || 0x10000;
        const end = this.cpu.read8_physical(table + 7) & 0x80;
        const length = Math.min(count, byte_count - offset);
        if(address + length > 0x100000000) throw new RangeError("IDE DMA exceeds 32-bit address width");
        this.cpu.validate_physical_range(address, length);
        segments.push({ address, offset, length });
        offset += length;
        if(end && offset < byte_count) throw new RangeError("IDE PRDT ends before the requested transfer");
        table += 8;
    }
    return segments;
};

IDEInterface.prototype.capture_regs = function()
{
    return `ST=${h(this.status_reg & 0xFF)} ER=${h(this.error_reg & 0xFF)} ` +
        `SC=${h(this.sector_count_reg & 0xFF)} LL=${h(this.lba_low_reg & 0xFF)} ` +
        `LM=${h(this.lba_mid_reg & 0xFF)} LH=${h(this.lba_high_reg & 0xFF)} ` +
        `FE=${h(this.features_reg & 0xFF)}`;
};

IDEInterface.prototype.ata_command = function(cmd)
{
    if(!this.drive_connected && cmd !== ATA_CMD_EXECUTE_DEVICE_DIAGNOSTIC)
    {
        dbg_log(`${this.name}: ATA command ${ATA_CMD_NAME[cmd]} (${h(cmd)}) ignored: no slave drive connected`, LOG_DISK);
        return;
    }

    const regs_pre = DEBUG ? this.capture_regs() : undefined;
    let do_dbg_log = DEBUG;

    this.current_command = cmd;
    this.error_reg = 0;

    switch(cmd)
    {
        case ATA_CMD_DEVICE_RESET:
            this.data_pointer = 0;
            this.data_end = 0;
            this.data_length = 0;
            this.device_reset();
            this.push_irq();
            break;

        case ATA_CMD_10h:
            this.lba_mid_reg = 0;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_READ_NATIVE_MAX_ADDRESS:
            var last_sector = this.sector_count - 1;
            this.lba_low_reg = last_sector & 0xFF;
            this.lba_mid_reg = last_sector >> 8 & 0xFF;
            this.lba_high_reg = last_sector >> 16 & 0xFF;
            this.device_reg = this.device_reg & 0xF0 | last_sector >> 24 & 0x0F;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_READ_NATIVE_MAX_ADDRESS_EXT:
            var last_sector = this.sector_count - 1;
            // 48 bits: the previous (HOB) byte of each register holds bits 24-47
            var last_high = Math.floor(last_sector / 0x1000000);
            this.lba_low_reg = last_sector & 0xFF | (last_high & 0xFF) << 8;
            this.lba_mid_reg = last_sector >> 8 & 0xFF | (last_high >> 8 & 0xFF) << 8;
            this.lba_high_reg = last_sector >> 16 & 0xFF | (last_high >> 16 & 0xFF) << 8;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_READ_SECTORS:
            do_dbg_log = false;
            if(this.is_atapi)
            {
                this.lba_mid_reg = ATAPI_SIGNATURE_LO;  // see [ATA8-ACS] 4.3
                this.lba_high_reg = ATAPI_SIGNATURE_HI;
                this.ata_abort_command();
            }
            else
            {
                this.ata_read_sectors(cmd);
            }
            break;

        case ATA_CMD_READ_SECTORS_EXT:
        case ATA_CMD_READ_MULTIPLE:
        case ATA_CMD_READ_MULTIPLE_EXT:
            do_dbg_log = false;
            if(this.is_atapi)
            {
                this.ata_abort_command();
            }
            else
            {
                this.ata_read_sectors(cmd);
            }
            break;

        case ATA_CMD_WRITE_SECTORS:
        case ATA_CMD_WRITE_SECTORS_EXT:
        case ATA_CMD_WRITE_MULTIPLE:
        case ATA_CMD_WRITE_MULTIPLE_EXT:
            do_dbg_log = false;
            if(this.is_atapi)
            {
                this.ata_abort_command();
            }
            else
            {
                this.ata_write_sectors(cmd);
            }
            break;

        case ATA_CMD_EXECUTE_DEVICE_DIAGNOSTIC:
            // the behaviour of this command is independent of the selected device;
            // each device present then has its signature in the command block
            // registers (OVMF tells a hard disk from a CD drive by it)
            this.channel.master.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.channel.master.error_reg = 0x01;    // Master drive passed, slave drive passed or not present
            if(this.channel.master.drive_connected) this.channel.master.set_signature();
            this.channel.master.push_irq();
            if(this.channel.slave && this.channel.slave.drive_connected)
            {
                this.channel.slave.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
                this.channel.slave.error_reg = 0x01; // Slave drive passed
                this.channel.slave.set_signature();
                this.channel.slave.push_irq();
            }
            break;

        case ATA_CMD_INITIALIZE_DEVICE_PARAMETERS:
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_PACKET:
            if(this.is_atapi)
            {
                do_dbg_log = false;
                this.data_allocate(12);
                this.data_end = 12;
                this.sector_count_reg = 0x01;   // 0x01: indicates transfer of a command packet (C/D)
                this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
                this.push_irq();
            }
            else
            {
                this.ata_abort_command();
            }
            break;

        case ATA_CMD_IDENTIFY_PACKET_DEVICE:
            if(this.is_atapi)
            {
                this.create_identify_packet();
                this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
                this.push_irq();
            }
            else
            {
                this.ata_abort_command();
            }
            break;

        case ATA_CMD_SET_MULTIPLE_MODE:
            // Logical sectors per DRQ Block in word 1
            dbg_log(this.name + ": logical sectors per DRQ Block: " + h(this.sector_count_reg & 0xFF), LOG_DISK);
            this.sectors_per_drq = this.sector_count_reg & 0xFF;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_READ_DMA:
        case ATA_CMD_READ_DMA_EXT:
            do_dbg_log = false;
            this.ata_read_sectors_dma(cmd);
            break;

        case ATA_CMD_WRITE_DMA:
        case ATA_CMD_WRITE_DMA_EXT:
            do_dbg_log = false;
            this.ata_write_sectors_dma(cmd);
            break;

        case ATA_CMD_READ_VERIFY_SECTORS:
            // TODO: check that lba_low/mid/high and sector_count regs are within the bounds of the disk's size
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_GET_MEDIA_STATUS:
            if(this.is_atapi)
            {
                if(!this.buffer)
                {
                    this.error_reg |= 0x02; // NM: No Media
                }
                if(this.medium_changed)
                {
                    this.error_reg |= 0x20; // MC: Media Change
                    this.medium_changed = MEDIUM_CHANGED_NONE;
                }
                this.error_reg |= 0x40;     // WP: Write Protect
            }
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_STANDBY_IMMEDIATE:
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_IDLE_IMMEDIATE:
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_FLUSH_CACHE:
        case ATA_CMD_FLUSH_CACHE_EXT:
            // the writes before it have reached the backend
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_BSY;
            this.when_writes_done(() =>
            {
                this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
                this.push_irq();
            });
            break;

        case ATA_CMD_IDENTIFY_DEVICE:
            if(this.is_atapi)
            {
                this.lba_mid_reg = ATAPI_SIGNATURE_LO;  // see [ATA8-ACS] 4.3
                this.lba_high_reg = ATAPI_SIGNATURE_HI;
                this.ata_abort_command();
            }
            else
            {
                this.create_identify_packet();
                this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
                this.push_irq();
            }
            break;

        case ATA_CMD_SET_FEATURES:
            // 02h, 82h: a write-back disk's write cache on, off (the other
            // subcommands, and these for the other disks, are taken as
            // before)
            if(this.has_write_cache() && ((this.features_reg & 0xFF) === 0x02 || (this.features_reg & 0xFF) === 0x82))
            {
                this.write_cache_enabled = (this.features_reg & 0xFF) === 0x02;
                dbg_log(this.name + ": write cache " + (this.write_cache_enabled ? "on" : "off"), LOG_DISK);
            }
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_MEDIA_LOCK:
            this.status_reg = ATA_SR_DRDY;
            this.push_irq();
            break;

        case ATA_CMD_SECURITY_FREEZE_LOCK:
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.push_irq();
            break;

        case ATA_CMD_SET_MAX:
            this.ata_abort_command();
            break;

        case ATA_CMD_NOP:
            this.ata_abort_command();
            break;

        case ATA_CMD_F0h:
            dbg_log(`${this.name}: error: unimplemented vendor-specific ATA command ${h(cmd)}: ABORT [${this.capture_regs()}]`, LOG_DISK);
            this.ata_abort_command();
            break;

        default:
            // Unsupported commands abort (ATA8-ACS); guests probe optional
            // ones, e.g. Windows 8 sends READ LOG EXT (2Fh)
            dbg_log(`${this.name}: unimplemented ATA command ${h(cmd)}: ABORT [${this.capture_regs()}]`, LOG_DISK);
            this.ata_abort_command();
            break;
    }

    if(DEBUG && do_dbg_log)
    {
        const regs_msg = `[${regs_pre}] -> [${this.capture_regs()}]`;
        const result = this.status_reg & ATA_SR_ERR ? (this.error_reg & ATA_ER_ABRT ? "ABORT" : "ERROR") : "OK";
        dbg_log(`${this.name}: ATA command ${ATA_CMD_NAME[cmd]} (${h(cmd)}): ${result} ${regs_msg}`, LOG_DISK);
    }
};

IDEInterface.prototype.atapi_handle = function()
{
    const cmd = this.data[0];
    const cmd_name = ATAPI_CMD[cmd] ? ATAPI_CMD[cmd].name : "<undefined>";
    const cmd_flags = ATAPI_CMD[cmd] ? ATAPI_CMD[cmd].flags : ATAPI_CF_NONE;
    const regs_pre = DEBUG ? this.capture_regs() : undefined;

    let do_dbg_log = DEBUG;
    let dbg_log_extra;

    this.data_pointer = 0;
    this.current_atapi_command = cmd;

    // Report a media change before the sense-clear, over two commands each
    // pending until REQUEST SENSE: NOT PRESENT then UNIT ATTENTION. Polling
    // guests need this absent->changed order to drop the cached volume.
    if(this.medium_changed && this.buffer &&
        cmd !== ATAPI_CMD_REQUEST_SENSE && cmd !== ATAPI_CMD_INQUIRY)
    {
        if(this.medium_changed === MEDIUM_CHANGED_NOT_PRESENT)
        {
            this.medium_changed = MEDIUM_CHANGED_UNIT_ATTENTION;
            this.atapi_check_condition_response(ATAPI_SK_NOT_READY, ATAPI_ASC_MEDIUM_NOT_PRESENT);
        }
        else
        {
            this.medium_changed = MEDIUM_CHANGED_NONE;
            this.atapi_check_condition_response(ATAPI_SK_UNIT_ATTENTION, ATAPI_ASC_MEDIUM_MAY_HAVE_CHANGED);
        }
        this.push_irq();
        return;
    }

    if(cmd !== ATAPI_CMD_REQUEST_SENSE) // TODO
    {
        this.atapi_sense_key = 0;
        this.atapi_add_sense = 0;
    }

    if(!this.buffer && cmd_flags & ATAPI_CF_NEEDS_DISK)
    {
        this.atapi_check_condition_response(ATAPI_SK_NOT_READY, ATAPI_ASC_MEDIUM_NOT_PRESENT);
        this.push_irq();
        if(DEBUG)
        {
            dbg_log(`${this.name}: ATAPI command ${cmd_name} (${h(cmd)}) without medium: ERROR [${regs_pre}]`, LOG_DISK);
        }
        return;
    }

    switch(cmd)
    {
        case ATAPI_CMD_TEST_UNIT_READY:
            if(this.buffer)
            {
                this.data_allocate(0);
                this.data_end = this.data_length;
                this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            }
            else
            {
                this.atapi_check_condition_response(ATAPI_SK_NOT_READY, ATAPI_ASC_MEDIUM_NOT_PRESENT);
            }
            break;

        case ATAPI_CMD_REQUEST_SENSE:
            this.data_allocate(this.data[4]);
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.data[0] = 0x80 | 0x70;             // valid | SCSI error code
            this.data[2] = this.atapi_sense_key;    // SCSI sense key
            this.data[7] = 8;                       // SCSI additional sense length (fixed 8 for this error code 0x70)
            this.data[12] = this.atapi_add_sense;   // SCSI additional sense code
            this.atapi_sense_key = 0;
            this.atapi_add_sense = 0;
            break;

        case ATAPI_CMD_INQUIRY:
            var length = this.data[4];
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            dbg_log_extra = "lun=" + h(this.data[1], 2) + " length=" + length;
            // for data layout see [CD-SCSI-2] "INQUIRY Command"
            this.data.set([
                // 0: Device-type, Removable, ANSI-Version, Response Format
                0x05, 0x80, 0x01, 0x31,
                // 4: Additional length, Reserved, Reserved, Reserved
                31, 0, 0, 0,
            ]);
            // 8: Vendor Identification, 16: Product Identification,
            // 32: Product Revision Level (QEMU's with platform.qemu_compatible)
            [...this.cpu.platform.qemu_compatible ? "QEMU    QEMU DVD-ROM    2.5+" : "SONY    CD-ROM CDU-1000 1.1a"]
                .forEach((c, i) => { this.data[8 + i] = c.charCodeAt(0); });
            this.data_end = this.data_length = Math.min(36, length);
            break;

        case ATAPI_CMD_MODE_SENSE_6:
            this.data_allocate(this.data[4]);
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
            this.data_allocate(0);
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            break;

        case ATAPI_CMD_READ_CAPACITY:
            var count = this.sector_count - 1;
            this.data_set(new Uint8Array([
                count >> 24 & 0xFF,
                count >> 16 & 0xFF,
                count >> 8 & 0xFF,
                count & 0xFF,
                0,
                0,
                this.sector_size >> 8 & 0xFF,
                this.sector_size & 0xFF,
            ]));
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_READ_FORMAT_CAPACITIES:
            var count = this.sector_count - 1;
            this.data_set(new Uint8Array([
                0,
                0,
                0,
                8, // capacity list length
                count >> 24 & 0xFF,
                count >> 16 & 0xFF,
                count >> 8 & 0xFF,
                count & 0xFF,
                2, // formatted
                this.sector_size >> 16 & 0xFF,
                this.sector_size >> 8 & 0xFF,
                this.sector_size & 0xFF,
            ]));
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_READ_10:
        case ATAPI_CMD_READ_12:
            do_dbg_log = false;
            if(this.features_reg & 1)
            {
                this.atapi_read_dma(this.data);
            }
            else
            {
                this.atapi_read(this.data);
            }
            break;

        case ATAPI_CMD_READ_SUBCHANNEL:
            var length = this.data[8];
            dbg_log_extra = "length=" + length;
            this.data_allocate(Math.min(8, length));
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_READ_TOC_PMA_ATIP:
            var length = this.data[8] | this.data[7] << 8;
            var format = this.data[9] >> 6;
            // Read the MSF flag before data_allocate() overwrites this.data.
            const toc_msf = (this.data[1] & 2) !== 0;
            dbg_log_extra = `${h(format, 2)} length=${length} ${toc_msf} ${h(this.data[6])}`;

            this.data_allocate(length);
            this.data_end = this.data_length;
            if(format === 0)
            {
                // Track 1 start and lead-out, in MSF when requested. Win9x sizes
                // the disc from the lead-out MSF; raw LBA mis-sizes >~256 MB discs.
                const addr = (lba) => toc_msf
                    ? [0, (lba + 150) / (75 * 60) | 0, ((lba + 150) / 75 | 0) % 60, (lba + 150) % 75]
                    : [lba >> 24 & 0xFF, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF];
                const start = addr(0);
                const leadout = addr(this.sector_count);
                this.data.set(new Uint8Array([
                    0, 18, // length
                    1, 1, // first and last session

                    0,
                    0x14,
                    1, // track number
                    0,
                    start[0], start[1], start[2], start[3],

                    0,
                    0x16,
                    0xAA, // track number
                    0,
                    leadout[0], leadout[1], leadout[2], leadout[3],
                ]));
            }
            else if(format === 1)
            {
                this.data.set(new Uint8Array([
                    0, 10, // length
                    1, 1, // first and last session
                    0, 0,
                    0, 0,
                    0, 0,
                    0, 0,
                ]));
            }
            else
            {
                dbg_assert(false, this.name + ": error: unimplemented format: " + format);
            }

            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_GET_CONFIGURATION:
            var length = Math.min(this.data[8] | this.data[7] << 8, 32);
            dbg_log_extra = "length=" + length;
            this.data_allocate(length);
            this.data_end = this.data_length;
            this.data[0] = length - 4 >> 24 & 0xFF;
            this.data[1] = length - 4 >> 16 & 0xFF;
            this.data[2] = length - 4 >> 8 & 0xFF;
            this.data[3] = length - 4 & 0xFF;
            this.data[6] = 0x08;
            this.data[10] = 3;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_READ_DISK_INFORMATION:
            this.data_allocate(0);
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            break;

        case ATAPI_CMD_READ_TRACK_INFORMATION:
            dbg_log_extra = "unimplemented";
            this.atapi_check_condition_response(ATAPI_SK_ILLEGAL_REQUEST, ATAPI_ASC_INV_FIELD_IN_CMD_PACKET);
            break;

        case ATAPI_CMD_MODE_SENSE_10:
            var length = this.data[8] | this.data[7] << 8;
            var page_code = this.data[2];
            dbg_log_extra = "page_code=" + h(page_code) + " length=" + length;
            if(page_code === 0x2A)
            {
                this.data_allocate(Math.min(30, length));
            }
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_MECHANISM_STATUS:
            this.data_allocate(this.data[9] | this.data[8] << 8);
            this.data_end = this.data_length;
            this.data[5] = 1;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            break;

        case ATAPI_CMD_START_STOP_UNIT:
            var loej_start = this.data[4] & 0x3;
            dbg_log_extra = `Immed=${h(this.data[1] & 1)} LoEj/Start=${h(loej_start)}`;
            if(this.buffer && loej_start === 0x2)
            {
                dbg_log_extra += ": disk ejected";
                this.medium_changed = MEDIUM_CHANGED_NOT_PRESENT;
                this.buffer = null;
            }
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.data_allocate(0);
            this.data_end = this.data_length;
            break;

        case ATAPI_CMD_PAUSE:
        case ATAPI_CMD_GET_EVENT_STATUS_NOTIFICATION:
        case ATAPI_CMD_REPORT_KEY:
        case ATAPI_CMD_READ_DISC_STRUCTURE:
            dbg_log_extra = "unimplemented";
            this.atapi_check_condition_response(ATAPI_SK_ILLEGAL_REQUEST, ATAPI_ASC_INV_FIELD_IN_CMD_PACKET);
            break;

        case ATAPI_CMD_READ_CD:
            dbg_log_extra = "unimplemented";
            this.data_allocate(0);
            this.data_end = this.data_length;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            break;

        default:
            // Answered with ILLEGAL REQUEST, which guests use to probe features
            dbg_log(`${this.name}: unimplemented ATAPI command ${h(this.data[0])}`, LOG_DISK);
            this.atapi_check_condition_response(ATAPI_SK_ILLEGAL_REQUEST, ATAPI_ASC_INV_FIELD_IN_CMD_PACKET);
            break;
    }

    this.sector_count_reg = this.sector_count_reg & ~7 | 2;

    if((this.status_reg & ATA_SR_BSY) === 0)
    {
        this.push_irq();
    }

    if((this.status_reg & ATA_SR_BSY) === 0 && this.data_length === 0)
    {
        this.sector_count_reg |= 1;
        this.status_reg &= ~ATA_SR_DRQ;
    }

    if(DEBUG && do_dbg_log)
    {
        const regs_msg = `[${regs_pre}] -> [${this.capture_regs()}]`;
        const result = this.status_reg & ATA_SR_ERR ? (this.error_reg & ATA_ER_ABRT ? "ABORT" : "ERROR") : "OK";
        dbg_log_extra = dbg_log_extra ? ` ${dbg_log_extra}:` : "";
        dbg_log(`${this.name}: ATAPI command ${cmd_name} (${h(cmd)}):${dbg_log_extra} ${result} ${regs_msg}`, LOG_DISK);
    }
};

IDEInterface.prototype.atapi_check_condition_response = function(sense_key, additional_sense)
{
    // Setup ATA registers to CHECK CONDITION state.
    // The sense state (sense_key and additional_sense) must be requested
    // by the host using ATAPI_CMD_REQUEST_SENSE immediately following a
    // CHECK CONDITION response or else it will be lost.
    // https://github.com/qemu/qemu/blob/757a34115e7491744a63dfc3d291fd1de5297ee2/hw/ide/atapi.c#L186
    this.data_allocate(0);
    this.data_end = this.data_length;
    this.status_reg = ATA_SR_DRDY|ATA_SR_COND;
    this.error_reg = sense_key << 4;
    this.sector_count_reg = (this.sector_count_reg & ~7) | 2 | 1;
    this.atapi_sense_key = sense_key;
    this.atapi_add_sense = additional_sense;
};

IDEInterface.prototype.do_write = function()
{
    dbg_assert(this.data_length <= this.data.length);
    // (a copy: the next command may reuse this.data before the backend is done)
    var data = this.data.slice(0, this.data_length);

    //dbg_log(hex_dump(data), LOG_DISK);
    dbg_assert(this.data_length % this.sector_size === 0);
    const sectors = this.data_length / this.sector_size;

    // Busy until the backend has the data: completion is reported after it
    this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_BSY;
    this.write_to_backend(this.write_dest, data, () =>
    {
        this.ata_advance(this.current_command, sectors);
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
        this.push_irq();
    });

    this.report_write(this.data_length);
};

/**
 * Write to the disk image. The callback runs once the backend has taken the
 * data, unless a device reset happened in between; FLUSH CACHE waits for
 * every write in flight (when_writes_done). A backend that fails the write
 * (its callback's argument: docs/disk-image-formats-plan.md P0) ends the
 * command with an error instead (on_error, or io_error).
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function()} callback
 * @param {function(!Error)=} on_error
 * @param {boolean=} fua the write is durable before it completes (NCQ's FUA)
 */
IDEInterface.prototype.write_to_backend = function(start, data, callback, on_error, fua)
{
    // (the guest turned a write-back disk's write cache off: each write is
    // durable before it completes; FUA, the same for one write)
    const durable = !!fua || this.has_write_cache() && !this.write_cache_enabled;
    block_write(this, start, data, callback, on_error || (error => this.io_error(error)), durable);
};

/**
 * Whether the disk reports a volatile write cache: one written back
 * (disk_option "read_write", docs/disk-persistence-plan.md "向客户机报告写缓存"),
 * where a completed write is in the host's page cache, durable only after
 * a flush; the other disks' IDENTIFY is as it was
 * @return {boolean}
 */
IDEInterface.prototype.has_write_cache = function()
{
    return !this.is_atapi && !!this.buffer && !!this.buffer.writeback;
};

/**
 * Call back when no write is in flight any more, and the backend's own
 * flush (if it has one) is done: FLUSH CACHE; a failed flush ends the
 * command with an error (io_error)
 * @param {function()} callback
 */
IDEInterface.prototype.when_writes_done = function(callback)
{
    block_when_writes_done(this, callback, error => this.io_error(error));
};

IDEInterface.prototype.atapi_read = function(cmd)
{
    // Note: Big Endian
    var lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5];
    var count = cmd[0] === ATAPI_CMD_READ_12 ? (cmd[6] << 24 | cmd[7] << 16 | cmd[8] << 8 | cmd[9]) : (cmd[7] << 8 | cmd[8]);
    count >>>= 0;
    var flags = cmd[1];
    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    if(LOG_DETAILS & LOG_DETAIL_RW)
    {
        dbg_log(this.name + ": CD read lba=" + h(lba) +
                " lbacount=" + h(count) +
                " bytecount=" + h(byte_count) +
                " flags=" + h(flags), LOG_DISK);
    }

    this.data_length = 0;
    var req_length = this.lba_high_reg << 8 & 0xFF00 | this.lba_mid_reg & 0xFF;
    //dbg_log(this.name + ": " + h(this.lba_high_reg, 2) + " " + h(this.lba_mid_reg, 2), LOG_DISK);
    this.lba_mid_reg = this.lba_high_reg = 0; // oak technology driver (windows 3.0)

    if(req_length === 0xFFFF)
        req_length--;

    if(req_length > byte_count)
    {
        req_length = byte_count;
    }

    if(!this.buffer)
    {
        dbg_log(this.name + ": CD read: no medium", LOG_DISK);
        this.atapi_check_condition_response(ATAPI_SK_NOT_READY, ATAPI_ASC_MEDIUM_NOT_PRESENT);
        this.push_irq();
    }
    else if(start >= this.buffer.byteLength)
    {
        dbg_log(this.name + ": CD read: Outside of disk  end=" + h(start + byte_count) +
                          " size=" + h(this.buffer.byteLength), LOG_DISK);
        this.atapi_check_condition_response(ATAPI_SK_ILLEGAL_REQUEST, ATAPI_ASC_LBA_OUT_OF_RANGE);
        this.push_irq();
    }
    else if(byte_count === 0)
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;

        this.data_pointer = 0;
        //this.push_irq();
    }
    else
    {
        byte_count = Math.min(byte_count, this.buffer.byteLength - start);
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_BSY;
        this.report_read_start();

        this.read_buffer(start, byte_count, (data) =>
        {
            if(LOG_DETAILS & LOG_DETAIL_RW)
            {
                dbg_log(this.name + ": CD read: data arrived", LOG_DISK);
            }
            this.data_set(data);
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.sector_count_reg = this.sector_count_reg & ~7 | 2;

            this.push_irq();

            req_length &= ~3;

            this.data_end = req_length;
            if(this.data_end > this.data_length)
            {
                this.data_end = this.data_length;
            }
            this.lba_mid_reg = this.data_end & 0xFF;
            this.lba_high_reg = this.data_end >> 8 & 0xFF;

            this.report_read_end(byte_count);
        });
    }
};

IDEInterface.prototype.atapi_read_dma = function(cmd)
{
    // Note: Big Endian
    var lba = cmd[2] << 24 | cmd[3] << 16 | cmd[4] << 8 | cmd[5];
    var count = cmd[0] === ATAPI_CMD_READ_12 ? (cmd[6] << 24 | cmd[7] << 16 | cmd[8] << 8 | cmd[9]) : (cmd[7] << 8 | cmd[8]);
    count >>>= 0;
    var flags = cmd[1];
    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    dbg_log(this.name + ": CD read DMA lba=" + h(lba) +
            " lbacount=" + h(count) +
            " bytecount=" + h(byte_count) +
            " flags=" + h(flags), LOG_DISK);

    if(start >= this.buffer.byteLength)
    {
        dbg_log(this.name + ": CD read: Outside of disk  end=" + h(start + byte_count) +
                          " size=" + h(this.buffer.byteLength), LOG_DISK);
        this.channel.dma_status &= ~1;
        this.atapi_check_condition_response(ATAPI_SK_ILLEGAL_REQUEST, ATAPI_ASC_LBA_OUT_OF_RANGE);
        this.push_irq();
    }
    else
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_BSY;
        this.report_read_start();

        this.read_buffer(start, byte_count, (data) =>
        {
            dbg_log(this.name + ": atapi_read_dma: Data arrived", LOG_DISK);
            this.report_read_end(byte_count);
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.sector_count_reg = this.sector_count_reg & ~7 | 2;
            this.data_set(data);

            this.do_atapi_dma();
        });
    }
};

IDEInterface.prototype.do_atapi_dma = function()
{
    if((this.channel.dma_status & 1) === 0)
    {
        dbg_log(this.name + ": do_atapi_dma: Status not set", LOG_DISK);
        return;
    }

    if((this.status_reg & ATA_SR_DRQ) === 0)
    {
        dbg_log(this.name + ": do_atapi_dma: DRQ not set", LOG_DISK);
        return;
    }

    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.name + ": ATAPI DMA transfer len=" + this.data_length, LOG_DISK);
    }

    try
    {
        for(const segment of this.dma_segments(this.data_length))
        {
            this.cpu.write_blob_physical(this.data.subarray(segment.offset, segment.offset + segment.length), segment.address);
        }
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.dma_abort();
        return;
    }

    this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
    this.channel.dma_status &= ~1;
    this.sector_count_reg = this.sector_count_reg & ~7 | 3;
    this.push_irq();
};

IDEInterface.prototype.read_data = function(length)
{
    if(this.data_pointer < this.data_end)
    {
        dbg_assert(this.data_pointer + length - 1 < this.data_end);
        dbg_assert(this.data_pointer % length === 0, h(this.data_pointer) + " " + length);

        if(length === 1)
        {
            var result = this.data[this.data_pointer];
        }
        else if(length === 2)
        {
            var result = this.data16[this.data_pointer >>> 1];
        }
        else
        {
            var result = this.data32[this.data_pointer >>> 2];
        }

        this.data_pointer += length;

        var align = (this.data_end & 0xFFF) === 0 ? 0xFFF : 0xFF;

        if(LOG_DETAILS & LOG_DETAIL_RW)
        {
            if((this.data_pointer & align) === 0)
            {
                dbg_log(this.name + ": read 1F0: " + h(this.data[this.data_pointer], 2) +
                            " cur=" + h(this.data_pointer) +
                            " cnt=" + h(this.data_length), LOG_DISK);
            }
        }

        if(this.data_pointer >= this.data_end)
        {
            this.read_end();
        }

        return result;
    }
    else
    {
        if(LOG_DETAILS & LOG_DETAIL_RW)
        {
            dbg_log(this.name + ": read 1F0: empty", LOG_DISK);
        }
        this.data_pointer += length;
        return 0;
    }
};

IDEInterface.prototype.read_end = function()
{
    if(LOG_DETAILS & LOG_DETAIL_RW)
    {
        dbg_log(this.name + ": read_end cmd=" + h(this.current_command) +
                " data_pointer=" + h(this.data_pointer) + " end=" + h(this.data_end) +
                " length=" + h(this.data_length), LOG_DISK);
    }

    if(this.current_command === ATA_CMD_PACKET)
    {
        if(this.data_end === this.data_length)
        {
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
            this.sector_count_reg = this.sector_count_reg & ~7 | 3;
            this.push_irq();
        }
        else
        {
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.sector_count_reg = this.sector_count_reg & ~7 | 2;
            this.push_irq();
            var byte_count = this.lba_high_reg << 8 & 0xFF00 | this.lba_mid_reg & 0xFF;

            if(this.data_end + byte_count > this.data_length)
            {
                this.lba_mid_reg = (this.data_length - this.data_end) & 0xFF;
                this.lba_high_reg = (this.data_length - this.data_end) >> 8 & 0xFF;
                this.data_end = this.data_length;
            }
            else
            {
                this.data_end += byte_count;
            }
            if(LOG_DETAILS & LOG_DETAIL_RW)
            {
                dbg_log(this.name + ": data_end=" + h(this.data_end), LOG_DISK);
            }
        }
    }
    else
    {
        this.error_reg = 0;
        if(this.data_pointer >= this.data_length)
        {
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
        }
        else
        {
            if(this.current_command === ATA_CMD_READ_MULTIPLE || this.current_command === ATA_CMD_READ_MULTIPLE_EXT)
            {
                var sector_count = Math.min(this.sectors_per_drq,
                    (this.data_length - this.data_end) / this.sector_size);
                dbg_assert(sector_count % 1 === 0);
            }
            else
            {
                dbg_assert(this.current_command === ATA_CMD_READ_SECTORS || this.current_command === ATA_CMD_READ_SECTORS_EXT);
                var sector_count = 1;
            }
            this.ata_advance(this.current_command, sector_count);
            this.data_end += this.sector_size * sector_count;
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.push_irq();
        }
    }
};

IDEInterface.prototype.write_data_port = function(data, length)
{
    dbg_assert(this.data_pointer % length === 0);

    if(this.data_pointer >= this.data_end)
    {
        dbg_log(this.name + ": redundant write to data port: " + h(data) + " count=" +
                h(this.data_end) + " cur=" + h(this.data_pointer), LOG_DISK);
    }
    else
    {
        var align = (this.data_end & 0xFFF) === 0 ? 0xFFF : 0xFF;
        if(LOG_DETAILS & LOG_DETAIL_RW)
        {
            if((this.data_pointer + length & align) === 0 || this.data_end < 20)
            {
                dbg_log(this.name + ": data port: " + h(data >>> 0) + " count=" +
                        h(this.data_end) + " cur=" + h(this.data_pointer), LOG_DISK);
            }
        }

        if(length === 1)
        {
            this.data[this.data_pointer++] = data;
        }
        else if(length === 2)
        {
            this.data16[this.data_pointer >>> 1] = data;
            this.data_pointer += 2;
        }
        else
        {
            this.data32[this.data_pointer >>> 2] = data;
            this.data_pointer += 4;
        }

        dbg_assert(this.data_pointer <= this.data_end);
        if(this.data_pointer === this.data_end)
        {
            this.write_end();
        }
    }
};

IDEInterface.prototype.write_data_port8 = function(data)
{
    this.write_data_port(data, 1);
};

IDEInterface.prototype.write_data_port16 = function(data)
{
    this.write_data_port(data, 2);
};

IDEInterface.prototype.write_data_port32 = function(data)
{
    this.write_data_port(data, 4);
};

IDEInterface.prototype.write_end = function()
{
    if(this.current_command === ATA_CMD_PACKET)
    {
        this.atapi_handle();
    }
    else
    {
        if(LOG_DETAILS & LOG_DETAIL_RW)
        {
            dbg_log(this.name + ": write_end data_pointer=" + h(this.data_pointer) +
                " data_length=" + h(this.data_length), LOG_DISK);
        }

        if(this.data_pointer >= this.data_length)
        {
            this.do_write();
        }
        else
        {
            dbg_assert(this.current_command === ATA_CMD_WRITE_SECTORS ||
                this.current_command === ATA_CMD_WRITE_SECTORS_EXT ||
                this.current_command === ATA_CMD_WRITE_MULTIPLE_EXT,
                "Unexpected command: " + h(this.current_command));

            // XXX: Should advance here, but do_write does all the advancing
            //this.ata_advance(this.current_command, 1);
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.data_end += this.sector_size;
            this.push_irq();
        }
    }
};

IDEInterface.prototype.ata_advance = function(cmd, sectors)
{
    if(LOG_DETAILS & LOG_DETAIL_RW)
    {
        dbg_log(this.name + ": advance sectors=" + sectors + " old_sector_count_reg=" + this.sector_count_reg, LOG_DISK);
    }
    this.sector_count_reg -= sectors;

    if(cmd === ATA_CMD_READ_SECTORS_EXT ||
            cmd === ATA_CMD_READ_MULTIPLE ||
            cmd === ATA_CMD_READ_DMA_EXT ||
            cmd === ATA_CMD_WRITE_SECTORS_EXT ||
            cmd === ATA_CMD_WRITE_MULTIPLE ||
            cmd === ATA_CMD_WRITE_DMA_EXT)
    {
        var new_sector = sectors + this.get_lba48();
        this.lba_low_reg = new_sector & 0xFF | new_sector >> 16 & 0xFF00;
        this.lba_mid_reg = new_sector >> 8 & 0xFF;
        this.lba_high_reg = new_sector >> 16 & 0xFF;
    }
    else if(this.is_lba)
    {
        var new_sector = sectors + this.get_lba28();
        this.lba_low_reg = new_sector & 0xFF;
        this.lba_mid_reg = new_sector >> 8 & 0xFF;
        this.lba_high_reg = new_sector >> 16 & 0xFF;
        this.head = this.head & ~0xF | new_sector & 0xF;
    }
    else // chs
    {
        var new_sector = sectors + this.get_chs();

        var c = new_sector / (this.head_count * this.sectors_per_track) | 0;
        this.lba_mid_reg = c & 0xFF;
        this.lba_high_reg = c >> 8 & 0xFF;
        this.head = (new_sector / this.sectors_per_track | 0) % this.head_count & 0xF;
        this.lba_low_reg = (new_sector % this.sectors_per_track + 1) & 0xFF;

        dbg_assert(new_sector === this.get_chs());
    }
};

IDEInterface.prototype.ata_read_sectors = function(cmd)
{
    var is_lba48 = cmd === ATA_CMD_READ_SECTORS_EXT || cmd === ATA_CMD_READ_MULTIPLE;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var is_single = cmd === ATA_CMD_READ_SECTORS || cmd === ATA_CMD_READ_SECTORS_EXT;

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    if(LOG_DETAILS & LOG_DETAIL_RW)
    {
        dbg_log(this.name + ": ATA read cmd=" + h(cmd) +
                " mode=" + (this.is_lba ? "lba" : "chs") +
                " lba=" + h(lba) +
                " lbacount=" + h(count) +
                " bytecount=" + h(byte_count), LOG_DISK);
    }

    if(start + byte_count > this.buffer.byteLength)
    {
        dbg_log(this.name + ": ATA read: Outside of disk", LOG_DISK);
        this.ata_id_not_found();
    }
    else
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_BSY;
        this.report_read_start();

        this.read_buffer(start, byte_count, (data) =>
        {
            if(LOG_DETAILS & LOG_DETAIL_RW)
            {
                dbg_log(this.name + ": ata_read: Data arrived", LOG_DISK);
            }

            this.data_set(data);
            this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
            this.data_end = is_single ? this.sector_size : Math.min(byte_count, this.sectors_per_drq * this.sector_size);
            this.ata_advance(cmd, is_single ? 1 : Math.min(count, this.sectors_per_track));

            this.push_irq();
            this.report_read_end(byte_count);
        });
    }
};

IDEInterface.prototype.ata_read_sectors_dma = function(cmd)
{
    var is_lba48 = cmd === ATA_CMD_READ_DMA_EXT;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.name + ": ATA DMA read lba=" + h(lba) +
                " lbacount=" + h(count) +
                " bytecount=" + h(byte_count), LOG_DISK);
    }

    if(start + byte_count > this.buffer.byteLength)
    {
        dbg_log(this.name + ": ATA read: Outside of disk", LOG_DISK);
        this.ata_id_not_found();
        return;
    }

    this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
    this.channel.dma_status |= 1;
};

IDEInterface.prototype.do_ata_read_sectors_dma = function()
{
    var cmd = this.current_command;

    var is_lba48 = cmd === ATA_CMD_READ_DMA_EXT;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    dbg_assert(lba < this.buffer.byteLength);

    this.report_read_start();

    var orig_prdt_start = this.channel.prdt_addr;

    this.read_buffer(start, byte_count, (data) =>
    {
        if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
        {
            dbg_log(this.name + ": do_ata_read_sectors_dma: Data arrived", LOG_DISK);
        }
        dbg_assert(orig_prdt_start === this.channel.prdt_addr);
        try
        {
            for(const segment of this.dma_segments(byte_count))
            {
                this.cpu.write_blob_physical(data.subarray(segment.offset, segment.offset + segment.length), segment.address);
            }
        }
        catch(error)
        {
            if(!(error instanceof RangeError)) throw error;
            this.dma_abort();
            this.report_read_end(0);
            return;
        }

        this.ata_advance(this.current_command, count);
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
        this.channel.dma_status &= ~1;
        this.current_command = -1;

        this.report_read_end(byte_count);

        this.push_irq();
    });
};

IDEInterface.prototype.ata_write_sectors = function(cmd)
{
    var is_lba48 = cmd === ATA_CMD_WRITE_SECTORS_EXT || cmd === ATA_CMD_WRITE_MULTIPLE;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var is_single = cmd === ATA_CMD_WRITE_SECTORS || cmd === ATA_CMD_WRITE_SECTORS_EXT;

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    if(LOG_DETAILS & LOG_DETAIL_RW)
    {
        dbg_log(this.name + ": ATA write lba=" + h(lba) +
                " mode=" + (this.is_lba ? "lba" : "chs") +
                " lbacount=" + h(count) +
                " bytecount=" + h(byte_count), LOG_DISK);
    }

    if(start + byte_count > this.buffer.byteLength)
    {
        dbg_log(this.name + ": ATA write: Outside of disk", LOG_DISK);
        this.ata_id_not_found();
    }
    else
    {
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
        this.data_allocate_noclear(byte_count);
        this.data_end = is_single ? this.sector_size : Math.min(byte_count, this.sectors_per_drq * this.sector_size);
        this.write_dest = start;
    }
};

IDEInterface.prototype.ata_write_sectors_dma = function(cmd)
{
    var is_lba48 = cmd === ATA_CMD_WRITE_DMA_EXT;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
    {
        dbg_log(this.name + ": ATA DMA write lba=" + h(lba) +
                " lbacount=" + h(count) +
                " bytecount=" + h(byte_count), LOG_DISK);
    }

    if(start + byte_count > this.buffer.byteLength)
    {
        dbg_log(this.name + ": ATA DMA write: Outside of disk", LOG_DISK);
        this.ata_id_not_found();
        return;
    }

    this.status_reg = ATA_SR_DRDY|ATA_SR_DSC|ATA_SR_DRQ;
    this.channel.dma_status |= 1;
};

IDEInterface.prototype.do_ata_write_sectors_dma = function()
{
    var cmd = this.current_command;

    var is_lba48 = cmd === ATA_CMD_WRITE_DMA_EXT;
    var count = this.get_count(is_lba48);
    var lba = this.get_lba(is_lba48);

    var byte_count = count * this.sector_size;
    var start = lba * this.sector_size;

    const buffer = new Uint8Array(byte_count);
    try
    {
        for(const segment of this.dma_segments(byte_count))
        {
            buffer.set(this.cpu.read_blob_physical(segment.address, segment.length), segment.offset);
        }
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.dma_abort();
        return;
    }

    this.write_to_backend(start, buffer, () =>
    {
        if(LOG_DETAILS & LOG_DETAIL_RW_DMA)
        {
            dbg_log(this.name + ": DMA write completed", LOG_DISK);
        }
        this.ata_advance(this.current_command, count);
        this.status_reg = ATA_SR_DRDY|ATA_SR_DSC;
        this.push_irq();
        this.channel.dma_status &= ~1;
        this.current_command = -1;
    });

    this.report_write(byte_count);
};

IDEInterface.prototype.get_chs = function()
{
    var c = this.lba_mid_reg & 0xFF | this.lba_high_reg << 8 & 0xFF00;
    var h = this.head;
    var s = this.lba_low_reg & 0xFF;

    if(LOG_DETAILS & LOG_DETAIL_CHS)
    {
        dbg_log(this.name + ": get_chs: c=" + c + " h=" + h + " s=" + s, LOG_DISK);
    }

    return (c * this.head_count + h) * this.sectors_per_track + s - 1;
};

IDEInterface.prototype.get_lba28 = function()
{
    return this.lba_low_reg & 0xFF |
            this.lba_mid_reg << 8 & 0xFF00 |
            this.lba_high_reg << 16 & 0xFF0000 |
            (this.head & 0xF) << 24;
};

IDEInterface.prototype.get_lba48 = function()
{
    // Bits 24-47 are the previous (HOB) bytes of the three LBA registers;
    // bits 32-47 are added arithmetically (the result exceeds 32 bits).
    const low = (this.lba_low_reg & 0xFF |
            this.lba_mid_reg << 8 & 0xFF00 |
            this.lba_high_reg << 16 & 0xFF0000 |
            (this.lba_low_reg >> 8) << 24 & 0xFF000000) >>> 0;
    return low + ((this.lba_mid_reg >> 8 & 0xFF) | (this.lba_high_reg >> 8 & 0xFF) << 8) * 0x100000000;
};

IDEInterface.prototype.get_lba = function(is_lba48)
{
    if(is_lba48)
    {
        return this.get_lba48();
    }
    else if(this.is_lba)
    {
        return this.get_lba28();
    }
    else
    {
        return this.get_chs();
    }
};

IDEInterface.prototype.get_count = function(is_lba48)
{
    if(is_lba48)
    {
        var count = this.sector_count_reg;
        if(count === 0) count = 0x10000;
        return count;
    }
    else
    {
        var count = this.sector_count_reg & 0xFF;
        if(count === 0) count = 0x100;
        return count;
    }
};

IDEInterface.prototype.create_identify_packet = function()
{
    const cylinder_count = Math.min(16383, this.cylinder_count);
    const strcpy_be16 = (out_buffer, ofs16, len16, str) => {
        let ofs8 = ofs16 << 1;
        const len8 = len16 << 1;
        const end8 = ofs8 + len8;
        out_buffer.fill(32, ofs8, len8); // fill output buffer with ASCII whitespace
        for(let i_str = 0; i_str < str.length && ofs8 < end8; i_str++) {
            if(i_str & 1) {
                out_buffer[ofs8] = str.charCodeAt(i_str);
                ofs8 += 2;
            }
            else {
                out_buffer[ofs8 + 1] = str.charCodeAt(i_str);
            }
        }
    };

    // Initialize array of 256 16-bit words (big-endian)
    // Best source for the lower 64 words of the memory layout used below:
    // - [ATA-retro]
    //   AT Attachment Interface for Disk Drives, Revision 4c
    //   https://dn790009.ca.archive.org/0/items/SCSISpecificationDocumentsATAATAPI/ATA_ATAPI/AT%20Attachment%20Interface%20for%20Disk%20Drives%20Revision%204c.pdf
    // For the words above 64 see [ATA-6] Table 27, [ATA8-ACS] 7.12 and 7.13.
    //
    // dead link: http://bochs.sourceforge.net/cgi-bin/lxr/source/iodev/harddrv.cc#L2821

    // most significant bit indicates ATAPI CD-ROM device
    const general_cfg = this.is_atapi ? 0x8540 : 0x0040;
    // multiword DMA transfer mode, meaning of 0x0407:
    // - 0x0007: Multiword DMA modes 2, 1 and 0 are supported
    // - 0x0400: Multiword DMA mode 2 is selected
    const multiword_dma_mode = this.current_command === ATA_CMD_PACKET ? 0 : 0x0407;
    // Major version number: bits 3/4/5/6 indicate support for ATA/ATAPI-3/4/5/6 (bits 0/1/2 are obsolete in [ATA-6])
    const major_version = 0x0000;   // device does not report version
    // capacity above the 28-bit limit is only reachable with 48-bit commands
    const lba28_count = Math.min(this.sector_count, 0x0FFFFFFF);
    const sector_count_high = Math.floor(this.sector_count / 0x100000000);
    // supported ATA:   NOP, FLUSH CACHE, FLUSH CACHE EXT, 48-bit addr
    // supported ATAPI: NOP, DEVICE RESET, PACKET and FLUSH CACHE
    // (a write-back disk: a volatile write cache, word 82 bit 5; enabled in
    // word 85 bit 5 unless SET FEATURES 82h turned it off)
    const write_cache = this.has_write_cache();
    const feat_82 = this.is_atapi ? 1 << 14 | 1 << 9 | 1 << 5 : 1 << 14 | (write_cache ? 1 << 5 : 0);
    const feat_85 = this.is_atapi ? feat_82 : 1 << 14 | (write_cache && this.write_cache_enabled ? 1 << 5 : 0);
    const feat_83 = this.is_atapi ? 1 << 14 | 1 << 12 : 1 << 14 | 1 << 13 | 1 << 12 | 1 << 10;
    const feat_84 = this.is_atapi ? 1 << 14 : 1 << 14;

    this.data.fill(0, 0, 512);
    this.data_set([
        // 0: General configuration
        general_cfg & 0xFF, general_cfg >> 8 & 0xFF,
        // 1: Number of cylinders
        cylinder_count & 0xFF, cylinder_count >> 8 & 0xFF,
        // 2: reserved
        0, 0,
        // 3: Number of heads
        this.head_count & 0xFF, this.head_count >> 8 & 0xFF,
        // 4: Number of unformatted bytes per track
        this.sectors_per_track / 512 & 0xFF, this.sectors_per_track / 512 >> 8 & 0xFF,
        // 5: Number of unformatted bytes per sector
        0, 512 >> 8,
        // 6: Number of sectors per track
        this.sectors_per_track & 0xFF, this.sectors_per_track >> 8 & 0xFF,
        // 7-9: Vendor-unique
        0, 0, 0, 0,  0, 0,
        // 10-19: Serial number (20 ASCII characters, filled below)
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,
        // 20: Buffer type
        3, 0,
        // 21: Buffer size in 512 byte increments
        0, 2,
        // 22: Number of ECC bytes avail on read/write long cmds
        4, 0,
        // 23-26: Firmware revision (8 ASCII characters, filled below)
        0, 0, 0, 0,  0, 0, 0, 0,
        // 27-46: Model number (40 ASCII characters, filled below)
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,  0, 0, 0, 0,
        // 47: Max. number of sectors per interrupt on read/write multiple commands (1st byte) and Vendor-unique (2nd)
        0x80, 0,
        // 48: Indicates whether can perform doubleword I/O (1st byte) [0: no, 1: yes]
        1, 0,
        // 49: Vendor-unique (1st byte) and Capabilities (2nd) [2: Only LBA, 3: LBA and DMA]
        0, 2,
        // 50: reserved
        0, 0,
        // 51: PIO data transfer cycle timing mode
        0, 2,
        // 52: DMA data transfer cycle timing mode
        0, 2,
        // 53: Indicates whether fields 54-58 are valid (1st byte) [0: no, 1: yes]
        7, 0,
        // 54: Number of current cylinders
        cylinder_count & 0xFF, cylinder_count >> 8 & 0xFF,
        // 55: Number of current heads
        this.head_count & 0xFF, this.head_count >> 8 & 0xFF,
        // 56: Number of current sectors per track
        this.sectors_per_track, 0,
        // 57-58: Current capacity in sectors
        this.sector_count & 0xFF, this.sector_count >> 8 & 0xFF,
        this.sector_count >> 16 & 0xFF, this.sector_count >> 24 & 0xFF,
        // 59:  Multiple sector setting
        0, 0,
        // 60-61: Total number of user addressable sectors (LBA mode only),
        // at most 0x0FFFFFFF (28-bit commands)
        lba28_count & 0xFF, lba28_count >> 8 & 0xFF,
        lba28_count >> 16 & 0xFF, lba28_count >> 24 & 0xFF,
        // 62: Single word DMA transfer mode
        0, 0,
        // 63: Multiword DMA transfer mode (DMA supported mode, DMA selected mode)
        multiword_dma_mode & 0xFF, multiword_dma_mode >> 8 & 0xFF,

        // 64: PIO modes supported
        0, 0,
        // 65-68: fields related to cycle-time
        30, 0, 30, 0, 30, 0, 30, 0,
        // 69-74: reserved
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0, 0, 0,
        // 75: Queue depth
        0, 0,
        // 76-79: reserved
        0, 0, 0, 0,  0, 0, 0, 0,
        // 80: Major version number
        major_version & 0xFF, major_version >> 8 & 0xFF,
        // 81: Minor version number
        0, 0,
        // 82: Command set supported
        feat_82 & 0xFF, feat_82 >> 8 & 0xFF,
        // 83: Command set supported
        feat_83 & 0xFF, feat_83 >> 8 & 0xFF,
        // 84: Command set/feature supported extension
        feat_84 & 0xFF, feat_84 >> 8 & 0xFF,
        // 85: Command set/feature enabled (of 82)
        feat_85 & 0xFF, feat_85 >> 8 & 0xFF,
        // 86: Command set/feature enabled (copy of 83)
        feat_83 & 0xFF, feat_83 >> 8 & 0xFF,
        // 87: Command set/feature default (copy of 84)
        feat_84 & 0xFF, feat_84 >> 8 & 0xFF,
        // 88: DMA related field
        0, 0,
        // 89: Time required for security erase unit completion
        0, 0,
        // 90: Time required for Enhanced security erase completion
        0, 0,
        // 91: Current advanced power management value
        0, 0,
        // 92: Master Password Revision Code
        0, 0,
        // 93: Hardware reset result
        1, 0x60,
        // 94: Acoustic management value
        0, 0,
        // 95-99: reserved
        0, 0, 0, 0,  0, 0, 0, 0,
        0, 0,
        // 100-103: Maximum user LBA for 48-bit Address feature set.
        this.sector_count & 0xFF, this.sector_count >> 8 & 0xFF,
        this.sector_count >> 16 & 0xFF, this.sector_count >> 24 & 0xFF,
        sector_count_high & 0xFF, sector_count_high >> 8 & 0xFF, 0, 0,
    ]);

    // (QEMU's with platform.qemu_compatible: Windows names a drive after them)
    const qemu = this.cpu.platform.qemu_compatible;
    // (padded with spaces, as QEMU's are: strcpy_be16 does not pad)
    // 10-19 serial number
    strcpy_be16(this.data, 10, 10, qemu ? ("QM0000" + (this.channel_nr * 2 + this.interface_nr + 1)).padEnd(20) : `8086-86${this.channel_nr}${this.interface_nr}`);
    // 23-26 firmware revision
    strcpy_be16(this.data, 23, 4, qemu ? "2.5+".padEnd(8) : "1.00");
    // 27-46 model number
    strcpy_be16(this.data, 27, 20, qemu ? (this.is_atapi ? "QEMU DVD-ROM" : "QEMU HARDDISK").padEnd(40) : this.is_atapi ? "v86 ATAPI CD-ROM" : "v86 ATA HD");

    if(this.channel.sata)
    {
        // A Serial ATA device ([ATA8-ACS] 7.12.7.38-41). Linux tells SATA
        // from PATA by words 80 (ATA-5 or later) and 93 (no cable detection).
        const word = (index, value) => { this.data[index << 1] = value & 0xFF; this.data[(index << 1) + 1] = value >> 8; };
        const read_word = index => this.data[index << 1] | this.data[(index << 1) + 1] << 8;
        // DMA is supported (the AHCI transport moves all data by its PRDT):
        // word 49 DMA, word 53 word 88 valid, PIO modes 3 and 4, UDMA 0-5
        // with mode 5 selected (as QEMU reports)
        word(49, read_word(49) | 1 << 8);
        word(53, read_word(53) | 1 << 2);
        word(64, 0x0003);
        word(88, 0x003F | 1 << 13);
        const queue_depth = this.is_atapi ? 0 : this.channel.ncq_depth;
        word(75, queue_depth ? queue_depth - 1 : 0);
        // Gen1 signaling speed, native command queuing, host-initiated
        // interface power management (partial and slumber)
        word(76, 1 << 1 | (queue_depth ? 1 << 8 : 0) | 1 << 9);
        if(queue_depth)
        {
            // general purpose logging (READ LOG EXT: NCQ error recovery)
            word(84, read_word(84) | 1 << 5);
            word(87, read_word(87) | 1 << 5);
        }
        word(77, 0);
        word(78, 0);
        word(79, 0);
        word(80, 0x0070); // ATA/ATAPI-4, -5 and -6
        word(93, 0);
    }

    if(!this.is_atapi && this.sector_size !== HD_SECTOR_SIZE)
    {
        // Logical sectors longer than 256 words ([ATA8-ACS] 7.12, words
        // 106 and 117-118): word 106 valid (bit 14) with bit 12, one
        // logical sector per physical one; words 117-118 the size in words.
        // The capacity (words 60-61, 100-103) counts these sectors.
        const words = this.sector_size >> 1;
        this.data[106 << 1] = 0;
        this.data[(106 << 1) + 1] = (1 << 14 | 1 << 12) >> 8;
        this.data[117 << 1] = words & 0xFF;
        this.data[(117 << 1) + 1] = words >> 8 & 0xFF;
        this.data[118 << 1] = words >> 16 & 0xFF;
        this.data[(118 << 1) + 1] = words >> 24 & 0xFF;
    }

    this.data_length = 512;
    this.data_end = 512;
};

IDEInterface.prototype.data_allocate = function(len)
{
    this.data_allocate_noclear(len);
    this.data32.fill(0, 0, len + 3 >> 2);
};

IDEInterface.prototype.data_allocate_noclear = function(len)
{
    if(this.data.length < len)
    {
        this.data = new Uint8Array(len + 3 & ~3);
        this.data16 = new Uint16Array(this.data.buffer);
        this.data32 = new Int32Array(this.data.buffer);
    }

    this.data_length = len;
    this.data_pointer = 0;
};

IDEInterface.prototype.data_set = function(data)
{
    this.data_allocate_noclear(data.length);
    this.data.set(data);
};

IDEInterface.prototype.report_read_start = function()
{
    this.bus.send("ide-read-start");
};

IDEInterface.prototype.report_read_end = function(byte_count)
{
    const sector_count = byte_count / this.sector_size | 0;
    this.bus.send("ide-read-end", [this.channel_nr, byte_count, sector_count]);
};

IDEInterface.prototype.report_write = function(byte_count)
{
    const sector_count = byte_count / this.sector_size | 0;
    this.bus.send("ide-write-end", [this.channel_nr, byte_count, sector_count]);
};

/**
 * Read from the disk image: callback(data), or, when the backend fails the
 * read (a second argument: docs/disk-image-formats-plan.md P0), on_error
 * (io_error without one). Neither runs for a read cancelled before.
 * @param {number} start
 * @param {number} length
 * @param {function(!Uint8Array)} callback
 * @param {function(!Error)=} on_error
 */
IDEInterface.prototype.read_buffer = function(start, length, callback, on_error)
{
    block_read(this, start, length, callback, on_error || (error =>
    {
        this.report_read_end(0);
        this.io_error(error);
    }));
};

/**
 * The disk image failed a read or write: the command ends with an error, as
 * QEMU's ide_rw_error (ABRT); a DMA transfer also sets the bus master's error
 * bit, an ATAPI command reports a medium error
 * @param {!Error} error
 */
IDEInterface.prototype.io_error = function(error)
{
    dbg_log(this.name + ": I/O error: " + error.message, LOG_DISK);
    if(this.is_atapi)
    {
        this.channel.dma_status &= ~1;
        this.atapi_check_condition_response(ATAPI_SK_MEDIUM_ERROR, ATAPI_ASC_UNRECOVERED_READ_ERROR);
        this.push_irq();
        return;
    }
    const cmd = this.current_command;
    if(cmd === ATA_CMD_READ_DMA || cmd === ATA_CMD_READ_DMA_EXT || cmd === ATA_CMD_WRITE_DMA || cmd === ATA_CMD_WRITE_DMA_EXT)
    {
        this.dma_abort();
    }
    else
    {
        this.ata_abort_command();
    }
};

IDEInterface.prototype.cancel_io_operations = function()
{
    block_cancel_reads(this);
};

/** The drive is gone (AHCI hot unplug): its requests held after an I/O error are dropped */
IDEInterface.prototype.drop_held_requests = function()
{
    block_drop_holds(this);
};

IDEInterface.prototype.get_state = function()
{
    var state = [];
    state[0] = this.sector_count_reg;
    state[1] = this.cylinder_count;
    state[2] = this.lba_high_reg;
    state[3] = this.lba_mid_reg;
    state[4] = this.data_pointer;
    state[5] = 0;
    state[6] = 0;
    state[7] = 0;
    state[8] = 0;
    state[9] = this.device_reg;
    state[10] = this.error_reg;
    state[11] = this.head;
    state[12] = this.head_count;
    state[13] = this.is_atapi;
    state[14] = this.is_lba;
    state[15] = this.features_reg;
    state[16] = this.data;
    state[17] = this.data_length;
    state[18] = this.lba_low_reg;
    state[19] = this.sector_count;
    state[20] = this.sector_size;
    state[21] = this.sectors_per_drq;
    state[22] = this.sectors_per_track;
    state[23] = this.status_reg;
    state[24] = this.write_dest;
    state[25] = this.current_command;
    state[26] = this.data_end;
    state[27] = this.current_atapi_command;
    state[28] = this.buffer;
    state[29] = this.write_cache_enabled;
    return state;
};

IDEInterface.prototype.set_state = function(state)
{
    // I/O of the machine before the restore must not reach the restored one
    this.cancel_io_operations();
    this.reset_epoch++;

    this.sector_count_reg = state[0];
    this.cylinder_count = state[1];
    this.lba_high_reg = state[2];
    this.lba_mid_reg = state[3];
    this.data_pointer = state[4];

    this.device_reg = state[9];
    this.error_reg = state[10];
    this.head = state[11];
    this.head_count = state[12];
    this.is_atapi = state[13];
    this.is_lba = state[14];
    this.features_reg = state[15];
    this.data = state[16];
    this.data_length = state[17];
    this.lba_low_reg = state[18];
    this.sector_count = state[19];
    this.sector_size = state[20];
    this.sectors_per_drq = state[21];
    this.sectors_per_track = state[22];
    this.status_reg = state[23];
    this.write_dest = state[24];
    this.current_command = state[25];

    this.data_end = state[26];
    this.current_atapi_command = state[27];

    this.data16 = new Uint16Array(this.data.buffer);
    this.data32 = new Int32Array(this.data.buffer);

    // (a snapshot's reference of a disk written back, or its changes in
    // memory: src/disk_writeback.js)
    this.buffer && restore_disk_state(this.buffer, state[28]);
    this.write_cache_enabled = state[29] !== false;

    this.drive_connected = this.is_atapi || this.buffer;
    this.medium_changed = MEDIUM_CHANGED_NONE;
};
                                                                                                                                                                                                                                                                                                  source/v64/src/image/disk_image.js                                                                  0000644 0000000 0000000 00000057437 00000000000 014207  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A hard disk from a disk image in a container format
// (docs/disk-image-formats-plan.md): the format's reader decodes the guest's
// sectors from the file (src/image/qcow2.js, ...), the guest's writes stay
// in memory (src/image/overlay.js), and the device sees the interface of the
// buffers of src/buffer.js (load, byteLength, get, set, get_and_cache,
// get_from_cache, get_state, set_state). byteLength is the disk's size as
// the guest sees it, not the file's; logical_sector_size the size of its
// sectors, 512 or 4096 bytes, which the controllers report and count in
// (the plan's appendix, 4K logical sectors).
//
// Callbacks: get's is fn(data) when it worked and fn(undefined, error) when
// not (the second argument: old buffers never pass one), set's is fn(error).

import { dbg_assert, dbg_log } from "../log.js";
import { LOG_DISK } from "../const.js";
import { DiskImageError } from "./source.js";
import { WriteOverlay, OVERLAY_BLOCK_SIZE } from "./overlay.js";

/** the data is in the file at host_offset (in extent.source, if it has one: a
 * file of several, VMDK) */
export const EXTENT_DATA = 0;
/** reads as zeros */
export const EXTENT_ZERO = 1;
/** not in this file: the parent's data, or zeros without a parent */
export const EXTENT_PARENT = 2;
/** in a compressed cluster at host_offset, host_length bytes */
export const EXTENT_COMPRESSED = 3;

/** a snapshot's disk state of a DiskImage: [DISK_IMAGE_STATE, version, identity, indices, chunks] */
export const DISK_IMAGE_STATE = "v86-disk-image";
const DISK_IMAGE_STATE_VERSION = 1;

// the most compressed clusters kept decompressed
const DECOMPRESSED_CACHE_SIZE = 8 * 1024 * 1024;

/**
 * A bigint, its type left open: the build's Closure Compiler (v20210601)
 * checks no bitwise operators on bigint
 * @param {number|string} value
 * @return {?}
 */
export function big(value)
{
    return BigInt(value);
}

/**
 * Read a big-endian or little-endian unsigned 64-bit field as a BigInt
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @param {boolean=} little_endian
 * @return {?} a bigint
 */
export function read_u64(bytes, offset, little_endian)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const high = view.getUint32(offset + (little_endian ? 4 : 0), little_endian);
    const low = view.getUint32(offset + (little_endian ? 0 : 4), little_endian);
    return big(high) << big(32) | big(low);
}

/**
 * A 64-bit field as a Number, checked to be a safe integer no larger than
 * `max`
 * @param {?} value a bigint
 * @param {string} what for the message
 * @param {number=} max
 * @return {number}
 */
export function to_number(value, what, max)
{
    if(value > big(max === undefined ? Number.MAX_SAFE_INTEGER : max))
    {
        throw new DiskImageError(what + " " + value + " is too large" +
            (max === undefined ? " (beyond 2^53)" : " (at most " + max + ")"), "unsupported");
    }
    return Number(value);
}

/**
 * The reader of an opened image file: the format's mapping from the guest's
 * offsets to its file (map), and the data read through it (read). A format
 * sets virtual_size, format and the metadata hashed for its identity in
 * open(), and may have a parent (another reader) for the parts it does not
 * have.
 */
export class ImageReader
{
    /**
     * @param {?} source an opened source (src/image/source.js)
     * @param {string} name for messages
     */
    constructor(source, name)
    {
        this.source = source;
        this.name = name;
        this.format = "";
        this.virtual_size = 0;
        /** @type {ImageReader} */
        this.parent = null;
        /** the metadata that identifies the image (hex SHA-256, set by open) */
        this.metadata_sha256 = "";
        /** what the image says about its parent (format specific), or null */
        this.parent_link = null;
        /** the descriptor's image_id: a version of the image its publisher gives */
        this.image_id = "";
        /**
         * The disk's logical sectors as the guest sees them: 512 bytes, or
         * the descriptor's logical_sector_size, the image's own or its
         * parent's (src/image/factory.js open_image)
         */
        this.logical_sector_size = 512;
        /** the logical sector size the format records (VHDX), 0 for formats without one */
        this.own_sector_size = 0;
        /** whether logical_sector_size was given (descriptor, image, parent), not the default */
        this.sector_size_given = false;
        /** @type {!Map<number, !Uint8Array>} host offset -> decompressed cluster, the most recently used last */
        this.decompressed = new Map();
        this.decompressed_bytes = 0;
        /** @type {!Map<number, !Array<function((!Uint8Array|undefined), (Error|undefined)=)>>} */
        this.decompressing = new Map();
        /** reads of the format's tables (L2 tables, block maps, ...), decompressions */
        this.stats = { table_reads: 0, table_hits: 0, decompressed: 0, decompress_hits: 0 };
    }

    /**
     * @param {function((Error|undefined))} callback
     */
    open(callback)
    {
        dbg_assert(false);
    }

    /**
     * The extents of [offset, offset + length), in order and covering it
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        dbg_assert(false);
    }

    /**
     * Check a parent against what this image says about it (parent_link):
     * format-specific identity rules, errors for a parent that is not this
     * image's
     * @param {!ImageReader} parent
     */
    check_parent(parent)
    {
    }

    /**
     * Decompress a compressed cluster (formats with compression)
     * @param {!Uint8Array} bytes
     * @param {!Object} extent
     * @return {!Uint8Array}
     */
    decompress(bytes, extent)
    {
        throw new DiskImageError(this.name + ": compressed data is not supported", "unsupported");
    }

    /**
     * What identifies this image (and its parents) in a snapshot
     * @return {!Object}
     */
    identity()
    {
        return {
            "format": this.format,
            "size": this.virtual_size,
            "file_size": this.source.byteLength,
            "metadata_sha256": this.metadata_sha256,
            "image_id": this.image_id,
            "parent": this.parent ? this.parent.identity() : null,
        };
    }

    /**
     * [offset, offset + length) as the guest sees it: a new array
     * @param {number} offset
     * @param {number} length
     * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    read(offset, length, callback, signal)
    {
        dbg_assert(offset >= 0 && length >= 0 && offset + length <= this.virtual_size);
        this.map(offset, length, (extents, error) =>
        {
            if(error)
            {
                callback(undefined, error);
                return;
            }
            const result = new Uint8Array(length);
            let pending = 1;
            let failed = false;
            const fail = error =>
            {
                if(failed) return;
                failed = true;
                callback(undefined, error);
            };
            const done = () =>
            {
                if(--pending === 0 && !failed) callback(result);
            };
            let position = 0;
            for(const extent of /** @type {!Array<!Object>} */ (extents))
            {
                const at = position;
                position += extent.length;
                if(failed) break;
                switch(extent.type)
                {
                    case EXTENT_DATA:
                    {
                        // (past the end of the file reads as zeros, as in QEMU:
                        // a cluster's last part may never have been written)
                        const source = extent.source || this.source;
                        const available = Math.min(extent.length, source.byteLength - extent.host_offset);
                        if(available <= 0) break;
                        pending++;
                        source.read(extent.host_offset, available, (data, error) =>
                        {
                            if(error) fail(error);
                            else
                            {
                                result.set(/** @type {!Uint8Array} */ (data), at);
                                done();
                            }
                        }, signal);
                        break;
                    }
                    case EXTENT_PARENT:
                    {
                        const parent = this.parent;
                        // (past a smaller parent's end: zeros)
                        const available = parent ? Math.min(extent.length, parent.virtual_size - (offset + at)) : 0;
                        if(available <= 0) break;
                        pending++;
                        parent.read(offset + at, available, (data, error) =>
                        {
                            if(error) fail(error);
                            else
                            {
                                result.set(/** @type {!Uint8Array} */ (data), at);
                                done();
                            }
                        }, signal);
                        break;
                    }
                    case EXTENT_COMPRESSED:
                        pending++;
                        this.read_compressed(extent, (cluster, error) =>
                        {
                            if(error) fail(error);
                            else
                            {
                                result.set(/** @type {!Uint8Array} */ (cluster).subarray(extent.cluster_start, extent.cluster_start + extent.length), at);
                                done();
                            }
                        }, signal);
                        break;
                    case EXTENT_ZERO:
                        break;
                    default:
                        dbg_assert(false);
                }
            }
            dbg_assert(failed || position === length);
            done();
        }, signal);
    }

    /**
     * Whether [offset, offset + length) reads as zeros by the image's
     * metadata alone (zero and unallocated extents, a parent's likewise):
     * false where it may have data. An export skips such parts without
     * reading them.
     * @param {number} offset
     * @param {number} length
     * @param {function(boolean, (Error|undefined)=)} callback
     */
    is_zero(offset, length, callback)
    {
        this.map(offset, length, (extents, error) =>
        {
            if(error)
            {
                callback(false, error);
                return;
            }
            let pending = 1, zero = true;
            const done = () =>
            {
                if(--pending === 0) callback(zero);
            };
            let position = 0;
            for(const extent of /** @type {!Array<!Object>} */ (extents))
            {
                const at = position;
                position += extent.length;
                if(extent.type === EXTENT_ZERO) continue;
                if(extent.type === EXTENT_PARENT)
                {
                    const parent = this.parent;
                    const available = parent ? Math.min(extent.length, parent.virtual_size - (offset + at)) : 0;
                    if(available <= 0) continue;
                    pending++;
                    parent.is_zero(offset + at, available, parent_zero =>
                    {
                        zero = zero && parent_zero;
                        done();
                    });
                    continue;
                }
                zero = false;
                break;
            }
            done();
        });
    }

    /**
     * A compressed cluster, decompressed (kept for the next reads of it)
     * @param {!Object} extent
     * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    read_compressed(extent, callback, signal)
    {
        // (formats of several files key their clusters themselves)
        const key = extent.key === undefined ? extent.host_offset : extent.key;
        const source = extent.source || this.source;
        const cached = this.decompressed.get(key);
        if(cached)
        {
            this.stats.decompress_hits++;
            this.decompressed.delete(key);
            this.decompressed.set(key, cached);
            callback(cached);
            return;
        }
        const waiting = this.decompressing.get(key);
        if(waiting)
        {
            waiting.push(callback);
            return;
        }
        const callbacks = [callback];
        this.decompressing.set(key, callbacks);
        const length = Math.min(extent.host_length, source.byteLength - extent.host_offset);
        const finish = (cluster, error) =>
        {
            this.decompressing.delete(key);
            for(const f of callbacks) f(cluster, error);
        };
        if(length <= 0)
        {
            finish(undefined, new DiskImageError(this.name + ": a compressed cluster at " + extent.host_offset +
                " is past the end of the file (" + source.byteLength + " bytes)", "corrupt"));
            return;
        }
        // (not cancelled with one reader's signal: others may wait for it)
        source.read(extent.host_offset, length, (bytes, error) =>
        {
            if(error)
            {
                finish(undefined, error);
                return;
            }
            let cluster;
            try
            {
                cluster = this.decompress(bytes, extent);
            }
            catch(e)
            {
                finish(undefined, e instanceof DiskImageError ? e : new DiskImageError(this.name +
                    ": the compressed cluster at " + extent.host_offset + " is invalid: " + e.message, "corrupt"));
                return;
            }
            this.stats.decompressed++;
            this.decompressed.set(key, cluster);
            this.decompressed_bytes += cluster.length;
            while(this.decompressed_bytes > DECOMPRESSED_CACHE_SIZE && this.decompressed.size > 1)
            {
                const oldest = this.decompressed.keys().next().value;
                this.decompressed_bytes -= this.decompressed.get(oldest).length;
                this.decompressed.delete(oldest);
            }
            finish(cluster, undefined);
        });
    }
}

/**
 * Add an extent to a list, merged with the one before it where they continue
 * each other
 * @param {!Array<!Object>} extents
 * @param {number} type
 * @param {number} length
 * @param {number=} host_offset
 * @param {?=} source the file, if not the reader's
 */
export function push_extent(extents, type, length, host_offset, source)
{
    const last = extents[extents.length - 1];
    if(last && last.type === type && (type === EXTENT_ZERO || type === EXTENT_PARENT ||
        type === EXTENT_DATA && last.host_offset + last.length === host_offset && last.source === source))
    {
        last.length += length;
        return;
    }
    extents.push({ type, length, host_offset: host_offset || 0, source });
}

/**
 * The device's side of a disk image: what src/ide.js (and AHCI's drives)
 * use of a buffer
 * @constructor
 * @param {string} name hda, hdb, ...
 * @param {function():!Promise<!ImageReader>} open opens the image (src/image/factory.js)
 * @param {{overlay_limit: (number|undefined)}=} options
 */
export function DiskImage(name, open, options)
{
    this.name = name;
    this.open_reader = open;
    this.overlay_limit = options && options.overlay_limit;
    /** @type {ImageReader} */
    this.reader = null;
    /** @type {WriteOverlay} */
    this.overlay = null;
    /** the guest's size of the disk, known once loaded */
    this.byteLength = 0;
    /** the guest's logical sectors (the controllers read it), known once loaded */
    this.logical_sector_size = 512;
    /** @type {Promise<void>} */
    this.loading = null;
    /** blocks of the image read with get_and_cache (the first sector, for the geometry) */
    this.block_cache = new Map();
    /** errors reported so far (each told once in the console) */
    this.errors = new Set();
    this.onload = undefined;
    this.onerror = undefined;
    this.onprogress = undefined;
}

/**
 * Open the image: onload, or onerror and a rejected promise
 * @return {!Promise<void>}
 */
DiskImage.prototype.load = function()
{
    if(!this.loading)
    {
        this.loading = this.open_reader().then(reader =>
        {
            this.reader = reader;
            this.byteLength = reader.virtual_size;
            this.logical_sector_size = reader.logical_sector_size;
            this.overlay = new WriteOverlay(reader.virtual_size, this.overlay_limit, this.name);
            dbg_log(this.name + ": " + reader.format + " image, " + reader.virtual_size + " bytes" +
                (reader.logical_sector_size !== 512 ? ", " + reader.logical_sector_size + "-byte sectors" : "") +
                (reader.parent ? ", with a parent" : ""), LOG_DISK);
            this.onload && this.onload(Object.create(null));
        }, error =>
        {
            this.onerror && this.onerror(error);
            throw error;
        });
    }
    return this.loading;
};

/**
 * @param {Error} error
 */
DiskImage.prototype.report_error = function(error)
{
    if(this.errors.has(error.message)) return;
    if(this.errors.size < 100) this.errors.add(error.message);
    console.error(error.message.startsWith(this.name) ? error.message : "Disk " + this.name + ": " + error.message);
};

/**
 * @param {number} start
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} fn
 * @param {{signal: (AbortSignal|undefined)}=} options
 */
DiskImage.prototype.get = function(start, length, fn, options)
{
    dbg_assert(this.reader, "disk image not loaded");
    dbg_assert(start >= 0 && start + length <= this.byteLength);
    const signal = options && options.signal;
    if(this.overlay.covers(start, length))
    {
        const result = new Uint8Array(length);
        this.overlay.apply(start, result);
        fn(result);
        return;
    }
    this.reader.read(start, length, (data, error) =>
    {
        if(signal && signal.aborted) return;
        if(error)
        {
            this.report_error(error);
            fn(undefined, error);
            return;
        }
        // (the guest's writes win, also those after the read began)
        this.overlay.apply(start, /** @type {!Uint8Array} */ (data));
        fn(data);
    }, signal);
};

/**
 * @param {number} start
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} fn
 * @param {{signal: (AbortSignal|undefined)}=} options
 */
DiskImage.prototype.get_and_cache = function(start, length, fn, options)
{
    this.get(start, length, (data, error) =>
    {
        if(data && start % OVERLAY_BLOCK_SIZE === 0 && length % OVERLAY_BLOCK_SIZE === 0)
        {
            for(let i = 0; i < length / OVERLAY_BLOCK_SIZE; i++)
            {
                const index = start / OVERLAY_BLOCK_SIZE + i;
                // (blocks written are in the overlay)
                if(!this.overlay.block(index))
                {
                    this.block_cache.set(index, data.slice(i * OVERLAY_BLOCK_SIZE, (i + 1) * OVERLAY_BLOCK_SIZE));
                }
            }
        }
        fn(data, error);
    }, options);
};

/**
 * The data, if it was written or read with get_and_cache: synchronous
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array|undefined}
 */
DiskImage.prototype.get_from_cache = function(start, length)
{
    if(start % OVERLAY_BLOCK_SIZE || length % OVERLAY_BLOCK_SIZE) return undefined;
    const result = new Uint8Array(length);
    for(let i = 0; i < length / OVERLAY_BLOCK_SIZE; i++)
    {
        const index = start / OVERLAY_BLOCK_SIZE + i;
        const block = this.overlay.block(index) || this.block_cache.get(index);
        if(!block) return undefined;
        result.set(block, i * OVERLAY_BLOCK_SIZE);
    }
    return result;
};

/**
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function((Error|undefined)=)} fn
 */
DiskImage.prototype.set = function(start, data, fn)
{
    dbg_assert(this.reader, "disk image not loaded");
    const error = this.overlay.write(start, data);
    if(error) this.report_error(error);
    fn(error);
};

/**
 * (the whole disk in one buffer: not for disk images, see export)
 * @param {function((!ArrayBuffer|undefined))} fn
 */
DiskImage.prototype.get_buffer = function(fn)
{
    fn(undefined);
};

/**
 * The identity of the image a snapshot's changes belong to
 * @return {!Object}
 */
DiskImage.prototype.identity = function()
{
    return this.reader.identity();
};

DiskImage.prototype.get_state = function()
{
    const state = [];
    state[0] = DISK_IMAGE_STATE;
    state[1] = DISK_IMAGE_STATE_VERSION;
    state[2] = JSON.stringify(this.identity());
    const [indices, chunks] = this.overlay.get_state();
    state[3] = indices;
    state[4] = chunks;
    return state;
};

/**
 * Check a snapshot's state of this disk before anything is restored: it
 * must be of the same image (format, size, metadata, parents)
 * @param {*} state
 */
DiskImage.prototype.check_state = function(state)
{
    if(!Array.isArray(state) || state[0] !== DISK_IMAGE_STATE)
    {
        throw new DiskImageError(state ?
            "The snapshot's disk " + this.name + " is a RAW image (or the snapshot is from an older v86), this machine's " +
            "is a " + this.reader.format + " image: its changes cannot be applied to it" :
            "The snapshot has no disk " + this.name + ", this machine has a " + this.reader.format + " image", "config");
    }
    if(state[1] !== DISK_IMAGE_STATE_VERSION)
    {
        throw new DiskImageError("The snapshot's disk " + this.name + " has a state of version " + state[1] +
            ", this v86 reads version " + DISK_IMAGE_STATE_VERSION, "config");
    }
    let saved;
    try
    {
        saved = JSON.parse(state[2]);
    }
    catch(e)
    {
        throw new DiskImageError("The snapshot's disk " + this.name + " has an invalid identity", "config");
    }
    const mismatch = identity_mismatch(saved, this.identity(), "");
    if(mismatch)
    {
        throw new DiskImageError("The snapshot's disk " + this.name + " is of another image (" + mismatch +
            "): its changes are not applied to this one", "config");
    }
    this.overlay.check_state(state[3], state[4]);
};

/**
 * @param {*} state
 */
DiskImage.prototype.set_state = function(state)
{
    this.check_state(state);
    this.overlay.set_state(state[3], state[4]);
};

/**
 * The first difference of two identities, or ""
 * @param {*} saved
 * @param {!Object} current
 * @param {string} path
 * @return {string}
 */
function identity_mismatch(saved, current, path)
{
    if(!saved || typeof saved !== "object") return path + "identity missing";
    for(const key of ["format", "size", "file_size", "metadata_sha256", "image_id"])
    {
        if(current[key] === undefined) continue;
        if(saved[key] !== current[key])
        {
            return path + key + " " + JSON.stringify(saved[key]) + " in the snapshot, " + JSON.stringify(current[key]) + " here";
        }
    }
    if(!!saved["parent"] !== !!current["parent"])
    {
        return path + (saved["parent"] ? "the snapshot's image has a parent, this one none" : "this image has a parent, the snapshot's none");
    }
    return current["parent"] ? identity_mismatch(saved["parent"], current["parent"], path + "parent: ") : "";
}

/**
 * Whether a snapshot's state of a disk is a DiskImage's
 * @param {*} state
 * @return {boolean}
 */
export function is_disk_image_state(state)
{
    return Array.isArray(state) && state[0] === DISK_IMAGE_STATE;
}
                                                                                                                                                                                                                                 source/v64/src/image/export.js                                                                      0000644 0000000 0000000 00000004354 00000000000 013422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Export of a hard disk as the guest sees it (docs/disk-image-formats-plan.md
// P2): a RAW stream of the disk's whole size, the image's data with the
// guest's writes, in order, with progress, cancellation and the writer's
// backpressure (write may return a promise). Any disk buffer: a disk image
// (src/image/disk_image.js) or one of src/buffer.js. The caller stops the
// machine and waits for its disk I/O first (v86.prototype.export_disk), so
// the stream is one view of the disk.

import { DiskImageError } from "./source.js";

// the most bytes in one chunk (STATE_STREAM_CHUNK_SIZE: the CPU Worker sends
// them to the page as they are)
export const EXPORT_CHUNK_SIZE = 1024 * 1024;

/**
 * @param {?} buffer the disk's buffer
 * @param {function(!Uint8Array):(Promise<*>|undefined)} write
 * @param {{progress: (function({loaded: number, total: number})|undefined),
 *          signal: (AbortSignal|undefined), chunk_size: (number|undefined)}=} options
 * @return {!Promise<number>} the size written
 */
export async function export_raw(buffer, write, options)
{
    if(!buffer) throw new DiskImageError("No disk", "config");
    const total = buffer.byteLength;
    const chunk_size = Math.max(512, Math.min(EXPORT_CHUNK_SIZE, options && options.chunk_size || EXPORT_CHUNK_SIZE) & ~511);
    const progress = options && options.progress;
    const signal = options && options.signal;
    progress && progress({ loaded: 0, total });
    for(let offset = 0; offset < total;)
    {
        if(signal && signal.aborted) throw new DiskImageError("The export was cancelled at " + offset + " of " + total + " bytes", "io");
        const length = Math.min(chunk_size, total - offset);
        const data = await new Promise((resolve, reject) =>
        {
            buffer.get(offset, length, (data, error) =>
            {
                if(error || !data) reject(error || new DiskImageError("The disk returned no data at " + offset, "io"));
                else resolve(data);
            });
        });
        // (a copy: the buffer's view may be of memory that changes, and the
        // writer may transfer what it gets)
        await write(data.slice());
        offset += length;
        progress && progress({ loaded: offset, total });
    }
    return total;
}
                                                                                                                                                                                                                                                                                    source/v64/src/image/factory.js                                                                     0000644 0000000 0000000 00000047302 00000000000 013550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Hard disk images by their descriptor (docs/disk-image-formats-plan.md P0):
// the options a disk's descriptor may have, the format from its signature
// and structure ("auto"), the source of its bytes and the format's reader.
// Without a format (or with "raw") a disk keeps the buffers of src/buffer.js.

import { DiskImageError, MemorySource, BlobSource, URLSource, PartsSource, CachedSource } from "./source.js";
import { DiskImage, ImageReader, EXTENT_DATA } from "./disk_image.js";
import { QCOW2Reader, QCOW2_MAGIC } from "./qcow2.js";
import { VHDReader } from "./vhd.js";
import { VDIReader } from "./vdi.js";
import { VMDKReader } from "./vmdk.js";
import { VHDXReader } from "./vhdx.js";
import { SliceSource, read_tar, read_ova } from "./ova.js";
import { load_file } from "../lib.js";
import { check_disk_policy } from "../disk_options.js";

/** the formats a hard disk's `format` may name */
export const DISK_IMAGE_FORMATS = ["raw", "qcow2", "vhd", "vpc", "vdi", "vmdk", "vhdx", "auto"];

/** formats recognised but not (yet) read, and where they are planned */
const FORMATS_LATER = {};

/** the logical sector sizes a hard disk may have (logical_sector_size) */
export const LOGICAL_SECTOR_SIZES = [512, 4096];

// how many parents a disk may have
export const MAX_CHAIN_DEPTH = 16;

/**
 * Check the image options of a descriptor: `format` and `disk_option`
 * @param {string} name hda, hdb, cdrom, ...
 * @param {*} file
 * @param {boolean} hard_disk whether the descriptor is a hard disk's
 * @return {string|undefined} the format, undefined for RAW in a buffer of src/buffer.js
 */
export function check_image_options(name, file, hard_disk)
{
    if(!file || typeof file !== "object") return undefined;
    const format = file.format;
    // (disk_option, disk_error, token: src/disk_options.js)
    check_disk_policy(name, file);
    // (logical sectors of 4096 bytes, for RAW disks too: the plan's appendix)
    const sector_size = file["logical_sector_size"];
    if(sector_size !== undefined)
    {
        if(!hard_disk)
        {
            throw new DiskImageError(name + ": logical_sector_size is for hard disks (hda, hdb, SATA drives, virtio_disks), not " + name, "config");
        }
        if(!LOGICAL_SECTOR_SIZES.includes(sector_size))
        {
            throw new DiskImageError(name + ": logical_sector_size " + JSON.stringify(sector_size) + " is not one of " +
                LOGICAL_SECTOR_SIZES.join(", "), "config");
        }
    }
    if(format === undefined || format === "raw") return undefined;
    if(typeof format !== "string")
    {
        throw new DiskImageError(name + ": format must be a string", "config");
    }
    if(!hard_disk)
    {
        throw new DiskImageError(name + ": format " + JSON.stringify(format) + " is for hard disks (hda, hdb, SATA drives, virtio_disks); " +
            name + " is read as it is", "config");
    }
    if(FORMATS_LATER[format])
    {
        throw new DiskImageError(name + ": the format " + format + " is not supported yet (docs/disk-image-formats-plan.md " +
            FORMATS_LATER[format] + ")", "unsupported");
    }
    if(!DISK_IMAGE_FORMATS.includes(format))
    {
        throw new DiskImageError(name + ": unknown format " + JSON.stringify(format) + " (one of " + DISK_IMAGE_FORMATS.join(", ") + ")", "config");
    }
    if(file.get || file.set || file.load)
    {
        throw new DiskImageError(name + ": format is for descriptors (url, buffer), not for a disk object of one's own", "config");
    }
    if(!file.url && !(file.buffer instanceof ArrayBuffer) && !(typeof Blob !== "undefined" && file.buffer instanceof Blob))
    {
        throw new DiskImageError(name + ": a disk image needs a url or a buffer (ArrayBuffer, File)", "config");
    }
    if(file.files !== undefined && (typeof file.files !== "object" || !file.files ||
        Object.values(file.files).some(f => !f || typeof f !== "object")))
    {
        throw new DiskImageError(name + ": files must map file names to descriptors (url, buffer)", "config");
    }
    if(file.archive_member !== undefined && typeof file.archive_member !== "string")
    {
        throw new DiskImageError(name + ": archive_member must be the name of a file in the archive", "config");
    }
    return format;
}

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @param {string} text
 * @return {boolean}
 */
function has_text(bytes, offset, text)
{
    if(offset < 0 || offset + text.length > bytes.length) return false;
    for(let i = 0; i < text.length; i++)
    {
        if(bytes[offset + i] !== text.charCodeAt(i)) return false;
    }
    return true;
}

/**
 * The format of an image from its first bytes and its last 512: a format
 * reader decides, or the name of one v86 does not read, or "" (RAW has no
 * signature)
 * @param {!Uint8Array} head
 * @param {!Uint8Array} tail
 * @return {string}
 */
export function detect_format(head, tail)
{
    const u32 = offset => (head[offset] << 24 | head[offset + 1] << 16 | head[offset + 2] << 8 | head[offset + 3]) >>> 0;
    if(head.length >= 8 && u32(0) === QCOW2_MAGIC)
    {
        const version = u32(4);
        return version === 1 ? "qcow" : "qcow2";
    }
    if(has_text(head, 0, "QED\0")) return "qed";
    if(has_text(head, 0, "vhdxfile")) return "vhdx";
    if(has_text(head, 0, "conectix") || has_text(tail, tail.length - 512, "conectix") ||
        has_text(tail, tail.length - 511, "conectix"))
    {
        return "vhd";
    }
    if(head.length >= 0x44 && (head[0x40] | head[0x41] << 8 | head[0x42] << 16 | head[0x43] << 24) >>> 0 === 0xBEDA107F)
    {
        return "vdi";
    }
    if(has_text(head, 0, "KDMV") || has_text(head, 0, "# Disk DescriptorFile")) return "vmdk";
    if(has_text(head, 0, "COWD")) return "vmdk-cowd";
    if(has_text(head, 0, "WithoutFreeSpace") || has_text(head, 0, "WithouFreSpacExt")) return "parallels";
    if(has_text(head, 0x8001, "CD001")) return "iso";
    return "";
}

/**
 * A raw image as a reader (a parent of another image)
 */
export class RawReader extends ImageReader
{
    constructor(source, name)
    {
        super(source, name);
        this.format = "raw";
    }

    /** @param {function((Error|undefined))} callback */
    open(callback)
    {
        this.virtual_size = this.source.byteLength;
        // (a RAW image has no metadata: it is identified by its size and,
        // like any image, an image_id)
        this.metadata_sha256 = "";
        callback(undefined);
    }

    map(offset, length, callback, signal)
    {
        callback([{ type: EXTENT_DATA, length, host_offset: offset }]);
    }
}

/**
 * A name for messages: the disk and its file
 * @param {string} name
 * @param {!Object} file
 * @return {string}
 */
function display_name(name, file)
{
    const path = file.url || file.buffer && file.buffer.name;
    return path ? name + " (" + String(path).replace(/^.*\//, "") + ")" : name;
}

/**
 * The source of an image file's bytes
 * @param {string} name
 * @param {!Object} file
 * @param {!Object} settings
 * @return {!Promise<?>}
 */
export async function open_source(name, file, settings)
{
    if(settings.open_source) return settings.open_source(name, file);
    let source;
    if(file.buffer instanceof ArrayBuffer)
    {
        source = new MemorySource(new Uint8Array(file.buffer), name);
    }
    else if(typeof Blob !== "undefined" && file.buffer instanceof Blob)
    {
        source = new BlobSource(file.buffer, name);
    }
    else if(file.url && !file.async)
    {
        // downloaded whole, as RAW disks with async: false
        const bytes = await new Promise((resolve, reject) =>
        {
            load_file(file.url, {
                done: result => resolve(new Uint8Array(result)),
                error: status => reject(new DiskImageError(name + ": loading " + file.url + " failed (" + status + ")", "io")),
                progress: settings.progress && (e => settings.progress(file.url, e)),
            });
        });
        let data = bytes;
        if(file.url.endsWith(".zst"))
        {
            if(!file.size || !settings.zstd_decompress)
            {
                throw new DiskImageError(name + ": a compressed (.zst) image needs its size", "config");
            }
            data = new Uint8Array(settings.zstd_decompress(file.size, bytes));
        }
        source = new MemorySource(data, name);
    }
    else if(file.url && file.use_parts)
    {
        source = new CachedSource(new PartsSource(file.url, file.size, file.fixed_chunk_size, false,
            settings.zstd_decompress_worker, name), file.fixed_chunk_size);
    }
    else if(file.url)
    {
        source = new CachedSource(new URLSource(file.url, file.size, name), file.fixed_chunk_size);
    }
    else
    {
        throw new DiskImageError(name + ": no url or buffer", "config");
    }
    await new Promise((resolve, reject) => source.open(error => error ? reject(error) : resolve()));
    if(file.archive_member)
    {
        // a file in a TAR archive (an OVA)
        const member = (await read_tar(source)).find(m => m.name === file.archive_member);
        if(!member) throw new DiskImageError(name + ": the archive has no file " + JSON.stringify(file.archive_member), "config");
        return new SliceSource(source, member.offset, member.size, name + " " + file.archive_member);
    }
    return source;
}

/**
 * The first and last bytes of a source, for detect_format
 * @param {?} source
 * @return {!Promise<!Array<!Uint8Array>>}
 */
function read_ends(source)
{
    const read = (offset, length) => new Promise((resolve, reject) =>
        source.read(offset, length, (data, error) => error ? reject(error) : resolve(data)));
    const size = source.byteLength;
    const head_length = Math.min(size, 0x10000);
    return Promise.all([read(0, head_length), size >= 512 ? read(size - 512, 512) : Promise.resolve(new Uint8Array(0))]);
}

/** the readers by format */
const READERS = {
    "qcow2": QCOW2Reader,
    "vhd": VHDReader,
    "vdi": VDIReader,
    "vmdk": VMDKReader,
    "vhdx": VHDXReader,
};

/**
 * The source of a file an image's descriptor names (VMDK extents): from the
 * descriptor's files (by the name, or the name without a directory), or,
 * for an image in an archive, the archive's file of that name
 * @param {string} label
 * @param {!Object} file the image's descriptor
 * @param {string} extent the name in the image's descriptor
 * @param {!Object} settings
 * @return {!Promise<?>}
 */
async function extent_source(label, file, extent, settings)
{
    const base = name => name.replace(/^.*[\\/]/, "");
    const files = file.files || {};
    const given = files[extent] || Object.keys(files).filter(name => base(name) === base(extent)).map(name => files[name])[0];
    if(given) return open_source(label + " " + base(extent), given, settings);
    if(file.archive_member)
    {
        const directory = file.archive_member.replace(/[^\/]*$/, "");
        return open_source(label + " " + base(extent), { url: file.url, buffer: file.buffer, async: file.async, size: file.size,
            archive_member: directory + extent }, settings);
    }
    throw new DiskImageError(label + ": the image is in several files, and " + JSON.stringify(extent) +
        " is not given: name it in files", "config");
}

/**
 * Whether a descriptor is one of `chain` (the same object, URL or buffer)
 * @param {!Object} file
 * @param {!Array<!Object>} chain
 * @return {boolean}
 */
function in_chain(file, chain)
{
    return chain.some(other => other === file || file.url && other.url === file.url ||
        file.buffer && other.buffer === file.buffer);
}

/**
 * The formats QEMU names in a QCOW2 image's backing format, as v86's
 * @param {string} name
 * @return {string}
 */
function format_name(name)
{
    return name === "vpc" ? "vhd" : name === "file" ? "raw" : name;
}

/**
 * Open an image file and its parents: a parent is given by the caller
 * (backing), never loaded by the name an image has for it; a missing parent
 * is an error, not zeros (docs/disk-image-formats-plan.md P2)
 * @param {string} name
 * @param {!Object} file
 * @param {!Object} settings
 * @param {number=} depth
 * @param {!Array<!Object>=} chain the descriptors of the children
 * @return {!Promise<!ImageReader>}
 */
export async function open_image(name, file, settings, depth = 0, chain = [])
{
    const label = display_name(name, file);
    if(depth > MAX_CHAIN_DEPTH)
    {
        throw new DiskImageError(label + ": more than " + MAX_CHAIN_DEPTH + " parent images", "config");
    }
    if(in_chain(file, chain))
    {
        throw new DiskImageError(label + ": the chain of parents is circular (an image is its own parent)", "config");
    }
    const source = await open_source(label, file, settings);
    const [head, tail] = await read_ends(source);
    const detected = detect_format(head, tail);
    // ("vpc": QEMU's name of VHD)
    let format = format_name(file.format || "auto");
    if(format === "auto")
    {
        if(!detected)
        {
            throw new DiskImageError(label + ": the format could not be determined (RAW has no signature): give the " +
                "format (\"raw\" for a RAW image)", "config");
        }
        format = detected;
    }
    else if(format !== "raw" && detected !== format)
    {
        throw new DiskImageError(label + ": not a " + format + " image" + (detected ? " (it looks like " + detected + ")" : ""), "config");
    }
    if(format === "iso")
    {
        throw new DiskImageError(label + ": an ISO 9660 image, for a CD drive (cdrom), not a hard disk", "config");
    }
    const Reader = format === "raw" ? RawReader : READERS[format];
    if(!Reader)
    {
        throw new DiskImageError(label + ": the format " + format + " is not supported" +
            (FORMATS_LATER[format] ? " yet (docs/disk-image-formats-plan.md " + FORMATS_LATER[format] + ")" : ""), "unsupported");
    }
    const reader = new Reader(source, label, Object.assign({}, settings,
        { open_extent_source: extent => extent_source(label, file, extent, settings) }));
    await new Promise((resolve, reject) => reader.open(error => error ? reject(error) : resolve()));
    reader.image_id = file.image_id || "";

    const link = reader.parent_link;
    const backing = file.backing;
    if(link && !backing)
    {
        throw new DiskImageError(label + ": the image's data continues in a parent image (" + JSON.stringify(link) +
            "): give it as backing (a missing parent is not read as zeros)", "config");
    }
    if(!link && backing)
    {
        throw new DiskImageError(label + ": backing is given, but the image has no parent", "config");
    }
    if(link)
    {
        if(typeof backing !== "object") throw new DiskImageError(label + ": backing must be a descriptor (url, buffer)", "config");
        // the parent's format: the one given, or the one the image names
        const named = format_name(link["backing_format"] || "");
        const given = backing.format && backing.format !== "auto" ? backing.format : "";
        if(named && given && named !== given)
        {
            throw new DiskImageError(label + ": the image names its parent's format " + named + ", backing is given as " + given, "config");
        }
        const parent_file = Object.assign({}, backing, { format: given || named || "auto" });
        const parent = await open_image(name + " parent", parent_file, settings, depth + 1, chain.concat([file]));
        reader.check_parent(parent);
        reader.parent = parent;
    }
    set_reader_sector_size(label, reader, file);
    return reader;
}

/**
 * The logical sector size of an opened image: the descriptor's
 * (logical_sector_size), the image's own (VHDX) or its parent's, which must
 * agree where several give one; 512 bytes where none does. The disk's size
 * must be a multiple of a size given.
 * @param {string} label
 * @param {!ImageReader} reader
 * @param {!Object} file
 */
function set_reader_sector_size(label, reader, file)
{
    const sizes = [];
    const given = file["logical_sector_size"];
    if(given !== undefined)
    {
        // (a parent's descriptor, backing, is not checked by check_image_options)
        if(!LOGICAL_SECTOR_SIZES.includes(given))
        {
            throw new DiskImageError(label + ": logical_sector_size " + JSON.stringify(given) + " is not one of " +
                LOGICAL_SECTOR_SIZES.join(", "), "config");
        }
        sizes.push([given, "logical_sector_size"]);
    }
    if(reader.own_sector_size) sizes.push([reader.own_sector_size, "the image's"]);
    if(reader.parent && reader.parent.sector_size_given) sizes.push([reader.parent.logical_sector_size, "the parent image's"]);
    for(const [size, what] of sizes)
    {
        if(size !== sizes[0][0])
        {
            throw new DiskImageError(label + ": logical sectors of " + sizes[0][0] + " bytes (" + sizes[0][1] + "), but " + what +
                " are " + size + " bytes", "config");
        }
    }
    if(!sizes.length) return;
    reader.logical_sector_size = sizes[0][0];
    reader.sector_size_given = true;
    if(reader.virtual_size % reader.logical_sector_size)
    {
        throw new DiskImageError(label + ": the disk's size " + reader.virtual_size + " is not a multiple of its " +
            reader.logical_sector_size + "-byte sectors", "config");
    }
}

/**
 * A RAW disk's buffer (src/buffer.js, or a buffer object of one's own) with
 * the descriptor's logical_sector_size, which the controllers read from it:
 * its size must be a multiple
 * @param {string} name
 * @param {?} buffer loaded (its byteLength known)
 * @param {number|undefined} sector_size checked by check_image_options
 */
export function set_buffer_sector_size(name, buffer, sector_size)
{
    if(sector_size === undefined || !buffer) return;
    if(buffer.byteLength % sector_size)
    {
        throw new DiskImageError(name + ": the disk's size " + buffer.byteLength + " is not a multiple of its " +
            sector_size + "-byte sectors (logical_sector_size)", "config");
    }
    buffer.logical_sector_size = sector_size;
}

/**
 * An OVF package (an OVA archive): its disks as descriptors (the archive's,
 * with archive_member), the hardware as v86 options, notes for what v86
 * does not have (docs/disk-image-formats-plan.md P4)
 * @param {!Object} file the archive's descriptor (url, buffer)
 * @param {!Object} settings
 * @return {!Promise<!Object>}
 */
export async function import_ova(file, settings)
{
    const label = display_name("ova", file);
    const source = await open_source(label, Object.assign({}, file, { archive_member: undefined }), settings);
    const ova = await read_ova(source);
    const archive = { url: file.url, buffer: file.buffer, async: file.async === undefined ? true : file.async, size: file.size };
    const disks = ova.disks.map(disk => Object.assign({}, disk, {
        descriptor: disk.member && !disk.missing ? Object.assign({}, archive, { archive_member: disk.member, format: disk.format }) : null,
    }));
    const options = Object.assign({}, ova.options);
    const usable = disks.filter(d => d.descriptor);
    if(options["machine_type"] === "q35" || usable.length > 2)
    {
        options["machine_type"] = "q35";
    }
    if(usable[0]) options["hda"] = usable[0].descriptor;
    if(usable[1]) options["hdb"] = usable[1].descriptor;
    if(usable.length > 2)
    {
        ova.notes.push("disks after the second: attach them with attach_sata_drive (ports 3-5) after the start");
    }
    return { "ovf": ova.ovf, "files": ova.members.map(m => m.name), "disks": disks, "options": options, "notes": ova.notes };
}

/**
 * A hard disk from a descriptor with a format (check_image_options)
 * @param {string} name hda, hdb, sata<port>
 * @param {!Object} file
 * @param {!Object} settings zstd_decompress (synchronous), zstd_decompress_worker, progress
 * @return {!DiskImage}
 */
export function create_disk_image(name, file, settings)
{
    return new DiskImage(name, () => open_image(name, file, settings), {
        overlay_limit: file.overlay_limit,
    });
}
                                                                                                                                                                                                                                                                                                                              source/v64/src/image/ova.js                                                                         0000644 0000000 0000000 00000037156 00000000000 012674  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // OVF packages (docs/disk-image-formats-plan.md P4): an OVA is a TAR archive
// of an OVF descriptor (XML), its disks and other files. The importer reads
// the descriptor, the disks it names (each one opened by the disk image
// readers, inside the archive: a disk's descriptor gets archive_member) and
// the hardware it describes, mapped to v86's options where v86 has the
// hardware, with a note for each part it has not (architecture, firmware,
// controllers, devices). The disks come first; the options are a proposal.

import { DiskImageError } from "./source.js";

/**
 * A part of a source (a file in an archive)
 * @constructor
 * @param {?} source
 * @param {number} offset
 * @param {number} length
 * @param {string} name
 */
export function SliceSource(source, offset, length, name)
{
    this.inner = source;
    this.offset = offset;
    this.byteLength = length;
    this.name = name;
    this.sync = source.sync;
    this.stats = source.stats;
}

/** @param {function((Error|undefined))} callback */
SliceSource.prototype.open = function(callback)
{
    callback(undefined);
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
SliceSource.prototype.read = function(offset, length, callback, signal)
{
    if(offset < 0 || length < 0 || offset + length > this.byteLength)
    {
        throw new DiskImageError(this.name + ": read of " + length + " bytes at " + offset + " outside of the file (" +
            this.byteLength + " bytes)", "corrupt");
    }
    this.inner.read(this.offset + offset, length, callback, signal);
};

/**
 * @param {?} source
 * @param {number} offset
 * @param {number} length
 * @return {!Promise<!Uint8Array>}
 */
function read(source, offset, length)
{
    return new Promise((resolve, reject) => source.read(offset, length, (data, error) => error ? reject(error) : resolve(data)));
}

/**
 * A number of a TAR header: octal, or base-256 for large ones (GNU)
 * @param {!Uint8Array} bytes
 * @return {number}
 */
function tar_number(bytes)
{
    if(bytes[0] & 0x80)
    {
        let value = bytes[0] & 0x7F;
        for(let i = 1; i < bytes.length; i++) value = value * 256 + bytes[i];
        return value;
    }
    const text = String.fromCharCode(...bytes).replace(/\0.*$/, "").trim();
    return text ? parseInt(text, 8) : 0;
}

/**
 * @param {!Uint8Array} bytes
 * @return {string}
 */
function tar_string(bytes)
{
    const end = bytes.indexOf(0);
    return new TextDecoder().decode(end < 0 ? bytes : bytes.subarray(0, end));
}

/**
 * The files of a TAR archive (ustar, with GNU long names and PAX headers)
 * @param {?} source
 * @return {!Promise<!Array<{name: string, offset: number, size: number}>>}
 */
export async function read_tar(source)
{
    const files = [];
    let long_name = "";
    let pax = Object.create(null);
    for(let offset = 0; offset + 512 <= source.byteLength;)
    {
        const header = (await read(source, offset, 512)).slice();
        if(header.every(b => b === 0)) break;
        let sum = 0;
        for(let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
        if(sum !== tar_number(header.subarray(148, 156)))
        {
            throw new DiskImageError(source.name + ": the TAR header at " + offset + " has a wrong checksum", "corrupt");
        }
        const type = String.fromCharCode(header[156]);
        let size = tar_number(header.subarray(124, 136));
        if(pax["size"] !== undefined) size = +pax["size"];
        let name = tar_string(header.subarray(0, 100));
        if(String.fromCharCode(...header.subarray(257, 262)) === "ustar")
        {
            const prefix = tar_string(header.subarray(345, 500));
            if(prefix) name = prefix + "/" + name;
        }
        if(long_name) name = long_name;
        if(pax["path"] !== undefined) name = pax["path"];
        const data = offset + 512;
        if(!Number.isSafeInteger(size) || data + size > source.byteLength)
        {
            throw new DiskImageError(source.name + ": the TAR member " + JSON.stringify(name) + " (" + size +
                " bytes) runs past the end of the archive", "corrupt");
        }
        if(type === "L")
        {
            long_name = tar_string(await read(source, data, size));
        }
        else if(type === "x")
        {
            const text = new TextDecoder().decode(await read(source, data, size));
            for(const record of text.split("\n"))
            {
                const match = /^\d+ ([^=]+)=(.*)$/.exec(record);
                if(match) pax[match[1]] = match[2];
            }
        }
        else if(type === "g")
        {
            // (global PAX headers: nothing that matters here)
        }
        else
        {
            if(type === "0" || type === "\0" || type === "7")
            {
                files.push({ name: name.replace(/^\.\//, ""), offset: data, size });
            }
            long_name = "";
            pax = Object.create(null);
        }
        offset = data + Math.ceil(size / 512) * 512;
    }
    return files;
}

/**
 * A small XML parser for OVF descriptors: elements by their local name
 * (namespace prefixes dropped), attributes likewise, and text
 * @param {string} text
 * @return {!Object} the root element: {name, attributes, children, text}
 */
export function parse_xml(text)
{
    const root = { name: "", attributes: Object.create(null), children: [], text: "" };
    const stack = [root];
    const local = name => name.replace(/^[^:]*:/, "");
    const unescape = s => s.replace(/&(lt|gt|amp|quot|apos|#\d+|#x[0-9a-fA-F]+);/g, (m, e) =>
        e === "lt" ? "<" : e === "gt" ? ">" : e === "amp" ? "&" : e === "quot" ? "\"" : e === "apos" ? "'" :
        String.fromCodePoint(e[1] === "x" ? parseInt(e.substring(2), 16) : parseInt(e.substring(1), 10)));
    const tag = /<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!\[CDATA\[([\s\S]*?)\]\]>|<!DOCTYPE[^>]*>|<(\/?)([^\s>\/]+)((?:\s+[^\s=>\/]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;
    for(let match; (match = tag.exec(text));)
    {
        const top = stack[stack.length - 1];
        if(match[1] !== undefined)
        {
            top.text += match[1];
        }
        else if(match[6] !== undefined)
        {
            top.text += unescape(match[6]);
        }
        else if(match[3] !== undefined)
        {
            if(match[2])
            {
                if(stack.length === 1 || top.name !== local(match[3]))
                {
                    throw new DiskImageError("OVF: the XML closes " + match[3] + " where " + (top.name || "nothing") + " is open", "corrupt");
                }
                stack.pop();
                continue;
            }
            const element = { name: local(match[3]), attributes: Object.create(null), children: [], text: "" };
            for(const attribute of (match[4] || "").matchAll(/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g))
            {
                element.attributes[local(attribute[1])] = unescape(attribute[2] !== undefined ? attribute[2] : attribute[3]);
            }
            top.children.push(element);
            if(!match[5]) stack.push(element);
        }
    }
    if(stack.length !== 1) throw new DiskImageError("OVF: the XML ends with " + stack[stack.length - 1].name + " open", "corrupt");
    return root;
}

/**
 * @param {!Object} element
 * @param {string} name
 * @return {!Array<!Object>} the descendants of that name
 */
function find_all(element, name)
{
    const result = [];
    const visit = e =>
    {
        for(const child of e.children)
        {
            if(child.name === name) result.push(child);
            visit(child);
        }
    };
    visit(element);
    return result;
}

/**
 * @param {!Object} element
 * @param {string} name
 * @return {string|undefined} the text of a child
 */
function child_text(element, name)
{
    const child = element.children.find(c => c.name === name);
    return child ? child.text.trim() : undefined;
}

/**
 * Bytes from an OVF quantity and its units ("byte * 2^20", "MegaBytes", ...)
 * @param {number} value
 * @param {string|undefined} units
 * @return {number}
 */
export function ovf_bytes(value, units)
{
    if(!units) return value;
    const u = units.replace(/\s+/g, "").toLowerCase();
    const power = /^byte\*2\^(\d+)$/.exec(u);
    if(power) return value * 2 ** +power[1];
    const table = { "byte": 1, "bytes": 1, "kilobytes": 2 ** 10, "kb": 2 ** 10, "megabytes": 2 ** 20, "mb": 2 ** 20,
        "gigabytes": 2 ** 30, "gb": 2 ** 30, "terabytes": 2 ** 40 };
    if(table[u] !== undefined) return value * table[u];
    throw new DiskImageError("OVF: unknown allocation units " + JSON.stringify(units), "unsupported");
}

// OVF/CIM ResourceType (DMTF CIM_ResourceAllocationSettingData)
const RESOURCE = {
    PROCESSOR: 3, MEMORY: 4, IDE: 5, SCSI: 6, ETHERNET: 10, FLOPPY: 14, CD: 15, DVD: 16, DISK: 17,
    USB: 23, GRAPHICS: 24, SOUND: 35, SATA: 20,
};

/**
 * What an OVF descriptor says: its disks (the file each is in, its
 * controller), the hardware as v86 options, notes for what v86 does not have
 * @param {string} text the descriptor
 * @return {{disks: !Array<!Object>, options: !Object, notes: !Array<string>}}
 */
export function read_ovf(text)
{
    const root = parse_xml(text);
    const envelope = root.children.find(c => c.name === "Envelope");
    if(!envelope) throw new DiskImageError("OVF: no Envelope", "corrupt");
    const notes = [];
    const files = new Map(find_all(envelope, "References").flatMap(r => r.children.filter(c => c.name === "File"))
        .map(f => [f.attributes["id"], f.attributes]));
    const disks = [];
    for(const disk of find_all(envelope, "DiskSection").flatMap(s => s.children.filter(c => c.name === "Disk")))
    {
        const a = disk.attributes;
        const file = a["fileRef"] && files.get(a["fileRef"]);
        const capacity = ovf_bytes(+a["capacity"], a["capacityAllocationUnits"]);
        const format_uri = a["format"] || "";
        const format = /vmdk/i.test(format_uri) ? "vmdk" : /vhdx/i.test(format_uri) ? "vhdx" : /vhd/i.test(format_uri) ? "vhd" :
            /qcow/i.test(format_uri) ? "qcow2" : "auto";
        if(!file && a["fileRef"]) notes.push("disk " + a["diskId"] + ": its file " + a["fileRef"] + " is not in References");
        disks.push({
            id: a["diskId"], file: file ? file["href"] : "", format, format_uri, capacity, controller: "",
            compression: file && file["compression"] || "",
        });
    }

    const options = Object.create(null);
    const system = find_all(envelope, "VirtualSystem")[0];
    if(!system) throw new DiskImageError("OVF: no VirtualSystem", "corrupt");
    if(find_all(envelope, "VirtualSystem").length > 1) notes.push("several virtual systems: the first one is read");
    const os = find_all(system, "OperatingSystemSection")[0];
    if(os)
    {
        const description = child_text(os, "Description") || os.attributes["osType"] || "id " + os.attributes["id"];
        notes.push("the guest: " + description);
        if(/64/.test(os.attributes["osType"] || description)) options["cpu_type"] = "x86-64";
        if(/arm|aarch/i.test(os.attributes["osType"] || description))
        {
            notes.push("an ARM guest: v86 emulates x86 (and the arm64 virt machine, cpu_type \"arm64\", for Linux)");
        }
    }
    const hardware = find_all(system, "VirtualHardwareSection")[0];
    const items = hardware ? hardware.children.filter(c => c.name === "Item" || c.name === "StorageItem" || c.name === "EthernetPortItem") : [];
    const controllers = new Map();
    for(const item of items)
    {
        const type = +child_text(item, "ResourceType");
        const id = child_text(item, "InstanceID");
        const subtype = child_text(item, "ResourceSubType") || "";
        if(type === RESOURCE.IDE) controllers.set(id, "ide");
        else if(type === RESOURCE.SATA) controllers.set(id, "sata");
        else if(type === RESOURCE.SCSI) controllers.set(id, "scsi" + (subtype ? " (" + subtype + ")" : ""));
    }
    for(const item of items)
    {
        const type = +child_text(item, "ResourceType");
        const quantity = +(child_text(item, "VirtualQuantity") || 0);
        const subtype = child_text(item, "ResourceSubType") || "";
        const name = child_text(item, "ElementName") || "";
        if(type === RESOURCE.PROCESSOR)
        {
            options["cpu_cores"] = Math.max(1, quantity);
        }
        else if(type === RESOURCE.MEMORY)
        {
            options["memory_size"] = ovf_bytes(quantity, child_text(item, "AllocationUnits"));
        }
        else if(type === RESOURCE.DISK)
        {
            const resource = child_text(item, "HostResource") || "";
            const disk = disks.find(d => resource.endsWith("/" + d.id) || resource === d.id);
            if(disk) disk.controller = controllers.get(child_text(item, "Parent")) || "";
        }
        else if(type === RESOURCE.ETHERNET)
        {
            notes.push("network adapter " + (subtype || name) + ": v86 has an NE2000 and virtio-net (net_device), not this one");
        }
        else if(type === RESOURCE.SOUND)
        {
            notes.push("sound " + (subtype || name) + ": v86 has a Sound Blaster 16");
        }
        else if(type === RESOURCE.USB)
        {
            notes.push("USB " + (subtype || name) + ": v86 has no USB controller");
        }
    }
    for(const [, controller] of controllers)
    {
        if(controller.startsWith("scsi")) notes.push("a SCSI controller " + controller + ": v86 has IDE and AHCI (SATA): its disks go there");
    }
    if(disks.some(d => d.controller === "sata")) options["machine_type"] = "q35";
    // firmware: VMware's "firmware" config, VirtualBox's Firmware element
    const firmware = find_all(system, "Config").find(c => c.attributes["key"] === "firmware");
    const vbox_firmware = find_all(system, "Firmware")[0];
    if(firmware && firmware.attributes["value"] === "efi" || vbox_firmware && /efi/i.test(vbox_firmware.attributes["type"] || ""))
    {
        notes.push("the system boots with EFI: v86's firmware is a BIOS (SeaBIOS); it boots only if the disk can boot from a BIOS too");
    }
    if(disks.filter(d => d.file).length > 2 && options["machine_type"] !== "q35")
    {
        notes.push(disks.length + " disks: i440FX has hda and hdb (machine_type \"q35\" has six SATA ports)");
    }
    return { disks, options, notes };
}

/**
 * Read an OVA: its OVF descriptor and the disks in it
 * @param {?} source the archive
 * @return {!Promise<!Object>} ovf, members, disks, options, notes
 */
export async function read_ova(source)
{
    const members = await read_tar(source);
    const ovf_member = members.find(m => /\.ovf$/i.test(m.name));
    if(!ovf_member) throw new DiskImageError(source.name + ": no OVF descriptor (.ovf) in the archive", "corrupt");
    if(ovf_member.size > 16 * 1024 * 1024) throw new DiskImageError(source.name + ": the OVF descriptor is too large", "unsupported");
    const ovf = new TextDecoder().decode(await read(source, ovf_member.offset, ovf_member.size));
    const result = read_ovf(ovf);
    for(const disk of result.disks)
    {
        if(!disk.file) continue;
        const member = members.find(m => m.name === disk.file || m.name.replace(/^.*\//, "") === disk.file);
        if(!member)
        {
            result.notes.push("disk " + disk.id + ": its file " + disk.file + " is not in the archive");
            disk.missing = true;
            continue;
        }
        if(disk.compression)
        {
            result.notes.push("disk " + disk.id + ": its file is compressed (" + disk.compression + "): not supported");
            disk.missing = true;
        }
        disk.member = member.name;
        disk.offset = member.offset;
        disk.size = member.size;
    }
    return { ovf, members, ...result };
}
                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/image/overlay.js                                                                     0000644 0000000 0000000 00000022764 00000000000 013567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The guest's writes to a disk image (docs/disk-image-formats-plan.md P0):
// in memory, by the offset the guest sees (not the container file's), in
// 256-byte blocks (the smallest the emulated hardware writes: no write ever
// updates part of a block) packed into 16 MiB chunks, as the lazily loaded
// RAW disks of src/buffer.js keep them (the reasons are in docs/sata.md,
// "Disk backends"). Written blocks are never evicted: past the budget a
// write fails.

import { DiskImageError } from "./source.js";

export const OVERLAY_BLOCK_SIZE = 256;

// blocks in a chunk (16 MiB)
const CHUNK_BLOCKS = 0x10000;

/**
 * @constructor
 * @param {number} byte_length the disk's size
 * @param {number=} limit the most bytes written that are kept (Infinity)
 * @param {string=} name
 */
export function WriteOverlay(byte_length, limit, name)
{
    this.byte_length = byte_length;
    this.limit = limit === undefined ? Infinity : limit;
    this.name = name || "disk";
    /** @type {!Map<number, number>} block number -> slot in the chunks */
    this.blocks = new Map();
    /** @type {!Array<!Uint8Array>} */
    this.chunks = [];
    /** @type {!Array<!Uint8Array>} chunks allocated for the write in progress */
    this.spare_chunks = [];
}

/** @return {number} the bytes written so far */
WriteOverlay.prototype.size = function()
{
    return this.blocks.size * OVERLAY_BLOCK_SIZE;
};

/**
 * The data of a written block
 * @param {number} index
 * @return {!Uint8Array|undefined}
 */
WriteOverlay.prototype.block = function(index)
{
    const slot = this.blocks.get(index);
    if(slot === undefined) return undefined;
    const offset = slot % CHUNK_BLOCKS * OVERLAY_BLOCK_SIZE;
    return this.chunks[Math.floor(slot / CHUNK_BLOCKS)].subarray(offset, offset + OVERLAY_BLOCK_SIZE);
};

/**
 * Write `data` at `offset` (both multiples of the block size): nothing is
 * written if the budget does not allow all of it
 * @param {number} offset
 * @param {!Uint8Array} data
 * @return {Error|undefined}
 */
WriteOverlay.prototype.write = function(offset, data)
{
    const length = data.length;
    if(offset % OVERLAY_BLOCK_SIZE || length % OVERLAY_BLOCK_SIZE || offset < 0 || offset + length > this.byte_length)
    {
        return new DiskImageError(this.name + ": write of " + length + " bytes at " + offset + " is not in whole blocks of the disk", "io");
    }
    const first = offset / OVERLAY_BLOCK_SIZE, count = length / OVERLAY_BLOCK_SIZE;
    let added = 0;
    for(let i = 0; i < count; i++)
    {
        if(!this.blocks.has(first + i)) added++;
    }
    if((this.blocks.size + added) * OVERLAY_BLOCK_SIZE > this.limit)
    {
        const error = new DiskImageError(this.name + ": the guest's changes would exceed their memory budget (" +
            this.limit + " bytes): the write of " + length + " bytes at " + offset + " fails", "io");
        // (trying again does not help: src/block_backend.js)
        /** @type {?} */ (error)["retryable"] = false;
        return error;
    }
    // (the chunks the write needs first: a write that does not fit in
    // memory fails as a whole)
    const added_chunks = Math.ceil((this.blocks.size + added) / CHUNK_BLOCKS) - this.chunks.length;
    try
    {
        for(let i = 0; i < added_chunks; i++) this.spare_chunks.push(new Uint8Array(CHUNK_BLOCKS * OVERLAY_BLOCK_SIZE));
    }
    catch(e)
    {
        this.spare_chunks = [];
        return new DiskImageError(this.name + ": no memory for the guest's changes (" + this.size() +
            " bytes so far): the write of " + length + " bytes at " + offset + " fails (" + e.message + ")", "io");
    }
    for(let i = 0; i < count; i++)
    {
        this.write_block(first + i, data.subarray(i * OVERLAY_BLOCK_SIZE, (i + 1) * OVERLAY_BLOCK_SIZE));
    }
    this.spare_chunks = [];
    return undefined;
};

/**
 * @param {number} index
 * @param {!Uint8Array} data
 */
WriteOverlay.prototype.write_block = function(index, data)
{
    let slot = this.blocks.get(index);
    if(slot === undefined)
    {
        // (no block leaves the map: the next slot is its size)
        slot = this.blocks.size;
        if(slot % CHUNK_BLOCKS === 0)
        {
            this.chunks.push(this.spare_chunks.pop() || new Uint8Array(CHUNK_BLOCKS * OVERLAY_BLOCK_SIZE));
        }
        this.blocks.set(index, slot);
    }
    this.chunks[Math.floor(slot / CHUNK_BLOCKS)].set(data, slot % CHUNK_BLOCKS * OVERLAY_BLOCK_SIZE);
};

/**
 * Put the written blocks of [offset, offset + result.length) over the data
 * read from the image
 * @param {number} offset
 * @param {!Uint8Array} result
 */
WriteOverlay.prototype.apply = function(offset, result)
{
    if(this.blocks.size === 0) return;
    const first = Math.floor(offset / OVERLAY_BLOCK_SIZE);
    const last = Math.floor((offset + result.length - 1) / OVERLAY_BLOCK_SIZE);
    for(let index = first; index <= last; index++)
    {
        const block = this.block(index);
        if(!block) continue;
        const block_start = index * OVERLAY_BLOCK_SIZE;
        const from = Math.max(offset, block_start), to = Math.min(offset + result.length, block_start + OVERLAY_BLOCK_SIZE);
        result.set(block.subarray(from - block_start, to - block_start), from - offset);
    }
};

/**
 * Whether every block of [offset, offset + length) was written
 * @param {number} offset
 * @param {number} length
 * @return {boolean}
 */
WriteOverlay.prototype.covers = function(offset, length)
{
    if(this.blocks.size === 0 || length === 0) return false;
    const first = Math.floor(offset / OVERLAY_BLOCK_SIZE);
    const last = Math.floor((offset + length - 1) / OVERLAY_BLOCK_SIZE);
    for(let index = first; index <= last; index++)
    {
        if(!this.blocks.has(index)) return false;
    }
    return true;
};

/**
 * The written runs in disk order: [first block, slot, count], each run in
 * one chunk
 * @return {!Array<!Array<number>>}
 */
WriteOverlay.prototype.runs = function()
{
    const indices = Float64Array.from(this.blocks.keys()).sort();
    const runs = [];
    for(let i = 0; i < indices.length;)
    {
        const index = indices[i];
        const slot = this.blocks.get(index);
        let count = 1;
        while(i + count < indices.length && indices[i + count] === index + count &&
            this.blocks.get(index + count) === slot + count && (slot + count) % CHUNK_BLOCKS)
        {
            count++;
        }
        runs.push([index, slot, count]);
        i += count;
    }
    return runs;
};

/**
 * The data of `count` blocks from `slot` (a run)
 * @param {number} slot
 * @param {number} count
 * @return {!Uint8Array}
 */
WriteOverlay.prototype.slots = function(slot, count)
{
    const offset = slot % CHUNK_BLOCKS * OVERLAY_BLOCK_SIZE;
    return this.chunks[Math.floor(slot / CHUNK_BLOCKS)].subarray(offset, offset + count * OVERLAY_BLOCK_SIZE);
};

/**
 * The written blocks for a snapshot: their numbers in the order of their data
 * in the chunks, and the chunks (referenced, not copied: the machine is
 * stopped until it is saved), as AsyncXHRBuffer's
 * @return {!Array<*>}
 */
WriteOverlay.prototype.get_state = function()
{
    const count = this.blocks.size;
    const indices = new Float64Array(count);
    for(const [index, slot] of this.blocks)
    {
        indices[slot] = index;
    }
    return [indices, this.chunks.map((chunk, i) =>
        chunk.subarray(0, Math.min(CHUNK_BLOCKS, count - i * CHUNK_BLOCKS) * OVERLAY_BLOCK_SIZE))];
};

/**
 * Check a snapshot's written blocks against this disk
 * @param {*} indices
 * @param {*} chunks
 */
WriteOverlay.prototype.check_state = function(indices, chunks)
{
    const block_count = Math.ceil(this.byte_length / OVERLAY_BLOCK_SIZE);
    let total = 0;
    if(!Array.isArray(chunks)) throw new DiskImageError("Invalid disk snapshot: chunks", "config");
    for(const chunk of chunks)
    {
        if(!(chunk instanceof Uint8Array) || chunk.length % OVERLAY_BLOCK_SIZE)
        {
            throw new DiskImageError("Invalid disk snapshot: chunk", "config");
        }
        total += chunk.length / OVERLAY_BLOCK_SIZE;
    }
    if(!(indices instanceof Float64Array) || indices.length !== total ||
        indices.some(index => !Number.isInteger(index) || index < 0 || index >= block_count))
    {
        throw new DiskImageError("Invalid disk snapshot: block numbers", "config");
    }
    if(total * OVERLAY_BLOCK_SIZE > this.limit)
    {
        throw new DiskImageError(this.name + ": the snapshot's changes (" + total * OVERLAY_BLOCK_SIZE +
            " bytes) exceed the memory budget of this disk (" + this.limit + " bytes)", "config");
    }
};

/**
 * @param {!Float64Array} indices
 * @param {!Array<!Uint8Array>} chunks
 */
WriteOverlay.prototype.set_state = function(indices, chunks)
{
    this.check_state(indices, chunks);
    this.blocks.clear();
    this.chunks = [];
    let i = 0;
    for(const chunk of chunks)
    {
        const count = chunk.length / OVERLAY_BLOCK_SIZE;
        if(count === CHUNK_BLOCKS && i % CHUNK_BLOCKS === 0)
        {
            // a full chunk becomes this disk's as it is (a restore makes new
            // buffers for the snapshot's)
            this.chunks.push(chunk);
            for(const end = i + count; i < end; i++)
            {
                this.blocks.set(indices[i], i);
            }
            if(this.blocks.size !== i) throw new DiskImageError("Invalid disk snapshot: a block saved twice", "config");
        }
        else
        {
            for(let offset = 0; offset < chunk.length; offset += OVERLAY_BLOCK_SIZE)
            {
                this.write_block(indices[i++], chunk.subarray(offset, offset + OVERLAY_BLOCK_SIZE));
            }
        }
    }
};
            source/v64/src/image/qcow2.js                                                                       0000644 0000000 0000000 00000051613 00000000000 013134  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // QCOW2 images, versions 2 and 3 (docs/disk-image-formats-plan.md P1, P2;
// the format: https://www.qemu.org/docs/master/interop/qcow2.html): the
// active disk through the L1 and L2 tables, with data, unallocated, zero and
// compressed (deflate, zstd) clusters, and a parent (backing file) the
// caller gives. Internal snapshots may be there; only the active disk is
// read. Refused: encryption, external data files, extended L2 entries,
// unknown incompatible features, dirty or corrupt images.

import { DiskImageError } from "./source.js";
import { ImageReader, EXTENT_DATA, EXTENT_ZERO, EXTENT_PARENT, EXTENT_COMPRESSED, push_extent,
    to_number, big } from "./disk_image.js";
import { sha256_hex } from "./sha256.js";
import { inflate } from "../virt/inflate.js";

export const QCOW2_MAGIC = 0x514649FB; // "QFI\xfb"

const INCOMPAT_DIRTY = 1;
const INCOMPAT_CORRUPT = 2;
const INCOMPAT_DATA_FILE = 4;
const INCOMPAT_COMPRESSION = 8;
const INCOMPAT_EXTL2 = 16;
const INCOMPAT_KNOWN = 31;

const EXT_END = 0;
const EXT_BACKING_FORMAT = 0xE2792ACA;
const EXT_CRYPTO = 0x0537BE77;
const EXT_DATA_FILE = 0x44415441;

export const COMPRESSION_DEFLATE = 0;
export const COMPRESSION_ZSTD = 1;

const OFLAG_COPIED = big(1) << big(63);
const OFLAG_COMPRESSED = big(1) << big(62);
const OFLAG_ZERO = big(1);
const OFFSET_MASK = big("0x00FFFFFFFFFFFE00");
const L1E_RESERVED = big("0x7F000000000001FF");
const L2E_STD_RESERVED = big("0x3F000000000001FE");

// QEMU's limits (block/qcow2.h): QCOW_MAX_L1_SIZE, the largest cluster
const MAX_L1_BYTES = 32 * 1024 * 1024;
const MAX_CLUSTER_BITS = 21;
const MIN_CLUSTER_BITS = 9;

// L2 tables kept (bytes)
const L2_CACHE_SIZE = 8 * 1024 * 1024;

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
function u32(bytes, offset)
{
    return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
}

/**
 * A big-endian 64-bit field
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {?} a bigint (the build's Closure Compiler checks no bitwise
 *     operators on bigint)
 */
function be64(bytes, offset)
{
    return big(u32(bytes, offset)) << big(32) | big(u32(bytes, offset + 4));
}

/**
 * @param {!Uint8Array} bytes
 * @return {string}
 */
function utf8(bytes)
{
    return new TextDecoder().decode(bytes);
}

export class QCOW2Reader extends ImageReader
{
    /**
     * @param {?} source
     * @param {string} name
     * @param {{zstd_decompress: ((function(number, !Uint8Array): !Uint8Array)|undefined)}=} options
     */
    constructor(source, name, options)
    {
        super(source, name);
        this.format = "qcow2";
        this.zstd_decompress = options && options.zstd_decompress;
        this.version = 0;
        this.cluster_bits = 0;
        this.cluster_size = 0;
        this.l2_entries = 0;
        this.l1_size = 0;
        /** @type {!Uint8Array} */
        this.l1 = new Uint8Array(0);
        this.compression_type = COMPRESSION_DEFLATE;
        this.backing_file = "";
        this.backing_format = "";
        this.snapshots = 0;
        /** @type {!Map<number, !Uint8Array>} L2 table offset -> table, the most recently used last */
        this.l2_cache = new Map();
        /** @type {!Map<number, !Array<function((Error|undefined))>>} */
        this.l2_loading = new Map();
        this.max_l2_tables = 16;
    }

    /**
     * @param {string} what
     * @param {string=} kind
     * @return {!DiskImageError}
     */
    error(what, kind)
    {
        return new DiskImageError(this.name + ": qcow2: " + what, kind || "corrupt");
    }

    /**
     * Read [offset, offset + length) of the file, which must be there
     * @param {number} offset
     * @param {number} length
     * @param {string} what
     * @return {!Promise<!Uint8Array>}
     */
    read_metadata(offset, length, what)
    {
        return new Promise((resolve, reject) =>
        {
            if(offset + length > this.source.byteLength)
            {
                reject(this.error(what + " (" + length + " bytes at " + offset + ") is past the end of the file (" +
                    this.source.byteLength + " bytes): the file is truncated or corrupt"));
                return;
            }
            this.source.read(offset, length, (data, error) => error ? reject(error) : resolve(data));
        });
    }

    /**
     * @param {function((Error|undefined))} callback
     */
    open(callback)
    {
        this.parse().then(() => callback(undefined), error => callback(/** @type {!Error} */ (error)));
    }

    async parse()
    {
        const file_size = this.source.byteLength;
        if(file_size < 72) throw this.error("the file (" + file_size + " bytes) is too small for a header");
        let header = await this.read_metadata(0, Math.min(file_size, 4096), "the header");
        if(u32(header, 0) !== QCOW2_MAGIC) throw this.error("no QCOW2 signature");
        const version = this.version = u32(header, 4);
        if(version !== 2 && version !== 3)
        {
            throw this.error("version " + version + " is not supported (only 2 and 3)", "unsupported");
        }
        const cluster_bits = u32(header, 20);
        if(cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS)
        {
            throw this.error("cluster_bits " + cluster_bits + " outside of " + MIN_CLUSTER_BITS + "-" + MAX_CLUSTER_BITS);
        }
        const cluster_size = this.cluster_size = 2 ** cluster_bits;
        this.cluster_bits = cluster_bits;
        this.l2_entries = cluster_size / 8;
        this.max_l2_tables = Math.max(4, L2_CACHE_SIZE / cluster_size);

        const size = to_number(be64(header, 24), this.name + ": qcow2: the virtual size");
        if(size % 512)
        {
            throw this.error("the virtual size " + size + " is not a multiple of 512 bytes", "unsupported");
        }
        this.virtual_size = size;

        const crypt_method = u32(header, 32);
        if(crypt_method)
        {
            throw this.error("the image is encrypted (method " + crypt_method + "): not supported", "unsupported");
        }

        let header_length = 72, incompatible = big(0), refcount_order = 4;
        if(version === 3)
        {
            if(file_size < 104) throw this.error("the file is too small for a version 3 header");
            incompatible = be64(header, 72);
            refcount_order = u32(header, 96);
            header_length = u32(header, 100);
            if(header_length < 104 || header_length % 8)
            {
                throw this.error("header_length " + header_length + " is invalid (at least 104, a multiple of 8)");
            }
        }
        if(header_length > cluster_size) throw this.error("the header is larger than a cluster");
        if(header_length > header.length || cluster_size > header.length && file_size > header.length)
        {
            // the header with its extensions fills the first cluster at most
            header = await this.read_metadata(0, Math.min(file_size, cluster_size), "the first cluster");
        }
        if(refcount_order > 6) throw this.error("refcount_order " + refcount_order + " is invalid");

        const unknown = incompatible & ~big(INCOMPAT_KNOWN);
        if(unknown)
        {
            throw this.error("unknown incompatible features 0x" + unknown.toString(16) + ": not supported", "unsupported");
        }
        const flags = Number(incompatible);
        if(flags & INCOMPAT_DIRTY)
        {
            throw this.error("the image is dirty (not closed cleanly): repair it first (qemu-img check -r all)", "unsupported");
        }
        if(flags & INCOMPAT_CORRUPT)
        {
            throw this.error("the image is marked corrupt: repair it first (qemu-img check -r all)", "unsupported");
        }
        if(flags & INCOMPAT_DATA_FILE)
        {
            throw this.error("the image has an external data file: not supported", "unsupported");
        }
        if(flags & INCOMPAT_EXTL2)
        {
            throw this.error("the image has extended L2 entries (subclusters): not supported", "unsupported");
        }
        this.compression_type = COMPRESSION_DEFLATE;
        if(flags & INCOMPAT_COMPRESSION)
        {
            if(header_length < 105) throw this.error("the compression type bit is set, the header has no compression type");
            this.compression_type = header[104];
            if(this.compression_type !== COMPRESSION_DEFLATE && this.compression_type !== COMPRESSION_ZSTD)
            {
                throw this.error("compression type " + this.compression_type + " is not supported", "unsupported");
            }
        }
        else if(header_length > 104 && header[104] !== 0)
        {
            throw this.error("a compression type is given without its incompatible feature bit");
        }

        const backing_offset = to_number(be64(header, 8), this.name + ": qcow2: backing_file_offset");
        const backing_size = u32(header, 16);
        if(backing_offset && (backing_offset > cluster_size || backing_size === 0 ||
            backing_size > Math.min(1023, cluster_size - backing_offset) || backing_offset + backing_size > header.length))
        {
            throw this.error("the backing file name (" + backing_size + " bytes at " + backing_offset + ") is invalid");
        }

        // header extensions: from the end of the header to the backing file
        // name or the end of the first cluster, as QEMU reads them
        // (qcow2_read_extensions); unknown ones are for features that do not
        // matter for reading the active disk
        const extensions_end = backing_offset || Math.min(cluster_size, header.length);
        let position = header_length;
        while(position < extensions_end)
        {
            if(position + 8 > extensions_end) throw this.error("a header extension runs past the extension area");
            const type = u32(header, position), length = u32(header, position + 4);
            const data_start = position + 8;
            if(length > extensions_end - data_start)
            {
                throw this.error("header extension 0x" + type.toString(16) + " (" + length + " bytes) is too large");
            }
            if(type === EXT_END)
            {
                position = data_start;
                break;
            }
            const data = header.subarray(data_start, data_start + length);
            if(type === EXT_BACKING_FORMAT)
            {
                this.backing_format = utf8(data);
            }
            else if(type === EXT_CRYPTO)
            {
                throw this.error("the image has an encryption header: not supported", "unsupported");
            }
            else if(type === EXT_DATA_FILE)
            {
                throw this.error("the image names an external data file: not supported", "unsupported");
            }
            position = data_start + (length + 7 & ~7);
        }
        let metadata_end = Math.min(position, header.length);
        if(backing_offset)
        {
            this.backing_file = utf8(header.subarray(backing_offset, backing_offset + backing_size));
            metadata_end = Math.max(metadata_end, backing_offset + backing_size);
            this.parent_link = { "backing_file": this.backing_file, "backing_format": this.backing_format };
        }

        this.snapshots = u32(header, 60);

        // the L1 table: enough entries for the disk, inside the file
        this.l1_size = u32(header, 36);
        const l1_offset = to_number(be64(header, 40), this.name + ": qcow2: l1_table_offset");
        const per_l1_entry = cluster_size * this.l2_entries;
        const needed = Math.ceil(size / per_l1_entry);
        if(this.l1_size < needed)
        {
            throw this.error("the L1 table has " + this.l1_size + " entries, the size needs " + needed);
        }
        if(this.l1_size * 8 > MAX_L1_BYTES)
        {
            throw this.error("the L1 table (" + this.l1_size + " entries) is too large", "unsupported");
        }
        if(l1_offset % cluster_size)
        {
            throw this.error("the L1 table at " + l1_offset + " is not aligned to a cluster");
        }
        this.l1 = this.l1_size ?
            (await this.read_metadata(l1_offset, this.l1_size * 8, "the L1 table")).slice() :
            new Uint8Array(0);
        for(let i = 0; i < needed; i++)
        {
            const entry = be64(this.l1, i * 8);
            if(entry & L1E_RESERVED)
            {
                throw this.error("L1 entry " + i + " has reserved bits set (0x" + entry.toString(16) + ")");
            }
            const l2_offset = entry & OFFSET_MASK;
            if(l2_offset && Number(l2_offset) % cluster_size)
            {
                throw this.error("L1 entry " + i + ": the L2 table at 0x" + l2_offset.toString(16) + " is not aligned to a cluster");
            }
        }

        // the identity: the header with its extensions and the backing file
        // name, the L1 table
        this.metadata_sha256 = sha256_hex(header.subarray(0, metadata_end), this.l1);
    }

    /**
     * The L2 table at `offset` (cached)
     * @param {number} offset
     * @param {function((Error|undefined))} callback
     */
    load_l2(offset, callback)
    {
        const waiting = this.l2_loading.get(offset);
        if(waiting)
        {
            waiting.push(callback);
            return;
        }
        const callbacks = [callback];
        this.l2_loading.set(offset, callbacks);
        const finish = error =>
        {
            this.l2_loading.delete(offset);
            for(const f of callbacks) f(error);
        };
        if(offset + this.cluster_size > this.source.byteLength)
        {
            finish(this.error("the L2 table at " + offset + " is past the end of the file (" + this.source.byteLength +
                " bytes): the file is truncated or corrupt"));
            return;
        }
        this.stats.table_reads++;
        this.source.read(offset, this.cluster_size, (data, error) =>
        {
            if(error)
            {
                finish(error);
                return;
            }
            this.l2_cache.set(offset, data.slice());
            while(this.l2_cache.size > this.max_l2_tables)
            {
                this.l2_cache.delete(this.l2_cache.keys().next().value);
            }
            finish(undefined);
        });
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        const cluster_size = this.cluster_size;
        const first = Math.floor(offset / cluster_size), last = Math.floor((offset + length - 1) / cluster_size);
        const tables = this.l2_entries;
        // the L2 tables needed that are not cached
        const missing = new Set();
        for(let l1_index = Math.floor(first / tables); l1_index <= Math.floor(last / tables); l1_index++)
        {
            const l2_offset = Number(be64(this.l1, l1_index * 8) & OFFSET_MASK);
            if(l2_offset && !this.l2_cache.has(l2_offset)) missing.add(l2_offset);
        }
        if(missing.size === 0)
        {
            this.stats.table_hits++;
            this.build(offset, length, callback, signal);
            return;
        }
        let pending = missing.size, failed = false;
        for(const l2_offset of missing)
        {
            this.load_l2(l2_offset, error =>
            {
                if(failed) return;
                if(error)
                {
                    failed = true;
                    callback(undefined, error);
                    return;
                }
                if(--pending === 0) this.build(offset, length, callback, signal);
            });
        }
    }

    /**
     * The extents of [offset, offset + length) from the cached L2 tables
     * (one evicted meanwhile by other reads is loaded again)
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    build(offset, length, callback, signal)
    {
        const cluster_size = this.cluster_size, tables = this.l2_entries;
        const extents = [];
        const end = offset + length;
        for(let position = offset; position < end;)
        {
            const cluster = Math.floor(position / cluster_size);
            const in_cluster = position - cluster * cluster_size;
            const count = Math.min(cluster_size - in_cluster, end - position);
            const l1_index = Math.floor(cluster / tables);
            const l2_offset = Number(be64(this.l1, l1_index * 8) & OFFSET_MASK);
            if(!l2_offset)
            {
                push_extent(extents, EXTENT_PARENT, count);
                position += count;
                continue;
            }
            const table = this.l2_cache.get(l2_offset);
            if(!table)
            {
                this.map(position, end - position, (rest, error) =>
                {
                    if(error) callback(undefined, error);
                    else callback(extents.concat(rest));
                }, signal);
                return;
            }
            // the most recently used last
            this.l2_cache.delete(l2_offset);
            this.l2_cache.set(l2_offset, table);
            const l2_index = cluster % tables;
            const entry = be64(table, l2_index * 8);
            const where = () => "the L2 entry of guest offset " + cluster * cluster_size + " (table at " + l2_offset +
                ", entry " + l2_index + ", 0x" + entry.toString(16) + ")";

            if(entry & OFLAG_COMPRESSED)
            {
                // x = 62 - (cluster_bits - 8): the host offset below bit x,
                // the 512-byte sectors after the first above it
                const x = big(62 - (this.cluster_bits - 8));
                if(entry & OFLAG_COPIED)
                {
                    callback(undefined, this.error(where() + ": a compressed cluster with the copied flag"));
                    return;
                }
                const host = entry & ((big(1) << x) - big(1));
                if(host >> big(56))
                {
                    callback(undefined, this.error(where() + ": the compressed cluster's offset is beyond 2^56"));
                    return;
                }
                const sectors = Number((entry >> x) & ((big(1) << (big(62) - x)) - big(1))) + 1;
                const host_offset = Number(host);
                extents.push({ type: EXTENT_COMPRESSED, length: count, host_offset,
                    host_length: sectors * 512 - host_offset % 512, cluster_start: in_cluster });
            }
            else
            {
                if(entry & L2E_STD_RESERVED)
                {
                    callback(undefined, this.error(where() + ": reserved bits set"));
                    return;
                }
                const host = Number(entry & OFFSET_MASK);
                if(entry & OFLAG_ZERO)
                {
                    if(this.version < 3)
                    {
                        callback(undefined, this.error(where() + ": the zero flag in a version 2 image"));
                        return;
                    }
                    push_extent(extents, EXTENT_ZERO, count);
                }
                else if(!host)
                {
                    push_extent(extents, EXTENT_PARENT, count);
                }
                else
                {
                    if(host % cluster_size)
                    {
                        callback(undefined, this.error(where() + ": the data cluster is not aligned to a cluster"));
                        return;
                    }
                    push_extent(extents, EXTENT_DATA, count, host + in_cluster);
                }
            }
            position += count;
        }
        callback(extents);
    }

    /**
     * A compressed cluster: raw deflate (RFC 1951, no zlib header) or a
     * Zstandard frame, the data a whole cluster; the compressed bytes end in
     * a 512-byte sector, the rest of which is not the stream's (as QEMU's
     * qcow2_zlib_decompress and qcow2_zstd_decompress read them)
     * @param {!Uint8Array} bytes
     * @param {!Object} extent
     * @return {!Uint8Array}
     */
    decompress(bytes, extent)
    {
        const size = this.cluster_size;
        let output;
        if(this.compression_type === COMPRESSION_DEFLATE)
        {
            output = inflate(bytes, 0, size, size).output;
        }
        else
        {
            if(!this.zstd_decompress)
            {
                throw this.error("no Zstandard decompressor for the compressed clusters", "unsupported");
            }
            output = this.zstd_decompress(size, bytes);
        }
        if(output.length !== size)
        {
            throw this.error("the compressed cluster at " + extent.host_offset + " has " + output.length +
                " bytes, not a cluster (" + size + ")");
        }
        return output.buffer.byteLength === size ? output : output.slice();
    }
}
                                                                                                                     source/v64/src/image/qcow2_export.js                                                                0000644 0000000 0000000 00000023517 00000000000 014537  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Export of a hard disk as a new QCOW2 image (docs/disk-image-formats-plan.md
// P5): version 3, clusters of 64 KiB, 16-bit refcounts, no compression, no
// parent, the clusters that are all zeros left out. The stream is written
// in order, so the image's layout is decided first: a first pass over the
// disk finds the clusters with data, the second writes the header, the L1
// table, the refcount table and blocks, the L2 tables and the data.
// qemu-img check finds no errors in it (refcounts and copied flags
// consistent).

import { DiskImageError } from "./source.js";
import { big } from "./disk_image.js";

const CLUSTER_BITS = 16;
const CLUSTER_SIZE = 1 << CLUSTER_BITS;
const L2_ENTRIES = CLUSTER_SIZE / 8;
// 16-bit refcounts: entries in a refcount block
const REFCOUNTS_PER_BLOCK = CLUSTER_SIZE / 2;
const COPIED = big(1) << big(63);

// clusters read at once
const READ_CLUSTERS = 16;
// the parts of the disk checked for zeros by the image's metadata first
const SPAN = 256 * 1024 * 1024;

/**
 * @param {?} buffer
 * @param {number} offset
 * @param {number} length
 * @return {!Promise<!Uint8Array>}
 */
function get(buffer, offset, length)
{
    return new Promise((resolve, reject) => buffer.get(offset, length, (data, error) =>
        error || !data ? reject(error || new DiskImageError("The disk returned no data at " + offset, "io")) : resolve(data)));
}

/**
 * The layout of the image for the clusters with data
 * @param {number} size the disk's size
 * @param {!Uint8Array} allocated one byte per cluster: 1 with data
 * @return {!Object}
 */
export function qcow2_layout(size, allocated)
{
    const clusters = allocated.length;
    const l1_size = Math.ceil(clusters / L2_ENTRIES);
    const l1_clusters = Math.max(1, Math.ceil(l1_size * 8 / CLUSTER_SIZE));
    let l2_count = 0;
    const l2_index = new Int32Array(l1_size).fill(-1);
    for(let i = 0; i < l1_size; i++)
    {
        const start = i * L2_ENTRIES;
        for(let c = start; c < Math.min(clusters, start + L2_ENTRIES); c++)
        {
            if(allocated[c])
            {
                l2_index[i] = l2_count++;
                break;
            }
        }
    }
    let data_count = 0;
    for(let c = 0; c < clusters; c++) data_count += allocated[c];
    // the refcount table and blocks cover every cluster, theirs included
    let rb_count = 1, rt_clusters = 1;
    for(;;)
    {
        const total = 1 + l1_clusters + rt_clusters + rb_count + l2_count + data_count;
        const rb_needed = Math.ceil(total / REFCOUNTS_PER_BLOCK);
        const rt_needed = Math.max(1, Math.ceil(rb_needed * 8 / CLUSTER_SIZE));
        if(rb_needed <= rb_count && rt_needed <= rt_clusters) break;
        rb_count = Math.max(rb_count, rb_needed);
        rt_clusters = Math.max(rt_clusters, rt_needed);
    }
    const l1_offset = CLUSTER_SIZE;
    const rt_offset = l1_offset + l1_clusters * CLUSTER_SIZE;
    const rb_offset = rt_offset + rt_clusters * CLUSTER_SIZE;
    const l2_offset = rb_offset + rb_count * CLUSTER_SIZE;
    const data_offset = l2_offset + l2_count * CLUSTER_SIZE;
    const total = data_offset / CLUSTER_SIZE + data_count;
    return { size, clusters, l1_size, l1_clusters, l1_offset, rt_clusters, rt_offset, rb_count, rb_offset,
        l2_count, l2_index, l2_offset, data_count, data_offset, total, file_size: total * CLUSTER_SIZE };
}

/**
 * The header and the tables of the image, in the order of the file
 * @param {!Object} layout
 * @param {!Uint8Array} allocated
 * @return {!Uint8Array} everything up to the data
 */
export function qcow2_metadata(layout, allocated)
{
    const bytes = new Uint8Array(layout.data_offset);
    const view = new DataView(bytes.buffer);
    const u64 = (offset, value) =>
    {
        view.setUint32(offset, Number(value >> big(32)));
        view.setUint32(offset + 4, Number(value & big(0xFFFFFFFF)));
    };
    // the header (version 3, 104 bytes, then the end of the extensions)
    view.setUint32(0, 0x514649FB);
    view.setUint32(4, 3);
    view.setUint32(20, CLUSTER_BITS);
    u64(24, big(layout.size));
    view.setUint32(36, layout.l1_size);
    u64(40, big(layout.l1_offset));
    u64(48, big(layout.rt_offset));
    view.setUint32(56, layout.rt_clusters);
    view.setUint32(96, 4);
    view.setUint32(100, 104);
    // L1 and L2: the clusters with data in order
    let data_cluster = 0;
    for(let i = 0; i < layout.l1_size; i++)
    {
        const table = layout.l2_index[i];
        if(table < 0) continue;
        const table_offset = layout.l2_offset + table * CLUSTER_SIZE;
        u64(layout.l1_offset + i * 8, big(table_offset) | COPIED);
        const start = i * L2_ENTRIES;
        for(let c = start; c < Math.min(layout.clusters, start + L2_ENTRIES); c++)
        {
            if(!allocated[c]) continue;
            u64(table_offset + (c - start) * 8, big(layout.data_offset + data_cluster++ * CLUSTER_SIZE) | COPIED);
        }
    }
    // refcounts: 1 for every cluster of the file
    for(let b = 0; b < layout.rb_count; b++)
    {
        u64(layout.rt_offset + b * 8, big(layout.rb_offset + b * CLUSTER_SIZE));
    }
    for(let c = 0; c < layout.total; c++)
    {
        view.setUint16(layout.rb_offset + c * 2, 1);
    }
    return bytes;
}

/**
 * @param {?} buffer the disk's buffer
 * @param {function(!Uint8Array):(Promise<*>|undefined)} write
 * @param {{progress: (function({phase: string, loaded: number, total: number})|undefined),
 *          signal: (AbortSignal|undefined)}=} options
 * @return {!Promise<number>} the image's size
 */
export async function export_qcow2(buffer, write, options)
{
    const size = buffer.byteLength;
    if(size % 512) throw new DiskImageError("The disk's size " + size + " is not a multiple of 512 bytes", "unsupported");
    const progress = options && options.progress;
    const signal = options && options.signal;
    const check = () =>
    {
        if(signal && signal.aborted) throw new DiskImageError("The export was cancelled", "io");
    };
    const clusters = Math.ceil(size / CLUSTER_SIZE);
    const read_cluster_run = async first =>
    {
        const start = first * CLUSTER_SIZE;
        const length = Math.min(size - start, READ_CLUSTERS * CLUSTER_SIZE);
        return get(buffer, start, length);
    };

    // which clusters have data: the parts that read as zeros by a disk
    // image's metadata and have no guest writes are not read (a large
    // sparse disk), spans of 256 MiB first, then groups of READ_CLUSTERS
    const allocated = new Uint8Array(clusters);
    const group_size = READ_CLUSTERS * CLUSTER_SIZE;
    const guest_written = new Set();
    if(buffer.overlay)
    {
        for(const [first, , count] of buffer.overlay.runs())
        {
            const start = first * 256, end = start + count * 256;
            for(let g = Math.floor(start / group_size); g <= Math.floor((end - 1) / group_size); g++) guest_written.add(g);
        }
    }
    const zero = (offset, length) => !buffer.reader ? Promise.resolve(false) :
        new Promise(resolve => buffer.reader.is_zero(offset, length, (is_zero, error) => resolve(!error && is_zero)));
    const groups_per_span = SPAN / group_size;
    for(let span = 0; span * SPAN < size; span++)
    {
        check();
        const span_start = span * SPAN, span_length = Math.min(SPAN, size - span_start);
        let touched = false;
        for(let g = span * groups_per_span; g < (span + 1) * groups_per_span && !touched; g++) touched = guest_written.has(g);
        if(!touched && await zero(span_start, span_length)) continue;
        for(let g = span * groups_per_span; g * group_size < Math.min(size, span_start + SPAN); g++)
        {
            const c = g * READ_CLUSTERS;
            const group_start = g * group_size;
            if(!guest_written.has(g) && await zero(group_start, Math.min(group_size, size - group_start))) continue;
            check();
            const data = await read_cluster_run(c);
            for(let i = 0; i < READ_CLUSTERS && c + i < clusters; i++)
            {
                const part = data.subarray(i * CLUSTER_SIZE, (i + 1) * CLUSTER_SIZE);
                for(let j = 0; j < part.length; j++)
                {
                    if(part[j])
                    {
                        allocated[c + i] = 1;
                        break;
                    }
                }
            }
        }
        progress && progress({ phase: "scan", loaded: span_start + span_length, total: size });
    }
    const layout = qcow2_layout(size, allocated);
    const metadata = qcow2_metadata(layout, allocated);
    progress && progress({ phase: "write", loaded: 0, total: layout.file_size });
    for(let offset = 0; offset < metadata.length; offset += 1024 * 1024)
    {
        check();
        await write(metadata.slice(offset, offset + 1024 * 1024));
    }
    let written = metadata.length;
    for(let c = 0; c < clusters; c += READ_CLUSTERS)
    {
        let any = false;
        for(let i = 0; i < READ_CLUSTERS && c + i < clusters; i++) any = any || !!allocated[c + i];
        if(!any) continue;
        check();
        const data = await read_cluster_run(c);
        const parts = [];
        for(let i = 0; i < READ_CLUSTERS && c + i < clusters; i++)
        {
            if(!allocated[c + i]) continue;
            const cluster = new Uint8Array(CLUSTER_SIZE);
            cluster.set(data.subarray(i * CLUSTER_SIZE, (i + 1) * CLUSTER_SIZE));
            parts.push(cluster);
        }
        const out = new Uint8Array(parts.length * CLUSTER_SIZE);
        parts.forEach((p, i) => out.set(p, i * CLUSTER_SIZE));
        // (the length first: the writer may transfer the buffer)
        written += out.length;
        await write(out);
        progress && progress({ phase: "write", loaded: written, total: layout.file_size });
    }
    if(written !== layout.file_size)
    {
        throw new DiskImageError("The disk changed during the export (" + written + " bytes written, " + layout.file_size + " planned)", "io");
    }
    return written;
}
                                                                                                                                                                                 source/v64/src/image/sha256.js                                                                      0000644 0000000 0000000 00000010527 00000000000 013110  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SHA-256 (FIPS 180-4), synchronous: the identity of a disk image's metadata
// (docs/disk-image-formats-plan.md P1). crypto.subtle is asynchronous and
// missing on pages that are not a secure context (http:// on a LAN).

const K = new Int32Array([
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);

/**
 * An incremental SHA-256
 * @constructor
 */
export function SHA256()
{
    this.h = new Int32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
    this.w = new Int32Array(64);
    this.block = new Uint8Array(64);
    this.block_length = 0;
    this.total = 0;
}

/**
 * @param {!Uint8Array} data
 * @return {!SHA256}
 */
SHA256.prototype.update = function(data)
{
    this.total += data.length;
    let i = 0;
    if(this.block_length)
    {
        const n = Math.min(64 - this.block_length, data.length);
        this.block.set(data.subarray(0, n), this.block_length);
        this.block_length += n;
        i = n;
        if(this.block_length < 64) return this;
        this.compress(this.block, 0);
        this.block_length = 0;
    }
    for(; i + 64 <= data.length; i += 64)
    {
        this.compress(data, i);
    }
    this.block.set(data.subarray(i), 0);
    this.block_length = data.length - i;
    return this;
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 */
SHA256.prototype.compress = function(bytes, offset)
{
    const w = this.w, h = this.h;
    for(let t = 0; t < 16; t++)
    {
        const p = offset + t * 4;
        w[t] = bytes[p] << 24 | bytes[p + 1] << 16 | bytes[p + 2] << 8 | bytes[p + 3];
    }
    for(let t = 16; t < 64; t++)
    {
        const x = w[t - 15], y = w[t - 2];
        const s0 = (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3;
        const s1 = (y >>> 17 | y << 15) ^ (y >>> 19 | y << 13) ^ y >>> 10;
        w[t] = w[t - 16] + s0 + w[t - 7] + s1 | 0;
    }
    let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], k = h[7];
    for(let t = 0; t < 64; t++)
    {
        const s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7);
        const t1 = k + s1 + (e & f ^ ~e & g) + K[t] + w[t] | 0;
        const s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10);
        const t2 = s0 + (a & b ^ a & c ^ b & c) | 0;
        k = g; g = f; f = e; e = d + t1 | 0;
        d = c; c = b; b = a; a = t1 + t2 | 0;
    }
    h[0] += a; h[1] += b; h[2] += c; h[3] += d;
    h[4] += e; h[5] += f; h[6] += g; h[7] += k;
};

/**
 * @return {string} the digest in hexadecimal
 */
SHA256.prototype.hex = function()
{
    const bits_high = Math.floor(this.total / 0x20000000), bits_low = this.total * 8 >>> 0;
    const pad = new Uint8Array((this.block_length < 56 ? 64 : 128) - this.block_length);
    pad[0] = 0x80;
    const n = pad.length;
    pad[n - 8] = bits_high >>> 24; pad[n - 7] = bits_high >>> 16; pad[n - 6] = bits_high >>> 8; pad[n - 5] = bits_high;
    pad[n - 4] = bits_low >>> 24; pad[n - 3] = bits_low >>> 16; pad[n - 2] = bits_low >>> 8; pad[n - 1] = bits_low;
    const total = this.total;
    this.update(pad);
    this.total = total;
    return Array.from(this.h, x => (x >>> 0).toString(16).padStart(8, "0")).join("");
};

/**
 * @return {!Uint8Array} the digest's 32 bytes
 */
SHA256.prototype.digest = function()
{
    const hex = this.hex();
    const out = new Uint8Array(32);
    for(let i = 0; i < 32; i++) out[i] = parseInt(hex.substr(2 * i, 2), 16);
    return out;
};

/**
 * @param {...!Uint8Array} parts
 * @return {string}
 */
export function sha256_hex(...parts)
{
    const hash = new SHA256();
    for(const part of parts) hash.update(part);
    return hash.hex();
}
                                                                                                                                                                         source/v64/src/image/source.js                                                                      0000644 0000000 0000000 00000073376 00000000000 013413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bytes of a disk image file (docs/disk-image-formats-plan.md P0): read
// at any offset and length, the reads cancellable, with an explicit error
// instead of a callback that never comes. The format readers
// (src/image/*.js) sit on top; the device sees a DiskImage
// (src/image/disk_image.js).
//
// A source: byteLength (once opened), name (for messages), sync (reads call
// back before read() returns), open(callback(error)), read(offset, length,
// callback(data, error), signal). `data` has exactly `length` bytes and
// may be a view of the source's own memory: readers copy from it and do not
// write to it. After `signal` aborts, the callback does not run.

import { dbg_assert, dbg_log } from "../log.js";
import { LOG_DISK } from "../const.js";
import { response_header } from "../lib.js";

// How long one HTTP request may take, and how often one that failed for a
// reason that may pass (network, timeout, 5xx) is tried again
const REQUEST_TIMEOUT = 30000;
const RETRY_DELAYS = [1000, 2000, 4000];

// The read cache of sources that are slow to read (URLs, split files)
export const DEFAULT_WINDOW_SIZE = 64 * 1024;
export const DEFAULT_CACHE_SIZE = 32 * 1024 * 1024;

/**
 * An error of a disk image: its source, its format or a feature the reader
 * does not support. `kind` is "io", "corrupt", "unsupported", "changed" or
 * "config".
 */
export class DiskImageError extends Error
{
    /**
     * @param {string} message
     * @param {string=} kind
     */
    constructor(message, kind)
    {
        super(message);
        this.name = "DiskImageError";
        /** @type {string} */
        this.kind = kind || "io";
    }
}

// lib.js reads `url` with fs in Node (a local path) and with XHR in browsers
const IN_NODE = typeof XMLHttpRequest === "undefined" ||
    typeof process !== "undefined" && !!process.versions && !!process.versions.node;

/* global require */
let node_fs;
async function get_node_fs()
{
    if(!node_fs)
    {
        // (as in lib.js: require in Electron renderers, the string split
        // for the Closure Compiler)
        node_fs = typeof require !== "undefined" ? require("fs")["promises"] : await import("node:" + "fs/promises");
    }
    return node_fs;
}

/**
 * Check a read against a source's length
 * @param {{byteLength: number, name: string}} source
 * @param {number} offset
 * @param {number} length
 */
function check_range(source, offset, length)
{
    if(!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 ||
        offset + length > source.byteLength)
    {
        throw new DiskImageError(source.name + ": read of " + length + " bytes at " + offset +
            " outside of the file (" + source.byteLength + " bytes)", "corrupt");
    }
}

/**
 * The bytes in memory (an ArrayBuffer, or a whole file downloaded)
 * @constructor
 * @param {!Uint8Array} bytes
 * @param {string} name
 */
export function MemorySource(bytes, name)
{
    this.bytes = bytes;
    this.byteLength = bytes.length;
    this.name = name;
    this.sync = true;
    this.stats = { requests: 0, bytes: 0 };
}

/** @param {function((Error|undefined))} callback */
MemorySource.prototype.open = function(callback)
{
    callback(undefined);
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
MemorySource.prototype.read = function(offset, length, callback, signal)
{
    check_range(this, offset, length);
    this.stats.requests++;
    this.stats.bytes += length;
    callback(this.bytes.subarray(offset, offset + length));
};

/**
 * A File or Blob: read synchronously in a worker (FileReaderSync, as
 * AsyncFileBuffer), asynchronously otherwise
 * @constructor
 * @param {!Blob} blob
 * @param {string} name
 */
export function BlobSource(blob, name)
{
    this.blob = blob;
    this.byteLength = blob.size;
    this.name = name;
    this.sync = typeof FileReaderSync !== "undefined";
    this.stats = { requests: 0, bytes: 0 };
}

BlobSource.prototype.open = MemorySource.prototype.open;

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
BlobSource.prototype.read = function(offset, length, callback, signal)
{
    check_range(this, offset, length);
    this.stats.requests++;
    this.stats.bytes += length;
    const slice = this.blob.slice(offset, offset + length);
    const fail = error => new DiskImageError(this.name + ": reading " + length + " bytes at " + offset + " failed: " +
        (error && error.message || error), "io");
    if(this.sync)
    {
        let data;
        try
        {
            data = new Uint8Array(new FileReaderSync().readAsArrayBuffer(slice));
        }
        catch(error)
        {
            callback(undefined, fail(error));
            return;
        }
        callback(data.length === length ? data : undefined,
            data.length === length ? undefined : fail("short read"));
        return;
    }
    const reader = new FileReader();
    const abort = () => reader.abort();
    signal && signal.addEventListener("abort", abort, { once: true });
    reader.onload = () =>
    {
        signal && signal.removeEventListener("abort", abort);
        if(signal && signal.aborted) return;
        const data = new Uint8Array(/** @type {!ArrayBuffer} */ (reader.result));
        if(data.length !== length) callback(undefined, fail("short read"));
        else callback(data);
    };
    reader.onerror = () =>
    {
        signal && signal.removeEventListener("abort", abort);
        if(signal && signal.aborted) return;
        callback(undefined, fail(reader.error));
    };
    reader.readAsArrayBuffer(slice);
};

/**
 * One ranged read through XMLHttpRequest. `info` has the response's status
 * and the headers the source checks.
 * @param {string} url
 * @param {number} start
 * @param {number|undefined} length undefined: the whole file
 * @param {function((!Uint8Array|undefined), (Object|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
export function xhr_transport(url, start, length, callback, signal)
{
    const http = new XMLHttpRequest();
    let finished = false;
    const finish = (data, info, error) =>
    {
        if(finished) return;
        finished = true;
        signal && signal.removeEventListener("abort", abort);
        if(signal && signal.aborted) return;
        callback(data, info, error);
    };
    const abort = () =>
    {
        finished = true;
        http.abort();
    };
    if(signal)
    {
        if(signal.aborted) return;
        signal.addEventListener("abort", abort, { once: true });
    }
    http.open("GET", url, true);
    http.responseType = "arraybuffer";
    http.timeout = REQUEST_TIMEOUT;
    if(length !== undefined)
    {
        http.setRequestHeader("Range", "bytes=" + start + "-" + (start + length - 1));
    }
    // (the same request headers as load_file's ranged reads)
    http.setRequestHeader("X-Accept-Encoding", "identity");
    const info = () => ({
        status: http.status,
        content_range: http.getResponseHeader("Content-Range"),
        content_encoding: http.getResponseHeader("Content-Encoding"),
        etag: response_header(http, "ETag"),
        last_modified: response_header(http, "Last-Modified"),
        total: undefined,
        version: undefined,
    });
    http.onreadystatechange = () =>
    {
        // the whole file in response to a range: stop it before it downloads
        if(length !== undefined && http.readyState === 2 && http.status === 200)
        {
            const result = info();
            http.abort();
            finish(undefined, result, new DiskImageError(url + ": the server sent the whole file in response to a " +
                "Range request: it must support Range requests (HTTP 206)", "io"));
        }
    };
    http.onload = () => finish(new Uint8Array(/** @type {!ArrayBuffer} */ (http.response || new ArrayBuffer(0))), info(), undefined);
    http.onerror = () => finish(undefined, undefined, new DiskImageError(url + ": network error", "io"));
    http.ontimeout = () => finish(undefined, undefined, new DiskImageError(url + ": no response in " +
        REQUEST_TIMEOUT / 1000 + " seconds", "io"));
    http.send(null);
}

/**
 * One read of a local file in Node: `info` has the file's size and version
 * (inode, size and modification time)
 * @param {string} path
 * @param {number} start
 * @param {number|undefined} length
 * @param {function((!Uint8Array|undefined), (Object|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
export function node_file_transport(path, start, length, callback, signal)
{
    (async () =>
    {
        const fs = await get_node_fs();
        const file = await fs["open"](path, "r");
        try
        {
            const stat = await file["stat"]();
            const size = stat["size"];
            if(length === undefined) length = Math.max(0, size - start);
            const data = new Uint8Array(length);
            let done = 0;
            while(done < length)
            {
                const result = await file["read"](data, done, length - done, start + done);
                if(!result["bytesRead"]) break;
                done += result["bytesRead"];
            }
            const info = {
                status: done === length ? 206 : 0,
                total: size,
                version: stat["ino"] + ":" + stat["size"] + ":" + stat["mtimeMs"],
                content_range: null, content_encoding: null, etag: null, last_modified: null,
            };
            return { data: done === length ? data : data.subarray(0, done), info };
        }
        finally
        {
            await file["close"]();
        }
    })().then(({ data, info }) =>
    {
        if(signal && signal.aborted) return;
        callback(data, info);
    }, error =>
    {
        if(signal && signal.aborted) return;
        callback(undefined, undefined, new DiskImageError(path + ": " + (error && error.message || error), "io"));
    });
}

/**
 * A file at a URL, read in ranges (HTTP Range requests in browsers, a local
 * path in Node, as load_file). Every response is checked: status 206, the
 * Content-Range asked for and the file's length, the length of the data,
 * and the file's version (ETag, Last-Modified; inode and modification time
 * in Node), which must not change during the session: a source that changes
 * fails every read from then on rather than mix data of two versions.
 * @constructor
 * @param {string} url
 * @param {number|undefined} size the file's length, if known
 * @param {string} name
 * @param {!Function=} transport
 * @param {!Array<number>=} retry_delays (tests)
 */
export function URLSource(url, size, name, transport, retry_delays)
{
    this.url = url;
    this.byteLength = size === undefined ? -1 : size;
    this.given_size = size;
    this.name = name;
    this.sync = false;
    this.transport = transport || (IN_NODE ? node_file_transport : xhr_transport);
    this.node = !transport && IN_NODE;
    this.retry_delays = retry_delays || RETRY_DELAYS;
    /** @type {?Object} the version of the first response */
    this.version = null;
    /** @type {Error|undefined} set when the source changed: every read fails */
    this.failed = undefined;
    this.stats = { requests: 0, bytes: 0, retries: 0 };
}

/** @param {function((Error|undefined))} callback */
URLSource.prototype.open = function(callback)
{
    if(this.given_size !== undefined && !this.node)
    {
        // (the first read checks the length the server reports)
        if(!Number.isSafeInteger(this.given_size) || this.given_size < 0)
        {
            callback(new DiskImageError(this.name + ": invalid size " + this.given_size, "config"));
            return;
        }
        callback(undefined);
        return;
    }
    // the length from a read of the first byte (Content-Range: bytes 0-0/<length>)
    this.request(0, 1, true, (data, error) => callback(error), undefined, 0);
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
URLSource.prototype.read = function(offset, length, callback, signal)
{
    check_range(this, offset, length);
    if(length === 0)
    {
        callback(new Uint8Array(0));
        return;
    }
    this.request(offset, length, false, callback, signal, 0);
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {boolean} opening
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal|undefined} signal
 * @param {number} attempt
 */
URLSource.prototype.request = function(offset, length, opening, callback, signal, attempt)
{
    if(this.failed)
    {
        callback(undefined, this.failed);
        return;
    }
    this.stats.requests++;
    this.transport(this.url, offset, length, (data, info, error) =>
    {
        if(this.failed)
        {
            callback(undefined, this.failed);
            return;
        }
        if(!error)
        {
            error = this.check_response(offset, length, opening, data, info);
        }
        if(error)
        {
            const retry = error.kind === "io" && attempt < this.retry_delays.length &&
                (!info || info.status >= 500 && info.status < 600) && !this.node;
            if(retry)
            {
                this.stats.retries++;
                dbg_log(this.name + ": " + error.message + ", trying again", LOG_DISK);
                setTimeout(() =>
                {
                    if(signal && signal.aborted) return;
                    this.request(offset, length, opening, callback, signal, attempt + 1);
                }, this.retry_delays[attempt]);
                return;
            }
            if(error.kind === "changed") this.failed = error;
            callback(undefined, error);
            return;
        }
        this.stats.bytes += length;
        callback(data);
    }, signal);
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {boolean} opening
 * @param {!Uint8Array|undefined} data
 * @param {!Object} info
 * @return {Error|undefined}
 */
URLSource.prototype.check_response = function(offset, length, opening, data, info)
{
    const where = this.name + ": the response to a read of " + length + " bytes at " + offset;
    if(this.node)
    {
        if(opening)
        {
            this.byteLength = info.total;
            this.version = info.version;
            if(this.given_size !== undefined && this.given_size !== info.total)
            {
                return new DiskImageError(this.name + ": the file has " + info.total + " bytes, its size is given as " +
                    this.given_size, "config");
            }
            return undefined;
        }
        if(info.version !== this.version)
        {
            return new DiskImageError(this.name + ": the file changed during the session", "changed");
        }
        if(!data || data.length !== length)
        {
            return new DiskImageError(where + " is short (" + (data ? data.length : 0) + " bytes): the file was truncated?", "io");
        }
        return undefined;
    }

    if(info.status !== 206)
    {
        return new DiskImageError(where + " has status " + info.status + " (expected 206)", "io");
    }
    if(info.content_encoding && info.content_encoding !== "identity")
    {
        return new DiskImageError(where + " has Content-Encoding " + info.content_encoding, "io");
    }
    const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec((info.content_range || "").trim());
    if(!range)
    {
        return new DiskImageError(where + " has the Content-Range \"" + info.content_range + "\"", "io");
    }
    const first = +range[1], last = +range[2], total = +range[3];
    if(first !== offset || last !== offset + length - 1)
    {
        return new DiskImageError(where + " is for bytes " + first + "-" + last, "io");
    }
    if(!data || data.length !== length)
    {
        return new DiskImageError(where + " has " + (data ? data.length : 0) + " bytes", "io");
    }
    if(opening || this.version === null)
    {
        if(this.given_size !== undefined && total !== this.given_size)
        {
            return new DiskImageError(this.name + ": the server reports " + total + " bytes, the size is given as " +
                this.given_size, "config");
        }
        this.byteLength = total;
        this.version = { etag: info.etag, last_modified: info.last_modified };
        return undefined;
    }
    if(total !== this.byteLength ||
        this.version.etag && info.etag !== this.version.etag ||
        this.version.last_modified && info.last_modified !== this.version.last_modified)
    {
        return new DiskImageError(this.name + ": the file changed on the server during the session (" +
            (total !== this.byteLength ? "length " + this.byteLength + " -> " + total :
            "ETag/Last-Modified " + JSON.stringify(this.version) + " -> " + JSON.stringify([info.etag, info.last_modified])) +
            "): no more reads from it", "changed");
    }
    return undefined;
};

/**
 * A file split in parts of `chunk_size` bytes (use_parts with
 * fixed_chunk_size, as AsyncXHRPartfileBuffer), each part optionally
 * compressed with Zstandard (".zst")
 * @constructor
 * @param {string} url
 * @param {number} size
 * @param {number} chunk_size
 * @param {boolean} alt_format the parts are numbered (filename-%08d.ext)
 * @param {function(number, !Uint8Array):!Promise<!ArrayBuffer>|undefined} zstd_decompress
 * @param {string} name
 * @param {!Function=} transport
 */
export function PartsSource(url, size, chunk_size, alt_format, zstd_decompress, name, transport)
{
    const parts = url.match(/\.[^\.]+(\.zst)?$/);
    this.extension = parts ? parts[0] : "";
    this.basename = url.substring(0, url.length - this.extension.length);
    if(!this.basename.endsWith("/")) this.basename += "-";
    this.is_zstd = this.extension.endsWith(".zst");
    this.byteLength = size;
    this.chunk_size = chunk_size;
    this.alt_format = alt_format;
    this.zstd_decompress = zstd_decompress;
    this.name = name;
    this.sync = false;
    this.transport = transport || (IN_NODE ? node_file_transport : xhr_transport);
    this.node = !transport && IN_NODE;
    this.stats = { requests: 0, bytes: 0, retries: 0 };
}

/** @param {function((Error|undefined))} callback */
PartsSource.prototype.open = function(callback)
{
    if(!Number.isSafeInteger(this.byteLength) || this.byteLength < 0 ||
        !Number.isSafeInteger(this.chunk_size) || this.chunk_size <= 0 || this.chunk_size % 512)
    {
        callback(new DiskImageError(this.name + ": use_parts needs size and a fixed_chunk_size that is a multiple of 512", "config"));
        return;
    }
    if(this.is_zstd && !this.zstd_decompress)
    {
        callback(new DiskImageError(this.name + ": no Zstandard decompressor for the parts", "config"));
        return;
    }
    callback(undefined);
};

/**
 * @param {number} index
 * @return {string}
 */
PartsSource.prototype.part_url = function(index)
{
    const start = index * this.chunk_size;
    return this.alt_format ?
        this.basename + String(index).padStart(8, "0") + this.extension :
        this.basename + start + "-" + (start + this.chunk_size) + this.extension;
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
PartsSource.prototype.read = function(offset, length, callback, signal)
{
    check_range(this, offset, length);
    if(length === 0)
    {
        callback(new Uint8Array(0));
        return;
    }
    const first = Math.floor(offset / this.chunk_size);
    const last = Math.floor((offset + length - 1) / this.chunk_size);
    const result = new Uint8Array(length);
    let pending = last - first + 1;
    let failed = false;
    for(let index = first; index <= last; index++)
    {
        this.read_part(index, (data, error) =>
        {
            if(failed) return;
            if(error)
            {
                failed = true;
                callback(undefined, error);
                return;
            }
            const part_start = index * this.chunk_size;
            const from = Math.max(offset, part_start), to = Math.min(offset + length, part_start + data.length);
            result.set(data.subarray(from - part_start, to - part_start), from - offset);
            if(--pending === 0) callback(result);
        }, signal, 0);
    }
};

/**
 * @param {number} index
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal|undefined} signal
 * @param {number} attempt
 */
PartsSource.prototype.read_part = function(index, callback, signal, attempt)
{
    const url = this.part_url(index);
    const expected = Math.min(this.chunk_size, this.byteLength - index * this.chunk_size);
    this.stats.requests++;
    this.transport(url, 0, undefined, (data, info, error) =>
    {
        if(!error && !this.node && info.status !== 200)
        {
            error = new DiskImageError(this.name + ": " + url + " has status " + info.status, "io");
        }
        if(error)
        {
            if(attempt < RETRY_DELAYS.length && (!info || info.status >= 500) && !this.node)
            {
                this.stats.retries++;
                setTimeout(() =>
                {
                    if(signal && signal.aborted) return;
                    this.read_part(index, callback, signal, attempt + 1);
                }, RETRY_DELAYS[attempt]);
                return;
            }
            callback(undefined, error);
            return;
        }
        const check = bytes =>
        {
            if(signal && signal.aborted) return;
            // (a last part may be the whole chunk size, padded)
            if(bytes.length !== expected && !(bytes.length === this.chunk_size && expected < this.chunk_size))
            {
                callback(undefined, new DiskImageError(this.name + ": " + url + " has " + bytes.length +
                    " bytes, expected " + expected, "io"));
                return;
            }
            this.stats.bytes += bytes.length;
            callback(bytes.subarray(0, expected));
        };
        if(this.is_zstd)
        {
            this.zstd_decompress(this.chunk_size, data).then(result => check(new Uint8Array(result)), error =>
            {
                if(signal && signal.aborted) return;
                callback(undefined, new DiskImageError(this.name + ": " + url + ": " + error.message, "corrupt"));
            });
        }
        else
        {
            check(/** @type {!Uint8Array} */ (data));
        }
    }, signal);
};

/**
 * A read cache over a slow source: the file in aligned windows, the ones
 * read last kept up to a budget. Reads of windows already on their way wait
 * for them; adjacent missing windows are read with one request. A read
 * cancelled by its caller ends the requests no other read waits for.
 * @constructor
 * @param {?} inner a source
 * @param {number=} window_size
 * @param {number=} budget
 */
export function CachedSource(inner, window_size, budget)
{
    this.inner = inner;
    this.name = inner.name;
    this.byteLength = inner.byteLength;
    this.sync = inner.sync;
    this.window_size = window_size || DEFAULT_WINDOW_SIZE;
    this.max_windows = Math.max(4, Math.floor((budget || DEFAULT_CACHE_SIZE) / this.window_size));
    /** @type {!Map<number, !Uint8Array>} window number -> data, the most recently used last */
    this.windows = new Map();
    /** @type {!Map<number, !Object>} window number -> the request reading it */
    this.in_flight = new Map();
    this.stats = { hits: 0, misses: 0 };
}

/** @param {function((Error|undefined))} callback */
CachedSource.prototype.open = function(callback)
{
    this.inner.open(error =>
    {
        this.byteLength = this.inner.byteLength;
        callback(error);
    });
};

/**
 * @param {number} offset
 * @param {number} length
 * @param {function((!Uint8Array|undefined), (Error|undefined)=)} callback
 * @param {AbortSignal=} signal
 */
CachedSource.prototype.read = function(offset, length, callback, signal)
{
    check_range(this, offset, length);
    if(length === 0)
    {
        callback(new Uint8Array(0));
        return;
    }
    if(signal && signal.aborted) return;
    const size = this.window_size;
    const first = Math.floor(offset / size), last = Math.floor((offset + length - 1) / size);
    // (the windows a read waits for are kept with it: others may evict them
    // from the cache meanwhile)
    const waiter = { first, last, offset, length, callback, signal, on_abort: null,
        /** @type {!Map<number, !Uint8Array>} */ parts: new Map(),
        remaining: 0, done: false, /** @type {!Set<!Object>} */ requests: new Set() };

    const new_indices = [];
    for(let index = first; index <= last; index++)
    {
        const cached = this.windows.get(index);
        if(cached)
        {
            // the most recently used last
            this.windows.delete(index);
            this.windows.set(index, cached);
            waiter.parts.set(index, cached);
            continue;
        }
        waiter.remaining++;
        const request = this.in_flight.get(index);
        if(request)
        {
            request.waiters.add(waiter);
            waiter.requests.add(request);
        }
        else
        {
            new_indices.push(index);
        }
    }
    if(waiter.remaining) this.stats.misses++;
    else this.stats.hits++;
    if(waiter.remaining === 0)
    {
        this.deliver(waiter);
        return;
    }

    // one request for each run of adjacent missing windows
    const started = [];
    for(let i = 0; i < new_indices.length;)
    {
        let j = i + 1;
        while(j < new_indices.length && new_indices[j] === new_indices[j - 1] + 1) j++;
        const request = { indices: new_indices.slice(i, j), waiters: new Set([waiter]),
            controller: new AbortController(), finished: false };
        for(const index of request.indices) this.in_flight.set(index, request);
        waiter.requests.add(request);
        started.push(request);
        i = j;
    }
    if(signal)
    {
        waiter.on_abort = () => this.cancel(waiter);
        signal.addEventListener("abort", waiter.on_abort, { once: true });
    }
    for(const request of started)
    {
        if(request.finished) continue;
        const start = request.indices[0] * size;
        const end = Math.min(this.byteLength, (request.indices[request.indices.length - 1] + 1) * size);
        this.inner.read(start, end - start, (data, error) => this.complete(request, data, error), request.controller.signal);
    }
};

/**
 * A read stops waiting: its callback does not run, and the requests only it
 * waited for are ended
 * @param {!Object} waiter
 */
CachedSource.prototype.cancel = function(waiter)
{
    if(waiter.done) return;
    this.end(waiter);
    for(const request of waiter.requests)
    {
        if(!request.finished && request.waiters.size === 0)
        {
            request.finished = true;
            request.controller.abort();
            for(const index of request.indices)
            {
                if(this.in_flight.get(index) === request) this.in_flight.delete(index);
            }
        }
    }
};

/** @param {!Object} waiter */
CachedSource.prototype.end = function(waiter)
{
    waiter.done = true;
    if(waiter.signal && waiter.on_abort) waiter.signal.removeEventListener("abort", waiter.on_abort);
    for(const request of waiter.requests) request.waiters.delete(waiter);
};

/** @param {!Object} waiter */
CachedSource.prototype.deliver = function(waiter)
{
    this.end(waiter);
    const size = this.window_size;
    if(waiter.first === waiter.last)
    {
        const start = waiter.offset - waiter.first * size;
        waiter.callback(waiter.parts.get(waiter.first).subarray(start, start + waiter.length));
        return;
    }
    const result = new Uint8Array(waiter.length);
    for(let index = waiter.first; index <= waiter.last; index++)
    {
        const data = waiter.parts.get(index);
        const window_start = index * size;
        const from = Math.max(waiter.offset, window_start);
        const to = Math.min(waiter.offset + waiter.length, window_start + data.length);
        result.set(data.subarray(from - window_start, to - window_start), from - waiter.offset);
    }
    waiter.callback(result);
};

/**
 * @param {!Object} request
 * @param {!Uint8Array|undefined} data
 * @param {Error|undefined} error
 */
CachedSource.prototype.complete = function(request, data, error)
{
    if(request.finished) return;
    request.finished = true;
    for(const index of request.indices)
    {
        if(this.in_flight.get(index) === request) this.in_flight.delete(index);
    }
    const size = this.window_size;
    /** @type {!Map<number, !Uint8Array>} */
    const arrived = new Map();
    if(!error)
    {
        const start = request.indices[0] * size;
        for(const index of request.indices)
        {
            const from = index * size - start;
            // (a copy: the inner source's view may be of memory it reuses)
            const window = data.slice(from, Math.min(data.length, from + size));
            arrived.set(index, window);
            this.windows.set(index, window);
        }
        while(this.windows.size > this.max_windows)
        {
            this.windows.delete(this.windows.keys().next().value);
        }
    }
    for(const waiter of Array.from(request.waiters))
    {
        if(waiter.done) continue;
        if(error)
        {
            this.end(waiter);
            waiter.callback(undefined, error);
            continue;
        }
        for(const [index, window] of arrived)
        {
            if(index >= waiter.first && index <= waiter.last && !waiter.parts.has(index))
            {
                waiter.parts.set(index, window);
                waiter.remaining--;
            }
        }
        dbg_assert(waiter.remaining >= 0);
        if(waiter.remaining === 0) this.deliver(waiter);
    }
};
                                                                                                                                                                                                                                                                  source/v64/src/image/vdi.js                                                                         0000644 0000000 0000000 00000014711 00000000000 012661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VDI images (VirtualBox), dynamic and fixed (docs/disk-image-formats-plan.md
// P3): the header of version 1.1, the block map, unallocated and discarded
// blocks (zeros). As QEMU's vdi driver: 512-byte sectors, blocks of 1 MiB,
// no extra block data. Differencing images (a parent or link UUID) are
// refused (no independent tool here makes them).

import { DiskImageError } from "./source.js";
import { ImageReader, EXTENT_DATA, EXTENT_ZERO, push_extent, read_u64, to_number } from "./disk_image.js";
import { sha256_hex } from "./sha256.js";

export const VDI_SIGNATURE = 0xBEDA107F;
const VERSION_1_1 = 0x00010001;
const TYPE_DYNAMIC = 1;
const TYPE_STATIC = 2;
const UNALLOCATED = 0xFFFFFFFF;
const DISCARDED = 0xFFFFFFFE;
const BLOCK_SIZE = 1024 * 1024;
const MAX_BLOCKS = 0x3FFFFFFF;

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
function u32le(bytes, offset)
{
    return (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
}

export class VDIReader extends ImageReader
{
    /**
     * @param {?} source
     * @param {string} name
     */
    constructor(source, name)
    {
        super(source, name);
        this.format = "vdi";
        this.image_type = 0;
        this.offset_data = 0;
        this.blocks = 0;
        /** @type {!Uint8Array} */
        this.bmap = new Uint8Array(0);
    }

    /**
     * @param {string} what
     * @param {string=} kind
     * @return {!DiskImageError}
     */
    error(what, kind)
    {
        return new DiskImageError(this.name + ": vdi: " + what, kind || "corrupt");
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {string} what
     * @return {!Promise<!Uint8Array>}
     */
    read_metadata(offset, length, what)
    {
        return new Promise((resolve, reject) =>
        {
            if(offset + length > this.source.byteLength)
            {
                reject(this.error(what + " (" + length + " bytes at " + offset + ") is past the end of the file (" +
                    this.source.byteLength + " bytes): the file is truncated or corrupt"));
                return;
            }
            this.source.read(offset, length, (data, error) => error ? reject(error) : resolve(data));
        });
    }

    /** @param {function((Error|undefined))} callback */
    open(callback)
    {
        this.parse().then(() => callback(undefined), error => callback(/** @type {!Error} */ (error)));
    }

    async parse()
    {
        const header = (await this.read_metadata(0, 512, "the header")).slice();
        if(u32le(header, 0x40) !== VDI_SIGNATURE) throw this.error("no VDI signature");
        const version = u32le(header, 0x44);
        if(version !== VERSION_1_1)
        {
            throw this.error("version 0x" + version.toString(16) + " is not supported (only 1.1)", "unsupported");
        }
        // (the header after the pre-header of 0x48 bytes: 0x180 bytes in 1.1)
        const header_size = u32le(header, 0x48);
        if(header_size < 0x180 || 0x48 + header_size > 512) throw this.error("header size " + header_size + " is invalid");
        this.image_type = u32le(header, 0x4C);
        if(this.image_type !== TYPE_DYNAMIC && this.image_type !== TYPE_STATIC)
        {
            throw this.error("image type " + this.image_type + " is not supported (only dynamic and fixed)", "unsupported");
        }
        const offset_bmap = u32le(header, 0x154);
        this.offset_data = u32le(header, 0x158);
        const sector_size = u32le(header, 0x168);
        const size = to_number(read_u64(header, 0x170, true), this.name + ": vdi: the disk size");
        const block_size = u32le(header, 0x178);
        const block_extra = u32le(header, 0x17C);
        this.blocks = u32le(header, 0x180);
        if(sector_size !== 512) throw this.error("sector size " + sector_size + " is not supported", "unsupported");
        if(block_size !== BLOCK_SIZE) throw this.error("block size " + block_size + " is not supported (only 1 MiB)", "unsupported");
        if(block_extra !== 0) throw this.error("extra block data (" + block_extra + " bytes) is not supported", "unsupported");
        if(size % 512) throw this.error("the disk size " + size + " is not a multiple of 512 bytes", "unsupported");
        if(this.blocks > MAX_BLOCKS) throw this.error("too many blocks (" + this.blocks + ")");
        if(size > this.blocks * BLOCK_SIZE)
        {
            throw this.error("the disk size " + size + " is larger than its " + this.blocks + " blocks");
        }
        if(offset_bmap % 512 || this.offset_data % 512)
        {
            throw this.error("the block map (" + offset_bmap + ") or the data (" + this.offset_data + ") is not aligned to a sector");
        }
        const zero_uuid = offset => header.subarray(offset, offset + 16).every(b => b === 0);
        if(!zero_uuid(0x1A8) || !zero_uuid(0x1B8))
        {
            throw this.error("a differencing image (a link or parent UUID): not supported", "unsupported");
        }
        this.virtual_size = size;
        this.bmap = (await this.read_metadata(offset_bmap, this.blocks * 4, "the block map")).slice();
        this.metadata_sha256 = sha256_hex(header.subarray(0, 0x48 + header_size), this.bmap);
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        const extents = [];
        const end = offset + length;
        for(let position = offset; position < end;)
        {
            const block = Math.floor(position / BLOCK_SIZE);
            const in_block = position - block * BLOCK_SIZE;
            const count = Math.min(BLOCK_SIZE - in_block, end - position);
            const entry = u32le(this.bmap, block * 4);
            if(entry === UNALLOCATED || entry === DISCARDED)
            {
                push_extent(extents, EXTENT_ZERO, count);
            }
            else if(entry >= this.blocks)
            {
                callback(undefined, this.error("the block map entry of guest offset " + block * BLOCK_SIZE + " (" + entry +
                    ") is beyond the image's " + this.blocks + " blocks"));
                return;
            }
            else
            {
                push_extent(extents, EXTENT_DATA, count, this.offset_data + entry * BLOCK_SIZE + in_block);
            }
            position += count;
        }
        callback(extents);
    }
}
                                                       source/v64/src/image/vhd.js                                                                         0000644 0000000 0000000 00000022712 00000000000 012660  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VHD images, fixed and dynamic (docs/disk-image-formats-plan.md P3; the
// format: Microsoft's Virtual Hard Disk Image Format Specification). The
// footer (and for dynamic disks the header) must have a valid checksum; the
// size the guest sees follows QEMU's vpc driver (the CHS geometry for images
// of Virtual PC and QEMU, the footer's current size for Hyper-V and others).
// Differencing disks are refused (no independent tool here makes them).

import { DiskImageError } from "./source.js";
import { ImageReader, EXTENT_DATA, EXTENT_ZERO, push_extent, read_u64, to_number } from "./disk_image.js";
import { sha256_hex } from "./sha256.js";

const TYPE_FIXED = 2;
const TYPE_DYNAMIC = 3;
const TYPE_DIFFERENCING = 4;

// QEMU: the largest geometry (65535 cylinders, 16 heads, 255 sectors) means
// "use the current size"; at most 2040 GiB
const MAX_GEOMETRY = 65535 * 16 * 255;
const MAX_SECTORS = 0xFF000000;

const UNALLOCATED = 0xFFFFFFFF;

// BAT entries kept: all of them (4 bytes each, at most 2040 GiB / 512 bytes)
const MAX_BAT_BYTES = 64 * 1024 * 1024;

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
function u32(bytes, offset)
{
    return (bytes[offset] << 24 | bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3]) >>> 0;
}

/**
 * The checksum of a footer or header: the one's complement of the sum of its
 * bytes, the checksum's own as zeros
 * @param {!Uint8Array} bytes
 * @param {number} checksum_offset
 * @return {number}
 */
function vhd_checksum(bytes, checksum_offset)
{
    let sum = 0;
    for(let i = 0; i < bytes.length; i++)
    {
        if(i >= checksum_offset && i < checksum_offset + 4) continue;
        sum += bytes[i];
    }
    return ~sum >>> 0;
}

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @param {number} length
 * @return {string}
 */
function ascii(bytes, offset, length)
{
    return String.fromCharCode(...bytes.subarray(offset, offset + length));
}

export class VHDReader extends ImageReader
{
    /**
     * @param {?} source
     * @param {string} name
     */
    constructor(source, name)
    {
        super(source, name);
        this.format = "vhd";
        this.disk_type = 0;
        this.creator = "";
        this.block_size = 0;
        this.bitmap_size = 0;
        /** @type {!Uint8Array} */
        this.bat = new Uint8Array(0);
        this.bat_entries = 0;
    }

    /**
     * @param {string} what
     * @param {string=} kind
     * @return {!DiskImageError}
     */
    error(what, kind)
    {
        return new DiskImageError(this.name + ": vhd: " + what, kind || "corrupt");
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {string} what
     * @return {!Promise<!Uint8Array>}
     */
    read_metadata(offset, length, what)
    {
        return new Promise((resolve, reject) =>
        {
            if(offset < 0 || offset + length > this.source.byteLength)
            {
                reject(this.error(what + " (" + length + " bytes at " + offset + ") is past the end of the file (" +
                    this.source.byteLength + " bytes): the file is truncated or corrupt"));
                return;
            }
            this.source.read(offset, length, (data, error) => error ? reject(error) : resolve(data));
        });
    }

    /** @param {function((Error|undefined))} callback */
    open(callback)
    {
        this.parse().then(() => callback(undefined), error => callback(/** @type {!Error} */ (error)));
    }

    async parse()
    {
        const file_size = this.source.byteLength;
        if(file_size < 512) throw this.error("the file is too small for a footer");
        // a dynamic disk has a copy of the footer at the start (QEMU reads that
        // one), a fixed disk only the one at the end
        let footer = (await this.read_metadata(0, 512, "the footer's copy")).slice();
        if(ascii(footer, 0, 8) !== "conectix" || u32(footer, 60) === TYPE_FIXED)
        {
            footer = (await this.read_metadata(file_size - 512, 512, "the footer")).slice();
            if(ascii(footer, 0, 8) !== "conectix")
            {
                // (images of old tools: a footer of 511 bytes)
                const short = await this.read_metadata(file_size - 511, 511, "the footer");
                if(ascii(short, 0, 8) !== "conectix") throw this.error("no footer (\"conectix\")");
                footer = new Uint8Array(512);
                footer.set(short);
            }
        }
        const checksum = u32(footer, 64);
        if(vhd_checksum(footer, 64) !== checksum)
        {
            throw this.error("the footer's checksum is wrong (0x" + checksum.toString(16) + ", computed 0x" +
                vhd_checksum(footer, 64).toString(16) + ")");
        }
        const version = u32(footer, 12);
        if(version >>> 16 !== 1)
        {
            throw this.error("file format version 0x" + version.toString(16) + " is not supported", "unsupported");
        }
        this.disk_type = u32(footer, 60);
        this.creator = ascii(footer, 28, 4);
        const current_size = to_number(read_u64(footer, 48), this.name + ": vhd: the current size");

        // the guest's size, as QEMU's vpc driver
        const geometry_sectors = (footer[56] << 8 | footer[57]) * footer[58] * footer[59];
        const use_geometry = this.creator === "vpc " || this.creator === "qemu";
        let sectors = use_geometry && geometry_sectors !== MAX_GEOMETRY ? geometry_sectors : Math.floor(current_size / 512);
        if(sectors > MAX_SECTORS) throw this.error("the disk (" + sectors + " sectors) is larger than VHD allows (2040 GiB)", "unsupported");
        this.virtual_size = sectors * 512;

        const parts = [footer];
        if(this.disk_type === TYPE_FIXED)
        {
            // the data, then the footer
            if(this.virtual_size > file_size - 512 + (file_size % 512 === 511 ? 1 : 0))
            {
                throw this.error("the data (" + this.virtual_size + " bytes) does not fit before the footer: the file (" +
                    file_size + " bytes) is truncated");
            }
        }
        else if(this.disk_type === TYPE_DYNAMIC || this.disk_type === TYPE_DIFFERENCING)
        {
            if(this.disk_type === TYPE_DIFFERENCING)
            {
                throw this.error("differencing disks are not supported", "unsupported");
            }
            const header_offset = to_number(read_u64(footer, 16), this.name + ": vhd: the header's offset");
            const header = (await this.read_metadata(header_offset, 1024, "the dynamic disk header")).slice();
            if(ascii(header, 0, 8) !== "cxsparse") throw this.error("no dynamic disk header (\"cxsparse\") at " + header_offset);
            if(vhd_checksum(header, 36) !== u32(header, 36))
            {
                throw this.error("the dynamic disk header's checksum is wrong");
            }
            const header_version = u32(header, 24);
            if(header_version >>> 16 !== 1)
            {
                throw this.error("dynamic header version 0x" + header_version.toString(16) + " is not supported", "unsupported");
            }
            const bat_offset = to_number(read_u64(header, 16), this.name + ": vhd: the BAT's offset");
            this.bat_entries = u32(header, 28);
            this.block_size = u32(header, 32);
            if(this.block_size < 512 || this.block_size & this.block_size - 1)
            {
                throw this.error("the block size " + this.block_size + " is not a power of two of at least 512");
            }
            if(this.bat_entries * this.block_size < this.virtual_size)
            {
                throw this.error("the BAT (" + this.bat_entries + " blocks of " + this.block_size + " bytes) is too small for the disk");
            }
            if(this.bat_entries * 4 > MAX_BAT_BYTES) throw this.error("the BAT is too large", "unsupported");
            this.bitmap_size = Math.ceil(this.block_size / 512 / 8 / 512) * 512;
            this.bat = (await this.read_metadata(bat_offset, this.bat_entries * 4, "the BAT")).slice();
            parts.push(header, this.bat);
        }
        else
        {
            throw this.error("disk type " + this.disk_type + " is not supported", "unsupported");
        }
        this.metadata_sha256 = sha256_hex(...parts);
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        if(this.disk_type === TYPE_FIXED)
        {
            callback([{ type: EXTENT_DATA, length, host_offset: offset }]);
            return;
        }
        const extents = [];
        const end = offset + length;
        for(let position = offset; position < end;)
        {
            const block = Math.floor(position / this.block_size);
            const in_block = position - block * this.block_size;
            const count = Math.min(this.block_size - in_block, end - position);
            const entry = u32(this.bat, block * 4);
            if(entry === UNALLOCATED)
            {
                push_extent(extents, EXTENT_ZERO, count);
            }
            else
            {
                // (as QEMU: an allocated block is read whole, its sector
                // bitmap only matters for differencing disks)
                push_extent(extents, EXTENT_DATA, count, entry * 512 + this.bitmap_size + in_block);
            }
            position += count;
        }
        callback(extents);
    }
}
                                                      source/v64/src/image/vhdx.js                                                                        0000644 0000000 0000000 00000032442 00000000000 013051  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VHDX images (docs/disk-image-formats-plan.md P5; the format: [MS-VHDX]):
// the two headers (the current one: valid, the higher sequence number), the
// region tables, the metadata (block size, virtual size, sector sizes) and
// the BAT, every structure with its CRC-32C. Logical sectors of 512 or 4096
// bytes: the disk's own (the devices present them, the chunk ratio of the
// BAT depends on them). Refused: a log to replay (its replay changes what
// the file holds, [MS-VHDX] 2.3.3: an image with a log is not read without
// it), a parent (differencing disks), unknown required regions or metadata.

import { DiskImageError } from "./source.js";
import { ImageReader, EXTENT_DATA, EXTENT_ZERO, push_extent, read_u64, to_number, big } from "./disk_image.js";
import { sha256_hex } from "./sha256.js";

const KiB = 1024, MiB = 1024 * 1024;

const GUID_BAT = "2dc27766-f623-4200-9d64-115e9bfd4a08";
const GUID_METADATA = "8b7ca206-4790-4b9a-b8fe-575f050f886e";
const GUID_FILE_PARAMETERS = "caa16737-fa36-4d43-b3b6-33f0aa44e76b";
const GUID_VIRTUAL_DISK_SIZE = "2fa54224-cd1b-4876-b211-5dbed83bf4b8";
const GUID_VIRTUAL_DISK_ID = "beca12ab-b2e6-4523-93ef-c309e000c746";
const GUID_LOGICAL_SECTOR_SIZE = "8141bf1d-a96f-4709-ba47-f233a8faab5f";
const GUID_PHYSICAL_SECTOR_SIZE = "cda348c7-445d-4471-9cc9-e9885251c556";
const GUID_PAGE83 = GUID_VIRTUAL_DISK_ID;
const GUID_PARENT_LOCATOR = "a8d35f2d-b30b-454d-abf7-d3d84834ab0c";
const KNOWN_METADATA = [GUID_FILE_PARAMETERS, GUID_VIRTUAL_DISK_SIZE, GUID_PAGE83, GUID_LOGICAL_SECTOR_SIZE,
    GUID_PHYSICAL_SECTOR_SIZE, GUID_PARENT_LOCATOR];

// payload block states
const PAYLOAD_NOT_PRESENT = 0;
const PAYLOAD_UNDEFINED = 1;
const PAYLOAD_ZERO = 2;
const PAYLOAD_UNMAPPED = 3;
const PAYLOAD_UNMAPPED_V095 = 5;
const PAYLOAD_FULLY_PRESENT = 6;
const PAYLOAD_PARTIALLY_PRESENT = 7;

const MAX_BAT_BYTES = 256 * MiB;

let crc32c_table;

/**
 * CRC-32C (Castagnoli), as [MS-VHDX] checksums are
 * @param {!Uint8Array} bytes
 * @param {number=} skip the offset of a 4-byte checksum field read as zeros
 * @return {number}
 */
export function crc32c(bytes, skip = -1)
{
    if(!crc32c_table)
    {
        crc32c_table = new Int32Array(256);
        for(let n = 0; n < 256; n++)
        {
            let c = n;
            for(let k = 0; k < 8; k++) c = c & 1 ? 0x82F63B78 ^ c >>> 1 : c >>> 1;
            crc32c_table[n] = c;
        }
    }
    let crc = -1;
    for(let i = 0; i < bytes.length; i++)
    {
        const byte = skip >= 0 && i >= skip && i < skip + 4 ? 0 : bytes[i];
        crc = crc32c_table[(crc ^ byte) & 0xFF] ^ crc >>> 8;
    }
    return ~crc >>> 0;
}

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
function u32le(bytes, offset)
{
    return (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
}

/**
 * A GUID as text ([MS-DTYP]: the first three fields little-endian)
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {string}
 */
function guid(bytes, offset)
{
    const hex = i => bytes[offset + i].toString(16).padStart(2, "0");
    return [3, 2, 1, 0].map(hex).join("") + "-" + [5, 4].map(hex).join("") + "-" + [7, 6].map(hex).join("") + "-" +
        [8, 9].map(hex).join("") + "-" + [10, 11, 12, 13, 14, 15].map(hex).join("");
}

export class VHDXReader extends ImageReader
{
    /**
     * @param {?} source
     * @param {string} name
     */
    constructor(source, name)
    {
        super(source, name);
        this.format = "vhdx";
        this.block_size = 0;
        this.chunk_ratio = 0;
        /** (the device's sectors are the disk's: the physical size is not presented) */
        this.physical_sector_size = 0;
        /** @type {!Uint8Array} */
        this.bat = new Uint8Array(0);
        this.bat_entries = 0;
    }

    /**
     * @param {string} what
     * @param {string=} kind
     * @return {!DiskImageError}
     */
    error(what, kind)
    {
        return new DiskImageError(this.name + ": vhdx: " + what, kind || "corrupt");
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {string} what
     * @return {!Promise<!Uint8Array>}
     */
    read_metadata(offset, length, what)
    {
        return new Promise((resolve, reject) =>
        {
            if(offset + length > this.source.byteLength)
            {
                reject(this.error(what + " (" + length + " bytes at " + offset + ") is past the end of the file (" +
                    this.source.byteLength + " bytes): the file is truncated or corrupt"));
                return;
            }
            this.source.read(offset, length, (data, error) => error ? reject(error) : resolve(data));
        });
    }

    /** @param {function((Error|undefined))} callback */
    open(callback)
    {
        this.parse().then(() => callback(undefined), error => callback(/** @type {!Error} */ (error)));
    }

    async parse()
    {
        const identifier = await this.read_metadata(0, 8, "the file type identifier");
        if(String.fromCharCode(...identifier) !== "vhdxfile") throw this.error("no file type identifier (vhdxfile)");

        // the headers: the valid one with the higher sequence number
        let header = null, sequence = big(-1);
        for(const offset of [64 * KiB, 128 * KiB])
        {
            const bytes = (await this.read_metadata(offset, 4 * KiB, "the header at " + offset)).slice();
            if(String.fromCharCode(...bytes.subarray(0, 4)) !== "head" || crc32c(bytes, 4) !== u32le(bytes, 4)) continue;
            const n = read_u64(bytes, 8, true);
            if(n > sequence)
            {
                header = bytes;
                sequence = n;
            }
        }
        if(!header) throw this.error("neither header is valid (signature, CRC-32C)");
        const version = header[66] | header[67] << 8;
        if(version !== 1) throw this.error("version " + version + " is not supported", "unsupported");
        const log_guid = header.subarray(48, 64);
        if(log_guid.some(b => b !== 0))
        {
            throw this.error("the image has a log to replay (the log GUID is set): v86 does not replay logs; open and " +
                "close it once with a tool that does (e.g. qemu-img check -r all, Hyper-V)", "unsupported");
        }

        // the region tables: the first valid one
        let regions = null;
        for(const offset of [192 * KiB, 256 * KiB])
        {
            const bytes = await this.read_metadata(offset, 64 * KiB, "the region table at " + offset);
            if(String.fromCharCode(...bytes.subarray(0, 4)) === "regi" && crc32c(bytes, 4) === u32le(bytes, 4))
            {
                regions = bytes.slice();
                break;
            }
        }
        if(!regions) throw this.error("neither region table is valid (signature, CRC-32C)");
        const region_count = u32le(regions, 8);
        if(region_count > 2047) throw this.error(region_count + " regions is too many");
        let bat_region = null, metadata_region = null;
        for(let i = 0; i < region_count; i++)
        {
            const entry = 16 + i * 32;
            const id = guid(regions, entry);
            const region = {
                offset: to_number(read_u64(regions, entry + 16, true), this.name + ": vhdx: a region's offset"),
                length: u32le(regions, entry + 24),
            };
            if(region.offset % MiB || region.length % MiB) throw this.error("region " + id + " is not aligned to 1 MiB");
            if(id === GUID_BAT) bat_region = region;
            else if(id === GUID_METADATA) metadata_region = region;
            else if(u32le(regions, entry + 28) & 1) throw this.error("an unknown required region " + id, "unsupported");
        }
        if(!bat_region || !metadata_region) throw this.error("the BAT or the metadata region is missing");

        // the metadata
        const metadata = (await this.read_metadata(metadata_region.offset, metadata_region.length, "the metadata region")).slice();
        if(String.fromCharCode(...metadata.subarray(0, 8)) !== "metadata") throw this.error("no metadata table");
        const item_count = metadata[10] | metadata[11] << 8;
        if(item_count > 2047) throw this.error(item_count + " metadata items is too many");
        const items = new Map();
        for(let i = 0; i < item_count; i++)
        {
            const entry = 32 + i * 32;
            const id = guid(metadata, entry);
            const offset = u32le(metadata, entry + 16), length = u32le(metadata, entry + 20), flags = u32le(metadata, entry + 24);
            if(length && (offset < 64 * KiB || offset + length > metadata.length))
            {
                throw this.error("metadata item " + id + " (" + length + " bytes at " + offset + ") is outside the region");
            }
            if(!KNOWN_METADATA.includes(id) && flags & 4) throw this.error("an unknown required metadata item " + id, "unsupported");
            items.set(id, metadata.subarray(offset, offset + length));
        }
        const item = (id, length) =>
        {
            const data = items.get(id);
            if(!data || data.length < length) throw this.error("the metadata item " + id + " is missing");
            return data;
        };
        const parameters = item(GUID_FILE_PARAMETERS, 8);
        this.block_size = u32le(parameters, 0);
        const has_parent = !!(u32le(parameters, 4) & 2);
        if(this.block_size < MiB || this.block_size > 256 * MiB || this.block_size & this.block_size - 1)
        {
            throw this.error("the block size " + this.block_size + " is invalid (a power of two from 1 to 256 MiB)");
        }
        if(has_parent || items.has(GUID_PARENT_LOCATOR))
        {
            throw this.error("a differencing disk (with a parent): not supported", "unsupported");
        }
        const size = to_number(read_u64(item(GUID_VIRTUAL_DISK_SIZE, 8), 0, true), this.name + ": vhdx: the virtual size");
        const logical_sector_size = u32le(item(GUID_LOGICAL_SECTOR_SIZE, 4), 0);
        this.physical_sector_size = u32le(item(GUID_PHYSICAL_SECTOR_SIZE, 4), 0);
        if(logical_sector_size !== 512 && logical_sector_size !== 4096 ||
            this.physical_sector_size !== 512 && this.physical_sector_size !== 4096)
        {
            throw this.error("sector sizes " + logical_sector_size + "/" + this.physical_sector_size + " are invalid");
        }
        // (the disk's: open_image checks the descriptor's against it)
        this.logical_sector_size = this.own_sector_size = logical_sector_size;
        if(size % this.logical_sector_size) throw this.error("the virtual size " + size + " is not a multiple of the sector size");
        this.virtual_size = size;

        // the BAT: a sector bitmap entry after each chunk of payload blocks
        this.chunk_ratio = 2 ** 23 * logical_sector_size / this.block_size;
        const payload_blocks = Math.ceil(size / this.block_size);
        this.bat_entries = payload_blocks + Math.floor((payload_blocks - 1) / this.chunk_ratio);
        if(this.bat_entries * 8 > bat_region.length) throw this.error("the BAT region is too small for the disk");
        if(this.bat_entries * 8 > MAX_BAT_BYTES) throw this.error("the BAT is too large", "unsupported");
        this.bat = (await this.read_metadata(bat_region.offset, this.bat_entries * 8, "the BAT")).slice();
        for(let block = 0; block < payload_blocks; block++)
        {
            const state = this.bat[this.bat_index(block) * 8] & 7;
            if(state === 4 || state === PAYLOAD_PARTIALLY_PRESENT)
            {
                throw this.error("the BAT entry of block " + block + " has the state " + state + " (not of a disk without a parent)");
            }
        }
        this.metadata_sha256 = sha256_hex(header, regions, metadata, this.bat);
    }

    /**
     * @param {number} block a payload block
     * @return {number} its BAT entry
     */
    bat_index(block)
    {
        return block + Math.floor(block / this.chunk_ratio);
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        const extents = [];
        const end = offset + length;
        for(let position = offset; position < end;)
        {
            const block = Math.floor(position / this.block_size);
            const in_block = position - block * this.block_size;
            const count = Math.min(this.block_size - in_block, end - position);
            const index = this.bat_index(block) * 8;
            const state = this.bat[index] & 7;
            if(state === PAYLOAD_FULLY_PRESENT)
            {
                // FileOffsetMB: bits 20-63
                const file_offset = Number(read_u64(this.bat, index, true) >> big(20)) * MiB;
                push_extent(extents, EXTENT_DATA, count, file_offset + in_block);
            }
            else if(state === PAYLOAD_NOT_PRESENT || state === PAYLOAD_UNDEFINED || state === PAYLOAD_ZERO ||
                state === PAYLOAD_UNMAPPED || state === PAYLOAD_UNMAPPED_V095)
            {
                push_extent(extents, EXTENT_ZERO, count);
            }
            else
            {
                callback(undefined, this.error("the BAT entry of block " + block + " has the state " + state));
                return;
            }
            position += count;
        }
        callback(extents);
    }
}
                                                                                                                                                                                                                              source/v64/src/image/vmdk.js                                                                        0000644 0000000 0000000 00000057452 00000000000 013051  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // VMDK images (docs/disk-image-formats-plan.md P4; the format: VMware's
// Virtual Disk Format 1.1 and QEMU's vmdk driver). What is read:
//
// | createType | extents | status |
// | --- | --- | --- |
// | monolithicSparse | one hosted sparse extent with the descriptor in it | supported |
// | streamOptimized | one sparse extent, compressed grains with markers | supported |
// | monolithicFlat, vmfs | a descriptor file and one flat extent | supported (files) |
// | twoGbMaxExtentSparse | a descriptor file and sparse extents | supported (files) |
// | twoGbMaxExtentFlat | a descriptor file and flat extents | supported (files) |
// | a sparse extent alone | its capacity, no descriptor | supported |
// | vmfsSparse, vmfsThin, seSparse, custom, fullDevice, partitionedDevice, ... | | refused |
//
// Extent types FLAT, VMFS, SPARSE and ZERO; RW and RDONLY. The files a
// descriptor names come from the descriptor's `files` (by name); none is
// loaded by its name alone. A child (parentCID) needs its parent as backing,
// a VMDK whose CID is the child's parentCID.

import { DiskImageError } from "./source.js";
import { ImageReader, EXTENT_DATA, EXTENT_ZERO, EXTENT_PARENT, EXTENT_COMPRESSED, push_extent, read_u64, to_number, big } from "./disk_image.js";
import { sha256_hex } from "./sha256.js";
import { inflate } from "../virt/inflate.js";

const SPARSE_MAGIC = 0x564D444B; // "KDMV" read little-endian
const FLAG_ZEROED_GRAIN = 1 << 2;
const FLAG_COMPRESSED = 1 << 16;
const FLAG_MARKERS = 1 << 17;
const GD_AT_END = big("0xFFFFFFFFFFFFFFFF");
const GTE_ZEROED = 1;
const MARKER_END_OF_STREAM = 0;
const MARKER_FOOTER = 3;
const NO_PARENT = "ffffffff";

const SUPPORTED_TYPES = ["monolithicSparse", "streamOptimized", "monolithicFlat", "vmfs", "twoGbMaxExtentSparse", "twoGbMaxExtentFlat"];

// grain tables kept (bytes)
const GT_CACHE_SIZE = 4 * 1024 * 1024;

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 * @return {number}
 */
function u32le(bytes, offset)
{
    return (bytes[offset] | bytes[offset + 1] << 8 | bytes[offset + 2] << 16 | bytes[offset + 3] << 24) >>> 0;
}

/**
 * Adler-32 (RFC 1950), the checksum after a zlib stream
 * @param {!Uint8Array} bytes
 * @return {number}
 */
function adler32(bytes)
{
    let a = 1, b = 0;
    for(let i = 0; i < bytes.length;)
    {
        // (5552 bytes keep the sums below 2^32)
        const end = Math.min(bytes.length, i + 5552);
        for(; i < end; i++)
        {
            a += bytes[i];
            b += a;
        }
        a %= 65521;
        b %= 65521;
    }
    return (b << 16 | a) >>> 0;
}

/**
 * A descriptor's fields and extents
 * @param {string} text
 * @param {string} name for messages
 * @return {!Object}
 */
export function parse_descriptor(text, name)
{
    const fields = Object.create(null);
    const extents = [];
    for(const raw_line of text.split(/\r?\n/))
    {
        const line = raw_line.replace(/\0.*$/, "").trim();
        if(!line || line.startsWith("#")) continue;
        const extent = /^(RW|RDONLY|NOACCESS)\s+(\d+)\s+(FLAT|SPARSE|ZERO|VMFS|VMFSSPARSE|VMFSRDM|VMFSRAW)(?:\s+"([^"]*)"(?:\s+(\d+))?)?\s*$/.exec(line);
        if(extent)
        {
            extents.push({ access: extent[1], sectors: +extent[2], type: extent[3], file: extent[4] || "",
                offset: extent[5] === undefined ? 0 : +extent[5] });
            continue;
        }
        const field = /^([A-Za-z0-9_.]+)\s*=\s*"?([^"]*)"?\s*$/.exec(line);
        if(field)
        {
            fields[field[1]] = field[2];
            continue;
        }
        if(/^(RW|RDONLY|NOACCESS)\s/.test(line))
        {
            throw new DiskImageError(name + ": vmdk: an extent line that is not understood: " + JSON.stringify(line), "unsupported");
        }
    }
    return {
        version: fields["version"],
        cid: (fields["CID"] || "").toLowerCase(),
        parent_cid: (fields["parentCID"] || NO_PARENT).toLowerCase(),
        create_type: fields["createType"] || "",
        parent_hint: fields["parentFileNameHint"] || "",
        extents,
    };
}

export class VMDKReader extends ImageReader
{
    /**
     * @param {?} source the descriptor file, or the sparse extent with its descriptor
     * @param {string} name
     * @param {{open_extent_source: (function(string):!Promise<?>|undefined)}=} options
     */
    constructor(source, name, options)
    {
        super(source, name);
        this.format = "vmdk";
        /** opens a file a descriptor names (src/image/factory.js: from `files`) */
        this.open_extent_source = options && options.open_extent_source;
        this.create_type = "";
        this.cid = "";
        this.parent_cid = NO_PARENT;
        /** @type {!Array<!Object>} the extents in order: start, length, type, source, ... */
        this.extents = [];
        /** @type {!Map<string, !Uint8Array>} grain tables by extent number and offset */
        this.gt_cache = new Map();
        this.gt_cache_bytes = 0;
        /** @type {!Map<string, !Array<function((Error|undefined))>>} */
        this.gt_loading = new Map();
    }

    /**
     * @param {string} what
     * @param {string=} kind
     * @return {!DiskImageError}
     */
    error(what, kind)
    {
        return new DiskImageError(this.name + ": vmdk: " + what, kind || "corrupt");
    }

    /**
     * @param {?} source
     * @param {number} offset
     * @param {number} length
     * @param {string} what
     * @return {!Promise<!Uint8Array>}
     */
    read_from(source, offset, length, what)
    {
        return new Promise((resolve, reject) =>
        {
            if(offset < 0 || offset + length > source.byteLength)
            {
                reject(this.error(what + " (" + length + " bytes at " + offset + ") is past the end of " + source.name +
                    " (" + source.byteLength + " bytes): the file is truncated or corrupt"));
                return;
            }
            source.read(offset, length, (data, error) => error ? reject(error) : resolve(data));
        });
    }

    /** @param {function((Error|undefined))} callback */
    open(callback)
    {
        this.parse().then(() => callback(undefined), error => callback(/** @type {!Error} */ (error)));
    }

    async parse()
    {
        const metadata = [];
        const head = await this.read_from(this.source, 0, Math.min(this.source.byteLength, 512), "the header");
        let descriptor;
        if(head.length >= 4 && u32le(head, 0) === SPARSE_MAGIC)
        {
            // a sparse extent, with its descriptor (monolithicSparse,
            // streamOptimized) or alone
            const sparse = await this.open_sparse(this.source, metadata);
            if(sparse.descriptor_text)
            {
                descriptor = parse_descriptor(sparse.descriptor_text, this.name);
                metadata.push(new TextEncoder().encode(sparse.descriptor_text));
                if(descriptor.extents.length !== 1 || descriptor.extents[0].type !== "SPARSE")
                {
                    throw this.error("the descriptor in a sparse file names " + descriptor.extents.length +
                        " extents (" + descriptor.extents.map(e => e.type).join(", ") + "), not its one sparse extent");
                }
                const extent = descriptor.extents[0];
                if(extent.sectors > sparse.capacity)
                {
                    throw this.error("the extent (" + extent.sectors + " sectors) is larger than its capacity (" + sparse.capacity + ")");
                }
                this.extents.push({ ...sparse, start: 0, length: extent.sectors * 512, readonly: extent.access !== "RW" });
            }
            else
            {
                descriptor = { cid: "", parent_cid: NO_PARENT, create_type: "monolithicSparse", parent_hint: "", extents: [] };
                this.extents.push({ ...sparse, start: 0, length: sparse.capacity * 512 });
            }
        }
        else
        {
            const text = new TextDecoder().decode(await this.read_from(this.source, 0, Math.min(this.source.byteLength, 1 << 20), "the descriptor"));
            if(!/^\s*#\s*Disk DescriptorFile/.test(text)) throw this.error("neither a descriptor nor a sparse extent");
            if(this.source.byteLength > 1 << 20) throw this.error("the descriptor file is larger than 1 MiB", "unsupported");
            descriptor = parse_descriptor(text, this.name);
            metadata.push(new TextEncoder().encode(text));
            let start = 0;
            for(const [index, extent] of descriptor.extents.entries())
            {
                const length = extent.sectors * 512;
                if(extent.access === "NOACCESS") throw this.error("extent " + index + " is NOACCESS: not supported", "unsupported");
                if(extent.type === "ZERO")
                {
                    this.extents.push({ type: "ZERO", start, length });
                }
                else if(extent.type === "FLAT" || extent.type === "VMFS")
                {
                    const source = await this.extent_source(extent.file);
                    const offset = extent.offset * 512;
                    if(offset + length > source.byteLength)
                    {
                        throw this.error("the flat extent " + extent.file + " (" + length + " bytes at " + offset +
                            ") is past the end of its file (" + source.byteLength + " bytes)");
                    }
                    this.extents.push({ type: "FLAT", start, length, source, offset });
                }
                else if(extent.type === "SPARSE")
                {
                    const source = await this.extent_source(extent.file);
                    const sparse = await this.open_sparse(source, metadata);
                    if(extent.sectors > sparse.capacity)
                    {
                        throw this.error("the sparse extent " + extent.file + " (" + extent.sectors +
                            " sectors) is larger than its capacity (" + sparse.capacity + ")");
                    }
                    this.extents.push({ ...sparse, start, length });
                }
                else
                {
                    throw this.error("extents of type " + extent.type + " are not supported", "unsupported");
                }
                start += length;
            }
        }
        if(descriptor.create_type && !SUPPORTED_TYPES.includes(descriptor.create_type))
        {
            throw this.error("createType " + descriptor.create_type + " is not supported (" + SUPPORTED_TYPES.join(", ") + ")", "unsupported");
        }
        this.create_type = descriptor.create_type;
        this.cid = descriptor.cid;
        this.parent_cid = descriptor.parent_cid;
        if(this.parent_cid !== NO_PARENT)
        {
            this.parent_link = { "parent_cid": this.parent_cid, "parent_file_name_hint": descriptor.parent_hint };
        }
        const size = this.extents.reduce((sum, e) => sum + e.length, 0);
        if(size === 0) throw this.error("no extents");
        if(!Number.isSafeInteger(size)) throw this.error("the disk is too large", "unsupported");
        this.virtual_size = size;
        this.extents.forEach((extent, index) => { extent.index = index; });
        this.metadata_sha256 = sha256_hex(...metadata);
    }

    /**
     * The source of a file a descriptor names
     * @param {string} file
     * @return {!Promise<?>}
     */
    async extent_source(file)
    {
        if(!this.open_extent_source)
        {
            throw this.error("the descriptor names the file " + JSON.stringify(file) + ": give it in files", "config");
        }
        return this.open_extent_source(file);
    }

    /**
     * A hosted sparse extent: header (or the footer of a stream), grain
     * directory, the descriptor in it
     * @param {?} source
     * @param {!Array<!Uint8Array>} metadata
     * @return {!Promise<!Object>}
     */
    async open_sparse(source, metadata)
    {
        let header = (await this.read_from(source, 0, 512, "the sparse header")).slice();
        const where = source.name || this.name;
        if(u32le(header, 0) !== SPARSE_MAGIC) throw this.error(where + ": no sparse header (KDMV)");
        const version = u32le(header, 4);
        if(version < 1 || version > 3) throw this.error(where + ": sparse version " + version + " is not supported", "unsupported");
        const descriptor_offset = to_number(read_u64(header, 28, true), "the descriptor offset") * 512;
        const descriptor_size = to_number(read_u64(header, 36, true), "the descriptor size") * 512;
        if(read_u64(header, 56, true) === GD_AT_END)
        {
            // a stream: the footer (after a marker, before the end-of-stream
            // marker) has the grain directory's place
            const length = source.byteLength;
            if(length < 1536) throw this.error(where + ": a stream without its footer");
            const end = await this.read_from(source, length - 1536, 1536, "the stream's footer");
            if(u32le(end, 12) !== MARKER_FOOTER || u32le(end, 8) !== 0 || u32le(end, 512) !== SPARSE_MAGIC ||
                u32le(end, 1024 + 12) !== MARKER_END_OF_STREAM || u32le(end, 1024 + 8) !== 0 || read_u64(end, 1024, true) !== big(0))
            {
                throw this.error(where + ": the stream's footer is invalid");
            }
            header = end.slice(512, 1024);
        }
        metadata.push(header);
        const flags = u32le(header, 8);
        const capacity = to_number(read_u64(header, 12, true), where + ": the capacity");
        const grain_sectors = to_number(read_u64(header, 20, true), where + ": the grain size");
        const gtes_per_gt = u32le(header, 44);
        const gd_offset = to_number(read_u64(header, 56, true), where + ": the grain directory's offset") * 512;
        const compress = header[77] | header[78] << 8;
        if(grain_sectors < 8 || grain_sectors & grain_sectors - 1 || grain_sectors > 0x200000)
        {
            throw this.error(where + ": the grain size " + grain_sectors + " sectors is invalid");
        }
        if(gtes_per_gt === 0 || gtes_per_gt > 512) throw this.error(where + ": " + gtes_per_gt + " entries per grain table is invalid");
        const compressed = !!(flags & FLAG_COMPRESSED);
        if(compressed && compress !== 1) throw this.error(where + ": compression algorithm " + compress + " is not supported", "unsupported");
        const grain_bytes = grain_sectors * 512;
        const gd_entries = Math.ceil(capacity / (grain_sectors * gtes_per_gt));
        if(gd_entries * 4 > 32 * 1024 * 1024) throw this.error(where + ": the grain directory is too large", "unsupported");
        const gd = (await this.read_from(source, gd_offset, gd_entries * 4, "the grain directory")).slice();
        metadata.push(gd);
        let descriptor_text = "";
        if(descriptor_offset && descriptor_size)
        {
            const bytes = await this.read_from(source, descriptor_offset, descriptor_size, "the embedded descriptor");
            const end = bytes.indexOf(0);
            descriptor_text = new TextDecoder().decode(end < 0 ? bytes : bytes.subarray(0, end));
        }
        return {
            type: "SPARSE", source, capacity, grain_bytes, gtes_per_gt, gd, compressed,
            markers: !!(flags & FLAG_MARKERS), zeroed_grain: !!(flags & FLAG_ZEROED_GRAIN), descriptor_text,
        };
    }

    /**
     * A grain table of an extent (cached)
     * @param {!Object} extent
     * @param {number} offset
     * @param {function((Error|undefined))} callback
     */
    load_gt(extent, offset, callback)
    {
        const key = extent.index + ":" + offset;
        const waiting = this.gt_loading.get(key);
        if(waiting)
        {
            waiting.push(callback);
            return;
        }
        const callbacks = [callback];
        this.gt_loading.set(key, callbacks);
        const finish = error =>
        {
            this.gt_loading.delete(key);
            for(const f of callbacks) f(error);
        };
        const length = extent.gtes_per_gt * 4;
        if(offset + length > extent.source.byteLength)
        {
            finish(this.error("the grain table at " + offset + " is past the end of " + extent.source.name));
            return;
        }
        this.stats.table_reads++;
        extent.source.read(offset, length, (data, error) =>
        {
            if(error)
            {
                finish(error);
                return;
            }
            this.gt_cache.set(key, data.slice());
            this.gt_cache_bytes += length;
            while(this.gt_cache_bytes > GT_CACHE_SIZE && this.gt_cache.size > 1)
            {
                const oldest = this.gt_cache.keys().next().value;
                this.gt_cache_bytes -= this.gt_cache.get(oldest).length;
                this.gt_cache.delete(oldest);
            }
            finish(undefined);
        });
    }

    /**
     * @param {number} offset
     * @param {number} length
     * @param {function((Array<!Object>|undefined), (Error|undefined)=)} callback
     * @param {AbortSignal=} signal
     */
    map(offset, length, callback, signal)
    {
        // the grain tables needed that are not cached
        const missing = [];
        this.walk(offset, length, (extent, in_extent, count) =>
        {
            if(extent.type !== "SPARSE") return;
            const grains_per_gt = extent.gtes_per_gt;
            const first = Math.floor(in_extent / extent.grain_bytes), last = Math.floor((in_extent + count - 1) / extent.grain_bytes);
            for(let gd_index = Math.floor(first / grains_per_gt); gd_index <= Math.floor(last / grains_per_gt); gd_index++)
            {
                const gt_offset = u32le(extent.gd, gd_index * 4) * 512;
                if(gt_offset && !this.gt_cache.has(extent.index + ":" + gt_offset)) missing.push([extent, gt_offset]);
            }
        });
        if(!missing.length)
        {
            this.stats.table_hits++;
            this.build(offset, length, callback, signal);
            return;
        }
        let pending = missing.length, failed = false;
        for(const [extent, gt_offset] of missing)
        {
            this.load_gt(extent, gt_offset, error =>
            {
                if(failed) return;
                if(error)
                {
                    failed = true;
                    callback(undefined, error);
                    return;
                }
                if(--pending === 0) this.build(offset, length, callback, signal);
            });
        }
    }

    /**
     * Call f(extent, offset in the extent, count) for the parts of
     * [offset, offset + length) in each extent
     */
    walk(offset, length, f)
    {
        const end = offset + length;
        for(const extent of this.extents)
        {
            const from = Math.max(offset, extent.start), to = Math.min(end, extent.start + extent.length);
            if(from < to) f(extent, from - extent.start, to - from);
        }
    }

    build(offset, length, callback, signal)
    {
        const extents = [];
        let failed;
        this.walk(offset, length, (extent, in_extent, count) =>
        {
            if(failed) return;
            if(extent.type === "ZERO")
            {
                push_extent(extents, EXTENT_ZERO, count);
                return;
            }
            if(extent.type === "FLAT")
            {
                push_extent(extents, EXTENT_DATA, count, extent.offset + in_extent, extent.source);
                return;
            }
            const end = in_extent + count;
            for(let position = in_extent; position < end;)
            {
                const grain = Math.floor(position / extent.grain_bytes);
                const in_grain = position - grain * extent.grain_bytes;
                const n = Math.min(extent.grain_bytes - in_grain, end - position);
                const gt_offset = u32le(extent.gd, Math.floor(grain / extent.gtes_per_gt) * 4) * 512;
                let entry = 0;
                if(gt_offset)
                {
                    const table = this.gt_cache.get(extent.index + ":" + gt_offset);
                    if(!table)
                    {
                        // evicted meanwhile: map the rest again
                        failed = true;
                        const rest_start = extent.start + position;
                        this.map(rest_start, offset + length - rest_start, (rest, error) =>
                        {
                            if(error) callback(undefined, error);
                            else callback(extents.concat(rest));
                        }, signal);
                        return;
                    }
                    entry = u32le(table, grain % extent.gtes_per_gt * 4);
                }
                if(entry === 0)
                {
                    push_extent(extents, EXTENT_PARENT, n);
                }
                else if(entry === GTE_ZEROED && extent.zeroed_grain)
                {
                    push_extent(extents, EXTENT_ZERO, n);
                }
                else if(extent.compressed)
                {
                    const host_offset = entry * 512;
                    extents.push({ type: EXTENT_COMPRESSED, length: n, host_offset, source: extent.source,
                        host_length: Math.min(extent.grain_bytes + 4096, extent.source.byteLength - host_offset),
                        cluster_start: in_grain, grain_bytes: extent.grain_bytes, markers: extent.markers,
                        key: extent.index * 2 ** 40 + entry });
                }
                else
                {
                    push_extent(extents, EXTENT_DATA, n, entry * 512 + in_grain, extent.source);
                }
                position += n;
            }
        });
        if(!failed) callback(extents);
    }

    /**
     * A compressed grain: after a marker (the grain's sector, the data's
     * length) with markers, zlib data (RFC 1950)
     * @param {!Uint8Array} bytes
     * @param {!Object} extent
     * @return {!Uint8Array}
     */
    decompress(bytes, extent)
    {
        let data = bytes;
        if(extent.markers)
        {
            if(bytes.length < 12) throw this.error("a grain marker at " + extent.host_offset + " is cut off");
            const size = u32le(bytes, 8);
            if(size === 0 || size > bytes.length - 12)
            {
                throw this.error("the grain marker at " + extent.host_offset + " has the size " + size);
            }
            data = bytes.subarray(12, 12 + size);
        }
        const cmf = data[0], flg = data[1];
        if((cmf & 0x0F) !== 8 || ((cmf << 8) + flg) % 31 || flg & 0x20)
        {
            throw this.error("the grain at " + extent.host_offset + " is not zlib data");
        }
        const { output, end } = inflate(data, 2, extent.grain_bytes, extent.grain_bytes);
        if(output.length < extent.cluster_start + extent.length)
        {
            throw this.error("the grain at " + extent.host_offset + " has " + output.length + " bytes, " +
                (extent.cluster_start + extent.length) + " are needed");
        }
        // the stream ends with the data's Adler-32 (as zlib's uncompress,
        // which QEMU uses, checks)
        const sum = end + 4 <= data.length ? (data[end] << 24 | data[end + 1] << 16 | data[end + 2] << 8 | data[end + 3]) >>> 0 : -1;
        if(sum !== adler32(output))
        {
            throw this.error("the grain at " + extent.host_offset + " has a wrong Adler-32 checksum");
        }
        return output;
    }

    /**
     * A parent: a VMDK whose CID is this one's parentCID
     * @param {!ImageReader} parent
     */
    check_parent(parent)
    {
        if(parent.format !== "vmdk")
        {
            throw this.error("the parent is " + parent.format + ": a VMDK's parent is a VMDK", "config");
        }
        if(/** @type {!VMDKReader} */ (parent).cid !== this.parent_cid)
        {
            throw this.error("the parent's CID is " + /** @type {!VMDKReader} */ (parent).cid + ", this image's parentCID " +
                this.parent_cid + ": not its parent", "config");
        }
    }
}
                                                                                                                                                                                                                      source/v64/src/io.js                                                                                0000644 0000000 0000000 00000047100 00000000000 011422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_IO, MMAP_BLOCK_BITS, MMAP_BLOCK_SIZE, MMAP_MAX } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";

// Enables logging all IO port reads and writes. Very verbose
const LOG_ALL_IO = false;

/**
 * The ISA IO bus
 * Devices register their ports here
 *
 * @constructor
 * @param {CPU} cpu
 */
export function IO(cpu)
{
    /** @const */
    this.ports = [];

    /** @const @type {CPU} */
    this.cpu = cpu;

    for(var i = 0; i < 0x10000; i++)
    {
        this.ports[i] = this.create_empty_entry();
    }

    var memory_size = cpu.memory_size[0];

    for(var i = 0; (i << MMAP_BLOCK_BITS) < memory_size; i++)
    {
        // avoid sparse arrays
        cpu.memory_map_read8[i] = cpu.memory_map_write8[i] = undefined;
        cpu.memory_map_read32[i] = cpu.memory_map_write32[i] = undefined;
    }

    // (kept for mmap_unregister)
    this.unmapped = [
        function(addr) {
            // read outside of the memory size
            dbg_log("Read from unmapped memory space, addr=" + h(addr >>> 0, 8), LOG_IO);
            return 0xFF;
        },
        function(addr, value) {
            // write outside of the memory size
            dbg_log("Write to unmapped memory space, addr=" + h(addr >>> 0, 8) + " value=" + h(value, 2), LOG_IO);
        },
        function(addr) {
            dbg_log("Read from unmapped memory space, addr=" + h(addr >>> 0, 8), LOG_IO);
            return -1;
        },
        function(addr, value) {
            dbg_log("Write to unmapped memory space, addr=" + h(addr >>> 0, 8) + " value=" + h(value >>> 0, 8), LOG_IO);
        },
    ];
    this.mmap_register(memory_size, MMAP_MAX - memory_size, this.unmapped[0], this.unmapped[1], this.unmapped[2], this.unmapped[3]);
}

IO.prototype.create_empty_entry = function()
{
    return {
        read8: this.empty_port_read8,
        read16: this.empty_port_read16,
        read32: this.empty_port_read32,

        write8: this.empty_port_write,
        write16: this.empty_port_write,
        write32: this.empty_port_write,

        device: undefined,
    };
};

IO.prototype.empty_port_read8 = function()
{
    return 0xFF;
};

IO.prototype.empty_port_read16 = function()
{
    return 0xFFFF;
};

IO.prototype.empty_port_read32 = function()
{
    return -1;
};

IO.prototype.empty_port_write = function(x)
{
};


/**
 * Remove the handlers of a device from a range of ports (for devices whose
 * decode can move, like the ACPI PM block)
 * @param {number} port_addr
 * @param {number} length
 * @param {Object} device
 */
IO.prototype.unregister_range = function(port_addr, length, device)
{
    for(let port = port_addr; port < port_addr + length; port++)
    {
        if(this.ports[port].device === device)
        {
            this.ports[port] = this.create_empty_entry();
        }
    }
};

/**
 * @param {number} port_addr
 * @param {Object} device
 * @param {function(number):number=} r8
 * @param {function(number):number=} r16
 * @param {function(number):number=} r32
 */
IO.prototype.register_read = function(port_addr, device, r8, r16, r32)
{
    dbg_assert(typeof port_addr === "number");
    dbg_assert(typeof device === "object");
    dbg_assert(!r8 || typeof r8 === "function");
    dbg_assert(!r16 || typeof r16 === "function");
    dbg_assert(!r32 || typeof r32 === "function");
    dbg_assert(r8 || r16 || r32);

    if(DEBUG)
    {
        var fail = function(n) {
            dbg_assert(false, "Overlapped read" + n + " " + h(port_addr, 4) + " (" + device.name + ")");
            return -1 >>> (32 - n) | 0;
        };
        if(!r8) r8 = fail.bind(this, 8);
        if(!r16) r16 = fail.bind(this, 16);
        if(!r32) r32 = fail.bind(this, 32);
    }

    if(r8) this.ports[port_addr].read8 = r8;
    if(r16) this.ports[port_addr].read16 = r16;
    if(r32) this.ports[port_addr].read32 = r32;
    this.ports[port_addr].device = device;
};

/**
 * @param {number} port_addr
 * @param {Object} device
 * @param {function(number)=} w8
 * @param {function(number)=} w16
 * @param {function(number)=} w32
 */
IO.prototype.register_write = function(port_addr, device, w8, w16, w32)
{
    dbg_assert(typeof port_addr === "number");
    dbg_assert(typeof device === "object");
    dbg_assert(!w8 || typeof w8 === "function");
    dbg_assert(!w16 || typeof w16 === "function");
    dbg_assert(!w32 || typeof w32 === "function");
    dbg_assert(w8 || w16 || w32);

    if(DEBUG)
    {
        var fail = function(n) {
            dbg_assert(false, "Overlapped write" + n + " " + h(port_addr) + " (" + device.name + ")");
        };
        if(!w8) w8 = fail.bind(this, 8);
        if(!w16) w16 = fail.bind(this, 16);
        if(!w32) w32 = fail.bind(this, 32);
    }

    if(w8) this.ports[port_addr].write8 = w8;
    if(w16) this.ports[port_addr].write16 = w16;
    if(w32) this.ports[port_addr].write32 = w32;
    this.ports[port_addr].device = device;
};

/**
 * > Any two consecutive 8-bit ports can be treated as a 16-bit port;
 * > and four consecutive 8-bit ports can be treated as a 32-bit port
 * > http://css.csail.mit.edu/6.858/2012/readings/i386/s08_01.htm
 *
 * This info is not correct for all ports, but handled by the following functions
 *
 * Register the write of 2 or 4 consecutive 8-bit ports, 1 or 2 16-bit
 * ports and 0 or 1 32-bit ports
 *
 * @param {number} port_addr
 * @param {!Object} device
 * @param {function():number} r8_1
 * @param {function():number} r8_2
 * @param {function():number=} r8_3
 * @param {function():number=} r8_4
 */
IO.prototype.register_read_consecutive = function(port_addr, device, r8_1, r8_2, r8_3, r8_4)
{
    dbg_assert(arguments.length === 4 || arguments.length === 6);

    function r16_1()
    {
        return r8_1.call(this) |
                r8_2.call(this) << 8;
    }
    function r16_2()
    {
        return r8_3.call(this) |
                r8_4.call(this) << 8;
    }
    function r32()
    {
        return r8_1.call(this) |
                r8_2.call(this) << 8 |
                r8_3.call(this) << 16 |
                r8_4.call(this) << 24;
    }

    if(r8_3 && r8_4)
    {
        this.register_read(port_addr, device, r8_1, r16_1, r32);
        this.register_read(port_addr + 1, device, r8_2);
        this.register_read(port_addr + 2, device, r8_3, r16_2);
        this.register_read(port_addr + 3, device, r8_4);
    }
    else
    {
        this.register_read(port_addr, device, r8_1, r16_1);
        this.register_read(port_addr + 1, device, r8_2);
    }
};

/**
 * @param {number} port_addr
 * @param {!Object} device
 * @param {function(number)} w8_1
 * @param {function(number)} w8_2
 * @param {function(number)=} w8_3
 * @param {function(number)=} w8_4
 */
IO.prototype.register_write_consecutive = function(port_addr, device, w8_1, w8_2, w8_3, w8_4)
{
    dbg_assert(arguments.length === 4 || arguments.length === 6);

    function w16_1(data)
    {
        w8_1.call(this, data & 0xFF);
        w8_2.call(this, data >> 8 & 0xFF);
    }
    function w16_2(data)
    {
        w8_3.call(this, data & 0xFF);
        w8_4.call(this, data >> 8 & 0xFF);
    }
    function w32(data)
    {
        w8_1.call(this, data & 0xFF);
        w8_2.call(this, data >> 8 & 0xFF);
        w8_3.call(this, data >> 16 & 0xFF);
        w8_4.call(this, data >>> 24);
    }

    if(w8_3 && w8_4)
    {
        this.register_write(port_addr,     device, w8_1, w16_1, w32);
        this.register_write(port_addr + 1, device, w8_2);
        this.register_write(port_addr + 2, device, w8_3, w16_2);
        this.register_write(port_addr + 3, device, w8_4);
    }
    else
    {
        this.register_write(port_addr,     device, w8_1, w16_1);
        this.register_write(port_addr + 1, device, w8_2);
    }
};

IO.prototype.mmap_read32_shim = function(addr)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;
    var fn = this.cpu.memory_map_read8[aligned_addr];

    return fn(addr) | fn(addr + 1) << 8 |
            fn(addr + 2) << 16 | fn(addr + 3) << 24;
};

IO.prototype.mmap_write32_shim = function(addr, value)
{
    var aligned_addr = addr >>> MMAP_BLOCK_BITS;
    var fn = this.cpu.memory_map_write8[aligned_addr];

    fn(addr, value & 0xFF);
    fn(addr + 1, value >> 8 & 0xFF);
    fn(addr + 2, value >> 16 & 0xFF);
    fn(addr + 3, value >>> 24);
};

/**
 * @param {number} addr
 * @param {number} size
 * @param {*} read_func8
 * @param {*} write_func8
 * @param {*=} read_func32
 * @param {*=} write_func32
 */
IO.prototype.mmap_register = function(addr, size, read_func8, write_func8, read_func32, write_func32)
{
    dbg_log("mmap_register addr=" + h(addr >>> 0, 8) + " size=" + h(size, 8), LOG_IO);

    dbg_assert((addr & MMAP_BLOCK_SIZE - 1) === 0);
    dbg_assert(size && (size & MMAP_BLOCK_SIZE - 1) === 0);

    if(!read_func32)
        read_func32 = this.mmap_read32_shim.bind(this);

    if(!write_func32)
        write_func32 = this.mmap_write32_shim.bind(this);

    var aligned_addr = addr >>> MMAP_BLOCK_BITS;

    for(; size > 0; aligned_addr++)
    {
        const shared = this.mmio_blocks && this.mmio_blocks.get(aligned_addr);
        if(shared)
        {
            // a block with exact ranges: this becomes what the rest of it decodes
            shared.background = [read_func8, write_func8, read_func32, write_func32];
        }
        else
        {
            this.cpu.memory_map_read8[aligned_addr] = read_func8;
            this.cpu.memory_map_write8[aligned_addr] = write_func8;
            this.cpu.memory_map_read32[aligned_addr] = read_func32;
            this.cpu.memory_map_write32[aligned_addr] = write_func32;
        }

        size -= MMAP_BLOCK_SIZE;
    }
};

/**
 * Map a memory range that need not be made of whole blocks of the memory map
 * (MMAP_BLOCK_SIZE): a small BAR, a chipset register block. Blocks that hold
 * such ranges dispatch every access by address; what the ranges don't cover
 * keeps decoding as before (the block's "background": unmapped, or a device
 * that registered the whole block). Each range has an owner; removing one
 * leaves the other ranges of the block alone.
 * @param {number} addr
 * @param {number} size
 * @param {Object} owner
 * @param {function(number):number} read8
 * @param {function(number, number)} write8
 * @param {function(number):number=} read32 aligned dwords inside the range
 * @param {function(number, number)=} write32
 */
IO.prototype.mmap_register_range = function(addr, size, owner, read8, write8, read32, write32)
{
    addr >>>= 0;
    dbg_log("mmap_register_range addr=" + h(addr, 8) + " size=" + h(size) + " (" + owner.name + ")", LOG_IO);
    dbg_assert(size > 0 && addr + size <= MMAP_MAX);

    if(!this.mmio_blocks)
    {
        /** @type {!Map<number, {ranges: !Array<!Object>, background: !Array<!Function>}>} */
        this.mmio_blocks = new Map();
    }

    const range = { start: addr, end: addr + size, owner, read8, write8, read32, write32 };
    const first = addr >>> MMAP_BLOCK_BITS, last = addr + size - 1 >>> MMAP_BLOCK_BITS;

    // (an error in every build, before anything is mapped: the later range
    // would shadow part of the earlier one; docs/arm64-virt-android16-plan.md P1.7)
    for(let block = first; block <= last; block++)
    {
        for(const other of this.mmio_blocks.get(block)?.ranges || [])
        {
            if(!(other.end <= range.start || range.end <= other.start))
            {
                throw new Error("MMIO range " + h(addr, 8) + " (" + owner.name + ") overlaps " + h(other.start, 8) + " (" + other.owner.name + ")");
            }
        }
    }

    for(let block = first; block <= last; block++)
    {
        let shared = this.mmio_blocks.get(block);
        if(!shared)
        {
            const cpu = this.cpu;
            shared = {
                ranges: [],
                background: [cpu.memory_map_read8[block], cpu.memory_map_write8[block],
                             cpu.memory_map_read32[block], cpu.memory_map_write32[block]],
            };
            this.mmio_blocks.set(block, shared);
            this.install_block_dispatch(block, shared);
        }
        shared.ranges.push(range);
    }
};

/**
 * Remove the ranges of an owner that mmap_register_range mapped at addr
 * @param {number} addr
 * @param {number} size
 * @param {Object} owner
 */
IO.prototype.mmap_unregister_range = function(addr, size, owner)
{
    addr >>>= 0;
    dbg_log("mmap_unregister_range addr=" + h(addr, 8) + " size=" + h(size) + " (" + owner.name + ")", LOG_IO);
    if(!this.mmio_blocks) return;

    for(let block = addr >>> MMAP_BLOCK_BITS; block <= addr + size - 1 >>> MMAP_BLOCK_BITS; block++)
    {
        const shared = this.mmio_blocks.get(block);
        if(!shared) continue;
        shared.ranges = shared.ranges.filter(r => r.owner !== owner || r.start !== addr);
        if(shared.ranges.length === 0)
        {
            // back to the plain block
            const cpu = this.cpu;
            [cpu.memory_map_read8[block], cpu.memory_map_write8[block],
             cpu.memory_map_read32[block], cpu.memory_map_write32[block]] = shared.background;
            this.mmio_blocks.delete(block);
        }
    }
};

/**
 * @param {number} block
 * @param {{ranges: !Array<!Object>, background: !Array<!Function>}} shared
 */
IO.prototype.install_block_dispatch = function(block, shared)
{
    const find = addr => {
        for(const range of shared.ranges)
        {
            if(addr >= range.start && addr < range.end) return range;
        }
        return null;
    };
    const read8 = addr => {
        const range = find(addr >>> 0);
        return range ? range.read8(addr >>> 0) : shared.background[0](addr);
    };
    const write8 = (addr, value) => {
        const range = find(addr >>> 0);
        range ? range.write8(addr >>> 0, value) : shared.background[1](addr, value);
    };
    // A dword inside one range goes to its 32-bit handler; one that
    // straddles a range boundary is split into bytes
    const read32 = addr => {
        const start = addr >>> 0;
        const range = find(start);
        if(range && start + 4 <= range.end && (start & 3) === 0 && range.read32)
        {
            return range.read32(start);
        }
        if(!range && !find(start + 3) && !find(start + 1) && !find(start + 2))
        {
            return shared.background[2](addr);
        }
        return read8(addr) | read8(addr + 1) << 8 | read8(addr + 2) << 16 | read8(addr + 3) << 24;
    };
    const write32 = (addr, value) => {
        const start = addr >>> 0;
        const range = find(start);
        if(range && start + 4 <= range.end && (start & 3) === 0 && range.write32)
        {
            range.write32(start, value);
            return;
        }
        if(!range && !find(start + 3) && !find(start + 1) && !find(start + 2))
        {
            shared.background[3](addr, value);
            return;
        }
        for(let i = 0; i < 4; i++) write8(addr + i, value >>> (i << 3) & 0xFF);
    };

    const cpu = this.cpu;
    cpu.memory_map_read8[block] = read8;
    cpu.memory_map_write8[block] = write8;
    cpu.memory_map_read32[block] = read32;
    cpu.memory_map_write32[block] = write32;
};

/**
 * Give a range back to the unmapped-memory handlers (a device's memory BAR
 * that moved away)
 * @param {number} addr
 * @param {number} size
 */
IO.prototype.mmap_unregister = function(addr, size)
{
    this.mmap_register(addr, size, this.unmapped[0], this.unmapped[1], this.unmapped[2], this.unmapped[3]);
};

IO.prototype.port_write8 = function(port_addr, data)
{
    var entry = this.ports[port_addr];

    if(entry.write8 === this.empty_port_write || LOG_ALL_IO)
    {
        dbg_log(
            "write8 port #" + h(port_addr, 4) + " <- " + h(data, 2) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    return entry.write8.call(entry.device, data);
};

IO.prototype.port_write16 = function(port_addr, data)
{
    var entry = this.ports[port_addr];

    if(entry.write16 === this.empty_port_write || LOG_ALL_IO)
    {
        dbg_log(
            "write16 port #" + h(port_addr, 4) + " <- " + h(data, 4) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    return entry.write16.call(entry.device, data);
};

IO.prototype.port_write32 = function(port_addr, data)
{
    var entry = this.ports[port_addr];

    if(entry.write32 === this.empty_port_write || LOG_ALL_IO)
    {
        dbg_log(
            "write32 port #" + h(port_addr, 4) + " <- " + h(data >>> 0, 8) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    return entry.write32.call(entry.device, data);
};

IO.prototype.port_read8 = function(port_addr)
{
    var entry = this.ports[port_addr];

    if(entry.read8 === this.empty_port_read8 || LOG_ALL_IO)
    {
        dbg_log(
            "read8 port  #" + h(port_addr, 4) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    var value = entry.read8.call(entry.device, port_addr);
    dbg_assert(typeof value === "number");
    if(value < 0 || value >= 0x100) dbg_assert(false, "8 bit port returned large value: " + h(port_addr));
    return value;
};

IO.prototype.port_read16 = function(port_addr)
{
    var entry = this.ports[port_addr];

    if(entry.read16 === this.empty_port_read16 || LOG_ALL_IO)
    {
        dbg_log(
            "read16 port  #" + h(port_addr, 4) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    var value = entry.read16.call(entry.device, port_addr);
    dbg_assert(typeof value === "number");
    if(value < 0 || value >= 0x10000) dbg_assert(false, "16 bit port returned large value: " + h(port_addr));
    return value;
};

IO.prototype.port_read32 = function(port_addr)
{
    var entry = this.ports[port_addr];

    if(entry.read32 === this.empty_port_read32 || LOG_ALL_IO)
    {
        dbg_log(
            "read32 port  #" + h(port_addr, 4) + this.get_port_description(port_addr),
            LOG_IO
        );
    }
    var value = entry.read32.call(entry.device, port_addr);
    dbg_assert((value | 0) === value);
    return value;
};

// via seabios ioport.h
var debug_port_list = {
    0x0004: "PORT_DMA_ADDR_2",
    0x0005: "PORT_DMA_CNT_2",
    0x000a: "PORT_DMA1_MASK_REG",
    0x000b: "PORT_DMA1_MODE_REG",
    0x000c: "PORT_DMA1_CLEAR_FF_REG",
    0x000d: "PORT_DMA1_MASTER_CLEAR",
    0x0020: "PORT_PIC1_CMD",
    0x0021: "PORT_PIC1_DATA",
    0x0040: "PORT_PIT_COUNTER0",
    0x0041: "PORT_PIT_COUNTER1",
    0x0042: "PORT_PIT_COUNTER2",
    0x0043: "PORT_PIT_MODE",
    0x0060: "PORT_PS2_DATA",
    0x0061: "PORT_PS2_CTRLB",
    0x0064: "PORT_PS2_STATUS",
    0x0070: "PORT_CMOS_INDEX",
    0x0071: "PORT_CMOS_DATA",
    0x0080: "PORT_DIAG",
    0x0081: "PORT_DMA_PAGE_2",
    0x0092: "PORT_A20",
    0x00a0: "PORT_PIC2_CMD",
    0x00a1: "PORT_PIC2_DATA",
    0x00b2: "PORT_SMI_CMD",
    0x00b3: "PORT_SMI_STATUS",
    0x00d4: "PORT_DMA2_MASK_REG",
    0x00d6: "PORT_DMA2_MODE_REG",
    0x00da: "PORT_DMA2_MASTER_CLEAR",
    0x00f0: "PORT_MATH_CLEAR",
    0x0170: "PORT_ATA2_CMD_BASE",
    0x01f0: "PORT_ATA1_CMD_BASE",
    0x0278: "PORT_LPT2",
    0x02e8: "PORT_SERIAL4",
    0x02f8: "PORT_SERIAL2",
    0x0374: "PORT_ATA2_CTRL_BASE",
    0x0378: "PORT_LPT1",
    0x03e8: "PORT_SERIAL3",
    //0x03f4: "PORT_ATA1_CTRL_BASE",
    0x03f0: "PORT_FD_BASE",
    0x03f2: "PORT_FD_DOR",
    0x03f4: "PORT_FD_STATUS",
    0x03f5: "PORT_FD_DATA",
    0x03f6: "PORT_HD_DATA",
    0x03f7: "PORT_FD_DIR",
    0x03f8: "PORT_SERIAL1",
    0x0cf8: "PORT_PCI_CMD",
    0x0cf9: "PORT_PCI_REBOOT",
    0x0cfc: "PORT_PCI_DATA",
    0x0402: "PORT_BIOS_DEBUG",
    0x0510: "PORT_QEMU_CFG_CTL",
    0x0511: "PORT_QEMU_CFG_DATA",
    0xb000: "PORT_ACPI_PM_BASE",
    0xb100: "PORT_SMB_BASE",
    0x8900: "PORT_BIOS_APM"
};

IO.prototype.get_port_description = function(addr)
{
    if(debug_port_list[addr])
    {
        return "  (" + debug_port_list[addr] + ")";
    }
    else
    {
        return "";
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/ios/crypto.js                                                                        0000644 0000000 0000000 00000024323 00000000000 013127  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The ciphers and hashes Apple's firmware needs (docs/iphone4-plan.md S0),
// synchronous and in plain JS so that the same code runs in node, in a
// browser worker and on pages that are not a secure context (crypto.subtle
// is missing there): AES (FIPS 197) with CBC and no padding (IMG3 payloads,
// the root filesystem's chunks), SHA-1 (FIPS 180-4; the IPSW's identity,
// HMAC-SHA1 for the root filesystem's chunk IVs) and HMAC (RFC 2104).

const SBOX = new Uint8Array(256), INV_SBOX = new Uint8Array(256);
// (the round tables: T0..T3 encrypt, D0..D3 decrypt, one byte rotation apart)
const T = [0, 1, 2, 3].map(() => new Uint32Array(256)), D = [0, 1, 2, 3].map(() => new Uint32Array(256));

{
    const exp = new Uint8Array(256), log = new Uint8Array(256);
    for(let i = 0, x = 1; i < 255; i++)
    {
        exp[i] = x;
        log[x] = i;
        x ^= x << 1 ^ (x & 0x80 ? 0x11B : 0);
        x &= 0xFF;
    }
    const mul = (a, b) => a && b ? exp[(log[a] + log[b]) % 255] : 0;
    for(let i = 0; i < 256; i++)
    {
        const inv = i ? exp[(255 - log[i]) % 255] : 0;
        let s = inv;
        for(let k = 1; k < 5; k++) s ^= (inv << k | inv >>> 8 - k) & 0xFF;
        s ^= 0x63;
        SBOX[i] = s;
        INV_SBOX[s] = i;
    }
    for(let i = 0; i < 256; i++)
    {
        const s = SBOX[i], v = INV_SBOX[i];
        const e = (mul(s, 2) << 24 | s << 16 | s << 8 | mul(s, 3)) >>> 0;
        const d = (mul(v, 14) << 24 | mul(v, 9) << 16 | mul(v, 13) << 8 | mul(v, 11)) >>> 0;
        for(let r = 0; r < 4; r++)
        {
            T[r][i] = (e >>> 8 * r | e << 32 - 8 * r) >>> 0;
            D[r][i] = (d >>> 8 * r | d << 32 - 8 * r) >>> 0;
        }
    }
}

/**
 * An expanded AES key (128, 192 or 256 bits)
 * @constructor
 * @param {!Uint8Array} key
 */
export function AES(key)
{
    const nk = key.length / 4;
    if(nk !== 4 && nk !== 6 && nk !== 8) throw new Error(`AES: a ${key.length}-byte key`);
    const rounds = this.rounds = nk + 6;
    const w = this.encrypt_keys = new Uint32Array(4 * (rounds + 1));
    for(let i = 0; i < nk; i++) w[i] = (key[4 * i] << 24 | key[4 * i + 1] << 16 | key[4 * i + 2] << 8 | key[4 * i + 3]) >>> 0;
    for(let i = nk, rcon = 1; i < w.length; i++)
    {
        let t = w[i - 1];
        if(i % nk === 0)
        {
            t = (SBOX[t >>> 16 & 0xFF] << 24 | SBOX[t >>> 8 & 0xFF] << 16 | SBOX[t & 0xFF] << 8 | SBOX[t >>> 24]) ^ rcon << 24;
            rcon = rcon << 1 ^ (rcon & 0x80 ? 0x11B : 0);
        }
        else if(nk > 6 && i % nk === 4)
        {
            t = SBOX[t >>> 24] << 24 | SBOX[t >>> 16 & 0xFF] << 16 | SBOX[t >>> 8 & 0xFF] << 8 | SBOX[t & 0xFF];
        }
        w[i] = (w[i - nk] ^ t) >>> 0;
    }
    // (the equivalent inverse cipher's keys: reversed, InvMixColumns on the middle rounds)
    const dk = this.decrypt_keys = new Uint32Array(w.length);
    for(let r = 0; r <= rounds; r++)
    {
        for(let c = 0; c < 4; c++)
        {
            const x = w[4 * (rounds - r) + c];
            dk[4 * r + c] = r === 0 || r === rounds ? x :
                D[0][SBOX[x >>> 24]] ^ D[1][SBOX[x >>> 16 & 0xFF]] ^ D[2][SBOX[x >>> 8 & 0xFF]] ^ D[3][SBOX[x & 0xFF]];
        }
    }
    this.state = new Uint32Array(4);
}

/**
 * One block in place, encrypted (decrypt false) or decrypted
 * @param {!Uint8Array} b
 * @param {number} at
 * @param {boolean} decrypt
 */
AES.prototype.block = function(b, at, decrypt)
{
    const k = decrypt ? this.decrypt_keys : this.encrypt_keys, t = decrypt ? D : T, box = decrypt ? INV_SBOX : SBOX;
    const [t0, t1, t2, t3] = t;
    // (decrypting, the rows shift the other way: the word sources run 3, 2, 1 instead of 1, 2, 3)
    const s1 = decrypt ? 3 : 1, s3 = decrypt ? 1 : 3;
    let a0 = (b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]) ^ k[0];
    let a1 = (b[at + 4] << 24 | b[at + 5] << 16 | b[at + 6] << 8 | b[at + 7]) ^ k[1];
    let a2 = (b[at + 8] << 24 | b[at + 9] << 16 | b[at + 10] << 8 | b[at + 11]) ^ k[2];
    let a3 = (b[at + 12] << 24 | b[at + 13] << 16 | b[at + 14] << 8 | b[at + 15]) ^ k[3];
    const a = this.state;
    for(let r = 1; r < this.rounds; r++)
    {
        a[0] = a0; a[1] = a1; a[2] = a2; a[3] = a3;
        const q = 4 * r;
        a0 = t0[a[0] >>> 24] ^ t1[a[s1] >>> 16 & 0xFF] ^ t2[a[2] >>> 8 & 0xFF] ^ t3[a[s3] & 0xFF] ^ k[q];
        a1 = t0[a[1] >>> 24] ^ t1[a[(1 + s1) & 3] >>> 16 & 0xFF] ^ t2[a[3] >>> 8 & 0xFF] ^ t3[a[(1 + s3) & 3] & 0xFF] ^ k[q + 1];
        a2 = t0[a[2] >>> 24] ^ t1[a[(2 + s1) & 3] >>> 16 & 0xFF] ^ t2[a[0] >>> 8 & 0xFF] ^ t3[a[(2 + s3) & 3] & 0xFF] ^ k[q + 2];
        a3 = t0[a[3] >>> 24] ^ t1[a[(3 + s1) & 3] >>> 16 & 0xFF] ^ t2[a[1] >>> 8 & 0xFF] ^ t3[a[(3 + s3) & 3] & 0xFF] ^ k[q + 3];
    }
    a[0] = a0; a[1] = a1; a[2] = a2; a[3] = a3;
    const q = 4 * this.rounds;
    for(let c = 0; c < 4; c++)
    {
        const x = box[a[c] >>> 24] << 24 | box[a[(c + s1) & 3] >>> 16 & 0xFF] << 16 |
            box[a[(c + 2) & 3] >>> 8 & 0xFF] << 8 | box[a[(c + s3) & 3] & 0xFF];
        const y = x ^ k[q + c];
        b[at + 4 * c] = y >>> 24; b[at + 4 * c + 1] = y >>> 16; b[at + 4 * c + 2] = y >>> 8; b[at + 4 * c + 3] = y;
    }
};

/**
 * CBC without padding, in place: data's length a multiple of 16. Returns the
 * IV for what follows (the last cipher block)
 * @param {!Uint8Array} data
 * @param {!Uint8Array} iv 16 bytes, not changed
 * @param {boolean} decrypt
 * @return {!Uint8Array}
 */
AES.prototype.cbc = function(data, iv, decrypt)
{
    if(data.length % 16) throw new Error(`AES-CBC: ${data.length} bytes, not whole blocks`);
    const chain = new Uint8Array(iv), saved = new Uint8Array(16);
    for(let at = 0; at < data.length; at += 16)
    {
        if(decrypt)
        {
            saved.set(data.subarray(at, at + 16));
            this.block(data, at, true);
            for(let i = 0; i < 16; i++) data[at + i] ^= chain[i];
            chain.set(saved);
        }
        else
        {
            for(let i = 0; i < 16; i++) data[at + i] ^= chain[i];
            this.block(data, at, false);
            chain.set(data.subarray(at, at + 16));
        }
    }
    return chain;
};

/**
 * An incremental SHA-1
 * @constructor
 */
export function SHA1()
{
    this.h = new Int32Array([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
    this.w = new Int32Array(80);
    this.block = new Uint8Array(64);
    this.block_length = 0;
    this.total = 0;
}

/**
 * @param {!Uint8Array} data
 * @return {!SHA1}
 */
SHA1.prototype.update = function(data)
{
    this.total += data.length;
    let i = 0;
    if(this.block_length)
    {
        const n = Math.min(64 - this.block_length, data.length);
        this.block.set(data.subarray(0, n), this.block_length);
        this.block_length += n;
        i = n;
        if(this.block_length < 64) return this;
        this.compress(this.block, 0);
        this.block_length = 0;
    }
    for(; i + 64 <= data.length; i += 64) this.compress(data, i);
    this.block.set(data.subarray(i), 0);
    this.block_length = data.length - i;
    return this;
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} offset
 */
SHA1.prototype.compress = function(bytes, offset)
{
    const w = this.w, h = this.h;
    for(let t = 0; t < 16; t++)
    {
        const p = offset + t * 4;
        w[t] = bytes[p] << 24 | bytes[p + 1] << 16 | bytes[p + 2] << 8 | bytes[p + 3];
    }
    for(let t = 16; t < 80; t++)
    {
        const x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
        w[t] = x << 1 | x >>> 31;
    }
    let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
    for(let t = 0; t < 80; t++)
    {
        const f = t < 20 ? (b & c | ~b & d) + 0x5A827999 :
            t < 40 ? (b ^ c ^ d) + 0x6ED9EBA1 :
            t < 60 ? (b & c | b & d | c & d) + 0x8F1BBCDC :
            (b ^ c ^ d) + 0xCA62C1D6;
        const x = (a << 5 | a >>> 27) + f + e + w[t] | 0;
        e = d; d = c; c = b << 30 | b >>> 2; b = a; a = x;
    }
    h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
};

/**
 * @return {!Uint8Array} the digest's 20 bytes (the hash is finished)
 */
SHA1.prototype.digest = function()
{
    const bits_high = Math.floor(this.total / 0x20000000), bits_low = this.total * 8 >>> 0;
    const pad = new Uint8Array((this.block_length < 56 ? 64 : 128) - this.block_length);
    pad[0] = 0x80;
    const n = pad.length;
    pad[n - 8] = bits_high >>> 24; pad[n - 7] = bits_high >>> 16; pad[n - 6] = bits_high >>> 8; pad[n - 5] = bits_high;
    pad[n - 4] = bits_low >>> 24; pad[n - 3] = bits_low >>> 16; pad[n - 2] = bits_low >>> 8; pad[n - 1] = bits_low;
    this.update(pad);
    const out = new Uint8Array(20);
    for(let i = 0; i < 5; i++)
    {
        out[4 * i] = this.h[i] >>> 24; out[4 * i + 1] = this.h[i] >>> 16; out[4 * i + 2] = this.h[i] >>> 8; out[4 * i + 3] = this.h[i];
    }
    return out;
};

/**
 * @return {string} the digest in hexadecimal (the hash is finished)
 */
SHA1.prototype.hex = function()
{
    return to_hex(this.digest());
};

/**
 * HMAC-SHA1 with a fixed key: the key's padded blocks hashed once
 * @constructor
 * @param {!Uint8Array} key
 */
export function HMAC_SHA1(key)
{
    if(key.length > 64) key = new SHA1().update(key).digest();
    const pad = new Uint8Array(64);
    pad.set(key);
    for(let i = 0; i < 64; i++) pad[i] ^= 0x36;
    this.inner = new SHA1().update(pad);
    for(let i = 0; i < 64; i++) pad[i] ^= 0x36 ^ 0x5C;
    this.outer = new SHA1().update(pad);
}

/**
 * @param {!Uint8Array} message
 * @return {!Uint8Array} 20 bytes
 */
HMAC_SHA1.prototype.mac = function(message)
{
    const inner = clone_sha1(this.inner).update(message).digest();
    return clone_sha1(this.outer).update(inner).digest();
};

/** @param {!SHA1} hash @return {!SHA1} */
function clone_sha1(hash)
{
    const copy = new SHA1();
    copy.h.set(hash.h);
    copy.block.set(hash.block);
    copy.block_length = hash.block_length;
    copy.total = hash.total;
    return copy;
}

/**
 * @param {string} hex
 * @return {!Uint8Array}
 */
export function from_hex(hex)
{
    if(!/^([0-9a-fA-F]{2})*$/.test(hex)) throw new Error("not a hexadecimal string of whole bytes");
    const out = new Uint8Array(hex.length / 2);
    for(let i = 0; i < out.length; i++) out[i] = parseInt(hex.substr(2 * i, 2), 16);
    return out;
}

/**
 * @param {!Uint8Array} bytes
 * @return {string}
 */
export function to_hex(bytes)
{
    return Array.from(bytes, x => x.toString(16).padStart(2, "0")).join("");
}
                                                                                                                                                                                                                                                                                                             source/v64/src/ios/hfsplus.js                                                                       0000644 0000000 0000000 00000033451 00000000000 013275  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // HFS+ and HFSX volumes, read-only (docs/iphone4-plan.md S0; Apple TN1150):
// the root filesystem and the ramdisks. A volume header at 1024, files as
// forks of up to eight extents (more in the extents overflow B-tree), the
// catalog B-tree keyed by (parent ID, name), extended attributes in the
// attributes B-tree (decmpfs compression lives there). Names are never
// compared: a directory's records are found by descending the catalog on
// the parent ID alone (its records sort together, the thread first) and
// read in order, so case folding (HFS+) and binary order (HFSX) both work.
// Reads go through read(offset, length), which returns bytes or a promise.

import { latin1 } from "../android/bytes.js";
import { inflate_zlib } from "./udif.js";

const be16 = (b, at) => b[at] << 8 | b[at + 1];
const be32 = (b, at) => (b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]) >>> 0;
const be64 = (b, at) => be32(b, at) * 0x100000000 + be32(b, at + 4);

const FOLDER = 1, FILE = 2, FOLDER_THREAD = 3, FILE_THREAD = 4;
const ROOT_ID = 2, EXTENTS_ID = 3, CATALOG_ID = 4, ATTRIBUTES_ID = 8;
const LEAF = -1, INDEX = 0, HEADER = 1;
// (seconds from 1904 to 1970)
const EPOCH = 2082844800;

/** @param {!Uint8Array} b @param {number} at @return {string} an HFSUniStr255 */
function unistr(b, at)
{
    const n = be16(b, at);
    let s = "";
    for(let i = 0; i < n; i++) s += String.fromCharCode(be16(b, at + 2 + 2 * i));
    return s;
}

/** @param {!Uint8Array} b @param {number} at @return {{size: number, extents: !Array<{start: number, count: number}>}} */
function fork(b, at)
{
    const extents = [];
    for(let i = 0; i < 8; i++)
    {
        const count = be32(b, at + 16 + 8 * i + 4);
        if(count) extents.push({ start: be32(b, at + 16 + 8 * i), count });
    }
    return { size: be64(b, at), blocks: be32(b, at + 12), extents };
}

/**
 * @constructor
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 */
export function HFSPlus(read)
{
    this.read = read;
    this.header = null;
}

/** Reads the volume header and the B-trees' headers */
HFSPlus.prototype.open = async function()
{
    const h = await this.read(1024, 512);
    const signature = latin1(h, 0, 2);
    if(signature !== "H+" && signature !== "HX") throw new Error(`HFS+: no volume header (${JSON.stringify(signature)})`);
    this.case_sensitive = signature === "HX";
    this.block_size = be32(h, 0x28);
    this.total_blocks = be32(h, 0x2C);
    this.free_blocks = be32(h, 0x30);
    this.header = h;
    this.forks = { [EXTENTS_ID]: fork(h, 0xC0), [CATALOG_ID]: fork(h, 0x110), [ATTRIBUTES_ID]: fork(h, 0x160) };
    this.extents = await this.btree(EXTENTS_ID);
    this.catalog = await this.btree(CATALOG_ID);
    this.attributes = this.forks[ATTRIBUTES_ID].size ? await this.btree(ATTRIBUTES_ID) : null;
    return this;
};

/**
 * A fork's bytes [start, start + length)
 * @param {number} file_id
 * @param {{size: number, extents: !Array<{start: number, count: number}>}} f
 * @param {number} start
 * @param {number} length
 * @param {number=} fork_type 0 data, 0xFF resource
 * @return {!Promise<!Uint8Array>}
 */
HFSPlus.prototype.read_fork = async function(file_id, f, start, length, fork_type = 0)
{
    length = Math.max(0, Math.min(length, f.size - start));
    const out = new Uint8Array(length);
    let extents = f.extents, covered = extents.reduce((n, e) => n + e.count, 0);
    if(covered * this.block_size < f.size && file_id !== EXTENTS_ID)
    {
        extents = extents.concat(await this.overflow_extents(file_id, fork_type, covered));
    }
    let logical = 0;
    for(const e of extents)
    {
        const bytes = e.count * this.block_size, lo = Math.max(start, logical), hi = Math.min(start + length, logical + bytes);
        if(lo < hi)
        {
            const data = await this.read(e.start * this.block_size + (lo - logical), hi - lo);
            out.set(data, lo - start);
        }
        logical += bytes;
        if(logical >= start + length) break;
    }
    return out;
};

/**
 * The extents of a fork beyond its first eight
 * @param {number} file_id
 * @param {number} fork_type
 * @param {number} from_block
 * @return {!Promise<!Array<{start: number, count: number}>>}
 */
HFSPlus.prototype.overflow_extents = async function(file_id, fork_type, from_block)
{
    const found = [];
    // (keys: length, fork type, pad, file ID, start block; records: eight extents)
    await this.walk(this.extents, key => Math.sign(be32(key, 4) - file_id) || Math.sign(key[2] - fork_type), (key, record) =>
    {
        if(be32(key, 4) !== file_id || key[2] !== fork_type) return false;
        if(be32(key, 8) >= from_block)
        {
            for(let i = 0; i < 8; i++)
            {
                const count = be32(record, 8 * i + 4);
                if(count) found.push({ start: be32(record, 8 * i), count });
            }
        }
        return true;
    });
    return found;
};

/**
 * A B-tree's header
 * @param {number} file_id
 */
HFSPlus.prototype.btree = async function(file_id)
{
    const f = this.forks[file_id];
    const first = await this.read_fork(file_id, f, 0, 512);
    const h = first.subarray(14);
    const tree = { file_id, fork: f, node_size: be16(h, 18), root: be32(h, 2), first_leaf: be32(h, 10), key_compare: h[37] };
    tree.cache = new Map();
    return tree;
};

/**
 * A node's records as [key, data] (index nodes: data is the child's number)
 * @param {Object} tree
 * @param {number} n
 * @return {!Promise<{kind: number, next: number, records: !Array<{key: !Uint8Array, data: !Uint8Array}>}>}
 */
HFSPlus.prototype.node = async function(tree, n)
{
    if(tree.cache.has(n)) return tree.cache.get(n);
    const b = await this.read_fork(tree.file_id, tree.fork, n * tree.node_size, tree.node_size);
    const kind = b[8] << 24 >> 24, count = be16(b, 10);
    const records = [];
    for(let i = 0; i < count; i++)
    {
        const start = be16(b, tree.node_size - 2 * (i + 1)), end = be16(b, tree.node_size - 2 * (i + 2));
        const key_length = be16(b, start);
        // (keys are padded to an even length in index nodes and always in the catalog's)
        const key = b.subarray(start, start + 2 + key_length);
        const data_at = start + 2 + key_length + (key_length & 1);
        records.push({ key, data: b.subarray(data_at, i + 1 < count ? end : end || tree.node_size) });
    }
    const node = { kind, next: be32(b, 0), records };
    if(tree.cache.size > 4096) tree.cache.clear();
    tree.cache.set(n, node);
    return node;
};

/**
 * Visits leaf records in order from the first whose key compares >= 0 to
 * the target (compare(key) < 0: the key sorts before it); visit returns
 * false to stop
 * @param {Object} tree
 * @param {function(!Uint8Array): number} compare
 * @param {function(!Uint8Array, !Uint8Array): boolean} visit
 */
HFSPlus.prototype.walk = async function(tree, compare, visit)
{
    if(!tree.root) return;
    let n = tree.root;
    for(;;)
    {
        const node = await this.node(tree, n);
        if(node.kind === LEAF) break;
        if(node.kind !== INDEX) throw new Error(`HFS+: node ${n} of kind ${node.kind} in the index`);
        // (the last child whose first key sorts before the target: equal keys may continue in its left sibling)
        let child = be32(node.records[0].data, 0);
        for(const r of node.records)
        {
            if(compare(r.key) < 0) child = be32(r.data, 0);
            else break;
        }
        n = child;
    }
    for(; n;)
    {
        const node = await this.node(tree, n);
        for(const r of node.records)
        {
            if(compare(r.key) < 0) continue;
            if(!visit(r.key, r.data)) return;
        }
        n = node.next;
    }
};

/**
 * A directory's entries
 * @param {number} parent_id
 * @return {!Promise<!Array<Object>>}
 */
HFSPlus.prototype.list = async function(parent_id)
{
    const entries = [];
    await this.walk(this.catalog, key => Math.sign(be32(key, 2) - parent_id) || (be16(key, 6) ? 1 : 0), (key, data) =>
    {
        if(be32(key, 2) !== parent_id) return false;
        const type = be16(data, 0);
        if(type === FOLDER || type === FILE) entries.push(this.record(unistr(key, 6), data));
        return true;
    });
    return entries;
};

/**
 * @param {string} name
 * @param {!Uint8Array} d a folder or file record
 * @return {Object}
 */
HFSPlus.prototype.record = function(name, d)
{
    const type = be16(d, 0);
    const entry = {
        name, type: type === FOLDER ? "directory" : "file", id: be32(d, 8),
        created: be32(d, 12) - EPOCH, modified: be32(d, 16) - EPOCH,
        uid: be32(d, 32), gid: be32(d, 36), flags: d[41] | d[40] << 8, mode: be16(d, 42), special: be32(d, 44),
    };
    if(type === FILE)
    {
        entry.file_type = latin1(d, 48, 52);
        entry.creator = latin1(d, 52, 56);
        entry.data = fork(d, 88);
        entry.resource = fork(d, 168);
        entry.size = entry.data.size;
        if((entry.mode & 0xF000) === 0xA000 || entry.file_type === "slnk" && entry.creator === "rhap") entry.type = "symlink";
        else if(entry.file_type === "hlnk" && entry.creator === "hfs+") entry.type = "hardlink";
        // (UF_COMPRESSED: the contents are in the com.apple.decmpfs attribute)
        entry.compressed = !!(entry.flags & 0x20);
    }
    else
    {
        entry.valence = be32(d, 4);
    }
    return entry;
};

/**
 * The entry at an absolute path (symbolic links in the path not followed)
 * @param {string} path
 * @return {!Promise<?Object>}
 */
HFSPlus.prototype.lookup = async function(path)
{
    let entry = { name: "/", type: "directory", id: ROOT_ID };
    for(const part of path.split("/").filter(Boolean))
    {
        if(entry.type !== "directory") return null;
        const children = await this.list(entry.id);
        entry = children.find(c => c.name === part) ||
            (!this.case_sensitive && children.find(c => c.name.toLowerCase() === part.toLowerCase())) || null;
        if(!entry) return null;
    }
    return entry;
};

/**
 * An attribute's value
 * @param {number} file_id
 * @param {string} name
 * @return {!Promise<?Uint8Array>}
 */
HFSPlus.prototype.attribute = async function(file_id, name)
{
    if(!this.attributes) return null;
    let found = null;
    await this.walk(this.attributes, key => Math.sign(be32(key, 4) - file_id), (key, data) =>
    {
        if(be32(key, 4) !== file_id) return false;
        let n = "";
        for(let i = 0, length = be16(key, 12); i < length; i++) n += String.fromCharCode(be16(key, 14 + 2 * i));
        if(n !== name) return true;
        if(be32(data, 0) !== 0x10) throw new Error(`HFS+: attribute ${name} of file ${file_id} is not inline`);
        found = data.slice(16, 16 + be32(data, 12));
        return false;
    });
    return found;
};

/**
 * A file's contents (hard links resolved, decmpfs zlib decompressed;
 * a symbolic link's target)
 * @param {Object} entry list's or lookup's
 * @return {!Promise<!Uint8Array>}
 */
HFSPlus.prototype.contents = async function(entry)
{
    if(entry.type === "directory") throw new Error(`HFS+: ${entry.name} is a directory`);
    if(entry.type === "hardlink")
    {
        const node = await this.lookup(`/\u0000\u0000\u0000\u0000HFS+ Private Data/iNode${entry.special}`);
        if(!node) throw new Error(`HFS+: hard link ${entry.name} to a missing iNode${entry.special}`);
        return this.contents(node);
    }
    if(entry.compressed)
    {
        const header = await this.attribute(entry.id, "com.apple.decmpfs");
        if(!header || latin1(header, 0, 4) !== "fpmc") throw new Error(`HFS+: ${entry.name} is compressed without a decmpfs header`);
        const type = header[4] | header[5] << 8, size = (header[8] | header[9] << 8 | header[10] << 16 | header[11] << 24) >>> 0;
        if(type === 3)
        {
            // (inline: 0xFF then the bytes as they are, or zlib)
            const body = header.subarray(16);
            return (body[0] & 0x0F) === 0x0F ? body.slice(1, 1 + size) : (await inflate_zlib(body)).subarray(0, size);
        }
        if(type === 4)
        {
            // (in the resource fork: a resource header, then a table of zlib blocks of 64 KiB each)
            const rsrc = await this.read_fork(entry.id, entry.resource, 0, entry.resource.size, 0xFF);
            const data_at = be32(rsrc, 0);
            const table = data_at + 4, count = rsrc[table] | rsrc[table + 1] << 8 | rsrc[table + 2] << 16 | rsrc[table + 3] << 24;
            const out = new Uint8Array(size);
            for(let i = 0, o = 0; i < count; i++)
            {
                const at = table + 4 + 8 * i;
                const offset = (rsrc[at] | rsrc[at + 1] << 8 | rsrc[at + 2] << 16 | rsrc[at + 3] << 24) >>> 0;
                const length = (rsrc[at + 4] | rsrc[at + 5] << 8 | rsrc[at + 6] << 16 | rsrc[at + 7] << 24) >>> 0;
                const block = rsrc.subarray(table + offset, table + offset + length);
                const plain = (block[0] & 0x0F) === 0x0F ? block.subarray(1) : await inflate_zlib(block);
                out.set(plain.subarray(0, size - o), o);
                o += plain.length;
            }
            return out;
        }
        throw new Error(`HFS+: ${entry.name} uses decmpfs type ${type}`);
    }
    return this.read_fork(entry.id, entry.data, 0, entry.data.size);
};

/**
 * Every entry under a directory, depth first: visit(path, entry)
 * @param {string} path
 * @param {function(string, Object): (Promise|undefined)} visit
 */
HFSPlus.prototype.walk_tree = async function(path, visit)
{
    const start = await this.lookup(path);
    if(!start) throw new Error(`HFS+: no ${path}`);
    const recurse = async (prefix, id) =>
    {
        for(const child of await this.list(id))
        {
            const p = prefix + "/" + child.name;
            await visit(p, child);
            if(child.type === "directory") await recurse(p, child.id);
        }
    };
    if(start.type === "directory") await recurse(path.replace(/\/$/, ""), start.id);
    else await visit(path, start);
};
                                                                                                                                                                                                                       source/v64/src/ios/img3.js                                                                          0000644 0000000 0000000 00000010611 00000000000 012441  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // IMG3, the container of iOS 2–6 firmware files (docs/iphone4-plan.md S0):
// a 20-byte header (magic "Img3", full size, size without the signature,
// signed area, the image's type) then tags, each a magic, its total length
// (with padding), its data's length and the data. Magics and types are
// four characters stored little-endian ("DATA" reads "ATAD"). DATA is the
// payload; KBAG says how it is encrypted (AES-CBC, its IV and key wrapped
// by the device's GID key, so the keys come from the user: The Apple Wiki's
// key pages). The cipher text runs on into the tag's padding up to a whole
// AES block: decrypting only DATA's recorded length garbles the last block.

import { u32, latin1 } from "../android/bytes.js";
import { AES, from_hex } from "./crypto.js";

const MAGIC = 0x496D6733; // "Img3"

/** @param {!Uint8Array} b @param {number} at @return {string} a four-character code stored little-endian */
function fourcc(b, at)
{
    return latin1(b, at, at + 4).split("").reverse().join("");
}

/**
 * The tags of an IMG3 file
 * @param {!Uint8Array} bytes
 * @return {{type: string, tags: !Array<{magic: string, data: !Uint8Array, room: !Uint8Array}>}}
 *     (room: the tag's data with its padding)
 */
export function img3_parse(bytes)
{
    if(bytes.length < 20 || u32(bytes, 0) !== MAGIC) throw new Error("IMG3: no Img3 header");
    const size = Math.min(u32(bytes, 4), bytes.length);
    const tags = [];
    for(let at = 20; at + 12 <= size;)
    {
        const total = u32(bytes, at + 4), length = u32(bytes, at + 8);
        if(total < 12 || length > total - 12 || at + total > size) throw new Error(`IMG3: a broken tag at ${at}`);
        tags.push({ magic: fourcc(bytes, at), data: bytes.subarray(at + 12, at + 12 + length), room: bytes.subarray(at + 12, at + total) });
        at += total;
    }
    return { type: fourcc(bytes, 16), tags };
}

/**
 * An IMG3 file's payload, decrypted with key (hexadecimal or bytes; null
 * for an unencrypted image)
 * @param {!Uint8Array} bytes
 * @param {?{iv: (string|!Uint8Array), key: (string|!Uint8Array)}=} key
 * @return {{type: string, data: !Uint8Array, encrypted: boolean}}
 */
export function img3_payload(bytes, key)
{
    const image = img3_parse(bytes);
    const data = image.tags.find(t => t.magic === "DATA");
    if(!data) throw new Error(`IMG3 ${image.type}: no DATA tag`);
    const kbag = image.tags.find(t => t.magic === "KBAG");
    if(!kbag) return { type: image.type, data: data.data.slice(), encrypted: false };
    if(!key) throw new Error(`IMG3 ${image.type}: encrypted, and no key given`);
    const iv = typeof key.iv === "string" ? from_hex(key.iv) : key.iv;
    const k = typeof key.key === "string" ? from_hex(key.key) : key.key;
    const bits = u32(kbag.data, 4);
    if(iv.length !== 16 || k.length * 8 !== bits) throw new Error(`IMG3 ${image.type}: wants AES-${bits}, got a ${k.length * 8}-bit key and a ${iv.length}-byte IV`);
    const whole = data.data.length + 15 & ~15;
    if(whole > data.room.length) throw new Error(`IMG3 ${image.type}: DATA is not padded to an AES block`);
    const plain = data.room.slice(0, whole);
    new AES(k).cbc(plain, iv, true);
    return { type: image.type, data: plain.subarray(0, data.data.length), encrypted: true };
}

/**
 * An IMG3 file made of tags (tests; the padding up to 4 bytes, or to whole
 * AES blocks for an encrypted DATA, given in the tag's room)
 * @param {string} type
 * @param {!Array<{magic: string, data: !Uint8Array, room: (!Uint8Array|undefined)}>} tags
 * @return {!Uint8Array}
 */
export function img3_build(type, tags)
{
    const cc = s => [3, 2, 1, 0].map(i => s.charCodeAt(i));
    const parts = tags.map(t =>
    {
        const room = t.room || new Uint8Array(t.data.length + 3 & ~3);
        if(!t.room) room.set(t.data);
        const out = new Uint8Array(12 + room.length);
        out.set(cc(t.magic), 0);
        new DataView(out.buffer).setUint32(4, out.length, true);
        new DataView(out.buffer).setUint32(8, t.data.length, true);
        out.set(room, 12);
        return out;
    });
    const size = 20 + parts.reduce((n, p) => n + p.length, 0);
    const out = new Uint8Array(size), view = new DataView(out.buffer);
    view.setUint32(0, MAGIC, true);
    view.setUint32(4, size, true);
    view.setUint32(8, size - 20, true);
    view.setUint32(12, size - 20, true);
    out.set(cc(type), 16);
    let at = 20;
    for(const p of parts) { out.set(p, at); at += p.length; }
    return out;
}
                                                                                                                       source/v64/src/ios/ipsw.js                                                                          0000644 0000000 0000000 00000031626 00000000000 012575  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // An iPhone's IPSW (docs/iphone4-plan.md S0): a zip of the restore
// firmware. The user brings it and the keys (The Apple Wiki's key page, as
// the key file below); this decrypts and checks each image and takes out
// what the s5l8930 machine boots: the kernelcache (a Mach-O), the device
// tree, the restore ramdisk (HFS+) and the root filesystem's system
// partition (HFSX). The archive is read through read(offset, length), which
// returns bytes or a promise of them (a file in node, a File's slices).
//
// The key file (never in the repository: docs/iphone4-plan.md "法律与分发"):
//   { "format": "v86-ios-keys", "version": 1, "device": "iPhone3,1", "build": "10B329", ...,
//     "images": { "<the key page's item>": { "file": "<name in the IPSW>", "iv": "<hex>", "key": "<hex>" } } }
// RootFileSystem has a 36-byte key and no IV.

import { zip_entries, zip_stream, zip_read } from "../android/zip.js";
import { latin1, u32be } from "../android/bytes.js";
import { plist_parse } from "./plist.js";
import { img3_payload } from "./img3.js";
import { complzss_decompress } from "./lzss.js";
import { vfdecrypt_stream } from "./vfdecrypt.js";
import { udif_trailer, udif_partitions, udif_partition_stream, inflate_zlib, CHUNK } from "./udif.js";
import { SHA1 } from "./crypto.js";
import { dt_parse, dt_property, dt_strings, dt_walk } from "../apple/devicetree.js";
import { macho_parse, CPU_TYPE_ARM } from "../apple/macho.js";

export const KEY_FORMAT = "v86-ios-keys";

/**
 * A key file, checked
 * @param {string|Object} source
 * @return {Object}
 */
export function keys_parse(source)
{
    const keys = typeof source === "string" ? JSON.parse(source) : source;
    if(keys?.format !== KEY_FORMAT || keys.version !== 1) throw new Error(`keys: not a ${KEY_FORMAT} version 1 file`);
    if(typeof keys.images !== "object" || !keys.images) throw new Error("keys: no images");
    for(const [name, image] of Object.entries(keys.images))
    {
        if(typeof image.file !== "string") throw new Error(`keys: ${name} has no file`);
        if(name === "RootFileSystem")
        {
            if(!/^[0-9a-fA-F]{72}$/.test(image.key || "")) throw new Error("keys: RootFileSystem's key is not 36 bytes of hexadecimal");
        }
        else if(!/^[0-9a-fA-F]{32}$/.test(image.iv || "") || !/^([0-9a-fA-F]{32}|[0-9a-fA-F]{48}|[0-9a-fA-F]{64})$/.test(image.key || ""))
        {
            throw new Error(`keys: ${name} needs a 16-byte IV and a 16-, 24- or 32-byte key in hexadecimal`);
        }
    }
    return keys;
}

/**
 * The archive's members and what its plists say
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {number} size
 * @return {!Promise<Object>}
 */
export async function ipsw_open(read, size)
{
    const entries = await zip_entries(read, size);
    const by_name = new Map(entries.map(e => [e.name, e]));
    const plist = async name => by_name.has(name) ? plist_parse(await zip_read(read, by_name.get(name))) : null;
    const manifest = await plist("BuildManifest.plist");
    const restore = await plist("Restore.plist");
    if(!manifest && !restore) throw new Error("IPSW: neither BuildManifest.plist nor Restore.plist: not an IPSW");
    // (the erase install's identity names the files)
    const identity = manifest?.BuildIdentities?.find(i => /Erase/.test(i.Info?.Variant || "")) ?? manifest?.BuildIdentities?.[0];
    const path_of = key => identity?.Manifest?.[key]?.Info?.Path ?? null;
    return {
        read, size, entries,
        version: manifest?.ProductVersion ?? restore?.ProductVersion,
        build: manifest?.ProductBuildVersion ?? restore?.ProductBuildVersion,
        product_types: manifest?.SupportedProductTypes ?? (restore?.SupportedProductTypes || [restore?.ProductType]).filter(Boolean),
        boards: (restore?.DeviceMap || []).map(d => d.BoardConfig).filter(Boolean),
        kernelcache: path_of("KernelCache"),
        devicetree: path_of("DeviceTree"),
        restore_ramdisk: path_of("RestoreRamDisk"),
        system_image: path_of("OS"),
        /** @param {string} file @return {?Object} the member whose name ends in file */
        member(file)
        {
            return entries.find(e => e.name === file || e.name.endsWith("/" + file)) || null;
        },
    };
}

/**
 * The archive's SHA-1, in hexadecimal
 * @param {function(number, number): (!Uint8Array|!Promise<!Uint8Array>)} read
 * @param {number} size
 * @param {function(number)=} progress bytes done
 * @return {!Promise<string>}
 */
export async function ipsw_sha1(read, size, progress)
{
    const hash = new SHA1();
    for(let at = 0; at < size;)
    {
        const n = Math.min(8 << 20, size - at);
        hash.update(await read(at, n));
        at += n;
        if(progress) progress(at);
    }
    return hash.hex();
}

/** @param {!Uint8Array} b @param {string} text @return {number} */
function find_text(b, text)
{
    const first = text.charCodeAt(0);
    outer: for(let at = b.indexOf(first); at >= 0 && at + text.length <= b.length; at = b.indexOf(first, at + 1))
    {
        for(let i = 1; i < text.length; i++) if(b[at + i] !== text.charCodeAt(i)) continue outer;
        return at;
    }
    return -1;
}

/** @param {!Uint8Array} b @param {number} at @return {string} printable text from at */
function text_at(b, at)
{
    let end = at;
    while(end < b.length && b[end] >= 0x20 && b[end] < 0x7F) end++;
    return latin1(b, at, end);
}

/**
 * What a decrypted image's payload is, checked by its type: a summary, or
 * an exception when it is not what it should be (a wrong key)
 * @param {string} type the IMG3 type
 * @param {!Uint8Array} plain
 * @return {string}
 */
export function check_payload(type, plain)
{
    if(type === "krnl")
    {
        const kernel = complzss_decompress(plain);
        const m = macho_parse(kernel);
        if(m.cputype !== CPU_TYPE_ARM || m.is64) throw new Error("kernelcache: not a 32-bit ARM Mach-O");
        const at = find_text(kernel, "Darwin Kernel Version");
        return `ARM Mach-O, ${kernel.length} bytes; ` + (at >= 0 ? text_at(kernel, at) : "no version string");
    }
    if(type === "dtre")
    {
        const root = dt_parse(plain);
        let nodes = 0;
        dt_walk(root, () => { nodes++; });
        const compatible = dt_property(root, "compatible");
        return `${nodes} nodes, compatible ${compatible ? dt_strings(compatible.value).join(", ") : "?"}`;
    }
    if(type === "rdsk")
    {
        const signature = latin1(plain, 0x400, 0x402);
        if(signature !== "H+" && signature !== "HX") throw new Error("ramdisk: no HFS+ volume header at 0x400");
        return `HFS+ volume of ${u32be(plain, 0x428) * u32be(plain, 0x42C) >> 20} MiB`;
    }
    if(type === "ibot" || type === "ibss" || type === "ibec" || type === "illb")
    {
        const at = find_text(plain, "iBoot-");
        if(at < 0) throw new Error(`${type}: no iBoot version string`);
        return text_at(plain, at);
    }
    if(latin1(plain, 0, 8) !== "iBootIm\0") throw new Error(`${type}: no iBootIm header`);
    return "iBootIm image";
}

/**
 * A key file's image, decrypted out of the archive
 * @param {Object} ipsw ipsw_open's
 * @param {Object} image the key file's entry
 * @return {!Promise<{type: string, data: !Uint8Array, encrypted: boolean}>}
 */
export async function ipsw_image(ipsw, image)
{
    const entry = ipsw.member(image.file);
    if(!entry) throw new Error(`IPSW: no ${image.file}`);
    return img3_payload(await zip_read(ipsw.read, entry), image);
}

/**
 * The root filesystem's decrypted data, streamed: the head (first `head`
 * bytes) and the tail (last `tail` bytes) only
 * @param {Object} ipsw
 * @param {Object} image the key file's RootFileSystem
 * @param {number} head
 * @param {number} tail
 * @param {function(number)=} progress compressed bytes done
 * @return {!Promise<{head: !Uint8Array, tail: !Uint8Array, data_size: number}>}
 */
async function rootfs_ends(ipsw, image, head, tail, progress)
{
    const entry = ipsw.member(image.file);
    if(!entry) throw new Error(`IPSW: no ${image.file}`);
    let data_size = 0, head_bytes = null, tail_bytes = null, tail_from = 0;
    const stream = vfdecrypt_stream(image.key, (bytes, offset) =>
    {
        if(!data_size)
        {
            data_size = stream.header().data_size;
            head_bytes = new Uint8Array(Math.min(head, data_size));
            tail_from = Math.max(0, data_size - tail);
            tail_bytes = new Uint8Array(data_size - tail_from);
        }
        if(offset < head_bytes.length) head_bytes.set(bytes.subarray(0, head_bytes.length - offset), offset);
        if(offset + bytes.length > tail_from)
        {
            const skip = Math.max(0, tail_from - offset);
            tail_bytes.set(bytes.subarray(skip), offset + skip - tail_from);
        }
    }, { want: (offset, length) =>
    {
        const size = stream.header().data_size;
        return offset < head || offset + length > size - tail;
    } });
    let done = 0;
    await zip_stream(ipsw.read, entry, async bytes =>
    {
        await stream.write(bytes);
        done += bytes.length;
        if(progress) progress(done);
    });
    await stream.end();
    return { head: head_bytes, tail: tail_bytes, data_size };
}

/**
 * The root filesystem's DMG checked: its trailer, partitions and the
 * system partition's volume header
 * @param {Object} ipsw
 * @param {Object} image
 * @param {function(number)=} progress
 * @return {!Promise<{summary: string, partitions: !Array<Object>, system: Object, trailer: Object}>}
 */
export async function check_rootfs(ipsw, image, progress)
{
    const { head, tail, data_size } = await rootfs_ends(ipsw, image, 4 << 20, 8 << 20, progress);
    const tail_start = data_size - tail.length;
    const trailer = udif_trailer(tail.subarray(tail.length - 512));
    if(trailer.xml_offset < tail_start) throw new Error("root filesystem: the DMG's plist is outside the last 8 MiB");
    const partitions = udif_partitions(tail.subarray(trailer.xml_offset - tail_start, trailer.xml_offset - tail_start + trailer.xml_length));
    const system = partitions.find(p => /Apple_HFS/.test(p.name));
    if(!system) throw new Error("root filesystem: no Apple_HFS partition");
    const first = system.chunks.find(c => c.sector === 0 && (c.type === CHUNK.ZLIB || c.type === CHUNK.RAW));
    const start = trailer.data_fork_offset + system.data_offset + (first ? first.offset : 0);
    if(!first || start + first.length > head.length) throw new Error("root filesystem: the system partition's first chunk is not in the first 4 MiB");
    const raw = head.subarray(start, start + first.length);
    const sector0 = first.type === CHUNK.ZLIB ? await inflate_zlib(raw) : raw;
    const summary = check_payload("rdsk", sector0).replace("HFS+ volume", "system partition: HFS+ volume");
    return {
        summary: `DMG of ${trailer.sectors * 512 >> 20} MiB, ${partitions.length} partitions; ${system.name}; ${summary}`,
        partitions, system, trailer,
    };
}

/**
 * Every image of the key file checked, in order: report(name, ok, text)
 * @param {Object} ipsw
 * @param {Object} keys keys_parse's
 * @param {function(string, boolean, string)} report
 * @param {function(string, number)=} progress
 * @return {!Promise<number>} the failures
 */
export async function ipsw_check(ipsw, keys, report, progress)
{
    let failures = 0;
    for(const [name, image] of Object.entries(keys.images))
    {
        try
        {
            let text;
            if(name === "RootFileSystem")
            {
                text = (await check_rootfs(ipsw, image, progress && (n => progress(name, n)))).summary;
            }
            else
            {
                const payload = await ipsw_image(ipsw, image);
                text = `[${payload.type}] ` + check_payload(payload.type, payload.data);
            }
            report(name, true, text);
        }
        catch(e)
        {
            failures++;
            report(name, false, e.message);
        }
    }
    return failures;
}

/**
 * The root filesystem's system partition, written out: out(offset, bytes)
 * in order (awaited); the zero-filled stretches are left out
 * @param {Object} ipsw
 * @param {Object} image the key file's RootFileSystem
 * @param {function(number, !Uint8Array): (Promise|undefined)} out
 * @param {function(string, number)=} progress
 * @return {!Promise<{size: number, name: string}>} the partition's
 */
export async function extract_system_partition(ipsw, image, out, progress)
{
    const { system, trailer } = await check_rootfs(ipsw, image, progress && (n => progress("check", n)));
    const entry = ipsw.member(image.file);
    const partition = udif_partition_stream(system, out, trailer.data_fork_offset);
    const stream = vfdecrypt_stream(image.key, bytes => partition.write(bytes));
    let done = 0;
    await zip_stream(ipsw.read, entry, async bytes =>
    {
        await stream.write(bytes);
        done += bytes.length;
        if(progress) progress("extract", done);
    });
    await stream.end();
    await partition.end();
    return { size: system.sectors * 512, name: system.name };
}
                                                                                                          source/v64/src/ios/lzss.js                                                                          0000644 0000000 0000000 00000005422 00000000000 012601  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The kernelcache's compression (docs/iphone4-plan.md S0): a 0x180-byte
// header ("comp", "lzss", Adler-32 and sizes of the plain data, big-endian)
// then LZSS as Okumura's lzss.c and XNU's decompress_lzss: a 4096-byte ring
// (filled with spaces), 18-byte matches at most, flag bytes read low bit
// first (1: a literal; 0: a 12-bit position and a 4-bit length less 3).

import { u32be, latin1 } from "../android/bytes.js";

const N = 4096, F = 18, THRESHOLD = 2;

/**
 * @param {!Uint8Array} src
 * @param {number} limit the output's size at most
 * @return {!Uint8Array}
 */
export function lzss_decompress(src, limit)
{
    const ring = new Uint8Array(N);
    ring.fill(0x20, 0, N - F);
    const out = new Uint8Array(limit);
    let r = N - F, flags = 0, i = 0, o = 0;
    while(o < limit)
    {
        flags >>>= 1;
        if(!(flags & 0x100))
        {
            if(i >= src.length) break;
            flags = src[i++] | 0xFF00;
        }
        if(flags & 1)
        {
            if(i >= src.length) break;
            const c = src[i++];
            out[o++] = c;
            ring[r] = c;
            r = r + 1 & N - 1;
        }
        else
        {
            if(i + 1 >= src.length) break;
            const position = src[i] | (src[i + 1] & 0xF0) << 4, length = (src[i + 1] & 0x0F) + THRESHOLD + 1;
            i += 2;
            for(let k = 0; k < length && o < limit; k++)
            {
                const c = ring[position + k & N - 1];
                out[o++] = c;
                ring[r] = c;
                r = r + 1 & N - 1;
            }
        }
    }
    return out.subarray(0, o);
}

/**
 * Adler-32 (RFC 1950)
 * @param {!Uint8Array} b
 * @return {number}
 */
export function adler32(b)
{
    let a = 1, s = 0;
    for(let at = 0; at < b.length;)
    {
        const end = Math.min(b.length, at + 5552);
        for(; at < end; at++) { a += b[at]; s += a; }
        a %= 65521; s %= 65521;
    }
    return (s << 16 | a) >>> 0;
}

/**
 * A compressed kernelcache's contents: the plain data, its size and
 * Adler-32 checked against the header's
 * @param {!Uint8Array} bytes
 * @return {!Uint8Array}
 */
export function complzss_decompress(bytes)
{
    if(bytes.length < 0x180 || latin1(bytes, 0, 8) !== "complzss") throw new Error("kernelcache: no complzss header");
    const checksum = u32be(bytes, 8), size = u32be(bytes, 12), packed = u32be(bytes, 16);
    if(0x180 + packed > bytes.length) throw new Error(`kernelcache: ${packed} compressed bytes, ${bytes.length - 0x180} there`);
    const out = lzss_decompress(bytes.subarray(0x180, 0x180 + packed), size);
    if(out.length !== size) throw new Error(`kernelcache: ${out.length} bytes decompressed, the header says ${size}`);
    if(adler32(out) !== checksum) throw new Error("kernelcache: the Adler-32 differs");
    return out;
}
                                                                                                                                                                                                                                              source/v64/src/ios/plist.js                                                                         0000644 0000000 0000000 00000013656 00000000000 012751  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // XML property lists as Apple's firmware carries them (docs/iphone4-plan.md
// S0): BuildManifest.plist and Restore.plist in the IPSW, a DMG's resource
// fork, the kernelcache's prelink info. The kernel's dialect (OSUnserializeXML)
// shares repeated values: ID="n" on the first, IDREF="n" on the empty
// element that repeats it; its integers may be hexadecimal and 64 bits
// wide. Values: objects (dict), arrays, strings, numbers (bigint beyond
// 2^53), booleans, Uint8Array (data), Date.

const ENTITIES = { lt: "<", gt: ">", amp: "&", quot: "\"", apos: "'" };

/** @param {string} text @return {string} */
function unescape(text)
{
    return text.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-z]+);/g, (whole, name) =>
        name[0] === "#" ? String.fromCodePoint(name[1] === "x" ? parseInt(name.slice(2), 16) : +name.slice(1)) :
        ENTITIES[name] ?? whole);
}

/** @param {string} text @return {!Uint8Array} */
function base64(text)
{
    const clean = text.replace(/[^A-Za-z0-9+/]/g, "");
    const out = new Uint8Array(clean.length * 3 >> 2);
    const value = c => c >= 97 ? c - 71 : c >= 65 ? c - 65 : c >= 48 ? c + 4 : c === 43 ? 62 : 63;
    let bits = 0, n = 0, o = 0;
    for(let i = 0; i < clean.length; i++)
    {
        bits = bits << 6 | value(clean.charCodeAt(i));
        n += 6;
        if(n >= 8) { n -= 8; out[o++] = bits >> n & 0xFF; }
    }
    return out.subarray(0, o);
}

/** @param {string} text @return {number|bigint} */
function integer(text)
{
    text = text.trim();
    const negative = text[0] === "-";
    const digits = negative ? text.slice(1) : text;
    const big = BigInt(digits.startsWith("0x") || digits.startsWith("0X") ? digits : digits.replace(/^0+(?=\d)/, ""));
    const value = negative ? -big : big;
    return value >= -(2n ** 53n) && value <= 2n ** 53n ? Number(value) : value;
}

/**
 * @param {string|!Uint8Array} source
 * @return {*} the plist's top-level value
 */
export function plist_parse(source)
{
    const text = typeof source === "string" ? source : new TextDecoder().decode(source);
    // (the elements and the text between them; comments, the prolog and the doctype skipped)
    const tokens = text.replace(/<!--[\s\S]*?-->/g, "").replace(/<\?[\s\S]*?\?>/g, "").replace(/<!DOCTYPE[^>]*>/gi, "")
        .split(/(<[^>]+>)/);
    let at = 0;
    const ids = new Map();
    const next_tag = () =>
    {
        while(at < tokens.length && !tokens[at].startsWith("<"))
        {
            if(tokens[at].trim()) throw new Error(`plist: text outside an element: ${tokens[at].trim().slice(0, 40)}`);
            at++;
        }
        if(at >= tokens.length) throw new Error("plist: cut short");
        return tokens[at++];
    };
    const attributes = tag =>
    {
        const out = {};
        for(const m of tag.matchAll(/([A-Za-z_:][\w:.-]*)\s*=\s*"([^"]*)"/g)) out[m[1]] = m[2];
        return out;
    };
    const value = () =>
    {
        const tag = next_tag();
        const m = /^<\s*([A-Za-z]+)([^>]*?)(\/?)\s*>$/.exec(tag);
        if(!m) throw new Error(`plist: unexpected ${tag}`);
        const [, name, rest, empty] = m;
        const attrs = attributes(rest);
        if(attrs.IDREF !== undefined)
        {
            if(!ids.has(attrs.IDREF)) throw new Error(`plist: IDREF ${attrs.IDREF} before its ID`);
            return ids.get(attrs.IDREF);
        }
        let result;
        if(name === "plist")
        {
            result = value();
            if(next_tag() !== "</plist>") throw new Error("plist: more than one top-level value");
            return result;
        }
        const body = () =>
        {
            if(empty) return "";
            let content = "";
            while(at < tokens.length && tokens[at] !== `</${name}>`)
            {
                if(tokens[at].startsWith("<")) throw new Error(`plist: ${tokens[at]} inside <${name}>`);
                content += tokens[at++];
            }
            if(at >= tokens.length) throw new Error(`plist: <${name}> not closed`);
            at++;
            return unescape(content);
        };
        switch(name)
        {
            case "dict":
            {
                result = {};
                if(attrs.ID !== undefined) ids.set(attrs.ID, result);
                if(empty) return result;
                for(;;)
                {
                    const key = next_tag();
                    if(key === "</dict>") break;
                    if(key !== "<key>") throw new Error(`plist: ${key} where a key goes`);
                    let k = "";
                    while(tokens[at] !== "</key>") { if(at >= tokens.length) throw new Error("plist: <key> not closed"); k += tokens[at++]; }
                    at++;
                    result[unescape(k)] = value();
                }
                return result;
            }
            case "array":
            {
                result = [];
                if(attrs.ID !== undefined) ids.set(attrs.ID, result);
                if(empty) return result;
                for(;;)
                {
                    let peek = at;
                    while(peek < tokens.length && !tokens[peek].startsWith("<")) peek++;
                    if(tokens[peek] === "</array>")
                    {
                        next_tag();
                        break;
                    }
                    result.push(value());
                }
                return result;
            }
            case "string": result = body(); break;
            case "integer": result = integer(body()); break;
            case "real": result = parseFloat(body()); break;
            case "true": result = true; if(!empty) body(); break;
            case "false": result = false; if(!empty) body(); break;
            case "data": result = base64(body()); break;
            case "date": result = new Date(body().trim()); break;
            default: throw new Error(`plist: unknown element <${name}>`);
        }
        if(attrs.ID !== undefined) ids.set(attrs.ID, result);
        return result;
    };
    return value();
}
                                                                                  source/v64/src/ios/udif.js                                                                          0000644 0000000 0000000 00000013472 00000000000 012541  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // UDIF disk images, the DMG format of the root filesystem (docs/iphone4-plan.md
// S0): the data fork (the partitions' chunks, each raw, zero-filled or
// compressed), an XML plist whose resource fork's "blkx" entries describe
// one partition each (a "mish" block: its first sector and size, then its
// chunks: type, sectors, where the bytes are in the data fork), and a
// 512-byte "koly" trailer at the very end (big-endian) that says where the
// data fork and the plist are. The root filesystem's DMG is an Apple
// partition map whose "Apple_HFSX" partition is the system volume.

import { u32be, u64be, latin1 } from "../android/bytes.js";
import { plist_parse } from "./plist.js";

export const CHUNK = { ZERO: 0, RAW: 1, IGNORE: 2, ADC: 0x80000004, ZLIB: 0x80000005, BZIP2: 0x80000006, LZFSE: 0x80000007,
    COMMENT: 0x7FFFFFFE, END: 0xFFFFFFFF };

/**
 * @param {!Uint8Array} bytes the image's last 512 bytes
 * @return {{data_fork_offset: number, data_fork_length: number, xml_offset: number, xml_length: number, sectors: number}}
 */
export function udif_trailer(bytes)
{
    if(bytes.length !== 512 || latin1(bytes, 0, 4) !== "koly") throw new Error("DMG: no koly trailer");
    return {
        data_fork_offset: u64be(bytes, 0x18), data_fork_length: u64be(bytes, 0x20),
        xml_offset: u64be(bytes, 0xD8), xml_length: u64be(bytes, 0xE0),
        sectors: u64be(bytes, 0x1EC),
    };
}

/**
 * A partition's "mish" block
 * @param {!Uint8Array} b
 * @return {{first_sector: number, sectors: number, data_offset: number, chunks: !Array<{type: number, sector: number, sectors: number, offset: number, length: number}>}}
 */
export function udif_mish(b)
{
    if(b.length < 0xCC || latin1(b, 0, 4) !== "mish") throw new Error("DMG: a blkx entry without its mish block");
    const count = u32be(b, 0xC8);
    if(0xCC + 40 * count > b.length) throw new Error("DMG: a mish block cut short");
    const chunks = [];
    for(let i = 0; i < count; i++)
    {
        const at = 0xCC + 40 * i;
        chunks.push({ type: u32be(b, at), sector: u64be(b, at + 8), sectors: u64be(b, at + 16), offset: u64be(b, at + 24), length: u64be(b, at + 32) });
    }
    return { first_sector: u64be(b, 8), sectors: u64be(b, 0x10), data_offset: u64be(b, 0x18), chunks };
}

/**
 * The image's partitions, from its plist
 * @param {!Uint8Array} xml
 * @return {!Array<{name: string, id: number, first_sector: number, sectors: number, data_offset: number, chunks: !Array<Object>}>}
 */
export function udif_partitions(xml)
{
    const blkx = plist_parse(xml)?.["resource-fork"]?.blkx;
    if(!Array.isArray(blkx)) throw new Error("DMG: no blkx entries in the plist");
    return blkx.map(entry => ({ name: entry.Name || entry.CFName || "", id: +entry.ID, ...udif_mish(entry.Data) }));
}

/**
 * zlib (RFC 1950) inflated
 * @param {!Uint8Array} bytes
 * @return {!Promise<!Uint8Array>}
 */
export async function inflate_zlib(bytes)
{
    const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate"));
    return new Uint8Array(await new Response(stream).arrayBuffer());
}

/**
 * A partition's sectors out of the image's bytes written in order from the
 * start (a stream, as the root filesystem's decryption gives them):
 * out(offset, bytes) gets each data chunk's bytes at its offset in the
 * partition, in order (awaited); zero-filled and free chunks are left out
 * (the target reads as zeros there). end() checks every chunk came
 * @param {{first_sector: number, sectors: number, data_offset: number, chunks: !Array<Object>}} partition
 * @param {function(number, !Uint8Array): (Promise|undefined)} out
 * @param {number=} data_fork_offset the trailer's
 * @return {{write: function(!Uint8Array): !Promise, end: function(): !Promise}}
 */
export function udif_partition_stream(partition, out, data_fork_offset = 0)
{
    const chunks = partition.chunks.filter(c => c.type !== CHUNK.ZERO && c.type !== CHUNK.IGNORE &&
        c.type !== CHUNK.COMMENT && c.type !== CHUNK.END).sort((a, b) => a.offset - b.offset);
    for(const c of chunks)
    {
        if(c.type !== CHUNK.RAW && c.type !== CHUNK.ZLIB) throw new Error(`DMG: chunks of type 0x${c.type.toString(16)} are not supported`);
    }
    const base = data_fork_offset + partition.data_offset;
    let index = 0, position = 0, buffer = null, filled = 0;
    const finish = async () =>
    {
        const c = chunks[index++];
        const data = c.type === CHUNK.ZLIB ? await inflate_zlib(buffer) : buffer;
        if(data.length !== c.sectors * 512) throw new Error(`DMG: a chunk at sector ${c.sector} gives ${data.length} bytes, not ${c.sectors * 512}`);
        await out(c.sector * 512, data);
        buffer = null;
        filled = 0;
    };
    return {
        async write(bytes)
        {
            for(let at = 0; at < bytes.length && index < chunks.length;)
            {
                const c = chunks[index], start = base + c.offset;
                if(position < start)
                {
                    const skip = Math.min(bytes.length - at, start - position);
                    at += skip;
                    position += skip;
                    continue;
                }
                if(position > start) throw new Error("DMG: chunks overlap");
                if(!buffer) buffer = new Uint8Array(c.length);
                const n = Math.min(bytes.length - at, c.length - filled);
                buffer.set(bytes.subarray(at, at + n), filled);
                filled += n;
                at += n;
                if(filled === c.length)
                {
                    position += c.length;
                    await finish();
                }
            }
            if(index >= chunks.length) position += bytes.length;
        },
        async end()
        {
            if(index < chunks.length) throw new Error(`DMG: ${chunks.length - index} chunks missing, the image is cut short`);
        },
    };
}
                                                                                                                                                                                                      source/v64/src/ios/vfdecrypt.js                                                                     0000644 0000000 0000000 00000012026 00000000000 013612  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The root filesystem DMG's encryption (docs/iphone4-plan.md S0): FileVault's
// "encrcdsa" version 2 format as vfdecrypt reads it. The header (big-endian)
// gives the chunk size, the plain data's size and where the chunks start;
// each chunk is AES-128-CBC with IV = HMAC-SHA1(chunk number, big-endian
// 32 bits) cut to 16 bytes. The key page's root filesystem key is 36 bytes:
// the AES key, then the HMAC key.

import { u32be, u64be, latin1 } from "../android/bytes.js";
import { AES, HMAC_SHA1, from_hex } from "./crypto.js";

/**
 * @param {!Uint8Array} bytes the file's first bytes (0x48 at least)
 * @return {{block_size: number, data_size: number, data_offset: number}}
 */
export function encrcdsa_header(bytes)
{
    if(bytes.length < 0x48 || latin1(bytes, 0, 8) !== "encrcdsa") throw new Error("root filesystem: no encrcdsa header");
    const version = u32be(bytes, 8);
    if(version !== 2) throw new Error(`root filesystem: encrcdsa version ${version}`);
    const block_size = u32be(bytes, 52), data_size = u64be(bytes, 56), data_offset = u64be(bytes, 64);
    if(!block_size || block_size % 16) throw new Error(`root filesystem: a chunk of ${block_size} bytes`);
    return { block_size, data_size, data_offset };
}

/**
 * The chunk cipher
 * @constructor
 * @param {string|!Uint8Array} key 36 bytes
 * @param {number} block_size
 */
export function VFDecrypt(key, block_size)
{
    const k = typeof key === "string" ? from_hex(key) : key;
    if(k.length !== 36) throw new Error(`root filesystem: a ${k.length}-byte key, not 36`);
    this.aes = new AES(k.subarray(0, 16));
    this.hmac = new HMAC_SHA1(k.subarray(16));
    this.block_size = block_size;
    this.number = new Uint8Array(4);
}

/**
 * Chunk number n in place
 * @param {!Uint8Array} chunk
 * @param {number} n
 */
VFDecrypt.prototype.decrypt = function(chunk, n)
{
    this.number[0] = n >>> 24; this.number[1] = n >>> 16; this.number[2] = n >>> 8; this.number[3] = n;
    this.aes.cbc(chunk, this.hmac.mac(this.number).subarray(0, 16), true);
};

/**
 * Chunk number n in place, encrypted (tests)
 * @param {!Uint8Array} chunk
 * @param {number} n
 */
VFDecrypt.prototype.encrypt = function(chunk, n)
{
    this.number[0] = n >>> 24; this.number[1] = n >>> 16; this.number[2] = n >>> 8; this.number[3] = n;
    this.aes.cbc(chunk, this.hmac.mac(this.number).subarray(0, 16), false);
};

/**
 * A decrypting stream: write() the encrypted file's bytes in order, from
 * its start; sink(bytes, offset) gets the plain data in order, data_size
 * bytes in all (awaited), or only the chunks that want(offset, length)
 * accepts (the others are not decrypted). end() checks that the file was
 * whole
 * @param {string|!Uint8Array} key
 * @param {function(!Uint8Array, number): (Promise|undefined)} sink
 * @param {{want: (function(number, number): boolean|undefined)}=} options
 * @return {{write: function(!Uint8Array): !Promise, end: function(): !Promise, header: function(): ?Object}}
 */
export function vfdecrypt_stream(key, sink, options = {})
{
    const want = options.want || (() => true);
    let header = null, cipher = null, head = new Uint8Array(0), offset = 0, chunk = null, filled = 0, number = 0, out = 0;
    const flush = async () =>
    {
        const n = Math.min(chunk.length, header.data_size - out);
        if(n > 0 && want(out, n))
        {
            cipher.decrypt(chunk, number);
            await sink(chunk.slice(0, n), out);
        }
        number++;
        out += n;
        filled = 0;
    };
    return {
        header: () => header,
        async write(bytes)
        {
            let at = 0;
            if(!header)
            {
                const joined = new Uint8Array(head.length + bytes.length);
                joined.set(head);
                joined.set(bytes, head.length);
                head = joined;
                if(head.length < 0x48) return;
                header = encrcdsa_header(head);
                cipher = new VFDecrypt(key, header.block_size);
                chunk = new Uint8Array(header.block_size);
                bytes = head;
                head = null;
            }
            for(; at < bytes.length;)
            {
                if(offset < header.data_offset)
                {
                    const skip = Math.min(bytes.length - at, header.data_offset - offset);
                    at += skip;
                    offset += skip;
                    continue;
                }
                const n = Math.min(bytes.length - at, chunk.length - filled);
                chunk.set(bytes.subarray(at, at + n), filled);
                filled += n;
                at += n;
                offset += n;
                if(filled === chunk.length && out < header.data_size) await flush();
                else if(filled === chunk.length) filled = 0;
            }
        },
        async end()
        {
            if(!header) throw new Error("root filesystem: cut short before its header");
            if(out < header.data_size) throw new Error(`root filesystem: ${out} of ${header.data_size} bytes decrypted, the file is cut short`);
        },
    };
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/iso9660.js                                                                           0000644 0000000 0000000 00000034037 00000000000 012137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Source:
// - ISO9660: https://wiki.osdev.org/ISO_9660
// - Joliet: https://pismotec.com/cfs/jolspec.html

// Limitations:
// - can only generate iso files
// - only supports a single directory, no file system hierarchy
// - root directory entry is limited to 2 KiB (~42 files)

import { dbg_assert } from "./log.js";

const BLOCK_SIZE = 2 * 1024; // 0x800

const FILE_FLAGS_HIDDEN = 1 << 0;
const FILE_FLAGS_DIRECTORY = 1 << 1;
const FILE_FLAGS_ASSOCIATED_FILE = 1 << 2;
const FILE_FLAGS_HAS_EXTENDED_ATTRIBUTE_RECORD = 1 << 3;
const FILE_FLAGS_HAS_PERMISSIONS = 1 << 4;
const FILE_FLAGS_NOT_FINAL = 1 << 7;

const SYSTEM_ID = "V86";
const VOLUME_ID = "CDROM";

/**
 * @param {Array.<{ name: string, contents: Uint8Array}>} files
 */
export function generate(files)
{
    const te = new TextEncoder();
    const date = new Date;

    const write8 = (b, v) => { b.buffer[b.offset++] = v; };
    const write_le16 = (b, v) => { b.buffer[b.offset++] = v; b.buffer[b.offset++] = v >> 8; };
    const write_le32 = (b, v) => { b.buffer[b.offset++] = v; b.buffer[b.offset++] = v >> 8; b.buffer[b.offset++] = v >> 16; b.buffer[b.offset++] = v >> 24; };
    const write_be16 = (b, v) => { b.buffer[b.offset++] = v >> 8; b.buffer[b.offset++] = v; };
    const write_be32 = (b, v) => { b.buffer[b.offset++] = v >> 24; b.buffer[b.offset++] = v >> 16; b.buffer[b.offset++] = v >> 8; b.buffer[b.offset++] = v; };
    const write_lebe16 = (b, v) => { write_le16(b, v); write_be16(b, v); };
    const write_lebe32 = (b, v) => { write_le32(b, v); write_be32(b, v); };
    const fill = (b, len, v) => { b.buffer.fill(v, b.offset, b.offset += len); };
    const write_ascii = (b, v) => { b.offset += te.encodeInto(v, b.buffer.subarray(b.offset)).written; };
    const write_padded_ascii = (b, len, v) => { b.offset += te.encodeInto(v.padEnd(len), b.buffer.subarray(b.offset)).written; };
    const write_dummy_date_ascii = b => { fill(b, 16, 0x20); write8(b, 0); };
    const write_date_compact = b => {
        write8(b, date.getUTCFullYear() - 1900);
        write8(b, 1 + date.getUTCMonth());
        write8(b, date.getUTCDate());
        write8(b, date.getUTCHours());
        write8(b, date.getUTCMinutes());
        write8(b, date.getUTCSeconds());
        write8(b, 0);
    };
    const skip = (b, len) => { b.offset += len; };
    const write_utf16be = (b, v) => {
        for(let i = 0; i < v.length; i++) write_be16(b, v.charCodeAt(i));
        return v.length * 2;
    };
    const write_padded_utf16be = (b, len, v) => write_utf16be(b, v.padEnd(len / 2));

    const write_record = (b, name, flags, is_special, lba, len, joliet) => {
        // write name first and get its length
        const START = b.offset;
        const NAME_OFFSET = 33;
        let name_len = 0;
        if(joliet)
        {
            // encode into utf16be
            name = sanitise_filename_joliet(name);
            let name_buffer = {
                buffer: b.buffer,
                offset: START + NAME_OFFSET,
            };
            name_len = write_utf16be(name_buffer, name);
        }
        else
        {
            if(!is_special) name = sanitise_filename(name) + ";1";
            name_len = te.encodeInto(name, b.buffer.subarray(b.offset + NAME_OFFSET)).written;
        }
        const pad = (name_len & 1) ? 0 : 1;
        const len_field = 33 + name_len + pad;
        dbg_assert(len_field < 256);

        write8(b, len_field);      // Length of directory record
        write8(b, 0);              // Extended Attribute Record length
        write_lebe32(b, lba);      // Location of extent (LBA)
        write_lebe32(b, len);      // Data length (size of extent)
        write_date_compact(b);
        write8(b, flags);
        write8(b, 0);              // File unit size for files recorded in interleaved mode, zero otherwise
        write8(b, 0);              // Interleave gap size for files recorded in interleaved mode, zero otherwise
        write_lebe16(b, 1);        // Volume sequence number - the volume that this extent is recorded on
        write8(b, name_len);       // length of file name
        dbg_assert(b.offset === START + NAME_OFFSET);
        skip(b, name_len + pad);   // File name: was already written
        dbg_assert(b.offset === START + len_field);
    };
    const write_special_directory_record = (b, name, lba, len) => write_record(b, name, FILE_FLAGS_DIRECTORY, true, lba, len, false);
    const write_file_record = (b, name, lba, len, joliet) => write_record(b, name, 0, false, lba, len, joliet);

    function round_byte_size_to_block_size(n)
    {
        return 1 + Math.floor((n - 1) / BLOCK_SIZE);
    }
    dbg_assert(round_byte_size_to_block_size(0) === 0);
    dbg_assert(round_byte_size_to_block_size(1) === 1);
    dbg_assert(round_byte_size_to_block_size(BLOCK_SIZE - 1) === 1);
    dbg_assert(round_byte_size_to_block_size(BLOCK_SIZE) === 1);
    dbg_assert(round_byte_size_to_block_size(BLOCK_SIZE + 1) === 2);
    dbg_assert(round_byte_size_to_block_size(2 * BLOCK_SIZE) === 2);
    dbg_assert(round_byte_size_to_block_size(2 * BLOCK_SIZE + 1) === 3);
    dbg_assert(round_byte_size_to_block_size(10 * BLOCK_SIZE + 1) === 11);

    function to_msdos_filename(name)
    {
        const dot = name.lastIndexOf(".");
        if(dot === -1) return name.substr(0, 8);
        return name.substr(0, Math.min(8, dot)) + "." + name.substr(dot + 1, 3);
    }

    dbg_assert(to_msdos_filename("abcdefghijkl.qwerty") === "abcdefgh.qwe");
    dbg_assert(to_msdos_filename("abcdefghijkl") === "abcdefgh");

    function sanitise_filename(name)
    {
        return to_msdos_filename(name.toUpperCase().replace(/[^A-Z0-9_.]/g, ""));
    }

    function sanitise_filename_joliet(name)
    {
        return name.replace(/[*\/:;?\\]/g, "");
    }

    // layout:
    // (lba = one block of BLOCK_SIZE bytes)
    // LBA   | contents
    // ------+--------
    // 0..15 | System Area (could be used for mbr, but not used by us)
    //    16 | Primary Volume Descriptor
    //    17 | Supplementary Volume Descriptor (Joliet)
    //    18 | Volume Descriptor Set Terminator
    //    19 | Little Endian Path Table
    //    20 | Little Endian Path Table (Joliet)
    //    21 | Big Endian Path Table
    //    22 | Big Endian Path Table (Joliet)
    //    23 | Root directory
    //    24 | Root directory (Joliet)
    // 25..n | File contents
    const SYSTEM_AREA_SIZE = 16 * BLOCK_SIZE;
    const PRIMARY_VOLUME_LBA = 16;
    const SUPPLEMENTARY_VOLUME_LBA = 17;
    const VOLUME_SET_TERMINATOR_LBA = 18;
    const LE_PATH_TABLE_LBA = 19;
    const LE_PATH_TABLE_JOLIET_LBA = 20;
    const BE_PATH_TABLE_LBA = 21;
    const BE_PATH_TABLE_JOLIET_LBA = 22;
    const ROOT_DIRECTORY_LBA = 23;
    const ROOT_DIRECTORY_JOLIET_LBA = 24;
    const LE_PATH_TABLE_SIZE = BLOCK_SIZE;
    const BE_PATH_TABLE_SIZE = BLOCK_SIZE;
    const ROOT_DIRECTORY_SIZE = BLOCK_SIZE;

    const write_volume_descriptor = (is_supplementary) => {
        const VD_OFFSET = (is_supplementary ? SUPPLEMENTARY_VOLUME_LBA : PRIMARY_VOLUME_LBA) * BLOCK_SIZE;

        write8(buffer, is_supplementary ? 0x02 : 0x01); // Volume Descriptor type: Primary/Supplementary Volume Descriptor
        write_ascii(buffer, "CD001");               // Always CD001
        write8(buffer, 0x01);                       // Version
        write8(buffer, 0x00);                       // unused
        if(is_supplementary)
        {
            write_padded_utf16be(buffer, 32, SYSTEM_ID);    // System Identifier
            write_padded_utf16be(buffer, 32, VOLUME_ID);    // Identification of this volume
        }
        else
        {
            write_padded_ascii(buffer, 32, SYSTEM_ID);
            write_padded_ascii(buffer, 32, VOLUME_ID);
        }

        skip(buffer, 8);                            // unused
        write_lebe32(buffer, N_LBAS);

        // Escape Sequence
        if(is_supplementary)
        {
            write_ascii(buffer, "%/C"); // UTF-16BE
            skip(buffer, 29);
        }
        else
        {
            skip(buffer, 32); // unused
        }
        dbg_assert(buffer.offset === VD_OFFSET + 120);

        write_lebe16(buffer, 1); // Volume Set Size
        write_lebe16(buffer, 1); // Volume Sequence Number
        dbg_assert(buffer.offset === VD_OFFSET + 128);

        write_lebe16(buffer, BLOCK_SIZE);

        write_lebe32(buffer, 10);               // Path Table Size
        write_le32(buffer, is_supplementary ? LE_PATH_TABLE_JOLIET_LBA : LE_PATH_TABLE_LBA);  // Location of Type-L Path Table
        write_le32(buffer, 0);                  // Location of the Optional Type-L Path Table
        write_be32(buffer, is_supplementary ? BE_PATH_TABLE_JOLIET_LBA : BE_PATH_TABLE_LBA);  // Location of Type-M Path Table
        write_be32(buffer, 0);                  // Location of the Optional Type-M Path Table
        dbg_assert(buffer.offset === VD_OFFSET + 156);

        // Directory entry for the root directory
        write_special_directory_record(buffer, "\x00", is_supplementary ? ROOT_DIRECTORY_JOLIET_LBA : ROOT_DIRECTORY_LBA, 0x800);
        dbg_assert(buffer.offset === VD_OFFSET + 190);

        fill(buffer, 128, 0x20); // Volume Set Identifier
        fill(buffer, 128, 0x20); // Publisher Identifier
        fill(buffer, 128, 0x20); // Data Preparer Identifier
        fill(buffer, 128, 0x20); // Application Identifier
        fill(buffer,  37, 0x20); // Copyright File Identifier
        fill(buffer,  37, 0x20); // Abstract File Identifier
        fill(buffer,  37, 0x20); // Bibliographic File Identifier

        dbg_assert(buffer.offset === VD_OFFSET + 813);

        write_dummy_date_ascii(buffer); // Volume Creation Date and Time
        write_dummy_date_ascii(buffer); // Volume Modification Date and Time
        write_dummy_date_ascii(buffer); // Volume Expiration Date and Time
        write_dummy_date_ascii(buffer); // Volume Effective Date and Time

        write8(buffer, 0x01); // File Structure Version
        dbg_assert(buffer.offset === VD_OFFSET + 882);

        write8(buffer, 0x00); // Unused
        skip(buffer, 512);    // Application Used
        skip(buffer, 653);    // Reserved
    };

    const write_path_table = (start_lba, root_lba, is_le) => {
        buffer.offset = start_lba * BLOCK_SIZE;
        write8(buffer, 0x01);                   // Length of Directory Identifier
        write8(buffer, 0x00);                   // Extended Attribute Record Length
        if(is_le)
        {
            write_le32(buffer, root_lba);       // Location of Extent (LBA) ROOT_DIRECTORY_LBA
            write_le16(buffer, 1);              // Directory number of parent directory
        }
        else
        {
            write_be32(buffer, root_lba);
            write_be16(buffer, 1);
        }
        write_ascii(buffer, "\x00");            // file name
    };

    let next_file_lba = 25;
    const iso_files = files.map(({ name, contents }) => {
        const lba = next_file_lba;
        next_file_lba += round_byte_size_to_block_size(contents.length);
        return { name, contents, lba };
    });

    const write_root_directory = (start_lba, joliet) => {
        write_special_directory_record(buffer, "\x00", start_lba, 0x800);  // "."
        write_special_directory_record(buffer, "\x01", start_lba, 0x800);  // ".."
        for(const { name, contents, lba } of iso_files)
        {
            write_file_record(buffer, joliet ? name : to_msdos_filename(name), lba, contents.length, joliet);
        }
    };

    const N_LBAS = next_file_lba;
    const total_size = N_LBAS * BLOCK_SIZE;

    const buffer = {
        buffer: new Uint8Array(total_size),
        offset: SYSTEM_AREA_SIZE,
    };

    // LBA 16: Primary Volume Descriptor
    dbg_assert(buffer.offset === PRIMARY_VOLUME_LBA * BLOCK_SIZE);
    write_volume_descriptor(false);

    // LBA 17: Supplementary Volume Descriptor
    dbg_assert(buffer.offset === SUPPLEMENTARY_VOLUME_LBA * BLOCK_SIZE);
    write_volume_descriptor(true);

    // LBA 18: Volume Descriptor Set Terminator
    dbg_assert(buffer.offset === VOLUME_SET_TERMINATOR_LBA * BLOCK_SIZE);
    write8(buffer, 0xFF);           // 0xFF: Volume Descriptor Set Terminator
    write_ascii(buffer, "CD001");   // Always CD001
    write8(buffer, 0x01);           // Version

    // LBA 19: Little Endian Path Table
    write_path_table(LE_PATH_TABLE_LBA, ROOT_DIRECTORY_LBA, true);
    dbg_assert(buffer.offset < LE_PATH_TABLE_LBA * BLOCK_SIZE + LE_PATH_TABLE_SIZE);

    // LBA 20: Little Endian Path Table (Joliet)
    write_path_table(LE_PATH_TABLE_JOLIET_LBA, ROOT_DIRECTORY_JOLIET_LBA, true);
    dbg_assert(buffer.offset < LE_PATH_TABLE_JOLIET_LBA * BLOCK_SIZE + LE_PATH_TABLE_SIZE);

    // LBA 21: Big Endian Path Table
    write_path_table(BE_PATH_TABLE_LBA, ROOT_DIRECTORY_LBA, false);
    dbg_assert(buffer.offset < BE_PATH_TABLE_LBA * BLOCK_SIZE + BE_PATH_TABLE_SIZE);

    // LBA 22: Big Endian Path Table (Joliet)
    write_path_table(BE_PATH_TABLE_JOLIET_LBA, ROOT_DIRECTORY_JOLIET_LBA, false);
    dbg_assert(buffer.offset < BE_PATH_TABLE_JOLIET_LBA * BLOCK_SIZE + BE_PATH_TABLE_SIZE);

    // LBA 23: root directory
    buffer.offset = ROOT_DIRECTORY_LBA * BLOCK_SIZE;
    write_root_directory(ROOT_DIRECTORY_LBA, false);
    // TODO: this assertion can fail if too many files are used as input
    // ROOT_DIRECTORY_SIZE should be choosen dynamically
    dbg_assert(buffer.offset < ROOT_DIRECTORY_LBA * BLOCK_SIZE + ROOT_DIRECTORY_SIZE);

    // LBA 24: root directory (Joliet)
    buffer.offset = ROOT_DIRECTORY_JOLIET_LBA * BLOCK_SIZE;
    write_root_directory(ROOT_DIRECTORY_JOLIET_LBA, true);
    dbg_assert(buffer.offset < ROOT_DIRECTORY_JOLIET_LBA * BLOCK_SIZE + ROOT_DIRECTORY_SIZE);

    // file contents
    for(let { contents, lba } of iso_files)
    {
        buffer.buffer.set(contents, lba * BLOCK_SIZE);
    }

    return buffer.buffer;
}

/**
 * @param {Uint8Array} buffer
 */
export function is_probably_iso9660_file(buffer)
{
    return (
        buffer.length >= 17 * BLOCK_SIZE &&
        buffer[BLOCK_SIZE + 0] ===  1 && // Primary Volume Descriptor
        buffer[BLOCK_SIZE + 1] === 67 && // "C"
        buffer[BLOCK_SIZE + 2] === 68 && // "D"
        buffer[BLOCK_SIZE + 3] === 48 && // "0"
        buffer[BLOCK_SIZE + 4] === 48 && // "0"
        buffer[BLOCK_SIZE + 5] === 49    // "1"
    );
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/src/jit_switches.js                                                                      0000644 0000000 0000000 00000007140 00000000000 013512  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The JIT switches of src/rust/jit_switches.rs (docs/jit-unification-plan.md,
// cross-phase rule 1). The names come from the Wasm module; values are set by
// name, from the build's JIT_DEFAULTS, the V86 option jit_switches
// ({ name: value } or "name=value,...") and, in tests, JIT_SWITCHES
// (tests/lib/jit_switches.mjs).

const UNSET = 0xFFFFFFFF;

// (a copy: TextDecoder refuses views of the parallel build's shared memory)
function text(exports, memory, which)
{
    const bytes = new Uint8Array(memory.buffer, exports["jit_switch_text"](which) >>> 0, exports["jit_switch_text_length"](which) >>> 0).slice();
    return new TextDecoder().decode(bytes);
}

/**
 * The switches of a v86 Wasm module, by id; none for a module without them
 * @return {Array<{name: string, default: number}>}
 */
export function jit_switch_table(exports, memory)
{
    if(!exports["jit_switch_count"]) return [];
    return text(exports, memory, 0).split("\n").filter(Boolean).map(line => {
        const [name, value] = line.split(" ");
        return { name, default: Number(value) };
    });
}

/**
 * "name=value, ..." or an object, as an object; booleans become 0 and 1
 * @param {Object|string|undefined} values
 * @return {!Object<string, number>}
 */
export function parse_jit_switches(values)
{
    const result = {};
    if(values === undefined || values === null) return result;
    if(typeof values === "object")
    {
        for(const [name, value] of Object.entries(values)) result[name] = typeof value === "boolean" ? +value : value;
        return result;
    }
    for(const pair of String(values).split(",").map(p => p.trim()).filter(Boolean))
    {
        const match = /^([a-z0-9_]+)\s*=\s*(\d+)$/.exec(pair);
        if(!match) throw new Error("JIT switches: expected name=value, not " + JSON.stringify(pair));
        result[match[1]] = Number(match[2]);
    }
    return result;
}

/**
 * Sets switches by name, in the registry's order (src/rust/jit_switches.rs).
 * Throws on an unknown name, and on a value the module refuses: out of range,
 * or a change it allows only before anything is compiled. `origin` names the
 * source in the message.
 */
export function set_jit_switches(exports, memory, values, origin = "jit_switches")
{
    const wanted = parse_jit_switches(values);
    const names = Object.keys(wanted);
    if(!names.length) return;
    const table = jit_switch_table(exports, memory);
    for(const name of names)
    {
        if(!table.some(s => s.name === name))
            throw new Error(`${origin}: no JIT switch ${name} (the switches: ${table.map(s => s.name).join(", ")})`);
    }
    table.forEach(({ name }, id) => {
        if(!(name in wanted)) return;
        const value = wanted[name];
        if(!Number.isInteger(value) || value < 0 || value >= UNSET || !exports["jit_set_switch"](id, value))
            throw new Error(`${origin}: the JIT switch ${name} cannot be ${value} now`);
    });
}

/**
 * The value of each switch: all of them, or with `explicit` only those set
 * through set_jit_switches (what a vCPU worker is started with)
 * @return {!Object<string, number>}
 */
export function get_jit_switches(exports, memory, explicit = false)
{
    const result = {};
    jit_switch_table(exports, memory).forEach(({ name }, id) => {
        const value = (explicit ? exports["jit_switch_explicit"](id) : exports["jit_switch"](id)) >>> 0;
        if(value !== UNSET) result[name] = value;
    });
    return result;
}

/** The build's JIT_DEFAULTS (Makefile), as an object */
export function build_jit_defaults(exports, memory)
{
    return exports["jit_switch_count"] ? parse_jit_switches(text(exports, memory, 1)) : {};
}
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/src/kernel.js                                                                            0000644 0000000 0000000 00000020451 00000000000 012273  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";


// https://www.kernel.org/doc/Documentation/x86/boot.txt

const LINUX_BOOT_HDR_SETUP_SECTS = 0x1F1;
const LINUX_BOOT_HDR_SYSSIZE = 0x1F4;
const LINUX_BOOT_HDR_VIDMODE = 0x1FA;
const LINUX_BOOT_HDR_BOOT_FLAG = 0x1FE;
const LINUX_BOOT_HDR_HEADER = 0x202;
const LINUX_BOOT_HDR_VERSION = 0x206;
const LINUX_BOOT_HDR_TYPE_OF_LOADER = 0x210;
const LINUX_BOOT_HDR_LOADFLAGS = 0x211;
const LINUX_BOOT_HDR_CODE32_START = 0x214;
const LINUX_BOOT_HDR_RAMDISK_IMAGE = 0x218;
const LINUX_BOOT_HDR_RAMDISK_SIZE = 0x21C;
const LINUX_BOOT_HDR_HEAP_END_PTR = 0x224;
const LINUX_BOOT_HDR_CMD_LINE_PTR = 0x228;
const LINUX_BOOT_HDR_INITRD_ADDR_MAX = 0x22C;
const LINUX_BOOT_HDR_KERNEL_ALIGNMENT = 0x230;
const LINUX_BOOT_HDR_RELOCATABLE_KERNEL = 0x234;
const LINUX_BOOT_HDR_MIN_ALIGNMENT = 0x235;
const LINUX_BOOT_HDR_XLOADFLAGS = 0x236;
const LINUX_BOOT_HDR_CMDLINE_SIZE = 0x238;
const LINUX_BOOT_HDR_PAYLOAD_OFFSET = 0x248;
const LINUX_BOOT_HDR_PAYLOAD_LENGTH = 0x24C;
const LINUX_BOOT_HDR_PREF_ADDRESS = 0x258;
const LINUX_BOOT_HDR_INIT_SIZE = 0x260;

const LINUX_BOOT_HDR_CHECKSUM1 = 0xAA55;
const LINUX_BOOT_HDR_CHECKSUM2 = 0x53726448;

const LINUX_BOOT_HDR_TYPE_OF_LOADER_NOT_ASSIGNED = 0xFF;

const LINUX_BOOT_HDR_LOADFLAGS_LOADED_HIGH = 1 << 0;
const LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG = 1 << 5;
const LINUX_BOOT_HDR_LOADFLAGS_KEEP_SEGMENTS = 1 << 6;
const LINUX_BOOT_HDR_LOADFLAGS_CAN_USE_HEAPS = 1 << 7;


export function load_kernel(mem8, bzimage, initrd, cmdline)
{
    dbg_log("Trying to load kernel of size " + bzimage.byteLength);

    const KERNEL_HIGH_ADDRESS = 0x100000;

    // Put the initrd at the 64 MB boundary. This means the minimum memory size
    // is 64 MB plus the size of the initrd.
    // Note: If set too low, kernel may fail to load the initrd with "invalid magic at start of compressed archive"
    const INITRD_ADDRESS = 64 << 20;

    const quiet = false;

    const bzimage8 = new Uint8Array(bzimage);
    const bzimage16 = new Uint16Array(bzimage);
    const bzimage32 = new Uint32Array(bzimage);

    const setup_sects = bzimage8[LINUX_BOOT_HDR_SETUP_SECTS] || 4;
    const syssize = bzimage32[LINUX_BOOT_HDR_SYSSIZE >> 2] << 4;

    const vidmode = bzimage16[LINUX_BOOT_HDR_VIDMODE >> 1];

    const checksum1 = bzimage16[LINUX_BOOT_HDR_BOOT_FLAG >> 1];
    if(checksum1 !== LINUX_BOOT_HDR_CHECKSUM1)
    {
        throw new Error("bzimage: no Linux boot sector signature (" + h(checksum1) + ")");
    }

    // Not aligned, so split into two 16-bit reads
    const checksum2 =
        bzimage16[LINUX_BOOT_HDR_HEADER >> 1] |
        bzimage16[LINUX_BOOT_HDR_HEADER + 2 >> 1] << 16;
    if(checksum2 !== LINUX_BOOT_HDR_CHECKSUM2)
    {
        throw new Error("bzimage: no Linux boot protocol header (" + h(checksum2) + ")");
    }

    const protocol = bzimage16[LINUX_BOOT_HDR_VERSION >> 1];
    if(protocol < 0x202)
    {
        throw new Error("bzimage: Linux boot protocol " + h(protocol) + " is older than 2.02 (not supported)");
    }

    const flags = bzimage8[LINUX_BOOT_HDR_LOADFLAGS];
    if(!(flags & LINUX_BOOT_HDR_LOADFLAGS_LOADED_HIGH))
    {
        throw new Error("bzimage: zImage kernels loaded low are not supported");
    }

    // we don't relocate the kernel, so we don't care much about most of these

    const flags2 = bzimage16[LINUX_BOOT_HDR_XLOADFLAGS >> 1];
    const initrd_addr_max = bzimage32[LINUX_BOOT_HDR_INITRD_ADDR_MAX >> 2];
    const kernel_alignment = bzimage32[LINUX_BOOT_HDR_KERNEL_ALIGNMENT >> 2];
    const relocatable_kernel = bzimage8[LINUX_BOOT_HDR_RELOCATABLE_KERNEL];
    const min_alignment = bzimage8[LINUX_BOOT_HDR_MIN_ALIGNMENT];
    const cmdline_size = protocol >= 0x206 ? bzimage32[LINUX_BOOT_HDR_CMDLINE_SIZE >> 2] : 255;
    const payload_offset = bzimage32[LINUX_BOOT_HDR_PAYLOAD_OFFSET >> 2];
    const payload_length = bzimage32[LINUX_BOOT_HDR_PAYLOAD_LENGTH >> 2];
    const pref_address = bzimage32[LINUX_BOOT_HDR_PREF_ADDRESS >> 2];
    const pref_address_high = bzimage32[LINUX_BOOT_HDR_PREF_ADDRESS + 4 >> 2];
    const init_size = bzimage32[LINUX_BOOT_HDR_INIT_SIZE >> 2];

    dbg_log("kernel boot protocol version: " + h(protocol));
    dbg_log("flags=" + h(flags) + " xflags=" + h(flags2));
    dbg_log("code32_start=" + h(bzimage32[LINUX_BOOT_HDR_CODE32_START >> 2]));
    dbg_log("initrd_addr_max=" + h(initrd_addr_max));
    dbg_log("kernel_alignment=" + h(kernel_alignment));
    dbg_log("relocatable=" + relocatable_kernel);
    dbg_log("min_alignment=" + h(min_alignment));
    dbg_log("cmdline max=" + h(cmdline_size));
    dbg_log("payload offset=" + h(payload_offset) + " size=" + h(payload_length));
    dbg_log("pref_address=" + h(pref_address_high) + ":" + h(pref_address));
    dbg_log("init_size=" + h(init_size));

    const real_mode_segment = 0x8000;
    const base_ptr = real_mode_segment << 4;

    const heap_end = 0xE000;
    const heap_end_ptr = heap_end - 0x200;

    // fill in the kernel boot header with infos the kernel needs to know

    bzimage8[LINUX_BOOT_HDR_TYPE_OF_LOADER] = LINUX_BOOT_HDR_TYPE_OF_LOADER_NOT_ASSIGNED;

    const new_flags =
        (quiet ? flags | LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG : flags & ~LINUX_BOOT_HDR_LOADFLAGS_QUIET_FLAG)
        & ~LINUX_BOOT_HDR_LOADFLAGS_KEEP_SEGMENTS
        | LINUX_BOOT_HDR_LOADFLAGS_CAN_USE_HEAPS;
    bzimage8[LINUX_BOOT_HDR_LOADFLAGS] = new_flags;

    bzimage16[LINUX_BOOT_HDR_HEAP_END_PTR >> 1] = heap_end_ptr;

    // should parse the vga=... paramter from cmdline here, but we don't really care
    bzimage16[LINUX_BOOT_HDR_VIDMODE >> 1] = 0xFFFF; // normal

    dbg_log("heap_end_ptr=" + h(heap_end_ptr));

    cmdline += "\x00";
    dbg_assert(cmdline.length < cmdline_size);

    const cmd_line_ptr = base_ptr + heap_end;
    dbg_log("cmd_line_ptr=" + h(cmd_line_ptr));

    bzimage32[LINUX_BOOT_HDR_CMD_LINE_PTR >> 2] = cmd_line_ptr;
    for(let i = 0; i < cmdline.length; i++)
    {
        mem8[cmd_line_ptr + i] = cmdline.charCodeAt(i);
    }

    const prot_mode_kernel_start = (setup_sects + 1) * 512;
    dbg_log("prot_mode_kernel_start=" + h(prot_mode_kernel_start));

    const real_mode_kernel = new Uint8Array(bzimage, 0, prot_mode_kernel_start);
    const protected_mode_kernel = new Uint8Array(bzimage, prot_mode_kernel_start);

    let ramdisk_address = 0;
    let ramdisk_size = 0;

    if(initrd)
    {
        ramdisk_address = INITRD_ADDRESS;
        ramdisk_size = initrd.byteLength;

        dbg_assert(KERNEL_HIGH_ADDRESS + protected_mode_kernel.length < ramdisk_address);

        mem8.set(new Uint8Array(initrd), ramdisk_address);
    }

    bzimage32[LINUX_BOOT_HDR_RAMDISK_IMAGE >> 2] = ramdisk_address;
    bzimage32[LINUX_BOOT_HDR_RAMDISK_SIZE >> 2] = ramdisk_size;

    dbg_assert(base_ptr + real_mode_kernel.length < 0xA0000);

    mem8.set(real_mode_kernel, base_ptr);
    mem8.set(protected_mode_kernel, KERNEL_HIGH_ADDRESS);

    return {
        name: "genroms/kernel.bin",
        data: make_linux_boot_rom(real_mode_segment, heap_end),
    };
}

function make_linux_boot_rom(real_mode_segment, heap_end)
{
    // This rom will be executed by seabios after its initialisation
    // It sets up segment registers, the stack and calls the kernel real mode entry point

    const SIZE = 0x200;

    const data8 = new Uint8Array(SIZE);
    const data16 = new Uint16Array(data8.buffer);

    data16[0] = 0xAA55;
    data8[2] = SIZE / 0x200;

    let i = 3;

    data8[i++] = 0xFA; // cli
    data8[i++] = 0xB8; // mov ax, real_mode_segment
    data8[i++] = real_mode_segment >> 0;
    data8[i++] = real_mode_segment >> 8;
    data8[i++] = 0x8E; // mov es, ax
    data8[i++] = 0xC0;
    data8[i++] = 0x8E; // mov ds, ax
    data8[i++] = 0xD8;
    data8[i++] = 0x8E; // mov fs, ax
    data8[i++] = 0xE0;
    data8[i++] = 0x8E; // mov gs, ax
    data8[i++] = 0xE8;
    data8[i++] = 0x8E; // mov ss, ax
    data8[i++] = 0xD0;
    data8[i++] = 0xBC; // mov sp, heap_end
    data8[i++] = heap_end >> 0;
    data8[i++] = heap_end >> 8;
    data8[i++] = 0xEA; // jmp (real_mode_segment+0x20):0x0
    data8[i++] = 0x00;
    data8[i++] = 0x00;
    data8[i++] = real_mode_segment + 0x20 >> 0;
    data8[i++] = real_mode_segment + 0x20 >> 8;

    dbg_assert(i < SIZE);

    const checksum_index = i;
    data8[checksum_index] = 0;

    let checksum = 0;

    for(let i = 0; i < data8.length; i++)
    {
        checksum += data8[i];
    }

    data8[checksum_index] = -checksum;

    return data8;
}
                                                                                                                                                                                                                       source/v64/src/lib.js                                                                               0000644 0000000 0000000 00000051566 00000000000 011574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "./log.js";

// pad string with spaces on the right
export function pads(str, len)
{
    str = (str || str === 0) ? str + "" : "";
    return str.padEnd(len, " ");
}

// pad string with zeros on the left
export function pad0(str, len)
{
    str = (str || str === 0) ? str + "" : "";
    return str.padStart(len, "0");
}

export var view = function(constructor, memory, offset, length)
{
    dbg_assert(offset >= 0);
    return new Proxy({},
        {
            get: function(target, property, receiver)
            {
                const b = new constructor(memory.buffer, offset, length);
                const x = b[property];
                if(typeof x === "function")
                {
                    return x.bind(b);
                }
                dbg_assert(/^\d+$/.test(property) || property === "buffer" || property === "length" ||
                    property === "BYTES_PER_ELEMENT" || property === "byteOffset");
                return x;
            },
            set: function(target, property, value, receiver)
            {
                dbg_assert(/^\d+$/.test(property));
                new constructor(memory.buffer, offset, length)[property] = value;
                return true;
            },
        });
};

/**
 * number to hex
 * @param {number} n
 * @param {number=} len
 * @return {string}
 */
export function h(n, len)
{
    if(!n)
    {
        var str = "";
    }
    else
    {
        var str = n.toString(16);
    }

    return "0x" + pad0(str.toUpperCase(), len || 1);
}

export function hex_dump(buffer)
{
    function hex(n, len)
    {
        return pad0(n.toString(16).toUpperCase(), len);
    }

    const result = [];
    let offset = 0;

    for(; offset + 15 < buffer.length; offset += 16)
    {
        let line = hex(offset, 5) + "   ";

        for(let j = 0; j < 0x10; j++)
        {
            line += hex(buffer[offset + j], 2) + " ";
        }

        line += "  ";

        for(let j = 0; j < 0x10; j++)
        {
            const x = buffer[offset + j];
            line += (x >= 33 && x !== 34 && x !== 92 && x <= 126) ? String.fromCharCode(x) : ".";
        }

        result.push(line);
    }

    let line = hex(offset, 5) + "   ";

    for(; offset < buffer.length; offset++)
    {
        line += hex(buffer[offset], 2) + " ";
    }

    const remainder = offset & 0xF;
    line += "   ".repeat(0x10 - remainder);
    line += "  ";

    for(let j = 0; j < remainder; j++)
    {
        const x = buffer[offset + j];
        line += (x >= 33 && x !== 34 && x !== 92 && x <= 126) ? String.fromCharCode(x) : ".";
    }

    result.push(line);

    return "\n" + result.join("\n") + "\n";
}

/* global require */
export var get_rand_int;
if(typeof crypto !== "undefined" && crypto.getRandomValues)
{
    const rand_data = new Int32Array(1);

    get_rand_int = function()
    {
        crypto.getRandomValues(rand_data);
        return rand_data[0];
    };
}
else if(typeof require !== "undefined")
{
    /** @type {{ randomBytes: Function }} */
    const crypto = require("crypto");

    get_rand_int = function()
    {
        return crypto.randomBytes(4)["readInt32LE"](0);
    };
}
else if(typeof process !== "undefined")
    {
        import("node:" + "crypto").then(crypto => {
            get_rand_int = function()
            {
                return crypto["randomBytes"](4)["readInt32LE"](0);
            };
        });
    }
else
{
    dbg_assert(false, "Unsupported platform: No cryptographic random values");
}

export var int_log2;

if(typeof Math.clz32 === "function" && Math.clz32(0) === 32 && Math.clz32(0x12345) === 15 && Math.clz32(-1) === 0)
{
    /**
     * calculate the integer logarithm base 2
     * @param {number} x
     * @return {number}
     */
    int_log2 = function(x)
    {
        dbg_assert(x > 0);

        return 31 - Math.clz32(x);
    };
} else {

    var int_log2_table = new Int8Array(256);

    for(var i = 0, b = -2; i < 256; i++)
    {
        if(!(i & i - 1))
            b++;

        int_log2_table[i] = b;
    }

    /**
     * calculate the integer logarithm base 2
     * @param {number} x
     * @return {number}
     */
    int_log2 = function(x)
    {
        x >>>= 0;
        dbg_assert(x > 0);

        // http://jsperf.com/integer-log2/6
        var tt = x >>> 16;

        if(tt)
        {
            var t = tt >>> 8;
            if(t)
            {
                return 24 + int_log2_table[t];
            }
            else
            {
                return 16 + int_log2_table[tt];
            }
        }
        else
        {
            var t = x >>> 8;
            if(t)
            {
                return 8 + int_log2_table[t];
            }
            else
            {
                return int_log2_table[x];
            }
        }
    };
}

export const round_up_to_next_power_of_2 = function(x)
{
    dbg_assert(x >= 0);
    return x <= 1 ? 1 : 1 << 1 + int_log2(x - 1);
};

if(typeof DEBUG !== "undefined" && DEBUG)
{
    dbg_assert(int_log2(1) === 0);
    dbg_assert(int_log2(2) === 1);
    dbg_assert(int_log2(7) === 2);
    dbg_assert(int_log2(8) === 3);
    dbg_assert(int_log2(123456789) === 26);

    dbg_assert(round_up_to_next_power_of_2(0) === 1);
    dbg_assert(round_up_to_next_power_of_2(1) === 1);
    dbg_assert(round_up_to_next_power_of_2(2) === 2);
    dbg_assert(round_up_to_next_power_of_2(7) === 8);
    dbg_assert(round_up_to_next_power_of_2(8) === 8);
    dbg_assert(round_up_to_next_power_of_2(123456789) === 134217728);
}

/**
 * @constructor
 *
 * Queue wrapper around Uint8Array
 * Used by devices such as the PS2 controller
 */
export function ByteQueue(size)
{
    var data = new Uint8Array(size),
        start,
        end;

    dbg_assert((size & size - 1) === 0);

    this.length = 0;

    this.push = function(item)
    {
        if(this.length === size)
        {
            // intentional overwrite
        }
        else
        {
            this.length++;
        }

        data[end] = item;
        end = end + 1 & size - 1;
    };

    this.shift = function()
    {
        if(!this.length)
        {
            return -1;
        }
        else
        {
            var item = data[start];

            start = start + 1 & size - 1;
            this.length--;

            return item;
        }
    };

    this.peek = function()
    {
        if(!this.length)
        {
            return -1;
        }
        else
        {
            return data[start];
        }
    };

    this.clear = function()
    {
        start = 0;
        end = 0;
        this.length = 0;
    };

    this.clear();
}


/**
 * @constructor
 *
 * Queue wrapper around Float32Array
 * Used by devices such as the sound blaster sound card
 */
export function FloatQueue(size)
{
    this.size = size;
    this.data = new Float32Array(size);
    this.start = 0;
    this.end = 0;
    this.length = 0;

    dbg_assert((size & size - 1) === 0);
}

FloatQueue.prototype.push = function(item)
{
    if(this.length === this.size)
    {
        // intentional overwrite
        this.start = this.start + 1 & this.size - 1;
    }
    else
    {
        this.length++;
    }

    this.data[this.end] = item;
    this.end = this.end + 1 & this.size - 1;
};

FloatQueue.prototype.shift = function()
{
    if(!this.length)
    {
        return undefined;
    }
    else
    {
        var item = this.data[this.start];

        this.start = this.start + 1 & this.size - 1;
        this.length--;

        return item;
    }
};

FloatQueue.prototype.shift_block = function(count)
{
    var slice = new Float32Array(count);

    if(count > this.length)
    {
        count = this.length;
    }
    var slice_end = this.start + count;

    var partial = this.data.subarray(this.start, slice_end);

    slice.set(partial);
    if(slice_end >= this.size)
    {
        slice_end -= this.size;
        slice.set(this.data.subarray(0, slice_end), partial.length);
    }
    this.start = slice_end;

    this.length -= count;

    return slice;
};

FloatQueue.prototype.peek = function()
{
    if(!this.length)
    {
        return undefined;
    }
    else
    {
        return this.data[this.start];
    }
};

FloatQueue.prototype.clear = function()
{
    this.start = 0;
    this.end = 0;
    this.length = 0;
};


/**
 * Simple circular queue for logs
 *
 * @param {number} size
 * @constructor
 */
function CircularQueue(size)
{
    this.data = [];
    this.index = 0;
    this.size = size;
}

CircularQueue.prototype.add = function(item)
{
    this.data[this.index] = item;
    this.index = (this.index + 1) % this.size;
};

CircularQueue.prototype.toArray = function()
{
    return [].slice.call(this.data, this.index).concat([].slice.call(this.data, 0, this.index));
};

CircularQueue.prototype.clear = function()
{
    this.data = [];
    this.index = 0;
};

/**
 * @param {Array} new_data
 */
CircularQueue.prototype.set = function(new_data)
{
    this.data = new_data;
    this.index = 0;
};

export function dump_file(ab, name)
{
    if(!Array.isArray(ab))
    {
        ab = [ab];
    }

    var blob = new Blob(ab);
    download(blob, name);
}

export function download(file_or_blob, name)
{
    var a = document.createElement("a");
    a["download"] = name;
    a.href = window.URL.createObjectURL(file_or_blob);
    a.dataset["downloadurl"] = ["application/octet-stream", a["download"], a.href].join(":");

    if(document.createEvent)
    {
        var ev = document.createEvent("MouseEvent");
        ev.initMouseEvent("click", true, true, window,
                          0, 0, 0, 0, 0, false, false, false, false, 0, null);
        a.dispatchEvent(ev);
    }
    else
    {
        a.click();
    }

    window.URL.revokeObjectURL(a.href);
}

/**
 * A simple 1d bitmap
 * @constructor
 */
export var Bitmap = function(length_or_buffer)
{
    if(typeof length_or_buffer === "number")
    {
        this.view = new Uint8Array(length_or_buffer + 7 >> 3);
    }
    else if(length_or_buffer instanceof ArrayBuffer)
    {
        this.view = new Uint8Array(length_or_buffer);
    }
    else
    {
        dbg_assert(false, "Bitmap: Invalid argument");
    }
};

Bitmap.prototype.set = function(index, value)
{
    const bit_index = index & 7;
    const byte_index = index >> 3;
    const bit_mask = 1 << bit_index;

    this.view[byte_index] =
        value ? this.view[byte_index] | bit_mask : this.view[byte_index] & ~bit_mask;
};

Bitmap.prototype.get = function(index)
{
    const bit_index = index & 7;
    const byte_index = index >> 3;

    return this.view[byte_index] >> bit_index & 1;
};

Bitmap.prototype.get_buffer = function()
{
    return this.view.buffer;
};

export var load_file;
export var get_file_size;

/**
 * A response header, or null when the response has none or does not expose
 * it to this page (a cross-origin response's ETag without
 * Access-Control-Expose-Headers): getResponseHeader logs "Refused to get
 * unsafe header" for each such read, getAllResponseHeaders lists only the
 * headers the page may read
 * @param {?} http an XMLHttpRequest (or an object with getResponseHeader)
 * @param {string} name
 * @return {?string}
 */
export function response_header(http, name)
{
    if(typeof http.getAllResponseHeaders !== "function") return http.getResponseHeader(name);
    const wanted = name.toLowerCase();
    for(const line of String(http.getAllResponseHeaders() || "").split("\r\n"))
    {
        const colon = line.indexOf(":");
        if(colon > 0 && line.slice(0, colon).trim().toLowerCase() === wanted) return line.slice(colon + 1).trim();
    }
    return null;
}

if(typeof XMLHttpRequest === "undefined" ||
    typeof process !== "undefined" && process.versions && process.versions.node)
{
    let fs;

    const get_fs = async function()
    {
        // Electron renderers with nodeIntegration have process.versions.node but
        // a browser module loader, so dynamic import of node: URLs fails. require() works.
        if(typeof require !== "undefined")
        {
            return require("fs")["promises"];
        }
        // string concat to work around closure compiler 'Invalid module path "node:fs/promises" for resolution mode'
        return import("node:" + "fs/promises");
    };

    /**
     * @param {string} filename
     * @param {Object} options
     * @param {number=} n_tries
     */
    load_file = async function(filename, options, n_tries)
    {
        if(!fs)
        {
            fs = await get_fs();
        }

        if(options.range)
        {
            dbg_assert(!options.as_json);

            const length = options.range.length;
            const buffer = Buffer.allocUnsafe(length);
            let bytes_read;

            try
            {
                const fd = await fs["open"](filename, "r");
                try
                {
                    /** @type {{ bytesRead: Number }} */
                    const result = await fd["read"]({
                        buffer,
                        position: options.range.start
                    });
                    bytes_read = result.bytesRead;
                }
                finally
                {
                    await fd["close"]();
                }
            }
            catch(e)
            {
                // (options.error: the caller handles a failed read, src/buffer.js)
                if(!options.error) throw e;
                options.error(e.message);
                return;
            }

            // (past the end of the file: zeroes)
            if(bytes_read < length) buffer.fill(0, bytes_read);
            options.done && options.done(new Uint8Array(buffer));
        }
        else
        {
            const o = {
                encoding: options.as_json ? "utf-8" : null,
            };

            let data;
            try
            {
                data = await fs["readFile"](filename, o);
            }
            catch(e)
            {
                // (options.error: the caller handles a missing file)
                if(!options.error) throw e;
                options.error(e);
                return;
            }
            const result = options.as_json ? JSON.parse(data) : new Uint8Array(data).buffer;

            options.done(result);
        }
    };

    get_file_size = async function(path)
    {
        if(!fs)
        {
            fs = await get_fs();
        }
        const stat = await fs["stat"](path);
        return stat.size;
    };
}
else
{
    /**
     * @param {string} filename
     * @param {Object} options
     * @param {number=} n_tries
     */
    load_file = async function(filename, options, n_tries)
    {
        var http = new XMLHttpRequest();

        const abort = () => http.abort();

        if(options.signal)
        {
            if(options.signal.aborted) return;
            options.signal.addEventListener("abort", abort, { once: true });
        }

        http.open(options.method || "get", filename, true);

        if(options.as_json)
        {
            http.responseType = "json";
        }
        else
        {
            http.responseType = "arraybuffer";
        }

        if(options.headers)
        {
            var header_names = Object.keys(options.headers);

            for(var i = 0; i < header_names.length; i++)
            {
                var name = header_names[i];
                http.setRequestHeader(name, options.headers[name]);
            }
        }

        if(options.range)
        {
            const start = options.range.start;
            const end = start + options.range.length - 1;
            http.setRequestHeader("Range", "bytes=" + start + "-" + end);
            http.setRequestHeader("X-Accept-Encoding", "identity");

            // Abort if server responds with complete file in response to range
            // request, to prevent downloading large files from broken http servers
            http.onreadystatechange = function()
            {
                if(http.status === 200)
                {
                    console.error("Server sent full file in response to ranged request, aborting", { filename });
                    http.onreadystatechange = null;
                    http.abort();
                    if(options.signal) options.signal.removeEventListener("abort", abort);
                    // (a disk read fails: src/buffer.js)
                    options.error && options.error("the server ignored the Range header (status 200)");
                }
            };
        }

        http.onload = function(e)
        {
            if(options.signal) options.signal.removeEventListener("abort", abort);

            if(http.readyState === 4)
            {
                if(http.status !== 200 && http.status !== 206)
                {
                    console.error("Loading the image " + filename + " failed (status %d)", http.status);
                    if(http.status >= 500 && http.status < 600)
                    {
                        retry();
                    }
                    else if(options.error)
                    {
                        options.error(http.status);
                    }
                }
                else if(http.response)
                {
                    if(options.range)
                    {
                        const enc = http.getResponseHeader("Content-Encoding");
                        if(enc && enc !== "identity")
                        {
                            console.error("Server sent Content-Encoding in response to ranged request", {filename, enc});
                        }
                    }
                    options.done && options.done(http.response, http);
                }
            }
        };

        http.onerror = function(e)
        {
            if(options.signal) options.signal.removeEventListener("abort", abort);

            console.error("Loading the image " + filename + " failed", e);
            retry();
        };

        if(options.progress)
        {
            http.onprogress = function(e)
            {
                options.progress(e);
            };
        }

        http.send(null);

        function retry()
        {
            const number_of_tries = n_tries || 0;
            const timeout = [1, 1, 2, 3, 5, 8, 13, 21][number_of_tries] || 34;
            setTimeout(() => {
                load_file(filename, options, number_of_tries + 1);
            }, 1000 * timeout);
        }
    };

    get_file_size = async function(url)
    {
        return new Promise((resolve, reject) => {
            load_file(url, {
                done: (buffer, http) =>
                {
                    var header = http.getResponseHeader("Content-Range") || "";
                    var match = header.match(/\/(\d+)\s*$/);

                    if(match)
                    {
                        resolve(+match[1]);
                    }
                    else
                    {
                        const error = new Error("`Range: bytes=...` header not supported (Got `" + header + "`)");
                        reject(error);
                    }
                },
                headers: {
                    Range: "bytes=0-0",
                    "X-Accept-Encoding": "identity"
                }
            });
        });
    };
}

// Reads len characters at offset from Memory object mem as a JS string
export function read_sized_string_from_mem(mem, offset, len)
{
    offset >>>= 0;
    len >>>= 0;
    return String.fromCharCode(...new Uint8Array(mem.buffer, offset, len));
}

/**
 * Unicode mappings of supported 8-bit code pages.
 * Each mapping is a string of 256 Unicode symbols used as a lookup table for 8-bit character codes.
 *
 * Supported mappings and their encoding labels:
 * - "cp437": CP437 (MS-DOS Latin US), default
 * - "cp858": CP858 (Western Europe), the lower 128 bytes are identical to CP437
 * - "ascii": ASCII (7-Bit), same as CP437 with lower 32 and upper 128 bytes mapped to "."
 *
 * @type {Object<string, string>}
 */
const CHARMAPS =
{
    cp437: " ☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñÑªº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ",
    cp858: "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýÝ¯´­±‗¾¶§÷¸°¨·¹³²■ "
};

CHARMAPS.cp858 = CHARMAPS.cp437.slice(0, 128) + CHARMAPS.cp858;
CHARMAPS.ascii = CHARMAPS.cp437.split("").map((c, i) => i > 31 && i < 128 ? c : ".").join("");

/**
 * Return charmap for given encoding, default to CP437 if encoding is falsey or not defined in CHARMAPS.
 *
 * @param {string} encoding
 * @return {!string}
 */
export function get_charmap(encoding)
{
    return encoding && CHARMAPS[encoding] ? CHARMAPS[encoding] : CHARMAPS.cp437;
}
                                                                                                                                          source/v64/src/log.js                                                                               0000644 0000000 0000000 00000006034 00000000000 011575  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       if(typeof DEBUG === "undefined")
{
    globalThis.DEBUG = true;
}

import { LOG_NAMES } from "./const.js";
import { pad0, pads } from "./lib.js";
import {
    LOG_ALL, LOG_PS2, LOG_PIT, LOG_9P, LOG_PIC, LOG_DMA, LOG_NET, LOG_FLOPPY, LOG_DISK,
    LOG_SERIAL, LOG_VGA, LOG_SB16, LOG_VIRTIO
} from "./const.js";

/** @const */
export var LOG_TO_FILE = false;

export var LOG_LEVEL = LOG_ALL & ~LOG_PS2 & ~LOG_PIT & ~LOG_VIRTIO & ~LOG_9P & ~LOG_PIC &
                          ~LOG_DMA & ~LOG_SERIAL & ~LOG_NET & ~LOG_FLOPPY & ~LOG_DISK & ~LOG_VGA & ~LOG_SB16;

export function set_log_level(level) {
    LOG_LEVEL = level;
}

export var log_data = [];

function do_the_log(message)
{
    if(LOG_TO_FILE)
    {
        log_data.push(message, "\n");
    }
    else
    {
        console.log(message);
    }
}

/**
 * @type {function((string|number), number=)}
 */
export const dbg_log = (function()
{
    if(!DEBUG)
    {
        return function() {};
    }

    /** @type {Object.<number, string>} */
    const dbg_names = LOG_NAMES.reduce(function(a, x)
    {
        a[x[0]] = x[1];
        return a;
    }, {});

    var log_last_message = "";
    var log_message_repetitions = 0;

    /**
     * @param {number=} level
     */
    function dbg_log_(stuff, level)
    {
        if(!DEBUG) return;

        level = level || 1;

        if(level & LOG_LEVEL)
        {
            var level_name = dbg_names[level] || "",
                message = "[" + pads(level_name, 4) + "] " + stuff;

            if(message === log_last_message)
            {
                log_message_repetitions++;

                if(log_message_repetitions < 2048)
                {
                    return;
                }
            }

            var now = new Date();
            var time_str = pad0(now.getHours(), 2) + ":" +
                           pad0(now.getMinutes(), 2) + ":" +
                           pad0(now.getSeconds(), 2) + "+" +
                           pad0(now.getMilliseconds(), 3) + " ";

            if(log_message_repetitions)
            {
                if(log_message_repetitions === 1)
                {
                    do_the_log(time_str + log_last_message);
                }
                else
                {
                    do_the_log("Previous message repeated " + log_message_repetitions + " times");
                }

                log_message_repetitions = 0;
            }

            do_the_log(time_str + message);
            log_last_message = message;
        }
    }

    return dbg_log_;
})();

/**
 * @param {number=} level
 */
export function dbg_trace(level)
{
    if(!DEBUG) return;

    dbg_log(Error().stack, level);
}

/**
 * console.assert is fucking slow
 * @param {string=} msg
 * @param {number=} level
 */
export function dbg_assert(cond, msg, level)
{
    if(!DEBUG) return;

    if(!cond)
    {
        dbg_assert_failed(msg);
    }
}


export function dbg_assert_failed(msg)
{
    debugger;
    console.trace();

    if(msg)
    {
        throw "Assert failed: " + msg;
    }
    else
    {
        throw "Assert failed";
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/src/mac_address.js                                                                       0000644 0000000 0000000 00000016517 00000000000 013270  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // MAC addresses of the network cards (src/virtio_net.js and the card
// plugins, src/net_adapters/: the NE2000, the e1000): their notation, a new card's random
// address, and the translation between the address a restored guest has and
// the card's own.

import { LOG_NET } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

/**
 * A new card's address: 00:22:15 and three random bytes
 * @return {!Uint8Array}
 */
export function random_mac()
{
    return new Uint8Array([
        0x00, 0x22, 0x15,
        Math.random() * 255 | 0,
        Math.random() * 255 | 0,
        Math.random() * 255 | 0,
    ]);
}

// Search and replace MAC addresses in ethernet, arp and dhcp packets.
// Used after restoring an OS from memory dump, so that multiple instances of
// that OS can run at the same time with different external MAC addresses.
// Crude but seems to work.
export function translate_mac_address(packet, search_mac, replacement_mac)
{
    if(packet[0] === search_mac[0] &&
       packet[1] === search_mac[1] &&
       packet[2] === search_mac[2] &&
       packet[3] === search_mac[3] &&
       packet[4] === search_mac[4] &&
       packet[5] === search_mac[5])
    {
        dbg_log("Replace mac in eth destination field", LOG_NET);

        packet[0] = replacement_mac[0];
        packet[1] = replacement_mac[1];
        packet[2] = replacement_mac[2];
        packet[3] = replacement_mac[3];
        packet[4] = replacement_mac[4];
        packet[5] = replacement_mac[5];
    }

    if(packet[6 + 0] === search_mac[0] &&
       packet[6 + 1] === search_mac[1] &&
       packet[6 + 2] === search_mac[2] &&
       packet[6 + 3] === search_mac[3] &&
       packet[6 + 4] === search_mac[4] &&
       packet[6 + 5] === search_mac[5])
    {
        dbg_log("Replace mac in eth source field", LOG_NET);

        packet[6 + 0] = replacement_mac[0];
        packet[6 + 1] = replacement_mac[1];
        packet[6 + 2] = replacement_mac[2];
        packet[6 + 3] = replacement_mac[3];
        packet[6 + 4] = replacement_mac[4];
        packet[6 + 5] = replacement_mac[5];
    }

    const ethertype = packet[12] << 8 | packet[13];

    if(ethertype === 0x0800)
    {
        // ipv4
        const ipv4_packet = packet.subarray(14);
        const ipv4_version = ipv4_packet[0] >> 4;

        if(ipv4_version !== 4)
        {
            dbg_log("Expected ipv4.version==4 but got: " + ipv4_version, LOG_NET);
            return;
        }

        const ipv4_ihl = ipv4_packet[0] & 0xF;
        dbg_assert(ipv4_ihl === 5, "TODO: ihl!=5");

        const ipv4_proto = ipv4_packet[9];
        if(ipv4_proto === 0x11)
        {
            // udp
            const udp_packet = ipv4_packet.subarray(5 * 4);
            const source_port = udp_packet[0] << 8 | udp_packet[1];
            const destination_port = udp_packet[2] << 8 | udp_packet[3];
            const checksum = udp_packet[6] << 8 | udp_packet[7];

            dbg_log("udp srcport=" + source_port + " dstport=" + destination_port + " checksum=" + h(checksum, 4), LOG_NET);

            if(source_port === 67 || destination_port === 67)
            {
                // dhcp
                const dhcp_packet = udp_packet.subarray(8);
                const dhcp_magic = dhcp_packet[0xEC] << 24 | dhcp_packet[0xED] << 16 | dhcp_packet[0xEE] << 8 | dhcp_packet[0xEF];

                if(dhcp_magic !== 0x63825363)
                {
                    dbg_log("dhcp packet didn't match magic: " + h(dhcp_magic, 8));
                    return;
                }

                if(dhcp_packet[28 + 0] === search_mac[0] &&
                   dhcp_packet[28 + 1] === search_mac[1] &&
                   dhcp_packet[28 + 2] === search_mac[2] &&
                   dhcp_packet[28 + 3] === search_mac[3] &&
                   dhcp_packet[28 + 4] === search_mac[4] &&
                   dhcp_packet[28 + 5] === search_mac[5])
                {
                    dbg_log("Replace mac in dhcp.chaddr", LOG_NET);

                    dhcp_packet[28 + 0] = replacement_mac[0];
                    dhcp_packet[28 + 1] = replacement_mac[1];
                    dhcp_packet[28 + 2] = replacement_mac[2];
                    dhcp_packet[28 + 3] = replacement_mac[3];
                    dhcp_packet[28 + 4] = replacement_mac[4];
                    dhcp_packet[28 + 5] = replacement_mac[5];

                    udp_packet[6] = udp_packet[7] = 0; // zero udp checksum
                }

                let offset = 0xF0;
                while(offset < dhcp_packet.length)
                {
                    const dhcp_option_type = dhcp_packet[offset++];

                    if(dhcp_option_type === 0xFF)
                    {
                        break;
                    }

                    const length = dhcp_packet[offset++];

                    if(dhcp_option_type === 0x3D && // client identifier
                       dhcp_packet[offset + 0] === 0x01 && // ethernet
                       dhcp_packet[offset + 1] === search_mac[0] &&
                       dhcp_packet[offset + 2] === search_mac[1] &&
                       dhcp_packet[offset + 3] === search_mac[2] &&
                       dhcp_packet[offset + 4] === search_mac[3] &&
                       dhcp_packet[offset + 5] === search_mac[4] &&
                       dhcp_packet[offset + 6] === search_mac[5])
                    {
                        dbg_log("Replace mac in dhcp.clientidentifier", LOG_NET);

                        dhcp_packet[offset + 1] = replacement_mac[0];
                        dhcp_packet[offset + 2] = replacement_mac[1];
                        dhcp_packet[offset + 3] = replacement_mac[2];
                        dhcp_packet[offset + 4] = replacement_mac[3];
                        dhcp_packet[offset + 5] = replacement_mac[4];
                        dhcp_packet[offset + 6] = replacement_mac[5];

                        udp_packet[6] = udp_packet[7] = 0; // zero udp checksum
                    }

                    offset += length;
                }
            }
        }
        else
        {
            // tcp, ...
        }
    }
    else if(ethertype === 0x0806)
    {
        // arp
        const arp_packet = packet.subarray(14);
        dbg_log("arp oper=" + arp_packet[7] + " " + format_mac(arp_packet.subarray(8, 8+6)) + " " + format_mac(arp_packet.subarray(18, 18+6)), LOG_NET);

        if(arp_packet[8 + 0] === search_mac[0] &&
           arp_packet[8 + 1] === search_mac[1] &&
           arp_packet[8 + 2] === search_mac[2] &&
           arp_packet[8 + 3] === search_mac[3] &&
           arp_packet[8 + 4] === search_mac[4] &&
           arp_packet[8 + 5] === search_mac[5])
        {
            dbg_log("Replace mac in arp.sha", LOG_NET);

            arp_packet[8 + 0] = replacement_mac[0];
            arp_packet[8 + 1] = replacement_mac[1];
            arp_packet[8 + 2] = replacement_mac[2];
            arp_packet[8 + 3] = replacement_mac[3];
            arp_packet[8 + 4] = replacement_mac[4];
            arp_packet[8 + 5] = replacement_mac[5];
        }
    }
    else
    {
        // TODO: ipv6, ...
    }
}

export function format_mac(mac)
{
    return [
        mac[0].toString(16).padStart(2, "0"),
        mac[1].toString(16).padStart(2, "0"),
        mac[2].toString(16).padStart(2, "0"),
        mac[3].toString(16).padStart(2, "0"),
        mac[4].toString(16).padStart(2, "0"),
        mac[5].toString(16).padStart(2, "0"),
    ].join(":");
}
                                                                                                                                                                                 source/v64/src/machine_clock.js                                                                     0000644 0000000 0000000 00000017104 00000000000 013573  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // One time domain for the entire machine, in milliseconds. Guest clocks must
// never infer elapsed time from the number of reads or the number of vCPUs.

/**
 * @constructor
 * @param {Object=} options
 */
export function MachineClock(options)
{
    options = options || {};
    this.mode = options["mode"] || "normal";
    this.instructions_per_ms = options["instructions_per_ms"] === undefined ? 100000 : options["instructions_per_ms"];
    this.max_host_delta_ms = options["max_host_delta_ms"] === undefined ? 1000 : options["max_host_delta_ms"];
    // (normal time: guest milliseconds per host millisecond, at most 1; below
    // 1 the guest's timeouts get more host time, for a CPU much slower than
    // the guest's software expects, as Bochs's ips; the wall clock lags)
    this.rate = options["rate"] === undefined ? 1 : options["rate"];
    this.host_now = options["now"] || (() => performance.now());
    this.wall_epoch_ms = options["wall_epoch_ms"] === undefined ?
        (this.mode === "deterministic" ? 946684800000 : Date.now()) : options["wall_epoch_ms"];

    if(this.mode !== "normal" && this.mode !== "deterministic" ||
        !Number.isFinite(this.instructions_per_ms) || this.instructions_per_ms <= 0 ||
        !Number.isFinite(this.max_host_delta_ms) || this.max_host_delta_ms <= 0 ||
        !Number.isFinite(this.rate) || this.rate <= 0 || this.rate > 1 ||
        !Number.isFinite(this.wall_epoch_ms) || typeof this.host_now !== "function")
    {
        throw new Error("Invalid machine clock configuration");
    }

    this.time_ms = 0;
    this.instruction_count = 0;
    this.idle_ms = 0;
    this.paused = false;
    this.host_last = this.host_now();
    if(!Number.isFinite(this.host_last))
    {
        throw new Error("Invalid host monotonic clock reading");
    }
    this.host_pause_count = 0;
    this.discarded_host_ms = 0;
    this.host_backwards_count = 0;
    /** @type {?function():number} */
    this.instruction_source = null;
}

/**
 * Reading deterministic time consumes only already committed progress. Normal
 * time samples the host clock without artificially incrementing equal readings.
 * Long host gaps are bounded; discarded time is not repaid on later reads.
 * @return {number}
 */
MachineClock.prototype.now = function()
{
    if(!this.paused && this.mode === "deterministic" && this.instruction_source)
    {
        // A PIO read may occur inside a Wasm slice. Consume prior architectural
        // progress then, without giving the read itself any artificial ticks.
        this.commit_instructions(this.instruction_source());
    }
    if(!this.paused && this.mode === "normal")
    {
        const host = this.host_now();
        if(!Number.isFinite(host))
        {
            throw new Error("Invalid host monotonic clock reading");
        }
        const delta = host - this.host_last;
        if(delta < 0)
        {
            this.host_backwards_count++;
        }
        else
        {
            this.host_last = host;
            if(delta > this.max_host_delta_ms)
            {
                this.host_pause_count++;
                this.discarded_host_ms += delta - this.max_host_delta_ms;
            }
            this.time_ms += Math.min(delta, this.max_host_delta_ms) * this.rate;
        }
    }
    return this.time_ms;
};

/** The RTC epoch is independent of the destination host's calendar. */
MachineClock.prototype.wall_time = function()
{
    return this.wall_epoch_ms + this.now();
};

/** Called once for committed progress, never once per time read or vCPU. */
MachineClock.prototype.advance_instructions = function(count)
{
    this.commit_instructions(count);
    return this.now();
};

/** @param {number} count */
MachineClock.prototype.commit_instructions = function(count)
{
    if(!Number.isSafeInteger(count) || count < 0 ||
        !Number.isSafeInteger(this.instruction_count + count))
    {
        throw new Error("Invalid committed instruction count");
    }
    if(this.mode === "deterministic" && !this.paused)
    {
        this.instruction_count += count;
        // Use the total to avoid floating-point drift depending on slice size.
        this.time_ms = this.instruction_count / this.instructions_per_ms + this.idle_ms;
    }
};

/**
 * The callback consumes a delta of committed instructions/REP elements.
 * @param {?function():number} source
 */
MachineClock.prototype.set_instruction_source = function(source)
{
    if(source !== null && typeof source !== "function")
    {
        throw new Error("Invalid committed instruction source");
    }
    this.now();
    this.instruction_source = source;
};

/** Only the scheduler may jump a fully halted machine to its next event. */
MachineClock.prototype.advance_to = function(deadline_ms)
{
    this.now();
    if(!Number.isFinite(deadline_ms) || deadline_ms < 0)
    {
        throw new Error("Invalid machine clock deadline");
    }
    if(this.mode === "deterministic" && !this.paused && deadline_ms > this.time_ms)
    {
        this.idle_ms += deadline_ms - this.time_ms;
        this.time_ms = deadline_ms;
    }
    return this.now();
};

/**
 * The host milliseconds until `ms` of the machine's time have passed (the
 * run loop's waits)
 * @param {number} ms
 * @return {number}
 */
MachineClock.prototype.to_host_ms = function(ms)
{
    return this.mode === "normal" ? ms / this.rate : ms;
};

MachineClock.prototype.pause = function()
{
    this.now();
    this.paused = true;
};

MachineClock.prototype.resume = function()
{
    if(this.paused)
    {
        this.host_last = this.host_now();
        this.paused = false;
    }
};

/**
 * Go on from `time_ms` (a vCPU worker's clock when it leaves a stop: the
 * machine's time, which a restore may have set anywhere)
 * @param {number} time_ms
 */
MachineClock.prototype.set_time = function(time_ms)
{
    this.time_ms = time_ms;
    this.host_last = this.host_now();
};

MachineClock.prototype.get_diagnostics = function()
{
    return {
        "host_pause_count": this.host_pause_count,
        "discarded_host_ms": this.discarded_host_ms,
        "host_backwards_count": this.host_backwards_count,
        "committed_instructions": this.instruction_count,
        "idle_ms": this.idle_ms,
    };
};

MachineClock.prototype.get_state = function()
{
    return [1, this.mode, this.now(), this.wall_epoch_ms, this.instructions_per_ms,
        this.max_host_delta_ms, this.instruction_count, this.idle_ms,
        this.host_pause_count, this.discarded_host_ms, this.host_backwards_count];
};

MachineClock.prototype.set_state = function(state)
{
    if(state[0] !== 1 || state[1] !== "normal" && state[1] !== "deterministic" ||
        !Number.isFinite(state[2]) || state[2] < 0 || !Number.isFinite(state[3]) ||
        !Number.isFinite(state[4]) || state[4] <= 0 || !Number.isFinite(state[5]) || state[5] <= 0 ||
        !Number.isSafeInteger(state[6]) || state[6] < 0 || !Number.isFinite(state[7]) || state[7] < 0 ||
        !Number.isSafeInteger(state[8]) || state[8] < 0 || !Number.isFinite(state[9]) || state[9] < 0 ||
        !Number.isSafeInteger(state[10]) || state[10] < 0)
    {
        throw new Error("Invalid machine clock snapshot");
    }
    this.mode = state[1];
    this.time_ms = state[2];
    this.wall_epoch_ms = state[3];
    this.instructions_per_ms = state[4];
    this.max_host_delta_ms = state[5];
    this.instruction_count = state[6];
    this.idle_ms = state[7];
    this.host_pause_count = state[8];
    this.discarded_host_ms = state[9];
    this.host_backwards_count = state[10];
    this.host_last = this.host_now();
    // Pause/run belongs to the destination emulator's lifecycle. Restoring a
    // running snapshot into a stopped emulator must not start its clocks.
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/machine_options.js                                                                   0000644 0000000 0000000 00000057142 00000000000 014201  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The guest CPU and machine of new V86() and the options each combination
// allows (docs/arm64-virt-android16-plan.md, the configuration contract and
// P1.1): the V86 constructor checks the options, CPU.init checks its
// settings again. The PC machines (i440fx, q35) run the x86 CPUs, the virt
// machine runs the arm64 CPU; an option of the other family is an error,
// never silently ignored.

/** The guest CPUs (`cpu_type`); the first is the default */
export const CPU_TYPES = ["x86", "x86_64", "arm64", "arm32"];
/** The ARM family's CPU types: the ARM core (v86-arm64.wasm) on the virt machine; arm32 is AArch32 throughout (docs/aarch32-plan.md part 2) */
export const ARM_CPU_TYPES = ["arm64", "arm32"];
/**
 * @param {string|undefined} cpu_type
 * @return {boolean} whether the ARM core runs it
 */
export function is_arm(cpu_type) { return ARM_CPU_TYPES.includes(/** @type {string} */ (cpu_type)); }

/**
 * The CPU models (`cpu_profile`, docs/iphone4-plan.md "CPU 型号：统一的
 * cpu_profile"): which CPU the guest sees. Each runs on one cpu_type, so a
 * cpu_profile alone picks it. The generic- ones are v86's own (all it
 * implements), each cpu_type's default; a real chip goes by its model's
 * name, for software that checks which CPU it runs on. hidden: for the
 * regression tests against the QEMU references only (the VM manager leaves
 * them out). The instruction set levels stay with cpu_features.
 * @type {!Object<string, {cpu_type: string, hidden: (boolean|undefined)}>}
 */
export const CPU_PROFILES = {
    "generic-x86": { cpu_type: "x86" },
    "generic-x86-64": { cpu_type: "x86_64" },
    // (src/virt/platform.js: v86-aarch64-v2, with FEAT_PAN; -compat32 is v3, AArch32 at EL0 too)
    "generic-arm64": { cpu_type: "arm64" },
    "generic-arm64-compat32": { cpu_type: "arm64" },
    "generic-arm64-v1": { cpu_type: "arm64", hidden: true },
    "generic-arm64-v1.1": { cpu_type: "arm64", hidden: true },
    "cortex-a15": { cpu_type: "arm32" },
};

/** Each cpu_type's CPU model when cpu_profile is not given */
export const DEFAULT_CPU_PROFILES = { "x86": "generic-x86", "x86_64": "generic-x86-64", "arm64": "generic-arm64", "arm32": "cortex-a15" };

/** The CPU models a machine takes, where it is choosy: machine_type → cpu_type → models */
export const MACHINE_CPU_PROFILES = { "ranchu": { "arm32": ["cortex-a15"] } };

/**
 * The CPU models a page may offer for a CPU type and machine (the hidden ones left out)
 * @param {string} cpu_type
 * @param {string=} machine_type
 * @return {!Array<string>}
 */
export function cpu_profiles_of(cpu_type, machine_type)
{
    const only = machine_type && MACHINE_CPU_PROFILES[machine_type] && MACHINE_CPU_PROFILES[machine_type][cpu_type];
    return Object.keys(CPU_PROFILES).filter(name => CPU_PROFILES[name].cpu_type === cpu_type && !CPU_PROFILES[name].hidden &&
        (!only || only.includes(name)));
}

/**
 * The machines (`machine_type`): "i440fx" (the default with an x86 CPU:
 * i440FX host bridge, PIIX3/4, IDE), "q35" (Q35 MCH, ICH9 LPC with its power
 * management, AHCI; docs/q35.md), "virt" (the ARM board, docs/virt.md) and
 * "ranchu" (the Android emulator's ARM board: its SDK images, src/virt/ranchu.js)
 */
export const MACHINE_TYPES = ["i440fx", "q35", "virt", "ranchu"];
/** The ARM CPUs' machines */
export const ARM_MACHINE_TYPES = ["virt", "ranchu"];

/**
 * The most cores (`cpu_cores`) of the PC machines (src/platform.js): must
 * match MAX_CORES in src/rust/cpu/apic.rs. The virt machine has as many
 * (VIRT_MAX_CORES in src/virt/platform.js; tests/app/machine_rules.mjs checks)
 */
export const MAX_CORES = 8;

/** Q35's PCI Express root ports (`pcie_root_ports`): ICH9 has six, device 28 (src/platform.js) */
export const Q35_ROOT_PORTS_MAX = 6;

/**
 * The largest vram_size: the VGA core backs at most this much
 * (VGA_MAX_MEMORY_SIZE in graphics_adapters/vga_core.js), and a device whose
 * BAR were larger would reach past it (src/graphics_adapter.js)
 */
export const MAX_VRAM_SIZE = 256 << 20;

/** Every value graphics_adapter may name (src/graphics_adapter.js) */
export const GRAPHICS_ADAPTERS = ["bochs_vga", "vmware_svga", "virtio_gpu", "none"];

/** The network cards (net_device.type) of the PC machines */
export const NET_DEVICE_TYPES = ["ne2k", "e1000", "virtio", "none"];

/** The network cards that are plugins (src/device_plugin.js): build/v86-<type>.js; all but virtio-net */
export const NET_DEVICE_PLUGINS = ["ne2k", "e1000"];

/** The sound cards (audio_device) of the PC machines: one or none (the PC speaker is not a sound card) */
export const AUDIO_DEVICES = ["sb16", "hd_audio", "none"];

/** The sound cards that are plugins: build/v86-<name>.js (underscores as dashes); all of them */
export const AUDIO_DEVICE_PLUGINS = ["sb16", "hd_audio"];

/** The USB host controllers (usb.controller) of the PC machines: UHCI, EHCI with its UHCI companions, xHCI */
export const USB_CONTROLLERS = ["uhci", "ehci", "xhci"];

/** Their ports: the tablet and USB disks each take one (there is no hub; xHCI's are each a USB 3 and a USB 2 root port) */
export const USB_PORTS = { "uhci": 2, "ehci": 6, "xhci": 4 };

/** The firmware of the PC machines (firmware.type): SeaBIOS (bios, vga_bios), the default, or UEFI (OVMF, docs/uefi.md) */
export const FIRMWARE_TYPES = ["seabios", "uefi"];

/** Options of the PC machines that the virt machine rejects */
export const PC_ONLY = ["bzimage", "bzimage_initrd_from_filesystem", "multiboot", "bios", "vga_bios", "fda", "fdb", "cdrom",
    "hpet", "smbus", "pcie_root_ports", "qemu_compatible", "uart1", "uart2", "uart3", "parallel1", "modem",
    "cpuid_level", "x87_fast_math", "x87_jit_cache", "high_memory_size", "cpu_features", "audio_device", "audio_device_path", "usb", "firmware", "tpm"];

/** Options of the virt machine that the PC machines reject */
export const VIRT_ONLY = ["kernel", "dtb", "virtio_disks", "virtio_rng", "virtio_transport", "virtio_input", "virtio_vsock",
    "virtio_console_ports", "virtio_gpu_pci_slot"];

/** The display adapters of the virt machine (no VGA) */
export const VIRT_GRAPHICS_ADAPTERS = ["none", "virtio_gpu"];

/** The network cards of the virt machine (virtio-net) */
export const VIRT_NET_DEVICE_TYPES = ["virtio", "none"];

/** Options that only the Q35 machine has */
export const Q35_ONLY = ["hpet", "smbus", "pcie_root_ports"];

const given = value => value !== undefined && value !== null && value !== false;

/**
 * Check the guest CPU, the machine and the options that belong to them
 * @param {!Object} options the options of new V86(), or CPU.init's settings
 * @return {{cpu_type: string, machine_type: string, cpu_profile: string}}
 */
export function check_machine_options(options)
{
    if(options["experimental_x64"] !== undefined)
    {
        throw new Error("experimental_x64 was replaced by cpu_type: \"x86_64\"");
    }
    if(options["a64_profile"] !== undefined)
    {
        throw new Error("a64_profile was replaced by cpu_profile: \"generic-arm64\" (a64_profile \"v2\"), " +
            "\"generic-arm64-compat32\" (\"v3\"), \"generic-arm64-v1.1\", \"generic-arm64-v1\"");
    }
    const cpu_profile = options["cpu_profile"];
    if(cpu_profile !== undefined && !Object.prototype.hasOwnProperty.call(CPU_PROFILES, cpu_profile))
    {
        throw new Error("Unknown cpu_profile " + JSON.stringify(cpu_profile) + "; supported: " +
            Object.keys(CPU_PROFILES).map(name => "\"" + name + "\"").join(", "));
    }
    // (a CPU model alone picks its CPU type)
    const cpu_type = options["cpu_type"] !== undefined ? options["cpu_type"] :
        cpu_profile !== undefined ? CPU_PROFILES[cpu_profile].cpu_type : CPU_TYPES[0];
    if(!CPU_TYPES.includes(cpu_type))
    {
        throw new Error("Unknown cpu_type " + JSON.stringify(cpu_type) + "; supported: " +
            CPU_TYPES.map(name => "\"" + name + "\"").join(", "));
    }
    if(cpu_profile !== undefined && CPU_PROFILES[cpu_profile].cpu_type !== cpu_type)
    {
        throw new Error("cpu_profile \"" + cpu_profile + "\" is a CPU of cpu_type \"" + CPU_PROFILES[cpu_profile].cpu_type +
            "\", not \"" + cpu_type + "\"; cpu_type \"" + cpu_type + "\" has " + cpu_profiles_of(cpu_type).map(name => "\"" + name + "\"").join(", "));
    }
    const arm = is_arm(cpu_type);
    const machine_type = options["machine_type"] === undefined ? (arm ? "virt" : "i440fx") : options["machine_type"];
    if(!MACHINE_TYPES.includes(machine_type))
    {
        throw new Error("machine_type must be one of " + MACHINE_TYPES.map(m => "\"" + m + "\"").join(", ") +
            ", got " + JSON.stringify(machine_type));
    }
    for(const name of ["ranchu_display", "ranchu_properties", "ranchu_gpu", "ranchu_gles_version"])
    {
        if(options[name] !== undefined && machine_type !== "ranchu") throw new Error(name + " is an option of machine_type \"ranchu\"");
    }
    // (the GPU of the emulator's images: the guest renders, or the GLES host, docs/gles-proxy-plan.md)
    if(options["ranchu_gpu"] !== undefined && !["guest", "host"].includes(options["ranchu_gpu"]))
    {
        throw new Error("ranchu_gpu must be \"guest\" or \"host\", got " + JSON.stringify(options["ranchu_gpu"]));
    }
    // (the highest GLES version the GLES host announces, docs/gles3-plan.md)
    if(options["ranchu_gles_version"] !== undefined && !["2.0", "3.0", "3.1", "3.2"].includes(options["ranchu_gles_version"]))
    {
        throw new Error("ranchu_gles_version must be \"2.0\", \"3.0\", \"3.1\" or \"3.2\", got " + JSON.stringify(options["ranchu_gles_version"]));
    }
    // (the GLES backdoor of arm32's user code, docs/gles-proxy-plan.md "iOS 传输": the iOS machine's, the virt machine's in tests)
    if(options["gles_backdoor"] !== undefined && typeof options["gles_backdoor"] !== "boolean")
    {
        throw new Error("gles_backdoor must be a boolean, got " + JSON.stringify(options["gles_backdoor"]));
    }
    if(options["gles_backdoor"] && (cpu_type !== "arm32" || machine_type !== "virt"))
    {
        throw new Error("gles_backdoor is an option of cpu_type \"arm32\" on machine_type \"virt\"");
    }
    if(arm !== ARM_MACHINE_TYPES.includes(machine_type))
    {
        throw new Error("cpu_type \"" + cpu_type + "\" does not run on machine_type \"" + machine_type + "\": " +
            (arm ? "the ARM CPUs need machine_type \"virt\" (the default with them) or \"ranchu\"" :
                "the " + machine_type + " machine needs cpu_type \"arm64\" or \"arm32\""));
    }
    const profile = cpu_profile === undefined ? DEFAULT_CPU_PROFILES[cpu_type] : cpu_profile;
    const only = MACHINE_CPU_PROFILES[machine_type] && MACHINE_CPU_PROFILES[machine_type][cpu_type];
    if(only && !only.includes(profile))
    {
        throw new Error("machine_type \"" + machine_type + "\" takes cpu_profile " + only.map(name => "\"" + name + "\"").join(", ") +
            " with cpu_type \"" + cpu_type + "\", got " + JSON.stringify(profile));
    }

    if(arm)
    {
        for(const name of PC_ONLY)
        {
            if(given(options[name]))
            {
                throw new Error(name + " is an option of the PC machines (machine_type \"i440fx\", \"q35\"), not of machine_type \"virt\"");
            }
        }
        if(options["acpi"])
        {
            throw new Error("acpi: true is an option of the PC machines; the virt machine describes itself with a device tree");
        }
        const adapter = options["graphics_adapter"];
        if(adapter !== undefined && typeof adapter === "string" && !VIRT_GRAPHICS_ADAPTERS.includes(adapter))
        {
            throw new Error("graphics_adapter " + JSON.stringify(adapter) + " is not on machine_type \"virt\" (no VGA); supported: " +
                VIRT_GRAPHICS_ADAPTERS.map(name => "\"" + name + "\"").join(", "));
        }
        const net = options["net_device"];
        if(net && net["type"] !== undefined && net["type"] !== "virtio" && net["type"] !== "none")
        {
            throw new Error("net_device type " + JSON.stringify(net["type"]) + " is not on machine_type \"virt\"; it has virtio-net");
        }
        if((given(options["hda"]) || given(options["hdb"])) && given(options["virtio_disks"]))
        {
            throw new Error("hda/hdb and virtio_disks both name the virt machine's first disks: give one of them");
        }
        const input = options["virtio_input"];
        if(Array.isArray(input) && input.some(kind => !["keyboard", "tablet", "multitouch"].includes(kind)))
        {
            throw new Error("virtio_input is true or a list of \"keyboard\", \"tablet\" and \"multitouch\", got " + JSON.stringify(input));
        }
        // (ranchu: its own framebuffer, no PCIe)
        if(machine_type === "ranchu" && adapter !== undefined && adapter !== "none" && adapter !== null)
        {
            throw new Error("graphics_adapter " + JSON.stringify(adapter) + " is not on machine_type \"ranchu\", which has the emulator's framebuffer");
        }
        if(machine_type === "ranchu" && options["virtio_transport"] === "pci")
        {
            throw new Error("virtio_transport \"pci\" is not on machine_type \"ranchu\", which has no PCIe host");
        }
        const transport = options["virtio_transport"];
        if(transport !== undefined && transport !== "mmio" && transport !== "pci")
        {
            throw new Error("virtio_transport is \"mmio\" (the default) or \"pci\", got " + JSON.stringify(transport));
        }
    }
    else
    {
        for(const name of VIRT_ONLY)
        {
            if(given(options[name]))
            {
                throw new Error(name + " is an option of machine_type \"virt\" (cpu_type \"arm64\" or \"arm32\")");
            }
        }
        const net = options["net_device"];
        if(net && net["type"] !== undefined && !NET_DEVICE_TYPES.includes(net["type"]))
        {
            throw new Error("Unknown net_device type " + JSON.stringify(net["type"]) + "; supported: " +
                NET_DEVICE_TYPES.map(type => "\"" + type + "\"").join(", "));
        }
        const path = net && net["plugin_path"];
        if(path !== undefined && (typeof path !== "string" || !path))
        {
            throw new Error("net_device.plugin_path must be the path or URL of the plugin file");
        }
        const audio = options["audio_device"];
        if(audio !== undefined && !AUDIO_DEVICES.includes(audio))
        {
            throw new Error("Unknown audio_device " + JSON.stringify(audio) + "; supported: " +
                AUDIO_DEVICES.map(name => "\"" + name + "\"").join(", "));
        }
        const audio_path = options["audio_device_path"];
        if(audio_path !== undefined && (typeof audio_path !== "string" || !audio_path))
        {
            throw new Error("audio_device_path must be the path or URL of the plugin file");
        }
        const usb = options["usb"];
        if(usb !== undefined && usb !== null)
        {
            if(typeof usb !== "object" || !USB_CONTROLLERS.includes(usb["controller"]))
            {
                throw new Error("usb.controller must be one of " + USB_CONTROLLERS.map(name => "\"" + name + "\"").join(", "));
            }
            if(usb["tablet"] !== undefined && typeof usb["tablet"] !== "boolean") throw new Error("usb.tablet must be true or false");
            if(usb["plugin_path"] !== undefined && (typeof usb["plugin_path"] !== "string" || !usb["plugin_path"]))
            {
                throw new Error("usb.plugin_path must be the path or URL of the plugin file");
            }
            // USB disks: { id, image, read_only }, each in a port of its own
            const disks = usb["mass_storage"];
            if(disks !== undefined)
            {
                if(!Array.isArray(disks)) throw new Error("usb.mass_storage must be a list of USB disks ({ id, image, read_only })");
                const ids = new Set(["tablet"]);
                for(const disk of disks)
                {
                    const id = disk && disk["id"];
                    if(typeof id !== "string" || !id) throw new Error("usb.mass_storage: each USB disk needs an id (a string)");
                    if(ids.has(id)) throw new Error("usb.mass_storage: the id " + JSON.stringify(id) + " is taken");
                    ids.add(id);
                    if(!disk["image"] || typeof disk["image"] !== "object") throw new Error("usb.mass_storage: " + JSON.stringify(id) + " needs an image");
                    if(disk["read_only"] !== undefined && typeof disk["read_only"] !== "boolean")
                    {
                        throw new Error("usb.mass_storage: read_only of " + JSON.stringify(id) + " must be true or false");
                    }
                }
                const ports = USB_PORTS[usb["controller"]];
                if(disks.length + (usb["tablet"] ? 1 : 0) > ports)
                {
                    throw new Error("usb: the " + usb["controller"].toUpperCase() + " controller has " + ports + " ports, for " +
                        (usb["tablet"] ? "the tablet and " : "") + disks.length + " USB disk" + (disks.length === 1 ? "" : "s"));
                }
            }
        }
        const tpm = options["tpm"];
        if(tpm !== undefined && tpm !== null)
        {
            if(typeof tpm !== "object" || (tpm["version"] !== undefined && tpm["version"] !== "2.0"))
            {
                throw new Error("tpm.version must be \"2.0\" (the TPM 2.0, docs/tpm.md)");
            }
            if(tpm["interface"] !== undefined && tpm["interface"] !== "crb")
            {
                throw new Error("tpm.interface must be \"crb\" (the Command Response Buffer)");
            }
            if(tpm["state"] !== undefined && (!tpm["state"] || typeof tpm["state"] !== "object"))
            {
                throw new Error("tpm.state must be the image of the TPM's state ({ url } or { buffer }, disk_option \"read_write\" to keep it)");
            }
            for(const name of ["plugin_path", "wasm_path"])
            {
                if(tpm[name] !== undefined && (typeof tpm[name] !== "string" || !tpm[name])) throw new Error("tpm." + name + " must be a path or URL");
            }
        }
        const firmware = options["firmware"];
        if(firmware !== undefined && firmware !== null)
        {
            if(typeof firmware !== "object" || !FIRMWARE_TYPES.includes(firmware["type"]))
            {
                throw new Error("firmware.type must be one of " + FIRMWARE_TYPES.map(name => "\"" + name + "\"").join(", "));
            }
            if(firmware["type"] === "uefi")
            {
                if(!firmware["code"] || typeof firmware["code"] !== "object")
                {
                    throw new Error("firmware: UEFI needs its code image (firmware.code: { url } or { buffer })");
                }
                if(firmware["vars"] !== undefined && (!firmware["vars"] || typeof firmware["vars"] !== "object"))
                {
                    throw new Error("firmware.vars must be the variable store's image ({ url } or { buffer })");
                }
                if(options["bios"] || options["vga_bios"])
                {
                    throw new Error("firmware: UEFI takes the place of bios and vga_bios; give one or the other");
                }
                if(cpu_type !== "x86_64")
                {
                    throw new Error("firmware: the UEFI firmware (OVMF, X64) needs cpu_type \"x86_64\"");
                }
                if(!options["acpi"])
                {
                    throw new Error("firmware: UEFI needs acpi: true (OVMF installs the machine's ACPI tables)");
                }
                if(machine_type === "i440fx" && !options["qemu_compatible"])
                {
                    throw new Error("firmware: UEFI on machine_type \"i440fx\" needs qemu_compatible: true " +
                        "(OVMF expects QEMU's PIIX3/PIIX4 functions at 00:01.0 to 00:01.3)");
                }
                if(firmware["secure_boot"] !== undefined && typeof firmware["secure_boot"] !== "boolean")
                {
                    throw new Error("firmware.secure_boot must be a boolean");
                }
                if(firmware["secure_boot"])
                {
                    // (the Secure Boot build keeps its variables in SMM: Q35's SMRAM)
                    if(machine_type !== "q35")
                    {
                        throw new Error("firmware.secure_boot needs machine_type \"q35\" (the firmware runs its variable services in SMM)");
                    }
                    if(!firmware["vars"])
                    {
                        throw new Error("firmware.secure_boot needs the variable store (firmware.vars)");
                    }
                }
            }
        }
    }
    return { cpu_type, machine_type, cpu_profile: profile };
}

/**
 * What the options of new V86() may be on a CPU and machine, for a page that
 * offers them (docs/vm-manager-plan.md, the settings dialog: it disables what
 * does not apply and says why). The same rules as check_machine_options and
 * the machines' own checks (src/platform.js: hpet, smbus and pcie_root_ports
 * need Q35, Q35 needs ACPI, more than one core needs ACPI).
 * @param {string} cpu_type
 * @param {string} machine_type
 * @return {{machine_types: !Array<string>, graphics_adapters: !Array<string>, net_device_types: !Array<string>,
 *     audio_devices: !Array<string>, usb_controllers: !Array<string>, cpu_profiles: !Array<string>,
 *     max_cores: number, acpi: string, unavailable: !Object<string, string>}} machine_types: the machines
 *     of the CPU; cpu_profiles: the CPU models to offer (cpu_profile); acpi: "required" (Q35),
 *     "with_cores" (needed with more than one core), "none" (virt); unavailable: the options that do
 *     not apply, each with the reason
 */
export function allowed_options(cpu_type, machine_type)
{
    const virt = ARM_MACHINE_TYPES.includes(machine_type);
    /** @type {!Object<string, string>} */
    const unavailable = {};
    if(virt)
    {
        for(const name of PC_ONLY)
        {
            unavailable[name] = name + " is an option of the PC machines (i440FX, Q35), not of the virt machine";
        }
        unavailable["bios"] = unavailable["vga_bios"] = "the virt machine has no PC firmware (it boots its kernel directly)";
        unavailable["fda"] = unavailable["fdb"] = "the virt machine has no floppy controller";
        unavailable["acpi"] = "the virt machine describes itself with a device tree, not ACPI";
        if(machine_type === "ranchu")
        {
            unavailable["virtio_transport"] = "the ranchu machine has no PCIe host: its virtio devices are on virtio-mmio";
        }
    }
    else
    {
        for(const name of VIRT_ONLY)
        {
            unavailable[name] = name + " is an option of the virt machine (cpu_type \"arm64\" or \"arm32\")";
        }
        if(machine_type !== "q35")
        {
            unavailable["hpet"] = "only the Q35 machine has an HPET";
            unavailable["smbus"] = "only the Q35 machine has an SMBus controller";
            unavailable["pcie_root_ports"] = "only the Q35 machine has PCI Express root ports";
        }
    }
    return {
        machine_types: is_arm(cpu_type) ? ARM_MACHINE_TYPES.slice() : MACHINE_TYPES.filter(m => !ARM_MACHINE_TYPES.includes(m)),
        graphics_adapters: machine_type === "ranchu" ? ["none"] : virt ? VIRT_GRAPHICS_ADAPTERS.slice() : GRAPHICS_ADAPTERS.slice(),
        net_device_types: virt ? VIRT_NET_DEVICE_TYPES.slice() : NET_DEVICE_TYPES.slice(),
        // (the virt machine's sound is virtio_sound)
        audio_devices: virt ? [] : AUDIO_DEVICES.slice(),
        // (the virt machine's input is virtio_input)
        usb_controllers: virt ? [] : USB_CONTROLLERS.slice(),
        cpu_profiles: cpu_profiles_of(cpu_type, machine_type),
        max_cores: MAX_CORES,
        acpi: virt ? "none" : machine_type === "q35" ? "required" : "with_cores",
        unavailable,
    };
}
                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/main.js                                                                              0000644 0000000 0000000 00000034142 00000000000 011741  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { CPU } from "./cpu.js";
import { A64CPU } from "./arm/cpu.js";
import { save_state, restore_state, save_state_stream, restore_state_stream } from "./state.js";
import { export_raw } from "./image/export.js";
import { export_qcow2 } from "./image/qcow2_export.js";
import { release_disk_holds, drop_disk_holds, check_no_disk_holds } from "./block_backend.js";
import { disks_to_prepare, prepare_disks } from "./disk_writeback.js";
import { PluginDevice } from "./device_plugin.js";
export { V86 } from "./browser/starter.js";

/**
 * @constructor
 * @param {Object=} wasm
 */
export function v86(bus, wasm)
{
    /** @type {boolean} */
    this.running = false;

    /** @type {boolean} */
    this.stopping = false;

    /** @type {boolean} */
    this.idle = true;

    this.tick_counter = 0;
    this.worker = null;

    // the CPU of the core's family (docs/arm64-virt-android16-plan.md P1.2):
    // the ARM core exports the ISA marker isa_aarch64
    const stop_idling = () => { this.running && this.idle && this.next_tick(0); };
    /** @type {CPU} */
    this.cpu = wasm.exports["isa_aarch64"] ? /** @type {?} */ (new A64CPU(bus, wasm, stop_idling)) : new CPU(bus, wasm, stop_idling);
    // (a disk request failed with disk_error "stop": src/block_backend.js)
    this.cpu.stop_machine = () => this.stop();

    this.bus = bus;

    this.register_yield();
}

v86.prototype.run = function()
{
    if(this.state_busy) { this.state_busy.resume = true; return; }
    if(this.cpu.parallel?.failure) return;   // a vCPU failed: the machine cannot go on
    this.stopping = false;
    this.cpu.clock.resume();

    if(this.cpu.powered_off())
    {
        // The guest turned the machine off (ACPI S5/S4): power it on again
        this.cpu.reboot_internal("power-on");
    }

    if(!this.running)
    {
        this.running = true;
        this.bus.send("emulator-started");
    }

    // the disk requests held after an I/O error (disk_error "stop") are
    // retried, in their order (src/block_backend.js)
    release_disk_holds(this.cpu);

    this.next_tick(0);
};

v86.prototype.do_tick = function()
{
    if(this.stopping || !this.running)
    {
        // (the cores in vCPU workers stop too; run_cores lets them go on)
        this.cpu.parallel?.request_stop();
        this.cpu.clock.pause();
        this.stopping = this.running = false;
        this.bus.send("emulator-stopped");
        return;
    }

    this.idle = false;
    const t = this.cpu.clock.to_host_ms(this.cpu.run_cores());

    const failure = this.cpu.parallel?.failure;
    if(failure)
    {
        // a vCPU worker failed (src/parallel/machine.js)
        this.cpu.clock.pause();
        this.stopping = this.running = false;
        this.bus.send("emulator-stopped");
        this.bus.send("emulator-error", failure);
        return;
    }

    if(this.cpu.powered_off())
    {
        // The guest turned the machine off; stop at the end of this slice
        this.stopping = true;
        this.next_tick(0);
        return;
    }

    this.next_tick(t);
};

v86.prototype.next_tick = function(t)
{
    const tick = ++this.tick_counter;
    this.idle = true;
    this.yield(t, tick);
};

v86.prototype.yield_callback = function(tick)
{
    if(tick === this.tick_counter)
    {
        this.do_tick();
    }
};

v86.prototype.stop = function()
{
    if(this.state_busy) { this.state_busy.resume = false; return; }
    if(this.running)
    {
        this.stopping = true;
    }
};

v86.prototype.destroy = function()
{
    // (the disk requests held after an I/O error are dropped, as by a power loss)
    drop_disk_holds(this.cpu);
    this.cpu.parallel?.destroy();
    // (a device plugin's hook: src/device_plugin.js)
    this.cpu.devices.net instanceof PluginDevice && this.cpu.devices.net.destroy();
    this.cpu.devices.audio && this.cpu.devices.audio.destroy();
    this.cpu.devices.usb && this.cpu.devices.usb.destroy();
    this.cpu.devices.tpm && this.cpu.devices.tpm.destroy();
    this.cpu.clock.pause();
    this.unregister_yield();
};

/** @param {string=} reason "power-on" after the guest turned the machine off */
v86.prototype.restart = function(reason)
{
    if(this.state_busy) throw new Error("Snapshot transaction is in progress");
    this.cpu.reboot_internal(reason === "power-on" ? "power-on" : "restart");
};

v86.prototype.init = function(settings)
{
    this.cpu.init(settings, this.bus);
    this.cpu.clock.pause();
    this.bus.send("emulator-ready");
};

if(typeof process !== "undefined")
{
    v86.prototype.yield = function(t, tick)
    {
        /* global global */
        if(t < 1)
        {
            global.setImmediate(tick => this.yield_callback(tick), tick);
        }
        else
        {
            setTimeout(tick => this.yield_callback(tick), t, tick);
        }
    };

    v86.prototype.register_yield = function() {};
    v86.prototype.unregister_yield = function() {};
}
else if(globalThis["scheduler"] && typeof globalThis["scheduler"]["postTask"] === "function" && location.href.includes("use-scheduling-api"))
{
    v86.prototype.yield = function(t, tick)
    {
        t = Math.max(0, t);
        globalThis["scheduler"]["postTask"](() => this.yield_callback(tick), { delay: t });
    };

    v86.prototype.register_yield = function() {};
    v86.prototype.unregister_yield = function() {};
}
else if(typeof window === "undefined" && typeof MessageChannel !== "undefined")
{
    // The CPU is already in a dedicated worker. A local task queue yields to
    // input/GPU replies without a second worker and without timer clamping.
    v86.prototype.register_yield = function()
    {
        this.tick_channel = new globalThis.MessageChannel();
        this.tick_channel.port1.onmessage = e => this.yield_callback(e.data);
    };
    v86.prototype.yield = function(t, tick)
    {
        if(t < 1) this.tick_channel.port2.postMessage(tick);
        else this.tick_timeout = setTimeout(() => this.yield_callback(tick), t);
    };
    v86.prototype.unregister_yield = function()
    {
        clearTimeout(this.tick_timeout);
        this.tick_channel.port1.close();
        this.tick_channel.port2.close();
    };
}
else if(typeof Worker !== "undefined")
{
    // XXX: This has a slightly lower throughput compared to window.postMessage

    function the_worker()
    {
        let timeout;
        globalThis.onmessage = function(e)
        {
            const t = e.data.t;
            timeout = timeout && clearTimeout(timeout);
            if(t < 1) postMessage(e.data.tick);
            else timeout = setTimeout(() => postMessage(e.data.tick), t);
        };
    }

    v86.prototype.register_yield = function()
    {
        const url = URL.createObjectURL(new Blob(["(" + the_worker.toString() + ")()"], { type: "text/javascript" }));
        this.worker = new Worker(url);
        this.worker.onmessage = e => this.yield_callback(e.data);
        URL.revokeObjectURL(url);
    };

    v86.prototype.yield = function(t, tick)
    {
        this.worker.postMessage({ t, tick });
    };

    v86.prototype.unregister_yield = function()
    {
        this.worker && this.worker.terminate();
        this.worker = null;
    };
}
//else if(typeof window !== "undefined" && typeof postMessage !== "undefined")
//{
//    // setImmediate shim for the browser.
//    // TODO: Make this deactivatable, for other applications
//    //       using postMessage
//
//    const MAGIC_POST_MESSAGE = 0xAA55;
//
//    v86.prototype.yield = function(t)
//    {
//        // XXX: Use t
//        window.postMessage(MAGIC_POST_MESSAGE, "*");
//    };
//
//    let tick;
//
//    v86.prototype.register_yield = function()
//    {
//        tick = e =>
//        {
//            if(e.source === window && e.data === MAGIC_POST_MESSAGE)
//            {
//                this.do_tick();
//            }
//        };
//
//        window.addEventListener("message", tick, false);
//    };
//
//    v86.prototype.unregister_yield = function()
//    {
//        window.removeEventListener("message", tick);
//        tick = null;
//    };
//}
else
{
    v86.prototype.yield = function(t)
    {
        setTimeout(() => { this.do_tick(); }, t);
    };

    v86.prototype.register_yield = function() {};
    v86.prototype.unregister_yield = function() {};
}

// Async snapshots keep the scheduler stopped for the entire writer/read cycle,
// including backpressure. External input cannot start new DMA while draining.
v86.prototype.state_transaction = function(operation, resume_on_error)
{
    const previous = this.state_operation || Promise.resolve();
    const next = previous.then(async () => {
        const transaction = { resume: this.running && !this.stopping };
        this.state_busy = transaction;
        ++this.tick_counter;
        this.running = this.stopping = false;
        this.idle = true;
        this.cpu.clock.pause();
        this.bus.send("emulator-stopped");
        const input = this.bus.pair, pending = [];
        const send = input && input.send;
        if(input) input.send = (...args) => { pending.push(args); };
        let success = false;
        try
        {
            const deadline = Date.now() + 30000;
            while(this.cpu["snapshot_io_pending"])
            {
                if(Date.now() >= deadline) throw new Error("Snapshot timed out waiting for device I/O");
                await new Promise(resolve => setTimeout(resolve, 1));
            }
            const result = await operation();
            success = true;
            return result;
        }
        finally
        {
            this.state_busy = null;
            if(input)
            {
                input.send = send;
                for(const args of pending) send.apply(input, args);
            }
            if(transaction.resume && (success || resume_on_error)) this.run();
        }
    });
    this.state_operation = next.then(() => {}, () => {});
    return next;
};

/**
 * With cores in vCPU workers, a snapshot waits until each of them is parked
 * at a safe point; run() lets them continue (src/parallel/machine.js).
 */
v86.prototype.parallel_save = async function(save)
{
    await this.cpu.parallel.park();
    this.cpu.parallel_capture();
    return save();
};

v86.prototype.parallel_restore = async function(restore)
{
    await this.cpu.parallel.park();
    const result = await restore();
    this.cpu.parallel_install();
    return result;
};

v86.prototype.save_state_stream = function(write)
{
    // (the disks written back to a disk service: flushed, their generation
    // recorded, with the machine stopped: src/disk_writeback.js)
    const prepare = disks_to_prepare(this.cpu);
    const save = async () =>
    {
        if(prepare.length) { check_no_disk_holds(this.cpu); await prepare_disks(prepare); }
        return this.cpu.parallel ? this.parallel_save(() => save_state_stream(this.cpu, write)) : save_state_stream(this.cpu, write);
    };
    return this.state_transaction(save, true);
};

v86.prototype.restore_state_stream = function(source)
{
    if(this.cpu.parallel) return this.state_transaction(() => this.parallel_restore(() => restore_state_stream(this.cpu, source)), false);
    return this.state_transaction(() => restore_state_stream(this.cpu, source), false);
};

/**
 * Export a disk as the guest sees it, RAW (src/image/export.js) or a new
 * QCOW2 image (src/image/qcow2_export.js): the machine stops and its disk
 * I/O finishes first, so the stream is one view of the disk; it goes on
 * afterwards
 * @param {?} buffer the disk's buffer
 * @param {function(!Uint8Array):(Promise<*>|undefined)} write
 * @param {?=} options format ("raw", "qcow2"), progress, signal
 * @return {!Promise<number>}
 */
v86.prototype.export_disk = function(buffer, write, options)
{
    const format = options && options.format || "raw";
    if(format !== "raw" && format !== "qcow2") return Promise.reject(new Error("Export: unknown format " + JSON.stringify(format) + " (raw, qcow2)"));
    const run = () => format === "qcow2" ? export_qcow2(buffer, write, options) : export_raw(buffer, write, options);
    if(this.cpu.parallel) return this.state_transaction(() => this.parallel_save(run), true);
    return this.state_transaction(run, true);
};

v86.prototype.save_state = function()
{
    // (the disks written back to a disk service: flushed, their generation
    // recorded, with the machine stopped: src/disk_writeback.js)
    const prepare = disks_to_prepare(this.cpu);
    if(prepare.length)
    {
        return this.state_transaction(async () =>
        {
            check_no_disk_holds(this.cpu);
            await prepare_disks(prepare);
            return this.cpu.parallel ? this.parallel_save(() => save_state(this.cpu)) : save_state(this.cpu);
        }, true);
    }
    if(this.cpu.parallel) return this.state_transaction(() => this.parallel_save(() => save_state(this.cpu)), true);
    // (disk I/O in flight: the commands complete first, their devices are
    // then in a state a snapshot can hold)
    if(this.state_busy || this.cpu["snapshot_io_pending"]) return this.state_transaction(() => save_state(this.cpu), true);
    if(this.cpu.in_cpu) return Promise.resolve().then(() => this.save_state());
    const paused = this.cpu.clock.paused;
    this.cpu.clock.pause();
    try { return save_state(this.cpu); }
    finally { if(!paused) this.cpu.clock.resume(); }
};

v86.prototype.restore_state = function(state)
{
    if(this.cpu.parallel) return this.state_transaction(() => this.parallel_restore(() => restore_state(this.cpu, state)), false);
    if(this.state_busy) return this.state_transaction(() => restore_state(this.cpu, state), false);
    if(this.cpu.in_cpu) return Promise.resolve().then(() => this.restore_state(state));
    const paused = this.cpu.clock.paused;
    this.cpu.clock.pause();
    try { return restore_state(this.cpu, state); }
    finally { if(!paused) this.cpu.clock.resume(); }
};

/* global require */
if(typeof performance === "object" && performance.now)
{
    v86.microtick = performance.now.bind(performance);
}
else if(typeof require === "function")
{
    const { performance } = require("perf_hooks");
    v86.microtick = performance.now.bind(performance);
}
else if(typeof process === "object" && process.hrtime)
{
    v86.microtick = function()
    {
        var t = process.hrtime();
        return t[0] * 1000 + t[1] / 1e6;
    };
}
else
{
    v86.microtick = Date.now;
}
                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/net_adapters/e1000/e1000.js                                                          0000644 0000000 0000000 00000151071 00000000000 014741  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Intel 82540EM Gigabit Ethernet controller (PRO/1000 MT Desktop,
// 8086:100E, subsystem 8086:001E): the card Windows Vista to 11 and Linux
// drive with their own drivers (nete1g3e.inf, e1000.ko). See
// docs/modern-pc-devices-plan.md, "N1", and the PCI/PCI-X Family of Gigabit
// Ethernet Controllers Software Developer's Manual (8254x); QEMU's e1000.c
// and VirtualBox's DevE1000.cpp were the references for what drivers expect.
//
// BAR0 holds the registers (128 KiB), BAR1 the I/O window (IOADDR/IODATA).
// Transmit and receive use descriptor rings in guest memory; this model
// moves frames between them and the network bus synchronously: a write of
// TDT sends what is queued, a frame from the network goes straight into the
// receive ring. What waits (receive delay timers, interrupt throttling,
// auto-negotiation, frames that found no free descriptor) waits on the
// machine clock, through the device's timer.

import { LOG_NET } from "../../const.js";
import { h } from "../../lib.js";
import { dbg_log } from "../../log.js";
import { format_mac, random_mac, translate_mac_address } from "../../mac_address.js";
import { NetMachine } from "../machine.js";
import { CHECKSUM_BAD, CHECKSUM_GOOD, CHECKSUM_NONE, check_checksums, checksum_add, checksum_finish, checksum_fold,
    ethernet_fcs, load16, load32, store16, store32 } from "../offload.js";

const MMIO_SIZE = 0x20000;
const IO_SIZE = 0x40;

const PCI_VENDOR = 0x8086;
const PCI_DEVICE = 0x100E;
const PCI_SUBSYSTEM = 0x001E;
const PCI_REVISION = 0x02;
/** The power management capability (the 82540EM has no MSI) */
const PM_CAP = 0xDC;
const PM_PMC = 0xC822;

// registers (byte offsets in BAR0)
const CTRL = 0x0000, STATUS = 0x0008, EECD = 0x0010, EERD = 0x0014, CTRL_EXT = 0x0018, FLA = 0x001C, MDIC = 0x0020,
    FCAL = 0x0028, FCAH = 0x002C, FCT = 0x0030, VET = 0x0038,
    ICR = 0x00C0, ITR = 0x00C4, ICS = 0x00C8, IMS = 0x00D0, IMC = 0x00D8,
    RCTL = 0x0100, FCTTV = 0x0170, TXCW = 0x0178, RXCW = 0x0180, TCTL = 0x0400, TIPG = 0x0410, AIT = 0x0458,
    LEDCTL = 0x0E00, PBA = 0x1000, FCRTL = 0x2160, FCRTH = 0x2168,
    RDFH = 0x2410, RDFT = 0x2418, RDFHS = 0x2420, RDFTS = 0x2428, RDFPC = 0x2430,
    RDBAL = 0x2800, RDBAH = 0x2804, RDLEN = 0x2808, RDH = 0x2810, RDT = 0x2818, RDTR = 0x2820, RXDCTL = 0x2828, RADV = 0x282C,
    RSRPD = 0x2C00,
    TDFH = 0x3410, TDFT = 0x3418, TDFHS = 0x3420, TDFTS = 0x3428, TDFPC = 0x3430,
    TDBAL = 0x3800, TDBAH = 0x3804, TDLEN = 0x3808, TDH = 0x3810, TDT = 0x3818, TIDV = 0x3820, TXDCTL = 0x3828, TADV = 0x382C,
    RXCSUM = 0x5000, MTA = 0x5200, RA = 0x5400, VFTA = 0x5600,
    WUC = 0x5800, WUFC = 0x5808, WUS = 0x5810, MANC = 0x5820, IPAV = 0x5838, IP4AT = 0x5840, IP6AT = 0x5880,
    WUPL = 0x5900, WUPM = 0x5A00, FFLT = 0x5F00, FFMT = 0x9000, FFVT = 0x9800;

// statistics (all read to clear; a 64-bit counter clears when its high half is read)
const STATS_START = 0x4000, STATS_END = 0x4100;
const MPC = 0x4010, GPRC = 0x4074, BPRC = 0x4078, MPRC = 0x407C, GPTC = 0x4080,
    GORCL = 0x4088, GORCH = 0x408C, GOTCL = 0x4090, GOTCH = 0x4094, RNBC = 0x40A0, ROC = 0x40AC,
    TORL = 0x40C0, TORH = 0x40C4, TOTL = 0x40C8, TOTH = 0x40CC, TPR = 0x40D0, TPT = 0x40D4,
    MPTC = 0x40F0, BPTC = 0x40F4, TSCTC = 0x40F8;
const PRC_SIZES = [0x405C, 0x4060, 0x4064, 0x4068, 0x406C, 0x4070];
const PTC_SIZES = [0x40D8, 0x40DC, 0x40E0, 0x40E4, 0x40E8, 0x40EC];

// CTRL
const CTRL_FD = 1 << 0, CTRL_SLU = 1 << 6, CTRL_SPD_1000 = 2 << 8, CTRL_SWDPIN0 = 1 << 18, CTRL_SWDPIN2 = 1 << 20,
    CTRL_RST = 1 << 26, CTRL_VME = 1 << 30, CTRL_PHY_RST = 1 << 31;
// STATUS
const STATUS_FD = 1 << 0, STATUS_LU = 1 << 1, STATUS_SPEED_1000 = 2 << 6, STATUS_ASDV_1000 = 3 << 8, STATUS_MTXCKOK = 1 << 10,
    STATUS_GIO_MASTER_ENABLE = 1 << 19;
// EECD
const EECD_SK = 1 << 0, EECD_CS = 1 << 1, EECD_DI = 1 << 2, EECD_DO = 1 << 3, EECD_FWE = 3 << 4, EECD_REQ = 1 << 6,
    EECD_GNT = 1 << 7, EECD_PRES = 1 << 8;
const EECD_WRITABLE = EECD_SK | EECD_CS | EECD_DI | EECD_FWE | EECD_REQ;
const EEPROM_READ_OPCODE = 6;
// EERD
const EERD_START = 1 << 0, EERD_DONE = 1 << 4;
// MDIC
const MDIC_OP_WRITE = 1, MDIC_OP_READ = 2, MDIC_READY = 1 << 28, MDIC_INT_EN = 1 << 29, MDIC_ERROR = 1 << 30;
// interrupt causes (ICR, ICS, IMS, IMC)
const ICR_TXDW = 1 << 0, ICR_TXQE = 1 << 1, ICR_LSC = 1 << 2, ICR_RXDMT0 = 1 << 4, ICR_RXO = 1 << 6, ICR_RXT0 = 1 << 7,
    ICR_MDAC = 1 << 9;
const ICR_MASK = 0x0001F6DF;
// RCTL
const RCTL_EN = 1 << 1, RCTL_SBP = 1 << 2, RCTL_UPE = 1 << 3, RCTL_MPE = 1 << 4, RCTL_LPE = 1 << 5, RCTL_LBM = 3 << 6,
    RCTL_BAM = 1 << 15, RCTL_VFE = 1 << 18, RCTL_BSEX = 1 << 25, RCTL_SECRC = 1 << 26;
// TCTL
const TCTL_EN = 1 << 1;
// RXCSUM
const RXCSUM_IPOFL = 1 << 8, RXCSUM_TUOFL = 1 << 9;
// RAH
const RAH_AV = 1 << 31;
// (RDTR, TIDV) flush partial descriptor block: the delay ends now
const DELAY_FPD = 1 << 31;

// transmit descriptors: the command byte (bits 24-31 of the second dword)
const TXD_EOP = 1 << 24, TXD_IC = 1 << 26, TXD_TSE = 1 << 26, TXD_RS = 1 << 27, TXD_RPS = 1 << 28, TXD_DEXT = 1 << 29,
    TXD_VLE = 1 << 30, TXD_IDE = 1 << 31, TXD_DTYP_D = 1 << 20;
// a context descriptor's TUCMD
const TXD_CMD_TCP = 1 << 24, TXD_CMD_IP = 1 << 25;
// a data descriptor's POPTS
const POPTS_IXSM = 1, POPTS_TXSM = 2;
// a descriptor's status
const TXD_STAT_DD = 1;

// receive descriptor status and errors
const RXD_STAT_DD = 1 << 0, RXD_STAT_EOP = 1 << 1, RXD_STAT_IXSM = 1 << 2, RXD_STAT_VP = 1 << 3, RXD_STAT_TCPCS = 1 << 5,
    RXD_STAT_IPCS = 1 << 6;
const RXD_ERR_TCPE = 1 << 5, RXD_ERR_IPE = 1 << 6;

// the PHY (Marvell 88E1011, as on the 82540EM), at MDIO address 1
const PHY_ADDRESS = 1;
const MII_BMCR = 0, MII_BMSR = 1, MII_PHYID1 = 2, MII_PHYID2 = 3, MII_ANAR = 4, MII_ANLPAR = 5, MII_ANER = 6,
    MII_CTRL1000 = 9, MII_STAT1000 = 10, MII_EXTSTAT = 15,
    M88_PHY_SPEC_CTRL = 0x10, M88_PHY_SPEC_STATUS = 0x11, M88_INT_STATUS = 0x13, M88_EXT_PHY_SPEC_CTRL = 0x14,
    M88_RX_ERR_CNTR = 0x15;
const BMCR_RESET = 1 << 15, BMCR_LOOPBACK = 1 << 14, BMCR_AUTOEN = 1 << 12, BMCR_ANRESTART = 1 << 9;
const BMSR_LINK = 1 << 2, BMSR_AN_COMP = 1 << 5;
const ANLPAR_ACK = 1 << 14;
const M88_STATUS_LINK = 1 << 10;
const PHY_READ_ONLY = [MII_BMSR, MII_PHYID1, MII_PHYID2, MII_ANLPAR, MII_ANER, MII_STAT1000, MII_EXTSTAT,
    M88_PHY_SPEC_STATUS, M88_INT_STATUS, M88_RX_ERR_CNTR];
const PHY_INIT = new Map([
    [MII_BMCR, 0x1140], [MII_BMSR, 0x796D], [MII_PHYID1, 0x0141], [MII_PHYID2, 0x0C20], [MII_ANAR, 0x0DE1],
    [MII_ANLPAR, 0x01E0 | ANLPAR_ACK], [MII_ANER, 0x0001], [MII_CTRL1000, 0x0E00], [MII_STAT1000, 0x3C00], [MII_EXTSTAT, 0x3000],
    [M88_PHY_SPEC_CTRL, 0x0360], [M88_PHY_SPEC_STATUS, 0xAC00], [M88_EXT_PHY_SPEC_CTRL, 0x0D60],
]);
/** How long auto-negotiation takes after a restart */
const AUTONEG_MS = 100;

/** The EEPROM's 64 words (QEMU's template); the address, IDs and checksum are filled in */
const EEPROM_TEMPLATE = [
    0x0000, 0x0000, 0x0000, 0x0000, 0xFFFF, 0x0000, 0x0000, 0x0000,
    0x3000, 0x1000, 0x6403, PCI_SUBSYSTEM, PCI_VENDOR, PCI_DEVICE, PCI_VENDOR, 0x3040,
    0x0008, 0x2000, 0x7E14, 0x0048, 0x1000, 0x00D8, 0x0000, 0x2700,
    0x6CC9, 0x3150, 0x0722, 0x040B, 0x0984, 0x0000, 0xC000, 0x0706,
    0x1008, 0x0000, 0x0F04, 0x7FFF, 0x4D01, 0xFFFF, 0xFFFF, 0xFFFF,
    0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
    0x0100, 0x4000, 0x121C, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF,
    0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0x0000,
];
const EEPROM_WORDS = 64;
const EEPROM_CHECKSUM = 0xBABA;

/** A transmitted frame is gathered here (and a TSO segment); longer ones are cut */
const TX_BUFFER_SIZE = 0x10000;
/** Per round: descriptors and bytes, the rest in the next (the timer's) */
const TX_DESCRIPTOR_BUDGET = 256;
const TX_BYTE_BUDGET = 1 << 20;

/** The 802.3 limits: a frame without its FCS */
const MIN_FRAME = 60;
const MAX_FRAME = 1518;
const MAX_LONG_FRAME = 16384 - 4;

/** The machine clock is in milliseconds: ITR counts 256 ns, the delay timers 1.024 µs */
const ITR_UNIT = 256e-6;
const DELAY_UNIT = 1.024e-3;

// a context's fields (Int32Array)
const P_IPCSS = 0, P_IPCSO = 1, P_IPCSE = 2, P_TUCSS = 3, P_TUCSO = 4, P_TUCSE = 5, P_PAYLEN = 6, P_HDRLEN = 7, P_MSS = 8,
    P_IP = 9, P_TCP = 10, PROPS_SIZE = 11;

// deadlines (Float64Array, machine time; 0 when not set)
const T_AUTONEG = 0, T_RX_PACKET = 1, T_RX_ABSOLUTE = 2, T_TX_PACKET = 3, T_TX_ABSOLUTE = 4, T_ITR = 5, T_COUNT = 6;

// What the registers are, by dword: plain storage, a statistic, or handled
// in read/write (everything else reads 0 and ignores writes)
const REG_PLAIN = 1, REG_STAT = 2, REG_STAT_LOW = 3, REG_STAT_HIGH = 4, REG_SPECIAL = 5;
const REG_KIND = new Uint8Array(MMIO_SIZE >> 2);
{
    const mark = (offset, kind, count = 1) => REG_KIND.fill(kind, offset >> 2, (offset >> 2) + count);
    for(const offset of [CTRL_EXT, FLA, FCAL, FCAH, FCT, VET, FCTTV, TXCW, RXCW, TIPG, AIT, LEDCTL, PBA, FCRTL, FCRTH,
        RDFH, RDFT, RDFHS, RDFTS, RDFPC, RDBAL, RDBAH, RXDCTL, RSRPD, TDFH, TDFT, TDFHS, TDFTS, TDFPC, TDBAL, TDBAH, TXDCTL,
        RXCSUM, WUC, WUFC, MANC, IPAV, WUPL])
    {
        mark(offset, REG_PLAIN);
    }
    mark(MTA, REG_PLAIN, 128);
    mark(VFTA, REG_PLAIN, 128);
    mark(IP4AT, REG_PLAIN, 7);
    mark(IP6AT, REG_PLAIN, 4);
    mark(WUPM, REG_PLAIN, 32);
    mark(FFLT, REG_PLAIN, 8);
    mark(FFMT, REG_PLAIN, 256);
    mark(FFVT, REG_PLAIN, 256);
    mark(STATS_START, REG_STAT, (STATS_END - STATS_START) >> 2);
    for(const low of [GORCL, GOTCL, TORL, TOTL])
    {
        mark(low, REG_STAT_LOW);
        mark(low + 4, REG_STAT_HIGH);
    }
    for(const offset of [CTRL, STATUS, EECD, EERD, MDIC, ICR, ITR, ICS, IMS, IMC, RCTL, TCTL, RDLEN, RDH, RDT, RDTR, RADV,
        TDLEN, TDH, TDT, TIDV, TADV, WUS])
    {
        mark(offset, REG_SPECIAL);
    }
    mark(RA, REG_SPECIAL, 32);
}

/** The values after a reset (the rest is 0) */
const REG_INIT = new Map([
    [CTRL, CTRL_SWDPIN2 | CTRL_SWDPIN0 | CTRL_SPD_1000 | CTRL_SLU | CTRL_FD],
    [STATUS, STATUS_GIO_MASTER_ENABLE | STATUS_ASDV_1000 | STATUS_MTXCKOK | STATUS_SPEED_1000 | STATUS_FD | STATUS_LU],
    [EECD, EECD_PRES | EECD_GNT],
    [PBA, 0x00100030],
    [LEDCTL, 0x07068302],
    [TIPG, 0x00602008],
    [RXCSUM, RXCSUM_IPOFL | RXCSUM_TUOFL],
    [TXDCTL, 0x00010000],
    [RXDCTL, 0x00010000],
    [MANC, 0x00222300],
]);

/**
 * @constructor
 * @param {!Object} handle the machine handle (src/device_plugin.js)
 * @param {!Object} options "preserve_mac_from_state_image", "mac_address_translation"
 */
export function E1000(handle, options)
{
    const machine = new NetMachine(handle);
    /** @const @type {NetMachine} */
    this.machine = machine;
    this.name = "e1000";

    this.preserve_mac_from_state_image = !!options["preserve_mac_from_state_image"];
    this.mac_address_translation = !!options["mac_address_translation"];

    /** The card's own address (the one the network knows) */
    this.mac = random_mac();
    /** After restoring with mac_address_translation: the address the guest has */
    this.mac_in_state = null;

    this.regs = new Int32Array(MMIO_SIZE >> 2);
    this.phy = new Uint16Array(32);
    this.eeprom = new Uint16Array(EEPROM_WORDS);
    this.write_eeprom_address();

    // the EEPROM's serial interface (EECD): bits shifted in, the word shifted out
    this.eecd_bits = 0;
    this.eecd_in = 0;
    this.eecd_in_count = 0;
    this.eecd_out = 0;
    this.eecd_reading = false;

    // the transmit side: the frame being gathered, the contexts of offload
    this.tx_data = new Uint8Array(TX_BUFFER_SIZE);
    this.tx_header = new Uint8Array(256);
    this.tx_size = 0;
    this.tx_props = new Int32Array(PROPS_SIZE);
    this.tx_tso_props = new Int32Array(PROPS_SIZE);
    this.tx_sum_needed = 0;
    this.tx_vlan_tag = -1;
    this.tx_tse = false;
    this.tx_tso_frames = 0;
    /** a legacy descriptor's checksum (IC): [CSO, CSS], or null */
    this.tx_legacy_sum = null;
    /** the ring has more than one round's budget: the timer goes on */
    this.tx_more = false;
    /** the descriptors since the last TXDW had IDE (the delay timers apply) */
    this.tx_ide = false;
    /** what this round sent (TX_BYTE_BUDGET) */
    this.tx_bytes = 0;

    /** Frames that found no free descriptor (the receive FIFO, PBA's size) */
    this.rx_fifo = [];
    this.rx_fifo_bytes = 0;

    this.deadlines = new Float64Array(T_COUNT);
    /** INTA as the card drives it */
    this.irq_level = false;
    /** a rising edge waits for ITR's interval */
    this.irq_held = false;

    this.io_base = machine.allocate_io(IO_SIZE);
    this.io_address = 0;
    /** Where BAR0 is decoded, or -1 */
    this.mmio = -1;
    this.bar0 = 0;

    this.reset_registers();
    this.reset_phy();

    this.register_ports();
    machine.register_pci({
        pci_space: this.create_pci_space(),
        pci_bars: [
            { size: MMIO_SIZE, on_move: base => { this.bar0 = base; this.update_decode(); } },
            { size: IO_SIZE, on_move: undefined },
        ],
        on_command_change: () => { this.update_decode(); this.resume_dma(); },
        on_config_restore: () => this.update_decode(),
        on_upstream_change: () => { this.update_decode(); this.resume_dma(); },
        on_config_write: (offset, size) => this.config_written(offset, size),
    });

    machine.on_receive(frame => this.receive(frame));
    machine.add_timer(now => this.timer(now));
    machine.set_mac(format_mac(this.mac));
    dbg_log("e1000: MAC " + format_mac(this.mac), LOG_NET);
}

E1000.prototype.create_pci_space = function()
{
    const space = new Array(256).fill(0);
    const put16 = (offset, value) => { space[offset] = value & 0xFF; space[offset + 1] = value >> 8 & 0xFF; };
    const put32 = (offset, value) => { put16(offset, value & 0xFFFF); put16(offset + 2, value >>> 16); };
    put16(0x00, PCI_VENDOR);
    put16(0x02, PCI_DEVICE);
    // status: a capabilities list, medium DEVSEL timing
    put16(0x06, 0x0210);
    // revision, class 02/00/00 (Ethernet)
    put32(0x08, PCI_REVISION | 0x02000000);
    put32(0x10, 0);
    put32(0x14, this.io_base | 1);
    put16(0x2C, PCI_VENDOR);
    put16(0x2E, PCI_SUBSYSTEM);
    space[0x34] = PM_CAP;
    // INTA, MIN_GNT
    space[0x3D] = 1;
    space[0x3E] = 0xFF;
    space[PM_CAP] = 0x01;
    put16(PM_CAP + 2, PM_PMC);
    return space;
};

/**
 * A write beyond the header: the power management capability keeps its
 * read-only bytes; PMCSR has its power state and PME enable
 */
E1000.prototype.config_written = function(offset, size)
{
    if(offset + size <= PM_CAP || offset >= PM_CAP + 8) return;
    const space = this.machine.pci_config();
    const pmcsr = (space[PM_CAP + 4] | space[PM_CAP + 5] << 8) & 0x0103;
    space.set([0x01, 0x00, PM_PMC & 0xFF, PM_PMC >> 8, pmcsr & 0xFF, pmcsr >> 8, 0, 0], PM_CAP);
};

/** BAR0 is mapped where it is decoded (memory space on, the bridges upstream forward it) */
E1000.prototype.update_decode = function()
{
    const base = this.bar0 && this.machine.memory_decoded(this.bar0, MMIO_SIZE) ? this.bar0 : -1;
    if(base === this.mmio) return;
    if(this.mmio !== -1)
    {
        this.machine.mmap_unregister_range(this.mmio, MMIO_SIZE);
    }
    dbg_log("e1000: registers " + (base === -1 ? "not decoded" : "at " + h(base >>> 0, 8)), LOG_NET);
    this.mmio = base;
    if(base !== -1)
    {
        this.machine.mmap_register_range(base, MMIO_SIZE,
            address => this.peek(address - this.mmio & ~3) >>> ((address & 3) << 3) & 0xFF,
            (address, value) => this.write_byte(address - this.mmio, value),
            address => this.read(address - this.mmio),
            (address, value) => this.write(address - this.mmio, value));
    }
};

E1000.prototype.register_ports = function()
{
    const machine = this.machine;
    // IOADDR: the register IODATA reaches
    machine.register_read(this.io_base, this,
        function(port) { return this.io_address >>> ((port & 3) << 3) & 0xFF; }, undefined,
        function(port) { return this.io_address; });
    machine.register_write(this.io_base, this, undefined, undefined,
        function(value) { this.io_address = value & 0x1FFFC; });
    machine.register_read(this.io_base + 4, this,
        function(port) { return this.peek(this.io_address) >>> ((port & 3) << 3) & 0xFF; }, undefined,
        function(port) { return this.read(this.io_address); });
    machine.register_write(this.io_base + 4, this, undefined, undefined,
        function(value) { this.write(this.io_address, value); });
};

/** The address in the EEPROM's first words (and its checksum) */
E1000.prototype.write_eeprom_address = function()
{
    this.eeprom.set(EEPROM_TEMPLATE);
    const mac = this.mac;
    this.eeprom[0] = mac[0] | mac[1] << 8;
    this.eeprom[1] = mac[2] | mac[3] << 8;
    this.eeprom[2] = mac[4] | mac[5] << 8;
    this.update_eeprom_checksum();
};

E1000.prototype.update_eeprom_checksum = function()
{
    let sum = 0;
    for(let i = 0; i < EEPROM_WORDS - 1; i++) sum += this.eeprom[i];
    this.eeprom[EEPROM_WORDS - 1] = EEPROM_CHECKSUM - sum & 0xFFFF;
};

/** The address in the EEPROM */
E1000.prototype.eeprom_mac = function()
{
    const e = this.eeprom;
    return new Uint8Array([e[0] & 0xFF, e[0] >> 8, e[1] & 0xFF, e[1] >> 8, e[2] & 0xFF, e[2] >> 8]);
};

/** The address the guest gave receive address 0 (or the EEPROM's) */
E1000.prototype.guest_mac = function()
{
    const low = this.regs[RA >> 2], high = this.regs[RA + 4 >> 2];
    if(!(high & RAH_AV)) return this.eeprom_mac();
    return new Uint8Array([low & 0xFF, low >>> 8 & 0xFF, low >>> 16 & 0xFF, low >>> 24, high & 0xFF, high >>> 8 & 0xFF]);
};

/** The registers of a reset (power on, CTRL.RST): RA[0] from the EEPROM */
E1000.prototype.reset_registers = function()
{
    this.regs.fill(0);
    for(const [offset, value] of REG_INIT) this.regs[offset >> 2] = value;
    const e = this.eeprom;
    this.regs[RA >> 2] = e[0] | e[1] << 16;
    this.regs[RA + 4 >> 2] = e[2] | RAH_AV;
    if(!this.mac_in_state && format_mac(this.mac) !== format_mac(this.eeprom_mac()))
    {
        // (the guest had given the card another address)
        this.mac = this.eeprom_mac();
        this.machine.set_mac(format_mac(this.mac));
    }
    this.eecd_bits = 0;
    this.eecd_reading = false;
    this.io_address = 0;
    this.tx_size = 0;
    this.tx_props.fill(0);
    this.tx_tso_props.fill(0);
    this.tx_sum_needed = 0;
    this.tx_vlan_tag = -1;
    this.tx_tse = false;
    this.tx_tso_frames = 0;
    this.tx_legacy_sum = null;
    this.tx_more = false;
    this.tx_ide = false;
    this.rx_fifo = [];
    this.rx_fifo_bytes = 0;
    const autoneg = this.deadlines[T_AUTONEG];
    this.deadlines.fill(0);
    // (CTRL.RST leaves the PHY as it is)
    this.deadlines[T_AUTONEG] = autoneg;
    this.irq_held = false;
    this.update_irq();
};

E1000.prototype.reset_phy = function()
{
    this.phy.fill(0);
    for(const [reg, value] of PHY_INIT) this.phy[reg] = value;
    this.deadlines[T_AUTONEG] = 0;
    this.set_link(true);
};

/** A machine reset (PCIRST#) */
E1000.prototype.reset = function()
{
    this.reset_registers();
    this.reset_phy();
    this.update_decode();
};

/**
 * The link as the MAC and the PHY report it
 * @param {boolean} up
 */
E1000.prototype.set_link = function(up)
{
    const status = this.regs[STATUS >> 2];
    this.regs[STATUS >> 2] = up ? status | STATUS_LU : status & ~STATUS_LU;
    if(up)
    {
        this.phy[MII_BMSR] |= BMSR_LINK | BMSR_AN_COMP;
        this.phy[M88_PHY_SPEC_STATUS] |= M88_STATUS_LINK;
        this.phy[MII_ANLPAR] |= ANLPAR_ACK;
    }
    else
    {
        this.phy[MII_BMSR] &= ~(BMSR_LINK | BMSR_AN_COMP);
        this.phy[M88_PHY_SPEC_STATUS] &= ~M88_STATUS_LINK;
        this.phy[MII_ANLPAR] &= ~ANLPAR_ACK;
    }
};

E1000.prototype.link_up = function()
{
    return !!(this.regs[STATUS >> 2] & STATUS_LU);
};

// registers

/**
 * A register's value without the side effects of reading it
 * @param {number} offset
 * @return {number}
 */
E1000.prototype.peek = function(offset)
{
    offset &= MMIO_SIZE - 4;
    switch(offset)
    {
        case EECD:
            return this.read_eecd();
        case IMC:
            return 0;
        case ICS:
            return this.regs[ICR >> 2];
    }
    return REG_KIND[offset >> 2] ? this.regs[offset >> 2] : 0;
};

/**
 * @param {number} offset
 * @return {number}
 */
E1000.prototype.read = function(offset)
{
    offset &= MMIO_SIZE - 4;
    const kind = REG_KIND[offset >> 2];
    if(kind === REG_STAT || kind === REG_STAT_HIGH)
    {
        const value = this.regs[offset >> 2];
        this.regs[offset >> 2] = 0;
        if(kind === REG_STAT_HIGH) this.regs[offset - 4 >> 2] = 0;
        return value;
    }
    if(offset === ICR)
    {
        const value = this.regs[ICR >> 2];
        this.regs[ICR >> 2] = 0;
        this.update_irq();
        return value;
    }
    if(!kind)
    {
        dbg_log("e1000: read of unknown register " + h(offset, 5), LOG_NET);
    }
    return this.peek(offset);
};

/**
 * A byte write: the register's other bytes as they are
 * @param {number} offset
 * @param {number} value
 */
E1000.prototype.write_byte = function(offset, value)
{
    const shift = (offset & 3) << 3;
    const old = offset === ICR || offset === ICS || offset === IMS || offset === IMC ? 0 : this.peek(offset & ~3);
    this.write(offset & ~3, old & ~(0xFF << shift) | (value & 0xFF) << shift);
};

/**
 * @param {number} offset
 * @param {number} value
 */
E1000.prototype.write = function(offset, value)
{
    offset &= MMIO_SIZE - 4;
    const index = offset >> 2;
    const kind = REG_KIND[index];
    if(kind === REG_PLAIN)
    {
        this.regs[index] = value;
        return;
    }
    if(kind !== REG_SPECIAL)
    {
        if(!kind) dbg_log("e1000: write of unknown register " + h(offset, 5) + ": " + h(value >>> 0, 8), LOG_NET);
        return;
    }
    if(offset >= RA && offset < RA + 0x80)
    {
        this.regs[index] = value;
        if(offset === RA + 4) this.receive_address_written();
        return;
    }
    switch(offset)
    {
        case CTRL:
            if(value & CTRL_RST)
            {
                dbg_log("e1000: reset", LOG_NET);
                this.reset_registers();
                return;
            }
            if(value & CTRL_PHY_RST && !(this.regs[index] & CTRL_PHY_RST))
            {
                this.reset_phy();
            }
            this.regs[index] = value;
            break;
        case STATUS:
            break;
        case EECD:
            this.write_eecd(value);
            break;
        case EERD:
            this.regs[index] = value & EERD_START ? this.read_eerd(value) : value & ~EERD_DONE;
            break;
        case MDIC:
            this.regs[index] = this.mdio(value);
            if(value & MDIC_INT_EN) this.interrupt(ICR_MDAC);
            break;
        case ICR:
            this.regs[ICR >> 2] &= ~value;
            this.update_irq();
            break;
        case ICS:
            this.interrupt(value & ICR_MASK);
            break;
        case IMS:
            this.regs[index] |= value & ICR_MASK;
            this.update_irq();
            break;
        case IMC:
            this.regs[IMS >> 2] &= ~value;
            this.update_irq();
            break;
        case ITR:
            this.regs[index] = value & 0xFFFF;
            if(!(value & 0xFFFF))
            {
                // (no throttling: what waits goes now)
                this.deadlines[T_ITR] = 0;
                this.update_irq();
            }
            break;
        case RCTL:
            this.regs[index] = value;
            this.drain_rx_fifo();
            break;
        case TCTL:
            this.regs[index] = value;
            this.transmit();
            break;
        case RDLEN:
        case TDLEN:
            this.regs[index] = value & 0xFFF80;
            break;
        case RDH:
        case TDH:
            this.regs[index] = value & 0xFFFF;
            break;
        case RDT:
            this.regs[index] = value & 0xFFFF;
            this.drain_rx_fifo();
            break;
        case TDT:
            this.regs[index] = value & 0xFFFF;
            this.transmit();
            break;
        case RDTR:
            this.regs[index] = value & 0xFFFF;
            if(value & DELAY_FPD) this.end_rx_delay();
            break;
        case TIDV:
            this.regs[index] = value & 0xFFFF;
            if(value & DELAY_FPD) this.end_tx_delay();
            break;
        case RADV:
        case TADV:
            this.regs[index] = value & 0xFFFF;
            break;
        case WUS:
            this.regs[index] &= ~value;
            break;
    }
};

/**
 * The guest set receive address 0: the network learns it (with address
 * translation, the guest's address is the one translated)
 */
E1000.prototype.receive_address_written = function()
{
    if(!(this.regs[RA + 4 >> 2] & RAH_AV)) return;
    const mac = this.guest_mac();
    if(this.mac_in_state)
    {
        this.mac_in_state = mac;
    }
    else if(format_mac(mac) !== format_mac(this.mac))
    {
        this.mac = mac;
        this.machine.set_mac(format_mac(mac));
    }
};

// the EEPROM

/**
 * EERD: a word read in one step
 * @param {number} value
 * @return {number}
 */
E1000.prototype.read_eerd = function(value)
{
    const address = value >>> 8 & 0xFF;
    const word = address < EEPROM_WORDS ? this.eeprom[address] : 0;
    return word << 16 | address << 8 | EERD_DONE;
};

/** @return {number} */
E1000.prototype.read_eecd = function()
{
    let value = EECD_PRES | EECD_GNT | this.eecd_bits;
    if(!this.eecd_reading || this.eeprom[this.eecd_out >> 4 & (EEPROM_WORDS - 1)] >> (~this.eecd_out & 0xF) & 1)
    {
        value |= EECD_DO;
    }
    return value;
};

/**
 * EECD: Microwire, bit by bit. The read opcode (110) and six address bits go
 * in on rising edges of SK, the word comes out most significant bit first,
 * advancing on falling edges
 * @param {number} value
 */
E1000.prototype.write_eecd = function(value)
{
    const old = this.eecd_bits;
    this.eecd_bits = value & EECD_WRITABLE;
    if(!(value & EECD_CS)) return;
    if(!(old & EECD_CS))
    {
        this.eecd_in = 0;
        this.eecd_in_count = 0;
        this.eecd_out = 0;
        this.eecd_reading = false;
    }
    if(!((old ^ value) & EECD_SK)) return;
    if(!(value & EECD_SK))
    {
        this.eecd_out++;
        return;
    }
    this.eecd_in = this.eecd_in << 1 | (value & EECD_DI ? 1 : 0);
    if(++this.eecd_in_count === 9 && !this.eecd_reading)
    {
        this.eecd_out = ((this.eecd_in & 0x3F) << 4) - 1;
        this.eecd_reading = (this.eecd_in >> 6 & 7) === EEPROM_READ_OPCODE;
    }
};

// the PHY

/**
 * An MDIO transaction (MDIC): done at once
 * @param {number} value
 * @return {number} MDIC afterwards
 */
E1000.prototype.mdio = function(value)
{
    const address = value >>> 21 & 0x1F, reg = value >>> 16 & 0x1F, op = value >>> 26 & 3;
    if(address !== PHY_ADDRESS)
    {
        return value | MDIC_READY | MDIC_ERROR;
    }
    if(op === MDIC_OP_READ)
    {
        return value & ~0xFFFF | this.phy[reg] | MDIC_READY;
    }
    if(op === MDIC_OP_WRITE)
    {
        this.phy_write(reg, value & 0xFFFF);
    }
    return value | MDIC_READY;
};

/**
 * @param {number} reg
 * @param {number} value
 */
E1000.prototype.phy_write = function(reg, value)
{
    if(PHY_READ_ONLY.includes(reg)) return;
    if(reg !== MII_BMCR)
    {
        this.phy[reg] = value;
        return;
    }
    if(value & BMCR_RESET)
    {
        this.reset_phy();
    }
    this.phy[MII_BMCR] = value & ~(BMCR_RESET | BMCR_ANRESTART);
    if(value & BMCR_AUTOEN && value & BMCR_ANRESTART)
    {
        // the link goes down while the PHY negotiates again
        this.set_link(false);
        this.deadlines[T_AUTONEG] = this.machine.now() + AUTONEG_MS;
    }
};

// interrupts

/**
 * Set interrupt causes
 * @param {number} causes
 */
E1000.prototype.interrupt = function(causes)
{
    this.regs[ICR >> 2] |= causes;
    this.update_irq();
};

/**
 * INTA follows ICR & IMS; a rising edge waits for the interval ITR sets
 * since the last one
 */
E1000.prototype.update_irq = function()
{
    const pending = (this.regs[ICR >> 2] & this.regs[IMS >> 2]) !== 0;
    if(pending === this.irq_level)
    {
        if(!pending) this.irq_held = false;
        return;
    }
    if(!pending)
    {
        this.irq_level = false;
        this.irq_held = false;
        this.machine.lower_irq();
        return;
    }
    const now = this.machine.now();
    if(this.deadlines[T_ITR] > now)
    {
        // (the timer raises it; from a frame of the network, a halted
        // machine wakes for that)
        if(!this.irq_held) this.machine.wake();
        this.irq_held = true;
        return;
    }
    this.irq_held = false;
    this.irq_level = true;
    const interval = this.regs[ITR >> 2] & 0xFFFF;
    this.deadlines[T_ITR] = interval ? now + interval * ITR_UNIT : 0;
    this.machine.raise_irq();
};

/** The receive delay ended (RDTR, RADV, a flush): RXT0 */
E1000.prototype.end_rx_delay = function()
{
    if(!this.deadlines[T_RX_PACKET] && !this.deadlines[T_RX_ABSOLUTE]) return;
    this.deadlines[T_RX_PACKET] = this.deadlines[T_RX_ABSOLUTE] = 0;
    this.interrupt(ICR_RXT0);
};

/** The transmit delay ended (TIDV, TADV, a flush): TXDW */
E1000.prototype.end_tx_delay = function()
{
    if(!this.deadlines[T_TX_PACKET] && !this.deadlines[T_TX_ABSOLUTE]) return;
    this.deadlines[T_TX_PACKET] = this.deadlines[T_TX_ABSOLUTE] = 0;
    this.interrupt(ICR_TXDW);
};

/**
 * The machine's timers run: deadlines that passed, the ring work that waits
 * @param {number} now
 * @return {number} milliseconds until it needs to run again
 */
E1000.prototype.timer = function(now)
{
    const d = this.deadlines;
    if(d[T_AUTONEG] && now >= d[T_AUTONEG])
    {
        d[T_AUTONEG] = 0;
        this.set_link(true);
        this.interrupt(ICR_LSC);
        this.drain_rx_fifo();
    }
    if(d[T_RX_PACKET] && now >= d[T_RX_PACKET] || d[T_RX_ABSOLUTE] && now >= d[T_RX_ABSOLUTE])
    {
        this.end_rx_delay();
    }
    if(d[T_TX_PACKET] && now >= d[T_TX_PACKET] || d[T_TX_ABSOLUTE] && now >= d[T_TX_ABSOLUTE])
    {
        this.end_tx_delay();
    }
    if(this.irq_held && now >= d[T_ITR])
    {
        this.update_irq();
    }
    if(this.tx_more)
    {
        this.transmit();
    }
    if(this.rx_fifo.length)
    {
        this.drain_rx_fifo();
    }

    if(this.tx_more) return 0;
    let next = 100;
    for(let i = 0; i < T_COUNT; i++)
    {
        if(d[i] && (i !== T_ITR || this.irq_held)) next = Math.min(next, Math.max(0, d[i] - now));
    }
    return next;
};

// DMA

/** Whether the card may use guest memory (bus mastering, also upstream) */
E1000.prototype.can_dma = function()
{
    return this.machine.is_bus_master();
};

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array} null where it is not memory
 */
E1000.prototype.dma_read = function(address, length)
{
    try
    {
        return this.machine.read_physical(address, length);
    }
    catch(e)
    {
        dbg_log("e1000: DMA read outside memory at " + h(address, 9) + " (" + e.message + ")", LOG_NET);
        return null;
    }
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 * @return {boolean} whether it was memory
 */
E1000.prototype.dma_write = function(bytes, address)
{
    try
    {
        this.machine.write_physical(bytes, address);
        return true;
    }
    catch(e)
    {
        dbg_log("e1000: DMA write outside memory at " + h(address, 9) + " (" + e.message + ")", LOG_NET);
        return false;
    }
};

/** Bus mastering or decode came back: work that waited for it */
E1000.prototype.resume_dma = function()
{
    if(!this.can_dma()) return;
    this.transmit();
    this.drain_rx_fifo();
};

/**
 * A ring's base address (16-byte aligned, 64 bits)
 * @param {number} low_register
 * @return {number}
 */
E1000.prototype.ring_base = function(low_register)
{
    return (this.regs[low_register + 4 >> 2] >>> 0) * 0x100000000 + ((this.regs[low_register >> 2] & ~0xF) >>> 0);
};

// transmit

/** Send what the ring holds between TDH and TDT (within a round's budget) */
E1000.prototype.transmit = function()
{
    this.tx_more = false;
    if(!(this.regs[TCTL >> 2] & TCTL_EN) || !this.can_dma()) return;
    const count = this.regs[TDLEN >> 2] >> 4;
    const start = this.regs[TDH >> 2];
    if(!count || start >= count)
    {
        if(start !== this.regs[TDT >> 2]) dbg_log("e1000: bad transmit ring: TDH " + start + ", TDLEN " + h(this.regs[TDLEN >> 2]), LOG_NET);
        return;
    }
    const base = this.ring_base(TDBAL);
    let causes = 0, descriptors = 0;
    this.tx_bytes = 0;
    while(this.regs[TDH >> 2] !== this.regs[TDT >> 2])
    {
        if(descriptors === TX_DESCRIPTOR_BUDGET || this.tx_bytes >= TX_BYTE_BUDGET)
        {
            this.tx_more = true;
            break;
        }
        const head = this.regs[TDH >> 2];
        const address = base + head * 16;
        const descriptor = this.dma_read(address, 16);
        if(!descriptor) break;
        this.process_tx_descriptor(descriptor);
        const lower = descriptor[8] | descriptor[9] << 8 | descriptor[10] << 16 | descriptor[11] << 24;
        if(lower & (TXD_RS | TXD_RPS))
        {
            // write back: done (DD), no collisions or underrun
            const upper = (descriptor[12] | TXD_STAT_DD) & ~0xE;
            this.dma_write(Uint8Array.of(upper), address + 12);
            causes |= ICR_TXDW;
            if(lower & TXD_IDE) this.tx_ide = true;
        }
        descriptors++;
        const next = head + 1 === count ? 0 : head + 1;
        this.regs[TDH >> 2] = next;
        if(next === start)
        {
            dbg_log("e1000: transmit ring wrapped (TDT " + this.regs[TDT >> 2] + " beyond the ring)", LOG_NET);
            break;
        }
    }
    if(this.regs[TDH >> 2] === this.regs[TDT >> 2]) causes |= ICR_TXQE;
    if(causes & ICR_TXDW && this.tx_ide)
    {
        // delayed (TIDV after the last one, TADV after the first)
        causes &= ~ICR_TXDW;
        this.tx_ide = false;
        const now = this.machine.now();
        const tidv = this.regs[TIDV >> 2] & 0xFFFF, tadv = this.regs[TADV >> 2] & 0xFFFF;
        if(!tidv)
        {
            causes |= ICR_TXDW;
        }
        else
        {
            this.deadlines[T_TX_PACKET] = now + tidv * DELAY_UNIT;
            if(tadv && !this.deadlines[T_TX_ABSOLUTE]) this.deadlines[T_TX_ABSOLUTE] = now + tadv * DELAY_UNIT;
        }
    }
    if(causes) this.interrupt(causes);
};

/**
 * One transmit descriptor: a context for offload, or a buffer of the frame
 * @param {!Uint8Array} d its 16 bytes
 */
E1000.prototype.process_tx_descriptor = function(d)
{
    const lower = d[8] | d[9] << 8 | d[10] << 16 | d[11] << 24;
    const type = lower & (TXD_DEXT | TXD_DTYP_D);
    let length = lower & 0xFFFF;

    if(type === TXD_DEXT)
    {
        // a context: TSE's for segmentation, the other for checksums
        const props = lower & TXD_TSE ? this.tx_tso_props : this.tx_props;
        props[P_IPCSS] = d[0];
        props[P_IPCSO] = d[1];
        props[P_IPCSE] = d[2] | d[3] << 8;
        props[P_TUCSS] = d[4];
        props[P_TUCSO] = d[5];
        props[P_TUCSE] = d[6] | d[7] << 8;
        props[P_PAYLEN] = lower & 0xFFFFF;
        props[P_HDRLEN] = d[13];
        props[P_MSS] = d[14] | d[15] << 8;
        props[P_IP] = lower & TXD_CMD_IP ? 1 : 0;
        props[P_TCP] = lower & TXD_CMD_TCP ? 1 : 0;
        if(lower & TXD_TSE) this.tx_tso_frames = 0;
        return;
    }
    if(type === (TXD_DEXT | TXD_DTYP_D))
    {
        // data: POPTS of a frame's first descriptor
        if(this.tx_size === 0) this.tx_sum_needed = d[13];
        this.tx_tse = !!(lower & TXD_TSE);
        length = lower & 0xFFFFF;
    }
    else
    {
        // legacy: CSO and CSS of the frame's last descriptor
        this.tx_tse = false;
        if(lower & TXD_EOP) this.tx_legacy_sum = lower & TXD_IC ? [d[10], d[13]] : null;
    }

    if(this.regs[CTRL >> 2] & CTRL_VME && lower & TXD_VLE && (this.tx_tse || lower & TXD_EOP))
    {
        this.tx_vlan_tag = d[14] | d[15] << 8;
    }

    let address = (d[4] | d[5] << 8 | d[6] << 16 | d[7] << 24) >>> 0;
    address = address * 0x100000000 + ((d[0] | d[1] << 8 | d[2] << 16 | d[3] << 24) >>> 0);

    if(this.tx_tse)
    {
        const props = this.tx_tso_props;
        const hdr_len = props[P_HDRLEN];
        const segment = hdr_len + props[P_MSS];
        while(length > 0 && this.tx_size < segment)
        {
            const bytes = Math.min(length, segment - this.tx_size, TX_BUFFER_SIZE - this.tx_size);
            if(!bytes) break;
            const data = this.dma_read(address, bytes);
            if(!data) break;
            this.tx_data.set(data, this.tx_size);
            const size = this.tx_size + bytes;
            if(size >= hdr_len && this.tx_size < hdr_len)
            {
                this.tx_header.set(this.tx_data.subarray(0, hdr_len));
            }
            this.tx_size = size;
            address += bytes;
            length -= bytes;
            if(size === segment)
            {
                this.transmit_segment();
                this.tx_data.set(this.tx_header.subarray(0, hdr_len));
                this.tx_size = hdr_len;
            }
        }
    }
    else
    {
        const bytes = Math.min(length, TX_BUFFER_SIZE - this.tx_size);
        const data = bytes ? this.dma_read(address, bytes) : null;
        if(data)
        {
            this.tx_data.set(data, this.tx_size);
            this.tx_size += bytes;
        }
    }

    if(!(lower & TXD_EOP)) return;
    if(!(this.tx_tse && this.tx_size < this.tx_tso_props[P_HDRLEN]))
    {
        this.transmit_segment();
    }
    this.tx_tso_frames = 0;
    this.tx_sum_needed = 0;
    this.tx_vlan_tag = -1;
    this.tx_size = 0;
    this.tx_tse = false;
    this.tx_legacy_sum = null;
};

/**
 * Send the frame gathered (or one TSO segment of it): headers of the
 * segment, checksums, the VLAN tag
 */
E1000.prototype.transmit_segment = function()
{
    const data = this.tx_data;
    const size = this.tx_size;
    const props = this.tx_tse ? this.tx_tso_props : this.tx_props;

    if(this.tx_tse)
    {
        const frames = this.tx_tso_frames;
        let css = props[P_IPCSS];
        if(props[P_IP])
        {
            // IPv4: total length, identification + the segment's number
            store16(data, css + 2, size - css);
            store16(data, css + 4, load16(data, css + 4) + frames);
        }
        else
        {
            // IPv6: payload length
            store16(data, css + 4, size - css - 40);
        }
        css = props[P_TUCSS];
        const length = size - css;
        if(props[P_TCP])
        {
            const sofar = frames * props[P_MSS];
            store32(data, css + 4, load32(data, css + 4) + sofar);
            if(props[P_PAYLEN] - sofar > props[P_MSS])
            {
                // not the last segment: no PSH, no FIN
                data[css + 13] &= ~9;
            }
            else if(frames)
            {
                this.count(TSCTC);
            }
        }
        else
        {
            store16(data, css + 4, length);
        }
        if(this.tx_sum_needed & POPTS_TXSM)
        {
            // the driver's pseudo header sum has no length: add the segment's
            const at = props[P_TUCSO];
            store16(data, at, checksum_fold(load16(data, at) + length));
        }
        this.tx_tso_frames++;
    }

    if(this.tx_sum_needed & POPTS_TXSM)
    {
        insert_checksum(data, size, props[P_TUCSO], props[P_TUCSS], props[P_TUCSE]);
    }
    if(this.tx_sum_needed & POPTS_IXSM)
    {
        insert_checksum(data, size, props[P_IPCSO], props[P_IPCSS], props[P_IPCSE]);
    }
    if(this.tx_legacy_sum)
    {
        insert_checksum(data, size, this.tx_legacy_sum[0], this.tx_legacy_sum[1], 0);
    }

    let frame;
    if(this.tx_vlan_tag >= 0)
    {
        frame = new Uint8Array(size + 4);
        frame.set(data.subarray(0, 12));
        store16(frame, 12, this.regs[VET >> 2] & 0xFFFF);
        store16(frame, 14, this.tx_vlan_tag);
        frame.set(data.subarray(12, size), 16);
    }
    else
    {
        frame = data.slice(0, size);
    }
    this.tx_bytes += frame.length;
    this.send_frame(frame);
};

/**
 * @param {!Uint8Array} frame
 */
E1000.prototype.send_frame = function(frame)
{
    const fcs_size = frame.length + 4;
    this.count(TPT);
    this.count(GPTC);
    this.count64(TOTL, fcs_size);
    this.count64(GOTCL, fcs_size);
    this.count_size(PTC_SIZES, fcs_size);
    if(is_broadcast(frame)) this.count(BPTC);
    else if(frame[0] & 1) this.count(MPTC);

    if(this.phy[MII_BMCR] & BMCR_LOOPBACK || (this.regs[RCTL >> 2] & RCTL_LBM) === 1 << 6)
    {
        this.receive(frame);
        return;
    }
    if(this.mac_in_state)
    {
        translate_mac_address(frame, this.mac_in_state, this.mac);
    }
    this.machine.send(frame);
};

/**
 * Store a checksum: bytes [css, cse] (cse 0: to the end) at sloc
 * @param {!Uint8Array} data
 * @param {number} size
 * @param {number} sloc
 * @param {number} css
 * @param {number} cse
 */
function insert_checksum(data, size, sloc, css, cse)
{
    let end = size;
    if(cse && cse < end) end = cse + 1;
    if(sloc < end - 1 && css < end)
    {
        store16(data, sloc, checksum_finish(checksum_add(data, css, end)));
    }
}

/** @param {!Uint8Array} frame */
function is_broadcast(frame)
{
    return frame[0] === 0xFF && frame[1] === 0xFF && frame[2] === 0xFF && frame[3] === 0xFF && frame[4] === 0xFF && frame[5] === 0xFF;
}

// statistics

/** @param {number} offset a counter: one more, up to its maximum */
E1000.prototype.count = function(offset)
{
    if(this.regs[offset >> 2] !== -1) this.regs[offset >> 2]++;
};

/**
 * @param {number} offset the low half of a 64-bit counter
 * @param {number} value
 */
E1000.prototype.count64 = function(offset, value)
{
    const low = (this.regs[offset >> 2] >>> 0) + value;
    const high = (this.regs[offset + 4 >> 2] >>> 0) + Math.floor(low / 0x100000000);
    if(high > 0xFFFFFFFF)
    {
        this.regs[offset >> 2] = this.regs[offset + 4 >> 2] = -1;
        return;
    }
    this.regs[offset >> 2] = low;
    this.regs[offset + 4 >> 2] = high;
};

/**
 * @param {!Array<number>} counters 64, 127, 255, 511, 1023, 1522 bytes
 * @param {number} size with the FCS
 */
E1000.prototype.count_size = function(counters, size)
{
    this.count(counters[size > 1023 ? 5 : size > 511 ? 4 : size > 255 ? 3 : size > 127 ? 2 : size > 64 ? 1 : 0]);
};

// receive

/** The receive buffers' size (RCTL.BSIZE, BSEX) */
E1000.prototype.rx_buffer_size = function()
{
    const rctl = this.regs[RCTL >> 2];
    const bsize = rctl >>> 16 & 3;
    if(rctl & RCTL_BSEX) return [2048, 16384, 8192, 4096][bsize];
    return [2048, 1024, 512, 256][bsize];
};

/**
 * A frame from the network
 * @param {!Uint8Array} frame without FCS
 * @return {boolean} whether the card took it
 */
E1000.prototype.receive = function(frame)
{
    const rctl = this.regs[RCTL >> 2];
    if(!(rctl & RCTL_EN) || !this.link_up()) return false;

    if(frame.length < MIN_FRAME)
    {
        const padded = new Uint8Array(MIN_FRAME);
        padded.set(frame);
        frame = padded;
    }
    if(frame.length > MAX_LONG_FRAME || frame.length > MAX_FRAME && !(rctl & RCTL_LPE))
    {
        if(!(rctl & RCTL_SBP))
        {
            this.count(ROC);
            return false;
        }
    }
    if(this.mac_in_state)
    {
        frame = new Uint8Array(frame);
        translate_mac_address(frame, this.mac, this.mac_in_state);
    }
    if(!this.accepts(frame)) return false;

    if(!this.rx_fifo.length && this.deliver(frame))
    {
        return true;
    }
    // no free descriptor (or no bus mastering): the frame waits in the FIFO
    this.count(RNBC);
    const fifo_size = (this.regs[PBA >> 2] & 0xFFFF) << 10;
    if(this.rx_fifo_bytes + frame.length > fifo_size)
    {
        this.count(MPC);
        this.interrupt(ICR_RXO);
        return false;
    }
    this.rx_fifo.push(new Uint8Array(frame));
    this.rx_fifo_bytes += frame.length;
    return true;
};

/** Frames from the FIFO into descriptors the guest has given since */
E1000.prototype.drain_rx_fifo = function()
{
    while(this.rx_fifo.length)
    {
        const rctl = this.regs[RCTL >> 2];
        if(!(rctl & RCTL_EN) || !this.deliver(this.rx_fifo[0])) return;
        this.rx_fifo_bytes -= this.rx_fifo.shift().length;
    }
};

/**
 * The receive filter: VLAN, broadcast, multicast, unicast addresses
 * @param {!Uint8Array} frame
 * @return {boolean}
 */
E1000.prototype.accepts = function(frame)
{
    const regs = this.regs;
    const rctl = regs[RCTL >> 2];
    if(this.vlan_frame(frame) && rctl & RCTL_VFE)
    {
        const vid = load16(frame, 14) & 0xFFF;
        if(!(regs[(VFTA >> 2) + (vid >> 5)] >>> (vid & 0x1F) & 1)) return false;
    }
    if(is_broadcast(frame))
    {
        if(rctl & RCTL_BAM) return true;
    }
    else if(frame[0] & 1)
    {
        if(rctl & RCTL_MPE) return true;
    }
    else if(rctl & RCTL_UPE)
    {
        return true;
    }
    const low = frame[0] | frame[1] << 8 | frame[2] << 16 | frame[3] << 24;
    const high = frame[4] | frame[5] << 8;
    for(let i = 0; i < 16; i++)
    {
        const rah = regs[(RA >> 2) + 2 * i + 1];
        if(rah & RAH_AV && regs[(RA >> 2) + 2 * i] === low && (rah & 0xFFFF) === high) return true;
    }
    // the multicast table: 12 bits of the address, at RCTL.MO's offset
    const shift = [4, 3, 2, 0][rctl >>> 12 & 3];
    const hash = (frame[5] << 8 | frame[4]) >> shift & 0xFFF;
    return !!(regs[(MTA >> 2) + (hash >> 5)] >>> (hash & 0x1F) & 1);
};

/**
 * @param {!Uint8Array} frame
 * @return {boolean}
 */
E1000.prototype.vlan_frame = function(frame)
{
    return frame.length >= 18 && load16(frame, 12) === (this.regs[VET >> 2] & 0xFFFF);
};

/**
 * Write a frame into the receive ring
 * @param {!Uint8Array} frame
 * @return {boolean} false when it does not fit (yet): too few descriptors, no bus mastering
 */
E1000.prototype.deliver = function(frame)
{
    if(!this.can_dma()) return false;
    const regs = this.regs;
    const rctl = regs[RCTL >> 2];
    const count = regs[RDLEN >> 2] >> 4;
    const head = regs[RDH >> 2], tail = regs[RDT >> 2];
    if(!count || head >= count) return false;
    const free = tail >= head ? tail - head : count - head + tail;

    // a VLAN tag goes into the descriptor (with CTRL.VME)
    let special = 0, status = 0;
    if(regs[CTRL >> 2] & CTRL_VME && this.vlan_frame(frame))
    {
        special = load16(frame, 14);
        status |= RXD_STAT_VP;
        const untagged = new Uint8Array(frame.length - 4);
        untagged.set(frame.subarray(0, 12));
        untagged.set(frame.subarray(16), 12);
        frame = untagged;
    }
    const size = frame.length;
    const fcs = rctl & RCTL_SECRC ? 0 : 4;
    const total = size + fcs;
    const buffer_size = this.rx_buffer_size();
    if(free * buffer_size < total) return false;

    let data = frame;
    if(fcs)
    {
        data = new Uint8Array(total);
        data.set(frame);
        const crc = ethernet_fcs(frame, 0, size);
        data[size] = crc;
        data[size + 1] = crc >>> 8;
        data[size + 2] = crc >>> 16;
        data[size + 3] = crc >>> 24;
    }

    // receive checksum offload
    const rxcsum = regs[RXCSUM >> 2];
    let errors = 0;
    if(rxcsum & (RXCSUM_IPOFL | RXCSUM_TUOFL))
    {
        const sums = check_checksums(frame, size);
        if(rxcsum & RXCSUM_IPOFL && sums.ip !== CHECKSUM_NONE)
        {
            status |= RXD_STAT_IPCS;
            if(sums.ip === CHECKSUM_BAD) errors |= RXD_ERR_IPE;
        }
        if(rxcsum & RXCSUM_TUOFL && sums.l4 !== CHECKSUM_NONE)
        {
            status |= RXD_STAT_TCPCS;
            if(sums.l4 === CHECKSUM_BAD) errors |= RXD_ERR_TCPE;
        }
    }
    if(!(status & (RXD_STAT_IPCS | RXD_STAT_TCPCS))) status |= RXD_STAT_IXSM;
    // the packet checksum (from RXCSUM.PCSS)
    const packet_sum = checksum_fold(checksum_add(frame, Math.min(rxcsum & 0xFF, size), size));

    const base = this.ring_base(RDBAL);
    let offset = 0, index = head;
    const descriptor = new Uint8Array(16);
    while(offset < total)
    {
        const address = base + index * 16;
        const old = this.dma_read(address, 16);
        if(!old) return false;
        const buffer = (old[4] | old[5] << 8 | old[6] << 16 | old[7] << 24) >>> 0;
        const buffer_address = buffer * 0x100000000 + ((old[0] | old[1] << 8 | old[2] << 16 | old[3] << 24) >>> 0);
        descriptor.set(old.subarray(0, 8));
        let length = 0;
        if(buffer_address)
        {
            length = Math.min(total - offset, buffer_size);
            this.dma_write(data.subarray(offset, offset + length), buffer_address);
            offset += length;
        }
        // (a descriptor without a buffer is skipped, as the manual says)
        const last = offset >= total;
        descriptor[8] = length;
        descriptor[9] = length >> 8;
        descriptor[10] = last ? packet_sum : 0;
        descriptor[11] = last ? packet_sum >> 8 : 0;
        descriptor[12] = status | RXD_STAT_DD | (last ? RXD_STAT_EOP : 0);
        descriptor[13] = last ? errors : 0;
        descriptor[14] = special;
        descriptor[15] = special >> 8;
        this.dma_write(descriptor, address);
        index = index + 1 === count ? 0 : index + 1;
        if(index === tail && !last) return false;
    }
    regs[RDH >> 2] = index;

    this.count(TPR);
    this.count(GPRC);
    this.count64(TORL, size + 4);
    this.count64(GORCL, size + 4);
    this.count_size(PRC_SIZES, size + 4);
    if(is_broadcast(frame)) this.count(BPRC);
    else if(frame[0] & 1) this.count(MPRC);

    let causes = 0;
    // few free descriptors left (RCTL.RDMTS: 1/2, 1/4, 1/8 of the ring)
    const left = tail >= index ? tail - index : count - index + tail;
    if(left * 16 <= regs[RDLEN >> 2] >> ((rctl >>> 8 & 3) + 1)) causes |= ICR_RXDMT0;
    const rdtr = regs[RDTR >> 2] & 0xFFFF;
    if(!rdtr)
    {
        causes |= ICR_RXT0;
    }
    else
    {
        // RXT0 after RDTR without a frame, at most RADV after the first
        const now = this.machine.now();
        this.deadlines[T_RX_PACKET] = now + rdtr * DELAY_UNIT;
        const radv = regs[RADV >> 2] & 0xFFFF;
        if(radv && !this.deadlines[T_RX_ABSOLUTE]) this.deadlines[T_RX_ABSOLUTE] = now + radv * DELAY_UNIT;
        this.machine.wake();
    }
    if(causes) this.interrupt(causes);
    return true;
};

// snapshots

E1000.prototype.get_state = function()
{
    return [
        this.regs,
        this.phy,
        this.eeprom,
        new Int32Array([this.eecd_bits, this.eecd_in, this.eecd_in_count, this.eecd_out, +this.eecd_reading, this.io_address]),
        this.tx_data.slice(0, this.tx_size),
        this.tx_header,
        this.tx_props,
        this.tx_tso_props,
        new Int32Array([this.tx_sum_needed, this.tx_vlan_tag, +this.tx_tse, this.tx_tso_frames, +this.tx_more, +this.tx_ide,
            this.tx_legacy_sum ? 1 : 0, this.tx_legacy_sum ? this.tx_legacy_sum[0] : 0, this.tx_legacy_sum ? this.tx_legacy_sum[1] : 0]),
        this.rx_fifo,
        this.deadlines,
        new Int32Array([+this.irq_level, +this.irq_held, this.bar0]),
        this.mac,
    ];
};

E1000.prototype.set_state = function(state)
{
    this.regs.set(state[0]);
    this.phy.set(state[1]);
    this.eeprom.set(state[2]);
    [this.eecd_bits, this.eecd_in, this.eecd_in_count, this.eecd_out] = state[3];
    this.eecd_reading = !!state[3][4];
    this.io_address = state[3][5];
    this.tx_data.set(state[4]);
    this.tx_size = state[4].length;
    this.tx_header.set(state[5]);
    this.tx_props.set(state[6]);
    this.tx_tso_props.set(state[7]);
    const tx = state[8];
    this.tx_sum_needed = tx[0];
    this.tx_vlan_tag = tx[1];
    this.tx_tse = !!tx[2];
    this.tx_tso_frames = tx[3];
    this.tx_more = !!tx[4];
    this.tx_ide = !!tx[5];
    this.tx_legacy_sum = tx[6] ? [tx[7], tx[8]] : null;
    this.rx_fifo = Array.from(state[9], frame => new Uint8Array(frame));
    this.rx_fifo_bytes = this.rx_fifo.reduce((sum, frame) => sum + frame.length, 0);
    this.deadlines.set(state[10]);
    this.irq_level = !!state[11][0];
    this.irq_held = !!state[11][1];
    this.bar0 = state[11][2] >>> 0;

    const saved_mac = new Uint8Array(state[12]);
    this.mac_in_state = null;
    if(this.preserve_mac_from_state_image)
    {
        this.mac = saved_mac;
    }
    else if(this.mac_address_translation)
    {
        // the guest keeps the address it has; frames are translated to ours
        this.mac_in_state = this.guest_mac();
        dbg_log("e1000: address translation, guest " + format_mac(this.mac_in_state) + ", card " + format_mac(this.mac), LOG_NET);
    }
    else
    {
        // the card keeps its own address: in the EEPROM and receive address
        // 0, unless the guest gave it another one
        const guest = this.guest_mac();
        const saved_eeprom = this.eeprom_mac();
        this.write_eeprom_address();
        if(format_mac(guest) === format_mac(saved_eeprom))
        {
            const e = this.eeprom;
            this.regs[RA >> 2] = e[0] | e[1] << 16;
            this.regs[RA + 4 >> 2] = this.regs[RA + 4 >> 2] & ~0xFFFF | e[2];
        }
    }
    if(!this.mac_in_state && this.regs[RA + 4 >> 2] & RAH_AV)
    {
        this.mac = this.guest_mac();
    }
    this.machine.set_mac(format_mac(this.mac));

    if(this.irq_level) this.machine.raise_irq();
    else this.machine.lower_irq();
    this.update_decode();
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/net_adapters/e1000/plugin.js                                                         0000644 0000000 0000000 00000001244 00000000000 015506  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // net_device.type "e1000" -- an Intel 82540EM (PRO/1000 MT Desktop), the card
// Windows Vista to 11 and Linux have drivers for. Built into
// build/v86-e1000.js; from the source tree, src/device_plugin.js imports this
// file directly.

import { E1000 } from "./e1000.js";
import { register_net_adapter } from "../machine.js";

register_net_adapter({
    "name": "e1000",
    "create": (handle, options) =>
    {
        const card = new E1000(handle, options);
        return {
            "card": card,
            "reset": () => card.reset(),
            "get_state": () => card.get_state(),
            "set_state": state => card.set_state(state),
        };
    },
});
                                                                                                                                                                                                                                                                                                                                                            source/v64/src/net_adapters/machine.js                                                              0000644 0000000 0000000 00000003102 00000000000 015062  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A network card plugin's view of the machine (net_device.type "e1000"): the
// device handle of src/device_machine.js plus the card's network, the
// net<id>-send/-receive/-mac messages of the bus (src/cpu.js,
// create_net_plugin). Built into each card's plugin file.

import { DeviceMachine, register_device_plugin } from "../device_machine.js";

/**
 * Make a card known to v86 (its plugin file calls this when it loads)
 * @param {!Object} descriptor { "name", "create": function(handle, options) }
 */
export function register_net_adapter(descriptor)
{
    register_device_plugin("V86NetAdapters", descriptor);
}

/**
 * @constructor
 * @extends {DeviceMachine}
 * @param {!Object} handle
 */
export function NetMachine(handle)
{
    DeviceMachine.call(this, handle);

    /** @const @type {!Object} */
    this.net = handle["net"];

    /** @const @type {number} the network (net<id>) */
    this.net_id = this.net["id"];
}

NetMachine.prototype = Object.create(DeviceMachine.prototype);

/**
 * A frame to the network (without its FCS); the card does not keep it
 * @param {!Uint8Array} frame
 */
NetMachine.prototype.send = function(frame)
{
    this.net["send"](frame);
};

/**
 * The card's address, for the backend (its DHCP, ARP)
 * @param {string} mac "00:22:15:01:02:03"
 */
NetMachine.prototype.set_mac = function(mac)
{
    this.net["set_mac"](mac);
};

/**
 * Frames from the network: `handler` returns whether the card took the frame
 * @param {function(!Uint8Array):boolean} handler
 */
NetMachine.prototype.on_receive = function(handler)
{
    this.net["on_receive"](handler);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/net_adapters/ne2k/ne2k.js                                                            0000644 0000000 0000000 00000077711 00000000000 015175  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // net_device.type "ne2k" (the default) -- an NE2000-compatible card, the
// RTL8029 on PCI: the card DOS, Windows 9x to XP and Linux have drivers for.
// A plugin since M1 (docs/modern-pc-devices-plan.md): its machine is a
// NetMachine (src/net_adapters/machine.js); its state is the one the core's
// NE2000 had, field for field, so that snapshots from before read as they are.

import { LOG_NET } from "../../const.js";
import { h, hex_dump } from "../../lib.js";
import { dbg_assert, dbg_log } from "../../log.js";
import { format_mac, random_mac, translate_mac_address } from "../../mac_address.js";

// For Types Only
import { NetMachine } from "../machine.js";

// http://www.ethernut.de/pdf/8019asds.pdf

const NE2K_LOG_VERBOSE = false;
const NE2K_LOG_PACKETS = false;

const E8390_CMD = 0x00; /* The command register (for all pages) */

/* Page 0 register offsets. */
const EN0_CLDALO = 0x01; /* Low byte of current local dma addr RD */
const EN0_STARTPG = 0x01; /* Starting page of ring bfr WR */
const EN0_CLDAHI = 0x02; /* High byte of current local dma addr RD */
const EN0_STOPPG = 0x02; /* Ending page +1 of ring bfr WR */
const EN0_BOUNDARY = 0x03; /* Boundary page of ring bfr RD WR */
const EN0_TSR = 0x04; /* Transmit status reg RD */
const EN0_TPSR = 0x04; /* Transmit starting page WR */
const EN0_NCR = 0x05; /* Number of collision reg RD */
const EN0_TCNTLO = 0x05; /* Low byte of tx byte count WR */
const EN0_FIFO = 0x06; /* FIFO RD */
const EN0_TCNTHI = 0x06; /* High byte of tx byte count WR */
const EN0_ISR = 0x07; /* Interrupt status reg RD WR */
const EN0_CRDALO = 0x08; /* low byte of current remote dma address RD */
const EN0_RSARLO = 0x08; /* Remote start address reg 0 */
const EN0_CRDAHI = 0x09; /* high byte, current remote dma address RD */
const EN0_RSARHI = 0x09; /* Remote start address reg 1 */
const EN0_RCNTLO = 0x0a; /* Remote byte count reg WR */
const EN0_RCNTHI = 0x0b; /* Remote byte count reg WR */
const EN0_RSR = 0x0c; /* rx status reg RD */
const EN0_RXCR = 0x0c; /* RX configuration reg WR */
const EN0_TXCR = 0x0d; /* TX configuration reg WR */
const EN0_COUNTER0 = 0x0d; /* Rcv alignment error counter RD */
const EN0_DCFG = 0x0e; /* Data configuration reg WR */
const EN0_COUNTER1 = 0x0e; /* Rcv CRC error counter RD */
const EN0_IMR = 0x0f; /* Interrupt mask reg WR */
const EN0_COUNTER2 = 0x0f; /* Rcv missed frame error counter RD */

const NE_DATAPORT = 0x10; /* NatSemi-defined port window offset. */
const NE_RESET = 0x1f; /* Issue a read to reset, a write to clear. */

/* Bits in EN0_ISR - Interrupt status register */
const ENISR_RX = 0x01; /* Receiver, no error */
const ENISR_TX = 0x02; /* Transmitter, no error */
const ENISR_RX_ERR = 0x04; /* Receiver, with error */
const ENISR_TX_ERR = 0x08; /* Transmitter, with error */
const ENISR_OVER = 0x10; /* Receiver overwrote the ring */
const ENISR_COUNTERS = 0x20; /* Counters need emptying */
const ENISR_RDC = 0x40; /* remote dma complete */
const ENISR_RESET = 0x80; /* Reset completed */
const ENISR_ALL = 0x3f; /* Interrupts we will enable */

const ENRSR_RXOK = 0x01; /* Received a good packet */

const START_PAGE = 0x40;
const START_RX_PAGE = 0x40 + 12;
const STOP_PAGE = 0x80;


function dump_packet(packet, prefix)
{
    const ethertype = packet[12] << 8 | packet[13] << 0;
    if(ethertype === 0x0800)
    {
        const ipv4_packet = packet.subarray(14);
        const ipv4_len = ipv4_packet[2] << 8 | ipv4_packet[3];
        const ipv4_proto = ipv4_packet[9];
        if(ipv4_proto === 0x11)
        {
            const udp_packet = ipv4_packet.subarray(5 * 4);
            const source_port = udp_packet[0] << 8 | udp_packet[1];
            const destination_port = udp_packet[2] << 8 | udp_packet[3];
            const checksum = udp_packet[6] << 8 | udp_packet[7];

            if(source_port === 67 || destination_port === 67)
            {
                const dhcp_packet = udp_packet.subarray(8);
                const dhcp_chaddr = dhcp_packet.subarray(28, 28+6);
                dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9]) + " udp.srcport=" + source_port + " udp.dstport=" + destination_port + " udp.chksum=" + h(checksum, 4) + " dhcp.chaddr=" + format_mac(dhcp_chaddr));
            }
            else
            {
                dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9]) + " udp.srcport=" + source_port + " udp.dstport=" + destination_port + " udp.chksum=" + h(checksum, 4));
            }
        }
        else if(ipv4_proto === 0x01)
        {
        }
        else
        {
            dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " ipv4.len=" + ipv4_len + " ipv4.proto=" + h(packet[14 + 9]));
        }
    }
    else
    {
        const arp_packet = packet.subarray(14);
        dbg_log(prefix + " len=" + packet.length + " ethertype=" + h(ethertype) + " arp");
    }
    dbg_log(hex_dump(packet));
}

/**
 * @constructor
 * @param {NetMachine} machine its PCI function where the machine puts it (its
 *     usual slot, or behind a root port), net<id> of the network bus
 * @param {!Object} options "preserve_mac_from_state_image",
 *     "mac_address_translation"
 */
export function Ne2k(machine, options)
{
    /** @const @type {NetMachine} */
    this.machine = machine;

    this.id = machine.net_id;
    this.preserve_mac_from_state_image = !!options["preserve_mac_from_state_image"];
    this.mac_address_translation = !!options["mac_address_translation"];

    machine.on_receive(data => this.receive(data));

    const pci_id = machine.pci_id();
    // (behind a bridge, the I/O BAR starts above the legacy ports, which
    // bridges do not forward)
    this.port = (pci_id >= 0x100 ? 0x1300 : 0x300) + 0x100 * this.id;

    this.name = "ne2k";

    const use_pci = true;

    if(use_pci)
    {
        this.pci_space = [
            0xec, 0x10, 0x29, 0x80, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,
            this.port & 0xFF | 1, this.port >> 8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf4, 0x1a, 0x00, 0x11,
            0x00, 0x00, 0xb8, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
        ];
        this.pci_id = pci_id;
        this.pci_bars = [
            {
                size: 32,
            },
        ];
    }

    this.isr = 0;
    this.imr = 0; // interrupt mask register

    this.cr = 1;

    this.dcfg = 0;

    this.rcnt = 0;

    this.tcnt = 0;
    this.tpsr = 0;
    this.memory = new Uint8Array(256 * 0x80);

    this.rxcr = 0;
    this.txcr = 0;
    this.tsr = 1;

    // mac address
    this.mac = random_mac();

    machine.set_mac(format_mac(this.mac));

    // multicast addresses
    this.mar = Uint8Array.of(0xFF, 0xFF, 0xFF, 0xFF,  0xFF, 0xFF, 0xFF, 0xFF);

    // Used for mac address translation
    // The mac the OS thinks it has
    this.mac_address_in_state = null;

    for(var i = 0; i < 6; i++)
    {
        this.memory[i << 1] = this.memory[i << 1 | 1] = this.mac[i];
    }

    // the PROM signature of 0x57, 0x57 is also doubled
    // resulting in setting the 4 bytes at the end, 28, 29, 30 and 31 to 0x57
    this.memory[14 << 1] = this.memory[14 << 1 | 1] = 0x57;
    this.memory[15 << 1] = this.memory[15 << 1 | 1] = 0x57;

    dbg_log("Mac: " + format_mac(this.mac), LOG_NET);

    this.rsar = 0;

    this.pstart = START_PAGE;
    this.pstop = STOP_PAGE;

    this.curpg = START_RX_PAGE;
    this.boundary = START_RX_PAGE;

    // (the machine registers the ports as the I/O bus would, `this` bound)
    var io = machine;

    io.register_read(this.port | E8390_CMD, this, function()
    {
        dbg_log("Read cmd", LOG_NET);
        return this.cr;
    }, function()
    {
        dbg_log("Read16 cmd", LOG_NET);
        return this.cr;
    }
    );

    io.register_write(this.port | E8390_CMD, this, function(data_byte)
    {
        this.cr = data_byte;
        dbg_log("Write command: " + h(data_byte, 2) + " newpg=" + (this.cr >> 6) + " txcr=" + h(this.txcr, 2), LOG_NET);

        if(this.cr & 1)
        {
            return;
        }

        if((data_byte & 0x18) && this.rcnt === 0)
        {
            this.do_interrupt(ENISR_RDC);
        }

        if(data_byte & 4)
        {
            var start = this.tpsr << 8;
            var data = this.memory.subarray(start, start + this.tcnt);

            if(NE2K_LOG_PACKETS)
            {
                dump_packet(data, "send");
            }

            if(this.mac_address_in_state)
            {
                data = new Uint8Array(data); // make a copy
                translate_mac_address(data, this.mac_address_in_state, this.mac);
            }

            this.machine.send(data);
            this.cr &= ~4;
            this.do_interrupt(ENISR_TX);

            dbg_log("Command: Transfer. length=" + h(data.byteLength), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_COUNTER0, this, function()
    {
        var pg = this.get_page();
        if(pg === 1)
        {
            dbg_log("Read mar5", LOG_NET);
            return this.mar[5];
        }
        else
        {
            dbg_log("Read counter0 pg=" + pg, LOG_NET);
            return 0;
        }
    });

    io.register_read(this.port | EN0_COUNTER1, this, function()
    {
        var pg = this.get_page();
        if(pg === 1)
        {
            dbg_log("Read mar6", LOG_NET);
            return this.mar[6];
        }
        else
        {
            dbg_log("Read8 counter1 pg=" + pg, LOG_NET);
            return 0;
        }
    }, function()
    {
        dbg_log("Read16 counter1 pg=" + this.get_page(), LOG_NET);
        // openbsd
        return 0;
    }
    );

    io.register_read(this.port | EN0_COUNTER2, this, function()
    {
        var pg = this.get_page();
        if(pg === 1)
        {
            dbg_log("Read mar7", LOG_NET);
            return this.mar[7];
        }
        else
        {
            dbg_log("Read counter2 pg=" + pg, LOG_NET);
            return 0;
        }
    });

    io.register_read(this.port | NE_RESET, this, function()
    {
        var pg = this.get_page();
        dbg_log("Read reset", LOG_NET);
        this.do_interrupt(ENISR_RESET);
        return 0;
    });

    io.register_write(this.port | NE_RESET, this, function(data_byte)
    {
        var pg = this.get_page();
        dbg_log("Write reset: " + h(data_byte, 2), LOG_NET);
        //this.isr &= ~ENISR_RESET;
    });

    io.register_read(this.port | EN0_STARTPG, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            return this.pstart;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/01 (mac[0])", LOG_NET);
            return this.mac[0];
        }
        else if(pg === 2)
        {
            return this.pstart;
        }
        else
        {
            dbg_log("Read pg" + pg + "/01");
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_STARTPG, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("start page: " + h(data_byte, 2), LOG_NET);
            this.pstart = data_byte;
        }
        else if(pg === 1)
        {
            dbg_log("mac[0] = " + h(data_byte), LOG_NET);
            this.mac[0] = data_byte;
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Write pg3/01 (9346CR): " + h(data_byte), LOG_NET);
        }
        else
        {
            dbg_log("Write pg" + pg + "/01: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });


    io.register_read(this.port | EN0_STOPPG, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            return this.pstop;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/02 (mac[1])", LOG_NET);
            return this.mac[1];
        }
        else if(pg === 2)
        {
            return this.pstop;
        }
        else
        {
            dbg_log("Read pg" + pg + "/02", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_STOPPG, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("stop page: " + h(data_byte, 2), LOG_NET);
            if(data_byte > (this.memory.length >> 8))
            {
                data_byte = this.memory.length >> 8;
                dbg_log("XXX: Adjusting stop page to " + h(data_byte), LOG_NET);
            }
            this.pstop = data_byte;
        }
        else if(pg === 1)
        {
            dbg_log("mac[1] = " + h(data_byte), LOG_NET);
            this.mac[1] = data_byte;
        }
        else
        {
            dbg_log("Write pg" + pg + "/02: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });

    io.register_read(this.port | EN0_ISR, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read isr: " + h(this.isr, 2), LOG_NET);
            return this.isr;
        }
        else if(pg === 1)
        {
            dbg_log("Read curpg: " + h(this.curpg, 2), LOG_NET);
            return this.curpg;
        }
        else
        {
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_ISR, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            // acknowledge interrupts where bit is set
            dbg_log("Write isr: " + h(data_byte, 2), LOG_NET);
            this.isr &= ~data_byte;
            this.update_irq();
        }
        else if(pg === 1)
        {
            dbg_log("Write curpg: " + h(data_byte, 2), LOG_NET);
            this.curpg = data_byte;
        }
        else
        {
            dbg_assert(false);
        }
    });

    io.register_write(this.port | EN0_TXCR, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            this.txcr = data_byte;
            dbg_log("Write tx config: " + h(data_byte, 2), LOG_NET);
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0d " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_write(this.port | EN0_DCFG, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write data configuration: " + h(data_byte, 2), LOG_NET);
            this.dcfg = data_byte;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0e " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_RCNTLO, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read pg0/0a", LOG_NET);
            return 0x50;
        }
        else if(pg === 1)
        {
            dbg_log("Read mar2", LOG_NET);
            return this.mar[2];
        }
        else
        {
            dbg_assert(false, "TODO");
            return 0;
        }
    });

    io.register_write(this.port | EN0_RCNTLO, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write remote byte count low: " + h(data_byte, 2), LOG_NET);
            this.rcnt = this.rcnt & 0xFF00 | data_byte & 0xFF;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0a " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_RCNTHI, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read pg0/0b", LOG_NET);
            return 0x43;
        }
        else if(pg === 1)
        {
            dbg_log("Read mar3", LOG_NET);
            return this.mar[3];
        }
        else
        {
            dbg_assert(false, "TODO");
            return 0;
        }
    });

    io.register_write(this.port | EN0_RCNTHI, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write remote byte count high: " + h(data_byte, 2), LOG_NET);
            this.rcnt = this.rcnt & 0xFF | data_byte << 8 & 0xFF00;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0b " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_RSARLO, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read remote start address low", LOG_NET);
            return this.rsar & 0xFF;
        }
        else if(pg === 1)
        {
            dbg_log("Read mar0", LOG_NET);
            return this.mar[0];
        }
        else
        {
            dbg_log("Unimplemented: Read pg" + pg + "/08", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_RSARLO, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write remote start address low: " + h(data_byte, 2), LOG_NET);
            this.rsar = this.rsar & 0xFF00 | data_byte & 0xFF;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/08 " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_RSARHI, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read remote start address high", LOG_NET);
            return this.rsar >> 8 & 0xFF;
        }
        else if(pg === 1)
        {
            dbg_log("Read mar1", LOG_NET);
            return this.mar[1];
        }
        else
        {
            dbg_log("Unimplemented: Read pg" + pg + "/09", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_RSARHI, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write remote start address low: " + h(data_byte, 2), LOG_NET);
            this.rsar = this.rsar & 0xFF | data_byte << 8 & 0xFF00;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/09 " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_write(this.port | EN0_IMR, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write interrupt mask register: " + h(data_byte, 2) + " isr=" + h(this.isr, 2), LOG_NET);
            this.imr = data_byte;
            this.update_irq();
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0f " + h(data_byte, 2), LOG_NET);
        }
    });

    io.register_read(this.port | EN0_BOUNDARY, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Read boundary: " + h(this.boundary, 2), LOG_NET);
            return this.boundary;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/03 (mac[2])", LOG_NET);
            return this.mac[2];
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Read pg3/03 (CONFIG0)", LOG_NET);
            return 0;
        }
        else
        {
            dbg_log("Read pg" + pg + "/03", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_BOUNDARY, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write boundary: " + h(data_byte, 2), LOG_NET);
            this.boundary = data_byte;
        }
        else if(pg === 1)
        {
            dbg_log("mac[2] = " + h(data_byte), LOG_NET);
            this.mac[2] = data_byte;
        }
        else
        {
            dbg_log("Write pg" + pg + "/03: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });

    io.register_read(this.port | EN0_TSR, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            return this.tsr;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/04 (mac[3])", LOG_NET);
            return this.mac[3];
        }
        else
        {
            dbg_log("Read pg" + pg + "/04", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_TPSR, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write tpsr: " + h(data_byte, 2), LOG_NET);
            this.tpsr = data_byte;
        }
        else if(pg === 1)
        {
            dbg_log("mac[3] = " + h(data_byte), LOG_NET);
            this.mac[3] = data_byte;
        }
        else
        {
            dbg_log("Write pg" + pg + "/04: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });

    io.register_read(this.port | EN0_TCNTLO, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Unimplemented: Read pg0/05 (NCR: Number of Collisions Register)", LOG_NET);
            return 0;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/05 (mac[4])", LOG_NET);
            return this.mac[4];
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Read pg3/05 (CONFIG2)", LOG_NET);
            return 0;
        }
        else
        {
            dbg_log("Read pg" + pg + "/05", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_TCNTLO, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write tcnt low: " + h(data_byte, 2), LOG_NET);
            this.tcnt = this.tcnt & ~0xFF | data_byte;
        }
        else if(pg === 1)
        {
            dbg_log("mac[4] = " + h(data_byte), LOG_NET);
            this.mac[4] = data_byte;
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Write pg3/05 (CONFIG2): " + h(data_byte), LOG_NET);
        }
        else
        {
            dbg_log("Write pg" + pg + "/05: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });

    io.register_read(this.port | EN0_TCNTHI, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_assert(false, "TODO");
            return 0;
        }
        else if(pg === 1)
        {
            dbg_log("Read pg1/06 (mac[5])", LOG_NET);
            return this.mac[5];
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Read pg3/06 (CONFIG3)", LOG_NET);
            return 0;
        }
        else
        {
            dbg_log("Read pg" + pg + "/06", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_TCNTHI, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("Write tcnt high: " + h(data_byte, 2), LOG_NET);
            this.tcnt = this.tcnt & 0xFF | data_byte << 8;
        }
        else if(pg === 1)
        {
            dbg_log("mac[5] = " + h(data_byte), LOG_NET);
            this.mac[5] = data_byte;
        }
        else if(pg === 3)
        {
            dbg_log("Unimplemented: Write pg3/06 (CONFIG3): " + h(data_byte), LOG_NET);
        }
        else
        {
            dbg_log("Write pg" + pg + "/06: " + h(data_byte), LOG_NET);
            dbg_assert(false);
        }
    });

    io.register_read(this.port | EN0_RSR, this, function()
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            return 1 | 1 << 3; // receive status ok
        }
        else if(pg === 1)
        {
            dbg_log("Read mar4", LOG_NET);
            return this.mar[4];
        }
        else
        {
            dbg_log("Unimplemented: Read pg" + pg + "/0c", LOG_NET);
            dbg_assert(false);
            return 0;
        }
    });

    io.register_write(this.port | EN0_RXCR, this, function(data_byte)
    {
        var pg = this.get_page();
        if(pg === 0)
        {
            dbg_log("RX configuration reg write: " + h(data_byte, 2), LOG_NET);
            this.rxcr = data_byte;
        }
        else
        {
            dbg_log("Unimplemented: Write pg" + pg + "/0c: " + h(data_byte), LOG_NET);
        }
    });

    io.register_read(this.port | NE_DATAPORT | 0, this,
            this.data_port_read8,
            this.data_port_read16,
            this.data_port_read32);
    io.register_write(this.port | NE_DATAPORT | 0, this,
            this.data_port_write16,
            this.data_port_write16,
            this.data_port_write32);

    if(use_pci)
    {
        machine.register_pci({ pci_space: this.pci_space, pci_bars: this.pci_bars });
    }
}

Ne2k.prototype.get_state = function()
{
    var state = [];

    state[0] = this.isr;
    state[1] = this.imr;
    state[2] = this.cr;
    state[3] = this.dcfg;
    state[4] = this.rcnt;
    state[5] = this.tcnt;
    state[6] = this.tpsr;
    state[7] = this.rsar;
    state[8] = this.pstart;
    state[9] = this.curpg;
    state[10] = this.boundary;
    state[11] = this.pstop;
    state[12] = this.rxcr;
    state[13] = this.txcr;
    state[14] = this.tsr;
    state[15] = this.mac;
    state[16] = this.memory;

    return state;
};

Ne2k.prototype.set_state = function(state)
{
    this.isr = state[0];
    this.imr = state[1];
    this.cr = state[2];
    this.dcfg = state[3];
    this.rcnt = state[4];
    this.tcnt = state[5];
    this.tpsr = state[6];
    this.rsar = state[7];
    this.pstart = state[8];
    this.curpg = state[9];
    this.boundary = state[10];
    this.pstop = state[11];
    this.rxcr = state[12];
    this.txcr = state[13];
    this.tsr = state[14];

    if(this.preserve_mac_from_state_image)
    {
        this.mac = state[15];
        this.memory = state[16];
    }
    else if(this.mac_address_translation)
    {
        this.mac_address_in_state = state[15];
        this.memory = state[16];

        dbg_log("Using mac address translation" +
            " guest_os_mac=" + format_mac(this.mac_address_in_state) +
            " real_mac=" + format_mac(this.mac), LOG_NET);
    }
    this.machine.set_mac(format_mac(this.mac));
};

Ne2k.prototype.do_interrupt = function(ir_mask)
{
    dbg_log("Do interrupt " + h(ir_mask, 2), LOG_NET);
    this.isr |= ir_mask;
    this.update_irq();
};

Ne2k.prototype.update_irq = function()
{
    if(this.imr & this.isr)
    {
        this.machine.raise_irq();
    }
    else
    {
        this.machine.lower_irq();
    }
};

Ne2k.prototype.data_port_write = function(data_byte)
{
    if(NE2K_LOG_VERBOSE)
    {
        dbg_log("Write data port: data=" + h(data_byte & 0xFF, 2) +
                                " rsar=" + h(this.rsar, 4) +
                                " rcnt=" + h(this.rcnt, 4), LOG_NET);
    }

    if(this.rsar <= 0x10 || this.rsar >= (START_PAGE << 8) && this.rsar < (STOP_PAGE << 8))
    {
        this.memory[this.rsar] = data_byte;
    }

    this.rsar++;
    this.rcnt--;

    if(this.rsar >= (this.pstop << 8))
    {
        this.rsar += (this.pstart - this.pstop) << 8;
    }

    if(this.rcnt === 0)
    {
        this.do_interrupt(ENISR_RDC);
    }
};

Ne2k.prototype.data_port_write16 = function(data)
{
    this.data_port_write(data);

    if(this.dcfg & 1)
    {
        this.data_port_write(data >> 8);
    }
};

Ne2k.prototype.data_port_write32 = function(data)
{
    this.data_port_write(data);
    this.data_port_write(data >> 8);
    this.data_port_write(data >> 16);
    this.data_port_write(data >> 24);
};

Ne2k.prototype.data_port_read = function()
{
    let data = 0;

    if(this.rsar < (STOP_PAGE << 8))
    {
        data = this.memory[this.rsar];
    }

    if(NE2K_LOG_VERBOSE)
    {
        dbg_log("Read data port: data=" + h(data, 2) +
                               " rsar=" + h(this.rsar, 4) +
                               " rcnt=" + h(this.rcnt, 4), LOG_NET);
    }

    this.rsar++;
    this.rcnt--;

    if(this.rsar >= (this.pstop << 8))
    {
        this.rsar += (this.pstart - this.pstop) << 8;
    }

    if(this.rcnt === 0)
    {
        this.do_interrupt(ENISR_RDC);
    }

    return data;
};

Ne2k.prototype.data_port_read8 = function()
{
    return this.data_port_read16() & 0xFF;
};

Ne2k.prototype.data_port_read16 = function()
{
    if(this.dcfg & 1)
    {
        return this.data_port_read() | this.data_port_read() << 8;
    }
    else
    {
        return this.data_port_read();
    }
};

Ne2k.prototype.data_port_read32 = function()
{
    return this.data_port_read() | this.data_port_read() << 8 |
            this.data_port_read() << 16 | this.data_port_read() << 24;
};

/**
 * A frame from the network: whether the card took it (it does while started,
 * also when its filters drop it, as the core's NE2000 counted it)
 * @param {!Uint8Array} data
 * @return {boolean}
 */
Ne2k.prototype.receive = function(data)
{
    if(this.cr & 1)
    {
        // stop bit set
        return false;
    }

    if(NE2K_LOG_PACKETS)
    {
        dump_packet(data, "receive");
    }

    this.receive_frame(data);
    return true;
};

/** @param {!Uint8Array} data */
Ne2k.prototype.receive_frame = function(data)
{
    if(this.rxcr & 0x10)
    {
        // promiscuous
    }
    else if((this.rxcr & 4) &&
            data[0] === 0xFF && data[1] === 0xFF && data[2] === 0xFF &&
            data[3] === 0xFF && data[4] === 0xFF && data[5] === 0xFF)
    {
        // broadcast
    }
    else if((this.rxcr & 8) && (data[0] & 1) === 1)
    {
        // multicast
        // XXX
        return;
    }
    else if(data[0] === this.mac[0] && data[1] === this.mac[1] &&
            data[2] === this.mac[2] && data[3] === this.mac[3] &&
            data[4] === this.mac[4] && data[5] === this.mac[5])
    {
    }
    else
    {
        return;
    }

    if(this.mac_address_in_state)
    {
        data = new Uint8Array(data); // make a copy
        translate_mac_address(data, this.mac, this.mac_address_in_state);
    }

    var packet_length = Math.max(60, data.length);

    var offset = this.curpg << 8;
    var total_length = packet_length + 4;
    var data_start = offset + 4;
    var next = this.curpg + 1 + (total_length >> 8);

    var end = offset + total_length;

    const needed = 1 + (total_length >> 8);

    // boundary == curpg interpreted as ringbuffer empty
    const available = this.boundary > this.curpg ?
        this.boundary - this.curpg :
        this.pstop - this.curpg + this.boundary - this.pstart;

    if(available < needed &&
        this.boundary !== 0 // XXX: ReactOS sets this to 0 initially and never updates it unless it receives a packet
    )
    {
        dbg_log("Buffer full, dropping packet pstart=" + h(this.pstart) + " pstop=" + h(this.pstop) +
            " curpg=" + h(this.curpg) + " needed=" + h(needed) + " boundary=" + h(this.boundary) + " available=" + h(available), LOG_NET);
        return;
    }

    if(end > (this.pstop << 8))
    {
        // Shouldn't happen because at this size it can't cross a page,
        // so we can skip filling with zeroes
        dbg_assert(data.length >= 60);

        var cut = (this.pstop << 8) - data_start;
        dbg_assert(cut >= 0);

        this.memory.set(data.subarray(0, cut), data_start);
        this.memory.set(data.subarray(cut), this.pstart << 8);
        dbg_log("rcv cut=" + h(cut), LOG_NET);
    }
    else
    {
        this.memory.set(data, data_start);

        if(data.length < 60)
        {
            this.memory.fill(0, data_start + data.length, data_start + 60);
        }
    }

    if(next >= this.pstop)
    {
        next += this.pstart - this.pstop;
    }

    // write packet header
    this.memory[offset] = ENRSR_RXOK; // status
    this.memory[offset + 1] = next;
    this.memory[offset + 2] = total_length;
    this.memory[offset + 3] = total_length >> 8;

    this.curpg = next;

    dbg_log("rcv offset=" + h(offset) + " len=" + h(total_length) + " next=" + h(next), LOG_NET);

    this.do_interrupt(ENISR_RX);
};

Ne2k.prototype.get_page = function()
{
    return this.cr >> 6 & 3;
};
                                                       source/v64/src/net_adapters/ne2k/plugin.js                                                          0000644 0000000 0000000 00000001446 00000000000 015624  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // net_device.type "ne2k" (the default) -- an NE2000-compatible card (RTL8029).
// Built into build/v86-ne2k.js; from the source tree, src/device_plugin.js
// imports this file directly. Its state is the core NE2000's of before (a
// snapshot's untagged state[59] is read as it is: src/device_plugin.js). No
// reset hook: the machine's reset left the NE2000 as it was before as well.

import { Ne2k } from "./ne2k.js";
import { NetMachine, register_net_adapter } from "../machine.js";

register_net_adapter({
    "name": "ne2k",
    "create": (handle, options) =>
    {
        const card = new Ne2k(new NetMachine(handle), options);
        return {
            "card": card,
            "get_state": () => card.get_state(),
            "set_state": state => card.set_state(state),
        };
    },
});
                                                                                                                                                                                                                          source/v64/src/net_adapters/offload.js                                                              0000644 0000000 0000000 00000011323 00000000000 015074  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What network cards compute for the driver (built into the card plugins):
// the Internet checksum (RFC 1071) of transmit offload and receive checks,
// and the Ethernet FCS a card leaves in memory when it does not strip it.

/**
 * The 16-bit one's complement sum of bytes [start, end), not yet folded; an
 * odd last byte is the high half of a word
 * @param {!Uint8Array} data
 * @param {number} start
 * @param {number} end
 * @param {number=} sum to continue
 * @return {number}
 */
export function checksum_add(data, start, end, sum = 0)
{
    let i = start;
    for(; i + 1 < end; i += 2)
    {
        sum += data[i] << 8 | data[i + 1];
        // (fold early: a frame of 64 KiB stays far below 2 ** 53 anyway, but
        // small integers are faster)
        if(sum > 0x7FFFFFFF) sum = (sum & 0xFFFF) + (sum >>> 16);
    }
    if(i < end)
    {
        sum += data[i] << 8;
    }
    return sum;
}

/**
 * Fold a sum into 16 bits
 * @param {number} sum
 * @return {number}
 */
export function checksum_fold(sum)
{
    while(sum > 0xFFFF)
    {
        sum = (sum & 0xFFFF) + Math.floor(sum / 0x10000);
    }
    return sum;
}

/**
 * The checksum to store: the complement of the folded sum, 0xFFFF instead of
 * 0 (for UDP, 0 means "no checksum"; for TCP and IP the two are the same)
 * @param {number} sum
 * @return {number}
 */
export function checksum_finish(sum)
{
    return ~checksum_fold(sum) & 0xFFFF || 0xFFFF;
}

/**
 * Store a big-endian 16-bit value
 * @param {!Uint8Array} data
 * @param {number} offset
 * @param {number} value
 */
export function store16(data, offset, value)
{
    data[offset] = value >> 8;
    data[offset + 1] = value;
}

/**
 * @param {!Uint8Array} data
 * @param {number} offset
 * @return {number}
 */
export function load16(data, offset)
{
    return data[offset] << 8 | data[offset + 1];
}

/**
 * @param {!Uint8Array} data
 * @param {number} offset
 * @param {number} value
 */
export function store32(data, offset, value)
{
    data[offset] = value >>> 24;
    data[offset + 1] = value >>> 16;
    data[offset + 2] = value >>> 8;
    data[offset + 3] = value;
}

/**
 * @param {!Uint8Array} data
 * @param {number} offset
 * @return {number}
 */
export function load32(data, offset)
{
    return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
}

/** @type {Int32Array} */
let crc_table = null;

/**
 * The Ethernet FCS (CRC-32, IEEE 802.3) of bytes [start, end); it goes on
 * the wire least significant byte first
 * @param {!Uint8Array} data
 * @param {number} start
 * @param {number} end
 * @return {number}
 */
export function ethernet_fcs(data, start, end)
{
    if(!crc_table)
    {
        crc_table = new Int32Array(256);
        for(let n = 0; n < 256; n++)
        {
            let c = n;
            for(let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
            crc_table[n] = c;
        }
    }
    let crc = -1;
    for(let i = start; i < end; i++)
    {
        crc = crc_table[(crc ^ data[i]) & 0xFF] ^ crc >>> 8;
    }
    return ~crc >>> 0;
}

/** What a card found when it checked a frame's checksums (receive offload) */
export const CHECKSUM_NONE = 0;
export const CHECKSUM_GOOD = 1;
export const CHECKSUM_BAD = 2;

/**
 * Check the IPv4 header and the TCP or UDP checksum of an Ethernet frame
 * (without a VLAN tag). Fragments and other protocols have no L4 result.
 * @param {!Uint8Array} frame
 * @param {number} length
 * @return {{ip: number, l4: number}} CHECKSUM_*
 */
export function check_checksums(frame, length)
{
    const result = { ip: CHECKSUM_NONE, l4: CHECKSUM_NONE };
    if(length < 14 + 20 || load16(frame, 12) !== 0x0800 || frame[14] >> 4 !== 4)
    {
        return result;
    }
    const ihl = (frame[14] & 0xF) << 2;
    const total = load16(frame, 16);
    if(ihl < 20 || 14 + ihl > length)
    {
        return result;
    }
    result.ip = checksum_fold(checksum_add(frame, 14, 14 + ihl)) === 0xFFFF ? CHECKSUM_GOOD : CHECKSUM_BAD;

    const protocol = frame[14 + 9];
    const fragment = load16(frame, 14 + 6) & 0x3FFF;
    if(result.ip !== CHECKSUM_GOOD || fragment || protocol !== 6 && protocol !== 17 ||
        total < ihl || 14 + total > length)
    {
        return result;
    }
    const start = 14 + ihl, end = 14 + total;
    if(protocol === 17 && (end - start < 8 || load16(frame, start + 6) === 0))
    {
        // (UDP without a checksum)
        result.l4 = end - start < 8 ? CHECKSUM_BAD : CHECKSUM_GOOD;
        return result;
    }
    // the pseudo header: addresses, protocol, length
    let sum = checksum_add(frame, 14 + 12, 14 + 20);
    sum += protocol + (end - start);
    sum = checksum_add(frame, start, end, sum);
    result.l4 = checksum_fold(sum) === 0xFFFF ? CHECKSUM_GOOD : CHECKSUM_BAD;
    return result;
}
                                                                                                                                                                                                                                                                                                             source/v64/src/opfs_disk.js                                                                         0000644 0000000 0000000 00000034735 00000000000 013006  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Browser disks (docs/vm-manager-plan.md "浏览器磁盘（OPFS）", U6): an image
// in the browser's private file system (OPFS), named by its url
// "opfs:v86/disks/<id>.img". With disk_option "read_write" OpfsDisk writes
// the guest's changes into it, as NodeFileDisk (src/disk_writeback.js) does
// into a local file, through a FileSystemSyncAccessHandle: read, write,
// flush synchronously, in the CPU Worker only (the handles exist in
// dedicated workers). The rules of src/disk_writeback.js hold: a write is
// complete when it is in the file, durable after a flush (the guest's, the
// timer's: 1 s after the last write, at most 5 s after the first not yet
// flushed; stop(), destroy(), pulling the drive out); a snapshot holds a
// reference (identity, generation, size), no data.
// OPFS files have no inode: the identity is a UUID and the generation a
// counter, kept in v86/disks/<id>.json beside the image; the generation
// moves on when the image's size differs from the record, at the first
// write of each session and at the first write after a snapshot, so a
// snapshot never fits an image written after it. The sync access handle is
// exclusive: a disk open in another tab cannot be opened here.
// With disk_option "read_only" the image is read as a File (opfs_file) and
// the changes stay in memory, as for a file the user picked.

import { disk_error, WRITEBACK_STATE, WRITEBACK_STATE_VERSION, FLUSH_IDLE_MS, FLUSH_MAX_MS, is_writeback_state } from "./disk_writeback.js";
import { dbg_log } from "./log.js";
import { LOG_DISK } from "./const.js";

const SECTOR_SIZE = 512;
export const OPFS_SCHEME = "opfs:";

/**
 * Whether a url names a browser disk
 * @param {*} url
 * @return {boolean}
 */
export function is_opfs_url(url)
{
    return typeof url === "string" && url.startsWith(OPFS_SCHEME);
}

/**
 * The directory and file name of a browser disk's url
 * @param {string} url
 * @return {{directory: !Array<string>, name: string}}
 */
function opfs_path(url)
{
    const parts = url.slice(OPFS_SCHEME.length).split("/").filter(Boolean);
    if(!parts.length || parts.some(part => part === "." || part === ".."))
    {
        throw disk_error("The browser disk's url " + url + " names no file (opfs:<directory>/<file>)", "config", false);
    }
    return { directory: parts.slice(0, -1), name: parts[parts.length - 1] };
}

/**
 * A browser disk's directory (not made: a disk that does not exist is an error)
 * @param {string} url
 * @param {string} label the disk's name, for messages
 * @return {!Promise<{dir: ?, name: string}>}
 */
async function opfs_entry(url, label)
{
    const storage = globalThis.navigator && globalThis.navigator["storage"];
    if(!storage || typeof storage["getDirectory"] !== "function")
    {
        throw disk_error(label + ": a browser disk (" + url + ") is in a browser's private storage (OPFS), which is not here", "config", false);
    }
    const path = opfs_path(url);
    let dir = await storage["getDirectory"]();
    try
    {
        for(const part of path.directory) dir = await dir["getDirectoryHandle"](part);
    }
    catch(e)
    {
        throw disk_error(label + ": the browser disk " + url + " does not exist", "config", false);
    }
    return { dir, name: path.name };
}

/**
 * A browser disk's image as a File (read only: the changes stay in memory)
 * @param {string} url
 * @param {string} label
 * @return {!Promise<!File>}
 */
export async function opfs_file(url, label)
{
    const { dir, name } = await opfs_entry(url, label);
    try
    {
        return await (await dir["getFileHandle"](name))["getFile"]();
    }
    catch(e)
    {
        throw disk_error(label + ": the browser disk " + url + " does not exist (" + (e && e.message || e) + ")", "config", false);
    }
}

/**
 * A browser disk, written back
 * @constructor
 * @param {string} url "opfs:v86/disks/<id>.img"
 * @param {{name: string, size: (number|undefined)}} options
 */
export function OpfsDisk(url, options)
{
    this.url = url;
    this.name = options.name;
    this.expected_size = options.size;
    /** @type {number} */
    this.byteLength = 0;
    /** a backend of the contract (src/block_backend.js, src/ide.js: the write cache) */
    this.writeback = true;
    /** @type {?} the image's FileSystemSyncAccessHandle */
    this.access = null;
    /** @type {?} the record's (<id>.json) */
    this.record_access = null;
    /** @type {!Object} the record: uuid, generation, size (and the VM manager's fields) */
    this.record = {};
    this.closed = false;
    /** @type {!Object} */
    this.identity = {};
    /** the generation moves on before the next write (the session's first, the first after a snapshot) */
    this.move_before_write = true;
    this.dirty_since = 0;
    this.flush_timer = 0;
    this.flush_requests = 0;
    this.flushes = 0;
    this.writes = 0;
    this.onload = undefined;
    this.onprogress = undefined;
}

OpfsDisk.prototype.load = async function()
{
    /**
     * @param {string} message
     * @param {string=} kind
     */
    const fail = (message, kind) => { throw disk_error(this.name + ": " + message, kind || "config", false); };
    const { dir, name } = await opfs_entry(this.url, this.name);
    let file;
    try
    {
        file = await dir["getFileHandle"](name);
    }
    catch(e)
    {
        fail("the browser disk " + this.url + " does not exist");
    }
    if(typeof file["createSyncAccessHandle"] !== "function")
    {
        fail("a browser disk written back (disk_option \"read_write\") needs the CPU Worker (cpu_worker): the browser's " +
            "synchronous access to its files is there only");
    }
    try
    {
        this.access = await file["createSyncAccessHandle"]();
    }
    catch(e)
    {
        if(e && e.name === "NoModificationAllowedError")
        {
            fail("the browser disk " + this.url + " is used by another tab (or another disk of this machine)", "in_use");
        }
        fail("the browser disk " + this.url + " cannot be opened (" + (e && e.message || e) + ")");
    }
    const size = this.access["getSize"]();
    if(size % SECTOR_SIZE)
    {
        this.close_now();
        fail(this.url + " has " + size + " bytes, not a whole number of " + SECTOR_SIZE + "-byte sectors");
    }
    if(this.expected_size !== undefined && this.expected_size !== size)
    {
        this.close_now();
        fail(this.url + " has " + size + " bytes, the descriptor's size says " + this.expected_size);
    }
    // the record: identity and generation (made for a disk without one)
    const record_name = name.replace(/\.img$/, "") + ".json";
    try
    {
        this.record_access = await (await dir["getFileHandle"](record_name, { "create": true }))["createSyncAccessHandle"]();
    }
    catch(e)
    {
        this.close_now();
        fail("the record of the browser disk " + this.url + " cannot be opened (" + (e && e.message || e) + ")", e && e.name === "NoModificationAllowedError" ? "in_use" : "config");
    }
    /** @type {!Object} */
    let record = {};
    try
    {
        const bytes = new Uint8Array(this.record_access["getSize"]());
        this.record_access["read"](bytes, { "at": 0 });
        const parsed = bytes.length ? JSON.parse(new TextDecoder().decode(bytes)) : {};
        record = parsed && typeof parsed === "object" ? /** @type {!Object} */ (parsed) : {};
    }
    catch(e)
    {
        record = {};
    }
    if(typeof record["uuid"] !== "string" || !record["uuid"]) record["uuid"] = globalThis.crypto["randomUUID"]();
    if(!Number.isSafeInteger(record["generation"])) record["generation"] = 1;
    // (changed since the record: another generation)
    if(record["size"] !== size) record["generation"]++;
    record["size"] = size;
    this.record = record;
    this.save_record();
    this.identity = { "opfs": this.url, "uuid": record["uuid"] };
    this.byteLength = size;
    this.onload && this.onload(Object.create(null));
};

/** The record into its file, flushed */
OpfsDisk.prototype.save_record = function()
{
    const bytes = new TextEncoder().encode(JSON.stringify(this.record));
    this.record_access["truncate"](0);
    this.record_access["write"](bytes, { "at": 0 });
    this.record_access["flush"]();
};

/**
 * @param {*} e
 * @param {string} what
 * @return {!Error}
 */
OpfsDisk.prototype.io_error = function(e, what)
{
    // (the browser's quota: no space; trying again does not help)
    const quota = e && e.name === "QuotaExceededError";
    return disk_error(this.name + ": the " + what + " of the browser disk " + this.url + " failed (" + (e && e.message || e) + ")" +
        (quota ? ": the browser's storage for this site is full" : ""), quota ? "no_space" : "io", !quota && !(e && e.name === "InvalidStateError"));
};

/**
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array}
 */
OpfsDisk.prototype.read_now = function(start, length)
{
    if(this.closed) throw disk_error(this.name + ": the disk is closed", "io", false);
    const data = new Uint8Array(length);
    this.access["read"](data, { "at": start });
    return data;
};

/**
 * @param {number} start
 * @param {number} length
 * @param {function((!Uint8Array|undefined), !Error=)} fn
 */
OpfsDisk.prototype.get = function(start, length, fn)
{
    let data;
    try { data = this.read_now(start, length); }
    catch(e) { fn(undefined, e["retryable"] === undefined ? this.io_error(e, "read") : e); return; }
    fn(data);
};

OpfsDisk.prototype.get_and_cache = OpfsDisk.prototype.get;

/**
 * (synchronous anyway)
 * @param {number} start
 * @param {number} length
 * @return {!Uint8Array|undefined}
 */
OpfsDisk.prototype.get_from_cache = function(start, length)
{
    try { return this.read_now(start, length); }
    catch(e) { return undefined; }
};

/**
 * @param {number} start
 * @param {!Uint8Array} data
 * @param {function(!Error=)} fn
 */
OpfsDisk.prototype.set = function(start, data, fn)
{
    if(this.closed)
    {
        fn(disk_error(this.name + ": the disk is closed", "io", false));
        return;
    }
    try
    {
        if(this.move_before_write)
        {
            // the session's first write, the first after a snapshot: the
            // generation moves on before the data changes
            this.record["generation"]++;
            this.save_record();
            this.move_before_write = false;
        }
        for(let done = 0; done < data.length;)
        {
            const n = this.access["write"](data.subarray(done), { "at": start + done });
            if(!n) throw new Error("nothing written");
            done += n;
        }
    }
    catch(e)
    {
        fn(this.io_error(e, "write"));
        return;
    }
    this.writes++;
    this.schedule_flush();
    fn(undefined);
};

/** @return {string} the image's generation now */
OpfsDisk.prototype.generation = function()
{
    return String(this.record["generation"]);
};

/** The timed flush (FLUSH_IDLE_MS after the last write, FLUSH_MAX_MS at most) */
OpfsDisk.prototype.schedule_flush = function()
{
    const now = Date.now();
    if(!this.dirty_since) this.dirty_since = now;
    clearTimeout(this.flush_timer);
    const wait = Math.max(0, Math.min(FLUSH_IDLE_MS, this.dirty_since + FLUSH_MAX_MS - now));
    this.flush_timer = setTimeout(() =>
    {
        this.flush_timer = 0;
        this.flush(error => { if(error) dbg_log(error.message, LOG_DISK); });
    }, wait);
};

/**
 * The writes completed before are durable
 * @param {function(!Error=)} fn
 */
OpfsDisk.prototype.flush = function(fn)
{
    this.flush_requests++;
    if(this.closed || !this.dirty_since)
    {
        fn(undefined);
        return;
    }
    clearTimeout(this.flush_timer);
    this.flush_timer = 0;
    try
    {
        this.access["flush"]();
    }
    catch(e)
    {
        const error = this.io_error(e, "flush");
        error["retryable"] = false;
        fn(error);
        return;
    }
    this.dirty_since = 0;
    this.flushes++;
    fn(undefined);
};

/**
 * Flush and close (destroy(), the drive pulled out): the handles go, another tab may open the disk
 * @param {function(!Error=)} fn
 */
OpfsDisk.prototype.close = function(fn)
{
    if(this.closed)
    {
        fn(undefined);
        return;
    }
    this.flush(error =>
    {
        this.close_now();
        fn(error);
    });
};

OpfsDisk.prototype.close_now = function()
{
    clearTimeout(this.flush_timer);
    this.flush_timer = 0;
    for(const access of [this.access, this.record_access])
    {
        if(access) try { access["close"](); } catch(e) {}
    }
    this.access = null;
    this.record_access = null;
    this.closed = true;
};

/**
 * Flush and record the generation, for a snapshot: the next write moves it on
 * @return {string}
 */
OpfsDisk.prototype.mark = function()
{
    let failed;
    this.flush(error => { failed = error; });
    if(failed) throw failed;
    this.move_before_write = true;
    return this.generation();
};

/** (no whole image in memory: export reads the file) */
OpfsDisk.prototype.get_buffer = function(fn)
{
    fn(undefined);
};

/**
 * A snapshot's reference: identity, generation, size; no data
 * @return {!Array<*>}
 */
OpfsDisk.prototype.get_state = function()
{
    const generation = this.mark();
    return [WRITEBACK_STATE, WRITEBACK_STATE_VERSION, JSON.stringify(this.identity), generation, this.byteLength];
};

/**
 * @param {*} state
 */
OpfsDisk.prototype.check_state = function(state)
{
    const name = this.name;
    if(!is_writeback_state(state))
    {
        throw new Error(state ?
            "The snapshot's disk " + name + " has its changes in memory (disk_option \"read_only\", or an older v86): " +
            "they are not written into the browser disk " + this.url :
            "The snapshot has no disk " + name + ", this machine writes back the browser disk " + this.url);
    }
    if(state[1] !== WRITEBACK_STATE_VERSION)
    {
        throw new Error("The snapshot's disk " + name + " has a reference of version " + state[1] + ", this v86 reads version " + WRITEBACK_STATE_VERSION);
    }
    const identity = JSON.parse(state[2]);
    const generation = this.generation();
    if(JSON.stringify(identity) !== JSON.stringify(this.identity) || state[3] !== generation || state[4] !== this.byteLength)
    {
        throw new Error("The snapshot's disk " + name + " is " + JSON.stringify(identity) + " in generation " + state[3] +
            "; this machine's is " + JSON.stringify(this.identity) + " in generation " + generation +
            " (a disk written to after the snapshot was saved cannot go back to it)");
    }
};

OpfsDisk.prototype.set_state = function(state)
{
    this.check_state(state);
    // (restored: the first write after it moves the generation on)
    this.move_before_write = true;
};
                                   source/v64/src/parallel.js                                                                          0000644 0000000 0000000 00000011720 00000000000 012606  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

import { dbg_assert } from "./log.js";

const DATA_PORT = 0;
const STATUS_PORT = 1;
const CONTROL_PORT = 2;

const STATUS_ACK = 0x40;

const CONTROL_IRQ_ENABLE = 0x10;
const CONTROL_MASK = 0x1F;
// Nothing plugged in: the status lines float high, which reads as busy (bit 7
// is inverted) with paper-out, select and no error, like a real port without
// a cable. Drivers then give up on the port quickly (Windows polls a ready
// port for an IEEE 1284 device for seconds at boot). A peripheral drives the
// lines through "parallelN-status-input" (idle: not busy, ACK, select and no
// error, 0xD8).
const STATUS_UNPLUGGED = 0x7F;

/**
 * Parallel port.
 *
 * @constructor
 *
 * @param {CPU} cpu
 * @param {number} port
 * @param {number} irq
 * @param {number} lpt (zero-based)
 * @param {BusConnector} bus
 */
export function ParallelPort(cpu, port, irq, lpt, bus)
{
    /** @const */
    this.cpu = cpu;

    /** @const */
    this.bus = bus;

    this.data = 0;
    this.status = STATUS_UNPLUGGED;
    this.control = 0;
    this.status_latched = undefined;
    this.irq = irq;
    this.lpt = lpt;

    this.data_output_event = "parallel" + this.lpt + "-data-output";
    this.control_output_event = "parallel" + this.lpt + "-control-output";
    this.status_input_event = "parallel" + this.lpt + "-status-input";

    const io = cpu.io;

    this.bus.register(this.status_input_event, this.set_status, this);

    io.register_read(port + DATA_PORT, this, this.read_data, this.read_data_status);
    io.register_read(port + STATUS_PORT, this, this.read_status, this.read_status_control);
    io.register_read(port + CONTROL_PORT, this, this.read_control);

    io.register_write(port + DATA_PORT, this, this.write_data, this.write_data_status);
    io.register_write(port + STATUS_PORT, this, this.write_status, this.write_status_control);
    io.register_write(port + CONTROL_PORT, this, this.write_control);
}

ParallelPort.prototype.read_data = function()
{
    return this.data;
};

ParallelPort.prototype.read_data_status = function()
{
    return this.read_data() | this.read_status() << 8;
};

ParallelPort.prototype.read_status_control = function()
{
    return this.read_status() | this.read_control() << 8;
};

ParallelPort.prototype.read_control = function()
{
    return this.control;
};

ParallelPort.prototype.write_data = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFF);

    this.data = value & 0xFF;
    this.bus.send(this.data_output_event, this.data);
};

ParallelPort.prototype.write_data_status = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFFFF);

    this.write_data(value & 0xFF);
    this.write_status(value >> 8 & 0xFF);
};

ParallelPort.prototype.write_status = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFF);
    /* no-op, status driven by peripheral side */
};

ParallelPort.prototype.write_status_control = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFFFF);

    this.write_status(value & 0xFF);
    this.write_control(value >> 8 & 0xFF);
};

ParallelPort.prototype.set_status = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFF);

    const status_next = value & 0xFF;
    const ack_prev = this.status & STATUS_ACK;
    const ack_next = status_next & STATUS_ACK;

    this.status = status_next;

    const ack_fell = ack_prev && !ack_next;
    if(ack_fell)
    {
        /*
           Both seabios and Boch's BIOS send data by latching
           the data lines, pulsing the strobe line, and then
           polling the status register until ACK goes low.

           A typical ACK low pulse is 5-10us.

           v86 doesn't have a precise scheduler for devices to pulse lines.
           The hack here is to let the peripheral go as fast as it
           wants, and latch ACK drops so the BIOS can detect them.
         */
        this.status_latched = status_next;
        if(this.control & CONTROL_IRQ_ENABLE)
        {
            this.cpu.device_lower_irq(this.irq);
            this.cpu.device_raise_irq(this.irq);
        }
    }
};

ParallelPort.prototype.read_status = function()
{
    if(this.status_latched !== undefined)
    {
        const status = this.status_latched;
        this.status_latched = undefined;
        return status;
    }

    return this.status;
};

ParallelPort.prototype.write_control = function(value)
{
    dbg_assert(value >= 0 && value <= 0xFF);

    this.control = value & CONTROL_MASK;
    this.bus.send(this.control_output_event, this.control);
};

ParallelPort.prototype.get_state = function()
{
    return [
        this.data,
        this.status,
        this.control,
        this.status_latched,
    ];
};

ParallelPort.prototype.set_state = function(state)
{
    if(!state)
    {
        return;
    }

    this.data = state[0];
    this.status = state[1];
    this.control = state[2];
    // (nothing latched is undefined, which a snapshot stores as null)
    this.status_latched = state[3] === null ? undefined : state[3];
};
                                                source/v64/src/parallel/control.js                                                                  0000644 0000000 0000000 00000011107 00000000000 014265  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The control block shared by the machine and its vCPU workers
// (docs/multicore.md): an Int32Array over a
// SharedArrayBuffer of its own. Guest RAM and CPU state live in the Wasm
// memory; this block only carries the host protocol:
//
// - stop-the-world: the machine raises STOP to a new epoch and kicks every
//   core; a core acknowledges at its next safe point (between slices, or
//   while it waits halted) by writing the epoch to its ACK word, then waits
//   for RESUME to reach the same epoch and runs the COMMAND left for it;
// - I/O: a core in a worker posts a port or MMIO access in its slot, rings
//   DOORBELL and waits; the machine performs it on the devices' thread;
// - status words the machine reads for diagnostics and scheduling.

export const MAX_CORES = 8;

// machine words
export const STOP = 0;
export const RESUME = 1;
export const DOORBELL = 2;
export const COMMAND = 3;
export const SHUTDOWN = 4;          // workers exit their loop
export const CLOCK_ORIGIN_LO = 5;   // (unused: clocks use performance.timeOrigin)
export const PM_BASE = 6;           // the ACPI PM block's port, or -1 (ACPI.prototype.share_timer)

// per-core words, at core_word(core, WORD)
const CORE_BASE = 16;
const CORE_STRIDE = 32;
export const ACK = 0;               // last stop epoch this core acknowledged
export const STATUS = 1;            // STATUS_*
export const IO_STATE = 2;          // IO_IDLE, IO_REQUEST, IO_DONE
export const IO_OP = 3;
export const IO_ADDR = 4;
export const IO_V0 = 5;             // values of a write (up to 128 bits)
export const IO_V1 = 6;
export const IO_V2 = 7;
export const IO_V3 = 8;
export const IO_RESULT = 9;
export const TSC_OFFSET_LO = 10;    // published while parked
export const TSC_OFFSET_HI = 11;
export const RUNNING = 12;          // started by a start-up IPI (APs)
export const STATE_BASE = 13;       // address of the core's CPU state block
export const ERROR = 14;            // nonzero after the worker failed
export const SLICES = 15;
export const STEPS = 16;            // retired instructions, low 32 bits
export const WAITS = 17;            // halted waits
export const IO_COUNT = 18;         // requests served by the machine
export const JIT_ENTRIES = 19;      // entries into compiled code (the x64 page tier's functions)
export const REFUSED = 20;          // code installations given up: the other cores had not acknowledged in time
export const IO_RESULT_HI = 21;     // the high 32 bits of a 64-bit result (OP_A64_MMIO_READ)
export const STEPS_HI = 22;         // retired instructions, high bits (the ARM core's workers)
export const RING_STATS = 23;       // (the ARM core's workers, 3 words) TLB maintenance posted, DSBs that waited, entries taken
export const KICKED = 26;           // (the ARM core's workers) runs a kick ended early

export const CONTROL_WORDS = CORE_BASE + CORE_STRIDE * MAX_CORES;

// after the words, 8-byte slots: the clock offset (Float64), the PM timer
// offset (Float64) and the PM timer's shared maximum (BigInt64)
export const SLOT_CLOCK_OFFSET = 0;
export const SLOT_PM_TIMER_OFFSET = 1;
export const SLOT_PM_TIMER_LAST = 2;
export const CONTROL_BYTES = CONTROL_WORDS * 4 + 3 * 8;

export const STATUS_STARTING = 0;
export const STATUS_WAIT_SIPI = 1;
export const STATUS_RUNNING = 2;
export const STATUS_HALTED = 3;
export const STATUS_PARKED = 4;
export const STATUS_FAILED = 5;
export const STATUS_EXITED = 6;

export const IO_IDLE = 0;
export const IO_REQUEST = 1;
export const IO_DONE = 2;

// requests of a core in a worker
export const OP_IN8 = 1, OP_IN16 = 2, OP_IN32 = 3;
export const OP_OUT8 = 4, OP_OUT16 = 5, OP_OUT32 = 6;
export const OP_MMIO_READ8 = 7, OP_MMIO_READ32 = 8;
export const OP_MMIO_WRITE8 = 9, OP_MMIO_WRITE16 = 10, OP_MMIO_WRITE32 = 11, OP_MMIO_WRITE64 = 12, OP_MMIO_WRITE128 = 13;
export const OP_HALTED_FOREVER = 14;   // HLT with interrupts disabled (cpu_event_halt)
export const OP_RESET = 15;            // triple fault of the BSP is handled by the machine; unused by APs
// the ARM core (P8.2): a device register of the virt machine (src/virt/io.js),
// IO_ADDR the owner | width << 24, IO_V0/IO_V1 the offset, IO_V2/IO_V3 the value
export const OP_A64_MMIO_READ = 16, OP_A64_MMIO_WRITE = 17;

// commands for parked cores (the machine writes them before RESUME)
export const COMMAND_NONE = 0;
export const COMMAND_RELOAD = 1;       // state may have changed: drop caches derived from it
export const COMMAND_RESET = 2;        // machine reset: wait for INIT/SIPI again
export const COMMAND_FLUSH = 3;        // translations changed: flush TLBs

export function core_word(core, word)
{
    return CORE_BASE + CORE_STRIDE * core + word;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/parallel/entry_url.js                                                                0000644 0000000 0000000 00000000433 00000000000 014630  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The vCPU worker entry of the source tree. Loaded only when running from
// source (src/parallel/machine.js): the Closure bundles cannot compile
// import.meta and use build/vcpu-worker.js instead.
export const VCPU_WORKER_ENTRY = new URL("vcpu_worker_entry.js", import.meta.url);
                                                                                                                                                                                                                                     source/v64/src/parallel/machine.js                                                                  0000644 0000000 0000000 00000043225 00000000000 014217  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Host-parallel machine (docs/multicore.md): the
// bootstrap processor and every device run on this thread, in the machine
// instance of v86-parallel.wasm (base 0); each application processor runs in
// a vCPU worker (src/parallel/vcpu.js) with its own relocated instance in the
// same shared memory.
//
// This side serves the workers' port and device-MMIO accesses, keeps the
// control block's clock offset current and stops all cores (parks them at a
// safe point) around snapshots, resets, sleep states and pauses.

import { dbg_log } from "../log.js";
import { LOG_CPU } from "../const.js";
import { CORE_STATE_RANGES } from "../state_layout.js";
import { image_size, PAGE_SIZE } from "./relocate.js";
import * as C from "./control.js";

/* global __dirname, V86_BUNDLE */

const NODE = typeof process !== "undefined" && process.versions && process.versions.node;

export class ParallelMachine
{
    /**
     * @param {Object} cpu the machine's CPU (instance at base 0)
     * @param {{bytes: Uint8Array, settings: Object, worker_url: (string|URL)}} options
     */
    constructor(cpu, options)
    {
        this.cpu = cpu;
        this.exports = cpu.wm.exports;
        // (the x86 CPU keeps an array of its cores, the ARM CPU their number)
        this.cores = typeof cpu.cores === "number" ? cpu.cores : cpu.cores.length;
        /** the ranges of a core's state block that save_core_state copies */
        this.state_ranges = cpu.core_state_ranges || CORE_STATE_RANGES;
        this.bytes = options.bytes;
        this.settings = options.settings;
        this.worker_url = options.worker_url;
        this.control = new SharedArrayBuffer(C.CONTROL_BYTES);
        this.ctrl = new Int32Array(this.control);
        this.clock_offset = new Float64Array(this.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_CLOCK_OFFSET, 1);
        this.ctrl[C.PM_BASE] = -1;
        // the workers read the PM timer themselves (src/acpi.js)
        cpu.devices.acpi?.share_timer(this.ctrl.subarray(C.PM_BASE, C.PM_BASE + 1),
            new Float64Array(this.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_PM_TIMER_OFFSET, 1),
            new BigInt64Array(this.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_PM_TIMER_LAST, 1));
        this.workers = [];
        /** each vCPU worker instance's base in the shared memory (its statics are there + their address in this instance) */
        this.instance_bases = [0];
        this.epoch = 0;
        this.stopping_epoch = 0;
        this.command = C.COMMAND_NONE;
        this.failure = null;
        this.failed_core = 0;
        /** @type {?{reason: (string|undefined), keep_memory: (boolean|undefined)}} a reset waiting for the workers to park */
        this.pending_reset = null;
        this.destroyed = false;
        this.served = 0;
        this.sync_clock();
    }

    sync_clock()
    {
        this.clock_offset[0] = performance.timeOrigin + performance.now() - this.cpu.clock.now();
    }

    /** Start the application processors; they wait for INIT/SIPI */
    async start()
    {
        const memory = this.cpu.wasm_memory;
        const pages = Math.ceil(image_size(this.bytes) / PAGE_SIZE);
        this.exports["parallel_set_active"](true);
        const ready = [];
        for(let core = 1; core < this.cores; core++)
        {
            // fresh (so zeroed) pages for the worker's static data and stack
            const base = memory.grow(pages) * PAGE_SIZE;
            this.instance_bases[core] = base;
            const worker = await create_worker(this.worker_url, "v86 vCPU " + core);
            this.workers[core] = worker;
            ready.push(new Promise((resolve, reject) => {
                const fail = error => {
                    this.fail(core, error);
                    reject(this.failure);
                };
                worker.on_message(message => {
                    if(message["type"] === "ready") resolve();
                    else if(message["type"] === "error") fail(new Error("vCPU " + core + " failed: " + message["message"]));
                });
                worker.on_error(error => fail(error));
                // (Node: a worker that ends without an error message, e.g. process.exit)
                worker.on_exit(code => {
                    if(!this.destroyed && Atomics.load(this.ctrl, C.core_word(core, C.STATUS)) !== C.STATUS_EXITED)
                    {
                        fail(new Error("vCPU " + core + " worker exited (code " + code + ")"));
                    }
                });
            }));
            worker.post({
                "bytes": this.bytes, "memory": memory, "control": this.control,
                "base": base, "core": core, "cores": this.cores,
                "mem8": this.cpu.mem8.byteOffset, "memory_size": this.cpu.memory_size[0],
                "settings": this.settings, "log": false, "cpu_type": this.cpu.cpu_type || "x86",
                "extended": this.cpu.extended_store ? this.cpu.extended_store.transfer() : null,
            });
        }
        await Promise.all(ready);
        this.watch();
        dbg_log("parallel machine: " + (this.cores - 1) + " vCPU workers", LOG_CPU);
    }

    /** Run the machine's loop whenever a worker kicks core 0 (I/O, parking, IPIs) */
    watch()
    {
        const wake = new Int32Array(this.cpu.wasm_memory.buffer);
        const index = this.exports["parallel_wake_addr"](0) >>> 2;
        const loop = () => {
            if(this.destroyed) return;
            const value = Atomics.load(wake, index);
            const waiter = typeof Atomics.waitAsync === "function" ? Atomics.waitAsync(wake, index, value, 100) : null;
            const next = () => { if(!this.destroyed) { this.cpu.stop_idling(); loop(); } };
            if(waiter && waiter.async) waiter.value.then(next);
            else setTimeout(next, waiter ? 0 : 1);
        };
        loop();
    }

    /** Perform the workers' pending port and MMIO accesses; returns how many */
    service()
    {
        const ctrl = this.ctrl, cpu = this.cpu;
        let count = 0;
        for(let core = 1; core < this.cores; core++)
        {
            const at = w => C.core_word(core, w);
            if(Atomics.load(ctrl, at(C.IO_STATE)) !== C.IO_REQUEST) continue;
            const op = ctrl[at(C.IO_OP)], addr = ctrl[at(C.IO_ADDR)];
            const v0 = ctrl[at(C.IO_V0)], v1 = ctrl[at(C.IO_V1)], v2 = ctrl[at(C.IO_V2)], v3 = ctrl[at(C.IO_V3)];
            let result = 0;
            // (e.g. an SMI from the APM control port goes to this core)
            cpu.io_core = core;
            switch(op)
            {
                case C.OP_IN8: result = this.exports["machine_io_read8"](addr); break;
                case C.OP_IN16: result = cpu.io.port_read16(addr); break;
                case C.OP_IN32: result = cpu.io.port_read32(addr); break;
                case C.OP_OUT8: this.exports["machine_io_write8"](addr, v0); break;
                case C.OP_OUT16: cpu.io.port_write16(addr, v0 & 0xFFFF); break;
                case C.OP_OUT32: cpu.io.port_write32(addr, v0); break;
                case C.OP_MMIO_READ8: result = cpu.mmap_read8(addr >>> 0); break;
                case C.OP_MMIO_READ32: result = cpu.mmap_read32(addr >>> 0); break;
                case C.OP_MMIO_WRITE8: cpu.mmap_write8(addr >>> 0, v0 & 0xFF); break;
                case C.OP_MMIO_WRITE16: cpu.mmap_write16(addr >>> 0, v0 & 0xFFFF); break;
                case C.OP_MMIO_WRITE32: cpu.mmap_write32(addr >>> 0, v0); break;
                case C.OP_MMIO_WRITE64: cpu.mmap_write64(addr >>> 0, v0, v1); break;
                case C.OP_MMIO_WRITE128: cpu.mmap_write128(addr >>> 0, v0, v1, v2, v3); break;
                case C.OP_A64_MMIO_READ:
                {
                    const value = /** @type {bigint} */ (cpu.io.mmio_read(addr & 0xFFFFFF, BigInt(v1 >>> 0) << 32n | BigInt(v0 >>> 0), addr >>> 24));
                    result = Number(value & 0xFFFFFFFFn) | 0;
                    ctrl[at(C.IO_RESULT_HI)] = Number(value >> 32n) | 0;
                    break;
                }
                case C.OP_A64_MMIO_WRITE:
                    cpu.io.mmio_write(addr & 0xFFFFFF, BigInt(v1 >>> 0) << 32n | BigInt(v0 >>> 0), addr >>> 24,
                        BigInt(v3 >>> 0) << 32n | BigInt(v2 >>> 0));
                    break;
                default: dbg_log("vCPU " + core + ": unknown request " + op, LOG_CPU);
            }
            cpu.io_core = -1;
            ctrl[at(C.IO_RESULT)] = result;
            ctrl[at(C.IO_COUNT)]++;
            Atomics.store(ctrl, at(C.IO_STATE), C.IO_DONE);
            Atomics.notify(ctrl, at(C.IO_STATE));
            count++;
        }
        this.served += count;
        return count;
    }

    /**
     * A vCPU failed: the machine cannot go on (its state is lost). Release
     * what the core held, stop the other workers; the machine's loop reports
     * the error ("emulator-error") and stops.
     */
    fail(core, error)
    {
        if(this.failure || this.destroyed) return;
        this.failure = error;
        this.failed_core = core;
        dbg_log("parallel machine: " + error, LOG_CPU);
        Atomics.store(this.ctrl, C.core_word(core, C.STATUS), C.STATUS_FAILED);
        this.exports["parallel_core_failed"](core);
        this.request_stop();
        this.cpu.stop_idling();
    }

    /** @return {Error|null} the failure of a vCPU, if one failed */
    check_failure()
    {
        if(!this.failure)
        {
            for(let core = 1; core < this.cores; core++)
            {
                if(Atomics.load(this.ctrl, C.core_word(core, C.ERROR)))
                {
                    // (its error message follows by postMessage)
                    this.fail(core, new Error("vCPU " + core + " failed"));
                }
            }
        }
        return this.failure;
    }

    /** Whether a stop is in effect (requested and not resumed) */
    stopping()
    {
        return this.stopping_epoch > Atomics.load(this.ctrl, C.RESUME);
    }

    /** Ask every worker to park at its next safe point, without waiting */
    request_stop()
    {
        if(this.stopping()) return;
        this.stopping_epoch = ++this.epoch;
        Atomics.store(this.ctrl, C.STOP, this.stopping_epoch);
        for(let core = 1; core < this.cores; core++) this.exports["parallel_kick"](core);
    }

    /** Whether every worker has parked for the current stop */
    all_parked()
    {
        if(!this.stopping()) return false;
        for(let core = 1; core < this.cores; core++)
        {
            const status = Atomics.load(this.ctrl, C.core_word(core, C.STATUS));
            if(status === C.STATUS_FAILED || status === C.STATUS_EXITED) continue;
            if(Atomics.load(this.ctrl, C.core_word(core, C.ACK)) !== this.stopping_epoch) return false;
        }
        return true;
    }

    /** Stop every worker at a safe point, serving their I/O until they get there */
    async park()
    {
        if(this.check_failure()) throw this.failure;
        this.request_stop();
        const deadline = Date.now() + 30000;
        while(!this.all_parked())
        {
            this.service();
            if(this.check_failure()) throw this.failure;
            if(Date.now() > deadline) throw new Error("vCPU workers did not stop: " + JSON.stringify(this.status()));
            await new Promise(resolve => setTimeout(resolve, 0));
        }
    }

    /** A command the workers run when they next resume (they must be parked) */
    schedule(command)
    {
        this.command = Math.max(this.command, command);
    }

    /** Let parked workers continue */
    resume()
    {
        if(!this.stopping()) return;
        this.sync_clock();
        Atomics.store(this.ctrl, C.COMMAND, this.command);
        this.command = C.COMMAND_NONE;
        Atomics.store(this.ctrl, C.RESUME, this.stopping_epoch);
        Atomics.notify(this.ctrl, C.RESUME);
    }

    /** The saved state of a parked core, in the layout of CPU.prototype.save_core_state */
    read_core(core)
    {
        const base = this.ctrl[C.core_word(core, C.STATE_BASE)] >>> 0;
        const memory = new Uint8Array(this.cpu.wasm_memory.buffer);
        return this.state_ranges.map(([start, end]) => memory.slice(base + start, base + end));
    }

    write_core(core, saved)
    {
        const base = this.ctrl[C.core_word(core, C.STATE_BASE)] >>> 0;
        const memory = new Uint8Array(this.cpu.wasm_memory.buffer);
        this.state_ranges.forEach(([start], i) => memory.set(saved[i], base + start));
    }

    /** Address of offset 0 of a worker core's state block (live, racy while it runs) */
    state_base(core) { return this.ctrl[C.core_word(core, C.STATE_BASE)] >>> 0; }
    core_running(core) { return Atomics.load(this.ctrl, C.core_word(core, C.RUNNING)) !== 0; }
    set_core_running(core, running) { Atomics.store(this.ctrl, C.core_word(core, C.RUNNING), running ? 1 : 0); }
    core_tsc_offset(core)
    {
        return [this.ctrl[C.core_word(core, C.TSC_OFFSET_LO)] >>> 0, this.ctrl[C.core_word(core, C.TSC_OFFSET_HI)] >>> 0];
    }
    set_core_tsc_offset(core, tsc)
    {
        this.ctrl[C.core_word(core, C.TSC_OFFSET_LO)] = tsc[0];
        this.ctrl[C.core_word(core, C.TSC_OFFSET_HI)] = tsc[1];
    }
    /** The instructions core `core` retired, as its worker last published (the ARM core's workers) */
    core_retired(core)
    {
        return (this.ctrl[C.core_word(core, C.STEPS)] >>> 0) + (this.ctrl[C.core_word(core, C.STEPS_HI)] >>> 0) * 0x100000000;
    }
    core_counters(core)
    {
        const at = w => this.ctrl[C.core_word(core, w)] >>> 0;
        return { slices: at(C.SLICES), steps: at(C.STEPS), waits: at(C.WAITS), io: at(C.IO_COUNT), jit: at(C.JIT_ENTRIES),
            refused: at(C.REFUSED), tlbi_posted: at(C.RING_STATS), dsb_waits: at(C.RING_STATS + 1), tlbi_taken: at(C.RING_STATS + 2),
            kicked: at(C.KICKED) };
    }

    status()
    {
        const names = ["starting", "wait-for-sipi", "running", "halted", "parked", "failed", "exited"];
        const cores = [];
        for(let core = 1; core < this.cores; core++)
        {
            const at = w => this.ctrl[C.core_word(core, w)];
            cores.push(Object.assign({ "core": core, "status": names[at(C.STATUS)], "ack": at(C.ACK),
                "io_state": at(C.IO_STATE) }, this.core_counters(core)));
        }
        return { "epoch": this.epoch, "resume": this.ctrl[C.RESUME], "served": this.served, "cores": cores,
            "failure": this.failure ? String(this.failure.message || this.failure) : null };
    }

    destroy()
    {
        if(this.destroyed) return;
        this.destroyed = true;
        Atomics.store(this.ctrl, C.SHUTDOWN, 1);
        Atomics.notify(this.ctrl, C.RESUME);
        for(let core = 1; core < this.cores; core++)
        {
            this.exports["parallel_kick"](core);
            Atomics.notify(this.ctrl, C.core_word(core, C.IO_STATE));
            this.workers[core]?.terminate();
        }
        this.exports["parallel_set_active"](false);
        const acpi = this.cpu.devices.acpi;
        if(acpi) acpi.shared_base = acpi.shared_offset = acpi.shared_last = null;
    }
}

/**
 * Why this host cannot run vCPU workers ("" if it can): shared memory and
 * Atomics, workers, in browsers cross-origin isolation (the page needs the
 * COOP "same-origin" and COEP "require-corp" or "credentialless" headers),
 * and a host thread for each core (with fewer, the threads would take turns
 * on the host's CPUs, which the cooperative mode does at less cost)
 * @param {number=} cores
 * @return {string}
 */
export function parallel_unsupported_reason(cores)
{
    const threads = typeof navigator !== "undefined" && navigator["hardwareConcurrency"] || 0;
    if(cores && threads && threads < cores) return "only " + threads + " host threads";
    // (a browser hides SharedArrayBuffer from pages that are not isolated)
    if(!NODE && globalThis["crossOriginIsolated"] !== true) return "not cross-origin isolated";
    if(typeof SharedArrayBuffer !== "function" || typeof Atomics !== "object") return "no SharedArrayBuffer";
    if(!NODE && typeof Worker !== "function") return "no Worker";
    try
    {
        new WebAssembly.Memory({ "initial": 1, "maximum": 1, "shared": true });
    }
    catch(e)
    {
        return "no shared WebAssembly.Memory";
    }
    return "";
}

/**
 * The script of the vCPU workers when the embedder doesn't pass one
 * (`vcpu_worker_url`): build/vcpu-worker.js for the bundles (next to
 * libv86.js in Node, like v86.wasm), the ES module entry for the source tree
 * @return {Promise<string|URL>}
 */
export async function default_worker_url()
{
    if(typeof V86_BUNDLE !== "undefined")
    {
        return NODE && typeof __dirname === "string" ? __dirname + "/vcpu-worker.js" : "build/vcpu-worker.js";
    }
    return (await import("./" + "entry_url.js"))["VCPU_WORKER_ENTRY"];
}

async function create_worker(url, name)
{
    if(NODE)
    {
        const { Worker } = await import("node:" + "worker_threads");
        // (a relative path is relative to the working directory, like v86.wasm)
        const target = url instanceof URL || /^[a-z]+:/i.test(url) ? new URL(url) :
            /^\.{0,2}[\\/]/.test(url) ? url : "./" + url;
        const worker = new Worker(target, { "name": name });
        worker["unref"]();
        return {
            post: message => worker.postMessage(message),
            on_message: f => worker.on("message", f),
            on_error: f => worker.on("error", f),
            on_exit: f => worker.on("exit", f),
            terminate: () => worker.terminate(),
        };
    }
    const worker = new Worker(url, { "type": "module", "name": name });
    return {
        post: message => worker.postMessage(message),
        on_message: f => { worker.onmessage = e => f(e.data); },
        on_error: f => { worker.onerror = e => { e.preventDefault(); f(e.error || new Error(e.message)); }; },
        on_exit: () => {},
        terminate: () => worker.terminate(),
    };
}
                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/parallel/relocate.js                                                                 0000644 0000000 0000000 00000022733 00000000000 014412  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Loading build/v86-parallel.wasm (docs/multicore.md):
// one shared memory holds several instances of the module, each with its
// own static data, stack and CPU state block at a different base address.
// tools/parallel_wasm.mjs lists every field that holds an address of the
// module's static data; relocate() adds the base to them, except for
// addresses of the CPU state block (the fields whose relocation names it),
// which it moves to the instance's state slot at slot * STATE_SLOT_SIZE,
// below the module's static data: the
// generated code then addresses registers with small constants (which arm64
// hosts encode in the load or store instruction). Slot 0 is the machine
// instance's, so its state block is where v86.wasm has it.

import { dbg_assert } from "../log.js";

export const PAGE_SIZE = 65536;
export const STATE_SLOTS = 8;
export const STATE_SLOT_SIZE = 4096;

function read_uleb(bytes, at)
{
    let result = 0, shift = 0, byte;
    do
    {
        byte = bytes[at.pos++];
        result += (byte & 0x7F) * 2 ** shift;
        shift += 7;
    }
    while(byte & 0x80);
    return result;
}

function sections(bytes)
{
    const list = [];
    const at = { pos: 8 };
    while(at.pos < bytes.length)
    {
        const id = bytes[at.pos++];
        const size = read_uleb(bytes, at);
        const start = at.pos;
        let name = null;
        if(id === 0)
        {
            const length = read_uleb(bytes, at);
            name = String.fromCharCode(...bytes.subarray(at.pos, at.pos + length));
            at.pos += length;
        }
        list.push({ id, start, end: start + size, content: at.pos, name });
        at.pos = start + size;
    }
    return list;
}

/**
 * The memory the module imports as env.memory, or null for the normal build
 * (which defines its own memory)
 * @param {Uint8Array} bytes
 * @return {?{initial: number, maximum: number, shared: boolean}}
 */
export function memory_import(bytes)
{
    const section = sections(bytes).find(s => s.id === 2);
    if(!section) return null;
    const at = { pos: section.start };
    const name = () => {
        const length = read_uleb(bytes, at);
        const text = String.fromCharCode(...bytes.subarray(at.pos, at.pos + length));
        at.pos += length;
        return text;
    };
    for(let count = read_uleb(bytes, at); count--;)
    {
        const module = name(), field = name();
        const kind = bytes[at.pos++];
        if(kind === 0) read_uleb(bytes, at);
        else if(kind === 1) { at.pos++; const flags = bytes[at.pos++]; read_uleb(bytes, at); if(flags & 1) read_uleb(bytes, at); }
        else if(kind === 3) at.pos += 2;
        else if(kind === 2)
        {
            const flags = bytes[at.pos++];
            const initial = read_uleb(bytes, at);
            const maximum = flags & 1 ? read_uleb(bytes, at) : 65536;
            if(module === "env" && field === "memory") return { initial, maximum, shared: !!(flags & 2) };
        }
    }
    return null;
}

/**
 * Positions of the relocated fields and where the linker put the state block
 * @param {Uint8Array} bytes
 * @return {{uleb5: !Array<number>, sleb5: !Array<number>, u32: !Array<number>,
 *     uleb5_state: !Array<number>, sleb5_state: !Array<number>, u32_state: !Array<number>,
 *     state_address: number, state_size: number}}
 */
export function relocations(bytes)
{
    const section = sections(bytes).find(s => s.name === "v86.relocs");
    if(!section) throw new Error("v86-parallel.wasm: no relocation table (not built by tools/parallel_wasm.mjs)");
    const at = { pos: section.content };
    const version = read_uleb(bytes, at);
    if(version !== 3) throw new Error("v86-parallel.wasm: relocation table version " + version + " (rebuild it)");
    const list = () => {
        const positions = [];
        let position = 0;
        for(let count = read_uleb(bytes, at); count--;)
        {
            position += read_uleb(bytes, at);
            positions.push(position);
        }
        return positions;
    };
    const uleb5 = list(), sleb5 = list(), u32 = list();
    const uleb5_state = list(), sleb5_state = list(), u32_state = list();
    const state_address = read_uleb(bytes, at), state_size = read_uleb(bytes, at);
    dbg_assert(at.pos === section.end && state_size === STATE_SLOT_SIZE);
    return { uleb5, sleb5, u32, uleb5_state, sleb5_state, u32_state, state_address, state_size };
}

/**
 * A copy of the module whose static data and stack are at `base` instead of
 * 0 and whose CPU state block is in state slot `slot`. The memory at [base,
 * base + __heap_base) and the slot must be reserved for the instance and
 * zeroed: only non-zero data segments are written.
 * @param {!Uint8Array} bytes
 * @param {number} base a multiple of 64 KiB
 * @param {number} slot 0 for the machine instance, else its vCPU's core number
 * @return {!Uint8Array}
 */
export function relocate(bytes, base, slot)
{
    dbg_assert(base % PAGE_SIZE === 0 && base >= 0 && base < 2 ** 32);
    dbg_assert(slot >= 0 && slot < STATE_SLOTS);
    const table = relocations(bytes);
    const state_start = table.state_address;
    // the new value of a field that holds the (unsigned) address `value`: of
    // the instance's static data, or of its state block (`state`)
    const map = (value, state) => state ? slot * STATE_SLOT_SIZE + value - state_start : value + base;
    const out = new Uint8Array(bytes);
    const view = new DataView(out.buffer, out.byteOffset, out.byteLength);

    const read5 = at => {
        let value = 0;
        for(let i = 0; i < 5; i++) value += (out[at + i] & 0x7F) * 2 ** (7 * i);
        return value; // 35 bits, no sign
    };
    const write5 = (at, value) => {
        for(let i = 0; i < 5; i++)
        {
            out[at + i] = value % 128 | (i < 4 ? 0x80 : 0);
            value = Math.floor(value / 128);
        }
    };
    for(const state of [false, true])
    {
        for(const at of state ? table.uleb5_state : table.uleb5)
        {
            // load/store offsets and unsigned immediates: must stay below 4 GiB
            const value = map(read5(at), state);
            if(value < 0 || value >= 2 ** 32) throw new Error("relocated offset beyond 4 GiB");
            write5(at, value);
        }
        for(const at of state ? table.sleb5_state : table.sleb5)
        {
            // i32.const: a signed 32-bit value in 5 bytes (bits 32..34 are sign extension)
            const value = map(read5(at) % 2 ** 32, state) % 2 ** 32 | 0;
            write5(at, (value >>> 0) + (value < 0 ? 0x700000000 : 0));
        }
        for(const at of state ? table.u32_state : table.u32)
        {
            view.setUint32(at, map(view.getUint32(at, true), state) >>> 0, true);
        }
    }
    return out;
}

/**
 * Instantiate v86.wasm or v86-parallel.wasm. The parallel build imports its
 * memory: this instance (base 0) gets a new shared one.
 * @param {ArrayBuffer|Uint8Array} bytes
 * @param {!Object} imports with an "env" object
 */
export function instantiate_v86(bytes, imports)
{
    const view = new Uint8Array(bytes instanceof ArrayBuffer ? bytes : bytes.buffer, bytes.byteOffset || 0, bytes.byteLength);
    const memory = memory_import(view);
    if(memory)
    {
        imports["env"]["memory"] = new WebAssembly.Memory({ "initial": memory.initial, "maximum": memory.maximum, "shared": true });
        // (the machine instance: base 0, state slot 0)
        return WebAssembly.instantiate(relocate(view, 0, 0), imports);
    }
    return WebAssembly.instantiate(bytes, imports);
}

/**
 * Bytes an instance occupies at its base: static data, CPU state and stack
 * (__heap_base). Its heap is grown separately, like the one at base 0.
 * @param {Uint8Array} bytes
 */
export function image_size(bytes)
{
    const list = sections(bytes);
    let index = -1;
    {
        const section = list.find(s => s.id === 7);
        const at = { pos: section.start };
        for(let count = read_uleb(bytes, at); count--;)
        {
            const length = read_uleb(bytes, at);
            const name = String.fromCharCode(...bytes.subarray(at.pos, at.pos + length));
            at.pos += length;
            const kind = bytes[at.pos++];
            const i = read_uleb(bytes, at);
            if(kind === 3 && name === "__heap_base") index = i;
        }
    }
    dbg_assert(index >= 0);
    const section = list.find(s => s.id === 6);
    const at = { pos: section.start };
    const count = read_uleb(bytes, at);
    for(let i = 0; i < count; i++)
    {
        at.pos += 2; // type, mutability
        dbg_assert(bytes[at.pos] === 0x41);
        at.pos++;
        let value = 0, shift = 0, byte;
        do { byte = bytes[at.pos++]; value += (byte & 0x7F) * 2 ** shift; shift += 7; } while(byte & 0x80);
        at.pos++; // end
        if(i === index) return value % 2 ** 32;
    }
    dbg_assert(false);
}

/**
 * Another instance of v86-parallel.wasm in `memory`, in freshly grown (so
 * zeroed) pages that nothing else uses
 * @param {!Uint8Array} bytes
 * @param {!Object} imports with an "env" object
 * @param {!WebAssembly.Memory} memory the shared memory of the instance at base 0
 * @param {number} slot its state slot (1..STATE_SLOTS-1, unused by other instances)
 * @return {Promise<{instance: WebAssembly.Instance, base: number}>}
 */
export async function instantiate_relocated(bytes, imports, memory, slot)
{
    const pages = Math.ceil(image_size(bytes) / PAGE_SIZE);
    const base = memory.grow(pages) * PAGE_SIZE;
    imports["env"]["memory"] = memory;
    const { instance } = await WebAssembly.instantiate(relocate(bytes, base, slot), imports);
    return { instance, base };
}
                                     source/v64/src/parallel/vcpu.js                                                                     0000644 0000000 0000000 00000041217 00000000000 013567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A vCPU worker (docs/multicore.md): one
// application processor of a machine whose bootstrap processor and devices
// run on another thread (src/parallel/machine.js).
//
// The worker relocates its own instance of v86-parallel.wasm into the shared
// memory and attaches it to the machine (crate::parallel): guest RAM, the
// local APICs and the IOAPIC are the machine's; the CPU state, TLB, JIT and
// Rust heap are this instance's. Port and device MMIO accesses go to the
// machine through the control block; the worker blocks meanwhile. Its loop
// never returns to the event loop: generated code is compiled synchronously
// and all coordination goes through shared memory.

import { CPU } from "../cpu.js";
import { MachineClock } from "../machine_clock.js";
import { WASM_TABLE_OFFSET, WASM_TABLE_SIZE } from "../const.js";
import { view } from "../lib.js";
import { CORE_STATE_RANGES, INIT_PRESERVED } from "../state_layout.js";
import { relocate } from "./relocate.js";
import { PM_TIMER_TICKS_PER_MS, pm_timer_shared_max } from "../acpi.js";
import { ExtendedStore } from "../extended_memory.js";
import * as C from "./control.js";
import { set_jit_switches } from "../jit_switches.js";
import { run_vcpu_arm } from "./vcpu_arm.js";

const CORE_EVENT_INIT = 1;
const CORE_EVENT_SIPI = 2;

/**
 * @param {Object} init from ParallelMachine.start
 * @param {function(Object)} post message to the machine
 * @param {{exports: Object}} handle receives the instance's exports (for the failure path)
 */
export async function run_vcpu(init, post, handle)
{
    const core = init.core;
    const memory = init.memory;
    const ctrl = new Int32Array(init.control);
    const clock_offset = new Float64Array(init.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_CLOCK_OFFSET, 1);
    const pm_timer_offset = new Float64Array(init.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_PM_TIMER_OFFSET, 1);
    const pm_timer_last = new BigInt64Array(init.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_PM_TIMER_LAST, 1);
    const word = w => C.core_word(core, w);
    const table = new WebAssembly.Table({ "element": "anyfunc", "initial": WASM_TABLE_SIZE + WASM_TABLE_OFFSET });

    let cpu = null, exports = null;
    const extended = init.extended ? new ExtendedStore(init.extended["pages"], init.extended["chunks"], init.extended["touched"]) : null;
    const host_now = () => performance.timeOrigin + performance.now();
    const now = () => host_now() - clock_offset[0];

    // a request the machine performs on the devices' thread
    function request(op, addr, v0 = 0, v1 = 0, v2 = 0, v3 = 0)
    {
        ctrl[word(C.IO_OP)] = op;
        ctrl[word(C.IO_ADDR)] = addr;
        ctrl[word(C.IO_V0)] = v0;
        ctrl[word(C.IO_V1)] = v1;
        ctrl[word(C.IO_V2)] = v2;
        ctrl[word(C.IO_V3)] = v3;
        Atomics.store(ctrl, word(C.IO_STATE), C.IO_REQUEST);
        Atomics.add(ctrl, C.DOORBELL, 1);
        Atomics.notify(ctrl, C.DOORBELL);
        // the machine's core leaves its slice to serve it
        exports["parallel_kick"](0);
        while(Atomics.load(ctrl, word(C.IO_STATE)) === C.IO_REQUEST)
        {
            Atomics.wait(ctrl, word(C.IO_STATE), C.IO_REQUEST, 1000);
            if(Atomics.load(ctrl, C.SHUTDOWN)) throw new Error("machine shut down during I/O");
        }
        const result = ctrl[word(C.IO_RESULT)];
        Atomics.store(ctrl, word(C.IO_STATE), C.IO_IDLE);
        return result;
    }

    // Ports this worker serves itself: the ACPI PM timer (the same ticks the
    // machine's device computes from the shared clock, see
    // ACPI.prototype.share_timer) and the POST port 0x80, which ignores writes
    function read32(port)
    {
        const pm_base = ctrl[C.PM_BASE];
        if(pm_base >= 0 && port === pm_base + 8)
        {
            const ticks = Math.floor(cpu.clock.now() * PM_TIMER_TICKS_PER_MS) + pm_timer_offset[0];
            return pm_timer_shared_max(pm_timer_last, ticks) & 0xFFFFFF;
        }
        return request(C.OP_IN32, port);
    }

    const env = {
        "memory": memory,
        "__indirect_function_table": table,
        "cpu_exception_hook": () => false,
        "run_hardware_timers": (acpi_enabled, t) => acpi_enabled ? exports["apic_timer"](t) : 100,
        "cpu_event_halt": () => {},
        "abort": () => { throw new Error("abort from vCPU " + core); },
        "microtick": () => cpu ? cpu.clock.now() : now(),
        "get_rand_int": () => Math.random() * 0x100000000 | 0,
        "stop_idling": () => {},
        // (cores built before the wide-native path was removed import it)
        "x64_native_discard": () => {},
        "jit_publish": (client, id, slot, pointer, length) => cpu.jit_publish(client, id, slot, pointer, length),
        "io_port_read8": port => request(C.OP_IN8, port),
        "io_port_read16": port => request(C.OP_IN16, port),
        "io_port_read32": read32,
        "io_port_write8": (port, value) => { if(port !== 0x80) request(C.OP_OUT8, port, value); },
        "io_port_write16": (port, value) => { request(C.OP_OUT16, port, value); },
        "io_port_write32": (port, value) => { request(C.OP_OUT32, port, value); },
        "mmap_read8": addr => request(C.OP_MMIO_READ8, addr),
        "mmap_read32": addr => request(C.OP_MMIO_READ32, addr),
        "mmap_write8": (addr, value) => { request(C.OP_MMIO_WRITE8, addr, value); },
        "mmap_write16": (addr, value) => { request(C.OP_MMIO_WRITE16, addr, value); },
        "mmap_write32": (addr, value) => { request(C.OP_MMIO_WRITE32, addr, value); },
        "mmap_write64": (addr, v0, v1) => { request(C.OP_MMIO_WRITE64, addr, v0, v1); },
        "mmap_write128": (addr, v0, v1, v2, v3) => { request(C.OP_MMIO_WRITE128, addr, v0, v1, v2, v3); },
        "log_from_wasm": (offset, length) => {
            const bytes = new Uint8Array(memory.buffer, offset >>> 0, length >>> 0).slice();
            if(init.log) console.log("[vCPU " + core + "] " + new TextDecoder().decode(bytes));
        },
        "console_log_from_wasm": (offset, length) => {
            const bytes = new Uint8Array(memory.buffer, offset >>> 0, length >>> 0).slice();
            console.error("[vCPU " + core + "] " + new TextDecoder().decode(bytes));
        },
        "dbg_trace_from_wasm": () => {},
        "jit_clear_func": index => cpu.jit_clear_func(index),
        "parallel_notify": address => { Atomics.notify(new Int32Array(memory.buffer), address >>> 2); },
        // the machine's extended RAM store (src/extended_memory.js)
        "extended_load": (page, pointer) => { extended.load(page, memory, pointer); },
        "extended_store": (page, pointer) => { extended.store(page, memory, pointer); },
    };

    const { instance } = await WebAssembly.instantiate(relocate(new Uint8Array(init.bytes), init.base, core), { "env": env });
    exports = handle.exports = instance.exports;
    exports["rust_init"]();
    exports["parallel_attach"](init.base, core);

    const bus = { send() {}, register() {}, pair: null };
    cpu = new CPU(bus, { exports, wasm_table: table }, () => {});
    cpu.clock = new MachineClock({ now });
    const settings = init.settings;
    cpu.configure_jit_backend(settings);
    // no event loop in this worker: install generated code synchronously
    cpu.ir_sync_publication = true;
    // (the CPU profile, CPUID level and x64 capabilities, is the machine's:
    // crate::cpu::cpu::copy_machine_configuration)
    exports["set_x87_fast_math"]?.(settings["x87_fast_math"] !== false);
    exports["set_x87_jit_cache"]?.(settings["x87_jit_cache"] !== false);
    // the machine's JIT switches (src/browser/starter.js), over what
    // configure_jit_backend set; later changes arrive through
    // crate::jit_switches::copy_from_machine
    set_jit_switches(exports, memory, settings["jit_switches"], "jit_switches (from the machine)");
    cpu.mem8 = view(Uint8Array, memory, init.mem8, init.memory_size);
    cpu.mem32s = view(Uint32Array, memory, init.mem8, init.memory_size >> 2);
    exports["parallel_set_active"](true);
    exports["parallel_idle"](true);
    cpu.reset_cpu();
    exports["context_reset"](core);
    const reset_state = cpu.save_core_state();
    let running = false;

    ctrl[word(C.STATE_BASE)] = cpu.state_base;
    Atomics.store(ctrl, word(C.STATUS), C.STATUS_WAIT_SIPI);
    post({ "type": "ready", "core": core, "state_base": cpu.state_base });

    // INIT and start-up IPIs for this core (CPU.prototype.take_core_events)
    function take_core_events()
    {
        const events = exports["apic_take_core_events"](core);
        if(!events) return;
        if(events & CORE_EVENT_INIT)
        {
            if(exports["exception_shutdown"](core) === 2) return;
            exports["apic_init_core"](core);
            exports["context_reset"](core);
            const next = reset_state.map(bytes => bytes.slice());
            const current = cpu.save_core_state();
            for(const [offset, size] of INIT_PRESERVED)
            {
                const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
                const at = offset - CORE_STATE_RANGES[index][0];
                next[index].set(current[index].subarray(at, at + size), at);
            }
            cpu.load_core_state(next);
            running = false;
        }
        if((events & CORE_EVENT_SIPI) && !running)
        {
            const vector = events >> 8 & 0xFF;
            cpu.sreg[1] = vector << 8;
            cpu.segment_offsets[1] = vector << 12;
            cpu.instruction_pointer[0] = vector << 12;
            cpu.previous_ip[0] = vector << 12;
            cpu.update_state_flags();
            running = true;
        }
        Atomics.store(ctrl, word(C.RUNNING), running ? 1 : 0);
    }

    // a safe point: the machine stops every core for a snapshot, reset or pause
    function park(epoch)
    {
        exports["fpu_cache_barrier"]();
        ctrl[word(C.TSC_OFFSET_LO)] = exports["parallel_tsc_offset"](false);
        ctrl[word(C.TSC_OFFSET_HI)] = exports["parallel_tsc_offset"](true);
        Atomics.store(ctrl, word(C.RUNNING), running ? 1 : 0);
        Atomics.store(ctrl, word(C.STATUS), C.STATUS_PARKED);
        exports["parallel_idle"](true);
        Atomics.store(ctrl, word(C.ACK), epoch);
        Atomics.add(ctrl, C.DOORBELL, 1);
        Atomics.notify(ctrl, C.DOORBELL);
        for(;;)
        {
            const resumed = Atomics.load(ctrl, C.RESUME);
            if(resumed >= epoch || Atomics.load(ctrl, C.SHUTDOWN)) break;
            Atomics.wait(ctrl, C.RESUME, resumed, 1000);
        }
        if(Atomics.load(ctrl, C.SHUTDOWN)) return;
        // (the machine's clock as resume() synchronized it: after a restore
        // into a new machine this core's own clock, which only goes on by
        // at most a second per reading, would stay behind it for good; as
        // vcpu_arm.js)
        cpu.clock.set_time(now());
        const command = Atomics.load(ctrl, C.COMMAND);
        if(command === C.COMMAND_RESET)
        {
            // machine reset or power-on: back to waiting for INIT/SIPI
            exports["jit_clear_cache_js"]();
            cpu.reset_cpu();
            exports["context_reset"](core);
            cpu.load_core_state(reset_state.map(bytes => bytes.slice()));
            running = false;
        }
        else if(command === C.COMMAND_RELOAD)
        {
            // the machine replaced this core's state and RAM (snapshot restore)
            exports["jit_clear_cache_js"]();
            exports["context_reset"](core);
            exports["parallel_set_tsc_offset"](ctrl[word(C.TSC_OFFSET_LO)], ctrl[word(C.TSC_OFFSET_HI)]);
            exports["fpu_discard_cache"]();
            cpu.full_clear_tlb();
            cpu.update_state_flags();
            running = Atomics.load(ctrl, word(C.RUNNING)) !== 0;
        }
        else if(command === C.COMMAND_FLUSH)
        {
            exports["context_reset_translations"]?.(core);
            cpu.full_clear_tlb();
        }
        exports["parallel_sync"]();
        exports["parallel_idle"](false);
        Atomics.store(ctrl, word(C.RUNNING), running ? 1 : 0);
        Atomics.store(ctrl, word(C.STATUS), running ? C.STATUS_RUNNING : C.STATUS_WAIT_SIPI);
    }

    const wake = new Int32Array(memory.buffer);
    const wake_index = exports["parallel_wake_addr"](core) >>> 2;
    // (a slice as long as the BSP's main-loop batch, LOOP_COUNTER: kicks end
    // it early, and run_cpu_slice acknowledges other cores' code
    // publications between entries as the BSP's loop does; what this loop
    // does per slice cost a float benchmark 2% at 20000)
    const quantum = settings.cpu_quantum || 100000;
    // test hook (tests/parallel/lifecycle.mjs): this core fails after some slices
    const fault = settings["parallel_fault"];
    const faulty = fault && fault["core"] === core;
    let acked = Atomics.load(ctrl, C.STOP);
    let steps = 0;
    let jit_entries = 0, last_entries = 0;

    for(;;)
    {
        if(Atomics.load(ctrl, C.SHUTDOWN)) break;
        const stop = Atomics.load(ctrl, C.STOP);
        if(stop !== acked)
        {
            park(stop);
            acked = stop;
            continue;
        }
        const seen = Atomics.load(wake, wake_index);
        take_core_events();
        if(!running)
        {
            Atomics.store(ctrl, word(C.STATUS), C.STATUS_WAIT_SIPI);
            exports["parallel_idle"](true);
            Atomics.wait(wake, wake_index, seen, 100);
            exports["parallel_idle"](false);
            continue;
        }
        // compiled code: other cores' publications and code writes
        exports["parallel_poll"]();
        const now = cpu.clock.now();
        const next_timer = exports["apic_timer"](now);
        const retired = cpu.run_cpu_slice(quantum);
        steps = steps + retired | 0;
        ctrl[word(C.STEPS)] = steps;
        ctrl[word(C.SLICES)]++;
        // (cumulative: a reset or restore clears the page tier's own
        // counters; its functions' entries)
        const entries = exports["x64_page_stat"](6) >>> 0;
        jit_entries += entries >= last_entries ? entries - last_entries : entries;
        last_entries = entries;
        ctrl[word(C.JIT_ENTRIES)] = jit_entries;
        ctrl[word(C.REFUSED)] = exports["parallel_code_stat"](0);
        if(faulty && ctrl[word(C.SLICES)] >= fault["after_slices"])
        {
            if(fault["kind"] === "trap") exports["parallel_test_fault"]();
            if(fault["kind"] === "exit") typeof process !== "undefined" ? process.exit(3) : globalThis.close();
            throw new Error("injected fault");
        }
        if(cpu.in_hlt[0])
        {
            exports["handle_irqs"]();
            if(cpu.in_hlt[0] && !exports["apic_peek_core_events"](core))
            {
                Atomics.store(ctrl, word(C.STATUS), C.STATUS_HALTED);
                ctrl[word(C.WAITS)]++;
                exports["parallel_idle"](true);
                Atomics.wait(wake, wake_index, seen, Math.max(0, Math.min(next_timer, 50)));
                exports["parallel_idle"](false);
            }
        }
        Atomics.store(ctrl, word(C.STATUS), C.STATUS_RUNNING);
    }
    Atomics.store(ctrl, word(C.STATUS), C.STATUS_EXITED);
    post({ "type": "exited", "core": core });
}

/** Worker entry: the first message starts the core */
export function start_vcpu_worker()
{
    const node = typeof process !== "undefined" && process.versions && process.versions.node;
    const start = async (init, post) => {
        const handle = { exports: null };
        try
        {
            // (the ARM core's workers: P8.2; arm32's too)
            await (init["cpu_type"] === "arm64" || init["cpu_type"] === "arm32" ? run_vcpu_arm : run_vcpu)(init, post, handle);
        }
        catch(error)
        {
            // release the machine's locks this core held before anyone waits for it
            try { handle.exports?.["parallel_fail"](); } catch(e) { /* the instance may be unusable */ }
            const ctrl = new Int32Array(init.control);
            Atomics.store(ctrl, C.core_word(init.core, C.ERROR), 1);
            Atomics.store(ctrl, C.core_word(init.core, C.STATUS), C.STATUS_FAILED);
            Atomics.add(ctrl, C.DOORBELL, 1);
            Atomics.notify(ctrl, C.DOORBELL);
            try { handle.exports?.["parallel_kick"](0); } catch(e) { /* the instance may be unusable */ }
            post({ "type": "error", "core": init.core, "message": String(error && error.stack || error) });
        }
    };
    if(node)
    {
        import("node:" + "worker_threads").then(({ parentPort }) => {
            parentPort.once("message", init => start(init, message => parentPort.postMessage(message)));
        });
    }
    else
    {
        const first = e => {
            globalThis.removeEventListener("message", first);
            start(e.data, message => globalThis.postMessage(message));
        };
        globalThis.addEventListener("message", first);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                 source/v64/src/parallel/vcpu_arm.js                                                                 0000644 0000000 0000000 00000025424 00000000000 014430  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A vCPU worker of the ARM core (docs/arm64-virt-android16-plan.md P8.2;
// the x86 one is src/parallel/vcpu.js): one core of a virt machine whose
// core 0 and devices run on another thread (src/parallel/machine.js).
//
// The worker relocates its own instance of v86-arm64-parallel.wasm into the
// shared memory and attaches it to the machine: guest RAM, the GIC, PSCI's
// power states, the exclusive monitor and the machine's map are the
// machine's (src/rust/aarch64/isa_hooks.rs); the core's state block, TLB, page
// tier and Rust heap are this instance's. The core is off until PSCI CPU_ON
// (another core's call) turns it on; device register accesses go to the
// machine through the control block while the worker waits. Its loop never
// returns to the event loop: generated code is compiled synchronously and
// all coordination goes through shared memory.

import { A64CPU } from "../arm/cpu.js";
import { MachineClock } from "../machine_clock.js";
import { WASM_TABLE_OFFSET, WASM_TABLE_SIZE } from "../const.js";
import { relocate } from "./relocate.js";
import { ExtendedStore } from "../extended_memory.js";
import * as C from "./control.js";
import { set_jit_switches } from "../jit_switches.js";

/**
 * @param {Object} init from ParallelMachine.start
 * @param {function(Object)} post message to the machine
 * @param {{exports: Object}} handle receives the instance's exports (for the failure path)
 */
export async function run_vcpu_arm(init, post, handle)
{
    const core = init.core;
    const memory = init.memory;
    const ctrl = new Int32Array(init.control);
    const clock_offset = new Float64Array(init.control, C.CONTROL_WORDS * 4 + 8 * C.SLOT_CLOCK_OFFSET, 1);
    const word = w => C.core_word(core, w);
    const table = new WebAssembly.Table({ "element": "anyfunc", "initial": WASM_TABLE_SIZE + WASM_TABLE_OFFSET });

    let cpu = null, exports = null;
    const extended = init.extended ? new ExtendedStore(init.extended["pages"], init.extended["chunks"], init.extended["touched"]) : null;
    const host_now = () => performance.timeOrigin + performance.now();
    const now = () => host_now() - clock_offset[0];

    // A posted request (an MMIO write) not waited for yet: the next request,
    // and a park, wait for it first, so this core's device accesses stay in
    // order and a stopped machine has done them all
    let posted = false;
    function settle()
    {
        if(!posted) return;
        posted = false;
        while(Atomics.load(ctrl, word(C.IO_STATE)) === C.IO_REQUEST)
        {
            Atomics.wait(ctrl, word(C.IO_STATE), C.IO_REQUEST, 1000);
            if(Atomics.load(ctrl, C.SHUTDOWN)) throw new Error("machine shut down during I/O");
        }
        Atomics.store(ctrl, word(C.IO_STATE), C.IO_IDLE);
    }
    // a request the machine performs on the devices' thread: the result's low
    // 32 bits (IO_RESULT_HI the high); `post`: the result is not needed, the
    // core goes on (MMIO writes are posted, as PCIe's)
    function request(op, addr, v0 = 0, v1 = 0, v2 = 0, v3 = 0, post = false)
    {
        settle();
        ctrl[word(C.IO_OP)] = op;
        ctrl[word(C.IO_ADDR)] = addr;
        ctrl[word(C.IO_V0)] = v0;
        ctrl[word(C.IO_V1)] = v1;
        ctrl[word(C.IO_V2)] = v2;
        ctrl[word(C.IO_V3)] = v3;
        Atomics.store(ctrl, word(C.IO_STATE), C.IO_REQUEST);
        Atomics.add(ctrl, C.DOORBELL, 1);
        Atomics.notify(ctrl, C.DOORBELL);
        // the machine's core leaves its slice to serve it
        exports["parallel_kick"](0);
        if(post)
        {
            posted = true;
            return 0;
        }
        while(Atomics.load(ctrl, word(C.IO_STATE)) === C.IO_REQUEST)
        {
            Atomics.wait(ctrl, word(C.IO_STATE), C.IO_REQUEST, 1000);
            if(Atomics.load(ctrl, C.SHUTDOWN)) throw new Error("machine shut down during I/O");
        }
        const result = ctrl[word(C.IO_RESULT)];
        Atomics.store(ctrl, word(C.IO_STATE), C.IO_IDLE);
        return result;
    }
    const halves = value => {
        const v = BigInt.asUintN(64, BigInt(value));
        return [Number(v & 0xFFFFFFFFn) | 0, Number(v >> 32n) | 0];
    };

    const env = {
        "memory": memory,
        "__indirect_function_table": table,
        "microtick": () => cpu ? cpu.clock.now() : now(),
        // a device register of the virt machine (src/virt/io.js), on the machine's thread
        "a64_mmio_read": (owner, offset, width) => {
            const [low, high] = halves(offset);
            const result = request(C.OP_A64_MMIO_READ, owner | width << 24, low, high);
            return BigInt(result >>> 0) | BigInt(ctrl[word(C.IO_RESULT_HI)] >>> 0) << 32n;
        },
        "a64_mmio_write": (owner, offset, width, value) => {
            const [low, high] = halves(offset);
            const [value_low, value_high] = halves(value);
            request(C.OP_A64_MMIO_WRITE, owner | width << 24, low, high, value_low, value_high, true);
        },
        "jit_publish": (client, id, slot, pointer, length) => cpu.jit_publish(client, id, slot, pointer, length),
        "jit_clear_func": index => cpu.jit_clear_func(index),
        // (the GLES backdoor needs the calling core's page tables: the cores
        // are cooperative where it is used; here its UDF stays undefined)
        "a32_backdoor": () => -0x80000000,
        "parallel_notify": address => { Atomics.notify(new Int32Array(memory.buffer), address >>> 2); },
        // the machine's extended RAM store (src/extended_memory.js)
        "extended_load": (page, pointer) => { extended.load(page, memory, pointer); },
        "extended_store": (page, pointer) => { extended.store(page, memory, pointer); },
        "console_log_from_wasm": (offset, length) => {
            const bytes = new Uint8Array(memory.buffer, offset >>> 0, length >>> 0).slice();
            console.error("[vCPU " + core + "] " + new TextDecoder().decode(bytes));
        },
    };

    const { instance } = await WebAssembly.instantiate(relocate(new Uint8Array(init.bytes), init.base, core), { "env": env });
    exports = handle.exports = instance.exports;
    exports["rust_init"]();
    exports["parallel_attach"](init.base, core);

    cpu = new A64CPU({ send() {}, register() {}, pair: null }, { exports, wasm_table: table }, () => {});
    cpu.clock = new MachineClock({ now });
    // no event loop in this worker: install generated code synchronously
    cpu.ir_sync_publication = true;
    const settings = init.settings;
    // the machine's JIT switches (src/browser/starter.js)
    set_jit_switches(exports, memory, settings["jit_switches"], "jit_switches (from the machine)");
    exports["parallel_set_active"](true);
    exports["parallel_idle"](true);

    ctrl[word(C.STATE_BASE)] = cpu.state_base;
    Atomics.store(ctrl, word(C.STATUS), C.STATUS_WAIT_SIPI);
    post({ "type": "ready", "core": core, "state_base": cpu.state_base });

    const publish_counters = () => {
        const retired = exports["core_statistics_get"](core, 0);
        ctrl[word(C.STEPS)] = retired % 0x100000000 | 0;
        ctrl[word(C.STEPS_HI)] = Math.floor(retired / 0x100000000) | 0;
        // (the instructions its page tier retired, cumulative while no reset clears them; installations given up)
        ctrl[word(C.JIT_ENTRIES)] = exports["jit_stat"](1, 2) % 0x100000000 | 0;
        ctrl[word(C.REFUSED)] = exports["parallel_code_stat"](0);
        // (diagnostics: TLB maintenance posted, DSBs that waited, entries taken; runs a kick ended)
        for(let i = 0; i < 3; i++) ctrl[word(C.RING_STATS + i)] = exports["a64_tlb_ring_stat"](i);
        ctrl[word(C.KICKED)] = exports["a64_kicked"]();
    };

    // a safe point: the machine stops every core for a snapshot, a reset or a pause
    function park(epoch)
    {
        settle();
        publish_counters();
        Atomics.store(ctrl, word(C.STATUS), C.STATUS_PARKED);
        exports["parallel_idle"](true);
        Atomics.store(ctrl, word(C.ACK), epoch);
        Atomics.add(ctrl, C.DOORBELL, 1);
        Atomics.notify(ctrl, C.DOORBELL);
        for(;;)
        {
            const resumed = Atomics.load(ctrl, C.RESUME);
            if(resumed >= epoch || Atomics.load(ctrl, C.SHUTDOWN)) break;
            Atomics.wait(ctrl, C.RESUME, resumed, 1000);
        }
        if(Atomics.load(ctrl, C.SHUTDOWN)) return;
        // (the machine's clock as resume() synchronized it: after a restore
        // into a new machine this core's own clock, which only goes on by
        // at most a second per reading, would stay behind it for good)
        cpu.clock.set_time(now());
        const command = Atomics.load(ctrl, C.COMMAND);
        if(command === C.COMMAND_RESET || command === C.COMMAND_RELOAD)
        {
            // (a reset: the core is off until CPU_ON again, a64_boot set that;
            // a restore: the machine wrote this core's state block)
            exports["jit_clear_cache_js"]();
            exports["a64_worker_restored"]();
        }
        exports["parallel_sync"]();
        exports["parallel_idle"](false);
    }

    const wake = new Int32Array(memory.buffer);
    const wake_index = exports["parallel_wake_addr"](core) >>> 2;
    const quantum = settings.cpu_quantum || 20000;
    // test hook (tests/parallel/lifecycle.mjs): this core fails after some slices
    const fault = settings["parallel_fault"];
    const faulty = fault && fault["core"] === core;
    let acked = Atomics.load(ctrl, C.STOP);

    for(;;)
    {
        if(Atomics.load(ctrl, C.SHUTDOWN)) break;
        const stop = Atomics.load(ctrl, C.STOP);
        if(stop !== acked)
        {
            park(stop);
            acked = stop;
            continue;
        }
        const seen = Atomics.load(wake, wake_index);
        // (its code writes, publications and TLB maintenance first, then up to `quantum` instructions)
        const ms = exports["a64_worker_slice"](quantum);
        ctrl[word(C.SLICES)]++;
        if((ctrl[word(C.SLICES)] & 63) === 0) publish_counters();
        Atomics.store(ctrl, word(C.RUNNING), ms >= 0 ? 1 : 0);
        if(faulty && ctrl[word(C.SLICES)] >= fault["after_slices"])
        {
            if(fault["kind"] === "trap") exports["parallel_test_fault"]();
            if(fault["kind"] === "exit") typeof process !== "undefined" ? process.exit(3) : globalThis.close();
            throw new Error("injected fault");
        }
        if(ms !== 0)
        {
            // off (until CPU_ON), or waiting (WFI, WFE) until its timers or a kick
            Atomics.store(ctrl, word(C.STATUS), ms < 0 ? C.STATUS_WAIT_SIPI : C.STATUS_HALTED);
            ctrl[word(C.WAITS)]++;
            exports["parallel_idle"](true);
            Atomics.wait(wake, wake_index, seen, ms < 0 ? 100 : Math.min(ms, 50));
            exports["parallel_idle"](false);
        }
        Atomics.store(ctrl, word(C.STATUS), C.STATUS_RUNNING);
    }
    Atomics.store(ctrl, word(C.STATUS), C.STATUS_EXITED);
    post({ "type": "exited", "core": core });
}
                                                                                                                                                                                                                                            source/v64/src/parallel/vcpu_worker_entry.js                                                        0000644 0000000 0000000 00000000104 00000000000 016367  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { start_vcpu_worker } from "./vcpu.js";
start_vcpu_worker();
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/pci.js                                                                               0000644 0000000 0000000 00000167564 00000000000 011607  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_PCI } from "./const.js";
import { QEMU_PCI_SUBSYSTEM, RESET_PORT } from "./platform.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";

// http://wiki.osdev.org/PCI
//
// Configuration space is reached through the address/data ports 0xCF8/0xCFC
// (mechanism #1) and, on Q35, through the memory-mapped ECAM window. Both go
// through config_read/config_write, which give the header registers their
// semantics (read-only fields, write-one-to-clear status bits, BARs); the
// device-specific part (0x40 and above) is plain storage plus the device's
// on_config_write callback.
//
// Buses behind PCI-to-PCI bridges (the PCI Express root ports of Q35): a
// function's pci_id is its place, bus 0 or a bridge's secondary bus by the
// number the machine gave that bus when it was built (a bridge's
// pci_secondary_bus), << 8 | device << 3 | function. The bus numbers the
// guest sees are the ones it programs into the bridges; configuration
// accesses are routed by them (route_config). A bridge forwards memory and
// I/O accesses within its windows while its decode is enabled, bus master
// requests (DMA, MSI) while its bus mastering is enabled, and interrupt pins
// with the swizzle of the PCI-to-PCI bridge specification. Devices behind a
// bridge take decode and DMA from memory_decoded, upstream_forwards_memory and
// is_bus_master, and hear of changes upstream by on_upstream_change; their I/O
// BARs are mapped only where the bridges forward them.
//
// The virt machine's generic PCIe host bridge (`generic`,
// docs/arm64-virt-android16-plan.md P5.6, P5.10) is the same bus without the
// PC's parts: configuration through ECAM only (ecam_handler, no 0xCF8/0xCFC
// and no reset control register), no i440FX; INTx to the GIC (an SPI per pin
// and slot, level-triggered); memory BARs decoded only while their memory
// space is enabled, reached through the bridge's windows (window_handler),
// also above 4 GiB: a BAR may be 64 bits wide (bits64, the next BAR register
// its upper half). A reset gives every function its power-on configuration.

export const PCI_CONFIG_ADDRESS = 0xCF8;
export const PCI_CONFIG_DATA = 0xCFC;

// Command register bits that have an effect, and those a guest can change
export const PCI_COMMAND_IO = 1 << 0;
export const PCI_COMMAND_MEMORY = 1 << 1;
export const PCI_COMMAND_MASTER = 1 << 2;
export const PCI_COMMAND_INTX_DISABLE = 1 << 10;
const PCI_COMMAND_WRITABLE = PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
    1 << 6 | 1 << 8 | PCI_COMMAND_INTX_DISABLE; // (and parity / SERR# response)

// Status register: interrupt status is read-only, the error bits are
// cleared by writing one
const PCI_STATUS_INTERRUPT = 1 << 3;
const PCI_STATUS_RW1C = 0xF900;

/** Capability ID of MSI (PCI Local Bus 3.0, 6.8.1) */
export const PCI_CAP_MSI = 0x05;
const MSI_CONTROL_ENABLE = 1 << 0;
const MSI_CONTROL_64BIT = 1 << 7;

/**
 * An MSI capability with one message and 64-bit addresses: ID, next,
 * message control, address (low, high), data
 * @param {number} next the next capability's offset, or 0
 * @return {!Array<number>}
 */
export function msi_capability(next)
{
    return [PCI_CAP_MSI, next, MSI_CONTROL_64BIT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
}

/**
 * Bytes of the type 0 header (0x00-0x3F) a guest may write as plain storage;
 * everything else in the header is read-only or handled specially (command,
 * status, BARs, expansion ROM)
 * @param {number} offset
 * @return {boolean}
 */
function header_byte_writable(offset)
{
    return offset === 0x0C || offset === 0x0D || offset === 0x0F || offset === 0x3C;
}

// The type 1 header of a PCI-to-PCI bridge (PCI-to-PCI Bridge Architecture 1.2, 3.2)
const PCI_HEADER_TYPE_BRIDGE = 1;
const BRIDGE_SECONDARY_BUS = 0x19;
const BRIDGE_SUBORDINATE_BUS = 0x1A;
const BRIDGE_IO_BASE = 0x1C;
const BRIDGE_IO_LIMIT = 0x1D;
const BRIDGE_SECONDARY_STATUS = 0x1E;
const BRIDGE_MEMORY_BASE = 0x20;
const BRIDGE_MEMORY_LIMIT = 0x22;
const BRIDGE_PREFETCH_BASE = 0x24;
const BRIDGE_PREFETCH_LIMIT = 0x26;
const BRIDGE_PREFETCH_BASE_UPPER = 0x28;
const BRIDGE_PREFETCH_LIMIT_UPPER = 0x2C;
const BRIDGE_CONTROL = 0x3E;
const BRIDGE_CONTROL_ISA = 1 << 2;

/**
 * Writable bits of the type 1 header bytes 0x18-0x3F: bus numbers, secondary
 * latency timer, I/O (16-bit decode), memory and prefetchable (64-bit)
 * windows, interrupt line, bridge control (parity and SERR# response, ISA,
 * VGA, VGA 16-bit decode, secondary bus reset). The secondary status is
 * write-one-to-clear; the rest is read-only (no BARs beyond 0x10-0x17, no
 * expansion ROM).
 */
const BRIDGE_HEADER_WRITABLE = new Uint8Array(0x40);
BRIDGE_HEADER_WRITABLE.fill(0xFF, 0x18, 0x1C);
BRIDGE_HEADER_WRITABLE[BRIDGE_IO_BASE] = BRIDGE_HEADER_WRITABLE[BRIDGE_IO_LIMIT] = 0xF0;
BRIDGE_HEADER_WRITABLE.set([0xF0, 0xFF, 0xF0, 0xFF, 0xF0, 0xFF, 0xF0, 0xFF], BRIDGE_MEMORY_BASE);
BRIDGE_HEADER_WRITABLE.fill(0xFF, BRIDGE_PREFETCH_BASE_UPPER, BRIDGE_PREFETCH_LIMIT_UPPER + 4);
BRIDGE_HEADER_WRITABLE[0x3C] = 0xFF;
BRIDGE_HEADER_WRITABLE[BRIDGE_CONTROL] = 0x5F;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {{generic: boolean}=} options generic: the virt machine's generic PCIe host bridge
 */
export function PCI(cpu, options)
{
    /** the virt machine's generic PCIe host bridge (P5.6) */
    this.generic = !!(options && options.generic);

    this.pci_addr = new Uint8Array(4);
    // (pci_value, pci_response and pci_status are no longer used; they stay
    // for the layout of state images)
    this.pci_value = new Uint8Array(4);
    this.pci_response = new Uint8Array(4);
    this.pci_status = new Uint8Array(4);

    this.pci_addr32 = new Int32Array(this.pci_addr.buffer);

    /**
     * Configuration spaces by bdf (bus << 8 | device << 3 | function): 64
     * dwords (conventional PCI) or 1024 (PCI Express extended space)
     * @type {!Array<Int32Array|undefined>}
     */
    this.device_spaces = [];
    this.devices = [];

    /**
     * The IRQ line each function has asserted, by pci_id
     * @type {!Array<number|undefined>}
     */
    this.asserted_irq_lines = [];

    /**
     * The IOAPIC-only input (GSI) each function has asserted (Q35)
     * @type {!Array<number|undefined>}
     */
    this.asserted_gsis = [];

    /**
     * The level each function drives on its interrupt pin, before INTx Disable
     * @type {!Array<boolean|undefined>}
     */
    this.intx_levels = [];

    /** @const @type {CPU} */
    this.cpu = cpu;

    for(var i = 0; i < 256; i++)
    {
        this.device_spaces[i] = undefined;
        this.devices[i] = undefined;
    }

    this.io = cpu.io;

    /**
     * Where the chipset connects interrupt pin (0-3: INTA-D) of a function on
     * bus 0: an ISA IRQ for the PIC (bit 7 set: not routed) and an
     * IOAPIC-only input (GSI 16-23 on Q35, -1 when the IOAPIC sees the pin
     * through the ISA IRQ, as on i440FX). Pins behind bridges arrive here as
     * the pin of their bridge on bus 0 (root_pin). Replaced by the chipset;
     * the default is the PIIX3 PIRQ routing.
     * @type {function(number, number):{pic: number, gsi: number}}
     */
    this.irq_route = (pci_id, pin) => ({ pic: this.piix_pirq_line(pci_id, pin), gsi: -1 });
    if(this.generic)
    {
        // (the reference's interrupt-map: pin p (0-3) of slot s is SPI 3 +
        // (p + s) % 4, INTID 32 + that; not a PIC line, bit 7)
        this.irq_route = (pci_id, pin) => ({ pic: 0x80, gsi: 32 + 3 + (pin + (pci_id >> 3 & 0x1F) & 3) });
    }

    /**
     * The bridge whose secondary side each bus is, by the bus's number in
     * pci_ids (pci_secondary_bus of the bridge)
     * @type {!Array<number|undefined>}
     */
    this.bridge_for_bus = [];
    /**
     * The bridges on each bus, by the bus's number in pci_ids
     * @type {!Array<!Array<number>|undefined>}
     */
    this.bridges_on = [];

    /** The mapped ECAM window (Q35), or -1 */
    this.ecam_base = -1;
    this.ecam_size = 0;

    /**
     * Functions behind a hot plug slot that are not on the bus (the slot is
     * empty or off, src/pcie_root_port.js), by pci_id: see set_function_present
     * @type {!Array<boolean|undefined>}
     */
    this.absent = [];
    /**
     * The power-on configuration space of each function behind a bridge,
     * which a card plugged into a hot plug slot has again
     * @type {!Array<Int32Array|undefined>}
     */
    this.templates = [];

    /**
     * The generic host's decoded memory BARs: where each is, by its owner
     * (window_handler)
     * @type {!Array<{owner: !Object, base: number, size: number, handler: !Object}>}
     */
    this.memory_decoders = [];

    if(this.generic)
    {
        this.reset_control = 0;
        this.create_generic_host();
        return;
    }

    // Configuration data port. Accesses wider than a byte are one config
    // access each, so that registers keep their access-width semantics.
    const data_port = offset => this.pci_addr32[0] + offset | 0;
    cpu.io.register_read(PCI_CONFIG_DATA, this,
        () => this.config_read_cf8(data_port(0), 1),
        () => this.config_read_cf8(data_port(0), 2),
        () => this.config_read_cf8(data_port(0), 4));
    cpu.io.register_read(PCI_CONFIG_DATA + 1, this,
        () => this.config_read_cf8(data_port(1), 1));
    cpu.io.register_read(PCI_CONFIG_DATA + 2, this,
        () => this.config_read_cf8(data_port(2), 1),
        () => this.config_read_cf8(data_port(2), 2));
    cpu.io.register_read(PCI_CONFIG_DATA + 3, this,
        () => this.config_read_cf8(data_port(3), 1));

    cpu.io.register_write(PCI_CONFIG_DATA, this,
        value => this.config_write_cf8(data_port(0), 1, value),
        value => this.config_write_cf8(data_port(0), 2, value),
        value => this.config_write_cf8(data_port(0), 4, value));
    cpu.io.register_write(PCI_CONFIG_DATA + 1, this,
        value => this.config_write_cf8(data_port(1), 1, value));
    cpu.io.register_write(PCI_CONFIG_DATA + 2, this,
        value => this.config_write_cf8(data_port(2), 1, value),
        value => this.config_write_cf8(data_port(2), 2, value));
    cpu.io.register_write(PCI_CONFIG_DATA + 3, this,
        value => this.config_write_cf8(data_port(3), 1, value));

    // Configuration address register: reads return what was written (bits
    // 1:0 are zero). Byte and word writes update the corresponding bytes; a
    // byte access to 0xCF9 is the reset control register instead.
    cpu.io.register_read_consecutive(PCI_CONFIG_ADDRESS, this,
        () => this.pci_addr[0],
        () => this.pci_addr[1],
        () => this.pci_addr[2],
        () => this.pci_addr[3]);
    cpu.io.register_write_consecutive(PCI_CONFIG_ADDRESS, this,
        out_byte => { this.pci_addr[0] = out_byte & 0xFC; },
        out_byte => { this.pci_addr[1] = out_byte; },
        out_byte => { this.pci_addr[2] = out_byte; },
        out_byte => { this.pci_addr[3] = out_byte; });

    // PIIX/ICH9 reset control register (RCR): byte accesses to 0xCF9 only; word and
    // dword accesses at 0xCF8 are the configuration address. A 0 -> 1
    // transition of RST_CPU (bit 2) resets the machine (the FADT reset
    // register writes 0x06; Linux' reboot=pci writes 0x02, then 0x06).
    this.reset_control = 0;
    cpu.io.register_read(RESET_PORT, this, function()
    {
        return this.reset_control;
    });
    cpu.io.register_write(RESET_PORT, this, function(value)
    {
        const rst_cpu_rising = ~this.reset_control & value & 0x04;
        this.reset_control = value & 0x06;
        if(rst_cpu_rising)
        {
            dbg_log("CPU reboot via PIIX reset control register");
            cpu.reboot_internal("cf9");
        }
    });

    if(cpu.platform.machine === "i440fx")
    {
        this.create_i440fx();
    }
}

/**
 * The i440FX host bridge and the PIIX3 ISA bridge with its PIRQ routing
 * registers (0x60-0x63); the PIIX4 power management function is src/acpi.js
 */
PCI.prototype.create_i440fx = function()
{
    const cpu = this.cpu;

    // This needs to be set in order for seabios to not execute code outside of
    // mapped memory. While we map the BIOS into high memory, we don't allow
    // executing code there, which enables optimisations in read_imm8.
    // See [make_bios_writable_intel] in src/fw/shadow.c in seabios for details
    const PAM0 = 0x10;
    // (the ISA bridge has QEMU's subsystem in its layout; not the host
    // bridge: SeaBIOS takes it for QEMU then, and waits 5 s for something)
    const subsystem = cpu.platform.qemu_compatible ? QEMU_PCI_SUBSYSTEM : [0x00, 0x00, 0x00, 0x00];

    var host_bridge = {
        pci_id: 0,
        pci_space: [
            // 00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
            0x86, 0x80, 0x37, 0x12, 0x00, 0x00, 0x00, 0x00,  0x02, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  0x00, PAM0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
        name: "82441FX PMC",
    };
    this.register_device(host_bridge);

    this.isa_bridge = {
        pci_id: 1 << 3,
        pci_space: [
            // 00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
            0x86, 0x80, 0x00, 0x70, 0x07, 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x80, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ...subsystem,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ],
        pci_bars: [],
        name: "82371SB PIIX3 ISA",
    };
    this.isa_bridge_space = this.register_device(this.isa_bridge);
    this.isa_bridge_space8 = new Uint8Array(this.isa_bridge_space.buffer);
};

/**
 * The generic host's function 00:00.0, QEMU's gpex-root ("QEMU PCIe Host
 * bridge"): its configuration as the reference's (tests/a64/linux_boot.mjs's
 * pci variant compares them)
 */
PCI.prototype.create_generic_host = function()
{
    const space = new Array(64).fill(0);
    space.splice(0, 12, 0x36, 0x1B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06);
    space.splice(0x2C, 4, 0xF4, 0x1A, 0x00, 0x11);
    this.register_device({ pci_id: 0, pci_space: space, pci_bars: [], name: "gpex-root" });
};

/** Machine reset (the generic host: every function's power-on configuration, reset_functions) */
PCI.prototype.reset = function()
{
    this.reset_control = 0;
    if(this.generic)
    {
        this.reset_functions();
    }
};

/**
 * The generic host's functions get their power-on configuration (a machine
 * reset): their BARs unassigned (where the template has them), no
 * interrupt asserted; the devices reset themselves
 */
PCI.prototype.reset_functions = function()
{
    this.devices.forEach((device, pci_id) => {
        const template = this.templates[pci_id];
        if(!device || !template) return;
        if(this.intx_levels[pci_id])
        {
            this.set_irq_level(pci_id, false);
        }
        this.device_spaces[pci_id].set(template);
        device.pci_bars.forEach((bar, i) => {
            if(bar && bar.on_move && !(template[(0x10 >> 2) + i] & 1))
            {
                this.move_memory_bar(bar, this.bar_base(template, i, bar));
            }
        });
        device.on_config_restore && device.on_config_restore();
    });
};

/**
 * Where a memory BAR's registers in `space` put it (both halves of a 64-bit one)
 * @param {!Int32Array} space
 * @param {number} bar_nr
 * @param {Object} bar
 * @return {number}
 */
PCI.prototype.bar_base = function(space, bar_nr, bar)
{
    const low = (space[(0x10 >> 2) + bar_nr] & ~0xF) >>> 0;
    return bar.bits64 ? (space[(0x10 >> 2) + bar_nr + 1] >>> 0) * 0x100000000 + low : low;
};

PCI.prototype.get_state = function()
{
    var state = [];

    for(var i = 0; i < 256; i++)
    {
        state[i] = this.device_spaces[i];
    }

    state[256] = this.pci_addr;
    state[257] = this.pci_value;
    state[258] = this.pci_response;
    state[259] = this.pci_status;
    state[260] = this.reset_control;
    // functions behind bus 0 (bdf >= 256)
    state[261] = this.device_spaces.map((space, bdf) => bdf >= 256 && space ? [bdf, space] : undefined).filter(e => e);
    // levels and routed lines of the interrupt pins
    state[262] = this.intx_levels.map((level, pci_id) => level ? pci_id : -1).filter(id => id >= 0);
    state[263] = this.asserted_irq_lines.map((irq, pci_id) => irq === undefined ? undefined : [pci_id, irq]).filter(e => e);
    state[264] = this.asserted_gsis.map((gsi, pci_id) => gsi === undefined ? undefined : [pci_id, gsi]).filter(e => e);
    // functions of empty or switched-off hot plug slots
    state[265] = this.absent.map((absent, pci_id) => absent ? pci_id : -1).filter(id => id >= 0);

    return state;
};

PCI.prototype.set_state = function(state)
{
    const spaces = [];
    for(var i = 0; i < 256; i++)
    {
        spaces.push([i, state[i]]);
    }
    for(const [bdf, space] of state[261] || [])
    {
        spaces.push([bdf, space]);
    }

    for(const [bdf, space] of spaces)
    {
        var device = this.devices[bdf];

        if(!device || !space)
        {
            if(device)
            {
                dbg_log("Warning: While restoring PCI device: Device exists in current " +
                        "configuration but not in snapshot (" + device.name + ")");
            }
            if(space)
            {
                dbg_log("Warning: While restoring PCI device: Device doesn't exist in current " +
                        "configuration but does in snapshot (device " + h(bdf, 2) + ")");
            }
            continue;
        }

        for(var bar_nr = 0; bar_nr < device.pci_bars.length; bar_nr++)
        {
            var value = space[(0x10 >> 2) + bar_nr];
            var bar = device.pci_bars[bar_nr];

            // Like register_device, allow holes in a device's BAR array.
            // A saved probe value in an unimplemented slot is not an I/O BAR.
            if(!bar) continue;

            if(bar.fixed)
            {
                // Legacy devices can expose a firmware-assigned BAR without a PnP guest driver.
                // Keep the original port mapping when restoring an old snapshot.
                space[(0x10 >> 2) + bar_nr] = bar.original_bar;
                continue;
            }

            if(value & 1)
            {
                if(bar.on_move)
                {
                    if((value | 3 | bar.size - 1) !== -1)
                    {
                        this.move_io_bar(bar, value & ~3 & 0xFFFF);
                    }
                    continue;
                }
                if(bdf >= 256)
                {
                    // (mapped once the bridges are restored too, below)
                    bar.assigned = value & ~1 & 0xFFFF;
                    continue;
                }
                var from = bar.original_bar & ~1 & 0xFFFF;
                var to = value & ~1 & 0xFFFF;
                this.set_io_bars(bar, from, to);
            }
            else if(bar.on_move)
            {
                // memory: where the snapshot's guest had put it (a snapshot
                // taken mid-sizing holds the size mask, which is not a place)
                if((value | 0xF | bar.size - 1) !== -1)
                {
                    this.move_memory_bar(bar, this.bar_base(space, bar_nr, bar));
                }
            }
        }

        if(space.length === this.device_spaces[bdf].length)
        {
            this.device_spaces[bdf].set(space);
        }
        else
        {
            // (a conventional space saved for a function that now has the
            // extended one, or the reverse: the common part)
            this.device_spaces[bdf].set(space.subarray(0, Math.min(space.length, this.device_spaces[bdf].length)));
        }
        device.on_config_restore && device.on_config_restore();
    }

    this.pci_addr.set(state[256]);
    this.pci_value.set(state[257]);
    this.pci_response.set(state[258]);
    this.pci_status.set(state[259]);
    this.reset_control = state[260] === undefined ? 0 : state[260];

    this.intx_levels = [];
    this.asserted_irq_lines = [];
    this.asserted_gsis = [];
    for(const pci_id of state[262] || [])
    {
        this.intx_levels[pci_id] = true;
    }
    for(const [pci_id, irq] of state[263] || [])
    {
        this.asserted_irq_lines[pci_id] = irq;
    }
    for(const [pci_id, gsi] of state[264] || [])
    {
        this.asserted_gsis[pci_id] = gsi;
    }
    this.absent = [];
    for(const pci_id of state[265] || [])
    {
        if(this.devices[pci_id]) this.absent[pci_id] = true;
    }

    // devices behind bridges: decode and bus mastering as the restored bridges forward them
    this.devices.forEach((device, pci_id) => {
        if(pci_id >= 256) this.upstream_changed(pci_id);
    });
};

/**
 * The function addressed by a value of the configuration address register,
 * as bdf << 12 | register, or -1 when the enable bit (31) is clear
 * @param {number} address
 * @return {number}
 */
function cf8_target(address)
{
    if(address >= 0)
    {
        return -1;
    }
    return (address >> 8 & 0xFFFF) << 12 | address & 0xFF;
}

/**
 * A config access through 0xCFC-0xCFF (the low bits of the address select the byte)
 * @param {number} address configuration address register + port offset
 * @param {number} size
 * @return {number}
 */
PCI.prototype.config_read_cf8 = function(address, size)
{
    const target = cf8_target(address);
    if(target === -1)
    {
        return size === 4 ? -1 : (1 << (size << 3)) - 1;
    }
    return this.config_read(target >>> 12, target & 0xFFF, size);
};

/**
 * @param {number} address configuration address register + port offset
 * @param {number} size
 * @param {number} value
 */
PCI.prototype.config_write_cf8 = function(address, size, value)
{
    const target = cf8_target(address);
    if(target !== -1)
    {
        this.config_write(target >>> 12, target & 0xFFF, size, value);
    }
};

/**
 * The function a configuration access to bus:device.function (bdf) reaches,
 * by the bus numbers the guest gave the bridges: bus 0 is the root bus; a
 * bridge passes an access for its secondary bus to the device there (only
 * device 0 behind a PCI Express downstream port), one for a bus up to its
 * subordinate bus on to the bridges behind it.
 * @param {number} bdf
 * @return {number} the function's pci_id, or -1: nothing answers
 */
PCI.prototype.route_config = function(bdf)
{
    const bus = bdf >> 8;
    if(bus === 0)
    {
        return bdf;
    }
    for(let at = 0; ;)
    {
        let next = -1;
        for(const bridge of this.bridges_on[at] || [])
        {
            const space = this.device_spaces[bridge];
            const secondary = space[BRIDGE_SECONDARY_BUS >> 2] >> 8 & 0xFF;
            const subordinate = space[BRIDGE_SUBORDINATE_BUS >> 2] >> 16 & 0xFF;
            const behind = this.devices[bridge].pci_secondary_bus;
            if(bus === secondary)
            {
                if(this.devices[bridge].pci_express_downstream && (bdf & 0xF8))
                {
                    return -1;
                }
                const pci_id = behind << 8 | bdf & 0xFF;
                return this.device_spaces[pci_id] && !this.absent[pci_id] ? pci_id : -1;
            }
            if(bus > secondary && bus <= subordinate)
            {
                next = behind;
                break;
            }
        }
        if(next === -1)
        {
            return -1;
        }
        at = next;
    }
};

/**
 * Read 1, 2 or 4 bytes of the configuration space of the function at
 * bus:device.function (route_config). Functions that don't exist, and
 * registers beyond a function's space, read as all ones.
 * @param {number} bdf
 * @param {number} offset
 * @param {number} size
 * @return {number} unsigned for 1 and 2 bytes, a signed 32-bit value for 4
 */
PCI.prototype.config_read = function(bdf, offset, size)
{
    return this.function_read(this.route_config(bdf), offset, size);
};

/**
 * Write 1, 2 or 4 bytes to the configuration space of the function at
 * bus:device.function (route_config); see function_write
 * @param {number} bdf
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
PCI.prototype.config_write = function(bdf, offset, size, value)
{
    this.function_write(this.route_config(bdf), offset, size, value);
};

/**
 * Read a function's configuration space by its pci_id (-1: none, all ones)
 * @param {number} pci_id
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
PCI.prototype.function_read = function(pci_id, offset, size)
{
    const space = pci_id < 0 ? undefined : this.device_spaces[pci_id];

    if(space === undefined || offset + size > space.byteLength)
    {
        return size === 4 ? -1 : (1 << (size << 3)) - 1;
    }

    let value;
    if((offset & 3) + size <= 4)
    {
        value = space[offset >> 2] >>> ((offset & 3) << 3);
    }
    else
    {
        // (straddles two dwords: assembled from bytes)
        const bytes = new Uint8Array(space.buffer, space.byteOffset);
        value = 0;
        for(let i = 0; i < size; i++)
        {
            value |= bytes[offset + i] << (i << 3);
        }
    }

    if(size === 4)
    {
        value |= 0;
    }
    else
    {
        value &= (1 << (size << 3)) - 1;
    }

    dbg_log("PCI read" + (size << 3) + " " + h(pci_id, 4) + ":" + h(offset, 3) + " -> " + h(value >>> 0) +
            " (" + this.devices[pci_id].name + ")", LOG_PCI);
    return value;
};

/**
 * Write 1, 2 or 4 bytes of a function's configuration space (by its pci_id)
 * with the semantics of the header registers, type 0 or type 1 (bridges).
 * Writes to functions that don't exist (-1), or beyond a function's space,
 * are dropped.
 * @param {number} pci_id
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
PCI.prototype.function_write = function(pci_id, offset, size, value)
{
    const space = pci_id < 0 ? undefined : this.device_spaces[pci_id];
    const device = this.devices[pci_id];

    if(space === undefined || offset + size > space.byteLength)
    {
        return;
    }

    dbg_log("PCI write" + (size << 3) + " " + h(pci_id, 4) + ":" + h(offset, 3) + " <- " + h(value >>> 0) +
            " (" + device.name + ")", LOG_PCI);

    const bridge = device.pci_secondary_bus !== undefined;

    // BARs and the expansion ROM base (type 0): 32-bit registers
    if(bridge ? offset >= 0x10 && offset < 0x18 : offset >= 0x10 && offset < 0x28 || offset >= 0x30 && offset < 0x34)
    {
        if(size === 4 && (offset & 3) === 0)
        {
            if(offset === 0x30)
            {
                this.write_expansion_rom(device, space, value);
            }
            else
            {
                this.write_bar(device, space, offset, value);
            }
        }
        else
        {
            // (e.g. the Bochs BIOS: narrower writes leave BARs alone)
            dbg_log("Warning: PCI: Expected 32-bit write, got " + (size << 3) + "-bit (addr: " + h(offset) + ")", LOG_PCI);
        }
        return;
    }

    const bytes = new Uint8Array(space.buffer, space.byteOffset);
    const old_command = bytes[4] | bytes[5] << 8;
    let header_written = false;
    let windows_written = false;

    for(let i = 0; i < size; i++)
    {
        const o = offset + i;
        const byte = value >>> (i << 3) & 0xFF;

        if(o >= 0x40)
        {
            bytes[o] = byte;
        }
        else if(bridge && o >= 0x18)
        {
            if(o === BRIDGE_SECONDARY_STATUS + 1)
            {
                bytes[o] &= ~(byte & PCI_STATUS_RW1C >> 8);
            }
            else
            {
                const mask = BRIDGE_HEADER_WRITABLE[o];
                bytes[o] = bytes[o] & ~mask | byte & mask;
                // (the windows and the ISA enable bit decide what is forwarded)
                windows_written = windows_written || o >= BRIDGE_IO_BASE && o < 0x30 || o === BRIDGE_CONTROL;
            }
        }
        else if(o === 0x04 || o === 0x05)
        {
            const mask = PCI_COMMAND_WRITABLE >> ((o - 4) << 3) & 0xFF;
            bytes[o] = bytes[o] & ~mask | byte & mask;
        }
        else if(o === 0x06 || o === 0x07)
        {
            // status: write one to clear
            bytes[o] &= ~(byte & PCI_STATUS_RW1C >> ((o - 6) << 3));
        }
        else if(header_byte_writable(o))
        {
            bytes[o] = byte;
            header_written = true;
        }
    }

    const command = bytes[4] | bytes[5] << 8;
    if(command !== old_command)
    {
        this.command_changed(pci_id, old_command, command);
    }
    else if(windows_written)
    {
        this.bridge_changed(pci_id);
    }

    if(offset + size > 0x40 || header_written)
    {
        device.on_config_write && device.on_config_write(offset, size);
    }
};

/**
 * @param {Object} device
 * @param {!Int32Array} space
 * @param {number} offset
 * @param {number} written
 */
PCI.prototype.write_bar = function(device, space, offset, written)
{
    var bar_nr = offset - 0x10 >> 2;
    var bar = device.pci_bars[bar_nr];
    var space_addr = offset >> 2;

    dbg_log("BAR" + bar_nr + " exists=" + (bar ? "y" : "n") + " changed from " + h(space[space_addr]) + " to " +
            h(written >>> 0) + " (" + device.name + ") ", LOG_PCI);

    if(!bar)
    {
        const lower = bar_nr > 0 ? device.pci_bars[bar_nr - 1] : undefined;
        if(lower && lower.bits64)
        {
            // the upper half of a 64-bit memory BAR (P5.10)
            this.write_bar_upper(lower, space, space_addr, written);
            return;
        }
        space[space_addr] = 0;
        return;
    }

    dbg_assert(!(bar.size & bar.size - 1), "bar size should be power of 2");

    var type = space[space_addr] & 1;
    const probe = (written | 3 | bar.size - 1) === -1;

    if(probe) // size check
    {
        written = ~(bar.size - 1) | type;

        if(type === 0)
        {
            // the type and prefetchable bits are read-only and stay
            space[space_addr] = written | bar.original_bar & 0xF;
        }
    }
    else
    {
        if(type === 0)
        {
            // memory
            var original_bar = bar.original_bar;

            if(bar.on_move)
            {
                // The device decodes its memory where the guest puts it:
                // SeaBIOS assigns every BAR, and an OS may reassign them
                const base = written & ~(bar.size - 1) & ~0xF;
                space[space_addr] = base | original_bar & 0xF;
                this.move_memory_bar(bar, this.bar_base(space, bar_nr, bar));
            }
            else
            {
                if((written & ~0xF) !== (original_bar & ~0xF))
                {
                    dbg_log("Warning: Changing memory bar not supported, ignored", LOG_PCI);
                }

                // this device cannot move, keep the default
                space[space_addr] = original_bar;
            }
        }
    }

    if(type === 1)
    {
        // io
        if(bar.on_move)
        {
            // decoded by the device itself, wherever the guest puts it
            // (also among the legacy ports below 0x1000)
            space[space_addr] = written | 1;
            if(!probe)
            {
                this.move_io_bar(bar, written & ~3 & 0xFFFF);
            }
        }
        else if(bar.fixed)
        {
            // The guest may probe BAR size, but this legacy device has no PnP driver
            // to consume a relocated resource. Keep its firmware-assigned I/O range.
            space[space_addr] = (written | 3 | bar.size - 1) === -1
                ? ~(bar.size - 1) | type
                : bar.original_bar;
        }
        else if(device.pci_id >= 256)
        {
            // behind a bridge: mapped where the bridges forward it
            bar.assigned = written & ~1 & 0xFFFF;
            space[space_addr] = written | 1;
            this.update_io_bar(device.pci_id, bar);
        }
        else
        {
            var from = space[space_addr] & ~1 & 0xFFFF;
            var to = written & ~1 & 0xFFFF;
            dbg_log("io bar changed from " + h(from >>> 0, 8) +
                    " to " + h(to >>> 0, 8) + " size=" + bar.size, LOG_PCI);
            this.set_io_bars(bar, from, to);
            space[space_addr] = written | 1;
        }
    }

    dbg_log("BAR effective value: " + h(space[space_addr] >>> 0), LOG_PCI);
};

/**
 * A write to the upper half of a 64-bit memory BAR: all its bits are
 * writable but those of a size of 4 GiB or more (sizing reads them back as
 * the mask's upper half). The BAR moves unless either half holds the size
 * mask.
 * @param {Object} bar the BAR, of the register below
 * @param {!Int32Array} space
 * @param {number} space_addr
 * @param {number} written
 */
PCI.prototype.write_bar_upper = function(bar, space, space_addr, written)
{
    const mask = ~Math.floor((bar.size - 1) / 0x100000000);
    space[space_addr] = written & mask;
    const low = space[space_addr - 1];
    if(written !== -1 && (low | 0xF | bar.size - 1) !== -1)
    {
        this.move_memory_bar(bar, this.bar_base(space, space_addr - 1 - (0x10 >> 2), bar));
    }
};

/**
 * @param {Object} device
 * @param {!Int32Array} space
 * @param {number} written
 */
PCI.prototype.write_expansion_rom = function(device, space, written)
{
    dbg_log("PCI write rom address (" + device.name + ")" + " value=" + h(written >>> 0, 8), LOG_PCI);

    if(device.pci_rom_size)
    {
        if((written | 0x7FF) === (0xFFFFFFFF|0))
        {
            space[0x30 >> 2] = -device.pci_rom_size | 0;
        }
        else
        {
            space[0x30 >> 2] = device.pci_rom_address | 0;
        }
    }
    else
    {
        space[0x30 >> 2] = 0;
    }
};

/**
 * The guest changed the command register: INTx Disable takes effect here,
 * memory/I/O decode and bus mastering in devices that implement them
 * (on_command_change, is_bus_master, ...)
 * @param {number} bdf
 * @param {number} old_command
 * @param {number} command
 */
PCI.prototype.command_changed = function(bdf, old_command, command)
{
    dbg_log("PCI command " + h(bdf, 4) + ": " + h(old_command, 4) + " -> " + h(command, 4) +
            " (" + this.devices[bdf].name + ")", LOG_PCI);

    if((old_command ^ command) & PCI_COMMAND_INTX_DISABLE)
    {
        this.drive_intx(bdf, !!this.intx_levels[bdf] && !(command & PCI_COMMAND_INTX_DISABLE));
    }

    const device = this.devices[bdf];
    device.on_command_change && device.on_command_change(old_command, command);

    if(device.pci_secondary_bus !== undefined &&
        (old_command ^ command) & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER))
    {
        // a bridge: what it forwards changed
        this.bridge_changed(bdf);
    }
};

/**
 * @param {number} bdf
 * @return {number}
 */
PCI.prototype.get_command = function(bdf)
{
    const space = this.device_spaces[bdf];
    return space ? space[1] & 0xFFFF : 0;
};

/**
 * Whether the function may master the bus (DMA, MSI): its bus mastering is
 * enabled, and that of every bridge between it and the root bus
 * @param {number} bdf its pci_id
 */
PCI.prototype.is_bus_master = function(bdf)
{
    return (this.get_command(bdf) & PCI_COMMAND_MASTER) !== 0 && this.upstream_bus_master(bdf);
};

/**
 * Whether the bridges between a function and the root bus forward its bus
 * master requests (for functions on bus 0: yes)
 * @param {number} pci_id
 * @return {boolean}
 */
PCI.prototype.upstream_bus_master = function(pci_id)
{
    if(this.absent[pci_id])
    {
        return false;
    }
    for(let bridge = this.parent_bridge(pci_id); bridge !== -1; bridge = this.parent_bridge(bridge))
    {
        if(!(this.get_command(bridge) & PCI_COMMAND_MASTER))
        {
            return false;
        }
    }
    return true;
};

/**
 * The bridge on whose secondary bus a function is, or -1 (bus 0)
 * @param {number} pci_id
 * @return {number}
 */
PCI.prototype.parent_bridge = function(pci_id)
{
    const bridge = pci_id >= 256 ? this.bridge_for_bus[pci_id >> 8] : undefined;
    return bridge === undefined ? -1 : bridge;
};

/**
 * Whether memory accesses to [base, base + size) reach a function: the
 * bridges between it and the root bus have memory decode enabled and the
 * range within their memory or prefetchable window (for functions on bus 0:
 * yes; the function's own memory space enable is its own business)
 * @param {number} pci_id
 * @param {number} base
 * @param {number} size
 * @return {boolean}
 */
PCI.prototype.upstream_forwards_memory = function(pci_id, base, size)
{
    if(this.absent[pci_id])
    {
        return false;
    }
    const end = base + size - 1;
    for(let bridge = this.parent_bridge(pci_id); bridge !== -1; bridge = this.parent_bridge(bridge))
    {
        if(!(this.get_command(bridge) & PCI_COMMAND_MEMORY))
        {
            return false;
        }
        const bytes = this.space_bytes(bridge);
        const u16 = o => bytes[o] | bytes[o + 1] << 8;
        const u32 = o => (bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24) >>> 0;
        const memory_base = (u16(BRIDGE_MEMORY_BASE) & 0xFFF0) * 0x10000;
        const memory_limit = (u16(BRIDGE_MEMORY_LIMIT) & 0xFFF0) * 0x10000 + 0xFFFFF;
        const prefetch_base = (u16(BRIDGE_PREFETCH_BASE) & 0xFFF0) * 0x10000 + u32(BRIDGE_PREFETCH_BASE_UPPER) * 0x100000000;
        const prefetch_limit = (u16(BRIDGE_PREFETCH_LIMIT) & 0xFFF0) * 0x10000 + 0xFFFFF + u32(BRIDGE_PREFETCH_LIMIT_UPPER) * 0x100000000;
        if(!(base >= memory_base && end <= memory_limit) && !(base >= prefetch_base && end <= prefetch_limit))
        {
            return false;
        }
    }
    return true;
};

/**
 * Whether I/O accesses to [port, port + size) reach a function: the bridges
 * between it and the root bus have I/O decode enabled and the range within
 * their I/O window (with ISA enable: not the top 768 bytes of each KiB)
 * @param {number} pci_id
 * @param {number} port
 * @param {number} size
 * @return {boolean}
 */
PCI.prototype.upstream_forwards_io = function(pci_id, port, size)
{
    if(this.absent[pci_id])
    {
        return false;
    }
    const end = port + size - 1;
    for(let bridge = this.parent_bridge(pci_id); bridge !== -1; bridge = this.parent_bridge(bridge))
    {
        if(!(this.get_command(bridge) & PCI_COMMAND_IO))
        {
            return false;
        }
        const bytes = this.space_bytes(bridge);
        const io_base = (bytes[BRIDGE_IO_BASE] & 0xF0) << 8;
        const io_limit = (bytes[BRIDGE_IO_LIMIT] & 0xF0) << 8 | 0xFFF;
        if(port < io_base || end > io_limit)
        {
            return false;
        }
        if(bytes[BRIDGE_CONTROL] & BRIDGE_CONTROL_ISA && ((port & 0x300) || (end & 0x300) || end - port >= 0x100))
        {
            return false;
        }
    }
    return true;
};

/**
 * Whether a function decodes memory at [base, base + size): its memory space
 * is enabled and the bridges upstream forward the range
 * @param {number} pci_id
 * @param {number} base
 * @param {number} size
 * @return {boolean}
 */
PCI.prototype.memory_decoded = function(pci_id, base, size)
{
    return this.is_memory_enabled(pci_id) && this.upstream_forwards_memory(pci_id, base, size);
};

/**
 * @param {number} pci_id
 * @return {!Uint8Array}
 */
PCI.prototype.space_bytes = function(pci_id)
{
    const space = this.device_spaces[pci_id];
    return new Uint8Array(space.buffer, space.byteOffset, space.byteLength);
};

/**
 * A bridge's decode, bus mastering or windows changed: the functions behind
 * it (at any depth) map their I/O BARs again and hear of it
 * (on_upstream_change)
 * @param {number} bridge
 */
PCI.prototype.bridge_changed = function(bridge)
{
    dbg_log("PCI bridge " + h(bridge, 4) + " (" + this.devices[bridge].name + "): forwarding changed", LOG_PCI);
    this.devices.forEach((device, pci_id) => {
        for(let up = this.parent_bridge(pci_id); up !== -1; up = this.parent_bridge(up))
        {
            if(up === bridge)
            {
                this.upstream_changed(pci_id);
                break;
            }
        }
    });
};

/**
 * @param {number} pci_id a function behind a bridge
 */
PCI.prototype.upstream_changed = function(pci_id)
{
    const device = this.devices[pci_id];
    for(const bar of device.pci_bars)
    {
        if(bar && bar.assigned !== undefined)
        {
            this.update_io_bar(pci_id, bar);
        }
    }
    device.on_upstream_change && device.on_upstream_change();
};

/**
 * Map an I/O BAR of a function behind a bridge where it is assigned, if the
 * bridges forward it there (never over the legacy ports below 0x1000)
 * @param {number} pci_id
 * @param {Object} bar
 */
PCI.prototype.update_io_bar = function(pci_id, bar)
{
    const at = bar.assigned >= 0x1000 && bar.assigned + bar.size <= 0x10000 &&
        this.upstream_forwards_io(pci_id, bar.assigned, bar.size) ? bar.assigned : -1;
    if(at === bar.mapped)
    {
        return;
    }
    dbg_log("PCI " + h(pci_id, 4) + ": I/O BAR " + (at === -1 ? "not forwarded" : "at " + h(at, 4)) +
        " size=" + bar.size, LOG_PCI);
    const ports = this.io.ports;
    if(bar.mapped !== -1)
    {
        for(let i = 0; i < bar.size; i++)
        {
            if(ports[bar.mapped + i] === bar.entries[i]) ports[bar.mapped + i] = this.io.create_empty_entry();
        }
    }
    if(at !== -1)
    {
        for(let i = 0; i < bar.size; i++)
        {
            ports[at + i] = bar.entries[i];
        }
    }
    bar.mapped = at;
};

/** @param {number} bdf */
PCI.prototype.is_memory_enabled = function(bdf)
{
    return (this.get_command(bdf) & PCI_COMMAND_MEMORY) !== 0;
};

/** @param {number} bdf */
PCI.prototype.is_io_enabled = function(bdf)
{
    return (this.get_command(bdf) & PCI_COMMAND_IO) !== 0;
};

/**
 * After a guest write to an MSI capability (msi_capability) at cap: the
 * capability ID, next pointer, the read-only bits of message control and the
 * low two address bits keep their values; one message (multiple message
 * enable stays 0)
 * @param {number} bdf
 * @param {number} cap
 * @param {number} next
 */
PCI.prototype.msi_config_written = function(bdf, cap, next)
{
    const space = this.device_spaces[bdf];
    const bytes = new Uint8Array(space.buffer, space.byteOffset);
    bytes[cap] = PCI_CAP_MSI;
    bytes[cap + 1] = next;
    bytes[cap + 2] = bytes[cap + 2] & MSI_CONTROL_ENABLE | MSI_CONTROL_64BIT;
    bytes[cap + 3] = 0;
    bytes[cap + 4] &= ~3;
};

/**
 * @param {number} bdf
 * @param {number} cap the offset of its MSI capability
 * @return {boolean}
 */
PCI.prototype.msi_enabled = function(bdf, cap)
{
    const space = this.device_spaces[bdf];
    return space !== undefined && (new Uint8Array(space.buffer, space.byteOffset)[cap + 2] & MSI_CONTROL_ENABLE) !== 0;
};

/**
 * Signal the function's message: its data written to its address, which
 * delivers it to the local APICs. Messages to other addresses (or above 4
 * GiB) are not supported and dropped.
 * @param {number} bdf
 * @param {number} cap
 * @return {boolean} whether a local APIC accepted it
 */
PCI.prototype.msi_notify = function(bdf, cap)
{
    const space = this.device_spaces[bdf];
    const bytes = new Uint8Array(space.buffer, space.byteOffset);
    const u32 = o => (bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24) >>> 0;
    const address = u32(cap + 4), high = u32(cap + 8);
    const data = bytes[cap + 12] | bytes[cap + 13] << 8;
    if(high !== 0 || !this.cpu.apic_msi)
    {
        dbg_log("PCI " + h(bdf, 4) + ": MSI to " + h(high) + ":" + h(address) + " dropped", LOG_PCI);
        return false;
    }
    if(!this.is_bus_master(bdf))
    {
        // (a message is a memory write: bus mastering must be on, also in
        // the bridges upstream)
        return false;
    }
    return !!this.cpu.apic_msi(address | 0, data);
};

/**
 * Map the ECAM (memory-mapped configuration) window, or unmap it (base -1).
 * Offset bits 27:20 select the bus, 19:12 device and function, 11:0 the register.
 * @param {number} base
 * @param {number} size
 */
PCI.prototype.set_ecam = function(base, size)
{
    if(base === this.ecam_base && size === this.ecam_size)
    {
        return;
    }

    if(this.ecam_base !== -1)
    {
        this.io.mmap_unregister(this.ecam_base, this.ecam_size);
    }

    dbg_log("ECAM " + (base === -1 ? "disabled" : "at " + h(base >>> 0, 8) + " size " + h(size)), LOG_PCI);
    this.ecam_base = base;
    this.ecam_size = base === -1 ? 0 : size;
    // The MCH decodes the window itself, before any BAR: device memory there
    // (the VGA's frame buffer starts at 0xE0000000, where OVMF puts the
    // window) waits until the window or the BAR moves
    this.cpu.mmio_ram_reserve(base === -1 ? 0 : base, this.ecam_size);

    if(base !== -1)
    {
        // (addresses above 2 GiB arrive as negative int32s)
        const offset = addr => addr - this.ecam_base >>> 0;
        const read8 = addr => {
            const o = offset(addr);
            return this.config_read(o >>> 12, o & 0xFFF, 1);
        };
        const write8 = (addr, value) => {
            const o = offset(addr);
            this.config_write(o >>> 12, o & 0xFFF, 1, value);
        };
        const read32 = addr => {
            const o = offset(addr);
            if(o & 3)
            {
                return read8(addr) | read8(addr + 1) << 8 | read8(addr + 2) << 16 | read8(addr + 3) << 24;
            }
            return this.config_read(o >>> 12, o & 0xFFF, 4);
        };
        const write32 = (addr, value) => {
            const o = offset(addr);
            if(o & 3)
            {
                for(let i = 0; i < 4; i++) write8(addr + i, value >>> (i << 3) & 0xFF);
                return;
            }
            this.config_write(o >>> 12, o & 0xFFF, 4, value);
        };
        this.io.mmap_register(base, size, read8, write8, read32, write32);
    }
};

/**
 * The generic host's ECAM (src/virt/io.js's handler for its 256 MiB, bus
 * 0-255): offset bits 27:20 select the bus, 19:12 device and function, 11:0
 * the register; an 8-byte access is two 4-byte ones
 * @return {{name: string, read: function(number, number): (number|bigint), write: function(number, number, (number|bigint))}}
 */
PCI.prototype.ecam_handler = function()
{
    const read = (offset, width) => this.config_read(offset >>> 12, offset & 0xFFF, width);
    const write = (offset, width, value) => this.config_write(offset >>> 12, offset & 0xFFF, width, value);
    return {
        name: "pcie-ecam",
        read: (offset, width) => width === 8 ?
            BigInt(read(offset, 4) >>> 0) | BigInt(read(offset + 4, 4) >>> 0) << 32n : read(offset, width) >>> 0,
        write: (offset, width, value) => {
            if(width === 8)
            {
                write(offset, 4, Number(BigInt.asUintN(32, /** @type {bigint} */ (value))) | 0);
                write(offset + 4, 4, Number(/** @type {bigint} */ (value) >> 32n) | 0);
            }
            else
            {
                write(offset, width, /** @type {number} */ (value));
            }
        },
    };
};

/**
 * The generic host's memory window at `window_base` (src/virt/io.js's
 * handler): an access reaches the BAR that decodes all of it
 * (set_memory_decoder), at its offset in the BAR; elsewhere reads are all
 * ones and writes go nowhere, as on the reference
 * @param {number} window_base
 * @return {{name: string, read: function(number, number): (number|bigint), write: function(number, number, (number|bigint))}}
 */
PCI.prototype.window_handler = function(window_base)
{
    const find = (address, width) => {
        for(const decoder of this.memory_decoders)
        {
            if(address >= decoder.base && address + width <= decoder.base + decoder.size) return decoder;
        }
        return null;
    };
    return {
        name: "pcie-window",
        read: (offset, width) => {
            const address = window_base + offset;
            const decoder = find(address, width);
            if(decoder) return decoder.handler.read(address - decoder.base, width);
            return width === 8 ? 0xFFFFFFFFFFFFFFFFn : 2 ** (8 * width) - 1;
        },
        write: (offset, width, value) => {
            const address = window_base + offset;
            const decoder = find(address, width);
            if(decoder) decoder.handler.write(address - decoder.base, width, value);
        },
    };
};

/**
 * A memory BAR of a function on the generic host is decoded at [base, base +
 * size) by `handler` (offset in the BAR and width, as src/virt/io.js's), or
 * no longer (base -1)
 * @param {!Object} owner the BAR's device, which names the decoder
 * @param {number} base
 * @param {number} size
 * @param {Object} handler
 */
PCI.prototype.set_memory_decoder = function(owner, base, size, handler)
{
    dbg_assert(this.generic);
    this.memory_decoders = this.memory_decoders.filter(decoder => decoder.owner !== owner);
    if(base !== -1)
    {
        dbg_log("PCI memory decoded at " + h(base) + " size " + h(size) + " (" + owner.name + ")", LOG_PCI);
        this.memory_decoders.push({ owner, base, size, handler: /** @type {!Object} */ (handler) });
    }
};

PCI.prototype.register_device = function(device)
{
    dbg_assert(device.pci_id !== undefined);
    dbg_assert(device.pci_space !== undefined);
    dbg_assert(device.pci_bars !== undefined);

    var device_id = device.pci_id;

    dbg_log("PCI register bdf=" + h(device_id) + " (" + device.name + ")", LOG_PCI);

    if(this.devices[device_id])
    {
        dbg_log("warning: overwriting device " + this.devices[device_id].name + " with " + device.name, LOG_PCI);
    }
    dbg_assert(device.pci_space.length >= 64);
    dbg_assert(device_id >= 0 && device_id < 0x10000);

    // convert bytewise notation from lspci to double words; a function with
    // PCI Express extended configuration space has 4 KiB
    const config_size = device.pci_config_size || 256;
    dbg_assert(config_size === 256 || config_size === 4096);
    var space = new Int32Array(config_size >> 2);
    space.set(new Int32Array(new Uint8Array(device.pci_space).buffer));
    this.device_spaces[device_id] = space;
    this.devices[device_id] = device;
    if(device_id >= 256 || this.generic)
    {
        this.templates[device_id] = space.slice();
    }

    if((device.pci_space[0x0E] & 0x7F) === PCI_HEADER_TYPE_BRIDGE)
    {
        // a bridge: the bus behind it (pci_secondary_bus) is reached through it
        const behind = device.pci_secondary_bus;
        dbg_assert(behind > 0 && behind < 256 && this.bridge_for_bus[behind] === undefined, "PCI bridge: bad secondary bus");
        this.bridge_for_bus[behind] = device_id;
        const bus = device_id >> 8;
        this.bridges_on[bus] = (this.bridges_on[bus] || []).concat([device_id]);
    }
    dbg_assert(device_id < 256 || this.bridge_for_bus[device_id >> 8] !== undefined,
        "PCI: no bridge leads to the bus of " + device.name);

    var bar_space = space.slice(4, 10);

    for(var i = 0; i < device.pci_bars.length; i++)
    {
        var bar = device.pci_bars[i];

        if(!bar)
        {
            continue;
        }

        var bar_base = bar_space[i];
        var type = bar_base & 1;
        dbg_log("device "+ device.name +" register bar of size "+bar.size +" at " + h(bar_base), LOG_PCI);

        bar.original_bar = bar_base;
        bar.entries = [];

        if(type === 0)
        {
            // memory: the device decodes it itself (bar.on_move)
            dbg_assert(!bar.bits64 || this.generic && (bar_base & 6) === 4 && i < 5 && !device.pci_bars[i + 1],
                "PCI: a 64-bit BAR is the generic host's, of type 64-bit, and the next register its upper half");
            bar.base = this.bar_base(space, i, bar);
        }
        else if(bar.on_move)
        {
            // an I/O BAR the device decodes itself (on_move)
            bar.base = bar_base & ~3 & 0xFFFF;
        }
        else
        {
            dbg_assert(type === 1);
            var port = bar_base & ~1;

            for(var j = 0; j < bar.size; j++)
            {
                bar.entries[j] = this.io.ports[port + j];
            }

            if(device_id >= 256)
            {
                // behind a bridge: nothing reaches the ports until the
                // bridges forward them (update_io_bar)
                dbg_assert(port >= 0x1000, "PCI: I/O BAR of a device behind a bridge in the legacy ports");
                bar.assigned = port;
                bar.mapped = port;
                this.update_io_bar(device_id, bar);
            }
        }
    }

    return space;
};

/**
 * A function behind a hot plug slot comes or goes (src/pcie_root_port.js).
 * Absent, nothing reaches it: configuration cycles, its BARs (the bridges do
 * not forward to it), and it neither masters the bus (DMA, MSI) nor drives
 * its pin. Arriving `fresh` (a card plugged in, or switched on), it has its
 * power-on configuration space, its BARs where that has them, and the device
 * is reset.
 * @param {number} pci_id a function behind a bridge
 * @param {boolean} present
 * @param {boolean=} fresh
 */
PCI.prototype.set_function_present = function(pci_id, present, fresh)
{
    const device = this.devices[pci_id];
    dbg_assert(device && pci_id >= 256);
    dbg_log("PCI " + h(pci_id, 4) + " (" + device.name + "): " + (present ? "on the bus" : "off the bus"), LOG_PCI);
    if(!present && !this.absent[pci_id])
    {
        device.on_unplug && device.on_unplug();
    }
    this.absent[pci_id] = !present;
    if(present && fresh)
    {
        const template = /** @type {!Int32Array} */ (this.templates[pci_id]);
        this.device_spaces[pci_id].set(template);
        device.pci_bars.forEach((bar, i) => {
            if(!bar) return;
            const value = template[(0x10 >> 2) + i];
            if(value & 1)
            {
                if(bar.on_move) this.move_io_bar(bar, value & ~3 & 0xFFFF);
                else bar.assigned = value & ~1 & 0xFFFF;
            }
            else if(bar.on_move)
            {
                this.move_memory_bar(bar, value & ~0xF);
            }
        });
        this.intx_levels[pci_id] = false;
        device.reset && device.reset();
    }
    this.set_irq_level(pci_id, !!this.intx_levels[pci_id]);
    this.upstream_changed(pci_id);
};

/**
 * @param {Object} bar
 * @param {number} base
 */
PCI.prototype.move_memory_bar = function(bar, base)
{
    if(!bar.bits64) base >>>= 0;
    if(bar.base !== base)
    {
        dbg_log("memory bar moved from " + h(bar.base >>> 0, 8) + " to " + h(base, 8) + " size=" + h(bar.size), LOG_PCI);
        bar.base = base;
        bar.on_move(base);
    }
};

/**
 * An I/O BAR a device decodes itself moved
 * @param {Object} bar
 * @param {number} port
 */
PCI.prototype.move_io_bar = function(bar, port)
{
    if(bar.base !== port)
    {
        dbg_log("io bar (device decoded) moved from " + h(bar.base, 4) + " to " + h(port, 4) + " size=" + bar.size, LOG_PCI);
        bar.base = port;
        bar.on_move(port);
    }
};

PCI.prototype.set_io_bars = function(bar, from, to)
{
    var count = bar.size;
    dbg_log("Move io bars: from=" + h(from) + " to=" + h(to) + " count=" + count, LOG_PCI);

    var ports = this.io.ports;

    for(var i = 0; i < count; i++)
    {
        var old_entry = ports[from + i];

        if(from + i >= 0x1000)
        {
            ports[from + i] = this.io.create_empty_entry();
        }

        var entry = bar.entries[i];
        var empty_entry = ports[to + i];
        dbg_assert(entry && empty_entry);

        if(to + i >= 0x1000)
        {
            ports[to + i] = entry;
        }
    }
};

/**
 * The IRQ line that the PIIX PIRQ routing registers (0x60..0x63 of the ISA
 * bridge) currently assign to the interrupt pin of a function. Bit 7 set
 * means the PIRQ is not routed to an ISA IRQ (e.g. after a link device's _DIS).
 * @param {number} pci_id
 * @return {number}
 */
PCI.prototype.get_irq_line = function(pci_id)
{
    const root = this.root_pin(pci_id);
    return this.piix_pirq_line(root.pci_id, root.pin);
};

/**
 * PIIX3: device d's pin p (0-3) on bus 0 is wired to PIRQ (p + d - 1) & 3
 * @param {number} pci_id
 * @param {number} pin
 * @return {number}
 */
PCI.prototype.piix_pirq_line = function(pci_id, pin)
{
    var device = (pci_id >> 3) - 1 & 0xFF;
    var parent_pin = pin + device & 3;
    return this.isa_bridge_space8[0x60 + parent_pin];
};

/**
 * The function on bus 0 and its pin that a function's interrupt pin reaches:
 * crossing a bridge, INTx of device d on its secondary bus becomes the
 * bridge's INT((x + d) % 4) (the PCI-to-PCI bridge swizzle)
 * @param {number} pci_id
 * @return {{pci_id: number, pin: number}} pin 0-3 (INTA-D), -1: none
 */
PCI.prototype.root_pin = function(pci_id)
{
    const space = this.device_spaces[pci_id];
    dbg_assert(space);
    let pin = (space[0x3C >>> 2] >> 8 & 0xFF) - 1;
    if(pin < 0 || pin > 3)
    {
        return { pci_id, pin: -1 };
    }
    for(let bridge = this.parent_bridge(pci_id); bridge !== -1; bridge = this.parent_bridge(bridge))
    {
        pin = pin + (pci_id >> 3 & 0x1F) & 3;
        pci_id = bridge;
    }
    return { pci_id, pin };
};

PCI.prototype.raise_irq = function(pci_id)
{
    this.set_irq_level(pci_id, true);
};

PCI.prototype.lower_irq = function(pci_id)
{
    this.set_irq_level(pci_id, false);
};

/**
 * A function drives its interrupt pin: the interrupt status bit follows the
 * level, the line follows it unless INTx Disable is set
 * @param {number} pci_id
 * @param {boolean} level
 */
PCI.prototype.set_irq_level = function(pci_id, level)
{
    this.intx_levels[pci_id] = level;

    const space = this.device_spaces[pci_id];
    if(space)
    {
        space[1] = level ? space[1] | PCI_STATUS_INTERRUPT << 16 : space[1] & ~(PCI_STATUS_INTERRUPT << 16);
    }

    const disabled = space !== undefined && (space[1] & PCI_COMMAND_INTX_DISABLE) !== 0;
    this.drive_intx(pci_id, level && !disabled && !this.absent[pci_id]);
};

/**
 * Drive the lines the chipset connects to a function's pin: the PIC input
 * (an ISA IRQ, also seen by the IOAPIC at the same pin) and, on Q35, the
 * IOAPIC-only input
 * @param {number} pci_id
 * @param {boolean} level
 */
PCI.prototype.drive_intx = function(pci_id, level)
{
    const root = this.root_pin(pci_id);
    const route = this.irq_route(root.pci_id, root.pin);

    if(level)
    {
        var irq = route.pic;
        var previous = this.asserted_irq_lines[pci_id];

        if(irq & 0x80)
        {
            dbg_log("PCI irq of " + this.devices[pci_id].name + " not routed (PIRQ route " + h(irq) + ")", LOG_PCI);
            irq = undefined;
        }

        if(previous !== undefined && previous !== irq)
        {
            // the guest rerouted the pin while it was asserted
            this.cpu.set_shared_irq_level(previous, pci_id, false);
        }
        this.asserted_irq_lines[pci_id] = irq;

        if(irq !== undefined)
        {
            this.cpu.set_shared_irq_level(irq, pci_id, true);
        }

        const previous_gsi = this.asserted_gsis[pci_id];
        const gsi = route.gsi >= 0 ? route.gsi : undefined;
        if(previous_gsi !== undefined && previous_gsi !== gsi)
        {
            this.cpu.set_shared_gsi_level(previous_gsi, pci_id, false);
        }
        this.asserted_gsis[pci_id] = gsi;
        if(gsi !== undefined)
        {
            this.cpu.set_shared_gsi_level(gsi, pci_id, true);
        }
    }
    else
    {
        // Deassert the line that was asserted, even if the guest has changed the
        // routing since. Without a record (e.g. after restoring a state image)
        // fall back to the current routing.
        var irq = this.asserted_irq_lines[pci_id];
        if(irq === undefined)
        {
            irq = route.pic;
        }
        this.asserted_irq_lines[pci_id] = undefined;

        if(!(irq & 0x80))
        {
            this.cpu.set_shared_irq_level(irq, pci_id, false);
        }

        var gsi = this.asserted_gsis[pci_id];
        if(gsi === undefined && route.gsi >= 0)
        {
            gsi = route.gsi;
        }
        this.asserted_gsis[pci_id] = undefined;
        if(gsi !== undefined)
        {
            this.cpu.set_shared_gsi_level(gsi, pci_id, false);
        }
    }
};
                                                                                                                                            source/v64/src/pcie_root_port.js                                                                    0000644 0000000 0000000 00000045776 00000000000 014063  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The PCI Express root ports of the Q35 machine's ICH9 (00:1c.0-5): PCI-to-
// PCI bridges (type 1 header, src/pci.js) with the PCI Express capability of
// a root port. Each one's secondary bus holds what the machine puts behind it
// (device 0 only, as behind any PCI Express downstream port), in a slot with
// PCI Express native hot plug, as QEMU's pcie-root-port has it: attention
// button, power controller, power and attention indicators, presence detect
// and data link layer state changed events, command completed, signalled by
// MSI or INTx. The guest takes the slots over through _OSC (acpi_tables.js).
// After reset, a slot with a card is on, an empty one off (as QEMU's).
//
// The card in a slot is the device the options put behind the port. The host
// plugs it in and pulls it out (V86.attach_pcie_device, detach_pcie_device;
// pcie_plugged: false starts with the slot empty), either at once (a
// surprise removal) or by pressing the attention button: the guest then
// releases the device and switches the slot and its power indicator off. A
// card out of the slot or without power is off the bus (src/pci.js
// set_function_present); plugged in or switched on again it starts afresh.
// The link is up (x1, 2.5 GT/s) while a card is in and powered. No PME or
// error events.
// ICH9 datasheet (316972), chapter 18; PCI Express Base 2.0, 6.7 and 7.8.

import { LOG_PCI } from "./const.js";
import { dbg_log } from "./log.js";
import { msi_capability } from "./pci.js";
import { QEMU_PCI_SUBSYSTEM, Q35_ROOT_PORT_SLOT } from "./platform.js";

// For Types Only
import { CPU } from "./cpu.js";

/** 82801I (ICH9) PCI Express Port 1; port n is 0x2940 + 2 * (n - 1) */
const ICH9_ROOT_PORT_DEVICE_ID = 0x2940;

const PCIE_CAP = 0x40;
const MSI_CAP = 0x80;
const SSVID_CAP = 0x90;
const PM_CAP = 0xA0;

const PCI_CAP_PCIE = 0x10;
const PCI_CAP_SSVID = 0x0D;
const PCI_CAP_PM = 0x01;

// PCI Express capability (version 1: PCI Express Base 1.1, 7.8)
const PCIE_FLAGS = 1 | 4 << 4 | 1 << 8;    // version 1, root port, slot implemented
const PCIE_DEVCAP = 1 << 15;                // role-based error reporting; 128-byte payload
const PCIE_LINK_SPEED_2_5 = 1;
const PCIE_LINK_WIDTH_X1 = 1 << 4;
const PCIE_LNKCAP_DLLLARC = 1 << 20;        // data link layer link active reporting
const PCIE_LNKSTA_SLOT_CLOCK = 1 << 12;
const PCIE_LNKSTA_DLLLA = 1 << 13;          // data link layer link active

const LNKSTA = PCIE_CAP + 0x12;
const SLTCAP = PCIE_CAP + 0x14;
const SLTCTL = PCIE_CAP + 0x18;
const SLTSTA = PCIE_CAP + 0x1A;

// Slot capabilities
const SLTCAP_ABP = 1 << 0;                  // attention button present
const SLTCAP_PCP = 1 << 1;                  // power controller present
const SLTCAP_AIP = 1 << 3;                  // attention indicator present
const SLTCAP_PIP = 1 << 4;                  // power indicator present
const SLTCAP_HPS = 1 << 5;                  // hot plug surprise
const SLTCAP_HPC = 1 << 6;                  // hot plug capable
const SLTCAP_PSN_SHIFT = 19;                // physical slot number

// Slot control: the enables of the events, in the bits of their status
// (but DLLSCE), the indicators, the power controller
const SLTCTL_EVENT_ENABLES = 0x1F;          // ABPE, PFDE, MRLSCE, PDCE, CCIE
const SLTCTL_HPIE = 1 << 5;                 // hot plug interrupt enable
const SLTCTL_AIC_OFF = 3 << 6;              // attention indicator off
const SLTCTL_PIC_ON = 1 << 8;               // power indicator on
const SLTCTL_PIC_OFF = 3 << 8;              // power indicator off
const SLTCTL_PIC = 3 << 8;                  // (the power indicator's field)
const SLTCTL_PCC = 1 << 10;                 // power controller control: set, the slot is off
const SLTCTL_DLLSCE = 1 << 12;              // data link layer state changed enable
/** What a guest may write (no electromechanical interlock: EIC reads as 0) */
const SLTCTL_WRITABLE = 0x17FF;
/** After reset, as QEMU's: a slot with a card powered, its power indicator on */
const SLTCTL_RESET_OCCUPIED = SLTCTL_AIC_OFF | SLTCTL_PIC_ON;
/** and an empty slot switched off, both indicators off */
const SLTCTL_RESET_EMPTY = SLTCTL_AIC_OFF | SLTCTL_PIC_OFF | SLTCTL_PCC;

// Slot status
const SLTSTA_ABP = 1 << 0;                  // attention button pressed
const SLTSTA_PDC = 1 << 3;                  // presence detect changed
const SLTSTA_CC = 1 << 4;                   // command completed
const SLTSTA_PDS = 1 << 6;                  // presence detect state
const SLTSTA_DLLSC = 1 << 8;                // data link layer state changed
/** The events: write one to clear (ABP, PFD, MRLSC, PDC, CC, DLLSC) */
const SLTSTA_EVENTS = 0x1F | SLTSTA_DLLSC;

/**
 * The bits of the capabilities (0x40-0xFF) a guest may write; MSI is
 * pci.msi_config_written's, the slot's control and status the port's own
 * (config_written). The other status registers (device, link, root; their
 * write-one-to-clear bits never get set) and everything else are read-only.
 */
const WRITABLE = new Uint8Array(256);
WRITABLE.set([0xFF, 0x7F], PCIE_CAP + 0x08);    // device control
WRITABLE.set([0xFB, 0x01], PCIE_CAP + 0x10);    // link control (retrain link reads as 0)
WRITABLE.set([0x1F, 0x00], PCIE_CAP + 0x1C);    // root control
WRITABLE.fill(0xFF, MSI_CAP, MSI_CAP + 14);
WRITABLE.set([0x03, 0x01], PM_CAP + 0x04);      // power state, PME enable

const STATE_FORMAT = 1;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {number} number the port, 0-5 (function number on device 28)
 * @param {number} count the root ports the machine has (function 0 then is
 *     a multi-function device)
 */
export function PCIeRootPort(cpu, number, count)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.number = number;
    this.name = "pcie_root_port" + number;
    this.pci_id = Q35_ROOT_PORT_SLOT << 3 | number;
    /** The bus behind it, as pci_ids number it: device 0 there is pci_id secondary_bus << 8 */
    this.pci_secondary_bus = number + 1;
    /** A PCI Express downstream port: its secondary bus has only device 0 */
    this.pci_express_downstream = true;
    /** PCI Express: 4 KiB of configuration space (no extended capabilities) */
    this.pci_config_size = 4096;
    /** The card's function: device 0 on the secondary bus */
    this.card_pci_id = this.pci_secondary_bus << 8;

    const device_id = ICH9_ROOT_PORT_DEVICE_ID + 2 * number;
    const space = new Array(256).fill(0);
    // 00:1c.n PCI bridge: Intel Corporation 82801I (ICH9 Family) PCI Express Port n+1 (rev 02)
    space.splice(0, 16,
        0x86, 0x80, device_id & 0xFF, device_id >> 8,
        0x00, 0x00, 0x10, 0x00,             // command; status: capabilities list
        0x02, 0x00, 0x04, 0x06,             // revision; PCI-to-PCI bridge
        0x00, 0x00, number === 0 && count > 1 ? 0x81 : 0x01, 0x00);
    space[0x24] = space[0x26] = 0x01;       // prefetchable window: 64-bit
    space[0x34] = PCIE_CAP;
    // INTA-D for ports 1-4, then INTA, INTB (D28IP's default)
    space[0x3D] = (number & 3) + 1;

    const put = (offset, bytes, value) => {
        for(let i = 0; i < bytes; i++) space[offset + i] = value >>> (i << 3) & 0xFF;
    };
    space[PCIE_CAP] = PCI_CAP_PCIE;
    space[PCIE_CAP + 1] = MSI_CAP;
    put(PCIE_CAP + 0x02, 2, PCIE_FLAGS);
    put(PCIE_CAP + 0x04, 4, PCIE_DEVCAP);
    put(PCIE_CAP + 0x0C, 4, PCIE_LINK_SPEED_2_5 | PCIE_LINK_WIDTH_X1 | PCIE_LNKCAP_DLLLARC | number + 1 << 24);
    put(LNKSTA, 2, PCIE_LINK_SPEED_2_5 | PCIE_LINK_WIDTH_X1 | PCIE_LNKSTA_SLOT_CLOCK);
    put(SLTCAP, 4, SLTCAP_ABP | SLTCAP_PCP | SLTCAP_AIP | SLTCAP_PIP | SLTCAP_HPS | SLTCAP_HPC |
        number + 1 << SLTCAP_PSN_SHIFT);
    put(SLTCTL, 2, SLTCTL_RESET_OCCUPIED);
    space.splice(MSI_CAP, 14, ...msi_capability(SSVID_CAP));
    space.splice(SSVID_CAP, 8, PCI_CAP_SSVID, PM_CAP, 0, 0,
        ...cpu.platform.qemu_compatible ? QEMU_PCI_SUBSYSTEM : [0x86, 0x80, device_id & 0xFF, device_id >> 8]);
    // PM: version 2, PME from D0, D3hot and D3cold
    space.splice(PM_CAP, 8, PCI_CAP_PM, 0x00, 0x02, 0xC8, 0x00, 0x00, 0x00, 0x00);

    this.pci_space = space;
    /** The read-only values of the capabilities */
    this.template = Uint8Array.from(space);
    this.pci_bars = [];
    this.on_config_write = (offset, size) => this.config_written(offset, size);
    this.on_config_restore = () => this.load_slot();

    /** Slot control and the events of slot status (PDS: card) */
    this.slot_control = SLTCTL_RESET_OCCUPIED;
    this.slot_status = 0;
    /** A card is in the slot */
    this.card = false;
    /** The attention button was pressed to take the card out: the guest switches the slot off for it */
    this.removal_requested = false;
    /** @type {!Array<{resolve: function(), reject: function(Error)}>} the callers waiting for that */
    this.removal_waiters = [];
    /** Whether the hot plug interrupt is signalled (MSI: sent once, until it drops) */
    this.notified = false;

    /** @const @type {!Int32Array} */
    this.pci_config = cpu.devices.pci.register_device(this);
}

/**
 * The machine's devices exist: is there a card for the slot, and is it
 * plugged in (the options' pcie_plugged)? An empty slot starts switched off.
 * @param {boolean} plugged
 */
PCIeRootPort.prototype.setup = function(plugged)
{
    this.card = this.has_card() && plugged;
    if(this.has_card() && !this.card)
    {
        this.cpu.devices.pci.set_function_present(this.card_pci_id, false);
    }
    this.slot_control = this.card ? SLTCTL_RESET_OCCUPIED : SLTCTL_RESET_EMPTY;
    dbg_log(this.name + ": " + (this.card ? "card present, link up" : this.has_card() ? "card not plugged in" : "empty"), LOG_PCI);
    this.store_slot();
};

/** @return {boolean} whether the options put a device behind the port */
PCIeRootPort.prototype.has_card = function()
{
    return this.cpu.devices.pci.devices[this.card_pci_id] !== undefined;
};

/** @return {boolean} the power controller has the slot on */
PCIeRootPort.prototype.powered = function()
{
    return !(this.slot_control & SLTCTL_PCC);
};

/**
 * @return {boolean} the slot is off and its power indicator too: the card may
 *     be taken out (a blinking indicator: the guest is not done yet)
 */
PCIeRootPort.prototype.safe_to_remove = function()
{
    return !this.powered() && (this.slot_control & SLTCTL_PIC) === SLTCTL_PIC_OFF;
};

/** The slot's registers, as the fields have them */
PCIeRootPort.prototype.store_slot = function()
{
    const bytes = this.cpu.devices.pci.space_bytes(this.pci_id);
    const put = (offset, value) => {
        bytes[offset] = value & 0xFF;
        bytes[offset + 1] = value >> 8 & 0xFF;
    };
    const link_up = this.card && this.powered();
    put(LNKSTA, PCIE_LINK_SPEED_2_5 | PCIE_LINK_WIDTH_X1 | PCIE_LNKSTA_SLOT_CLOCK | (link_up ? PCIE_LNKSTA_DLLLA : 0));
    put(SLTCTL, this.slot_control);
    put(SLTSTA, this.slot_status & SLTSTA_EVENTS | (this.card ? SLTSTA_PDS : 0));
};

/** The fields, as the restored registers have them (a snapshot) */
PCIeRootPort.prototype.load_slot = function()
{
    const bytes = this.cpu.devices.pci.space_bytes(this.pci_id);
    this.slot_control = (bytes[SLTCTL] | bytes[SLTCTL + 1] << 8) & SLTCTL_WRITABLE;
    this.slot_status = (bytes[SLTSTA] | bytes[SLTSTA + 1] << 8) & SLTSTA_EVENTS;
};

/**
 * Hot plug events: their status bits, and the interrupt if they are enabled
 * (an event already pending signals nothing new)
 * @param {number} events
 */
PCIeRootPort.prototype.event = function(events)
{
    const added = events & ~this.slot_status;
    this.slot_status |= events;
    this.store_slot();
    if(added)
    {
        this.update_interrupt();
    }
};

/**
 * The hot plug interrupt (PCI Express Base 2.0, 6.7.3.4): asserted while hot
 * plug interrupts are enabled and an enabled event is pending; with MSI, a
 * message when that starts
 */
PCIeRootPort.prototype.update_interrupt = function()
{
    const pci = this.cpu.devices.pci;
    const enabled = this.slot_control & SLTCTL_EVENT_ENABLES | (this.slot_control & SLTCTL_DLLSCE ? SLTSTA_DLLSC : 0);
    const active = (this.slot_control & SLTCTL_HPIE) !== 0 && (this.slot_status & enabled) !== 0;
    if(pci.msi_enabled(this.pci_id, MSI_CAP))
    {
        pci.lower_irq(this.pci_id);
        if(active && !this.notified)
        {
            pci.msi_notify(this.pci_id, MSI_CAP);
        }
    }
    else
    {
        pci.set_irq_level(this.pci_id, active);
    }
    this.notified = active;
};

/**
 * Plug the card in (V86.attach_pcie_device): presence detect changed. A
 * powered slot brings the link up (data link layer state changed). An
 * unpowered one (empty slots start switched off, and guests switch them off)
 * waits for the guest to switch it on: as QEMU, the attention button is
 * pressed too, for guests
 * that, like Linux, enable the button's event and not presence detect's
 * when the slot has a button (Linux then finds presence detect changed as
 * well and switches the slot on at once).
 * @return {boolean} whether it was out
 */
PCIeRootPort.prototype.insert = function()
{
    if(!this.has_card())
    {
        throw new Error("attach_pcie_device: no device for root port " + this.number + " (pcie_root_port in its options)");
    }
    if(this.card)
    {
        return false;
    }
    dbg_log(this.name + ": card plugged in", LOG_PCI);
    this.card = true;
    if(this.powered())
    {
        this.cpu.devices.pci.set_function_present(this.card_pci_id, true, true);
        this.event(SLTSTA_PDC | SLTSTA_DLLSC);
    }
    else
    {
        this.event(SLTSTA_PDC | SLTSTA_ABP);
    }
    return true;
};

/**
 * Take the card out (V86.detach_pcie_device). A surprise removal pulls it at
 * once; otherwise the attention button asks the guest, which releases the
 * device and switches the slot and its power indicator off, and the card
 * leaves then (at once if the slot is off already).
 * @param {boolean} surprise
 * @return {!Promise<void>} settled once the card is out
 */
PCIeRootPort.prototype.remove = function(surprise)
{
    if(!this.card)
    {
        return Promise.resolve();
    }
    if(surprise || !this.powered())
    {
        dbg_log(this.name + ": card pulled out" + (surprise ? " (surprise)" : ""), LOG_PCI);
        const link_was_up = this.powered();
        this.card = false;
        this.cpu.devices.pci.set_function_present(this.card_pci_id, false);
        this.event(SLTSTA_PDC | (link_was_up ? SLTSTA_DLLSC : 0));
        this.removed();
        return Promise.resolve();
    }
    const done = new Promise((resolve, reject) => this.removal_waiters.push({ resolve, reject }));
    if(!this.removal_requested)
    {
        // (pressed once: a second press would cancel the request)
        dbg_log(this.name + ": attention button pressed", LOG_PCI);
        this.removal_requested = true;
        this.event(SLTSTA_ABP);
    }
    return done;
};

/** The card is out: those waiting for its removal hear of it */
PCIeRootPort.prototype.removed = function()
{
    this.removal_requested = false;
    const waiters = this.removal_waiters;
    this.removal_waiters = [];
    waiters.forEach(waiter => waiter.resolve());
};

/**
 * The guest wrote slot control: a command, completed at once (command
 * completed). Switching the slot off takes the card off the bus (the link
 * goes down), switching it on brings the card back afresh. A card whose
 * removal was requested leaves once the slot is off and its power indicator
 * too, as with QEMU: while the indicator blinks, the guest is not done
 * (Windows switches the power off first, the indicator a moment later)
 * @param {number} value
 */
PCIeRootPort.prototype.slot_control_written = function(value)
{
    const was_powered = this.powered();
    this.slot_control = value & SLTCTL_WRITABLE;
    let events = SLTSTA_CC;
    if(this.card && was_powered !== this.powered())
    {
        const pci = this.cpu.devices.pci;
        if(this.powered())
        {
            dbg_log(this.name + ": slot switched on, link up", LOG_PCI);
            pci.set_function_present(this.card_pci_id, true, true);
        }
        else
        {
            dbg_log(this.name + ": slot switched off", LOG_PCI);
            pci.set_function_present(this.card_pci_id, false);
        }
        events |= SLTSTA_DLLSC;
    }
    if(this.card && this.removal_requested && this.safe_to_remove())
    {
        dbg_log(this.name + ": slot and power indicator off, the card leaves", LOG_PCI);
        this.card = false;
        events |= SLTSTA_PDC;
        this.removed();
    }
    this.store_slot();
    this.event(events);
};

/**
 * A guest write to the capabilities: read-only bytes and bits keep their
 * values; slot control is a command, slot status has write-one-to-clear
 * events
 * @param {number} offset
 * @param {number} size
 */
PCIeRootPort.prototype.config_written = function(offset, size)
{
    const pci = this.cpu.devices.pci;
    const bytes = pci.space_bytes(this.pci_id);
    const written = at => at >= offset && at < offset + size;
    // (what the write put into the slot's registers)
    const control = written(SLTCTL) || written(SLTCTL + 1) ? bytes[SLTCTL] | bytes[SLTCTL + 1] << 8 : -1;
    const cleared = (written(SLTSTA) ? bytes[SLTSTA] : 0) | (written(SLTSTA + 1) ? bytes[SLTSTA + 1] << 8 : 0);
    for(let o = Math.max(offset, 0x40); o < offset + size; o++)
    {
        // (no extended capabilities: 0x100 and up read as zero)
        bytes[o] = o < 0x100 ? this.template[o] & ~WRITABLE[o] | bytes[o] & WRITABLE[o] : 0;
    }
    if(offset < MSI_CAP + 14 && offset + size > MSI_CAP)
    {
        pci.msi_config_written(this.pci_id, MSI_CAP, SSVID_CAP);
    }
    this.slot_status &= ~(cleared & SLTSTA_EVENTS);
    this.store_slot();
    if(control !== -1)
    {
        this.slot_control_written(control);
    }
    // (events cleared, enables changed, or MSI switched on or off)
    this.update_interrupt();
};

/**
 * PCIRST#: as QEMU, a slot with a card powered (the power indicator on), an
 * empty one switched off; no events; a requested removal is forgotten. The
 * card stays in.
 */
PCIeRootPort.prototype.reset = function()
{
    const was_powered = this.powered();
    this.slot_control = this.card ? SLTCTL_RESET_OCCUPIED : SLTCTL_RESET_EMPTY;
    this.slot_status = 0;
    this.notified = false;
    this.removal_requested = false;
    const waiters = this.removal_waiters;
    this.removal_waiters = [];
    waiters.forEach(waiter => waiter.reject(new Error("detach_pcie_device: the machine was reset before the guest released the device")));
    if(this.card && !was_powered)
    {
        this.cpu.devices.pci.set_function_present(this.card_pci_id, true, true);
    }
    this.store_slot();
    this.cpu.devices.pci.lower_irq(this.pci_id);
};

PCIeRootPort.prototype.get_state = function()
{
    return [STATE_FORMAT, this.card, this.removal_requested, this.notified];
};

PCIeRootPort.prototype.set_state = function(state)
{
    [, this.card, this.removal_requested, this.notified] = state;
    this.load_slot();
    // those waiting for a removal: done if the restored slot is empty, still
    // waiting if the restored guest has the request too
    if(!this.card)
    {
        this.removed();
    }
    else if(!this.removal_requested)
    {
        const waiters = this.removal_waiters;
        this.removal_waiters = [];
        waiters.forEach(waiter => waiter.reject(new Error("detach_pcie_device: a snapshot without the removal was restored")));
    }
};
  source/v64/src/pflash.js                                                                            0000644 0000000 0000000 00000017122 00000000000 012271  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The UEFI firmware's variable store as CFI flash (docs/uefi.md): QEMU's
// pflash unit 1 (hw/block/pflash_cfi01.c, as OVMF's QemuFlashFvbServices
// drives it: OvmfPkg/QemuFlashFvbServicesRuntimeDxe/QemuFlash.c). In read
// array mode it is device memory that reads at memory speed and leaves
// writes here (crate::cpu::mmio_ram, read-only); a command switches it out
// of the address space, so that reads return the status register, until
// "read array" puts it back.
//
// Commands (Intel/Sharp set): 0x10 or 0x40 program a byte (the next write
// is its data), 0x20 then 0xD0 erase a 4 KiB block, 0x50 clear the status
// register, 0x70 read it, 0x90 read the identifiers, 0xFF read array. The
// status register: 0x80 ready, 0x20 erase error, 0x10 program error.
//
// The Secure Boot firmware's store (secure, QEMU's pflash with secure=on) is
// the SMM's: outside SMM writes are dropped and reads see the array, so that
// only the firmware's SMM code changes variables (the store holds the keys
// that decide what boots).
//
// The bytes are kept in a buffer object (src/buffer.js's SyncBuffer, or a
// disk written back: src/disk_writeback.js, src/opfs_disk.js), which every
// program and erase also updates: a variable store written back outlives the
// machine as a disk does, and a snapshot has its reference, or its bytes.

import { dbg_assert, dbg_log } from "./log.js";
import { LOG_BIOS } from "./const.js";
import { h } from "./lib.js";
import { restore_disk_state } from "./disk_writeback.js";

// For Types Only
import { CPU } from "./cpu.js";

const BLOCK_SIZE = 4096;

const CMD_READ_ARRAY = 0xFF;
const CMD_PROGRAM = 0x10;
const CMD_PROGRAM_ALT = 0x40;
const CMD_ERASE = 0x20;
const CMD_ERASE_CONFIRM = 0xD0;
const CMD_CLEAR_STATUS = 0x50;
const CMD_READ_STATUS = 0x70;
const CMD_READ_ID = 0x90;

const STATUS_READY = 0x80;
const STATUS_ERASE_ERROR = 0x20;
const STATUS_PROGRAM_ERROR = 0x10;

/** (Intel's manufacturer code, QEMU's default device code for its x86 machines) */
const ID_MANUFACTURER = 0x89;
const ID_DEVICE = 0x18;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {number} region the mmio_ram region of the store
 * @param {number} base its guest physical address
 * @param {!Object} buffer its bytes: get, set (synchronous), byteLength
 * @param {boolean=} secure written only in SMM
 */
export function PFlash(cpu, region, base, buffer, secure = false)
{
    this.cpu = cpu;
    this.secure = secure;
    /** Writes dropped outside SMM (diagnostics) */
    this.refused_writes = 0;
    this.region = region;
    this.base = base;
    this.buffer = buffer;
    this.size = buffer.byteLength;
    dbg_assert(this.size % BLOCK_SIZE === 0);

    /** 0: read array; else the command whose cycle runs, or the read mode */
    this.command = 0;
    this.status = 0;

    this.load();
    cpu.mmio_ram_set_writable(region, false);
    this.read_array();
}

/** The buffer's bytes into the array */
PFlash.prototype.load = function()
{
    this.buffer.get(0, this.size, data => {
        dbg_assert(data, "the variable store cannot be read");
        // (a view of the moment: the wasm memory may grow)
        new Uint8Array(this.cpu.wasm_memory.buffer, this.cpu.mmio_ram_backing(this.region) >>> 0, this.size).set(data);
    });
};

/** The array in the address space again */
PFlash.prototype.read_array = function()
{
    this.command = 0;
    this.cpu.mmio_ram_map(this.region, this.base | 0);
};

/**
 * A mode whose reads are not the array's: out of the address space
 * @param {number} command
 */
PFlash.prototype.enter = function(command)
{
    if(this.command === 0)
    {
        this.cpu.mmio_ram_unmap(this.region);
    }
    this.command = command;
};

/**
 * A read outside read array mode
 * @param {number} offset
 * @return {number}
 */
PFlash.prototype.read = function(offset)
{
    // (outside SMM a secure store reads as its array, whatever mode SMM left it in)
    if(this.secure && !this.cpu.smm_active())
    {
        return this.array_byte(offset);
    }
    switch(this.command)
    {
        case 0:
            return this.array_byte(offset);
        case CMD_READ_ID:
            return (offset & 0xFF) === 0 ? ID_MANUFACTURER : (offset & 0xFF) === 1 ? ID_DEVICE : 0;
        default:
            // (the program, erase, clear and read status cycles)
            return this.status;
    }
};

/** @param {number} offset */
PFlash.prototype.array_byte = function(offset)
{
    // (the wasm memory may have grown since: a view of the moment)
    return this.cpu.mmio_ram_read8(this.region, offset);
};

/**
 * A write anywhere in the store
 * @param {number} offset
 * @param {number} value
 */
PFlash.prototype.write = function(offset, value)
{
    if(this.secure && !this.cpu.smm_active())
    {
        if(this.refused_writes++ === 0)
        {
            dbg_log("pflash: a write outside SMM to the Secure Boot firmware's variable store, dropped", LOG_BIOS);
        }
        return;
    }
    value &= 0xFF;
    switch(this.command)
    {
        case CMD_PROGRAM:
        case CMD_PROGRAM_ALT:
            if(this.status & 0x7F)
            {
                // (an error not cleared: the device refuses the program)
                this.status |= STATUS_READY | STATUS_PROGRAM_ERROR;
            }
            else
            {
                this.store(offset, Uint8Array.of(value));
                this.status |= STATUS_READY;
            }
            // (the status register's read mode until "read array")
            this.command = CMD_READ_STATUS;
            return;
        case CMD_ERASE:
            if(value === CMD_ERASE_CONFIRM)
            {
                const start = offset & ~(BLOCK_SIZE - 1);
                this.store(start, new Uint8Array(BLOCK_SIZE).fill(0xFF));
                this.status |= STATUS_READY;
            }
            else
            {
                this.status |= STATUS_READY | STATUS_ERASE_ERROR | STATUS_PROGRAM_ERROR;
            }
            this.command = CMD_READ_STATUS;
            return;
    }
    switch(value)
    {
        case CMD_READ_ARRAY:
            this.read_array();
            break;
        case CMD_CLEAR_STATUS:
            this.status = 0;
            this.read_array();
            break;
        case CMD_PROGRAM:
        case CMD_PROGRAM_ALT:
        case CMD_ERASE:
        case CMD_READ_STATUS:
        case CMD_READ_ID:
            this.enter(value);
            break;
        default:
            dbg_log("pflash: unknown command " + h(value, 2) + " at " + h(offset, 5), LOG_BIOS);
            this.read_array();
    }
};

/**
 * Bytes into the array and the buffer
 * @param {number} offset
 * @param {!Uint8Array} data
 */
PFlash.prototype.store = function(offset, data)
{
    new Uint8Array(this.cpu.wasm_memory.buffer, this.cpu.mmio_ram_backing(this.region) >>> 0, this.size).set(data, offset);
    this.buffer.set(offset, data, error => {
        if(error)
        {
            // (the firmware sees a failed program or erase)
            dbg_log("pflash: the variable store could not be written: " + error.message, LOG_BIOS);
            this.status |= STATUS_PROGRAM_ERROR;
        }
    });
};

/** The machine's power-on: read array mode, the status clear; the array's bytes stay */
PFlash.prototype.reset = function()
{
    this.status = 0;
    this.read_array();
};

PFlash.prototype.get_state = function()
{
    return [this.command, this.status, this.buffer.get_state()];
};

PFlash.prototype.set_state = function(state)
{
    // (checked before: CPU.prototype.validate_state)
    restore_disk_state(this.buffer, state[2]);
    this.load();
    this.status = state[1];
    if(state[0] === 0)
    {
        this.read_array();
    }
    else
    {
        this.enter(state[0]);
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/pit.js                                                                               0000644 0000000 0000000 00000022376 00000000000 011617  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_PIT } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";


// In kHz
export const OSCILLATOR_FREQ = 1193.1816666; // 1.193182 MHz

/**
 * @constructor
 *
 * Programmable Interval Timer
 */
export function PIT(cpu, bus)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    this.bus = bus;

    this.counter_start_time = new Float64Array(3);
    this.counter_start_value = new Uint16Array(3);

    this.counter_next_low = new Uint8Array(4);
    this.counter_enabled = new Uint8Array(4);
    this.counter_mode = new Uint8Array(4);
    this.counter_read_mode = new Uint8Array(4);

    // 2 = latch low, 1 = latch high, 0 = no latch
    this.counter_latch = new Uint8Array(4);
    this.counter_latch_value = new Uint16Array(3);

    this.counter_reload = new Uint16Array(3);

    // TODO:
    // - counter2 can be controlled by an input

    cpu.io.register_read(0x61, this, function()
    {
        var now = this.cpu.clock.now();

        var ref_toggle = (now * (1000 * 1000 / 15000)) & 1;
        var counter2_out = this.did_rollover(2, now);

        return ref_toggle << 4 | counter2_out << 5;
    });
    cpu.io.register_write(0x61, this, function(data)
    {
        if(data & 1)
        {
            this.bus.send("pcspeaker-enable");
        }
        else
        {
            this.bus.send("pcspeaker-disable");
        }
    });

    cpu.io.register_read(0x40, this, function() { return this.counter_read(0); });
    cpu.io.register_read(0x41, this, function() { return this.counter_read(1); });
    cpu.io.register_read(0x42, this, function() { return this.counter_read(2); });

    cpu.io.register_write(0x40, this, function(data) { this.counter_write(0, data); });
    cpu.io.register_write(0x41, this, function(data) { this.counter_write(1, data); });
    cpu.io.register_write(0x42, this, function(data) {
        this.counter_write(2, data);
        this.bus.send("pcspeaker-update", [this.counter_mode[2], this.counter_reload[2]]);
    });

    cpu.io.register_write(0x43, this, this.port43_write);
}

PIT.prototype.get_state = function()
{
    var state = [];

    state[0] = this.counter_next_low;
    state[1] = this.counter_enabled;
    state[2] = this.counter_mode;
    state[3] = this.counter_read_mode;
    state[4] = this.counter_latch;
    state[5] = this.counter_latch_value;
    state[6] = this.counter_reload;
    state[7] = this.counter_start_time;
    state[8] = this.counter_start_value;

    return state;
};

PIT.prototype.set_state = function(state)
{
    this.counter_next_low = state[0];
    this.counter_enabled = state[1];
    this.counter_mode = state[2];
    this.counter_read_mode = state[3];
    this.counter_latch = state[4];
    this.counter_latch_value = state[5];
    this.counter_reload = state[6];
    this.counter_start_time = state[7];
    this.counter_start_value = state[8];
};

/** Counter 0's output reaches IRQ 0, unless the HPET's legacy replacement route took it */
PIT.prototype.drives_irq0 = function()
{
    const hpet = this.cpu.devices.hpet;
    return !hpet || !hpet.legacy_replacement();
};

PIT.prototype.timer = function(now, no_irq)
{
    var time_to_next_interrupt = 100;

    // counter 0 produces interrupts
    if(!no_irq)
    {
        if(this.counter_enabled[0] && this.did_rollover(0, now))
        {
            const deadline = this.counter_start_time[0] + this.counter_start_value[0] / OSCILLATOR_FREQ;
            const period = this.counter_reload[0] / OSCILLATOR_FREQ;
            // Coalesce missed periods, retaining the original phase. Rearming
            // at 'now' would discard the fractional PIT tick on every service.
            this.counter_start_time[0] = deadline + Math.floor((now - deadline) / period) * period;
            this.counter_start_value[0] = this.counter_reload[0];

            dbg_log("pit interrupt. new value: " + this.counter_start_value[0], LOG_PIT);

            // This isn't strictly correct, but it's necessary since browsers
            // may sleep longer than necessary to trigger the else branch below
            // and clear the irq
            if(this.drives_irq0())
            {
                this.cpu.device_lower_irq(0);
                this.cpu.device_raise_irq(0);
            }
            var mode = this.counter_mode[0];

            if(mode === 0)
            {
                this.counter_enabled[0] = 0;
            }
        }
        else if(this.drives_irq0())
        {
            this.cpu.device_lower_irq(0);
        }

        if(this.counter_enabled[0])
        {
            time_to_next_interrupt = Math.max(0,
                this.counter_start_time[0] + this.counter_start_value[0] / OSCILLATOR_FREQ - now);
        }
    }

    return time_to_next_interrupt;
};

PIT.prototype.get_counter_value = function(i, now)
{
    if(!this.counter_enabled[i])
    {
        return 0;
    }

    const deadline = this.counter_start_time[i] + this.counter_start_value[i] / OSCILLATOR_FREQ;
    if(now >= deadline)
    {
        const reload = this.counter_reload[i];
        return this.counter_mode[i] === 0 ? 0 :
            reload - Math.floor((now - deadline) * OSCILLATOR_FREQ) % reload;
    }
    const elapsed = Math.floor((now - this.counter_start_time[i]) * OSCILLATOR_FREQ);
    return Math.max(1, this.counter_start_value[i] - elapsed);
};

PIT.prototype.did_rollover = function(i, now)
{
    var diff = now - this.counter_start_time[i];

    if(diff < 0)
    {
        // should only happen after restore_state
        dbg_log("Warning: PIT timer difference is negative, resetting (timer " + i + ")");
        return true;
    }
    // Compare the same absolute deadline returned by timer(). Multiplying the
    // rounded floating-point delta back into ticks can miss an exact deadline.
    return now >= this.counter_start_time[i] + this.counter_start_value[i] / OSCILLATOR_FREQ;
};

PIT.prototype.counter_read = function(i)
{
    var latch = this.counter_latch[i];

    if(latch)
    {
        this.counter_latch[i]--;

        if(latch === 2)
        {
            return this.counter_latch_value[i] & 0xFF;
        }
        else
        {
            return this.counter_latch_value[i] >> 8;
        }
    }
    else
    {
        var next_low = this.counter_next_low[i];

        if(this.counter_mode[i] === 3)
        {
            this.counter_next_low[i] ^= 1;
        }

        var value = this.get_counter_value(i, this.cpu.clock.now());

        if(next_low)
        {
            return value & 0xFF;
        }
        else
        {
            return value >> 8;
        }
    }
};

PIT.prototype.counter_write = function(i, value)
{
    if(this.counter_next_low[i])
    {
        this.counter_reload[i] = this.counter_reload[i] & ~0xFF | value;
    }
    else
    {
        this.counter_reload[i] = this.counter_reload[i] & 0xFF | value << 8;
    }

    if(this.counter_read_mode[i] !== 3 || !this.counter_next_low[i])
    {
        if(!this.counter_reload[i])
        {
            this.counter_reload[i] = 0xFFFF;
        }

        // depends on the mode, should actually
        // happen on the first tick
        this.counter_start_value[i] = this.counter_reload[i];

        this.counter_enabled[i] = true;

        this.counter_start_time[i] = this.cpu.clock.now();

        dbg_log("counter" + i + " reload=" + h(this.counter_reload[i]) +
                " tick=" + (this.counter_reload[i] || 0x10000) / OSCILLATOR_FREQ + "ms", LOG_PIT);
    }

    if(this.counter_read_mode[i] === 3)
    {
        this.counter_next_low[i] ^= 1;
    }
};

PIT.prototype.port43_write = function(reg_byte)
{
    var mode = reg_byte >> 1 & 7,
        binary_mode = reg_byte & 1,
        i = reg_byte >> 6 & 3,
        read_mode = reg_byte >> 4 & 3;

    if(i === 1)
    {
        dbg_log("Unimplemented timer1", LOG_PIT);
    }

    if(i === 3)
    {
        dbg_log("Unimplemented read back", LOG_PIT);
        return;
    }

    if(read_mode === 0)
    {
        // latch
        this.counter_latch[i] = 2;
        var value = this.get_counter_value(i, this.cpu.clock.now());
        dbg_log("latch: " + value, LOG_PIT);
        this.counter_latch_value[i] = value ? value - 1 : 0;

        return;
    }

    if(mode >= 6)
    {
        // 6 and 7 are aliased to 2 and 3
        mode &= ~4;
    }

    dbg_log("Control: mode=" + mode + " ctr=" + i +
            " read_mode=" + read_mode + " bcd=" + binary_mode, LOG_PIT);

    if(read_mode === 1)
    {
        // lsb
        this.counter_next_low[i] = 1;
    }
    else if(read_mode === 2)
    {
        // msb
        this.counter_next_low[i] = 0;
    }
    else
    {
        // first lsb then msb
        this.counter_next_low[i] = 1;
    }

    if(i === 0 && this.drives_irq0())
    {
        this.cpu.device_lower_irq(0);
    }

    if(mode === 0)
    {
    }
    else if(mode === 3 || mode === 2)
    {
        // what is the difference
    }
    else
    {
        dbg_log("Unimplemented counter mode: " + h(mode), LOG_PIT);
    }

    this.counter_mode[i] = mode;
    this.counter_read_mode[i] = read_mode;

    if(i === 2)
    {
        this.bus.send("pcspeaker-update", [this.counter_mode[2], this.counter_reload[2]]);
    }
};

PIT.prototype.dump = function()
{
    const reload = this.counter_reload[0];
    const time = (reload || 0x10000) / OSCILLATOR_FREQ;
    dbg_log("counter0 ticks every " + time + "ms (reload=" + reload + ")");
};
                                                                                                                                                                                                                                                                  source/v64/src/platform.js                                                                          0000644 0000000 0000000 00000047522 00000000000 012647  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Description of the emulated PC platform: the single source for the ACPI
// tables (src/acpi_tables.js), the fw_cfg and CMOS inputs of the firmware,
// and the fixed resources of the devices that implement them.
// See docs/acpi.md.

import { dbg_assert } from "./log.js";
import { h } from "./lib.js";
import { MACHINE_TYPES, MAX_CORES, Q35_ROOT_PORTS_MAX } from "./machine_options.js";


export const LAPIC_ADDRESS = 0xFEE00000;
export const IOAPIC_ADDRESS = 0xFEC00000;
/** Must match IOAPIC_ID in src/rust/cpu/ioapic.rs */
export const IOAPIC_ID = 0;

/** PCI memory BARs must lie below the IOAPIC; v86 does not relocate them */
export const PCI_MMIO_END = 0xFEBFFFFF;

// PIIX4 power management function (PCI 00:07.0)
export const ACPI_PM_PCI_ID = 0x07 << 3;

/** The PCI subsystem (vendor 1AF4, device 1100) of QEMU's emulated devices */
export const QEMU_PCI_SUBSYSTEM = [0xF4, 0x1A, 0x00, 0x11];

// settings.machine_type: see src/machine_options.js ("i440fx", "q35" and,
// with cpu_type "arm64", "virt"); this file describes the PC machines
// (MAX_CORES must match src/rust/cpu/apic.rs: src/machine_options.js)
export { MACHINE_TYPES, MAX_CORES, Q35_ROOT_PORTS_MAX } from "./machine_options.js";

/**
 * Version of the device layout a snapshot records with its machine type;
 * raised when a machine's devices change in a way old snapshots can't express
 */
export const MACHINE_LAYOUT_VERSION = 1;

// Q35. SeaBIOS rel-1.16.2 programs PCIEXBAR to this fixed address and then
// allocates PCI memory above the ECAM window (src/fw/dev-q35.h, pciinit.c
// mch_mem_addr_setup); the platform has to match it.
export const Q35_ECAM_BASE = 0xB0000000;
export const Q35_ECAM_SIZE = 0x10000000;
export const Q35_PCI_MMIO_START = Q35_ECAM_BASE + Q35_ECAM_SIZE;
/**
 * The UEFI firmware (OVMF, docs/uefi.md) has its own layout: Q35's ECAM at
 * its PcdPciExpressBaseAddress, PCI memory from its Uc32Base (4 GiB less
 * the largest power of two that fits between RAM and 4 GiB) up to the ECAM
 * on Q35, up to 0xFC000000 on i440FX (OvmfPkg PlatformInitLib)
 */
export const OVMF_Q35_ECAM_BASE = 0xE0000000;
/** @param {number} memory_size RAM below 4 GiB */
export function ovmf_pci_mmio_start(memory_size)
{
    const gap = 2 ** 32 - memory_size;
    return 2 ** 32 - 2 ** Math.floor(Math.log2(gap));
}
/** The TPM's CRB (docs/tpm.md, src/tpm/crb.js): five localities of 4 KiB */
export const TPM_CRB_BASE = 0xFED40000;
export const TPM_CRB_SIZE = 0x5000;
/** ICH9 root complex register block (LPC config 0xF0), as SeaBIOS programs it */
export const ICH9_RCBA_ADDRESS = 0xFED1C000;
export const ICH9_RCBA_SIZE = 0x4000;
/** The ICH9 PM I/O block decoded at PMBASE (LPC config 0x40), 128-aligned */
export const ICH9_PM_LENGTH = 0x80;
/** GPE0_STS (8 bytes) and GPE0_EN (8 bytes) inside the ICH9 PM block */
export const ICH9_GPE0_OFFSET = 0x20;
export const ICH9_GPE0_LENGTH = 0x10;
/** SMI_CMD values of QEMU's ICH9 (include/hw/southbridge/ich9.h) */
export const ICH9_ACPI_ENABLE = 0x02;
export const ICH9_ACPI_DISABLE = 0x03;

// PCI functions of the Q35 chipset (bus 0)
export const Q35_MCH_PCI_ID = 0x00 << 3;
export const ICH9_LPC_PCI_ID = 0x1F << 3;
export const ICH9_AHCI_PCI_ID = 0x1F << 3 | 2;
/** Device numbers that only the chipset may use */
const Q35_CHIPSET_SLOTS = [0x00, 0x1F];
/** ICH9's PCI Express root ports: device 28, one function per port (src/pcie_root_port.js) */
export const Q35_ROOT_PORT_SLOT = 0x1C;

/**
 * PCI functions (device << 3 | function on bus 0) of the devices whose place
 * differs between the machine layouts. i440FX: v86's layout, or QEMU's PC with
 * settings.qemu_compatible (a Windows installed under QEMU then finds its
 * devices where they were). Q35: QEMU's layout (display at 00:01.0, the first
 * network card at 00:02.0) with the chipset at 00:00.0 and 00:1f.*.
 * Functions a machine does not have are -1.
 * @param {?Platform} platform
 * The HD Audio controller (audio_device "hd_audio") is where ICH6 and ICH9
 * have it, 00:1b.0, as with QEMU's Q35; QEMU's PC has no fixed place, the
 * first after its network card is 00:04.0. The UHCI controller (usb) is
 * ICH9's at 00:1d.0, PIIX3's function 2 of 00:01 on i440FX (QEMU's -usb):
 * SeaBIOS's PCI IRQ routing table, which Windows without ACPI goes by,
 * covers devices 1 to 6 only. EHCI (usb.controller "ehci") is function 7 of
 * a device whose functions 0 to 2 are its UHCI companions: 00:1d as ICH9
 * and QEMU have it (QEMU's PC too, in its example), v86's PC at 00:06
 * (inside that table). xHCI ("xhci") is at 00:14.0, where Intel's PCHs
 * have it (QEMU's PC: 00:05.0, the first slot after its sound card).
 * @return {{ide: number, acpi_pm: number, vga: number, ne2k: number, lpc: number, ahci: number, hda: number, uhci: number,
 *     ehci: number, xhci: number}}
 */
export function pci_functions(platform)
{
    if(platform && platform.machine === "q35")
    {
        return { ide: -1, acpi_pm: -1, vga: 0x01 << 3, ne2k: 0x02 << 3, lpc: ICH9_LPC_PCI_ID, ahci: ICH9_AHCI_PCI_ID, hda: 0x1B << 3,
            uhci: 0x1D << 3, ehci: 0x1D << 3 | 7, xhci: 0x14 << 3 };
    }
    return platform && platform.qemu_compatible ?
        { ide: 0x01 << 3 | 1, acpi_pm: 0x01 << 3 | 3, vga: 0x02 << 3, ne2k: 0x03 << 3, lpc: -1, ahci: -1, hda: 0x04 << 3, uhci: 0x01 << 3 | 2,
            ehci: 0x1D << 3 | 7, xhci: 0x05 << 3 } :
        { ide: 0x1E << 3, acpi_pm: ACPI_PM_PCI_ID, vga: 0x12 << 3, ne2k: 0x05 << 3, lpc: -1, ahci: -1, hda: 0x1B << 3, uhci: 0x01 << 3 | 2,
            ehci: 0x06 << 3 | 7, xhci: 0x14 << 3 };
}
/**
 * The root bridge's 32-bit PCI memory windows, [first, last] each: from
 * pci_mmio_start to PCI_MMIO_END, less the ECAM window where it lies inside
 * (OVMF's Q35 layout)
 * @param {Platform} platform
 * @return {!Array<!Array<number>>}
 */
export function pci_memory_windows(platform)
{
    const start = platform.pci_mmio_start;
    const ecam = platform.ecam;
    if(!ecam || ecam.base + ecam.size <= start || ecam.base > PCI_MMIO_END)
    {
        return [[start, PCI_MMIO_END]];
    }
    return [[start, ecam.base - 1], [ecam.base + ecam.size, PCI_MMIO_END]].filter(([first, last]) => first <= last);
}

/** PM I/O block size decoded at PMBA (PCI config 0x40) */
export const ACPI_PM_LENGTH = 0x40;
/**
 * PM base that SeaBIOS programs when it loads v86's tables through
 * etc/table-loader (src/fw/paravirt.c). The device decodes whatever the
 * firmware writes to PMBA; the tables are generated from that value.
 */
export const ACPI_PM_BASE_DEFAULT = 0x600;
export const ACPI_GPE0_BASE = 0xAFE0;
export const ACPI_GPE0_LENGTH = 4;
export const ACPI_SMI_CMD_PORT = 0xB2;
export const ACPI_ENABLE = 0xF1;
export const ACPI_DISABLE = 0xF0;
export const ACPI_SCI_IRQ = 9;

/** PIIX reset control register; the FADT reset register writes RESET_VALUE to it */
export const RESET_PORT = 0xCF9;
export const RESET_VALUE = 0x06;

export const FW_CFG_PORT = 0x510;

/**
 * ISA IRQs that the PCI interrupt links (PIRQA..D) may use. SeaBIOS routes
 * them to 10, 10, 11, 11. IRQ 5 is not offered: the SB16 uses it.
 */
export const PCI_LINK_IRQS = [10, 11];

/**
 * Sleep states. The SLP_TYP values are what the ACPI device decodes; the
 * tables advertise a state only when it is supported.
 */
export const ACPI_SLEEP_STATES = [
    // S3 (suspend to RAM): cores stop, RAM and the BIOS shadow are kept; a
    // wake event resets CPUs and devices and SeaBIOS jumps to the FACS
    // waking vector
    { state: 3, slp_typ: 1, supported: true },
    // S4 (OS-directed hibernation): a soft off for the hardware; the guest
    // restores itself from disk at the next power-on
    { state: 4, slp_typ: 2, supported: true },
    // S5 (soft off)
    { state: 5, slp_typ: 0, supported: true },
];

/**
 * Sleep states of the Q35 machine: S3 and S4 stay unadvertised until the
 * firmware's resume path and the AHCI lifecycle are verified for them (see
 * docs/q35.md); the encodings match the i440FX ones.
 */
const Q35_SLEEP_STATES = ACPI_SLEEP_STATES.map(s => ({ state: s.state, slp_typ: s.slp_typ, supported: s.state === 5 }));
/** With the UEFI firmware, likewise on both machines: OVMF's S3 resume and its S4 path are not verified yet */
const UEFI_SLEEP_STATES = Q35_SLEEP_STATES;

/**
 * Legacy devices at fixed resources. `when` names the setting that enables an
 * optional device.
 */
const UARTS = [
    { port: 0x3F8, irq: 4 },
    { port: 0x2F8, irq: 3, when: "uart1" },
    { port: 0x3E8, irq: 4, when: "uart2" },
    { port: 0x2E8, irq: 3, when: "uart3" },
];

const PARALLEL_PORTS = [
    { port: 0x378, irq: 7 },
    { port: 0x278, irq: 5, when: "parallel1" },
];

/**
 * @typedef {{
 *     cores: number,
 *     topology: {sockets: number, cores_per_socket: number, threads_per_core: number, logical_processors: number, package_shift: number},
 *     cpuid_profile: string,
 *     apic_ids: !Array<number>,
 *     memory_size: number,
 *     pci_mmio_start: number,
 *     uarts: !Array<{index: number, port: number, irq: number}>,
 *     parallel_ports: !Array<{index: number, port: number, irq: number}>,
 *     qemu_compatible: boolean,
 *     machine: string,
 *     firmware: string,
 *     tpm: boolean,
 *     acpi: boolean,
 *     ecam: ?{base: number, size: number},
 *     pm: {length: number, gpe0_offset: number, gpe0_base: number, gpe0_length: number, acpi_enable: number, acpi_disable: number},
 *     sleep_states: !Array<{state: number, slp_typ: number, supported: boolean}>,
 *     reserved_pci_slots: !Array<number>,
 *     pcie_root_ports: number,
 *     root_port_devices: !Object<string, number>,
 *     hpet: boolean,
 *     smbus: boolean,
 * }}
 */
export var Platform;

/**
 * The built-in devices that may sit behind a root port (their options'
 * pcie_root_port), by their name in settings.root_port_devices
 */
export const ROOT_PORT_DEVICES = ["net", "virtio_9p", "virtio_console", "virtio_balloon"];

/**
 * The machine type of the settings, validated
 * @param {Object} settings
 * @return {string}
 */
export function machine_type(settings)
{
    const machine = settings.machine_type === undefined ? "i440fx" : settings.machine_type;
    if(!MACHINE_TYPES.includes(machine))
    {
        throw new Error("machine_type must be one of " + MACHINE_TYPES.map(m => "\"" + m + "\"").join(", ") + ", got " + JSON.stringify(machine));
    }
    if(machine === "virt")
    {
        throw new Error("machine_type \"virt\" is not a PC machine (cpu_type \"arm64\")");
    }
    return machine;
}

/**
 * Whether the machine has ACPI: as configured; Q35 has it unless switched off,
 * which it does not support (SeaBIOS's fallback DSDT only describes an i440FX,
 * and v86 without ACPI has neither the PM function nor the IOAPIC)
 * @param {Object} settings
 * @return {boolean}
 */
export function machine_acpi(settings)
{
    if(machine_type(settings) === "q35")
    {
        if(settings.acpi === false)
        {
            throw new Error("machine_type \"q35\" requires ACPI (it is on by default); acpi: false is not supported");
        }
        return true;
    }
    return !!settings.acpi;
}

/**
 * @param {Object} settings
 * @param {number} memory_size RAM below 4 GiB in bytes
 * @return {Platform}
 */
export function create_platform(settings, memory_size)
{
    const enabled = device => !device.when || !!settings[device.when];
    const indexed = list => list.map((device, index) => ({ index, port: device.port, irq: device.irq })).filter((_, i) => enabled(list[i]));

    const machine = machine_type(settings);
    const acpi = machine_acpi(settings);
    const q35 = machine === "q35";

    // One socket, `cpu_cores` cores, one thread per core. CPUID, fw_cfg, CMOS
    // and the MADT all read the core count from here.
    const cores = settings.cpu_cores === undefined ? 1 : settings.cpu_cores;
    if(!Number.isInteger(cores) || cores < 1 || cores > MAX_CORES)
    {
        throw new Error("cpu_cores must be an integer from 1 to " + MAX_CORES + ", got " + cores);
    }
    if(cores > 1 && !acpi)
    {
        throw new Error("cpu_cores > 1 requires acpi: true (it enables the local APICs)");
    }
    if(settings.tpm && !acpi)
    {
        throw new Error("tpm requires acpi: true (the ACPI tables describe the TPM)");
    }
    if(q35 && memory_size > Q35_ECAM_BASE)
    {
        throw new Error("machine_type \"q35\": RAM below 4 GiB must end below the ECAM window at 0x" + Q35_ECAM_BASE.toString(16));
    }

    // Q35: the ICH9 PCI Express root ports (settings.pcie_root_ports)
    const root_ports = settings.pcie_root_ports === undefined ? 0 : settings.pcie_root_ports;
    if(!(Number.isInteger(root_ports) && root_ports >= 0 && root_ports <= Q35_ROOT_PORTS_MAX))
    {
        throw new Error("pcie_root_ports must be an integer from 0 to " + Q35_ROOT_PORTS_MAX + ", got " + root_ports);
    }
    if(root_ports && !q35)
    {
        throw new Error("pcie_root_ports requires machine_type \"q35\"");
    }
    // built-in devices behind root ports (settings.root_port_devices: their
    // root port, and whether they start plugged in), one per port
    const root_port_devices = {};
    const taken = new Set();
    for(const [name, placement] of Object.entries(settings.root_port_devices || {}))
    {
        const port = placement.port;
        if(!ROOT_PORT_DEVICES.includes(name))
        {
            throw new Error("root_port_devices: unknown device " + JSON.stringify(name));
        }
        if(!(Number.isInteger(port) && port >= 0 && port < root_ports))
        {
            throw new Error(name + ": pcie_root_port must be the number of a root port (0 to pcie_root_ports - 1), got " +
                port + (q35 ? "" : " (root ports need machine_type \"q35\")"));
        }
        if(taken.has(port))
        {
            throw new Error(name + ": root port " + port + " is taken by another device");
        }
        taken.add(port);
        root_port_devices[name] = port;
    }
    // Q35: ICH9's high precision event timer (settings.hpet) and SMBus
    // controller (settings.smbus)
    const hpet = !!settings.hpet;
    if(hpet && !q35)
    {
        throw new Error("hpet requires machine_type \"q35\"");
    }
    const smbus = !!settings.smbus;
    if(smbus && !q35)
    {
        throw new Error("smbus requires machine_type \"q35\"");
    }

    // i440FX: the PCI memory window starts at the first 256 MiB boundary above
    // RAM (OVMF allocates at or above it too). Q35: above the ECAM window,
    // where SeaBIOS allocates the BARs; with UEFI where OVMF does, below its
    // ECAM window (which the tables leave out of the PCI window)
    const uefi = !!settings.firmware && settings.firmware.type === "uefi";
    const pci_mmio_start = q35 ? (uefi ? ovmf_pci_mmio_start(memory_size) : Q35_PCI_MMIO_START) :
        Math.ceil(memory_size / 0x10000000) * 0x10000000;

    const platform = {
        cores,
        topology: {
            sockets: 1,
            cores_per_socket: cores,
            threads_per_core: 1,
            logical_processors: cores,
            package_shift: Math.ceil(Math.log2(cores)),
        },
        cpuid_profile: cores === 1 ? "legacy" : "smp32",
        apic_ids: Array.from({ length: cores }, (_, i) => i),
        memory_size,
        pci_mmio_start,
        uarts: indexed(UARTS),
        parallel_ports: indexed(PARALLEL_PORTS),
        // devices with the places and identities of QEMU's i440FX PC
        // (pci_functions, and the ACPI namespace, see acpi_tables.js); on
        // Q35 the layout is always QEMU's, the option keeps QEMU's
        // identities (subsystem, drive names)
        qemu_compatible: !!settings.qemu_compatible,
        machine,
        // "seabios" (bios, vga_bios) or "uefi" (firmware: { type: "uefi" })
        firmware: uefi ? "uefi" : "seabios",
        // a TPM 2.0 (tpm: docs/tpm.md): its device and TPM2 table
        tpm: !!settings.tpm,
        acpi,
        ecam: q35 ? { base: uefi ? OVMF_Q35_ECAM_BASE : Q35_ECAM_BASE, size: Q35_ECAM_SIZE } : null,
        // The power management block: PIIX4 (PMBA, separate GPE0 block) or
        // ICH9 (PMBASE, GPE0 inside the block). gpe0_base is absolute for
        // PIIX4; ICH9's is pm_base + gpe0_offset (gpe0_block).
        pm: q35 ?
            { length: ICH9_PM_LENGTH, gpe0_offset: ICH9_GPE0_OFFSET, gpe0_base: -1, gpe0_length: ICH9_GPE0_LENGTH,
              acpi_enable: ICH9_ACPI_ENABLE, acpi_disable: ICH9_ACPI_DISABLE } :
            { length: ACPI_PM_LENGTH, gpe0_offset: -1, gpe0_base: ACPI_GPE0_BASE, gpe0_length: ACPI_GPE0_LENGTH,
              acpi_enable: ACPI_ENABLE, acpi_disable: ACPI_DISABLE },
        sleep_states: uefi ? UEFI_SLEEP_STATES : q35 ? Q35_SLEEP_STATES : ACPI_SLEEP_STATES,
        reserved_pci_slots: q35 ? Q35_CHIPSET_SLOTS.concat(root_ports ? [Q35_ROOT_PORT_SLOT] : []) : [],
        // the root ports at 00:1c.0 and up; behind port n is the bus that
        // pci_ids number n + 1
        pcie_root_ports: root_ports,
        root_port_devices,
        hpet,
        smbus,
    };

    check_platform(platform);
    return platform;
}

/**
 * The GPE0 register block (status, then enable bytes) for a PM base
 * @param {Platform} platform
 * @param {number} pm_base
 * @return {{base: number, length: number}}
 */
export function gpe0_block(platform, pm_base)
{
    const pm = platform.pm;
    return { base: pm.gpe0_offset >= 0 ? pm_base + pm.gpe0_offset : pm.gpe0_base, length: pm.gpe0_length };
}

/**
 * I/O port ranges with a fixed owner. Everything the tables describe must be
 * in here, and no two ranges may overlap.
 * @param {Platform} platform
 * @param {number=} pm_base
 * @return {!Array<{name: string, start: number, length: number}>}
 */
export function platform_io_ranges(platform, pm_base)
{
    const ranges = [
        { name: "dma1", start: 0x00, length: 0x10 },
        { name: "pic1", start: 0x20, length: 2 },
        { name: "pit", start: 0x40, length: 4 },
        { name: "kbd-data", start: 0x60, length: 1 },
        { name: "speaker", start: 0x61, length: 1 },
        { name: "kbd-cmd", start: 0x64, length: 1 },
        { name: "rtc", start: 0x70, length: 2 },
        { name: "dma-page", start: 0x80, length: 0x10 },
        { name: "port92", start: 0x92, length: 1 },
        { name: "pic2", start: 0xA0, length: 2 },
        { name: "smi-cmd", start: ACPI_SMI_CMD_PORT, length: 2 },
        { name: "dma2", start: 0xC0, length: 0x20 },
        { name: "fpu", start: 0xF0, length: 0x10 },
        { name: "sb16", start: 0x220, length: 0x10 },
        { name: "fdc", start: 0x3F2, length: 4 },
        { name: "fdc-dir", start: 0x3F7, length: 1 },
        { name: "elcr", start: 0x4D0, length: 2 },
        { name: "fw-cfg", start: FW_CFG_PORT, length: 2 },
        { name: "pci-config", start: 0xCF8, length: 8 },
    ];
    if(platform.pm.gpe0_offset < 0)
    {
        // (ICH9's GPE0 block is part of the PM block)
        ranges.push({ name: "gpe0", start: platform.pm.gpe0_base, length: platform.pm.gpe0_length });
    }

    for(const { index, port } of platform.uarts)
    {
        ranges.push({ name: "uart" + index, start: port, length: 8 });
    }
    for(const { index, port } of platform.parallel_ports)
    {
        ranges.push({ name: "parallel" + index, start: port, length: 8 });
    }
    if(pm_base !== undefined)
    {
        ranges.push({ name: "acpi-pm", start: pm_base, length: platform.pm.length });
    }

    return ranges;
}

/**
 * @param {Platform} platform
 * @param {number=} pm_base
 */
export function check_platform(platform, pm_base)
{
    const ranges = platform_io_ranges(platform, pm_base).sort((a, b) => a.start - b.start);

    for(let i = 1; i < ranges.length; i++)
    {
        const a = ranges[i - 1];
        const b = ranges[i];
        if(a.start + a.length > b.start)
        {
            throw new Error("Platform I/O conflict: " + a.name + " " + h(a.start, 4) + " overlaps " + b.name + " " + h(b.start, 4));
        }
    }

    dbg_assert(platform.cores >= 1 && platform.apic_ids.length === platform.cores);
    dbg_assert(platform.pci_mmio_start <= 0xE0000000, "RAM overlaps the PCI memory window");
    dbg_assert(!platform.ecam || platform.memory_size <= platform.ecam.base && platform.memory_size <= platform.pci_mmio_start,
        "ECAM or the PCI memory window overlaps RAM");
}
                                                                                                                                                                              source/v64/src/ps2.js                                                                               0000644 0000000 0000000 00000055405 00000000000 011526  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_PS2 } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";
import { ByteQueue } from "./lib.js";

const PS2_LOG_VERBOSE = false;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 */
export function PS2(cpu, bus)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    /** @const @type {BusConnector} */
    this.bus = bus;

    this.reset();

    this.bus.register("keyboard-code", function(code)
    {
        this.kbd_send_code(code);
    }, this);

    // The pointer goes to one device of the guest: while the guest uses the
    // USB tablet (usb.tablet), it has the pointer, unless the page locked it
    // (then the movement is relative, this mouse's)
    this.pointer_elsewhere = false;
    this.pointer_locked = false;
    const route = () =>
    {
        const elsewhere = this.usb_tablet_active && !this.pointer_locked;
        // (buttons held go up when the pointer changes hands)
        if(elsewhere && !this.pointer_elsewhere && this.have_mouse && this.use_mouse) this.mouse_send_click(false, false, false);
        this.pointer_elsewhere = elsewhere;
    };
    this.usb_tablet_active = false;
    this.bus.register("usb-tablet-active", function(active)
    {
        this.usb_tablet_active = !!active;
        route();
    }, this);
    this.bus.register("mouse-pointer-lock", function(locked)
    {
        this.pointer_locked = !!locked;
        route();
    }, this);

    this.bus.register("mouse-click", function(data)
    {
        if(this.pointer_elsewhere) return;
        this.mouse_send_click(data[0], data[1], data[2]);
    }, this);

    this.bus.register("mouse-delta", function(data)
    {
        if(this.pointer_elsewhere) return;
        this.mouse_send_delta(data[0], data[1]);
    }, this);

    this.bus.register("mouse-wheel", function(data)
    {
        if(!this.have_mouse || !this.use_mouse || !this.mouse_stream_active() || this.pointer_elsewhere)
        {
            return;
        }

        this.wheel_movement -= data[0];
        this.wheel_movement -= data[1] * 2; // X Wheel Movement
        this.wheel_movement = Math.min(7, Math.max(-8, this.wheel_movement));
        this.send_mouse_packet(0, 0);
    }, this);

    cpu.io.register_read(0x60, this, this.port60_read);
    cpu.io.register_read(0x64, this, this.port64_read);

    cpu.io.register_write(0x60, this, this.port60_write);
    cpu.io.register_write(0x64, this, this.port64_write);
}

PS2.prototype.reset = function()
{
    /** @type {boolean} */
    this.enable_mouse_stream = false;

    /** @type {boolean} */
    this.use_mouse = false;

    /** @type {boolean} */
    this.have_mouse = true;

    /** @type {number} */
    this.mouse_delta_x = 0;
    /** @type {number} */
    this.mouse_delta_y = 0;
    /** @type {number} */
    this.mouse_clicks = 0;

    /** @type {boolean} */
    this.have_keyboard = true;

    /** @type {boolean} */
    this.enable_keyboard_stream = false;

    /** @type {boolean} */
    this.next_is_mouse_command = false;

    /** @type {boolean} */
    this.next_read_sample = false;

    /** @type {boolean} */
    this.next_read_led = false;

    /** @type {boolean} */
    this.next_handle_scan_code_set = false;

    /** @type {boolean} */
    this.next_read_rate = false;

    /** @type {boolean} */
    this.next_read_resolution = false;

    /**
     * @type {ByteQueue}
     */
    this.kbd_buffer = new ByteQueue(1024);

    this.last_port60_byte = 0;

    /** @type {number} */
    this.sample_rate = 100;

    /** @type {number} */
    this.mouse_detect_state = 0;

    /** @type {number} */
    this.mouse_id = 0x00;

    /** @type {boolean} */
    this.mouse_reset_workaround = false;

    /** @type {number} */
    this.wheel_movement = 0;

    /** @type {number} */
    this.resolution = 4;

    /** @type {boolean} */
    this.scaling2 = false;

    /** @type {number} */
    this.last_mouse_packet = -1;

    /**
     * @type {ByteQueue}
     */
    this.mouse_buffer = new ByteQueue(1024);

    /**
     * @type {boolean}
     * Also known as DBBOUT OBF - Output Buffer Full flag
     */
    this.next_byte_is_ready = false;

    /** @type {boolean} */
    this.next_byte_is_aux = false;

    this.command_register = 1 | 4;
    // TODO: What should be the initial value?
    this.controller_output_port = 0;
    this.read_output_register = false;
    this.read_command_register = false;
    this.read_controller_output_port = false;
};

PS2.prototype.get_state = function()
{
    var state = [];

    state[0] = this.enable_mouse_stream;
    state[1] = this.use_mouse;
    state[2] = this.have_mouse;
    state[3] = this.mouse_delta_x;
    state[4] = this.mouse_delta_y;
    state[5] = this.mouse_clicks;
    state[6] = this.have_keyboard;
    state[7] = this.enable_keyboard_stream;
    state[8] = this.next_is_mouse_command;
    state[9] = this.next_read_sample;
    state[10] = this.next_read_led;
    state[11] = this.next_handle_scan_code_set;
    state[12] = this.next_read_rate;
    state[13] = this.next_read_resolution;
    //state[14] = this.kbd_buffer;
    state[15] = this.last_port60_byte;
    state[16] = this.sample_rate;
    state[17] = this.resolution;
    state[18] = this.scaling2;
    //state[19] = this.mouse_buffer;
    state[20] = this.command_register;
    state[21] = this.read_output_register;
    state[22] = this.read_command_register;
    state[23] = this.controller_output_port;
    state[24] = this.read_controller_output_port;
    state[25] = this.mouse_id;
    state[26] = this.mouse_detect_state;
    state[27] = this.mouse_reset_workaround;

    return state;
};

PS2.prototype.set_state = function(state)
{
    this.enable_mouse_stream = state[0];
    this.use_mouse = state[1];
    this.have_mouse = state[2];
    this.mouse_delta_x = state[3];
    this.mouse_delta_y = state[4];
    this.mouse_clicks = state[5];
    this.have_keyboard = state[6];
    this.enable_keyboard_stream = state[7];
    this.next_is_mouse_command = state[8];
    this.next_read_sample = state[9];
    this.next_read_led = state[10];
    this.next_handle_scan_code_set = state[11];
    this.next_read_rate = state[12];
    this.next_read_resolution = state[13];
    //this.kbd_buffer = state[14];
    this.last_port60_byte = state[15];
    this.sample_rate = state[16];
    this.resolution = state[17];
    this.scaling2 = state[18];
    //this.mouse_buffer = state[19];
    this.command_register = state[20];
    this.read_output_register = state[21];
    this.read_command_register = state[22];
    this.controller_output_port = state[23];
    this.read_controller_output_port = state[24];
    this.mouse_id = state[25] || 0;
    this.mouse_detect_state = state[26] || 0;
    this.mouse_reset_workaround = state[27] || false;

    this.next_byte_is_ready = false;
    this.next_byte_is_aux = false;
    this.kbd_buffer.clear();
    this.mouse_buffer.clear();

    this.bus.send("mouse-enable", this.use_mouse);
};

PS2.prototype.mouse_stream_active = function()
{
    return this.enable_mouse_stream && !(this.command_register & 0x20);
};

PS2.prototype.raise_irq = function()
{
    if(this.next_byte_is_ready)
    {
        // Wait until previous byte is read
        // http://halicery.com/Hardware/8042/8042_1503033_TXT.htm
        return;
    }

    // Kbd has priority over aux
    if(this.kbd_buffer.length)
    {
        this.kbd_irq();
    }
    else if(this.mouse_buffer.length)
    {
        this.mouse_irq();
    }
};

PS2.prototype.mouse_irq = function()
{
    this.next_byte_is_ready = true;
    this.next_byte_is_aux = true;

    if(this.command_register & 2)
    {
        dbg_log("Mouse irq", LOG_PS2);

        // Pulse the irq line
        // Note: can't lower immediately after rising, so lower before rising
        // http://www.os2museum.com/wp/ibm-ps2-model-50-keyboard-controller/
        this.cpu.device_lower_irq(12);
        this.cpu.device_raise_irq(12);
    }
};

PS2.prototype.kbd_irq = function()
{
    this.next_byte_is_ready = true;
    this.next_byte_is_aux = false;

    if(this.command_register & 1)
    {
        dbg_log("Keyboard irq", LOG_PS2);

        // Pulse the irq line
        // Note: can't lower immediately after rising, so lower before rising
        // http://www.os2museum.com/wp/ibm-ps2-model-50-keyboard-controller/
        this.cpu.device_lower_irq(1);
        this.cpu.device_raise_irq(1);
    }
};

PS2.prototype.kbd_send_code = function(code)
{
    if(this.enable_keyboard_stream)
    {
        dbg_log("adding kbd code: " + h(code), LOG_PS2);
        this.kbd_buffer.push(code);
        this.raise_irq();
    }
};

PS2.prototype.mouse_send_delta = function(delta_x, delta_y)
{
    if(!this.have_mouse || !this.use_mouse)
    {
        return;
    }

    // note: delta_x or delta_y can be floating point numbers

    //const factor = this.resolution * this.sample_rate / 80;
    const factor = 1;

    this.mouse_delta_x += delta_x * factor;
    this.mouse_delta_y += delta_y * factor;

    if(this.mouse_stream_active())
    {
        var change_x = this.mouse_delta_x | 0,
            change_y = this.mouse_delta_y | 0;

        if(change_x || change_y)
        {
            //var now = Date.now();
            //if(now - this.last_mouse_packet < 1000 / this.sample_rate)
            //{
            //    // TODO: set timeout
            //    return;
            //}

            this.mouse_delta_x -= change_x;
            this.mouse_delta_y -= change_y;

            this.send_mouse_packet(change_x, change_y);
        }
    }
};

PS2.prototype.mouse_send_click = function(left, middle, right)
{
    if(!this.have_mouse || !this.use_mouse)
    {
        return;
    }

    this.mouse_clicks = left | right << 1 | middle << 2;

    if(this.mouse_stream_active())
    {
        this.send_mouse_packet(0, 0);
    }
};

PS2.prototype.send_mouse_packet = function(dx, dy)
{
    var info_byte =
            (dy < 0) << 5 |
            (dx < 0) << 4 |
            1 << 3 |
            this.mouse_clicks,
        delta_x = dx,
        delta_y = dy;

    this.last_mouse_packet = Date.now();

    //if(this.scaling2)
    //{
    //    // only in automatic packets, not 0xEB requests
    //    delta_x = this.apply_scaling2(delta_x);
    //    delta_y = this.apply_scaling2(delta_y);
    //}

    this.mouse_buffer.push(info_byte);
    this.mouse_buffer.push(delta_x);
    this.mouse_buffer.push(delta_y);

    if(this.mouse_id === 0x04)
    {
        this.mouse_buffer.push(
            0 << 5 | // TODO: 5th button
            0 << 4 | // TODO: 4th button
            this.wheel_movement & 0x0F
        );
        this.wheel_movement = 0;
    }
    else if(this.mouse_id === 0x03)
    {
        this.mouse_buffer.push(this.wheel_movement & 0xFF); // Byte 4 - Z Movement
        this.wheel_movement = 0;
    }

    if(PS2_LOG_VERBOSE)
    {
        dbg_log("adding mouse packets: " + [info_byte, dx, dy], LOG_PS2);
    }

    this.raise_irq();
};

PS2.prototype.apply_scaling2 = function(n)
{
    // http://www.computer-engineering.org/ps2mouse/#Inputs.2C_Resolution.2C_and_Scaling
    var abs = Math.abs(n),
        sign = n >> 31;

    switch(abs)
    {
        case 0:
        case 1:
        case 3:
            return n;
        case 2:
            return sign;
        case 4:
            return 6 * sign;
        case 5:
            return 9 * sign;
        default:
            return n << 1;
    }
};

PS2.prototype.port60_read = function()
{
    //dbg_log("port 60 read: " + (buffer[0] || "(none)"));

    this.next_byte_is_ready = false;

    if(!this.kbd_buffer.length && !this.mouse_buffer.length)
    {
        // should not happen
        dbg_log("Port 60 read: Empty", LOG_PS2);
        return this.last_port60_byte;
    }

    if(this.next_byte_is_aux)
    {
        this.cpu.device_lower_irq(12);
        this.last_port60_byte = this.mouse_buffer.shift();
        dbg_log("Port 60 read (mouse): " + h(this.last_port60_byte), LOG_PS2);
    }
    else
    {
        this.cpu.device_lower_irq(1);
        this.last_port60_byte = this.kbd_buffer.shift();
        dbg_log("Port 60 read (kbd)  : " + h(this.last_port60_byte), LOG_PS2);
    }

    if(this.kbd_buffer.length || this.mouse_buffer.length)
    {
        this.raise_irq();
    }

    return this.last_port60_byte;
};

PS2.prototype.port64_read = function()
{
    // status port

    var status_byte = 0x10;

    if(this.next_byte_is_ready)
    {
        status_byte |= 0x1;
    }
    if(this.next_byte_is_aux)
    {
        status_byte |= 0x20;
    }

    dbg_log("port 64 read: " + h(status_byte), LOG_PS2);

    return status_byte;
};

PS2.prototype.port60_write = function(write_byte)
{
    dbg_log("port 60 write: " + h(write_byte), LOG_PS2);

    if(this.read_command_register)
    {
        this.command_register = write_byte;
        this.read_command_register = false;

        // not sure, causes "spurious ack" in Linux
        //this.kbd_buffer.push(0xFA);
        //this.kbd_irq();

        dbg_log("Keyboard command register = " + h(this.command_register), LOG_PS2);
    }
    else if(this.read_output_register)
    {
        this.read_output_register = false;

        this.mouse_buffer.clear();
        this.mouse_buffer.push(write_byte);
        this.mouse_irq();
    }
    else if(this.next_read_sample)
    {
        this.next_read_sample = false;
        this.mouse_buffer.clear();
        this.mouse_buffer.push(0xFA);

        this.sample_rate = write_byte;

        switch(this.mouse_detect_state)
        {
            case -1:
                if(write_byte === 60)
                {
                    // Detect Windows NT and turn on workaround the bug
                    // 200->100->80->60
                    this.mouse_reset_workaround = true;
                    this.mouse_detect_state = 0;
                }
                else
                {
                    this.mouse_reset_workaround = false;
                    this.mouse_detect_state = (write_byte === 200) ? 1 : 0;
                }
                break;
            case 0:
                if(write_byte === 200) this.mouse_detect_state = 1;
                break;
            case 1:
                if(write_byte === 100) this.mouse_detect_state = 2;
                else if(write_byte === 200) this.mouse_detect_state = 3;
                else this.mouse_detect_state = 0;
                break;
            case 2:
                // Host sends sample rate 200->100->80 to activate Intellimouse wheel
                if(write_byte === 80) this.mouse_id = 0x03;
                this.mouse_detect_state = -1;
                break;
            case 3:
                // Host sends sample rate 200->200->80 to activate Intellimouse 4th, 5th buttons
                if(write_byte === 80) this.mouse_id = 0x04;
                this.mouse_detect_state = -1;
                break;
        }

        dbg_log("mouse sample rate: " + h(write_byte) + ", mouse id: " + h(this.mouse_id), LOG_PS2);

        if(!this.sample_rate)
        {
            dbg_log("invalid sample rate, reset to 100", LOG_PS2);
            this.sample_rate = 100;
        }

        this.mouse_irq();
    }
    else if(this.next_read_resolution)
    {
        this.next_read_resolution = false;
        this.mouse_buffer.clear();
        this.mouse_buffer.push(0xFA);

        if(write_byte > 3)
        {
            this.resolution = 4;
            dbg_log("invalid resolution, resetting to 4", LOG_PS2);
        }
        else
        {
            this.resolution = 1 << write_byte;
            dbg_log("resolution: " + this.resolution, LOG_PS2);
        }
        this.mouse_irq();
    }
    else if(this.next_read_led)
    {
        // nope
        this.next_read_led = false;
        this.kbd_buffer.push(0xFA);
        this.kbd_irq();
    }
    else if(this.next_handle_scan_code_set)
    {
        this.next_handle_scan_code_set = false;

        this.kbd_buffer.push(0xFA);
        this.kbd_irq();

        if(write_byte)
        {
            // set scan code set
        }
        else
        {
            this.kbd_buffer.push(1);
        }
    }
    else if(this.next_read_rate)
    {
        // nope
        this.next_read_rate = false;
        this.kbd_buffer.push(0xFA);
        this.kbd_irq();
    }
    else if(this.next_is_mouse_command)
    {
        this.next_is_mouse_command = false;
        dbg_log("Port 60 data register write: " + h(write_byte), LOG_PS2);

        if(!this.have_mouse)
        {
            return;
        }

        // send ack
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.mouse_buffer.push(0xFA);

        switch(write_byte)
        {
        case 0xE6:
            // set scaling to 1:1
            dbg_log("Scaling 1:1", LOG_PS2);
            this.scaling2 = false;
            break;
        case 0xE7:
            // set scaling to 2:1
            dbg_log("Scaling 2:1", LOG_PS2);
            this.scaling2 = true;
            break;
        case 0xE8:
            // set mouse resolution
            this.next_read_resolution = true;
            break;
        case 0xE9:
            // status request - send one packet
            this.send_mouse_packet(0, 0);
            break;
        case 0xEB:
            // request single packet
            dbg_log("unimplemented request single packet", LOG_PS2);
            this.send_mouse_packet(0, 0);
            break;
        case 0xF2:
            //  MouseID Byte
            dbg_log("required id: " + h(this.mouse_id), LOG_PS2);
            this.mouse_buffer.push(this.mouse_id);

            this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0;
            // this.send_mouse_packet(0, 0);
            this.raise_irq();
            break;
        case 0xF3:
            // sample rate
            this.next_read_sample = true;
            break;
        case 0xF4:
            // enable streaming
            this.enable_mouse_stream = true;
            this.use_mouse = true;
            this.bus.send("mouse-enable", true);

            this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0;
            break;
        case 0xF5:
            // disable streaming
            this.enable_mouse_stream = false;
            break;
        case 0xF6:
            // set defaults
            this.enable_mouse_stream = false;
            this.sample_rate = 100;
            this.scaling2 = false;
            this.resolution = 4;
            break;
        case 0xFF:
            // reset, send completion code
            dbg_log("Mouse reset", LOG_PS2);
            this.mouse_buffer.push(0xAA);
            this.mouse_buffer.push(0);

            this.use_mouse = true;
            this.bus.send("mouse-enable", true);

            this.enable_mouse_stream = false;
            this.sample_rate = 100;
            this.scaling2 = false;
            this.resolution = 4;

            if(!this.mouse_reset_workaround)
            {
                this.mouse_id = 0x00;
            }

            this.mouse_clicks = this.mouse_delta_x = this.mouse_delta_y = 0;
            break;

        default:
            dbg_log("Unimplemented mouse command: " + h(write_byte), LOG_PS2);
        }

        this.mouse_irq();
    }
    else if(this.read_controller_output_port)
    {
        this.read_controller_output_port = false;
        this.controller_output_port = write_byte;
        // If we ever want to implement A20 masking, here is where
        // we should turn the masking off if the second bit is on
    }
    else
    {
        dbg_log("Port 60 data register write: " + h(write_byte), LOG_PS2);

        // send ack
        this.mouse_buffer.clear();
        this.kbd_buffer.clear();
        this.kbd_buffer.push(0xFA);

        switch(write_byte)
        {
        case 0xED:
            this.next_read_led = true;
            break;
        case 0xF0:
            // get/set scan code set
            this.next_handle_scan_code_set = true;
            break;
        case 0xF2:
            // identify
            this.kbd_buffer.push(0xAB);
            this.kbd_buffer.push(0x83);
            break;
        case 0xF3:
            //  Set typematic rate and delay
            this.next_read_rate = true;
            break;
        case 0xF4:
            // enable scanning
            dbg_log("kbd enable scanning", LOG_PS2);
            this.enable_keyboard_stream = true;
            break;
        case 0xF5:
            // disable scanning
            dbg_log("kbd disable scanning", LOG_PS2);
            this.enable_keyboard_stream = false;
            break;
        case 0xF6:
            // reset defaults
            //this.enable_keyboard_stream = false;
            break;
        case 0xFF:
            this.kbd_buffer.clear();
            this.kbd_buffer.push(0xFA);
            this.kbd_buffer.push(0xAA);
            this.kbd_buffer.push(0);
            break;
        default:
            dbg_log("Unimplemented keyboard command: " + h(write_byte), LOG_PS2);
        }

        this.kbd_irq();
    }
};

PS2.prototype.port64_write = function(write_byte)
{
    dbg_log("port 64 write: " + h(write_byte), LOG_PS2);

    switch(write_byte)
    {
    case 0x20:
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.kbd_buffer.push(this.command_register);
        this.kbd_irq();
        break;
    case 0x60:
        this.read_command_register = true;
        break;
    case 0xD0:
        // read controller output port
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.kbd_buffer.push(this.controller_output_port);
        this.kbd_irq();
        break;
    case 0xD1:
        this.read_controller_output_port = true;
        break;
    case 0xD3:
        this.read_output_register = true;
        break;
    case 0xD4:
        this.next_is_mouse_command = true;
        break;
    case 0xA7:
        // Disable second port
        dbg_log("Disable second port", LOG_PS2);
        this.command_register |= 0x20;
        break;
    case 0xA8:
        // Enable second port
        dbg_log("Enable second port", LOG_PS2);
        this.command_register &= ~0x20;
        break;
    case 0xA9:
        // test second ps/2 port
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.kbd_buffer.push(0);
        this.kbd_irq();
        break;
    case 0xAA:
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.kbd_buffer.push(0x55);
        this.kbd_irq();
        break;
    case 0xAB:
        // Test first PS/2 port
        this.kbd_buffer.clear();
        this.mouse_buffer.clear();
        this.kbd_buffer.push(0);
        this.kbd_irq();
        break;
    case 0xAD:
        // Disable Keyboard
        dbg_log("Disable Keyboard", LOG_PS2);
        this.command_register |= 0x10;
        break;
    case 0xAE:
        // Enable Keyboard
        dbg_log("Enable Keyboard", LOG_PS2);
        this.command_register &= ~0x10;
        break;
    case 0xFE:
        dbg_log("CPU reboot via PS2");
        this.cpu.reboot_internal("8042");
        break;
    default:
        dbg_log("port 64: Unimplemented command byte: " + h(write_byte), LOG_PS2);
    }
};
                                                                                                                                                                                                                                                           source/v64/src/q35.js                                                                               0000644 0000000 0000000 00000040532 00000000000 011425  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Q35 chipset: the MCH host bridge (PCI 00:00.0) with its PCI Express
// configuration window (ECAM), and the ICH9 LPC bridge (00:1f.0) with the
// power management base, the PIRQ routing and the root complex register
// block. The AHCI function (00:1f.2) is src/ahci.js, the PM I/O block that
// the LPC decodes is src/acpi.js.
//
// Register layouts: Intel 3 Series Express Chipset Family datasheet (MCH),
// Intel I/O Controller Hub 9 datasheet (LPC), and QEMU's implementation, whose
// defaults and interrupt routing the guest sees here as well:
// https://github.com/qemu/qemu/blob/v9.2.0/hw/pci-host/q35.c
// https://github.com/qemu/qemu/blob/v9.2.0/hw/isa/lpc_ich9.c
// See docs/q35.md.

import { LOG_PCI } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";
import {
    ICH9_LPC_PCI_ID, ICH9_RCBA_SIZE, QEMU_PCI_SUBSYSTEM, Q35_MCH_PCI_ID,
} from "./platform.js";

// For Types Only
import { CPU } from "./cpu.js";

// MCH configuration registers
const MCH_PCIEXBAR = 0x60;          // 64 bits: base, length (bits 2:1), enable (bit 0)
const MCH_PAM0 = 0x90;              // PAM0..PAM6: BIOS shadow attributes
const MCH_SMRAM = 0x9D;
const MCH_ESMRAMC = 0x9E;
const MCH_SMRAM_DEFAULT = 0x02;     // C_BASE_SEG = 010b (A/B segment), read-only
const SMRAM_G_SMRAME = 1 << 3;
const SMRAM_D_LCK = 1 << 4;
const SMRAM_D_CLS = 1 << 5;
const SMRAM_D_OPEN = 1 << 6;
const MCH_ESMRAMC_DEFAULT = 0x38;     // SM_CACHE, SM_L1, SM_L2: read-only ones
const ESMRAMC_T_EN = 1 << 0;
const ESMRAMC_TSEG_SZ_SHIFT = 1;      // 1, 2 or 8 MiB, or the extended size
const ESMRAMC_H_SMRAME = 1 << 7;
const ESMRAMC_WRITABLE = ESMRAMC_H_SMRAME | 3 << ESMRAMC_TSEG_SZ_SHIFT | ESMRAMC_T_EN;
// QEMU's extended TSEG: writing 0xFFFF reads back its size in MiB
const MCH_EXT_TSEG_MBYTES = 0x50;
const EXT_TSEG_QUERY = 0xFFFF;
const EXT_TSEG_MBYTES = 16;

// This needs to be set in order for seabios to not execute code outside of
// mapped memory (as for the i440FX in src/pci.js): with PAM0's "RAM present"
// bit SeaBIOS doesn't copy itself from the alias below 4 GiB.
// See [make_bios_writable_intel] in src/fw/shadow.c in seabios
const PAM0_DEFAULT = 0x10;

// LPC configuration registers
const LPC_PMBASE = 0x40;            // bits 15:7 base, bit 0 hardwired to 1
const LPC_ACPI_CNTL = 0x44;         // bit 7 ACPI_EN, bits 2:0 SCI IRQ select
const LPC_ACPI_EN = 0x80;
const LPC_PIRQA_ROUT = 0x60;        // PIRQA..D
const LPC_SIRQ_CNTL = 0x64;
const LPC_PIRQE_ROUT = 0x68;        // PIRQE..H
const LPC_PIRQ_ROUT_DISABLED = 0x80;
const LPC_GEN_PMCON_1 = 0xA0;
const GEN_PMCON_1_SMI_LOCK = 0x10;  // set once until reset: SMI_EN.GBL_SMI_EN read-only
const LPC_RCBA = 0xF0;              // bits 31:14 base, bit 0 enable

// Chipset configuration registers in the RCBA block
// Device 25..31 interrupt route: INTA..D -> PIRQ (3 bits per pin, 4 apart)
const RCBA_DIR = { 31: 0x3140, 29: 0x3144, 28: 0x3146, 27: 0x3148, 26: 0x314C, 25: 0x3150 };
const RCBA_DIR_DEFAULT = 0x3210;    // INTA -> PIRQA, ..., INTD -> PIRQD
const RCBA_GCS = 0x3410;
const RCBA_GCS_DEFAULT = 0x20;      // no reboot on TCO timeout
const RCBA_HPTC = 0x3404;
const RCBA_HPTC_ENABLED = 0x80;     // HPET address enable, address select 0: 0xFED00000

/**
 * @constructor
 * @param {CPU} cpu
 */
export function Q35(cpu)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.name = "q35";

    const pci = cpu.devices.pci;
    this.pci = pci;
    const qemu = cpu.platform.qemu_compatible;

    // 00:00.0 Host bridge: Intel Corporation 82G33/G31/P35/P31 Express DRAM Controller
    // (no QEMU subsystem on the host bridge: with it SeaBIOS takes the
    // machine for QEMU, as with the i440FX in src/pci.js)
    const mch_space = new Array(256).fill(0);
    mch_space.splice(0, 16, 0x86, 0x80, 0xC0, 0x29, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00);
    this.mch = {
        pci_id: Q35_MCH_PCI_ID,
        pci_space: mch_space,
        pci_bars: [],
        name: "Q35 MCH",
        on_config_write: (offset, size) => this.mch_config_written(offset, size),
        on_config_restore: () => {
            this.update_ecam();
            this.smram_locked = (this.mch_space8[MCH_SMRAM] & SMRAM_D_LCK) !== 0;
            this.smram_locked_value = this.mch_space8[MCH_SMRAM] & (SMRAM_G_SMRAME | SMRAM_D_LCK);
            this.esmramc = this.mch_space8[MCH_ESMRAMC];
            this.update_smram();
        },
    };
    /** @const @type {!Int32Array} */
    this.mch_space = pci.register_device(this.mch);
    /** @const @type {!Uint8Array} */
    this.mch_space8 = new Uint8Array(this.mch_space.buffer);

    // 00:1f.0 ISA bridge: Intel Corporation 82801IB (ICH9) LPC Interface Controller (rev 02)
    // (multi-function: the AHCI controller is function 2)
    const lpc_space = new Array(256).fill(0);
    lpc_space.splice(0, 16, 0x86, 0x80, 0x18, 0x29, 0x07, 0x00, 0x00, 0x02, 0x02, 0x00, 0x01, 0x06, 0x00, 0x00, 0x80, 0x00);
    lpc_space.splice(0x2C, 4, ...qemu ? QEMU_PCI_SUBSYSTEM : [0x00, 0x00, 0x00, 0x00]);
    this.lpc = {
        pci_id: ICH9_LPC_PCI_ID,
        pci_space: lpc_space,
        pci_bars: [],
        name: "ICH9 LPC",
        on_config_write: (offset, size) => this.lpc_config_written(offset, size),
        on_config_restore: () => {
            this.update_pm_decode();
            this.update_rcba();
            this.smi_lock = (this.lpc_space8[LPC_GEN_PMCON_1] & GEN_PMCON_1_SMI_LOCK) !== 0;
        },
    };
    /** @const @type {!Int32Array} */
    this.lpc_space = pci.register_device(this.lpc);
    /** @const @type {!Uint8Array} */
    this.lpc_space8 = new Uint8Array(this.lpc_space.buffer);

    /** The root complex register block (chipset configuration registers) */
    this.rcba = new Uint8Array(ICH9_RCBA_SIZE);
    /** Where the block is decoded, or -1 */
    this.rcba_base = -1;

    pci.irq_route = (pci_id, pin) => this.irq_route(pci_id, pin);

    this.reset();
}

/** Power-on values of the chipset registers (PCIRST#) */
Q35.prototype.reset = function()
{
    const mch = this.mch_space8;
    mch.fill(0, MCH_PCIEXBAR, MCH_PCIEXBAR + 8);
    mch.fill(0, MCH_PAM0, MCH_PAM0 + 7);
    mch[MCH_PAM0] = PAM0_DEFAULT;
    mch[MCH_SMRAM] = MCH_SMRAM_DEFAULT;
    mch[MCH_ESMRAMC] = MCH_ESMRAMC_DEFAULT;
    /** ESMRAMC as written (it is read-only once SMRAM.D_LCK is set) */
    this.esmramc = MCH_ESMRAMC_DEFAULT;
    mch[MCH_EXT_TSEG_MBYTES] = EXT_TSEG_QUERY & 0xFF;
    mch[MCH_EXT_TSEG_MBYTES + 1] = EXT_TSEG_QUERY >> 8;
    /** SMRAM.D_LCK was set: the locked bits */
    this.smram_locked = false;
    this.smram_locked_value = 0;
    this.update_smram();

    const lpc = this.lpc_space8;
    this.lpc_space[LPC_PMBASE >> 2] = 1;
    lpc[LPC_ACPI_CNTL] = 0;
    lpc.fill(LPC_PIRQ_ROUT_DISABLED, LPC_PIRQA_ROUT, LPC_PIRQA_ROUT + 4);
    lpc.fill(LPC_PIRQ_ROUT_DISABLED, LPC_PIRQE_ROUT, LPC_PIRQE_ROUT + 4);
    lpc[LPC_SIRQ_CNTL] = 0x10;
    lpc.fill(0, LPC_GEN_PMCON_1, LPC_GEN_PMCON_1 + 8); // GEN_PMCON_1..3, GEN_PMCON_LOCK
    /** GEN_PMCON_1.SMI_LOCK: SMI_EN.GBL_SMI_EN cannot be cleared */
    this.smi_lock = false;
    this.lpc_space[LPC_RCBA >> 2] = 0;

    this.rcba.fill(0);
    for(const offset of Object.values(RCBA_DIR))
    {
        this.rcba[offset] = RCBA_DIR_DEFAULT & 0xFF;
        this.rcba[offset + 1] = RCBA_DIR_DEFAULT >> 8;
    }
    this.rcba[RCBA_GCS] = RCBA_GCS_DEFAULT;
    // (the HPET, if the machine has one, is always at 0xFED00000)
    this.rcba[RCBA_HPTC] = this.cpu.platform.hpet ? RCBA_HPTC_ENABLED : 0;

    this.update_ecam();
    this.update_pm_decode();
    this.update_rcba();
};

/**
 * @param {number} offset
 * @param {number} size
 * @param {number} start
 * @param {number} end
 * @return {boolean}
 */
function touches(offset, size, start, end)
{
    return offset < end && offset + size > start;
}

/**
 * @param {number} offset
 * @param {number} size
 */
Q35.prototype.mch_config_written = function(offset, size)
{
    if(touches(offset, size, MCH_ESMRAMC, MCH_ESMRAMC + 1))
    {
        // H_SMRAME, TSEG_SZ and T_EN, until D_LCK (also when this write sets it)
        if(!this.smram_locked)
        {
            this.esmramc = this.mch_space8[MCH_ESMRAMC] & ESMRAMC_WRITABLE | MCH_ESMRAMC_DEFAULT;
        }
        this.mch_space8[MCH_ESMRAMC] = this.esmramc;
    }
    if(touches(offset, size, MCH_EXT_TSEG_MBYTES, MCH_EXT_TSEG_MBYTES + 2) &&
        (this.mch_space8[MCH_EXT_TSEG_MBYTES] | this.mch_space8[MCH_EXT_TSEG_MBYTES + 1] << 8) === EXT_TSEG_QUERY)
    {
        this.mch_space8[MCH_EXT_TSEG_MBYTES] = EXT_TSEG_MBYTES & 0xFF;
        this.mch_space8[MCH_EXT_TSEG_MBYTES + 1] = EXT_TSEG_MBYTES >> 8;
    }
    if(touches(offset, size, MCH_SMRAM, MCH_ESMRAMC + 1))
    {
        // C_BASE_SEG is read-only; once D_LCK is set, D_OPEN, G_SMRAME and
        // D_LCK are too (until a reset), and D_OPEN is clear
        let value = this.mch_space8[MCH_SMRAM] & ~7 | MCH_SMRAM_DEFAULT;
        if(this.smram_locked)
        {
            value = value & ~(SMRAM_D_OPEN | SMRAM_G_SMRAME | SMRAM_D_LCK) | this.smram_locked_value;
        }
        if(value & SMRAM_D_LCK)
        {
            value &= ~SMRAM_D_OPEN;
            this.smram_locked = true;
            this.smram_locked_value = value & (SMRAM_G_SMRAME | SMRAM_D_LCK);
        }
        this.mch_space8[MCH_SMRAM] = value;
        this.update_smram();
    }
    if(touches(offset, size, MCH_PCIEXBAR, MCH_PCIEXBAR + 8))
    {
        this.update_ecam();
    }
};

/**
 * The CPU's view of SMRAM (src/rust/cpu/smm.rs): compatible SMRAM is RAM at
 * 0xA0000-0xBFFFF in SMM with G_SMRAME (with D_CLS, for instruction fetches
 * only), and always with D_OPEN; with H_SMRAME, the same RAM is at
 * 0xFEDA0000-0xFEDBFFFF instead (high SMRAM). TSEG (T_EN with G_SMRAME), the
 * top of the RAM below 4 GiB, is RAM in SMM only. As in QEMU: TSEG_SZ 11 is
 * the extended size (EXT_TSEG_MBYTES).
 */
Q35.prototype.update_smram = function()
{
    const smram = this.mch_space8[MCH_SMRAM];
    const esmramc = this.mch_space8[MCH_ESMRAMC];
    this.cpu.smram_set_control && this.cpu.smram_set_control(
        (smram & SMRAM_G_SMRAME ? 1 : 0) | (smram & SMRAM_D_OPEN ? 2 : 0) |
        (esmramc & ESMRAMC_H_SMRAME ? 4 : 0) | (smram & SMRAM_D_CLS ? 8 : 0));
    const top = this.cpu.low_memory_size;
    let size = 0;
    if(esmramc & ESMRAMC_T_EN && smram & SMRAM_G_SMRAME)
    {
        size = Math.min(top, [1, 2, 8, EXT_TSEG_MBYTES][esmramc >> ESMRAMC_TSEG_SZ_SHIFT & 3] << 20);
    }
    this.cpu.smram_set_tseg && this.cpu.smram_set_tseg(top - size, top);
};

/** Map the ECAM window where PCIEXBAR puts it, or unmap it */
Q35.prototype.update_ecam = function()
{
    const low = this.mch_space[MCH_PCIEXBAR >> 2] >>> 0;
    const high = this.mch_space[MCH_PCIEXBAR + 4 >> 2] >>> 0;

    if(!(low & 1))
    {
        this.pci.set_ecam(-1, 0);
        return;
    }

    // length 00b: 256 MiB (256 buses), 01b: 128 MiB, 10b: 64 MiB
    const length = low >> 1 & 3;
    const size = length === 1 ? 128 << 20 : length === 2 ? 64 << 20 : 256 << 20;
    const base = (low & ~(size - 1)) >>> 0;

    if(high & 0xF)
    {
        // (v86's memory map ends at 4 GiB; firmware puts it below)
        dbg_log("Q35: ECAM above 4 GiB is not supported, disabled", LOG_PCI);
        this.pci.set_ecam(-1, 0);
        return;
    }
    if(base < this.cpu.memory_size[0])
    {
        dbg_log("Q35: ECAM at " + h(base, 8) + " overlaps RAM, disabled", LOG_PCI);
        this.pci.set_ecam(-1, 0);
        return;
    }

    this.pci.set_ecam(base, size);
};

/**
 * @param {number} offset
 * @param {number} size
 */
Q35.prototype.lpc_config_written = function(offset, size)
{
    if(touches(offset, size, LPC_PMBASE, LPC_ACPI_CNTL + 1))
    {
        this.update_pm_decode();
    }
    if(touches(offset, size, LPC_PIRQA_ROUT, LPC_PIRQA_ROUT + 4) || touches(offset, size, LPC_PIRQE_ROUT, LPC_PIRQE_ROUT + 4))
    {
        for(let i = 0; i < 4; i++)
        {
            // bit 7: not routed, bits 3:0: ISA IRQ
            this.lpc_space8[LPC_PIRQA_ROUT + i] &= 0x8F;
            this.lpc_space8[LPC_PIRQE_ROUT + i] &= 0x8F;
        }
        this.reroute_pins();
    }
    if(touches(offset, size, LPC_RCBA, LPC_RCBA + 4))
    {
        this.update_rcba();
    }
    if(touches(offset, size, LPC_GEN_PMCON_1, LPC_GEN_PMCON_1 + 1))
    {
        // SMI_LOCK stays set until the platform's reset (OVMF sets it, then
        // checks that GBL_SMI_EN no longer clears)
        if(this.smi_lock) this.lpc_space8[LPC_GEN_PMCON_1] |= GEN_PMCON_1_SMI_LOCK;
        this.smi_lock = (this.lpc_space8[LPC_GEN_PMCON_1] & GEN_PMCON_1_SMI_LOCK) !== 0;
    }
};

/**
 * Decode the ICH9 PM I/O block at PMBASE once ACPI_EN is set. The SCI IRQ
 * select (ACPI_CNTL bits 2:0) is not implemented: the SCI is IRQ 9, the
 * default SeaBIOS keeps.
 */
Q35.prototype.update_pm_decode = function()
{
    // bits 31:16 and 6:1 are reserved, bit 0 is hardwired to 1
    const pmbase = this.lpc_space[LPC_PMBASE >> 2] & 0xFF80;
    this.lpc_space[LPC_PMBASE >> 2] = pmbase | 1;

    const enabled = (this.lpc_space8[LPC_ACPI_CNTL] & LPC_ACPI_EN) !== 0;
    const acpi = this.cpu.devices.acpi;
    if(acpi)
    {
        acpi.set_pm_decode(enabled && pmbase !== 0 ? pmbase : -1);
    }
};

/** Decode the root complex register block at RCBA, or stop decoding it */
Q35.prototype.update_rcba = function()
{
    const value = this.lpc_space[LPC_RCBA >> 2];
    // bits 13:1 are reserved
    this.lpc_space[LPC_RCBA >> 2] = value & ~0x3FFE;
    const base = value & 1 ? (value & ~0x3FFF) >>> 0 : -1;

    if(base === this.rcba_base)
    {
        return;
    }

    const io = this.cpu.io;
    if(this.rcba_base !== -1)
    {
        io.mmap_unregister_range(this.rcba_base, ICH9_RCBA_SIZE, this);
    }

    dbg_log("ICH9 RCBA " + (base === -1 ? "disabled" : "at " + h(base, 8)), LOG_PCI);
    this.rcba_base = base;

    if(base !== -1)
    {
        const offset = addr => addr - this.rcba_base >>> 0;
        io.mmap_register_range(base, ICH9_RCBA_SIZE, this,
            addr => this.rcba[offset(addr)],
            (addr, value) => this.rcba_write(offset(addr), value),
            addr => {
                const o = offset(addr);
                return this.rcba[o] | this.rcba[o + 1] << 8 | this.rcba[o + 2] << 16 | this.rcba[o + 3] << 24;
            },
            (addr, value) => {
                const o = offset(addr);
                for(let i = 0; i < 4; i++) this.rcba_write(o + i, value >>> (i << 3) & 0xFF);
            });
    }
};

/**
 * One byte of the chipset configuration registers: storage, except that the
 * device 25-31 interrupt routes take effect
 * @param {number} offset
 * @param {number} value
 */
Q35.prototype.rcba_write = function(offset, value)
{
    this.rcba[offset] = value;
    if(offset >= 0x3140 && offset < 0x3154)
    {
        this.reroute_pins();
    }
};

/**
 * Where interrupt pin (0-3: INTA-D) of a function on bus 0 goes: QEMU's Q35
 * wiring. Devices 0-24: INTA-D rotate over PIRQE-H; 25-31: the DxxIR route
 * registers (default: INTA-D -> PIRQA-D; the root ports' secondary buses
 * arrive here through device 28's); PIRQn is IOAPIC input 16 + n, and the
 * ISA IRQ in its routing register for the PIC.
 * @param {number} pci_id
 * @param {number} pin
 * @return {{pic: number, gsi: number}}
 */
Q35.prototype.irq_route = function(pci_id, pin)
{
    if(pin < 0 || pin > 3 || pci_id >= 256)
    {
        return { pic: LPC_PIRQ_ROUT_DISABLED, gsi: -1 };
    }

    const slot = pci_id >> 3;
    let pirq;
    if(slot <= 24)
    {
        pirq = 4 + (slot + pin) % 4;
    }
    else if(RCBA_DIR[slot] !== undefined)
    {
        const offset = RCBA_DIR[slot];
        const route = this.rcba[offset] | this.rcba[offset + 1] << 8;
        pirq = route >> (pin << 2) & 7;
    }
    else
    {
        // device 30 (a DMI-to-PCI bridge on real hardware): PIRQE-H
        pirq = 4 + pin;
    }

    const rout = this.lpc_space8[pirq < 4 ? LPC_PIRQA_ROUT + pirq : LPC_PIRQE_ROUT + pirq - 4];
    return { pic: rout & LPC_PIRQ_ROUT_DISABLED ? LPC_PIRQ_ROUT_DISABLED : rout & 0x0F, gsi: 16 + pirq };
};

/** The routing changed: pins that are asserted move to their new lines */
Q35.prototype.reroute_pins = function()
{
    const pci = this.pci;
    pci.intx_levels.forEach((level, pci_id) => {
        if(level)
        {
            const disabled = (pci.get_command(pci_id) & 1 << 10) !== 0;
            pci.drive_intx(pci_id, !disabled);
        }
    });
};

Q35.prototype.get_state = function()
{
    const state = [];
    state[0] = this.rcba;
    return state;
};

Q35.prototype.set_state = function(state)
{
    this.rcba.set(state[0]);
    // (PCI restores the configuration, and with it the decodes, separately)
};
                                                                                                                                                                      source/v64/src/rtc.js                                                                               0000644 0000000 0000000 00000034110 00000000000 011600  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_RTC } from "./const.js";
import { h } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";
import { DMA } from "./dma.js";


export const CMOS_RTC_SECONDS = 0x00;
export const CMOS_RTC_SECONDS_ALARM = 0x01;
export const CMOS_RTC_MINUTES = 0x02;
export const CMOS_RTC_MINUTES_ALARM = 0x03;
export const CMOS_RTC_HOURS = 0x04;
export const CMOS_RTC_HOURS_ALARM = 0x05;
export const CMOS_RTC_DAY_WEEK = 0x06;
export const CMOS_RTC_DAY_MONTH = 0x07;
export const CMOS_RTC_MONTH = 0x08;
export const CMOS_RTC_YEAR = 0x09;
export const CMOS_STATUS_A = 0x0a;
export const CMOS_STATUS_B = 0x0b;
export const CMOS_STATUS_C = 0x0c;
export const CMOS_STATUS_D = 0x0d;
export const CMOS_DIAG_STATUS = 0x0e;
export const CMOS_RESET_CODE = 0x0f;

export const CMOS_FLOPPY_DRIVE_TYPE = 0x10;
export const CMOS_DISK_DATA = 0x12;
export const CMOS_EQUIPMENT_INFO = 0x14;
export const CMOS_MEM_BASE_LOW = 0x15;
export const CMOS_MEM_BASE_HIGH = 0x16;
export const CMOS_MEM_OLD_EXT_LOW = 0x17;
export const CMOS_MEM_OLD_EXT_HIGH = 0x18;
export const CMOS_DISK_DRIVE1_TYPE = 0x19;
export const CMOS_DISK_DRIVE2_TYPE = 0x1a;
export const CMOS_DISK_DRIVE1_CYL = 0x1b;
export const CMOS_DISK_DRIVE2_CYL = 0x24;
export const CMOS_MEM_EXTMEM_LOW = 0x30;
export const CMOS_MEM_EXTMEM_HIGH = 0x31;
export const CMOS_CENTURY = 0x32;
export const CMOS_MEM_EXTMEM2_LOW = 0x34;
export const CMOS_MEM_EXTMEM2_HIGH = 0x35;
export const CMOS_CENTURY2 = 0x37;
export const CMOS_BIOS_BOOTFLAG1 = 0x38;
export const CMOS_BIOS_DISKTRANSFLAG = 0x39;
export const CMOS_BIOS_BOOTFLAG2 = 0x3d;
export const CMOS_MEM_HIGHMEM_LOW = 0x5b;
export const CMOS_MEM_HIGHMEM_MID = 0x5c;
export const CMOS_MEM_HIGHMEM_HIGH = 0x5d;
export const CMOS_BIOS_SMP_COUNT = 0x5f;

// see CPU.prototype.fill_cmos
export const BOOT_ORDER_CD_FIRST = 0x123;
export const BOOT_ORDER_HD_FIRST = 0x312;
export const BOOT_ORDER_FD_FIRST = 0x321;

/**
 * RTC (real time clock) and CMOS
 * @constructor
 * @param {CPU} cpu
 */
export function RTC(cpu)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    this.cmos_index = 0;
    this.cmos_data = new Uint8Array(128);

    // used for cmos entries
    this.rtc_time = cpu.clock.wall_time();
    this.last_update = cpu.clock.now();

    // used for periodic interrupt
    this.next_interrupt = 0;

    // next alarm interrupt
    this.next_interrupt_alarm = 0;

    this.periodic_interrupt = false;

    // corresponds to default value for cmos_a
    this.periodic_interrupt_time = 1000 / 1024;

    this.cmos_a = 0x26;
    this.cmos_b = 2;
    this.cmos_c = 0;

    this.cmos_diag_status = 0;

    this.nmi_disabled = 0;

    this.update_interrupt = false;
    this.update_interrupt_time = 0;

    cpu.io.register_write(0x70, this, function(out_byte)
    {
        this.cmos_index = out_byte & 0x7F;
        this.nmi_disabled = out_byte >> 7;
    });

    cpu.io.register_write(0x71, this, this.cmos_port_write);
    cpu.io.register_read(0x71, this, this.cmos_port_read);
}

RTC.prototype.get_state = function()
{
    this.update_time(this.cpu.clock.now());
    var state = [];

    state[0] = this.cmos_index;
    state[1] = this.cmos_data;
    state[2] = this.rtc_time;
    state[3] = this.last_update;
    state[4] = this.next_interrupt;
    state[5] = this.next_interrupt_alarm;
    state[6] = this.periodic_interrupt;
    state[7] = this.periodic_interrupt_time;
    state[8] = this.cmos_a;
    state[9] = this.cmos_b;
    state[10] = this.cmos_c;
    state[11] = this.nmi_disabled;
    state[12] = this.update_interrupt;
    state[13] = this.update_interrupt_time;
    state[14] = this.cmos_diag_status;
    state[15] = 1; // deadlines and last_update use MachineClock, not host UTC

    return state;
};

RTC.prototype.set_state = function(state)
{
    this.cmos_index = state[0];
    this.cmos_data = state[1];
    this.rtc_time = state[2];
    this.last_update = state[3];
    this.next_interrupt = state[4];
    this.next_interrupt_alarm = state[5];
    this.periodic_interrupt = state[6];
    this.periodic_interrupt_time = state[7];
    this.cmos_a = state[8];
    this.cmos_b = state[9];
    this.cmos_c = state[10];
    this.nmi_disabled = state[11];
    this.update_interrupt = state[12] || false;
    this.update_interrupt_time = state[13] || 0;
    this.cmos_diag_status = state[14] || 0;
    if(state[15] === undefined)
    {
        // Legacy snapshots used host UTC for all RTC deadlines. Preserve the
        // saved calendar and remaining durations without charging offline time.
        const offset = this.cpu.clock.now() - this.last_update;
        this.last_update += offset;
        this.next_interrupt += offset;
        if(this.next_interrupt_alarm) this.next_interrupt_alarm += offset;
        if(this.update_interrupt) this.update_interrupt_time += offset;
    }
};

RTC.prototype.update_time = function(time)
{
    this.rtc_time += time - this.last_update;
    this.last_update = time;
};

/** The RTC's interrupt reaches IRQ 8, unless the HPET's legacy replacement route took it */
RTC.prototype.drives_irq8 = function()
{
    const hpet = this.cpu.devices.hpet;
    return !hpet || !hpet.legacy_replacement();
};

RTC.prototype.timer = function(time, legacy_mode)
{
    this.update_time(time);

    if(this.periodic_interrupt && this.next_interrupt <= time)
    {
        this.drives_irq8() && this.cpu.device_raise_irq(8);
        this.cmos_c |= 1 << 6 | 1 << 7;

        // Coalesce missed edges and move strictly beyond this service point.
        // At an exact deadline, ceil(0) would otherwise leave HLT stuck here.
        this.next_interrupt += this.periodic_interrupt_time *
                (Math.floor((time - this.next_interrupt) / this.periodic_interrupt_time) + 1);
    }
    if(this.next_interrupt_alarm && this.next_interrupt_alarm <= time)
    {
        this.drives_irq8() && this.cpu.device_raise_irq(8);
        this.cmos_c |= 1 << 5 | 1 << 7;

        this.next_interrupt_alarm = 0;
        // ACPI RTC_STS: the alarm is also the RTC wake event (from S3)
        this.cpu.devices.acpi?.rtc_alarm();
    }
    if(this.update_interrupt && this.update_interrupt_time <= time)
    {
        this.drives_irq8() && this.cpu.device_raise_irq(8);
        this.cmos_c |= 1 << 4 | 1 << 7;

        this.update_interrupt_time = time + 1000; // 1 second
    }

    let t = 100;

    if(this.periodic_interrupt && this.next_interrupt)
    {
        t = Math.min(t, Math.max(0, this.next_interrupt - time));
    }
    if(this.next_interrupt_alarm)
    {
        t = Math.min(t, Math.max(0, this.next_interrupt_alarm - time));
    }
    if(this.update_interrupt)
    {
        t = Math.min(t, Math.max(0, this.update_interrupt_time - time));
    }

    return t;
};

RTC.prototype.bcd_pack = function(n)
{
    var i = 0,
        result = 0,
        digit;

    while(n)
    {
        digit = n % 10;

        result |= digit << (4 * i);
        i++;
        n = (n - digit) / 10;
    }

    return result;
};

RTC.prototype.bcd_unpack = function(n)
{
    const low = n & 0xF;
    const high = n >> 4 & 0xF;

    dbg_assert(n < 0x100);
    dbg_assert(low < 10);
    dbg_assert(high < 10);

    return low + 10 * high;
};

RTC.prototype.encode_time = function(t)
{
    if(this.cmos_b & 4)
    {
        // binary mode
        return t;
    }
    else
    {
        return this.bcd_pack(t);
    }
};

RTC.prototype.decode_time = function(t)
{
    if(this.cmos_b & 4)
    {
        // binary mode
        return t;
    }
    else
    {
        return this.bcd_unpack(t);
    }
};

// TODO
// - interrupt on update
// - countdown
// - letting bios/os set values
// (none of these are used by seabios or the OSes we're
// currently testing)
RTC.prototype.cmos_port_read = function()
{
    this.update_time(this.cpu.clock.now());
    var index = this.cmos_index;

    //this.cmos_index = 0xD;

    switch(index)
    {
        case CMOS_RTC_SECONDS:
            dbg_log("read second: " + h(this.encode_time(new Date(this.rtc_time).getUTCSeconds())), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCSeconds());
        case CMOS_RTC_MINUTES:
            dbg_log("read minute: " + h(this.encode_time(new Date(this.rtc_time).getUTCMinutes())), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCMinutes());
        case CMOS_RTC_HOURS:
            dbg_log("read hour: " + h(this.encode_time(new Date(this.rtc_time).getUTCHours())), LOG_RTC);
            // TODO: 12 hour mode
            return this.encode_time(new Date(this.rtc_time).getUTCHours());
        case CMOS_RTC_DAY_WEEK:
            dbg_log("read day: " + h(this.encode_time(new Date(this.rtc_time).getUTCDay() + 1)), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCDay() + 1);
        case CMOS_RTC_DAY_MONTH:
            dbg_log("read day of month: " + h(this.encode_time(new Date(this.rtc_time).getUTCDate())), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCDate());
        case CMOS_RTC_MONTH:
            dbg_log("read month: " + h(this.encode_time(new Date(this.rtc_time).getUTCMonth() + 1)), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCMonth() + 1);
        case CMOS_RTC_YEAR:
            dbg_log("read year: " + h(this.encode_time(new Date(this.rtc_time).getUTCFullYear() % 100)), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCFullYear() % 100);

        case CMOS_STATUS_A:
            if(this.rtc_time % 1000 >= 999)
            {
                // Set update-in-progress for one millisecond every second (we
                // may not have precision higher than that in browser
                // environments)
                return this.cmos_a | 0x80;
            }
            return this.cmos_a;
        case CMOS_STATUS_B:
            //dbg_log("cmos read from index " + h(index));
            return this.cmos_b;

        case CMOS_STATUS_C:
            // It is important to know that upon a IRQ 8, Status Register C
            // will contain a bitmask telling which interrupt happened.
            // What is important is that if register C is not read after an
            // IRQ 8, then the interrupt will not happen again.
            this.drives_irq8() && this.cpu.device_lower_irq(8);

            dbg_log("cmos reg C read", LOG_RTC);
            // Missing IRQF flag
            //return cmos_b & 0x70;
            var c = this.cmos_c;

            this.cmos_c &= ~0xF0;

            return c;

        case CMOS_STATUS_D:
            return 1 << 7; // CMOS battery charged

        case CMOS_DIAG_STATUS:
            dbg_log("cmos diagnostic status read", LOG_RTC);
            return this.cmos_diag_status;

        case CMOS_CENTURY:
        case CMOS_CENTURY2:
            dbg_log("read century: " + h(this.encode_time(new Date(this.rtc_time).getUTCFullYear() / 100 | 0)), LOG_RTC);
            return this.encode_time(new Date(this.rtc_time).getUTCFullYear() / 100 | 0);

        default:
            dbg_log("cmos read from index " + h(index), LOG_RTC);
            return this.cmos_data[this.cmos_index];
    }
};

RTC.prototype.cmos_port_write = function(data_byte)
{
    const time = this.cpu.clock.now();
    this.update_time(time);
    switch(this.cmos_index)
    {
        case 0xA:
            this.cmos_a = data_byte & 0x7F;
            this.periodic_interrupt_time = 1000 / (32768 >> (this.cmos_a & 0xF) - 1);

            dbg_log("Periodic interrupt, a=" + h(this.cmos_a, 2) + " t=" + this.periodic_interrupt_time , LOG_RTC);
            break;
        case 0xB:
            this.cmos_b = data_byte;
            if(this.cmos_b & 0x80)
            {
                // remove update interrupt flag
                this.cmos_b &= 0xEF;
            }
            if(this.cmos_b & 0x40)
            {
                this.next_interrupt = time + this.periodic_interrupt_time;
            }

            if(this.cmos_b & 0x20)
            {
                const now = new Date(this.rtc_time);

                const seconds = this.decode_time(this.cmos_data[CMOS_RTC_SECONDS_ALARM]);
                const minutes = this.decode_time(this.cmos_data[CMOS_RTC_MINUTES_ALARM]);
                const hours = this.decode_time(this.cmos_data[CMOS_RTC_HOURS_ALARM]);

                const alarm_date = new Date(Date.UTC(
                    now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
                    hours, minutes, seconds
                ));

                const ms_from_now = alarm_date - now;
                dbg_log("RTC alarm scheduled for " + alarm_date +
                        " hh:mm:ss=" + hours + ":" + minutes + ":" + seconds +
                        " ms_from_now=" + ms_from_now, LOG_RTC);

                this.next_interrupt_alarm = time + ms_from_now;
            }

            if(this.cmos_b & 0x10)
            {
                dbg_log("update interrupt", LOG_RTC);
                this.update_interrupt_time = time + 1000;
            }

            dbg_log("cmos b=" + h(this.cmos_b, 2), LOG_RTC);
            break;

        case CMOS_DIAG_STATUS:
            this.cmos_diag_status = data_byte;
            break;

        case CMOS_RTC_SECONDS_ALARM:
        case CMOS_RTC_MINUTES_ALARM:
        case CMOS_RTC_HOURS_ALARM:
            this.cmos_write(this.cmos_index, data_byte);
            break;

        default:
            dbg_log("cmos write index " + h(this.cmos_index) + ": " + h(data_byte), LOG_RTC);
            // General purpose CMOS RAM (e.g. 0x0F, the shutdown status that
            // SeaBIOS clears after an S3 resume) keeps what is written
            if(this.cmos_index >= CMOS_DIAG_STATUS + 1 && this.cmos_index < 0x80)
            {
                this.cmos_data[this.cmos_index] = data_byte;
            }
    }

    this.update_interrupt = (this.cmos_b & 0x10) === 0x10 && (this.cmos_a & 0xF) > 0;
    this.periodic_interrupt = (this.cmos_b & 0x40) === 0x40 && (this.cmos_a & 0xF) > 0;
};

/**
 * @param {number} index
 */
RTC.prototype.cmos_read = function(index)
{
    dbg_assert(index < 128);
    return this.cmos_data[index];
};

/**
 * @param {number} index
 * @param {number} value
 */
RTC.prototype.cmos_write = function(index, value)
{
    dbg_log("cmos " + h(index) + " <- " + h(value), LOG_RTC);
    dbg_assert(index < 128);
    this.cmos_data[index] = value;
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/aarch64/a32.rs                                                                  0000644 0000000 0000000 00000202047 00000000000 013640  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AArch32 at EL0 (docs/aarch32-plan.md, profile v3): the A32 and T32
//! instructions of a process the AArch64 kernel runs in AArch32, interpreted.
//! R0-R14 are the low halves of X0-X14 (a write zero-extends), R15 the PC;
//! `pstate` is laid out as an AArch32 SPSR (T, ITSTATE, GE, Q, E) and NZCV
//! is in `nzcv`. An instruction that faults has written no state, as A64's:
//! loads read everything before they write a register, stores translate
//! every access before they write memory.
//!
//! The decoders (A32 here, T32 in t32.rs) call the operations below, which
//! take their operands already read (the PC as the instruction set reads it).

use crate::aarch64::cpu::*;
use crate::aarch64::decode::Inst;
use crate::aarch64::execute::{self, Flow};
use crate::aarch64::memory::{self, Syndrome};
use crate::aarch64::state::{event_register, excl_valid, tpidr_el0, tpidrro_el0};

/// The length of the instruction being executed (2 for a 16-bit T32 one):
/// its exception's return address and ESR.IL
static mut INSTRUCTION_LENGTH: u32 = 4;

#[inline(always)]
pub fn instruction_length() -> u32 { unsafe { INSTRUCTION_LENGTH } }

// ---- registers and flags

/// R[n], n < 15 (R15 is read as the instruction's address + 8 in A32, + 4 in T32: the decoders pass it)
#[inline(always)]
pub fn reg(n: u32) -> u32 { xr(n) as u32 }

/// Write R[n], n < 15: X[n] zero-extended
#[inline(always)]
pub fn set_reg(n: u32, value: u32) { set_x(n, value as u64) }

#[inline(always)]
pub fn carry() -> bool { get_nzcv() & NZCV_C != 0 }

/// N and Z of a result, C and V as given
#[inline(always)]
pub fn flags(result: u32, c: bool, v: bool) -> u32 {
    (result & 0x8000_0000) | ((result == 0) as u32) << 30 | (c as u32) << 29 | (v as u32) << 28
}

/// N and Z of a result, C as given, V kept (the logical operations)
#[inline(always)]
pub fn logical_flags(result: u32, c: bool) -> u32 { flags(result, c, get_nzcv() & NZCV_V != 0) }

/// AddWithCarry: the result, C and V
#[inline(always)]
pub fn add_with_carry(x: u32, y: u32, carry_in: bool) -> (u32, bool, bool) {
    let unsigned = x as u64 + y as u64 + carry_in as u64;
    let signed = x as i32 as i64 + y as i32 as i64 + carry_in as i64;
    let result = unsigned as u32;
    (result, unsigned >> 32 != 0, result as i32 as i64 != signed)
}

#[inline(always)]
fn set_q() { set_pstate_bits(PSTATE_Q, PSTATE_Q) }

#[inline(always)]
pub fn set_pstate_bits(mask: u32, value: u32) { set_pstate(get_pstate() & !mask | value & mask) }

#[inline(always)]
fn ge() -> u32 { get_pstate() >> 16 & 15 }

#[inline(always)]
fn set_ge(value: u32) { set_pstate_bits(PSTATE_GE, value << 16) }

#[inline(always)]
pub fn thumb() -> bool { get_pstate() & PSTATE_T != 0 }

/// ConditionPassed for `cond` with the current NZCV
#[inline(always)]
pub fn condition_passed(cond: u32) -> bool {
    let flags = get_nzcv();
    let n = flags & NZCV_N != 0;
    let z = flags & NZCV_Z != 0;
    let c = flags & NZCV_C != 0;
    let v = flags & NZCV_V != 0;
    let result = match cond >> 1 {
        0 => z,
        1 => c,
        2 => n,
        3 => v,
        4 => c && !z,
        5 => n == v,
        6 => n == v && !z,
        _ => true,
    };
    // (cond 0b1111 is "always" here: the unconditional spaces are decoded before)
    if cond & 1 != 0 && cond != 0b1111 {
        !result
    }
    else {
        result
    }
}

// ---- the shifter

pub const SHIFT_LSL: u32 = 0;
pub const SHIFT_LSR: u32 = 1;
pub const SHIFT_ASR: u32 = 2;
pub const SHIFT_ROR: u32 = 3;
pub const SHIFT_RRX: u32 = 4;

/// DecodeImmShift: an immediate shift's kind and amount (LSR and ASR #0 are
/// #32, ROR #0 is RRX)
#[inline(always)]
pub fn decode_imm_shift(kind: u32, imm5: u32) -> (u32, u32) {
    match kind {
        SHIFT_LSL => (SHIFT_LSL, imm5),
        SHIFT_LSR | SHIFT_ASR => (kind, if imm5 == 0 { 32 } else { imm5 }),
        _ => {
            if imm5 == 0 {
                (SHIFT_RRX, 1)
            }
            else {
                (SHIFT_ROR, imm5)
            }
        },
    }
}

/// Shift_C: the shifted value and the carry out
#[inline(always)]
pub fn shift_c(value: u32, kind: u32, amount: u32, carry_in: bool) -> (u32, bool) {
    if amount == 0 && kind != SHIFT_RRX {
        return (value, carry_in);
    }
    match kind {
        SHIFT_LSL => {
            if amount < 32 {
                (value << amount, value >> (32 - amount) & 1 != 0)
            }
            else if amount == 32 {
                (0, value & 1 != 0)
            }
            else {
                (0, false)
            }
        },
        SHIFT_LSR => {
            if amount < 32 {
                (value >> amount, value >> (amount - 1) & 1 != 0)
            }
            else if amount == 32 {
                (0, value >> 31 != 0)
            }
            else {
                (0, false)
            }
        },
        SHIFT_ASR => {
            if amount < 32 {
                (
                    ((value as i32) >> amount) as u32,
                    value >> (amount - 1) & 1 != 0,
                )
            }
            else {
                (((value as i32) >> 31) as u32, value >> 31 != 0)
            }
        },
        SHIFT_ROR => {
            let result = value.rotate_right(amount & 31);
            (result, result >> 31 != 0)
        },
        _ => ((carry_in as u32) << 31 | value >> 1, value & 1 != 0),
    }
}

/// ARMExpandImm_C (A32's modified immediate): the value and the carry out
#[inline(always)]
pub fn expand_imm_c(imm12: u32, carry_in: bool) -> (u32, bool) {
    let value = imm12 & 0xFF;
    let amount = 2 * (imm12 >> 8);
    if amount == 0 {
        (value, carry_in)
    }
    else {
        let result = value.rotate_right(amount);
        (result, result >> 31 != 0)
    }
}

// ---- writing the PC

/// BranchWritePC: a branch within the instruction set
#[inline(always)]
pub fn branch_to(target: u32) -> Flow {
    Flow::Jump((target & if thumb() { !1 } else { !3 }) as u64)
}

/// BXWritePC (and LoadWritePC, A32's ALUWritePC): bit 0 selects T32
#[inline(always)]
pub fn bx_write_pc(target: u32) -> Flow {
    if target & 1 != 0 {
        set_pstate_bits(PSTATE_T, PSTATE_T);
        Flow::Jump((target & !1) as u64)
    }
    else {
        set_pstate_bits(PSTATE_T, 0);
        // (A32 at an address with bit 1 set: CONSTRAINED UNPREDICTABLE, the
        // PC alignment fault QEMU takes)
        Flow::Jump(target as u64)
    }
}

/// The ALU's write of the PC: BXWritePC in A32, BranchWritePC in T32
#[inline(always)]
fn alu_write_pc(target: u32) -> Flow {
    if thumb() {
        branch_to(target)
    }
    else {
        bx_write_pc(target)
    }
}

// ---- data processing

/// The data processing operations by A32's opcode (bits 24:21; T32 maps its own)
pub const DP_AND: u32 = 0;
pub const DP_EOR: u32 = 1;
pub const DP_SUB: u32 = 2;
pub const DP_RSB: u32 = 3;
pub const DP_ADD: u32 = 4;
pub const DP_ADC: u32 = 5;
pub const DP_SBC: u32 = 6;
pub const DP_RSC: u32 = 7;
pub const DP_TST: u32 = 8;
pub const DP_TEQ: u32 = 9;
pub const DP_CMP: u32 = 10;
pub const DP_CMN: u32 = 11;
pub const DP_ORR: u32 = 12;
pub const DP_MOV: u32 = 13;
pub const DP_BIC: u32 = 14;
pub const DP_MVN: u32 = 15;
/// (T32's ORN)
pub const DP_ORN: u32 = 16;

/// A data processing operation: Rd (15: the PC) = Rn op operand, the flags
/// when `s` (the shifter's carry for the logical ones)
pub fn data_processing(
    op: u32,
    s: bool,
    rd: u32,
    n: u32,
    operand: u32,
    shifter_carry: bool,
) -> Result<Flow, Exception> {
    let c = carry();
    let (result, arithmetic) = match op {
        DP_AND | DP_TST => (n & operand, None),
        DP_EOR | DP_TEQ => (n ^ operand, None),
        DP_ORR => (n | operand, None),
        DP_ORN => (n | !operand, None),
        DP_MOV => (operand, None),
        DP_BIC => (n & !operand, None),
        DP_MVN => (!operand, None),
        DP_SUB | DP_CMP => {
            let (r, c, v) = add_with_carry(n, !operand, true);
            (r, Some((c, v)))
        },
        DP_RSB => {
            let (r, c, v) = add_with_carry(!n, operand, true);
            (r, Some((c, v)))
        },
        DP_ADD | DP_CMN => {
            let (r, c, v) = add_with_carry(n, operand, false);
            (r, Some((c, v)))
        },
        DP_ADC => {
            let (r, c, v) = add_with_carry(n, operand, c);
            (r, Some((c, v)))
        },
        DP_SBC => {
            let (r, c, v) = add_with_carry(n, !operand, c);
            (r, Some((c, v)))
        },
        _ => {
            let (r, c, v) = add_with_carry(!n, operand, c);
            (r, Some((c, v)))
        },
    };
    let compare = (DP_TST..=DP_CMN).contains(&op);
    if s || compare {
        if rd == 15 && !compare {
            // (SUBS PC, LR and the like: an exception return at PL1, UNPREDICTABLE at EL0)
            if crate::aarch64::a32_system::privileged() {
                return crate::aarch64::a32_system::exception_return(result);
            }
            return Err(Exception::Undefined);
        }
        set_nzcv(match arithmetic {
            Some((c, v)) => flags(result, c, v),
            None => logical_flags(result, shifter_carry),
        });
    }
    if compare {
        return Ok(Flow::Next);
    }
    if rd == 15 {
        return Ok(alu_write_pc(result));
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

// ---- multiplies

/// MUL, MLA, MLS (op 0, 1, 2): Rd = Rn * Rm (+ Ra, Ra -)
pub fn multiply(op: u32, s: bool, rd: u32, n: u32, m: u32, a: u32) -> Result<Flow, Exception> {
    let product = n.wrapping_mul(m);
    let result = match op {
        0 => product,
        1 => product.wrapping_add(a),
        _ => a.wrapping_sub(product),
    };
    if s {
        set_nzcv(logical_flags(result, carry()));
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// UMULL, UMLAL, SMULL, SMLAL, UMAAL (op 4, 5, 6, 7, 2): RdHi:RdLo
pub fn multiply_long(
    op: u32,
    s: bool,
    lo: u32,
    hi: u32,
    n: u32,
    m: u32,
) -> Result<Flow, Exception> {
    let acc = (reg(hi) as u64) << 32 | reg(lo) as u64;
    let result = match op {
        4 => n as u64 * m as u64,
        5 => (n as u64 * m as u64).wrapping_add(acc),
        6 => (n as i32 as i64 * m as i32 as i64) as u64,
        7 => ((n as i32 as i64 * m as i32 as i64) as u64).wrapping_add(acc),
        // UMAAL: Rn * Rm + RdHi + RdLo
        _ => n as u64 * m as u64 + reg(hi) as u64 + reg(lo) as u64,
    };
    if s {
        set_nzcv(
            (result >> 32) as u32 & 0x8000_0000
                | ((result == 0) as u32) << 30
                | get_nzcv() & (NZCV_C | NZCV_V),
        );
    }
    set_reg(lo, result as u32);
    set_reg(hi, (result >> 32) as u32);
    Ok(Flow::Next)
}

/// The halfword of `value` that `top` names, sign-extended
#[inline(always)]
fn half(value: u32, top: bool) -> i32 {
    if top {
        (value as i32) >> 16
    }
    else {
        value as u16 as i16 as i32
    }
}

/// SMLA<x><y>, SMUL<x><y> (op 0, 3), SMLAW<y>, SMULW<y> (op 1 with or
/// without `accumulate`), SMLAL<x><y> (op 2: RdHi rd, RdLo ra): the signed
/// halfword multiplies
pub fn multiply_halfword(
    op: u32,
    rd: u32,
    ra: u32,
    n: u32,
    m: u32,
    n_top: bool,
    m_top: bool,
    accumulate: bool,
) -> Result<Flow, Exception> {
    match op {
        0 | 3 => {
            let product = half(n, n_top) as i64 * half(m, m_top) as i64;
            let result = if op == 0 { product + reg(ra) as i32 as i64 } else { product };
            if op == 0 && result != result as i32 as i64 {
                set_q();
            }
            set_reg(rd, result as u32);
        },
        1 => {
            let product = (n as i32 as i64 * half(m, m_top) as i64) >> 16;
            let result = if accumulate { product + reg(ra) as i32 as i64 } else { product };
            if accumulate && result != result as i32 as i64 {
                set_q();
            }
            set_reg(rd, result as u32);
        },
        _ => {
            let product = half(n, n_top) as i64 * half(m, m_top) as i64;
            let acc = ((reg(rd) as u64) << 32 | reg(ra) as u64) as i64;
            let result = acc.wrapping_add(product) as u64;
            set_reg(ra, result as u32);
            set_reg(rd, (result >> 32) as u32);
        },
    }
    Ok(Flow::Next)
}

/// SMLAD, SMLSD, SMUAD, SMUSD (`ra` 15: no accumulator), SMLALD, SMLSLD
/// (`long`: RdHi rd, RdLo ra): the dual 16-bit multiplies, `swap` exchanging
/// Rm's halves
pub fn multiply_dual(
    rd: u32,
    ra: u32,
    n: u32,
    m: u32,
    subtract: bool,
    swap: bool,
    long: bool,
) -> Result<Flow, Exception> {
    let m = if swap { m.rotate_right(16) } else { m };
    let p1 = half(n, false) as i64 * half(m, false) as i64;
    let p2 = half(n, true) as i64 * half(m, true) as i64;
    let sum = if subtract { p1 - p2 } else { p1 + p2 };
    if long {
        let acc = ((reg(rd) as u64) << 32 | reg(ra) as u64) as i64;
        let result = acc.wrapping_add(sum) as u64;
        set_reg(ra, result as u32);
        set_reg(rd, (result >> 32) as u32);
    }
    else {
        let result = if ra == 15 { sum } else { sum + reg(ra) as i32 as i64 };
        if result != result as i32 as i64 {
            set_q();
        }
        set_reg(rd, result as u32);
    }
    Ok(Flow::Next)
}

/// SMMLA, SMMLS, SMMUL (`ra` 15): the most significant word, rounded with `round`
pub fn multiply_most(
    rd: u32,
    ra: u32,
    n: u32,
    m: u32,
    subtract: bool,
    round: bool,
) -> Result<Flow, Exception> {
    let product = n as i32 as i64 * m as i32 as i64;
    let acc = if ra == 15 { 0 } else { (reg(ra) as i32 as i64) << 32 };
    let mut result = if subtract { acc.wrapping_sub(product) } else { acc.wrapping_add(product) };
    if round {
        result = result.wrapping_add(0x8000_0000);
    }
    set_reg(rd, (result >> 32) as u32);
    Ok(Flow::Next)
}

/// SDIV, UDIV: division by 0 is 0 (no trap in this profile)
pub fn divide(rd: u32, n: u32, m: u32, signed: bool) -> Result<Flow, Exception> {
    let result = if m == 0 {
        0
    }
    else if signed {
        (n as i32).wrapping_div(m as i32) as u32
    }
    else {
        n / m
    };
    set_reg(rd, result);
    Ok(Flow::Next)
}

// ---- saturation

/// SignedSatQ to `bits` bits: the value and whether it saturated
#[inline(always)]
fn signed_sat(value: i64, bits: u32) -> (u32, bool) {
    let max = (1i64 << (bits - 1)) - 1;
    let min = -(1i64 << (bits - 1));
    if value > max {
        (max as u32, true)
    }
    else if value < min {
        (min as u32, true)
    }
    else {
        (value as u32, false)
    }
}

/// UnsignedSatQ to `bits` bits
#[inline(always)]
fn unsigned_sat(value: i64, bits: u32) -> (u32, bool) {
    let max = if bits >= 32 { u32::MAX as i64 } else { (1i64 << bits) - 1 };
    if value > max {
        (max as u32, true)
    }
    else if value < 0 {
        (0, true)
    }
    else {
        (value as u32, false)
    }
}

/// QADD, QSUB, QDADD, QDSUB (op 0-3): `m` + or - (`n`, or `n` doubled and saturated)
pub fn saturating_add(op: u32, rd: u32, n: u32, m: u32) -> Result<Flow, Exception> {
    let (doubled, sat1) =
        if op & 2 != 0 { signed_sat(2 * n as i32 as i64, 32) } else { (n, false) };
    let (result, sat2) = if op & 1 != 0 {
        signed_sat(m as i32 as i64 - doubled as i32 as i64, 32)
    }
    else {
        signed_sat(m as i32 as i64 + doubled as i32 as i64, 32)
    };
    if sat1 || sat2 {
        set_q();
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// SSAT, USAT: (Rn shifted) saturated to `bits`
pub fn saturate(rd: u32, value: u32, bits: u32, unsigned: bool) -> Result<Flow, Exception> {
    let (result, sat) = if unsigned {
        unsigned_sat(value as i32 as i64, bits)
    }
    else {
        signed_sat(value as i32 as i64, bits)
    };
    if sat {
        set_q();
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// SSAT16, USAT16
pub fn saturate16(rd: u32, value: u32, bits: u32, unsigned: bool) -> Result<Flow, Exception> {
    let sat =
        |h: i32| if unsigned { unsigned_sat(h as i64, bits) } else { signed_sat(h as i64, bits) };
    let (lo, s1) = sat(half(value, false));
    let (hi, s2) = sat(half(value, true));
    if s1 || s2 {
        set_q();
    }
    set_reg(rd, lo & 0xFFFF | hi << 16);
    Ok(Flow::Next)
}

// ---- parallel addition and subtraction

/// The parallel operations: `kind` 1 signed (GE), 2 signed saturating, 3
/// signed halving, 5 unsigned (GE), 6 unsigned saturating, 7 unsigned
/// halving; `op` 0 ADD16, 1 ASX, 2 SAX, 3 SUB16, 4 ADD8, 7 SUB8
pub fn parallel(kind: u32, op: u32, rd: u32, n: u32, m: u32) -> Result<Flow, Exception> {
    let unsigned = kind & 4 != 0;
    let mode = kind & 3;
    let lanes8 = op >= 4;
    let width = if lanes8 { 8 } else { 16 };
    let count = 32 / width;
    let lane = |v: u32, i: u32| -> i64 {
        let raw = v >> (i * width) & ((1 << width) - 1);
        if unsigned {
            raw as i64
        }
        else {
            ((raw << (32 - width)) as i32 >> (32 - width)) as i64
        }
    };
    let mut result = 0u32;
    let mut ge_bits = 0u32;
    for i in 0..count {
        // (ASX adds in the top lane and subtracts in the bottom, Rm's halves crossed; SAX the other way)
        let (a, b, add) = match op {
            0 | 4 => (lane(n, i), lane(m, i), true),
            3 | 7 => (lane(n, i), lane(m, i), false),
            1 => (lane(n, i), lane(m, 1 - i), i == 1),
            _ => (lane(n, i), lane(m, 1 - i), i == 0),
        };
        let sum = if add { a + b } else { a - b };
        let value = match mode {
            1 => {
                // GE: an unsigned addition's carry, an unsigned subtraction's no borrow, a signed result >= 0
                let set = if unsigned && add { sum >= 1 << width } else { sum >= 0 };
                if set {
                    ge_bits |= if lanes8 { 1 << i } else { 3 << (2 * i) };
                }
                sum as u32
            },
            2 => {
                if unsigned {
                    unsigned_sat(sum, width).0
                }
                else {
                    signed_sat(sum, width).0
                }
            },
            _ => (sum >> 1) as u32,
        };
        result |= (value & ((1 << width) - 1)) << (i * width);
    }
    if mode == 1 {
        set_ge(ge_bits);
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// SEL: each byte from Rn where its GE bit is set, else from Rm
pub fn select(rd: u32, n: u32, m: u32) -> Result<Flow, Exception> {
    let g = ge();
    let mut result = 0;
    for i in 0..4 {
        let byte = if g >> i & 1 != 0 { n } else { m } >> (8 * i) & 0xFF;
        result |= byte << (8 * i);
    }
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// USAD8, USADA8 (`ra` 15: none)
pub fn sum_absolute(rd: u32, ra: u32, n: u32, m: u32) -> Result<Flow, Exception> {
    let mut sum = if ra == 15 { 0u32 } else { reg(ra) };
    for i in 0..4 {
        let a = (n >> (8 * i) & 0xFF) as i32;
        let b = (m >> (8 * i) & 0xFF) as i32;
        sum = sum.wrapping_add((a - b).unsigned_abs());
    }
    set_reg(rd, sum);
    Ok(Flow::Next)
}

// ---- extension, packing, bit operations

/// SXTB, SXTH, SXTB16, UXTB, UXTH, UXTB16 and their accumulating forms
/// (`n` None: no addend), Rm rotated right by `rotation`
pub fn extend(
    rd: u32,
    n: Option<u32>,
    m: u32,
    rotation: u32,
    size: u32,
    signed: bool,
    dual: bool,
) -> Result<Flow, Exception> {
    let rotated = m.rotate_right(rotation);
    let result = if dual {
        let lo = rotated & 0xFF;
        let hi = rotated >> 16 & 0xFF;
        let (lo, hi) = if signed {
            (
                lo as u8 as i8 as u32 & 0xFFFF,
                hi as u8 as i8 as u32 & 0xFFFF,
            )
        }
        else {
            (lo, hi)
        };
        match n {
            Some(n) => {
                (n as u16).wrapping_add(lo as u16) as u32
                    | (((n >> 16) as u16).wrapping_add(hi as u16) as u32) << 16
            },
            None => lo | hi << 16,
        }
    }
    else {
        let value = match (size, signed) {
            (8, true) => rotated as u8 as i8 as i32 as u32,
            (8, false) => rotated & 0xFF,
            (_, true) => rotated as u16 as i16 as i32 as u32,
            _ => rotated & 0xFFFF,
        };
        n.map_or(value, |n| n.wrapping_add(value))
    };
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// PKHBT (`tb` false: Rn's bottom, Rm's top after LSL), PKHTB (Rn's top, Rm's bottom after ASR)
pub fn pack(rd: u32, n: u32, m: u32, tb: bool, shift: u32) -> Result<Flow, Exception> {
    let result = if tb {
        let (shifted, _) = shift_c(m, SHIFT_ASR, if shift == 0 { 32 } else { shift }, false);
        n & 0xFFFF_0000 | shifted & 0xFFFF
    }
    else {
        n & 0xFFFF | (m << shift) & 0xFFFF_0000
    };
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// REV, REV16, REVSH, RBIT, CLZ (op 0-4)
pub fn bit_op(op: u32, rd: u32, m: u32) -> Result<Flow, Exception> {
    let result = match op {
        0 => m.swap_bytes(),
        1 => (m & 0x00FF_00FF) << 8 | (m & 0xFF00_FF00) >> 8,
        2 => (m as u16).swap_bytes() as i16 as i32 as u32,
        3 => m.reverse_bits(),
        _ => m.leading_zeros(),
    };
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// SBFX, UBFX: `width` bits of Rn from `lsb`
pub fn bitfield_extract(
    rd: u32,
    n: u32,
    lsb: u32,
    width: u32,
    signed: bool,
) -> Result<Flow, Exception> {
    if lsb + width > 32 {
        // (UNPREDICTABLE: UNDEFINED, as QEMU)
        return Err(Exception::Undefined);
    }
    let shifted = n << (32 - lsb - width);
    let result =
        if signed { ((shifted as i32) >> (32 - width)) as u32 } else { shifted >> (32 - width) };
    set_reg(rd, result);
    Ok(Flow::Next)
}

/// BFI (`n` Some: Rn's low bits), BFC (None): bits lsb..=msb of Rd
pub fn bitfield_insert(rd: u32, n: Option<u32>, lsb: u32, msb: u32) -> Result<Flow, Exception> {
    if msb < lsb {
        return Err(Exception::Undefined);
    }
    let width = msb - lsb + 1;
    let mask = if width == 32 { u32::MAX } else { ((1u32 << width) - 1) << lsb };
    let value = n.map_or(0, |n| n << lsb);
    set_reg(rd, reg(rd) & !mask | value & mask);
    Ok(Flow::Next)
}

/// CRC32{B,H,W}, CRC32C{B,H,W} (size 0-2)
pub fn crc32(rd: u32, n: u32, m: u32, size: u32, castagnoli: bool) -> Result<Flow, Exception> {
    if size > 2 {
        return Err(Exception::Undefined);
    }
    let bytes = 1u32 << size;
    let poly: u32 = if castagnoli { 0x82F6_3B78 } else { 0xEDB8_8320 };
    let mut crc = n;
    for i in 0..bytes {
        crc ^= m >> (8 * i) & 0xFF;
        for _ in 0..8 {
            crc = if crc & 1 != 0 { crc >> 1 ^ poly } else { crc >> 1 };
        }
    }
    set_reg(rd, crc);
    Ok(Flow::Next)
}

// ---- status registers

/// MRS Rd, APSR: NZCVQ, GE, and as QEMU reads it at EL0 the mode, E, A, I,
/// F (not the execution state's T and IT)
pub fn mrs_apsr(rd: u32) -> Result<Flow, Exception> {
    let shown = PSTATE_Q | PSTATE_GE | PSTATE_E | PSTATE_A | PSTATE_I | PSTATE_F | 0x1F;
    set_reg(rd, get_nzcv() | get_pstate() & shown);
    Ok(Flow::Next)
}

/// MSR CPSR_<fields> (`fields` c 0, x 1, s 2, f 3): APSR's at EL0 (s and
/// f), CPSRWriteByInstr's with cpu_type arm32
pub fn msr_cpsr(value: u32, fields: u32) -> Result<Flow, Exception> {
    if a32_only() {
        crate::aarch64::a32_system::msr_cpsr(value, fields);
        return Ok(Flow::Next);
    }
    msr_apsr(fields >> 2, value)
}

/// MSR SPSR_<fields> (at PL1; UNPREDICTABLE in User and System modes, and at EL0)
pub fn msr_spsr(value: u32, fields: u32) -> Result<Flow, Exception> {
    if !crate::aarch64::a32_system::privileged() || crate::aarch64::a32_system::spsr().is_none() {
        return Err(Exception::Undefined);
    }
    crate::aarch64::a32_system::msr_spsr(value, fields);
    Ok(Flow::Next)
}

/// MRS Rd, CPSR (APSR's view at EL0) or SPSR (`spsr`, at PL1)
pub fn mrs(rd: u32, spsr: bool) -> Result<Flow, Exception> {
    use crate::aarch64::a32_system as system;
    if spsr {
        match system::spsr() {
            Some(value) if system::privileged() => set_reg(rd, value),
            _ => return Err(Exception::Undefined),
        }
        return Ok(Flow::Next);
    }
    if a32_only() {
        set_reg(rd, system::mrs_cpsr());
        return Ok(Flow::Next);
    }
    mrs_apsr(rd)
}

/// MRS Rd, <banked register> and MSR <banked register>, Rn (SYSm `sysm`,
/// `r` the SPSRs) at PL1
pub fn banked(read: bool, r: bool, sysm: u32, rd: u32) -> Result<Flow, Exception> {
    use crate::aarch64::a32_system::{self as system, *};
    if !system::privileged() {
        return Err(Exception::Undefined);
    }
    if r {
        // (SPSR_fiq, _irq, _svc, _abt, _und)
        let mode = match sysm {
            0b01110 => MODE_FIQ,
            0b10000 => MODE_IRQ,
            0b10010 => MODE_SVC,
            0b10100 => MODE_ABT,
            0b10110 => MODE_UND,
            _ => return Err(Exception::Undefined),
        };
        if read {
            set_reg(rd, system::spsr_of(mode));
        }
        else {
            system::set_spsr_of(mode, reg(rd));
        }
        return Ok(Flow::Next);
    }
    // (R8_usr-R14_usr, R8_fiq-R14_fiq, then LR and SP of IRQ, SVC, ABT, UND)
    let (mode, n) = match sysm {
        0b00000..=0b00110 => (MODE_USR, 8 + sysm),
        0b01000..=0b01110 => (MODE_FIQ, sysm),
        0b10000..=0b10111 => {
            let mode = [MODE_IRQ, MODE_SVC, MODE_ABT, MODE_UND][(sysm >> 1 & 3) as usize];
            (mode, if sysm & 1 == 0 { 14 } else { 13 })
        },
        _ => return Err(Exception::Undefined),
    };
    if read {
        set_reg(rd, system::banked_reg(mode, n));
    }
    else {
        system::set_banked_reg(mode, n, reg(rd));
    }
    Ok(Flow::Next)
}

/// MSR APSR_<mask>, value: bit 1 of `mask` NZCVQ, bit 0 GE
pub fn msr_apsr(mask: u32, value: u32) -> Result<Flow, Exception> {
    if mask & 2 != 0 {
        set_nzcv(value & 0xF000_0000);
        set_pstate_bits(PSTATE_Q, value);
    }
    if mask & 1 != 0 {
        set_pstate_bits(PSTATE_GE, value);
    }
    Ok(Flow::Next)
}

// ---- loads and stores

/// A data access's syndrome (ISV 0 for EL1: memory.rs)
#[inline(always)]
fn syndrome(size: u32) -> Syndrome {
    Syndrome {
        valid: true,
        size_log: size.trailing_zeros(),
        ..Syndrome::NONE
    }
}

/// A load of `size` bytes (1, 2, 4), zero-extended, from an address that
/// need not be aligned (MemU: unaligned to Normal memory unless SCTLR.A)
#[inline(always)]
pub fn load(address: u32, size: u32, unprivileged: bool) -> Result<u32, Exception> {
    Ok(memory::read(address as u64, size, unprivileged, syndrome(size))? as u32)
}

/// A load that must be aligned (MemA: LDRD, LDM, LDREX, LDA)
#[inline(always)]
pub(crate) fn load_aligned(address: u32, size: u32) -> Result<u32, Exception> {
    if address & (size - 1) != 0 {
        return Err(execute::alignment(address as u64, false, Syndrome::NONE));
    }
    load(address, size, false)
}

/// A store's translation, written later (nothing is written if any of an
/// instruction's accesses faults)
#[inline(always)]
pub(crate) fn prepare_store(
    address: u32,
    size: u32,
    unprivileged: bool,
    aligned: bool,
) -> Result<memory::Store, Exception> {
    if aligned && address & (size - 1) != 0 {
        return Err(execute::alignment(address as u64, true, Syndrome::NONE));
    }
    memory::prepare_write(address as u64, size, unprivileged, syndrome(size))
}

/// LDR, LDRB, LDRH, LDRSB, LDRSH and the unprivileged forms: `address` the
/// access's, `writeback` the base's new value (None: none); a load of the
/// PC branches (LoadWritePC)
pub fn load_register(
    rt: u32,
    address: u32,
    size: u32,
    signed: bool,
    rn: u32,
    writeback: Option<u32>,
    unprivileged: bool,
) -> Result<Flow, Exception> {
    let raw = load(address, size, unprivileged)?;
    let value = match (size, signed) {
        (1, true) => raw as u8 as i8 as i32 as u32,
        (2, true) => raw as u16 as i16 as i32 as u32,
        _ => raw,
    };
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    if rt == 15 {
        return Ok(bx_write_pc(value));
    }
    set_reg(rt, value);
    Ok(Flow::Next)
}

/// STR, STRB, STRH and the unprivileged forms (`value` read before the writeback)
pub fn store_register(
    value: u32,
    address: u32,
    size: u32,
    rn: u32,
    writeback: Option<u32>,
    unprivileged: bool,
) -> Result<Flow, Exception> {
    let store = prepare_store(address, size, unprivileged, false)?;
    store.commit(value as u64)?;
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    Ok(Flow::Next)
}

/// LDRD: Rt, Rt2 from two aligned words
pub fn load_dual(
    rt: u32,
    rt2: u32,
    address: u32,
    rn: u32,
    writeback: Option<u32>,
) -> Result<Flow, Exception> {
    let first = load_aligned(address, 4)?;
    let second = load_aligned(address.wrapping_add(4), 4)?;
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    set_reg(rt, first);
    set_reg(rt2, second);
    Ok(Flow::Next)
}

/// STRD
pub fn store_dual(
    first: u32,
    second: u32,
    address: u32,
    rn: u32,
    writeback: Option<u32>,
) -> Result<Flow, Exception> {
    let s1 = prepare_store(address, 4, false, true)?;
    let s2 = prepare_store(address.wrapping_add(4), 4, false, true)?;
    s1.commit(first as u64)?;
    s2.commit(second as u64)?;
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    Ok(Flow::Next)
}

/// LDM (every form): the registers of `list` from `start` up, the base's
/// writeback; the PC in the list branches
pub fn load_multiple(
    rn: u32,
    list: u32,
    start: u32,
    writeback: Option<u32>,
) -> Result<Flow, Exception> {
    let mut values = [0u32; 16];
    let mut address = start;
    for i in 0..16 {
        if list & 1 << i != 0 {
            values[i] = load_aligned(address, 4)?;
            address = address.wrapping_add(4);
        }
    }
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    for i in 0..15 {
        if list & 1 << i != 0 {
            set_reg(i as u32, values[i]);
        }
    }
    if list & 1 << 15 != 0 {
        return Ok(bx_write_pc(values[15]));
    }
    Ok(Flow::Next)
}

/// STM (every form): `pc` the value stored for the PC
pub fn store_multiple(
    rn: u32,
    list: u32,
    start: u32,
    writeback: Option<u32>,
    pc: u32,
) -> Result<Flow, Exception> {
    let mut stores: [Option<(memory::Store, u32)>; 16] = Default::default();
    let mut address = start;
    for i in 0..16u32 {
        if list & 1 << i != 0 {
            // (the base in the list: its value before the writeback)
            let value = if i == 15 { pc } else { reg(i) };
            stores[i as usize] = Some((prepare_store(address, 4, false, true)?, value));
            address = address.wrapping_add(4);
        }
    }
    for store in stores.into_iter().flatten() {
        store.0.commit(store.1 as u64)?;
    }
    if let Some(base) = writeback {
        set_reg(rn, base);
    }
    Ok(Flow::Next)
}

/// LDREX*, STREX*, LDAEX*, STLEX* (A64's exclusives: size 0 byte, 1
/// halfword, 2 word, 3 the doubleword pair), `status` the STREX result
/// register
pub fn exclusive(
    load: bool,
    size: u32,
    acquire_release: bool,
    rt: u32,
    rt2: u32,
    status: u32,
    address: u32,
    pc: u32,
) -> Result<Flow, Exception> {
    let pair = size == 3;
    unsafe { execute::STEPPED_EXCLUSIVE_LOAD = load };
    let i = Inst {
        op: crate::aarch64::decode::Op::Exclusive,
        rd: rt as u8,
        rn: 0,
        rm: status as u8,
        ra: rt2 as u8,
        sf: false,
        s: false,
        sub: load as u8 | (pair as u8) << 1 | (acquire_release as u8) << 2,
        cond: if pair { 2 } else { size as u8 },
        shift: 0,
        amount: 0,
        imm: 0,
    };
    execute::exclusive_at(&i, pc as u64, address as u64)
}

/// LDA*, STL* (size 1, 2, 4): aligned, ordered
pub fn acquire_release(load: bool, size: u32, rt: u32, address: u32) -> Result<Flow, Exception> {
    if load {
        let value = load_aligned(address, size)?;
        crate::parallel::full_fence();
        set_reg(rt, value);
    }
    else {
        let store = prepare_store(address, size, false, true)?;
        crate::parallel::full_fence();
        store.commit(reg(rt) as u64)?;
    }
    Ok(Flow::Next)
}

// ---- hints, barriers, system registers

/// The hints of A32 and T32 (NOP 0, YIELD 1, WFE 2, WFI 3, SEV 4, SEVL 5;
/// the rest are NOPs here), `cond` for a trapped WFx's syndrome
pub fn hint(hint: u32, cond: u32) -> Result<Flow, Exception> {
    // (WFx's syndrome from AArch32: CV, COND, TI)
    let wfx = |ti: u32| Exception::Trapped32 {
        ec: EC_WFX,
        iss: 1 << 24 | cond << 20 | ti,
    };
    match hint {
        1 => Ok(Flow::Yield),
        2 => unsafe {
            if *event_register != 0 {
                *event_register = 0;
                Ok(Flow::Next)
            }
            else if sctlr() & SCTLR_NTWE == 0 && el() == 0 {
                Err(wfx(1))
            }
            else {
                Ok(Flow::Wait(2))
            }
        },
        3 => {
            if sctlr() & SCTLR_NTWI == 0 && el() == 0 {
                return Err(wfx(0));
            }
            Ok(Flow::Wait(1))
        },
        4 => {
            crate::aarch64::smp::send_event();
            Ok(Flow::Next)
        },
        5 => {
            unsafe { *event_register = 1 };
            Ok(Flow::Next)
        },
        _ => Ok(Flow::Next),
    }
}

/// CLREX
pub fn clear_exclusive() -> Result<Flow, Exception> {
    unsafe { *excl_valid = 0 };
    crate::aarch64::smp::release();
    Ok(Flow::Next)
}

/// DMB, DSB, ISB (`dsb`: waits for the other cores' maintenance, as A64's)
pub fn barrier(dsb: bool) -> Result<Flow, Exception> {
    crate::parallel::full_fence();
    if dsb && !crate::aarch64::tlb::synced() {
        return Ok(Flow::Retry);
    }
    Ok(Flow::Next)
}

/// SCTLR_EL1.CP15BEN: CP15's barrier operations at EL0
const SCTLR_CP15BEN: u64 = 1 << 5;

/// The syndrome of a trapped MCR/MRC (EC 0x03, 0x05) or MCRR/MRRC (0x04, 0x0C)
fn cp_trap(
    ec: u32,
    cond: u32,
    opc1: u32,
    crn: u32,
    crm: u32,
    opc2: u32,
    rt: u32,
    rt2: u32,
    read: bool,
) -> Exception {
    let common = 1 << 24 | cond << 20 | rt << 5 | crm << 1 | read as u32;
    let iss = if ec == 0x04 || ec == 0x0C {
        common | opc1 << 16 | rt2 << 10
    }
    else {
        common | opc2 << 17 | opc1 << 14 | crn << 10
    };
    Exception::Trapped32 { ec, iss }
}

/// A trap of the AArch64 register an AArch32 one is (EC 0x18 from the
/// timer) as the AArch32 trap
fn as_cp_trap(e: Exception, trap: Exception) -> Exception {
    match e {
        Exception::SystemRegister(_) => trap,
        other => other,
    }
}

/// MRC, MCR of CP15 at EL0 (`value` what MCR writes): the thread ID
/// registers, the generic timer's, CP15's barriers; the rest UNDEFINED
pub fn cp15(
    read: bool,
    opc1: u32,
    crn: u32,
    crm: u32,
    opc2: u32,
    rt: u32,
    value: u32,
    cond: u32,
) -> Result<Flow, Exception> {
    if crate::aarch64::a32_system::privileged() {
        return crate::aarch64::a32_system::cp15(read, opc1, crn, crm, opc2, rt, value);
    }
    let trap = cp_trap(0x03, cond, opc1, crn, crm, opc2, rt, 0, read);
    match (opc1, crn, crm, opc2) {
        // TPIDRURW (TPIDR_EL0's low half), TPIDRURO (TPIDRRO_EL0's, read-only at EL0)
        (0, 13, 0, 2) => unsafe {
            if read {
                set_reg(rt, *tpidr_el0 as u32);
            }
            else {
                *tpidr_el0 = value as u64;
            }
            Ok(Flow::Next)
        },
        (0, 13, 0, 3) if read => {
            unsafe { set_reg(rt, *tpidrro_el0 as u32) };
            Ok(Flow::Next)
        },
        // CP15DMB, CP15DSB, CP15ISB (writes, with SCTLR_EL1.CP15BEN)
        (0, 7, 10, 5) | (0, 7, 10, 4) | (0, 7, 5, 4) if !read => {
            if sctlr() & SCTLR_CP15BEN == 0 {
                return Err(Exception::Undefined);
            }
            barrier(crm == 10 && opc2 == 4)
        },
        // CNTFRQ, CNTP_TVAL, CNTP_CTL, CNTV_TVAL, CNTV_CTL
        (0, 14, 0, 0) | (0, 14, 2, 0) | (0, 14, 2, 1) | (0, 14, 3, 0) | (0, 14, 3, 1) => {
            let key = crate::aarch64::sysregs::key(3, 3, 14, crm, opc2);
            if read {
                let v = crate::aarch64::timer::read(key, rt).map_err(|e| as_cp_trap(e, trap))?;
                set_reg(rt, v as u32);
            }
            else {
                crate::aarch64::timer::write(key, rt, value as u64)
                    .map_err(|e| as_cp_trap(e, trap))?;
            }
            Ok(Flow::Next)
        },
        _ => Err(Exception::Undefined),
    }
}

/// MRRC, MCRR of CP15 at EL0: the timer's 64-bit registers (CRm 14: CNTPCT
/// opc1 0, CNTVCT 1, CNTP_CVAL 2, CNTV_CVAL 3)
pub fn cp15_64(
    read: bool,
    opc1: u32,
    crm: u32,
    rt: u32,
    rt2: u32,
    value: u64,
    cond: u32,
) -> Result<Flow, Exception> {
    if crate::aarch64::a32_system::privileged() {
        return crate::aarch64::a32_system::cp15_64(read, opc1, crm, rt, rt2, value);
    }
    let trap = cp_trap(0x04, cond, opc1, 0, crm, 0, rt, rt2, read);
    if crm != 14 || opc1 > 3 {
        return Err(Exception::Undefined);
    }
    let key = match opc1 {
        0 => crate::aarch64::sysregs::key(3, 3, 14, 0, 1),
        1 => crate::aarch64::sysregs::key(3, 3, 14, 0, 2),
        2 => crate::aarch64::sysregs::key(3, 3, 14, 2, 2),
        _ => crate::aarch64::sysregs::key(3, 3, 14, 3, 2),
    };
    if read {
        let v = crate::aarch64::timer::read(key, rt).map_err(|e| as_cp_trap(e, trap))?;
        set_reg(rt, v as u32);
        set_reg(rt2, (v >> 32) as u32);
    }
    else {
        if opc1 < 2 {
            return Err(Exception::Undefined);
        }
        crate::aarch64::timer::write(key, rt, value).map_err(|e| as_cp_trap(e, trap))?;
    }
    Ok(Flow::Next)
}

// ---- fetch

/// Whether a T32 halfword starts a 32-bit instruction
#[inline(always)]
pub fn t32_wide(halfword: u32) -> bool { halfword >> 11 >= 0b11101 }

/// The T32 halfword at `address` (2-aligned)
fn fetch_halfword(address: u64) -> Result<u32, Exception> {
    let word = memory::fetch(address & !3)?;
    Ok(if address & 2 != 0 { word >> 16 } else { word & 0xFFFF })
}

/// The instruction at the PC and its length: A32's word (4-aligned), or T32's
/// halfword or two (the first in bits 31:16, as the ARM ARM writes them)
fn fetch(address: u64, thumb: bool) -> Result<(u32, u32), Exception> {
    if thumb {
        let first = fetch_halfword(address)?;
        if !t32_wide(first) {
            return Ok((first, 2));
        }
        // (the second halfword may be on the next page)
        let second = fetch_halfword((address as u32).wrapping_add(2) as u64)?;
        Ok((first << 16 | second, 4))
    }
    else {
        if address & 3 != 0 {
            return Err(Exception::PcAlignment(address));
        }
        Ok((memory::fetch(address)?, 4))
    }
}

// ---- one instruction

/// (diagnostics: crate::aarch64::jit::pages' step and helper counts) an
/// AArch32 instruction's class: A32's bits 27:20 (768 up), T32's first
/// halfword's top bits (16-bit 512 up, 32-bit 640 up)
pub fn step_key(word: u32, length: u32, thumb: bool) -> u32 {
    if !thumb {
        768 | word >> 20 & 0xFF
    }
    else if length == 2 {
        512 | word >> 9 & 0x7F
    }
    else {
        640 | word >> 20 & 0x7F
    }
}

/// An instruction fetched (`length` 4, or T32's 2 or 4) executed at `pc`
/// (the page tier's helpers too: crate::aarch64::jit::pages::a32_page_helper)
#[inline(always)]
pub fn execute_fetched(word: u32, length: u32, pc: u32, thumb: bool) -> Result<Flow, Exception> {
    unsafe { INSTRUCTION_LENGTH = length };
    if thumb {
        crate::aarch64::t32::execute(word, length, pc)
    }
    else {
        a32(word, pc)
    }
}

/// Execute the AArch32 instruction at `address` (the PC): it retires, or
/// takes its exception having written no state (execute::interpret_one's
/// contract)
pub fn interpret_one(address: u64) -> Flow {
    let thumb = thumb();
    unsafe { INSTRUCTION_LENGTH = if thumb { 2 } else { 4 } };
    let mut fetched = 0;
    let result = fetch(address, thumb).and_then(|(word, length)| {
        fetched = word;
        unsafe { INSTRUCTION_LENGTH = length };
        if unsafe { crate::aarch64::jit::pages::A32_TRACE } && crate::aarch64::cpu::el() == 0 {
            crate::aarch64::jit::pages::a32_trace(1, address as u32, word);
        }
        // (a breakpoint: BAS 1111 or 0011 the word, 1100 its second halfword)
        if unsafe { crate::aarch64::debug::ANY_BREAKPOINT } {
            if let Some(exception) = crate::aarch64::debug::check_breakpoint(address) {
                return Err(exception);
            }
        }
        // (software step's EX: whether the stepped instruction is a load exclusive)
        unsafe { execute::STEPPED_EXCLUSIVE_LOAD = false };
        unsafe { execute::LAST_STEPPED = (step_key(word, length, thumb), word) };
        execute_fetched(word, length, address as u32, thumb)
    });
    let length = instruction_length();
    match result {
        Ok(flow) => {
            crate::core_stats::add_pending(1, 0);
            match flow {
                Flow::Next | Flow::Yield | Flow::Wait(_) | Flow::Off => {
                    set_pc((address as u32).wrapping_add(length) as u64)
                },
                Flow::Jump(target) => set_pc(target),
                Flow::Set | Flow::Retry => {},
            }
            // (the IT block goes on: T32's instructions, executed or not)
            if thumb && !matches!(flow, Flow::Set | Flow::Retry) {
                crate::aarch64::t32::it_advance();
            }
            flow
        },
        Err(exception @ Exception::Svc(_)) => {
            // (the instruction executed: the exception returns after it, the
            // IT block a step on; a software step is done, SPSR.SS 0)
            crate::core_stats::add_pending(1, 0);
            if thumb {
                crate::aarch64::t32::it_advance();
            }
            if crate::aarch64::debug::stepping() {
                crate::aarch64::debug::step_done();
            }
            take_sync(exception);
            Flow::Set
        },
        // (the GLES backdoor's UDF: a call, answered in r0, crate::aarch64::backdoor)
        Err(Exception::Undefined) if crate::aarch64::backdoor::call(fetched, length, thumb) => {
            crate::core_stats::add_pending(1, 0);
            set_pc((address as u32).wrapping_add(length) as u64);
            if thumb {
                crate::aarch64::t32::it_advance();
            }
            Flow::Next
        },
        Err(exception) => {
            take_sync(exception);
            Flow::Set
        },
    }
}

// ---- A32

/// An A32 register read: the PC as the instruction's address + 8
#[inline(always)]
fn a32_read(n: u32, pc: u32) -> u32 {
    if n == 15 {
        pc.wrapping_add(8)
    }
    else {
        reg(n)
    }
}

/// A32's operand 2 of a data processing instruction with an immediate
/// shift (bit 4 0) or a register shift (bit 4 1): the value, the carry
fn a32_shifted_operand(word: u32, pc: u32) -> Result<(u32, bool), Exception> {
    let rm = word & 15;
    let kind = word >> 5 & 3;
    if word & 1 << 4 == 0 {
        let (kind, amount) = decode_imm_shift(kind, word >> 7 & 31);
        Ok(shift_c(a32_read(rm, pc), kind, amount, carry()))
    }
    else {
        let rs = word >> 8 & 15;
        if rm == 15 || rs == 15 || word >> 12 & 15 == 15 || word >> 16 & 15 == 15 {
            // (a register-shifted register with the PC: UNPREDICTABLE)
            return Err(Exception::Undefined);
        }
        Ok(shift_c(reg(rm), kind, reg(rs) & 0xFF, carry()))
    }
}

/// A32: the instruction `word` at `pc`
fn a32(word: u32, pc: u32) -> Result<Flow, Exception> {
    let cond = word >> 28;
    if cond == 0b1111 {
        return a32_unconditional(word, pc);
    }
    // (UDF: cond 0b1110 only; the permanently undefined space regardless of the condition)
    if word & 0x0FF0_00F0 == 0x07F0_00F0 {
        return Err(Exception::Undefined);
    }
    if !condition_passed(cond) {
        return Ok(Flow::Next);
    }
    let rn = word >> 16 & 15;
    let rd = word >> 12 & 15;
    match word >> 25 & 7 {
        0b000 => {
            let op1 = word >> 20 & 31;
            if word & 0x90 == 0x90 {
                if word >> 5 & 3 == 0 {
                    return if word & 1 << 24 == 0 {
                        a32_multiply(word)
                    }
                    else {
                        a32_synchronization(word, pc)
                    };
                }
                return a32_extra_load_store(word, pc);
            }
            if op1 & 0b11001 == 0b10000 {
                return if word & 0x80 == 0 {
                    a32_miscellaneous(word, pc)
                }
                else {
                    a32_halfword_multiply(word)
                };
            }
            let (operand, shifter_carry) = a32_shifted_operand(word, pc)?;
            let n = if word & 1 << 4 != 0 { reg(rn) } else { a32_read(rn, pc) };
            data_processing(
                word >> 21 & 15,
                word & 1 << 20 != 0,
                rd,
                n,
                operand,
                shifter_carry,
            )
        },
        0b001 => {
            let op1 = word >> 20 & 31;
            match op1 {
                // MOVW, MOVT
                0b10000 | 0b10100 => {
                    if rd == 15 {
                        return Err(Exception::Undefined);
                    }
                    let imm16 = (word >> 4 & 0xF000) | word & 0xFFF;
                    let value = if op1 == 0b10000 { imm16 } else { reg(rd) & 0xFFFF | imm16 << 16 };
                    set_reg(rd, value);
                    Ok(Flow::Next)
                },
                // MSR (immediate) and the hints
                0b10010 | 0b10110 => {
                    if op1 == 0b10010 && rn == 0 {
                        return hint(word & 0xFF, cond);
                    }
                    let (value, _) = expand_imm_c(word & 0xFFF, carry());
                    if op1 == 0b10110 {
                        // (MSR SPSR: UNPREDICTABLE at EL0)
                        return msr_spsr(value, rn);
                    }
                    msr_cpsr(value, rn)
                },
                _ => {
                    let (operand, shifter_carry) = expand_imm_c(word & 0xFFF, carry());
                    data_processing(
                        word >> 21 & 15,
                        word & 1 << 20 != 0,
                        rd,
                        a32_read(rn, pc),
                        operand,
                        shifter_carry,
                    )
                },
            }
        },
        0b010 | 0b011 => {
            if word >> 25 & 1 != 0 && word & 1 << 4 != 0 {
                return a32_media(word);
            }
            a32_load_store(word, pc)
        },
        0b100 => a32_block_transfer(word, pc),
        0b101 => {
            let offset = ((word << 8) as i32 >> 6) as u32;
            if word & 1 << 24 != 0 {
                set_reg(14, pc.wrapping_add(4));
            }
            Ok(Flow::Jump(pc.wrapping_add(8).wrapping_add(offset) as u64))
        },
        _ => {
            // SVC: the immediate's low 16 bits are the ISS
            if word >> 24 & 15 == 15 {
                return Err(Exception::Svc(word as u16));
            }
            a32_coprocessor(word, pc, word >> 8 & 15, cond)
        },
    }
}

/// The multiplies (bits 27:24 0000, 7:4 1001)
fn a32_multiply(word: u32) -> Result<Flow, Exception> {
    let s = word & 1 << 20 != 0;
    let rd = word >> 16 & 15;
    let ra = word >> 12 & 15;
    let rm = word >> 8 & 15;
    let rn = word & 15;
    if rd == 15 || rn == 15 || rm == 15 {
        return Err(Exception::Undefined);
    }
    match word >> 21 & 7 {
        0 => multiply(0, s, rd, reg(rn), reg(rm), 0),
        1 if ra != 15 => multiply(1, s, rd, reg(rn), reg(rm), reg(ra)),
        2 if !s && ra != 15 && ra != rd => multiply_long(2, false, ra, rd, reg(rn), reg(rm)),
        3 if !s && ra != 15 => multiply(2, false, rd, reg(rn), reg(rm), reg(ra)),
        op @ 4..=7 => {
            if ra == 15 || ra == rd {
                return Err(Exception::Undefined);
            }
            multiply_long(op, s, ra, rd, reg(rn), reg(rm))
        },
        _ => Err(Exception::Undefined),
    }
}

/// The synchronization primitives (bits 27:23 00011, 7:4 1001): the
/// exclusives and load-acquire/store-release
fn a32_synchronization(word: u32, pc: u32) -> Result<Flow, Exception> {
    let size = [2, 3, 0, 1][(word >> 21 & 3) as usize];
    let load = word & 1 << 20 != 0;
    let rn = word >> 16 & 15;
    let ex_ord = word >> 8 & 3;
    if word >> 10 & 3 != 3 || rn == 15 {
        return Err(Exception::Undefined);
    }
    let address = reg(rn) as u64;
    let rt = if load { word >> 12 & 15 } else { word & 15 };
    let status = word >> 12 & 15;
    if rt == 15 || size == 3 && (rt & 1 != 0 || rt == 14) {
        return Err(Exception::Undefined);
    }
    match ex_ord {
        // LDREX, STREX and LDAEX, STLEX
        3 | 2 => {
            if !load
                && (status == 15 || status == rn || status == rt || size == 3 && status == rt + 1)
            {
                return Err(Exception::Undefined);
            }
            exclusive(
                load,
                size,
                ex_ord == 2,
                rt,
                rt + 1,
                status,
                address as u32,
                pc,
            )
        },
        // LDA, STL (no doubleword)
        0 => {
            if size == 3 || !load && status != 15 {
                return Err(Exception::Undefined);
            }
            acquire_release(load, 1 << size, rt, address as u32)
        },
        _ => Err(Exception::Undefined),
    }
}

/// The extra loads and stores (bits 27:25 000, 7 1, 4 1, 6:5 not 00):
/// LDRH, STRH, LDRSB, LDRSH, LDRD, STRD and their unprivileged forms
fn a32_extra_load_store(word: u32, pc: u32) -> Result<Flow, Exception> {
    let p = word & 1 << 24 != 0;
    let u = word & 1 << 23 != 0;
    let immediate = word & 1 << 22 != 0;
    let w = word & 1 << 21 != 0;
    let l = word & 1 << 20 != 0;
    let rn = word >> 16 & 15;
    let rt = word >> 12 & 15;
    let op2 = word >> 5 & 3;
    if !immediate && word & 15 == 15 {
        return Err(Exception::Undefined);
    }
    let offset = if immediate { (word >> 4 & 0xF0) | word & 15 } else { reg(word & 15) };
    let unprivileged = !p && w;
    let base = a32_read(rn, pc);
    let offset_address = if u { base.wrapping_add(offset) } else { base.wrapping_sub(offset) };
    let address = if p { offset_address } else { base };
    let wback = !p || w;
    if wback && (rn == 15 || rn == rt) {
        return Err(Exception::Undefined);
    }
    let writeback = if wback { Some(offset_address) } else { None };
    match (op2, l) {
        (1, false) => store_register(a32_read(rt, pc), address, 2, rn, writeback, unprivileged),
        (1, true) => load_register(rt, address, 2, false, rn, writeback, unprivileged),
        (2, true) => load_register(rt, address, 1, true, rn, writeback, unprivileged),
        (3, true) => load_register(rt, address, 2, true, rn, writeback, unprivileged),
        // LDRD, STRD (no unprivileged form)
        (2, false) | (3, false) => {
            if unprivileged || rt & 1 != 0 || rt == 14 || wback && rn == rt + 1 {
                return Err(Exception::Undefined);
            }
            if op2 == 2 {
                load_dual(rt, rt + 1, address, rn, writeback)
            }
            else {
                store_dual(reg(rt), reg(rt + 1), address, rn, writeback)
            }
        },
        _ => Err(Exception::Undefined),
    }
}

/// The miscellaneous instructions (bits 27:23 00010, 20 0, 7 0)
fn a32_miscellaneous(word: u32, pc: u32) -> Result<Flow, Exception> {
    let op0 = word >> 21 & 3;
    let rd = word >> 12 & 15;
    let rn = word >> 16 & 15;
    let rm = word & 15;
    match word >> 4 & 7 {
        0 => {
            let spsr = word & 1 << 22 != 0;
            if word & 1 << 9 != 0 {
                // (banked registers: PL1's; SYSm M:M1)
                let sysm = (word >> 8 & 1) << 4 | rn;
                return if op0 & 1 == 0 {
                    banked(true, spsr, sysm, rd)
                }
                else {
                    banked(false, spsr, sysm, rm)
                };
            }
            match (op0 & 1 != 0, spsr) {
                (false, _) => mrs(rd, spsr),
                (true, false) => msr_cpsr(reg(rm), rn),
                (true, true) => msr_spsr(reg(rm), rn),
            }
        },
        // BX, BXJ (as BX)
        1 | 2 if op0 == 1 => Ok(bx_write_pc(a32_read(rm, pc))),
        1 if op0 == 3 => bit_op(4, rd, reg(rm)),
        3 if op0 == 1 => {
            let target = reg(rm);
            set_reg(14, pc.wrapping_add(4));
            Ok(bx_write_pc(target))
        },
        4 => crc32(rd, reg(rn), reg(rm), op0, word & 1 << 9 != 0),
        5 => saturating_add(op0, rd, reg(rn), reg(rm)),
        // BKPT (EC 0x38, its immediate); HVC, SMC and ERET are UNDEFINED at EL0
        7 if op0 == 1 => Err(Exception::Trapped32 {
            ec: 0x38,
            iss: (word >> 4 & 0xFFF0) | word & 15,
        }),
        // HVC, SMC (PSCI at PL1, the device tree's conduit is HVC); ERET (as SUBS PC, LR, #0)
        7 if op0 == 2 && crate::aarch64::a32_system::privileged() => {
            crate::aarch64::a32_system::hvc()
        },
        7 if op0 == 3 && crate::aarch64::a32_system::privileged() => {
            crate::aarch64::a32_system::hvc()
        },
        6 if op0 == 3 && rm == 14 && crate::aarch64::a32_system::privileged() => {
            crate::aarch64::a32_system::exception_return(reg(14))
        },
        _ => Err(Exception::Undefined),
    }
}

/// The halfword multiplies (bits 27:23 00010, 20 0, 7 1, 4 0)
fn a32_halfword_multiply(word: u32) -> Result<Flow, Exception> {
    let rd = word >> 16 & 15;
    let ra = word >> 12 & 15;
    let rm = word >> 8 & 15;
    let rn = word & 15;
    let m_top = word & 1 << 6 != 0;
    let n_top = word & 1 << 5 != 0;
    match word >> 21 & 3 {
        0 => multiply_halfword(0, rd, ra, reg(rn), reg(rm), n_top, m_top, true),
        1 => multiply_halfword(1, rd, ra, reg(rn), reg(rm), false, m_top, !n_top),
        2 => {
            if ra == rd {
                return Err(Exception::Undefined);
            }
            multiply_halfword(2, rd, ra, reg(rn), reg(rm), n_top, m_top, true)
        },
        _ => multiply_halfword(3, rd, ra, reg(rn), reg(rm), n_top, m_top, false),
    }
}

/// LDR, STR, LDRB, STRB (bits 27:26 01): immediate (bit 25 0) or register offsets
fn a32_load_store(word: u32, pc: u32) -> Result<Flow, Exception> {
    let register = word & 1 << 25 != 0;
    let p = word & 1 << 24 != 0;
    let u = word & 1 << 23 != 0;
    let byte = word & 1 << 22 != 0;
    let w = word & 1 << 21 != 0;
    let l = word & 1 << 20 != 0;
    let rn = word >> 16 & 15;
    let rt = word >> 12 & 15;
    let offset = if register {
        let rm = word & 15;
        if rm == 15 {
            return Err(Exception::Undefined);
        }
        let (kind, amount) = decode_imm_shift(word >> 5 & 3, word >> 7 & 31);
        shift_c(reg(rm), kind, amount, carry()).0
    }
    else {
        word & 0xFFF
    };
    let unprivileged = !p && w;
    let base = a32_read(rn, pc);
    let offset_address = if u { base.wrapping_add(offset) } else { base.wrapping_sub(offset) };
    let address = if p { offset_address } else { base };
    let wback = !p || w;
    if wback && (rn == 15 || rn == rt) || byte && rt == 15 {
        return Err(Exception::Undefined);
    }
    let writeback = if wback { Some(offset_address) } else { None };
    let size = if byte { 1 } else { 4 };
    if l {
        load_register(rt, address, size, false, rn, writeback, unprivileged)
    }
    else {
        store_register(a32_read(rt, pc), address, size, rn, writeback, unprivileged)
    }
}

/// LDM, STM (bits 27:25 100)
fn a32_block_transfer(word: u32, pc: u32) -> Result<Flow, Exception> {
    let p = word & 1 << 24 != 0;
    let u = word & 1 << 23 != 0;
    let user = word & 1 << 22 != 0;
    let w = word & 1 << 21 != 0;
    let l = word & 1 << 20 != 0;
    let rn = word >> 16 & 15;
    let list = word & 0xFFFF;
    if rn == 15 || list == 0 || user && !crate::aarch64::a32_system::privileged() {
        // (the user registers and exception returns: UNPREDICTABLE at EL0)
        return Err(Exception::Undefined);
    }
    let count = list.count_ones();
    let base = reg(rn);
    let start = match (p, u) {
        (false, true) => base,
        (true, true) => base.wrapping_add(4),
        (false, false) => base.wrapping_sub(4 * count).wrapping_add(4),
        (true, false) => base.wrapping_sub(4 * count),
    };
    let new_base = if u { base.wrapping_add(4 * count) } else { base.wrapping_sub(4 * count) };
    if user {
        // LDM (exception return), LDM and STM of the User mode's registers (no writeback)
        return crate::aarch64::a32_system::block_user(
            l,
            rn,
            list,
            start,
            if w { Some(new_base) } else { None },
            pc.wrapping_add(8),
        );
    }
    if l {
        // (the base in the list with writeback: UNPREDICTABLE, the loaded value here)
        let writeback = if w && list & 1 << rn == 0 { Some(new_base) } else { None };
        load_multiple(rn, list, start, writeback)
    }
    else {
        store_multiple(
            rn,
            list,
            start,
            if w { Some(new_base) } else { None },
            pc.wrapping_add(8),
        )
    }
}

/// The media instructions (bits 27:25 011, 4 1)
fn a32_media(word: u32) -> Result<Flow, Exception> {
    let op1 = word >> 20 & 31;
    let op2 = word >> 5 & 7;
    let rn = word >> 16 & 15;
    let rd = word >> 12 & 15;
    let rs = word >> 8 & 15;
    let rm = word & 15;
    match op1 >> 3 {
        0 => {
            // parallel addition and subtraction: op1 bits 2:0 the kind, op2 the operation
            let kind = op1 & 7;
            if kind & 3 == 0 || op2 == 5 || op2 == 6 || rd == 15 || rn == 15 || rm == 15 {
                return Err(Exception::Undefined);
            }
            parallel(kind, op2, rd, reg(rn), reg(rm))
        },
        1 => {
            // packing, unpacking, saturation, reversal
            let rotation = 8 * (word >> 10 & 3);
            let addend = if rn == 15 { None } else { Some(reg(rn)) };
            match (op1 & 7, op2) {
                (0, 0) | (0, 2) | (0, 4) | (0, 6) => {
                    pack(rd, reg(rn), reg(rm), word & 1 << 6 != 0, word >> 7 & 31)
                },
                (0, 3) => extend(rd, addend, reg(rm), rotation, 8, true, true),
                (0, 5) => select(rd, reg(rn), reg(rm)),
                (2, 1) => saturate16(rd, reg(rm), rn + 1, false),
                (2, 3) => extend(rd, addend, reg(rm), rotation, 8, true, false),
                (3, 1) => bit_op(0, rd, reg(rm)),
                (3, 3) => extend(rd, addend, reg(rm), rotation, 16, true, false),
                (3, 5) => bit_op(1, rd, reg(rm)),
                (4, 3) => extend(rd, addend, reg(rm), rotation, 8, false, true),
                (6, 1) => saturate16(rd, reg(rm), rn, true),
                (6, 3) => extend(rd, addend, reg(rm), rotation, 8, false, false),
                (7, 1) => bit_op(3, rd, reg(rm)),
                (7, 3) => extend(rd, addend, reg(rm), rotation, 16, false, false),
                (7, 5) => bit_op(2, rd, reg(rm)),
                // SSAT, USAT (bit 5 0): Rn shifted by LSL or ASR (bit 6)
                (2 | 3 | 6 | 7, 0 | 2 | 4 | 6) => {
                    let (kind, amount) = decode_imm_shift(word >> 5 & 2, word >> 7 & 31);
                    let value = shift_c(reg(rm), kind, amount, false).0;
                    let unsigned = op1 & 4 != 0;
                    let bits = (word >> 16 & 31) + if unsigned { 0 } else { 1 };
                    saturate(rd, value, bits, unsigned)
                },
                _ => Err(Exception::Undefined),
            }
        },
        2 => {
            // signed multiplies and divides: Rd bits 19:16, Ra 15:12, Rm 11:8, Rn 3:0
            let (rd, ra, rm, rn) = (word >> 16 & 15, word >> 12 & 15, word >> 8 & 15, word & 15);
            let swap = word & 1 << 5 != 0;
            match (op1 & 7, op2 >> 1) {
                (0, 0) => multiply_dual(rd, ra, reg(rn), reg(rm), false, swap, false),
                (0, 1) => multiply_dual(rd, ra, reg(rn), reg(rm), true, swap, false),
                (1, 0) if op2 == 0 && ra == 15 => divide(rd, reg(rn), reg(rm), true),
                (3, 0) if op2 == 0 && ra == 15 => divide(rd, reg(rn), reg(rm), false),
                (4, 0) => multiply_dual(rd, ra, reg(rn), reg(rm), false, swap, true),
                (4, 1) => multiply_dual(rd, ra, reg(rn), reg(rm), true, swap, true),
                (5, 0) => multiply_most(rd, ra, reg(rn), reg(rm), false, swap),
                (5, 3) if ra != 15 => multiply_most(rd, ra, reg(rn), reg(rm), true, swap),
                _ => Err(Exception::Undefined),
            }
        },
        _ => {
            let lsb = word >> 7 & 31;
            let width_bits = word >> 16 & 31;
            if op1 == 0b11000 && op2 == 0 {
                // USAD8, USADA8: Rd 19:16, Ra 15:12, Rm 11:8, Rn 3:0
                return sum_absolute(word >> 16 & 15, rd, reg(rm), reg(rs));
            }
            match (op1 & 6, op2 & 3) {
                (2, 2) => bitfield_extract(rd, reg(rm), lsb, width_bits + 1, true),
                (4, 0) => bitfield_insert(
                    rd,
                    if rm == 15 { None } else { Some(reg(rm)) },
                    lsb,
                    width_bits,
                ),
                (6, 2) => bitfield_extract(rd, reg(rm), lsb, width_bits + 1, false),
                _ => Err(Exception::Undefined),
            }
        },
    }
}

/// The coprocessor space (bits 27:25 110, 111 but SVC): VFP (coprocessors
/// 10, 11), MCR, MRC, MCRR, MRRC of CP15; CP14 and the rest UNDEFINED
fn a32_coprocessor(word: u32, pc: u32, cp: u32, cond: u32) -> Result<Flow, Exception> {
    if cp == 10 || cp == 11 {
        return crate::aarch64::a32_fp::vfp(word, pc.wrapping_add(8), false);
    }
    if cp == 14 && word >> 24 & 15 == 0b1110 && word & 1 << 4 != 0 {
        return crate::aarch64::a32_system::cp14(word & 1 << 20 != 0, word >> 12 & 15);
    }
    if cp != 15 {
        return Err(Exception::Undefined);
    }
    let rt = word >> 12 & 15;
    if word >> 24 & 15 == 0b1110 && word & 1 << 4 != 0 {
        if rt == 15 {
            return Err(Exception::Undefined);
        }
        let read = word & 1 << 20 != 0;
        return cp15(
            read,
            word >> 21 & 7,
            word >> 16 & 15,
            word & 15,
            word >> 5 & 7,
            rt,
            reg(rt),
            cond,
        );
    }
    if word >> 21 & 0x7F == 0b1100010 {
        let rt2 = word >> 16 & 15;
        if rt == 15 || rt2 == 15 {
            return Err(Exception::Undefined);
        }
        let read = word & 1 << 20 != 0;
        let value = (reg(rt2) as u64) << 32 | reg(rt) as u64;
        return cp15_64(read, word >> 4 & 15, word & 15, rt, rt2, value, cond);
    }
    Err(Exception::Undefined)
}

/// A32's unconditional space (cond 0b1111): barriers, CLREX, preloads,
/// BLX (immediate), Advanced SIMD, ARMv8's VFP additions; the rest
/// UNDEFINED (SETEND, CPS, SRS, RFE at EL0)
fn a32_unconditional(word: u32, pc: u32) -> Result<Flow, Exception> {
    if word >> 25 == 0b1111001 {
        return crate::aarch64::a32_simd::data_processing(word);
    }
    if word & 0xFF10_0000 == 0xF400_0000 {
        return crate::aarch64::a32_simd::load_store(word);
    }
    if word >> 24 == 0xFE {
        return crate::aarch64::a32_fp::vfp_unconditional(word);
    }
    // BLX (immediate): to T32, imm24:H:0 from the PC + 8
    if word >> 25 & 7 == 0b101 {
        let offset = ((word << 8) as i32 >> 6) as u32 | (word >> 23 & 2);
        set_reg(14, pc.wrapping_add(4));
        set_pstate_bits(PSTATE_T, PSTATE_T);
        return Ok(Flow::Jump(pc.wrapping_add(8).wrapping_add(offset) as u64));
    }
    if word == 0xF57F_F01F {
        return clear_exclusive();
    }
    // CPS (a NOP in User mode), SRS, RFE: PL1's (cpu_type arm32)
    if word & 0xFFF1_FE20 == 0xF100_0000 && a32_only() {
        crate::aarch64::a32_system::cps(
            word >> 18 & 3,
            word >> 6 & 7,
            word & 1 << 17 != 0,
            word & 31,
        );
        return Ok(Flow::Next);
    }
    if crate::aarch64::a32_system::privileged() {
        // (P bit 24, U 23, W 21)
        if word & 0xFE5F_FFE0 == 0xF84D_0500 {
            return crate::aarch64::a32_system::srs(
                word >> 24 & 1 != 0,
                word >> 23 & 1 != 0,
                word >> 21 & 1 != 0,
                word & 31,
            );
        }
        if word & 0xFE50_FFFF == 0xF810_0A00 {
            return crate::aarch64::a32_system::rfe(
                word >> 24 & 1 != 0,
                word >> 23 & 1 != 0,
                word >> 21 & 1 != 0,
                word >> 16 & 15,
            );
        }
    }
    if word & 0xFFFF_FF00 == 0xF57F_F000 {
        return match word >> 4 & 15 {
            4 => barrier(true),
            5 | 6 => barrier(false),
            // (SB: not in the profile)
            _ => Err(Exception::Undefined),
        };
    }
    // PLD, PLDW, PLI (immediate, register): hints
    if word & 0xFF30_F000 == 0xF510_F000
        || word & 0xFF30_F010 == 0xF710_F000
        || word & 0xFF70_F000 == 0xF450_F000
        || word & 0xFF70_F010 == 0xF650_F000
    {
        return Ok(Flow::Next);
    }
    Err(Exception::Undefined)
}

/// (tests) the instruction set the core runs: 0 A64, 1 A32, 2 T32
#[no_mangle]
pub fn a64_instruction_set() -> u32 {
    if !aarch32() {
        0
    }
    else if thumb() {
        2
    }
    else {
        1
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/rust/aarch64/a32_fp.rs                                                               0000644 0000000 0000000 00000062063 00000000000 014327  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AArch32's floating point at EL0 (docs/aarch32-plan.md Q4.1, Q4.4):
//! VFPv4 as ARMv8 has it (no short vectors, no half-precision arithmetic),
//! on fp.rs's SoftFloat environment. S0-S31, D0-D31 and Q0-Q15 are views
//! of V0-V15 (S n: bits 32(n%4) of V n/4; D n: half n%2 of V n/2), and an
//! AArch32 write leaves the rest of the V register as it was. FPSCR is
//! FPSR's NZCV, QC and cumulative flags with FPCR's AHP, DN, FZ and RMode;
//! Len and Stride read as zero and are ignored (as FPCR's), the trap
//! enables are RAZ/WI. At EL0 VMRS and VMSR reach FPSCR alone, the ID
//! registers and FPEXC are UNDEFINED. CPACR_EL1.FPEN traps (EC 0x07, CV 1
//! and COND 0xE, as A64's FP trap); FPEXC.EN is FPEXC32_EL2's, which needs
//! an EL2, so it never applies.
//!
//! The decoders take the instruction as A32 encodes it (T32's VFP space is
//! A32's with the condition 0b1110), the condition already passed.

use crate::aarch64::a32::{condition_passed, reg, set_reg};
use crate::aarch64::cpu::*;
use crate::aarch64::execute::{self, Flow};
use crate::aarch64::fp::{self, Arith, Format, Fp, F32, F64};
use crate::aarch64::memory::{self, Syndrome};
use crate::aarch64::simd::{set_vreg, vreg};
use crate::aarch64::state::{fpcr, fpsr};

// ---- the registers

/// S[n]: bits 32(n%4) of V[n/4]
#[inline(always)]
pub fn sreg(n: u32) -> u32 { (vreg(n >> 2) >> (32 * (n & 3))) as u32 }

#[inline(always)]
pub fn set_sreg(n: u32, value: u32) {
    let shift = 32 * (n & 3);
    let v = vreg(n >> 2) & !(0xFFFF_FFFFu128 << shift);
    set_vreg(n >> 2, v | (value as u128) << shift)
}

/// D[n]: half n%2 of V[n/2]
#[inline(always)]
pub fn dreg(n: u32) -> u64 { (vreg(n >> 1) >> (64 * (n & 1))) as u64 }

#[inline(always)]
pub fn set_dreg(n: u32, value: u64) {
    let shift = 64 * (n & 1);
    let v = vreg(n >> 1) & !((u64::MAX as u128) << shift);
    set_vreg(n >> 1, v | (value as u128) << shift)
}

/// FPSR's bits FPSCR has: NZCV, QC, the cumulative flags
const FPSR_KEPT: u32 = 0xF800_009F;

pub fn fpscr() -> u32 { unsafe { *fpsr & FPSR_KEPT | *fpcr & fp::FPCR_WRITABLE } }

pub fn set_fpscr(value: u32) {
    unsafe {
        *fpsr = value & FPSR_KEPT;
        *fpcr = value & fp::FPCR_WRITABLE;
    }
}

/// A single-precision register number (Vx:bit), or a double's (bit:Vx)
#[inline(always)]
fn number(v: u32, bit: u32, double: bool) -> u32 {
    if double {
        bit << 4 | v
    }
    else {
        v << 1 | bit
    }
}
#[inline(always)]
fn vd(word: u32, double: bool) -> u32 { number(word >> 12 & 15, word >> 22 & 1, double) }
#[inline(always)]
fn vn(word: u32, double: bool) -> u32 { number(word >> 16 & 15, word >> 7 & 1, double) }
#[inline(always)]
fn vm(word: u32, double: bool) -> u32 { number(word & 15, word >> 5 & 1, double) }

/// Read an S (`double` false) or D register
#[inline(always)]
fn read(n: u32, double: bool) -> u64 {
    if double {
        dreg(n)
    }
    else {
        sreg(n) as u64
    }
}
#[inline(always)]
fn write(n: u32, double: bool, value: u64) {
    if double {
        set_dreg(n, value)
    }
    else {
        set_sreg(n, value as u32)
    }
}

/// The SoftFloat rounding mode of FPSCR.RMode
#[inline(always)]
fn fpscr_rounding() -> u8 { fp::rounding_of(unsafe { *fpcr } >> 22) }

/// FPDecodeRM: VRINT{A,N,P,M} and VCVT{A,N,P,M}'s rounding modes
const DECODE_RM: [u8; 4] = [
    fp::ROUND_NEAR_MAX_MAG,
    fp::ROUND_NEAR_EVEN,
    fp::ROUND_MAX,
    fp::ROUND_MIN,
];

// ---- the coprocessor space of coprocessors 10 and 11

/// A VFP instruction (bits 27:25 110 or 111, bits 11:9 101): `pc` the PC
/// as the instruction set reads it (A32's + 8, T32's + 4)
pub fn vfp(word: u32, pc: u32, thumb: bool) -> Result<Flow, Exception> {
    match word >> 24 & 15 {
        0b1110 => {
            if word & 1 << 4 == 0 {
                data_processing(word)
            }
            else {
                transfer(word, thumb)
            }
        },
        0b1100 | 0b1101 => {
            if word >> 21 & 0x7F == 0b1100010 {
                transfer_64(word, thumb)
            }
            else {
                load_store(word, pc, thumb)
            }
        },
        _ => Err(Exception::Undefined),
    }
}

#[derive(Clone, Copy)]
enum Three {
    Mla,
    Mls,
    Nmla,
    Nmls,
    Mul,
    Nmul,
    Add,
    Sub,
    Div,
    Fma,
    Fms,
    Fnma,
    Fnms,
    MaxNm,
    MinNm,
}

/// The data processing instructions (bits 27:24 1110, bit 4 0)
fn data_processing(word: u32) -> Result<Flow, Exception> {
    let op = word >> 6 & 1 != 0;
    let three = match word >> 20 & 0b1011 {
        0b0000 => [Three::Mla, Three::Mls][op as usize],
        0b0001 => [Three::Nmls, Three::Nmla][op as usize],
        0b0010 => [Three::Mul, Three::Nmul][op as usize],
        0b0011 => [Three::Add, Three::Sub][op as usize],
        0b1000 if !op => Three::Div,
        0b1001 => [Three::Fnms, Three::Fnma][op as usize],
        0b1010 => [Three::Fma, Three::Fms][op as usize],
        0b1011 => return other(word),
        _ => return Err(Exception::Undefined),
    };
    three_operands(word, three)
}

fn three_operands(word: u32, op: Three) -> Result<Flow, Exception> {
    fp::check_access()?;
    let double = word & 1 << 8 != 0;
    let (d, n, m) = (vd(word, double), vn(word, double), vm(word, double));
    let (a, b, c) = (read(d, double), read(n, double), read(m, double));
    let r = if double { three_op::<F64>(op, a, b, c) } else { three_op::<F32>(op, a, b, c) };
    write(d, double, r);
    Ok(Flow::Next)
}

/// The operation on D, N, M (FPNeg flips the sign, a NaN's too)
fn three_op<T: Format>(op: Three, d: u64, n: u64, m: u64) -> u64 {
    let mut fp = Fp::new();
    let neg = |v: u64| v ^ T::SIGN;
    let r = match op {
        Three::Mla => {
            let product = fp.arith::<T>(Arith::Mul, n, m);
            fp.arith::<T>(Arith::Add, d, product)
        },
        Three::Mls => {
            let product = fp.arith::<T>(Arith::Mul, n, m);
            fp.arith::<T>(Arith::Add, d, neg(product))
        },
        Three::Nmla => {
            let product = fp.arith::<T>(Arith::Mul, n, m);
            fp.arith::<T>(Arith::Add, neg(d), neg(product))
        },
        Three::Nmls => {
            let product = fp.arith::<T>(Arith::Mul, n, m);
            fp.arith::<T>(Arith::Add, neg(d), product)
        },
        Three::Mul => fp.arith::<T>(Arith::Mul, n, m),
        Three::Nmul => neg(fp.arith::<T>(Arith::Mul, n, m)),
        Three::Add => fp.arith::<T>(Arith::Add, n, m),
        Three::Sub => fp.arith::<T>(Arith::Sub, n, m),
        Three::Div => fp.arith::<T>(Arith::Div, n, m),
        Three::Fma => fp.mul_add::<T>(d, n, m),
        Three::Fms => fp.mul_add::<T>(d, neg(n), m),
        Three::Fnma => fp.mul_add::<T>(neg(d), neg(n), m),
        Three::Fnms => fp.mul_add::<T>(neg(d), n, m),
        Three::MaxNm => fp.max_min::<T>(n, m, true, true),
        Three::MinNm => fp.max_min::<T>(n, m, false, true),
    };
    fp.finish();
    r
}

/// The two-register and immediate forms (opc1 1x11): VMOV, VABS, VNEG,
/// VSQRT, VCVTB/VCVTT, VCMP(E), VRINTR/Z/X, the conversions
fn other(word: u32) -> Result<Flow, Exception> {
    let double = word & 1 << 8 != 0;
    let opc2 = word >> 16 & 15;
    let bit7 = word >> 7 & 1 != 0;
    if word & 1 << 6 == 0 {
        // VMOV (immediate): bits 7:4 0000
        if word >> 4 & 15 != 0 {
            return Err(Exception::Undefined);
        }
        fp::check_access()?;
        let imm8 = opc2 << 4 | word & 15;
        write(
            vd(word, double),
            double,
            fp::expand_imm(imm8, if double { 64 } else { 32 }),
        );
        return Ok(Flow::Next);
    }
    match opc2 {
        0b0000 | 0b0001 => {
            fp::check_access()?;
            let (d, m) = (vd(word, double), vm(word, double));
            let x = read(m, double);
            let sign = if double { F64::SIGN } else { F32::SIGN };
            let r = match (opc2, bit7) {
                (0, false) => x,
                (0, true) => x & !sign,
                (_, false) => x ^ sign,
                (_, true) => {
                    let mut fp = Fp::new();
                    let r = if double { fp.sqrt::<F64>(x) } else { fp.sqrt::<F32>(x) };
                    fp.finish();
                    r
                },
            };
            write(d, double, r);
            Ok(Flow::Next)
        },
        0b0010 => {
            // VCVTB, VCVTT from half precision (to single, or double)
            fp::check_access()?;
            let h = (sreg(vm(word, false)) >> (16 * bit7 as u32)) as u16;
            let mut fp = Fp::new();
            let r = fp.from_half(h, if double { 64 } else { 32 });
            fp.finish();
            write(vd(word, double), double, r);
            Ok(Flow::Next)
        },
        0b0011 => {
            // VCVTB, VCVTT to half precision, into a half of Sd
            fp::check_access()?;
            let x = read(vm(word, double), double);
            let mut fp = Fp::new();
            let h = fp.to_half(x, if double { 64 } else { 32 });
            fp.finish();
            let d = vd(word, false);
            let shift = 16 * bit7 as u32;
            set_sreg(d, sreg(d) & !(0xFFFF << shift) | (h as u32) << shift);
            Ok(Flow::Next)
        },
        0b0100 | 0b0101 => {
            // VCMP, VCMPE (bit 16: with zero, Vm and M zero)
            let (d, m) = (vd(word, double), vm(word, double));
            let zero = opc2 & 1 != 0;
            if zero && m != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let a = read(d, double);
            let b = if zero { 0 } else { read(m, double) };
            let mut fp = Fp::new();
            let nzcv =
                if double { fp.compare::<F64>(a, b, bit7) } else { fp.compare::<F32>(a, b, bit7) };
            fp.finish();
            unsafe { *fpsr = *fpsr & 0x0FFF_FFFF | nzcv };
            Ok(Flow::Next)
        },
        0b0110 | 0b0111 if !(opc2 == 0b0111 && bit7) => {
            // VRINTR (FPSCR's mode), VRINTZ (to zero), VRINTX (FPSCR's, exact)
            fp::check_access()?;
            let (d, m) = (vd(word, double), vm(word, double));
            let (mode, exact) = match (opc2, bit7) {
                (0b0110, false) => (fpscr_rounding(), false),
                (0b0110, true) => (fp::ROUND_MIN_MAG, false),
                _ => (fpscr_rounding(), true),
            };
            let x = read(m, double);
            let mut fp = Fp::new();
            let r = if double {
                fp.round_to_int::<F64>(x, mode, exact)
            }
            else {
                fp.round_to_int::<F32>(x, mode, exact)
            };
            fp.finish();
            write(d, double, r);
            Ok(Flow::Next)
        },
        0b0111 => {
            // VCVT between single and double (cp10: single to double)
            fp::check_access()?;
            let mut fp = Fp::new();
            if double {
                let r = fp.double_to_single(dreg(vm(word, true)), false);
                set_sreg(vd(word, false), r);
            }
            else {
                let r = fp.single_to_double(sreg(vm(word, false)));
                set_dreg(vd(word, true), r);
            }
            fp.finish();
            Ok(Flow::Next)
        },
        0b1000 => {
            // VCVT from a 32-bit integer in Sm (bit 7: signed)
            fp::check_access()?;
            let x = sreg(vm(word, false)) as u64;
            let mut fp = Fp::new();
            let r = if double {
                fp.from_integer::<F64>(x, bit7, 32, 0)
            }
            else {
                fp.from_integer::<F32>(x, bit7, 32, 0)
            };
            fp.finish();
            write(vd(word, double), double, r);
            Ok(Flow::Next)
        },
        0b1010 | 0b1011 | 0b1110 | 0b1111 => convert_fixed(word, double),
        0b1100 | 0b1101 => {
            // VCVT, VCVTR to a 32-bit integer in Sd (bit 16: signed; bit 7: toward zero)
            fp::check_access()?;
            let x = read(vm(word, double), double);
            let signed = opc2 & 1 != 0;
            let mode = if bit7 { fp::ROUND_MIN_MAG } else { fpscr_rounding() };
            let mut fp = Fp::new();
            let r = if double {
                fp.to_integer::<F64>(x, signed, 32, 0, mode)
            }
            else {
                fp.to_integer::<F32>(x, signed, 32, 0, mode)
            };
            fp.finish();
            set_sreg(vd(word, false), r as u32);
            Ok(Flow::Next)
        },
        // (VJCVT: not in the profile)
        _ => Err(Exception::Undefined),
    }
}

/// VCVT between floating point and fixed point, in place: bit 18 to fixed
/// (rounding toward zero; from fixed: to nearest), bit 16 unsigned, bit 7
/// a 32-bit integer (else 16), the fraction bits size - imm4:i
fn convert_fixed(word: u32, double: bool) -> Result<Flow, Exception> {
    let to_fixed = word & 1 << 18 != 0;
    let unsigned = word & 1 << 16 != 0;
    let size = if word & 1 << 7 != 0 { 32 } else { 16 };
    let imm = (word & 15) << 1 | word >> 5 & 1;
    if imm > size {
        // (fewer than zero fraction bits: UNPREDICTABLE)
        return Err(Exception::Undefined);
    }
    let fbits = size - imm;
    fp::check_access()?;
    let d = vd(word, double);
    let x = read(d, double);
    let r = if to_fixed {
        let mut fp = Fp::new();
        let r = match (double, size) {
            (false, 32) => fp.to_integer::<F32>(x, !unsigned, 32, fbits, fp::ROUND_MIN_MAG),
            (true, 32) => fp.to_integer::<F64>(x, !unsigned, 32, fbits, fp::ROUND_MIN_MAG),
            (false, _) => fp.to_integer16::<F32>(x, !unsigned, fbits, fp::ROUND_MIN_MAG),
            (true, _) => fp.to_integer16::<F64>(x, !unsigned, fbits, fp::ROUND_MIN_MAG),
        };
        fp.finish();
        // (extended to the register by the signedness)
        let r = r & (u64::MAX >> (64 - size));
        if unsigned {
            r
        }
        else {
            ((r << (64 - size)) as i64 >> (64 - size)) as u64
        }
    }
    else {
        let low = x & (u64::MAX >> (64 - size));
        let value =
            if unsigned { low } else { ((low << (64 - size)) as i64 >> (64 - size)) as u64 };
        let mut fp = Fp::with(unsafe { *fpcr } & !(3 << 22));
        let r = if double {
            fp.from_integer::<F64>(value, !unsigned, 32, fbits)
        }
        else {
            fp.from_integer::<F32>(value, !unsigned, 32, fbits)
        };
        fp.finish();
        r
    };
    let r = if double { r } else { r & 0xFFFF_FFFF };
    write(d, double, r);
    Ok(Flow::Next)
}

/// The transfers between core and extension registers (bits 27:24 1110,
/// bit 4 1): VMOV (core, single), VMRS, VMSR; VMOV (scalar), VDUP (core)
fn transfer(word: u32, thumb: bool) -> Result<Flow, Exception> {
    let rt = word >> 12 & 15;
    let bad_rt = rt == 15 || (thumb && rt == 13);
    let to_core = word & 1 << 20 != 0;
    if word & 1 << 8 == 0 {
        if word >> 21 & 7 == 0 && word & 0x7F == 0x10 {
            // VMOV between a core register and S
            if bad_rt {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let n = vn(word, false);
            if to_core {
                set_reg(rt, sreg(n));
            }
            else {
                set_sreg(n, reg(rt));
            }
            return Ok(Flow::Next);
        }
        if word >> 21 & 7 == 7 && word & 0xFF == 0x10 {
            return special_register(word >> 16 & 15, rt, to_core, thumb);
        }
        return Err(Exception::Undefined);
    }
    if word & 15 != 0 || bad_rt {
        return Err(Exception::Undefined);
    }
    let n = vn(word, true);
    let unsigned = word & 1 << 23 != 0;
    if !to_core && unsigned {
        // VDUP (core): bit 22 bytes, bit 5 halfwords, else words; bit 21 Q
        let (b, q, e) = (word >> 22 & 1, word >> 21 & 1, word >> 5 & 1);
        if word & 1 << 6 != 0 || (b == 1 && e == 1) || (q == 1 && n & 1 != 0) {
            return Err(Exception::Undefined);
        }
        fp::check_access()?;
        let value = reg(rt);
        let d = if b == 1 {
            (value & 0xFF) as u64 * 0x0101_0101_0101_0101
        }
        else if e == 1 {
            (value & 0xFFFF) as u64 * 0x0001_0001_0001_0001
        }
        else {
            value as u64 * 0x0000_0001_0000_0001
        };
        set_dreg(n, d);
        if q == 1 {
            set_dreg(n + 1, d);
        }
        return Ok(Flow::Next);
    }
    // VMOV (scalar to core: bit 23 unsigned; core to scalar)
    let (esize, index) = if word & 1 << 22 != 0 {
        (8, (word >> 21 & 1) << 2 | (word >> 5 & 3))
    }
    else if word & 1 << 5 != 0 {
        (16, (word >> 21 & 1) << 1 | (word >> 6 & 1))
    }
    else if word & 1 << 6 == 0 && !unsigned {
        (32, word >> 21 & 1)
    }
    else {
        return Err(Exception::Undefined);
    };
    fp::check_access()?;
    let shift = esize * index;
    let mask = u64::MAX >> (64 - esize);
    if to_core {
        let element = dreg(n) >> shift & mask;
        let value = if unsigned || esize == 32 {
            element
        }
        else {
            ((element << (64 - esize)) as i64 >> (64 - esize)) as u64
        };
        set_reg(rt, value as u32);
    }
    else {
        let element = reg(rt) as u64 & mask;
        set_dreg(n, dreg(n) & !(mask << shift) | element << shift);
    }
    Ok(Flow::Next)
}

/// VMRS, VMSR at EL0: FPSCR (VMRS to the PC: APSR_nzcv from FPSCR's)
fn special_register(register: u32, rt: u32, to_core: bool, thumb: bool) -> Result<Flow, Exception> {
    if register != 1 && crate::aarch64::a32_system::privileged() && !(thumb && rt == 13) {
        // (PL1's: FPSID, MVFR0-2, FPEXC)
        return crate::aarch64::a32_system::vfp_system(register, rt, to_core);
    }
    if register != 1 || (thumb && rt == 13) || (!to_core && rt == 15) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    if !to_core {
        set_fpscr(reg(rt));
    }
    else if rt == 15 {
        set_nzcv(unsafe { *fpsr } & 0xF000_0000);
    }
    else {
        set_reg(rt, fpscr());
    }
    Ok(Flow::Next)
}

/// VMOV between two core registers and two S registers (Sm, Sm+1) or a D register
fn transfer_64(word: u32, thumb: bool) -> Result<Flow, Exception> {
    let (rt, rt2) = (word >> 12 & 15, word >> 16 & 15);
    let to_core = word & 1 << 20 != 0;
    let double = word & 1 << 8 != 0;
    let m = vm(word, double);
    let bad = |r: u32| r == 15 || (thumb && r == 13);
    if word >> 6 & 3 != 0
        || word & 1 << 4 == 0
        || bad(rt)
        || bad(rt2)
        || (to_core && rt == rt2)
        || (!double && m == 31)
    {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    match (double, to_core) {
        (true, true) => {
            let value = dreg(m);
            set_reg(rt, value as u32);
            set_reg(rt2, (value >> 32) as u32);
        },
        (true, false) => set_dreg(m, (reg(rt2) as u64) << 32 | reg(rt) as u64),
        (false, true) => {
            let (low, high) = (sreg(m), sreg(m + 1));
            set_reg(rt, low);
            set_reg(rt2, high);
        },
        (false, false) => {
            set_sreg(m, reg(rt));
            set_sreg(m + 1, reg(rt2));
        },
    }
    Ok(Flow::Next)
}

/// An aligned word of a VFP load (MemA; no ISS)
fn load_word(address: u32) -> Result<u32, Exception> {
    if address & 3 != 0 {
        return Err(execute::alignment(address as u64, false, Syndrome::NONE));
    }
    Ok(memory::read(address as u64, 4, false, Syndrome::NONE)? as u32)
}

fn prepare_word(address: u32) -> Result<memory::Store, Exception> {
    if address & 3 != 0 {
        return Err(execute::alignment(address as u64, true, Syndrome::NONE));
    }
    memory::prepare_write(address as u64, 4, false, Syndrome::NONE)
}

/// VLDR, VSTR, VLDM, VSTM (VPUSH, VPOP; FLDMX, FSTMX: an odd imm8 of
/// doubles); the base the PC aligned (literal). Words, each aligned: a
/// double is two, low first. Nothing is written if any access faults.
fn load_store(word: u32, pc: u32, thumb: bool) -> Result<Flow, Exception> {
    let double = word & 1 << 8 != 0;
    let (p, u, w) = (
        word >> 24 & 1 != 0,
        word >> 23 & 1 != 0,
        word >> 21 & 1 != 0,
    );
    let load = word & 1 << 20 != 0;
    let rn = word >> 16 & 15;
    let imm8 = word & 0xFF;
    let d = vd(word, double);
    let base = if rn == 15 { pc & !3 } else { reg(rn) };
    let words_per = if double { 2 } else { 1 };
    let (first, count, writeback) = if p && !w {
        // VLDR, VSTR (T32's VSTR of the PC: UNPREDICTABLE)
        if rn == 15 && thumb && !load {
            return Err(Exception::Undefined);
        }
        let offset = imm8 << 2;
        let address = if u { base.wrapping_add(offset) } else { base.wrapping_sub(offset) };
        (address, 1, None)
    }
    else if p != u && (u || w) {
        // VLDM, VSTM: increment after, or decrement before with writeback
        let regs = if double { imm8 >> 1 } else { imm8 };
        if regs == 0 || d + regs > 32 || (double && regs > 16) || (rn == 15 && (w || thumb)) {
            return Err(Exception::Undefined);
        }
        let size = imm8 << 2;
        let first = if p { base.wrapping_sub(size) } else { base };
        let new_base = if u { base.wrapping_add(size) } else { base.wrapping_sub(size) };
        (first, regs, if w { Some(new_base) } else { None })
    }
    else {
        return Err(Exception::Undefined);
    };
    fp::check_access()?;
    if load {
        let mut values = [0u64; 32];
        let mut address = first;
        for value in values.iter_mut().take(count as usize) {
            let low = load_word(address)? as u64;
            *value =
                if double { low | (load_word(address.wrapping_add(4))? as u64) << 32 } else { low };
            address = address.wrapping_add(4 * words_per);
        }
        if let Some(new_base) = writeback {
            set_reg(rn, new_base);
        }
        for (i, value) in values.iter().take(count as usize).enumerate() {
            write(d + i as u32, double, *value);
        }
    }
    else {
        let mut stores: [Option<(memory::Store, u32)>; 64] = [None; 64];
        let mut address = first;
        for i in 0..count {
            let value = read(d + i, double);
            for half in 0..words_per {
                let slot = (i * words_per + half) as usize;
                stores[slot] = Some((prepare_word(address)?, (value >> (32 * half)) as u32));
                address = address.wrapping_add(4);
            }
        }
        for store in stores.into_iter().flatten() {
            store.0.commit(store.1 as u64)?;
        }
        if let Some(new_base) = writeback {
            set_reg(rn, new_base);
        }
    }
    Ok(Flow::Next)
}

// ---- the unconditional space: ARMv8's additions

/// VSEL, VMAXNM, VMINNM, VRINT{A,N,P,M}, VCVT{A,N,P,M} (A32 and T32: 1111
/// 1110, bits 11:9 101, bit 4 0)
pub fn vfp_unconditional(word: u32) -> Result<Flow, Exception> {
    if word >> 24 != 0xFE || word >> 9 & 7 != 0b101 || word & 1 << 4 != 0 {
        return Err(Exception::Undefined);
    }
    let double = word & 1 << 8 != 0;
    if word & 1 << 23 == 0 {
        // VSEL: EQ, VS, GE, GT on APSR
        if word & 1 << 6 != 0 {
            return Err(Exception::Undefined);
        }
        fp::check_access()?;
        let cond = [0b0000, 0b0110, 0b1010, 0b1100][(word >> 20 & 3) as usize];
        let (d, n, m) = (vd(word, double), vn(word, double), vm(word, double));
        let source = if condition_passed(cond) { n } else { m };
        write(d, double, read(source, double));
        return Ok(Flow::Next);
    }
    match word >> 20 & 0b1011 {
        0b1000 => three_operands(
            word,
            if word & 1 << 6 != 0 { Three::MinNm } else { Three::MaxNm },
        ),
        0b1011 => {
            let mode = DECODE_RM[(word >> 16 & 3) as usize];
            match word >> 18 & 3 {
                0b10 if word >> 6 & 3 == 0b01 => {
                    // VRINT{A,N,P,M}
                    fp::check_access()?;
                    let x = read(vm(word, double), double);
                    let mut fp = Fp::new();
                    let r = if double {
                        fp.round_to_int::<F64>(x, mode, false)
                    }
                    else {
                        fp.round_to_int::<F32>(x, mode, false)
                    };
                    fp.finish();
                    write(vd(word, double), double, r);
                    Ok(Flow::Next)
                },
                0b11 if word & 1 << 6 != 0 => {
                    // VCVT{A,N,P,M} to a 32-bit integer in Sd (bit 7 signed)
                    fp::check_access()?;
                    let x = read(vm(word, double), double);
                    let signed = word & 1 << 7 != 0;
                    let mut fp = Fp::new();
                    let r = if double {
                        fp.to_integer::<F64>(x, signed, 32, 0, mode)
                    }
                    else {
                        fp.to_integer::<F32>(x, signed, 32, 0, mode)
                    };
                    fp.finish();
                    set_sreg(vd(word, false), r as u32);
                    Ok(Flow::Next)
                },
                // (VMOVX, VINS: half precision, not in the profile)
                _ => Err(Exception::Undefined),
            }
        },
        _ => Err(Exception::Undefined),
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/rust/aarch64/a32_simd.rs                                                             0000644 0000000 0000000 00000153740 00000000000 014661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AArch32's Advanced SIMD at EL0 (docs/aarch32-plan.md Q4.2, Q4.3): the
//! data processing groups as QEMU's neon-dp.decode divides them (three
//! registers of the same length, of different lengths, two and a scalar,
//! two and a shift amount, one and a modified immediate, VEXT, VTBL and
//! VTBX, VDUP (scalar), two registers miscellaneous), the element and
//! structure loads and stores, and the crypto instructions (AES, SHA-1,
//! SHA-256, VMULL.P64). A D register is a half of V0-V15 (a32_fp.rs), a Q
//! register an even D and the next. Floating point runs on the standard
//! FPSCR value (FZ, DN, round to nearest, FPSCR's AHP) with its flags into
//! FPSCR; saturation sets FPSCR.QC. Half precision arithmetic, RDM, the
//! dot products and BF16 are not in the profile (UNDEFINED); so are the
//! UNPREDICTABLE encodings QEMU's decoder rejects and those it takes in a
//! way of its own (registers past D31, the PC as a base).
//!
//! The decoders take A32's encodings (T32's: a32.rs and t32.rs map them),
//! the instruction's condition (T32's IT block) already passed.

use crate::aarch64::a32::reg;
use crate::aarch64::a32::set_reg;
use crate::aarch64::a32_fp::{dreg, set_dreg};
use crate::aarch64::cpu::*;
use crate::aarch64::crypto;
use crate::aarch64::execute::{self, Flow};
use crate::aarch64::fp::{self, is_inf, is_zero, Arith, Format, Fp, F32};
use crate::aarch64::memory::{self, Syndrome};
use crate::aarch64::simd::{self, elem, ones, sat, set_qc, sext, with_elem};
use crate::aarch64::state::fpcr;

// ---- registers and elements

#[inline(always)]
fn d_of(word: u32) -> u32 { (word >> 22 & 1) << 4 | (word >> 12 & 15) }
#[inline(always)]
fn n_of(word: u32) -> u32 { (word >> 7 & 1) << 4 | (word >> 16 & 15) }
#[inline(always)]
fn m_of(word: u32) -> u32 { (word >> 5 & 1) << 4 | (word & 15) }

/// D[n] (`q` false) or Q[n/2] (n even)
#[inline(always)]
fn read_vec(n: u32, q: bool) -> u128 {
    if q {
        dreg(n) as u128 | (dreg(n + 1) as u128) << 64
    }
    else {
        dreg(n) as u128
    }
}
#[inline(always)]
fn write_vec(n: u32, q: bool, value: u128) {
    set_dreg(n, value as u64);
    if q {
        set_dreg(n + 1, (value >> 64) as u64);
    }
}

/// The elements of a D (`q` false) or Q register
#[inline(always)]
fn count(q: bool, esize: u32) -> u32 { (64 << q as u32) / esize }

#[inline(always)]
fn all(condition: bool, esize: u32) -> u64 {
    if condition {
        ones(esize)
    }
    else {
        0
    }
}

/// The value replicated across 64 bits
fn replicate(value: u64, esize: u32) -> u64 {
    let value = value & ones(esize);
    let mut r = 0;
    let mut at = 0;
    while at < 64 {
        r |= value << at;
        at += esize;
    }
    r
}

/// The standard FPSCR value's environment
fn standard() -> Fp { Fp::with(unsafe { *fpcr } & fp::FPCR_AHP | fp::FPCR_DN | fp::FPCR_FZ) }

const ONE_POINT_FIVE: u64 = 0x3FC0_0000;
const TWO: u64 = 0x4000_0000;
const THREE: u64 = 0x4040_0000;

/// An odd register where a Q register is named
#[inline(always)]
fn odd(q: bool, registers: u32) -> bool { q && registers & 1 != 0 }

// ---- data processing

/// The data processing instructions (A32: 1111 001U)
pub fn data_processing(word: u32) -> Result<Flow, Exception> {
    if word & 1 << 23 == 0 {
        return three_same(word);
    }
    if word & 1 << 4 != 0 {
        if word >> 19 & 7 == 0 && word & 1 << 7 == 0 {
            return one_register_immediate(word);
        }
        return shift_immediate(word);
    }
    if word >> 20 & 3 == 3 {
        if word & 1 << 24 == 0 {
            return extract(word);
        }
        if word & 1 << 11 == 0 {
            return two_misc(word);
        }
        if word >> 10 & 3 == 0b10 {
            return table(word);
        }
        if word >> 7 & 31 == 0b11000 {
            return duplicate_scalar(word);
        }
        return Err(Exception::Undefined);
    }
    if word & 1 << 6 == 0 {
        three_different(word)
    }
    else {
        two_scalar(word)
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Int3 {
    Hadd,
    Rhadd,
    Hsub,
    Qadd,
    Qsub,
    Cgt,
    Cge,
    Shl,
    Qshl,
    Rshl,
    Qrshl,
    Max,
    Min,
    Abd,
    Aba,
    Add,
    Sub,
    Tst,
    Ceq,
    Mla,
    Mls,
    Mul,
    Pmul,
    Qdmulh,
    Qrdmulh,
    Pmax,
    Pmin,
    Padd,
}

/// One element of a three-same integer operation: `n`, `m` the operands'
/// (for the shifts by register `n` is the shift), `d` the destination's
fn int3(op: Int3, n: u64, m: u64, d: u64, esize: u32, unsigned: bool, qc: &mut bool) -> u64 {
    let mask = ones(esize);
    let (x, y) = (simd::int(n, esize, unsigned), simd::int(m, esize, unsigned));
    match op {
        Int3::Hadd => ((x + y) >> 1) as u64 & mask,
        Int3::Rhadd => ((x + y + 1) >> 1) as u64 & mask,
        Int3::Hsub => ((x - y) >> 1) as u64 & mask,
        Int3::Qadd => sat(x + y, esize, unsigned, qc),
        Int3::Qsub => sat(x - y, esize, unsigned, qc),
        Int3::Cgt => all(x > y, esize),
        Int3::Cge => all(x >= y, esize),
        Int3::Shl | Int3::Qshl | Int3::Rshl | Int3::Qrshl => simd::shift_by(
            y,
            sext(n & 0xFF, 8),
            esize,
            unsigned,
            op == Int3::Rshl || op == Int3::Qrshl,
            op == Int3::Qshl || op == Int3::Qrshl,
            qc,
        ),
        Int3::Max | Int3::Pmax => x.max(y) as u64 & mask,
        Int3::Min | Int3::Pmin => x.min(y) as u64 & mask,
        Int3::Abd => (x - y).unsigned_abs() as u64 & mask,
        Int3::Aba => d.wrapping_add((x - y).unsigned_abs() as u64) & mask,
        Int3::Add | Int3::Padd => n.wrapping_add(m) & mask,
        Int3::Sub => n.wrapping_sub(m) & mask,
        Int3::Tst => all(n & m != 0, esize),
        Int3::Ceq => all(n & mask == m & mask, esize),
        Int3::Mla => d.wrapping_add(n.wrapping_mul(m)) & mask,
        Int3::Mls => d.wrapping_sub(n.wrapping_mul(m)) & mask,
        Int3::Mul => n.wrapping_mul(m) & mask,
        Int3::Pmul => simd::pmul(n, m, 8) as u64 & 0xFF,
        Int3::Qdmulh | Int3::Qrdmulh => {
            let (x, y) = (sext(n, esize) as i128, sext(m, esize) as i128);
            let round = if op == Int3::Qrdmulh { 1i128 << (esize - 1) } else { 0 };
            sat((2 * x * y + round) >> esize, esize, false, qc)
        },
    }
}

/// Three registers of the same length (bit 23 0)
fn three_same(word: u32) -> Result<Flow, Exception> {
    let (d, n, m) = (d_of(word), n_of(word), m_of(word));
    let q = word & 1 << 6 != 0;
    let u = word & 1 << 24 != 0;
    let size = word >> 20 & 3;
    let o1 = word & 1 << 4 != 0;
    let opc = word >> 8 & 15;
    if opc == 0b1100 && !o1 {
        return sha_three(word, u, size, d, n, m);
    }
    if opc >= 0b1101 || opc == 0b1100 {
        return three_same_float(word, opc, o1, u, d, n, m, q);
    }
    // the bitwise operations: size is the opcode
    if opc == 0b0001 && o1 {
        if odd(q, d | n | m) {
            return Err(Exception::Undefined);
        }
        fp::check_access()?;
        let (a, b, c) = (read_vec(n, q), read_vec(m, q), read_vec(d, q));
        let r = match (u, size) {
            (false, 0) => a & b,
            (false, 1) => a & !b,
            (false, 2) => a | b,
            (false, _) => a | !b,
            (true, 0) => a ^ b,
            (true, 1) => a & c | b & !c,
            (true, 2) => a & b | c & !b,
            (true, _) => c & b | a & !b,
        };
        write_vec(d, q, r);
        return Ok(Flow::Next);
    }
    let op = match (opc, o1, u) {
        (0b0000, false, _) => Int3::Hadd,
        (0b0000, true, _) => Int3::Qadd,
        (0b0001, false, _) => Int3::Rhadd,
        (0b0010, false, _) => Int3::Hsub,
        (0b0010, true, _) => Int3::Qsub,
        (0b0011, false, _) => Int3::Cgt,
        (0b0011, true, _) => Int3::Cge,
        (0b0100, false, _) => Int3::Shl,
        (0b0100, true, _) => Int3::Qshl,
        (0b0101, false, _) => Int3::Rshl,
        (0b0101, true, _) => Int3::Qrshl,
        (0b0110, false, _) => Int3::Max,
        (0b0110, true, _) => Int3::Min,
        (0b0111, false, _) => Int3::Abd,
        (0b0111, true, _) => Int3::Aba,
        (0b1000, false, false) => Int3::Add,
        (0b1000, false, true) => Int3::Sub,
        (0b1000, true, false) => Int3::Tst,
        (0b1000, true, true) => Int3::Ceq,
        (0b1001, false, false) => Int3::Mla,
        (0b1001, false, true) => Int3::Mls,
        (0b1001, true, false) => Int3::Mul,
        (0b1001, true, true) => Int3::Pmul,
        (0b1010, false, _) => Int3::Pmax,
        (0b1010, true, _) => Int3::Pmin,
        (0b1011, false, false) => Int3::Qdmulh,
        (0b1011, false, true) => Int3::Qrdmulh,
        (0b1011, true, false) => Int3::Padd,
        // (VQRDMLAH: RDM is not in the profile)
        _ => return Err(Exception::Undefined),
    };
    let size_ok = match op {
        Int3::Qadd | Int3::Qsub | Int3::Shl | Int3::Qshl | Int3::Rshl | Int3::Qrshl => true,
        Int3::Add | Int3::Sub => true,
        Int3::Pmul => size == 0,
        Int3::Qdmulh | Int3::Qrdmulh => size == 1 || size == 2,
        _ => size != 3,
    };
    let pairwise = matches!(op, Int3::Pmax | Int3::Pmin | Int3::Padd);
    if !size_ok || (pairwise && q) || odd(q, d | n | m) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let esize = 8 << size;
    // (signed: the doubling multiplies, the U bit their rounding)
    let unsigned = u && !matches!(op, Int3::Qdmulh | Int3::Qrdmulh);
    let (a, b, c) = (read_vec(n, q), read_vec(m, q), read_vec(d, q));
    let mut qc = false;
    let mut r = 0u128;
    if pairwise {
        let half = count(false, esize) / 2;
        for i in 0..half {
            let first = int3(
                op,
                elem(a, 2 * i, esize),
                elem(a, 2 * i + 1, esize),
                0,
                esize,
                unsigned,
                &mut qc,
            );
            let second = int3(
                op,
                elem(b, 2 * i, esize),
                elem(b, 2 * i + 1, esize),
                0,
                esize,
                unsigned,
                &mut qc,
            );
            r = with_elem(r, i, esize, first);
            r = with_elem(r, i + half, esize, second);
        }
    }
    else {
        for i in 0..count(q, esize) {
            let e = int3(
                op,
                elem(a, i, esize),
                elem(b, i, esize),
                elem(c, i, esize),
                esize,
                unsigned,
                &mut qc,
            );
            r = with_elem(r, i, esize, e);
        }
    }
    if qc {
        set_qc();
    }
    write_vec(d, q, r);
    Ok(Flow::Next)
}

/// SHA1C, SHA1P, SHA1M, SHA1SU0 (U 0), SHA256H, SHA256H2, SHA256SU1 (U 1): Q registers
fn sha_three(word: u32, u: bool, size: u32, d: u32, n: u32, m: u32) -> Result<Flow, Exception> {
    if word & 1 << 6 == 0 || (d | n | m) & 1 != 0 || (u && size == 3) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let (vd, vn, vm) = (read_vec(d, true), read_vec(n, true), read_vec(m, true));
    let r = match (u, size) {
        (false, 0) => crypto::sha1_hash(vd, vn as u32, vm, crypto::choose),
        (false, 1) => crypto::sha1_hash(vd, vn as u32, vm, crypto::parity),
        (false, 2) => crypto::sha1_hash(vd, vn as u32, vm, crypto::majority),
        (false, _) => crypto::sha1su0(vd, vn, vm),
        (true, 0) => crypto::sha256_hash(vd, vn, vm, true),
        (true, 1) => crypto::sha256_hash(vn, vd, vm, false),
        (true, _) => crypto::sha256su1(vd, vn, vm),
    };
    write_vec(d, true, r);
    Ok(Flow::Next)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Float3 {
    Add,
    Sub,
    Abd,
    Mla,
    Mls,
    Mul,
    Fma,
    Fms,
    Ceq,
    Cge,
    Cgt,
    Acge,
    Acgt,
    Max,
    Min,
    Maxnm,
    Minnm,
    Recps,
    Rsqrts,
    Padd,
    Pmax,
    Pmin,
}

/// VRECPS, VRSQRTS as QEMU computes them (not fused): inputs flushed,
/// infinity times zero 2 (1.5), else 2 - n * m ((3 - n * m) / 2)
fn step(fp: &mut Fp, n: u64, m: u64, sqrt: bool) -> u64 {
    let (n, m) = (fp.input::<F32>(n), fp.input::<F32>(m));
    if (is_inf::<F32>(n) && is_zero::<F32>(m)) || (is_inf::<F32>(m) && is_zero::<F32>(n)) {
        return if sqrt { ONE_POINT_FIVE } else { TWO };
    }
    let product = fp.arith::<F32>(Arith::Mul, n, m);
    if sqrt {
        let r = fp.arith::<F32>(Arith::Sub, THREE, product);
        fp.arith::<F32>(Arith::Div, r, TWO)
    }
    else {
        fp.arith::<F32>(Arith::Sub, TWO, product)
    }
}

fn float3(op: Float3, fp: &mut Fp, n: u64, m: u64, d: u64) -> u64 {
    let abs = |v: u64| v & !F32::SIGN;
    match op {
        Float3::Add | Float3::Padd => fp.arith::<F32>(Arith::Add, n, m),
        Float3::Sub => fp.arith::<F32>(Arith::Sub, n, m),
        Float3::Abd => abs(fp.arith::<F32>(Arith::Sub, n, m)),
        Float3::Mla => {
            let product = fp.arith::<F32>(Arith::Mul, n, m);
            fp.arith::<F32>(Arith::Add, d, product)
        },
        Float3::Mls => {
            let product = fp.arith::<F32>(Arith::Mul, n, m);
            fp.arith::<F32>(Arith::Sub, d, product)
        },
        Float3::Mul => fp.arith::<F32>(Arith::Mul, n, m),
        Float3::Fma => fp.mul_add::<F32>(d, n, m),
        Float3::Fms => fp.mul_add::<F32>(d, n ^ F32::SIGN, m),
        Float3::Ceq => all(fp.compare_eq::<F32>(n, m), 32),
        Float3::Cge => all(fp.compare_ge::<F32>(n, m), 32),
        Float3::Cgt => all(fp.compare_gt::<F32>(n, m), 32),
        Float3::Acge => all(fp.compare_ge::<F32>(abs(n), abs(m)), 32),
        Float3::Acgt => all(fp.compare_gt::<F32>(abs(n), abs(m)), 32),
        Float3::Max | Float3::Pmax => fp.max_min::<F32>(n, m, true, false),
        Float3::Min | Float3::Pmin => fp.max_min::<F32>(n, m, false, false),
        Float3::Maxnm => fp.max_min::<F32>(n, m, true, true),
        Float3::Minnm => fp.max_min::<F32>(n, m, false, true),
        Float3::Recps => step(fp, n, m, false),
        Float3::Rsqrts => step(fp, n, m, true),
    }
}

/// The floating-point three-same instructions (single precision; bit 20, half precision, is not in the profile)
fn three_same_float(
    word: u32,
    opc: u32,
    o1: bool,
    u: bool,
    d: u32,
    n: u32,
    m: u32,
    q: bool,
) -> Result<Flow, Exception> {
    let op21 = word & 1 << 21 != 0;
    let op = match (opc, o1, u, op21) {
        (0b1100, true, false, false) => Float3::Fma,
        (0b1100, true, false, true) => Float3::Fms,
        (0b1101, false, false, false) => Float3::Add,
        (0b1101, false, false, true) => Float3::Sub,
        (0b1101, false, true, false) => Float3::Padd,
        (0b1101, false, true, true) => Float3::Abd,
        (0b1101, true, false, false) => Float3::Mla,
        (0b1101, true, false, true) => Float3::Mls,
        (0b1101, true, true, false) => Float3::Mul,
        (0b1110, false, false, false) => Float3::Ceq,
        (0b1110, false, true, false) => Float3::Cge,
        (0b1110, false, true, true) => Float3::Cgt,
        (0b1110, true, true, false) => Float3::Acge,
        (0b1110, true, true, true) => Float3::Acgt,
        (0b1111, false, false, false) => Float3::Max,
        (0b1111, false, false, true) => Float3::Min,
        (0b1111, false, true, false) => Float3::Pmax,
        (0b1111, false, true, true) => Float3::Pmin,
        (0b1111, true, false, false) => Float3::Recps,
        (0b1111, true, false, true) => Float3::Rsqrts,
        (0b1111, true, true, false) => Float3::Maxnm,
        (0b1111, true, true, true) => Float3::Minnm,
        _ => return Err(Exception::Undefined),
    };
    let pairwise = matches!(op, Float3::Padd | Float3::Pmax | Float3::Pmin);
    if word & 1 << 20 != 0 || (pairwise && q) || odd(q, d | n | m) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let (a, b, c) = (read_vec(n, q), read_vec(m, q), read_vec(d, q));
    let mut fp = standard();
    let mut r = 0u128;
    if pairwise {
        let first = float3(op, &mut fp, elem(a, 0, 32), elem(a, 1, 32), 0);
        let second = float3(op, &mut fp, elem(b, 0, 32), elem(b, 1, 32), 0);
        r = first as u128 | (second as u128) << 32;
    }
    else {
        for i in 0..count(q, 32) {
            let e = float3(op, &mut fp, elem(a, i, 32), elem(b, i, 32), elem(c, i, 32));
            r = with_elem(r, i, 32, e);
        }
    }
    fp.finish();
    write_vec(d, q, r);
    Ok(Flow::Next)
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Shift {
    Shr,
    Sra,
    Rshr,
    Rsra,
    Sri,
    Shl,
    Sli,
    Qshlu,
    Qshl,
}

/// Two registers and a shift amount (bit 23 1, bit 4 1): the element size
/// is L:imm6's leading one, a right shift 2 * esize - L:imm6, a left one
/// L:imm6 - esize
fn shift_immediate(word: u32) -> Result<Flow, Exception> {
    let u = word & 1 << 24 != 0;
    let l = word & 1 << 7 != 0;
    let imm6 = word >> 16 & 63;
    let opc = word >> 8 & 15;
    let q = word & 1 << 6 != 0;
    let (d, m) = (d_of(word), m_of(word));
    let esize = if l {
        64
    }
    else if imm6 & 32 != 0 {
        32
    }
    else if imm6 & 16 != 0 {
        16
    }
    else {
        8
    };
    let imm = if l { 64 + imm6 } else { imm6 };
    let right = 2 * esize - imm;
    let left = imm - esize;
    match opc {
        0..=7 => {
            let op = match (opc, u) {
                (0, _) => Shift::Shr,
                (1, _) => Shift::Sra,
                (2, _) => Shift::Rshr,
                (3, _) => Shift::Rsra,
                (4, true) => Shift::Sri,
                (5, false) => Shift::Shl,
                (5, true) => Shift::Sli,
                (6, true) => Shift::Qshlu,
                (7, _) => Shift::Qshl,
                _ => return Err(Exception::Undefined),
            };
            if odd(q, d | m) {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let (a, c) = (read_vec(m, q), read_vec(d, q));
            let mask = ones(esize);
            let mut qc = false;
            let mut r = 0u128;
            for i in 0..count(q, esize) {
                let (x, old) = (elem(a, i, esize), elem(c, i, esize));
                let shr = |round: bool, qc: &mut bool| {
                    simd::shift_by(
                        simd::int(x, esize, u),
                        -(right as i64),
                        esize,
                        u,
                        round,
                        false,
                        qc,
                    )
                };
                let e = match op {
                    Shift::Shr => shr(false, &mut qc),
                    Shift::Sra => old.wrapping_add(shr(false, &mut qc)) & mask,
                    Shift::Rshr => shr(true, &mut qc),
                    Shift::Rsra => old.wrapping_add(shr(true, &mut qc)) & mask,
                    Shift::Sri => {
                        if right == esize {
                            old
                        }
                        else {
                            old & !(mask >> right) | x >> right
                        }
                    },
                    Shift::Shl => x << left & mask,
                    Shift::Sli => old & ones(left) | x << left & mask,
                    Shift::Qshlu => simd::shift_by(
                        sext(x, esize) as i128,
                        left as i64,
                        esize,
                        true,
                        false,
                        true,
                        &mut qc,
                    ),
                    Shift::Qshl => simd::shift_by(
                        simd::int(x, esize, u),
                        left as i64,
                        esize,
                        u,
                        false,
                        true,
                        &mut qc,
                    ),
                };
                r = with_elem(r, i, esize, e);
            }
            if qc {
                set_qc();
            }
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        8 | 9 => {
            // VSHRN, VRSHRN (U 0), VQSHRUN, VQRSHRUN (U 1); VQSHRN, VQRSHRN:
            // from Qm's 2 * esize elements to Dd's (bit 6: rounding)
            if l || m & 1 != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let round = q;
            let (source_unsigned, dest_unsigned, saturate) = match (opc, u) {
                (8, false) => (true, true, false),
                (8, true) => (false, true, true),
                (_, unsigned) => (unsigned, unsigned, true),
            };
            let a = read_vec(m, true);
            let mut qc = false;
            let mut r = 0u128;
            for i in 0..64 / esize {
                let x = simd::int(elem(a, i, 2 * esize), 2 * esize, source_unsigned);
                let shifted = (x + if round { 1i128 << (right - 1) } else { 0 }) >> right;
                let e = if saturate {
                    sat(shifted, esize, dest_unsigned, &mut qc)
                }
                else {
                    shifted as u64 & ones(esize)
                };
                r = with_elem(r, i, esize, e);
            }
            if qc {
                set_qc();
            }
            set_dreg(d, r as u64);
            Ok(Flow::Next)
        },
        10 => {
            // VSHLL (VMOVL with 0): Dm's elements widened, shifted left
            if l || q || d & 1 != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let a = dreg(m) as u128;
            let mut r = 0u128;
            for i in 0..64 / esize {
                let x = simd::int(elem(a, i, esize), esize, u) << left;
                r = with_elem(r, i, 2 * esize, x as u64);
            }
            write_vec(d, true, r);
            Ok(Flow::Next)
        },
        14 | 15 => {
            // VCVT between single precision and 32-bit fixed point (64 - imm6 fraction bits)
            if l || esize != 32 || odd(q, d | m) {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let fbits = 64 - imm6;
            let a = read_vec(m, q);
            let mut fp = standard();
            let mut r = 0u128;
            for i in 0..count(q, 32) {
                let x = elem(a, i, 32);
                let e = if opc == 14 {
                    fp.from_integer::<F32>(x, !u, 32, fbits)
                }
                else {
                    fp.to_integer::<F32>(x, !u, 32, fbits, fp::ROUND_MIN_MAG)
                };
                r = with_elem(r, i, 32, e);
            }
            fp.finish();
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        // (12, 13: half precision; 11)
        _ => Err(Exception::Undefined),
    }
}

/// AdvSIMDExpandImm as QEMU's asimd_imm_const has it: op 1 inverts the
/// 32-bit forms (VMVN, VBIC), cmode 1110 with op 1 is the byte mask
pub fn expand_imm(imm8: u32, cmode: u32, op: u32) -> u64 {
    let mut imm = imm8;
    match cmode {
        0 | 1 => {},
        2 | 3 => imm <<= 8,
        4 | 5 => imm <<= 16,
        6 | 7 => imm <<= 24,
        8 | 9 => imm |= imm << 16,
        10 | 11 => imm = imm << 8 | imm << 24,
        12 => imm = imm << 8 | 0xFF,
        13 => imm = imm << 16 | 0xFFFF,
        14 => {
            if op == 1 {
                let mut r = 0u64;
                for i in 0..8 {
                    if imm8 >> i & 1 != 0 {
                        r |= 0xFF << (8 * i);
                    }
                }
                return r;
            }
            imm |= imm << 8 | imm << 16 | imm << 24;
        },
        _ => {
            imm = (imm8 & 0x80) << 24
                | (imm8 & 0x3F) << 19
                | if imm8 & 0x40 != 0 { 0x1F << 25 } else { 1 << 30 };
        },
    }
    if op == 1 {
        imm = !imm;
    }
    imm as u64 | (imm as u64) << 32
}

/// One register and a modified immediate: VMOV, VMVN, VORR, VBIC
fn one_register_immediate(word: u32) -> Result<Flow, Exception> {
    let imm8 = (word >> 24 & 1) << 7 | (word >> 16 & 7) << 4 | word & 15;
    let cmode = word >> 8 & 15;
    let op = word >> 5 & 1;
    let q = word & 1 << 6 != 0;
    let d = d_of(word);
    if odd(q, d) || (cmode == 15 && op == 1) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let imm = expand_imm(imm8, cmode, op);
    let imm = imm as u128 | (imm as u128) << 64;
    let r = if cmode & 1 == 1 && cmode < 12 {
        let current = read_vec(d, q);
        if op == 1 {
            current & imm
        }
        else {
            current | imm
        }
    }
    else {
        imm
    };
    write_vec(d, q, r);
    Ok(Flow::Next)
}

/// Three registers of different lengths (bit 23 1, size not 11, bit 6 0)
fn three_different(word: u32) -> Result<Flow, Exception> {
    let u = word & 1 << 24 != 0;
    let size = word >> 20 & 3;
    let opc = word >> 8 & 15;
    let (d, n, m) = (d_of(word), n_of(word), m_of(word));
    let esize = 8 << size;
    let wide = 2 * esize;
    let lanes = 64 / esize;
    let undefined = match opc {
        0..=3 => d & 1 != 0 || (opc & 1 != 0 && n & 1 != 0),
        4 | 6 => (n | m) & 1 != 0,
        9 | 11 | 13 => u || size == 0 || d & 1 != 0,
        14 => u || size == 1 || d & 1 != 0,
        15 => true,
        _ => d & 1 != 0,
    };
    if undefined {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let mut qc = false;
    match opc {
        4 | 6 => {
            // VADDHN, VSUBHN, VRADDHN, VRSUBHN (U): the high halves of Qn +- Qm
            let (a, b) = (read_vec(n, true), read_vec(m, true));
            let round = if u { 1u64 << (esize - 1) } else { 0 };
            let mut r = 0u128;
            for i in 0..lanes {
                let (x, y) = (elem(a, i, wide), elem(b, i, wide));
                let s = if opc == 4 { x.wrapping_add(y) } else { x.wrapping_sub(y) };
                r = with_elem(r, i, esize, (s.wrapping_add(round) & ones(wide)) >> esize);
            }
            set_dreg(d, r as u64);
        },
        14 => {
            // VMULL.P8, VMULL.P64
            let (a, b) = (dreg(n), dreg(m));
            let r = if size == 0 {
                let mut r = 0u128;
                for i in 0..8 {
                    r = with_elem(
                        r,
                        i,
                        16,
                        simd::pmul(a >> (8 * i) & 0xFF, b >> (8 * i) & 0xFF, 8) as u64,
                    );
                }
                r
            }
            else {
                simd::pmul(a, b, 64)
            };
            write_vec(d, true, r);
        },
        _ => {
            let a = if opc <= 3 && opc & 1 != 0 { read_vec(n, true) } else { dreg(n) as u128 };
            let b = dreg(m) as u128;
            let acc = read_vec(d, true);
            let mut r = 0u128;
            for i in 0..lanes {
                let x = if opc <= 3 && opc & 1 != 0 {
                    simd::int(elem(a, i, wide), wide, u)
                }
                else {
                    simd::int(elem(a, i, esize), esize, u)
                };
                let y = simd::int(elem(b, i, esize), esize, u);
                let z = simd::int(elem(acc, i, wide), wide, false);
                let e = match opc {
                    0 | 1 => (x + y) as u64,
                    2 | 3 => (x - y) as u64,
                    5 => (z + (x - y).abs()) as u64,
                    7 => (x - y).abs() as u64,
                    8 => (z + x * y) as u64,
                    10 => (z - x * y) as u64,
                    12 => (x * y) as u64,
                    // VQDMLAL, VQDMLSL, VQDMULL: the doubled product saturated, then the sum
                    _ => {
                        let product = sat(2 * x * y, wide, false, &mut qc);
                        let product = sext(product, wide) as i128;
                        match opc {
                            9 => sat(z + product, wide, false, &mut qc),
                            11 => sat(z - product, wide, false, &mut qc),
                            _ => product as u64,
                        }
                    },
                };
                r = with_elem(r, i, wide, e & ones(wide));
            }
            write_vec(d, true, r);
        },
    }
    if qc {
        set_qc();
    }
    Ok(Flow::Next)
}

/// Two registers and a scalar (bit 23 1, size not 11, bit 6 1): bit 24 is
/// Q for the forms that are not long, U for the long ones
fn two_scalar(word: u32) -> Result<Flow, Exception> {
    let opc = word >> 8 & 15;
    let size = word >> 20 & 3;
    let bit24 = word & 1 << 24 != 0;
    let long = matches!(opc, 2 | 3 | 6 | 7 | 10 | 11);
    let float = matches!(opc, 1 | 5 | 9);
    let q = !long && bit24;
    let u = long && bit24;
    let (d, n) = (d_of(word), n_of(word));
    let vm = m_of(word);
    let (dm, index) = if size == 1 { (vm & 7, vm >> 3) } else { (vm & 15, vm >> 4) };
    let undefined = (if float { size != 2 } else { size == 0 })
        || opc >= 14
        || (matches!(opc, 3 | 7 | 11) && u)
        || if long { d & 1 != 0 } else { odd(q, d | n) };
    if undefined {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let esize = 8 << size;
    let scalar = elem(dreg(dm) as u128, index, esize);
    let mut qc = false;
    if long {
        let wide = 2 * esize;
        let a = dreg(n) as u128;
        let acc = read_vec(d, true);
        let y = simd::int(scalar, esize, u);
        let mut r = 0u128;
        for i in 0..64 / esize {
            let x = simd::int(elem(a, i, esize), esize, u);
            let z = simd::int(elem(acc, i, wide), wide, false);
            let e = match opc {
                2 => (z + x * y) as u64,
                6 => (z - x * y) as u64,
                10 => (x * y) as u64,
                _ => {
                    let product = sext(sat(2 * x * y, wide, false, &mut qc), wide) as i128;
                    match opc {
                        3 => sat(z + product, wide, false, &mut qc),
                        7 => sat(z - product, wide, false, &mut qc),
                        _ => product as u64,
                    }
                },
            };
            r = with_elem(r, i, wide, e & ones(wide));
        }
        if qc {
            set_qc();
        }
        write_vec(d, true, r);
        return Ok(Flow::Next);
    }
    let (a, acc) = (read_vec(n, q), read_vec(d, q));
    let mut r = 0u128;
    let mut fp = standard();
    for i in 0..count(q, esize) {
        let (x, z) = (elem(a, i, esize), elem(acc, i, esize));
        let e = match opc {
            0 => int3(Int3::Mla, x, scalar, z, esize, false, &mut qc),
            4 => int3(Int3::Mls, x, scalar, z, esize, false, &mut qc),
            8 => int3(Int3::Mul, x, scalar, z, esize, false, &mut qc),
            12 => int3(Int3::Qdmulh, x, scalar, z, esize, false, &mut qc),
            13 => int3(Int3::Qrdmulh, x, scalar, z, esize, false, &mut qc),
            1 => float3(Float3::Mla, &mut fp, x, scalar, z),
            5 => float3(Float3::Mls, &mut fp, x, scalar, z),
            _ => float3(Float3::Mul, &mut fp, x, scalar, z),
        };
        r = with_elem(r, i, esize, e);
    }
    if float {
        fp.finish();
    }
    if qc {
        set_qc();
    }
    write_vec(d, q, r);
    Ok(Flow::Next)
}

/// VEXT: bytes from imm4 of Vm:Vn
fn extract(word: u32) -> Result<Flow, Exception> {
    let imm4 = word >> 8 & 15;
    let q = word & 1 << 6 != 0;
    let (d, n, m) = (d_of(word), n_of(word), m_of(word));
    if odd(q, d | n | m) || (!q && imm4 > 7) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let shift = 8 * imm4;
    let r = if q {
        let (low, high) = (read_vec(n, true), read_vec(m, true));
        if shift == 0 {
            low
        }
        else {
            low >> shift | high << (128 - shift)
        }
    }
    else {
        ((dreg(m) as u128) << 64 | dreg(n) as u128) >> shift
    };
    write_vec(d, q, r);
    Ok(Flow::Next)
}

/// VTBL, VTBX (bit 6): Dd's bytes looked up in D[n..n+len], out of range 0 (VTBL) or Dd's
fn table(word: u32) -> Result<Flow, Exception> {
    let len = word >> 8 & 3;
    let extension = word & 1 << 6 != 0;
    let (d, n, m) = (d_of(word), n_of(word), m_of(word));
    if n + len + 1 > 32 {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let mut bytes = [0u8; 32];
    for i in 0..=len {
        bytes[8 * i as usize..8 * i as usize + 8].copy_from_slice(&dreg(n + i).to_le_bytes());
    }
    let (indexes, current) = (dreg(m), dreg(d));
    let size = 8 * (len + 1) as u64;
    let mut r = 0u64;
    for i in 0..8 {
        let index = indexes >> (8 * i) & 0xFF;
        let byte = if index < size {
            bytes[index as usize] as u64
        }
        else if extension {
            current >> (8 * i) & 0xFF
        }
        else {
            0
        };
        r |= byte << (8 * i);
    }
    set_dreg(d, r);
    Ok(Flow::Next)
}

/// VDUP (scalar): imm4 xxx1 a byte, xx10 a halfword, x100 a word
fn duplicate_scalar(word: u32) -> Result<Flow, Exception> {
    let imm4 = word >> 16 & 15;
    let q = word & 1 << 6 != 0;
    let (d, m) = (d_of(word), m_of(word));
    let (esize, index) = if imm4 & 1 != 0 {
        (8, imm4 >> 1)
    }
    else if imm4 & 2 != 0 {
        (16, imm4 >> 2)
    }
    else if imm4 & 4 != 0 {
        (32, imm4 >> 3)
    }
    else {
        return Err(Exception::Undefined);
    };
    if odd(q, d) {
        return Err(Exception::Undefined);
    }
    fp::check_access()?;
    let value = replicate(elem(dreg(m) as u128, index, esize), esize);
    write_vec(d, q, value as u128 | (value as u128) << 64);
    Ok(Flow::Next)
}

/// The integer leading sign bits (VCLS) of an element
fn leading_sign(x: u64, esize: u32) -> u64 {
    let v = sext(x, esize);
    let flipped = (v ^ (v >> 63)) as u64 & ones(esize);
    (flipped.leading_zeros() - (64 - esize)) as u64 - 1
}

/// Two registers, miscellaneous (bit 23 1, size 11, bit 24 1, bit 11 0):
/// size in 19:18, opc1 in 17:16, opc2 in 10:7
fn two_misc(word: u32) -> Result<Flow, Exception> {
    let size = word >> 18 & 3;
    let opc1 = word >> 16 & 3;
    let opc2 = word >> 7 & 15;
    let q = word & 1 << 6 != 0;
    let (d, m) = (d_of(word), m_of(word));
    let esize = 8 << size;
    let b6 = q;
    // the crypto and conversion forms that name Q registers or halves: their own checks
    match (opc1, opc2) {
        (0, 0b0110) | (0, 0b0111) => {
            // AESE, AESD (bit 6); AESMC, AESIMC
            if size != 0 || (d | m) & 1 != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let (vd, vm) = (read_vec(d, true), read_vec(m, true));
            let r = if opc2 == 0b0110 {
                crypto::aes_round(vd, vm, b6)
            }
            else {
                crypto::aes_mix(vm, b6)
            };
            write_vec(d, true, r);
            return Ok(Flow::Next);
        },
        (1, 0b0101) | (2, 0b0111) => {
            // SHA1H (bit 6 1); SHA1SU1, SHA256SU0 (bit 6)
            if size != 2 || (d | m) & 1 != 0 || (opc1 == 1 && !b6) {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let (vd, vm) = (read_vec(d, true), read_vec(m, true));
            let r = match (opc1, b6) {
                (1, _) => (vm as u32).rotate_left(30) as u128,
                (_, false) => crypto::sha1su1(vd, vm),
                _ => crypto::sha256su0(vd, vm),
            };
            write_vec(d, true, r);
            return Ok(Flow::Next);
        },
        (2, 0b0100) | (2, 0b0101) => {
            // VMOVN, VQMOVUN (bit 6); VQMOVN signed, unsigned (bit 6): Qm to Dd
            if size == 3 || m & 1 != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let a = read_vec(m, true);
            let mut qc = false;
            let mut r = 0u128;
            for i in 0..64 / esize {
                let x = elem(a, i, 2 * esize);
                let e = match (opc2, b6) {
                    (0b0100, false) => x & ones(esize),
                    (0b0100, true) => sat(sext(x, 2 * esize) as i128, esize, true, &mut qc),
                    (_, false) => sat(sext(x, 2 * esize) as i128, esize, false, &mut qc),
                    _ => sat(x as i128, esize, true, &mut qc),
                };
                r = with_elem(r, i, esize, e);
            }
            if qc {
                set_qc();
            }
            set_dreg(d, r as u64);
            return Ok(Flow::Next);
        },
        (2, 0b0110) => {
            // VSHLL (by the element size): Dm to Qd
            if b6 || size == 3 || d & 1 != 0 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let a = dreg(m) as u128;
            let mut r = 0u128;
            for i in 0..64 / esize {
                r = with_elem(r, i, 2 * esize, elem(a, i, esize) << esize);
            }
            write_vec(d, true, r);
            return Ok(Flow::Next);
        },
        (2, 0b1100) | (2, 0b1110) => {
            // VCVT.F16.F32 (Qm to Dd), VCVT.F32.F16 (Dm to Qd); bit 6: BF16, not in the profile
            if b6 || size != 1 || (opc2 == 0b1100 && m & 1 != 0) || (opc2 == 0b1110 && d & 1 != 0) {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let mut fp = standard();
            if opc2 == 0b1100 {
                let a = read_vec(m, true);
                let mut r = 0u64;
                for i in 0..4 {
                    r |= (fp.to_half(elem(a, i, 32), 32) as u64) << (16 * i);
                }
                fp.finish();
                set_dreg(d, r);
            }
            else {
                let a = dreg(m);
                let mut r = 0u128;
                for i in 0..4 {
                    r = with_elem(r, i, 32, fp.from_half((a >> (16 * i)) as u16, 32));
                }
                fp.finish();
                write_vec(d, true, r);
            }
            return Ok(Flow::Next);
        },
        _ => {},
    }
    // the element-wise and permuting forms on D or Q
    if odd(q, d | m) {
        return Err(Exception::Undefined);
    }
    let (a, c) = (read_vec(m, q), read_vec(d, q));
    let lanes = count(q, esize);
    match (opc1, opc2) {
        (0, 0b0000) | (0, 0b0001) | (0, 0b0010) => {
            // VREV64, VREV32, VREV16: the elements reversed within 64, 32, 16 bits
            let container = [64, 32, 16][opc2 as usize];
            if esize >= container {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let per = container / esize;
            let mut r = 0u128;
            for i in 0..lanes {
                let j = i / per * per + (per - 1 - i % per);
                r = with_elem(r, i, esize, elem(a, j, esize));
            }
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        (0, 0b0100) | (0, 0b0101) | (0, 0b1100) | (0, 0b1101) => {
            // VPADDL, VPADAL (signed, unsigned): adjacent pairs widened and added
            if size == 3 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let unsigned = opc2 & 1 != 0;
            let accumulate = opc2 & 8 != 0;
            let wide = 2 * esize;
            let mut r = 0u128;
            for i in 0..lanes / 2 {
                let sum = simd::int(elem(a, 2 * i, esize), esize, unsigned)
                    + simd::int(elem(a, 2 * i + 1, esize), esize, unsigned);
                let e = if accumulate {
                    (sum as u64).wrapping_add(elem(c, i, wide))
                }
                else {
                    sum as u64
                };
                r = with_elem(r, i, wide, e);
            }
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        (0, 0b1010) | (0, 0b1011) | (2, 0b0000) if size != 0 => Err(Exception::Undefined),
        (0, 0b1000)
        | (0, 0b1001)
        | (0, 0b1010)
        | (0, 0b1011)
        | (0, 0b1110)
        | (0, 0b1111)
        | (1, 0..=4)
        | (1, 6)
        | (1, 7) => {
            // VCLS, VCLZ, VCNT (bytes), VMVN (bytes), VQABS, VQNEG; compares with
            // zero, VABS, VNEG (integer)
            if size == 3 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let mut qc = false;
            let mut r = 0u128;
            for i in 0..lanes {
                let x = elem(a, i, esize);
                let v = sext(x, esize) as i128;
                let e = match (opc1, opc2) {
                    (0, 0b1000) => leading_sign(x, esize),
                    (0, 0b1001) => (x.leading_zeros() - (64 - esize)) as u64,
                    (0, 0b1010) => x.count_ones() as u64,
                    (0, 0b1011) => !x & 0xFF,
                    (0, 0b1110) => sat(v.abs(), esize, false, &mut qc),
                    (0, _) => sat(-v, esize, false, &mut qc),
                    (1, 0) => all(v > 0, esize),
                    (1, 1) => all(v >= 0, esize),
                    (1, 2) => all(v == 0, esize),
                    (1, 3) => all(v <= 0, esize),
                    (1, 4) => all(v < 0, esize),
                    (1, 6) => v.unsigned_abs() as u64 & ones(esize),
                    _ => (v.wrapping_neg()) as u64 & ones(esize),
                };
                r = with_elem(r, i, esize, e);
            }
            if qc {
                set_qc();
            }
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        (2, 0b0000) => {
            // VSWP
            fp::check_access()?;
            write_vec(d, q, a);
            write_vec(m, q, c);
            Ok(Flow::Next)
        },
        (2, 0b0001) => {
            // VTRN: Dd's odd elements and Dm's even ones exchanged (d = m: UNPREDICTABLE)
            if size == 3 || d == m {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let (mut rd, mut rm) = (c, a);
            for i in (0..lanes).step_by(2) {
                rd = with_elem(rd, i + 1, esize, elem(a, i, esize));
                rm = with_elem(rm, i, esize, elem(c, i + 1, esize));
            }
            write_vec(d, q, rd);
            write_vec(m, q, rm);
            Ok(Flow::Next)
        },
        (2, 0b0010) | (2, 0b0011) => {
            // VUZP, VZIP: on D, bytes and halfwords; on Q, words too (d = m: UNPREDICTABLE)
            if size == 3 || (!q && size == 2) || d == m {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let (mut rd, mut rm) = (0u128, 0u128);
            for i in 0..lanes {
                // (the pair as one vector: Dd's elements, then Dm's)
                let source =
                    |k: u32| if k < lanes { elem(c, k, esize) } else { elem(a, k - lanes, esize) };
                let e = if opc2 == 0b0010 {
                    source(2 * i)
                }
                else {
                    let k = i / 2;
                    if i % 2 == 0 {
                        elem(c, k, esize)
                    }
                    else {
                        elem(a, k, esize)
                    }
                };
                let f = if opc2 == 0b0010 {
                    source(2 * i + 1)
                }
                else {
                    let k = (i + lanes) / 2;
                    if i % 2 == 0 {
                        elem(c, k, esize)
                    }
                    else {
                        elem(a, k, esize)
                    }
                };
                rd = with_elem(rd, i, esize, e);
                rm = with_elem(rm, i, esize, f);
            }
            write_vec(d, q, rd);
            write_vec(m, q, rm);
            Ok(Flow::Next)
        },
        (1, 0b1000..=0b1100)
        | (1, 0b1110)
        | (1, 0b1111)
        | (2, 0b1000..=0b1011)
        | (2, 0b1101)
        | (2, 0b1111)
        | (3, _) => {
            // single precision: compares with zero, VABS, VNEG; VRINT*; VCVT{A,N,P,M}; the estimates; the conversions
            if size != 2 {
                return Err(Exception::Undefined);
            }
            fp::check_access()?;
            let mut fp = standard();
            let mut r = 0u128;
            for i in 0..lanes {
                let x = elem(a, i, 32);
                let e = match (opc1, opc2) {
                    (1, 0b1000) => all(fp.compare_gt::<F32>(x, 0), 32),
                    (1, 0b1001) => all(fp.compare_ge::<F32>(x, 0), 32),
                    (1, 0b1010) => all(fp.compare_eq::<F32>(x, 0), 32),
                    (1, 0b1011) => all(fp.compare_ge::<F32>(0, x), 32),
                    (1, 0b1100) => all(fp.compare_gt::<F32>(0, x), 32),
                    (1, 0b1110) => x & !F32::SIGN,
                    (1, _) => x ^ F32::SIGN,
                    (2, 0b1001) => fp.round_to_int::<F32>(x, fp::ROUND_NEAR_EVEN, true),
                    (2, _) => {
                        let mode = match opc2 {
                            0b1000 => fp::ROUND_NEAR_EVEN,
                            0b1010 => fp::ROUND_NEAR_MAX_MAG,
                            0b1011 => fp::ROUND_MIN_MAG,
                            0b1101 => fp::ROUND_MIN,
                            _ => fp::ROUND_MAX,
                        };
                        fp.round_to_int::<F32>(x, mode, false)
                    },
                    (_, 0..=7) => {
                        let mode = [
                            fp::ROUND_NEAR_MAX_MAG,
                            fp::ROUND_NEAR_EVEN,
                            fp::ROUND_MAX,
                            fp::ROUND_MIN,
                        ][(opc2 >> 1) as usize];
                        fp.to_integer::<F32>(x, opc2 & 1 == 0, 32, 0, mode)
                    },
                    (_, 0b1000) => {
                        // VRECPE (unsigned)
                        if x >> 31 == 0 {
                            0xFFFF_FFFF
                        }
                        else {
                            (fp::recip_estimate((x >> 23) as u32 & 0x1FF) as u64) << 23
                        }
                    },
                    (_, 0b1001) => {
                        // VRSQRTE (unsigned)
                        if x >> 30 == 0 {
                            0xFFFF_FFFF
                        }
                        else {
                            (fp::recip_sqrt_estimate((x >> 23) as u32 & 0x1FF) as u64) << 23
                        }
                    },
                    (_, 0b1010) => fp.recip_estimate::<F32>(x),
                    (_, 0b1011) => fp.recip_sqrt_estimate::<F32>(x),
                    (_, 0b1100) => fp.from_integer::<F32>(x, true, 32, 0),
                    (_, 0b1101) => fp.from_integer::<F32>(x, false, 32, 0),
                    (_, 0b1110) => fp.to_integer::<F32>(x, true, 32, 0, fp::ROUND_MIN_MAG),
                    _ => fp.to_integer::<F32>(x, false, 32, 0, fp::ROUND_MIN_MAG),
                };
                r = with_elem(r, i, 32, e);
            }
            fp.finish();
            write_vec(d, q, r);
            Ok(Flow::Next)
        },
        _ => Err(Exception::Undefined),
    }
}

// ---- loads and stores

/// One element's access (MemU: SCTLR.A and Device memory check it)
fn load_element(address: u32, bytes: u32) -> Result<u64, Exception> {
    memory::read(address as u64, bytes, false, Syndrome::NONE)
}

/// The alignment the instruction asks for, of its first access
fn check_alignment(address: u32, alignment: u32, write: bool) -> Result<(), Exception> {
    if alignment > 1 && address & (alignment - 1) != 0 {
        return Err(execute::alignment(address as u64, write, Syndrome::NONE));
    }
    Ok(())
}

/// VLDn, VSTn (A32: 1111 0100, bit 20 0): bit 23 multiple structures, else
/// one lane or all lanes; Rm 15 no writeback, 13 the size transferred,
/// else Rn + Rm. Every access translates before anything is written.
pub fn load_store(word: u32) -> Result<Flow, Exception> {
    let rn = word >> 16 & 15;
    let rm = word & 15;
    let d = d_of(word);
    let load = word & 1 << 21 != 0;
    if word & 1 << 20 != 0 || rn == 15 {
        return Err(Exception::Undefined);
    }
    // the elements: (D register, lane, element bytes) in memory order; a
    // load to all lanes replicates into each register
    let mut elements: [(u8, u8); 64] = [(0, 0); 64];
    let mut used = 0;
    let (ebytes, alignment, all_lanes, transferred) = if word & 1 << 23 == 0 {
        let itype = word >> 8 & 15;
        let size = word >> 6 & 3;
        let align = word >> 4 & 3;
        const TYPES: [(u32, u32, u32); 11] = [
            (1, 4, 1),
            (1, 4, 2),
            (4, 1, 1),
            (2, 2, 2),
            (1, 3, 1),
            (1, 3, 2),
            (3, 1, 1),
            (1, 1, 1),
            (1, 2, 1),
            (1, 2, 2),
            (2, 1, 1),
        ];
        if itype > 10 || (itype & 12 == 4 && align >= 2) || (itype & 12 == 8 && align == 3) {
            return Err(Exception::Undefined);
        }
        let (registers, interleave, spacing) = TYPES[itype as usize];
        if (size == 3 && (interleave != 1 || spacing != 1))
            || d + registers - 1 + spacing * (interleave - 1) > 31
        {
            return Err(Exception::Undefined);
        }
        let ebytes = 1 << size;
        for r in 0..registers {
            for lane in 0..8 >> size {
                for x in 0..interleave {
                    elements[used] = ((d + r + spacing * x) as u8, lane as u8);
                    used += 1;
                }
            }
        }
        (
            ebytes,
            if align != 0 { 4 << align } else { 1 },
            false,
            registers * interleave * 8,
        )
    }
    else if word >> 10 & 3 == 3 {
        // to all lanes (loads alone; bit 5 T, bit 4 a)
        let registers = (word >> 8 & 3) + 1;
        let size = word >> 6 & 3;
        let (t, a) = (word & 1 << 5 != 0, word & 1 << 4 != 0);
        if !load {
            return Err(Exception::Undefined);
        }
        let (ebytes, alignment) = if size == 3 {
            if registers != 4 || !a {
                return Err(Exception::Undefined);
            }
            (4, 16)
        }
        else {
            let ebytes = 1 << size;
            let alignment = match (a, registers) {
                (false, _) => 1,
                (true, 1) if size == 0 => return Err(Exception::Undefined),
                (true, 1) => ebytes,
                (true, 2) => 2 * ebytes,
                (true, 3) => return Err(Exception::Undefined),
                (true, _) => {
                    if size == 2 {
                        8
                    }
                    else {
                        4 * ebytes
                    }
                },
            };
            (ebytes, alignment)
        };
        let stride = if t { 2 } else { 1 };
        // (VLD1: T writes two registers)
        let last = if registers == 1 { d + (stride - 1) } else { d + stride * (registers - 1) };
        if last > 31 {
            return Err(Exception::Undefined);
        }
        for r in 0..registers {
            elements[used] = ((d + stride * r) as u8, 0);
            used += 1;
        }
        (ebytes, alignment, true, ebytes * registers)
    }
    else {
        // one lane: the index, the register stride, the alignment by size
        let size = word >> 10 & 3;
        let registers = (word >> 8 & 3) + 1;
        let (lane, stride, align) = match size {
            0 => (word >> 5 & 7, 1, word >> 4 & 1),
            1 => (
                word >> 6 & 3,
                if word & 1 << 5 != 0 { 2 } else { 1 },
                word >> 4 & 1,
            ),
            _ => (
                word >> 7 & 1,
                if word & 1 << 6 != 0 { 2 } else { 1 },
                word >> 4 & 3,
            ),
        };
        let undefined = match registers {
            1 => {
                stride != 1 || align & (1 << size) != 0 || (size == 2 && (align == 1 || align == 2))
            },
            2 => size == 2 && align & 2 != 0,
            3 => align != 0,
            _ => size == 2 && align == 3,
        };
        if undefined || d + stride * (registers - 1) > 31 {
            return Err(Exception::Undefined);
        }
        let ebytes = 1 << size;
        let alignment = match (align, registers) {
            (0, _) => 1,
            (_, 1) => ebytes,
            (_, 2) => 2 * ebytes,
            _ => {
                if size == 2 {
                    ebytes << align
                }
                else {
                    4 * ebytes
                }
            },
        };
        for r in 0..registers {
            elements[used] = ((d + stride * r) as u8, lane as u8);
            used += 1;
        }
        (ebytes, alignment, false, ebytes * registers)
    };
    fp::check_access()?;
    let base = reg(rn);
    let writeback = match rm {
        15 => None,
        13 => Some(base.wrapping_add(transferred)),
        _ => Some(base.wrapping_add(reg(rm))),
    };
    check_alignment(base, alignment, !load)?;
    let esize = 8 * ebytes;
    if load {
        let mut values = [0u64; 64];
        for (i, value) in values.iter_mut().take(used).enumerate() {
            *value = load_element(base.wrapping_add(i as u32 * ebytes), ebytes)?;
        }
        if let Some(new_base) = writeback {
            set_reg(rn, new_base);
        }
        for (&(register, lane), &value) in elements.iter().zip(values.iter()).take(used) {
            let register = register as u32;
            if all_lanes {
                set_dreg(register, replicate(value, esize));
                if used == 1 && word & 1 << 5 != 0 {
                    set_dreg(register + 1, replicate(value, esize));
                }
            }
            else {
                set_dreg(
                    register,
                    with_elem(dreg(register) as u128, lane as u32, esize, value) as u64,
                );
            }
        }
    }
    else {
        let mut stores: [Option<(memory::Store, u64)>; 64] = [None; 64];
        for (i, &(register, lane)) in elements.iter().take(used).enumerate() {
            let address = base.wrapping_add(i as u32 * ebytes);
            let value = elem(dreg(register as u32) as u128, lane as u32, esize);
            stores[i] = Some((
                memory::prepare_write(address as u64, ebytes, false, Syndrome::NONE)?,
                value,
            ));
        }
        for store in stores.into_iter().flatten() {
            store.0.commit(store.1)?;
        }
        if let Some(new_base) = writeback {
            set_reg(rn, new_base);
        }
    }
    Ok(Flow::Next)
}
                                source/v64/src/rust/aarch64/a32_system.rs                                                           0000644 0000000 0000000 00000067635 00000000000 015260  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AArch32 at PL1 (cpu_type "arm32", docs/aarch32-plan.md R2): the CPU is
//! AArch32 throughout (cpu::a32_only). The modes and their banked
//! registers (X0-X14 hold the current mode's R0-R14; the others' R13 and
//! R14, and R8-R12 of FIQ or of the rest, wait in the state block's a32
//! fields), CPSR (NZCV in `nzcv`, the rest in `pstate` as an AArch32 SPSR
//! lays it out) and the modes' SPSRs, exception entry (the vectors at VBAR
//! or 0xFFFF0000 with SCTLR.V, the return addresses' offsets, DFSR, IFSR,
//! DFAR, IFAR) and return, the privileged instructions' semantics (CPS,
//! MRS and MSR of CPSR and SPSR, SRS, RFE, LDM and STM of the user
//! registers), and CP15 at PL1, most of it the AArch64 registers' views.

use crate::aarch64::a32::{instruction_length, reg, set_reg, thumb};
use crate::aarch64::cpu::{self, *};
use crate::aarch64::execute::Flow;
use crate::aarch64::state::*;

pub const MODE_USR: u32 = 0x10;
pub const MODE_FIQ: u32 = 0x11;
pub const MODE_IRQ: u32 = 0x12;
pub const MODE_SVC: u32 = 0x13;
pub const MODE_ABT: u32 = 0x17;
pub const MODE_UND: u32 = 0x1B;
pub const MODE_SYS: u32 = 0x1F;

/// SCTLR's bits AArch32 has of its own
const SCTLR_V: u32 = 1 << 13;
const SCTLR_EE: u32 = 1 << 25;
const SCTLR_TE: u32 = 1 << 30;
/// SCTLR at reset (QEMU's cortex-a15)
pub const SCTLR_RESET_A32: u64 = 0x00C5_0078;

/// The modes this CPU has (no Monitor, no Hyp)
#[inline(always)]
pub fn valid_mode(mode: u32) -> bool {
    matches!(
        mode,
        MODE_USR | MODE_FIQ | MODE_IRQ | MODE_SVC | MODE_ABT | MODE_UND | MODE_SYS
    )
}

/// The R13 and R14 bank of a mode: USR and SYS share one
#[inline(always)]
fn bank(mode: u32) -> usize {
    match mode {
        MODE_FIQ => 1,
        MODE_IRQ => 2,
        MODE_SVC => 3,
        MODE_ABT => 4,
        MODE_UND => 5,
        _ => 0,
    }
}

/// A mode's SPSR (none in USR and SYS)
#[inline(always)]
fn spsr_index(mode: u32) -> Option<usize> {
    match mode {
        MODE_FIQ => Some(0),
        MODE_IRQ => Some(1),
        MODE_SVC => Some(2),
        MODE_ABT => Some(3),
        MODE_UND => Some(4),
        _ => None,
    }
}

#[inline(always)]
pub fn mode() -> u32 { get_pstate() & 0x1F }

/// (AArch32 code) whether it runs at PL1: a mode but User (only with cpu::a32_only)
#[inline(always)]
pub fn privileged() -> bool { get_pstate() & 0xF != 0 }

/// The banked registers from mode `old`'s to mode `new`'s (pstate is set after)
pub fn switch_registers(old: u32, new: u32) {
    unsafe {
        let (ob, nb) = (bank(old), bank(new));
        if ob != nb {
            *a32_bank.add(2 * ob) = *x.add(13) as u32;
            *a32_bank.add(2 * ob + 1) = *x.add(14) as u32;
            *x.add(13) = *a32_bank.add(2 * nb) as u64;
            *x.add(14) = *a32_bank.add(2 * nb + 1) as u64;
        }
        // (R8-R12: FIQ's own; a32_bank_r8 0-4 the others' while in FIQ, 5-9 FIQ's while not)
        if (old == MODE_FIQ) != (new == MODE_FIQ) {
            let (save, load) = if new == MODE_FIQ { (0, 5) } else { (5, 0) };
            for i in 0..5 {
                *a32_bank_r8.add(save + i) = *x.add(8 + i) as u32;
                *x.add(8 + i) = *a32_bank_r8.add(load + i) as u64;
            }
        }
    }
}

/// A register of mode `of` (R0-R14), from wherever it is now
pub fn banked_reg(of: u32, n: u32) -> u32 {
    let current = mode();
    unsafe {
        if n >= 13 && bank(of) != bank(current) {
            return *a32_bank.add(2 * bank(of) + n as usize - 13);
        }
        if (8..13).contains(&n) && (of == MODE_FIQ) != (current == MODE_FIQ) {
            return *a32_bank_r8.add(if of == MODE_FIQ { 5 } else { 0 } + n as usize - 8);
        }
    }
    reg(n)
}
pub fn set_banked_reg(of: u32, n: u32, value: u32) {
    let current = mode();
    unsafe {
        if n >= 13 && bank(of) != bank(current) {
            *a32_bank.add(2 * bank(of) + n as usize - 13) = value;
            return;
        }
        if (8..13).contains(&n) && (of == MODE_FIQ) != (current == MODE_FIQ) {
            *a32_bank_r8.add(if of == MODE_FIQ { 5 } else { 0 } + n as usize - 8) = value;
            return;
        }
    }
    set_reg(n, value)
}

/// CPSR as an SPSR keeps it (NZCV, the mode and masks, T, E, ITSTATE, GE, Q)
#[inline(always)]
pub fn cpsr() -> u32 {
    get_nzcv() | get_pstate() & PSTATE_SAVED_A32 & !(PSTATE_IL | PSTATE_SS | PSTATE_PAN)
}

/// The current mode's SPSR (None in USR and SYS: UNPREDICTABLE there)
pub fn spsr() -> Option<u32> { spsr_index(mode()).map(|i| unsafe { *a32_spsr.add(i) }) }
pub fn set_spsr(value: u32) { set_spsr_of(mode(), value) }

/// The SPSR of mode `of` (MRS and MSR of a banked SPSR)
pub fn spsr_of(of: u32) -> u32 { spsr_index(of).map_or(0, |i| unsafe { *a32_spsr.add(i) }) }
pub fn set_spsr_of(of: u32, value: u32) {
    if let Some(i) = spsr_index(of) {
        unsafe { *a32_spsr.add(i) = value };
    }
}

/// CPSR := `value` (the exception return's, an SPSR's): the mode's banks
/// switch; an illegal mode keeps the current one
fn set_cpsr(value: u32) {
    let new_mode = if valid_mode(value & 0x1F) { value & 0x1F } else { mode() };
    set_nzcv(value & 0xF000_0000);
    let keep = PSTATE_IL | PSTATE_SS | PSTATE_PAN;
    let saved = PSTATE_SAVED_A32 & !keep & !0x1F;
    cpu::set_pstate(get_pstate() & keep | value & saved | new_mode);
}

/// MRS of CPSR (the execution state bits, but E, read as 0)
pub fn mrs_cpsr() -> u32 { cpsr() & !(PSTATE_T | PSTATE_IT) }

/// MSR CPSR_<fields> at PL1 (CPSRWriteByInstr): `mask` the byte fields
/// c (bit 0: mode, I, F), x (1: A, E), s (2: GE), f (3: NZCV, Q)
pub fn msr_cpsr(value: u32, mask: u32) {
    let privileged = mode() != MODE_USR;
    let mut pstate_value = get_pstate();
    if mask & 8 != 0 {
        set_nzcv(value & 0xF000_0000);
        pstate_value = pstate_value & !PSTATE_Q | value & PSTATE_Q;
    }
    if mask & 4 != 0 {
        pstate_value = pstate_value & !PSTATE_GE | value & PSTATE_GE;
    }
    if mask & 2 != 0 && privileged {
        pstate_value = pstate_value & !(PSTATE_A | PSTATE_E) | value & (PSTATE_A | PSTATE_E);
    }
    if mask & 1 != 0 && privileged {
        pstate_value = pstate_value & !(PSTATE_I | PSTATE_F) | value & (PSTATE_I | PSTATE_F);
        if valid_mode(value & 0x1F) {
            pstate_value = pstate_value & !0x1F | value & 0x1F;
        }
    }
    cpu::set_pstate(pstate_value);
}

/// The bits of an SPSR that MSR writes (as QEMU's cortex-a15: all but 23:21)
const SPSR_VALID: u32 = 0xFF1F_FFFF;

/// MSR SPSR_<fields>
pub fn msr_spsr(value: u32, mask: u32) {
    let Some(old) = spsr()
    else {
        return;
    };
    let bytes = (0..4)
        .filter(|b| mask & 1 << b != 0)
        .fold(0, |m, b| m | 0xFF << (8 * b))
        & SPSR_VALID;
    set_spsr(old & !bytes | value & bytes);
}

/// CPS: `imod` 2 enable, 3 disable the A, I, F masks `aif` (bits 2:0); a mode when `change_mode`
pub fn cps(imod: u32, aif: u32, change_mode: bool, new_mode: u32) {
    if mode() == MODE_USR {
        return;
    }
    let masks = (aif & 4 != 0) as u32 * PSTATE_A
        | (aif & 2 != 0) as u32 * PSTATE_I
        | (aif & 1 != 0) as u32 * PSTATE_F;
    let mut value = get_pstate();
    match imod {
        2 => value &= !masks,
        3 => value |= masks,
        _ => {},
    }
    if change_mode && valid_mode(new_mode) {
        value = value & !0x1F | new_mode;
    }
    cpu::set_pstate(value);
}

/// An exception return (SUBS PC, LR; LDM with the PC and ^; RFE takes its
/// CPSR from memory): CPSR := `value`, the PC `target` aligned for the
/// instruction set it returns to
pub fn return_to(target: u32, value: u32) -> Flow {
    crate::aarch64::jit::pages::a32_trace(7, target, value);
    set_cpsr(value);
    unsafe { *excl_valid = 0 };
    Flow::Jump((target & if value & PSTATE_T != 0 { !1 } else { !3 }) as u64)
}

/// SUBS PC, LR and the data processing with S into the PC at PL1: CPSR := SPSR
pub fn exception_return(target: u32) -> Result<Flow, Exception> {
    match spsr() {
        Some(value) => Ok(return_to(target, value)),
        None => Err(Exception::Undefined),
    }
}

/// LDM with the PC and ^ (an exception return), LDM and STM of the User
/// mode's registers (`writeback` UNPREDICTABLE there: UNDEFINED), `pc` the
/// value an STM stores for the PC
pub fn block_user(
    load: bool,
    rn: u32,
    list: u32,
    start: u32,
    writeback: Option<u32>,
    stored_pc: u32,
) -> Result<Flow, Exception> {
    use crate::aarch64::a32::{load_aligned, prepare_store};
    let returns = load && list & 1 << 15 != 0;
    if !returns && writeback.is_some() || returns && spsr().is_none() {
        return Err(Exception::Undefined);
    }
    let mut address = start;
    if load {
        let mut values = [0u32; 16];
        for i in 0..16 {
            if list & 1 << i != 0 {
                values[i] = load_aligned(address, 4)?;
                address = address.wrapping_add(4);
            }
        }
        if returns {
            if let Some(base) = writeback {
                set_reg(rn, base);
            }
            for i in 0..15 {
                if list & 1 << i != 0 {
                    set_reg(i as u32, values[i]);
                }
            }
            return Ok(return_to(values[15], spsr().unwrap_or(0)));
        }
        for i in 0..15 {
            if list & 1 << i != 0 {
                set_banked_reg(MODE_USR, i as u32, values[i]);
            }
        }
        return Ok(Flow::Next);
    }
    let mut stores: [Option<(crate::aarch64::memory::Store, u32)>; 16] = Default::default();
    for i in 0..16u32 {
        if list & 1 << i != 0 {
            let value = if i == 15 { stored_pc } else { banked_reg(MODE_USR, i) };
            stores[i as usize] = Some((prepare_store(address, 4, false, true)?, value));
            address = address.wrapping_add(4);
        }
    }
    for store in stores.into_iter().flatten() {
        store.0.commit(store.1 as u64)?;
    }
    Ok(Flow::Next)
}

/// The first of two words an SRS or RFE transfers from `base`: P (before) and U (up)
fn two_words(base: u32, p: bool, u: bool) -> (u32, u32) {
    let start = match (p, u) {
        (false, true) => base,
        (true, true) => base.wrapping_add(4),
        (false, false) => base.wrapping_sub(4),
        (true, false) => base.wrapping_sub(8),
    };
    (
        start,
        if u { base.wrapping_add(8) } else { base.wrapping_sub(8) },
    )
}

/// SRS: the current mode's LR and SPSR to the stack of mode `to`
pub fn srs(p: bool, u: bool, w: bool, to: u32) -> Result<Flow, Exception> {
    use crate::aarch64::a32::prepare_store;
    let Some(saved) = spsr()
    else {
        return Err(Exception::Undefined);
    };
    if !valid_mode(to) || to == MODE_USR {
        return Err(Exception::Undefined);
    }
    let (start, new_base) = two_words(banked_reg(to, 13), p, u);
    let first = prepare_store(start, 4, false, true)?;
    let second = prepare_store(start.wrapping_add(4), 4, false, true)?;
    first.commit(reg(14) as u64)?;
    second.commit(saved as u64)?;
    if w {
        set_banked_reg(to, 13, new_base);
    }
    Ok(Flow::Next)
}

/// RFE: the PC and CPSR from [Rn]
pub fn rfe(p: bool, u: bool, w: bool, rn: u32) -> Result<Flow, Exception> {
    use crate::aarch64::a32::load_aligned;
    if rn == 15 {
        return Err(Exception::Undefined);
    }
    let (start, new_base) = two_words(reg(rn), p, u);
    let target = load_aligned(start, 4)?;
    let value = load_aligned(start.wrapping_add(4), 4)?;
    if w {
        set_reg(rn, new_base);
    }
    Ok(return_to(target, value))
}

/// MRC, MCR of CP14 (debug, the trivial Jazelle and its registers): read as
/// zero, writes ignored at PL1 (DBGDIDR 0: Linux finds no debug
/// architecture it supports); UNDEFINED at PL0
pub fn cp14(read: bool, rt: u32) -> Result<Flow, Exception> {
    if !privileged() {
        return Err(Exception::Undefined);
    }
    if read {
        if rt == 15 {
            set_nzcv(0);
        }
        else {
            set_reg(rt, 0);
        }
    }
    Ok(Flow::Next)
}

/// FPSID (cortex-a15's)
const FPSID: u32 = 0x4104_30F0;
const FPEXC_EN: u32 = 1 << 30;

/// Whether VFP and Advanced SIMD are enabled (FPEXC.EN)
#[inline(always)]
pub fn fp_enabled() -> bool { (unsafe { *a32_fpexc }) & FPEXC_EN != 0 }

/// VMRS, VMSR of FPSID (0), MVFR2 (5), MVFR1 (6), MVFR0 (7), FPEXC (8) at
/// PL1: CPACR's access, whatever FPEXC.EN says
pub fn vfp_system(register: u32, rt: u32, to_core: bool) -> Result<Flow, Exception> {
    let fpen = unsafe { *cpacr_el1 } >> 20 & 3;
    if !privileged() || fpen != 3 && fpen != 1 || rt == 15 {
        return Err(Exception::Undefined);
    }
    let id = |row: usize| crate::aarch64::sysregs::AARCH32_ID[2][row] as u32;
    let value = match register {
        0 => FPSID,
        5 => id(2),
        6 => id(1),
        7 => id(0),
        8 => unsafe { *a32_fpexc },
        _ => return Err(Exception::Undefined),
    };
    if to_core {
        set_reg(rt, value);
    }
    else {
        match register {
            8 => unsafe { *a32_fpexc = reg(rt) & FPEXC_EN },
            0 => {},
            _ => return Err(Exception::Undefined),
        }
    }
    Ok(Flow::Next)
}

// ---- exception entry

/// Take an exception to `new_mode` at vector `offset`: SPSR := CPSR, LR := `lr`,
/// the masks `mask` set, T and E as SCTLR says
fn enter(offset: u32, new_mode: u32, lr: u32, mask: u32) {
    let old = cpsr();
    crate::aarch64::jit::pages::a32_trace(6, cpu::get_pc() as u32, old);
    let sctlr = cpu::sctlr() as u32;
    let mut value = get_pstate()
        & !(0x1F | PSTATE_T | PSTATE_IT | PSTATE_E | PSTATE_IL | PSTATE_SS)
        | new_mode
        | mask;
    if sctlr & SCTLR_TE != 0 {
        value |= PSTATE_T;
    }
    if sctlr & SCTLR_EE != 0 {
        value |= PSTATE_E;
    }
    cpu::set_pstate(value);
    set_spsr(old);
    set_reg(14, lr);
    let base =
        if sctlr & SCTLR_V != 0 { 0xFFFF_0000 } else { (unsafe { *vbar_el1 }) as u32 & !0x1F };
    unsafe { *excl_valid = 0 };
    cpu::set_pc(base.wrapping_add(offset) as u64);
}

/// The fault status (DFSR, IFSR) of an AArch64 DFSC: with the long
/// descriptors LPAE's (bit 9, the DFSC); else the short descriptors' (level
/// 1 sections, levels 2 and 3 pages; 0x3D and 0x3E the domain faults): FS[4]
/// in bit 10, FS[3:0] in bits 3:0
fn fsr(code: u32) -> u32 {
    let dfsc = code & 0x3F;
    if crate::aarch64::mmu_a32::long_descriptors() {
        return 1 << 9 | dfsc;
    }
    // (the domain, mmu_a32::FSC_DOMAIN_SHIFT)
    let domain = code >> crate::aarch64::mmu_a32::FSC_DOMAIN_SHIFT & 15;
    let fs = match dfsc {
        0x21 => 0b00001,
        0x22 => 0b00010,
        0x04..=0x05 => 0b00101,
        0x06..=0x07 => 0b00111,
        0x08..=0x09 => 0b00011,
        0x0A..=0x0B => 0b00110,
        0x0C..=0x0D => 0b01101,
        0x0E..=0x0F => 0b01111,
        0x3D => 0b01001,
        0x3E => 0b01011,
        // (external aborts on the walk: level 1, level 2)
        0x14..=0x15 => 0b01100,
        0x16..=0x17 => 0b01110,
        // (synchronous external aborts)
        _ => 0b01000,
    };
    (fs & 0x10) << 6 | fs & 0xF | domain << 4
}

/// The current instruction (at the PC) takes `exception` (cpu::take_sync's
/// AArch32 counterpart): its vector, mode, LR and fault status
pub fn take_sync(exception: Exception) {
    let here = cpu::get_pc() as u32;
    let a = PSTATE_A | PSTATE_I;
    match exception {
        Exception::Svc(_) => enter(
            0x08,
            MODE_SVC,
            here.wrapping_add(instruction_length()),
            PSTATE_I,
        ),
        Exception::InstructionAbort { fsc, far } => {
            // (a64_page_aarch32_trace: EL0's execute permission faults, which
            // Linux makes SIGSEGV)
            if fsc & 0x3C == 0x0C && cpu::el() == 0 {
                crate::aarch64::jit::pages::a32_trace_dump("an instruction permission fault");
            }
            unsafe {
                *a32_ifsr = fsr(fsc);
                *far_el1 = *far_el1 & 0xFFFF_FFFF | (far as u32 as u64) << 32;
            }
            enter(0x0C, MODE_ABT, here.wrapping_add(4), a);
        },
        Exception::PcAlignment(far) => {
            unsafe {
                *a32_ifsr = fsr(0x21);
                *far_el1 = *far_el1 & 0xFFFF_FFFF | (far as u32 as u64) << 32;
            }
            enter(0x0C, MODE_ABT, here.wrapping_add(4), a);
        },
        // (BKPT: a prefetch abort of a debug event)
        Exception::Breakpoint | Exception::Trapped32 { ec: 0x38, .. } => {
            // (IFAR UNKNOWN: 0, as QEMU writes it)
            unsafe {
                *a32_ifsr = fsr(0x22);
                *far_el1 &= 0xFFFF_FFFF;
            }
            enter(0x0C, MODE_ABT, here.wrapping_add(4), a);
        },
        Exception::DataAbort { iss, far } => {
            unsafe {
                // (WnR in bit 11, CM in bit 13)
                *esr_el1 = (fsr(iss) | (iss >> 6 & 1) << 11 | (iss >> 8 & 1) << 13) as u64;
                *far_el1 = *far_el1 & !0xFFFF_FFFF | far as u32 as u64;
            }
            enter(0x10, MODE_ABT, here.wrapping_add(8), a);
        },
        Exception::Watchpoint { write, far } => {
            unsafe {
                *esr_el1 = (fsr(0x22) | (write as u32) << 11) as u64;
                *far_el1 = *far_el1 & !0xFFFF_FFFF | far as u32 as u64;
            }
            enter(0x10, MODE_ABT, here.wrapping_add(8), a);
        },
        _ => enter(
            0x04,
            MODE_UND,
            here.wrapping_add(if thumb() { 2 } else { 4 }),
            PSTATE_I,
        ),
    }
}

/// An interrupt (cpu::take_exception's): IRQ or FIQ, the PC the next instruction's
pub fn take_interrupt(fiq: bool) {
    let lr = (cpu::get_pc() as u32).wrapping_add(4);
    if fiq {
        enter(0x1C, MODE_FIQ, lr, PSTATE_A | PSTATE_I | PSTATE_F);
    }
    else {
        enter(0x18, MODE_IRQ, lr, PSTATE_A | PSTATE_I);
    }
}

/// The core's state at reset: SVC mode, A, I and F masked, A32 (T32 when
/// bit 0 of `entry`), MMU off; R0 `context`
pub fn reset(entry: u64, context: u64) {
    unsafe {
        *pstate =
            MODE_SVC | PSTATE_A | PSTATE_I | PSTATE_F | if entry & 1 != 0 { PSTATE_T } else { 0 };
        *pc = entry & !1;
        *x = context as u32 as u64;
        *sctlr_el1 = SCTLR_RESET_A32;
        for i in 0..12 {
            *a32_bank.add(i) = 0;
        }
        for i in 0..10 {
            *a32_bank_r8.add(i) = 0;
        }
        for i in 0..5 {
            *a32_spsr.add(i) = 0;
        }
        *a32_ttbcr = 0;
        *a32_dacr = 0;
        *a32_ifsr = 0;
    }
}

/// (the machine) a 32-bit kernel's boot: core 0 from `entry` in SVC mode with
/// R0 0, R1 ~0 (a device tree, not a board number), R2 the device tree
#[no_mangle]
pub fn a32_boot(entry: u32, dtb: u32) {
    crate::aarch64::smp::a64_boot(entry, 0, 0, 0);
    cpu::set_x(1, 0xFFFF_FFFF);
    cpu::set_x(2, dtb as u64);
}

// ---- CP15 at PL1

/// The ID registers of profile arm32-v1: profile v3's AArch32 ones
/// (sysregs::AARCH32_ID, CRm 1-2: ID_PFR0, PFR1, DFR0, AFR0, MMFR0-3;
/// ISAR0-5, MMFR4, ISAR6) with ID_PFR1's programmers' model of the PL1
/// modes; no Security, no Virtualization
fn id_register(crm: u32, op2: u32) -> u32 {
    let value = crate::aarch64::sysregs::AARCH32_ID[crm as usize - 1][op2 as usize] as u32;
    if (crm, op2) == (1, 1) {
        value | 1
    }
    else {
        value
    }
}
/// MIDR: cortex-a15 r4p0 (QEMU's; the Android emulator's 32-bit CPU)
pub const MIDR_A15: u32 = 0x414F_C0F0;
const CTR_A15: u32 = 0x8444_C004;

/// MRC (read, Rt := the value) or MCR (`value`) of CP15 at PL1
pub fn cp15(
    read: bool,
    opc1: u32,
    crn: u32,
    crm: u32,
    opc2: u32,
    rt: u32,
    value: u32,
) -> Result<Flow, Exception> {
    use crate::aarch64::sysregs;
    // (the registers that are AArch64's: op0 3, the same op1, CRn, CRm, op2)
    let aarch64 = |reg: u32, read: bool| -> Result<Flow, Exception> {
        if read {
            let got = sysregs::read(reg, rt)?;
            set_reg(rt, got as u32);
        }
        else {
            // (a 32-bit view: the high half kept)
            let old = sysregs::read(reg, rt).unwrap_or(0);
            sysregs::write(reg, rt, old & !0xFFFF_FFFF | value as u64)?;
        }
        Ok(Flow::Next)
    };
    let field = |p: *mut u32| -> Result<Flow, Exception> {
        unsafe {
            if read {
                set_reg(rt, *p);
            }
            else {
                *p = value;
            }
        }
        Ok(Flow::Next)
    };
    let half = |p: *mut u64, high: bool| -> Result<Flow, Exception> {
        unsafe {
            let shift = if high { 32 } else { 0 };
            if read {
                set_reg(rt, (*p >> shift) as u32);
            }
            else {
                *p = *p & !(0xFFFF_FFFFu64 << shift) | (value as u64) << shift;
            }
        }
        Ok(Flow::Next)
    };
    let constant = |got: u32| -> Result<Flow, Exception> {
        if read {
            set_reg(rt, got);
        }
        Ok(Flow::Next)
    };
    match (opc1, crn, crm, opc2) {
        // MIDR, CTR, TCMTR, TLBTR, MPIDR, REVIDR
        (0, 0, 0, 0) | (0, 0, 0, 4) | (0, 0, 0, 7) => constant(MIDR_A15),
        (0, 0, 0, 1) => constant(CTR_A15),
        (0, 0, 0, 2) | (0, 0, 0, 3) | (0, 0, 0, 6) => constant(0),
        (0, 0, 0, 5) => constant(sysregs::mpidr() as u32),
        (0, 0, 1..=2, _) => constant(id_register(crm, opc2)),
        (0, 0, _, _) => constant(0),
        // CCSIDR, CLIDR, AIDR; CSSELR
        (1, 0, 0, 0) | (1, 0, 0, 1) | (1, 0, 0, 7) => aarch64(sysregs::key(3, 1, 0, 0, opc2), true),
        (2, 0, 0, 0) => aarch64(sysregs::key(3, 2, 0, 0, 0), read),
        // SCTLR (AArch32's bits: V, TE, EE too), ACTLR, CPACR
        (0, 1, 0, 0) => {
            if read {
                set_reg(rt, cpu::sctlr() as u32);
            }
            else {
                unsafe { *sctlr_el1 = value as u64 };
                crate::aarch64::mmu::regime_changed();
            }
            Ok(Flow::Next)
        },
        // (ACTLR: RAZ/WI, as QEMU's cortex-a15)
        (0, 1, 0, 1) => constant(0),
        (0, 1, 0, 2) => {
            let r = half(cpacr_el1, false);
            // (ASEDIS, D32DIS, cp11, cp10, as QEMU's ARMv7 CPUs keep them)
            unsafe { *cpacr_el1 &= 0xC0F0_0000 };
            r
        },
        // TTBR0, TTBR1 (32-bit views), TTBCR
        (0, 2, 0, 0) | (0, 2, 0, 1) => {
            let r = half(if opc2 == 0 { ttbr0_el1 } else { ttbr1_el1 }, false);
            if !read {
                crate::aarch64::mmu::ttbr_changed();
            }
            r
        },
        (0, 2, 0, 2) => {
            let r = field(a32_ttbcr);
            if !read {
                crate::aarch64::mmu::regime_changed();
            }
            r
        },
        // DACR (the TLB's entries keep their domain: mmu_a32::with_domain; the
        // page tier's access cache has the permissions it gave)
        (0, 3, 0, 0) => {
            let old = unsafe { *a32_dacr };
            let r = field(a32_dacr);
            if !read && value != old {
                crate::aarch64::tlb::bump_generation();
                crate::aarch64::jit::pages::tlb_flushed(crate::isa::current_core());
            }
            r
        },
        // DFSR (ESR_EL1's), IFSR, ADFSR, AIFSR
        (0, 5, 0, 0) => half(esr_el1, false),
        (0, 5, 0, 1) => field(a32_ifsr),
        (0, 5, 1, 0) | (0, 5, 1, 1) => constant(0),
        // DFAR, IFAR (FAR_EL1's halves)
        (0, 6, 0, 0) => half(far_el1, false),
        (0, 6, 0, 2) => half(far_el1, true),
        // cache maintenance and the CP15 barriers; the branch predictor
        (0, 7, 5, 4) | (0, 7, 10, 4) | (0, 7, 10, 5) if !read => Ok(Flow::Next),
        (0, 7, 1 | 5 | 6 | 10 | 11 | 14, _) if !read => Ok(Flow::Next),
        // PAR (32-bit) and the address translation operations: not yet (UNDEFINED)
        // TLB maintenance (the IS forms CRm 3; ITLB, DTLB, unified 5, 6, 7):
        // all, by MVA and ASID, by ASID, by MVA all ASIDs (the last level's too)
        (0, 8, 3 | 5 | 6 | 7, 0..=3 | 5 | 7) if !read => {
            use crate::aarch64::tlb;
            let shareable = crm == 3;
            let (page, asid) = ((value >> 12) as u64, (value & 0xFF) as u16);
            match opc2 {
                0 => tlb::flush(shareable),
                2 => tlb::flush_asid(shareable, asid),
                1 | 5 => tlb::flush_page(shareable, page, Some(asid)),
                _ => tlb::flush_page(shareable, page, None),
            }
            Ok(Flow::Next)
        },
        // the performance monitors: read as 0, writes ignored
        (0, 9, 12..=14, _) => constant(0),
        // PRRR, NMRR (MAIR_EL1's halves), AMAIR0/1
        (0, 10, 2, 0) | (0, 10, 2, 1) => {
            let r = half(mair_el1, opc2 == 1);
            if !read {
                crate::aarch64::mmu::regime_changed();
            }
            r
        },
        (0, 10, 3, 0) | (0, 10, 3, 1) => half(amair_el1, opc2 == 1),
        // VBAR
        (0, 12, 0, 0) => half(vbar_el1, false),
        // the GICv3 CPU interface (ICC_*: AArch64's registers by the same encodings)
        (0, 4, 6, 0) | (0, 12, 8 | 9 | 11 | 12, _) => {
            aarch64(sysregs::key(3, 0, crn, crm, opc2), read)
        },
        // CONTEXTIDR, TPIDRURW, TPIDRURO, TPIDRPRW
        (0, 13, 0, 1) => {
            let r = half(contextidr_el1, false);
            if !read {
                crate::aarch64::mmu::ttbr_changed();
            }
            r
        },
        (0, 13, 0, 2) => half(tpidr_el0, false),
        (0, 13, 0, 3) => half(tpidrro_el0, false),
        (0, 13, 0, 4) => half(tpidr_el1, false),
        // the generic timer: CNTFRQ, CNTKCTL, CNTP_TVAL/CTL, CNTV_TVAL/CTL
        (0, 14, 0, 0) | (0, 14, 2, 0) | (0, 14, 2, 1) | (0, 14, 3, 0) | (0, 14, 3, 1) => {
            let key = sysregs::key(3, 3, 14, crm, opc2);
            if read {
                let got = crate::aarch64::timer::read(key, rt)?;
                set_reg(rt, got as u32);
            }
            else {
                crate::aarch64::timer::write(key, rt, value as u64)?;
            }
            Ok(Flow::Next)
        },
        (0, 14, 1, 0) => half(cntkctl_el1, false),
        _ => Err(Exception::Undefined),
    }
}

/// MRRC (read: Rt, Rt2 := the value's halves) or MCRR (`value`) of CP15 at
/// PL1: TTBR0 (opc1 0), TTBR1 (1) and PAR (CRm 7) of 64 bits; the timer's
/// counters and compare values (CRm 14); ICC_SGI1R (CRm 12)
pub fn cp15_64(
    read: bool,
    opc1: u32,
    crm: u32,
    rt: u32,
    rt2: u32,
    value: u64,
) -> Result<Flow, Exception> {
    use crate::aarch64::sysregs;
    let set = |got: u64| {
        set_reg(rt, got as u32);
        set_reg(rt2, (got >> 32) as u32);
    };
    match (opc1, crm) {
        (0 | 1, 2) => unsafe {
            let p = if opc1 == 0 { ttbr0_el1 } else { ttbr1_el1 };
            if read {
                set(*p);
            }
            else {
                *p = value;
                crate::aarch64::mmu::ttbr_changed();
            }
            Ok(Flow::Next)
        },
        (0, 7) => unsafe {
            if read {
                set(*par_el1);
            }
            else {
                *par_el1 = value;
            }
            Ok(Flow::Next)
        },
        (0..=3, 14) => {
            let key = match opc1 {
                0 => sysregs::key(3, 3, 14, 0, 1),
                1 => sysregs::key(3, 3, 14, 0, 2),
                2 => sysregs::key(3, 3, 14, 2, 2),
                _ => sysregs::key(3, 3, 14, 3, 2),
            };
            if read {
                set(crate::aarch64::timer::read(key, rt)?);
            }
            else {
                if opc1 < 2 {
                    return Err(Exception::Undefined);
                }
                crate::aarch64::timer::write(key, rt, value)?;
            }
            Ok(Flow::Next)
        },
        // ICC_SGI1R (MCRR p15, 0, Rt, Rt2, c12)
        (0, 12) if !read => {
            sysregs::write(sysregs::key(3, 0, 12, 11, 5), rt, value)?;
            Ok(Flow::Next)
        },
        _ => Err(Exception::Undefined),
    }
}

/// HVC at PL1: PSCI (the device tree's conduit); a machine powered off or
/// a core suspended waits
pub fn hvc() -> Result<Flow, Exception> {
    Ok(match crate::aarch64::psci::call() {
        crate::aarch64::psci::After::Continue => Flow::Next,
        crate::aarch64::psci::After::Wait => Flow::Wait(1),
        crate::aarch64::psci::After::Off => Flow::Off,
    })
}
                                                                                                   source/v64/src/rust/aarch64/backdoor.rs                                                             0000644 0000000 0000000 00000005210 00000000000 015030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The GLES backdoor of AArch32 user code (docs/gles-proxy-plan.md "iOS
//! 传输", E6): UDF #0x8664 (A32 0xE7F866F4, T32 0xF7F8 0xA664) executed at
//! PL0 with r0's top half 0x8664 is a call of the machine's backdoor device
//! (src/arm/backdoor_a32.js) with r0 to r3: its answer goes to r0 and the
//! PC to the next instruction. Any other UDF, one at PL1, one whose r0 is
//! not a call, or one while the machine has no backdoor (the device answers
//! NOT_HANDLED) is the undefined instruction it always was.
//!
//! The interpreter's undefined path checks for it (crate::aarch64::a32::
//! interpret_one): the page tier's helper of a UDF fails and the instruction
//! is retried there, so compiled code reaches it too.

/// r0's top half for a call
pub const CALL: u32 = 0x8664;
/// The device's answer when there is no backdoor: the UDF stays undefined
pub const NOT_HANDLED: i32 = i32::MIN;

#[cfg(target_arch = "wasm32")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn a32_backdoor(r0: u32, r1: u32, r2: u32, r3: u32) -> i32;
    }
}
// (cargo test: no machine, no backdoor)
#[cfg(not(target_arch = "wasm32"))]
mod js {
    pub unsafe fn a32_backdoor(_r0: u32, _r1: u32, _r2: u32, _r3: u32) -> i32 { super::NOT_HANDLED }
}

/// Whether the undefined instruction `word` (`length` bytes; T32's two
/// halfwords first << 16 | second) is a backdoor call; if it is, the call
/// was made and r0 holds its answer
pub fn call(word: u32, length: u32, thumb: bool) -> bool {
    let encoding = if thumb { length == 4 && word == 0xF7F8_A664 } else { word == 0xE7F8_66F4 };
    if !encoding || crate::aarch64::cpu::el() != 0 {
        return false;
    }
    let reg = crate::aarch64::a32::reg;
    let r0 = reg(0);
    if r0 >> 16 != CALL {
        return false;
    }
    let answer = unsafe { js::a32_backdoor(r0, reg(1), reg(2), reg(3)) };
    if answer == NOT_HANDLED {
        return false;
    }
    crate::aarch64::a32::set_reg(0, answer as u32);
    true
}

/// (the backdoor device) The physical address of user address `va` for a
/// read or a `write` by PL0 code, as the running core translates it; -1: a
/// fault (not mapped, or not allowed), which the guest library resolves by
/// touching the page and calling again
#[no_mangle]
pub fn a32_backdoor_translate(va: u32, write: bool) -> f64 {
    use crate::aarch64::memory::Access;
    if crate::aarch64::cpu::sctlr() & crate::aarch64::cpu::SCTLR_M == 0 {
        return va as f64;
    }
    let access = if write { Access::Write } else { Access::Read };
    match crate::aarch64::mmu::translate(va as u64, access, true, 1) {
        Ok(t) if !t.device => t.pa as f64,
        _ => -1.0,
    }
}
                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/aarch64/bus.rs                                                                  0000644 0000000 0000000 00000107346 00000000000 014052  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ARM core's physical address space (docs/arm64-virt-android16-plan.md
//! P1.5; the JIT plan's `Bus`): 64-bit physical addresses up to the
//! profile's 40 bits, guest RAM from 0x4000_0000 at backing offset 0 of
//! guest memory (mem8), and regions of ROM (read-only backing), MMIO (with
//! the owner that handles it, also above 4 GiB) and holes. Unlike the x86
//! core's physical bus there is no VGA hole and no 4 GiB split; an access
//! never spans regions (it faults instead, writing nothing).
//!
//! Every write to RAM goes through `write` or `written` (CPU stores, DC
//! ZVA, store-exclusive, DMA, the loader and snapshot restore), which retire
//! code compiled from the page (crate::jitrt::watch, and with cores in
//! workers crate::parallel::code). A change of the map bumps the generation
//! and drops all compiled code and cached translations.
//!
//! Device memory (P7.1: virtio-gpu's host visible memory) is guest memory
//! a device owns, from DEVICE_START in the backing (after RAM and the ROMs),
//! mapped where its BAR is: the cores read and write it as RAM, but their
//! writes mark its pages (the device takes them, a64_device_take_dirty), and
//! compiled code writes it through the interpreter's path (the access cache
//! is not filled for it).
//!
//! Extended RAM (P8.5: RAM beyond the one allocation of guest memory) is a
//! region at or above 4 GiB that crate::aarch64::extended keeps (a host store
//! cached in frames): the cores read and write it a page at a time, code is
//! compiled from it under its own code keys (from EXTENDED_CODE_KEY on), the
//! access cache is not filled for it.
//!
//! With cores in workers (P8.2), the map is the machine instance's: a
//! worker keeps a copy (`sync_worker`), taken again when the machine's
//! generation changes; the machine changes it under MAP_SEQ (odd while
//! changing), so that a copy made meanwhile is made again. Device memory's
//! marks are the machine's words, set and taken atomically.
//!
//! JavaScript passes 64-bit addresses as two 32-bit halves (low, high).

use crate::page::Page;

/// Guest RAM's base
pub const RAM_BASE: u64 = 0x4000_0000;
/// The physical address range of profile v86-aarch64-v1 (40 bits)
pub const PA_LIMIT: u64 = 1 << 40;
/// The largest access: a Q register (larger SIMD accesses are split into these)
pub const MAX_ACCESS: u32 = 16;
/// The largest probe (DC ZVA, an exclusive pair): one 64-byte granule
pub const MAX_PROBE: u64 = 64;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    /// read-only backing at `backing` in guest memory
    Rom { backing: u32 },
    /// a device: its accesses go to the owner (src/virt), offset from the region's base
    Mmio { owner: u32 },
    /// device memory at `backing` (at or above DEVICE_START): guest memory whose written pages are marked
    Device { backing: u32 },
    /// extended RAM (crate::aarch64::extended)
    Extended,
}

/// The code key of extended RAM's first page (the keys of guest memory are
/// its pages, below 2 GiB)
pub const EXTENDED_CODE_KEY: u32 = 1 << 20;

/// What a physical address is
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Lookup {
    /// guest memory at `backing` (RAM, or ROM when not `writable`); compiled
    /// code from it is watched under `code_key`
    Ram {
        backing: u32,
        code_key: u32,
        writable: bool,
    },
    Mmio {
        owner: u32,
        offset: u64,
    },
    /// extended RAM: `page` from its start
    Extended {
        page: u32,
    },
    Hole,
}

/// A synchronous external abort or (beyond the PA range) an address size fault
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Fault {
    External,
    AddressSize,
}

#[derive(Clone, Copy)]
struct Region {
    base: u64,
    size: u64,
    kind: Kind,
}

pub struct AddressSpace {
    ram_size: u64,
    /// the non-RAM regions, sorted by base, not overlapping
    regions: Vec<Region>,
    generation: u32,
}

static mut BUS: AddressSpace = AddressSpace {
    ram_size: 0,
    regions: Vec::new(),
    generation: 0,
};
/// Guest memory's base in the Wasm memory (crate::aarch64::root's Env.mem8)
pub static mut MEM8: *mut u8 = std::ptr::null_mut();
/// The bytes of guest memory (RAM and the ROMs after it)
pub static mut MEM8_SIZE: u32 = 0;
/// Where device memory starts in guest memory (u32::MAX: there is none)
pub static mut DEVICE_START: u32 = u32::MAX;
/// One bit per 4 KiB page of device memory, from DEVICE_START: written by a core since its device took it
static mut DEVICE_DIRTY: Vec<u64> = Vec::new();
/// The words a64_device_take_dirty hands out
static mut DEVICE_TAKEN: Vec<u64> = Vec::new();

#[inline(always)]
pub fn bus() -> &'static AddressSpace { unsafe { &*(&raw const BUS) } }

/// The bus behind compiled code's access cache (jitrt::access::Bus,
/// docs/jit-unification-plan.md P5.8; the A64 page tier is J2): writable
/// RAM only, never ROM, a device or a hole
impl crate::jitrt::access::Bus for AddressSpace {
    fn ram_backing(&self, physical: u64) -> Option<u32> {
        match self.lookup(physical & !4095) {
            Lookup::Ram {
                backing,
                writable: true,
                ..
            } => Some(backing),
            _ => None,
        }
    }
}
#[inline(always)]
fn bus_mut() -> &'static mut AddressSpace { unsafe { &mut *(&raw mut BUS) } }

impl AddressSpace {
    #[inline(always)]
    pub fn ram_size(&self) -> u64 { self.ram_size }
    #[inline(always)]
    pub fn generation(&self) -> u32 { self.generation }

    /// What `pa` is
    #[inline]
    pub fn lookup(&self, pa: u64) -> Lookup {
        let offset = pa.wrapping_sub(RAM_BASE);
        if offset < self.ram_size {
            return Lookup::Ram {
                backing: offset as u32,
                code_key: (offset >> 12) as u32,
                writable: true,
            };
        }
        match self.region_of(pa) {
            Some(r) => match r.kind {
                Kind::Rom { backing } => {
                    let at = backing + (pa - r.base) as u32;
                    Lookup::Ram {
                        backing: at,
                        code_key: at >> 12,
                        writable: false,
                    }
                },
                Kind::Mmio { owner } => Lookup::Mmio {
                    owner,
                    offset: pa - r.base,
                },
                Kind::Device { backing } => {
                    let at = backing + (pa - r.base) as u32;
                    Lookup::Ram {
                        backing: at,
                        code_key: at >> 12,
                        writable: true,
                    }
                },
                Kind::Extended => Lookup::Extended {
                    page: ((pa - r.base) >> 12) as u32,
                },
            },
            None => Lookup::Hole,
        }
    }

    fn region_of(&self, pa: u64) -> Option<&Region> {
        let i = self.regions.partition_point(|r| r.base <= pa);
        let r = self.regions.get(i.checked_sub(1)?)?;
        (pa - r.base < r.size).then_some(r)
    }

    /// The region (RAM, a ROM, a device) holding all of [pa, pa + len), or a
    /// fault: a hole, beyond the PA range, or more than one region
    pub fn span(&self, pa: u64, len: u64) -> Result<Lookup, Fault> {
        debug_assert!(len >= 1);
        let last = pa.checked_add(len - 1).ok_or(Fault::AddressSize)?;
        if last >= PA_LIMIT {
            return Err(Fault::AddressSize);
        }
        let first = self.lookup(pa);
        let end = self.lookup(last);
        match (first, end) {
            (
                Lookup::Ram {
                    backing: a,
                    writable: wa,
                    ..
                },
                Lookup::Ram {
                    backing: b,
                    writable: wb,
                    ..
                },
            ) if wa == wb && b.wrapping_sub(a) as u64 == len - 1 => Ok(first),
            (
                Lookup::Mmio {
                    owner: a,
                    offset: o,
                },
                Lookup::Mmio {
                    owner: b,
                    offset: p,
                },
            ) if a == b && p - o == len - 1 => Ok(first),
            (Lookup::Extended { .. }, Lookup::Extended { .. }) => Ok(first),
            _ => Err(Fault::External),
        }
    }

    /// The code key of the page `pa` is on, if it is guest memory
    pub fn code_key(&self, pa: u64) -> Option<u32> {
        match self.lookup(pa) {
            Lookup::Ram { code_key, .. } => Some(code_key),
            Lookup::Extended { page } => Some(EXTENDED_CODE_KEY + page),
            _ => None,
        }
    }

    fn map(&mut self, base: u64, size: u64, kind: Kind) -> bool {
        let Some(end) = base.checked_add(size)
        else {
            return false;
        };
        if size == 0 || end > PA_LIMIT {
            return false;
        }
        // (not over RAM or another region)
        if base < RAM_BASE + self.ram_size && end > RAM_BASE {
            return false;
        }
        let i = self.regions.partition_point(|r| r.base < base);
        if self.regions.get(i).is_some_and(|r| r.base < end)
            || i > 0 && self.regions[i - 1].base + self.regions[i - 1].size > base
        {
            return false;
        }
        if let Kind::Rom { backing } = kind {
            if backing as u64 + size > unsafe { MEM8_SIZE } as u64 {
                return false;
            }
        }
        if kind == Kind::Extended && (base | size) & 0xFFF != 0 {
            return false;
        }
        if let Kind::Device { backing } = kind {
            if backing < unsafe { DEVICE_START }
                || backing as u64 + size > unsafe { MEM8_SIZE } as u64
                || (backing | size as u32) & 0xFFF != 0
            {
                return false;
            }
        }
        self.regions.insert(i, Region { base, size, kind });
        self.changed();
        true
    }

    fn unmap(&mut self, base: u64) -> bool {
        let Some(i) = self.regions.iter().position(|r| r.base == base)
        else {
            return false;
        };
        self.regions.remove(i);
        self.changed();
        true
    }

    /// The map changed: translations and compiled code that cached it go
    fn changed(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        run_map_hooks();
    }
}

fn run_map_hooks() {
    for hook in unsafe { &*(&raw const MAP_CHANGED) } {
        hook();
    }
}

/// (cores in workers) odd while the machine instance changes its map
static mut MAP_SEQ: u32 = 0;

/// Change the machine's map (`change`), so that workers copying it meanwhile notice
fn mutate<T>(change: impl FnOnce(&mut AddressSpace) -> T) -> T {
    let seq = &raw mut MAP_SEQ;
    unsafe {
        crate::parallel::word_store(seq, *seq | 1);
        let result = change(bus_mut());
        crate::parallel::word_store(seq, (*seq | 1).wrapping_add(1));
        result
    }
}

/// A worker's copy of the machine's map and guest memory (P8.2): at its
/// attachment, after a stop, and when the machine's generation changed
pub unsafe fn sync_worker() {
    let machine = &*crate::parallel::machine(&raw mut BUS);
    let seq = crate::parallel::machine(&raw mut MAP_SEQ);
    MEM8 = *crate::parallel::machine(&raw mut MEM8);
    MEM8_SIZE = *crate::parallel::machine(&raw mut MEM8_SIZE);
    DEVICE_START = *crate::parallel::machine(&raw mut DEVICE_START);
    let b = bus_mut();
    loop {
        let before = crate::parallel::word_load(seq);
        if before & 1 != 0 {
            std::hint::spin_loop();
            continue;
        }
        // (the machine's Vec may be changing: its length is checked, a torn copy made again)
        let (pointer, length) = (machine.regions.as_ptr(), machine.regions.len());
        if length <= 4096 {
            b.regions.clear();
            b.regions
                .extend_from_slice(std::slice::from_raw_parts(pointer, length));
            b.ram_size = machine.ram_size;
            b.generation = machine.generation;
        }
        if crate::parallel::word_load(seq) == before && length <= 4096 {
            WORKER_SEQ = before;
            break;
        }
    }
    run_map_hooks();
}

/// The machine's MAP_SEQ when the worker's copy was made
static mut WORKER_SEQ: u32 = 0;
/// (cores in workers, each slice) copy the map again if the machine changed it
#[inline]
pub unsafe fn sync_worker_if_stale() {
    if crate::parallel::word_load(crate::parallel::machine(&raw mut MAP_SEQ)) != WORKER_SEQ {
        sync_worker();
    }
}

/// Called when the map changes (the TLB, compiled code: crate::aarch64::root)
static mut MAP_CHANGED: Vec<fn()> = Vec::new();
pub fn on_map_changed(hook: fn()) { unsafe { (*(&raw mut MAP_CHANGED)).push(hook) } }

#[cfg(target_arch = "wasm32")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn a64_mmio_read(owner: u32, offset: u64, size: u32) -> u64;
        pub fn a64_mmio_write(owner: u32, offset: u64, size: u32, value: u64);
    }
}
// (cargo test: a device that reads its offset and keeps the last write)
#[cfg(not(target_arch = "wasm32"))]
mod js {
    pub static mut LAST_WRITE: (u32, u64, u32, u64) = (0, 0, 0, 0);
    pub unsafe fn a64_mmio_read(owner: u32, offset: u64, size: u32) -> u64 {
        offset ^ (owner as u64) << 32 ^ (size as u64) << 48
    }
    pub unsafe fn a64_mmio_write(owner: u32, offset: u64, size: u32, value: u64) {
        LAST_WRITE = (owner, offset, size, value)
    }
}

#[inline(always)]
unsafe fn host(backing: u32) -> *mut u8 { MEM8.add(backing as usize) }

/// A write of the running core reached guest memory at `backing` (len
/// bytes, within one page or across pages): retire code compiled from the
/// pages, clear other cores' exclusive reservations of its granules
#[inline]
pub fn written(backing: u32, len: u32) {
    if len == 0 {
        return;
    }
    if backing >= unsafe { DEVICE_START } {
        device_written(backing, len);
    }
    crate::aarch64::smp::monitors_written(backing, len, false);
    retire_code(backing, len);
}

/// A core wrote device memory: its pages are marked (the machine's words)
#[cold]
fn device_written(backing: u32, len: u32) {
    let dirty = unsafe { &*crate::parallel::machine(&raw mut DEVICE_DIRTY) };
    let start = unsafe { DEVICE_START };
    for page in (backing - start) >> 12..=(backing - start + (len - 1)) >> 12 {
        if (page as usize / 64) < dirty.len() {
            unsafe {
                crate::parallel::or64(
                    dirty.as_ptr().add(page as usize / 64) as *mut u8,
                    1 << (page % 64),
                )
            };
        }
    }
}

/// Retire code compiled from the pages of [backing, backing + len), by
/// this core and (cores in workers) the others
#[inline]
fn retire_code(backing: u32, len: u32) {
    let first = backing >> 12;
    let last = (backing + (len - 1)) >> 12;
    for page in first..=last {
        if crate::aarch64::root::page_watched(page) {
            let lo = if page == first { backing & 0xFFF } else { 0 };
            let hi = if page == last { ((backing + (len - 1)) & 0xFFF) + 1 } else { 0x1000 };
            crate::aarch64::root::dirty_bytes(Page::page_of(page << 12), lo, hi);
            unsafe { crate::parallel::code::written(page) };
        }
    }
}

/// The owners of the devices the ARM core decodes itself (the GIC's
/// distributor and redistributors, P4.2); src/virt's owners count from 1
pub const OWNER_GICD: u32 = 0xFFFF_0000;
pub const OWNER_GICR: u32 = 0xFFFF_0001;
/// (a GICv2's CPU interface)
pub const OWNER_GICC: u32 = 0xFFFF_0002;

#[inline(always)]
unsafe fn mmio_read(owner: u32, offset: u64, size: u32) -> u64 {
    match owner {
        OWNER_GICD => crate::aarch64::gic::gicd_read(offset, size),
        OWNER_GICR => crate::aarch64::gic::gicr_read(offset, size),
        OWNER_GICC => crate::aarch64::gic::gicc_read(offset, size),
        _ => js::a64_mmio_read(owner, offset, size),
    }
}

#[inline(always)]
unsafe fn mmio_write(owner: u32, offset: u64, size: u32, value: u64) {
    match owner {
        OWNER_GICD => crate::aarch64::gic::gicd_write(offset, size, value),
        OWNER_GICR => crate::aarch64::gic::gicr_write(offset, size, value),
        OWNER_GICC => crate::aarch64::gic::gicc_write(offset, size, value),
        _ => js::a64_mmio_write(owner, offset, size, value),
    }
}

/// Map the GIC's frames for `cores` cores (the machine's devices, P4.2)
#[no_mangle]
pub unsafe fn a64_set_cores(cores: u32) -> bool {
    let cores = (cores as usize).clamp(1, crate::isa::MAX_CORES);
    *crate::parallel::machine(&raw mut crate::aarch64::isa_hooks::CORE_COUNT) = cores;
    let v2 = crate::aarch64::gic::is_v2();
    mutate(|b| {
        b.unmap(crate::aarch64::gic::GICD_BASE);
        b.unmap(crate::aarch64::gic::GICR_BASE);
        b.unmap(crate::aarch64::gic::GICC_BASE);
        b.map(
            crate::aarch64::gic::GICD_BASE,
            crate::aarch64::gic::GICD_SIZE,
            Kind::Mmio { owner: OWNER_GICD },
        ) && if v2 {
            // (a GICv2: its CPU interface, no redistributors)
            b.map(
                crate::aarch64::gic::GICC_BASE,
                crate::aarch64::gic::GICC_SIZE,
                Kind::Mmio { owner: OWNER_GICC },
            )
        }
        else {
            b.map(
                crate::aarch64::gic::GICR_BASE,
                crate::aarch64::gic::GICR_STRIDE * cores as u64,
                Kind::Mmio { owner: OWNER_GICR },
            )
        }
    })
}

/// Read `size` bytes (1, 2, 4, 8) at `pa`, little-endian
pub unsafe fn read(pa: u64, size: u32) -> Result<u64, Fault> {
    debug_assert!(matches!(size, 1 | 2 | 4 | 8));
    match bus().span(pa, size as u64)? {
        Lookup::Ram { backing, .. } => {
            let p = host(backing);
            Ok(match size {
                1 => crate::parallel::load8(p) as u64,
                2 => crate::parallel::load16(p) as u64,
                4 => crate::parallel::load32(p) as u64,
                _ => crate::parallel::load64(p),
            })
        },
        Lookup::Mmio { owner, offset } => Ok(mmio_read(owner, offset, size)),
        Lookup::Extended { .. } => Ok(crate::aarch64::extended::read(pa, size)),
        Lookup::Hole => Err(Fault::External),
    }
}

/// Write `size` bytes (1, 2, 4, 8) at `pa`, little-endian; a write to ROM is ignored
pub unsafe fn write(pa: u64, size: u32, value: u64) -> Result<(), Fault> {
    debug_assert!(matches!(size, 1 | 2 | 4 | 8));
    match bus().span(pa, size as u64)? {
        Lookup::Ram {
            backing, writable, ..
        } => {
            if writable {
                let p = host(backing);
                match size {
                    1 => crate::parallel::store8(p, value as u8),
                    2 => crate::parallel::store16(p, value as u16),
                    4 => crate::parallel::store32(p, value as u32),
                    _ => crate::parallel::store64(p, value),
                }
                written(backing, size);
            }
            Ok(())
        },
        Lookup::Mmio { owner, offset } => {
            mmio_write(owner, offset, size, value);
            Ok(())
        },
        Lookup::Extended { .. } => {
            crate::aarch64::extended::write(pa, size, value);
            Ok(())
        },
        Lookup::Hole => Err(Fault::External),
    }
}

/// Read a Q register's 16 bytes at `pa` (a device sees two 8-byte reads)
pub unsafe fn read128(pa: u64) -> Result<u128, Fault> {
    match bus().span(pa, 16)? {
        Lookup::Ram { backing, .. } => {
            let [lo, hi] = crate::parallel::load128(host(backing));
            Ok(lo as u128 | (hi as u128) << 64)
        },
        Lookup::Mmio { owner, offset } => {
            let lo = mmio_read(owner, offset, 8);
            let hi = mmio_read(owner, offset + 8, 8);
            Ok(lo as u128 | (hi as u128) << 64)
        },
        Lookup::Extended { .. } => {
            let lo = crate::aarch64::extended::read(pa, 8);
            let hi = crate::aarch64::extended::read(pa + 8, 8);
            Ok(lo as u128 | (hi as u128) << 64)
        },
        Lookup::Hole => Err(Fault::External),
    }
}

/// Write a Q register's 16 bytes at `pa`, all or nothing
pub unsafe fn write128(pa: u64, value: u128) -> Result<(), Fault> {
    match bus().span(pa, 16)? {
        Lookup::Ram {
            backing, writable, ..
        } => {
            if writable {
                crate::parallel::store128(host(backing), [value as u64, (value >> 64) as u64]);
                written(backing, 16);
            }
            Ok(())
        },
        Lookup::Mmio { owner, offset } => {
            mmio_write(owner, offset, 8, value as u64);
            mmio_write(owner, offset + 8, 8, (value >> 64) as u64);
            Ok(())
        },
        Lookup::Extended { .. } => {
            let _guard = crate::extended::Guard::new();
            crate::aarch64::extended::write(pa, 8, value as u64);
            crate::aarch64::extended::write(pa + 8, 8, (value >> 64) as u64);
            Ok(())
        },
        Lookup::Hole => Err(Fault::External),
    }
}

/// Whether [pa, pa + len) (at most 64 bytes) is one region of guest memory
/// that may be written, where (DC ZVA, a store-exclusive pair) an access
/// completes at once: its backing
pub fn probe_writable(pa: u64, len: u64) -> Result<Option<u32>, Fault> {
    debug_assert!(len >= 1 && len <= MAX_PROBE);
    Ok(match bus().span(pa, len)? {
        Lookup::Ram {
            backing,
            writable: true,
            ..
        } => Some(backing),
        Lookup::Hole => return Err(Fault::External),
        _ => None,
    })
}

const fn pa(low: u32, high: u32) -> u64 { low as u64 | (high as u64) << 32 }

/// Guest memory of `size` bytes (RAM first, then any ROM backing): its
/// address in the Wasm memory. Once, before the RAM is mapped.
#[no_mangle]
pub unsafe fn a64_allocate_memory(size: u32) -> u32 {
    assert!(MEM8.is_null(), "a64_allocate_memory: already allocated");
    let memory = vec![0u8; size as usize].leak();
    MEM8 = memory.as_mut_ptr();
    MEM8_SIZE = size;
    MEM8 as u32
}

/// RAM of `size` bytes at 0x4000_0000, backed by the start of guest memory
#[no_mangle]
pub unsafe fn a64_bus_set_ram(size: u32) -> bool {
    if size > MEM8_SIZE
        || bus()
            .regions
            .iter()
            .any(|r| r.base < RAM_BASE + size as u64 && r.base + r.size > RAM_BASE)
    {
        return false;
    }
    mutate(|b| {
        b.ram_size = size as u64;
        b.changed();
    });
    true
}

/// Map a device's registers (`owner`, src/virt) at [base, base + size)
#[no_mangle]
pub unsafe fn a64_bus_map_mmio(
    base_low: u32,
    base_high: u32,
    size_low: u32,
    size_high: u32,
    owner: u32,
) -> bool {
    mutate(|b| {
        b.map(
            pa(base_low, base_high),
            pa(size_low, size_high),
            Kind::Mmio { owner },
        )
    })
}
/// Map read-only guest memory at [base, base + size), from `backing`
#[no_mangle]
pub unsafe fn a64_bus_map_rom(
    base_low: u32,
    base_high: u32,
    size_low: u32,
    size_high: u32,
    backing: u32,
) -> bool {
    mutate(|b| {
        b.map(
            pa(base_low, base_high),
            pa(size_low, size_high),
            Kind::Rom { backing },
        )
    })
}
/// Device memory from `start` to the end of guest memory (once, after
/// a64_allocate_memory; `start` page aligned, at or after the RAM's end)
#[no_mangle]
pub unsafe fn a64_device_memory(start: u32) -> bool {
    if start & 0xFFF != 0 || start > MEM8_SIZE || (start as u64) < bus().ram_size {
        return false;
    }
    DEVICE_START = start;
    let pages = (MEM8_SIZE - start).div_ceil(4096) as usize;
    *(&raw mut DEVICE_DIRTY) = vec![0; pages.div_ceil(64)];
    true
}
/// Map device memory at [base, base + size), from `backing` (page aligned, device memory)
#[no_mangle]
pub unsafe fn a64_bus_map_device(
    base_low: u32,
    base_high: u32,
    size_low: u32,
    size_high: u32,
    backing: u32,
) -> bool {
    mutate(|b| {
        b.map(
            pa(base_low, base_high),
            pa(size_low, size_high),
            Kind::Device { backing },
        )
    })
}
/// Take the marks of the pages of [backing, backing + size) of device
/// memory (backing 256 KiB aligned from DEVICE_START): the address of words
/// with a bit a page, the first page bit 0 of the first word, 64 a word;
/// 0 when none was written. The marks clear.
#[no_mangle]
pub unsafe fn a64_device_take_dirty(backing: u32, size: u32) -> u32 {
    take_device_dirty(backing, size).map_or(0, |words| words.as_ptr() as u32)
}
unsafe fn take_device_dirty(backing: u32, size: u32) -> Option<&'static [u64]> {
    let dirty = &mut *(&raw mut DEVICE_DIRTY);
    let taken = &mut *(&raw mut DEVICE_TAKEN);
    let offset = backing.checked_sub(DEVICE_START)?;
    debug_assert!(offset % (64 * 4096) == 0);
    let first = (offset >> 18) as usize;
    let count = (size.div_ceil(4096) as usize).div_ceil(64);
    taken.clear();
    let mut any = false;
    for i in first..(first + count).min(dirty.len()) {
        // (cores in workers mark them meanwhile)
        let word = crate::parallel::swap64(&raw mut dirty[i], 0);
        any |= word != 0;
        taken.push(word);
    }
    any.then_some(&taken[..])
}
/// Mark every page of [backing, backing + size) of device memory written
#[no_mangle]
pub unsafe fn a64_device_mark_dirty(backing: u32, size: u32) {
    if backing >= DEVICE_START && size != 0 {
        device_written(backing, size);
    }
}
/// Map extended RAM at [base, base + size) (crate::aarch64::extended)
pub fn map_extended(base: u64, size: u64) -> bool { mutate(|b| b.map(base, size, Kind::Extended)) }

/// Unmap the region at `base`
#[no_mangle]
pub unsafe fn a64_bus_unmap(base_low: u32, base_high: u32) -> bool {
    mutate(|b| b.unmap(pa(base_low, base_high)))
}
#[no_mangle]
pub fn a64_bus_generation() -> u32 { bus().generation() }

/// What `pa` is: 0 a hole, 1 RAM, 2 ROM, 3 MMIO, 4 extended RAM
/// (a64_bus_lookup_detail: the backing, the owner or the extended page)
#[no_mangle]
pub fn a64_bus_lookup(pa_low: u32, pa_high: u32) -> u32 {
    match bus().lookup(pa(pa_low, pa_high)) {
        Lookup::Hole => 0,
        Lookup::Ram { writable: true, .. } => 1,
        Lookup::Ram { .. } => 2,
        Lookup::Mmio { .. } => 3,
        Lookup::Extended { .. } => 4,
    }
}
#[no_mangle]
pub fn a64_bus_lookup_detail(pa_low: u32, pa_high: u32) -> f64 {
    match bus().lookup(pa(pa_low, pa_high)) {
        Lookup::Hole => -1.0,
        Lookup::Ram { backing, .. } => backing as f64,
        Lookup::Mmio { owner, .. } => owner as f64,
        Lookup::Extended { page } => page as f64,
    }
}
/// The code key of `pa`'s page, -1 when it is not guest memory
#[no_mangle]
pub fn a64_bus_code_key(pa_low: u32, pa_high: u32) -> i32 {
    bus()
        .code_key(pa(pa_low, pa_high))
        .map_or(-1, |key| key as i32)
}

/// A read through the bus (tests, the debugger): the value, or with
/// a64_bus_status 1 an external abort, 2 an address size fault
static mut STATUS: u32 = 0;
#[no_mangle]
pub fn a64_bus_status() -> u32 { unsafe { STATUS } }
fn status(result: Result<(), Fault>) {
    unsafe {
        STATUS = match result {
            Ok(()) => 0,
            Err(Fault::External) => 1,
            Err(Fault::AddressSize) => 2,
        }
    }
}
#[no_mangle]
pub unsafe fn a64_bus_read(pa_low: u32, pa_high: u32, size: u32) -> u64 {
    let result = read(pa(pa_low, pa_high), size);
    status(result.map(|_| ()));
    result.unwrap_or(0)
}
#[no_mangle]
pub unsafe fn a64_bus_write(pa_low: u32, pa_high: u32, size: u32, value: u64) -> u32 {
    status(write(pa(pa_low, pa_high), size, value));
    STATUS
}
/// JavaScript wrote guest memory at [backing, backing + len) (the loader,
/// snapshot restore, a device's DMA): retire code compiled from it
#[no_mangle]
pub fn a64_bus_written(backing: u32, len: u32) {
    // (a device's write: every core's reservation of the granules clears)
    if len != 0 {
        crate::aarch64::smp::monitors_written(backing, len, true);
        retire_code(backing, len);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    unsafe fn setup(ram: u32, extra: u32) {
        let b = bus_mut();
        b.regions.clear();
        b.ram_size = 0;
        MEM8 = std::ptr::null_mut();
        DEVICE_START = u32::MAX;
        a64_allocate_memory(ram + extra);
        assert!(a64_bus_set_ram(ram));
    }

    /// Device memory (P7.1): read and written as RAM where it is mapped,
    /// the pages the cores write marked, a device's own writes not
    #[test]
    fn device_memory() {
        unsafe {
            setup(1 << 20, 1 << 20);
            let start = 1 << 20;
            assert!(
                !a64_bus_map_device(0, 0x80, 0x40000, 0, start),
                "no device memory yet"
            );
            assert!(a64_device_memory(start));
            assert!(
                !a64_bus_map_device(0, 0x80, 0x40000, 0, 0x1000),
                "RAM is no device memory"
            );
            assert!(a64_bus_map_device(0, 0x80, 0x80000, 0, start + 0x40000));
            let take = || take_device_dirty(start + 0x40000, 0x80000).map(|words| words.to_vec());
            assert_eq!(take(), None, "nothing written yet");
            assert_eq!(write(0x80_0000_1008, 8, 0x1122_3344_5566_7788), Ok(()));
            assert_eq!(
                write(0x80_0004_5ffe, 4, 0xAABB_CCDD),
                Ok(()),
                "across two pages"
            );
            assert_eq!(read(0x80_0000_1008, 8), Ok(0x1122_3344_5566_7788));
            assert_eq!(*host(start + 0x40000 + 0x100c), 0x44, "at its backing");
            assert_eq!(
                take(),
                Some(vec![1 << 1, 1 << 5 | 1 << 6]),
                "pages 1, 0x45 and 0x46"
            );
            assert_eq!(take(), None, "taken: clear");
            // (a device's own writes, through JavaScript, are not marked)
            a64_bus_written(start + 0x40000, 4096);
            assert_eq!(take(), None);
            a64_device_mark_dirty(start + 0x40000 + 0x2000, 1);
            assert_eq!(take(), Some(vec![1 << 2, 0]));
            assert!(a64_bus_unmap(0, 0x80));
            assert_eq!(bus().lookup(0x80_0000_1008), Lookup::Hole);
        }
    }

    #[test]
    fn address_space() {
        unsafe {
            setup(1 << 20, 0x10000);
            let b = bus();
            assert_eq!(
                b.lookup(RAM_BASE),
                Lookup::Ram {
                    backing: 0,
                    code_key: 0,
                    writable: true
                }
            );
            assert_eq!(
                b.lookup(RAM_BASE + 0x1234),
                Lookup::Ram {
                    backing: 0x1234,
                    code_key: 1,
                    writable: true
                }
            );
            assert_eq!(b.lookup(RAM_BASE + (1 << 20)), Lookup::Hole);
            assert_eq!(b.lookup(0), Lookup::Hole);
            // a 0x200 window inside a 128 KiB block, and devices above 4 GiB
            let generation = b.generation();
            assert!(a64_bus_map_mmio(0x0a00_0200, 0, 0x200, 0, 7));
            assert!(a64_bus_map_mmio(0x0a00_0400, 0, 0x200, 0, 8));
            assert!(a64_bus_map_mmio(0x1000_0000, 0x40, 0x1000_0000, 0, 9));
            assert!(a64_bus_map_mmio(0, 0x80, 0x1000, 0, 10));
            assert_ne!(b.generation(), generation);
            assert!(!a64_bus_map_mmio(0x0a00_0300, 0, 0x200, 0, 11), "overlap");
            assert!(!a64_bus_map_mmio(0x4000_0000, 0, 0x1000, 0, 11), "over RAM");
            assert!(!a64_bus_map_mmio(0, 0x100, 0x1000, 0, 11), "beyond 40 bits");
            assert_eq!(b.lookup(0x0a00_01ff), Lookup::Hole);
            assert_eq!(
                b.lookup(0x0a00_0200),
                Lookup::Mmio {
                    owner: 7,
                    offset: 0
                }
            );
            assert_eq!(
                b.lookup(0x0a00_03ff),
                Lookup::Mmio {
                    owner: 7,
                    offset: 0x1ff
                }
            );
            assert_eq!(
                b.lookup(0x0a00_0400),
                Lookup::Mmio {
                    owner: 8,
                    offset: 0
                }
            );
            assert_eq!(
                b.lookup(0x40_1000_0010),
                Lookup::Mmio {
                    owner: 9,
                    offset: 0x10
                }
            );
            assert_eq!(
                b.lookup(0x80_0000_0fff),
                Lookup::Mmio {
                    owner: 10,
                    offset: 0xfff
                }
            );
            // 16-bit and 64-bit device accesses
            assert_eq!(read(0x0a00_0204, 2), Ok(0x4 ^ 7 << 32 ^ 2 << 48));
            write(0x80_0000_0008, 8, 0x1122_3344_5566_7788).unwrap();
            assert_eq!(
                *&raw const js::LAST_WRITE,
                (10, 8, 8, 0x1122_3344_5566_7788)
            );
            // RAM
            write(RAM_BASE + 8, 8, 0x0102_0304_0506_0708).unwrap();
            assert_eq!(read(RAM_BASE + 8, 4), Ok(0x0506_0708));
            assert_eq!(read(RAM_BASE + 12, 2), Ok(0x0304));
            write128(RAM_BASE + 0x100, 0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0000_1111).unwrap();
            assert_eq!(
                read128(RAM_BASE + 0x100),
                Ok(0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0000_1111)
            );
            // an access over the end of RAM faults and writes nothing
            let end = RAM_BASE + (1 << 20);
            write(end - 8, 8, 0).unwrap();
            assert_eq!(write(end - 4, 8, u64::MAX), Err(Fault::External));
            assert_eq!(read(end - 8, 8), Ok(0));
            assert_eq!(
                read(0x0a00_03fe, 4),
                Err(Fault::External),
                "across two devices"
            );
            assert_eq!(read(1 << 40, 1), Err(Fault::AddressSize));
            assert_eq!(read(0x0900_0000, 4), Err(Fault::External));
            // ROM: reads its backing, ignores writes; its own code keys
            assert!(a64_bus_map_rom(0, 0, 0x10000, 0, 1 << 20));
            *MEM8.add((1 << 20) + 4) = 0x5a;
            assert_eq!(read(4, 1), Ok(0x5a));
            write(4, 1, 0).unwrap();
            assert_eq!(read(4, 1), Ok(0x5a));
            assert_eq!(b.code_key(0x2000), Some(((1 << 20) + 0x2000) >> 12));
            assert_eq!(b.code_key(0x0a00_0200), None);
            // probes
            assert_eq!(probe_writable(RAM_BASE + 0x40, 64), Ok(Some(0x40)));
            assert_eq!(probe_writable(0x40, 64), Ok(None));
            assert_eq!(probe_writable(end - 32, 64), Err(Fault::External));
            assert!(a64_bus_unmap(0x0a00_0200, 0));
            assert_eq!(b.lookup(0x0a00_0200), Lookup::Hole);
        }
    }

    /// A fill of a page-function access cache (the JIT plan's jac, as
    /// x64::pages::x64_page_access does): a guest page resolved to a host
    /// pointer and a code key, valid while the generation stays
    #[test]
    fn access_cache_fill() {
        unsafe {
            setup(1 << 16, 0);
            struct Entry {
                page: u64,
                host: *mut u8,
                code_key: u32,
                generation: u32,
            }
            let fill = |pa: u64| match bus().span(pa & !0xFFF, 0x1000) {
                Ok(Lookup::Ram {
                    backing,
                    code_key,
                    writable: true,
                }) => Some(Entry {
                    page: pa & !0xFFF,
                    host: host(backing),
                    code_key,
                    generation: bus().generation(),
                }),
                _ => None,
            };
            let entry = fill(RAM_BASE + 0x3008).unwrap();
            assert_eq!(entry.page, RAM_BASE + 0x3000);
            assert_eq!(entry.code_key, 3);
            *entry.host.add(8) = 0x77;
            assert_eq!(read(RAM_BASE + 0x3008, 1), Ok(0x77));
            assert!(fill(0x0900_0000).is_none());
            a64_bus_map_mmio(0x0900_0000, 0, 0x1000, 0, 1);
            assert_ne!(
                entry.generation,
                bus().generation(),
                "the map changed: the entry is stale"
            );
        }
    }
}
                                                                                                                                                                                                                                                                                          source/v64/src/rust/aarch64/cpu.rs                                                                  0000644 0000000 0000000 00000043451 00000000000 014044  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The AArch64 core's architectural state and exceptions
//! (docs/arm64-virt-android16-plan.md P2, P3): the registers in the state
//! block (crate::aarch64::state), PSTATE, the banked stack pointers, and
//! synchronous exception entry and return at EL1. An instruction that faults
//! has written no state (P2.9): it computes everything, then commits.

use crate::aarch64::state::*;

// PSTATE bits in `pstate` (as SPSR_EL1 lays them out; NZCV is in `nzcv`)
pub const PSTATE_SP: u32 = 1 << 0;
pub const PSTATE_EL_SHIFT: u32 = 2;
pub const PSTATE_F: u32 = 1 << 6;
pub const PSTATE_I: u32 = 1 << 7;
pub const PSTATE_A: u32 = 1 << 8;
pub const PSTATE_D: u32 = 1 << 9;
pub const PSTATE_DAIF: u32 = 0xF << 6;
pub const PSTATE_IL: u32 = 1 << 20;
pub const PSTATE_SS: u32 = 1 << 21;
/// Privileged Access Never (FEAT_PAN, profile v2): EL1's data accesses to
/// memory EL0 may access fault, but the unprivileged ones (LDTR, STTR)
pub const PSTATE_PAN: u32 = 1 << 22;
/// The bits of `pstate` an SPSR keeps (M[4:0] as AArch64 EL0t/EL1t/EL1h, DAIF, IL, SS, PAN)
pub const PSTATE_SAVED: u32 = 0x1F | PSTATE_DAIF | PSTATE_IL | PSTATE_SS | PSTATE_PAN;

// AArch32 at EL0 (profile v3, docs/aarch32-plan.md): `pstate` as an
// AArch32 SPSR lays it out, M[4:0] the User mode (0b10000: M[4] is nRW)
pub const PSTATE_NRW: u32 = 1 << 4;
pub const PSTATE_T: u32 = 1 << 5;
/// AArch32's endianness bit (where AArch64 has D)
pub const PSTATE_E: u32 = 1 << 9;
/// ITSTATE: IT[7:2] in bits 15:10, IT[1:0] in bits 26:25
pub const PSTATE_IT: u32 = 0x3F << 10 | 3 << 25;
pub const PSTATE_GE: u32 = 0xF << 16;
pub const PSTATE_Q: u32 = 1 << 27;
/// AArch32 User mode (M[4:0])
pub const MODE_USER: u32 = 0b10000;
/// The bits of an AArch32 `pstate` an SPSR keeps
pub const PSTATE_SAVED_A32: u32 = 0x1F
    | PSTATE_T
    | PSTATE_E
    | PSTATE_A
    | PSTATE_I
    | PSTATE_F
    | PSTATE_IT
    | PSTATE_GE
    | PSTATE_Q
    | PSTATE_IL
    | PSTATE_SS
    | PSTATE_PAN;

pub const NZCV_N: u32 = 1 << 31;
pub const NZCV_Z: u32 = 1 << 30;
pub const NZCV_C: u32 = 1 << 29;
pub const NZCV_V: u32 = 1 << 28;

// SCTLR_EL1 bits
pub const SCTLR_M: u64 = 1 << 0;
pub const SCTLR_A: u64 = 1 << 1;
pub const SCTLR_C: u64 = 1 << 2;
pub const SCTLR_SA: u64 = 1 << 3;
pub const SCTLR_SA0: u64 = 1 << 4;
pub const SCTLR_UMA: u64 = 1 << 9;
pub const SCTLR_DZE: u64 = 1 << 14;
pub const SCTLR_UCT: u64 = 1 << 15;
pub const SCTLR_NTWI: u64 = 1 << 16;
pub const SCTLR_NTWE: u64 = 1 << 18;
pub const SCTLR_E0E: u64 = 1 << 24;
pub const SCTLR_EE: u64 = 1 << 25;
pub const SCTLR_UCI: u64 = 1 << 26;
/// Set Privileged Access Never: when clear, an exception taken to EL1 sets PSTATE.PAN (FEAT_PAN)
pub const SCTLR_SPAN: u64 = 1 << 23;
/// SCTLR_EL1 at reset: the reference's (QEMU 9.2 cortex-a35: SA, SA0,
/// CP15BEN, EOS, nTWI, nTWE, EIS, SPAN)
pub const SCTLR_RESET: u64 = 0x00C5_0838;

// ---- the profile's optional features (a64_set_features)

/// FEAT_PAN (profile v2)
pub const FEATURE_PAN: u32 = 1 << 0;
/// AArch32 at EL0 (profile v3)
pub const FEATURE_AARCH32: u32 = 1 << 1;
/// AArch32 throughout, PL0 and PL1 (cpu_type "arm32", profile arm32-v1:
/// crate::aarch64::a32_system)
pub const FEATURE_A32: u32 = 1 << 2;
static mut FEATURES: u32 = 0;

/// The optional features of the machine's profile: FEATURE_PAN (v2),
/// FEATURE_AARCH32 (v3), FEATURE_A32 (arm32-v1); none in v1 and v1.1
#[no_mangle]
pub fn a64_set_features(mask: u32) {
    unsafe {
        *crate::parallel::machine(&raw mut FEATURES) =
            mask & (FEATURE_PAN | FEATURE_AARCH32 | FEATURE_A32)
    };
    crate::aarch64::tlb::flush(true);
}

/// Whether the profile has FEAT_PAN
#[inline(always)]
pub fn has_pan() -> bool {
    unsafe { *crate::parallel::machine(&raw mut FEATURES) & FEATURE_PAN != 0 }
}

/// Whether the profile has AArch32 at EL0
#[inline(always)]
pub fn has_aarch32() -> bool {
    unsafe { *crate::parallel::machine(&raw mut FEATURES) & FEATURE_AARCH32 != 0 }
}

/// Whether the CPU is AArch32 throughout (cpu_type "arm32")
#[inline(always)]
pub fn a32_only() -> bool {
    unsafe { *crate::parallel::machine(&raw mut FEATURES) & FEATURE_A32 != 0 }
}

/// Whether the core runs AArch32 (EL0's A32 or T32; with a32_only any mode)
#[inline(always)]
pub fn aarch32() -> bool { get_pstate() & PSTATE_NRW != 0 }

// ---- registers

/// X[n] with register 31 as the zero register
#[inline(always)]
pub fn xr(n: u32) -> u64 {
    if n == 31 {
        0
    }
    else {
        unsafe { *x.add(n as usize) }
    }
}
/// X[n] with register 31 as the current stack pointer
#[inline(always)]
pub fn xr_sp(n: u32) -> u64 { unsafe { *x.add(n as usize) } }
/// W[n] (register 31: the zero register)
#[inline(always)]
pub fn wr(n: u32) -> u32 { xr(n) as u32 }
/// Write X[n] (register 31: discarded)
#[inline(always)]
pub fn set_x(n: u32, value: u64) {
    if n != 31 {
        unsafe { *x.add(n as usize) = value }
    }
}
/// Write X[n] with register 31 as the stack pointer
#[inline(always)]
pub fn set_x_sp(n: u32, value: u64) { unsafe { *x.add(n as usize) = value } }
/// Write W[n], zero-extended to X[n] (register 31: discarded)
#[inline(always)]
pub fn set_w(n: u32, value: u32) { set_x(n, value as u64) }
/// Write the register of a 64-bit (sf) or 32-bit operation: a 32-bit result is zero-extended
#[inline(always)]
pub fn set_xw(n: u32, sf: bool, value: u64) {
    set_x(n, if sf { value } else { value as u32 as u64 })
}
#[inline(always)]
pub fn set_xw_sp(n: u32, sf: bool, value: u64) {
    set_x_sp(n, if sf { value } else { value as u32 as u64 })
}

#[inline(always)]
pub fn get_pc() -> u64 { unsafe { *pc } }
#[inline(always)]
pub fn set_pc(value: u64) { unsafe { *pc = value } }
#[inline(always)]
pub fn get_nzcv() -> u32 { unsafe { *nzcv } }
#[inline(always)]
pub fn set_nzcv(value: u32) { unsafe { *nzcv = value & 0xF000_0000 } }
#[inline(always)]
pub fn get_pstate() -> u32 { unsafe { *pstate } }
/// The current exception level (0 or 1; AArch32's User mode PL0, its other modes PL1)
#[inline(always)]
pub fn el() -> u32 {
    let p = get_pstate();
    if p & PSTATE_NRW != 0 {
        (p & 0xF != 0) as u32
    }
    else {
        p >> PSTATE_EL_SHIFT & 3
    }
}
#[inline(always)]
pub fn sctlr() -> u64 { unsafe { *sctlr_el1 } }

/// Which stack pointer is current: 0 SP_EL0, 1 SP_EL1
#[inline(always)]
fn sp_select(pstate_value: u32) -> usize {
    if pstate_value >> PSTATE_EL_SHIFT & 3 != 0 && pstate_value & PSTATE_SP != 0 {
        1
    }
    else {
        0
    }
}

/// Change PSTATE (but NZCV), banking the stack pointer when its selection
/// changes (AArch32's modes: their banked registers)
pub fn set_pstate(value: u32) {
    unsafe {
        if value & *pstate & PSTATE_NRW != 0 {
            crate::aarch64::a32_system::switch_registers(*pstate & 0x1F, value & 0x1F);
            *pstate = value;
            return;
        }
        let old = sp_select(*pstate);
        let new = sp_select(value);
        if old != new {
            *sp_el.add(old) = *x.add(31);
            *x.add(31) = *sp_el.add(new);
        }
        *pstate = value;
    }
}

/// SP_EL0 or SP_EL1 as a system register (the banked copy, or the current SP)
pub fn get_sp_el(n: usize) -> u64 {
    unsafe {
        if sp_select(*pstate) == n {
            *x.add(31)
        }
        else {
            *sp_el.add(n)
        }
    }
}
pub fn set_sp_el(n: usize, value: u64) {
    unsafe {
        if sp_select(*pstate) == n {
            *x.add(31) = value
        }
        else {
            *sp_el.add(n) = value
        }
    }
}

/// The value of an SPSR for the current PSTATE: NZCV and the saved bits
/// (AArch32's: T, ITSTATE, GE, Q, E as well)
pub fn current_spsr() -> u64 {
    let saved = if aarch32() { PSTATE_SAVED_A32 } else { PSTATE_SAVED };
    (get_nzcv() | get_pstate() & saved) as u64
}

// ---- exceptions

/// A synchronous exception the current instruction takes (P3.2)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Exception {
    /// unallocated, outside the profile, or not permitted here (EC 0x00)
    Undefined,
    /// trapped WFI or WFE (EC 0x01): the trap's TI bit
    Wfx(u32),
    /// FP or SIMD with CPACR_EL1.FPEN trapping (EC 0x07)
    FpAccess,
    /// an illegal exception return's PSTATE.IL (EC 0x0E)
    IllegalState,
    Svc(u16),
    Hvc(u16),
    Smc(u16),
    /// a trapped MSR, MRS or system instruction (EC 0x18): its ISS
    SystemRegister(u32),
    /// an instruction abort (EC 0x20/0x21): fault status code, address
    InstructionAbort {
        fsc: u32,
        far: u64,
    },
    /// a misaligned PC (EC 0x22)
    PcAlignment(u64),
    /// a data abort (EC 0x24/0x25): its ISS and the address
    DataAbort {
        iss: u32,
        far: u64,
    },
    /// a misaligned SP (EC 0x26)
    SpAlignment,
    /// BRK (EC 0x3C)
    Brk(u16),
    /// a hardware breakpoint (EC 0x30/0x31; FAR 0)
    Breakpoint,
    /// a watchpoint (EC 0x34/0x35): whether the access writes, the first watched byte
    Watchpoint {
        write: bool,
        far: u64,
    },
    /// software step (EC 0x32/0x33): whether the stepped instruction was a load-exclusive
    SoftwareStep(bool),
    /// an AArch32 instruction's trap with its own syndrome (MCR/MRC and
    /// MCRR/MRRC of CP15 and CP14 0x03-0x06/0x0C, WFx 0x01, FP 0x07, BKPT 0x38): EC, ISS
    Trapped32 {
        ec: u32,
        iss: u32,
    },
}

pub const EC_UNKNOWN: u32 = 0x00;
pub const EC_WFX: u32 = 0x01;
pub const EC_FP: u32 = 0x07;
pub const EC_ILLEGAL: u32 = 0x0E;
/// SVC from AArch32
pub const EC_SVC32: u32 = 0x11;
pub const EC_SVC: u32 = 0x15;
pub const EC_HVC: u32 = 0x16;
pub const EC_SMC: u32 = 0x17;
pub const EC_SYSREG: u32 = 0x18;
pub const EC_IABT_LOWER: u32 = 0x20;
pub const EC_IABT: u32 = 0x21;
pub const EC_PC_ALIGN: u32 = 0x22;
pub const EC_DABT_LOWER: u32 = 0x24;
pub const EC_DABT: u32 = 0x25;
pub const EC_SP_ALIGN: u32 = 0x26;
pub const EC_BRK: u32 = 0x3C;
pub const EC_BREAKPOINT_LOWER: u32 = 0x30;
pub const EC_STEP_LOWER: u32 = 0x32;
pub const EC_WATCHPOINT_LOWER: u32 = 0x34;
/// The fault status of a debug exception
const FSC_DEBUG: u32 = 0x22;

/// Fault status codes (DFSC/IFSC)
pub const FSC_ADDRESS_SIZE_L0: u32 = 0x00;
pub const FSC_TRANSLATION_L0: u32 = 0x04;
pub const FSC_ACCESS_FLAG_L0: u32 = 0x08;
pub const FSC_PERMISSION_L0: u32 = 0x0C;
pub const FSC_EXTERNAL: u32 = 0x10;
pub const FSC_ALIGNMENT: u32 = 0x21;

const IL: u32 = 1 << 25;

impl Exception {
    /// ESR_EL1, taken from exception level `from`
    pub fn syndrome(self, from: u32) -> u32 {
        let a32 = aarch32();
        let (ec, iss) = match self {
            Exception::Undefined => (EC_UNKNOWN, 0),
            Exception::Wfx(ti) => (EC_WFX, 0x1E0_0000 | ti),
            Exception::FpAccess => (EC_FP, 0x1E0_0000),
            Exception::IllegalState => (EC_ILLEGAL, 0),
            Exception::Svc(imm) => (if a32 { EC_SVC32 } else { EC_SVC }, imm as u32),
            Exception::Hvc(imm) => (EC_HVC, imm as u32),
            Exception::Smc(imm) => (EC_SMC, imm as u32),
            Exception::SystemRegister(iss) => (EC_SYSREG, iss),
            Exception::InstructionAbort { fsc, .. } => {
                (if from == 0 { EC_IABT_LOWER } else { EC_IABT }, fsc)
            },
            Exception::PcAlignment(_) => (EC_PC_ALIGN, 0),
            Exception::DataAbort { iss, .. } => {
                (if from == 0 { EC_DABT_LOWER } else { EC_DABT }, iss)
            },
            Exception::SpAlignment => (EC_SP_ALIGN, 0),
            Exception::Brk(imm) => (EC_BRK, imm as u32),
            // (the same-EL classes are one more than the lower-EL ones)
            Exception::Breakpoint => (EC_BREAKPOINT_LOWER + (from != 0) as u32, FSC_DEBUG),
            Exception::Watchpoint { write, .. } => (
                EC_WATCHPOINT_LOWER + (from != 0) as u32,
                FSC_DEBUG | (write as u32) << 6,
            ),
            Exception::SoftwareStep(ex) => (
                EC_STEP_LOWER + (from != 0) as u32,
                1 << 24 | (ex as u32) << 6 | FSC_DEBUG,
            ),
            Exception::Trapped32 { ec, iss } => (ec, iss),
        };
        // (IL: the instruction's length, 0 for a 16-bit T32 one; 1 where
        // there is no instruction to speak of: unknown, aborts on fetch, PC
        // alignment, illegal state, the debug exceptions)
        let il = if a32
            && crate::aarch64::a32::instruction_length() == 2
            && !matches!(
                self,
                Exception::Undefined
                    | Exception::InstructionAbort { .. }
                    | Exception::PcAlignment(_)
                    | Exception::IllegalState
                    | Exception::Breakpoint
                    | Exception::Watchpoint { .. }
                    | Exception::SoftwareStep(_)
            ) {
            0
        }
        else {
            IL
        };
        ec << 26 | il | iss
    }

    /// FAR_EL1, if the exception sets it
    pub fn fault_address(self) -> Option<u64> {
        match self {
            Exception::InstructionAbort { far, .. }
            | Exception::DataAbort { far, .. }
            | Exception::PcAlignment(far)
            | Exception::Watchpoint { far, .. } => Some(far),
            // (FAR is UNKNOWN for a breakpoint: 0, as the reference writes it)
            Exception::Breakpoint => Some(0),
            _ => None,
        }
    }
}

/// Vector offsets from VBAR_EL1
pub const VECTOR_SYNC: u64 = 0x000;
pub const VECTOR_IRQ: u64 = 0x080;
pub const VECTOR_FIQ: u64 = 0x100;
pub const VECTOR_SERROR: u64 = 0x180;

/// Take an exception to EL1: ELR_EL1 = `return_address`, SPSR_EL1 the
/// PSTATE before, the vector by where it came from (`kind`: VECTOR_*)
pub fn take_exception(kind: u64, return_address: u64, esr: Option<u32>, far: Option<u64>) {
    if a32_only() {
        // (an interrupt: AArch32's IRQ or FIQ)
        return crate::aarch64::a32_system::take_interrupt(kind == VECTOR_FIQ);
    }
    unsafe {
        let from = el();
        *spsr_el1 = current_spsr();
        *elr_el1 = return_address;
        if let Some(esr) = esr {
            *esr_el1 = esr as u64;
        }
        if let Some(far) = far {
            *far_el1 = far;
        }
        // (from EL0: AArch64's vectors at 0x400, AArch32's at 0x600)
        let base = if from == 0 {
            if aarch32() {
                0x600
            }
            else {
                0x400
            }
        }
        else if get_pstate() & PSTATE_SP != 0 {
            0x200
        }
        else {
            0x000
        };
        // (PAN: set with SCTLR_EL1.SPAN clear, else kept)
        let pan = if has_pan() && *sctlr_el1 & SCTLR_SPAN == 0 {
            PSTATE_PAN
        }
        else {
            get_pstate() & PSTATE_PAN
        };
        set_pstate(1 << PSTATE_EL_SHIFT | PSTATE_SP | PSTATE_DAIF | pan);
        set_pc(*vbar_el1 + base + kind);
    }
}

/// The current instruction (at the PC) takes a synchronous exception
pub fn take_sync(exception: Exception) {
    if a32_only() {
        crate::core_stats::note_fault();
        return crate::aarch64::a32_system::take_sync(exception);
    }
    let from = el();
    let return_address = match exception {
        // (the preferred return address of SVC, HVC and SMC is the next
        // instruction: in T32 maybe 2 bytes on)
        Exception::Svc(_) | Exception::Hvc(_) | Exception::Smc(_) => {
            get_pc().wrapping_add(if aarch32() {
                crate::aarch64::a32::instruction_length() as u64
            }
            else {
                4
            })
        },
        _ => get_pc(),
    };
    crate::core_stats::note_fault();
    take_exception(
        VECTOR_SYNC,
        return_address,
        Some(exception.syndrome(from)),
        exception.fault_address(),
    );
}

/// ERET: return to ELR_EL1 with SPSR_EL1's PSTATE (an illegal return keeps
/// the EL and sets PSTATE.IL); clears the local monitor, sets the event register
pub fn exception_return() {
    unsafe {
        let spsr = *spsr_el1 as u32;
        let target = *elr_el1;
        let m = spsr & 0x1F;
        // AArch64 EL0t (0b00000), EL1t (0b00100), EL1h (0b00101); AArch32
        // User (0b10000) with profile v3 (no AArch32 at EL1)
        let a32 = m == MODE_USER && has_aarch32();
        let legal = m == 0 || m == 0b00100 || m == 0b00101 || a32;
        let new = if a32 {
            spsr & PSTATE_SAVED_A32
        }
        else if legal {
            spsr & PSTATE_SAVED
        }
        else {
            // (NZCV, DAIF and PAN still come from SPSR_EL1)
            get_pstate() & !(PSTATE_IL | PSTATE_SS | PSTATE_DAIF | PSTATE_PAN)
                | PSTATE_IL
                | spsr & (PSTATE_DAIF | PSTATE_PAN)
        };
        set_nzcv(spsr & 0xF000_0000);
        set_pstate(new);
        if a32 {
            // (to AArch32: the PC's 32 bits, aligned for its instruction set)
            set_pc((target as u32 & if spsr & PSTATE_T != 0 { !1 } else { !3 }) as u64);
        }
        else {
            // (an AArch64 return: the PC as written, with TBI not applied here; bits 1:0 stay for a PC alignment fault)
            set_pc(target);
        }
        *excl_valid = 0;
        *event_register = 1;
    }
}

/// The reset state of a core: EL1h, every interrupt masked, MMU off
pub fn reset_core(entry: u64, context: u64) {
    unsafe {
        for i in 0..32 {
            *x.add(i) = 0;
        }
        for i in 0..2 {
            *sp_el.add(i) = 0;
        }
        *pstate = 1 << PSTATE_EL_SHIFT | PSTATE_SP | PSTATE_DAIF;
        *nzcv = 0;
        *fpcr = 0;
        *fpsr = 0;
        for i in 0..32 {
            *v.add(i) = 0;
        }
        *sctlr_el1 = SCTLR_RESET;
        *cpacr_el1 = 0;
        *vbar_el1 = 0;
        *tcr_el1 = 0;
        *ttbr0_el1 = 0;
        *ttbr1_el1 = 0;
        *mair_el1 = 0;
        *cntkctl_el1 = 0;
        *cntfrq_el0 = crate::aarch64::sysregs::CNTFRQ_RESET;
        *mdscr_el1 = 0;
        *oslsr_el1 = 0b1010; // OSLK set at reset, OSLM = 0b10 (OS Lock implemented)
        *excl_valid = 0;
        *waiting = 0;
        *event_register = 0;
        *x = context;
        *pc = entry;
    }
    if a32_only() {
        crate::aarch64::a32_system::reset(entry, context);
    }
}
                                                                                                                                                                                                                       source/v64/src/rust/aarch64/crypto.rs                                                               0000644 0000000 0000000 00000023411 00000000000 014567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The crypto extension of profile v86-aarch64-v1 (docs/arm64-virt-android16-plan.md
//! P2.11): AESE, AESD, AESMC, AESIMC; SHA1C/P/M/H/SU0/SU1; SHA256H/H2/SU0/SU1
//! (PMULL is in simd.rs). Scalar helpers on V registers, as the Arm ARM's
//! pseudocode writes them; the JIT calls the same ones (P6).

use crate::aarch64::decode::bits;
use crate::aarch64::execute::Flow;
use crate::aarch64::simd::{set_vreg, vreg};

// ---- AES

const fn gf_mul(a: u8, b: u8) -> u8 {
    let (mut a, mut b, mut result) = (a, b, 0u8);
    while b != 0 {
        if b & 1 != 0 {
            result ^= a;
        }
        a = if a & 0x80 != 0 { a << 1 ^ 0x1B } else { a << 1 };
        b >>= 1;
    }
    result
}

const fn sbox() -> [u8; 256] {
    let mut table = [0u8; 256];
    let mut x = 0;
    while x < 256 {
        // the multiplicative inverse (x^254), then the affine transformation
        let mut inverse = 1u8;
        let mut i = 0;
        while i < 254 {
            inverse = gf_mul(inverse, x as u8);
            i += 1;
        }
        if x == 0 {
            inverse = 0;
        }
        let b = inverse;
        table[x] =
            b ^ b.rotate_left(1) ^ b.rotate_left(2) ^ b.rotate_left(3) ^ b.rotate_left(4) ^ 0x63;
        x += 1;
    }
    table
}

const fn inverse_sbox() -> [u8; 256] {
    let forward = sbox();
    let mut table = [0u8; 256];
    let mut x = 0;
    while x < 256 {
        table[forward[x] as usize] = x as u8;
        x += 1;
    }
    table
}

static SBOX: [u8; 256] = sbox();
static INVERSE_SBOX: [u8; 256] = inverse_sbox();
const SHIFT_ROWS: [usize; 16] = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];
const INVERSE_SHIFT_ROWS: [usize; 16] = [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3];

fn bytes(value: u128) -> [u8; 16] { value.to_le_bytes() }
fn from_bytes(bytes: [u8; 16]) -> u128 { u128::from_le_bytes(bytes) }

/// AESE (SubBytes(ShiftRows(d ^ n))) or AESD (InvSubBytes(InvShiftRows(d ^ n)))
pub fn aes_round(state: u128, key: u128, decrypt: bool) -> u128 {
    let input = bytes(state ^ key);
    let (rows, sbox) =
        if decrypt { (&INVERSE_SHIFT_ROWS, &INVERSE_SBOX) } else { (&SHIFT_ROWS, &SBOX) };
    let mut output = [0u8; 16];
    for i in 0..16 {
        output[i] = sbox[input[rows[i]] as usize];
    }
    from_bytes(output)
}

/// AESMC (MixColumns) or AESIMC (InvMixColumns), the four columns (the
/// 32-bit lanes) at once: forward, each byte is a ^ t ^ xtime(a ^ a'), t
/// the column's bytes xored and a' the next byte in it; the inverse first
/// adds xtime(xtime(a ^ a'')), a'' the byte two on (FIPS-197 5.3.3's
/// factorisation of InvMixColumns)
pub fn aes_mix(state: u128, inverse: bool) -> u128 {
    const LOW_BITS: u128 = 0x0101_0101_0101_0101_0101_0101_0101_0101;
    // each byte times x in GF(2^8)
    let xtime = |x: u128| (x << 1) & !(LOW_BITS * 0x01) ^ (x >> 7 & LOW_BITS) * 0x1B;
    // each 32-bit lane's bytes rotated by `bytes` toward the low one
    let rotate = |x: u128, bytes: u32| {
        let (right, left) = (8 * bytes, 32 - 8 * bytes);
        let lanes = |m: u32| u128::from(m) * 0x0000_0001_0000_0001_0000_0001_0000_0001;
        (x >> right) & lanes(u32::MAX >> right) | (x << left) & lanes(u32::MAX << left)
    };
    let mut a = state;
    if inverse {
        a ^= xtime(xtime(a ^ rotate(a, 2)));
    }
    let next = rotate(a, 1);
    let t = a ^ next ^ rotate(a, 2) ^ rotate(a, 3);
    a ^ t ^ xtime(a ^ next)
}

/// (tests) aes_mix as the Arm ARM's pseudocode writes it, byte by byte
#[cfg(test)]
fn aes_mix_reference(state: u128, inverse: bool) -> u128 {
    let input = bytes(state);
    let m: [u8; 4] = if inverse { [14, 11, 13, 9] } else { [2, 3, 1, 1] };
    let mut output = [0u8; 16];
    for c in 0..4 {
        let column = &input[4 * c..4 * c + 4];
        for r in 0..4 {
            output[4 * c + r] = gf_mul(column[r], m[0])
                ^ gf_mul(column[(r + 1) % 4], m[1])
                ^ gf_mul(column[(r + 2) % 4], m[2])
                ^ gf_mul(column[(r + 3) % 4], m[3]);
        }
    }
    from_bytes(output)
}

pub fn aes(word: u32) -> Flow {
    let d = word & 31;
    let n = word >> 5 & 31;
    let result = match bits(word, 16, 12) {
        0b00100 => aes_round(vreg(d), vreg(n), false),
        0b00101 => aes_round(vreg(d), vreg(n), true),
        0b00110 => aes_mix(vreg(n), false),
        _ => aes_mix(vreg(n), true),
    };
    set_vreg(d, result);
    Flow::Next
}

// ---- SHA

fn words(value: u128) -> [u32; 4] {
    [
        value as u32,
        (value >> 32) as u32,
        (value >> 64) as u32,
        (value >> 96) as u32,
    ]
}
fn from_words(w: [u32; 4]) -> u128 {
    w[0] as u128 | (w[1] as u128) << 32 | (w[2] as u128) << 64 | (w[3] as u128) << 96
}

pub(crate) fn choose(x: u32, y: u32, z: u32) -> u32 { (y ^ z) & x ^ z }
pub(crate) fn parity(x: u32, y: u32, z: u32) -> u32 { x ^ y ^ z }
pub(crate) fn majority(x: u32, y: u32, z: u32) -> u32 { x & y | (x | y) & z }

/// SHA1C (choose), SHA1P (parity), SHA1M (majority): four rounds
pub fn sha1_hash(abcd: u128, e: u32, w: u128, f: fn(u32, u32, u32) -> u32) -> u128 {
    let mut x = words(abcd);
    let mut y = e;
    let w = words(w);
    for i in 0..4 {
        let t = f(x[1], x[2], x[3]);
        y = y
            .wrapping_add(x[0].rotate_left(5))
            .wrapping_add(t)
            .wrapping_add(w[i]);
        x[1] = x[1].rotate_left(30);
        // (Y:X rotated left by 32)
        let top = x[3];
        x = [y, x[0], x[1], x[2]];
        y = top;
    }
    from_words(x)
}

/// SHA256H (part 1: the new X) and SHA256H2 (the new Y)
pub fn sha256_hash(x: u128, y: u128, w: u128, part1: bool) -> u128 {
    let (mut x, mut y, w) = (words(x), words(y), words(w));
    for e in 0..4 {
        let chs = choose(y[0], y[1], y[2]);
        let maj = majority(x[0], x[1], x[2]);
        let sigma1 = y[0].rotate_right(6) ^ y[0].rotate_right(11) ^ y[0].rotate_right(25);
        let sigma0 = x[0].rotate_right(2) ^ x[0].rotate_right(13) ^ x[0].rotate_right(22);
        let t = y[3]
            .wrapping_add(sigma1)
            .wrapping_add(chs)
            .wrapping_add(w[e]);
        x[3] = t.wrapping_add(x[3]);
        y[3] = t.wrapping_add(sigma0).wrapping_add(maj);
        // (Y:X rotated left by 32)
        let (x3, y3) = (x[3], y[3]);
        x = [y3, x[0], x[1], x[2]];
        y = [x3, y[0], y[1], y[2]];
    }
    from_words(if part1 { x } else { y })
}

pub fn sha3(word: u32) -> Flow {
    let d = word & 31;
    let n = word >> 5 & 31;
    let m = word >> 16 & 31;
    let (vd, vn, vm) = (vreg(d), vreg(n), vreg(m));
    let result = match bits(word, 14, 12) {
        0b000 => sha1_hash(vd, vn as u32, vm, choose),
        0b001 => sha1_hash(vd, vn as u32, vm, parity),
        0b010 => sha1_hash(vd, vn as u32, vm, majority),
        0b011 => sha1su0(vd, vn, vm),
        0b100 => sha256_hash(vd, vn, vm, true),
        0b101 => sha256_hash(vn, vd, vm, false),
        _ => sha256su1(vd, vn, vm),
    };
    set_vreg(d, result);
    Flow::Next
}

/// SHA1SU0
pub fn sha1su0(vd: u128, vn: u128, vm: u128) -> u128 { (vn << 64 | vd >> 64) ^ vd ^ vm }

/// SHA256SU1
pub fn sha256su1(vd: u128, vn: u128, vm: u128) -> u128 {
    let t0 = words((vm as u32 as u128) << 96 | vn >> 32);
    let op1 = words(vd);
    let sigma = |x: u32| x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10);
    let mut r = [0u32; 4];
    let t1 = words(vm);
    for e in 0..2 {
        r[e] = sigma(t1[2 + e]).wrapping_add(op1[e]).wrapping_add(t0[e]);
    }
    for e in 2..4 {
        r[e] = sigma(r[e - 2]).wrapping_add(op1[e]).wrapping_add(t0[e]);
    }
    from_words(r)
}

pub fn sha2(word: u32) -> Flow {
    let d = word & 31;
    let n = word >> 5 & 31;
    let (vd, vn) = (vreg(d), vreg(n));
    let result = match bits(word, 16, 12) {
        0b00000 => (vn as u32).rotate_left(30) as u128,
        0b00001 => sha1su1(vd, vn),
        _ => sha256su0(vd, vn),
    };
    set_vreg(d, result);
    Flow::Next
}

/// SHA1SU1
pub fn sha1su1(vd: u128, vn: u128) -> u128 {
    let t = words(vd ^ vn >> 32);
    let mut r = [
        t[0].rotate_left(1),
        t[1].rotate_left(1),
        t[2].rotate_left(1),
        t[3].rotate_left(1),
    ];
    r[3] ^= t[0].rotate_left(2);
    from_words(r)
}

/// SHA256SU0
pub fn sha256su0(vd: u128, vn: u128) -> u128 {
    let t = words((vn as u32 as u128) << 96 | vd >> 32);
    let op1 = words(vd);
    let mut r = [0u32; 4];
    for e in 0..4 {
        let x = t[e];
        r[e] = (x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3)).wrapping_add(op1[e]);
    }
    from_words(r)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn aes_tables() {
        assert_eq!(SBOX[0x00], 0x63);
        assert_eq!(SBOX[0x53], 0xED);
        assert_eq!(INVERSE_SBOX[0x63], 0x00);
        // FIPS-197 C.1, round 1: start of round, after SubBytes/ShiftRows (as AESE with a zero key)
        let state = u128::from_le_bytes(
            *b"\x00\x10\x20\x30\x40\x50\x60\x70\x80\x90\xa0\xb0\xc0\xd0\xe0\xf0",
        );
        let after = aes_round(state, 0, false);
        assert_eq!(
            after.to_le_bytes(),
            *b"\x63\x53\xe0\x8c\x09\x60\xe1\x04\xcd\x70\xb7\x51\xba\xca\xd0\xe7"
        );
        let mixed = aes_mix(after, false);
        assert_eq!(
            mixed.to_le_bytes(),
            *b"\x5f\x72\x64\x15\x57\xf5\xbc\x92\xf7\xbe\x3b\x29\x1d\xb9\xf9\x1a"
        );
        assert_eq!(aes_mix(mixed, true), after);
        assert_eq!(aes_round(aes_round(state, 0, false), 0, true), state);
    }

    #[test]
    fn aes_mix_matches_reference() {
        let mut x = 0x9E37_79B9_7F4A_7C15_F39C_C060_5CED_C834u128;
        for _ in 0..10000 {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            for inverse in [false, true] {
                assert_eq!(
                    aes_mix(x, inverse),
                    aes_mix_reference(x, inverse),
                    "{x:032x} {inverse}"
                );
            }
        }
    }
}
                                                                                                                                                                                                                                                       source/v64/src/rust/aarch64/debug.rs                                                                0000644 0000000 0000000 00000023107 00000000000 014337  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Self-hosted debug of profile v1 (docs/arm64-virt-android16-plan.md P3.8):
//! 2 breakpoints (the second context-aware: CONTEXTIDR_EL1 matches, and the
//! target of linked address matches), 2 watchpoints, software step, the OS
//! Lock and OS Double Lock, MDSCR_EL1. No external debug, no Halting, no
//! debug communications channel. The registers keep what is written (BAS[3]
//! and BAS[1] of a breakpoint copy BAS[2] and BAS[0]), as the reference's
//! do. Where the Arm ARM leaves a choice this follows QEMU 9.2
//! (target/arm/debug_helper.c): a breakpoint fires when its address is the
//! instruction's; BAS with MASK set is ignored, reserved MASK or LSC values
//! disable a watchpoint, only the first run of BAS ones counts; FAR is 0
//! for a breakpoint and the first watched byte for a watchpoint. Unlike the
//! reference, OSLSR_EL1.OSLK (set at reset) blocks debug exceptions, as the
//! architecture says, and unlinked context ID breakpoints fire.

use crate::aarch64::cpu::{self, Exception, PSTATE_D, PSTATE_SS};
use crate::aarch64::state::{
    contextidr_el1, dbgbcr, dbgbvr, dbgwcr, dbgwvr, mdccint_el1, mdscr_el1, osdlr_el1, oslsr_el1,
};
use crate::aarch64::sysregs::key;

const BREAKPOINTS: usize = 2;
const WATCHPOINTS: usize = 2;
/// The context-aware breakpoint (the last one)
const CONTEXT_BREAKPOINT: usize = 1;

const MDSCR_SS: u64 = 1 << 0;
const MDSCR_KDE: u64 = 1 << 13;
const MDSCR_MDE: u64 = 1 << 15;

/// Whether any breakpoint or watchpoint is enabled (the fast paths check this first)
pub static mut ANY_BREAKPOINT: bool = false;
pub static mut ANY_WATCHPOINT: bool = false;

pub fn refresh() {
    unsafe {
        ANY_BREAKPOINT = (0..BREAKPOINTS).any(|n| *dbgbcr.add(n) & 1 != 0);
        ANY_WATCHPOINT = (0..WATCHPOINTS).any(|n| *dbgwcr.add(n) & 1 != 0);
    }
}

/// AArch64.GenerateDebugExceptions: whether debug exceptions are enabled at
/// the current EL (their target is EL1)
pub fn enabled() -> bool {
    unsafe {
        // (the OS Lock, or the OS Double Lock with no powerdown request)
        if *oslsr_el1 & 2 != 0 || *osdlr_el1 & 1 != 0 {
            return false;
        }
        if cpu::el() == 1 {
            *mdscr_el1 & MDSCR_KDE != 0 && cpu::get_pstate() & PSTATE_D == 0
        }
        else {
            true
        }
    }
}

/// Whether software step is active (MDSCR_EL1.SS with debug exceptions enabled)
#[inline(always)]
pub fn stepping() -> bool { (unsafe { *mdscr_el1 } & MDSCR_SS != 0) && enabled() }

/// PMC (and HMC, SSC: no EL2 or EL3 here) of a control register match the access's EL
fn el_matches(control: u64, el: u32) -> bool {
    let pmc = control >> 1 & 3;
    if el == 0 {
        pmc & 2 != 0
    }
    else {
        pmc & 1 != 0
    }
}

/// Whether the context breakpoint `n` matches now (linked or not)
fn context_matches(n: usize) -> bool {
    if n != CONTEXT_BREAKPOINT {
        return false;
    }
    unsafe { *dbgbcr.add(n) & 1 != 0 && *contextidr_el1 as u32 == *dbgbvr.add(n) as u32 }
}

/// The breakpoint debug exception the instruction at `pc` takes before it runs, if any
pub fn check_breakpoint(address: u64) -> Option<Exception> {
    unsafe {
        if *mdscr_el1 & MDSCR_MDE == 0 || !enabled() {
            return None;
        }
        let el = cpu::el();
        for n in 0..BREAKPOINTS {
            let control = *dbgbcr.add(n);
            if control & 1 == 0 || !el_matches(control, el) {
                continue;
            }
            let value = *dbgbvr.add(n);
            let bas = control >> 5 & 15;
            let hit = match control >> 20 & 15 {
                // address match (unlinked, or linked to a context breakpoint)
                bt @ (0 | 1) => {
                    let target = (value & !3) + if bas == 0xC { 2 } else { 0 };
                    bas != 0
                        && target == address
                        && (bt == 0 || context_matches((control >> 16 & 15) as usize))
                },
                // unlinked context ID match
                2 => context_matches(n),
                _ => false,
            };
            if hit {
                return Some(Exception::Breakpoint);
            }
        }
        None
    }
}

/// The watchpoint debug exception an access of `size` bytes at `va` takes
/// (`el0`: an unprivileged or EL0 access), if any; it takes it before the access
pub fn check_watchpoint(va: u64, size: u32, write: bool, el0: bool) -> Option<Exception> {
    unsafe {
        if *mdscr_el1 & MDSCR_MDE == 0 || !enabled() {
            return None;
        }
        for n in 0..WATCHPOINTS {
            let control = *dbgwcr.add(n);
            if control & 1 == 0 || !el_matches(control, if el0 { 0 } else { 1 }) {
                continue;
            }
            let lsc = control >> 3 & 3;
            if lsc == 0 || write && lsc & 2 == 0 || !write && lsc & 1 == 0 {
                continue;
            }
            let mut start = *dbgwvr.add(n);
            let length;
            let mask = control >> 24 & 31;
            if mask == 1 || mask == 2 {
                continue;
            }
            if mask != 0 {
                length = 1u64 << mask;
                start &= !(length - 1);
            }
            else {
                let mut bas = control >> 5 & 0xFF;
                if start >> 2 & 1 != 0 {
                    bas &= 0xF;
                }
                if bas == 0 {
                    continue;
                }
                let first = bas.trailing_zeros() as u64;
                length = (bas >> first).trailing_ones() as u64;
                start = (start & !7) + first;
            }
            if control >> 20 & 1 != 0 && !context_matches((control >> 16 & 15) as usize) {
                continue;
            }
            let end = va.wrapping_add(size as u64);
            if va < start.wrapping_add(length) && end > start {
                return Some(Exception::Watchpoint {
                    write,
                    far: va.max(start),
                });
            }
        }
        None
    }
}

/// Software step: whether the next instruction is stepped over (active-pending:
/// the step exception comes first)
#[inline(always)]
pub fn step_pending() -> bool { stepping() && cpu::get_pstate() & PSTATE_SS == 0 }

/// After an instruction ran in the active-not-pending state: PSTATE.SS goes to 0
#[inline(always)]
pub fn step_done() { cpu::set_pstate(cpu::get_pstate() & !PSTATE_SS) }

pub fn read(reg: u32, _rt: u32) -> Result<u64, Exception> {
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op1 = reg >> 11 & 7;
    let op2 = reg & 7;
    unsafe {
        Ok(match (op1, crn, crm, op2) {
            (0, 0, n, 4) if (n as usize) < BREAKPOINTS => *dbgbvr.add(n as usize),
            (0, 0, n, 5) if (n as usize) < BREAKPOINTS => *dbgbcr.add(n as usize),
            (0, 0, n, 6) if (n as usize) < WATCHPOINTS => *dbgwvr.add(n as usize),
            (0, 0, n, 7) if (n as usize) < WATCHPOINTS => *dbgwcr.add(n as usize),
            _ => match reg {
                r if r == key(2, 0, 0, 2, 2) => *mdscr_el1,
                r if r == key(2, 0, 0, 2, 0) => *mdccint_el1,
                r if r == key(2, 0, 1, 1, 4) => *oslsr_el1,
                r if r == key(2, 0, 1, 3, 4) => *osdlr_el1,
                r if r == key(2, 0, 1, 0, 0) => 0, // MDRAR_EL1: no memory-mapped debug
                r if r == key(2, 0, 1, 4, 4) => 0, // DBGPRCR_EL1
                r if r == key(2, 0, 7, 8, 6) || r == key(2, 0, 7, 9, 6) => 0, // DBGCLAIMSET/CLR
                r if r == key(2, 0, 7, 14, 6) => 0xAA, // DBGAUTHSTATUS_EL1: non-secure debug enabled
                r if r == key(2, 0, 0, 6, 2) => 0,     // OSECCR_EL1
                _ => return Err(Exception::Undefined),
            },
        })
    }
}

pub fn write(reg: u32, _rt: u32, value: u64) -> Result<(), Exception> {
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op1 = reg >> 11 & 7;
    let op2 = reg & 7;
    unsafe {
        match (op1, crn, crm, op2) {
            (0, 0, n, 4) if (n as usize) < BREAKPOINTS => *dbgbvr.add(n as usize) = value,
            (0, 0, n, 5) if (n as usize) < BREAKPOINTS => {
                // (BAS[3] reads as BAS[2], BAS[1] as BAS[0])
                let bas2 = value >> 7 & 1;
                let bas0 = value >> 5 & 1;
                *dbgbcr.add(n as usize) = value & !(1 << 8 | 1 << 6) | bas2 << 8 | bas0 << 6;
                refresh();
            },
            (0, 0, n, 6) if (n as usize) < WATCHPOINTS => *dbgwvr.add(n as usize) = value,
            (0, 0, n, 7) if (n as usize) < WATCHPOINTS => {
                *dbgwcr.add(n as usize) = value;
                refresh();
            },
            _ => match reg {
                r if r == key(2, 0, 0, 2, 2) => *mdscr_el1 = value & 0xE000_E03F | value & 0x2_0000,
                r if r == key(2, 0, 0, 2, 0) => *mdccint_el1 = value & 1 << 29,
                r if r == key(2, 0, 1, 0, 4) => {
                    // OSLAR_EL1: the OS Lock (OSLSR_EL1.OSLK, bit 1)
                    *oslsr_el1 = *oslsr_el1 & !2 | (value & 1) << 1
                },
                r if r == key(2, 0, 1, 3, 4) => *osdlr_el1 = value & 1,
                r if r == key(2, 0, 1, 4, 4) => {},
                r if r == key(2, 0, 7, 8, 6) || r == key(2, 0, 7, 9, 6) => {},
                r if r == key(2, 0, 0, 6, 2) => {},
                _ => return Err(Exception::Undefined),
            },
        }
    }
    Ok(())
}

/// Reset: everything disabled, the OS Lock set
pub fn reset() {
    unsafe {
        for n in 0..BREAKPOINTS {
            *dbgbvr.add(n) = 0;
            *dbgbcr.add(n) = 0;
        }
        for n in 0..WATCHPOINTS {
            *dbgwvr.add(n) = 0;
            *dbgwcr.add(n) = 0;
        }
    }
    refresh();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/rust/aarch64/decode.rs                                                               0000644 0000000 0000000 00000103031 00000000000 014467  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The A64 decoder (docs/arm64-virt-android16-plan.md P2.1): an instruction
//! word to an `Inst`, following the encoding index of the Arm ARM (DDI 0487
//! L.b, C4.1). Every encoding is implemented, a HINT (a NOP unless
//! implemented), or UNDEF: unallocated, or a feature profile v86-aarch64-v1
//! does not declare (tests/platform/a64-profile.json). The scalar FP,
//! AdvSIMD and crypto classes are in simd_decode (P2.5-P2.8, P2.11).
//! `mnemonic` names the base instruction (not LLVM's preferred alias) for
//! the decode oracle (tests/a64/oracle/decode.mjs).

/// What an instruction does; the fields of `Inst` hold its operands
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Op {
    Undef,
    // data processing (immediate)
    Adr,
    Adrp,
    /// ADD/ADDS/SUB/SUBS (immediate): sub = 1 for SUB, s = 1 sets flags
    AddSubImm,
    /// AND/ORR/EOR/ANDS (immediate): sub = opc, imm = the bitmask
    LogicalImm,
    /// MOVN (sub 0), MOVZ (2), MOVK (3): imm = imm16, amount = hw * 16
    MoveWide,
    /// SBFM (sub 0), BFM (1), UBFM (2): amount = immr, imm = imms
    Bitfield,
    /// EXTR: amount = lsb
    Extr,
    // branches, exceptions, system
    /// B.cond: cond, imm = offset
    BCond,
    /// B (sub 0) or BL (sub 1): imm = offset
    Branch,
    /// BR (sub 0), BLR (1), RET (2): rn
    BranchReg,
    /// CBZ (sub 0), CBNZ (1): rd = Rt, imm = offset
    CompareBranch,
    /// TBZ (sub 0), TBNZ (1): rd = Rt, amount = bit, imm = offset
    TestBranch,
    /// SVC, HVC, SMC, BRK, HLT: sub = 1..5, imm = imm16
    ExceptionGen,
    Eret,
    /// a hint: imm = CRm:op2 (0 NOP, 1 YIELD, 2 WFE, 3 WFI, 4 SEV, 5 SEVL, others NOP)
    Hint,
    Clrex,
    /// DSB (sub 0), DMB (1), ISB (2)
    Barrier,
    /// MSR (immediate) to PSTATE: sub 0 SPSel, 1 DAIFSet, 2 DAIFClr, 3 PAN; imm = CRm
    MsrImm,
    /// SYS (cache and TLB maintenance, AT): imm = op1:CRn:CRm:op2 (14 bits), rd = Rt
    Sys,
    /// MRS: imm = the system register's op0:op1:CRn:CRm:op2 (16 bits), rd = Rt
    Mrs,
    /// MSR (register): as Mrs
    Msr,
    // loads and stores
    /// LDR (literal): sub 0 W, 1 X, 2 LDRSW, 3 PRFM; imm = offset; rd = Rt
    LoadLiteral,
    /// a single register: see LdSt
    LoadStore,
    /// a pair: see LdSt
    LoadStorePair,
    /// LDXR/STXR/LDAXR/STLXR/LDXP/STXP/LDAXP/STLXP: rd = Rt, ra = Rt2, rm = Rs, size; sub bit 0 load,
    /// bit 1 pair, bit 2 acquire/release
    Exclusive,
    /// LDAR/STLR (and B, H): rd = Rt, size; sub = 1 for loads
    LoadAcquireStoreRelease,
    // data processing (register)
    /// AND/BIC/ORR/ORN/EOR/EON/ANDS/BICS (shifted register): sub = opc << 1 | N, shift, amount
    LogicalShifted,
    /// ADD/ADDS/SUB/SUBS (shifted register): sub = 1 for SUB, s, shift, amount
    AddSubShifted,
    /// ADD/ADDS/SUB/SUBS (extended register): sub, s, shift = option, amount = imm3
    AddSubExtended,
    /// ADC/ADCS/SBC/SBCS: sub = 1 for SBC, s
    AddSubCarry,
    /// CCMN (sub 0) / CCMP (1): cond, imm = nzcv; amount = 1 for the immediate form (rm = imm5)
    CondCompare,
    /// CSEL (sub 0), CSINC (1), CSINV (2), CSNEG (3): cond
    CondSelect,
    /// MADD/MSUB/SMADDL/SMSUBL/SMULH/UMADDL/UMSUBL/UMULH: sub = op31 << 1 | o0
    DataProc3,
    /// UDIV, SDIV, LSLV, LSRV, ASRV, RORV, CRC32*: sub = opcode
    DataProc2,
    /// RBIT, REV16, REV32, REV, CLZ, CLS: sub = opcode
    DataProc1,
    // scalar FP, AdvSIMD and crypto (simd_decode): imm = the instruction
    // word; a scalar AdvSIMD form shares its vector form's class (bit 28 of
    // the word tells them apart)
    FpDp1,
    FpDp2,
    FpDp3,
    FpCompare,
    FpCondCompare,
    FpCondSelect,
    FpImm,
    FpFixed,
    FpInt,
    SimdThreeSame,
    SimdThreeDiff,
    SimdTwoMisc,
    SimdAcross,
    SimdPairwise,
    SimdCopy,
    SimdModImm,
    SimdShiftImm,
    SimdIndexed,
    SimdTable,
    SimdPermute,
    SimdExtract,
    CryptoAes,
    CryptoSha3,
    CryptoSha2,
    /// LD1-LD4/ST1-ST4 and LD1R-LD4R (simd_decode::structure): imm = the word
    SimdStructure,
}

/// A decoded instruction
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Inst {
    pub op: Op,
    pub rd: u8,
    pub rn: u8,
    pub rm: u8,
    pub ra: u8,
    /// 64-bit operation (or a load/store's register width: see LdSt)
    pub sf: bool,
    /// sets the flags
    pub s: bool,
    pub sub: u8,
    pub cond: u8,
    pub shift: u8,
    pub amount: u8,
    pub imm: u64,
}

impl Inst {
    pub const UNDEF: Inst = Inst {
        op: Op::Undef,
        rd: 0,
        rn: 0,
        rm: 0,
        ra: 0,
        sf: false,
        s: false,
        sub: 0,
        cond: 0,
        shift: 0,
        amount: 0,
        imm: 0,
    };
    pub(crate) fn new(op: Op, word: u32) -> Inst {
        Inst {
            op,
            rd: (word & 31) as u8,
            rn: (word >> 5 & 31) as u8,
            rm: (word >> 16 & 31) as u8,
            ra: (word >> 10 & 31) as u8,
            sf: word >> 31 != 0,
            ..Inst::UNDEF
        }
    }
}

// Load/store details (LoadStore, LoadStorePair), packed in sub, shift and amount:
/// sub bits: 0 load, 1 SIMD&FP register, 2 sign-extend, 3 to a 32-bit register (sign-extending loads), 4 prefetch, 5 unprivileged
pub const LS_LOAD: u8 = 1;
pub const LS_SIMD: u8 = 2;
pub const LS_SIGNED: u8 = 4;
pub const LS_TO_W: u8 = 8;
pub const LS_PREFETCH: u8 = 16;
pub const LS_UNPRIVILEGED: u8 = 32;
/// cond: log2 of the access size in bytes (0..4)
/// shift: the addressing mode
pub const MODE_OFFSET: u8 = 0;
pub const MODE_PRE: u8 = 1;
pub const MODE_POST: u8 = 2;
/// register offset: amount = the shift (0 or log2 size), ra = option (extend)
pub const MODE_REGISTER: u8 = 3;
/// amount of an immediate-offset single register: the unscaled form (LDUR, STUR, PRFUM)
pub const LS_UNSCALED: u8 = 1;
/// amount of a pair: the no-allocate form (LDNP, STNP)
pub const LS_NO_ALLOCATE: u8 = 1;

#[inline(always)]
pub(crate) fn bits(word: u32, high: u32, low: u32) -> u32 {
    word >> low & ((1u32 << (high - low + 1)) - 1)
}
#[inline(always)]
fn sext(value: u64, width: u32) -> u64 { ((value << (64 - width)) as i64 >> (64 - width)) as u64 }

/// DecodeBitMasks (Arm ARM J1): the wmask of a logical immediate, or None
/// for a reserved encoding
pub fn decode_bit_masks(n: u32, imms: u32, immr: u32, sf: bool) -> Option<u64> {
    let combined = n << 6 | !imms & 0x3F;
    if combined == 0 {
        return None;
    }
    let len = 31 - combined.leading_zeros();
    if len < 1 || !sf && len > 5 {
        return None;
    }
    let levels = (1u32 << len) - 1;
    let s = imms & levels;
    let r = immr & levels;
    if s == levels {
        return None;
    }
    let esize = 1u32 << len;
    let welem: u64 = if s + 1 == 64 { u64::MAX } else { (1u64 << (s + 1)) - 1 };
    let mask = if esize == 64 { u64::MAX } else { (1u64 << esize) - 1 };
    let rotated = if r == 0 { welem } else { (welem >> r | welem << (esize - r)) & mask };
    let mut result = 0u64;
    let mut at = 0;
    while at < 64 {
        result |= rotated << at;
        at += esize;
    }
    Some(if sf { result } else { result & 0xFFFF_FFFF })
}

/// Decode one instruction word
pub fn decode(word: u32) -> Inst {
    match bits(word, 28, 25) {
        0b1000 | 0b1001 => data_processing_immediate(word),
        0b1010 | 0b1011 => branch_system(word),
        0b0100 | 0b0110 | 0b1100 | 0b1110 => load_store(word),
        0b0101 | 0b1101 => data_processing_register(word),
        0b0111 | 0b1111 => crate::aarch64::simd_decode::data_processing(word),
        // reserved, SME, SVE
        _ => Inst::UNDEF,
    }
}

fn data_processing_immediate(word: u32) -> Inst {
    let sf = word >> 31 != 0;
    match bits(word, 25, 23) {
        0b000 | 0b001 => {
            let mut i = Inst::new(if word >> 31 != 0 { Op::Adrp } else { Op::Adr }, word);
            let imm = sext((bits(word, 23, 5) << 2 | bits(word, 30, 29)) as u64, 21);
            i.imm = if i.op == Op::Adrp { imm << 12 } else { imm };
            i
        },
        0b010 => {
            let mut i = Inst::new(Op::AddSubImm, word);
            i.sub = bits(word, 30, 30) as u8;
            i.s = word >> 29 & 1 != 0;
            i.imm = (bits(word, 21, 10) as u64) << if word >> 22 & 1 != 0 { 12 } else { 0 };
            i
        },
        0b100 => {
            let n = bits(word, 22, 22);
            if !sf && n != 0 {
                return Inst::UNDEF;
            }
            match decode_bit_masks(n, bits(word, 15, 10), bits(word, 21, 16), sf) {
                Some(mask) => {
                    let mut i = Inst::new(Op::LogicalImm, word);
                    i.sub = bits(word, 30, 29) as u8;
                    i.imm = mask;
                    i
                },
                None => Inst::UNDEF,
            }
        },
        0b101 => {
            let opc = bits(word, 30, 29);
            let hw = bits(word, 22, 21);
            if opc == 1 || !sf && hw >= 2 {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::MoveWide, word);
            i.sub = opc as u8;
            i.imm = bits(word, 20, 5) as u64;
            i.amount = (hw * 16) as u8;
            i
        },
        0b110 => {
            let opc = bits(word, 30, 29);
            let n = bits(word, 22, 22);
            let immr = bits(word, 21, 16);
            let imms = bits(word, 15, 10);
            if opc == 3 || (n != 0) != sf || !sf && (immr >= 32 || imms >= 32) {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::Bitfield, word);
            i.sub = opc as u8;
            i.amount = immr as u8;
            i.imm = imms as u64;
            i
        },
        0b111 => {
            let n = bits(word, 22, 22);
            let imms = bits(word, 15, 10);
            if bits(word, 30, 29) != 0
                || bits(word, 21, 21) != 0
                || (n != 0) != sf
                || !sf && imms >= 32
            {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::Extr, word);
            i.amount = imms as u8;
            i
        },
        // ADD/SUB (immediate, with tags): MTE
        _ => Inst::UNDEF,
    }
}

fn branch_system(word: u32) -> Inst {
    let op0 = bits(word, 31, 29);
    if op0 == 0b010 {
        // conditional branch (BC.cond, o0 = 1, is FEAT_HBC)
        if bits(word, 25, 24) != 0 || word >> 4 & 1 != 0 {
            return Inst::UNDEF;
        }
        let mut i = Inst::new(Op::BCond, word);
        i.cond = (word & 15) as u8;
        i.imm = sext((bits(word, 23, 5) as u64) << 2, 21);
        return i;
    }
    if op0 & 3 == 0b00 {
        let mut i = Inst::new(Op::Branch, word);
        i.sub = (word >> 31) as u8;
        i.imm = sext((bits(word, 25, 0) as u64) << 2, 28);
        return i;
    }
    if op0 & 3 == 0b01 {
        if word >> 25 & 1 == 0 {
            let mut i = Inst::new(Op::CompareBranch, word);
            i.sub = (word >> 24 & 1) as u8;
            i.imm = sext((bits(word, 23, 5) as u64) << 2, 21);
            return i;
        }
        let mut i = Inst::new(Op::TestBranch, word);
        i.sub = (word >> 24 & 1) as u8;
        i.amount = (bits(word, 31, 31) << 5 | bits(word, 23, 19)) as u8;
        i.imm = sext((bits(word, 18, 5) as u64) << 2, 16);
        return i;
    }
    if op0 != 0b110 {
        return Inst::UNDEF;
    }
    // op0 = 110
    if word >> 25 & 1 == 1 {
        // unconditional branch (register)
        let opc = bits(word, 24, 21);
        if bits(word, 20, 16) != 0b11111 || bits(word, 15, 10) != 0 || word & 31 != 0 {
            return Inst::UNDEF;
        }
        return match opc {
            0b0000 | 0b0001 | 0b0010 => {
                let mut i = Inst::new(Op::BranchReg, word);
                i.sub = opc as u8;
                i
            },
            0b0100 if bits(word, 9, 5) == 31 => Inst::new(Op::Eret, word),
            // DRPS: an instruction, UNDEF outside Debug state
            0b0101 if bits(word, 9, 5) == 31 => {
                let mut i = Inst::new(Op::BranchReg, word);
                i.sub = 5;
                i
            },
            _ => Inst::UNDEF,
        };
    }
    if word >> 24 & 1 == 0 {
        // exception generation
        let opc = bits(word, 23, 21);
        let op2 = bits(word, 4, 2);
        let ll = bits(word, 1, 0);
        let sub = match (opc, op2, ll) {
            (0b000, 0, 1) => 1, // SVC
            (0b000, 0, 2) => 2, // HVC
            (0b000, 0, 3) => 3, // SMC
            (0b001, 0, 0) => 4, // BRK
            (0b010, 0, 0) => 5, // HLT
            // DCPS1-3: instructions, UNDEF outside Debug state
            (0b101, 0, 1..=3) => 5 + ll as u8,
            // TCANCEL (FEAT_TME)
            _ => return Inst::UNDEF,
        };
        let mut i = Inst::new(Op::ExceptionGen, word);
        i.sub = sub;
        i.imm = bits(word, 20, 5) as u64;
        return i;
    }
    if bits(word, 23, 22) != 0b00 {
        return Inst::UNDEF;
    }
    // system: L op0 op1 CRn CRm op2 Rt
    let l = word >> 21 & 1;
    let sys_op0 = bits(word, 20, 19);
    let op1 = bits(word, 18, 16);
    let crn = bits(word, 15, 12);
    let crm = bits(word, 11, 8);
    let op2 = bits(word, 7, 5);
    let rt = bits(word, 4, 0);
    if sys_op0 == 0 {
        if l == 1 {
            return Inst::UNDEF;
        }
        if crn == 0b0010 && op1 == 0b011 && rt == 31 {
            let mut i = Inst::new(Op::Hint, word);
            i.imm = (crm << 3 | op2) as u64;
            return i;
        }
        if crn == 0b0011 && op1 == 0b011 {
            return match (op2, rt) {
                (0b010, 31) => Inst::new(Op::Clrex, word),
                (0b100, 31) | (0b101, 31) => {
                    let mut i = Inst::new(Op::Barrier, word);
                    i.sub = (op2 - 0b100) as u8;
                    i.imm = crm as u64;
                    i
                },
                (0b110, 31) => {
                    let mut i = Inst::new(Op::Barrier, word);
                    i.sub = 2;
                    i.imm = crm as u64;
                    i
                },
                // SB (FEAT_SB), DSB nXS (FEAT_XS), TCOMMIT (FEAT_TME)
                _ => Inst::UNDEF,
            };
        }
        if crn == 0b0100 && rt == 31 {
            // MSR (immediate): SPSel, DAIFSet, DAIFClr; PAN (FEAT_PAN: profile v2,
            // UNDEFINED when it executes without it); UAO, DIT, SSBS, TCO are not
            let sub = match (op1, op2) {
                (0b000, 0b101) => 0,
                (0b011, 0b110) => 1,
                (0b011, 0b111) => 2,
                (0b000, 0b100) => 3,
                _ => return Inst::UNDEF,
            };
            let mut i = Inst::new(Op::MsrImm, word);
            i.sub = sub;
            i.imm = crm as u64;
            return i;
        }
        return Inst::UNDEF;
    }
    if sys_op0 == 1 {
        // SYS, and SYSL (sub 1: an instruction, but v1 defines no SYSL operation)
        let mut i = Inst::new(Op::Sys, word);
        i.sub = l as u8;
        i.imm = (op1 << 11 | crn << 7 | crm << 3 | op2) as u64;
        return i;
    }
    let mut i = Inst::new(if l == 1 { Op::Mrs } else { Op::Msr }, word);
    i.imm = bits(word, 20, 5) as u64;
    i
}

fn load_store(word: u32) -> Inst {
    let v = word >> 26 & 1 != 0;
    match bits(word, 29, 28) {
        0b00 => {
            if bits(word, 29, 24) == 0b001000 && !v {
                return exclusive(word);
            }
            if v && word >> 31 == 0 && bits(word, 29, 25) == 0b00110 {
                // AdvSIMD structures
                return match crate::aarch64::simd_decode::structure(word) {
                    Some(_) => {
                        let mut i = Inst::new(Op::SimdStructure, word);
                        i.imm = word as u64;
                        i
                    },
                    None => Inst::UNDEF,
                };
            }
            // LDAPR, RCPC, MTE, LSE128, ...
            Inst::UNDEF
        },
        0b01 => {
            if word >> 24 & 1 != 0 {
                // LDAPR/STLR (unscaled immediate): FEAT_LRCPC2; MTE
                return Inst::UNDEF;
            }
            let opc = bits(word, 31, 30);
            let mut i = Inst::new(Op::LoadLiteral, word);
            if v {
                // LDR (literal, SIMD&FP): sub 4 S, 5 D, 6 Q
                if opc == 3 {
                    return Inst::UNDEF;
                }
                i.sub = 4 + opc as u8;
                i.imm = sext((bits(word, 23, 5) as u64) << 2, 21);
                return i;
            }
            i.sub = opc as u8;
            i.imm = sext((bits(word, 23, 5) as u64) << 2, 21);
            i
        },
        0b10 => pair(word),
        _ => single(word),
    }
}

fn exclusive(word: u32) -> Inst {
    let size = bits(word, 31, 30);
    let o2 = word >> 23 & 1;
    let load = word >> 22 & 1;
    let o1 = word >> 21 & 1;
    let o0 = word >> 15 & 1;
    let mut i = Inst::new(Op::Exclusive, word);
    i.rm = bits(word, 20, 16) as u8;
    i.ra = bits(word, 14, 10) as u8;
    i.cond = size as u8;
    match (o2, o1) {
        (0, 0) => {
            i.sub = load as u8 | (o0 as u8) << 2;
        },
        (0, 1) => {
            if size < 2 {
                // CASP (FEAT_LSE)
                return Inst::UNDEF;
            }
            i.sub = load as u8 | 2 | (o0 as u8) << 2;
        },
        (1, 0) => {
            // LDAR/STLR; LDLAR/STLLR (o0 = 0) are FEAT_LOR
            if o0 == 0 {
                return Inst::UNDEF;
            }
            i.op = Op::LoadAcquireStoreRelease;
            i.sub = load as u8;
        },
        // CAS (FEAT_LSE)
        _ => return Inst::UNDEF,
    }
    i
}

fn pair(word: u32) -> Inst {
    let opc = bits(word, 31, 30);
    let v = word >> 26 & 1 != 0;
    let mode = bits(word, 24, 23);
    let load = word >> 22 & 1 != 0;
    let (size, signed) = if v {
        // S, D, Q
        if opc == 3 {
            return Inst::UNDEF;
        }
        (2 + opc, false)
    }
    else {
        match (opc, load) {
            (0b00, _) => (2, false),
            (0b01, true) if mode != 0 => (2, true), // LDPSW
            (0b10, _) => (3, false),
            // STGP (FEAT_MTE), LDPSW without allocation, reserved
            _ => return Inst::UNDEF,
        }
    };
    let mut i = Inst::new(Op::LoadStorePair, word);
    i.ra = bits(word, 14, 10) as u8; // Rt2
    i.cond = size as u8;
    i.sub = load as u8 | if signed { LS_SIGNED } else { 0 } | if v { LS_SIMD } else { 0 };
    i.shift = match mode {
        0b00 | 0b10 => MODE_OFFSET,
        0b01 => MODE_POST,
        _ => MODE_PRE,
    };
    if mode == 0b00 {
        i.amount = LS_NO_ALLOCATE;
    }
    i.imm = sext(bits(word, 21, 15) as u64, 7) << size;
    i
}

fn single(word: u32) -> Inst {
    let size = bits(word, 31, 30);
    let v = word >> 26 & 1 != 0;
    let opc = bits(word, 23, 22);
    let unsigned_offset = word >> 24 & 1 != 0;
    let unscaled = !unsigned_offset && word >> 21 & 1 == 0 && bits(word, 11, 10) == 0b00;
    let (mode, unprivileged) = if unsigned_offset {
        (MODE_OFFSET, false)
    }
    else if word >> 21 & 1 == 0 {
        match bits(word, 11, 10) {
            0b00 => (MODE_OFFSET, false),
            0b01 => (MODE_POST, false),
            0b10 => (MODE_OFFSET, true),
            _ => (MODE_PRE, false),
        }
    }
    else if bits(word, 11, 10) == 0b10 {
        (MODE_REGISTER, false)
    }
    else {
        // atomic memory operations (FEAT_LSE), LDRAA/LDRAB (FEAT_PAuth)
        return Inst::UNDEF;
    };
    // the access: store, load, prefetch, sign-extending loads; SIMD&FP B, H, S, D, Q
    let (sub, size_log) = if v {
        if unprivileged {
            return Inst::UNDEF;
        }
        match (size, opc) {
            (_, 0b00) => (LS_SIMD, size),
            (_, 0b01) => (LS_SIMD | LS_LOAD, size),
            (0b00, 0b10) => (LS_SIMD, 4),
            (0b00, 0b11) => (LS_SIMD | LS_LOAD, 4),
            _ => return Inst::UNDEF,
        }
    }
    else {
        match (size, opc) {
            (_, 0b00) => (0, size),
            (_, 0b01) => (LS_LOAD, size),
            (0b11, 0b10) => {
                // PRFM, PRFUM; none unprivileged or with write-back
                if unprivileged || mode == MODE_PRE || mode == MODE_POST {
                    return Inst::UNDEF;
                }
                (LS_PREFETCH, 3)
            },
            (0b11, _) | (0b10, 0b11) => return Inst::UNDEF,
            (_, 0b10) => (LS_LOAD | LS_SIGNED, size),
            (_, _) => (LS_LOAD | LS_SIGNED | LS_TO_W, size),
        }
    };
    let mut i = Inst::new(Op::LoadStore, word);
    i.cond = size_log as u8;
    i.sub = sub | if unprivileged { LS_UNPRIVILEGED } else { 0 };
    i.shift = mode;
    match mode {
        MODE_REGISTER => {
            let option = bits(word, 15, 13);
            if option & 2 == 0 {
                // (option<1> = 0 is reserved)
                return Inst::UNDEF;
            }
            i.ra = option as u8;
            i.amount = if word >> 12 & 1 != 0 { size_log as u8 } else { 0 };
        },
        _ if unsigned_offset => i.imm = (bits(word, 21, 10) as u64) << size_log,
        _ => i.imm = sext(bits(word, 20, 12) as u64, 9),
    }
    if unscaled {
        i.amount = LS_UNSCALED;
    }
    i
}

fn data_processing_register(word: u32) -> Inst {
    let sf = word >> 31 != 0;
    let op0 = word >> 30 & 1;
    let op1 = word >> 28 & 1;
    let op2 = bits(word, 24, 21);
    if op1 == 0 {
        if op2 & 0b1000 == 0 {
            // logical (shifted register)
            let imm6 = bits(word, 15, 10);
            if !sf && imm6 >= 32 {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::LogicalShifted, word);
            i.sub = (bits(word, 30, 29) << 1 | bits(word, 21, 21)) as u8;
            i.shift = bits(word, 23, 22) as u8;
            i.amount = imm6 as u8;
            return i;
        }
        if op2 & 1 == 0 {
            let shift = bits(word, 23, 22);
            let imm6 = bits(word, 15, 10);
            if shift == 3 || !sf && imm6 >= 32 {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::AddSubShifted, word);
            i.sub = op0 as u8;
            i.s = word >> 29 & 1 != 0;
            i.shift = shift as u8;
            i.amount = imm6 as u8;
            return i;
        }
        let imm3 = bits(word, 12, 10);
        if bits(word, 23, 22) != 0 || imm3 > 4 {
            return Inst::UNDEF;
        }
        let mut i = Inst::new(Op::AddSubExtended, word);
        i.sub = op0 as u8;
        i.s = word >> 29 & 1 != 0;
        i.shift = bits(word, 15, 13) as u8;
        i.amount = imm3 as u8;
        return i;
    }
    match op2 {
        0b0000 => {
            if bits(word, 15, 10) != 0 {
                // RMIF, SETF8/SETF16 (FEAT_FlagM)
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::AddSubCarry, word);
            i.sub = op0 as u8;
            i.s = word >> 29 & 1 != 0;
            i
        },
        0b0010 => {
            if word >> 29 & 1 == 0 || word >> 10 & 1 != 0 || word >> 4 & 1 != 0 {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::CondCompare, word);
            i.sub = op0 as u8;
            i.cond = bits(word, 15, 12) as u8;
            i.imm = (word & 15) as u64;
            i.amount = (word >> 11 & 1) as u8;
            i
        },
        0b0100 => {
            let op2_bits = bits(word, 11, 10);
            if word >> 29 & 1 != 0 || op2_bits >= 2 {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::CondSelect, word);
            i.sub = (op0 << 1 | op2_bits) as u8;
            i.cond = bits(word, 15, 12) as u8;
            i
        },
        0b0110 => {
            if word >> 29 & 1 != 0 {
                return Inst::UNDEF;
            }
            let opcode = bits(word, 15, 10);
            if op0 == 0 {
                let valid = match opcode {
                    0b000010 | 0b000011 | 0b001000..=0b001011 => true,
                    // CRC32B/H/W (sf 0), CRC32X (sf 1), and the CRC32C forms
                    0b010000..=0b010010 | 0b010100..=0b010110 => !sf,
                    0b010011 | 0b010111 => sf,
                    _ => false,
                };
                if !valid {
                    return Inst::UNDEF;
                }
                let mut i = Inst::new(Op::DataProc2, word);
                i.sub = opcode as u8;
                return i;
            }
            if bits(word, 20, 16) != 0 {
                return Inst::UNDEF;
            }
            let valid = match opcode {
                0b000000 | 0b000001 | 0b000100 | 0b000101 => true,
                0b000010 => true, // REV32 (sf 1) or REV (sf 0)
                0b000011 => sf,
                _ => false,
            };
            if !valid {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::DataProc1, word);
            i.sub = opcode as u8;
            i
        },
        0b1000..=0b1111 => {
            if bits(word, 30, 29) != 0 {
                return Inst::UNDEF;
            }
            let op31 = bits(word, 23, 21);
            let o0 = word >> 15 & 1;
            let valid = match (op31, o0) {
                (0b000, _) => true,
                (0b001, _) | (0b101, _) => sf,
                (0b010, 0) | (0b110, 0) => sf,
                _ => false,
            };
            if !valid {
                return Inst::UNDEF;
            }
            let mut i = Inst::new(Op::DataProc3, word);
            i.sub = (op31 << 1 | o0) as u8;
            i
        },
        _ => Inst::UNDEF,
    }
}

/// The base mnemonic (the Arm ARM's instruction name, not an alias) of a
/// decoded instruction, "" for UNDEF
pub fn mnemonic(i: &Inst) -> &'static str {
    match i.op {
        Op::Undef => "",
        Op::Adr => "adr",
        Op::Adrp => "adrp",
        Op::AddSubImm | Op::AddSubShifted | Op::AddSubExtended => match (i.sub, i.s) {
            (0, false) => "add",
            (0, true) => "adds",
            (_, false) => "sub",
            (_, true) => "subs",
        },
        Op::LogicalImm => ["and", "orr", "eor", "ands"][i.sub as usize],
        Op::MoveWide => ["movn", "", "movz", "movk"][i.sub as usize],
        Op::Bitfield => ["sbfm", "bfm", "ubfm"][i.sub as usize],
        Op::Extr => "extr",
        Op::BCond => "b.cond",
        Op::Branch => ["b", "bl"][i.sub as usize],
        Op::BranchReg => ["br", "blr", "ret", "", "", "drps"][i.sub as usize],
        Op::CompareBranch => ["cbz", "cbnz"][i.sub as usize],
        Op::TestBranch => ["tbz", "tbnz"][i.sub as usize],
        Op::ExceptionGen => [
            "", "svc", "hvc", "smc", "brk", "hlt", "dcps1", "dcps2", "dcps3",
        ][i.sub as usize],
        Op::Eret => "eret",
        Op::Hint => "hint",
        Op::Clrex => "clrex",
        Op::Barrier => ["dsb", "dmb", "isb"][i.sub as usize],
        Op::MsrImm => "msr",
        Op::Sys => ["sys", "sysl"][i.sub as usize],
        Op::Mrs => "mrs",
        Op::Msr => "msr",
        Op::LoadLiteral => ["ldr", "ldr", "ldrsw", "prfm", "ldr", "ldr", "ldr"][i.sub as usize],
        Op::LoadStore => {
            let load = i.sub & LS_LOAD != 0;
            let unprivileged = i.sub & LS_UNPRIVILEGED != 0;
            let unscaled = i.amount == LS_UNSCALED && i.shift == MODE_OFFSET;
            if i.sub & LS_SIMD != 0 {
                return match (load, unscaled) {
                    (false, false) => "str",
                    (true, false) => "ldr",
                    (false, true) => "stur",
                    (true, true) => "ldur",
                };
            }
            if i.sub & LS_PREFETCH != 0 {
                return if unscaled { "prfum" } else { "prfm" };
            }
            let signed = i.sub & LS_SIGNED != 0;
            if unscaled {
                return match (load, signed, i.cond) {
                    (false, _, 0) => "sturb",
                    (false, _, 1) => "sturh",
                    (false, _, _) => "stur",
                    (true, false, 0) => "ldurb",
                    (true, false, 1) => "ldurh",
                    (true, false, _) => "ldur",
                    (true, true, 0) => "ldursb",
                    (true, true, 1) => "ldursh",
                    (true, true, _) => "ldursw",
                };
            }
            match (load, signed, i.cond, unprivileged) {
                (false, _, 0, false) => "strb",
                (false, _, 1, false) => "strh",
                (false, _, _, false) => "str",
                (false, _, 0, true) => "sttrb",
                (false, _, 1, true) => "sttrh",
                (false, _, _, true) => "sttr",
                (true, false, 0, false) => "ldrb",
                (true, false, 1, false) => "ldrh",
                (true, false, _, false) => "ldr",
                (true, true, 0, false) => "ldrsb",
                (true, true, 1, false) => "ldrsh",
                (true, true, _, false) => "ldrsw",
                (true, false, 0, true) => "ldtrb",
                (true, false, 1, true) => "ldtrh",
                (true, false, _, true) => "ldtr",
                (true, true, 0, true) => "ldtrsb",
                (true, true, 1, true) => "ldtrsh",
                (true, true, _, true) => "ldtrsw",
            }
        },
        Op::LoadStorePair => match (
            i.sub & LS_LOAD != 0,
            i.sub & LS_SIGNED != 0,
            i.amount == LS_NO_ALLOCATE,
        ) {
            (false, _, true) => "stnp",
            (true, _, true) => "ldnp",
            (false, _, false) => "stp",
            (true, false, false) => "ldp",
            (true, true, false) => "ldpsw",
        },
        Op::Exclusive => {
            let names: [[&str; 4]; 2] = [
                ["stxr", "ldxr", "stxp", "ldxp"],
                ["stlxr", "ldaxr", "stlxp", "ldaxp"],
            ];
            let base = names[(i.sub >> 2 & 1) as usize][(i.sub & 3) as usize];
            // (store or load, plain or acquire/release)
            let kind = (i.sub & 1 | i.sub >> 1 & 2) as usize;
            match (i.sub & 2 != 0, i.cond) {
                (false, 0) => ["stxrb", "ldxrb", "stlxrb", "ldaxrb"][kind],
                (false, 1) => ["stxrh", "ldxrh", "stlxrh", "ldaxrh"][kind],
                _ => base,
            }
        },
        Op::LoadAcquireStoreRelease => match (i.sub, i.cond) {
            (0, 0) => "stlrb",
            (0, 1) => "stlrh",
            (0, _) => "stlr",
            (_, 0) => "ldarb",
            (_, 1) => "ldarh",
            _ => "ldar",
        },
        Op::LogicalShifted => {
            ["and", "bic", "orr", "orn", "eor", "eon", "ands", "bics"][i.sub as usize]
        },
        Op::AddSubCarry => match (i.sub, i.s) {
            (0, false) => "adc",
            (0, true) => "adcs",
            (_, false) => "sbc",
            (_, true) => "sbcs",
        },
        Op::CondCompare => ["ccmn", "ccmp"][i.sub as usize],
        Op::CondSelect => ["csel", "csinc", "csinv", "csneg"][i.sub as usize],
        Op::DataProc3 => match i.sub {
            0 => "madd",
            1 => "msub",
            2 => "smaddl",
            3 => "smsubl",
            4 => "smulh",
            10 => "umaddl",
            11 => "umsubl",
            _ => "umulh",
        },
        Op::DataProc2 => match i.sub {
            0b000010 => "udiv",
            0b000011 => "sdiv",
            0b001000 => "lslv",
            0b001001 => "lsrv",
            0b001010 => "asrv",
            0b001011 => "rorv",
            0b010000 => "crc32b",
            0b010001 => "crc32h",
            0b010010 => "crc32w",
            0b010011 => "crc32x",
            0b010100 => "crc32cb",
            0b010101 => "crc32ch",
            0b010110 => "crc32cw",
            _ => "crc32cx",
        },
        Op::DataProc1 => match (i.sub, i.sf) {
            (0, _) => "rbit",
            (1, _) => "rev16",
            (2, true) => "rev32",
            (2, false) | (3, _) => "rev",
            (4, _) => "clz",
            _ => "cls",
        },
        Op::SimdStructure => {
            crate::aarch64::simd_decode::structure(i.imm as u32).map_or("", |s| s.name)
        },
        _ => crate::aarch64::simd_decode::classify(i.imm as u32).map_or("", |c| c.1),
    }
}

/// (tests/a64/oracle/decode.mjs --check: the base mnemonic of a word, a
/// NUL-terminated string in the Wasm memory, empty for UNDEF)
#[no_mangle]
pub fn a64_decode_mnemonic(word: u32) -> u32 {
    static mut BUFFER: [u8; 16] = [0; 16];
    let name = mnemonic(&decode(word));
    unsafe {
        let buffer = &mut *(&raw mut BUFFER);
        buffer.fill(0);
        buffer[..name.len()].copy_from_slice(name.as_bytes());
        buffer.as_ptr() as u32
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bit_masks() {
        // ORR W0, WZR, #0x55555555 (N 0, immr 0, imms 0b111100)
        assert_eq!(decode_bit_masks(0, 0b111100, 0, false), Some(0x5555_5555));
        assert_eq!(decode_bit_masks(1, 0b000000, 0, true), Some(1));
        assert_eq!(decode_bit_masks(1, 0b111111, 0, true), None);
        assert_eq!(
            decode_bit_masks(0, 0b011111, 1, false),
            None,
            "32 ones of 32: reserved"
        );
        assert_eq!(decode_bit_masks(0, 0b011110, 1, false), Some(0xBFFF_FFFF));
    }

    #[test]
    fn some_words() {
        let m = |w: u32| mnemonic(&decode(w));
        assert_eq!(m(0xD503201F), "hint"); // NOP
        assert_eq!(m(0x8B020020), "add");
        assert_eq!(m(0xEB02003F), "subs"); // CMP
        assert_eq!(m(0xAA0103E0), "orr"); // MOV X0, X1
        assert_eq!(m(0xD2800020), "movz");
        assert_eq!(m(0x9AC20C20), "sdiv");
        assert_eq!(m(0xC85FFC20), "ldaxr");
        assert_eq!(m(0xA9BF7BFD), "stp");
        assert_eq!(m(0xF9400020), "ldr");
        assert_eq!(m(0x00000000), "");
        assert_eq!(m(0xB8200020), "", "LDADD (LSE) is outside v1");
        assert_eq!(m(0xD5380000), "mrs");
        assert_eq!(m(0xD69F03E0), "eret");
        assert_eq!(m(0xD4000001), "svc");
        assert_eq!(m(0x1AC04000), "crc32b");
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/rust/aarch64/execute.rs                                                              0000644 0000000 0000000 00000133404 00000000000 014715  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The A64 interpreter (docs/arm64-virt-android16-plan.md P2.2-P2.4, P2.9):
//! integer data processing, branches, loads and stores, exclusives, CRC32
//! and the system instructions. `interpret_one` executes the instruction at
//! the PC: an instruction that faults has written no state, and the
//! exception is taken instead (P2.9, the JIT plan's StepFrontend). Decoded
//! instructions are cached by their 32-bit word, so a cache entry is valid
//! whenever its word matches (P2.2).

use crate::aarch64::cpu::{self, *};
use crate::aarch64::decode::{
    self, Inst, Op, LS_LOAD, LS_PREFETCH, LS_SIGNED, LS_SIMD, LS_TO_W, LS_UNPRIVILEGED,
};
use crate::aarch64::decode::{MODE_POST, MODE_PRE, MODE_REGISTER};
use crate::aarch64::memory::{self, Syndrome};
use crate::aarch64::psci;
use crate::aarch64::state::{event_register, excl_addr, excl_valid, excl_value};
use crate::aarch64::sysregs;
use crate::aarch64::{crypto, fp, simd, simd_fp};

// ---- the decode cache (by instruction word)

const DECODE_CACHE_BITS: u32 = 12;
static mut DECODE_CACHE: [(u32, Inst); 1 << DECODE_CACHE_BITS] =
    [(0, Inst::UNDEF); 1 << DECODE_CACHE_BITS];

#[inline(always)]
pub fn decode_cached(word: u32) -> Inst {
    let index = (word.wrapping_mul(0x9E37_79B1) >> (32 - DECODE_CACHE_BITS)) as usize;
    let cache = unsafe { &mut *(&raw mut DECODE_CACHE) };
    let entry = &mut cache[index];
    if entry.0 != word {
        *entry = (word, decode::decode(word));
    }
    entry.1
}

// ---- helpers

/// What an instruction does to the PC
pub enum Flow {
    /// the next instruction
    Next,
    /// a branch
    Jump(u64),
    /// the PC was set (an exception return, an exception taken by the instruction)
    Set,
    /// the core waits (WFI, WFE, CPU_SUSPEND) after the instruction
    Wait(u32),
    /// the core stopped (CPU_OFF, SYSTEM_OFF)
    Off,
    /// YIELD: the next instruction, and the other cores may run first
    Yield,
    /// The instruction waits for other cores (a DSB for their TLB maintenance,
    /// P8.3): the PC stays, the core gives up its turn
    Retry,
}

#[inline(always)]
fn mask(sf: bool) -> u64 {
    if sf {
        u64::MAX
    }
    else {
        0xFFFF_FFFF
    }
}

#[inline(always)]
fn nzcv_of(result: u64, sf: bool, carry: bool, overflow: bool) -> u32 {
    let negative = if sf { result >> 63 } else { result >> 31 & 1 } != 0;
    let zero = result & mask(sf) == 0;
    (negative as u32) << 31 | (zero as u32) << 30 | (carry as u32) << 29 | (overflow as u32) << 28
}

/// AddWithCarry: the result and NZCV
#[inline(always)]
pub fn add_with_carry(x: u64, y: u64, carry_in: bool, sf: bool) -> (u64, u32) {
    if sf {
        let (r1, c1) = x.overflowing_add(y);
        let (result, c2) = r1.overflowing_add(carry_in as u64);
        let overflow = ((x ^ result) & (y ^ result)) >> 63 != 0;
        (result, nzcv_of(result, true, c1 || c2, overflow))
    }
    else {
        let (x, y) = (x as u32, y as u32);
        let (r1, c1) = x.overflowing_add(y);
        let (result, c2) = r1.overflowing_add(carry_in as u32);
        let overflow = ((x ^ result) & (y ^ result)) >> 31 != 0;
        (
            result as u64,
            nzcv_of(result as u64, false, c1 || c2, overflow),
        )
    }
}

/// A shifted register operand: LSL, LSR, ASR, ROR
#[inline(always)]
pub fn shift_reg(value: u64, kind: u8, amount: u32, sf: bool) -> u64 {
    if sf {
        match kind {
            0 => value << amount,
            1 => value >> amount,
            2 => ((value as i64) >> amount) as u64,
            _ => value.rotate_right(amount),
        }
    }
    else {
        let v = value as u32;
        (match kind {
            0 => v << amount,
            1 => v >> amount,
            2 => ((v as i32) >> amount) as u32,
            _ => v.rotate_right(amount),
        }) as u64
    }
}

/// An extended register operand: UXTB, UXTH, UXTW, UXTX, SXTB, SXTH, SXTW, SXTX, shifted left
#[inline(always)]
pub fn extend_reg(value: u64, option: u8, amount: u32) -> u64 {
    let extended = match option {
        0 => value as u8 as u64,
        1 => value as u16 as u64,
        2 => value as u32 as u64,
        3 => value,
        4 => value as i8 as i64 as u64,
        5 => value as i16 as i64 as u64,
        6 => value as i32 as i64 as u64,
        _ => value,
    };
    extended << amount
}

/// ConditionHolds for NZCV
#[inline(always)]
pub fn condition_holds(cond: u8, flags: u32) -> bool {
    let n = flags >> 31 & 1 != 0;
    let z = flags >> 30 & 1 != 0;
    let c = flags >> 29 & 1 != 0;
    let v = flags >> 28 & 1 != 0;
    let result = match cond >> 1 {
        0 => z,
        1 => c,
        2 => n,
        3 => v,
        4 => c && !z,
        5 => n == v,
        6 => n == v && !z,
        _ => true,
    };
    if cond & 1 != 0 && cond != 0b1111 {
        !result
    }
    else {
        result
    }
}

/// The masks of a bitfield instruction (DecodeBitMasks without the
/// immediate's restrictions): wmask, tmask
pub(crate) fn bitfield_masks(n: u32, imms: u32, immr: u32, sf: bool) -> (u64, u64) {
    let combined = n << 6 | !imms & 0x3F;
    let len = 31 - combined.leading_zeros();
    let levels = (1u32 << len) - 1;
    let s = imms & levels;
    let r = immr & levels;
    let diff = s.wrapping_sub(r) & levels;
    let esize = 1u32 << len;
    let ones = |count: u32| if count >= 64 { u64::MAX } else { (1u64 << count) - 1 };
    let emask = ones(esize);
    let welem = ones(s + 1);
    let telem = ones(diff + 1);
    let wrot = if r == 0 { welem } else { (welem >> r | welem << (esize - r)) & emask };
    let replicate = |element: u64| {
        let mut result = 0;
        let mut at = 0;
        while at < 64 {
            result |= element << at;
            at += esize;
        }
        result
    };
    let width = mask(sf);
    (replicate(wrot) & width, replicate(telem) & width)
}

/// The SP alignment check of a load or store with the SP as its base
#[inline(always)]
pub(crate) fn check_sp(rn: u32, base: u64) -> Result<(), Exception> {
    if rn == 31 && base & 15 != 0 {
        let sctlr = cpu::sctlr();
        if sctlr & if cpu::el() == 0 { SCTLR_SA0 } else { SCTLR_SA } != 0 {
            return Err(Exception::SpAlignment);
        }
    }
    Ok(())
}

/// A branch target (TBI: AArch64.BranchAddr)
#[inline(always)]
fn branch_target(target: u64) -> u64 { crate::aarch64::mmu::branch_address(target) }

// ---- CRC32

fn crc32(acc: u32, value: u64, bytes: u32, castagnoli: bool) -> u32 {
    let poly: u32 = if castagnoli { 0x82F6_3B78 } else { 0xEDB8_8320 };
    let mut crc = acc;
    for i in 0..bytes {
        crc ^= (value >> (8 * i)) as u8 as u32;
        for _ in 0..8 {
            crc = crc >> 1 ^ poly & (crc & 1).wrapping_neg();
        }
    }
    crc
}

// ---- DC ZVA

/// DC ZVA: zero the 64-byte block holding `va` (DCZID_EL0.BS = 4); an
/// alignment fault on Device memory (the MMU off, or a Device mapping), as
/// the Arm ARM says (QEMU zeroes there: an allowed difference). DC ZVA is no
/// cache maintenance instruction for ESR.CM, which stays 0.
pub fn dc_zva(va: u64, rt: u32) -> Result<(), Exception> {
    let block = va & !63;
    let syndrome = Syndrome {
        register: rt,
        ..Syndrome::NONE
    };
    let device_fault = Exception::DataAbort {
        iss: FSC_ALIGNMENT | 1 << 6,
        far: va,
    };
    if cpu::sctlr() & SCTLR_M == 0 {
        return Err(device_fault);
    }
    // (one 64-byte block lies in one page: checked once, then written as 8 doublewords)
    memory::prepare_write(block, 64, false, syndrome).map_err(|e| with_far(e, va))?;
    if let Ok(translation) =
        crate::aarch64::mmu::translate(block, memory::Access::Write, cpu::el() == 0, 1)
    {
        if translation.device {
            return Err(device_fault);
        }
    }
    for i in 0..8 {
        memory::write(block + 8 * i, 8, 0, false, syndrome).map_err(|e| with_far(e, va))?;
    }
    Ok(())
}

fn with_far(exception: Exception, far: u64) -> Exception {
    match exception {
        Exception::DataAbort { iss, .. } => Exception::DataAbort { iss, far },
        other => other,
    }
}

// ---- execution

/// Execute `inst` (`word`, at `address`)
pub fn execute(inst: &Inst, address: u64) -> Result<Flow, Exception> {
    let i = inst;
    let rd = i.rd as u32;
    let rn = i.rn as u32;
    let rm = i.rm as u32;
    let sf = i.sf;
    match i.op {
        Op::Undef => Err(Exception::Undefined),

        // ---- data processing (immediate)
        Op::Adr => {
            set_x(rd, address.wrapping_add(i.imm));
            Ok(Flow::Next)
        },
        Op::Adrp => {
            set_x(rd, (address & !0xFFF).wrapping_add(i.imm));
            Ok(Flow::Next)
        },
        Op::AddSubImm => {
            let x = xr_sp(rn);
            let (result, flags) = if i.sub == 0 {
                add_with_carry(x, i.imm, false, sf)
            }
            else {
                add_with_carry(x, !i.imm, true, sf)
            };
            if i.s {
                set_nzcv(flags);
                set_xw(rd, sf, result);
            }
            else {
                set_xw_sp(rd, sf, result);
            }
            Ok(Flow::Next)
        },
        Op::LogicalImm => {
            let x = xr(rn);
            let result = match i.sub {
                0 | 3 => x & i.imm,
                1 => x | i.imm,
                _ => x ^ i.imm,
            } & mask(sf);
            if i.sub == 3 {
                set_nzcv(nzcv_of(result, sf, false, false));
                set_xw(rd, sf, result);
            }
            else {
                set_xw_sp(rd, sf, result);
            }
            Ok(Flow::Next)
        },
        Op::MoveWide => {
            let shifted = i.imm << i.amount;
            let result = match i.sub {
                0 => !shifted,
                2 => shifted,
                _ => xr(rd) & !(0xFFFF << i.amount) | shifted,
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::Bitfield => {
            let imms = i.imm as u32;
            let immr = i.amount as u32;
            let (wmask, tmask) = bitfield_masks(sf as u32, imms, immr, sf);
            let src = xr(rn);
            let rotated = shift_reg(src, 3, immr, sf) & mask(sf);
            let result = match i.sub {
                0 => {
                    let bot = rotated & wmask;
                    let sign = src >> imms & 1;
                    let top = if sign != 0 { mask(sf) } else { 0 };
                    top & !tmask | bot & tmask
                },
                1 => {
                    let dst = xr(rd);
                    let bot = dst & !wmask | rotated & wmask;
                    dst & !tmask | bot & tmask
                },
                _ => rotated & wmask & tmask,
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::Extr => {
            let lsb = i.amount as u32;
            let result = if sf {
                if lsb == 0 {
                    xr(rm)
                }
                else {
                    xr(rm) >> lsb | xr(rn) << (64 - lsb)
                }
            }
            else {
                let concatenated = (wr(rn) as u64) << 32 | wr(rm) as u64;
                (concatenated >> lsb) as u32 as u64
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },

        // ---- branches
        Op::BCond => {
            if condition_holds(i.cond, get_nzcv()) {
                Ok(Flow::Jump(branch_target(address.wrapping_add(i.imm))))
            }
            else {
                Ok(Flow::Next)
            }
        },
        Op::Branch => {
            if i.sub == 1 {
                set_x(30, address.wrapping_add(4));
            }
            Ok(Flow::Jump(branch_target(address.wrapping_add(i.imm))))
        },
        Op::BranchReg => {
            if i.sub == 5 {
                // DRPS: UNDEF outside Debug state
                return Err(Exception::Undefined);
            }
            let target = xr(rn);
            if i.sub == 1 {
                set_x(30, address.wrapping_add(4));
            }
            Ok(Flow::Jump(branch_target(target)))
        },
        Op::CompareBranch => {
            let zero = xr(rd) & mask(sf) == 0;
            if zero == (i.sub == 0) {
                Ok(Flow::Jump(branch_target(address.wrapping_add(i.imm))))
            }
            else {
                Ok(Flow::Next)
            }
        },
        Op::TestBranch => {
            let set = xr(rd) >> i.amount & 1 != 0;
            if set == (i.sub == 1) {
                Ok(Flow::Jump(branch_target(address.wrapping_add(i.imm))))
            }
            else {
                Ok(Flow::Next)
            }
        },
        Op::ExceptionGen => {
            let imm = i.imm as u16;
            match i.sub {
                1 => Err(Exception::Svc(imm)),
                2 => {
                    if cpu::el() == 0 {
                        return Err(Exception::Undefined);
                    }
                    Ok(match psci::call() {
                        psci::After::Continue => Flow::Next,
                        psci::After::Wait => Flow::Wait(1),
                        psci::After::Off => Flow::Off,
                    })
                },
                4 => Err(Exception::Brk(imm)),
                // SMC (no EL3), HLT (halting debug is off)
                _ => Err(Exception::Undefined),
            }
        },
        Op::Eret => {
            if cpu::el() == 0 {
                return Err(Exception::Undefined);
            }
            cpu::exception_return();
            Ok(Flow::Set)
        },
        Op::Hint => match i.imm {
            // WFE: wait unless the event register is set (it traps at EL0 with
            // SCTLR_EL1.nTWE clear only when it would wait)
            2 => unsafe {
                if *event_register != 0 {
                    *event_register = 0;
                    Ok(Flow::Next)
                }
                else if cpu::el() == 0 && cpu::sctlr() & SCTLR_NTWE == 0 {
                    Err(Exception::Wfx(1))
                }
                else {
                    Ok(Flow::Wait(2))
                }
            },
            3 => {
                if cpu::el() == 0 && cpu::sctlr() & SCTLR_NTWI == 0 {
                    return Err(Exception::Wfx(0));
                }
                Ok(Flow::Wait(1))
            },
            4 => {
                crate::aarch64::smp::send_event();
                Ok(Flow::Next)
            },
            5 => {
                unsafe { *event_register = 1 };
                Ok(Flow::Next)
            },
            1 => Ok(Flow::Yield),
            // NOP and the unimplemented hints (ESB, PSB, CSDB, PAC, BTI, ...)
            _ => Ok(Flow::Next),
        },
        Op::Clrex => {
            unsafe { *excl_valid = 0 };
            crate::aarch64::smp::release();
            Ok(Flow::Next)
        },
        Op::Barrier => {
            crate::parallel::full_fence();
            // (DSB: with cores in workers, the TLB maintenance and IC this
            // core posted are done on the others first, P8.3)
            if i.sub == 0 && !crate::aarch64::tlb::synced() {
                return Ok(Flow::Retry);
            }
            Ok(Flow::Next)
        },
        Op::MsrImm => {
            sysregs::write_pstate_field(i.sub, i.imm as u32)?;
            Ok(Flow::Next)
        },
        Op::Sys => {
            if i.sub == 1 {
                // SYSL: none in v1
                return Err(Exception::Undefined);
            }
            sysregs::sys(i.imm as u32, rd)?;
            Ok(Flow::Next)
        },
        Op::Mrs => {
            let value = sysregs::read(i.imm as u32, rd)?;
            set_x(rd, value);
            Ok(Flow::Next)
        },
        Op::Msr => {
            sysregs::write(i.imm as u32, rd, xr(rd))?;
            Ok(Flow::Next)
        },

        // ---- loads and stores
        Op::LoadLiteral if i.sub >= 4 => {
            // LDR (literal, SIMD&FP): S, D, Q
            fp::check_access()?;
            let va = address.wrapping_add(i.imm);
            let value = simd::read_vector(va, 4 << (i.sub - 4))?;
            simd::set_vreg(rd, value);
            Ok(Flow::Next)
        },
        Op::LoadLiteral => {
            let va = address.wrapping_add(i.imm);
            let syndrome = Syndrome {
                valid: true,
                size_log: 2,
                register: rd,
                ..Syndrome::NONE
            };
            match i.sub {
                0 => set_x(rd, memory::read(va, 4, false, syndrome)?),
                1 => set_x(
                    rd,
                    memory::read(
                        va,
                        8,
                        false,
                        Syndrome {
                            size_log: 3,
                            sixty_four: true,
                            ..syndrome
                        },
                    )?,
                ),
                2 => set_x(
                    rd,
                    memory::read(
                        va,
                        4,
                        false,
                        Syndrome {
                            signed: true,
                            sixty_four: true,
                            ..syndrome
                        },
                    )? as u32 as i32 as i64 as u64,
                ),
                _ => {},
            }
            Ok(Flow::Next)
        },
        Op::LoadStore => load_store(i),
        Op::LoadStorePair => load_store_pair(i),
        Op::Exclusive => exclusive(i, address),
        Op::LoadAcquireStoreRelease => {
            let size_log = i.cond as u32;
            let size = 1u32 << size_log;
            let base = xr_sp(rn);
            check_sp(rn, base)?;
            // (aligned, or an alignment fault even to Normal memory)
            let syndrome = Syndrome {
                valid: true,
                size_log,
                register: rd,
                sixty_four: size_log == 3,
                acquire_release: true,
                ..Syndrome::NONE
            };
            if base & (size as u64 - 1) != 0 {
                return Err(alignment(base, i.sub == 0, syndrome));
            }
            if i.sub == 1 {
                let value = memory::read(base, size, false, syndrome)?;
                crate::parallel::full_fence();
                set_x(rd, value);
            }
            else {
                crate::parallel::full_fence();
                memory::write(base, size, xr(rd), false, syndrome)?;
            }
            Ok(Flow::Next)
        },

        // ---- data processing (register)
        Op::LogicalShifted => {
            let operand = shift_reg(xr(rm), i.shift, i.amount as u32, sf);
            let operand = if i.sub & 1 != 0 { !operand } else { operand };
            let x = xr(rn);
            let result = match i.sub >> 1 {
                0 | 3 => x & operand,
                1 => x | operand,
                _ => x ^ operand,
            } & mask(sf);
            if i.sub >> 1 == 3 {
                set_nzcv(nzcv_of(result, sf, false, false));
            }
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::AddSubShifted => {
            let operand = shift_reg(xr(rm), i.shift, i.amount as u32, sf);
            let x = xr(rn);
            let (result, flags) = if i.sub == 0 {
                add_with_carry(x, operand, false, sf)
            }
            else {
                add_with_carry(x, !operand, true, sf)
            };
            if i.s {
                set_nzcv(flags);
            }
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::AddSubExtended => {
            let operand = extend_reg(xr(rm), i.shift, i.amount as u32);
            let x = xr_sp(rn);
            let (result, flags) = if i.sub == 0 {
                add_with_carry(x, operand, false, sf)
            }
            else {
                add_with_carry(x, !operand, true, sf)
            };
            if i.s {
                set_nzcv(flags);
                set_xw(rd, sf, result);
            }
            else {
                set_xw_sp(rd, sf, result);
            }
            Ok(Flow::Next)
        },
        Op::AddSubCarry => {
            let carry = get_nzcv() & NZCV_C != 0;
            let operand = if i.sub == 0 { xr(rm) } else { !xr(rm) };
            let (result, flags) = add_with_carry(xr(rn), operand, carry, sf);
            if i.s {
                set_nzcv(flags);
            }
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::CondCompare => {
            if condition_holds(i.cond, get_nzcv()) {
                let operand = if i.amount == 1 { rm as u64 } else { xr(rm) };
                let (_, flags) = if i.sub == 0 {
                    add_with_carry(xr(rn), operand, false, sf)
                }
                else {
                    add_with_carry(xr(rn), !operand, true, sf)
                };
                set_nzcv(flags);
            }
            else {
                set_nzcv((i.imm as u32) << 28);
            }
            Ok(Flow::Next)
        },
        Op::CondSelect => {
            let result = if condition_holds(i.cond, get_nzcv()) {
                xr(rn)
            }
            else {
                let m = xr(rm);
                match i.sub {
                    0 => m,
                    1 => m.wrapping_add(1),
                    2 => !m,
                    _ => m.wrapping_neg(),
                }
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::DataProc3 => {
            let ra = i.ra as u32;
            let (n, m, a) = (xr(rn), xr(rm), xr(ra));
            let result = match i.sub {
                0 => a.wrapping_add(n.wrapping_mul(m)),
                1 => a.wrapping_sub(n.wrapping_mul(m)),
                2 => a.wrapping_add(
                    (n as u32 as i32 as i64).wrapping_mul(m as u32 as i32 as i64) as u64,
                ),
                3 => a.wrapping_sub(
                    (n as u32 as i32 as i64).wrapping_mul(m as u32 as i32 as i64) as u64,
                ),
                4 => ((n as i64 as i128 * m as i64 as i128) >> 64) as u64,
                10 => a.wrapping_add((n as u32 as u64).wrapping_mul(m as u32 as u64)),
                11 => a.wrapping_sub((n as u32 as u64).wrapping_mul(m as u32 as u64)),
                _ => ((n as u128 * m as u128) >> 64) as u64,
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        Op::DataProc2 => {
            let (n, m) = (xr(rn), xr(rm));
            let width = if sf { 64 } else { 32 };
            let result = match i.sub {
                0b000010 => {
                    if sf {
                        if m == 0 {
                            0
                        }
                        else {
                            n / m
                        }
                    }
                    else {
                        let (n, m) = (n as u32, m as u32);
                        if m == 0 {
                            0
                        }
                        else {
                            (n / m) as u64
                        }
                    }
                },
                0b000011 => {
                    if sf {
                        if m == 0 {
                            0
                        }
                        else {
                            (n as i64).wrapping_div(m as i64) as u64
                        }
                    }
                    else {
                        let (n, m) = (n as u32 as i32, m as u32 as i32);
                        if m == 0 {
                            0
                        }
                        else {
                            n.wrapping_div(m) as u32 as u64
                        }
                    }
                },
                0b001000..=0b001011 => shift_reg(n, i.sub - 0b001000, (m % width) as u32, sf),
                op => {
                    let bytes = 1 << (op & 3);
                    crc32(n as u32, m, bytes, op & 0b100 != 0) as u64
                },
            };
            if i.sub >= 0b010000 {
                // (CRC32X takes a 64-bit value; every CRC32 result is a W register)
                set_w(rd, result as u32);
            }
            else {
                set_xw(rd, sf, result);
            }
            Ok(Flow::Next)
        },
        Op::DataProc1 => {
            let n = xr(rn);
            let result = match (i.sub, sf) {
                (0, true) => n.reverse_bits(),
                (0, false) => (n as u32).reverse_bits() as u64,
                (1, _) => {
                    let swapped =
                        (n & 0x00FF_00FF_00FF_00FF) << 8 | (n & 0xFF00_FF00_FF00_FF00) >> 8;
                    swapped & mask(sf)
                },
                (2, true) => {
                    let low = (n as u32).swap_bytes() as u64;
                    let high = ((n >> 32) as u32).swap_bytes() as u64;
                    high << 32 | low
                },
                (2, false) => (n as u32).swap_bytes() as u64,
                (3, _) => n.swap_bytes(),
                (4, true) => n.leading_zeros() as u64,
                (4, false) => (n as u32).leading_zeros() as u64,
                (_, true) => {
                    let sign_bits =
                        if (n as i64) < 0 { (!n).leading_zeros() } else { n.leading_zeros() };
                    (sign_bits - 1) as u64
                },
                (_, false) => {
                    let w = n as u32;
                    let sign_bits =
                        if (w as i32) < 0 { (!w).leading_zeros() } else { w.leading_zeros() };
                    (sign_bits - 1) as u64
                },
            };
            set_xw(rd, sf, result);
            Ok(Flow::Next)
        },
        // ---- scalar FP, AdvSIMD, crypto (P2.5-P2.8, P2.11)
        Op::SimdStructure => simd::structure(i.imm as u32),
        _ => {
            fp::check_access()?;
            let word = i.imm as u32;
            Ok(match i.op {
                Op::FpDp1 => simd_fp::dp1(word),
                Op::FpDp2 => simd_fp::dp2(word),
                Op::FpDp3 => simd_fp::dp3(word),
                Op::FpCompare => simd_fp::compare(word),
                Op::FpCondCompare => simd_fp::cond_compare(word),
                Op::FpCondSelect => simd_fp::cond_select(word),
                Op::FpImm => simd_fp::immediate(word),
                Op::FpFixed => simd_fp::fixed(word),
                Op::FpInt => simd_fp::int(word),
                Op::SimdThreeSame => simd::three_same(word),
                Op::SimdThreeDiff => simd::three_different(word),
                Op::SimdTwoMisc => simd::two_misc(word),
                Op::SimdAcross => simd::across(word),
                Op::SimdPairwise => simd::pairwise(word),
                Op::SimdCopy => simd::copy(word),
                Op::SimdModImm => simd::modified_immediate(word),
                Op::SimdShiftImm => simd::shift_immediate(word),
                Op::SimdIndexed => simd::indexed(word),
                Op::SimdTable => simd::table(word),
                Op::SimdPermute => simd::permute(word),
                Op::SimdExtract => simd::extract(word),
                Op::CryptoAes => crypto::aes(word),
                Op::CryptoSha3 => crypto::sha3(word),
                _ => crypto::sha2(word),
            })
        },
    }
}

pub(crate) fn alignment(va: u64, write: bool, _syndrome: Syndrome) -> Exception {
    // (ISV 0, as for every data abort taken to EL1: memory.rs)
    Exception::DataAbort {
        iss: FSC_ALIGNMENT | (write as u32) << 6,
        far: va,
    }
}

/// LDR/STR and their variants (one register)
fn load_store(i: &Inst) -> Result<Flow, Exception> {
    let rt = i.rd as u32;
    let rn = i.rn as u32;
    let size_log = i.cond as u32;
    let size = 1u32 << size_log;
    if i.sub & LS_SIMD != 0 {
        fp::check_access()?;
    }
    let base = xr_sp(rn);
    check_sp(rn, base)?;
    let address = match i.shift {
        MODE_POST => base,
        MODE_REGISTER => base.wrapping_add(extend_reg(xr(i.rm as u32), i.ra, i.amount as u32)),
        _ => base.wrapping_add(i.imm),
    };
    let writeback = i.shift == MODE_PRE || i.shift == MODE_POST;
    let new_base = if i.shift == MODE_POST { base.wrapping_add(i.imm) } else { address };
    if i.sub & LS_PREFETCH != 0 {
        // (PRFM never faults)
        return Ok(Flow::Next);
    }
    if i.sub & LS_SIMD != 0 {
        // a SIMD&FP register: B, H, S, D, Q
        if i.sub & LS_LOAD != 0 {
            let value = simd::read_vector(address, size)?;
            simd::set_vreg(rt, value);
        }
        else {
            let value = simd::vreg(rt);
            simd::prepare_vector_write(address, size)?.commit(value)?;
        }
        if writeback {
            set_x_sp(rn, new_base);
        }
        return Ok(Flow::Next);
    }
    let unprivileged = i.sub & LS_UNPRIVILEGED != 0 && cpu::el() == 1;
    let load = i.sub & LS_LOAD != 0;
    let signed = i.sub & LS_SIGNED != 0;
    let to_w = i.sub & LS_TO_W != 0;
    let syndrome = Syndrome {
        valid: !writeback,
        size_log,
        signed,
        register: rt,
        sixty_four: if load { signed && !to_w || !signed && size_log == 3 } else { size_log == 3 },
        ..Syndrome::NONE
    };
    if load {
        let raw = memory::read(address, size, unprivileged, syndrome)?;
        let value = if signed {
            let extended = match size_log {
                0 => raw as u8 as i8 as i64 as u64,
                1 => raw as u16 as i16 as i64 as u64,
                _ => raw as u32 as i32 as i64 as u64,
            };
            if to_w {
                extended as u32 as u64
            }
            else {
                extended
            }
        }
        else {
            raw
        };
        set_x(rt, value);
    }
    else {
        memory::write(address, size, xr(rt), unprivileged, syndrome)?;
    }
    if writeback {
        set_x_sp(rn, new_base);
    }
    Ok(Flow::Next)
}

/// LDP/STP/LDNP/STNP/LDPSW
fn load_store_pair(i: &Inst) -> Result<Flow, Exception> {
    let rt = i.rd as u32;
    let rt2 = i.ra as u32;
    let rn = i.rn as u32;
    let size_log = i.cond as u32;
    let size = 1u32 << size_log;
    let base = xr_sp(rn);
    check_sp(rn, base)?;
    let address = if i.shift == MODE_POST { base } else { base.wrapping_add(i.imm) };
    let writeback = i.shift == MODE_PRE || i.shift == MODE_POST;
    let new_base = if i.shift == MODE_POST { base.wrapping_add(i.imm) } else { address };
    if i.sub & LS_SIMD != 0 {
        // SIMD&FP pairs: S, D, Q
        let second_address = address.wrapping_add(size as u64);
        if i.sub & LS_LOAD != 0 {
            let first = simd::read_vector(address, size)?;
            let second = simd::read_vector(second_address, size)?;
            simd::set_vreg(rt, first);
            simd::set_vreg(rt2, second);
        }
        else {
            let (first, second) = (simd::vreg(rt), simd::vreg(rt2));
            let a = simd::prepare_vector_write(address, size)?;
            let b = simd::prepare_vector_write(second_address, size)?;
            a.commit(first)?;
            b.commit(second)?;
        }
        if writeback {
            set_x_sp(rn, new_base);
        }
        return Ok(Flow::Next);
    }
    if i.sub & LS_LOAD != 0 {
        let first = memory::read(address, size, false, Syndrome::NONE)?;
        let second = memory::read(
            address.wrapping_add(size as u64),
            size,
            false,
            Syndrome::NONE,
        )?;
        let extend = |value: u64| {
            if i.sub & LS_SIGNED != 0 {
                value as u32 as i32 as i64 as u64
            }
            else {
                value
            }
        };
        set_x(rt, extend(first));
        set_x(rt2, extend(second));
    }
    else {
        let (first, second) = (xr(rt), xr(rt2));
        // (both translated before either is written)
        let a = memory::prepare_write(address, size, false, Syndrome::NONE)?;
        let b = memory::prepare_write(
            address.wrapping_add(size as u64),
            size,
            false,
            Syndrome::NONE,
        )?;
        a.commit(first)?;
        b.commit(second)?;
    }
    if writeback {
        set_x_sp(rn, new_base);
    }
    Ok(Flow::Next)
}

/// The exclusive monitor's granule (P3.3: 64 bytes)
const GRANULE: u64 = !63;

/// A spin on a load-exclusive (P3.9): the PC and value of each core's last
/// one and how often it repeated with no store-exclusive between. A core
/// that keeps reading the same value at the same load waits for another
/// core (a lock without WFE): its turn ends there, as a YIELD's does
static mut SPIN: [(u64, u128, u32); crate::isa::MAX_CORES] = [(0, 0, 0); crate::isa::MAX_CORES];
const SPIN_YIELD: u32 = 4;

/// LDXR/STXR/LDAXR/STLXR/LDXP/STXP/LDAXP/STLXP
fn exclusive(i: &Inst, address: u64) -> Result<Flow, Exception> {
    let rn = i.rn as u32;
    let base = xr_sp(rn);
    check_sp(rn, base)?;
    exclusive_at(i, address, base)
}

/// An exclusive load or store of `i` (the instruction at `address`) at `base`
/// (AArch32's: its offset added)
pub(crate) fn exclusive_at(i: &Inst, address: u64, base: u64) -> Result<Flow, Exception> {
    let rt = i.rd as u32;
    let rt2 = i.ra as u32;
    let rs = i.rm as u32;
    let load = i.sub & 1 != 0;
    let pair = i.sub & 2 != 0;
    let element_log = i.cond as u32;
    let total = (1u32 << element_log) * if pair { 2 } else { 1 };
    if base & (total as u64 - 1) != 0 {
        return Err(alignment(base, !load, Syndrome::NONE));
    }
    if load {
        let (first, second) = if total <= 8 {
            let value = memory::read(base, total, false, Syndrome::NONE)?;
            if pair {
                let half = 32 * (element_log == 2) as u32 + 64 * (element_log == 3) as u32;
                (
                    value & (1u64 << half).wrapping_sub(1),
                    if half == 64 { 0 } else { value >> half },
                )
            }
            else {
                (value, 0)
            }
        }
        else {
            let low = memory::read(base, 8, false, Syndrome::NONE)?;
            let high = memory::read(base + 8, 8, false, Syndrome::NONE)?;
            (low, high)
        };
        let pa = crate::aarch64::mmu::physical_address_of(base).unwrap_or(base);
        unsafe {
            *excl_valid = 1;
            *excl_addr = pa & GRANULE;
            *excl_value = first as u128 | (second as u128) << 64;
        }
        // (guest RAM: the global monitor marks the granule too, P3.7)
        match monitor_key(pa) {
            Some(backing) => crate::aarch64::smp::reserve(backing),
            None => crate::aarch64::smp::release(),
        }
        if i.sub & 4 != 0 {
            crate::parallel::full_fence();
        }
        set_x(rt, first);
        if pair {
            set_x(rt2, second);
        }
        let value = first as u128 | (second as u128) << 64;
        let spin = unsafe { &mut SPIN[crate::isa::current_core()] };
        if spin.0 == address && spin.1 == value {
            spin.2 += 1;
            if spin.2 >= SPIN_YIELD {
                spin.2 = 0;
                return Ok(Flow::Yield);
            }
        }
        else {
            *spin = (address, value, 0);
        }
        return Ok(Flow::Next);
    }
    // a store-exclusive: translated and checked first (it faults even when it would fail)
    let (first, second) = (xr(rt), if pair { xr(rt2) } else { 0 });
    let stores = if total <= 8 {
        let value = if pair {
            if element_log == 2 {
                first & 0xFFFF_FFFF | second << 32
            }
            else {
                first
            }
        }
        else {
            first
        };
        (
            memory::prepare_write(base, total, false, Syndrome::NONE)?,
            None,
            value,
            0,
        )
    }
    else {
        (
            memory::prepare_write(base, 8, false, Syndrome::NONE)?,
            Some(memory::prepare_write(base + 8, 8, false, Syndrome::NONE)?),
            first,
            second,
        )
    };
    let pa = crate::aarch64::mmu::physical_address_of(base).unwrap_or(base);
    // (the local monitor, and for guest RAM the global one: another core's or
    // a device's write to the granule cleared it)
    let success = unsafe { *excl_valid != 0 && *excl_addr == pa & GRANULE }
        && monitor_key(pa).map_or(true, crate::aarch64::smp::reserved);
    let loaded = unsafe { *excl_value };
    unsafe { *excl_valid = 0 };
    crate::aarch64::smp::release();
    unsafe { SPIN[crate::isa::current_core()].0 = 0 };
    if success && crate::parallel::active() {
        // (cores in workers, P8.3: the store commits only if memory still
        // holds what the load-exclusive read, as QEMU does: another core's
        // compiled store does not clear the reservation, and a value written
        // back passes, the deviation docs/aarch64.md declares)
        if i.sub & 4 != 0 {
            crate::parallel::full_fence();
        }
        let (expected, value) = if total <= 8 {
            let low = loaded as u64;
            let high = (loaded >> 64) as u64;
            let expected =
                if pair && element_log == 2 { low & 0xFFFF_FFFF | high << 32 } else { low };
            (expected as u128, stores.2 as u128)
        }
        else {
            (loaded, stores.2 as u128 | (stores.3 as u128) << 64)
        };
        let stored = store_compared(
            pa, total, expected, value, stores.0, stores.1, stores.2, stores.3,
        )?;
        set_w(rs, if stored { 0 } else { 1 });
        return Ok(Flow::Next);
    }
    if success {
        if i.sub & 4 != 0 {
            crate::parallel::full_fence();
        }
        stores.0.commit(stores.2)?;
        if let Some(high) = stores.1 {
            high.commit(stores.3)?;
        }
    }
    set_w(rs, if success { 0 } else { 1 });
    Ok(Flow::Next)
}

/// (cores in workers) a store-exclusive's `total` bytes at `pa`: `value`
/// if they still hold `expected`, whether they did. RAM and device memory
/// compare and exchange atomically; extended RAM under its lock; anything
/// else (ROM, a device) is written as before
#[allow(clippy::too_many_arguments)]
fn store_compared(
    pa: u64,
    total: u32,
    expected: u128,
    value: u128,
    low: memory::Store,
    high: Option<memory::Store>,
    low_value: u64,
    high_value: u64,
) -> Result<bool, Exception> {
    use crate::aarch64::bus::{self, Lookup};
    match bus::bus().lookup(pa) {
        Lookup::Ram {
            backing,
            writable: true,
            ..
        } => {
            let p = unsafe { bus::MEM8.add(backing as usize) };
            let stored = unsafe {
                if total == 16 {
                    crate::parallel::compare_exchange128(p, expected, value)
                }
                else {
                    crate::parallel::compare_exchange(p, total, expected as u64, value as u64)
                }
            };
            if stored {
                bus::written(backing, total);
            }
            Ok(stored)
        },
        Lookup::Extended { .. } => {
            let _guard = unsafe { crate::extended::Guard::new() };
            let current = if total == 16 {
                unsafe {
                    crate::aarch64::extended::read(pa, 8) as u128
                        | (crate::aarch64::extended::read(pa + 8, 8) as u128) << 64
                }
            }
            else {
                unsafe { crate::aarch64::extended::read(pa, total) as u128 }
            };
            if current != expected {
                return Ok(false);
            }
            low.commit(low_value)?;
            if let Some(high) = high {
                high.commit(high_value)?;
            }
            Ok(true)
        },
        _ => {
            low.commit(low_value)?;
            if let Some(high) = high {
                high.commit(high_value)?;
            }
            Ok(true)
        },
    }
}

/// The global monitor's key of physical address `pa`, if it is RAM: the
/// offset in guest memory's backing, or extended RAM's key
fn monitor_key(pa: u64) -> Option<u32> {
    match crate::aarch64::bus::bus().lookup(pa) {
        crate::aarch64::bus::Lookup::Ram { backing, .. } => Some(backing),
        crate::aarch64::bus::Lookup::Extended { .. } => {
            Some(crate::aarch64::extended::monitor_key(pa))
        },
        _ => None,
    }
}

// ---- UNDEF telemetry (P2.3): counts by EL and encoding class, the last ones

/// UNDEF counts: [EL][bits 28:25 of the word]
static mut UNDEF_COUNTS: [[u32; 16]; 2] = [[0; 16]; 2];
/// The last UNDEFs: (PC, word, EL), a ring
static mut UNDEF_LAST: [(u64, u32, u32); 16] = [(0, 0, 0); 16];
static mut UNDEF_NEXT: usize = 0;

#[cold]
fn note_undefined(address: u64) {
    let word = memory::fetch(address).unwrap_or(0);
    let el = cpu::el() as usize & 1;
    unsafe {
        UNDEF_COUNTS[el][(word >> 25 & 15) as usize] += 1;
        UNDEF_LAST[UNDEF_NEXT % 16] = (address, word, el as u32);
        UNDEF_NEXT += 1;
    }
}

/// (diagnostics) UNDEFs at `el` (0 or 1) in encoding class `class` (bits 28:25); class 16: all
#[no_mangle]
pub fn a64_undef_count(el: u32, class: u32) -> u32 {
    let counts = unsafe { &*(&raw const UNDEF_COUNTS) }[el as usize & 1];
    if class >= 16 {
        counts.iter().sum()
    }
    else {
        counts[class as usize]
    }
}
/// (diagnostics) the i-th most recent UNDEF: its PC (low, high), word and EL by `field` 0-3
#[no_mangle]
pub fn a64_undef_last(i: u32, field: u32) -> u32 {
    unsafe {
        if i as usize >= UNDEF_NEXT.min(16) {
            return 0;
        }
        let (pc, word, el) = UNDEF_LAST[(UNDEF_NEXT - 1 - i as usize) % 16];
        match field {
            0 => pc as u32,
            1 => (pc >> 32) as u32,
            2 => word,
            _ => el,
        }
    }
}

// ---- one instruction

/// Fetch the instruction at the PC
#[inline(always)]
fn fetch_at(address: u64) -> Result<u32, Exception> {
    if address & 3 != 0 {
        return Err(Exception::PcAlignment(address));
    }
    memory::fetch(address)
}

/// The stepped instruction was a load-exclusive (ISS.EX of the step exception), per core
static mut STEPPED_EXCLUSIVE_LOADS: [bool; crate::isa::MAX_CORES] = [false; crate::isa::MAX_CORES];
pub(crate) static mut STEPPED_EXCLUSIVE_LOAD: bool = false;

/// (diagnostics, crate::aarch64::jit::pages::a64_step_stat) the class
/// (step_key) and word of the instruction interpret_one ran last
pub static mut LAST_STEPPED: (u32, u32) = (0, 0);
/// An instruction's class for the diagnostics: its Op and the low bits of its sub
#[inline(always)]
pub fn step_key(inst: &Inst) -> u32 { (inst.op as u32) << 4 | inst.sub as u32 & 15 }
static mut STEPPED_CORE: usize = 0;

/// (crate::aarch64::smp) another core runs now
pub fn core_switched() {
    unsafe {
        STEPPED_EXCLUSIVE_LOADS[STEPPED_CORE] = STEPPED_EXCLUSIVE_LOAD;
        STEPPED_CORE = crate::isa::current_core();
        STEPPED_EXCLUSIVE_LOAD = STEPPED_EXCLUSIVE_LOADS[STEPPED_CORE];
    }
}

/// Execute the instruction at the PC (P2.9): it retires, or takes its
/// exception having written no state. What the core does next. Software
/// step (P3.8): in the active-pending state the step exception comes
/// first; an instruction run in the active-not-pending state clears
/// PSTATE.SS when it completes (an exception return sets it from SPSR_EL1,
/// an exception the instruction generated saves it as 0, a fault as 1).
pub fn interpret_one() -> Flow {
    let address = get_pc();
    // (an illegal exception return left PSTATE.IL set: the next instruction takes EC 0x0E)
    if get_pstate() & PSTATE_IL != 0 {
        take_sync(Exception::IllegalState);
        return Flow::Set;
    }
    let stepping = crate::aarch64::debug::stepping();
    if stepping && get_pstate() & PSTATE_SS == 0 {
        take_sync(Exception::SoftwareStep(unsafe { STEPPED_EXCLUSIVE_LOAD }));
        return Flow::Set;
    }
    // (AArch32 at EL0: its own instructions; docs/aarch32-plan.md)
    if cpu::aarch32() {
        let flow = crate::aarch64::a32::interpret_one(address);
        if stepping && !matches!(flow, Flow::Set | Flow::Retry) {
            crate::aarch64::debug::step_done();
        }
        return flow;
    }
    let result = fetch_at(address).and_then(|word| {
        if unsafe { crate::aarch64::debug::ANY_BREAKPOINT } {
            if let Some(exception) = crate::aarch64::debug::check_breakpoint(address) {
                return Err(exception);
            }
        }
        let inst = decode_cached(word);
        if stepping {
            unsafe { STEPPED_EXCLUSIVE_LOAD = inst.op == Op::Exclusive && inst.sub & 1 != 0 };
        }
        unsafe { LAST_STEPPED = (step_key(&inst), word) };
        execute(&inst, address)
    });
    match result {
        Ok(flow) => {
            crate::core_stats::add_pending(1, 0);
            match flow {
                Flow::Next | Flow::Yield => set_pc(address.wrapping_add(4)),
                Flow::Jump(target) => set_pc(target),
                Flow::Wait(_) | Flow::Off => set_pc(address.wrapping_add(4)),
                Flow::Set | Flow::Retry => {},
            }
            // (Flow::Set is an exception return or an exception: PSTATE.SS is already what it must be)
            if stepping && !matches!(flow, Flow::Set | Flow::Retry) {
                crate::aarch64::debug::step_done();
            }
            flow
        },
        Err(exception @ (Exception::Svc(_) | Exception::Hvc(_) | Exception::Smc(_))) => {
            // (the instruction executed: the exception returns after it)
            crate::core_stats::add_pending(1, 0);
            if stepping {
                crate::aarch64::debug::step_done();
            }
            take_sync(exception);
            Flow::Set
        },
        Err(exception) => {
            if let Exception::Undefined = exception {
                note_undefined(address);
            }
            take_sync(exception);
            Flow::Set
        },
    }
}

/// (tests: the instruction count `interpret_one` retires)
#[no_mangle]
pub fn a64_step() -> u32 {
    match interpret_one() {
        Flow::Wait(kind) => kind,
        Flow::Off => 3,
        _ => 0,
    }
}
                                                                                                                                                                                                                                                            source/v64/src/rust/aarch64/extended.rs                                                             0000644 0000000 0000000 00000013302 00000000000 015045  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ARM core's extended RAM (docs/arm64-virt-android16-plan.md P8.5):
//! guest RAM beyond the one allocation of guest memory in the wasm32 heap,
//! at guest physical 4 GiB on (the device tree's second memory range),
//! through the engine both cores share (crate::extended: a host store and
//! a pool of frames).
//!
//! The bus maps the range as `Kind::Extended` (crate::aarch64::bus): the
//! interpreter's accesses, the table walks and instruction fetches come
//! here a page at a time. The page tier's access cache maps a page to its
//! frame (`cache_frame`, with the cores in one instance, as x86's), which is
//! then CACHED and not reused before the run loop's next safe point
//! (crate::extended::safe_point in crate::aarch64::smp::run_core) retires
//! every access cache entry. The page tier compiles code from it under the code
//! keys from bus::EXTENDED_CODE_KEY on, which its next write retires
//! (crate::extended's code watch); with the cores in workers that code is
//! interpreted. The exclusive monitors know its granules by keys above
//! every backing offset of guest memory (`monitor_key`).

use crate::extended::{self, PAGE};

/// The monitors' keys of extended RAM (smp::reserve takes a guest memory
/// offset, below 2 GiB): from 2 GiB on, the offset modulo 2 GiB - 64 KiB
/// (so that a page's keys do not wrap; an alias only clears a reservation,
/// which the guest retries)
pub const KEY_BASE: u32 = 0x8000_0000;
const KEY_SPAN: u64 = 0x7FFF_0000;

#[inline(always)]
pub fn monitor_key(address: u64) -> u32 {
    let base = extended::ext().base;
    KEY_BASE + (address.wrapping_sub(base) % KEY_SPAN) as u32
}

/// The host address of the frame of the extended page at `address` for the
/// page tier's access cache (crate::aarch64::jit::pages::a64_page_access),
/// or None: with the cores in workers (their access caches cannot be retired
/// at one safe point), when no frame is reusable before the next safe point,
/// or for a write to a page with compiled code (the interpreter's write
/// retires that code). A write entry's frame is dirty from here on: stores
/// through it do not come here.
pub unsafe fn cache_frame(address: u64, write: bool) -> Option<u32> {
    if crate::parallel::active() || !extended::contains(address) {
        return None;
    }
    let e = extended::ext();
    let page = ((address - e.base) / PAGE) as u32;
    if write && extended::has_code(e, page) {
        return None;
    }
    let frame = extended::resident(e, page, write)?;
    extended::mark_cached(e, frame);
    Some(e.pool.add(frame as usize * PAGE as usize) as u32)
}

/// The frames' host addresses, [start, end)
pub unsafe fn frame_range() -> (u32, u32) {
    let e = extended::ext();
    let start = e.pool as u32;
    (start, start.wrapping_add(e.frames * PAGE as u32))
}

/// Instructions from extended RAM: [0] interpreted (fetched), [1] retired by compiled code
pub static mut RETIRED: [u64; 2] = [0; 2];

/// The instruction at `address` (an interpreted fetch)
#[inline(never)]
pub unsafe fn fetch(address: u64) -> u32 {
    RETIRED[0] += 1;
    extended::read(address, 4) as u32
}

/// `width` (1, 2, 4 or 8) bytes at `address` (accesses across pages byte by byte)
pub unsafe fn read(address: u64, width: u32) -> u64 {
    if address % PAGE + width as u64 > PAGE {
        let mut value = 0;
        for i in 0..width as u64 {
            value |= extended::read(address + i, 1) << (8 * i);
        }
        return value;
    }
    extended::read(address, width as usize)
}

/// A core's write: other cores' reservations of the granules clear
pub unsafe fn write(address: u64, width: u32, value: u64) {
    if address % PAGE + width as u64 > PAGE {
        for i in 0..width as u64 {
            extended::write(address + i, 1, value >> (8 * i) & 0xFF);
        }
    }
    else {
        extended::write(address, width as usize, value);
    }
    crate::aarch64::smp::monitors_written(monitor_key(address), width, false);
}

/// Configure extended RAM (before the cores run): `pages` pages at guest
/// physical `base` (at or above 4 GiB, not over another region), cached in
/// `frames` frames; mapped into the address space
#[no_mangle]
pub unsafe fn a64_ext_configure(base_low: u32, base_high: u32, pages: u32, frames: u32) -> bool {
    let base = (base_high as u64) << 32 | base_low as u64;
    if pages == 0 || base < 1 << 32 {
        return false;
    }
    extended::configure(base, pages, frames)
        && crate::aarch64::bus::map_extended(base, pages as u64 * PAGE)
}

/// Write back every dirty frame (the store is then complete: snapshots)
#[no_mangle]
pub unsafe fn a64_ext_flush() { extended::flush() }

/// Forget every frame without writing it back (the store was replaced:
/// snapshot restore, power-on). Every core is stopped.
#[no_mangle]
pub unsafe fn a64_ext_discard() { extended::discard() }

/// The frame of extended page `page` for a host copy (a device's DMA, the
/// loader, debugging), resident until a64_ext_unpin: its address in wasm
/// memory. For a write, every core's reservation in the page clears.
#[no_mangle]
pub unsafe fn a64_ext_pin(page: u32, write: bool) -> u32 {
    let pointer = extended::pin(page, write);
    if write && pointer != 0 {
        let base = extended::ext().base;
        crate::aarch64::smp::monitors_written(
            monitor_key(base + page as u64 * PAGE),
            PAGE as u32,
            true,
        );
    }
    pointer
}
#[no_mangle]
pub unsafe fn a64_ext_unpin(page: u32) { extended::unpin(page) }

/// (crate::extended::stat); 16 instructions interpreted from extended RAM,
/// 17 retired there by compiled code
#[no_mangle]
pub unsafe fn a64_ext_stat(field: u32) -> f64 {
    match field {
        16 | 17 => RETIRED[field as usize - 16] as f64,
        _ => extended::stat(field),
    }
}
                                                                                                                                                                                                                                                                                                                              source/v64/src/rust/aarch64/fp.rs                                                                   0000644 0000000 0000000 00000077336 00000000000 013673  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Floating point of the AArch64 core (docs/arm64-virt-android16-plan.md
//! P2.6, P2.8): SoftFloat 3e with the ARM-VFPv2 specialization
//! (build/softfloat_arm.c, tools/softfloat_arm.mjs) and the rules the Arm
//! ARM's pseudocode adds around it: FPCR's RMode, FZ (a denormal input reads
//! as zero and sets IDC; a result whose exact value is below the normal
//! range becomes zero and sets UFC alone), DN (every NaN result is the
//! default NaN; a signaling input still sets IOC) and AHP; the sticky
//! FPSR flags; NaN selection for the fused multiply-adds (addend, op1, op2,
//! signaling before quiet, with the operands FNMADD and FNMSUB negate
//! negated first); FMAX/FMIN/FMAXNM/FMINNM; comparisons; conversions that
//! saturate with a NaN converting to 0; the estimates. FPCR's trap enables
//! read as zero, so no FP exception ever traps.

use crate::aarch64::cpu::{self, Exception};
use crate::aarch64::state::{cpacr_el1, fpcr, fpsr};

/// FPCR's bits that take effect: AHP, DN, FZ, RMode (the trap enables are
/// RAZ/WI, FZ16 is not in v1)
pub const FPCR_WRITABLE: u32 = 0x07C0_0000;
pub const FPCR_AHP: u32 = 1 << 26;
pub const FPCR_DN: u32 = 1 << 25;
pub const FPCR_FZ: u32 = 1 << 24;

// FPSR's cumulative bits
pub const FPSR_IOC: u32 = 1 << 0;
pub const FPSR_DZC: u32 = 1 << 1;
pub const FPSR_OFC: u32 = 1 << 2;
pub const FPSR_UFC: u32 = 1 << 3;
pub const FPSR_IXC: u32 = 1 << 4;
pub const FPSR_IDC: u32 = 1 << 7;
pub const FPSR_QC: u32 = 1 << 27;

pub fn fpcr_read() -> u64 { unsafe { *fpcr as u64 } }
pub fn fpcr_write(value: u64) { unsafe { *fpcr = value as u32 & FPCR_WRITABLE } }

/// CPACR_EL1.FPEN: whether FP and AdvSIMD instructions trap at this EL
#[inline]
pub fn check_access() -> Result<(), Exception> {
    // (cpu_type arm32: FPEXC.EN too)
    if cpu::a32_only() && !crate::aarch64::a32_system::fp_enabled() {
        return Err(Exception::Undefined);
    }
    let fpen = unsafe { *cpacr_el1 } >> 20 & 3;
    let allowed = match fpen {
        0b01 => cpu::el() == 1,
        0b11 => true,
        _ => false,
    };
    if allowed {
        Ok(())
    }
    else {
        Err(Exception::FpAccess)
    }
}

// SoftFloat (single-element structs pass as their scalar in Wasm's C ABI)
#[allow(improper_ctypes)]
extern "C" {
    static mut softfloat_roundingMode: u8;
    static mut softfloat_exceptionFlags: u8;
    fn f32_add(a: u32, b: u32) -> u32;
    fn f32_sub(a: u32, b: u32) -> u32;
    fn f32_mul(a: u32, b: u32) -> u32;
    fn f32_div(a: u32, b: u32) -> u32;
    fn f32_sqrt(a: u32) -> u32;
    fn f32_mulAdd(a: u32, b: u32, c: u32) -> u32;
    fn f32_roundToInt(a: u32, mode: u8, exact: bool) -> u32;
    fn f32_to_f64(a: u32) -> u64;
    fn f32_to_f16(a: u32) -> u16;
    fn f32_to_i32(a: u32, mode: u8, exact: bool) -> i32;
    fn f32_to_ui32(a: u32, mode: u8, exact: bool) -> u32;
    fn f32_to_i64(a: u32, mode: u8, exact: bool) -> i64;
    fn f32_to_ui64(a: u32, mode: u8, exact: bool) -> u64;
    fn f64_add(a: u64, b: u64) -> u64;
    fn f64_sub(a: u64, b: u64) -> u64;
    fn f64_mul(a: u64, b: u64) -> u64;
    fn f64_div(a: u64, b: u64) -> u64;
    fn f64_sqrt(a: u64) -> u64;
    fn f64_mulAdd(a: u64, b: u64, c: u64) -> u64;
    fn f64_roundToInt(a: u64, mode: u8, exact: bool) -> u64;
    fn f64_to_f32(a: u64) -> u32;
    fn f64_to_f16(a: u64) -> u16;
    fn f64_to_i32(a: u64, mode: u8, exact: bool) -> i32;
    fn f64_to_ui32(a: u64, mode: u8, exact: bool) -> u32;
    fn f64_to_i64(a: u64, mode: u8, exact: bool) -> i64;
    fn f64_to_ui64(a: u64, mode: u8, exact: bool) -> u64;
    fn f16_to_f32(a: u16) -> u32;
    fn f16_to_f64(a: u16) -> u64;
    fn i32_to_f32(a: i32) -> u32;
    fn i64_to_f32(a: i64) -> u32;
    fn ui32_to_f32(a: u32) -> u32;
    fn ui64_to_f32(a: u64) -> u32;
    fn i32_to_f64(a: i32) -> u64;
    fn i64_to_f64(a: i64) -> u64;
    fn ui32_to_f64(a: u32) -> u64;
    fn ui64_to_f64(a: u64) -> u64;
}

// SoftFloat's rounding modes and flags
pub const ROUND_NEAR_EVEN: u8 = 0;
pub const ROUND_MIN_MAG: u8 = 1;
pub const ROUND_MIN: u8 = 2;
pub const ROUND_MAX: u8 = 3;
pub const ROUND_NEAR_MAX_MAG: u8 = 4;
pub const ROUND_ODD: u8 = 6;
const FLAG_INEXACT: u8 = 1;
const FLAG_UNDERFLOW: u8 = 2;
const FLAG_OVERFLOW: u8 = 4;
const FLAG_INFINITE: u8 = 8;
const FLAG_INVALID: u8 = 16;

/// FPCR.RMode as SoftFloat's rounding mode (RN, RP, RM, RZ)
pub fn rounding_of(rmode: u32) -> u8 {
    [ROUND_NEAR_EVEN, ROUND_MAX, ROUND_MIN, ROUND_MIN_MAG][rmode as usize & 3]
}

/// One instruction's FP environment: FPCR, and the FPSR flags it raises
pub struct Fp {
    pub fpcr: u32,
    flags: u32,
}

/// A floating-point format's constants
pub trait Format: Copy {
    const BITS: u32;
    const EXPONENT: u64;
    const MANTISSA: u64;
    const SIGN: u64;
    const QUIET: u64;
    const DEFAULT_NAN: u64;
    fn to(v: u64) -> u64 { v & (u64::MAX >> (64 - Self::BITS)) }
}
#[derive(Clone, Copy)]
pub struct F32;
#[derive(Clone, Copy)]
pub struct F64;
impl Format for F32 {
    const BITS: u32 = 32;
    const EXPONENT: u64 = 0x7F80_0000;
    const MANTISSA: u64 = 0x007F_FFFF;
    const SIGN: u64 = 0x8000_0000;
    const QUIET: u64 = 0x0040_0000;
    const DEFAULT_NAN: u64 = 0x7FC0_0000;
}
impl Format for F64 {
    const BITS: u32 = 64;
    const EXPONENT: u64 = 0x7FF0_0000_0000_0000;
    const MANTISSA: u64 = 0x000F_FFFF_FFFF_FFFF;
    const SIGN: u64 = 0x8000_0000_0000_0000;
    const QUIET: u64 = 0x0008_0000_0000_0000;
    const DEFAULT_NAN: u64 = 0x7FF8_0000_0000_0000;
}

#[inline(always)]
pub fn is_nan<T: Format>(v: u64) -> bool { v & T::EXPONENT == T::EXPONENT && v & T::MANTISSA != 0 }
#[inline(always)]
pub fn is_snan<T: Format>(v: u64) -> bool { is_nan::<T>(v) && v & T::QUIET == 0 }
#[inline(always)]
pub fn is_inf<T: Format>(v: u64) -> bool { v & !T::SIGN == T::EXPONENT }
#[inline(always)]
pub fn is_zero<T: Format>(v: u64) -> bool { v & !T::SIGN == 0 }
#[inline(always)]
pub fn is_denormal<T: Format>(v: u64) -> bool { v & T::EXPONENT == 0 && v & T::MANTISSA != 0 }

impl Fp {
    /// The current FPCR, SoftFloat set to its rounding mode
    pub fn new() -> Fp { Fp::with(unsafe { *fpcr }) }
    /// An environment of the given FPCR (AArch32's Advanced SIMD runs on
    /// the standard FPSCR value: AHP as FPSCR's, DN, FZ, round to nearest)
    pub fn with(fpcr_value: u32) -> Fp {
        unsafe {
            softfloat_roundingMode = rounding_of(fpcr_value >> 22);
            softfloat_exceptionFlags = 0;
        }
        Fp {
            fpcr: fpcr_value,
            flags: 0,
        }
    }
    #[inline(always)]
    pub fn fz(&self) -> bool { self.fpcr & FPCR_FZ != 0 }
    #[inline(always)]
    pub fn dn(&self) -> bool { self.fpcr & FPCR_DN != 0 }
    #[inline(always)]
    pub fn ahp(&self) -> bool { self.fpcr & FPCR_AHP != 0 }
    #[inline(always)]
    pub fn raise(&mut self, flags: u32) { self.flags |= flags }
    /// FPSR |= the flags raised
    pub fn finish(self) { unsafe { *fpsr |= self.flags } }

    /// SoftFloat's flags since the last take, as FPSR bits
    fn take_softfloat(&mut self) -> u32 {
        let flags = unsafe { softfloat_exceptionFlags };
        unsafe { softfloat_exceptionFlags = 0 };
        let mut fpsr_bits = 0;
        if flags & FLAG_INVALID != 0 {
            fpsr_bits |= FPSR_IOC;
        }
        if flags & FLAG_INFINITE != 0 {
            fpsr_bits |= FPSR_DZC;
        }
        if flags & FLAG_OVERFLOW != 0 {
            fpsr_bits |= FPSR_OFC;
        }
        if flags & FLAG_UNDERFLOW != 0 {
            fpsr_bits |= FPSR_UFC;
        }
        if flags & FLAG_INEXACT != 0 {
            fpsr_bits |= FPSR_IXC;
        }
        fpsr_bits
    }

    /// FPUnpack's flush: a denormal input reads as zero under FZ (IDC)
    #[inline(always)]
    pub fn input<T: Format>(&mut self, v: u64) -> u64 {
        if self.fz() && is_denormal::<T>(v) {
            self.flags |= FPSR_IDC;
            v & T::SIGN
        }
        else {
            v
        }
    }

    /// A SoftFloat result: DN, the FZ flush of a result below the normal
    /// range (UFC only), the flags
    #[inline(always)]
    pub fn output<T: Format>(&mut self, v: u64) -> u64 {
        let flags = self.take_softfloat();
        if is_nan::<T>(v) {
            self.flags |= flags;
            return if self.dn() { T::DEFAULT_NAN } else { v };
        }
        if self.fz() && (is_denormal::<T>(v) || flags & FPSR_UFC != 0) {
            self.flags |= flags & !(FPSR_UFC | FPSR_IXC) | FPSR_UFC;
            return v & T::SIGN;
        }
        self.flags |= flags;
        v
    }

    /// FPProcessNaNs for two operands (signaling before quiet, op1 before op2)
    pub fn process_nans<T: Format>(&mut self, a: u64, b: u64) -> Option<u64> {
        let pick = if is_snan::<T>(a) {
            a
        }
        else if is_snan::<T>(b) {
            b
        }
        else if is_nan::<T>(a) {
            a
        }
        else if is_nan::<T>(b) {
            b
        }
        else {
            return None;
        };
        Some(self.nan_result::<T>(pick))
    }
    /// A NaN operand's result: quieted (IOC if it signaled), or the default NaN with DN
    pub fn nan_result<T: Format>(&mut self, v: u64) -> u64 {
        if is_snan::<T>(v) {
            self.flags |= FPSR_IOC;
        }
        if self.dn() {
            T::DEFAULT_NAN
        }
        else {
            v | T::QUIET
        }
    }
}

// ---- the operations, generic over F32 and F64

macro_rules! dispatch {
    ($t:ty, $f32:ident, $f64:ident, $($arg:expr),*) => {
        if <$t>::BITS == 32 { unsafe { $f32($($arg as u32),*) as u64 } } else { unsafe { $f64($($arg),*) } }
    };
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Arith {
    Add,
    Sub,
    Mul,
    Div,
}

impl Fp {
    pub fn arith<T: Format>(&mut self, op: Arith, a: u64, b: u64) -> u64 {
        let (a, b) = (self.input::<T>(a), self.input::<T>(b));
        let r = match op {
            Arith::Add => dispatch!(T, f32_add, f64_add, a, b),
            Arith::Sub => dispatch!(T, f32_sub, f64_sub, a, b),
            Arith::Mul => dispatch!(T, f32_mul, f64_mul, a, b),
            Arith::Div => dispatch!(T, f32_div, f64_div, a, b),
        };
        self.output::<T>(r)
    }

    pub fn sqrt<T: Format>(&mut self, a: u64) -> u64 {
        let a = self.input::<T>(a);
        let r = if T::BITS == 32 {
            unsafe { f32_sqrt(a as u32) as u64 }
        }
        else {
            unsafe { f64_sqrt(a) }
        };
        self.output::<T>(r)
    }

    /// FPMulAdd: addend + op1 * op2, rounded once
    pub fn mul_add<T: Format>(&mut self, addend: u64, op1: u64, op2: u64) -> u64 {
        let (a, n, m) = (
            self.input::<T>(addend),
            self.input::<T>(op1),
            self.input::<T>(op2),
        );
        let inf_zero = (is_inf::<T>(n) && is_zero::<T>(m)) || (is_zero::<T>(n) && is_inf::<T>(m));
        // (FPProcessNaNs3 in the order addend, op1, op2)
        for v in [a, n, m] {
            if is_snan::<T>(v) {
                return self.nan_result::<T>(v);
            }
        }
        if is_nan::<T>(a) && inf_zero {
            self.flags |= FPSR_IOC;
            return T::DEFAULT_NAN;
        }
        for v in [a, n, m] {
            if is_nan::<T>(v) {
                return self.nan_result::<T>(v);
            }
        }
        let r = if T::BITS == 32 {
            unsafe { f32_mulAdd(n as u32, m as u32, a as u32) as u64 }
        }
        else {
            unsafe { f64_mulAdd(n, m, a) }
        };
        self.output::<T>(r)
    }

    /// FMAX (max) or FMIN, and with `numbers` FMAXNM/FMINNM (a quiet NaN
    /// against a number gives the number)
    pub fn max_min<T: Format>(&mut self, a: u64, b: u64, max: bool, numbers: bool) -> u64 {
        let (a, b) = (self.input::<T>(a), self.input::<T>(b));
        if numbers {
            let (qa, qb) = (
                is_nan::<T>(a) && !is_snan::<T>(a),
                is_nan::<T>(b) && !is_snan::<T>(b),
            );
            if qa && !is_nan::<T>(b) {
                return b;
            }
            if qb && !is_nan::<T>(a) {
                return a;
            }
        }
        if let Some(nan) = self.process_nans::<T>(a, b) {
            return nan;
        }
        if is_zero::<T>(a) && is_zero::<T>(b) {
            // (+0 is the larger zero)
            return if max { a & b } else { a | b };
        }
        let a_greater = compare_values::<T>(a, b) == core::cmp::Ordering::Greater;
        if a_greater == max {
            a
        }
        else {
            b
        }
    }

    /// FMULX: FMUL, except that infinity times zero is 2.0 (signed)
    pub fn mulx<T: Format>(&mut self, a: u64, b: u64) -> u64 {
        let (a, b) = (self.input::<T>(a), self.input::<T>(b));
        if let Some(nan) = self.process_nans::<T>(a, b) {
            return nan;
        }
        if (is_inf::<T>(a) && is_zero::<T>(b)) || (is_zero::<T>(a) && is_inf::<T>(b)) {
            let two = if T::BITS == 32 { 0x4000_0000 } else { 0x4000_0000_0000_0000 };
            return (a ^ b) & T::SIGN | two;
        }
        self.arith::<T>(Arith::Mul, a, b)
    }

    /// FPCompare: N Z C V (unordered 0011); IOC for a signaling NaN, or any NaN with `signal`
    pub fn compare<T: Format>(&mut self, a: u64, b: u64, signal: bool) -> u32 {
        let (a, b) = (self.input::<T>(a), self.input::<T>(b));
        if is_nan::<T>(a) || is_nan::<T>(b) {
            if signal || is_snan::<T>(a) || is_snan::<T>(b) {
                self.flags |= FPSR_IOC;
            }
            return 0b0011 << 28;
        }
        match compare_values::<T>(a, b) {
            core::cmp::Ordering::Equal => 0b0110 << 28,
            core::cmp::Ordering::Less => 0b1000 << 28,
            core::cmp::Ordering::Greater => 0b0010 << 28,
        }
    }
    /// FPCompareEQ (quiet), FPCompareGE and FPCompareGT (signaling)
    pub fn compare_eq<T: Format>(&mut self, a: u64, b: u64) -> bool {
        self.compare::<T>(a, b, false) == 0b0110 << 28
    }
    pub fn compare_ge<T: Format>(&mut self, a: u64, b: u64) -> bool {
        let r = self.compare::<T>(a, b, true);
        r == 0b0110 << 28 || r == 0b0010 << 28
    }
    pub fn compare_gt<T: Format>(&mut self, a: u64, b: u64) -> bool {
        self.compare::<T>(a, b, true) == 0b0010 << 28
    }

    /// FRINT*: to an integral value with `mode` (SoftFloat's), `exact` raises IXC
    pub fn round_to_int<T: Format>(&mut self, a: u64, mode: u8, exact: bool) -> u64 {
        let a = self.input::<T>(a);
        if is_nan::<T>(a) {
            return self.nan_result::<T>(a);
        }
        let r = if T::BITS == 32 {
            unsafe { f32_roundToInt(a as u32, mode, exact) as u64 }
        }
        else {
            unsafe { f64_roundToInt(a, mode, exact) }
        };
        self.output::<T>(r)
    }

    /// FPToFixed: to a signed or unsigned integer of `int_bits` (32, 64) bits
    /// with `fbits` fraction bits, rounding with `mode`; saturating, NaN to 0
    pub fn to_integer<T: Format>(
        &mut self,
        a: u64,
        signed: bool,
        int_bits: u32,
        fbits: u32,
        mode: u8,
    ) -> u64 {
        let mut a = self.input::<T>(a);
        if fbits != 0 && !is_nan::<T>(a) && !is_inf::<T>(a) && !is_zero::<T>(a) {
            // (an exact scaling: in double precision; the flags of the multiply are not the result's)
            let wide = if T::BITS == 32 { unsafe { f32_to_f64(a as u32) } } else { a };
            let scale = (1023 + fbits as u64) << 52;
            let scaled = unsafe { f64_mul(wide, scale) };
            unsafe { softfloat_exceptionFlags = 0 };
            let r = convert_f64(scaled, signed, int_bits, mode);
            self.flags |= self.take_softfloat();
            return r;
        }
        a = T::to(a);
        let r = if T::BITS == 32 {
            let v = a as u32;
            unsafe {
                match (signed, int_bits) {
                    (true, 32) => f32_to_i32(v, mode, true) as u32 as u64,
                    (false, 32) => f32_to_ui32(v, mode, true) as u64,
                    (true, _) => f32_to_i64(v, mode, true) as u64,
                    (false, _) => f32_to_ui64(v, mode, true),
                }
            }
        }
        else {
            convert_f64(a, signed, int_bits, mode)
        };
        self.flags |= self.take_softfloat();
        r
    }

    /// FPToFixed to a 16-bit integer (AArch32's VCVT to fixed point): the
    /// 32-bit conversion saturated again, Invalid Operation alone when it
    /// saturates; the result in the low 16 bits
    pub fn to_integer16<T: Format>(&mut self, a: u64, signed: bool, fbits: u32, mode: u8) -> u64 {
        let before = self.flags;
        let r = self.to_integer::<T>(a, signed, 32, fbits, mode) as u32;
        let (value, low, high) =
            if signed { (r as i32 as i64, -0x8000, 0x7FFF) } else { (r as i64, 0, 0xFFFF) };
        if value < low || value > high {
            self.flags = before | FPSR_IOC;
            return (if value < low { low } else { high }) as u64 & 0xFFFF;
        }
        value as u64 & 0xFFFF
    }

    /// FixedToFP: a signed or unsigned integer (`int_bits` wide) with `fbits` fraction bits
    pub fn from_integer<T: Format>(
        &mut self,
        value: u64,
        signed: bool,
        int_bits: u32,
        fbits: u32,
    ) -> u64 {
        let r = unsafe {
            match (T::BITS, signed, int_bits) {
                (32, true, 32) => i32_to_f32(value as i32) as u64,
                (32, true, _) => i64_to_f32(value as i64) as u64,
                (32, false, 32) => ui32_to_f32(value as u32) as u64,
                (32, false, _) => ui64_to_f32(value) as u64,
                (_, true, 32) => i32_to_f64(value as i32),
                (_, true, _) => i64_to_f64(value as i64),
                (_, false, 32) => ui32_to_f64(value as u32),
                (_, false, _) => ui64_to_f64(value),
            }
        };
        let r = if fbits != 0 && !is_zero::<T>(r) {
            // (exact: dividing by 2^fbits stays in the normal range here)
            let exponent = (r & T::EXPONENT) >> (T::BITS - 1 - if T::BITS == 32 { 8 } else { 11 });
            let shift = T::BITS - 1 - if T::BITS == 32 { 8 } else { 11 };
            (r & !T::EXPONENT) | (exponent - fbits as u64) << shift
        }
        else {
            r
        };
        self.output::<T>(r)
    }
}

fn convert_f64(v: u64, signed: bool, int_bits: u32, mode: u8) -> u64 {
    unsafe {
        match (signed, int_bits) {
            (true, 32) => f64_to_i32(v, mode, true) as u32 as u64,
            (false, 32) => f64_to_ui32(v, mode, true) as u64,
            (true, _) => f64_to_i64(v, mode, true) as u64,
            (false, _) => f64_to_ui64(v, mode, true),
        }
    }
}

/// The order of two non-NaN values
fn compare_values<T: Format>(a: u64, b: u64) -> core::cmp::Ordering {
    use core::cmp::Ordering::*;
    if is_zero::<T>(a) && is_zero::<T>(b) {
        return Equal;
    }
    let (sa, sb) = (a & T::SIGN != 0, b & T::SIGN != 0);
    let (ma, mb) = (a & !T::SIGN, b & !T::SIGN);
    match (sa, sb) {
        (false, true) => Greater,
        (true, false) => Less,
        (false, false) => ma.cmp(&mb),
        (true, true) => mb.cmp(&ma),
    }
}

/// VFPExpandImm: the 8-bit immediate of FMOV as a single (`n` 32) or double
pub fn expand_imm(imm8: u32, n: u32) -> u64 {
    let sign = (imm8 >> 7 & 1) as u64;
    let b6 = (imm8 >> 6 & 1) as u64;
    let low = (imm8 & 0x3F) as u64;
    if n == 32 {
        // sign : NOT(b6) : b6 x5 : imm8<5:0> : zeros(19)
        sign << 31 | (b6 ^ 1) << 30 | (if b6 != 0 { 0x1F } else { 0 }) << 25 | low << 19
    }
    else {
        sign << 63 | (b6 ^ 1) << 62 | (if b6 != 0 { 0xFF } else { 0 }) << 54 | low << 48
    }
}

// ---- conversions between precisions

impl Fp {
    /// FCVT single to double
    pub fn single_to_double(&mut self, a: u32) -> u64 {
        let a = self.input::<F32>(a as u64) as u32;
        if is_nan::<F32>(a as u64) {
            if is_snan::<F32>(a as u64) {
                self.flags |= FPSR_IOC;
            }
            if self.dn() {
                return F64::DEFAULT_NAN;
            }
            let sign = (a as u64 & F32::SIGN) << 32;
            return sign | F64::EXPONENT | F64::QUIET | ((a as u64 & F32::MANTISSA) << 29);
        }
        let r = unsafe { f32_to_f64(a) };
        self.output::<F64>(r)
    }
    /// FCVT double to single (FCVTXN: `odd`, rounding to odd)
    pub fn double_to_single(&mut self, a: u64, odd: bool) -> u32 {
        let a = self.input::<F64>(a);
        if is_nan::<F64>(a) {
            if is_snan::<F64>(a) {
                self.flags |= FPSR_IOC;
            }
            if self.dn() {
                return F32::DEFAULT_NAN as u32;
            }
            let sign = (a >> 32) as u32 & 0x8000_0000;
            return sign | 0x7FC0_0000 | (a >> 29) as u32 & 0x003F_FFFF;
        }
        let saved = unsafe { softfloat_roundingMode };
        if odd {
            unsafe { softfloat_roundingMode = ROUND_ODD };
        }
        let r = unsafe { f64_to_f32(a) };
        unsafe { softfloat_roundingMode = saved };
        self.output::<F32>(r as u64) as u32
    }

    /// FCVT to half precision from single (`bits` 32) or double; AHP gives
    /// the alternative format (no infinity or NaN). FZ16 is not in v1, so a
    /// half-precision result is never flushed.
    pub fn to_half(&mut self, a: u64, bits: u32) -> u16 {
        let a = if bits == 32 { self.input::<F32>(a) } else { self.input::<F64>(a) };
        let (nan, snan, inf) = if bits == 32 {
            (is_nan::<F32>(a), is_snan::<F32>(a), is_inf::<F32>(a))
        }
        else {
            (is_nan::<F64>(a), is_snan::<F64>(a), is_inf::<F64>(a))
        };
        let sign = if bits == 32 { (a >> 16) as u16 & 0x8000 } else { (a >> 48) as u16 & 0x8000 };
        if self.ahp() {
            if nan {
                self.flags |= FPSR_IOC;
                return sign;
            }
            if inf {
                self.flags |= FPSR_IOC;
                return sign | 0x7FFF;
            }
        }
        else if nan {
            if snan {
                self.flags |= FPSR_IOC;
            }
            if self.dn() {
                return 0x7E00;
            }
            let payload =
                if bits == 32 { (a >> 13) as u16 & 0x01FF } else { (a >> 42) as u16 & 0x01FF };
            return sign | 0x7E00 | payload;
        }
        let convert = |v: u64| unsafe {
            if bits == 32 {
                f32_to_f16(v as u32)
            }
            else {
                f64_to_f16(v)
            }
        };
        let r = convert(a);
        let flags = self.take_softfloat();
        if self.ahp() && flags & FPSR_OFC != 0 {
            // (above IEEE half precision's range: the alternative format has
            // one more exponent; half the value, exact here, converts with
            // the same rounding)
            let one = if bits == 32 { 1 << 23 } else { 1 << 52 };
            let r = convert(a - one);
            let flags = self.take_softfloat();
            if flags & FPSR_OFC != 0 {
                // (overflow: the largest value, Invalid Operation only)
                self.flags |= FPSR_IOC;
                return sign | 0x7FFF;
            }
            self.flags |= flags;
            return r + 0x400;
        }
        self.flags |= flags;
        r
    }

    /// FCVT from half precision to single (`bits` 32) or double
    pub fn from_half(&mut self, h: u16, bits: u32) -> u64 {
        let sign = (h & 0x8000) as u64;
        let exponent = (h >> 10) & 0x1F;
        let mantissa = (h & 0x3FF) as u64;
        if exponent == 0x1F && !self.ahp() {
            if mantissa != 0 {
                let snan = mantissa & 0x200 == 0;
                if snan {
                    self.flags |= FPSR_IOC;
                }
                if self.dn() {
                    return if bits == 32 { F32::DEFAULT_NAN } else { F64::DEFAULT_NAN };
                }
                return if bits == 32 {
                    sign << 16 | F32::EXPONENT | F32::QUIET | mantissa << 13
                }
                else {
                    sign << 48 | F64::EXPONENT | F64::QUIET | mantissa << 42
                };
            }
            return if bits == 32 {
                sign << 16 | F32::EXPONENT
            }
            else {
                sign << 48 | F64::EXPONENT
            };
        }
        if exponent == 0x1F {
            // (AHP: an ordinary value, 2^16 * 1.mantissa)
            return if bits == 32 {
                sign << 16 | (127 + 16) << 23 | mantissa << 13
            }
            else {
                sign << 48 | (1023 + 16) << 52 | mantissa << 42
            };
        }
        // (exact; a half denormal is normal in single and double, and FZ16 is not in v1)
        unsafe {
            if bits == 32 {
                f16_to_f32(h) as u64
            }
            else {
                f16_to_f64(h)
            }
        }
    }
}

// ---- the estimates (FRECPE, FRSQRTE, FRECPX) and the steps (FRECPS, FRSQRTS)

/// RecipEstimate (8-bit) of a scaled mantissa a in [256, 511]
pub fn recip_estimate(a: u32) -> u32 {
    let a = a * 2 + 1;
    let b = (1 << 19) / a;
    (b + 1) / 2
}

/// RecipSqrtEstimate of a scaled mantissa a in [128, 511]
pub fn recip_sqrt_estimate(a: u32) -> u32 {
    let a = if a < 256 { a * 2 + 1 } else { (a >> 1 << 1) * 2 + 2 };
    let mut b = 512u32;
    while a * (b + 1) * (b + 1) < 1 << 28 {
        b += 1;
    }
    (b + 1) / 2
}

impl Fp {
    /// FRECPE
    pub fn recip_estimate<T: Format>(&mut self, a: u64) -> u64 {
        let a = self.input::<T>(a);
        let (exp_bits, mant_bits) = if T::BITS == 32 { (8u32, 23u32) } else { (11, 52) };
        let bias = (1i64 << (exp_bits - 1)) - 1;
        let sign = a & T::SIGN;
        if is_nan::<T>(a) {
            return self.nan_result::<T>(a);
        }
        if is_inf::<T>(a) {
            return sign;
        }
        if is_zero::<T>(a) {
            self.flags |= FPSR_DZC;
            return sign | T::EXPONENT;
        }
        let exponent = ((a & T::EXPONENT) >> mant_bits) as i64;
        let fraction = a & T::MANTISSA;
        // (too small: overflow to infinity or the largest value, by rounding mode)
        let too_small = if T::BITS == 32 {
            a & !T::SIGN < 0x0020_0000
        }
        else {
            a & !T::SIGN < 0x0004_0000_0000_0000
        };
        if too_small {
            self.flags |= FPSR_OFC | FPSR_IXC;
            let rmode = self.fpcr >> 22 & 3;
            let to_infinity = match rmode {
                0 => true,
                1 => sign == 0,
                2 => sign != 0,
                _ => false,
            };
            return if to_infinity {
                sign | T::EXPONENT
            }
            else {
                sign | (T::EXPONENT - (1 << mant_bits)) | T::MANTISSA
            };
        }
        // (too large: the result is below the normal range; FZ flushes it)
        if self.fz() && exponent >= 2 * bias - 1 {
            self.flags |= FPSR_UFC;
            return sign;
        }
        // (the scaled mantissa: 9 bits with the leading one)
        let (mut exp, mut frac) = (exponent, fraction);
        if exp == 0 {
            if frac >> (mant_bits - 1) == 0 {
                exp = -1;
                frac = frac << 2 & T::MANTISSA;
            }
            else {
                frac = frac << 1 & T::MANTISSA;
            }
        }
        let scaled = (1 << 8) | (frac >> (mant_bits - 8)) as u32;
        let estimate = recip_estimate(scaled) as u64;
        let result_exp = 2 * bias - 1 - exp;
        let mut result_frac = (estimate & 0xFF) << (mant_bits - 8);
        let mut result_exp = result_exp;
        if result_exp == 0 {
            result_frac = (1 << (mant_bits - 1)) | result_frac >> 1;
        }
        else if result_exp == -1 {
            result_frac = (1 << (mant_bits - 2)) | result_frac >> 2;
            result_exp = 0;
        }
        sign | (result_exp as u64) << mant_bits | result_frac
    }

    /// FRSQRTE
    pub fn recip_sqrt_estimate<T: Format>(&mut self, a: u64) -> u64 {
        let a = self.input::<T>(a);
        let (exp_bits, mant_bits) = if T::BITS == 32 { (8u32, 23u32) } else { (11, 52) };
        let bias = (1i64 << (exp_bits - 1)) - 1;
        let sign = a & T::SIGN;
        if is_nan::<T>(a) {
            return self.nan_result::<T>(a);
        }
        if is_zero::<T>(a) {
            self.flags |= FPSR_DZC;
            return sign | T::EXPONENT;
        }
        if sign != 0 {
            self.flags |= FPSR_IOC;
            return T::DEFAULT_NAN;
        }
        if is_inf::<T>(a) {
            return 0;
        }
        let (mut exp, mut frac) = (((a & T::EXPONENT) >> mant_bits) as i64, a & T::MANTISSA);
        if exp == 0 {
            while frac >> (mant_bits - 1) & 1 == 0 {
                frac <<= 1;
                exp -= 1;
            }
            frac = frac << 1 & T::MANTISSA;
        }
        let scaled = if exp & 1 == 0 {
            (1 << 8) | (frac >> (mant_bits - 8)) as u32
        }
        else {
            (1 << 7) | (frac >> (mant_bits - 7)) as u32
        };
        let estimate = recip_sqrt_estimate(scaled) as u64;
        let result_exp = (3 * bias - 1 - exp) / 2;
        sign | (result_exp as u64) << mant_bits | (estimate & 0xFF) << (mant_bits - 8)
    }

    /// FRECPX: the exponent inverted, the mantissa zero
    pub fn recip_exponent<T: Format>(&mut self, a: u64) -> u64 {
        let a = self.input::<T>(a);
        if is_nan::<T>(a) {
            return self.nan_result::<T>(a);
        }
        let sign = a & T::SIGN;
        let exponent = a & T::EXPONENT;
        if exponent == 0 {
            // (zero and denormals: the largest exponent below infinity)
            return sign | (T::EXPONENT - (T::EXPONENT & T::EXPONENT.wrapping_neg()));
        }
        sign | (!exponent & T::EXPONENT)
    }

    /// FRECPS: 2 - op1 * op2 (inf * 0 gives 2), fused
    pub fn recip_step<T: Format>(&mut self, a: u64, b: u64) -> u64 { self.step::<T>(a, b, false) }
    /// FRSQRTS: (3 - op1 * op2) / 2 (inf * 0 gives 1.5), fused
    pub fn recip_sqrt_step<T: Format>(&mut self, a: u64, b: u64) -> u64 {
        self.step::<T>(a, b, true)
    }

    fn step<T: Format>(&mut self, a: u64, b: u64, sqrt: bool) -> u64 {
        // (op1 is negated first, NaN included)
        let (a, b) = (self.input::<T>(a) ^ T::SIGN, self.input::<T>(b));
        if let Some(nan) = self.process_nans::<T>(a, b) {
            return nan;
        }
        let (one_half, two, three_halves, three) = if T::BITS == 32 {
            (
                0x3F00_0000u64,
                0x4000_0000u64,
                0x3FC0_0000u64,
                0x4040_0000u64,
            )
        }
        else {
            (
                0x3FE0_0000_0000_0000,
                0x4000_0000_0000_0000,
                0x3FF8_0000_0000_0000,
                0x4008_0000_0000_0000,
            )
        };
        if (is_inf::<T>(a) && is_zero::<T>(b)) || (is_zero::<T>(a) && is_inf::<T>(b)) {
            return if sqrt { three_halves } else { two };
        }
        if is_inf::<T>(a) || is_inf::<T>(b) {
            return (a ^ b) & T::SIGN | T::EXPONENT;
        }
        let fma = |n: u64, m: u64, c: u64| {
            if T::BITS == 32 {
                unsafe { f32_mulAdd(n as u32, m as u32, c as u32) as u64 }
            }
            else {
                unsafe { f64_mulAdd(n, m, c) }
            }
        };
        if !sqrt {
            let r = fma(a, b, two);
            return self.output::<T>(r);
        }
        // (3 + op1 * op2) / 2, rounded once: halve the larger operand when
        // that is exact (an exponent above 1), else op1 * op2 is so small
        // that the sum is near 3 and halving it is exact
        let one = T::EXPONENT & T::EXPONENT.wrapping_neg();
        let (larger, other) = if a & !T::SIGN >= b & !T::SIGN { (a, b) } else { (b, a) };
        let r = if larger & T::EXPONENT > one {
            fma(larger - one, other, three_halves)
        }
        else {
            let r = fma(a, b, three);
            if T::BITS == 32 {
                unsafe { f32_mul(r as u32, one_half as u32) as u64 }
            }
            else {
                unsafe { f64_mul(r, one_half) }
            }
        };
        self.output::<T>(r)
    }
}
                                                                                                                                                                                                                                                                                                  source/v64/src/rust/aarch64/gic.rs                                                                  0000644 0000000 0000000 00000124256 00000000000 014022  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The GICv3 of the virt machine (docs/arm64-virt-android16-plan.md P4.2):
//! the distributor (GICD), one redistributor (GICR, RD and SGI frames) and
//! one CPU interface (the ICC_* system registers) per core, decoded here in
//! Rust. The configuration is the reference's (QEMU 9.2 virt, gic-version=3,
//! its=off, no EL3): one security state (GICD_CTLR.DS = 1), affinity
//! routing always on, 288 INTIDs (256 SPIs), no LPIs, 5 priority bits;
//! group 0 is signaled as FIQ and group 1 as IRQ. Where the architecture
//! leaves a choice this follows QEMU's hw/intc/arm_gicv3*.c: equal
//! priorities go to the lowest INTID, the distributor keeps all 8 priority
//! bits, IROUTER's IRM is ignored (No1N), an SPI routed to no core stays
//! pending.
//!
//! With cores in workers (P8.2) the GIC is the machine instance's: every
//! entry point holds its lock (re-entrant), the signals are its bytes, and a
//! changed signal of another core kicks that core.
//!
//! The same state behind a GICv2's registers (a64_gic_set_version(2): the
//! ranchu board's Linux 3.10, docs/aarch32-plan.md R4.2, R6): the
//! distributor without affinity routing (the SGIs' and PPIs' registers
//! banked per core, ITARGETSR, GICD_SGIR and the SGIs' source cores) and a
//! memory-mapped CPU interface (GICC) at GICC_BASE whose priority logic is
//! the ICC registers'; group 0 is an IRQ there unless GICC_CTLR.FIQEn. No
//! Security Extensions, 5 priority bits, as QEMU's GICv2 without EL3.

use crate::aarch64::cpu::{self, Exception};
use crate::isa::MAX_CORES;

pub const NUM_IRQ: usize = 288;
const WORDS: usize = NUM_IRQ / 32;
const SPURIOUS: u64 = 1023;

/// The distributor's and redistributors' frames
pub const GICD_BASE: u64 = 0x0800_0000;
pub const GICD_SIZE: u64 = 0x1_0000;
pub const GICR_BASE: u64 = 0x080A_0000;
pub const GICR_STRIDE: u64 = 0x2_0000;
/// The GICv2 CPU interface's frame (GICC_DIR at 0x1000)
pub const GICC_BASE: u64 = 0x0801_0000;
pub const GICC_SIZE: u64 = 0x1_0000;

const CTLR_EN_GRP0: u32 = 1 << 0;
const CTLR_EN_GRP1: u32 = 1 << 1;
const CTLR_ARE: u32 = 1 << 4;
const CTLR_DS: u32 = 1 << 6;

// the CPU interface
const PRIBITS: u32 = 5;
const PRIO_MASK: u32 = (0xFF << (8 - PRIBITS)) & 0xFF;
/// The minimum BPR of group 0 (7 - PREbits) and group 1 (one more)
const MIN_BPR0: u32 = 7 - PRIBITS;
const MIN_BPR1: u32 = MIN_BPR0 + 1;
const ICC_CTLR_CBPR: u32 = 1 << 0;
const ICC_CTLR_EOIMODE: u32 = 1 << 1;
const ICC_CTLR_RESET: u32 = 1 << 15 /* A3V */ | 1 << 11 /* IDbits: 24 */ | (PRIBITS - 1) << 8;

#[derive(Clone, Copy)]
struct Distributor {
    ctlr: u32,
    group: [u32; WORDS],
    enabled: [u32; WORDS],
    pending: [u32; WORDS],
    active: [u32; WORDS],
    level: [u32; WORDS],
    edge: [u32; WORDS],
    priority: [u8; NUM_IRQ],
    irouter: [u64; NUM_IRQ],
}

#[derive(Clone, Copy)]
struct Redistributor {
    waker: u32,
    group: u32,
    enabled: u32,
    pending: u32,
    active: u32,
    level: u32,
    edge: u32,
    priority: [u8; 32],
}

/// A core's CPU interface: index 0 group 0, 1 group 1
#[derive(Clone, Copy)]
struct CpuInterface {
    pmr: u32,
    bpr: [u32; 2],
    igrpen: [u32; 2],
    ctlr: u32,
    apr: [u32; 2],
}

/// The highest priority pending interrupt of a core: (INTID, priority, group); priority 0x100 none
#[derive(Clone, Copy)]
struct Hppi {
    irq: u32,
    prio: u32,
    group: usize,
}

const HPPI_NONE: Hppi = Hppi {
    irq: SPURIOUS as u32,
    prio: 0x100,
    group: 0,
};

struct Gic {
    dist: Distributor,
    redist: [Redistributor; MAX_CORES],
    cpuif: [CpuInterface; MAX_CORES],
    hppi: [Hppi; MAX_CORES],
}

const REDIST_RESET: Redistributor = Redistributor {
    waker: 0b110,
    group: 0,
    enabled: 0,
    pending: 0,
    active: 0,
    level: 0,
    edge: 0xFFFF,
    priority: [0; 32],
};
const CPUIF_RESET: CpuInterface = CpuInterface {
    pmr: 0,
    bpr: [MIN_BPR0, MIN_BPR1],
    igrpen: [0, 0],
    ctlr: ICC_CTLR_RESET,
    apr: [0, 0],
};

static mut GIC: Gic = Gic {
    dist: Distributor {
        ctlr: CTLR_DS | CTLR_ARE,
        group: [0; WORDS],
        enabled: [0; WORDS],
        pending: [0; WORDS],
        active: [0; WORDS],
        level: [0; WORDS],
        edge: [0; WORDS],
        priority: [0; NUM_IRQ],
        irouter: [0; NUM_IRQ],
    },
    redist: [REDIST_RESET; MAX_CORES],
    cpuif: [CPUIF_RESET; MAX_CORES],
    hppi: [HPPI_NONE; MAX_CORES],
};

/// The GICv2's own state (a64_gic_set_version; snapshots: a64_machine_state 2)
#[derive(Clone, Copy)]
struct Gic2 {
    /// 2 or 3
    version: u32,
    /// ITARGETSR of the SPIs: the cores an SPI may go to (the lowest takes it)
    targets: [u8; NUM_IRQ],
    /// the source cores of each core's pending SGIs
    sgi_sources: [[u8; 16]; MAX_CORES],
    /// GICC_CTLR's bits besides the group enables and EOImode: AckCtl, FIQEn, CBPR
    ctlr: [u32; MAX_CORES],
    /// the source core of each core's active SGIs (IAR's CPUID)
    active_source: [[u8; 16]; MAX_CORES],
}
static mut GIC2: Gic2 = Gic2 {
    version: 3,
    targets: [0; NUM_IRQ],
    sgi_sources: [[0; 16]; MAX_CORES],
    ctlr: [0; MAX_CORES],
    active_source: [[0; 16]; MAX_CORES],
};
#[inline(always)]
fn gic2() -> &'static mut Gic2 { unsafe { &mut *crate::parallel::machine(&raw mut GIC2) } }
/// Whether the GIC is a GICv2
#[inline(always)]
pub fn is_v2() -> bool { gic2().version == 2 }

/// (the machine, before a64_set_cores) the GIC's architecture: 2 or 3 (the default)
#[no_mangle]
pub fn a64_gic_set_version(version: u32) {
    gic2().version = if version == 2 { 2 } else { 3 };
    reset();
}

/// (snapshots) the GICv2's own state as bytes: its address and size
pub fn v2_state_bytes() -> (u32, u32) {
    (&raw const GIC2 as u32, core::mem::size_of::<Gic2>() as u32)
}

const GICC_CTLR_FIQEN: u32 = 1 << 3;
const GICC_CTLR_CBPR: u32 = 1 << 4;
const GICC_CTLR_EOIMODE: u32 = 1 << 9;

/// Each core's interrupt request to the PE: bit 0 IRQ, bit 1 FIQ
pub static mut SIGNAL: [u8; MAX_CORES] = [0; MAX_CORES];
pub const SIGNAL_IRQ: u8 = 1;
pub const SIGNAL_FIQ: u8 = 2;

#[inline(always)]
fn gic() -> &'static mut Gic { unsafe { &mut *crate::parallel::machine(&raw mut GIC) } }

/// Core `core`'s interrupt request to the PE (SIGNAL_IRQ, SIGNAL_FIQ)
#[inline(always)]
pub fn signal(core: usize) -> u8 {
    unsafe {
        crate::parallel::load8(
            crate::parallel::machine(&raw mut SIGNAL)
                .cast::<u8>()
                .add(core),
        )
    }
}
fn set_signal(core: usize, value: u8) {
    unsafe {
        let at = crate::parallel::machine(&raw mut SIGNAL)
            .cast::<u8>()
            .add(core);
        if crate::parallel::load8(at) != value {
            crate::parallel::store8(at, value);
            // (a core in a worker leaves its slice or its wait)
            if value != 0 && core != crate::isa::current_core() {
                crate::parallel::kick(core);
            }
        }
    }
}

/// (cores in workers) the machine's GIC lock, held through each entry point
static mut LOCK: crate::parallel::SpinLock = crate::parallel::SpinLock::new();
/// How deep this instance's core holds it
static mut DEPTH: u32 = 0;
struct Guard;
impl Guard {
    #[inline(always)]
    fn new() -> Guard {
        unsafe {
            if crate::parallel::active() {
                if DEPTH == 0 {
                    (*crate::parallel::machine(&raw mut LOCK)).lock();
                }
                DEPTH += 1;
            }
        }
        Guard
    }
}
impl Drop for Guard {
    #[inline(always)]
    fn drop(&mut self) {
        unsafe {
            if crate::parallel::active() {
                DEPTH -= 1;
                if DEPTH == 0 {
                    (*crate::parallel::machine(&raw mut LOCK)).unlock();
                }
            }
        }
    }
}
/// A failed core's worker holds the lock no more (crate::parallel::parallel_fail)
pub fn release_held_by(core: usize) {
    unsafe { (*crate::parallel::machine(&raw mut LOCK)).release_held_by(core) }
}
/// (tests/parallel/lifecycle.mjs) a failing core traps inside the critical section
pub fn lock_for_test_fault() { unsafe { (*crate::parallel::machine(&raw mut LOCK)).lock() } }

fn cores() -> usize { crate::isa::core_count() }

/// (snapshots) the GIC's state as bytes: its address and size
pub fn state_bytes() -> (u32, u32) { (&raw const GIC as u32, core::mem::size_of::<Gic>() as u32) }

/// (snapshots) the state was replaced: the signals follow it
pub fn restored() {
    let _guard = Guard::new();
    update_all();
}

/// Reset the distributor, the redistributors and the CPU interfaces
pub fn reset() {
    let _guard = Guard::new();
    let g = gic();
    g.dist = Distributor {
        ctlr: CTLR_DS | CTLR_ARE,
        group: [0; WORDS],
        enabled: [0; WORDS],
        pending: [0; WORDS],
        active: [0; WORDS],
        level: [0; WORDS],
        edge: [0; WORDS],
        priority: [0; NUM_IRQ],
        irouter: [0; NUM_IRQ],
    };
    g.redist = [REDIST_RESET; MAX_CORES];
    g.cpuif = [CPUIF_RESET; MAX_CORES];
    g.hppi = [HPPI_NONE; MAX_CORES];
    let v2 = gic2();
    v2.targets = [0; NUM_IRQ];
    v2.sgi_sources = [[0; 16]; MAX_CORES];
    v2.ctlr = [0; MAX_CORES];
    v2.active_source = [[0; 16]; MAX_CORES];
    if v2.version == 2 {
        // (no affinity routing; the SGIs always enabled, as QEMU's; BPR's
        // minimum 0, ABPR's 1)
        g.dist.ctlr = 0;
        for core in 0..MAX_CORES {
            g.redist[core].enabled = 0xFFFF;
            g.cpuif[core].bpr = [0, 1];
        }
    }
    for core in 0..MAX_CORES {
        set_signal(core, 0);
    }
}

#[inline(always)]
fn bit(words: &[u32], irq: usize) -> bool { words[irq / 32] >> (irq % 32) & 1 != 0 }
#[inline(always)]
fn set_bit(words: &mut [u32], irq: usize, value: bool) {
    if value {
        words[irq / 32] |= 1 << (irq % 32);
    }
    else {
        words[irq / 32] &= !(1 << (irq % 32));
    }
}

/// The core an SPI goes to (its IROUTER's affinity; a GICv2's lowest ITARGETSR core), if any
fn target(irq: usize) -> Option<usize> {
    if is_v2() {
        let mask = gic2().targets[irq];
        let core = mask.trailing_zeros() as usize;
        return (mask != 0 && core < cores()).then_some(core);
    }
    let r = gic().dist.irouter[irq];
    // (Aff3:Aff2:Aff1:Aff0; Aff0 is the core, the others 0)
    let affinity = r & 0xFF_FFFF | (r >> 32 & 0xFF) << 24;
    let core = affinity as usize;
    (core < cores()).then_some(core)
}

/// Group enables of the distributor, as a mask for the group bits `group`
#[inline(always)]
fn group_mask(group: u32) -> u32 {
    let ctlr = gic().dist.ctlr;
    let mut mask = 0;
    if ctlr & CTLR_EN_GRP1 != 0 {
        mask |= group;
    }
    if ctlr & CTLR_EN_GRP0 != 0 {
        mask |= !group;
    }
    mask
}

/// Recompute a core's highest priority pending interrupt and its IRQ/FIQ signal
fn update(core: usize) {
    let g = gic();
    let mut best = HPPI_NONE;
    let mut consider = |irq: usize, prio: u32, group: usize| {
        if prio < best.prio || prio == best.prio && (irq as u32) < best.irq {
            best = Hppi {
                irq: irq as u32,
                prio,
                group,
            };
        }
    };
    let r = &g.redist[core];
    let pending = (r.pending | !r.edge & r.level) & r.enabled & !r.active & group_mask(r.group);
    let mut bits = pending;
    while bits != 0 {
        let irq = bits.trailing_zeros() as usize;
        bits &= bits - 1;
        consider(irq, r.priority[irq] as u32, (r.group >> irq & 1) as usize);
    }
    let d = &g.dist;
    for w in 1..WORDS {
        let mut bits = (d.pending[w] | !d.edge[w] & d.level[w])
            & d.enabled[w]
            & !d.active[w]
            & group_mask(d.group[w]);
        while bits != 0 {
            let irq = w * 32 + bits.trailing_zeros() as usize;
            bits &= bits - 1;
            if target(irq) == Some(core) {
                consider(irq, d.priority[irq] as u32, bit(&d.group, irq) as usize);
            }
        }
    }
    g.hppi[core] = best;
    let signal = if can_preempt(core) {
        // (a GICv2's group 0 is an IRQ unless FIQEn)
        if best.group == 0 && (!is_v2() || gic2().ctlr[core] & GICC_CTLR_FIQEN != 0) {
            SIGNAL_FIQ
        }
        else {
            SIGNAL_IRQ
        }
    }
    else {
        0
    };
    set_signal(core, signal);
}

fn update_all() {
    for core in 0..cores() {
        update(core);
    }
}

/// The SPI `irq` changed: its target core's state
fn update_spi(irq: usize) {
    match target(irq) {
        Some(core) => update(core),
        None => update_all(),
    }
}

// ---- the CPU interface's priority logic

/// The running priority: from the lowest set bit of the active priorities, 0xFF idle
fn running_priority(core: usize) -> u32 {
    let c = &gic().cpuif[core];
    let apr = c.apr[0] | c.apr[1];
    if apr == 0 {
        0xFF
    }
    else {
        apr.trailing_zeros() << (MIN_BPR0 + 1)
    }
}

/// The mask of a group's group-priority bits (GroupBits)
fn group_priority_mask(core: usize, group: usize) -> u32 {
    let c = &gic().cpuif[core];
    let (group, bpr) = if group == 1 && c.ctlr & ICC_CTLR_CBPR != 0 {
        (0, c.bpr[0] & 7)
    }
    else {
        (group, c.bpr[group] & 7)
    };
    let bpr = if group == 1 { bpr - 1 } else { bpr };
    !0u32 << (bpr + 1)
}

fn no_enabled_hppi(core: usize) -> bool {
    let h = gic().hppi[core];
    h.prio == 0x100 || gic().cpuif[core].igrpen[h.group] == 0
}

fn can_preempt(core: usize) -> bool {
    if no_enabled_hppi(core) {
        return false;
    }
    let h = gic().hppi[core];
    if h.prio >= gic().cpuif[core].pmr {
        return false;
    }
    let running = running_priority(core);
    if running == 0xFF {
        return true;
    }
    let mask = group_priority_mask(core, h.group);
    h.prio & mask < running & mask
}

fn activate(core: usize, irq: usize) {
    let g = gic();
    let h = g.hppi[core];
    let prio = h.prio & group_priority_mask(core, h.group);
    let aprbit = prio >> (8 - PRIBITS);
    g.cpuif[core].apr[h.group] |= 1 << aprbit;
    if irq < 32 {
        let r = &mut g.redist[core];
        r.active |= 1 << irq;
        r.pending &= !(1 << irq);
        // (a GICv2's SGI: one source at a time, the others stay pending)
        if is_v2() && irq < 16 {
            let sources = &mut gic2().sgi_sources[core][irq];
            let source = sources.trailing_zeros().min(7) as u8;
            *sources &= !(1 << source);
            gic2().active_source[core][irq] = source;
            if *sources != 0 {
                g.redist[core].pending |= 1 << irq;
            }
        }
        update(core);
    }
    else {
        set_bit(&mut g.dist.active, irq, true);
        set_bit(&mut g.dist.pending, irq, false);
        update_spi(irq);
        update(core);
    }
}

fn deactivate(core: usize, irq: usize) {
    let g = gic();
    if irq < 32 {
        g.redist[core].active &= !(1 << irq);
        update(core);
    }
    else if irq < NUM_IRQ {
        set_bit(&mut g.dist.active, irq, false);
        update_spi(irq);
    }
}

fn highest_active_group(core: usize) -> Option<usize> {
    let c = &gic().cpuif[core];
    let (a0, a1) = (c.apr[0], c.apr[1]);
    if a0 == 0 && a1 == 0 {
        return None;
    }
    // (the lowest set bit is the highest priority)
    Some(if a1 != 0 && (a0 == 0 || a1.trailing_zeros() < a0.trailing_zeros()) { 1 } else { 0 })
}

// ---- input lines

/// A device's SPI line (INTID 32-287) went to `level`
pub fn set_spi(irq: usize, level: bool) {
    if !(32..NUM_IRQ).contains(&irq) {
        return;
    }
    let _guard = Guard::new();
    let d = &mut gic().dist;
    if bit(&d.level, irq) == level {
        return;
    }
    set_bit(&mut d.level, irq, level);
    if level && bit(&d.edge, irq) {
        set_bit(&mut d.pending, irq, true);
    }
    update_spi(irq);
}

/// A PPI line (INTID 16-31) of `core` went to `level` (the timers)
pub fn set_ppi(core: usize, irq: usize, level: bool) {
    let _guard = Guard::new();
    let r = &mut gic().redist[core];
    if r.level >> irq & 1 == level as u32 {
        return;
    }
    r.level = r.level & !(1 << irq) | (level as u32) << irq;
    if level && r.edge >> irq & 1 != 0 {
        r.pending |= 1 << irq;
    }
    update(core);
}

/// (src/virt: a device's interrupt line)
#[no_mangle]
pub fn a64_gic_set_spi(irq: u32, level: bool) { set_spi(irq as usize, level) }

/// ISR_EL1: the pending IRQ (bit 7) and FIQ (bit 6) of the current core
pub fn isr_el1() -> u64 {
    crate::aarch64::timer::tick();
    let s = signal(crate::isa::current_core());
    ((s & SIGNAL_IRQ != 0) as u64) << 7 | ((s & SIGNAL_FIQ != 0) as u64) << 6
}

// ---- the ICC system registers

/// Whether `reg` is an ICC_* register (op0 3, op1 0, CRn 12 with CRm 8, 9,
/// 11 or 12, or ICC_PMR_EL1)
pub fn is_icc(reg: u32) -> bool {
    let op0 = reg >> 14;
    let op1 = reg >> 11 & 7;
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    op0 == 3
        && op1 == 0
        && (crn == 12 && matches!(crm, 8 | 9 | 11 | 12) || crn == 4 && crm == 6 && op2 == 0)
}

fn hppir_value(core: usize, group: usize) -> u64 {
    if no_enabled_hppi(core) {
        return SPURIOUS;
    }
    let h = gic().hppi[core];
    if h.group != group {
        SPURIOUS
    }
    else {
        h.irq as u64
    }
}

pub fn icc_read(reg: u32) -> Result<u64, Exception> {
    if cpu::el() == 0 {
        return Err(Exception::Undefined);
    }
    crate::aarch64::timer::tick();
    let _guard = Guard::new();
    let core = crate::isa::current_core();
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    let crn = reg >> 7 & 15;
    if crn == 4 {
        return Ok(gic().cpuif[core].pmr as u64);
    }
    let c = gic().cpuif[core];
    Ok(match (crm, op2) {
        (8, 0) | (12, 0) => {
            // IAR0, IAR1: acknowledge
            let group = (crm == 12) as usize;
            let intid = if can_preempt(core) { hppir_value(core, group) } else { SPURIOUS };
            if intid < 1020 {
                activate(core, intid as usize);
            }
            intid
        },
        (8, 2) => hppir_value(core, 0),
        (12, 2) => hppir_value(core, 1),
        (8, 3) => c.bpr[0] as u64,
        (12, 3) => {
            if c.ctlr & ICC_CTLR_CBPR != 0 {
                (c.bpr[0] + 1).min(7) as u64
            }
            else {
                c.bpr[1] as u64
            }
        },
        (8, 4..=7) => {
            if op2 == 4 {
                c.apr[0] as u64
            }
            else {
                0
            }
        },
        (9, 0..=3) => {
            if op2 == 0 {
                c.apr[1] as u64
            }
            else {
                0
            }
        },
        (11, 3) => running_priority(core) as u64,
        (12, 4) => c.ctlr as u64,
        // ICC_SRE_EL1: SRE, DFB, DIB (RAO/WI)
        (12, 5) => 7,
        (12, 6) => c.igrpen[0] as u64,
        (12, 7) => c.igrpen[1] as u64,
        // (EOIR, DIR, SGIxR are write-only)
        _ => return Err(Exception::Undefined),
    })
}

pub fn icc_write(reg: u32, value: u64) -> Result<(), Exception> {
    if cpu::el() == 0 {
        return Err(Exception::Undefined);
    }
    let _guard = Guard::new();
    let core = crate::isa::current_core();
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    let crn = reg >> 7 & 15;
    let g = gic();
    if crn == 4 {
        g.cpuif[core].pmr = value as u32 & PRIO_MASK;
        update(core);
        return Ok(());
    }
    match (crm, op2) {
        (8, 1) | (12, 1) => {
            // EOIR0, EOIR1: priority drop (and deactivation unless EOImode)
            let irq = (value & 0xFF_FFFF) as usize;
            if irq >= NUM_IRQ {
                return Ok(());
            }
            let eoir0 = crm == 8;
            match highest_active_group(core) {
                Some(0) if eoir0 => {},
                Some(1) if !eoir0 => {},
                _ => return Ok(()),
            }
            let group = (!eoir0) as usize;
            let apr = &mut g.cpuif[core].apr[group];
            *apr &= apr.wrapping_sub(1);
            update(core);
            if g.cpuif[core].ctlr & ICC_CTLR_EOIMODE == 0 {
                deactivate(core, irq);
            }
        },
        (11, 1) => {
            // DIR: deactivation with EOImode
            let irq = (value & 0xFF_FFFF) as usize;
            if irq < NUM_IRQ && g.cpuif[core].ctlr & ICC_CTLR_EOIMODE != 0 {
                deactivate(core, irq);
            }
        },
        (8, 3) => {
            g.cpuif[core].bpr[0] = (value as u32).max(MIN_BPR0) & 7;
            update(core);
        },
        (12, 3) => {
            if g.cpuif[core].ctlr & ICC_CTLR_CBPR == 0 {
                g.cpuif[core].bpr[1] = (value as u32).max(MIN_BPR1) & 7;
                update(core);
            }
        },
        (8, 4..=7) => {
            if op2 == 4 {
                g.cpuif[core].apr[0] = value as u32;
                update(core);
            }
        },
        (9, 0..=3) => {
            if op2 == 0 {
                g.cpuif[core].apr[1] = value as u32;
                update(core);
            }
        },
        // SGI1R (group 1), ASGI1R (the other group: group 0 here), SGI0R
        (11, 5) => send_sgi(core, value, 1),
        (11, 6) | (11, 7) => send_sgi(core, value, 0),
        (12, 4) => {
            let mask = ICC_CTLR_CBPR | ICC_CTLR_EOIMODE;
            let c = &mut g.cpuif[core];
            c.ctlr = c.ctlr & !mask | value as u32 & mask;
            update(core);
        },
        (12, 5) => {},
        (12, 6) => {
            g.cpuif[core].igrpen[0] = value as u32 & 1;
            update(core);
        },
        (12, 7) => {
            g.cpuif[core].igrpen[1] = value as u32 & 1;
            update(core);
        },
        // (IAR, HPPIR, RPR are read-only)
        _ => return Err(Exception::Undefined),
    }
    Ok(())
}

/// ICC_SGI*R: SGI `value[27:24]` to the cores in the target list of
/// Aff3.Aff2.Aff1 (IRM 0) or to every other core (IRM 1), in `group`
fn send_sgi(core: usize, value: u64, group: usize) {
    let affinity = (value >> 48 & 0xFF) << 16 | (value >> 32 & 0xFF) << 8 | (value >> 16 & 0xFF);
    let targets = value & 0xFFFF;
    let irq = (value >> 24 & 15) as usize;
    let irm = value >> 40 & 1 != 0;
    for other in 0..cores() {
        if irm {
            if other == core {
                continue;
            }
        }
        else if affinity != 0 || other > 15 || targets >> other & 1 == 0 {
            continue;
        }
        // (the SGI is accepted if it is in the requested group at the target)
        let r = &mut gic().redist[other];
        if (r.group >> irq & 1) as usize != group {
            continue;
        }
        r.pending |= 1 << irq;
        update(other);
    }
}

// ---- the distributor's and redistributors' registers

/// ID registers at 0xFFD0-0xFFFC (PIDR4-7, PIDR0-3, CIDR0-3), `pidr0` the part
fn id_register(offset: u64, pidr0: u64) -> u64 {
    const IDS: [u64; 12] = [0x44, 0, 0, 0, 0x92, 0xB4, 0x3B, 0, 0x0D, 0xF0, 0x05, 0xB1];
    let index = ((offset - 0xFFD0) / 4) as usize;
    if index == 4 {
        pidr0
    }
    else {
        IDS[index]
    }
}

/// A bitmap register of 32 INTIDs at `word` (set/clear forms); `words` the state
fn bitmap_write(words: &mut [u32], word: usize, value: u32, set: bool) {
    if set {
        words[word] |= value;
    }
    else {
        words[word] &= !value;
    }
}

/// Read a byte-wide field array (IPRIORITYR) of `size` bytes from `bytes[irq..]`
fn bytes_read(bytes: &[u8], irq: usize, size: u32) -> u64 {
    let mut value = 0;
    for i in 0..size as usize {
        if irq + i < bytes.len() {
            value |= (bytes[irq + i] as u64) << (8 * i);
        }
    }
    value
}

pub fn gicd_read(offset: u64, size: u32) -> u64 {
    crate::aarch64::timer::tick_all();
    let _guard = Guard::new();
    if is_v2() {
        let value = gicd2_read(offset, size);
        return value & if size == 8 { u64::MAX } else { (1u64 << (8 * size)) - 1 };
    }
    let d = &gic().dist;
    let word = ((offset & 0x7F) / 4) as usize;
    let value = match offset {
        0x0000 => d.ctlr as u64,
        // TYPER: No1N, A3V, IDbits 16, ITLinesNumber
        0x0004 => (1 << 25 | 1 << 24 | 0xF << 19 | (NUM_IRQ / 32 - 1)) as u64,
        0x0008 => 0x43B,
        0x0080..=0x00FC => {
            if word == 0 || word >= WORDS {
                0
            }
            else {
                d.group[word] as u64
            }
        },
        0x0100..=0x017C | 0x0180..=0x01FC => {
            if word == 0 || word >= WORDS {
                0
            }
            else {
                d.enabled[word] as u64
            }
        },
        // (the pending latch, or the line of a level-sensitive interrupt)
        0x0200..=0x027C | 0x0280..=0x02FC => {
            if word == 0 || word >= WORDS {
                0
            }
            else {
                (d.pending[word] | !d.edge[word] & d.level[word]) as u64
            }
        },
        0x0300..=0x037C | 0x0380..=0x03FC => {
            if word == 0 || word >= WORDS {
                0
            }
            else {
                d.active[word] as u64
            }
        },
        0x0400..=0x07FB => {
            let irq = (offset - 0x400) as usize;
            if irq < 32 {
                0
            }
            else {
                bytes_read(&d.priority, irq, size)
            }
        },
        0x0C00..=0x0CFC => {
            // ICFGR: 16 INTIDs per word, bit 2n+1 edge
            let first = ((offset - 0xC00) / 4) as usize * 16;
            let mut value = 0u64;
            if first >= 32 && first < NUM_IRQ {
                for i in 0..16 {
                    if bit(&d.edge, first + i) {
                        value |= 2 << (2 * i);
                    }
                }
            }
            value
        },
        0x6100..=0x7FD8 => {
            let irq = ((offset - 0x6000) / 8) as usize;
            let v = if irq < NUM_IRQ { d.irouter[irq] } else { 0 };
            if offset & 4 != 0 {
                v >> 32
            }
            else {
                v
            }
        },
        0xFFD0..=0xFFFC => id_register(offset & !3, 0x92),
        _ => 0,
    };
    value & if size == 8 { u64::MAX } else { (1u64 << (8 * size)) - 1 }
}

pub fn gicd_write(offset: u64, size: u32, value: u64) {
    let _guard = Guard::new();
    if is_v2() {
        return gicd2_write(offset, size, value);
    }
    let g = gic();
    let word = ((offset & 0x7F) / 4) as usize;
    let v = value as u32;
    match offset {
        0x0000 => {
            let mask = CTLR_EN_GRP0 | CTLR_EN_GRP1;
            g.dist.ctlr = g.dist.ctlr & !mask | v & mask;
            update_all();
        },
        0x0080..=0x00FC if word != 0 && word < WORDS => {
            g.dist.group[word] = v;
            update_all();
        },
        0x0100..=0x017C if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.enabled, word, v, true);
            update_all();
        },
        0x0180..=0x01FC if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.enabled, word, v, false);
            update_all();
        },
        0x0200..=0x027C if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.pending, word, v, true);
            update_all();
        },
        0x0280..=0x02FC if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.pending, word, v, false);
            update_all();
        },
        0x0300..=0x037C if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.active, word, v, true);
            update_all();
        },
        0x0380..=0x03FC if word != 0 && word < WORDS => {
            bitmap_write(&mut g.dist.active, word, v, false);
            update_all();
        },
        0x0400..=0x07FB => {
            let irq = (offset - 0x400) as usize;
            for i in 0..size as usize {
                if irq + i >= 32 && irq + i < NUM_IRQ {
                    g.dist.priority[irq + i] = (value >> (8 * i)) as u8;
                }
            }
            update_all();
        },
        0x0C00..=0x0CFC => {
            let first = ((offset - 0xC00) / 4) as usize * 16;
            if first >= 32 && first < NUM_IRQ {
                for i in 0..16 {
                    set_bit(&mut g.dist.edge, first + i, v >> (2 * i + 1) & 1 != 0);
                }
            }
            update_all();
        },
        0x6100..=0x7FD8 => {
            let irq = ((offset - 0x6000) / 8) as usize;
            if irq >= 32 && irq < NUM_IRQ {
                let old = g.dist.irouter[irq];
                g.dist.irouter[irq] = match (size, offset & 4) {
                    (8, _) => value,
                    (_, 0) => old & !0xFFFF_FFFF | value & 0xFFFF_FFFF,
                    _ => old & 0xFFFF_FFFF | (value & 0xFFFF_FFFF) << 32,
                };
                update_all();
            }
        },
        _ => {},
    }
}

pub fn gicr_read(offset: u64, size: u32) -> u64 {
    // (every core's timer lines as of now: they follow the counter)
    crate::aarch64::timer::tick_all();
    let _guard = Guard::new();
    let core = (offset / GICR_STRIDE) as usize;
    if core >= cores() {
        return 0;
    }
    let offset = offset % GICR_STRIDE;
    let r = &gic().redist[core];
    let typer =
        (core as u64) << 32 | 1 << 24 | (core as u64) << 8 | ((core + 1 == cores()) as u64) << 4;
    let value = match offset {
        0x0000 => 0,
        0x0004 => 0x43B,
        0x0008 => typer,
        0x000C => typer >> 32,
        0x0014 => r.waker as u64,
        0xFFD0..=0xFFFC => id_register(offset & !3, 0x93),
        0x1_0080 => r.group as u64,
        0x1_0100 | 0x1_0180 => r.enabled as u64,
        0x1_0200 | 0x1_0280 => (r.pending | !r.edge & r.level) as u64,
        0x1_0300 | 0x1_0380 => r.active as u64,
        0x1_0400..=0x1_041F => bytes_read(&r.priority, (offset - 0x1_0400) as usize, size),
        0x1_0C00 => 0xAAAA_AAAA,
        0x1_0C04 => {
            let mut value = 0u64;
            for i in 0..16 {
                if r.edge >> (16 + i) & 1 != 0 {
                    value |= 2 << (2 * i);
                }
            }
            value
        },
        _ => 0,
    };
    value & if size == 8 { u64::MAX } else { (1u64 << (8 * size)) - 1 }
}

pub fn gicr_write(offset: u64, size: u32, value: u64) {
    let _guard = Guard::new();
    let core = (offset / GICR_STRIDE) as usize;
    if core >= cores() {
        return;
    }
    let offset = offset % GICR_STRIDE;
    let r = &mut gic().redist[core];
    let v = value as u32;
    match offset {
        0x0014 => {
            // WAKER: ProcessorSleep, and ChildrenAsleep follows it at once
            let sleep = v & 2;
            r.waker = sleep | sleep << 1;
        },
        0x1_0080 => r.group = v,
        0x1_0100 => r.enabled |= v,
        0x1_0180 => r.enabled &= !v,
        0x1_0200 => r.pending |= v,
        0x1_0280 => r.pending &= !v,
        0x1_0300 => r.active |= v,
        0x1_0380 => r.active &= !v,
        0x1_0400..=0x1_041F => {
            let irq = (offset - 0x1_0400) as usize;
            for i in 0..size as usize {
                if irq + i < 32 {
                    r.priority[irq + i] = (value >> (8 * i)) as u8;
                }
            }
        },
        0x1_0C04 => {
            let mut edge = r.edge & 0xFFFF;
            for i in 0..16 {
                if v >> (2 * i + 1) & 1 != 0 {
                    edge |= 1 << (16 + i);
                }
            }
            r.edge = edge;
        },
        _ => return,
    }
    update(core);
}

// ---- the GICv2's registers

/// A GICv2 distributor register: the SGIs' and PPIs' words and bytes are
/// the current core's (its redistributor state)
fn gicd2_read(offset: u64, size: u32) -> u64 {
    let core = crate::isa::current_core();
    let g = gic();
    let d = &g.dist;
    let r = &g.redist[core];
    let word = ((offset & 0x7F) / 4) as usize;
    let banked = |w: usize, own: u32, words: &[u32; WORDS]| -> u64 {
        if w == 0 {
            own as u64
        }
        else if w < WORDS {
            words[w] as u64
        }
        else {
            0
        }
    };
    match offset {
        0x0000 => (d.ctlr & (CTLR_EN_GRP0 | CTLR_EN_GRP1)) as u64,
        // TYPER: CPUNumber, ITLinesNumber; no Security Extensions
        0x0004 => (cores() as u64 - 1) << 5 | (NUM_IRQ / 32 - 1) as u64,
        0x0008 => 0x43B,
        0x0080..=0x00FC => banked(word, r.group, &d.group),
        0x0100..=0x017C | 0x0180..=0x01FC => banked(word, r.enabled, &d.enabled),
        0x0200..=0x027C | 0x0280..=0x02FC => {
            let own = r.pending | !r.edge & r.level;
            if word == 0 {
                own as u64
            }
            else if word < WORDS {
                (d.pending[word] | !d.edge[word] & d.level[word]) as u64
            }
            else {
                0
            }
        },
        0x0300..=0x037C | 0x0380..=0x03FC => banked(word, r.active, &d.active),
        0x0400..=0x07FB => {
            let irq = (offset - 0x400) as usize;
            let mut value = 0u64;
            for i in 0..size as usize {
                let n = irq + i;
                let p = if n < 32 {
                    r.priority[n]
                }
                else if n < NUM_IRQ {
                    d.priority[n]
                }
                else {
                    0
                };
                value |= (p as u64) << (8 * i);
            }
            value
        },
        // ITARGETSR: the SGIs' and PPIs' read as this core
        0x0800..=0x0BFB => {
            let irq = (offset - 0x800) as usize;
            let mut value = 0u64;
            for i in 0..size as usize {
                let n = irq + i;
                let t = if n < 32 {
                    1u8 << core
                }
                else if n < NUM_IRQ {
                    gic2().targets[n]
                }
                else {
                    0
                };
                value |= (t as u64) << (8 * i);
            }
            value
        },
        0x0C00..=0x0CFC => {
            let first = ((offset - 0xC00) / 4) as usize * 16;
            let mut value = 0u64;
            for i in 0..16 {
                let n = first + i;
                let edge = if n < 16 {
                    true
                }
                else if n < 32 {
                    r.edge >> n & 1 != 0
                }
                else {
                    n < NUM_IRQ && bit(&d.edge, n)
                };
                if edge {
                    value |= 2 << (2 * i);
                }
            }
            value
        },
        // CPENDSGIR, SPENDSGIR: a byte per SGI, a bit per source core
        0x0F10..=0x0F2F => {
            let sgi = ((offset & 0xF) as usize).min(15);
            let mut value = 0u64;
            for i in 0..size as usize {
                if sgi + i < 16 {
                    value |= (gic2().sgi_sources[core][sgi + i] as u64) << (8 * i);
                }
            }
            value
        },
        // PIDR2: ArchRev 2
        0x0FE8 => 0x2B,
        _ => 0,
    }
}

fn gicd2_write(offset: u64, size: u32, value: u64) {
    let core = crate::isa::current_core();
    let g = gic();
    let word = ((offset & 0x7F) / 4) as usize;
    let v = value as u32;
    // (word 0 of a bitmap: the current core's SGIs and PPIs)
    let bitmap = |g: &mut Gic, kind: usize, set: bool| {
        if word == 0 {
            let r = &mut g.redist[core];
            let own = match kind {
                0 => &mut r.enabled,
                1 => &mut r.pending,
                _ => &mut r.active,
            };
            if set {
                *own |= v;
            }
            else {
                *own &= !v;
            }
        }
        else if word < WORDS {
            let words = match kind {
                0 => &mut g.dist.enabled,
                1 => &mut g.dist.pending,
                _ => &mut g.dist.active,
            };
            bitmap_write(words, word, v, set);
        }
    };
    match offset {
        0x0000 => g.dist.ctlr = v & (CTLR_EN_GRP0 | CTLR_EN_GRP1),
        0x0080..=0x00FC => {
            if word == 0 {
                g.redist[core].group = v;
            }
            else if word < WORDS {
                g.dist.group[word] = v;
            }
        },
        0x0100..=0x017C => bitmap(g, 0, true),
        0x0180..=0x01FC => {
            bitmap(g, 0, false);
            g.redist[core].enabled |= 0xFFFF;
        },
        0x0200..=0x027C => bitmap(g, 1, true),
        0x0280..=0x02FC => {
            bitmap(g, 1, false);
            // (SGIs are cleared through CPENDSGIR, not here)
        },
        0x0300..=0x037C => bitmap(g, 2, true),
        0x0380..=0x03FC => bitmap(g, 2, false),
        0x0400..=0x07FB => {
            let irq = (offset - 0x400) as usize;
            for i in 0..size as usize {
                let n = irq + i;
                let p = (value >> (8 * i)) as u8;
                if n < 32 {
                    g.redist[core].priority[n] = p;
                }
                else if n < NUM_IRQ {
                    g.dist.priority[n] = p;
                }
            }
        },
        0x0800..=0x0BFB => {
            let irq = (offset - 0x800) as usize;
            for i in 0..size as usize {
                let n = irq + i;
                if (32..NUM_IRQ).contains(&n) {
                    gic2().targets[n] = (value >> (8 * i)) as u8;
                }
            }
        },
        0x0C00..=0x0CFC => {
            let first = ((offset - 0xC00) / 4) as usize * 16;
            for i in 0..16 {
                let n = first + i;
                let edge = v >> (2 * i + 1) & 1 != 0;
                if (16..32).contains(&n) {
                    let r = &mut g.redist[core];
                    r.edge = r.edge & !(1 << n) | (edge as u32) << n;
                }
                else if (32..NUM_IRQ).contains(&n) {
                    set_bit(&mut g.dist.edge, n, edge);
                }
            }
        },
        // SGIR: TargetListFilter (0 the list, 1 the others, 2 this core), the list, the INTID
        0x0F00 => {
            let sgi = (v & 15) as usize;
            let list = match v >> 24 & 3 {
                0 => v >> 16 & 0xFF,
                1 => 0xFF & !(1 << core),
                2 => 1 << core,
                _ => 0,
            };
            for other in 0..cores().min(8) {
                if list >> other & 1 != 0 {
                    gic2().sgi_sources[other][sgi] |= 1 << core;
                    g.redist[other].pending |= 1 << sgi;
                    update(other);
                }
            }
        },
        0x0F10..=0x0F2F => {
            let set = offset >= 0x0F20;
            let sgi = (offset & 0xF) as usize;
            for i in 0..size as usize {
                if sgi + i >= 16 {
                    break;
                }
                let bits = (value >> (8 * i)) as u8;
                let sources = &mut gic2().sgi_sources[core][sgi + i];
                if set {
                    *sources |= bits;
                }
                else {
                    *sources &= !bits;
                }
                let r = &mut g.redist[core];
                r.pending = r.pending & !(1 << (sgi + i)) | ((*sources != 0) as u32) << (sgi + i);
            }
        },
        _ => return,
    }
    update_all();
}

/// The GICv2 CPU interface (GICC): its registers are the ICC registers'
/// logic for both groups at once (no Security Extensions)
pub fn gicc_read(offset: u64, _size: u32) -> u64 {
    crate::aarch64::timer::tick();
    let _guard = Guard::new();
    let core = crate::isa::current_core();
    let c = gic().cpuif[core];
    match offset {
        0x0000 => {
            (c.igrpen[0] | c.igrpen[1] << 1) as u64
                | gic2().ctlr[core] as u64
                | if c.ctlr & ICC_CTLR_EOIMODE != 0 { GICC_CTLR_EOIMODE as u64 } else { 0 }
        },
        0x0004 => c.pmr as u64,
        0x0008 => c.bpr[0] as u64,
        0x001C => c.bpr[1] as u64,
        // IAR, AIAR: acknowledge the highest priority pending interrupt (an SGI with its source)
        0x000C | 0x0020 => {
            if !can_preempt(core) {
                return SPURIOUS;
            }
            let h = gic().hppi[core];
            let irq = h.irq as usize;
            activate(core, irq);
            if irq < 16 {
                irq as u64 | (gic2().active_source[core][irq] as u64) << 10
            }
            else {
                irq as u64
            }
        },
        0x0014 => running_priority(core) as u64,
        // (HPPIR: not an interrupt the priority mask holds back, as QEMU's)
        0x0018 | 0x0028 => {
            let h = gic().hppi[core];
            if no_enabled_hppi(core) || h.prio >= c.pmr {
                SPURIOUS
            }
            else {
                h.irq as u64
            }
        },
        0x00D0 => c.apr[0] as u64,
        0x00E0 => c.apr[1] as u64,
        // IIDR: GICv2, ARM
        0x00FC => 0x0202_043B,
        _ => 0,
    }
}

pub fn gicc_write(offset: u64, _size: u32, value: u64) {
    let _guard = Guard::new();
    let core = crate::isa::current_core();
    let g = gic();
    let v = value as u32;
    match offset {
        0x0000 => {
            let c = &mut g.cpuif[core];
            c.igrpen = [v & 1, v >> 1 & 1];
            let mut ctlr = c.ctlr & !(ICC_CTLR_CBPR | ICC_CTLR_EOIMODE);
            if v & GICC_CTLR_CBPR != 0 {
                ctlr |= ICC_CTLR_CBPR;
            }
            if v & GICC_CTLR_EOIMODE != 0 {
                ctlr |= ICC_CTLR_EOIMODE;
            }
            c.ctlr = ctlr;
            gic2().ctlr[core] = v & (1 << 2 | GICC_CTLR_FIQEN | GICC_CTLR_CBPR);
        },
        0x0004 => g.cpuif[core].pmr = v & PRIO_MASK,
        0x0008 => g.cpuif[core].bpr[0] = v & 7,
        0x001C => g.cpuif[core].bpr[1] = v.max(1) & 7,
        // EOIR, AEOIR: priority drop of the highest active priority, and deactivation unless EOImode
        0x0010 | 0x0024 => {
            let irq = (v & 0x3FF) as usize;
            if irq >= NUM_IRQ {
                return;
            }
            let Some(group) = highest_active_group(core)
            else {
                return;
            };
            let apr = &mut g.cpuif[core].apr[group];
            *apr &= apr.wrapping_sub(1);
            update(core);
            if g.cpuif[core].ctlr & ICC_CTLR_EOIMODE == 0 {
                deactivate(core, irq);
            }
        },
        0x00D0 => g.cpuif[core].apr[0] = v,
        0x00E0 => g.cpuif[core].apr[1] = v,
        // DIR
        0x1000 => {
            let irq = (v & 0x3FF) as usize;
            if irq < NUM_IRQ && g.cpuif[core].ctlr & ICC_CTLR_EOIMODE != 0 {
                deactivate(core, irq);
            }
        },
        _ => return,
    }
    update(core);
}
                                                                                                                                                                                                                                                                                                                                                  source/v64/src/rust/aarch64/isa_hooks.rs                                                            0000644 0000000 0000000 00000010577 00000000000 015237  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ARM core's side of the code both cores share (lib.rs names this
//! module `crate::isa` in the ARM core; cpu::isa_hooks is the x86 core's),
//! and how its cores run in vCPU workers (P8.2): a worker attaches with a
//! copy of the machine's map and guest memory, and takes other cores' code
//! writes, publications and TLB maintenance at its safe points (`poll`).
use crate::page::Page;

pub const MAX_CORES: usize = 8;

/// The core this instance runs now (the cooperative scheduler sets it, P3.7)
pub(crate) static mut CURRENT_CORE: usize = 0;
/// The machine's cores
pub(crate) static mut CORE_COUNT: usize = 1;
/// Set by parallel::kick: leave the current slice
pub(crate) static mut CORE_YIELD: u8 = 0;

#[cfg(target_arch = "wasm32")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn microtick() -> f64;
    }
}
#[cfg(not(target_arch = "wasm32"))]
mod js {
    pub unsafe fn microtick() -> f64 { 0.0 }
}

#[inline(always)]
pub fn current_core() -> usize { unsafe { CURRENT_CORE } }
#[inline(always)]
pub fn core_count() -> usize { unsafe { *crate::parallel::machine(&raw mut CORE_COUNT) } }
/// The host's clock in milliseconds (env.microtick)
#[inline(always)]
pub unsafe fn microtick() -> f64 { js::microtick() }

#[inline(always)]
pub unsafe fn core_yield_address() -> u32 { &raw mut CORE_YIELD as u32 }

/// The machine instance starts running cores in workers: the RAM pages
/// whose compiled code the cores track (crate::parallel::code)
pub unsafe fn machine_set_active() {
    crate::parallel::code::allocate(crate::aarch64::bus::bus().ram_size() as u32 / 4096);
    crate::aarch64::tlb::ring_synced_now();
}
/// parallel_attach: this instance runs core `core`, with the machine's map and guest memory
pub unsafe fn attach_worker(core: u32) {
    CURRENT_CORE = core as usize;
    crate::aarch64::bus::sync_worker();
    crate::aarch64::tlb::ring_synced_now();
    crate::aarch64::tlb::flush(false);
}
/// After a stop: the machine may have changed its map
pub unsafe fn sync_worker() {
    crate::aarch64::bus::sync_worker();
    crate::aarch64::tlb::ring_synced_now();
}
#[inline(always)]
pub unsafe fn sync_worker_configuration() { crate::aarch64::bus::sync_worker_if_stale() }
/// A failed core's locks: the GIC's, extended RAM's
pub unsafe fn release_locks_held_by(core: usize) {
    crate::aarch64::gic::release_held_by(core);
    crate::extended::release_held_by(core);
}
pub unsafe fn lock_for_test_fault() { crate::aarch64::gic::lock_for_test_fault() }

/// At a safe point (no compiled code runs): the other cores' code writes
/// and publications (crate::parallel::code), then their TLB maintenance,
/// acknowledged (crate::aarch64::tlb)
#[inline]
pub fn poll() {
    if crate::parallel::active() {
        unsafe { crate::parallel::code::poll() };
        crate::aarch64::tlb::poll();
    }
}

// ---- crate::extended (extended RAM, P8.5): the page tier's access cache
// may hold its frames (crate::aarch64::extended::cache_frame); code compiled
// from a page retires at its write

/// Every core's access cache entries retire (no compiled code is active)
pub unsafe fn extended_release_caches() {
    for core in 0..MAX_CORES {
        crate::aarch64::jit::pages::tlb_flushed(core);
    }
}
pub unsafe fn extended_retire_cached_writes(host: u32) {
    crate::aarch64::jit::pages::retire_writes_to(host)
}
pub unsafe fn extended_code_written(page: u32) {
    crate::aarch64::root::dirty_bytes(
        crate::page::Page::of_u32(crate::aarch64::bus::EXTENDED_CODE_KEY + page),
        0,
        4096,
    );
}
#[inline(always)]
pub unsafe fn extended_discarded() {}

/// Other cores published code from `pages`: this core's access cache
/// serves no more stores to them (they must reach crate::parallel::code)
pub unsafe fn others_published(pages: &[u32], overflow: bool) {
    let core = current_core();
    if overflow {
        crate::aarch64::jit::pages::tlb_flushed(core);
        return;
    }
    let set: std::collections::HashSet<Page> = pages.iter().map(|&p| Page::of_u32(p)).collect();
    crate::aarch64::jit::pages::pages_gain_code(&set);
}

/// Other cores wrote `pages`: retire this core's code from them
#[inline(always)]
pub unsafe fn others_wrote(pages: Vec<u32>, overflow: bool) {
    let mut rt = crate::jitrt::state();
    if overflow {
        rt.watch.reset();
    }
    else {
        for page in pages {
            rt.watch.retire(Page::page_of(page << 12), None);
        }
    }
}
                                                                                                                                 source/v64/src/rust/aarch64/jit/mod.rs                                                              0000644 0000000 0000000 00000017502 00000000000 014620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The A64 page tier (docs/jit-unification-plan.md P6, J2;
//! docs/arm64-virt-android16-plan.md P6): the runtime client (pages) and the
//! code generator (pagegen), the ARM core's composition of jitrt (with
//! crate::aarch64::root) and its switches (P6.0):
//!
//! - a64_page: compiled code runs (default off until its F gate)
//! - a64_page_hot: interpreted instructions on a page before it is compiled
//! - a64_neon: the AdvSIMD templates (P6.3b)
//! - a64_asid_tag: the ASID in the access cache's tags (P6.4: an epoch per
//!   ASID; 0, off: an ASID switch flushes the non-global entries; 2, auto,
//!   the default since the ARM plan's P9.3: on while the ASIDs change often)
//! - a64_helpers: helper calls for the forms pagegen::helper takes (off:
//!   single steps)
//! - a64_relaxed_fma: the multiply-adds through relaxed SIMD (only where the
//!   host fuses them; its default is the host's probe)
//! - a64_page_aarch32: AArch32's code (EL0's A32 and T32) compiled too
//!   (docs/aarch32-plan.md Q6; on since its gate, Q6.4); for bisecting,
//!   2: helper calls only (the native forms stepped), 3: the native forms
//!   only (helper calls stepped), 16 + a mask of native kinds run as helper
//!   calls (32 data processing, 64 MOVW and MOVT, 128 loads and stores, 256
//!   LDM and STM, 512 multiplies, 1024 extends)
//! - a64_page_aarch32_filter: (bisecting) n << 16 | pattern: only the
//!   AArch32 pages whose code key's low n bits are the pattern's are
//!   compiled, each named on the console
//! - a64_system: the EL1 system templates, a mask (pagegen::SYSTEM_*): bit 0
//!   MRS and MSR of SP_EL0, TPIDR_EL1, DAIF, ELR_EL1, SPSR_EL1, ESR_EL1,
//!   FAR_EL1, MRS DCZID_EL0, MSR DAIFSet and DAIFClr; 1 TLBI; 2 DC ZVA; 3 LDTR
//!   and STTR; 4 DSB with cores in workers when nothing is pending (0: helpers
//!   and steps, as before 2026-10-20)
//!
//! jitrt and pagegen never name this module (tools/check_a64_imports.mjs,
//! tools/check_x86tpl_imports.mjs).

pub mod pagegen;
pub mod pages;

/// AdvSIMD templates
pub static mut NEON: bool = true;
/// Helper calls instead of single steps for the forms pagegen::helper takes
pub static mut HELPERS: bool = true;
/// The EL1 system templates (a64_system's mask: pagegen::SYSTEM_*)
pub static mut SYSTEM: u32 = pagegen::SYSTEM_ALL;
/// The multiply-adds through relaxed SIMD (a64_relaxed_fma): only where the
/// host fuses them (a64_page_set_relaxed_fma_fused, the host's probe)
pub static mut RELAXED_FMA: bool = false;
static mut FMA_FUSED: bool = false;
#[no_mangle]
pub fn a64_page_set_relaxed_fma_fused(fused: bool) {
    unsafe {
        FMA_FUSED = fused;
        RELAXED_FMA = fused;
    }
}
/// The ASID in the access cache's tags (P6.4: an epoch per ASID,
/// pages::bind_asid; off, an ASID switch drops the non-global entries)
pub static mut ASID_TAG: bool = false;
/// a64_asid_tag: 0 off, 1 on, 2 auto (pages::asid_tag_tick: on while the
/// ASIDs change often, as with SW_TTBR0_PAN, which changes them at every
/// entry from EL0 and around every uaccess; the epochs cost a stock kernel,
/// whose ASIDs change seldom, refills of its global entries in each; auto
/// passed P9.3's F gate: the androidish kernel's boot to a login 30% faster,
/// the stock kernel's runs as with 0)
pub static mut ASID_TAG_MODE: u32 = 2;

// ---- the switch registry: the x86 core's interface (src/rust/jit_switches.rs,
// src/jit_switches.js), so the V86 option jit_switches and tests' JIT_SWITCHES
// set them by name

struct Switch {
    name: &'static str,
    default: u32,
    get: fn() -> u32,
    /// false: the value is refused
    set: fn(u32) -> bool,
}
const UNSET: u32 = u32::MAX;
const SWITCHES: [Switch; 13] = [
    Switch {
        name: "a64_page",
        default: 0,
        get: || unsafe { pages::ENABLED as u32 },
        set: |v| v <= 1 && unsafe { pages::ENABLED = v != 0 } == (),
    },
    Switch {
        name: "a64_page_hot",
        default: 2000,
        get: || unsafe { pages::HOT },
        set: |v| v >= 1 && unsafe { pages::HOT = v } == (),
    },
    Switch {
        name: "a64_neon",
        default: 1,
        get: || unsafe { NEON as u32 },
        set: |v| v <= 1 && unsafe { NEON = v != 0 } == (),
    },
    Switch {
        name: "a64_helpers",
        default: 1,
        get: || unsafe { HELPERS as u32 },
        set: |v| v <= 1 && unsafe { HELPERS = v != 0 } == (),
    },
    Switch {
        name: "a64_system",
        default: pagegen::SYSTEM_ALL,
        get: || unsafe { SYSTEM },
        set: |v| v <= pagegen::SYSTEM_ALL && unsafe { SYSTEM = v } == (),
    },
    Switch {
        name: "a64_relaxed_fma",
        default: 0,
        get: || unsafe { RELAXED_FMA as u32 },
        // (on only where the host fuses them)
        set: |v| {
            v <= 1 && (v == 0 || unsafe { FMA_FUSED }) && unsafe { RELAXED_FMA = v != 0 } == ()
        },
    },
    Switch {
        name: "a64_page_code_mb",
        default: 160,
        get: || unsafe { pages::CODE_BUDGET_MB },
        set: |v| v >= 8 && unsafe { pages::CODE_BUDGET_MB = v } == (),
    },
    Switch {
        name: "a64_page_aarch32",
        default: 1,
        get: || unsafe { pages::AARCH32 as u32 },
        set: |v| {
            v < 1 << 12
                && unsafe {
                    pages::AARCH32 = v != 0;
                    pages::AARCH32_DEBUG = v
                } == ()
        },
    },
    Switch {
        name: "a64_page_aarch32_filter",
        default: 0,
        get: || unsafe { pages::AARCH32_FILTER },
        set: |v| v < 32 << 16 && unsafe { pages::AARCH32_FILTER = v } == (),
    },
    Switch {
        name: "a64_page_aarch32_trace",
        default: 0,
        get: || unsafe { pages::A32_TRACE as u32 },
        set: |v| v <= 1 && unsafe { pages::A32_TRACE = v != 0 } == (),
    },
    Switch {
        name: "a64_reserved_fill",
        default: 0,
        get: || unsafe { pages::RESERVED_FILL_REFUSED as u32 },
        set: |v| v <= 1 && unsafe { pages::RESERVED_FILL_REFUSED = v != 0 } == (),
    },
    Switch {
        name: "a64_step_stats",
        default: 1,
        get: || unsafe { pages::STEP_STATS as u32 },
        set: |v| v <= 1 && unsafe { pages::STEP_STATS = v != 0 } == (),
    },
    Switch {
        name: "a64_asid_tag",
        default: 2,
        get: || unsafe { ASID_TAG_MODE },
        set: |v| v <= 2 && unsafe { ASID_TAG_MODE = v } == () && pages::set_asid_tag(v == 1) == (),
    },
];
static mut EXPLICIT: [u32; SWITCHES.len()] = [UNSET; SWITCHES.len()];
static mut NAMES: Option<String> = None;

#[no_mangle]
pub fn jit_switch_count() -> u32 { SWITCHES.len() as u32 }
#[no_mangle]
pub fn jit_switch(id: u32) -> u32 { SWITCHES.get(id as usize).map_or(UNSET, |s| (s.get)()) }
#[no_mangle]
pub fn jit_set_switch(id: u32, value: u32) -> bool {
    let Some(s) = SWITCHES.get(id as usize)
    else {
        return false;
    };
    if value == UNSET || !(s.set)(value) {
        return false;
    }
    unsafe { EXPLICIT[id as usize] = value };
    true
}
#[no_mangle]
pub fn jit_switch_explicit(id: u32) -> u32 {
    unsafe {
        (*(&raw const EXPLICIT))
            .get(id as usize)
            .copied()
            .unwrap_or(UNSET)
    }
}
/// The address of a text: 0, the switches ("name default\n" by id); 1, the
/// build-time defaults (none in the ARM core)
#[no_mangle]
pub fn jit_switch_text(which: u32) -> u32 { text(which).as_ptr() as u32 }
#[no_mangle]
pub fn jit_switch_text_length(which: u32) -> u32 { text(which).len() as u32 }
fn text(which: u32) -> &'static str {
    if which == 1 {
        return "";
    }
    unsafe {
        (*(&raw mut NAMES)).get_or_insert_with(|| {
            SWITCHES
                .iter()
                .map(|s| format!("{} {}\n", s.name, s.default))
                .collect()
        })
    }
}

/// The page tier's functions return the instructions they retired (the
/// table's Fn1Ret: called by index)
#[no_mangle]
pub fn call_indirect1_ret(f: fn(u16) -> i32, x: u16) -> i32 { f(x) }
                                                                                                                                                                                              source/v64/src/rust/aarch64/jit/pagegen.rs                                                          0000644 0000000 0000000 00000314103 00000000000 015444  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The A64 page tier's code generator (docs/jit-unification-plan.md P6.3,
//! J2): one Wasm function per 4 KiB page of A64 code, built in the neutral
//! skeleton crate::pagegen::frame (the frame, the structured layout of the
//! block graph, the page dispatch, the access cache's lookups, chaining).
//!
//! The function serves the page's block starts (the interpreter's block
//! boundaries the runtime saw, and the static targets and fall-throughs
//! found from them). X0-X30, SP (of the EL the function was compiled for),
//! the PC and NZCV live in locals, loaded in the prologue and written back
//! at every way out and around single steps, so memory is authoritative
//! whenever Rust code runs. Templates cover integer v1 (P6.3): the
//! arithmetic, logical, move, bitfield, shift, multiply and divide forms,
//! conditional select and compare, every branch, and the loads and stores
//! of general registers (single, pair, literal, acquire/release); NOPs and
//! barriers. Everything else is a single step (jitrt::step: the
//! interpreter, crate::aarch64::jit::pages::a64_page_step), and so is a
//! template whose precondition fails at run time (an access the cache
//! does not serve, a misaligned SP or acquire/release address, a tagged
//! branch target): the function leaves with the PC at the instruction and
//! none of its effects (EXIT_RETRY).
//!
//! NZCV is kept in its local as the interpreter keeps it (bits 31:28),
//! computed by every flag-setting template.
//!
//! In the parallel build (cores in workers, P8.2) guest memory accesses are
//! sequentially consistent atomics (the frame refuses unaligned ones, which
//! retry in the interpreter), DMB and ISB a fence, and a DSB a single step
//! while cores run in workers (it waits for their TLB maintenance, P8.3),
//! with a64_system only when this core's maintenance is pending.

use crate::aarch64::cpu;
use crate::aarch64::decode::{
    self, Inst, Op, LS_LOAD, LS_PREFETCH, LS_SIGNED, LS_SIMD, LS_TO_W, LS_UNPRIVILEGED, MODE_POST,
    MODE_PRE, MODE_REGISTER,
};
use crate::aarch64::state;
use crate::jitrt::step::{StepAbi, EXIT_RETRY, EXIT_UNKNOWN};
use crate::pagegen::frame::{
    self, AccessAbi, ChainEpoch, DispatchKind, Frame, Level, LookupLocals, PageEmitter,
};
use crate::wasmgen::wasm_builder::{
    Label, Signature, WasmBuilder, WasmLocal, WasmLocalI64, WasmType,
};
use crate::wasmgen::wasm_opcodes as op;
use std::collections::{BTreeMap, BTreeSet};

mod a32;
mod neon;

const PAGE: u64 = 4096;
/// The sign-extension operators
const OP_I64EXTEND8S: u8 = 0xC2;
const OP_I64EXTEND16S: u8 = 0xC3;
const OP_I64EXTEND32S: u8 = 0xC4;

/// What the bytes depend on besides the page
#[derive(Clone, Copy)]
pub struct CompileEnv {
    /// the code runs at EL1 (else EL0): which SP, which access cache tables
    pub el1: bool,
    /// SP alignment is checked for SP-based accesses (SCTLR_EL1.SA or SA0)
    pub sp_checked: bool,
    /// leaving the page tail-calls the next page's function (jitrt::chain)
    pub chaining: bool,
    /// AdvSIMD templates (a64_neon; P6.3b)
    pub neon: bool,
    /// helper calls (a64_helpers)
    pub helpers: bool,
    /// the EL1 system templates (a64_system: SYSTEM_*)
    pub system: u32,
    /// the host's relaxed SIMD multiply-adds fuse (a64_relaxed_fma, probed by the host)
    pub relaxed_fma: bool,
    /// the page's instruction set: A64, or AArch32's at EL0 (pagegen::a32)
    pub isa: Isa,
}

/// The instruction sets of page functions
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Isa {
    A64,
    /// AArch32's (docs/aarch32-plan.md Q6): R0-R14 and NZCV stay in memory
    A32,
    T32,
}

/// A scalar FP form with a native template (P6.3b), from its word
#[derive(Clone, Copy, PartialEq, Eq)]
enum FpForm {
    /// FMUL, FDIV, FADD, FSUB (0-3), FNMUL (8): admitted on the fast path's conditions
    Arithmetic { op: u8, negate: bool },
    /// FMADD, FMSUB, FNMADD, FNMSUB: o1 negates the addend, o0 the product
    MultiplyAdd {
        negate_addend: bool,
        negate_product: bool,
    },
    /// FMOV, FABS, FNEG (register): bit operations, never an exception
    Move(u8),
    /// FCMP, FCMPE (with zero: `zero`): NZCV, when neither operand is a NaN
    Compare { zero: bool },
}
/// The native scalar FP template of `word` (S and D only), if any
fn fp_form(i: &Inst, env: &CompileEnv) -> Option<FpForm> {
    if !env.neon {
        return None;
    }
    let word = i.imm as u32;
    let ptype = word >> 22 & 3;
    if ptype > 1 || word >> 29 & 7 != 0 {
        return None;
    }
    match i.op {
        Op::FpDp2 => match word >> 12 & 15 {
            op @ 0..=3 => Some(FpForm::Arithmetic {
                op: op as u8,
                negate: false,
            }),
            8 => Some(FpForm::Arithmetic {
                op: 0,
                negate: true,
            }),
            _ => None,
        },
        // (relaxed SIMD: a core built with simd128 only)
        Op::FpDp3 if env.relaxed_fma && cfg!(target_feature = "simd128") => {
            Some(FpForm::MultiplyAdd {
                negate_addend: word >> 21 & 1 != 0,
                negate_product: (word >> 21 & 1) != (word >> 15 & 1),
            })
        },
        Op::FpDp1 => match word >> 15 & 63 {
            op @ 0..=2 => Some(FpForm::Move(op as u8)),
            _ => None,
        },
        Op::FpCompare if word >> 14 & 3 == 0 && word & 7 == 0 => Some(FpForm::Compare {
            zero: word >> 3 & 1 != 0,
        }),
        _ => None,
    }
}

pub struct Compiled {
    pub bytes: Vec<u8>,
    /// block starts served: a bitmap of offsets
    pub served: Vec<u64>,
    pub instructions: u32,
    pub templated: u32,
}

// ---- discovery

#[derive(Clone, Copy, PartialEq, Eq)]
enum End {
    /// the next instruction, at this offset (4096: the next page)
    Next(u16),
    /// the instruction at this offset is stepped
    StepAt(u16),
    /// the last instruction transferred control itself
    Stop,
}
struct Block {
    start: u16,
    insts: Vec<(u16, Inst)>,
    /// AArch32's instructions (pagegen::a32), in place of `insts`
    insts32: Vec<(u16, a32::Inst32)>,
    end: End,
}
impl Block {
    /// the instructions it runs natively or by helpers
    fn count(&self) -> usize { self.insts.len() + self.insts32.len() }
}

/// How an instruction ends a block: not (None), or with its targets in the
/// page and whether it falls through
fn control(i: &Inst, offset: u16) -> Option<(Vec<u64>, bool)> {
    let relative = |imm: u64| (offset as u64).wrapping_add(imm);
    match i.op {
        Op::Branch => Some((
            if i.sub == 1 {
                vec![relative(i.imm), offset as u64 + 4]
            }
            else {
                vec![relative(i.imm)]
            },
            false,
        )),
        Op::BCond | Op::CompareBranch | Op::TestBranch => Some((vec![relative(i.imm)], true)),
        // (a call's return lands after it)
        Op::BranchReg => Some((
            if i.sub == 1 { vec![offset as u64 + 4] } else { vec![] },
            false,
        )),
        _ => None,
    }
}

/// Whether the instruction has a template (native or a helper; else it is stepped)
fn templated(i: &Inst, env: &CompileEnv) -> bool { native(i, env) || helper(i, env).is_some() }

/// What a helper call (crate::aarch64::jit::pages::a64_page_helper) syncs:
/// the general registers it may read or write (stored before, loaded after:
/// their state copies must be current), and whether NZCV
struct HelperSync {
    gprs: Vec<u8>,
    nzcv: bool,
}
/// Whether the instruction runs as a helper call: the interpreter's execute
/// on the state in memory, for forms that never transfer control nor change
/// what compiled code depends on (the translation regime, the access cache,
/// the EL; those step): the scalar FP, AdvSIMD and crypto forms (P6.3b: the
/// crypto helpers of P2.11, not steps), the SIMD&FP loads and stores, CRC32,
/// RBIT, the exclusives, CLREX, MRS, the unprivileged loads and stores
fn helper(i: &Inst, env: &CompileEnv) -> Option<HelperSync> {
    if !env.helpers {
        return None;
    }
    let fields = |word: u32| {
        vec![
            (word & 31) as u8,
            (word >> 5 & 31) as u8,
            (word >> 16 & 31) as u8,
        ]
    };
    let named = |i: &Inst| vec![i.rd, i.rn, i.rm, i.ra];
    let sync = |gprs: Vec<u8>, nzcv: bool| Some(HelperSync { gprs, nzcv });
    let word = i.imm as u32;
    match i.op {
        // (V registers, FPCR and FPSR only)
        Op::FpDp1
        | Op::FpDp2
        | Op::FpDp3
        | Op::FpImm
        | Op::SimdThreeSame
        | Op::SimdThreeDiff
        | Op::SimdTwoMisc
        | Op::SimdAcross
        | Op::SimdPairwise
        | Op::SimdModImm
        | Op::SimdShiftImm
        | Op::SimdIndexed
        | Op::SimdTable
        | Op::SimdPermute
        | Op::SimdExtract
        | Op::CryptoAes
        | Op::CryptoSha3
        | Op::CryptoSha2 => sync(vec![], false),
        // (general registers too: DUP, INS, UMOV, SMOV; FMOV, conversions)
        Op::SimdCopy | Op::FpInt | Op::FpFixed => sync(fields(word), false),
        Op::FpCompare | Op::FpCondCompare | Op::FpCondSelect => sync(vec![], true),
        // (the base and a post-index register)
        Op::SimdStructure => sync(fields(word), false),
        Op::LoadStore
            if !native_simd(i, env)
                && (i.sub & LS_SIMD != 0 || i.sub & LS_UNPRIVILEGED != 0 && env.el1) =>
        {
            sync(named(i), false)
        },
        Op::LoadStorePair if i.sub & LS_SIMD != 0 && !native_simd(i, env) => sync(named(i), false),
        Op::LoadLiteral if i.sub >= 4 => sync(vec![], false),
        Op::DataProc2 if i.sub >= 0b010000 => sync(named(i), false),
        Op::DataProc1 if i.sub == 0 => sync(named(i), false),
        Op::Exclusive => sync(named(i), false),
        Op::Clrex => sync(vec![], false),
        Op::Mrs => sync(vec![i.rd], true),
        _ => None,
    }
}

/// Whether the instruction has a native template
fn native(i: &Inst, env: &CompileEnv) -> bool {
    if fp_form(i, env).is_some() || neon::form(i, env).is_some() {
        return true;
    }
    match i.op {
        Op::Adr
        | Op::Adrp
        | Op::AddSubImm
        | Op::LogicalImm
        | Op::MoveWide
        | Op::Bitfield
        | Op::Extr
        | Op::BCond
        | Op::CompareBranch
        | Op::TestBranch
        | Op::LogicalShifted
        | Op::AddSubShifted
        | Op::AddSubExtended
        | Op::AddSubCarry
        | Op::CondCompare
        | Op::CondSelect => true,
        Op::Branch => true,
        // BR, BLR, RET (not the pointer authentication forms, nor ERET, DRPS)
        Op::BranchReg => i.sub <= 2,
        Op::DataProc3 => matches!(i.sub, 0..=4 | 10 | 11 | 12),
        // UDIV, SDIV, LSLV, LSRV, ASRV, RORV (CRC32: stepped)
        Op::DataProc2 => matches!(i.sub, 0b000010 | 0b000011 | 0b001000..=0b001011),
        // RBIT, REV16, REV32, REV, CLZ, CLS
        Op::DataProc1 => matches!(i.sub, 0..=5),
        // NOP and the hints that are NOPs here (YIELD, WFE, WFI, SEV, SEVL step)
        Op::Hint => !(1..=5).contains(&i.imm),
        // (DSB with cores in workers: a step, crate::aarch64::tlb::synced;
        // with a64_system only when this core's maintenance is pending)
        Op::Barrier => !(i.sub == 0 && crate::parallel::active()) || env.system & SYSTEM_DSB != 0,
        // (and the SIMD&FP registers' S, D and Q forms: native_simd)
        // (LDTR, STTR at EL1 through EL0's access cache tables with a64_system)
        Op::LoadStore => {
            i.sub & LS_SIMD == 0
                && (i.sub & LS_UNPRIVILEGED == 0
                    || !env.el1
                    || env.system & SYSTEM_UNPRIVILEGED != 0)
                || native_simd(i, env)
        },
        Op::LoadStorePair => i.sub & LS_SIMD == 0 || native_simd(i, env),
        Op::LoadLiteral => i.sub <= 3,
        Op::LoadAcquireStoreRelease => true,
        Op::Mrs | Op::Msr => {
            i.imm as u32 == TPIDR_EL0
                || i.imm as u32 == NZCV_KEY
                || system_register(i, env).is_some()
        },
        // MSR DAIFSet, DAIFClr at EL1 (a64_system)
        Op::MsrImm => env.system & SYSTEM_REGISTERS != 0 && env.el1 && (i.sub == 1 || i.sub == 2),
        // TLBI at EL1, DC ZVA at EL1 and EL0 (a64_system; at EL0 it checks
        // SCTLR_EL1.DZE as it runs: bionic's memset zeroes with it)
        Op::Sys => {
            i.sub == 0
                && (env.el1 && env.system & SYSTEM_TLBI != 0 && tlbi_form(i.imm as u32)
                    || env.system & SYSTEM_DC_ZVA != 0 && i.imm as u32 == DC_ZVA)
        },
        _ => false,
    }
}

/// a64_system's templates: the system registers and PSTATE.DAIF, TLBI, DC
/// ZVA, LDTR and STTR, DSB (with cores in workers)
pub const SYSTEM_REGISTERS: u32 = 1;
pub const SYSTEM_TLBI: u32 = 2;
pub const SYSTEM_DC_ZVA: u32 = 4;
pub const SYSTEM_UNPRIVILEGED: u32 = 8;
pub const SYSTEM_DSB: u32 = 16;
pub const SYSTEM_ALL: u32 = 31;

/// SYS's DC ZVA (op1:CRn:CRm:op2)
const DC_ZVA: u32 = 3 << 11 | 7 << 7 | 4 << 3 | 1;
/// A TLBI the interpreter does (sysregs::sys): op1 0, CRn 8, CRm 3 (inner
/// shareable) or 7, op2 VMALLE1, VAE1, ASIDE1, VAAE1, VALE1, VAALE1
fn tlbi_form(op: u32) -> bool {
    op >> 11 == 0
        && op >> 7 & 15 == 8
        && matches!(op >> 3 & 15, 3 | 7)
        && matches!(op & 7, 0..=3 | 5 | 7)
}

/// The system registers whose MRS and MSR (register) have EL1 templates
/// (a64_system): plain state, or PSTATE's bits
#[derive(Clone, Copy, PartialEq, Eq)]
enum SystemRegister {
    /// SP_EL0: Linux's `current`; at EL1t the SP itself (an MSR there is UNDEFINED: retried)
    SpEl0,
    Tpidr1,
    Daif,
    Elr,
    /// SPSR_EL1 (MSR: the bits the profile keeps)
    Spsr,
    /// ESR_EL1 (MSR: the low 32 bits)
    Esr,
    Far,
    /// DCZID_EL0: BS 4, DZP set at EL0 while SCTLR_EL1.DZE is clear
    Dczid,
    /// CNTVCT_EL0 (EL0: CNTKCTL_EL1 bit 1) or CNTPCT_EL0 (bit 0), read: the counter
    Counter(u64),
    /// CNTFRQ_EL0, read (EL0: CNTKCTL_EL1 bit 0 or 1)
    Cntfrq,
    /// TPIDRRO_EL0 (MSR at EL1 only)
    TpidrRo,
    /// CONTEXTIDR_EL1 (MSR: the low 32 bits)
    Contextidr,
    /// FPCR and FPSR (as FP instructions, CPACR_EL1.FPEN as it runs; MSR:
    /// the writable bits; compiled FP code reads them as it runs)
    Fpcr,
    Fpsr,
}
fn system_register(i: &Inst, env: &CompileEnv) -> Option<SystemRegister> {
    use crate::aarch64::sysregs::key;
    if env.system & SYSTEM_REGISTERS == 0 {
        return None;
    }
    let reg = i.imm as u32;
    let write = i.op == Op::Msr;
    // (at EL0 too, its checks made as the template runs: the counter that
    // Android's clock_gettime reads in the vDSO, TPIDRRO_EL0, FPCR and FPSR)
    let any_el = match reg {
        r if r == key(3, 3, 14, 0, 2) && !write => Some(SystemRegister::Counter(2)),
        r if r == key(3, 3, 14, 0, 1) && !write => Some(SystemRegister::Counter(1)),
        r if r == key(3, 3, 14, 0, 0) && !write => Some(SystemRegister::Cntfrq),
        r if r == key(3, 3, 0, 0, 7) && !write => Some(SystemRegister::Dczid),
        r if r == key(3, 3, 13, 0, 3) && (!write || env.el1) => Some(SystemRegister::TpidrRo),
        r if r == key(3, 3, 4, 4, 0) => Some(SystemRegister::Fpcr),
        r if r == key(3, 3, 4, 4, 1) => Some(SystemRegister::Fpsr),
        _ => None,
    };
    if any_el.is_some() || !env.el1 {
        return any_el;
    }
    Some(match reg {
        r if r == key(3, 0, 4, 1, 0) => SystemRegister::SpEl0,
        r if r == key(3, 0, 13, 0, 4) => SystemRegister::Tpidr1,
        r if r == key(3, 3, 4, 2, 1) => SystemRegister::Daif,
        r if r == key(3, 0, 4, 0, 1) => SystemRegister::Elr,
        r if r == key(3, 0, 4, 0, 0) => SystemRegister::Spsr,
        r if r == key(3, 0, 5, 2, 0) => SystemRegister::Esr,
        r if r == key(3, 0, 6, 0, 0) => SystemRegister::Far,
        r if r == key(3, 0, 13, 0, 1) => SystemRegister::Contextidr,
        _ => return None,
    })
}
/// A SIMD&FP load or store of an S, D or Q register (single or pair, not a
/// prefetch) with the native template (a64_neon)
fn native_simd(i: &Inst, env: &CompileEnv) -> bool {
    env.neon && i.sub & LS_SIMD != 0 && i.sub & LS_PREFETCH == 0 && (2..=4).contains(&i.cond)
}

/// The system register keys of the MRS/MSR templates (sysregs::key)
const TPIDR_EL0: u32 = 3 << 14 | 3 << 11 | 13 << 7 | 0 << 3 | 2;
const NZCV_KEY: u32 = 3 << 14 | 3 << 11 | 4 << 7 | 2 << 3 | 0;

fn discover(
    words: &[u32],
    entries: &[u16],
    env: &CompileEnv,
) -> (Vec<Block>, BTreeMap<u16, usize>) {
    let mut starts: BTreeSet<u16> = entries.iter().copied().filter(|&o| o % 4 == 0).collect();
    let mut queue: Vec<u16> = starts.iter().copied().collect();
    let mut decoded: BTreeSet<u16> = BTreeSet::new();
    let add = |o: u64, starts: &mut BTreeSet<u16>, queue: &mut Vec<u16>| {
        if o < PAGE && o % 4 == 0 && starts.insert(o as u16) {
            queue.push(o as u16);
        }
    };
    while let Some(start) = queue.pop() {
        let mut o = start;
        loop {
            if !decoded.insert(o) {
                break;
            }
            let i = decode::decode(words[o as usize / 4]);
            if let Some((targets, falls)) = control(&i, o).filter(|_| templated(&i, env)) {
                for t in targets {
                    add(t, &mut starts, &mut queue);
                }
                if falls {
                    add(o as u64 + 4, &mut starts, &mut queue);
                }
                break;
            }
            if !templated(&i, env) {
                // (a step continues at the PC it leaves: usually the next instruction)
                add(o as u64 + 4, &mut starts, &mut queue);
                break;
            }
            o += 4;
            if o as u64 >= PAGE || starts.contains(&o) {
                break;
            }
        }
    }
    let mut blocks = Vec::new();
    let mut index = BTreeMap::new();
    for &start in &starts {
        let mut insts = Vec::new();
        let mut o = start;
        let end = loop {
            let i = decode::decode(words[o as usize / 4]);
            if !templated(&i, env) {
                break End::StepAt(o);
            }
            insts.push((o, i));
            if let Some((_, falls)) = control(&i, o) {
                break if falls { End::Next(o + 4) } else { End::Stop };
            }
            o += 4;
            if o as u64 >= PAGE {
                break End::Next(PAGE as u16);
            }
            if starts.contains(&o) {
                break End::Next(o);
            }
        };
        index.insert(start, blocks.len());
        blocks.push(Block {
            start,
            insts,
            insts32: Vec::new(),
            end,
        });
    }
    (blocks, index)
}

/// The static successors of each block in the page (pagegen::frame::structured)
fn successors(blocks: &[Block], index: &BTreeMap<u16, usize>) -> Vec<Vec<u32>> {
    blocks
        .iter()
        .map(|b| {
            let mut out = vec![];
            let mut to = |o: u64| {
                if o < PAGE {
                    if let Some(&k) = index.get(&(o as u16)) {
                        out.push(k as u32);
                    }
                }
            };
            if let Some(&(o, i)) = b.insts.last() {
                if let Some((targets, _)) = control(&i, o) {
                    if !matches!(i.op, Op::Branch if i.sub == 1) {
                        for t in targets {
                            to(t);
                        }
                    }
                    else {
                        to((o as u64).wrapping_add(i.imm));
                    }
                }
            }
            if let Some((o, i)) = b.insts32.last() {
                for t in a32::targets(i, *o) {
                    to(t);
                }
            }
            if let End::Next(o) = b.end {
                to(o as u64);
            }
            out
        })
        .collect()
}

// ---- the emitter

// i64 locals: X0-X30, SP (31), then
const PC: usize = 32;
const BASE: usize = 33;
const ADDR: usize = 34;
const EP: usize = 35;
const TAG: usize = 36;
const T0: usize = 37;
const T1: usize = 38;
const T2: usize = 39;
const T3: usize = 40;
const T4: usize = 41;
/// a store's value (store_any)
const SV: usize = 42;
const LOCALS64: usize = 43;
// i32 locals
const N: usize = 0;
const K: usize = 1;
const NZCV: usize = 2;
const JAC: usize = 3;
const ENT: usize = 4;
const OFF: usize = 5;
const HH: usize = 6;
const ST: usize = 7;
const C0: usize = 8;
const C1: usize = 9;
/// the access cache's EL0 tables, for LDTR and STTR at EL1
const J0: usize = 10;
/// AArch32's operands and results (pagegen::a32)
const A0: usize = 11;
const A1: usize = 12;
const A2: usize = 13;
/// a store's host address (store_any)
const SH: usize = 14;
const LOCALS32: usize = 15;

struct Emitter<'a> {
    b: WasmBuilder,
    v: Vec<WasmLocalI64>,
    w: Vec<WasmLocal>,
    budget: WasmLocal,
    frame: Option<Frame>,
    levels: Vec<Level>,
    blocks: &'a [Block],
    env: CompileEnv,
    access: Option<u32>,
    step: StepAbi,
    /// the page's instruction words (helpers take theirs)
    words: Vec<u32>,
}

/// The state block's fields generated code reads and writes
fn x_address(n: usize) -> u32 { state::x as u32 + 8 * n as u32 }

/// (debugging, pages::a32_trace_dump) AArch32 discovery's blocks over the
/// offsets [from, to): each one's start, instructions' kinds and end
pub fn describe_a32(bytes: &[u8], entries: &[u16], env: CompileEnv, from: u16, to: u16) -> String {
    let (blocks, _) = a32::discover(bytes, entries, &env);
    let mut out = String::new();
    for b in &blocks {
        let last = b
            .insts32
            .last()
            .map_or(b.start, |&(o, i)| o + i.length as u16);
        if last < from || b.start >= to {
            continue;
        }
        out += &format!("block {:x}:", b.start);
        for (o, i) in &b.insts32 {
            out += &format!(" {:x}={}", o, a32::kind_name(&i.kind));
        }
        out += &match b.end {
            End::Stop => " stop".to_string(),
            End::StepAt(o) => format!(" step@{:x}", o),
            End::Next(o) => format!(" next@{:x}", o),
        };
        out += "\n";
    }
    out
}

pub fn compile(bytes: &[u8], entries: &[u16], env: CompileEnv, name: String) -> Option<Compiled> {
    let words: Vec<u32> = bytes
        .chunks_exact(4)
        .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
        .collect();
    let (blocks, index) = if env.isa == Isa::A64 {
        discover(&words, entries, &env)
    }
    else {
        a32::discover(bytes, entries, &env)
    };
    if blocks.is_empty() {
        return None;
    }
    let instructions = blocks
        .iter()
        .map(|b| b.count() as u32 + matches!(b.end, End::StepAt(_)) as u32)
        .sum();
    let templated = blocks.iter().map(|b| b.count() as u32).sum();
    let mut served = vec![0u64; 64];
    for &o in index.keys() {
        served[o as usize / 64] |= 1 << (o % 64);
    }
    let mut b = WasmBuilder::new();
    b.set_entry_result();
    b.set_function_name(name);
    let budget = b.arg_local_initial_state.unsafe_clone();
    let v = (0..LOCALS64)
        .map(|_| b.declare_zeroed_local_i64())
        .collect();
    let w = (0..LOCALS32).map(|_| b.declare_zeroed_local()).collect();
    let mut e = Emitter {
        b,
        v,
        w,
        budget,
        frame: None,
        levels: Vec::new(),
        blocks: &blocks,
        env,
        access: None,
        step: StepAbi {
            exit_code: state::a64_page_exit as u32,
        },
        words: words.clone(),
    };
    e.prologue();
    let start = |k: u32| blocks[k as usize].start as usize;
    let units = frame::structured(&successors(&blocks, &index), &start, true);
    e.page(&units, blocks.len(), &index, DispatchKind::Buckets);
    let Emitter {
        mut b,
        v,
        w,
        budget,
        ..
    } = e;
    for l in v {
        b.free_local_i64(l);
    }
    for l in w {
        b.free_local(l);
    }
    std::mem::forget(budget);
    b.finish();
    Some(Compiled {
        bytes: b.output().to_vec(),
        served,
        instructions,
        templated,
    })
}

impl Emitter<'_> {
    fn g(&mut self, i: usize) { self.b.get_local_i64(&self.v[i]) }
    fn s(&mut self, i: usize) { self.b.set_local_i64(&self.v[i]) }
    fn gi(&mut self, i: usize) { self.b.get_local(&self.w[i]) }
    fn si(&mut self, i: usize) { self.b.set_local(&self.w[i]) }
    fn ti(&mut self, i: usize) { self.b.tee_local(&self.w[i]) }
    fn c64(&mut self, v: u64) { self.b.const_i64(v as i64) }
    fn c32(&mut self, v: i32) { self.b.const_i32(v) }
    fn o(&mut self, opcode: u8) { self.b.op(opcode) }
    fn f(&self) -> Frame { self.frame.unwrap() }

    fn load64(&mut self, address: u32) {
        self.c32(address as i32);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
    }
    fn load32(&mut self, address: u32) {
        self.c32(address as i32);
        self.b.memory_op(op::OP_I32LOAD, op::MEM_ALIGN32, 0);
    }
    /// (the value pushed after) a store to `address`: push the address first
    fn store64_at(&mut self, address: u32, local: usize) {
        self.c32(address as i32);
        self.g(local);
        self.b.memory_op(op::OP_I64STORE, op::MEM_ALIGN64, 0);
    }

    /// The registers, the PC and NZCV into their locals; the access cache's
    /// epoch and table base
    fn prologue(&mut self) {
        self.load_registers();
        self.load64(state::a64_page_linear as u32);
        self.s(BASE);
    }
    fn load_registers(&mut self) {
        // (AArch32's registers and NZCV stay in memory: pagegen::a32)
        let a64 = self.env.isa == Isa::A64;
        if a64 {
            for i in 0..32 {
                self.load64(x_address(i));
                self.s(i);
            }
        }
        self.load64(state::pc as u32);
        self.s(PC);
        if a64 {
            self.load32(state::nzcv as u32);
            self.si(NZCV);
        }
        self.load64(state::a64_jac_epoch as u32);
        self.s(EP);
        self.load32(state::a64_jac_base as u32);
        self.si(JAC);
    }
    fn writeback(&mut self) {
        if self.env.isa != Isa::A64 {
            self.store64_at(state::pc as u32, PC);
            return;
        }
        for i in 0..32 {
            self.store64_at(x_address(i), i);
        }
        self.store64_at(state::pc as u32, PC);
        self.c32(state::nzcv as i32);
        self.gi(NZCV);
        self.b.store_aligned_i32(0);
    }
    fn set_exit(&mut self, code: u32) {
        self.c32(self.step.exit_code as i32);
        self.c32(code as i32);
        self.b.store_aligned_i32(0);
    }
    /// Push N + K (the instructions retired natively and stepped)
    fn n_and_steps(&mut self) {
        self.gi(N);
        self.gi(K);
        self.b.add_i32();
    }
    /// Push the absolute address of offset `offset` of the page
    fn linear(&mut self, offset: u64) {
        self.g(BASE);
        if offset != 0 {
            self.c64(offset);
            self.b.add_i64();
        }
    }

    // ---- operands

    /// Push X[n] (register 31: the zero register), 64-bit
    fn xr(&mut self, n: u8) {
        if n == 31 {
            self.c64(0)
        }
        else {
            self.g(n as usize)
        }
    }
    /// Push X[n] with register 31 as SP
    fn xr_sp(&mut self, n: u8) { self.g(n as usize) }
    /// Pop into X[n] (register 31: discarded)
    fn set_x(&mut self, n: u8) {
        if n == 31 {
            self.b.drop_()
        }
        else {
            self.s(n as usize)
        }
    }
    /// Pop into X[n] with register 31 as SP
    fn set_x_sp(&mut self, n: u8) { self.s(n as usize) }
    /// Pop a result of width `sf` into the register: a 32-bit one zero-extended
    fn set_xw(&mut self, n: u8, sf: bool, sp: bool) {
        if !sf {
            self.c64(0xFFFF_FFFF);
            self.b.and_i64();
        }
        if sp {
            self.set_x_sp(n)
        }
        else {
            self.set_x(n)
        }
    }
    /// The shifted register operand (LSL, LSR, ASR, ROR) of width `sf`, as an i64
    fn shifted(&mut self, rm: u8, kind: u8, amount: u8, sf: bool) {
        self.xr(rm);
        if amount == 0 {
            return;
        }
        if sf {
            self.c64(amount as u64);
            match kind {
                0 => self.b.shl_i64(),
                1 => self.b.shr_u_i64(),
                2 => self.b.shr_s_i64(),
                _ => self.b.rotr_i64(),
            }
        }
        else {
            self.b.wrap_i64_to_i32();
            self.c32(amount as i32);
            match kind {
                0 => self.b.shl_i32(),
                1 => self.b.shr_u_i32(),
                2 => self.b.shr_s_i32(),
                _ => self.b.rotr_i32(),
            }
            self.b.extend_unsigned_i32_to_i64();
        }
    }
    /// The extended register operand (UXTB..SXTX, shifted left), as an i64
    fn extended(&mut self, rm: u8, option: u8, amount: u8) {
        self.xr(rm);
        match option {
            0 => {
                self.c64(0xFF);
                self.b.and_i64();
            },
            1 => {
                self.c64(0xFFFF);
                self.b.and_i64();
            },
            2 => {
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
            },
            4 => self.o(OP_I64EXTEND8S),
            5 => self.o(OP_I64EXTEND16S),
            6 => self.o(OP_I64EXTEND32S),
            _ => {},
        }
        if amount != 0 {
            self.c64(amount as u64);
            self.b.shl_i64();
        }
    }

    // ---- flags

    /// NZCV from T0 (x), T1 (the second operand, inverted for a subtraction
    /// with carry, see add_flags) and T2 (the result) of an addition (`sub`
    /// false) or subtraction of width `sf` without carry in
    fn arith_flags(&mut self, sub: bool, sf: bool) {
        if sf {
            // N, Z
            self.g(T2);
            self.c64(32);
            self.b.shr_u_i64();
            self.b.wrap_i64_to_i32();
            self.c32(0x8000_0000u32 as i32);
            self.b.and_i32();
            self.g(T2);
            self.o(op::OP_I64EQZ);
            self.c32(30);
            self.b.shl_i32();
            self.b.or_i32();
            // C: no borrow (x >= y), or the sum wrapped (result < x)
            if sub {
                self.g(T0);
                self.g(T1);
                self.o(op::OP_I64GEU);
            }
            else {
                self.g(T2);
                self.g(T0);
                self.o(op::OP_I64LTU);
            }
            self.c32(29);
            self.b.shl_i32();
            self.b.or_i32();
            // V: ((x ^ y) & (x ^ r)) for a subtraction, ((x ^ r) & (y ^ r)) for an addition
            if sub {
                self.g(T0);
                self.g(T1);
                self.b.xor_i64();
                self.g(T0);
                self.g(T2);
                self.b.xor_i64();
            }
            else {
                self.g(T0);
                self.g(T2);
                self.b.xor_i64();
                self.g(T1);
                self.g(T2);
                self.b.xor_i64();
            }
            self.b.and_i64();
            self.c64(63);
            self.b.shr_u_i64();
            self.b.wrap_i64_to_i32();
            self.c32(28);
            self.b.shl_i32();
            self.b.or_i32();
        }
        else {
            // (32-bit: the low halves; T2 holds the 32-bit result zero-extended)
            self.g(T2);
            self.b.wrap_i64_to_i32();
            self.ti(C0);
            self.c32(0x8000_0000u32 as i32);
            self.b.and_i32();
            self.gi(C0);
            self.b.eqz_i32();
            self.c32(30);
            self.b.shl_i32();
            self.b.or_i32();
            if sub {
                self.g(T0);
                self.b.wrap_i64_to_i32();
                self.g(T1);
                self.b.wrap_i64_to_i32();
                self.o(op::OP_I32GEU);
            }
            else {
                self.gi(C0);
                self.g(T0);
                self.b.wrap_i64_to_i32();
                self.o(op::OP_I32LTU);
            }
            self.c32(29);
            self.b.shl_i32();
            self.b.or_i32();
            if sub {
                self.g(T0);
                self.g(T1);
                self.b.xor_i64();
                self.g(T0);
                self.g(T2);
                self.b.xor_i64();
            }
            else {
                self.g(T0);
                self.g(T2);
                self.b.xor_i64();
                self.g(T1);
                self.g(T2);
                self.b.xor_i64();
            }
            self.b.and_i64();
            self.b.wrap_i64_to_i32();
            self.c32(31);
            self.b.shr_u_i32();
            self.c32(28);
            self.b.shl_i32();
            self.b.or_i32();
        }
        self.si(NZCV);
    }
    /// x (T0) + y (T1) + carry (C1, 0 or 1) of width `sf` into T2, NZCV when
    /// `flags` (AddWithCarry: y is already inverted for a subtraction)
    fn add_with_carry(&mut self, sf: bool, flags: bool) {
        self.g(T0);
        self.g(T1);
        self.b.add_i64();
        self.gi(C1);
        self.b.extend_unsigned_i32_to_i64();
        self.b.add_i64();
        if !sf {
            self.c64(0xFFFF_FFFF);
            self.b.and_i64();
        }
        self.s(T2);
        if !flags {
            return;
        }
        // N, Z
        if sf {
            self.g(T2);
            self.c64(32);
            self.b.shr_u_i64();
            self.b.wrap_i64_to_i32();
        }
        else {
            self.g(T2);
            self.b.wrap_i64_to_i32();
        }
        self.c32(0x8000_0000u32 as i32);
        self.b.and_i32();
        self.g(T2);
        self.o(op::OP_I64EQZ);
        self.c32(30);
        self.b.shl_i32();
        self.b.or_i32();
        // C: carry out of x + y + c: r < x, or c and r == x (width sf)
        let (x_, r_) = (T0, T2);
        let cmp = |e: &mut Self, opcode: u8| {
            e.g(r_);
            if !sf {
                e.b.wrap_i64_to_i32();
            }
            e.g(x_);
            if !sf {
                e.b.wrap_i64_to_i32();
            }
            e.o(opcode);
        };
        cmp(self, if sf { op::OP_I64LTU } else { op::OP_I32LTU });
        cmp(self, if sf { op::OP_I64EQ } else { op::OP_I32EQ });
        self.gi(C1);
        self.b.and_i32();
        self.b.or_i32();
        self.c32(29);
        self.b.shl_i32();
        self.b.or_i32();
        // V: ((x ^ r) & (y ^ r)) sign
        self.g(T0);
        self.g(T2);
        self.b.xor_i64();
        self.g(T1);
        self.g(T2);
        self.b.xor_i64();
        self.b.and_i64();
        self.c64(if sf { 63 } else { 31 });
        self.b.shr_u_i64();
        self.b.wrap_i64_to_i32();
        self.c32(1);
        self.b.and_i32();
        self.c32(28);
        self.b.shl_i32();
        self.b.or_i32();
        self.si(NZCV);
    }
    /// NZCV of a logical result in T2 (width sf): N, Z; C and V clear
    fn logic_flags(&mut self, sf: bool) {
        if sf {
            self.g(T2);
            self.c64(32);
            self.b.shr_u_i64();
            self.b.wrap_i64_to_i32();
        }
        else {
            self.g(T2);
            self.b.wrap_i64_to_i32();
        }
        self.c32(0x8000_0000u32 as i32);
        self.b.and_i32();
        self.g(T2);
        if !sf {
            self.c64(0xFFFF_FFFF);
            self.b.and_i64();
        }
        self.o(op::OP_I64EQZ);
        self.c32(30);
        self.b.shl_i32();
        self.b.or_i32();
        self.si(NZCV);
    }
    /// Push ConditionHolds(cond) of NZCV (an i32 0 or 1)
    fn condition(&mut self, cond: u8) {
        let bit = |e: &mut Self, n: i32| {
            e.gi(NZCV);
            e.c32(n);
            e.b.shr_u_i32();
            e.c32(1);
            e.b.and_i32();
        };
        match cond >> 1 {
            0 => bit(self, 30),
            1 => bit(self, 29),
            2 => bit(self, 31),
            3 => bit(self, 28),
            4 => {
                // C && !Z
                self.gi(NZCV);
                self.c32(0x6000_0000);
                self.b.and_i32();
                self.c32(0x2000_0000);
                self.b.eq_i32();
            },
            5 | 6 => {
                // N == V (GE), and !Z (GT)
                self.gi(NZCV);
                self.c32(31);
                self.b.shr_u_i32();
                self.gi(NZCV);
                self.c32(28);
                self.b.shr_u_i32();
                self.b.xor_i32();
                self.c32(1);
                self.b.and_i32();
                self.b.eqz_i32();
                if cond >> 1 == 6 {
                    bit(self, 30);
                    self.b.eqz_i32();
                    self.b.and_i32();
                }
            },
            _ => self.c32(1),
        }
        if cond & 1 != 0 && cond != 0b1111 {
            self.b.eqz_i32();
        }
    }

    // ---- memory

    fn lookup_locals(&self) -> LookupLocals {
        LookupLocals {
            addr: self.v[ADDR].unsafe_clone(),
            epoch: self.v[EP].unsafe_clone(),
            tag: self.v[TAG].unsafe_clone(),
            tables: self.w[JAC].unsafe_clone(),
            entry: self.w[ENT].unsafe_clone(),
            offset: self.w[OFF].unsafe_clone(),
            host: self.w[HH].unsafe_clone(),
        }
    }
    fn access_abi() -> AccessAbi {
        AccessAbi {
            epoch: state::a64_jac_epoch as u32,
            base: state::a64_jac_base as u32,
            entries: super::pages::ENTRIES as u32,
            slow: "a64_page_access",
            bounce: super::pages::bounce_address(),
        }
    }
    /// Push the host address of a `size`-byte access at ADDR (else retry the
    /// instruction at `offset`)
    fn host(&mut self, size: u32, write: bool, offset: u16) { self.host_in(size, write, offset, 0) }
    /// As `host`, an unaligned read copied to bounce slot `slot` (0 or 1:
    /// a pair's second element, whose copy must not replace the first's)
    fn host_in(&mut self, size: u32, write: bool, offset: u16, slot: u32) {
        let (l, abi) = (self.lookup_locals(), Self::access_abi());
        let retry = self.f().retry;
        self.inline_lookup(
            &l,
            &abi,
            (size, false),
            (write as u32) << 8 | slot << 10,
            offset as u64,
            retry,
        );
    }
    /// As `host_in` for a plain store (STR, STP, the SIMD&FP ones): with
    /// cores in workers the host may be unaligned, which store_any stores
    /// to (kind bit 9; LDAR, STLR, the exclusives must fault instead)
    fn host_store(&mut self, size: u32, offset: u16, slot: u32) {
        if !WasmBuilder::ATOMIC_GUEST_MEMORY || size == 1 {
            return self.host_in(size, true, offset, slot);
        }
        let (l, abi) = (self.lookup_locals(), Self::access_abi());
        let retry = self.f().retry;
        self.inline_lookup(
            &l,
            &abi,
            (size, false),
            0x300 | slot << 10,
            offset as u64,
            retry,
        );
    }
    /// Push the value of a system register with an EL1 template (system_register)
    fn system_read(&mut self, r: SystemRegister, offset: u16) {
        match r {
            SystemRegister::SpEl0 => {
                // (at EL1h the banked copy, at EL1t the SP)
                self.load64(state::sp_el as u32);
                self.g(31);
                self.load32(state::pstate as u32);
                self.c32(cpu::PSTATE_SP as i32);
                self.b.and_i32();
                self.b.select();
            },
            SystemRegister::Tpidr1 => self.load64(state::tpidr_el1 as u32),
            SystemRegister::Daif => {
                self.load32(state::pstate as u32);
                self.c32(cpu::PSTATE_DAIF as i32);
                self.b.and_i32();
                self.b.extend_unsigned_i32_to_i64();
            },
            SystemRegister::Elr => self.load64(state::elr_el1 as u32),
            SystemRegister::Spsr => self.load64(state::spsr_el1 as u32),
            SystemRegister::Esr => self.load64(state::esr_el1 as u32),
            SystemRegister::Far => self.load64(state::far_el1 as u32),
            SystemRegister::Dczid if self.env.el1 => self.c64(4),
            SystemRegister::Dczid => {
                // (DZP: SCTLR_EL1.DZE clear)
                self.load64(state::sctlr_el1 as u32);
                self.c64(crate::aarch64::cpu::SCTLR_DZE);
                self.b.and_i64();
                self.c64(0);
                self.b.eq_i64();
                self.b.extend_unsigned_i32_to_i64();
                self.c64(4);
                self.b.shl_i64();
                self.c64(4);
                self.b.or_i64();
            },
            SystemRegister::Counter(enable) => {
                self.el0_enabled(enable, offset);
                self.b
                    .call_signature("a64_page_counter", Signature::new(&[], &[WasmType::I64]));
            },
            SystemRegister::Cntfrq => {
                self.el0_enabled(3, offset);
                self.load64(state::cntfrq_el0 as u32);
            },
            SystemRegister::TpidrRo => self.load64(state::tpidrro_el0 as u32),
            SystemRegister::Contextidr => self.load64(state::contextidr_el1 as u32),
            SystemRegister::Fpcr | SystemRegister::Fpsr => {
                self.fp_check(offset);
                self.load32(if matches!(r, SystemRegister::Fpcr) {
                    state::fpcr
                }
                else {
                    state::fpsr
                } as u32);
                self.b.extend_unsigned_i32_to_i64();
            },
        }
    }
    /// At EL0, retry (the interpreter's trap) unless CNTKCTL_EL1 has one of `bits`
    fn el0_enabled(&mut self, bits: u64, offset: u16) {
        if self.env.el1 {
            return;
        }
        self.load64(state::cntkctl_el1 as u32);
        self.c64(bits);
        self.b.and_i64();
        self.c64(0);
        self.b.eq_i64();
        self.retry_if(offset);
    }
    /// MSR of a system register with an EL1 template: X[rt] into it
    fn system_write(&mut self, r: SystemRegister, rt: u8, offset: u16) {
        let store64 = |e: &mut Self, address: u32, mask: u64| {
            e.c32(address as i32);
            e.xr(rt);
            if mask != u64::MAX {
                e.c64(mask);
                e.b.and_i64();
            }
            e.b.store_aligned_i64(0);
        };
        match r {
            SystemRegister::SpEl0 => {
                // (UNDEFINED at EL1t: the interpreter says so)
                self.load32(state::pstate as u32);
                self.c32(cpu::PSTATE_SP as i32);
                self.b.and_i32();
                self.b.eqz_i32();
                self.retry_if(offset);
                store64(self, state::sp_el as u32, u64::MAX);
            },
            SystemRegister::Tpidr1 => store64(self, state::tpidr_el1 as u32, u64::MAX),
            SystemRegister::Daif => {
                self.c32(state::pstate as i32);
                self.load32(state::pstate as u32);
                self.c32(!cpu::PSTATE_DAIF as i32);
                self.b.and_i32();
                self.xr(rt);
                self.b.wrap_i64_to_i32();
                self.c32(cpu::PSTATE_DAIF as i32);
                self.b.and_i32();
                self.b.or_i32();
                self.b.store_aligned_i32(0);
                self.unmasked(offset);
            },
            SystemRegister::Elr => store64(self, state::elr_el1 as u32, u64::MAX),
            SystemRegister::Spsr => {
                // (sysregs' mask: in profile v3 AArch32's Q, IT, GE and IL too)
                let pan = if cpu::has_pan() { cpu::PSTATE_PAN as u64 } else { 0 };
                let a32 = if cpu::has_aarch32() {
                    (cpu::PSTATE_Q | cpu::PSTATE_IT | cpu::PSTATE_GE | cpu::PSTATE_IL) as u64
                }
                else {
                    0
                };
                store64(self, state::spsr_el1 as u32, 0xF060_03FF | pan | a32)
            },
            SystemRegister::Esr => store64(self, state::esr_el1 as u32, 0xFFFF_FFFF),
            SystemRegister::Far => store64(self, state::far_el1 as u32, u64::MAX),
            SystemRegister::TpidrRo => store64(self, state::tpidrro_el0 as u32, u64::MAX),
            SystemRegister::Contextidr => store64(self, state::contextidr_el1 as u32, 0xFFFF_FFFF),
            SystemRegister::Fpcr | SystemRegister::Fpsr => {
                self.fp_check(offset);
                let (at, mask) = if matches!(r, SystemRegister::Fpcr) {
                    (state::fpcr as u32, crate::aarch64::fp::FPCR_WRITABLE)
                }
                else {
                    (state::fpsr as u32, 0xF800_009F)
                };
                self.c32(at as i32);
                self.xr(rt);
                self.b.wrap_i64_to_i32();
                self.c32(mask as i32);
                self.b.and_i32();
                self.b.store_aligned_i32(0);
            },
            SystemRegister::Dczid | SystemRegister::Counter(_) | SystemRegister::Cntfrq => {
                unreachable!()
            },
        }
    }
    /// After a write to PSTATE.DAIF at `offset`: leave for the run loop,
    /// the PC at the next instruction, when an interrupt is now deliverable
    fn unmasked(&mut self, offset: u16) {
        self.b
            .call_signature("a64_page_unmasked", Signature::new(&[], &[WasmType::I32]));
        self.b.if_void();
        let exit = self.f().exit;
        self.leave_to(exit, offset as u64 + 4);
        self.b.block_end();
    }
    /// As `host`, an unprivileged access at EL1 (LDTR, STTR): a lookup of
    /// the access cache's EL0 tables (after the EL1 ones: jitrt::access's
    /// kinds, read 1 and write 3), filled on a miss with EL0's permissions
    /// (pages::a64_page_access, kind bit 11); not the frame's lookups, which
    /// probe the activation's tables
    fn host_unprivileged(&mut self, size: u32, write: bool, offset: u16) {
        let entries = super::pages::ENTRIES as u32;
        let bytes = crate::jitrt::access::ENTRY_BYTES;
        let table = if write { 2 * entries * bytes } else { 0 };
        // the tag, the entry, the offset in the page
        self.g(ADDR);
        self.c64(12);
        self.b.shr_u_i64();
        self.g(EP);
        self.b.or_i64();
        self.s(TAG);
        self.g(TAG);
        self.b.wrap_i64_to_i32();
        self.c32(entries as i32 - 1);
        self.b.and_i32();
        self.c32(bytes.trailing_zeros() as i32);
        self.b.shl_i32();
        self.gi(JAC);
        self.b.add_i32();
        self.c32((entries * bytes) as i32);
        self.b.add_i32();
        self.si(J0);
        self.g(ADDR);
        self.b.wrap_i64_to_i32();
        self.c32(4095);
        self.b.and_i32();
        self.si(OFF);
        // a hit: the tag matches, the access stays in the page (and is
        // aligned with cores in workers, whose accesses are atomic)
        self.gi(J0);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, table);
        self.g(TAG);
        self.b.eq_i64();
        self.gi(OFF);
        self.c32((4096 - size) as i32);
        self.b.leu_i32();
        self.b.and_i32();
        if WasmBuilder::ATOMIC_GUEST_MEMORY && size > 1 {
            self.gi(OFF);
            self.c32(size.min(8) as i32 - 1);
            self.b.and_i32();
            self.b.eqz_i32();
            self.b.and_i32();
        }
        self.b.if_i32();
        self.gi(J0);
        self.b.load_aligned_i32(table + 8);
        self.gi(OFF);
        self.b.add_i32();
        self.b.else_();
        self.g(ADDR);
        self.c32(size as i32 | (write as i32) << 8 | 0x800);
        self.b.call_signature(
            "a64_page_access",
            Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
        );
        self.b.block_end();
        self.b.tee_local(&self.w[HH]);
        self.b.eqz_i32();
        self.retry_if(offset);
        self.gi(HH);
    }
    /// Retry the instruction at `offset` when the i32 condition on the stack is true
    fn retry_if(&mut self, offset: u16) {
        self.b.if_void();
        let retry = self.f().retry;
        self.leave_to(retry, offset as u64);
        self.b.block_end();
    }
    /// An SP-based access with SP alignment checked: retry when SP is misaligned
    fn sp_check(&mut self, rn: u8, offset: u16) {
        if rn == 31 && self.env.sp_checked {
            self.g(31);
            self.c64(15);
            self.b.and_i64();
            self.c64(0);
            self.b.ne_i64();
            self.retry_if(offset);
        }
    }
    /// Load `size_log` bytes from the host address on the stack into an i64
    /// (sign-extended by `signed`, to 32 bits then zero-extended by `to_w`)
    fn load_value(&mut self, size_log: u32, signed: bool, to_w: bool) {
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            // (atomic loads only zero-extend: the sign extension follows)
            self.b.guest_load_i64_bits(8 << size_log.min(3), 0);
            if signed && size_log < 3 {
                self.o([0xC2, 0xC3, 0xC4][size_log as usize]); // i64.extend8_s, 16_s, 32_s
                if to_w {
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                }
            }
            return;
        }
        let align = size_log.min(3) as u8;
        if signed && to_w {
            let opcode = [op::OP_I32LOAD8S, op::OP_I32LOAD16S, op::OP_I32LOAD][size_log as usize];
            self.b.memory_op(opcode, align, 0);
            self.b.extend_unsigned_i32_to_i64();
            return;
        }
        let opcode = match (size_log, signed) {
            (0, false) => op::OP_I64LOAD8U,
            (1, false) => op::OP_I64LOAD16U,
            (2, false) => op::OP_I64LOAD32U,
            (0, true) => op::OP_I64LOAD8S,
            (1, true) => op::OP_I64LOAD16S,
            (2, true) => op::OP_I64LOAD32S,
            _ => op::OP_I64LOAD,
        };
        self.b.memory_op(opcode, align, 0);
    }
    /// [host, value] -> []: the low `bits` of the value stored at host +
    /// `offset`, a host of host_store: with cores in workers an unaligned one
    /// is a plain store, as the interpreter's (an unaligned access is no
    /// single-copy atomic one; barriers order it as any other)
    fn store_any(&mut self, bits: u32, offset: u32) {
        if !WasmBuilder::ATOMIC_GUEST_MEMORY || bits == 8 {
            return self.b.guest_store_i64_bits(bits, offset);
        }
        self.s(SV);
        self.ti(SH);
        self.c32(bits as i32 / 8 - 1);
        self.b.and_i32();
        self.b.if_void();
        self.gi(SH);
        self.g(SV);
        self.b.memory_op(
            match bits {
                16 => op::OP_I64STORE16,
                32 => op::OP_I64STORE32,
                _ => op::OP_I64STORE,
            },
            op::MEM_NO_ALIGN,
            offset,
        );
        self.b.else_();
        self.gi(SH);
        self.g(SV);
        self.b.guest_store_i64_bits(bits, offset);
        self.b.block_end();
    }
    /// Store the i64 on the stack (after the host address) as `size_log` bytes
    fn store_value(&mut self, size_log: u32) {
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            self.b.guest_store_i64_bits(8 << size_log.min(3), 0);
            return;
        }
        let opcode = [
            op::OP_I64STORE8,
            op::OP_I64STORE16,
            op::OP_I64STORE32,
            op::OP_I64STORE,
        ][size_log as usize];
        self.b.memory_op(opcode, size_log.min(3) as u8, 0);
    }

    // ---- instructions

    /// A helper call (helper): the registers it names and NZCV to memory,
    /// the interpreter's execute, back into their locals; a refusal retries
    /// the instruction in the interpreter. (The locals are loaded again
    /// before the result is looked at: a helper that was done but asks the
    /// run loop for something, a load-exclusive's spin yield, leaves as a
    /// refusal does (pages::HELPER_DONE), and the leaving writes the locals
    /// back over what it wrote; after a refusal memory holds what was stored)
    fn helper_call(&mut self, offset: u16, sync: &HelperSync) {
        let mut gprs = sync.gprs.clone();
        gprs.sort_unstable();
        gprs.dedup();
        for &r in &gprs {
            self.store64_at(x_address(r as usize), r as usize);
        }
        if sync.nzcv {
            self.c32(state::nzcv as i32);
            self.gi(NZCV);
            self.b.store_aligned_i32(0);
        }
        self.c32(self.words[offset as usize / 4] as i32);
        self.linear(offset as u64);
        self.b.call_signature(
            "a64_page_helper",
            Signature::new(&[WasmType::I32, WasmType::I64], &[WasmType::I32]),
        );
        self.si(A0);
        for &r in &gprs {
            self.load64(x_address(r as usize));
            self.s(r as usize);
        }
        if sync.nzcv {
            self.load32(state::nzcv as u32);
            self.si(NZCV);
        }
        self.gi(A0);
        self.retry_if(offset);
    }

    // ---- scalar FP (P6.3b): the fast path's rules (docs/arm64-virt-android16-plan.md P6)

    /// Push whether an FP value's bits in local `l` (D: 64 bits, S: the low
    /// 32) are zero or a normal number, or with `result`, zero or a normal
    /// number of exponent 2 or more (no NaN, infinity, denormal, nor what
    /// may have been tiny)
    fn fp_ordinary(&mut self, l: usize, double: bool, result: bool) {
        let (sign, low, inf) = if double {
            (
                0x8000_0000_0000_0000u64,
                if result { 0x0020_0000_0000_0000u64 } else { 0x0010_0000_0000_0000 },
                0x7FF0_0000_0000_0000u64,
            )
        }
        else {
            (
                0x8000_0000u64,
                if result { 0x0100_0000u64 } else { 0x0080_0000 },
                0x7F80_0000u64,
            )
        };
        let magnitude = |e: &mut Self| {
            e.g(l);
            e.c64(!sign & if double { u64::MAX } else { 0xFFFF_FFFF });
            e.b.and_i64();
        };
        magnitude(self);
        self.o(op::OP_I64EQZ);
        magnitude(self);
        self.c64(low);
        self.b.sub_i64();
        self.c64(inf - low);
        self.o(op::OP_I64LTU);
        self.b.or_i32();
    }
    /// Load V[v]'s low 64 bits (D) or 32 (S, zero-extended) into local `l`
    fn fp_load(&mut self, v: u32, double: bool, l: usize) {
        self.c32((state::v as u32 + 16 * v) as i32);
        self.b.memory_op(
            if double { op::OP_I64LOAD } else { op::OP_I64LOAD32U },
            if double { 3 } else { 2 },
            0,
        );
        self.s(l);
    }
    /// Write local `l`'s bits to V[d], the rest of the register zero
    fn fp_store(&mut self, d: u32, double: bool, l: usize) {
        let at = state::v as u32 + 16 * d;
        self.c32(at as i32);
        self.g(l);
        if !double {
            self.c64(0xFFFF_FFFF);
            self.b.and_i64();
        }
        self.b.store_aligned_i64(0);
        self.c32(at as i32 + 8);
        self.c64(0);
        self.b.store_aligned_i64(0);
    }
    /// Push local `l` as an f64 (D) or f32 (S)
    fn fp_value(&mut self, l: usize, double: bool) {
        self.g(l);
        if double {
            self.b.reinterpret_i64_as_f64();
        }
        else {
            self.b.wrap_i64_to_i32();
            self.b.reinterpret_i32_as_f32();
        }
    }
    /// Pop an f64 (D) or f32 (S) into local `l` as its bits
    fn fp_bits(&mut self, l: usize, double: bool) {
        if double {
            self.b.reinterpret_f64_as_i64();
        }
        else {
            self.b.reinterpret_f32_as_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
        self.s(l);
    }
    fn fp_instruction(&mut self, offset: u16, i: &Inst, form: FpForm) {
        let word = i.imm as u32;
        let double = word >> 22 & 1 != 0;
        let (d, n, m, a) = (word & 31, word >> 5 & 31, word >> 16 & 31, word >> 10 & 31);
        self.fp_check(offset);
        if let FpForm::Move(op) = form {
            self.fp_load(n, double, T0);
            self.g(T0);
            let sign = if double { 1u64 << 63 } else { 1 << 31 };
            match op {
                1 => {
                    self.c64(!sign);
                    self.b.and_i64();
                },
                2 => {
                    self.c64(sign);
                    self.b.xor_i64();
                },
                _ => {},
            }
            self.s(T0);
            return self.fp_store(d, double, T0);
        }
        let done = self.b.block_void();
        // the fast path: RMode RN and FZ 0 (FPCR), IXC already set (FPSR), operands ordinary
        self.fp_load(n, double, T0);
        match form {
            FpForm::Compare { zero: true } => {
                self.c64(0);
                self.s(T1);
            },
            _ => self.fp_load(m, double, T1),
        }
        let compare = matches!(form, FpForm::Compare { .. });
        if let FpForm::MultiplyAdd { .. } = form {
            self.fp_load(a, double, T2);
        }
        self.load32(state::fpcr as u32);
        self.c32(0x01C0_0000);
        self.b.and_i32();
        self.b.eqz_i32();
        if !compare {
            // (IXC: bit 4, as 0 or 1)
            self.load32(state::fpsr as u32);
            self.c32(4);
            self.b.shr_u_i32();
            self.c32(1);
            self.b.and_i32();
            self.b.and_i32();
        }
        for l in if matches!(form, FpForm::MultiplyAdd { .. }) {
            &[T0, T1, T2][..]
        }
        else {
            &[T0, T1][..]
        } {
            if compare {
                // (a compare only refuses NaNs: magnitude <= infinity)
                self.g(*l);
                self.c64(if double { 0x7FFF_FFFF_FFFF_FFFF } else { 0x7FFF_FFFF });
                self.b.and_i64();
                self.c64(if double { 0x7FF0_0000_0000_0000 } else { 0x7F80_0000 });
                self.o(op::OP_I64LEU);
            }
            else {
                self.fp_ordinary(*l, double, false);
            }
            self.b.and_i32();
        }
        if let FpForm::Arithmetic { op: 1, .. } = form {
            // (FDIV: a divisor that is not zero)
            self.g(T1);
            self.c64(if double { 0x7FFF_FFFF_FFFF_FFFF } else { 0x7FFF_FFFF });
            self.b.and_i64();
            self.c64(0);
            self.b.ne_i64();
            self.b.and_i32();
        }
        self.b.if_void();
        match form {
            FpForm::Compare { .. } => {
                // equal 0110, less 1000, greater 0010
                self.fp_value(T0, double);
                self.fp_value(T1, double);
                self.o(if double { op::OP_F64EQ } else { 0x5B });
                self.b.if_i32();
                self.c32(0x6000_0000);
                self.b.else_();
                self.fp_value(T0, double);
                self.fp_value(T1, double);
                self.o(if double { op::OP_F64LT } else { 0x5D });
                self.b.if_i32();
                self.c32(0x8000_0000u32 as i32);
                self.b.else_();
                self.c32(0x2000_0000);
                self.b.block_end();
                self.b.block_end();
                self.si(NZCV);
                self.b.br(done);
                self.b.block_end();
            },
            _ => {
                match form {
                    FpForm::Arithmetic { op, negate } => {
                        // (FMUL 0, FDIV 1, FADD 2, FSUB 3 in the word; Wasm's 0 add, 1 sub, 2 mul, 3 div)
                        let wasm = [2, 3, 0, 1][op as usize];
                        self.fp_value(T0, double);
                        self.fp_value(T1, double);
                        if double {
                            self.b.arithmetic_f64(wasm);
                        }
                        else {
                            self.b.arithmetic_f32(wasm);
                        }
                        if negate {
                            if double {
                                self.b.unary_f64(true);
                            }
                            else {
                                self.o(0x8C); // f32.neg
                            }
                        }
                    },
                    FpForm::MultiplyAdd {
                        negate_addend,
                        negate_product,
                    } => {
                        // relaxed_madd(n, m, a) = n * m + a; relaxed_nmadd = -(n * m) + a, fused (probed)
                        for l in [T0, T1, T2] {
                            self.fp_value(l, double);
                            if l == T2 && negate_addend {
                                if double {
                                    self.b.unary_f64(true);
                                }
                                else {
                                    self.o(0x8C);
                                }
                            }
                            self.b.simd(if double { 0x14 } else { 0x13 }); // splat
                        }
                        self.b.simd(match (double, negate_product) {
                            (false, false) => 0x105,
                            (false, true) => 0x106,
                            (true, false) => 0x107,
                            (true, true) => 0x108,
                        });
                        self.b.simd_lane(if double { 0x21 } else { 0x1F }, 0); // extract lane 0
                    },
                    _ => unreachable!(),
                }
                self.fp_bits(T3, double);
                self.fp_ordinary(T3, double, true);
                self.b.if_void();
                self.fp_store(d, double, T3);
                self.b.br(done);
                self.b.block_end();
                self.b.block_end();
            },
        }
        // the exact path: the interpreter's SoftFloat
        let sync = HelperSync {
            gprs: vec![],
            nzcv: compare,
        };
        self.helper_call(offset, &sync);
        self.b.block_end();
    }

    fn instruction(&mut self, offset: u16, i: &Inst, index: &BTreeMap<u16, usize>) {
        if let Some(form) = fp_form(i, &self.env) {
            return self.fp_instruction(offset, i, form);
        }
        if let Some(form) = neon::form(i, &self.env) {
            return self.vector_instruction(offset, i, form);
        }
        if !native(i, &self.env) {
            let sync = helper(i, &self.env).expect("a template");
            return self.helper_call(offset, &sync);
        }
        let (rd, rn, rm, sf) = (i.rd, i.rn, i.rm, i.sf);
        let mask = |sf: bool| if sf { u64::MAX } else { 0xFFFF_FFFF };
        match i.op {
            Op::Adr => {
                self.linear((offset as u64).wrapping_add(i.imm));
                self.set_x(rd);
            },
            Op::Adrp => {
                self.g(BASE);
                self.c64(i.imm);
                self.b.add_i64();
                self.set_x(rd);
            },
            Op::AddSubImm => {
                self.xr_sp(rn);
                self.s(T0);
                if i.s {
                    self.c64(i.imm);
                    self.s(T1);
                    self.g(T0);
                    self.g(T1);
                    if i.sub == 0 {
                        self.b.add_i64();
                    }
                    else {
                        self.b.sub_i64();
                    }
                    self.c64(mask(sf));
                    self.b.and_i64();
                    self.s(T2);
                    self.arith_flags(i.sub != 0, sf);
                    self.g(T2);
                    self.set_x(rd);
                }
                else {
                    self.g(T0);
                    self.c64(i.imm);
                    if i.sub == 0 {
                        self.b.add_i64();
                    }
                    else {
                        self.b.sub_i64();
                    }
                    self.set_xw(rd, sf, true);
                }
            },
            Op::LogicalImm => {
                self.xr(rn);
                self.c64(i.imm);
                match i.sub {
                    0 | 3 => self.b.and_i64(),
                    1 => self.b.or_i64(),
                    _ => self.b.xor_i64(),
                }
                self.c64(mask(sf));
                self.b.and_i64();
                if i.sub == 3 {
                    self.s(T2);
                    self.logic_flags(sf);
                    self.g(T2);
                    self.set_x(rd);
                }
                else {
                    self.set_x_sp(rd);
                }
            },
            Op::MoveWide => {
                let shifted = i.imm << i.amount;
                match i.sub {
                    0 => self.c64(!shifted & mask(sf)),
                    2 => self.c64(shifted),
                    _ => {
                        self.xr(rd);
                        self.c64(!(0xFFFFu64 << i.amount) & mask(sf));
                        self.b.and_i64();
                        self.c64(shifted);
                        self.b.or_i64();
                    },
                }
                self.set_x(rd);
            },
            Op::Bitfield => self.bitfield(i),
            Op::Extr => {
                let lsb = i.amount as u64;
                if sf {
                    self.xr(rm);
                    if lsb != 0 {
                        self.c64(lsb);
                        self.b.shr_u_i64();
                        self.xr(rn);
                        self.c64(64 - lsb);
                        self.b.shl_i64();
                        self.b.or_i64();
                    }
                }
                else {
                    self.xr(rn);
                    self.c64(32);
                    self.b.shl_i64();
                    self.xr(rm);
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                    self.b.or_i64();
                    self.c64(lsb);
                    self.b.shr_u_i64();
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                }
                self.set_x(rd);
            },
            Op::LogicalShifted => {
                self.xr(rn);
                self.shifted(rm, i.shift, i.amount, sf);
                if i.sub & 1 != 0 {
                    self.c64(u64::MAX);
                    self.b.xor_i64();
                }
                match i.sub >> 1 {
                    0 | 3 => self.b.and_i64(),
                    1 => self.b.or_i64(),
                    _ => self.b.xor_i64(),
                }
                self.c64(mask(sf));
                self.b.and_i64();
                if i.sub >> 1 == 3 {
                    self.s(T2);
                    self.logic_flags(sf);
                    self.g(T2);
                }
                self.set_x(rd);
            },
            Op::AddSubShifted | Op::AddSubExtended => {
                let extended = i.op == Op::AddSubExtended;
                if extended {
                    self.xr_sp(rn);
                }
                else {
                    self.xr(rn);
                }
                self.s(T0);
                if extended {
                    self.extended(rm, i.shift, i.amount);
                }
                else {
                    self.shifted(rm, i.shift, i.amount, sf);
                }
                self.s(T1);
                self.g(T0);
                self.g(T1);
                if i.sub == 0 {
                    self.b.add_i64();
                }
                else {
                    self.b.sub_i64();
                }
                self.c64(mask(sf));
                self.b.and_i64();
                self.s(T2);
                if i.s {
                    self.arith_flags(i.sub != 0, sf);
                }
                self.g(T2);
                if extended && !i.s {
                    self.set_x_sp(rd);
                }
                else {
                    self.set_x(rd);
                }
            },
            Op::AddSubCarry => {
                self.xr(rn);
                self.s(T0);
                self.xr(rm);
                if i.sub != 0 {
                    self.c64(u64::MAX);
                    self.b.xor_i64();
                }
                self.c64(mask(sf));
                self.b.and_i64();
                self.s(T1);
                self.gi(NZCV);
                self.c32(29);
                self.b.shr_u_i32();
                self.c32(1);
                self.b.and_i32();
                self.si(C1);
                if !sf {
                    self.g(T0);
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                    self.s(T0);
                }
                self.add_with_carry(sf, i.s);
                self.g(T2);
                self.set_x(rd);
            },
            Op::CondCompare => {
                self.condition(i.cond);
                self.b.if_void();
                self.xr(rn);
                self.c64(mask(sf));
                self.b.and_i64();
                self.s(T0);
                if i.amount == 1 {
                    self.c64(rm as u64);
                }
                else {
                    self.xr(rm);
                }
                self.c64(mask(sf));
                self.b.and_i64();
                self.s(T1);
                self.g(T0);
                self.g(T1);
                if i.sub == 0 {
                    self.b.add_i64();
                }
                else {
                    self.b.sub_i64();
                }
                self.c64(mask(sf));
                self.b.and_i64();
                self.s(T2);
                self.arith_flags(i.sub != 0, sf);
                self.b.else_();
                self.c32(((i.imm as u32) << 28) as i32);
                self.si(NZCV);
                self.b.block_end();
            },
            Op::CondSelect => {
                self.xr(rn);
                self.xr(rm);
                match i.sub {
                    0 => {},
                    1 => {
                        self.c64(1);
                        self.b.add_i64();
                    },
                    2 => {
                        self.c64(u64::MAX);
                        self.b.xor_i64();
                    },
                    _ => {
                        self.s(T0);
                        self.c64(0);
                        self.g(T0);
                        self.b.sub_i64();
                    },
                }
                self.condition(i.cond);
                self.b.select();
                self.set_xw(rd, sf, false);
            },
            Op::DataProc3 => self.data_processing_3(i),
            Op::DataProc2 => self.data_processing_2(i),
            Op::DataProc1 => self.data_processing_1(i),
            Op::Hint => {},
            Op::Barrier => {
                self.b.guest_fence();
                if i.sub == 0 && crate::parallel::active() {
                    // (the TLB maintenance this core posted: the DSB steps, and waits)
                    self.load32(crate::aarch64::tlb::pending_address());
                    self.b.if_void();
                    let step = self.f().step;
                    self.leave_to(step, offset as u64);
                    self.b.block_end();
                }
            },
            Op::MsrImm => {
                // DAIFSet (1), DAIFClr (2) at EL1
                let bits = (i.imm as u32 & 15) << 6;
                self.c32(state::pstate as i32);
                self.load32(state::pstate as u32);
                if i.sub == 1 {
                    self.c32(bits as i32);
                    self.b.or_i32();
                }
                else {
                    self.c32(!bits as i32);
                    self.b.and_i32();
                }
                self.b.store_aligned_i32(0);
                if i.sub == 2 {
                    self.unmasked(offset);
                }
            },
            Op::Sys if i.imm as u32 == DC_ZVA => {
                // (at EL0 only while SCTLR_EL1.DZE allows it: else the
                // interpreter, which traps)
                if !self.env.el1 {
                    self.load64(state::sctlr_el1 as u32);
                    self.c64(crate::aarch64::cpu::SCTLR_DZE);
                    self.b.and_i64();
                    self.b.wrap_i64_to_i32();
                    self.b.eqz_i32();
                    self.retry_if(offset);
                }
                // the 64-byte block (DCZID_EL0's BS 4) zeroed through the
                // access cache's write entry (a miss, Device memory, a code
                // or watched page: the interpreter, which faults or marks)
                self.xr(rd);
                self.c64(!63);
                self.b.and_i64();
                self.s(ADDR);
                self.host(8, true, offset);
                self.si(C1);
                for k in 0..8 {
                    self.gi(C1);
                    self.c64(0);
                    self.b.guest_store_i64(8 * k);
                }
            },
            Op::Sys => {
                // TLBI: the TLBs and access caches in Rust; the function leaves
                // when what it depends on changed (its access cache's epoch)
                self.c32(self.words[offset as usize / 4] as i32);
                self.xr(rd);
                self.b.call_signature(
                    "a64_page_tlbi",
                    Signature::new(&[WasmType::I32, WasmType::I64], &[WasmType::I32]),
                );
                self.b.if_void();
                let exit = self.f().exit;
                self.leave_to(exit, offset as u64 + 4);
                self.b.block_end();
            },
            Op::Mrs if system_register(i, &self.env).is_some() => {
                self.system_read(system_register(i, &self.env).unwrap(), offset);
                self.set_x(rd);
            },
            Op::Msr if system_register(i, &self.env).is_some() => {
                self.system_write(system_register(i, &self.env).unwrap(), rd, offset);
            },
            Op::Mrs => {
                if i.imm as u32 == TPIDR_EL0 {
                    self.load64(state::tpidr_el0 as u32);
                }
                else {
                    self.gi(NZCV);
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_x(rd);
            },
            Op::Msr => {
                if i.imm as u32 == TPIDR_EL0 {
                    self.c32(state::tpidr_el0 as i32);
                    self.xr(rd);
                    self.b.store_aligned_i64(0);
                }
                else {
                    self.xr(rd);
                    self.b.wrap_i64_to_i32();
                    self.c32(0xF000_0000u32 as i32);
                    self.b.and_i32();
                    self.si(NZCV);
                }
            },
            Op::LoadLiteral => {
                if i.sub == 3 {
                    // (PRFM literal: no effect)
                    return;
                }
                self.linear((offset as u64).wrapping_add(i.imm));
                self.s(ADDR);
                let size = if i.sub == 1 { 8 } else { 4 };
                self.host(size, false, offset);
                if WasmBuilder::ATOMIC_GUEST_MEMORY {
                    self.b.guest_load_i64_bits(8 * size, 0);
                    if i.sub == 2 {
                        self.o(0xC4); // i64.extend32_s
                    }
                }
                else {
                    match i.sub {
                        0 => self.b.memory_op(op::OP_I64LOAD32U, 2, 0),
                        1 => self.b.memory_op(op::OP_I64LOAD, 3, 0),
                        _ => self.b.memory_op(op::OP_I64LOAD32S, 2, 0),
                    }
                }
                self.set_x(rd);
            },
            Op::LoadStore => self.load_store(offset, i),
            Op::LoadStorePair => self.load_store_pair(offset, i),
            Op::LoadAcquireStoreRelease => {
                let size_log = i.cond as u32;
                self.sp_check(rn, offset);
                self.xr_sp(rn);
                self.s(ADDR);
                // (aligned, or the interpreter's alignment fault)
                if size_log != 0 {
                    self.g(ADDR);
                    self.c64((1 << size_log) - 1);
                    self.b.and_i64();
                    self.c64(0);
                    self.b.ne_i64();
                    self.retry_if(offset);
                }
                self.host(1 << size_log, i.sub != 1, offset);
                if i.sub == 1 {
                    self.load_value(size_log, false, false);
                    self.set_x(rd);
                }
                else {
                    self.xr(rd);
                    self.store_value(size_log);
                }
            },
            Op::Branch => {
                if i.sub == 1 {
                    self.linear(offset as u64 + 4);
                    self.s(30);
                }
                self.goto((offset as u64).wrapping_add(i.imm), index);
            },
            Op::BCond => {
                self.condition(i.cond);
                self.b.if_void();
                self.goto((offset as u64).wrapping_add(i.imm), index);
                self.b.block_end();
            },
            Op::CompareBranch => {
                self.xr(rd);
                if !sf {
                    self.b.wrap_i64_to_i32();
                    self.b.eqz_i32();
                }
                else {
                    self.o(op::OP_I64EQZ);
                }
                if i.sub != 0 {
                    self.b.eqz_i32();
                }
                self.b.if_void();
                self.goto((offset as u64).wrapping_add(i.imm), index);
                self.b.block_end();
            },
            Op::TestBranch => {
                self.xr(rd);
                self.c64(i.amount as u64);
                self.b.shr_u_i64();
                self.c64(1);
                self.b.and_i64();
                self.b.wrap_i64_to_i32();
                if i.sub != 1 {
                    self.b.eqz_i32();
                }
                self.b.if_void();
                self.goto((offset as u64).wrapping_add(i.imm), index);
                self.b.block_end();
            },
            Op::BranchReg => {
                self.xr(rn);
                self.s(T0);
                // (a target whose top byte is not its bit 55 extended: TBI, the interpreter's)
                self.g(T0);
                self.c64(8);
                self.b.shl_i64();
                self.c64(8);
                self.b.shr_s_i64();
                self.g(T0);
                self.b.ne_i64();
                self.retry_if(offset);
                if i.sub == 1 {
                    self.linear(offset as u64 + 4);
                    self.s(30);
                }
                self.g(T0);
                self.s(PC);
                self.b.br(self.f().dispatch);
            },
            _ => unreachable!("no template: {:?}", i.op),
        }
    }

    fn bitfield(&mut self, i: &Inst) {
        let sf = i.sf;
        let width = if sf { 64 } else { 32 };
        let imms = i.imm as u32;
        let immr = i.amount as u32;
        let (wmask, tmask) = crate::aarch64::execute::bitfield_masks(sf as u32, imms, immr, sf);
        let full = if sf { u64::MAX } else { 0xFFFF_FFFF };
        // rotated = ROR(src, immr) within the width
        let rotated = |e: &mut Self| {
            e.xr(i.rn);
            if sf {
                if immr != 0 {
                    e.c64(immr as u64);
                    e.b.rotr_i64();
                }
            }
            else {
                e.b.wrap_i64_to_i32();
                if immr != 0 {
                    e.c32(immr as i32);
                    e.b.rotr_i32();
                }
                e.b.extend_unsigned_i32_to_i64();
            }
        };
        match i.sub {
            0 => {
                // SBFM: the sign of bit imms above the field
                rotated(self);
                self.c64(wmask & tmask);
                self.b.and_i64();
                self.xr(i.rn);
                self.c64((63 - imms) as u64);
                self.b.shl_i64();
                self.c64(63);
                self.b.shr_s_i64();
                self.c64(!tmask & full);
                self.b.and_i64();
                self.b.or_i64();
            },
            1 => {
                // BFM: the destination's other bits stay
                self.xr(i.rd);
                self.c64(!(wmask & tmask) & full);
                self.b.and_i64();
                rotated(self);
                self.c64(wmask & tmask);
                self.b.and_i64();
                self.b.or_i64();
            },
            _ => {
                rotated(self);
                self.c64(wmask & tmask);
                self.b.and_i64();
            },
        }
        let _ = width;
        self.set_x(i.rd);
    }

    fn data_processing_3(&mut self, i: &Inst) {
        let (rd, rn, rm, ra, sf) = (i.rd, i.rn, i.rm, i.ra, i.sf);
        match i.sub {
            0 | 1 => {
                self.xr(ra);
                self.xr(rn);
                self.xr(rm);
                self.b.mul_i64();
                if i.sub == 0 {
                    self.b.add_i64();
                }
                else {
                    self.b.sub_i64();
                }
                self.set_xw(rd, sf, false);
            },
            2 | 3 | 10 | 11 => {
                // SMADDL, SMSUBL, UMADDL, UMSUBL
                let signed = i.sub < 10;
                self.xr(ra);
                for r in [rn, rm] {
                    self.xr(r);
                    if signed {
                        self.o(OP_I64EXTEND32S);
                    }
                    else {
                        self.c64(0xFFFF_FFFF);
                        self.b.and_i64();
                    }
                }
                self.b.mul_i64();
                if i.sub & 1 == 0 {
                    self.b.add_i64();
                }
                else {
                    self.b.sub_i64();
                }
                self.set_x(rd);
            },
            _ => {
                // SMULH (4), UMULH (12): the product's high 64 bits from 32-bit halves
                self.xr(rn);
                self.s(T0);
                self.xr(rm);
                self.s(T1);
                let half = |e: &mut Self, l: usize, high: bool| {
                    e.g(l);
                    if high {
                        e.c64(32);
                        e.b.shr_u_i64();
                    }
                    else {
                        e.c64(0xFFFF_FFFF);
                        e.b.and_i64();
                    }
                };
                // T2 = lo(a) * lo(b); T3 = hi(a) * lo(b); T4 = lo(a) * hi(b)
                half(self, T0, false);
                half(self, T1, false);
                self.b.mul_i64();
                self.s(T2);
                half(self, T0, true);
                half(self, T1, false);
                self.b.mul_i64();
                self.s(T3);
                half(self, T0, false);
                half(self, T1, true);
                self.b.mul_i64();
                self.s(T4);
                // cross = (T2 >> 32) + (T3 & mask) + T4, in T4
                self.g(T2);
                self.c64(32);
                self.b.shr_u_i64();
                self.g(T3);
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
                self.b.add_i64();
                self.g(T4);
                self.b.add_i64();
                self.s(T4);
                // high = hi(a) * hi(b) + (T3 >> 32) + (cross >> 32)
                half(self, T0, true);
                half(self, T1, true);
                self.b.mul_i64();
                self.g(T3);
                self.c64(32);
                self.b.shr_u_i64();
                self.b.add_i64();
                self.g(T4);
                self.c64(32);
                self.b.shr_u_i64();
                self.b.add_i64();
                if i.sub == 4 {
                    // signed: minus b where a < 0, minus a where b < 0
                    for (sign, other) in [(T0, T1), (T1, T0)] {
                        self.g(other);
                        self.g(sign);
                        self.c64(63);
                        self.b.shr_s_i64();
                        self.b.and_i64();
                        self.b.sub_i64();
                    }
                }
                self.set_x(rd);
            },
        }
    }

    fn data_processing_2(&mut self, i: &Inst) {
        let (rd, rn, rm, sf) = (i.rd, i.rn, i.rm, i.sf);
        match i.sub {
            0b000010 | 0b000011 => {
                // UDIV, SDIV: by 0 gives 0; SDIV of the most negative by -1 wraps
                let signed = i.sub == 0b000011;
                if sf {
                    self.xr(rn);
                    self.s(T0);
                    self.xr(rm);
                    self.s(T1);
                }
                else {
                    for (r, l) in [(rn, T0), (rm, T1)] {
                        self.xr(r);
                        if signed {
                            self.o(OP_I64EXTEND32S);
                        }
                        else {
                            self.c64(0xFFFF_FFFF);
                            self.b.and_i64();
                        }
                        self.s(l);
                    }
                }
                self.g(T1);
                self.o(op::OP_I64EQZ);
                self.b.if_i64();
                self.c64(0);
                self.b.else_();
                if signed {
                    self.g(T1);
                    self.c64(u64::MAX);
                    self.b.eq_i64();
                    self.b.if_i64();
                    self.c64(0);
                    self.g(T0);
                    self.b.sub_i64();
                    self.b.else_();
                    self.g(T0);
                    self.g(T1);
                    self.o(op::OP_I64DIVS);
                    self.b.block_end();
                }
                else {
                    self.g(T0);
                    self.g(T1);
                    self.o(op::OP_I64DIVU);
                }
                self.b.block_end();
                self.set_xw(rd, sf, false);
            },
            _ => {
                // LSLV, LSRV, ASRV, RORV: Wasm takes the count modulo the width, as A64
                let kind = i.sub - 0b001000;
                self.xr(rn);
                if sf {
                    self.xr(rm);
                    match kind {
                        0 => self.b.shl_i64(),
                        1 => self.b.shr_u_i64(),
                        2 => self.b.shr_s_i64(),
                        _ => self.b.rotr_i64(),
                    }
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.xr(rm);
                    self.b.wrap_i64_to_i32();
                    match kind {
                        0 => self.b.shl_i32(),
                        1 => self.b.shr_u_i32(),
                        2 => self.b.shr_s_i32(),
                        _ => self.b.rotr_i32(),
                    }
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_x(rd);
            },
        }
    }

    fn data_processing_1(&mut self, i: &Inst) {
        let (rd, rn, sf) = (i.rd, i.rn, i.sf);
        // swap adjacent groups of `bits` bits within each 2*bits
        let swap = |e: &mut Self, bits: u64, m: u64| {
            e.s(T0);
            e.g(T0);
            e.c64(m);
            e.b.and_i64();
            e.c64(bits);
            e.b.shl_i64();
            e.g(T0);
            e.c64(bits);
            e.b.shr_u_i64();
            e.c64(m);
            e.b.and_i64();
            e.b.or_i64();
        };
        match i.sub {
            0 => {
                // RBIT: bits, pairs and nibbles swapped, then REV (the
                // swaps stay in 32-bit lanes: a W register's low word)
                self.xr(rn);
                swap(self, 1, 0x5555_5555_5555_5555);
                swap(self, 2, 0x3333_3333_3333_3333);
                swap(self, 4, 0x0F0F_0F0F_0F0F_0F0F);
                swap(self, 8, 0x00FF_00FF_00FF_00FF);
                swap(self, 16, 0x0000_FFFF_0000_FFFF);
                if sf {
                    self.c64(32);
                    self.b.rotr_i64();
                }
                else {
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                }
                self.set_x(rd);
            },
            1 => {
                // REV16
                self.xr(rn);
                swap(self, 8, 0x00FF_00FF_00FF_00FF);
                self.set_xw(rd, sf, false);
            },
            2 | 3 => {
                // REV32 (and REV of a W register), REV
                self.xr(rn);
                swap(self, 8, 0x00FF_00FF_00FF_00FF);
                swap(self, 16, 0x0000_FFFF_0000_FFFF);
                if i.sub == 3 && sf {
                    self.c64(32);
                    self.b.rotr_i64();
                }
                if !sf {
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                }
                self.set_x(rd);
            },
            4 => {
                // CLZ
                self.xr(rn);
                if sf {
                    self.b.clz_i64();
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.b.clz_i32();
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_x(rd);
            },
            _ => {
                // CLS: CLZ(x ^ (x >> (width - 1))) - 1
                self.xr(rn);
                if sf {
                    self.s(T0);
                    self.g(T0);
                    self.g(T0);
                    self.c64(63);
                    self.b.shr_s_i64();
                    self.b.xor_i64();
                    self.b.clz_i64();
                    self.c64(1);
                    self.b.sub_i64();
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.ti(C0);
                    self.gi(C0);
                    self.c32(31);
                    self.b.shr_s_i32();
                    self.b.xor_i32();
                    self.b.clz_i32();
                    self.c32(1);
                    self.b.sub_i32();
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_x(rd);
            },
        }
    }

    /// The FP and AdvSIMD access check of the compiled EL (CPACR_EL1.FPEN:
    /// EL1 needs bit 0, EL0 both bits): retry the instruction when disabled
    fn fp_check(&mut self, offset: u16) {
        self.load32(state::cpacr_el1 as u32);
        self.c32(20);
        self.b.shr_u_i32();
        self.c32(3);
        self.b.and_i32();
        if self.env.el1 {
            self.c32(1);
            self.b.and_i32();
            self.b.eqz_i32();
        }
        else {
            self.c32(3);
            self.b.ne_i32();
        }
        self.retry_if(offset);
    }
    /// Load a SIMD&FP register of `size_log` bytes (2: S, 3: D, 4: Q) from the
    /// host address in `host` into V[v] (zero-extended to 128 bits)
    fn load_vector(&mut self, host: usize, size_log: u32, v: u8) {
        let at = state::v as u32 + 16 * v as u32;
        // low half
        self.c32(at as i32);
        self.gi(host);
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            self.b
                .guest_load_i64_bits(if size_log == 2 { 32 } else { 64 }, 0);
        }
        else if size_log == 2 {
            self.b.memory_op(op::OP_I64LOAD32U, 2, 0);
        }
        else {
            self.b.memory_op(op::OP_I64LOAD, 3, 0);
        }
        self.b.store_aligned_i64(0);
        // high half
        self.c32(at as i32 + 8);
        if size_log == 4 {
            self.gi(host);
            if WasmBuilder::ATOMIC_GUEST_MEMORY {
                self.b.guest_load_i64(8);
            }
            else {
                self.b.memory_op(op::OP_I64LOAD, 3, 8);
            }
        }
        else {
            self.c64(0);
        }
        self.b.store_aligned_i64(0);
    }
    /// Store V[v]'s low `size_log` bytes at the host address in `host`
    fn store_vector(&mut self, host: usize, size_log: u32, v: u8) {
        let at = state::v as u32 + 16 * v as u32;
        self.gi(host);
        self.load64(at);
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            // (a host of host_store: maybe unaligned)
            self.store_any(if size_log == 2 { 32 } else { 64 }, 0);
        }
        else if size_log == 2 {
            self.b.memory_op(op::OP_I64STORE32, 2, 0);
        }
        else {
            self.b.memory_op(op::OP_I64STORE, 3, 0);
        }
        if size_log == 4 {
            self.gi(host);
            self.load64(at + 8);
            if WasmBuilder::ATOMIC_GUEST_MEMORY {
                self.store_any(64, 8);
            }
            else {
                self.b.memory_op(op::OP_I64STORE, 3, 8);
            }
        }
    }

    fn load_store(&mut self, offset: u16, i: &Inst) {
        let (rt, rn) = (i.rd, i.rn);
        let size_log = i.cond as u32;
        let simd = i.sub & LS_SIMD != 0;
        if simd {
            self.fp_check(offset);
        }
        if i.sub & LS_PREFETCH != 0 {
            // (PRFM: no effect, never a fault)
            return;
        }
        self.sp_check(rn, offset);
        let writeback = i.shift == MODE_PRE || i.shift == MODE_POST;
        // the address in ADDR (the base in T0 for a writeback)
        self.xr_sp(rn);
        if writeback {
            self.s(T0);
            self.g(T0);
        }
        match i.shift {
            MODE_POST => {},
            MODE_REGISTER => {
                self.extended(i.rm, i.ra, i.amount);
                self.b.add_i64();
            },
            _ => {
                if i.imm != 0 {
                    self.c64(i.imm);
                    self.b.add_i64();
                }
            },
        }
        self.s(ADDR);
        let load = i.sub & LS_LOAD != 0;
        if i.sub & LS_UNPRIVILEGED != 0 && self.env.el1 {
            self.host_unprivileged(1 << size_log, !load, offset);
        }
        else if load {
            self.host(1 << size_log, false, offset);
        }
        else {
            self.host_store(1 << size_log, offset, 0);
        }
        if simd {
            self.si(C1);
            if load {
                self.load_vector(C1, size_log, rt);
            }
            else {
                self.store_vector(C1, size_log, rt);
            }
        }
        else if load {
            self.load_value(size_log, i.sub & LS_SIGNED != 0, i.sub & LS_TO_W != 0);
            self.set_x(rt);
        }
        else if i.sub & LS_UNPRIVILEGED != 0 && self.env.el1 {
            self.xr(rt);
            self.store_value(size_log);
        }
        else {
            self.xr(rt);
            self.store_any(8 << size_log.min(3), 0);
        }
        if writeback {
            if i.shift == MODE_POST {
                self.g(T0);
                self.c64(i.imm);
                self.b.add_i64();
            }
            else {
                self.g(ADDR);
            }
            self.set_x_sp(rn);
        }
    }

    fn load_store_pair(&mut self, offset: u16, i: &Inst) {
        let (rt, rt2, rn) = (i.rd, i.ra, i.rn);
        let size_log = i.cond as u32;
        let size = 1u32 << size_log;
        let simd = i.sub & LS_SIMD != 0;
        if simd {
            self.fp_check(offset);
        }
        self.sp_check(rn, offset);
        let writeback = i.shift == MODE_PRE || i.shift == MODE_POST;
        self.xr_sp(rn);
        self.s(T0);
        // the first address in T1, the second in ADDR, both looked up first
        self.g(T0);
        if i.shift != MODE_POST {
            self.c64(i.imm);
            self.b.add_i64();
        }
        self.s(T1);
        let load = i.sub & LS_LOAD != 0;
        self.g(T1);
        self.s(ADDR);
        if load {
            self.host(size, false, offset);
        }
        else {
            self.host_store(size, offset, 0);
        }
        self.si(C1);
        self.g(T1);
        self.c64(size as u64);
        self.b.add_i64();
        self.s(ADDR);
        if load {
            self.host_in(size, false, offset, 1);
        }
        else {
            self.host_store(size, offset, 1);
        }
        self.si(HH);
        if simd {
            // (both read before either register is written, as the interpreter)
            if load {
                if rt == rt2 {
                    self.load_vector(HH, size_log, rt2);
                }
                else {
                    self.load_vector(C1, size_log, rt);
                    self.load_vector(HH, size_log, rt2);
                }
            }
            else {
                self.store_vector(C1, size_log, rt);
                self.store_vector(HH, size_log, rt2);
            }
        }
        else if load {
            let signed = i.sub & LS_SIGNED != 0;
            self.gi(C1);
            self.load_value(size_log, signed, false);
            self.s(T2);
            self.gi(HH);
            self.load_value(size_log, signed, false);
            self.s(T3);
            self.g(T2);
            self.set_x(rt);
            self.g(T3);
            self.set_x(rt2);
        }
        else {
            self.gi(C1);
            self.xr(rt);
            self.store_any(8 << size_log.min(3), 0);
            self.gi(HH);
            self.xr(rt2);
            self.store_any(8 << size_log.min(3), 0);
        }
        if writeback {
            if i.shift == MODE_POST {
                self.g(T0);
                self.c64(i.imm);
                self.b.add_i64();
            }
            else {
                self.g(T1);
            }
            self.set_x_sp(rn);
        }
    }

    /// The chaining lookup at the leave (jitrt::chain): with budget left and
    /// an entry for the PC's page, write the state back and tail-call that
    /// page's function, which counts on from what this one retired
    fn chain(&mut self) {
        self.n_and_steps();
        self.b.get_local(&self.budget);
        self.b.ltu_i32();
        self.b.if_void();
        frame::chain_lookup(
            &mut self.b,
            &self.v[PC],
            &self.v[TAG],
            &self.w[ENT],
            state::a64_code_base as u32,
            ChainEpoch::Local(&self.v[EP]),
        );
        self.writeback();
        self.c32(state::a64_page_chain as i32);
        self.load32(state::a64_page_chain as u32);
        self.n_and_steps();
        self.b.add_i32();
        self.b.store_aligned_i32(0);
        // (the linear page the next function runs at)
        self.c32(state::a64_page_linear as i32);
        self.g(PC);
        self.c64(!0xFFF);
        self.b.and_i64();
        self.b.store_aligned_i64(0);
        self.b.get_local(&self.budget);
        self.n_and_steps();
        self.b.sub_i32();
        frame::chain_call(&mut self.b, &self.w[ENT]);
        self.b.block_end();
        self.b.block_end();
    }
}

impl PageEmitter for Emitter<'_> {
    fn b(&mut self) -> &mut WasmBuilder { &mut self.b }
    fn frame(&self) -> Frame { self.frame.unwrap() }
    fn set_frame(&mut self, frame: Frame) { self.frame = Some(frame) }
    fn levels(&mut self) -> &mut Vec<Level> { &mut self.levels }
    fn levels_ref(&self) -> &[Level] { &self.levels }
    fn span_bytes(&self) -> u64 { PAGE }
    fn pc_offset(&mut self) {
        self.g(PC);
        self.g(BASE);
        self.b.sub_i64();
        self.b.wrap_i64_to_i32();
    }
    fn tee_offset(&mut self) { self.ti(OFF) }
    fn get_offset(&mut self) { self.gi(OFF) }
    fn head(&mut self) {
        self.n_and_steps();
        self.b.get_local(&self.budget);
        self.b.geu_i32();
        self.b.br_if(self.f().exit);
    }
    fn emit_block(&mut self, k: u32, index: &BTreeMap<u16, usize>) {
        let blocks = self.blocks;
        let block = &blocks[k as usize];
        // (the block's native instructions counted at its entry)
        if block.count() != 0 {
            self.gi(N);
            self.c32(block.count() as i32);
            self.b.add_i32();
            self.si(N);
        }
        for (offset, i) in &block.insts {
            self.instruction(*offset, i, index);
        }
        for (offset, i) in &block.insts32 {
            self.instruction32(*offset, i, index);
        }
        match block.end {
            End::Stop => {},
            End::StepAt(o) => {
                let step = self.f().step;
                self.leave_to(step, o as u64);
            },
            End::Next(o) => {
                if !self.falls_into(o, index) {
                    self.goto(o as u64, index);
                }
            },
        }
    }
    fn block_start(&self, k: u32) -> u16 { self.blocks[k as usize].start }
    fn leave_to(&mut self, label: Label, target: u64) {
        self.linear(target);
        // (AArch32's addresses wrap at 4 GiB)
        if self.env.isa != Isa::A64 {
            self.c64(0xFFFF_FFFF);
            self.b.and_i64();
        }
        self.s(PC);
        self.b.br(label);
    }
    fn before_branch(&mut self) {}
    fn span_check(&mut self, _target: u64) {}
    fn direct_loops(&self) -> bool { true }
    fn bounds(&mut self, leave: Label) {
        self.g(PC);
        self.g(BASE);
        self.b.sub_i64();
        self.c64(PAGE);
        self.o(op::OP_I64GEU);
        self.b.br_if(leave);
    }
    fn unknown_offset(&mut self) {
        self.g(PC);
        self.b.call_signature(
            "a64_page_unserved",
            Signature::new(&[WasmType::I64], &[WasmType::I32]),
        );
        self.b.eqz_i32();
        self.b.br_if(self.f().step);
        self.set_exit(EXIT_UNKNOWN);
        self.b.br(self.f().exit);
    }
    fn step_tail(&mut self) {
        self.writeback();
        self.gi(K);
        self.c32(1);
        self.b.add_i32();
        self.si(K);
        self.b
            .call_signature("a64_page_step", Signature::new(&[], &[WasmType::I32]));
        self.si(ST);
        self.gi(ST);
        self.b.if_void();
        self.n_and_steps();
        self.b.return_();
        self.b.block_end();
        self.load_registers();
        self.b.br(self.f().dispatch);
    }
    fn retry_tail(&mut self) {
        self.set_exit(EXIT_RETRY);
        self.b.br(self.f().exit);
    }
    fn leave_tail(&mut self) {
        if !self.env.chaining {
            return;
        }
        if self.env.isa == Isa::T32 {
            // (T32: not inside an IT block, which the next page's function
            // knows nothing of: pages::run's rule for entries)
            self.load32(state::pstate as u32);
            self.c32(cpu::PSTATE_IT as i32);
            self.b.and_i32();
            self.b.eqz_i32();
            self.b.if_void();
            self.chain();
            self.b.block_end();
            return;
        }
        self.chain();
    }
    fn exit_tail(&mut self) {
        self.writeback();
        self.n_and_steps();
    }
    fn lookup_function(&mut self) -> u32 {
        if let Some(f) = self.access {
            return f;
        }
        let f = frame::lookup_function(&mut self.b, &Self::access_abi());
        self.access = Some(f);
        f
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/rust/aarch64/jit/pagegen/a32.rs                                                      0000644 0000000 0000000 00000371332 00000000000 016040  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AArch32's page functions (docs/aarch32-plan.md Q6): EL0's A32 and T32
//! code in the A64 page tier's frame. R0-R14 (X0-X14's low halves) and NZCV
//! stay in the state's memory, so a helper call, the interpreter's execute
//! of the instruction (crate::aarch64::jit::pages::a32_page_helper), needs
//! no copies; branches are native (B, BL, B<c>, CBZ, CBNZ, BX and BLX of a
//! register to the same instruction set; another one retries in the
//! interpreter). What writes the PC otherwise (loads of the PC, LDM and POP
//! with it, data processing into it), changes the instruction set (BLX of
//! an immediate), raises an exception (SVC, BKPT, UDF) or waits (WFE, WFI,
//! YIELD), and the UNPREDICTABLE forms around the PC, are single steps.
//! Inside an IT block every instruction is a helper call or a step (ITSTATE
//! decides their conditions), but in IT blocks of native instructions only
//! (their conditions compiled, ITSTATE left 0, no block starts inside);
//! compiled code is entered at ITSTATE 0 (pages::run), and a step that
//! leaves ITSTATE set ends the activation.

use super::{Block, CompileEnv, Emitter, End, Isa, A0, A1, A2, C0, C1, NZCV, PAGE};
use crate::aarch64::state;
use crate::pagegen::frame::PageEmitter;
use crate::wasmgen::wasm_builder::{Signature, WasmType};
use std::collections::{BTreeMap, BTreeSet};

/// An AArch32 instruction of a page function
#[derive(Clone, Copy)]
pub struct Inst32 {
    /// A32's word, T32's halfword or two (the first in bits 31:16)
    pub word: u32,
    /// 4, or T32's 2
    pub length: u8,
    pub kind: Kind,
}

#[derive(Clone, Copy)]
pub enum Kind {
    /// the interpreter's execute (pages::a32_page_helper)
    Helper,
    /// B, BL, B<c>: to `target` (the page's offset, wrapping), when `cond`
    /// holds (14: always); BL's LR the next instruction's address (T32's
    /// with bit 0 set)
    Branch { target: u64, cond: u8, link: bool },
    /// CBZ, CBNZ (T32)
    CompareBranch { rn: u8, nonzero: bool, target: u64 },
    /// BX, BLX of a register: the same instruction set's target (else a
    /// retry), when `cond` holds (A32's may have one)
    Exchange { rm: u8, link: bool, cond: u8 },
    /// data processing (Q6.2): `op` A32's opcode (ORN 16), `rn` 16 for
    /// none (MOV, MVN), 15 the PC as the instruction set reads it (A32 +8,
    /// T32's Align(PC + 4, 4): ADR's); not into the PC
    Data {
        op: u8,
        s: bool,
        rd: u8,
        rn: u8,
        op2: Operand,
        cond: u8,
    },
    /// MOVW, MOVT
    Wide {
        rd: u8,
        imm: u16,
        top: bool,
        cond: u8,
    },
    /// LDR, STR and their byte, halfword and signed forms: a size of
    /// 1 << `size` bytes; `index`: the offset address accessed, `writeback`
    /// to Rn; Rn 15: a literal (no writeback); never of the PC
    Mem {
        load: bool,
        size: u8,
        signed: bool,
        rt: u8,
        rn: u8,
        offset: Offset,
        add: bool,
        index: bool,
        writeback: bool,
        cond: u8,
    },
    /// LDM, STM, PUSH, POP of R0-R14 (not of the base for LDM, nor with
    /// it and a writeback for STM): `increment`, `before` the addressing mode
    Multiple {
        load: bool,
        rn: u8,
        list: u16,
        increment: bool,
        before: bool,
        writeback: bool,
        cond: u8,
    },
    /// MUL, MLA, MLS (no flags)
    Multiply {
        rd: u8,
        rn: u8,
        rm: u8,
        ra: u8,
        sub: bool,
        cond: u8,
    },
    /// SXTB, SXTH, UXTB, UXTH (Rm rotated right by `rotation`)
    Extend {
        rd: u8,
        rm: u8,
        signed: bool,
        half: bool,
        rotation: u8,
        cond: u8,
    },
    /// LDRD, STRD of an immediate offset (word aligned, in one page)
    Dual {
        load: bool,
        rt: u8,
        rt2: u8,
        rn: u8,
        imm: u32,
        add: bool,
        index: bool,
        writeback: bool,
        cond: u8,
    },
    /// CLZ (0), REV (1), REV16 (2), REVSH (3)
    Bits { op: u8, rd: u8, rm: u8, cond: u8 },
    /// VLDR, VSTR (`single`: one register at Rn plus or minus `imm`; Rn 15
    /// a literal), VLDM, VSTM, VPUSH, VPOP: `count` S (or with `double` D)
    /// registers from `first`, word aligned and in one page (Q6.3)
    FpMemory {
        load: bool,
        double: bool,
        first: u8,
        count: u8,
        rn: u8,
        imm: u16,
        add: bool,
        single: bool,
        writeback: bool,
        cond: u8,
    },
    /// VADD, VSUB, VMUL, VNMUL, VDIV (`op` 0-4) of S (or with `double` D)
    /// registers: on A64's fast path (RN, no flush, IXC set, ordinary
    /// operands and result: Wasm's arithmetic), else the helper (Q6.3)
    FpArith {
        op: u8,
        double: bool,
        d: u8,
        n: u8,
        m: u8,
        cond: u8,
    },
    /// VFP's moves (Q6.3): `kind` 0 VMOV (register), 1 VABS, 2 VNEG of S or
    /// D registers (`double`) m to d; 3 core register `n` to S[d]; 4 S[m] to
    /// core register `d`; 5 core registers `n`, `m` to D[d]; 6 D[d] to them
    FpMove {
        kind: u8,
        double: bool,
        d: u8,
        n: u8,
        m: u8,
        cond: u8,
    },
    /// VLD1, VST1 of multiple single elements (whole D registers `first`..,
    /// `count` of them): word aligned (and to `align` bytes, 0 none) and in
    /// one page; Rm 15 no writeback, 13 the size, else Rm added (Q6.3)
    Vld1 {
        load: bool,
        first: u8,
        count: u8,
        rn: u8,
        rm: u8,
        align: u8,
    },
    /// an IT whose instructions are all native (with their conditions,
    /// pagegen's discovery): nothing at run time, ITSTATE stays 0
    It,
    /// Transfers between core registers and system or extension registers
    /// (Q6.3 part 4): `op` TRANSFER_*; `address` the state's field (the
    /// TPIDR registers) or the element's byte (VMOV scalar: `size` bytes,
    /// `signed`); VDUP's Q (`q`)
    Transfer {
        op: u8,
        rt: u8,
        address: u32,
        size: u8,
        signed: bool,
        q: bool,
        cond: u8,
    },
    /// Advanced SIMD data processing (Q6.3 part 3), unconditional (T32's in
    /// an IT block are helper calls): `form` on D registers (`q` false: the
    /// 64 bits of D[d], D[n], D[m]; the other half of their Q register
    /// stays) or Q registers (Q[d/2], ...)
    Neon {
        form: NeonForm,
        q: bool,
        d: u8,
        n: u8,
        m: u8,
    },
}

/// The template of an Advanced SIMD data processing instruction (Wasm SIMD,
/// neon.rs's lane operations)
#[derive(Clone, Copy)]
pub enum NeonForm {
    /// d = op(n, m), the lanes' operation `op`; `invert_m`: VORN's m
    /// inverted first; `test`: VTST, (n & m) != 0 with `op` the lanes' ne
    Binary { op: u32, invert_m: bool, test: bool },
    /// VBSL, VBIT, VBIF: v128.bitselect(first, second, mask), each 0 (d), 1 (n) or 2 (m)
    Select { first: u8, second: u8, mask: u8 },
    /// d = op(m, amount): VSHL, VSHR by an immediate; `zero`: VSHR.U by the element's size
    Shift { op: u32, amount: u8, zero: bool },
    /// VMOV, VMVN (`kind` 0: d = value), VORR (1: d | value), VBIC (2: d & value) of a modified immediate
    Immediate { value: u64, kind: u8 },
    /// VDUP (scalar): element `index` of D[m] (`esize` bits) in every element
    Dup { esize: u8, index: u8 },
    /// VEXT, VREV: the bytes `lanes` of first:m (0-15 first's, n's or with
    /// `of_m` m's; 16-31 m's)
    Shuffle { lanes: [u8; 16], of_m: bool },
    /// d = op(m): VMVN, VCNT, VABS, VNEG (register)
    Unary { op: u32 },
}

/// (debugging) the kind's name, and a condition's
pub fn kind_name(kind: &Kind) -> String {
    match kind {
        Kind::Helper => "helper".into(),
        Kind::Branch { cond, .. } => format!("branch/{}", cond),
        Kind::CompareBranch { .. } => "cbz".into(),
        Kind::Exchange { cond, .. } => format!("bx/{}", cond),
        Kind::Data { cond, s, .. } => format!("data{}/{}", if *s { "s" } else { "" }, cond),
        Kind::Wide { cond, .. } => format!("wide/{}", cond),
        Kind::Mem { cond, .. } => format!("mem/{}", cond),
        Kind::Multiple { .. } => "multiple".into(),
        Kind::Multiply { cond, .. } => format!("mul/{}", cond),
        Kind::Extend { cond, .. } => format!("extend/{}", cond),
        Kind::Dual { .. } => "dual".into(),
        Kind::Bits { cond, .. } => format!("bits/{}", cond),
        Kind::FpMemory { .. } => "fpmem".into(),
        Kind::FpArith { .. } => "fparith".into(),
        Kind::FpMove { .. } => "fpmove".into(),
        Kind::Vld1 { .. } => "vld1".into(),
        Kind::It => "it".into(),
        Kind::Neon { .. } => "neon".into(),
        Kind::Transfer { op, cond, .. } => format!("transfer{}/{}", op, cond),
    }
}

/// Data processing's second operand
#[derive(Clone, Copy)]
pub enum Operand {
    /// a constant, and its shifter carry (None: C as it was)
    Imm { value: u32, carry: Option<bool> },
    /// a register shifted by a constant: `kind` 0 LSL, 1 LSR, 2 ASR, 3 ROR,
    /// 4 RRX; `amount` 0 none, LSR and ASR up to 32
    Reg { rm: u8, kind: u8, amount: u8 },
    /// a register shifted by Rs's bottom byte (`kind` 0-3)
    RegShift { rm: u8, kind: u8, rs: u8 },
}

/// A load's or store's offset
#[derive(Clone, Copy)]
pub enum Offset {
    Imm(u32),
    /// a register shifted left
    Reg {
        rm: u8,
        shift: u8,
    },
}

// data processing's operations (A32's opcodes; ORN T32's)
const AND: u8 = 0;
const EOR: u8 = 1;
const SUB: u8 = 2;
const RSB: u8 = 3;
const ADD: u8 = 4;
const ADC: u8 = 5;
const SBC: u8 = 6;
const RSC: u8 = 7;
const TST: u8 = 8;
const TEQ: u8 = 9;
const CMP: u8 = 10;
const CMN: u8 = 11;
const ORR: u8 = 12;
const MOV: u8 = 13;
const BIC: u8 = 14;
const MVN: u8 = 15;
const ORN: u8 = 16;
/// no first operand
const NONE: u8 = 16;

/// VFP's and Advanced SIMD's loads and stores with native templates (Q6.3):
/// A32's word, or T32's (whose halfwords are A32's with the condition 1110
/// and, for Advanced SIMD, 1111 1001 for 1111 0100): VLDR, VSTR, VLDM,
/// VSTM (not FLDMX nor FSTMX, nor the UNPREDICTABLE forms) and VLD1, VST1
/// of multiple single elements; None for anything else
fn fp_memory(word: u32, thumb: bool) -> Option<Kind> {
    let rn = (word >> 16 & 15) as u8;
    let simd = if thumb { word >> 24 == 0xF9 } else { word >> 24 == 0xF4 };
    if simd {
        // 1111 0100 A D L 0 Rn Vd type size align Rm, A 0 (multiple structures)
        if word & 1 << 23 != 0 || word & 1 << 20 != 0 || rn == 15 {
            return None;
        }
        let align_field = word >> 4 & 3;
        let count = match word >> 8 & 15 {
            0b0111 if align_field & 2 == 0 => 1,
            0b1010 if align_field != 3 => 2,
            0b0110 if align_field & 2 == 0 => 3,
            0b0010 => 4,
            _ => return None,
        };
        let first = (word >> 22 & 1) << 4 | word >> 12 & 15;
        if first + count > 32 {
            return None;
        }
        return Some(Kind::Vld1 {
            load: word & 1 << 21 != 0,
            first: first as u8,
            count: count as u8,
            rn,
            rm: (word & 15) as u8,
            align: if align_field == 0 { 0 } else { 4 << align_field },
        });
    }
    let cond = (word >> 28) as u8;
    if cond == 15 || word >> 25 & 7 != 0b110 || word >> 9 & 7 != 0b101 {
        return None;
    }
    let (p, u, w, l) = (
        word & 1 << 24 != 0,
        word & 1 << 23 != 0,
        word & 1 << 21 != 0,
        word & 1 << 20 != 0,
    );
    let double = word & 1 << 8 != 0;
    let (vd, bit) = (word >> 12 & 15, word >> 22 & 1);
    let first = if double { bit << 4 | vd } else { vd << 1 | bit };
    let imm8 = word & 0xFF;
    let cond = if thumb { 14 } else { cond };
    if p && !w {
        // VLDR, VSTR
        return Some(Kind::FpMemory {
            load: l,
            double,
            first: first as u8,
            count: 1,
            rn,
            imm: (imm8 * 4) as u16,
            add: u,
            single: true,
            writeback: false,
            cond,
        });
    }
    // VLDM, VSTM: increment after (W 0 or 1), or decrement before with W
    if p == u || p && !w || rn == 15 || double && imm8 & 1 != 0 {
        return None;
    }
    let count = if double { imm8 / 2 } else { imm8 };
    if count == 0 || first + count > 32 || double && count > 16 {
        return None;
    }
    Some(Kind::FpMemory {
        load: l,
        double,
        first: first as u8,
        count: count as u8,
        rn,
        imm: 0,
        add: u,
        single: false,
        writeback: w,
        cond,
    })
}

/// VFP's data processing with native templates (Q6.3): A32's word or
/// T32's (A32's with the condition 1110): the arithmetic of FpArith and
/// the moves of FpMove; None for anything else
/// Kind::Transfer's operations
const TRANSFER_READ: u8 = 0;
const TRANSFER_WRITE: u8 = 1;
const TRANSFER_FPSCR: u8 = 2;
const TRANSFER_FPSCR_FLAGS: u8 = 3;
const TRANSFER_FROM_SCALAR: u8 = 4;
const TRANSFER_TO_SCALAR: u8 = 5;
const TRANSFER_DUP: u8 = 6;

/// MRC and MCR of the thread ID registers (EL0: TPIDRURW and TPIDRURO;
/// PL1's reads of those and TPIDRPRW), VMRS of FPSCR, VMOV between a core
/// register and a scalar, VDUP (core) as native transfers (Q6.3 part 4)
fn transfer(word: u32, thumb: bool, el1: bool) -> Option<Kind> {
    let cond = (word >> 28) as u8;
    if cond == 15 || word >> 24 & 15 != 0b1110 || word & 1 << 4 == 0 {
        return None;
    }
    let cond = if thumb { 14 } else { cond };
    let rt = (word >> 12 & 15) as u8;
    if rt == 15 && word & 0x0FFF_0FFF != 0x0EF1_0A10 || thumb && rt == 13 {
        return None;
    }
    let read = word & 1 << 20 != 0;
    let kind = |op: u8, address: u32, size: u8, signed: bool, q: bool| {
        Some(Kind::Transfer {
            op,
            rt,
            address,
            size,
            signed,
            q,
            cond,
        })
    };
    match word >> 8 & 15 {
        15 => {
            // MRC, MCR p15: opc1 0, CRn 13, CRm 0
            if word >> 21 & 7 != 0 || word >> 16 & 15 != 13 || word & 15 != 0 {
                return None;
            }
            let field = match (word >> 5 & 7, el1) {
                (2, _) => state::tpidr_el0 as u32,
                (3, _) => state::tpidrro_el0 as u32,
                (4, true) => state::tpidr_el1 as u32,
                _ => return None,
            };
            if read {
                kind(TRANSFER_READ, field, 4, false, false)
            }
            else if !el1 && word >> 5 & 7 == 2 {
                kind(TRANSFER_WRITE, field, 4, false, false)
            }
            else {
                None
            }
        },
        10 => {
            // VMRS Rt, FPSCR; VMRS APSR_nzcv, FPSCR
            if word & 0x0FFF_0FFF != 0x0EF1_0A10 {
                return None;
            }
            kind(
                if rt == 15 { TRANSFER_FPSCR_FLAGS } else { TRANSFER_FPSCR },
                0,
                4,
                false,
                false,
            )
        },
        11 => {
            // VMOV (scalar), VDUP (core): D[Vn:N]
            if word & 15 != 0 || rt == 15 {
                return None;
            }
            let n = (word >> 7 & 1) << 4 | word >> 16 & 15;
            let unsigned = word & 1 << 23 != 0;
            if !read && unsigned {
                let (b, q, e) = (word >> 22 & 1, word >> 21 & 1 != 0, word >> 5 & 1);
                if word & 1 << 6 != 0 || b == 1 && e == 1 || q && n & 1 != 0 {
                    return None;
                }
                return kind(
                    TRANSFER_DUP,
                    state::v as u32 + 8 * n,
                    if b == 1 {
                        1
                    }
                    else if e == 1 {
                        2
                    }
                    else {
                        4
                    },
                    false,
                    q,
                );
            }
            let (size, index) = if word & 1 << 22 != 0 {
                (1, (word >> 21 & 1) << 2 | (word >> 5 & 3))
            }
            else if word & 1 << 5 != 0 {
                (2, (word >> 21 & 1) << 1 | (word >> 6 & 1))
            }
            else if word & 1 << 6 == 0 && !unsigned {
                (4, word >> 21 & 1)
            }
            else {
                return None;
            };
            let address = state::v as u32 + 8 * n + size * index;
            if read {
                kind(
                    TRANSFER_FROM_SCALAR,
                    address,
                    size as u8,
                    !unsigned && size < 4,
                    false,
                )
            }
            else {
                kind(TRANSFER_TO_SCALAR, address, size as u8, false, false)
            }
        },
        _ => None,
    }
}

/// Advanced SIMD data processing (A32's 1111 001U, T32's 111U 1111) as a
/// native form (Q6.3 part 3); None: a helper call (the others, and the
/// UNDEFINED forms: odd Q registers, reserved sizes)
fn neon_data(word: u32, thumb: bool) -> Option<Kind> {
    if !cfg!(target_feature = "simd128") {
        return None;
    }
    let word = if thumb {
        if word >> 24 & 0xEF != 0xEF {
            return None;
        }
        0xF200_0000 | (word >> 28 & 1) << 24 | word & 0x00FF_FFFF
    }
    else {
        if word >> 25 != 0b111_1001 {
            return None;
        }
        word
    };
    let d = (word >> 22 & 1) << 4 | word >> 12 & 15;
    let n = (word >> 7 & 1) << 4 | word >> 16 & 15;
    let m = (word >> 5 & 1) << 4 | word & 15;
    let q = word & 1 << 6 != 0;
    let u = word >> 24 & 1;
    let even = |r: u32| !q || r & 1 == 0;
    let neon = |form: NeonForm, registers: &[u32]| {
        registers.iter().all(|&r| even(r)).then_some(Kind::Neon {
            form,
            q,
            d: d as u8,
            n: n as u8,
            m: m as u8,
        })
    };
    if word & 1 << 23 == 0 {
        // three registers of the same length
        let size = (word >> 20 & 3) as usize;
        let lanes = |table: [u32; 4]| Some(table[size]).filter(|&op| op != 0);
        let binary = |op: Option<u32>, test: bool| {
            op.and_then(|op| {
                neon(
                    NeonForm::Binary {
                        op,
                        invert_m: false,
                        test,
                    },
                    &[d, n, m],
                )
            })
        };
        return match (word >> 8 & 15, word >> 4 & 1, u) {
            (0b0001, 1, 0) => neon(
                NeonForm::Binary {
                    op: [0x4E, 0x4F, 0x50, 0x50][size],
                    invert_m: size == 3,
                    test: false,
                },
                &[d, n, m],
            ),
            (0b0001, 1, _) => neon(
                match size {
                    0 => NeonForm::Binary {
                        op: 0x51,
                        invert_m: false,
                        test: false,
                    },
                    1 => NeonForm::Select {
                        first: 1,
                        second: 2,
                        mask: 0,
                    },
                    2 => NeonForm::Select {
                        first: 1,
                        second: 0,
                        mask: 2,
                    },
                    _ => NeonForm::Select {
                        first: 0,
                        second: 1,
                        mask: 2,
                    },
                },
                &[d, n, m],
            ),
            (0b1000, 0, 0) => binary(lanes([0x6E, 0x8E, 0xAE, 0xCE]), false),
            (0b1000, 0, _) => binary(lanes([0x71, 0x91, 0xB1, 0xD1]), false),
            (0b1000, 1, 0) => binary(lanes([0x24, 0x2E, 0x38, 0]), true),
            (0b1000, 1, _) => binary(lanes([0x23, 0x2D, 0x37, 0]), false),
            (0b0011, 0, 0) => binary(lanes([0x27, 0x31, 0x3B, 0]), false),
            (0b0011, 0, _) => binary(lanes([0x28, 0x32, 0x3C, 0]), false),
            (0b0011, 1, 0) => binary(lanes([0x2B, 0x35, 0x3F, 0]), false),
            (0b0011, 1, _) => binary(lanes([0x2C, 0x36, 0x40, 0]), false),
            (0b0110, 0, 0) => binary(lanes([0x78, 0x98, 0xB8, 0]), false),
            (0b0110, 0, _) => binary(lanes([0x79, 0x99, 0xB9, 0]), false),
            (0b0110, 1, 0) => binary(lanes([0x76, 0x96, 0xB6, 0]), false),
            (0b0110, 1, _) => binary(lanes([0x77, 0x97, 0xB7, 0]), false),
            (0b1001, 1, 0) => binary(lanes([0, 0x95, 0xB5, 0]), false),
            _ => None,
        };
    }
    if word & 1 << 4 != 0 {
        if word >> 19 & 7 == 0 && word & 1 << 7 == 0 {
            // one register and a modified immediate (expand_imm: VMVN's and
            // VBIC's inverted)
            let imm8 = (word >> 24 & 1) << 7 | (word >> 16 & 7) << 4 | word & 15;
            let (cmode, op) = (word >> 8 & 15, word >> 5 & 1);
            if cmode == 15 && op == 1 {
                return None;
            }
            let value = crate::aarch64::a32_simd::expand_imm(imm8, cmode, op);
            let kind = if cmode & 1 == 1 && cmode < 12 { 1 + op as u8 } else { 0 };
            return neon(NeonForm::Immediate { value, kind }, &[d]);
        }
        // shifts by an immediate: VSHR, VSHL
        let imm6 = word >> 16 & 63;
        let size = if word & 1 << 7 != 0 {
            3
        }
        else {
            match imm6 >> 3 {
                0 => return None,
                1 => 0,
                2 | 3 => 1,
                _ => 2,
            }
        };
        let esize = 8u32 << size;
        let field = if size == 3 { imm6 } else { imm6 & (2 * esize - 1) };
        return match (word >> 8 & 15, u) {
            (0b0000, _) => {
                let amount = (if size == 3 { 64 } else { 2 * esize }) - field;
                let zero = u == 1 && amount == esize;
                let op =
                    if u == 1 { [0x6D, 0x8D, 0xAD, 0xCD] } else { [0x6C, 0x8C, 0xAC, 0xCC] }[size];
                neon(
                    NeonForm::Shift {
                        op,
                        amount: amount.min(esize - 1) as u8,
                        zero,
                    },
                    &[d, m],
                )
            },
            (0b0101, 0) => neon(
                NeonForm::Shift {
                    op: [0x6B, 0x8B, 0xAB, 0xCB][size],
                    amount: (if size == 3 { field } else { field - esize }) as u8,
                    zero: false,
                },
                &[d, m],
            ),
            _ => None,
        };
    }
    if word >> 20 & 3 != 3 {
        return None;
    }
    if word & 1 << 24 == 0 {
        // VEXT: bytes from imm4 of n:m
        let imm = (word >> 8 & 15) as u8;
        let bytes = if q { 16 } else { 8 };
        if imm >= bytes {
            return None;
        }
        let mut lanes = [0u8; 16];
        for i in 0..bytes {
            let at = i + imm;
            lanes[i as usize] = if at < bytes { at } else { 16 + at - bytes };
        }
        return neon(NeonForm::Shuffle { lanes, of_m: false }, &[d, n, m]);
    }
    if word >> 7 & 31 == 0b11000 {
        // VDUP (scalar)
        let imm4 = word >> 16 & 15;
        let (esize, index) = match imm4.trailing_zeros() {
            0 => (8, imm4 >> 1),
            1 => (16, imm4 >> 2),
            2 => (32, imm4 >> 3),
            _ => return None,
        };
        return neon(
            NeonForm::Dup {
                esize,
                index: index as u8,
            },
            &[d],
        );
    }
    if word & 1 << 11 != 0 {
        return None;
    }
    // two registers, miscellaneous
    let size = (word >> 18 & 3) as usize;
    let unary = |op: u32| neon(NeonForm::Unary { op }, &[d, m]);
    match (word >> 16 & 3, word >> 7 & 15) {
        (0b00, 0b1011) if size == 0 => unary(0x4D),
        (0b00, 0b1010) if size == 0 => unary(0x62),
        (0b01, 0b0110) if size < 3 => unary([0x60, 0x80, 0xA0][size]),
        (0b01, 0b0111) if size < 3 => unary([0x61, 0x81, 0xA1][size]),
        (0b00, rev @ 0..=2) => {
            // VREV64, VREV32, VREV16: the elements reversed in each region
            let (region, element) = (8 >> rev, 1 << size);
            if element >= region {
                return None;
            }
            let mut lanes = [0u8; 16];
            for i in 0..16 {
                let (start, j, k) = (i - i % region, i % region / element, i % element);
                lanes[i as usize] = (start + (region / element - 1 - j) * element + k) as u8;
            }
            neon(NeonForm::Shuffle { lanes, of_m: true }, &[d, m])
        },
        _ => None,
    }
}

fn fp_data(word: u32, thumb: bool) -> Option<Kind> {
    let cond = (word >> 28) as u8;
    if cond == 15 {
        return None;
    }
    let cond = if thumb { 14 } else { cond };
    let double = word & 1 << 8 != 0;
    let (vd, vn, vm) = (word >> 12 & 15, word >> 16 & 15, word & 15);
    let (bd, bn, bm) = (word >> 22 & 1, word >> 7 & 1, word >> 5 & 1);
    let reg = |v: u32, bit: u32| (if double { bit << 4 | v } else { v << 1 | bit }) as u8;
    let (d, n, m) = (reg(vd, bd), reg(vn, bn), reg(vm, bm));
    let op = match word & 0x0FB0_0E50 {
        0x0E30_0A00 => Some(0),
        0x0E30_0A40 => Some(1),
        0x0E20_0A00 => Some(2),
        0x0E20_0A40 => Some(4),
        0x0E80_0A00 => Some(3),
        _ => None,
    };
    if let Some(op) = op {
        return Some(Kind::FpArith {
            op,
            double,
            d,
            n,
            m,
            cond,
        });
    }
    let unary = match word & 0x0FBF_0ED0 {
        0x0EB0_0A40 => Some(0),
        0x0EB0_0AC0 => Some(1),
        0x0EB1_0A40 => Some(2),
        _ => None,
    };
    if let Some(kind) = unary {
        return Some(Kind::FpMove {
            kind,
            double,
            d,
            n: 0,
            m,
            cond,
        });
    }
    let rt = (word >> 12 & 15) as u8;
    if word & 0x0FE0_0F7F == 0x0E00_0A10 && rt != 15 {
        // VMOV between Rt and S[Vn:N]
        let s = (vn << 1 | bn) as u8;
        return Some(if word & 1 << 20 != 0 {
            Kind::FpMove {
                kind: 4,
                double: false,
                d: rt,
                n: 0,
                m: s,
                cond,
            }
        }
        else {
            Kind::FpMove {
                kind: 3,
                double: false,
                d: s,
                n: rt,
                m: 0,
                cond,
            }
        });
    }
    let rt2 = (word >> 16 & 15) as u8;
    if word & 0x0FE0_0FD0 == 0x0C40_0B10 && rt != 15 && rt2 != 15 {
        // VMOV between Rt, Rt2 and D[M:Vm] (to the core registers: not one register twice)
        let dm = (bm << 4 | vm) as u8;
        if word & 1 << 20 != 0 {
            if rt == rt2 {
                return None;
            }
            return Some(Kind::FpMove {
                kind: 6,
                double: true,
                d: dm,
                n: rt,
                m: rt2,
                cond,
            });
        }
        return Some(Kind::FpMove {
            kind: 5,
            double: true,
            d: dm,
            n: rt,
            m: rt2,
            cond,
        });
    }
    None
}

/// DecodeImmShift: the kind and amount of a constant shift (`kind` 0-3, `imm5`)
fn imm_shift(kind: u32, imm5: u32) -> (u8, u8) {
    match (kind, imm5) {
        (1 | 2, 0) => (kind as u8, 32),
        (3, 0) => (4, 1),
        _ => (kind as u8, imm5 as u8),
    }
}

/// The targets of an instruction that ends a block, in the page or not
/// (pagegen::successors keeps the page's)
pub fn targets(i: &Inst32, _offset: u16) -> Vec<u64> {
    match i.kind {
        Kind::Branch { target, .. } | Kind::CompareBranch { target, .. } => vec![target],
        _ => vec![],
    }
}

/// How an instruction ends a block: its in-page targets and whether it
/// falls through; None: it does not
fn control(i: &Inst32, offset: u16) -> Option<(Vec<u64>, bool)> {
    match i.kind {
        Kind::Branch { target, cond, link } => Some((
            if link { vec![target, offset as u64 + i.length as u64] } else { vec![target] },
            cond != 14,
        )),
        Kind::CompareBranch { target, .. } => Some((vec![target], true)),
        // (a return: LDM, POP, LDR of the PC)
        Kind::Multiple { list, cond, .. } if list & 0x8000 != 0 => Some((vec![], cond != 14)),
        Kind::Mem {
            load: true,
            rt: 15,
            cond,
            ..
        } => Some((vec![], cond != 14)),
        Kind::Exchange { link, cond, .. } => Some((
            if link || cond != 14 { vec![offset as u64 + i.length as u64] } else { vec![] },
            cond != 14,
        )),
        _ => None,
    }
}

/// (PL1, cpu_type arm32: docs/aarch32-plan.md R5.3) the instructions a PL1
/// function steps that are helpers otherwise: MSR of CPSR's control or
/// extension field (the mode, the masks: a function is of one privilege,
/// and interrupts are taken between activations) and CP15's writes, MCR
/// and MCRR (the MMU's controls, TLB and cache maintenance)
fn pl1_steps(word: u32, length: u8, thumb: bool) -> bool {
    if !thumb {
        let msr = word & 0x0FB0_F000 == 0x0320_F000 || word & 0x0FB0_FFF0 == 0x0120_F000;
        let mcr = word & 0x0F10_0010 == 0x0E00_0010 || word & 0x0FF0_0000 == 0x0C40_0000;
        return msr && word & 1 << 22 == 0 && word >> 16 & 3 != 0 || mcr && word >> 8 & 15 == 15;
    }
    if length != 4 {
        return false;
    }
    let (hw1, hw2) = (word >> 16, word & 0xFFFF);
    let msr = hw1 & 0xFFE0 == 0xF380 && hw2 & 0xD020 == 0x8000 && hw2 >> 8 & 3 != 0;
    let mcr = (hw1 & 0xEF10 == 0xEE00 && hw2 & 0x10 != 0 || hw1 & 0xEFF0 == 0xEC40)
        && hw2 >> 8 & 15 == 15;
    msr || mcr
}

fn sign_extend(value: u32, bits: u32) -> i64 {
    ((value << (32 - bits)) as i32 >> (32 - bits)) as i64
}

/// A32: the instruction's kind at `offset`; None: a single step
fn a32(word: u32, offset: u16) -> Option<Kind> {
    let cond = (word >> 28) as u8;
    let rd = word >> 12 & 15;
    let rn = word >> 16 & 15;
    if cond == 0xF {
        // the unconditional space: Advanced SIMD (data processing, element
        // and structure loads and stores), PLD and PLI, the barriers and
        // CLREX, VFP's unconditional forms; BLX of an immediate changes the
        // instruction set, CPS, SETEND, RFE and SRS are not EL0's
        let helper = word >> 25 & 7 == 0b001
            || word >> 24 & 15 == 0b0100 && word & 1 << 20 == 0
            || word >> 26 & 3 == 0b01 && word >> 20 & 3 == 0b01
            || word & 0xFFFF_FF00 == 0xF57F_F000
            || word >> 24 & 15 == 0b1110;
        return helper.then_some(Kind::Helper);
    }
    let compare = |w: u32| w >> 23 & 3 == 2 && w & 1 << 20 != 0;
    match word >> 25 & 7 {
        0b101 => Some(Kind::Branch {
            target: (offset as i64 + 8 + sign_extend(word & 0xFF_FFFF, 24) * 4) as u64,
            cond,
            link: word & 1 << 24 != 0,
        }),
        0b100 => {
            // LDM and STM: not the user registers' nor an exception return,
            // nor LDM of the PC; the PC as the base is UNPREDICTABLE
            let writes_pc = word & 1 << 20 != 0 && word & 1 << 15 != 0;
            (word & 1 << 22 == 0 && !writes_pc && rn != 15).then_some(Kind::Helper)
        },
        0b010 | 0b011 => {
            if word & 1 << 25 != 0 && word & 1 << 4 != 0 {
                // the media instructions (UDF among them): Rd in bits 15:12
                // (Rn 1111 the extends' and BFC's without an operand, REV's),
                // the signed multiplies' and USAD8's in bits 19:16
                let udf = word >> 20 & 0xFF == 0x7F && word >> 4 & 15 == 15;
                let high =
                    word >> 23 & 31 == 0b01110 || word >> 20 & 0xFF == 0x78 && word >> 5 & 7 == 0;
                return (!udf && if high { rn != 15 } else { rd != 15 }).then_some(Kind::Helper);
            }
            // LDR, STR, LDRB, STRB (and the unprivileged forms)
            let load = word & 1 << 20 != 0;
            let writeback = word & 1 << 24 == 0 || word & 1 << 21 != 0;
            (!(load && rd == 15) && !(writeback && rn == 15)).then_some(Kind::Helper)
        },
        0b110 | 0b111 => {
            // SVC, else the coprocessors' (VFP, Advanced SIMD's transfers,
            // CP15's EL0 registers; their traps are exceptions)
            (word >> 24 & 15 != 15).then_some(Kind::Helper)
        },
        _ => {
            // data processing and the miscellaneous instructions
            let immediate = word & 1 << 25 != 0;
            let op = word >> 21 & 15;
            let s = word & 1 << 20 != 0;
            if !immediate && word & 0x90 == 0x90 {
                // multiplies, swaps and exclusives, the extra loads and stores
                if word >> 5 & 3 == 0 {
                    return (rd != 15 && rn != 15).then_some(Kind::Helper);
                }
                let load = word & 1 << 20 != 0;
                let dual = !load && word >> 5 & 2 != 0;
                let writeback = word & 1 << 24 == 0 || word & 1 << 21 != 0;
                if load && rd == 15 || dual && rd >= 14 || writeback && rn == 15 {
                    return None;
                }
                return Some(Kind::Helper);
            }
            if op >> 2 == 2 && !s {
                if immediate {
                    // MOVW, MOVT; MSR of an immediate and the hints (NOP the
                    // only one that goes on)
                    if op & 1 == 0 {
                        return (rd != 15).then_some(Kind::Helper);
                    }
                    if word & 0x0FFF_FFFF == 0x0320_F000 {
                        return Some(Kind::Helper);
                    }
                    return (rn != 0 && word & 1 << 22 == 0).then_some(Kind::Helper);
                }
                // BX, BLX of a register
                if word & 0x0FFF_FFD0 == 0x012F_FF10 && word & 15 != 15 {
                    return Some(Kind::Exchange {
                        rm: (word & 15) as u8,
                        link: word & 1 << 5 != 0,
                        cond,
                    });
                }
                return match word >> 4 & 15 {
                    // MRS, MSR of a register
                    0 => (word & 1 << 21 != 0 || rd != 15).then_some(Kind::Helper),
                    // CLZ
                    1 if op == 0b1011 => (rd != 15).then_some(Kind::Helper),
                    // QADD, QSUB, QDADD, QDSUB
                    5 => (rd != 15).then_some(Kind::Helper),
                    // the halfword multiplies
                    8 | 10 | 12 | 14 => (rd != 15 && rn != 15).then_some(Kind::Helper),
                    _ => None,
                };
            }
            (rd != 15 || compare(word)).then_some(Kind::Helper)
        },
    }
}

/// T32: the kind of the instruction (`length` 2 or 4) at `offset`; None: a single step
fn t32(word: u32, length: u8, offset: u16) -> Option<Kind> {
    if length == 2 {
        let hw = word;
        return match hw >> 10 {
            0b010001 => {
                // ADD, CMP, MOV of the high registers; BX, BLX
                let rdn = (hw >> 4 & 8 | hw & 7) as u8;
                match hw >> 8 & 3 {
                    0 | 2 => (rdn != 15).then_some(Kind::Helper),
                    1 => Some(Kind::Helper),
                    _ => {
                        let rm = (hw >> 3 & 15) as u8;
                        (rm != 15).then_some(Kind::Exchange {
                            rm,
                            link: hw & 0x80 != 0,
                            cond: 14,
                        })
                    },
                }
            },
            0b101100..=0b101111 => {
                if hw & 0xF500 == 0xB100 {
                    // CBZ, CBNZ
                    let imm = (hw >> 3 & 0x40 | hw >> 2 & 0x3E) as u64;
                    return Some(Kind::CompareBranch {
                        rn: (hw & 7) as u8,
                        nonzero: hw & 0x800 != 0,
                        target: offset as u64 + 4 + imm,
                    });
                }
                match hw >> 8 & 15 {
                    // POP with the PC
                    0xD => None,
                    // CPS, SETEND
                    0x6 => None,
                    // BKPT
                    0xE => None,
                    // IT; the hints (NOP the only one that goes on)
                    0xF => (hw & 15 != 0 || hw == 0xBF00).then_some(Kind::Helper),
                    _ => Some(Kind::Helper),
                }
            },
            0b110100..=0b110111 => {
                // B<c>; UDF, SVC
                let cond = (hw >> 8 & 15) as u8;
                (cond < 14).then_some(Kind::Branch {
                    target: (offset as i64 + 4 + sign_extend(hw & 0xFF, 8) * 2) as u64,
                    cond,
                    link: false,
                })
            },
            0b111000 | 0b111001 => Some(Kind::Branch {
                target: (offset as i64 + 4 + sign_extend(hw & 0x7FF, 11) * 2) as u64,
                cond: 14,
                link: false,
            }),
            _ => Some(Kind::Helper),
        };
    }
    let hw1 = word >> 16;
    let hw2 = word & 0xFFFF;
    let rd = hw2 >> 8 & 15;
    let rt = hw2 >> 12 & 15;
    let rn = hw1 & 15;
    match hw1 >> 11 {
        0b11101 => {
            if hw1 >> 9 & 3 == 0 {
                if hw1 & 1 << 6 == 0 {
                    // LDM, STM (not of the PC), not SRS nor RFE
                    let kind = hw1 >> 7 & 3;
                    let load = hw1 & 1 << 4 != 0;
                    return ((kind == 1 || kind == 2) && !(load && hw2 & 1 << 15 != 0) && rn != 15)
                        .then_some(Kind::Helper);
                }
                // TBB, TBH branch; the exclusives, LDRD and STRD
                if hw1 & 0xFFF0 == 0xE8D0 && hw2 & 0xFFE0 == 0xF000 {
                    return None;
                }
                let load = hw1 & 1 << 4 != 0;
                return (!(load && (rt == 15 || rd == 15))).then_some(Kind::Helper);
            }
            if hw1 >> 9 & 3 == 1 {
                // data processing (shifted register): Rd the PC only for the
                // compares and tests (S)
                return (rd != 15 || hw1 & 1 << 4 != 0).then_some(Kind::Helper);
            }
            // the coprocessors (VFP, Advanced SIMD)
            Some(Kind::Helper)
        },
        0b11110 => {
            if hw2 & 0x8000 == 0 {
                // data processing (immediates)
                return (rd != 15 || hw1 & 1 << 4 != 0 && hw1 & 1 << 9 == 0)
                    .then_some(Kind::Helper);
            }
            let s = (hw1 >> 10 & 1) as i64;
            let j1 = (hw2 >> 13 & 1) as i64;
            let j2 = (hw2 >> 11 & 1) as i64;
            match hw2 >> 12 & 5 {
                0 => {
                    let cond = (hw1 >> 6 & 15) as u8;
                    if cond < 14 {
                        let imm = (hw1 & 0x3F) as i64 * 2048 + (hw2 & 0x7FF) as i64;
                        let value = (s << 20 | j2 << 19 | j1 << 18) + imm * 2;
                        let signed = value - (s << 21);
                        return Some(Kind::Branch {
                            target: (offset as i64 + 4 + signed) as u64,
                            cond,
                            link: false,
                        });
                    }
                    // MSR, MRS, the hints (NOP), barriers, CLREX; not
                    // BXJ, ERET, SMC, HVC, UDF
                    match hw1 >> 4 & 0x7F {
                        0b0111000 | 0b0111001 | 0b0111011 => Some(Kind::Helper),
                        0b0111010 => (hw2 & 0x7FF == 0).then_some(Kind::Helper),
                        0b0111110 | 0b0111111 => (rd != 15).then_some(Kind::Helper),
                        _ => None,
                    }
                },
                1 | 5 => {
                    // B.W, BL
                    let i1 = 1 - (j1 ^ s);
                    let i2 = 1 - (j2 ^ s);
                    let imm = (hw1 & 0x3FF) as i64 * 2048 + (hw2 & 0x7FF) as i64;
                    let value = (i1 << 23 | i2 << 22) + imm * 2;
                    let signed = value - (s << 24);
                    Some(Kind::Branch {
                        target: (offset as i64 + 4 + signed) as u64,
                        cond: 14,
                        link: hw2 & 0x4000 != 0,
                    })
                },
                // BLX of an immediate: A32's
                _ => None,
            }
        },
        _ => {
            if hw1 >> 9 & 7 == 0b100 {
                // loads and stores of one register: not of the PC
                let load = hw1 & 1 << 4 != 0;
                return (!(load && rt == 15)).then_some(Kind::Helper);
            }
            if hw1 >> 8 & 15 == 0b1010 {
                // data processing (register): shifts, extends (Rn 1111: no
                // addition), parallel additions, REV, CLZ, SEL
                return (rd != 15).then_some(Kind::Helper);
            }
            if hw1 >> 8 & 15 == 0b1011 {
                // multiplies; the long ones (RdLo too) and divides (1111 there)
                let long = hw1 & 1 << 7 != 0 && hw1 >> 4 & 7 != 0b001 && hw1 >> 4 & 7 != 0b011;
                return (rd != 15 && rn != 15 && !(long && rt == 15)).then_some(Kind::Helper);
            }
            // the coprocessors, Advanced SIMD's element and structure accesses
            Some(Kind::Helper)
        },
    }
}

// ---- Q6.2: the native forms' decoding (of instructions the classification
// above runs by helper calls: the PC is never their destination)

/// A32's register list without the PC (else None)
fn list_without_pc(list: u32) -> Option<u16> {
    (list & 0x8000 == 0 && list != 0).then_some(list as u16)
}

/// LDM and STM's native form: not of the base for LDM, nor with it and a
/// writeback for STM (UNKNOWN values)
fn multiple(
    load: bool,
    rn: u8,
    list: u16,
    increment: bool,
    before: bool,
    writeback: bool,
    cond: u8,
) -> Option<Kind> {
    let based = list & 1 << rn != 0;
    if load && based || !load && based && writeback || rn == 15 || list & 1 << 13 != 0 {
        return None;
    }
    Some(Kind::Multiple {
        load,
        rn,
        list,
        increment,
        before,
        writeback,
        cond,
    })
}

/// A32's native forms
fn a32_native(word: u32) -> Option<Kind> {
    let cond = (word >> 28) as u8;
    if cond == 15 {
        return None;
    }
    let rd = (word >> 12 & 15) as u8;
    let rn = (word >> 16 & 15) as u8;
    let rm = (word & 15) as u8;
    let p = word & 1 << 24 != 0;
    let u = word & 1 << 23 != 0;
    let w = word & 1 << 21 != 0;
    let l = word & 1 << 20 != 0;
    match word >> 25 & 7 {
        0b000 | 0b001 => {
            let immediate = word & 1 << 25 != 0;
            if !immediate && word & 0x90 == 0x90 {
                if word >> 4 & 15 == 9 && word >> 24 & 15 == 0 {
                    // MUL, MLA, MLS (no S)
                    let op = word >> 21 & 7;
                    if word & 1 << 20 != 0 || !(op == 0 || op == 1 || op == 3) {
                        return None;
                    }
                    let (rd, ra, rs) = (rn, rd, (word >> 8 & 15) as u8);
                    if rd == 15 || rm == 15 || rs == 15 || op != 0 && ra == 15 {
                        return None;
                    }
                    return Some(Kind::Multiply {
                        rd,
                        rn: rm,
                        rm: rs,
                        ra: if op == 0 { NONE } else { ra },
                        sub: op == 3,
                        cond,
                    });
                }
                // LDRH, STRH, LDRSB, LDRSH (not the unprivileged ones); LDRD,
                // STRD of an immediate offset
                let sh = word >> 5 & 3;
                if !l && sh >= 2 {
                    let writeback = !p || w;
                    if word & 1 << 22 == 0
                        || rd & 1 != 0
                        || rd == 14
                        || !p && w
                        || rn == 15
                        || writeback && (rn == rd || rn == rd + 1)
                    {
                        return None;
                    }
                    return Some(Kind::Dual {
                        load: sh == 2,
                        rt: rd,
                        rt2: rd + 1,
                        rn,
                        imm: word >> 4 & 0xF0 | word & 15,
                        add: u,
                        index: p,
                        writeback,
                        cond,
                    });
                }
                let (size, signed) = match (l, sh) {
                    (false, 1) | (true, 1) => (1, false),
                    (true, 2) => (0, true),
                    (true, 3) => (1, true),
                    _ => return None,
                };
                if !p && w || rd == 15 || l && (!p || w) && rn == rd || (!p || w) && rn == 15 {
                    return None;
                }
                let offset = if word & 1 << 22 != 0 {
                    Offset::Imm(word >> 4 & 0xF0 | word & 15)
                }
                else {
                    if rm == 15 {
                        return None;
                    }
                    Offset::Reg { rm, shift: 0 }
                };
                return Some(Kind::Mem {
                    load: l,
                    size,
                    signed,
                    rt: rd,
                    rn,
                    offset,
                    add: u,
                    index: p,
                    writeback: !p || w,
                    cond,
                });
            }
            let op = (word >> 21 & 15) as u8;
            let s = word & 1 << 20 != 0;
            if word & 0x0FFF_0FF0 == 0x016F_0F10 && rd != 15 && rm != 15 {
                return Some(Kind::Bits {
                    op: 0,
                    rd,
                    rm,
                    cond,
                });
            }
            if op >> 2 == 2 && !s {
                // MOVW, MOVT; the miscellaneous instructions
                if immediate && op & 1 == 0 && rd != 15 {
                    return Some(Kind::Wide {
                        rd,
                        imm: (word >> 4 & 0xF000 | word & 0xFFF) as u16,
                        top: op == 10,
                        cond,
                    });
                }
                return None;
            }
            let op2 = if immediate {
                let rotation = (word >> 8 & 15) * 2;
                let value = (word & 0xFF).rotate_right(rotation);
                Operand::Imm {
                    value,
                    carry: (rotation != 0).then_some(value >> 31 != 0),
                }
            }
            else if word & 1 << 4 == 0 {
                let (kind, amount) = imm_shift(word >> 5 & 3, word >> 7 & 31);
                Operand::Reg { rm, kind, amount }
            }
            else {
                // shifted by a register (none of them the PC)
                let rs = (word >> 8 & 15) as u8;
                if rs == 15 || rm == 15 || rn == 15 {
                    return None;
                }
                Operand::RegShift {
                    rm,
                    kind: (word >> 5 & 3) as u8,
                    rs,
                }
            };
            let rn = if op == MOV || op == MVN { NONE } else { rn };
            Some(Kind::Data {
                op,
                s,
                rd,
                rn,
                op2,
                cond,
            })
        },
        0b010 | 0b011 => {
            if word & 1 << 25 != 0 && word & 1 << 4 != 0 {
                // REV, REV16, REVSH
                let bits = match word & 0x0FFF_0FF0 {
                    0x06BF_0F30 => Some(1),
                    0x06BF_0FB0 => Some(2),
                    0x06FF_0FB0 => Some(3),
                    _ => None,
                };
                if let Some(op) = bits {
                    return (rd != 15 && rm != 15).then_some(Kind::Bits { op, rd, rm, cond });
                }
                // SXTB, SXTH, UXTB, UXTH (not their adding forms)
                if word >> 23 & 3 == 0b01 && word >> 4 & 15 == 7 && rn == 15 && rd != 15 && rm != 15
                {
                    let op = word >> 20 & 7;
                    let (signed, half) = match op {
                        0b010 => (true, false),
                        0b011 => (true, true),
                        0b110 => (false, false),
                        0b111 => (false, true),
                        _ => return None,
                    };
                    return Some(Kind::Extend {
                        rd,
                        rm,
                        signed,
                        half,
                        rotation: (word >> 10 & 3) as u8 * 8,
                        cond,
                    });
                }
                return None;
            }
            // LDR, STR, LDRB, STRB (not the unprivileged forms); register
            // offsets shifted left only
            if !p && w || rd == 15 || l && (!p || w) && rn == rd || (!p || w) && rn == 15 {
                return None;
            }
            let offset = if word & 1 << 25 == 0 {
                Offset::Imm(word & 0xFFF)
            }
            else {
                if word >> 5 & 3 != 0 || rm == 15 {
                    return None;
                }
                Offset::Reg {
                    rm,
                    shift: (word >> 7 & 31) as u8,
                }
            };
            let size = if word & 1 << 22 != 0 { 0 } else { 2 };
            Some(Kind::Mem {
                load: l,
                size,
                signed: false,
                rt: rd,
                rn,
                offset,
                add: u,
                index: p,
                writeback: !p || w,
                cond,
            })
        },
        0b100 => {
            if word & 1 << 22 != 0 {
                return None;
            }
            multiple(l, rn, list_without_pc(word & 0xFFFF)?, u, p, w, cond)
        },
        _ => None,
    }
}

/// T32's modified immediate (ThumbExpandImm_C): the value and its carry
fn thumb_expand(imm12: u32) -> Option<(u32, Option<bool>)> {
    let imm8 = imm12 & 0xFF;
    if imm12 >> 10 == 0 {
        if imm12 >> 8 & 3 != 0 && imm8 == 0 {
            return None;
        }
        let value = match imm12 >> 8 & 3 {
            0 => imm8,
            1 => imm8 << 16 | imm8,
            2 => imm8 << 24 | imm8 << 8,
            _ => imm8 * 0x0101_0101,
        };
        return Some((value, None));
    }
    let value = (0x80 | imm12 & 0x7F).rotate_right(imm12 >> 7 & 31);
    Some((value, Some(value >> 31 != 0)))
}

/// T32's data processing operations (bits 24:21 of their encodings) as A32's
fn t32_data(op: u32, s: bool, rd: u8, rn: u8, op2: Operand) -> Option<Kind> {
    let (op, rd, rn) = match op {
        0b0000 if rd == 15 => (TST, 0, rn),
        0b0000 => (AND, rd, rn),
        0b0001 => (BIC, rd, rn),
        0b0010 if rn == 15 => (MOV, rd, NONE),
        0b0010 => (ORR, rd, rn),
        0b0011 if rn == 15 => (MVN, rd, NONE),
        0b0011 => (ORN, rd, rn),
        0b0100 if rd == 15 => (TEQ, 0, rn),
        0b0100 => (EOR, rd, rn),
        0b1000 if rd == 15 => (CMN, 0, rn),
        0b1000 => (ADD, rd, rn),
        0b1010 => (ADC, rd, rn),
        0b1011 => (SBC, rd, rn),
        0b1101 if rd == 15 => (CMP, 0, rn),
        0b1101 => (SUB, rd, rn),
        0b1110 => (RSB, rd, rn),
        _ => return None,
    };
    // (the compares and tests only with S; the PC nowhere else; SP only as ADD's and SUB's)
    let compare = matches!(op, TST | TEQ | CMN | CMP);
    if compare && !s || rd == 15 || rn == 15 {
        return None;
    }
    if (rd == 13 || rn == 13) && !matches!(op, ADD | SUB | CMP | CMN) {
        return None;
    }
    if let Operand::Reg { rm: 13 | 15, .. } = op2 {
        return None;
    }
    Some(Kind::Data {
        op,
        s,
        rd,
        rn,
        op2,
        cond: 14,
    })
}

/// T32's native forms (outside IT blocks: the 16-bit forms set flags)
fn t32_native(word: u32, length: u8) -> Option<Kind> {
    if length == 2 {
        let hw = word;
        let r = |at: u32| (hw >> at & 7) as u8;
        let reg = |rm: u8| Operand::Reg {
            rm,
            kind: 0,
            amount: 0,
        };
        let imm = |value: u32| Operand::Imm { value, carry: None };
        let data = |op: u8, rd: u8, rn: u8, op2: Operand| {
            Some(Kind::Data {
                op,
                s: true,
                rd,
                rn,
                op2,
                cond: 14,
            })
        };
        let mem = |load: bool, size: u8, signed: bool, rt: u8, rn: u8, offset: Offset| {
            Some(Kind::Mem {
                load,
                size,
                signed,
                rt,
                rn,
                offset,
                add: true,
                index: true,
                writeback: false,
                cond: 14,
            })
        };
        return match hw >> 11 {
            // LSL, LSR, ASR of a constant (LSL #0: MOVS)
            0b00000..=0b00010 => {
                let (kind, amount) = imm_shift(hw >> 11, hw >> 6 & 31);
                data(
                    MOV,
                    r(0),
                    NONE,
                    Operand::Reg {
                        rm: r(3),
                        kind,
                        amount,
                    },
                )
            },
            0b00011 => {
                let op = if hw & 1 << 9 != 0 { SUB } else { ADD };
                data(
                    op,
                    r(0),
                    r(3),
                    if hw & 1 << 10 != 0 { imm(hw >> 6 & 7) } else { reg(r(6)) },
                )
            },
            0b00100 => data(MOV, r(8), NONE, imm(hw & 0xFF)),
            0b00101 => data(CMP, 0, r(8), imm(hw & 0xFF)),
            0b00110 => data(ADD, r(8), r(8), imm(hw & 0xFF)),
            0b00111 => data(SUB, r(8), r(8), imm(hw & 0xFF)),
            0b01000 => {
                if hw & 1 << 10 == 0 {
                    // data processing (registers): not the shifts by a register, nor MULS
                    let (rdn, rm) = (r(0), r(3));
                    let shift = |kind: u8| {
                        data(
                            MOV,
                            rdn,
                            NONE,
                            Operand::RegShift {
                                rm: rdn,
                                kind,
                                rs: rm,
                            },
                        )
                    };
                    return match hw >> 6 & 15 {
                        0b0000 => data(AND, rdn, rdn, reg(rm)),
                        0b0001 => data(EOR, rdn, rdn, reg(rm)),
                        0b0010 => shift(0),
                        0b0011 => shift(1),
                        0b0100 => shift(2),
                        0b0111 => shift(3),
                        0b0101 => data(ADC, rdn, rdn, reg(rm)),
                        0b0110 => data(SBC, rdn, rdn, reg(rm)),
                        0b1000 => data(TST, 0, rdn, reg(rm)),
                        0b1001 => data(RSB, rdn, rm, imm(0)),
                        0b1010 => data(CMP, 0, rdn, reg(rm)),
                        0b1011 => data(CMN, 0, rdn, reg(rm)),
                        0b1100 => data(ORR, rdn, rdn, reg(rm)),
                        0b1110 => data(BIC, rdn, rdn, reg(rm)),
                        0b1111 => data(MVN, rdn, NONE, reg(rm)),
                        _ => None,
                    };
                }
                // ADD, CMP, MOV of the high registers (not of the PC)
                let rdn = (hw >> 4 & 8 | hw & 7) as u8;
                let rm = (hw >> 3 & 15) as u8;
                if rm == 15 || rdn == 15 {
                    return None;
                }
                match hw >> 8 & 3 {
                    0 => Some(Kind::Data {
                        op: ADD,
                        s: false,
                        rd: rdn,
                        rn: rdn,
                        op2: reg(rm),
                        cond: 14,
                    }),
                    1 => data(CMP, 0, rdn, reg(rm)),
                    2 => Some(Kind::Data {
                        op: MOV,
                        s: false,
                        rd: rdn,
                        rn: NONE,
                        op2: reg(rm),
                        cond: 14,
                    }),
                    _ => None,
                }
            },
            0b01001 => mem(true, 2, false, r(8), 15, Offset::Imm((hw & 0xFF) * 4)),
            0b01010 | 0b01011 => {
                let (load, size, signed) = match hw >> 9 & 7 {
                    0 => (false, 2, false),
                    1 => (false, 1, false),
                    2 => (false, 0, false),
                    3 => (true, 0, true),
                    4 => (true, 2, false),
                    5 => (true, 1, false),
                    6 => (true, 0, false),
                    _ => (true, 1, true),
                };
                mem(
                    load,
                    size,
                    signed,
                    r(0),
                    r(3),
                    Offset::Reg { rm: r(6), shift: 0 },
                )
            },
            0b01100 | 0b01101 => mem(
                hw & 1 << 11 != 0,
                2,
                false,
                r(0),
                r(3),
                Offset::Imm((hw >> 6 & 31) * 4),
            ),
            0b01110 | 0b01111 => mem(
                hw & 1 << 11 != 0,
                0,
                false,
                r(0),
                r(3),
                Offset::Imm(hw >> 6 & 31),
            ),
            0b10000 | 0b10001 => mem(
                hw & 1 << 11 != 0,
                1,
                false,
                r(0),
                r(3),
                Offset::Imm((hw >> 6 & 31) * 2),
            ),
            0b10010 | 0b10011 => mem(
                hw & 1 << 11 != 0,
                2,
                false,
                r(8),
                13,
                Offset::Imm((hw & 0xFF) * 4),
            ),
            // ADR, ADD of SP (no flags)
            0b10100 => Some(Kind::Data {
                op: ADD,
                s: false,
                rd: r(8),
                rn: 15,
                op2: imm((hw & 0xFF) * 4),
                cond: 14,
            }),
            0b10101 => Some(Kind::Data {
                op: ADD,
                s: false,
                rd: r(8),
                rn: 13,
                op2: imm((hw & 0xFF) * 4),
                cond: 14,
            }),
            0b10110 | 0b10111 => match hw >> 8 & 15 {
                0b0000 => Some(Kind::Data {
                    op: if hw & 0x80 != 0 { SUB } else { ADD },
                    s: false,
                    rd: 13,
                    rn: 13,
                    op2: imm((hw & 0x7F) * 4),
                    cond: 14,
                }),
                0b0010 => Some(Kind::Extend {
                    rd: r(0),
                    rm: r(3),
                    signed: hw & 0x80 == 0,
                    half: hw & 0x40 == 0,
                    rotation: 0,
                    cond: 14,
                }),
                // REV, REV16, REVSH
                0b1010 if hw >> 6 & 3 != 2 => Some(Kind::Bits {
                    op: [1, 2, 0, 3][(hw >> 6 & 3) as usize],
                    rd: r(0),
                    rm: r(3),
                    cond: 14,
                }),
                // PUSH (LR with M), POP (without the PC)
                0b0100 | 0b0101 => multiple(
                    false,
                    13,
                    (hw & 0xFF | (hw & 0x100) << 6) as u16,
                    false,
                    true,
                    true,
                    14,
                ),
                0b1100 => multiple(true, 13, (hw & 0xFF) as u16, true, false, true, 14),
                _ => None,
            },
            // STM, LDM (the writeback unless LDM's base is listed)
            0b11000 => multiple(false, r(8), (hw & 0xFF) as u16, true, false, true, 14),
            0b11001 => {
                let list = (hw & 0xFF) as u16;
                if list & 1 << r(8) != 0 {
                    return None;
                }
                multiple(true, r(8), list, true, false, true, 14)
            },
            _ => None,
        };
    }
    let hw1 = word >> 16;
    let hw2 = word & 0xFFFF;
    let rn = (hw1 & 15) as u8;
    let rd = (hw2 >> 8 & 15) as u8;
    let rt = (hw2 >> 12 & 15) as u8;
    let rm = (hw2 & 15) as u8;
    let s = hw1 & 1 << 4 != 0;
    t32_native32(hw1, hw2, rn, rd, rt, rm, s)
}

fn t32_native32(hw1: u32, hw2: u32, rn: u8, rd: u8, rt: u8, rm: u8, s: bool) -> Option<Kind> {
    if hw1 >> 11 == 0b11110 && hw2 & 0x8000 == 0 {
        if hw1 & 1 << 9 == 0 {
            let (value, carry) =
                thumb_expand((hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | hw2 & 0xFF)?;
            return t32_data(hw1 >> 5 & 15, s, rd, rn, Operand::Imm { value, carry });
        }
        // the plain binary immediates: ADDW, SUBW (ADR with the PC), MOVW, MOVT
        let imm12 = (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | hw2 & 0xFF;
        if rd == 15 || rd == 13 && rn != 13 {
            return None;
        }
        return match hw1 >> 4 & 31 {
            0b00000 => Some(Kind::Data {
                op: ADD,
                s: false,
                rd,
                rn,
                op2: Operand::Imm {
                    value: imm12,
                    carry: None,
                },
                cond: 14,
            }),
            0b01010 => Some(Kind::Data {
                op: SUB,
                s: false,
                rd,
                rn,
                op2: Operand::Imm {
                    value: imm12,
                    carry: None,
                },
                cond: 14,
            }),
            0b00100 | 0b01100 => Some(Kind::Wide {
                rd,
                imm: ((hw1 & 15) << 12 | imm12) as u16,
                top: hw1 & 1 << 7 != 0,
                cond: 14,
            }),
            _ => None,
        };
    }
    if hw1 >> 9 == 0b1110101 {
        // data processing (shifted register)
        let (kind, amount) = imm_shift(hw2 >> 4 & 3, (hw2 >> 12 & 7) << 2 | hw2 >> 6 & 3);
        return t32_data(hw1 >> 5 & 15, s, rd, rn, Operand::Reg { rm, kind, amount });
    }
    if hw1 >> 9 == 0b1110100 && hw1 & 1 << 6 == 0 {
        // LDM, STM (IA, DB): one register at least (one as the interpreter
        // takes it, t32_block_transfer), neither SP nor the PC
        let mode = hw1 >> 7 & 3;
        let list = hw2 as u16;
        if !(mode == 1 || mode == 2) || list == 0 || list & 0xA000 != 0 {
            return None;
        }
        return multiple(
            hw1 & 1 << 4 != 0,
            rn,
            list,
            mode == 1,
            mode == 2,
            hw1 & 1 << 5 != 0,
            14,
        );
    }
    if hw1 >> 9 == 0b1111100 && hw1 & 1 << 8 == 0 || hw1 >> 8 == 0b11111001 && hw1 & 1 << 4 != 0 {
        // loads and stores of one register
        let load = hw1 & 1 << 4 != 0;
        let signed = hw1 & 1 << 8 != 0;
        let size = (hw1 >> 5 & 3) as u8;
        if size == 3 || rt == 15 || rt == 13 && !(size == 2 && !signed) {
            return None;
        }
        if rn == 15 {
            // a literal
            return load.then_some(Kind::Mem {
                load,
                size,
                signed,
                rt,
                rn,
                offset: Offset::Imm(hw2 & 0xFFF),
                add: hw1 & 1 << 7 != 0,
                index: true,
                writeback: false,
                cond: 14,
            });
        }
        let (offset, add, index, writeback) = if hw1 & 1 << 7 != 0 {
            (Offset::Imm(hw2 & 0xFFF), true, true, false)
        }
        else if hw2 & 1 << 11 != 0 {
            let (p, u, w) = (hw2 & 1 << 10 != 0, hw2 & 1 << 9 != 0, hw2 & 1 << 8 != 0);
            // (LDRT and the like: P U W 1 1 0)
            if p && u && !w || !p && !w {
                return None;
            }
            (Offset::Imm(hw2 & 0xFF), u, p, w || !p)
        }
        else if hw2 >> 6 & 63 == 0 {
            if rm == 13 || rm == 15 {
                return None;
            }
            (
                Offset::Reg {
                    rm,
                    shift: (hw2 >> 4 & 3) as u8,
                },
                true,
                true,
                false,
            )
        }
        else {
            return None;
        };
        if writeback && (rn == rt || rn == 15) {
            return None;
        }
        return Some(Kind::Mem {
            load,
            size,
            signed,
            rt,
            rn,
            offset,
            add,
            index,
            writeback,
            cond: 14,
        });
    }
    if hw1 >> 4 == 0b111110110000 && hw2 >> 4 & 15 <= 1 {
        // MUL, MLA, MLS
        let ra = rt;
        let sub = hw2 >> 4 & 15 == 1;
        if rd == 15
            || rd == 13
            || rn == 15
            || rn == 13
            || rm == 15
            || rm == 13
            || sub && ra == 15
            || ra == 13
        {
            return None;
        }
        return Some(Kind::Multiply {
            rd,
            rn,
            rm,
            ra: if ra == 15 { NONE } else { ra },
            sub,
            cond: 14,
        });
    }
    if hw1 >> 7 == 0b111110100 && hw2 >> 12 == 15 && hw2 & 0xF0 == 0 {
        // LSL, LSR, ASR, ROR of a register (Rm the amount)
        if rd >= 13 || rn >= 13 || rm >= 13 {
            return None;
        }
        return Some(Kind::Data {
            op: MOV,
            s,
            rd,
            rn: NONE,
            op2: Operand::RegShift {
                rm: rn,
                kind: (hw1 >> 5 & 3) as u8,
                rs: rm,
            },
            cond: 14,
        });
    }
    if (hw1 & 0xFFF0 == 0xFA90 || hw1 & 0xFFF0 == 0xFAB0) && hw2 & 0xF0C0 == 0xF080 && rn == rm {
        // REV, REV16, REVSH; CLZ (not RBIT)
        let op = if hw1 & 0xFFF0 == 0xFAB0 {
            if hw2 & 0x30 != 0 {
                return None;
            }
            0
        }
        else {
            match hw2 >> 4 & 3 {
                0 => 1,
                1 => 2,
                3 => 3,
                _ => return None,
            }
        };
        return (rd < 13 && rm < 13).then_some(Kind::Bits {
            op,
            rd,
            rm,
            cond: 14,
        });
    }
    if hw1 >> 9 == 0b1110100 && hw1 & 1 << 6 != 0 && (hw1 & 1 << 8 != 0 || hw1 & 1 << 5 != 0) {
        // LDRD, STRD of an immediate offset
        let rt2 = rd;
        let (p, u, w, load) = (
            hw1 & 1 << 8 != 0,
            hw1 & 1 << 7 != 0,
            hw1 & 1 << 5 != 0,
            hw1 & 1 << 4 != 0,
        );
        if rt >= 13 || rt2 >= 13 || rn == 15 || load && rt == rt2 || w && (rn == rt || rn == rt2) {
            return None;
        }
        return Some(Kind::Dual {
            load,
            rt,
            rt2,
            rn,
            imm: (hw2 & 0xFF) * 4,
            add: u,
            index: p,
            writeback: w,
            cond: 14,
        });
    }
    if hw1 >> 7 == 0b111110100 && rn == 15 && hw2 >> 12 == 15 && hw2 & 0x80 != 0 && hw2 & 0x40 == 0
    {
        // SXTH, UXTH, SXTB, UXTB
        let (signed, half) = match hw1 >> 4 & 7 {
            0b000 => (true, true),
            0b001 => (false, true),
            0b100 => (true, false),
            0b101 => (false, false),
            _ => return None,
        };
        if rd >= 13 || rm >= 13 {
            return None;
        }
        return Some(Kind::Extend {
            rd,
            rm,
            signed,
            half,
            rotation: (hw2 >> 4 & 3) as u8 * 8,
            cond: 14,
        });
    }
    None
}

/// A32's returns: LDM of the PC (not the user registers', not of the base
/// nor SP), LDR of the PC (not unprivileged); the target's instruction set
/// checked at run time (another one: the interpreter's)
fn a32_return(word: u32) -> Option<Kind> {
    let cond = (word >> 28) as u8;
    if cond == 15 {
        return None;
    }
    let rn = (word >> 16 & 15) as u8;
    let (p, u, w, l) = (
        word & 1 << 24 != 0,
        word & 1 << 23 != 0,
        word & 1 << 21 != 0,
        word & 1 << 20 != 0,
    );
    match word >> 25 & 7 {
        0b100 if l && word & 1 << 22 == 0 && word & 0x8000 != 0 => {
            let list = word as u16;
            if rn == 15 || list & 1 << rn != 0 || list & 0x2000 != 0 {
                return None;
            }
            Some(Kind::Multiple {
                load: true,
                rn,
                list,
                increment: u,
                before: p,
                writeback: w,
                cond,
            })
        },
        0b010 if l && word & 1 << 22 == 0 && word >> 12 & 15 == 15 => {
            if !p && w || (!p || w) && rn == 15 {
                return None;
            }
            Some(Kind::Mem {
                load: true,
                size: 2,
                signed: false,
                rt: 15,
                rn,
                offset: Offset::Imm(word & 0xFFF),
                add: u,
                index: p,
                writeback: !p || w,
                cond,
            })
        },
        _ => None,
    }
}

/// T32's returns: POP and LDM of the PC, LDR of the PC
fn t32_return(word: u32, length: u8) -> Option<Kind> {
    if length == 2 {
        // POP with the PC
        return (word >> 8 == 0xBD).then_some(Kind::Multiple {
            load: true,
            rn: 13,
            list: (word & 0xFF | 0x8000) as u16,
            increment: true,
            before: false,
            writeback: true,
            cond: 14,
        });
    }
    let hw1 = word >> 16;
    let hw2 = word & 0xFFFF;
    let rn = (hw1 & 15) as u8;
    if hw1 >> 9 == 0b1110100 && hw1 & 1 << 6 == 0 && hw1 & 1 << 4 != 0 {
        // LDM.W (IA, DB) of the PC: not of LR too, nor SP, nor of the base with a writeback
        let mode = hw1 >> 7 & 3;
        let list = hw2 as u16;
        let writeback = hw1 & 1 << 5 != 0;
        if !(mode == 1 || mode == 2)
            || list & 0x8000 == 0
            || list & 0x6000 != 0
            || rn == 15
            || list & 1 << rn != 0
        {
            return None;
        }
        return Some(Kind::Multiple {
            load: true,
            rn,
            list,
            increment: mode == 1,
            before: mode == 2,
            writeback,
            cond: 14,
        });
    }
    if hw1 & 0xFFF0 == 0xF8D0
        || hw1 & 0xFF7F == 0xF85F
        || hw1 & 0xFFF0 == 0xF850 && hw2 & 0x0800 != 0
    {
        // LDR.W of the PC: an offset of 12 bits, a literal, or 8 bits indexed
        if hw2 >> 12 != 15 {
            return None;
        }
        let (offset, add, index, writeback) = if rn == 15 {
            (hw2 & 0xFFF, hw1 & 1 << 7 != 0, true, false)
        }
        else if hw1 & 1 << 7 != 0 {
            (hw2 & 0xFFF, true, true, false)
        }
        else {
            let (p, u, w) = (hw2 & 1 << 10 != 0, hw2 & 1 << 9 != 0, hw2 & 1 << 8 != 0);
            if p && u && !w || !p && !w {
                return None;
            }
            (hw2 & 0xFF, u, p, w || !p)
        };
        if writeback && rn == 15 {
            return None;
        }
        return Some(Kind::Mem {
            load: true,
            size: 2,
            signed: false,
            rt: 15,
            rn,
            offset: Offset::Imm(offset),
            add,
            index,
            writeback,
            cond: 14,
        });
    }
    None
}

/// An instruction of an IT block as a native form of condition `cond`: the
/// 16-bit forms that set the flags outside one do not inside; None for
/// what might leave (loads and stores, branches)
fn t32_native_it(word: u32, length: u8, cond: u8) -> Option<Kind> {
    let mut kind = t32_native(word, length)?;
    match &mut kind {
        Kind::Data { op, s, cond: c, .. } => {
            if length == 2 && !matches!(*op, CMP | CMN | TST) {
                *s = false;
            }
            *c = cond;
        },
        Kind::Wide { cond: c, .. }
        | Kind::Multiply { cond: c, .. }
        | Kind::Extend { cond: c, .. }
        | Kind::Bits { cond: c, .. } => *c = cond,
        _ => return None,
    }
    Some(kind)
}

/// The instructions an IT instruction's mask covers
fn it_count(hw: u32) -> u32 { 4 - (hw & 15).trailing_zeros() }

/// Discovery (pagegen::discover's, AArch32's instructions): blocks from the
/// entries the runtime saw, their static targets and fall-throughs
pub(super) fn discover(
    bytes: &[u8],
    entries: &[u16],
    env: &CompileEnv,
) -> (Vec<Block>, BTreeMap<u16, usize>) {
    let thumb = env.isa == Isa::T32;
    let align: u16 = if thumb { 2 } else { 4 };
    let half = |o: u16| u16::from_le_bytes([bytes[o as usize], bytes[o as usize + 1]]) as u32;
    // the instruction at `o` and its length; None at a T32 instruction the
    // page splits (stepped: the interpreter fetches across)
    let fetch = |o: u16| -> Option<(u32, u8)> {
        if !thumb {
            return Some((
                u32::from_le_bytes(bytes[o as usize..o as usize + 4].try_into().unwrap()),
                4,
            ));
        }
        let first = half(o);
        if !crate::aarch64::a32::t32_wide(first) {
            return Some((first, 2));
        }
        if o as u64 + 4 > PAGE {
            return None;
        }
        Some((first << 16 | half(o + 2), 4))
    };
    // the instructions IT blocks cover (helpers or steps only), but those of
    // native IT blocks (their conditions)
    let mut covered: BTreeSet<u16> = BTreeSet::new();
    let native_it: std::cell::RefCell<BTreeMap<u16, u8>> = Default::default();
    let decode = |o: u16, covered: &mut BTreeSet<u16>| -> (Option<Inst32>, u16) {
        let Some((word, length)) = fetch(o)
        else {
            return (None, 2);
        };
        let mut kind = if thumb { t32(word, length, o) } else { a32(word, o) };
        if env.el1 && pl1_steps(word, length, thumb) {
            kind = None;
        }
        // (an instruction of an IT block whose instructions are all native)
        if let Some(&cond) = native_it.borrow().get(&o) {
            return (
                t32_native_it(word, length, cond).map(|kind| Inst32 { word, length, kind }),
                length as u16,
            );
        }
        // (Q6.2: returns, which the interpreter steps otherwise)
        if kind.is_none()
            && !covered.contains(&o)
            && unsafe { crate::aarch64::jit::pages::AARCH32_DEBUG } < 2
        {
            kind = if thumb { t32_return(word, length) } else { a32_return(word) };
        }
        // (Q6.2: the forms with native templates, of those a helper call would
        // run; Q6.3: VFP's and Advanced SIMD's loads and stores)
        if matches!(kind, Some(Kind::Helper)) && !covered.contains(&o) {
            let native =
                if thumb { t32_native(word, length) } else { a32_native(word) }.or_else(|| {
                    (length == 4)
                        .then(|| {
                            fp_memory(word, thumb)
                                .or_else(|| fp_data(word, thumb))
                                .or_else(|| transfer(word, thumb, env.el1))
                                .or_else(|| env.neon.then(|| neon_data(word, thumb)).flatten())
                        })
                        .flatten()
                });
            if let Some(native) = native {
                let debug = unsafe { crate::aarch64::jit::pages::AARCH32_DEBUG };
                let bit = match native {
                    Kind::Data { .. } => 32,
                    Kind::Wide { .. } => 64,
                    Kind::Mem { .. } => 128,
                    Kind::Multiple { .. } => 256,
                    Kind::Multiply { .. } => 512,
                    Kind::FpMemory { .. }
                    | Kind::Vld1 { .. }
                    | Kind::FpArith { .. }
                    | Kind::FpMove { .. }
                    | Kind::Neon { .. }
                    | Kind::Transfer { .. } => 2048,
                    _ => 1024,
                };
                if debug & 16 == 0 || debug & bit == 0 {
                    kind = Some(native);
                }
            }
        }
        let debug = unsafe { crate::aarch64::jit::pages::AARCH32_DEBUG };
        if debug == 2 && !matches!(kind, Some(Kind::Helper))
            || debug == 3 && matches!(kind, Some(Kind::Helper))
        {
            kind = None;
        }
        if covered.contains(&o) && !matches!(kind, Some(Kind::Helper) | None) {
            kind = None;
        }
        if thumb && length == 2 && word & 0xFF00 == 0xBF00 && word & 15 != 0 {
            // its instructions and their conditions (ITAdvance)
            let mut block = Vec::new();
            let mut at = o + 2;
            let mut it = word & 0xFF;
            for _ in 0..it_count(word) {
                if at as u64 >= PAGE {
                    break;
                }
                covered.insert(at);
                let instruction = fetch(at);
                block.push((at, instruction, (it >> 4) as u8));
                it = if it & 7 == 0 { 0 } else { it & 0xE0 | it << 1 & 0x1F };
                at += instruction.map_or(2, |(_, l)| l as u16);
            }
            // (all native, none that may leave: the block runs with its
            // conditions and no ITSTATE)
            let native = block.len() as u32 == it_count(word)
                && unsafe { crate::aarch64::jit::pages::AARCH32_DEBUG } < 2
                && block.iter().all(|&(_, instruction, cond)| {
                    instruction.is_some_and(|(w, l)| t32_native_it(w, l, cond).is_some())
                });
            if native && matches!(kind, Some(Kind::Helper)) {
                for &(at, _, cond) in &block {
                    native_it.borrow_mut().insert(at, cond);
                }
                kind = Some(Kind::It);
            }
        }
        (
            kind.map(|kind| Inst32 { word, length, kind }),
            length as u16,
        )
    };
    let mut starts: BTreeSet<u16> = entries
        .iter()
        .copied()
        .filter(|&o| o % align == 0)
        .collect();
    let mut queue: Vec<u16> = starts.iter().copied().collect();
    let mut decoded: BTreeSet<u16> = BTreeSet::new();
    let add = |o: u64, starts: &mut BTreeSet<u16>, queue: &mut Vec<u16>| {
        if o < PAGE && o % align as u64 == 0 && starts.insert(o as u16) {
            queue.push(o as u16);
        }
    };
    while let Some(start) = queue.pop() {
        let mut o = start;
        loop {
            if !decoded.insert(o) {
                break;
            }
            let (inst, length) = decode(o, &mut covered);
            let Some(inst) = inst
            else {
                // (a step continues at the PC it leaves: usually the next instruction)
                add(o as u64 + length as u64, &mut starts, &mut queue);
                break;
            };
            if let Some((targets, falls)) = control(&inst, o) {
                for t in targets {
                    add(t, &mut starts, &mut queue);
                }
                if falls {
                    add(o as u64 + length as u64, &mut starts, &mut queue);
                }
                break;
            }
            o += length;
            if o as u64 >= PAGE || starts.contains(&o) {
                break;
            }
        }
    }
    // (no block starts inside a native IT block: its instructions run with
    // their conditions and ITSTATE 0, so none may be entered nor left at.
    // Such a start is the target of something that is not code (a literal
    // pool's "branch" after a call that does not return) or a stepped PC
    // inside the block; the interpreter runs those)
    starts.retain(|o| !native_it.borrow().contains_key(o));
    let mut blocks = Vec::new();
    let mut index = BTreeMap::new();
    for &start in &starts {
        let mut insts = Vec::new();
        let mut o = start;
        let end = loop {
            let (inst, length) = decode(o, &mut covered);
            let Some(inst) = inst
            else {
                break End::StepAt(o);
            };
            insts.push((o, inst));
            if let Some((_, falls)) = control(&inst, o) {
                break if falls { End::Next(o + length) } else { End::Stop };
            }
            o += length;
            if o as u64 >= PAGE {
                break End::Next(PAGE as u16);
            }
            if starts.contains(&o) {
                break End::Next(o);
            }
        };
        index.insert(start, blocks.len());
        blocks.push(Block {
            start,
            insts: Vec::new(),
            insts32: insts,
            end,
        });
    }
    (blocks, index)
}

impl Emitter<'_> {
    /// Push X[n]'s low half, an i32 (R0-R14 in memory)
    fn r32(&mut self, n: u8) { self.load32(super::x_address(n as usize)); }
    /// LR := the address after the instruction (T32's with bit 0 set)
    fn link(&mut self, offset: u16, length: u8) {
        self.c32(super::x_address(14) as i32);
        self.linear(offset as u64 + length as u64);
        self.c64(if self.env.isa == Isa::T32 { 1 } else { 0 });
        self.b.or_i64();
        self.c64(0xFFFF_FFFF);
        self.b.and_i64();
        self.b.store_aligned_i64(0);
    }

    // ---- Q6.2's native forms: the registers and NZCV in memory

    /// Push the PC as an operand: A32's instruction + 8, T32's Align(+ 4, 4)
    fn pc_operand(&mut self, offset: u16) {
        let thumb = self.env.isa == Isa::T32;
        self.linear(if thumb { (offset as u64 + 4) & !3 } else { offset as u64 + 8 });
        self.b.wrap_i64_to_i32();
    }
    /// Push R[n] (the PC as an operand)
    fn operand(&mut self, n: u8, offset: u16) {
        if n == 15 {
            self.pc_operand(offset)
        }
        else {
            self.r32(n)
        }
    }
    /// R[n] := the i32 in local `l`
    fn set_r32(&mut self, n: u8, l: usize) {
        self.c32(super::x_address(n as usize) as i32);
        self.gi(l);
        self.b.extend_unsigned_i32_to_i64();
        self.b.store_aligned_i64(0);
    }
    /// Push NZCV (memory's)
    fn nzcv(&mut self) { self.load32(state::nzcv as u32); }
    /// Push C (0 or 1)
    fn carry_flag(&mut self) {
        self.nzcv();
        self.c32(29);
        self.b.shr_u_i32();
        self.c32(1);
        self.b.and_i32();
    }
    /// NZCV := local NZCV
    fn store_nzcv(&mut self) {
        self.c32(state::nzcv as i32);
        self.gi(NZCV);
        self.b.store_aligned_i32(0);
    }
    /// The body when `cond` holds (14: always)
    fn when(&mut self, cond: u8, body: impl FnOnce(&mut Self)) {
        if cond == 14 {
            return body(self);
        }
        self.nzcv();
        self.si(NZCV);
        self.condition(cond);
        self.b.if_void();
        body(self);
        self.b.block_end();
    }

    /// The second operand into A1; its shifter carry into C1 when
    /// `carry` and the operand has one (the answer)
    fn operand2(&mut self, op2: Operand, offset: u16, carry: bool) -> bool {
        match op2 {
            Operand::Imm { value, carry: c } => {
                self.c32(value as i32);
                self.si(A1);
                if carry && c.is_some() {
                    self.c32(c.unwrap() as i32);
                    self.si(C1);
                }
                c.is_some()
            },
            Operand::RegShift { rm, kind, rs } => {
                // the amount: Rs's bottom byte
                self.r32(rm);
                self.si(C0);
                self.r32(rs);
                self.c32(0xFF);
                self.b.and_i32();
                self.si(A0);
                // the value
                match kind {
                    0 | 1 => {
                        self.gi(C0);
                        self.gi(A0);
                        if kind == 0 {
                            self.b.shl_i32();
                        }
                        else {
                            self.b.shr_u_i32();
                        }
                        self.c32(0);
                        self.gi(A0);
                        self.c32(32);
                        self.b.ltu_i32();
                        self.b.select();
                    },
                    2 => {
                        self.gi(C0);
                        self.gi(A0);
                        self.c32(31);
                        self.gi(A0);
                        self.c32(31);
                        self.b.ltu_i32();
                        self.b.select();
                        self.b.shr_s_i32();
                    },
                    _ => {
                        self.gi(C0);
                        self.gi(A0);
                        self.b.rotr_i32();
                    },
                }
                self.si(A1);
                if !carry {
                    return false;
                }
                // the carry: the last bit out (none when the amount is 0: C as it was)
                match kind {
                    0 | 1 => {
                        // (64-bit: up to 32 positions; past them 0)
                        self.gi(C0);
                        self.b.extend_unsigned_i32_to_i64();
                        if kind == 0 {
                            self.gi(A0);
                            self.b.extend_unsigned_i32_to_i64();
                            self.b.shl_i64();
                            self.c64(32);
                            self.b.shr_u_i64();
                        }
                        else {
                            self.gi(A0);
                            self.c32(1);
                            self.b.sub_i32();
                            self.b.extend_unsigned_i32_to_i64();
                            self.c64(63);
                            self.b.and_i64();
                            self.b.shr_u_i64();
                        }
                        self.b.wrap_i64_to_i32();
                        self.c32(1);
                        self.b.and_i32();
                        self.c32(0);
                        self.gi(A0);
                        self.c32(33);
                        self.b.ltu_i32();
                        self.b.select();
                    },
                    2 => {
                        self.gi(C0);
                        self.gi(A0);
                        self.c32(1);
                        self.b.sub_i32();
                        self.c32(31);
                        self.gi(A0);
                        self.c32(32);
                        self.b.ltu_i32();
                        self.b.select();
                        self.b.shr_s_i32();
                        self.c32(1);
                        self.b.and_i32();
                    },
                    _ => {
                        self.gi(A1);
                        self.c32(31);
                        self.b.shr_u_i32();
                    },
                }
                self.carry_flag();
                self.gi(A0);
                self.b.select();
                self.si(C1);
                true
            },
            Operand::Reg { rm, kind, amount } => {
                self.operand(rm, offset);
                self.si(C0);
                let n = amount as i32;
                // the value
                match (kind, amount) {
                    (_, 0) => self.gi(C0),
                    (0, _) => {
                        self.gi(C0);
                        self.c32(n);
                        self.b.shl_i32();
                    },
                    (1, 32) => self.c32(0),
                    (1, _) => {
                        self.gi(C0);
                        self.c32(n);
                        self.b.shr_u_i32();
                    },
                    (2, _) => {
                        self.gi(C0);
                        self.c32(n.min(31));
                        self.b.shr_s_i32();
                    },
                    (3, _) => {
                        self.gi(C0);
                        self.c32(n);
                        self.b.rotr_i32();
                    },
                    _ => {
                        // RRX
                        self.carry_flag();
                        self.c32(31);
                        self.b.shl_i32();
                        self.gi(C0);
                        self.c32(1);
                        self.b.shr_u_i32();
                        self.b.or_i32();
                    },
                }
                self.si(A1);
                if amount == 0 {
                    return false;
                }
                if carry {
                    // the last bit shifted out
                    self.gi(C0);
                    match kind {
                        0 => self.c32(32 - n),
                        4 => self.c32(0),
                        _ => self.c32(n - 1),
                    }
                    self.b.shr_u_i32();
                    self.c32(1);
                    self.b.and_i32();
                    self.si(C1);
                }
                true
            },
        }
    }

    fn data(&mut self, op: u8, s: bool, rd: u8, rn: u8, op2: Operand, offset: u16) {
        let logical = matches!(op, AND | EOR | TST | TEQ | ORR | MOV | BIC | MVN | ORN);
        let shifter_carry = self.operand2(op2, offset, s && logical);
        if rn != NONE {
            self.operand(rn, offset);
            self.si(A0);
        }
        if logical {
            match op {
                AND | TST => {
                    self.gi(A0);
                    self.gi(A1);
                    self.b.and_i32();
                },
                EOR | TEQ => {
                    self.gi(A0);
                    self.gi(A1);
                    self.b.xor_i32();
                },
                ORR => {
                    self.gi(A0);
                    self.gi(A1);
                    self.b.or_i32();
                },
                MOV => self.gi(A1),
                BIC | ORN => {
                    self.gi(A0);
                    self.gi(A1);
                    self.c32(-1);
                    self.b.xor_i32();
                    if op == BIC {
                        self.b.and_i32();
                    }
                    else {
                        self.b.or_i32();
                    }
                },
                _ => {
                    self.gi(A1);
                    self.c32(-1);
                    self.b.xor_i32();
                },
            }
            self.si(A2);
            if s {
                // N, Z of the result; C the shifter's (or as it was), V as it was
                self.gi(A2);
                self.c32(0x8000_0000u32 as i32);
                self.b.and_i32();
                self.gi(A2);
                self.b.eqz_i32();
                self.c32(30);
                self.b.shl_i32();
                self.b.or_i32();
                self.nzcv();
                if shifter_carry {
                    self.c32(0x1000_0000);
                    self.b.and_i32();
                    self.b.or_i32();
                    self.gi(C1);
                    self.c32(29);
                    self.b.shl_i32();
                }
                else {
                    self.c32(0x3000_0000);
                    self.b.and_i32();
                }
                self.b.or_i32();
                self.si(NZCV);
                self.store_nzcv();
            }
        }
        else {
            // x + y + carry in: subtractions add the inverse
            let (x, y_inverted, swap) = match op {
                ADD | ADC | CMN => (A0, false, false),
                SUB | SBC | CMP => (A0, true, false),
                _ => (A1, true, true),
            };
            let (x, y) = if swap { (A1, A0) } else { (x, A1) };
            self.gi(y);
            if y_inverted {
                self.c32(-1);
                self.b.xor_i32();
            }
            self.si(C1);
            self.gi(x);
            self.si(C0);
            // (the 64-bit sum: the carry out in bit 32)
            self.gi(C0);
            self.b.extend_unsigned_i32_to_i64();
            self.gi(C1);
            self.b.extend_unsigned_i32_to_i64();
            self.b.add_i64();
            match op {
                ADC | SBC | RSC => {
                    self.carry_flag();
                    self.b.extend_unsigned_i32_to_i64();
                    self.b.add_i64();
                },
                SUB | CMP | RSB => {
                    self.c64(1);
                    self.b.add_i64();
                },
                _ => {},
            }
            self.s(super::T0);
            self.g(super::T0);
            self.b.wrap_i64_to_i32();
            self.si(A2);
            if s {
                self.gi(A2);
                self.c32(0x8000_0000u32 as i32);
                self.b.and_i32();
                self.gi(A2);
                self.b.eqz_i32();
                self.c32(30);
                self.b.shl_i32();
                self.b.or_i32();
                self.g(super::T0);
                self.c64(32);
                self.b.shr_u_i64();
                self.b.wrap_i64_to_i32();
                self.c32(29);
                self.b.shl_i32();
                self.b.or_i32();
                // V: x and y of one sign, the result of the other
                self.gi(C0);
                self.gi(A2);
                self.b.xor_i32();
                self.gi(C1);
                self.gi(A2);
                self.b.xor_i32();
                self.b.and_i32();
                self.c32(31);
                self.b.shr_u_i32();
                self.c32(28);
                self.b.shl_i32();
                self.b.or_i32();
                self.si(NZCV);
                self.store_nzcv();
            }
        }
        if !matches!(op, TST | TEQ | CMP | CMN) {
            self.set_r32(rd, A2);
        }
    }

    fn wide(&mut self, rd: u8, imm: u16, top: bool) {
        if top {
            self.r32(rd);
            self.c32(0xFFFF);
            self.b.and_i32();
            self.c32((imm as i32) << 16);
            self.b.or_i32();
        }
        else {
            self.c32(imm as i32);
        }
        self.si(A2);
        self.set_r32(rd, A2);
    }

    #[allow(clippy::too_many_arguments)]
    fn memory(
        &mut self,
        load: bool,
        size: u8,
        signed: bool,
        rt: u8,
        rn: u8,
        offset_form: Offset,
        add: bool,
        index: bool,
        writeback: bool,
        offset: u16,
    ) {
        // the base, the offset, the offset address
        self.operand(rn, offset);
        self.si(A0);
        match offset_form {
            Offset::Imm(value) => self.c32(value as i32),
            Offset::Reg { rm, shift } => {
                self.r32(rm);
                if shift != 0 {
                    self.c32(shift as i32);
                    self.b.shl_i32();
                }
            },
        }
        self.si(A1);
        self.gi(A0);
        self.gi(A1);
        if add {
            self.b.add_i32();
        }
        else {
            self.b.sub_i32();
        }
        self.si(A2);
        self.gi(if index { A2 } else { A0 });
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::ADDR);
        // (a miss, a fault, an access across the page: the interpreter's)
        self.host(1 << size, !load, offset);
        if load {
            self.load_value(size as u32, signed, true);
            self.s(super::T1);
            if rt == 15 {
                // a return: to this instruction set (else the interpreter's)
                self.g(super::T1);
                self.b.wrap_i64_to_i32();
                self.si(C0);
                self.same_set(offset);
                if writeback {
                    self.set_r32(rn, A2);
                }
                return self.jump_c0();
            }
            if writeback {
                self.set_r32(rn, A2);
            }
            self.c32(super::x_address(rt as usize) as i32);
            self.g(super::T1);
            self.b.store_aligned_i64(0);
        }
        else {
            self.operand(rt, offset);
            self.b.extend_unsigned_i32_to_i64();
            self.store_value(size as u32);
            if writeback {
                self.set_r32(rn, A2);
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn multiple(
        &mut self,
        load: bool,
        rn: u8,
        list: u16,
        increment: bool,
        before: bool,
        writeback: bool,
        offset: u16,
    ) {
        let n = list.count_ones() as i32;
        // the lowest address, the base's new value
        self.r32(rn);
        self.si(A0);
        self.gi(A0);
        let start = match (increment, before) {
            (true, false) => 0,
            (true, true) => 4,
            (false, false) => 4 - 4 * n,
            (false, true) => -4 * n,
        };
        if start != 0 {
            self.c32(start);
            self.b.add_i32();
        }
        self.si(A1);
        self.gi(A0);
        self.c32(if increment { 4 * n } else { -4 * n });
        self.b.add_i32();
        self.si(A2);
        // (aligned, in one page: else the interpreter's)
        self.gi(A1);
        self.c32(3);
        self.b.and_i32();
        self.gi(A1);
        self.c32(0xFFF);
        self.b.and_i32();
        self.c32(4096 - 4 * n);
        self.b.gtu_i32();
        self.b.or_i32();
        self.retry_if(offset);
        self.gi(A1);
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::ADDR);
        self.host(4, !load, offset);
        self.si(super::HH);
        let pc = load && list & 0x8000 != 0;
        if pc {
            // a return: its target (the highest word) first, to this
            // instruction set (else the interpreter's, before any effect)
            self.gi(super::HH);
            self.c32(4 * (n - 1));
            self.b.add_i32();
            self.load_value(2, false, true);
            self.b.wrap_i64_to_i32();
            self.si(C0);
            self.same_set(offset);
        }
        let mut at = 0;
        for r in (0..15u8).filter(|r| list & 1 << r != 0) {
            if load {
                self.c32(super::x_address(r as usize) as i32);
                self.gi(super::HH);
                if at != 0 {
                    self.c32(at);
                    self.b.add_i32();
                }
                self.load_value(2, false, true);
                self.b.store_aligned_i64(0);
            }
            else {
                self.gi(super::HH);
                if at != 0 {
                    self.c32(at);
                    self.b.add_i32();
                }
                self.r32(r);
                self.b.extend_unsigned_i32_to_i64();
                self.store_value(2);
            }
            at += 4;
        }
        if writeback {
            self.set_r32(rn, A2);
        }
        if pc {
            self.jump_c0();
        }
    }

    /// Retry the instruction at `offset` when the target in C0 is another
    /// instruction set's (T32: bit 0 set; A32: bits 1:0 clear)
    fn same_set(&mut self, offset: u16) {
        let thumb = self.env.isa == Isa::T32;
        self.gi(C0);
        self.c32(if thumb { 1 } else { 3 });
        self.b.and_i32();
        self.c32(thumb as i32);
        self.b.ne_i32();
        self.retry_if(offset);
    }
    /// PC := C0 (bit 0 clear), dispatched
    fn jump_c0(&mut self) {
        self.gi(C0);
        self.c32(!1);
        self.b.and_i32();
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::PC);
        self.b.br(self.f().dispatch);
    }

    /// The FP and Advanced SIMD access check (pagegen's fp_check), with
    /// cpu_type arm32's FPEXC.EN too: retry the instruction when disabled
    fn fp_access(&mut self, offset: u16) {
        self.fp_check(offset);
        if crate::aarch64::cpu::a32_only() {
            self.load32(state::a32_fpexc as u32);
            self.c32(1 << 30);
            self.b.and_i32();
            self.b.eqz_i32();
            self.retry_if(offset);
        }
    }

    /// Words between memory at the host address in HH and the SIMD&FP
    /// registers' bytes from `register_word` (the state's V registers as
    /// words: S[n] word n, D[n] words 2n and 2n + 1): word copies, which
    /// atomic guest memory allows at any word-aligned address
    fn fp_words(&mut self, load: bool, register_word: u32, words: u32) {
        for w in 0..words {
            let at = state::v as u32 + 4 * (register_word + w);
            if load {
                self.c32(at as i32);
                self.gi(super::HH);
                if w != 0 {
                    self.c32(4 * w as i32);
                    self.b.add_i32();
                }
                self.load_value(2, false, false);
                self.b.wrap_i64_to_i32();
                self.b.store_aligned_i32(0);
            }
            else {
                self.gi(super::HH);
                if w != 0 {
                    self.c32(4 * w as i32);
                    self.b.add_i32();
                }
                self.load32(at);
                self.b.extend_unsigned_i32_to_i64();
                self.store_value(2);
            }
        }
    }

    /// The host address of `bytes` from the address in local A1 into HH:
    /// word aligned (and to `align` bytes) and in one page, else the
    /// interpreter's
    fn fp_host(&mut self, load: bool, bytes: u32, align: u32, offset: u16) {
        self.gi(A1);
        self.c32(align.max(4) as i32 - 1);
        self.b.and_i32();
        self.gi(A1);
        self.c32(0xFFF);
        self.b.and_i32();
        self.c32((4096 - bytes) as i32);
        self.b.gtu_i32();
        self.b.or_i32();
        self.retry_if(offset);
        self.gi(A1);
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::ADDR);
        self.host(4, !load, offset);
        self.si(super::HH);
    }

    /// A helper call: the interpreter's execute of the instruction
    /// (pages::a32_page_helper), a refusal retried in the interpreter
    fn a32_helper(&mut self, word: u32, length: u8, offset: u16) {
        self.c32(word as i32);
        self.linear(offset as u64);
        self.c32(length as i32);
        self.b.call_signature(
            "a32_page_helper",
            Signature::new(
                &[WasmType::I32, WasmType::I64, WasmType::I32],
                &[WasmType::I32],
            ),
        );
        self.retry_if(offset);
    }

    /// The state's address of S[r] (word r of the V registers) or D[r]
    fn fp_address(r: u8, double: bool) -> u32 {
        state::v as u32 + if double { 8 } else { 4 } * r as u32
    }
    /// S[r] (zero-extended) or D[r] into 64-bit local `l`
    fn a32_fp_load(&mut self, r: u8, double: bool, l: usize) {
        self.c32(Self::fp_address(r, double) as i32);
        self.b.memory_op(
            if double {
                crate::wasmgen::wasm_opcodes::OP_I64LOAD
            }
            else {
                crate::wasmgen::wasm_opcodes::OP_I64LOAD32U
            },
            if double { 3 } else { 2 },
            0,
        );
        self.s(l);
    }
    /// 64-bit local `l` into D[r], or its low 32 bits into S[r] (the rest of the V register as it was)
    fn a32_fp_store(&mut self, r: u8, double: bool, l: usize) {
        self.c32(Self::fp_address(r, double) as i32);
        self.g(l);
        if double {
            self.b.store_aligned_i64(0);
        }
        else {
            self.b.wrap_i64_to_i32();
            self.b.store_aligned_i32(0);
        }
    }

    /// VADD, VSUB, VMUL, VNMUL, VDIV (FpArith): pagegen's scalar rules
    #[allow(clippy::too_many_arguments)]
    fn fp_arith(
        &mut self,
        op: u8,
        double: bool,
        d: u8,
        n: u8,
        m: u8,
        word: u32,
        length: u8,
        offset: u16,
    ) {
        use super::{T0, T1, T3};
        self.fp_access(offset);
        let done = self.b.block_void();
        self.a32_fp_load(n, double, T0);
        self.a32_fp_load(m, double, T1);
        // RMode RN and FZ 0 (FPCR), IXC already set (FPSR), the operands zero or normal
        self.load32(state::fpcr as u32);
        self.c32(0x01C0_0000);
        self.b.and_i32();
        self.b.eqz_i32();
        self.load32(state::fpsr as u32);
        self.c32(4);
        self.b.shr_u_i32();
        self.c32(1);
        self.b.and_i32();
        self.b.and_i32();
        for l in [T0, T1] {
            self.fp_ordinary(l, double, false);
            self.b.and_i32();
        }
        if op == 3 {
            // (a divisor that is not zero)
            self.g(T1);
            self.c64(if double { 0x7FFF_FFFF_FFFF_FFFF } else { 0x7FFF_FFFF });
            self.b.and_i64();
            self.c64(0);
            self.b.ne_i64();
            self.b.and_i32();
        }
        self.b.if_void();
        self.fp_value(T0, double);
        self.fp_value(T1, double);
        // (Wasm's 0 add, 1 sub, 2 mul, 3 div)
        let wasm = [0, 1, 2, 3, 2][op as usize];
        if double {
            self.b.arithmetic_f64(wasm);
        }
        else {
            self.b.arithmetic_f32(wasm);
        }
        if op == 4 {
            if double {
                self.b.unary_f64(true);
            }
            else {
                self.o(0x8C); // f32.neg
            }
        }
        self.fp_bits(T3, double);
        self.fp_ordinary(T3, double, true);
        self.b.if_void();
        self.a32_fp_store(d, double, T3);
        self.b.br(done);
        self.b.block_end();
        self.b.block_end();
        // the exact path: the interpreter's
        self.a32_helper(word, length, offset);
        self.b.block_end();
    }

    /// VFP's moves (FpMove)
    /// Kind::Transfer
    #[allow(clippy::too_many_arguments)]
    fn transfer(
        &mut self,
        op: u8,
        rt: u8,
        address: u32,
        size: u8,
        signed: bool,
        q: bool,
        offset: u16,
    ) {
        use crate::wasmgen::wasm_opcodes as o;
        match op {
            TRANSFER_READ => {
                self.load32(address);
                self.si(A0);
                self.set_r32(rt, A0);
            },
            TRANSFER_WRITE => {
                self.c32(address as i32);
                self.r32(rt);
                self.b.extend_unsigned_i32_to_i64();
                self.b.store_aligned_i64(0);
            },
            TRANSFER_FPSCR | TRANSFER_FPSCR_FLAGS => {
                self.fp_access(offset);
                if op == TRANSFER_FPSCR_FLAGS {
                    self.c32(state::nzcv as i32);
                    self.load32(state::fpsr as u32);
                    self.c32(0xF000_0000u32 as i32);
                    self.b.and_i32();
                    self.b.store_aligned_i32(0);
                    return;
                }
                self.load32(state::fpsr as u32);
                self.c32(0xF800_009Fu32 as i32);
                self.b.and_i32();
                self.load32(state::fpcr as u32);
                self.c32(crate::aarch64::fp::FPCR_WRITABLE as i32);
                self.b.and_i32();
                self.b.or_i32();
                self.si(A0);
                self.set_r32(rt, A0);
            },
            TRANSFER_FROM_SCALAR => {
                self.fp_access(offset);
                self.c32(address as i32);
                let opcode = match (size, signed) {
                    (1, true) => o::OP_I32LOAD8S,
                    (1, false) => o::OP_I32LOAD8U,
                    (2, true) => o::OP_I32LOAD16S,
                    (2, false) => o::OP_I32LOAD16U,
                    _ => o::OP_I32LOAD,
                };
                self.b.memory_op(opcode, size.trailing_zeros() as u8, 0);
                self.si(A0);
                self.set_r32(rt, A0);
            },
            TRANSFER_TO_SCALAR => {
                self.fp_access(offset);
                self.c32(address as i32);
                self.r32(rt);
                let opcode = match size {
                    1 => o::OP_I32STORE8,
                    2 => o::OP_I32STORE16,
                    _ => o::OP_I32STORE,
                };
                self.b.memory_op(opcode, size.trailing_zeros() as u8, 0);
            },
            _ => {
                // VDUP (core): Rt's low `size` bytes in every element of D or Q
                self.fp_access(offset);
                self.c32(address as i32);
                self.r32(rt);
                self.b.simd(match size {
                    1 => 0x0F,
                    2 => 0x10,
                    _ => 0x11,
                });
                if q {
                    self.b.simd_memory(0x0B, 4);
                }
                else {
                    self.b.simd_lane(0x1D, 0);
                    self.b.store_aligned_i64(0);
                }
            },
        }
    }

    /// D[r] (`q` false: in both halves) or Q[r/2] onto the stack, a v128
    fn neon_load(&mut self, r: u8, q: bool) {
        self.c32(state::v as i32 + 8 * r as i32);
        if q {
            self.b.simd_memory(0x00, 4);
        }
        else {
            self.b
                .memory_op(crate::wasmgen::wasm_opcodes::OP_I64LOAD, 3, 0);
            self.b.simd(0x12);
        }
    }

    /// Advanced SIMD data processing (Neon): the result into D[d] (the
    /// v128's low half) or Q[d/2]
    fn neon(&mut self, form: NeonForm, q: bool, d: u8, n: u8, m: u8, offset: u16) {
        self.fp_access(offset);
        self.c32(state::v as i32 + 8 * d as i32);
        let register = |x: u8| [d, n, m][x as usize];
        match form {
            NeonForm::Binary { op, invert_m, test } => {
                self.neon_load(n, q);
                self.neon_load(m, q);
                if invert_m {
                    self.b.simd(0x4D);
                }
                if test {
                    self.b.simd(0x4E);
                    self.b.simd_zero();
                }
                self.b.simd(op);
            },
            NeonForm::Select {
                first,
                second,
                mask,
            } => {
                self.neon_load(register(first), q);
                self.neon_load(register(second), q);
                self.neon_load(register(mask), q);
                self.b.simd(0x52);
            },
            NeonForm::Shift { op, amount, zero } => {
                if zero {
                    self.b.simd_zero();
                }
                else {
                    self.neon_load(m, q);
                    self.c32(amount as i32);
                    self.b.simd(op);
                }
            },
            NeonForm::Immediate { value, kind } => {
                if kind != 0 {
                    self.neon_load(d, q);
                }
                let mut bytes = [0u8; 16];
                bytes[..8].copy_from_slice(&value.to_le_bytes());
                bytes[8..].copy_from_slice(&value.to_le_bytes());
                self.b.const_v128(bytes);
                match kind {
                    1 => self.b.simd(0x50),
                    2 => self.b.simd(0x4E),
                    _ => {},
                }
            },
            NeonForm::Dup { esize, index } => {
                self.neon_load(m, false);
                let (extract, splat) = match esize {
                    8 => (0x16, 0x0F),
                    16 => (0x19, 0x10),
                    _ => (0x1B, 0x11),
                };
                self.b.simd_lane(extract, index);
                self.b.simd(splat);
            },
            NeonForm::Shuffle { lanes, of_m } => {
                self.neon_load(if of_m { m } else { n }, q);
                self.neon_load(m, q);
                self.b.simd_shuffle(lanes);
            },
            NeonForm::Unary { op } => {
                self.neon_load(m, q);
                self.b.simd(op);
            },
        }
        if q {
            self.b.simd_memory(0x0B, 4);
        }
        else {
            self.b.simd_lane(0x1D, 0);
            self.b.store_aligned_i64(0);
        }
    }

    fn fp_move(&mut self, kind: u8, double: bool, d: u8, n: u8, m: u8, offset: u16) {
        use super::T0;
        self.fp_access(offset);
        match kind {
            0..=2 => {
                self.a32_fp_load(m, double, T0);
                let sign = if double { 1u64 << 63 } else { 1 << 31 };
                if kind != 0 {
                    self.g(T0);
                    if kind == 1 {
                        self.c64(!sign);
                        self.b.and_i64();
                    }
                    else {
                        self.c64(sign);
                        self.b.xor_i64();
                    }
                    self.s(T0);
                }
                self.a32_fp_store(d, double, T0);
            },
            3 => {
                self.c32(Self::fp_address(d, false) as i32);
                self.r32(n);
                self.b.store_aligned_i32(0);
            },
            4 => {
                self.load32(Self::fp_address(m, false));
                self.si(A0);
                self.set_r32(d, A0);
            },
            5 => {
                let at = Self::fp_address(d, true);
                self.c32(at as i32);
                self.r32(n);
                self.b.store_aligned_i32(0);
                self.c32(at as i32 + 4);
                self.r32(m);
                self.b.store_aligned_i32(0);
            },
            _ => {
                let at = Self::fp_address(d, true);
                self.load32(at);
                self.si(A0);
                self.set_r32(n, A0);
                self.load32(at + 4);
                self.si(A0);
                self.set_r32(m, A0);
            },
        }
    }

    /// VLDR, VSTR, VLDM, VSTM, VPUSH, VPOP (FpMemory)
    #[allow(clippy::too_many_arguments)]
    fn fp_memory(
        &mut self,
        load: bool,
        double: bool,
        first: u8,
        count: u8,
        rn: u8,
        imm: u16,
        add: bool,
        single: bool,
        writeback: bool,
        offset: u16,
    ) {
        self.fp_access(offset);
        let bytes = count as i32 * if double { 8 } else { 4 };
        // the lowest address (A1) and the base's new value (A2)
        self.operand(rn, offset);
        self.si(A0);
        self.gi(A0);
        if single {
            if imm != 0 {
                self.c32(imm as i32);
                if add {
                    self.b.add_i32();
                }
                else {
                    self.b.sub_i32();
                }
            }
        }
        else if !add {
            self.c32(bytes);
            self.b.sub_i32();
        }
        self.si(A1);
        self.gi(A0);
        self.c32(if add { bytes } else { -bytes });
        self.b.add_i32();
        self.si(A2);
        self.fp_host(load, bytes as u32, 4, offset);
        let register_word = if double { 2 * first as u32 } else { first as u32 };
        self.fp_words(load, register_word, bytes as u32 / 4);
        if writeback {
            self.set_r32(rn, A2);
        }
    }

    /// VLD1, VST1 of multiple single elements (Vld1)
    #[allow(clippy::too_many_arguments)]
    fn vld1(&mut self, load: bool, first: u8, count: u8, rn: u8, rm: u8, align: u8, offset: u16) {
        self.fp_access(offset);
        let bytes = 8 * count as u32;
        self.r32(rn);
        self.si(A1);
        self.fp_host(load, bytes, align as u32, offset);
        self.fp_words(load, 2 * first as u32, 2 * count as u32);
        if rm != 15 {
            self.gi(A1);
            if rm == 13 {
                self.c32(bytes as i32);
            }
            else {
                self.r32(rm);
            }
            self.b.add_i32();
            self.si(A2);
            self.set_r32(rn, A2);
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn dual(
        &mut self,
        load: bool,
        rt: u8,
        rt2: u8,
        rn: u8,
        imm: u32,
        add: bool,
        index: bool,
        writeback: bool,
        offset: u16,
    ) {
        self.r32(rn);
        self.si(A0);
        self.gi(A0);
        self.c32(imm as i32);
        if add {
            self.b.add_i32();
        }
        else {
            self.b.sub_i32();
        }
        self.si(A2);
        self.gi(if index { A2 } else { A0 });
        self.si(A1);
        // (word aligned, both words in one page: else the interpreter's)
        self.gi(A1);
        self.c32(3);
        self.b.and_i32();
        self.gi(A1);
        self.c32(0xFFF);
        self.b.and_i32();
        self.c32(4088);
        self.b.gtu_i32();
        self.b.or_i32();
        self.retry_if(offset);
        self.gi(A1);
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::ADDR);
        self.host(4, !load, offset);
        self.si(super::HH);
        for (k, r) in [rt, rt2].into_iter().enumerate() {
            if load {
                self.c32(super::x_address(r as usize) as i32);
                self.gi(super::HH);
                if k != 0 {
                    self.c32(4);
                    self.b.add_i32();
                }
                self.load_value(2, false, true);
                self.b.store_aligned_i64(0);
            }
            else {
                self.gi(super::HH);
                if k != 0 {
                    self.c32(4);
                    self.b.add_i32();
                }
                self.r32(r);
                self.b.extend_unsigned_i32_to_i64();
                self.store_value(2);
            }
        }
        if writeback {
            self.set_r32(rn, A2);
        }
    }

    /// CLZ, REV, REV16, REVSH
    fn bits(&mut self, op: u8, rd: u8, rm: u8) {
        self.r32(rm);
        self.si(C0);
        match op {
            0 => {
                self.gi(C0);
                self.b.clz_i32();
            },
            1 => {
                for (shift, mask, left) in [
                    (24, 0xFF, false),
                    (8, 0xFF00, false),
                    (8, 0xFF_0000, true),
                    (24, 0xFF00_0000u32, true),
                ] {
                    self.gi(C0);
                    self.c32(shift);
                    if left {
                        self.b.shl_i32();
                    }
                    else {
                        self.b.shr_u_i32();
                    }
                    self.c32(mask as i32);
                    self.b.and_i32();
                }
                self.b.or_i32();
                self.b.or_i32();
                self.b.or_i32();
            },
            2 => {
                self.gi(C0);
                self.c32(8);
                self.b.shr_u_i32();
                self.c32(0x00FF_00FF);
                self.b.and_i32();
                self.gi(C0);
                self.c32(8);
                self.b.shl_i32();
                self.c32(0xFF00_FF00u32 as i32);
                self.b.and_i32();
                self.b.or_i32();
            },
            _ => {
                self.gi(C0);
                self.c32(24);
                self.b.shl_i32();
                self.c32(16);
                self.b.shr_s_i32();
                self.gi(C0);
                self.c32(8);
                self.b.shr_u_i32();
                self.c32(0xFF);
                self.b.and_i32();
                self.b.or_i32();
            },
        }
        self.si(A2);
        self.set_r32(rd, A2);
    }

    fn multiply(&mut self, rd: u8, rn: u8, rm: u8, ra: u8, sub: bool) {
        if ra != NONE {
            self.r32(ra);
        }
        self.r32(rn);
        self.r32(rm);
        self.b.mul_i32();
        if ra != NONE {
            if sub {
                self.b.sub_i32();
            }
            else {
                self.b.add_i32();
            }
        }
        self.si(A2);
        self.set_r32(rd, A2);
    }

    fn extend(&mut self, rd: u8, rm: u8, signed: bool, half: bool, rotation: u8) {
        self.r32(rm);
        if rotation != 0 {
            self.c32(rotation as i32);
            self.b.rotr_i32();
        }
        let bits = if half { 16 } else { 24 };
        if signed {
            self.c32(bits);
            self.b.shl_i32();
            self.c32(bits);
            self.b.shr_s_i32();
        }
        else {
            self.c32(if half { 0xFFFF } else { 0xFF });
            self.b.and_i32();
        }
        self.si(A2);
        self.set_r32(rd, A2);
    }

    pub(super) fn instruction32(&mut self, offset: u16, i: &Inst32, index: &BTreeMap<u16, usize>) {
        match i.kind {
            Kind::Data {
                op,
                s,
                rd,
                rn,
                op2,
                cond,
            } => self.when(cond, |e| e.data(op, s, rd, rn, op2, offset)),
            Kind::Wide { rd, imm, top, cond } => self.when(cond, |e| e.wide(rd, imm, top)),
            Kind::Mem {
                load,
                size,
                signed,
                rt,
                rn,
                offset: o,
                add,
                index: ix,
                writeback,
                cond,
            } => self.when(cond, |e| {
                e.memory(load, size, signed, rt, rn, o, add, ix, writeback, offset)
            }),
            Kind::Multiple {
                load,
                rn,
                list,
                increment,
                before,
                writeback,
                cond,
            } => self.when(cond, |e| {
                e.multiple(load, rn, list, increment, before, writeback, offset)
            }),
            Kind::Multiply {
                rd,
                rn,
                rm,
                ra,
                sub,
                cond,
            } => self.when(cond, |e| e.multiply(rd, rn, rm, ra, sub)),
            Kind::Extend {
                rd,
                rm,
                signed,
                half,
                rotation,
                cond,
            } => self.when(cond, |e| e.extend(rd, rm, signed, half, rotation)),
            Kind::Dual {
                load,
                rt,
                rt2,
                rn,
                imm,
                add,
                index: ix,
                writeback,
                cond,
            } => self.when(cond, |e| {
                e.dual(load, rt, rt2, rn, imm, add, ix, writeback, offset)
            }),
            Kind::Bits { op, rd, rm, cond } => self.when(cond, |e| e.bits(op, rd, rm)),
            Kind::FpMemory {
                load,
                double,
                first,
                count,
                rn,
                imm,
                add,
                single,
                writeback,
                cond,
            } => self.when(cond, |e| {
                e.fp_memory(
                    load, double, first, count, rn, imm, add, single, writeback, offset,
                )
            }),
            Kind::Vld1 {
                load,
                first,
                count,
                rn,
                rm,
                align,
            } => self.vld1(load, first, count, rn, rm, align, offset),
            Kind::FpArith {
                op,
                double,
                d,
                n,
                m,
                cond,
            } => self.when(cond, |e| {
                e.fp_arith(op, double, d, n, m, i.word, i.length, offset)
            }),
            Kind::FpMove {
                kind,
                double,
                d,
                n,
                m,
                cond,
            } => self.when(cond, |e| e.fp_move(kind, double, d, n, m, offset)),
            Kind::It => {},
            Kind::Neon { form, q, d, n, m } => self.neon(form, q, d, n, m, offset),
            Kind::Transfer {
                op,
                rt,
                address,
                size,
                signed,
                q,
                cond,
            } => self.when(cond, |e| {
                e.transfer(op, rt, address, size, signed, q, offset)
            }),
            Kind::Helper => self.a32_helper(i.word, i.length, offset),
            Kind::Branch { target, cond, link } => {
                if cond != 14 {
                    self.load32(state::nzcv as u32);
                    self.si(NZCV);
                    self.condition(cond);
                    self.b.if_void();
                }
                if link {
                    self.link(offset, i.length);
                }
                self.goto(target, index);
                if cond != 14 {
                    self.b.block_end();
                }
            },
            Kind::CompareBranch {
                rn,
                nonzero,
                target,
            } => {
                self.r32(rn);
                if !nonzero {
                    self.b.eqz_i32();
                }
                self.b.if_void();
                self.goto(target, index);
                self.b.block_end();
            },
            Kind::Exchange { rm, link, cond } => {
                self.when(cond, |e| e.exchange(rm, link, offset, i.length))
            },
        }
    }

    /// BX, BLX of a register: the target's instruction set this one's (T32
    /// bit 0 set, A32 bits 1:0 clear; else the interpreter switches)
    fn exchange(&mut self, rm: u8, link: bool, offset: u16, length: u8) {
        self.r32(rm);
        self.b.extend_unsigned_i32_to_i64();
        self.s(super::T0);
        self.g(super::T0);
        self.c64(if self.env.isa == Isa::T32 { 1 } else { 3 });
        self.b.and_i64();
        self.c64(if self.env.isa == Isa::T32 { 1 } else { 0 });
        self.b.ne_i64();
        self.retry_if(offset);
        if link {
            self.link(offset, length);
        }
        self.g(super::T0);
        self.c64(!1);
        self.b.and_i64();
        self.s(super::PC);
        self.b.br(self.f().dispatch);
    }
}
                                                                                                                                                                                                                                                                                                      source/v64/src/rust/aarch64/jit/pagegen/neon.rs                                                     0000644 0000000 0000000 00000073255 00000000000 016415  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The AdvSIMD templates of the A64 page tier (docs/jit-unification-plan.md
//! P6.3b): vector forms as Wasm SIMD (v128) operations on the V registers
//! in the state block, emitted only by a core built with simd128 (as
//! src/rust/x64/pagegen.rs's vector templates). The integer and bitwise
//! forms, the permutes and the element moves have no exceptions and no
//! FPSR effects (the saturating forms, which set FPSR.QC, are helper
//! calls). The FP forms take the fast path of the ARM plan's rules
//! ("A64 JIT 的语义红线"), lane by lane: FPCR RMode RN and FZ 0, FPSR.IXC
//! already set, every operand lane zero or normal, every divisor lane not
//! zero, every result lane zero or normal with exponent 2 or more; FMLA
//! and FMLS only with fused relaxed multiply-adds (a64_relaxed_fma).
//! Anything else calls the interpreter (the helper). A 64-bit form (Q = 0)
//! computes on the low half and writes the upper half zero.

use super::*;
use crate::wasmgen::wasm_builder::WasmLocalV128;

// Wasm SIMD opcodes (after the 0xFD prefix)
const V128_LOAD: u32 = 0x00;
const V128_STORE: u32 = 0x0B;
const V128_NOT: u32 = 0x4D;
const V128_AND: u32 = 0x4E;
const V128_ANDNOT: u32 = 0x4F;
const V128_OR: u32 = 0x50;
const V128_BITSELECT: u32 = 0x52;
const I8X16_POPCNT: u32 = 0x62;

/// Where an operand of a bit select comes from
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Source {
    D,
    N,
    M,
}

/// The template of a vector instruction
#[derive(Clone, Copy)]
pub(super) enum VecForm {
    /// d = op(n, m), the lane width's operation `op`; `invert_m`: ORN's m
    /// inverted first; `test`: CMTST, (n & m) != 0 with `op` the lanes' ne
    Binary { op: u32, invert_m: bool, test: bool },
    /// BSL, BIT, BIF: v128.bitselect(first, second, mask)
    Select {
        first: Source,
        second: Source,
        mask: Source,
    },
    /// d = op(n); `compare_zero`: op(n, 0)
    Unary { op: u32, compare_zero: bool },
    /// d = op(n, amount) (a lane shift); `zero`: USHR by the element size
    Shift { op: u32, amount: u32, zero: bool },
    /// d = the bytes `lanes` of first:second (0-15: first, 16-31: second),
    /// the bytes from `keep` on zero
    Shuffle {
        first: u8,
        second: u8,
        lanes: [u8; 16],
        keep: u8,
    },
    /// d = `value` (MOVI, MVNI, FMOV vector immediate), d | value (ORR),
    /// d & !value (BIC)
    Immediate { value: u128, kind: u8 },
    /// DUP (general): X[n]'s low `esize` bits in every element
    DupGeneral { esize: u32 },
    /// INS: element `index` of d from X[n] or from element `source` of n
    Insert {
        esize: u32,
        index: u32,
        source: Option<u32>,
    },
    /// UMOV, SMOV: element `index` of n into X[d] (`signed`; `wide`: X, else W)
    Move {
        esize: u32,
        index: u32,
        signed: bool,
        wide: bool,
    },
    /// FADD, FSUB, FMUL, FDIV (0-3), FMLA, FMLS (4, 5) on the fast path
    Fp { op: u8, double: bool },
    /// FMOV (general): between X[n]/X[d] and V's low 32 or 64 bits, or the
    /// upper 64 (`top`)
    FmovGeneral { to_gpr: bool, bits: u32, top: bool },
}

const IMM_SET: u8 = 0;
const IMM_OR: u8 = 1;
const IMM_AND_NOT: u8 = 2;

/// The lane operation of `table` for elements of 8 << size bits (None: no
/// such Wasm operation)
fn lanes(table: [u32; 4], size: u32) -> Option<u32> {
    Some(table[size as usize]).filter(|&o| o != 0)
}

/// The bytes of a shuffle that builds `elements` elements of `esize` bits,
/// element e from element `pick(e)` = (operand 0 or 1, index) of first:second
fn element_lanes(esize: u32, elements: u32, pick: impl Fn(u32) -> (u32, u32)) -> [u8; 16] {
    let bytes = esize / 8;
    let mut lanes = [0u8; 16];
    for e in 0..elements {
        let (operand, index) = pick(e);
        for b in 0..bytes {
            lanes[(e * bytes + b) as usize] = (16 * operand + index * bytes + b) as u8;
        }
    }
    lanes
}

/// The vector template of `i`, if any
pub(super) fn form(i: &Inst, env: &CompileEnv) -> Option<VecForm> {
    if !env.neon || !cfg!(target_feature = "simd128") {
        return None;
    }
    let word = i.imm as u32;
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let vector = word >> 28 & 1 == 0;
    let size = word >> 22 & 3;
    let datasize = if q { 128 } else { 64 };
    match i.op {
        Op::SimdThreeSame if vector => {
            let opcode = word >> 11 & 31;
            if opcode >= 0b11000 {
                // FP: FADD, FSUB, FMUL, FDIV; FMLA, FMLS fused
                let double = size & 1 != 0;
                let op = match (u, size >> 1, opcode) {
                    (0, 0, 0b11010) => 0,
                    (0, 1, 0b11010) => 1,
                    (1, 0, 0b11011) => 2,
                    (1, 0, 0b11111) => 3,
                    (0, 0, 0b11001) if env.relaxed_fma => 4,
                    (0, 1, 0b11001) if env.relaxed_fma => 5,
                    _ => return None,
                };
                return Some(VecForm::Fp { op, double });
            }
            if opcode == 0b00011 {
                use Source::*;
                return Some(match u << 2 | size {
                    0 => VecForm::Binary {
                        op: V128_AND,
                        invert_m: false,
                        test: false,
                    },
                    1 => VecForm::Binary {
                        op: V128_ANDNOT,
                        invert_m: false,
                        test: false,
                    },
                    2 => VecForm::Binary {
                        op: V128_OR,
                        invert_m: false,
                        test: false,
                    },
                    3 => VecForm::Binary {
                        op: V128_OR,
                        invert_m: true,
                        test: false,
                    },
                    4 => VecForm::Binary {
                        op: 0x51,
                        invert_m: false,
                        test: false,
                    },
                    5 => VecForm::Select {
                        first: N,
                        second: M,
                        mask: D,
                    },
                    6 => VecForm::Select {
                        first: N,
                        second: D,
                        mask: M,
                    },
                    _ => VecForm::Select {
                        first: D,
                        second: N,
                        mask: M,
                    },
                });
            }
            let binary = |op: Option<u32>| {
                op.map(|op| VecForm::Binary {
                    op,
                    invert_m: false,
                    test: false,
                })
            };
            match (u, opcode) {
                (0, 0b10000) => binary(lanes([0x6E, 0x8E, 0xAE, 0xCE], size)),
                (1, 0b10000) => binary(lanes([0x71, 0x91, 0xB1, 0xD1], size)),
                (1, 0b10001) => binary(lanes([0x23, 0x2D, 0x37, 0xD6], size)),
                (0, 0b10001) => lanes([0x24, 0x2E, 0x38, 0xD7], size).map(|op| VecForm::Binary {
                    op,
                    invert_m: false,
                    test: true,
                }),
                (0, 0b00110) => binary(lanes([0x27, 0x31, 0x3B, 0xD9], size)),
                (1, 0b00110) => binary(lanes([0x28, 0x32, 0x3C, 0], size)),
                (0, 0b00111) => binary(lanes([0x2B, 0x35, 0x3F, 0xDB], size)),
                (1, 0b00111) => binary(lanes([0x2C, 0x36, 0x40, 0], size)),
                (0, 0b01100) => binary(lanes([0x78, 0x98, 0xB8, 0], size)),
                (1, 0b01100) => binary(lanes([0x79, 0x99, 0xB9, 0], size)),
                (0, 0b01101) => binary(lanes([0x76, 0x96, 0xB6, 0], size)),
                (1, 0b01101) => binary(lanes([0x77, 0x97, 0xB7, 0], size)),
                (0, 0b10011) => binary(lanes([0, 0x95, 0xB5, 0], size)),
                // URHADD
                (1, 0b00010) => binary(lanes([0x7B, 0x9B, 0, 0], size)),
                _ => None,
            }
        },
        Op::SimdTwoMisc if vector => {
            let opcode = word >> 12 & 31;
            let unary = |op: Option<u32>| {
                op.map(|op| VecForm::Unary {
                    op,
                    compare_zero: false,
                })
            };
            let zero = |op: Option<u32>| {
                op.map(|op| VecForm::Unary {
                    op,
                    compare_zero: true,
                })
            };
            match (u, opcode) {
                (1, 0b00101) if size == 0 => Some(VecForm::Unary {
                    op: V128_NOT,
                    compare_zero: false,
                }),
                (0, 0b00101) if size == 0 => Some(VecForm::Unary {
                    op: I8X16_POPCNT,
                    compare_zero: false,
                }),
                (0, 0b01011) => unary(lanes([0x60, 0x80, 0xA0, 0xC0], size)),
                (1, 0b01011) => unary(lanes([0x61, 0x81, 0xA1, 0xC1], size)),
                (0, 0b01000) => zero(lanes([0x27, 0x31, 0x3B, 0xD9], size)),
                (1, 0b01000) => zero(lanes([0x2B, 0x35, 0x3F, 0xDB], size)),
                (0, 0b01001) => zero(lanes([0x23, 0x2D, 0x37, 0xD6], size)),
                (1, 0b01001) => zero(lanes([0x29, 0x33, 0x3D, 0xDA], size)),
                (0, 0b01010) => zero(lanes([0x25, 0x2F, 0x39, 0xD8], size)),
                // REV64, REV32, REV16: the elements reversed within each container
                (_, 0b00000) | (0, 0b00001) => {
                    let container = match (u, opcode) {
                        (0, 0b00000) => 64,
                        (1, 0b00000) => 32,
                        _ => 16,
                    };
                    let esize = 8 << size;
                    let per = container / esize;
                    let lanes = element_lanes(esize, datasize / esize, |e| {
                        (0, e - e % per + (per - 1 - e % per))
                    });
                    let n = (word >> 5 & 31) as u8;
                    Some(VecForm::Shuffle {
                        first: n,
                        second: n,
                        lanes,
                        keep: datasize as u8 / 8,
                    })
                },
                // XTN, XTN2: the low halves of n's elements, into d's lower or upper half
                (0, 0b10010) => {
                    let esize = 8 << size;
                    let narrow = element_lanes(esize, 64 / esize, |e| (1, 2 * e));
                    // (element e of n, 2 * esize bits wide: byte 2e*esize/8 of n, as an
                    // esize-wide index 2e)
                    let mut lanes = [0u8; 16];
                    for b in 0..8 {
                        lanes[b] = if q { b as u8 } else { narrow[b] };
                        if q {
                            lanes[8 + b] = narrow[b];
                        }
                    }
                    Some(VecForm::Shuffle {
                        first: (word & 31) as u8,
                        second: (word >> 5 & 31) as u8,
                        lanes,
                        keep: if q { 16 } else { 8 },
                    })
                },
                _ => None,
            }
        },
        Op::SimdShiftImm if vector => {
            let opcode = word >> 11 & 31;
            let immh = word >> 19 & 15;
            let immhb = word >> 16 & 127;
            let size = 31 - immh.leading_zeros();
            let esize = 8 << size;
            match (u, opcode) {
                (0, 0b01010) => Some(VecForm::Shift {
                    op: [0x6B, 0x8B, 0xAB, 0xCB][size as usize],
                    amount: immhb - esize,
                    zero: false,
                }),
                (_, 0b00000) => {
                    let amount = 2 * esize - immhb;
                    if u == 1 {
                        Some(VecForm::Shift {
                            op: [0x6D, 0x8D, 0xAD, 0xCD][size as usize],
                            amount,
                            zero: amount == esize,
                        })
                    }
                    else {
                        Some(VecForm::Shift {
                            op: [0x6C, 0x8C, 0xAC, 0xCC][size as usize],
                            amount: amount.min(esize - 1),
                            zero: false,
                        })
                    }
                },
                _ => None,
            }
        },
        Op::SimdModImm => {
            let op = word >> 29 & 1;
            let cmode = word >> 12 & 15;
            let imm8 = (word >> 16 & 7) << 5 | word >> 5 & 31;
            let imm64 = crate::aarch64::simd::expand_imm(op, cmode, imm8 as u64);
            let imm = if q { imm64 as u128 | (imm64 as u128) << 64 } else { imm64 as u128 };
            let keep = if q { u128::MAX } else { u64::MAX as u128 };
            let orr_bic = cmode < 0b1100 && cmode & 1 == 1;
            Some(match (orr_bic, op) {
                (true, 0) => VecForm::Immediate {
                    value: imm,
                    kind: IMM_OR,
                },
                (true, _) => VecForm::Immediate {
                    value: imm,
                    kind: IMM_AND_NOT,
                },
                (false, 1) if cmode < 0b1110 => VecForm::Immediate {
                    value: !imm & keep,
                    kind: IMM_SET,
                },
                _ => VecForm::Immediate {
                    value: imm & keep,
                    kind: IMM_SET,
                },
            })
        },
        Op::SimdCopy => {
            let imm5 = word >> 16 & 31;
            let imm4 = word >> 11 & 15;
            let size = imm5.trailing_zeros();
            let esize = 8 << size;
            let index = imm5 >> (size + 1);
            let n = (word >> 5 & 31) as u8;
            if !vector {
                // DUP (element), scalar: element `index` of n, the rest zero
                let lanes = element_lanes(esize, 1, |_| (0, index));
                return Some(VecForm::Shuffle {
                    first: n,
                    second: n,
                    lanes,
                    keep: (esize / 8) as u8,
                });
            }
            if u == 1 {
                return Some(VecForm::Insert {
                    esize,
                    index,
                    source: Some(imm4 >> size),
                });
            }
            match imm4 {
                0b0000 => {
                    let lanes = element_lanes(esize, datasize / esize, |_| (0, index));
                    Some(VecForm::Shuffle {
                        first: n,
                        second: n,
                        lanes,
                        keep: datasize as u8 / 8,
                    })
                },
                0b0001 => Some(VecForm::DupGeneral { esize }),
                0b0011 => Some(VecForm::Insert {
                    esize,
                    index,
                    source: None,
                }),
                0b0101 => Some(VecForm::Move {
                    esize,
                    index,
                    signed: true,
                    wide: q,
                }),
                _ => Some(VecForm::Move {
                    esize,
                    index,
                    signed: false,
                    wide: esize == 64,
                }),
            }
        },
        Op::SimdPermute => {
            let esize = 8 << size;
            let elements = datasize / esize;
            let part = word >> 14 & 1;
            let pairs = elements / 2;
            let lanes = match word >> 12 & 3 {
                // UZP1, UZP2
                0b01 => element_lanes(esize, elements, |e| {
                    let i = 2 * e + part;
                    if i < elements {
                        (0, i)
                    }
                    else {
                        (1, i - elements)
                    }
                }),
                // TRN1, TRN2
                0b10 => element_lanes(esize, elements, |e| (e % 2, 2 * (e / 2) + part)),
                // ZIP1, ZIP2
                _ => element_lanes(esize, elements, |e| (e % 2, part * pairs + e / 2)),
            };
            Some(VecForm::Shuffle {
                first: (word >> 5 & 31) as u8,
                second: (word >> 16 & 31) as u8,
                lanes,
                keep: datasize as u8 / 8,
            })
        },
        Op::SimdExtract => {
            // EXT: bytes position.. of m:n (the 64-bit form: of m's and n's low halves)
            let position = word >> 11 & 15;
            let mut lanes = [0u8; 16];
            for k in 0..datasize / 8 {
                let at = position + k;
                lanes[k as usize] = if q {
                    at as u8
                }
                else if at < 8 {
                    at as u8
                }
                else {
                    (16 + at - 8) as u8
                };
            }
            Some(VecForm::Shuffle {
                first: (word >> 5 & 31) as u8,
                second: (word >> 16 & 31) as u8,
                lanes,
                keep: datasize as u8 / 8,
            })
        },
        Op::FpInt => {
            // FMOV (general): sf, type, rmode, opcode
            let (sf, ptype, rmode, opcode) =
                (word >> 31, word >> 22 & 3, word >> 19 & 3, word >> 16 & 7);
            if word >> 29 & 1 != 0 || opcode < 6 {
                return None;
            }
            let (bits, top) = match (sf, ptype, rmode) {
                (0, 0, 0) => (32, false),
                (1, 1, 0) => (64, false),
                (1, 2, 1) => (64, true),
                _ => return None,
            };
            Some(VecForm::FmovGeneral {
                to_gpr: opcode == 6,
                bits,
                top,
            })
        },
        _ => None,
    }
}

impl Emitter<'_> {
    fn v_address(r: u32) -> u32 { state::v as u32 + 16 * r }
    fn vload(&mut self, r: u32) {
        self.c32(Self::v_address(r) as i32);
        self.b.simd_memory(V128_LOAD, 4);
    }
    fn vstore(&mut self) { self.b.simd_memory(V128_STORE, 4) }
    /// v128 & the low `bytes` bytes
    fn keep_bytes(&mut self, bytes: u8) {
        if bytes < 16 {
            let mut mask = [0u8; 16];
            mask[..bytes as usize].fill(0xFF);
            self.b.const_v128(mask);
            self.b.simd(V128_AND);
        }
    }
    fn splat_const(&mut self, value: u64, double: bool) {
        let bytes = if double {
            let mut b = [0u8; 16];
            b[..8].copy_from_slice(&value.to_le_bytes());
            b[8..].copy_from_slice(&value.to_le_bytes());
            b
        }
        else {
            let mut b = [0u8; 16];
            for lane in 0..4 {
                b[4 * lane..4 * lane + 4].copy_from_slice(&(value as u32).to_le_bytes());
            }
            b
        };
        self.b.const_v128(bytes);
    }
    /// Push whether every lane of `l` is zero or a normal number (with
    /// `result`: of exponent 2 or more)
    fn v_ordinary(&mut self, l: &WasmLocalV128, double: bool, result: bool) {
        let (low, inf, magnitude) = if double {
            (
                if result { 0x0020_0000_0000_0000u64 } else { 0x0010_0000_0000_0000 },
                0x7FF0_0000_0000_0000u64,
                0x7FFF_FFFF_FFFF_FFFFu64,
            )
        }
        else {
            (
                if result { 0x0100_0000u64 } else { 0x0080_0000 },
                0x7F80_0000u64,
                0x7FFF_FFFFu64,
            )
        };
        let (eq, ge_s, lt_s, all_true) =
            if double { (0xD6, 0xDB, 0xD8, 0xC3) } else { (0x37, 0x3F, 0x39, 0xA3) };
        self.b.get_local_v128(l);
        self.splat_const(magnitude, double);
        self.b.simd(V128_AND);
        let m = self.b.set_new_local_v128();
        self.b.get_local_v128(&m);
        self.b.simd_zero();
        self.b.simd(eq);
        self.b.get_local_v128(&m);
        self.splat_const(low, double);
        self.b.simd(ge_s);
        self.b.get_local_v128(&m);
        self.splat_const(inf, double);
        self.b.simd(lt_s);
        self.b.simd(V128_AND);
        self.b.simd(V128_OR);
        self.b.simd(all_true);
        self.b.free_local_v128(m);
    }
    /// V[r] as a v128 local (the 64-bit form: its low half in both halves)
    fn v_operand(&mut self, r: u32, q: bool) -> WasmLocalV128 {
        self.vload(r);
        if !q {
            self.vload(r);
            self.b
                .simd_shuffle([0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7]);
        }
        self.b.set_new_local_v128()
    }

    pub(super) fn vector_instruction(&mut self, offset: u16, i: &Inst, form: VecForm) {
        let word = i.imm as u32;
        let q = word >> 30 & 1 != 0;
        let (d, n, m) = (word & 31, word >> 5 & 31, word >> 16 & 31);
        let keep = if q { 16 } else { 8 };
        self.fp_check(offset);
        match form {
            VecForm::Binary { op, invert_m, test } => {
                self.c32(Self::v_address(d) as i32);
                self.vload(n);
                self.vload(m);
                if invert_m {
                    self.b.simd(V128_NOT);
                }
                if test {
                    self.b.simd(V128_AND);
                    self.b.simd_zero();
                }
                self.b.simd(op);
                self.keep_bytes(keep);
                self.vstore();
            },
            VecForm::Select {
                first,
                second,
                mask,
            } => {
                let register = |s: Source| match s {
                    Source::D => d,
                    Source::N => n,
                    Source::M => m,
                };
                self.c32(Self::v_address(d) as i32);
                self.vload(register(first));
                self.vload(register(second));
                self.vload(register(mask));
                self.b.simd(V128_BITSELECT);
                self.keep_bytes(keep);
                self.vstore();
            },
            VecForm::Unary { op, compare_zero } => {
                self.c32(Self::v_address(d) as i32);
                self.vload(n);
                if compare_zero {
                    self.b.simd_zero();
                }
                self.b.simd(op);
                self.keep_bytes(keep);
                self.vstore();
            },
            VecForm::Shift { op, amount, zero } => {
                self.c32(Self::v_address(d) as i32);
                if zero {
                    self.b.simd_zero();
                }
                else {
                    self.vload(n);
                    self.c32(amount as i32);
                    self.b.simd(op);
                    self.keep_bytes(keep);
                }
                self.vstore();
            },
            VecForm::Shuffle {
                first,
                second,
                lanes,
                keep,
            } => {
                self.c32(Self::v_address(d) as i32);
                self.vload(first as u32);
                self.vload(second as u32);
                self.b.simd_shuffle(lanes);
                self.keep_bytes(keep);
                self.vstore();
            },
            VecForm::Immediate { value, kind } => {
                self.c32(Self::v_address(d) as i32);
                if kind != IMM_SET {
                    self.vload(d);
                }
                self.b.const_v128(value.to_le_bytes());
                match kind {
                    IMM_OR => self.b.simd(V128_OR),
                    IMM_AND_NOT => self.b.simd(V128_ANDNOT),
                    _ => {},
                }
                if kind != IMM_SET {
                    self.keep_bytes(keep);
                }
                self.vstore();
            },
            VecForm::DupGeneral { esize } => {
                self.c32(Self::v_address(d) as i32);
                self.xr(n as u8);
                if esize == 64 {
                    self.b.simd(0x12);
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.b.simd([0x0F, 0x10, 0x11][(esize / 16) as usize]);
                }
                self.keep_bytes(keep);
                self.vstore();
            },
            VecForm::Insert {
                esize,
                index,
                source,
            } => {
                let (extract, replace) = match esize {
                    8 => (0x16, 0x17),
                    16 => (0x19, 0x1A),
                    32 => (0x1B, 0x1C),
                    _ => (0x1D, 0x1E),
                };
                self.c32(Self::v_address(d) as i32);
                self.vload(d);
                match source {
                    Some(source) => {
                        self.vload(n);
                        self.b.simd_lane(extract, source as u8);
                    },
                    None => {
                        self.xr(n as u8);
                        if esize != 64 {
                            self.b.wrap_i64_to_i32();
                        }
                    },
                }
                self.b.simd_lane(replace, index as u8);
                self.vstore();
            },
            VecForm::Move {
                esize,
                index,
                signed,
                wide,
            } => {
                self.vload(n);
                let extract = match (esize, signed) {
                    (8, true) => 0x15,
                    (8, false) => 0x16,
                    (16, true) => 0x18,
                    (16, false) => 0x19,
                    (32, _) => 0x1B,
                    _ => 0x1D,
                };
                self.b.simd_lane(extract, index as u8);
                if esize != 64 {
                    if signed && wide {
                        self.b.extend_signed_i32_to_i64();
                    }
                    else {
                        self.b.extend_unsigned_i32_to_i64();
                    }
                }
                self.set_x(d as u8);
            },
            VecForm::FmovGeneral { to_gpr, bits, top } => {
                let at = Self::v_address(if to_gpr { n } else { d }) + if top { 8 } else { 0 };
                if to_gpr {
                    self.c32(at as i32);
                    self.b.memory_op(
                        if bits == 32 { op::OP_I64LOAD32U } else { op::OP_I64LOAD },
                        if bits == 32 { 2 } else { 3 },
                        0,
                    );
                    self.set_x(d as u8);
                }
                else {
                    self.c32(at as i32);
                    self.xr(n as u8);
                    if bits == 32 {
                        self.c64(0xFFFF_FFFF);
                        self.b.and_i64();
                    }
                    self.b.store_aligned_i64(0);
                    if !top {
                        self.c32(at as i32 + 8);
                        self.c64(0);
                        self.b.store_aligned_i64(0);
                    }
                }
            },
            VecForm::Fp { op, double } => self.vector_fp(offset, word, op, double),
        }
    }

    /// The FP forms: the fast path, else the helper
    fn vector_fp(&mut self, offset: u16, word: u32, op: u8, double: bool) {
        let q = word >> 30 & 1 != 0;
        let (d, n, m) = (word & 31, word >> 5 & 31, word >> 16 & 31);
        let done = self.b.block_void();
        let a = self.v_operand(n, q);
        let b = self.v_operand(m, q);
        let c = if op >= 4 { Some(self.v_operand(d, q)) } else { None };
        // RMode RN and FZ 0 (FPCR), IXC already set (FPSR)
        self.load32(state::fpcr as u32);
        self.c32(0x01C0_0000);
        self.b.and_i32();
        self.b.eqz_i32();
        self.load32(state::fpsr as u32);
        self.c32(4);
        self.b.shr_u_i32();
        self.c32(1);
        self.b.and_i32();
        self.b.and_i32();
        for l in [Some(&a), Some(&b), c.as_ref()].into_iter().flatten() {
            self.v_ordinary(l, double, false);
            self.b.and_i32();
        }
        if op == 3 {
            // (FDIV: no divisor lane zero)
            self.b.get_local_v128(&b);
            self.splat_const(
                if double { 0x7FFF_FFFF_FFFF_FFFF } else { 0x7FFF_FFFF },
                double,
            );
            self.b.simd(V128_AND);
            self.b.simd_zero();
            self.b.simd(if double { 0xD7 } else { 0x38 });
            self.b.simd(if double { 0xC3 } else { 0xA3 });
            self.b.and_i32();
        }
        self.b.if_void();
        self.b.get_local_v128(&a);
        self.b.get_local_v128(&b);
        match op {
            4 | 5 => {
                self.b.get_local_v128(c.as_ref().unwrap());
                // relaxed_madd(n, m, d) = n * m + d, relaxed_nmadd = -(n * m) + d, fused (probed)
                self.b.simd(match (double, op == 5) {
                    (false, false) => 0x105,
                    (false, true) => 0x106,
                    (true, false) => 0x107,
                    (true, true) => 0x108,
                });
            },
            _ => {
                // (f32x4 add, sub, mul, div 0xE4-0xE7; f64x2 0xF0-0xF3)
                self.b.simd(if double { 0xF0 } else { 0xE4 } + op as u32);
            },
        }
        let r = self.b.set_new_local_v128();
        self.v_ordinary(&r, double, true);
        self.b.if_void();
        self.c32(Self::v_address(d) as i32);
        self.b.get_local_v128(&r);
        self.keep_bytes(if q { 16 } else { 8 });
        self.vstore();
        self.b.br(done);
        self.b.block_end();
        self.b.block_end();
        // the exact path: the interpreter
        let sync = HelperSync {
            gprs: vec![],
            nzcv: false,
        };
        self.helper_call(offset, &sync);
        self.b.block_end();
        self.b.free_local_v128(r);
        for l in [Some(a), Some(b), c].into_iter().flatten() {
            self.b.free_local_v128(l);
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                   source/v64/src/rust/aarch64/jit/pages.rs                                                            0000644 0000000 0000000 00000162437 00000000000 015150  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The A64 page tier's runtime (docs/jit-unification-plan.md P6, J2;
//! docs/arm64-virt-android16-plan.md P6): jitrt's client A64Page in the ARM
//! core. One Wasm function per 4 KiB code page (crate::aarch64::jit::pagegen),
//! keyed by the page's code key (its RAM backing page from the AddressSpace,
//! P6.1: the code is position independent) with the mode it was compiled for
//! (the EL and whether SP alignment is checked); compiled once the
//! interpreter ran HOT instructions on the page, published through
//! jitrt::publish, retired when the page is written (jitrt::watch: the
//! interpreter's and compiled code's stores, DC ZVA, store-exclusives, DMA,
//! the loader and restores all reach bus::written or a64_bus_written). The
//! run loop (crate::aarch64::smp) offers each block boundary to `run`.
//!
//! What a page function reads and writes of the core: the registers, SP,
//! NZCV and the PC from the state block (loaded in its prologue, written
//! back at every way out and around single steps), guest memory through the
//! access cache (jitrt::access: per core and EL, filled by a64_page_access
//! from translations the TLB holds, so every TLB flush of the core retires
//! them, P6.4) and the chaining tables (jitrt::chain, per core and mode).
//! Steps go to the interpreter (A64Step, jitrt::step; P6.2).
//!
//! Not run (the interpreter goes on): with the MMU off (data accesses are
//! Device memory) or SCTLR_EL1.A set, with a breakpoint or watchpoint
//! enabled, while software step is active, with PSTATE.IL set.

use crate::aarch64::bus::{self, Lookup};
use crate::aarch64::cpu::{self, PSTATE_IL};
use crate::aarch64::execute::{self, Flow};
use crate::aarch64::jit::pagegen;
use crate::aarch64::state::{
    a64_code_base, a64_jac_base, a64_jac_epoch, a64_page_chain, a64_page_exit, a64_page_linear,
    mdscr_el1, sctlr_el1, tcr_el1, ttbr0_el1, ttbr1_el1,
};
use crate::isa::{current_core, MAX_CORES};
use crate::jitrt::access::{AccessCache, TagLayout};
use crate::jitrt::chain::ChainTable;
use crate::jitrt::page::{Function, PageFrontend, PageRuntime};
use crate::jitrt::publish::{self, Phase};
use crate::jitrt::step::{self, StepFrontend, StepOutcome, EXIT_RETRY, EXIT_UNKNOWN};
use crate::jitrt::table::{Owner, Signature};
use crate::jitrt::{self, ClientId};
use crate::page::Page;
use crate::wasmgen::wasm_builder::WasmBuilder;
use std::collections::HashSet;

extern "C" {
    fn call_indirect1_ret(f: i32, x: u16) -> i32;
}

// ---- switches (crate::aarch64::jit's registry)

/// The page tier runs (a64_page; default off until its F gate)
pub static mut ENABLED: bool = false;
/// AArch32's code is compiled too (a64_page_aarch32, docs/aarch32-plan.md Q6)
pub static mut AARCH32: bool = true;
/// (bisecting) the switch's value: 2 helper calls only, 3 native forms only, 16 + a mask
pub static mut AARCH32_DEBUG: u32 = 1;
/// (bisecting, a64_page_aarch32_filter) n << 16 | pattern
pub static mut AARCH32_FILTER: u32 = 0;
/// (debugging, a64_page_aarch32_trace) the last events of AArch32's EL0
/// code, its exceptions and returns, printed when an IT instruction is
/// UNDEFINED inside an IT block (a32_trace_dump)
pub static mut A32_TRACE: bool = false;
const TRACE_LENGTH: usize = 384;
/// (kind, core, ITSTATE, PC, extra): kinds 1 interpreted (the word), 2 a
/// helper (the word), 3 a function entered (its slot), 4 left (the exit
/// code | retired << 8), 5 a step (before), 8 its end (the step's result),
/// 6 an exception taken (the CPSR it saved), 7 an exception return (the CPSR)
static mut TRACE: [(u8, u8, u8, u32, u32); TRACE_LENGTH] = [(0, 0, 0, 0, 0); TRACE_LENGTH];
static mut TRACE_AT: usize = 0;
#[inline(always)]
pub fn a32_trace(kind: u8, pc: u32, extra: u32) {
    unsafe {
        if !A32_TRACE {
            return;
        }
        TRACE[TRACE_AT % TRACE_LENGTH] = (
            kind,
            current_core() as u8,
            crate::aarch64::t32::itstate() as u8,
            pc,
            extra,
        );
        TRACE_AT += 1;
    }
}
/// (a64_page_aarch32_trace) the trace, oldest first, and the page function's
/// view of the PC's page (pagegen::describe_a32)
pub fn a32_trace_dump(why: &str) {
    if !unsafe { A32_TRACE } {
        return;
    }
    let pc = cpu::get_pc();
    console_log!("a32 trace: {} at {:x} core {}", why, pc, current_core());
    let at = unsafe { TRACE_AT };
    for i in at.saturating_sub(TRACE_LENGTH)..at {
        let (kind, core, it, pc, extra) = unsafe { TRACE[i % TRACE_LENGTH] };
        let name = [
            "?", "interp", "helper", "enter", "leave", "step", "exc", "eret", "stepped",
        ][kind as usize % 9];
        console_log!(
            "  {} c{} it={:02x} {:08x} {:08x}",
            name,
            core,
            it,
            pc,
            extra
        );
    }
    let mode = mode();
    if let Some(key) = code_page(pc, mode) {
        let code_key = key & ((1 << MODE_SHIFT) - 1);
        let r = rt();
        let entries: Vec<u16> = r.pages.get(&key).map_or(Vec::new(), |state| {
            (0..4096u16)
                .filter(|&o| state.entries[o as usize / 64] >> (o % 64) & 1 != 0)
                .collect()
        });
        let compiled = r.by_page.get(&key).is_some();
        if code_key < bus::EXTENDED_CODE_KEY {
            let bytes = unsafe {
                std::slice::from_raw_parts(bus::MEM8.add((code_key << 12) as usize), 4096)
            };
            let offset = (pc & 0xFFF) as u16;
            console_log!(
                "a32 trace: page key {:x} compiled {} entries {:?}",
                key,
                compiled,
                entries
            );
            console_log!(
                "{}",
                pagegen::describe_a32(
                    bytes,
                    &entries,
                    pagegen::CompileEnv {
                        el1: false,
                        sp_checked: false,
                        chaining: true,
                        neon: unsafe { super::NEON },
                        helpers: unsafe { super::HELPERS },
                        system: unsafe { super::SYSTEM },
                        relaxed_fma: unsafe { super::RELAXED_FMA },
                        isa: if mode & !1 == MODE_T32 {
                            pagegen::Isa::T32
                        }
                        else {
                            pagegen::Isa::A32
                        },
                    },
                    offset.saturating_sub(32),
                    offset + 16,
                )
            );
        }
    }
    unsafe { TRACE_AT = 0 };
}
/// Interpreted instructions on a page before it is compiled
pub static mut HOT: u32 = 2000;
/// Unserved entries of a published function before its page is recompiled
const RECOMPILE_MISSES: u32 = 64;
/// The most functions (this client's quota of the core's table)
pub const MAX_FUNCTIONS: u32 = 9000;
/// The most Wasm bytes of live functions, MiB (a64_page_code_mb): the host
/// commits about 1.3 times as much machine code for them, and every core
/// of a process (cores in workers) draws on one limit, V8's 4 GiB of
/// committed Wasm code; Android's boot on four cores exceeded it with the
/// table full of functions. Past it the least recently used ones go
pub static mut CODE_BUDGET_MB: u32 = 160;
/// The Wasm bytes of the live (and pending) functions
static mut LIVE_BYTES: u64 = 0;
/// Instructions an activation may retire: the run loop ticks the timers
/// and takes interrupts between activations (a step ticks them too)
const MAX_BUDGET: u32 = 1 << 14;

// ---- keys and modes

/// A function's key: the code key (below 2^28) with its mode's bits
const MODE_SHIFT: u32 = 28;
/// Modes: bit 0 EL1, bit 1 SP alignment checked; AArch32, A32 and T32 at
/// EL0 (Q6), or PL1 with bit 0 (cpu_type arm32, R5.3)
pub const MODES: usize = 8;
pub const MODE_A32: u32 = 4;
pub const MODE_T32: u32 = 6;

/// Whether a mode is AArch32's (A32 or T32, either privilege)
#[inline(always)]
fn aarch32_mode(mode: u32) -> bool { mode & !1 == MODE_A32 || mode & !1 == MODE_T32 }

/// The mode the running core's code would be compiled for
#[inline(always)]
fn mode() -> u32 {
    if cpu::aarch32() {
        let isa = if cpu::get_pstate() & cpu::PSTATE_T != 0 { MODE_T32 } else { MODE_A32 };
        return isa | (cpu::el() != 0) as u32;
    }
    let el1 = cpu::el() != 0;
    let sctlr = cpu::sctlr();
    let sp_checked = sctlr & if el1 { cpu::SCTLR_SA } else { cpu::SCTLR_SA0 } != 0;
    el1 as u32 | (sp_checked as u32) << 1
}

// ---- the access cache (jitrt::access) and the chaining tables (jitrt::chain)

/// A64's tags: the virtual page below bit 52, the epoch above (with
/// a64_asid_tag, the ASID's: bind_asid); a tagged pointer (TBI: Android's
/// heap pointers) gets an entry of its own in the untagged page's slot,
/// which a TLBI by VA (naming the page untagged) clears with it
/// (tlb_flushed_page); regions: no block marks them (the TLB decides when a
/// page's invalidation flushes, tlb::flush_page)
pub const LAYOUT: TagLayout = TagLayout {
    epoch_shift: 52,
    region_shift: 21,
};
pub const ENTRIES: usize = 2048;
static mut ACCESS: [AccessCache; MAX_CORES] = [const { AccessCache::NEW }; MAX_CORES];
#[inline(always)]
fn access(core: usize) -> &'static mut AccessCache { unsafe { &mut (*(&raw mut ACCESS))[core] } }

#[repr(C, align(16))]
struct ChainTables([ChainTable; MODES]);
static mut CHAIN: [ChainTables; MAX_CORES] =
    [const { ChainTables([const { ChainTable::EMPTY }; MODES]) }; MAX_CORES];
#[inline(always)]
fn chain(core: usize) -> &'static mut ChainTables { unsafe { &mut (*(&raw mut CHAIN))[core] } }
/// Whether generated code tail-calls between pages (the host supports Wasm
/// tail calls: jit_set_tail_calls)
static mut CHAINING: bool = false;
#[no_mangle]
pub fn a64_page_set_chaining(enabled: bool) {
    unsafe { CHAINING = enabled };
    clear_chains();
}
fn clear_chains() {
    for core in 0..MAX_CORES {
        for table in chain(core).0.iter_mut() {
            table.clear();
        }
    }
}

/// Per core: the code pages' translations (tag: epoch | mode, the virtual
/// page, the function key), direct mapped by virtual page
const CODE_TLB_SIZE: usize = 16;
static mut CODE_TLB: [[(u64, u64, u32); CODE_TLB_SIZE]; MAX_CORES] =
    [[(0, 0, 0); CODE_TLB_SIZE]; MAX_CORES];

/// The TLB of `core` was flushed: its access cache entries and code
/// translations retire (an epoch), its chaining entries go
pub fn tlb_flushed(core: usize) {
    if unsafe { super::ASID_TAG } {
        // (every ASID's epoch goes; the chaining tables' and the code TLB's
        // entries of old epochs never match again)
        asids(core).slots = [NO_SLOT; ASID_SLOTS];
        fresh_epoch(core);
        return;
    }
    if access(core).flush(LAYOUT) {
        // (the epochs wrapped: the tables were emptied, and tags of old epochs would match again)
        unsafe { CODE_TLB[core] = [(0, 0, 0); CODE_TLB_SIZE] };
    }
    for table in chain(core).0.iter_mut() {
        table.clear();
    }
}
/// The TLB of `core` dropped its non-global entries (an ASID's)
pub fn tlb_flushed_nonglobal(core: usize) {
    access(core).flush_nonglobal(ENTRIES);
    unsafe { CODE_TLB[core] = [(0, 0, 0); CODE_TLB_SIZE] };
    for table in chain(core).0.iter_mut() {
        table.forget_nonglobal();
    }
}
/// The TLB of `core` dropped the non-global entries of `asid` (TLBI ASIDE1)
pub fn tlb_flushed_asid(core: usize, asid: u16) {
    if !unsafe { super::ASID_TAG } {
        return tlb_flushed_nonglobal(core);
    }
    let a = asids(core);
    match a.slots.iter().position(|s| s.epoch != 0 && s.asid == asid) {
        Some(i) if a.current == Some(i) => drop_current_epoch(core),
        Some(i) => a.slots[i] = NO_SLOT,
        None => {},
    }
}
/// The TLB of `core` dropped the entries of virtual page `page` (VA >> 12,
/// TBI applied) for `asid` (and the global ones), or for every ASID (None)
pub fn tlb_flushed_page(core: usize, page: u64, asid: Option<u16>) {
    let flushed = access(core).invalidate_page(LAYOUT, ENTRIES, page << 12);
    if flushed.is_none() {
        forget_tagged(core, page);
    }
    unsafe { CODE_TLB[core][page as usize & (CODE_TLB_SIZE - 1)].0 = 0 };
    for table in chain(core).0.iter_mut() {
        table.forget_page(LAYOUT, page);
    }
    if unsafe { super::ASID_TAG } {
        if flushed.is_some() {
            // (jitrt's flush numbered the new epoch itself: start over)
            asids(core).slots = [NO_SLOT; ASID_SLOTS];
            fresh_epoch(core);
            return;
        }
        // the other epochs that may hold the page: the ASID's, those with a
        // global translation in the lower half, all of them for the upper
        // half (the kernel's global pages are in every epoch)
        let upper = page >> 43 & 1 != 0;
        let a = asids(core);
        for i in 0..ASID_SLOTS {
            let slot = a.slots[i];
            if a.current != Some(i)
                && slot.epoch != 0
                && (upper || slot.low_global || asid.map_or(true, |x| x == slot.asid))
            {
                a.slots[i] = NO_SLOT;
            }
        }
    }
    else if flushed == Some(true) {
        // (the epochs wrapped: tags of old epochs would match again)
        unsafe { CODE_TLB[core] = [(0, 0, 0); CODE_TLB_SIZE] };
        for table in chain(core).0.iter_mut() {
            table.clear();
        }
    }
}

/// The current epoch's entries of virtual page `page` under any pointer tag
/// (TBI: VA bits 63:56, the page number's 51:44) go: they share the
/// untagged page's slot
fn forget_tagged(core: usize, page: u64) {
    const TAG_BITS: u64 = 0xFF << 44;
    let cache = access(core);
    let epoch = cache.epoch();
    for kind in 0..crate::jitrt::access::TABLES {
        let entry = &mut cache.tables[AccessCache::slot(ENTRIES, kind, page)];
        if entry.tag != 0
            && entry.tag >> LAYOUT.epoch_shift == epoch
            && LAYOUT.page(entry.tag) & !TAG_BITS == page & !TAG_BITS
        {
            entry.tag = 0;
        }
    }
}

// ---- a64_asid_tag (P6.4): an epoch per ASID

/// With a64_asid_tag, each recently used ASID of a core has an epoch of its
/// own: an ASID switch makes the running ASID's epoch the access cache's
/// current one (its entries, and the code TLB's and chaining tables', are
/// live again) instead of dropping every non-global entry. Epoch numbers are
/// never reused before the epochs wrap (everything is emptied then), and
/// binding happens at an activation (bind_asid), which a TTBR write by a
/// single step ends. A TLBI drops the epochs its entries may be in: TLBI
/// ASIDE1 the ASID's; a TLBI by VA the current epoch's entries of the page,
/// and the other epochs that may hold it; anything else, every epoch.
const ASID_SLOTS: usize = 16;
#[derive(Clone, Copy)]
struct AsidSlot {
    asid: u16,
    /// 0: an empty slot
    epoch: u64,
    used: u64,
    /// an entry of a global translation in the lower half (TTBR0) was filled
    low_global: bool,
}
const NO_SLOT: AsidSlot = AsidSlot {
    asid: 0,
    epoch: 0,
    used: 0,
    low_global: false,
};
struct Asids {
    slots: [AsidSlot; ASID_SLOTS],
    /// the slot of the current epoch (None: a fresh epoch, no entries yet)
    current: Option<usize>,
    /// the last epoch number given out
    latest: u64,
    clock: u64,
}
static mut ASIDS: [Asids; MAX_CORES] = [const {
    Asids {
        slots: [NO_SLOT; ASID_SLOTS],
        current: None,
        latest: 0,
        clock: 0,
    }
}; MAX_CORES];
fn asids(core: usize) -> &'static mut Asids { unsafe { &mut (*(&raw mut ASIDS))[core] } }

/// A new epoch number, made the current epoch of `core`'s access cache
/// (bound to no ASID yet); when the numbers run out, everything tagged
/// with one is emptied
fn fresh_epoch(core: usize) -> u64 {
    let a = asids(core);
    a.latest = a.latest.max(access(core).epoch()) + 1;
    if a.latest >= LAYOUT.epoch_limit() {
        access(core).clear();
        unsafe { CODE_TLB[core] = [(0, 0, 0); CODE_TLB_SIZE] };
        for table in chain(core).0.iter_mut() {
            table.clear();
        }
        a.slots = [NO_SLOT; ASID_SLOTS];
        a.latest = 1;
    }
    access(core).set_epoch(a.latest);
    a.current = None;
    a.latest
}
/// The current epoch's entries are no longer valid: its slot goes, a fresh epoch comes
fn drop_current_epoch(core: usize) {
    let a = asids(core);
    if let Some(i) = a.current {
        a.slots[i] = NO_SLOT;
    }
    fresh_epoch(core);
}
/// Before compiled code runs or the code TLB is used: the access cache's
/// current epoch is the running ASID's
#[inline]
fn bind_asid(core: usize) {
    if !unsafe { super::ASID_TAG } {
        return;
    }
    let asid = crate::aarch64::mmu::current_asid();
    let a = asids(core);
    if let Some(i) = a.current {
        if a.slots[i].asid == asid {
            return;
        }
    }
    a.clock += 1;
    if let Some(i) = a.slots.iter().position(|s| s.epoch != 0 && s.asid == asid) {
        a.slots[i].used = a.clock;
        access(core).set_epoch(a.slots[i].epoch);
        a.current = Some(i);
        return;
    }
    // (an unbound epoch has no entries: the ASID takes it; else a fresh one)
    let epoch = if a.current.is_none() { access(core).epoch() } else { fresh_epoch(core) };
    let a = asids(core);
    let i = a
        .slots
        .iter()
        .position(|s| s.epoch == 0)
        .unwrap_or_else(|| (0..ASID_SLOTS).min_by_key(|&i| a.slots[i].used).unwrap());
    a.slots[i] = AsidSlot {
        asid,
        epoch,
        used: a.clock,
        low_global: false,
    };
    a.current = Some(i);
}
/// a64_asid_tag 2 (auto): every AUTO_WINDOW ticks of the run loop (about 4
/// million instructions) the tags go on when the ASIDs changed AUTO_ON times
/// or more in the window, off when fewer than AUTO_OFF (P9.3: about 1300 per
/// window while the androidish kernel, with SW_TTBR0_PAN, boots Alpine to a
/// login; about 7 for the stock kernel)
const AUTO_WINDOW: u32 = 4096;
const AUTO_ON: u64 = 256;
const AUTO_OFF: u64 = 16;
static mut AUTO_TICKS: u32 = 0;
static mut AUTO_LAST: u64 = 0;
/// the tags turned on or off by auto
static mut AUTO_SWITCHES: u64 = 0;
/// (crate::aarch64::smp::run_core, about every 1024 instructions: no compiled code is active)
pub fn asid_tag_tick() {
    unsafe {
        if super::ASID_TAG_MODE != 2 {
            return;
        }
        AUTO_TICKS += 1;
        if AUTO_TICKS < AUTO_WINDOW {
            return;
        }
        AUTO_TICKS = 0;
        let changes = crate::aarch64::mmu::asid_changes();
        let window = changes.wrapping_sub(AUTO_LAST);
        AUTO_LAST = changes;
        if !super::ASID_TAG && window >= AUTO_ON || super::ASID_TAG && window < AUTO_OFF {
            set_asid_tag(!super::ASID_TAG);
            AUTO_SWITCHES += 1;
        }
    }
}

/// a64_asid_tag changed: every core's cache starts over, empty (an epoch
/// number either way may have been given out by the other)
pub fn set_asid_tag(on: bool) {
    unsafe { super::ASID_TAG = on };
    for core in 0..MAX_CORES {
        access(core).clear();
        unsafe { CODE_TLB[core] = [(0, 0, 0); CODE_TLB_SIZE] };
        for table in chain(core).0.iter_mut() {
            table.clear();
        }
        let a = asids(core);
        a.slots = [NO_SLOT; ASID_SLOTS];
        a.current = None;
    }
}

// ---- the runtime

pub struct A64;
/// A function's own data: its source page's hash when it was compiled
/// (with cores in workers, checked again when it is installed, P8.2)
#[derive(Default)]
pub struct A64Code {
    source: u64,
    /// its module's Wasm bytes, against CODE_BUDGET_MB
    bytes: u32,
}
#[derive(Default)]
pub struct A64Page;
pub struct A64Extra {
    /// the page of the last activation's or boundary's PC, for heat
    last_key: u32,
    /// instructions interpreted since the last boundary
    interpreted: u32,
}
impl PageFrontend for A64 {
    type Code = A64Code;
    type Page = A64Page;
    type Extra = A64Extra;
}
type Runtime = PageRuntime<A64>;
static mut RUNTIME: Option<Runtime> = None;
fn rt() -> &'static mut Runtime {
    unsafe {
        (*(&raw mut RUNTIME)).get_or_insert_with(|| {
            Runtime::new(A64Extra {
                last_key: u32::MAX,
                interpreted: 0,
            })
        })
    }
}

// statistics (jit_stat(1, n), a64_page_stat)
const COMPILED: usize = 0;
const ACTIVATIONS: usize = 1;
const RETIRED: usize = 2;
const STEPS: usize = 3;
const RETRIES: usize = 4;
const UNKNOWN: usize = 5;
const RETIRED_FUNCTIONS: usize = 6;
const ACCESS_FILLS: usize = 7;
const ACCESS_REFUSED: usize = 8;
const FAILED: usize = 9;
const CHAINED: usize = 10;
const INSTRUCTIONS: usize = 11;
const TEMPLATED: usize = 12;
/// (the client's own counters, past PageRuntime::stats)
static mut WRITES: u64 = 0;
static mut RESETS: u64 = 0;
static mut HELPERS: u64 = 0;
/// functions retired to make room (P6.6b), and the time spent compiling (ms)
static mut EVICTIONS: u64 = 0;
static mut COMPILE_MS: f64 = 0.0;

/// Code retired (a write to code, a reset): a step that sees it changed ends the activation
static mut CODE_WRITES: u64 = 0;

/// (diagnostics) why the access cache refused a fill (a64_page_stat 120 +
/// reason): a page crossing (or SCTLR_EL1.A), no translation (a fault, or
/// none the cache may hold), a write to memory that is not writable RAM, a
/// write to a page with code, a write to a page a core holds a reservation
/// in, extended RAM without a frame, not RAM; and an unaligned access the
/// caller cannot take (filled, refused this once)
const REFUSED_CROSSING: usize = 0;
const REFUSED_TRANSLATION: usize = 1;
const REFUSED_NOT_WRITABLE: usize = 2;
const REFUSED_WATCHED: usize = 3;
const REFUSED_RESERVED: usize = 4;
const REFUSED_EXTENDED: usize = 5;
const REFUSED_NOT_RAM: usize = 6;
const REFUSED_UNALIGNED: usize = 7;
static mut REFUSED: [u64; 8] = [0; 8];

/// (a64_reserved_fill) whether a write entry to a page some core holds a
/// reservation in is refused also with the cores in workers, where a
/// store-exclusive compares the value instead (docs/aarch64.md) and the
/// write entries already filled stay; with four cores the refusals (every
/// store to an ART lock word's page through the interpreter) cost more
/// than the reservation they protect
pub static mut RESERVED_FILL_REFUSED: bool = false;
/// (a64_step_stats) whether steps and helper calls are counted (a64_step_stat)
pub static mut STEP_STATS: bool = true;
/// Steps and helper calls are counted one in STEP_SAMPLE (the counts in
/// machine memory, which every core writes, scaled up): a count per call
/// made the cores share the counters' cache lines
const STEP_SAMPLE: u32 = 64;
static mut STEP_SAMPLED: u32 = 0;
#[inline(always)]
fn refused(reason: usize) { unsafe { REFUSED[reason] += 1 } }

/// A function is retired: its chaining entries and fast entries go
fn retire(r: &mut Runtime, index: usize) {
    if !r.kill(index) {
        return;
    }
    let f = &r.functions[index];
    unsafe { LIVE_BYTES = LIVE_BYTES.saturating_sub(f.x.bytes as u64) };
    for &key in &f.members {
        if r.by_page.get(&key) == Some(&index) {
            r.by_page.remove(&key);
        }
    }
    let table_index = f.slot + crate::aarch64::root::WASM_TABLE_OFFSET;
    for core in 0..MAX_CORES {
        for table in chain(core).0.iter_mut() {
            table.unchain(table_index);
        }
    }
    r.stats[RETIRED_FUNCTIONS] += 1;
    unsafe { CODE_WRITES += 1 };
}
/// At a cold point: dead functions' slots back to the table
fn release_dead(r: &mut Runtime) {
    r.release_dead(|slot, id| {
        let mut rt = jitrt::state();
        if rt.table.release(slot, ClientId::A64Page, id) {
            rt.watch.detach(slot);
            (jitrt::host::env().clear_slot)(slot);
        }
    });
}

/// The watch's listener (crate::aarch64::root): the code page `page` (a
/// code key) was written; the functions of each mode compiled from it retire
pub fn page_written(page: u32) {
    unsafe { WRITES += 1 };
    let r = rt();
    for mode in 0..MODES as u32 {
        if let Some(&index) = r.by_page.get(&(page | mode << MODE_SHIFT)) {
            retire(r, index);
        }
    }
}
/// Every function retires (a reset of the watch: a new map, a restore)
pub fn retire_all() {
    unsafe { RESETS += 1 };
    let r = rt();
    for index in 0..r.functions.len() {
        retire(r, index);
    }
    for core in 0..MAX_CORES {
        tlb_flushed(core);
    }
}

/// Before `core` runs (crate::aarch64::smp::switch_to): its write entries to
/// the RAM pages the cores in `monitors` hold reservations in retire, so
/// that its compiled stores there reach the global monitor (P3.7). (A scan
/// at every reservation instead cost 2-core Alpine half its speed, also
/// interpreted: every atomic is a load-exclusive.)
pub fn retire_reserved_writes(core: usize, monitors: u32) {
    if !unsafe { ENABLED } {
        return;
    }
    let mem8 = unsafe { bus::MEM8 } as u32;
    let mut hosts = [u32::MAX; MAX_CORES];
    let mut count = 0;
    let mut extended = false;
    for c in 0..MAX_CORES {
        if monitors & 1 << c != 0 {
            let backing = crate::aarch64::smp::reserved_backing(c);
            extended |= backing >= crate::aarch64::extended::KEY_BASE;
            hosts[count] = mem8.wrapping_add(backing & !0xFFF);
            count += 1;
        }
    }
    // (a reservation in extended RAM: its key names no frame, so the write
    // entries to every frame retire)
    let (start, end) =
        if extended { unsafe { crate::aarch64::extended::frame_range() } } else { (0, 0) };
    access(core).retire_writes(ENTRIES, |entry| {
        hosts[..count].contains(&entry.host) || entry.host >= start && entry.host < end
    });
}

/// The frame of extended RAM at `host` gained code: write entries to it retire
pub fn retire_writes_to(host: u32) {
    for core in 0..MAX_CORES {
        access(core).retire_writes(ENTRIES, |entry| entry.host == host);
    }
}

/// Pages that gained code: write entries to them retire (stores must notify)
pub fn pages_gain_code(pages: &HashSet<Page>) {
    let mem8 = unsafe { bus::MEM8 } as u32;
    for page in pages {
        let host = mem8.wrapping_add(page.to_u32() << 12);
        for core in 0..MAX_CORES {
            access(core).retire_writes(ENTRIES, |entry| entry.host == host);
        }
    }
}

// ---- running

/// What `run` did: nothing (the interpreter goes on), or an activation
pub enum Ran {
    None,
    /// `retired` instructions; `flow`: what a single step that ended it
    /// asks of the run loop (a wait, a stop, a yield), else Flow::Next
    Native {
        retired: u32,
        flow: Flow,
    },
}

#[inline(always)]
fn allowed() -> bool {
    let sctlr = cpu::sctlr();
    unsafe {
        ENABLED
            && sctlr & cpu::SCTLR_M != 0
            && sctlr & cpu::SCTLR_A == 0
            && !crate::aarch64::debug::ANY_BREAKPOINT
            && !crate::aarch64::debug::ANY_WATCHPOINT
            && !crate::aarch64::debug::stepping()
            && cpu::get_pstate() & PSTATE_IL == 0
    }
}

/// The function key of the code page at `pc` for the current mode, if it is RAM
fn code_page(pc: u64, mode: u32) -> Option<u32> {
    let core = current_core();
    let tag = access(core).epoch_bits(LAYOUT) | mode as u64;
    let index = (pc >> 12) as usize & (CODE_TLB_SIZE - 1);
    let (cached_tag, page, key) = unsafe { CODE_TLB[core][index] };
    if cached_tag == tag && page == pc >> 12 {
        return Some(key);
    }
    let pa = crate::aarch64::mmu::translate(
        pc,
        crate::aarch64::memory::Access::Fetch,
        cpu::el() == 0,
        4,
    )
    .ok()?
    .pa;
    let code_key = bus::bus().code_key(pa)?;
    // (code in extended RAM: compiled with the cores in one instance; in
    // workers it is interpreted, P8.5)
    if code_key >= 1 << MODE_SHIFT
        || code_key >= bus::EXTENDED_CODE_KEY && crate::parallel::active()
    {
        return None;
    }
    let key = code_key | mode << MODE_SHIFT;
    unsafe { CODE_TLB[core][index] = (tag, pc >> 12, key) };
    Some(key)
}

/// At a block boundary (a branch, an exception, a slice's start): run the
/// function of the PC's page if there is one ready and it serves the PC,
/// for at most `budget` instructions; else note the page's heat and entry,
/// and compile it when hot
pub fn run(budget: u32) -> Ran {
    // (AArch32's code with a64_page_aarch32, docs/aarch32-plan.md Q6, R5.3; not
    // from inside an IT block: compiled code enters at ITSTATE 0, little-endian)
    if !allowed()
        || budget == 0
        || cpu::aarch32()
            && !(unsafe { AARCH32 }
                && crate::aarch64::t32::itstate() == 0
                && cpu::get_pstate() & cpu::PSTATE_E == 0)
    {
        return Ran::None;
    }
    let pc = cpu::get_pc();
    let mode = mode();
    bind_asid(current_core());
    let Some(key) = code_page(pc, mode)
    else {
        return Ran::None;
    };
    let offset = (pc & 0xFFF) as u16;
    let r = rt();
    // (heat: the instructions interpreted since the last boundary went to its page)
    let interpreted = std::mem::replace(&mut r.x.interpreted, 0);
    if r.x.last_key != u32::MAX && interpreted != 0 {
        let last = r.x.last_key;
        if !r.by_page.contains_key(&last) {
            let state = r.pages.entry(last).or_default();
            state.heat = state.heat.saturating_add(interpreted);
        }
    }
    r.x.last_key = key;
    if let Some(&index) = r.by_page.get(&key) {
        let f = &r.functions[index];
        if f.phase == Phase::Ready {
            if f.serves(0, offset) {
                let slot = f.slot;
                r.clock += 1;
                r.functions[index].last_used = r.clock;
                let ran = execute(slot, budget, pc);
                if key & ((1 << MODE_SHIFT) - 1) >= bus::EXTENDED_CODE_KEY {
                    if let Ran::Native { retired, .. } = ran {
                        unsafe { crate::aarch64::extended::RETIRED[1] += retired as u64 };
                    }
                }
                return ran;
            }
            // (an entry it does not serve: noted, recompiled after enough of them)
            let state = r.pages.entry(key).or_default();
            note_entry_bits(&mut state.entries, offset);
            state.misses += 1;
            if state.misses >= RECOMPILE_MISSES {
                state.misses = 0;
                compile(key, pc);
            }
        }
        return Ran::None;
    }
    let state = r.pages.entry(key).or_default();
    note_entry_bits(&mut state.entries, offset);
    let threshold = unsafe { HOT } << crate::jitrt::heat::backoff(state.compiles);
    if state.heat >= threshold {
        state.heat = 0;
        compile(key, pc);
    }
    Ran::None
}

/// The run loop interpreted an instruction (heat for the page of the last boundary)
#[inline(always)]
pub fn interpreted() { unsafe { (*(&raw mut RUNTIME)).as_mut().map(|r| r.x.interpreted += 1) }; }

fn note_entry_bits(entries: &mut [u64; 64], offset: u16) {
    entries[offset as usize / 64] |= 1 << (offset % 64);
}

/// (the parallel build) where page functions copy unaligned reads to,
/// pagegen::frame: two slots of 32 bytes (a pair's elements)
#[repr(C, align(16))]
struct Bounce([u8; 64]);
static mut BOUNCE: Bounce = Bounce([0; 64]);
pub fn bounce_address() -> u32 { &raw mut BOUNCE as u32 }

/// The flow a step asked for (a wait, a stop, a yield) while compiled code ran
static mut STEP_FLOW: Option<Flow> = None;
/// A helper's instruction that completed but asked the run loop for
/// something (a load-exclusive's spin yield): its next PC and that flow;
/// the function left as for a retry, which this finishes instead of
/// executing the instruction again
static mut HELPER_DONE: Option<(u64, Flow)> = None;

fn execute(slot: u32, budget: u32, pc: u64) -> Ran {
    let core = current_core();
    let mode = mode();
    // (functions leaving for this page chain to this one: jitrt::chain)
    let epoch_bits = access(core).epoch_bits(LAYOUT);
    chain(core).0[mode as usize].fill(
        pc >> 12,
        epoch_bits,
        slot + crate::aarch64::root::WASM_TABLE_OFFSET,
        false,
    );
    unsafe {
        *a64_page_exit = 0;
        *a64_page_chain = 0;
        *a64_page_linear = pc & !0xFFF;
        *a64_jac_epoch = access(core).epoch_bits(LAYOUT);
        *a64_jac_base = access(core).base(ENTRIES, (mode & 1 == 0) as usize);
        *a64_code_base = chain(core).0[mode as usize].base();
        STEP_FLOW = None;
        HELPER_DONE = None;
    }
    let r = rt();
    r.stats[ACTIVATIONS] += 1;
    a32_trace(3, pc as u32, slot);
    let native = unsafe {
        call_indirect1_ret(
            (slot + crate::aarch64::root::WASM_TABLE_OFFSET) as i32,
            budget.min(MAX_BUDGET) as u16,
        )
    } as u32;
    let chained = unsafe { *a64_page_chain };
    let retired = native.wrapping_add(chained);
    let r = rt();
    r.stats[RETIRED] += retired as u64;
    if chained != 0 {
        r.stats[CHAINED] += 1;
    }
    crate::core_stats::add_pending(retired, 0);
    r.x.last_key = u32::MAX;
    let mut retired = retired;
    let mut flow = unsafe { (*(&raw mut STEP_FLOW)).take() }.unwrap_or(Flow::Next);
    match unsafe { *a64_page_exit } {
        EXIT_RETRY if unsafe { (*(&raw const HELPER_DONE)).is_some() } => {
            let (next, f) = unsafe { (*(&raw mut HELPER_DONE)).take() }.unwrap();
            cpu::set_pc(next);
            retired += 1;
            flow = f;
        },
        EXIT_RETRY => {
            // (the instruction at the PC: a template refused it before any of its effects)
            r.stats[RETRIES] += 1;
            let f = execute::interpret_one();
            if !matches!(f, Flow::Set | Flow::Retry) {
                retired += 1;
            }
            if matches!(f, Flow::Wait(_) | Flow::Off | Flow::Yield | Flow::Retry) {
                flow = f;
            }
        },
        EXIT_UNKNOWN => r.stats[UNKNOWN] += 1,
        _ => {},
    }
    release_dead(rt());
    a32_trace(
        4,
        cpu::get_pc() as u32,
        unsafe { *a64_page_exit } | retired << 8,
    );
    Ran::Native { retired, flow }
}

// ---- compiling

fn compile(key: u32, pc: u64) {
    let r = rt();
    let state = r.pages.entry(key).or_default();
    state.compiles += 1;
    let entries: Vec<u16> = (0..4096u16)
        .filter(|&o| state.entries[o as usize / 64] >> (o % 64) & 1 != 0)
        .collect();
    let code_key = key & ((1 << MODE_SHIFT) - 1);
    let mode = key >> MODE_SHIFT;
    let filter = unsafe { AARCH32_FILTER };
    if filter != 0 && aarch32_mode(mode) {
        let mask = (1u32 << (filter >> 16)) - 1;
        if code_key & mask != filter & 0xFFFF & mask {
            return;
        }
        console_log!(
            "a32 page {:x} key {:x} {}",
            pc & !0xFFF,
            code_key,
            if mode & !1 == MODE_T32 { "T32" } else { "A32" }
        );
    }
    let bytes = if code_key >= bus::EXTENDED_CODE_KEY {
        unsafe { crate::extended::copy_page(code_key - bus::EXTENDED_CODE_KEY) }
    }
    else {
        unsafe { std::slice::from_raw_parts(bus::MEM8.add((code_key << 12) as usize), 4096) }
            .to_vec()
    };
    let name = format!(
        "a64_page{}_{:x}",
        match mode {
            MODE_A32 => "_a32",
            MODE_T32 => "_t32",
            5 => "_a32_pl1",
            7 => "_t32_pl1",
            _ if mode & 1 != 0 => "_el1",
            _ => "_el0",
        },
        pc & !0xFFF
    );
    let started = unsafe { crate::isa::microtick() };
    let compiled = pagegen::compile(
        &bytes,
        &entries,
        pagegen::CompileEnv {
            el1: mode & 1 != 0,
            sp_checked: mode & 2 != 0,
            // (a64_page_aarch32_filter's bit 15: AArch32's functions do not chain)
            chaining: unsafe { CHAINING } && !(aarch32_mode(mode) && filter & 0x8000 != 0),
            neon: unsafe { super::NEON },
            helpers: unsafe { super::HELPERS },
            system: unsafe { super::SYSTEM },
            relaxed_fma: unsafe { super::RELAXED_FMA },
            isa: match mode & !1 {
                MODE_A32 => pagegen::Isa::A32,
                MODE_T32 => pagegen::Isa::T32,
                _ => pagegen::Isa::A64,
            },
        },
        name,
    );
    unsafe { COMPILE_MS += crate::isa::microtick() - started };
    let Some(code) = compiled
    else {
        rt().stats[FAILED] += 1;
        return;
    };
    let r = rt();
    // room in the table: the least recently used function goes
    let live = r.live();
    let must_evict = {
        let rt = jitrt::state();
        let free = rt.table.free_count();
        crate::jitrt::capacity::must_evict(ClientId::A64Page, live, free, |c| {
            rt.table.owned_by(c) as u32
        })
    };
    if crate::jitrt::capacity::take_request(ClientId::A64Page) || must_evict {
        if let Some(i) = r.victim(|_| true, usize::MAX) {
            retire(r, i);
            unsafe { EVICTIONS += 1 };
        }
    }
    // room in the code budget: the least recently used go until it fits
    let budget = unsafe { CODE_BUDGET_MB } as u64 * 1048576;
    while unsafe { LIVE_BYTES } + code.bytes.len() as u64 > budget {
        let Some(i) = r.victim(|_| true, usize::MAX)
        else {
            break;
        };
        retire(r, i);
        unsafe { EVICTIONS += 1 };
    }
    release_dead(r);
    let id = r.next_id;
    r.next_id += 1;
    let slot = {
        let mut rt = jitrt::state();
        let Some(slot) = rt.table.reserve(Owner {
            client: ClientId::A64Page,
            signature: Signature::Fn1Ret,
            id,
        })
        else {
            drop(rt);
            self::rt().stats[FAILED] += 1;
            return;
        };
        rt.watch
            .attach(slot, HashSet::from([Page::of_u32(code_key)]));
        slot
    };
    // (its next write retires it: crate::aarch64::isa_hooks::extended_code_written)
    if code_key >= bus::EXTENDED_CODE_KEY {
        unsafe { crate::extended::watch_code(code_key - bus::EXTENDED_CODE_KEY) };
    }
    let r = rt();
    if let Some(&old) = r.by_page.get(&key) {
        retire(r, old);
    }
    let index = match r.functions.iter().position(|f| {
        f.phase == Phase::Dead && !r.releases.iter().any(|&(s, i)| s == f.slot && i == f.id)
    }) {
        Some(i) => i,
        None => {
            r.functions.push(Function {
                page: key,
                id: 0,
                slot: 0,
                phase: Phase::Dead,
                served: Vec::new(),
                members: Vec::new(),
                last_used: 0,
                x: A64Code::default(),
            });
            r.functions.len() - 1
        },
    };
    r.clock += 1;
    r.functions[index] = Function {
        page: key,
        id,
        slot,
        phase: Phase::Pending,
        served: code.served,
        members: vec![key],
        last_used: r.clock,
        x: A64Code {
            source: source_hash(&bytes),
            bytes: code.bytes.len() as u32,
        },
    };
    unsafe { LIVE_BYTES += code.bytes.len() as u64 };
    r.by_page.insert(key, index);
    r.generation = r.generation.wrapping_add(1);
    r.stats[COMPILED] += 1;
    r.stats[INSTRUCTIONS] += code.instructions as u64;
    r.stats[TEMPLATED] += code.templated as u64;
    publish::publish(ClientId::A64Page, id, slot, &code.bytes);
}

/// FNV-1a over a code page
fn source_hash(bytes: &[u8]) -> u64 {
    let mut hash = 0xCBF29CE484222325u64;
    for &byte in bytes {
        hash = (hash ^ byte as u64).wrapping_mul(0x100000001B3);
    }
    hash
}

// publication's answers (jitrt::publish)
fn install(id: u64, slot: u32) -> bool {
    let r = rt();
    let Some(f) = r.pending(id, slot).map(|i| &r.functions[i])
    else {
        return false;
    };
    if !crate::parallel::active() {
        return true;
    }
    // (cores in workers, P8.2: the other cores mark the page first, so that
    // their stores to it retire this code; then its bytes are checked once
    // more, which sees any store before the marks)
    let (key, source) = (f.page & ((1 << MODE_SHIFT) - 1), f.x.source);
    if key >= bus::EXTENDED_CODE_KEY
        || !unsafe { crate::parallel::code::wait_published(std::iter::once(key), 0.5) }
    {
        return false;
    }
    let bytes = unsafe { std::slice::from_raw_parts(bus::MEM8.add((key << 12) as usize), 4096) };
    source_hash(bytes) == source
}
fn ready(id: u64, slot: u32) -> bool { rt().ready(id, slot).is_some() }
fn cancel(id: u64, slot: u32) {
    let r = rt();
    if let Some(index) = r.pending(id, slot) {
        retire(r, index);
    }
}
pub fn register() {
    publish::register(
        ClientId::A64Page,
        publish::Client {
            install,
            ready,
            cancel,
        },
    );
}

// ---- what generated code calls

/// The access cache's miss (pagegen::frame::AccessAbi::slow): the host
/// address of a `kind & 255`-byte access (bit 8: write) at virtual address
/// `address` by the running core at its EL, filling the cache; 0 when
/// refused (a fault, a device, a page with code for a write, a page
/// crossing): the function leaves for the interpreter to do it
#[no_mangle]
pub fn a64_page_access(address: u64, kind: u32) -> u32 {
    let size = kind & 255;
    let write = kind & 0x100 != 0;
    let r = rt();
    // (an access across pages, and with SCTLR_EL1.A every access: the
    // interpreter, which splits it or raises the alignment fault)
    if (address & 0xFFF) + size as u64 > 0x1000 || cpu::sctlr() & cpu::SCTLR_A != 0 {
        r.stats[ACCESS_REFUSED] += 1;
        refused(REFUSED_CROSSING);
        return 0;
    }
    // (the parallel build's atomics need natural alignment: an unaligned
    // access whose code cannot take an unaligned host (kind bit 9: a plain
    // store's; reads copy through the bounce slot on a hit) retries in the
    // interpreter, but the entry is filled, so the next access hits:
    // pagegen::frame)
    let unaligned = WasmBuilder::ATOMIC_GUEST_MEMORY
        && size > 1
        && address & (size.min(8) as u64 - 1) != 0
        && kind & 0x200 == 0;
    // (kind bit 11: an unprivileged access at EL1, LDTR/STTR: EL0's permissions and table)
    let el0 = cpu::el() == 0 || kind & 0x800 != 0;
    let Some((pa, _large, global)) = crate::aarch64::mmu::translate_for_cache(address, write, el0)
    else {
        r.stats[ACCESS_REFUSED] += 1;
        refused(REFUSED_TRANSLATION);
        return 0;
    };
    let host = match bus::bus().lookup(pa) {
        Lookup::Ram {
            backing, writable, ..
        } => {
            let page = backing & !0xFFF;
            // (device memory: its writes go the interpreter's way, which marks them)
            if write
                && (!writable
                    || page >= unsafe { bus::DEVICE_START }
                    || crate::aarch64::root::page_watched(page >> 12)
                    || (unsafe { RESERVED_FILL_REFUSED } || !crate::parallel::active())
                        && crate::aarch64::smp::reserved_page(page))
            {
                r.stats[ACCESS_REFUSED] += 1;
                refused(if !writable || page >= unsafe { bus::DEVICE_START } {
                    REFUSED_NOT_WRITABLE
                }
                else if crate::aarch64::root::page_watched(page >> 12) {
                    REFUSED_WATCHED
                }
                else {
                    REFUSED_RESERVED
                });
                return 0;
            }
            (unsafe { bus::MEM8 } as u32).wrapping_add(page)
        },
        // (extended RAM: its frame, held until the run loop's next safe
        // point; no write entry while a core holds a reservation in the page)
        Lookup::Extended { .. } => {
            let frame = if write
                && crate::aarch64::smp::reserved_page(crate::aarch64::extended::monitor_key(
                    pa & !0xFFF,
                )) {
                None
            }
            else {
                unsafe { crate::aarch64::extended::cache_frame(pa & !0xFFF, write) }
            };
            match frame {
                Some(frame) => frame,
                None => {
                    r.stats[ACCESS_REFUSED] += 1;
                    refused(REFUSED_EXTENDED);
                    return 0;
                },
            }
        },
        _ => {
            r.stats[ACCESS_REFUSED] += 1;
            refused(REFUSED_NOT_RAM);
            return 0;
        },
    };
    // (a tagged pointer, TBI, gets an entry too: forget_tagged)
    let core = current_core();
    access(core).fill(LAYOUT, ENTRIES, el0, write, address, host, false, global);
    if global && address >> 55 == 0 && unsafe { super::ASID_TAG } {
        let a = asids(core);
        if let Some(i) = a.current {
            a.slots[i].low_global = true;
        }
    }
    r.stats[ACCESS_FILLS] += 1;
    if unaligned {
        r.stats[ACCESS_REFUSED] += 1;
        refused(REFUSED_UNALIGNED);
        return 0;
    }
    host + (address & 0xFFF) as u32
}

/// The PC (an offset in the page) is no block start of the function: note
/// it; whether the page is due for a recompile (the function then leaves)
#[no_mangle]
pub fn a64_page_unserved(pc: u64) -> u32 {
    // (inside an IT block, a step's PC: no entry, compiled code never starts there)
    if cpu::aarch32() && crate::aarch64::t32::itstate() != 0 {
        return 0;
    }
    let mode = mode();
    let Some(key) = code_page(pc, mode)
    else {
        return 1;
    };
    let state = rt().pages.entry(key).or_default();
    let offset = (pc & 0xFFF) as u16;
    note_entry_bits(&mut state.entries, offset);
    state.misses += 1;
    (state.misses >= RECOMPILE_MISSES) as u32
}

/// What a step may change that compiled code depends on
#[derive(Clone, Copy, PartialEq, Eq)]
struct Context {
    el: u32,
    /// DAIF, SS, IL, SPSel, PAN; AArch32's state and instruction set
    /// (a step's BX or BLX: a function is one set's, Q6)
    pstate: u32,
    sctlr: u64,
    tcr: u64,
    ttbr0: u64,
    ttbr1: u64,
    mdscr: u64,
    debug: (bool, bool),
    code_writes: u64,
    epoch: u64,
}
fn context() -> Context {
    unsafe {
        Context {
            el: cpu::el(),
            pstate: cpu::get_pstate()
                & (cpu::PSTATE_DAIF
                    | cpu::PSTATE_SS
                    | PSTATE_IL
                    | cpu::PSTATE_SP
                    | cpu::PSTATE_PAN
                    | cpu::PSTATE_NRW
                    | cpu::PSTATE_T
                    | cpu::PSTATE_E),
            sctlr: *sctlr_el1,
            tcr: *tcr_el1,
            ttbr0: *ttbr0_el1,
            ttbr1: *ttbr1_el1,
            mdscr: *mdscr_el1,
            debug: (
                crate::aarch64::debug::ANY_BREAKPOINT,
                crate::aarch64::debug::ANY_WATCHPOINT,
            ),
            code_writes: CODE_WRITES,
            epoch: access(current_core()).epoch(),
        }
    }
}

/// The A64 page tier's step frontend (jitrt::step, P6.2): the interpreter's
/// `interpret_one` (P2.9); the activation ends when the step changed the
/// context, asked the run loop for something (a wait, a stop, a yield), or
/// left an interrupt the core takes pending
struct A64Step;
impl StepFrontend for A64Step {
    type Context = Context;
    fn context() -> Context { context() }
    fn interpret_one() {
        let flow = execute::interpret_one();
        let (key, word) = unsafe { execute::LAST_STEPPED };
        note_step(STEPPED, key, word);
        if matches!(flow, Flow::Wait(_) | Flow::Off | Flow::Yield | Flow::Retry) {
            unsafe { STEP_FLOW = Some(flow) };
        }
    }
    fn outcome(before: &Context) -> StepOutcome {
        // (a busy loop around a stepped counter read sees its timer's
        // interrupt: after the system register accesses and the hints, WFE
        // and WFI among them; not after SYS, TLBI and its kind, nor other
        // steps: the run loop ticks every 1024 instructions)
        let (key, word) = unsafe { execute::LAST_STEPPED };
        if word & 0xFFC0_0000 == 0xD500_0000 && word >> 19 & 3 != 1 {
            crate::aarch64::timer::tick();
        }
        let changed = context() != *before;
        if changed {
            note_step(CHANGED_CONTEXT, key, word);
        }
        // (T32: inside an IT block, which the interpreter finishes: the
        // function's next instruction may be a native IT block's, compiled
        // for ITSTATE 0)
        let it = cpu::aarch32() && crate::aarch64::t32::itstate() != 0;
        if unsafe { (*(&raw const STEP_FLOW)).is_some() } || changed || it || interrupt_pending() {
            return StepOutcome::Exit;
        }
        StepOutcome::Continue
    }
}

// Diagnostics (a64_step_stat): how often each instruction class
// (execute::step_key) was stepped, ended an activation by changing the
// context, or ran as a helper; machine-wide (every core adds), approximate
const STEPPED: usize = 0;
const CHANGED_CONTEXT: usize = 1;
const HELPED: usize = 2;
const STEP_KEYS: usize = 1024;
static mut STEP_COUNTS: [[u32; STEP_KEYS]; 3] = [[0; STEP_KEYS]; 3];
/// the last word of each class
static mut STEP_WORDS: [u32; STEP_KEYS] = [0; STEP_KEYS];
/// MRS and MSR (register) by their register (the word's bits 19:5, op0's low bit and op1:CRn:CRm:op2), MSR from 1 << 15
static mut SYSREG_COUNTS: [[u32; 1 << 16]; 3] = [[0; 1 << 16]; 3];
/// SYS (TLBI, DC, IC, AT) by op1:CRn:CRm:op2
static mut SYS_COUNTS: [[u32; 1 << 14]; 3] = [[0; 1 << 14]; 3];
#[inline(always)]
fn note_step(kind: usize, key: u32, word: u32) {
    unsafe {
        if !STEP_STATS {
            return;
        }
        STEP_SAMPLED = STEP_SAMPLED.wrapping_add(1);
        if STEP_SAMPLED % STEP_SAMPLE != 0 {
            return;
        }
    }
    let index = key as usize & (STEP_KEYS - 1);
    unsafe {
        let counts = &mut *crate::parallel::machine(&raw mut STEP_COUNTS);
        counts[kind][index] = counts[kind][index].wrapping_add(STEP_SAMPLE);
        (*crate::parallel::machine(&raw mut STEP_WORDS))[index] = word;
        // (MRS and MSR (register): which register)
        if word & 0xFFD0_0000 == 0xD510_0000 {
            let reg = (word >> 5 & 0x7FFF | (!word >> 21 & 1) << 15) as usize;
            let counts = &mut *crate::parallel::machine(&raw mut SYSREG_COUNTS);
            counts[kind][reg] = counts[kind][reg].wrapping_add(STEP_SAMPLE);
        }
        // (SYS: which operation)
        else if word & 0xFFF8_0000 == 0xD508_0000 {
            let op = (word >> 5 & 0x3FFF) as usize;
            let counts = &mut *crate::parallel::machine(&raw mut SYS_COUNTS);
            counts[kind][op] = counts[kind][op].wrapping_add(STEP_SAMPLE);
        }
    }
}
/// (diagnostics) The count of MRS (`reg` < 1 << 15) or MSR (register) of
/// the register `reg` & 0x7FFF (the word's bits 19:5), by kind as a64_step_stat
#[no_mangle]
pub fn a64_sysreg_stat(kind: u32, reg: u32) -> f64 {
    // (kinds 4-6: SYS by op1:CRn:CRm:op2, as kinds 0-2)
    if (4..=6).contains(&kind) {
        return unsafe {
            (*crate::parallel::machine(&raw mut SYS_COUNTS))[kind as usize - 4]
                [reg as usize & 0x3FFF] as f64
        };
    }
    if kind > 2 {
        return 0.0;
    }
    unsafe {
        (*crate::parallel::machine(&raw mut SYSREG_COUNTS))[kind as usize][reg as usize & 0xFFFF]
            as f64
    }
}
/// The count of class `key` (kind 0 stepped, 1 changed the context, 2 a
/// helper), or with kind 3 the class's last word
#[no_mangle]
pub fn a64_step_stat(kind: u32, key: u32) -> f64 {
    let key = key as usize & (STEP_KEYS - 1);
    unsafe {
        match kind {
            0..=2 => (*crate::parallel::machine(&raw mut STEP_COUNTS))[kind as usize][key] as f64,
            3 => (*crate::parallel::machine(&raw mut STEP_WORDS))[key] as f64,
            _ => 0.0,
        }
    }
}
/// An interrupt the PE would take now
fn interrupt_pending() -> bool {
    let signal = crate::aarch64::gic::signal(current_core());
    let state = cpu::get_pstate();
    signal & crate::aarch64::gic::SIGNAL_IRQ != 0 && state & cpu::PSTATE_I == 0
        || signal & crate::aarch64::gic::SIGNAL_FIQ != 0 && state & cpu::PSTATE_F == 0
}

/// (pagegen's TLBI template, a64_system) the TLBI `word` of Xt `value` at
/// EL1, as the interpreter does it: 1 when it changed what compiled code
/// depends on (the access cache's epoch): the function then leaves
#[no_mangle]
pub fn a64_page_tlbi(word: u32, value: u64) -> u32 {
    let core = current_core();
    let epoch = access(core).epoch();
    let crm = word >> 8 & 15;
    crate::aarch64::mmu::tlbi(crm == 3, word >> 5 & 7, value);
    note_step(
        HELPED,
        execute::step_key(&execute::decode_cached(word)),
        word,
    );
    (access(core).epoch() != epoch) as u32
}

/// (pagegen's MSR DAIF and DAIFClr templates) 1 when an interrupt is now
/// deliverable, or a debug exception may be: the function leaves for the
/// run loop to take it
#[no_mangle]
pub fn a64_page_unmasked() -> u32 {
    // (and when clearing PSTATE.D made a debug exception due: a software
    // step, a breakpoint or a watchpoint, which allowed() keeps compiled
    // code from)
    (interrupt_pending()
        || unsafe {
            crate::aarch64::debug::ANY_BREAKPOINT || crate::aarch64::debug::ANY_WATCHPOINT
        }
        || crate::aarch64::debug::stepping()) as u32
}

/// The system counter, CNTVCT_EL0 and CNTPCT_EL0 (pagegen's template: the
/// EL0 checks made)
#[no_mangle]
pub fn a64_page_counter() -> u64 { crate::aarch64::timer::counter() }

/// A helper for a page function (pagegen's helper template): the instruction
/// `word` at `pc` on the state in memory (the registers it names and NZCV
/// were written back), by the interpreter's own execute. Only forms that
/// never transfer control nor change what compiled code depends on come
/// here (pagegen::helper_kind); 0 when done, 1 when it refused before any
/// effect (an exception: the function retries it in the interpreter) or
/// was done but asks the run loop for something (HELPER_DONE)
#[no_mangle]
pub fn a64_page_helper(word: u32, pc: u64) -> u32 {
    unsafe { HELPERS += 1 };
    let inst = execute::decode_cached(word);
    note_step(HELPED, execute::step_key(&inst), word);
    match execute::execute(&inst, pc) {
        Ok(Flow::Next) => {
            crate::core_stats::add_pending(1, 0);
            0
        },
        Ok(flow @ (Flow::Yield | Flow::Wait(_) | Flow::Off)) => {
            crate::core_stats::add_pending(1, 0);
            unsafe { HELPER_DONE = Some((pc.wrapping_add(4), flow)) };
            1
        },
        _ => 1,
    }
}

/// A helper call of an AArch32 page function (pagegen::a32): the A32 or
/// T32 instruction (`length` 4, or T32's 2 or 4) executed on the state in
/// memory, as the interpreter does it without the fetch (the IT block a step
/// on); 1 when it did not simply go on to the next instruction, which the
/// compiler rules out but for its exceptions (raised before any of its
/// effects: the interpreter runs it again) and a load-exclusive's spin
/// yield (done: HELPER_DONE)
/// (diagnostics) AArch32's helper calls by instruction word: an open
/// addressed table of (word, count), new words dropped when it is full
const HELPER_WORDS_SIZE: usize = 4096;
static mut HELPER_WORDS: [(u32, u32); HELPER_WORDS_SIZE] = [(0, 0); HELPER_WORDS_SIZE];
#[inline(always)]
fn note_helper_word(word: u32) {
    let table = unsafe { &mut *crate::parallel::machine(&raw mut HELPER_WORDS) };
    let mut i = (word.wrapping_mul(0x9E37_79B1) >> 20) as usize;
    for _ in 0..8 {
        let e = &mut table[i];
        if e.1 == 0 || e.0 == word {
            *e = (word, e.1.wrapping_add(1));
            return;
        }
        i = (i + 1) % HELPER_WORDS_SIZE;
    }
}
/// (diagnostics) entry `i` of the helper words' table: `count` false the
/// word, true its count (0: empty)
#[no_mangle]
pub fn a32_helper_word(i: u32, count: bool) -> f64 {
    let e = unsafe {
        (*crate::parallel::machine(&raw mut HELPER_WORDS))[i as usize % HELPER_WORDS_SIZE]
    };
    if count {
        e.1 as f64
    }
    else {
        e.0 as f64
    }
}

#[no_mangle]
pub fn a32_page_helper(word: u32, pc: u64, length: u32) -> u32 {
    unsafe { HELPERS += 1 };
    note_helper_word(word);
    a32_trace(2, pc as u32, word);
    let thumb = cpu::get_pstate() & cpu::PSTATE_T != 0;
    note_step(
        HELPED,
        crate::aarch64::a32::step_key(word, length, thumb),
        word,
    );
    match crate::aarch64::a32::execute_fetched(word, length, pc as u32, thumb) {
        Ok(flow @ (Flow::Next | Flow::Yield | Flow::Wait(_) | Flow::Off)) => {
            crate::core_stats::add_pending(1, 0);
            if thumb {
                crate::aarch64::t32::it_advance();
            }
            if matches!(flow, Flow::Next) {
                return 0;
            }
            let next = (pc as u32).wrapping_add(length) as u64;
            unsafe { HELPER_DONE = Some((next, flow)) };
            1
        },
        _ => 1,
    }
}

/// A single step for a page function (the state is in memory)
#[no_mangle]
pub fn a64_page_step() -> i32 {
    rt().stats[STEPS] += 1;
    if cpu::aarch32() {
        a32_trace(5, cpu::get_pc() as u32, 0);
        let result = step::step::<A64Step>() as i32;
        a32_trace(8, cpu::get_pc() as u32, result as u32);
        return result;
    }
    step::step::<A64Step>() as i32
}

/// The page tier's counters (tests, diagnostics)
#[no_mangle]
pub fn a64_page_stat(n: u32) -> f64 {
    let r = rt();
    match n {
        100 => r.live() as f64,
        101 => (unsafe { WRITES }) as f64,
        102 => (unsafe { RESETS }) as f64,
        103 => r.pages.values().filter(|p| p.compiles != 0).count() as f64,
        104 => r.pages.values().map(|p| p.compiles).max().unwrap_or(0) as f64,
        105 => r.pages.values().map(|p| p.misses).sum::<u32>() as f64,
        106 => (unsafe { HELPERS }) as f64,
        107 => (unsafe { EVICTIONS }) as f64,
        108 => unsafe { COMPILE_MS },
        109 => (unsafe { AUTO_SWITCHES }) as f64,
        110 => (unsafe { super::ASID_TAG }) as u32 as f64,
        111 => (unsafe { LIVE_BYTES }) as f64,
        120..=127 => (unsafe { REFUSED[n as usize - 120] }) as f64,
        _ => r.stats.get(n as usize).copied().unwrap_or(0) as f64,
    }
}
                                                                                                                                                                                                                                 source/v64/src/rust/aarch64/memory.rs                                                               0000644 0000000 0000000 00000021456 00000000000 014566  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Virtual memory accesses of the AArch64 core: translation (the stage 1 MMU,
//! mmu.rs; with SCTLR_EL1.M clear an address is its physical address, data
//! accesses are to Device memory and must be aligned) and the accesses
//! themselves through the address space (crate::aarch64::bus). A
//! multi-byte access that faults anywhere writes nothing.

use crate::aarch64::bus::{self, Fault, Lookup};
use crate::aarch64::cpu::{
    self, Exception, FSC_ADDRESS_SIZE_L0, FSC_ALIGNMENT, FSC_EXTERNAL, SCTLR_A, SCTLR_M,
};
use crate::aarch64::mmu;

/// What an access does
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Access {
    Read,
    Write,
    Fetch,
}

/// The data abort syndrome's ISS for an access: whether its ISS is valid
/// (ISV, a single general-purpose register without write-back, as QEMU
/// reports), the access size, sign extension, register, 64-bit register,
/// acquire/release (AR), write
#[derive(Clone, Copy, Default)]
pub struct Syndrome {
    pub valid: bool,
    pub size_log: u32,
    pub signed: bool,
    pub register: u32,
    pub sixty_four: bool,
    pub acquire_release: bool,
    /// a cache maintenance or DC ZVA (CM, reported as a write)
    pub cache: bool,
}

impl Syndrome {
    pub const NONE: Syndrome = Syndrome {
        valid: false,
        size_log: 0,
        signed: false,
        register: 0,
        sixty_four: false,
        acquire_release: false,
        cache: false,
    };
    /// The ISS of a data abort taken to EL1: ISV is 0 for every fault
    /// reported in ESR_EL1 without FEAT_LS64 (DDI 0487 L.b; QEMU likewise),
    /// so only WnR and CM are kept (the rest of the syndrome is for an EL2)
    fn iss(self, write: bool, fsc: u32) -> u32 {
        fsc | (write as u32) << 6 | (self.cache as u32) << 8
    }
}

fn abort(access: Access, va: u64, fsc: u32, syndrome: Syndrome) -> Exception {
    match access {
        Access::Fetch => Exception::InstructionAbort { fsc, far: va },
        _ => Exception::DataAbort {
            iss: syndrome.iss(access == Access::Write, fsc),
            far: va,
        },
    }
}

fn bus_fault(fault: Fault) -> u32 {
    match fault {
        Fault::External => FSC_EXTERNAL,
        Fault::AddressSize => FSC_ADDRESS_SIZE_L0,
    }
}

/// Translate `va` for an access of `size` bytes at the current EL (or EL0
/// for an unprivileged one): the physical address, or the fault. The access
/// must not cross a page (callers split them).
#[inline]
pub fn translate(
    va: u64,
    size: u32,
    access: Access,
    unprivileged: bool,
    syndrome: Syndrome,
) -> Result<u64, Exception> {
    let sctlr = cpu::sctlr();
    let aligned = va & (size as u64 - 1) == 0;
    let el0 = unprivileged || cpu::el() == 0;
    // (a watchpoint fires after translation, before the access; the MMU on or off)
    let watch = |pa: u64| {
        if access != Access::Fetch && unsafe { crate::aarch64::debug::ANY_WATCHPOINT } {
            if let Some(exception) =
                crate::aarch64::debug::check_watchpoint(va, size, access == Access::Write, el0)
            {
                return Err(exception);
            }
        }
        Ok(pa)
    };
    if sctlr & SCTLR_M == 0 {
        // the MMU off: data accesses are to Device memory (always aligned)
        if access != Access::Fetch && !aligned {
            return Err(abort(access, va, FSC_ALIGNMENT, syndrome));
        }
        let pa =
            mmu::mmu_off(va).ok_or_else(|| abort(access, va, FSC_ADDRESS_SIZE_L0, syndrome))?;
        return watch(pa);
    }
    if access != Access::Fetch && sctlr & SCTLR_A != 0 && !aligned {
        return Err(abort(access, va, FSC_ALIGNMENT, syndrome));
    }
    match mmu::translate(va, access, el0, size) {
        Ok(translation) => watch(translation.pa),
        Err(fsc) => Err(abort(access, va, fsc, syndrome)),
    }
}

/// Whether [va, va + size) crosses into the next page
#[inline(always)]
fn crosses_page(va: u64, size: u32) -> bool { (va & 0xFFF) + size as u64 > 0x1000 }

/// An access across a page is unaligned: with the MMU off (Device memory)
/// or SCTLR_EL1.A it is an alignment fault, before either page translates
#[inline]
fn check_split(va: u64, access: Access, syndrome: Syndrome) -> Result<(), Exception> {
    let sctlr = cpu::sctlr();
    if sctlr & SCTLR_M == 0 || sctlr & SCTLR_A != 0 {
        return Err(abort(access, va, FSC_ALIGNMENT, syndrome));
    }
    Ok(())
}

/// Fetch the instruction at `va`: guest memory only (a fetch from a device
/// is an external abort, without reading it)
pub fn fetch(va: u64) -> Result<u32, Exception> {
    let pa = translate(va, 4, Access::Fetch, false, Syndrome::NONE)?;
    match bus::bus().lookup(pa) {
        Lookup::Ram { backing, .. } => {
            Ok(unsafe { crate::parallel::load32(bus::MEM8.add(backing as usize)) })
        },
        Lookup::Extended { .. } => Ok(unsafe { crate::aarch64::extended::fetch(pa) }),
        _ => Err(Exception::InstructionAbort {
            fsc: FSC_EXTERNAL,
            far: va,
        }),
    }
}

/// Read `size` bytes (1, 2, 4, 8) at `va`, little-endian
pub fn read(va: u64, size: u32, unprivileged: bool, syndrome: Syndrome) -> Result<u64, Exception> {
    if crosses_page(va, size) {
        // (an unaligned access across a page: both pages translate first)
        check_split(va, Access::Read, syndrome)?;
        let first = 0x1000 - (va & 0xFFF) as u32;
        let pa_low = translate(va, first, Access::Read, unprivileged, syndrome)?;
        let pa_high = translate(
            va + first as u64,
            size - first,
            Access::Read,
            unprivileged,
            syndrome,
        )?;
        let mut value = 0u64;
        for i in 0..size {
            let pa = if i < first { pa_low + i as u64 } else { pa_high + (i - first) as u64 };
            let byte = unsafe { bus::read(pa, 1) }
                .map_err(|f| abort(Access::Read, va, bus_fault(f), syndrome))?;
            value |= byte << (8 * i);
        }
        return Ok(value);
    }
    let pa = translate(va, size, Access::Read, unprivileged, syndrome)?;
    unsafe { bus::read(pa, size) }.map_err(|f| abort(Access::Read, va, bus_fault(f), syndrome))
}

/// A write, translated (and checked) before anything is written
#[derive(Clone, Copy)]
pub struct Store {
    va: u64,
    size: u32,
    pa_low: u64,
    /// the second page's address when the store crosses a page
    pa_high: Option<u64>,
    syndrome: Syndrome,
}

/// Translate a write of `size` bytes at `va`: it may fault now, then
/// `commit` cannot fail on translation (an external abort from the bus
/// still can, before anything is written)
pub fn prepare_write(
    va: u64,
    size: u32,
    unprivileged: bool,
    syndrome: Syndrome,
) -> Result<Store, Exception> {
    if crosses_page(va, size) {
        check_split(va, Access::Write, syndrome)?;
        let first = 0x1000 - (va & 0xFFF) as u32;
        let pa_low = translate(va, first, Access::Write, unprivileged, syndrome)?;
        let pa_high = translate(
            va + first as u64,
            size - first,
            Access::Write,
            unprivileged,
            syndrome,
        )?;
        for (pa, len) in [(pa_low, first), (pa_high, size - first)] {
            if let Err(fault) = bus::bus().span(pa, len as u64) {
                return Err(abort(Access::Write, va, bus_fault(fault), syndrome));
            }
        }
        return Ok(Store {
            va,
            size,
            pa_low,
            pa_high: Some(pa_high),
            syndrome,
        });
    }
    let pa = translate(va, size, Access::Write, unprivileged, syndrome)?;
    if let Err(fault) = bus::bus().span(pa, size as u64) {
        return Err(abort(Access::Write, va, bus_fault(fault), syndrome));
    }
    Ok(Store {
        va,
        size,
        pa_low: pa,
        pa_high: None,
        syndrome,
    })
}

impl Store {
    /// Write `value` (little-endian)
    pub fn commit(self, value: u64) -> Result<(), Exception> {
        let fail = |f| abort(Access::Write, self.va, bus_fault(f), self.syndrome);
        match self.pa_high {
            None => unsafe { bus::write(self.pa_low, self.size, value) }.map_err(fail),
            Some(pa_high) => {
                let first = 0x1000 - (self.va & 0xFFF) as u32;
                for i in 0..self.size {
                    let pa = if i < first {
                        self.pa_low + i as u64
                    }
                    else {
                        pa_high + (i - first) as u64
                    };
                    unsafe { bus::write(pa, 1, value >> (8 * i) & 0xFF) }.map_err(fail)?;
                }
                Ok(())
            },
        }
    }
}

/// Write `size` bytes at `va` (a single access: nothing is written if it faults)
pub fn write(
    va: u64,
    size: u32,
    value: u64,
    unprivileged: bool,
    syndrome: Syndrome,
) -> Result<(), Exception> {
    prepare_write(va, size, unprivileged, syndrome)?.commit(value)
}
                                                                                                                                                                                                                  source/v64/src/rust/aarch64/mmu.rs                                                                  0000644 0000000 0000000 00000046072 00000000000 014055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The stage 1 MMU of the AArch64 core (docs/arm64-virt-android16-plan.md
//! P3.3-P3.5): VMSAv8-64 translation of the EL1&0 regime with the 4 KiB
//! granule (16 and 64 KiB too with profiles v1.1 and v2, the default), TBI, ASIDs, the TLB
//! (tlb.rs), AT and TLBI. Where the Arm ARM leaves a choice this follows
//! QEMU 9.2 (target/arm/ptw.c), the reference: a TnSZ out of range is a
//! level 0 translation fault; a granule the profile does not have is the
//! 4 KiB one; faults come in the order translation, address size, access
//! flag (the walk), then the alignment of Device memory, then permission.
//! Hardware access-flag and dirty-state updates are not in v1.

use crate::aarch64::cpu::{self, SCTLR_M};
use crate::aarch64::state::{mair_el1, par_el1, sctlr_el1, tcr_el1, ttbr0_el1, ttbr1_el1};
use crate::aarch64::tlb::{
    self, Entry, DEVICE, EL0_EXEC, EL0_READ, EL0_WRITE, EL1_EXEC, EL1_READ, EL1_WRITE, GLOBAL,
};

/// What an access does
pub use crate::aarch64::memory::Access;

// fault status codes (DFSC/IFSC), plus the level
pub(crate) const FSC_ADDRESS_SIZE: u32 = 0x00;
pub(crate) const FSC_TRANSLATION: u32 = 0x04;
pub(crate) const FSC_ACCESS_FLAG: u32 = 0x08;
pub(crate) const FSC_PERMISSION: u32 = 0x0C;
pub(crate) const FSC_EXTERNAL_WALK: u32 = 0x14;

/// The granules the profile has: bit 0 4 KiB, 1 16 KiB, 2 64 KiB (v1: 4 KiB only)
static mut GRANULES: u32 = 1;

/// (profiles v1.1 and v2, the default: 16 and 64 KiB granules too, P3.4)
#[no_mangle]
pub fn a64_set_granules(mask: u32) {
    unsafe { *crate::parallel::machine(&raw mut GRANULES) = mask & 7 | 1 };
    tlb::flush(true);
}

/// The profile's granules (a64_set_granules): bit 0 4 KiB, 1 16 KiB, 2 64 KiB
#[no_mangle]
pub fn a64_granules() -> u32 { unsafe { *crate::parallel::machine(&raw mut GRANULES) } }

/// ID_AA64MMFR0_EL1's TGran16 and TGran64 fields for the profile
pub fn mmfr0_granules() -> u64 {
    let g = unsafe { *crate::parallel::machine(&raw mut GRANULES) };
    let tgran16 = if g & 2 != 0 { 1 } else { 0 };
    let tgran64 = if g & 4 != 0 { 0 } else { 0xF };
    tgran16 << 20 | tgran64 << 24
}

/// log2 of the granule TCR_EL1 selects for the half of the VA space bit 55 picks
fn granule_of(select: u64) -> u32 {
    let tcr = unsafe { *tcr_el1 };
    // (TG0: 00 4K, 01 64K, 10 16K; TG1: 01 16K, 10 4K, 11 64K)
    let log = if select == 0 {
        match tcr >> 14 & 3 {
            1 => 16,
            2 => 14,
            _ => 12,
        }
    }
    else {
        match tcr >> 30 & 3 {
            1 => 14,
            3 => 16,
            _ => 12,
        }
    };
    let supported = unsafe { *crate::parallel::machine(&raw mut GRANULES) }
        & match log {
            12 => 1,
            14 => 2,
            _ => 4,
        }
        != 0;
    if supported {
        log
    }
    else {
        12
    }
}

/// The current ASID: TTBR1_EL1's if TCR_EL1.A1, else TTBR0_EL1's (8 bits
/// unless TCR_EL1.AS; AArch32's regime: crate::aarch64::mmu_a32::asid)
#[inline(always)]
pub fn current_asid() -> u16 {
    if cpu::a32_only() {
        return crate::aarch64::mmu_a32::asid();
    }
    unsafe {
        let tcr = *tcr_el1;
        let ttbr = if tcr >> 22 & 1 != 0 { *ttbr1_el1 } else { *ttbr0_el1 };
        let asid = (ttbr >> 48) as u16;
        if tcr >> 36 & 1 != 0 {
            asid
        }
        else {
            asid & 0xFF
        }
    }
}

/// The VA with TBI applied (bits 63:56 a copy of bit 55 when TBI is on for its half)
#[inline(always)]
fn untagged(va: u64) -> u64 {
    let tcr = unsafe { *tcr_el1 };
    let tbi = if va >> 55 & 1 == 0 { tcr >> 37 & 1 } else { tcr >> 38 & 1 };
    if tbi != 0 {
        ((va << 8) as i64 >> 8) as u64
    }
    else {
        va
    }
}

/// A successful walk: the leaf for one VA
pub(crate) struct Leaf {
    /// the physical address of the VA
    pub pa: u64,
    pub level: u32,
    pub size_log: u32,
    pub flags: u16,
    pub attr: u8,
    pub sh: u8,
}

/// Read a translation table descriptor (RAM only: anything else is an external abort on the walk)
pub(crate) fn descriptor(pa: u64) -> Option<u64> {
    match crate::aarch64::bus::bus().lookup(pa) {
        crate::aarch64::bus::Lookup::Ram { backing, .. } => Some(unsafe {
            crate::parallel::load64(crate::aarch64::bus::MEM8.add(backing as usize))
        }),
        crate::aarch64::bus::Lookup::Extended { .. } => {
            Some(unsafe { crate::aarch64::extended::read(pa, 8) })
        },
        _ => None,
    }
}

#[inline(always)]
fn mask(bits: u32) -> u64 {
    if bits >= 64 {
        u64::MAX
    }
    else {
        (1u64 << bits) - 1
    }
}

/// A 32-bit descriptor (AArch32's short descriptors)
pub(crate) fn descriptor32(pa: u64) -> Option<u32> {
    match crate::aarch64::bus::bus().lookup(pa) {
        crate::aarch64::bus::Lookup::Ram { backing, .. } => Some(unsafe {
            crate::parallel::load32(crate::aarch64::bus::MEM8.add(backing as usize))
        }),
        crate::aarch64::bus::Lookup::Extended { .. } => {
            Some(unsafe { crate::aarch64::extended::read(pa, 4) } as u32)
        },
        _ => None,
    }
}

/// The translation table walk of `va` (AArch64.TranslationTableWalk for the
/// EL1&0 regime; AArch32's with cpu::a32_only): the leaf, or the fault status code
fn walk(va: u64) -> Result<Leaf, u32> {
    if cpu::a32_only() {
        return crate::aarch64::mmu_a32::walk(va);
    }
    let tcr = unsafe { *tcr_el1 };
    let select = va >> 55 & 1;
    let (tsz, epd) =
        if select == 0 { (tcr & 63, tcr >> 7 & 1) } else { (tcr >> 16 & 63, tcr >> 23 & 1) };
    if !(16..=39).contains(&tsz) {
        return Err(FSC_TRANSLATION);
    }
    let tbi = tcr >> (37 + select) & 1;
    let addrsize = 64 - 8 * tbi as u32;
    let inputsize = 64 - tsz as u32;
    if inputsize < addrsize {
        // (the bits above the region must all be `select`: the gap faults)
        let top = ((va >> inputsize) << (64 - (addrsize - inputsize))) as i64
            >> (64 - (addrsize - inputsize));
        if top.wrapping_neg() as u64 != select {
            return Err(FSC_TRANSLATION);
        }
    }
    if epd != 0 {
        return Err(FSC_TRANSLATION);
    }
    let granule = granule_of(select);
    // (the output size: TCR_EL1.IPS bounded by PARange, 40 bits)
    let ps = (tcr >> 32 & 7).min(2);
    let outputsize = [32, 36, 40][ps as usize];
    let ttbr = unsafe {
        if select == 0 {
            *ttbr0_el1
        }
        else {
            *ttbr1_el1
        }
    };
    walk_tables(va, inputsize, granule, outputsize, ttbr, false)
}

/// The walk from the table `ttbr` of a VA of `inputsize` bits, its region
/// chosen (the long descriptors: AArch64's and, `aarch32`, LPAE's, whose
/// execution needs read permission at its level, and PL1's no permission
/// to write at PL0 unless SCTLR.UWXN)
pub(crate) fn walk_tables(
    va: u64,
    inputsize: u32,
    granule: u32,
    outputsize: u32,
    ttbr: u64,
    aarch32: bool,
) -> Result<Leaf, u32> {
    let stride = granule - 3;
    let mut level = 4 - (inputsize - 4) / stride;
    let mut descaddr = ttbr & mask(48);
    if descaddr >> outputsize != 0 {
        return Err(FSC_ADDRESS_SIZE);
    }
    let indexmask_grainsize = mask(stride + 3);
    let mut indexmask = mask(inputsize - stride * (4 - level));
    descaddr &= !indexmask;
    let descaddrmask = mask(48) & !indexmask_grainsize;
    let mut tableattrs = 0u64;
    loop {
        descaddr |= (va >> (stride * (4 - level))) & indexmask;
        descaddr &= !7;
        let d = match descriptor(descaddr) {
            Some(d) => d,
            None => return Err(FSC_EXTERNAL_WALK + level),
        };
        // (a block is valid at level 1 or 2 with 4 KiB, level 2 with 16 or 64 KiB)
        let block_valid = level == 2 || level == 1 && granule == 12;
        if d & 1 == 0 || d & 2 == 0 && !block_valid {
            return Err(FSC_TRANSLATION + level);
        }
        let next = d & descaddrmask;
        if next >> outputsize != 0 {
            return Err(FSC_ADDRESS_SIZE + level);
        }
        if d & 2 != 0 && level < 3 {
            tableattrs |= d >> 59 & 31;
            level += 1;
            indexmask = indexmask_grainsize;
            descaddr = next;
            continue;
        }
        let size_log = stride * (4 - level) + 3;
        let pa = next & !mask(size_log) | va & mask(size_log);
        if d >> 10 & 1 == 0 {
            return Err(FSC_ACCESS_FLAG + level);
        }
        // AP[2:1] with APTable (APTable[0]: no EL0 access, APTable[1]: read-only)
        let mut ap = d >> 6 & 3;
        if tableattrs >> 2 & 1 != 0 {
            ap &= !1;
        }
        if tableattrs >> 3 & 1 != 0 {
            ap |= 2;
        }
        let uxn = d >> 54 & 1 != 0 || tableattrs >> 1 & 1 != 0;
        let pxn = d >> 53 & 1 != 0 || tableattrs & 1 != 0;
        let el1_write = ap & 2 == 0;
        let el0_read = ap & 1 != 0;
        let el0_write = ap == 1;
        let wxn = unsafe { *sctlr_el1 } >> 19 & 1 != 0;
        let mut flags = EL1_READ;
        if el1_write {
            flags |= EL1_WRITE;
        }
        if el0_read {
            flags |= EL0_READ;
        }
        if el0_write {
            flags |= EL0_WRITE;
        }
        if aarch32 {
            // (VMSAv8-32: XN for both, PXN; WXN; UWXN, SCTLR bit 20)
            let uwxn = unsafe { *sctlr_el1 } >> 20 & 1 != 0;
            if el0_read && !uxn && !(wxn && el0_write) {
                flags |= EL0_EXEC;
            }
            if !uxn && !pxn && !(wxn && el1_write) && !(uwxn && el0_write) {
                flags |= EL1_EXEC;
            }
        }
        else {
            if !uxn && !(wxn && el0_write) {
                flags |= EL0_EXEC;
            }
            if !(pxn || el0_write) && !(wxn && el1_write) {
                flags |= EL1_EXEC;
            }
        }
        if d >> 11 & 1 == 0 {
            flags |= GLOBAL;
        }
        let attr = (unsafe { *mair_el1 } >> (8 * (d >> 2 & 7))) as u8;
        if attr & 0xF0 == 0 {
            flags |= DEVICE;
        }
        return Ok(Leaf {
            pa,
            level,
            size_log,
            flags,
            attr,
            sh: (d >> 8 & 3) as u8,
        });
    }
}

/// A translation: the physical address, and whether it is Device memory
pub struct Translation {
    pub pa: u64,
    pub device: bool,
}

/// The TLB entry of `va` (walked and cached on a miss), or the walk's fault status code
#[inline(always)]
fn entry_of(va: u64) -> Result<Entry, u32> {
    let page = untagged(va) >> 12;
    let asid = current_asid();
    if let Some(entry) = tlb::lookup(page, asid) {
        if cpu::a32_only() {
            return crate::aarch64::mmu_a32::with_domain(entry);
        }
        return Ok(entry);
    }
    let leaf = walk(va)?;
    let entry = Entry {
        tag: 0,
        pa: leaf.pa & !0xFFF,
        asid,
        flags: leaf.flags,
        level: leaf.level as u8,
        size_log: leaf.size_log as u8,
        attr: leaf.attr,
        sh: leaf.sh,
    };
    tlb::insert(page, entry);
    if cpu::a32_only() {
        return crate::aarch64::mmu_a32::with_domain(entry);
    }
    Ok(entry)
}

/// Translate `va` (the MMU is on) for an access at EL0 (`el0`: also an
/// unprivileged access at EL1) or EL1 needing `align` bytes of alignment on
/// Device memory: the physical address, or the fault status code
#[inline]
pub fn translate(va: u64, access: Access, el0: bool, align: u32) -> Result<Translation, u32> {
    let entry = entry_of(va)?;
    let device = entry.flags & DEVICE != 0;
    if device && access != Access::Fetch && va & (align as u64 - 1) != 0 {
        return Err(cpu::FSC_ALIGNMENT);
    }
    let needed = match (access, el0) {
        (Access::Read, false) => EL1_READ,
        (Access::Write, false) => EL1_WRITE,
        (Access::Fetch, false) => EL1_EXEC,
        (Access::Read, true) => EL0_READ,
        (Access::Write, true) => EL0_WRITE,
        (Access::Fetch, true) => EL0_EXEC,
    };
    if entry.flags & needed == 0 {
        if cpu::a32_only() {
            return Err(
                FSC_PERMISSION + entry.level as u32 | crate::aarch64::mmu_a32::fault_domain(&entry)
            );
        }
        return Err(FSC_PERMISSION + entry.level as u32);
    }
    // (PAN: an EL1 data access to memory EL0 may access, AP[1] set; not
    // the unprivileged ones, `el0`, nor instruction fetches)
    if !el0
        && access != Access::Fetch
        && entry.flags & EL0_READ != 0
        && cpu::get_pstate() & cpu::PSTATE_PAN != 0
    {
        return Err(FSC_PERMISSION + entry.level as u32);
    }
    Ok(Translation {
        pa: entry.pa | va & 0xFFF,
        device,
    })
}

/// (the page tier's access cache, crate::aarch64::jit::pages) The
/// translation of `va` for a data access at EL0 (`el0`) or EL1 with the MMU
/// on, if the access cache may keep it: Normal memory the access is allowed
/// to: the physical address, whether it came from a block (invalidating a
/// page of it must flush), whether it is global
pub fn translate_for_cache(va: u64, write: bool, el0: bool) -> Option<(u64, bool, bool)> {
    let entry = entry_of(va).ok()?;
    let needed = match (write, el0) {
        (false, false) => EL1_READ,
        (true, false) => EL1_WRITE,
        (false, true) => EL0_READ,
        (true, true) => EL0_WRITE,
    };
    if entry.flags & DEVICE != 0 || entry.flags & needed == 0 {
        return None;
    }
    // (with FEAT_PAN, EL1's entries are never of memory EL0 may access:
    // PSTATE.PAN changes without the cache knowing)
    if !el0 && entry.flags & EL0_READ != 0 && cpu::has_pan() {
        return None;
    }
    Some((
        entry.pa | va & 0xFFF,
        entry.size_log > 12,
        entry.flags & GLOBAL != 0,
    ))
}

/// SCTLR_EL1, TCR_EL1 or MAIR_EL1 changed: what the TLB derived from them is stale
pub fn regime_changed() { tlb::flush(false); }

/// TTBR0_EL1 and TTBR1_EL1 writes, and those that changed their core's
/// current ASID (P9.3: what SW_TTBR0_PAN costs, two of each per entry from
/// EL0 and per uaccess window); each core's last ASID
static mut TTBR_WRITES: u64 = 0;
static mut ASID_CHANGES: u64 = 0;
static mut LAST_ASID: [u16; crate::aarch64::isa_hooks::MAX_CORES] =
    [0; crate::aarch64::isa_hooks::MAX_CORES];

/// TTBR0_EL1 or TTBR1_EL1 changed: entries are tagged with their ASID, so
/// nothing is flushed (software changing a table under an ASID must TLBI)
pub fn ttbr_changed() {
    unsafe {
        tlb::GENERATION = tlb::GENERATION.wrapping_add(1).max(1);
        TTBR_WRITES += 1;
        let asid = current_asid();
        let core = crate::isa::current_core() as usize % crate::aarch64::isa_hooks::MAX_CORES;
        if LAST_ASID[core] != asid {
            LAST_ASID[core] = asid;
            ASID_CHANGES += 1;
        }
    }
    // (without a64_asid_tag, the page tier's access cache is not tagged with
    // the ASID: its non-global entries go; with it, the next activation
    // takes the running ASID's epoch, P6.4)
    if !unsafe { crate::aarch64::jit::ASID_TAG } {
        crate::aarch64::jit::pages::tlb_flushed_nonglobal(crate::isa::current_core());
    }
}

/// The ASID changes so far (crate::aarch64::jit::pages::asid_tag_tick)
pub fn asid_changes() -> u64 { unsafe { ASID_CHANGES } }

/// The TTBR writes (0) and ASID changes (1) since the module started (tests)
#[no_mangle]
pub fn a64_mmu_stat(n: u32) -> f64 {
    unsafe {
        match n {
            0 => TTBR_WRITES as f64,
            1 => ASID_CHANGES as f64,
            _ => 0.0,
        }
    }
}

/// A data or instruction cache maintenance by VA: no effect, and no fault
/// (as QEMU, which implements them as NOPs)
pub fn check_cache_maintenance(_va: u64) -> Result<(), crate::aarch64::cpu::Exception> { Ok(()) }

/// AT S1E1R (0), S1E1W (1), S1E0R (2), S1E0W (3): PAR_EL1. An external abort
/// on the walk is taken as a data abort (CM 1, WnR 1) instead.
pub fn address_translate(op2: u32, va: u64) -> Result<(), crate::aarch64::cpu::Exception> {
    let access = if op2 & 1 != 0 { Access::Write } else { Access::Read };
    let el0 = op2 & 2 != 0;
    let par = if cpu::sctlr() & SCTLR_M == 0 {
        // (the MMU off: the VA is the PA, Device-nGnRnE, outer shareable)
        match mmu_off(va) {
            None => 1 | (FSC_ADDRESS_SIZE as u64) << 1,
            Some(pa) => pa & !0xFFF | 1 << 9 | 2 << 7,
        }
    }
    else {
        match walk(va) {
            Ok(leaf) => {
                let needed = match (access, el0) {
                    (Access::Read, false) => EL1_READ,
                    (Access::Write, false) => EL1_WRITE,
                    (Access::Read, true) => EL0_READ,
                    _ => EL0_WRITE,
                };
                if leaf.flags & needed == 0 {
                    1 | ((FSC_PERMISSION + leaf.level) as u64) << 1
                }
                else {
                    let sh = if leaf.attr & 0xF0 == 0 || leaf.attr == 0x44 || leaf.attr == 0x40 {
                        2
                    }
                    else {
                        leaf.sh as u64
                    };
                    leaf.pa & mask(48) & !0xFFF | (leaf.attr as u64) << 56 | 1 << 9 | sh << 7
                }
            },
            Err(fsc) if fsc & 0x3C == FSC_EXTERNAL_WALK => {
                return Err(crate::aarch64::cpu::Exception::DataAbort {
                    iss: fsc | 1 << 6 | 1 << 8,
                    far: va,
                });
            },
            Err(fsc) => 1 | (fsc as u64) << 1,
        }
    };
    unsafe { *par_el1 = par | 1 << 11 };
    Ok(())
}

/// TLBI (op1 0, CRn 8): `shareable` the IS forms (CRm 3), op2 the operation, `value` Xt
pub fn tlbi(shareable: bool, op2: u32, value: u64) {
    let asid = (value >> 48) as u16;
    let asid = if unsafe { *tcr_el1 } >> 36 & 1 != 0 { asid } else { asid & 0xFF };
    // (VA[55:12] in Xt[43:0], the upper bits a copy of bit 55)
    let page = (((value << 20) as i64) >> 20) as u64 & mask(52);
    match op2 {
        0 => tlb::flush(shareable),
        2 => tlb::flush_asid(shareable, asid),
        1 | 5 => tlb::flush_page(shareable, page, Some(asid)),
        _ => tlb::flush_page(shareable, page, None),
    }
}

/// AArch64.BranchAddr: a branch target with TBI (TCR_EL1.TBI0/TBI1 for the
/// half bit 55 selects): bits 63:56 become copies of bit 55
#[inline(always)]
pub fn branch_address(target: u64) -> u64 {
    let tcr = unsafe { *tcr_el1 };
    let tbi = if target >> 55 & 1 == 0 { tcr >> 37 & 1 } else { tcr >> 38 & 1 };
    if tbi == 0 {
        target
    }
    else {
        ((target << 8) as i64 >> 8) as u64
    }
}

/// The physical address of `va` with the MMU off: the VA itself (TBI still
/// applies), or None for one beyond the 40-bit physical address space (a
/// level 0 address size fault)
#[inline(always)]
pub fn mmu_off(va: u64) -> Option<u64> {
    let tcr = unsafe { *tcr_el1 };
    let tbi = if va >> 55 & 1 == 0 { tcr >> 37 & 1 } else { tcr >> 38 & 1 };
    let pa = if tbi != 0 { va & mask(56) } else { va };
    if pa >> 40 != 0 {
        None
    }
    else {
        Some(pa)
    }
}

/// The physical address `va` translates to now for a read at the current
/// EL, if it does (the exclusive monitor's address)
pub fn physical_address_of(va: u64) -> Option<u64> {
    if cpu::sctlr() & SCTLR_M == 0 {
        mmu_off(va)
    }
    else {
        translate(va, Access::Read, cpu::el() == 0, 1)
            .ok()
            .map(|t| t.pa)
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/rust/aarch64/mmu_a32.rs                                                              0000644 0000000 0000000 00000023402 00000000000 014512  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The AArch32 translation regime of cpu_type "arm32" (docs/aarch32-plan.md
//! R3), as QEMU 9.2 (target/arm/ptw.c: get_phys_addr_v6, get_phys_addr_lpae)
//! has it. TTBCR.EAE 0: VMSAv7's short descriptors (sections, supersections,
//! large and small pages; AP[2:0], or SCTLR.AFE's simplified model with
//! AP[0] the access flag; XN and PXN; TEX remap by PRRR and NMRR with
//! SCTLR.TRE; the ASID CONTEXTIDR's); TTBCR.EAE 1: LPAE's long descriptors
//! (mmu.rs's walk of the 4 KiB granule, a 32-bit input, 40-bit output).
//!
//! A short descriptor's domain is checked by the walk and again on every
//! use of its TLB entry (`with_domain`): the entry keeps the client
//! permissions and the domain (in `sh`), so a write of DACR (Linux's
//! uaccess windows) needs no flush. A small page's entry is at level 3
//! (not a block for tlb.rs), its faults' level the page's.

use crate::aarch64::cpu;
use crate::aarch64::mmu::{
    descriptor32, walk_tables, Leaf, FSC_ACCESS_FLAG, FSC_EXTERNAL_WALK, FSC_TRANSLATION,
};
use crate::aarch64::state::{a32_dacr, a32_ttbcr, contextidr_el1, mair_el1, ttbr0_el1, ttbr1_el1};
use crate::aarch64::tlb::{
    Entry, DEVICE, EL0_EXEC, EL0_READ, EL0_WRITE, EL1_EXEC, EL1_READ, EL1_WRITE, GLOBAL,
};

const TTBCR_EAE: u32 = 1 << 31;
const TTBCR_PD0: u32 = 1 << 4;
const TTBCR_PD1: u32 = 1 << 5;
const SCTLR_TRE: u64 = 1 << 28;
const SCTLR_AFE: u64 = 1 << 29;

/// The domain faults (AArch64's DFSC encodings of them): section, page
pub const FSC_DOMAIN_SECTION: u32 = 0x3D;
pub const FSC_DOMAIN_PAGE: u32 = 0x3E;

/// An entry's `sh` with a domain: bit 3, the domain in bits 7:4
const SH_DOMAIN: u8 = 1 << 3;

/// A short-descriptor fault's domain (DFSR and IFSR bits 7:4, as QEMU reports
/// every fault's): bits 23:20 of its fault status code
pub const FSC_DOMAIN_SHIFT: u32 = 20;

const ALL: u16 = EL1_READ | EL1_WRITE | EL1_EXEC | EL0_READ | EL0_WRITE | EL0_EXEC;

/// Whether TTBCR selects the long descriptors (LPAE)
#[inline(always)]
pub fn long_descriptors() -> bool { (unsafe { *a32_ttbcr }) & TTBCR_EAE != 0 }

/// The current ASID: CONTEXTIDR's (short descriptors), or TTBR0's or
/// TTBR1's (TTBCR.A1) bits 55:48
#[inline(always)]
pub fn asid() -> u16 {
    unsafe {
        if *a32_ttbcr & TTBCR_EAE == 0 {
            *contextidr_el1 as u16 & 0xFF
        }
        else {
            let ttbr = if *a32_ttbcr >> 22 & 1 != 0 { *ttbr1_el1 } else { *ttbr0_el1 };
            (ttbr >> 48) as u16 & 0xFF
        }
    }
}

/// The walk of `va` (its 32 bits)
pub(crate) fn walk(va: u64) -> Result<Leaf, u32> {
    if long_descriptors() {
        walk_long(va as u32)
    }
    else {
        walk_short(va as u32)
    }
}

/// An entry as DACR has its domain now: a domain fault (no access), every
/// permission (manager), or the entry's (client)
#[inline(always)]
pub fn with_domain(entry: Entry) -> Result<Entry, u32> {
    if entry.sh & SH_DOMAIN == 0 {
        return Ok(entry);
    }
    let domain = entry.sh >> 4;
    match unsafe { *a32_dacr } >> (2 * domain as u32) & 3 {
        1 => Ok(entry),
        3 => Ok(Entry {
            flags: entry.flags | ALL,
            ..entry
        }),
        _ => Err(
            if entry.level == 1 { FSC_DOMAIN_SECTION } else { FSC_DOMAIN_PAGE }
                | (domain as u32) << FSC_DOMAIN_SHIFT,
        ),
    }
}

/// The domain bits of a permission fault on `entry` (none with the long descriptors)
#[inline(always)]
pub fn fault_domain(entry: &Entry) -> u32 {
    if entry.sh & SH_DOMAIN != 0 {
        ((entry.sh >> 4) as u32) << FSC_DOMAIN_SHIFT
    }
    else {
        0
    }
}

// ---- LPAE

fn walk_long(va: u32) -> Result<Leaf, u32> {
    let ttbcr = unsafe { *a32_ttbcr };
    let (t0sz, t1sz) = (ttbcr & 7, ttbcr >> 16 & 7);
    // (aa32_va_parameters: TTBR1 when T1SZ is 0 above TTBR0's region, else from its own)
    let select = if t1sz == 0 { va > u32::MAX >> t0sz } else { va >= !(u32::MAX >> t1sz) };
    let (tsz, epd, ttbr) = unsafe {
        if select {
            (t1sz, ttbcr >> 23 & 1, *ttbr1_el1)
        }
        else {
            (t0sz, ttbcr >> 7 & 1, *ttbr0_el1)
        }
    };
    let inputsize = 32 - tsz;
    if inputsize < 32 {
        // (the gap between the regions)
        let top = va >> inputsize;
        let all = u32::MAX >> inputsize;
        if top != if select { all } else { 0 } {
            return Err(FSC_TRANSLATION + 1);
        }
    }
    if epd != 0 {
        return Err(FSC_TRANSLATION + 1);
    }
    walk_tables(va as u64, inputsize, 12, 40, ttbr, true)
}

// ---- short descriptors

/// AP[2:0]'s read and write permissions (PL1, PL0) without the access flag model
fn full_permissions(ap: u32) -> (u16, u16) {
    const RW: u16 = 3;
    const R: u16 = 1;
    match ap {
        1 => (RW, 0),
        2 => (RW, R),
        3 => (RW, RW),
        5 => (R, 0),
        6 | 7 => (R, R),
        _ => (0, 0),
    }
}

/// AP[2:1]'s (SCTLR.AFE)
fn simple_permissions(ap: u32) -> (u16, u16) {
    match ap {
        0 => (3, 0),
        1 => (3, 3),
        2 => (1, 0),
        _ => (1, 1),
    }
}

/// A MAIR-like attribute byte of a cacheability (NMRR's encoding: 0 Non-cacheable,
/// 1 write-back write-allocate, 2 write-through, 3 write-back)
fn cacheability(c: u32) -> u8 { [0x4, 0xF, 0xA, 0xE][c as usize & 3] }

fn walk_short(va: u32) -> Result<Leaf, u32> {
    let ttbcr = unsafe { *a32_ttbcr };
    let n = ttbcr & 7;
    let table = unsafe {
        if n != 0 && va >> (32 - n) != 0 {
            if ttbcr & TTBCR_PD1 != 0 {
                return Err(FSC_TRANSLATION + 1);
            }
            *ttbr1_el1 as u32 & 0xFFFF_C000
        }
        else {
            if ttbcr & TTBCR_PD0 != 0 {
                return Err(FSC_TRANSLATION + 1);
            }
            *ttbr0_el1 as u32 & !(0x3FFF >> n)
        }
    };
    let l1 = descriptor32((table | va >> 18 & 0x3FFC) as u64).ok_or(FSC_EXTERNAL_WALK + 1)?;
    let kind = l1 & 3;
    // (the faults' domain: the level 1 descriptor's bits 8:5, as QEMU has it)
    let in_domain = (l1 >> 5 & 15) << FSC_DOMAIN_SHIFT;
    if kind == 0 {
        return Err(FSC_TRANSLATION + 1 | in_domain);
    }
    let supersection = kind != 1 && l1 & 1 << 18 != 0;
    // (supersections are in domain 0)
    let domain = if supersection { 0 } else { l1 >> 5 & 15 };
    let domain_prot = unsafe { *a32_dacr } >> (2 * domain) & 3;
    let page = kind == 1;
    if domain_prot == 0 || domain_prot == 2 {
        return Err(if page { FSC_DOMAIN_PAGE } else { FSC_DOMAIN_SECTION } | in_domain);
    }
    let (pa, size_log, ap, xn, pxn, tex, cb, s, ng);
    if !page {
        if supersection {
            pa = (l1 & 0xFF00_0000 | va & 0x00FF_FFFF) as u64
                | ((l1 >> 20 & 15) as u64) << 32
                | ((l1 >> 5 & 15) as u64) << 36;
            size_log = 24;
        }
        else {
            pa = (l1 & 0xFFF0_0000 | va & 0x000F_FFFF) as u64;
            size_log = 20;
        }
        ap = l1 >> 10 & 3 | l1 >> 13 & 4;
        xn = l1 >> 4 & 1 != 0;
        pxn = l1 & 1 != 0;
        tex = l1 >> 12 & 7;
        cb = l1 >> 2 & 3;
        s = l1 >> 16 & 1;
        ng = l1 >> 17 & 1;
    }
    else {
        pxn = l1 >> 2 & 1 != 0;
        let l2 = descriptor32((l1 & 0xFFFF_FC00 | va >> 10 & 0x3FC) as u64)
            .ok_or(FSC_EXTERNAL_WALK + 2 | in_domain)?;
        ap = l2 >> 4 & 3 | l2 >> 7 & 4;
        match l2 & 3 {
            0 => return Err(FSC_TRANSLATION + 2 | in_domain),
            1 => {
                pa = (l2 & 0xFFFF_0000 | va & 0xFFFF) as u64;
                size_log = 16;
                xn = l2 >> 15 & 1 != 0;
                tex = l2 >> 12 & 7;
            },
            _ => {
                pa = (l2 & 0xFFFF_F000 | va & 0xFFF) as u64;
                size_log = 12;
                xn = l2 & 1 != 0;
                tex = l2 >> 6 & 7;
            },
        }
        cb = l2 >> 2 & 3;
        s = l2 >> 10 & 1;
        ng = l2 >> 11 & 1;
    }
    let level = if page { 2 } else { 1 };
    let sctlr = cpu::sctlr();
    // the client permissions (a manager's are every one: with_domain)
    let afe = sctlr & SCTLR_AFE != 0;
    let (pl1, pl0) = if afe {
        if ap & 1 == 0 {
            if domain_prot != 3 {
                return Err(FSC_ACCESS_FLAG + level | in_domain);
            }
            (0, 0)
        }
        else {
            simple_permissions(ap >> 1)
        }
    }
    else {
        full_permissions(ap)
    };
    let mut flags = 0;
    if pl1 & 1 != 0 {
        flags |= EL1_READ;
        if !xn && !pxn {
            flags |= EL1_EXEC;
        }
    }
    if pl1 & 2 != 0 {
        flags |= EL1_WRITE;
    }
    if pl0 & 1 != 0 {
        flags |= EL0_READ;
        if !xn {
            flags |= EL0_EXEC;
        }
    }
    if pl0 & 2 != 0 {
        flags |= EL0_WRITE;
    }
    if ng == 0 {
        flags |= GLOBAL;
    }
    // the memory type: PRRR's and NMRR's with TEX remap (TEX[0]:C:B), else TEX:C:B's
    let (device, attr) = if sctlr & SCTLR_TRE != 0 {
        let index = (tex & 1) << 2 | cb;
        let (prrr, nmrr) = unsafe { (*mair_el1 as u32, (*mair_el1 >> 32) as u32) };
        let tr = prrr >> (2 * index) & 3;
        let inner = cacheability(nmrr >> (2 * index));
        let outer = cacheability(nmrr >> (2 * index + 16));
        (tr < 2, if tr < 2 { 0 } else { outer << 4 | inner })
    }
    else if tex & 4 != 0 {
        (false, cacheability(tex & 3) << 4 | cacheability(cb))
    }
    else {
        match (tex, cb) {
            (0, 0 | 1) | (2, 0) => (true, 0),
            (0, 2) => (false, 0xAA),
            (0, 3) => (false, 0xEE),
            (1, 3) => (false, 0xFF),
            _ => (false, 0x44),
        }
    };
    if device {
        flags |= DEVICE;
    }
    Ok(Leaf {
        pa,
        // (a small or large page is a page for tlb.rs, a section a block)
        level: if page { 3 } else { 1 },
        size_log,
        flags,
        attr,
        sh: if s != 0 { 3 } else { 0 } | SH_DOMAIN | (domain as u8) << 4,
    })
}
                                                                                                                                                                                                                                                              source/v64/src/rust/aarch64/mod.rs                                                                  0000644 0000000 0000000 00000001765 00000000000 014036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ARM core, build/v86-arm64.wasm (docs/arm64-virt-android16-plan.md):
//! an AArch64 CPU (profile v86-aarch64-v1) for the virt machine, built from
//! this crate with the feature aarch64 instead of the x86 modules. It shares
//! the ISA-neutral modules (jitrt, wasmgen, leb, page, zstd, parallel, the
//! state block) and names no x86 module (tools/check_a64_imports.mjs).

pub mod a32;
pub mod a32_fp;
pub mod a32_simd;
pub mod a32_system;
pub mod backdoor;
pub mod bus;
pub mod cpu;
pub mod crypto;
pub mod debug;
pub mod decode;
pub mod execute;
pub mod extended;
pub mod fp;
pub mod gic;
pub mod isa_hooks;
pub mod jit;
pub mod memory;
pub mod mmu;
pub mod mmu_a32;
pub mod psci;
pub mod root;
pub mod simd;
pub mod simd_decode;
pub mod simd_fp;
pub mod smp;
pub mod state;
pub mod sysregs;
pub mod t32;
pub mod timer;
pub mod tlb;

/// The ISA marker the loader checks after instantiating a core (P1.3): the
/// ARM core exports it, the x86 core does not
#[no_mangle]
pub fn isa_aarch64() -> u32 { 1 }
           source/v64/src/rust/aarch64/psci.rs                                                                 0000644 0000000 0000000 00000020161 00000000000 014204  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! PSCI 1.1 over HVC (docs/arm64-virt-android16-plan.md: the emulator takes
//! HVC as PSCI/SMCCC, as QEMU does without EL2): the functions QEMU 9.2
//! implements (target/arm/tcg/psci.c), with the same results; any other
//! function ID, SMCCC_VERSION included, returns NOT_SUPPORTED.
//!
//! The power states, the start addresses and the machine's request are the
//! machine instance's (crate::parallel::machine): with cores in workers
//! (P8.2) CPU_ON kicks the started core's worker, SYSTEM_OFF and
//! SYSTEM_RESET the machine's core.

use crate::aarch64::cpu;

pub const PSCI_VERSION: u64 = 0x8400_0000;
pub const CPU_SUSPEND: u64 = 0x8400_0001;
pub const CPU_OFF: u64 = 0x8400_0002;
pub const CPU_ON: u64 = 0x8400_0003;
pub const AFFINITY_INFO: u64 = 0x8400_0004;
pub const MIGRATE: u64 = 0x8400_0005;
pub const MIGRATE_INFO_TYPE: u64 = 0x8400_0006;
pub const SYSTEM_OFF: u64 = 0x8400_0008;
pub const SYSTEM_RESET: u64 = 0x8400_0009;
pub const PSCI_FEATURES: u64 = 0x8400_000A;
const FN64: u64 = 0x4000_0000;
// PSCI 0.1's function IDs (QEMU's, from KVM)
const V01_CPU_SUSPEND: u64 = 0x95C1_BA5E;
const V01_CPU_OFF: u64 = 0x95C1_BA5F;
const V01_CPU_ON: u64 = 0x95C1_BA60;
const V01_MIGRATE: u64 = 0x95C1_BA61;

pub const SUCCESS: i64 = 0;
pub const NOT_SUPPORTED: i64 = -1;
pub const INVALID_PARAMETERS: i64 = -2;
pub const ALREADY_ON: i64 = -4;
pub const ON_PENDING_RESULT: i64 = -5;

// the cores' power states (AFFINITY_INFO's values)
pub const ON: u8 = 0;
pub const OFF: u8 = 1;
pub const ON_PENDING: u8 = 2;

/// The cores' power states: 0 on, 1 off, 2 on pending (AFFINITY_INFO)
pub static mut POWER: [u8; crate::isa::MAX_CORES] = [0, 1, 1, 1, 1, 1, 1, 1];
/// A core started by CPU_ON: its entry point and context ID (the scheduler starts it, crate::aarch64::smp)
pub static mut START: [(u64, u64); crate::isa::MAX_CORES] = [(0, 0); crate::isa::MAX_CORES];
/// SYSTEM_OFF (1) or SYSTEM_RESET (2) was called
pub static mut REQUEST: u32 = 0;

/// Core `core`'s power state (ON, OFF, ON_PENDING)
#[inline(always)]
pub fn power(core: usize) -> u8 {
    unsafe {
        crate::parallel::load8(
            crate::parallel::machine(&raw mut POWER)
                .cast::<u8>()
                .add(core),
        )
    }
}
pub fn set_power(core: usize, state: u8) {
    unsafe {
        crate::parallel::store8(
            crate::parallel::machine(&raw mut POWER)
                .cast::<u8>()
                .add(core),
            state,
        )
    }
}
/// The entry point and context ID CPU_ON gave core `core`
pub fn start(core: usize) -> (u64, u64) {
    unsafe {
        let at = crate::parallel::machine(&raw mut START)
            .cast::<(u64, u64)>()
            .add(core);
        crate::parallel::full_fence();
        *at
    }
}
/// The machine's request: SYSTEM_OFF (1), SYSTEM_RESET (2)
#[inline(always)]
pub fn request() -> u32 {
    unsafe { crate::parallel::word_load(crate::parallel::machine(&raw mut REQUEST)) }
}
pub fn set_request(value: u32) {
    unsafe { crate::parallel::word_store(crate::parallel::machine(&raw mut REQUEST), value) };
    // (the machine's core leaves its slice: the machine stops)
    if value != 0 {
        unsafe { crate::parallel::kick(0) };
    }
}
/// Reset the power states: core 0 on, the others off (a64_boot)
pub fn reset() {
    for core in 0..crate::isa::MAX_CORES {
        set_power(core, if core == 0 { ON } else { OFF });
    }
    set_request(0);
}

#[repr(C)]
struct PowerState {
    power: [u8; crate::isa::MAX_CORES],
    start: [(u64, u64); crate::isa::MAX_CORES],
    request: u32,
}

/// (snapshots) the cores' power states as bytes: copied out of and into a scratch area
static mut SNAPSHOT: PowerState = PowerState {
    power: [0; crate::isa::MAX_CORES],
    start: [(0, 0); crate::isa::MAX_CORES],
    request: 0,
};

/// (snapshots) the power states: their bytes (an area filled now; read back by `restored`)
pub fn state_bytes() -> (u32, u32) {
    unsafe {
        SNAPSHOT = PowerState {
            power: *crate::parallel::machine(&raw mut POWER),
            start: *crate::parallel::machine(&raw mut START),
            request: request(),
        };
        (
            &raw const SNAPSHOT as u32,
            core::mem::size_of::<PowerState>() as u32,
        )
    }
}

/// (snapshots) take the power states written into the scratch area
#[no_mangle]
pub fn a64_psci_restored() {
    unsafe {
        *crate::parallel::machine(&raw mut POWER) = SNAPSHOT.power;
        *crate::parallel::machine(&raw mut START) = SNAPSHOT.start;
        *crate::parallel::machine(&raw mut REQUEST) = SNAPSHOT.request;
    }
}

/// What the calling core does after the call
pub enum After {
    Continue,
    /// CPU_SUSPEND: wait for an interrupt (as WFI)
    Wait,
    /// CPU_OFF, SYSTEM_OFF, SYSTEM_RESET: this core stops
    Off,
}

fn core_of(mpidr: u64) -> Option<usize> {
    // (Aff0 is the core; Aff1-3 are 0)
    let core = (mpidr & 0xFF_00FF_FFFF) as usize;
    (core < crate::isa::core_count()).then_some(core)
}

/// A PSCI call: x0 the function, x1-x3 its arguments; the result goes to x0
pub fn call() -> After {
    let function = cpu::xr(0);
    let (a1, a2, a3) = (cpu::xr(1), cpu::xr(2), cpu::xr(3));
    let mut after = After::Continue;
    let result: i64 = unsafe {
        match function {
            PSCI_VERSION => 0x1_0001,
            MIGRATE_INFO_TYPE => 2, // no trusted OS
            f if f == AFFINITY_INFO || f == AFFINITY_INFO | FN64 => {
                if a2 != 0 {
                    0 // (levels above 0 are always on)
                }
                else {
                    match core_of(a1) {
                        Some(core) => power(core) as i64,
                        None => INVALID_PARAMETERS,
                    }
                }
            },
            SYSTEM_RESET => {
                set_request(2);
                after = After::Off;
                0
            },
            SYSTEM_OFF => {
                set_request(1);
                after = After::Off;
                0
            },
            f if f == CPU_ON || f == CPU_ON | FN64 || f == V01_CPU_ON => match core_of(a1) {
                None => INVALID_PARAMETERS,
                Some(core) if power(core) == ON => ALREADY_ON,
                Some(core) if power(core) == ON_PENDING => ON_PENDING_RESULT,
                Some(core) => {
                    // (the start address before the state the core's worker waits for)
                    *crate::parallel::machine(&raw mut START)
                        .cast::<(u64, u64)>()
                        .add(core) = (a2, a3);
                    crate::parallel::full_fence();
                    set_power(core, ON_PENDING);
                    crate::parallel::kick(core);
                    SUCCESS
                },
            },
            CPU_OFF | V01_CPU_OFF => {
                set_power(crate::isa::current_core(), OFF);
                after = After::Off;
                0
            },
            f if f == CPU_SUSPEND || f == CPU_SUSPEND | FN64 || f == V01_CPU_SUSPEND => {
                if a1 & 0xFFFE_0000 != 0 {
                    INVALID_PARAMETERS
                }
                else {
                    after = After::Wait;
                    0
                }
            },
            PSCI_FEATURES => match a1 {
                PSCI_VERSION | MIGRATE_INFO_TYPE | SYSTEM_RESET | SYSTEM_OFF | CPU_OFF
                | PSCI_FEATURES | V01_CPU_ON | V01_CPU_OFF | V01_CPU_SUSPEND => 0,
                f if f == AFFINITY_INFO || f == AFFINITY_INFO | FN64 => 0,
                f if f == CPU_ON || f == CPU_ON | FN64 => 0,
                f if f == CPU_SUSPEND || f == CPU_SUSPEND | FN64 => 0,
                _ => NOT_SUPPORTED,
            },
            MIGRATE | V01_MIGRATE => NOT_SUPPORTED,
            _ => NOT_SUPPORTED,
        }
    };
    cpu::set_x(0, result as u64);
    after
}

/// Whether the guest turned the machine off (the machine's power hook)
#[no_mangle]
pub fn a64_powered_off() -> bool { request() == 1 }
/// SYSTEM_RESET was called (and is taken)
#[no_mangle]
pub fn a64_take_reset_request() -> bool {
    let reset = request() == 2;
    if reset {
        unsafe { crate::parallel::word_store(crate::parallel::machine(&raw mut REQUEST), 0) };
    }
    reset
}
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/rust/aarch64/root.rs                                                                 0000644 0000000 0000000 00000010627 00000000000 014237  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ARM core's composition root (the x86 core's is crate::jit): the host
//! environment of the ISA-neutral runtime crate::jitrt, and what happens to
//! compiled code when guest memory is written or the address space changes.
//! Its code client is the A64 page tier (crate::aarch64::jit, the JIT plan's
//! J2).
use std::collections::HashSet;

use crate::aarch64::bus;
use crate::jitrt::table::{Owner, Signature};
use crate::jitrt::watch::Trigger;
use crate::jitrt::{self, host::Env, ClientId};
use crate::page::Page;

#[cfg(target_arch = "wasm32")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn jit_clear_func(wasm_table_index: u16);
    }
}
#[cfg(not(target_arch = "wasm32"))]
mod js {
    pub unsafe fn jit_clear_func(_wasm_table_index: u16) {}
}

/// The table's geometry: as the x86 core's (src/const.js)
pub const WASM_TABLE_SIZE: u32 = 12000;
pub const WASM_TABLE_OFFSET: u32 = 1024;

#[no_mangle]
pub fn rust_init() {
    jitrt::init(Env {
        table_size: WASM_TABLE_SIZE,
        table_offset: WASM_TABLE_OFFSET,
        state_base: crate::state_block::state_base(),
        mem8: || unsafe { bus::MEM8 },
        now: || unsafe { crate::isa::microtick() },
        core: crate::isa::current_core,
        clear_slot: |slot| unsafe { js::jit_clear_func(slot as u16) },
        page_has_code: |_, _| {},
        // (write entries of the access cache to pages that gained code retire)
        pages_gain_code: crate::aarch64::jit::pages::pages_gain_code,
        claim: |page, on| unsafe {
            if on {
                crate::parallel::code::claim(page)
            }
            else {
                crate::parallel::code::release(page)
            }
        },
        release_all: || unsafe { crate::parallel::code::release_all() },
    });
    // (a new map invalidates every translation compiled code made)
    bus::on_map_changed(|| jitrt::state().watch.reset());
    // the A64 page tier: publication's answers; a write to a page retires the
    // functions compiled from it (each mode's), a reset all of them
    crate::aarch64::jit::pages::register();
    // (the whole table is the A64 page tier's: jitrt::capacity)
    jitrt::capacity::set_quota(ClientId::A64Page, crate::aarch64::jit::pages::MAX_FUNCTIONS);
    // (its counters through jit_stat(1, field), P5.10)
    jitrt::stat::register(ClientId::A64Page, crate::aarch64::jit::pages::a64_page_stat);
    jitrt::state()
        .watch
        .on_dirty(Trigger::WatchedOnly, |page, _| {
            unsafe { TEST_RETIRED += 1 };
            crate::aarch64::jit::pages::page_written(page);
            Vec::new()
        });
    jitrt::state()
        .watch
        .on_reset(crate::aarch64::jit::pages::retire_all);
    std::panic::set_hook(Box::new(|panic_info| {
        console_log!("{}", panic_info.to_string());
    }));
}

/// The fewest free table slots since the last jit_wasm_table_free_low_reset
/// (as the x86 core's, src/rust/jit.rs)
#[no_mangle]
pub fn jit_wasm_table_free_low() -> u32 { jitrt::state().table.free_low() }
#[no_mangle]
pub fn jit_wasm_table_free_low_reset() { jitrt::state().table.reset_free_low() }

/// Drop all compiled code (a snapshot was restored, guest memory changed under it)
#[no_mangle]
pub fn jit_clear_cache_js() { jitrt::state().watch.reset() }

/// Whether code was compiled from this page of guest memory, by this
/// instance or (with cores in workers) another: writes must notify
#[inline(always)]
pub fn page_watched(page: u32) -> bool {
    jitrt::watch::bit(page) || unsafe { crate::parallel::code::others_own(page) }
}

/// A write of the bytes lo..hi of the page: retire the code compiled from it
pub fn dirty_bytes(page: Page, lo: u32, hi: u32) {
    jitrt::state().watch.write(page, Some((lo, hi)));
}

/// Writes that retired a page a64_test_watch_page watched
static mut TEST_RETIRED: u32 = 0;
/// Tests (tests/a64/address_space.mjs), until the A64 page tier (P6) has
/// code: watch the guest-memory page `page` (a code key) as code compiled
/// from it would be watched
#[no_mangle]
pub fn a64_test_watch_page(page: u32) -> bool {
    let mut rt = jitrt::state();
    let Some(slot) = rt.table.reserve(Owner {
        client: ClientId::A64Page,
        signature: Signature::Fn1,
        id: page as u64,
    })
    else {
        return false;
    };
    rt.watch
        .attach(slot, HashSet::from([Page::page_of(page << 12)]));
    true
}
#[no_mangle]
pub fn a64_test_retired() -> u32 { unsafe { TEST_RETIRED } }
                                                                                                         source/v64/src/rust/aarch64/simd.rs                                                                 0000644 0000000 0000000 00000113112 00000000000 014201  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AdvSIMD and the SIMD&FP registers' loads, stores and moves
//! (docs/arm64-virt-android16-plan.md P2.5, P2.7): the integer classes of
//! AdvSIMD, vector and scalar, written element by element on u128 values
//! (so the portable build runs them too), the structure loads and stores,
//! TBL/TBX, the permutes. The FP operations of the same classes are in
//! simd_fp, the crypto instructions in crypto. Each instruction reads its
//! operands from the word (simd_decode checked it), computes, and only then
//! writes registers; a saturating operation sets FPSR.QC.

use crate::aarch64::cpu::{self, xr, xr_sp, Exception};
use crate::aarch64::decode::bits;
use crate::aarch64::execute::Flow;
use crate::aarch64::fp;
use crate::aarch64::memory::{self, Syndrome};
use crate::aarch64::simd_decode;
use crate::aarch64::state::{fpsr, v};

// ---- registers and elements

#[inline(always)]
pub fn vreg(n: u32) -> u128 { unsafe { *v.add(n as usize) } }
#[inline(always)]
pub fn set_vreg(n: u32, value: u128) { unsafe { *v.add(n as usize) = value } }

#[inline(always)]
pub fn ones(bits: u32) -> u64 {
    if bits >= 64 {
        u64::MAX
    }
    else {
        (1u64 << bits) - 1
    }
}
#[inline(always)]
pub fn elem(x: u128, index: u32, esize: u32) -> u64 { (x >> (index * esize)) as u64 & ones(esize) }
#[inline(always)]
pub fn with_elem(x: u128, index: u32, esize: u32, value: u64) -> u128 {
    let at = index * esize;
    x & !((ones(esize) as u128) << at) | ((value & ones(esize)) as u128) << at
}
/// The element as a signed value
#[inline(always)]
pub fn sext(value: u64, esize: u32) -> i64 { ((value << (64 - esize)) as i64) >> (64 - esize) }
#[inline(always)]
pub(crate) fn int(value: u64, esize: u32, unsigned: bool) -> i128 {
    if unsigned {
        value as i128
    }
    else {
        sext(value, esize) as i128
    }
}

/// The registers of a data processing word: Rd, Rn, Rm
#[inline(always)]
fn regs(word: u32) -> (u32, u32, u32) { (word & 31, word >> 5 & 31, word >> 16 & 31) }

#[inline(always)]
pub fn set_qc() { unsafe { *fpsr |= fp::FPSR_QC } }

/// SatQ: the value saturated to `esize` bits (signed or unsigned); whether it saturated
#[inline(always)]
pub fn sat(value: i128, esize: u32, unsigned: bool, qc: &mut bool) -> u64 {
    let (min, max) = if unsigned {
        (0i128, ones(esize) as i128)
    }
    else {
        (-(1i128 << (esize - 1)), (1i128 << (esize - 1)) - 1)
    };
    let clamped = if value > max {
        *qc = true;
        max
    }
    else if value < min {
        *qc = true;
        min
    }
    else {
        value
    };
    clamped as u64 & ones(esize)
}

/// The shift of SSHL and its kin: `value` << `shift` (a right shift for a
/// negative one), rounded, saturated or truncated to `esize` bits
pub(crate) fn shift_by(
    value: i128,
    shift: i64,
    esize: u32,
    unsigned: bool,
    round: bool,
    saturate: bool,
    qc: &mut bool,
) -> u64 {
    let result = if shift >= 0 {
        if value == 0 {
            0
        }
        else if shift as u32 >= esize {
            // (every bit leaves the element; any nonzero value saturates)
            if saturate {
                return sat(
                    if value < 0 { i128::MIN / 2 } else { i128::MAX / 2 },
                    esize,
                    unsigned,
                    qc,
                );
            }
            0
        }
        else {
            value << shift
        }
    }
    else {
        let k = (-shift).min(esize as i64 + 1) as u32;
        let round_const = if round { 1i128 << (k - 1) } else { 0 };
        (value + round_const) >> k
    };
    if saturate {
        sat(result, esize, unsigned, qc)
    }
    else {
        result as u64 & ones(esize)
    }
}

/// Polynomial multiplication of two `esize`-bit values (the 2 * esize-bit product)
pub fn pmul(a: u64, b: u64, esize: u32) -> u128 {
    let mut result = 0u128;
    for i in 0..esize {
        if a >> i & 1 != 0 {
            result ^= (b as u128) << i;
        }
    }
    result
}

/// The width of a vector operation: 64 or 128 bits
#[inline(always)]
fn datasize(word: u32) -> u32 { 64 << (word >> 30 & 1) }

/// The upper or lower half of a register for the "2" forms (Q = 1: the upper)
#[inline(always)]
fn half(value: u128, word: u32) -> u64 {
    if word >> 30 & 1 != 0 {
        (value >> 64) as u64
    }
    else {
        value as u64
    }
}

/// Vpart write of a narrowing instruction: the lower half (Q = 0, the upper
/// half zeroed) or the upper half (Q = 1, the lower half kept)
#[inline(always)]
fn write_narrow(d: u32, word: u32, result: u64) {
    if word >> 30 & 1 != 0 {
        set_vreg(d, vreg(d) & u64::MAX as u128 | (result as u128) << 64);
    }
    else {
        set_vreg(d, result as u128);
    }
}

// ---- the classes

/// AdvSIMD three same (vector and scalar), integer and logical
pub fn three_same(word: u32) -> Flow {
    let opcode = bits(word, 15, 11);
    if opcode >= 0b11000 {
        return crate::aarch64::simd_fp::three_same(word);
    }
    let (d, n, m) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let size = bits(word, 23, 22);
    let (a, b, c) = (vreg(n), vreg(m), vreg(d));
    let width = if scalar { 8 << size } else { datasize(word) };
    let keep = if width == 128 { u128::MAX } else { (1u128 << width) - 1 };
    if opcode == 0b00011 {
        let result = match u << 2 | size {
            0 => a & b,
            1 => a & !b,
            2 => a | b,
            3 => a | !b,
            4 => a ^ b,
            5 => a & c | b & !c,
            6 => a & b | c & !b,
            _ => c & b | a & !b,
        };
        set_vreg(d, result & keep);
        return Flow::Next;
    }
    let esize = 8 << size;
    let elements = width / esize;
    let mut qc = false;
    if !scalar && matches!(opcode, 0b10100 | 0b10101 | 0b10111) {
        // pairwise: the elements of m:n, two by two
        let mut result = 0u128;
        for e in 0..elements {
            let (source, i) = if 2 * e < elements { (a, 2 * e) } else { (b, 2 * e - elements) };
            let (x, y) = (elem(source, i, esize), elem(source, i + 1, esize));
            let (sx, sy) = (int(x, esize, unsigned), int(y, esize, unsigned));
            let r = match opcode {
                0b10100 => sx.max(sy) as u64,
                0b10101 => sx.min(sy) as u64,
                _ => x.wrapping_add(y),
            };
            result = with_elem(result, e, esize, r);
        }
        set_vreg(d, result);
        return Flow::Next;
    }
    let mut result = 0u128;
    for e in 0..elements {
        let (x, y, z) = (elem(a, e, esize), elem(b, e, esize), elem(c, e, esize));
        let (sx, sy) = (int(x, esize, unsigned), int(y, esize, unsigned));
        let mask = ones(esize);
        let test = |t: bool| if t { mask } else { 0 };
        let r = match (u, opcode) {
            (_, 0b00000) => ((sx + sy) >> 1) as u64,
            (_, 0b00001) => sat(sx + sy, esize, unsigned, &mut qc),
            (_, 0b00010) => ((sx + sy + 1) >> 1) as u64,
            (_, 0b00100) => ((sx - sy) >> 1) as u64,
            (_, 0b00101) => sat(sx - sy, esize, unsigned, &mut qc),
            (_, 0b00110) => test(sx > sy),
            (_, 0b00111) => test(sx >= sy),
            (_, 0b01000..=0b01011) => {
                let shift = y as u8 as i8 as i64;
                shift_by(
                    sx,
                    shift,
                    esize,
                    unsigned,
                    opcode & 2 != 0,
                    opcode & 1 != 0,
                    &mut qc,
                )
            },
            (_, 0b01100) => sx.max(sy) as u64,
            (_, 0b01101) => sx.min(sy) as u64,
            (_, 0b01110) => (sx - sy).unsigned_abs() as u64,
            (_, 0b01111) => z.wrapping_add((sx - sy).unsigned_abs() as u64),
            (0, 0b10000) => x.wrapping_add(y),
            (1, 0b10000) => x.wrapping_sub(y),
            (0, 0b10001) => test(x & y != 0),
            (1, 0b10001) => test(x == y),
            (0, 0b10010) => z.wrapping_add(x.wrapping_mul(y)),
            (1, 0b10010) => z.wrapping_sub(x.wrapping_mul(y)),
            (0, 0b10011) => x.wrapping_mul(y),
            (1, 0b10011) => pmul(x, y, 8) as u64,
            (_, 0b10110) => {
                // SQDMULH, SQRDMULH
                let (sx, sy) = (sext(x, esize) as i128, sext(y, esize) as i128);
                let round = if u == 1 { 1i128 << (esize - 1) } else { 0 };
                sat((2 * sx * sy + round) >> esize, esize, false, &mut qc)
            },
            _ => 0,
        };
        result = with_elem(result, e, esize, r);
    }
    set_vreg(d, result);
    if qc {
        set_qc();
    }
    Flow::Next
}

/// AdvSIMD three different (vector and scalar): long, wide and narrow
pub fn three_different(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 15, 12);
    let esize = 8 << size;
    let (a, b, c) = (vreg(n), vreg(m), vreg(d));
    if opcode == 0b1110 {
        // PMULL, PMULL2
        if size == 3 {
            set_vreg(d, pmul(half(a, word), half(b, word), 64));
        }
        else {
            let (x, y) = (half(a, word), half(b, word));
            let mut result = 0u128;
            for e in 0..8 {
                result = with_elem(
                    result,
                    e,
                    16,
                    pmul(elem(x as u128, e, 8), elem(y as u128, e, 8), 8) as u64,
                );
            }
            set_vreg(d, result);
        }
        return Flow::Next;
    }
    let elements = if scalar { 1 } else { 64 / esize };
    let mut qc = false;
    if matches!(opcode, 0b0100 | 0b0110) {
        // ADDHN, RADDHN, SUBHN, RSUBHN: the high halves of wide sums
        let mut result = 0u64;
        for e in 0..elements {
            let (x, y) = (elem(a, e, 2 * esize) as u128, elem(b, e, 2 * esize) as u128);
            let round = if unsigned { 1u128 << (esize - 1) } else { 0 };
            let sum = if opcode == 0b0100 { x.wrapping_add(y) } else { x.wrapping_sub(y) }
                .wrapping_add(round);
            result |= ((sum >> esize) as u64 & ones(esize)) << (e * esize);
        }
        write_narrow(d, word, result);
        return Flow::Next;
    }
    let (x_half, y_half) = if scalar {
        (a as u64 as u128, b as u64 as u128)
    }
    else {
        (half(a, word) as u128, half(b, word) as u128)
    };
    let mut result = 0u128;
    for e in 0..elements {
        let wide_x = if matches!(opcode, 0b0001 | 0b0011) {
            int(elem(a, e, 2 * esize), 2 * esize, unsigned)
        }
        else {
            int(elem(x_half, e, esize), esize, unsigned)
        };
        let y = int(elem(y_half, e, esize), esize, unsigned);
        let acc = int(elem(c, e, 2 * esize), 2 * esize, unsigned);
        let w = 2 * esize;
        let r = match opcode {
            0b0000 | 0b0001 => (wide_x + y) as u64,
            0b0010 | 0b0011 => (wide_x - y) as u64,
            0b0101 => (acc + (wide_x - y).abs()) as u64,
            0b0111 => (wide_x - y).abs() as u64,
            0b1000 => (acc + wide_x * y) as u64,
            0b1010 => (acc - wide_x * y) as u64,
            0b1100 => (wide_x * y) as u64,
            // SQDMLAL, SQDMLSL, SQDMULL
            _ => {
                let product = sat(2 * wide_x * y, w, false, &mut qc);
                let product = sext(product, w) as i128;
                let acc = sext(elem(c, e, w), w) as i128;
                match opcode {
                    0b1001 => sat(acc + product, w, false, &mut qc),
                    0b1011 => sat(acc - product, w, false, &mut qc),
                    _ => product as u64,
                }
            },
        };
        result = with_elem(result, e, w, r);
    }
    set_vreg(d, result);
    if qc {
        set_qc();
    }
    Flow::Next
}

/// AdvSIMD two-register miscellaneous (vector and scalar), integer
pub fn two_misc(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    let fp_class = matches!(opcode, 0b01100..=0b01111) && size >= 2 || opcode >= 0b10110;
    if fp_class {
        return crate::aarch64::simd_fp::two_misc(word);
    }
    let esize = 8 << size;
    let width = if scalar { esize } else { datasize(word) };
    let elements = width / esize;
    let (a, c) = (vreg(n), vreg(d));
    let mut qc = false;
    match (u, opcode) {
        (_, 0b00000) | (0, 0b00001) => {
            // REV64, REV32, REV16: the elements reversed within each container
            let container = match (u, opcode) {
                (0, 0b00000) => 64,
                (1, 0b00000) => 32,
                _ => 16,
            };
            let per = container / esize;
            let mut result = 0u128;
            for e in 0..elements {
                let target = e - e % per + (per - 1 - e % per);
                result = with_elem(result, target, esize, elem(a, e, esize));
            }
            set_vreg(d, result);
        },
        (_, 0b00010) | (_, 0b00110) => {
            // SADDLP, UADDLP, SADALP, UADALP
            let mut result = 0u128;
            for e in 0..elements / 2 {
                let sum = int(elem(a, 2 * e, esize), esize, unsigned)
                    + int(elem(a, 2 * e + 1, esize), esize, unsigned);
                let acc = if opcode == 0b00110 { elem(c, e, 2 * esize) as i128 } else { 0 };
                result = with_elem(result, e, 2 * esize, (acc + sum) as u64);
            }
            set_vreg(d, result);
        },
        (_, 0b10010) | (_, 0b10100) => {
            // XTN, SQXTN, UQXTN, SQXTUN: narrow (scalar: one element)
            let mut result = 0u64;
            let count = if scalar { 1 } else { 64 / esize };
            for e in 0..count {
                let x = elem(a, e, 2 * esize);
                let r = match (u, opcode) {
                    (0, 0b10010) => x & ones(esize),
                    (0, 0b10100) => sat(sext(x, 2 * esize) as i128, esize, false, &mut qc),
                    (1, 0b10100) => sat(x as i128, esize, true, &mut qc),
                    _ => sat(sext(x, 2 * esize) as i128, esize, true, &mut qc),
                };
                result |= r << (e * esize);
            }
            if scalar {
                set_vreg(d, result as u128);
            }
            else {
                write_narrow(d, word, result);
            }
        },
        (1, 0b10011) => {
            // SHLL, SHLL2
            let x = half(a, word) as u128;
            let mut result = 0u128;
            for e in 0..64 / esize {
                result = with_elem(result, e, 2 * esize, elem(x, e, esize) << esize);
            }
            set_vreg(d, result);
        },
        (1, 0b00101) => {
            // NOT (size 0), RBIT
            let result = if size == 0 {
                !a
            }
            else {
                let mut r = 0u128;
                for e in 0..16 {
                    r = with_elem(r, e, 8, (elem(a, e, 8) as u8).reverse_bits() as u64);
                }
                r
            };
            let keep = if width == 128 { u128::MAX } else { (1u128 << width) - 1 };
            set_vreg(d, result & keep);
        },
        _ => {
            let mut result = 0u128;
            for e in 0..elements {
                let x = elem(a, e, esize);
                let sx = sext(x, esize) as i128;
                let mask = ones(esize);
                let test = |t: bool| if t { mask } else { 0 };
                let r = match (u, opcode) {
                    (0, 0b00011) => sat(
                        sext(elem(c, e, esize), esize) as i128 + x as i128,
                        esize,
                        false,
                        &mut qc,
                    ),
                    (1, 0b00011) => sat(elem(c, e, esize) as i128 + sx, esize, true, &mut qc),
                    (0, 0b00100) => {
                        // CLS
                        let bits = if sx < 0 { !x & mask } else { x };
                        (bits.leading_zeros() - (64 - esize)).saturating_sub(1) as u64
                    },
                    (1, 0b00100) => (x.leading_zeros() - (64 - esize)) as u64,
                    (0, 0b00101) => x.count_ones() as u64,
                    (0, 0b00111) => sat(sx.abs(), esize, false, &mut qc),
                    (1, 0b00111) => sat(-sx, esize, false, &mut qc),
                    (0, 0b01000) => test(sx > 0),
                    (1, 0b01000) => test(sx >= 0),
                    (0, 0b01001) => test(sx == 0),
                    (1, 0b01001) => test(sx <= 0),
                    (0, 0b01010) => test(sx < 0),
                    (0, 0b01011) => sx.unsigned_abs() as u64,
                    (1, 0b01011) => (-sx) as u64,
                    _ => 0,
                };
                result = with_elem(result, e, esize, r);
            }
            set_vreg(d, result);
        },
    }
    if qc {
        set_qc();
    }
    Flow::Next
}

/// AdvSIMD across lanes
pub fn across(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    if matches!(opcode, 0b01100 | 0b01111) {
        return crate::aarch64::simd_fp::across(word);
    }
    let esize = 8 << size;
    let elements = datasize(word) / esize;
    let a = vreg(n);
    let values = (0..elements).map(|e| int(elem(a, e, esize), esize, unsigned));
    let (result, rsize) = match opcode {
        0b00011 => (values.sum::<i128>() as u64, 2 * esize),
        0b01010 => (values.max().unwrap_or(0) as u64, esize),
        0b11010 => (values.min().unwrap_or(0) as u64, esize),
        _ => (values.sum::<i128>() as u64, esize),
    };
    set_vreg(d, (result & ones(rsize)) as u128);
    Flow::Next
}

/// AdvSIMD scalar pairwise
pub fn pairwise(word: u32) -> Flow {
    if word >> 29 & 1 != 0 {
        return crate::aarch64::simd_fp::pairwise(word);
    }
    let (d, n, _) = regs(word);
    let a = vreg(n);
    set_vreg(d, (a as u64).wrapping_add((a >> 64) as u64) as u128);
    Flow::Next
}

/// AdvSIMD copy (DUP, INS, SMOV, UMOV) and scalar DUP
pub fn copy(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let q = word >> 30 & 1 != 0;
    let imm5 = bits(word, 20, 16);
    let imm4 = bits(word, 14, 11);
    let size = imm5.trailing_zeros();
    let esize = 8 << size;
    let index = imm5 >> (size + 1);
    if word >> 28 & 1 != 0 {
        // DUP (element), scalar
        set_vreg(d, elem(vreg(n), index, esize) as u128);
        return Flow::Next;
    }
    if word >> 29 & 1 != 0 {
        // INS (element)
        let source = imm4 >> size;
        set_vreg(
            d,
            with_elem(vreg(d), index, esize, elem(vreg(n), source, esize)),
        );
        return Flow::Next;
    }
    match imm4 {
        0b0000 | 0b0001 => {
            let value = if imm4 == 0 { elem(vreg(n), index, esize) } else { xr(n) & ones(esize) };
            let mut result = 0u128;
            for e in 0..datasize(word) / esize {
                result = with_elem(result, e, esize, value);
            }
            set_vreg(d, result);
        },
        0b0011 => set_vreg(d, with_elem(vreg(d), index, esize, xr(n))),
        0b0101 => {
            let value = sext(elem(vreg(n), index, esize), esize) as u64;
            cpu::set_x(d, if q { value } else { value & 0xFFFF_FFFF });
        },
        _ => cpu::set_x(d, elem(vreg(n), index, esize)),
    }
    Flow::Next
}

/// AdvSIMDExpandImm
pub fn expand_imm(op: u32, cmode: u32, imm8: u64) -> u64 {
    let replicate = |value: u64, esize: u32| {
        let mut result = 0;
        let mut at = 0;
        while at < 64 {
            result |= value << at;
            at += esize;
        }
        result
    };
    match cmode >> 1 {
        0..=3 => replicate(imm8 << (8 * (cmode >> 1)), 32),
        4 | 5 => replicate(imm8 << (8 * (cmode >> 1 & 1)), 16),
        6 => {
            let value = if cmode & 1 == 0 { imm8 << 8 | 0xFF } else { imm8 << 16 | 0xFFFF };
            replicate(value, 32)
        },
        _ => match (cmode & 1, op) {
            (0, 0) => replicate(imm8, 8),
            (0, _) => {
                let mut result = 0;
                for i in 0..8 {
                    if imm8 >> i & 1 != 0 {
                        result |= 0xFF << (8 * i);
                    }
                }
                result
            },
            (_, 0) => {
                // FMOV (vector, immediate), single precision
                let imm32 = fp::expand_imm(imm8 as u32, 32);
                replicate(imm32, 32)
            },
            _ => fp::expand_imm(imm8 as u32, 64),
        },
    }
}

/// AdvSIMD modified immediate
pub fn modified_immediate(word: u32) -> Flow {
    let d = word & 31;
    let q = word >> 30 & 1 != 0;
    let op = word >> 29 & 1;
    let cmode = bits(word, 15, 12);
    let imm8 = (bits(word, 18, 16) << 5 | bits(word, 9, 5)) as u64;
    let imm64 = expand_imm(op, cmode, imm8);
    let imm = if q { imm64 as u128 | (imm64 as u128) << 64 } else { imm64 as u128 };
    let keep = if q { u128::MAX } else { u64::MAX as u128 };
    // ORR and BIC: cmode 0xx1, 10x1 (not 11xx)
    let orr_bic = cmode < 0b1100 && cmode & 1 == 1;
    let result = match (orr_bic, op) {
        (true, 0) => vreg(d) | imm,
        (true, _) => vreg(d) & !imm,
        // MOVI; MVNI (op 1) except the 64-bit MOVI and FMOV double (cmode 111x)
        (false, 1) if cmode < 0b1110 => !imm,
        _ => imm,
    };
    set_vreg(d, result & keep);
    Flow::Next
}

/// AdvSIMD shift by immediate (vector and scalar), integer
pub fn shift_immediate(word: u32) -> Flow {
    let opcode = bits(word, 15, 11);
    if opcode == 0b11100 || opcode == 0b11111 {
        return crate::aarch64::simd_fp::fixed_point(word);
    }
    let (d, n, _) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let immh = bits(word, 22, 19);
    let immhb = bits(word, 22, 16);
    let esize = 8 << (31 - immh.leading_zeros());
    let (a, c) = (vreg(n), vreg(d));
    let mut qc = false;
    let narrow = (0b10000..=0b10011).contains(&opcode);
    if narrow {
        // SHRN, RSHRN, SQ(R)SHRN, UQ(R)SHRN, SQ(R)SHRUN: the source elements are 2 * esize
        let shift = 2 * esize - immhb;
        let round_const = if opcode & 1 != 0 { 1i128 << (shift - 1) } else { 0 };
        let count = if scalar { 1 } else { 64 / esize };
        let mut result = 0u64;
        for e in 0..count {
            let x = elem(a, e, 2 * esize);
            let source_unsigned = u == 1 && opcode >= 0b10010;
            let shifted = (int(x, 2 * esize, source_unsigned) + round_const) >> shift;
            let r = match u {
                // SHRN, RSHRN; SQSHRN, SQRSHRN
                0 if opcode < 0b10010 => shifted as u64 & ones(esize),
                0 => sat(shifted, esize, false, &mut qc),
                // SQSHRUN, SQRSHRUN, UQSHRN, UQRSHRN
                _ => sat(shifted, esize, true, &mut qc),
            };
            result |= r << (e * esize);
        }
        if scalar {
            set_vreg(d, result as u128);
        }
        else {
            write_narrow(d, word, result);
        }
        if qc {
            set_qc();
        }
        return Flow::Next;
    }
    if opcode == 0b10100 {
        // SSHLL, USHLL
        let shift = immhb - esize;
        let x = half(a, word) as u128;
        let mut result = 0u128;
        for e in 0..64 / esize {
            let value = int(elem(x, e, esize), esize, unsigned) << shift;
            result = with_elem(result, e, 2 * esize, value as u64);
        }
        set_vreg(d, result);
        return Flow::Next;
    }
    let width = if scalar { esize } else { datasize(word) };
    let left = immhb - esize;
    let right = 2 * esize - immhb;
    let mut result = 0u128;
    for e in 0..width / esize {
        let x = elem(a, e, esize);
        let z = elem(c, e, esize);
        let value = int(x, esize, unsigned);
        let r = match (u, opcode) {
            (_, 0b00000) | (_, 0b00010) | (_, 0b00100) | (_, 0b00110) => {
                let round = opcode & 0b00100 != 0;
                let shifted = shift_by(
                    value,
                    -(right as i64),
                    esize,
                    unsigned,
                    round,
                    false,
                    &mut qc,
                );
                if opcode & 0b00010 != 0 {
                    z.wrapping_add(shifted)
                }
                else {
                    shifted
                }
            },
            (0, 0b01010) => x << left,
            (1, 0b01000) => {
                // SRI: the top `right` bits of the destination stay
                let mask = if right == esize { 0 } else { ones(esize) >> right };
                (z & !mask) | (if right == esize { 0 } else { x >> right })
            },
            (1, 0b01010) => {
                // SLI
                let mask = ones(esize) << left;
                (z & !mask) | (x << left)
            },
            (0, 0b01110) => shift_by(
                sext(x, esize) as i128,
                left as i64,
                esize,
                false,
                false,
                true,
                &mut qc,
            ),
            (1, 0b01110) => shift_by(x as i128, left as i64, esize, true, false, true, &mut qc),
            // SQSHLU: a signed value, saturated as unsigned
            _ => shift_by(
                sext(x, esize) as i128,
                left as i64,
                esize,
                true,
                false,
                true,
                &mut qc,
            ),
        };
        result = with_elem(result, e, esize, r);
    }
    set_vreg(d, result);
    if qc {
        set_qc();
    }
    Flow::Next
}

/// The element operand of a by-element instruction: (Rm, index) for an esize
pub fn indexed_operand(word: u32, esize: u32) -> (u32, u32) {
    let h = word >> 11 & 1;
    let l = word >> 21 & 1;
    let m = word >> 20 & 1;
    let rm = bits(word, 19, 16);
    match esize {
        16 => (rm, h << 2 | l << 1 | m),
        32 => (m << 4 | rm, h << 1 | l),
        _ => (m << 4 | rm, h),
    }
}

/// AdvSIMD (vector and scalar) x indexed element, integer
pub fn indexed(word: u32) -> Flow {
    let opcode = bits(word, 15, 12);
    if matches!(opcode, 0b0001 | 0b0101 | 0b1001) {
        return crate::aarch64::simd_fp::indexed(word);
    }
    let (d, n, _) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let unsigned = u == 1;
    let size = bits(word, 23, 22);
    let esize = 8 << size;
    let (m, index) = indexed_operand(word, esize);
    let y = elem(vreg(m), index, esize);
    let (a, c) = (vreg(n), vreg(d));
    let mut qc = false;
    let long = matches!(opcode, 0b0010 | 0b0011 | 0b0110 | 0b0111 | 0b1010 | 0b1011);
    let mut result = 0u128;
    if long {
        let x_half = if scalar { a & ones(esize) as u128 } else { half(a, word) as u128 };
        let count = if scalar { 1 } else { 64 / esize };
        let w = 2 * esize;
        for e in 0..count {
            let x = int(elem(x_half, e, esize), esize, unsigned);
            let yv = int(y, esize, unsigned);
            let acc = int(elem(c, e, w), w, unsigned);
            let r = match (u, opcode) {
                (_, 0b0010) => (acc + x * yv) as u64,
                (_, 0b0110) => (acc - x * yv) as u64,
                (_, 0b1010) => (x * yv) as u64,
                _ => {
                    let product = sext(sat(2 * x * yv, w, false, &mut qc), w) as i128;
                    match opcode {
                        0b0011 => sat(acc + product, w, false, &mut qc),
                        0b0111 => sat(acc - product, w, false, &mut qc),
                        _ => product as u64,
                    }
                },
            };
            result = with_elem(result, e, w, r);
        }
    }
    else {
        let width = if scalar { esize } else { datasize(word) };
        for e in 0..width / esize {
            let x = elem(a, e, esize);
            let z = elem(c, e, esize);
            let r = match (u, opcode) {
                (0, 0b1000) => x.wrapping_mul(y),
                (1, 0b0000) => z.wrapping_add(x.wrapping_mul(y)),
                (1, 0b0100) => z.wrapping_sub(x.wrapping_mul(y)),
                _ => {
                    // SQDMULH, SQRDMULH
                    let (sx, sy) = (sext(x, esize) as i128, sext(y, esize) as i128);
                    let round = if opcode == 0b1101 { 1i128 << (esize - 1) } else { 0 };
                    sat((2 * sx * sy + round) >> esize, esize, false, &mut qc)
                },
            };
            result = with_elem(result, e, esize, r);
        }
    }
    set_vreg(d, result);
    if qc {
        set_qc();
    }
    Flow::Next
}

/// TBL, TBX
pub fn table(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let len = bits(word, 14, 13) + 1;
    let tbx = word >> 12 & 1 != 0;
    let bytes = datasize(word) / 8;
    let indices = vreg(m);
    let original = vreg(d);
    let mut result = 0u128;
    for i in 0..bytes {
        let index = elem(indices, i, 8) as u32;
        let byte = if index < 16 * len {
            elem(vreg((n + index / 16) % 32), index % 16, 8)
        }
        else if tbx {
            elem(original, i, 8)
        }
        else {
            0
        };
        result = with_elem(result, i, 8, byte);
    }
    set_vreg(d, result);
    Flow::Next
}

/// UZP1/2, TRN1/2, ZIP1/2
pub fn permute(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let esize = 8 << bits(word, 23, 22);
    let elements = datasize(word) / esize;
    let part = word >> 14 & 1;
    let (a, b) = (vreg(n), vreg(m));
    let mut result = 0u128;
    let pairs = elements / 2;
    match bits(word, 13, 12) {
        0b01 => {
            // UZP: the even (or odd) elements of m:n
            for e in 0..elements {
                let i = 2 * e + part;
                let value =
                    if i < elements { elem(a, i, esize) } else { elem(b, i - elements, esize) };
                result = with_elem(result, e, esize, value);
            }
        },
        0b10 => {
            for p in 0..pairs {
                result = with_elem(result, 2 * p, esize, elem(a, 2 * p + part, esize));
                result = with_elem(result, 2 * p + 1, esize, elem(b, 2 * p + part, esize));
            }
        },
        _ => {
            let base = part * pairs;
            for p in 0..pairs {
                result = with_elem(result, 2 * p, esize, elem(a, base + p, esize));
                result = with_elem(result, 2 * p + 1, esize, elem(b, base + p, esize));
            }
        },
    }
    set_vreg(d, result);
    Flow::Next
}

/// EXT
pub fn extract(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let position = bits(word, 14, 11) * 8;
    let width = datasize(word);
    let (a, b) = (vreg(n), vreg(m));
    let (low, high) = if width == 128 { (a, b) } else { (a & u64::MAX as u128 | b << 64, 0) };
    // (the 256-bit m:n, shifted right by position bits)
    let result = if position == 0 { low } else { low >> position | high << (128 - position) };
    let keep = if width == 128 { u128::MAX } else { u64::MAX as u128 };
    set_vreg(d, result & keep);
    Flow::Next
}

// ---- loads and stores

fn alignment_fault(va: u64, write: bool) -> Exception {
    Exception::DataAbort {
        iss: cpu::FSC_ALIGNMENT | (write as u32) << 6,
        far: va,
    }
}

/// Whether a 16-byte access must be aligned to 16 bytes: SCTLR_EL1.A (on
/// Device memory the two 8-byte halves need 8, as QEMU checks the pair)
#[inline(always)]
fn strict_alignment() -> bool { cpu::sctlr() & cpu::SCTLR_A != 0 }

/// Read `size` bytes (1-16) of a SIMD&FP register's load
pub fn read_vector(va: u64, size: u32) -> Result<u128, Exception> {
    if size <= 8 {
        return memory::read(va, size, false, Syndrome::NONE).map(|value| value as u128);
    }
    if strict_alignment() && va & 15 != 0 {
        return Err(alignment_fault(va, false));
    }
    let low = memory::read(va, 8, false, Syndrome::NONE)?;
    let high = memory::read(va.wrapping_add(8), 8, false, Syndrome::NONE)?;
    Ok(low as u128 | (high as u128) << 64)
}

/// A SIMD&FP store of 1-16 bytes, translated and checked (written by `commit`)
pub struct VectorStore {
    low: memory::Store,
    high: Option<memory::Store>,
}

pub fn prepare_vector_write(va: u64, size: u32) -> Result<VectorStore, Exception> {
    if size <= 8 {
        return Ok(VectorStore {
            low: memory::prepare_write(va, size, false, Syndrome::NONE)?,
            high: None,
        });
    }
    if strict_alignment() && va & 15 != 0 {
        return Err(alignment_fault(va, true));
    }
    Ok(VectorStore {
        low: memory::prepare_write(va, 8, false, Syndrome::NONE)?,
        high: Some(memory::prepare_write(
            va.wrapping_add(8),
            8,
            false,
            Syndrome::NONE,
        )?),
    })
}

impl VectorStore {
    pub fn commit(self, value: u128) -> Result<(), Exception> {
        self.low.commit(value as u64)?;
        if let Some(high) = self.high {
            high.commit((value >> 64) as u64)?;
        }
        Ok(())
    }
}

/// LD1-LD4, ST1-ST4, LD1R-LD4R
pub fn structure(word: u32) -> Result<Flow, Exception> {
    fp::check_access()?;
    let s = match simd_decode::structure(word) {
        Some(s) => s,
        None => return Err(Exception::Undefined),
    };
    let t = word & 31;
    let rn = word >> 5 & 31;
    let rm = word >> 16 & 31;
    let post = word >> 23 & 1 != 0;
    let q = word >> 30 & 1;
    let base = xr_sp(rn);
    crate::aarch64::execute::check_sp(rn, base)?;
    let esize = 8 << s.size_log;
    let ebytes = 1u64 << s.size_log;
    let (registers, mut values) = (s.registers, [0u128; 4]);
    for r in 0..registers {
        values[r as usize] = vreg((t + r) % 32);
    }
    let total;
    if let Some(index) = s.index {
        // a single structure: one element of each register
        total = ebytes * registers as u64;
        if s.load {
            let mut loaded = [0u64; 4];
            for r in 0..registers as usize {
                loaded[r] = memory::read(
                    base.wrapping_add(r as u64 * ebytes),
                    ebytes as u32,
                    false,
                    Syndrome::NONE,
                )?;
            }
            for r in 0..registers as usize {
                values[r] = with_elem(values[r], index, esize, loaded[r]);
            }
        }
        else {
            let mut stores = [None; 4];
            for r in 0..registers as usize {
                stores[r] = Some(memory::prepare_write(
                    base.wrapping_add(r as u64 * ebytes),
                    ebytes as u32,
                    false,
                    Syndrome::NONE,
                )?);
            }
            for r in 0..registers as usize {
                stores[r].unwrap().commit(elem(values[r], index, esize))?;
            }
        }
    }
    else if s.replicate {
        total = ebytes * registers as u64;
        let mut loaded = [0u64; 4];
        for r in 0..registers as usize {
            loaded[r] = memory::read(
                base.wrapping_add(r as u64 * ebytes),
                ebytes as u32,
                false,
                Syndrome::NONE,
            )?;
        }
        let elements = (64 << q) / esize;
        for r in 0..registers as usize {
            let mut value = 0u128;
            for e in 0..elements {
                value = with_elem(value, e, esize, loaded[r]);
            }
            values[r] = value;
        }
    }
    else {
        // multiple structures: element e of register r at (e * selem + r) (interleaved) or r * elements + e
        let elements = (64 << q) / esize;
        let selem = s.interleave;
        let rpt = registers / selem;
        total = ebytes * (elements * registers) as u64;
        let mut stores: [Option<memory::Store>; 64] = [None; 64];
        let mut count = 0;
        let mut loaded = [[0u64; 16]; 4];
        let mut address = base;
        for rep in 0..rpt {
            for e in 0..elements {
                for sr in 0..selem {
                    let r = (rep * selem + sr) as usize;
                    if s.load {
                        loaded[r][e as usize] =
                            memory::read(address, ebytes as u32, false, Syndrome::NONE)?;
                    }
                    else {
                        stores[count] = Some(memory::prepare_write(
                            address,
                            ebytes as u32,
                            false,
                            Syndrome::NONE,
                        )?);
                        count += 1;
                    }
                    address = address.wrapping_add(ebytes);
                }
            }
        }
        if s.load {
            for r in 0..registers as usize {
                let mut value = 0u128;
                for e in 0..elements {
                    value = with_elem(value, e, esize, loaded[r][e as usize]);
                }
                values[r] = value;
            }
        }
        else {
            let mut i = 0;
            for rep in 0..rpt {
                for e in 0..elements {
                    for sr in 0..selem {
                        let r = (rep * selem + sr) as usize;
                        stores[i].unwrap().commit(elem(values[r], e, esize))?;
                        i += 1;
                    }
                }
            }
        }
    }
    if s.load {
        let keep = if q == 1 || s.index.is_some() { u128::MAX } else { u64::MAX as u128 };
        for r in 0..registers {
            set_vreg((t + r) % 32, values[r as usize] & keep);
        }
    }
    if post {
        let offset = if rm == 31 { total } else { xr(rm) };
        cpu::set_x_sp(rn, base.wrapping_add(offset));
    }
    Ok(Flow::Next)
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/rust/aarch64/simd_decode.rs                                                          0000644 0000000 0000000 00000104366 00000000000 015517  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The scalar FP, AdvSIMD and crypto part of the A64 decoder
//! (docs/arm64-virt-android16-plan.md P2.5-P2.8, P2.11): the classes of the
//! encoding index's "Data Processing -- Scalar Floating-Point and Advanced
//! SIMD" group and the AdvSIMD structure loads and stores. Each class
//! function checks a word against the class's allocated encodings for profile
//! v86-aarch64-v1 (v8.0 with FP, AdvSIMD, AES, PMULL, SHA1, SHA256; no FP16,
//! RDM, DotProd, FCMA, JSCVT, FRINTTS, SHA512, SHA3, SM3/SM4) and names
//! the instruction; the interpreter (simd.rs, fpu.rs) reads the operands
//! from the word again. A name ends in "2" for the second-half forms (Q = 1)
//! of the long, wide and narrow instructions, as llvm-mc prints them.

use crate::aarch64::decode::{bits, Inst, Op};

macro_rules! q2 {
    ($q:expr, $name:literal) => {
        if $q {
            concat!($name, "2")
        }
        else {
            $name
        }
    };
}

/// A word of the FP/SIMD data processing group (bits 28:25 = x111)
pub fn data_processing(word: u32) -> Inst {
    match classify(word) {
        Some((op, _)) => {
            let mut i = Inst::new(op, word);
            i.imm = word as u64;
            i
        },
        None => Inst::UNDEF,
    }
}

/// The class and name of a FP/SIMD data processing word
pub fn classify(word: u32) -> Option<(Op, &'static str)> {
    let m = |mask: u32, value: u32| word & mask == value;
    let r = |op: Op, name: Option<&'static str>| name.map(|n| (op, n));
    if word >> 28 & 1 == 0 {
        // vector AdvSIMD (0 Q U 0111x ...)
        if word >> 31 != 0 {
            return None;
        }
        if m(0xFF3E_0C00, 0x4E28_0800) {
            return r(Op::CryptoAes, aes(word));
        }
        if m(0xBF20_8C00, 0x0E00_0000) {
            return r(Op::SimdTable, table(word));
        }
        if m(0xBF20_8C00, 0x0E00_0800) {
            return r(Op::SimdPermute, permute(word));
        }
        if m(0xBF20_8400, 0x2E00_0000) {
            return r(Op::SimdExtract, extract(word));
        }
        if m(0x9FE0_8400, 0x0E00_0400) {
            return r(Op::SimdCopy, copy(word));
        }
        if m(0x9F20_0400, 0x0E20_0400) {
            return r(Op::SimdThreeSame, three_same(word));
        }
        if m(0x9F20_0C00, 0x0E20_0000) {
            return r(Op::SimdThreeDiff, three_different(word));
        }
        if m(0x9F3E_0C00, 0x0E20_0800) {
            return r(Op::SimdTwoMisc, two_misc(word));
        }
        if m(0x9F3E_0C00, 0x0E30_0800) {
            return r(Op::SimdAcross, across(word));
        }
        if m(0x9FF8_0400, 0x0F00_0400) {
            return r(Op::SimdModImm, modified_immediate(word));
        }
        if m(0x9F80_0400, 0x0F00_0400) {
            return r(Op::SimdShiftImm, shift_immediate(word));
        }
        if m(0x9F00_0400, 0x0F00_0000) {
            return r(Op::SimdIndexed, indexed(word));
        }
        return None;
    }
    if word >> 30 & 1 != 0 {
        // scalar AdvSIMD (01 U 1111x ...)
        if word >> 31 != 0 {
            return None;
        }
        if m(0xFF20_8C00, 0x5E00_0000) {
            return r(Op::CryptoSha3, sha3(word));
        }
        if m(0xFF3E_0C00, 0x5E28_0800) {
            return r(Op::CryptoSha2, sha2(word));
        }
        if m(0xDFE0_8400, 0x5E00_0400) {
            return r(Op::SimdCopy, scalar_copy(word));
        }
        if m(0xDF20_0400, 0x5E20_0400) {
            return r(Op::SimdThreeSame, scalar_three_same(word));
        }
        if m(0xDF20_0C00, 0x5E20_0000) {
            return r(Op::SimdThreeDiff, scalar_three_different(word));
        }
        if m(0xDF3E_0C00, 0x5E20_0800) {
            return r(Op::SimdTwoMisc, scalar_two_misc(word));
        }
        if m(0xDF3E_0C00, 0x5E30_0800) {
            return r(Op::SimdPairwise, scalar_pairwise(word));
        }
        if m(0xDF80_0400, 0x5F00_0400) {
            return r(Op::SimdShiftImm, scalar_shift_immediate(word));
        }
        if m(0xDF00_0400, 0x5F00_0000) {
            return r(Op::SimdIndexed, scalar_indexed(word));
        }
        return None;
    }
    // scalar FP and the conversions (M/sf 0 S 1111x)
    if m(0x5F20_0000, 0x1E00_0000) {
        return r(Op::FpFixed, fp_fixed(word));
    }
    if m(0x5F20_FC00, 0x1E20_0000) {
        return r(Op::FpInt, fp_int(word));
    }
    if m(0x5F00_0000, 0x1F00_0000) {
        return r(Op::FpDp3, fp_dp3(word));
    }
    // (the rest need M = 0, S = 0 and a single or double type: FP16 is not in v1)
    if word >> 31 != 0 || word >> 29 & 1 != 0 {
        return None;
    }
    let ty = bits(word, 23, 22);
    if m(0x5F20_7C00, 0x1E20_4000) {
        return r(Op::FpDp1, fp_dp1(word));
    }
    if ty >= 2 {
        return None;
    }
    if m(0x5F20_3C00, 0x1E20_2000) {
        let name = match (bits(word, 15, 14), bits(word, 4, 0)) {
            // (the zero forms ignore Rm, a should-be-zero field, as QEMU does)
            (0, 0b00000) | (0, 0b01000) => "fcmp",
            (0, 0b10000) | (0, 0b11000) => "fcmpe",
            _ => return None,
        };
        return Some((Op::FpCompare, name));
    }
    if m(0x5F20_1C00, 0x1E20_1000) {
        return if bits(word, 9, 5) == 0 { Some((Op::FpImm, "fmov")) } else { None };
    }
    if m(0x5F20_0C00, 0x1E20_0400) {
        return Some((
            Op::FpCondCompare,
            if word >> 4 & 1 == 0 { "fccmp" } else { "fccmpe" },
        ));
    }
    if m(0x5F20_0C00, 0x1E20_0800) {
        let name = match bits(word, 15, 12) {
            0b0000 => "fmul",
            0b0001 => "fdiv",
            0b0010 => "fadd",
            0b0011 => "fsub",
            0b0100 => "fmax",
            0b0101 => "fmin",
            0b0110 => "fmaxnm",
            0b0111 => "fminnm",
            0b1000 => "fnmul",
            _ => return None,
        };
        return Some((Op::FpDp2, name));
    }
    if m(0x5F20_0C00, 0x1E20_0C00) {
        return Some((Op::FpCondSelect, "fcsel"));
    }
    None
}

// ---- AdvSIMD, vector

fn three_same(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 15, 11);
    if opcode >= 0b11000 {
        let a = size >> 1;
        if size & 1 == 1 && !q {
            return None;
        }
        return Some(match (u, a, opcode) {
            (0, 0, 0b11000) => "fmaxnm",
            (0, 0, 0b11001) => "fmla",
            (0, 0, 0b11010) => "fadd",
            (0, 0, 0b11011) => "fmulx",
            (0, 0, 0b11100) => "fcmeq",
            (0, 0, 0b11110) => "fmax",
            (0, 0, 0b11111) => "frecps",
            (0, 1, 0b11000) => "fminnm",
            (0, 1, 0b11001) => "fmls",
            (0, 1, 0b11010) => "fsub",
            (0, 1, 0b11110) => "fmin",
            (0, 1, 0b11111) => "frsqrts",
            (1, 0, 0b11000) => "fmaxnmp",
            (1, 0, 0b11010) => "faddp",
            (1, 0, 0b11011) => "fmul",
            (1, 0, 0b11100) => "fcmge",
            (1, 0, 0b11101) => "facge",
            (1, 0, 0b11110) => "fmaxp",
            (1, 0, 0b11111) => "fdiv",
            (1, 1, 0b11000) => "fminnmp",
            (1, 1, 0b11010) => "fabd",
            (1, 1, 0b11100) => "fcmgt",
            (1, 1, 0b11101) => "facgt",
            (1, 1, 0b11110) => "fminp",
            _ => return None,
        });
    }
    if opcode == 0b00011 {
        return Some(
            ["and", "bic", "orr", "orn", "eor", "bsl", "bit", "bif"][(u << 2 | size) as usize],
        );
    }
    // (the rule on the element size: not 64-bit, 64-bit only as 2D, only H and S, only B)
    enum Sizes {
        No64,
        Q64,
        HS,
        B,
    }
    use Sizes::*;
    let (name, sizes) = match (u, opcode) {
        (0, 0b00000) => ("shadd", No64),
        (0, 0b00001) => ("sqadd", Q64),
        (0, 0b00010) => ("srhadd", No64),
        (0, 0b00100) => ("shsub", No64),
        (0, 0b00101) => ("sqsub", Q64),
        (0, 0b00110) => ("cmgt", Q64),
        (0, 0b00111) => ("cmge", Q64),
        (0, 0b01000) => ("sshl", Q64),
        (0, 0b01001) => ("sqshl", Q64),
        (0, 0b01010) => ("srshl", Q64),
        (0, 0b01011) => ("sqrshl", Q64),
        (0, 0b01100) => ("smax", No64),
        (0, 0b01101) => ("smin", No64),
        (0, 0b01110) => ("sabd", No64),
        (0, 0b01111) => ("saba", No64),
        (0, 0b10000) => ("add", Q64),
        (0, 0b10001) => ("cmtst", Q64),
        (0, 0b10010) => ("mla", No64),
        (0, 0b10011) => ("mul", No64),
        (0, 0b10100) => ("smaxp", No64),
        (0, 0b10101) => ("sminp", No64),
        (0, 0b10110) => ("sqdmulh", HS),
        (0, 0b10111) => ("addp", Q64),
        (1, 0b00000) => ("uhadd", No64),
        (1, 0b00001) => ("uqadd", Q64),
        (1, 0b00010) => ("urhadd", No64),
        (1, 0b00100) => ("uhsub", No64),
        (1, 0b00101) => ("uqsub", Q64),
        (1, 0b00110) => ("cmhi", Q64),
        (1, 0b00111) => ("cmhs", Q64),
        (1, 0b01000) => ("ushl", Q64),
        (1, 0b01001) => ("uqshl", Q64),
        (1, 0b01010) => ("urshl", Q64),
        (1, 0b01011) => ("uqrshl", Q64),
        (1, 0b01100) => ("umax", No64),
        (1, 0b01101) => ("umin", No64),
        (1, 0b01110) => ("uabd", No64),
        (1, 0b01111) => ("uaba", No64),
        (1, 0b10000) => ("sub", Q64),
        (1, 0b10001) => ("cmeq", Q64),
        (1, 0b10010) => ("mls", No64),
        (1, 0b10011) => ("pmul", B),
        (1, 0b10100) => ("umaxp", No64),
        (1, 0b10101) => ("uminp", No64),
        (1, 0b10110) => ("sqrdmulh", HS),
        _ => return None,
    };
    let valid = match sizes {
        No64 => size != 3,
        Q64 => size != 3 || q,
        HS => size == 1 || size == 2,
        B => size == 0,
    };
    if valid {
        Some(name)
    }
    else {
        None
    }
}

fn three_different(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 15, 12);
    let name = match (u, opcode) {
        (0, 0b0000) => q2!(q, "saddl"),
        (0, 0b0001) => q2!(q, "saddw"),
        (0, 0b0010) => q2!(q, "ssubl"),
        (0, 0b0011) => q2!(q, "ssubw"),
        (0, 0b0100) => q2!(q, "addhn"),
        (0, 0b0101) => q2!(q, "sabal"),
        (0, 0b0110) => q2!(q, "subhn"),
        (0, 0b0111) => q2!(q, "sabdl"),
        (0, 0b1000) => q2!(q, "smlal"),
        (0, 0b1001) => q2!(q, "sqdmlal"),
        (0, 0b1010) => q2!(q, "smlsl"),
        (0, 0b1011) => q2!(q, "sqdmlsl"),
        (0, 0b1100) => q2!(q, "smull"),
        (0, 0b1101) => q2!(q, "sqdmull"),
        (0, 0b1110) => q2!(q, "pmull"),
        (1, 0b0000) => q2!(q, "uaddl"),
        (1, 0b0001) => q2!(q, "uaddw"),
        (1, 0b0010) => q2!(q, "usubl"),
        (1, 0b0011) => q2!(q, "usubw"),
        (1, 0b0100) => q2!(q, "raddhn"),
        (1, 0b0101) => q2!(q, "uabal"),
        (1, 0b0110) => q2!(q, "rsubhn"),
        (1, 0b0111) => q2!(q, "uabdl"),
        (1, 0b1000) => q2!(q, "umlal"),
        (1, 0b1010) => q2!(q, "umlsl"),
        (1, 0b1100) => q2!(q, "umull"),
        _ => return None,
    };
    let valid = match (u, opcode) {
        (0, 0b1001) | (0, 0b1011) | (0, 0b1101) => size == 1 || size == 2,
        // PMULL: 8-bit, and the 64-bit form (FEAT_PMULL)
        (0, 0b1110) => size == 0 || size == 3,
        _ => size != 3,
    };
    if valid {
        Some(name)
    }
    else {
        None
    }
}

fn two_misc(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    let (a, sz) = (size >> 1, size & 1);
    // FP: the double-precision vector forms are 2D only
    let fp = |name: &'static str| if sz == 1 && !q { None } else { Some(name) };
    match (u, opcode) {
        (0, 0b00000) => (size != 3).then_some("rev64"),
        (0, 0b00001) => (size == 0).then_some("rev16"),
        (0, 0b00010) => (size != 3).then_some("saddlp"),
        (0, 0b00011) => (size != 3 || q).then_some("suqadd"),
        (0, 0b00100) => (size != 3).then_some("cls"),
        (0, 0b00101) => (size == 0).then_some("cnt"),
        (0, 0b00110) => (size != 3).then_some("sadalp"),
        (0, 0b00111) => (size != 3 || q).then_some("sqabs"),
        (0, 0b01000) => (size != 3 || q).then_some("cmgt"),
        (0, 0b01001) => (size != 3 || q).then_some("cmeq"),
        (0, 0b01010) => (size != 3 || q).then_some("cmlt"),
        (0, 0b01011) => (size != 3 || q).then_some("abs"),
        (0, 0b10010) => (size != 3).then_some(q2!(q, "xtn")),
        (0, 0b10100) => (size != 3).then_some(q2!(q, "sqxtn")),
        (1, 0b00000) => (size < 2).then_some("rev32"),
        (1, 0b00010) => (size != 3).then_some("uaddlp"),
        (1, 0b00011) => (size != 3 || q).then_some("usqadd"),
        (1, 0b00100) => (size != 3).then_some("clz"),
        (1, 0b00101) => match size {
            0 => Some("not"),
            1 => Some("rbit"),
            _ => None,
        },
        (1, 0b00110) => (size != 3).then_some("uadalp"),
        (1, 0b00111) => (size != 3 || q).then_some("sqneg"),
        (1, 0b01000) => (size != 3 || q).then_some("cmge"),
        (1, 0b01001) => (size != 3 || q).then_some("cmle"),
        (1, 0b01011) => (size != 3 || q).then_some("neg"),
        (1, 0b10010) => (size != 3).then_some(q2!(q, "sqxtun")),
        (1, 0b10011) => (size != 3).then_some(q2!(q, "shll")),
        (1, 0b10100) => (size != 3).then_some(q2!(q, "uqxtn")),
        _ => match (u, a, opcode) {
            (0, 0, 0b10110) => Some(q2!(q, "fcvtn")),
            (0, 0, 0b10111) => Some(q2!(q, "fcvtl")),
            (0, 0, 0b11000) => fp("frintn"),
            (0, 0, 0b11001) => fp("frintm"),
            (0, 0, 0b11010) => fp("fcvtns"),
            (0, 0, 0b11011) => fp("fcvtms"),
            (0, 0, 0b11100) => fp("fcvtas"),
            (0, 0, 0b11101) => fp("scvtf"),
            (0, 1, 0b01100) => fp("fcmgt"),
            (0, 1, 0b01101) => fp("fcmeq"),
            (0, 1, 0b01110) => fp("fcmlt"),
            (0, 1, 0b01111) => fp("fabs"),
            (0, 1, 0b11000) => fp("frintp"),
            (0, 1, 0b11001) => fp("frintz"),
            (0, 1, 0b11010) => fp("fcvtps"),
            (0, 1, 0b11011) => fp("fcvtzs"),
            (0, 1, 0b11100) => (sz == 0).then_some("urecpe"),
            (0, 1, 0b11101) => fp("frecpe"),
            (1, 0, 0b10110) => (sz == 1).then_some(q2!(q, "fcvtxn")),
            (1, 0, 0b11000) => fp("frinta"),
            (1, 0, 0b11001) => fp("frintx"),
            (1, 0, 0b11010) => fp("fcvtnu"),
            (1, 0, 0b11011) => fp("fcvtmu"),
            (1, 0, 0b11100) => fp("fcvtau"),
            (1, 0, 0b11101) => fp("ucvtf"),
            (1, 1, 0b01100) => fp("fcmge"),
            (1, 1, 0b01101) => fp("fcmle"),
            (1, 1, 0b01111) => fp("fneg"),
            (1, 1, 0b11001) => fp("frinti"),
            (1, 1, 0b11010) => fp("fcvtpu"),
            (1, 1, 0b11011) => fp("fcvtzu"),
            (1, 1, 0b11100) => (sz == 0).then_some("ursqrte"),
            (1, 1, 0b11101) => fp("frsqrte"),
            (1, 1, 0b11111) => fp("fsqrt"),
            _ => None,
        },
    }
}

fn across(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    let integer = size != 3 && (size != 2 || q);
    match (u, opcode) {
        (0, 0b00011) => integer.then_some("saddlv"),
        (0, 0b01010) => integer.then_some("smaxv"),
        (0, 0b11010) => integer.then_some("sminv"),
        (0, 0b11011) => integer.then_some("addv"),
        (1, 0b00011) => integer.then_some("uaddlv"),
        (1, 0b01010) => integer.then_some("umaxv"),
        (1, 0b11010) => integer.then_some("uminv"),
        // FP: 4S only
        (1, 0b01100) if size & 1 == 0 && q => {
            Some(if size >> 1 == 0 { "fmaxnmv" } else { "fminnmv" })
        },
        (1, 0b01111) if size & 1 == 0 && q => Some(if size >> 1 == 0 { "fmaxv" } else { "fminv" }),
        _ => None,
    }
}

fn copy(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let op = word >> 29 & 1;
    let imm5 = bits(word, 20, 16);
    let imm4 = bits(word, 14, 11);
    if imm5 & 0xF == 0 {
        return None;
    }
    let size = imm5.trailing_zeros();
    if op == 1 {
        return q.then_some("ins");
    }
    match imm4 {
        0b0000 => (size != 3 || q).then_some("dup"),
        0b0001 => (size != 3 || q).then_some("dup"),
        0b0011 => q.then_some("ins"),
        0b0101 => (size < 2 || q && size == 2).then_some("smov"),
        0b0111 => (if q { size == 3 } else { size < 3 }).then_some("umov"),
        _ => None,
    }
}

fn modified_immediate(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let op = word >> 29 & 1;
    let cmode = bits(word, 15, 12);
    if word >> 11 & 1 != 0 {
        // (o2: FMOV half precision, FEAT_FP16)
        return None;
    }
    Some(match (op, cmode) {
        (0, 0b1111) => "fmov",
        (1, 0b1111) => return q.then_some("fmov"),
        (1, 0b1110) => "movi",
        (0, _) if cmode & 0b1001 == 0b0001 || cmode & 0b1101 == 0b1001 => "orr",
        (1, _) if cmode & 0b1001 == 0b0001 || cmode & 0b1101 == 0b1001 => "bic",
        (0, _) => "movi",
        _ => "mvni",
    })
}

fn shift_immediate(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let immh = bits(word, 22, 19);
    let opcode = bits(word, 15, 11);
    let wide = immh >> 3 == 0 || q; // (64-bit elements only as 2D)
    let narrow = immh >> 3 == 0; // (no 64-bit narrow or long element)
    let fixed = immh >= 0b0100 && wide; // (single or double: FP16 is not in v1)
    match (u, opcode) {
        (0, 0b00000) => wide.then_some("sshr"),
        (0, 0b00010) => wide.then_some("ssra"),
        (0, 0b00100) => wide.then_some("srshr"),
        (0, 0b00110) => wide.then_some("srsra"),
        (0, 0b01010) => wide.then_some("shl"),
        (0, 0b01110) => wide.then_some("sqshl"),
        (0, 0b10000) => narrow.then_some(q2!(q, "shrn")),
        (0, 0b10001) => narrow.then_some(q2!(q, "rshrn")),
        (0, 0b10010) => narrow.then_some(q2!(q, "sqshrn")),
        (0, 0b10011) => narrow.then_some(q2!(q, "sqrshrn")),
        (0, 0b10100) => narrow.then_some(q2!(q, "sshll")),
        (0, 0b11100) => fixed.then_some("scvtf"),
        (0, 0b11111) => fixed.then_some("fcvtzs"),
        (1, 0b00000) => wide.then_some("ushr"),
        (1, 0b00010) => wide.then_some("usra"),
        (1, 0b00100) => wide.then_some("urshr"),
        (1, 0b00110) => wide.then_some("ursra"),
        (1, 0b01000) => wide.then_some("sri"),
        (1, 0b01010) => wide.then_some("sli"),
        (1, 0b01100) => wide.then_some("sqshlu"),
        (1, 0b01110) => wide.then_some("uqshl"),
        (1, 0b10000) => narrow.then_some(q2!(q, "sqshrun")),
        (1, 0b10001) => narrow.then_some(q2!(q, "sqrshrun")),
        (1, 0b10010) => narrow.then_some(q2!(q, "uqshrn")),
        (1, 0b10011) => narrow.then_some(q2!(q, "uqrshrn")),
        (1, 0b10100) => narrow.then_some(q2!(q, "ushll")),
        (1, 0b11100) => fixed.then_some("ucvtf"),
        (1, 0b11111) => fixed.then_some("fcvtzu"),
        _ => None,
    }
}

fn indexed(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let l = word >> 21 & 1;
    let opcode = bits(word, 15, 12);
    let integer = size == 1 || size == 2;
    let fp = size == 2 || size == 3 && l == 0 && q;
    match (u, opcode) {
        (0, 0b0010) => integer.then_some(q2!(q, "smlal")),
        (0, 0b0011) => integer.then_some(q2!(q, "sqdmlal")),
        (0, 0b0110) => integer.then_some(q2!(q, "smlsl")),
        (0, 0b0111) => integer.then_some(q2!(q, "sqdmlsl")),
        (0, 0b1000) => integer.then_some("mul"),
        (0, 0b1010) => integer.then_some(q2!(q, "smull")),
        (0, 0b1011) => integer.then_some(q2!(q, "sqdmull")),
        (0, 0b1100) => integer.then_some("sqdmulh"),
        (0, 0b1101) => integer.then_some("sqrdmulh"),
        (1, 0b0000) => integer.then_some("mla"),
        (1, 0b0010) => integer.then_some(q2!(q, "umlal")),
        (1, 0b0100) => integer.then_some("mls"),
        (1, 0b0110) => integer.then_some(q2!(q, "umlsl")),
        (1, 0b1010) => integer.then_some(q2!(q, "umull")),
        (0, 0b0001) => fp.then_some("fmla"),
        (0, 0b0101) => fp.then_some("fmls"),
        (0, 0b1001) => fp.then_some("fmul"),
        (1, 0b1001) => fp.then_some("fmulx"),
        _ => None,
    }
}

fn table(word: u32) -> Option<&'static str> {
    if bits(word, 23, 22) != 0 {
        return None;
    }
    Some(if word >> 12 & 1 == 0 { "tbl" } else { "tbx" })
}

fn permute(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    if bits(word, 23, 22) == 3 && !q {
        return None;
    }
    match bits(word, 14, 12) {
        0b001 => Some("uzp1"),
        0b010 => Some("trn1"),
        0b011 => Some("zip1"),
        0b101 => Some("uzp2"),
        0b110 => Some("trn2"),
        0b111 => Some("zip2"),
        _ => None,
    }
}

fn extract(word: u32) -> Option<&'static str> {
    let q = word >> 30 & 1 != 0;
    if bits(word, 23, 22) != 0 || !q && word >> 14 & 1 != 0 {
        return None;
    }
    Some("ext")
}

// ---- AdvSIMD, scalar

fn scalar_three_same(word: u32) -> Option<&'static str> {
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 15, 11);
    if opcode >= 0b11000 {
        return match (u, size >> 1, opcode) {
            (0, 0, 0b11011) => Some("fmulx"),
            (0, 0, 0b11100) => Some("fcmeq"),
            (0, 0, 0b11111) => Some("frecps"),
            (0, 1, 0b11111) => Some("frsqrts"),
            (1, 0, 0b11100) => Some("fcmge"),
            (1, 0, 0b11101) => Some("facge"),
            (1, 1, 0b11010) => Some("fabd"),
            (1, 1, 0b11100) => Some("fcmgt"),
            (1, 1, 0b11101) => Some("facgt"),
            _ => None,
        };
    }
    let d = size == 3;
    match (u, opcode) {
        (0, 0b00001) => Some("sqadd"),
        (0, 0b00101) => Some("sqsub"),
        (0, 0b00110) => d.then_some("cmgt"),
        (0, 0b00111) => d.then_some("cmge"),
        (0, 0b01000) => d.then_some("sshl"),
        (0, 0b01001) => Some("sqshl"),
        (0, 0b01010) => d.then_some("srshl"),
        (0, 0b01011) => Some("sqrshl"),
        (0, 0b10000) => d.then_some("add"),
        (0, 0b10001) => d.then_some("cmtst"),
        (0, 0b10110) => (size == 1 || size == 2).then_some("sqdmulh"),
        (1, 0b00001) => Some("uqadd"),
        (1, 0b00101) => Some("uqsub"),
        (1, 0b00110) => d.then_some("cmhi"),
        (1, 0b00111) => d.then_some("cmhs"),
        (1, 0b01000) => d.then_some("ushl"),
        (1, 0b01001) => Some("uqshl"),
        (1, 0b01010) => d.then_some("urshl"),
        (1, 0b01011) => Some("uqrshl"),
        (1, 0b10000) => d.then_some("sub"),
        (1, 0b10001) => d.then_some("cmeq"),
        (1, 0b10110) => (size == 1 || size == 2).then_some("sqrdmulh"),
        _ => None,
    }
}

fn scalar_three_different(word: u32) -> Option<&'static str> {
    let size = bits(word, 23, 22);
    if word >> 29 & 1 != 0 || !(size == 1 || size == 2) {
        return None;
    }
    match bits(word, 15, 12) {
        0b1001 => Some("sqdmlal"),
        0b1011 => Some("sqdmlsl"),
        0b1101 => Some("sqdmull"),
        _ => None,
    }
}

fn scalar_two_misc(word: u32) -> Option<&'static str> {
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    let d = size == 3;
    match (u, opcode) {
        (0, 0b00011) => Some("suqadd"),
        (0, 0b00111) => Some("sqabs"),
        (0, 0b01000) => d.then_some("cmgt"),
        (0, 0b01001) => d.then_some("cmeq"),
        (0, 0b01010) => d.then_some("cmlt"),
        (0, 0b01011) => d.then_some("abs"),
        (0, 0b10100) => (!d).then_some("sqxtn"),
        (1, 0b00011) => Some("usqadd"),
        (1, 0b00111) => Some("sqneg"),
        (1, 0b01000) => d.then_some("cmge"),
        (1, 0b01001) => d.then_some("cmle"),
        (1, 0b01011) => d.then_some("neg"),
        (1, 0b10010) => (!d).then_some("sqxtun"),
        (1, 0b10100) => (!d).then_some("uqxtn"),
        _ => match (u, size >> 1, opcode) {
            (0, 0, 0b11010) => Some("fcvtns"),
            (0, 0, 0b11011) => Some("fcvtms"),
            (0, 0, 0b11100) => Some("fcvtas"),
            (0, 0, 0b11101) => Some("scvtf"),
            (0, 1, 0b01100) => Some("fcmgt"),
            (0, 1, 0b01101) => Some("fcmeq"),
            (0, 1, 0b01110) => Some("fcmlt"),
            (0, 1, 0b11010) => Some("fcvtps"),
            (0, 1, 0b11011) => Some("fcvtzs"),
            (0, 1, 0b11101) => Some("frecpe"),
            (0, 1, 0b11111) => Some("frecpx"),
            (1, 0, 0b10110) => (size & 1 == 1).then_some("fcvtxn"),
            (1, 0, 0b11010) => Some("fcvtnu"),
            (1, 0, 0b11011) => Some("fcvtmu"),
            (1, 0, 0b11100) => Some("fcvtau"),
            (1, 0, 0b11101) => Some("ucvtf"),
            (1, 1, 0b01100) => Some("fcmge"),
            (1, 1, 0b01101) => Some("fcmle"),
            (1, 1, 0b11010) => Some("fcvtpu"),
            (1, 1, 0b11011) => Some("fcvtzu"),
            (1, 1, 0b11101) => Some("frsqrte"),
            _ => None,
        },
    }
}

fn scalar_pairwise(word: u32) -> Option<&'static str> {
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    match (u, bits(word, 16, 12)) {
        (0, 0b11011) => (size == 3).then_some("addp"),
        (1, 0b01100) => Some(if size >> 1 == 0 { "fmaxnmp" } else { "fminnmp" }),
        (1, 0b01101) => (size >> 1 == 0).then_some("faddp"),
        (1, 0b01111) => Some(if size >> 1 == 0 { "fmaxp" } else { "fminp" }),
        _ => None,
    }
}

fn scalar_copy(word: u32) -> Option<&'static str> {
    (word >> 29 & 1 == 0 && bits(word, 14, 11) == 0 && bits(word, 19, 16) != 0).then_some("dup")
}

fn scalar_shift_immediate(word: u32) -> Option<&'static str> {
    let u = word >> 29 & 1;
    let immh = bits(word, 22, 19);
    let opcode = bits(word, 15, 11);
    let d = immh >> 3 == 1;
    let narrow = immh != 0 && !d;
    let any = immh != 0;
    let fixed = immh >= 0b0100;
    match (u, opcode) {
        (0, 0b00000) => d.then_some("sshr"),
        (0, 0b00010) => d.then_some("ssra"),
        (0, 0b00100) => d.then_some("srshr"),
        (0, 0b00110) => d.then_some("srsra"),
        (0, 0b01010) => d.then_some("shl"),
        (0, 0b01110) => any.then_some("sqshl"),
        (0, 0b10010) => narrow.then_some("sqshrn"),
        (0, 0b10011) => narrow.then_some("sqrshrn"),
        (0, 0b11100) => fixed.then_some("scvtf"),
        (0, 0b11111) => fixed.then_some("fcvtzs"),
        (1, 0b00000) => d.then_some("ushr"),
        (1, 0b00010) => d.then_some("usra"),
        (1, 0b00100) => d.then_some("urshr"),
        (1, 0b00110) => d.then_some("ursra"),
        (1, 0b01000) => d.then_some("sri"),
        (1, 0b01010) => d.then_some("sli"),
        (1, 0b01100) => any.then_some("sqshlu"),
        (1, 0b01110) => any.then_some("uqshl"),
        (1, 0b10000) => narrow.then_some("sqshrun"),
        (1, 0b10001) => narrow.then_some("sqrshrun"),
        (1, 0b10010) => narrow.then_some("uqshrn"),
        (1, 0b10011) => narrow.then_some("uqrshrn"),
        (1, 0b11100) => fixed.then_some("ucvtf"),
        (1, 0b11111) => fixed.then_some("fcvtzu"),
        _ => None,
    }
}

fn scalar_indexed(word: u32) -> Option<&'static str> {
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let l = word >> 21 & 1;
    let integer = size == 1 || size == 2;
    let fp = size == 2 || size == 3 && l == 0;
    match (u, bits(word, 15, 12)) {
        (0, 0b0011) => integer.then_some("sqdmlal"),
        (0, 0b0111) => integer.then_some("sqdmlsl"),
        (0, 0b1011) => integer.then_some("sqdmull"),
        (0, 0b1100) => integer.then_some("sqdmulh"),
        (0, 0b1101) => integer.then_some("sqrdmulh"),
        (0, 0b0001) => fp.then_some("fmla"),
        (0, 0b0101) => fp.then_some("fmls"),
        (0, 0b1001) => fp.then_some("fmul"),
        (1, 0b1001) => fp.then_some("fmulx"),
        _ => None,
    }
}

// ---- crypto (P2.11)

fn aes(word: u32) -> Option<&'static str> {
    if bits(word, 23, 22) != 0 {
        return None;
    }
    match bits(word, 16, 12) {
        0b00100 => Some("aese"),
        0b00101 => Some("aesd"),
        0b00110 => Some("aesmc"),
        0b00111 => Some("aesimc"),
        _ => None,
    }
}

fn sha3(word: u32) -> Option<&'static str> {
    if bits(word, 23, 22) != 0 {
        return None;
    }
    match bits(word, 14, 12) {
        0b000 => Some("sha1c"),
        0b001 => Some("sha1p"),
        0b010 => Some("sha1m"),
        0b011 => Some("sha1su0"),
        0b100 => Some("sha256h"),
        0b101 => Some("sha256h2"),
        0b110 => Some("sha256su1"),
        _ => None,
    }
}

fn sha2(word: u32) -> Option<&'static str> {
    if bits(word, 23, 22) != 0 {
        return None;
    }
    match bits(word, 16, 12) {
        0b00000 => Some("sha1h"),
        0b00001 => Some("sha1su1"),
        0b00010 => Some("sha256su0"),
        _ => None,
    }
}

// ---- scalar FP

fn fp_fixed(word: u32) -> Option<&'static str> {
    let sf = word >> 31;
    let ty = bits(word, 23, 22);
    if word >> 29 & 1 != 0 || ty >= 2 || sf == 0 && word >> 15 & 1 == 0 {
        return None;
    }
    match (bits(word, 20, 19), bits(word, 18, 16)) {
        (0b00, 0b010) => Some("scvtf"),
        (0b00, 0b011) => Some("ucvtf"),
        (0b11, 0b000) => Some("fcvtzs"),
        (0b11, 0b001) => Some("fcvtzu"),
        _ => None,
    }
}

fn fp_int(word: u32) -> Option<&'static str> {
    let sf = word >> 31;
    let ty = bits(word, 23, 22);
    if word >> 29 & 1 != 0 {
        return None;
    }
    let rmode = bits(word, 20, 19);
    let opcode = bits(word, 18, 16);
    if ty == 2 {
        // FMOV Xd, Vn.D[1] and FMOV Vd.D[1], Xn
        return (sf == 1 && rmode == 1 && opcode >= 0b110).then_some("fmov");
    }
    if ty == 3 {
        return None;
    }
    match (rmode, opcode) {
        (0b00, 0b000) => Some("fcvtns"),
        (0b00, 0b001) => Some("fcvtnu"),
        (0b00, 0b010) => Some("scvtf"),
        (0b00, 0b011) => Some("ucvtf"),
        (0b00, 0b100) => Some("fcvtas"),
        (0b00, 0b101) => Some("fcvtau"),
        (0b00, 0b110) | (0b00, 0b111) => (sf == ty).then_some("fmov"),
        (0b01, 0b000) => Some("fcvtps"),
        (0b01, 0b001) => Some("fcvtpu"),
        (0b10, 0b000) => Some("fcvtms"),
        (0b10, 0b001) => Some("fcvtmu"),
        (0b11, 0b000) => Some("fcvtzs"),
        (0b11, 0b001) => Some("fcvtzu"),
        _ => None,
    }
}

fn fp_dp1(word: u32) -> Option<&'static str> {
    let ty = bits(word, 23, 22);
    let opcode = bits(word, 20, 15);
    if ty == 2 {
        return None;
    }
    if ty == 3 {
        // half precision: only FCVT to single and double are v8.0
        return (opcode == 0b000100 || opcode == 0b000101).then_some("fcvt");
    }
    match opcode {
        0b000000 => Some("fmov"),
        0b000001 => Some("fabs"),
        0b000010 => Some("fneg"),
        0b000011 => Some("fsqrt"),
        0b000100 => (ty == 1).then_some("fcvt"),
        0b000101 => (ty == 0).then_some("fcvt"),
        0b000111 => Some("fcvt"),
        0b001000 => Some("frintn"),
        0b001001 => Some("frintp"),
        0b001010 => Some("frintm"),
        0b001011 => Some("frintz"),
        0b001100 => Some("frinta"),
        0b001110 => Some("frintx"),
        0b001111 => Some("frinti"),
        _ => None,
    }
}

fn fp_dp3(word: u32) -> Option<&'static str> {
    if word >> 31 != 0 || word >> 29 & 1 != 0 || bits(word, 23, 22) >= 2 {
        return None;
    }
    Some(["fmadd", "fmsub", "fnmadd", "fnmsub"][(word >> 20 & 2 | word >> 15 & 1) as usize])
}

// ---- AdvSIMD structure loads and stores

/// LD1-LD4/ST1-ST4 (multiple structures, single structures, replicate):
/// the name, the registers, and for a single structure its element
pub struct Structure {
    pub name: &'static str,
    pub load: bool,
    /// the number of registers (selem: 1-4)
    pub registers: u32,
    /// multiple structures: the registers' elements interleave `interleave` ways (1 for LD1/ST1 of 1-4 registers)
    pub interleave: u32,
    /// log2 of the element size in bytes
    pub size_log: u32,
    /// a single structure: the element index, or None for multiple structures
    pub index: Option<u32>,
    /// LDnR: replicate to every element
    pub replicate: bool,
}

pub fn structure(word: u32) -> Option<Structure> {
    let q = word >> 30 & 1;
    let load = word >> 22 & 1 != 0;
    let post = word >> 23 & 1 != 0;
    if !post && bits(word, 20, 16) != 0 {
        return None;
    }
    let size = bits(word, 11, 10);
    if word >> 24 & 1 == 0 {
        if word >> 21 & 1 != 0 {
            return None;
        }
        let (registers, interleave) = match bits(word, 15, 12) {
            0b0000 => (4, 4),
            0b0010 => (4, 1),
            0b0100 => (3, 3),
            0b0110 => (3, 1),
            0b0111 => (1, 1),
            0b1000 => (2, 2),
            0b1010 => (2, 1),
            _ => return None,
        };
        if interleave > 1 && size == 3 && q == 0 {
            return None;
        }
        let names = if load { ["ld1", "ld2", "ld3", "ld4"] } else { ["st1", "st2", "st3", "st4"] };
        return Some(Structure {
            name: names[(interleave - 1) as usize],
            load,
            registers,
            interleave,
            size_log: size,
            index: None,
            replicate: false,
        });
    }
    let r = word >> 21 & 1;
    let opcode = bits(word, 15, 13);
    let s = word >> 12 & 1;
    let registers = ((opcode & 1) << 1 | r) + 1;
    let (size_log, index, replicate) = match opcode >> 1 {
        0 => (0, q << 3 | s << 2 | size, false),
        1 => {
            if size & 1 != 0 {
                return None;
            }
            (1, q << 2 | s << 1 | size >> 1, false)
        },
        2 => {
            if size >> 1 != 0 {
                return None;
            }
            if size == 0 {
                (2, q << 1 | s, false)
            }
            else {
                if s != 0 {
                    return None;
                }
                (3, q, false)
            }
        },
        _ => {
            if !load || s != 0 {
                return None;
            }
            (size, 0, true)
        },
    };
    let name = match (load, replicate, registers) {
        (true, true, n) => ["ld1r", "ld2r", "ld3r", "ld4r"][(n - 1) as usize],
        (true, false, n) => ["ld1", "ld2", "ld3", "ld4"][(n - 1) as usize],
        (false, _, n) => ["st1", "st2", "st3", "st4"][(n - 1) as usize],
    };
    Some(Structure {
        name,
        load,
        registers,
        interleave: registers,
        size_log,
        index: if replicate { None } else { Some(index) },
        replicate,
    })
}
                                                                                                                                                                                                                                                                          source/v64/src/rust/aarch64/simd_fp.rs                                                              0000644 0000000 0000000 00000050055 00000000000 014674  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Scalar FP and the FP operations of AdvSIMD (docs/arm64-virt-android16-plan.md
//! P2.6, P2.8): the instructions, on top of fp.rs's arithmetic with the
//! ARM rules. One `Fp` per instruction collects the FPSR flags of all its
//! elements; they are written with the result.

use crate::aarch64::cpu::{self, xr};
use crate::aarch64::decode::bits;
use crate::aarch64::execute::{condition_holds, Flow};
use crate::aarch64::fp::{
    self, Arith, Format, Fp, F32, F64, ROUND_MAX, ROUND_MIN, ROUND_MIN_MAG, ROUND_NEAR_EVEN,
    ROUND_NEAR_MAX_MAG,
};
use crate::aarch64::simd::{elem, ones, set_vreg, vreg, with_elem};

#[inline(always)]
fn regs(word: u32) -> (u32, u32, u32) { (word & 31, word >> 5 & 31, word >> 16 & 31) }
#[inline(always)]
fn datasize(word: u32) -> u32 { 64 << (word >> 30 & 1) }
#[inline(always)]
fn all<T: Format>(test: bool) -> u64 {
    if test {
        ones(T::BITS)
    }
    else {
        0
    }
}

/// Run an element operation on each element of `elements`, as single or double precision
macro_rules! per_type {
    ($esize:expr, $f:ident, $($arg:expr),*) => {
        if $esize == 32 { $f::<F32>($($arg),*) } else { $f::<F64>($($arg),*) }
    };
}

// ---- AdvSIMD three same

fn same_op<T: Format>(fp: &mut Fp, u: u32, a: u32, opcode: u32, x: u64, y: u64, z: u64) -> u64 {
    match (u, a, opcode) {
        (_, 0, 0b11000) => fp.max_min::<T>(x, y, true, true),
        (_, 1, 0b11000) => fp.max_min::<T>(x, y, false, true),
        (0, 0, 0b11001) => fp.mul_add::<T>(z, x, y),
        (0, 1, 0b11001) => fp.mul_add::<T>(z, x ^ T::SIGN, y),
        (_, 0, 0b11010) => fp.arith::<T>(Arith::Add, x, y),
        (0, 1, 0b11010) => fp.arith::<T>(Arith::Sub, x, y),
        (1, 1, 0b11010) => fp.arith::<T>(Arith::Sub, x, y) & !T::SIGN,
        (0, 0, 0b11011) => fp.mulx::<T>(x, y),
        (1, 0, 0b11011) => fp.arith::<T>(Arith::Mul, x, y),
        (0, 0, 0b11100) => all::<T>(fp.compare_eq::<T>(x, y)),
        (1, 0, 0b11100) => all::<T>(fp.compare_ge::<T>(x, y)),
        (1, 1, 0b11100) => all::<T>(fp.compare_gt::<T>(x, y)),
        (1, 0, 0b11101) => all::<T>(fp.compare_ge::<T>(x & !T::SIGN, y & !T::SIGN)),
        (1, 1, 0b11101) => all::<T>(fp.compare_gt::<T>(x & !T::SIGN, y & !T::SIGN)),
        (_, 0, 0b11110) => fp.max_min::<T>(x, y, true, false),
        (_, 1, 0b11110) => fp.max_min::<T>(x, y, false, false),
        (0, 0, 0b11111) => fp.recip_step::<T>(x, y),
        (0, 1, 0b11111) => fp.recip_sqrt_step::<T>(x, y),
        (1, 0, 0b11111) => fp.arith::<T>(Arith::Div, x, y),
        _ => 0,
    }
}

pub fn three_same(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 15, 11);
    let (a, esize) = (size >> 1, 32 << (size & 1));
    let width = if scalar { esize } else { datasize(word) };
    let elements = width / esize;
    let pairwise =
        !scalar && u == 1 && matches!((a, opcode), (_, 0b11000) | (0, 0b11010) | (_, 0b11110));
    let (va, vb, vc) = (vreg(n), vreg(m), vreg(d));
    let mut fp = Fp::new();
    let mut result = 0u128;
    for e in 0..elements {
        let (x, y) = if pairwise {
            let (source, i) = if 2 * e < elements { (va, 2 * e) } else { (vb, 2 * e - elements) };
            (elem(source, i, esize), elem(source, i + 1, esize))
        }
        else {
            (elem(va, e, esize), elem(vb, e, esize))
        };
        let r = per_type!(
            esize,
            same_op,
            &mut fp,
            u,
            a,
            opcode,
            x,
            y,
            elem(vc, e, esize)
        );
        result = with_elem(result, e, esize, r);
    }
    fp.finish();
    set_vreg(d, result);
    Flow::Next
}

// ---- AdvSIMD two-register miscellaneous

fn misc_op<T: Format>(fp: &mut Fp, u: u32, a: u32, opcode: u32, x: u64) -> u64 {
    let fpcr_mode = fp::rounding_of(fp.fpcr >> 22);
    let zero = 0;
    match (u, a, opcode) {
        (0, 0, 0b11000) => fp.round_to_int::<T>(x, ROUND_NEAR_EVEN, false),
        (0, 0, 0b11001) => fp.round_to_int::<T>(x, ROUND_MIN, false),
        (0, 1, 0b11000) => fp.round_to_int::<T>(x, ROUND_MAX, false),
        (0, 1, 0b11001) => fp.round_to_int::<T>(x, ROUND_MIN_MAG, false),
        (1, 0, 0b11000) => fp.round_to_int::<T>(x, ROUND_NEAR_MAX_MAG, false),
        (1, 0, 0b11001) => fp.round_to_int::<T>(x, fpcr_mode, true),
        (1, 1, 0b11001) => fp.round_to_int::<T>(x, fpcr_mode, false),
        // FCVT[NMAPZ][SU] (vector and scalar: the element size)
        (_, _, 0b11010) | (_, _, 0b11011) | (_, 0, 0b11100) => {
            let mode = match (a, opcode) {
                (0, 0b11010) => ROUND_NEAR_EVEN,
                (0, 0b11011) => ROUND_MIN,
                (0, _) => ROUND_NEAR_MAX_MAG,
                (_, 0b11010) => ROUND_MAX,
                _ => ROUND_MIN_MAG,
            };
            fp.to_integer::<T>(x, u == 0, T::BITS, 0, mode)
        },
        (_, 0, 0b11101) => fp.from_integer::<T>(x, u == 0, T::BITS, 0),
        (0, 1, 0b01100) => all::<T>(fp.compare_gt::<T>(x, zero)),
        (0, 1, 0b01101) => all::<T>(fp.compare_eq::<T>(x, zero)),
        (0, 1, 0b01110) => all::<T>(fp.compare_gt::<T>(zero, x)),
        (1, 1, 0b01100) => all::<T>(fp.compare_ge::<T>(x, zero)),
        (1, 1, 0b01101) => all::<T>(fp.compare_ge::<T>(zero, x)),
        (0, 1, 0b01111) => x & !T::SIGN,
        (1, 1, 0b01111) => x ^ T::SIGN,
        (0, 1, 0b11100) => {
            // URECPE
            if x >> 31 == 0 {
                0xFFFF_FFFF
            }
            else {
                (fp::recip_estimate((x >> 23) as u32 & 0x1FF) as u64) << 23
            }
        },
        (1, 1, 0b11100) => {
            // URSQRTE
            if x >> 30 == 0 {
                0xFFFF_FFFF
            }
            else {
                (fp::recip_sqrt_estimate((x >> 23) as u32 & 0x1FF) as u64) << 23
            }
        },
        (0, 1, 0b11101) => fp.recip_estimate::<T>(x),
        (1, 1, 0b11101) => fp.recip_sqrt_estimate::<T>(x),
        (0, 1, 0b11111) => fp.recip_exponent::<T>(x),
        (1, 1, 0b11111) => fp.sqrt::<T>(x),
        _ => 0,
    }
}

pub fn two_misc(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let q = word >> 30 & 1 != 0;
    let u = word >> 29 & 1;
    let size = bits(word, 23, 22);
    let opcode = bits(word, 16, 12);
    let (a, sz) = (size >> 1, size & 1);
    let va = vreg(n);
    let mut fp = Fp::new();
    match (u, a, opcode) {
        (_, 0, 0b10110) => {
            // FCVTN (single to half, double to single), FCVTXN (double to single, rounding to odd)
            let odd = u == 1;
            let (from, to) = if sz == 0 { (32, 16) } else { (64, 32) };
            let count = if scalar { 1 } else { 64 / to };
            let mut result = 0u64;
            for e in 0..count {
                let x = elem(va, e, from);
                let r = if to == 16 {
                    fp.to_half(x, 32) as u64
                }
                else {
                    fp.double_to_single(x, odd) as u64
                };
                result |= r << (e * to);
            }
            fp.finish();
            if scalar || !q {
                set_vreg(d, result as u128);
            }
            else {
                set_vreg(d, vreg(d) & u64::MAX as u128 | (result as u128) << 64);
            }
        },
        (0, 0, 0b10111) => {
            // FCVTL: half to single, single to double (the lower or upper half)
            let (from, to) = if sz == 0 { (16, 32) } else { (32, 64) };
            let source = if q { va >> 64 } else { va };
            let mut result = 0u128;
            for e in 0..128 / to {
                let x = elem(source, e, from);
                let r = if from == 16 {
                    fp.from_half(x as u16, 32)
                }
                else {
                    fp.single_to_double(x as u32)
                };
                result = with_elem(result, e, to, r);
            }
            fp.finish();
            set_vreg(d, result);
        },
        _ => {
            let esize = 32 << sz;
            let width = if scalar { esize } else { datasize(word) };
            let mut result = 0u128;
            for e in 0..width / esize {
                let r = per_type!(esize, misc_op, &mut fp, u, a, opcode, elem(va, e, esize));
                result = with_elem(result, e, esize, r);
            }
            fp.finish();
            set_vreg(d, result);
        },
    }
    Flow::Next
}

// ---- across lanes, pairwise

pub fn across(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let a = bits(word, 23, 23);
    let opcode = bits(word, 16, 12);
    let va = vreg(n);
    let numbers = opcode == 0b01100;
    let max = a == 0;
    let mut fp = Fp::new();
    // (a tree: op(op(e0, e1), op(e2, e3)))
    let e = |i| elem(va, i, 32);
    let low = fp.max_min::<F32>(e(0), e(1), max, numbers);
    let high = fp.max_min::<F32>(e(2), e(3), max, numbers);
    let result = fp.max_min::<F32>(low, high, max, numbers);
    fp.finish();
    set_vreg(d, result as u128);
    Flow::Next
}

fn pair_op<T: Format>(fp: &mut Fp, a: u32, opcode: u32, x: u64, y: u64) -> u64 {
    match opcode {
        0b01100 => fp.max_min::<T>(x, y, a == 0, true),
        0b01101 => fp.arith::<T>(Arith::Add, x, y),
        _ => fp.max_min::<T>(x, y, a == 0, false),
    }
}

pub fn pairwise(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let size = bits(word, 23, 22);
    let esize = 32 << (size & 1);
    let va = vreg(n);
    let mut fp = Fp::new();
    let r = per_type!(
        esize,
        pair_op,
        &mut fp,
        size >> 1,
        bits(word, 16, 12),
        elem(va, 0, esize),
        elem(va, 1, esize)
    );
    fp.finish();
    set_vreg(d, r as u128);
    Flow::Next
}

// ---- shift by immediate: the fixed-point conversions

fn fixed_op<T: Format>(fp: &mut Fp, u: u32, opcode: u32, fbits: u32, x: u64) -> u64 {
    if opcode == 0b11100 {
        fp.from_integer::<T>(x, u == 0, T::BITS, fbits)
    }
    else {
        fp.to_integer::<T>(x, u == 0, T::BITS, fbits, ROUND_MIN_MAG)
    }
}

pub fn fixed_point(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let immh = bits(word, 22, 19);
    let esize = if immh >> 3 != 0 { 64 } else { 32 };
    let fbits = 2 * esize - bits(word, 22, 16);
    let opcode = bits(word, 15, 11);
    let width = if scalar { esize } else { datasize(word) };
    let va = vreg(n);
    let mut fp = Fp::new();
    let mut result = 0u128;
    for e in 0..width / esize {
        let r = per_type!(
            esize,
            fixed_op,
            &mut fp,
            u,
            opcode,
            fbits,
            elem(va, e, esize)
        );
        result = with_elem(result, e, esize, r);
    }
    fp.finish();
    set_vreg(d, result);
    Flow::Next
}

// ---- by element

fn indexed_op<T: Format>(fp: &mut Fp, u: u32, opcode: u32, x: u64, y: u64, z: u64) -> u64 {
    match (u, opcode) {
        (0, 0b0001) => fp.mul_add::<T>(z, x, y),
        (0, 0b0101) => fp.mul_add::<T>(z, x ^ T::SIGN, y),
        (0, _) => fp.arith::<T>(Arith::Mul, x, y),
        _ => fp.mulx::<T>(x, y),
    }
}

pub fn indexed(word: u32) -> Flow {
    let d = word & 31;
    let n = word >> 5 & 31;
    let scalar = word >> 28 & 1 != 0;
    let u = word >> 29 & 1;
    let esize = 32 << (bits(word, 23, 22) & 1);
    let opcode = bits(word, 15, 12);
    let (m, index) = crate::aarch64::simd::indexed_operand(word, esize);
    let y = elem(vreg(m), index, esize);
    let (va, vc) = (vreg(n), vreg(d));
    let width = if scalar { esize } else { datasize(word) };
    let mut fp = Fp::new();
    let mut result = 0u128;
    for e in 0..width / esize {
        let r = per_type!(
            esize,
            indexed_op,
            &mut fp,
            u,
            opcode,
            elem(va, e, esize),
            y,
            elem(vc, e, esize)
        );
        result = with_elem(result, e, esize, r);
    }
    fp.finish();
    set_vreg(d, result);
    Flow::Next
}

// ---- scalar FP

/// The scalar FP type of a word: 32 (single), 64 (double), 16 (half)
#[inline(always)]
fn ftype(word: u32) -> u32 {
    match bits(word, 23, 22) {
        0 => 32,
        1 => 64,
        _ => 16,
    }
}

fn dp1_op<T: Format>(fp: &mut Fp, opcode: u32, x: u64) -> u64 {
    let fpcr_mode = fp::rounding_of(fp.fpcr >> 22);
    match opcode {
        0b000000 => x,
        0b000001 => x & !T::SIGN,
        0b000010 => x ^ T::SIGN,
        0b000011 => fp.sqrt::<T>(x),
        0b001000 => fp.round_to_int::<T>(x, ROUND_NEAR_EVEN, false),
        0b001001 => fp.round_to_int::<T>(x, ROUND_MAX, false),
        0b001010 => fp.round_to_int::<T>(x, ROUND_MIN, false),
        0b001011 => fp.round_to_int::<T>(x, ROUND_MIN_MAG, false),
        0b001100 => fp.round_to_int::<T>(x, ROUND_NEAR_MAX_MAG, false),
        0b001110 => fp.round_to_int::<T>(x, fpcr_mode, true),
        _ => fp.round_to_int::<T>(x, fpcr_mode, false),
    }
}

pub fn dp1(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let opcode = bits(word, 20, 15);
    let from = ftype(word);
    let x = vreg(n) as u64 & ones(from);
    let mut fp = Fp::new();
    let result = if opcode >> 2 == 1 {
        // FCVT: the destination type in opcode<1:0>
        let to = match opcode & 3 {
            0 => 32,
            1 => 64,
            _ => 16,
        };
        match (from, to) {
            (32, 64) => fp.single_to_double(x as u32),
            (64, 32) => fp.double_to_single(x, false) as u64,
            (16, _) => fp.from_half(x as u16, to),
            (_, _) => fp.to_half(x, from) as u64,
        }
    }
    else {
        per_type!(from, dp1_op, &mut fp, opcode, x)
    };
    fp.finish();
    set_vreg(d, result as u128);
    Flow::Next
}

fn dp2_op<T: Format>(fp: &mut Fp, opcode: u32, x: u64, y: u64) -> u64 {
    match opcode {
        0b0000 => fp.arith::<T>(Arith::Mul, x, y),
        0b0001 => fp.arith::<T>(Arith::Div, x, y),
        0b0010 => fp.arith::<T>(Arith::Add, x, y),
        0b0011 => fp.arith::<T>(Arith::Sub, x, y),
        0b0100 => fp.max_min::<T>(x, y, true, false),
        0b0101 => fp.max_min::<T>(x, y, false, false),
        0b0110 => fp.max_min::<T>(x, y, true, true),
        0b0111 => fp.max_min::<T>(x, y, false, true),
        _ => fp.arith::<T>(Arith::Mul, x, y) ^ T::SIGN,
    }
}

pub fn dp2(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let size = ftype(word);
    let (x, y) = (vreg(n) as u64 & ones(size), vreg(m) as u64 & ones(size));
    let mut fp = Fp::new();
    let result = per_type!(size, dp2_op, &mut fp, bits(word, 15, 12), x, y);
    fp.finish();
    set_vreg(d, result as u128);
    Flow::Next
}

fn dp3_op<T: Format>(fp: &mut Fp, o1: u32, o0: u32, x: u64, y: u64, z: u64) -> u64 {
    // FMADD: a + n*m; FMSUB: a - n*m; FNMADD: -a - n*m; FNMSUB: -a + n*m
    let addend = if o1 == 1 { z ^ T::SIGN } else { z };
    let op1 = if o0 != o1 { x ^ T::SIGN } else { x };
    fp.mul_add::<T>(addend, op1, y)
}

pub fn dp3(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let a = word >> 10 & 31;
    let size = ftype(word);
    let mask = ones(size);
    let (x, y, z) = (
        vreg(n) as u64 & mask,
        vreg(m) as u64 & mask,
        vreg(a) as u64 & mask,
    );
    let mut fp = Fp::new();
    let result = per_type!(
        size,
        dp3_op,
        &mut fp,
        word >> 21 & 1,
        word >> 15 & 1,
        x,
        y,
        z
    );
    fp.finish();
    set_vreg(d, result as u128);
    Flow::Next
}

fn compare_op<T: Format>(fp: &mut Fp, x: u64, y: u64, signal: bool) -> u32 {
    fp.compare::<T>(x, y, signal)
}

pub fn compare(word: u32) -> Flow {
    let (_, n, m) = regs(word);
    let size = ftype(word);
    let opcode2 = bits(word, 4, 0);
    let x = vreg(n) as u64 & ones(size);
    let y = if opcode2 & 0b01000 != 0 { 0 } else { vreg(m) as u64 & ones(size) };
    let mut fp = Fp::new();
    let flags = per_type!(size, compare_op, &mut fp, x, y, opcode2 & 0b10000 != 0);
    fp.finish();
    cpu::set_nzcv(flags);
    Flow::Next
}

pub fn cond_compare(word: u32) -> Flow {
    let (_, n, m) = regs(word);
    let size = ftype(word);
    let cond = bits(word, 15, 12) as u8;
    if condition_holds(cond, cpu::get_nzcv()) {
        let (x, y) = (vreg(n) as u64 & ones(size), vreg(m) as u64 & ones(size));
        let mut fp = Fp::new();
        let flags = per_type!(size, compare_op, &mut fp, x, y, word >> 4 & 1 != 0);
        fp.finish();
        cpu::set_nzcv(flags);
    }
    else {
        cpu::set_nzcv((word & 15) << 28);
    }
    Flow::Next
}

pub fn cond_select(word: u32) -> Flow {
    let (d, n, m) = regs(word);
    let size = ftype(word);
    let cond = bits(word, 15, 12) as u8;
    let source = if condition_holds(cond, cpu::get_nzcv()) { n } else { m };
    set_vreg(d, (vreg(source) as u64 & ones(size)) as u128);
    Flow::Next
}

pub fn immediate(word: u32) -> Flow {
    let d = word & 31;
    set_vreg(d, fp::expand_imm(bits(word, 20, 13), ftype(word)) as u128);
    Flow::Next
}

/// SCVTF, UCVTF, FCVTZS, FCVTZU (fixed-point: fbits = 64 - scale)
pub fn fixed(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let sf = word >> 31 != 0;
    let size = ftype(word);
    let fbits = 64 - bits(word, 15, 10);
    let int_bits = if sf { 64 } else { 32 };
    let opcode = bits(word, 18, 16);
    let mut fp = Fp::new();
    if opcode >> 1 == 1 {
        let value = xr(n);
        let value = if sf { value } else { value & 0xFFFF_FFFF };
        let signed = opcode == 0b010;
        let r = if size == 32 {
            fp.from_integer::<F32>(value, signed, int_bits, fbits)
        }
        else {
            fp.from_integer::<F64>(value, signed, int_bits, fbits)
        };
        fp.finish();
        set_vreg(d, r as u128);
    }
    else {
        let x = vreg(n) as u64 & ones(size);
        let signed = opcode == 0b000;
        let r = if size == 32 {
            fp.to_integer::<F32>(x, signed, int_bits, fbits, ROUND_MIN_MAG)
        }
        else {
            fp.to_integer::<F64>(x, signed, int_bits, fbits, ROUND_MIN_MAG)
        };
        fp.finish();
        cpu::set_x(d, if sf { r } else { r & 0xFFFF_FFFF });
    }
    Flow::Next
}

/// The conversions between FP and integer registers, and FMOV (general)
pub fn int(word: u32) -> Flow {
    let (d, n, _) = regs(word);
    let sf = word >> 31 != 0;
    let ty = bits(word, 23, 22);
    let rmode = bits(word, 20, 19);
    let opcode = bits(word, 18, 16);
    let int_bits = if sf { 64 } else { 32 };
    match opcode {
        0b110 => {
            // FMOV to a general register (type 2: the upper doubleword)
            let value = vreg(n);
            let r = match (ty, sf) {
                (2, _) => (value >> 64) as u64,
                (_, true) => value as u64,
                _ => value as u32 as u64,
            };
            cpu::set_x(d, r);
            return Flow::Next;
        },
        0b111 => {
            let value = xr(n);
            match (ty, sf) {
                (2, _) => set_vreg(d, vreg(d) & u64::MAX as u128 | (value as u128) << 64),
                (_, true) => set_vreg(d, value as u128),
                _ => set_vreg(d, value as u32 as u128),
            }
            return Flow::Next;
        },
        _ => {},
    }
    let size = if ty == 0 { 32 } else { 64 };
    let mut fp = Fp::new();
    if opcode == 0b010 || opcode == 0b011 {
        let value = xr(n);
        let value = if sf { value } else { value & 0xFFFF_FFFF };
        let r = if size == 32 {
            fp.from_integer::<F32>(value, opcode == 0b010, int_bits, 0)
        }
        else {
            fp.from_integer::<F64>(value, opcode == 0b010, int_bits, 0)
        };
        fp.finish();
        set_vreg(d, r as u128);
        return Flow::Next;
    }
    let mode = match (rmode, opcode >> 2) {
        (0, 0) => ROUND_NEAR_EVEN,
        (0, _) => ROUND_NEAR_MAX_MAG,
        (1, _) => ROUND_MAX,
        (2, _) => ROUND_MIN,
        _ => ROUND_MIN_MAG,
    };
    let signed = opcode & 1 == 0;
    let x = vreg(n) as u64 & ones(size);
    let r = if size == 32 {
        fp.to_integer::<F32>(x, signed, int_bits, 0, mode)
    }
    else {
        fp.to_integer::<F64>(x, signed, int_bits, 0, mode)
    };
    fp.finish();
    cpu::set_x(d, if sf { r } else { r & 0xFFFF_FFFF });
    Flow::Next
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/rust/aarch64/smp.rs                                                                  0000644 0000000 0000000 00000056426 00000000000 014062  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The machine's cores and how they run (docs/arm64-virt-android16-plan.md
//! P3.9: cooperative SMP; P8.2 runs them in workers): one core at a time in
//! the state block, the others' state in their saved copies, switched in a
//! round robin of bounded turns; waiting (WFI, WFE), events (SEV, the event
//! stream, the global monitor), starting cores (PSCI CPU_ON), and the global
//! exclusive monitor (P3.7). The GIC's CPU interfaces, the TLBs and the
//! statistics are per core already and stay where they are.
//!
//! With cores in workers (P8.2) each instance runs one core (`local`): the
//! machine instance core 0, a worker its own; the events and the global
//! monitor are the machine's words, and an event for a core in another
//! instance kicks it. A worker runs its core through a64_worker_slice.

use crate::aarch64::cpu;
use crate::aarch64::execute::{self, Flow};
use crate::aarch64::psci;
use crate::aarch64::state::*;
use crate::isa::{core_count, current_core, MAX_CORES};

/// Instructions in a slice before the machine's other work (timers, devices) runs
pub const SLICE: u32 = 50_000;
/// Instructions a core runs in its turn when there are several
const QUANTUM: u32 = 4096;

/// The per-core part of the state block, from its offset 64 to the end of the last field
/// (src/arm/state_layout.js: a32_fpexc at 1480, cpu_type arm32's; the
/// page tier's scratch fields before the a32 range come along, unused
/// between activations)
const STATE_START: usize = 64;
const STATE_END: usize = 1484;
const STATE_BYTES: usize = STATE_END - STATE_START;

#[repr(C, align(16))]
struct Saved([u8; STATE_BYTES]);

/// The state of the cores that are not running (the running core's copy is stale)
static mut SAVED: [Saved; MAX_CORES] = [const { Saved([0; STATE_BYTES]) }; MAX_CORES];
/// Events for cores that are not running (SEV, the event stream, a cleared
/// reservation): their event register is set when they run next
static mut EVENTS: u32 = 0;
/// Where the next round robin starts
static mut ROUND: usize = 0;
/// (diagnostics, this instance's) runs a kick ended early
static mut KICKED: u32 = 0;
/// A kick ended the last run: the machine's core returns to its loop, which
/// serves the workers' requests (a device register access waits for it)
static mut KICKED_NOW: bool = false;
#[no_mangle]
pub fn a64_kicked() -> u32 { unsafe { KICKED } }

/// (cores in workers) a WFE of this instance's core ends by this counter
/// value at the latest: a store compiled in another worker clears no
/// reservation and sends no event, and WFE may end without one
static mut WFE_UNTIL: u64 = 0;
const WFE_TIMEOUT_NS: u64 = 20_000;
/// (cores in workers) the most instructions an activation of compiled code runs
const ACTIVATION: u32 = 1024;

/// The global monitor (P3.7): the cores holding a reservation, and each one's
/// 64-byte granule of guest RAM (its offset in the RAM's backing >> 6)
static mut MONITORS: u32 = 0;
static mut MONITOR_GRANULE: [u32; MAX_CORES] = [0; MAX_CORES];

#[inline(always)]
fn live() -> *mut u8 { (crate::state_block::state_base() as usize + STATE_START) as *mut u8 }

/// The cores this instance runs: all of them, or with cores in workers its own
#[inline]
pub fn local() -> core::ops::Range<usize> {
    if crate::parallel::active() {
        current_core()..current_core() + 1
    }
    else {
        0..core_count()
    }
}

// the machine's words (crate::parallel::machine): events, the global monitor
#[inline(always)]
fn events() -> *mut u32 { crate::parallel::machine(&raw mut EVENTS) }
#[inline(always)]
fn monitors() -> *mut u32 { crate::parallel::machine(&raw mut MONITORS) }
#[inline(always)]
fn granule(core: usize) -> *mut u32 {
    unsafe {
        crate::parallel::machine(&raw mut MONITOR_GRANULE)
            .cast::<u32>()
            .add(core)
    }
}

/// A field of core `core`'s state: the state block for the running core, its saved copy otherwise
#[inline]
pub fn field<T>(core: usize, pointer: *mut T) -> *mut T {
    if core == current_core() {
        pointer
    }
    else {
        // (the other cores' state is in other instances with cores in workers)
        debug_assert!(!crate::parallel::active());
        let offset = pointer as usize - crate::state_block::state_base() as usize - STATE_START;
        debug_assert!(offset + core::mem::size_of::<T>() <= STATE_BYTES);
        unsafe {
            (&raw mut SAVED[core].0)
                .cast::<u8>()
                .add(offset)
                .cast::<T>()
        }
    }
}

/// Make `core` the running core
pub fn switch_to(core: usize) {
    let old = current_core();
    if old == core {
        return;
    }
    unsafe {
        crate::core_stats::flush_core_statistics();
        core::ptr::copy_nonoverlapping(live(), (&raw mut SAVED[old].0).cast::<u8>(), STATE_BYTES);
        core::ptr::copy_nonoverlapping(
            (&raw const SAVED[core].0).cast::<u8>(),
            live(),
            STATE_BYTES,
        );
        crate::aarch64::isa_hooks::CURRENT_CORE = core;
    }
    take_events();
    // (what derives from the core's registers: the debug fast paths, the fetch fast path)
    crate::aarch64::debug::refresh();
    crate::aarch64::tlb::bump_generation();
    execute::core_switched();
    // (the page tier: this core's compiled stores to pages other cores hold
    // reservations in must reach monitors_written, P3.7; while it runs no
    // other core reserves, and reserved pages get no write entries)
    let others = unsafe { crate::parallel::word_load(monitors()) } & !(1 << core);
    if others != 0 {
        crate::aarch64::jit::pages::retire_reserved_writes(core, others);
    }
}

/// The running core's pending events (SEV, the event stream, a cleared reservation) set its event register
#[inline]
fn take_events() {
    let core = current_core();
    unsafe {
        if crate::parallel::word_load(events()) & 1 << core != 0 {
            crate::parallel::word_and(events(), !(1 << core));
            *event_register = 1;
        }
    }
}

/// The running core (tests, snapshots)
#[no_mangle]
pub fn a64_current_core() -> u32 { current_core() as u32 }

/// (snapshots, diagnostics) make `core` the running one, between slices
#[no_mangle]
pub fn a64_switch_core(core: u32) {
    assert!((core as usize) < core_count());
    switch_to(core as usize);
}

/// An event for `core` (its WFE ends)
pub fn event_to(core: usize) {
    unsafe {
        if core == current_core() {
            *event_register = 1;
        }
        else {
            crate::parallel::word_or(events(), 1 << core);
            crate::parallel::kick(core);
        }
    }
}

/// SEV: an event to every core
pub fn send_event() {
    unsafe {
        *event_register = 1;
        let others = ((1u32 << core_count()) - 1) & !(1 << current_core());
        crate::parallel::word_or(events(), others);
        for core in 0..core_count() {
            if others & 1 << core != 0 {
                crate::parallel::kick(core);
            }
        }
    }
}

// ---- the global monitor (P3.7)

/// A load-exclusive of guest RAM at `backing` marks its granule for the running core
pub fn reserve(backing: u32) {
    let core = current_core();
    unsafe {
        crate::parallel::word_store(granule(core), backing >> 6);
        crate::parallel::word_or(monitors(), 1 << core);
    }
    // (other cores' compiled stores to the page must reach monitors_written:
    // their write entries to it retire when they next run, switch_to, and
    // the access cache fills none while the reservation holds, P3.7)
}

/// The RAM backing offset of `core`'s reserved granule
pub fn reserved_backing(core: usize) -> u32 {
    unsafe { crate::parallel::word_load(granule(core)) << 6 }
}

/// Whether a core holds a reservation in the RAM page at `backing` (the page
/// tier's access cache serves no stores to it)
pub fn reserved_page(backing: u32) -> bool {
    if core_count() == 1 {
        return false;
    }
    let page = backing >> 12;
    let held = unsafe { crate::parallel::word_load(monitors()) };
    held != 0
        && (0..MAX_CORES).any(|c| {
            held & 1 << c != 0 && unsafe { crate::parallel::word_load(granule(c)) } >> 6 == page
        })
}

/// Whether the running core's reservation of the granule at `backing` still holds
pub fn reserved(backing: u32) -> bool {
    let core = current_core();
    unsafe {
        crate::parallel::word_load(monitors()) & 1 << core != 0
            && crate::parallel::word_load(granule(core)) == backing >> 6
    }
}

/// The running core's reservation ends (a store-exclusive, CLREX)
pub fn release() { unsafe { crate::parallel::word_and(monitors(), !(1 << current_core())) } }

/// Guest RAM at [backing, backing + len) was written by the running core
/// (`device` false) or a device: the reservations of other observers on
/// those granules clear, and their cores get an event
#[inline(always)]
pub fn monitors_written(backing: u32, len: u32, device: bool) {
    let others = unsafe { crate::parallel::word_load(monitors()) }
        & if device { u32::MAX } else { !(1 << current_core()) };
    if others != 0 {
        clear_reservations(others, backing, len);
    }
}

#[cold]
fn clear_reservations(cores: u32, backing: u32, len: u32) {
    let first = backing >> 6;
    let last = (backing + len.max(1) - 1) >> 6;
    for core in 0..MAX_CORES {
        if cores & 1 << core != 0 {
            let reserved = unsafe { crate::parallel::word_load(granule(core)) };
            if reserved >= first && reserved <= last {
                unsafe { crate::parallel::word_and(monitors(), !(1 << core)) };
                event_to(core);
            }
        }
    }
}

// ---- running

/// Take a pending interrupt the PE does not mask (at an instruction boundary): whether it did
#[inline(always)]
fn take_interrupt() -> bool {
    let signal = crate::aarch64::gic::signal(current_core());
    let state = cpu::get_pstate();
    let kind = if signal & crate::aarch64::gic::SIGNAL_FIQ != 0 && state & cpu::PSTATE_F == 0 {
        cpu::VECTOR_FIQ
    }
    else if signal & crate::aarch64::gic::SIGNAL_IRQ != 0 && state & cpu::PSTATE_I == 0 {
        cpu::VECTOR_IRQ
    }
    else {
        return false;
    };
    cpu::take_exception(kind, cpu::get_pc(), None, None);
    true
}

/// Whether core `core`, waiting, wakes: WFI on any pending interrupt (masked
/// or not), WFE on an event or an interrupt the PE does not mask
fn wakes(core: usize, kind: u32) -> bool {
    let signal = crate::aarch64::gic::signal(core);
    match kind {
        1 => signal != 0,
        2 => {
            let state = unsafe { *field(core, pstate) };
            let unmasked = signal & crate::aarch64::gic::SIGNAL_IRQ != 0
                && state & cpu::PSTATE_I == 0
                || signal & crate::aarch64::gic::SIGNAL_FIQ != 0 && state & cpu::PSTATE_F == 0;
            unmasked
                || unsafe {
                    *field(core, event_register) != 0
                        || crate::parallel::word_load(events()) & 1 << core != 0
                        || crate::parallel::active()
                            && crate::aarch64::timer::counter() >= WFE_UNTIL
                }
        },
        _ => false,
    }
}

/// Whether core `core` can run now (PSCI's power state, its wait)
fn runnable(core: usize) -> bool {
    match psci::power(core) {
        psci::ON_PENDING => true,
        psci::ON => {
            let kind = unsafe { *field(core, waiting) };
            kind == 0 || kind != 3 && wakes(core, kind)
        },
        _ => false,
    }
}

/// Switch to a runnable core and end its wait (a core started by CPU_ON comes out of reset)
fn prepare(core: usize) {
    switch_to(core);
    take_events();
    unsafe {
        if psci::power(core) == psci::ON_PENDING {
            let (entry, context) = psci::start(core);
            reset_state(entry, context);
            psci::set_power(core, psci::ON);
            return;
        }
        let kind = *waiting;
        if kind != 0 {
            *waiting = 0;
            if kind == 2 {
                // (WFE consumes the event that ended it)
                *event_register = 0;
            }
        }
    }
}

/// The running core from reset: every register of the state block (P4.4:
/// EL1h, MMU off, DAIF masked), its TLB empty
fn reset_state(entry: u64, context: u64) {
    unsafe { core::ptr::write_bytes(live(), 0, STATE_BYTES) };
    cpu::reset_core(entry, context);
    crate::aarch64::debug::reset();
    crate::aarch64::tlb::flush(false);
    release();
    unsafe { crate::parallel::word_and(events(), !(1 << current_core())) };
}

/// Run the running core for up to `budget` instructions: how many it ran.
/// At each block boundary (a branch, an exception, an interrupt, the turn's
/// start) the A64 page tier may run the PC's compiled function
/// (crate::aarch64::jit::pages; J2), else instructions are interpreted.
/// With cores in workers a kick (an interrupt, an event, a stop, another
/// core's TLBI) ends the run early.
fn run_core(budget: u32) -> u32 {
    use crate::aarch64::jit::pages::{self, Ran};
    let several = core_count() > 1;
    let mut i = 0;
    let mut next_tick = 1023;
    let mut boundary = true;
    while i < budget {
        if cfg!(feature = "parallel") && unsafe { crate::aarch64::isa_hooks::CORE_YIELD } != 0 {
            unsafe {
                crate::aarch64::isa_hooks::CORE_YIELD = 0;
                KICKED += 1;
                KICKED_NOW = true;
            }
            // (what the kick may be for: another core's DSB waiting for this one)
            crate::aarch64::isa_hooks::poll();
            break;
        }
        if i >= next_tick {
            crate::aarch64::timer::tick();
            next_tick = i + 1024;
            // (no compiled code is active: frames of extended RAM the access
            // caches hold are released if due; a64_asid_tag's auto mode)
            unsafe { crate::extended::safe_point() };
            pages::asid_tag_tick();
        }
        if crate::aarch64::gic::signal(current_core()) != 0 && take_interrupt() {
            i += 1;
            boundary = true;
            continue;
        }
        let flow = if boundary && unsafe { pages::ENABLED } {
            boundary = false;
            // (with cores in workers an activation is short: a kick, another
            // core's DSB waiting for this one, ends the run at its end)
            let activation =
                if crate::parallel::active() { (budget - i).min(ACTIVATION) } else { budget - i };
            match pages::run(activation) {
                Ran::Native { retired, flow } => {
                    i += retired.max(1);
                    boundary = true;
                    flow
                },
                Ran::None => {
                    i += 1;
                    pages::interpreted();
                    execute::interpret_one()
                },
            }
        }
        else {
            i += 1;
            pages::interpreted();
            execute::interpret_one()
        };
        match flow {
            Flow::Jump(_) | Flow::Set => boundary = true,
            Flow::Wait(kind) => {
                boundary = true;
                // (a wait that is already over goes on; WFE consumes the event)
                take_events();
                if wakes(current_core(), kind) {
                    if kind == 2 {
                        unsafe { *event_register = 0 };
                    }
                    continue;
                }
                unsafe { *waiting = kind };
                if kind == 2 && crate::parallel::active() {
                    unsafe { WFE_UNTIL = crate::aarch64::timer::counter() + WFE_TIMEOUT_NS };
                }
                unsafe { crate::core_stats::note_halt() };
                return i;
            },
            Flow::Off => {
                unsafe { *waiting = 3 };
                return i;
            },
            // (YIELD: the other cores' turn; a spin loop waits for one of them)
            Flow::Yield if several => return i,
            // (a DSB waits for other cores' acknowledgements, P8.3: a worker
            // waits here, taking the others' maintenance meanwhile, until a
            // kick asks it to stop; the machine's core returns, its loop
            // serves the workers' requests meanwhile)
            Flow::Retry => {
                if !crate::parallel::is_worker() || !wait_synced() {
                    return i;
                }
            },
            _ => {},
        }
    }
    i
}

/// (a worker's DSB) until the TLB maintenance this core posted is done on
/// the others, taking theirs meanwhile: whether it is (else a kick asks
/// this core to stop, or it waited long)
fn wait_synced() -> bool {
    for _ in 0..1 << 16 {
        crate::aarch64::isa_hooks::poll();
        if crate::aarch64::tlb::synced() {
            return true;
        }
        if unsafe { crate::aarch64::isa_hooks::CORE_YIELD } != 0 {
            return false;
        }
        std::hint::spin_loop();
    }
    false
}

/// The milliseconds the machine can sleep: until the first waiting core's
/// timers or event stream need it (capped at 100)
fn sleep_ms() -> f64 {
    let mut due = u64::MAX;
    for core in local() {
        if psci::power(core) == psci::ON && unsafe { *field(core, waiting) } != 3 {
            due = due.min(crate::aarch64::timer::next_due(core));
            if crate::parallel::active() && unsafe { *field(core, waiting) } == 2 {
                due =
                    due.min(unsafe { WFE_UNTIL }.saturating_sub(crate::aarch64::timer::counter()));
            }
        }
    }
    if due == u64::MAX {
        100.0
    }
    else {
        (due as f64 / 1e6).min(100.0)
    }
}

/// Run the machine for one slice: the milliseconds until something is due
/// (0: run again soon). With cores in workers, only the machine's core runs here.
#[no_mangle]
pub fn a64_run_slice(_now: f64) -> f64 {
    if psci::a64_powered_off() {
        return 100.0;
    }
    let cores = local();
    let count = cores.len();
    let budget = if core_count() == 1 { SLICE } else { QUANTUM };
    let mut executed = 0;
    // (other cores' code writes, publications and TLB maintenance, P8.2, P8.3)
    crate::aarch64::isa_hooks::poll();
    loop {
        crate::aarch64::timer::tick_all();
        let start = unsafe {
            ROUND = (ROUND + 1) % count;
            ROUND
        };
        let mut ran = false;
        for turn in 0..count {
            let core = cores.start + (start + turn) % count;
            // (with cores in workers, what they posted: they may wait for this core's acknowledgement)
            crate::aarch64::isa_hooks::poll();
            if !runnable(core) {
                continue;
            }
            prepare(core);
            executed += run_core(budget);
            ran = true;
            if crate::parallel::active()
                && unsafe { core::ptr::replace(&raw mut KICKED_NOW, false) }
            {
                unsafe { crate::core_stats::flush_core_statistics() };
                return 0.0;
            }
            // (SYSTEM_OFF, SYSTEM_RESET: the machine stops here)
            if psci::request() != 0 {
                unsafe { crate::core_stats::flush_core_statistics() };
                return 0.0;
            }
        }
        // (with cores in workers the machine's loop serves their requests between slices)
        if !ran || executed >= SLICE || crate::parallel::active() && executed >= 4 * QUANTUM {
            break;
        }
    }
    unsafe { crate::core_stats::flush_core_statistics() };
    crate::aarch64::timer::tick_all();
    if cores.clone().any(runnable) {
        0.0
    }
    else {
        sleep_ms()
    }
}

/// A vCPU worker's slice (P8.2): its core, up to `budget` instructions. The
/// milliseconds until it needs to run again (0: at once, the core waits
/// otherwise), or -1 while it is off (it waits for CPU_ON). Other cores'
/// code writes, publications and TLB maintenance are taken first.
#[no_mangle]
pub fn a64_worker_slice(budget: u32) -> f64 {
    unsafe { crate::aarch64::bus::sync_worker_if_stale() };
    crate::aarch64::isa_hooks::poll();
    let core = current_core();
    if psci::request() != 0 || psci::power(core) == psci::OFF {
        return -1.0;
    }
    crate::aarch64::timer::tick();
    if !runnable(core) {
        return sleep_ms().max(0.01);
    }
    prepare(core);
    run_core(budget);
    unsafe { crate::core_stats::flush_core_statistics() };
    crate::aarch64::timer::tick();
    if runnable(core) {
        0.0
    }
    else if psci::power(core) == psci::OFF {
        -1.0
    }
    else {
        sleep_ms().max(0.01)
    }
}

/// Reset the machine's cores: core 0 starts at `entry` with `x0`, the others
/// are off (with cores in workers, the workers reset theirs: COMMAND_RESET)
#[no_mangle]
pub fn a64_boot(entry_low: u32, entry_high: u32, x0_low: u32, x0_high: u32) {
    let entry = entry_low as u64 | (entry_high as u64) << 32;
    let x0 = x0_low as u64 | (x0_high as u64) << 32;
    switch_to(0);
    unsafe {
        for core in 1..MAX_CORES {
            SAVED[core].0.fill(0);
        }
        crate::parallel::word_store(events(), 0);
        crate::parallel::word_store(monitors(), 0);
        ROUND = 0;
    }
    psci::reset();
    crate::aarch64::timer::reset_counter();
    reset_state(entry, x0);
    crate::aarch64::gic::reset();
    crate::aarch64::tlb::flush(true);
}

// ---- snapshots (P3.10): the machine's state outside the cores' state blocks

/// The bytes of the machine's own state `which` (0 the GIC, 1 PSCI's power
/// states): its address in the Wasm memory and its size
#[no_mangle]
pub fn a64_machine_state(which: u32, size: bool) -> u32 {
    let (pointer, length) = match which {
        0 => crate::aarch64::gic::state_bytes(),
        // (the GICv2's own state, docs/aarch32-plan.md R4.2)
        2 => crate::aarch64::gic::v2_state_bytes(),
        _ => psci::state_bytes(),
    };
    if size {
        length
    }
    else {
        pointer
    }
}

/// After a state was restored: what derives from it is recomputed (interrupt
/// lines, the debug fast paths), what may not survive is dropped (TLBs, the
/// exclusive monitors); every core gets an event (a WFE may end early, as
/// the architecture allows, rather than miss one). With cores in workers,
/// the machine's core here, each worker's in a64_worker_restored.
#[no_mangle]
pub fn a64_restored() {
    crate::aarch64::timer::reset_counter();
    crate::aarch64::tlb::flush(true);
    crate::aarch64::debug::refresh();
    crate::aarch64::gic::restored();
    unsafe {
        crate::parallel::word_store(monitors(), 0);
        for core in local() {
            *field(core, excl_valid) = 0;
        }
    }
    for core in 0..core_count() {
        event_to(core);
    }
    crate::aarch64::timer::tick_all();
}

/// (a vCPU worker, P8.2) its core's state was replaced: as a64_restored for it
#[no_mangle]
pub fn a64_worker_restored() {
    crate::aarch64::tlb::flush(false);
    crate::aarch64::debug::refresh();
    unsafe { *excl_valid = 0 };
    event_to(current_core());
    crate::aarch64::timer::tick();
}

/// The core's registers for JavaScript (tests, diagnostics): X0-X30, SP,
/// PC, NZCV, PSTATE are in the state block (src/arm/state_layout.js)
#[no_mangle]
pub fn a64_state_base() -> u32 { crate::state_block::state_base() }

#[cfg(test)]
mod tests {
    #[test]
    fn saved_range_covers_the_layout() {
        use crate::aarch64::state::{a32_fpexc, x};
        let base = crate::state_block::state_base() as usize;
        assert_eq!(x as usize - base, super::STATE_START);
        assert_eq!(a32_fpexc as usize + 4 - base, super::STATE_END);
    }
}
                                                                                                                                                                                                                                          source/v64/src/rust/aarch64/state.rs                                                                0000644 0000000 0000000 00000005036 00000000000 014372  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_upper_case_globals, dead_code)]
//! The ARM core's state block (docs/arm64-virt-android16-plan.md P1.4): its
//! own 4096 bytes from offset 64, like the x86 core's
//! (crate::state_block), laid out by gen/state_layout.js (A64_STATE_FIELDS)
//! and mirrored for JavaScript in src/arm/state_layout.js.

// BEGIN GENERATED by gen/state_layout.js (edit the layout there)
state!(x: u64 = 64);
state!(pc: u64 = 320);
state!(nzcv: u32 = 328);
state!(pstate: u32 = 332);
state!(fpcr: u32 = 336);
state!(fpsr: u32 = 340);
state!(instruction_counter: u32 = 344);
state!(slice_budget: u32 = 348);
state!(v: u128 = 352);
state!(sp_el: u64 = 864);
state!(elr_el1: u64 = 880);
state!(spsr_el1: u64 = 888);
state!(esr_el1: u64 = 896);
state!(far_el1: u64 = 904);
state!(vbar_el1: u64 = 912);
state!(sctlr_el1: u64 = 920);
state!(cpacr_el1: u64 = 928);
state!(ttbr0_el1: u64 = 936);
state!(ttbr1_el1: u64 = 944);
state!(tcr_el1: u64 = 952);
state!(mair_el1: u64 = 960);
state!(amair_el1: u64 = 968);
state!(contextidr_el1: u64 = 976);
state!(tpidr_el0: u64 = 984);
state!(tpidrro_el0: u64 = 992);
state!(tpidr_el1: u64 = 1000);
state!(par_el1: u64 = 1008);
state!(afsr0_el1: u64 = 1016);
state!(afsr1_el1: u64 = 1024);
state!(actlr_el1: u64 = 1032);
state!(csselr_el1: u64 = 1040);
state!(cntkctl_el1: u64 = 1048);
state!(cntfrq_el0: u64 = 1056);
state!(mdscr_el1: u64 = 1064);
state!(osdlr_el1: u64 = 1072);
state!(oslsr_el1: u64 = 1080);
state!(mdccint_el1: u64 = 1088);
state!(disr_el1: u64 = 1096);
state!(cntv_ctl: u64 = 1104);
state!(cntv_cval: u64 = 1112);
state!(cntp_ctl: u64 = 1120);
state!(cntp_cval: u64 = 1128);
state!(icc_pmr: u32 = 1136);
state!(icc_bpr: u32 = 1140);
state!(icc_igrpen: u32 = 1148);
state!(icc_ctlr: u32 = 1156);
state!(icc_ap0r: u32 = 1160);
state!(icc_ap1r: u32 = 1164);
state!(icc_active: u32 = 1168);
state!(icc_active_count: u32 = 1200);
state!(excl_valid: u32 = 1208);
state!(excl_addr: u64 = 1216);
state!(excl_value: u128 = 1232);
state!(dbgbvr: u64 = 1248);
state!(dbgbcr: u64 = 1264);
state!(dbgwvr: u64 = 1280);
state!(dbgwcr: u64 = 1296);
state!(waiting: u32 = 1312);
state!(event_register: u32 = 1316);
state!(a64_page_exit: u32 = 1328);
state!(a64_page_chain: u32 = 1332);
state!(a64_page_linear: u64 = 1336);
state!(a64_jac_epoch: u64 = 1344);
state!(a64_jac_base: u32 = 1352);
state!(a64_code_base: u32 = 1356);
state!(a32_bank: u32 = 1360);
state!(a32_bank_r8: u32 = 1408);
state!(a32_spsr: u32 = 1448);
state!(a32_ttbcr: u32 = 1468);
state!(a32_dacr: u32 = 1472);
state!(a32_ifsr: u32 = 1476);
state!(a32_fpexc: u32 = 1480);
// END GENERATED
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/rust/aarch64/sysregs.rs                                                              0000644 0000000 0000000 00000041163 00000000000 014752  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! System registers and system instructions of profile v86-aarch64-v1
//! (docs/arm64-virt-android16-plan.md P3.1; the values are those of
//! tests/platform/a64-profile.json, which tools/cpu_contract.mjs checks):
//! access rights at EL0 and EL1, reset values, RES0/RES1, and the traps
//! SCTLR_EL1 controls (UCT, UCI, DZE, UMA: EC 0x18). The ID space follows the
//! profile: op0=3, op1=0, CRn=0, CRm=1-7 encodings that are not registers
//! read 0 at EL1; CRm=0 has MIDR, MPIDR, REVIDR only.

use crate::aarch64::cpu::{self, *};
use crate::aarch64::state::*;

/// CNTFRQ_EL0 at reset: the system counter's 1 GHz
pub const CNTFRQ_RESET: u64 = 1_000_000_000;

/// A system register's encoding op0:op1:CRn:CRm:op2 (16 bits, as in MRS/MSR)
pub const fn key(op0: u32, op1: u32, crn: u32, crm: u32, op2: u32) -> u32 {
    op0 << 14 | op1 << 11 | crn << 7 | crm << 3 | op2
}

// the ID registers (the profile's values)
pub const MIDR: u64 = 0x000F_0860;
pub const ID_AA64PFR0: u64 = 0x1100_0000_0100_0011;
pub const ID_AA64DFR0: u64 = 0x0010_1006;
pub const ID_AA64ISAR0: u64 = 0x0001_1120;
pub const ID_AA64MMFR0: u64 = 0x0F00_0022;
pub const CTR: u64 = 0x8444_C004;
pub const CLIDR: u64 = 0x0A20_0023;
pub const CCSIDR: [u64; 3] = [0x700F_E01A, 0x200F_E01A, 0x703F_E07A];

/// Profile v3's AArch32 ID registers (CRm 1-3, op2 0-7: ID_PFR0, PFR1,
/// DFR0, AFR0, MMFR0-3; ISAR0-5, MMFR4, ISAR6; MVFR0-2, -, PFR2, DFR1,
/// MMFR5): the reference's (cortex-a35) for an AArch32 at EL0 only, as
/// Cortex-A76's: no AArch32 EL1 modes (ID_PFR1.ProgMod 0), no SETEND
/// (ID_ISAR1.Endian 0, no mixed endianness), no SMC (ID_ISAR4.SMC 0, no EL3)
pub const AARCH32_ID: [[u64; 8]; 3] = [
    [
        0x0000_0131,
        0x1001_0000,
        0x0000_0006,
        0,
        0x1020_1105,
        0x4000_0000,
        0x0126_0000,
        0x0210_2211,
    ],
    [
        0x0210_1110,
        0x1311_2110,
        0x2123_2042,
        0x0111_2131,
        0x0001_0142,
        0x0001_1121,
        0,
        0,
    ],
    [0x1011_0222, 0x1211_1111, 0x0000_0043, 0, 0, 0, 0, 0],
];

/// SCTLR_EL1 keeps what is written but the MTE controls (ITFSB, TCF0, TCF,
/// ATA0, ATA: FEAT_MTE is not in v1), as the reference does; v86 acts on the
/// bits profile v1 defines
const SCTLR_MTE: u64 = 1 << 37 | 3 << 38 | 3 << 40 | 1 << 42 | 1 << 43;

/// The ISS of a trapped system register access or instruction (EC 0x18)
fn trap_iss(reg: u32, rt: u32, read: bool) -> u32 {
    let op0 = reg >> 14 & 3;
    let op1 = reg >> 11 & 7;
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    op0 << 20 | op2 << 17 | op1 << 14 | crn << 10 | rt << 5 | crm << 1 | read as u32
}

/// The core's MPIDR_EL1 (bit 31 RES1, Aff0 the core)
pub fn mpidr() -> u64 { 0x8000_0000 | crate::isa::current_core() as u64 }

/// The system counter (P3.6: one for the machine, from the machine clock)
pub fn counter() -> u64 { crate::aarch64::timer::counter() }

/// MRS: the value of the register `reg` read by instruction register `rt`
pub fn read(reg: u32, rt: u32) -> Result<u64, Exception> {
    let el = cpu::el();
    let op0 = reg >> 14;
    let op1 = reg >> 11 & 7;
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    if op0 == 3 && op1 == 0 && crn == 0 {
        // the ID space
        if el == 0 {
            return Err(Exception::Undefined);
        }
        return match (crm, op2) {
            (0, 0) => Ok(MIDR),
            (0, 5) => Ok(mpidr()),
            (0, 6) => Ok(0),
            (0, _) => Err(Exception::Undefined),
            // (EL0: AArch64 and AArch32 in profile v3)
            (4, 0) => Ok(if cpu::has_aarch32() { ID_AA64PFR0 & !0xF | 2 } else { ID_AA64PFR0 }),
            (1..=3, _) if cpu::has_aarch32() => Ok(AARCH32_ID[crm as usize - 1][op2 as usize]),
            (5, 0) => Ok(ID_AA64DFR0),
            (6, 0) => Ok(ID_AA64ISAR0),
            (7, 0) => Ok(ID_AA64MMFR0 & !(0xFF << 20) | crate::aarch64::mmu::mmfr0_granules()),
            // ID_AA64MMFR1_EL1: PAN 0b0001 (FEAT_PAN) in v2
            (7, 1) => Ok(if cpu::has_pan() { 1 << 20 } else { 0 }),
            _ => Ok(0),
        };
    }
    let el0_ok =
        |allowed: bool| if el == 0 && !allowed { Err(Exception::Undefined) } else { Ok(()) };
    let trap = |enabled: bool| {
        if el == 0 && !enabled {
            Err(Exception::SystemRegister(trap_iss(reg, rt, true)))
        }
        else {
            Ok(())
        }
    };
    unsafe {
        Ok(match reg {
            // EL0-accessible
            r if r == key(3, 3, 4, 2, 0) => get_nzcv() as u64,
            r if r == key(3, 3, 4, 2, 1) => {
                trap(cpu::sctlr() & SCTLR_UMA != 0)?;
                (get_pstate() & PSTATE_DAIF) as u64
            },
            // (FPCR and FPSR trap as FP instructions do: CPACR_EL1.FPEN)
            r if r == key(3, 3, 4, 4, 0) => {
                crate::aarch64::fp::check_access()?;
                crate::aarch64::fp::fpcr_read()
            },
            r if r == key(3, 3, 4, 4, 1) => {
                crate::aarch64::fp::check_access()?;
                *fpsr as u64
            },
            r if r == key(3, 3, 13, 0, 2) => *tpidr_el0,
            r if r == key(3, 3, 13, 0, 3) => *tpidrro_el0,
            r if r == key(3, 3, 0, 0, 1) => {
                trap(cpu::sctlr() & SCTLR_UCT != 0)?;
                CTR
            },
            r if r == key(3, 3, 0, 0, 7) => {
                // DZP: prohibited at EL0 with SCTLR_EL1.DZE clear
                4 | if el == 0 && cpu::sctlr() & SCTLR_DZE == 0 { 1 << 4 } else { 0 }
            },
            r if (r >> 7) == key(3, 3, 14, 0, 0) >> 7 => {
                return crate::aarch64::timer::read(reg, rt)
            },
            r if r == key(2, 3, 0, 1, 0) => {
                // MDCCSR_EL0 (the debug communications channel: not implemented)
                el0_ok(*mdscr_el1 & 1 << 12 == 0)?;
                0
            },
            _ => {
                el0_ok(false)?;
                read_el1(reg, rt)?
            },
        })
    }
}

unsafe fn read_el1(reg: u32, rt: u32) -> Result<u64, Exception> {
    Ok(match reg {
        // CCSIDR_EL1 of the level and kind CSSELR_EL1 selects (0 for none)
        r if r == key(3, 1, 0, 0, 0) => CCSIDR.get(*csselr_el1 as usize).copied().unwrap_or(0),
        r if r == key(3, 1, 0, 0, 1) => CLIDR,
        r if r == key(3, 1, 0, 0, 7) => 0, // AIDR_EL1
        r if r == key(3, 2, 0, 0, 0) => *csselr_el1,
        r if r == key(3, 0, 1, 0, 0) => *sctlr_el1,
        // PAN (FEAT_PAN)
        r if r == key(3, 0, 4, 2, 3) && cpu::has_pan() => (get_pstate() & PSTATE_PAN) as u64,
        r if r == key(3, 0, 1, 0, 1) => *actlr_el1,
        r if r == key(3, 0, 1, 0, 2) => *cpacr_el1,
        r if r == key(3, 0, 2, 0, 0) => *ttbr0_el1,
        r if r == key(3, 0, 2, 0, 1) => *ttbr1_el1,
        r if r == key(3, 0, 2, 0, 2) => *tcr_el1,
        r if r == key(3, 0, 4, 0, 0) => *spsr_el1,
        r if r == key(3, 0, 4, 0, 1) => *elr_el1,
        r if r == key(3, 0, 4, 1, 0) => {
            // SP_EL0 is not accessible while it is the current SP
            if get_pstate() & PSTATE_SP == 0 {
                return Err(Exception::Undefined);
            }
            cpu::get_sp_el(0)
        },
        r if r == key(3, 0, 4, 2, 0) => (get_pstate() & PSTATE_SP) as u64,
        r if r == key(3, 0, 4, 2, 2) => (get_pstate() & 0xC) as u64, // CurrentEL
        r if r == key(3, 0, 5, 1, 0) => *afsr0_el1,
        r if r == key(3, 0, 5, 1, 1) => *afsr1_el1,
        r if r == key(3, 0, 5, 2, 0) => *esr_el1,
        r if r == key(3, 0, 6, 0, 0) => *far_el1,
        r if r == key(3, 0, 7, 4, 0) => *par_el1,
        r if r == key(3, 0, 10, 2, 0) => *mair_el1,
        r if r == key(3, 0, 10, 3, 0) => *amair_el1,
        r if r == key(3, 0, 12, 0, 0) => *vbar_el1,
        r if r == key(3, 0, 12, 0, 1) => 0, // RVBAR_EL1
        r if r == key(3, 0, 12, 1, 0) => crate::aarch64::gic::isr_el1(),
        r if r == key(3, 0, 13, 0, 1) => *contextidr_el1,
        r if r == key(3, 0, 13, 0, 4) => *tpidr_el1,
        r if r == key(3, 0, 14, 1, 0) => *cntkctl_el1,
        // the GIC CPU interface (P3.5)
        r if crate::aarch64::gic::is_icc(r) => return crate::aarch64::gic::icc_read(r),
        // debug (P3.8)
        r if r >> 14 == 2 => return crate::aarch64::debug::read(r, rt),
        _ => return Err(Exception::Undefined),
    })
}

/// MSR (register): write `value` to the register `reg`
pub fn write(reg: u32, rt: u32, value: u64) -> Result<(), Exception> {
    let el = cpu::el();
    let op0 = reg >> 14;
    if op0 == 3 && reg >> 7 & 0x7F == 0 && reg >> 11 & 7 == 0 {
        // the ID space (op1 = 0, CRn = 0): read-only
        return Err(Exception::Undefined);
    }
    let trap = |enabled: bool| {
        if el == 0 && !enabled {
            Err(Exception::SystemRegister(trap_iss(reg, rt, false)))
        }
        else {
            Ok(())
        }
    };
    unsafe {
        match reg {
            r if r == key(3, 3, 4, 2, 0) => set_nzcv(value as u32),
            r if r == key(3, 3, 4, 2, 1) => {
                trap(cpu::sctlr() & SCTLR_UMA != 0)?;
                set_pstate(get_pstate() & !PSTATE_DAIF | value as u32 & PSTATE_DAIF);
            },
            r if r == key(3, 3, 4, 4, 0) => {
                crate::aarch64::fp::check_access()?;
                crate::aarch64::fp::fpcr_write(value)
            },
            r if r == key(3, 3, 4, 4, 1) => {
                crate::aarch64::fp::check_access()?;
                *fpsr = value as u32 & 0xF800_009F
            },
            r if r == key(3, 3, 13, 0, 2) => *tpidr_el0 = value,
            r if (r >> 7) == key(3, 3, 14, 0, 0) >> 7 => {
                return crate::aarch64::timer::write(reg, rt, value)
            },
            _ if el == 0 => return Err(Exception::Undefined),
            r if r == key(3, 3, 13, 0, 3) => *tpidrro_el0 = value,
            r if r == key(3, 2, 0, 0, 0) => *csselr_el1 = value & 0x1F,
            r if r == key(3, 0, 1, 0, 0) => {
                *sctlr_el1 = value & !SCTLR_MTE;
                crate::aarch64::mmu::regime_changed();
            },
            r if r == key(3, 0, 1, 0, 1) => *actlr_el1 = value,
            r if r == key(3, 0, 1, 0, 2) => *cpacr_el1 = value & 3 << 20,
            r if r == key(3, 0, 2, 0, 0) => {
                *ttbr0_el1 = value;
                crate::aarch64::mmu::ttbr_changed();
            },
            r if r == key(3, 0, 2, 0, 1) => {
                *ttbr1_el1 = value;
                crate::aarch64::mmu::ttbr_changed();
            },
            r if r == key(3, 0, 2, 0, 2) => {
                *tcr_el1 = value;
                crate::aarch64::mmu::regime_changed();
            },
            // NZCV, SS, DAIF, M; PAN with FEAT_PAN; in profile v3 AArch32's
            // Q, IT and GE too, and IL (which v1 and v2 drop, as they always did)
            r if r == key(3, 0, 4, 0, 0) => {
                let a32 = if cpu::has_aarch32() {
                    (PSTATE_Q | PSTATE_IT | PSTATE_GE | PSTATE_IL) as u64
                }
                else {
                    0
                };
                *spsr_el1 =
                    value & (0xF060_03FF | a32 | if cpu::has_pan() { PSTATE_PAN as u64 } else { 0 })
            },
            r if r == key(3, 0, 4, 2, 3) && cpu::has_pan() => {
                set_pstate(get_pstate() & !PSTATE_PAN | value as u32 & PSTATE_PAN)
            },
            r if r == key(3, 0, 4, 0, 1) => *elr_el1 = value,
            r if r == key(3, 0, 4, 1, 0) => {
                if get_pstate() & PSTATE_SP == 0 {
                    return Err(Exception::Undefined);
                }
                cpu::set_sp_el(0, value)
            },
            r if r == key(3, 0, 4, 2, 0) => {
                set_pstate(get_pstate() & !PSTATE_SP | value as u32 & PSTATE_SP)
            },
            r if r == key(3, 0, 5, 1, 0) => *afsr0_el1 = value,
            r if r == key(3, 0, 5, 1, 1) => *afsr1_el1 = value,
            r if r == key(3, 0, 5, 2, 0) => *esr_el1 = value & 0xFFFF_FFFF,
            r if r == key(3, 0, 6, 0, 0) => *far_el1 = value,
            r if r == key(3, 0, 7, 4, 0) => *par_el1 = value,
            r if r == key(3, 0, 10, 2, 0) => {
                *mair_el1 = value;
                crate::aarch64::mmu::regime_changed();
            },
            r if r == key(3, 0, 10, 3, 0) => *amair_el1 = value,
            r if r == key(3, 0, 12, 0, 0) => *vbar_el1 = value & !0x7FF,
            r if r == key(3, 0, 13, 0, 1) => {
                *contextidr_el1 = value & 0xFFFF_FFFF;
            },
            r if r == key(3, 0, 13, 0, 4) => *tpidr_el1 = value,
            r if r == key(3, 0, 14, 1, 0) => *cntkctl_el1 = value & 0x3FF,
            r if crate::aarch64::gic::is_icc(r) => return crate::aarch64::gic::icc_write(r, value),
            r if r >> 14 == 2 => return crate::aarch64::debug::write(r, rt, value),
            _ => return Err(Exception::Undefined),
        }
    }
    Ok(())
}

/// MSR (immediate): SPSel (0), DAIFSet (1), DAIFClr (2), PAN (3, FEAT_PAN)
pub fn write_pstate_field(field: u8, imm: u32) -> Result<(), Exception> {
    let el = cpu::el();
    match field {
        0 => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
            set_pstate(get_pstate() & !PSTATE_SP | imm & 1);
        },
        3 => {
            if el == 0 || !cpu::has_pan() {
                return Err(Exception::Undefined);
            }
            set_pstate(get_pstate() & !PSTATE_PAN | if imm & 1 != 0 { PSTATE_PAN } else { 0 });
        },
        _ => {
            if el == 0 && cpu::sctlr() & SCTLR_UMA == 0 {
                // (the trap reports the instruction's own encoding: op0 0, op1 3, CRn 4, CRm the
                // immediate, op2 6 for DAIFSet and 7 for DAIFClr, Rt 31; the reference swaps op1 and op2)
                let op2 = if field == 1 { 6 } else { 7 };
                let reg = key(0, 3, 4, imm & 15, op2);
                return Err(Exception::SystemRegister(trap_iss(reg, 31, false)));
            }
            let bits = (imm & 0xF) << 6;
            if field == 1 {
                set_pstate(get_pstate() | bits);
            }
            else {
                set_pstate(get_pstate() & !bits);
            }
        },
    }
    Ok(())
}

/// SYS: a cache, TLB or address translation operation (`op` = op1:CRn:CRm:op2)
pub fn sys(op: u32, rt: u32) -> Result<(), Exception> {
    let el = cpu::el();
    let op1 = op >> 11 & 7;
    let crn = op >> 7 & 15;
    let crm = op >> 3 & 15;
    let op2 = op & 7;
    let reg = 1 << 14 | op;
    let trap = |enabled: bool| {
        if el == 0 && !enabled {
            Err(Exception::SystemRegister(trap_iss(reg, rt, false)))
        }
        else {
            Ok(())
        }
    };
    let value = cpu::xr(rt);
    match (op1, crn, crm, op2) {
        // instruction cache: v86 needs none of it (code retires on writes);
        // with cores in workers the inner shareable ones make the next DSB
        // wait until the others took the code invalidations (P8.3)
        (0, 7, 1, 0) | (0, 7, 5, 0) => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
            if crm == 1 {
                crate::aarch64::tlb::post_code();
            }
        },
        (3, 7, 5, 1) => {
            trap(cpu::sctlr() & SCTLR_UCI != 0)?;
            crate::aarch64::mmu::check_cache_maintenance(value)?;
            crate::aarch64::tlb::post_code();
        },
        // data cache by VA: checked as a read (a translation or permission fault), no effect
        (0, 7, 6, 1) => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
            crate::aarch64::mmu::check_cache_maintenance(value)?;
        },
        (3, 7, 10, 1) | (3, 7, 11, 1) | (3, 7, 14, 1) => {
            trap(cpu::sctlr() & SCTLR_UCI != 0)?;
            crate::aarch64::mmu::check_cache_maintenance(value)?;
        },
        // by set/way
        (0, 7, 6, 2) | (0, 7, 10, 2) | (0, 7, 14, 2) => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
        },
        (3, 7, 4, 1) => {
            trap(cpu::sctlr() & SCTLR_DZE != 0)?;
            crate::aarch64::execute::dc_zva(value, rt)?;
        },
        // address translation (P3.4)
        (0, 7, 8, 0..=3) => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
            crate::aarch64::mmu::address_translate(op2, value)?;
        },
        // TLB maintenance (P3.4)
        (0, 8, 3, 0..=3)
        | (0, 8, 3, 5)
        | (0, 8, 3, 7)
        | (0, 8, 7, 0..=3)
        | (0, 8, 7, 5)
        | (0, 8, 7, 7) => {
            if el == 0 {
                return Err(Exception::Undefined);
            }
            crate::aarch64::mmu::tlbi(crm == 3, op2, value);
        },
        _ => return Err(Exception::Undefined),
    }
    Ok(())
}
                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/rust/aarch64/t32.rs                                                                  0000644 0000000 0000000 00000140031 00000000000 013655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! T32 (Thumb-2) at EL0 (docs/aarch32-plan.md Q3): the decoder of the 16-bit
//! and 32-bit encodings onto a32.rs's operations, and ITSTATE (IT blocks).
//! The PC reads as the instruction's address + 4 (literals: aligned down to
//! a word); a 32-bit instruction is (first halfword) << 16 | second. The
//! 16-bit data processing instructions set the flags outside an IT block.

use crate::aarch64::a32::*;
use crate::aarch64::cpu::*;
use crate::aarch64::execute::Flow;

// ---- ITSTATE

/// ITSTATE (IT[7:0]: the base condition in 7:5, the mask in 4:0)
#[inline(always)]
pub fn itstate() -> u32 {
    let p = get_pstate();
    (p >> 25 & 3) | (p >> 10 & 0x3F) << 2
}

#[inline(always)]
fn set_itstate(it: u32) { set_pstate_bits(PSTATE_IT, (it & 3) << 25 | (it >> 2 & 0x3F) << 10) }

/// Whether an instruction runs in an IT block
#[inline(always)]
pub fn in_it_block() -> bool { itstate() & 0xF != 0 }

/// Whether the instruction is the last of its IT block (or outside one)
#[inline(always)]
fn last_in_it_block() -> bool { itstate() & 0xF == 0b1000 || !in_it_block() }

/// The condition of the instruction in the IT block (AL outside)
#[inline(always)]
fn it_condition() -> u32 {
    if in_it_block() {
        itstate() >> 4
    }
    else {
        0b1110
    }
}

/// The IT instruction set ITSTATE: the instruction after it is the block's first
static mut IT_JUST_SET: bool = false;

/// ITAdvance, after each T32 instruction that executed (or was skipped by
/// its condition), but the IT instruction itself
pub fn it_advance() {
    if unsafe { IT_JUST_SET } {
        unsafe { IT_JUST_SET = false };
        return;
    }
    let it = itstate();
    if it == 0 {
        return;
    }
    if it & 7 == 0 {
        set_itstate(0);
    }
    else {
        set_itstate(it & 0xE0 | it << 1 & 0x1F);
    }
}

// ---- operands

/// A T32 register read: the PC as the instruction's address + 4
#[inline(always)]
fn read(n: u32, pc: u32) -> u32 {
    if n == 15 {
        pc.wrapping_add(4)
    }
    else {
        reg(n)
    }
}

/// ThumbExpandImm_C: the value of i:imm3:imm8 and the carry out
fn expand_imm_c(imm12: u32, carry_in: bool) -> (u32, bool) {
    if imm12 >> 10 == 0 {
        let b = imm12 & 0xFF;
        let value = match imm12 >> 8 & 3 {
            0 => b,
            1 => b << 16 | b,
            2 => b << 24 | b << 8,
            _ => b << 24 | b << 16 | b << 8 | b,
        };
        (value, carry_in)
    }
    else {
        let value = (0x80 | imm12 & 0x7F).rotate_right(imm12 >> 7);
        (value, value >> 31 != 0)
    }
}

/// A branch, BranchWritePC: in T32 (bit 0 cleared)
#[inline(always)]
fn jump(target: u32) -> Flow { Flow::Jump((target & !1) as u64) }

/// An UNPREDICTABLE register use (SP or PC where they are not allowed): UNDEFINED
#[inline(always)]
fn bad(r: u32) -> bool { r == 13 || r == 15 }

// ---- one instruction

/// An instruction of T32 at `pc` (`length` 2 or 4)
pub fn execute(word: u32, length: u32, pc: u32) -> Result<Flow, Exception> {
    unsafe { IT_JUST_SET = false };
    let cond = it_condition();
    // (BKPT and HLT run whatever their condition)
    if !condition_passed(cond) && !(length == 2 && (word >> 8 == 0xBE || word >> 6 == 0x2EA)) {
        return Ok(Flow::Next);
    }
    if length == 2 {
        t16(word, pc, cond)
    }
    else {
        t32(word, pc, cond)
    }
}

// ---- 16-bit

fn t16(hw: u32, pc: u32, cond: u32) -> Result<Flow, Exception> {
    let s = !in_it_block();
    match hw >> 10 {
        // shift (immediate), add, subtract, move, compare
        0b000000..=0b001111 => {
            let rd = hw & 7;
            let rn = hw >> 3 & 7;
            match hw >> 11 {
                0b000 | 0b001 | 0b010 => {
                    let op = hw >> 11;
                    let imm5 = hw >> 6 & 31;
                    if op == 0 && imm5 == 0 {
                        // MOVS Rd, Rm (T2): UNPREDICTABLE in an IT block
                        if !s {
                            return Err(Exception::Undefined);
                        }
                        return data_processing(DP_MOV, true, rd, 0, reg(rn), carry());
                    }
                    let (kind, amount) = decode_imm_shift(op, imm5);
                    let (value, c) = shift_c(reg(rn), kind, amount, carry());
                    data_processing(DP_MOV, s, rd, 0, value, c)
                },
                0b011 => {
                    let operand = if hw & 1 << 10 != 0 { hw >> 6 & 7 } else { reg(hw >> 6 & 7) };
                    let op = if hw & 1 << 9 != 0 { DP_SUB } else { DP_ADD };
                    data_processing(op, s, rd, reg(rn), operand, carry())
                },
                op => {
                    let rdn = hw >> 8 & 7;
                    let imm8 = hw & 0xFF;
                    match op {
                        0b100 => data_processing(DP_MOV, s, rdn, 0, imm8, carry()),
                        0b101 => data_processing(DP_CMP, true, 0, reg(rdn), imm8, carry()),
                        0b110 => data_processing(DP_ADD, s, rdn, reg(rdn), imm8, carry()),
                        _ => data_processing(DP_SUB, s, rdn, reg(rdn), imm8, carry()),
                    }
                },
            }
        },
        // data processing (register)
        0b010000 => {
            let rdn = hw & 7;
            let rm = hw >> 3 & 7;
            let (n, m) = (reg(rdn), reg(rm));
            match hw >> 6 & 15 {
                0b0000 => data_processing(DP_AND, s, rdn, n, m, carry()),
                0b0001 => data_processing(DP_EOR, s, rdn, n, m, carry()),
                op @ (0b0010 | 0b0011 | 0b0100 | 0b0111) => {
                    let kind = match op {
                        0b0010 => SHIFT_LSL,
                        0b0011 => SHIFT_LSR,
                        0b0100 => SHIFT_ASR,
                        _ => SHIFT_ROR,
                    };
                    let (value, c) = shift_c(n, kind, m & 0xFF, carry());
                    data_processing(DP_MOV, s, rdn, 0, value, c)
                },
                0b0101 => data_processing(DP_ADC, s, rdn, n, m, carry()),
                0b0110 => data_processing(DP_SBC, s, rdn, n, m, carry()),
                0b1000 => data_processing(DP_TST, true, 0, n, m, carry()),
                0b1001 => data_processing(DP_RSB, s, rdn, m, 0, carry()),
                0b1010 => data_processing(DP_CMP, true, 0, n, m, carry()),
                0b1011 => data_processing(DP_CMN, true, 0, n, m, carry()),
                0b1100 => data_processing(DP_ORR, s, rdn, n, m, carry()),
                0b1101 => multiply(0, s, rdn, m, n, 0),
                0b1110 => data_processing(DP_BIC, s, rdn, n, m, carry()),
                _ => data_processing(DP_MVN, s, rdn, 0, m, carry()),
            }
        },
        // special data processing, branch and exchange
        0b010001 => {
            let rdn = (hw >> 4 & 8) | hw & 7;
            let rm = hw >> 3 & 15;
            match hw >> 8 & 3 {
                0 => {
                    if rdn == 15 && rm == 15 {
                        return Err(Exception::Undefined);
                    }
                    let result = read(rdn, pc).wrapping_add(read(rm, pc));
                    if rdn == 15 {
                        if !last_in_it_block() {
                            return Err(Exception::Undefined);
                        }
                        return Ok(jump(result));
                    }
                    set_reg(rdn, result);
                    Ok(Flow::Next)
                },
                1 => {
                    if rdn < 8 && rm < 8 || rdn == 15 || rm == 15 {
                        return Err(Exception::Undefined);
                    }
                    data_processing(DP_CMP, true, 0, reg(rdn), reg(rm), carry())
                },
                2 => {
                    let value = read(rm, pc);
                    if rdn == 15 {
                        if !last_in_it_block() {
                            return Err(Exception::Undefined);
                        }
                        return Ok(jump(value));
                    }
                    set_reg(rdn, value);
                    Ok(Flow::Next)
                },
                _ => {
                    if hw & 7 != 0 || !last_in_it_block() {
                        return Err(Exception::Undefined);
                    }
                    let target = read(rm, pc);
                    if hw & 1 << 7 != 0 {
                        // BLX (register): the return address in T32
                        if rm == 15 {
                            return Err(Exception::Undefined);
                        }
                        set_reg(14, pc.wrapping_add(2) | 1);
                    }
                    Ok(bx_write_pc(target))
                },
            }
        },
        // LDR (literal)
        0b010010 | 0b010011 => {
            let address = (pc.wrapping_add(4) & !3).wrapping_add((hw & 0xFF) << 2);
            load_register(hw >> 8 & 7, address, 4, false, 0, None, false)
        },
        // loads and stores (register offset)
        0b010100..=0b010111 => {
            let rt = hw & 7;
            let address = reg(hw >> 3 & 7).wrapping_add(reg(hw >> 6 & 7));
            match hw >> 9 & 7 {
                0 => store_register(reg(rt), address, 4, 0, None, false),
                1 => store_register(reg(rt), address, 2, 0, None, false),
                2 => store_register(reg(rt), address, 1, 0, None, false),
                3 => load_register(rt, address, 1, true, 0, None, false),
                4 => load_register(rt, address, 4, false, 0, None, false),
                5 => load_register(rt, address, 2, false, 0, None, false),
                6 => load_register(rt, address, 1, false, 0, None, false),
                _ => load_register(rt, address, 2, true, 0, None, false),
            }
        },
        // loads and stores (immediate): word, byte, halfword, SP-relative
        0b011000..=0b100111 => {
            let rt = hw & 7;
            let imm5 = hw >> 6 & 31;
            let load = hw & 1 << 11 != 0;
            let (size, address, rt) = match hw >> 12 {
                0b0110 => (4, reg(hw >> 3 & 7).wrapping_add(imm5 << 2), rt),
                0b0111 => (1, reg(hw >> 3 & 7).wrapping_add(imm5), rt),
                0b1000 => (2, reg(hw >> 3 & 7).wrapping_add(imm5 << 1), rt),
                _ => (4, reg(13).wrapping_add((hw & 0xFF) << 2), hw >> 8 & 7),
            };
            if load {
                load_register(rt, address, size, false, 0, None, false)
            }
            else {
                store_register(reg(rt), address, size, 0, None, false)
            }
        },
        // ADR, ADD (SP plus immediate)
        0b101000..=0b101011 => {
            let imm = (hw & 0xFF) << 2;
            let base = if hw & 1 << 11 != 0 { reg(13) } else { pc.wrapping_add(4) & !3 };
            set_reg(hw >> 8 & 7, base.wrapping_add(imm));
            Ok(Flow::Next)
        },
        0b101100..=0b101111 => t16_miscellaneous(hw, pc, cond),
        // STM, LDM (IA, writeback; LDM's not with the base in the list)
        0b110000..=0b110011 => {
            let rn = hw >> 8 & 7;
            let list = hw & 0xFF;
            if list == 0 {
                return Err(Exception::Undefined);
            }
            let base = reg(rn);
            let new_base = base.wrapping_add(4 * list.count_ones());
            if hw & 1 << 11 != 0 {
                load_multiple(
                    rn,
                    list,
                    base,
                    if list & 1 << rn == 0 { Some(new_base) } else { None },
                )
            }
            else {
                // (the base in the list but not lowest: UNKNOWN; its value before the writeback here)
                store_multiple(rn, list, base, Some(new_base), 0)
            }
        },
        // B<cond>, UDF, SVC
        0b110100..=0b110111 => {
            let c = hw >> 8 & 15;
            match c {
                0b1110 => Err(Exception::Undefined),
                0b1111 => Err(Exception::Svc((hw & 0xFF) as u16)),
                _ => {
                    if in_it_block() {
                        return Err(Exception::Undefined);
                    }
                    if !condition_passed(c) {
                        return Ok(Flow::Next);
                    }
                    let offset = ((hw << 24) as i32 >> 23) as u32;
                    Ok(jump(pc.wrapping_add(4).wrapping_add(offset)))
                },
            }
        },
        // B: imm11 << 1 from the PC + 4
        0b111000 | 0b111001 => {
            if !last_in_it_block() {
                return Err(Exception::Undefined);
            }
            let offset = ((hw << 21) as i32 >> 20) as u32;
            Ok(jump(pc.wrapping_add(4).wrapping_add(offset)))
        },
        _ => Err(Exception::Undefined),
    }
}

/// The 16-bit miscellaneous instructions (1011 xxxx)
fn t16_miscellaneous(hw: u32, pc: u32, cond: u32) -> Result<Flow, Exception> {
    match hw >> 8 & 15 {
        // ADD, SUB (SP plus immediate)
        0b0000 => {
            let imm = (hw & 0x7F) << 2;
            let sp = reg(13);
            set_reg(
                13,
                if hw & 0x80 != 0 { sp.wrapping_sub(imm) } else { sp.wrapping_add(imm) },
            );
            Ok(Flow::Next)
        },
        // CBZ, CBNZ: i:imm5:'0' forward
        0b0001 | 0b0011 | 0b1001 | 0b1011 => {
            if in_it_block() {
                return Err(Exception::Undefined);
            }
            let zero = reg(hw & 7) == 0;
            let nonzero = hw & 1 << 11 != 0;
            if zero != nonzero {
                let offset = (hw >> 3 & 0x40) | (hw >> 2 & 0x3E);
                return Ok(jump(pc.wrapping_add(4).wrapping_add(offset)));
            }
            Ok(Flow::Next)
        },
        // SXTH, SXTB, UXTH, UXTB
        0b0010 => {
            let rd = hw & 7;
            let m = reg(hw >> 3 & 7);
            match hw >> 6 & 3 {
                0 => extend(rd, None, m, 0, 16, true, false),
                1 => extend(rd, None, m, 0, 8, true, false),
                2 => extend(rd, None, m, 0, 16, false, false),
                _ => extend(rd, None, m, 0, 8, false, false),
            }
        },
        // PUSH {list, LR}: STMDB SP!
        0b0100 | 0b0101 => {
            let list = (hw & 0xFF) | (hw & 0x100) << 6;
            if list == 0 {
                return Err(Exception::Undefined);
            }
            let sp = reg(13);
            let start = sp.wrapping_sub(4 * list.count_ones());
            store_multiple(13, list, start, Some(start), 0)
        },
        // SETEND, CPS: UNDEFINED (big endian is not here) and a NOP at EL0
        0b0110 => {
            if hw & 0xFFE8 == 0xB660 {
                if in_it_block() {
                    return Err(Exception::Undefined);
                }
                if a32_only() {
                    // (im bit 4: disable)
                    crate::aarch64::a32_system::cps(2 | hw >> 4 & 1, hw & 7, false, 0);
                }
                return Ok(Flow::Next);
            }
            Err(Exception::Undefined)
        },
        // REV, REV16, REVSH
        0b1010 => {
            let rd = hw & 7;
            let m = reg(hw >> 3 & 7);
            match hw >> 6 & 3 {
                0 => bit_op(0, rd, m),
                1 => bit_op(1, rd, m),
                3 => bit_op(2, rd, m),
                // (HLT: no halting debug)
                _ => Err(Exception::Undefined),
            }
        },
        // POP {list, PC}: LDMIA SP!
        0b1100 | 0b1101 => {
            let list = (hw & 0xFF) | (hw & 0x100) << 7;
            if list == 0 || list & 1 << 15 != 0 && !last_in_it_block() {
                return Err(Exception::Undefined);
            }
            let sp = reg(13);
            load_multiple(13, list, sp, Some(sp.wrapping_add(4 * list.count_ones())))
        },
        // BKPT
        0b1110 => Err(Exception::Trapped32 {
            ec: 0x38,
            iss: hw & 0xFF,
        }),
        // IT, hints
        0b1111 => {
            if hw & 15 != 0 {
                // IT: firstcond:mask (UNPREDICTABLE in a block, or with cond 1111, or AL with a mask bit set)
                let first = hw >> 4 & 15;
                if in_it_block() || first == 15 || first == 14 && (hw & 15).count_ones() != 1 {
                    if in_it_block() && crate::aarch64::cpu::el() == 0 {
                        crate::aarch64::jit::pages::a32_trace_dump("IT in an IT block");
                    }
                    return Err(Exception::Undefined);
                }
                set_itstate(hw & 0xFF);
                unsafe { IT_JUST_SET = true };
                return Ok(Flow::Next);
            }
            let _ = pc;
            hint(hw >> 4 & 15, cond)
        },
        _ => Err(Exception::Undefined),
    }
}

// ---- 32-bit

fn t32(word: u32, pc: u32, cond: u32) -> Result<Flow, Exception> {
    let hw1 = word >> 16;
    let hw2 = word & 0xFFFF;
    match hw1 >> 11 {
        0b11101 => {
            if hw1 & 1 << 10 != 0 {
                return t32_coprocessor(hw1, hw2, pc, cond);
            }
            if hw1 & 1 << 9 == 0 {
                if hw1 & 1 << 6 == 0 {
                    t32_block_transfer(hw1, hw2, pc)
                }
                else {
                    t32_dual_exclusive(hw1, hw2, pc)
                }
            }
            else {
                t32_shifted_register(hw1, hw2)
            }
        },
        0b11110 => {
            if hw2 & 1 << 15 == 0 {
                if hw1 & 1 << 9 == 0 {
                    t32_modified_immediate(hw1, hw2)
                }
                else {
                    t32_plain_immediate(hw1, hw2, pc)
                }
            }
            else {
                t32_branch_control(hw1, hw2, pc, cond)
            }
        },
        _ => match hw1 >> 9 & 3 {
            // (1111 1001 xxx0: Advanced SIMD's loads and stores, A32's 1111 0100)
            0 if word & 0xFF10_0000 == 0xF900_0000 => {
                crate::aarch64::a32_simd::load_store(word & 0x00FF_FFFF | 0xF400_0000)
            },
            0 => t32_load_store(hw1, hw2, pc),
            // (1111 1010: data processing (register); 1111 1011: the multiplies)
            1 => {
                if hw1 & 1 << 8 != 0 {
                    t32_multiply(hw1, hw2)
                }
                else {
                    t32_data_register(hw1, hw2)
                }
            },
            // (1111 11xx: coprocessor, Advanced SIMD and floating point)
            _ => t32_coprocessor(hw1, hw2, pc, cond),
        },
    }
}

/// LDM, STM, LDMDB, STMDB (1110 100x x0xx)
fn t32_block_transfer(hw1: u32, hw2: u32, pc: u32) -> Result<Flow, Exception> {
    let op = hw1 >> 7 & 3;
    let w = hw1 & 1 << 5 != 0;
    let l = hw1 & 1 << 4 != 0;
    let rn = hw1 & 15;
    let list = hw2;
    if (op == 0 || op == 3) && crate::aarch64::a32_system::privileged() {
        // SRS (to SP: Rn 13, the mode in the list's bits 4:0), RFE (DB op 0, IA op 3)
        let (p, u) = (op == 0, op == 3);
        if l {
            if list != 0xC000 || !last_in_it_block() {
                return Err(Exception::Undefined);
            }
            return crate::aarch64::a32_system::rfe(p, u, w, rn);
        }
        if rn != 13 || list & 0xFFE0 != 0xC000 {
            return Err(Exception::Undefined);
        }
        return crate::aarch64::a32_system::srs(p, u, w, list & 31);
    }
    if op == 0 || op == 3 || rn == 15 || list == 0 || list & 1 << 13 != 0 {
        // (SRS, RFE: UNDEFINED at EL0; no register, SP in the list: UNPREDICTABLE.
        // One register is CONSTRAINED UNPREDICTABLE: it is transferred, as
        // Cortex-A cores and the Android emulator's QEMU do, where QEMU 9.2
        // takes it as UNDEFINED; Android 7.1's YouTube runs LDM.W R8!, {R0})
        return Err(Exception::Undefined);
    }
    if l && list & 0xC000 == 0xC000 || !l && list & 0x8000 != 0 || w && list & 1 << rn != 0 {
        return Err(Exception::Undefined);
    }
    if l && list & 1 << 15 != 0 && !last_in_it_block() {
        return Err(Exception::Undefined);
    }
    let count = list.count_ones();
    let base = reg(rn);
    let (start, new_base) = if op == 1 {
        (base, base.wrapping_add(4 * count))
    }
    else {
        let start = base.wrapping_sub(4 * count);
        (start, start)
    };
    let writeback = if w { Some(new_base) } else { None };
    let _ = pc;
    if l {
        load_multiple(rn, list, start, writeback)
    }
    else {
        store_multiple(rn, list, start, writeback, 0)
    }
}

/// LDRD, STRD, the exclusives, load-acquire/store-release, TBB/TBH (1110 100x x1xx)
fn t32_dual_exclusive(hw1: u32, hw2: u32, pc: u32) -> Result<Flow, Exception> {
    let rn = hw1 & 15;
    let rt = hw2 >> 12 & 15;
    let l = hw1 & 1 << 4 != 0;
    let p = hw1 & 1 << 8 != 0;
    let w = hw1 & 1 << 5 != 0;
    let u = hw1 & 1 << 7 != 0;
    if p || w {
        // LDRD, STRD (immediate, literal)
        let rt2 = hw2 >> 8 & 15;
        let imm = (hw2 & 0xFF) << 2;
        if bad(rt) || bad(rt2) || l && rt == rt2 || w && (rn == rt || rn == rt2 || rn == 15) {
            return Err(Exception::Undefined);
        }
        let base = if rn == 15 { pc.wrapping_add(4) & !3 } else { reg(rn) };
        let offset_address = if u { base.wrapping_add(imm) } else { base.wrapping_sub(imm) };
        let address = if p { offset_address } else { base };
        let writeback = if w { Some(offset_address) } else { None };
        return if l {
            load_dual(rt, rt2, address, rn, writeback)
        }
        else {
            store_dual(reg(rt), reg(rt2), address, rn, writeback)
        };
    }
    match hw1 >> 4 & 0xF {
        // STREX, LDREX: Rn + imm8 << 2
        0b0100 | 0b0101 => {
            let address = reg(rn).wrapping_add((hw2 & 0xFF) << 2);
            let rd = hw2 >> 8 & 15;
            if rn == 15 || bad(rt) || !l && (bad(rd) || rd == rn || rd == rt) {
                return Err(Exception::Undefined);
            }
            if l && rd != 15 {
                return Err(Exception::Undefined);
            }
            exclusive(l, 2, false, rt, 0, rd, address, pc)
        },
        // TBB, TBH, the byte, halfword and doubleword exclusives, LDA/STL
        0b1100 | 0b1101 => {
            let op = hw2 >> 4 & 15;
            let rt2 = hw2 >> 8 & 15;
            let rd = hw2 & 15;
            match op {
                0b0000 | 0b0001 if l => {
                    // TBB, TBH: a table of forward offsets (halfwords) at Rn + Rm (Rm * 2)
                    let rm = hw2 & 15;
                    if bad(rm) || rn == 13 || !last_in_it_block() {
                        return Err(Exception::Undefined);
                    }
                    let base = read(rn, pc);
                    let halfwords = op == 1;
                    let address = base.wrapping_add(if halfwords { reg(rm) << 1 } else { reg(rm) });
                    let entry = load(address, if halfwords { 2 } else { 1 }, false)?;
                    Ok(jump(pc.wrapping_add(4).wrapping_add(entry * 2)))
                },
                0b0100 | 0b0101 | 0b0111 => {
                    let size = [0, 1, 0, 3][(op & 3) as usize];
                    if rn == 15 || bad(rt) || size == 3 && (bad(rt2) || l && rt == rt2) {
                        return Err(Exception::Undefined);
                    }
                    if l {
                        if rd != 15 || size != 3 && rt2 != 15 {
                            return Err(Exception::Undefined);
                        }
                    }
                    else if bad(rd) || rd == rn || rd == rt || size == 3 && rd == rt2 {
                        return Err(Exception::Undefined);
                    }
                    exclusive(l, size, false, rt, rt2, rd, reg(rn), pc)
                },
                0b1000..=0b1111 => {
                    // LDA*/STL* (8-10), LDAEX*/STLEX* (12-15)
                    let size = op & 3;
                    if rn == 15 || bad(rt) {
                        return Err(Exception::Undefined);
                    }
                    if op & 4 == 0 {
                        if size == 3 || rt2 != 15 || rd != 15 {
                            return Err(Exception::Undefined);
                        }
                        return acquire_release(l, 1 << size, rt, reg(rn));
                    }
                    let size = [0, 1, 2, 3][size as usize];
                    if size == 3 && (bad(rt2) || l && rt == rt2) || size != 3 && rt2 != 15 {
                        return Err(Exception::Undefined);
                    }
                    if l && rd != 15
                        || !l && (bad(rd) || rd == rn || rd == rt || size == 3 && rd == rt2)
                    {
                        return Err(Exception::Undefined);
                    }
                    exclusive(l, size, true, rt, rt2, rd, reg(rn), pc)
                },
                _ => Err(Exception::Undefined),
            }
        },
        _ => Err(Exception::Undefined),
    }
}

/// The data processing operations of T32's 32-bit encodings by their op
/// (bits 8:5 of the first halfword): A32's, None for none
fn t32_op(op: u32) -> Option<u32> {
    match op {
        0b0000 => Some(DP_AND),
        0b0001 => Some(DP_BIC),
        0b0010 => Some(DP_ORR),
        0b0011 => Some(DP_ORN),
        0b0100 => Some(DP_EOR),
        0b1000 => Some(DP_ADD),
        0b1010 => Some(DP_ADC),
        0b1011 => Some(DP_SBC),
        0b1101 => Some(DP_SUB),
        0b1110 => Some(DP_RSB),
        _ => None,
    }
}

/// A data processing operation of T32's: TST, TEQ, CMN, CMP for Rd = PC with
/// S; MOV and MVN for ORR, ORN with Rn = PC
fn t32_data(op: u32, s: bool, rd: u32, rn: u32, operand: u32, c: bool) -> Result<Flow, Exception> {
    let Some(mut dp) = t32_op(op)
    else {
        return Err(Exception::Undefined);
    };
    if rd == 15 && s {
        dp = match dp {
            DP_AND => DP_TST,
            DP_EOR => DP_TEQ,
            DP_ADD => DP_CMN,
            DP_SUB => DP_CMP,
            _ => return Err(Exception::Undefined),
        };
        return data_processing(dp, true, 0, reg(rn), operand, c);
    }
    if rn == 15 {
        dp = match dp {
            DP_ORR => DP_MOV,
            DP_ORN => DP_MVN,
            _ => return Err(Exception::Undefined),
        };
        if bad(rd) {
            return Err(Exception::Undefined);
        }
        return data_processing(dp, s, rd, 0, operand, c);
    }
    // (SP: ADD and SUB only, into SP or not; other operations UNPREDICTABLE)
    if rd == 15
        || rn == 13 && dp != DP_ADD && dp != DP_SUB
        || rd == 13 && !(rn == 13 && (dp == DP_ADD || dp == DP_SUB))
    {
        return Err(Exception::Undefined);
    }
    data_processing(dp, s, rd, reg(rn), operand, c)
}

/// Data processing (shifted register), PKHBT, PKHTB (1110 101x)
fn t32_shifted_register(hw1: u32, hw2: u32) -> Result<Flow, Exception> {
    let op = hw1 >> 5 & 15;
    let s = hw1 & 1 << 4 != 0;
    let rn = hw1 & 15;
    let rd = hw2 >> 8 & 15;
    let rm = hw2 & 15;
    let imm5 = (hw2 >> 10 & 0x1C) | (hw2 >> 6 & 3);
    let kind = hw2 >> 4 & 3;
    if hw2 & 1 << 15 != 0 || bad(rm) {
        return Err(Exception::Undefined);
    }
    if op == 0b0110 {
        // PKHBT, PKHTB (tb: bit 5)
        if s || kind & 1 != 0 || bad(rd) || bad(rn) {
            return Err(Exception::Undefined);
        }
        return pack(rd, reg(rn), reg(rm), kind & 2 != 0, imm5);
    }
    let (kind, amount) = decode_imm_shift(kind, imm5);
    let (operand, c) = shift_c(reg(rm), kind, amount, carry());
    t32_data(op, s, rd, rn, operand, c)
}

/// Data processing (modified immediate) (11110 x0x / 0)
fn t32_modified_immediate(hw1: u32, hw2: u32) -> Result<Flow, Exception> {
    let op = hw1 >> 5 & 15;
    let s = hw1 & 1 << 4 != 0;
    let rn = hw1 & 15;
    let rd = hw2 >> 8 & 15;
    let imm12 = (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | hw2 & 0xFF;
    let (operand, c) = expand_imm_c(imm12, carry());
    t32_data(op, s, rd, rn, operand, c)
}

/// Data processing (plain binary immediate) (11110 x1x / 0)
fn t32_plain_immediate(hw1: u32, hw2: u32, pc: u32) -> Result<Flow, Exception> {
    let op = hw1 >> 4 & 31;
    let rn = hw1 & 15;
    let rd = hw2 >> 8 & 15;
    let imm12 = (hw1 >> 10 & 1) << 11 | (hw2 >> 12 & 7) << 8 | hw2 & 0xFF;
    let imm3_imm2 = (hw2 >> 10 & 0x1C) | (hw2 >> 6 & 3);
    let width = hw2 & 31;
    if bad(rd) && !(rd == 13 && (op == 0b00000 || op == 0b01010) && rn == 13) {
        return Err(Exception::Undefined);
    }
    match op {
        // ADDW, SUBW (ADR with Rn = PC: the aligned PC)
        0b00000 | 0b01010 => {
            let base = if rn == 15 { pc.wrapping_add(4) & !3 } else { reg(rn) };
            set_reg(
                rd,
                if op == 0 { base.wrapping_add(imm12) } else { base.wrapping_sub(imm12) },
            );
            Ok(Flow::Next)
        },
        // MOVW, MOVT
        0b00100 | 0b01100 => {
            let imm16 = (hw1 & 15) << 12 | imm12;
            set_reg(
                rd,
                if op == 0b00100 { imm16 } else { reg(rd) & 0xFFFF | imm16 << 16 },
            );
            Ok(Flow::Next)
        },
        // SSAT, USAT (shift: bit 5 of the first halfword, LSL or ASR), SSAT16, USAT16
        0b10000 | 0b10010 | 0b11000 | 0b11010 => {
            if bad(rn) {
                return Err(Exception::Undefined);
            }
            let unsigned = op & 0b01000 != 0;
            let asr = hw1 & 1 << 5 != 0;
            if asr && imm3_imm2 == 0 {
                // SSAT16, USAT16
                if width & 0x10 != 0 && !unsigned || hw2 & 0x30 != 0 {
                    return Err(Exception::Undefined);
                }
                return saturate16(
                    rd,
                    reg(rn),
                    (width & 15) + if unsigned { 0 } else { 1 },
                    unsigned,
                );
            }
            let (kind, amount) =
                decode_imm_shift(if asr { SHIFT_ASR } else { SHIFT_LSL }, imm3_imm2);
            let value = shift_c(reg(rn), kind, amount, false).0;
            saturate(rd, value, width + if unsigned { 0 } else { 1 }, unsigned)
        },
        // SBFX, UBFX
        0b10100 | 0b11100 => {
            if bad(rn) {
                return Err(Exception::Undefined);
            }
            bitfield_extract(rd, reg(rn), imm3_imm2, width + 1, op == 0b10100)
        },
        // BFI, BFC (Rn = PC)
        0b10110 => {
            if rn == 13 {
                return Err(Exception::Undefined);
            }
            bitfield_insert(
                rd,
                if rn == 15 { None } else { Some(reg(rn)) },
                imm3_imm2,
                width,
            )
        },
        _ => Err(Exception::Undefined),
    }
}

/// Branches and miscellaneous control (11110 / 1)
fn t32_branch_control(hw1: u32, hw2: u32, pc: u32, cond: u32) -> Result<Flow, Exception> {
    let op1 = hw2 >> 12 & 7;
    if op1 & 0b101 == 0b000 {
        let op = hw1 >> 4 & 0x3F;
        if op & 0b111000 != 0b111000 {
            // B<cond> (T3): S:J2:J1:imm6:imm11 << 1
            if in_it_block() {
                return Err(Exception::Undefined);
            }
            let c = hw1 >> 6 & 15;
            if !condition_passed(c) {
                return Ok(Flow::Next);
            }
            let s = hw1 >> 10 & 1;
            let imm = s << 20
                | (hw2 >> 11 & 1) << 19
                | (hw2 >> 13 & 1) << 18
                | (hw1 & 0x3F) << 12
                | (hw2 & 0x7FF) << 1;
            let offset = ((imm << 11) as i32 >> 11) as u32;
            return Ok(jump(pc.wrapping_add(4).wrapping_add(offset)));
        }
        // (HVC, SMC, UDF (T2): bit 10 of the first halfword set; UNDEFINED at EL0)
        if hw1 & 1 << 10 != 0 {
            // (HVC 1111 0111 1110, SMC 1111 0111 1111, op1 0: PSCI at PL1)
            if crate::aarch64::a32_system::privileged() && op1 == 0 && hw1 >> 5 & 0x3F == 0x3F {
                return crate::aarch64::a32_system::hvc();
            }
            return Err(Exception::Undefined);
        }
        if a32_only() {
            match op {
                // MSR (register) of CPSR (mask hw2[11:8]), SPSR (R), a banked register (bit 5)
                0b111000 | 0b111001 => {
                    let rn = hw1 & 15;
                    let r = hw1 & 1 << 4 != 0;
                    if bad(rn) {
                        return Err(Exception::Undefined);
                    }
                    if hw2 & 0x20 != 0 {
                        return banked(false, r, (hw2 >> 4 & 1) << 4 | hw2 >> 8 & 15, rn);
                    }
                    let mask = hw2 >> 8 & 15;
                    if mask == 0 {
                        return Err(Exception::Undefined);
                    }
                    return if r { msr_spsr(reg(rn), mask) } else { msr_cpsr(reg(rn), mask) };
                },
                // MRS of CPSR, SPSR (R), a banked register (bit 5)
                0b111110 | 0b111111 => {
                    let rd = hw2 >> 8 & 15;
                    let r = hw1 & 1 << 4 != 0;
                    if bad(rd) {
                        return Err(Exception::Undefined);
                    }
                    if hw2 & 0x20 != 0 {
                        return banked(true, r, (hw2 >> 4 & 1) << 4 | hw1 & 15, rd);
                    }
                    return mrs(rd, r);
                },
                // CPS (imod hw2[10:9], M bit 8)
                0b111010 if hw2 & 0x700 != 0 => {
                    if in_it_block() {
                        return Err(Exception::Undefined);
                    }
                    crate::aarch64::a32_system::cps(
                        hw2 >> 9 & 3,
                        hw2 >> 5 & 7,
                        hw2 & 1 << 8 != 0,
                        hw2 & 31,
                    );
                    return Ok(Flow::Next);
                },
                // SUBS PC, LR, #imm8 (ERET: imm8 0)
                0b111101 if hw1 & 15 == 14 && hw2 & 0xFF00 == 0x8F00 => {
                    if !crate::aarch64::a32_system::privileged() || !last_in_it_block() {
                        return Err(Exception::Undefined);
                    }
                    return crate::aarch64::a32_system::exception_return(
                        reg(14).wrapping_sub(hw2 & 0xFF),
                    );
                },
                _ => {},
            }
        }
        return match op {
            // MSR (register): APSR's nzcvq (bit 11), g (bit 10)
            0b111000 | 0b111001 => {
                let rn = hw1 & 15;
                let mask = hw2 >> 10 & 3;
                if hw1 & 1 << 4 != 0 || hw2 & 0x300 != 0 || mask == 0 || bad(rn) || hw2 & 0x20 != 0
                {
                    return Err(Exception::Undefined);
                }
                msr_apsr(mask, reg(rn))
            },
            // hints, CPS (a NOP at EL0 is not encoded here: UNDEFINED)
            0b111010 => {
                if hw2 & 0x700 != 0 {
                    return Err(Exception::Undefined);
                }
                hint(hw2 & 0xFF, cond)
            },
            // CLREX, DSB, DMB, ISB
            0b111011 => match hw2 >> 4 & 15 {
                2 => clear_exclusive(),
                4 => barrier(true),
                5 | 6 => barrier(false),
                _ => Err(Exception::Undefined),
            },
            // BXJ: BX
            0b111100 => {
                let rm = hw1 & 15;
                if bad(rm) || !last_in_it_block() {
                    return Err(Exception::Undefined);
                }
                Ok(bx_write_pc(reg(rm)))
            },
            // MRS (APSR)
            0b111110 | 0b111111 => {
                let rd = hw2 >> 8 & 15;
                if hw1 & 1 << 4 != 0 || hw2 & 0x20 != 0 || bad(rd) {
                    return Err(Exception::Undefined);
                }
                mrs_apsr(rd)
            },
            // ERET, HVC, SMC: UNDEFINED at EL0; UDF (T2)
            _ => Err(Exception::Undefined),
        };
    }
    // B (T4), BL, BLX (immediate): S:I1:I2:imm10:imm11 << 1, I = NOT(J XOR S)
    if !last_in_it_block() {
        return Err(Exception::Undefined);
    }
    let s = hw1 >> 10 & 1;
    let i1 = !(hw2 >> 13 & 1 ^ s) & 1;
    let i2 = !(hw2 >> 11 & 1 ^ s) & 1;
    let imm = s << 24 | i1 << 23 | i2 << 22 | (hw1 & 0x3FF) << 12 | (hw2 & 0x7FF) << 1;
    let offset = ((imm << 7) as i32 >> 7) as u32;
    match op1 {
        // B
        0b001 | 0b011 => Ok(jump(pc.wrapping_add(4).wrapping_add(offset))),
        // BL
        0b101 | 0b111 => {
            set_reg(14, pc.wrapping_add(4) | 1);
            Ok(jump(pc.wrapping_add(4).wrapping_add(offset)))
        },
        // BLX (immediate): to A32, the target from the aligned PC (H, bit 0, is 0)
        _ => {
            if hw2 & 1 != 0 {
                return Err(Exception::Undefined);
            }
            set_reg(14, pc.wrapping_add(4) | 1);
            set_pstate_bits(PSTATE_T, 0);
            Ok(Flow::Jump(
                (pc.wrapping_add(4) & !3).wrapping_add(offset) as u64
            ))
        },
    }
}

/// Loads and stores (1111 100x): byte, halfword, word; immediate (12 or 8
/// bits with P U W), register (LSL 0-3), literal, unprivileged; the preloads
fn t32_load_store(hw1: u32, hw2: u32, pc: u32) -> Result<Flow, Exception> {
    let signed = hw1 & 1 << 8 != 0;
    let size = 1u32 << (hw1 >> 5 & 3);
    let l = hw1 & 1 << 4 != 0;
    let rn = hw1 & 15;
    let rt = hw2 >> 12 & 15;
    if size == 8 || !l && signed {
        return Err(Exception::Undefined);
    }
    // (the preloads: PLD, PLI as loads to the PC of bytes and halfwords)
    let preload = l && rt == 15 && size < 4;
    let u = hw1 & 1 << 7 != 0;
    let (address, writeback, unprivileged) = if rn == 15 {
        // literal: aligned PC + or - imm12
        if !l {
            return Err(Exception::Undefined);
        }
        let base = pc.wrapping_add(4) & !3;
        let imm = hw2 & 0xFFF;
        (
            if u { base.wrapping_add(imm) } else { base.wrapping_sub(imm) },
            None,
            false,
        )
    }
    else if u {
        (reg(rn).wrapping_add(hw2 & 0xFFF), None, false)
    }
    else if hw2 & 0xFC0 == 0 {
        // register: Rn + Rm << imm2
        let rm = hw2 & 15;
        if bad(rm) {
            return Err(Exception::Undefined);
        }
        (reg(rn).wrapping_add(reg(rm) << (hw2 >> 4 & 3)), None, false)
    }
    else if hw2 & 0xF00 == 0xE00 {
        // LDRT and the other unprivileged forms: Rn + imm8
        (reg(rn).wrapping_add(hw2 & 0xFF), None, true)
    }
    else if hw2 & 0x800 != 0 {
        // imm8 with P, U, W (P = 0 and W = 0 is not one)
        let p = hw2 & 0x400 != 0;
        let up = hw2 & 0x200 != 0;
        let w = hw2 & 0x100 != 0;
        if !p && !w {
            return Err(Exception::Undefined);
        }
        let imm = hw2 & 0xFF;
        let offset_address = if up { reg(rn).wrapping_add(imm) } else { reg(rn).wrapping_sub(imm) };
        if w && (rn == rt || preload) {
            return Err(Exception::Undefined);
        }
        (
            if p { offset_address } else { reg(rn) },
            if w { Some(offset_address) } else { None },
            false,
        )
    }
    else {
        return Err(Exception::Undefined);
    };
    if preload {
        return Ok(Flow::Next);
    }
    if l {
        if rt == 15 && (size != 4 || !last_in_it_block()) || rt == 13 && size != 4 {
            return Err(Exception::Undefined);
        }
        load_register(rt, address, size, signed, rn, writeback, unprivileged)
    }
    else {
        if rt == 15 || rn == 15 {
            return Err(Exception::Undefined);
        }
        store_register(reg(rt), address, size, rn, writeback, unprivileged)
    }
}

/// Data processing (register) (1111 1010): shifts by a register, the
/// extends, the parallel additions and subtractions, the miscellaneous ones
fn t32_data_register(hw1: u32, hw2: u32) -> Result<Flow, Exception> {
    let op1 = hw1 >> 4 & 15;
    let rn = hw1 & 15;
    let rd = hw2 >> 8 & 15;
    let rm = hw2 & 15;
    let op2 = hw2 >> 4 & 15;
    if hw2 >> 12 != 0b1111 || bad(rd) || bad(rm) {
        return Err(Exception::Undefined);
    }
    if op1 < 8 && op2 == 0 {
        // LSL, LSR, ASR, ROR (register), S in bit 4
        if bad(rn) {
            return Err(Exception::Undefined);
        }
        let kind = op1 >> 1;
        let (value, c) = shift_c(reg(rn), kind, reg(rm) & 0xFF, carry());
        return data_processing(DP_MOV, op1 & 1 != 0, rd, 0, value, c);
    }
    if op1 < 8 && op2 & 8 != 0 {
        // SXTAH, UXTAH, SXTAB16, UXTAB16, SXTAB, UXTAB (Rn = PC: no addend)
        let rotation = 8 * (op2 & 3);
        if rn == 13 || op2 & 4 != 0 {
            return Err(Exception::Undefined);
        }
        let addend = if rn == 15 { None } else { Some(reg(rn)) };
        let m = reg(rm);
        return match op1 {
            0 => extend(rd, addend, m, rotation, 16, true, false),
            1 => extend(rd, addend, m, rotation, 16, false, false),
            2 => extend(rd, addend, m, rotation, 8, true, true),
            3 => extend(rd, addend, m, rotation, 8, false, true),
            4 => extend(rd, addend, m, rotation, 8, true, false),
            5 => extend(rd, addend, m, rotation, 8, false, false),
            _ => Err(Exception::Undefined),
        };
    }
    if bad(rn) {
        return Err(Exception::Undefined);
    }
    if op1 & 8 != 0 && op2 < 8 {
        // parallel additions and subtractions: op1 2:0 the operation (A32's
        // op), op2 1:0 the kind (00 signed, 01 saturating, 10 halving),
        // op2 bit 2 unsigned
        let op = match op1 & 7 {
            0b001 => 0, // ADD16
            0b010 => 1, // ASX
            0b110 => 2, // SAX
            0b101 => 3, // SUB16
            0b000 => 4, // ADD8
            0b100 => 7, // SUB8
            _ => return Err(Exception::Undefined),
        };
        let mode = match op2 & 3 {
            0 => 1,
            1 => 2,
            2 => 3,
            _ => return Err(Exception::Undefined),
        };
        let kind = mode | (op2 & 4);
        return parallel(kind, op, rd, reg(rn), reg(rm));
    }
    if op1 & 0b1100 == 0b1000 && op2 & 0b1100 == 0b1000 {
        // the miscellaneous: QADD, QDADD, QSUB, QDSUB; REV, REV16, RBIT, REVSH; SEL; CLZ; CRC32
        let (n, m) = (reg(rn), reg(rm));
        return match (op1 & 3, op2 & 3) {
            // (QADD Rd, Rm, Rn: Rm + Rn, QSUB: Rm - Rn, QDADD: Rm + 2 Rn)
            (0, 0) => saturating_add(0, rd, n, m),
            (0, 1) => saturating_add(2, rd, n, m),
            (0, 2) => saturating_add(1, rd, n, m),
            (0, 3) => saturating_add(3, rd, n, m),
            // (REV and friends: Rn and Rm the same register)
            (1, _) if rn != rm => Err(Exception::Undefined),
            (1, 0) => bit_op(0, rd, m),
            (1, 1) => bit_op(1, rd, m),
            (1, 2) => bit_op(3, rd, m),
            (1, 3) => bit_op(2, rd, m),
            (2, 0) => select(rd, n, m),
            (3, 0) if rn == rm => bit_op(4, rd, m),
            _ => Err(Exception::Undefined),
        };
    }
    if op1 & 0b1100 == 0b1100 && op2 & 0b1100 == 0b1000 {
        // CRC32{C}{B,H,W}: sz in op2 1:0, C in op1 bit 0... (1111 1010 1100 Rn / 1111 Rd 10 sz Rm)
        let castagnoli = op1 & 1 != 0;
        if op1 & 2 != 0 {
            return Err(Exception::Undefined);
        }
        return crc32(rd, reg(rn), reg(rm), op2 & 3, castagnoli);
    }
    Err(Exception::Undefined)
}

/// The multiplies, multiply-accumulates, the long ones and the divides (1111 1011)
fn t32_multiply(hw1: u32, hw2: u32) -> Result<Flow, Exception> {
    let op1 = hw1 >> 4 & 7;
    let rn = hw1 & 15;
    let ra = hw2 >> 12 & 15;
    let rd = hw2 >> 8 & 15;
    let op2 = hw2 >> 4 & 15;
    let rm = hw2 & 15;
    if bad(rn) || bad(rm) || bad(rd) {
        return Err(Exception::Undefined);
    }
    let (n, m) = (reg(rn), reg(rm));
    if hw1 & 1 << 7 == 0 {
        // the 32-bit products: Ra = PC for none
        if ra == 13 {
            return Err(Exception::Undefined);
        }
        return match (op1, op2) {
            (0, 0) => {
                if ra == 15 {
                    multiply(0, false, rd, n, m, 0)
                }
                else {
                    multiply(1, false, rd, n, m, reg(ra))
                }
            },
            (0, 1) if ra != 15 => multiply(2, false, rd, n, m, reg(ra)),
            // SMLA<x><y>, SMUL<x><y>: N bit 5, M bit 4 of the second halfword
            (1, 0..=3) => {
                let n_top = op2 & 2 != 0;
                let m_top = op2 & 1 != 0;
                if ra == 15 {
                    multiply_halfword(3, rd, 0, n, m, n_top, m_top, false)
                }
                else {
                    multiply_halfword(0, rd, ra, n, m, n_top, m_top, true)
                }
            },
            // SMLAD, SMUAD, SMLSD, SMUSD (X: bit 4)
            (2, 0 | 1) => multiply_dual(rd, ra, n, m, false, op2 & 1 != 0, false),
            (4, 0 | 1) => multiply_dual(rd, ra, n, m, true, op2 & 1 != 0, false),
            // SMLAW<y>, SMULW<y>
            (3, 0 | 1) => multiply_halfword(1, rd, ra, n, m, false, op2 & 1 != 0, ra != 15),
            // SMMLA, SMMUL, SMMLS (R: bit 4)
            (5, 0 | 1) => multiply_most(rd, ra, n, m, false, op2 & 1 != 0),
            (6, 0 | 1) if ra != 15 => multiply_most(rd, ra, n, m, true, op2 & 1 != 0),
            // USAD8, USADA8
            (7, 0) => sum_absolute(rd, ra, n, m),
            _ => Err(Exception::Undefined),
        };
    }
    // the 64-bit products, the divides: RdLo in 15:12, RdHi in 11:8
    let (lo, hi) = (ra, rd);
    match (op1, op2) {
        (1, 15) if ra == 15 => divide(rd, n, m, true),
        (3, 15) if ra == 15 => divide(rd, n, m, false),
        _ => {
            if bad(lo) || lo == hi {
                return Err(Exception::Undefined);
            }
            match (op1, op2) {
                (0, 0) => multiply_long(6, false, lo, hi, n, m),
                (2, 0) => multiply_long(4, false, lo, hi, n, m),
                (4, 0) => multiply_long(7, false, lo, hi, n, m),
                (6, 0) => multiply_long(5, false, lo, hi, n, m),
                (6, 6) => multiply_long(2, false, lo, hi, n, m),
                // SMLAL<x><y>
                (4, 8..=11) => multiply_halfword(2, hi, lo, n, m, op2 & 2 != 0, op2 & 1 != 0, true),
                // SMLALD, SMLSLD
                (4, 12 | 13) => multiply_dual(hi, lo, n, m, false, op2 & 1 != 0, true),
                (5, 12 | 13) => multiply_dual(hi, lo, n, m, true, op2 & 1 != 0, true),
                _ => Err(Exception::Undefined),
            }
        },
    }
}

/// The coprocessor space (111x 11xx): VFP (coprocessors 10, 11: A32's
/// encodings with the condition 1110, and ARMv8's unconditional ones),
/// Advanced SIMD's data processing, MCR, MRC, MCRR, MRRC of CP15; the
/// rest UNDEFINED
fn t32_coprocessor(hw1: u32, hw2: u32, pc: u32, cond: u32) -> Result<Flow, Exception> {
    let cp = hw2 >> 8 & 15;
    let word = hw1 << 16 | hw2;
    // (111U 1111: Advanced SIMD data processing, A32's 1111 001U)
    if word & 0xEF00_0000 == 0xEF00_0000 {
        return crate::aarch64::a32_simd::data_processing(
            word & 0xE2FF_FFFF | (word & 1 << 28) >> 4 | 1 << 28,
        );
    }
    if hw1 >> 8 == 0xFE {
        return crate::aarch64::a32_fp::vfp_unconditional(word);
    }
    if (cp == 10 || cp == 11) && hw1 >> 12 == 0xE {
        return crate::aarch64::a32_fp::vfp(
            word & 0x0FFF_FFFF | 0xE000_0000,
            pc.wrapping_add(4),
            true,
        );
    }
    if cp == 14 && hw1 >> 12 & 1 == 0 && hw1 >> 8 & 15 == 0b1110 && hw2 & 1 << 4 != 0 {
        return crate::aarch64::a32_system::cp14(hw1 & 1 << 4 != 0, hw2 >> 12 & 15);
    }
    // (MCR2 and the other 1111 forms: UNDEFINED)
    if cp != 15 || hw1 >> 12 & 1 != 0 {
        return Err(Exception::Undefined);
    }
    let rt = hw2 >> 12 & 15;
    if hw1 >> 8 & 15 == 0b1110 && hw2 & 1 << 4 != 0 {
        if rt == 15 || rt == 13 {
            return Err(Exception::Undefined);
        }
        let read = hw1 & 1 << 4 != 0;
        return cp15(
            read,
            hw1 >> 5 & 7,
            hw1 & 15,
            hw2 & 15,
            hw2 >> 5 & 7,
            rt,
            reg(rt),
            cond,
        );
    }
    if hw1 >> 5 & 0x7F == 0b1100010 || hw1 >> 4 & 0xFE == 0xC4 {
        let rt2 = hw1 & 15;
        if bad(rt) || bad(rt2) {
            return Err(Exception::Undefined);
        }
        let read = hw1 & 1 << 4 != 0;
        let value = (reg(rt2) as u64) << 32 | reg(rt) as u64;
        return cp15_64(read, hw2 >> 4 & 15, hw2 & 15, rt, rt2, value, cond);
    }
    Err(Exception::Undefined)
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/rust/aarch64/timer.rs                                                                0000644 0000000 0000000 00000016377 00000000000 014404  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The generic timer of the AArch64 core (docs/arm64-virt-android16-plan.md
//! P4.3): one system counter for the machine at CNTFRQ's 1 GHz, the EL1
//! virtual and physical timers of each core with their registers and their
//! interrupt lines (PPIs 27 and 30, level-sensitive, in the GIC), the event
//! stream of CNTKCTL_EL1; CNTVOFF is 0 (no EL2).

use crate::aarch64::cpu::{self, Exception};
use crate::aarch64::state::*;
use crate::aarch64::sysregs::key;

/// The system counter: nanoseconds of the machine's clock. With cores in
/// workers (P8.2) each reads its own host clock: the machine's last value
/// keeps the counter from going back from one core to the next.
pub fn counter() -> u64 {
    let now = unsafe { crate::isa::microtick() };
    let value = (now * 1_000_000.0) as u64;
    if crate::parallel::active() {
        unsafe { crate::parallel::max64(crate::parallel::machine(&raw mut COUNTER_LAST), value) }
    }
    else {
        value
    }
}
/// (cores in workers) the highest counter value read on any core
static mut COUNTER_LAST: u64 = 0;
/// The machine's clock was set back (a snapshot restored, a boot): the
/// counter follows it (every core is stopped)
pub fn reset_counter() { unsafe { *crate::parallel::machine(&raw mut COUNTER_LAST) = 0 } }

const CTL_ENABLE: u64 = 1;
const CTL_IMASK: u64 = 2;
const CTL_ISTATUS: u64 = 4;

/// The timers' PPIs (the INTIDs the DTB lists: virtual 27, non-secure physical 30)
pub const PPI_VIRTUAL: usize = 27;
pub const PPI_PHYSICAL: usize = 30;

/// The counter when the event stream last ticked (per core)
static mut EVENT_STREAM_LAST: [u64; crate::isa::MAX_CORES] = [0; crate::isa::MAX_CORES];

#[inline(always)]
fn fires(control: u64, compare: u64, now: u64) -> bool {
    control & CTL_ENABLE != 0 && now >= compare
}

/// Bring the current core's timer interrupt lines and event stream up to
/// the counter: called on timer register writes and from the run loop
pub fn tick() { tick_core(crate::isa::current_core(), counter()) }

/// Every core's timers (the cores that are not running too: their registers
/// are in their saved state, crate::aarch64::smp::field); with cores in
/// workers, this instance's core's
pub fn tick_all() {
    let now = counter();
    for core in crate::aarch64::smp::local() {
        tick_core(core, now);
    }
}

fn tick_core(core: usize, now: u64) {
    use crate::aarch64::smp::field;
    unsafe {
        let (vctl, vcval) = (*field(core, cntv_ctl), *field(core, cntv_cval));
        let (pctl, pcval) = (*field(core, cntp_ctl), *field(core, cntp_cval));
        let virtual_line = fires(vctl, vcval, now) && vctl & CTL_IMASK == 0;
        let physical_line = fires(pctl, pcval, now) && pctl & CTL_IMASK == 0;
        crate::aarch64::gic::set_ppi(core, PPI_VIRTUAL, virtual_line);
        crate::aarch64::gic::set_ppi(core, PPI_PHYSICAL, physical_line);
        // the event stream: an event whenever bit EVNTI of the counter has toggled
        let kctl = *field(core, cntkctl_el1);
        if kctl >> 2 & 1 != 0 {
            let shift = (kctl >> 4 & 15) + 1;
            if now >> shift != EVENT_STREAM_LAST[core] >> shift {
                crate::aarch64::smp::event_to(core);
            }
        }
        EVENT_STREAM_LAST[core] = now;
    }
}

/// Nanoseconds until core `core`'s timers or event stream next need it
/// (u64::MAX: never), for a core that waits
pub fn next_due(core: usize) -> u64 {
    use crate::aarch64::smp::field;
    let now = counter();
    let mut due = u64::MAX;
    unsafe {
        for (control, compare) in [
            (*field(core, cntv_ctl), *field(core, cntv_cval)),
            (*field(core, cntp_ctl), *field(core, cntp_cval)),
        ] {
            if control & CTL_ENABLE != 0 && control & CTL_IMASK == 0 {
                due = due.min(compare.saturating_sub(now));
            }
        }
        let kctl = *field(core, cntkctl_el1);
        if kctl >> 2 & 1 != 0 {
            due = due.min(1u64 << ((kctl >> 4 & 15) + 1));
        }
    }
    due
}

/// CNTx_CTL with ISTATUS: whether the timer's condition is met
fn ctl(control: u64, compare: u64) -> u64 {
    let status = control & CTL_ENABLE != 0 && counter() >= compare;
    control & (CTL_ENABLE | CTL_IMASK) | if status { CTL_ISTATUS } else { 0 }
}

fn trap(reg: u32, rt: u32, read: bool) -> Exception {
    let op0 = reg >> 14 & 3;
    let op1 = reg >> 11 & 7;
    let crn = reg >> 7 & 15;
    let crm = reg >> 3 & 15;
    let op2 = reg & 7;
    Exception::SystemRegister(
        op0 << 20 | op2 << 17 | op1 << 14 | crn << 10 | rt << 5 | crm << 1 | read as u32,
    )
}

/// Whether EL0 may access the register (CNTKCTL_EL1)
fn el0_allowed(reg: u32) -> bool {
    let kctl = unsafe { *cntkctl_el1 };
    let pcten = kctl & 1 != 0;
    let vcten = kctl & 2 != 0;
    match reg {
        r if r == key(3, 3, 14, 0, 0) => pcten || vcten,
        r if r == key(3, 3, 14, 0, 1) => pcten,
        r if r == key(3, 3, 14, 0, 2) => vcten,
        r if r >> 3 == key(3, 3, 14, 2, 0) >> 3 => kctl & 1 << 9 != 0,
        r if r >> 3 == key(3, 3, 14, 3, 0) >> 3 => kctl & 1 << 8 != 0,
        _ => false,
    }
}

pub fn read(reg: u32, rt: u32) -> Result<u64, Exception> {
    if cpu::el() == 0 && !el0_allowed(reg) {
        return Err(trap(reg, rt, true));
    }
    unsafe {
        Ok(match reg {
            r if r == key(3, 3, 14, 0, 0) => *cntfrq_el0,
            r if r == key(3, 3, 14, 0, 1) || r == key(3, 3, 14, 0, 2) => counter(),
            r if r == key(3, 3, 14, 2, 0) => {
                (*cntp_cval).wrapping_sub(counter()) as u32 as i32 as u64 & 0xFFFF_FFFF
            },
            r if r == key(3, 3, 14, 2, 1) => ctl(*cntp_ctl, *cntp_cval),
            r if r == key(3, 3, 14, 2, 2) => *cntp_cval,
            r if r == key(3, 3, 14, 3, 0) => {
                (*cntv_cval).wrapping_sub(counter()) as u32 as i32 as u64 & 0xFFFF_FFFF
            },
            r if r == key(3, 3, 14, 3, 1) => ctl(*cntv_ctl, *cntv_cval),
            r if r == key(3, 3, 14, 3, 2) => *cntv_cval,
            _ => return Err(Exception::Undefined),
        })
    }
}

pub fn write(reg: u32, rt: u32, value: u64) -> Result<(), Exception> {
    let el = cpu::el();
    if el == 0 && !el0_allowed(reg) {
        return Err(trap(reg, rt, false));
    }
    unsafe {
        match reg {
            // (CNTFRQ_EL0: writable at EL1, the highest EL here)
            r if r == key(3, 3, 14, 0, 0) => {
                if el == 0 {
                    return Err(Exception::Undefined);
                }
                *cntfrq_el0 = value & 0xFFFF_FFFF
            },
            r if r == key(3, 3, 14, 0, 1) || r == key(3, 3, 14, 0, 2) => {
                return Err(Exception::Undefined)
            },
            r if r == key(3, 3, 14, 2, 0) => {
                *cntp_cval = counter().wrapping_add(value as u32 as i32 as i64 as u64)
            },
            r if r == key(3, 3, 14, 2, 1) => *cntp_ctl = value & (CTL_ENABLE | CTL_IMASK),
            r if r == key(3, 3, 14, 2, 2) => *cntp_cval = value,
            r if r == key(3, 3, 14, 3, 0) => {
                *cntv_cval = counter().wrapping_add(value as u32 as i32 as i64 as u64)
            },
            r if r == key(3, 3, 14, 3, 1) => *cntv_ctl = value & (CTL_ENABLE | CTL_IMASK),
            r if r == key(3, 3, 14, 3, 2) => *cntv_cval = value,
            _ => return Err(Exception::Undefined),
        }
    }
    tick();
    Ok(())
}
                                                                                                                                                                                                                                                                 source/v64/src/rust/aarch64/tlb.rs                                                                  0000644 0000000 0000000 00000035153 00000000000 014036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The TLB of the AArch64 core (docs/arm64-virt-android16-plan.md P3.5):
//! per core, direct-mapped by the 4 KiB page of the VA (a leaf of a larger
//! granule or a block is cached per 4 KiB page it covers), tagged with the
//! ASID unless global. An entry holds the permissions of both EL0 and EL1,
//! so it serves either. Intermediate table entries are not cached. TLBI by
//! VA covers every entry derived from the same leaf: the 4 KiB pages of the
//! 64 KiB-aligned range holding the VA (any granule's page), and a block's
//! pages through the list of blocks cached since the last full flush (a hit
//! there flushes everything).
//!
//! With cores in workers (P8.3) an inner shareable TLBI (and IC IVAU) acts
//! on this core at once and goes to the other cores through the machine's
//! ring (`post`); each core takes the ring at its safe points (`poll`) and
//! acknowledges, and the posting core's DSB completes only when every other
//! core has acknowledged or is idle (`synced`: an idle core polls before it
//! runs again).

use crate::isa::MAX_CORES;

pub const TLB_BITS: u32 = 10;
pub const TLB_SIZE: usize = 1 << TLB_BITS;

// entry flags
pub const EL1_READ: u16 = 1 << 0;
pub const EL1_WRITE: u16 = 1 << 1;
pub const EL1_EXEC: u16 = 1 << 2;
pub const EL0_READ: u16 = 1 << 3;
pub const EL0_WRITE: u16 = 1 << 4;
pub const EL0_EXEC: u16 = 1 << 5;
pub const GLOBAL: u16 = 1 << 6;
pub const DEVICE: u16 = 1 << 7;

#[derive(Clone, Copy)]
pub struct Entry {
    /// the VA's 4 KiB page (TBI applied) + 1; 0: empty
    pub tag: u64,
    /// the physical address of that 4 KiB page
    pub pa: u64,
    pub asid: u16,
    pub flags: u16,
    /// the leaf's level and log2 of its size
    pub level: u8,
    pub size_log: u8,
    /// MAIR attribute and shareability (AT, PAR_EL1)
    pub attr: u8,
    pub sh: u8,
}

impl Entry {
    pub const EMPTY: Entry = Entry {
        tag: 0,
        pa: 0,
        asid: 0,
        flags: 0,
        level: 0,
        size_log: 0,
        attr: 0,
        sh: 0,
    };
}

/// A cached block (a leaf larger than a page): its VA (TBI applied), size and ASID
#[derive(Clone, Copy)]
struct Block {
    va: u64,
    size_log: u8,
    asid: u16,
    global: bool,
}

const BLOCKS: usize = 32;

struct Tlb {
    entries: [Entry; TLB_SIZE],
    blocks: [Block; BLOCKS],
    block_count: usize,
    /// a block was dropped from the full list: TLBI by VA flushes everything
    blocks_overflowed: bool,
}

static mut TLBS: [Tlb; MAX_CORES] = [const {
    Tlb {
        entries: [Entry::EMPTY; TLB_SIZE],
        blocks: [Block {
            va: 0,
            size_log: 0,
            asid: 0,
            global: false,
        }; BLOCKS],
        block_count: 0,
        blocks_overflowed: false,
    }
}; MAX_CORES];

/// Changes with every invalidation on any core (the fetch fast path checks it)
pub static mut GENERATION: u32 = 1;

#[inline(always)]
fn tlb(core: usize) -> &'static mut Tlb { unsafe { &mut (*(&raw mut TLBS))[core] } }

#[inline(always)]
pub fn index(page: u64) -> usize { (page as usize ^ (page >> TLB_BITS) as usize) & (TLB_SIZE - 1) }

/// The entry of `page` (VA >> 12, TBI applied) for `asid`, if cached
#[inline(always)]
pub fn lookup(page: u64, asid: u16) -> Option<Entry> {
    let entry = tlb(crate::isa::current_core()).entries[index(page)];
    if entry.tag == page + 1 && (entry.flags & GLOBAL != 0 || entry.asid == asid) {
        Some(entry)
    }
    else {
        None
    }
}

pub fn insert(page: u64, entry: Entry) {
    let t = tlb(crate::isa::current_core());
    t.entries[index(page)] = Entry {
        tag: page + 1,
        ..entry
    };
    if entry.level < 3 {
        // (a block: TLBI by VA must find its other pages)
        let block = Block {
            va: page << 12 & !((1u64 << entry.size_log) - 1),
            size_log: entry.size_log,
            asid: entry.asid,
            global: entry.flags & GLOBAL != 0,
        };
        let known = t.blocks[..t.block_count].iter().any(|b| {
            b.va == block.va
                && b.size_log == block.size_log
                && b.asid == block.asid
                && b.global == block.global
        });
        if !known {
            if t.block_count < BLOCKS {
                t.blocks[t.block_count] = block;
                t.block_count += 1;
            }
            else {
                t.blocks_overflowed = true;
            }
        }
    }
}

fn bump() { unsafe { GENERATION = GENERATION.wrapping_add(1).max(1) } }
/// (another core runs now: the fetch fast path's translation is another TLB's)
pub fn bump_generation() { bump() }

fn flush_core(core: usize) {
    let t = tlb(core);
    t.entries.fill(Entry::EMPTY);
    t.block_count = 0;
    t.blocks_overflowed = false;
    // (what the page tier derived from the TLB goes with it: P6.4)
    crate::aarch64::jit::pages::tlb_flushed(core);
}

/// The cores a TLBI acts on here: this one, or all (the inner shareable
/// domain); with cores in workers the others take it from the ring
fn cores(shareable: bool) -> core::ops::Range<usize> {
    if shareable && !crate::parallel::active() {
        0..crate::isa::core_count()
    }
    else {
        let core = crate::isa::current_core();
        core..core + 1
    }
}

// ---- the other cores' maintenance (cores in workers, P8.3)

/// What an entry of the ring does: all entries, one ASID's, a page's (an
/// ASID's or every ASID's), or nothing but a poll of the code invalidations (IC IVAU)
const RING_ALL: u64 = 1;
const RING_ASID: u64 = 2;
const RING_PAGE: u64 = 3;
const RING_PAGE_ALL_ASIDS: u64 = 4;
const RING_CODE: u64 = 5;
const RING: usize = 1024;

// the machine's (crate::parallel::machine)
static mut RING_NEXT: u32 = 0;
/// Each entry: [seq << 32 | kind << 16 | asid, page]
static mut RING_ENTRIES: [[u64; 2]; RING] = [[0; 2]; RING];
static mut RING_ACKED: [u32; MAX_CORES] = [0; MAX_CORES];
// this instance's
static mut RING_SEEN: u32 = 0;
/// The last entry this core posted that its next DSB waits for (0: none)
static mut PENDING: u32 = 0;
/// Where PENDING is (the page tier's DSB template steps a DSB only when it is not 0)
pub fn pending_address() -> u32 { &raw const PENDING as u32 }
/// (diagnostics, this instance's) 0 entries posted, 1 DSBs that waited, 2
/// entries taken from the ring, 3 rings overflowed
static mut RING_STATS: [u32; 4] = [0; 4];
#[no_mangle]
pub fn a64_tlb_ring_stat(field: u32) -> u32 {
    unsafe {
        (*(&raw const RING_STATS))
            .get(field as usize)
            .copied()
            .unwrap_or(0)
    }
}
/// Entries posted since this core's last completed DSB (a batch): IC posts
/// once a batch, and after BATCH_PAGES pages one full flush stands for the rest
static mut BATCH: u32 = 0;
static mut BATCH_CODE: bool = false;
static mut BATCH_ALL: bool = false;
const BATCH_PAGES: u32 = 32;
/// The pending entry each core was last kicked for (synced kicks a core once a batch)
static mut KICKED_FOR: [u32; MAX_CORES] = [0; MAX_CORES];

/// Post maintenance for the other cores (with cores in workers); they take
/// it when the posting core's DSB kicks them, or at their next safe point
fn post(kind: u64, page: u64, asid: u16) {
    if !crate::parallel::active() || crate::isa::core_count() == 1 {
        return;
    }
    unsafe {
        // (a batch: one IC entry; many pages: one full flush)
        let kind = match kind {
            RING_CODE if BATCH_CODE => return,
            RING_PAGE | RING_PAGE_ALL_ASIDS | RING_ASID if BATCH_ALL => return,
            RING_PAGE | RING_PAGE_ALL_ASIDS if BATCH >= BATCH_PAGES => RING_ALL,
            _ => kind,
        };
        BATCH += 1;
        BATCH_CODE |= kind == RING_CODE;
        BATCH_ALL |= kind == RING_ALL;
        let next = crate::parallel::machine(&raw mut RING_NEXT);
        let seq = crate::parallel::fetch_add32(next, 1).wrapping_add(1);
        let entry = crate::parallel::machine(&raw mut RING_ENTRIES)
            .cast::<[u64; 2]>()
            .add(seq as usize % RING);
        crate::parallel::store64((&raw mut (*entry)[1]).cast(), page);
        crate::parallel::store64(
            (&raw mut (*entry)[0]).cast(),
            (seq as u64) << 32 | kind << 16 | asid as u64,
        );
        PENDING = seq;
        RING_STATS[0] += 1;
    }
}

/// IC IVAU (and IC IALLUIS) with cores in workers: the next DSB waits until
/// every other core has taken the code invalidations (crate::parallel::code)
pub fn post_code() { post(RING_CODE, 0, 0) }

/// Take the other cores' maintenance (at a safe point: no compiled code
/// runs) and acknowledge it
pub fn poll() {
    if !crate::parallel::active() {
        return;
    }
    unsafe {
        let next = crate::parallel::word_load(crate::parallel::machine(&raw mut RING_NEXT));
        let first = RING_SEEN;
        if next == first {
            return;
        }
        let me = crate::isa::current_core();
        let count = next.wrapping_sub(first);
        let ring = crate::parallel::machine(&raw mut RING_ENTRIES).cast::<[u64; 2]>();
        let mut overflow = count as usize > RING;
        if !overflow {
            for i in 1..=count {
                let seq = first.wrapping_add(i);
                let entry = ring.add(seq as usize % RING);
                let meta = loop {
                    let meta = crate::parallel::load64((&raw const (*entry)[0]).cast());
                    let tag = (meta >> 32) as u32;
                    if tag == seq {
                        break Some(meta);
                    }
                    if (tag.wrapping_sub(seq) as i32) > 0 {
                        break None; // overwritten by a later round
                    }
                    // (the poster reserved the slot and fills it next)
                    std::hint::spin_loop();
                };
                let Some(meta) = meta
                else {
                    overflow = true;
                    break;
                };
                let page = crate::parallel::load64((&raw const (*entry)[1]).cast());
                // (one's own entries were done when they were posted)
                let asid = meta as u16;
                match meta >> 16 & 0xFFFF {
                    RING_ALL => flush_local(),
                    RING_ASID => flush_asid_local(asid),
                    RING_PAGE => flush_page_local(page, Some(asid)),
                    RING_PAGE_ALL_ASIDS => flush_page_local(page, None),
                    _ => {},
                }
            }
        }
        if overflow {
            flush_local();
            RING_STATS[3] += 1;
        }
        RING_STATS[2] = RING_STATS[2].wrapping_add(count);
        RING_SEEN = next;
        crate::parallel::word_store(
            crate::parallel::machine(&raw mut RING_ACKED)
                .cast::<u32>()
                .add(me),
            next,
        );
        bump();
    }
}

/// Whether the maintenance this core posted is done on every other core
/// (the DSB that waits for it may complete); kicks the cores it waits for
pub fn synced() -> bool {
    unsafe {
        let pending = PENDING;
        if pending == 0 || !crate::parallel::active() {
            return true;
        }
        let me = crate::isa::current_core();
        let acked = crate::parallel::machine(&raw mut RING_ACKED).cast::<u32>();
        let mut done = true;
        for core in 0..crate::isa::core_count() {
            if core == me || crate::parallel::code::is_idle(core) {
                continue;
            }
            if (crate::parallel::word_load(acked.add(core)).wrapping_sub(pending) as i32) < 0 {
                done = false;
                if KICKED_FOR[core] != pending {
                    KICKED_FOR[core] = pending;
                    crate::parallel::kick(core);
                }
            }
        }
        if done {
            PENDING = 0;
            BATCH = 0;
            BATCH_CODE = false;
            BATCH_ALL = false;
        }
        else {
            RING_STATS[1] += 1;
        }
        done
    }
}

/// (a stop, a reset) this core has taken the ring as it is now: nothing is pending
pub fn ring_synced_now() {
    unsafe {
        RING_SEEN = crate::parallel::word_load(crate::parallel::machine(&raw mut RING_NEXT));
        PENDING = 0;
        BATCH = 0;
        BATCH_CODE = false;
        BATCH_ALL = false;
        crate::parallel::word_store(
            crate::parallel::machine(&raw mut RING_ACKED)
                .cast::<u32>()
                .add(crate::isa::current_core()),
            RING_SEEN,
        );
    }
}

/// Everything (TLBI VMALLE1, and any change of the regime's controls)
pub fn flush(shareable: bool) {
    for core in cores(shareable) {
        flush_core(core);
    }
    bump();
    if shareable {
        post(RING_ALL, 0, 0);
    }
}
fn flush_local() { flush(false) }

/// The non-global entries of `asid` (TLBI ASIDE1)
pub fn flush_asid(shareable: bool, asid: u16) {
    flush_asid_cores(cores(shareable), asid);
    if shareable {
        post(RING_ASID, 0, asid);
    }
}
fn flush_asid_local(asid: u16) { flush_asid(false, asid) }
fn flush_asid_cores(cores: core::ops::Range<usize>, asid: u16) {
    for core in cores {
        let t = tlb(core);
        for entry in t.entries.iter_mut() {
            if entry.flags & GLOBAL == 0 && entry.asid == asid {
                *entry = Entry::EMPTY;
            }
        }
        crate::aarch64::jit::pages::tlb_flushed_asid(core, asid);
    }
    bump();
}

/// The entries of `page` (VA >> 12, TBI applied) for `asid`, or for every
/// ASID (`asid` None: TLBI VAAE1, VAALE1)
pub fn flush_page(shareable: bool, page: u64, asid: Option<u16>) {
    flush_page_cores(cores(shareable), page, asid);
    if shareable {
        match asid {
            Some(asid) => post(RING_PAGE, page, asid),
            None => post(RING_PAGE_ALL_ASIDS, page, 0),
        }
    }
}
fn flush_page_local(page: u64, asid: Option<u16>) { flush_page(false, page, asid) }
fn flush_page_cores(cores: core::ops::Range<usize>, page: u64, asid: Option<u16>) {
    let matches = |global: bool, entry_asid: u16| global || asid.map_or(true, |a| a == entry_asid);
    for core in cores {
        let t = tlb(core);
        let va = page << 12;
        let in_block = t.blocks_overflowed
            || t.blocks[..t.block_count]
                .iter()
                .any(|b| va & !((1u64 << b.size_log) - 1) == b.va && matches(b.global, b.asid));
        if in_block {
            flush_core(core);
            continue;
        }
        // (the 4 KiB pages of the largest page, 64 KiB, holding `va`)
        let first = page & !15;
        for p in first..first + 16 {
            let entry = &mut t.entries[index(p)];
            if entry.tag == p + 1 && matches(entry.flags & GLOBAL != 0, entry.asid) {
                *entry = Entry::EMPTY;
            }
            crate::aarch64::jit::pages::tlb_flushed_page(core, p, asid);
        }
    }
    bump();
}
                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/src/rust/config.rs                                                                       0000644 0000000 0000000 00000000131 00000000000 013256  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub const LOG_PAGE_FAULTS: bool = false;

pub const VMWARE_HYPERVISOR_PORT: bool = true;
                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/rust/core_stats.rs                                                                   0000644 0000000 0000000 00000007715 00000000000 014176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Retired instructions and the other per-core counters, the same for both
//! cores (docs/arm64-virt-android16-plan.md P1.10): the x86 core's
//! cpu::execution and the ARM core count through here, and
//! core_statistics_get(core, 0) means retired instructions in both
//! (docs/jit-unification-plan.md cross-phase rule 3). Up to 8 cores.

use crate::isa::current_core;

#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(crate) struct CoreStatistics {
    pub retired: u64,
    pub rep_elements: u64,
    pub faults: u64,
    pub halts: u64,
    pub runtime_ms: f64,
}
pub(crate) static mut CORE_STATISTICS: [CoreStatistics; 8] = [CoreStatistics {
    retired: 0,
    rep_elements: 0,
    faults: 0,
    halts: 0,
    runtime_ms: 0.0,
}; 8];
// Retired instructions and REP elements of the current core not yet added to
// CORE_STATISTICS: two plain adds per instruction instead of an indexed
// update. Flushed on core switch and before any read or reset.
pub(crate) static mut PENDING_RETIRED: u64 = 0;
pub(crate) static mut PENDING_REP_ELEMENTS: u64 = 0;
pub unsafe fn flush_core_statistics() {
    if PENDING_RETIRED | PENDING_REP_ELEMENTS != 0 {
        let stats = &mut (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()];
        stats.retired += PENDING_RETIRED;
        stats.rep_elements += PENDING_REP_ELEMENTS;
        PENDING_RETIRED = 0;
        PENDING_REP_ELEMENTS = 0;
    }
}

// (the ARM core's counting; the x86 core updates the statics in cpu::execution)
/// Instructions (and REP elements) the current core retired one by one
#[allow(dead_code)]
#[inline(always)]
pub fn add_pending(retired: u32, rep_elements: u32) {
    unsafe {
        PENDING_RETIRED += retired as u64;
        PENDING_REP_ELEMENTS += rep_elements as u64;
    }
}
/// A synchronous fault of the current core
#[allow(dead_code)]
pub fn note_fault() {
    unsafe { (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()].faults += 1 }
}

/// A HLT or WFI of the current core
pub unsafe fn note_halt() {
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()].halts += 1;
}
/// REP elements compiled code completed
pub unsafe fn note_jit_rep(elements: u32) {
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()].rep_elements +=
        elements as u64;
}
/// Instructions compiled code retired natively (the instructions it leaves
/// to the interpreter retire there: finish_instruction)
pub unsafe fn note_native_retired(native: u32) {
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()].retired += native as u64;
}
/// The current core's retired instructions so far, pending ones included
pub unsafe fn retired_now() -> u64 {
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[current_core()].retired + PENDING_RETIRED
}

#[no_mangle]
pub unsafe fn core_statistics_reset() {
    PENDING_RETIRED = 0;
    PENDING_REP_ELEMENTS = 0;
    *crate::parallel::machine(&raw mut CORE_STATISTICS) = [CoreStatistics::default(); 8];
}
#[no_mangle]
pub unsafe fn core_statistics_addr(core: u32) -> u32 {
    assert!(core < 8);
    flush_core_statistics();
    crate::parallel::machine(&raw mut CORE_STATISTICS)
        .cast::<CoreStatistics>()
        .add(core as usize) as u32
}
#[no_mangle]
pub fn core_statistics_size() -> u32 { std::mem::size_of::<CoreStatistics>() as u32 }
#[no_mangle]
pub unsafe fn core_statistics_get(core: u32, field: u32) -> f64 {
    assert!(core < 8);
    flush_core_statistics();
    let stats = (*crate::parallel::machine(&raw mut CORE_STATISTICS))[core as usize];
    match field {
        0 => stats.retired as f64,
        1 => stats.rep_elements as f64,
        2 => stats.faults as f64,
        3 => stats.halts as f64,
        4 => stats.runtime_ms,
        _ => 0.0,
    }
}
#[no_mangle]
pub unsafe fn core_statistics_runtime(core: u32, elapsed_ms: f64) {
    assert!(core < 8 && elapsed_ms.is_finite() && elapsed_ms >= 0.0);
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[core as usize].runtime_ms += elapsed_ms;
}
                                                   source/v64/src/rust/cpu/apic.rs                                                                     0000644 0000000 0000000 00000125477 00000000000 013541  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // See Intel's System Programming Guide

use crate::cpu::{cpu::js, global_pointers::acpi_enabled, ioapic, pic};
use crate::parallel;

const APIC_LOG_VERBOSE: bool = false;

// should probably be kept in sync with TSC_RATE in cpu.rs
const APIC_TIMER_FREQ: f64 = 1.0 * 1000.0 * 1000.0;

const APIC_TIMER_MODE_MASK: u32 = 3 << 17;

const APIC_TIMER_MODE_ONE_SHOT: u32 = 0;
const APIC_TIMER_MODE_PERIODIC: u32 = 1 << 17;

const _APIC_TIMER_MODE_TSC: u32 = 2 << 17;

const DELIVERY_MODES: [&str; 8] = [
    "Fixed (0)",
    "Lowest Prio (1)",
    "SMI (2)",
    "Reserved (3)",
    "NMI (4)",
    "INIT (5)",
    "Start-up (6)",
    "ExtINT (7)",
];

const DESTINATION_MODES: [&str; 2] = ["physical", "logical"];

const IOAPIC_CONFIG_MASKED: u32 = 0x10000;

const IOAPIC_DELIVERY_INIT: u8 = 5;
const IOAPIC_DELIVERY_NMI: u8 = 4;
const IOAPIC_DELIVERY_FIXED: u8 = 0;
const DELIVERY_LOWEST_PRIORITY: u8 = 1;
const DELIVERY_STARTUP: u8 = 6;
const DELIVERY_EXTINT: u8 = 7;
const DELIVERY_SMI: u8 = 2;

const ICR_LEVEL_ASSERT: u32 = 1 << 14;
const APIC_SOFTWARE_ENABLE: u32 = 1 << 8;
const ESR_SEND_ILLEGAL_VECTOR: u32 = 1 << 5;
const ESR_RECEIVE_ILLEGAL_VECTOR: u32 = 1 << 6;
const ESR_ILLEGAL_REGISTER: u32 = 1 << 7;

/// Cores a machine can have; each has its own local APIC
pub const MAX_CORES: usize = 8;

/// Events for the core scheduler in JavaScript (CPU.prototype.run_cores),
/// taken with apic_take_core_events: INIT and a start-up IPI (vector in bits 8..15)
pub const CORE_EVENT_INIT: u32 = 1;
pub const CORE_EVENT_SIPI: u32 = 2;

// keep in sync with cpu.js
#[allow(dead_code)]
const APIC_STRUCT_SIZE: usize = 4 * 46;

// Note: JavaScript (cpu.get_state_apic) depens on this layout
const _: () = assert!(std::mem::offset_of!(Apic, timer_last_tick) == 6 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, lvt_timer) == 8 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, lvt_perf_counter) == 9 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, icr0) == 14 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, icr1) == 15 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, irr) == 16 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, isr) == 24 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, tmr) == 32 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, spurious_vector) == 40 * 4);
const _: () = assert!(std::mem::offset_of!(Apic, lvt_thermal_sensor) == 45 * 4);
const _: () = assert!(std::mem::size_of::<Apic>() == APIC_STRUCT_SIZE);
#[repr(C)]
pub struct Apic {
    apic_id: u32,
    timer_divider: u32,
    timer_divider_shift: u32,
    timer_initial_count: u32,
    timer_current_count: u32,
    timer_last_tick: f64,
    lvt_timer: u32,
    lvt_perf_counter: u32,
    lvt_int0: u32,
    lvt_int1: u32,
    lvt_error: u32,
    tpr: u32,
    icr0: u32,
    icr1: u32,
    irr: [u32; 8],
    isr: [u32; 8],
    tmr: [u32; 8],
    spurious_vector: u32,
    destination_format: u32,
    local_destination: u32,
    error: u32,
    read_error: u32,
    lvt_thermal_sensor: u32,
}

const APIC_RESET: Apic = Apic {
    apic_id: 0,
    timer_divider: 0,
    timer_divider_shift: 1,
    timer_initial_count: 0,
    timer_current_count: 0,
    timer_last_tick: 0.0,
    lvt_timer: IOAPIC_CONFIG_MASKED,
    lvt_thermal_sensor: IOAPIC_CONFIG_MASKED,
    lvt_perf_counter: IOAPIC_CONFIG_MASKED,
    lvt_int0: IOAPIC_CONFIG_MASKED,
    lvt_int1: IOAPIC_CONFIG_MASKED,
    lvt_error: IOAPIC_CONFIG_MASKED,
    tpr: 0,
    icr0: 0,
    icr1: 0,
    irr: [0; 8],
    isr: [0; 8],
    tmr: [0; 8],
    spurious_vector: 0xFF,
    destination_format: !0,
    local_destination: 0,
    error: 0,
    read_error: 0,
};

// One local APIC per core. Only one core runs at a time (cooperative
// multicore: the active core's state is swapped in, see
// CPU.prototype.save_core_state); CURRENT_CORE is the one whose APIC the
// MMIO window, interrupt acceptance and CPUID see.
static mut APICS: [Apic; MAX_CORES] = [APIC_RESET; MAX_CORES];
static mut CURRENT_CORE: usize = 0;
static mut CORE_COUNT: usize = 1;
static mut CORE_EVENTS: [u32; MAX_CORES] = [0; MAX_CORES];
/// NMIs latched for each core until it can take one (nmi_blocked)
static mut NMI_PENDING: [u32; MAX_CORES] = [0; MAX_CORES];
/// SMIs latched for each core until it can take one (not in SMM)
static mut SMI_PENDING: [u32; MAX_CORES] = [0; MAX_CORES];

// With cores in workers (crate::parallel), the APICs, their latches and the
// core count are the machine instance's, reached through parallel::machine;
// CURRENT_CORE stays the core of this instance. Other cores' latches and
// request registers (IRR, pending trigger modes, ESR) change with atomic
// word operations; the rest of an APIC belongs to its own core.
fn core_events(core: usize) -> *mut u32 {
    dbg_assert!(core < MAX_CORES);
    unsafe {
        parallel::machine(&raw mut CORE_EVENTS)
            .cast::<u32>()
            .add(core)
    }
}
fn nmi_latch(core: usize) -> *mut u32 {
    dbg_assert!(core < MAX_CORES);
    unsafe {
        parallel::machine(&raw mut NMI_PENDING)
            .cast::<u32>()
            .add(core)
    }
}
fn smi_latch(core: usize) -> *mut u32 {
    dbg_assert!(core < MAX_CORES);
    unsafe {
        parallel::machine(&raw mut SMI_PENDING)
            .cast::<u32>()
            .add(core)
    }
}
/// A worker's instance runs this core
pub unsafe fn attach_worker(core: u32) {
    dbg_assert!((core as usize) < core_count());
    CURRENT_CORE = core as usize;
}
/// Whether an event for `core` must wake it in another worker
fn remote(core: usize) -> bool { parallel::active() && core != current_core() }

// Keep the legacy 184-byte LAPIC image stable. These additional architectural
// latches are snapshotted separately; they are not scheduler/JIT cache state.
#[repr(C)]
struct ApicAux {
    hardware_enabled: u32,
    extint_pending: u32,
    // An interrupt may be queued while its vector is still in service. Its
    // trigger mode must not overwrite the mode needed by the current EOI.
    pending_tmr: [u32; 8],
    ipi_sent: u32,
    ipi_received: u32,
}
const APIC_AUX_RESET: ApicAux = ApicAux {
    hardware_enabled: 1,
    extint_pending: 0,
    pending_tmr: [0; 8],
    ipi_sent: 0,
    ipi_received: 0,
};
static mut APIC_AUX: [ApicAux; MAX_CORES] = [APIC_AUX_RESET; MAX_CORES];

fn aux_of(core: usize) -> &'static mut ApicAux {
    dbg_assert!(core < MAX_CORES);
    unsafe {
        &mut *parallel::machine(&raw mut APIC_AUX)
            .cast::<ApicAux>()
            .add(core)
    }
}

#[no_mangle]
pub fn apic_aux_addr(core: u32) -> u32 { &raw mut *aux_of(core as usize) as u32 }
#[no_mangle]
pub fn apic_aux_size() -> u32 { std::mem::size_of::<ApicAux>() as u32 }
/// Version-6 images contain only the original LAPIC registers. Reconstruct
/// queued trigger modes before the first acknowledge, including level IRQs.
#[no_mangle]
pub fn apic_restore_legacy_aux(core: u32, enabled: bool) {
    let apic = apic_of(core as usize);
    let aux = aux_of(core as usize);
    *aux = APIC_AUX_RESET;
    aux.hardware_enabled = enabled as u32;
    for i in 0..8 {
        aux.pending_tmr[i] = apic.irr[i] & apic.tmr[i];
    }
}

#[no_mangle]
pub fn apic_core_ipi_sent(core: u32) -> u32 { aux_of(core as usize).ipi_sent }
#[no_mangle]
pub fn apic_core_ipi_received(core: u32) -> u32 { aux_of(core as usize).ipi_received }
#[no_mangle]
pub fn apic_core_hardware_enabled(core: u32) -> bool { aux_of(core as usize).hardware_enabled != 0 }
#[no_mangle]
pub fn apic_set_hardware_enabled(core: u32, enabled: bool) {
    aux_of(core as usize).hardware_enabled = enabled as u32;
}
#[no_mangle]
pub fn apic_core_extint_pending(core: u32) -> bool { aux_of(core as usize).extint_pending != 0 }
#[no_mangle]
pub fn apic_restore_extint(core: u32, pending: bool) {
    unsafe {
        parallel::word_store(
            &raw mut aux_of(core as usize).extint_pending,
            pending as u32,
        )
    };
}

fn apic_of(core: usize) -> &'static mut Apic {
    dbg_assert!(core < MAX_CORES);
    unsafe { &mut *parallel::machine(&raw mut APICS).cast::<Apic>().add(core) }
}

pub fn get_apic() -> &'static mut Apic { apic_of(current_core()) }

pub fn current_core() -> usize { unsafe { CURRENT_CORE } }
pub fn core_count() -> usize { unsafe { *parallel::machine(&raw mut CORE_COUNT) } }

#[no_mangle]
pub fn get_apic_addr() -> u32 { &raw mut *get_apic() as u32 }

/// Address of a core's local APIC (layout: see CPU.prototype.get_state_apic)
#[no_mangle]
pub fn apic_addr(core: u32) -> u32 { &raw mut *apic_of(core as usize) as u32 }

/// Power-on state of all local APICs; core i gets APIC ID i
#[no_mangle]
pub unsafe fn apic_set_core_count(count: u32) {
    dbg_assert!(count >= 1 && count as usize <= MAX_CORES);
    crate::cpu::execution::flush_core_statistics();
    *parallel::machine(&raw mut CORE_COUNT) = count as usize;
    CURRENT_CORE = 0;
    for core in 0..MAX_CORES {
        *apic_of(core) = APIC_RESET;
        apic_of(core).apic_id = (core as u32) << 24;
        *aux_of(core) = APIC_AUX_RESET;
        if core == 0 {
            // Platform virtual-wire power-on compatibility: the BSP receives
            // the 8259 output through LINT0 until firmware programs/masks it.
            apic_of(core).lvt_int0 = (DELIVERY_EXTINT as u32) << 8;
        }
        *core_events(core) = 0;
        *nmi_latch(core) = 0;
        *smi_latch(core) = 0;
    }
}

/// IA32_APIC_BASE.EN cleared: the local APIC returns to its power-on state,
/// including the initial APIC ID (as KVM does when it is enabled again)
pub unsafe fn software_disable() {
    let core = current_core();
    *apic_of(core) = APIC_RESET;
    apic_of(core).apic_id = (core as u32) << 24;
    *aux_of(core) = APIC_AUX_RESET;
    aux_of(core).hardware_enabled = 0;
    parallel::word_store(nmi_latch(core), 0);
    parallel::word_store(core_events(core), 0);
}

/// Take a pending NMI of the active core
pub unsafe fn take_nmi() -> bool {
    parallel::word_load(nmi_latch(current_core())) != 0
        && parallel::word_swap(nmi_latch(current_core()), 0) != 0
}

pub unsafe fn nmi_pending() -> bool { parallel::word_load(nmi_latch(current_core())) != 0 }

#[no_mangle]
pub unsafe fn apic_core_nmi_pending(core: u32) -> bool {
    parallel::word_load(nmi_latch(core as usize)) != 0
}

/// An SMI for `core`: the chipset's SMI# (src/acpi.js), or an SMI message
/// (an IPI, MSI or IOAPIC entry with delivery mode SMI). Latched, one deep,
/// until the core can take it: not while it is in SMM (crate::cpu::smm)
#[no_mangle]
pub unsafe fn apic_raise_smi(core: u32) {
    dbg_assert!((core as usize) < core_count());
    parallel::word_store(smi_latch(core as usize), 1);
    parallel::kick(core as usize);
}

/// Take a pending SMI of the active core
pub unsafe fn take_smi() -> bool {
    parallel::word_load(smi_latch(current_core())) != 0
        && parallel::word_swap(smi_latch(current_core()), 0) != 0
}

pub unsafe fn smi_pending() -> bool { parallel::word_load(smi_latch(current_core())) != 0 }

#[no_mangle]
pub unsafe fn apic_core_smi_pending(core: u32) -> bool {
    parallel::word_load(smi_latch(core as usize)) != 0
}

#[no_mangle]
pub unsafe fn apic_restore_smi(core: u32, pending: bool) {
    dbg_assert!((core as usize) < core_count());
    parallel::word_store(smi_latch(core as usize), pending as u32);
}

#[no_mangle]
pub unsafe fn apic_set_current_core(core: u32) {
    dbg_assert!((core as usize) < core_count());
    crate::cpu::execution::flush_core_statistics();
    CURRENT_CORE = core as usize;
}

/// INIT: the local APIC returns to its power-on state except for its ID
#[no_mangle]
pub unsafe fn apic_init_core(core: u32) {
    let apic = apic_of(core as usize);
    let apic_id = apic.apic_id;
    *apic = APIC_RESET;
    apic.apic_id = apic_id;
    let aux = aux_of(core as usize);
    aux.hardware_enabled = 1;
    parallel::word_store(&raw mut aux.extint_pending, 0);
    for word in 0..8 {
        parallel::word_store(&raw mut aux.pending_tmr[word], 0);
    }
}

#[no_mangle]
pub unsafe fn apic_take_core_events(core: u32) -> u32 {
    if parallel::word_load(core_events(core as usize)) == 0 {
        return 0;
    }
    parallel::word_swap(core_events(core as usize), 0)
}

/// Snapshot the pending startup events without acknowledging them.
#[no_mangle]
pub unsafe fn apic_peek_core_events(core: u32) -> u32 {
    parallel::word_load(core_events(core as usize))
}

/// INIT or start-up IPIs are waiting: for any core in a cooperative machine
/// (the scheduler takes them); with workers, for this instance's core
pub unsafe fn has_core_events() -> bool {
    if parallel::active() {
        return parallel::word_load(core_events(current_core())) != 0;
    }
    (0..core_count()).any(|core| *core_events(core) != 0)
}

#[no_mangle]
pub unsafe fn apic_restore_core_events(core: u32, events: u32, nmi: bool) {
    dbg_assert!((core as usize) < core_count());
    parallel::word_store(core_events(core as usize), events);
    parallel::word_store(nmi_latch(core as usize), nmi as u32);
}

/// Whether a (halted) core has an interrupt it would accept
#[no_mangle]
pub unsafe fn apic_core_interrupt_pending(core: u32) -> bool {
    let core = core as usize;
    pending_irq(apic_of(core), aux_of(core)).is_some() || routed_pic_pending(core as u32)
}

pub fn read32(addr: u32) -> u32 {
    if unsafe { !*acpi_enabled } {
        return 0;
    }
    if !apic_core_hardware_enabled(current_core() as u32) {
        return !0;
    }
    read32_internal(get_apic(), addr)
}

fn read32_internal(apic: &mut Apic, addr: u32) -> u32 {
    match addr {
        0x20 => {
            dbg_log!("APIC read id");
            apic.apic_id
        },

        0x30 => {
            // version
            dbg_log!("APIC read version");
            0x50014
        },

        0x80 => {
            if APIC_LOG_VERBOSE {
                dbg_log!("APIC read tpr");
            }
            apic.tpr
        },

        0xA0 => processor_priority(apic) as u32,

        0xB0 => {
            // write-only (written by DSL)
            if APIC_LOG_VERBOSE {
                dbg_log!("APIC read eoi register");
            }
            0
        },

        0xD0 => {
            dbg_log!("Read local destination");
            apic.local_destination
        },

        0xE0 => {
            dbg_log!("Read destination format");
            apic.destination_format
        },

        0xF0 => apic.spurious_vector,

        0x100 | 0x110 | 0x120 | 0x130 | 0x140 | 0x150 | 0x160 | 0x170 => {
            let index = ((addr - 0x100) >> 4) as usize;
            dbg_log!("Read isr {}: {:08x}", index, apic.isr[index] as u32);
            apic.isr[index]
        },

        0x180 | 0x190 | 0x1A0 | 0x1B0 | 0x1C0 | 0x1D0 | 0x1E0 | 0x1F0 => {
            let index = ((addr - 0x180) >> 4) as usize;
            dbg_log!("Read tmr {}: {:08x}", index, apic.tmr[index] as u32);
            apic.tmr[index]
        },

        0x200 | 0x210 | 0x220 | 0x230 | 0x240 | 0x250 | 0x260 | 0x270 => {
            let index = ((addr - 0x200) >> 4) as usize;
            dbg_log!("Read irr {}: {:08x}", index, apic.irr[index] as u32);
            apic.irr[index]
        },

        0x280 => {
            dbg_log!("Read error: {:08x}", apic.read_error);
            apic.read_error
        },

        0x300 => {
            if APIC_LOG_VERBOSE {
                dbg_log!("APIC read icr0");
            }
            apic.icr0
        },

        0x310 => {
            dbg_log!("APIC read icr1");
            apic.icr1
        },

        0x320 => {
            if APIC_LOG_VERBOSE {
                dbg_log!("read timer lvt");
            }
            apic.lvt_timer
        },

        0x330 => {
            dbg_log!("read lvt thermal sensor");
            apic.lvt_thermal_sensor
        },

        0x340 => {
            dbg_log!("read lvt perf counter");
            apic.lvt_perf_counter
        },

        0x350 => {
            dbg_log!("read lvt int0");
            apic.lvt_int0
        },

        0x360 => {
            dbg_log!("read lvt int1");
            apic.lvt_int1
        },

        0x370 => {
            dbg_log!("read lvt error");
            apic.lvt_error
        },

        0x3E0 => {
            // divider
            dbg_log!("read timer divider");
            apic.timer_divider
        },

        0x380 => {
            dbg_log!("read timer initial count");
            apic.timer_initial_count
        },

        0x390 => timer_current_count(apic, unsafe { js::microtick() }),

        _ => {
            dbg_log!("APIC read {:x}", addr);
            apic.error |= ESR_ILLEGAL_REGISTER;
            0
        },
    }
}

pub fn write32(addr: u32, value: u32) {
    if unsafe { !*acpi_enabled } {
        return;
    }
    // Routing may touch the sending APIC again. End its exclusive borrow
    // before delivering an IPI or an IOAPIC EOI that can reassert the line.
    if !apic_core_hardware_enabled(current_core() as u32) {
        return;
    }
    match write32_internal(get_apic(), aux_of(current_core()), addr, value) {
        Some(ApicAction::Eoi(vector)) => ioapic::remote_eoi(vector),
        Some(ApicAction::Ipi { value, destination }) => {
            let source = current_core();
            aux_of(source).ipi_sent = aux_of(source).ipi_sent.wrapping_add(1);
            let targets = match (value >> 18) & 3 {
                0 => destination_cores(destination, ((value >> 11) & 1) as u8),
                1 => vec![source],
                2 => (0..core_count()).collect(),
                _ => (0..core_count()).filter(|&c| c != source).collect(),
            };
            deliver_to_cores(
                &targets,
                value as u8,
                ((value >> 8) & 7) as u8,
                false, // integrated xAPIC IPIs are edge-triggered (except INIT deassert)
                true,
            );
        },
        None => {},
    }
}

enum ApicAction {
    Eoi(u8),
    Ipi { value: u32, destination: u8 },
}

fn write32_internal(
    apic: &mut Apic,
    aux: &mut ApicAux,
    addr: u32,
    value: u32,
) -> Option<ApicAction> {
    match addr {
        0x20 => {
            dbg_log!("APIC write id: {:08x}", value >> 8);
            apic.apic_id = value & 0xFF000000;
        },

        0x30 => {
            // version
            dbg_log!("APIC write version: {:08x}, ignored", value);
        },

        0x80 => {
            if APIC_LOG_VERBOSE {
                dbg_log!("Set tpr: {:02x}", value & 0xFF);
            }
            apic.tpr = value & 0xFF;
        },

        0xB0 => {
            if let Some(highest_isr) = highest_isr(apic) {
                if APIC_LOG_VERBOSE {
                    dbg_log!("eoi: {:08x} for vector {:x}", value, highest_isr);
                }
                register_clear_bit(&mut apic.isr, highest_isr);
                // TMR records the last accepted trigger mode; EOI clears
                // ISR, not TMR. The next acknowledge installs queued mode.
                if register_get_bit(&apic.tmr, highest_isr) {
                    return Some(ApicAction::Eoi(highest_isr));
                }
            }
            else {
                dbg_log!("Bad eoi: No isr set");
            }
        },

        0xD0 => {
            dbg_log!("Set local destination: {:08x}", value);
            apic.local_destination = value & 0xFF000000;
        },

        0xE0 => {
            dbg_log!("Set destination format: {:08x}", value);
            apic.destination_format = value | 0x0FFFFFFF;
        },

        0xF0 => {
            dbg_log!("Set spurious vector: {:08x}", value);
            // Directed EOI suppression is not advertised by our version.
            apic.spurious_vector = value & 0x3FF;
            if value & APIC_SOFTWARE_ENABLE == 0 {
                apic.lvt_timer |= IOAPIC_CONFIG_MASKED;
                apic.lvt_thermal_sensor |= IOAPIC_CONFIG_MASKED;
                apic.lvt_perf_counter |= IOAPIC_CONFIG_MASKED;
                apic.lvt_int0 |= IOAPIC_CONFIG_MASKED;
                apic.lvt_int1 |= IOAPIC_CONFIG_MASKED;
                apic.lvt_error |= IOAPIC_CONFIG_MASKED;
            }
        },

        0x280 => {
            // updated readable error register with real error
            dbg_log!("Write error: {:08x}", value);
            apic.read_error = apic.error;
            apic.error = 0;
        },

        0x300 => {
            let vector = (value & 0xFF) as u8;
            let delivery_mode = ((value >> 8) & 7) as u8;
            let destination_mode = ((value >> 11) & 1) as u8;
            let is_level = value & ioapic::IOAPIC_CONFIG_TRIGGER_MODE_LEVEL
                == ioapic::IOAPIC_CONFIG_TRIGGER_MODE_LEVEL;
            let destination_shorthand = (value >> 18) & 3;
            let destination = (apic.icr1 >> 24) as u8;
            dbg_log!(
                "APIC write icr0: {:08x} vector={:02x} destination_mode={} delivery_mode={} destination_shorthand={}",
                value,
                vector,
                DESTINATION_MODES[destination_mode as usize],
                DELIVERY_MODES[delivery_mode as usize],
                ["no", "self", "all with self", "all without self"][destination_shorthand as usize]
            );

            // delivery is immediate: the status bit (12) always reads as idle
            apic.icr0 = value & !(1 << 12);

            // ExtINT is not a legal ICR delivery mode. Reserved encodings
            // must never become fixed IRQs.
            if matches!(delivery_mode, 3 | DELIVERY_EXTINT) {
                return None;
            }
            if matches!(
                delivery_mode,
                IOAPIC_DELIVERY_FIXED | DELIVERY_LOWEST_PRIORITY
            ) && vector < 0x10
            {
                apic.error |= ESR_SEND_ILLEGAL_VECTOR;
                return None;
            }
            let is_assert = value & ICR_LEVEL_ASSERT != 0;
            if delivery_mode == IOAPIC_DELIVERY_INIT && is_level && !is_assert {
                // INIT level de-assert only synchronizes arbitration IDs
                return None;
            }
            return Some(ApicAction::Ipi { value, destination });
        },

        0x310 => {
            dbg_log!("APIC write icr1: {:08x}", value);
            apic.icr1 = value;
        },

        0x320 => {
            if APIC_LOG_VERBOSE {
                dbg_log!("timer lvt: {:08x}", value);
            }
            // Expire under the previous mask/mode before changing it: an
            // elapsed masked one-shot must not be resurrected by unmasking.
            timer(apic, aux, unsafe { js::microtick() });
            apic.lvt_timer = masked_lvt(apic, value & 0x700FF);
        },

        0x330 => {
            dbg_log!("lvt thermal sensor: {:08x}", value);
            apic.lvt_thermal_sensor = masked_lvt(apic, value);
        },

        0x340 => {
            dbg_log!("lvt perf counter: {:08x}", value);
            apic.lvt_perf_counter = masked_lvt(apic, value);
        },

        0x350 => {
            dbg_log!("lvt int0: {:08x}", value);
            apic.lvt_int0 = masked_lvt(apic, value);
        },

        0x360 => {
            dbg_log!("lvt int1: {:08x}", value);
            apic.lvt_int1 = masked_lvt(apic, value);
        },

        0x370 => {
            dbg_log!("lvt error: {:08x}", value);
            apic.lvt_error = masked_lvt(apic, value);
        },

        0x3E0 => {
            apic.timer_divider = value;

            let divide_shift = (value & 0b11) | ((value & 0b1000) >> 1);
            apic.timer_divider_shift = if divide_shift == 0b111 { 0 } else { divide_shift + 1 };
            dbg_log!(
                "APIC timer divider: {:08x} shift={} tick={:.6}ms",
                apic.timer_divider,
                apic.timer_divider_shift,
                (1 << apic.timer_divider_shift) as f64 / APIC_TIMER_FREQ
            );
        },

        0x380 => {
            if APIC_LOG_VERBOSE {
                dbg_log!(
                    "APIC timer initial: {} next_interrupt={:.2}ms",
                    value,
                    value as f64 * (1 << apic.timer_divider_shift) as f64 / APIC_TIMER_FREQ,
                );
            }
            apic.timer_initial_count = value;
            apic.timer_current_count = value;
            apic.timer_last_tick = unsafe { js::microtick() };
        },

        0x390 => {
            dbg_log!("write timer current: {:08x}", value);
            // Writes to the read-only current count are ignored.
        },

        _ => {
            dbg_log!("APIC write32 {:x} <- {:08x}", addr, value);
            apic.error |= ESR_ILLEGAL_REGISTER;
        },
    }
    None
}

fn masked_lvt(apic: &Apic, value: u32) -> u32 {
    value | if apic.spurious_vector & APIC_SOFTWARE_ENABLE == 0 { IOAPIC_CONFIG_MASKED } else { 0 }
}

/// Advance the timer of every core's local APIC (with cores in workers, of
/// this instance's core: each worker runs its own)
#[no_mangle]
pub fn apic_timer(now: f64) -> f64 {
    if parallel::active() {
        let core = current_core();
        return timer(apic_of(core), aux_of(core), now);
    }
    let mut next = 100.0f64;
    for core in 0..core_count() {
        next = next.min(timer(apic_of(core), aux_of(core), now));
    }
    next
}

fn timer_current_count(apic: &Apic, now: f64) -> u32 {
    if apic.timer_initial_count == 0 || apic.timer_current_count == 0 {
        return 0;
    }
    let ticks = ((now - apic.timer_last_tick).max(0.0) * APIC_TIMER_FREQ
        / (1 << apic.timer_divider_shift) as f64) as u64;
    match apic.lvt_timer & APIC_TIMER_MODE_MASK {
        APIC_TIMER_MODE_PERIODIC => {
            apic.timer_initial_count - (ticks % apic.timer_initial_count as u64) as u32
        },
        APIC_TIMER_MODE_ONE_SHOT => apic
            .timer_initial_count
            .saturating_sub(ticks.min(u32::MAX as u64) as u32),
        _ => 0, // TSC deadline is not advertised; reserved modes do not run.
    }
}

fn timer(apic: &mut Apic, aux: &mut ApicAux, now: f64) -> f64 {
    if aux.hardware_enabled == 0 || apic.timer_initial_count == 0 || apic.timer_current_count == 0 {
        return 100.0;
    }
    let mode = apic.lvt_timer & APIC_TIMER_MODE_MASK;
    if mode != APIC_TIMER_MODE_PERIODIC && mode != APIC_TIMER_MODE_ONE_SHOT {
        return 100.0;
    }
    if apic.timer_last_tick > now {
        apic.timer_last_tick = now;
    }
    let period =
        apic.timer_initial_count as f64 * (1 << apic.timer_divider_shift) as f64 / APIC_TIMER_FREQ;
    let elapsed = now - apic.timer_last_tick;
    if elapsed >= period {
        if mode == APIC_TIMER_MODE_PERIODIC {
            // Coalesce overdue expirations, preserving the timer's phase.
            apic.timer_last_tick += (elapsed / period).floor() * period;
        }
        else {
            apic.timer_current_count = 0;
        }
        if apic.lvt_timer & IOAPIC_CONFIG_MASKED == 0 {
            deliver(apic, aux, apic.lvt_timer as u8, false, false);
        }
    }
    if apic.timer_current_count == 0 {
        100.0
    }
    else {
        (apic.timer_last_tick + period - now).max(0.0)
    }
}

/// Deliver an interrupt from the IO APIC (or an IPI) to the local APICs its
/// destination selects
pub fn route(vector: u8, mode: u8, is_level: bool, destination: u8, destination_mode: u8) -> bool {
    deliver_to_cores(
        &destination_cores(destination, destination_mode),
        vector,
        mode,
        is_level,
        false,
    )
}

/// Cores selected by a destination field: physical (APIC ID, 0xFF = all) or
/// logical (flat or cluster model, per the core's DFR/LDR)
fn destination_cores(destination: u8, destination_mode: u8) -> Vec<usize> {
    (0..core_count())
        .filter(|&core| {
            let apic = apic_of(core);
            if destination == 0xFF && destination_mode == 0 {
                return true;
            }
            if destination_mode == 0 {
                return (apic.apic_id >> 24) as u8 == destination;
            }
            let ldr = (apic.local_destination >> 24) as u8;
            if apic.destination_format >> 28 == 0xF {
                // flat model: 8 bits, one per APIC
                ldr & destination != 0
            }
            else if apic.destination_format >> 28 == 0 {
                // Cluster 0xF broadcasts to all clusters, while low bits
                // still select members. Other DFR encodings are reserved.
                (destination >> 4 == 0xF || ldr >> 4 == destination >> 4)
                    && ldr & destination & 0xF != 0
            }
            else {
                false
            }
        })
        .collect()
}

fn fixed_enabled(apic: &Apic, aux: &ApicAux) -> bool {
    aux.hardware_enabled != 0 && apic.spurious_vector & APIC_SOFTWARE_ENABLE != 0
}

fn deliver_to_cores(cores: &[usize], vector: u8, mode: u8, is_level: bool, is_ipi: bool) -> bool {
    if mode == DELIVERY_LOWEST_PRIORITY {
        // A disabled recipient does not participate in arbitration.
        if let Some(&core) = cores
            .iter()
            .filter(|&&core| fixed_enabled(apic_of(core), aux_of(core)))
            .min_by_key(|&&core| {
                let apic = apic_of(core);
                (processor_priority(apic) & 0xF0, apic.apic_id >> 24)
            })
        {
            let accepted = deliver(apic_of(core), aux_of(core), vector, is_level, remote(core));
            if accepted && is_ipi {
                count_ipi(core);
            }
            if accepted {
                unsafe { parallel::kick(core) };
            }
            return accepted;
        }
        return false;
    }
    let mut accepted = false;
    for &core in cores {
        if aux_of(core).hardware_enabled == 0 {
            continue;
        }
        let accepted_here = match mode {
            IOAPIC_DELIVERY_INIT => unsafe {
                parallel::word_store(core_events(core), CORE_EVENT_INIT);
                parallel::word_store(nmi_latch(core), 0);
                parallel::word_store(smi_latch(core), 0);
                parallel::word_store(&raw mut aux_of(core).extint_pending, 0);
                true
            },
            DELIVERY_STARTUP => unsafe {
                // The BSP never waits for SIPI; AP scheduler state ignores
                // subsequent SIPIs after the first has started execution.
                core != 0 && sipi_latch(core, vector)
            },
            IOAPIC_DELIVERY_NMI => unsafe {
                parallel::word_store(nmi_latch(core), 1);
                true
            },
            // (the vector is ignored)
            DELIVERY_SMI => unsafe {
                parallel::word_store(smi_latch(core), 1);
                true
            },
            DELIVERY_EXTINT => {
                if fixed_enabled(apic_of(core), aux_of(core)) {
                    unsafe { parallel::word_store(&raw mut aux_of(core).extint_pending, 1) };
                    true
                }
                else {
                    false
                }
            },
            IOAPIC_DELIVERY_FIXED => {
                deliver(apic_of(core), aux_of(core), vector, is_level, remote(core))
            },
            _ => false, // reserved: never reinterpret as fixed
        };
        if accepted_here && is_ipi {
            count_ipi(core);
        }
        if accepted_here {
            unsafe { parallel::kick(core) };
        }
        accepted |= accepted_here;
        if accepted_here && mode == DELIVERY_EXTINT {
            // ExtINT represents one shared 8259 acknowledge cycle.
            break;
        }
    }
    accepted
}

/// Only this core's first start-up IPI after INIT counts
unsafe fn sipi_latch(core: usize, vector: u8) -> bool {
    let events = core_events(core);
    loop {
        let current = parallel::word_load(events);
        if current & CORE_EVENT_SIPI != 0 {
            return false;
        }
        let value = current | CORE_EVENT_SIPI | (vector as u32) << 8;
        if parallel::compare_exchange(events.cast(), 4, current as u64, value as u64) {
            return true;
        }
    }
}

fn count_ipi(core: usize) {
    let aux = aux_of(core);
    aux.ipi_received = aux.ipi_received.wrapping_add(1);
}

/// Accept a fixed interrupt into IRR. For a core running in another worker
/// (`remote`), only the request words change, atomically: its TMR takes the
/// queued trigger mode when that core acknowledges the vector.
fn deliver(apic: &mut Apic, aux: &mut ApicAux, vector: u8, is_level: bool, remote: bool) -> bool {
    if !fixed_enabled(apic, aux) {
        return false;
    }
    if vector < 0x10 {
        unsafe { parallel::word_or(&raw mut apic.error, ESR_RECEIVE_ILLEGAL_VECTOR) };
        return false;
    }
    if register_get_bit(&apic.irr, vector) {
        return true;
    }
    register_update(&raw mut aux.pending_tmr, vector, is_level);
    register_update(&raw mut apic.irr, vector, true);
    if !remote && !register_get_bit(&apic.isr, vector) {
        if is_level {
            register_set_bit(&mut apic.tmr, vector);
        }
        else {
            register_clear_bit(&mut apic.tmr, vector);
        }
    }
    true
}

/// The platform wires the PIC output to BSP LINT0 and IOAPIC input 0.
/// An IOAPIC ExtINT RTE routes that same output to its selected processor.
/// An explicit ExtINT message is also latched until the recipient accepts it.
#[no_mangle]
pub fn routed_pic_pending(core: u32) -> bool {
    if !pic::has_pending_irq() {
        return false;
    }
    let core = core as usize;
    if unsafe { !*acpi_enabled } || aux_of(core).hardware_enabled == 0 {
        return core == 0;
    }
    let apic = apic_of(core);
    if aux_of(core).extint_pending != 0 && fixed_enabled(apic, aux_of(core)) {
        return true;
    }
    if core == 0
        && apic.lvt_int0 & IOAPIC_CONFIG_MASKED == 0
        && (apic.lvt_int0 >> 8) & 7 == DELIVERY_EXTINT as u32
    {
        return true;
    }
    if let Some((destination, mode)) = ioapic::pic_destination() {
        return destination_cores(destination, mode)
            .into_iter()
            .find(|&target| fixed_enabled(apic_of(target), aux_of(target)))
            == Some(core);
    }
    false
}

pub fn acknowledge_pic_irq() -> Option<u8> {
    if !routed_pic_pending(current_core() as u32) {
        return None;
    }
    let vector = pic::pic_acknowledge_irq();
    // Only one CPU can acknowledge the shared PIC output. Retire broadcast
    // latches together, so a stale target cannot steal the next device IRQ.
    for core in 0..core_count() {
        unsafe { parallel::word_store(&raw mut aux_of(core).extint_pending, 0) };
    }
    vector
}

fn highest_irr(apic: &Apic) -> Option<u8> {
    let highest = register_get_highest_bit(&apic.irr);
    if let Some(x) = highest {
        dbg_assert!(x >= 0x10);
    }
    highest
}

fn highest_isr(apic: &Apic) -> Option<u8> {
    let highest = register_get_highest_bit(&apic.isr);
    if let Some(x) = highest {
        dbg_assert!(x >= 0x10);
    }
    highest
}

/// PPR preserves the TPR subclass only when the task-priority class is at
/// least the highest in-service interrupt's class (Intel SDM 11.8.3.1).
fn processor_priority(apic: &Apic) -> u8 {
    let task = apic.tpr as u8;
    let service = highest_isr(apic).unwrap_or(0) & 0xF0;
    if task & 0xF0 >= service {
        task
    }
    else {
        service
    }
}

/// Read-only; does not acknowledge or reprioritize an interrupt.
pub fn has_pending_irq() -> bool { pending_irq(get_apic(), aux_of(current_core())).is_some() }
pub fn acknowledge_irq() -> Option<u8> {
    acknowledge_irq_internal(get_apic(), aux_of(current_core()))
}

// Share the exact priority policy with acknowledgement, without modifying IRR,
// ISR or TPR. Continuation must not introduce a second interrupt policy.
fn pending_irq(apic: &Apic, aux: &ApicAux) -> Option<u8> {
    if !fixed_enabled(apic, aux) {
        return None;
    }
    let highest_irr = match highest_irr(apic) {
        None => return None,
        Some(x) => x,
    };

    if highest_irr & 0xF0 <= processor_priority(apic) & 0xF0 {
        if APIC_LOG_VERBOSE {
            dbg_log!(
                "Higher ppr, ppr={:x} irr={:x}",
                processor_priority(apic),
                highest_irr
            );
        }
        return None;
    }

    Some(highest_irr)
}

fn acknowledge_irq_internal(apic: &mut Apic, aux: &mut ApicAux) -> Option<u8> {
    let highest_irr = pending_irq(apic, aux)?;
    register_update(&raw mut apic.irr, highest_irr, false);
    register_set_bit(&mut apic.isr, highest_irr);
    if register_get_bit(&aux.pending_tmr, highest_irr) {
        register_set_bit(&mut apic.tmr, highest_irr);
    }
    else {
        register_clear_bit(&mut apic.tmr, highest_irr);
    }
    register_update(&raw mut aux.pending_tmr, highest_irr, false);

    if APIC_LOG_VERBOSE {
        dbg_log!("Calling vector {:x}", highest_irr);
    }

    dbg_assert!(pending_irq(apic, aux).is_none());

    Some(highest_irr)
}

// functions operating on 256-bit registers (for irr, isr, tmr)
fn register_get_bit(v: &[u32; 8], bit: u8) -> bool { v[(bit >> 5) as usize] & 1 << (bit & 31) != 0 }

fn register_set_bit(v: &mut [u32; 8], bit: u8) { v[(bit >> 5) as usize] |= 1 << (bit & 31); }

fn register_clear_bit(v: &mut [u32; 8], bit: u8) { v[(bit >> 5) as usize] &= !(1 << (bit & 31)); }

/// Set or clear a bit of a register other cores change as well (IRR, pending TMR)
fn register_update(v: *mut [u32; 8], bit: u8, set: bool) {
    unsafe {
        let word = v.cast::<u32>().add((bit >> 5) as usize);
        if set {
            parallel::word_or(word, 1 << (bit & 31));
        }
        else {
            parallel::word_and(word, !(1 << (bit & 31)));
        }
    }
}

fn register_get_highest_bit(v: &[u32; 8]) -> Option<u8> {
    dbg_assert!(v.as_ptr().addr() & std::mem::align_of::<u64>() - 1 == 0);
    let v: &[u64; 4] = unsafe { std::mem::transmute(v) };
    for i in (0..4).rev() {
        let word = v[i];

        if word != 0 {
            return Some(word.ilog2() as u8 | (i as u8) << 6);
        }
    }

    None
}

#[cfg(test)]
mod continuation_tests {
    use super::*;
    #[test]
    fn pending_query_is_pure_and_matches_acknowledgement() {
        for vector in [0x20, 0x51, 0x7F, 0xE0] {
            for service in [
                None,
                Some(0x30),
                Some(vector & 0xF0),
                Some(vector),
                Some(0xF0),
            ] {
                for tpr in [0, 0x50, 0x70, 0xF0] {
                    // Apic contains only integer and floating-point fields.
                    let mut apic = APIC_RESET;
                    let mut aux = APIC_AUX_RESET;
                    apic.spurious_vector |= APIC_SOFTWARE_ENABLE;
                    register_set_bit(&mut apic.irr, vector);
                    if let Some(service) = service {
                        register_set_bit(&mut apic.isr, service);
                    }
                    apic.tpr = tpr;
                    let before = (apic.irr, apic.isr, apic.tpr);
                    let pending = pending_irq(&apic, &aux);
                    assert_eq!((apic.irr, apic.isr, apic.tpr), before);
                    let expected = service.is_none_or(|s| s & 0xF0 < vector & 0xF0)
                        && (vector & 0xF0) > (tpr as u8 & 0xF0);
                    assert_eq!(pending, expected.then_some(vector));
                    assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), pending);
                    if !expected {
                        assert_eq!((apic.irr, apic.isr, apic.tpr), before);
                    }
                }
            }
        }
    }

    fn enabled_apic() -> (Apic, ApicAux) {
        let mut apic = APIC_RESET;
        apic.spurious_vector |= APIC_SOFTWARE_ENABLE;
        (apic, APIC_AUX_RESET)
    }

    #[test]
    fn disabled_apic_holds_pending_but_rejects_new_fixed_interrupts() {
        let (mut apic, mut aux) = enabled_apic();
        assert!(deliver(&mut apic, &mut aux, 0x51, false, false));
        apic.spurious_vector &= !APIC_SOFTWARE_ENABLE;
        assert_eq!(pending_irq(&apic, &aux), None);
        assert!(!deliver(&mut apic, &mut aux, 0x61, false, false));
        assert!(register_get_bit(&apic.irr, 0x51));
        assert!(!register_get_bit(&apic.irr, 0x61));
        apic.spurious_vector |= APIC_SOFTWARE_ENABLE;
        aux.hardware_enabled = 0;
        assert_eq!(pending_irq(&apic, &aux), None);
        aux.hardware_enabled = 1;
        assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), Some(0x51));
    }

    #[test]
    fn illegal_vectors_set_esr_and_ff_is_a_legal_interrupt_vector() {
        let (mut apic, mut aux) = enabled_apic();
        for vector in 0..16 {
            assert!(!deliver(&mut apic, &mut aux, vector, false, false));
        }
        assert_eq!(apic.error, ESR_RECEIVE_ILLEGAL_VECTOR);
        assert_eq!(apic.irr, [0; 8]);
        assert!(deliver(&mut apic, &mut aux, 0xFF, false, false));
        assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), Some(0xFF));
    }

    #[test]
    fn queued_edge_does_not_destroy_in_service_level_trigger_mode() {
        let (mut apic, mut aux) = enabled_apic();
        assert!(deliver(&mut apic, &mut aux, 0x51, true, false));
        assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), Some(0x51));
        assert!(register_get_bit(&apic.tmr, 0x51));
        assert!(deliver(&mut apic, &mut aux, 0x51, false, false));
        assert!(
            register_get_bit(&apic.tmr, 0x51),
            "EOI still requires broadcast"
        );
        register_clear_bit(&mut apic.isr, 0x51);
        assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), Some(0x51));
        assert!(
            !register_get_bit(&apic.tmr, 0x51),
            "queued edge does not require broadcast"
        );
    }

    #[test]
    fn periodic_timer_coalesces_expiry_without_losing_phase() {
        let (mut apic, mut aux) = enabled_apic();
        apic.lvt_timer = APIC_TIMER_MODE_PERIODIC | 0x60;
        apic.timer_divider_shift = 0;
        apic.timer_initial_count = 1_000_000;
        apic.timer_current_count = apic.timer_initial_count;
        assert_eq!(timer(&mut apic, &mut aux, 3.25), 0.75);
        assert_eq!(apic.timer_last_tick, 3.0);
        assert_eq!(timer_current_count(&apic, 3.25), 750_000);
        assert_eq!(acknowledge_irq_internal(&mut apic, &mut aux), Some(0x60));
        assert_eq!(timer(&mut apic, &mut aux, 3.5), 0.5);
        assert!(!register_get_bit(&apic.irr, 0x60));
        assert_eq!(timer(&mut apic, &mut aux, 4.0), 1.0);
        assert!(register_get_bit(&apic.irr, 0x60));
    }

    #[test]
    fn masked_one_shot_expires_without_being_replayed_on_unmask() {
        let (mut apic, mut aux) = enabled_apic();
        apic.lvt_timer = IOAPIC_CONFIG_MASKED | 0x60;
        apic.timer_divider_shift = 0;
        apic.timer_initial_count = 1_000_000;
        apic.timer_current_count = apic.timer_initial_count;
        assert_eq!(timer(&mut apic, &mut aux, 2.0), 100.0);
        assert_eq!(apic.timer_current_count, 0);
        assert_eq!(timer_current_count(&apic, 2.0), 0);
        apic.lvt_timer &= !IOAPIC_CONFIG_MASKED;
        assert_eq!(timer(&mut apic, &mut aux, 3.0), 100.0);
        assert_eq!(apic.irr, [0; 8]);
    }

    #[test]
    fn reserved_timer_modes_remain_stopped() {
        let (mut apic, mut aux) = enabled_apic();
        apic.timer_initial_count = 1;
        apic.timer_current_count = 1;
        for mode in [2, 3] {
            apic.lvt_timer = mode << 17 | 0x60;
            assert_eq!(timer(&mut apic, &mut aux, 10.0), 100.0);
            assert_eq!(timer_current_count(&apic, 10.0), 0);
        }
        assert_eq!(apic.irr, [0; 8]);
    }
}
                                                                                                                                                                                                 source/v64/src/rust/cpu/arith.rs                                                                    0000644 0000000 0000000 00000112124 00000000000 013715  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::cpu::cpu::*;
use crate::cpu::global_pointers::*;
use crate::cpu::misc_instr::{getaf, getcf, getzf};

fn int_log2(x: i32) -> i32 { 31 - x.leading_zeros() as i32 }

fn opsize_to_mask(op_size: i32) -> i32 {
    dbg_assert!(op_size == OPSIZE_8 || op_size == OPSIZE_16 || op_size == OPSIZE_32);
    (2 << op_size) - 1
}

unsafe fn add(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let res = (dest_operand + source_operand) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL;
    return res;
}
unsafe fn adc(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let cf = getcf() as i32;
    let res = (dest_operand + source_operand + cf) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW;
    *flags = *flags & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW
        | (dest_operand ^ ((dest_operand ^ source_operand) & (source_operand ^ res))) >> op_size
            & FLAG_CARRY
        | (dest_operand ^ source_operand ^ res) & FLAG_ADJUST
        | ((source_operand ^ res) & (dest_operand ^ res)) >> op_size << 11 & FLAG_OVERFLOW;
    return res;
}
unsafe fn sub(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let res = (dest_operand - source_operand) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL | FLAG_SUB;
    return res;
}
unsafe fn sbb(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let cf = getcf() as i32;
    let res = (dest_operand - source_operand - cf) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW | FLAG_SUB;
    *flags = *flags & !FLAG_CARRY & !FLAG_ADJUST & !FLAG_OVERFLOW
        | (res ^ ((res ^ source_operand) & (source_operand ^ dest_operand))) >> op_size
            & FLAG_CARRY
        | (dest_operand ^ source_operand ^ res) & FLAG_ADJUST
        | ((source_operand ^ dest_operand) & (res ^ dest_operand)) >> op_size << 11 & FLAG_OVERFLOW;
    return res;
}
pub unsafe fn add8(x: i32, y: i32) -> i32 {
    dbg_assert!(x >= 0 && x < 0x100);
    dbg_assert!(y >= 0 && y < 0x100);
    return add(x, y, OPSIZE_8);
}
#[no_mangle]
pub unsafe fn add16(x: i32, y: i32) -> i32 {
    dbg_assert!(x >= 0 && x < 0x10000);
    dbg_assert!(y >= 0 && y < 0x10000);
    return add(x, y, OPSIZE_16);
}
pub unsafe fn add32(x: i32, y: i32) -> i32 { return add(x, y, OPSIZE_32); }
pub unsafe fn sub8(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn sub16(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_16); }
pub unsafe fn sub32(x: i32, y: i32) -> i32 { return sub(x, y, OPSIZE_32); }
#[no_mangle]
pub unsafe fn adc8(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn adc16(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_16); }
#[no_mangle]
pub unsafe fn adc32(x: i32, y: i32) -> i32 { return adc(x, y, OPSIZE_32); }
#[no_mangle]
pub unsafe fn sbb8(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn sbb16(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_16); }
#[no_mangle]
pub unsafe fn sbb32(x: i32, y: i32) -> i32 { return sbb(x, y, OPSIZE_32); }
pub unsafe fn cmp8(x: i32, y: i32) {
    dbg_assert!(x >= 0 && x < 0x100);
    dbg_assert!(y >= 0 && y < 0x100);
    sub(x, y, OPSIZE_8);
}
pub unsafe fn cmp16(x: i32, y: i32) {
    dbg_assert!(x >= 0 && x < 0x10000);
    dbg_assert!(y >= 0 && y < 0x10000);
    sub(x, y, OPSIZE_16);
}
pub unsafe fn cmp32(x: i32, y: i32) { sub(x, y, OPSIZE_32); }
unsafe fn inc(dest_operand: i32, op_size: i32) -> i32 {
    *flags = *flags & !1 | getcf() as i32;
    let res = (dest_operand + 1) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL & !1;
    return res;
}
unsafe fn dec(dest_operand: i32, op_size: i32) -> i32 {
    *flags = *flags & !1 | getcf() as i32;
    let res = (dest_operand - 1) & opsize_to_mask(op_size);
    *last_op1 = dest_operand;
    *last_result = res;
    *last_op_size = op_size;
    *flags_changed = FLAGS_ALL & !1 | FLAG_SUB;
    return res;
}
#[no_mangle]
pub unsafe fn inc8(x: i32) -> i32 { return inc(x, OPSIZE_8); }
pub unsafe fn inc16(x: i32) -> i32 { return inc(x, OPSIZE_16); }
pub unsafe fn inc32(x: i32) -> i32 { return inc(x, OPSIZE_32); }
#[no_mangle]
pub unsafe fn dec8(x: i32) -> i32 { return dec(x, OPSIZE_8); }
pub unsafe fn dec16(x: i32) -> i32 { return dec(x, OPSIZE_16); }
pub unsafe fn dec32(x: i32) -> i32 { return dec(x, OPSIZE_32); }

unsafe fn neg(dest_operand: i32, op_size: i32) -> i32 { sub(0, dest_operand, op_size) }
#[no_mangle]
pub unsafe fn neg8(x: i32) -> i32 { return neg(x, OPSIZE_8); }
#[no_mangle]
pub unsafe fn neg16(x: i32) -> i32 { return neg(x, OPSIZE_16); }
pub unsafe fn neg32(x: i32) -> i32 { return neg(x, OPSIZE_32); }

#[no_mangle]
pub unsafe fn mul8(source_operand: i32) {
    let result = source_operand * read_reg8(AL);
    write_reg16(AX, result);
    *last_result = result & 255;
    *last_op_size = OPSIZE_8;
    if result < 256 {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    else {
        *flags |= 1 | FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn imul8(source_operand: i32) {
    let result = source_operand * (read_reg8(AL) << 24 >> 24);
    write_reg16(AX, result);
    *last_result = result & 255;
    *last_op_size = OPSIZE_8;
    if result > 127 || result < -128 {
        *flags |= 1 | FLAG_OVERFLOW
    }
    else {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn mul16(source_operand: u32) {
    let result = source_operand * read_reg16(AX) as u32;
    let high_result = result >> 16;
    write_reg16(AX, result as i32);
    write_reg16(DX, high_result as i32);
    *last_result = (result & 0xFFFF) as i32;
    *last_op_size = OPSIZE_16;
    if high_result == 0 {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    else {
        *flags |= 1 | FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn imul16(source_operand: i32) {
    let result = source_operand * (read_reg16(AX) << 16 >> 16);
    write_reg16(AX, result);
    write_reg16(DX, result >> 16);
    *last_result = result & 0xFFFF;
    *last_op_size = OPSIZE_16;
    if result > 32767 || result < -32768 {
        *flags |= 1 | FLAG_OVERFLOW
    }
    else {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn imul_reg16(mut operand1: i32, mut operand2: i32) -> i32 {
    operand1 = operand1 << 16 >> 16;
    operand2 = operand2 << 16 >> 16;
    let result = operand1 * operand2;
    *last_result = result & 0xFFFF;
    *last_op_size = OPSIZE_16;
    if result > 32767 || result < -32768 {
        *flags |= 1 | FLAG_OVERFLOW
    }
    else {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
    return result;
}
#[no_mangle]
pub unsafe fn mul32(source_operand: i32) {
    let dest_operand = read_reg32(EAX);
    let result = (dest_operand as u32 as u64) * (source_operand as u32 as u64);
    let result_low = result as i32;
    let result_high = (result >> 32) as i32;
    write_reg32(EAX, result_low);
    write_reg32(EDX, result_high);
    *last_result = result_low;
    *last_op_size = OPSIZE_32;
    if result_high == 0 {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    else {
        *flags |= 1 | FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
pub unsafe fn imul32(source_operand: i32) {
    let dest_operand = read_reg32(EAX);
    let result = dest_operand as i64 * source_operand as i64;
    let result_low = result as i32;
    let result_high = (result >> 32) as i32;
    write_reg32(EAX, result_low);
    write_reg32(EDX, result_high);
    *last_result = result_low;
    *last_op_size = OPSIZE_32;
    if result_high == result_low >> 31 {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    else {
        *flags |= 1 | FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
}
pub unsafe fn imul_reg32(operand1: i32, operand2: i32) -> i32 {
    let result = operand1 as i64 * operand2 as i64;
    let result_low = result as i32;
    let result_high = (result >> 32) as i32;
    *last_result = result_low;
    *last_op_size = OPSIZE_32;
    if result_high == result_low >> 31 {
        *flags &= !1 & !FLAG_OVERFLOW
    }
    else {
        *flags |= 1 | FLAG_OVERFLOW
    }
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
    return result_low;
}

#[no_mangle]
pub unsafe fn xadd8(source_operand: i32, reg: i32) -> i32 {
    let tmp = read_reg8(reg);
    write_reg8(reg, source_operand);
    return add(source_operand, tmp, OPSIZE_8);
}
#[no_mangle]
pub unsafe fn xadd16(source_operand: i32, reg: i32) -> i32 {
    let tmp = read_reg16(reg);
    write_reg16(reg, source_operand);
    return add(source_operand, tmp, OPSIZE_16);
}
pub unsafe fn xadd32(source_operand: i32, reg: i32) -> i32 {
    let tmp = read_reg32(reg);
    write_reg32(reg, source_operand);
    return add(source_operand, tmp, OPSIZE_32);
}

#[no_mangle]
pub unsafe fn cmpxchg8(data: i32, r: i32) -> i32 {
    cmp8(read_reg8(AL), data);
    if getzf() {
        read_reg8(r)
    }
    else {
        write_reg8(AL, data);
        data
    }
}
#[no_mangle]
pub unsafe fn cmpxchg16(data: i32, r: i32) -> i32 {
    cmp16(read_reg16(AX), data);
    if getzf() {
        read_reg16(r)
    }
    else {
        write_reg16(AX, data);
        data
    }
}
pub unsafe fn cmpxchg32(data: i32, r: i32) -> i32 {
    cmp32(read_reg32(EAX), data);
    if getzf() {
        read_reg32(r)
    }
    else {
        write_reg32(EAX, data);
        data
    }
}

#[no_mangle]
pub unsafe fn bcd_daa() {
    let old_al = read_reg8(AL);
    let old_cf = getcf();
    let old_af = getaf();
    *flags &= !1 & !FLAG_ADJUST;
    if old_al & 15 > 9 || old_af {
        write_reg8(AL, read_reg8(AL) + 6);
        *flags |= FLAG_ADJUST
    }
    if old_al > 153 || old_cf {
        write_reg8(AL, read_reg8(AL) + 96);
        *flags |= 1
    }
    *last_result = read_reg8(AL);
    *last_op_size = OPSIZE_8;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn bcd_das() {
    let old_al = read_reg8(AL);
    let old_cf = getcf();
    *flags &= !1;
    if old_al & 15 > 9 || getaf() {
        write_reg8(AL, read_reg8(AL) - 6);
        *flags |= FLAG_ADJUST;
        *flags = *flags & !1 | old_cf as i32 | (old_al < 6) as i32
    }
    else {
        *flags &= !FLAG_ADJUST
    }
    if old_al > 153 || old_cf {
        write_reg8(AL, read_reg8(AL) - 96);
        *flags |= 1
    }
    *last_result = read_reg8(AL);
    *last_op_size = OPSIZE_8;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW;
}
#[no_mangle]
pub unsafe fn bcd_aad(imm8: i32) {
    let result = read_reg8(AL) + read_reg8(AH) * imm8;
    *last_result = result & 255;
    write_reg16(AX, *last_result);
    *last_op_size = OPSIZE_8;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW;
    *flags &= !1 & !FLAG_ADJUST & !FLAG_OVERFLOW;
    if result > 0xFFFF {
        *flags |= 1
    };
}
#[no_mangle]
pub unsafe fn bcd_aam(imm8: i32) {
    // ascii adjust after multiplication
    if imm8 == 0 {
        trigger_de();
    }
    else {
        let temp = read_reg8(AL);
        write_reg8(AH, temp as i32 / imm8);
        write_reg8(AL, temp as i32 % imm8);
        *last_result = read_reg8(AL);
        *last_op_size = OPSIZE_8;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_ADJUST & !FLAG_OVERFLOW;
        *flags &= !1 & !FLAG_ADJUST & !FLAG_OVERFLOW
    };
}
#[no_mangle]
pub unsafe fn bcd_aaa() {
    if read_reg8(AL) & 15 > 9 || getaf() {
        write_reg16(AX, read_reg16(AX) + 6);
        write_reg8(AH, read_reg8(AH) + 1);
        *flags |= FLAG_ADJUST | 1
    }
    else {
        *flags &= !FLAG_ADJUST & !1
    }
    write_reg8(AL, read_reg8(AL) & 15);
    *flags_changed &= !FLAG_ADJUST & !1;
}
#[no_mangle]
pub unsafe fn bcd_aas() {
    if read_reg8(AL) & 15 > 9 || getaf() {
        write_reg16(AX, read_reg16(AX) - 6);
        write_reg8(AH, read_reg8(AH) - 1);
        *flags |= FLAG_ADJUST | 1
    }
    else {
        *flags &= !FLAG_ADJUST & !1
    }
    write_reg8(AL, read_reg8(AL) & 15);
    *flags_changed &= !FLAG_ADJUST & !1;
}
unsafe fn and(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let result = dest_operand & source_operand;
    *last_result = result;
    *last_op_size = op_size;
    *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    return result;
}
unsafe fn or(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let result = dest_operand | source_operand;
    *last_result = result;
    *last_op_size = op_size;
    *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    return result;
}
unsafe fn xor(dest_operand: i32, source_operand: i32, op_size: i32) -> i32 {
    let result = dest_operand ^ source_operand;
    *last_result = result;
    *last_op_size = op_size;
    *flags &= !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW & !FLAG_ADJUST;
    return result;
}
pub unsafe fn and8(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn and16(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_16); }
pub unsafe fn and32(x: i32, y: i32) -> i32 { return and(x, y, OPSIZE_32); }
pub unsafe fn test8(x: i32, y: i32) { and(x, y, OPSIZE_8); }
pub unsafe fn test16(x: i32, y: i32) { and(x, y, OPSIZE_16); }
pub unsafe fn test32(x: i32, y: i32) { and(x, y, OPSIZE_32); }
pub unsafe fn or8(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn or16(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_16); }
pub unsafe fn or32(x: i32, y: i32) -> i32 { return or(x, y, OPSIZE_32); }
pub unsafe fn xor8(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_8); }
#[no_mangle]
pub unsafe fn xor16(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_16); }
pub unsafe fn xor32(x: i32, y: i32) -> i32 { return xor(x, y, OPSIZE_32); }

#[no_mangle]
pub unsafe fn rol8(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        count &= 7;
        let result = dest_operand << count | dest_operand >> 8 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result & 1
            | (result << 11 ^ result << 4) & FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn rol16(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        count &= 15;
        let result = dest_operand << count | dest_operand >> 16 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result & 1
            | (result << 11 ^ result >> 4) & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn rol32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        let result = ((dest_operand << count) as u32 | dest_operand as u32 >> 32 - count) as i32;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result & 1
            | (result << 11 ^ result >> 20) & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn rcl8(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    count %= 9;
    if 0 == count {
        return dest_operand;
    }
    else {
        let result =
            dest_operand << count | (getcf() as i32) << count - 1 | dest_operand >> 9 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 8 & 1
            | (result << 3 ^ result << 4) & FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn rcl16(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    count %= 17;
    if 0 == count {
        return dest_operand;
    }
    else {
        let result =
            dest_operand << count | (getcf() as i32) << count - 1 | dest_operand >> 17 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 16 & 1
            | (result >> 5 ^ result >> 4) & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn rcl32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        let mut result = dest_operand << count | (getcf() as i32) << count - 1;
        if count > 1 {
            result = (result as u32 | dest_operand as u32 >> 33 - count) as i32
        }
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        let b = (dest_operand as u32 >> 32 - count & 1) as i32;
        *flags = (*flags & !1 & !FLAG_OVERFLOW | b) | (b << 11 ^ result >> 20) & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn ror8(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        count &= 7;
        let result = dest_operand >> count | dest_operand << 8 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 7 & 1
            | (result << 4 ^ result << 5) & FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn ror16(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        count &= 15;
        let result = dest_operand >> count | dest_operand << 16 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 15 & 1
            | (result >> 4 ^ result >> 3) & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn ror32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        let result = (dest_operand as u32 >> count | (dest_operand << 32 - count) as u32) as i32;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 31 & 1
            | (result >> 20 ^ result >> 19) & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn rcr8(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    count %= 9;
    if 0 == count {
        return dest_operand;
    }
    else {
        let result =
            dest_operand >> count | (getcf() as i32) << 8 - count | dest_operand << 9 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 8 & 1
            | (result << 4 ^ result << 5) & FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn rcr16(dest_operand: i32, mut count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    count %= 17;
    if 0 == count {
        return dest_operand;
    }
    else {
        let result =
            dest_operand >> count | (getcf() as i32) << 16 - count | dest_operand << 17 - count;
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 16 & 1
            | (result >> 4 ^ result >> 3) & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn rcr32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if 0 == count {
        return dest_operand;
    }
    else {
        let mut result =
            (dest_operand as u32 >> count | ((getcf() as i32) << 32 - count) as u32) as i32;
        if count > 1 {
            result |= dest_operand << 33 - count
        }
        *flags_changed &= !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | dest_operand >> count - 1 & 1
            | (result >> 20 ^ result >> 19) & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn div8(source_operand: u32) {
    if source_operand == 0 {
        trigger_de();
        return;
    }
    let target_operand = read_reg16(AX) as u32;
    let result = target_operand / source_operand;
    if result >= 0x100 {
        trigger_de();
        return;
    }
    write_reg8(AL, result as i32);
    write_reg8(AH, (target_operand % source_operand) as i32);
}

#[no_mangle]
pub unsafe fn idiv8(source_operand: i32) {
    if source_operand == 0 {
        trigger_de();
        return;
    }
    let target_operand = read_reg16(AX) << 16 >> 16;
    let result = target_operand / source_operand;
    if result >= 0x80 || result < -0x80 {
        trigger_de();
        return;
    }
    write_reg8(AL, result);
    write_reg8(AH, target_operand % source_operand);
}

#[no_mangle]
pub unsafe fn div16_without_fault(source_operand: u32) -> bool {
    let target_operand = (read_reg16(AX) | read_reg16(DX) << 16) as u32;
    let result = match target_operand.checked_div(source_operand) {
        None => return false,
        Some(r) => r,
    };
    if result >= 0x10000 {
        return false;
    }
    write_reg16(AX, result as i32);
    write_reg16(DX, (target_operand % source_operand) as i32);
    return true;
}
pub unsafe fn div16(source_operand: u32) {
    if !div16_without_fault(source_operand) {
        trigger_de()
    }
}
#[no_mangle]
pub unsafe fn idiv16_without_fault(source_operand: i32) -> bool {
    let target_operand = read_reg16(AX) | read_reg16(DX) << 16;
    let result = match target_operand.checked_div(source_operand) {
        None => return false,
        Some(r) => r,
    };
    if result >= 0x8000 || result < -0x8000 {
        return false;
    }
    write_reg16(AX, result);
    write_reg16(DX, (target_operand % source_operand) as i32);
    return true;
}
pub unsafe fn idiv16(source_operand: i32) {
    if !idiv16_without_fault(source_operand) {
        trigger_de()
    }
}

pub unsafe fn div32_without_fault(source_operand: u32) -> bool {
    let source_operand = source_operand as u64;
    let target_low = read_reg32(EAX) as u32;
    let target_high = read_reg32(EDX) as u32;
    let target_operand = (target_high as u64) << 32 | target_low as u64;
    let result = match target_operand.checked_div(source_operand) {
        None => return false,
        Some(r) => r,
    };
    if result > 0xFFFFFFFF {
        return false;
    }
    let modulo = target_operand % source_operand;
    write_reg32(EAX, result as i32);
    write_reg32(EDX, modulo as i32);
    return true;
}
pub unsafe fn div32(source_operand: u32) {
    if !div32_without_fault(source_operand) {
        trigger_de()
    }
}
#[no_mangle]
pub unsafe fn idiv32_without_fault(source_operand: i32) -> bool {
    let source_operand = source_operand as i64;
    let target_low = read_reg32(EAX) as u32;
    let target_high = read_reg32(EDX) as u32;
    let target_operand = (target_high as i64) << 32 | target_low as i64;
    let result = match target_operand.checked_div(source_operand) {
        None => return false,
        Some(r) => r,
    };
    if result < -0x80000000 || result > 0x7FFFFFFF {
        return false;
    }
    let modulo = target_operand % source_operand;
    write_reg32(EAX, result as i32);
    write_reg32(EDX, modulo as i32);
    return true;
}
pub unsafe fn idiv32(source_operand: i32) {
    if !idiv32_without_fault(source_operand) {
        trigger_de()
    }
}

#[no_mangle]
pub unsafe fn shl8(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand << count;
        *last_result = result;
        *last_op_size = OPSIZE_8;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 8 & 1
            | (result << 3 ^ result << 4) & FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn shl16(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand << count;
        *last_result = result;
        *last_op_size = OPSIZE_16;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | result >> 16 & 1
            | (result >> 5 ^ result >> 4) & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn shl32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand << count;
        *last_result = result;
        *last_op_size = OPSIZE_32;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        let b = dest_operand >> 32 - count & 1;
        *flags = *flags & !1 & !FLAG_OVERFLOW | b | (b ^ result >> 31) << 11 & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn shr8(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand >> count;
        *last_result = result;
        *last_op_size = OPSIZE_8;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | dest_operand >> count - 1 & 1
            | (dest_operand >> 7 & 1) << 11 & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn shr16(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand >> count;
        *last_result = result;
        *last_op_size = OPSIZE_16;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !1 & !FLAG_OVERFLOW
            | dest_operand >> count - 1 & 1
            | dest_operand >> 4 & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn shr32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = (dest_operand as u32 >> count) as i32;
        *last_result = result;
        *last_op_size = OPSIZE_32;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = (*flags & !1 & !FLAG_OVERFLOW)
            | (dest_operand as u32 >> count - 1 & 1) as i32
            | (dest_operand >> 20 & FLAG_OVERFLOW);
        return result;
    };
}
#[no_mangle]
pub unsafe fn sar8(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result;
        if count < 8 {
            result = dest_operand << 24 >> count + 24;
            // of is zero
            *flags = *flags & !1 & !FLAG_OVERFLOW | dest_operand >> count - 1 & 1
        }
        else {
            result = dest_operand << 24 >> 31;
            *flags = *flags & !1 & !FLAG_OVERFLOW | result & 1
        }
        *last_result = result;
        *last_op_size = OPSIZE_8;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        return result & 0xFF;
    };
}
#[no_mangle]
pub unsafe fn sar16(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result;
        if count < 16 {
            result = dest_operand << 16 >> count + 16;
            *flags = *flags & !1 & !FLAG_OVERFLOW | dest_operand >> count - 1 & 1
        }
        else {
            result = dest_operand << 16 >> 31;
            *flags = *flags & !1 & !FLAG_OVERFLOW | result & 1
        }
        *last_result = result;
        *last_op_size = OPSIZE_16;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn sar32(dest_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = dest_operand >> count;
        *last_result = result;
        *last_op_size = OPSIZE_32;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = (*flags & !1 & !FLAG_OVERFLOW) | (dest_operand as u32 >> count - 1 & 1) as i32;
        return result;
    };
}

#[no_mangle]
pub unsafe fn shrd16(dest_operand: i32, source_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result;
        if count <= 16 {
            result = dest_operand >> count | source_operand << 16 - count;
            *flags = *flags & !1 | dest_operand >> count - 1 & 1
        }
        else {
            result = dest_operand << 32 - count | source_operand >> count - 16;
            *flags = *flags & !1 | source_operand >> count - 17 & 1
        }
        *last_result = result;
        *last_op_size = OPSIZE_16;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !FLAG_OVERFLOW | (result ^ dest_operand) >> 4 & FLAG_OVERFLOW;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn shrd32(dest_operand: i32, source_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = (dest_operand as u32 >> count | (source_operand << 32 - count) as u32) as i32;
        *last_result = result;
        *last_op_size = OPSIZE_32;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = ((*flags & !1 & !FLAG_OVERFLOW) | (dest_operand as u32 >> count - 1 & 1) as i32)
            | (result ^ dest_operand) >> 20 & FLAG_OVERFLOW;
        return result;
    };
}
#[no_mangle]
pub unsafe fn shld16(dest_operand: i32, source_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result;
        if count <= 16 {
            result = ((dest_operand << count) as u32 | source_operand as u32 >> 16 - count) as i32;
            *flags = (*flags & !1) | (dest_operand as u32 >> 16 - count & 1) as i32;
        }
        else {
            result = dest_operand >> 32 - count | source_operand << count - 16;
            *flags = (*flags & !1) | (source_operand as u32 >> 32 - count & 1) as i32;
        }
        *last_result = result;
        *last_op_size = OPSIZE_16;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = *flags & !FLAG_OVERFLOW | (*flags & 1 ^ result >> 15 & 1) << 11;
        return result & 0xFFFF;
    };
}
#[no_mangle]
pub unsafe fn shld32(dest_operand: i32, source_operand: i32, count: i32) -> i32 {
    dbg_assert!(count >= 0 && count < 32);
    if count == 0 {
        return dest_operand;
    }
    else {
        let result = ((dest_operand << count) as u32 | source_operand as u32 >> 32 - count) as i32;
        *last_result = result;
        *last_op_size = OPSIZE_32;
        *flags_changed = FLAGS_ALL & !1 & !FLAG_OVERFLOW;
        *flags = (*flags & !1) | (dest_operand as u32 >> 32 - count & 1) as i32;
        if count == 1 {
            *flags = *flags & !FLAG_OVERFLOW | (*flags & 1 ^ result >> 31 & 1) << 11
        }
        else {
            *flags &= !FLAG_OVERFLOW
        }
        return result;
    };
}

pub unsafe fn bt_reg(bit_base: i32, bit_offset: i32) {
    *flags = *flags & !1 | bit_base >> bit_offset & 1;
    *flags_changed &= !1;
}
pub unsafe fn btc_reg(bit_base: i32, bit_offset: i32) -> i32 {
    *flags = *flags & !1 | bit_base >> bit_offset & 1;
    *flags_changed &= !1;
    return bit_base ^ 1 << bit_offset;
}
pub unsafe fn bts_reg(bit_base: i32, bit_offset: i32) -> i32 {
    *flags = *flags & !1 | bit_base >> bit_offset & 1;
    *flags_changed &= !1;
    return bit_base | 1 << bit_offset;
}
pub unsafe fn btr_reg(bit_base: i32, bit_offset: i32) -> i32 {
    *flags = *flags & !1 | bit_base >> bit_offset & 1;
    *flags_changed &= !1;
    return bit_base & !(1 << bit_offset);
}

pub unsafe fn bt_mem(virt_addr: i32, mut bit_offset: i32) {
    let bit_base = return_on_pagefault!(safe_read8(virt_addr + (bit_offset >> 3)));
    bit_offset &= 7;
    *flags = *flags & !1 | bit_base >> bit_offset & 1;
    *flags_changed &= !1;
}
// The byte holding the bit is read and written back as one locked
// read-modify-write (LOCK BTS is a common spinlock acquire)
pub unsafe fn btc_mem(virt_addr: i32, bit_offset: i32) {
    bit_rmw(virt_addr, bit_offset, &|bit_base, bit| bit_base ^ bit)
}
pub unsafe fn btr_mem(virt_addr: i32, bit_offset: i32) {
    bit_rmw(virt_addr, bit_offset, &|bit_base, bit| bit_base & !bit)
}
pub unsafe fn bts_mem(virt_addr: i32, bit_offset: i32) {
    bit_rmw(virt_addr, bit_offset, &|bit_base, bit| bit_base | bit)
}
unsafe fn bit_rmw(virt_addr: i32, bit_offset: i32, operation: &dyn Fn(i32, i32) -> i32) {
    let shift = bit_offset & 7;
    safe_read_write8(virt_addr + (bit_offset >> 3), &|bit_base| {
        *flags = *flags & !1 | bit_base >> shift & 1;
        *flags_changed &= !1;
        operation(bit_base, 1 << shift)
    });
}

#[no_mangle]
pub unsafe fn bsf16(old: i32, bit_base: i32) -> i32 {
    *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY;
    *flags &= !FLAG_CARRY;
    *last_op_size = OPSIZE_16;
    if bit_base == 0 {
        *flags |= FLAG_ZERO;
        *last_result = bit_base;
        // not defined in the docs, but value doesn't change on my intel machine
        return old;
    }
    else {
        *flags &= !FLAG_ZERO;
        *last_result = int_log2(-bit_base & bit_base);
        return *last_result;
    };
}
#[no_mangle]
pub unsafe fn bsf32(old: i32, bit_base: i32) -> i32 {
    *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY;
    *flags &= !FLAG_CARRY;
    *last_op_size = OPSIZE_32;
    if bit_base == 0 {
        *flags |= FLAG_ZERO;
        *last_result = bit_base;
        return old;
    }
    else {
        *flags &= !FLAG_ZERO;
        *last_result = int_log2(-bit_base & bit_base);
        return *last_result;
    };
}
#[no_mangle]
pub unsafe fn bsr16(old: i32, bit_base: i32) -> i32 {
    *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY;
    *flags &= !FLAG_CARRY;
    *last_op_size = OPSIZE_16;
    if bit_base == 0 {
        *flags |= FLAG_ZERO;
        *last_result = bit_base;
        return old;
    }
    else {
        *flags &= !FLAG_ZERO;
        *last_result = int_log2(bit_base);
        return *last_result;
    };
}
#[no_mangle]
pub unsafe fn bsr32(old: i32, bit_base: i32) -> i32 {
    *flags_changed = FLAGS_ALL & !FLAG_ZERO & !FLAG_CARRY;
    *flags &= !FLAG_CARRY;
    *last_op_size = OPSIZE_32;
    if bit_base == 0 {
        *flags |= FLAG_ZERO;
        *last_result = bit_base;
        return old;
    }
    else {
        *flags &= !FLAG_ZERO;
        *last_result = int_log2(bit_base);
        return *last_result;
    };
}
#[no_mangle]
pub unsafe fn popcnt(v: i32) -> i32 {
    *flags_changed = 0;
    *flags &= !FLAGS_ALL;
    if 0 != v {
        return v.count_ones() as i32;
    }
    else {
        *flags |= FLAG_ZERO;
        return 0;
    };
}

pub unsafe fn saturate_sw_to_ub(v: u16) -> u8 {
    let mut ret = v;
    if ret >= 32768 {
        ret = 0
    }
    else if ret > 255 {
        ret = 255
    }
    return ret as u8;
}
pub unsafe fn saturate_sw_to_sb(v: i32) -> u8 {
    dbg_assert!(v as u32 & 0xFFFF_0000 == 0);
    let mut ret = v;
    if ret > 65408 {
        ret = ret & 255
    }
    else if ret > 32767 {
        ret = 128
    }
    else if ret > 127 {
        ret = 127
    }
    dbg_assert!(ret as u32 & 0xFFFF_FF00 == 0);
    return ret as u8;
}
pub unsafe fn saturate_sd_to_sw(v: u32) -> u16 {
    let mut ret = v;
    if ret > 4294934528 {
        ret = ret & 0xFFFF
    }
    else if ret > 0x7FFFFFFF {
        ret = 32768
    }
    else if ret > 32767 {
        ret = 32767
    }
    dbg_assert!(ret & 0xFFFF_0000 == 0);
    return ret as u16;
}
pub unsafe fn saturate_sd_to_sb(v: u32) -> i8 {
    let mut ret = v;
    if ret > 0xFFFFFF80 {
        ret = ret & 255
    }
    else if ret > 0x7FFFFFFF {
        ret = 128
    }
    else if ret > 127 {
        ret = 127
    }
    dbg_assert!(ret & 0xFFFF_FF00 == 0);
    return ret as i8;
}
pub unsafe fn saturate_sd_to_ub(v: i32) -> i32 {
    let mut ret = v;
    if ret < 0 {
        ret = 0
    }
    dbg_assert!(ret as u32 & 0xFFFF_FF00 == 0);
    return ret;
}
pub unsafe fn saturate_ud_to_ub(v: u32) -> u8 {
    let mut ret = v;
    if ret > 255 {
        ret = 255
    }
    dbg_assert!(ret & 0xFFFF_FF00 == 0);
    return ret as u8;
}
pub unsafe fn saturate_uw(v: u32) -> u16 {
    let mut ret = v;
    if ret > 0x7FFFFFFF {
        ret = 0
    }
    else if ret > 0xFFFF {
        ret = 0xFFFF
    }
    dbg_assert!(ret & 0xFFFF_0000 == 0);
    return ret as u16;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/rust/cpu/avx.rs                                                                      0000644 0000000 0000000 00000166556 00000000000 013426  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! AVX: the VEX-encoded SIMD instructions (docs/simd-xsave-plan.md, P5-P6).
//! One executor serves the 32-bit interpreter (crate::cpu::vex) and the x64
//! engine (crate::x64::vector); the IR region tiers' helper too until
//! docs/jit-unification-plan.md M11 deleted them.
//! An engine decodes the instruction (decode_rules::vex_row: the row exists,
//! has its semantics and accepts the VEX fields), calls `check` once all of
//! its bytes are fetched and before its operand's segment is checked, then
//! `execute`, which reaches memory, the general-purpose registers, FLAGS and
//! exception delivery through the engine's `Machine`. The XMM registers, the
//! upper halves of the YMM registers, MXCSR, CR0, CR4 and XCR0 are the same
//! state in every engine.
//!
//! The semantics are the legacy forms' (crate::cpu::simd_ops, simd_int, simd_fp)
//! with VEX's operands: VEX.vvvv is the first source, a VEX.128 form zeroes
//! bits 255:128 of its destination register (VMOVSS/VMOVSD between registers
//! too), and every input is read before the destination is written, so any of
//! the operands may be the same register. A VEX.256 form (execute256) runs
//! them on each 128-bit half where it works lane by lane.
use crate::cpu::cpu::{self, reg128, CR0_TS, CR4_OSXSAVE, MXCSR_MASK};
use crate::cpu::global_pointers as gp;
use crate::cpu::simd_ops::{PackedOp, ShuffleOp, TransferOp};
use crate::cpu::{simd_fp, simd_int};

/// A decoded VEX instruction
#[derive(Clone, Copy, Debug)]
pub struct Instruction {
    /// The row's catalogue key 0xC4_MM_PP_OO (decode_rules::Vex::key)
    pub key: u32,
    /// ModRM.reg (with VEX.R): a register, or a group's opcode extension
    pub reg: u8,
    /// VEX.vvvv: a register, or 0 for a form without that operand
    pub vvvv: u8,
    /// ModRM.rm (with VEX.B) of a register form; None: the memory operand
    pub rm: Option<u8>,
    /// A VEX.256 form: VEX.L1 of a row that has one (a VEX.LIG form's VEX.L
    /// is not this)
    pub l: bool,
    pub w: bool,
    pub imm8: u8,
    /// 64-bit mode: XMM8-XMM15, and the 64-bit general-purpose operands of
    /// the VEX.W1 forms
    pub long: bool,
    /// A gather's VSIB memory operand (whose address is then that of its
    /// base and displacement)
    pub vsib: Option<Vsib>,
}
/// A VSIB memory operand's indices: their vector register and the scale
/// (log2)
#[derive(Clone, Copy, Debug)]
pub struct Vsib {
    pub index: u8,
    pub scale: u8,
}

/// An exception the executor raises
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Exception {
    /// #UD
    InvalidOpcode,
    /// #NM
    DeviceNotAvailable,
    /// #GP(0)
    GeneralProtection,
    /// An unmasked SIMD floating-point exception: #XM, or #UD without
    /// CR4.OSXMMEXCPT
    SimdFloatingPoint,
}

/// An engine's side of an instruction
pub trait Machine {
    /// An exception that ends the instruction (the interpreter delivers it
    /// when raised)
    type Fault;
    unsafe fn raise(&mut self, e: Exception) -> Self::Fault;
    /// `bytes` (1, 2, 4, 8 or 16) of the memory operand, zero-extended;
    /// `aligned`: #GP(0) unless the operand is aligned to 16 bytes
    unsafe fn read(&mut self, bytes: u8, aligned: bool) -> Result<u128, Self::Fault>;
    /// The low `bytes` of `value` to the memory operand
    unsafe fn write(&mut self, bytes: u8, value: u128, aligned: bool) -> Result<(), Self::Fault>;
    /// A VEX.256 form's 32-byte memory operand: its low and high halves;
    /// `aligned`: #GP(0) unless the operand is aligned to 32 bytes
    unsafe fn read256(&mut self, aligned: bool) -> Result<(u128, u128), Self::Fault>;
    /// ... `value` to it, nothing unless all of it can be written
    unsafe fn write256(&mut self, value: (u128, u128), aligned: bool) -> Result<(), Self::Fault>;
    /// VMASKMOVDQU: the bytes of `value` whose bit in `mask` is set, to
    /// (E/R)DI in DS or the segment prefix's
    unsafe fn write_masked(&mut self, value: u128, mask: u16) -> Result<(), Self::Fault>;
    /// VMASKMOVPS/PD: the `count` lanes of `size` bytes (4, 8) of the memory
    /// operand whose bit in `selected` is set, the others zero, as a value's
    /// low and high halves (bytes 16 to 31: a VEX.256 form's); only they are
    /// accessed (no fault for another)
    unsafe fn read_lanes(
        &mut self,
        size: u8,
        count: u8,
        selected: u8,
    ) -> Result<(u128, u128), Self::Fault>;
    /// VMASKMOVPS/PD: the selected lanes of `value` to the memory operand,
    /// none unless every one can be written
    unsafe fn write_lanes(
        &mut self,
        size: u8,
        count: u8,
        value: (u128, u128),
        selected: u8,
    ) -> Result<(), Self::Fault>;
    /// A gather's element: `bytes` (4, 8) at the memory operand's address
    /// plus `offset` (the element's sign-extended, scaled index), with the
    /// address size's wraparound
    unsafe fn gather(&mut self, offset: u64, bytes: u8) -> Result<u64, Self::Fault>;
    unsafe fn gpr(&mut self, r: u8) -> u64;
    /// The low 32 bits of `value` (zero-extended in 64-bit mode), or all 64
    /// with `wide`
    unsafe fn set_gpr(&mut self, r: u8, value: u64, wide: bool);
    /// OF, SF, ZF, AF, PF and CF to those of `flags`
    unsafe fn set_flags(&mut self, flags: u32);
}

/// The exceptions of every AVX instruction before its operands (SDM vol. 2,
/// 2.8, the exception types of VEX-encoded forms): #UD unless the operating
/// system enabled the AVX state (CR4.OSXSAVE and XCR0[2:1] = 11b), then #NM
/// with CR0.TS. Unlike legacy SSE, CR0.EM and CR4.OSFXSR do not matter.
pub unsafe fn check<M: Machine>(m: &mut M) -> Result<(), M::Fault> {
    if *gp::cr.add(4) & CR4_OSXSAVE == 0 || *gp::xcr0 & 6 != 6 {
        return Err(m.raise(Exception::InvalidOpcode));
    }
    if *gp::cr & CR0_TS != 0 {
        return Err(m.raise(Exception::DeviceNotAvailable));
    }
    Ok(())
}

/// The catalogue key of the legacy form whose semantics a VEX form has: 66
/// 0F 58 for VEX.66.0F 58, 66 0F 38 00 for VEX.66.0F38 00
pub fn legacy(key: u32) -> u32 {
    let prefix = [0, 0x66, 0xF3, 0xF2][(key >> 8 & 3) as usize];
    let op = key & 0xFF;
    match key >> 16 & 0xFF {
        1 => prefix << 16 | 0x0F00 | op,
        2 => prefix << 24 | 0x0F3800 | op,
        _ => prefix << 24 | 0x0F3A00 | op,
    }
}

unsafe fn xmm(r: u8) -> u128 { cpu::read_xmm128s(r as i32).bits() }
/// A VEX.128 destination register: bits 255:128 zeroed
unsafe fn set_xmm(r: u8, value: u128) {
    cpu::write_xmm_reg128(r as i32, reg128::of_bits(value));
    *gp::ymm_hi.add(r as usize) = reg128::of_bits(0);
}
/// YMM register `r`: bits 127:0 and 255:128
unsafe fn ymm(r: u8) -> (u128, u128) { (xmm(r), (*gp::ymm_hi.add(r as usize)).bits()) }
/// A VEX.256 destination register
unsafe fn set_ymm(r: u8, (low, high): (u128, u128)) {
    cpu::write_xmm_reg128(r as i32, reg128::of_bits(low));
    *gp::ymm_hi.add(r as usize) = reg128::of_bits(high);
}
/// A VEX.256 form's r/m operand: a register, or 32 bytes of memory
unsafe fn source256<M: Machine>(
    m: &mut M,
    i: &Instruction,
    aligned: bool,
) -> Result<(u128, u128), M::Fault> {
    match i.rm {
        Some(r) => Ok(ymm(r)),
        None => m.read256(aligned),
    }
}
/// The lane at byte `offset` of `size` bytes of a 256-bit value
pub fn lane256(v: (u128, u128), offset: u32, size: u32) -> u64 {
    let half = if offset < 16 { v.0 } else { v.1 };
    (half >> (offset % 16 * 8)) as u64 & (u64::MAX >> (64 - size * 8))
}
/// The r/m operand: a register, or `bytes` of memory
unsafe fn source<M: Machine>(
    m: &mut M,
    i: &Instruction,
    bytes: u8,
    aligned: bool,
) -> Result<u128, M::Fault> {
    match i.rm {
        Some(r) => Ok(xmm(r)),
        None => m.read(bytes, aligned),
    }
}
/// The shifts by imm8 (`op` 71, 72 or 73, `group` its ModRM.reg) of 128
/// bits: PSRLW/PSRAW/PSLLW, PSRLD/PSRAD/PSLLD, PSRLQ/PSRLDQ/PSLLQ/PSLLDQ
fn shift_imm(op: u8, group: u8, v: u128, count: u32) -> u128 {
    match (op, group) {
        (0x73, 3) => {
            if count < 16 {
                v >> (8 * count)
            }
            else {
                0
            }
        },
        (0x73, 7) => {
            if count < 16 {
                v << (8 * count)
            }
            else {
                0
            }
        },
        (_, group) => {
            let id = [0xD1, 0xE1, 0xF1][(group / 2 - 1) as usize] + (op as u32 - 0x71);
            packed(PackedOp::from_id(id).unwrap(), v, count as u128)
        },
    }
}
/// The element size of VBROADCASTSS/SD (18, 19), VPBROADCASTD/Q (58, 59) and
/// VPBROADCASTB/W (78, 79)
fn broadcast_size(op: u8) -> u32 {
    match op {
        0x78 => 1,
        0x79 => 2,
        0x18 | 0x58 => 4,
        _ => 8,
    }
}
/// `v` (`size` bytes) in each lane of 128 bits
fn splat(v: u128, size: u32) -> u128 {
    let mut r = v;
    let mut bits = size * 8;
    while bits < 128 {
        r |= r << bits;
        bits *= 2;
    }
    r
}
/// A broadcast's element: `size` bytes of memory, or the low lane of the r/m
/// register
unsafe fn element<M: Machine>(m: &mut M, i: &Instruction, size: u32) -> Result<u128, M::Fault> {
    Ok(match i.rm {
        Some(r) => xmm(r) & u128::MAX >> (128 - 8 * size),
        None => m.read(size as u8, false)?,
    })
}
/// VPBLENDD of 128 bits: dword n from `b` where bit n of `select` is set,
/// else from `a`
fn blend_dwords(a: u128, b: u128, select: u8) -> u128 {
    let mut mask = 0;
    for n in 0..4 {
        if select >> n & 1 != 0 {
            mask |= 0xFFFF_FFFF << (32 * n);
        }
    }
    a & !mask | b & mask
}
/// VPSRLVD/Q (45), VPSRAVD (46), VPSLLVD/Q (47) of 128 bits: each element of
/// `a` (`qword`: quadwords, else dwords) shifted by the unsigned count in the
/// same element of `b`; from the element's width on, the logical shifts give
/// 0, VPSRAVD the sign
fn shift_variable(op: u8, qword: bool, a: u128, b: u128) -> u128 {
    let bits = if qword { 64 } else { 32 };
    let mask = u128::MAX >> (128 - bits);
    let mut r = 0;
    for at in (0..128).step_by(bits as usize) {
        let (x, count) = (a >> at & mask, b >> at & mask);
        let v = match op {
            0x45 if count < bits as u128 => x >> count,
            0x47 if count < bits as u128 => x << count & mask,
            0x46 => (x as u32 as i32 >> count.min(31)) as u32 as u128,
            _ => 0,
        };
        r |= v << at;
    }
    r
}
/// The lanes of `v` (`size` 4 or 8 bytes) at the indices `index(n)` of the
/// result's lane n, over 256 bits (VPERMD/PS/Q/PD)
fn permute256(v: (u128, u128), size: u32, index: impl Fn(u32) -> u32) -> (u128, u128) {
    let mut r = [0; 2];
    for n in 0..32 / size {
        let at = n * size * 8;
        r[(at / 128) as usize] |= (lane256(v, size * index(n), size) as u128) << (at % 128);
    }
    (r[0], r[1])
}
/// VPGATHERDD/DQ/QD/QQ, VGATHERDPS/DPD/QPS/QPD (90 to 93; VEX.W1: quadword
/// data; 91 and 93: quadword indices). As the SDM's operation: the mask
/// (VEX.vvvv) first, each element all ones or zero by its sign and zero
/// beyond the elements; then each element in turn, loaded into the
/// destination if selected, its mask cleared (a fault leaves the elements
/// before it done, so the instruction restarts with the rest); last, the
/// destination zero beyond the elements
unsafe fn gather<M: Machine>(m: &mut M, i: &Instruction) -> Result<(), M::Fault> {
    let vsib = i.vsib.unwrap();
    let data = if i.w { 8 } else { 4 };
    let index_size = if i.key & 1 != 0 { 8 } else { 4 };
    let count = if i.l { 32 } else { 16 } / data.max(index_size);
    let bytes = |v: (u128, u128)| {
        let mut b = [0u8; 32];
        b[..16].copy_from_slice(&v.0.to_le_bytes());
        b[16..].copy_from_slice(&v.1.to_le_bytes());
        b
    };
    let halves = |b: &[u8; 32]| {
        (
            u128::from_le_bytes(b[..16].try_into().unwrap()),
            u128::from_le_bytes(b[16..].try_into().unwrap()),
        )
    };
    let (mut mask, mut destination, index) = (
        bytes(ymm(i.vvvv)),
        bytes(ymm(i.reg)),
        bytes(ymm(vsib.index)),
    );
    for n in 0..count {
        let sign = mask[(n + 1) * data - 1] >> 7;
        mask[n * data..(n + 1) * data].fill(if sign != 0 { 0xFF } else { 0 });
    }
    mask[count * data..].fill(0);
    set_ymm(i.vvvv, halves(&mask));
    for n in 0..count {
        if mask[n * data] != 0 {
            let mut raw = [0u8; 8];
            raw[..index_size].copy_from_slice(&index[n * index_size..(n + 1) * index_size]);
            let raw = u64::from_le_bytes(raw);
            let element = if index_size == 4 { raw as u32 as i32 as i64 as u64 } else { raw };
            let value = m.gather(element.wrapping_shl(vsib.scale as u32), data as u8)?;
            destination[n * data..(n + 1) * data].copy_from_slice(&value.to_le_bytes()[..data]);
            set_ymm(i.reg, halves(&destination));
        }
        mask[n * data..(n + 1) * data].fill(0);
        set_ymm(i.vvvv, halves(&mask));
    }
    destination[count * data..].fill(0);
    set_ymm(i.reg, halves(&destination));
    Ok(())
}
fn packed(op: PackedOp, a: u128, b: u128) -> u128 {
    u128::from_le_bytes(op.apply(a.to_le_bytes(), b.to_le_bytes()))
}
/// A function of byte vectors on 128-bit values
fn bytes(f: impl FnOnce([u8; 16]) -> [u8; 16], v: u128) -> u128 {
    u128::from_le_bytes(f(v.to_le_bytes()))
}
/// The low `bytes` bytes
fn low(bytes: u32) -> u128 { u128::MAX >> (128 - 8 * bytes) }
/// VPERMILPS, VPERMILPD: the lanes of `v` (`size` 4 or 8 bytes) at the
/// indices of `index`
fn permute(v: u128, size: u32, index: impl Fn(u32) -> u32) -> u128 {
    (0..16 / size).fold(0, |r, n| {
        r | (v >> (index(n) * size * 8) & low(size)) << (n * size * 8)
    })
}
/// The sign bits of `v`'s lanes of `lane` bytes
fn sign_mask(v: u128, lane: u32) -> u64 {
    (0..16 / lane).fold(0, |mask, n| {
        mask | ((v >> (n * lane * 8 + lane * 8 - 1)) as u64 & 1) << n
    })
}
/// ... of a 256-bit value's lanes
fn sign_mask256(v: (u128, u128), lane: u32) -> u64 {
    sign_mask(v.0, lane) | sign_mask(v.1, lane) << (16 / lane)
}

/// Execute `i` (after `check`)
pub unsafe fn execute<M: Machine>(m: &mut M, i: &Instruction) -> Result<(), M::Fault> {
    if i.l {
        return execute256(m, i);
    }
    const LOW: u128 = u64::MAX as u128;
    let (map, pp, op) = (i.key >> 16 & 0xFF, i.key >> 8 & 3, i.key as u8);
    // (the general-purpose operands of VEX.W1 forms, in 64-bit mode)
    let wide = i.long && i.w;
    // VMOVSS and VMOVSD: the bytes of the scalar and its lanes' mask
    let scalar = if pp == 2 { (4, 0xFFFF_FFFF) } else { (8, LOW) };
    match (map, pp, op) {
        // VMOVUPS, VMOVUPD, VMOVAPS, VMOVAPD, VMOVDQA, VMOVDQU, VLDDQU and
        // VMOVNTDQA, the aligned ones #GP(0) otherwise
        (1, 0 | 1, 0x10 | 0x28) | (1, 1 | 2, 0x6F) | (1, 3, 0xF0) | (2, 1, 0x2A) => {
            let aligned = matches!(op, 0x28 | 0x2A) || op == 0x6F && pp == 1;
            let v = source(m, i, 16, aligned)?;
            set_xmm(i.reg, v);
        },
        // their stores, and VMOVNTPS, VMOVNTPD, VMOVNTDQ
        (1, 0 | 1, 0x11 | 0x29 | 0x2B) | (1, 1 | 2, 0x7F) | (1, 1, 0xE7) => {
            let aligned = matches!(op, 0x29 | 0x2B | 0xE7) || op == 0x7F && pp == 1;
            let v = xmm(i.reg);
            match i.rm {
                Some(r) => set_xmm(r, v),
                None => m.write(16, v, aligned)?,
            }
        },
        // VMOVSS, VMOVSD: from memory zero-extended; between registers the
        // other lanes from the first source
        (1, 2 | 3, 0x10) => {
            let v = match i.rm {
                Some(r) => xmm(i.vvvv) & !scalar.1 | xmm(r) & scalar.1,
                None => m.read(scalar.0, false)?,
            };
            set_xmm(i.reg, v);
        },
        (1, 2 | 3, 0x11) => match i.rm {
            Some(r) => set_xmm(r, xmm(i.vvvv) & !scalar.1 | xmm(i.reg) & scalar.1),
            None => m.write(scalar.0, xmm(i.reg) & scalar.1, false)?,
        },
        // VMOVHLPS, VMOVLPS, VMOVLPD: the low quadword from the source's
        // high one or memory, the high one from the first source
        (1, 0 | 1, 0x12) => {
            let low = match i.rm {
                Some(r) => xmm(r) >> 64,
                None => m.read(8, false)?,
            };
            set_xmm(i.reg, xmm(i.vvvv) & !LOW | low);
        },
        // VMOVLHPS, VMOVHPS, VMOVHPD: the high quadword from the source's
        // low one or memory, the low one from the first source
        (1, 0 | 1, 0x16) => {
            let high = match i.rm {
                Some(r) => xmm(r) & LOW,
                None => m.read(8, false)?,
            };
            set_xmm(i.reg, xmm(i.vvvv) & LOW | high << 64);
        },
        // VMOVLPS, VMOVLPD, VMOVHPS, VMOVHPD m64, xmm
        (1, 0 | 1, 0x13) => m.write(8, xmm(i.reg) & LOW, false)?,
        (1, 0 | 1, 0x17) => m.write(8, xmm(i.reg) >> 64, false)?,
        // VMOVSLDUP, VMOVSHDUP, VMOVDDUP (from 64 bits of memory)
        (1, 2, 0x12 | 0x16) | (1, 3, 0x12) => {
            let v = source(m, i, if pp == 3 { 8 } else { 16 }, false)?;
            let t = TransferOp::from_encoding(legacy(i.key)).unwrap();
            set_xmm(
                i.reg,
                u128::from_le_bytes(t.apply([0; 16], v.to_le_bytes())),
            );
        },
        // VUNPCKLPS, VUNPCKLPD, VUNPCKHPS, VUNPCKHPD; VANDPS, VANDPD,
        // VANDNPS, VANDNPD, VORPS, VORPD, VXORPS, VXORPD; the packed integer
        // operations of 66 0F: unpacks, packs, compares, shifts by xmm/m128
        // (the count in its low quadword), arithmetic and logic
        (1, 0 | 1, 0x14 | 0x15 | 0x54..=0x57)
        | (
            1,
            1,
            0x60..=0x6D
            | 0x74..=0x76
            | 0xD1..=0xD5
            | 0xD8..=0xDF
            | 0xE0..=0xE5
            | 0xE8..=0xEF
            | 0xF1..=0xF6
            | 0xF8..=0xFE,
        ) => {
            let b = source(m, i, 16, false)?;
            let p = PackedOp::from_encoding(legacy(i.key)).unwrap();
            set_xmm(i.reg, packed(p, xmm(i.vvvv), b));
        },
        // VPSRLW/VPSRAW/VPSLLW, VPSRLD/VPSRAD/VPSLLD, VPSRLQ/VPSRLDQ/VPSLLQ/
        // VPSLLDQ by imm8: VEX.vvvv is the destination, the r/m register the
        // source
        (1, 1, 0x71..=0x73) => {
            let v = xmm(i.rm.unwrap());
            set_xmm(i.vvvv, shift_imm(op, i.reg & 7, v, i.imm8 as u32));
        },
        // VSQRT, VADD, VMUL, VSUB, VMIN, VDIV, VMAX PS/PD/SS/SD, VHADDPS/PD,
        // VHSUBPS/PD, VADDSUBPS/PD; VCMP* with 32 predicates: a scalar
        // form's other lanes from the first source (VSQRTPS/PD: one source)
        (1, 0..=3, 0x51 | 0x58 | 0x59 | 0x5C..=0x5F | 0xC2) | (1, 1 | 3, 0x7C | 0x7D | 0xD0) => {
            let scalar = pp >= 2 && !matches!(op, 0x7C | 0x7D | 0xD0);
            let bytes = match (scalar, pp) {
                (false, _) => 16,
                (true, 2) => 4,
                _ => 8,
            };
            let b = source(m, i, bytes, false)?;
            let r = if op == 0xC2 {
                simd_fp::compare(legacy(i.key), xmm(i.vvvv), b, i.imm8)
            }
            else {
                simd_fp::arithmetic(legacy(i.key), xmm(i.vvvv), b, 0)
            };
            let r = r.map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VRSQRTPS/SS, VRCPPS/SS: no exceptions
        (1, 0 | 2, 0x52 | 0x53) => {
            let b = source(m, i, if pp == 2 { 4 } else { 16 }, false)?;
            set_xmm(i.reg, simd_fp::reciprocal(legacy(i.key), xmm(i.vvvv), b));
        },
        // VUCOMISS/SD, VCOMISS/SD: ZF, PF and CF
        (1, 0 | 1, 0x2E | 0x2F) => {
            let b = source(m, i, if pp == 0 { 4 } else { 8 }, false)?;
            let flags = simd_fp::compare_flags(legacy(i.key), xmm(i.reg), b)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            m.set_flags(flags);
        },
        // VCVTSI2SS/SD: from a general-purpose register or memory (64 bits
        // with VEX.W1 in 64-bit mode) into the first source's low lane
        (1, 2 | 3, 0x2A) => {
            let value = match i.rm {
                Some(r) => m.gpr(r),
                None => m.read(if wide { 8 } else { 4 }, false)? as u64,
            };
            let value = if wide { value } else { value & 0xFFFF_FFFF };
            let r = simd_fp::convert(legacy(i.key), wide, xmm(i.vvvv), value as u128)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VCVTSS2SI, VCVTTSS2SI, VCVTSD2SI, VCVTTSD2SI: to a general-purpose
        // register (64-bit with VEX.W1 in 64-bit mode)
        (1, 2 | 3, 0x2C | 0x2D) => {
            let b = source(m, i, if pp == 2 { 4 } else { 8 }, false)?;
            let r = simd_fp::convert(legacy(i.key), wide, 0, b)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            m.set_gpr(i.reg, r as u64, wide);
        },
        // VCVTPS2PD (m64), VCVTPD2PS, VCVTSS2SD (m32), VCVTSD2SS (m64);
        // VCVTDQ2PS, VCVTPS2DQ, VCVTTPS2DQ; VCVTTPD2DQ, VCVTDQ2PD (m64),
        // VCVTPD2DQ: a scalar form's other lanes from the first source
        (1, 0..=3, 0x5A) | (1, 0..=2, 0x5B) | (1, 1..=3, 0xE6) => {
            let bytes = match (op, pp) {
                (0x5A, 0) | (0x5A, 3) | (0xE6, 2) => 8,
                (0x5A, 2) => 4,
                _ => 16,
            };
            let b = source(m, i, bytes, false)?;
            let r = simd_fp::convert(legacy(i.key), false, xmm(i.vvvv), b)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VROUNDPS/PD (one source), VROUNDSS/SD
        (3, 1, 0x08..=0x0B) => {
            let b = source(m, i, [16, 16, 4, 8][(op - 8) as usize], false)?;
            let r = simd_fp::round(legacy(i.key), xmm(i.vvvv), b, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VDPPS, VDPPD
        (3, 1, 0x40 | 0x41) => {
            let b = source(m, i, 16, false)?;
            let r = simd_fp::dot_product(op == 0x41, xmm(i.vvvv), b, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VBLENDVPS, VBLENDVPD: the mask register is imm8[7:4] (bit 7
        // ignored outside 64-bit mode)
        (3, 1, 0x4A | 0x4B) => {
            let b = source(m, i, 16, false)?;
            let selector = xmm(i.imm8 >> 4 & if i.long { 15 } else { 7 }).to_le_bytes();
            let a = xmm(i.vvvv).to_le_bytes();
            let legacy = if op == 0x4A { 0x14 } else { 0x15 };
            set_xmm(i.reg, bytes(|b| simd_int::sse4(legacy, a, b, selector), b));
        },
        // VBROADCASTSS xmm, m32 (AVX2: also xmm); VPBROADCASTB, VPBROADCASTW,
        // VPBROADCASTD, VPBROADCASTQ (AVX2): an element of memory or of the
        // r/m register's low lane in each lane
        (2, 1, 0x18 | 0x58 | 0x59 | 0x78 | 0x79) => {
            let size = broadcast_size(op);
            let v = element(m, i, size)?;
            set_xmm(i.reg, splat(v, size));
        },
        // VPGATHERDD/DQ/QD/QQ, VGATHERDPS/DPD/QPS/QPD (AVX2, P8)
        (2, 1, 0x90..=0x93) => gather(m, i)?,
        // VPSRLVD/Q, VPSRAVD, VPSLLVD/Q (AVX2; VEX.W1: quadwords): each
        // element by the count in the same element of the second source
        (2, 1, 0x45..=0x47) => {
            let b = source(m, i, 16, false)?;
            set_xmm(i.reg, shift_variable(op, i.w, xmm(i.vvvv), b));
        },
        // VPBLENDD (AVX2): the dwords imm8 selects from the second source,
        // the others from the first
        (3, 1, 0x02) => {
            let b = source(m, i, 16, false)?;
            set_xmm(i.reg, blend_dwords(xmm(i.vvvv), b, i.imm8));
        },
        // VPERMILPS, VPERMILPD: the first source's lanes at the indices of
        // the second's lanes (bits 1:0 of each dword, bit 1 of each quadword)
        (2, 1, 0x0C | 0x0D) => {
            let index = source(m, i, 16, false)?;
            let a = xmm(i.vvvv);
            let r = if op == 0x0C {
                permute(a, 4, |n| (index >> (32 * n)) as u32 & 3)
            }
            else {
                permute(a, 8, |n| (index >> (64 * n + 1)) as u32 & 1)
            };
            set_xmm(i.reg, r);
        },
        // ... and at the indices of imm8 (two bits per dword, one per quadword)
        (3, 1, 0x04 | 0x05) => {
            let v = source(m, i, 16, false)?;
            let r = if op == 0x04 {
                permute(v, 4, |n| (i.imm8 >> (2 * n)) as u32 & 3)
            }
            else {
                permute(v, 8, |n| (i.imm8 >> n) as u32 & 1)
            };
            set_xmm(i.reg, r);
        },
        // VTESTPS, VTESTPD: ZF and CF of the lanes' sign bits, AF, OF, PF,
        // SF cleared
        (2, 1, 0x0E | 0x0F) => {
            let b = source(m, i, 16, false)?;
            let signs: u128 = if op == 0x0E {
                0x8000_0000_8000_0000_8000_0000_8000_0000
            }
            else {
                0x8000_0000_0000_0000_8000_0000_0000_0000
            };
            let a = xmm(i.reg);
            let (zf, cf) = (a & b & signs == 0, !a & b & signs == 0);
            m.set_flags((zf as u32) << 6 | cf as u32);
        },
        // VMASKMOVPS, VMASKMOVPD; AVX2: VPMASKMOVD, VPMASKMOVQ (VEX.W1)
        // xmm, xmm, m128: the lanes of memory the first source's sign bits
        // select, the others zero
        (2, 1, 0x2C | 0x2D | 0x8C) => {
            let size = if op == 0x2C || op == 0x8C && !i.w { 4 } else { 8 };
            let selected = sign_mask(xmm(i.vvvv), size as u32) as u8;
            let v = m.read_lanes(size, 16 / size, selected)?;
            set_xmm(i.reg, v.0);
        },
        // ... m128, xmm, xmm: ModRM.reg's lanes that VEX.vvvv's sign bits
        // select
        (2, 1, 0x2E | 0x2F | 0x8E) => {
            let size = if op == 0x2E || op == 0x8E && !i.w { 4 } else { 8 };
            let selected = sign_mask(xmm(i.vvvv), size as u32) as u8;
            m.write_lanes(size, 16 / size, (xmm(i.reg), 0), selected)?;
        },
        // VSHUFPS, VSHUFPD: the low lanes from the first source, the high
        // ones from the second, as imm8 selects
        (1, 0 | 1, 0xC6) => {
            let b = source(m, i, 16, false)?;
            let shuffle = ShuffleOp::from_encoding(legacy(i.key)).unwrap();
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| shuffle.apply(a, b, i.imm8), b));
        },
        // VPSHUFD, VPSHUFHW, VPSHUFLW: the source's lanes as imm8 selects
        (1, 1..=3, 0x70) => {
            let v = source(m, i, 16, false)?;
            let shuffle = ShuffleOp::from_encoding(legacy(i.key)).unwrap();
            set_xmm(i.reg, bytes(|v| shuffle.apply([0; 16], v, i.imm8), v));
        },
        // VPINSRW: a general-purpose register's low word or an m16 into the
        // first source's word imm8[2:0]
        (1, 1, 0xC4) => {
            let value = match i.rm {
                Some(r) => m.gpr(r) as u128 & 0xFFFF,
                None => m.read(2, false)?,
            };
            let at = (i.imm8 as u32 & 7) * 16;
            set_xmm(i.reg, xmm(i.vvvv) & !(0xFFFF << at) | value << at);
        },
        // VPEXTRW (C5): word imm8[2:0] to a general-purpose register
        (1, 1, 0xC5) => {
            let v = xmm(i.rm.unwrap()) >> ((i.imm8 as u32 & 7) * 16) & 0xFFFF;
            m.set_gpr(i.reg, v as u64, wide);
        },
        // SSSE3: VPSHUFB, VPHADDW/D/SW, VPMADDUBSW, VPHSUBW/D/SW,
        // VPSIGNB/W/D, VPMULHRSW; VPABSB/W/D (of the source alone)
        (2, 1, 0x00..=0x0B | 0x1C..=0x1E) => {
            let b = source(m, i, 16, false)?;
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| simd_int::ssse3(op, a, b), b));
        },
        // VPTEST: ZF and CF
        (2, 1, 0x17) => {
            let b = source(m, i, 16, false)?;
            let (zf, cf) = simd_int::ptest(xmm(i.reg).to_le_bytes(), b.to_le_bytes());
            m.set_flags((zf as u32) << 6 | cf as u32);
        },
        // VPMOVSX*, VPMOVZX*: the source's low lanes extended (from memory,
        // those bytes only)
        (2, 1, 0x20..=0x25 | 0x30..=0x35) => {
            let b = source(m, i, [8, 4, 2, 8, 4, 8][(op & 7) as usize], false)?;
            set_xmm(i.reg, bytes(|b| simd_int::sse4(op, [0; 16], b, [0; 16]), b));
        },
        // VPMULDQ, VPCMPEQQ, VPACKUSDW, VPCMPGTQ, VPMINSB/SD/UW/UD,
        // VPMAXSB/SD/UW/UD, VPMULLD; VPHMINPOSUW (of the source alone)
        (2, 1, 0x28 | 0x29 | 0x2B | 0x37..=0x41) => {
            let b = source(m, i, 16, false)?;
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| simd_int::sse4(op, a, b, [0; 16]), b));
        },
        // VBLENDPS, VBLENDPD, VPBLENDW, VMPSADBW
        (3, 1, 0x0C..=0x0E | 0x42) => {
            let b = source(m, i, 16, false)?;
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| simd_int::sse4_imm(op, a, b, i.imm8), b));
        },
        // VPALIGNR
        (3, 1, 0x0F) => {
            let b = source(m, i, 16, false)?;
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| simd_int::palignr(a, b, i.imm8), b));
        },
        // VPEXTRB, VPEXTRW, VPEXTRD/VPEXTRQ, VEXTRACTPS: an element to a
        // general-purpose register (zero-extended) or memory
        (3, 1, 0x14..=0x17) => {
            let size = match op {
                0x14 => 1,
                0x15 => 2,
                0x16 if wide => 8,
                _ => 4,
            };
            let v = xmm(i.reg) >> ((i.imm8 as u32 & (16 / size - 1)) * size * 8) & low(size);
            match i.rm {
                Some(r) => m.set_gpr(r, v as u64, wide),
                None => m.write(size as u8, v, false)?,
            }
        },
        // VPINSRB, VPINSRD/VPINSRQ: a general-purpose register's low bytes or
        // memory into the first source's element imm8
        (3, 1, 0x20 | 0x22) => {
            let size = if op == 0x20 {
                1
            }
            else if wide {
                8
            }
            else {
                4
            };
            let value = match i.rm {
                Some(r) => m.gpr(r) as u128 & low(size),
                None => m.read(size as u8, false)?,
            };
            let at = (i.imm8 as u32 & (16 / size - 1)) * size * 8;
            set_xmm(i.reg, xmm(i.vvvv) & !(low(size) << at) | value << at);
        },
        // VINSERTPS: the source register's dword imm8[7:6], or the m32
        (3, 1, 0x21) => {
            let value = match i.rm {
                Some(r) => (xmm(r) >> ((i.imm8 >> 6) * 32)) as u32,
                None => m.read(4, false)? as u32,
            };
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(
                i.reg,
                u128::from_le_bytes(simd_int::insertps(a, value, i.imm8)),
            );
        },
        // VPBLENDVB: the mask register is imm8[7:4] (bit 7 ignored outside
        // 64-bit mode)
        (3, 1, 0x4C) => {
            let b = source(m, i, 16, false)?;
            let selector = xmm(i.imm8 >> 4 & if i.long { 15 } else { 7 }).to_le_bytes();
            let a = xmm(i.vvvv).to_le_bytes();
            set_xmm(i.reg, bytes(|b| simd_int::sse4(0x10, a, b, selector), b));
        },
        // VPCMPESTRM, VPCMPESTRI, VPCMPISTRM, VPCMPISTRI: the explicit
        // lengths in EAX and EDX (RAX and RDX with VEX.W1 in 64-bit mode); the
        // index to ECX (zero-extended) or the mask to XMM0
        (3, 1, 0x60..=0x63) => {
            let b = source(m, i, 16, false)?;
            let length = |m: &mut M, r| {
                let v = m.gpr(r);
                if wide {
                    v as i64
                }
                else {
                    v as i32 as i64
                }
            };
            let (la, lb) =
                if op < 0x62 { (Some(length(m, 0)), Some(length(m, 2))) } else { (None, None) };
            let r = simd_int::compare_strings(
                i.imm8,
                xmm(i.reg).to_le_bytes(),
                b.to_le_bytes(),
                la,
                lb,
            );
            if op & 1 != 0 {
                m.set_gpr(1, r.index as u64, false);
            }
            else {
                set_xmm(0, u128::from_le_bytes(r.xmm0));
            }
            m.set_flags(r.flags as u32);
        },
        // VMOVMSKPS, VMOVMSKPD, VPMOVMSKB: the lanes' sign bits
        (1, 0 | 1, 0x50) | (1, 1, 0xD7) => {
            let lane = if op == 0xD7 {
                1
            }
            else if pp == 0 {
                4
            }
            else {
                8
            };
            let mask = sign_mask(xmm(i.rm.unwrap()), lane);
            m.set_gpr(i.reg, mask, wide);
        },
        // VMOVD, VMOVQ xmm, r/m32 or r/m64: zero-extended
        (1, 1, 0x6E) => {
            let v = match i.rm {
                Some(r) => m.gpr(r) & if wide { u64::MAX } else { 0xFFFF_FFFF },
                None => m.read(if wide { 8 } else { 4 }, false)? as u64,
            };
            set_xmm(i.reg, v as u128);
        },
        // VMOVD, VMOVQ r/m32 or r/m64, xmm
        (1, 1, 0x7E) => {
            let v = xmm(i.reg) as u64 & if wide { u64::MAX } else { 0xFFFF_FFFF };
            match i.rm {
                Some(r) => m.set_gpr(r, v, wide),
                None => m.write(if wide { 8 } else { 4 }, v as u128, false)?,
            }
        },
        // VMOVQ xmm, xmm/m64 and xmm/m64, xmm: the low quadword, zero-extended
        (1, 2, 0x7E) => {
            let v = source(m, i, 8, false)? & LOW;
            set_xmm(i.reg, v);
        },
        (1, 1, 0xD6) => {
            let v = xmm(i.reg) & LOW;
            match i.rm {
                Some(r) => set_xmm(r, v),
                None => m.write(8, v, false)?,
            }
        },
        // VZEROUPPER: bits 255:128 of YMM0-YMM7, in 64-bit mode of YMM0-YMM15
        (1, 0, 0x77) => {
            for r in 0..if i.long { 16 } else { 8 } {
                *gp::ymm_hi.add(r) = reg128::of_bits(0);
            }
        },
        // VLDMXCSR (#GP(0) for a reserved bit), VSTMXCSR
        (1, 0, 0xAE) if i.reg & 7 == 2 => {
            let v = m.read(4, false)? as i32;
            if v & !MXCSR_MASK != 0 {
                return Err(m.raise(Exception::GeneralProtection));
            }
            cpu::set_mxcsr(v);
        },
        (1, 0, 0xAE) if i.reg & 7 == 3 => m.write(4, *gp::mxcsr as u32 as u128, false)?,
        // VMASKMOVDQU: the bytes whose mask byte (in the r/m register) has
        // its top bit set
        (1, 1, 0xF7) => {
            let mask = sign_mask(xmm(i.rm.unwrap()), 1);
            m.write_masked(xmm(i.reg), mask as u16)?;
        },
        // FMA (P11): VFMADD/VFMSUB/VFNMADD/VFNMSUB 132/213/231 PS/PD/SS/SD,
        // VFMADDSUB/VFMSUBADD 132/213/231 PS/PD, rounded once
        // (simd_fp::fused); a scalar form's other lanes are the destination's
        (2, 1, 0x96..=0x9F | 0xA6..=0xAF | 0xB6..=0xBF) => {
            let scalar = op & 0xF >= 9 && op & 1 == 1;
            let c = source(
                m,
                i,
                if !scalar {
                    16
                }
                else if i.w {
                    8
                }
                else {
                    4
                },
                false,
            )?;
            let [r] = simd_fp::fused(op, i.w, [xmm(i.reg)], [xmm(i.vvvv)], [c])
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // F16C (P11): VCVTPH2PS xmm, xmm/m64
        (2, 1, 0x13) => {
            let v = source(m, i, 8, false)?;
            let (r, _) =
                simd_fp::half_to_single(v, 4).map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r);
        },
        // VCVTPS2PH xmm/m64, xmm, imm8 (a register destination's other bits
        // zeroed)
        (3, 1, 0x1D) => {
            let r = simd_fp::single_to_half((xmm(i.reg), 0), 4, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            match i.rm {
                Some(rm) => set_xmm(rm, r),
                None => m.write(8, r, false)?,
            }
        },
        _ => {
            dbg_assert!(false, "VEX form {:x} without semantics", i.key);
            return Err(m.raise(Exception::InvalidOpcode));
        },
    }
    Ok(())
}

/// Execute VEX.256 form `i` (Instruction::l): the forms that work lane by
/// lane run their VEX.128 semantics on each 128-bit half, with a 32-byte
/// memory operand
unsafe fn execute256<M: Machine>(m: &mut M, i: &Instruction) -> Result<(), M::Fault> {
    let (map, pp, op) = (i.key >> 16 & 0xFF, i.key >> 8 & 3, i.key as u8);
    match (map, pp, op) {
        // VMOVUPS, VMOVUPD, VMOVAPS, VMOVAPD, VMOVDQA, VMOVDQU, VLDDQU, the
        // aligned ones #GP(0) unless 32-byte aligned
        (1, 0 | 1, 0x10 | 0x28) | (1, 1 | 2, 0x6F) | (1, 3, 0xF0) => {
            let aligned = op == 0x28 || op == 0x6F && pp == 1;
            let v = source256(m, i, aligned)?;
            set_ymm(i.reg, v);
        },
        // their stores, and VMOVNTPS, VMOVNTPD, VMOVNTDQ
        (1, 0 | 1, 0x11 | 0x29 | 0x2B) | (1, 1 | 2, 0x7F) | (1, 1, 0xE7) => {
            let aligned = matches!(op, 0x29 | 0x2B | 0xE7) || op == 0x7F && pp == 1;
            let v = ymm(i.reg);
            match i.rm {
                Some(r) => set_ymm(r, v),
                None => m.write256(v, aligned)?,
            }
        },
        // VMOVSLDUP, VMOVSHDUP, VMOVDDUP: in each half (VMOVDDUP from 32
        // bytes of memory, as the others)
        (1, 2, 0x12 | 0x16) | (1, 3, 0x12) => {
            let v = source256(m, i, false)?;
            let t = TransferOp::from_encoding(legacy(i.key)).unwrap();
            let f = |v: u128| u128::from_le_bytes(t.apply([0; 16], v.to_le_bytes()));
            set_ymm(i.reg, (f(v.0), f(v.1)));
        },
        // VUNPCKLPS, VUNPCKLPD, VUNPCKHPS, VUNPCKHPD, VANDPS, VANDPD, VANDNPS,
        // VANDNPD, VORPS, VORPD, VXORPS, VXORPD: in each half
        (1, 0 | 1, 0x14 | 0x15 | 0x54..=0x57) => {
            let b = source256(m, i, false)?;
            let p = PackedOp::from_encoding(legacy(i.key)).unwrap();
            let a = ymm(i.vvvv);
            set_ymm(i.reg, (packed(p, a.0, b.0), packed(p, a.1, b.1)));
        },
        // VSHUFPS (imm8 for each half), VSHUFPD (imm8[1:0] for the low
        // half, imm8[3:2] for the high one)
        (1, 0 | 1, 0xC6) => {
            let b = source256(m, i, false)?;
            let shuffle = ShuffleOp::from_encoding(legacy(i.key)).unwrap();
            let a = ymm(i.vvvv);
            let high = if pp == 1 { i.imm8 >> 2 } else { i.imm8 };
            set_ymm(
                i.reg,
                (
                    bytes(|b| shuffle.apply(a.0.to_le_bytes(), b, i.imm8), b.0),
                    bytes(|b| shuffle.apply(a.1.to_le_bytes(), b, high), b.1),
                ),
            );
        },
        // VBLENDPS (imm8[3:0] for the low half's dwords, imm8[7:4] for the
        // high one's), VBLENDPD (imm8[1:0], imm8[3:2]); AVX2: VPBLENDW (imm8
        // for each half), VMPSADBW (imm8[2:0], imm8[5:3])
        (3, 1, 0x0C..=0x0E | 0x42) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let high = i.imm8
                >> match op {
                    0x0C => 4,
                    0x0D => 2,
                    0x0E => 0,
                    _ => 3,
                };
            set_ymm(
                i.reg,
                (
                    bytes(
                        |b| simd_int::sse4_imm(op, a.0.to_le_bytes(), b, i.imm8),
                        b.0,
                    ),
                    bytes(|b| simd_int::sse4_imm(op, a.1.to_le_bytes(), b, high), b.1),
                ),
            );
        },
        // VBLENDVPS, VBLENDVPD; AVX2: VPBLENDVB. The mask register is
        // imm8[7:4] (bit 7 ignored outside 64-bit mode)
        (3, 1, 0x4A..=0x4C) => {
            let b = source256(m, i, false)?;
            let selector = ymm(i.imm8 >> 4 & if i.long { 15 } else { 7 });
            let a = ymm(i.vvvv);
            let legacy = [0x14, 0x15, 0x10][(op - 0x4A) as usize];
            let blend = |a: u128, b: u128, s: u128| {
                bytes(
                    |b| simd_int::sse4(legacy, a.to_le_bytes(), b, s.to_le_bytes()),
                    b,
                )
            };
            set_ymm(
                i.reg,
                (blend(a.0, b.0, selector.0), blend(a.1, b.1, selector.1)),
            );
        },
        // VPERMILPS, VPERMILPD by the second source's lanes: in each half
        (2, 1, 0x0C | 0x0D) => {
            let index = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let f = |a: u128, index: u128| {
                if op == 0x0C {
                    permute(a, 4, |n| (index >> (32 * n)) as u32 & 3)
                }
                else {
                    permute(a, 8, |n| (index >> (64 * n + 1)) as u32 & 1)
                }
            };
            set_ymm(i.reg, (f(a.0, index.0), f(a.1, index.1)));
        },
        // ... by imm8: VPERMILPS the same for each half, VPERMILPD imm8[1:0]
        // for the low half and imm8[3:2] for the high one
        (3, 1, 0x04 | 0x05) => {
            let v = source256(m, i, false)?;
            let f = |v: u128, imm8: u8| {
                if op == 0x04 {
                    permute(v, 4, |n| (imm8 >> (2 * n)) as u32 & 3)
                }
                else {
                    permute(v, 8, |n| (imm8 >> n) as u32 & 1)
                }
            };
            let high = if op == 0x05 { i.imm8 >> 2 } else { i.imm8 };
            set_ymm(i.reg, (f(v.0, i.imm8), f(v.1, high)));
        },
        // VBROADCASTSS ymm, m32; VBROADCASTSD ymm, m64 (AVX2: also from an
        // XMM register); VPBROADCASTB/W/D/Q (AVX2): an element in each lane;
        // VBROADCASTF128, VBROADCASTI128 (AVX2): m128 in each half
        (2, 1, 0x18..=0x1A | 0x58..=0x5A | 0x78 | 0x79) => {
            let v = if op == 0x1A || op == 0x5A {
                m.read(16, false)?
            }
            else {
                let size = broadcast_size(op);
                splat(element(m, i, size)?, size)
            };
            set_ymm(i.reg, (v, v));
        },
        // VINSERTF128, VINSERTI128 (AVX2): the first source with half
        // imm8[0] from xmm/m128
        (3, 1, 0x18 | 0x38) => {
            let v = source(m, i, 16, false)?;
            let a = ymm(i.vvvv);
            set_ymm(i.reg, if i.imm8 & 1 == 0 { (v, a.1) } else { (a.0, v) });
        },
        // VEXTRACTF128, VEXTRACTI128 (AVX2): half imm8[0] to an XMM
        // register (bits 255:128 of its YMM register zeroed) or to m128
        (3, 1, 0x19 | 0x39) => {
            let a = ymm(i.reg);
            let v = if i.imm8 & 1 == 0 { a.0 } else { a.1 };
            match i.rm {
                Some(r) => set_xmm(r, v),
                None => m.write(16, v, false)?,
            }
        },
        // VPERM2F128, VPERM2I128 (AVX2): each half one of the sources'
        // halves (imm8[1:0] for the low half, imm8[5:4] for the high one) or
        // zero (imm8[3], imm8[7])
        (3, 1, 0x06 | 0x46) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let select = |control: u8| {
                if control & 8 != 0 {
                    0
                }
                else {
                    [a.0, a.1, b.0, b.1][(control & 3) as usize]
                }
            };
            set_ymm(i.reg, (select(i.imm8), select(i.imm8 >> 4)));
        },
        // VZEROALL: YMM0-YMM7, in 64-bit mode YMM0-YMM15
        (1, 0, 0x77) => {
            for r in 0..if i.long { 16 } else { 8 } {
                set_ymm(r, (0, 0));
            }
        },
        // VPTEST: ZF and CF over both halves
        (2, 1, 0x17) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.reg);
            let low = simd_int::ptest(a.0.to_le_bytes(), b.0.to_le_bytes());
            let high = simd_int::ptest(a.1.to_le_bytes(), b.1.to_le_bytes());
            m.set_flags(((low.0 && high.0) as u32) << 6 | (low.1 && high.1) as u32);
        },
        // VTESTPS, VTESTPD: ZF and CF of all lanes' sign bits, AF, OF, PF,
        // SF cleared
        (2, 1, 0x0E | 0x0F) => {
            let b = source256(m, i, false)?;
            let signs: u128 = if op == 0x0E {
                0x8000_0000_8000_0000_8000_0000_8000_0000
            }
            else {
                0x8000_0000_0000_0000_8000_0000_0000_0000
            };
            let a = ymm(i.reg);
            let zf = (a.0 & b.0 | a.1 & b.1) & signs == 0;
            let cf = (!a.0 & b.0 | !a.1 & b.1) & signs == 0;
            m.set_flags((zf as u32) << 6 | cf as u32);
        },
        // VMOVMSKPS, VMOVMSKPD: all lanes' sign bits
        (1, 0 | 1, 0x50) => {
            let lane = if pp == 0 { 4 } else { 8 };
            m.set_gpr(i.reg, sign_mask256(ymm(i.rm.unwrap()), lane), i.long && i.w);
        },
        // VSQRT, VADD, VMUL, VSUB, VMIN, VDIV, VMAX PS/PD, VHADDPS/PD,
        // VHSUBPS/PD, VADDSUBPS/PD, VCMPPS/PD with 32 predicates: the lanes of
        // both halves with one exception context (VSQRTPS/PD: one source)
        (1, 0 | 1, 0x51 | 0x58 | 0x59 | 0x5C..=0x5F | 0xC2) | (1, 1 | 3, 0x7C | 0x7D | 0xD0) => {
            let b = source256(m, i, false)?;
            let r = simd_fp::arithmetic256(legacy(i.key), ymm(i.vvvv), b, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, r);
        },
        // VRSQRTPS, VRCPPS: no exceptions
        (1, 0, 0x52 | 0x53) => {
            let b = source256(m, i, false)?;
            let key = legacy(i.key);
            set_ymm(
                i.reg,
                (
                    simd_fp::reciprocal(key, 0, b.0),
                    simd_fp::reciprocal(key, 0, b.1),
                ),
            );
        },
        // VROUNDPS, VROUNDPD
        (3, 1, 0x08 | 0x09) => {
            let b = source256(m, i, false)?;
            let r = simd_fp::round256(legacy(i.key), b, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, r);
        },
        // VDPPS: in each half, the low one first (its unmasked exception
        // faults before the high one's operations)
        (3, 1, 0x40) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let low = simd_fp::dot_product(false, a.0, b.0, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            let high = simd_fp::dot_product(false, a.1, b.1, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, (low, high));
        },
        // VCVTDQ2PS, VCVTPS2DQ, VCVTTPS2DQ: eight lanes
        (1, 0..=2, 0x5B) => {
            let b = source256(m, i, false)?;
            let r = simd_fp::convert256(legacy(i.key), b)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, r);
        },
        // VCVTPS2PD, VCVTDQ2PD: xmm/m128's four lanes into four doubles
        (1, 0, 0x5A) | (1, 2, 0xE6) => {
            let b = source(m, i, 16, false)?;
            let r = simd_fp::convert256(legacy(i.key), (b, 0))
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, r);
        },
        // VCVTPD2PS, VCVTPD2DQ, VCVTTPD2DQ: ymm/m256's four doubles into an
        // XMM register (bits 255:128 of its YMM register zeroed)
        (1, 1, 0x5A) | (1, 1 | 3, 0xE6) => {
            let b = source256(m, i, false)?;
            let r = simd_fp::convert256(legacy(i.key), b)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_xmm(i.reg, r.0);
        },
        // VMASKMOVPS, VMASKMOVPD; AVX2: VPMASKMOVD, VPMASKMOVQ (VEX.W1)
        // ymm, ymm, m256: the lanes of memory the first source's sign bits
        // select, the others zero
        (2, 1, 0x2C | 0x2D | 0x8C) => {
            let size = if op == 0x2C || op == 0x8C && !i.w { 4 } else { 8 };
            let selected = sign_mask256(ymm(i.vvvv), size as u32) as u8;
            let v = m.read_lanes(size, 32 / size, selected)?;
            set_ymm(i.reg, v);
        },
        // ... m256, ymm, ymm: ModRM.reg's lanes that VEX.vvvv's sign bits
        // select
        (2, 1, 0x2E | 0x2F | 0x8E) => {
            let size = if op == 0x2E || op == 0x8E && !i.w { 4 } else { 8 };
            let selected = sign_mask256(ymm(i.vvvv), size as u32) as u8;
            m.write_lanes(size, 32 / size, ymm(i.reg), selected)?;
        },
        // AVX2 (P7 part 1): the packed integer forms on each half. 66 0F:
        // unpacks, packs, compares, arithmetic and logic
        (
            1,
            1,
            0x60..=0x6D
            | 0x74..=0x76
            | 0xD4
            | 0xD5
            | 0xD8..=0xE0
            | 0xE3..=0xE5
            | 0xE8..=0xEF
            | 0xF4..=0xF6
            | 0xF8..=0xFE,
        ) => {
            let b = source256(m, i, false)?;
            let p = PackedOp::from_encoding(legacy(i.key)).unwrap();
            let a = ymm(i.vvvv);
            set_ymm(i.reg, (packed(p, a.0, b.0), packed(p, a.1, b.1)));
        },
        // the shifts by xmm/m128: one count (its low quadword) for both
        (1, 1, 0xD1..=0xD3 | 0xE1 | 0xE2 | 0xF1..=0xF3) => {
            let count = source(m, i, 16, false)?;
            let p = PackedOp::from_encoding(legacy(i.key)).unwrap();
            let a = ymm(i.vvvv);
            set_ymm(i.reg, (packed(p, a.0, count), packed(p, a.1, count)));
        },
        // the shifts by imm8 (VEX.vvvv the destination; VPSRLDQ, VPSLLDQ:
        // within each half)
        (1, 1, 0x71..=0x73) => {
            let v = ymm(i.rm.unwrap());
            let f = |v| shift_imm(op, i.reg & 7, v, i.imm8 as u32);
            set_ymm(i.vvvv, (f(v.0), f(v.1)));
        },
        // VPSHUFD, VPSHUFHW, VPSHUFLW: each half's lanes as imm8 selects
        (1, 1..=3, 0x70) => {
            let v = source256(m, i, false)?;
            let shuffle = ShuffleOp::from_encoding(legacy(i.key)).unwrap();
            let f = |v| bytes(|v| shuffle.apply([0; 16], v, i.imm8), v);
            set_ymm(i.reg, (f(v.0), f(v.1)));
        },
        // VPMOVMSKB: the sign bits of all 32 bytes
        (1, 1, 0xD7) => {
            m.set_gpr(i.reg, sign_mask256(ymm(i.rm.unwrap()), 1), i.long && i.w);
        },
        // VPSHUFB (indices within each half), VPHADDW/D/SW, VPMADDUBSW,
        // VPHSUBW/D/SW, VPSIGNB/W/D, VPMULHRSW; VPABSB/W/D (of the source
        // alone)
        (2, 1, 0x00..=0x0B | 0x1C..=0x1E) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let f = |a: u128, b| bytes(|b| simd_int::ssse3(op, a.to_le_bytes(), b), b);
            set_ymm(i.reg, (f(a.0, b.0), f(a.1, b.1)));
        },
        // VPMULDQ, VPCMPEQQ, VPACKUSDW, VPCMPGTQ, VPMINSB/SD/UW/UD,
        // VPMAXSB/SD/UW/UD, VPMULLD
        (2, 1, 0x28 | 0x29 | 0x2B | 0x37..=0x40) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let f = |a: u128, b| bytes(|b| simd_int::sse4(op, a.to_le_bytes(), b, [0; 16]), b);
            set_ymm(i.reg, (f(a.0, b.0), f(a.1, b.1)));
        },
        // VMOVNTDQA: 32-byte aligned
        (2, 1, 0x2A) => {
            let v = source256(m, i, true)?;
            set_ymm(i.reg, v);
        },
        // VPALIGNR: within each half
        (3, 1, 0x0F) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let f = |a: u128, b| bytes(|b| simd_int::palignr(a.to_le_bytes(), b, i.imm8), b);
            set_ymm(i.reg, (f(a.0, b.0), f(a.1, b.1)));
        },
        // VPGATHERDD/DQ/QD/QQ, VGATHERDPS/DPD/QPS/QPD (AVX2, P8)
        (2, 1, 0x90..=0x93) => gather(m, i)?,
        // AVX2 (P7 part 2): VPERMD, VPERMPS: the dwords of the second source
        // at the indices in the first's (bits 2:0 of each)
        (2, 1, 0x16 | 0x36) => {
            let data = source256(m, i, false)?;
            let index = ymm(i.vvvv);
            set_ymm(
                i.reg,
                permute256(data, 4, |n| lane256(index, 4 * n, 4) as u32 & 7),
            );
        },
        // VPERMQ, VPERMPD: the source's quadwords at the indices of imm8
        // (two bits each)
        (3, 1, 0x00 | 0x01) => {
            let v = source256(m, i, false)?;
            set_ymm(i.reg, permute256(v, 8, |n| (i.imm8 >> (2 * n)) as u32 & 3));
        },
        // VPBLENDD: imm8[3:0] for the low half's dwords, imm8[7:4] for the
        // high one's
        (3, 1, 0x02) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            set_ymm(
                i.reg,
                (
                    blend_dwords(a.0, b.0, i.imm8),
                    blend_dwords(a.1, b.1, i.imm8 >> 4),
                ),
            );
        },
        // VPSRLVD/Q, VPSRAVD, VPSLLVD/Q (VEX.W1: quadwords)
        (2, 1, 0x45..=0x47) => {
            let b = source256(m, i, false)?;
            let a = ymm(i.vvvv);
            let f = |a, b| shift_variable(op, i.w, a, b);
            set_ymm(i.reg, (f(a.0, b.0), f(a.1, b.1)));
        },
        // VPMOVSX*, VPMOVZX*: the source's lanes extended over 256 bits (from
        // memory, those bytes only)
        (2, 1, 0x20..=0x25 | 0x30..=0x35) => {
            let half = [8, 4, 2, 8, 4, 8][(op & 7) as usize];
            let b = source(m, i, 2 * half, false)?;
            let f = |b: u128| bytes(|b| simd_int::sse4(op, [0; 16], b, [0; 16]), b);
            set_ymm(i.reg, (f(b), f(b >> (8 * half))));
        },
        // FMA's packed forms (P11) on all eight or four lanes, one exception
        // context
        (2, 1, 0x96..=0x98 | 0x9A | 0x9C | 0x9E | 0xA6..=0xA8 | 0xAA | 0xAC | 0xAE)
        | (2, 1, 0xB6..=0xB8 | 0xBA | 0xBC | 0xBE) => {
            let c = source256(m, i, false)?;
            let (a, b) = (ymm(i.reg), ymm(i.vvvv));
            let [low, high] = simd_fp::fused(op, i.w, [a.0, a.1], [b.0, b.1], [c.0, c.1])
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, (low, high));
        },
        // F16C (P11): VCVTPH2PS ymm, xmm/m128
        (2, 1, 0x13) => {
            let v = source(m, i, 16, false)?;
            let r =
                simd_fp::half_to_single(v, 8).map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            set_ymm(i.reg, r);
        },
        // VCVTPS2PH xmm/m128, ymm, imm8 (a register destination's bits
        // 255:128 zeroed)
        (3, 1, 0x1D) => {
            let r = simd_fp::single_to_half(ymm(i.reg), 8, i.imm8)
                .map_err(|_| m.raise(Exception::SimdFloatingPoint))?;
            match i.rm {
                Some(rm) => set_xmm(rm, r),
                None => m.write(16, r, false)?,
            }
        },
        _ => {
            dbg_assert!(false, "VEX.256 form {:x} without semantics", i.key);
            return Err(m.raise(Exception::InvalidOpcode));
        },
    }
    Ok(())
}

/// The 32-bit interpreter's and the IR helper's side: `address` is the
/// memory operand's linear address (VMASKMOVDQU's destination), which the
/// caller computes after `check`
pub struct Interpreter {
    pub address: i32,
}
impl Machine for Interpreter {
    type Fault = ();
    /// (32-bit addressing: the offset wraps at 32 bits, so does the linear
    /// address with the segment's base)
    unsafe fn gather(&mut self, offset: u64, bytes: u8) -> Result<u64, ()> {
        let a = self.address.wrapping_add(offset as i32);
        Ok(match bytes {
            4 => cpu::safe_read32s(a)? as u32 as u64,
            _ => cpu::safe_read64s(a)?,
        })
    }
    unsafe fn raise(&mut self, e: Exception) {
        match e {
            Exception::InvalidOpcode => cpu::trigger_ud(),
            Exception::DeviceNotAvailable => cpu::trigger_nm(),
            Exception::GeneralProtection => cpu::trigger_gp(0),
            Exception::SimdFloatingPoint => cpu::trigger_simd_fp(),
        }
    }
    unsafe fn read(&mut self, bytes: u8, aligned: bool) -> Result<u128, ()> {
        let a = self.address;
        if aligned {
            cpu::aligned16(a)?;
        }
        Ok(match bytes {
            1 => cpu::safe_read8(a)? as u8 as u128,
            2 => cpu::safe_read16(a)? as u16 as u128,
            4 => cpu::safe_read32s(a)? as u32 as u128,
            8 => cpu::safe_read64s(a)? as u128,
            16 => cpu::safe_read128s(a)?.bits(),
            _ => unreachable!(),
        })
    }
    unsafe fn write(&mut self, bytes: u8, value: u128, aligned: bool) -> Result<(), ()> {
        let a = self.address;
        if aligned {
            cpu::aligned16(a)?;
        }
        match bytes {
            1 => cpu::safe_write8(a, value as u8 as i32),
            2 => cpu::safe_write16(a, value as u16 as i32),
            4 => cpu::safe_write32(a, value as i32),
            8 => cpu::safe_write64(a, value as u64),
            16 => cpu::safe_write128(a, reg128::of_bits(value)),
            _ => unreachable!(),
        }
    }
    unsafe fn read256(&mut self, aligned: bool) -> Result<(u128, u128), ()> {
        let a = self.address;
        if aligned && a & 31 != 0 {
            cpu::trigger_gp(0);
            return Err(());
        }
        let low = cpu::safe_read128s(a)?.bits();
        Ok((low, cpu::safe_read128s(a.wrapping_add(16))?.bits()))
    }
    unsafe fn write256(&mut self, value: (u128, u128), aligned: bool) -> Result<(), ()> {
        let a = self.address;
        if aligned && a & 31 != 0 {
            cpu::trigger_gp(0);
            return Err(());
        }
        cpu::writable_or_pagefault(a, 32)?;
        cpu::safe_write128(a, reg128::of_bits(value.0)).unwrap();
        cpu::safe_write128(a.wrapping_add(16), reg128::of_bits(value.1)).unwrap();
        Ok(())
    }
    /// (as MASKMOVDQU: the whole range writable first, whatever the mask)
    unsafe fn write_masked(&mut self, value: u128, mask: u16) -> Result<(), ()> {
        let a = self.address;
        cpu::writable_or_pagefault(a, 16)?;
        for n in 0..16 {
            if mask >> n & 1 != 0 {
                cpu::safe_write8(a.wrapping_add(n), (value >> (n * 8)) as u8 as i32).unwrap();
            }
        }
        Ok(())
    }
    unsafe fn read_lanes(&mut self, size: u8, count: u8, selected: u8) -> Result<(u128, u128), ()> {
        let mut v = (0, 0);
        for n in 0..count {
            if selected >> n & 1 != 0 {
                let a = self.address.wrapping_add((n * size) as i32);
                let lane = if size == 4 {
                    cpu::safe_read32s(a)? as u32 as u128
                }
                else {
                    cpu::safe_read64s(a)? as u128
                };
                let offset = n as u32 * size as u32;
                if offset < 16 {
                    v.0 |= lane << (offset * 8);
                }
                else {
                    v.1 |= lane << ((offset - 16) * 8);
                }
            }
        }
        Ok(v)
    }
    unsafe fn write_lanes(
        &mut self,
        size: u8,
        count: u8,
        value: (u128, u128),
        selected: u8,
    ) -> Result<(), ()> {
        let lanes = (0..count).filter(|n| selected >> n & 1 != 0);
        for n in lanes.clone() {
            cpu::writable_or_pagefault(self.address.wrapping_add((n * size) as i32), size as i32)?;
        }
        for n in lanes {
            let a = self.address.wrapping_add((n * size) as i32);
            let lane = lane256(value, n as u32 * size as u32, size as u32);
            if size == 4 {
                cpu::safe_write32(a, lane as i32).unwrap();
            }
            else {
                cpu::safe_write64(a, lane).unwrap();
            }
        }
        Ok(())
    }
    unsafe fn gpr(&mut self, r: u8) -> u64 { cpu::read_reg32(r as i32) as u32 as u64 }
    unsafe fn set_gpr(&mut self, r: u8, value: u64, _wide: bool) {
        cpu::write_reg32(r as i32, value as i32);
    }
    unsafe fn set_flags(&mut self, flags: u32) {
        *gp::flags = *gp::flags & !cpu::FLAGS_ALL | flags as i32;
        *gp::flags_changed = 0;
    }
}
                                                                                                                                                  source/v64/src/rust/cpu/bmi.rs                                                                      0000644 0000000 0000000 00000035622 00000000000 013364  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! BMI1, BMI2, LZCNT and MOVBE (docs/simd-xsave-plan.md 9.2, P10): the
//! general-purpose register instructions' results and flags, shared by the
//! three engines. Values are operand-size integers (`bits`: 16, 32 or 64) in
//! the low bits of a u64. Flags are cpu::FLAG_*'s positions (OF, SF, ZF, AF,
//! PF, CF). The SDM leaves some flags undefined; v86 gives them one value:
//! AF 0, PF the parity of the result's low byte (as the logical
//! instructions), and where SF or OF is undefined (BEXTR; TZCNT and LZCNT)
//! the result's sign and 0.

use crate::cpu::{cpu, global_pointers as gp};

pub const CF: u32 = 1;
pub const PF: u32 = 1 << 2;
pub const AF: u32 = 1 << 4;
pub const ZF: u32 = 1 << 6;
pub const SF: u32 = 1 << 7;
pub const OF: u32 = 1 << 11;
/// The flags these instructions write
pub const ARITHMETIC: u32 = CF | PF | AF | ZF | SF | OF;

fn mask(bits: u32) -> u64 { u64::MAX >> (64 - bits) }
/// ZF, SF and PF of `result`, AF and OF clear, and CF
pub fn logic_flags(result: u64, bits: u32, cf: bool) -> u32 {
    let result = result & mask(bits);
    (result == 0) as u32 * ZF
        | (result >> (bits - 1) & 1) as u32 * SF
        | ((result as u8).count_ones() % 2 == 0) as u32 * PF
        | cf as u32 * CF
}

/// ANDN: NOT `a` AND `b`; SF, ZF from the result, CF and OF clear
pub fn andn(a: u64, b: u64, bits: u32) -> (u64, u32) {
    let r = !a & b & mask(bits);
    (r, logic_flags(r, bits, false))
}
/// BEXTR: `src`'s bits from `control`[7:0] on, `control`[15:8] of them
/// (those beyond the operand size are 0); ZF from the result, CF and OF clear
pub fn bextr(src: u64, control: u64, bits: u32) -> (u64, u32) {
    let (start, length) = ((control & 0xFF) as u32, (control >> 8 & 0xFF) as u32);
    let r = if start >= bits {
        0
    }
    else {
        let v = (src & mask(bits)) >> start;
        if length >= 64 {
            v
        }
        else {
            v & ((1 << length) - 1)
        }
    };
    (r, logic_flags(r, bits, false))
}
/// BLSI: the lowest set bit; SF, ZF from the result, CF if `src` is not 0
pub fn blsi(src: u64, bits: u32) -> (u64, u32) {
    let s = src & mask(bits);
    let r = s.wrapping_neg() & s;
    (r, logic_flags(r, bits, s != 0))
}
/// BLSMSK: the bits up to the lowest set one; SF from the result, ZF clear
/// (the result is never 0), CF if `src` is 0
pub fn blsmsk(src: u64, bits: u32) -> (u64, u32) {
    let s = src & mask(bits);
    let r = (s.wrapping_sub(1) ^ s) & mask(bits);
    (r, logic_flags(r, bits, s == 0))
}
/// BLSR: the lowest set bit cleared; SF, ZF from the result, CF if `src` is 0
pub fn blsr(src: u64, bits: u32) -> (u64, u32) {
    let s = src & mask(bits);
    let r = s.wrapping_sub(1) & s;
    (r, logic_flags(r, bits, s == 0))
}
/// BZHI: `src` with its bits from `index`[7:0] on cleared; SF, ZF from the
/// result, CF if the index is beyond the operand size (then `src` whole)
pub fn bzhi(src: u64, index: u64, bits: u32) -> (u64, u32) {
    let n = (index & 0xFF) as u32;
    let s = src & mask(bits);
    let r = if n < bits { s & ((1 << n) - 1) } else { s };
    (r, logic_flags(r, bits, n > bits - 1))
}
/// MULX: the unsigned product of `a` (EDX or RDX) and `b`: (high, low)
pub fn mulx(a: u64, b: u64, bits: u32) -> (u64, u64) {
    let p = (a & mask(bits)) as u128 * (b & mask(bits)) as u128;
    ((p >> bits) as u64 & mask(bits), p as u64 & mask(bits))
}
/// PDEP: `src`'s low bits in turn at the set bits of `selector`
pub fn pdep(src: u64, selector: u64, bits: u32) -> u64 {
    let (mut r, mut k) = (0, 0);
    for i in 0..bits {
        if selector >> i & 1 != 0 {
            r |= (src >> k & 1) << i;
            k += 1;
        }
    }
    r
}
/// PEXT: `src`'s bits at the set bits of `selector`, in turn from bit 0
pub fn pext(src: u64, selector: u64, bits: u32) -> u64 {
    let (mut r, mut k) = (0, 0);
    for i in 0..bits {
        if selector >> i & 1 != 0 {
            r |= (src >> i & 1) << k;
            k += 1;
        }
    }
    r
}
/// RORX: `src` rotated right by `count` modulo the operand size
pub fn rorx(src: u64, count: u8, bits: u32) -> u64 {
    let (s, n) = (src & mask(bits), count as u32 & (bits - 1));
    if n == 0 {
        s
    }
    else {
        (s >> n | s << (bits - n)) & mask(bits)
    }
}
/// SARX, SHLX, SHRX: `src` shifted by `count` modulo the operand size
pub fn sarx(src: u64, count: u64, bits: u32) -> u64 {
    let n = count as u32 & (bits - 1);
    ((((src << (64 - bits)) as i64) >> n >> (64 - bits)) as u64) & mask(bits)
}
pub fn shlx(src: u64, count: u64, bits: u32) -> u64 {
    src << (count as u32 & (bits - 1)) & mask(bits)
}
pub fn shrx(src: u64, count: u64, bits: u32) -> u64 {
    (src & mask(bits)) >> (count as u32 & (bits - 1))
}
/// TZCNT: the trailing zeros, the operand size for 0; ZF if the result is
/// 0, CF if `src` is 0
pub fn tzcnt(src: u64, bits: u32) -> (u64, u32) {
    let s = src & mask(bits);
    let r = if s == 0 { bits as u64 } else { s.trailing_zeros() as u64 };
    (r, logic_flags(r, bits, s == 0))
}
/// LZCNT: the leading zeros, the operand size for 0; as TZCNT's flags
pub fn lzcnt(src: u64, bits: u32) -> (u64, u32) {
    let s = src & mask(bits);
    let r = if s == 0 { bits as u64 } else { (s.leading_zeros() - (64 - bits)) as u64 };
    (r, logic_flags(r, bits, s == 0))
}
/// MOVBE: the bytes of an operand reversed
pub fn byte_swap(value: u64, bits: u32) -> u64 { (value & mask(bits)).swap_bytes() >> (64 - bits) }

/// The VEX-encoded BMI1 and BMI2 instructions
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Vex {
    Andn,
    Bextr,
    Blsi,
    Blsmsk,
    Blsr,
    Bzhi,
    Mulx,
    Pdep,
    Pext,
    Rorx,
    Sarx,
    Shlx,
    Shrx,
}
impl Vex {
    /// The instruction of a VEX key (0xC4_MM_PP_OO: map, pp, opcode) and
    /// ModRM.reg (VEX.0F38 F3's group)
    pub fn of(key: u32, group: u8) -> Option<Vex> {
        use Vex::*;
        Some(match (key >> 16 & 0xFF, key >> 8 & 0xFF, key & 0xFF) {
            (2, 0, 0xF2) => Andn,
            (2, 0, 0xF3) => match group {
                1 => Blsr,
                2 => Blsmsk,
                3 => Blsi,
                _ => return None,
            },
            (2, 0, 0xF5) => Bzhi,
            (2, 2, 0xF5) => Pext,
            (2, 3, 0xF5) => Pdep,
            (2, 3, 0xF6) => Mulx,
            (2, 0, 0xF7) => Bextr,
            (2, 1, 0xF7) => Shlx,
            (2, 2, 0xF7) => Sarx,
            (2, 3, 0xF7) => Shrx,
            (3, 3, 0xF0) => Rorx,
            _ => return None,
        })
    }
}

/// An engine's operands of a VEX BMI instruction
pub trait Machine {
    type Fault;
    /// The r/m operand: a register's or memory's `bits` bits
    unsafe fn source(&mut self, bits: u32) -> Result<u64, Self::Fault>;
    unsafe fn gpr(&mut self, r: u8) -> u64;
    /// The low `bits` bits of `value` to register `r` (32 bits: the upper half
    /// zeroed in 64-bit mode)
    unsafe fn set_gpr(&mut self, r: u8, value: u64, bits: u32);
    /// OF, SF, ZF, AF, PF and CF to those of `flags`
    unsafe fn set_flags(&mut self, flags: u32);
}
/// The 32-bit engines (the interpreter, the IR's helper): the r/m operand a
/// register, or the dword at the linear address `address`
pub struct Interpreter {
    pub rm: Option<u8>,
    pub address: i32,
}
impl Machine for Interpreter {
    type Fault = ();
    unsafe fn source(&mut self, _bits: u32) -> Result<u64, ()> {
        Ok(match self.rm {
            Some(r) => cpu::read_reg32(r as i32) as u32 as u64,
            None => cpu::safe_read32s(self.address)? as u32 as u64,
        })
    }
    unsafe fn gpr(&mut self, r: u8) -> u64 { cpu::read_reg32(r as i32) as u32 as u64 }
    unsafe fn set_gpr(&mut self, r: u8, value: u64, _bits: u32) {
        cpu::write_reg32(r as i32, value as i32)
    }
    unsafe fn set_flags(&mut self, flags: u32) { set_flags(flags) }
}
/// The arithmetic flags of `flags`, the others kept (32-bit engines)
pub unsafe fn set_flags(flags: u32) {
    *gp::flags = *gp::flags & !cpu::FLAGS_ALL | flags as i32;
    *gp::flags_changed = 0;
}

/// A decoded VEX BMI instruction: ModRM.reg, VEX.vvvv, the operand size (64
/// with VEX.W1 in 64-bit mode, otherwise 32) and RORX's imm8
#[derive(Clone, Copy, Debug)]
pub struct Instruction {
    pub op: Vex,
    pub reg: u8,
    pub vvvv: u8,
    pub bits: u32,
    pub imm8: u8,
}
/// Execute `i`: the r/m operand first (a fault before any register changes),
/// then the destinations; MULX writes VEX.vvvv (the low half) before
/// ModRM.reg (the high half), which so wins when they are the same
pub unsafe fn execute<M: Machine>(m: &mut M, i: &Instruction) -> Result<(), M::Fault> {
    use Vex::*;
    let bits = i.bits;
    let source = m.source(bits)?;
    let (destination, value, flags) = match i.op {
        Andn => {
            let (r, f) = andn(m.gpr(i.vvvv), source, bits);
            (i.reg, r, Some(f))
        },
        Bextr => {
            let (r, f) = bextr(source, m.gpr(i.vvvv), bits);
            (i.reg, r, Some(f))
        },
        Blsi | Blsmsk | Blsr => {
            let (r, f) = match i.op {
                Blsi => blsi(source, bits),
                Blsmsk => blsmsk(source, bits),
                _ => blsr(source, bits),
            };
            (i.vvvv, r, Some(f))
        },
        Bzhi => {
            let (r, f) = bzhi(source, m.gpr(i.vvvv), bits);
            (i.reg, r, Some(f))
        },
        Mulx => {
            let (high, low) = mulx(m.gpr(2), source, bits);
            m.set_gpr(i.vvvv, low, bits);
            (i.reg, high, None)
        },
        Pdep => (i.reg, pdep(m.gpr(i.vvvv), source, bits), None),
        Pext => (i.reg, pext(m.gpr(i.vvvv), source, bits), None),
        Rorx => (i.reg, rorx(source, i.imm8, bits), None),
        Sarx => (i.reg, sarx(source, m.gpr(i.vvvv), bits), None),
        Shlx => (i.reg, shlx(source, m.gpr(i.vvvv), bits), None),
        Shrx => (i.reg, shrx(source, m.gpr(i.vvvv), bits), None),
    };
    m.set_gpr(destination, value, bits);
    if let Some(f) = flags {
        m.set_flags(f);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn bit_fields_and_their_edges() {
        for bits in [32, 64] {
            let all = mask(bits);
            assert_eq!(andn(0xF0, 0xFF, bits), (0x0F, PF));
            assert_eq!(andn(all, all, bits), (0, ZF | PF));
            assert_eq!(andn(0, 1 << (bits - 1), bits).1, SF | PF);
            // BEXTR: start and length beyond the operand size, length 0
            assert_eq!(bextr(0xABCD, 0x0804, bits).0, 0xBC);
            assert_eq!(bextr(all, (bits as u64) << 0, bits), (0, ZF | PF));
            assert_eq!(bextr(all, 0xFF00 | 8, bits).0, all >> 8);
            assert_eq!(bextr(all, 0x0000, bits), (0, ZF | PF), "length 0");
            assert_eq!(bextr(all, 0x40_00, bits).0, all, "length 64");
            assert_eq!(
                bextr(0x8000_0000, 0x2000, 32).1,
                SF | PF,
                "SF from the result"
            );
            // BLSI, BLSMSK, BLSR
            assert_eq!(blsi(0b1011000, bits), (0b1000, CF));
            assert_eq!(blsi(0, bits), (0, ZF | PF));
            assert_eq!(blsmsk(0b1011000, bits), (0b1111, PF));
            assert_eq!(
                blsmsk(0, bits),
                (all, SF | PF | CF),
                "all ones for 0, ZF clear"
            );
            assert_eq!(blsr(0b1011000, bits), (0b1010000, PF));
            assert_eq!(blsr(0, bits), (0, ZF | PF | CF));
            assert_eq!(blsr(1 << (bits - 1), bits), (0, ZF | PF));
            // BZHI: the index from bits 7:0 only; beyond the operand size CF
            assert_eq!(bzhi(all, 4, bits), (0xF, PF));
            assert_eq!(bzhi(all, 0, bits), (0, ZF | PF));
            assert_eq!(bzhi(all, bits as u64 - 1, bits), (all >> 1, PF));
            assert_eq!(bzhi(all, bits as u64, bits), (all, SF | PF | CF));
            assert_eq!(bzhi(all, 0x1_04, bits), (0xF, PF), "index 7:0");
            assert_eq!(bzhi(all, 0xFF, bits).1 & CF, CF);
        }
    }
    #[test]
    fn multiply_deposit_extract_rotate_shift() {
        assert_eq!(mulx(u32::MAX as u64, u32::MAX as u64, 32), (0xFFFF_FFFE, 1));
        assert_eq!(mulx(u64::MAX, u64::MAX, 64), (u64::MAX - 1, 1));
        assert_eq!(mulx(1 << 40 | 3, 7, 32), (0, 21), "32 bits of each operand");
        for bits in [32, 64] {
            let all = mask(bits);
            assert_eq!(pdep(all, 0, bits), 0);
            assert_eq!(pdep(all, all, bits), all);
            assert_eq!(pdep(0b101, 0b1110_0000, bits), 0b1010_0000);
            assert_eq!(pext(all, 0, bits), 0);
            assert_eq!(pext(0b1010_0000, 0b1110_0000, bits), 0b101);
            assert_eq!(pext(all, all, bits), all);
            assert_eq!(
                pext(
                    pdep(0x1234_5678, 0xF0F0_F0F0_F0F0_F0F0, bits),
                    0xF0F0_F0F0_F0F0_F0F0,
                    bits
                ),
                0x1234_5678 & mask(bits / 2)
            );
            assert_eq!(rorx(1, 1, bits), 1 << (bits - 1));
            assert_eq!(rorx(0x12, bits as u8, bits), 0x12, "count modulo the size");
            assert_eq!(
                rorx(0x12, 4 + bits as u8, bits),
                0x12 >> 4 | 2 << (bits - 4)
            );
            assert_eq!(shlx(1, bits as u64 + 3, bits), 8);
            assert_eq!(shrx(all, bits as u64 - 1, bits), 1);
            assert_eq!(sarx(1 << (bits - 1), bits as u64 - 1, bits), all);
            assert_eq!(
                sarx(1 << (bits - 1), bits as u64, bits),
                1 << (bits - 1),
                "count modulo the size"
            );
            assert_eq!(sarx(0x40, 3, bits), 8);
        }
    }
    #[test]
    fn counts_and_byte_swaps() {
        for bits in [16, 32, 64] {
            assert_eq!(
                tzcnt(0, bits),
                (bits as u64, logic_flags(bits as u64, bits, true))
            );
            assert_eq!(
                lzcnt(0, bits),
                (bits as u64, logic_flags(bits as u64, bits, true))
            );
            assert_eq!(tzcnt(1, bits), (0, ZF | PF));
            assert_eq!(lzcnt(1 << (bits - 1), bits), (0, ZF | PF));
            assert_eq!(lzcnt(1, bits).0, bits as u64 - 1);
            assert_eq!(tzcnt(1 << (bits - 1), bits).0, bits as u64 - 1);
            assert_eq!(
                tzcnt(1 << bits.min(63), bits).0,
                if bits == 64 { 63 } else { bits as u64 },
                "only the operand's bits"
            );
        }
        assert_eq!(byte_swap(0x1234, 16), 0x3412);
        assert_eq!(byte_swap(0xFFFF_1234, 16), 0x3412);
        assert_eq!(byte_swap(0x1234_5678, 32), 0x7856_3412);
        assert_eq!(byte_swap(0x0102_0304_0506_0708, 64), 0x0807_0605_0403_0201);
    }
    #[test]
    fn vex_keys() {
        assert_eq!(Vex::of(0xC402_00F2, 0), Some(Vex::Andn));
        assert_eq!(Vex::of(0xC402_00F3, 1), Some(Vex::Blsr));
        assert_eq!(Vex::of(0xC402_00F3, 3), Some(Vex::Blsi));
        assert_eq!(Vex::of(0xC402_00F3, 4), None);
        assert_eq!(Vex::of(0xC402_03F5, 0), Some(Vex::Pdep));
        assert_eq!(Vex::of(0xC402_02F7, 0), Some(Vex::Sarx));
        assert_eq!(Vex::of(0xC403_03F0, 0), Some(Vex::Rorx));
        assert_eq!(Vex::of(0xC402_01F5, 0), None);
    }
}
                                                                                                              source/v64/src/rust/cpu/call_indirect.rs                                                            0000644 0000000 0000000 00000000333 00000000000 015400  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #[no_mangle]
pub fn call_indirect1(f: fn(u16), x: u16) { f(x); }
/// The x64 page tier's functions return the instructions they retired.
#[no_mangle]
pub fn call_indirect1_ret(f: fn(u16) -> i32, x: u16) -> i32 { f(x) }
                                                                                                                                                                                                                                                                                                     source/v64/src/rust/cpu/context.rs                                                                  0000644 0000000 0000000 00000011266 00000000000 014277  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! State kept outside the fixed register block. Switching cores preserves
//! translations: only the guest's CR3/INVLPG/shootdown changes their lifetime.
use crate::cpu::cpu::TLB_HAS_CODE;
use crate::cpu::{apic, cpu, global_pointers::*, memory};
use crate::page::Page;

static mut CONTEXTS: [Context; 8] = [const {
    Context {
        tlb: Vec::new(),
        tsc_offset: 0,
    }
}; 8];
struct Context {
    // Portable guest physical address + flags, never a host RAM pointer.
    tlb: Vec<(u32, u32)>,
    tsc_offset: u64,
}

unsafe fn capture(core: usize) {
    let context = &mut CONTEXTS[core];
    context.tlb.clear();
    context.tsc_offset = cpu::tsc_offset;
    for i in 0..cpu::valid_tlb_entries_count as usize {
        let page = cpu::valid_tlb_entries[i] as u32;
        let entry = cpu::tlb_data[page as usize] as u32;
        if entry != 0 {
            let physical = ((entry & !0xFFF) ^ (page << 12)).wrapping_sub(memory::mem8 as u32);
            // (TLB_HAS_CODE is derived from the code caches: install recomputes it)
            context.tlb.push((
                page,
                physical | (entry as u32 & 0xFFF & !(TLB_HAS_CODE as u32)),
            ));
            // Deduplicate the valid list (INVLPG can leave an old index).
            cpu::tlb_data[page as usize] = 0;
        }
    }
    cpu::valid_tlb_entries_count = 0;
    *last_virt_eip = -1;
}
unsafe fn install(core: usize) {
    // (no new code epoch: the core's own translations come back, P7.1)
    cpu::clear_all_tlb_entries();
    cpu::tsc_offset = CONTEXTS[core].tsc_offset;
    cpu::tsc_last_value = 0;
    cpu::tsc_resolution = u64::MAX;
    cpu::tsc_number_of_same_readings = 0;
    for &(page, portable) in &CONTEXTS[core].tlb {
        let physical = portable & !0xFFF;
        let mut info = portable & 0xFFF & !(TLB_HAS_CODE as u32);
        if !memory::in_mapped_range(physical)
            && crate::jit::page_needs_notification(Page::page_of(physical))
        {
            info |= TLB_HAS_CODE as u32;
        }
        cpu::tlb_data[page as usize] =
            ((physical.wrapping_add(memory::mem8 as u32) ^ (page << 12)) | info) as i32;
        cpu::valid_tlb_entries[cpu::valid_tlb_entries_count as usize] = page as i32;
        cpu::valid_tlb_entries_count += 1;
    }
}
#[no_mangle]
pub unsafe fn context_switch(old: u32, new: u32) {
    assert!(old < apic::core_count() as u32 && new < apic::core_count() as u32);
    capture(old as usize);
    install(new as usize);
}
#[no_mangle]
pub unsafe fn context_reset(core: u32) {
    assert!(core < 8);
    crate::cpu::exceptions::init(core);
    crate::x64::memory::invalidate_core(core as usize);
    CONTEXTS[core as usize].tlb.clear();
    if core == apic::current_core() as u32 {
        cpu::full_clear_tlb();
    }
}
#[no_mangle]
pub unsafe fn context_reset_all() {
    crate::cpu::exceptions::reset();
    let offset = (cpu::js::microtick() * cpu::TSC_RATE) as u64;
    for core in 0..8 {
        context_reset(core);
        CONTEXTS[core as usize].tsc_offset = offset;
    }
    cpu::tsc_offset = offset;
}
#[no_mangle]
pub unsafe fn context_capture() {
    let core = apic::current_core();
    capture(core);
    install(core);
}
#[no_mangle]
pub unsafe fn context_install(core: u32) {
    assert!(core < 8);
    install(core as usize);
}
#[no_mangle]
pub unsafe fn context_tlb_len(core: u32) -> u32 {
    assert!(core < 8);
    CONTEXTS[core as usize].tlb.len() as u32
}
#[no_mangle]
pub unsafe fn context_tlb_get(core: u32, index: u32, field: u32) -> u32 {
    assert!(core < 8);
    let (page, entry) = CONTEXTS[core as usize].tlb[index as usize];
    if field == 0 {
        page
    }
    else {
        entry
    }
}
#[no_mangle]
pub unsafe fn context_tlb_push(core: u32, page: u32, entry: u32) {
    assert!(core < 8 && page < 0x100000 && entry & 1 != 0);
    let entries = &mut CONTEXTS[core as usize].tlb;
    assert!(entries.len() < 10000);
    entries.push((page, entry));
}
#[no_mangle]
pub unsafe fn context_tsc_get(core: u32, high: bool) -> u32 {
    assert!(core < 8);
    (CONTEXTS[core as usize].tsc_offset >> if high { 32 } else { 0 }) as u32
}
#[no_mangle]
pub unsafe fn context_tsc_set(core: u32, low: u32, high: u32) {
    assert!(core < 8);
    CONTEXTS[core as usize].tsc_offset = low as u64 | (high as u64) << 32;
}

/// A physical mapping change invalidates address translations, not vCPU state.
pub unsafe fn invalidate_all_tlbs() {
    crate::x64::memory::invalidate_all_tlbs();
    invalidate_legacy_tlbs();
}
/// Only the 32-bit TLBs of every core (host addresses of RAM and of
/// extended RAM frames); the x64 TLBs keep their physical translations
pub unsafe fn invalidate_legacy_tlbs() {
    for core in 0..8 {
        CONTEXTS[core].tlb.clear();
    }
    cpu::full_clear_tlb();
}
                                                                                                                                                                                                                                                                                                                                          source/v64/src/rust/cpu/cpu.rs                                                                      0000644 0000000 0000000 00000541634 00000000000 013411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_upper_case_globals)]

use crate::config;
use crate::cpu::fpu::fpu_set_tag_word;
use crate::cpu::global_pointers::*;
use crate::cpu::memory;
use crate::cpu::misc_instr::{
    adjust_stack_reg, get_stack_pointer, getaf, getcf, getof, getpf, getsf, getzf, pop16, pop32s,
    push16, push32,
};
use crate::cpu::modrm::{resolve_modrm16, resolve_modrm32};
use crate::cpu::{apic, ioapic, pic};
use crate::dbg::dbg_trace;
use crate::gen;
use crate::jit;
use crate::page::Page;
use crate::paging::OrPageFault;
use crate::prefix;
use crate::profiler;
use crate::profiler::stat;
use crate::softfloat;
use crate::state_flags::CachedStateFlags;

use std::collections::HashSet;

pub mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn cpu_exception_hook(interrupt: i32) -> bool;
        pub fn microtick() -> f64;
        pub fn run_hardware_timers(acpi_enabled: bool, t: f64) -> f64;
        pub fn cpu_event_halt();
        pub fn stop_idling();

        pub fn io_port_read8(port: i32) -> i32;
        pub fn io_port_read16(port: i32) -> i32;
        pub fn io_port_read32(port: i32) -> i32;

        pub fn io_port_write8(port: i32, value: i32);
        pub fn io_port_write16(port: i32, value: i32);
        pub fn io_port_write32(port: i32, value: i32);

        pub fn get_rand_int() -> i32;
    }
}

/// The offset for our generated functions in the wasm table. Every index less than this is
/// reserved for rustc's indirect functions
pub const WASM_TABLE_OFFSET: u32 = 1024;

#[derive(Copy, Clone)]
#[repr(C)]
#[repr(align(16))]
pub union reg128 {
    pub i8: [i8; 16],
    pub i16: [i16; 8],
    pub i32: [i32; 4],
    pub i64: [i64; 2],
    pub u8: [u8; 16],
    pub u16: [u16; 8],
    pub u32: [u32; 4],
    pub u64: [u64; 2],
    pub f32: [f32; 4],
    pub f64: [f64; 2],
}

impl reg128 {
    /// The register's 128 bits (lane 0 in the low bits)
    pub fn bits(self) -> u128 { unsafe { std::mem::transmute(self) } }
    pub fn of_bits(bits: u128) -> reg128 { unsafe { std::mem::transmute(bits) } }
}

pub const INTERPRETER_ITERATION_LIMIT: u32 = 100_001;

// How often, in milliseconds, to yield to the browser for rendering and running events
pub const TIME_PER_FRAME: f64 = 1.0;

pub const FLAG_SUB: i32 = -0x8000_0000;
pub const FLAG_CARRY: i32 = 1;
pub const FLAG_PARITY: i32 = 4;
pub const FLAG_ADJUST: i32 = 16;
pub const FLAG_ZERO: i32 = 64;
pub const FLAG_SIGN: i32 = 128;
pub const FLAG_TRAP: i32 = 256;
pub const FLAG_INTERRUPT: i32 = 512;
pub const FLAG_DIRECTION: i32 = 1024;
pub const FLAG_OVERFLOW: i32 = 2048;
pub const FLAG_IOPL: i32 = 1 << 12 | 1 << 13;
pub const FLAG_NT: i32 = 1 << 14;
pub const FLAG_RF: i32 = 1 << 16;
pub const FLAG_VM: i32 = 1 << 17;
pub const FLAG_AC: i32 = 1 << 18;
pub const FLAG_VIF: i32 = 1 << 19;
pub const FLAG_VIP: i32 = 1 << 20;
pub const FLAG_ID: i32 = 1 << 21;
pub const FLAGS_DEFAULT: i32 = 1 << 1;
pub const FLAGS_MASK: i32 = FLAG_CARRY
    | FLAG_PARITY
    | FLAG_ADJUST
    | FLAG_ZERO
    | FLAG_SIGN
    | FLAG_TRAP
    | FLAG_INTERRUPT
    | FLAG_DIRECTION
    | FLAG_OVERFLOW
    | FLAG_IOPL
    | FLAG_NT
    | FLAG_RF
    | FLAG_VM
    | FLAG_AC
    | FLAG_VIF
    | FLAG_VIP
    | FLAG_ID;
pub const FLAGS_ALL: i32 =
    FLAG_CARRY | FLAG_PARITY | FLAG_ADJUST | FLAG_ZERO | FLAG_SIGN | FLAG_OVERFLOW;
pub const OPSIZE_8: i32 = 7;
pub const OPSIZE_16: i32 = 15;
pub const OPSIZE_32: i32 = 31;

pub const EAX: i32 = 0;
pub const ECX: i32 = 1;
pub const EDX: i32 = 2;
pub const EBX: i32 = 3;
pub const ESP: i32 = 4;
pub const EBP: i32 = 5;
pub const ESI: i32 = 6;
pub const EDI: i32 = 7;

pub const AX: i32 = 0;
pub const CX: i32 = 1;
pub const DX: i32 = 2;
pub const BX: i32 = 3;
pub const SP: i32 = 4;
pub const BP: i32 = 5;
pub const SI: i32 = 6;
pub const DI: i32 = 7;

pub const AL: i32 = 0;
pub const CL: i32 = 1;
pub const DL: i32 = 2;
pub const BL: i32 = 3;
pub const AH: i32 = 4;
pub const CH: i32 = 5;
pub const DH: i32 = 6;
pub const BH: i32 = 7;

pub const ES: i32 = 0;
pub const CS: i32 = 1;
pub const SS: i32 = 2;
pub const DS: i32 = 3;
pub const FS: i32 = 4;
pub const GS: i32 = 5;
pub const TR: i32 = 6;

pub const LDTR: i32 = 7;
pub const PAGE_TABLE_PRESENT_MASK: i32 = 1 << 0;
pub const PAGE_TABLE_RW_MASK: i32 = 1 << 1;
pub const PAGE_TABLE_USER_MASK: i32 = 1 << 2;
pub const PAGE_TABLE_ACCESSED_MASK: i32 = 1 << 5;
pub const PAGE_TABLE_DIRTY_MASK: i32 = 1 << 6;
pub const PAGE_TABLE_PSE_MASK: i32 = 1 << 7;
pub const PAGE_TABLE_GLOBAL_MASK: i32 = 1 << 8;
pub const MMAP_BLOCK_BITS: i32 = 17;
pub const MMAP_BLOCK_SIZE: i32 = 1 << MMAP_BLOCK_BITS;
pub const CR0_PE: i32 = 1;
pub const CR0_MP: i32 = 1 << 1;
pub const CR0_EM: i32 = 1 << 2;
pub const CR0_TS: i32 = 1 << 3;
pub const CR0_ET: i32 = 1 << 4;
pub const CR0_WP: i32 = 1 << 16;
pub const CR0_AM: i32 = 1 << 18;
pub const CR0_NW: i32 = 1 << 29;
pub const CR0_CD: i32 = 1 << 30;
pub const CR0_PG: i32 = 1 << 31;
pub const CR4_VME: i32 = 1;
pub const CR4_PVI: i32 = 1 << 1;
pub const CR4_TSD: i32 = 1 << 2;
pub const CR4_PSE: i32 = 1 << 4;
pub const CR4_DE: i32 = 1 << 3;
pub const CR4_PAE: i32 = 1 << 5;
pub const CR4_PGE: i32 = 1 << 7;
pub const CR4_OSFXSR: i32 = 1 << 9;
pub const CR4_OSXMMEXCPT: i32 = 1 << 10;
pub const CR4_OSXSAVE: i32 = 1 << 18;
pub const CR4_SMEP: i32 = 1 << 20;
/// The CR4 bits MOV to CR4 (legacy and x64) and RSM accept, those of the
/// features this CPU has: VME through OSXMMEXCPT, OSXSAVE with XSAVE
pub fn cr4_valid_bits() -> u32 {
    0x7FF
        | if crate::cpu::features::has(crate::cpu::features::XSAVE) {
            CR4_OSXSAVE as u32
        }
        else {
            0
        }
}

pub const TSR_BACKLINK: i32 = 0x00;
pub const TSR_CR3: i32 = 0x1C;
pub const TSR_EIP: i32 = 0x20;
pub const TSR_EFLAGS: i32 = 0x24;

pub const TSR_EAX: i32 = 0x28;
pub const TSR_ECX: i32 = 0x2c;
pub const TSR_EDX: i32 = 0x30;
pub const TSR_EBX: i32 = 0x34;
pub const TSR_ESP: i32 = 0x38;
pub const TSR_EBP: i32 = 0x3c;
pub const TSR_ESI: i32 = 0x40;
pub const TSR_EDI: i32 = 0x44;

pub const TSR_ES: i32 = 0x48;
pub const TSR_CS: i32 = 0x4c;
pub const TSR_SS: i32 = 0x50;
pub const TSR_DS: i32 = 0x54;
pub const TSR_FS: i32 = 0x58;
pub const TSR_GS: i32 = 0x5c;
pub const TSR_LDT: i32 = 0x60;

pub const IA32_TIME_STAMP_COUNTER: i32 = 0x10;
pub const IA32_PLATFORM_ID: i32 = 0x17;
pub const IA32_APIC_BASE: i32 = 0x1B;
pub const MSR_TEST_CTRL: i32 = 0x33;
pub const MSR_SMI_COUNT: i32 = 0x34;
pub const IA32_FEAT_CTL: i32 = 0x3A;
pub const IA32_SPEC_CTRL: i32 = 0x48;
pub const IA32_BIOS_UPDT_TRIG: i32 = 0x79;
pub const IA32_BIOS_SIGN_ID: i32 = 0x8B;
pub const IA32_PMC0: i32 = 0xC1;
pub const IA32_PMC1: i32 = 0xC2;
pub const MSR_PLATFORM_INFO: i32 = 0xCE;
pub const MSR_TSX_FORCE_ABORT: i32 = 0x10F;
pub const IA32_TSX_CTRL: i32 = 0x122;
pub const IA32_MCU_OPT_CTRL: i32 = 0x123;
pub const MISC_FEATURE_ENABLES: i32 = 0x140;
pub const IA32_SYSENTER_CS: i32 = 0x174;
pub const IA32_SYSENTER_ESP: i32 = 0x175;
pub const IA32_SYSENTER_EIP: i32 = 0x176;
pub const IA32_MCG_CAP: i32 = 0x179;
pub const IA32_PERFEVTSEL0: i32 = 0x186;
pub const IA32_PERFEVTSEL1: i32 = 0x187;
pub const IA32_MISC_ENABLE: i32 = 0x1A0;
pub const IA32_PAT: i32 = 0x277;
pub const IA32_RTIT_CTL: i32 = 0x570;
pub const MSR_PKG_C2_RESIDENCY: i32 = 0x60D;
pub const IA32_FS_BASE: i32 = 0xC0000100u32 as i32;
pub const IA32_GS_BASE: i32 = 0xC0000101u32 as i32;
pub const MSR_AMD64_LS_CFG: i32 = 0xC0011020u32 as i32;
pub const MSR_AMD64_DE_CFG: i32 = 0xC0011029u32 as i32;

pub const IA32_APIC_BASE_BSP: i32 = 1 << 8;
pub const IA32_APIC_BASE_EXTD: i32 = 1 << 10;
pub const IA32_APIC_BASE_EN: i32 = 1 << 11;

pub const IOAPIC_MEM_ADDRESS: u32 = 0xFEC00000;
pub const IOAPIC_MEM_SIZE: u32 = 32;
pub const APIC_MEM_ADDRESS: u32 = 0xFEE00000;
pub const APIC_MEM_SIZE: u32 = 0x1000;

pub const MXCSR_MASK: i32 = 0xffff;
pub const MXCSR_FZ: i32 = 1 << 15;
pub const MXCSR_DAZ: i32 = 1 << 6;
pub const MXCSR_RC_SHIFT: i32 = 13;

pub const VALID_TLB_ENTRY_MAX: i32 = 10000;
pub const TLB_VALID: i32 = 1 << 0;
pub const TLB_READONLY: i32 = 1 << 1;
pub const TLB_NO_USER: i32 = 1 << 2;
pub const TLB_IN_MAPPED_RANGE: i32 = 1 << 3;
pub const TLB_GLOBAL: i32 = 1 << 4;
pub const TLB_HAS_CODE: i32 = 1 << 5;
/// Filled by an IA-32e data access (fill_ia32e_tlb): the entry serves data
/// accesses of compiled 32-bit code but does not show that the page is
/// executable (NX was not checked), so code validation treats it as a miss.
pub const TLB_IA32E_DATA: i32 = 1 << 6;
pub const IVT_SIZE: u32 = 0x400;
pub const CPU_EXCEPTION_DE: i32 = 0;
pub const CPU_EXCEPTION_DB: i32 = 1;
pub const CPU_EXCEPTION_NMI: i32 = 2;
pub const CPU_EXCEPTION_BP: i32 = 3;
pub const CPU_EXCEPTION_OF: i32 = 4;
pub const CPU_EXCEPTION_BR: i32 = 5;
pub const CPU_EXCEPTION_UD: i32 = 6;
pub const CPU_EXCEPTION_NM: i32 = 7;
pub const CPU_EXCEPTION_DF: i32 = 8;
pub const CPU_EXCEPTION_TS: i32 = 10;
pub const CPU_EXCEPTION_NP: i32 = 11;
pub const CPU_EXCEPTION_SS: i32 = 12;
pub const CPU_EXCEPTION_GP: i32 = 13;
pub const CPU_EXCEPTION_PF: i32 = 14;
pub const CPU_EXCEPTION_MF: i32 = 16;
pub const CPU_EXCEPTION_AC: i32 = 17;
pub const CPU_EXCEPTION_MC: i32 = 18;
pub const CPU_EXCEPTION_XM: i32 = 19;
pub const CPU_EXCEPTION_VE: i32 = 20;

pub const CHECK_TLB_INVARIANTS: bool = false;

pub const DEBUG: bool = cfg!(debug_assertions);

pub const LOOP_COUNTER: i32 = 100_003;

// should probably be kept in sync with APIC_TIMER_FREQ in apic.js
pub const TSC_RATE: f64 = 1_000_000.0;

pub static mut cpuid_level: u32 = 0x16;

pub static mut jit_block_boundary: bool = false;

#[cfg(debug_assertions)]
pub static mut tsc_last_extra: u64 = 0;

// the last value returned by rdtsc
pub static mut tsc_last_value: u64 = 0;
// the smallest difference between two rdtsc readings (depends on the browser's performance.now resolution)
pub static mut tsc_resolution: u64 = u64::MAX;
// how many times rdtsc was called and had to return the same value (due to browser's performance.now resolution)
pub static mut tsc_number_of_same_readings: u64 = 0;
// how often rdtsc was previously called without its value changing, used for interpolating quick
// consecutive calls between rdtsc (when it's called faster than the browser's performance.now
// changes)
pub static mut tsc_speed: u64 = 1;

// used for restoring the state
pub static mut tsc_offset: u64 = 0;

/// Set by PAUSE when the machine has more than one core: the active core ends
/// its slice so that another one can run, e.g. to release a spinlock the
/// spinning core waits for (see CPU.prototype.run_cores)
pub static mut core_yield: bool = false;

#[no_mangle]
pub unsafe fn request_core_yield() {
    core_yield = true;
    jit_block_boundary = true;
}

/// A spin-wait hint (PAUSE) or a bounded REP step with several cores: when
/// they share this thread (cooperative scheduling), let another one run. A
/// core with a thread of its own (crate::parallel) only leaves the current
/// compiled block: ending its slice would not let anyone else run sooner,
/// and on the machine's thread it would return to the event loop each time.
pub unsafe fn yield_to_other_cores() {
    if !crate::parallel::active() {
        core_yield = true;
    }
    jit_block_boundary = true;
}

/// A worker instance takes the machine instance's CPU profile (CPUID level
/// and features) and compiler policy: when it attaches and at the start of
/// each slice (crate::parallel::sync_worker_configuration), so that every
/// core reports the same CPU even when the embedder changes the profile after
/// the workers started. JavaScript applies the other settings to it the same
/// way as to the machine instance.
pub unsafe fn copy_machine_configuration() {
    use crate::parallel::machine;
    cpuid_level = *machine(&raw mut cpuid_level);
    crate::cpu::instructions_0f::copy_cpu_profile();
    crate::jit_switches::copy_from_machine();
}

pub static mut tlb_data: [i32; 0x100000] = [0; 0x100000];

pub static mut valid_tlb_entries: [i32; 10000] = [0; 10000];
pub static mut valid_tlb_entries_count: i32 = 0;

pub enum LastJump {
    Interrupt {
        phys_addr: u32,
        int: u8,
        software: bool,
        error: Option<u32>,
    },
    Interpreted {
        phys_addr: u32,
    },
    None,
}
impl LastJump {
    pub fn phys_address(&self) -> Option<u32> {
        match self {
            LastJump::Interrupt { phys_addr, .. } => Some(*phys_addr),
            LastJump::Interpreted { phys_addr } => Some(*phys_addr),
            LastJump::None => None,
        }
    }
    pub fn name(&self) -> &'static str {
        match self {
            LastJump::Interrupt { .. } => "interrupt",
            LastJump::Interpreted { .. } => "interpreted",
            LastJump::None => "none",
        }
    }
}
pub static mut debug_last_jump: LastJump = LastJump::None;

#[derive(Copy, Clone)]
pub struct SegmentSelector {
    raw: u16,
}

impl SegmentSelector {
    pub fn of_u16(raw: u16) -> SegmentSelector { SegmentSelector { raw } }
    pub fn rpl(&self) -> u8 { (self.raw & 3) as u8 }
    pub fn is_gdt(&self) -> bool { (self.raw & 4) == 0 }
    pub fn descriptor_offset(&self) -> u16 { (self.raw & !7) as u16 }

    pub fn is_null(&self) -> bool { self.is_gdt() && self.descriptor_offset() == 0 }
}

// Used to indicate early that the selector cannot be used to fetch a descriptor
#[derive(PartialEq)]
pub enum SelectorNullOrInvalid {
    IsNull,
    OutsideOfTableLimit,
}

pub struct SegmentDescriptor {
    pub raw: u64,
}

impl SegmentDescriptor {
    pub fn of_u64(raw: u64) -> SegmentDescriptor { SegmentDescriptor { raw } }
    pub fn base(&self) -> i32 {
        ((self.raw >> 16) & 0xffff | (self.raw & 0xff_00000000) >> 16 | (self.raw >> 56 << 24))
            as i32
    }
    pub fn limit(&self) -> u32 { (self.raw & 0xffff | ((self.raw >> 48) & 0xf) << 16) as u32 }
    pub fn access_byte(&self) -> u8 { ((self.raw >> 40) & 0xff) as u8 }
    pub fn flags(&self) -> u8 { ((self.raw >> 48 >> 4) & 0xf) as u8 }

    pub fn is_system(&self) -> bool { self.access_byte() & 0x10 == 0 }
    pub fn system_type(&self) -> u8 { self.access_byte() & 0xF }

    pub fn accessed(&self) -> bool { self.access_byte() & 1 == 1 }
    pub fn is_rw(&self) -> bool { self.access_byte() & 2 == 2 }
    pub fn is_dc(&self) -> bool { self.access_byte() & 4 == 4 }
    pub fn is_executable(&self) -> bool { self.access_byte() & 8 == 8 }
    pub fn is_present(&self) -> bool { self.access_byte() & 0x80 == 0x80 }
    pub fn is_writable(&self) -> bool { self.is_rw() && !self.is_executable() }
    pub fn is_readable(&self) -> bool { self.is_rw() || !self.is_executable() }
    pub fn is_conforming_executable(&self) -> bool { self.is_dc() && self.is_executable() }
    pub fn dpl(&self) -> u8 { (self.access_byte() >> 5) & 3 }
    pub fn is_32(&self) -> bool { self.flags() & 4 == 4 }
    pub fn effective_limit(&self) -> u32 {
        if self.flags() & 8 == 8 {
            self.limit() << 12 | 0xFFF
        }
        else {
            self.limit()
        }
    }
    pub fn set_busy(&self) -> SegmentDescriptor {
        SegmentDescriptor {
            raw: self.raw | 2 << 40,
        }
    }
    pub fn clear_busy(&self) -> SegmentDescriptor {
        SegmentDescriptor {
            raw: self.raw & !(2 << 40),
        }
    }
    pub fn set_accessed(&self) -> SegmentDescriptor {
        SegmentDescriptor {
            raw: self.raw | 1 << 40,
        }
    }
}

pub struct InterruptDescriptor {
    raw: u64,
}

impl InterruptDescriptor {
    pub fn of_u64(raw: u64) -> InterruptDescriptor { InterruptDescriptor { raw } }
    pub fn offset(&self) -> i32 { (self.raw & 0xffff | self.raw >> 32 & 0xffff0000) as i32 }
    pub fn selector(&self) -> u16 { (self.raw >> 16 & 0xffff) as u16 }
    pub fn access_byte(&self) -> u8 { (self.raw >> 40 & 0xff) as u8 }
    pub fn dpl(&self) -> u8 { (self.access_byte() >> 5 & 3) as u8 }
    pub fn gate_type(&self) -> u8 { self.access_byte() & 7 }
    pub fn is_32(&self) -> bool { self.access_byte() & 8 == 8 }
    pub fn is_present(&self) -> bool { self.access_byte() & 0x80 == 0x80 }
    pub fn reserved_zeros_are_valid(&self) -> bool { self.access_byte() & 16 == 0 }

    const TASK_GATE: u8 = 0b101;
    const INTERRUPT_GATE: u8 = 0b110;
    const TRAP_GATE: u8 = 0b111;
}

pub unsafe fn switch_cs_real_mode(selector: i32) {
    dbg_assert!(!*protected_mode || vm86_mode());

    *sreg.offset(CS as isize) = selector as u16;
    *segment_is_null.offset(CS as isize) = false;
    *segment_offsets.offset(CS as isize) = selector << 4;
    update_cs_size(false);
}

// Descriptor/TSS reads are supervisor accesses and can straddle guest pages.
unsafe fn read_system(addr: i32, size: u32) -> OrPageFault<u64> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return crate::x64::memory::read_system(addr as u32 as u64, (size * 8) as u8)
            .map_err(|fault| crate::x64::system::raise(fault));
    }
    let first = translate_address_system_read(addr)?;
    if (addr as u32 & 0xFFF) + size <= 4096 {
        return Ok(match size {
            8 => memory::read64s(first) as u64,
            4 => memory::read32s(first) as u32 as u64,
            2 => memory::read16(first) as u64,
            _ => unreachable!(),
        });
    }
    let mut physical = [0u32; 8];
    for i in 0..size {
        physical[i as usize] = translate_address_system_read(addr.wrapping_add(i as i32))?;
    }
    let mut value = 0;
    for i in 0..size {
        value |= (memory::read8(physical[i as usize]) as u64) << (i * 8);
    }
    Ok(value)
}

unsafe fn get_tss_ss_esp(dpl: u8) -> OrPageFault<(i32, i32)> {
    let offset = if *tss_size_32 { ((dpl as u32) << 3) + 4 } else { ((dpl as u32) << 2) + 2 };
    let size = if *tss_size_32 { 4 } else { 2 };
    if offset + size + 1 > *segment_limits.offset(TR as isize) {
        trigger_ts(*sreg.offset(TR as isize) as i32 & !3);
        return Err(());
    }
    let addr = (*segment_offsets.offset(TR as isize)).wrapping_add(offset as i32);
    let esp = read_system(addr, size)? as i32;
    let ss = read_system(addr.wrapping_add(size as i32), 2)? as i32;
    Ok((ss, esp))
}

pub unsafe fn iret16() { iret(true); }
pub unsafe fn iret32() { iret(false); }

pub unsafe fn iret(is_16: bool) {
    crate::parallel::code::poll();
    iret_checked(is_16);
}

/// Reports whether the semantic body completed; delivered faults remain CPU-owned.
pub unsafe fn iret_checked(is_16: bool) -> bool {
    // IRET ends NMI blocking (also when it faults)
    *nmi_blocked = false;
    *interrupt_shadow = 0;
    let mut completed = true;
    if vm86_mode() && getiopl() < 3 {
        // vm86 mode, iopl != 3
        dbg_log!("#gp iret vm86 mode, iopl != 3");
        trigger_gp(0);
        return false;
    }

    let (new_eip, new_cs, mut new_flags) = if is_16 {
        (
            return_on_pagefault!(safe_read16(get_stack_pointer(0)), false),
            return_on_pagefault!(safe_read16(get_stack_pointer(2)), false),
            return_on_pagefault!(safe_read16(get_stack_pointer(4)), false),
        )
    }
    else {
        (
            return_on_pagefault!(safe_read32s(get_stack_pointer(0)), false),
            return_on_pagefault!(safe_read16(get_stack_pointer(4)), false),
            return_on_pagefault!(safe_read32s(get_stack_pointer(8)), false),
        )
    };

    if !*protected_mode || (vm86_mode() && getiopl() == 3) {
        if new_eip as u32 & 0xFFFF0000 != 0 {
            trigger_gp(0);
            return false;
        }

        switch_cs_real_mode(new_cs);
        *instruction_pointer = get_seg_cs() + new_eip;

        if is_16 {
            update_eflags(new_flags | *flags & !0xFFFF);
            adjust_stack_reg(3 * 2);
        }
        else {
            if !*protected_mode {
                update_eflags((new_flags & 0x257FD5) | (*flags & 0x1A0000));
            }
            else {
                update_eflags(new_flags);
            }
            adjust_stack_reg(3 * 4);
        }

        update_state_flags();
        handle_irqs();
        return completed;
    }

    dbg_assert!(!vm86_mode());

    if *flags & FLAG_NT != 0 {
        // nested task: return to the task linked through the back-link field of the current tss
        let tss_offset = *segment_offsets.offset(TR as isize);
        let backlink = return_on_pagefault!(safe_read16(tss_offset + TSR_BACKLINK), false);
        return do_task_switch_checked(backlink, None, TaskSwitchSource::Iret);
    }

    if new_flags & FLAG_VM != 0 {
        if *cpl == 0 {
            // return to virtual 8086 mode

            // vm86 cannot be set in 16 bit flag
            dbg_assert!(!is_16);

            let temp_esp = return_on_pagefault!(safe_read32s(get_stack_pointer(12)), false);
            let temp_ss = return_on_pagefault!(safe_read16(get_stack_pointer(16)), false);

            let new_es = return_on_pagefault!(safe_read16(get_stack_pointer(20)), false);
            let new_ds = return_on_pagefault!(safe_read16(get_stack_pointer(24)), false);
            let new_fs = return_on_pagefault!(safe_read16(get_stack_pointer(28)), false);
            let new_gs = return_on_pagefault!(safe_read16(get_stack_pointer(32)), false);

            // no exceptions below

            update_eflags(new_flags);
            *flags |= FLAG_VM;

            switch_cs_real_mode(new_cs);
            *instruction_pointer = get_seg_cs() + (new_eip & 0xFFFF);

            if !switch_seg(ES, new_es)
                || !switch_seg(DS, new_ds)
                || !switch_seg(FS, new_fs)
                || !switch_seg(GS, new_gs)
            {
                // XXX: Should be checked before side effects
                dbg_assert!(false);
                completed = false;
            }

            adjust_stack_reg(9 * 4); // 9 dwords: eip, cs, flags, esp, ss, es, ds, fs, gs

            write_reg32(ESP, temp_esp);
            if !switch_seg(SS, temp_ss) {
                // XXX
                dbg_assert!(false);
                completed = false;
            }

            *cpl = 3;
            cpl_changed();

            update_cs_size(false);
            update_state_flags();

            // iret end
            return completed;
        }
        else {
            dbg_log!("vm86 flag ignored because cpl != 0");
            new_flags &= !FLAG_VM;
        }
    }

    // protected mode return

    let cs_selector = SegmentSelector::of_u16(new_cs as u16);
    let cs_descriptor = match return_on_pagefault!(lookup_segment_selector(cs_selector), false) {
        Ok((desc, _)) => desc,
        Err(SelectorNullOrInvalid::IsNull) => {
            trigger_gp(0);
            return false;
        },
        Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
            trigger_gp(new_cs & !3);
            return false;
        },
    };

    if cs_descriptor.is_system() || !cs_descriptor.is_executable() {
        trigger_gp(new_cs & !3);
        return false;
    }
    if cs_selector.rpl() < *cpl {
        trigger_gp(new_cs & !3);
        return false;
    }
    if cs_descriptor.is_dc() && cs_descriptor.dpl() > cs_selector.rpl() {
        trigger_gp(new_cs & !3);
        return false;
    }

    if !cs_descriptor.is_dc() && cs_selector.rpl() != cs_descriptor.dpl() {
        dbg_log!(
            "#gp iret: non-conforming cs and rpl != dpl, dpl={} rpl={}",
            cs_descriptor.dpl(),
            cs_selector.rpl()
        );
        trigger_gp(new_cs & !3);
        return false;
    }

    if !cs_descriptor.is_present() {
        trigger_np(new_cs & !3);
        return false;
    }
    if new_eip as u32 > cs_descriptor.effective_limit() {
        trigger_gp(0);
        return false;
    }

    if cs_selector.rpl() > *cpl {
        // outer privilege return
        let (temp_esp, temp_ss) = if is_16 {
            (
                return_on_pagefault!(safe_read16(get_stack_pointer(6)), false),
                return_on_pagefault!(safe_read16(get_stack_pointer(8)), false),
            )
        }
        else {
            (
                return_on_pagefault!(safe_read32s(get_stack_pointer(12)), false),
                return_on_pagefault!(safe_read16(get_stack_pointer(16)), false),
            )
        };

        let ss_selector = SegmentSelector::of_u16(temp_ss as u16);
        let ss_descriptor = match return_on_pagefault!(lookup_segment_selector(ss_selector), false)
        {
            Ok((desc, _)) => desc,
            Err(SelectorNullOrInvalid::IsNull) => {
                dbg_log!("#GP for loading 0 in SS sel={:x}", temp_ss);
                dbg_trace();
                trigger_gp(0);
                return false;
            },
            Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
                dbg_log!("#GP for loading invalid in SS sel={:x}", temp_ss);
                trigger_gp(temp_ss & !3);
                return false;
            },
        };
        let new_cpl = cs_selector.rpl();

        if ss_descriptor.is_system()
            || ss_selector.rpl() != new_cpl
            || !ss_descriptor.is_writable()
            || ss_descriptor.dpl() != new_cpl
        {
            dbg_log!("#GP for loading invalid in SS sel={:x}", temp_ss);
            dbg_trace();
            trigger_gp(temp_ss & !3);
            return false;
        }

        if !ss_descriptor.is_present() {
            dbg_log!("#SS for loading non-present in SS sel={:x}", temp_ss);
            dbg_trace();
            trigger_ss(temp_ss & !3);
            return false;
        }

        // no exceptions below

        if is_16 {
            update_eflags(new_flags | *flags & !0xFFFF);
        }
        else {
            update_eflags(new_flags);
        }

        *cpl = cs_selector.rpl();
        cpl_changed();

        if !switch_seg(SS, temp_ss) {
            // XXX
            dbg_assert!(false);
            completed = false;
        }

        set_stack_reg(temp_esp);

        if *cpl == 0 && !is_16 {
            *flags = *flags & !FLAG_VIF & !FLAG_VIP | (new_flags & (FLAG_VIF | FLAG_VIP));
        }

        for reg in [ES, DS, FS, GS] {
            let access = *segment_access_bytes.offset(reg as isize);
            let dpl = access >> 5 & 3;
            let executable = access & 8 == 8;
            let conforming = access & 4 == 4;
            if dpl < *cpl && !(executable && conforming) {
                //dbg_log!(
                //    "set segment to null sreg={} dpl={} executable={} conforming={}",
                //    reg,
                //    dpl,
                //    executable,
                //    conforming
                //);
                *segment_is_null.offset(reg as isize) = true;
                *sreg.offset(reg as isize) = 0;
            }
        }
    }
    else if cs_selector.rpl() == *cpl {
        // same privilege return
        // no exceptions below
        if is_16 {
            adjust_stack_reg(3 * 2);
            update_eflags(new_flags | *flags & !0xFFFF);
        }
        else {
            adjust_stack_reg(3 * 4);
            update_eflags(new_flags);
        }

        // update vip and vif, which are not changed by update_eflags
        if *cpl == 0 && !is_16 {
            *flags = *flags & !FLAG_VIF & !FLAG_VIP | (new_flags & (FLAG_VIF | FLAG_VIP));
        }
    }
    else {
        dbg_assert!(false);
    }

    *sreg.offset(CS as isize) = new_cs as u16;
    dbg_assert!((new_cs & 3) == *cpl as i32);

    update_cs_size(cs_descriptor.is_32());

    *segment_limits.offset(CS as isize) = cs_descriptor.effective_limit();
    *segment_offsets.offset(CS as isize) = cs_descriptor.base();
    *segment_access_bytes.offset(CS as isize) = cs_descriptor.access_byte();

    *instruction_pointer = new_eip + get_seg_cs();

    update_state_flags();

    // iret end

    handle_irqs();
    completed
}

pub unsafe fn call_interrupt_vector(
    interrupt_nr: i32,
    is_software_int: bool,
    error_code: Option<i32>,
) {
    call_interrupt_vector_checked(interrupt_nr, is_software_int, error_code);
}

/// Reports whether the semantic body completed; delivered faults remain CPU-owned.
pub unsafe fn call_interrupt_vector_checked(
    interrupt_nr: i32,
    is_software_int: bool,
    error_code: Option<i32>,
) -> bool {
    crate::cpu::exceptions::interrupt(interrupt_nr, is_software_int, error_code)
}

fn stack_range_valid(
    start: u32,
    size: u32,
    limit: u32,
    expand_down: bool,
    wide_stack: bool,
) -> bool {
    let Some(last) = start.checked_add(size - 1)
    else {
        return false;
    };
    if expand_down {
        start > limit && last <= if wide_stack { u32::MAX } else { 0xFFFF }
    }
    else {
        last <= limit
    }
}

pub unsafe fn deliver_interrupt(
    interrupt_nr: i32,
    is_software_int: bool,
    error_code: Option<i32>,
) -> bool {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return match crate::x64::system::interrupt(
            interrupt_nr as u8,
            is_software_int,
            error_code.map(|c| c as u32),
        ) {
            Ok(()) => true,
            Err(fault) => {
                crate::x64::system::raise(fault);
                false
            },
        };
    }
    let mut completed = true;
    if *protected_mode {
        if vm86_mode() && *cr.offset(4) & CR4_VME != 0 {
            panic!("Unimplemented: VME");
        }

        if vm86_mode() && is_software_int && getiopl() < 3 {
            dbg_log!("call_interrupt_vector #GP. vm86 && software int && iopl < 3");
            dbg_trace();
            trigger_gp(0);
            return false;
        }

        if interrupt_nr << 3 | 7 > *idtr_size {
            dbg_log!("interrupt_nr={:x} idtr_size={:x}", interrupt_nr, *idtr_size);
            dbg_trace();
            trigger_gp(interrupt_nr << 3 | 2);
            return false;
        }

        let descriptor = InterruptDescriptor::of_u64(return_on_pagefault!(
            read_system((*idtr_offset).wrapping_add(interrupt_nr << 3), 8),
            false
        ));

        let mut offset = descriptor.offset();
        let selector = descriptor.selector() as i32;
        let dpl = descriptor.dpl();
        let gate_type = descriptor.gate_type();

        if is_software_int && dpl < *cpl {
            dbg_log!("#gp software interrupt ({:x}) and dpl < cpl", interrupt_nr);
            dbg_trace();
            trigger_gp(interrupt_nr << 3 | 2);
            return false;
        }

        if gate_type != InterruptDescriptor::TRAP_GATE
            && gate_type != InterruptDescriptor::INTERRUPT_GATE
            && gate_type != InterruptDescriptor::TASK_GATE
        {
            // invalid gate_type
            dbg_log!(
                "gate type invalid. gate_type=0b{:b} raw={:b}",
                gate_type,
                descriptor.raw
            );
            dbg_trace();
            trigger_gp(interrupt_nr << 3 | 2);
            return false;
        }

        if !descriptor.reserved_zeros_are_valid() {
            dbg_log!(
                "reserved 0s violated. gate_type=0b{:b} raw={:b}",
                gate_type,
                descriptor.raw
            );
            dbg_trace();
            trigger_gp(interrupt_nr << 3 | 2);
            return false;
        }

        if !descriptor.is_present() {
            // present bit not set
            dbg_log!("#np int descriptor not present, int={}", interrupt_nr);
            trigger_np(interrupt_nr << 3 | 2);
            return false;
        }

        if gate_type == InterruptDescriptor::TASK_GATE {
            // task gate
            dbg_log!(
                "interrupt to task gate: int={:x} sel={:x} dpl={}",
                interrupt_nr,
                selector,
                dpl
            );
            dbg_trace();
            return do_task_switch_checked(selector, error_code, TaskSwitchSource::CallOrInt);
        }

        let cs_segment_descriptor = match return_on_pagefault!(
            lookup_segment_selector(SegmentSelector::of_u16(selector as u16)),
            false
        ) {
            Ok((desc, _)) => desc,
            Err(SelectorNullOrInvalid::IsNull) => {
                dbg_log!("is null");
                trigger_gp(selector & !3);
                return false;
            },
            Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
                dbg_log!("is invalid");
                trigger_gp(selector & !3);
                return false;
            },
        };

        if cs_segment_descriptor.is_system()
            || !cs_segment_descriptor.is_executable()
            || cs_segment_descriptor.dpl() > *cpl
        {
            dbg_log!("not exec");
            trigger_gp(selector & !3);
            return false;
        }
        if !cs_segment_descriptor.is_present() {
            trigger_np(selector & !3);
            return false;
        }

        if offset as u32 > cs_segment_descriptor.effective_limit() {
            trigger_gp(0);
            return false;
        }

        let old_flags = get_eflags();

        if !cs_segment_descriptor.is_dc() && cs_segment_descriptor.dpl() < *cpl {
            // inter privilege level interrupt
            // interrupt from vm86 mode

            if old_flags & FLAG_VM != 0 && cs_segment_descriptor.dpl() != 0 {
                trigger_gp(selector & !3);
                return false;
            }

            let (new_ss, new_esp) =
                return_on_pagefault!(get_tss_ss_esp(cs_segment_descriptor.dpl()), false);

            let ss_segment_selector = SegmentSelector::of_u16(new_ss as u16);
            let ss_segment_descriptor =
                match return_on_pagefault!(lookup_segment_selector(ss_segment_selector), false) {
                    Ok((desc, _)) => desc,
                    Err(
                        SelectorNullOrInvalid::IsNull | SelectorNullOrInvalid::OutsideOfTableLimit,
                    ) => {
                        trigger_ts(new_ss & !3);
                        return false;
                    },
                };

            if ss_segment_descriptor.is_system() || !ss_segment_descriptor.is_writable() {
                trigger_ts(new_ss & !3);
                return false;
            }

            if ss_segment_selector.rpl() != cs_segment_descriptor.dpl() {
                trigger_ts(new_ss & !3);
                return false;
            }
            if ss_segment_descriptor.dpl() != cs_segment_descriptor.dpl()
                || !ss_segment_descriptor.is_rw()
            {
                trigger_ts(new_ss & !3);
                return false;
            }
            if !ss_segment_descriptor.is_present() {
                trigger_ss(new_ss & !3);
                return false;
            }

            let old_esp = read_reg32(ESP);
            let old_ss = *sreg.offset(SS as isize) as i32;

            let error_code_space = if error_code.is_some() { 1 } else { 0 };
            let vm86_space = if (old_flags & FLAG_VM) == FLAG_VM { 4 } else { 0 };
            let bytes_per_arg = if descriptor.is_32() { 4 } else { 2 };

            let stack_space = bytes_per_arg * (5 + error_code_space + vm86_space);
            let stack_offset = (new_esp as u32).wrapping_sub(stack_space as u32)
                & if ss_segment_descriptor.is_32() { u32::MAX } else { 0xFFFF };
            if !stack_range_valid(
                stack_offset,
                stack_space as u32,
                ss_segment_descriptor.effective_limit(),
                ss_segment_descriptor.is_dc(),
                ss_segment_descriptor.is_32(),
            ) {
                trigger_ss(new_ss & !3);
                return false;
            }
            let new_stack_pointer = ss_segment_descriptor.base()
                + if ss_segment_descriptor.is_32() {
                    new_esp - stack_space
                }
                else {
                    new_esp - stack_space & 0xFFFF
                };

            return_on_pagefault!(translate_address_system_write(new_stack_pointer), false);
            return_on_pagefault!(
                translate_address_system_write(ss_segment_descriptor.base() + new_esp - 1),
                false
            );

            // no exceptions below
            *cpl = cs_segment_descriptor.dpl();
            cpl_changed();

            update_cs_size(cs_segment_descriptor.is_32());

            *flags &= !FLAG_VM & !FLAG_RF;

            if !switch_seg(SS, new_ss) {
                // XXX
                dbg_assert!(false);
                completed = false;
            }
            set_stack_reg(new_esp);

            // XXX: #SS if stack would cross stack limit

            if old_flags & FLAG_VM != 0 {
                if !descriptor.is_32() {
                    dbg_assert!(false);
                }
                else {
                    push32(*sreg.offset(GS as isize) as i32).unwrap();
                    push32(*sreg.offset(FS as isize) as i32).unwrap();
                    push32(*sreg.offset(DS as isize) as i32).unwrap();
                    push32(*sreg.offset(ES as isize) as i32).unwrap();
                }
            }

            if descriptor.is_32() {
                push32(old_ss).unwrap();
                push32(old_esp).unwrap();
            }
            else {
                push16(old_ss).unwrap();
                push16(old_esp & 0xFFFF).unwrap();
            }
        }
        else if cs_segment_descriptor.is_dc() || cs_segment_descriptor.dpl() == *cpl {
            // intra privilege level interrupt

            //dbg_log!("Intra privilege interrupt gate=" + h(selector, 4) + ":" + h(offset >>> 0, 8) +
            //        " gate_type=" + gate_type + " 16bit=" + descriptor.is_32() +
            //        " cpl=" + *cpl + " dpl=" + segment_descriptor.dpl() + " conforming=" + +segment_descriptor.is_dc(), );
            //debug.dump_regs_short();

            if *flags & FLAG_VM != 0 {
                dbg_assert!(false, "check error code");
                trigger_gp(selector & !3);
                return false;
            }

            let bytes_per_arg = if descriptor.is_32() { 4 } else { 2 };
            let error_code_space = if error_code.is_some() { 1 } else { 0 };

            let stack_space = bytes_per_arg * (3 + error_code_space);

            let stack_offset = (get_stack_pointer(-stack_space) as u32)
                .wrapping_sub(*segment_offsets.offset(SS as isize) as u32);
            if !stack_range_valid(
                stack_offset,
                stack_space as u32,
                *segment_limits.offset(SS as isize),
                *segment_access_bytes.offset(SS as isize) & 4 != 0,
                *stack_size_32,
            ) {
                trigger_ss(0);
                return false;
            }
            return_on_pagefault!(
                writable_or_pagefault(get_stack_pointer(-stack_space), stack_space),
                false
            );

        // no exceptions below
        }
        else {
            trigger_gp(selector & !3);
            return false;
        }

        // XXX: #SS if stack would cross stack limit
        if descriptor.is_32() {
            push32(old_flags).unwrap();
            push32(*sreg.offset(CS as isize) as i32).unwrap();
            push32(get_real_eip()).unwrap();

            if let Some(ec) = error_code {
                push32(ec).unwrap();
            }
        }
        else {
            push16(old_flags & 0xFFFF).unwrap();
            push16(*sreg.offset(CS as isize) as i32).unwrap();
            push16(get_real_eip() & 0xFFFF).unwrap();

            if let Some(ec) = error_code {
                dbg_assert!(ec >= 0 && ec < 0x10000);
                push16(ec).unwrap();
            }

            offset &= 0xFFFF;
        }

        if old_flags & FLAG_VM != 0 {
            if !switch_seg(GS, 0) || !switch_seg(FS, 0) || !switch_seg(DS, 0) || !switch_seg(ES, 0)
            {
                // can't fail
                dbg_assert!(false);
                completed = false;
            }
        }

        *sreg.offset(CS as isize) = (selector as u16) & !3 | *cpl as u16;
        dbg_assert!((*sreg.offset(CS as isize) & 3) == *cpl as u16);

        update_cs_size(cs_segment_descriptor.is_32());

        *segment_limits.offset(CS as isize) = cs_segment_descriptor.effective_limit();
        *segment_offsets.offset(CS as isize) = cs_segment_descriptor.base();
        *segment_access_bytes.offset(CS as isize) = cs_segment_descriptor.access_byte();

        *instruction_pointer = get_seg_cs() + offset;

        *flags &= !FLAG_NT & !FLAG_VM & !FLAG_RF & !FLAG_TRAP;

        if gate_type == InterruptDescriptor::INTERRUPT_GATE {
            // clear int flag for interrupt gates
            *flags &= !FLAG_INTERRUPT;
        }
        else {
            if *flags & FLAG_INTERRUPT != 0 && old_flags & FLAG_INTERRUPT == 0 {
                handle_irqs();
            }
        }

        update_state_flags();
    }
    else {
        // call 4 byte cs:ip interrupt vector from ivt at cpu.memory 0

        let index = (interrupt_nr << 2) as u32;
        let new_ip = memory::read16(index);
        let new_cs = memory::read16(index + 2);

        dbg_assert!(
            index | 3 <= IVT_SIZE,
            "Unimplemented: #GP for interrupt number out of IVT bounds"
        );

        // XXX: #SS if stack would cross stack limit

        // push flags, cs:ip
        push16(get_eflags() & 0xFFFF).unwrap();
        push16(*sreg.offset(CS as isize) as i32).unwrap();
        push16(get_real_eip() & 0xFFFF).unwrap();

        *flags &= !FLAG_INTERRUPT & !FLAG_AC & !FLAG_TRAP;

        switch_cs_real_mode(new_cs);
        *instruction_pointer = get_seg_cs() + new_ip;
        update_state_flags();
    }
    completed
}

pub unsafe fn far_jump(eip: i32, selector: i32, is_call: bool, is_osize_32: bool) {
    far_jump_checked(eip, selector, is_call, is_osize_32);
}

/// Reports whether the semantic body completed; delivered faults remain CPU-owned.
pub unsafe fn far_jump_checked(eip: i32, selector: i32, is_call: bool, is_osize_32: bool) -> bool {
    let mut completed = true;
    dbg_assert!(selector < 0x10000 && selector >= 0);

    if !*protected_mode || vm86_mode() {
        if is_call {
            if is_osize_32 {
                return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-8), 8), false);

                push32(*sreg.offset(CS as isize) as i32).unwrap();
                push32(get_real_eip()).unwrap();
            }
            else {
                return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-4), 4), false);

                push16(*sreg.offset(CS as isize) as i32).unwrap();
                push16(get_real_eip()).unwrap();
            }
        }
        switch_cs_real_mode(selector);
        *instruction_pointer = get_seg_cs() + eip;
        update_state_flags();
        return completed;
    }

    let cs_selector = SegmentSelector::of_u16(selector as u16);
    let info = match return_on_pagefault!(lookup_segment_selector(cs_selector), false) {
        Ok((desc, _)) => desc,
        Err(SelectorNullOrInvalid::IsNull) => {
            dbg_log!("#gp null cs");
            trigger_gp(0);
            return false;
        },
        Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
            dbg_log!("#gp invalid cs: {:x}", selector);
            trigger_gp(selector & !3);
            return false;
        },
    };

    if info.is_system() {
        dbg_log!("system type cs: {:x}", selector);

        if info.system_type() == 0xC || info.system_type() == 4 {
            // call gate
            dbg_assert!(is_call, "TODO: Jump through call gate");

            let is_16 = info.system_type() == 4;

            if info.dpl() < *cpl || info.dpl() < cs_selector.rpl() {
                dbg_log!("#gp cs gate dpl < cpl or dpl < rpl: {:x}", selector);
                trigger_gp(selector & !3);
                return false;
            }

            if !info.is_present() {
                dbg_log!("#NP for loading not-present in gate cs sel={:x}", selector);
                trigger_np(selector & !3);
                return false;
            }

            let cs_selector = (info.raw >> 16) as i32;

            let cs_info = match return_on_pagefault!(
                lookup_segment_selector(SegmentSelector::of_u16(cs_selector as u16)),
                false
            ) {
                Ok((desc, _)) => desc,
                Err(SelectorNullOrInvalid::IsNull) => {
                    dbg_log!("#gp null cs");
                    trigger_gp(0);
                    return false;
                },
                Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
                    dbg_log!("#gp invalid cs: {:x}", cs_selector);
                    trigger_gp(cs_selector & !3);
                    return false;
                },
            };

            if cs_info.is_system() {
                dbg_log!("#gp non-code cs: {:x}", cs_selector);
                trigger_gp(cs_selector & !3);
                return false;
            }

            if !cs_info.is_executable() {
                dbg_log!("#gp non-executable cs: {:x}", cs_selector);
                trigger_gp(cs_selector & !3);
                return false;
            }

            if cs_info.dpl() > *cpl {
                dbg_log!("#gp dpl > cpl: {:x}", cs_selector);
                trigger_gp(cs_selector & !3);
                return false;
            }

            if !cs_info.is_present() {
                dbg_log!("#NP for loading not-present in cs sel={:x}", cs_selector);
                trigger_np(cs_selector & !3);
                return false;
            }

            if !cs_info.is_dc() && cs_info.dpl() < *cpl {
                dbg_log!(
                    "more privilege call gate is_16={} from={} to={}",
                    is_16,
                    *cpl,
                    cs_info.dpl()
                );
                let (new_ss, new_esp) = return_on_pagefault!(get_tss_ss_esp(cs_info.dpl()), false);

                let ss_selector = SegmentSelector::of_u16(new_ss as u16);
                let ss_info =
                    match return_on_pagefault!(lookup_segment_selector(ss_selector), false) {
                        Ok((desc, _)) => desc,
                        Err(SelectorNullOrInvalid::IsNull) => {
                            panic!("null ss: {}", new_ss);
                        },
                        Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
                            panic!("invalid ss: {}", new_ss);
                        },
                    };

                if ss_info.is_dc() {
                    dbg_assert!(new_esp as u32 > ss_info.effective_limit());
                }
                else {
                    dbg_assert!(new_esp as u32 - 1 <= ss_info.effective_limit());
                }
                dbg_assert!(!ss_info.is_system() && ss_info.is_writable());

                if ss_selector.rpl() != cs_info.dpl()
                // xxx: 0 in v86 mode
                {
                    panic!("#TS handler");
                }
                if ss_info.dpl() != cs_info.dpl() || !ss_info.is_writable() {
                    panic!("#TS handler");
                }
                if !ss_info.is_present() {
                    panic!("#SS handler");
                }

                let parameter_count = (info.raw >> 32 & 0x1F) as i32;
                let mut stack_space = if is_16 { 4 } else { 8 };
                if is_call {
                    stack_space +=
                        if is_16 { 4 + 2 * parameter_count } else { 8 + 4 * parameter_count };
                }
                if ss_info.is_32() {
                    return_on_pagefault!(
                        writable_or_pagefault_cpl(
                            cs_info.dpl(),
                            ss_info.base() + new_esp - stack_space,
                            stack_space
                        ),
                        false
                    );
                }
                else {
                    return_on_pagefault!(
                        writable_or_pagefault_cpl(
                            cs_info.dpl(),
                            ss_info.base() + (new_esp - stack_space & 0xFFFF),
                            stack_space
                        ),
                        false
                    );
                }

                let old_esp = read_reg32(ESP);
                let old_ss = *sreg.offset(SS as isize);
                let old_stack_pointer = get_stack_pointer(0);

                //dbg_log!("old_esp=" + h(old_esp));

                *cpl = cs_info.dpl();
                cpl_changed();

                update_cs_size(cs_info.is_32());

                dbg_assert!(new_ss & 3 == cs_info.dpl() as i32);
                // XXX: Should be checked before side effects
                if !switch_seg(SS, new_ss) {
                    dbg_assert!(false);
                    completed = false;
                };
                set_stack_reg(new_esp);

                //dbg_log!("parameter_count=" + parameter_count);
                //dbg_assert!(parameter_count == 0, "TODO");

                if is_16 {
                    push16(old_ss as i32).unwrap();
                    push16(old_esp).unwrap();
                }
                else {
                    push32(old_ss as i32).unwrap();
                    push32(old_esp).unwrap();
                }

                if is_call {
                    if is_16 {
                        for i in (0..parameter_count).rev() {
                            let parameter = safe_read16(old_stack_pointer + 2 * i).unwrap();
                            push16(parameter).unwrap();
                        }

                        //writable_or_pagefault(get_stack_pointer(-4), 4);
                        push16(*sreg.offset(CS as isize) as i32).unwrap();
                        push16(get_real_eip()).unwrap();
                    }
                    else {
                        for i in (0..parameter_count).rev() {
                            let parameter = safe_read32s(old_stack_pointer + 4 * i).unwrap();
                            push32(parameter).unwrap();
                        }

                        //writable_or_pagefault(get_stack_pointer(-8), 8);
                        push32(*sreg.offset(CS as isize) as i32).unwrap();
                        push32(get_real_eip()).unwrap();
                    }
                }
            }
            else {
                dbg_log!(
                    "same privilege call gate is_16={} from={} to={} conforming={}",
                    is_16,
                    *cpl,
                    cs_info.dpl(),
                    cs_info.is_dc()
                );

                if is_call {
                    if is_16 {
                        return_on_pagefault!(
                            writable_or_pagefault(get_stack_pointer(-4), 4),
                            false
                        );

                        push16(*sreg.offset(CS as isize) as i32).unwrap();
                        push16(get_real_eip()).unwrap();
                    }
                    else {
                        return_on_pagefault!(
                            writable_or_pagefault(get_stack_pointer(-8), 8),
                            false
                        );

                        push32(*sreg.offset(CS as isize) as i32).unwrap();
                        push32(get_real_eip()).unwrap();
                    }
                }

                dbg_assert!(*cpl == cs_info.dpl());
            }

            // Note: eip from call is ignored
            let mut new_eip = (info.raw & 0xFFFF) as i32;
            if !is_16 {
                new_eip |= ((info.raw >> 32) & 0xFFFF0000) as i32;
            }

            dbg_log!(
                "call gate eip={:x} cs={:x} conforming={}",
                new_eip as u32,
                cs_selector,
                cs_info.is_dc()
            );
            dbg_assert!((new_eip as u32) <= cs_info.effective_limit(), "todo: #gp");

            update_cs_size(cs_info.is_32());

            *segment_is_null.offset(CS as isize) = false;
            *segment_limits.offset(CS as isize) = cs_info.effective_limit();
            *segment_offsets.offset(CS as isize) = cs_info.base();
            *segment_access_bytes.offset(CS as isize) = cs_info.access_byte();
            *sreg.offset(CS as isize) = cs_selector as u16 & !3 | *cpl as u16;
            dbg_assert!(*sreg.offset(CS as isize) & 3 == *cpl as u16);

            *instruction_pointer = get_seg_cs() + new_eip;

            update_state_flags();
        }
        else if info.system_type() == 1 || info.system_type() == 9 {
            // available tss
            if info.dpl() < *cpl || info.dpl() < cs_selector.rpl() {
                dbg_log!("#gp tss dpl < cpl or dpl < rpl: {:x}", selector);
                trigger_gp(selector & !3);
                return false;
            }

            if !info.is_present() {
                dbg_log!("#NP for loading not-present tss sel={:x}", selector);
                trigger_np(selector & !3);
                return false;
            }

            completed &= do_task_switch_checked(
                selector,
                None,
                if is_call { TaskSwitchSource::CallOrInt } else { TaskSwitchSource::Jump },
            );
        }
        else if info.system_type() == 5 {
            // task gate
            if info.dpl() < *cpl || info.dpl() < cs_selector.rpl() {
                dbg_log!("#gp task gate dpl < cpl or dpl < rpl: {:x}", selector);
                trigger_gp(selector & !3);
                return false;
            }

            if !info.is_present() {
                dbg_log!("#NP for loading not-present task gate sel={:x}", selector);
                trigger_np(selector & !3);
                return false;
            }

            let tss_selector = (info.raw >> 16) as i32 & 0xFFFF;
            completed &= do_task_switch_checked(
                tss_selector,
                None,
                if is_call { TaskSwitchSource::CallOrInt } else { TaskSwitchSource::Jump },
            );
        }
        else {
            // busy TSS, LDT, interrupt/trap gates, reserved types
            dbg_log!(
                "#gp far transfer to system type {:x}: {:x}",
                info.system_type(),
                selector
            );
            trigger_gp(selector & !3);
            return false;
        }
    }
    else {
        if !info.is_executable() {
            dbg_log!("#gp non-executable cs: {:x}", selector);
            trigger_gp(selector & !3);
            return false;
        }

        if info.is_dc() {
            // conforming code segment
            if info.dpl() > *cpl {
                dbg_log!("#gp cs dpl > cpl: {:x}", selector);
                trigger_gp(selector & !3);
                return false;
            }
        }
        else {
            // non-conforming code segment

            if cs_selector.rpl() > *cpl || info.dpl() != *cpl {
                dbg_log!("#gp cs rpl > cpl or dpl != cpl: {:x}", selector);
                trigger_gp(selector & !3);
                return false;
            }
        }

        if !info.is_present() {
            dbg_log!("#NP for loading not-present in cs sel={:x}", selector);
            dbg_trace();
            trigger_np(selector & !3);
            return false;
        }

        if is_call {
            if is_osize_32 {
                return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-8), 8), false);

                push32(*sreg.offset(CS as isize) as i32).unwrap();
                push32(get_real_eip()).unwrap();
            }
            else {
                return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-4), 4), false);

                push16(*sreg.offset(CS as isize) as i32).unwrap();
                push16(get_real_eip()).unwrap();
            }
        }

        let long =
            crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 && info.flags() & 2 != 0;
        if long && info.is_32() || !long && eip as u32 > info.effective_limit() {
            trigger_gp(0);
            return false;
        }
        *x64_cs_long = long as u8;
        *x64_rip_hi = 0;
        update_cs_size(info.is_32());

        *segment_is_null.offset(CS as isize) = false;
        *segment_limits.offset(CS as isize) = info.effective_limit();
        *segment_access_bytes.offset(CS as isize) = info.access_byte();

        *segment_offsets.offset(CS as isize) = if long { 0 } else { info.base() };
        *sreg.offset(CS as isize) = selector as u16 & !3 | *cpl as u16;

        *instruction_pointer = get_seg_cs() + eip;

        update_state_flags();
    }
    completed
}

pub unsafe fn far_return(eip: i32, selector: i32, stack_adjust: i32, is_osize_32: bool) {
    far_return_checked(eip, selector, stack_adjust, is_osize_32);
}

/// Reports whether the semantic body completed; delivered faults remain CPU-owned.
pub unsafe fn far_return_checked(
    eip: i32,
    selector: i32,
    stack_adjust: i32,
    is_osize_32: bool,
) -> bool {
    let mut completed = true;
    dbg_assert!(selector < 0x10000 && selector >= 0);

    if !*protected_mode {
        dbg_assert!(!*is_32);
    }

    if !*protected_mode || vm86_mode() {
        switch_cs_real_mode(selector);
        *instruction_pointer = get_seg_cs() + eip;
        adjust_stack_reg(2 * (if is_osize_32 { 4 } else { 2 }) + stack_adjust);
        update_state_flags();
        return completed;
    }

    let cs_selector = SegmentSelector::of_u16(selector as u16);
    let info = match return_on_pagefault!(lookup_segment_selector(cs_selector), false) {
        Ok((desc, _)) => desc,
        Err(SelectorNullOrInvalid::IsNull) => {
            dbg_log!("far return: #gp null cs");
            trigger_gp(0);
            return false;
        },
        Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
            dbg_log!("far return: #gp invalid cs: {:x}", selector);
            trigger_gp(selector & !3);
            return false;
        },
    };

    if info.is_system() {
        trigger_gp(selector & !3);
        return false;
    }

    if !info.is_executable() {
        dbg_log!("non-executable cs: {:x}", selector);
        trigger_gp(selector & !3);
        return false;
    }

    if cs_selector.rpl() < *cpl {
        dbg_log!("cs rpl < cpl: {:x}", selector);
        trigger_gp(selector & !3);
        return false;
    }

    if info.is_dc() && info.dpl() > cs_selector.rpl() {
        dbg_log!("cs conforming and dpl > rpl: {:x}", selector);
        trigger_gp(selector & !3);
        return false;
    }

    if !info.is_dc() && info.dpl() != cs_selector.rpl() {
        dbg_log!("cs non-conforming and dpl != rpl: {:x}", selector);
        trigger_gp(selector & !3);
        return false;
    }

    if !info.is_present() {
        dbg_log!("#NP for loading not-present in cs sel={:x}", selector);
        dbg_trace();
        trigger_np(selector & !3);
        return false;
    }

    let long =
        crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 && info.flags() & 2 != 0;
    if long && info.is_32() || !long && eip as u32 > info.effective_limit() {
        trigger_gp(0);
        return false;
    }

    if cs_selector.rpl() > *cpl {
        dbg_log!(
            "far return privilege change cs: {:x} from={} to={} is_16={}",
            selector,
            *cpl,
            cs_selector.rpl(),
            is_osize_32
        );

        let temp_esp;
        let temp_ss;
        if is_osize_32 {
            //dbg_log!("esp read from " + h(translate_address_system_read(get_stack_pointer(stack_adjust + 8))))
            temp_esp = safe_read32s(get_stack_pointer(stack_adjust + 8)).unwrap();
            //dbg_log!("esp=" + h(temp_esp));
            temp_ss = safe_read16(get_stack_pointer(stack_adjust + 12)).unwrap();
        }
        else {
            //dbg_log!("esp read from " + h(translate_address_system_read(get_stack_pointer(stack_adjust + 4))));
            temp_esp = safe_read16(get_stack_pointer(stack_adjust + 4)).unwrap();
            //dbg_log!("esp=" + h(temp_esp));
            temp_ss = safe_read16(get_stack_pointer(stack_adjust + 6)).unwrap();
        }

        *cpl = cs_selector.rpl();
        cpl_changed();

        // XXX: This failure should be checked before side effects
        if !switch_seg(SS, temp_ss) {
            dbg_assert!(false);
            completed = false;
        }
        set_stack_reg(temp_esp + stack_adjust);

        //if(is_osize_32)
        //{
        //    adjust_stack_reg(2 * 4);
        //}
        //else
        //{
        //    adjust_stack_reg(2 * 2);
        //}

        //throw debug.unimpl("privilege change");

        //adjust_stack_reg(stack_adjust);

        for reg in [ES, DS, FS, GS] {
            let access = *segment_access_bytes.offset(reg as isize);
            let dpl = access >> 5 & 3;
            let executable = access & 8 == 8;
            let conforming = access & 4 == 4;
            if dpl < *cpl && !(executable && conforming) {
                *segment_is_null.offset(reg as isize) = true;
                *sreg.offset(reg as isize) = 0;
            }
        }
    }
    else {
        if is_osize_32 {
            adjust_stack_reg(2 * 4 + stack_adjust);
        }
        else {
            adjust_stack_reg(2 * 2 + stack_adjust);
        }
    }

    //dbg_assert(*cpl == info.dpl);

    *x64_cs_long = long as u8;
    *x64_rip_hi = 0;
    update_cs_size(info.is_32());

    *segment_is_null.offset(CS as isize) = false;
    *segment_limits.offset(CS as isize) = info.effective_limit();
    *segment_access_bytes.offset(CS as isize) = info.access_byte();

    *segment_offsets.offset(CS as isize) = if long { 0 } else { info.base() };
    *sreg.offset(CS as isize) = selector as u16;
    dbg_assert!(selector & 3 == *cpl as i32);

    *instruction_pointer = get_seg_cs() + eip;

    update_state_flags();
    completed
}

#[derive(Copy, Clone, PartialEq)]
pub enum TaskSwitchSource {
    Jump,
    CallOrInt,
    Iret,
}

pub unsafe fn do_task_switch(selector: i32, error_code: Option<i32>, source: TaskSwitchSource) {
    do_task_switch_checked(selector, error_code, source);
}

/// Reports whether the semantic body completed; delivered faults remain CPU-owned.
///
/// SDM Vol.3A §7.3: every check, and every read of the new TSS, happens
/// before the first state change, so a failure there faults in the old task
/// (#TS/#NP/#GP with the TSS selector, or #PF) with nothing modified. After
/// the commit point (old state saved, TR and CR3 switched) a bad LDT or CS
/// selector faults in the context of the new task.
pub unsafe fn do_task_switch_checked(
    selector: i32,
    error_code: Option<i32>,
    source: TaskSwitchSource,
) -> bool {
    dbg_log!("do_task_switch sel={:x}", selector);

    let selector = SegmentSelector::of_u16(selector as u16);
    let error = selector.raw as i32 & !3;
    let (descriptor, descriptor_address) =
        match return_on_pagefault!(lookup_segment_selector(selector), false) {
            Ok(desc) => desc,
            Err(_) => {
                if source == TaskSwitchSource::Iret {
                    trigger_ts(error);
                }
                else {
                    trigger_gp(error);
                }
                return false;
            },
        };

    let tss_type = descriptor.system_type();
    if !selector.is_gdt() || !descriptor.is_system() || !matches!(tss_type, 1 | 3 | 9 | 11) {
        if source == TaskSwitchSource::Iret {
            trigger_ts(error);
        }
        else {
            trigger_gp(error);
        }
        return false;
    }
    let tss_is_16 = tss_type <= 3;
    let tss_is_busy = (tss_type & 2) == 2;

    if source == TaskSwitchSource::Iret {
        if !tss_is_busy {
            // a task return must target a busy task
            trigger_ts(error);
            return false;
        }
    }
    else if tss_is_busy {
        // jump, call or int to a busy task
        trigger_gp(error);
        return false;
    }

    if !descriptor.is_present() {
        trigger_np(error);
        return false;
    }

    if descriptor.effective_limit() < if tss_is_16 { 43 } else { 103 } {
        trigger_ts(error);
        return false;
    }
    if tss_is_16 {
        // 16-bit TSSs (80286 tasks) are not implemented; fail the guest, not the host
        dbg_log!("task switch to a 16-bit TSS: #TS");
        trigger_ts(error);
        return false;
    }

    let tsr_offset = *segment_offsets.offset(TR as isize);
    let new_tsr_offset = descriptor.base();

    let mut old_eflags = get_eflags();
    if tss_is_busy {
        old_eflags &= !FLAG_NT;
    }

    // Everything that can fault before the commit point
    return_on_pagefault!(writable_or_pagefault(tsr_offset, 0x66), false);
    if source == TaskSwitchSource::CallOrInt {
        return_on_pagefault!(
            writable_or_pagefault(new_tsr_offset + TSR_BACKLINK, 2),
            false
        );
    }
    let read32 = |offset| safe_read32s(new_tsr_offset + offset);
    let read16 = |offset| safe_read16(new_tsr_offset + offset);
    let new_cr3 = return_on_pagefault!(read32(TSR_CR3), false);
    let new_eip = return_on_pagefault!(read32(TSR_EIP), false);
    let mut new_eflags = return_on_pagefault!(read32(TSR_EFLAGS), false);
    let mut new_gpr = [0; 8];
    for (i, offset) in [
        TSR_EAX, TSR_ECX, TSR_EDX, TSR_EBX, TSR_ESP, TSR_EBP, TSR_ESI, TSR_EDI,
    ]
    .iter()
    .enumerate()
    {
        new_gpr[i] = return_on_pagefault!(read32(*offset), false);
    }
    let new_cs = return_on_pagefault!(read16(TSR_CS), false);
    let mut new_segments = [0; 4];
    for (i, offset) in [TSR_ES, TSR_SS, TSR_DS, TSR_FS].iter().enumerate() {
        new_segments[i] = return_on_pagefault!(read16(*offset), false);
    }
    let new_gs = return_on_pagefault!(read16(TSR_GS), false);
    let new_ldt = return_on_pagefault!(read16(TSR_LDT), false);

    // Commit: save the old task
    let saved = [
        (TSR_EIP, get_real_eip()),
        (TSR_EFLAGS, old_eflags),
        (TSR_EAX, read_reg32(EAX)),
        (TSR_ECX, read_reg32(ECX)),
        (TSR_EDX, read_reg32(EDX)),
        (TSR_EBX, read_reg32(EBX)),
        (TSR_ESP, read_reg32(ESP)),
        (TSR_EBP, read_reg32(EBP)),
        (TSR_ESI, read_reg32(ESI)),
        (TSR_EDI, read_reg32(EDI)),
        (TSR_ES, *sreg.offset(ES as isize) as i32),
        (TSR_CS, *sreg.offset(CS as isize) as i32),
        (TSR_SS, *sreg.offset(SS as isize) as i32),
        (TSR_DS, *sreg.offset(DS as isize) as i32),
        (TSR_FS, *sreg.offset(FS as isize) as i32),
        (TSR_GS, *sreg.offset(GS as isize) as i32),
    ];
    for (offset, value) in saved {
        return_on_pagefault!(safe_write32(tsr_offset + offset, value), false);
    }

    if source == TaskSwitchSource::Jump || source == TaskSwitchSource::Iret {
        // mark the old task as not busy
        let tr_selector = SegmentSelector::of_u16(*sreg.offset(TR as isize));
        if let Ok((tr_descriptor, tr_descriptor_address)) =
            return_on_pagefault!(lookup_segment_selector(tr_selector), false)
        {
            return_on_pagefault!(
                safe_write64(tr_descriptor_address as i32, tr_descriptor.clear_busy().raw),
                false
            );
        }
    }

    if source != TaskSwitchSource::Iret {
        // jump, call and int mark the new task as busy (iret would not)
        return_on_pagefault!(
            safe_write64(descriptor_address as i32, descriptor.set_busy().raw),
            false
        );
    }

    if source == TaskSwitchSource::CallOrInt {
        return_on_pagefault!(
            safe_write16(
                new_tsr_offset + TSR_BACKLINK,
                *sreg.offset(TR as isize) as i32
            ),
            false
        );
        new_eflags |= FLAG_NT;
    }

    // The new task: TR, CR3 and the general registers
    *segment_offsets.offset(TR as isize) = descriptor.base();
    *segment_limits.offset(TR as isize) = descriptor.effective_limit();
    *sreg.offset(TR as isize) = selector.raw;
    set_cr3(new_cr3);
    *cr.offset(0) |= CR0_TS;
    for (i, reg) in [EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI].iter().enumerate() {
        write_reg32(*reg, new_gpr[i]);
    }
    *flags &= !FLAG_VM;

    // Faults from here on are taken in the context of the new task
    if !return_on_pagefault!(load_ldt_checked(new_ldt, true), false) {
        return false;
    }

    let new_cpl;
    if new_eflags & FLAG_VM != 0 {
        *segment_is_null.offset(CS as isize) = false;
        *segment_offsets.offset(CS as isize) = new_cs << 4;
        *sreg.offset(CS as isize) = new_cs as u16;
        update_cs_size(false);
        new_cpl = 3;
    }
    else {
        let new_cs_selector = SegmentSelector::of_u16(new_cs as u16);
        let cs_error = new_cs & !3;
        let new_cs_descriptor =
            match return_on_pagefault!(lookup_segment_selector(new_cs_selector), false) {
                Ok((desc, _)) => desc,
                Err(_) => {
                    dbg_log!("task switch: invalid cs {:x}", new_cs);
                    trigger_ts(cs_error);
                    return false;
                },
            };
        if new_cs_descriptor.is_system()
            || !new_cs_descriptor.is_executable()
            || new_cs_descriptor.is_dc() && new_cs_descriptor.dpl() > new_cs_selector.rpl()
            || !new_cs_descriptor.is_dc() && new_cs_descriptor.dpl() != new_cs_selector.rpl()
        {
            trigger_ts(cs_error);
            return false;
        }
        if !new_cs_descriptor.is_present() {
            trigger_np(cs_error);
            return false;
        }

        *segment_is_null.offset(CS as isize) = false;
        *segment_limits.offset(CS as isize) = new_cs_descriptor.effective_limit();
        *segment_offsets.offset(CS as isize) = new_cs_descriptor.base();
        *segment_access_bytes.offset(CS as isize) = new_cs_descriptor.access_byte();
        *sreg.offset(CS as isize) = new_cs as u16;
        update_cs_size(new_cs_descriptor.is_32());

        new_cpl = new_cs_selector.rpl();
    }

    *cpl = 0; // run update_eflags at cpl 0
    update_eflags(new_eflags);
    if new_eflags & FLAG_VM != 0 {
        *flags |= FLAG_VM;
    }
    *cpl = new_cpl;
    cpl_changed();

    *instruction_pointer =
        get_seg_cs() + if new_eflags & FLAG_VM != 0 { new_eip & 0xFFFF } else { new_eip };

    if !switch_seg(ES, new_segments[0])
        || !switch_seg(SS, new_segments[1])
        || !switch_seg(DS, new_segments[2])
        || !switch_seg(FS, new_segments[3])
        || !switch_seg(GS, new_gs)
    {
        // (the fault was delivered in the new task)
        return false;
    }

    if !(new_cs_limit_ok(new_eip) || new_eflags & FLAG_VM != 0) {
        trigger_gp(0);
        return false;
    }

    if let Some(error_code) = error_code {
        return_on_pagefault!(push32(error_code), false);
    }

    update_state_flags();
    true
}

unsafe fn new_cs_limit_ok(eip: i32) -> bool { eip as u32 <= *segment_limits.offset(CS as isize) }

pub unsafe fn after_block_boundary() { jit_block_boundary = true; }

#[no_mangle]
pub unsafe fn get_eflags() -> i32 {
    return *flags & !FLAGS_ALL
        | getcf() as i32
        | (getpf() as i32) << 2
        | (getaf() as i32) << 4
        | (getzf() as i32) << 6
        | (getsf() as i32) << 7
        | (getof() as i32) << 11;
}

pub unsafe fn readable_or_pagefault(addr: i32, size: i32) -> OrPageFault<()> {
    dbg_assert!(size < 0x1000);
    dbg_assert!(size > 0);

    let user = *cpl == 3;
    translate_address(addr, false, user, true)?;

    let end = addr + size - 1 & !0xFFF;
    if addr & !0xFFF != end & !0xFFF {
        translate_address(end, false, user, true)?;
    }

    return Ok(());
}

pub unsafe fn writable_or_pagefault(addr: i32, size: i32) -> OrPageFault<()> {
    writable_or_pagefault_cpl(*cpl, addr, size)
}

pub unsafe fn writable_or_pagefault_cpl(other_cpl: u8, addr: i32, size: i32) -> OrPageFault<()> {
    dbg_assert!(size < 0x1000);
    dbg_assert!(size > 0);

    let user = other_cpl == 3;
    translate_address(addr, true, user, true)?;

    let end = addr + size - 1 & !0xFFF;
    if addr & !0xFFF != end & !0xFFF {
        translate_address(end, true, user, true)?;
    }

    return Ok(());
}

pub fn translate_address_read_no_side_effects(address: i32) -> OrPageFault<u32> {
    unsafe { translate_address(address, false, *cpl == 3, false) }
}
pub fn translate_address_read(address: i32) -> OrPageFault<u32> {
    unsafe { translate_address(address, false, *cpl == 3, true) }
}

pub unsafe fn translate_address_write(address: i32) -> OrPageFault<u32> {
    translate_address(address, true, *cpl == 3, true)
}
pub unsafe fn translate_address_system_read(address: i32) -> OrPageFault<u32> {
    translate_address(address, false, false, true)
}
pub unsafe fn translate_address_system_write(address: i32) -> OrPageFault<u32> {
    translate_address(address, true, false, true)
}

#[inline(always)]
pub unsafe fn translate_address(
    address: i32,
    for_writing: bool,
    user: bool,
    side_effects: bool,
) -> OrPageFault<u32> {
    let mut entry = tlb_data[(address as u32 >> 12) as usize];
    let refused = entry
        & (TLB_VALID
            | if user { TLB_NO_USER } else { 0 }
            | if for_writing { TLB_READONLY } else { 0 })
        != TLB_VALID;
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // compatibility mode: the 32-bit TLB holds x64 translations of 32-bit
        // linear addresses (fill_ia32e_tlb; data-only entries are good for
        // data); 64-bit code never uses it
        if refused || *x64_cs_long != 0 {
            return ia32e_translate(address, for_writing, user, side_effects);
        }
        return Ok(((entry & !0xFFF ^ address) as u32).wrapping_sub(memory::mem8 as u32));
    }
    if refused {
        entry = do_page_walk(address, for_writing, user, side_effects)?.get();
    }
    Ok((entry & !0xFFF ^ address) as u32 - memory::mem8 as u32)
}

pub unsafe fn translate_address_write_and_can_skip_dirty(address: i32) -> OrPageFault<(u32, bool)> {
    let mut entry = tlb_data[(address as u32 >> 12) as usize];
    let user = *cpl == 3;
    let refused =
        entry & (TLB_VALID | if user { TLB_NO_USER } else { 0 } | TLB_READONLY) != TLB_VALID;
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode: as translate_address)
        if refused || *x64_cs_long != 0 {
            return ia32e_translate(address, true, user, true).map(|address| (address, false));
        }
    }
    else if refused {
        entry = do_page_walk(address, true, user, true)?.get();
    }
    Ok((
        (entry & !0xFFF ^ address) as u32 - memory::mem8 as u32,
        entry & TLB_HAS_CODE == 0,
    ))
}

// 32-bit paging:
// - 10 bits PD | 10 bits PT | 12 bits offset
// - 10 bits PD | 22 bits offset (4MB huge page)
//
// PAE paging:
// - 2 bits PDPT | 9 bits PD | 9 bits PT | 12 bits offset
// - 2 bits PDPT | 9 bits PD | 21 bits offset (2MB huge page)
//
// Note that PAE entries are 64-bit, and can describe physical addresses over 32
// bits. However, since we support only 32-bit physical addresses, we require
// the high half of the entry to be 0.
#[cold]
pub unsafe fn do_page_walk(
    addr: i32,
    for_writing: bool,
    user: bool,
    side_effects: bool,
) -> OrPageFault<std::num::NonZeroI32> {
    let global;
    let mut allow_user = true;
    let page = (addr as u32 >> 12) as i32;
    let high;

    let cr0 = *cr;
    let cr4 = *cr.offset(4);

    if cr0 & CR0_PG == 0 {
        // paging disabled
        high = addr as u32 & 0xFFFFF000;
        global = false
    }
    else {
        profiler::stat_increment(stat::TLB_MISS);

        let pae = cr4 & CR4_PAE != 0;

        let (page_dir_addr, page_dir_entry) = if pae {
            let pdpt_entry = *reg_pdpte.offset(((addr as u32) >> 30) as isize);
            if pdpt_entry as i32 & PAGE_TABLE_PRESENT_MASK == 0 {
                if side_effects {
                    trigger_pagefault(addr, false, for_writing, user);
                }
                return Err(());
            }

            let page_dir_addr =
                (pdpt_entry as u32 & 0xFFFFF000) + ((((addr as u32) >> 21) & 0x1FF) << 3);
            let page_dir_entry = memory::read64s(page_dir_addr);
            dbg_assert!(
                page_dir_entry as u64 & 0x7FFF_FFFF_0000_0000 == 0,
                "Unsupported: Page directory entry larger than 32 bits"
            );
            dbg_assert!(
                page_dir_entry & 0x8000_0000_0000_0000u64 as i64 == 0,
                "Unsupported: NX bit"
            );

            (page_dir_addr, page_dir_entry as i32)
        }
        else {
            let page_dir_addr = *cr.offset(3) as u32 + (((addr as u32) >> 22) << 2);
            let page_dir_entry = memory::read32s(page_dir_addr);
            (page_dir_addr, page_dir_entry)
        };

        if page_dir_entry & PAGE_TABLE_PRESENT_MASK == 0 {
            if side_effects {
                trigger_pagefault(addr, false, for_writing, user);
            }
            return Err(());
        }

        let kernel_write_override = !user && 0 == cr0 & CR0_WP;
        let mut allow_write = page_dir_entry & PAGE_TABLE_RW_MASK != 0;
        allow_user &= page_dir_entry & PAGE_TABLE_USER_MASK != 0;

        if 0 != page_dir_entry & PAGE_TABLE_PSE_MASK && 0 != cr4 & CR4_PSE {
            // size bit is set

            if for_writing && !allow_write && !kernel_write_override || user && !allow_user {
                if side_effects {
                    trigger_pagefault(addr, true, for_writing, user);
                }
                return Err(());
            }

            // set the accessed and dirty bits

            let new_page_dir_entry = page_dir_entry
                | PAGE_TABLE_ACCESSED_MASK
                | if for_writing { PAGE_TABLE_DIRTY_MASK } else { 0 };

            if side_effects && page_dir_entry != new_page_dir_entry {
                memory::set_page_entry_bits(
                    page_dir_addr,
                    (new_page_dir_entry ^ page_dir_entry) as u8,
                );
            }

            high = if pae {
                page_dir_entry as u32 & 0xFFE00000 | (addr & 0x1FF000) as u32
            }
            else {
                page_dir_entry as u32 & 0xFFC00000 | (addr & 0x3FF000) as u32
            };
            global = page_dir_entry & PAGE_TABLE_GLOBAL_MASK == PAGE_TABLE_GLOBAL_MASK
        }
        else {
            let (page_table_addr, page_table_entry) = if pae {
                let page_table_addr =
                    (page_dir_entry as u32 & 0xFFFFF000) + (((addr as u32 >> 12) & 0x1FF) << 3);
                let page_table_entry = memory::read64s(page_table_addr);
                dbg_assert!(
                    page_table_entry as u64 & 0x7FFF_FFFF_0000_0000 == 0,
                    "Unsupported: Page table entry larger than 32 bits"
                );
                dbg_assert!(
                    page_table_entry & 0x8000_0000_0000_0000u64 as i64 == 0,
                    "Unsupported: NX bit"
                );

                (page_table_addr, page_table_entry as i32)
            }
            else {
                let page_table_addr =
                    (page_dir_entry as u32 & 0xFFFFF000) + (((addr as u32 >> 12) & 0x3FF) << 2);
                let page_table_entry = memory::read32s(page_table_addr);
                (page_table_addr, page_table_entry)
            };

            let present = page_table_entry & PAGE_TABLE_PRESENT_MASK != 0;
            allow_write &= page_table_entry & PAGE_TABLE_RW_MASK != 0;
            allow_user &= page_table_entry & PAGE_TABLE_USER_MASK != 0;

            if !present
                || for_writing && !allow_write && !kernel_write_override
                || user && !allow_user
            {
                if side_effects {
                    trigger_pagefault(addr, present, for_writing, user);
                }
                return Err(());
            }

            // Set the accessed and dirty bits
            // Note: dirty bit is only set on the page table entry
            let new_page_dir_entry = page_dir_entry | PAGE_TABLE_ACCESSED_MASK;
            if side_effects && new_page_dir_entry != page_dir_entry {
                memory::set_page_entry_bits(
                    page_dir_addr,
                    (new_page_dir_entry ^ page_dir_entry) as u8,
                );
            }
            let new_page_table_entry = page_table_entry
                | PAGE_TABLE_ACCESSED_MASK
                | if for_writing { PAGE_TABLE_DIRTY_MASK } else { 0 };
            if side_effects && page_table_entry != new_page_table_entry {
                memory::set_page_entry_bits(
                    page_table_addr,
                    (new_page_table_entry ^ page_table_entry) as u8,
                );
            }

            high = page_table_entry as u32 & 0xFFFFF000;
            global = page_table_entry & PAGE_TABLE_GLOBAL_MASK == PAGE_TABLE_GLOBAL_MASK
        }
    }

    if side_effects && tlb_data[page as usize] == 0 {
        if valid_tlb_entries_count == VALID_TLB_ENTRY_MAX {
            profiler::stat_increment(stat::TLB_FULL);
            clear_tlb();
            // also clear global entries if tlb is almost full after clearing non-global pages
            if valid_tlb_entries_count > VALID_TLB_ENTRY_MAX * 3 / 4 {
                profiler::stat_increment(stat::TLB_GLOBAL_FULL);
                full_clear_tlb();
            }
        }
        dbg_assert!(valid_tlb_entries_count < VALID_TLB_ENTRY_MAX);
        valid_tlb_entries[valid_tlb_entries_count as usize] = page;
        valid_tlb_entries_count += 1;
    // TODO: Check that there are no duplicates in valid_tlb_entries
    // XXX: There will probably be duplicates due to invlpg deleting
    // entries from tlb_data but not from valid_tlb_entries
    }
    else if side_effects && CHECK_TLB_INVARIANTS {
        let mut found = false;
        for i in 0..valid_tlb_entries_count {
            if valid_tlb_entries[i as usize] == page {
                found = true;
                break;
            }
        }
        dbg_assert!(found);
    }

    let is_in_mapped_range = memory::in_mapped_range(high);
    let has_code = if side_effects {
        !is_in_mapped_range && jit::page_needs_notification(Page::page_of(high))
    }
    else {
        // If side_effects is false, don't call into jit::jit_page_has_code. This value is not used
        // anyway (we only get here by translate_address_read_no_side_effects, which only uses the
        // address part)
        true
    };
    let info_bits = TLB_VALID
        | if for_writing { 0 } else { TLB_READONLY }
        | if allow_user { 0 } else { TLB_NO_USER }
        | if is_in_mapped_range { TLB_IN_MAPPED_RANGE } else { 0 }
        | if global && 0 != cr4 & CR4_PGE { TLB_GLOBAL } else { 0 }
        | if has_code { TLB_HAS_CODE } else { 0 };

    let tlb_entry = (high + memory::mem8 as u32) as i32 ^ page << 12 | info_bits as i32;

    dbg_assert!((high ^ (page as u32) << 12) & 0xFFF == 0);
    if side_effects {
        // bake in the addition with memory::mem8 to save an instruction from the fast path
        // of memory accesses
        tlb_data[page as usize] = tlb_entry;
    }

    Ok(if DEBUG {
        std::num::NonZeroI32::new(tlb_entry).unwrap()
    }
    else {
        std::num::NonZeroI32::new_unchecked(tlb_entry)
    })
}

/// In compatibility mode, x64 translations of 32-bit linear addresses also
/// fill the 32-bit TLB, which compiled 32-bit code reads inline. Only plain
/// RAM is cached; every x64 TLB invalidation (CR3/CR0/CR4/EFER writes, INVLPG)
/// also clears this TLB.
pub unsafe fn fill_ia32e_tlb(
    address: u32,
    physical: u64,
    access: crate::x64::paging::Access,
    user: bool,
) {
    use crate::x64::paging::Access;
    crate::x64::pages::COUNTERS[crate::x64::pages::COUNT_COMPAT_FILLS] += 1;
    // (extended RAM: its frame while cores share this thread; never 32-bit
    // code, and never a write entry for a page with page-tier code, so no
    // code-write notification; see crate::x64::extended::cache_frame)
    let (backing, extended) = match crate::x64::jac::ram_backing(physical) {
        Some(backing) => (backing, false),
        None if access == Access::Execute => return,
        None => {
            match crate::x64::extended::cache_frame(physical & !4095, access == Access::Write) {
                Some(host) => {
                    crate::x64::extended::note_legacy_tlb();
                    (host.wrapping_sub(memory::mem8 as u32), true)
                },
                None => return,
            }
        },
    };
    let page = address >> 12;
    if tlb_data[page as usize] != 0 {
        crate::x64::pages::COUNTERS[crate::x64::pages::COUNT_COMPAT_REFILLS] += 1;
    }
    if tlb_data[page as usize] == 0 {
        if valid_tlb_entries_count == VALID_TLB_ENTRY_MAX {
            clear_tlb();
            if valid_tlb_entries_count > VALID_TLB_ENTRY_MAX * 3 / 4 {
                full_clear_tlb();
            }
        }
        valid_tlb_entries[valid_tlb_entries_count as usize] = page as i32;
        valid_tlb_entries_count += 1;
    }
    let has_code = !extended && jit::page_needs_notification(Page::page_of(backing));
    let info = TLB_VALID
        | if access == Access::Write { 0 } else { TLB_READONLY }
        | if user { 0 } else { TLB_NO_USER }
        | if access == Access::Execute { 0 } else { TLB_IA32E_DATA }
        | if has_code { TLB_HAS_CODE } else { 0 };
    tlb_data[page as usize] =
        backing.wrapping_add(memory::mem8 as u32) as i32 ^ (page << 12) as i32 | info;
}

#[no_mangle]
pub unsafe fn full_clear_tlb() {
    clear_all_tlb_entries();
    legacy_code_epoch();
}
/// The page tier's code translations of this core (code TLB, chaining
/// entries) carry its access cache epoch (x64 jac): a legacy-mode flush
/// starts a new one, as x64 invalidations do (docs/jit-unification-plan.md
/// P7.1; in long and compatibility mode the x64 paths flush it themselves)
unsafe fn legacy_code_epoch() {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA == 0 {
        crate::x64::jac::flush(crate::cpu::apic::current_core());
    }
}
/// full_clear_tlb without a new code epoch: the cooperative cores'
/// context switch reinstalls a core's own entries (P7.1)
pub unsafe fn clear_all_tlb_entries() {
    profiler::stat_increment(stat::FULL_CLEAR_TLB);
    // clear tlb including global pages
    *last_virt_eip = -1;
    for i in 0..valid_tlb_entries_count {
        let page = valid_tlb_entries[i as usize];
        tlb_data[page as usize] = 0;
    }
    valid_tlb_entries_count = 0;

    if CHECK_TLB_INVARIANTS {
        #[allow(static_mut_refs)]
        for &entry in tlb_data.iter() {
            dbg_assert!(entry == 0);
        }
    };
}

#[no_mangle]
pub unsafe fn clear_tlb() {
    profiler::stat_increment(stat::CLEAR_TLB);
    // clear tlb excluding global pages
    *last_virt_eip = -1;
    let mut global_page_offset = 0;
    for i in 0..valid_tlb_entries_count {
        let page = valid_tlb_entries[i as usize];
        let entry = tlb_data[page as usize];
        if 0 != entry & TLB_GLOBAL {
            // reinsert at the front
            valid_tlb_entries[global_page_offset as usize] = page;
            global_page_offset += 1;
        }
        else {
            tlb_data[page as usize] = 0;
        }
    }
    valid_tlb_entries_count = global_page_offset;

    if CHECK_TLB_INVARIANTS {
        #[allow(static_mut_refs)]
        for &entry in tlb_data.iter() {
            dbg_assert!(entry == 0 || 0 != entry & TLB_GLOBAL);
        }
    };
    legacy_code_epoch();
}

pub unsafe fn trigger_pagefault(addr: i32, present: bool, write: bool, user: bool) {
    crate::cpu::execution::mark_fault();
    if config::LOG_PAGE_FAULTS {
        dbg_log!(
            "page fault w={} u={} p={} eip={:x} cr2={:x}",
            write as i32,
            user as i32,
            present as i32,
            *previous_ip,
            addr
        );
        dbg_trace();
    }
    profiler::stat_increment(stat::PAGE_FAULT);
    *cr.offset(2) = addr;
    // invalidate tlb entry
    let page = ((addr as u32) >> 12) as i32;
    tlb_data[page as usize] = 0;
    let error_code = (user as i32) << 2 | (write as i32) << 1 | present as i32;
    *instruction_pointer = *previous_ip;
    crate::cpu::exceptions::fault(CPU_EXCEPTION_PF, Some(error_code));
}

pub fn tlb_set_has_code(physical_page: Page, has_code: bool) {
    for i in 0..unsafe { valid_tlb_entries_count } {
        let page = unsafe { valid_tlb_entries[i as usize] };
        let entry = unsafe { tlb_data[page as usize] };
        if 0 != entry {
            let tlb_physical_page = Page::of_u32(
                (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12),
            );
            if physical_page == tlb_physical_page {
                unsafe {
                    tlb_data[page as usize] =
                        if has_code { entry | TLB_HAS_CODE } else { entry & !TLB_HAS_CODE }
                }
            }
        }
    }

    check_tlb_invariants();
}
pub fn tlb_set_has_code_multiple(physical_pages: &HashSet<Page>, has_code: bool) {
    let physical_pages: Vec<Page> = physical_pages.into_iter().copied().collect();
    for i in 0..unsafe { valid_tlb_entries_count } {
        let page = unsafe { valid_tlb_entries[i as usize] };
        let entry = unsafe { tlb_data[page as usize] };
        if 0 != entry {
            let tlb_physical_page = Page::of_u32(
                (entry as u32 >> 12 ^ page as u32) - (unsafe { memory::mem8 } as u32 >> 12),
            );
            if physical_pages.contains(&tlb_physical_page) {
                unsafe {
                    tlb_data[page as usize] =
                        if has_code { entry | TLB_HAS_CODE } else { entry & !TLB_HAS_CODE }
                }
            }
        }
    }

    check_tlb_invariants();
}

pub fn check_tlb_invariants() {
    if !CHECK_TLB_INVARIANTS {
        return;
    }

    for i in 0..unsafe { valid_tlb_entries_count } {
        let page = unsafe { valid_tlb_entries[i as usize] };
        let entry = unsafe { tlb_data[page as usize] };

        if 0 == entry || 0 != entry & TLB_IN_MAPPED_RANGE {
            // there's no code in mapped memory
            continue;
        }

        let target = (entry ^ page << 12) as u32 - unsafe { memory::mem8 } as u32;
        dbg_assert!(!memory::in_mapped_range(target));

        let entry_has_code = entry & TLB_HAS_CODE != 0;
        let has_code = jit::jit_page_has_code(Page::page_of(target));

        // If some code has been created in a page, the corresponding tlb entries must be marked
        dbg_assert!(!has_code || entry_has_code);
    }
}

pub const DISABLE_EIP_TRANSLATION_OPTIMISATION: bool = false;

pub unsafe fn read_imm8() -> OrPageFault<i32> {
    let eip = *instruction_pointer;
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode with the fetch page cached: as below)
        if *x64_cs_long != 0 || 0 != eip & !0xFFF ^ *last_virt_eip {
            return ia32e_fetch8();
        }
    }
    else if DISABLE_EIP_TRANSLATION_OPTIMISATION || 0 != eip & !0xFFF ^ *last_virt_eip {
        return read_imm8_uncached(eip);
    }
    // cached pages are plain RAM (see cache_fetch_page; in compatibility
    // mode also relocated RAM, ia32e_phys_eip)
    dbg_assert!(memory::is_ram_backing((*eip_phys ^ eip) as u32));
    let data8 = *memory::mem8.offset((*eip_phys ^ eip) as isize) as i32;
    *instruction_pointer = eip + 1;
    return Ok(data8);
}

#[inline(never)]
unsafe fn read_imm8_uncached(eip: i32) -> OrPageFault<i32> {
    let phys = translate_address_read(eip)?;
    cache_fetch_page(eip, phys);
    // A remapped low RAM page is an open bus, never the high RAM backing
    let data8 = memory::fetch8(phys);
    *instruction_pointer = eip + 1;
    Ok(data8)
}

/// Remember the physical page of instruction fetches from `eip`'s page, but
/// only for plain RAM: fetches from mapped ranges (VGA, MMIO, the low hole
/// left by RAM relocated above 4 GiB) go through the bus every time.
#[inline(always)]
unsafe fn cache_fetch_page(eip: i32, phys: u32) {
    if memory::in_mapped_range(phys & !0xFFF) || memory::in_mapped_range(phys | 0xFFF) {
        *last_virt_eip = -1;
    }
    else {
        *eip_phys = (phys ^ eip as u32) as i32;
        *last_virt_eip = eip & !0xFFF;
    }
}

pub unsafe fn read_imm8s() -> OrPageFault<i32> { return Ok(read_imm8()? << 24 >> 24); }

pub unsafe fn read_imm16() -> OrPageFault<i32> {
    // Two checks:
    // 1. Did the high 20 bits of eip change (last_virt_eip's -1, no page
    //    cached, has low bits: it must not pass for the page at 0xFFFFF000,
    //    where firmware runs from flash)
    // or 2. Are the low 12 bits of eip 0xFFF (and this read crosses a page boundary)
    // (IA-32e mode: compatibility mode with the fetch page cached only)
    if DISABLE_EIP_TRANSLATION_OPTIMISATION
        || 0 != *instruction_pointer & !0xFFF ^ *last_virt_eip
        || *instruction_pointer & 0xFFF > 0xFFE
        || crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 && *x64_cs_long != 0
    {
        return Ok(read_imm8()? | read_imm8()? << 8);
    }
    else {
        let data16 = memory::read16_no_mmap_check((*eip_phys ^ *instruction_pointer) as u32);
        *instruction_pointer = *instruction_pointer + 2;
        return Ok(data16);
    };
}

pub unsafe fn read_imm32s() -> OrPageFault<i32> {
    // Analogue to the above comment
    if DISABLE_EIP_TRANSLATION_OPTIMISATION
        || 0 != *instruction_pointer & !0xFFF ^ *last_virt_eip
        || *instruction_pointer & 0xFFF > 0xFFC
        || crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 && *x64_cs_long != 0
    {
        return Ok(read_imm16()? | read_imm16()? << 16);
    }
    else {
        let data32 = memory::read32_no_mmap_check((*eip_phys ^ *instruction_pointer) as u32);
        *instruction_pointer = *instruction_pointer + 4;
        return Ok(data32);
    };
}

pub unsafe fn is_osize_32() -> bool {
    return *is_32 != (*prefixes & prefix::PREFIX_MASK_OPSIZE == prefix::PREFIX_MASK_OPSIZE);
}

pub unsafe fn is_asize_32() -> bool {
    return *is_32 != (*prefixes & prefix::PREFIX_MASK_ADDRSIZE == prefix::PREFIX_MASK_ADDRSIZE);
}

pub unsafe fn lookup_segment_selector(
    selector: SegmentSelector,
) -> OrPageFault<Result<(SegmentDescriptor, u64), SelectorNullOrInvalid>> {
    if selector.is_null() {
        return Ok(Err(SelectorNullOrInvalid::IsNull));
    }

    // IA-32e mode (compatibility mode included): GDTR and LDTR hold 64-bit
    // bases; Windows keeps its GDT above 4 GiB.
    let long_mode = crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0;
    let (table_offset, table_limit) = if selector.is_gdt() {
        (
            if long_mode {
                crate::x64::state::read_gdtr_base()
            }
            else {
                *gdtr_offset as u32 as u64
            },
            *gdtr_size as u32,
        )
    }
    else {
        (
            if long_mode {
                crate::x64::state::read_segment_base(LDTR as usize)
            }
            else {
                *segment_offsets.offset(LDTR as isize) as u32 as u64
            },
            *segment_limits.offset(LDTR as isize) as u32,
        )
    };

    if selector.descriptor_offset() as u32 + 7 > table_limit {
        dbg_log!(
            "segment outside of table limit: selector={:x} offset={:x} isgdt={} table_limit={:x}",
            selector.raw,
            selector.descriptor_offset(),
            selector.is_gdt(),
            table_limit
        );
        return Ok(Err(SelectorNullOrInvalid::OutsideOfTableLimit));
    }

    let descriptor_address = if long_mode {
        table_offset.wrapping_add(selector.descriptor_offset() as u64)
    }
    else {
        (table_offset as u32).wrapping_add(selector.descriptor_offset() as u32) as u64
    };

    let descriptor = SegmentDescriptor::of_u64(if long_mode {
        crate::x64::memory::read_system(descriptor_address, 64)
            .map_err(|fault| crate::x64::system::raise(fault))?
    }
    else {
        read_system(descriptor_address as i32, 8)?
    });

    Ok(Ok((descriptor, descriptor_address)))
}

/// Stores a descriptor's access byte (accessed or busy bit) at the linear
/// address from lookup_segment_selector.
unsafe fn write_descriptor_access_byte(
    descriptor_address: u64,
    access_byte: u8,
) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return crate::x64::memory::write_system(
            descriptor_address.wrapping_add(5),
            8,
            access_byte as u64,
        )
        .map_err(|fault| crate::x64::system::raise(fault));
    }
    memory::write8(
        translate_address_system_write(descriptor_address as i32 + 5)?,
        access_byte as i32,
    );
    Ok(())
}

#[inline(never)]
pub unsafe fn switch_seg(reg: i32, selector_raw: i32) -> bool {
    dbg_assert!(reg >= 0 && reg <= 5);
    dbg_assert!(reg != CS);
    dbg_assert!(selector_raw >= 0 && selector_raw < 0x10000);

    if vm86_mode() {
        // TODO: Should set segment_limits and segment_access_bytes if ever implemented in get_seg
        //       (only vm86, not in real mode)
    }

    if !*protected_mode || vm86_mode() {
        *sreg.offset(reg as isize) = selector_raw as u16;
        *segment_is_null.offset(reg as isize) = false;
        *segment_offsets.offset(reg as isize) = selector_raw << 4;

        if reg == SS {
            *stack_size_32 = false;
        }
        update_state_flags();
        return true;
    }

    let selector = SegmentSelector::of_u16(selector_raw as u16);
    let (mut descriptor, descriptor_address) =
        match return_on_pagefault!(lookup_segment_selector(selector), false) {
            Ok(desc) => desc,
            Err(SelectorNullOrInvalid::IsNull) => {
                if reg == SS {
                    dbg_log!("#GP for loading 0 in SS sel={:x}", selector_raw);
                    trigger_gp(0);
                    return false;
                }
                else {
                    // es, ds, fs, gs
                    *sreg.offset(reg as isize) = selector_raw as u16;
                    *segment_is_null.offset(reg as isize) = true;
                    update_state_flags();
                    return true;
                }
            },
            Err(SelectorNullOrInvalid::OutsideOfTableLimit) => {
                dbg_log!(
                    "#GP for loading invalid in seg={} sel={:x}",
                    reg,
                    selector_raw,
                );
                dbg_trace();
                trigger_gp(selector_raw & !3);
                return false;
            },
        };

    if reg == SS {
        if descriptor.is_system()
            || selector.rpl() != *cpl
            || !descriptor.is_writable()
            || descriptor.dpl() != *cpl
        {
            dbg_log!("#GP for loading invalid in SS sel={:x}", selector_raw);
            trigger_gp(selector_raw & !3);
            return false;
        }

        if !descriptor.is_present() {
            dbg_log!("#SS for loading non-present in SS sel={:x}", selector_raw);
            trigger_ss(selector_raw & !3);
            return false;
        }

        *stack_size_32 = descriptor.is_32();
    }
    else {
        if descriptor.is_system()
            || !descriptor.is_readable()
            || (!descriptor.is_conforming_executable()
                && (selector.rpl() > descriptor.dpl() || *cpl > descriptor.dpl()))
        {
            dbg_log!(
                "#GP for loading invalid in seg {} sel={:x} sys={} readable={} dc={} exec={} rpl={} dpl={} cpl={} present={} paging={}",
                reg,
                selector_raw,
                descriptor.is_system(),
                descriptor.is_readable(),
                descriptor.is_dc(),
                descriptor.is_executable(),
                selector.rpl(),
                descriptor.dpl(),
                *cpl,
                descriptor.is_present(),
                *cr & CR0_PG != 0,
            );
            dbg_trace();
            trigger_gp(selector_raw & !3);
            return false;
        }

        if !descriptor.is_present() {
            dbg_log!(
                "#NP for loading not-present in seg {} sel={:x}",
                reg,
                selector_raw,
            );
            trigger_np(selector_raw & !3);
            return false;
        }
    }

    if !descriptor.accessed() {
        descriptor = descriptor.set_accessed();
        return_on_pagefault!(
            write_descriptor_access_byte(descriptor_address, descriptor.access_byte()),
            false
        );
    }

    *segment_is_null.offset(reg as isize) = false;
    *segment_limits.offset(reg as isize) = descriptor.effective_limit();
    // (compatibility mode: the 32-bit base, zero-extended)
    crate::x64::state::write_segment_base(reg as usize, descriptor.base() as u32 as u64);
    *segment_access_bytes.offset(reg as isize) = descriptor.access_byte();
    *sreg.offset(reg as isize) = selector_raw as u16;

    update_state_flags();

    true
}

/// switch_seg for ES, DS, FS or GS in legacy protected mode when it raises
/// nothing and leaves the state flags as they are (the MOV Sreg template,
/// docs/jit-unification-plan.md P3.7(b), IR Tier-0's until P7.5). false, with nothing
/// changed: a fault, a descriptor that does not translate without one, an
/// accessed bit to set on a page with compiled code or a device, or (with
/// `keep_flat`) a DS whose load changes flat segmentation (then the
/// interpreter runs the instruction, as switch_seg; the x64 page tier's
/// functions compiled for segment bases take any DS, P7.2(3))
pub unsafe fn switch_seg_without_fault(reg: i32, selector_raw: i32, keep_flat: bool) -> bool {
    dbg_assert!(reg == ES || reg == DS || reg == FS || reg == GS);
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return false;
    }
    // (real mode and virtual-8086 mode: no descriptor and no fault, as
    // switch_seg; the page tier's 16-bit code, docs/jit-unification-plan.md
    // P7.8)
    if !*protected_mode || vm86_mode() {
        *sreg.offset(reg as isize) = selector_raw as u16;
        *segment_is_null.offset(reg as isize) = false;
        *segment_offsets.offset(reg as isize) = selector_raw << 4;
        update_state_flags();
        return true;
    }
    let selector = SegmentSelector::of_u16(selector_raw as u16);
    let flat = has_flat_segmentation();
    if selector.is_null() {
        // (a null DS is not flat segmentation)
        if reg == DS && flat && keep_flat {
            return false;
        }
        *sreg.offset(reg as isize) = selector_raw as u16;
        *segment_is_null.offset(reg as isize) = true;
        update_state_flags();
        return true;
    }
    // lookup_segment_selector's read, a system access, must not fault
    let (table, limit) = if selector.is_gdt() {
        (*gdtr_offset as u32, *gdtr_size as u32)
    }
    else {
        (
            *segment_offsets.offset(LDTR as isize) as u32,
            *segment_limits.offset(LDTR as isize) as u32,
        )
    };
    if selector.descriptor_offset() as u32 + 7 > limit {
        return false;
    }
    let address = table.wrapping_add(selector.descriptor_offset() as u32);
    for byte in [address, address.wrapping_add(7)] {
        if translate_address(byte as i32, false, false, false).is_err() {
            return false;
        }
    }
    let Ok(Ok((mut descriptor, descriptor_address))) = lookup_segment_selector(selector)
    else {
        return false;
    };
    if descriptor.is_system()
        || !descriptor.is_readable()
        || (!descriptor.is_conforming_executable()
            && (selector.rpl() > descriptor.dpl() || *cpl > descriptor.dpl()))
        || !descriptor.is_present()
    {
        return false;
    }
    if reg == DS
        && keep_flat
        && flat
            != (*segment_offsets.offset(SS as isize) == 0
                && descriptor.base() as u32 == 0
                && *segment_offsets.offset(CS as isize) == 0)
    {
        return false;
    }
    if !descriptor.accessed() {
        let Ok(physical) = translate_address(descriptor_address as i32 + 5, true, false, false)
        else {
            return false;
        };
        if crate::jit::jit_page_has_code(crate::page::Page::page_of(physical))
            || memory::may_interrupt(physical)
        {
            return false;
        }
        descriptor = descriptor.set_accessed();
        if write_descriptor_access_byte(descriptor_address, descriptor.access_byte()).is_err() {
            dbg_assert!(false, "a translated accessed-bit write faulted");
            return false;
        }
    }
    *segment_is_null.offset(reg as isize) = false;
    *segment_limits.offset(reg as isize) = descriptor.effective_limit();
    crate::x64::state::write_segment_base(reg as usize, descriptor.base() as u32 as u64);
    *segment_access_bytes.offset(reg as isize) = descriptor.access_byte();
    *sreg.offset(reg as isize) = selector_raw as u16;
    update_state_flags();
    true
}

pub unsafe fn load_tr(selector: i32) { let _ = load_tr_checked(selector); }

// Explicit read-fault status for terminal IR callers. load_tr keeps
// its original void ABI and all panic/partial-commit behavior is unchanged.
pub unsafe fn load_tr_checked(selector: i32) -> OrPageFault<()> {
    let selector = SegmentSelector::of_u16(selector as u16);
    let error = selector.raw as i32 & !3;

    // (SDM LTR: #GP(0) for a null selector; #GP(selector) for one outside
    // the GDT, not a TSS or a busy TSS; #NP(selector) if not present.
    // Err: the fault was delivered)
    if selector.is_null() {
        trigger_gp(0);
        return Err(());
    }
    if !selector.is_gdt() {
        trigger_gp(error);
        return Err(());
    }
    let (descriptor, descriptor_address) = match lookup_segment_selector(selector)? {
        Ok((desc, addr)) => (desc, addr),
        Err(_) => {
            trigger_gp(error);
            return Err(());
        },
    };

    // 0x9: available 386 TSS, 0x1: available 286 TSS (0xB/0x3: busy, #GP)
    if !descriptor.is_system() || descriptor.system_type() != 9 && descriptor.system_type() != 1 {
        dbg_log!(
            "ltr: {:x} is not an available TSS (type 0x{:x})",
            selector.raw,
            descriptor.system_type()
        );
        trigger_gp(error);
        return Err(());
    }

    if !descriptor.is_present() {
        trigger_np(error);
        return Err(());
    }

    *tss_size_32 = descriptor.system_type() == 9;
    *segment_limits.offset(TR as isize) = descriptor.effective_limit();
    *segment_offsets.offset(TR as isize) = descriptor.base();
    *sreg.offset(TR as isize) = selector.raw;

    // Mark task as busy
    write_descriptor_access_byte(descriptor_address, descriptor.set_busy().access_byte())
}

pub unsafe fn load_ldt(selector: i32) -> OrPageFault<()> {
    // Err: a page fault or the #GP/#NP was delivered
    if load_ldt_checked(selector, false)? {
        Ok(())
    }
    else {
        Err(())
    }
}

/// LLDT, or the LDT selector of a task switch (then every failure is #TS).
/// Ok(false): a #GP/#NP/#TS with the selector was delivered.
pub unsafe fn load_ldt_checked(selector: i32, task_switch: bool) -> OrPageFault<bool> {
    let selector = SegmentSelector::of_u16(selector as u16);
    let error = selector.raw as i32 & !3;

    if selector.is_null() {
        dbg_log!("lldt: null loaded");
        *segment_limits.offset(LDTR as isize) = 0;
        *segment_offsets.offset(LDTR as isize) = 0;
        *sreg.offset(LDTR as isize) = selector.raw;
        return Ok(true);
    }

    let fault = |not_present: bool| {
        if task_switch {
            trigger_ts(error)
        }
        else if not_present {
            trigger_np(error)
        }
        else {
            trigger_gp(error)
        }
        Ok(false)
    };

    // the LDT descriptor must be in the GDT
    if !selector.is_gdt() {
        return fault(false);
    }
    let descriptor = match lookup_segment_selector(selector)? {
        Ok((desc, _)) => desc,
        Err(_) => return fault(false),
    };
    if !descriptor.is_system() || descriptor.system_type() != 2 {
        dbg_log!("lldt: {:x} is not an LDT descriptor", selector.raw);
        return fault(false);
    }
    if !descriptor.is_present() {
        return fault(true);
    }

    dbg_log!(
        "lldt: {:x} offset={:x} limit={:x}",
        selector.raw,
        descriptor.base(),
        descriptor.effective_limit()
    );
    *segment_limits.offset(LDTR as isize) = descriptor.effective_limit();
    *segment_offsets.offset(LDTR as isize) = descriptor.base();
    *sreg.offset(LDTR as isize) = selector.raw;

    Ok(true)
}

pub unsafe fn get_seg(segment: i32) -> OrPageFault<i32> {
    dbg_assert!(segment >= 0 && segment < 8);
    if *segment_is_null.offset(segment as isize) {
        dbg_assert!(segment != CS && segment != SS);
        dbg_log!("#gp: Access null segment {}", segment);
        dbg_trace();
        trigger_gp(0);
        return Err(());
    }
    return Ok(*segment_offsets.offset(segment as isize));
}

/// false: a fault was delivered
pub unsafe fn set_cr0(cr0: i32) -> bool {
    if crate::x64::state::efer() & (crate::x64::state::EFER_LME | crate::x64::state::EFER_LMA) != 0
    {
        if let Err(fault) = crate::x64::system::write_cr(0, cr0 as u32 as u64) {
            crate::x64::system::raise(fault);
            return false;
        }
        return true;
    }
    let old_cr0 = *cr;

    if old_cr0 & CR0_AM == 0 && cr0 & CR0_AM != 0 {
        dbg_log!("Warning: Unimplemented: cr0 alignment mask");
    }
    if (cr0 & (CR0_PE | CR0_PG)) == CR0_PG {
        trigger_gp(0);
        return false;
    }
    if (old_cr0 ^ cr0) & CR0_TS != 0 {
        crate::step_profile::note_event(crate::step_profile::event::CR0_TS, 0);
    }

    *cr = cr0;
    *cr |= CR0_ET;

    if old_cr0 & (CR0_PG | CR0_WP) != cr0 & (CR0_PG | CR0_WP) {
        full_clear_tlb();
    }

    if *cr.offset(4) & CR4_PAE != 0
        && *cr & CR0_PG != 0
        && old_cr0 & (CR0_CD | CR0_NW | CR0_PG) != cr0 & (CR0_CD | CR0_NW | CR0_PG)
    {
        load_pdpte(*cr.offset(3))
    }

    *protected_mode = (*cr & CR0_PE) == CR0_PE;
    *segment_access_bytes.offset(CS as isize) = 0x80 | 0x10 | 0x08 | 0x02; // P dpl0 S E RW
    true
}

/// false: a fault was delivered
pub unsafe fn set_cr3(mut cr3: i32) -> bool {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Err(fault) = crate::x64::system::write_cr(3, cr3 as u32 as u64) {
            crate::x64::system::raise(fault);
            return false;
        }
        return true;
    }
    if false {
        dbg_log!("cr3 <- {:x}", cr3);
    }
    if *cr.offset(4) & CR4_PAE != 0 {
        cr3 &= !0b1111;
        if *cr & CR0_PG != 0 {
            load_pdpte(cr3);
        }
    }
    else {
        cr3 &= !0b111111100111;
        dbg_assert!(cr3 & 0xFFF == 0, "TODO");
    }
    // (outside long mode a 32-bit value, zero-extended: the upper half a long
    // mode OS left must go, or OVMF's SMI entry, which sets CR3 in 16-bit
    // code, walks from the OS's page tables once it enables paging)
    crate::x64::state::write_cr_raw(3, cr3 as u32 as u64);
    clear_tlb();
    true
}

pub unsafe fn load_pdpte(cr3: i32) {
    dbg_assert!(cr3 & 0b1111 == 0);
    for i in 0..4 {
        let mut pdpt_entry = memory::read64s(cr3 as u32 + 8 * i as u32) as u64;
        pdpt_entry &= !0b1110_0000_0000;
        dbg_assert!(pdpt_entry & 0b11000 == 0, "TODO");
        dbg_assert!(
            pdpt_entry as u64 & 0xFFFF_FFFF_0000_0000 == 0,
            "Unsupported: PDPT entry larger than 32 bits"
        );
        if pdpt_entry as i32 & PAGE_TABLE_PRESENT_MASK != 0 {
            dbg_assert!(
                pdpt_entry & 0b1_1110_0110 == 0,
                "TODO: #gp reserved bit in pdpte"
            );
        }
        *reg_pdpte.offset(i) = pdpt_entry;
    }
}

pub unsafe fn cpl_changed() { *last_virt_eip = -1 }

pub unsafe fn update_cs_size(new_size: bool) {
    if *is_32 != new_size {
        *is_32 = new_size;
    }
}

/// VMware's backdoor port: VMware lets every privilege level use it (its
/// tools and its user-mode 3D driver do), and so does v86 (src/vmware.js)
pub const VMWARE_BACKDOOR_PORT: i32 = 0x5658;

#[inline(never)]
pub unsafe fn test_privileges_for_io(port: i32, size: i32) -> bool {
    if port == VMWARE_BACKDOOR_PORT {
        return true;
    }
    // compatibility mode: the 64-bit TSS base
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return match crate::x64::system::check_io_access(port as u16, (size * 8) as u8) {
            Ok(()) => true,
            Err(fault) => {
                crate::x64::system::raise(fault);
                false
            },
        };
    }
    if *protected_mode && (*cpl > getiopl() as u8 || (*flags & FLAG_VM != 0)) {
        if !*tss_size_32 {
            dbg_log!("#GP for port io, 16-bit TSS  port={:x} size={}", port, size);
            trigger_gp(0);
            return false;
        }

        let tsr_size = *segment_limits.offset(TR as isize);
        let tsr_offset = *segment_offsets.offset(TR as isize);

        if tsr_size >= 0x67 {
            dbg_assert!(tsr_offset + 0x64 + 2 & 0xFFF < 0xFFF);

            let iomap_base = memory::read16(return_on_pagefault!(
                translate_address_system_read(tsr_offset + 0x64 + 2),
                false
            ));
            let high_port = port + size - 1;

            if tsr_size >= (iomap_base + (high_port >> 3)) as u32 {
                let mask = ((1 << size) - 1) << (port & 7);
                let addr = return_on_pagefault!(
                    translate_address_system_read(tsr_offset + iomap_base + (port >> 3)),
                    false
                );
                let port_info =
                    if mask & 0xFF00 != 0 { memory::read16(addr) } else { memory::read8(addr) };

                dbg_assert!(addr & 0xFFF < 0xFFF);

                if port_info & mask == 0 {
                    return true;
                }
            }
        }

        dbg_log!("#GP for port io  port={:x} size={}", port, size);
        trigger_gp(0);
        return false;
    }

    return true;
}

pub unsafe fn popa16() {
    return_on_pagefault!(readable_or_pagefault(get_stack_pointer(0), 16));

    write_reg16(DI, pop16().unwrap());
    write_reg16(SI, pop16().unwrap());
    write_reg16(BP, pop16().unwrap());
    adjust_stack_reg(2);
    write_reg16(BX, pop16().unwrap());
    write_reg16(DX, pop16().unwrap());
    write_reg16(CX, pop16().unwrap());
    write_reg16(AX, pop16().unwrap());
}

pub unsafe fn popa32() {
    return_on_pagefault!(readable_or_pagefault(get_stack_pointer(0), 32));

    write_reg32(EDI, pop32s().unwrap());
    write_reg32(ESI, pop32s().unwrap());
    write_reg32(EBP, pop32s().unwrap());
    adjust_stack_reg(4);
    write_reg32(EBX, pop32s().unwrap());
    write_reg32(EDX, pop32s().unwrap());
    write_reg32(ECX, pop32s().unwrap());
    write_reg32(EAX, pop32s().unwrap());
}

pub fn get_state_flags() -> CachedStateFlags { unsafe { *state_flags } }

#[no_mangle]
pub fn get_seg_cs() -> i32 { unsafe { *segment_offsets.offset(CS as isize) } }

pub unsafe fn get_seg_ss() -> i32 { return *segment_offsets.offset(SS as isize); }

pub unsafe fn segment_prefix(default_segment: i32) -> i32 {
    let prefix = *prefixes & prefix::PREFIX_MASK_SEGMENT;
    if 0 != prefix {
        dbg_assert!(prefix != prefix::SEG_PREFIX_ZERO);
        prefix as i32 - 1
    }
    else {
        default_segment
    }
}

pub unsafe fn get_seg_prefix(default_segment: i32) -> OrPageFault<i32> {
    let prefix = *prefixes & prefix::PREFIX_MASK_SEGMENT;
    if 0 != prefix {
        if prefix == prefix::SEG_PREFIX_ZERO {
            return Ok(0);
        }
        else {
            return get_seg(prefix as i32 - 1);
        }
    }
    else {
        return get_seg(default_segment);
    };
}

pub unsafe fn get_seg_prefix_ds(offset: i32) -> OrPageFault<i32> {
    Ok(get_seg_prefix(DS)? + offset)
}

pub unsafe fn get_seg_prefix_ss(offset: i32) -> OrPageFault<i32> {
    Ok(get_seg_prefix(SS)? + offset)
}

pub unsafe fn modrm_resolve(modrm_byte: i32) -> OrPageFault<i32> {
    if is_asize_32() {
        resolve_modrm32(modrm_byte)
    }
    else {
        resolve_modrm16(modrm_byte)
    }
}

pub unsafe fn run_instruction(opcode: i32) {
    // (debug builds only: no cost in the release interpreter)
    if cfg!(debug_assertions) && INSTRUCTION_TRACE_ENABLED {
        instruction_trace_note(*instruction_pointer - 1);
    }
    gen::interpreter::run(opcode as u32)
}
pub unsafe fn run_instruction0f_16(opcode: i32) { gen::interpreter0f::run(opcode as u32) }
pub unsafe fn run_instruction0f_32(opcode: i32) { gen::interpreter0f::run(opcode as u32 | 0x100) }

/// Instructions run by the interpreter loop (not page tier steps), in total and
/// by linear page in a small direct-mapped table: where compiled code is
/// missing (diagnostics; see ir_interpreted_stat).
static mut INTERPRETED: u32 = 0;
static mut INTERPRETED_PAGES: [(u32, u32); 1024] = [(0, 0); 1024];
/// Interpreted instructions of one chosen page by 16-byte chunk of the EIP
/// the interpreter started at (ir_interpreted_stat fields 4 and 5).
static mut INTERPRETED_WATCH: u32 = u32::MAX;
static mut INTERPRETED_OFFSETS: [u32; 256] = [0; 256];
/// VEX instructions the interpreter ran (cpu::vex::run; ir_interpreted_stat
/// field 6)
pub static mut INTERPRETED_VEX: u32 = 0;
#[inline(always)]
unsafe fn note_interpreted_page(eip: u32, steps: u32) {
    INTERPRETED = INTERPRETED.wrapping_add(steps);
    let page = eip >> 12;
    if page == INTERPRETED_WATCH {
        INTERPRETED_OFFSETS[(eip as usize & 4095) >> 4] += steps;
    }
    let slot = &mut INTERPRETED_PAGES[(page.wrapping_mul(0x9E3779B1) >> 22) as usize];
    if slot.0 != page {
        if slot.1 > steps {
            slot.1 -= steps;
            return;
        }
        *slot = (page, 0);
    }
    slot.1 = slot.1.wrapping_add(steps);
}
/// field 0: total interpreted instructions; 1/2: page and count of table
/// slot `index`; 3: reset; 4: watch page `index` (a page number); 5: its
/// interpreted instructions started in 16-byte chunk `index`; 6: VEX
/// instructions interpreted.
#[no_mangle]
pub unsafe fn ir_interpreted_stat(field: u32, index: u32) -> u32 {
    match field {
        0 => INTERPRETED,
        1 | 2 if index < 1024 => {
            let slot = INTERPRETED_PAGES[index as usize];
            if field == 1 {
                slot.0
            }
            else {
                slot.1
            }
        },
        3 => {
            INTERPRETED = 0;
            INTERPRETED_PAGES = [(0, 0); 1024];
            INTERPRETED_VEX = 0;
            0
        },
        4 => {
            INTERPRETED_WATCH = index;
            INTERPRETED_OFFSETS = [0; 256];
            0
        },
        5 if index < 256 => {
            let offsets = INTERPRETED_OFFSETS;
            offsets[index as usize]
        },
        6 => INTERPRETED_VEX,
        _ => 0,
    }
}

pub unsafe fn cycle_internal() -> bool {
    if crate::x64::state::mode().is_long() {
        if !crate::jit::enabled() {
            let span = crate::cpu::execution::ledger_begin();
            run_long_instruction();
            crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
            return false;
        }
        // (to the end of the batch, as legacy mode's functions run since P7.3:
        // a return to this loop every 4096 instructions, as long mode had,
        // cost a CPU-Z-like float kernel 2%)
        let ran = (*instruction_counter).wrapping_sub(jit_link_batch_start);
        let attempt = crate::x64::pages::run(jit_link_batch_limit.saturating_sub(ran).max(1));
        if attempt.retired == 0 {
            let span = crate::cpu::execution::ledger_begin();
            run_long_instruction();
            crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
        }
        return attempt.submitted;
    }
    // 32-bit compatibility-mode code in the x64 page tier (x64_page_compat32,
    // docs/jit-unification-plan.md P7.2) and legacy protected-mode code
    // (x64_page_legacy32, P7.3)
    if crate::x64::pages::page32()
        && crate::jit::enabled()
        && !crate::cpu::execution::is_deterministic()
        && crate::x64::pages::runnable32()
    {
        // (to the end of the batch, as IR Tier-0's functions ran: a return to
        // this loop every 4096 instructions cost 531.bitboard 4%)
        let ran = (*instruction_counter).wrapping_sub(jit_link_batch_start);
        let attempt = crate::x64::pages::run(jit_link_batch_limit.saturating_sub(ran).max(1));
        if attempt.retired == 0 && still_32_bit_code() {
            let span = crate::cpu::execution::ledger_begin();
            run_compat_instruction();
            crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
        }
        return attempt.submitted;
    }
    profiler::stat_increment(stat::CYCLE_INTERNAL);
    let initial_eip = *instruction_pointer;
    *previous_ip = initial_eip;
    let phys_addr = return_on_pagefault!(get_phys_eip(), false);

    let initial_instruction_counter = *instruction_counter;
    let span = crate::cpu::execution::ledger_begin();
    jit_run_interpreted(phys_addr, u32::MAX);
    crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
    note_interpreted_page(
        initial_eip as u32,
        (*instruction_counter).wrapping_sub(initial_instruction_counter),
    );
    profiler::stat_increment_by(
        stat::RUN_INTERPRETED_STEPS,
        (*instruction_counter - initial_instruction_counter) as u64,
    );
    dbg_assert!(
        *instruction_counter != initial_instruction_counter,
        "Instruction counter didn't change"
    );
    false
}

/// After a 32-bit page tier attempt that retired nothing (x64::pages::run),
/// whether its fallback, the interpreted instruction at CS:EIP, still
/// applies. An activation that ends before its first instruction (with
/// cores in workers: another core kicked this one, parallel::kick) still
/// takes a deliverable interrupt (pages::execute), and in IA-32e mode that
/// enters 64-bit code. The 32-bit interpreter would then fetch at the
/// handler's RIP truncated to 32 bits, at CPL 0 with the interrupted user
/// code's GS base: Windows 8.1 x64 took a #PF there from a WOW64 process
/// and, finding a kernel CS in the frame, ran its page fault handler
/// without SWAPGS (a #PF/#DF loop on its IST stack, or a bug check).
#[inline(always)]
unsafe fn still_32_bit_code() -> bool { !crate::x64::state::mode().is_long() }

// IA-32e mode (compatibility-mode code) paths of the legacy memory and
// fetch helpers. Out of line and cold, so the 32-bit fast paths stay small
// enough to be inlined into the interpreter.
/// Whether an opcode at `phys_addr` (from get_phys_eip) is read through the
/// bus: a mapped range (VGA, MMIO, firmware flash, the low hole left by RAM
/// relocated above 4 GiB). With EFER.LMA, get_phys_eip resolves relocated
/// RAM to its backing, which is plain memory although it lies in the low
/// hole; what is mapped then is the extended RAM aperture or device memory.
#[inline(always)]
unsafe fn fetch_through_bus(phys_addr: u32) -> bool {
    memory::in_mapped_range(phys_addr)
        && (crate::x64::state::efer() & crate::x64::state::EFER_LMA == 0
            || crate::x64::extended::aperture::contains(phys_addr)
            || crate::cpu::mmio_ram::contains(phys_addr))
}

#[cold]
#[inline(never)]
unsafe fn ia32e_phys_eip() -> OrPageFault<u32> {
    let address = crate::x64::memory::translate(
        *instruction_pointer as u32 as u64,
        crate::x64::paging::Access::Execute,
        false,
        false,
    )
    .map_err(|fault| crate::x64::system::raise(fault))?;
    match crate::x64::physical::ram_page(address & !4095) {
        Ok(page) => {
            let phys = page.backing | (address & 4095) as u32;
            // compatibility mode: remember the page (get_phys_eip, read_imm*)
            if *x64_cs_long == 0 {
                *eip_phys = (phys ^ *instruction_pointer as u32) as i32;
                *last_virt_eip = *instruction_pointer & !0xFFF;
            }
            Ok(phys)
        },
        // code in extended RAM runs from its aperture address (interpreted:
        // nothing compiles from the mapped range)
        Err(_) if crate::x64::extended::contains(address) => {
            Ok(crate::x64::extended::aperture::map(address))
        },
        // and code in device memory (the UEFI firmware's flash) from its
        // address on the legacy bus, likewise
        Err(_) if address >> 32 == 0 && crate::cpu::mmio_ram::contains(address as u32) => {
            Ok(address as u32)
        },
        Err(_) => Err(crate::x64::system::raise(crate::x64::memory::Fault::gp())),
    }
}
#[cold]
#[inline(never)]
unsafe fn ia32e_fetch8() -> OrPageFault<i32> {
    let value = crate::x64::memory::fetch(*instruction_pointer as u32 as u64)
        .map_err(|fault| crate::x64::system::raise(fault))?;
    *instruction_pointer = (*instruction_pointer).wrapping_add(1);
    Ok(value as i32)
}
#[cold]
#[inline(never)]
unsafe fn ia32e_translate(
    address: i32,
    for_writing: bool,
    user: bool,
    side_effects: bool,
) -> OrPageFault<u32> {
    crate::x64::memory::legacy_translate(
        address as u32,
        if for_writing {
            crate::x64::paging::Access::Write
        }
        else {
            crate::x64::paging::Access::Read
        },
        user,
        side_effects,
    )
}
#[cold]
#[inline(never)]
unsafe fn ia32e_read(addr: i32, bits: u8) -> OrPageFault<u64> {
    crate::x64::memory::read(addr as u32 as u64, bits, false)
        .map_err(|fault| crate::x64::system::raise(fault))
}
#[cold]
#[inline(never)]
unsafe fn ia32e_read128(addr: i32) -> OrPageFault<reg128> {
    crate::x64::memory::read128(addr as u32 as u64, false)
        .map(|value| reg128 {
            u64: [value as u64, (value >> 64) as u64],
        })
        .map_err(|fault| crate::x64::system::raise(fault))
}
#[cold]
#[inline(never)]
unsafe fn ia32e_write(addr: i32, bits: u8, value: u64) -> OrPageFault<()> {
    crate::x64::memory::write(addr as u32 as u64, bits, value, false)
        .map_err(|fault| crate::x64::system::raise(fault))
}
#[cold]
#[inline(never)]
unsafe fn ia32e_write128(addr: i32, value: reg128) -> OrPageFault<()> {
    crate::x64::memory::write128(
        addr as u32 as u64,
        value.u64[0] as u128 | (value.u64[1] as u128) << 64,
        false,
    )
    .map_err(|fault| crate::x64::system::raise(fault))
}

pub unsafe fn get_phys_eip() -> OrPageFault<u32> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // compatibility mode: the last fetch page too (ia32e_phys_eip fills
        // it; whatever may change its translation resets last_virt_eip)
        let eip = *instruction_pointer;
        if *x64_cs_long == 0 {
            if 0 == eip & !0xFFF ^ *last_virt_eip {
                return Ok((*eip_phys ^ eip) as u32);
            }
            // an entry a fetch made (not data-only: NX was checked), which
            // is RAM (fill_ia32e_tlb makes none of another kind for fetches)
            let entry = tlb_data[(eip as u32 >> 12) as usize];
            let mask = TLB_VALID | TLB_IA32E_DATA | if *cpl == 3 { TLB_NO_USER } else { 0 };
            if entry & mask == TLB_VALID {
                let phys = ((entry & !0xFFF ^ eip) as u32).wrapping_sub(memory::mem8 as u32);
                *eip_phys = (phys ^ eip as u32) as i32;
                *last_virt_eip = eip & !0xFFF;
                return Ok(phys);
            }
        }
        return ia32e_phys_eip();
    }
    let eip = *instruction_pointer;
    if 0 != eip & !0xFFF ^ *last_virt_eip {
        let phys = translate_address_read(eip)?;
        cache_fetch_page(eip, phys);
        return Ok(phys);
    }
    let phys_addr = (*eip_phys ^ eip) as u32;
    return Ok(phys_addr);
}

/// Diagnostics (off by default): the last interpreted instructions as
/// (EIP, ESP, CR3, EAX, EBX, EDX), for debugging guests that jump into
/// garbage. Debug builds only; compiled code is not traced (use disable_jit).
/// EIP is the opcode byte (after any prefixes).
const INSTRUCTION_TRACE_LEN: usize = 4096;
static mut INSTRUCTION_TRACE: [[u32; 6]; INSTRUCTION_TRACE_LEN] = [[0; 6]; INSTRUCTION_TRACE_LEN];
static mut INSTRUCTION_TRACE_NEXT: usize = 0;
static mut INSTRUCTION_TRACE_ENABLED: bool = false;
#[cold]
#[inline(never)]
unsafe fn instruction_trace_note(eip: i32) {
    INSTRUCTION_TRACE[INSTRUCTION_TRACE_NEXT % INSTRUCTION_TRACE_LEN] = [
        eip as u32,
        *reg32.offset(ESP as isize) as u32,
        *cr.offset(3) as u32,
        *reg32.offset(EAX as isize) as u32,
        *reg32.offset(EBX as isize) as u32,
        *reg32.offset(EDX as isize) as u32,
    ];
    INSTRUCTION_TRACE_NEXT += 1;
}
#[no_mangle]
pub unsafe fn instruction_trace_enable(enabled: bool) {
    INSTRUCTION_TRACE_ENABLED = enabled;
    INSTRUCTION_TRACE_NEXT = 0;
}
#[no_mangle]
pub unsafe fn instruction_trace_count() -> u32 {
    INSTRUCTION_TRACE_NEXT.min(INSTRUCTION_TRACE_LEN) as u32
}
/// `index` 0 is the most recent instruction
#[no_mangle]
pub unsafe fn instruction_trace_get(index: u32, field: u32) -> u32 {
    if index as usize >= INSTRUCTION_TRACE_LEN.min(INSTRUCTION_TRACE_NEXT) || field >= 6 {
        return 0;
    }
    INSTRUCTION_TRACE[(INSTRUCTION_TRACE_NEXT - 1 - index as usize) % INSTRUCTION_TRACE_LEN]
        [field as usize]
}

/// The x64 page tier's misses in 16-bit code (pages::miss_run,
/// docs/jit-unification-plan.md P7.8): a basic block in the interpreter, as
/// code without compiled code runs; the instructions it retired (0 when the
/// fetch faulted, the fault delivered)
pub unsafe fn run_interpreted_block(budget: u32) -> u32 {
    let before = *instruction_counter;
    // (a fault restores EIP from here; jit_run_interpreted sets it between
    // instructions)
    *previous_ip = *instruction_pointer;
    if let Ok(phys_addr) = get_phys_eip() {
        jit_run_interpreted(phys_addr, budget);
    }
    (*instruction_counter).wrapping_sub(before)
}

unsafe fn jit_run_interpreted(mut phys_addr: u32, budget: u32) {
    profiler::stat_increment(stat::RUN_INTERPRETED);

    jit_block_boundary = false;
    // (the page tier gathers heat at outer dispatch: a same-page interpreted
    // loop returns at its back edge, or after 64 instructions)
    let ir_dispatch = crate::jit::enabled();
    let before = *instruction_counter;
    let mut i = 0;

    loop {
        i += 1;
        let start_eip = *instruction_pointer;
        // A remapped low RAM page is an open bus, never the high RAM backing.
        // Compatibility mode has already resolved a full physical RAM
        // address (fetch_through_bus).
        let opcode = if fetch_through_bus(phys_addr) {
            memory::fetch8(phys_addr)
        }
        else {
            *memory::mem8.offset(phys_addr as isize) as i32
        };
        *instruction_pointer += 1;
        dbg_assert!(*prefixes == 0);
        let tracked = crate::cpu::execution::is_deterministic();
        crate::cpu::execution::begin_instruction();
        run_instruction(opcode | (*is_32 as i32) << 8);
        crate::cpu::execution::finish_instruction();
        if tracked {
            if *interrupt_shadow != 0 {
                *interrupt_shadow -= 1;
            }
            handle_irqs();
        }
        dbg_assert!(*prefixes == 0);

        if ir_dispatch && (i >= 64 || (*instruction_pointer as u32) <= start_eip as u32) {
            break;
        }

        // STI may execute its one shadow instruction recursively. Account
        // for that work too; at most that one instruction exceeds a slice.
        if (budget != u32::MAX && i + (*instruction_counter).wrapping_sub(before) >= budget)
            || jit_block_boundary
            // (64-bit mode: CS.L is only ever set with EFER.LMA)
            || *x64_cs_long != 0
            || Page::page_of(start_eip as u32) != Page::page_of(*instruction_pointer as u32)
                // Limit the number of iterations, as jumps within the same page are not counted as
                // block boundaries for the interpreter, but only on the next backwards jump
            || (i >= INTERPRETER_ITERATION_LIMIT
                && (start_eip as u32) >= (*instruction_pointer as u32))
        {
            break;
        }

        *previous_ip = *instruction_pointer;
        phys_addr = return_on_pagefault!(get_phys_eip()) as u32;
    }

    if cfg!(debug_assertions) {
        debug_last_jump = LastJump::Interpreted { phys_addr };
    }

    *instruction_counter += i;
}

/// The wide interpreter is the authoritative fallback until wide native IR
/// has passed its own admission/differential gates.
pub unsafe fn run_long_instruction() {
    let trap = *flags & FLAG_TRAP != 0;
    let resume = *flags & FLAG_RF != 0;
    crate::cpu::execution::begin_instruction();
    crate::cpu::execution::set_irq_deferral(true);
    let result = crate::x64::debug::begin().and_then(|()| crate::x64::execute::step());
    crate::cpu::execution::set_irq_deferral(false);
    let completed = match result {
        Ok(()) => true,
        Err(fault) => {
            crate::x64::system::raise(fault);
            false
        },
    };
    crate::cpu::execution::finish_instruction();
    *instruction_counter = (*instruction_counter).wrapping_add(1);
    if *interrupt_shadow != 0 {
        *interrupt_shadow -= 1;
    }
    if completed {
        if resume {
            *flags &= !FLAG_RF;
        }
    }
    if crate::x64::debug::finish(completed, trap) {
        crate::cpu::exceptions::trap(1);
    }
    handle_irqs();
}

/// One instruction of 32-bit compatibility-mode code in the 32-bit
/// interpreter, with run_long_instruction's bookkeeping: the x64 page tier's
/// steps, retries and misses in compatibility mode (x64_page_compat32,
/// docs/jit-unification-plan.md P7.2, and in legacy mode, P7.3). A fetch
/// fault is delivered and, as in the 32-bit interpreter loop
/// (cycle_internal), not counted (cross-phase rule 3).
pub unsafe fn run_compat_instruction() {
    let (shadow, interrupts) = (*interrupt_shadow, *flags & FLAG_INTERRUPT);
    *previous_ip = *instruction_pointer;
    crate::cpu::execution::begin_instruction();
    crate::cpu::execution::set_irq_deferral(true);
    let fetched = get_phys_eip();
    if let Ok(phys_addr) = fetched {
        // (as jit_run_interpreted fetches: the page tier steps legacy modes
        // here too)
        let opcode = if fetch_through_bus(phys_addr) {
            memory::fetch8(phys_addr)
        }
        else {
            *memory::mem8.offset(phys_addr as isize) as i32
        };
        *instruction_pointer += 1;
        run_instruction(opcode | (*is_32 as i32) << 8);
    }
    crate::cpu::execution::set_irq_deferral(false);
    crate::cpu::execution::finish_instruction();
    *instruction_counter = (*instruction_counter).wrapping_add(fetched.is_ok() as u32);
    if *interrupt_shadow != 0 {
        *interrupt_shadow -= 1;
    }
    // Only where an interrupt can have become deliverable (P7.3: a poll
    // after each of the page tier's interpreted instructions cost an XP boot
    // 2%): a shadow ended, IF set, handle_irqs called while held (a device
    // raised one; the APIC, IOAPIC, POPF, IRET and STI call it), the PIC's
    // registers written (an EOI or unmask), events of other cores, NMI, SMI.
    // Nothing else makes one deliverable between instructions: timers raise
    // theirs at main-loop boundaries, which look.
    if shadow != 0
        || *flags & FLAG_INTERRUPT & !interrupts != 0
        || crate::cpu::execution::irq_check_owed()
        || pic::take_port_written()
        || apic::has_core_events()
        || *acpi_enabled && apic::nmi_pending()
        || crate::cpu::smm::smi_deliverable()
    {
        handle_irqs();
    }
}

/// The cooperative scheduler's interpreter slice. Device clocks are serviced once by
/// the machine scheduler, outside this entry. Yield only after a complete
/// instruction or the string engine's resumable REP element batch; a LOCK
/// transaction cannot be split by switching cores.
#[no_mangle]
pub unsafe fn run_cpu_slice(budget: u32) -> u32 {
    core_yield = false;
    crate::parallel::sync_worker_configuration();
    handle_irqs();
    let before = *instruction_counter;
    let mut remaining = budget;
    jit_link_batch_start = before;
    jit_link_batch_limit = budget;
    jit_link_batch = true;
    let native = crate::jit::enabled();
    // (P7.2, P7.3: a switch hands 32-bit code to the page tier)
    let page32 = native && crate::x64::pages::page32();
    while remaining != 0 && !*in_hlt && !core_yield {
        // (as in do_many_cycles_native: other cores' code publications and
        // code writes are taken between entries, so a core installing code
        // waits for an activation of this one, not its slice; extended RAM
        // frames held by access caches are released)
        crate::parallel::code::poll();
        crate::x64::extended::safe_point();
        *previous_ip = *instruction_pointer;
        // A fault can change CS:EIP without retiring an instruction. Charge
        // that dispatch as well, so a fault loop cannot monopolize the host.
        let count = *instruction_counter;
        *slice_budget = remaining;
        if crate::x64::state::mode().is_long() {
            let attempt = if native {
                crate::x64::pages::run(remaining)
            }
            else {
                crate::x64::pages::Attempt {
                    retired: 0,
                    submitted: false,
                }
            };
            if attempt.retired == 0 {
                let span = crate::cpu::execution::ledger_begin();
                run_long_instruction();
                crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
            }
            remaining = remaining.saturating_sub(attempt.retired.max(1));
            if attempt.submitted {
                break;
            }
            continue;
        }
        // 32-bit compatibility-mode code in the x64 page tier
        // (x64_page_compat32, docs/jit-unification-plan.md P7.2), and legacy
        // protected-mode code (x64_page_legacy32, P7.3)
        if page32 && !crate::cpu::execution::is_deterministic() && crate::x64::pages::runnable32() {
            let attempt = crate::x64::pages::run(remaining);
            if attempt.retired == 0 && still_32_bit_code() {
                let span = crate::cpu::execution::ledger_begin();
                run_compat_instruction();
                crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
            }
            remaining = remaining.saturating_sub(attempt.retired.max(1));
            if attempt.submitted {
                break;
            }
            continue;
        }
        if let Ok(phys_addr) = get_phys_eip() {
            let span = crate::cpu::execution::ledger_begin();
            jit_run_interpreted(phys_addr, remaining);
            crate::cpu::execution::ledger_end(span, crate::cpu::execution::Way::Interpreted);
        }
        remaining = remaining.saturating_sub((*instruction_counter).wrapping_sub(count).max(1));
        if apic::has_core_events() {
            break;
        }
    }
    jit_link_batch = false;
    core_yield = false;
    (*instruction_counter).wrapping_sub(before)
}

#[no_mangle]
pub fn update_state_flags() {
    unsafe {
        *state_flags = CachedStateFlags::of_u32(
            (*is_32 as u32) << 0
                | (*stack_size_32 as u32) << 1
                | ((*cpl == 3) as u32) << 2
                | (has_flat_segmentation() as u32) << 3,
        )
    }
}

#[no_mangle]
pub unsafe fn has_flat_segmentation() -> bool {
    // cs/ss can't be null
    return *segment_offsets.offset(SS as isize) == 0
        && !*segment_is_null.offset(DS as isize)
        && *segment_offsets.offset(DS as isize) == 0
        && *segment_offsets.offset(CS as isize) == 0;
}

pub unsafe fn run_prefix_instruction() {
    run_instruction(return_on_pagefault!(read_imm8()) | (is_osize_32() as i32) << 8);
}

pub unsafe fn segment_prefix_op(seg: i32) {
    dbg_assert!(seg <= 5 && seg >= 0);
    *prefixes = crate::decode_rules::apply_prefix(
        *prefixes,
        [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][seg as usize],
    )
    .unwrap();
    run_prefix_instruction();
    *prefixes = 0
}

#[no_mangle]
pub unsafe fn main_loop() -> f64 {
    profiler::stat_increment(stat::MAIN_LOOP);

    let start = js::microtick();

    if *in_hlt {
        if *flags & FLAG_INTERRUPT != 0
            || *acpi_enabled && !*nmi_blocked && apic::nmi_pending()
            || crate::cpu::smm::smi_deliverable()
        {
            let t = js::run_hardware_timers(*acpi_enabled, start);
            handle_irqs();
            if *in_hlt {
                profiler::stat_increment(stat::MAIN_LOOP_IDLE);
                return t.max(0.0);
            }
        }
        else {
            // dead
            return 100.0;
        }
    }

    let mut batches = 0;
    loop {
        batches += 1;
        let publication_yield = do_many_cycles_native();

        let now = js::microtick();
        let t = js::run_hardware_timers(*acpi_enabled, now);
        handle_irqs();
        if *in_hlt {
            return t.max(0.0);
        }
        if core_yield {
            core_yield = false;
            return 0.0;
        }

        // Give the host a chance to install a newly submitted IR module. All
        // guest state is committed and the normal timer/IRQ work above is kept.
        // Only a new submission requests this; a held Promise cannot spin here.
        if publication_yield || now - start > TIME_PER_FRAME || batches >= 16 {
            break;
        }
    }

    return 0.0;
}

// The CPU batch in progress: IR chaining stops at the batch's instruction
// budget, as the outer loop would.
static mut jit_link_batch: bool = false;
static mut jit_link_batch_start: u32 = 0;
static mut jit_link_batch_limit: u32 = LOOP_COUNTER as u32;
pub unsafe fn ir_link_budget_available() -> bool {
    jit_link_batch
        && !core_yield
        && !apic::has_core_events()
        && (*instruction_counter).wrapping_sub(jit_link_batch_start) < jit_link_batch_limit
}

pub unsafe fn do_many_cycles_native() -> bool {
    let mut publication_yield = false;
    profiler::stat_increment(stat::DO_MANY_CYCLES);
    let initial_instruction_counter = *instruction_counter;
    jit_link_batch_start = initial_instruction_counter;
    jit_link_batch_limit = LOOP_COUNTER as u32;
    *slice_budget = LOOP_COUNTER as u32;
    jit_link_batch = true;
    while (*instruction_counter).wrapping_sub(initial_instruction_counter) < LOOP_COUNTER as u32
        && !*in_hlt
        && !core_yield
    {
        // With cores in workers: acknowledge other cores' code publications
        // and take their code writes between entries, so that a core
        // installing code rarely waits for this one (crate::parallel::code;
        // two loads when nothing is new, nothing in the normal build)
        crate::parallel::code::poll();
        crate::x64::extended::safe_point();
        if cycle_internal() {
            publication_yield = true;
            break;
        }
    }
    jit_link_batch = false;
    publication_yield
}

#[cold]
pub unsafe fn trigger_de() {
    crate::cpu::execution::mark_fault();
    dbg_log!("#de");
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_DE) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_DE, None);
}

#[inline(never)]
pub unsafe fn trigger_ud() {
    crate::cpu::execution::mark_fault();
    dbg_log!("#ud");
    dbg_trace();
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_UD) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_UD, None);
}

#[inline(never)]
pub unsafe fn trigger_nm() {
    crate::cpu::execution::mark_fault();
    dbg_log!("#nm eip={:x}", *previous_ip);
    dbg_trace();
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_NM) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_NM, None);
}

#[inline(never)]
pub unsafe fn trigger_gp(code: i32) {
    crate::cpu::execution::mark_fault();
    dbg_log!("#gp");
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_GP) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_GP, Some(code));
}

/// An unmasked SIMD floating-point exception (cpu/simd_fp.rs): #XM, or #UD
/// without CR4.OSXMMEXCPT
#[inline(never)]
pub unsafe fn trigger_simd_fp() {
    if *cr.offset(4) & CR4_OSXMMEXCPT == 0 {
        trigger_ud();
        return;
    }
    crate::cpu::execution::mark_fault();
    dbg_log!("#xm");
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_XM) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_XM, None);
}

#[cold]
pub unsafe fn virt_boundary_read16(low: u32, high: u32) -> i32 {
    dbg_assert!(low & 0xFFF == 0xFFF);
    dbg_assert!(high & 0xFFF == 0);
    return memory::read8(low as u32) | memory::read8(high as u32) << 8;
}

#[cold]
pub unsafe fn virt_boundary_read32s(low: u32, high: u32) -> i32 {
    dbg_assert!(low & 0xFFF >= 0xFFD);
    dbg_assert!(high - 3 & 0xFFF == low & 0xFFF);
    let mid;
    if 0 != low & 1 {
        if 0 != low & 2 {
            // 0xFFF
            mid = memory::read16(high - 2)
        }
        else {
            // 0xFFD
            mid = memory::read16(low + 1)
        }
    }
    else {
        // 0xFFE
        mid = virt_boundary_read16(low + 1, high - 1)
    }
    return memory::read8(low as u32) | mid << 8 | memory::read8(high as u32) << 24;
}

#[cold]
pub unsafe fn virt_boundary_write16(low: u32, high: u32, value: i32) {
    dbg_assert!(low & 0xFFF == 0xFFF);
    dbg_assert!(high & 0xFFF == 0);
    memory::write8(low as u32, value);
    memory::write8(high as u32, value >> 8);
}

#[cold]
pub unsafe fn virt_boundary_write32(low: u32, high: u32, value: i32) {
    dbg_assert!(low & 0xFFF >= 0xFFD);
    dbg_assert!(high - 3 & 0xFFF == low & 0xFFF);
    memory::write8(low as u32, value);
    if 0 != low & 1 {
        if 0 != low & 2 {
            // 0xFFF
            memory::write8((high - 2) as u32, value >> 8);
            memory::write8((high - 1) as u32, value >> 16);
        }
        else {
            // 0xFFD
            memory::write8((low + 1) as u32, value >> 8);
            memory::write8((low + 2) as u32, value >> 16);
        }
    }
    else {
        // 0xFFE
        memory::write8((low + 1) as u32, value >> 8);
        memory::write8((high - 1) as u32, value >> 16);
    }
    memory::write8(high as u32, value >> 24);
}

/// Compatibility mode: the backing of `bytes` bytes at `addr` (not crossing a
/// page) when the 32-bit TLB has the page for this access (writes: neither
/// read-only nor with compiled code), else None. Entries are x64
/// translations of 32-bit linear addresses (fill_ia32e_tlb), of RAM or an
/// extended RAM frame: plain memory, possibly outside the guest's RAM range,
/// so callers read and write the wasm memory directly.
#[inline(always)]
unsafe fn ia32e_compat_backing(addr: i32, bytes: u32, write: bool) -> Option<u32> {
    if *x64_cs_long != 0 || (addr as u32 & 0xFFF) > 0x1000 - bytes {
        return None;
    }
    let entry = tlb_data[(addr as u32 >> 12) as usize];
    let mask = TLB_VALID
        | if *cpl == 3 { TLB_NO_USER } else { 0 }
        | if write { TLB_READONLY | TLB_HAS_CODE } else { 0 };
    if entry & mask != TLB_VALID {
        return None;
    }
    Some(((entry & !0xFFF ^ addr) as u32).wrapping_sub(memory::mem8 as u32))
}
#[inline(always)]
unsafe fn compat_host(backing: u32) -> *mut u8 { memory::mem8.wrapping_add(backing as usize) }

pub unsafe fn safe_read8(addr: i32) -> OrPageFault<i32> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 1, false) {
            return Ok(*compat_host(backing) as i32);
        }
        return ia32e_read(addr, 8).map(|value| value as i32);
    }
    Ok(memory::read8(translate_address_read(addr)?))
}

pub unsafe fn safe_read16(addr: i32) -> OrPageFault<i32> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 2, false) {
            return Ok(memory::read16_no_mmap_check(backing));
        }
        return ia32e_read(addr, 16).map(|value| value as i32);
    }
    if addr & 0xFFF == 0xFFF {
        Ok(safe_read8(addr)? | safe_read8(addr + 1)? << 8)
    }
    else {
        Ok(memory::read16(translate_address_read(addr)?))
    }
}

pub unsafe fn safe_read32s(addr: i32) -> OrPageFault<i32> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 4, false) {
            return Ok(memory::read32_no_mmap_check(backing));
        }
        return ia32e_read(addr, 32).map(|value| value as i32);
    }
    if addr & 0xFFF >= 0xFFD {
        Ok(safe_read16(addr)? | safe_read16(addr + 2)? << 16)
    }
    else {
        Ok(memory::read32s(translate_address_read(addr)?))
    }
}

pub unsafe fn safe_read_f32(addr: i32) -> OrPageFault<f32> {
    Ok(f32::from_bits(i32::cast_unsigned(safe_read32s(addr)?)))
}

pub unsafe fn safe_read64s(addr: i32) -> OrPageFault<u64> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 8, false) {
            return Ok(std::ptr::read_unaligned(compat_host(backing) as *const u64));
        }
        return ia32e_read(addr, 64);
    }
    if addr & 0xFFF > 0x1000 - 8 {
        Ok(safe_read32s(addr)? as u32 as u64 | (safe_read32s(addr + 4)? as u32 as u64) << 32)
    }
    else {
        Ok(memory::read64s(translate_address_read(addr)?) as u64)
    }
}

/// The m128 operand of a legacy SSE form other than MOVUPS, MOVUPD, MOVDQU
/// and LDDQU (exception type 4, SDM vol. 2 table 2-21): #GP(0) unless
/// 16-byte aligned, whatever the segment, before any page fault
pub unsafe fn aligned16(addr: i32) -> OrPageFault<()> {
    if addr & 15 != 0 {
        trigger_gp(0);
        return Err(());
    }
    Ok(())
}
pub unsafe fn safe_read128s_aligned(addr: i32) -> OrPageFault<reg128> {
    aligned16(addr)?;
    safe_read128s(addr)
}

pub unsafe fn safe_read128s(addr: i32) -> OrPageFault<reg128> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return ia32e_read128(addr);
    }
    if addr & 0xFFF > 0x1000 - 16 {
        Ok(reg128 {
            u64: [safe_read64s(addr)?, safe_read64s(addr + 8)?],
        })
    }
    else {
        Ok(memory::read128(translate_address_read(addr)?))
    }
}

pub unsafe fn safe_write8(addr: i32, value: i32) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 1, true) {
            memory::write8_no_mmap_or_dirty_check(backing, value);
            return Ok(());
        }
        return ia32e_write(addr, 8, value as u32 as u64);
    }
    let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
    if memory::in_mapped_range(phys_addr) {
        memory::mmap_write8(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 1);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        memory::write8_no_mmap_or_dirty_check(phys_addr, value);
    };
    Ok(())
}

pub unsafe fn safe_write16(addr: i32, value: i32) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 2, true) {
            memory::write16_no_mmap_or_dirty_check(backing, value);
            return Ok(());
        }
        return ia32e_write(addr, 16, value as u32 as u64);
    }
    let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
    dbg_assert!(value >= 0 && value < 0x10000);
    if addr & 0xFFF == 0xFFF {
        virt_boundary_write16(phys_addr, translate_address_write(addr + 1)?, value);
    }
    else if memory::in_mapped_range(phys_addr) {
        memory::mmap_write16(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 2);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        memory::write16_no_mmap_or_dirty_check(phys_addr, value);
    };
    Ok(())
}

pub unsafe fn safe_write32(addr: i32, value: i32) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 4, true) {
            memory::write32_no_mmap_or_dirty_check(backing, value);
            return Ok(());
        }
        return ia32e_write(addr, 32, value as u32 as u64);
    }
    let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
    if addr & 0xFFF > 0x1000 - 4 {
        virt_boundary_write32(
            phys_addr,
            translate_address_write(addr + 3 & !3)? | (addr as u32 + 3 & 3),
            value,
        );
    }
    else if memory::in_mapped_range(phys_addr) {
        memory::mmap_write32(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 4);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        memory::write32_no_mmap_or_dirty_check(phys_addr, value);
    };
    Ok(())
}

pub unsafe fn safe_write64(addr: i32, value: u64) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Some(backing) = ia32e_compat_backing(addr, 8, true) {
            memory::write64_no_mmap_or_dirty_check(backing, value);
            return Ok(());
        }
        return ia32e_write(addr, 64, value);
    }
    if addr & 0xFFF > 0x1000 - 8 {
        writable_or_pagefault(addr, 8)?;
        safe_write32(addr, value as i32).unwrap();
        safe_write32(addr + 4, (value >> 32) as i32).unwrap();
    }
    else {
        let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
        if memory::in_mapped_range(phys_addr) {
            memory::mmap_write64(phys_addr, value);
        }
        else {
            if !can_skip_dirty_page {
                jit::jit_dirty_bytes(phys_addr, 8);
            }
            else {
                dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
            }
            memory::write64_no_mmap_or_dirty_check(phys_addr, value);
        }
    };
    Ok(())
}

pub unsafe fn safe_write128(addr: i32, value: reg128) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        return ia32e_write128(addr, value);
    }
    if addr & 0xFFF > 0x1000 - 16 {
        writable_or_pagefault(addr, 16)?;
        safe_write64(addr, value.u64[0]).unwrap();
        safe_write64(addr + 8, value.u64[1]).unwrap();
    }
    else {
        let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
        if memory::in_mapped_range(phys_addr) {
            memory::mmap_write128(phys_addr, value.u64[0], value.u64[1]);
        }
        else {
            if !can_skip_dirty_page {
                jit::jit_dirty_bytes(phys_addr, 16);
            }
            else {
                dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
            }
            memory::write128_no_mmap_or_dirty_check(phys_addr, value);
        }
    };
    Ok(())
}

#[cold]
#[inline(never)]
unsafe fn wide_read_write(
    addr: i32,
    width: u8,
    instruction: &dyn Fn(i32) -> i32,
) -> OrPageFault<()> {
    let linear = addr as u32 as u64;
    // (a locked commit when other cores run in workers, see x64::memory::run_locked)
    crate::x64::memory::run_locked(|| {
        crate::x64::memory::probe_write(linear, width, false)?;
        let value = crate::x64::memory::read(linear, width, false)?;
        let result = instruction(value as i32);
        crate::x64::memory::write(linear, width, result as u32 as u64, false)
    })
    .map_err(|fault| crate::x64::system::raise(fault))
}

/// Commit `instruction` applied to the RAM operand at `phys_addr` (naturally
/// sized access within one page): read, compute, then store only if the
/// operand is unchanged, else start over. With one core, a plain store.
#[inline(always)]
unsafe fn read_write_ram(phys_addr: u32, bytes: u32, instruction: &dyn Fn(i32) -> i32) {
    #[cfg(feature = "parallel")]
    let saved = crate::cpu::isa_hooks::Registers::save();
    loop {
        let x = match bytes {
            1 => memory::read8_no_mmap_check(phys_addr),
            2 => memory::read16_no_mmap_check(phys_addr),
            _ => memory::read32_no_mmap_check(phys_addr),
        };
        let value = instruction(x);
        dbg_assert!(bytes == 4 || value >= 0 && value < 1 << (8 * bytes));
        let mask = if bytes == 4 { u32::MAX as u64 } else { (1 << 8 * bytes) - 1 };
        if memory::compare_exchange_no_mmap_or_dirty_check(
            phys_addr,
            bytes,
            x as u32 as u64 & mask,
            value as u32 as u64 & mask,
        ) {
            return;
        }
        #[cfg(feature = "parallel")]
        saved.restore();
    }
}

#[inline(always)]
pub unsafe fn safe_read_write8(addr: i32, instruction: &dyn Fn(i32) -> i32) {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode, the page in the 32-bit TLB: as below)
        if let Some(backing) = ia32e_compat_backing(addr, 1, true) {
            read_write_ram(backing, 1, instruction);
            return;
        }
        let _ = wide_read_write(addr, 8, instruction);
        return;
    }
    let (phys_addr, can_skip_dirty_page) =
        return_on_pagefault!(translate_address_write_and_can_skip_dirty(addr));
    if memory::in_mapped_range(phys_addr) {
        let x = memory::read8(phys_addr);
        let value = instruction(x);
        dbg_assert!(value >= 0 && value < 0x100);
        memory::mmap_write8(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 1);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        read_write_ram(phys_addr, 1, instruction);
    }
}

#[inline(always)]
pub unsafe fn safe_read_write16(addr: i32, instruction: &dyn Fn(i32) -> i32) {
    let _ = safe_read_write16_checked(addr, instruction);
}

pub unsafe fn safe_read_write16_checked(
    addr: i32,
    instruction: &dyn Fn(i32) -> i32,
) -> OrPageFault<()> {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode, the page in the 32-bit TLB: as below)
        if let Some(backing) = ia32e_compat_backing(addr, 2, true) {
            read_write_ram(backing, 2, instruction);
            return Ok(());
        }
        return wide_read_write(addr, 16, instruction);
    }
    let (phys_addr, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr)?;
    if phys_addr & 0xFFF == 0xFFF {
        let phys_addr_high = translate_address_write(addr + 1)?;
        // (a split operand: locked only against other split locked operations)
        crate::parallel::split_lock().lock();
        let x = virt_boundary_read16(phys_addr, phys_addr_high);
        virt_boundary_write16(phys_addr, phys_addr_high, instruction(x));
        crate::parallel::split_lock().unlock();
    }
    else if memory::in_mapped_range(phys_addr) {
        let x = memory::read16(phys_addr);
        let value = instruction(x);
        dbg_assert!(value >= 0 && value < 0x10000);
        memory::mmap_write16(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 2);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        read_write_ram(phys_addr, 2, instruction);
    }
    Ok(())
}

#[inline(always)]
pub unsafe fn safe_read_write32(addr: i32, instruction: &dyn Fn(i32) -> i32) {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode, the page in the 32-bit TLB: as below)
        if let Some(backing) = ia32e_compat_backing(addr, 4, true) {
            read_write_ram(backing, 4, instruction);
            return;
        }
        let _ = wide_read_write(addr, 32, instruction);
        return;
    }
    let (phys_addr, can_skip_dirty_page) =
        return_on_pagefault!(translate_address_write_and_can_skip_dirty(addr));
    if phys_addr & 0xFFF >= 0xFFD {
        let phys_addr_high = return_on_pagefault!(translate_address_write(addr + 3 & !3));
        let phys_addr_high = phys_addr_high | (addr as u32) + 3 & 3;
        crate::parallel::split_lock().lock();
        let x = virt_boundary_read32s(phys_addr, phys_addr_high);
        virt_boundary_write32(phys_addr, phys_addr_high, instruction(x));
        crate::parallel::split_lock().unlock();
    }
    else if memory::in_mapped_range(phys_addr) {
        let x = memory::read32s(phys_addr);
        let value = instruction(x);
        memory::mmap_write32(phys_addr, value);
    }
    else {
        if !can_skip_dirty_page {
            jit::jit_dirty_bytes(phys_addr, 4);
        }
        else {
            dbg_assert!(!jit::jit_page_has_code(Page::page_of(phys_addr as u32)));
        }
        read_write_ram(phys_addr, 4, instruction);
    }
}

fn get_reg8_index(index: i32) -> i32 { return index << 2 & 12 | index >> 2 & 1; }

pub unsafe fn read_reg8(index: i32) -> i32 {
    dbg_assert!(index >= 0 && index < 8);
    return *reg8.offset(get_reg8_index(index) as isize) as i32;
}

pub unsafe fn write_reg8(index: i32, value: i32) {
    dbg_assert!(index >= 0 && index < 8);
    *reg8.offset(get_reg8_index(index) as isize) = value as u8;
}

fn get_reg16_index(index: i32) -> i32 { return index << 1; }

pub unsafe fn read_reg16(index: i32) -> i32 {
    dbg_assert!(index >= 0 && index < 8);
    return *reg16.offset(get_reg16_index(index) as isize) as i32;
}

pub unsafe fn write_reg16(index: i32, value: i32) {
    dbg_assert!(index >= 0 && index < 8);
    *reg16.offset(get_reg16_index(index) as isize) = value as u16;
}

pub unsafe fn read_reg32(index: i32) -> i32 {
    dbg_assert!(index >= 0 && index < 8);
    *reg32.offset(index as isize)
}

pub unsafe fn write_reg32(index: i32, value: i32) {
    dbg_assert!(index >= 0 && index < 8);
    *reg32.offset(index as isize) = value;
}

pub unsafe fn read_mmx32s(r: i32) -> i32 {
    crate::cpu::fpu::fpu_sync_slot(r as u32);
    (*fpu_st.offset(r as isize)).mantissa as i32
}

pub unsafe fn read_mmx64s(r: i32) -> u64 {
    crate::cpu::fpu::fpu_sync_slot(r as u32);
    (*fpu_st.offset(r as isize)).mantissa
}

pub unsafe fn write_mmx_reg64(r: i32, data: u64) {
    crate::cpu::fpu::fpu_invalidate_slot(r as u32);
    *fpu_st.offset(r as isize) = softfloat::F80 {
        mantissa: data,
        sign_exponent: 0xFFFF,
    };
}

// XMM0..7 retain the legacy ABI; XMM8..15 use the per-core wide bank.
#[inline]
unsafe fn xmm_register_pointer(r: i32) -> *mut reg128 {
    crate::x64::state::xmm_offset(r as usize) as *mut reg128
}

pub unsafe fn read_xmm_f32(r: i32) -> f32 { return (*xmm_register_pointer(r)).f32[0]; }

pub unsafe fn read_xmm32(r: i32) -> i32 { return (*xmm_register_pointer(r)).u32[0] as i32; }

pub unsafe fn read_xmm64s(r: i32) -> u64 { (*xmm_register_pointer(r)).u64[0] }

pub unsafe fn read_xmm128s(r: i32) -> reg128 { return *xmm_register_pointer(r); }

pub unsafe fn write_xmm_f32(r: i32, data: f32) { (*xmm_register_pointer(r)).f32[0] = data; }

pub unsafe fn write_xmm32(r: i32, data: i32) { (*xmm_register_pointer(r)).i32[0] = data; }

pub unsafe fn write_xmm64(r: i32, data: u64) { (*xmm_register_pointer(r)).u64[0] = data }
pub unsafe fn write_xmm_f64(r: i32, data: f64) { (*xmm_register_pointer(r)).f64[0] = data }

pub unsafe fn write_xmm128(r: i32, i0: i32, i1: i32, i2: i32, i3: i32) {
    let x = reg128 {
        u32: [i0 as u32, i1 as u32, i2 as u32, i3 as u32],
    };
    *xmm_register_pointer(r) = x;
}

pub unsafe fn write_xmm128_2(r: i32, i0: u64, i1: u64) {
    *xmm_register_pointer(r) = reg128 { u64: [i0, i1] };
}

pub unsafe fn write_xmm_reg128(r: i32, data: reg128) { *xmm_register_pointer(r) = data; }

/// Set the fpu tag word to valid and the top-of-stack to 0 on mmx instructions
#[no_mangle]
pub fn transition_fpu_to_mmx() {
    unsafe {
        fpu_set_tag_word(0);
        *fpu_stack_ptr = 0;
    }
}

pub unsafe fn task_switch_test() -> bool {
    if 0 != *cr & (CR0_EM | CR0_TS) {
        trigger_nm();
        return false;
    }
    else {
        return true;
    };
}

/// RC, DAZ, FZ and the exception masks apply through cpu::simd_fp
pub unsafe fn set_mxcsr(new_mxcsr: i32) {
    dbg_assert!(new_mxcsr & !MXCSR_MASK == 0); // checked by caller
    *mxcsr = new_mxcsr;
}

/// The checks of an MMX form (gen/x86_table.js mmx_form): #UD with CR0.EM,
/// then #NM with CR0.TS
pub unsafe fn task_switch_test_mmx() -> bool {
    if 0 != *cr & CR0_EM {
        trigger_ud();
        return false;
    }
    else if 0 != *cr & CR0_TS {
        trigger_nm();
        return false;
    }
    else {
        return true;
    };
}

/// The checks of a legacy SSE XMM form: #UD with CR0.EM or without
/// CR4.OSFXSR, then #NM with CR0.TS
pub unsafe fn task_switch_test_xmm() -> bool {
    if 0 != *cr & CR0_EM || 0 == *cr.offset(4) & CR4_OSFXSR {
        trigger_ud();
        return false;
    }
    else if 0 != *cr & CR0_TS {
        trigger_nm();
        return false;
    }
    else {
        return true;
    };
}

pub unsafe fn read_moffs() -> OrPageFault<i32> {
    // read 2 or 4 byte from ip, depending on address size attribute
    if is_asize_32() {
        read_imm32s()
    }
    else {
        read_imm16()
    }
}

#[no_mangle]
pub unsafe fn get_real_eip() -> i32 {
    // Returns the 'real' instruction pointer, without segment offset
    return *instruction_pointer - get_seg_cs();
}

pub unsafe fn get_stack_reg() -> i32 {
    if *stack_size_32 {
        return read_reg32(ESP);
    }
    else {
        return read_reg16(SP);
    };
}

pub unsafe fn set_stack_reg(value: i32) {
    if *stack_size_32 {
        write_reg32(ESP, value)
    }
    else {
        write_reg16(SP, value)
    };
}

pub unsafe fn get_reg_asize(reg: i32) -> i32 {
    dbg_assert!(reg == ECX || reg == ESI || reg == EDI);
    let r = read_reg32(reg);
    if is_asize_32() {
        return r;
    }
    else {
        return r & 0xFFFF;
    };
}

pub unsafe fn set_reg_asize(is_asize_32: bool, reg: i32, value: i32) {
    dbg_assert!(reg == ECX || reg == ESI || reg == EDI);
    if is_asize_32 {
        write_reg32(reg, value)
    }
    else {
        write_reg16(reg, value)
    };
}

pub unsafe fn decr_ecx_asize(is_asize_32: bool) -> i32 {
    return if is_asize_32 {
        write_reg32(ECX, read_reg32(ECX) - 1);
        read_reg32(ECX)
    }
    else {
        write_reg16(CX, read_reg16(CX) - 1);
        read_reg16(CX)
    };
}

#[no_mangle]
pub unsafe fn set_tsc(low: u32, high: u32) {
    let new_value = low as u64 | (high as u64) << 32;
    let current_value = (js::microtick() * TSC_RATE) as u64;
    tsc_offset = current_value.wrapping_sub(new_value);
}

#[no_mangle]
pub unsafe fn read_tsc() -> u64 { ((js::microtick() * TSC_RATE) as u64).wrapping_sub(tsc_offset) }

pub unsafe fn vm86_mode() -> bool { return *flags & FLAG_VM == FLAG_VM; }

#[no_mangle]
pub unsafe fn getiopl() -> i32 { return *flags >> 12 & 3; }

pub unsafe fn invlpg(addr: i32) {
    let page = (addr as u32 >> 12) as i32;
    // Note: Doesn't remove this page from valid_tlb_entries: This isn't
    // necessary, because when valid_tlb_entries grows too large, it will be
    // empties by calling clear_tlb, which removes this entry as it isn't global.
    // This however means that valid_tlb_entries can contain some invalid entries
    tlb_data[page as usize] = 0;
    *last_virt_eip = -1;
    // (P7.1: the page tier's code translation of the page, if any)
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA == 0 {
        crate::x64::pages::forget_code_page(crate::cpu::apic::current_core(), addr as u32 as u64);
    }
}

#[no_mangle]
pub unsafe fn update_eflags(new_flags: i32) {
    let mut dont_update = FLAG_RF | FLAG_VM | FLAG_VIP | FLAG_VIF;
    let mut clear = !FLAG_VIP & !FLAG_VIF & FLAGS_MASK;
    if 0 != *flags & FLAG_VM {
        // other case needs to be handled in popf or iret
        dbg_assert!(getiopl() == 3);
        dont_update |= FLAG_IOPL;
        // don't clear vip or vif
        clear |= FLAG_VIP | FLAG_VIF
    }
    else {
        if !*protected_mode {
            dbg_assert!(*cpl == 0);
        }
        if 0 != *cpl {
            // cpl > 0
            // cannot update iopl
            dont_update |= FLAG_IOPL;
            if *cpl as i32 > getiopl() {
                // cpl > iopl
                // cannot update interrupt flag
                dont_update |= FLAG_INTERRUPT
            }
        }
    }
    *flags = (new_flags ^ (*flags ^ new_flags) & dont_update) & clear | FLAGS_DEFAULT;
    *flags_changed = 0;

    if *flags & FLAG_TRAP != 0 {
        dbg_log!("Not supported: trap flag");
    }
    *flags &= !FLAG_TRAP;
}

#[no_mangle]
pub unsafe fn get_valid_tlb_entries_count() -> i32 {
    if !cfg!(feature = "profiler") {
        return 0;
    }
    let mut result = 0;
    for i in 0..valid_tlb_entries_count {
        let page = valid_tlb_entries[i as usize];
        let entry = tlb_data[page as usize];
        if 0 != entry {
            result += 1
        }
    }
    return result;
}

#[no_mangle]
pub unsafe fn get_valid_global_tlb_entries_count() -> i32 {
    if !cfg!(feature = "profiler") {
        return 0;
    }
    let mut result = 0;
    for i in 0..valid_tlb_entries_count {
        let page = valid_tlb_entries[i as usize];
        let entry = tlb_data[page as usize];
        if 0 != entry & TLB_GLOBAL {
            result += 1
        }
    }
    return result;
}

#[cold]
pub unsafe fn trigger_ts(code: i32) {
    crate::cpu::execution::mark_fault();
    *instruction_pointer = *previous_ip;
    crate::cpu::exceptions::fault(10, Some(code));
}

#[inline(never)]
pub unsafe fn trigger_np(code: i32) {
    crate::cpu::execution::mark_fault();
    dbg_log!("#np");
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_NP) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_NP, Some(code));
}

#[inline(never)]
pub unsafe fn trigger_ss(code: i32) {
    crate::cpu::execution::mark_fault();
    dbg_log!("#ss");
    *instruction_pointer = *previous_ip;
    if DEBUG {
        if js::cpu_exception_hook(CPU_EXCEPTION_SS) {
            return;
        }
    }
    crate::cpu::exceptions::fault(CPU_EXCEPTION_SS, Some(code));
}

#[no_mangle]
pub unsafe fn store_current_tsc() { *current_tsc = read_tsc(); }

#[no_mangle]
pub unsafe fn handle_irqs() {
    if crate::cpu::execution::irqs_deferred() {
        crate::cpu::execution::note_held_irq();
        return;
    }
    if crate::cpu::exceptions::delivering() {
        return;
    }
    crate::cpu::execution::held_irqs_served();
    let core = apic::current_core() as u32;
    let shutdown = crate::cpu::exceptions::exception_shutdown(core);
    if shutdown == 2 {
        return;
    }
    // SMI: before NMI, regardless of IF; latched while in SMM (until RSM)
    if !crate::cpu::smm::smm_active() && apic::take_smi() && crate::cpu::smm::smm_enter() {
        crate::cpu::exceptions::exception_restore(core, 0);
        return;
    }
    // NMI: regardless of IF, not while an NMI handler runs (until IRET)
    if *acpi_enabled && !*nmi_blocked && apic::take_nmi() {
        crate::cpu::exceptions::exception_restore(core, 0);
        *nmi_blocked = true;
        pic_call_irq(CPU_EXCEPTION_NMI as u8);
        return;
    }
    if shutdown != 0 {
        return;
    }
    if *flags & FLAG_INTERRUPT != 0 && *interrupt_shadow == 0 {
        // the 8259 PIC is wired to the bootstrap processor (LINT0 of core 0)
        let pic_irq = apic::acknowledge_pic_irq();
        if let Some(irq) = pic_irq {
            pic_call_irq(irq)
        }
        else if *acpi_enabled {
            if let Some(irq) = apic::acknowledge_irq() {
                pic_call_irq(irq)
            }
        }
    }
}

/// Whether handle_irqs would deliver an interrupt now, without its effects
/// (nothing is acknowledged)
pub unsafe fn irq_deliverable() -> bool {
    if crate::cpu::smm::smi_deliverable() || *acpi_enabled && !*nmi_blocked && apic::nmi_pending() {
        return true;
    }
    *flags & FLAG_INTERRUPT != 0
        && *interrupt_shadow == 0
        && (apic::routed_pic_pending(apic::current_core() as u32)
            || *acpi_enabled && apic::has_pending_irq())
}

unsafe fn pic_call_irq(interrupt_nr: u8) {
    // (cross-modifying code: other cores' code writes are seen from here on)
    crate::parallel::code::poll();
    *previous_ip = *instruction_pointer; // XXX: What if called after instruction (port IO)
    if *in_hlt {
        js::stop_idling();
        *in_hlt = false;
    }
    call_interrupt_vector(interrupt_nr as i32, false, None);
}

#[no_mangle]
unsafe fn device_raise_irq(i: u8) {
    pic::set_irq(i);
    if *acpi_enabled {
        ioapic::set_irq(i);
    }
    handle_irqs()
}

#[no_mangle]
unsafe fn device_lower_irq(i: u8) {
    pic::clear_irq(i);
    if *acpi_enabled {
        ioapic::clear_irq(i);
    }
    handle_irqs()
}

/// An IOAPIC input without a PIC counterpart: GSI 16-23, where Q35 connects
/// the PIRQs (the PIC sees them only through the PIRQ routing registers)
#[no_mangle]
unsafe fn ioapic_raise_irq(i: u8) {
    if *acpi_enabled {
        ioapic::set_irq(i);
    }
    handle_irqs()
}

#[no_mangle]
unsafe fn ioapic_lower_irq(i: u8) {
    if *acpi_enabled {
        ioapic::clear_irq(i);
    }
    handle_irqs()
}

/// A message signalled interrupt (PCI MSI): a device's write of `data` to
/// `address` in the local APICs' range. Address bits 19:12 are the
/// destination, bit 2 the destination mode; data bits 7:0 the vector, 10:8
/// the delivery mode. Edge triggered. Returns whether a local APIC took it.
#[no_mangle]
unsafe fn apic_msi(address: u32, data: u32) -> bool {
    if !*acpi_enabled || address >> 20 != 0xFEE {
        return false;
    }
    let mode = (data >> 8 & 7) as u8;
    // fixed, lowest priority, SMI, NMI, INIT, ExtINT
    if !matches!(mode, 0 | 1 | 2 | 4 | 5 | 7) {
        return false;
    }
    let accepted = apic::route(
        data as u8,
        mode,
        false,
        (address >> 12) as u8,
        (address >> 2 & 1) as u8,
    );
    handle_irqs();
    accepted
}

pub fn io_port_read8(port: i32) -> i32 {
    unsafe {
        // (a worker's core reaches the machine's PIC through the devices' thread)
        if crate::parallel::is_worker() {
            return js::io_port_read8(port);
        }
        match port {
            0x20 => pic::port20_read() as i32,
            0x21 => pic::port21_read() as i32,
            0xA0 => pic::portA0_read() as i32,
            0xA1 => pic::portA1_read() as i32,
            0x4D0 => pic::port4D0_read() as i32,
            0x4D1 => pic::port4D1_read() as i32,
            _ => js::io_port_read8(port),
        }
    }
}
pub fn io_port_read16(port: i32) -> i32 { unsafe { js::io_port_read16(port) } }
pub fn io_port_read32(port: i32) -> i32 { unsafe { js::io_port_read32(port) } }

pub fn io_port_write8(port: i32, value: i32) {
    unsafe {
        if crate::parallel::is_worker() {
            return js::io_port_write8(port, value);
        }
        match port {
            0x20 | 0x21 | 0xA0 | 0xA1 | 0x4D0 | 0x4D1 => {
                match port {
                    0x20 => pic::port20_write(value as u8),
                    0x21 => pic::port21_write(value as u8),
                    0xA0 => pic::portA0_write(value as u8),
                    0xA1 => pic::portA1_write(value as u8),
                    0x4D0 => pic::port4D0_write(value as u8),
                    0x4D1 => pic::port4D1_write(value as u8),
                    _ => dbg_assert!(false),
                };
                handle_irqs()
            },
            _ => js::io_port_write8(port, value),
        }
    }
}
pub fn io_port_write16(port: i32, value: i32) { unsafe { js::io_port_write16(port, value) } }
pub fn io_port_write32(port: i32, value: i32) { unsafe { js::io_port_write32(port, value) } }

// Port accesses of cores in workers, performed by the machine instance on
// the devices' thread (src/parallel): the same decoding as its own accesses
#[no_mangle]
pub fn machine_io_read8(port: i32) -> i32 { io_port_read8(port) }
#[no_mangle]
pub fn machine_io_write8(port: i32, value: i32) { io_port_write8(port, value) }

/// Reset shared interrupt routing at a board reset, never on a per-core INIT.
#[no_mangle]
pub fn reset_interrupt_controllers() {
    pic::reset();
    ioapic::reset();
}

#[no_mangle]
pub unsafe fn reset_cpu() {
    crate::x64::state::reset_extension();
    crate::cpu::xstate::reset();
    crate::cpu::fpu::fpu_discard_cache();
    for i in 0..8 {
        *segment_is_null.offset(i) = false;
        *segment_limits.offset(i) = 0;
        *segment_offsets.offset(i) = 0;
        *segment_access_bytes.offset(i) = 0x80 | (0 << 5) | 0x10 | 0x02; // P dpl0 S RW

        *reg32.offset(i) = 0;

        *sreg.offset(i) = 0;
        *dreg.offset(i) = 0;

        write_xmm128_2(i as i32, 0, 0);

        *fpu_st.offset(i) = softfloat::F80::ZERO;
    }
    *segment_access_bytes.offset(CS as isize) = 0x80 | (0 << 5) | 0x10 | 0x08 | 0x02; // P dpl0 S E RW

    for i in 0..4 {
        *reg_pdpte.offset(i) = 0
    }

    *fpu_stack_empty = 0xFF;
    *fpu_stack_ptr = 0;
    *fpu_control_word = 0x37F;
    *fpu_status_word = 0;
    *fpu_ip = 0;
    *fpu_ip_selector = 0;
    *fpu_opcode = 0;
    *fpu_dp = 0;
    *fpu_dp_selector = 0;

    *mxcsr = 0x1F80;

    full_clear_tlb();

    *protected_mode = false;

    // http://www.sandpile.org/x86/initial.htm
    *idtr_size = 0;
    *idtr_offset = 0;

    *gdtr_size = 0;
    *gdtr_offset = 0;

    *cr = 1 << 30 | 1 << 29 | 1 << 4;
    *cr.offset(2) = 0;
    *cr.offset(3) = 0;
    *cr.offset(4) = 0;
    *dreg.offset(6) = 0xFFFF0FF0u32 as i32;
    *dreg.offset(7) = 0x400;
    *cpl = 0;

    *is_32 = false;
    *stack_size_32 = false;
    *prefixes = 0;

    *last_virt_eip = -1;

    *instruction_counter = 0;
    *previous_ip = 0;
    *in_hlt = false;
    *nmi_blocked = false;
    *interrupt_shadow = 0;
    crate::cpu::smm::reset();
    *slice_budget = LOOP_COUNTER as u32;
    crate::cpu::execution::reset();
    // the local APIC (present with ACPI) is enabled at reset
    *apic_enabled = *acpi_enabled;

    *sysenter_cs = 0;
    *sysenter_esp = 0;
    *sysenter_eip = 0;

    *flags = FLAGS_DEFAULT;
    *flags_changed = 0;
    *last_result = 0;
    *last_op1 = 0;
    *last_op_size = 0;

    set_tsc(0, 0);

    *instruction_pointer = 0xFFFF0;
    switch_cs_real_mode(0xF000);

    switch_seg(SS, 0x30);
    write_reg32(ESP, 0x100);

    update_state_flags();

    jit::jit_clear_cache_js();
}

#[no_mangle]
pub unsafe fn set_cpuid_level(level: u32) { cpuid_level = level }
                                                                                                    source/v64/src/rust/cpu/exceptions.rs                                                               0000644 0000000 0000000 00000010706 00000000000 014772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Exception delivery escalation (Intel SDM Vol. 3A, table 7-5).
//! Delivery is synchronous and never spans a scheduler boundary. Shutdown is
//! architectural per-core state; the board resets on BSP shutdown only.
use crate::cpu::{apic, cpu, global_pointers::*};

#[derive(Clone, Copy, PartialEq, Debug)]
enum Class {
    Benign,
    Contributory,
    Page,
    Double,
}
fn class(vector: i32) -> Class {
    match vector {
        0 | 10..=13 => Class::Contributory,
        14 => Class::Page,
        8 => Class::Double,
        _ => Class::Benign,
    }
}
#[derive(PartialEq, Debug)]
enum Action {
    Deliver,
    Double,
    Shutdown,
}
fn escalation(first: Class, second: Class) -> Action {
    match (first, second) {
        (Class::Double, Class::Contributory | Class::Page) => Action::Shutdown,
        (Class::Contributory, Class::Contributory)
        | (Class::Page, Class::Contributory | Class::Page) => Action::Double,
        _ => Action::Deliver,
    }
}
static mut DELIVERING: Option<Class> = None;
static mut EXTERNAL: bool = false;
// 0: running, 1: shutdown (NMI/INIT can wake), 2: shutdown during NMI (reset only).
static mut SHUTDOWN: [u8; 8] = [0; 8];
static mut BSP_RESET: bool = false;

pub unsafe fn delivering() -> bool { matches!(DELIVERING, Some(_)) }
pub unsafe fn interrupt(vector: i32, software: bool, code: Option<i32>) -> bool {
    let old = DELIVERING;
    let old_external = EXTERNAL;
    EXTERNAL = !software;
    DELIVERING = Some(Class::Benign);
    let completed = cpu::deliver_interrupt(vector, software, code);
    DELIVERING = old;
    EXTERNAL = old_external;
    completed
}
/// A CPU trap ignores gate DPL without marking a later selector fault as
/// externally caused. Its return IP already points past the retired opcode.
pub unsafe fn trap(vector: i32) {
    let old = DELIVERING;
    let old_external = EXTERNAL;
    EXTERNAL = false;
    DELIVERING = Some(Class::Benign);
    cpu::deliver_interrupt(vector, false, None);
    DELIVERING = old;
    EXTERNAL = old_external;
}
pub unsafe fn fault(vector: i32, code: Option<i32>) {
    if vector == 7 {
        // (the step profile's #NM count, docs/jit-unification-plan.md P4.0)
        crate::step_profile::note_event(crate::step_profile::event::NM, 0);
    }
    let old = DELIVERING;
    let action = escalation(old.unwrap_or(Class::Benign), class(vector));
    if action == Action::Shutdown {
        shutdown();
        return;
    }
    let code = if EXTERNAL && matches!(vector, 10..=13) { code.map(|code| code | 1) } else { code };
    let (vector, code) = if action == Action::Double { (8, Some(0)) } else { (vector, code) };
    DELIVERING = Some(class(vector));
    cpu::deliver_interrupt(vector, false, code);
    DELIVERING = old;
}
/// The shutdown state: a triple fault, or RSM to invalid state; the
/// chipset resets the machine for the BSP
pub unsafe fn shutdown() {
    let core = apic::current_core();
    (*crate::parallel::machine(&raw mut SHUTDOWN))[core] = if *nmi_blocked { 2 } else { 1 };
    if core == 0 {
        BSP_RESET = true;
    }
    *in_hlt = true;
    cpu::request_core_yield();
}
#[no_mangle]
pub unsafe fn exception_shutdown(core: u32) -> u32 {
    assert!(core < 8);
    (*crate::parallel::machine(&raw mut SHUTDOWN))[core as usize] as u32
}
#[no_mangle]
pub unsafe fn exception_restore(core: u32, state: u32) {
    assert!(core < 8 && state <= 2);
    (*crate::parallel::machine(&raw mut SHUTDOWN))[core as usize] = state as u8;
}
pub unsafe fn init(core: u32) -> bool {
    if exception_shutdown(core) == 2 {
        return false;
    }
    exception_restore(core, 0);
    true
}
pub unsafe fn reset() {
    *crate::parallel::machine(&raw mut SHUTDOWN) = [0; 8];
    DELIVERING = None;
    EXTERNAL = false;
    BSP_RESET = false;
}
#[no_mangle]
pub unsafe fn exception_take_bsp_reset() -> bool {
    let pending = BSP_RESET;
    BSP_RESET = false;
    pending
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn intel_delivery_escalation_matrix() {
        use Action::{Deliver, Shutdown};
        use Class::*;
        for (first, expected) in [
            (Benign, [Deliver, Deliver, Deliver]),
            (Contributory, [Deliver, Action::Double, Deliver]),
            (Page, [Deliver, Action::Double, Action::Double]),
            (Class::Double, [Deliver, Shutdown, Shutdown]),
        ] {
            for (second, expected) in [Benign, Contributory, Page].into_iter().zip(expected) {
                assert_eq!(escalation(first, second), expected);
            }
        }
    }
}
                                                          source/v64/src/rust/cpu/execution.rs                                                                0000644 0000000 0000000 00000030056 00000000000 014614  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Architectural progress for the machine clock. Dispatch attempts, exceptions
//! and REP continuation batches are deliberately not retired instructions.
//!
//! The cooperative scheduler switches cores only outside begin/finish. This
//! state is therefore Machine-owned transient execution state, not vCPU state.

use crate::cpu::apic;
use crate::cpu::string::{StringExecution, StringOutcome};

// The per-core counters are crate::core_stats's (both cores count there)
use crate::core_stats::retired_now;
pub use crate::core_stats::{flush_core_statistics, note_halt, note_jit_rep, note_native_retired};
use crate::core_stats::{CORE_STATISTICS, PENDING_REP_ELEMENTS, PENDING_RETIRED};

struct ExecutionState {
    deterministic: bool,
    active: bool,
    faulted: bool,
    string_result: Option<StringExecution>,
    pending_work: u64,
    retired: u32,
    rep_elements: u32,
    // The wide executor commits RIP only after its last access. A device
    // callback inside that window must not deliver an IRQ; the dispatch
    // loop polls again at the instruction boundary.
    defer_irqs: bool,
    // handle_irqs was called while defer_irqs held
    irq_noted: bool,
}

impl ExecutionState {
    const fn new() -> Self {
        Self {
            deterministic: false,
            active: false,
            faulted: false,
            string_result: None,
            pending_work: 0,
            retired: 0,
            rep_elements: 0,
            defer_irqs: false,
            irq_noted: false,
        }
    }

    fn begin(&mut self) {
        dbg_assert!(!self.active);
        self.active = true;
        self.faulted = false;
        self.string_result = None;
    }

    fn mark_fault(&mut self) {
        if self.active {
            self.faulted = true;
        }
    }

    fn record_string(&mut self, result: StringExecution) {
        if self.active {
            dbg_assert!(self.string_result.is_none());
            self.string_result = Some(result);
        }
    }

    fn finish(&mut self) -> u32 {
        dbg_assert!(self.active);
        let work = match self.string_result {
            // Completed REP elements remain architectural progress even when
            // the next element faults or a page/budget boundary yields.
            Some(result) if result.iterations > 0 => result.iterations,
            Some(result) => (result.outcome == StringOutcome::Complete && !self.faulted) as u32,
            None => (!self.faulted) as u32,
        };
        self.retired = (!self.faulted
            && self
                .string_result
                .is_none_or(|r| r.outcome == StringOutcome::Complete))
            as u32;
        self.rep_elements = self.string_result.map_or(0, |r| r.iterations);
        self.active = false;
        self.pending_work += work as u64;
        work
    }

    fn take_progress(&mut self) -> f64 {
        // JS consumes at slice boundaries and device reads. This counter is a
        // delta, rather than a floating-point lifetime instruction accumulator.
        dbg_assert!(self.pending_work <= (1u64 << 53) - 1);
        let work = self.pending_work;
        self.pending_work = 0;
        work as f64
    }
}

#[allow(non_upper_case_globals)]
static mut execution_state: ExecutionState = ExecutionState::new();

/// Hold external interrupt delivery until the current wide instruction has
/// committed or faulted.
#[inline(always)]
pub unsafe fn set_irq_deferral(enabled: bool) { execution_state.defer_irqs = enabled; }

#[inline(always)]
pub unsafe fn irqs_deferred() -> bool { execution_state.defer_irqs }

/// Whether handle_irqs was called while delivery was held, and nothing has
/// delivered since (cpu::run_compat_instruction)
#[inline(always)]
pub unsafe fn irq_check_owed() -> bool { execution_state.irq_noted }

/// handle_irqs while delivery is held: the hold's end looks again
#[inline(always)]
pub unsafe fn note_held_irq() { execution_state.irq_noted = true; }

/// handle_irqs outside a hold delivers what is deliverable: nothing is owed
#[inline(always)]
pub unsafe fn held_irqs_served() { execution_state.irq_noted = false; }

/// This mode uses the bounded interpreter and never a JIT/IR dispatch path.
#[no_mangle]
pub unsafe fn set_deterministic_execution(enabled: bool) {
    dbg_assert!(!execution_state.active);
    execution_state.deterministic = enabled;
}

#[inline(always)]
pub unsafe fn is_deterministic() -> bool { execution_state.deterministic }

/// Begin at outer dispatch; prefix recursion stays in this instruction.
#[inline(always)]
pub unsafe fn begin_instruction() { (&mut *(&raw mut execution_state)).begin() }

/// Return successful work from this dispatch, also queued for the JS clock.
#[inline(always)]
pub unsafe fn finish_instruction() -> u32 {
    let work = (&mut *(&raw mut execution_state)).finish();
    PENDING_RETIRED += execution_state.retired as u64;
    PENDING_REP_ELEMENTS += execution_state.rep_elements as u64;
    if !execution_state.deterministic {
        execution_state.pending_work = 0;
    }
    work
}

/// Mark synchronous faults only; traps and asynchronous IRQs are not faults.
#[inline(always)]
pub unsafe fn mark_fault() {
    (*crate::parallel::machine(&raw mut CORE_STATISTICS))[apic::current_core()].faults += 1;
    (&mut *(&raw mut execution_state)).mark_fault()
}

/// Called once by the outer interpreter string-instruction wrapper.
#[inline(always)]
pub unsafe fn record_string(result: StringExecution) {
    (&mut *(&raw mut execution_state)).record_string(result)
}

/// Consume accumulated progress without retiring the currently executing PIO.
#[no_mangle]
pub unsafe fn take_clock_progress() -> f64 { (&mut *(&raw mut execution_state)).take_progress() }

/// STI has retired before its recursively interpreted shadow instruction.
pub unsafe fn begin_shadow_instruction() {
    if execution_state.active {
        finish_instruction();
        begin_instruction();
    }
}

/// How retired instructions ran (the mode ledger)
#[derive(Clone, Copy)]
pub enum Way {
    /// by the interpreter, outside compiled code
    Interpreted = 0,
    // 1 and 2 were IR Tier-0's page functions and the instructions they
    // stepped (deleted in P7.5), 3 the IR regions (deleted in M11); the
    // numbering, which tools read, stays
    /// the x64 page tier, the instructions it stepped and the ones it
    /// retried in the interpreter after refusing an access
    PageNative = 4,
    PageStep = 5,
    PageRetry = 6,
}
const WAYS: usize = 7;
/// x64::state::ExecutionMode
const MODES: usize = 7;
/// The mode ledger (docs/jit-unification-plan.md P0.6, the JIT switch
/// mode_ledger, off by default): retired instructions (cross-phase rule 3:
/// what core_statistics_get(core, 0) counts) by mode, by whether 32-bit code
/// ran with flat segments (index 1), and by Way. While it is on, its sum
/// grows exactly as the retired count does.
static mut LEDGER: Option<[[[u64; WAYS]; 2]; MODES]> = None;

#[inline(always)]
pub fn ledger_on() -> bool { unsafe { (*(&raw const LEDGER)).is_some() } }
/// Off: the ledger is dropped; on: an empty one unless it was on
pub unsafe fn set_ledger(on: bool) {
    if on != ledger_on() {
        LEDGER = on.then_some([[[0; WAYS]; 2]; MODES]);
    }
}
#[no_mangle]
pub unsafe fn mode_ledger_reset() {
    if let Some(ledger) = (*(&raw mut LEDGER)).as_mut() {
        *ledger = [[[0; WAYS]; 2]; MODES];
    }
}
/// Retired instructions of mode `mode` (ExecutionMode), with flat 32-bit
/// segments or not (`flat`), that ran the Way `way`
#[no_mangle]
pub unsafe fn mode_ledger_get(mode: u32, flat: u32, way: u32) -> f64 {
    (*(&raw const LEDGER))
        .as_ref()
        .and_then(|l| l.get(mode as usize)?.get(flat as usize)?.get(way as usize))
        .map_or(0.0, |&n| n as f64)
}

/// Retirements of one Way from one mode, while the ledger is on: begun before
/// the instructions run, so that their mode is the row
pub struct LedgerSpan {
    mode: u8,
    flat: u8,
    retired: u64,
    counter: u32,
}
#[inline(always)]
pub unsafe fn ledger_begin() -> Option<LedgerSpan> {
    if ledger_on() {
        Some(ledger_begin_now())
    }
    else {
        None
    }
}
#[cold]
#[inline(never)]
unsafe fn ledger_begin_now() -> LedgerSpan {
    use crate::x64::state::ExecutionMode;
    let mode = crate::x64::state::mode();
    let flat = matches!(
        mode,
        ExecutionMode::Protected32 | ExecutionMode::Compatibility32
    ) && crate::cpu::cpu::has_flat_segmentation();
    LedgerSpan {
        mode: mode as u8,
        flat: flat as u8,
        retired: retired_now(),
        counter: *crate::cpu::global_pointers::instruction_counter,
    }
}
unsafe fn ledger_add(span: &LedgerSpan, way: Way, retired: u64) {
    if let Some(ledger) = (*(&raw mut LEDGER)).as_mut() {
        ledger[span.mode as usize][span.flat as usize][way as usize] += retired;
    }
}
/// Instructions retired one by one (finish_instruction) since the span began
#[inline(always)]
pub unsafe fn ledger_end(span: Option<LedgerSpan>, way: Way) {
    if let Some(span) = span {
        ledger_add(&span, way, retired_now() - span.retired);
    }
}
/// Instructions compiled code retired since the span began, as
/// note_native_retired counts them: the instruction counter's advance
#[inline(always)]
pub unsafe fn ledger_end_native(span: Option<LedgerSpan>, way: Way) {
    if let Some(span) = span {
        let native = (*crate::cpu::global_pointers::instruction_counter).wrapping_sub(span.counter);
        ledger_add(&span, way, native as u64);
    }
}
/// `retired` instructions compiled code retired since the span began, counted
/// by the caller
#[inline(always)]
pub unsafe fn ledger_end_count(span: Option<LedgerSpan>, way: Way, retired: u32) {
    if let Some(span) = span {
        ledger_add(&span, way, retired as u64);
    }
}

/// Used after reset/restore, with the previous pending delta already consumed.
/// The machine's execution mode survives architectural reset.
pub unsafe fn reset() {
    let deterministic = execution_state.deterministic;
    execution_state = ExecutionState::new();
    execution_state.deterministic = deterministic;
}

#[cfg(test)]
mod tests {
    use super::*;

    fn string_result(outcome: StringOutcome, iterations: u32) -> StringExecution {
        StringExecution {
            outcome,
            iterations,
        }
    }

    #[test]
    fn faults_do_not_retire_but_completed_instructions_do() {
        let mut state = ExecutionState::new();
        state.mark_fault(); // fault delivery outside a dispatch is irrelevant
        state.begin();
        assert_eq!(state.finish(), 1);
        state.begin();
        state.mark_fault();
        assert_eq!(state.finish(), 0);
        assert_eq!(state.take_progress(), 1.0);
        assert_eq!(state.take_progress(), 0.0);
    }

    #[test]
    fn rep_work_survives_faults_and_continuations_without_extra_retirements() {
        let mut state = ExecutionState::new();
        for (outcome, iterations, work) in [
            (StringOutcome::Complete, 0, 1),
            (StringOutcome::Complete, 17, 17),
            (StringOutcome::Repeat, 256, 256),
            (StringOutcome::Repeat, 0, 0),
            (StringOutcome::Fault, 5, 5),
            (StringOutcome::Fault, 0, 0),
        ] {
            state.begin();
            if outcome == StringOutcome::Fault {
                state.mark_fault();
            }
            state.record_string(string_result(outcome, iterations));
            assert_eq!(state.finish(), work);
        }
        assert_eq!(state.take_progress(), 279.0);
    }

    #[test]
    fn device_read_observes_only_prior_completed_dispatches() {
        let mut state = ExecutionState::new();
        state.begin();
        state.finish();
        state.begin(); // PIO callback during the next instruction
        assert_eq!(state.take_progress(), 1.0);
        assert_eq!(state.take_progress(), 0.0);
        state.finish();
        assert_eq!(state.take_progress(), 1.0);
    }

    #[test]
    fn jit_strings_outside_interpreter_dispatch_do_not_fabricate_progress() {
        let mut state = ExecutionState::new();
        state.record_string(string_result(StringOutcome::Complete, 100));
        assert_eq!(state.take_progress(), 0.0);
        state.begin();
        assert_eq!(state.finish(), 1);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/rust/cpu/features.rs                                                                 0000644 0000000 0000000 00000012024 00000000000 014422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The CPU features of docs/simd-xsave-plan.md (SSSE3 to x86-64-v3 and the
//! XSAVE family) that this machine has, fixed when it is created (settings
//! `cpu_features`, src/cpu.js). CPUID reports them, and the decoders and
//! executors test them: an opcode row whose feature is absent does not exist
//! (decode_rules::mandatory_variant), so its encoding is #UD, or for TZCNT and
//! LZCNT the older BSF and BSR.

// BEGIN GENERATED by gen/cpu_features.js (edit the table there)
pub const SSSE3: u32 = 1 << 0;
pub const SSE4_1: u32 = 1 << 1;
pub const SSE4_2: u32 = 1 << 2;
pub const XSAVE: u32 = 1 << 3;
pub const AVX: u32 = 1 << 4;
pub const AVX2: u32 = 1 << 5;
pub const FMA: u32 = 1 << 6;
pub const F16C: u32 = 1 << 7;
pub const BMI1: u32 = 1 << 8;
pub const BMI2: u32 = 1 << 9;
pub const LZCNT: u32 = 1 << 10;
pub const MOVBE: u32 = 1 << 11;
pub const XSAVEOPT: u32 = 1 << 12;
pub const XSAVEC: u32 = 1 << 13;
pub const XGETBV1: u32 = 1 << 14;
pub const XSAVES: u32 = 1 << 15;
pub const COUNT: usize = 16;
pub const ALL: u32 = 0xFFFF;
/// The other features each one requires (the always-present ones left out)
#[rustfmt::skip]
pub const REQUIRES: [u32; COUNT] = [0, SSSE3, SSE4_1, 0, XSAVE | SSE4_2, AVX, AVX, AVX, 0, 0, 0, 0, XSAVE, XSAVE, XSAVE, XSAVEC];
/// Where CPUID reports each: (leaf, subleaf, register: 0 = EAX .. 3 = EDX, bit)
#[rustfmt::skip]
pub const CPUID: [(u32, u32, usize, u32); COUNT] = [(0x1, 0, 2, 9), (0x1, 0, 2, 19), (0x1, 0, 2, 20), (0x1, 0, 2, 26), (0x1, 0, 2, 28), (0x7, 0, 1, 5), (0x1, 0, 2, 12), (0x1, 0, 2, 29), (0x7, 0, 1, 3), (0x7, 0, 1, 8), (0x80000001, 0, 2, 5), (0x1, 0, 2, 22), (0xD, 1, 0, 0), (0xD, 1, 0, 1), (0xD, 1, 0, 2), (0xD, 1, 0, 3)];
/// The lowest maximum basic leaf (cpuid_level) that lets CPUID report each
#[rustfmt::skip]
pub const MIN_CPUID_LEVEL: [u32; COUNT] = [0x1, 0x1, 0x1, 0xD, 0x1, 0x7, 0x1, 0x1, 0x7, 0x7, 0x1, 0x1, 0xD, 0xD, 0xD, 0xD];
/// Features the legacy (x86) profile may not have
pub const X86_64_ONLY: u32 = LZCNT;
// END GENERATED

/// The features of this machine (bits above)
static mut FEATURES: u32 = 0;

#[cfg(test)]
thread_local! {
    /// cargo test: the features of the test thread (the tests run in parallel)
    pub static TEST_FEATURES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// Whether the machine has all of `features`
#[inline]
pub fn has(features: u32) -> bool { all() & features == features }

/// The features of this machine
#[inline]
pub fn all() -> u32 {
    #[cfg(test)]
    return TEST_FEATURES.with(|f| f.get());
    #[cfg(not(test))]
    unsafe {
        FEATURES
    }
}

/// Set by src/cpu.js before the CPU runs, after it checked requirements,
/// profile and cpuid_level (CPU.prototype.resolve_cpu_features)
#[no_mangle]
pub unsafe fn set_cpu_features(features: u32) {
    dbg_assert!(features & !ALL == 0);
    dbg_assert!(valid(
        features,
        crate::cpu::instructions_0f::long_mode_capable()
    ));
    FEATURES = features;
}
#[no_mangle]
pub unsafe fn get_cpu_features() -> u32 { FEATURES }

/// A worker's cores have the machine's features (crate::parallel)
pub unsafe fn copy_from_machine() { FEATURES = *crate::parallel::machine(&raw mut FEATURES); }

/// Every feature's requirements are present, and the legacy profile has no
/// x86-64-only feature
pub fn valid(features: u32, x86_64: bool) -> bool {
    (0..COUNT).all(|i| features & 1 << i == 0 || features & REQUIRES[i] == REQUIRES[i])
        && (x86_64 || features & X86_64_ONLY == 0)
}

/// CPUID: set the bits of the machine's features in `registers` (EAX..EDX)
/// of leaf `leaf`, subleaf `subleaf` (ECX, which only leaves 7 and 0xD read)
pub fn cpuid(leaf: u32, subleaf: u32, registers: &mut [u32; 4]) {
    let indexed = matches!(leaf, 7 | 0xD);
    for (i, &(at_leaf, at_subleaf, register, bit)) in CPUID.iter().enumerate() {
        if all() & 1 << i != 0 && at_leaf == leaf && (!indexed || at_subleaf == subleaf) {
            registers[register] |= 1 << bit;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn requirements_and_cpuid_locations() {
        assert!(valid(0, false) && valid(ALL, true));
        assert!(!valid(SSE4_1, false), "SSE4.1 requires SSSE3");
        assert!(valid(SSSE3 | SSE4_1 | SSE4_2, false));
        assert!(
            !valid(AVX, true)
                && !valid(AVX | XSAVE, true)
                && valid(AVX | XSAVE | SSSE3 | SSE4_1 | SSE4_2, true)
        );
        assert!(
            !valid(LZCNT, false) && valid(LZCNT, true),
            "LZCNT needs the extended leaves of the x86-64 profile"
        );
        assert!(
            valid(BMI1 | BMI2 | MOVBE, false),
            "general-purpose extensions stand alone"
        );
        assert_eq!(CPUID[SSSE3.trailing_zeros() as usize], (1, 0, 2, 9));
        assert_eq!(CPUID[AVX2.trailing_zeros() as usize], (7, 0, 1, 5));
        assert_eq!(
            CPUID[LZCNT.trailing_zeros() as usize],
            (0x8000_0001, 0, 2, 5)
        );
        assert_eq!(MIN_CPUID_LEVEL[XSAVE.trailing_zeros() as usize], 0xD);
        assert_eq!(MIN_CPUID_LEVEL[BMI2.trailing_zeros() as usize], 7);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/src/rust/cpu/fpu.rs                                                                      0000644 0000000 0000000 00000104326 00000000000 013405  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::cpu::cpu::*;
use crate::cpu::global_pointers::*;
use crate::paging::OrPageFault;
use crate::softfloat::{Precision, RoundingMode, F80};

use std::f64;

const FPU_C0: u16 = 0x100;
const FPU_C1: u16 = 0x200;
const FPU_C2: u16 = 0x400;
const FPU_C3: u16 = 0x4000;
const FPU_RESULT_FLAGS: u16 = FPU_C0 | FPU_C1 | FPU_C2 | FPU_C3;

const FPU_EX_I: u16 = 1 << 0; // invalid operation
#[allow(dead_code)]
const FPU_EX_D: u16 = 1 << 1; // denormal operand
const FPU_EX_Z: u16 = 1 << 2; // zero divide
#[allow(dead_code)]
const FPU_EX_O: u16 = 1 << 3; // overflow
const FPU_EX_U: u16 = 1 << 4; // underflow
#[allow(dead_code)]
const FPU_EX_P: u16 = 1 << 5; // precision
const FPU_EX_SF: u16 = 1 << 6;

static mut X87_JIT_CACHE: bool = true;
// Physical stack slots survive regions, branches and JIT module returns.
// VALID identifies exact f64 mirrors; DIRTY identifies authoritative f64 values
// that must be materialized before any F80/MMX/state observer.
const X87_VALUES: *mut [u64; 8] = x87_shadow_values;
const X87_VALID: *mut u32 = x87_shadow_valid;
const X87_DIRTY: *mut u32 = x87_shadow_dirty;

#[no_mangle]
pub unsafe fn fpu_sync_slot(index: u32) {
    dbg_assert!(index < 8);
    let bit = 1 << index;
    if *X87_DIRTY & bit != 0 {
        *fpu_st.add(index as usize) = F80::of_f64((*X87_VALUES)[index as usize]);
        *X87_DIRTY &= !bit;
    }
}
#[no_mangle]
pub unsafe fn fpu_invalidate_slot(index: u32) {
    dbg_assert!(index < 8);
    *X87_VALID &= !(1 << index);
    *X87_DIRTY &= !(1 << index);
}
#[no_mangle]
pub unsafe fn fpu_sync_all() {
    while *X87_DIRTY != 0 {
        fpu_sync_slot((*X87_DIRTY).trailing_zeros());
    }
}
#[no_mangle]
pub unsafe fn fpu_discard_cache() {
    *X87_VALID = 0;
    *X87_DIRTY = 0;
}
#[no_mangle]
pub unsafe fn fpu_cache_barrier() {
    fpu_sync_all();
    fpu_discard_cache();
}

#[no_mangle]
pub unsafe fn set_x87_jit_cache(enabled: bool) {
    if !enabled {
        fpu_cache_barrier();
    }
    X87_JIT_CACHE = enabled;
    crate::softfloat::set_x87_policy_observer(refresh_x87_native_policy);
    refresh_x87_native_policy();
}
/// Generated IR code inlines fast-math x87 against the shadow cache only while
/// both policies hold; a change applies at the next instruction.
unsafe fn refresh_x87_native_policy() {
    *x87_native_policy = (X87_JIT_CACHE && crate::softfloat::x87_fast_math()) as u8;
}
/// Addresses of the shadow values ([u64; 8]), VALID and DIRTY masks, for
/// generated code that reads/writes the cache exactly like `write_cached`.
pub fn x87_cache_addresses() -> [u32; 3] { [X87_VALUES as u32, X87_VALID as u32, X87_DIRTY as u32] }
/// Mirror every full slot whose F80 is exactly a binary64 into the cache, as
/// `cached_value` would on first use. F80 stays authoritative (not DIRTY).
pub unsafe fn fpu_mirror_exact_slots() {
    if !X87_JIT_CACHE || !crate::softfloat::x87_fast_math() {
        return;
    }
    let full = !*fpu_stack_empty as u32 & !*X87_VALID & 255;
    for slot in 0..8 {
        if full & 1 << slot == 0 {
            continue;
        }
        let f = *fpu_st.add(slot);
        let exponent = f.sign_exponent & 0x7FFF;
        if (exponent == 0 && f.mantissa == 0)
            || ((0x3C01..=0x43FE).contains(&exponent)
                && f.mantissa >> 63 == 1
                && f.mantissa & 0x7FF == 0)
        {
            (*X87_VALUES)[slot] = f.to_f64();
            *X87_VALID |= 1 << slot;
        }
    }
}
#[no_mangle]
pub unsafe fn get_x87_jit_cache() -> bool { X87_JIT_CACHE }

// A host-side f64 helper shares exactly the same physical cache as emitted
// Wasm. F80 observers materialize only the slots they actually read.
unsafe fn cached_value(r: u32) -> Option<f64> {
    if !X87_JIT_CACHE || !crate::softfloat::x87_fast_math() {
        return None;
    }
    let slot = (*fpu_stack_ptr as u32 + r) & 7;
    if *fpu_stack_empty as u32 & (1 << slot) != 0 {
        return None;
    }
    if *X87_VALID & (1 << slot) == 0 {
        let f = *fpu_st.add(slot as usize);
        let exponent = f.sign_exponent & 0x7FFF;
        if !((exponent == 0 && f.mantissa == 0)
            || ((0x3C01..=0x43FE).contains(&exponent)
                && f.mantissa >> 63 == 1
                && f.mantissa & 0x7FF == 0))
        {
            return None;
        }
        (*X87_VALUES)[slot as usize] = f.to_f64();
        *X87_VALID |= 1 << slot;
    }
    Some(f64::from_bits((*X87_VALUES)[slot as usize]))
}
/// Exact f64 bits of ST(0) through the shared shadow cache, as FST m64 uses.
pub unsafe fn fpu_cached_st0() -> Option<u64> { cached_value(0).map(f64::to_bits) }
unsafe fn write_cached(r: u32, value: f64) {
    let slot = (*fpu_stack_ptr as u32 + r) & 7;
    (*X87_VALUES)[slot as usize] = value.to_bits();
    *X87_VALID |= 1 << slot;
    *X87_DIRTY |= 1 << slot;
}
unsafe fn push_cached(value: f64) -> bool {
    let next = (*fpu_stack_ptr + 7) & 7;
    if !X87_JIT_CACHE || !crate::softfloat::x87_fast_math() || *fpu_stack_empty & (1 << next) == 0 {
        return false;
    }
    *fpu_stack_ptr = next;
    *fpu_stack_empty &= !(1 << next);
    *fpu_status_word &= !FPU_C1;
    write_cached(0, value);
    true
}
#[no_mangle]
pub unsafe fn fpu_push_m64_bits(bits: u64) {
    let value = f64::from_bits(bits);
    if !value.is_nan() {
        F80::clear_exception_flags();
        if push_cached(value) {
            return;
        }
    }
    let value = f64_to_f80(bits);
    fpu_push(value);
}
#[no_mangle]
pub unsafe fn fpu_push_m32_bits(bits: i32) {
    let value = f32::from_bits(bits as u32);
    if !value.is_nan() {
        F80::clear_exception_flags();
        if push_cached(value as f64) {
            return;
        }
    }
    let value = f32_to_f80(bits);
    fpu_push(value);
}
#[no_mangle]
pub unsafe fn fpu_store_m64_bits() -> u64 {
    F80::clear_exception_flags();
    if let Some(value) = cached_value(0) {
        return value.to_bits();
    }
    f80_to_f64(fpu_get_st0())
}

pub fn fpu_write_st(index: i32, value: F80) {
    dbg_assert!(index >= 0 && index < 8);
    unsafe {
        fpu_invalidate_slot(index as u32);
        *fpu_st.offset(index as isize) = value;
    }
}

pub unsafe fn fpu_get_st0() -> F80 {
    dbg_assert!(*fpu_stack_ptr < 8);
    if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 {
        *fpu_status_word &= !FPU_C1;
        fpu_stack_fault();
        return F80::INDEFINITE_NAN;
    }
    else {
        fpu_sync_slot(*fpu_stack_ptr as u32);
        return *fpu_st.offset(*fpu_stack_ptr as isize);
    };
}
pub unsafe fn fpu_stack_fault() {
    // TODO: Interrupt
    *fpu_status_word |= FPU_EX_SF | FPU_EX_I;
}

pub unsafe fn fpu_zero_fault() {
    // TODO: Interrupt
    *fpu_status_word |= FPU_EX_Z;
}

pub unsafe fn fpu_underflow_fault() {
    // TODO: Interrupt
    *fpu_status_word |= FPU_EX_U;
}

pub unsafe fn fpu_sti_empty(mut i: i32) -> bool {
    dbg_assert!(i >= 0 && i < 8);
    i = i + *fpu_stack_ptr as i32 & 7;
    return 0 != *fpu_stack_empty >> i & 1;
}

pub unsafe fn fpu_get_sti(mut i: i32) -> F80 {
    dbg_assert!(i >= 0 && i < 8);
    i = i + *fpu_stack_ptr as i32 & 7;
    if 0 != *fpu_stack_empty >> i & 1 {
        *fpu_status_word &= !FPU_C1;
        fpu_stack_fault();
        return F80::INDEFINITE_NAN;
    }
    else {
        fpu_sync_slot(i as u32);
        return *fpu_st.offset(i as isize);
    };
}

// only used for debugging
#[no_mangle]
pub unsafe fn fpu_get_sti_f64(mut i: i32) -> f64 {
    i = i + *fpu_stack_ptr as i32 & 7;
    fpu_sync_slot(i as u32);
    f64::from_bits((*fpu_st.offset(i as isize)).to_f64())
}

pub unsafe fn f32_to_f80(v: i32) -> F80 {
    F80::clear_exception_flags();
    let x = F80::of_f32(v);
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
pub unsafe fn f64_to_f80(v: u64) -> F80 {
    F80::clear_exception_flags();
    let x = F80::of_f64(v);
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
#[no_mangle]
pub unsafe fn f80_to_f64(v: F80) -> u64 {
    F80::clear_exception_flags();
    let x = v.to_f64();
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}

pub unsafe fn i32_to_f80(v: i32) -> F80 { F80::of_i32(v) }
pub unsafe fn i64_to_f80(v: i64) -> F80 { F80::of_i64(v) }

pub unsafe fn fpu_load_i16(addr: i32) -> OrPageFault<F80> {
    let v = safe_read16(addr)? as i16 as i32;
    Ok(F80::of_i32(v))
}
pub unsafe fn fpu_load_i32(addr: i32) -> OrPageFault<F80> {
    let v = safe_read32s(addr)?;
    Ok(F80::of_i32(v))
}
pub unsafe fn fpu_load_i64(addr: i32) -> OrPageFault<F80> {
    let v = safe_read64s(addr)? as i64;
    Ok(F80::of_i64(v))
}

pub unsafe fn fpu_load_m32(addr: i32) -> OrPageFault<F80> {
    F80::clear_exception_flags();
    let v = F80::of_f32(safe_read32s(addr)?);
    *fpu_status_word |= F80::get_exception_flags() as u16;
    Ok(v)
}
pub unsafe fn fpu_load_m64(addr: i32) -> OrPageFault<F80> {
    F80::clear_exception_flags();
    let v = F80::of_f64(safe_read64s(addr)?);
    *fpu_status_word |= F80::get_exception_flags() as u16;
    Ok(v)
}
pub unsafe fn fpu_load_m80(addr: i32) -> OrPageFault<F80> {
    let mantissa = safe_read64s(addr)?;
    let sign_exponent = safe_read16(addr + 8)? as u16;
    // TODO: Canonical form
    Ok(F80 {
        mantissa,
        sign_exponent,
    })
}

#[no_mangle]
pub unsafe fn fpu_load_status_word() -> u16 {
    dbg_assert!(*fpu_stack_ptr < 8);
    return *fpu_status_word & !(7 << 11) | (*fpu_stack_ptr as u16) << 11;
}
#[no_mangle]
pub unsafe fn fpu_fadd(target_index: i32, val: F80) {
    F80::clear_exception_flags();
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, x + y);
        *fpu_status_word |= F80::get_exception_flags() as u16;
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 + val);
    *fpu_status_word |= F80::get_exception_flags() as u16;
}
pub unsafe fn fpu_fclex() { *fpu_status_word = 0; }
#[no_mangle]
pub unsafe fn fpu_fcmovcc(condition: bool, r: i32) {
    // outside of the condition is correct: A stack fault happens even if the condition is not
    // fulfilled
    let x = fpu_get_sti(r);
    if fpu_sti_empty(r) {
        fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN)
    }
    else {
        if condition {
            fpu_write_st(*fpu_stack_ptr as i32, x);
            *fpu_stack_empty &= !(1 << *fpu_stack_ptr)
        };
    }
}

#[no_mangle]
pub unsafe fn fpu_fcom(y: F80) {
    F80::clear_exception_flags();
    let x = fpu_get_st0();
    *fpu_status_word &= !FPU_RESULT_FLAGS;
    match x.partial_cmp(&y) {
        Some(std::cmp::Ordering::Greater) => {},
        Some(std::cmp::Ordering::Less) => *fpu_status_word |= FPU_C0,
        Some(std::cmp::Ordering::Equal) => *fpu_status_word |= FPU_C3,
        None => *fpu_status_word |= FPU_C0 | FPU_C2 | FPU_C3,
    }
    *fpu_status_word |= F80::get_exception_flags() as u16;
}

#[no_mangle]
pub unsafe fn fpu_fcomi(r: i32) {
    F80::clear_exception_flags();
    let x = fpu_get_st0();
    let y = fpu_get_sti(r);
    *flags_changed = 0;
    *flags &= !FLAGS_ALL;
    match x.partial_cmp(&y) {
        Some(std::cmp::Ordering::Greater) => {},
        Some(std::cmp::Ordering::Less) => *flags |= 1,
        Some(std::cmp::Ordering::Equal) => *flags |= FLAG_ZERO,
        None => *flags |= 1 | FLAG_PARITY | FLAG_ZERO,
    }
    *fpu_status_word |= F80::get_exception_flags() as u16;
}

#[no_mangle]
pub unsafe fn fpu_fcomip(r: i32) {
    fpu_fcomi(r);
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_pop() {
    dbg_assert!(*fpu_stack_ptr < 8);
    *fpu_stack_empty |= 1 << *fpu_stack_ptr;
    *fpu_stack_ptr = *fpu_stack_ptr + 1 & 7;
}

#[no_mangle]
pub unsafe fn fpu_fcomp(val: F80) {
    fpu_fcom(val);
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_fdiv(target_index: i32, val: F80) {
    F80::clear_exception_flags();
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, x / y);
        *fpu_status_word |= F80::get_exception_flags() as u16;
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 / val);
    *fpu_status_word |= F80::get_exception_flags() as u16;
}
#[no_mangle]
pub unsafe fn fpu_fdivr(target_index: i32, val: F80) {
    F80::clear_exception_flags();
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, y / x);
        *fpu_status_word |= F80::get_exception_flags() as u16;
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, val / st0);
    *fpu_status_word |= F80::get_exception_flags() as u16;
}
#[no_mangle]
pub unsafe fn fpu_ffree(r: i32) { *fpu_stack_empty |= 1 << (*fpu_stack_ptr as i32 + r & 7); }

pub unsafe fn fpu_fildm16(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i16(addr))); }
pub unsafe fn fpu_fildm32(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn fpu_fildm64(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_i64(addr))); }

#[no_mangle]
pub unsafe fn fpu_push(x: F80) {
    *fpu_stack_ptr = *fpu_stack_ptr - 1 & 7;
    if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 {
        *fpu_status_word &= !FPU_C1;
        *fpu_stack_empty &= !(1 << *fpu_stack_ptr);
        fpu_write_st(*fpu_stack_ptr as i32, x);
    }
    else {
        *fpu_status_word |= FPU_C1;
        fpu_stack_fault();
        fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN);
    };
}
pub unsafe fn fpu_finit() {
    // FINIT resets tags/control/TOP, not the physical register contents.
    // Keep their authoritative shadow values until overwritten or observed;
    // eagerly materializing and invalidating all eight slots adds no safety.
    set_control_word(0x37F);
    *fpu_status_word = 0;
    *fpu_ip = 0;
    *fpu_dp = 0;
    *fpu_opcode = 0;
    *fpu_stack_empty = 0xFF;
    *fpu_stack_ptr = 0;
}

#[no_mangle]
pub unsafe fn set_control_word(cw: u16) {
    *fpu_control_word = cw;

    let rc = cw >> 10 & 3;
    F80::set_rounding_mode(match rc {
        0 => RoundingMode::NearEven,
        1 => RoundingMode::Floor,
        2 => RoundingMode::Ceil,
        3 => RoundingMode::Trunc,
        _ => {
            dbg_assert!(false);
            RoundingMode::NearEven
        },
    });

    let precision_control = cw >> 8 & 3;
    F80::set_precision(match precision_control {
        0 => Precision::P32,
        1 => Precision::P80, // undefined
        2 => Precision::P64,
        3 => Precision::P80,
        _ => {
            dbg_assert!(false);
            Precision::P80
        },
    });
}

pub unsafe fn fpu_invalid_arithmetic() { *fpu_status_word |= FPU_EX_I; }

#[no_mangle]
pub unsafe fn fpu_convert_to_i16(f: F80) -> i16 {
    let st0 = fpu_convert_to_i32(f);
    if st0 < -0x8000 || st0 > 0x7FFF {
        fpu_invalid_arithmetic();
        -0x8000
    }
    else {
        st0 as i16
    }
}
pub unsafe fn fpu_fistm16(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 2));
    let v = fpu_convert_to_i16(fpu_get_st0());
    safe_write16(addr, v as i32 & 0xFFFF).unwrap();
}
pub unsafe fn fpu_fistm16p(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 2));
    let v = fpu_convert_to_i16(fpu_get_st0());
    safe_write16(addr, v as i32 & 0xFFFF).unwrap();
    fpu_pop();
}
#[no_mangle]
pub unsafe fn fpu_truncate_to_i16(f: F80) -> i16 {
    let st0 = fpu_truncate_to_i32(f);
    if st0 < -0x8000 || st0 > 0x7FFF {
        fpu_invalid_arithmetic();
        -0x8000
    }
    else {
        st0 as i16
    }
}
pub unsafe fn fpu_fisttpm16(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 2));
    let v = fpu_truncate_to_i16(fpu_get_st0());
    safe_write16(addr, v as i32 & 0xFFFF).unwrap();
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_convert_to_i32(f: F80) -> i32 {
    F80::clear_exception_flags();
    let x = f.to_i32();
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
pub unsafe fn fpu_fistm32(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 4));
    let v = fpu_convert_to_i32(fpu_get_st0());
    safe_write32(addr, v).unwrap();
}
pub unsafe fn fpu_fistm32p(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 4));
    let v = fpu_convert_to_i32(fpu_get_st0());
    safe_write32(addr, v).unwrap();
    fpu_pop();
}
#[no_mangle]
pub unsafe fn fpu_truncate_to_i32(f: F80) -> i32 {
    F80::clear_exception_flags();
    let x = f.truncate_to_i32();
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
pub unsafe fn fpu_fisttpm32(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 4));
    let v = fpu_truncate_to_i32(fpu_get_st0());
    safe_write32(addr, v).unwrap();
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_convert_to_i64(f: F80) -> i64 {
    F80::clear_exception_flags();
    let x = f.to_i64();
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
pub unsafe fn fpu_fistm64p(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 8));
    let v = fpu_convert_to_i64(fpu_get_st0());
    safe_write64(addr, v as u64).unwrap();
    fpu_pop();
}
#[no_mangle]
pub unsafe fn fpu_truncate_to_i64(f: F80) -> i64 {
    F80::clear_exception_flags();
    let x = f.truncate_to_i64();
    *fpu_status_word |= F80::get_exception_flags() as u16;
    x
}
pub unsafe fn fpu_fisttpm64(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 8));
    let v = fpu_truncate_to_i64(fpu_get_st0());
    safe_write64(addr, v as u64).unwrap();
    fpu_pop();
}

pub unsafe fn fpu_fldcw(addr: i32) {
    let word = return_on_pagefault!(safe_read16(addr)) as u16;
    set_control_word(word);
}

#[no_mangle]
pub unsafe fn fpu_fldenv16(addr: i32) {
    // protected-mode layout (the real-mode layout stores the linear ip/dp)
    set_control_word(safe_read16(addr).unwrap() as u16);
    fpu_set_status_word(safe_read16(addr + 2).unwrap() as u16);
    fpu_set_tag_word(safe_read16(addr + 4).unwrap());
    *fpu_ip = safe_read16(addr + 6).unwrap();
    *fpu_ip_selector = safe_read16(addr + 8).unwrap();
    *fpu_dp = safe_read16(addr + 10).unwrap();
    *fpu_dp_selector = safe_read16(addr + 12).unwrap()
}
#[no_mangle]
pub unsafe fn fpu_fldenv32(addr: i32) {
    // protected-mode layout (the real-mode layout stores the linear ip/dp)
    set_control_word(safe_read16(addr).unwrap() as u16);
    fpu_set_status_word(safe_read16(addr + 4).unwrap() as u16);
    fpu_set_tag_word(safe_read16(addr + 8).unwrap());
    *fpu_ip = safe_read32s(addr + 12).unwrap();
    *fpu_ip_selector = safe_read16(addr + 16).unwrap();
    *fpu_opcode = safe_read16(addr + 18).unwrap();
    *fpu_dp = safe_read32s(addr + 20).unwrap();
    *fpu_dp_selector = safe_read16(addr + 24).unwrap()
}
pub unsafe fn fpu_unimpl() {
    dbg_assert!(false);
    trigger_ud();
}
pub unsafe fn fpu_set_tag_word(tag_word: i32) {
    *fpu_stack_empty = 0;
    for i in 0..8 {
        let empty = tag_word >> (2 * i) & 3 == 3;
        *fpu_stack_empty |= (empty as u8) << i;
    }
}
pub unsafe fn fpu_set_status_word(sw: u16) {
    *fpu_status_word = sw & !(7 << 11);
    *fpu_stack_ptr = (sw >> 11 & 7) as u8;
}

pub unsafe fn fpu_fldm32(addr: i32) {
    F80::clear_exception_flags();
    fpu_push_m32_bits(return_on_pagefault!(safe_read32s(addr)));
}
pub unsafe fn fpu_fldm64(addr: i32) {
    F80::clear_exception_flags();
    fpu_push_m64_bits(return_on_pagefault!(safe_read64s(addr)));
}
pub unsafe fn fpu_fldm80(addr: i32) { fpu_push(return_on_pagefault!(fpu_load_m80(addr))); }

#[no_mangle]
pub unsafe fn fpu_fmul(target_index: i32, val: F80) {
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, x * y);
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 * val);
}
pub unsafe fn fpu_fnstsw_mem(addr: i32) {
    return_on_pagefault!(safe_write16(addr, fpu_load_status_word().into()));
}
pub unsafe fn fpu_fnstsw_reg() { write_reg16(AX, fpu_load_status_word().into()); }
pub unsafe fn fpu_fprem(ieee: bool) {
    // false: Faster, fails nasmtests
    // true: Slower, fails qemutests
    let intel_compatibility = false;

    let st0 = fpu_get_st0();
    let st1 = fpu_get_sti(1);

    if st1 == F80::ZERO {
        if st0 == F80::ZERO {
            fpu_invalid_arithmetic();
        }
        else {
            fpu_zero_fault();
        }
        fpu_write_st(*fpu_stack_ptr as i32, F80::INDEFINITE_NAN);
        return;
    }

    let exp0 = st0.log2();
    let exp1 = st1.log2();
    let d = (exp0 - exp1).abs();
    if !intel_compatibility || d < F80::of_f64(f64::to_bits(64.0)) {
        let fprem_quotient = if ieee { (st0 / st1).round() } else { (st0 / st1).trunc() };
        fpu_write_st(*fpu_stack_ptr as i32, st0 - st1 * fprem_quotient);
        let fprem_quotient = fprem_quotient.to_i32();
        *fpu_status_word &= !(FPU_C0 | FPU_C1 | FPU_C3);
        if 0 != fprem_quotient & 1 {
            *fpu_status_word |= FPU_C1
        }
        if 0 != fprem_quotient & 1 << 1 {
            *fpu_status_word |= FPU_C3
        }
        if 0 != fprem_quotient & 1 << 2 {
            *fpu_status_word |= FPU_C0
        }
        *fpu_status_word &= !FPU_C2;
    }
    else {
        let n = F80::of_f64(f64::to_bits(32.0));
        let fprem_quotient =
            (if ieee { (st0 / st1).round() } else { (st0 / st1).trunc() } / (d - n).two_pow());
        fpu_write_st(
            *fpu_stack_ptr as i32,
            st0 - st1 * fprem_quotient * (d - n).two_pow(),
        );
        *fpu_status_word |= FPU_C2;
    }
}

pub unsafe fn fpu_frstor16(_addr: i32) {
    dbg_log!("frstor16");
    fpu_unimpl();
}
pub unsafe fn fpu_frstor32(addr: i32) { let _ = fpu_frstor32_checked(addr); }

pub unsafe fn fpu_frstor32_checked(mut addr: i32) -> OrPageFault<()> {
    readable_or_pagefault(addr, 28 + 8 * 10)?;
    fpu_fldenv32(addr);
    addr += 28;
    for i in 0..8 {
        let reg_index = *fpu_stack_ptr as i32 + i & 7;
        fpu_write_st(reg_index, fpu_load_m80(addr).unwrap());
        addr += 10;
    }

    Ok(())
}

pub unsafe fn fpu_fsave16(_addr: i32) {
    dbg_log!("fsave16");
    fpu_unimpl();
}
pub unsafe fn fpu_fsave32(addr: i32) { let _ = fpu_fsave32_checked(addr); }

pub unsafe fn fpu_fsave32_checked(mut addr: i32) -> OrPageFault<()> {
    fpu_sync_all();
    writable_or_pagefault(addr, 108)?;
    fpu_fstenv32(addr);
    addr += 28;
    for i in 0..8 {
        let reg_index = i + *fpu_stack_ptr as i32 & 7;
        fpu_store_m80(addr, *fpu_st.offset(reg_index as isize));
        addr += 10;
    }
    fpu_finit();

    Ok(())
}

pub unsafe fn fpu_store_m80(addr: i32, f: F80) {
    // writable_or_pagefault must have checked called by the caller!
    safe_write64(addr, f.mantissa).unwrap();
    safe_write16(addr + 8, f.sign_exponent as i32).unwrap();
}

#[no_mangle]
pub unsafe fn fpu_fstenv16(addr: i32) {
    safe_write16(addr + 0, *fpu_control_word as i32).unwrap();
    safe_write16(addr + 2, fpu_load_status_word() as i32).unwrap();
    safe_write16(addr + 4, fpu_load_tag_word()).unwrap();
    safe_write16(addr + 6, *fpu_ip & 0xFFFF).unwrap();
    safe_write16(addr + 8, *fpu_ip_selector).unwrap();
    safe_write16(addr + 10, *fpu_dp & 0xFFFF).unwrap();
    safe_write16(addr + 12, *fpu_dp_selector).unwrap();
}

#[no_mangle]
pub unsafe fn fpu_fstenv32(addr: i32) {
    let high_bits = 0xFFFF0000u32 as i32;
    safe_write32(addr + 0, high_bits + *fpu_control_word as i32).unwrap();
    safe_write32(addr + 4, high_bits + fpu_load_status_word() as i32).unwrap();
    safe_write32(addr + 8, high_bits + fpu_load_tag_word()).unwrap();
    safe_write32(addr + 12, *fpu_ip).unwrap();
    safe_write16(addr + 16, *fpu_ip_selector).unwrap();
    safe_write16(addr + 18, *fpu_opcode).unwrap();
    safe_write32(addr + 20, *fpu_dp).unwrap();
    safe_write32(addr + 24, high_bits | *fpu_dp_selector).unwrap();
}
#[no_mangle]
pub unsafe fn fpu_load_tag_word() -> i32 {
    fpu_sync_all();
    let mut tag_word = 0;
    for i in 0..8 {
        let value = *fpu_st.offset(i as isize);
        if 0 != *fpu_stack_empty >> i & 1 {
            tag_word |= 3 << (i << 1)
        }
        else if value == F80::ZERO {
            tag_word |= 1 << (i << 1)
        }
        else if !value.is_finite() {
            tag_word |= 2 << (i << 1)
        }
    }
    return tag_word;
}
#[no_mangle]
pub unsafe fn fpu_fst(r: i32) {
    let index: i32 = *fpu_stack_ptr as i32 + r & 7;
    fpu_write_st(index, fpu_get_st0());
    if 0 == ((*fpu_stack_empty >> *fpu_stack_ptr) & 1) {
        *fpu_stack_empty &= !(1 << index);
    }
}
pub unsafe fn fpu_fst80p(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 10));
    fpu_store_m80(addr, fpu_get_st0());
    fpu_pop();
}

pub unsafe fn fpu_fstcw(addr: i32) {
    return_on_pagefault!(safe_write16(addr, (*fpu_control_word).into()));
}

pub unsafe fn fpu_fstm32(addr: i32) {
    return_on_pagefault!(fpu_store_m32(addr, fpu_get_st0()));
}
pub unsafe fn fpu_store_m32(addr: i32, x: F80) -> OrPageFault<()> {
    F80::clear_exception_flags();
    safe_write32(addr, x.to_f32())?;
    *fpu_status_word |= F80::get_exception_flags() as u16;
    Ok(())
}
pub unsafe fn fpu_fstm32p(addr: i32) {
    return_on_pagefault!(fpu_store_m32(addr, fpu_get_st0()));
    fpu_pop();
}
pub unsafe fn fpu_fstm64(addr: i32) {
    if let Some(value) = cached_value(0) {
        F80::clear_exception_flags();
        return_on_pagefault!(safe_write64(addr, value.to_bits()));
        return;
    }
    return_on_pagefault!(fpu_store_m64(addr, fpu_get_st0()));
}
pub unsafe fn fpu_store_m64(addr: i32, x: F80) -> OrPageFault<()> {
    F80::clear_exception_flags();
    safe_write64(addr, x.to_f64())?;
    *fpu_status_word |= F80::get_exception_flags() as u16;
    Ok(())
}
pub unsafe fn fpu_fstm64p(addr: i32) {
    if let Some(value) = cached_value(0) {
        F80::clear_exception_flags();
        return_on_pagefault!(safe_write64(addr, value.to_bits()));
        fpu_pop();
        return;
    }
    // XXX: writable_or_pagefault before get_st0
    return_on_pagefault!(fpu_store_m64(addr, fpu_get_st0()));
    fpu_pop();
}
#[no_mangle]
pub unsafe fn fpu_fstp(r: i32) {
    fpu_fst(r);
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_fbstp(addr: i32) {
    let st0 = fpu_get_st0();
    let mut x = st0.to_i64().unsigned_abs();
    if x <= 99_9999_9999_9999_9999 {
        for i in 0..=8 {
            let low = x % 10;
            x /= 10;
            let high = x % 10;
            x /= 10;
            safe_write8(addr + i, (high as i32) << 4 | low as i32).unwrap();
        }
        safe_write8(addr + 9, if st0.sign() { 0x80 } else { 0 }).unwrap();
    }
    else {
        fpu_invalid_arithmetic();
        safe_write64(addr + 0, 0xC000_0000_0000_0000).unwrap();
        safe_write16(addr + 8, 0xFFFF).unwrap();
    }
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_fsub(target_index: i32, val: F80) {
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, x - y);
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, st0 - val)
}
#[no_mangle]
pub unsafe fn fpu_fsubr(target_index: i32, val: F80) {
    if let Some(x) = cached_value(0) {
        let y = f64::from_bits(val.to_f64());
        crate::softfloat::count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
        write_cached(target_index as u32, y - x);
        return;
    }
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32 + target_index & 7, val - st0)
}

pub unsafe fn fpu_ftst() {
    let x = fpu_get_st0();
    *fpu_status_word &= !FPU_RESULT_FLAGS;
    if x.is_nan() {
        *fpu_status_word |= FPU_C3 | FPU_C2 | FPU_C0
    }
    else if x == F80::ZERO {
        *fpu_status_word |= FPU_C3
    }
    else if x < F80::ZERO {
        *fpu_status_word |= FPU_C0
    }
    // TODO: unordered (x is nan, etc)
}

#[no_mangle]
pub unsafe fn fpu_fucom(r: i32) {
    F80::clear_exception_flags();
    let x = fpu_get_st0();
    let y = fpu_get_sti(r);
    *fpu_status_word &= !FPU_RESULT_FLAGS;
    match x.partial_cmp_quiet(&y) {
        Some(std::cmp::Ordering::Greater) => {},
        Some(std::cmp::Ordering::Less) => *fpu_status_word |= FPU_C0,
        Some(std::cmp::Ordering::Equal) => *fpu_status_word |= FPU_C3,
        None => *fpu_status_word |= FPU_C0 | FPU_C2 | FPU_C3,
    }
    *fpu_status_word |= F80::get_exception_flags() as u16;
}

#[no_mangle]
pub unsafe fn fpu_fucomi(r: i32) {
    F80::clear_exception_flags();
    let x = fpu_get_st0();
    let y = fpu_get_sti(r);
    *flags_changed = 0;
    *flags &= !FLAGS_ALL;
    match x.partial_cmp_quiet(&y) {
        Some(std::cmp::Ordering::Greater) => {},
        Some(std::cmp::Ordering::Less) => *flags |= 1,
        Some(std::cmp::Ordering::Equal) => *flags |= FLAG_ZERO,
        None => *flags |= 1 | FLAG_PARITY | FLAG_ZERO,
    }
    *fpu_status_word |= F80::get_exception_flags() as u16;
}

#[no_mangle]
pub unsafe fn fpu_fucomip(r: i32) {
    fpu_fucomi(r);
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_fucomp(r: i32) {
    fpu_fucom(r);
    fpu_pop();
}

#[no_mangle]
pub unsafe fn fpu_fucompp() {
    fpu_fucom(1);
    fpu_pop();
    fpu_pop();
}

pub unsafe fn fpu_fxam() {
    let x = fpu_get_st0();
    *fpu_status_word &= !FPU_RESULT_FLAGS;
    *fpu_status_word |= (x.sign() as u16) << 9;
    if 0 != *fpu_stack_empty >> *fpu_stack_ptr & 1 {
        *fpu_status_word |= FPU_C3 | FPU_C0
    }
    else if x.is_nan() {
        *fpu_status_word |= FPU_C0
    }
    else if x == F80::ZERO {
        *fpu_status_word |= FPU_C3
    }
    else if !x.is_finite() {
        *fpu_status_word |= FPU_C2 | FPU_C0
    }
    else {
        *fpu_status_word |= FPU_C2
    }
    // TODO:
    // Unsupported, Denormal
}

#[no_mangle]
pub unsafe fn fpu_fxch(i: i32) {
    let sti = fpu_get_sti(i);
    fpu_write_st(*fpu_stack_ptr as i32 + i & 7, fpu_get_st0());
    fpu_write_st(*fpu_stack_ptr as i32, sti);
}
pub unsafe fn fpu_fyl2x() {
    let st0 = fpu_get_st0();
    if st0 < F80::ZERO {
        fpu_invalid_arithmetic();
    }
    else if st0 == F80::ZERO {
        fpu_zero_fault();
    }
    fpu_write_st(
        *fpu_stack_ptr as i32 + 1 & 7,
        fpu_get_sti(1) * st0.ln() / F80::LN_2,
    );
    fpu_pop();
}

pub unsafe fn fpu_fxtract() {
    let st0 = fpu_get_st0();
    if st0 == F80::ZERO {
        fpu_zero_fault();
        fpu_write_st(*fpu_stack_ptr as i32, F80::NEG_INFINITY);
        fpu_push(st0);
    }
    else {
        let exp = st0.exponent();
        fpu_write_st(*fpu_stack_ptr as i32, F80::of_i32(exp.into()));
        fpu_push(F80 {
            sign_exponent: 0x3FFF,
            mantissa: st0.mantissa,
        });
    }
}

pub unsafe fn fwait() {
    // NOP unless FPU instructions run in parallel with CPU instructions
}

pub unsafe fn fpu_fchs() {
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32, -st0);
}

pub unsafe fn fpu_fabs() {
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32, st0.abs());
}

pub unsafe fn fpu_f2xm1() {
    let st0 = fpu_get_st0();
    let r = st0.two_pow() - F80::ONE;
    fpu_write_st(*fpu_stack_ptr as i32, r)
}

pub unsafe fn fpu_fptan() {
    if let Some(x) = cached_value(0).filter(|v| v.is_finite()) {
        if *fpu_stack_empty & (1 << ((*fpu_stack_ptr + 7) & 7)) != 0 {
            write_cached(0, x.tan());
            push_cached(1.0);
            *fpu_status_word &= !FPU_C2;
            return;
        }
    }
    let st0 = fpu_get_st0();
    //if -pow(2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) {
    fpu_write_st(*fpu_stack_ptr as i32, st0.tan());
    // no bug: push constant 1
    fpu_push(F80::ONE);
    *fpu_status_word &= !FPU_C2;
    //}
    //else {
    //    *fpu_status_word |= FPU_C2;
    //}
}

pub unsafe fn fpu_fpatan() {
    if let (Some(x), Some(y)) = (cached_value(0), cached_value(1)) {
        if x.is_finite() && y.is_finite() {
            write_cached(1, y.atan2(x));
            fpu_pop();
            return;
        }
    }
    let st0 = fpu_get_st0();
    let st1 = fpu_get_sti(1);
    fpu_write_st(*fpu_stack_ptr as i32 + 1 & 7, st1.atan2(st0));
    fpu_pop();
}

pub unsafe fn fpu_fyl2xp1() {
    // fyl2xp1: y * log2(x+1) and pop
    let st0 = fpu_get_st0();
    let st1 = fpu_get_sti(1);
    let y = st1 * (st0 + F80::ONE).ln() / F80::LN_2;
    fpu_write_st(*fpu_stack_ptr as i32 + 1 & 7, y);
    fpu_pop();
}

pub unsafe fn fpu_fsqrt() {
    let st0 = fpu_get_st0();
    //if st0 < 0.0 {
    //    fpu_invalid_arithmetic();
    //}
    fpu_write_st(*fpu_stack_ptr as i32, st0.sqrt())
}

pub unsafe fn fpu_fsincos() {
    if let Some(x) = cached_value(0).filter(|v| v.is_finite()) {
        if *fpu_stack_empty & (1 << ((*fpu_stack_ptr + 7) & 7)) != 0 {
            write_cached(0, x.sin());
            push_cached(x.cos());
            *fpu_status_word &= !FPU_C2;
            return;
        }
    }
    let st0 = fpu_get_st0();
    //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) {
    fpu_write_st(*fpu_stack_ptr as i32, st0.sin());
    fpu_push(st0.cos());
    *fpu_status_word &= !FPU_C2;
    //}
    //else {
    //    *fpu_status_word |= FPU_C2;
    //}
}

pub unsafe fn fpu_frndint() {
    let st0 = fpu_get_st0();
    fpu_write_st(*fpu_stack_ptr as i32, st0.round());
}

pub unsafe fn fpu_fscale() {
    let st0 = fpu_get_st0();
    let y = st0.scale(fpu_get_sti(1));
    fpu_write_st(*fpu_stack_ptr as i32, y);
}

pub unsafe fn fpu_fsin() {
    if let Some(x) = cached_value(0).filter(|v| v.is_finite()) {
        write_cached(0, x.sin());
        *fpu_status_word &= !FPU_C2;
        return;
    }
    let st0 = fpu_get_st0();
    //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) {
    fpu_write_st(*fpu_stack_ptr as i32, st0.sin());
    *fpu_status_word &= !FPU_C2;
    //}
    //else {
    //    *fpu_status_word |= FPU_C2;
    //}
}

pub unsafe fn fpu_fcos() {
    if let Some(x) = cached_value(0).filter(|v| v.is_finite()) {
        write_cached(0, x.cos());
        *fpu_status_word &= !FPU_C2;
        return;
    }
    let st0 = fpu_get_st0();
    //if pow(-2.0, 63.0) < st0 && st0 < pow(2.0, 63.0) {
    fpu_write_st(*fpu_stack_ptr as i32, st0.cos());
    *fpu_status_word &= !FPU_C2;
    //}
    //else {
    //    *fpu_status_word |= FPU_C2;
    //}
}

pub unsafe fn fpu_fdecstp() {
    *fpu_stack_ptr = *fpu_stack_ptr - 1 & 7;
    *fpu_status_word &= !FPU_C1
}

pub unsafe fn fpu_fincstp() {
    *fpu_stack_ptr = *fpu_stack_ptr + 1 & 7;
    *fpu_status_word &= !FPU_C1
}
                                                                                                                                                                                                                                                                                                          source/v64/src/rust/cpu/global_pointers.rs                                                          0000644 0000000 0000000 00000012424 00000000000 015773  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_upper_case_globals)]

use crate::cpu::cpu::reg128;
use crate::softfloat::F80;
use crate::state_flags::CachedStateFlags;

// The fields of the x86 core's state block (crate::state_block)
pub use crate::state_block::state_base;

// BEGIN GENERATED by gen/state_layout.js (edit the layout there)
state!(reg8: u8 = 64);
state!(reg16: u16 = 64);
state!(reg32: i32 = 64);
state!(last_op_size: i32 = 96);
state!(flags_changed: i32 = 100);
state!(last_op1: i32 = 104);
state!(state_flags: CachedStateFlags = 108);
state!(last_result: i32 = 112);
state!(flags: i32 = 120);
state!(segment_access_bytes: u8 = 512); // TODO: reorder below segment_limits
state!(apic_enabled: bool = 548);
state!(acpi_enabled: bool = 552);
state!(instruction_pointer: i32 = 556);
state!(previous_ip: i32 = 560);
state!(idtr_size: i32 = 564);
state!(idtr_offset: i32 = 568);
state!(gdtr_size: i32 = 572);
state!(gdtr_offset: i32 = 576);
state!(cr: i32 = 580);
state!(cpl: u8 = 612);
state!(in_hlt: bool = 616);
state!(last_virt_eip: i32 = 620);
state!(eip_phys: i32 = 624);
state!(nmi_blocked: bool = 628);
state!(interrupt_shadow: u8 = 632);
state!(sysenter_cs: i32 = 636);
state!(sysenter_esp: i32 = 640);
state!(sysenter_eip: i32 = 644);
state!(prefixes: u8 = 648);
state!(instruction_counter: u32 = 664);
state!(sreg: u16 = 668);
state!(dreg: i32 = 684);
state!(svga_dirty_bitmap_min_offset: u32 = 716); // filled in by svga_fill_pixel_buffer, read by javacsript for optimised putImageData calls
state!(svga_dirty_bitmap_max_offset: u32 = 720);
state!(segment_is_null: bool = 724);
state!(segment_offsets: i32 = 736);
state!(segment_limits: u32 = 768);
state!(protected_mode: bool = 800);
state!(is_32: bool = 804);
state!(stack_size_32: bool = 808);
state!(memory_size: u32 = 812);
state!(fpu_stack_empty: u8 = 816);
state!(mxcsr: i32 = 824);
state!(reg_xmm: reg128 = 832);
state!(current_tsc: u64 = 960);
state!(reg_pdpte: u64 = 968); // 4 64-bit entries
state!(fpu_stack_ptr: u8 = 1032);
state!(fpu_control_word: u16 = 1036);
state!(fpu_status_word: u16 = 1040);
state!(fpu_opcode: i32 = 1044);
state!(fpu_ip: i32 = 1048);
state!(fpu_ip_selector: i32 = 1052);
state!(fpu_dp: i32 = 1056);
state!(fpu_dp_selector: i32 = 1060);
state!(tss_size_32: bool = 1128);
state!(sse_scratch_register: reg128 = 1136);
state!(fpu_st: F80 = 1152);
// f64 shadow of the physical x87 registers (cpu::fpu), with VALID/DIRTY
// masks, at fixed addresses so natively generated IR fixtures stay valid.
state!(x87_shadow_values: [u64; 8] = 1280);
state!(x87_shadow_valid: u32 = 1344);
state!(x87_shadow_dirty: u32 = 1348);
// Nonzero while generated IR code may inline fast-math x87 on that cache.
state!(x87_native_policy: u8 = 1352);
state!(slice_budget: u32 = 1356);
state!(x64_gpr_hi: u32 = 1360);
state!(x64_gpr_ext_lo: u32 = 1424);
state!(x64_xmm_ext: reg128 = 1456);
state!(x64_rip_hi: u32 = 1584);
state!(x64_previous_ip_hi: u32 = 1588);
state!(x64_idtr_base_hi: u32 = 1592);
state!(x64_gdtr_base_hi: u32 = 1596);
state!(x64_cr_hi: u32 = 1600);
state!(x64_dr_hi: u32 = 1632);
state!(x64_segment_base_hi: u32 = 1664);
state!(x64_efer: u64 = 1696);
state!(x64_kernel_gs_base: u64 = 1704);
state!(x64_star: u64 = 1712);
state!(x64_lstar: u64 = 1720);
state!(x64_cstar: u64 = 1728);
state!(x64_sfmask: u64 = 1736);
state!(x64_cs_long: u8 = 1744);
state!(x64_rex: u8 = 1748);
state!(x64_cr8: u64 = 1752);
state!(x64_sysenter_esp_hi: u32 = 1760);
state!(x64_sysenter_eip_hi: u32 = 1764);
state!(x64_fpu_ip_hi: u32 = 1768);
state!(x64_fpu_dp_hi: u32 = 1772);
state!(x64_pat: u64 = 1776);
state!(x64_tsc_aux: u32 = 1784);
state!(x64_page_exit: u32 = 1792);
state!(x64_jac_base: u32 = 1796);
state!(x64_jac_epoch: u64 = 1800);
state!(x64_page_linear: u64 = 1808);
state!(x64_page_chain: u32 = 1816);
state!(x64_code_base: u32 = 1820);
state!(x64_page_lazy_kind: u32 = 1824);
state!(x64_page_lazy_a: u64 = 1832);
state!(x64_page_lazy_b: u64 = 1840);
state!(x64_page_rep_elements: u32 = 1848);
state!(smm_state: u32 = 1856);
state!(smbase: u32 = 1860);
state!(x64_chain_gprs: u64 = 1864);
// Address of cpu::tlb_data, written at startup. Generated IR code loads it
// from this fixed slot (below --global-base) instead of calling an import.
state!(ir_tlb_base: u32 = 2048);
state!(x64_mtrr_def_type: u64 = 2056);
state!(x64_mtrr_fixed: u64 = 2064);
state!(x64_mtrr_var: u64 = 2152);
state!(x64_mcg_status: u64 = 2280);
state!(x64_mcg_ctl: u64 = 2288);
state!(x64_mc_banks: u64 = 2296);
state!(xcr0: u64 = 2432);
state!(xss: u64 = 2440);
state!(ymm_hi: reg128 = 2448);
// END GENERATED

pub fn get_reg32_offset(r: u32) -> u32 {
    dbg_assert!(r < 8);
    (unsafe { reg32.offset(r as isize) }) as u32
}

pub fn get_reg_mmx_offset(r: u32) -> u32 {
    dbg_assert!(r < 8);
    (unsafe { fpu_st.offset(r as isize) }) as u32
}

pub fn get_reg_xmm_offset(r: u32) -> u32 {
    dbg_assert!(r < 8);
    (unsafe { reg_xmm.offset(r as isize) }) as u32
}

pub fn get_sreg_offset(s: u32) -> u32 {
    dbg_assert!(s < 6);
    (unsafe { sreg.offset(s as isize) }) as u32
}

pub fn get_seg_offset(s: u32) -> u32 {
    dbg_assert!(s < 8);
    (unsafe { segment_offsets.offset(s as isize) }) as u32
}

pub fn get_segment_is_null_offset(s: u32) -> u32 {
    dbg_assert!(s < 8);
    (unsafe { segment_is_null.offset(s as isize) }) as u32
}

pub fn get_creg_offset(i: u32) -> u32 {
    dbg_assert!(i < 8);
    (unsafe { cr.offset(i as isize) }) as u32
}
                                                                                                                                                                                                                                            source/v64/src/rust/cpu/instructions.rs                                                             0000644 0000000 0000000 00000310551 00000000000 015356  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_snake_case)]

use crate::cpu::arith::*;
use crate::cpu::cpu::js;
use crate::cpu::cpu::*;
use crate::cpu::fpu::*;
use crate::cpu::global_pointers::*;
use crate::cpu::misc_instr::*;
use crate::cpu::string::*;
use crate::prefix;
use crate::softfloat::F80;

pub unsafe fn instr_00_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| add8(x, read_reg8(r))) }
pub unsafe fn instr_00_reg(r1: i32, r: i32) { write_reg8(r1, add8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_01_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| add16(x, read_reg16(r)))
}
pub unsafe fn instr16_01_reg(r1: i32, r: i32) {
    write_reg16(r1, add16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_01_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| add32(x, read_reg32(r)))
}
pub unsafe fn instr32_01_reg(r1: i32, r: i32) {
    write_reg32(r1, add32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_02_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        add8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_02_reg(r1: i32, r: i32) { write_reg8(r, add8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_03_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        add16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_03_reg(r1: i32, r: i32) {
    write_reg16(r, add16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_03_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        add32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_03_reg(r1: i32, r: i32) {
    write_reg32(r, add32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_04(imm8: i32) { write_reg8(AL, add8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_05(imm16: i32) { write_reg16(AX, add16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_05(imm32: i32) { write_reg32(EAX, add32(read_reg32(EAX), imm32)); }
pub unsafe fn instr16_06() {
    return_on_pagefault!(push16(*sreg.offset(ES as isize) as i32));
}
pub unsafe fn instr32_06() { return_on_pagefault!(push32_sreg(ES)) }

#[no_mangle]
pub unsafe fn instr16_07() {
    if !switch_seg(ES, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) {
        return;
    }
    adjust_stack_reg(2);
}
#[no_mangle]
pub unsafe fn instr32_07() {
    if !switch_seg(
        ES,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF,
    ) {
        return;
    }
    adjust_stack_reg(4);
}

pub unsafe fn instr_08_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| or8(x, read_reg8(r))) }
pub unsafe fn instr_08_reg(r1: i32, r: i32) { write_reg8(r1, or8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_09_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| or16(x, read_reg16(r)))
}
pub unsafe fn instr16_09_reg(r1: i32, r: i32) {
    write_reg16(r1, or16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_09_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| or32(x, read_reg32(r)))
}
pub unsafe fn instr32_09_reg(r1: i32, r: i32) {
    write_reg32(r1, or32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_0A_mem(addr: i32, r: i32) {
    write_reg8(r, or8(read_reg8(r), return_on_pagefault!(safe_read8(addr))));
}
pub unsafe fn instr_0A_reg(r1: i32, r: i32) { write_reg8(r, or8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_0B_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        or16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_0B_reg(r1: i32, r: i32) {
    write_reg16(r, or16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_0B_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        or32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_0B_reg(r1: i32, r: i32) {
    write_reg32(r, or32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_0C(imm8: i32) { write_reg8(AL, or8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_0D(imm16: i32) { write_reg16(AX, or16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_0D(imm32: i32) { write_reg32(EAX, or32(read_reg32(EAX), imm32)); }

pub unsafe fn instr16_0E() {
    return_on_pagefault!(push16(*sreg.offset(CS as isize) as i32));
}
pub unsafe fn instr32_0E() { return_on_pagefault!(push32_sreg(CS)) }

pub unsafe fn instr16_0F() { run_instruction0f_16(return_on_pagefault!(read_imm8())); }
pub unsafe fn instr32_0F() { run_instruction0f_32(return_on_pagefault!(read_imm8())); }

pub unsafe fn instr_10_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| adc8(x, read_reg8(r))) }
pub unsafe fn instr_10_reg(r1: i32, r: i32) { write_reg8(r1, adc8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_11_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| adc16(x, read_reg16(r)))
}
pub unsafe fn instr16_11_reg(r1: i32, r: i32) {
    write_reg16(r1, adc16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_11_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| adc32(x, read_reg32(r)))
}
pub unsafe fn instr32_11_reg(r1: i32, r: i32) {
    write_reg32(r1, adc32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_12_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        adc8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_12_reg(r1: i32, r: i32) { write_reg8(r, adc8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_13_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        adc16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_13_reg(r1: i32, r: i32) {
    write_reg16(r, adc16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_13_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        adc32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_13_reg(r1: i32, r: i32) {
    write_reg32(r, adc32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_14(imm8: i32) { write_reg8(AL, adc8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_15(imm16: i32) { write_reg16(AX, adc16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_15(imm32: i32) { write_reg32(EAX, adc32(read_reg32(EAX), imm32)); }

pub unsafe fn instr16_16() {
    return_on_pagefault!(push16(*sreg.offset(SS as isize) as i32));
}
pub unsafe fn instr32_16() { return_on_pagefault!(push32_sreg(SS)) }

#[no_mangle]
pub unsafe fn instr16_17() {
    if !switch_seg(SS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) {
        return;
    }
    adjust_stack_reg(2);
}
#[no_mangle]
pub unsafe fn instr32_17() {
    if !switch_seg(
        SS,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF,
    ) {
        return;
    }
    adjust_stack_reg(4);
}

pub unsafe fn instr_18_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| sbb8(x, read_reg8(r))) }
pub unsafe fn instr_18_reg(r1: i32, r: i32) { write_reg8(r1, sbb8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_19_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| sbb16(x, read_reg16(r)))
}
pub unsafe fn instr16_19_reg(r1: i32, r: i32) {
    write_reg16(r1, sbb16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_19_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| sbb32(x, read_reg32(r)))
}
pub unsafe fn instr32_19_reg(r1: i32, r: i32) {
    write_reg32(r1, sbb32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_1A_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        sbb8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_1A_reg(r1: i32, r: i32) { write_reg8(r, sbb8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_1B_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        sbb16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_1B_reg(r1: i32, r: i32) {
    write_reg16(r, sbb16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_1B_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        sbb32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_1B_reg(r1: i32, r: i32) {
    write_reg32(r, sbb32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_1C(imm8: i32) { write_reg8(AL, sbb8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_1D(imm16: i32) { write_reg16(AX, sbb16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_1D(imm32: i32) { write_reg32(EAX, sbb32(read_reg32(EAX), imm32)); }

pub unsafe fn instr16_1E() {
    return_on_pagefault!(push16(*sreg.offset(DS as isize) as i32));
}
pub unsafe fn instr32_1E() { return_on_pagefault!(push32_sreg(DS)) }

#[no_mangle]
pub unsafe fn instr16_1F() {
    if !switch_seg(DS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) {
        return;
    }
    adjust_stack_reg(2);
}
#[no_mangle]
pub unsafe fn instr32_1F() {
    if !switch_seg(
        DS,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF,
    ) {
        return;
    }
    adjust_stack_reg(4);
}

pub unsafe fn instr_20_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| and8(x, read_reg8(r))) }
pub unsafe fn instr_20_reg(r1: i32, r: i32) { write_reg8(r1, and8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_21_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| and16(x, read_reg16(r)))
}
pub unsafe fn instr16_21_reg(r1: i32, r: i32) {
    write_reg16(r1, and16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_21_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| and32(x, read_reg32(r)))
}
pub unsafe fn instr32_21_reg(r1: i32, r: i32) {
    write_reg32(r1, and32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_22_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        and8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_22_reg(r1: i32, r: i32) { write_reg8(r, and8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_23_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        and16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_23_reg(r1: i32, r: i32) {
    write_reg16(r, and16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_23_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        and32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_23_reg(r1: i32, r: i32) {
    write_reg32(r, and32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_24(imm8: i32) { write_reg8(AL, and8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_25(imm16: i32) { write_reg16(AX, and16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_25(imm32: i32) { write_reg32(EAX, and32(read_reg32(EAX), imm32)); }

pub unsafe fn instr_26() { segment_prefix_op(ES); }

#[no_mangle]
pub unsafe fn instr_27() { bcd_daa(); }

pub unsafe fn instr_28_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| sub8(x, read_reg8(r))) }
pub unsafe fn instr_28_reg(r1: i32, r: i32) { write_reg8(r1, sub8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_29_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| sub16(x, read_reg16(r)))
}
pub unsafe fn instr16_29_reg(r1: i32, r: i32) {
    write_reg16(r1, sub16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_29_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| sub32(x, read_reg32(r)))
}
pub unsafe fn instr32_29_reg(r1: i32, r: i32) {
    write_reg32(r1, sub32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_2A_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        sub8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_2A_reg(r1: i32, r: i32) { write_reg8(r, sub8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_2B_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        sub16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_2B_reg(r1: i32, r: i32) {
    write_reg16(r, sub16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_2B_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        sub32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_2B_reg(r1: i32, r: i32) {
    write_reg32(r, sub32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_2C(imm8: i32) { write_reg8(AL, sub8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_2D(imm16: i32) { write_reg16(AX, sub16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_2D(imm32: i32) { write_reg32(EAX, sub32(read_reg32(EAX), imm32)); }

pub unsafe fn instr_2E() { segment_prefix_op(CS); }

#[no_mangle]
pub unsafe fn instr_2F() { bcd_das(); }

pub unsafe fn instr_30_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xor8(x, read_reg8(r))) }
pub unsafe fn instr_30_reg(r1: i32, r: i32) { write_reg8(r1, xor8(read_reg8(r1), read_reg8(r))); }
pub unsafe fn instr16_31_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| xor16(x, read_reg16(r)))
}
pub unsafe fn instr16_31_reg(r1: i32, r: i32) {
    write_reg16(r1, xor16(read_reg16(r1), read_reg16(r)));
}
pub unsafe fn instr32_31_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| xor32(x, read_reg32(r)))
}
pub unsafe fn instr32_31_reg(r1: i32, r: i32) {
    write_reg32(r1, xor32(read_reg32(r1), read_reg32(r)));
}
pub unsafe fn instr_32_mem(addr: i32, r: i32) {
    write_reg8(
        r,
        xor8(read_reg8(r), return_on_pagefault!(safe_read8(addr))),
    );
}
pub unsafe fn instr_32_reg(r1: i32, r: i32) { write_reg8(r, xor8(read_reg8(r), read_reg8(r1))); }
pub unsafe fn instr16_33_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        xor16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_33_reg(r1: i32, r: i32) {
    write_reg16(r, xor16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_33_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        xor32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_33_reg(r1: i32, r: i32) {
    write_reg32(r, xor32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr_34(imm8: i32) { write_reg8(AL, xor8(read_reg8(AL), imm8)); }
pub unsafe fn instr16_35(imm16: i32) { write_reg16(AX, xor16(read_reg16(AX), imm16)); }
pub unsafe fn instr32_35(imm32: i32) { write_reg32(EAX, xor32(read_reg32(EAX), imm32)); }

pub unsafe fn instr_36() { segment_prefix_op(SS); }

#[no_mangle]
pub unsafe fn instr_37() { bcd_aaa(); }

pub unsafe fn instr_38_mem(addr: i32, r: i32) {
    cmp8(return_on_pagefault!(safe_read8(addr)), read_reg8(r));
}
pub unsafe fn instr_38_reg(r1: i32, r: i32) { cmp8(read_reg8(r1), read_reg8(r)); }
pub unsafe fn instr16_39_mem(addr: i32, r: i32) {
    cmp16(return_on_pagefault!(safe_read16(addr)), read_reg16(r));
}
pub unsafe fn instr16_39_reg(r1: i32, r: i32) { cmp16(read_reg16(r1), read_reg16(r)); }
pub unsafe fn instr32_39_mem(addr: i32, r: i32) {
    cmp32(return_on_pagefault!(safe_read32s(addr)), read_reg32(r));
}
pub unsafe fn instr32_39_reg(r1: i32, r: i32) { cmp32(read_reg32(r1), read_reg32(r)); }
pub unsafe fn instr_3A_mem(addr: i32, r: i32) {
    cmp8(read_reg8(r), return_on_pagefault!(safe_read8(addr)));
}
pub unsafe fn instr_3A_reg(r1: i32, r: i32) { cmp8(read_reg8(r), read_reg8(r1)); }
pub unsafe fn instr16_3B_mem(addr: i32, r: i32) {
    cmp16(read_reg16(r), return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr16_3B_reg(r1: i32, r: i32) { cmp16(read_reg16(r), read_reg16(r1)); }
pub unsafe fn instr32_3B_mem(addr: i32, r: i32) {
    cmp32(read_reg32(r), return_on_pagefault!(safe_read32s(addr)));
}
pub unsafe fn instr32_3B_reg(r1: i32, r: i32) { cmp32(read_reg32(r), read_reg32(r1)); }
pub unsafe fn instr_3C(imm8: i32) { cmp8(read_reg8(AL), imm8); }
pub unsafe fn instr16_3D(imm16: i32) { cmp16(read_reg16(AX), imm16); }
pub unsafe fn instr32_3D(imm32: i32) { cmp32(read_reg32(EAX), imm32); }

pub unsafe fn instr_3E() { segment_prefix_op(DS); }

#[no_mangle]
pub unsafe fn instr_3F() { bcd_aas(); }

pub unsafe fn instr16_40() { write_reg16(AX, inc16(read_reg16(AX))); }
pub unsafe fn instr32_40() { write_reg32(EAX, inc32(read_reg32(EAX))); }
pub unsafe fn instr16_41() { write_reg16(CX, inc16(read_reg16(CX))); }
pub unsafe fn instr32_41() { write_reg32(ECX, inc32(read_reg32(ECX))); }
pub unsafe fn instr16_42() { write_reg16(DX, inc16(read_reg16(DX))); }
pub unsafe fn instr32_42() { write_reg32(EDX, inc32(read_reg32(EDX))); }
pub unsafe fn instr16_43() { write_reg16(BX, inc16(read_reg16(BX))); }
pub unsafe fn instr32_43() { write_reg32(EBX, inc32(read_reg32(EBX))); }
pub unsafe fn instr16_44() { write_reg16(SP, inc16(read_reg16(SP))); }
pub unsafe fn instr32_44() { write_reg32(ESP, inc32(read_reg32(ESP))); }
pub unsafe fn instr16_45() { write_reg16(BP, inc16(read_reg16(BP))); }
pub unsafe fn instr32_45() { write_reg32(EBP, inc32(read_reg32(EBP))); }
pub unsafe fn instr16_46() { write_reg16(SI, inc16(read_reg16(SI))); }
pub unsafe fn instr32_46() { write_reg32(ESI, inc32(read_reg32(ESI))); }
pub unsafe fn instr16_47() { write_reg16(DI, inc16(read_reg16(DI))); }
pub unsafe fn instr32_47() { write_reg32(EDI, inc32(read_reg32(EDI))); }
pub unsafe fn instr16_48() { write_reg16(AX, dec16(read_reg16(AX))); }
pub unsafe fn instr32_48() { write_reg32(EAX, dec32(read_reg32(EAX))); }
pub unsafe fn instr16_49() { write_reg16(CX, dec16(read_reg16(CX))); }
pub unsafe fn instr32_49() { write_reg32(ECX, dec32(read_reg32(ECX))); }
pub unsafe fn instr16_4A() { write_reg16(DX, dec16(read_reg16(DX))); }
pub unsafe fn instr32_4A() { write_reg32(EDX, dec32(read_reg32(EDX))); }
pub unsafe fn instr16_4B() { write_reg16(BX, dec16(read_reg16(BX))); }
pub unsafe fn instr32_4B() { write_reg32(EBX, dec32(read_reg32(EBX))); }
pub unsafe fn instr16_4C() { write_reg16(SP, dec16(read_reg16(SP))); }
pub unsafe fn instr32_4C() { write_reg32(ESP, dec32(read_reg32(ESP))); }
pub unsafe fn instr16_4D() { write_reg16(BP, dec16(read_reg16(BP))); }
pub unsafe fn instr32_4D() { write_reg32(EBP, dec32(read_reg32(EBP))); }
pub unsafe fn instr16_4E() { write_reg16(SI, dec16(read_reg16(SI))); }
pub unsafe fn instr32_4E() { write_reg32(ESI, dec32(read_reg32(ESI))); }
pub unsafe fn instr16_4F() { write_reg16(DI, dec16(read_reg16(DI))); }
pub unsafe fn instr32_4F() { write_reg32(EDI, dec32(read_reg32(EDI))); }

pub unsafe fn push16_reg(r: i32) {
    return_on_pagefault!(push16(read_reg16(r)));
}
pub unsafe fn push32_reg(r: i32) {
    return_on_pagefault!(push32(read_reg32(r)));
}

pub unsafe fn instr16_50() { push16_reg(AX) }
pub unsafe fn instr32_50() { push32_reg(EAX) }
pub unsafe fn instr16_51() { push16_reg(CX) }
pub unsafe fn instr32_51() { push32_reg(ECX) }
pub unsafe fn instr16_52() { push16_reg(DX) }
pub unsafe fn instr32_52() { push32_reg(EDX) }
pub unsafe fn instr16_53() { push16_reg(BX) }
pub unsafe fn instr32_53() { push32_reg(EBX) }
pub unsafe fn instr16_54() { push16_reg(SP) }
pub unsafe fn instr32_54() { push32_reg(ESP) }
pub unsafe fn instr16_55() { push16_reg(BP) }
pub unsafe fn instr32_55() { push32_reg(EBP) }
pub unsafe fn instr16_56() { push16_reg(SI) }
pub unsafe fn instr32_56() { push32_reg(ESI) }
pub unsafe fn instr16_57() { push16_reg(DI) }
pub unsafe fn instr32_57() { push32_reg(EDI) }
pub unsafe fn instr16_58() { write_reg16(AX, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_58() { write_reg32(EAX, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_59() { write_reg16(CX, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_59() { write_reg32(ECX, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_5A() { write_reg16(DX, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_5A() { write_reg32(EDX, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_5B() { write_reg16(BX, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_5B() { write_reg32(EBX, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_5C() {
    write_reg16(SP, return_on_pagefault!(safe_read16(get_stack_pointer(0))));
}
pub unsafe fn instr32_5C() {
    write_reg32(
        ESP,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))),
    );
}
pub unsafe fn instr16_5D() { write_reg16(BP, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_5D() { write_reg32(EBP, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_5E() { write_reg16(SI, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_5E() { write_reg32(ESI, return_on_pagefault!(pop32s())); }
pub unsafe fn instr16_5F() { write_reg16(DI, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_5F() { write_reg32(EDI, return_on_pagefault!(pop32s())); }

#[no_mangle]
pub unsafe fn instr16_60() { pusha16(); }
#[no_mangle]
pub unsafe fn instr32_60() { pusha32(); }
#[no_mangle]
pub unsafe fn instr16_61() { popa16(); }
#[no_mangle]
pub unsafe fn instr32_61() { popa32(); }

#[no_mangle]
pub unsafe fn instr_62_reg(_r2: i32, _r: i32) {
    // bound
    dbg_log!("Unimplemented BOUND instruction");
    dbg_assert!(false);
}
#[no_mangle]
pub unsafe fn instr_62_mem(_addr: i32, _r: i32) {
    dbg_log!("Unimplemented BOUND instruction");
    dbg_assert!(false);
}

pub unsafe fn arpl(seg: i32, r16: i32) -> i32 {
    *flags_changed &= !FLAG_ZERO;

    if (seg & 3) < (r16 & 3) {
        *flags |= FLAG_ZERO;
        seg & !3 | r16 & 3
    }
    else {
        *flags &= !FLAG_ZERO;
        seg
    }
}

#[no_mangle]
pub unsafe fn instr_63_mem(addr: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("arpl #ud");
        trigger_ud();
        return;
    }
    safe_read_write16(addr, &|x| arpl(x, read_reg16(r)))
}
#[no_mangle]
pub unsafe fn instr_63_reg(r1: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("arpl #ud");
        trigger_ud();
        return;
    }
    write_reg16(r1, arpl(read_reg16(r1), read_reg16(r)));
}

pub unsafe fn instr_64() { segment_prefix_op(FS); }
pub unsafe fn instr_65() { segment_prefix_op(GS); }

pub unsafe fn instr_66() {
    // Operand-size override prefix
    *prefixes = crate::decode_rules::apply_prefix(*prefixes, 0x66).unwrap();
    run_prefix_instruction();
    *prefixes = 0;
}
pub unsafe fn instr_67() {
    // Address-size override prefix
    *prefixes = crate::decode_rules::apply_prefix(*prefixes, 0x67).unwrap();
    run_prefix_instruction();
    *prefixes = 0;
}

pub unsafe fn instr16_68(imm16: i32) {
    return_on_pagefault!(push16(imm16));
}
pub unsafe fn instr32_68(imm32: i32) {
    return_on_pagefault!(push32(imm32));
}
pub unsafe fn instr16_69_mem(addr: i32, r: i32, imm: i32) {
    write_reg16(r, imul_reg16(return_on_pagefault!(safe_read16(addr)), imm));
}
pub unsafe fn instr16_69_reg(r1: i32, r: i32, imm: i32) {
    write_reg16(r, imul_reg16(read_reg16(r1), imm));
}
pub unsafe fn instr32_69_mem(addr: i32, r: i32, imm: i32) {
    write_reg32(r, imul_reg32(return_on_pagefault!(safe_read32s(addr)), imm));
}
pub unsafe fn instr32_69_reg(r1: i32, r: i32, imm: i32) {
    write_reg32(r, imul_reg32(read_reg32(r1), imm));
}

pub unsafe fn instr16_6A(imm8: i32) {
    return_on_pagefault!(push16(imm8 & 0xFFFF));
}
pub unsafe fn instr32_6A(imm8: i32) {
    return_on_pagefault!(push32(imm8));
}
pub unsafe fn instr16_6B_mem(addr: i32, r: i32, imm: i32) {
    write_reg16(r, imul_reg16(return_on_pagefault!(safe_read16(addr)), imm));
}
pub unsafe fn instr16_6B_reg(r1: i32, r: i32, imm: i32) {
    write_reg16(r, imul_reg16(read_reg16(r1), imm));
}
pub unsafe fn instr32_6B_mem(addr: i32, r: i32, imm: i32) {
    write_reg32(r, imul_reg32(return_on_pagefault!(safe_read32s(addr)), imm));
}
pub unsafe fn instr32_6B_reg(r1: i32, r: i32, imm: i32) {
    write_reg32(r, imul_reg32(read_reg32(r1), imm));
}

pub unsafe fn instr_6C() { insb_no_rep(is_asize_32()); }
pub unsafe fn instr_F26C() { insb_rep(is_asize_32()); }
pub unsafe fn instr_F36C() { insb_rep(is_asize_32()); }
pub unsafe fn instr16_6D() { insw_no_rep(is_asize_32()); }
pub unsafe fn instr32_6D() { insd_no_rep(is_asize_32()); }
pub unsafe fn instr16_F26D() { insw_rep(is_asize_32()); }
pub unsafe fn instr16_F36D() { insw_rep(is_asize_32()); }
pub unsafe fn instr32_F26D() { insd_rep(is_asize_32()); }
pub unsafe fn instr32_F36D() { insd_rep(is_asize_32()); }

pub unsafe fn instr_6E() { outsb_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F26E() { outsb_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F36E() { outsb_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr16_6F() { outsw_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_6F() { outsd_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F26F() { outsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F36F() { outsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F26F() { outsd_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F36F() { outsd_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr16_70(imm8: i32) { jmpcc16(test_o(), imm8); }
pub unsafe fn instr16_71(imm8: i32) { jmpcc16(!test_o(), imm8); }
pub unsafe fn instr16_72(imm8: i32) { jmpcc16(test_b(), imm8); }
pub unsafe fn instr16_73(imm8: i32) { jmpcc16(!test_b(), imm8); }
pub unsafe fn instr16_74(imm8: i32) { jmpcc16(test_z(), imm8); }
pub unsafe fn instr16_75(imm8: i32) { jmpcc16(!test_z(), imm8); }
pub unsafe fn instr16_76(imm8: i32) { jmpcc16(test_be(), imm8); }
pub unsafe fn instr16_77(imm8: i32) { jmpcc16(!test_be(), imm8); }
pub unsafe fn instr16_78(imm8: i32) { jmpcc16(test_s(), imm8); }
pub unsafe fn instr16_79(imm8: i32) { jmpcc16(!test_s(), imm8); }
pub unsafe fn instr16_7A(imm8: i32) { jmpcc16(test_p(), imm8); }
pub unsafe fn instr16_7B(imm8: i32) { jmpcc16(!test_p(), imm8); }
pub unsafe fn instr16_7C(imm8: i32) { jmpcc16(test_l(), imm8); }
pub unsafe fn instr16_7D(imm8: i32) { jmpcc16(!test_l(), imm8); }
pub unsafe fn instr16_7E(imm8: i32) { jmpcc16(test_le(), imm8); }
pub unsafe fn instr16_7F(imm8: i32) { jmpcc16(!test_le(), imm8); }
pub unsafe fn instr32_70(imm8: i32) { jmpcc32(test_o(), imm8); }
pub unsafe fn instr32_71(imm8: i32) { jmpcc32(!test_o(), imm8); }
pub unsafe fn instr32_72(imm8: i32) { jmpcc32(test_b(), imm8); }
pub unsafe fn instr32_73(imm8: i32) { jmpcc32(!test_b(), imm8); }
pub unsafe fn instr32_74(imm8: i32) { jmpcc32(test_z(), imm8); }
pub unsafe fn instr32_75(imm8: i32) { jmpcc32(!test_z(), imm8); }
pub unsafe fn instr32_76(imm8: i32) { jmpcc32(test_be(), imm8); }
pub unsafe fn instr32_77(imm8: i32) { jmpcc32(!test_be(), imm8); }
pub unsafe fn instr32_78(imm8: i32) { jmpcc32(test_s(), imm8); }
pub unsafe fn instr32_79(imm8: i32) { jmpcc32(!test_s(), imm8); }
pub unsafe fn instr32_7A(imm8: i32) { jmpcc32(test_p(), imm8); }
pub unsafe fn instr32_7B(imm8: i32) { jmpcc32(!test_p(), imm8); }
pub unsafe fn instr32_7C(imm8: i32) { jmpcc32(test_l(), imm8); }
pub unsafe fn instr32_7D(imm8: i32) { jmpcc32(!test_l(), imm8); }
pub unsafe fn instr32_7E(imm8: i32) { jmpcc32(test_le(), imm8); }
pub unsafe fn instr32_7F(imm8: i32) { jmpcc32(!test_le(), imm8); }

pub unsafe fn instr_80_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| add8(x, imm)) }
pub unsafe fn instr_80_0_reg(r1: i32, imm: i32) { write_reg8(r1, add8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| or8(x, imm)) }
pub unsafe fn instr_80_1_reg(r1: i32, imm: i32) { write_reg8(r1, or8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| adc8(x, imm)) }
pub unsafe fn instr_80_2_reg(r1: i32, imm: i32) { write_reg8(r1, adc8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sbb8(x, imm)) }
pub unsafe fn instr_80_3_reg(r1: i32, imm: i32) { write_reg8(r1, sbb8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| and8(x, imm)) }
pub unsafe fn instr_80_4_reg(r1: i32, imm: i32) { write_reg8(r1, and8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sub8(x, imm)) }
pub unsafe fn instr_80_5_reg(r1: i32, imm: i32) { write_reg8(r1, sub8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| xor8(x, imm)) }
pub unsafe fn instr_80_6_reg(r1: i32, imm: i32) { write_reg8(r1, xor8(read_reg8(r1), imm)); }
pub unsafe fn instr_80_7_reg(r: i32, imm: i32) { cmp8(read_reg8(r), imm); }
pub unsafe fn instr_80_7_mem(addr: i32, imm: i32) {
    cmp8(return_on_pagefault!(safe_read8(addr)), imm);
}
pub unsafe fn instr16_81_0_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| add16(x, imm)) }
pub unsafe fn instr16_81_0_reg(r1: i32, imm: i32) { write_reg16(r1, add16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_1_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| or16(x, imm)) }
pub unsafe fn instr16_81_1_reg(r1: i32, imm: i32) { write_reg16(r1, or16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_2_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| adc16(x, imm)) }
pub unsafe fn instr16_81_2_reg(r1: i32, imm: i32) { write_reg16(r1, adc16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_3_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| sbb16(x, imm)) }
pub unsafe fn instr16_81_3_reg(r1: i32, imm: i32) { write_reg16(r1, sbb16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_4_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| and16(x, imm)) }
pub unsafe fn instr16_81_4_reg(r1: i32, imm: i32) { write_reg16(r1, and16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_5_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| sub16(x, imm)) }
pub unsafe fn instr16_81_5_reg(r1: i32, imm: i32) { write_reg16(r1, sub16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_6_mem(addr: i32, imm: i32) { safe_read_write16(addr, &|x| xor16(x, imm)) }
pub unsafe fn instr16_81_6_reg(r1: i32, imm: i32) { write_reg16(r1, xor16(read_reg16(r1), imm)); }
pub unsafe fn instr16_81_7_reg(r: i32, imm: i32) { cmp16(read_reg16(r), imm); }
pub unsafe fn instr16_81_7_mem(addr: i32, imm: i32) {
    cmp16(return_on_pagefault!(safe_read16(addr)), imm);
}
pub unsafe fn instr32_81_0_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| add32(x, imm)) }
pub unsafe fn instr32_81_0_reg(r1: i32, imm: i32) { write_reg32(r1, add32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_1_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| or32(x, imm)) }
pub unsafe fn instr32_81_1_reg(r1: i32, imm: i32) { write_reg32(r1, or32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_2_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| adc32(x, imm)) }
pub unsafe fn instr32_81_2_reg(r1: i32, imm: i32) { write_reg32(r1, adc32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_3_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sbb32(x, imm)) }
pub unsafe fn instr32_81_3_reg(r1: i32, imm: i32) { write_reg32(r1, sbb32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_4_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| and32(x, imm)) }
pub unsafe fn instr32_81_4_reg(r1: i32, imm: i32) { write_reg32(r1, and32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_5_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sub32(x, imm)) }
pub unsafe fn instr32_81_5_reg(r1: i32, imm: i32) { write_reg32(r1, sub32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_6_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| xor32(x, imm)) }
pub unsafe fn instr32_81_6_reg(r1: i32, imm: i32) { write_reg32(r1, xor32(read_reg32(r1), imm)); }
pub unsafe fn instr32_81_7_reg(r: i32, imm: i32) { cmp32(read_reg32(r), imm); }
pub unsafe fn instr32_81_7_mem(addr: i32, imm: i32) {
    cmp32(return_on_pagefault!(safe_read32s(addr)), imm);
}
pub unsafe fn instr_82_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| add8(x, imm)) }
pub unsafe fn instr_82_0_reg(r1: i32, imm: i32) { write_reg8(r1, add8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| or8(x, imm)) }
pub unsafe fn instr_82_1_reg(r1: i32, imm: i32) { write_reg8(r1, or8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| adc8(x, imm)) }
pub unsafe fn instr_82_2_reg(r1: i32, imm: i32) { write_reg8(r1, adc8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sbb8(x, imm)) }
pub unsafe fn instr_82_3_reg(r1: i32, imm: i32) { write_reg8(r1, sbb8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| and8(x, imm)) }
pub unsafe fn instr_82_4_reg(r1: i32, imm: i32) { write_reg8(r1, and8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sub8(x, imm)) }
pub unsafe fn instr_82_5_reg(r1: i32, imm: i32) { write_reg8(r1, sub8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| xor8(x, imm)) }
pub unsafe fn instr_82_6_reg(r1: i32, imm: i32) { write_reg8(r1, xor8(read_reg8(r1), imm)); }
pub unsafe fn instr_82_7_reg(r: i32, imm: i32) { cmp8(read_reg8(r), imm); }
pub unsafe fn instr_82_7_mem(addr: i32, imm: i32) {
    cmp8(return_on_pagefault!(safe_read8(addr)), imm);
}
pub unsafe fn instr16_83_0_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| add16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_0_reg(r1: i32, imm: i32) {
    write_reg16(r1, add16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_1_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| or16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_1_reg(r1: i32, imm: i32) {
    write_reg16(r1, or16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_2_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| adc16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_2_reg(r1: i32, imm: i32) {
    write_reg16(r1, adc16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_3_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| sbb16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_3_reg(r1: i32, imm: i32) {
    write_reg16(r1, sbb16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_4_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| and16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_4_reg(r1: i32, imm: i32) {
    write_reg16(r1, and16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_5_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| sub16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_5_reg(r1: i32, imm: i32) {
    write_reg16(r1, sub16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_6_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| xor16(x, imm & 0xFFFF))
}
pub unsafe fn instr16_83_6_reg(r1: i32, imm: i32) {
    write_reg16(r1, xor16(read_reg16(r1), imm & 0xFFFF));
}
pub unsafe fn instr16_83_7_reg(r: i32, imm: i32) { cmp16(read_reg16(r), imm & 0xFFFF); }
pub unsafe fn instr16_83_7_mem(addr: i32, imm: i32) {
    cmp16(return_on_pagefault!(safe_read16(addr)), imm & 0xFFFF);
}

pub unsafe fn instr32_83_0_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| add32(x, imm)) }
pub unsafe fn instr32_83_0_reg(r1: i32, imm: i32) { write_reg32(r1, add32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_1_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| or32(x, imm)) }
pub unsafe fn instr32_83_1_reg(r1: i32, imm: i32) { write_reg32(r1, or32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_2_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| adc32(x, imm)) }
pub unsafe fn instr32_83_2_reg(r1: i32, imm: i32) { write_reg32(r1, adc32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_3_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sbb32(x, imm)) }
pub unsafe fn instr32_83_3_reg(r1: i32, imm: i32) { write_reg32(r1, sbb32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_4_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| and32(x, imm)) }
pub unsafe fn instr32_83_4_reg(r1: i32, imm: i32) { write_reg32(r1, and32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_5_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| sub32(x, imm)) }
pub unsafe fn instr32_83_5_reg(r1: i32, imm: i32) { write_reg32(r1, sub32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_6_mem(addr: i32, imm: i32) { safe_read_write32(addr, &|x| xor32(x, imm)) }
pub unsafe fn instr32_83_6_reg(r1: i32, imm: i32) { write_reg32(r1, xor32(read_reg32(r1), imm)); }
pub unsafe fn instr32_83_7_reg(r: i32, imm: i32) { cmp32(read_reg32(r), imm); }
pub unsafe fn instr32_83_7_mem(addr: i32, imm: i32) {
    cmp32(return_on_pagefault!(safe_read32s(addr)), imm);
}

pub unsafe fn instr_84_mem(addr: i32, r: i32) {
    test8(return_on_pagefault!(safe_read8(addr)), read_reg8(r));
}
pub unsafe fn instr_84_reg(r1: i32, r: i32) { test8(read_reg8(r1), read_reg8(r)); }
pub unsafe fn instr16_85_mem(addr: i32, r: i32) {
    test16(return_on_pagefault!(safe_read16(addr)), read_reg16(r));
}
pub unsafe fn instr16_85_reg(r1: i32, r: i32) { test16(read_reg16(r1), read_reg16(r)); }
pub unsafe fn instr32_85_mem(addr: i32, r: i32) {
    test32(return_on_pagefault!(safe_read32s(addr)), read_reg32(r));
}
pub unsafe fn instr32_85_reg(r1: i32, r: i32) { test32(read_reg32(r1), read_reg32(r)); }
pub unsafe fn instr_86_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xchg8(x, r)) }
pub unsafe fn instr_86_reg(r1: i32, r: i32) { write_reg8(r1, xchg8(read_reg8(r1), r)); }
pub unsafe fn instr16_87_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| xchg16(x, r)) }
pub unsafe fn instr16_87_reg(r1: i32, r: i32) { write_reg16(r1, xchg16(read_reg16(r1), r)); }
pub unsafe fn instr32_87_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| xchg32(x, r)) }
pub unsafe fn instr32_87_reg(r1: i32, r: i32) { write_reg32(r1, xchg32(read_reg32(r1), r)); }
pub unsafe fn instr_88_reg(r2: i32, r: i32) { write_reg8(r2, read_reg8(r)); }
pub unsafe fn instr_88_mem(addr: i32, r: i32) {
    return_on_pagefault!(safe_write8(addr, read_reg8(r)));
}
pub unsafe fn instr16_89_reg(r2: i32, r: i32) { write_reg16(r2, read_reg16(r)); }
pub unsafe fn instr16_89_mem(addr: i32, r: i32) {
    return_on_pagefault!(safe_write16(addr, read_reg16(r)));
}
pub unsafe fn instr32_89_reg(r2: i32, r: i32) { write_reg32(r2, read_reg32(r)); }
pub unsafe fn instr32_89_mem(addr: i32, r: i32) {
    return_on_pagefault!(safe_write32(addr, read_reg32(r)));
}
pub unsafe fn instr_8A_mem(addr: i32, r: i32) {
    write_reg8(r, return_on_pagefault!(safe_read8(addr)));
}
pub unsafe fn instr_8A_reg(r1: i32, r: i32) { write_reg8(r, read_reg8(r1)); }
pub unsafe fn instr16_8B_mem(addr: i32, r: i32) {
    write_reg16(r, return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr16_8B_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1)); }
pub unsafe fn instr32_8B_mem(addr: i32, r: i32) {
    write_reg32(r, return_on_pagefault!(safe_read32s(addr)));
}
pub unsafe fn instr32_8B_reg(r1: i32, r: i32) { write_reg32(r, read_reg32(r1)); }

pub unsafe fn instr_8C_check_sreg(seg: i32) -> bool {
    if seg >= 6 {
        dbg_log!("mov sreg #ud");
        trigger_ud();
        return false;
    }
    else {
        return true;
    };
}
pub unsafe fn instr16_8C_reg(r: i32, seg: i32) {
    if instr_8C_check_sreg(seg) {
        write_reg16(r, *sreg.offset(seg as isize) as i32);
    };
}
pub unsafe fn instr16_8C_mem(addr: i32, seg: i32) {
    if instr_8C_check_sreg(seg) {
        return_on_pagefault!(safe_write16(addr, *sreg.offset(seg as isize) as i32));
    };
}
pub unsafe fn instr32_8C_reg(r: i32, seg: i32) {
    if instr_8C_check_sreg(seg) {
        write_reg32(r, *sreg.offset(seg as isize) as i32);
    };
}
pub unsafe fn instr32_8C_mem(addr: i32, seg: i32) {
    if instr_8C_check_sreg(seg) {
        return_on_pagefault!(safe_write16(addr, *sreg.offset(seg as isize) as i32));
    };
}

pub unsafe fn instr16_8D_reg(_r: i32, _r2: i32) {
    dbg_log!("lea #ud");
    trigger_ud();
}
pub unsafe fn instr16_8D_mem(modrm_byte: i32, r: i32) {
    // lea
    *prefixes |= prefix::SEG_PREFIX_ZERO;
    if let Ok(addr) = modrm_resolve(modrm_byte) {
        write_reg16(r, addr);
    }
    *prefixes = 0;
}
pub unsafe fn instr32_8D_reg(_r: i32, _r2: i32) {
    dbg_log!("lea #ud");
    trigger_ud();
}
pub unsafe fn instr32_8D_mem(modrm_byte: i32, r: i32) {
    // lea
    // override prefix, so modrm_resolve does not return the segment part
    *prefixes |= prefix::SEG_PREFIX_ZERO;
    if let Ok(addr) = modrm_resolve(modrm_byte) {
        write_reg32(r, addr);
    }
    *prefixes = 0;
}

#[no_mangle]
pub unsafe fn instr_8E_mem(addr: i32, r: i32) {
    if r == ES || r == SS || r == DS || r == FS || r == GS {
        if !switch_seg(r, return_on_pagefault!(safe_read16(addr))) {
            return;
        }
    }
    else {
        dbg_log!("mov sreg #ud");
        trigger_ud();
    }
}
#[no_mangle]
pub unsafe fn instr_8E_reg(r1: i32, r: i32) {
    if r == ES || r == SS || r == DS || r == FS || r == GS {
        switch_seg(r, read_reg16(r1));
    }
    else {
        dbg_log!("mov sreg #ud");
        trigger_ud();
    }
}

pub unsafe fn instr16_8F_0_mem(modrm_byte: i32) {
    // pop
    // Update esp *before* resolving the address
    adjust_stack_reg(2);
    match modrm_resolve(modrm_byte) {
        Err(()) => {
            // a pagefault happened, reset esp
            adjust_stack_reg(-2);
        },
        Ok(addr) => {
            adjust_stack_reg(-2);
            let stack_value = return_on_pagefault!(safe_read16(get_stack_pointer(0)));
            return_on_pagefault!(safe_write16(addr, stack_value));
            adjust_stack_reg(2);
        },
    }
}
pub unsafe fn instr16_8F_0_reg(r: i32) { write_reg16(r, return_on_pagefault!(pop16())); }
pub unsafe fn instr32_8F_0_mem(modrm_byte: i32) {
    // Update esp *before* resolving the address
    adjust_stack_reg(4);
    match modrm_resolve(modrm_byte) {
        Err(()) => {
            // a pagefault happened, reset esp
            adjust_stack_reg(-4);
        },
        Ok(addr) => {
            adjust_stack_reg(-4);
            let stack_value = return_on_pagefault!(safe_read32s(get_stack_pointer(0)));
            return_on_pagefault!(safe_write32(addr, stack_value));
            adjust_stack_reg(4);
        },
    }
}
pub unsafe fn instr32_8F_0_reg(r: i32) { write_reg32(r, return_on_pagefault!(pop32s())); }

pub unsafe fn instr_90() {
    // PAUSE (F3 90): a spin-wait hint; with several cores, let another one run
    if *prefixes & crate::prefix::PREFIX_F3 != 0 && crate::cpu::apic::core_count() > 1 {
        // (and leave the interpreter's same-page loop now, not after its iteration limit)
        crate::cpu::cpu::yield_to_other_cores();
    }
}
pub unsafe fn instr16_91() { xchg16r(CX); }
pub unsafe fn instr32_91() { xchg32r(ECX); }
pub unsafe fn instr16_92() { xchg16r(DX); }
pub unsafe fn instr32_92() { xchg32r(EDX); }
pub unsafe fn instr16_93() { xchg16r(BX); }
pub unsafe fn instr32_93() { xchg32r(EBX); }
pub unsafe fn instr16_94() { xchg16r(SP); }
pub unsafe fn instr32_94() { xchg32r(ESP); }
pub unsafe fn instr16_95() { xchg16r(BP); }
pub unsafe fn instr32_95() { xchg32r(EBP); }
pub unsafe fn instr16_96() { xchg16r(SI); }
pub unsafe fn instr32_96() { xchg32r(ESI); }
pub unsafe fn instr16_97() { xchg16r(DI); }
pub unsafe fn instr32_97() { xchg32r(EDI); }

pub unsafe fn instr16_98() { write_reg16(AX, read_reg8(AL) << 24 >> 24); }
pub unsafe fn instr32_98() { write_reg32(EAX, read_reg16(AX) as i16 as i32); }
pub unsafe fn instr16_99() { write_reg16(DX, read_reg16(AX) as i16 as i32 >> 15); }
pub unsafe fn instr32_99() { write_reg32(EDX, read_reg32(EAX) >> 31); }

#[no_mangle]
pub unsafe fn instr16_9A(new_ip: i32, new_cs: i32) {
    // callf
    far_jump(new_ip, new_cs, true, false);
}
#[no_mangle]
pub unsafe fn instr32_9A(new_ip: i32, new_cs: i32) {
    if !*protected_mode || vm86_mode() {
        if 0 != new_ip as u32 & 0xFFFF0000 {
            dbg_assert!(false);
        }
    }
    far_jump(new_ip, new_cs, true, true);
}
#[no_mangle]
pub unsafe fn instr_9B() {
    // fwait: check for pending fpu exceptions
    if *cr & (CR0_MP | CR0_TS) == CR0_MP | CR0_TS {
        // Note: Different from task_switch_test
        // Triggers when TS and MP bits are set (EM bit is ignored)
        trigger_nm();
    }
    else {
        fwait();
    };
}
unsafe fn instr_pushf_popf_check() -> bool { 0 != *flags & FLAG_VM && getiopl() < 3 }
pub unsafe fn instr16_9C() {
    // pushf
    if instr_pushf_popf_check() {
        dbg_assert!(*protected_mode);
        dbg_log!("pushf #gp");
        trigger_gp(0);
    }
    else {
        return_on_pagefault!(push16(get_eflags() & 0xFFFF));
    };
}
pub unsafe fn instr32_9C() {
    // pushf
    if instr_pushf_popf_check() {
        // trap to virtual 8086 monitor
        dbg_assert!(*protected_mode);
        dbg_log!("pushf #gp");
        trigger_gp(0);
    }
    else {
        // vm and rf flag are cleared in image stored on the stack
        return_on_pagefault!(push32(get_eflags() & 0xFCFFFF));
    };
}

pub unsafe fn instr16_9D() {
    // popf
    if instr_pushf_popf_check() {
        dbg_log!("popf #gp");
        trigger_gp(0);
        return;
    }
    let old_eflags = *flags;
    update_eflags(*flags & !0xFFFF | return_on_pagefault!(pop16()));
    if old_eflags & FLAG_INTERRUPT == 0 && *flags & FLAG_INTERRUPT != 0 {
        handle_irqs();
    }
}
pub unsafe fn instr32_9D() {
    // popf
    if instr_pushf_popf_check() {
        dbg_log!("popf #gp");
        trigger_gp(0);
        return;
    }
    let old_eflags = *flags;
    update_eflags(return_on_pagefault!(pop32s()));
    if old_eflags & FLAG_INTERRUPT == 0 && *flags & FLAG_INTERRUPT != 0 {
        handle_irqs();
    }
}

pub unsafe fn instr_9E() {
    // sahf
    *flags = *flags & !255 | read_reg8(AH);
    *flags = *flags & FLAGS_MASK | FLAGS_DEFAULT;
    *flags_changed &= !255;
}
pub unsafe fn instr_9F() {
    // lahf
    write_reg8(AH, get_eflags());
}

pub unsafe fn instr_A0(moffs: i32) {
    // mov
    let data = return_on_pagefault!(safe_read8(return_on_pagefault!(get_seg_prefix_ds(moffs))));
    write_reg8(AL, data);
}
pub unsafe fn instr16_A1(moffs: i32) {
    // mov
    let data = return_on_pagefault!(safe_read16(return_on_pagefault!(get_seg_prefix_ds(moffs))));
    write_reg16(AX, data);
}
pub unsafe fn instr32_A1(moffs: i32) {
    let data = return_on_pagefault!(safe_read32s(return_on_pagefault!(get_seg_prefix_ds(moffs))));
    write_reg32(EAX, data);
}
pub unsafe fn instr_A2(moffs: i32) {
    // mov
    return_on_pagefault!(safe_write8(
        return_on_pagefault!(get_seg_prefix_ds(moffs)),
        read_reg8(AL)
    ));
}
pub unsafe fn instr16_A3(moffs: i32) {
    // mov
    return_on_pagefault!(safe_write16(
        return_on_pagefault!(get_seg_prefix_ds(moffs)),
        read_reg16(AX)
    ));
}
pub unsafe fn instr32_A3(moffs: i32) {
    return_on_pagefault!(safe_write32(
        return_on_pagefault!(get_seg_prefix_ds(moffs)),
        read_reg32(EAX)
    ));
}

pub unsafe fn instr_A4() { movsb_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F2A4() { movsb_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F3A4() { movsb_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr16_A5() { movsw_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_A5() { movsd_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F2A5() { movsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F3A5() { movsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F2A5() { movsd_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F3A5() { movsd_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr_A6() { cmpsb_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F2A6() { cmpsb_repnz(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F3A6() { cmpsb_repz(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_A7() { cmpsw_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_A7() { cmpsd_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F2A7() { cmpsw_repnz(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F3A7() { cmpsw_repz(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F2A7() { cmpsd_repnz(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F3A7() { cmpsd_repz(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr_A8(imm8: i32) { test8(read_reg8(AL), imm8); }
pub unsafe fn instr16_A9(imm16: i32) { test16(read_reg16(AX), imm16); }
pub unsafe fn instr32_A9(imm32: i32) { test32(read_reg32(EAX), imm32); }

pub unsafe fn instr_AA() { stosb_no_rep(is_asize_32()); }
pub unsafe fn instr_F2AA() { stosb_rep(is_asize_32()); }
pub unsafe fn instr_F3AA() { stosb_rep(is_asize_32()); }

pub unsafe fn instr16_AB() { stosw_no_rep(is_asize_32()); }
pub unsafe fn instr32_AB() { stosd_no_rep(is_asize_32()); }
pub unsafe fn instr16_F2AB() { stosw_rep(is_asize_32()); }
pub unsafe fn instr16_F3AB() { stosw_rep(is_asize_32()); }
pub unsafe fn instr32_F2AB() { stosd_rep(is_asize_32()); }
pub unsafe fn instr32_F3AB() { stosd_rep(is_asize_32()); }

pub unsafe fn instr_AC() { lodsb_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F2AC() { lodsb_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr_F3AC() { lodsb_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr16_AD() { lodsw_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_AD() { lodsd_no_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F2AD() { lodsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr16_F3AD() { lodsw_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F2AD() { lodsd_rep(is_asize_32(), segment_prefix(DS)); }
pub unsafe fn instr32_F3AD() { lodsd_rep(is_asize_32(), segment_prefix(DS)); }

pub unsafe fn instr_AE() { scasb_no_rep(is_asize_32()); }
pub unsafe fn instr_F2AE() { scasb_repnz(is_asize_32()); }
pub unsafe fn instr_F3AE() { scasb_repz(is_asize_32()); }

pub unsafe fn instr16_AF() { scasw_no_rep(is_asize_32()); }
pub unsafe fn instr32_AF() { scasd_no_rep(is_asize_32()); }
pub unsafe fn instr16_F2AF() { scasw_repnz(is_asize_32()); }
pub unsafe fn instr16_F3AF() { scasw_repz(is_asize_32()); }
pub unsafe fn instr32_F2AF() { scasd_repnz(is_asize_32()); }
pub unsafe fn instr32_F3AF() { scasd_repz(is_asize_32()); }

pub unsafe fn instr_B0(imm8: i32) { write_reg8(AL, imm8); }
pub unsafe fn instr_B1(imm8: i32) { write_reg8(CL, imm8); }
pub unsafe fn instr_B2(imm8: i32) { write_reg8(DL, imm8); }
pub unsafe fn instr_B3(imm8: i32) { write_reg8(BL, imm8); }
pub unsafe fn instr_B4(imm8: i32) { write_reg8(AH, imm8); }
pub unsafe fn instr_B5(imm8: i32) { write_reg8(CH, imm8); }
pub unsafe fn instr_B6(imm8: i32) { write_reg8(DH, imm8); }
pub unsafe fn instr_B7(imm8: i32) { write_reg8(BH, imm8); }
pub unsafe fn instr16_B8(imm: i32) { write_reg16(AX, imm); }
pub unsafe fn instr32_B8(imm: i32) { write_reg32(EAX, imm); }
pub unsafe fn instr16_B9(imm: i32) { write_reg16(CX, imm); }
pub unsafe fn instr32_B9(imm: i32) { write_reg32(ECX, imm); }
pub unsafe fn instr16_BA(imm: i32) { write_reg16(DX, imm); }
pub unsafe fn instr32_BA(imm: i32) { write_reg32(EDX, imm); }
pub unsafe fn instr16_BB(imm: i32) { write_reg16(BX, imm); }
pub unsafe fn instr32_BB(imm: i32) { write_reg32(EBX, imm); }
pub unsafe fn instr16_BC(imm: i32) { write_reg16(SP, imm); }
pub unsafe fn instr32_BC(imm: i32) { write_reg32(ESP, imm); }
pub unsafe fn instr16_BD(imm: i32) { write_reg16(BP, imm); }
pub unsafe fn instr32_BD(imm: i32) { write_reg32(EBP, imm); }
pub unsafe fn instr16_BE(imm: i32) { write_reg16(SI, imm); }
pub unsafe fn instr32_BE(imm: i32) { write_reg32(ESI, imm); }
pub unsafe fn instr16_BF(imm: i32) { write_reg16(DI, imm); }
pub unsafe fn instr32_BF(imm: i32) { write_reg32(EDI, imm); }

pub unsafe fn instr_C0_0_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rol8(x, imm & 31)) }
pub unsafe fn instr_C0_0_reg(r1: i32, imm: i32) { write_reg8(r1, rol8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_1_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| ror8(x, imm & 31)) }
pub unsafe fn instr_C0_1_reg(r1: i32, imm: i32) { write_reg8(r1, ror8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_2_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rcl8(x, imm & 31)) }
pub unsafe fn instr_C0_2_reg(r1: i32, imm: i32) { write_reg8(r1, rcl8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_3_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| rcr8(x, imm & 31)) }
pub unsafe fn instr_C0_3_reg(r1: i32, imm: i32) { write_reg8(r1, rcr8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_4_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shl8(x, imm & 31)) }
pub unsafe fn instr_C0_4_reg(r1: i32, imm: i32) { write_reg8(r1, shl8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_5_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shr8(x, imm & 31)) }
pub unsafe fn instr_C0_5_reg(r1: i32, imm: i32) { write_reg8(r1, shr8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_6_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| shl8(x, imm & 31)) }
pub unsafe fn instr_C0_6_reg(r1: i32, imm: i32) { write_reg8(r1, shl8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr_C0_7_mem(addr: i32, imm: i32) { safe_read_write8(addr, &|x| sar8(x, imm & 31)) }
pub unsafe fn instr_C0_7_reg(r1: i32, imm: i32) { write_reg8(r1, sar8(read_reg8(r1), imm & 31)); }
pub unsafe fn instr16_C1_0_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| rol16(x, imm & 31))
}
pub unsafe fn instr16_C1_0_reg(r1: i32, imm: i32) {
    write_reg16(r1, rol16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_1_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| ror16(x, imm & 31))
}
pub unsafe fn instr16_C1_1_reg(r1: i32, imm: i32) {
    write_reg16(r1, ror16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_2_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| rcl16(x, imm & 31))
}
pub unsafe fn instr16_C1_2_reg(r1: i32, imm: i32) {
    write_reg16(r1, rcl16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_3_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| rcr16(x, imm & 31))
}
pub unsafe fn instr16_C1_3_reg(r1: i32, imm: i32) {
    write_reg16(r1, rcr16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_4_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| shl16(x, imm & 31))
}
pub unsafe fn instr16_C1_4_reg(r1: i32, imm: i32) {
    write_reg16(r1, shl16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_5_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| shr16(x, imm & 31))
}
pub unsafe fn instr16_C1_5_reg(r1: i32, imm: i32) {
    write_reg16(r1, shr16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_6_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| shl16(x, imm & 31))
}
pub unsafe fn instr16_C1_6_reg(r1: i32, imm: i32) {
    write_reg16(r1, shl16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr16_C1_7_mem(addr: i32, imm: i32) {
    safe_read_write16(addr, &|x| sar16(x, imm & 31))
}
pub unsafe fn instr16_C1_7_reg(r1: i32, imm: i32) {
    write_reg16(r1, sar16(read_reg16(r1), imm & 31));
}
pub unsafe fn instr32_C1_0_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| rol32(x, imm & 31))
}
pub unsafe fn instr32_C1_0_reg(r1: i32, imm: i32) {
    write_reg32(r1, rol32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_1_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| ror32(x, imm & 31))
}
pub unsafe fn instr32_C1_1_reg(r1: i32, imm: i32) {
    write_reg32(r1, ror32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_2_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| rcl32(x, imm & 31))
}
pub unsafe fn instr32_C1_2_reg(r1: i32, imm: i32) {
    write_reg32(r1, rcl32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_3_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| rcr32(x, imm & 31))
}
pub unsafe fn instr32_C1_3_reg(r1: i32, imm: i32) {
    write_reg32(r1, rcr32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_4_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| shl32(x, imm & 31))
}
pub unsafe fn instr32_C1_4_reg(r1: i32, imm: i32) {
    write_reg32(r1, shl32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_5_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| shr32(x, imm & 31))
}
pub unsafe fn instr32_C1_5_reg(r1: i32, imm: i32) {
    write_reg32(r1, shr32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_6_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| shl32(x, imm & 31))
}
pub unsafe fn instr32_C1_6_reg(r1: i32, imm: i32) {
    write_reg32(r1, shl32(read_reg32(r1), imm & 31));
}
pub unsafe fn instr32_C1_7_mem(addr: i32, imm: i32) {
    safe_read_write32(addr, &|x| sar32(x, imm & 31))
}
pub unsafe fn instr32_C1_7_reg(r1: i32, imm: i32) {
    write_reg32(r1, sar32(read_reg32(r1), imm & 31));
}

pub unsafe fn instr16_C2(imm16: i32) {
    // retn
    let cs = get_seg_cs();
    *instruction_pointer = cs + return_on_pagefault!(pop16());
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
    adjust_stack_reg(imm16);
}
pub unsafe fn instr32_C2(imm16: i32) {
    // retn
    let cs = get_seg_cs();
    let ip = return_on_pagefault!(pop32s());
    dbg_assert!(*is_32 || ip < 0x10000);
    *instruction_pointer = cs + ip;
    adjust_stack_reg(imm16);
}
pub unsafe fn instr16_C3() {
    // retn
    let cs = get_seg_cs();
    *instruction_pointer = cs + return_on_pagefault!(pop16());
}
pub unsafe fn instr32_C3() {
    // retn
    let cs = get_seg_cs();
    let ip = return_on_pagefault!(pop32s());
    dbg_assert!(*is_32 || ip < 0x10000);
    *instruction_pointer = cs + ip;
}

// The register forms of LES and LDS are VEX prefixes in protected mode
// (crate::cpu::vex), #UD in real and virtual-8086 mode
#[no_mangle]
pub unsafe fn instr16_C4_reg(rm: i32, reg: i32) {
    crate::cpu::vex::run(0xC4, (0xC0 | reg << 3 | rm) as u8);
}
#[no_mangle]
pub unsafe fn instr16_C4_mem(addr: i32, r: i32) { lss16(addr, r, ES); }
#[no_mangle]
pub unsafe fn instr32_C4_reg(rm: i32, reg: i32) {
    crate::cpu::vex::run(0xC4, (0xC0 | reg << 3 | rm) as u8);
}
#[no_mangle]
pub unsafe fn instr32_C4_mem(addr: i32, r: i32) { lss32(addr, r, ES); }
#[no_mangle]
pub unsafe fn instr16_C5_reg(rm: i32, reg: i32) {
    crate::cpu::vex::run(0xC5, (0xC0 | reg << 3 | rm) as u8);
}
#[no_mangle]
pub unsafe fn instr16_C5_mem(addr: i32, r: i32) { lss16(addr, r, DS); }
#[no_mangle]
pub unsafe fn instr32_C5_reg(rm: i32, reg: i32) {
    crate::cpu::vex::run(0xC5, (0xC0 | reg << 3 | rm) as u8);
}
#[no_mangle]
pub unsafe fn instr32_C5_mem(addr: i32, r: i32) { lss32(addr, r, DS); }

pub unsafe fn instr_C6_0_reg(r: i32, imm: i32) { write_reg8(r, imm); }
pub unsafe fn instr_C6_0_mem(addr: i32, imm: i32) {
    return_on_pagefault!(safe_write8(addr, imm));
}
pub unsafe fn instr16_C7_0_reg(r: i32, imm: i32) { write_reg16(r, imm); }
pub unsafe fn instr16_C7_0_mem(addr: i32, imm: i32) {
    return_on_pagefault!(safe_write16(addr, imm));
}
pub unsafe fn instr32_C7_0_reg(r: i32, imm: i32) { write_reg32(r, imm); }
pub unsafe fn instr32_C7_0_mem(addr: i32, imm: i32) {
    return_on_pagefault!(safe_write32(addr, imm));
}

#[no_mangle]
pub unsafe fn instr16_C8(size: i32, nesting: i32) { enter16(size, nesting); }
#[no_mangle]
pub unsafe fn instr32_C8(size: i32, nesting: i32) { enter32(size, nesting); }

pub unsafe fn instr16_C9() {
    // leave
    let old_vbp = if *stack_size_32 { read_reg32(EBP) } else { read_reg16(BP) };
    let new_bp = return_on_pagefault!(safe_read16(get_seg_ss() + old_vbp));
    set_stack_reg(old_vbp + 2);
    write_reg16(BP, new_bp);
}
pub unsafe fn instr32_C9() {
    let old_vbp = if *stack_size_32 { read_reg32(EBP) } else { read_reg16(BP) };
    let new_ebp = return_on_pagefault!(safe_read32s(get_seg_ss() + old_vbp));
    set_stack_reg(old_vbp + 4);
    write_reg32(EBP, new_ebp);
}
#[no_mangle]
pub unsafe fn instr16_CA(imm16: i32) {
    // retf
    let ip = return_on_pagefault!(safe_read16(get_stack_pointer(0)));
    let cs = return_on_pagefault!(safe_read16(get_stack_pointer(2)));
    far_return(ip, cs, imm16, false);
}
#[no_mangle]
pub unsafe fn instr32_CA(imm16: i32) {
    // retf
    let ip = return_on_pagefault!(safe_read32s(get_stack_pointer(0)));
    let cs = return_on_pagefault!(safe_read32s(get_stack_pointer(4))) & 0xFFFF;
    far_return(ip, cs, imm16, true);
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
#[no_mangle]
pub unsafe fn instr16_CB() {
    // retf
    let ip = return_on_pagefault!(safe_read16(get_stack_pointer(0)));
    let cs = return_on_pagefault!(safe_read16(get_stack_pointer(2)));
    far_return(ip, cs, 0, false);
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
#[no_mangle]
pub unsafe fn instr32_CB() {
    // retf
    let ip = return_on_pagefault!(safe_read32s(get_stack_pointer(0)));
    let cs = return_on_pagefault!(safe_read32s(get_stack_pointer(4))) & 0xFFFF;
    far_return(ip, cs, 0, true);
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
#[no_mangle]
pub unsafe fn instr_CC() {
    // INT3
    // TODO: inhibit iopl checks
    dbg_log!("INT3");
    call_interrupt_vector(3, true, None);
}
#[no_mangle]
pub unsafe fn instr_CD(imm8: i32) {
    // INT
    call_interrupt_vector(imm8, true, None);
}
#[no_mangle]
pub unsafe fn instr_CE() {
    // INTO
    dbg_log!("INTO");
    if getof() {
        // TODO: inhibit iopl checks
        call_interrupt_vector(CPU_EXCEPTION_OF, true, None);
    };
}
#[no_mangle]
pub unsafe fn instr16_CF() {
    // iret
    iret16();
}
#[no_mangle]
pub unsafe fn instr32_CF() { iret32(); }

pub unsafe fn instr_D0_0_mem(addr: i32) { safe_read_write8(addr, &|x| rol8(x, 1)) }
pub unsafe fn instr_D0_0_reg(r1: i32) { write_reg8(r1, rol8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_1_mem(addr: i32) { safe_read_write8(addr, &|x| ror8(x, 1)) }
pub unsafe fn instr_D0_1_reg(r1: i32) { write_reg8(r1, ror8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_2_mem(addr: i32) { safe_read_write8(addr, &|x| rcl8(x, 1)) }
pub unsafe fn instr_D0_2_reg(r1: i32) { write_reg8(r1, rcl8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_3_mem(addr: i32) { safe_read_write8(addr, &|x| rcr8(x, 1)) }
pub unsafe fn instr_D0_3_reg(r1: i32) { write_reg8(r1, rcr8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_4_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, 1)) }
pub unsafe fn instr_D0_4_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_5_mem(addr: i32) { safe_read_write8(addr, &|x| shr8(x, 1)) }
pub unsafe fn instr_D0_5_reg(r1: i32) { write_reg8(r1, shr8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_6_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, 1)) }
pub unsafe fn instr_D0_6_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), 1)); }
pub unsafe fn instr_D0_7_mem(addr: i32) { safe_read_write8(addr, &|x| sar8(x, 1)) }
pub unsafe fn instr_D0_7_reg(r1: i32) { write_reg8(r1, sar8(read_reg8(r1), 1)); }
pub unsafe fn instr16_D1_0_mem(addr: i32) { safe_read_write16(addr, &|x| rol16(x, 1)) }
pub unsafe fn instr16_D1_0_reg(r1: i32) { write_reg16(r1, rol16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_1_mem(addr: i32) { safe_read_write16(addr, &|x| ror16(x, 1)) }
pub unsafe fn instr16_D1_1_reg(r1: i32) { write_reg16(r1, ror16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_2_mem(addr: i32) { safe_read_write16(addr, &|x| rcl16(x, 1)) }
pub unsafe fn instr16_D1_2_reg(r1: i32) { write_reg16(r1, rcl16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_3_mem(addr: i32) { safe_read_write16(addr, &|x| rcr16(x, 1)) }
pub unsafe fn instr16_D1_3_reg(r1: i32) { write_reg16(r1, rcr16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_4_mem(addr: i32) { safe_read_write16(addr, &|x| shl16(x, 1)) }
pub unsafe fn instr16_D1_4_reg(r1: i32) { write_reg16(r1, shl16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_5_mem(addr: i32) { safe_read_write16(addr, &|x| shr16(x, 1)) }
pub unsafe fn instr16_D1_5_reg(r1: i32) { write_reg16(r1, shr16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_6_mem(addr: i32) { safe_read_write16(addr, &|x| shl16(x, 1)) }
pub unsafe fn instr16_D1_6_reg(r1: i32) { write_reg16(r1, shl16(read_reg16(r1), 1)); }
pub unsafe fn instr16_D1_7_mem(addr: i32) { safe_read_write16(addr, &|x| sar16(x, 1)) }
pub unsafe fn instr16_D1_7_reg(r1: i32) { write_reg16(r1, sar16(read_reg16(r1), 1)); }
pub unsafe fn instr32_D1_0_mem(addr: i32) { safe_read_write32(addr, &|x| rol32(x, 1)) }
pub unsafe fn instr32_D1_0_reg(r1: i32) { write_reg32(r1, rol32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_1_mem(addr: i32) { safe_read_write32(addr, &|x| ror32(x, 1)) }
pub unsafe fn instr32_D1_1_reg(r1: i32) { write_reg32(r1, ror32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_2_mem(addr: i32) { safe_read_write32(addr, &|x| rcl32(x, 1)) }
pub unsafe fn instr32_D1_2_reg(r1: i32) { write_reg32(r1, rcl32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_3_mem(addr: i32) { safe_read_write32(addr, &|x| rcr32(x, 1)) }
pub unsafe fn instr32_D1_3_reg(r1: i32) { write_reg32(r1, rcr32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_4_mem(addr: i32) { safe_read_write32(addr, &|x| shl32(x, 1)) }
pub unsafe fn instr32_D1_4_reg(r1: i32) { write_reg32(r1, shl32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_5_mem(addr: i32) { safe_read_write32(addr, &|x| shr32(x, 1)) }
pub unsafe fn instr32_D1_5_reg(r1: i32) { write_reg32(r1, shr32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_6_mem(addr: i32) { safe_read_write32(addr, &|x| shl32(x, 1)) }
pub unsafe fn instr32_D1_6_reg(r1: i32) { write_reg32(r1, shl32(read_reg32(r1), 1)); }
pub unsafe fn instr32_D1_7_mem(addr: i32) { safe_read_write32(addr, &|x| sar32(x, 1)) }
pub unsafe fn instr32_D1_7_reg(r1: i32) { write_reg32(r1, sar32(read_reg32(r1), 1)); }
pub unsafe fn instr_D2_0_mem(addr: i32) { safe_read_write8(addr, &|x| rol8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_0_reg(r1: i32) { write_reg8(r1, rol8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_1_mem(addr: i32) { safe_read_write8(addr, &|x| ror8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_1_reg(r1: i32) { write_reg8(r1, ror8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_2_mem(addr: i32) { safe_read_write8(addr, &|x| rcl8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_2_reg(r1: i32) { write_reg8(r1, rcl8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_3_mem(addr: i32) { safe_read_write8(addr, &|x| rcr8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_3_reg(r1: i32) { write_reg8(r1, rcr8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_4_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_4_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_5_mem(addr: i32) { safe_read_write8(addr, &|x| shr8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_5_reg(r1: i32) { write_reg8(r1, shr8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_6_mem(addr: i32) { safe_read_write8(addr, &|x| shl8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_6_reg(r1: i32) { write_reg8(r1, shl8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr_D2_7_mem(addr: i32) { safe_read_write8(addr, &|x| sar8(x, read_reg8(CL) & 31)) }
pub unsafe fn instr_D2_7_reg(r1: i32) { write_reg8(r1, sar8(read_reg8(r1), read_reg8(CL) & 31)); }
pub unsafe fn instr16_D3_0_mem(addr: i32) {
    safe_read_write16(addr, &|x| rol16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_0_reg(r1: i32) {
    write_reg16(r1, rol16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_1_mem(addr: i32) {
    safe_read_write16(addr, &|x| ror16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_1_reg(r1: i32) {
    write_reg16(r1, ror16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_2_mem(addr: i32) {
    safe_read_write16(addr, &|x| rcl16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_2_reg(r1: i32) {
    write_reg16(r1, rcl16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_3_mem(addr: i32) {
    safe_read_write16(addr, &|x| rcr16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_3_reg(r1: i32) {
    write_reg16(r1, rcr16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_4_mem(addr: i32) {
    safe_read_write16(addr, &|x| shl16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_4_reg(r1: i32) {
    write_reg16(r1, shl16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_5_mem(addr: i32) {
    safe_read_write16(addr, &|x| shr16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_5_reg(r1: i32) {
    write_reg16(r1, shr16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_6_mem(addr: i32) {
    safe_read_write16(addr, &|x| shl16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_6_reg(r1: i32) {
    write_reg16(r1, shl16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr16_D3_7_mem(addr: i32) {
    safe_read_write16(addr, &|x| sar16(x, read_reg8(CL) & 31))
}
pub unsafe fn instr16_D3_7_reg(r1: i32) {
    write_reg16(r1, sar16(read_reg16(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_0_mem(addr: i32) {
    safe_read_write32(addr, &|x| rol32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_0_reg(r1: i32) {
    write_reg32(r1, rol32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_1_mem(addr: i32) {
    safe_read_write32(addr, &|x| ror32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_1_reg(r1: i32) {
    write_reg32(r1, ror32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_2_mem(addr: i32) {
    safe_read_write32(addr, &|x| rcl32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_2_reg(r1: i32) {
    write_reg32(r1, rcl32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_3_mem(addr: i32) {
    safe_read_write32(addr, &|x| rcr32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_3_reg(r1: i32) {
    write_reg32(r1, rcr32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_4_mem(addr: i32) {
    safe_read_write32(addr, &|x| shl32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_4_reg(r1: i32) {
    write_reg32(r1, shl32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_5_mem(addr: i32) {
    safe_read_write32(addr, &|x| shr32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_5_reg(r1: i32) {
    write_reg32(r1, shr32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_6_mem(addr: i32) {
    safe_read_write32(addr, &|x| shl32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_6_reg(r1: i32) {
    write_reg32(r1, shl32(read_reg32(r1), read_reg8(CL) & 31));
}
pub unsafe fn instr32_D3_7_mem(addr: i32) {
    safe_read_write32(addr, &|x| sar32(x, read_reg8(CL) & 31))
}
pub unsafe fn instr32_D3_7_reg(r1: i32) {
    write_reg32(r1, sar32(read_reg32(r1), read_reg8(CL) & 31));
}

#[no_mangle]
pub unsafe fn instr_D4(arg: i32) { bcd_aam(arg); }
#[no_mangle]
pub unsafe fn instr_D5(arg: i32) { bcd_aad(arg); }
#[no_mangle]
pub unsafe fn instr_D6() {
    // salc
    write_reg8(AL, -(getcf() as i32));
}
pub unsafe fn instr_D7() {
    // xlat
    if is_asize_32() {
        write_reg8(
            AL,
            return_on_pagefault!(safe_read8(
                return_on_pagefault!(get_seg_prefix(DS)) + read_reg32(EBX) + read_reg8(AL),
            )),
        )
    }
    else {
        write_reg8(
            AL,
            return_on_pagefault!(safe_read8(
                return_on_pagefault!(get_seg_prefix(DS))
                    + (read_reg16(BX) + read_reg8(AL) & 0xFFFF),
            )),
        )
    };
}

pub unsafe fn instr_D8_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_0_reg(r: i32) { fpu_fadd(0, fpu_get_sti(r)); }
pub unsafe fn instr_D8_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_1_reg(r: i32) { fpu_fmul(0, fpu_get_sti(r)); }
pub unsafe fn instr_D8_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_2_reg(r: i32) { fpu_fcom(fpu_get_sti(r)); }
pub unsafe fn instr_D8_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_3_reg(r: i32) { fpu_fcomp(fpu_get_sti(r)); }
pub unsafe fn instr_D8_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_4_reg(r: i32) { fpu_fsub(0, fpu_get_sti(r)); }
pub unsafe fn instr_D8_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_5_reg(r: i32) { fpu_fsubr(0, fpu_get_sti(r)); }
pub unsafe fn instr_D8_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_6_reg(r: i32) { fpu_fdiv(0, fpu_get_sti(r)); }
pub unsafe fn instr_D8_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_m32(addr))); }
pub unsafe fn instr_D8_7_reg(r: i32) { fpu_fdivr(0, fpu_get_sti(r)); }

pub unsafe fn instr16_D9_0_mem(addr: i32) { fpu_fldm32(addr); }
pub unsafe fn instr16_D9_0_reg(r: i32) { fpu_push(fpu_get_sti(r)); }
pub unsafe fn instr16_D9_1_mem(_addr: i32) {
    dbg_log!("d9/1");
    trigger_ud();
}
pub unsafe fn instr16_D9_1_reg(r: i32) { fpu_fxch(r); }
pub unsafe fn instr16_D9_2_mem(addr: i32) { fpu_fstm32(addr); }
pub unsafe fn instr16_D9_2_reg(r: i32) {
    if r != 0 {
        trigger_ud();
    };
}
pub unsafe fn instr16_D9_3_mem(addr: i32) { fpu_fstm32p(addr); }
pub unsafe fn instr16_D9_3_reg(r: i32) { fpu_fstp(r) }
#[no_mangle]
pub unsafe fn instr16_D9_4_mem(addr: i32) {
    return_on_pagefault!(readable_or_pagefault(addr, 14));
    fpu_fldenv16(addr);
}
pub unsafe fn instr32_D9_4_mem(addr: i32) {
    return_on_pagefault!(readable_or_pagefault(addr, 28));
    fpu_fldenv32(addr);
}
#[no_mangle]
pub unsafe fn instr16_D9_4_reg(r: i32) {
    match r {
        0 => fpu_fchs(),
        1 => fpu_fabs(),
        4 => fpu_ftst(),
        5 => fpu_fxam(),
        _ => {
            dbg_log!("{:x}", r);
            trigger_ud();
        },
    };
}
#[no_mangle]
pub unsafe fn instr16_D9_5_mem(addr: i32) { fpu_fldcw(addr); }
#[no_mangle]
pub unsafe fn instr16_D9_5_reg(r: i32) {
    // fld1/fldl2t/fldl2e/fldpi/fldlg2/fldln2/fldz
    match r {
        0 => fpu_push(F80::ONE),
        1 => fpu_push(F80::LN_10 / F80::LN_2),
        2 => fpu_push(F80::LOG2_E),
        3 => fpu_push(F80::PI),
        4 => fpu_push(F80::LN_2 / F80::LN_10),
        5 => fpu_push(F80::LN_2),
        6 => fpu_push(F80::ZERO),
        7 => {
            dbg_log!("d9/5/7");
            trigger_ud();
        },
        _ => {},
    };
}
pub unsafe fn instr16_D9_6_mem(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 14));
    fpu_fstenv16(addr);
}
pub unsafe fn instr32_D9_6_mem(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 28));
    fpu_fstenv32(addr);
}
#[no_mangle]
pub unsafe fn instr16_D9_6_reg(r: i32) {
    match r {
        0 => fpu_f2xm1(),
        1 => fpu_fyl2x(),
        2 => fpu_fptan(),
        3 => fpu_fpatan(),
        4 => fpu_fxtract(),
        5 => fpu_fprem(true), // fprem1
        6 => fpu_fdecstp(),
        7 => fpu_fincstp(),
        _ => {
            dbg_assert!(false);
        },
    };
}
pub unsafe fn instr16_D9_7_mem(addr: i32) { fpu_fstcw(addr); }
#[no_mangle]
pub unsafe fn instr16_D9_7_reg(r: i32) {
    match r {
        0 => fpu_fprem(false),
        1 => fpu_fyl2xp1(),
        2 => fpu_fsqrt(),
        3 => fpu_fsincos(),
        4 => fpu_frndint(),
        5 => fpu_fscale(),
        6 => fpu_fsin(),
        7 => fpu_fcos(),
        _ => {
            dbg_assert!(false);
        },
    };
}

pub unsafe fn instr32_D9_0_reg(r: i32) { instr16_D9_0_reg(r) }
pub unsafe fn instr32_D9_1_reg(r: i32) { instr16_D9_1_reg(r) }
pub unsafe fn instr32_D9_2_reg(r: i32) { instr16_D9_2_reg(r) }
pub unsafe fn instr32_D9_3_reg(r: i32) { instr16_D9_3_reg(r) }
pub unsafe fn instr32_D9_4_reg(r: i32) { instr16_D9_4_reg(r) }
pub unsafe fn instr32_D9_5_reg(r: i32) { instr16_D9_5_reg(r) }
pub unsafe fn instr32_D9_6_reg(r: i32) { instr16_D9_6_reg(r) }
pub unsafe fn instr32_D9_7_reg(r: i32) { instr16_D9_7_reg(r) }

pub unsafe fn instr32_D9_0_mem(r: i32) { instr16_D9_0_mem(r) }
pub unsafe fn instr32_D9_1_mem(r: i32) { instr16_D9_1_mem(r) }
pub unsafe fn instr32_D9_2_mem(r: i32) { instr16_D9_2_mem(r) }
pub unsafe fn instr32_D9_3_mem(r: i32) { instr16_D9_3_mem(r) }
pub unsafe fn instr32_D9_5_mem(r: i32) { instr16_D9_5_mem(r) }
pub unsafe fn instr32_D9_7_mem(r: i32) { instr16_D9_7_mem(r) }

pub unsafe fn instr_DA_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_i32(addr))); }
pub unsafe fn instr_DA_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_i32(addr))); }
#[no_mangle]
pub unsafe fn instr_DA_0_reg(r: i32) { fpu_fcmovcc(test_b(), r); }
#[no_mangle]
pub unsafe fn instr_DA_1_reg(r: i32) { fpu_fcmovcc(test_z(), r); }
#[no_mangle]
pub unsafe fn instr_DA_2_reg(r: i32) { fpu_fcmovcc(test_be(), r); }
#[no_mangle]
pub unsafe fn instr_DA_3_reg(r: i32) { fpu_fcmovcc(test_p(), r); }
pub unsafe fn instr_DA_4_reg(_r: i32) { trigger_ud(); }
pub unsafe fn instr_DA_5_reg(r: i32) {
    if r == 1 {
        fpu_fucompp();
    }
    else {
        trigger_ud();
    };
}
pub unsafe fn instr_DA_6_reg(_r: i32) { trigger_ud(); }
pub unsafe fn instr_DA_7_reg(_r: i32) { trigger_ud(); }

pub unsafe fn instr_DB_0_mem(addr: i32) { fpu_fildm32(addr); }
pub unsafe fn instr_DB_1_mem(addr: i32) { fpu_fisttpm32(addr); }
pub unsafe fn instr_DB_2_mem(addr: i32) { fpu_fistm32(addr); }
pub unsafe fn instr_DB_3_mem(addr: i32) { fpu_fistm32p(addr); }
#[no_mangle]
pub unsafe fn instr_DB_4_mem(_addr: i32) { trigger_ud(); }
pub unsafe fn instr_DB_5_mem(addr: i32) {
    return_on_pagefault!(readable_or_pagefault(addr, 10));
    fpu_fldm80(addr);
}
pub unsafe fn instr_DB_6_mem(_addr: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_DB_7_mem(addr: i32) { fpu_fst80p(addr); }
#[no_mangle]
pub unsafe fn instr_DB_0_reg(r: i32) { fpu_fcmovcc(!test_b(), r); }
#[no_mangle]
pub unsafe fn instr_DB_1_reg(r: i32) { fpu_fcmovcc(!test_z(), r); }
#[no_mangle]
pub unsafe fn instr_DB_2_reg(r: i32) { fpu_fcmovcc(!test_be(), r); }
#[no_mangle]
pub unsafe fn instr_DB_3_reg(r: i32) { fpu_fcmovcc(!test_p(), r); }
#[no_mangle]
pub unsafe fn instr_DB_4_reg(r: i32) {
    if r == 3 {
        fpu_finit();
    }
    else if r == 4 || r == 1 || r == 0 {
        // fsetpm, fdisi, fneni; treated as nop
    }
    else if r == 2 {
        fpu_fclex();
    }
    else {
        trigger_ud();
    };
}
pub unsafe fn instr_DB_5_reg(r: i32) { fpu_fucomi(r); }
pub unsafe fn instr_DB_6_reg(r: i32) { fpu_fcomi(r); }
#[no_mangle]
pub unsafe fn instr_DB_7_reg(_r: i32) { trigger_ud(); }

pub unsafe fn instr_DC_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_m64(addr))); }
pub unsafe fn instr_DC_0_reg(r: i32) { fpu_fadd(r, fpu_get_sti(r)); }
pub unsafe fn instr_DC_1_reg(r: i32) { fpu_fmul(r, fpu_get_sti(r)); }
pub unsafe fn instr_DC_2_reg(r: i32) { fpu_fcom(fpu_get_sti(r)); }
pub unsafe fn instr_DC_3_reg(r: i32) { fpu_fcomp(fpu_get_sti(r)); }
pub unsafe fn instr_DC_4_reg(r: i32) { fpu_fsub(r, fpu_get_sti(r)); }
pub unsafe fn instr_DC_5_reg(r: i32) { fpu_fsubr(r, fpu_get_sti(r)); }
pub unsafe fn instr_DC_6_reg(r: i32) { fpu_fdiv(r, fpu_get_sti(r)); }
pub unsafe fn instr_DC_7_reg(r: i32) { fpu_fdivr(r, fpu_get_sti(r)); }

pub unsafe fn instr16_DD_0_mem(addr: i32) { fpu_fldm64(addr); }
pub unsafe fn instr16_DD_1_mem(addr: i32) { fpu_fisttpm64(addr); }
pub unsafe fn instr16_DD_2_mem(addr: i32) { fpu_fstm64(addr); }
pub unsafe fn instr16_DD_3_mem(addr: i32) { fpu_fstm64p(addr); }
#[no_mangle]
pub unsafe fn instr16_DD_4_mem(addr: i32) { fpu_frstor16(addr); }
#[no_mangle]
pub unsafe fn instr32_DD_4_mem(addr: i32) { fpu_frstor32(addr); }
pub unsafe fn instr16_DD_5_mem(_addr: i32) {
    dbg_log!("dd/5");
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr16_DD_6_mem(addr: i32) { fpu_fsave16(addr); }
#[no_mangle]
pub unsafe fn instr32_DD_6_mem(addr: i32) { fpu_fsave32(addr); }
#[no_mangle]
pub unsafe fn instr16_DD_7_mem(addr: i32) { fpu_fnstsw_mem(addr); }
pub unsafe fn instr16_DD_0_reg(r: i32) { fpu_ffree(r); }
pub unsafe fn instr16_DD_1_reg(r: i32) { fpu_fxch(r) }
pub unsafe fn instr16_DD_2_reg(r: i32) { fpu_fst(r); }
pub unsafe fn instr16_DD_3_reg(r: i32) { fpu_fstp(r); }
#[no_mangle]
pub unsafe fn instr16_DD_4_reg(r: i32) { fpu_fucom(r); }
pub unsafe fn instr16_DD_5_reg(r: i32) { fpu_fucomp(r); }
#[no_mangle]
pub unsafe fn instr16_DD_6_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr16_DD_7_reg(_r: i32) { trigger_ud(); }

pub unsafe fn instr32_DD_0_reg(r: i32) { instr16_DD_0_reg(r) }
#[no_mangle]
pub unsafe fn instr32_DD_1_reg(r: i32) { instr16_DD_1_reg(r) }
pub unsafe fn instr32_DD_2_reg(r: i32) { instr16_DD_2_reg(r) }
pub unsafe fn instr32_DD_3_reg(r: i32) { instr16_DD_3_reg(r) }
#[no_mangle]
pub unsafe fn instr32_DD_4_reg(r: i32) { instr16_DD_4_reg(r) }
pub unsafe fn instr32_DD_5_reg(r: i32) { instr16_DD_5_reg(r) }
#[no_mangle]
pub unsafe fn instr32_DD_6_reg(r: i32) { instr16_DD_6_reg(r) }
#[no_mangle]
pub unsafe fn instr32_DD_7_reg(r: i32) { instr16_DD_7_reg(r) }

pub unsafe fn instr32_DD_0_mem(r: i32) { instr16_DD_0_mem(r) }
#[no_mangle]
pub unsafe fn instr32_DD_1_mem(r: i32) { instr16_DD_1_mem(r) }
pub unsafe fn instr32_DD_2_mem(r: i32) { instr16_DD_2_mem(r) }
pub unsafe fn instr32_DD_3_mem(r: i32) { instr16_DD_3_mem(r) }
pub unsafe fn instr32_DD_5_mem(r: i32) { instr16_DD_5_mem(r) }
#[no_mangle]
pub unsafe fn instr32_DD_7_mem(r: i32) { instr16_DD_7_mem(r) }

#[no_mangle]
pub unsafe fn instr_DE_0_mem(addr: i32) { fpu_fadd(0, return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_1_mem(addr: i32) { fpu_fmul(0, return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_2_mem(addr: i32) { fpu_fcom(return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_3_mem(addr: i32) { fpu_fcomp(return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_4_mem(addr: i32) { fpu_fsub(0, return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_5_mem(addr: i32) { fpu_fsubr(0, return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_6_mem(addr: i32) { fpu_fdiv(0, return_on_pagefault!(fpu_load_i16(addr))); }
#[no_mangle]
pub unsafe fn instr_DE_7_mem(addr: i32) { fpu_fdivr(0, return_on_pagefault!(fpu_load_i16(addr))); }

#[no_mangle]
pub unsafe fn instr_DE_0_reg(r: i32) {
    fpu_fadd(r, fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_1_reg(r: i32) {
    fpu_fmul(r, fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_2_reg(r: i32) {
    fpu_fcom(fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_3_reg(r: i32) {
    if r == 1 {
        fpu_fcomp(fpu_get_sti(r));
        fpu_pop();
    }
    else {
        trigger_ud();
    }
}
pub unsafe fn instr_DE_4_reg(r: i32) {
    fpu_fsub(r, fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_5_reg(r: i32) {
    fpu_fsubr(r, fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_6_reg(r: i32) {
    fpu_fdiv(r, fpu_get_sti(r));
    fpu_pop();
}
pub unsafe fn instr_DE_7_reg(r: i32) {
    fpu_fdivr(r, fpu_get_sti(r));
    fpu_pop();
}

#[no_mangle]
pub unsafe fn instr_DF_0_mem(addr: i32) { fpu_fildm16(addr) }
pub unsafe fn instr_DF_1_mem(addr: i32) { fpu_fisttpm16(addr); }
pub unsafe fn instr_DF_2_mem(addr: i32) { fpu_fistm16(addr); }
pub unsafe fn instr_DF_3_mem(addr: i32) { fpu_fistm16p(addr); }
pub unsafe fn instr_DF_4_mem(_addr: i32) {
    dbg_log!("fbld");
    fpu_unimpl();
}
pub unsafe fn instr_DF_5_mem(addr: i32) { fpu_fildm64(addr); }
pub unsafe fn instr_DF_6_mem(addr: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 10));
    fpu_fbstp(addr);
}
pub unsafe fn instr_DF_7_mem(addr: i32) { fpu_fistm64p(addr); }

#[no_mangle]
pub unsafe fn instr_DF_0_reg(r: i32) {
    fpu_ffree(r);
    fpu_pop();
}
pub unsafe fn instr_DF_1_reg(r: i32) { fpu_fxch(r) }
pub unsafe fn instr_DF_2_reg(r: i32) { fpu_fstp(r); }
pub unsafe fn instr_DF_3_reg(r: i32) { fpu_fstp(r); }
pub unsafe fn instr_DF_4_reg(r: i32) {
    if r == 0 {
        fpu_fnstsw_reg();
    }
    else {
        trigger_ud();
    };
}
pub unsafe fn instr_DF_5_reg(r: i32) { fpu_fucomip(r); }
pub unsafe fn instr_DF_6_reg(r: i32) { fpu_fcomip(r); }
pub unsafe fn instr_DF_7_reg(_r: i32) { trigger_ud(); }

pub unsafe fn instr16_E0(imm8s: i32) { loopne16(imm8s); }
pub unsafe fn instr16_E1(imm8s: i32) { loope16(imm8s); }
pub unsafe fn instr16_E2(imm8s: i32) { loop16(imm8s); }
pub unsafe fn instr16_E3(imm8s: i32) { jcxz16(imm8s); }
pub unsafe fn instr32_E0(imm8s: i32) { loopne32(imm8s); }
pub unsafe fn instr32_E1(imm8s: i32) { loope32(imm8s); }
pub unsafe fn instr32_E2(imm8s: i32) { loop32(imm8s); }
pub unsafe fn instr32_E3(imm8s: i32) { jcxz32(imm8s); }

#[no_mangle]
pub unsafe fn instr_E4(port: i32) {
    if test_privileges_for_io(port, 1) {
        write_reg8(AL, io_port_read8(port));
    }
}
#[no_mangle]
pub unsafe fn instr16_E5(port: i32) {
    if test_privileges_for_io(port, 2) {
        write_reg16(AX, io_port_read16(port));
    }
}
#[no_mangle]
pub unsafe fn instr32_E5(port: i32) {
    if test_privileges_for_io(port, 4) {
        write_reg32(EAX, io_port_read32(port));
    }
}
#[no_mangle]
pub unsafe fn instr_E6(port: i32) {
    if test_privileges_for_io(port, 1) {
        io_port_write8(port, read_reg8(AL));
    }
}
#[no_mangle]
pub unsafe fn instr16_E7(port: i32) {
    if test_privileges_for_io(port, 2) {
        io_port_write16(port, read_reg16(AX));
    }
}
#[no_mangle]
pub unsafe fn instr32_E7(port: i32) {
    if test_privileges_for_io(port, 4) {
        io_port_write32(port, read_reg32(EAX));
    }
}

pub unsafe fn instr16_E8(imm16: i32) {
    // call
    return_on_pagefault!(push16(get_real_eip()));
    jmp_rel16(imm16);
}
pub unsafe fn instr32_E8(imm32s: i32) {
    // call
    return_on_pagefault!(push32(get_real_eip()));
    *instruction_pointer = *instruction_pointer + imm32s;
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
pub unsafe fn instr16_E9(imm16: i32) {
    // jmp
    jmp_rel16(imm16);
}
pub unsafe fn instr32_E9(imm32s: i32) {
    // jmp
    *instruction_pointer = *instruction_pointer + imm32s;
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}

#[no_mangle]
pub unsafe fn instr16_EA(new_ip: i32, cs: i32) {
    // jmpf
    far_jump(new_ip, cs, false, false);
}
#[no_mangle]
pub unsafe fn instr32_EA(new_ip: i32, cs: i32) {
    // jmpf
    far_jump(new_ip, cs, false, true);
}

pub unsafe fn instr16_EB(imm8: i32) {
    // jmp near
    jmp_rel16(imm8);
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
pub unsafe fn instr32_EB(imm8: i32) {
    // jmp near
    *instruction_pointer = *instruction_pointer + imm8;
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}

#[no_mangle]
pub unsafe fn instr_EC() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 1) {
        write_reg8(AL, io_port_read8(port));
    }
}
#[no_mangle]
pub unsafe fn instr16_ED() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 2) {
        write_reg16(AX, io_port_read16(port));
    }
}
#[no_mangle]
pub unsafe fn instr32_ED() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 4) {
        write_reg32(EAX, io_port_read32(port));
    }
}
#[no_mangle]
pub unsafe fn instr_EE() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 1) {
        io_port_write8(port, read_reg8(AL));
    }
}
#[no_mangle]
pub unsafe fn instr16_EF() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 2) {
        io_port_write16(port, read_reg16(AX));
    }
}
#[no_mangle]
pub unsafe fn instr32_EF() {
    let port = read_reg16(DX);
    if test_privileges_for_io(port, 4) {
        io_port_write32(port, read_reg32(EAX));
    }
}

pub unsafe fn instr_F0() {
    // Dispatch validates the complete opcode/ModRM before evaluating an
    // address. Cooperative scheduling cannot split the instruction body.
    *prefixes |= prefix::PREFIX_LOCK;
    run_prefix_instruction();
    *prefixes = 0;
}

#[no_mangle]
pub unsafe fn instr_F1() {
    // INT1
    // https://code.google.com/p/corkami/wiki/x86oddities#IceBP
    dbg_assert!(false);
}

pub unsafe fn instr_F2() {
    // repnz (after F3, the last of the two counts: decode_rules::apply_prefix)
    *prefixes = crate::decode_rules::apply_prefix(*prefixes, 0xF2).unwrap();
    run_prefix_instruction();
    *prefixes = 0;
}
pub unsafe fn instr_F3() {
    // repz (after F2, the last of the two counts)
    *prefixes = crate::decode_rules::apply_prefix(*prefixes, 0xF3).unwrap();
    run_prefix_instruction();
    *prefixes = 0;
}

#[no_mangle]
pub unsafe fn instr_F4() {
    if 0 != *cpl {
        dbg_log!("#gp hlt with cpl != 0");
        trigger_gp(0);
        return;
    }

    *in_hlt = true;
    crate::cpu::execution::note_halt();

    // Try an hlt loop right now: This will run timer interrupts, and if one is
    // due it will immediately call call_interrupt_vector and continue
    // execution without an unnecessary cycle through do_run
    if *flags & FLAG_INTERRUPT != 0 {
        if crate::cpu::apic::core_count() == 1 && !crate::cpu::execution::is_deterministic() {
            js::run_hardware_timers(*acpi_enabled, js::microtick());
        }
        handle_irqs();
    }
    else {
        // execution can never resume (until NMIs are supported)
        js::cpu_event_halt();
    }
}
#[no_mangle]
pub unsafe fn instr_F5() {
    // cmc
    *flags = (*flags | 1) ^ getcf() as i32;
    *flags_changed &= !1;
}

pub unsafe fn instr_F6_0_mem(addr: i32, imm: i32) {
    test8(return_on_pagefault!(safe_read8(addr)), imm);
}
pub unsafe fn instr_F6_0_reg(r1: i32, imm: i32) { test8(read_reg8(r1), imm); }
pub unsafe fn instr_F6_1_mem(addr: i32, imm: i32) {
    test8(return_on_pagefault!(safe_read8(addr)), imm);
}
pub unsafe fn instr_F6_1_reg(r1: i32, imm: i32) { test8(read_reg8(r1), imm); }

#[no_mangle]
pub unsafe fn instr_F6_2_mem(addr: i32) { safe_read_write8(addr, &|x| !x & 0xFF) }
#[no_mangle]
pub unsafe fn instr_F6_2_reg(r1: i32) { write_reg8(r1, !read_reg8(r1)); }
#[no_mangle]
pub unsafe fn instr_F6_3_mem(addr: i32) { safe_read_write8(addr, &|x| neg8(x)) }
#[no_mangle]
pub unsafe fn instr_F6_3_reg(r1: i32) { write_reg8(r1, neg8(read_reg8(r1))); }
#[no_mangle]
pub unsafe fn instr_F6_4_mem(addr: i32) { mul8(return_on_pagefault!(safe_read8(addr))); }
#[no_mangle]
pub unsafe fn instr_F6_4_reg(r1: i32) { mul8(read_reg8(r1)); }
#[no_mangle]
pub unsafe fn instr_F6_5_mem(addr: i32) {
    imul8(return_on_pagefault!(safe_read8(addr)) << 24 >> 24);
}
#[no_mangle]
pub unsafe fn instr_F6_5_reg(r1: i32) { imul8(read_reg8(r1) << 24 >> 24); }
#[no_mangle]
pub unsafe fn instr_F6_6_mem(addr: i32) { div8(return_on_pagefault!(safe_read8(addr)) as u32); }
#[no_mangle]
pub unsafe fn instr_F6_6_reg(r1: i32) { div8(read_reg8(r1) as u32); }
#[no_mangle]
pub unsafe fn instr_F6_7_mem(addr: i32) {
    idiv8(return_on_pagefault!(safe_read8(addr)) << 24 >> 24);
}
#[no_mangle]
pub unsafe fn instr_F6_7_reg(r1: i32) { idiv8(read_reg8(r1) << 24 >> 24); }

pub unsafe fn instr16_F7_0_mem(addr: i32, imm: i32) {
    test16(return_on_pagefault!(safe_read16(addr)), imm);
}
pub unsafe fn instr16_F7_0_reg(r1: i32, imm: i32) { test16(read_reg16(r1), imm); }
pub unsafe fn instr16_F7_1_mem(addr: i32, imm: i32) {
    test16(return_on_pagefault!(safe_read16(addr)), imm);
}
pub unsafe fn instr16_F7_1_reg(r1: i32, imm: i32) { test16(read_reg16(r1), imm); }
pub unsafe fn instr16_F7_2_mem(addr: i32) { safe_read_write16(addr, &|x| !x & 0xFFFF) }
pub unsafe fn instr16_F7_2_reg(r1: i32) { write_reg16(r1, !read_reg16(r1)); }
pub unsafe fn instr16_F7_3_mem(addr: i32) { safe_read_write16(addr, &|x| neg16(x)) }
pub unsafe fn instr16_F7_3_reg(r1: i32) { write_reg16(r1, neg16(read_reg16(r1))); }
pub unsafe fn instr16_F7_4_mem(addr: i32) { mul16(return_on_pagefault!(safe_read16(addr)) as u32); }
pub unsafe fn instr16_F7_4_reg(r1: i32) { mul16(read_reg16(r1) as u32); }
pub unsafe fn instr16_F7_5_mem(addr: i32) {
    imul16(return_on_pagefault!(safe_read16(addr)) << 16 >> 16);
}
pub unsafe fn instr16_F7_5_reg(r1: i32) { imul16(read_reg16(r1) << 16 >> 16); }
pub unsafe fn instr16_F7_6_mem(addr: i32) { div16(return_on_pagefault!(safe_read16(addr)) as u32); }
pub unsafe fn instr16_F7_6_reg(r1: i32) { div16(read_reg16(r1) as u32); }
pub unsafe fn instr16_F7_7_mem(addr: i32) {
    idiv16(return_on_pagefault!(safe_read16(addr)) << 16 >> 16);
}
pub unsafe fn instr16_F7_7_reg(r1: i32) { idiv16(read_reg16(r1) << 16 >> 16); }

pub unsafe fn instr32_F7_0_mem(addr: i32, imm: i32) {
    test32(return_on_pagefault!(safe_read32s(addr)), imm);
}
pub unsafe fn instr32_F7_0_reg(r1: i32, imm: i32) { test32(read_reg32(r1), imm); }
pub unsafe fn instr32_F7_1_mem(addr: i32, imm: i32) {
    test32(return_on_pagefault!(safe_read32s(addr)), imm);
}
pub unsafe fn instr32_F7_1_reg(r1: i32, imm: i32) { test32(read_reg32(r1), imm); }
pub unsafe fn instr32_F7_2_mem(addr: i32) { safe_read_write32(addr, &|x| !x) }
pub unsafe fn instr32_F7_2_reg(r1: i32) { write_reg32(r1, !read_reg32(r1)); }
pub unsafe fn instr32_F7_3_mem(addr: i32) { safe_read_write32(addr, &|x| neg32(x)) }
pub unsafe fn instr32_F7_3_reg(r1: i32) { write_reg32(r1, neg32(read_reg32(r1))); }
pub unsafe fn instr32_F7_4_mem(addr: i32) { mul32(return_on_pagefault!(safe_read32s(addr))); }
pub unsafe fn instr32_F7_4_reg(r1: i32) { mul32(read_reg32(r1)); }
pub unsafe fn instr32_F7_5_mem(addr: i32) { imul32(return_on_pagefault!(safe_read32s(addr))); }
pub unsafe fn instr32_F7_5_reg(r1: i32) { imul32(read_reg32(r1)); }
pub unsafe fn instr32_F7_6_mem(addr: i32) {
    div32(return_on_pagefault!(safe_read32s(addr)) as u32);
}
pub unsafe fn instr32_F7_6_reg(r1: i32) { div32(read_reg32(r1) as u32); }
pub unsafe fn instr32_F7_7_mem(addr: i32) { idiv32(return_on_pagefault!(safe_read32s(addr))); }
pub unsafe fn instr32_F7_7_reg(r1: i32) { idiv32(read_reg32(r1)); }

pub unsafe fn instr_F8() {
    // clc
    *flags &= !FLAG_CARRY;
    *flags_changed &= !1;
}
pub unsafe fn instr_F9() {
    // stc
    *flags |= FLAG_CARRY;
    *flags_changed &= !1;
}
#[no_mangle]
pub unsafe fn instr_FA_without_fault() -> bool {
    // cli
    if !*protected_mode
        || if 0 != *flags & FLAG_VM { getiopl() == 3 } else { getiopl() >= *cpl as i32 }
    {
        *flags &= !FLAG_INTERRUPT;
        return true;
    }
    else if false
        && getiopl() < 3
        && if 0 != *flags & FLAG_VM {
            0 != *cr.offset(4) & CR4_VME
        }
        else {
            *cpl == 3 && 0 != *cr.offset(4) & CR4_PVI
        }
    {
        *flags &= !FLAG_VIF;
        return true;
    }
    else {
        dbg_log!("cli #gp");
        return false;
    };
}
pub unsafe fn instr_FA() {
    if !instr_FA_without_fault() {
        trigger_gp(0);
    }
}

#[no_mangle]
pub unsafe fn instr_FB_without_fault() -> bool {
    // sti
    if !*protected_mode
        || if 0 != *flags & FLAG_VM { getiopl() == 3 } else { getiopl() >= *cpl as i32 }
    {
        *flags |= FLAG_INTERRUPT;
        return true;
    }
    else if false
        && getiopl() < 3
        && *flags & FLAG_VIP == 0
        && if 0 != *flags & FLAG_VM {
            0 != *cr.offset(4) & CR4_VME
        }
        else {
            *cpl == 3 && 0 != *cr.offset(4) & CR4_PVI
        }
    {
        *flags |= FLAG_VIF;
        return true;
    }
    else {
        dbg_log!("sti #gp");
        return false;
    };
}
pub unsafe fn instr_FB() {
    let was_enabled = *flags & FLAG_INTERRUPT != 0;
    if !instr_FB_without_fault() {
        trigger_gp(0);
    }
    else if crate::cpu::execution::is_deterministic() {
        if !was_enabled {
            *interrupt_shadow = 2;
        }
    }
    else if crate::cpu::apic::core_count() > 1 && was_enabled {
        // STI only creates an interrupt shadow on IF=0 -> 1. Recursing
        // through STI with IF already set lets a chain evade the SMP budget
        // and exhaust the host stack. Keep the legacy single-core path.
    }
    else {
        *prefixes = 0;
        *previous_ip = *instruction_pointer;
        *instruction_counter += 1;
        crate::cpu::execution::begin_shadow_instruction();
        run_instruction(return_on_pagefault!(read_imm8()) | (is_osize_32() as i32) << 8);

        handle_irqs();
    }
}

pub unsafe fn instr_FC() {
    // cld
    *flags &= !FLAG_DIRECTION;
}
pub unsafe fn instr_FD() {
    // std
    *flags |= FLAG_DIRECTION;
}

pub unsafe fn instr_FE_0_mem(addr: i32) { safe_read_write8(addr, &|x| inc8(x)) }
pub unsafe fn instr_FE_0_reg(r1: i32) { write_reg8(r1, inc8(read_reg8(r1))); }
pub unsafe fn instr_FE_1_mem(addr: i32) { safe_read_write8(addr, &|x| dec8(x)) }
pub unsafe fn instr_FE_1_reg(r1: i32) { write_reg8(r1, dec8(read_reg8(r1))); }
pub unsafe fn instr16_FF_0_mem(addr: i32) { safe_read_write16(addr, &|x| inc16(x)) }
pub unsafe fn instr16_FF_0_reg(r1: i32) { write_reg16(r1, inc16(read_reg16(r1))); }
pub unsafe fn instr16_FF_1_mem(addr: i32) { safe_read_write16(addr, &|x| dec16(x)) }
pub unsafe fn instr16_FF_1_reg(r1: i32) { write_reg16(r1, dec16(read_reg16(r1))); }
pub unsafe fn instr16_FF_2_helper(data: i32) {
    // call near
    let cs = get_seg_cs();
    return_on_pagefault!(push16(get_real_eip()));
    *instruction_pointer = cs + data;
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
pub unsafe fn instr16_FF_2_mem(addr: i32) {
    instr16_FF_2_helper(return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr16_FF_2_reg(r1: i32) { instr16_FF_2_helper(read_reg16(r1)); }

#[no_mangle]
pub unsafe fn instr16_FF_3_reg(_r: i32) {
    dbg_log!("callf #ud");
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr16_FF_3_mem(addr: i32) {
    // callf
    let new_ip = return_on_pagefault!(safe_read16(addr));
    let new_cs = return_on_pagefault!(safe_read16(addr + 2));
    far_jump(new_ip, new_cs, true, false);
}
pub unsafe fn instr16_FF_4_helper(data: i32) {
    // jmp near
    *instruction_pointer = get_seg_cs() + data;
    dbg_assert!(crate::x64::state::mode().is_long() || *is_32 || get_real_eip() < 0x10000);
}
pub unsafe fn instr16_FF_4_mem(addr: i32) {
    instr16_FF_4_helper(return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr16_FF_4_reg(r1: i32) { instr16_FF_4_helper(read_reg16(r1)); }

#[no_mangle]
pub unsafe fn instr16_FF_5_reg(_r: i32) {
    dbg_log!("jmpf #ud");
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr16_FF_5_mem(addr: i32) {
    // jmpf
    let new_ip = return_on_pagefault!(safe_read16(addr));
    let new_cs = return_on_pagefault!(safe_read16(addr + 2));
    far_jump(new_ip, new_cs, false, false);
}
pub unsafe fn instr16_FF_6_mem(addr: i32) {
    return_on_pagefault!(push16(return_on_pagefault!(safe_read16(addr))));
}
pub unsafe fn instr16_FF_6_reg(r1: i32) {
    return_on_pagefault!(push16(read_reg16(r1)));
}

pub unsafe fn instr32_FF_0_mem(addr: i32) { safe_read_write32(addr, &|x| inc32(x)) }
pub unsafe fn instr32_FF_0_reg(r1: i32) { write_reg32(r1, inc32(read_reg32(r1))); }
pub unsafe fn instr32_FF_1_mem(addr: i32) { safe_read_write32(addr, &|x| dec32(x)) }
pub unsafe fn instr32_FF_1_reg(r1: i32) { write_reg32(r1, dec32(read_reg32(r1))); }

pub unsafe fn instr32_FF_2_helper(data: i32) {
    // call near
    let cs = get_seg_cs();
    return_on_pagefault!(push32(get_real_eip()));
    // (16-bit code goes above 64 KiB only where CS's limit allows: SMM's
    // entry state, big real mode)
    dbg_assert!(*is_32 || data < 0x10000 || *segment_limits.offset(CS as isize) > 0xFFFF);
    *instruction_pointer = cs + data;
}
pub unsafe fn instr32_FF_2_mem(addr: i32) {
    instr32_FF_2_helper(return_on_pagefault!(safe_read32s(addr)));
}
pub unsafe fn instr32_FF_2_reg(r1: i32) { instr32_FF_2_helper(read_reg32(r1)); }
#[no_mangle]
pub unsafe fn instr32_FF_3_reg(_r: i32) {
    dbg_log!("callf #ud");
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr32_FF_3_mem(addr: i32) {
    // callf
    let new_ip = return_on_pagefault!(safe_read32s(addr));
    let new_cs = return_on_pagefault!(safe_read16(addr + 4));
    if !*protected_mode || vm86_mode() {
        if 0 != new_ip as u32 & 0xFFFF0000 {
            dbg_assert!(false);
        }
    }
    far_jump(new_ip, new_cs, true, true);
}

pub unsafe fn instr32_FF_4_helper(data: i32) {
    // jmp near (above 64 KiB in 16-bit code: see instr32_FF_2_helper)
    dbg_assert!(*is_32 || data < 0x10000 || *segment_limits.offset(CS as isize) > 0xFFFF);
    *instruction_pointer = get_seg_cs() + data;
}
pub unsafe fn instr32_FF_4_mem(addr: i32) {
    instr32_FF_4_helper(return_on_pagefault!(safe_read32s(addr)));
}
pub unsafe fn instr32_FF_4_reg(r1: i32) { instr32_FF_4_helper(read_reg32(r1)); }

#[no_mangle]
pub unsafe fn instr32_FF_5_reg(_r: i32) {
    dbg_log!("jmpf #ud");
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr32_FF_5_mem(addr: i32) {
    // jmpf
    let new_ip = return_on_pagefault!(safe_read32s(addr));
    let new_cs = return_on_pagefault!(safe_read16(addr + 4));
    if !*protected_mode || vm86_mode() {
        if 0 != new_ip as u32 & 0xFFFF0000 {
            dbg_assert!(false);
        }
    }
    far_jump(new_ip, new_cs, false, true);
}
pub unsafe fn instr32_FF_6_mem(addr: i32) {
    return_on_pagefault!(push32(return_on_pagefault!(safe_read32s(addr))));
}
pub unsafe fn instr32_FF_6_reg(r1: i32) {
    return_on_pagefault!(push32(read_reg32(r1)));
}
                                                                                                                                                       source/v64/src/rust/cpu/instructions_0f.rs                                                          0000644 0000000 0000000 00000607570 00000000000 015755  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_snake_case)]

// In IR-enabled cores, SSE FP semantic entries are not inlined: LLVM may reorder
// equivalent FP operands across callers, changing permitted Wasm NaN payloads.
// One shared kernel keeps interpreter/IR results bit-identical in each build.

unsafe fn undefined_instruction() {
    dbg_assert!(false, "Undefined instructions");
    trigger_ud()
}
unsafe fn unimplemented_sse() {
    dbg_assert!(false, "Unimplemented SSE instruction");
    trigger_ud()
}

use crate::config;
use crate::cpu::arith::{
    bsf16, bsf32, bsr16, bsr32, bt_mem, bt_reg, btc_mem, btc_reg, btr_mem, btr_reg, bts_mem,
    bts_reg, cmpxchg16, cmpxchg32, cmpxchg8, popcnt, shld16, shld32, shrd16, shrd32, xadd16,
    xadd32, xadd8,
};
use crate::cpu::arith::{
    imul_reg16, imul_reg32, saturate_sd_to_sb, saturate_sd_to_sw, saturate_sd_to_ub,
    saturate_sw_to_sb, saturate_sw_to_ub, saturate_ud_to_ub, saturate_uw,
};
use crate::cpu::cpu::*;
use crate::cpu::fpu::fpu_set_tag_word;
use crate::cpu::global_pointers::*;
use crate::cpu::misc_instr::{
    adjust_stack_reg, bswap, cmovcc16, cmovcc32, fxrstor, fxsave, get_stack_pointer, jmpcc16,
    jmpcc32, push16, push32_sreg, setcc_mem, setcc_reg, test_b, test_be, test_l, test_le, test_o,
    test_p, test_s, test_z,
};
use crate::cpu::misc_instr::{lar, lsl, verr, verw};
use crate::cpu::misc_instr::{lss16, lss32};
use crate::cpu::sse_instr::*;

#[no_mangle]
pub unsafe fn instr16_0F00_0_mem(addr: i32) {
    // sldt
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    return_on_pagefault!(safe_write16(addr, *sreg.offset(LDTR as isize) as i32));
}
#[no_mangle]
pub unsafe fn instr32_0F00_0_mem(addr: i32) { instr16_0F00_0_mem(addr) }
#[no_mangle]
pub unsafe fn instr16_0F00_0_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    write_reg16(r, *sreg.offset(LDTR as isize) as i32);
}
#[no_mangle]
pub unsafe fn instr32_0F00_0_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    write_reg32(r, *sreg.offset(LDTR as isize) as i32);
}

#[no_mangle]
pub unsafe fn instr16_0F00_1_mem(addr: i32) {
    // str
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    return_on_pagefault!(safe_write16(addr, *sreg.offset(TR as isize) as i32));
}
#[no_mangle]
pub unsafe fn instr32_0F00_1_mem(addr: i32) { instr16_0F00_1_mem(addr) }
#[no_mangle]
pub unsafe fn instr16_0F00_1_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    write_reg16(r, *sreg.offset(TR as isize) as i32);
}
#[no_mangle]
pub unsafe fn instr32_0F00_1_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
        return;
    }
    write_reg32(r, *sreg.offset(TR as isize) as i32);
}

#[no_mangle]
pub unsafe fn instr16_0F00_2_mem(addr: i32) {
    // lldt
    if !*protected_mode || vm86_mode() {
        trigger_ud();
    }
    else if 0 != *cpl {
        trigger_gp(0);
    }
    else {
        return_on_pagefault!(load_ldt(return_on_pagefault!(safe_read16(addr))));
    };
}
#[no_mangle]
pub unsafe fn instr32_0F00_2_mem(addr: i32) { instr16_0F00_2_mem(addr) }
#[no_mangle]
pub unsafe fn instr16_0F00_2_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
    }
    else if 0 != *cpl {
        trigger_gp(0);
    }
    else {
        return_on_pagefault!(load_ldt(read_reg16(r)));
    };
}
#[no_mangle]
pub unsafe fn instr32_0F00_2_reg(r: i32) { instr16_0F00_2_reg(r) }

#[no_mangle]
pub unsafe fn instr16_0F00_3_mem(addr: i32) {
    // ltr
    if !*protected_mode || vm86_mode() {
        trigger_ud();
    }
    else if 0 != *cpl {
        trigger_gp(0);
    }
    else {
        load_tr(return_on_pagefault!(safe_read16(addr)));
    };
}
#[no_mangle]
pub unsafe fn instr32_0F00_3_mem(addr: i32) { instr16_0F00_3_mem(addr); }
#[no_mangle]
pub unsafe fn instr16_0F00_3_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        trigger_ud();
    }
    else if 0 != *cpl {
        trigger_gp(0);
    }
    else {
        load_tr(read_reg16(r));
    };
}
#[no_mangle]
pub unsafe fn instr32_0F00_3_reg(r: i32) { instr16_0F00_3_reg(r) }

#[no_mangle]
pub unsafe fn instr16_0F00_4_mem(addr: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("verr #ud");
        trigger_ud();
        return;
    }
    verr(return_on_pagefault!(safe_read16(addr)));
}
#[no_mangle]
pub unsafe fn instr32_0F00_4_mem(addr: i32) { instr16_0F00_4_mem(addr) }
#[no_mangle]
pub unsafe fn instr16_0F00_4_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("verr #ud");
        trigger_ud();
        return;
    }
    verr(read_reg16(r));
}
#[no_mangle]
pub unsafe fn instr32_0F00_4_reg(r: i32) { instr16_0F00_4_reg(r) }
#[no_mangle]
pub unsafe fn instr16_0F00_5_mem(addr: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("verw #ud");
        trigger_ud();
        return;
    }
    verw(return_on_pagefault!(safe_read16(addr)));
}
#[no_mangle]
pub unsafe fn instr32_0F00_5_mem(addr: i32) { instr16_0F00_5_mem(addr) }
#[no_mangle]
pub unsafe fn instr16_0F00_5_reg(r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("verw #ud");
        trigger_ud();
        return;
    }
    verw(read_reg16(r));
}
#[no_mangle]
pub unsafe fn instr32_0F00_5_reg(r: i32) { instr16_0F00_5_reg(r) }

#[no_mangle]
pub unsafe fn instr16_0F01_0_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0F01_0_reg(_r: i32) { trigger_ud(); }

unsafe fn sgdt(addr: i32, mask: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 6));
    safe_write16(addr, *gdtr_size).unwrap();
    safe_write32(addr + 2, *gdtr_offset & mask).unwrap();
}
#[no_mangle]
pub unsafe fn instr16_0F01_0_mem(addr: i32) { sgdt(addr, 0xFFFFFF) }
#[no_mangle]
pub unsafe fn instr32_0F01_0_mem(addr: i32) { sgdt(addr, -1) }

#[no_mangle]
pub unsafe fn instr16_0F01_1_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0F01_1_reg(_r: i32) { trigger_ud(); }

unsafe fn sidt(addr: i32, mask: i32) {
    return_on_pagefault!(writable_or_pagefault(addr, 6));
    safe_write16(addr, *idtr_size).unwrap();
    safe_write32(addr + 2, *idtr_offset & mask).unwrap();
}
#[no_mangle]
pub unsafe fn instr16_0F01_1_mem(addr: i32) { sidt(addr, 0xFFFFFF) }
#[no_mangle]
pub unsafe fn instr32_0F01_1_mem(addr: i32) { sidt(addr, -1) }

#[no_mangle]
pub unsafe fn instr16_0F01_2_reg(r: i32) { instr_0F01_2_reg(r) }
#[no_mangle]
pub unsafe fn instr32_0F01_2_reg(r: i32) { instr_0F01_2_reg(r) }
unsafe fn instr_0F01_2_reg(r: i32) {
    use crate::prefix::{PREFIX_66, PREFIX_F2, PREFIX_F3};
    // (XGETBV and XSETBV have no mandatory prefix)
    if *prefixes & (PREFIX_66 | PREFIX_F2 | PREFIX_F3) != 0 {
        trigger_ud();
        return;
    }
    xgetbv_xsetbv(r);
}
/// 0F 01 D0 (XGETBV) and D1 (XSETBV), without a mandatory prefix (the IR
/// checks that when it decodes them); 0F 01 D2-D7 are #UD. False if a fault
/// was delivered.
pub unsafe fn xgetbv_xsetbv(r: i32) -> bool {
    if r > 1 {
        trigger_ud();
        return false;
    }
    if !crate::cpu::xstate::usable(false) {
        return false;
    }
    if r == 0 {
        let Some(value) = crate::cpu::xstate::xgetbv(read_reg32(ECX) as u32, false)
        else {
            trigger_gp(0);
            return false;
        };
        write_reg32(EAX, value as i32);
        write_reg32(EDX, (value >> 32) as i32);
        true
    }
    else if *cpl != 0
        || !crate::cpu::xstate::xsetbv(
            read_reg32(ECX) as u32,
            (read_reg32(EDX) as u32 as u64) << 32 | read_reg32(EAX) as u32 as u64,
        )
    {
        trigger_gp(0);
        false
    }
    else {
        true
    }
}

unsafe fn lgdt(addr: i32, mask: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }
    let size = return_on_pagefault!(safe_read16(addr));
    let offset = return_on_pagefault!(safe_read32s(addr + 2));
    *gdtr_size = size;
    *gdtr_offset = offset & mask;
    // (outside 64-bit mode the base is 32 bits, zero-extended: the upper half
    // a long mode OS left must go, or OVMF's SMI entry, which loads its GDT
    // in 32-bit code, then enables long mode with the OS's upper half)
    *x64_gdtr_base_hi = 0;
}
#[no_mangle]
pub unsafe fn instr16_0F01_2_mem(addr: i32) { lgdt(addr, 0xFFFFFF); }
#[no_mangle]
pub unsafe fn instr32_0F01_2_mem(addr: i32) { lgdt(addr, -1); }

#[no_mangle]
pub unsafe fn instr16_0F01_3_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0F01_3_reg(_r: i32) { trigger_ud(); }

unsafe fn lidt(addr: i32, mask: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }
    let size = return_on_pagefault!(safe_read16(addr));
    let offset = return_on_pagefault!(safe_read32s(addr + 2));
    *idtr_size = size;
    *idtr_offset = offset & mask;
    // (zero-extended, as lgdt's)
    *x64_idtr_base_hi = 0;
}
#[no_mangle]
pub unsafe fn instr16_0F01_3_mem(addr: i32) { lidt(addr, 0xFFFFFF); }
#[no_mangle]
pub unsafe fn instr32_0F01_3_mem(addr: i32) { lidt(addr, -1); }

#[no_mangle]
pub unsafe fn instr16_0F01_4_reg(r: i32) {
    // smsw
    write_reg16(r, *cr);
}
#[no_mangle]
pub unsafe fn instr32_0F01_4_reg(r: i32) { write_reg32(r, *cr); }
#[no_mangle]
pub unsafe fn instr16_0F01_4_mem(addr: i32) {
    return_on_pagefault!(safe_write16(addr, *cr & 0xFFFF));
}
#[no_mangle]
pub unsafe fn instr32_0F01_4_mem(addr: i32) {
    return_on_pagefault!(safe_write16(addr, *cr & 0xFFFF));
}

#[no_mangle]
pub unsafe fn lmsw(mut new_cr0: i32) {
    new_cr0 = *cr & !15 | new_cr0 & 15;
    if *protected_mode {
        // lmsw cannot be used to switch back
        new_cr0 |= CR0_PE
    }
    set_cr0(new_cr0);
}
#[no_mangle]
pub unsafe fn instr16_0F01_6_reg(r: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }
    lmsw(read_reg16(r));
}
#[no_mangle]
pub unsafe fn instr32_0F01_6_reg(r: i32) { instr16_0F01_6_reg(r); }
#[no_mangle]
pub unsafe fn instr16_0F01_6_mem(addr: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }
    lmsw(return_on_pagefault!(safe_read16(addr)));
}
#[no_mangle]
pub unsafe fn instr32_0F01_6_mem(addr: i32) { instr16_0F01_6_mem(addr) }

#[no_mangle]
pub unsafe fn instr16_0F01_7_reg(r: i32) {
    if r == 1 {
        rdtscp();
    }
    else {
        trigger_ud();
    }
}
#[no_mangle]
pub unsafe fn instr32_0F01_7_reg(r: i32) { instr16_0F01_7_reg(r) }

/// RDTSCP (0F 01 F9): RDTSC that also loads ECX with IA32_TSC_AUX. Only the
/// x86-64 profile advertises it (CPUID.80000001h:EDX[27]), and a 32-bit kernel
/// there uses it too (Linux's rdtsc_ordered); the legacy profile raises #UD.
/// In IA-32e mode x64::system has it in either profile, and so does
/// compatibility-mode code that compiled code steps through here. Whether it
/// completed.
pub unsafe fn rdtscp() -> bool {
    if !X64_TEST_CAPABILITIES && crate::x64::state::efer() & crate::x64::state::EFER_LMA == 0 {
        trigger_ud();
        return false;
    }
    if 0 != *cpl && 0 != *cr.offset(4) & CR4_TSD {
        trigger_gp(0);
        return false;
    }
    let tsc = read_tsc();
    write_reg32(EAX, tsc as i32);
    write_reg32(EDX, (tsc >> 32) as i32);
    write_reg32(ECX, *x64_tsc_aux as i32);
    true
}

#[no_mangle]
pub unsafe fn instr16_0F01_7_mem(addr: i32) {
    // invlpg
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }
    invlpg(addr);
}
#[no_mangle]
pub unsafe fn instr32_0F01_7_mem(addr: i32) { instr16_0F01_7_mem(addr) }

#[no_mangle]
pub unsafe fn instr16_0F02_mem(addr: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lar #ud");
        trigger_ud();
        return;
    }
    write_reg16(
        r,
        lar(return_on_pagefault!(safe_read16(addr)), read_reg16(r)),
    );
}
#[no_mangle]
pub unsafe fn instr16_0F02_reg(r1: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lar #ud");
        trigger_ud();
        return;
    }
    write_reg16(r, lar(read_reg16(r1), read_reg16(r)));
}
#[no_mangle]
pub unsafe fn instr32_0F02_mem(addr: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lar #ud");
        trigger_ud();
        return;
    }
    write_reg32(
        r,
        lar(return_on_pagefault!(safe_read16(addr)), read_reg32(r)),
    );
}
#[no_mangle]
pub unsafe fn instr32_0F02_reg(r1: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lar #ud");
        trigger_ud();
        return;
    }
    write_reg32(r, lar(read_reg16(r1), read_reg32(r)));
}
#[no_mangle]
pub unsafe fn instr16_0F03_mem(addr: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lsl #ud");
        trigger_ud();
        return;
    }
    write_reg16(
        r,
        lsl(return_on_pagefault!(safe_read16(addr)), read_reg16(r)),
    );
}
#[no_mangle]
pub unsafe fn instr16_0F03_reg(r1: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lsl #ud");
        trigger_ud();
        return;
    }
    write_reg16(r, lsl(read_reg16(r1), read_reg16(r)));
}
#[no_mangle]
pub unsafe fn instr32_0F03_mem(addr: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lsl #ud");
        trigger_ud();
        return;
    }
    write_reg32(
        r,
        lsl(return_on_pagefault!(safe_read16(addr)), read_reg32(r)),
    );
}
#[no_mangle]
pub unsafe fn instr32_0F03_reg(r1: i32, r: i32) {
    if !*protected_mode || vm86_mode() {
        dbg_log!("lsl #ud");
        trigger_ud();
        return;
    }
    write_reg32(r, lsl(read_reg16(r1), read_reg32(r)));
}
#[no_mangle]
pub unsafe fn instr_0F04() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F05() {
    // SYSCALL outside 64-bit mode (legacy or compatibility): #UD on Intel,
    // an architectural outcome rather than a missing instruction
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr_0F06() {
    // clts
    if 0 != *cpl {
        dbg_log!("clts #gp");
        trigger_gp(0);
    }
    else {
        if false {
            dbg_log!("clts");
        }
        crate::step_profile::note_event(crate::step_profile::event::CLTS, 0);
        *cr &= !CR0_TS;
    };
}
#[no_mangle]
pub unsafe fn instr_0F07() {
    // SYSRET outside 64-bit mode: #UD on Intel (see instr_0F05)
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr_0F08() {
    // invd
    undefined_instruction();
}
#[no_mangle]
pub unsafe fn instr_0F09() {
    if 0 != *cpl {
        dbg_log!("wbinvd #gp");
        trigger_gp(0);
    }
    else {
        // wbinvd
    };
}
#[no_mangle]
pub unsafe fn instr_0F0A() { undefined_instruction(); }
pub unsafe fn instr_0F0B() {
    // UD2
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr_0F0C() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F0D() {
    // nop
    undefined_instruction();
}
#[no_mangle]
pub unsafe fn instr_0F0E() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F0F() { undefined_instruction(); }

pub unsafe fn instr_0F10(source: reg128, r: i32) {
    // movups xmm, xmm/m128
    mov_rm_r128(source, r);
}
pub unsafe fn instr_0F10_reg(r1: i32, r2: i32) { instr_0F10(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F10_mem(addr: i32, r: i32) {
    instr_0F10(return_on_pagefault!(safe_read128s(addr)), r);
}
pub unsafe fn instr_F30F10_reg(r1: i32, r2: i32) {
    // movss xmm, xmm/m32
    let data = read_xmm128s(r1);
    write_xmm32(r2, data.u32[0] as i32);
}
pub unsafe fn instr_F30F10_mem(addr: i32, r: i32) {
    // movss xmm, xmm/m32
    let data = return_on_pagefault!(safe_read32s(addr));
    write_xmm128(r, data, 0, 0, 0);
}
pub unsafe fn instr_660F10(source: reg128, r: i32) {
    // movupd xmm, xmm/m128
    mov_rm_r128(source, r);
}
pub unsafe fn instr_660F10_reg(r1: i32, r2: i32) { instr_660F10(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F10_mem(addr: i32, r: i32) {
    instr_660F10(return_on_pagefault!(safe_read128s(addr)), r);
}
pub unsafe fn instr_F20F10_reg(r1: i32, r2: i32) {
    // movsd xmm, xmm/m64
    let data = read_xmm128s(r1);
    write_xmm64(r2, data.u64[0]);
}
pub unsafe fn instr_F20F10_mem(addr: i32, r: i32) {
    // movsd xmm, xmm/m64
    let data = return_on_pagefault!(safe_read64s(addr));
    write_xmm128_2(r, data, 0);
}
pub unsafe fn instr_0F11_reg(r1: i32, r2: i32) {
    // movups xmm/m128, xmm
    mov_r_r128(r1, r2);
}
pub unsafe fn instr_0F11_mem(addr: i32, r: i32) {
    // movups xmm/m128, xmm
    mov_r_m128(addr, r);
}
pub unsafe fn instr_F30F11_reg(rm_dest: i32, reg_src: i32) {
    // movss xmm/m32, xmm
    let data = read_xmm128s(reg_src);
    write_xmm32(rm_dest, data.u32[0] as i32);
}
pub unsafe fn instr_F30F11_mem(addr: i32, r: i32) {
    // movss xmm/m32, xmm
    let data = read_xmm128s(r);
    return_on_pagefault!(safe_write32(addr, data.u32[0] as i32));
}
pub unsafe fn instr_660F11_reg(r1: i32, r2: i32) {
    // movupd xmm/m128, xmm
    mov_r_r128(r1, r2);
}
pub unsafe fn instr_660F11_mem(addr: i32, r: i32) {
    // movupd xmm/m128, xmm
    mov_r_m128(addr, r);
}
pub unsafe fn instr_F20F11_reg(r1: i32, r2: i32) {
    // movsd xmm/m64, xmm
    let data = read_xmm128s(r2);
    write_xmm64(r1, data.u64[0]);
}
pub unsafe fn instr_F20F11_mem(addr: i32, r: i32) {
    // movsd xmm/m64, xmm
    let data = read_xmm64s(r);
    return_on_pagefault!(safe_write64(addr, data));
}
pub unsafe fn instr_0F12_mem(addr: i32, r: i32) {
    // movlps xmm, m64
    let data = return_on_pagefault!(safe_read64s(addr));
    write_xmm64(r, data);
}
pub unsafe fn instr_0F12_reg(r1: i32, r2: i32) {
    // movhlps xmm, xmm
    let data = read_xmm128s(r1);
    write_xmm64(r2, data.u64[1]);
}
pub unsafe fn instr_660F12_reg(_r1: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F12_mem(addr: i32, r: i32) {
    // movlpd xmm, m64
    let data = return_on_pagefault!(safe_read64s(addr));
    write_xmm64(r, data);
}
#[no_mangle]
pub unsafe fn instr_F20F12(source: u64, r: i32) {
    // movddup xmm1, xmm2/m64
    write_xmm_reg128(
        r,
        reg128 {
            u64: [source, source],
        },
    );
}
pub unsafe fn instr_F20F12_reg(r1: i32, r2: i32) { instr_F20F12(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F12_mem(addr: i32, r: i32) {
    instr_F20F12(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_F30F12(source: reg128, r: i32) {
    // movsldup xmm1, xmm2/m128
    write_xmm_reg128(
        r,
        reg128 {
            u32: [source.u32[0], source.u32[0], source.u32[2], source.u32[2]],
        },
    );
}
pub unsafe fn instr_F30F12_reg(r1: i32, r2: i32) { instr_F30F12(read_xmm128s(r1), r2); }
pub unsafe fn instr_F30F12_mem(addr: i32, r: i32) {
    instr_F30F12(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_0F13_mem(addr: i32, r: i32) {
    // movlps m64, xmm
    movl_r128_m64(addr, r);
}
pub unsafe fn instr_0F13_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660F13_reg(_r1: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F13_mem(addr: i32, r: i32) {
    // movlpd xmm/m64, xmm
    movl_r128_m64(addr, r);
}

#[no_mangle]
pub unsafe fn instr_0F14(source: u64, r: i32) {
    // unpcklps xmm, xmm/m128
    let destination = read_xmm64s(r);
    write_xmm128(
        r,
        destination as i32,
        source as i32,
        (destination >> 32) as i32,
        (source >> 32) as i32,
    );
}
pub unsafe fn instr_0F14_reg(r1: i32, r2: i32) { instr_0F14(read_xmm64s(r1), r2); }
pub unsafe fn instr_0F14_mem(addr: i32, r: i32) {
    // (an m128 operand, of which the low quadword is read)
    return_on_pagefault!(aligned16(addr));
    instr_0F14(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F14(source: u64, r: i32) {
    // unpcklpd xmm, xmm/m128
    let destination = read_xmm64s(r);
    write_xmm128(
        r,
        destination as i32,
        (destination >> 32) as i32,
        source as i32,
        (source >> 32) as i32,
    );
}
pub unsafe fn instr_660F14_reg(r1: i32, r2: i32) { instr_660F14(read_xmm64s(r1), r2); }
pub unsafe fn instr_660F14_mem(addr: i32, r: i32) {
    // (an m128 operand, of which the low quadword is read)
    return_on_pagefault!(aligned16(addr));
    instr_660F14(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F15(source: reg128, r: i32) {
    // unpckhps xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[2] as i32,
        source.u32[2] as i32,
        destination.u32[3] as i32,
        source.u32[3] as i32,
    );
}
pub unsafe fn instr_0F15_reg(r1: i32, r2: i32) { instr_0F15(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F15_mem(addr: i32, r: i32) {
    instr_0F15(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F15(source: reg128, r: i32) {
    // unpckhpd xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[2] as i32,
        destination.u32[3] as i32,
        source.u32[2] as i32,
        source.u32[3] as i32,
    );
}
pub unsafe fn instr_660F15_reg(r1: i32, r2: i32) { instr_660F15(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F15_mem(addr: i32, r: i32) {
    instr_660F15(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F16(source: u64, r: i32) { (*reg_xmm.offset(r as isize)).u64[1] = source; }
pub unsafe fn instr_0F16_mem(addr: i32, r: i32) {
    // movhps xmm, m64
    instr_0F16(return_on_pagefault!(safe_read64s(addr)), r);
}
pub unsafe fn instr_0F16_reg(r1: i32, r2: i32) {
    // movlhps xmm, xmm
    instr_0F16(read_xmm64s(r1), r2);
}
pub unsafe fn instr_660F16_mem(addr: i32, r: i32) {
    // movhpd xmm, m64
    instr_0F16(return_on_pagefault!(safe_read64s(addr)), r);
}
pub unsafe fn instr_660F16_reg(_r1: i32, _r2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_F30F16(source: reg128, r: i32) {
    // movshdup xmm1, xmm2/m128
    write_xmm_reg128(
        r,
        reg128 {
            u32: [source.u32[1], source.u32[1], source.u32[3], source.u32[3]],
        },
    );
}
pub unsafe fn instr_F30F16_reg(r1: i32, r2: i32) { instr_F30F16(read_xmm128s(r1), r2); }
pub unsafe fn instr_F30F16_mem(addr: i32, r: i32) {
    instr_F30F16(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_0F17_mem(addr: i32, r: i32) {
    // movhps m64, xmm
    movh_r128_m64(addr, r);
}
pub unsafe fn instr_0F17_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660F17_mem(addr: i32, r: i32) {
    // movhpd m64, xmm
    movh_r128_m64(addr, r);
}
pub unsafe fn instr_660F17_reg(_r1: i32, _r2: i32) { trigger_ud(); }

pub unsafe fn instr_0F18_reg(_r1: i32, _r2: i32) {
    // reserved nop
}
pub unsafe fn instr_0F18_mem(_addr: i32, _r: i32) {
    // prefetch
    // nop for us
}

pub unsafe fn instr_0F19_reg(_r1: i32, _r2: i32) {}
pub unsafe fn instr_0F19_mem(_addr: i32, _r: i32) {}

#[no_mangle]
pub unsafe fn instr_0F1A() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F1B() { undefined_instruction(); }

pub unsafe fn instr_0F1C_reg(_r1: i32, _r2: i32) {}
pub unsafe fn instr_0F1C_mem(_addr: i32, _r: i32) {}
pub unsafe fn instr_0F1D_reg(_r1: i32, _r2: i32) {}
pub unsafe fn instr_0F1D_mem(_addr: i32, _r: i32) {}
pub unsafe fn instr_0F1E_reg(_r1: i32, _r2: i32) {}
pub unsafe fn instr_0F1E_mem(_addr: i32, _r: i32) {}
pub unsafe fn instr_0F1F_reg(_r1: i32, _r2: i32) {}
pub unsafe fn instr_0F1F_mem(_addr: i32, _r: i32) {}

#[no_mangle]
pub unsafe fn instr_0F20(r: i32, creg: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }

    match creg {
        0 => {
            write_reg32(r, *cr);
        },
        2 => {
            write_reg32(r, *cr.offset(2));
        },
        3 => {
            write_reg32(r, *cr.offset(3));
        },
        4 => {
            write_reg32(r, *cr.offset(4));
        },
        _ => {
            dbg_log!("{}", creg);
            undefined_instruction();
        },
    }
}
#[no_mangle]
pub unsafe fn instr_0F21(r: i32, mut dreg_index: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }

    if dreg_index == 4 || dreg_index == 5 {
        if 0 != *cr.offset(4) & CR4_DE {
            dbg_log!("#ud mov dreg 4/5 with cr4.DE set");
            trigger_ud();
            return;
        }
        else {
            // DR4 and DR5 refer to DR6 and DR7 respectively
            dreg_index += 2
        }
    }
    write_reg32(r, *dreg.offset(dreg_index as isize));

    if false {
        dbg_log!(
            "read dr{}: {:x}",
            dreg_index,
            *dreg.offset(dreg_index as isize)
        );
    }
}
#[no_mangle]
pub unsafe fn instr_0F22(r: i32, creg: i32) { mov_to_cr(r, creg); }
/// false: a fault was delivered (the IR commits the instruction otherwise)
pub unsafe fn mov_to_cr(r: i32, creg: i32) -> bool {
    if 0 != *cpl {
        trigger_gp(0);
        return false;
    }

    let data = read_reg32(r);
    // mov cr, addr
    match creg {
        0 => {
            if false {
                dbg_log!("cr0 <- {:x}", data);
            }
            set_cr0(data)
        },
        2 => {
            dbg_log!("cr2 <- {:x}", data);
            *cr.offset(2) = data;
            true
        },
        3 => set_cr3(data),
        4 => {
            if crate::x64::state::efer() & crate::x64::state::EFER_LME != 0 {
                if let Err(fault) = crate::x64::system::write_cr(4, data as u32 as u64) {
                    crate::x64::system::raise(fault);
                    return false;
                }
                return true;
            }
            dbg_log!("cr4 <- {:x}", data);
            if 0 != data as u32 & !cr4_valid_bits() {
                dbg_log!("trigger_gp: Invalid cr4 bit");
                trigger_gp(0);
                false
            }
            else {
                if 0 != (*cr.offset(4) ^ data) & (CR4_PGE | CR4_PSE | CR4_PAE) {
                    full_clear_tlb();
                }
                if data & CR4_PAE != 0
                    && *cr & CR0_PG != 0
                    && 0 != (*cr.offset(4) ^ data) & (CR4_PGE | CR4_PSE | CR4_SMEP)
                {
                    load_pdpte(*cr.offset(3));
                }
                *cr.offset(4) = data;
                true
            }
        },
        _ => {
            dbg_log!("{}", creg);
            undefined_instruction();
            false
        },
    }
}
#[no_mangle]
pub unsafe fn instr_0F23(r: i32, mut dreg_index: i32) {
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }

    if dreg_index == 4 || dreg_index == 5 {
        if 0 != *cr.offset(4) & CR4_DE {
            dbg_log!("#ud mov dreg 4/5 with cr4.DE set");
            trigger_ud();
            return;
        }
        else {
            // DR4 and DR5 refer to DR6 and DR7 respectively
            dreg_index += 2
        }
    }
    *dreg.offset(dreg_index as isize) = read_reg32(r);
    if false {
        dbg_log!(
            "write dr{}: {:x}",
            dreg_index,
            *dreg.offset(dreg_index as isize)
        );
    }
}
#[no_mangle]
pub unsafe fn instr_0F24() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F25() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F26() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F27() { undefined_instruction(); }

pub unsafe fn instr_0F28(source: reg128, r: i32) {
    // movaps xmm, xmm/m128
    mov_rm_r128(source, r);
}
pub unsafe fn instr_0F28_reg(r1: i32, r2: i32) { instr_0F28(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F28_mem(addr: i32, r: i32) {
    instr_0F28(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_660F28(source: reg128, r: i32) {
    // movapd xmm, xmm/m128
    // Note: Same as movdqa (660F6F)
    mov_rm_r128(source, r);
}
pub unsafe fn instr_660F28_reg(r1: i32, r2: i32) { instr_660F28(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F28_mem(addr: i32, r: i32) {
    instr_660F28(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_0F29_mem(addr: i32, r: i32) {
    // movaps m128, xmm
    mov_r_m128_aligned(addr, r);
}
pub unsafe fn instr_0F29_reg(r1: i32, r2: i32) {
    // movaps xmm, xmm
    mov_r_r128(r1, r2);
}
pub unsafe fn instr_660F29_mem(addr: i32, r: i32) {
    // movapd m128, xmm
    mov_r_m128_aligned(addr, r);
}
pub unsafe fn instr_660F29_reg(r1: i32, r2: i32) {
    // movapd xmm, xmm
    mov_r_r128(r1, r2);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F2A(source: u64, r: i32) -> bool {
    // cvtpi2ps xmm, mm/m64
    match sse_fp_convert(0x0F2A, r, source as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_0F2A_reg(r1: i32, r2: i32) {
    // (only the MMX register form leaves the x87 for MMX, as CVTPI2PD's; from
    // memory the x87 stack stays: Need for Speed: Most Wanted's mixer runs x87
    // code right after CVTPI2PS xmm, m64, and each load overflowed into NaN)
    if instr_0F2A(read_mmx64s(r1), r2) {
        transition_fpu_to_mmx();
    }
}
pub unsafe fn instr_0F2A_mem(addr: i32, r: i32) {
    instr_0F2A(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F2A(source: u64, r: i32) -> bool {
    // cvtpi2pd xmm, mm/m64
    match sse_fp_convert(0x660F2A, r, source as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_660F2A_reg(r1: i32, r2: i32) {
    if instr_660F2A(read_mmx64s(r1), r2) {
        transition_fpu_to_mmx();
    }
}
pub unsafe fn instr_660F2A_mem(addr: i32, r: i32) {
    instr_660F2A(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F2A(source: i32, r: i32) -> bool {
    // cvtsi2sd xmm, r/m32
    match sse_fp_convert(0xF20F2A, r, source as u32 as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F20F2A_reg(r1: i32, r2: i32) { instr_F20F2A(read_reg32(r1), r2); }
pub unsafe fn instr_F20F2A_mem(addr: i32, r: i32) {
    instr_F20F2A(return_on_pagefault!(safe_read32s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F2A(source: i32, r: i32) -> bool {
    // cvtsi2ss xmm, r/m32
    match sse_fp_convert(0xF30F2A, r, source as u32 as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F30F2A_reg(r1: i32, r2: i32) { instr_F30F2A(read_reg32(r1), r2); }
pub unsafe fn instr_F30F2A_mem(addr: i32, r: i32) {
    instr_F30F2A(return_on_pagefault!(safe_read32s(addr)), r);
}

pub unsafe fn instr_0F2B_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_0F2B_mem(addr: i32, r: i32) {
    // movntps m128, xmm
    mov_r_m128_aligned(addr, r);
}
pub unsafe fn instr_660F2B_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660F2B_mem(addr: i32, r: i32) {
    // movntpd m128, xmm
    mov_r_m128_aligned(addr, r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F2C(source: u64, r: i32) -> bool {
    // cvttps2pi mm, xmm/m64
    match sse_fp_convert(0x0F2C, r, source as u128) {
        Some(v) => {
            write_mmx_reg64(r, v as u64);
            transition_fpu_to_mmx();
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_0F2C_mem(addr: i32, r: i32) {
    instr_0F2C(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F2C_reg(r1: i32, r2: i32) { instr_0F2C(read_xmm64s(r1), r2); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F2C(source: reg128, r: i32) -> bool {
    // cvttpd2pi mm, xmm/m128
    match sse_fp_convert(0x660F2C, r, source.bits()) {
        Some(v) => {
            write_mmx_reg64(r, v as u64);
            transition_fpu_to_mmx();
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_660F2C_mem(addr: i32, r: i32) {
    instr_660F2C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F2C_reg(r1: i32, r2: i32) { instr_660F2C(read_xmm128s(r1), r2); }

#[inline(never)]
pub unsafe fn instr_F20F2C(source: u64, r: i32) -> bool {
    // cvttsd2si r32, xmm/m64
    match sse_fp_convert(0xF20F2C, r, source as u128) {
        Some(v) => {
            write_reg32(r, v as i32);
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_F20F2C_reg(r1: i32, r2: i32) { instr_F20F2C(read_xmm64s(r1), r2); }
#[no_mangle]
pub unsafe fn instr_F20F2C_mem(addr: i32, r: i32) {
    instr_F20F2C(return_on_pagefault!(safe_read64s(addr)), r);
}

#[inline(never)]
pub unsafe fn instr_F30F2C(source: f32, r: i32) -> bool {
    // cvttss2si r32, xmm/m32
    match sse_fp_convert(0xF30F2C, r, source.to_bits() as u128) {
        Some(v) => {
            write_reg32(r, v as i32);
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_F30F2C_mem(addr: i32, r: i32) {
    instr_F30F2C(return_on_pagefault!(safe_read_f32(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_F30F2C_reg(r1: i32, r2: i32) { instr_F30F2C(read_xmm_f32(r1), r2); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F2D(source: u64, r: i32) -> bool {
    // cvtps2pi mm, xmm/m64
    match sse_fp_convert(0x0F2D, r, source as u128) {
        Some(v) => {
            write_mmx_reg64(r, v as u64);
            transition_fpu_to_mmx();
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_0F2D_reg(r1: i32, r2: i32) { instr_0F2D(read_xmm64s(r1), r2); }
#[no_mangle]
pub unsafe fn instr_0F2D_mem(addr: i32, r: i32) {
    instr_0F2D(return_on_pagefault!(safe_read64s(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F2D(source: reg128, r: i32) -> bool {
    // cvtpd2pi mm, xmm/m128
    match sse_fp_convert(0x660F2D, r, source.bits()) {
        Some(v) => {
            write_mmx_reg64(r, v as u64);
            transition_fpu_to_mmx();
            true
        },
        None => false,
    }
}
#[no_mangle]
pub unsafe fn instr_660F2D_reg(r1: i32, r2: i32) { instr_660F2D(read_xmm128s(r1), r2); }
#[no_mangle]
pub unsafe fn instr_660F2D_mem(addr: i32, r: i32) {
    instr_660F2D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[inline(never)]
pub unsafe fn instr_F20F2D(source: u64, r: i32) -> bool {
    // cvtsd2si r32, xmm/m64
    match sse_fp_convert(0xF20F2D, r, source as u128) {
        Some(v) => {
            write_reg32(r, v as i32);
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F20F2D_reg(r1: i32, r2: i32) { instr_F20F2D(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F2D_mem(addr: i32, r: i32) {
    instr_F20F2D(return_on_pagefault!(safe_read64s(addr)), r);
}
#[inline(never)]
pub unsafe fn instr_F30F2D(source: f32, r: i32) -> bool {
    // cvtss2si r32, xmm/m32
    match sse_fp_convert(0xF30F2D, r, source.to_bits() as u128) {
        Some(v) => {
            write_reg32(r, v as i32);
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F30F2D_reg(r1: i32, r2: i32) { instr_F30F2D(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F2D_mem(addr: i32, r: i32) {
    instr_F30F2D(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F2E(source: f32, r: i32) -> bool {
    // ucomiss xmm, xmm/m32
    sse_fp_compare_flags(0x0F2E, r, source.to_bits() as u128)
}
pub unsafe fn instr_0F2E_reg(r1: i32, r2: i32) { instr_0F2E(read_xmm_f32(r1), r2); }
pub unsafe fn instr_0F2E_mem(addr: i32, r: i32) {
    instr_0F2E(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F2E(source: u64, r: i32) -> bool {
    // ucomisd xmm, xmm/m64
    sse_fp_compare_flags(0x660F2E, r, source as u128)
}
pub unsafe fn instr_660F2E_reg(r1: i32, r: i32) { instr_660F2E(read_xmm64s(r1), r); }
pub unsafe fn instr_660F2E_mem(addr: i32, r: i32) {
    instr_660F2E(return_on_pagefault!(safe_read64s(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F2F(source: f32, r: i32) -> bool {
    // comiss xmm, xmm/m32
    sse_fp_compare_flags(0x0F2F, r, source.to_bits() as u128)
}
pub unsafe fn instr_0F2F_reg(r1: i32, r2: i32) { instr_0F2F(read_xmm_f32(r1), r2); }
pub unsafe fn instr_0F2F_mem(addr: i32, r: i32) {
    instr_0F2F(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F2F(source: u64, r: i32) -> bool {
    // comisd xmm, xmm/m64
    sse_fp_compare_flags(0x660F2F, r, source as u128)
}
pub unsafe fn instr_660F2F_reg(r1: i32, r: i32) { instr_660F2F(read_xmm64s(r1), r); }
pub unsafe fn instr_660F2F_mem(addr: i32, r: i32) {
    instr_660F2F(return_on_pagefault!(safe_read64s(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F30() { wrmsr_checked(); }

/// Whether WRMSR completed; fault delivery is owned by the CPU, while IR
/// callers must not commit a faulting instruction.
pub unsafe fn wrmsr_checked() -> bool {
    // wrmsr - write maschine specific register
    if 0 != *cpl {
        trigger_gp(0);
        return false;
    }

    let index = read_reg32(ECX);
    let low = read_reg32(EAX);
    let high = read_reg32(EDX);

    if index != IA32_SYSENTER_ESP {
        dbg_log!("wrmsr ecx={:x} data={:x}:{:x}", index, high, low);
    }

    // in the order of instr_0F32
    let x64 = crate::x64::state::efer() & crate::x64::state::EFER_LME != 0;
    let value = low as u32 as u64 | (high as u32 as u64) << 32;
    if (0xC0000080..=0xC0000084).contains(&(index as u32)) || x64 {
        if let Some(completed) = wrmsr_ia32e(index, value) {
            return completed;
        }
    }
    match write_msr_table(index, low, high) {
        Ok(true) => true,
        Ok(false) if !x64 => {
            if X64_TEST_CAPABILITIES {
                if let Some(completed) = wrmsr_ia32e(index, value) {
                    return completed;
                }
            }
            dbg_log!("Unknown msr: {:x}", index);
            dbg_assert!(false);
            true
        },
        Ok(false) | Err(()) => {
            trigger_gp(0);
            false
        },
    }
}

/// WRMSR of an MSR x64::system owns: whether it completed, None if it owns
/// no such MSR.
unsafe fn wrmsr_ia32e(index: i32, value: u64) -> Option<bool> {
    match crate::x64::system::write_msr(index as u32, value) {
        Ok(true) => Some(true),
        Err(fault) => {
            crate::x64::system::raise(fault);
            Some(false)
        },
        Ok(false) => None,
    }
}

/// See read_msr_table. Ok(false): no such MSR; Err: the value faults (#GP).
pub unsafe fn write_msr_table(index: i32, low: i32, high: i32) -> Result<bool, ()> {
    if let Some(result) =
        write_model_msr(index as u32, low as u32 as u64 | (high as u32 as u64) << 32)
    {
        return result.map(|()| true);
    }
    match index {
        IA32_SYSENTER_CS => *sysenter_cs = low & 0xFFFF,
        IA32_SYSENTER_EIP => *sysenter_eip = low,
        IA32_SYSENTER_ESP => *sysenter_esp = low,
        IA32_FEAT_CTL => {}, // linux 5.x
        MSR_TEST_CTRL => {}, // linux 5.x
        IA32_APIC_BASE => {
            let address = low & !(IA32_APIC_BASE_BSP | IA32_APIC_BASE_EXTD | IA32_APIC_BASE_EN);
            if high != 0
                || low & IA32_APIC_BASE_EXTD != 0
                || !(address == APIC_MEM_ADDRESS as i32 || address == 0 && !*acpi_enabled)
            {
                return Err(());
            }
            let enable = low & IA32_APIC_BASE_EN != 0;
            if *apic_enabled && !enable {
                crate::cpu::apic::software_disable();
            }
            *apic_enabled = enable;
            crate::cpu::apic::apic_set_hardware_enabled(
                crate::cpu::apic::current_core() as u32,
                enable,
            );
        },
        IA32_TIME_STAMP_COUNTER => set_tsc(low as u32, high as u32),
        IA32_BIOS_UPDT_TRIG => {}, // windows xp
        IA32_BIOS_SIGN_ID => {},
        MISC_FEATURE_ENABLES => {
            // Linux 4, see: https://patchwork.kernel.org/patch/9528279/
        },
        IA32_MISC_ENABLE => {
            // Enable Misc. Processor Features
        },
        IA32_FS_BASE | IA32_GS_BASE => {
            // These compatibility MSRs expose the 32-bit hidden segment base
            // used by kvm-unit-tests' per-CPU data. This is not the full
            // long-mode MSR contract: reject unrepresentable values before
            // changing state, identically in debug and release builds.
            if high != 0 {
                return Err(());
            }
            let segment = if index == IA32_FS_BASE { FS } else { GS };
            *segment_offsets.offset(segment as isize) = low;
            update_state_flags();
        },
        IA32_PERFEVTSEL0 | IA32_PERFEVTSEL1 => {}, // linux/9legacy
        IA32_PMC0 | IA32_PMC1 => {},               // linux
        IA32_SPEC_CTRL => {},                      // linux 5.19
        IA32_TSX_CTRL => {},                       // linux 5.19
        MSR_TSX_FORCE_ABORT => {},                 // linux 5.19
        IA32_MCU_OPT_CTRL => {},                   // linux 5.19
        MSR_AMD64_LS_CFG => {},                    // linux 5.19
        MSR_AMD64_DE_CFG => {},                    // linux 6.1
        _ => return Ok(false),
    }
    Ok(true)
}

pub unsafe fn instr_0F31() {
    // rdtsc - read timestamp counter
    if 0 == *cpl || 0 == *cr.offset(4) & CR4_TSD {
        let tsc = read_tsc();
        write_reg32(EAX, tsc as i32);
        write_reg32(EDX, (tsc >> 32) as i32);
        if false {
            dbg_log!("rdtsc  edx:eax={:x}:{:x}", read_reg32(EDX), read_reg32(EAX));
        }
    }
    else {
        trigger_gp(0);
    };
}

#[no_mangle]
pub unsafe fn instr_0F32() {
    // rdmsr - read maschine specific register
    if 0 != *cpl {
        trigger_gp(0);
        return;
    }

    let index = read_reg32(ECX);
    dbg_log!("rdmsr ecx={:x}", index);

    // x64::system owns the IA-32e MSRs, and in long mode it comes first: it
    // widens shared ones such as SYSENTER_EIP. The x64 profile advertises the
    // IA-32e MSRs in every mode (IA32_ARCH_CAPABILITIES, KERNEL_GS_BASE,
    // TSC_AUX); outside long mode they come after the table, so the shared
    // ones keep its 32-bit semantics.
    let x64 = crate::x64::state::efer() & crate::x64::state::EFER_LME != 0;
    if ((0xC0000080..=0xC0000084).contains(&(index as u32)) || x64) && rdmsr_ia32e(index) {
        return;
    }
    let (low, high) = match read_msr_table(index) {
        Some(value) => value,
        // IA-32e guests probe optional MSRs and expect #GP for absent ones
        None if x64 => {
            trigger_gp(0);
            return;
        },
        None if X64_TEST_CAPABILITIES && rdmsr_ia32e(index) => return,
        None => {
            dbg_log!("Unknown msr: {:x}", index);
            dbg_assert!(false);
            (0, 0)
        },
    };

    write_reg32(EAX, low);
    write_reg32(EDX, high);
}

/// RDMSR of an MSR x64::system owns; false if it owns no such MSR.
unsafe fn rdmsr_ia32e(index: i32) -> bool {
    match crate::x64::system::read_msr(index as u32) {
        Ok(Some(value)) => {
            write_reg32(EAX, value as i32);
            write_reg32(EDX, (value >> 32) as i32);
        },
        Err(fault) => crate::x64::system::raise(fault),
        Ok(None) => return false,
    }
    true
}

// Memory-type range registers, the page attribute table and machine-check
// banks (SDM Vol.3A, "Memory Cache Control" and "Machine-Check
// Architecture"). Memory types have no effect on
// emulation: the registers keep what the guest programs and reject reserved
// encodings. All are per core; reset disables them, INIT leaves them alone.
const MTRR_FIXED: [u32; 11] = [
    0x250, 0x258, 0x259, 0x268, 0x269, 0x26A, 0x26B, 0x26C, 0x26D, 0x26E, 0x26F,
];
/// Eight variable ranges, fixed ranges and write combining
const MTRRCAP: u64 = 8 | 1 << 8 | 1 << 10;
const MC_BANKS: u32 = 4;
/// Bank count and IA32_MCG_CTL present
const MCG_CAP: u64 = MC_BANKS as u64 | 1 << 8;
/// Physical address bits of the profile (CPUID 0x80000008)
const PHYSICAL_MASK: u64 = (1 << 36) - 1;
fn memory_type(value: u64) -> bool { matches!(value, 0 | 1 | 4 | 5 | 6) }

unsafe fn read_model_msr(index: u32) -> Option<u64> {
    Some(match index {
        0xFE => MTRRCAP,
        0x2FF => *x64_mtrr_def_type,
        0x200..=0x20F => *x64_mtrr_var.add((index - 0x200) as usize),
        0x277 => *x64_pat,
        0xDA0 => crate::cpu::xstate::read_xss()?,
        0x179 => MCG_CAP,
        0x17A => *x64_mcg_status,
        0x17B => *x64_mcg_ctl,
        _ if (0x400..0x400 + 4 * MC_BANKS).contains(&index) => {
            *x64_mc_banks.add((index - 0x400) as usize)
        },
        _ => *x64_mtrr_fixed.add(MTRR_FIXED.iter().position(|&msr| msr == index)?),
    })
}
/// None: not one of these MSRs; Some(Err): the value is reserved (#GP).
unsafe fn write_model_msr(index: u32, value: u64) -> Option<Result<(), ()>> {
    let fixed = MTRR_FIXED.iter().position(|&msr| msr == index);
    let bank = (0x400..0x400 + 4 * MC_BANKS).contains(&index);
    let valid = match index {
        0xFE | 0x179 => false, // read-only
        0x2FF => value & !0xCFF == 0 && memory_type(value & 0xFF),
        // PHYSBASEn: type and base; PHYSMASKn: valid bit and mask
        0x200..=0x20F if index & 1 == 0 => {
            value & !(PHYSICAL_MASK & !0xFFF | 0xFF) == 0 && memory_type(value & 0xFF)
        },
        0x200..=0x20F => value & !(PHYSICAL_MASK & !0xFFF | 0x800) == 0,
        0x277 => value
            .to_le_bytes()
            .iter()
            .all(|&t| memory_type(t as u64) || t == 7),
        0x17A => value & !7 == 0,
        0x17B => true,
        // IA32_XSS (with XSAVES): the value stored by write_xss
        0xDA0 => {
            return crate::cpu::xstate::write_xss(value).map(|valid| valid.then_some(()).ok_or(()))
        },
        // IA32_MCi_CTL takes any enable mask; status, address and misc only clear
        _ if bank => index & 3 == 0 || value == 0,
        _ if fixed.is_some() => value.to_le_bytes().iter().all(|&t| memory_type(t as u64)),
        _ => return None,
    };
    if !valid {
        return Some(Err(()));
    }
    match index {
        0x2FF => *x64_mtrr_def_type = value,
        0x200..=0x20F => *x64_mtrr_var.add((index - 0x200) as usize) = value,
        0x277 => *x64_pat = value,
        0x17A => *x64_mcg_status = value,
        0x17B => *x64_mcg_ctl = value,
        _ if bank => *x64_mc_banks.add((index - 0x400) as usize) = value,
        _ => *x64_mtrr_fixed.add(fixed.unwrap()) = value,
    }
    Some(Ok(()))
}

/// The model's MSRs outside the IA-32e set that x64::system owns, shared by
/// every mode. None: this model has no such MSR.
pub unsafe fn read_msr_table(index: i32) -> Option<(i32, i32)> {
    if let Some(value) = read_model_msr(index as u32) {
        return Some((value as i32, (value >> 32) as i32));
    }
    let mut low = 0;
    let mut high = 0;
    match index {
        IA32_SYSENTER_CS => low = *sysenter_cs,
        IA32_SYSENTER_EIP => low = *sysenter_eip,
        IA32_SYSENTER_ESP => low = *sysenter_esp,
        IA32_TIME_STAMP_COUNTER => {
            let tsc = read_tsc();
            low = tsc as i32;
            high = (tsc >> 32) as i32
        },
        IA32_FEAT_CTL => {}, // linux 5.x
        MSR_TEST_CTRL => {}, // linux 5.x
        IA32_PLATFORM_ID => {},
        IA32_APIC_BASE => {
            if *acpi_enabled {
                low = APIC_MEM_ADDRESS as i32;
                if *apic_enabled {
                    low |= IA32_APIC_BASE_EN
                }
                if crate::cpu::apic::current_core() == 0 {
                    low |= IA32_APIC_BASE_BSP
                }
            }
        },
        IA32_FS_BASE => low = *segment_offsets.offset(FS as isize),
        IA32_GS_BASE => low = *segment_offsets.offset(GS as isize),
        IA32_BIOS_SIGN_ID => {},
        MSR_PLATFORM_INFO => low = 1 << 8,
        MISC_FEATURE_ENABLES => {},
        IA32_MISC_ENABLE => {
            // Enable Misc. Processor Features
            low = 1 << 0; // fast string
        },
        IA32_RTIT_CTL => {}, // linux4
        MSR_SMI_COUNT => {},
        IA32_PERFEVTSEL0 | IA32_PERFEVTSEL1 => {}, // linux/9legacy
        IA32_PMC0 | IA32_PMC1 => {},               // linux
        MSR_PKG_C2_RESIDENCY => {},
        IA32_SPEC_CTRL => {},      // linux 5.19
        IA32_TSX_CTRL => {},       // linux 5.19
        MSR_TSX_FORCE_ABORT => {}, // linux 5.19
        IA32_MCU_OPT_CTRL => {},   // linux 5.19
        MSR_AMD64_LS_CFG => {},    // linux 5.19
        MSR_AMD64_DE_CFG => {},    // linux 6.1
        _ => return None,
    }
    Some((low, high))
}
#[no_mangle]
pub unsafe fn instr_0F33() {
    // rdpmc
    undefined_instruction();
}
#[no_mangle]
pub unsafe fn instr_0F34() {
    // sysenter
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Err(fault) =
            crate::x64::system::fast_call(0x0F34, false, crate::x64::state::read_rip())
        {
            crate::x64::system::raise(fault);
        }
        return;
    }
    let seg = *sysenter_cs & 0xFFFC;
    if !*protected_mode || seg == 0 {
        trigger_gp(0);
        return;
    }
    else {
        *flags &= !FLAG_VM & !FLAG_INTERRUPT;
        *instruction_pointer = *sysenter_eip;
        write_reg32(ESP, *sysenter_esp);
        *sreg.offset(CS as isize) = seg as u16;
        *segment_is_null.offset(CS as isize) = false;
        *segment_limits.offset(CS as isize) = -1i32 as u32;
        *segment_offsets.offset(CS as isize) = 0;
        *segment_access_bytes.offset(CS as isize) = 0x80 | (0 << 5) | 0x10 | 0x08 | 0x02; // P dpl0 S E RW
        update_cs_size(true);
        *cpl = 0;
        cpl_changed();
        *sreg.offset(SS as isize) = (seg + 8) as u16;
        *segment_is_null.offset(SS as isize) = false;
        *segment_limits.offset(SS as isize) = -1i32 as u32;
        *segment_offsets.offset(SS as isize) = 0;
        *segment_access_bytes.offset(SS as isize) = 0x80 | (0 << 5) | 0x10 | 0x02; // P dpl0 S RW
        *stack_size_32 = true;
        update_state_flags();
        return;
    };
}
#[no_mangle]
pub unsafe fn instr_0F35() {
    // sysexit
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        if let Err(fault) =
            crate::x64::system::fast_call(0x0F35, false, crate::x64::state::read_rip())
        {
            crate::x64::system::raise(fault);
        }
        return;
    }
    let seg = *sysenter_cs & 0xFFFC;
    if !*protected_mode || 0 != *cpl || seg == 0 {
        trigger_gp(0);
        return;
    }
    else {
        *instruction_pointer = read_reg32(EDX);
        write_reg32(ESP, read_reg32(ECX));
        *sreg.offset(CS as isize) = (seg + 16 | 3) as u16;
        *segment_is_null.offset(CS as isize) = false;
        *segment_limits.offset(CS as isize) = -1i32 as u32;
        *segment_offsets.offset(CS as isize) = 0;
        *segment_access_bytes.offset(CS as isize) = 0x80 | (3 << 5) | 0x10 | 0x08 | 0x02; // P dpl3 S E RW
        update_cs_size(true);
        *cpl = 3;
        cpl_changed();
        *sreg.offset(SS as isize) = (seg + 24 | 3) as u16;
        *segment_is_null.offset(SS as isize) = false;
        *segment_limits.offset(SS as isize) = -1i32 as u32;
        *segment_offsets.offset(SS as isize) = 0;
        *segment_access_bytes.offset(SS as isize) = 0x80 | (3 << 5) | 0x10 | 0x02; // P dpl3 S RW
        *stack_size_32 = true;
        update_state_flags();
        return;
    };
}
#[no_mangle]
pub unsafe fn instr_0F36() { undefined_instruction(); }
#[no_mangle]
pub unsafe fn instr_0F37() {
    // getsec
    undefined_instruction();
}
/// The three-byte opcode maps (gen/x86_table.js, docs/simd-xsave-plan.md)
#[no_mangle]
pub unsafe fn instr_0F38() {
    let opcode = return_on_pagefault!(read_imm8());
    crate::gen::interpreter0f38::run(opcode as u32 | (is_osize_32() as u32) << 8);
}
#[no_mangle]
pub unsafe fn instr_0F3A() {
    let opcode = return_on_pagefault!(read_imm8());
    crate::gen::interpreter0f3a::run(opcode as u32 | (is_osize_32() as u32) << 8);
}
// (undefined)
#[no_mangle]
pub unsafe fn instr_0F39() { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F3B() { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F3C() { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F3D() { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F3E() { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F3F() { trigger_ud(); }

pub unsafe fn instr16_0F40_mem(addr: i32, r: i32) {
    cmovcc16(test_o(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F40_reg(r1: i32, r: i32) { cmovcc16(test_o(), read_reg16(r1), r); }
pub unsafe fn instr32_0F40_mem(addr: i32, r: i32) {
    cmovcc32(test_o(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F40_reg(r1: i32, r: i32) { cmovcc32(test_o(), read_reg32(r1), r); }
pub unsafe fn instr16_0F41_mem(addr: i32, r: i32) {
    cmovcc16(!test_o(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F41_reg(r1: i32, r: i32) { cmovcc16(!test_o(), read_reg16(r1), r); }
pub unsafe fn instr32_0F41_mem(addr: i32, r: i32) {
    cmovcc32(!test_o(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F41_reg(r1: i32, r: i32) { cmovcc32(!test_o(), read_reg32(r1), r); }
pub unsafe fn instr16_0F42_mem(addr: i32, r: i32) {
    cmovcc16(test_b(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F42_reg(r1: i32, r: i32) { cmovcc16(test_b(), read_reg16(r1), r); }
pub unsafe fn instr32_0F42_mem(addr: i32, r: i32) {
    cmovcc32(test_b(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F42_reg(r1: i32, r: i32) { cmovcc32(test_b(), read_reg32(r1), r); }
pub unsafe fn instr16_0F43_mem(addr: i32, r: i32) {
    cmovcc16(!test_b(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F43_reg(r1: i32, r: i32) { cmovcc16(!test_b(), read_reg16(r1), r); }
pub unsafe fn instr32_0F43_mem(addr: i32, r: i32) {
    cmovcc32(!test_b(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F43_reg(r1: i32, r: i32) { cmovcc32(!test_b(), read_reg32(r1), r); }
pub unsafe fn instr16_0F44_mem(addr: i32, r: i32) {
    cmovcc16(test_z(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F44_reg(r1: i32, r: i32) { cmovcc16(test_z(), read_reg16(r1), r); }
pub unsafe fn instr32_0F44_mem(addr: i32, r: i32) {
    cmovcc32(test_z(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F44_reg(r1: i32, r: i32) { cmovcc32(test_z(), read_reg32(r1), r); }
pub unsafe fn instr16_0F45_mem(addr: i32, r: i32) {
    cmovcc16(!test_z(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F45_reg(r1: i32, r: i32) { cmovcc16(!test_z(), read_reg16(r1), r); }
pub unsafe fn instr32_0F45_mem(addr: i32, r: i32) {
    cmovcc32(!test_z(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F45_reg(r1: i32, r: i32) { cmovcc32(!test_z(), read_reg32(r1), r); }
pub unsafe fn instr16_0F46_mem(addr: i32, r: i32) {
    cmovcc16(test_be(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F46_reg(r1: i32, r: i32) { cmovcc16(test_be(), read_reg16(r1), r); }
pub unsafe fn instr32_0F46_mem(addr: i32, r: i32) {
    cmovcc32(test_be(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F46_reg(r1: i32, r: i32) { cmovcc32(test_be(), read_reg32(r1), r); }
pub unsafe fn instr16_0F47_mem(addr: i32, r: i32) {
    cmovcc16(!test_be(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F47_reg(r1: i32, r: i32) { cmovcc16(!test_be(), read_reg16(r1), r); }
pub unsafe fn instr32_0F47_mem(addr: i32, r: i32) {
    cmovcc32(!test_be(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F47_reg(r1: i32, r: i32) { cmovcc32(!test_be(), read_reg32(r1), r); }
pub unsafe fn instr16_0F48_mem(addr: i32, r: i32) {
    cmovcc16(test_s(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F48_reg(r1: i32, r: i32) { cmovcc16(test_s(), read_reg16(r1), r); }
pub unsafe fn instr32_0F48_mem(addr: i32, r: i32) {
    cmovcc32(test_s(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F48_reg(r1: i32, r: i32) { cmovcc32(test_s(), read_reg32(r1), r); }
pub unsafe fn instr16_0F49_mem(addr: i32, r: i32) {
    cmovcc16(!test_s(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F49_reg(r1: i32, r: i32) { cmovcc16(!test_s(), read_reg16(r1), r); }
pub unsafe fn instr32_0F49_mem(addr: i32, r: i32) {
    cmovcc32(!test_s(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F49_reg(r1: i32, r: i32) { cmovcc32(!test_s(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4A_mem(addr: i32, r: i32) {
    cmovcc16(test_p(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4A_reg(r1: i32, r: i32) { cmovcc16(test_p(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4A_mem(addr: i32, r: i32) {
    cmovcc32(test_p(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4A_reg(r1: i32, r: i32) { cmovcc32(test_p(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4B_mem(addr: i32, r: i32) {
    cmovcc16(!test_p(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4B_reg(r1: i32, r: i32) { cmovcc16(!test_p(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4B_mem(addr: i32, r: i32) {
    cmovcc32(!test_p(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4B_reg(r1: i32, r: i32) { cmovcc32(!test_p(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4C_mem(addr: i32, r: i32) {
    cmovcc16(test_l(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4C_reg(r1: i32, r: i32) { cmovcc16(test_l(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4C_mem(addr: i32, r: i32) {
    cmovcc32(test_l(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4C_reg(r1: i32, r: i32) { cmovcc32(test_l(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4D_mem(addr: i32, r: i32) {
    cmovcc16(!test_l(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4D_reg(r1: i32, r: i32) { cmovcc16(!test_l(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4D_mem(addr: i32, r: i32) {
    cmovcc32(!test_l(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4D_reg(r1: i32, r: i32) { cmovcc32(!test_l(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4E_mem(addr: i32, r: i32) {
    cmovcc16(test_le(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4E_reg(r1: i32, r: i32) { cmovcc16(test_le(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4E_mem(addr: i32, r: i32) {
    cmovcc32(test_le(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4E_reg(r1: i32, r: i32) { cmovcc32(test_le(), read_reg32(r1), r); }
pub unsafe fn instr16_0F4F_mem(addr: i32, r: i32) {
    cmovcc16(!test_le(), return_on_pagefault!(safe_read16(addr)), r);
}
pub unsafe fn instr16_0F4F_reg(r1: i32, r: i32) { cmovcc16(!test_le(), read_reg16(r1), r); }
pub unsafe fn instr32_0F4F_mem(addr: i32, r: i32) {
    cmovcc32(!test_le(), return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr32_0F4F_reg(r1: i32, r: i32) { cmovcc32(!test_le(), read_reg32(r1), r); }

#[no_mangle]
pub unsafe fn instr_0F50_reg(r1: i32, r2: i32) {
    // movmskps r, xmm
    let source = read_xmm128s(r1);
    let data = (source.u32[0] >> 31
        | source.u32[1] >> 31 << 1
        | source.u32[2] >> 31 << 2
        | source.u32[3] >> 31 << 3) as i32;
    write_reg32(r2, data);
}
#[no_mangle]
pub unsafe fn instr_0F50_mem(_addr: i32, _r1: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F50_reg(r1: i32, r2: i32) {
    // movmskpd r, xmm
    let source = read_xmm128s(r1);
    let data = (source.u32[1] >> 31 | source.u32[3] >> 31 << 1) as i32;
    write_reg32(r2, data);
}
#[no_mangle]
pub unsafe fn instr_660F50_mem(_addr: i32, _r1: i32) { trigger_ud(); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F51(source: reg128, r: i32) -> bool {
    // sqrtps xmm, xmm/m128
    sse_fp_arithmetic(0x0F51, r, source.bits(), 0)
}
pub unsafe fn instr_0F51_reg(r1: i32, r2: i32) { instr_0F51(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F51_mem(addr: i32, r: i32) {
    instr_0F51(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F51(source: reg128, r: i32) -> bool {
    // sqrtpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F51, r, source.bits(), 0)
}
pub unsafe fn instr_660F51_reg(r1: i32, r2: i32) { instr_660F51(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F51_mem(addr: i32, r: i32) {
    instr_660F51(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F51(source: u64, r: i32) -> bool {
    // sqrtsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F51, r, source as u128, 0)
}
pub unsafe fn instr_F20F51_reg(r1: i32, r2: i32) { instr_F20F51(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F51_mem(addr: i32, r: i32) {
    instr_F20F51(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F51(source: f32, r: i32) -> bool {
    // sqrtss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F51, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F51_reg(r1: i32, r2: i32) { instr_F30F51(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F51_mem(addr: i32, r: i32) {
    instr_F30F51(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F52(source: reg128, r: i32) -> bool {
    // rsqrtps xmm, xmm/m128
    sse_fp_reciprocal(0x0F52, r, source.bits())
}
pub unsafe fn instr_0F52_reg(r1: i32, r2: i32) { instr_0F52(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F52_mem(addr: i32, r: i32) {
    instr_0F52(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F52(source: f32, r: i32) -> bool {
    // rsqrtss xmm, xmm/m32
    sse_fp_reciprocal(0xF30F52, r, source.to_bits() as u128)
}
pub unsafe fn instr_F30F52_reg(r1: i32, r2: i32) { instr_F30F52(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F52_mem(addr: i32, r: i32) {
    instr_F30F52(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F53(source: reg128, r: i32) -> bool {
    // rcpps xmm, xmm/m128
    sse_fp_reciprocal(0x0F53, r, source.bits())
}
pub unsafe fn instr_0F53_reg(r1: i32, r2: i32) { instr_0F53(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F53_mem(addr: i32, r: i32) {
    instr_0F53(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F53(source: f32, r: i32) -> bool {
    // rcpss xmm, xmm/m32
    sse_fp_reciprocal(0xF30F53, r, source.to_bits() as u128)
}
pub unsafe fn instr_F30F53_reg(r1: i32, r2: i32) { instr_F30F53(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F53_mem(addr: i32, r: i32) {
    instr_F30F53(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F54(source: reg128, r: i32) {
    // andps xmm, xmm/mem128
    pand_r128(source, r);
}
pub unsafe fn instr_0F54_reg(r1: i32, r2: i32) { instr_0F54(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F54_mem(addr: i32, r: i32) {
    instr_0F54(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F54(source: reg128, r: i32) {
    // andpd xmm, xmm/mem128
    pand_r128(source, r);
}
pub unsafe fn instr_660F54_reg(r1: i32, r2: i32) { instr_660F54(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F54_mem(addr: i32, r: i32) {
    instr_660F54(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F55(source: reg128, r: i32) {
    // andnps xmm, xmm/mem128
    pandn_r128(source, r);
}
pub unsafe fn instr_0F55_reg(r1: i32, r2: i32) { instr_0F55(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F55_mem(addr: i32, r: i32) {
    instr_0F55(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F55(source: reg128, r: i32) {
    // andnpd xmm, xmm/mem128
    pandn_r128(source, r);
}
pub unsafe fn instr_660F55_reg(r1: i32, r2: i32) { instr_660F55(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F55_mem(addr: i32, r: i32) {
    instr_660F55(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F56(source: reg128, r: i32) {
    // orps xmm, xmm/mem128
    por_r128(source, r);
}
pub unsafe fn instr_0F56_reg(r1: i32, r2: i32) { instr_0F56(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F56_mem(addr: i32, r: i32) {
    instr_0F56(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F56(source: reg128, r: i32) {
    // orpd xmm, xmm/mem128
    por_r128(source, r);
}
pub unsafe fn instr_660F56_reg(r1: i32, r2: i32) { instr_660F56(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F56_mem(addr: i32, r: i32) {
    instr_660F56(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F57(source: reg128, r: i32) {
    // xorps xmm, xmm/mem128
    pxor_r128(source, r);
}
pub unsafe fn instr_0F57_reg(r1: i32, r2: i32) { instr_0F57(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F57_mem(addr: i32, r: i32) {
    instr_0F57(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F57(source: reg128, r: i32) {
    // xorpd xmm, xmm/mem128
    pxor_r128(source, r);
}
pub unsafe fn instr_660F57_reg(r1: i32, r2: i32) { instr_660F57(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F57_mem(addr: i32, r: i32) {
    instr_660F57(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F58(source: reg128, r: i32) -> bool {
    // addps xmm, xmm/m128
    sse_fp_arithmetic(0x0F58, r, source.bits(), 0)
}

pub unsafe fn instr_0F58_reg(r1: i32, r2: i32) { instr_0F58(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F58_mem(addr: i32, r: i32) {
    instr_0F58(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F58(source: reg128, r: i32) -> bool {
    // addpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F58, r, source.bits(), 0)
}

pub unsafe fn instr_660F58_reg(r1: i32, r2: i32) { instr_660F58(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F58_mem(addr: i32, r: i32) {
    instr_660F58(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F58(source: u64, r: i32) -> bool {
    // addsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F58, r, source as u128, 0)
}
pub unsafe fn instr_F20F58_reg(r1: i32, r2: i32) { instr_F20F58(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F58_mem(addr: i32, r: i32) {
    instr_F20F58(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F58(source: f32, r: i32) -> bool {
    // addss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F58, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F58_reg(r1: i32, r2: i32) { instr_F30F58(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F58_mem(addr: i32, r: i32) {
    instr_F30F58(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F59(source: reg128, r: i32) -> bool {
    // mulps xmm, xmm/m128
    sse_fp_arithmetic(0x0F59, r, source.bits(), 0)
}

pub unsafe fn instr_0F59_reg(r1: i32, r2: i32) { instr_0F59(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F59_mem(addr: i32, r: i32) {
    instr_0F59(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F59(source: reg128, r: i32) -> bool {
    // mulpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F59, r, source.bits(), 0)
}

pub unsafe fn instr_660F59_reg(r1: i32, r2: i32) { instr_660F59(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F59_mem(addr: i32, r: i32) {
    instr_660F59(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F59(source: u64, r: i32) -> bool {
    // mulsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F59, r, source as u128, 0)
}
pub unsafe fn instr_F20F59_reg(r1: i32, r2: i32) { instr_F20F59(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F59_mem(addr: i32, r: i32) {
    instr_F20F59(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F59(source: f32, r: i32) -> bool {
    // mulss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F59, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F59_reg(r1: i32, r2: i32) { instr_F30F59(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F59_mem(addr: i32, r: i32) {
    instr_F30F59(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5A(source: u64, r: i32) -> bool {
    // cvtps2pd xmm, xmm/m64
    match sse_fp_convert(0x0F5A, r, source as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_0F5A_reg(r1: i32, r2: i32) { instr_0F5A(read_xmm64s(r1), r2); }
pub unsafe fn instr_0F5A_mem(addr: i32, r: i32) {
    instr_0F5A(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5A(source: reg128, r: i32) -> bool {
    // cvtpd2ps xmm, xmm/m128
    match sse_fp_convert(0x660F5A, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_660F5A_reg(r1: i32, r2: i32) { instr_660F5A(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5A_mem(addr: i32, r: i32) {
    instr_660F5A(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F5A(source: u64, r: i32) -> bool {
    // cvtsd2ss xmm, xmm/m64
    match sse_fp_convert(0xF20F5A, r, source as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F20F5A_reg(r1: i32, r2: i32) { instr_F20F5A(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F5A_mem(addr: i32, r: i32) {
    instr_F20F5A(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5A(source: f32, r: i32) -> bool {
    // cvtss2sd xmm, xmm/m32
    match sse_fp_convert(0xF30F5A, r, source.to_bits() as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F30F5A_reg(r1: i32, r2: i32) { instr_F30F5A(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F5A_mem(addr: i32, r: i32) {
    instr_F30F5A(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5B(source: reg128, r: i32) -> bool {
    // cvtdq2ps xmm, xmm/m128
    match sse_fp_convert(0x0F5B, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_0F5B_reg(r1: i32, r2: i32) { instr_0F5B(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F5B_mem(addr: i32, r: i32) {
    instr_0F5B(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5B(source: reg128, r: i32) -> bool {
    // cvtps2dq xmm, xmm/m128
    match sse_fp_convert(0x660F5B, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_660F5B_reg(r1: i32, r2: i32) { instr_660F5B(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5B_mem(addr: i32, r: i32) {
    instr_660F5B(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5B(source: reg128, r: i32) -> bool {
    // cvttps2dq xmm, xmm/m128
    match sse_fp_convert(0xF30F5B, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F30F5B_reg(r1: i32, r2: i32) { instr_F30F5B(read_xmm128s(r1), r2); }
pub unsafe fn instr_F30F5B_mem(addr: i32, r: i32) {
    instr_F30F5B(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5C(source: reg128, r: i32) -> bool {
    // subps xmm, xmm/m128
    sse_fp_arithmetic(0x0F5C, r, source.bits(), 0)
}

pub unsafe fn instr_0F5C_reg(r1: i32, r2: i32) { instr_0F5C(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F5C_mem(addr: i32, r: i32) {
    instr_0F5C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5C(source: reg128, r: i32) -> bool {
    // subpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F5C, r, source.bits(), 0)
}

pub unsafe fn instr_660F5C_reg(r1: i32, r2: i32) { instr_660F5C(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5C_mem(addr: i32, r: i32) {
    instr_660F5C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F5C(source: u64, r: i32) -> bool {
    // subsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F5C, r, source as u128, 0)
}
pub unsafe fn instr_F20F5C_reg(r1: i32, r2: i32) { instr_F20F5C(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F5C_mem(addr: i32, r: i32) {
    instr_F20F5C(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5C(source: f32, r: i32) -> bool {
    // subss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F5C, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F5C_reg(r1: i32, r2: i32) { instr_F30F5C(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F5C_mem(addr: i32, r: i32) {
    instr_F30F5C(return_on_pagefault!(safe_read_f32(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5D(source: reg128, r: i32) -> bool {
    // minps xmm, xmm/m128
    sse_fp_arithmetic(0x0F5D, r, source.bits(), 0)
}
pub unsafe fn instr_0F5D_reg(r1: i32, r2: i32) { instr_0F5D(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F5D_mem(addr: i32, r: i32) {
    instr_0F5D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5D(source: reg128, r: i32) -> bool {
    // minpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F5D, r, source.bits(), 0)
}
pub unsafe fn instr_660F5D_reg(r1: i32, r2: i32) { instr_660F5D(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5D_mem(addr: i32, r: i32) {
    instr_660F5D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F5D(source: u64, r: i32) -> bool {
    // minsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F5D, r, source as u128, 0)
}
pub unsafe fn instr_F20F5D_reg(r1: i32, r2: i32) { instr_F20F5D(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F5D_mem(addr: i32, r: i32) {
    instr_F20F5D(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5D(source: f32, r: i32) -> bool {
    // minss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F5D, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F5D_reg(r1: i32, r2: i32) { instr_F30F5D(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F5D_mem(addr: i32, r: i32) {
    instr_F30F5D(return_on_pagefault!(safe_read_f32(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5E(source: reg128, r: i32) -> bool {
    // divps xmm, xmm/m128
    sse_fp_arithmetic(0x0F5E, r, source.bits(), 0)
}

pub unsafe fn instr_0F5E_reg(r1: i32, r2: i32) { instr_0F5E(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F5E_mem(addr: i32, r: i32) {
    instr_0F5E(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5E(source: reg128, r: i32) -> bool {
    // divpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F5E, r, source.bits(), 0)
}

pub unsafe fn instr_660F5E_reg(r1: i32, r2: i32) { instr_660F5E(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5E_mem(addr: i32, r: i32) {
    instr_660F5E(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F5E(source: u64, r: i32) -> bool {
    // divsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F5E, r, source as u128, 0)
}
pub unsafe fn instr_F20F5E_reg(r1: i32, r2: i32) { instr_F20F5E(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F5E_mem(addr: i32, r: i32) {
    instr_F20F5E(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5E(source: f32, r: i32) -> bool {
    // divss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F5E, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F5E_reg(r1: i32, r2: i32) { instr_F30F5E(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F5E_mem(addr: i32, r: i32) {
    instr_F30F5E(return_on_pagefault!(safe_read_f32(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0F5F(source: reg128, r: i32) -> bool {
    // maxps xmm, xmm/m128
    sse_fp_arithmetic(0x0F5F, r, source.bits(), 0)
}
pub unsafe fn instr_0F5F_reg(r1: i32, r2: i32) { instr_0F5F(read_xmm128s(r1), r2); }
pub unsafe fn instr_0F5F_mem(addr: i32, r: i32) {
    instr_0F5F(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F5F(source: reg128, r: i32) -> bool {
    // maxpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F5F, r, source.bits(), 0)
}
pub unsafe fn instr_660F5F_reg(r1: i32, r2: i32) { instr_660F5F(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F5F_mem(addr: i32, r: i32) {
    instr_660F5F(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F5F(source: u64, r: i32) -> bool {
    // maxsd xmm, xmm/m64
    sse_fp_arithmetic(0xF20F5F, r, source as u128, 0)
}
pub unsafe fn instr_F20F5F_reg(r1: i32, r2: i32) { instr_F20F5F(read_xmm64s(r1), r2); }
pub unsafe fn instr_F20F5F_mem(addr: i32, r: i32) {
    instr_F20F5F(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30F5F(source: f32, r: i32) -> bool {
    // maxss xmm, xmm/m32
    sse_fp_arithmetic(0xF30F5F, r, source.to_bits() as u128, 0)
}
pub unsafe fn instr_F30F5F_reg(r1: i32, r2: i32) { instr_F30F5F(read_xmm_f32(r1), r2); }
pub unsafe fn instr_F30F5F_mem(addr: i32, r: i32) {
    instr_F30F5F(return_on_pagefault!(safe_read_f32(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F60(source: i32, r: i32) {
    // punpcklbw mm, mm/m32
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 4] = i32::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..4 {
        result[2 * i + 0] = destination[i];
        result[2 * i + 1] = source[i];
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F60_reg(r1: i32, r2: i32) { instr_0F60(read_mmx32s(r1), r2); }
pub unsafe fn instr_0F60_mem(addr: i32, r: i32) {
    instr_0F60(return_on_pagefault!(safe_read32s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F60(source: reg128, r: i32) {
    // punpcklbw xmm, xmm/m128
    let destination: [u8; 8] = u64::to_le_bytes(read_xmm64s(r));
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u8[2 * i + 0] = destination[i];
        result.u8[2 * i + 1] = source.u8[i];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F60_reg(r1: i32, r2: i32) { instr_660F60(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F60_mem(addr: i32, r: i32) {
    instr_660F60(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F61(source: i32, r: i32) {
    // punpcklwd mm, mm/m32
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 2] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..2 {
        result[2 * i + 0] = destination[i];
        result[2 * i + 1] = source[i];
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F61_reg(r1: i32, r2: i32) { instr_0F61(read_mmx32s(r1), r2); }
pub unsafe fn instr_0F61_mem(addr: i32, r: i32) {
    instr_0F61(return_on_pagefault!(safe_read32s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F61(source: reg128, r: i32) {
    // punpcklwd xmm, xmm/m128
    let destination: [u16; 4] = std::mem::transmute(read_xmm64s(r));
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..4 {
        result.u16[2 * i + 0] = destination[i];
        result.u16[2 * i + 1] = source.u16[i];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F61_reg(r1: i32, r2: i32) { instr_660F61(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F61_mem(addr: i32, r: i32) {
    instr_660F61(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F62(source: i32, r: i32) {
    // punpckldq mm, mm/m32
    let destination = read_mmx64s(r);
    write_mmx_reg64(
        r,
        (destination & 0xFFFF_FFFF) | (source as u32 as u64) << 32,
    );
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F62_reg(r1: i32, r2: i32) { instr_0F62(read_mmx32s(r1), r2); }
pub unsafe fn instr_0F62_mem(addr: i32, r: i32) {
    instr_0F62(return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr_660F62(source: reg128, r: i32) {
    // punpckldq xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[0] as i32,
        source.u32[0] as i32,
        destination.u32[1] as i32,
        source.u32[1] as i32,
    );
}
pub unsafe fn instr_660F62_reg(r1: i32, r2: i32) { instr_660F62(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F62_mem(addr: i32, r: i32) {
    instr_660F62(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F63(source: u64, r: i32) {
    // packsswb mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result: [u8; 8] = [0; 8];
    for i in 0..4 {
        result[i + 0] = saturate_sw_to_sb(destination[i] as i32);
        result[i + 4] = saturate_sw_to_sb(source[i] as i32);
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F63_reg(r1: i32, r2: i32) { instr_0F63(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F63_mem(addr: i32, r: i32) {
    instr_0F63(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F63(source: reg128, r: i32) {
    // packsswb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u8[i + 0] = saturate_sw_to_sb(destination.u16[i] as i32);
        result.u8[i + 8] = saturate_sw_to_sb(source.u16[i] as i32);
    }
    write_xmm_reg128(r, result)
}
pub unsafe fn instr_660F63_reg(r1: i32, r2: i32) { instr_660F63(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F63_mem(addr: i32, r: i32) {
    instr_660F63(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F64(source: u64, r: i32) {
    // pcmpgtb mm, mm/m64
    let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r));
    let source: [i8; 8] = std::mem::transmute(source);
    let mut result: [u8; 8] = [0; 8];
    for i in 0..8 {
        result[i] = if destination[i] > source[i] { 255 } else { 0 };
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F64_reg(r1: i32, r2: i32) { instr_0F64(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F64_mem(addr: i32, r: i32) {
    instr_0F64(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F64(source: reg128, r: i32) {
    // pcmpgtb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = if destination.i8[i] as i32 > source.i8[i] as i32 { 255 } else { 0 };
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F64_reg(r1: i32, r2: i32) { instr_660F64(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F64_mem(addr: i32, r: i32) {
    instr_660F64(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F65(source: u64, r: i32) {
    // pcmpgtw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result: [u16; 4] = [0; 4];
    for i in 0..4 {
        result[i] = if destination[i] > source[i] { 0xFFFF } else { 0 }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F65_reg(r1: i32, r2: i32) { instr_0F65(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F65_mem(addr: i32, r: i32) {
    instr_0F65(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F65(source: reg128, r: i32) {
    // pcmpgtw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = if destination.i16[i] > source.i16[i] { 0xFFFF } else { 0 };
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F65_reg(r1: i32, r2: i32) { instr_660F65(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F65_mem(addr: i32, r: i32) {
    instr_660F65(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F66(source: u64, r: i32) {
    // pcmpgtd mm, mm/m64
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let source: [i32; 2] = std::mem::transmute(source);
    let mut result = [0; 2];
    for i in 0..2 {
        result[i] = if destination[i] > source[i] { -1 } else { 0 }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F66_reg(r1: i32, r2: i32) { instr_0F66(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F66_mem(addr: i32, r: i32) {
    instr_0F66(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F66(source: reg128, r: i32) {
    // pcmpgtd xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        if destination.i32[0] > source.i32[0] { -1 } else { 0 },
        if destination.i32[1] > source.i32[1] { -1 } else { 0 },
        if destination.i32[2] > source.i32[2] { -1 } else { 0 },
        if destination.i32[3] > source.i32[3] { -1 } else { 0 },
    );
}
pub unsafe fn instr_660F66_reg(r1: i32, r2: i32) { instr_660F66(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F66_mem(addr: i32, r: i32) {
    instr_660F66(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F67(source: u64, r: i32) {
    // packuswb mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 8];
    for i in 0..4 {
        result[i + 0] = saturate_sw_to_ub(destination[i]);
        result[i + 4] = saturate_sw_to_ub(source[i]);
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F67_reg(r1: i32, r2: i32) { instr_0F67(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F67_mem(addr: i32, r: i32) {
    instr_0F67(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F67(source: reg128, r: i32) {
    // packuswb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u8[i + 0] = saturate_sw_to_ub(destination.u16[i]);
        result.u8[i + 8] = saturate_sw_to_ub(source.u16[i]);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F67_reg(r1: i32, r2: i32) { instr_660F67(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F67_mem(addr: i32, r: i32) {
    instr_660F67(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F68(source: u64, r: i32) {
    // punpckhbw mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result: [u8; 8] = [0; 8];
    for i in 0..4 {
        result[2 * i + 0] = destination[i + 4];
        result[2 * i + 1] = source[i + 4];
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F68_reg(r1: i32, r2: i32) { instr_0F68(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F68_mem(addr: i32, r: i32) {
    instr_0F68(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F68(source: reg128, r: i32) {
    // punpckhbw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u8[2 * i + 0] = destination.u8[i + 8];
        result.u8[2 * i + 1] = source.u8[i + 8];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F68_reg(r1: i32, r2: i32) { instr_660F68(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F68_mem(addr: i32, r: i32) {
    instr_660F68(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F69(source: u64, r: i32) {
    // punpckhwd mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let result = [destination[2], source[2], destination[3], source[3]];
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F69_reg(r1: i32, r2: i32) { instr_0F69(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F69_mem(addr: i32, r: i32) {
    instr_0F69(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F69(source: reg128, r: i32) {
    // punpckhwd xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..4 {
        result.u16[2 * i + 0] = destination.u16[i + 4];
        result.u16[2 * i + 1] = source.u16[i + 4];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F69_reg(r1: i32, r2: i32) { instr_660F69(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F69_mem(addr: i32, r: i32) {
    instr_660F69(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F6A(source: u64, r: i32) {
    // punpckhdq mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, (destination >> 32) | (source >> 32 << 32));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F6A_reg(r1: i32, r2: i32) { instr_0F6A(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F6A_mem(addr: i32, r: i32) {
    instr_0F6A(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F6A(source: reg128, r: i32) {
    // punpckhdq xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[2] as i32,
        source.u32[2] as i32,
        destination.u32[3] as i32,
        source.u32[3] as i32,
    );
}
pub unsafe fn instr_660F6A_reg(r1: i32, r2: i32) { instr_660F6A(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F6A_mem(addr: i32, r: i32) {
    instr_660F6A(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F6B(source: u64, r: i32) {
    // packssdw mm, mm/m64
    let destination: [u32; 2] = std::mem::transmute(read_mmx64s(r));
    let source: [u32; 2] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..2 {
        result[i + 0] = saturate_sd_to_sw(destination[i]);
        result[i + 2] = saturate_sd_to_sw(source[i]);
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F6B_reg(r1: i32, r2: i32) { instr_0F6B(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F6B_mem(addr: i32, r: i32) {
    instr_0F6B(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F6B(source: reg128, r: i32) {
    // packssdw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..4 {
        result.u16[i + 0] = saturate_sd_to_sw(destination.u32[i]);
        result.u16[i + 4] = saturate_sd_to_sw(source.u32[i]);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F6B_reg(r1: i32, r2: i32) { instr_660F6B(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F6B_mem(addr: i32, r: i32) {
    instr_660F6B(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F6C_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F6C_reg(_r1: i32, _r2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F6C(source: reg128, r: i32) {
    // punpcklqdq xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[0] as i32,
        destination.u32[1] as i32,
        source.u32[0] as i32,
        source.u32[1] as i32,
    );
}
pub unsafe fn instr_660F6C_reg(r1: i32, r2: i32) { instr_660F6C(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F6C_mem(addr: i32, r: i32) {
    instr_660F6C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F6D_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F6D_reg(_r1: i32, _r2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F6D(source: reg128, r: i32) {
    // punpckhqdq xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[2] as i32,
        destination.u32[3] as i32,
        source.u32[2] as i32,
        source.u32[3] as i32,
    );
}
pub unsafe fn instr_660F6D_reg(r1: i32, r2: i32) { instr_660F6D(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F6D_mem(addr: i32, r: i32) {
    instr_660F6D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F6E(source: i32, r: i32) {
    // movd mm, r/m32
    write_mmx_reg64(r, source as u32 as u64);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F6E_reg(r1: i32, r2: i32) { instr_0F6E(read_reg32(r1), r2); }
pub unsafe fn instr_0F6E_mem(addr: i32, r: i32) {
    instr_0F6E(return_on_pagefault!(safe_read32s(addr)), r);
}
pub unsafe fn instr_660F6E(source: i32, r: i32) {
    // movd mm, r/m32
    write_xmm128(r, source, 0, 0, 0);
}
pub unsafe fn instr_660F6E_reg(r1: i32, r2: i32) { instr_660F6E(read_reg32(r1), r2); }
pub unsafe fn instr_660F6E_mem(addr: i32, r: i32) {
    instr_660F6E(return_on_pagefault!(safe_read32s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F6F(source: u64, r: i32) {
    // movq mm, mm/m64
    write_mmx_reg64(r, source);
    transition_fpu_to_mmx();
}
#[no_mangle]
pub unsafe fn instr_0F6F_reg(r1: i32, r2: i32) { instr_0F6F(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F6F_mem(addr: i32, r: i32) {
    instr_0F6F(return_on_pagefault!(safe_read64s(addr)), r);
}
pub unsafe fn instr_660F6F(source: reg128, r: i32) {
    // movdqa xmm, xmm/mem128
    mov_rm_r128(source, r);
}
pub unsafe fn instr_660F6F_reg(r1: i32, r2: i32) { instr_660F6F(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F6F_mem(addr: i32, r: i32) {
    instr_660F6F(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_F30F6F(source: reg128, r: i32) {
    // movdqu xmm, xmm/m128
    mov_rm_r128(source, r);
}
pub unsafe fn instr_F30F6F_reg(r1: i32, r2: i32) { instr_F30F6F(read_xmm128s(r1), r2); }
pub unsafe fn instr_F30F6F_mem(addr: i32, r: i32) {
    instr_F30F6F(return_on_pagefault!(safe_read128s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F70(source: u64, r: i32, imm8: i32) {
    // pshufw mm1, mm2/m64, imm8
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = source[(imm8 >> (2 * i) & 3) as usize]
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F70_reg(r1: i32, r2: i32, imm: i32) { instr_0F70(read_mmx64s(r1), r2, imm); }
pub unsafe fn instr_0F70_mem(addr: i32, r: i32, imm: i32) {
    instr_0F70(return_on_pagefault!(safe_read64s(addr)), r, imm);
}
pub unsafe fn instr_660F70(source: reg128, r: i32, imm8: i32) {
    // pshufd xmm, xmm/mem128, imm8
    write_xmm128(
        r,
        source.u32[(imm8 & 3) as usize] as i32,
        source.u32[(imm8 >> 2 & 3) as usize] as i32,
        source.u32[(imm8 >> 4 & 3) as usize] as i32,
        source.u32[(imm8 >> 6 & 3) as usize] as i32,
    );
}
pub unsafe fn instr_660F70_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F70(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F70_mem(addr: i32, r: i32, imm: i32) {
    instr_660F70(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}

#[no_mangle]
pub unsafe fn instr_F20F70(source: reg128, r: i32, imm8: i32) {
    // pshuflw xmm, xmm/m128, imm8
    write_xmm128(
        r,
        source.u16[(imm8 & 3) as usize] as i32
            | (source.u16[(imm8 >> 2 & 3) as usize] as i32) << 16,
        source.u16[(imm8 >> 4 & 3) as usize] as i32
            | (source.u16[(imm8 >> 6 & 3) as usize] as i32) << 16,
        source.u32[2] as i32,
        source.u32[3] as i32,
    );
}
pub unsafe fn instr_F20F70_reg(r1: i32, r2: i32, imm: i32) {
    instr_F20F70(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_F20F70_mem(addr: i32, r: i32, imm: i32) {
    instr_F20F70(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
#[no_mangle]
pub unsafe fn instr_F30F70(source: reg128, r: i32, imm8: i32) {
    // pshufhw xmm, xmm/m128, imm8
    write_xmm128(
        r,
        source.u32[0] as i32,
        source.u32[1] as i32,
        source.u16[(imm8 & 3 | 4) as usize] as i32
            | (source.u16[(imm8 >> 2 & 3 | 4) as usize] as i32) << 16,
        source.u16[(imm8 >> 4 & 3 | 4) as usize] as i32
            | (source.u16[(imm8 >> 6 & 3 | 4) as usize] as i32) << 16,
    );
}
pub unsafe fn instr_F30F70_reg(r1: i32, r2: i32, imm: i32) {
    instr_F30F70(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_F30F70_mem(addr: i32, r: i32, imm: i32) {
    instr_F30F70(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
pub unsafe fn instr_0F71_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_0F71_4_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_0F71_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F71_2_reg(r: i32, imm8: i32) {
    // psrlw mm, imm8
    psrlw_r64(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_0F71_4_reg(r: i32, imm8: i32) {
    // psraw mm, imm8
    psraw_r64(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_0F71_6_reg(r: i32, imm8: i32) {
    // psllw mm, imm8
    psllw_r64(r, imm8 as u64);
}
pub unsafe fn instr_660F71_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F71_4_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F71_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F71_2_reg(r: i32, imm8: i32) {
    // psrlw xmm, imm8
    psrlw_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F71_4_reg(r: i32, imm8: i32) {
    // psraw xmm, imm8
    psraw_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F71_6_reg(r: i32, imm8: i32) {
    // psllw xmm, imm8
    psllw_r128(r, imm8 as u64);
}
pub unsafe fn instr_0F72_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_0F72_4_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_0F72_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F72_2_reg(r: i32, imm8: i32) {
    // psrld mm, imm8
    psrld_r64(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_0F72_4_reg(r: i32, imm8: i32) {
    // psrad mm, imm8
    psrad_r64(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_0F72_6_reg(r: i32, imm8: i32) {
    // pslld mm, imm8
    pslld_r64(r, imm8 as u64);
}
pub unsafe fn instr_660F72_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F72_4_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F72_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F72_2_reg(r: i32, imm8: i32) {
    // psrld xmm, imm8
    psrld_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F72_4_reg(r: i32, imm8: i32) {
    // psrad xmm, imm8
    psrad_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F72_6_reg(r: i32, imm8: i32) {
    // pslld xmm, imm8
    pslld_r128(r, imm8 as u64);
}
pub unsafe fn instr_0F73_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_0F73_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0F73_2_reg(r: i32, imm8: i32) {
    // psrlq mm, imm8
    psrlq_r64(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_0F73_6_reg(r: i32, imm8: i32) {
    // psllq mm, imm8
    psllq_r64(r, imm8 as u64);
}
pub unsafe fn instr_660F73_2_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F73_3_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F73_6_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr_660F73_7_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660F73_2_reg(r: i32, imm8: i32) {
    // psrlq xmm, imm8
    psrlq_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F73_3_reg(r: i32, imm8: i32) {
    // psrldq xmm, imm8
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    if imm8 == 0 {
        return;
    }
    let shift = (if imm8 > 15 { 128 } else { imm8 << 3 }) as u32;
    if shift <= 63 {
        result.u64[0] = destination.u64[0] >> shift | destination.u64[1] << (64 - shift);
        result.u64[1] = destination.u64[1] >> shift
    }
    else if shift <= 127 {
        result.u64[0] = destination.u64[1] >> (shift - 64);
        result.u64[1] = 0
    }
    write_xmm_reg128(r, result);
}
#[no_mangle]
pub unsafe fn instr_660F73_6_reg(r: i32, imm8: i32) {
    // psllq xmm, imm8
    psllq_r128(r, imm8 as u64);
}
#[no_mangle]
pub unsafe fn instr_660F73_7_reg(r: i32, imm8: i32) {
    // pslldq xmm, imm8
    if imm8 == 0 {
        return;
    }
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    let shift = (if imm8 > 15 { 128 } else { imm8 << 3 }) as u32;
    if shift <= 63 {
        result.u64[0] = destination.u64[0] << shift;
        result.u64[1] = destination.u64[1] << shift | destination.u64[0] >> (64 - shift)
    }
    else if shift <= 127 {
        result.u64[0] = 0;
        result.u64[1] = destination.u64[0] << (shift - 64)
    }
    write_xmm_reg128(r, result);
}

#[no_mangle]
pub unsafe fn instr_0F74(source: u64, r: i32) {
    // pcmpeqb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result: [u8; 8] = [0; 8];
    for i in 0..8 {
        result[i] = if destination[i] == source[i] { 255 } else { 0 };
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F74_reg(r1: i32, r2: i32) { instr_0F74(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F74_mem(addr: i32, r: i32) {
    instr_0F74(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F74(source: reg128, r: i32) {
    // pcmpeqb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = if source.u8[i] == destination.u8[i] { 255 } else { 0 }
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F74_reg(r1: i32, r2: i32) { instr_660F74(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F74_mem(addr: i32, r: i32) {
    instr_660F74(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F75(source: u64, r: i32) {
    // pcmpeqw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result: [u16; 4] = [0; 4];
    for i in 0..4 {
        result[i] = if destination[i] == source[i] { 0xFFFF } else { 0 };
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F75_reg(r1: i32, r2: i32) { instr_0F75(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F75_mem(addr: i32, r: i32) {
    instr_0F75(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F75(source: reg128, r: i32) {
    // pcmpeqw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] =
            (if source.u16[i] as i32 == destination.u16[i] as i32 { 0xFFFF } else { 0 }) as u16;
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F75_reg(r1: i32, r2: i32) { instr_660F75(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F75_mem(addr: i32, r: i32) {
    instr_660F75(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F76(source: u64, r: i32) {
    // pcmpeqd mm, mm/m64
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let source: [i32; 2] = std::mem::transmute(source);
    let mut result = [0; 2];
    for i in 0..2 {
        result[i] = if destination[i] == source[i] { -1 } else { 0 }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F76_reg(r1: i32, r2: i32) { instr_0F76(read_mmx64s(r1), r2); }
pub unsafe fn instr_0F76_mem(addr: i32, r: i32) {
    instr_0F76(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660F76(source: reg128, r: i32) {
    // pcmpeqd xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..4 {
        result.i32[i] = if source.u32[i] == destination.u32[i] { -1 } else { 0 }
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660F76_reg(r1: i32, r2: i32) { instr_660F76(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F76_mem(addr: i32, r: i32) {
    instr_660F76(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0F77() {
    // emms
    fpu_set_tag_word(0xFFFF);
}

#[no_mangle]
pub unsafe fn instr_0F78() { unimplemented_sse(); }
#[no_mangle]
pub unsafe fn instr_0F79() { unimplemented_sse(); }
#[no_mangle]
pub unsafe fn instr_0F7A() { unimplemented_sse(); }
#[no_mangle]
pub unsafe fn instr_0F7B() { unimplemented_sse(); }

#[no_mangle]
pub unsafe fn instr_0F7C() { unimplemented_sse(); }
#[no_mangle]
pub unsafe fn instr_0F7D() { unimplemented_sse(); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F7C(source: reg128, r: i32) -> bool {
    // haddpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F7C, r, source.bits(), 0)
}
pub unsafe fn instr_660F7C_reg(r1: i32, r2: i32) { instr_660F7C(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F7C_mem(addr: i32, r: i32) {
    instr_660F7C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F7C(source: reg128, r: i32) -> bool {
    // haddps xmm, xmm/m128
    sse_fp_arithmetic(0xF20F7C, r, source.bits(), 0)
}
pub unsafe fn instr_F20F7C_reg(r1: i32, r2: i32) { instr_F20F7C(read_xmm128s(r1), r2); }
pub unsafe fn instr_F20F7C_mem(addr: i32, r: i32) {
    instr_F20F7C(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660F7D(source: reg128, r: i32) -> bool {
    // hsubpd xmm, xmm/m128
    sse_fp_arithmetic(0x660F7D, r, source.bits(), 0)
}
pub unsafe fn instr_660F7D_reg(r1: i32, r2: i32) { instr_660F7D(read_xmm128s(r1), r2); }
pub unsafe fn instr_660F7D_mem(addr: i32, r: i32) {
    instr_660F7D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20F7D(source: reg128, r: i32) -> bool {
    // hsubps xmm, xmm/m128
    sse_fp_arithmetic(0xF20F7D, r, source.bits(), 0)
}
pub unsafe fn instr_F20F7D_reg(r1: i32, r2: i32) { instr_F20F7D(read_xmm128s(r1), r2); }
pub unsafe fn instr_F20F7D_mem(addr: i32, r: i32) {
    instr_F20F7D(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0F7E(r: i32) -> i32 {
    // movd r/m32, mm
    return read_mmx64s(r) as i32;
}
pub unsafe fn instr_0F7E_reg(r1: i32, r2: i32) {
    write_reg32(r1, instr_0F7E(r2));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F7E_mem(addr: i32, r: i32) {
    return_on_pagefault!(safe_write32(addr, instr_0F7E(r)));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_660F7E(r: i32) -> i32 {
    // movd r/m32, xmm
    let data = read_xmm64s(r);
    return data as i32;
}
pub unsafe fn instr_660F7E_reg(r1: i32, r2: i32) { write_reg32(r1, instr_660F7E(r2)); }
pub unsafe fn instr_660F7E_mem(addr: i32, r: i32) {
    return_on_pagefault!(safe_write32(addr, instr_660F7E(r)));
}
pub unsafe fn instr_F30F7E_mem(addr: i32, r: i32) {
    // movq xmm, xmm/mem64
    let data = return_on_pagefault!(safe_read64s(addr));
    write_xmm128_2(r, data, 0);
}
pub unsafe fn instr_F30F7E_reg(r1: i32, r2: i32) {
    // movq xmm, xmm/mem64
    write_xmm128_2(r2, read_xmm64s(r1), 0);
}

pub unsafe fn instr_0F7F_mem(addr: i32, r: i32) {
    // movq mm/m64, mm
    mov_r_m64(addr, r);
}
#[no_mangle]
pub unsafe fn instr_0F7F_reg(r1: i32, r2: i32) {
    // movq mm/m64, mm
    write_mmx_reg64(r1, read_mmx64s(r2));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_660F7F_mem(addr: i32, r: i32) {
    // movdqa xmm/m128, xmm
    mov_r_m128_aligned(addr, r);
}
pub unsafe fn instr_660F7F_reg(r1: i32, r2: i32) {
    // movdqa xmm/m128, xmm
    mov_r_r128(r1, r2);
}
pub unsafe fn instr_F30F7F_mem(addr: i32, r: i32) {
    // movdqu xmm/m128, xmm
    mov_r_m128(addr, r);
}
pub unsafe fn instr_F30F7F_reg(r1: i32, r2: i32) {
    // movdqu xmm/m128, xmm
    mov_r_r128(r1, r2);
}

pub unsafe fn instr16_0F80(imm: i32) { jmpcc16(test_o(), imm); }
pub unsafe fn instr32_0F80(imm: i32) { jmpcc32(test_o(), imm); }
pub unsafe fn instr16_0F81(imm: i32) { jmpcc16(!test_o(), imm); }
pub unsafe fn instr32_0F81(imm: i32) { jmpcc32(!test_o(), imm); }
pub unsafe fn instr16_0F82(imm: i32) { jmpcc16(test_b(), imm); }
pub unsafe fn instr32_0F82(imm: i32) { jmpcc32(test_b(), imm); }
pub unsafe fn instr16_0F83(imm: i32) { jmpcc16(!test_b(), imm); }
pub unsafe fn instr32_0F83(imm: i32) { jmpcc32(!test_b(), imm); }
pub unsafe fn instr16_0F84(imm: i32) { jmpcc16(test_z(), imm); }
pub unsafe fn instr32_0F84(imm: i32) { jmpcc32(test_z(), imm); }
pub unsafe fn instr16_0F85(imm: i32) { jmpcc16(!test_z(), imm); }
pub unsafe fn instr32_0F85(imm: i32) { jmpcc32(!test_z(), imm); }
pub unsafe fn instr16_0F86(imm: i32) { jmpcc16(test_be(), imm); }
pub unsafe fn instr32_0F86(imm: i32) { jmpcc32(test_be(), imm); }
pub unsafe fn instr16_0F87(imm: i32) { jmpcc16(!test_be(), imm); }
pub unsafe fn instr32_0F87(imm: i32) { jmpcc32(!test_be(), imm); }
pub unsafe fn instr16_0F88(imm: i32) { jmpcc16(test_s(), imm); }
pub unsafe fn instr32_0F88(imm: i32) { jmpcc32(test_s(), imm); }
pub unsafe fn instr16_0F89(imm: i32) { jmpcc16(!test_s(), imm); }
pub unsafe fn instr32_0F89(imm: i32) { jmpcc32(!test_s(), imm); }
pub unsafe fn instr16_0F8A(imm: i32) { jmpcc16(test_p(), imm); }
pub unsafe fn instr32_0F8A(imm: i32) { jmpcc32(test_p(), imm); }
pub unsafe fn instr16_0F8B(imm: i32) { jmpcc16(!test_p(), imm); }
pub unsafe fn instr32_0F8B(imm: i32) { jmpcc32(!test_p(), imm); }
pub unsafe fn instr16_0F8C(imm: i32) { jmpcc16(test_l(), imm); }
pub unsafe fn instr32_0F8C(imm: i32) { jmpcc32(test_l(), imm); }
pub unsafe fn instr16_0F8D(imm: i32) { jmpcc16(!test_l(), imm); }
pub unsafe fn instr32_0F8D(imm: i32) { jmpcc32(!test_l(), imm); }
pub unsafe fn instr16_0F8E(imm: i32) { jmpcc16(test_le(), imm); }
pub unsafe fn instr32_0F8E(imm: i32) { jmpcc32(test_le(), imm); }
pub unsafe fn instr16_0F8F(imm: i32) { jmpcc16(!test_le(), imm); }
pub unsafe fn instr32_0F8F(imm: i32) { jmpcc32(!test_le(), imm); }

pub unsafe fn instr_0F90_reg(r: i32, _: i32) { setcc_reg(test_o(), r); }
pub unsafe fn instr_0F91_reg(r: i32, _: i32) { setcc_reg(!test_o(), r); }
pub unsafe fn instr_0F92_reg(r: i32, _: i32) { setcc_reg(test_b(), r); }
pub unsafe fn instr_0F93_reg(r: i32, _: i32) { setcc_reg(!test_b(), r); }
pub unsafe fn instr_0F94_reg(r: i32, _: i32) { setcc_reg(test_z(), r); }
pub unsafe fn instr_0F95_reg(r: i32, _: i32) { setcc_reg(!test_z(), r); }
pub unsafe fn instr_0F96_reg(r: i32, _: i32) { setcc_reg(test_be(), r); }
pub unsafe fn instr_0F97_reg(r: i32, _: i32) { setcc_reg(!test_be(), r); }
pub unsafe fn instr_0F98_reg(r: i32, _: i32) { setcc_reg(test_s(), r); }
pub unsafe fn instr_0F99_reg(r: i32, _: i32) { setcc_reg(!test_s(), r); }
pub unsafe fn instr_0F9A_reg(r: i32, _: i32) { setcc_reg(test_p(), r); }
pub unsafe fn instr_0F9B_reg(r: i32, _: i32) { setcc_reg(!test_p(), r); }
pub unsafe fn instr_0F9C_reg(r: i32, _: i32) { setcc_reg(test_l(), r); }
pub unsafe fn instr_0F9D_reg(r: i32, _: i32) { setcc_reg(!test_l(), r); }
pub unsafe fn instr_0F9E_reg(r: i32, _: i32) { setcc_reg(test_le(), r); }
pub unsafe fn instr_0F9F_reg(r: i32, _: i32) { setcc_reg(!test_le(), r); }
pub unsafe fn instr_0F90_mem(addr: i32, _: i32) { setcc_mem(test_o(), addr); }
pub unsafe fn instr_0F91_mem(addr: i32, _: i32) { setcc_mem(!test_o(), addr); }
pub unsafe fn instr_0F92_mem(addr: i32, _: i32) { setcc_mem(test_b(), addr); }
pub unsafe fn instr_0F93_mem(addr: i32, _: i32) { setcc_mem(!test_b(), addr); }
pub unsafe fn instr_0F94_mem(addr: i32, _: i32) { setcc_mem(test_z(), addr); }
pub unsafe fn instr_0F95_mem(addr: i32, _: i32) { setcc_mem(!test_z(), addr); }
pub unsafe fn instr_0F96_mem(addr: i32, _: i32) { setcc_mem(test_be(), addr); }
pub unsafe fn instr_0F97_mem(addr: i32, _: i32) { setcc_mem(!test_be(), addr); }
pub unsafe fn instr_0F98_mem(addr: i32, _: i32) { setcc_mem(test_s(), addr); }
pub unsafe fn instr_0F99_mem(addr: i32, _: i32) { setcc_mem(!test_s(), addr); }
pub unsafe fn instr_0F9A_mem(addr: i32, _: i32) { setcc_mem(test_p(), addr); }
pub unsafe fn instr_0F9B_mem(addr: i32, _: i32) { setcc_mem(!test_p(), addr); }
pub unsafe fn instr_0F9C_mem(addr: i32, _: i32) { setcc_mem(test_l(), addr); }
pub unsafe fn instr_0F9D_mem(addr: i32, _: i32) { setcc_mem(!test_l(), addr); }
pub unsafe fn instr_0F9E_mem(addr: i32, _: i32) { setcc_mem(test_le(), addr); }
pub unsafe fn instr_0F9F_mem(addr: i32, _: i32) { setcc_mem(!test_le(), addr); }

pub unsafe fn instr16_0FA0() {
    return_on_pagefault!(push16(*sreg.offset(FS as isize) as i32));
}
pub unsafe fn instr32_0FA0() { return_on_pagefault!(push32_sreg(FS)) }
#[no_mangle]
pub unsafe fn instr16_0FA1() {
    if !switch_seg(FS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) {
        return;
    }
    else {
        adjust_stack_reg(2);
        return;
    };
}
#[no_mangle]
pub unsafe fn instr32_0FA1() {
    if !switch_seg(
        FS,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF,
    ) {
        return;
    }
    else {
        adjust_stack_reg(4);
        return;
    };
}
// Internal OS qualification switch. The supported public CPU remains the
// legacy profile until the independent x86-64 acceptance gates pass. A test
// must opt in on each newly created machine; this is never a user config knob.
static mut X64_TEST_CAPABILITIES: bool = false;
/// IA32_ARCH_CAPABILITIES in the x64 profile (on by default there).
static mut X64_ARCH_CAPABILITIES: bool = true;

#[no_mangle]
pub unsafe fn set_x64_test_capabilities(enabled: bool) { X64_TEST_CAPABILITIES = enabled; }
#[no_mangle]
pub unsafe fn set_x64_arch_capabilities(enabled: bool) { X64_ARCH_CAPABILITIES = enabled; }
/// A worker's cores report the machine's CPU profile (crate::parallel)
pub unsafe fn copy_cpu_profile() {
    use crate::parallel::machine;
    X64_TEST_CAPABILITIES = *machine(&raw mut X64_TEST_CAPABILITIES);
    X64_ARCH_CAPABILITIES = *machine(&raw mut X64_ARCH_CAPABILITIES);
    crate::cpu::features::copy_from_machine();
}

/// The emulated core executes nothing speculatively, so it reports itself
/// unaffected: RDCL_NO, SKIP_L1DFL_VMENTRY, SSB_NO, MDS_NO, PSCHANGE_MC_NO,
/// TAA_NO, SBDR_SSDP_NO, FBSDP_NO, PSDP_NO, BHI_NO, PBRSB_NO, GDS_NO,
/// RFDS_NO and ITS_NO. (Guests then skip PTI, VERW buffer clearing and ITS
/// thunks.)
pub const ARCH_CAPABILITIES: u64 = 1
    | 1 << 3
    | 1 << 4
    | 1 << 5
    | 1 << 6
    | 1 << 8
    | 1 << 13
    | 1 << 14
    | 1 << 15
    | 1 << 20
    | 1 << 24
    | 1 << 26
    | 1 << 27
    | 1 << 62;
pub unsafe fn arch_capabilities() -> Option<u64> {
    (X64_TEST_CAPABILITIES && X64_ARCH_CAPABILITIES).then_some(ARCH_CAPABILITIES)
}
/// The x86-64 profile (e.g. its SMRAM save map, crate::cpu::smm)
pub unsafe fn long_mode_capable() -> bool { X64_TEST_CAPABILITIES }

fn apply_x64_test_capabilities(enabled: bool, leaf: u32, registers: &mut [u32; 4]) {
    if !enabled {
        return;
    }
    match leaf {
        1 => {
            registers[2] |= 1 << 13; // CMPXCHG16B
            registers[3] |= 1 << 19; // CLFLUSH (implemented; line size in EBX[15:8])
                                     // DE (CR4.DE, I/O breakpoints), MCE, MTRR, MCA, PAT: required by
                                     // Windows 8.1 x64 (UNSUPPORTED_PROCESSOR otherwise)
            registers[3] |= 1 << 2 | 1 << 7 | 1 << 12 | 1 << 14 | 1 << 16;
        },
        7 => {
            if unsafe { X64_ARCH_CAPABILITIES } {
                registers[3] |= 1 << 29
            }
        }, // IA32_ARCH_CAPABILITIES
        0x8000_0000 => registers[0] = 0x8000_0008,
        0x8000_0001 => {
            registers[2] |= 1; // LAHF/SAHF in long mode
            registers[3] |= (1 << 11) | (1 << 20) | (1 << 27) | (1 << 29); // SYSCALL, NX, RDTSCP, LM
        },
        0x8000_0008 => registers[0] = 36 | 48 << 8, // physical / linear address bits
        _ => {},
    }
}

#[cfg(test)]
mod x64_cpuid_tests {
    use super::apply_x64_test_capabilities;

    #[test]
    fn internal_profile_is_opt_in_and_has_only_implemented_extensions() {
        for leaf in [1, 7, 0x8000_0000, 0x8000_0001, 0x8000_0008] {
            let original = [0x1234, 0x5678, 0xABCD, 0xEF00];
            let mut result = original;
            apply_x64_test_capabilities(false, leaf, &mut result);
            assert_eq!(result, original);
        }
        for (leaf, expected) in [
            (
                1,
                [
                    0,
                    0,
                    1 << 13,
                    1 << 19 | 1 << 2 | 1 << 7 | 1 << 12 | 1 << 14 | 1 << 16,
                ],
            ),
            (7, [0, 0, 0, 1 << 29]),
            (0x8000_0000, [0x8000_0008, 0, 0, 0]),
            (
                0x8000_0001,
                [0, 0, 1, (1 << 11) | (1 << 20) | (1 << 27) | (1 << 29)],
            ),
            (0x8000_0008, [36 | 48 << 8, 0, 0, 0]),
        ] {
            let mut result = [0; 4];
            apply_x64_test_capabilities(true, leaf, &mut result);
            assert_eq!(result, expected);
        }
    }
}

#[no_mangle]
pub unsafe fn instr_0FA2() {
    // serializing: other cores' writes to code are seen from here on
    crate::parallel::code::poll();
    // cpuid
    // TODO: Fill in with less bogus values

    // http://lxr.linux.no/linux+%2a/arch/x86/include/asm/cpufeature.h
    // http://www.sandpile.org/x86/cpuid.htm
    let mut eax = 0;
    let mut ecx = 0;
    let mut edx = 0;
    let mut ebx = 0;

    let level = read_reg32(EAX) as u32;

    match level {
        0 => {
            // maximum supported level (default 0x16, overwritten to 2 as a workaround for Windows NT)
            eax = cpuid_level as i32;

            ebx = 0x756E6547 | 0; // Genu
            edx = 0x49656E69 | 0; // ineI
            ecx = 0x6C65746E | 0; // ntel
        },

        1 => {
            eax = 3 | 7 << 4 | 6 << 8; // pentium3
                                       // initial APIC ID of this core (topology fields: see
                                       // docs/multicore.md), cpu count, clflush size
            ebx = (crate::cpu::apic::current_core() as i32) << 24 | 1 << 16 | 8 << 8;
            ecx = 1 << 0 | 1 << 23 | 1 << 30; // sse3, popcnt, rdrand
            let vme = 0 << 1;
            if config::VMWARE_HYPERVISOR_PORT {
                ecx |= 1 << 31
            }; // hypervisor
            edx = (if true /* have fpu */ { 1 } else {  0 }) |      // fpu
                    vme | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 |  // vme, pse, tsc, msr, pae
                    1 << 8 | 1 << 11 | 1 << 13 | 1 << 15 | // cx8, sep, pge, cmov
                    1 << 23 | 1 << 24 | 1 << 25 | 1 << 26; // mmx, fxsr, sse1, sse2

            // reflects IA32_APIC_BASE.EN, like the processor's APIC feature flag
            if *acpi_enabled && *apic_enabled {
                edx |= 1 << 9; // apic
            }
        },

        2 => {
            // Taken from http://siyobik.info.gf/main/reference/instruction/CPUID
            eax = 0x665B5001;
            ebx = 0;
            ecx = 0;
            edx = 0x007A7000;
        },

        4 => {
            // from my local machine
            match read_reg32(ECX) {
                0 => {
                    eax = 0x00000121;
                    ebx = 0x01c0003f;
                    ecx = 0x0000003f;
                    edx = 0x00000001;
                },
                1 => {
                    eax = 0x00000122;
                    ebx = 0x01c0003f;
                    ecx = 0x0000003f;
                    edx = 0x00000001;
                },
                2 => {
                    eax = 0x00000143;
                    ebx = 0x05c0003f;
                    ecx = 0x00000fff;
                    edx = 0x00000001;
                },
                _ => {},
            }
        },

        5 => {
            // from my local machine
            eax = 0x40;
            ebx = 0x40;
            ecx = 3;
            edx = 0x00142120;
        },

        7 => {
            if read_reg32(ECX) == 0 {
                eax = 0; // maximum supported sub-level
                ebx = 1 << 9; // enhanced REP MOVSB/STOSB
                ecx = 0;
                edx = 0;
            }
        },

        0x80000000 => {
            // maximum supported extended level
            eax = 5;
            // other registers are reserved
        },

        0x40000000 => {
            // hypervisor
            if config::VMWARE_HYPERVISOR_PORT {
                // h("Ware".split("").reduce((a, c, i) => a | c.charCodeAt(0) << i * 8, 0))
                ebx = 0x61774D56 | 0; // VMwa
                ecx = 0x4D566572 | 0; // reVM
                edx = 0x65726177 | 0; // ware
            }
        },

        0x15 => {
            eax = 1; // denominator
            ebx = 1; // numerator
            ecx = (TSC_RATE * 1000.0) as u32 as i32; // core crystal clock frequency in Hz
            dbg_assert!(ecx > 0);
            //  (TSC frequency = core crystal clock frequency * EBX/EAX)
        },

        0x16 => {
            eax = (TSC_RATE / 1000.0).floor() as u32 as i32; // core base frequency in MHz
            ebx = (TSC_RATE / 1000.0).floor() as u32 as i32; // core maximum frequency in MHz
            ecx = 10; // bus (reference) frequency in MHz

            // 16-bit values
            dbg_assert!(eax < 0x10000);
            dbg_assert!(ebx < 0x10000);
            dbg_assert!(ecx < 0x10000);
        },

        x => {
            dbg_log!("cpuid: unimplemented eax: {:x}", x);
        },
    }

    if level == 4 || level == 7 {
        dbg_log!(
            "cpuid: eax={:08x} ecx={:02x}",
            read_reg32(EAX),
            read_reg32(ECX),
        );
    }
    else if level != 0 && level != 2 && level != 0x80000000 {
        dbg_log!("cpuid: eax={:08x}", read_reg32(EAX));
    }

    let mut topology = [eax as u32, ebx as u32, ecx as u32, edx as u32];
    apply_x64_test_capabilities(X64_TEST_CAPABILITIES, level, &mut topology);
    crate::cpu::features::cpuid(level, read_reg32(ECX) as u32, &mut topology);
    crate::cpu::xstate::cpuid(level, read_reg32(ECX) as u32, &mut topology);
    crate::cpu::topology::apply(
        level,
        read_reg32(ECX) as u32,
        crate::cpu::apic::core_count() as u32,
        crate::cpu::apic::current_core() as u32,
        &mut topology,
    );
    let [eax, ebx, ecx, edx] = topology.map(|x| x as i32);
    write_reg32(EAX, eax);
    write_reg32(ECX, ecx);
    write_reg32(EDX, edx);
    write_reg32(EBX, ebx);
}
/// What CPUID returns for `leaf` and `subleaf` on the current core, register
/// `register` (0 EAX, 1 EBX, 2 ECX, 3 EDX): for tables the host builds before
/// the guest runs (src/smbios.js). The general registers are left as they were.
#[no_mangle]
pub unsafe fn cpuid_query(leaf: u32, subleaf: u32, register: u32) -> u32 {
    let saved = [EAX, EBX, ECX, EDX].map(|r| read_reg32(r));
    write_reg32(EAX, leaf as i32);
    write_reg32(ECX, subleaf as i32);
    instr_0FA2();
    let result = read_reg32([EAX, EBX, ECX, EDX][register as usize & 3]) as u32;
    for (r, value) in [EAX, EBX, ECX, EDX].into_iter().zip(saved) {
        write_reg32(r, value);
    }
    result
}
pub unsafe fn instr16_0FA3_reg(r1: i32, r2: i32) { bt_reg(read_reg16(r1), read_reg16(r2) & 15); }
pub unsafe fn instr16_0FA3_mem(addr: i32, r: i32) { bt_mem(addr, read_reg16(r) << 16 >> 16); }
pub unsafe fn instr32_0FA3_reg(r1: i32, r2: i32) { bt_reg(read_reg32(r1), read_reg32(r2) & 31); }
pub unsafe fn instr32_0FA3_mem(addr: i32, r: i32) { bt_mem(addr, read_reg32(r)); }
pub unsafe fn instr16_0FA4_mem(addr: i32, r: i32, imm: i32) {
    safe_read_write16(addr, &|x| shld16(x, read_reg16(r), imm & 31))
}
pub unsafe fn instr16_0FA4_reg(r1: i32, r: i32, imm: i32) {
    write_reg16(r1, shld16(read_reg16(r1), read_reg16(r), imm & 31));
}
pub unsafe fn instr32_0FA4_mem(addr: i32, r: i32, imm: i32) {
    safe_read_write32(addr, &|x| shld32(x, read_reg32(r), imm & 31))
}
pub unsafe fn instr32_0FA4_reg(r1: i32, r: i32, imm: i32) {
    write_reg32(r1, shld32(read_reg32(r1), read_reg32(r), imm & 31));
}
pub unsafe fn instr16_0FA5_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| shld16(x, read_reg16(r), read_reg8(CL) & 31))
}
pub unsafe fn instr16_0FA5_reg(r1: i32, r: i32) {
    write_reg16(
        r1,
        shld16(read_reg16(r1), read_reg16(r), read_reg8(CL) & 31),
    );
}
pub unsafe fn instr32_0FA5_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| shld32(x, read_reg32(r), read_reg8(CL) & 31))
}
pub unsafe fn instr32_0FA5_reg(r1: i32, r: i32) {
    write_reg32(
        r1,
        shld32(read_reg32(r1), read_reg32(r), read_reg8(CL) & 31),
    );
}
#[no_mangle]
pub unsafe fn instr_0FA6() {
    // obsolete cmpxchg (os/2)
    trigger_ud();
}
#[no_mangle]
pub unsafe fn instr_0FA7() { undefined_instruction(); }
pub unsafe fn instr16_0FA8() {
    return_on_pagefault!(push16(*sreg.offset(GS as isize) as i32));
}
pub unsafe fn instr32_0FA8() { return_on_pagefault!(push32_sreg(GS)) }
#[no_mangle]
pub unsafe fn instr16_0FA9() {
    if !switch_seg(GS, return_on_pagefault!(safe_read16(get_stack_pointer(0)))) {
        return;
    }
    else {
        adjust_stack_reg(2);
        return;
    };
}
#[no_mangle]
pub unsafe fn instr32_0FA9() {
    if !switch_seg(
        GS,
        return_on_pagefault!(safe_read32s(get_stack_pointer(0))) & 0xFFFF,
    ) {
        return;
    }
    else {
        adjust_stack_reg(4);
        return;
    };
}
#[no_mangle]
pub unsafe fn instr_0FAA() {
    // rsm: only in system management mode
    if !crate::cpu::smm::smm_active() {
        undefined_instruction();
        return;
    }
    crate::cpu::smm::rsm();
}
#[no_mangle]
pub unsafe fn instr16_0FAB_reg(r1: i32, r2: i32) {
    write_reg16(r1, bts_reg(read_reg16(r1), read_reg16(r2) & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FAB_mem(addr: i32, r: i32) { bts_mem(addr, read_reg16(r) << 16 >> 16); }
#[no_mangle]
pub unsafe fn instr32_0FAB_reg(r1: i32, r2: i32) {
    write_reg32(r1, bts_reg(read_reg32(r1), read_reg32(r2) & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FAB_mem(addr: i32, r: i32) { bts_mem(addr, read_reg32(r)); }
pub unsafe fn instr16_0FAC_mem(addr: i32, r: i32, imm: i32) {
    safe_read_write16(addr, &|x| shrd16(x, read_reg16(r), imm & 31))
}
pub unsafe fn instr16_0FAC_reg(r1: i32, r: i32, imm: i32) {
    write_reg16(r1, shrd16(read_reg16(r1), read_reg16(r), imm & 31));
}
pub unsafe fn instr32_0FAC_mem(addr: i32, r: i32, imm: i32) {
    safe_read_write32(addr, &|x| shrd32(x, read_reg32(r), imm & 31))
}
pub unsafe fn instr32_0FAC_reg(r1: i32, r: i32, imm: i32) {
    write_reg32(r1, shrd32(read_reg32(r1), read_reg32(r), imm & 31));
}
pub unsafe fn instr16_0FAD_mem(addr: i32, r: i32) {
    safe_read_write16(addr, &|x| shrd16(x, read_reg16(r), read_reg8(CL) & 31))
}
pub unsafe fn instr16_0FAD_reg(r1: i32, r: i32) {
    write_reg16(
        r1,
        shrd16(read_reg16(r1), read_reg16(r), read_reg8(CL) & 31),
    );
}
pub unsafe fn instr32_0FAD_mem(addr: i32, r: i32) {
    safe_read_write32(addr, &|x| shrd32(x, read_reg32(r), read_reg8(CL) & 31))
}
pub unsafe fn instr32_0FAD_reg(r1: i32, r: i32) {
    write_reg32(
        r1,
        shrd32(read_reg32(r1), read_reg32(r), read_reg8(CL) & 31),
    );
}
// TZCNT and LZCNT (F3 0F BC/BD, whose rows need BMI1 and LZCNT: BSF and BSR
// without): the operand's trailing or leading zeros, its size for 0 (CF)
unsafe fn count(r: i32, value: i32, bits: u32, leading: bool) {
    let (result, arithmetic) = if leading {
        crate::cpu::bmi::lzcnt(value as u32 as u64, bits)
    }
    else {
        crate::cpu::bmi::tzcnt(value as u32 as u64, bits)
    };
    if bits == 16 {
        write_reg16(r, result as i32);
    }
    else {
        write_reg32(r, result as i32);
    }
    crate::cpu::bmi::set_flags(arithmetic);
}
pub unsafe fn instr16_F30FBC_mem(addr: i32, r: i32) {
    count(r, return_on_pagefault!(safe_read16(addr)), 16, false)
}
pub unsafe fn instr16_F30FBC_reg(r1: i32, r: i32) { count(r, read_reg16(r1), 16, false) }
pub unsafe fn instr32_F30FBC_mem(addr: i32, r: i32) {
    count(r, return_on_pagefault!(safe_read32s(addr)), 32, false)
}
pub unsafe fn instr32_F30FBC_reg(r1: i32, r: i32) { count(r, read_reg32(r1), 32, false) }
pub unsafe fn instr16_F30FBD_mem(addr: i32, r: i32) {
    count(r, return_on_pagefault!(safe_read16(addr)), 16, true)
}
pub unsafe fn instr16_F30FBD_reg(r1: i32, r: i32) { count(r, read_reg16(r1), 16, true) }
pub unsafe fn instr32_F30FBD_mem(addr: i32, r: i32) {
    count(r, return_on_pagefault!(safe_read32s(addr)), 32, true)
}
pub unsafe fn instr32_F30FBD_reg(r1: i32, r: i32) { count(r, read_reg32(r1), 32, true) }
#[no_mangle]
pub unsafe fn instr_0FAE_0_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FAE_0_mem(addr: i32) { fxsave(addr); }
#[no_mangle]
pub unsafe fn instr_0FAE_1_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FAE_1_mem(addr: i32) { fxrstor(addr); }
#[no_mangle]
pub unsafe fn instr_0FAE_2_reg(_r: i32) { unimplemented_sse(); }
#[no_mangle]
pub unsafe fn instr_0FAE_2_mem(addr: i32) {
    // ldmxcsr
    let new_mxcsr = return_on_pagefault!(safe_read32s(addr));
    if 0 != new_mxcsr & !MXCSR_MASK {
        dbg_log!("Invalid mxcsr bits: {:x}", new_mxcsr & !MXCSR_MASK);
        trigger_gp(0);
        return;
    }
    else {
        set_mxcsr(new_mxcsr);
        return;
    };
}
#[no_mangle]
pub unsafe fn instr_0FAE_3_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FAE_3_mem(addr: i32) {
    // stmxcsr
    return_on_pagefault!(safe_write32(addr, *mxcsr));
}
#[no_mangle]
pub unsafe fn instr_0FAE_4_reg(_r: i32) { trigger_ud(); }
// XSAVE and XRSTOR: #UD (CR4.OSXSAVE) and #NM (CR0.TS) come before the
// operand's segment checks (modrm_resolve)
#[no_mangle]
pub unsafe fn instr_0FAE_4_mem(modrm_byte: i32) {
    // xsave
    if crate::cpu::xstate::usable(true) {
        crate::cpu::xstate::xsave_32(return_on_pagefault!(modrm_resolve(modrm_byte)));
    }
}
pub unsafe fn instr_0FAE_5_reg(_r: i32) {
    // lfence
}
pub unsafe fn instr_0FAE_5_mem(modrm_byte: i32) {
    // xrstor
    if crate::cpu::xstate::usable(true) {
        crate::cpu::xstate::xrstor_32(return_on_pagefault!(modrm_resolve(modrm_byte)));
    }
}
#[no_mangle]
pub unsafe fn instr_0FAE_6_reg(_r: i32) {
    // mfence
}
#[no_mangle]
pub unsafe fn instr_0FAE_6_mem(modrm_byte: i32) {
    // xsaveopt: XSAVE's checks and their order, with its feature
    if !crate::cpu::features::has(crate::cpu::features::XSAVEOPT) {
        trigger_ud();
        return;
    }
    if crate::cpu::xstate::usable(true) {
        crate::cpu::xstate::xsaveopt_32(return_on_pagefault!(modrm_resolve(modrm_byte)));
    }
}
/// XRSTORS (0F C7 /3), XSAVEC (/4) and XSAVES (/5), whose rows need their
/// features: no mandatory prefix, then XSAVE's checks and their order, with
/// #GP(0) for CPL > 0 before the operand for XRSTORS and XSAVES. False if a
/// fault was delivered.
unsafe fn compacted_state(modrm_byte: i32, group: i32) -> bool {
    use crate::prefix::{PREFIX_66, PREFIX_F2, PREFIX_F3};
    if *prefixes & (PREFIX_66 | PREFIX_F2 | PREFIX_F3) != 0 {
        trigger_ud();
        return false;
    }
    if !crate::cpu::xstate::usable(true) {
        return false;
    }
    if group != 4 && *cpl != 0 {
        trigger_gp(0);
        return false;
    }
    let Ok(addr) = modrm_resolve(modrm_byte)
    else {
        return false;
    };
    match group {
        3 => crate::cpu::xstate::xrstors_32(addr),
        4 => crate::cpu::xstate::xsavec_32(addr),
        _ => crate::cpu::xstate::xsaves_32(addr),
    }
}
#[no_mangle]
pub unsafe fn instr_0FC7_3_mem(modrm_byte: i32) { compacted_state(modrm_byte, 3); }
#[no_mangle]
pub unsafe fn instr_0FC7_3_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FC7_4_mem(modrm_byte: i32) { compacted_state(modrm_byte, 4); }
#[no_mangle]
pub unsafe fn instr_0FC7_4_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FC7_5_mem(modrm_byte: i32) { compacted_state(modrm_byte, 5); }
#[no_mangle]
pub unsafe fn instr_0FC7_5_reg(_r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FAE_7_reg(_r: i32) {
    // sfence
}
#[no_mangle]
pub unsafe fn instr_0FAE_7_mem(_addr: i32) {
    // clflush
    undefined_instruction();
}
pub unsafe fn instr16_0FAF_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        imul_reg16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_0FAF_reg(r1: i32, r: i32) {
    write_reg16(r, imul_reg16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_0FAF_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        imul_reg32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_0FAF_reg(r1: i32, r: i32) {
    write_reg32(r, imul_reg32(read_reg32(r), read_reg32(r1)));
}

#[no_mangle]
pub unsafe fn instr_0FB0_reg(r1: i32, r2: i32) { write_reg8(r1, cmpxchg8(read_reg8(r1), r2)); }
#[no_mangle]
pub unsafe fn instr_0FB0_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| cmpxchg8(x, r)) }
pub unsafe fn instr16_0FB1_reg(r1: i32, r2: i32) { write_reg16(r1, cmpxchg16(read_reg16(r1), r2)); }
pub unsafe fn instr16_0FB1_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| cmpxchg16(x, r)) }
pub unsafe fn instr32_0FB1_reg(r1: i32, r2: i32) { write_reg32(r1, cmpxchg32(read_reg32(r1), r2)); }
pub unsafe fn instr32_0FB1_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| cmpxchg32(x, r)) }

#[no_mangle]
pub unsafe fn instr16_0FB2_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr16_0FB2_mem(addr: i32, r: i32) { lss16(addr, r, SS); }
#[no_mangle]
pub unsafe fn instr32_0FB2_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0FB2_mem(addr: i32, r: i32) { lss32(addr, r, SS); }
#[no_mangle]
pub unsafe fn instr16_0FB3_reg(r1: i32, r2: i32) {
    write_reg16(r1, btr_reg(read_reg16(r1), read_reg16(r2) & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FB3_mem(addr: i32, r: i32) { btr_mem(addr, read_reg16(r) << 16 >> 16); }
#[no_mangle]
pub unsafe fn instr32_0FB3_reg(r1: i32, r2: i32) {
    write_reg32(r1, btr_reg(read_reg32(r1), read_reg32(r2) & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FB3_mem(addr: i32, r: i32) { btr_mem(addr, read_reg32(r)); }
#[no_mangle]
pub unsafe fn instr16_0FB4_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr16_0FB4_mem(addr: i32, r: i32) { lss16(addr, r, FS); }
#[no_mangle]
pub unsafe fn instr32_0FB4_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0FB4_mem(addr: i32, r: i32) { lss32(addr, r, FS); }
#[no_mangle]
pub unsafe fn instr16_0FB5_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr16_0FB5_mem(addr: i32, r: i32) { lss16(addr, r, GS); }
#[no_mangle]
pub unsafe fn instr32_0FB5_reg(_unused: i32, _unused2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0FB5_mem(addr: i32, r: i32) { lss32(addr, r, GS); }
pub unsafe fn instr16_0FB6_mem(addr: i32, r: i32) {
    write_reg16(r, return_on_pagefault!(safe_read8(addr)));
}
pub unsafe fn instr16_0FB6_reg(r1: i32, r: i32) { write_reg16(r, read_reg8(r1)); }
pub unsafe fn instr32_0FB6_mem(addr: i32, r: i32) {
    write_reg32(r, return_on_pagefault!(safe_read8(addr)));
}
pub unsafe fn instr32_0FB6_reg(r1: i32, r: i32) { write_reg32(r, read_reg8(r1)); }
pub unsafe fn instr16_0FB7_mem(addr: i32, r: i32) {
    write_reg16(r, return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr16_0FB7_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1)); }
pub unsafe fn instr32_0FB7_mem(addr: i32, r: i32) {
    write_reg32(r, return_on_pagefault!(safe_read16(addr)));
}
pub unsafe fn instr32_0FB7_reg(r1: i32, r: i32) { write_reg32(r, read_reg16(r1)); }
#[no_mangle]
pub unsafe fn instr16_0FB8_reg(_r1: i32, _r2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr16_0FB8_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr16_F30FB8_mem(addr: i32, r: i32) {
    write_reg16(r, popcnt(return_on_pagefault!(safe_read16(addr))));
}
pub unsafe fn instr16_F30FB8_reg(r1: i32, r: i32) { write_reg16(r, popcnt(read_reg16(r1))); }
#[no_mangle]
pub unsafe fn instr32_0FB8_reg(_r1: i32, _r2: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0FB8_mem(_addr: i32, _r: i32) { trigger_ud(); }
pub unsafe fn instr32_F30FB8_mem(addr: i32, r: i32) {
    write_reg32(r, popcnt(return_on_pagefault!(safe_read32s(addr))));
}
pub unsafe fn instr32_F30FB8_reg(r1: i32, r: i32) { write_reg32(r, popcnt(read_reg32(r1))); }
#[no_mangle]
pub unsafe fn instr_0FB9() {
    // UD2
    trigger_ud();
}
pub unsafe fn instr16_0FBA_4_reg(r: i32, imm: i32) { bt_reg(read_reg16(r), imm & 15); }
pub unsafe fn instr16_0FBA_4_mem(addr: i32, imm: i32) { bt_mem(addr, imm & 15); }
#[no_mangle]
pub unsafe fn instr16_0FBA_5_reg(r: i32, imm: i32) {
    write_reg16(r, bts_reg(read_reg16(r), imm & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FBA_5_mem(addr: i32, imm: i32) { bts_mem(addr, imm & 15); }
#[no_mangle]
pub unsafe fn instr16_0FBA_6_reg(r: i32, imm: i32) {
    write_reg16(r, btr_reg(read_reg16(r), imm & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FBA_6_mem(addr: i32, imm: i32) { btr_mem(addr, imm & 15); }
#[no_mangle]
pub unsafe fn instr16_0FBA_7_reg(r: i32, imm: i32) {
    write_reg16(r, btc_reg(read_reg16(r), imm & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FBA_7_mem(addr: i32, imm: i32) { btc_mem(addr, imm & 15); }
pub unsafe fn instr32_0FBA_4_reg(r: i32, imm: i32) { bt_reg(read_reg32(r), imm & 31); }
pub unsafe fn instr32_0FBA_4_mem(addr: i32, imm: i32) { bt_mem(addr, imm & 31); }
#[no_mangle]
pub unsafe fn instr32_0FBA_5_reg(r: i32, imm: i32) {
    write_reg32(r, bts_reg(read_reg32(r), imm & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FBA_5_mem(addr: i32, imm: i32) { bts_mem(addr, imm & 31); }
#[no_mangle]
pub unsafe fn instr32_0FBA_6_reg(r: i32, imm: i32) {
    write_reg32(r, btr_reg(read_reg32(r), imm & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FBA_6_mem(addr: i32, imm: i32) { btr_mem(addr, imm & 31); }
#[no_mangle]
pub unsafe fn instr32_0FBA_7_reg(r: i32, imm: i32) {
    write_reg32(r, btc_reg(read_reg32(r), imm & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FBA_7_mem(addr: i32, imm: i32) { btc_mem(addr, imm & 31); }
#[no_mangle]
pub unsafe fn instr16_0FBB_reg(r1: i32, r2: i32) {
    write_reg16(r1, btc_reg(read_reg16(r1), read_reg16(r2) & 15));
}
#[no_mangle]
pub unsafe fn instr16_0FBB_mem(addr: i32, r: i32) { btc_mem(addr, read_reg16(r) << 16 >> 16); }
#[no_mangle]
pub unsafe fn instr32_0FBB_reg(r1: i32, r2: i32) {
    write_reg32(r1, btc_reg(read_reg32(r1), read_reg32(r2) & 31));
}
#[no_mangle]
pub unsafe fn instr32_0FBB_mem(addr: i32, r: i32) { btc_mem(addr, read_reg32(r)); }
pub unsafe fn instr16_0FBC_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        bsf16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_0FBC_reg(r1: i32, r: i32) {
    write_reg16(r, bsf16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_0FBC_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        bsf32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_0FBC_reg(r1: i32, r: i32) {
    write_reg32(r, bsf32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr16_0FBD_mem(addr: i32, r: i32) {
    write_reg16(
        r,
        bsr16(read_reg16(r), return_on_pagefault!(safe_read16(addr))),
    );
}
pub unsafe fn instr16_0FBD_reg(r1: i32, r: i32) {
    write_reg16(r, bsr16(read_reg16(r), read_reg16(r1)));
}
pub unsafe fn instr32_0FBD_mem(addr: i32, r: i32) {
    write_reg32(
        r,
        bsr32(read_reg32(r), return_on_pagefault!(safe_read32s(addr))),
    );
}
pub unsafe fn instr32_0FBD_reg(r1: i32, r: i32) {
    write_reg32(r, bsr32(read_reg32(r), read_reg32(r1)));
}
pub unsafe fn instr16_0FBE_mem(addr: i32, r: i32) {
    write_reg16(r, return_on_pagefault!(safe_read8(addr)) << 24 >> 24);
}
pub unsafe fn instr16_0FBE_reg(r1: i32, r: i32) { write_reg16(r, read_reg8(r1) << 24 >> 24); }
pub unsafe fn instr32_0FBE_mem(addr: i32, r: i32) {
    write_reg32(r, return_on_pagefault!(safe_read8(addr)) << 24 >> 24);
}
pub unsafe fn instr32_0FBE_reg(r1: i32, r: i32) { write_reg32(r, read_reg8(r1) << 24 >> 24); }
pub unsafe fn instr16_0FBF_mem(addr: i32, r: i32) {
    write_reg16(r, return_on_pagefault!(safe_read16(addr)) << 16 >> 16);
}
pub unsafe fn instr16_0FBF_reg(r1: i32, r: i32) { write_reg16(r, read_reg16(r1) << 16 >> 16); }
pub unsafe fn instr32_0FBF_mem(addr: i32, r: i32) {
    write_reg32(r, return_on_pagefault!(safe_read16(addr)) << 16 >> 16);
}
pub unsafe fn instr32_0FBF_reg(r1: i32, r: i32) { write_reg32(r, read_reg16(r1) << 16 >> 16); }
#[no_mangle]
pub unsafe fn instr_0FC0_mem(addr: i32, r: i32) { safe_read_write8(addr, &|x| xadd8(x, r)) }
#[no_mangle]
pub unsafe fn instr_0FC0_reg(r1: i32, r: i32) { write_reg8(r1, xadd8(read_reg8(r1), r)); }
pub unsafe fn instr16_0FC1_mem(addr: i32, r: i32) { safe_read_write16(addr, &|x| xadd16(x, r)) }
pub unsafe fn instr16_0FC1_reg(r1: i32, r: i32) { write_reg16(r1, xadd16(read_reg16(r1), r)); }
pub unsafe fn instr32_0FC1_mem(addr: i32, r: i32) { safe_read_write32(addr, &|x| xadd32(x, r)) }
pub unsafe fn instr32_0FC1_reg(r1: i32, r: i32) { write_reg32(r1, xadd32(read_reg32(r1), r)); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_0FC2(source: reg128, r: i32, imm8: i32) -> bool {
    // cmpps xmm, xmm/m128, imm8
    sse_fp_arithmetic(0x0FC2, r, source.bits(), imm8)
}
pub unsafe fn instr_0FC2_reg(r1: i32, r2: i32, imm: i32) { instr_0FC2(read_xmm128s(r1), r2, imm); }
pub unsafe fn instr_0FC2_mem(addr: i32, r: i32, imm: i32) {
    instr_0FC2(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660FC2(source: reg128, r: i32, imm8: i32) -> bool {
    // cmppd xmm, xmm/m128, imm8
    sse_fp_arithmetic(0x660FC2, r, source.bits(), imm8)
}
pub unsafe fn instr_660FC2_reg(r1: i32, r2: i32, imm: i32) {
    instr_660FC2(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660FC2_mem(addr: i32, r: i32, imm: i32) {
    instr_660FC2(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20FC2(source: u64, r: i32, imm8: i32) -> bool {
    // cmpsd xmm, xmm/m64, imm8
    sse_fp_arithmetic(0xF20FC2, r, source as u128, imm8)
}
pub unsafe fn instr_F20FC2_reg(r1: i32, r2: i32, imm: i32) {
    instr_F20FC2(read_xmm64s(r1), r2, imm);
}
pub unsafe fn instr_F20FC2_mem(addr: i32, r: i32, imm: i32) {
    instr_F20FC2(return_on_pagefault!(safe_read64s(addr)), r, imm);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30FC2(source: i32, r: i32, imm8: i32) -> bool {
    // cmpss xmm, xmm/m32, imm8
    sse_fp_arithmetic(0xF30FC2, r, source as u32 as u128, imm8)
}
pub unsafe fn instr_F30FC2_reg(r1: i32, r2: i32, imm: i32) {
    instr_F30FC2(read_xmm64s(r1) as i32, r2, imm);
}
pub unsafe fn instr_F30FC2_mem(addr: i32, r: i32, imm: i32) {
    instr_F30FC2(return_on_pagefault!(safe_read32s(addr)), r, imm);
}

pub unsafe fn instr_0FC3_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_0FC3_mem(addr: i32, r: i32) {
    // movnti
    return_on_pagefault!(safe_write32(addr, read_reg32(r)));
}

#[no_mangle]
pub unsafe fn instr_0FC4(source: i32, r: i32, imm8: i32) {
    // pinsrw mm, r32/m16, imm8
    let mut destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    destination[(imm8 & 3) as usize] = source as u16;
    write_mmx_reg64(r, std::mem::transmute(destination));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FC4_reg(r1: i32, r2: i32, imm: i32) { instr_0FC4(read_reg32(r1), r2, imm); }
pub unsafe fn instr_0FC4_mem(addr: i32, r: i32, imm: i32) {
    instr_0FC4(return_on_pagefault!(safe_read16(addr)), r, imm);
}
pub unsafe fn instr_660FC4(source: i32, r: i32, imm8: i32) {
    // pinsrw xmm, r32/m16, imm8
    let mut destination = read_xmm128s(r);
    let index = (imm8 & 7) as u32;
    destination.u16[index as usize] = (source & 0xFFFF) as u16;
    write_xmm_reg128(r, destination);
}
pub unsafe fn instr_660FC4_reg(r1: i32, r2: i32, imm: i32) {
    instr_660FC4(read_reg32(r1), r2, imm);
}
pub unsafe fn instr_660FC4_mem(addr: i32, r: i32, imm: i32) {
    instr_660FC4(return_on_pagefault!(safe_read16(addr)), r, imm);
}
pub unsafe fn instr_0FC5_mem(_addr: i32, _r: i32, _imm8: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FC5_reg(r1: i32, r2: i32, imm8: i32) {
    // pextrw r32, mm, imm8
    let data: [u16; 4] = std::mem::transmute(read_mmx64s(r1));
    write_reg32(r2, data[(imm8 & 3) as usize] as i32);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_660FC5_mem(_addr: i32, _r: i32, _imm8: i32) { trigger_ud(); }
pub unsafe fn instr_660FC5_reg(r1: i32, r2: i32, imm8: i32) {
    // pextrw r32, xmm, imm8
    let data = read_xmm128s(r1);
    let index = (imm8 & 7) as u32;
    let result = data.u16[index as usize] as u32;
    write_reg32(r2, result as i32);
}

#[no_mangle]
pub unsafe fn instr_0FC6(source: reg128, r: i32, imm8: i32) {
    // shufps xmm, xmm/mem128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.u32[(imm8 & 3) as usize] as i32,
        destination.u32[(imm8 >> 2 & 3) as usize] as i32,
        source.u32[(imm8 >> 4 & 3) as usize] as i32,
        source.u32[(imm8 >> 6 & 3) as usize] as i32,
    );
}
pub unsafe fn instr_0FC6_reg(r1: i32, r2: i32, imm: i32) { instr_0FC6(read_xmm128s(r1), r2, imm); }
pub unsafe fn instr_0FC6_mem(addr: i32, r: i32, imm: i32) {
    instr_0FC6(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}

#[no_mangle]
pub unsafe fn instr_660FC6(source: reg128, r: i32, imm8: i32) {
    // shufpd xmm, xmm/mem128
    let destination = read_xmm128s(r);
    let result = reg128 {
        i64: [
            destination.i64[imm8 as usize & 1],
            source.i64[imm8 as usize >> 1 & 1],
        ],
    };
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FC6_reg(r1: i32, r2: i32, imm: i32) {
    instr_660FC6(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660FC6_mem(addr: i32, r: i32, imm: i32) {
    instr_660FC6(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}

pub unsafe fn instr16_0FC7_1_reg(_r: i32) { trigger_ud(); }
pub unsafe fn instr32_0FC7_1_reg(_r: i32) { trigger_ud(); }
pub unsafe fn instr16_0FC7_1_mem(addr: i32) {
    // cmpxchg8b
    return_on_pagefault!(writable_or_pagefault(addr, 8));
    if crate::parallel::active() {
        cmpxchg8b_locked(addr);
        return;
    }
    let m64 = safe_read64s(addr).unwrap();
    let m64_low = m64 as i32;
    let m64_high = (m64 >> 32) as i32;
    if read_reg32(EAX) == m64_low && read_reg32(EDX) == m64_high {
        *flags |= FLAG_ZERO;
        safe_write64(
            addr,
            read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32,
        )
        .unwrap();
    }
    else {
        *flags &= !FLAG_ZERO;
        // CMPXCHG8B performs a write cycle even when comparison fails. Besides
        // RAM permissions, this matters for MMIO devices observing writes and
        // for the shared code-page invalidation barrier. Both pages were
        // checked before the first read, so no partial operand can commit.
        safe_write64(addr, m64).unwrap();
        write_reg32(EAX, m64_low);
        write_reg32(EDX, m64_high);
    }
    *flags_changed &= !FLAG_ZERO;
}
pub unsafe fn instr32_0FC7_1_mem(addr: i32) { instr16_0FC7_1_mem(addr) }

/// CMPXCHG8B with other cores running in workers: one 8-byte compare-exchange
/// of RAM, including the write-back of the unchanged value on a mismatch
#[cold]
unsafe fn cmpxchg8b_locked(addr: i32) {
    if crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 {
        // (compatibility mode: x64::memory commits the locked operand)
        let _ = crate::x64::memory::run_locked(|| {
            let linear = addr as u32 as u64;
            let m64 = crate::x64::memory::read(linear, 64, false)?;
            let equal =
                m64 == read_reg32(EAX) as u32 as u64 | (read_reg32(EDX) as u32 as u64) << 32;
            let value = if equal {
                read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32
            }
            else {
                m64
            };
            crate::x64::memory::write(linear, 64, value, false)?;
            cmpxchg8b_result(equal, m64);
            Ok(())
        })
        .map_err(|fault| crate::x64::system::raise(fault));
        return;
    }
    if addr as u32 & 0xFFF > 0xFF8 {
        // split across pages: (not) atomic like the other split locked operations
        crate::parallel::split_lock().lock();
        let m64 = safe_read64s(addr).unwrap();
        let equal = m64 == read_reg32(EAX) as u32 as u64 | (read_reg32(EDX) as u32 as u64) << 32;
        let value = if equal {
            read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32
        }
        else {
            m64
        };
        safe_write64(addr, value).unwrap();
        crate::parallel::split_lock().unlock();
        cmpxchg8b_result(equal, m64);
        return;
    }
    let (phys, can_skip_dirty_page) = translate_address_write_and_can_skip_dirty(addr).unwrap();
    if crate::cpu::memory::in_mapped_range(phys) {
        let m64 = crate::cpu::memory::read64s(phys) as u64;
        let equal = m64 == read_reg32(EAX) as u32 as u64 | (read_reg32(EDX) as u32 as u64) << 32;
        let value = if equal {
            read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32
        }
        else {
            m64
        };
        crate::cpu::memory::mmap_write64(phys, value);
        cmpxchg8b_result(equal, m64);
        return;
    }
    if !can_skip_dirty_page {
        crate::jit::jit_dirty_page(crate::page::Page::page_of(phys));
    }
    loop {
        let m64 = crate::cpu::memory::read64_no_mmap_check(phys);
        let equal = m64 == read_reg32(EAX) as u32 as u64 | (read_reg32(EDX) as u32 as u64) << 32;
        let value = if equal {
            read_reg32(EBX) as u32 as u64 | (read_reg32(ECX) as u32 as u64) << 32
        }
        else {
            m64
        };
        if crate::cpu::memory::compare_exchange_no_mmap_or_dirty_check(phys, 8, m64, value) {
            cmpxchg8b_result(equal, m64);
            return;
        }
    }
}
unsafe fn cmpxchg8b_result(equal: bool, m64: u64) {
    if equal {
        *flags |= FLAG_ZERO;
    }
    else {
        *flags &= !FLAG_ZERO;
        write_reg32(EAX, m64 as i32);
        write_reg32(EDX, (m64 >> 32) as i32);
    }
    *flags_changed &= !FLAG_ZERO;
}

#[no_mangle]
pub unsafe fn instr16_0FC7_6_reg(r: i32) {
    // rdrand
    let rand = js::get_rand_int();
    write_reg16(r, rand);
    *flags &= !FLAGS_ALL;
    *flags |= 1;
    *flags_changed = 0;
}
#[no_mangle]
pub unsafe fn instr32_0FC7_6_reg(r: i32) {
    // rdrand
    let rand = js::get_rand_int();
    write_reg32(r, rand);
    *flags &= !FLAGS_ALL;
    *flags |= 1;
    *flags_changed = 0;
}

#[no_mangle]
pub unsafe fn instr16_0FC7_6_mem(_addr: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr32_0FC7_6_mem(_addr: i32) { trigger_ud(); }

#[no_mangle]
pub unsafe fn instr_0FC8() { bswap(EAX); }
#[no_mangle]
pub unsafe fn instr_0FC9() { bswap(ECX); }
#[no_mangle]
pub unsafe fn instr_0FCA() { bswap(EDX); }
#[no_mangle]
pub unsafe fn instr_0FCB() { bswap(EBX); }
#[no_mangle]
pub unsafe fn instr_0FCC() { bswap(ESP); }
#[no_mangle]
pub unsafe fn instr_0FCD() { bswap(EBP); }
#[no_mangle]
pub unsafe fn instr_0FCE() { bswap(ESI); }
#[no_mangle]
pub unsafe fn instr_0FCF() { bswap(EDI); }
#[no_mangle]
pub unsafe fn instr_0FD0() { trigger_ud(); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660FD0(source: reg128, r: i32) -> bool {
    // addsubpd xmm, xmm/m128
    sse_fp_arithmetic(0x660FD0, r, source.bits(), 0)
}
pub unsafe fn instr_660FD0_reg(r1: i32, r2: i32) { instr_660FD0(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD0_mem(addr: i32, r: i32) {
    if addr & 15 != 0 {
        trigger_gp(0);
        return;
    }
    instr_660FD0(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20FD0(source: reg128, r: i32) -> bool {
    // addsubps xmm, xmm/m128
    sse_fp_arithmetic(0xF20FD0, r, source.bits(), 0)
}
pub unsafe fn instr_F20FD0_reg(r1: i32, r2: i32) { instr_F20FD0(read_xmm128s(r1), r2); }
pub unsafe fn instr_F20FD0_mem(addr: i32, r: i32) {
    if addr & 15 != 0 {
        trigger_gp(0);
        return;
    }
    instr_F20FD0(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0FD1(source: u64, r: i32) {
    // psrlw mm, mm/m64
    psrlw_r64(r, source);
}
pub unsafe fn instr_0FD1_reg(r1: i32, r2: i32) { instr_0FD1(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD1_mem(addr: i32, r: i32) {
    instr_0FD1(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD1(source: reg128, r: i32) {
    // psrlw xmm, xmm/m128
    psrlw_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FD1_reg(r1: i32, r2: i32) { instr_660FD1(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD1_mem(addr: i32, r: i32) {
    instr_660FD1(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FD2(source: u64, r: i32) {
    // psrld mm, mm/m64
    psrld_r64(r, source);
}
pub unsafe fn instr_0FD2_reg(r1: i32, r2: i32) { instr_0FD2(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD2_mem(addr: i32, r: i32) {
    instr_0FD2(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD2(source: reg128, r: i32) {
    // psrld xmm, xmm/m128
    psrld_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FD2_reg(r1: i32, r2: i32) { instr_660FD2(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD2_mem(addr: i32, r: i32) {
    instr_660FD2(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FD3(source: u64, r: i32) {
    // psrlq mm, mm/m64
    psrlq_r64(r, source);
}
pub unsafe fn instr_0FD3_reg(r1: i32, r2: i32) { instr_0FD3(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD3_mem(addr: i32, r: i32) {
    instr_0FD3(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD3(source: reg128, r: i32) {
    // psrlq xmm, mm/m64
    psrlq_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FD3_reg(r1: i32, r2: i32) { instr_660FD3(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD3_mem(addr: i32, r: i32) {
    instr_660FD3(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FD4(source: u64, r: i32) {
    // paddq mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, source + destination);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FD4_reg(r1: i32, r2: i32) { instr_0FD4(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD4_mem(addr: i32, r: i32) {
    instr_0FD4(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD4(source: reg128, r: i32) {
    // paddq xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = destination.u64[0] + source.u64[0];
    result.u64[1] = destination.u64[1] + source.u64[1];
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FD4_reg(r1: i32, r2: i32) { instr_660FD4(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD4_mem(addr: i32, r: i32) {
    instr_660FD4(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FD5(source: u64, r: i32) {
    // pmullw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = destination[i] * source[i];
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FD5_reg(r1: i32, r2: i32) { instr_0FD5(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD5_mem(addr: i32, r: i32) {
    instr_0FD5(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD5(source: reg128, r: i32) {
    // pmullw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = destination.u16[i] * source.u16[i]
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FD5_reg(r1: i32, r2: i32) { instr_660FD5(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD5_mem(addr: i32, r: i32) {
    instr_660FD5(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0FD6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FD6_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660FD6_mem(addr: i32, r: i32) {
    // movq xmm/m64, xmm
    movl_r128_m64(addr, r);
}
pub unsafe fn instr_660FD6_reg(r1: i32, r2: i32) {
    // movq xmm/m64, xmm
    write_xmm128_2(r1, read_xmm64s(r2), 0);
}

#[no_mangle]
pub unsafe fn instr_F20FD6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_F20FD6_reg(r1: i32, r2: i32) {
    // movdq2q mm, xmm
    write_mmx_reg64(r2, read_xmm128s(r1).u64[0]);
    transition_fpu_to_mmx();
}
#[no_mangle]
pub unsafe fn instr_F30FD6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_F30FD6_reg(r1: i32, r2: i32) {
    // movq2dq xmm, mm
    let source = read_mmx64s(r1);
    write_xmm_reg128(r2, reg128 { u64: [source, 0] });
    transition_fpu_to_mmx();
}

pub unsafe fn instr_0FD7_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FD7(r1: i32) -> i32 {
    // pmovmskb r, mm
    let x: [u8; 8] = u64::to_le_bytes(read_mmx64s(r1));
    let mut result = 0;
    for i in 0..8 {
        result |= x[i] as i32 >> 7 << i
    }
    transition_fpu_to_mmx();
    result
}
pub unsafe fn instr_0FD7_reg(r1: i32, r2: i32) { write_reg32(r2, instr_0FD7(r1)); }
pub unsafe fn instr_660FD7_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_660FD7(r1: i32) -> i32 {
    // pmovmskb reg, xmm
    let x = read_xmm128s(r1);
    let mut result = 0;
    for i in 0..16 {
        result |= x.u8[i] as i32 >> 7 << i
    }
    result
}
pub unsafe fn instr_660FD7_reg(r1: i32, r2: i32) { write_reg32(r2, instr_660FD7(r1)) }
#[no_mangle]
pub unsafe fn instr_0FD8(source: u64, r: i32) {
    // psubusb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = saturate_sd_to_ub(destination[i] as i32 - source[i] as i32) as u8;
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FD8_reg(r1: i32, r2: i32) { instr_0FD8(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD8_mem(addr: i32, r: i32) {
    instr_0FD8(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD8(source: reg128, r: i32) {
    // psubusb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = saturate_sd_to_ub(destination.u8[i] as i32 - source.u8[i] as i32) as u8;
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FD8_reg(r1: i32, r2: i32) { instr_660FD8(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD8_mem(addr: i32, r: i32) {
    instr_660FD8(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FD9(source: u64, r: i32) {
    // psubusw mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = saturate_uw(destination[i] as u32 - source[i] as u32)
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FD9_reg(r1: i32, r2: i32) { instr_0FD9(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FD9_mem(addr: i32, r: i32) {
    instr_0FD9(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FD9(source: reg128, r: i32) {
    // psubusw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = saturate_uw(destination.u16[i] as u32 - source.u16[i] as u32)
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FD9_reg(r1: i32, r2: i32) { instr_660FD9(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FD9_mem(addr: i32, r: i32) {
    instr_660FD9(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDA(source: u64, r: i32) {
    // pminub mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = u8::min(source[i], destination[i])
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDA_reg(r1: i32, r2: i32) { instr_0FDA(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDA_mem(addr: i32, r: i32) {
    instr_0FDA(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDA(source: reg128, r: i32) {
    // pminub xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { u8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = u8::min(source.u8[i], destination.u8[i]);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FDA_reg(r1: i32, r2: i32) { instr_660FDA(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDA_mem(addr: i32, r: i32) {
    instr_660FDA(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDB(source: u64, r: i32) {
    // pand mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, source & destination);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDB_reg(r1: i32, r2: i32) { instr_0FDB(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDB_mem(addr: i32, r: i32) {
    instr_0FDB(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDB(source: reg128, r: i32) {
    // pand xmm, xmm/m128
    pand_r128(source, r);
}
pub unsafe fn instr_660FDB_reg(r1: i32, r2: i32) { instr_660FDB(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDB_mem(addr: i32, r: i32) {
    instr_660FDB(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDC(source: u64, r: i32) {
    // paddusb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = saturate_ud_to_ub(destination[i] as u32 + source[i] as u32);
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDC_reg(r1: i32, r2: i32) { instr_0FDC(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDC_mem(addr: i32, r: i32) {
    instr_0FDC(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDC(source: reg128, r: i32) {
    // paddusb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = saturate_ud_to_ub(source.u8[i] as u32 + destination.u8[i] as u32);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FDC_reg(r1: i32, r2: i32) { instr_660FDC(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDC_mem(addr: i32, r: i32) {
    instr_660FDC(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDD(source: u64, r: i32) {
    // paddusw mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = saturate_uw(destination[i] as u32 + source[i] as u32)
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDD_reg(r1: i32, r2: i32) { instr_0FDD(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDD_mem(addr: i32, r: i32) {
    instr_0FDD(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDD(source: reg128, r: i32) {
    // paddusw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = saturate_uw(source.u16[i] as u32 + destination.u16[i] as u32)
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FDD_reg(r1: i32, r2: i32) { instr_660FDD(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDD_mem(addr: i32, r: i32) {
    instr_660FDD(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDE(source: u64, r: i32) {
    // pmaxub mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = u8::max(source[i], destination[i])
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDE_reg(r1: i32, r2: i32) { instr_0FDE(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDE_mem(addr: i32, r: i32) {
    instr_0FDE(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDE(source: reg128, r: i32) {
    // pmaxub xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = u8::max(source.u8[i], destination.u8[i]);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FDE_reg(r1: i32, r2: i32) { instr_660FDE(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDE_mem(addr: i32, r: i32) {
    instr_660FDE(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FDF(source: u64, r: i32) {
    // pandn mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, source & !destination);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FDF_reg(r1: i32, r2: i32) { instr_0FDF(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FDF_mem(addr: i32, r: i32) {
    instr_0FDF(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FDF(source: reg128, r: i32) {
    // pandn xmm, xmm/m128
    pandn_r128(source, r);
}
pub unsafe fn instr_660FDF_reg(r1: i32, r2: i32) { instr_660FDF(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FDF_mem(addr: i32, r: i32) {
    instr_660FDF(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE0(source: u64, r: i32) {
    // pavgb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = (destination[i] as i32 + source[i] as i32 + 1 >> 1) as u8;
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE0_reg(r1: i32, r2: i32) { instr_0FE0(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE0_mem(addr: i32, r: i32) {
    instr_0FE0(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE0(source: reg128, r: i32) {
    // pavgb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = (destination.u8[i] as i32 + source.u8[i] as i32 + 1 >> 1) as u8;
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FE0_reg(r1: i32, r2: i32) { instr_660FE0(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE0_mem(addr: i32, r: i32) {
    instr_660FE0(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE1(source: u64, r: i32) {
    // psraw mm, mm/m64
    psraw_r64(r, source);
}
pub unsafe fn instr_0FE1_reg(r1: i32, r2: i32) { instr_0FE1(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE1_mem(addr: i32, r: i32) {
    instr_0FE1(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE1(source: reg128, r: i32) {
    // psraw xmm, xmm/m128
    psraw_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FE1_reg(r1: i32, r2: i32) { instr_660FE1(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE1_mem(addr: i32, r: i32) {
    instr_660FE1(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE2(source: u64, r: i32) {
    // psrad mm, mm/m64
    psrad_r64(r, source);
}
pub unsafe fn instr_0FE2_reg(r1: i32, r2: i32) { instr_0FE2(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE2_mem(addr: i32, r: i32) {
    instr_0FE2(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE2(source: reg128, r: i32) {
    // psrad xmm, xmm/m128
    psrad_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FE2_reg(r1: i32, r2: i32) { instr_660FE2(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE2_mem(addr: i32, r: i32) {
    instr_660FE2(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE3(source: u64, r: i32) {
    // pavgw mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = (destination[i] as i32 + source[i] as i32 + 1 >> 1) as u16
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE3_reg(r1: i32, r2: i32) { instr_0FE3(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE3_mem(addr: i32, r: i32) {
    instr_0FE3(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE3(source: reg128, r: i32) {
    // pavgw xmm, xmm/m128
    let mut destination = read_xmm128s(r);
    for i in 0..8 {
        destination.u16[i] = (destination.u16[i] as i32 + source.u16[i] as i32 + 1 >> 1) as u16;
    }
    write_xmm_reg128(r, destination);
}
pub unsafe fn instr_660FE3_reg(r1: i32, r2: i32) { instr_660FE3(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE3_mem(addr: i32, r: i32) {
    instr_660FE3(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE4(source: u64, r: i32) {
    // pmulhuw mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = ((destination[i] as i32 * source[i] as i32) >> 16) as u16
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE4_reg(r1: i32, r2: i32) { instr_0FE4(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE4_mem(addr: i32, r: i32) {
    instr_0FE4(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE4(source: reg128, r: i32) {
    // pmulhuw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = (source.u16[i] as i32 * destination.u16[i] as i32 >> 16) as u16;
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FE4_reg(r1: i32, r2: i32) { instr_660FE4(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE4_mem(addr: i32, r: i32) {
    instr_660FE4(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE5(source: u64, r: i32) {
    // pmulhw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = ((destination[i] as i32 * source[i] as i32) >> 16) as i16
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE5_reg(r1: i32, r2: i32) { instr_0FE5(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE5_mem(addr: i32, r: i32) {
    instr_0FE5(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE5(source: reg128, r: i32) {
    // pmulhw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = (destination.i16[i] as i32 * source.i16[i] as i32 >> 16) as u16
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FE5_reg(r1: i32, r2: i32) { instr_660FE5(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE5_mem(addr: i32, r: i32) {
    instr_660FE5(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

#[no_mangle]
pub unsafe fn instr_0FE6_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn instr_0FE6_reg(_r1: i32, _r2: i32) { trigger_ud(); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_660FE6(source: reg128, r: i32) -> bool {
    // cvttpd2dq xmm, xmm/m128
    match sse_fp_convert(0x660FE6, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_660FE6_mem(addr: i32, r: i32) {
    instr_660FE6(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_660FE6_reg(r1: i32, r2: i32) { instr_660FE6(read_xmm128s(r1), r2); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F20FE6(source: reg128, r: i32) -> bool {
    // cvtpd2dq xmm, xmm/m128
    match sse_fp_convert(0xF20FE6, r, source.bits()) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F20FE6_mem(addr: i32, r: i32) {
    instr_F20FE6(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
pub unsafe fn instr_F20FE6_reg(r1: i32, r2: i32) { instr_F20FE6(read_xmm128s(r1), r2); }

#[no_mangle]
#[inline(never)]
pub unsafe fn instr_F30FE6(source: u64, r: i32) -> bool {
    // cvtdq2pd xmm, xmm/m64
    match sse_fp_convert(0xF30FE6, r, source as u128) {
        Some(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        None => false,
    }
}
pub unsafe fn instr_F30FE6_mem(addr: i32, r: i32) {
    instr_F30FE6(return_on_pagefault!(safe_read64s(addr)), r);
}
pub unsafe fn instr_F30FE6_reg(r1: i32, r2: i32) { instr_F30FE6(read_xmm64s(r1), r2); }

#[no_mangle]
pub unsafe fn instr_0FE7_mem(addr: i32, r: i32) {
    // movntq m64, mm
    mov_r_m64(addr, r);
}
#[no_mangle]
pub unsafe fn instr_0FE7_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660FE7_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660FE7_mem(addr: i32, r: i32) {
    // movntdq m128, xmm
    mov_r_m128_aligned(addr, r);
}
#[no_mangle]
pub unsafe fn instr_0FE8(source: u64, r: i32) {
    // psubsb mm, mm/m64
    let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r));
    let source: [i8; 8] = std::mem::transmute(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = saturate_sd_to_sb(destination[i] as u32 - source[i] as u32);
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE8_reg(r1: i32, r2: i32) { instr_0FE8(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE8_mem(addr: i32, r: i32) {
    instr_0FE8(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE8(source: reg128, r: i32) {
    // psubsb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.i8[i] = saturate_sd_to_sb(destination.i8[i] as u32 - source.i8[i] as u32);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FE8_reg(r1: i32, r2: i32) { instr_660FE8(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE8_mem(addr: i32, r: i32) {
    instr_660FE8(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FE9(source: u64, r: i32) {
    // psubsw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = saturate_sd_to_sw(destination[i] as u32 - source[i] as u32)
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FE9_reg(r1: i32, r2: i32) { instr_0FE9(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FE9_mem(addr: i32, r: i32) {
    instr_0FE9(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FE9(source: reg128, r: i32) {
    // psubsw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = saturate_sd_to_sw(destination.i16[i] as u32 - source.i16[i] as u32)
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FE9_reg(r1: i32, r2: i32) { instr_660FE9(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FE9_mem(addr: i32, r: i32) {
    instr_660FE9(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FEA(source: u64, r: i32) {
    // pminsw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = i16::min(destination[i], source[i])
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FEA_reg(r1: i32, r2: i32) { instr_0FEA(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FEA_mem(addr: i32, r: i32) {
    instr_0FEA(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FEA(source: reg128, r: i32) {
    // pminsw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.i16[i] = i16::min(destination.i16[i], source.i16[i])
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FEA_reg(r1: i32, r2: i32) { instr_660FEA(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FEA_mem(addr: i32, r: i32) {
    instr_660FEA(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FEB(source: u64, r: i32) {
    // por mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, source | destination);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FEB_reg(r1: i32, r2: i32) { instr_0FEB(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FEB_mem(addr: i32, r: i32) {
    instr_0FEB(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FEB(source: reg128, r: i32) {
    // por xmm, xmm/m128
    por_r128(source, r);
}
pub unsafe fn instr_660FEB_reg(r1: i32, r2: i32) { instr_660FEB(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FEB_mem(addr: i32, r: i32) {
    instr_660FEB(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FEC(source: u64, r: i32) {
    // paddsb mm, mm/m64
    let destination: [i8; 8] = std::mem::transmute(read_mmx64s(r));
    let source: [i8; 8] = std::mem::transmute(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = saturate_sd_to_sb(destination[i] as u32 + source[i] as u32);
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FEC_reg(r1: i32, r2: i32) { instr_0FEC(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FEC_mem(addr: i32, r: i32) {
    instr_0FEC(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FEC(source: reg128, r: i32) {
    // paddsb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.i8[i] = saturate_sd_to_sb(destination.i8[i] as u32 + source.i8[i] as u32);
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FEC_reg(r1: i32, r2: i32) { instr_660FEC(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FEC_mem(addr: i32, r: i32) {
    instr_660FEC(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FED(source: u64, r: i32) {
    // paddsw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = saturate_sd_to_sw(destination[i] as u32 + source[i] as u32)
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FED_reg(r1: i32, r2: i32) { instr_0FED(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FED_mem(addr: i32, r: i32) {
    instr_0FED(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FED(source: reg128, r: i32) {
    // paddsw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = saturate_sd_to_sw(destination.i16[i] as u32 + source.i16[i] as u32)
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FED_reg(r1: i32, r2: i32) { instr_660FED(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FED_mem(addr: i32, r: i32) {
    instr_660FED(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FEE(source: u64, r: i32) {
    // pmaxsw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = i16::max(destination[i], source[i])
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FEE_reg(r1: i32, r2: i32) { instr_0FEE(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FEE_mem(addr: i32, r: i32) {
    instr_0FEE(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FEE(source: reg128, r: i32) {
    // pmaxsw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.i16[i] = i16::max(destination.i16[i], source.i16[i])
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FEE_reg(r1: i32, r2: i32) { instr_660FEE(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FEE_mem(addr: i32, r: i32) {
    instr_660FEE(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FEF(source: u64, r: i32) {
    // pxor mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, source ^ destination);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FEF_reg(r1: i32, r2: i32) { instr_0FEF(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FEF_mem(addr: i32, r: i32) {
    instr_0FEF(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FEF(source: reg128, r: i32) {
    // pxor xmm, xmm/m128
    pxor_r128(source, r);
}
pub unsafe fn instr_660FEF_reg(r1: i32, r2: i32) { instr_660FEF(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FEF_mem(addr: i32, r: i32) {
    instr_660FEF(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF0() { trigger_ud(); }

pub unsafe fn instr_F20FF0_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_F20FF0_mem(addr: i32, r: i32) {
    // LDDQU is a memory-only, unaligned 128-bit load.
    write_xmm_reg128(r, return_on_pagefault!(safe_read128s(addr)));
}

#[no_mangle]
pub unsafe fn instr_0FF1(source: u64, r: i32) {
    // psllw mm, mm/m64
    psllw_r64(r, source);
}
pub unsafe fn instr_0FF1_reg(r1: i32, r2: i32) { instr_0FF1(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF1_mem(addr: i32, r: i32) {
    instr_0FF1(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF1(source: reg128, r: i32) {
    // psllw xmm, xmm/m128
    psllw_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FF1_reg(r1: i32, r2: i32) { instr_660FF1(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF1_mem(addr: i32, r: i32) {
    instr_660FF1(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF2(source: u64, r: i32) {
    // pslld mm, mm/m64
    pslld_r64(r, source);
}
pub unsafe fn instr_0FF2_reg(r1: i32, r2: i32) { instr_0FF2(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF2_mem(addr: i32, r: i32) {
    instr_0FF2(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF2(source: reg128, r: i32) {
    // pslld xmm, xmm/m128
    pslld_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FF2_reg(r1: i32, r2: i32) { instr_660FF2(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF2_mem(addr: i32, r: i32) {
    instr_660FF2(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF3(source: u64, r: i32) {
    // psllq mm, mm/m64
    psllq_r64(r, source);
}
pub unsafe fn instr_0FF3_reg(r1: i32, r2: i32) { instr_0FF3(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF3_mem(addr: i32, r: i32) {
    instr_0FF3(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF3(source: reg128, r: i32) {
    // psllq xmm, xmm/m128
    psllq_r128(r, source.u64[0]);
}
pub unsafe fn instr_660FF3_reg(r1: i32, r2: i32) { instr_660FF3(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF3_mem(addr: i32, r: i32) {
    instr_660FF3(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF4(source: u64, r: i32) {
    // pmuludq mm, mm/m64
    let destination = read_mmx64s(r);
    write_mmx_reg64(r, (source as u32 as u64) * (destination as u32 as u64));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF4_reg(r1: i32, r2: i32) { instr_0FF4(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF4_mem(addr: i32, r: i32) {
    instr_0FF4(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF4(source: reg128, r: i32) {
    // pmuludq xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = source.u32[0] as u64 * destination.u32[0] as u64;
    result.u64[1] = source.u32[2] as u64 * destination.u32[2] as u64;
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FF4_reg(r1: i32, r2: i32) { instr_660FF4(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF4_mem(addr: i32, r: i32) {
    instr_660FF4(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF5(source: u64, r: i32) {
    // pmaddwd mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mul0 = destination[0] as i32 * source[0] as i32;
    let mul1 = destination[1] as i32 * source[1] as i32;
    let mul2 = destination[2] as i32 * source[2] as i32;
    let mul3 = destination[3] as i32 * source[3] as i32;
    let low = mul0 + mul1;
    let high = mul2 + mul3;
    write_mmx_reg64(r, low as u32 as u64 | (high as u64) << 32);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF5_reg(r1: i32, r2: i32) { instr_0FF5(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF5_mem(addr: i32, r: i32) {
    instr_0FF5(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF5(source: reg128, r: i32) {
    // pmaddwd xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..4 {
        result.i32[i] = destination.i16[2 * i] as i32 * source.i16[2 * i] as i32
            + destination.i16[2 * i + 1] as i32 * source.i16[2 * i + 1] as i32
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FF5_reg(r1: i32, r2: i32) { instr_660FF5(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF5_mem(addr: i32, r: i32) {
    instr_660FF5(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF6(source: u64, r: i32) {
    // psadbw mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut sum = 0;
    for i in 0..8 {
        sum += (destination[i] as i32 - source[i] as i32).abs() as u64;
    }
    write_mmx_reg64(r, sum);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF6_reg(r1: i32, r2: i32) { instr_0FF6(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF6_mem(addr: i32, r: i32) {
    instr_0FF6(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF6(source: reg128, r: i32) {
    // psadbw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut sum0 = 0;
    let mut sum1 = 0;
    for i in 0..8 {
        sum0 += (destination.u8[i + 0] as i32 - source.u8[i + 0] as i32).abs() as u32;
        sum1 += (destination.u8[i + 8] as i32 - source.u8[i + 8] as i32).abs() as u32;
    }
    write_xmm128(r, sum0 as i32, 0, sum1 as i32, 0);
}
pub unsafe fn instr_660FF6_reg(r1: i32, r2: i32) { instr_660FF6(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF6_mem(addr: i32, r: i32) {
    instr_660FF6(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}

pub unsafe fn instr_0FF7_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn maskmovq(r1: i32, r2: i32, addr: i32) {
    // maskmovq mm, mm
    // the caller must have called writable_or_pagefault
    let source: [u8; 8] = u64::to_le_bytes(read_mmx64s(r2));
    let mask: [u8; 8] = u64::to_le_bytes(read_mmx64s(r1));
    for i in 0..8 {
        if 0 != mask[i] & 0x80 {
            safe_write8(addr + i as i32, source[i] as i32).unwrap();
        }
    }
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF7_reg(r1: i32, r2: i32) {
    let addr = return_on_pagefault!(get_seg_prefix_ds(get_reg_asize(EDI)));
    return_on_pagefault!(writable_or_pagefault(addr, 8));
    maskmovq(r1, r2, addr)
}

pub unsafe fn instr_660FF7_mem(_addr: i32, _r: i32) { trigger_ud(); }
#[no_mangle]
pub unsafe fn maskmovdqu(r1: i32, r2: i32, addr: i32) {
    // maskmovdqu xmm, xmm
    // the caller must have called writable_or_pagefault
    let source = read_xmm128s(r2);
    let mask = read_xmm128s(r1);
    for i in 0..16 {
        if 0 != mask.u8[i] & 0x80 {
            safe_write8(addr + i as i32, source.u8[i] as i32).unwrap();
        }
    }
}
pub unsafe fn instr_660FF7_reg(r1: i32, r2: i32) {
    let addr = return_on_pagefault!(get_seg_prefix_ds(get_reg_asize(EDI)));
    return_on_pagefault!(writable_or_pagefault(addr, 16));
    maskmovdqu(r1, r2, addr)
}
#[no_mangle]
pub unsafe fn instr_0FF8(source: u64, r: i32) {
    // psubb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = destination[i] - source[i];
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF8_reg(r1: i32, r2: i32) { instr_0FF8(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF8_mem(addr: i32, r: i32) {
    instr_0FF8(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF8(source: reg128, r: i32) {
    // psubb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = destination.u8[i] - source.u8[i];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FF8_reg(r1: i32, r2: i32) { instr_660FF8(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF8_mem(addr: i32, r: i32) {
    instr_660FF8(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FF9(source: u64, r: i32) {
    // psubw mm, mm/m64
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [i16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = destination[i] - source[i]
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FF9_reg(r1: i32, r2: i32) { instr_0FF9(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FF9_mem(addr: i32, r: i32) {
    instr_0FF9(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FF9(source: reg128, r: i32) {
    // psubw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.i16[i] = destination.i16[i] - source.i16[i]
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FF9_reg(r1: i32, r2: i32) { instr_660FF9(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FF9_mem(addr: i32, r: i32) {
    instr_660FF9(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFA(source: u64, r: i32) {
    // psubd mm, mm/m64
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let source: [i32; 2] = std::mem::transmute(source);
    let mut result = [0; 2];
    for i in 0..2 {
        result[i] = destination[i] - source[i]
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FFA_reg(r1: i32, r2: i32) { instr_0FFA(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FFA_mem(addr: i32, r: i32) {
    instr_0FFA(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FFA(source: reg128, r: i32) {
    // psubd xmm, xmm/m128
    let destination = read_xmm128s(r);
    write_xmm128(
        r,
        destination.i32[0] - source.i32[0],
        destination.i32[1] - source.i32[1],
        destination.i32[2] - source.i32[2],
        destination.i32[3] - source.i32[3],
    );
}
pub unsafe fn instr_660FFA_reg(r1: i32, r2: i32) { instr_660FFA(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FFA_mem(addr: i32, r: i32) {
    instr_660FFA(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFB(source: u64, r: i32) {
    // psubq mm, mm/m64
    write_mmx_reg64(r, read_mmx64s(r) - source);
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FFB_reg(r1: i32, r2: i32) { instr_0FFB(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FFB_mem(addr: i32, r: i32) {
    instr_0FFB(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FFB(source: reg128, r: i32) {
    // psubq xmm, xmm/m128
    let mut destination = read_xmm128s(r);
    destination.u64[0] = destination.u64[0] - source.u64[0];
    destination.u64[1] = destination.u64[1] - source.u64[1];
    write_xmm_reg128(r, destination);
}
pub unsafe fn instr_660FFB_reg(r1: i32, r2: i32) { instr_660FFB(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FFB_mem(addr: i32, r: i32) {
    instr_660FFB(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFC(source: u64, r: i32) {
    // paddb mm, mm/m64
    let destination: [u8; 8] = u64::to_le_bytes(read_mmx64s(r));
    let source: [u8; 8] = u64::to_le_bytes(source);
    let mut result = [0; 8];
    for i in 0..8 {
        result[i] = destination[i] + source[i];
    }
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FFC_reg(r1: i32, r2: i32) { instr_0FFC(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FFC_mem(addr: i32, r: i32) {
    instr_0FFC(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FFC(source: reg128, r: i32) {
    // paddb xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..16 {
        result.u8[i] = destination.u8[i] + source.u8[i];
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FFC_reg(r1: i32, r2: i32) { instr_660FFC(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FFC_mem(addr: i32, r: i32) {
    instr_660FFC(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFD(source: u64, r: i32) {
    // paddw mm, mm/m64
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let source: [u16; 4] = std::mem::transmute(source);
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = destination[i] + source[i]
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FFD_reg(r1: i32, r2: i32) { instr_0FFD(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FFD_mem(addr: i32, r: i32) {
    instr_0FFD(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FFD(source: reg128, r: i32) {
    // paddw xmm, xmm/m128
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    for i in 0..8 {
        result.u16[i] = (destination.u16[i] as i32 + source.u16[i] as i32 & 0xFFFF) as u16;
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn instr_660FFD_reg(r1: i32, r2: i32) { instr_660FFD(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FFD_mem(addr: i32, r: i32) {
    instr_660FFD(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFE(source: u64, r: i32) {
    // paddd mm, mm/m64
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let source: [i32; 2] = std::mem::transmute(source);
    let mut result = [0; 2];
    for i in 0..2 {
        result[i] = destination[i] + source[i]
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0FFE_reg(r1: i32, r2: i32) { instr_0FFE(read_mmx64s(r1), r2); }
pub unsafe fn instr_0FFE_mem(addr: i32, r: i32) {
    instr_0FFE(return_on_pagefault!(safe_read64s(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_660FFE(source: reg128, r: i32) {
    // paddd xmm, xmm/m128
    let destination = read_xmm128s(r);
    let dword0 = destination.i32[0] + source.i32[0];
    let dword1 = destination.i32[1] + source.i32[1];
    let dword2 = destination.i32[2] + source.i32[2];
    let dword3 = destination.i32[3] + source.i32[3];
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn instr_660FFE_reg(r1: i32, r2: i32) { instr_660FFE(read_xmm128s(r1), r2); }
pub unsafe fn instr_660FFE_mem(addr: i32, r: i32) {
    instr_660FFE(return_on_pagefault!(safe_read128s_aligned(addr)), r);
}
#[no_mangle]
pub unsafe fn instr_0FFF() {
    // Windows 98
    dbg_log!("#ud: 0F FF");
    trigger_ud();
}
                                                                                                                                        source/v64/src/rust/cpu/instructions_0f38.rs                                                        0000644 0000000 0000000 00000023317 00000000000 016117  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_snake_case)]
//! The opcode map 0F 38 (src/rust/gen/interpreter0f38.rs calls these). The
//! semantics are in crate::cpu::simd_int, shared with the IR and x64 engines.

use crate::cpu::cpu::*;
use crate::cpu::global_pointers::{flags, flags_changed};
use crate::cpu::simd_int;
use crate::paging::OrPageFault;

/// An SSSE3 MMX form: mm, mm/m64
pub unsafe fn ssse3_mmx(op: u8, source: u64, r: i32) {
    let destination = read_mmx64s(r).to_le_bytes();
    let result = simd_int::ssse3(op, destination, source.to_le_bytes());
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
/// An SSSE3 XMM form: xmm, xmm/m128 (aligned)
pub unsafe fn ssse3_xmm(op: u8, source: reg128, r: i32) {
    let destination = read_xmm128s(r);
    write_xmm_reg128(
        r,
        reg128 {
            u8: simd_int::ssse3(op, destination.u8, source.u8),
        },
    );
}

macro_rules! ssse3 {
    ($($op:literal $mmx:ident $mmx_reg:ident $mmx_mem:ident $xmm:ident $xmm_reg:ident $xmm_mem:ident;)*) => {$(
        pub unsafe fn $mmx(source: u64, r: i32) { ssse3_mmx($op, source, r) }
        pub unsafe fn $mmx_reg(r1: i32, r2: i32) { $mmx(read_mmx64s(r1), r2) }
        pub unsafe fn $mmx_mem(addr: i32, r: i32) { $mmx(return_on_pagefault!(safe_read64s(addr)), r) }
        pub unsafe fn $xmm(source: reg128, r: i32) { ssse3_xmm($op, source, r) }
        pub unsafe fn $xmm_reg(r1: i32, r2: i32) { $xmm(read_xmm128s(r1), r2) }
        pub unsafe fn $xmm_mem(addr: i32, r: i32) { $xmm(return_on_pagefault!(safe_read128s_aligned(addr)), r) }
    )*};
}
ssse3! {
    0x00 instr_0F3800 instr_0F3800_reg instr_0F3800_mem instr_660F3800 instr_660F3800_reg instr_660F3800_mem; // pshufb
    0x01 instr_0F3801 instr_0F3801_reg instr_0F3801_mem instr_660F3801 instr_660F3801_reg instr_660F3801_mem; // phaddw
    0x02 instr_0F3802 instr_0F3802_reg instr_0F3802_mem instr_660F3802 instr_660F3802_reg instr_660F3802_mem; // phaddd
    0x03 instr_0F3803 instr_0F3803_reg instr_0F3803_mem instr_660F3803 instr_660F3803_reg instr_660F3803_mem; // phaddsw
    0x04 instr_0F3804 instr_0F3804_reg instr_0F3804_mem instr_660F3804 instr_660F3804_reg instr_660F3804_mem; // pmaddubsw
    0x05 instr_0F3805 instr_0F3805_reg instr_0F3805_mem instr_660F3805 instr_660F3805_reg instr_660F3805_mem; // phsubw
    0x06 instr_0F3806 instr_0F3806_reg instr_0F3806_mem instr_660F3806 instr_660F3806_reg instr_660F3806_mem; // phsubd
    0x07 instr_0F3807 instr_0F3807_reg instr_0F3807_mem instr_660F3807 instr_660F3807_reg instr_660F3807_mem; // phsubsw
    0x08 instr_0F3808 instr_0F3808_reg instr_0F3808_mem instr_660F3808 instr_660F3808_reg instr_660F3808_mem; // psignb
    0x09 instr_0F3809 instr_0F3809_reg instr_0F3809_mem instr_660F3809 instr_660F3809_reg instr_660F3809_mem; // psignw
    0x0A instr_0F380A instr_0F380A_reg instr_0F380A_mem instr_660F380A instr_660F380A_reg instr_660F380A_mem; // psignd
    0x0B instr_0F380B instr_0F380B_reg instr_0F380B_mem instr_660F380B instr_660F380B_reg instr_660F380B_mem; // pmulhrsw
    0x1C instr_0F381C instr_0F381C_reg instr_0F381C_mem instr_660F381C instr_660F381C_reg instr_660F381C_mem; // pabsb
    0x1D instr_0F381D instr_0F381D_reg instr_0F381D_mem instr_660F381D instr_660F381D_reg instr_660F381D_mem; // pabsw
    0x1E instr_0F381E instr_0F381E_reg instr_0F381E_mem instr_660F381E instr_660F381E_reg instr_660F381E_mem; // pabsd
}

/// The bytes the memory form of 66 0F 38 `op` (simd_int::sse4) reads:
/// PMOVSX/PMOVZX only what they extend (no alignment), the others an m128
pub fn sse4_source_bytes(op: u8) -> u8 {
    match op {
        0x20..=0x25 | 0x30..=0x35 => [8, 4, 2, 8, 4, 8][(op & 7) as usize],
        _ => 16,
    }
}
/// The memory source of 66 0F 38 `op`: an aligned m128, or its low bytes
pub unsafe fn sse4_source(op: u8, addr: i32) -> OrPageFault<reg128> {
    Ok(match sse4_source_bytes(op) {
        16 => safe_read128s_aligned(addr)?,
        2 => reg128 {
            u64: [safe_read16(addr)? as u16 as u64, 0],
        },
        4 => reg128 {
            u64: [safe_read32s(addr)? as u32 as u64, 0],
        },
        _ => reg128 {
            u64: [safe_read64s(addr)?, 0],
        },
    })
}
/// An SSE4.1/SSE4.2 form of simd_int::sse4: xmm, xmm/m128 (BLENDV: the mask in XMM0)
pub unsafe fn sse4_xmm(op: u8, source: reg128, r: i32) {
    let result = simd_int::sse4(op, read_xmm128s(r).u8, source.u8, read_xmm128s(0).u8);
    write_xmm_reg128(r, reg128 { u8: result });
}

macro_rules! sse4 {
    ($($op:literal $xmm:ident $xmm_reg:ident $xmm_mem:ident;)*) => {$(
        pub unsafe fn $xmm(source: reg128, r: i32) { sse4_xmm($op, source, r) }
        pub unsafe fn $xmm_reg(r1: i32, r2: i32) { $xmm(read_xmm128s(r1), r2) }
        pub unsafe fn $xmm_mem(addr: i32, r: i32) { $xmm(return_on_pagefault!(sse4_source($op, addr)), r) }
    )*};
}
sse4! {
    0x10 instr_660F3810 instr_660F3810_reg instr_660F3810_mem; // pblendvb
    0x14 instr_660F3814 instr_660F3814_reg instr_660F3814_mem; // blendvps
    0x15 instr_660F3815 instr_660F3815_reg instr_660F3815_mem; // blendvpd
    0x20 instr_660F3820 instr_660F3820_reg instr_660F3820_mem; // pmovsxbw
    0x21 instr_660F3821 instr_660F3821_reg instr_660F3821_mem; // pmovsxbd
    0x22 instr_660F3822 instr_660F3822_reg instr_660F3822_mem; // pmovsxbq
    0x23 instr_660F3823 instr_660F3823_reg instr_660F3823_mem; // pmovsxwd
    0x24 instr_660F3824 instr_660F3824_reg instr_660F3824_mem; // pmovsxwq
    0x25 instr_660F3825 instr_660F3825_reg instr_660F3825_mem; // pmovsxdq
    0x28 instr_660F3828 instr_660F3828_reg instr_660F3828_mem; // pmuldq
    0x29 instr_660F3829 instr_660F3829_reg instr_660F3829_mem; // pcmpeqq
    0x2B instr_660F382B instr_660F382B_reg instr_660F382B_mem; // packusdw
    0x30 instr_660F3830 instr_660F3830_reg instr_660F3830_mem; // pmovzxbw
    0x31 instr_660F3831 instr_660F3831_reg instr_660F3831_mem; // pmovzxbd
    0x32 instr_660F3832 instr_660F3832_reg instr_660F3832_mem; // pmovzxbq
    0x33 instr_660F3833 instr_660F3833_reg instr_660F3833_mem; // pmovzxwd
    0x34 instr_660F3834 instr_660F3834_reg instr_660F3834_mem; // pmovzxwq
    0x35 instr_660F3835 instr_660F3835_reg instr_660F3835_mem; // pmovzxdq
    0x37 instr_660F3837 instr_660F3837_reg instr_660F3837_mem; // pcmpgtq (SSE4.2)
    0x38 instr_660F3838 instr_660F3838_reg instr_660F3838_mem; // pminsb
    0x39 instr_660F3839 instr_660F3839_reg instr_660F3839_mem; // pminsd
    0x3A instr_660F383A instr_660F383A_reg instr_660F383A_mem; // pminuw
    0x3B instr_660F383B instr_660F383B_reg instr_660F383B_mem; // pminud
    0x3C instr_660F383C instr_660F383C_reg instr_660F383C_mem; // pmaxsb
    0x3D instr_660F383D instr_660F383D_reg instr_660F383D_mem; // pmaxsd
    0x3E instr_660F383E instr_660F383E_reg instr_660F383E_mem; // pmaxuw
    0x3F instr_660F383F instr_660F383F_reg instr_660F383F_mem; // pmaxud
    0x40 instr_660F3840 instr_660F3840_reg instr_660F3840_mem; // pmulld
    0x41 instr_660F3841 instr_660F3841_reg instr_660F3841_mem; // phminposuw
}

pub unsafe fn instr_660F3817(source: reg128, r: i32) {
    // ptest xmm, xmm/m128: ZF and CF, the other arithmetic flags cleared
    let (zero, carry) = simd_int::ptest(read_xmm128s(r).u8, source.u8);
    *flags_changed = 0;
    *flags =
        *flags & !FLAGS_ALL | if zero { FLAG_ZERO } else { 0 } | if carry { FLAG_CARRY } else { 0 };
}
pub unsafe fn instr_660F3817_reg(r1: i32, r2: i32) { instr_660F3817(read_xmm128s(r1), r2) }
pub unsafe fn instr_660F3817_mem(addr: i32, r: i32) {
    instr_660F3817(return_on_pagefault!(safe_read128s_aligned(addr)), r)
}

pub unsafe fn instr_660F382A_reg(_r1: i32, _r2: i32) { trigger_ud(); }
pub unsafe fn instr_660F382A_mem(addr: i32, r: i32) {
    // movntdqa xmm, m128
    write_xmm_reg128(r, return_on_pagefault!(safe_read128s_aligned(addr)));
}

/// CRC32 r32, r/m8 (F2 0F 38 F0), r/m16 (66 F2 0F 38 F1), r/m32 (F2 0F 38
/// F1): the low `bytes` of `value` into the CRC-32C in `r` (simd_int::crc32c);
/// no flags, no XMM state checks
pub unsafe fn crc32(r: i32, value: u32, bytes: u32) {
    write_reg32(
        r,
        simd_int::crc32c(read_reg32(r) as u32, value as u64, bytes) as i32,
    );
}
// MOVBE (0F 38 F0: load, F1: store; memory only): one access of the operand
// size, its bytes reversed
pub unsafe fn instr16_0F38F0_mem(addr: i32, r: i32) {
    let value = return_on_pagefault!(safe_read16(addr)) as u64;
    write_reg16(r, crate::cpu::bmi::byte_swap(value, 16) as i32);
}
pub unsafe fn instr32_0F38F0_mem(addr: i32, r: i32) {
    let value = return_on_pagefault!(safe_read32s(addr)) as u32 as u64;
    write_reg32(r, crate::cpu::bmi::byte_swap(value, 32) as i32);
}
pub unsafe fn instr16_0F38F1_mem(addr: i32, r: i32) {
    let value = crate::cpu::bmi::byte_swap(read_reg16(r) as u64, 16) as i32;
    return_on_pagefault!(safe_write16(addr, value));
}
pub unsafe fn instr32_0F38F1_mem(addr: i32, r: i32) {
    let value = crate::cpu::bmi::byte_swap(read_reg32(r) as u32 as u64, 32) as i32;
    return_on_pagefault!(safe_write32(addr, value));
}
pub unsafe fn instr16_0F38F0_reg(_r1: i32, _r: i32) { trigger_ud() }
pub unsafe fn instr32_0F38F0_reg(_r1: i32, _r: i32) { trigger_ud() }
pub unsafe fn instr16_0F38F1_reg(_r1: i32, _r: i32) { trigger_ud() }
pub unsafe fn instr32_0F38F1_reg(_r1: i32, _r: i32) { trigger_ud() }
pub unsafe fn instr_F20F38F0_reg(r1: i32, r: i32) { crc32(r, read_reg8(r1) as u32, 1) }
pub unsafe fn instr_F20F38F0_mem(addr: i32, r: i32) {
    crc32(r, return_on_pagefault!(safe_read8(addr)) as u32, 1)
}
pub unsafe fn instr16_F20F38F1_reg(r1: i32, r: i32) { crc32(r, read_reg16(r1) as u32, 2) }
pub unsafe fn instr16_F20F38F1_mem(addr: i32, r: i32) {
    crc32(r, return_on_pagefault!(safe_read16(addr)) as u32, 2)
}
pub unsafe fn instr32_F20F38F1_reg(r1: i32, r: i32) { crc32(r, read_reg32(r1) as u32, 4) }
pub unsafe fn instr32_F20F38F1_mem(addr: i32, r: i32) {
    crc32(r, return_on_pagefault!(safe_read32s(addr)) as u32, 4)
}
                                                                                                                                                                                                                                                                                                                 source/v64/src/rust/cpu/instructions_0f3a.rs                                                        0000644 0000000 0000000 00000022616 00000000000 016171  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_snake_case)]
//! The opcode map 0F 3A (src/rust/gen/interpreter0f3a.rs calls these). The
//! semantics are in crate::cpu::simd_int, shared with the IR and x64 engines.

use crate::cpu::cpu::*;
use crate::cpu::global_pointers::{flags, flags_changed};
use crate::cpu::simd_int;
use crate::cpu::sse_instr::{sse_fp_dot_product, sse_fp_round};

pub unsafe fn instr_0F3A0F(source: u64, r: i32, imm8: i32) {
    // palignr mm, mm/m64, imm8
    let destination = read_mmx64s(r).to_le_bytes();
    let result = simd_int::palignr(destination, source.to_le_bytes(), imm8 as u8);
    write_mmx_reg64(r, u64::from_le_bytes(result));
    transition_fpu_to_mmx();
}
pub unsafe fn instr_0F3A0F_reg(r1: i32, r2: i32, imm: i32) {
    instr_0F3A0F(read_mmx64s(r1), r2, imm);
}
pub unsafe fn instr_0F3A0F_mem(addr: i32, r: i32, imm: i32) {
    instr_0F3A0F(return_on_pagefault!(safe_read64s(addr)), r, imm);
}
pub unsafe fn instr_660F3A0F(source: reg128, r: i32, imm8: i32) {
    // palignr xmm, xmm/m128, imm8
    let destination = read_xmm128s(r);
    write_xmm_reg128(
        r,
        reg128 {
            u8: simd_int::palignr(destination.u8, source.u8, imm8 as u8),
        },
    );
}
pub unsafe fn instr_660F3A0F_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A0F(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F3A0F_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A0F(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}

/// BLENDPS/BLENDPD/PBLENDW/MPSADBW (simd_int::sse4_imm): xmm, xmm/m128, imm8
pub unsafe fn sse4_imm_xmm(op: u8, source: reg128, r: i32, imm8: i32) {
    let result = simd_int::sse4_imm(op, read_xmm128s(r).u8, source.u8, imm8 as u8);
    write_xmm_reg128(r, reg128 { u8: result });
}
macro_rules! sse4_imm {
    ($($op:literal $xmm:ident $xmm_reg:ident $xmm_mem:ident;)*) => {$(
        pub unsafe fn $xmm(source: reg128, r: i32, imm8: i32) { sse4_imm_xmm($op, source, r, imm8) }
        pub unsafe fn $xmm_reg(r1: i32, r2: i32, imm: i32) { $xmm(read_xmm128s(r1), r2, imm) }
        pub unsafe fn $xmm_mem(addr: i32, r: i32, imm: i32) {
            $xmm(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm)
        }
    )*};
}
sse4_imm! {
    0x0C instr_660F3A0C instr_660F3A0C_reg instr_660F3A0C_mem; // blendps
    0x0D instr_660F3A0D instr_660F3A0D_reg instr_660F3A0D_mem; // blendpd
    0x0E instr_660F3A0E instr_660F3A0E_reg instr_660F3A0E_mem; // pblendw
    0x42 instr_660F3A42 instr_660F3A42_reg instr_660F3A42_mem; // mpsadbw
}

/// PEXTRB/PEXTRW/PEXTRD/EXTRACTPS: the element of `bytes` bytes of XMM `r`
/// that imm8 selects
pub unsafe fn extract(r: i32, bytes: usize, imm8: i32) -> u32 {
    let i = imm8 as usize & (16 / bytes - 1);
    read_xmm128s(r).u8[i * bytes..(i + 1) * bytes]
        .iter()
        .rev()
        .fold(0, |n, &b| n << 8 | b as u32)
}
/// PINSRB/PINSRD: the element of `bytes` bytes of XMM `r` that imm8 selects
/// := the low bytes of `value`
pub unsafe fn insert(r: i32, bytes: usize, value: u32, imm8: i32) {
    let i = imm8 as usize & (16 / bytes - 1);
    let mut v = read_xmm128s(r);
    v.u8[i * bytes..(i + 1) * bytes].copy_from_slice(&value.to_le_bytes()[..bytes]);
    write_xmm_reg128(r, v);
}
// pextrb r32/m8, xmm, imm8 (pextrw r32/m16, pextrd r/m32, extractps r/m32): a
// register destination is zero-extended
pub unsafe fn instr_660F3A14_reg(r1: i32, r2: i32, imm: i32) {
    write_reg32(r1, extract(r2, 1, imm) as i32)
}
pub unsafe fn instr_660F3A14_mem(addr: i32, r: i32, imm: i32) {
    return_on_pagefault!(safe_write8(addr, extract(r, 1, imm) as i32));
}
pub unsafe fn instr_660F3A15_reg(r1: i32, r2: i32, imm: i32) {
    write_reg32(r1, extract(r2, 2, imm) as i32)
}
pub unsafe fn instr_660F3A15_mem(addr: i32, r: i32, imm: i32) {
    return_on_pagefault!(safe_write16(addr, extract(r, 2, imm) as i32));
}
pub unsafe fn instr_660F3A16_reg(r1: i32, r2: i32, imm: i32) {
    write_reg32(r1, extract(r2, 4, imm) as i32)
}
pub unsafe fn instr_660F3A16_mem(addr: i32, r: i32, imm: i32) {
    return_on_pagefault!(safe_write32(addr, extract(r, 4, imm) as i32));
}
pub unsafe fn instr_660F3A17_reg(r1: i32, r2: i32, imm: i32) {
    write_reg32(r1, extract(r2, 4, imm) as i32)
}
pub unsafe fn instr_660F3A17_mem(addr: i32, r: i32, imm: i32) {
    return_on_pagefault!(safe_write32(addr, extract(r, 4, imm) as i32));
}
// pinsrb xmm, r32/m8, imm8 (pinsrd xmm, r/m32, imm8)
pub unsafe fn instr_660F3A20_reg(r1: i32, r2: i32, imm: i32) {
    insert(r2, 1, read_reg32(r1) as u32, imm)
}
pub unsafe fn instr_660F3A20_mem(addr: i32, r: i32, imm: i32) {
    insert(r, 1, return_on_pagefault!(safe_read8(addr)) as u32, imm)
}
pub unsafe fn instr_660F3A22_reg(r1: i32, r2: i32, imm: i32) {
    insert(r2, 4, read_reg32(r1) as u32, imm)
}
pub unsafe fn instr_660F3A22_mem(addr: i32, r: i32, imm: i32) {
    insert(r, 4, return_on_pagefault!(safe_read32s(addr)) as u32, imm)
}
pub unsafe fn instr_660F3A21(value: u32, r: i32, imm8: i32) {
    // insertps xmm, xmm/m32, imm8
    let result = simd_int::insertps(read_xmm128s(r).u8, value, imm8 as u8);
    write_xmm_reg128(r, reg128 { u8: result });
}
pub unsafe fn instr_660F3A21_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A21(read_xmm128s(r1).u32[(imm >> 6 & 3) as usize], r2, imm)
}
pub unsafe fn instr_660F3A21_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A21(return_on_pagefault!(safe_read32s(addr)) as u32, r, imm)
}

// roundps/roundpd xmm, xmm/m128, imm8; roundss xmm, xmm/m32, imm8; roundsd
// xmm, xmm/m64, imm8 (false: an unmasked exception, nothing changed)
pub unsafe fn instr_660F3A08(source: reg128, r: i32, imm: i32) -> bool {
    sse_fp_round(0x660F3A08, r, source.bits(), imm)
}
pub unsafe fn instr_660F3A08_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A08(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F3A08_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A08(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
pub unsafe fn instr_660F3A09(source: reg128, r: i32, imm: i32) -> bool {
    sse_fp_round(0x660F3A09, r, source.bits(), imm)
}
pub unsafe fn instr_660F3A09_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A09(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F3A09_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A09(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
pub unsafe fn instr_660F3A0A(source: u32, r: i32, imm: i32) -> bool {
    sse_fp_round(0x660F3A0A, r, source as u128, imm)
}
pub unsafe fn instr_660F3A0A_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A0A(read_xmm128s(r1).u32[0], r2, imm);
}
pub unsafe fn instr_660F3A0A_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A0A(return_on_pagefault!(safe_read32s(addr)) as u32, r, imm);
}
pub unsafe fn instr_660F3A0B(source: u64, r: i32, imm: i32) -> bool {
    sse_fp_round(0x660F3A0B, r, source as u128, imm)
}
pub unsafe fn instr_660F3A0B_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A0B(read_xmm64s(r1), r2, imm);
}
pub unsafe fn instr_660F3A0B_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A0B(return_on_pagefault!(safe_read64s(addr)), r, imm);
}
// dpps/dppd xmm, xmm/m128, imm8
pub unsafe fn instr_660F3A40(source: reg128, r: i32, imm: i32) -> bool {
    sse_fp_dot_product(false, r, source.bits(), imm)
}
pub unsafe fn instr_660F3A40_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A40(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F3A40_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A40(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}
pub unsafe fn instr_660F3A41(source: reg128, r: i32, imm: i32) -> bool {
    sse_fp_dot_product(true, r, source.bits(), imm)
}
pub unsafe fn instr_660F3A41_reg(r1: i32, r2: i32, imm: i32) {
    instr_660F3A41(read_xmm128s(r1), r2, imm);
}
pub unsafe fn instr_660F3A41_mem(addr: i32, r: i32, imm: i32) {
    instr_660F3A41(return_on_pagefault!(safe_read128s_aligned(addr)), r, imm);
}

/// PCMPESTRM/PCMPESTRI/PCMPISTRM/PCMPISTRI (66 0F 3A 60-63 by `op`): the
/// strings of XMM `r` and `source` compared as imm8 says (simd_int::
/// compare_strings), the explicit forms' lengths in EAX and EDX. The index
/// goes to ECX or the mask to XMM0; CF, ZF, SF and OF are set, AF and PF
/// cleared. The memory operand need not be aligned (SDM, exception type 4).
pub unsafe fn pcmpstr(op: u8, source: reg128, r: i32, imm8: i32) {
    let explicit = op & 2 == 0;
    let length = |register| explicit.then(|| read_reg32(register) as i64);
    let result = simd_int::compare_strings(
        imm8 as u8,
        read_xmm128s(r).u8,
        source.u8,
        length(EAX),
        length(EDX),
    );
    if op & 1 != 0 {
        write_reg32(ECX, result.index as i32);
    }
    else {
        write_xmm_reg128(0, reg128 { u8: result.xmm0 });
    }
    *flags_changed = 0;
    *flags = *flags & !FLAGS_ALL | result.flags;
}
macro_rules! pcmpstr {
    ($($op:literal $reg:ident $mem:ident;)*) => {$(
        pub unsafe fn $reg(r1: i32, r2: i32, imm: i32) { pcmpstr($op, read_xmm128s(r1), r2, imm) }
        pub unsafe fn $mem(addr: i32, r: i32, imm: i32) {
            pcmpstr($op, return_on_pagefault!(safe_read128s(addr)), r, imm)
        }
    )*};
}
pcmpstr! {
    0x60 instr_660F3A60_reg instr_660F3A60_mem; // pcmpestrm
    0x61 instr_660F3A61_reg instr_660F3A61_mem; // pcmpestri
    0x62 instr_660F3A62_reg instr_660F3A62_mem; // pcmpistrm
    0x63 instr_660F3A63_reg instr_660F3A63_mem; // pcmpistri
}

/// ROUNDPS/PD/SS/SD of the XMM `source` register's value (the IR helper):
/// false after an unmasked exception
pub unsafe fn instr_660F3A08_any(op: u32, source: reg128, r: i32, imm: i32) -> bool {
    sse_fp_round(op, r, source.bits(), imm)
}
                                                                                                                  source/v64/src/rust/cpu/ioapic.rs                                                                   0000644 0000000 0000000 00000030406 00000000000 014054  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // http://download.intel.com/design/chipsets/datashts/29056601.pdf

use crate::cpu::{apic, global_pointers::acpi_enabled};
#[cfg(not(feature = "parallel"))]
use std::sync::{Mutex, MutexGuard};

const IOAPIC_LOG_VERBOSE: bool = false;

const IOREGSEL: u32 = 0;
const IOWIN: u32 = 0x10;

const IOAPIC_IRQ_COUNT: usize = 24;

const IOAPIC_FIRST_IRQ_REG: u32 = 0x10;
const IOAPIC_LAST_IRQ_REG: u32 = 0x10 + 2 * IOAPIC_IRQ_COUNT as u32;

const IOAPIC_ID: u32 = 0; // must match value in seabios

pub const IOAPIC_CONFIG_TRIGGER_MODE_LEVEL: u32 = 1 << 15;

const IOAPIC_CONFIG_MASKED: u32 = 1 << 16;
const IOAPIC_CONFIG_DELIVS: u32 = 1 << 12;
const IOAPIC_CONFIG_REMOTE_IRR: u32 = 1 << 14;
const IOAPIC_CONFIG_READONLY_MASK: u32 =
    IOAPIC_CONFIG_REMOTE_IRR | IOAPIC_CONFIG_DELIVS | 0xFFFE0000;

const IOAPIC_DELIVERY_FIXED: u8 = 0;
const IOAPIC_DELIVERY_LOWEST_PRIORITY: u8 = 1;
const IOAPIC_DELIVERY_SMI: u8 = 2;
const IOAPIC_DELIVERY_NMI: u8 = 4;
const IOAPIC_DELIVERY_INIT: u8 = 5;
const IOAPIC_DELIVERY_EXTINT: u8 = 7;

const DELIVERY_MODES: [&str; 8] = [
    "Fixed (0)",
    "Lowest Prio (1)",
    "SMI (2)",
    "Reserved (3)",
    "NMI (4)",
    "INIT (5)",
    "Reserved (6)",
    "ExtINT (7)",
];

const DESTINATION_MODES: [&str; 2] = ["physical", "logical"];

// keep in sync with cpu.js
#[allow(dead_code)]
const IOAPIC_STRUCT_SIZE: usize = 4 * 52;

// Note: JavaScript (cpu.get_state_apic) depens on this layout
const _: () = assert!(std::mem::offset_of!(Ioapic, ioredtbl_destination) == 24 * 4);
const _: () = assert!(std::mem::offset_of!(Ioapic, ioregsel) == 48 * 4);
const _: () = assert!(std::mem::offset_of!(Ioapic, irq_value) == 51 * 4);
const _: () = assert!(std::mem::size_of::<Ioapic>() == IOAPIC_STRUCT_SIZE);
#[repr(C)]
struct Ioapic {
    ioredtbl_config: [u32; IOAPIC_IRQ_COUNT],
    ioredtbl_destination: [u32; IOAPIC_IRQ_COUNT],
    ioregsel: u32,
    ioapic_id: u32,
    irr: u32,
    irq_value: u32,
}

const IOAPIC_RESET: Ioapic = Ioapic {
    ioredtbl_config: [IOAPIC_CONFIG_MASKED; IOAPIC_IRQ_COUNT],
    ioredtbl_destination: [0; IOAPIC_IRQ_COUNT],
    ioregsel: 0,
    ioapic_id: IOAPIC_ID,
    irr: 0,
    irq_value: 0,
};

#[cfg(not(feature = "parallel"))]
static IOAPIC: Mutex<Ioapic> = Mutex::new(IOAPIC_RESET);

// With cores in workers, every core programs and EOIs the machine instance's
// IOAPIC while the devices raise its inputs: a spin lock guards it.
#[cfg(feature = "parallel")]
static mut IOAPIC: Ioapic = IOAPIC_RESET;
#[cfg(feature = "parallel")]
static mut IOAPIC_LOCK: crate::parallel::SpinLock = crate::parallel::SpinLock::new();
#[cfg(feature = "parallel")]
struct IoapicGuard;
/// The lock guarding the machine's IOAPIC (see crate::parallel::parallel_fail)
pub fn lock() -> &'static crate::parallel::SpinLock {
    #[cfg(feature = "parallel")]
    {
        unsafe { &*crate::parallel::machine(&raw mut IOAPIC_LOCK) }
    }
    #[cfg(not(feature = "parallel"))]
    {
        static UNUSED: crate::parallel::SpinLock = crate::parallel::SpinLock::new();
        &UNUSED
    }
}
#[cfg(feature = "parallel")]
impl std::ops::Deref for IoapicGuard {
    type Target = Ioapic;
    fn deref(&self) -> &Ioapic { unsafe { &*crate::parallel::machine(&raw mut IOAPIC) } }
}
#[cfg(feature = "parallel")]
impl std::ops::DerefMut for IoapicGuard {
    fn deref_mut(&mut self) -> &mut Ioapic {
        unsafe { &mut *crate::parallel::machine(&raw mut IOAPIC) }
    }
}
#[cfg(feature = "parallel")]
impl Drop for IoapicGuard {
    fn drop(&mut self) { unsafe { (*crate::parallel::machine(&raw mut IOAPIC_LOCK)).unlock() } }
}

/// Board reset, unlike an INIT targeted at one processor.
pub fn reset() { *get_ioapic() = IOAPIC_RESET; }

#[cfg(not(feature = "parallel"))]
fn get_ioapic() -> MutexGuard<'static, Ioapic> { IOAPIC.try_lock().unwrap() }
#[cfg(feature = "parallel")]
fn get_ioapic() -> IoapicGuard {
    unsafe { (*crate::parallel::machine(&raw mut IOAPIC_LOCK)).lock() };
    IoapicGuard
}

#[no_mangle]
pub fn get_ioapic_addr() -> u32 { &raw mut *get_ioapic() as u32 }

pub fn remote_eoi(vector: u8) { remote_eoi_internal(&mut get_ioapic(), vector); }

fn remote_eoi_internal(ioapic: &mut Ioapic, vector: u8) {
    for i in 0..IOAPIC_IRQ_COUNT as u8 {
        let config = ioapic.ioredtbl_config[i as usize];

        if (config & 0xFF) as u8 == vector && config & IOAPIC_CONFIG_REMOTE_IRR != 0 {
            dbg_log!("Clear remote IRR for irq={:x}", i);
            ioapic.ioredtbl_config[i as usize] &= !IOAPIC_CONFIG_REMOTE_IRR;
            check_irq(ioapic, i);
        }
    }
}

fn check_irq(ioapic: &mut Ioapic, irq: u8) {
    let mask = 1 << irq;

    if ioapic.irr & mask == 0 {
        return;
    }

    let config = ioapic.ioredtbl_config[irq as usize];

    if config & IOAPIC_CONFIG_MASKED == 0 {
        let delivery_mode = ((config >> 8) & 7) as u8;
        let destination_mode = ((config >> 11) & 1) as u8;
        let vector = (config & 0xFF) as u8;
        let destination = (ioapic.ioredtbl_destination[irq as usize] >> 24) as u8;
        let is_level =
            config & IOAPIC_CONFIG_TRIGGER_MODE_LEVEL == IOAPIC_CONFIG_TRIGGER_MODE_LEVEL;

        let tracks_eoi = is_level
            && matches!(
                delivery_mode,
                IOAPIC_DELIVERY_FIXED | IOAPIC_DELIVERY_LOWEST_PRIORITY
            );
        if tracks_eoi && config & IOAPIC_CONFIG_REMOTE_IRR != 0 {
            return;
        }
        // 3/6 are reserved. Never panic or accidentally inject an ordinary
        // fixed interrupt for these modes. (SMI ignores the vector, and is
        // edge triggered.)
        if !matches!(
            delivery_mode,
            IOAPIC_DELIVERY_FIXED
                | IOAPIC_DELIVERY_LOWEST_PRIORITY
                | IOAPIC_DELIVERY_SMI
                | IOAPIC_DELIVERY_NMI
                | IOAPIC_DELIVERY_INIT
                | IOAPIC_DELIVERY_EXTINT
        ) {
            return;
        }
        let accepted = apic::route(
            vector,
            delivery_mode,
            is_level,
            destination,
            destination_mode,
        );
        if !is_level {
            ioapic.irr &= !mask;
        }
        // NMI/INIT/ExtINT do not use LAPIC ISR/EOI. Setting remote IRR
        // for these would permanently suppress a level-triggered input.
        if accepted && tracks_eoi {
            ioapic.ioredtbl_config[irq as usize] |= IOAPIC_CONFIG_REMOTE_IRR;
        }

        ioapic.ioredtbl_config[irq as usize] &= !IOAPIC_CONFIG_DELIVS;
    }
}

pub fn set_irq(i: u8) { set_irq_internal(&mut get_ioapic(), i) }

fn set_irq_internal(ioapic: &mut Ioapic, i: u8) {
    if i as usize >= IOAPIC_IRQ_COUNT {
        dbg_assert!(false, "Bad irq: {}", i);
        return;
    }

    let mask = 1 << i;

    if ioapic.irq_value & mask == 0 {
        if IOAPIC_LOG_VERBOSE {
            dbg_log!("apic set irq {}", i);
        }

        ioapic.irq_value |= mask;

        let config = ioapic.ioredtbl_config[i as usize];
        if config & (IOAPIC_CONFIG_TRIGGER_MODE_LEVEL | IOAPIC_CONFIG_MASKED)
            == IOAPIC_CONFIG_MASKED
        {
            // edge triggered and masked
            return;
        }

        ioapic.irr |= mask;

        check_irq(ioapic, i);
    }
}

pub fn clear_irq(i: u8) { clear_irq_internal(&mut get_ioapic(), i) }

fn clear_irq_internal(ioapic: &mut Ioapic, i: u8) {
    if i as usize >= IOAPIC_IRQ_COUNT {
        dbg_assert!(false, "Bad irq: {}", i);
        return;
    }

    let mask = 1 << i;

    if ioapic.irq_value & mask == mask {
        ioapic.irq_value &= !mask;

        let config = ioapic.ioredtbl_config[i as usize];
        if config & IOAPIC_CONFIG_TRIGGER_MODE_LEVEL != 0 {
            ioapic.irr &= !mask;
        }
    }
}

pub fn read32(addr: u32) -> u32 {
    if unsafe { !*acpi_enabled } {
        return 0;
    }
    read32_internal(&mut get_ioapic(), addr)
}

fn read32_internal(ioapic: &mut Ioapic, addr: u32) -> u32 {
    match addr {
        IOREGSEL => ioapic.ioregsel,
        IOWIN => match ioapic.ioregsel {
            0 => {
                dbg_log!("IOAPIC Read id");
                ioapic.ioapic_id << 24
            },
            1 => {
                dbg_log!("IOAPIC Read version");
                0x11 | (IOAPIC_IRQ_COUNT as u32 - 1) << 16
            },
            2 => {
                dbg_log!("IOAPIC Read arbitration id");
                ioapic.ioapic_id << 24
            },
            IOAPIC_FIRST_IRQ_REG..IOAPIC_LAST_IRQ_REG => {
                let irq = ((ioapic.ioregsel - IOAPIC_FIRST_IRQ_REG) >> 1) as u8;
                let index = ioapic.ioregsel & 1;

                if index != 0 {
                    let value = ioapic.ioredtbl_destination[irq as usize];
                    dbg_log!("IOAPIC Read destination irq={:x} -> {:08x}", irq, value);
                    value
                }
                else {
                    let value = ioapic.ioredtbl_config[irq as usize];
                    dbg_log!("IOAPIC Read config irq={:x} -> {:08x}", irq, value);
                    value
                }
            },
            reg => {
                dbg_log!("IOAPIC register read outside of range {:x}", reg);
                0
            },
        },
        _ => {
            dbg_log!("Unaligned or oob IOAPIC memory read: {:x}", addr);
            0
        },
    }
}

pub fn write32(addr: u32, value: u32) {
    if unsafe { !*acpi_enabled } {
        return;
    }
    write32_internal(&mut get_ioapic(), addr, value)
}

fn write32_internal(ioapic: &mut Ioapic, addr: u32, value: u32) {
    //dbg_log!("IOAPIC write {:x} <- {:08x}", reg, value);

    match addr {
        IOREGSEL => ioapic.ioregsel = value & 0xFF,
        IOWIN => match ioapic.ioregsel {
            0 => ioapic.ioapic_id = (value >> 24) & 0x0F,
            1 | 2 => {
                dbg_log!("IOAPIC Invalid write: {}", ioapic.ioregsel);
            },
            IOAPIC_FIRST_IRQ_REG..IOAPIC_LAST_IRQ_REG => {
                let irq = ((ioapic.ioregsel - IOAPIC_FIRST_IRQ_REG) >> 1) as u8;
                let index = ioapic.ioregsel & 1;

                if index != 0 {
                    dbg_log!(
                        "Write destination {:08x} irq={:x} dest={:02x}",
                        value,
                        irq,
                        value >> 24
                    );
                    ioapic.ioredtbl_destination[irq as usize] = value & 0xFF000000;
                    check_irq(ioapic, irq);
                }
                else {
                    let old_value = ioapic.ioredtbl_config[irq as usize] as u32;
                    ioapic.ioredtbl_config[irq as usize] = (value & !IOAPIC_CONFIG_READONLY_MASK)
                        | (old_value & IOAPIC_CONFIG_READONLY_MASK);

                    let vector = value & 0xFF;
                    let delivery_mode = (value >> 8) & 7;
                    let destination_mode = (value >> 11) & 1;
                    let is_level = (value >> 15) & 1;
                    let disabled = (value >> 16) & 1;

                    dbg_log!(
                            "Write config {:08x} irq={:x} vector={:02x} deliverymode={} destmode={} is_level={} disabled={}",
                            value,
                            irq,
                            vector,
                            DELIVERY_MODES[delivery_mode as usize],
                            DESTINATION_MODES[destination_mode as usize],
                            is_level,
                            disabled
                        );

                    check_irq(ioapic, irq);
                }
            },
            reg => {
                dbg_log!(
                    "IOAPIC register write outside of range {:x} <- {:x}",
                    reg,
                    value
                );
            },
        },
        _ => {
            dbg_log!(
                "Unaligned or oob IOAPIC memory write: {:x} <- {:x}",
                addr,
                value
            );
        },
    }
}

/// The legacy PIC's INTR output is connected to IOAPIC input 0. Querying its
/// ExtINT route is side-effect free, so IF=0/HLT cannot acknowledge the 8259.
pub fn pic_destination() -> Option<(u8, u8)> {
    let ioapic = get_ioapic();
    let config = ioapic.ioredtbl_config[0];
    if config & IOAPIC_CONFIG_MASKED == 0 && (config >> 8) & 7 == IOAPIC_DELIVERY_EXTINT as u32 {
        Some((
            (ioapic.ioredtbl_destination[0] >> 24) as u8,
            ((config >> 11) & 1) as u8,
        ))
    }
    else {
        None
    }
}
                                                                                                                                                                                                                                                          source/v64/src/rust/cpu/isa_hooks.rs                                                                0000644 0000000 0000000 00000014111 00000000000 014562  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The x86 core's side of the code both cores share
//! (docs/arm64-virt-android16-plan.md P1.0): lib.rs names this module
//! `crate::isa` in the x86 core (aarch64::isa_hooks in the ARM core), and the
//! shared modules reach the ISA only through it. The hooks of crate::parallel
//! (set_active, attach, sync, poll) hold what was x86 in its bodies, inlined
//! so that the x86 core's code does not change.
use crate::cpu::{apic, cpu, global_pointers as gp, ioapic, memory};
use crate::page::Page;
use crate::parallel::{self, machine, machine_state};

pub const MAX_CORES: usize = apic::MAX_CORES;

/// The core this instance runs now
#[inline(always)]
pub fn current_core() -> usize { apic::current_core() }
/// The machine's cores
#[inline(always)]
pub fn core_count() -> usize { apic::core_count() }
/// The host's clock in milliseconds (env.microtick)
#[inline(always)]
pub unsafe fn microtick() -> f64 { cpu::js::microtick() }

// ---- crate::extended (extended RAM, the engine both cores share)

/// Every access cache entry, so that no frame of extended RAM is cached any more
#[inline(always)]
pub unsafe fn extended_release_caches() { crate::x64::extended::release_caches() }
/// The write entries to a frame of extended RAM whose page now has code
#[inline(always)]
pub unsafe fn extended_retire_cached_writes(host: u32) {
    crate::x64::extended::retire_cached_writes(host)
}
/// An extended page with page-tier code was written: retire its function
#[inline(always)]
pub unsafe fn extended_code_written(page: u32) {
    crate::x64::pages::dirty_page(crate::x64::extended::CODE_KEY_BASE + page)
}
/// The frames of extended RAM were discarded: the aperture's slots go too
#[inline(always)]
pub unsafe fn extended_discarded() { crate::x64::extended::aperture::clear() }

/// The address of this instance's yield flag (parallel::kick sets it)
#[inline(always)]
pub unsafe fn core_yield_address() -> u32 { &raw mut cpu::core_yield as u32 }

/// parallel_set_active in the machine instance: track RAM's code pages
#[inline(always)]
pub unsafe fn machine_set_active() {
    parallel::code::allocate(*gp::memory_size / 4096);
    // (writes of other cores to extended RAM do not retire code)
    crate::x64::pages::retire_extended();
}

/// parallel_attach: RAM, the machine configuration and the machine-shared
/// state of the machine instance
#[inline(always)]
pub unsafe fn attach_worker(core: u32) {
    memory::mem8 = *machine(&raw mut memory::mem8);
    memory::ram_fast_limit = *machine(&raw mut memory::ram_fast_limit);
    *gp::memory_size = *machine_state(gp::memory_size);
    *gp::acpi_enabled = *machine_state(gp::acpi_enabled);
    *gp::x87_native_policy = *machine_state(gp::x87_native_policy);
    cpu::copy_machine_configuration();
    crate::x64::physical::copy_from_machine();
    apic::attach_worker(core);
}

/// The TSC offset of this instance's core, published while it is parked
#[no_mangle]
pub unsafe fn parallel_tsc_offset(high: bool) -> u32 {
    let offset = cpu::tsc_offset;
    (if high { offset >> 32 } else { offset }) as u32
}
#[no_mangle]
pub unsafe fn parallel_set_tsc_offset(low: u32, high: u32) {
    cpu::tsc_offset = low as u64 | (high as u64) << 32;
    cpu::tsc_last_value = 0;
    cpu::tsc_resolution = u64::MAX;
    cpu::tsc_number_of_same_readings = 0;
}

/// parallel_sync in a worker: the machine's physical bus windows
#[inline(always)]
pub unsafe fn sync_worker() { crate::x64::physical::copy_from_machine(); }

/// Machine configuration that may change while the cores run (ACPI enable,
/// the CPU profile, TSEG), copied into a worker
#[inline(always)]
pub unsafe fn sync_worker_configuration() {
    *gp::acpi_enabled = *machine_state(gp::acpi_enabled);
    cpu::copy_machine_configuration();
    // (the chipset's TSEG)
    crate::cpu::smm::sync_worker();
}

/// A failed core's locks besides the split lock
#[inline(always)]
pub unsafe fn release_locks_held_by(core: usize) {
    ioapic::lock().release_held_by(core);
    crate::x64::extended::release_held_by(core);
}

/// parallel_test_fault: a machine lock to trap inside
#[inline(always)]
pub unsafe fn lock_for_test_fault() { ioapic::lock().lock(); }

/// parallel::code::poll: other cores published code from `pages` (or more
/// than the ring held): this core's stores to them take the slow path
#[inline(always)]
pub unsafe fn others_published(pages: &[u32], overflow: bool) {
    // (the x64 interpreter checks every store: only the access cache's
    // write entries of those pages must go)
    if overflow || pages.len() > 32 {
        cpu::full_clear_tlb();
        crate::x64::jac::flush_all();
    }
    else {
        for &page in pages {
            cpu::tlb_set_has_code(Page::page_of(page << 12), true);
            crate::x64::jac::retire_writes_on(current_core(), page << 12);
        }
    }
}

/// parallel::code::poll: other cores wrote `pages` (or more than the ring
/// held): retire this core's code from them
#[inline(always)]
pub unsafe fn others_wrote(pages: Vec<u32>, overflow: bool) {
    if overflow {
        crate::jit::jit_clear_cache_js();
    }
    else {
        for page in pages {
            crate::jit::jit_retire_page(Page::page_of(page << 12));
        }
    }
}

/// Registers and lazy flags an instruction may change before it commits a
/// locked read-modify-write: restored when another core changed the operand
/// in between and the instruction runs again
#[cfg(feature = "parallel")]
pub struct Registers([u8; 60], [u8; 96]);
#[cfg(feature = "parallel")]
impl Registers {
    pub unsafe fn save() -> Self {
        use crate::cpu::global_pointers::{reg32, x64_gpr_hi};
        let mut saved = Registers([0; 60], [0; 96]);
        // reg32 .. flags, and the upper and extra 64-bit GPR halves
        std::ptr::copy_nonoverlapping(reg32 as *const u8, saved.0.as_mut_ptr(), 60);
        std::ptr::copy_nonoverlapping(x64_gpr_hi as *const u8, saved.1.as_mut_ptr(), 96);
        saved
    }
    pub unsafe fn restore(&self) {
        use crate::cpu::global_pointers::{reg32, x64_gpr_hi};
        std::ptr::copy_nonoverlapping(self.0.as_ptr(), reg32 as *mut u8, 60);
        std::ptr::copy_nonoverlapping(self.1.as_ptr(), x64_gpr_hi as *mut u8, 96);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/rust/cpu/memory.rs                                                                   0000644 0000000 0000000 00000047662 00000000000 014134  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       mod ext {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn mmap_read8(addr: u32) -> i32;
        pub fn mmap_read32(addr: u32) -> i32;

        pub fn mmap_write8(addr: u32, value: i32);
        pub fn mmap_write16(addr: u32, value: i32);
        pub fn mmap_write32(addr: u32, value: i32);
        pub fn mmap_write64(addr: u32, v0: i32, v1: i32);
        pub fn mmap_write128(addr: u32, v0: i32, v1: i32, v2: i32, v3: i32);
    }
}

use crate::cpu::apic;
use crate::cpu::cpu::{
    handle_irqs, reg128, APIC_MEM_ADDRESS, APIC_MEM_SIZE, IOAPIC_MEM_ADDRESS, IOAPIC_MEM_SIZE,
};
use crate::cpu::global_pointers::memory_size;
use crate::cpu::ioapic;
use crate::cpu::mmio_ram;
use crate::jit;
use crate::page::Page;
use crate::parallel;

use std::alloc;
use std::ptr;

#[allow(non_upper_case_globals)]
pub static mut mem8: *mut u8 = ptr::null_mut();
// The first relocated low RAM byte, or memory_size when no RAM was relocated.
// Ordinary RAM below this threshold retains the original single bound check.
#[allow(non_upper_case_globals)]
pub static mut ram_fast_limit: u32 = 0;

#[no_mangle]
pub fn allocate_memory(size: u32) -> u32 {
    unsafe {
        dbg_assert!(mem8.is_null());
    };
    dbg_log!("Allocate memory size={}m", size >> 20);
    let layout = alloc::Layout::from_size_align(size as usize, 0x1000).unwrap();
    // RAM reads as zero at power-on. The pages the heap grows by are zero,
    // but below its current end the allocator may return chunks freed
    // before, their headers still in them: with the page tier's 32-bit code, the 16 chunks of
    // 2 MiB of jit::reserve_compiler_heap
    // (0x0020000A00400010 at guest 0x3FFEA0, ...). Only that part is cleared
    // (alloc_zeroed would commit every page of the guest's RAM up front).
    let heap_end = heap_end();
    let ptr = unsafe { alloc::alloc(layout) };
    if !ptr.is_null() && (ptr as u64) < heap_end {
        let reused = (heap_end - ptr as u64).min(size as u64);
        unsafe { ptr::write_bytes(ptr, 0, reused as usize) };
    }
    unsafe {
        mem8 = ptr;
        ram_fast_limit = size;
    };
    ptr as u32
}

/// The end of the memory the heap has used (the wasm memory's size): the
/// pages above it are zero
fn heap_end() -> u64 {
    #[cfg(target_arch = "wasm32")]
    return (std::arch::wasm32::memory_size(0) as u64) << 16;
    #[cfg(not(target_arch = "wasm32"))]
    return u64::MAX;
}

#[no_mangle]
pub unsafe fn zero_memory(addr: u32, size: u32) {
    ptr::write_bytes(mem8.offset(addr as isize), 0, size as usize);
}

#[no_mangle]
pub fn in_mapped_range(addr: u32) -> bool {
    addr >= 0xA0000 && addr < 0xC0000
        || addr >= unsafe { ram_fast_limit }
            && (addr >= unsafe { *memory_size }
                || unsafe { crate::x64::physical::is_low_ram_hole(addr) }
                || unsafe { crate::cpu::smm::in_tseg(addr) })
}

/// Whether `addr` is in a page of guest RAM in mem8: decoded by the low bus,
/// or RAM relocated above 4 GiB, whose backing is a hole of the low bus
/// (in_mapped_range) yet plain RAM to IA-32e mode's fetches
/// (crate::x64::physical::ram_page)
pub fn is_ram_backing(addr: u32) -> bool {
    !in_mapped_range(addr)
        || addr < unsafe { *memory_size } && unsafe { crate::x64::physical::is_low_ram_hole(addr) }
}

/// RAM that the low bus does not decode: relocated above 4 GiB, or TSEG
/// outside SMM (crate::cpu::smm)
#[inline]
fn low_ram_hole(addr: u32) -> bool {
    addr >= unsafe { ram_fast_limit }
        && addr < unsafe { *memory_size }
        && unsafe {
            crate::x64::physical::is_low_ram_hole(addr) || crate::cpu::smm::tseg_blackhole(addr)
        }
}

/// Memory-mapped I/O whose accesses may raise or unmask an interrupt: what
/// lies above RAM (the APIC, the IOAPIC, HPET, PCI memory BARs), except a
/// device's plain memory (mmio_ram), SMRAM and the extended RAM aperture.
/// Compiled code leaves an access there to the interpreter, which delivers
/// the interrupt at the instruction boundary (docs/jit-unification-plan.md
/// P3.0b). The legacy VGA window below 1 MiB raises none.
pub unsafe fn may_interrupt(addr: u32) -> bool {
    addr >= *memory_size
        && !aperture::contains(addr)
        && smram_ram(addr, 1, false).is_none()
        && mmio_ram::read_host(addr, 1).is_none()
}

#[inline]
fn mapped_width(addr: u32, bytes: u32) -> bool {
    in_mapped_range(addr)
        || addr & 4095 > 4096 - bytes && in_mapped_range(addr.wrapping_add(bytes - 1))
}

#[inline]
fn touches_low_hole(addr: u32, bytes: u32) -> bool {
    low_ram_hole(addr) || low_ram_hole(addr.wrapping_add(bytes - 1))
        // (and the extended RAM aperture: accessed byte by byte, or by aligned dwords)
        || aperture::contains(addr) || aperture::contains(addr.wrapping_add(bytes - 1))
        // (and accesses across an edge of TSEG, in SMM)
        || unsafe {
            crate::cpu::smm::in_tseg(addr) || crate::cpu::smm::in_tseg(addr.wrapping_add(bytes - 1))
        }
}

use crate::x64::extended::aperture;
// SMRAM: compatible SMRAM behind the VGA window, high SMRAM, TSEG
// (crate::cpu::smm); data accesses here, instruction fetches in fetch8
use crate::cpu::smm::smram_ram;
// Extended RAM through the aperture (crate::x64::extended), in long mode only;
// elsewhere the range reads as open bus
fn aperture_read8(addr: u32) -> i32 {
    unsafe {
        if long_mode() {
            aperture::read8(addr).map_or(0xFF, |v| v as i32)
        }
        else {
            0xFF
        }
    }
}
fn aperture_write8(addr: u32, value: i32) {
    unsafe {
        if long_mode() {
            aperture::write8(addr, value as u8);
        }
    }
}
unsafe fn long_mode() -> bool { crate::x64::state::efer() & crate::x64::state::EFER_LMA != 0 }

// The RAM path of the reads is always inlined; mapped ranges (VGA, MMIO,
// the low hole left by RAM relocated above 4 GiB) are handled out of line.
#[export_name = "read8"]
pub fn read8_export(addr: u32) -> i32 { read8(addr) }
#[inline(always)]
pub fn read8(addr: u32) -> i32 {
    if in_mapped_range(addr) {
        read8_mapped(addr)
    }
    else {
        read8_no_mmap_check(addr)
    }
}
#[inline(never)]
fn read8_mapped(addr: u32) -> i32 {
    {
        if let Some(ram) = unsafe { smram_ram(addr, 1, false) } {
            read8_no_mmap_check(ram)
        }
        else if low_ram_hole(addr) {
            0xFF
        }
        else if aperture::contains(addr) {
            aperture_read8(addr)
        }
        else if let Some(host) = unsafe { mmio_ram::read_host(addr, 1) } {
            unsafe { *host as i32 }
        }
        else if addr >= APIC_MEM_ADDRESS && addr < APIC_MEM_ADDRESS + APIC_MEM_SIZE {
            apic::read32((addr - APIC_MEM_ADDRESS) & !3) as i32 >> 8 * (addr & 3) & 0xFF
        }
        else if addr >= IOAPIC_MEM_ADDRESS && addr < IOAPIC_MEM_ADDRESS + IOAPIC_MEM_SIZE {
            ioapic::read32((addr - IOAPIC_MEM_ADDRESS) & !3) as i32 >> 8 * (addr & 3) & 0xFF
        }
        else {
            unsafe { ext::mmap_read8(addr) }
        }
    }
}
/// An instruction byte from a mapped range: as read8, but compatible SMRAM
/// serves code fetches in SMM also with D_CLS (crate::cpu::smm)
pub fn fetch8(addr: u32) -> i32 {
    match unsafe { smram_ram(addr, 1, true) } {
        Some(ram) => read8_no_mmap_check(ram),
        None => read8(addr),
    }
}

// RAM accesses go through crate::parallel: ordered atomics when cores run in
// workers, plain accesses in the normal build.
pub fn read8_no_mmap_check(addr: u32) -> i32 {
    unsafe { parallel::load8(mem8.offset(addr as isize)) as i32 }
}

#[export_name = "read16"]
pub fn read16_export(addr: u32) -> i32 { read16(addr) }
#[inline(always)]
pub fn read16(addr: u32) -> i32 {
    if mapped_width(addr, 2) {
        read16_mapped(addr)
    }
    else {
        read16_no_mmap_check(addr)
    }
}
#[inline(never)]
fn read16_mapped(addr: u32) -> i32 {
    {
        if let Some(ram) = unsafe { smram_ram(addr, 2, false) } {
            read16_no_mmap_check(ram)
        }
        else if let Some(host) = unsafe { mmio_ram::read_host(addr, 2) } {
            unsafe { ptr::read_unaligned(host as *const u16) as i32 }
        }
        else {
            read8(addr) | read8(addr.wrapping_add(1)) << 8
        }
    }
}
pub fn read16_no_mmap_check(addr: u32) -> i32 {
    unsafe { parallel::load16(mem8.offset(addr as isize)) as i32 }
}

#[export_name = "read32s"]
pub fn read32s_export(addr: u32) -> i32 { read32s(addr) }
#[inline(always)]
pub fn read32s(addr: u32) -> i32 {
    if mapped_width(addr, 4) {
        read32s_mapped(addr)
    }
    else {
        read32_no_mmap_check(addr)
    }
}
#[inline(never)]
fn read32s_mapped(addr: u32) -> i32 {
    {
        if let Some(ram) = unsafe { smram_ram(addr, 4, false) } {
            return read32_no_mmap_check(ram);
        }
        if aperture::contains(addr) && addr & 3 == 0 && unsafe { long_mode() } {
            return unsafe { aperture::read32(addr) }.map_or(-1, |v| v as i32);
        }
        if addr & 4095 > 4092 || touches_low_hole(addr, 4) {
            read8(addr)
                | read8(addr.wrapping_add(1)) << 8
                | read8(addr.wrapping_add(2)) << 16
                | read8(addr.wrapping_add(3)) << 24
        }
        else if let Some(host) = unsafe { mmio_ram::read_host(addr, 4) } {
            unsafe { ptr::read_unaligned(host as *const i32) }
        }
        else if addr >= APIC_MEM_ADDRESS && addr < APIC_MEM_ADDRESS + APIC_MEM_SIZE {
            apic::read32(addr - APIC_MEM_ADDRESS) as i32
        }
        else if addr >= IOAPIC_MEM_ADDRESS && addr < IOAPIC_MEM_ADDRESS + IOAPIC_MEM_SIZE {
            ioapic::read32(addr - IOAPIC_MEM_ADDRESS) as i32
        }
        else {
            unsafe { ext::mmap_read32(addr) }
        }
    }
}
pub fn read32_no_mmap_check(addr: u32) -> i32 {
    unsafe { parallel::load32(mem8.offset(addr as isize)) as i32 }
}

pub unsafe fn read64s(addr: u32) -> i64 {
    if mapped_width(addr, 8) {
        if let Some(ram) = smram_ram(addr, 8, false) {
            read64_no_mmap_check(ram) as i64
        }
        else if let Some(host) = mmio_ram::read_host(addr, 8) {
            ptr::read_unaligned(host as *const i64)
        }
        else {
            // Preserve the low dword's bits without sign-extending into the
            // high dword. MMIO exposes two independent 32-bit bus reads.
            read32s(addr) as u32 as i64 | (read32s(addr.wrapping_add(4)) as i64) << 32
        }
    }
    else {
        parallel::load64(mem8.offset(addr as isize)) as i64
    }
}

pub unsafe fn read128(addr: u32) -> reg128 {
    if mapped_width(addr, 16) {
        if let Some(ram) = smram_ram(addr, 16, false) {
            let [low, high] = parallel::load128(mem8.offset(ram as isize));
            reg128 { u64: [low, high] }
        }
        else if let Some(host) = mmio_ram::read_host(addr, 16) {
            ptr::read_unaligned(host as *const reg128)
        }
        else {
            reg128 {
                i32: [
                    read32s(addr + 0),
                    read32s(addr.wrapping_add(4)),
                    read32s(addr.wrapping_add(8)),
                    read32s(addr.wrapping_add(12)),
                ],
            }
        }
    }
    else {
        let [low, high] = parallel::load128(mem8.offset(addr as isize));
        reg128 { u64: [low, high] }
    }
}

#[no_mangle]
pub unsafe fn write8(addr: u32, value: i32) {
    if in_mapped_range(addr) {
        mmap_write8(addr, value & 0xFF);
    }
    else {
        write8_ram(addr, value);
    };
}

#[inline]
pub unsafe fn write8_ram(addr: u32, value: i32) {
    jit::jit_dirty_bytes(addr, 1);
    write8_no_mmap_or_dirty_check(addr, value);
}

pub unsafe fn write8_no_mmap_or_dirty_check(addr: u32, value: i32) {
    parallel::store8(mem8.offset(addr as isize), value as u8)
}

/// Set accessed/dirty bits in the low byte of a page table entry: a locked
/// OR, as the processor does it, so that another core's concurrent update of
/// the entry is not overwritten
pub unsafe fn set_page_entry_bits(addr: u32, bits: u8) {
    if in_mapped_range(addr) {
        mmap_write8(addr, read8(addr) | bits as i32);
        return;
    }
    jit::jit_dirty_page(Page::page_of(addr));
    parallel::or8(mem8.offset(addr as isize), bits);
}

pub fn read64_no_mmap_check(addr: u32) -> u64 {
    unsafe { parallel::load64(mem8.offset(addr as isize)) }
}

#[no_mangle]
pub unsafe fn write16(addr: u32, value: i32) {
    if mapped_width(addr, 2) {
        mmap_write16(addr, value & 0xFFFF);
    }
    else {
        write16_ram(addr, value);
    };
}
#[inline]
pub unsafe fn write16_ram(addr: u32, value: i32) {
    jit::jit_dirty_bytes_small(addr, addr + 2);
    write16_no_mmap_or_dirty_check(addr, value);
}
pub unsafe fn write16_no_mmap_or_dirty_check(addr: u32, value: i32) {
    parallel::store16(mem8.offset(addr as isize), value as u16)
}

#[no_mangle]
pub unsafe fn write32(addr: u32, value: i32) {
    if mapped_width(addr, 4) {
        mmap_write32(addr, value);
    }
    else {
        write32_ram(addr, value);
    }
}

#[inline]
pub unsafe fn write32_ram(addr: u32, value: i32) {
    jit::jit_dirty_bytes_small(addr, addr + 4);
    write32_no_mmap_or_dirty_check(addr, value);
}

pub unsafe fn write32_no_mmap_or_dirty_check(addr: u32, value: i32) {
    parallel::store32(mem8.offset(addr as isize), value as u32)
}

pub unsafe fn write64_no_mmap_or_dirty_check(addr: u32, value: u64) {
    parallel::store64(mem8.offset(addr as isize), value)
}

pub unsafe fn write128_no_mmap_or_dirty_check(addr: u32, value: reg128) {
    parallel::store128(mem8.offset(addr as isize), value.u64)
}

/// Replace the naturally aligned RAM value `expected` by `value` if another
/// core has not changed it in between (the commit of a locked
/// read-modify-write). Always succeeds when no other core runs concurrently.
pub unsafe fn compare_exchange_no_mmap_or_dirty_check(
    addr: u32,
    bytes: u32,
    expected: u64,
    value: u64,
) -> bool {
    parallel::compare_exchange(mem8.offset(addr as isize), bytes, expected, value)
}

// Bulk copies and fills: x86 string stores are not ordered among themselves,
// but with respect to the surrounding instructions (fences in parallel builds)
pub unsafe fn memset_no_mmap_or_dirty_check(addr: u32, value: u8, count: u32) {
    parallel::full_fence();
    ptr::write_bytes(mem8.offset(addr as isize), value, count as usize);
    parallel::full_fence();
}

/// The caller has checked the entire, page-bounded writable RAM range and
/// invalidated generated code if necessary. Repeat an x86 word/dword pattern.
#[inline]
pub unsafe fn memset_pattern_no_mmap_or_dirty_check(addr: u32, value: u32, size: u32, count: u32) {
    dbg_assert!(size == 2 || size == 4);
    let pattern = if size == 2 { (value & 0xFFFF) * 0x10001 } else { value };
    let bytes = count * size;
    parallel::full_fence();
    if pattern == (pattern & 255) * 0x01010101 {
        memset_no_mmap_or_dirty_check(addr, pattern as u8, bytes);
        return;
    }
    let mut offset = 0;
    #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
    {
        use core::arch::wasm32::{i32x4_splat, v128_store};
        let vector = i32x4_splat(pattern as i32);
        while offset + 16 <= bytes {
            v128_store(mem8.add((addr + offset) as usize).cast(), vector);
            offset += 16;
        }
    }
    while offset + 4 <= bytes {
        write32_no_mmap_or_dirty_check(addr + offset, pattern as i32);
        offset += 4;
    }
    if offset < bytes {
        write16_no_mmap_or_dirty_check(addr + offset, pattern as i32);
    }
    parallel::full_fence();
}

pub unsafe fn memcpy_no_mmap_or_dirty_check(src_addr: u32, dst_addr: u32, count: u32) {
    dbg_assert!(src_addr < *memory_size);
    dbg_assert!(dst_addr < *memory_size);
    parallel::full_fence();
    ptr::copy(
        mem8.offset(src_addr as isize),
        mem8.offset(dst_addr as isize),
        count as usize,
    );
    parallel::full_fence();
}

/// Copy RAM into device memory (mmio_ram) within one page
pub unsafe fn memcpy_into_mmio_ram(src_addr: u32, dst_addr: u32, count: u32) {
    dbg_assert!(src_addr < *memory_size);
    dbg_assert!(Page::page_of(dst_addr) == Page::page_of(dst_addr + count - 1));
    let destination = mmio_ram::write_host(dst_addr, count).expect("device memory");
    ptr::copy_nonoverlapping(mem8.offset(src_addr as isize), destination, count as usize)
}

pub unsafe fn mmap_write8(addr: u32, value: i32) {
    if let Some(ram) = smram_ram(addr, 1, false) {
        write8_ram(ram, value);
        return;
    }
    if low_ram_hole(addr) {
        return;
    }
    if aperture::contains(addr) {
        aperture_write8(addr, value);
        return;
    }
    if let Some(host) = mmio_ram::write_host(addr, 1) {
        *host = value as u8
    }
    else {
        ext::mmap_write8(addr, value)
    }
}
pub unsafe fn mmap_write16(addr: u32, value: i32) {
    if let Some(ram) = smram_ram(addr, 2, false) {
        write16_ram(ram, value);
        return;
    }
    if addr & 4095 > 4094 || touches_low_hole(addr, 2) {
        write8(addr, value & 0xFF);
        write8(addr.wrapping_add(1), value >> 8 & 0xFF);
        return;
    }
    if let Some(host) = mmio_ram::write_host(addr, 2) {
        ptr::write_unaligned(host as *mut u16, value as u16)
    }
    else {
        ext::mmap_write16(addr, value)
    }
}
pub unsafe fn mmap_write32(addr: u32, value: i32) {
    if let Some(ram) = smram_ram(addr, 4, false) {
        write32_ram(ram, value);
        return;
    }
    if aperture::contains(addr) && addr & 3 == 0 && long_mode() {
        aperture::write32(addr, value as u32);
        return;
    }
    if addr & 4095 > 4092 || touches_low_hole(addr, 4) {
        for index in 0..4 {
            write8(addr.wrapping_add(index), value >> (index * 8) & 0xFF);
        }
        return;
    }
    if let Some(host) = mmio_ram::write_host(addr, 4) {
        ptr::write_unaligned(host as *mut i32, value)
    }
    else if addr >= APIC_MEM_ADDRESS && addr < APIC_MEM_ADDRESS + APIC_MEM_SIZE {
        apic::write32(addr - APIC_MEM_ADDRESS, value as u32);
        handle_irqs();
    }
    else if addr >= IOAPIC_MEM_ADDRESS && addr < IOAPIC_MEM_ADDRESS + IOAPIC_MEM_SIZE {
        ioapic::write32(addr - IOAPIC_MEM_ADDRESS, value as u32);
        handle_irqs();
    }
    else {
        ext::mmap_write32(addr, value)
    }
}
pub unsafe fn mmap_write64(addr: u32, value: u64) {
    if let Some(ram) = smram_ram(addr, 8, false) {
        jit::jit_dirty_cache_small(ram, ram + 8);
        write64_no_mmap_or_dirty_check(ram, value);
        return;
    }
    if addr & 4095 > 4088 || touches_low_hole(addr, 8) {
        for index in 0..8 {
            write8(
                addr.wrapping_add(index),
                (value >> (index * 8)) as u8 as i32,
            );
        }
        return;
    }
    if let Some(host) = mmio_ram::write_host(addr, 8) {
        ptr::write_unaligned(host as *mut u64, value)
    }
    else {
        ext::mmap_write64(addr, value as i32, (value >> 32) as i32)
    }
}
pub unsafe fn mmap_write128(addr: u32, v0: u64, v1: u64) {
    if let Some(ram) = smram_ram(addr, 16, false) {
        jit::jit_dirty_cache_small(ram, ram + 16);
        write128_no_mmap_or_dirty_check(ram, reg128 { u64: [v0, v1] });
        return;
    }
    if addr & 4095 > 4080 || touches_low_hole(addr, 16) {
        for (offset, value) in [(0, v0), (8, v1)] {
            for index in 0..8 {
                write8(
                    addr.wrapping_add(offset + index),
                    (value >> (index * 8)) as u8 as i32,
                );
            }
        }
        return;
    }
    if let Some(host) = mmio_ram::write_host(addr, 16) {
        ptr::write_unaligned(host as *mut u64, v0);
        ptr::write_unaligned(host.add(8) as *mut u64, v1)
    }
    else {
        ext::mmap_write128(
            addr,
            v0 as i32,
            (v0 >> 32) as i32,
            v1 as i32,
            (v1 >> 32) as i32,
        )
    }
}

#[no_mangle]
pub unsafe fn is_memory_zeroed(addr: u32, length: u32) -> bool {
    dbg_assert!(addr % 8 == 0);
    dbg_assert!(length % 8 == 0);
    for i in (addr..addr + length).step_by(8) {
        if *(mem8.offset(i as isize) as *const i64) != 0 {
            return false;
        }
    }
    return true;
}
                                                                              source/v64/src/rust/cpu/misc_instr.rs                                                               0000644 0000000 0000000 00000041432 00000000000 014763  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::cpu::cpu::*;
use crate::cpu::global_pointers::*;
use crate::paging::OrPageFault;

pub unsafe fn getcf() -> bool {
    if 0 != *flags_changed & 1 {
        let m = (2 << *last_op_size) - 1;
        dbg_assert!((*last_op1 as u32) <= m);
        dbg_assert!((*last_result as u32) <= m);

        let sub_mask = *flags_changed >> 31;

        // sub: last_op1 < last_result  (or last_op1 < last_op2) (or (result ^ ((result ^ b) & (b ^ a))))
        // add: last_result < last_op1  (or last_result < last_op2) (or a ^ ((a ^ b) & (b ^ result)))
        return ((*last_result as i32 ^ sub_mask) as u32) < (*last_op1 ^ sub_mask) as u32;
    }
    else {
        return 0 != *flags & 1;
    };
}
#[no_mangle]
pub unsafe fn getpf() -> bool {
    if 0 != *flags_changed & FLAG_PARITY {
        // inverted lookup table
        return 0 != 0x9669 << 2 >> ((*last_result ^ *last_result >> 4) & 15) & FLAG_PARITY;
    }
    else {
        return 0 != *flags & FLAG_PARITY;
    };
}
pub unsafe fn getaf() -> bool {
    if 0 != *flags_changed & FLAG_ADJUST {
        let is_sub = *flags_changed & FLAG_SUB != 0;
        let last_op2 = (*last_result - *last_op1) * if is_sub { -1 } else { 1 };
        return 0 != (*last_op1 ^ last_op2 ^ *last_result) & FLAG_ADJUST;
    }
    else {
        return 0 != *flags & FLAG_ADJUST;
    };
}
pub unsafe fn getzf() -> bool {
    if 0 != *flags_changed & FLAG_ZERO {
        return 0 != (!*last_result & *last_result - 1) >> *last_op_size & 1;
    }
    else {
        return 0 != *flags & FLAG_ZERO;
    };
}
pub unsafe fn getsf() -> bool {
    if 0 != *flags_changed & FLAG_SIGN {
        return 0 != *last_result >> *last_op_size & 1;
    }
    else {
        return 0 != *flags & FLAG_SIGN;
    };
}
pub unsafe fn getof() -> bool {
    if 0 != *flags_changed & FLAG_OVERFLOW {
        let is_sub = (*flags_changed as u32) >> 31;

        // add: (a ^ result) & (b ^ result)
        // sub: (a ^ result) & (b ^ result ^ 1) (or (a ^ b) & (result ^ a))
        let b_xor_1_if_sub = (*last_result - *last_op1) - is_sub as i32;
        return 0
            != ((*last_op1 ^ *last_result) & (b_xor_1_if_sub ^ *last_result)) >> *last_op_size & 1;
    }
    else {
        return 0 != *flags & FLAG_OVERFLOW;
    };
}

pub unsafe fn test_o() -> bool { return getof(); }
pub unsafe fn test_b() -> bool { return getcf(); }
pub unsafe fn test_z() -> bool { return getzf(); }
pub unsafe fn test_s() -> bool { return getsf(); }
#[no_mangle]
pub unsafe fn test_p() -> bool { return getpf(); }
pub unsafe fn test_be() -> bool { return getcf() || getzf(); }
pub unsafe fn test_l() -> bool { return getsf() != getof(); }
pub unsafe fn test_le() -> bool { return getzf() || getsf() != getof(); }
pub unsafe fn test_no() -> bool { return !test_o(); }
pub unsafe fn test_nb() -> bool { return !test_b(); }
pub unsafe fn test_nz() -> bool { return !test_z(); }
pub unsafe fn test_ns() -> bool { return !test_s(); }
pub unsafe fn test_nbe() -> bool { return !test_be(); }
pub unsafe fn test_nl() -> bool { return !test_l(); }
pub unsafe fn test_nle() -> bool { return !test_le(); }

pub unsafe fn jmp_rel16(rel16: i32) {
    let cs_offset = get_seg_cs();
    // limit ip to 16 bit
    *instruction_pointer = cs_offset + (*instruction_pointer - cs_offset + rel16 & 0xFFFF);
}
pub unsafe fn jmpcc16(condition: bool, imm16: i32) {
    if condition {
        jmp_rel16(imm16);
    };
}
pub unsafe fn jmpcc32(condition: bool, imm32: i32) {
    if condition {
        *instruction_pointer += imm32
    };
}
pub unsafe fn loope16(imm8s: i32) { jmpcc16(0 != decr_ecx_asize(is_asize_32()) && getzf(), imm8s); }
pub unsafe fn loopne16(imm8s: i32) {
    jmpcc16(0 != decr_ecx_asize(is_asize_32()) && !getzf(), imm8s);
}
pub unsafe fn loop16(imm8s: i32) { jmpcc16(0 != decr_ecx_asize(is_asize_32()), imm8s); }
pub unsafe fn jcxz16(imm8s: i32) { jmpcc16(get_reg_asize(ECX) == 0, imm8s); }
pub unsafe fn loope32(imm8s: i32) { jmpcc32(0 != decr_ecx_asize(is_asize_32()) && getzf(), imm8s); }
pub unsafe fn loopne32(imm8s: i32) {
    jmpcc32(0 != decr_ecx_asize(is_asize_32()) && !getzf(), imm8s);
}
pub unsafe fn loop32(imm8s: i32) { jmpcc32(0 != decr_ecx_asize(is_asize_32()), imm8s); }
pub unsafe fn jcxz32(imm8s: i32) { jmpcc32(get_reg_asize(ECX) == 0, imm8s); }

pub unsafe fn cmovcc16(condition: bool, value: i32, r: i32) {
    if condition {
        write_reg16(r, value);
    };
}
pub unsafe fn cmovcc32(condition: bool, value: i32, r: i32) {
    if condition {
        write_reg32(r, value);
    };
}

pub unsafe fn get_stack_pointer(offset: i32) -> i32 {
    if *stack_size_32 {
        return get_seg_ss() + read_reg32(ESP) + offset;
    }
    else {
        return get_seg_ss() + (read_reg16(SP) + offset & 0xFFFF);
    };
}
pub unsafe fn adjust_stack_reg(adjustment: i32) {
    if *stack_size_32 {
        write_reg32(ESP, read_reg32(ESP) + adjustment);
    }
    else {
        write_reg16(SP, read_reg16(SP) + adjustment);
    };
}

pub unsafe fn push16_ss16(imm16: i32) -> OrPageFault<()> {
    let sp = get_seg_ss() + (read_reg16(SP) - 2 & 0xFFFF);
    safe_write16(sp, imm16)?;
    write_reg16(SP, read_reg16(SP) - 2);
    Ok(())
}
pub unsafe fn push16_ss32(imm16: i32) -> OrPageFault<()> {
    let sp = get_seg_ss() + read_reg32(ESP) - 2;
    safe_write16(sp, imm16)?;
    write_reg32(ESP, read_reg32(ESP) - 2);
    Ok(())
}

pub unsafe fn push16_ss16_mem(addr: i32) -> OrPageFault<()> { push16_ss16(safe_read16(addr)?) }
pub unsafe fn push16_ss32_mem(addr: i32) -> OrPageFault<()> { push16_ss32(safe_read16(addr)?) }

pub unsafe fn push16(imm16: i32) -> OrPageFault<()> {
    if *stack_size_32 {
        push16_ss32(imm16)
    }
    else {
        push16_ss16(imm16)
    }
}

pub unsafe fn push32_ss16(imm32: i32) -> OrPageFault<()> {
    let new_sp = read_reg16(SP) - 4 & 0xFFFF;
    safe_write32(get_seg_ss() + new_sp, imm32)?;
    write_reg16(SP, new_sp);
    Ok(())
}
pub unsafe fn push32_ss32(imm32: i32) -> OrPageFault<()> {
    let new_esp = read_reg32(ESP) - 4;
    safe_write32(get_seg_ss() + new_esp, imm32)?;
    write_reg32(ESP, new_esp);
    Ok(())
}

pub unsafe fn push32_ss16_mem(addr: i32) -> OrPageFault<()> { push32_ss16(safe_read32s(addr)?) }
pub unsafe fn push32_ss32_mem(addr: i32) -> OrPageFault<()> { push32_ss32(safe_read32s(addr)?) }

pub unsafe fn push32(imm32: i32) -> OrPageFault<()> {
    if *stack_size_32 {
        push32_ss32(imm32)
    }
    else {
        push32_ss16(imm32)
    }
}

pub unsafe fn push32_sreg(i: i32) -> OrPageFault<()> {
    // you can't make this up ...
    if *stack_size_32 {
        let new_esp = read_reg32(ESP) - 4;
        safe_write16(get_seg_ss() + new_esp, *sreg.offset(i as isize) as i32)?;
        write_reg32(ESP, new_esp);
    }
    else {
        let new_sp = read_reg16(SP) - 4 & 0xFFFF;
        safe_write16(get_seg_ss() + new_sp, *sreg.offset(i as isize) as i32)?;
        write_reg16(SP, new_sp);
    }
    Ok(())
}

pub unsafe fn pop16() -> OrPageFault<i32> {
    if *stack_size_32 {
        pop16_ss32()
    }
    else {
        pop16_ss16()
    }
}
pub unsafe fn pop16_ss16() -> OrPageFault<i32> {
    let sp = get_seg_ss() + read_reg16(SP);
    let result = safe_read16(sp)?;
    write_reg16(SP, read_reg16(SP) + 2);
    Ok(result)
}
pub unsafe fn pop16_ss32() -> OrPageFault<i32> {
    let esp = get_seg_ss() + read_reg32(ESP);
    let result = safe_read16(esp)?;
    write_reg32(ESP, read_reg32(ESP) + 2);
    Ok(result)
}
pub unsafe fn pop32s() -> OrPageFault<i32> {
    if *stack_size_32 {
        pop32s_ss32()
    }
    else {
        pop32s_ss16()
    }
}
pub unsafe fn pop32s_ss16() -> OrPageFault<i32> {
    let sp = read_reg16(SP);
    let result = safe_read32s(get_seg_ss() + sp)?;
    write_reg16(SP, sp + 4);
    Ok(result)
}
pub unsafe fn pop32s_ss32() -> OrPageFault<i32> {
    let esp = read_reg32(ESP);
    let result = safe_read32s(get_seg_ss() + esp)?;
    write_reg32(ESP, read_reg32(ESP) + 4);
    Ok(result)
}
pub unsafe fn pusha16() {
    let temp = read_reg16(SP);
    // make sure we don't get a pagefault after having
    // pushed several registers already
    return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-16), 16));
    push16(read_reg16(AX)).unwrap();
    push16(read_reg16(CX)).unwrap();
    push16(read_reg16(DX)).unwrap();
    push16(read_reg16(BX)).unwrap();
    push16(temp as i32).unwrap();
    push16(read_reg16(BP)).unwrap();
    push16(read_reg16(SI)).unwrap();
    push16(read_reg16(DI)).unwrap();
}
pub unsafe fn pusha32() {
    let temp = read_reg32(ESP);
    return_on_pagefault!(writable_or_pagefault(get_stack_pointer(-32), 32));
    push32(read_reg32(EAX)).unwrap();
    push32(read_reg32(ECX)).unwrap();
    push32(read_reg32(EDX)).unwrap();
    push32(read_reg32(EBX)).unwrap();
    push32(temp).unwrap();
    push32(read_reg32(EBP)).unwrap();
    push32(read_reg32(ESI)).unwrap();
    push32(read_reg32(EDI)).unwrap();
}

pub unsafe fn lss16(addr: i32, reg: i32, seg: i32) {
    let new_reg = return_on_pagefault!(safe_read16(addr));
    let new_seg = return_on_pagefault!(safe_read16(addr + 2));

    if !switch_seg(seg, new_seg) {
        return;
    }

    write_reg16(reg, new_reg);
}

pub unsafe fn lss32(addr: i32, reg: i32, seg: i32) {
    let new_reg = return_on_pagefault!(safe_read32s(addr));
    let new_seg = return_on_pagefault!(safe_read16(addr + 4));

    if !switch_seg(seg, new_seg) {
        return;
    }

    write_reg32(reg, new_reg);
}

pub unsafe fn enter16(size: i32, mut nesting_level: i32) {
    nesting_level &= 31;

    if nesting_level > 0 {
        dbg_log!(
            "enter16 stack={} size={} nest={}",
            (if *stack_size_32 { 16 } else { 32 }),
            size,
            nesting_level,
        );
    }

    let ss_mask = if *stack_size_32 { -1 } else { 0xFFFF };
    let ss = get_seg_ss();
    let frame_temp = read_reg32(ESP) - 2;

    if nesting_level > 0 {
        let mut tmp_ebp = read_reg32(EBP);
        for _ in 1..nesting_level {
            tmp_ebp -= 2;
            push16(safe_read16(ss + (tmp_ebp & ss_mask)).unwrap()).unwrap();
        }
        push16(frame_temp).unwrap();
    }

    return_on_pagefault!(safe_write16(ss + (frame_temp & ss_mask), read_reg16(BP)));
    write_reg16(BP, frame_temp);
    adjust_stack_reg(-size - 2);
}

pub unsafe fn enter32(size: i32, mut nesting_level: i32) {
    nesting_level &= 31;

    if nesting_level > 0 {
        dbg_log!(
            "enter32 stack={} size={} nest={}",
            (if *stack_size_32 { 16 } else { 32 }),
            size,
            nesting_level,
        );
    }

    let ss_mask = if *stack_size_32 { -1 } else { 0xFFFF };
    let ss = get_seg_ss();
    let frame_temp = read_reg32(ESP) - 4;

    if nesting_level > 0 {
        let mut tmp_ebp = read_reg32(EBP);
        for _ in 1..nesting_level {
            tmp_ebp -= 4;
            push32(safe_read32s(ss + (tmp_ebp & ss_mask)).unwrap()).unwrap();
        }
        push32(frame_temp).unwrap();
    }

    return_on_pagefault!(safe_write32(ss + (frame_temp & ss_mask), read_reg32(EBP)));
    write_reg32(EBP, frame_temp);
    adjust_stack_reg(-size - 4);
}

pub unsafe fn setcc_reg(condition: bool, r: i32) { write_reg8(r, condition as i32); }
pub unsafe fn setcc_mem(condition: bool, addr: i32) {
    return_on_pagefault!(safe_write8(addr, condition as i32));
}

pub unsafe fn fxsave(addr: i32) { fxsave_checked(addr); }
/// false: a fault was delivered (cpu::xstate::fxsave)
pub unsafe fn fxsave_checked(addr: i32) -> bool { crate::cpu::xstate::fxsave_32(addr) }
pub unsafe fn fxrstor(addr: i32) { fxrstor_checked(addr); }
/// false: a fault was delivered (cpu::xstate::fxrstor)
pub unsafe fn fxrstor_checked(addr: i32) -> bool { crate::cpu::xstate::fxrstor_32(addr) }

pub unsafe fn xchg8(data: i32, r8: i32) -> i32 {
    let tmp = read_reg8(r8);
    write_reg8(r8, data);
    return tmp;
}
pub unsafe fn xchg16(data: i32, r16: i32) -> i32 {
    let tmp = read_reg16(r16);
    write_reg16(r16, data);
    return tmp;
}
pub unsafe fn xchg16r(r16: i32) {
    let tmp = read_reg16(AX);
    write_reg16(AX, read_reg16(r16));
    write_reg16(r16, tmp);
}
pub unsafe fn xchg32(data: i32, r32: i32) -> i32 {
    let tmp = read_reg32(r32);
    write_reg32(r32, data);
    return tmp;
}
pub unsafe fn xchg32r(r32: i32) {
    let tmp = read_reg32(EAX);
    write_reg32(EAX, read_reg32(r32));
    write_reg32(r32, tmp);
}

pub unsafe fn bswap(r: i32) { write_reg32(r, read_reg32(r).swap_bytes()) }

pub unsafe fn lar(selector: i32, original: i32) -> i32 {
    if false {
        dbg_log!("lar sel={:x}", selector);
    }

    const LAR_INVALID_TYPE: u32 =
        1 << 0 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 0xA | 1 << 0xD | 1 << 0xE | 1 << 0xF;

    let sel = SegmentSelector::of_u16(selector as u16);
    match lookup_segment_selector(sel) {
        Err(()) => {
            // pagefault
            return original;
        },
        Ok(Err(_)) => {
            *flags_changed &= !FLAG_ZERO;
            *flags &= !FLAG_ZERO;
            dbg_log!("lar: invalid selector={:x}: null or invalid", selector);
            return original;
        },
        Ok(Ok((desc, _))) => {
            *flags_changed &= !FLAG_ZERO;
            let dpl_bad = desc.dpl() < *cpl || desc.dpl() < sel.rpl();

            if if desc.is_system() {
                (LAR_INVALID_TYPE >> desc.system_type() & 1 == 1) || dpl_bad
            }
            else {
                !desc.is_conforming_executable() && dpl_bad
            } {
                dbg_log!(
                    "lar: invalid selector={:x} is_null={} is_system={}",
                    selector,
                    false,
                    desc.is_system()
                );
                *flags &= !FLAG_ZERO;
                return original;
            }
            else {
                *flags |= FLAG_ZERO;
                return (desc.raw >> 32) as i32 & 0x00FFFF00;
            }
        },
    }
}

pub unsafe fn lsl(selector: i32, original: i32) -> i32 {
    if false {
        dbg_log!("lsl sel={:x}", selector);
    }

    const LSL_INVALID_TYPE: i32 = 1 << 0
        | 1 << 4
        | 1 << 5
        | 1 << 6
        | 1 << 7
        | 1 << 8
        | 1 << 0xA
        | 1 << 0xC
        | 1 << 0xD
        | 1 << 0xE
        | 1 << 0xF;

    let sel = SegmentSelector::of_u16(selector as u16);
    match lookup_segment_selector(sel) {
        Err(()) => {
            // pagefault
            return original;
        },
        Ok(Err(_)) => {
            *flags_changed &= !FLAG_ZERO;
            *flags &= !FLAG_ZERO;
            dbg_log!("lsl: invalid selector={:x}: null or invalid", selector);
            return original;
        },
        Ok(Ok((desc, _))) => {
            *flags_changed &= !FLAG_ZERO;
            let dpl_bad = desc.dpl() < *cpl || desc.dpl() < sel.rpl();

            if if desc.is_system() {
                (LSL_INVALID_TYPE >> desc.system_type() & 1 == 1) || dpl_bad
            }
            else {
                !desc.is_conforming_executable() && dpl_bad
            } {
                dbg_log!(
                    "lsl: invalid  selector={:x} is_null={} is_system={}",
                    selector,
                    false,
                    desc.is_system(),
                );
                *flags &= !FLAG_ZERO;
                return original;
            }
            else {
                *flags |= FLAG_ZERO;
                return desc.effective_limit() as i32;
            }
        },
    }
}

pub unsafe fn verr(selector: i32) {
    *flags_changed &= !FLAG_ZERO;
    let sel = SegmentSelector::of_u16(selector as u16);
    match return_on_pagefault!(lookup_segment_selector(sel)) {
        Err(_) => {
            *flags &= !FLAG_ZERO;
            dbg_log!("verr -> invalid. selector={:x}", selector);
        },
        Ok((desc, _)) => {
            if desc.is_system()
                || !desc.is_readable()
                || (!desc.is_conforming_executable()
                    && (desc.dpl() < *cpl || desc.dpl() < sel.rpl()))
            {
                dbg_log!("verr -> invalid. selector={:x}", selector);
                *flags &= !FLAG_ZERO;
            }
            else {
                dbg_log!("verr -> valid. selector={:x}", selector);
                *flags |= FLAG_ZERO;
            }
        },
    }
}

pub unsafe fn verw(selector: i32) {
    *flags_changed &= !FLAG_ZERO;
    let sel = SegmentSelector::of_u16(selector as u16);
    match return_on_pagefault!(lookup_segment_selector(sel)) {
        Err(_) => {
            *flags &= !FLAG_ZERO;
            dbg_log!("verw -> invalid. selector={:x}", selector);
        },
        Ok((desc, _)) => {
            if desc.is_system()
                || !desc.is_writable()
                || desc.dpl() < *cpl
                || desc.dpl() < sel.rpl()
            {
                dbg_log!(
                    "verw invalid selector={:x} is_system={} is_writable={}",
                    selector,
                    desc.is_system(),
                    desc.is_writable(),
                );
                *flags &= !FLAG_ZERO;
            }
            else {
                *flags |= FLAG_ZERO;
            }
        },
    }
}
                                                                                                                                                                                                                                      source/v64/src/rust/cpu/mmio_ram.rs                                                                 0000644 0000000 0000000 00000052761 00000000000 014420  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Device memory in the guest's physical address space: plain wasm memory
//! that a device owns -- the VGA core's frame buffer (every display adapter),
//! VMware SVGA's command FIFO, virtio-gpu's host visible memory, the UEFI
//! firmware's flash -- decoded where the device's PCI memory BAR currently is
//! (the flash: below 4 GiB). The guest reads and writes
//! it at memory speed; each region keeps a bitmap of the 4 KiB pages written
//! since its device last took them, and can convert those pages into an RGBA
//! picture for the screen. A read-only region (the flash in its read mode)
//! leaves writes to the memory map's handlers.
//!
//! Regions are page aligned and a whole number of pages, so an access that
//! does not cross a page boundary is entirely inside one region or outside all
//! of them. The table belongs to the machine instance: with cores in workers,
//! every instance looks regions up (and marks pages) through
//! crate::parallel::machine, and the backing and bitmaps are shared memory.

#![allow(static_mut_refs)]

use crate::cpu::global_pointers;
use crate::parallel;

use std::alloc;
use std::ptr;

pub const MAX_REGIONS: usize = 6;
const PAGE_SIZE: u32 = 4096;

#[derive(Clone, Copy)]
pub struct Region {
    /// Guest physical address of the first byte, while `mapped`
    pub base: u32,
    pub size: u32,
    pub mapped: bool,
    /// The device asked for it at `base` (mmio_ram_map): it is mapped there
    /// whenever that is possible (see mmio_ram_reserve)
    pub requested: bool,
    /// Writes reach the memory; otherwise they go to the memory map
    /// (crate::cpu::memory's ext::mmap_write*)
    pub writable: bool,
    /// The memory itself, in the wasm heap
    pub backing: *mut u8,
    /// One bit per page, written since the device last took them
    pub dirty: *mut u64,
    pub dirty_words: u32,
}

const EMPTY: Region = Region {
    base: 0,
    size: 0,
    mapped: false,
    requested: false,
    writable: true,
    backing: ptr::null_mut(),
    dirty: ptr::null_mut(),
    dirty_words: 0,
};

struct Table {
    regions: [Region; MAX_REGIONS],
    count: usize,
    /// RGBA pictures converted from a region (mmio_ram_fill_pixels)
    pixels: [Vec<u32>; MAX_REGIONS],
    /// Bitmap words taken from a region (mmio_ram_take_dirty)
    taken: [Vec<u64>; MAX_REGIONS],
    /// [start, end) that the chipset decodes before any device (mmio_ram_reserve)
    reserved: (u32, u32),
}

const NEW_TABLE: Table = Table {
    regions: [EMPTY; MAX_REGIONS],
    count: 0,
    pixels: [const { Vec::new() }; MAX_REGIONS],
    taken: [const { Vec::new() }; MAX_REGIONS],
    reserved: (0, 0),
};

#[cfg(not(test))]
static mut TABLE: Table = NEW_TABLE;

#[cfg(test)]
thread_local! {
    /// cargo test: the table of the test thread (the tests run in parallel)
    static TEST_TABLE: std::cell::UnsafeCell<Table> =
        const { std::cell::UnsafeCell::new(NEW_TABLE) };
}

#[inline(always)]
fn table() -> &'static mut Table {
    #[cfg(test)]
    return TEST_TABLE.with(|table| unsafe { &mut *table.get() });
    #[cfg(not(test))]
    unsafe {
        &mut *parallel::machine(&raw mut TABLE)
    }
}

/// The mapped region that contains all of [address, address + bytes)
#[inline]
pub fn find(address: u32, bytes: u32) -> Option<&'static Region> {
    let table = table();
    for region in table.regions[..table.count].iter() {
        let offset = address.wrapping_sub(region.base);
        if region.mapped && offset < region.size && bytes <= region.size - offset {
            return Some(region);
        }
    }
    None
}

/// Whether a mapped region decodes `address`
#[inline]
pub fn contains(address: u32) -> bool { find(address, 1).is_some() }

/// Whether the page at `address` (page aligned) is in a mapped read-only
/// region: its bytes do not change while that holds (mmio_ram_map,
/// mmio_ram_unmap and mmio_ram_set_writable retire code compiled from it)
#[inline]
pub fn read_only_page(address: u32) -> bool {
    find(address, PAGE_SIZE).map_or(false, |r| !r.writable)
}

/// Whether a mapped region decodes `address` and takes writes
#[inline]
pub fn contains_writable(address: u32) -> bool { find(address, 1).map_or(false, |r| r.writable) }

/// The memory behind [address, address + bytes) of a region, for reading
#[inline]
pub unsafe fn read_host(address: u32, bytes: u32) -> Option<*mut u8> {
    let region = find(address, bytes)?;
    Some(region.backing.add((address - region.base) as usize))
}

/// The memory behind [address, address + bytes) of a region, for writing:
/// the pages it touches are marked written. None for a read-only region.
#[inline]
pub unsafe fn write_host(address: u32, bytes: u32) -> Option<*mut u8> {
    let region = find(address, bytes).filter(|r| r.writable)?;
    let offset = address - region.base;
    let last = offset + bytes.max(1) - 1;
    for page in offset / PAGE_SIZE..=last / PAGE_SIZE {
        mark_page(region, page);
    }
    Some(region.backing.add(offset as usize))
}

#[inline]
unsafe fn mark_page(region: &Region, page: u32) {
    dbg_assert!(page >> 6 < region.dirty_words);
    parallel::or64(
        region.dirty.add((page >> 6) as usize).cast(),
        1 << (page & 63),
    )
}

/// Whether `host` is the memory of any region (the x64 page tier's direct
/// translations of written pages must be retired once the pages are taken)
pub fn backs(host: u32) -> bool {
    let table = table();
    table.regions[..table.count]
        .iter()
        .any(|region| host.wrapping_sub(region.backing as u32) < region.size)
}

/// Take a bitmap word: its pages are no longer written as far as the next
/// call knows. Atomic, since cores in workers may be marking pages.
unsafe fn take_word(word: *mut u64) -> u64 {
    #[cfg(feature = "parallel")]
    {
        use std::sync::atomic::{AtomicU64, Ordering::SeqCst};
        (*(word as *const AtomicU64)).swap(0, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        let value = *word;
        *word = 0;
        value
    }
}

unsafe fn region(id: u32) -> Option<&'static mut Region> {
    let table = table();
    if (id as usize) < table.count {
        Some(&mut table.regions[id as usize])
    }
    else {
        None
    }
}

/// A new region of `size` bytes (a multiple of 4 KiB), unmapped and zeroed
/// @return its id, or -1
#[no_mangle]
pub unsafe fn mmio_ram_allocate(size: u32) -> i32 {
    let table = table();
    if table.count == MAX_REGIONS || size == 0 || size % PAGE_SIZE != 0 {
        dbg_assert!(false, "mmio_ram_allocate: no region or bad size");
        return -1;
    }
    let pages = size / PAGE_SIZE;
    let dirty_words = (pages + 63) / 64;
    let backing = alloc::alloc_zeroed(alloc::Layout::from_size_align(size as usize, 4096).unwrap());
    let dirty =
        alloc::alloc_zeroed(alloc::Layout::array::<u64>(dirty_words as usize).unwrap()) as *mut u64;
    if backing.is_null() || dirty.is_null() {
        return -1;
    }
    let id = table.count;
    table.regions[id] = Region {
        base: 0,
        size,
        mapped: false,
        requested: false,
        writable: true,
        backing,
        dirty,
        dirty_words,
    };
    table.count += 1;
    id as i32
}

/// The region's memory, relative to the start of the wasm memory
#[no_mangle]
pub unsafe fn mmio_ram_backing(id: u32) -> u32 { region(id).map_or(0, |r| r.backing as u32) }

/// Whether nothing but devices is decoded at [base, base + size): not RAM,
/// not the legacy ranges below 1 MiB. A BAR the guest clears or has not
/// assigned yet must not shadow memory.
#[cfg(not(test))]
unsafe fn free_for_devices(base: u32, size: u32) -> bool {
    let last = base + (size - 1);
    base >= 0x100000
        && crate::cpu::memory::in_mapped_range(base)
        && crate::cpu::memory::in_mapped_range(last)
}
#[cfg(test)]
unsafe fn free_for_devices(base: u32, _size: u32) -> bool { base >= 0x100000 }

/// Whether a region of `size` bytes can be decoded at `base`: in the 32-bit
/// space, page aligned, free for devices and outside the reserved window
unsafe fn decodable(base: u32, size: u32) -> bool {
    let (start, end) = table().reserved;
    base as u64 + size as u64 <= 1 << 32
        && base % PAGE_SIZE == 0
        && free_for_devices(base, size)
        && (base as u64 + size as u64 <= start as u64 || base >= end)
}

/// Decode the region at guest physical `base` (page aligned), for example
/// where the guest has just moved its BAR. Anywhere it cannot be decoded
/// (see decodable), it is not mapped until that changes.
#[no_mangle]
pub unsafe fn mmio_ram_map(id: u32, base: u32) {
    let Some(region) = region(id)
    else {
        return;
    };
    region.base = base;
    region.requested = true;
    region.mapped = decodable(base, region.size);
    if !region.mapped {
        dbg_log!(
            "mmio_ram_map: region {} cannot be decoded at {:x}",
            id,
            base
        );
    }
    // x64 page functions may hold direct translations of the old place, and
    // code compiled from it
    crate::x64::jac::flush_all();
    crate::x64::pages::retire_device_code();
}

/// The chipset decodes [base, base + size) itself, before the PCI bus:
/// Q35's ECAM (PCIEXBAR). No region is decoded there; a region the window
/// moves away from is decoded at its base again. Size 0: no such window.
#[no_mangle]
pub unsafe fn mmio_ram_reserve(base: u32, size: u32) {
    let table = table();
    table.reserved = (
        base,
        if size == 0 { base } else { base.saturating_add(size) },
    );
    for region in table.regions[..table.count].iter_mut() {
        if region.requested {
            region.mapped = decodable(region.base, region.size);
        }
    }
    crate::x64::jac::flush_all();
    crate::x64::pages::retire_device_code();
}

/// Let writes reach the region's memory, or leave them to the memory map
#[no_mangle]
pub unsafe fn mmio_ram_set_writable(id: u32, writable: bool) {
    if let Some(region) = region(id) {
        region.writable = writable;
        // x64 page functions may hold direct write translations, and code
        // compiled from read-only memory
        crate::x64::jac::flush_all();
        crate::x64::pages::retire_device_code();
    }
}

/// Stop decoding the region anywhere (its memory is kept)
#[no_mangle]
pub unsafe fn mmio_ram_unmap(id: u32) {
    if let Some(region) = region(id) {
        region.mapped = false;
        region.requested = false;
        crate::x64::jac::flush_all();
        crate::x64::pages::retire_device_code();
    }
}

/// A byte of the region by its offset, wherever and whether it is mapped
/// (the VGA's banked window at 0xA0000 reaches the frame buffer this way)
#[no_mangle]
pub unsafe fn mmio_ram_read8(id: u32, offset: u32) -> i32 {
    match region(id) {
        Some(region) if offset < region.size => *region.backing.add(offset as usize) as i32,
        _ => 0xFF,
    }
}

#[no_mangle]
pub unsafe fn mmio_ram_write8(id: u32, offset: u32, value: i32) {
    if let Some(region) = region(id) {
        if offset < region.size {
            mark_page(region, offset / PAGE_SIZE);
            *region.backing.add(offset as usize) = value as u8;
        }
    }
}

/// Mark every page of the region written, e.g. to have all of it redrawn
#[no_mangle]
pub unsafe fn mmio_ram_mark_dirty(id: u32) {
    if let Some(region) = region(id) {
        for i in 0..region.dirty_words as usize {
            parallel::or64(region.dirty.add(i).cast(), u64::MAX);
        }
    }
}

/// Take the region's bitmap (the pages written since the last call, a bit a
/// page, 64 pages a word) into a buffer of the table's, for a device that
/// keeps a copy of the region elsewhere (virtio-gpu's host visible memory
/// and the GPU's buffers)
/// @return the buffer's address, relative to the start of the wasm memory
/// (as many words as the region has), or 0
#[no_mangle]
pub unsafe fn mmio_ram_take_dirty(id: u32) -> u32 {
    let Some(region) = region(id)
    else {
        return 0;
    };
    let region = *region;
    let taken = &mut table().taken[id as usize];
    taken.clear();
    taken.resize(region.dirty_words as usize, 0);
    for i in 0..region.dirty_words as usize {
        taken[i] = take_word(region.dirty.add(i));
    }
    // (as mmio_ram_fill_pixels: direct x64 write translations mark again)
    crate::x64::jac::retire_frame_buffer_writes();
    taken.as_mut_ptr() as u32
}

/// An RGBA buffer of `pixels` pixels that mmio_ram_fill_pixels converts the
/// region into, replacing the previous one
/// @return its address, relative to the start of the wasm memory
#[no_mangle]
pub unsafe fn mmio_ram_allocate_pixels(id: u32, pixels: u32) -> u32 {
    if region(id).is_none() {
        return 0;
    }
    let buffer = &mut table().pixels[id as usize];
    buffer.clear();
    buffer.resize(pixels as usize, 0);
    buffer.as_mut_ptr() as u32
}

/// Call `f` with the byte offset of each page written since the last call,
/// and forget them.
/// @return the first and last byte of those pages (u32::MAX and 0xFFF when
/// there were none)
unsafe fn take_dirty_pages(region: &Region, mut f: impl FnMut(u32)) -> (u32, u32) {
    let mut min_offset = u32::MAX;
    let mut max_offset = 0;
    for i in 0..region.dirty_words {
        let mut word = take_word(region.dirty.add(i as usize));
        while word != 0 {
            let bit = word.trailing_zeros();
            word &= word - 1;
            let offset = (i << 6 | bit) * PAGE_SIZE;
            if offset >= region.size {
                continue;
            }
            if min_offset == u32::MAX {
                min_offset = offset;
            }
            max_offset = offset;
            f(offset);
        }
    }
    (min_offset, max_offset + 0xFFF)
}

/// Convert the pages of the region written since the last call into its RGBA
/// buffer (mmio_ram_allocate_pixels), as `bpp`-bit pixels, the first
/// `first_pixel` of the region not shown (panning, page flipping). 8-bit
/// pixels go through a palette the region does not know: not handled here.
/// Reports the byte range of the pages in svga_dirty_bitmap_min_offset and
/// svga_dirty_bitmap_max_offset, for the screen to redraw only those rows.
#[no_mangle]
pub unsafe fn mmio_ram_fill_pixels(id: u32, bpp: u32, first_pixel: u32) {
    let (min_offset, max_offset) = fill_pixels(id, bpp, first_pixel);
    *global_pointers::svga_dirty_bitmap_min_offset = min_offset;
    *global_pointers::svga_dirty_bitmap_max_offset = max_offset;
}

unsafe fn fill_pixels(id: u32, bpp: u32, first_pixel: u32) -> (u32, u32) {
    let Some(region) = region(id)
    else {
        return (u32::MAX, 0xFFF);
    };
    let region = *region;
    let dest = &mut table().pixels[id as usize];
    let bytes_per_pixel = match bpp {
        32 => 4,
        24 => 3,
        16 | 15 => 2,
        _ => {
            dbg_log!("mmio_ram_fill_pixels: unsupported bpp {}", bpp);
            dbg_assert!(false, "Unsupported bpp");
            return (u32::MAX, 0xFFF);
        },
    };
    let source = region.backing;
    let size = region.size as usize;
    let range = take_dirty_pages(&region, |offset| {
        // The pixels that start in this page; a 24-bit pixel may begin in
        // the page before, and its dirty bit covers it too
        let first = (offset as usize + bytes_per_pixel - 1) / bytes_per_pixel;
        let first = if bytes_per_pixel == 3 && first > 0 { first - 1 } else { first };
        let end = ((offset + PAGE_SIZE) as usize).min(size) / bytes_per_pixel;
        for pixel in first..end {
            let Some(index) = pixel.checked_sub(first_pixel as usize)
            else {
                continue;
            };
            if index >= dest.len() {
                break;
            }
            let at = source.add(pixel * bytes_per_pixel);
            dest[index] = match bpp {
                32 => {
                    let dword = ptr::read_unaligned(at as *const u32);
                    dword << 16 | dword >> 16 & 0xFF | dword & 0xFF00 | 0xFF00_0000
                },
                24 => {
                    let dword = *at as u32 | (*at.add(1) as u32) << 8 | (*at.add(2) as u32) << 16;
                    dword << 16 | dword >> 16 & 0xFF | dword & 0xFF00 | 0xFF00_0000
                },
                16 => {
                    let word = ptr::read_unaligned(at as *const u16) as u32;
                    let r = (word & 0x1F) * 0xFF / 0x1F;
                    let g = (word >> 5 & 0x3F) * 0xFF / 0x3F;
                    let b = (word >> 11) * 0xFF / 0x1F;
                    r << 16 | g << 8 | b | 0xFF00_0000
                },
                _ => {
                    let word = ptr::read_unaligned(at as *const u16) as u32;
                    let r = (word & 0x1F) * 0xFF / 0x1F;
                    let g = (word >> 5 & 0x1F) * 0xFF / 0x1F;
                    let b = (word >> 10 & 0x1F) * 0xFF / 0x1F;
                    r << 16 | g << 8 | b | 0xFF00_0000
                },
            };
        }
    });
    // x64 page functions write the frame buffer directly once a write
    // translation marked its page: retire those, so the next write marks again
    crate::x64::jac::retire_frame_buffer_writes();
    range
}

#[cfg(test)]
mod tests {
    use super::*;

    unsafe fn reset() {
        let table = table();
        table.count = 0;
        table.reserved = (0, 0);
    }

    #[test]
    fn read_only_regions_leave_writes_to_the_memory_map() {
        unsafe {
            reset();
            // (the firmware's flash)
            let flash = mmio_ram_allocate(4 * 4096) as u32;
            mmio_ram_map(flash, 0xFFFF_C000);
            mmio_ram_set_writable(flash, false);
            assert!(read_host(0xFFFF_F000, 4).is_some());
            assert!(write_host(0xFFFF_F000, 4).is_none());
            assert!(read_only_page(0xFFFF_F000));
            assert!(contains(0xFFFF_F000) && !contains_writable(0xFFFF_F000));
            mmio_ram_set_writable(flash, true);
            assert!(write_host(0xFFFF_F000, 4).is_some());
            assert!(!read_only_page(0xFFFF_F000));
        }
    }

    #[test]
    fn nothing_is_decoded_in_the_reserved_window() {
        unsafe {
            reset();
            // a frame buffer where the chipset puts its ECAM window: not
            // decoded while the window is there, back once it moved away
            let id = mmio_ram_allocate(64 * 4096) as u32;
            mmio_ram_map(id, 0xE000_0000);
            mmio_ram_reserve(0xE000_0000, 0x1000_0000);
            assert!(!contains(0xE000_0000));
            mmio_ram_reserve(0, 0);
            assert!(contains(0xE000_0000));
            // moved into the window: waits; moved out of it: decoded at once
            mmio_ram_reserve(0xE000_0000, 0x1000_0000);
            mmio_ram_map(id, 0xE800_0000);
            assert!(!contains(0xE800_0000));
            mmio_ram_map(id, 0x8000_0000);
            assert!(contains(0x8000_0000));
            // (a window ending at 4 GiB, and one just below the region)
            mmio_ram_reserve(0xF000_0000, 0x1000_0000);
            assert!(contains(0x8000_0000));
            mmio_ram_reserve(0x7000_0000, 0x1000_0000);
            assert!(contains(0x8000_0000));
            // unmapped by its device: whatever the window does
            mmio_ram_unmap(id);
            mmio_ram_reserve(0, 0);
            assert!(!contains(0x8000_0000));
        }
    }

    #[test]
    fn regions_decode_where_mapped_and_track_written_pages() {
        unsafe {
            reset();
            let id = mmio_ram_allocate(64 * 4096) as u32;
            assert!(!contains(0xE000_0000), "unmapped until placed");
            mmio_ram_map(id, 0xE000_0000);
            assert!(contains(0xE000_0000) && contains(0xE003_FFFF));
            assert!(!contains(0xE004_0000) && !contains(0xDFFF_FFFF));
            // an access has to fit entirely
            assert!(read_host(0xE003_FFFE, 2).is_some());
            assert!(read_host(0xE003_FFFE, 4).is_none());

            let p = write_host(0xE000_1000, 4).unwrap();
            *(p as *mut u32) = 0x11223344;
            assert_eq!(
                *(read_host(0xE000_1000, 4).unwrap() as *const u32),
                0x11223344
            );
            let region = find(0xE000_0000, 1).unwrap();
            assert_eq!(*region.dirty, 0b10, "page 1 written");

            // moved by the guest: decoded at the new place, same memory
            mmio_ram_map(id, 0xF000_0000);
            assert!(!contains(0xE000_1000));
            assert_eq!(
                *(read_host(0xF000_1000, 4).unwrap() as *const u32),
                0x11223344
            );
            mmio_ram_unmap(id);
            assert!(!contains(0xF000_1000));
        }
    }

    #[test]
    fn written_pages_convert_to_rgba_once() {
        unsafe {
            reset();
            let id = mmio_ram_allocate(2 * 4096) as u32;
            mmio_ram_map(id, 0xE000_0000);
            mmio_ram_allocate_pixels(id, 2048);
            // (the export returns a wasm address; natively, take the pointer)
            let pixels = table().pixels[id as usize].as_ptr();
            // 32 bpp, pixel 1030 in page 1: xRGB 0x00112233
            *(write_host(0xE000_0000 + 1030 * 4, 4).unwrap() as *mut u32) = 0x0011_2233;
            // RGBA bytes in memory: 0x11 0x22 0x33 0xFF
            assert_eq!(fill_pixels(id, 32, 0), (4096, 8191));
            assert_eq!(*pixels.add(1030), 0xFF33_2211);
            // taken: a second call converts nothing
            *(find(0xE000_0000, 1).unwrap().backing.add(1030 * 4) as *mut u32) = 0;
            assert_eq!(fill_pixels(id, 32, 0), (u32::MAX, 0xFFF));
            assert_eq!(*pixels.add(1030), 0xFF33_2211);

            // skipping the first pixels (panning)
            *(write_host(0xE000_0000 + 1030 * 4, 4).unwrap() as *mut u32) = 0x00AA_BBCC;
            fill_pixels(id, 32, 1000);
            assert_eq!(*pixels.add(30), 0xFFCC_BBAA);
        }
    }
}
               source/v64/src/rust/cpu/mod.rs                                                                      0000644 0000000 0000000 00000001071 00000000000 013363  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub mod apic;
pub mod arith;
pub mod avx;
pub mod bmi;
pub mod call_indirect;
pub mod context;
pub mod cpu;
pub mod exceptions;
pub mod execution;
pub mod features;
pub mod fpu;
pub mod global_pointers;
pub mod instructions;
pub mod instructions_0f;
pub mod instructions_0f38;
pub mod instructions_0f3a;
pub mod ioapic;
pub mod isa_hooks;
pub mod memory;
pub mod misc_instr;
pub mod mmio_ram;
pub mod modrm;
pub mod pic;
pub mod simd_fp;
pub mod simd_int;
pub mod simd_ops;
pub mod smm;
pub mod sse_instr;
pub mod string;
pub mod topology;
pub mod vex;
pub mod xstate;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/src/rust/cpu/modrm.rs                                                                    0000644 0000000 0000000 00000010506 00000000000 013725  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Shared address forms with baseline-ordered instruction fetch and segment checks.
use crate::cpu::cpu::*;
use crate::paging::OrPageFault;
unsafe fn resolve(modrm: i32, size: u8) -> OrPageFault<i32> {
    let sib = if size == 32 && modrm & 7 == 4 { Some(read_imm8()? as u8) } else { None };
    let form = crate::decode_rules::address_form(modrm as u8, size, sib);
    let base = form.base.map_or(0, |r| {
        if size == 16 {
            read_reg16(r as i32)
        }
        else {
            read_reg32(r as i32)
        }
    });
    let index = form
        .index
        .map_or(0, |r| {
            if size == 16 {
                read_reg16(r as i32)
            }
            else {
                read_reg32(r as i32)
            }
        })
        .wrapping_shl(form.scale as u32);
    let early_segment = if form.segment_before_displacement {
        Some(get_seg_prefix(form.segment as i32)?)
    }
    else {
        None
    };
    let displacement = match form.displacement_bytes {
        0 => 0,
        1 => read_imm8s()?,
        2 => read_imm16()?,
        4 => read_imm32s()?,
        _ => unreachable!(),
    };
    let offset = base.wrapping_add(index).wrapping_add(displacement);
    let offset = if size == 16 { offset & 65535 } else { offset };
    Ok(early_segment
        .unwrap_or(0)
        .wrapping_add(offset)
        .wrapping_add(if early_segment.is_none() {
            get_seg_prefix(form.segment as i32)?
        }
        else {
            0
        }))
}
/// A memory operand's offset and segment (its default; get_seg_prefix applies
/// a prefix), its SIB and displacement bytes fetched, its segment not yet
/// checked: VEX instructions check the AVX state in between (cpu::vex)
pub unsafe fn resolve_offset(modrm: i32) -> OrPageFault<(i32, i32)> {
    let size = if is_asize_32() { 32 } else { 16 };
    let sib = if size == 32 && modrm & 7 == 4 { Some(read_imm8()? as u8) } else { None };
    let form = crate::decode_rules::address_form(modrm as u8, size, sib);
    let register = |r: u8| {
        if size == 16 {
            read_reg16(r as i32)
        }
        else {
            read_reg32(r as i32)
        }
    };
    let base = form.base.map_or(0, register);
    let index = form
        .index
        .map_or(0, register)
        .wrapping_shl(form.scale as u32);
    let displacement = match form.displacement_bytes {
        0 => 0,
        1 => read_imm8s()?,
        2 => read_imm16()?,
        4 => read_imm32s()?,
        _ => unreachable!(),
    };
    let offset = base.wrapping_add(index).wrapping_add(displacement);
    Ok((
        if size == 16 { offset & 65535 } else { offset },
        form.segment as i32,
    ))
}
/// A VSIB memory operand (the gathers; 32-bit addressing: 16-bit is #UD):
/// the offset of its base and displacement, its segment, and its SIB
/// byte's index field (a vector register) and scale (log2)
pub unsafe fn resolve_offset_vsib(modrm: i32) -> OrPageFault<(i32, i32, u8, u8)> {
    let sib = read_imm8()? as u8;
    // (the base and displacement of the same SIB without an index)
    let form = crate::decode_rules::address_form(modrm as u8, 32, Some(sib & !0x38 | 0x20));
    let base = form.base.map_or(0, |r| read_reg32(r as i32));
    let displacement = match form.displacement_bytes {
        0 => 0,
        1 => read_imm8s()?,
        4 => read_imm32s()?,
        _ => unreachable!(),
    };
    Ok((
        base.wrapping_add(displacement),
        form.segment as i32,
        sib >> 3 & 7,
        sib >> 6,
    ))
}
pub unsafe fn resolve_modrm16(m: i32) -> OrPageFault<i32> { resolve(m, 16) }
pub unsafe fn resolve_modrm32(m: i32) -> OrPageFault<i32> { resolve(m, 32) }
pub unsafe fn resolve_modrm32_(m: i32) -> OrPageFault<i32> { resolve(m, 32) }
#[cfg(feature = "ir-test-hooks")]
#[path = "../../../tests/decode/legacy_modrm.rs"]
pub mod legacy;

#[cfg(feature = "ir-test-hooks")]
#[no_mangle]
pub unsafe fn ir_test_resolve_modrm(modrm: u32, size: u32, old: u32) -> u64 {
    let result = match (size, old != 0) {
        (16, true) => legacy::resolve_modrm16(modrm as i32),
        (32, true) => legacy::resolve_modrm32(modrm as i32),
        (16, false) => resolve_modrm16(modrm as i32),
        (32, false) => resolve_modrm32(modrm as i32),
        _ => panic!("invalid test mode"),
    };
    match result {
        Ok(address) => address as u32 as u64,
        Err(()) => 1u64 << 32,
    }
}
                                                                                                                                                                                          source/v64/src/rust/cpu/pic.rs                                                                      0000644 0000000 0000000 00000027474 00000000000 013376  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(non_snake_case)]

// Programmable Interrupt Controller
// http://stanislavs.org/helppc/8259.html

use std::sync::{Mutex, MutexGuard};

pub const PIC_LOG: bool = false;
pub const PIC_LOG_VERBOSE: bool = false;

// Note: This layout is deliberately chosen to match the old JavaScript pic state
// (cpu.get_state_pic depens on this layout)
const _: () = assert!(std::mem::offset_of!(Pic0, special_mask_mode) == 12);
#[repr(C)]
struct Pic0 {
    irq_mask: u8,

    irq_map: u8,

    // in-service register
    // Holds interrupts that are currently being serviced
    isr: u8,

    // interrupt request register
    // Holds interrupts that have been requested
    irr: u8,

    master: bool,
    dummy: u8, // remove when state image is updated

    expect_icw4: bool,
    state: u8,
    read_isr: bool,
    auto_eoi: bool,

    elcr: u8,

    irq_value: u8,
    special_mask_mode: bool,
}

struct Pic {
    master: Pic0,
    slave: Pic0,
}

static PIC: Mutex<Pic> = Mutex::new(Pic {
    master: Pic0 {
        // all irqs off
        irq_mask: 0,
        // Bogus default value (both master and slave mapped to 0).
        // Will be initialized by the BIOS
        irq_map: 0,
        // in-service register
        // Holds interrupts that are currently being serviced
        isr: 0,
        // interrupt request register
        // Holds interrupts that have been requested
        irr: 0,
        irq_value: 0,
        expect_icw4: false,
        state: 0,
        read_isr: false,
        auto_eoi: false,
        special_mask_mode: false,
        elcr: 0,
        master: true,
        dummy: 0,
    },
    slave: Pic0 {
        // all irqs off
        irq_mask: 0,
        // Bogus default value (both master and slave mapped to 0).
        // Will be initialized by the BIOS
        irq_map: 0,
        // in-service register
        // Holds interrupts that are currently being serviced
        isr: 0,
        // interrupt request register
        // Holds interrupts that have been requested
        irr: 0,
        irq_value: 0,
        expect_icw4: false,
        state: 0,
        read_isr: false,
        auto_eoi: false,
        special_mask_mode: false,
        elcr: 0,
        master: false,
        dummy: 0,
    },
});

pub fn reset() {
    let mut pic = get_pic();
    let Pic { master, slave } = &mut *pic;
    for state in [master, slave] {
        state.irq_mask = 0;
        state.irq_map = 0;
        state.isr = 0;
        state.irr = 0;
        state.irq_value = 0;
        state.expect_icw4 = false;
        state.state = 0;
        state.read_isr = false;
        state.auto_eoi = false;
        state.special_mask_mode = false;
        state.elcr = 0;
    }
}

fn get_pic() -> MutexGuard<'static, Pic> { PIC.try_lock().unwrap() }

// called from javascript for saving/restoring state
#[no_mangle]
pub fn get_pic_addr_master() -> u32 { &raw mut get_pic().master as u32 }
#[no_mangle]
pub fn get_pic_addr_slave() -> u32 { &raw mut get_pic().slave as u32 }

impl Pic0 {
    fn get_irq(&self) -> Option<u8> {
        let enabled_irr = self.irr & self.irq_mask;

        if enabled_irr == 0 {
            if PIC_LOG_VERBOSE {
                dbg_log!(
                    "[PIC] no unmasked irrs. irr={:x} mask={:x} isr={:x}",
                    self.irr,
                    self.irq_mask,
                    self.isr
                );
            }
            return None;
        }

        let irq_mask = enabled_irr & (!enabled_irr + 1);
        let special_mask = if self.special_mask_mode { self.irq_mask } else { 0xFF };

        if self.isr != 0 && (self.isr & (!self.isr + 1) & special_mask) <= irq_mask {
            // wait for eoi of higher or same priority interrupt
            if PIC_LOG {
                dbg_log!(
                    "[PIC] higher prio: master={} isr={:x} mask={:x} irq={:x}",
                    self.master,
                    self.isr,
                    self.irq_mask,
                    irq_mask
                );
            }
            return None;
        }

        dbg_assert!(irq_mask != 0);
        let irq_number = irq_mask.ilog2() as u8;
        dbg_assert!(irq_mask == 1 << irq_number);

        if PIC_LOG_VERBOSE {
            dbg_log!("[PIC] request irq {}", irq_number);
        }

        Some(irq_number)
    }

    fn port0_read(self: &Pic0) -> u32 { (if self.read_isr { self.isr } else { self.irr }) as u32 }
    fn port1_read(self: &Pic0) -> u32 { !self.irq_mask as u32 }
}

impl Pic {
    fn set_irq(self: &mut Pic, i: u8) {
        let mask = 1 << (i & 7);
        let dev = if i < 8 { &mut self.master } else { &mut self.slave };
        if dev.irq_value & mask == 0 || dev.elcr & mask != 0 {
            dev.irr |= mask;
            dev.irq_value |= mask;
            if i >= 8 {
                self.check_irqs_slave()
            }
        }
    }

    fn clear_irq(self: &mut Pic, i: u8) {
        let mask = 1 << (i & 7);
        let dev = if i < 8 { &mut self.master } else { &mut self.slave };
        dev.irq_value &= !mask;
        if dev.elcr & mask != 0 {
            dev.irr &= !mask;
            if i >= 8 {
                self.check_irqs_slave()
            }
        }
    }

    fn port0_write(&mut self, index: u8, v: u8) {
        let dev = if index == 0 { &mut self.master } else { &mut self.slave };
        if v & 0x10 != 0 {
            // xxxx1xxx
            // icw1
            dbg_log!("icw1 = {:x}", v);
            dev.isr = 0;
            dev.irr = 0;
            dev.irq_mask = 0xff;
            dev.irq_value = 0;
            dev.auto_eoi = true;

            dev.expect_icw4 = v & 1 != 0;
            dbg_assert!(v & 2 == 0, "unimplemented: single mode");
            dbg_assert!(v & 8 == 0, "unimplemented: level mode");
            dev.state = 1;
        }
        else if v & 8 != 0 {
            // xxx01xxx
            // ocw3
            dbg_log!("ocw3: {:x}", v);
            if v & 2 != 0 {
                dev.read_isr = v & 1 != 0;
            }
            if v & 4 != 0 {
                dbg_assert!(false, "unimplemented: polling");
            }
            if v & 0x40 != 0 {
                dev.special_mask_mode = (v & 0x20) == 0x20;
                dbg_log!("special mask mode: {}", dev.special_mask_mode);
            }
        }
        else {
            // xxx00xxx
            // ocw2
            // end of interrupt
            if PIC_LOG {
                dbg_log!("eoi: {:x}", v);
            }

            let eoi_type = v >> 5;

            if eoi_type == 1 {
                // non-specific eoi
                dev.isr &= dev.isr - 1;
                if PIC_LOG {
                    dbg_log!("new isr: {:x}", dev.isr);
                }
            }
            else if eoi_type == 3 {
                // specific eoi
                dev.isr &= !(1 << (v & 7));
            }
            else if eoi_type == 6 {
                // os2 v4, freebsd
                let priority = v & 7;
                dbg_log!("lowest priority: {:x}", priority);
            }
            else {
                dbg_log!("Unknown eoi: {:x} type={:x}", v, eoi_type);
                dbg_assert!(false);
                dev.isr &= dev.isr - 1;
            }

            if index == 1 {
                self.check_irqs_slave()
            }
        }
    }

    fn port1_write(&mut self, index: u8, v: u8) {
        let dev = if index == 0 { &mut self.master } else { &mut self.slave };
        if dev.state == 0 {
            if dev.expect_icw4 {
                // icw4
                dev.expect_icw4 = false;
                dev.auto_eoi = v & 2 != 0;
                dbg_log!("icw4: {:x} autoeoi={}", v, dev.auto_eoi);
                dbg_assert!(v & 0x10 == 0, "unimplemented: nested mode");
                dbg_assert!(v & 1 == 1, "unimplemented: 8086/88 mode");
            }
            else {
                // ocw1
                dev.irq_mask = !v;

                if PIC_LOG_VERBOSE {
                    dbg_log!("interrupt mask: {:x}", dev.irq_mask);
                }

                if index == 1 {
                    self.check_irqs_slave()
                }
            }
        }
        else if dev.state == 1 {
            // icw2
            dev.irq_map = v;
            dbg_log!("interrupts are mapped to {:x}", dev.irq_map);
            dev.state += 1;
        }
        else if dev.state == 2 {
            // icw3
            dev.state = 0;
            dbg_log!("icw3: {:x}", v);
        }
    }

    fn check_irqs_slave(&mut self) {
        let is_set = self.slave.get_irq().is_some();
        if is_set {
            self.set_irq(2)
        }
        else {
            self.clear_irq(2)
        }
    }
}

// called by the cpu
/// Read-only counterpart of acknowledgement. A cascade request also requires
/// the cold path even if the slave is empty: acknowledgement mutates the master.
pub fn has_pending_irq() -> bool {
    let pic = get_pic();
    pic.master.get_irq().is_some()
}
pub fn pic_acknowledge_irq() -> Option<u8> {
    let mut pic = get_pic();
    let irq = match pic.master.get_irq() {
        Some(i) => i,
        None => return None,
    };

    if pic.master.irr == 0 {
        dbg_assert!(false);
        //PIC_LOG_VERBOSE && dbg_log!("master> spurious requested=" + irq);
        //Some(pic.irq_map | 7)
        return None;
    }

    let mask = 1 << irq;

    if pic.master.elcr & mask == 0 {
        // not in level mode
        pic.master.irr &= !mask;
    }

    if !pic.master.auto_eoi {
        pic.master.isr |= mask;
    }

    if PIC_LOG_VERBOSE {
        dbg_log!("[PIC] master> acknowledge {}", irq);
    }

    dbg_assert!(pic.master.get_irq().is_none());

    if irq == 2 {
        acknowledge_irq_slave(&mut pic)
    }
    else {
        Some(pic.master.irq_map | irq)
    }
}

fn acknowledge_irq_slave(pic: &mut Pic) -> Option<u8> {
    let irq = match pic.slave.get_irq() {
        Some(i) => i,
        None => return None,
    };

    if pic.slave.irr == 0 {
        //PIC_LOG_VERBOSE && dbg_log!("slave> spurious requested=" + irq);
        //Some(pic.irq_map | 7)
        dbg_assert!(false);
        return None;
    }

    let mask = 1 << irq;

    if pic.slave.elcr & mask == 0 {
        // not in level mode
        pic.slave.irr &= !mask;
    }

    if !pic.slave.auto_eoi {
        pic.slave.isr |= mask;
    }

    if PIC_LOG_VERBOSE {
        dbg_log!("[PIC] slave> acknowledge {}", irq);
    }

    dbg_assert!(pic.slave.get_irq().is_none());
    pic.clear_irq(2);

    Some(pic.slave.irq_map | irq)
}

pub fn set_irq(i: u8) {
    dbg_assert!(i < 16);

    if PIC_LOG_VERBOSE {
        dbg_log!("[PIC] set irq {}", i);
    }

    get_pic().set_irq(i)
}

pub fn clear_irq(i: u8) {
    dbg_assert!(i < 16);

    if PIC_LOG_VERBOSE {
        dbg_log!("[PIC] clear irq {}", i);
    }

    get_pic().clear_irq(i)
}

pub fn port20_read() -> u32 { get_pic().master.port0_read() }
pub fn port21_read() -> u32 { get_pic().master.port1_read() }

pub fn portA0_read() -> u32 { get_pic().slave.port0_read() }
pub fn portA1_read() -> u32 { get_pic().slave.port1_read() }

/// A command or mask register was written since take_port_written: an EOI or
/// an unmask can make a pending interrupt deliverable without the
/// handle_irqs a raised one gets (cpu::run_compat_instruction)
static mut PORT_WRITTEN: bool = false;
pub fn take_port_written() -> bool {
    unsafe { std::mem::replace(&mut *(&raw mut PORT_WRITTEN), false) }
}

pub fn port20_write(v: u8) {
    unsafe { PORT_WRITTEN = true };
    get_pic().port0_write(0, v)
}
pub fn port21_write(v: u8) {
    unsafe { PORT_WRITTEN = true };
    get_pic().port1_write(0, v)
}

pub fn portA0_write(v: u8) {
    unsafe { PORT_WRITTEN = true };
    get_pic().port0_write(1, v)
}
pub fn portA1_write(v: u8) {
    unsafe { PORT_WRITTEN = true };
    get_pic().port1_write(1, v)
}

pub fn port4D0_read() -> u32 { get_pic().master.elcr as u32 }
pub fn port4D1_read() -> u32 { get_pic().slave.elcr as u32 }
pub fn port4D0_write(v: u8) { get_pic().master.elcr = v }
pub fn port4D1_write(v: u8) { get_pic().slave.elcr = v }
                                                                                                                                                                                                    source/v64/src/rust/cpu/simd_fp.rs                                                                  0000644 0000000 0000000 00000151423 00000000000 014234  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! SSE floating point as the processor computes it (docs/simd-xsave-plan.md
//! 7.4): every operation through SoftFloat (its 8086-SSE specialization gives
//! x86's NaN rules), with MXCSR's rounding mode, DAZ and FZ, its exception
//! flags, and the fault of an unmasked exception. Shared by the 32-bit
//! interpreter (and the IR helpers that call it) and the x64 engine; compiled
//! code runs natively only where that gives the same results and flags.
//!
//! Operands and results are the bits of 128-bit registers (lane 0 in the low
//! bits), a VEX.256 form's the two halves of 256-bit ones; the engines read
//! the operands and write the results.
//!
//! The order of exceptions follows SDM Vol. 1, 11.5.3: pre-computation
//! exceptions (invalid operation, denormal operand, divide by zero) of all
//! lanes come first. When one of them is unmasked, MXCSR gets their flags and
//! the instruction faults without computing anything else. Otherwise the
//! post-computation exceptions (overflow, underflow, precision) are detected;
//! when one of them is unmasked, MXCSR gets all flags and the instruction
//! faults. Either way the destination is left alone. Within a lane, an
//! invalid operation, a QNaN operand and division by zero take precedence
//! over the denormal operand exception (SDM Vol. 1, 4.9.2).

use crate::cpu::global_pointers as gp;

extern "C" {
    fn f32_add(a: u32, b: u32) -> u32;
    fn f32_sub(a: u32, b: u32) -> u32;
    fn f32_mul(a: u32, b: u32) -> u32;
    fn f32_div(a: u32, b: u32) -> u32;
    fn f32_sqrt(a: u32) -> u32;
    fn f64_add(a: u64, b: u64) -> u64;
    fn f64_sub(a: u64, b: u64) -> u64;
    fn f64_mul(a: u64, b: u64) -> u64;
    fn f64_div(a: u64, b: u64) -> u64;
    fn f64_sqrt(a: u64) -> u64;
    fn f32_to_f64(a: u32) -> u64;
    fn f64_to_f32(a: u64) -> u32;
    fn i32_to_f32(a: i32) -> u32;
    fn i32_to_f64(a: i32) -> u64;
    fn i64_to_f32(a: i64) -> u32;
    fn i64_to_f64(a: i64) -> u64;
    fn f32_to_i32(a: u32, rounding: u8, exact: bool) -> i32;
    fn f32_to_i64(a: u32, rounding: u8, exact: bool) -> i64;
    fn f64_to_i32(a: u64, rounding: u8, exact: bool) -> i32;
    fn f64_to_i64(a: u64, rounding: u8, exact: bool) -> i64;
    fn f32_roundToInt(a: u32, rounding: u8, exact: bool) -> u32;
    fn f64_roundToInt(a: u64, rounding: u8, exact: bool) -> u64;
    fn f32_mulAdd(a: u32, b: u32, c: u32) -> u32;
    fn f64_mulAdd(a: u64, b: u64, c: u64) -> u64;
    // (float16_t is a struct of one u16: clang passes and returns it in an
    // i32 whose upper bits it does not define, so these take and give u32,
    // masked here; with u16 Rust would assume a zero-extended value)
    fn f16_to_f32(a: u32) -> u32;
    fn f32_to_f16(a: u32) -> u32;
    static mut softfloat_roundingMode: u8;
    static mut softfloat_exceptionFlags: u8;
}

// MXCSR's exception flags (its masks are 7 bits above)
pub const IE: u32 = 0x01;
pub const DE: u32 = 0x02;
pub const ZE: u32 = 0x04;
pub const OE: u32 = 0x08;
pub const UE: u32 = 0x10;
pub const PE: u32 = 0x20;
const PRE_COMPUTATION: u32 = IE | DE | ZE;
const DAZ: u32 = 0x40;
const UM: u32 = 0x800;
const FZ: u32 = 0x8000;
// SoftFloat's flags that take precedence over the denormal operand exception
const SF_UNDERFLOW: u8 = 2;
const SF_INFINITE: u8 = 8;
const SF_INVALID: u8 = 16;
/// SoftFloat's rounding mode for MXCSR.RC (nearest, down, up, toward zero)
const ROUNDING: [u8; 4] = [0, 2, 3, 1];

/// An unmasked SIMD floating-point exception: the engine raises #XM (#UD
/// without CR4.OSXMMEXCPT). MXCSR has the flags already; nothing else changed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Unmasked;

pub fn nan(v: u64, double: bool) -> bool {
    if double {
        v & 0x7FFF_FFFF_FFFF_FFFF > 0x7FF0_0000_0000_0000
    }
    else {
        v as u32 & 0x7FFF_FFFF > 0x7F80_0000
    }
}
pub fn snan(v: u64, double: bool) -> bool {
    nan(v, double) && v & if double { 1 << 51 } else { 1 << 22 } == 0
}
pub fn denormal(v: u64, double: bool) -> bool {
    if double {
        v & 0x7FF0_0000_0000_0000 == 0 && v & 0x000F_FFFF_FFFF_FFFF != 0
    }
    else {
        v & 0x7F80_0000 == 0 && v & 0x007F_FFFF != 0
    }
}
fn sign_mask(double: bool) -> u64 {
    if double {
        1 << 63
    }
    else {
        1 << 31
    }
}
fn lane_mask(double: bool) -> u128 {
    if double {
        u64::MAX as u128
    }
    else {
        u32::MAX as u128
    }
}
fn lane(v: u128, i: usize, double: bool) -> u64 {
    (v >> (if double { 64 } else { 32 } * i)) as u64 & lane_mask(double) as u64
}
fn set_lane(v: u128, i: usize, double: bool, x: u64) -> u128 {
    let shift = if double { 64 } else { 32 } * i;
    v & !(lane_mask(double) << shift) | (x as u128 & lane_mask(double)) << shift
}

/// One instruction's computation: MXCSR's controls, the flags so far, and
/// SoftFloat's state (shared with the x87 code) around it
pub struct Fp {
    mxcsr: u32,
    flags: u32,
    /// SoftFloat signalled underflow for the current lane: tiny after
    /// rounding (and inexact), even where the result rounded up to the
    /// smallest normal
    underflow: bool,
    saved_rounding: u8,
    saved_flags: u8,
}
impl Fp {
    pub unsafe fn new() -> Self {
        let mxcsr = *gp::mxcsr as u32;
        let fp = Self {
            mxcsr,
            flags: 0,
            underflow: false,
            saved_rounding: softfloat_roundingMode,
            saved_flags: softfloat_exceptionFlags,
        };
        softfloat_roundingMode = ROUNDING[(mxcsr >> 13 & 3) as usize];
        softfloat_exceptionFlags = 0;
        fp
    }
    /// SoftFloat's rounding mode for MXCSR.RC
    pub fn rounding(&self) -> u8 { ROUNDING[(self.mxcsr >> 13 & 3) as usize] }
    /// A source operand: a denormal is zero with DAZ, else the denormal
    /// operand exception (returned for the lane, see `lane`)
    fn input(&self, v: u64, double: bool, de: &mut u32) -> u64 {
        if denormal(v, double) {
            if self.mxcsr & DAZ != 0 {
                return v & sign_mask(double);
            }
            *de = DE;
        }
        v
    }
    /// A computed result (after `lane`): unmasked, the underflow exception is
    /// a tiny result even when exact; masked with FZ, a tiny result is zero
    /// (and inexact). Tiny: an exact denormal, or SoftFloat's underflow (an
    /// inexact one may round to the smallest normal)
    fn output(&mut self, v: u64, double: bool) -> u64 {
        if self.underflow || denormal(v, double) {
            if self.mxcsr & UM == 0 {
                self.flags |= UE;
            }
            else if self.mxcsr & FZ != 0 {
                self.flags |= UE | PE;
                return v & sign_mask(double);
            }
        }
        v
    }
    /// The flags of one lane: SoftFloat's (cleared for the next lane) and its
    /// denormal operand exception unless a QNaN operand, an invalid
    /// operation or a division by zero takes precedence
    unsafe fn lane(&mut self, de: u32, qnan_operand: bool) {
        let sf = softfloat_exceptionFlags;
        softfloat_exceptionFlags = 0;
        self.underflow = sf & SF_UNDERFLOW != 0;
        if !qnan_operand && sf & (SF_INVALID | SF_INFINITE) == 0 {
            self.flags |= de;
        }
        self.flags |= (sf as u32 & 1) << 5
            | (sf as u32 & 2) << 3
            | (sf as u32 & 4) << 1
            | (sf as u32 & 8) >> 1
            | (sf as u32 & 16) >> 4;
    }
    /// One lane of 0x51 SQRT (of b), 0x58 ADD, 0x59 MUL, 0x5C SUB, 0x5D MIN,
    /// 0x5E DIV, 0x5F MAX
    pub unsafe fn binary(&mut self, op: u8, a: u64, b: u64, double: bool) -> u64 {
        let mut de = 0;
        let a = if op == 0x51 { 0 } else { self.input(a, double, &mut de) };
        let b = self.input(b, double, &mut de);
        let qnan = nan(a, double) || nan(b, double);
        if op == 0x5D || op == 0x5F {
            // MIN and MAX: the second operand for any NaN (an invalid
            // operation) and for equal operands (zeros of either sign); no
            // post-computation exceptions
            let result = if qnan {
                self.flags |= IE;
                b
            }
            else {
                let (less, greater) = if double {
                    let (x, y) = (f64::from_bits(a), f64::from_bits(b));
                    (x < y, x > y)
                }
                else {
                    let (x, y) = (f32::from_bits(a as u32), f32::from_bits(b as u32));
                    (x < y, x > y)
                };
                if if op == 0x5D { less } else { greater } {
                    a
                }
                else {
                    b
                }
            };
            self.lane(de, qnan);
            return result;
        }
        let result = if double {
            match op {
                0x58 => f64_add(a, b),
                0x59 => f64_mul(a, b),
                0x5C => f64_sub(a, b),
                0x5E => f64_div(a, b),
                0x51 => f64_sqrt(b),
                _ => unreachable!(),
            }
        }
        else {
            let (a, b) = (a as u32, b as u32);
            (match op {
                0x58 => f32_add(a, b),
                0x59 => f32_mul(a, b),
                0x5C => f32_sub(a, b),
                0x5E => f32_div(a, b),
                0x51 => f32_sqrt(b),
                _ => unreachable!(),
            }) as u64
        };
        self.lane(de, qnan);
        self.output(result, double)
    }
    /// One lane of CMPPS/CMPPD/CMPSS/CMPSD's predicate 0-7, of VCMP*'s 0-31
    /// (imm8[3:0] the relation, imm8[4] swapping quiet and signaling; and
    /// COMISS/UCOMISS: 1 and 0): a QNaN is invalid for the signaling ones
    pub unsafe fn compare(&mut self, a: u64, b: u64, double: bool, predicate: u8) -> bool {
        let mut de = 0;
        let a = self.input(a, double, &mut de);
        let b = self.input(b, double, &mut de);
        let unordered = nan(a, double) || nan(b, double);
        // (the signaling predicates: 1, 2, 5 and 6 of each eight, the others
        // with imm8[4])
        let signaling = matches!(predicate & 7, 1 | 2 | 5 | 6) != (predicate & 16 != 0);
        if snan(a, double) || snan(b, double) || unordered && signaling {
            self.flags |= IE;
        }
        self.lane(de, unordered);
        let (eq, lt) = if unordered {
            (false, false)
        }
        else if double {
            (
                f64::from_bits(a) == f64::from_bits(b),
                f64::from_bits(a) < f64::from_bits(b),
            )
        }
        else {
            (
                f32::from_bits(a as u32) == f32::from_bits(b as u32),
                f32::from_bits(a as u32) < f32::from_bits(b as u32),
            )
        };
        if unordered {
            // UNORD, NEQ_U, NLT_U, NLE_U, EQ_U, NGE_U, NGT_U, TRUE
            return matches!(predicate & 15, 3..=6 | 8..=10 | 15);
        }
        // (ordered: imm8[2:0] decides; 8-15 are 0-7's other unordered results)
        match predicate & 7 {
            0 => eq,
            1 => lt,
            2 => lt || eq,
            3 => false,
            4 => !eq,
            5 => !lt,
            6 => !(lt || eq),
            _ => true,
        }
    }
    /// One lane of FMA (SDM Vol. 1, 14.5.2): `x` × `y`, negated if
    /// `negate_product`, plus `z`, negated if `negate_addend`, rounded once.
    /// A NaN operand gives the first of x, y and z quieted, and IE for an
    /// SNaN; with a QNaN addend 0 × ∞ gives that NaN without IE (SoftFloat's
    /// 8086-SSE rules give the default NaN with IE), so NaN operands are
    /// handled here, unnegated. Otherwise SoftFloat: 0 × ∞ and ∞ − ∞ are
    /// invalid operations (the default NaN).
    pub unsafe fn fused(
        &mut self,
        x: u64,
        y: u64,
        z: u64,
        double: bool,
        negate_product: bool,
        negate_addend: bool,
    ) -> u64 {
        let mut de = 0;
        let x = self.input(x, double, &mut de);
        let y = self.input(y, double, &mut de);
        let z = self.input(z, double, &mut de);
        if let Some(&first) = [x, y, z].iter().find(|&&v| nan(v, double)) {
            if snan(x, double) || snan(y, double) || snan(z, double) {
                self.flags |= IE;
            }
            self.lane(de, true);
            return first | if double { 1 << 51 } else { 1 << 22 };
        }
        let x = if negate_product { x ^ sign_mask(double) } else { x };
        let z = if negate_addend { z ^ sign_mask(double) } else { z };
        let result = if double {
            f64_mulAdd(x, y, z)
        }
        else {
            f32_mulAdd(x as u32, y as u32, z as u32) as u64
        };
        self.lane(de, false);
        self.output(result, double)
    }
    /// A half-precision result (VCVTPS2PH): FZ does not apply, a tiny result
    /// is a half denormal (SDM); unmasked, the underflow exception is a tiny
    /// result even when exact
    fn half_output(&mut self, v: u16) {
        let denormal = v & 0x7C00 == 0 && v & 0x03FF != 0;
        if (self.underflow || denormal) && self.mxcsr & UM == 0 {
            self.flags |= UE;
        }
    }
    /// A floating-point source of a conversion: DAZ, and the denormal operand
    /// exception unless `no_de` (conversions to integers do not have it)
    pub fn convert_input(&mut self, v: u64, double: bool, no_de: bool) -> u64 {
        let mut de = 0;
        let v = self.input(v, double, &mut de);
        if !no_de && !nan(v, double) {
            self.flags |= de;
        }
        v
    }
    /// The SoftFloat flags of a conversion lane
    pub unsafe fn convert_lane(&mut self) { self.lane(0, false) }
    /// A computed conversion result (see `output`)
    pub fn convert_output(&mut self, v: u64, double: bool) -> u64 { self.output(v, double) }
    /// Restore SoftFloat's state; commit the flags to MXCSR in the order of
    /// SDM Vol. 1, 11.5.3 (see above)
    pub unsafe fn finish(self) -> Result<(), Unmasked> {
        let flags = self.flags;
        softfloat_roundingMode = self.saved_rounding;
        softfloat_exceptionFlags = self.saved_flags;
        let unmasked = !(self.mxcsr >> 7) & 0x3F;
        let pre = flags & PRE_COMPUTATION;
        if pre & unmasked != 0 {
            *gp::mxcsr |= pre as i32;
            return Err(Unmasked);
        }
        *gp::mxcsr |= flags as i32;
        if flags & unmasked != 0 {
            return Err(Unmasked);
        }
        Ok(())
    }
}

/// One lane natively, by x86tpl::native_fp's rule (see there): with MXCSR at its
/// defaults and PE set (checked by the caller), host IEEE arithmetic gives
/// SoftFloat's result and changes no flag unless an operand is denormal or
/// the result is NaN, infinite or (MUL, DIV) tiny but not an exact zero. MIN,
/// MAX and the compares (`predicate`) need only operands that are neither NaN
/// nor denormal, whatever MXCSR. None: the exact path decides.
fn fast_lane(op: u8, a: u64, b: u64, double: bool, predicate: u8) -> Option<u64> {
    let abs = if double { u64::MAX >> 1 } else { 0x7FFF_FFFF };
    let min = if double { 0x0010_0000_0000_0000 } else { 0x0080_0000 };
    let infinity = if double { 0x7FF0_0000_0000_0000 } else { 0x7F80_0000 };
    let (ma, mb) = (a & abs, b & abs);
    let denormal = |m: u64| m != 0 && m < min;
    if denormal(mb) || op != 0x51 && denormal(ma) {
        return None;
    }
    if matches!(op, 0x5D | 0x5F | 0xC2) {
        if ma > infinity || mb > infinity {
            return None;
        }
        use std::cmp::Ordering::*;
        let order = if double {
            f64::from_bits(a).partial_cmp(&f64::from_bits(b))
        }
        else {
            f32::from_bits(a as u32).partial_cmp(&f32::from_bits(b as u32))
        }
        .unwrap();
        return Some(match op {
            0x5D => {
                if order == Less {
                    a
                }
                else {
                    b
                }
            },
            0x5F => {
                if order == Greater {
                    a
                }
                else {
                    b
                }
            },
            _ => {
                let truth = match predicate & 7 {
                    0 => order == Equal,
                    1 => order == Less,
                    2 => order != Greater,
                    3 => false,
                    4 => order != Equal,
                    5 => order != Less,
                    6 => order == Greater,
                    _ => true,
                };
                if truth {
                    lane_mask(double) as u64
                }
                else {
                    0
                }
            },
        });
    }
    let r = if double {
        let (x, y) = (f64::from_bits(a), f64::from_bits(b));
        (match op {
            0x58 => x + y,
            0x5C => x - y,
            0x59 => x * y,
            0x5E => x / y,
            _ => y.sqrt(),
        })
        .to_bits()
    }
    else {
        let (x, y) = (f32::from_bits(a as u32), f32::from_bits(b as u32));
        (match op {
            0x58 => x + y,
            0x5C => x - y,
            0x59 => x * y,
            0x5E => x / y,
            _ => y.sqrt(),
        })
        .to_bits() as u64
    };
    let mr = r & abs;
    if mr >= infinity {
        return None;
    }
    if matches!(op, 0x59 | 0x5E) && mr <= min && !(mr == 0 && (ma == 0 || op == 0x59 && mb == 0)) {
        return None;
    }
    Some(r)
}

/// The lanes of a form: (double, scalar, lane count)
fn shape(op: u32) -> (bool, bool) {
    let prefix = op >> 16;
    (matches!(prefix, 0x66 | 0xF2), matches!(prefix, 0xF2 | 0xF3))
}

/// SQRT/ADD/MUL/SUB/MIN/DIV/MAX (0F 51, 58-5F), CMP (0F C2, `imm8` the
/// predicate), HADD/HSUB (66/F2 0F 7C/7D) and ADDSUB (66/F2 0F D0), PS/PD/SS/SD
/// by the mandatory prefix of `op` (the catalogue key): the new destination.
/// A scalar form leaves the destination's upper lanes alone.
pub unsafe fn arithmetic(
    op: u32,
    destination: u128,
    source: u128,
    imm8: u8,
) -> Result<u128, Unmasked> {
    // (legacy CMP: imm8[2:0], its other bits ignored)
    operate(op, [destination], [source], imm8 & 7).map(|[r]| r)
}
/// VCMPPS/VCMPPD/VCMPSS/VCMPSD (VEX.0F C2): `arithmetic`'s CMP with the 32
/// predicates of imm8[4:0]
pub unsafe fn compare(
    op: u32,
    destination: u128,
    source: u128,
    imm8: u8,
) -> Result<u128, Unmasked> {
    operate(op, [destination], [source], imm8 & 31).map(|[r]| r)
}
/// The VEX.256 forms of `arithmetic` (VCMPPS/PD: `compare`'s): the lanes of
/// both halves (HADD/HSUB's pairs within each) with one exception context,
/// the halves of the new destination
pub unsafe fn arithmetic256(
    op: u32,
    destination: (u128, u128),
    source: (u128, u128),
    imm8: u8,
) -> Result<(u128, u128), Unmasked> {
    operate(
        op,
        [destination.0, destination.1],
        [source.0, source.1],
        imm8 & 31,
    )
    .map(|[low, high]| (low, high))
}
/// One half's `lanes` natively (fast_lane), or None when one is not
unsafe fn fast_half(
    code: u8,
    destination: u128,
    source: u128,
    double: bool,
    lanes: usize,
    imm8: u8,
) -> Option<u128> {
    // (lanes as arrays: u128 shifts are slow in Wasm)
    if double {
        let (d, s): ([u64; 2], [u64; 2]) = (
            std::mem::transmute(destination),
            std::mem::transmute(source),
        );
        let mut r = d;
        for i in 0..lanes {
            r[i] = fast_lane(code, d[i], s[i], true, imm8)?;
        }
        Some(std::mem::transmute(r))
    }
    else {
        let (d, s): ([u32; 4], [u32; 4]) = (
            std::mem::transmute(destination),
            std::mem::transmute(source),
        );
        let mut r = d;
        for i in 0..lanes {
            r[i] = fast_lane(code, d[i] as u64, s[i] as u64, false, imm8)? as u32;
        }
        Some(std::mem::transmute(r))
    }
}
/// `arithmetic` of N halves (a VEX.256 form: 2) with one exception context
unsafe fn operate<const N: usize>(
    op: u32,
    destination: [u128; N],
    source: [u128; N],
    imm8: u8,
) -> Result<[u128; N], Unmasked> {
    let code = op as u8;
    let (double, scalar) =
        if matches!(code, 0x7C | 0x7D | 0xD0) { (op >> 16 == 0x66, false) } else { shape(op) };
    let lanes = if scalar {
        1
    }
    else if double {
        2
    }
    else {
        4
    };
    // (MIN, MAX and CMP do not round: their fast path needs no MXCSR condition)
    let admitted = *gp::mxcsr as u32 & 0xFFE0 == 0x1FA0 || matches!(code, 0x5D | 0x5F | 0xC2);
    if admitted && matches!(code, 0x51 | 0x58 | 0x59 | 0x5C..=0x5F | 0xC2) {
        let mut r = destination;
        if (0..N).all(|h| {
            fast_half(code, destination[h], source[h], double, lanes, imm8)
                .map(|v| r[h] = v)
                .is_some()
        }) {
            return Ok(r);
        }
    }
    let mut fp = Fp::new();
    let mut result = destination;
    for h in 0..N {
        let (destination, source) = (destination[h], source[h]);
        for i in 0..lanes {
            let (a, b) = (lane(destination, i, double), lane(source, i, double));
            let v = match code {
                0xC2 => {
                    if fp.compare(a, b, double, imm8) {
                        lane_mask(double) as u64
                    }
                    else {
                        0
                    }
                },
                0xD0 => fp.binary(if i % 2 == 0 { 0x5C } else { 0x58 }, a, b, double),
                0x7C | 0x7D => {
                    let half = lanes / 2;
                    let input = if i < half { destination } else { source };
                    let base = i % half * 2;
                    fp.binary(
                        if code == 0x7C { 0x58 } else { 0x5C },
                        lane(input, base, double),
                        lane(input, base + 1, double),
                        double,
                    )
                },
                _ => fp.binary(code, a, b, double),
            };
            result[h] = set_lane(result[h], i, double, v);
        }
    }
    fp.finish()?;
    Ok(result)
}

/// The FMA forms (VEX.66.0F38 96-9F, A6-AF, B6-BF; `op` the opcode byte) of
/// DEST (also the first source), SRC2 (VEX.vvvv) and SRC3 (r/m) in halves of
/// 128 bits (a VEX.256 form: two) with one exception context; `double`:
/// VEX.W1 (PD, SD). The low nibble is the operation (6 ADDSUB: even lanes
/// subtract, 7 SUBADD: odd lanes subtract, 8/9 ADD, A/B SUB, C/D NADD (the
/// product negated), E/F NSUB; scalar from 9 when odd), the high one the
/// order: 9 (132) DEST × SRC3 + SRC2, A (213) SRC2 × DEST + SRC3, B (231)
/// SRC2 × SRC3 + DEST. A scalar form's other lanes are DEST's.
pub unsafe fn fused<const N: usize>(
    op: u8,
    double: bool,
    destination: [u128; N],
    second: [u128; N],
    third: [u128; N],
) -> Result<[u128; N], Unmasked> {
    let operation = op & 0xF;
    let scalar = operation >= 9 && operation & 1 == 1;
    let lanes = if scalar {
        1
    }
    else if double {
        2
    }
    else {
        4
    };
    // (the operands of lane `i` of half `h` in the order x × y + z, and the
    // negations of the product and the addend)
    let operands = |h: usize, i: usize| {
        let (a, b, c) = (
            lane(destination[h], i, double),
            lane(second[h], i, double),
            lane(third[h], i, double),
        );
        let (x, y, z) = match op >> 4 {
            9 => (a, c, b),
            0xA => (b, a, c),
            _ => (b, c, a),
        };
        let even = i % 2 == 0;
        let negations = match operation {
            6 => (false, even),
            7 => (false, !even),
            8 | 9 => (false, false),
            0xA | 0xB => (false, true),
            0xC | 0xD => (true, false),
            _ => (true, true),
        };
        (x, y, z, negations)
    };
    // The fast path (fused_fast) with rounding to nearest: when every lane
    // takes it, only the precision exception can arise, and it is masked or
    // the result exact (else the exact path raises it)
    let mxcsr = *gp::mxcsr as u32;
    if mxcsr & 0x6000 == 0 {
        let mut result = destination;
        let mut inexact = false;
        let sign = sign_mask(double);
        'fast: {
            for h in 0..N {
                for i in 0..lanes {
                    let (x, y, z, (negate_product, negate_addend)) = operands(h, i);
                    let x = if negate_product { x ^ sign } else { x };
                    let z = if negate_addend { z ^ sign } else { z };
                    let Some((v, lane_inexact)) = fused_fast(x, y, z, double)
                    else {
                        break 'fast;
                    };
                    inexact |= lane_inexact;
                    result[h] = set_lane(result[h], i, double, v);
                }
            }
            if inexact && mxcsr & (PE << 7) == 0 {
                break 'fast;
            }
            if inexact {
                *gp::mxcsr |= PE as i32;
            }
            return Ok(result);
        }
    }
    let mut fp = Fp::new();
    let mut result = destination;
    for h in 0..N {
        for i in 0..lanes {
            let (x, y, z, (negate_product, negate_addend)) = operands(h, i);
            let v = fp.fused(x, y, z, double, negate_product, negate_addend);
            result[h] = set_lane(result[h], i, double, v);
        }
    }
    fp.finish()?;
    Ok(result)
}

/// `a` + `b` and its rounding error (Knuth's TwoSum: exact in rounding to
/// nearest without overflow)
fn two_sum(a: f64, b: f64) -> (f64, f64) {
    let s = a + b;
    let b_part = s - a;
    (s, (a - (s - b_part)) + (b - b_part))
}
/// `a` × `b` and its rounding error (Dekker's product with Veltkamp's split:
/// exact when no intermediate overflows or underflows)
fn two_product(a: f64, b: f64) -> (f64, f64) {
    let split = |v: f64| {
        let c = 134217729.0 * v;
        let high = c - (c - v);
        (high, v - high)
    };
    let p = a * b;
    let ((ah, al), (bh, bl)) = (split(a), split(b));
    (p, ((ah * bh - p) + ah * bl + al * bh) + al * bl)
}
/// `s` + `error` (TwoSum's result and error) rounded to odd in double
/// precision: `s`, or its neighbour on the error's side when the sum is not
/// exact and `s` is even (no underflow: `s` is not zero then)
fn round_to_odd(s: f64, error: f64) -> f64 {
    if error == 0.0 || s.to_bits() & 1 == 1 {
        s
    }
    else if (error > 0.0) == (s > 0.0) {
        f64::from_bits(s.to_bits() + 1)
    }
    else {
        f64::from_bits(s.to_bits() - 1)
    }
}
/// One FMA lane (`x` × `y` + `z`, signs already applied) with host
/// arithmetic, rounded to nearest; None where the exact path (Fp::fused)
/// decides. Double precision: Boldo and Melquiond's emulation ("Emulation of
/// a FMA and correctly rounded sums: proved algorithms using rounding to
/// odd", IEEE Transactions on Computers 57(4), 2008): the exact product as two
/// doubles, the addend added to its high part exactly, the low parts summed
/// rounding to odd, then one rounding to nearest. It needs every
/// intermediate value normal, so the operands must be normal with |x| and |y|
/// within 2^±450 and |z| within 2^±900: the exact result is then zero or at
/// least 2^-1006, never tiny, and far from overflow. Single precision: the
/// product is exact in double precision, the sum is rounded to odd there and
/// then to single precision (RN24(RO53(v)) = RN24(v)); a result that is tiny
/// or overflows takes the exact path. Returns the result and whether it is
/// inexact.
pub fn fused_fast(x: u64, y: u64, z: u64, double: bool) -> Option<(u64, bool)> {
    if double {
        let exponent = |v: u64| (v >> 52 & 0x7FF) as i32 - 1023;
        if !(-450..=450).contains(&exponent(x))
            || !(-450..=450).contains(&exponent(y))
            || !(-900..=900).contains(&exponent(z))
        {
            return None;
        }
        let (high, low) = two_product(f64::from_bits(x), f64::from_bits(y));
        let (t_high, t_low) = two_sum(f64::from_bits(z), high);
        let (s, error) = two_sum(t_low, low);
        let (r, last) = two_sum(t_high, round_to_odd(s, error));
        Some((r.to_bits(), error != 0.0 || last != 0.0))
    }
    else {
        // (normal operands: an exponent field other than 0 and 255)
        let normal = |v: u64| (1..255).contains(&(v >> 23 & 0xFF));
        if !normal(x) || !normal(y) || !normal(z) {
            return None;
        }
        let single = |v: u64| f32::from_bits(v as u32) as f64;
        let (s, error) = two_sum(single(x) * single(y), single(z));
        let v = round_to_odd(s, error);
        let r = v as f32;
        if v == 0.0 {
            return Some((0, false));
        }
        if !(r.abs() > f32::MIN_POSITIVE && r.is_finite()) {
            return None;
        }
        Some((r.to_bits() as u64, error != 0.0 || r as f64 != v))
    }
}

/// VCVTPH2PS (F16C): the `count` (4 or 8) half-precision values in the low
/// bits of `source` as single-precision values, in halves of 128 bits. The
/// result is exact; DAZ does not apply and there is no denormal operand
/// exception (SDM); an SNaN is an invalid operation (quieted).
pub unsafe fn half_to_single(source: u128, count: usize) -> Result<(u128, u128), Unmasked> {
    let mut fp = Fp::new();
    let mut out = [0u128; 2];
    for i in 0..count {
        let v = f16_to_f32((source >> (16 * i)) as u16 as u32);
        fp.convert_lane();
        out[i / 4] |= (v as u128) << (32 * (i % 4));
    }
    fp.finish()?;
    Ok((out[0], out[1]))
}
/// VCVTPS2PH (F16C): the `count` (4 or 8) single-precision values of
/// `source` (halves of 128 bits) as half-precision values in the low bits of
/// the result, rounded as imm8[1:0] says or, with imm8[2], as MXCSR.RC does.
/// DAZ applies to the sources; FZ does not (half_output).
pub unsafe fn single_to_half(
    source: (u128, u128),
    count: usize,
    imm8: u8,
) -> Result<u128, Unmasked> {
    let mut fp = Fp::new();
    if imm8 & 4 == 0 {
        softfloat_roundingMode = ROUNDING[(imm8 & 3) as usize];
    }
    let mut out = 0u128;
    for i in 0..count {
        let half = if i < 4 { source.0 } else { source.1 };
        let mut de = 0;
        let value = fp.input((half >> (32 * (i % 4))) as u32 as u64, false, &mut de);
        let v = (f32_to_f16(value as u32) & 0xFFFF) as u16;
        fp.lane(de, nan(value, false));
        fp.half_output(v);
        out |= (v as u128) << (16 * i);
    }
    fp.finish()?;
    Ok(out)
}

/// ROUNDPS/ROUNDPD/ROUNDSS/ROUNDSD (66 0F 3A 08-0B by `op`'s low byte): each
/// lane (a scalar form's low one, the others from the destination) to an
/// integral value, rounded as imm8[1:0] says or, with imm8[2], as MXCSR.RC
/// does; imm8[3] suppresses the precision exception. DAZ applies, the
/// denormal operand exception does not (SDM); an SNaN is an invalid operation.
pub unsafe fn round(op: u32, destination: u128, source: u128, imm8: u8) -> Result<u128, Unmasked> {
    round_halves(op, [destination], [source], imm8).map(|[r]| r)
}
/// VROUNDPS/VROUNDPD with VEX.256 (`op` the legacy form's key): both halves
/// of `source` with one exception context
pub unsafe fn round256(op: u32, source: (u128, u128), imm8: u8) -> Result<(u128, u128), Unmasked> {
    round_halves(op, [0, 0], [source.0, source.1], imm8).map(|[low, high]| (low, high))
}
unsafe fn round_halves<const N: usize>(
    op: u32,
    destination: [u128; N],
    source: [u128; N],
    imm8: u8,
) -> Result<[u128; N], Unmasked> {
    let double = op & 1 != 0;
    let scalar = op & 0xFF >= 0x0A;
    let mut fp = Fp::new();
    let rounding = if imm8 & 4 != 0 { fp.rounding() } else { ROUNDING[(imm8 & 3) as usize] };
    let exact = imm8 & 8 == 0;
    let mut result = destination;
    for h in 0..N {
        for i in 0..if scalar {
            1
        }
        else if double {
            2
        }
        else {
            4
        } {
            let v = fp.convert_input(lane(source[h], i, double), double, true);
            let r = if double {
                f64_roundToInt(v, rounding, exact)
            }
            else {
                f32_roundToInt(v as u32, rounding, exact) as u64
            };
            fp.convert_lane();
            result[h] = set_lane(result[h], i, double, r);
        }
    }
    fp.finish()?;
    Ok(result)
}

/// DPPS/DPPD (66 0F 3A 40/41): the products of the lanes imm8[7:4] selects
/// (+0.0 for the others), summed pairwise in the SDM's order, in the lanes
/// imm8[3:0] selects (+0.0 in the others). Each multiplication and addition
/// has its own exceptions (as a single operation, SDM Vol. 1, 11.5.3) and
/// sets its flags in MXCSR. An unmasked one faults, the destination left
/// alone, where the SDM's pseudo-code looks for it: after DPPD's two
/// multiplications and after each addition (DPPS: only after the additions,
/// so the first addition runs even when a multiplication had one).
pub unsafe fn dot_product(
    double: bool,
    destination: u128,
    source: u128,
    imm8: u8,
) -> Result<u128, Unmasked> {
    unsafe fn step(op: u8, a: u64, b: u64, double: bool, unmasked: &mut bool) -> u64 {
        let mut fp = Fp::new();
        let r = fp.binary(op, a, b, double);
        *unmasked |= fp.finish().is_err();
        r
    }
    let lanes = if double { 2 } else { 4 };
    let mut unmasked = false;
    let mut products = [0; 4];
    for i in 0..lanes {
        if imm8 >> (4 + i) & 1 != 0 {
            products[i] = step(
                0x59,
                lane(destination, i, double),
                lane(source, i, double),
                double,
                &mut unmasked,
            );
        }
    }
    let check = |unmasked: bool| if unmasked { Err(Unmasked) } else { Ok(()) };
    let sum = if double {
        check(unmasked)?;
        step(0x58, products[0], products[1], double, &mut unmasked)
    }
    else {
        let low = step(0x58, products[0], products[1], double, &mut unmasked);
        check(unmasked)?;
        let high = step(0x58, products[2], products[3], double, &mut unmasked);
        check(unmasked)?;
        step(0x58, low, high, double, &mut unmasked)
    };
    check(unmasked)?;
    let mut result = 0;
    for i in 0..lanes {
        if imm8 >> i & 1 != 0 {
            result = set_lane(result, i, double, sum);
        }
    }
    Ok(result)
}

/// COMISS/UCOMISS/COMISD/UCOMISD (0F/66 0F 2F/2E): EFLAGS' ZF, PF and CF
/// (0x40, 0x04, 0x01) of comparing the low lanes. COMI signals a QNaN as an
/// invalid operation, UCOMI only an SNaN.
pub unsafe fn compare_flags(op: u32, a: u128, b: u128) -> Result<u32, Unmasked> {
    let double = op >> 16 == 0x66;
    let mut fp = Fp::new();
    let mut de = 0;
    let x = fp.input(lane(a, 0, double), double, &mut de);
    let y = fp.input(lane(b, 0, double), double, &mut de);
    let unordered = nan(x, double) || nan(y, double);
    if snan(x, double) || snan(y, double) || unordered && op as u8 == 0x2F {
        fp.flags |= IE;
    }
    fp.lane(de, unordered);
    fp.finish()?;
    let (eq, lt) = if unordered {
        (false, false)
    }
    else if double {
        (
            f64::from_bits(x) == f64::from_bits(y),
            f64::from_bits(x) < f64::from_bits(y),
        )
    }
    else {
        let (x, y) = (f32::from_bits(x as u32), f32::from_bits(y as u32));
        (x == y, x < y)
    };
    Ok(if unordered {
        0x45
    }
    else if lt {
        0x01
    }
    else if eq {
        0x40
    }
    else {
        0
    })
}

/// RCPPS/RCPSS/RSQRTPS/RSQRTSS (0F/F3 0F 53/52): the new destination. No
/// exceptions; denormal sources count as zero and tiny results are zero
/// (SDM: "Tiny results are always flushed to 0.0"). The approximation is the
/// correctly rounded value, well within the architectural 1.5 * 2^-12.
pub fn reciprocal(op: u32, destination: u128, source: u128) -> u128 {
    let scalar = op >> 16 == 0xF3;
    let square_root = op as u8 == 0x52;
    let mut result = if scalar { destination } else { 0 };
    for i in 0..if scalar { 1 } else { 4 } {
        let v = lane(source, i, false) as u32;
        let sign = v & 0x8000_0000;
        let bits = if nan(v as u64, false) {
            v | 0x40_0000
        }
        else if v & 0x7F80_0000 == 0 {
            // zero or denormal: an infinity of its sign
            sign | 0x7F80_0000
        }
        else if square_root && sign != 0 {
            0xFFC0_0000
        }
        else if v & 0x7FFF_FFFF == 0x7F80_0000 {
            sign
        }
        else {
            let x = f32::from_bits(v);
            let r = if square_root { 1.0 / x.sqrt() } else { 1.0 / x };
            let bits = r.to_bits();
            if denormal(bits as u64, false) {
                bits & 0x8000_0000
            }
            else {
                bits
            }
        };
        result = set_lane(result, i, false, bits as u64);
    }
    result
}

/// The VEX.256 conversions (the legacy forms' keys) with one exception
/// context: VCVTDQ2PS (0F 5B), VCVTPS2DQ (66 0F 5B) and VCVTTPS2DQ (F3 0F 5B)
/// of eight lanes; VCVTPS2PD (0F 5A) and VCVTDQ2PD (F3 0F E6) of an XMM
/// source's four into four doubles; VCVTPD2PS (66 0F 5A), VCVTPD2DQ (F2 0F E6)
/// and VCVTTPD2DQ (66 0F E6) of four doubles into an XMM result (the high
/// half zero)
pub unsafe fn convert256(op: u32, source: (u128, u128)) -> Result<(u128, u128), Unmasked> {
    let element = |i: usize, bytes: usize| {
        let offset = i * bytes;
        let half = if offset < 16 { source.0 } else { source.1 };
        (half >> (offset % 16 * 8)) as u64 & (u64::MAX >> (64 - bytes * 8))
    };
    let mut out = [0u128; 2];
    let mut put = |i: usize, bytes: usize, v: u64| {
        let offset = i * bytes;
        out[offset / 16] |= (v as u128 & (u128::MAX >> (128 - bytes * 8))) << (offset % 16 * 8);
    };
    let mut fp = Fp::new();
    match op {
        0x0F5B => {
            for i in 0..8 {
                let v = i32_to_f32(element(i, 4) as u32 as i32) as u64;
                fp.convert_lane();
                put(i, 4, fp.convert_output(v, false));
            }
        },
        0x660F5B | 0xF30F5B => {
            let rounding = if op == 0xF30F5B { 1 } else { fp.rounding() };
            for i in 0..8 {
                let value = fp.convert_input(element(i, 4), false, true);
                let n = f32_to_i32(value as u32, rounding, true);
                fp.convert_lane();
                put(i, 4, n as u32 as u64);
            }
        },
        0xF30FE6 => {
            for i in 0..4 {
                let v = i32_to_f64(element(i, 4) as u32 as i32);
                fp.convert_lane();
                put(i, 8, fp.convert_output(v, true));
            }
        },
        0x0F5A => {
            for i in 0..4 {
                let value = fp.convert_input(element(i, 4), false, false);
                let v = f32_to_f64(value as u32);
                fp.lane(0, nan(value, false));
                put(i, 8, fp.convert_output(v, true));
            }
        },
        0x660F5A => {
            for i in 0..4 {
                let value = fp.convert_input(element(i, 8), true, false);
                let v = f64_to_f32(value) as u64;
                fp.lane(0, nan(value, true));
                put(i, 4, fp.convert_output(v, false));
            }
        },
        0x660FE6 | 0xF20FE6 => {
            let rounding = if op == 0x660FE6 { 1 } else { fp.rounding() };
            for i in 0..4 {
                let value = fp.convert_input(element(i, 8), true, true);
                let n = f64_to_i32(value, rounding, true);
                fp.convert_lane();
                put(i, 4, n as u32 as u64);
            }
        },
        _ => unreachable!("not a VEX.256 conversion"),
    }
    fp.finish()?;
    Ok((out[0], out[1]))
}

/// The conversions (catalogue keys): the new XMM destination, or for those
/// to a general-purpose or MMX register the integer bits in the low 64 bits.
/// `wide`: REX.W (64-bit integers). The integer sources are in `source`'s low
/// bits (an MMX register, or a general-purpose register for CVTSI2SS/SD).
///
/// - 0F 2A CVTPI2PS, 66 0F 2A CVTPI2PD, F3/F2 0F 2A CVTSI2SS/SD
/// - 0F/66 0F 2C CVTTPS2PI/CVTTPD2PI, 2D CVTPS2PI/CVTPD2PI; F3/F2 0F 2C/2D
///   CVT(T)SS2SI/CVT(T)SD2SI
/// - 0F 5A CVTPS2PD, 66 0F 5A CVTPD2PS, F3 0F 5A CVTSS2SD, F2 0F 5A CVTSD2SS
/// - 0F 5B CVTDQ2PS, 66 0F 5B CVTPS2DQ, F3 0F 5B CVTTPS2DQ
/// - F3 0F E6 CVTDQ2PD, 66 0F E6 CVTTPD2DQ, F2 0F E6 CVTPD2DQ
pub unsafe fn convert(
    op: u32,
    wide: bool,
    destination: u128,
    source: u128,
) -> Result<u128, Unmasked> {
    let prefix = op >> 16;
    let code = op as u8;
    let scalar = matches!(prefix, 0xF2 | 0xF3) && matches!(code, 0x2A | 0x2C | 0x2D | 0x5A);
    let mut fp = Fp::new();
    let result;
    match code {
        0x2A => {
            // from integers: an MMX register's two, or one general-purpose register
            let double = matches!(prefix, 0x66 | 0xF2);
            let mut out = if prefix == 0x66 { 0 } else { destination };
            for i in 0..if scalar { 1 } else { 2 } {
                let n =
                    if scalar && wide { source as i64 } else { (source >> (i * 32)) as i32 as i64 };
                let v = if double { i64_to_f64(n) } else { i64_to_f32(n) as u64 };
                fp.convert_lane();
                out = set_lane(out, i, double, fp.convert_output(v, double));
            }
            result = out;
        },
        0x2C | 0x2D => {
            // to integers: two for an MMX register, one for a general-purpose register
            let double = matches!(prefix, 0x66 | 0xF2);
            let rounding = if code == 0x2C { 1 } else { fp.rounding() };
            let mut out = 0u128;
            for i in 0..if scalar { 1 } else { 2 } {
                let value = fp.convert_input(lane(source, i, double), double, true);
                let n = if scalar && wide {
                    if double {
                        f64_to_i64(value, rounding, true)
                    }
                    else {
                        f32_to_i64(value as u32, rounding, true)
                    }
                }
                else {
                    (if double {
                        f64_to_i32(value, rounding, true)
                    }
                    else {
                        f32_to_i32(value as u32, rounding, true)
                    }) as i64
                };
                fp.convert_lane();
                out |= if scalar { n as u64 as u128 } else { (n as u32 as u128) << (i * 32) };
            }
            result = out;
        },
        0x5A => {
            // between single and double precision
            let from_double = matches!(prefix, 0x66 | 0xF2);
            let mut out = if scalar { destination } else { 0 };
            for i in 0..if scalar { 1 } else { 2 } {
                let value = fp.convert_input(lane(source, i, from_double), from_double, false);
                let v =
                    if from_double { f64_to_f32(value) as u64 } else { f32_to_f64(value as u32) };
                let qnan = nan(value, from_double);
                fp.lane(0, qnan);
                out = set_lane(out, i, !from_double, fp.convert_output(v, !from_double));
            }
            result = out;
        },
        _ => {
            // 5B and E6: between 32-bit integers and floating point
            let to_float = op == 0x0F5B || op == 0xF30FE6;
            let double = code == 0xE6;
            let truncate = matches!(op, 0xF30F5B | 0x660FE6);
            let count = if double { 2 } else { 4 };
            let mut out = 0u128;
            for i in 0..count {
                if to_float {
                    let n = (source >> (i * 32)) as i32;
                    let v = if double { i32_to_f64(n) } else { i32_to_f32(n) as u64 };
                    fp.convert_lane();
                    out = set_lane(out, i, double, fp.convert_output(v, double));
                }
                else {
                    let value = fp.convert_input(lane(source, i, double), double, true);
                    let rounding = if truncate { 1 } else { fp.rounding() };
                    let n = if double {
                        f64_to_i32(value, rounding, true)
                    }
                    else {
                        f32_to_i32(value as u32, rounding, true)
                    };
                    fp.convert_lane();
                    out |= (n as u32 as u128) << (i * 32);
                }
            }
            result = out;
        },
    }
    fp.finish()?;
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::{fused_fast, two_sum};

    /// xorshift64
    struct Random(u64);
    impl Random {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn range(&mut self, low: i32, high: i32) -> i32 {
            low + (self.next() % (high - low + 1) as u64) as i32
        }
    }
    fn double(sign: u64, exponent: i32, mantissa: u64) -> u64 {
        sign << 63 | ((exponent + 1023) as u64) << 52 | mantissa & ((1 << 52) - 1)
    }
    /// Whether `a` × `x` + `y` differs from its rounding `r` (the host's
    /// fused multiply-add): the exact error as r2 + r3 (Boldo and Muller,
    /// "Exact and approximated error of the FMA", IEEE Transactions on
    /// Computers 60(2), 2011, ErrFma)
    fn fma_inexact(a: f64, x: f64, y: f64, r: f64) -> bool {
        let u1 = a * x;
        let u2 = a.mul_add(x, -u1);
        let (alpha1, alpha2) = two_sum(y, u2);
        let (beta1, beta2) = two_sum(u1, alpha1);
        let gamma = (beta1 - r) + beta2;
        gamma + alpha2 != 0.0
    }

    /// The fast path against the host's FMA: double precision operands in
    /// its whole range, with cancellation (the addend near minus the
    /// product), sticky bits (an addend below the product's last bit),
    /// mantissas of few or many bits, and sums just off a midpoint between
    /// two doubles, where only the rounding to odd gets the last bit right:
    /// x × RN(2^e / x) is 2^e within a relative 2^-53, added to an addend
    /// whose last bit is 2^(e+1)
    #[test]
    fn fused_fast_double() {
        let mut random = Random(0x9E37_79B9_7F4A_7C15);
        let mut taken = 0;
        for n in 0..20_000_000u64 {
            let mantissa = |random: &mut Random| match random.next() % 4 {
                0 => random.next() >> (random.next() % 52),
                1 => !(random.next() >> (random.next() % 52)),
                _ => random.next(),
            };
            let (ex, ey) = (random.range(-450, 450), random.range(-450, 450));
            let x = double(random.next() & 1, ex, mantissa(&mut random));
            let y = double(random.next() & 1, ey, mantissa(&mut random));
            let product = f64::from_bits(x) * f64::from_bits(y);
            let (x, y) = if n % 5 == 4 {
                let x = double(
                    random.next() & 1,
                    random.range(-200, 200),
                    mantissa(&mut random),
                );
                (
                    x,
                    (f64::from_bits(double(random.next() & 1, ey.clamp(-200, 200), 0))
                        / f64::from_bits(x))
                    .to_bits(),
                )
            }
            else {
                (x, y)
            };
            let z = match n % 5 {
                4 => double(
                    random.next() & 1,
                    ey.clamp(-200, 200) + 53,
                    mantissa(&mut random),
                ),
                // (near minus the product: its low bits changed)
                0 => (-product).to_bits() ^ random.next() >> random.range(12, 63),
                // (below the product's last bit, or around it)
                1 => double(
                    random.next() & 1,
                    ex + ey + random.range(-110, 2),
                    mantissa(&mut random),
                ),
                2 => double(
                    random.next() & 1,
                    (ex + ey + random.range(-60, 60)).clamp(-900, 900),
                    mantissa(&mut random),
                ),
                _ => double(
                    random.next() & 1,
                    random.range(-900, 900),
                    mantissa(&mut random),
                ),
            };
            let Some((r, inexact)) = fused_fast(x, y, z, true)
            else {
                continue;
            };
            taken += 1;
            let (a, b, c) = (f64::from_bits(x), f64::from_bits(y), f64::from_bits(z));
            let expected = a.mul_add(b, c);
            assert_eq!(r, expected.to_bits(), "{x:016x} × {y:016x} + {z:016x}");
            assert_eq!(
                inexact,
                fma_inexact(a, b, c, expected),
                "inexact: {x:016x} × {y:016x} + {z:016x}"
            );
        }
        assert!(taken > 19_000_000, "{taken} cases took the fast path");
    }

    /// Single precision against the host's FMA, every exponent
    #[test]
    fn fused_fast_single() {
        let mut random = Random(0x0123_4567_89AB_CDEF);
        let mut taken = 0;
        for n in 0..20_000_000u64 {
            let single = |random: &mut Random, exponent: i32| {
                (random.next() & 1) << 31
                    | ((exponent.clamp(-126, 127) + 127) as u64) << 23
                    | random.next() & 0x7F_FFFF
            };
            let (ex, ey) = (random.range(-126, 127), random.range(-126, 127));
            let (x, y) = (single(&mut random, ex), single(&mut random, ey));
            // (n % 3 == 2: 3a for an odd 24-bit a is a midpoint between two
            // singles, plus an addend far below it, of either sign)
            let (x, y) = if n % 3 == 2 {
                let a = (1 << 23 | random.next() % (11184810 - (1 << 23))) | 1;
                let exponent = random.range(-60, 60);
                let a = (a as f32 * 2f32.powi(exponent)).to_bits() as u64;
                (
                    a,
                    (3.0f32 * 2f32.powi(random.range(-30, 30))).to_bits() as u64,
                )
            }
            else {
                (x, y)
            };
            let product = f32::from_bits(x as u32) as f64 * f32::from_bits(y as u32) as f64;
            let z = match n % 3 {
                0 => {
                    ((-(product as f32)).to_bits() ^ (random.next() as u32 >> random.range(9, 31)))
                        as u64
                },
                1 => {
                    let exponent = ex + ey + random.range(-50, 30);
                    single(&mut random, exponent)
                },
                _ => {
                    let exponent =
                        (product.abs().log2().floor() as i32 - random.range(26, 60)).max(-126);
                    single(&mut random, exponent)
                },
            };
            let Some((r, inexact)) = fused_fast(x, y, z, false)
            else {
                continue;
            };
            taken += 1;
            let (a, b, c) = (
                f32::from_bits(x as u32),
                f32::from_bits(y as u32),
                f32::from_bits(z as u32),
            );
            let expected = a.mul_add(b, c);
            assert_eq!(r, expected.to_bits() as u64, "{x:08x} × {y:08x} + {z:08x}");
            // (the product is exact in double precision)
            let (s, error) = two_sum(a as f64 * b as f64, c as f64);
            assert_eq!(
                inexact,
                error != 0.0 || s as f32 as f64 != s,
                "inexact: {x:08x} × {y:08x} + {z:08x}"
            );
        }
        assert!(taken > 5_000_000, "{taken} cases took the fast path");
    }

    /// Outside its range the fast path declines: zeros, denormals,
    /// infinities, NaNs, large and small exponents
    #[test]
    fn fused_fast_declines() {
        let one = 1.0f64.to_bits();
        for v in [
            0,
            1 << 63,
            1,
            0x7FF0_0000_0000_0000,
            0x7FF8_0000_0000_0000,
            double(0, 451, 0),
            double(0, -451, 0),
        ] {
            assert_eq!(fused_fast(v, one, one, true), None, "{v:016x}");
            assert_eq!(fused_fast(one, v, one, true), None, "{v:016x}");
        }
        for v in [
            0,
            1 << 63,
            1,
            0x7FF0_0000_0000_0000,
            double(0, 901, 0),
            double(0, -901, 0),
        ] {
            assert_eq!(fused_fast(one, one, v, true), None, "{v:016x}");
        }
        let one = 1.0f32.to_bits() as u64;
        for v in [0, 1 << 31, 1, 0x7F80_0000, 0x7FC0_0000] {
            assert_eq!(fused_fast(v, one, one, false), None, "{v:08x}");
            assert_eq!(fused_fast(one, one, v, false), None, "{v:08x}");
        }
        // (tiny or overflowing single results)
        let tiny = f32::MIN_POSITIVE.to_bits() as u64;
        assert_eq!(
            fused_fast(
                tiny,
                (0.5f32).to_bits() as u64,
                (0.0001f32 * f32::MIN_POSITIVE).to_bits() as u64,
                false
            ),
            None
        );
        let max = f32::MAX.to_bits() as u64;
        assert_eq!(fused_fast(max, (2.0f32).to_bits() as u64, one, false), None);
        // (an exact zero: +0 in rounding to nearest)
        assert_eq!(
            fused_fast(one, one, (-1.0f32).to_bits() as u64, false),
            Some((0, false))
        );
        assert_eq!(
            fused_fast(
                1.0f64.to_bits(),
                1.0f64.to_bits(),
                (-1.0f64).to_bits(),
                true
            ),
            Some((0, false))
        );
    }
}
                                                                                                                                                                                                                                             source/v64/src/rust/cpu/simd_int.rs                                                                 0000644 0000000 0000000 00000077017 00000000000 014427  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Packed integer semantics shared by every engine (docs/simd-xsave-plan.md
//! 3.1): the 32-bit interpreter, the IR helpers and the x64 engine pass the
//! operands they read and commit the result. No CPU state, no memory.
//!
//! Vectors are little-endian bytes: N is 8 for an MMX register, 16 for an XMM
//! register (and for each 128-bit lane of the VEX.256 forms).

/// The lane of `size` bytes at `index`, sign-extended
fn lane(v: &[u8], size: usize, index: usize) -> i64 {
    let bytes = &v[index * size..(index + 1) * size];
    let value = bytes.iter().rev().fold(0i64, |n, &b| n << 8 | b as i64);
    value << (64 - 8 * size) >> (64 - 8 * size)
}
/// Stores the low `size` bytes of `value` as the lane at `index`
fn put(v: &mut [u8], size: usize, index: usize, value: i64) {
    v[index * size..(index + 1) * size].copy_from_slice(&value.to_le_bytes()[..size]);
}
fn saturate_word(value: i64) -> i64 { value.clamp(i16::MIN as i64, i16::MAX as i64) }
/// The lane of `size` bytes at `index`, zero-extended
fn unsigned(v: &[u8], size: usize, index: usize) -> u64 {
    v[index * size..(index + 1) * size]
        .iter()
        .rev()
        .fold(0, |n, &b| n << 8 | b as u64)
}

/// The SSSE3 operations of the opcode map 0F 38, by their opcode byte:
/// PSHUFB (00), PHADDW/D/SW (01-03), PMADDUBSW (04), PHSUBW/D/SW (05-07),
/// PSIGNB/W/D (08-0A), PMULHRSW (0B) and PABSB/W/D (1C-1E).
/// `destination` is the first operand, `source` the second.
pub fn ssse3<const N: usize>(op: u8, destination: [u8; N], source: [u8; N]) -> [u8; N] {
    let mut result = [0; N];
    match op {
        // the index is the low 3 (MMX) or 4 bits; bit 7 selects zero
        0x00 => {
            for i in 0..N {
                result[i] =
                    if source[i] & 0x80 != 0 { 0 } else { destination[source[i] as usize % N] };
            }
        },
        // horizontal pairs: the destination's sums or differences fill the low
        // half of the result, the source's the high half
        0x01 | 0x02 | 0x03 | 0x05 | 0x06 | 0x07 => {
            let size = if op & 3 == 2 { 4 } else { 2 };
            let lanes = N / size;
            for i in 0..lanes {
                let (v, pair) =
                    if i < lanes / 2 { (&destination, i) } else { (&source, i - lanes / 2) };
                let (a, b) = (lane(v, size, 2 * pair), lane(v, size, 2 * pair + 1));
                let value = if op >= 0x05 { a - b } else { a + b };
                put(
                    &mut result,
                    size,
                    i,
                    if op & 3 == 3 { saturate_word(value) } else { value },
                );
            }
        },
        // unsigned bytes of the destination times signed bytes of the source
        0x04 => {
            for i in 0..N / 2 {
                let product = |j: usize| destination[j] as i64 * source[j] as i8 as i64;
                put(
                    &mut result,
                    2,
                    i,
                    saturate_word(product(2 * i) + product(2 * i + 1)),
                );
            }
        },
        // negated, zeroed or kept by the sign of the source (the most negative
        // number stays as it is)
        0x08 | 0x09 | 0x0A => {
            let size = 1 << (op - 0x08);
            for i in 0..N / size {
                let (a, sign) = (lane(&destination, size, i), lane(&source, size, i));
                put(&mut result, size, i, a * sign.signum());
            }
        },
        // bits 16:1 of the product rounded at bit 14 (no saturation)
        0x0B => {
            for i in 0..N / 2 {
                let product = lane(&destination, 2, i) * lane(&source, 2, i);
                put(&mut result, 2, i, ((product >> 14) + 1) >> 1);
            }
        },
        // of the source; the most negative number becomes its unsigned magnitude
        0x1C | 0x1D | 0x1E => {
            let size = 1 << (op - 0x1C);
            for i in 0..N / size {
                put(&mut result, size, i, lane(&source, size, i).abs());
            }
        },
        _ => unreachable!("SSSE3 opcode {op:02x}"),
    }
    result
}

/// PALIGNR (0F 3A 0F): the destination above the source, shifted right by
/// `imm8` bytes; bytes beyond both are zero
pub fn palignr<const N: usize>(destination: [u8; N], source: [u8; N], imm8: u8) -> [u8; N] {
    std::array::from_fn(|i| {
        let n = i + imm8 as usize;
        if n < N {
            source[n]
        }
        else if n < 2 * N {
            destination[n - N]
        }
        else {
            0
        }
    })
}

/// The SSE4.1 and SSE4.2 operations of the opcode map 66 0F 38 but PTEST and
/// MOVNTDQA, by their opcode byte: PBLENDVB, BLENDVPS, BLENDVPD (10, 14, 15:
/// the sign of each lane of `xmm0` selects the source), PMOVSX and PMOVZX
/// (20-25, 30-35: the low lanes of the source, extended), PMULDQ (28),
/// PCMPEQQ (29), PACKUSDW (2B), PCMPGTQ (37), PMINSB/SD/UW/UD and
/// PMAXSB/SD/UW/UD (38-3F), PMULLD (40) and PHMINPOSUW (41).
pub fn sse4(op: u8, destination: [u8; 16], source: [u8; 16], xmm0: [u8; 16]) -> [u8; 16] {
    let mut result = [0; 16];
    match op {
        0x10 | 0x14 | 0x15 => {
            let size = match op {
                0x10 => 1,
                0x14 => 4,
                _ => 8,
            };
            for i in 0..16 / size {
                let selected =
                    if xmm0[(i + 1) * size - 1] & 0x80 != 0 { &source } else { &destination };
                result[i * size..(i + 1) * size]
                    .copy_from_slice(&selected[i * size..(i + 1) * size]);
            }
        },
        // (from, to): BW, BD, BQ, WD, WQ, DQ
        0x20..=0x25 | 0x30..=0x35 => {
            let (from, to) = [(1, 2), (1, 4), (1, 8), (2, 4), (2, 8), (4, 8)][(op & 7) as usize];
            for i in 0..16 / to {
                let value = if op < 0x30 {
                    lane(&source, from, i)
                }
                else {
                    unsigned(&source, from, i) as i64
                };
                put(&mut result, to, i, value);
            }
        },
        // the even signed dwords, multiplied to quadwords
        0x28 => {
            for i in 0..2 {
                put(
                    &mut result,
                    8,
                    i,
                    lane(&destination, 4, 2 * i) * lane(&source, 4, 2 * i),
                );
            }
        },
        0x29 | 0x37 => {
            for i in 0..2 {
                let (a, b) = (lane(&destination, 8, i), lane(&source, 8, i));
                put(
                    &mut result,
                    8,
                    i,
                    -((if op == 0x29 { a == b } else { a > b }) as i64),
                );
            }
        },
        // signed dwords to unsigned saturated words: the destination's, then the source's
        0x2B => {
            for i in 0..8 {
                let value = if i < 4 { lane(&destination, 4, i) } else { lane(&source, 4, i - 4) };
                put(&mut result, 2, i, value.clamp(0, 0xFFFF));
            }
        },
        // (lane size, signed) by the low two bits: SB, SD, UW, UD
        0x38..=0x3F => {
            let size = [1, 4, 2, 4][(op & 3) as usize];
            let signed = op & 3 < 2;
            for i in 0..16 / size {
                let (a, b) = if signed {
                    (lane(&destination, size, i), lane(&source, size, i))
                }
                else {
                    (
                        unsigned(&destination, size, i) as i64,
                        unsigned(&source, size, i) as i64,
                    )
                };
                put(
                    &mut result,
                    size,
                    i,
                    if op >= 0x3C { a.max(b) } else { a.min(b) },
                );
            }
        },
        // the low halves of the products
        0x40 => {
            for i in 0..4 {
                put(
                    &mut result,
                    4,
                    i,
                    lane(&destination, 4, i) * lane(&source, 4, i),
                );
            }
        },
        // the smallest unsigned word of the source and its index (the lowest on ties)
        0x41 => {
            let (index, value) = (0..8)
                .map(|i| (i, unsigned(&source, 2, i)))
                .min_by_key(|&(i, value)| (value, i))
                .unwrap();
            put(&mut result, 2, 0, value as i64);
            put(&mut result, 2, 1, index as i64);
        },
        _ => unreachable!("SSE4 opcode 66 0F 38 {op:02x}"),
    }
    result
}

/// PTEST (66 0F 38 17): (ZF, CF), whether source AND destination and source
/// AND NOT destination are zero
pub fn ptest(destination: [u8; 16], source: [u8; 16]) -> (bool, bool) {
    (
        (0..16).all(|i| destination[i] & source[i] == 0),
        (0..16).all(|i| !destination[i] & source[i] == 0),
    )
}

/// The SSE4.1 operations with imm8 of the map 66 0F 3A that move or combine
/// integer lanes: BLENDPS, BLENDPD, PBLENDW (0C-0E: imm8 bit i takes lane i
/// of the source) and MPSADBW (42: eight sums of absolute byte differences
/// against the source's 4-byte block imm8[1:0], from the destination's byte
/// 4 * imm8[2] on)
pub fn sse4_imm(op: u8, destination: [u8; 16], source: [u8; 16], imm8: u8) -> [u8; 16] {
    let mut result = destination;
    match op {
        0x0C | 0x0D | 0x0E => {
            let size = [4, 8, 2][(op - 0x0C) as usize];
            for i in 0..16 / size {
                if imm8 >> i & 1 != 0 {
                    result[i * size..(i + 1) * size]
                        .copy_from_slice(&source[i * size..(i + 1) * size]);
                }
            }
        },
        0x42 => {
            let (s, d) = ((imm8 & 3) as usize * 4, (imm8 >> 2 & 1) as usize * 4);
            for i in 0..8 {
                let sum = (0..4)
                    .map(|j| (destination[d + i + j] as i64 - source[s + j] as i64).abs())
                    .sum();
                put(&mut result, 2, i, sum);
            }
        },
        _ => unreachable!("SSE4 opcode 66 0F 3A {op:02x}"),
    }
    result
}

/// INSERTPS (66 0F 3A 21): `value` (the source register's dword imm8[7:6],
/// or the m32) into dword imm8[5:4], then the dwords of imm8[3:0] zeroed
pub fn insertps(destination: [u8; 16], value: u32, imm8: u8) -> [u8; 16] {
    let mut result = destination;
    put(&mut result, 4, (imm8 >> 4 & 3) as usize, value as i64);
    for i in 0..4 {
        if imm8 >> i & 1 != 0 {
            put(&mut result, 4, i, 0);
        }
    }
    result
}

/// PALIGNR as one i8x16.shuffle for compiled code (`n`: 8 or 16 bytes): the
/// lanes over (destination, source), or over (destination, zero) when the
/// second result is true (imm8 reaches beyond the source)
pub fn palignr_lanes(imm8: u8, n: usize) -> ([u8; 16], bool) {
    let imm8 = imm8 as usize;
    let zero = imm8 >= n;
    let mut lanes = [0; 16];
    for (i, lane) in lanes.iter_mut().enumerate().take(n) {
        let k = i + imm8;
        *lane = if zero {
            if k < 2 * n {
                k - n
            }
            else {
                16
            }
        }
        else if k < n {
            16 + k
        }
        else {
            k - n
        } as u8;
    }
    (lanes, zero)
}

/// What PCMPESTRI/PCMPESTRM/PCMPISTRI/PCMPISTRM (66 0F 3A 60-63) produce
/// (`compare_strings`)
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StringCompare {
    /// IntRes2: a bit per element of the second operand
    pub mask: u16,
    /// xSTRI's ECX: the lowest (imm8[6] clear) or highest set bit of `mask`,
    /// else the number of elements
    pub index: u32,
    /// xSTRM's XMM0: `mask` (imm8[6] clear) or a byte or word mask of it
    pub xmm0: [u8; 16],
    /// EFLAGS: CF (mask not zero), ZF (the second operand shorter than
    /// the register), SF (the first operand shorter), OF (mask bit 0); AF and
    /// PF clear
    pub flags: i32,
}

/// PCMPxSTRx (SDM Vol. 2, 4.1): compare the strings `a` (xmm1) and `b`
/// (xmm2/m128) as imm8 says: its elements (bits 1:0: unsigned or signed
/// bytes or words), the aggregation (3:2: equal any, ranges, equal each,
/// equal ordered), the polarity (5:4) and the output (6). The explicit
/// lengths `la` and `lb` (EAX and EDX, RAX and RDX with REX.W) count in
/// absolute value, at most the elements of a register; without them
/// (PCMPISTRx) a string ends before its first zero element.
pub fn compare_strings(
    imm8: u8,
    a: [u8; 16],
    b: [u8; 16],
    la: Option<i64>,
    lb: Option<i64>,
) -> StringCompare {
    let words = imm8 & 1 != 0;
    let signed = imm8 & 2 != 0;
    let n = if words { 8 } else { 16 };
    // the elements, once
    let elements = |v: &[u8; 16]| {
        let mut e = [0i32; 16];
        for (i, x) in e.iter_mut().enumerate().take(n) {
            *x = match (words, signed) {
                (true, true) => i16::from_le_bytes([v[2 * i], v[2 * i + 1]]) as i32,
                (true, false) => u16::from_le_bytes([v[2 * i], v[2 * i + 1]]) as i32,
                (false, true) => v[i] as i8 as i32,
                (false, false) => v[i] as i32,
            };
        }
        e
    };
    let (ea, eb) = (elements(&a), elements(&b));
    let length = |e: &[i32; 16], explicit: Option<i64>| match explicit {
        Some(l) => l.unsigned_abs().min(n as u64) as usize,
        None => e[..n].iter().position(|&x| x == 0).unwrap_or(n),
    };
    let (valid_a, valid_b) = (length(&ea, la), length(&eb, lb));
    let mask = |count: usize| ((1u32 << count) - 1) as u16;
    // IntRes1, a bit per element j of b, with the values SDM table 4-7 forces
    // for invalid elements: equal any and ranges false, equal each true when
    // both are invalid, equal ordered true for an invalid element of a (else
    // false for one of b). Only the comparisons an aggregation needs.
    let mut intres1 = 0u16;
    match imm8 >> 2 & 3 {
        // equal any: a set of a's valid elements
        0 if !words => {
            let mut set = [0u64; 4];
            for &x in &ea[..valid_a] {
                set[(x as u8 >> 6) as usize] |= 1 << (x as u8 & 63);
            }
            for (j, &y) in eb[..valid_b].iter().enumerate() {
                intres1 |= ((set[(y as u8 >> 6) as usize] >> (y as u8 & 63) & 1) as u16) << j;
            }
        },
        0 => {
            for (j, y) in eb[..valid_b].iter().enumerate() {
                intres1 |= (ea[..valid_a].contains(y) as u16) << j;
            }
        },
        // ranges: the valid pairs of a, lower and upper bounds
        1 => {
            for (j, &y) in eb[..valid_b].iter().enumerate() {
                let hit = (0..valid_a / 2).any(|k| y >= ea[2 * k] && y <= ea[2 * k + 1]);
                intres1 |= (hit as u16) << j;
            }
        },
        // equal each
        2 => {
            for j in 0..n {
                let hit = if j < valid_a && j < valid_b {
                    ea[j] == eb[j]
                }
                else {
                    j >= valid_a && j >= valid_b
                };
                intres1 |= (hit as u16) << j;
            }
        },
        // equal ordered: a found at element j of b
        _ => {
            for j in 0..n {
                let hit = (0..(n - j).min(valid_a)).all(|k| j + k < valid_b && ea[k] == eb[j + k]);
                intres1 |= (hit as u16) << j;
            }
        },
    }
    let mask = match imm8 >> 4 & 3 {
        1 => !intres1 & mask(n),
        // (masked: only the valid elements of b)
        3 => intres1 ^ mask(valid_b),
        _ => intres1,
    };
    let index = if mask == 0 {
        n as u32
    }
    else if imm8 & 0x40 != 0 {
        15 - mask.leading_zeros()
    }
    else {
        mask.trailing_zeros()
    };
    let mut xmm0 = [0; 16];
    if imm8 & 0x40 != 0 {
        let size = 16 / n;
        for i in 0..n {
            if mask >> i & 1 != 0 {
                xmm0[i * size..(i + 1) * size].fill(0xFF);
            }
        }
    }
    else {
        xmm0[..2].copy_from_slice(&mask.to_le_bytes());
    }
    let flags = (mask != 0) as i32
        | ((valid_b < n) as i32) << 6
        | ((valid_a < n) as i32) << 7
        | ((mask & 1) as i32) << 11;
    StringCompare {
        mask,
        index,
        xmm0,
        flags,
    }
}

/// CRC32 (SSE4.2, F2 0F 38 F0/F1; general-purpose registers only): `crc`
/// updated with the low `bytes` bytes of `value`, least significant first,
/// by CRC-32C (the polynomial 11EDC6F41H, bit-reflected)
pub fn crc32c(crc: u32, value: u64, bytes: u32) -> u32 {
    const TABLE: [u32; 256] = {
        let mut table = [0; 256];
        let mut i = 0;
        while i < 256 {
            let mut c = i as u32;
            let mut k = 0;
            while k < 8 {
                c = if c & 1 != 0 { c >> 1 ^ 0x82F6_3B78 } else { c >> 1 };
                k += 1;
            }
            table[i] = c;
            i += 1;
        }
        table
    };
    (0..bytes).fold(crc, |crc, i| {
        TABLE[(crc ^ (value >> (8 * i)) as u32) as u8 as usize] ^ crc >> 8
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    fn words<const N: usize>(v: [u8; N]) -> Vec<i16> {
        v.chunks(2)
            .map(|c| i16::from_le_bytes([c[0], c[1]]))
            .collect()
    }
    fn from_words<const N: usize>(w: &[i16]) -> [u8; N] {
        let bytes: Vec<u8> = w.iter().flat_map(|x| x.to_le_bytes()).collect();
        bytes.try_into().unwrap()
    }
    /// sse4 without a mask in XMM0
    fn s4(op: u8, d: [u8; 16], s: [u8; 16]) -> [u8; 16] { sse4(op, d, s, [0; 16]) }
    #[test]
    fn pshufb_zeroes_with_bit_7_and_wraps_the_index() {
        let a: [u8; 16] = std::array::from_fn(|i| 0xA0 + i as u8);
        let b: [u8; 16] = [
            0x80, 0x0F, 0x10, 0x1F, 0x7F, 0xFF, 0x00, 0x8F, 1, 2, 3, 4, 5, 6, 7, 0x41,
        ];
        let r = ssse3(0x00, a, b);
        assert_eq!(&r[..8], &[0, 0xAF, 0xA0, 0xAF, 0xAF, 0, 0xA0, 0]);
        assert_eq!(r[15], 0xA1);
        // MMX: three index bits
        let a8: [u8; 8] = std::array::from_fn(|i| 0x10 + i as u8);
        assert_eq!(
            ssse3(0x00, a8, [8, 9, 0x0F, 0x80, 0x87, 0x7F, 0, 1]),
            [0x10, 0x11, 0x17, 0, 0, 0x17, 0x10, 0x11]
        );
    }
    #[test]
    fn horizontal_add_and_subtract() {
        let d = from_words::<16>(&[1, 2, 3, 4, 0x7FFF, 1, -0x8000, -1]);
        let s = from_words::<16>(&[10, 20, 30, 40, 50, 60, 70, 80]);
        assert_eq!(
            words(ssse3(0x01, d, s)),
            [3, 7, -0x8000, 0x7FFF, 30, 70, 110, 150]
        );
        assert_eq!(
            words(ssse3(0x03, d, s)),
            [3, 7, 0x7FFF, -0x8000, 30, 70, 110, 150]
        );
        assert_eq!(
            words(ssse3(0x05, d, s)),
            [-1, -1, 0x7FFE, -0x7FFF, -10, -10, -10, -10]
        );
        let d = from_words::<16>(&[0x7FFF, -1, -0x8000, 1, 0, 0, 0, 0]);
        assert_eq!(words(ssse3(0x07, d, s))[..2], [0x7FFF, -0x8000]);
        // dwords, and the MMX halves
        let d: [u8; 16] = [1, 0, 0, 0, 2, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 0, 0, 0];
        assert_eq!(&ssse3(0x02, d, [0; 16])[..8], &[3, 0, 0, 0, 0, 0, 0, 0x80]);
        assert_eq!(
            &ssse3(0x06, d, [0; 16])[..8],
            &[0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0x7F]
        );
        let d8 = from_words::<8>(&[1, 2, 3, 4]);
        let s8 = from_words::<8>(&[5, 6, 7, 8]);
        assert_eq!(words(ssse3(0x01, d8, s8)), [3, 7, 11, 15]);
    }
    #[test]
    fn pmaddubsw_takes_unsigned_destination_and_signed_source_bytes() {
        let mut d = [0u8; 16];
        let mut s = [0u8; 16];
        d[..4].copy_from_slice(&[0xFF, 0xFF, 0x80, 0x01]);
        s[..4].copy_from_slice(&[0x7F, 0x7F, 0x80, 0xFF]);
        let r = words(ssse3(0x04, d, s));
        assert_eq!(r[0], 0x7FFF); // 255 * 127 * 2 saturates
        assert_eq!(r[1], -0x4001); // 128 * -128 + 1 * -1
        d[4..6].copy_from_slice(&[0xFF, 0xFF]);
        s[4..6].copy_from_slice(&[0x80, 0x80]);
        assert_eq!(words(ssse3(0x04, d, s))[2], -0x8000);
    }
    #[test]
    fn psign_pmulhrsw_and_pabs_edges() {
        let d = from_words::<16>(&[5, 5, 5, -0x8000, -0x8000, 0, 7, -7]);
        let s = from_words::<16>(&[1, 0, -1, -1, 1, -5, -0x8000, 0x7FFF]);
        assert_eq!(
            words(ssse3(0x09, d, s)),
            [5, 0, -5, -0x8000, -0x8000, 0, -7, -7]
        );
        let d = from_words::<16>(&[-0x8000, 0x4000, -0x8000, 1, 0x7FFF, 0x7FFF, -1, 3]);
        let s = from_words::<16>(&[-0x8000, 0x4000, 0x7FFF, 0x4000, 0x7FFF, -0x8000, 1, 0x2AAB]);
        assert_eq!(
            words(ssse3(0x0B, d, s)),
            [-0x8000, 0x2000, -0x7FFF, 1, 0x7FFE, -0x7FFF, 0, 1]
        );
        let mut s = [0u8; 16];
        s[..4].copy_from_slice(&[0x80, 0x7F, 0xFF, 0x00]);
        assert_eq!(&ssse3(0x1C, [0; 16], s)[..4], &[0x80, 0x7F, 0x01, 0x00]);
        assert_eq!(
            words(ssse3(
                0x1D,
                [0; 16],
                from_words::<16>(&[-0x8000, -1, 0, 1, 0, 0, 0, 0])
            ))[..4],
            [-0x8000, 1, 0, 1]
        );
        let s: [u8; 16] = [
            0, 0, 0, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 5, 0, 0, 0, 0, 0, 0, 0,
        ];
        assert_eq!(
            &ssse3(0x1E, [0; 16], s)[..12],
            &[0, 0, 0, 0x80, 1, 0, 0, 0, 5, 0, 0, 0]
        );
    }
    #[test]
    fn palignr_lanes_select_what_palignr_computes() {
        let d: [u8; 16] = std::array::from_fn(|i| 0x20 + i as u8);
        let s: [u8; 16] = std::array::from_fn(|i| 0x40 + i as u8);
        for n in [8, 16] {
            for imm in 0..=255u8 {
                let (lanes, zero) = palignr_lanes(imm, n);
                let second = if zero { [0; 16] } else { s };
                let shuffled: Vec<u8> = lanes[..n]
                    .iter()
                    .map(|&l| {
                        if l < 16 {
                            d[l as usize]
                        }
                        else {
                            second[l as usize - 16]
                        }
                    })
                    .collect();
                let expected: Vec<u8> = if n == 8 {
                    palignr::<8>(d[..8].try_into().unwrap(), s[..8].try_into().unwrap(), imm)
                        .to_vec()
                }
                else {
                    palignr(d, s, imm).to_vec()
                };
                assert_eq!(shuffled, expected, "{n} {imm}");
            }
        }
    }
    #[test]
    fn blendv_takes_the_sign_of_each_xmm0_lane() {
        let d = [0x11; 16];
        let s = [0x22; 16];
        let mut mask = [0u8; 16];
        mask[0] = 0x80;
        mask[7] = 0x80; // the sign of dword 1 and of quadword 0
        mask[3] = 0x7F;
        let r = sse4(0x10, d, s, mask);
        assert_eq!((r[0], r[1], r[3], r[7]), (0x22, 0x11, 0x11, 0x22));
        assert_eq!(
            &sse4(0x14, d, s, mask)[..8],
            &[0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22]
        );
        assert_eq!(
            &sse4(0x15, d, s, mask)[..9],
            &[0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x11]
        );
    }
    #[test]
    fn pmovsx_and_pmovzx_extend_the_low_lanes() {
        let s: [u8; 16] = [
            0x80, 0x7F, 0xFF, 1, 0, 0, 0, 0x80, 0xFF, 0xFF, 0xFF, 0xFF, 9, 9, 9, 9,
        ];
        assert_eq!(
            words(s4(0x20, [0; 16], s)),
            [-128, 127, -1, 1, 0, 0, 0, -128]
        );
        assert_eq!(
            words(s4(0x30, [0; 16], s)),
            [128, 127, 255, 1, 0, 0, 0, 128]
        );
        assert_eq!(
            &s4(0x22, [0; 16], s)[..16],
            &[0x80, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F, 0, 0, 0, 0, 0, 0, 0]
        );
        // DQ: the low two dwords
        let r = s4(0x25, [0; 16], s);
        assert_eq!(
            (lane(&r, 8, 0), lane(&r, 8, 1)),
            (0x01FF_7F80, i32::MIN as i64)
        );
        let r = s4(0x35, [0; 16], s);
        assert_eq!(
            (unsigned(&r, 8, 0), unsigned(&r, 8, 1)),
            (0x01FF_7F80, 0x8000_0000)
        );
        // WD and WQ
        assert_eq!(lane(&s4(0x23, [0; 16], s), 4, 1), 0x01FF);
        assert_eq!(lane(&s4(0x24, [0; 16], s), 8, 0), 0x7F80);
        assert_eq!(lane(&s4(0x21, [0; 16], s), 4, 2), -1);
        assert_eq!(unsigned(&s4(0x31, [0; 16], s), 4, 2), 0xFF);
    }
    #[test]
    fn quadword_compare_multiply_and_pack() {
        let mut d = [0u8; 16];
        let mut s = [0u8; 16];
        put(&mut d, 8, 0, -1);
        put(&mut s, 8, 0, -1);
        put(&mut d, 8, 1, i64::MIN);
        put(&mut s, 8, 1, i64::MAX);
        assert_eq!(
            (lane(&s4(0x29, d, s), 8, 0), lane(&s4(0x29, d, s), 8, 1)),
            (-1, 0)
        );
        assert_eq!(
            (lane(&s4(0x37, d, s), 8, 0), lane(&s4(0x37, d, s), 8, 1)),
            (0, 0)
        );
        assert_eq!(lane(&s4(0x37, s, d), 8, 1), -1);
        // PMULDQ: the even dwords, signed
        let mut d = [0u8; 16];
        let mut s = [0u8; 16];
        put(&mut d, 4, 0, i32::MIN as i64);
        put(&mut s, 4, 0, i32::MIN as i64);
        put(&mut d, 4, 1, 7);
        put(&mut d, 4, 2, -3);
        put(&mut s, 4, 2, 0x7FFF_FFFF);
        let r = s4(0x28, d, s);
        assert_eq!(
            (lane(&r, 8, 0), lane(&r, 8, 1)),
            (1 << 62, -3 * 0x7FFF_FFFF)
        );
        // PMULLD keeps the low half; PACKUSDW saturates to unsigned words
        assert_eq!(lane(&s4(0x40, d, s), 4, 0), 0);
        assert_eq!(lane(&s4(0x40, d, s), 4, 2), -3i64 * 0x7FFF_FFFF << 32 >> 32);
        let mut d = [0u8; 16];
        for (i, v) in [-1i64, 0x10000, 0xFFFF, 0x8000].iter().enumerate() {
            put(&mut d, 4, i, *v);
        }
        assert_eq!(
            words(s4(0x2B, d, [0; 16])),
            [0, -1, -1, -0x8000, 0, 0, 0, 0]
        );
    }
    #[test]
    fn min_max_signedness_and_phminposuw() {
        let mut d = [0u8; 16];
        let mut s = [0u8; 16];
        put(&mut d, 4, 0, -1);
        put(&mut s, 4, 0, 1);
        assert_eq!(lane(&s4(0x39, d, s), 4, 0), -1); // PMINSD
        assert_eq!(lane(&s4(0x3B, d, s), 4, 0), 1); // PMINUD
        assert_eq!(lane(&s4(0x3D, d, s), 4, 0), 1); // PMAXSD
        assert_eq!(lane(&s4(0x3F, d, s), 4, 0), -1); // PMAXUD
        assert_eq!(s4(0x38, [0x80; 16], [0x7F; 16])[0], 0x80); // PMINSB
        assert_eq!(s4(0x3C, [0x80; 16], [0x7F; 16])[0], 0x7F); // PMAXSB
        assert_eq!(
            words(s4(0x3A, from_words(&[-1; 8]), from_words(&[1; 8])))[0],
            1
        ); // PMINUW
        assert_eq!(
            words(s4(0x3E, from_words(&[-1; 8]), from_words(&[1; 8])))[0],
            -1
        ); // PMAXUW
           // the first of equal minimums; the rest zero
        let s = from_words::<16>(&[9, 3, -1, 3, 4, 3, 8, 3]);
        assert_eq!(words(s4(0x41, [0xFF; 16], s)), [3, 1, 0, 0, 0, 0, 0, 0]);
        assert_eq!(
            words(s4(0x41, [0; 16], from_words(&[-1; 8]))),
            [-1, 0, 0, 0, 0, 0, 0, 0]
        );
    }
    #[test]
    fn ptest_flags() {
        assert_eq!(ptest([0xF0; 16], [0x0F; 16]), (true, false));
        assert_eq!(ptest([0xFF; 16], [0x0F; 16]), (false, true));
        assert_eq!(ptest([0; 16], [0; 16]), (true, true));
        let mut s = [0u8; 16];
        s[15] = 0x80;
        assert_eq!(ptest([0x7F; 16], s), (true, false));
    }
    #[test]
    fn blends_mpsadbw_and_insertps() {
        let d: [u8; 16] = std::array::from_fn(|i| i as u8);
        let s: [u8; 16] = std::array::from_fn(|i| 0x80 + i as u8);
        assert_eq!(
            &sse4_imm(0x0C, d, s, 0b1010)[..8],
            &[0, 1, 2, 3, 0x84, 0x85, 0x86, 0x87]
        );
        assert_eq!(sse4_imm(0x0D, d, s, 0b10)[8], 0x88);
        assert_eq!(sse4_imm(0x0E, d, s, 0x81)[..4], [0x80, 0x81, 2, 3]);
        assert_eq!(sse4_imm(0x0E, d, s, 0x81)[14], 0x8E);
        // MPSADBW: |d[off + i + j] - s[4k + j]|
        let r = words(sse4_imm(0x42, d, s, 0b110));
        let expected: Vec<i16> = (0..8)
            .map(|i| (0..4).map(|j| (0x80 + 8 + j - (4 + i + j)) as i16).sum())
            .collect();
        assert_eq!(r, expected);
        // INSERTPS: dword 2 := value, then dwords 0 and 3 zeroed
        let r = insertps(d, 0xAABBCCDD, 0b10_1001);
        assert_eq!(unsigned(&r, 4, 2), 0xAABBCCDD);
        assert_eq!(
            (unsigned(&r, 4, 0), unsigned(&r, 4, 1), unsigned(&r, 4, 3)),
            (0, 0x07060504, 0)
        );
    }
    #[test]
    fn crc32c_check_value_and_widths() {
        // the check value of CRC-32C, "123456789": from all ones, inverted after
        let crc = b"123456789"
            .iter()
            .fold(!0, |crc, &b| crc32c(crc, b as u64, 1));
        assert_eq!(!crc, 0xE306_9283);
        // wider operands: their bytes, least significant first; only `bytes` of them
        let bytewise = b"12345678"
            .iter()
            .fold(!0, |crc, &b| crc32c(crc, b as u64, 1));
        assert_eq!(crc32c(!0, u64::from_le_bytes(*b"12345678"), 8), bytewise);
        assert_eq!(
            crc32c(5, 0xFFFF_0000_1234, 2),
            crc32c(crc32c(5, 0x34, 1), 0x12, 1)
        );
    }
    #[test]
    fn compare_strings_examples() {
        let s = |text: &[u8]| -> [u8; 16] {
            let mut v = [0; 16];
            v[..text.len()].copy_from_slice(text);
            v
        };
        // equal any: the vowels of "hello world"; both strings end early
        let r = compare_strings(0x00, s(b"aeiou"), s(b"hello world"), None, None);
        assert_eq!((r.mask, r.index, r.flags), (0x92, 1, 0xC1));
        // ... as a byte mask (PCMPxSTRM, imm8[6])
        let r = compare_strings(0x40, s(b"aeiou"), s(b"hello world"), None, None);
        assert_eq!(r.xmm0, s(b"\0\xFF\0\0\xFF\0\0\xFF"));
        // ranges: the lower-case letters
        let r = compare_strings(0x04, s(b"az"), s(b"Hello1"), None, None);
        assert_eq!(r.mask, 0x1E);
        // equal ordered: "lo" at 3; a needle running off the end of a full
        // haystack matches there, but not past the end of a shorter one
        let r = compare_strings(0x0C, s(b"lo"), s(b"hello world"), None, None);
        assert_eq!((r.mask, r.index), (0x08, 3));
        let r = compare_strings(0x0C, s(b"bcd"), *b"aaaaaaaaaaaaaaab", None, None);
        assert_eq!(r.mask, 0x8000);
        let r = compare_strings(0x0C, s(b"bcd"), s(b"aaaab"), None, None);
        assert_eq!(r.mask, 0);
        // equal each, masked negative: the first difference (strcmp), the
        // elements after both strings equal
        let r = compare_strings(0x38, s(b"abcd"), s(b"abxd"), None, None);
        assert_eq!((r.mask, r.index, r.flags & 1), (0xFFF4, 2, 1));
        // signed words, explicit lengths: absolute values, at most 8
        let w = |words: &[i16]| -> [u8; 16] {
            let mut v = [0; 16];
            for (i, x) in words.iter().enumerate() {
                v[2 * i..2 * i + 2].copy_from_slice(&x.to_le_bytes());
            }
            v
        };
        let r = compare_strings(0x03, w(&[-1, 5, 9]), w(&[5, -1, 7, 9]), Some(-2), Some(3));
        assert_eq!((r.mask, r.flags), (0b011, 0xC1 | 0x800));
        let r = compare_strings(0x03, w(&[-1, 5]), w(&[5]), Some(i64::MIN), Some(100));
        // (both saturate to 8 elements, the zero words valid too: they match;
        // no ZF or SF)
        assert_eq!((r.mask, r.flags & 0xC0), (0xFF, 0));
        // no match: the index is the element count
        let r = compare_strings(0x01, w(&[3]), w(&[4]), None, None);
        assert_eq!((r.mask, r.index), (0, 8));
    }
    #[test]
    fn palignr_every_shift() {
        let d: [u8; 16] = std::array::from_fn(|i| 0x20 + i as u8);
        let s: [u8; 16] = std::array::from_fn(|i| 0x10 + i as u8);
        for imm in 0..=255u8 {
            let r = palignr(d, s, imm);
            for i in 0..16 {
                let n = i + imm as usize;
                assert_eq!(r[i], if n < 32 { 0x10 + n as u8 } else { 0 });
            }
        }
        let r = palignr([0x21u8; 8], [0x11; 8], 7);
        assert_eq!(r, [0x11, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21]);
        assert_eq!(palignr([1u8; 8], [2; 8], 16), [0; 8]);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/src/rust/cpu/simd_ops.rs                                                                 0000644 0000000 0000000 00000045145 00000000000 014433  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Explicit packed XMM integer semantics. IDs are the canonical 66 0F opcode
//! byte, except PSHUFB's (66 0F 38 00), which takes the unused 00, and the
//! SSE4.1/SSE4.2 forms', which are their 66 0F 38 byte (PackedOp::sse4).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum PackedOp {
    UnpackLow8 = 0x60,
    UnpackLow16 = 0x61,
    UnpackLow32 = 0x62,
    UnpackHigh8 = 0x68,
    UnpackHigh16 = 0x69,
    UnpackHigh32 = 0x6A,
    UnpackLow64 = 0x6C,
    UnpackHigh64 = 0x6D,
    PackS16S8 = 0x63,
    PackS16U8 = 0x67,
    PackS32S16 = 0x6B,
    Shr16 = 0xD1,
    Shr32 = 0xD2,
    Shr64 = 0xD3,
    Sar16 = 0xE1,
    Sar32 = 0xE2,
    Shl16 = 0xF1,
    Shl32 = 0xF2,
    Shl64 = 0xF3,

    Add8 = 0xFC,
    Add16 = 0xFD,
    Add32 = 0xFE,
    Add64 = 0xD4,
    Sub8 = 0xF8,
    Sub16 = 0xF9,
    Sub32 = 0xFA,
    Sub64 = 0xFB,
    AddSatS8 = 0xEC,
    AddSatS16 = 0xED,
    AddSatU8 = 0xDC,
    AddSatU16 = 0xDD,
    SubSatS8 = 0xE8,
    SubSatS16 = 0xE9,
    SubSatU8 = 0xD8,
    SubSatU16 = 0xD9,
    GtS8 = 0x64,
    GtS16 = 0x65,
    GtS32 = 0x66,
    Eq8 = 0x74,
    Eq16 = 0x75,
    Eq32 = 0x76,
    MinU8 = 0xDA,
    MaxU8 = 0xDE,
    MinS16 = 0xEA,
    MaxS16 = 0xEE,
    AvgU8 = 0xE0,
    AvgU16 = 0xE3,
    MulHighU16 = 0xE4,
    MulHighS16 = 0xE5,
    MulU32 = 0xF4,
    SadU8 = 0xF6,
    MulLow16 = 0xD5,
    MaddS16 = 0xF5,
    And = 0xDB,
    AndNot = 0xDF,
    Or = 0xEB,
    Xor = 0xEF,
    /// PSHUFB (SSSE3)
    ShuffleBytes = 0x00,
    /// SSE4.1 and SSE4.2 (66 0F 38 xx, crate::cpu::simd_int::sse4)
    Eq64 = 0x29,
    PackS32U16 = 0x2B,
    GtS64 = 0x37,
    MinS8 = 0x38,
    MinS32 = 0x39,
    MinU16 = 0x3A,
    MinU32 = 0x3B,
    MaxS8 = 0x3C,
    MaxS32 = 0x3D,
    MaxU16 = 0x3E,
    MaxU32 = 0x3F,
    MulLow32 = 0x40,
}
impl PackedOp {
    pub fn from_id(id: u32) -> Option<Self> {
        Some(match id {
            0x60 => Self::UnpackLow8,
            0x61 => Self::UnpackLow16,
            0x62 => Self::UnpackLow32,
            0x68 => Self::UnpackHigh8,
            0x69 => Self::UnpackHigh16,
            0x6A => Self::UnpackHigh32,
            0x6C => Self::UnpackLow64,
            0x6D => Self::UnpackHigh64,
            0x63 => Self::PackS16S8,
            0x67 => Self::PackS16U8,
            0x6B => Self::PackS32S16,
            0xD1 => Self::Shr16,
            0xD2 => Self::Shr32,
            0xD3 => Self::Shr64,
            0xE1 => Self::Sar16,
            0xE2 => Self::Sar32,
            0xF1 => Self::Shl16,
            0xF2 => Self::Shl32,
            0xF3 => Self::Shl64,

            0xFC => Self::Add8,
            0xFD => Self::Add16,
            0xFE => Self::Add32,
            0xD4 => Self::Add64,
            0xF8 => Self::Sub8,
            0xF9 => Self::Sub16,
            0xFA => Self::Sub32,
            0xFB => Self::Sub64,
            0xEC => Self::AddSatS8,
            0xED => Self::AddSatS16,
            0xDC => Self::AddSatU8,
            0xDD => Self::AddSatU16,
            0xE8 => Self::SubSatS8,
            0xE9 => Self::SubSatS16,
            0xD8 => Self::SubSatU8,
            0xD9 => Self::SubSatU16,
            0x64 => Self::GtS8,
            0x65 => Self::GtS16,
            0x66 => Self::GtS32,
            0x74 => Self::Eq8,
            0x75 => Self::Eq16,
            0x76 => Self::Eq32,
            0xDA => Self::MinU8,
            0xDE => Self::MaxU8,
            0xEA => Self::MinS16,
            0xEE => Self::MaxS16,
            0xE0 => Self::AvgU8,
            0xE3 => Self::AvgU16,
            0xE4 => Self::MulHighU16,
            0xE5 => Self::MulHighS16,
            0xF4 => Self::MulU32,
            0xF6 => Self::SadU8,
            0xD5 => Self::MulLow16,
            0xF5 => Self::MaddS16,
            0xDB => Self::And,
            0xDF => Self::AndNot,
            0xEB => Self::Or,
            0xEF => Self::Xor,
            0x00 => Self::ShuffleBytes,
            0x29 => Self::Eq64,
            0x2B => Self::PackS32U16,
            0x37 => Self::GtS64,
            0x38 => Self::MinS8,
            0x39 => Self::MinS32,
            0x3A => Self::MinU16,
            0x3B => Self::MinU32,
            0x3C => Self::MaxS8,
            0x3D => Self::MaxS32,
            0x3E => Self::MaxU16,
            0x3F => Self::MaxU32,
            0x40 => Self::MulLow32,
            _ => return None,
        })
    }
    /// An SSE4.1/SSE4.2 form (its id is a 66 0F 38 byte; as a 66 0F byte, it
    /// is another instruction, MOVAPD for instance)
    pub fn sse4(self) -> bool { (self as u8) >= 0x29 && (self as u8) <= 0x40 }
    pub fn from_encoding(op: u32) -> Option<Self> {
        match op {
            0x0F14 => Some(Self::UnpackLow32),
            0x0F15 => Some(Self::UnpackHigh32),
            0x660F14 => Some(Self::UnpackLow64),
            0x660F15 => Some(Self::UnpackHigh64),
            0x0F54 | 0x660F54 => Some(Self::And),
            0x0F55 | 0x660F55 => Some(Self::AndNot),
            0x0F56 | 0x660F56 => Some(Self::Or),
            0x0F57 | 0x660F57 => Some(Self::Xor),
            0x660F3800 => Some(Self::ShuffleBytes),
            _ if op >> 8 == 0x660F38 => Self::from_id(op & 255).filter(|p| p.sse4()),
            _ if op >> 8 == 0x660F && op & 255 != 0 => {
                Self::from_id(op & 255).filter(|p| !p.sse4())
            },
            _ => None,
        }
    }
    pub fn wasm_opcode(self) -> Option<u32> {
        Some(match self {
            Self::PackS16S8 => 0x65,
            Self::PackS16U8 => 0x66,
            Self::PackS32S16 => 0x85,
            Self::Add8 => 0x6E,
            Self::Add16 => 0x8E,
            Self::Add32 => 0xAE,
            Self::Add64 => 0xCE,
            Self::Sub8 => 0x71,
            Self::Sub16 => 0x91,
            Self::Sub32 => 0xB1,
            Self::Sub64 => 0xD1,
            Self::AddSatS8 => 0x6F,
            Self::AddSatS16 => 0x8F,
            Self::AddSatU8 => 0x70,
            Self::AddSatU16 => 0x90,
            Self::SubSatS8 => 0x72,
            Self::SubSatS16 => 0x92,
            Self::SubSatU8 => 0x73,
            Self::SubSatU16 => 0x93,
            Self::GtS8 => 0x27,
            Self::GtS16 => 0x31,
            Self::GtS32 => 0x3B,
            Self::Eq8 => 0x23,
            Self::Eq16 => 0x2D,
            Self::Eq32 => 0x37,
            Self::MinU8 => 0x77,
            Self::MaxU8 => 0x79,
            Self::MinS16 => 0x96,
            Self::MaxS16 => 0x98,
            Self::AvgU8 => 0x7B,
            Self::AvgU16 => 0x9B,
            Self::MulLow16 => 0x95,
            Self::MaddS16 => 0xBA,
            Self::And => 0x4E,
            Self::AndNot => 0x4F,
            Self::Or => 0x50,
            Self::Xor => 0x51,
            Self::Eq64 => 0xD6,
            Self::PackS32U16 => 0x86,
            Self::GtS64 => 0xD9,
            Self::MinS8 => 0x76,
            Self::MinS32 => 0xB6,
            Self::MinU16 => 0x97,
            Self::MinU32 => 0xB7,
            Self::MaxS8 => 0x78,
            Self::MaxS32 => 0xB8,
            Self::MaxU16 => 0x99,
            Self::MaxU32 => 0xB9,
            Self::MulLow32 => 0xB5,
            _ => return None,
        })
    }
    pub fn unpack(self) -> Option<(u8, bool)> {
        use PackedOp::*;
        Some(match self {
            UnpackLow8 => (1, false),
            UnpackLow16 => (2, false),
            UnpackLow32 => (4, false),
            UnpackLow64 => (8, false),
            UnpackHigh8 => (1, true),
            UnpackHigh16 => (2, true),
            UnpackHigh32 => (4, true),
            UnpackHigh64 => (8, true),
            _ => return None,
        })
    }
    /// (lane bits, arithmetic right, left, Wasm opcode). Count is unsigned u64.
    pub fn shift(self) -> Option<(u8, bool, bool, u32)> {
        use PackedOp::*;
        Some(match self {
            Shr16 => (16, false, false, 0x8D),
            Shr32 => (32, false, false, 0xAD),
            Shr64 => (64, false, false, 0xCD),
            Sar16 => (16, true, false, 0x8C),
            Sar32 => (32, true, false, 0xAC),
            Shl16 => (16, false, true, 0x8B),
            Shl32 => (32, false, true, 0xAB),
            Shl64 => (64, false, true, 0xCB),
            _ => return None,
        })
    }
    /// CPU slow completion: destination is sampled after the entire source read.
    pub fn apply(self, destination: [u8; 16], source: [u8; 16]) -> [u8; 16] {
        use PackedOp::*;
        if self == ShuffleBytes {
            return crate::cpu::simd_int::ssse3(0x00, destination, source);
        }
        if self.sse4() {
            return crate::cpu::simd_int::sse4(self as u8, destination, source, [0; 16]);
        }
        fn lane(v: &[u8; 16], bytes: usize, index: usize) -> u64 {
            let mut value = [0; 8];
            value[..bytes].copy_from_slice(&v[index * bytes..(index + 1) * bytes]);
            u64::from_le_bytes(value)
        }
        fn signed(value: u64, bits: usize) -> i64 { ((value << (64 - bits)) as i64) >> (64 - bits) }
        if let Some((width, high)) = self.unpack() {
            let width = width as usize;
            let start = if high { 8 } else { 0 };
            let mut result = [0; 16];
            for i in 0..8 / width {
                for (side, value) in [destination, source].iter().enumerate() {
                    result[(2 * i + side) * width..(2 * i + side + 1) * width]
                        .copy_from_slice(&value[start + i * width..start + (i + 1) * width]);
                }
            }
            return result;
        }
        if matches!(self, PackS16S8 | PackS16U8 | PackS32S16) {
            let width = if self == PackS32S16 { 2 } else { 1 };
            let (min, max) = if self == PackS16U8 {
                (0, 255)
            }
            else {
                (-(1i64 << (width * 8 - 1)), (1i64 << (width * 8 - 1)) - 1)
            };
            let mut result = [0; 16];
            for (half, value) in [destination, source].iter().enumerate() {
                for i in 0..8 / width {
                    let n = signed(lane(value, width * 2, i), width * 16).clamp(min, max);
                    result[8 * half + i * width..8 * half + (i + 1) * width]
                        .copy_from_slice(&n.to_le_bytes()[..width]);
                }
            }
            return result;
        }
        if let Some((bits, arithmetic, left, _)) = self.shift() {
            let count = lane(&source, 8, 0);
            let bits = bits as usize;
            let width = bits / 8;
            let mut result = [0; 16];
            for i in 0..16 / width {
                let n = lane(&destination, width, i);
                let n = if arithmetic {
                    (signed(n, bits) >> count.min((bits - 1) as u64)) as u64
                }
                else if count >= bits as u64 {
                    0
                }
                else if left {
                    n << count
                }
                else {
                    n >> count
                };
                result[i * width..(i + 1) * width].copy_from_slice(&n.to_le_bytes()[..width]);
            }
            return result;
        }
        let bytes = match self {
            Add64 | Sub64 | MulU32 | SadU8 => 8,
            Add32 | Sub32 | GtS32 | Eq32 | MaddS16 => 4,
            Add16 | Sub16 | AddSatS16 | AddSatU16 | SubSatS16 | SubSatU16 | GtS16 | Eq16
            | MinS16 | MaxS16 | AvgU16 | MulHighU16 | MulHighS16 | MulLow16 => 2,
            _ => 1,
        };
        let bits = bytes * 8;
        let mask = u64::MAX >> (64 - bits);
        let mut result = [0; 16];
        for i in 0..16 / bytes {
            let a = lane(&destination, bytes, i);
            let b = lane(&source, bytes, i);
            let sa = signed(a, bits);
            let sb = signed(b, bits);
            let value = match self {
                Add8 | Add16 | Add32 | Add64 => a.wrapping_add(b),
                Sub8 | Sub16 | Sub32 | Sub64 => a.wrapping_sub(b),
                AddSatS8 | AddSatS16 => {
                    (sa + sb).clamp(-(1 << (bits - 1)), (1 << (bits - 1)) - 1) as u64
                },
                SubSatS8 | SubSatS16 => {
                    (sa - sb).clamp(-(1 << (bits - 1)), (1 << (bits - 1)) - 1) as u64
                },
                AddSatU8 | AddSatU16 => (a + b).min(mask),
                SubSatU8 | SubSatU16 => a.saturating_sub(b),
                GtS8 | GtS16 | GtS32 => {
                    if sa > sb {
                        mask
                    }
                    else {
                        0
                    }
                },
                Eq8 | Eq16 | Eq32 => {
                    if a == b {
                        mask
                    }
                    else {
                        0
                    }
                },
                MinU8 => a.min(b),
                MaxU8 => a.max(b),
                MinS16 => sa.min(sb) as u64,
                MaxS16 => sa.max(sb) as u64,
                AvgU8 | AvgU16 => (a + b + 1) >> 1,
                MulHighU16 => a * b >> 16,
                MulHighS16 => (sa * sb >> 16) as u64,
                MulLow16 => a * b,
                MulU32 => lane(&destination, 4, 2 * i) * lane(&source, 4, 2 * i),
                MaddS16 => (0..2)
                    .map(|j| {
                        signed(lane(&destination, 2, 2 * i + j), 16)
                            * signed(lane(&source, 2, 2 * i + j), 16)
                    })
                    .sum::<i64>() as u64,
                SadU8 => (0..8)
                    .map(|j| {
                        (destination[8 * i + j] as i64 - source[8 * i + j] as i64).unsigned_abs()
                    })
                    .sum(),
                And => a & b,
                AndNot => !a & b,
                Or => a | b,
                Xor => a ^ b,
                _ => unreachable!("packed operation handled above"),
            };
            result[i * bytes..(i + 1) * bytes].copy_from_slice(&value.to_le_bytes()[..bytes]);
        }
        result
    }
}

/// Immediate-controlled shuffles. Pure semantics select bytes from old destination/source.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum ShuffleOp {
    Dwords = 0,
    LowWords = 1,
    HighWords = 2,
    Singles = 3,
    Doubles = 4,
    /// BLENDPS, BLENDPD, PBLENDW (SSE4.1): imm8 selects the source's lanes
    BlendSingles = 5,
    BlendDoubles = 6,
    BlendWords = 7,
}
impl ShuffleOp {
    pub fn from_id(id: u32) -> Option<Self> {
        Some(match id {
            0 => Self::Dwords,
            1 => Self::LowWords,
            2 => Self::HighWords,
            3 => Self::Singles,
            4 => Self::Doubles,
            5 => Self::BlendSingles,
            6 => Self::BlendDoubles,
            7 => Self::BlendWords,
            _ => return None,
        })
    }
    pub fn from_encoding(op: u32) -> Option<Self> {
        Some(match op {
            0x660F3A0C => Self::BlendSingles,
            0x660F3A0D => Self::BlendDoubles,
            0x660F3A0E => Self::BlendWords,
            0x660F70 => Self::Dwords,
            0xF20F70 => Self::LowWords,
            0xF30F70 => Self::HighWords,
            0x0FC6 => Self::Singles,
            0x660FC6 => Self::Doubles,
            _ => return None,
        })
    }
    pub fn lanes(self, immediate: u8) -> [u8; 16] {
        let mut lanes = [0; 16];
        for byte in 0..16u8 {
            lanes[byte as usize] = match self {
                Self::Dwords => 16 + ((immediate >> (byte / 4 * 2)) & 3) * 4 + byte % 4,
                Self::LowWords if byte < 8 => {
                    16 + ((immediate >> (byte / 2 * 2)) & 3) * 2 + byte % 2
                },
                Self::HighWords if byte >= 8 => {
                    24 + ((immediate >> ((byte - 8) / 2 * 2)) & 3) * 2 + byte % 2
                },
                Self::LowWords | Self::HighWords => 16 + byte,
                Self::Singles => {
                    (if byte < 8 { 0 } else { 16 })
                        + ((immediate >> (byte / 4 * 2)) & 3) * 4
                        + byte % 4
                },
                Self::Doubles => {
                    (if byte < 8 { 0 } else { 16 }) + ((immediate >> (byte / 8)) & 1) * 8 + byte % 8
                },
                Self::BlendSingles | Self::BlendDoubles | Self::BlendWords => {
                    let size = match self {
                        Self::BlendSingles => 4,
                        Self::BlendDoubles => 8,
                        _ => 2,
                    };
                    byte + if immediate >> (byte / size) & 1 != 0 { 16 } else { 0 }
                },
            };
        }
        lanes
    }
    pub fn apply(self, destination: [u8; 16], source: [u8; 16], immediate: u8) -> [u8; 16] {
        let inputs = [destination, source];
        self.lanes(immediate)
            .map(|index| inputs[index as usize / 16][index as usize % 16])
    }
}

/// Fixed transfers that merge with old target lanes or duplicate source lanes.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum TransferOp {
    Low64 = 0,
    High64 = 1,
    Duplicate64 = 2,
    DuplicateLow32 = 3,
    DuplicateHigh32 = 4,
}
impl TransferOp {
    pub fn from_id(id: u32) -> Option<Self> {
        Some(match id {
            0 => Self::Low64,
            1 => Self::High64,
            2 => Self::Duplicate64,
            3 => Self::DuplicateLow32,
            4 => Self::DuplicateHigh32,
            _ => return None,
        })
    }
    pub fn from_encoding(op: u32) -> Option<Self> {
        Some(match op {
            0x0F12 | 0x660F12 => Self::Low64,
            0x0F16 | 0x660F16 => Self::High64,
            0xF20F12 => Self::Duplicate64,
            0xF30F12 => Self::DuplicateLow32,
            0xF30F16 => Self::DuplicateHigh32,
            _ => return None,
        })
    }
    pub fn bytes(self) -> u8 {
        if matches!(self, Self::DuplicateLow32 | Self::DuplicateHigh32) {
            16
        }
        else {
            8
        }
    }
    pub fn lanes(self) -> [u8; 16] {
        let mut lanes = [0; 16];
        for n in 0..16u8 {
            lanes[n as usize] = match self {
                Self::Low64 => {
                    if n < 8 {
                        16 + n
                    }
                    else {
                        n
                    }
                },
                Self::High64 => {
                    if n < 8 {
                        n
                    }
                    else {
                        16 + n - 8
                    }
                },
                Self::Duplicate64 => 16 + n % 8,
                Self::DuplicateLow32 => 16 + n / 8 * 8 + n % 4,
                Self::DuplicateHigh32 => 20 + n / 8 * 8 + n % 4,
            };
        }
        lanes
    }
    pub fn apply(self, destination: [u8; 16], source: [u8; 16]) -> [u8; 16] {
        let values = [destination, source];
        self.lanes()
            .map(|i| values[i as usize / 16][i as usize % 16])
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/rust/cpu/smm.rs                                                                      0000644 0000000 0000000 00000056343 00000000000 013414  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! System management mode, for the Q35 machine: the ICH9 raises SMIs from
//! the APM control port and the TCO watchdog (src/acpi.js), the local APICs
//! deliver SMI messages (IPIs, MSIs, IOAPIC entries). crate::cpu::apic
//! latches an SMI per core; handle_irqs takes it while the core is not in
//! SMM, so one that comes in SMM waits for RSM.
//!
//! An SMI saves the CPU state at SMBASE + 0xFE00 in a layout of QEMU's
//! target/i386/tcg/system/smm_helper.c: the 32-bit one (revision 0x20000)
//! with the legacy CPU profile, the 64-bit one (revision 0x20064) with the
//! x86-64 profile, in every mode, as AMD64 and Intel 64 processors do.
//! SeaBIOS's SMI handler reads and edits both (src/fw/smm.c: the SMBASE
//! relocation and call32_smm). The handler starts at SMBASE + 0x8000 in real
//! mode with 4 GiB segment limits, without paging (and long mode: EFER is
//! cleared). RSM restores the state, and a new SMBASE from the save area.
//!
//! SMRAM, as the Q35 MCH decodes it (src/q35.js passes its controls):
//! - compatible SMRAM, the RAM behind the VGA window (0xA0000-0xBFFFF): in SMM
//!   with G_SMRAME (D_CLS keeps data accesses on the VGA window then, but not
//!   instruction fetches), and for everyone while software opened it (D_OPEN);
//! - high SMRAM (ESMRAMC.H_SMRAME): instead of that, the same RAM at
//!   0xFEDA0000-0xFEDBFFFF, under the same conditions (SMBASE may point there);
//! - TSEG, the top of the RAM below 4 GiB (ESMRAMC.T_EN with G_SMRAME): RAM in
//!   SMM; elsewhere it reads as all ones and ignores writes.
//! Those addresses stay mapped (crate::cpu::memory's out-of-line paths
//! decide; TSEG lowers the fast RAM limit, and the x64 bus decodes it,
//! crate::x64::physical), so nothing in them is cached or compiled.
//!
//! An SMI that interrupts HLT sets the auto HALT restart field of the save
//! area; RSM returns to the halt state if the handler left it set. Not
//! supported: the I/O instruction restart field (cleared at the SMI, ignored
//! by RSM), and ESMRAMC.E_SMERR, as in QEMU.

use crate::cpu::apic;
use crate::cpu::cpu::*;
use crate::cpu::global_pointers::*;
use crate::cpu::memory;
use crate::x64::state as x64;

/// SMM revision identifiers: SMBASE relocation (bit 17), and the save map
pub const SMM_REVISION_32: u32 = 0x0002_0000;
pub const SMM_REVISION_64: u32 = 0x0002_0064;
const SMM_REVISION_RELOCATION: u32 = 0x0002_0000;
pub const SMBASE_DEFAULT: u32 = 0x30000;

const SMM_ACTIVE: u32 = 1 << 0;
const SMM_NMI_BLOCKED: u32 = 1 << 1;
/// The state is in the 64-bit save map (RSM reads the map the SMI wrote)
const SMM_MAP_64: u32 = 1 << 2;
/// The SMI interrupted HLT (the auto HALT restart field may return to it)
const SMM_HALTED: u32 = 1 << 3;

/// The chipset's SMRAM control, the same for every core
pub static mut SMRAM_CONTROL: u8 = 0;
pub const SMRAM_G_SMRAME: u8 = 1 << 0;
pub const SMRAM_D_OPEN: u8 = 1 << 1;
pub const SMRAM_H_SMRAME: u8 = 1 << 2;
pub const SMRAM_D_CLS: u8 = 1 << 3;

/// High SMRAM: compatible SMRAM's RAM at this address, with H_SMRAME
const HIGH_SMRAM: u32 = 0xFEDA_0000;
const COMPATIBLE_SMRAM: u32 = 0xA0000;
const SMRAM_SIZE: u32 = 0x20000;

/// TSEG: [base, end), empty without it. `generation` counts changes, so that
/// cores in workers take them over (sync_worker).
#[repr(C)]
pub struct Tseg {
    base: u32,
    end: u32,
    generation: u32,
}
pub static mut TSEG: Tseg = Tseg {
    base: 0,
    end: 0,
    generation: 0,
};
/// The TSEG generation this instance's fast RAM limit and caches reflect
static mut TSEG_SEEN: u32 = 0;

/// The chipset's SMRAM control changed (src/q35.js): G_SMRAME (bit 0),
/// D_OPEN (bit 1), H_SMRAME (bit 2), D_CLS (bit 3)
#[no_mangle]
pub unsafe fn smram_set_control(value: u8) {
    *crate::parallel::machine(&raw mut SMRAM_CONTROL) = value;
}

/// The chipset's TSEG changed (src/q35.js): [base, end), or empty
#[no_mangle]
pub unsafe fn smram_set_tseg(base: u32, end: u32) {
    let (base, end) = if base < end { (base, end) } else { (0, 0) };
    let tseg = &mut *crate::parallel::machine(&raw mut TSEG);
    if tseg.base == base && tseg.end == end {
        return;
    }
    dbg_log!("TSEG: {:x}-{:x}", base, end);
    tseg.base = base;
    tseg.end = end;
    tseg.generation = tseg.generation.wrapping_add(1);
    TSEG_SEEN = tseg.generation;
    crate::x64::physical::memory_map_changed();
}

/// The first byte of TSEG, or u32::MAX without one: the fast RAM limit is
/// below it (crate::x64::physical)
pub unsafe fn tseg_floor() -> u32 {
    let tseg = &*crate::parallel::machine(&raw mut TSEG);
    if tseg.base < tseg.end {
        tseg.base
    }
    else {
        u32::MAX
    }
}

#[inline(always)]
pub unsafe fn in_tseg(addr: u32) -> bool {
    let tseg = &*crate::parallel::machine(&raw mut TSEG);
    addr >= tseg.base && addr < tseg.end
}

/// TSEG outside SMM: all ones, writes dropped (as the low RAM hole)
#[inline(always)]
pub unsafe fn tseg_blackhole(addr: u32) -> bool { in_tseg(addr) && !smm_active() }

/// A core in a worker (crate::parallel), at the start of its slice: the
/// machine changed TSEG, so the fast RAM limit and the cached translations
/// of this instance change with it
pub unsafe fn sync_worker() {
    let generation = (*crate::parallel::machine(&raw mut TSEG)).generation;
    if generation != TSEG_SEEN {
        TSEG_SEEN = generation;
        memory::ram_fast_limit = *crate::parallel::machine(&raw mut memory::ram_fast_limit);
        crate::x64::physical::copy_from_machine();
        crate::cpu::context::invalidate_all_tlbs();
    }
}

#[no_mangle]
pub unsafe fn smm_active() -> bool { *smm_state & SMM_ACTIVE != 0 }

/// An SMI is waiting that this core can take
pub unsafe fn smi_deliverable() -> bool { !smm_active() && apic::smi_pending() }

/// Where an access to `addr` (`bytes` long) reaches the RAM of SMRAM:
/// compatible SMRAM behind the VGA window, its alias at 0xFEDA0000 (high
/// SMRAM), TSEG in SMM; None elsewhere. `fetch`: an instruction fetch (D_CLS
/// does not keep those from compatible SMRAM).
#[inline(always)]
pub unsafe fn smram_ram(addr: u32, bytes: u32, fetch: bool) -> Option<u32> {
    let last = addr.wrapping_add(bytes - 1);
    if addr >= COMPATIBLE_SMRAM && last < COMPATIBLE_SMRAM + SMRAM_SIZE {
        let control = *crate::parallel::machine(&raw mut SMRAM_CONTROL);
        (control & SMRAM_H_SMRAME == 0
            && (control & SMRAM_D_OPEN != 0
                || control & SMRAM_G_SMRAME != 0
                    && smm_active()
                    && (fetch || control & SMRAM_D_CLS == 0)))
            .then_some(addr)
    }
    else if addr >= HIGH_SMRAM && last < HIGH_SMRAM + SMRAM_SIZE {
        let control = *crate::parallel::machine(&raw mut SMRAM_CONTROL);
        (control & SMRAM_H_SMRAME != 0
            && (control & SMRAM_D_OPEN != 0 || control & SMRAM_G_SMRAME != 0 && smm_active()))
        .then_some(addr - HIGH_SMRAM + COMPATIBLE_SMRAM)
    }
    else {
        (in_tseg(addr) && in_tseg(last) && smm_active()).then_some(addr)
    }
}

/// Whether an SMI saves the state in the 64-bit map: with the x86-64
/// profile, and in long mode (which the legacy profile does not report, but
/// does not keep from a guest either)
unsafe fn layout_64() -> bool {
    crate::cpu::instructions_0f::long_mode_capable() || x64::efer() & x64::EFER_LMA != 0
}

/// QEMU's segment attributes: the access byte, and AVL, L, D/B, G in bits
/// 12-15. (TR and LDTR have no access byte here: a busy TSS of the size of
/// the task (a 64-bit one in long mode), an LDT.)
unsafe fn attributes(segment: i32) -> u32 {
    let access = match segment {
        TR => 0x80 | if x64::efer() & x64::EFER_LMA != 0 || *tss_size_32 { 0x0B } else { 0x03 },
        LDTR => {
            if *sreg.offset(LDTR as isize) & !3 == 0 {
                0
            }
            else {
                0x82
            }
        },
        _ => *segment_access_bytes.offset(segment as isize) as u32,
    };
    let long = segment == CS && *x64_cs_long != 0;
    let big = match segment {
        CS => *is_32,
        SS => *stack_size_32,
        _ => false,
    };
    let granular = *segment_limits.offset(segment as isize) > 0xFFFFF;
    access | (long as u32) << 13 | (big as u32) << 14 | (granular as u32) << 15
}

unsafe fn load_segment(segment: i32, selector: u32, base: u64, limit: u32, attributes: u32) {
    *sreg.offset(segment as isize) = selector as u16;
    x64::write_segment_base(segment as usize, base);
    *segment_limits.offset(segment as isize) = limit;
    *segment_access_bytes.offset(segment as isize) = attributes as u8;
    *segment_is_null.offset(segment as isize) = false;
}

/// The save area: the RAM of SMBASE + 0x8000 (offsets 0x7E00-0x7FFF)
#[derive(Clone, Copy)]
struct SaveArea(u32);

/// The save area of SMBASE `base`: in RAM, or in compatible SMRAM where high
/// SMRAM shows it (with `checked`, only if the chipset enables high SMRAM for
/// SMM). None: SMBASE + 0xFE00-0xFFFF is neither.
unsafe fn save_area(base: u32, checked: bool) -> Option<SaveArea> {
    let first = base.checked_add(0xFE00)?;
    let last = base.checked_add(0xFFFF)?;
    if (last as u64) < *memory_size as u64 {
        Some(SaveArea(base + 0x8000))
    }
    else if first >= HIGH_SMRAM && last < HIGH_SMRAM + SMRAM_SIZE {
        let control = *crate::parallel::machine(&raw mut SMRAM_CONTROL);
        let enabled =
            control & (SMRAM_G_SMRAME | SMRAM_H_SMRAME) == SMRAM_G_SMRAME | SMRAM_H_SMRAME;
        (enabled || !checked).then_some(SaveArea(base + 0x8000 - HIGH_SMRAM + COMPATIBLE_SMRAM))
    }
    else {
        None
    }
}
impl SaveArea {
    unsafe fn read32(self, offset: u32) -> u32 {
        memory::read32_no_mmap_check(self.0 + offset) as u32
    }
    unsafe fn read16(self, offset: u32) -> u32 { self.read32(offset) & 0xFFFF }
    unsafe fn read64(self, offset: u32) -> u64 {
        self.read32(offset) as u64 | (self.read32(offset + 4) as u64) << 32
    }
    unsafe fn write32(self, offset: u32, value: u32) {
        memory::write32_ram(self.0 + offset, value as i32)
    }
    unsafe fn write64(self, offset: u32, value: u64) {
        self.write32(offset, value as u32);
        self.write32(offset + 4, (value >> 32) as u32);
    }
}

/// (offset in the 32-bit save area) of ES, CS, SS, DS, FS, GS: their
/// selectors, and their attributes, limit and base
fn segment_slots_32(segment: i32) -> (u32, u32) {
    let selector = 0x7FA8 + segment as u32 * 4;
    let cache =
        if segment < 3 { 0x7F84 + segment as u32 * 12 } else { 0x7F2C + (segment as u32 - 3) * 12 };
    (selector, cache)
}

/// The 32-bit save area (revision 0x20000); `halted`: the SMI interrupted
/// HLT (the auto HALT restart field at 0x7F02, next to the I/O instruction
/// restart field at 0x7F00)
unsafe fn save_32(area: SaveArea, halted: bool) {
    area.write32(0x7FFC, *cr as u32);
    area.write32(0x7FF8, *cr.offset(3) as u32);
    area.write32(0x7FF4, get_eflags() as u32);
    area.write32(0x7FF0, get_real_eip() as u32);
    for (index, register) in [EDI, ESI, EBP, ESP, EBX, EDX, ECX, EAX].iter().enumerate() {
        area.write32(
            0x7FEC - index as u32 * 4,
            *reg32.offset(*register as isize) as u32,
        );
    }
    area.write32(0x7FCC, *dreg.offset(6) as u32);
    area.write32(0x7FC8, *dreg.offset(7) as u32);

    area.write32(0x7FC4, *sreg.offset(TR as isize) as u32);
    area.write32(0x7F64, *segment_offsets.offset(TR as isize) as u32);
    area.write32(0x7F60, *segment_limits.offset(TR as isize));
    area.write32(0x7F5C, attributes(TR));
    area.write32(0x7FC0, *sreg.offset(LDTR as isize) as u32);
    area.write32(0x7F80, *segment_offsets.offset(LDTR as isize) as u32);
    area.write32(0x7F7C, *segment_limits.offset(LDTR as isize));
    area.write32(0x7F78, attributes(LDTR));
    area.write32(0x7F74, *gdtr_offset as u32);
    area.write32(0x7F70, *gdtr_size as u32);
    area.write32(0x7F58, *idtr_offset as u32);
    area.write32(0x7F54, *idtr_size as u32);
    for segment in [ES, CS, SS, DS, FS, GS] {
        let (selector, cache) = segment_slots_32(segment);
        area.write32(selector, *sreg.offset(segment as isize) as u32);
        area.write32(cache + 8, *segment_offsets.offset(segment as isize) as u32);
        area.write32(cache + 4, *segment_limits.offset(segment as isize));
        area.write32(cache, attributes(segment));
    }
    area.write32(0x7F14, *cr.offset(4) as u32);
    area.write32(0x7F00, (halted as u32) << 16);
    area.write32(0x7EFC, SMM_REVISION_32);
    area.write32(0x7EF8, *smbase);
}

/// The 64-bit save area (revision 0x20064): ES-GS at 0x7E00 + 16 * n
/// (selector, attributes, limit, base), the descriptor tables and TR, the I/O
/// instruction and auto HALT restart bytes (0x7EC8, 0x7EC9, as AMD64 has
/// them), EFER, RIP, RFLAGS, the debug and control registers, the 16 GPRs
unsafe fn save_64(area: SaveArea, halted: bool) {
    let descriptor = |offset: u32, segment: i32| {
        area.write32(
            offset,
            *sreg.offset(segment as isize) as u32 | attributes(segment) << 16,
        );
        area.write32(offset + 4, *segment_limits.offset(segment as isize));
        area.write64(offset + 8, x64::read_segment_base(segment as usize));
    };
    for segment in [ES, CS, SS, DS, FS, GS] {
        descriptor(0x7E00 + segment as u32 * 16, segment);
    }
    area.write32(0x7E64, *gdtr_size as u32);
    area.write64(0x7E68, x64::read_gdtr_base());
    descriptor(0x7E70, LDTR);
    area.write32(0x7E84, *idtr_size as u32);
    area.write64(0x7E88, x64::read_idtr_base());
    descriptor(0x7E90, TR);
    area.write32(0x7EC8, (halted as u32) << 8);
    area.write64(0x7ED0, x64::efer());

    for register in 0..16 {
        area.write64(0x7FF8 - register as u32 * 8, x64::read_gpr(register));
    }
    area.write64(0x7F78, x64::read_rip());
    area.write32(0x7F70, get_eflags() as u32);
    area.write32(0x7F68, *dreg.offset(6) as u32);
    area.write32(0x7F60, *dreg.offset(7) as u32);
    area.write32(0x7F48, *cr.offset(4) as u32);
    area.write64(0x7F50, x64::read_cr(3));
    area.write32(0x7F58, *cr as u32);

    area.write32(0x7EFC, SMM_REVISION_64);
    area.write32(0x7F00, *smbase);
}

/// An SMI on this core (crate::cpu::apic::take_smi): save the state, run
/// the handler. False if the core is in SMM already (an SMI is not nested)
/// or the save area is not in RAM or enabled high SMRAM (the SMI is dropped).
#[no_mangle]
pub unsafe fn smm_enter() -> bool {
    if smm_active() {
        return false;
    }
    let base = *smbase;
    let Some(area) = save_area(base, true)
    else {
        dbg_log!("SMI: SMBASE {:x} is not in RAM or SMRAM, dropped", base);
        return false;
    };
    dbg_log!("SMI: enter SMM, SMBASE {:x}", base);
    let long = layout_64();
    let halted = *in_hlt;
    if long {
        save_64(area, halted);
    }
    else {
        save_32(area, halted);
    }

    // SMM: NMIs blocked until RSM, interrupts off, real mode with 4 GiB
    // limits, no paging; with the 64-bit map, EFER cleared
    *smm_state = SMM_ACTIVE
        | if *nmi_blocked { SMM_NMI_BLOCKED } else { 0 }
        | if long { SMM_MAP_64 } else { 0 }
        | if halted { SMM_HALTED } else { 0 };
    *nmi_blocked = true;
    if *in_hlt {
        js::stop_idling();
        *in_hlt = false;
    }
    *flags = FLAGS_DEFAULT;
    *flags_changed = 0;
    x64::write_cr_raw(
        0,
        (*cr & !(CR0_PE | CR0_EM | CR0_TS | CR0_PG) | CR0_ET) as u32 as u64,
    );
    x64::write_cr_raw(4, 0);
    if long {
        x64::set_efer_raw(0);
    }
    x64::write_dr(7, 0x400);
    *protected_mode = false;
    *cpl = 0;
    *x64_cs_long = 0;
    // (P, S, writable, accessed)
    load_segment(CS, base >> 4 & 0xFFFF, base as u64, 0xFFFF_FFFF, 0x93);
    for segment in [ES, SS, DS, FS, GS] {
        load_segment(segment, 0, 0, 0xFFFF_FFFF, 0x93);
    }
    *is_32 = false;
    *stack_size_32 = false;
    // The general registers' upper halves are undefined in SMM's 32-bit
    // modes; processors zero-extend 32-bit writes, which v86 leaves to the
    // halves kept apart (x64_gpr_hi). Handlers count on it: OVMF's SMI entry
    // sets ESP in 32-bit code, then pushes in 64-bit mode. The save map has
    // the whole registers for RSM.
    if long {
        for i in 0..16 {
            *x64_gpr_hi.offset(i) = 0;
        }
    }
    x64::write_rip(0x8000);
    x64::write_previous_rip(0x8000);
    entered_mode();
    true
}

/// After SMM entry or RSM: the translations, compiled code admission and
/// cached state of the old mode go
unsafe fn entered_mode() {
    // (cross-modifying code: other cores' code writes are seen from here on)
    crate::parallel::code::poll();
    full_clear_tlb();
    crate::x64::memory::invalidate_core(apic::current_core());
    update_state_flags();
    cpl_changed();
}

/// What RSM restored that the derived state depends on: EIP or RIP, and the
/// attributes of CS and SS (their D/B bits)
struct Restored {
    ip: u64,
    cs: u32,
    ss: u32,
}

/// The 32-bit save area (revision 0x20000)
unsafe fn restore_32(area: SaveArea) -> Restored {
    let new_cr0 = area.read32(0x7FFC) as i32;
    *cr = new_cr0 | CR0_ET;
    // (32 bits, zero-extended)
    x64::write_cr_raw(3, area.read32(0x7FF8) as u64);
    *cr.offset(4) = area.read32(0x7F14) as i32;

    *flags = area.read32(0x7FF4) as i32 & FLAGS_MASK | FLAGS_DEFAULT;
    *flags_changed = 0;
    for (index, register) in [EDI, ESI, EBP, ESP, EBX, EDX, ECX, EAX].iter().enumerate() {
        *reg32.offset(*register as isize) = area.read32(0x7FEC - index as u32 * 4) as i32;
    }
    *dreg.offset(6) = area.read32(0x7FCC) as i32;
    *dreg.offset(7) = area.read32(0x7FC8) as i32;

    load_segment(
        TR,
        area.read16(0x7FC4),
        area.read32(0x7F64) as u64,
        area.read32(0x7F60),
        area.read32(0x7F5C),
    );
    load_segment(
        LDTR,
        area.read16(0x7FC0),
        area.read32(0x7F80) as u64,
        area.read32(0x7F7C),
        area.read32(0x7F78),
    );
    // (32-bit bases, zero-extended)
    x64::write_gdtr_base(area.read32(0x7F74) as u64);
    *gdtr_size = area.read32(0x7F70) as i32;
    x64::write_idtr_base(area.read32(0x7F58) as u64);
    *idtr_size = area.read32(0x7F54) as i32;

    for segment in [ES, CS, SS, DS, FS, GS] {
        let (selector, cache) = segment_slots_32(segment);
        load_segment(
            segment,
            area.read16(selector),
            area.read32(cache + 8) as u64,
            area.read32(cache + 4),
            area.read32(cache),
        );
    }
    if area.read32(0x7EFC) & SMM_REVISION_RELOCATION != 0 {
        *smbase = area.read32(0x7EF8);
    }
    Restored {
        ip: area.read32(0x7FF0) as u64,
        cs: area.read32(segment_slots_32(CS).1),
        ss: area.read32(segment_slots_32(SS).1),
    }
}

/// The 64-bit save area (revision 0x20064). EFER.LMA follows from LME,
/// CR0.PG and CR4.PAE, as when software enables paging.
unsafe fn restore_64(area: SaveArea) -> Restored {
    let mut cr0 = area.read32(0x7F58) as i32 | CR0_ET;
    if cr0 & CR0_PE == 0 {
        // (paging without protection is not a state)
        cr0 &= !CR0_PG;
    }
    let cr4 = area.read32(0x7F48) as i32;
    let efer = area.read64(0x7ED0) & (x64::EFER_SCE | x64::EFER_LME | x64::EFER_NXE);
    let long = efer & x64::EFER_LME != 0 && cr0 & CR0_PG != 0 && cr4 & CR4_PAE != 0;
    x64::set_efer_raw(efer | if long { x64::EFER_LMA } else { 0 });
    x64::write_cr_raw(0, cr0 as u32 as u64);
    x64::write_cr_raw(3, area.read64(0x7F50));
    x64::write_cr_raw(4, cr4 as u32 as u64);

    *flags = area.read32(0x7F70) as i32 & FLAGS_MASK | FLAGS_DEFAULT;
    *flags_changed = 0;
    for register in 0..16 {
        let value = area.read64(0x7FF8 - register as u32 * 8);
        *(x64::gpr_low_offset(register) as *mut u32) = value as u32;
        *(x64::gpr_high_offset(register) as *mut u32) = (value >> 32) as u32;
    }
    x64::write_dr(6, area.read32(0x7F68) as u64);
    x64::write_dr(7, area.read32(0x7F60) as u64);

    let descriptor = |offset: u32, segment: i32| {
        let attributes = area.read16(offset + 2);
        load_segment(
            segment,
            area.read16(offset),
            area.read64(offset + 8),
            area.read32(offset + 4),
            attributes,
        );
        attributes
    };
    descriptor(0x7E90, TR);
    descriptor(0x7E70, LDTR);
    *gdtr_size = area.read32(0x7E64) as i32;
    x64::write_gdtr_base(area.read64(0x7E68));
    *idtr_size = area.read32(0x7E84) as i32;
    x64::write_idtr_base(area.read64(0x7E88));
    let mut attributes = [0; 6];
    for segment in [ES, CS, SS, DS, FS, GS] {
        attributes[segment as usize] = descriptor(0x7E00 + segment as u32 * 16, segment);
    }
    // 64-bit code: CS.L, its base is 0
    *x64_cs_long = (long && attributes[CS as usize] & 1 << 13 != 0) as u8;
    if *x64_cs_long != 0 {
        x64::write_segment_base(CS as usize, 0);
    }
    if area.read32(0x7EFC) & SMM_REVISION_RELOCATION != 0 {
        *smbase = area.read32(0x7F00);
    }
    Restored {
        ip: area.read64(0x7F78),
        cs: attributes[CS as usize],
        ss: attributes[SS as usize],
    }
}

/// RSM: the state from the save area, out of SMM
pub unsafe fn rsm() {
    // (the area the SMI saved to: SMBASE changes only here)
    let area = save_area(*smbase, false).unwrap();
    dbg_log!("RSM: leave SMM, SMBASE {:x}", *smbase);
    let map_64 = *smm_state & SMM_MAP_64 != 0;
    // invalid state in the save area: shutdown (SDM Vol. 3C 32.13 "RSM")
    let cr4 = area.read32(if map_64 { 0x7F48 } else { 0x7F14 });
    if cr4 & !cr4_valid_bits() != 0 {
        dbg_log!("RSM: invalid CR4 {:x}: shutdown", cr4);
        crate::cpu::exceptions::shutdown();
        return;
    }
    // auto HALT restart: back to HLT, if the SMI came there and the handler
    // left the field set
    let halt = *smm_state & SMM_HALTED != 0
        && if map_64 { area.read32(0x7EC8) >> 8 & 1 } else { area.read32(0x7F00) >> 16 & 1 } != 0;
    let restored = if map_64 { restore_64(area) } else { restore_32(area) };

    // derived state: the mode, the sizes of CS and SS, null data segments,
    // the TSS type, CPL (CS.RPL)
    *protected_mode = *cr & CR0_PE != 0;
    let vm86 = *flags & FLAG_VM != 0;
    let protected = *protected_mode && !vm86;
    *is_32 = protected && *x64_cs_long == 0 && restored.cs & 1 << 14 != 0;
    *stack_size_32 = protected && restored.ss & 1 << 14 != 0;
    for segment in [ES, DS, FS, GS] {
        *segment_is_null.offset(segment as isize) =
            protected && *sreg.offset(segment as isize) & !3 == 0;
    }
    *segment_is_null.offset(LDTR as isize) = *sreg.offset(LDTR as isize) & !3 == 0;
    let tss_type = *segment_access_bytes.offset(TR as isize) & 0xF;
    *tss_size_32 = tss_type == 0x9 || tss_type == 0xB;
    *cpl = if vm86 {
        3
    }
    else if *protected_mode {
        (*sreg.offset(CS as isize) & 3) as u8
    }
    else {
        0
    };

    *nmi_blocked = *smm_state & SMM_NMI_BLOCKED != 0;
    *smm_state = 0;
    x64::write_rip(restored.ip);
    x64::write_previous_rip(restored.ip);
    entered_mode();
    if x64::efer() & x64::EFER_LMA == 0 && *cr.offset(4) & CR4_PAE != 0 && *cr & CR0_PG != 0 {
        load_pdpte(*cr.offset(3) & !0b1111);
    }
    if halt {
        *in_hlt = true;
        crate::cpu::execution::note_halt();
        request_core_yield();
    }
    // an SMI or NMI that waited for RSM: taken at the start of the next slice
    if apic::smi_pending() || apic::nmi_pending() && !*nmi_blocked {
        request_core_yield();
    }
}

/// At reset: SMBASE back to its default, not in SMM (INIT keeps SMBASE)
pub unsafe fn reset() {
    *smm_state = 0;
    *smbase = SMBASE_DEFAULT;
}
                                                                                                                                                                                                                                                                                             source/v64/src/rust/cpu/sse_instr.rs                                                                0000644 0000000 0000000 00000043753 00000000000 014632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::cpu::cpu::*;
use crate::cpu::global_pointers::{flags, flags_changed, mxcsr};
use crate::cpu::simd_fp;

pub unsafe fn mov_r_m64(addr: i32, r: i32) {
    // mov* m64, mm
    let data = read_mmx64s(r);
    return_on_pagefault!(safe_write64(addr, data));
    transition_fpu_to_mmx();
}
pub unsafe fn movl_r128_m64(addr: i32, r: i32) {
    // mov* m64, xmm
    let data = read_xmm64s(r);
    return_on_pagefault!(safe_write64(addr, data));
}
pub unsafe fn mov_r_r128(r1: i32, r2: i32) {
    // mov* xmm, xmm
    let data = read_xmm128s(r2);
    write_xmm_reg128(r1, data);
}
pub unsafe fn mov_r_m128(addr: i32, r: i32) {
    // mov* m128, xmm
    let data = read_xmm128s(r);
    return_on_pagefault!(safe_write128(addr, data));
}
/// MOVAPS/MOVAPD/MOVDQA/MOVNT* m128, xmm: #GP(0) unless 16-byte aligned
pub unsafe fn mov_r_m128_aligned(addr: i32, r: i32) {
    return_on_pagefault!(aligned16(addr));
    mov_r_m128(addr, r);
}
pub unsafe fn mov_rm_r128(source: reg128, r: i32) {
    // mov* xmm, xmm/m128
    write_xmm_reg128(r, source);
}
pub unsafe fn movh_r128_m64(addr: i32, r: i32) {
    // movhp* m64, xmm
    let data = read_xmm128s(r);
    return_on_pagefault!(safe_write64(addr, data.u64[1]));
}

pub unsafe fn pand_r128(source: reg128, r: i32) {
    // pand xmm, xmm/m128
    // XXX: Aligned access or #gp
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = source.u64[0] & destination.u64[0];
    result.u64[1] = source.u64[1] & destination.u64[1];
    write_xmm_reg128(r, result);
}
pub unsafe fn pandn_r128(source: reg128, r: i32) {
    // pandn xmm, xmm/m128
    // XXX: Aligned access or #gp
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = source.u64[0] & !destination.u64[0];
    result.u64[1] = source.u64[1] & !destination.u64[1];
    write_xmm_reg128(r, result);
}
pub unsafe fn pxor_r128(source: reg128, r: i32) {
    // pxor xmm, xmm/m128
    // XXX: Aligned access or #gp
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = source.u64[0] ^ destination.u64[0];
    result.u64[1] = source.u64[1] ^ destination.u64[1];
    write_xmm_reg128(r, result);
}
pub unsafe fn por_r128(source: reg128, r: i32) {
    // por xmm, xmm/m128
    // XXX: Aligned access or #gp
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    result.u64[0] = source.u64[0] | destination.u64[0];
    result.u64[1] = source.u64[1] | destination.u64[1];
    write_xmm_reg128(r, result);
}

pub unsafe fn psrlw_r64(r: i32, shift: u64) {
    // psrlw mm, {shift}
    let destination: [u16; 4] = std::mem::transmute(read_mmx64s(r));
    let shift = if shift > 15 { 16 } else { shift };
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = ((destination[i] as u32) >> shift) as u16
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn psraw_r64(r: i32, shift: u64) {
    // psraw mm, {shift}
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let shift = if shift > 15 { 16 } else { shift };
    let mut result = [0; 4];
    for i in 0..4 {
        result[i] = (destination[i] as i32 >> shift) as i16
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn psllw_r64(r: i32, shift: u64) {
    // psllw mm, {shift}
    let destination: [i16; 4] = std::mem::transmute(read_mmx64s(r));
    let mut result = [0; 4];
    if shift <= 15 {
        for i in 0..4 {
            result[i] = destination[i] << shift
        }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn psrld_r64(r: i32, shift: u64) {
    // psrld mm, {shift}
    let destination: [u32; 2] = std::mem::transmute(read_mmx64s(r));
    let mut result = [0; 2];
    if shift <= 31 {
        for i in 0..2 {
            result[i] = destination[i] >> shift;
        }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn psrad_r64(r: i32, shift: u64) {
    // psrad mm, {shift}
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let shift = if shift > 31 { 31 } else { shift };
    let mut result = [0; 2];
    for i in 0..2 {
        result[i] = destination[i] >> shift;
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn pslld_r64(r: i32, shift: u64) {
    // pslld mm, {shift}
    let destination: [i32; 2] = std::mem::transmute(read_mmx64s(r));
    let mut result = [0; 2];
    if shift <= 31 {
        for i in 0..2 {
            result[i] = destination[i] << shift;
        }
    }
    write_mmx_reg64(r, std::mem::transmute(result));
    transition_fpu_to_mmx();
}
pub unsafe fn psrlq_r64(r: i32, shift: u64) {
    // psrlq mm, {shift}
    let destination = read_mmx64s(r);
    let mut result = 0;
    if shift <= 63 {
        result = destination >> shift
    }
    write_mmx_reg64(r, result);
    transition_fpu_to_mmx();
}
pub unsafe fn psllq_r64(r: i32, shift: u64) {
    // psllq mm, {shift}
    let destination = read_mmx64s(r);
    let mut result = 0;
    if shift <= 63 {
        result = destination << shift
    }
    write_mmx_reg64(r, result);
    transition_fpu_to_mmx();
}
pub unsafe fn psrlw_r128(r: i32, shift: u64) {
    // psrlw xmm, {shift}
    let destination = read_xmm128s(r);
    let mut dword0 = 0;
    let mut dword1 = 0;
    let mut dword2 = 0;
    let mut dword3 = 0;
    if shift <= 15 {
        dword0 = destination.u16[0] as i32 >> shift | destination.u16[1] as i32 >> shift << 16;
        dword1 = destination.u16[2] as i32 >> shift | destination.u16[3] as i32 >> shift << 16;
        dword2 = destination.u16[4] as i32 >> shift | destination.u16[5] as i32 >> shift << 16;
        dword3 = destination.u16[6] as i32 >> shift | destination.u16[7] as i32 >> shift << 16
    }
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn psraw_r128(r: i32, shift: u64) {
    // psraw xmm, {shift}
    let destination = read_xmm128s(r);
    let shift_clamped = (if shift > 15 { 16 } else { shift as u32 }) as i32;
    let dword0 = destination.i16[0] as i32 >> shift_clamped & 0xFFFF
        | destination.i16[1] as i32 >> shift_clamped << 16;
    let dword1 = destination.i16[2] as i32 >> shift_clamped & 0xFFFF
        | destination.i16[3] as i32 >> shift_clamped << 16;
    let dword2 = destination.i16[4] as i32 >> shift_clamped & 0xFFFF
        | destination.i16[5] as i32 >> shift_clamped << 16;
    let dword3 = destination.i16[6] as i32 >> shift_clamped & 0xFFFF
        | destination.i16[7] as i32 >> shift_clamped << 16;
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn psllw_r128(r: i32, shift: u64) {
    // psllw xmm, {shift}
    let destination = read_xmm128s(r);
    let mut dword0 = 0;
    let mut dword1 = 0;
    let mut dword2 = 0;
    let mut dword3 = 0;
    if shift <= 15 {
        dword0 = (destination.u16[0] as i32) << shift & 0xFFFF
            | (destination.u16[1] as i32) << shift << 16;
        dword1 = (destination.u16[2] as i32) << shift & 0xFFFF
            | (destination.u16[3] as i32) << shift << 16;
        dword2 = (destination.u16[4] as i32) << shift & 0xFFFF
            | (destination.u16[5] as i32) << shift << 16;
        dword3 = (destination.u16[6] as i32) << shift & 0xFFFF
            | (destination.u16[7] as i32) << shift << 16
    }
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn psrld_r128(r: i32, shift: u64) {
    // psrld xmm, {shift}
    let destination = read_xmm128s(r);
    let mut dword0 = 0;
    let mut dword1 = 0;
    let mut dword2 = 0;
    let mut dword3 = 0;
    if shift <= 31 {
        dword0 = (destination.u32[0] >> shift) as i32;
        dword1 = (destination.u32[1] >> shift) as i32;
        dword2 = (destination.u32[2] >> shift) as i32;
        dword3 = (destination.u32[3] >> shift) as i32
    }
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn psrad_r128(r: i32, shift: u64) {
    // psrad xmm, {shift}
    let destination = read_xmm128s(r);
    let shift_clamped = (if shift > 31 { 31 } else { shift }) as i32;
    let dword0 = destination.i32[0] >> shift_clamped;
    let dword1 = destination.i32[1] >> shift_clamped;
    let dword2 = destination.i32[2] >> shift_clamped;
    let dword3 = destination.i32[3] >> shift_clamped;
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn pslld_r128(r: i32, shift: u64) {
    // pslld xmm, {shift}
    let destination = read_xmm128s(r);
    let mut dword0 = 0;
    let mut dword1 = 0;
    let mut dword2 = 0;
    let mut dword3 = 0;
    if shift <= 31 {
        dword0 = destination.i32[0] << shift;
        dword1 = destination.i32[1] << shift;
        dword2 = destination.i32[2] << shift;
        dword3 = destination.i32[3] << shift
    }
    write_xmm128(r, dword0, dword1, dword2, dword3);
}
pub unsafe fn psrlq_r128(r: i32, shift: u64) {
    // psrlq xmm, {shift}
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    if shift <= 63 {
        result.u64[0] = destination.u64[0] >> shift;
        result.u64[1] = destination.u64[1] >> shift
    }
    write_xmm_reg128(r, result);
}
pub unsafe fn psllq_r128(r: i32, shift: u64) {
    // psllq xmm, {shift}
    let destination = read_xmm128s(r);
    let mut result = reg128 { i8: [0; 16] };
    if shift <= 63 {
        result.u64[0] = destination.u64[0] << shift;
        result.u64[1] = destination.u64[1] << shift
    }
    write_xmm_reg128(r, result);
}

pub unsafe fn sse_comparison(op: i32, x: f64, y: f64) -> bool {
    // TODO: Signaling
    match op & 7 {
        0 => return x == y,
        1 => return x < y,
        2 => return x <= y,
        3 => return x.is_nan() || y.is_nan(),
        4 => return x != y || x.is_nan() || y.is_nan(),
        5 => return x >= y || x.is_nan() || y.is_nan(),
        6 => return x > y || x.is_nan() || y.is_nan(),
        7 => return !x.is_nan() && !y.is_nan(),
        _ => {
            dbg_assert!(false);
            return false;
        },
    };
}
pub unsafe fn sse_min(x: f64, y: f64) -> f64 {
    // if both x and y are 0 or x is nan, y is returned
    return if x < y { x } else { y };
}
pub unsafe fn sse_max(x: f64, y: f64) -> f64 {
    // if both x and y are 0 or x is nan, y is returned
    return if x > y { x } else { y };
}

#[no_mangle]
pub unsafe fn sse_convert_with_truncation_f32_to_i32(x: f32) -> i32 {
    let x = x.trunc();
    if x >= -2147483648.0 && x < 2147483648.0 {
        return x as i64 as i32;
    }
    else {
        // TODO: Signal
        return -0x80000000;
    };
}
// NaN results of SSE arithmetic as x86 produces them, whatever the host's
// rules (Wasm leaves NaN sign and payload to the host: arm64 gives its default
// NaN 0x7FC00000): the first source operand if it is a NaN, else the second,
// quieted; the QNaN floating-point indefinite for an invalid operation
// (Intel SDM Vol. 1, 4.8.3.5 and Table 4-7).
#[inline]
pub fn sse_nan_f32(result: f32, first: f32, second: f32) -> f32 {
    if !result.is_nan() {
        result
    }
    else if first.is_nan() {
        f32::from_bits(first.to_bits() | 0x40_0000)
    }
    else if second.is_nan() {
        f32::from_bits(second.to_bits() | 0x40_0000)
    }
    else {
        f32::from_bits(0xFFC0_0000)
    }
}
#[inline]
pub fn sse_nan_f64(result: f64, first: f64, second: f64) -> f64 {
    if !result.is_nan() {
        result
    }
    else if first.is_nan() {
        f64::from_bits(first.to_bits() | 0x8_0000_0000_0000)
    }
    else if second.is_nan() {
        f64::from_bits(second.to_bits() | 0x8_0000_0000_0000)
    }
    else {
        f64::from_bits(0xFFF8_0000_0000_0000)
    }
}
/// `op` on each lane of `destination` and `source`, with x86 NaN results
#[inline]
pub unsafe fn sse_ps(destination: reg128, source: reg128, op: impl Fn(f32, f32) -> f32) -> reg128 {
    let (a, b) = (destination.f32, source.f32);
    reg128 {
        f32: [0, 1, 2, 3].map(|i| sse_nan_f32(op(a[i], b[i]), a[i], b[i])),
    }
}
#[inline]
pub unsafe fn sse_pd(destination: reg128, source: reg128, op: impl Fn(f64, f64) -> f64) -> reg128 {
    let (a, b) = (destination.f64, source.f64);
    reg128 {
        f64: [0, 1].map(|i| sse_nan_f64(op(a[i], b[i]), a[i], b[i])),
    }
}
#[inline]
pub fn sse_sqrt_f32(x: f32) -> f32 { sse_nan_f32(x.sqrt(), x, x) }
#[inline]
pub fn sse_sqrt_f64(x: f64) -> f64 { sse_nan_f64(x.sqrt(), x, x) }

#[no_mangle]
pub unsafe fn sse_convert_f32_to_i32(x: f32) -> i32 {
    let x = sse_integer_round(x as f64);
    if x >= -2147483648.0 && x < 2147483648.0 {
        return x as i64 as i32;
    }
    else {
        // TODO: Signal
        return -0x80000000;
    };
}

#[no_mangle]
pub unsafe fn sse_convert_with_truncation_f64_to_i32(x: f64) -> i32 {
    let x = x.trunc();
    if x >= -2147483648.0 && x < 2147483648.0 {
        return x as i64 as i32;
    }
    else {
        // TODO: Signal
        return -0x80000000;
    };
}
#[no_mangle]
pub unsafe fn sse_convert_f64_to_i32(x: f64) -> i32 {
    let x = sse_integer_round(x);
    if x >= -2147483648.0 && x < 2147483648.0 {
        return x as i64 as i32;
    }
    else {
        // TODO: Signal
        return -0x80000000;
    };
}

pub unsafe fn sse_integer_round(f: f64) -> f64 {
    // see fpu_integer_round
    let rc = *mxcsr >> MXCSR_RC_SHIFT & 3;
    if rc == 0 {
        // Round to nearest, or even if equidistant
        let mut rounded = f.round();
        let diff = rounded - f;
        if diff == 0.5 || diff == -0.5 {
            rounded = 2.0 * (f * 0.5).round()
        }
        return rounded;
    }
    else if rc == 1 || rc == 3 && f > 0.0 {
        // rc=3 is truncate -> floor for positive numbers
        return f.floor();
    }
    else {
        return f.ceil();
    };
}

/// SQRT/ADD/MUL/SUB/MIN/DIV/MAX, CMP, HADD/HSUB and ADDSUB (simd_fp::arithmetic,
/// `op` the catalogue key) of XMM r and `source` into XMM r: false after an
/// unmasked exception (XMM r unchanged)
pub unsafe fn sse_fp_arithmetic(op: u32, r: i32, source: u128, imm8: i32) -> bool {
    match simd_fp::arithmetic(op, read_xmm128s(r).bits(), source, imm8 as u8) {
        Ok(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        Err(simd_fp::Unmasked) => {
            trigger_simd_fp();
            false
        },
    }
}
/// ROUNDPS/PD/SS/SD (simd_fp::round, `op` the catalogue key) of `source`
/// into XMM r: false after an unmasked exception (XMM r unchanged)
pub unsafe fn sse_fp_round(op: u32, r: i32, source: u128, imm8: i32) -> bool {
    match simd_fp::round(op, read_xmm128s(r).bits(), source, imm8 as u8) {
        Ok(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        Err(simd_fp::Unmasked) => {
            trigger_simd_fp();
            false
        },
    }
}
/// DPPS/DPPD (simd_fp::dot_product) of XMM r and `source`: false after an
/// unmasked exception (XMM r unchanged)
pub unsafe fn sse_fp_dot_product(double: bool, r: i32, source: u128, imm8: i32) -> bool {
    match simd_fp::dot_product(double, read_xmm128s(r).bits(), source, imm8 as u8) {
        Ok(v) => {
            write_xmm_reg128(r, reg128::of_bits(v));
            true
        },
        Err(simd_fp::Unmasked) => {
            trigger_simd_fp();
            false
        },
    }
}
/// COMISS/UCOMISS/COMISD/UCOMISD of XMM r and `source`: ZF, PF and CF (the
/// other arithmetic flags cleared), or false after an unmasked exception
pub unsafe fn sse_fp_compare_flags(op: u32, r: i32, source: u128) -> bool {
    match simd_fp::compare_flags(op, read_xmm128s(r).bits(), source) {
        Ok(result) => {
            *flags_changed = 0;
            *flags = *flags & !FLAGS_ALL | result as i32;
            true
        },
        Err(simd_fp::Unmasked) => {
            trigger_simd_fp();
            false
        },
    }
}
/// RCPPS/RCPSS/RSQRTPS/RSQRTSS of `source` into XMM r (no exceptions)
pub unsafe fn sse_fp_reciprocal(op: u32, r: i32, source: u128) -> bool {
    write_xmm_reg128(
        r,
        reg128::of_bits(simd_fp::reciprocal(op, read_xmm128s(r).bits(), source)),
    );
    true
}
/// A conversion (simd_fp::convert) of `source` for XMM r (the destination
/// that XMM results merge into): the result, or None after an unmasked
/// exception
pub unsafe fn sse_fp_convert(op: u32, r: i32, source: u128) -> Option<u128> {
    match simd_fp::convert(op, false, read_xmm128s(r).bits(), source) {
        Ok(v) => Some(v),
        Err(simd_fp::Unmasked) => {
            trigger_simd_fp();
            None
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sse_nan_results_follow_x86() {
        let (qnan, snan) = (f32::from_bits(0x7FC0_1234), f32::from_bits(0xFF80_0001));
        // an invalid operation gives the QNaN floating-point indefinite
        assert_eq!(
            sse_nan_f32(f32::INFINITY - f32::INFINITY, 1.0, 2.0).to_bits(),
            0xFFC0_0000
        );
        assert_eq!(sse_sqrt_f32(-4.0).to_bits(), 0xFFC0_0000);
        assert_eq!(sse_sqrt_f64(-4.0).to_bits(), 0xFFF8_0000_0000_0000);
        assert_eq!(sse_sqrt_f32(-0.0).to_bits(), 0x8000_0000);
        // the first NaN operand, quieted
        assert_eq!(sse_nan_f32(qnan + snan, qnan, snan).to_bits(), 0x7FC0_1234);
        assert_eq!(sse_nan_f32(snan + qnan, snan, qnan).to_bits(), 0xFFC0_0001);
        assert_eq!(sse_nan_f32(1.0 + qnan, 1.0, qnan).to_bits(), 0x7FC0_1234);
        assert_eq!(sse_sqrt_f32(snan).to_bits(), 0xFFC0_0001);
        assert_eq!(
            sse_nan_f64(f64::NAN, 1.0, f64::from_bits(0x7FF0_0000_0000_0005)).to_bits(),
            0x7FF8_0000_0000_0005
        );
        // ordinary results are untouched
        assert_eq!(sse_nan_f32(1.5 + 2.0, 1.5, 2.0), 3.5);
        let (a, b) = (
            reg128 {
                f32: [1.0, -1.0, f32::INFINITY, 0.0],
            },
            reg128 {
                f32: [2.0, 0.0, f32::NEG_INFINITY, 0.0],
            },
        );
        let sum = unsafe { sse_ps(a, b, |x, y| x + y).u32 };
        assert_eq!(sum, [3.0f32.to_bits(), (-1.0f32).to_bits(), 0xFFC0_0000, 0]);
        let quotient = unsafe { sse_ps(a, b, |x, y| x / y).u32 };
        assert_eq!(quotient[3], 0xFFC0_0000); // 0 / 0
    }
}
                     source/v64/src/rust/cpu/string.rs                                                                   0000644 0000000 0000000 00000100437 00000000000 014120  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // string operations
//
//       cmp  si  di
// movs   0    1   1/w    A4
// cmps   1    1   1/r    A6
// stos   0    0   1/w    AA
// lods   0    1   0      AC
// scas   1    0   1/r    AE
// ins    0    0   1/w
// outs   0    1   0

use crate::cpu::arith::{cmp16, cmp32, cmp8};
use crate::cpu::cpu::{
    get_seg, io_port_read16, io_port_read32, io_port_read8, io_port_write16, io_port_write32,
    io_port_write8, read_reg16, read_reg32, safe_read16, safe_read32s, safe_read8, safe_write16,
    safe_write32, safe_write8, set_reg_asize, test_privileges_for_io, translate_address_read,
    translate_address_write_and_can_skip_dirty, writable_or_pagefault, write_reg16, write_reg32,
    write_reg8, AL, AX, DX, EAX, ECX, EDI, ES, ESI, FLAG_DIRECTION,
};
use crate::cpu::global_pointers::{flags, instruction_pointer, previous_ip};
use crate::cpu::memory;
use crate::jit;
use crate::page::Page;

// In-place ADD/XOR array loops. The final address ADD and counter DEC define
// the architectural flags, so intermediate element flags need not be stored.

fn count_until_end_of_page(direction: i32, size: i32, addr: u32) -> u32 {
    (if direction == 1 {
        (0x1000 - (addr & 0xFFF)) / size as u32
    }
    else {
        (addr & 0xFFF) / size as u32 + 1
    }) as u32
}

#[derive(Copy, Clone, PartialEq)]
enum Instruction {
    Movs,
    Lods,
    Stos,
    Scas,
    Cmps,
    Ins,
    Outs,
}
#[derive(PartialEq)]
enum Size {
    B,
    W,
    D,
}
#[derive(Copy, Clone)]
enum Rep {
    None,
    Z,
    NZ,
}

// Single-core interpreter callers retain their original page-bounded policy.
#[inline(always)]
unsafe fn string_instruction(
    is_asize_32: bool,
    ds_or_prefix: i32,
    instruction: Instruction,
    size: Size,
    rep: Rep,
) {
    let multicore = crate::cpu::apic::core_count() > 1;
    let limit = if multicore { 256 } else { u32::MAX };
    let result =
        string_instruction_bounded(is_asize_32, ds_or_prefix, instruction, size, rep, limit);
    if !matches!(rep, Rep::None) {
        crate::cpu::execution::record_string(result);
    }
    if multicore && result.outcome == StringOutcome::Repeat {
        crate::cpu::cpu::yield_to_other_cores();
    }
}

/// Explicit progress from one semantic batch, independent of the resulting EIP.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StringOutcome {
    Complete,
    Repeat,
    Fault,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StringExecution {
    pub outcome: StringOutcome,
    pub iterations: u32,
}
impl StringExecution {
    fn new(outcome: StringOutcome, iterations: u32) -> Self {
        Self {
            outcome,
            iterations,
        }
    }
}

// We implement all string instructions here and rely on the inliner on doing its job of optimising
// away anything known at compile time (check with `wasm-dis build/v86.wasm`)
#[inline(always)]
unsafe fn string_instruction_bounded(
    is_asize_32: bool,
    ds_or_prefix: i32,
    instruction: Instruction,
    size: Size,
    rep: Rep,
    limit: u32,
) -> StringExecution {
    let mut iterations = 0;
    let mut fault = false;
    let mut repeat = false;
    macro_rules! finish_on_fault {
        ($value:expr) => {
            return_on_pagefault!($value, StringExecution::new(StringOutcome::Fault, 0))
        };
    }
    macro_rules! break_with_fault {
        ($value:expr) => {
            break_on_pagefault!({
                let result = $value;
                if result.is_err() {
                    fault = true;
                }
                result
            })
        };
    }
    let asize_mask = if is_asize_32 { -1 } else { 0xFFFF };

    let direction = if 0 != *flags & FLAG_DIRECTION { -1 } else { 1 };

    let mut count = match rep {
        Rep::Z | Rep::NZ => {
            let c = (read_reg32(ECX) & asize_mask) as u32;
            if c == 0 {
                return StringExecution::new(StringOutcome::Complete, 0);
            };
            c
        },
        Rep::None => 0,
    };

    if limit == 0 {
        *instruction_pointer = *previous_ip;
        return StringExecution::new(StringOutcome::Repeat, 0);
    }

    let es = match instruction {
        Instruction::Movs
        | Instruction::Cmps
        | Instruction::Stos
        | Instruction::Scas
        | Instruction::Ins => finish_on_fault!(get_seg(ES)),
        _ => 0,
    };
    let ds = match instruction {
        Instruction::Movs
        | Instruction::Cmps
        | Instruction::Lods
        | Instruction::Scas
        | Instruction::Outs => finish_on_fault!(get_seg(ds_or_prefix)),
        _ => 0,
    };

    let size_bytes = match size {
        Size::B => 1,
        Size::W => 2,
        Size::D => 4,
    };
    let size_mask = match size {
        Size::B => 0xFF,
        Size::W => 0xFFFF,
        Size::D => -1,
    };

    let increment = direction * size_bytes;

    let data = match instruction {
        Instruction::Stos | Instruction::Scas => read_reg32(EAX),
        _ => 0,
    };

    let mut src = match instruction {
        Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
            read_reg32(ESI) & asize_mask
        },
        _ => 0,
    };
    let mut dst = match instruction {
        Instruction::Movs
        | Instruction::Cmps
        | Instruction::Stos
        | Instruction::Scas
        | Instruction::Ins => read_reg32(EDI) & asize_mask,
        _ => 0,
    };

    let port = match instruction {
        Instruction::Ins | Instruction::Outs => {
            let port = read_reg16(DX);
            if !test_privileges_for_io(port, size_bytes) {
                return StringExecution::new(StringOutcome::Fault, 0);
            }
            port
        },
        _ => 0,
    };

    let is_aligned = (ds + src) & (size_bytes - 1) == 0 && (es + dst) & (size_bytes - 1) == 0;

    // unaligned movs is properly handled in the fast path
    let mut rep_fast = (instruction == Instruction::Movs || is_aligned)
        && crate::x64::state::efer() & crate::x64::state::EFER_LMA == 0
        && is_asize_32 // 16-bit address wraparound
        && match rep {
            Rep::NZ | Rep::Z => true,
            Rep::None => false,
        };

    let mut phys_dst = 0;
    let mut phys_src = 0;
    let mut skip_dirty_page = false;

    let mut movs_into_mmio_ram = false;
    let mut movs_reenter_fast_path = false;
    let mut movs_overlap = false;

    let count_until_end_of_page = if rep_fast {
        match instruction {
            Instruction::Movs => {
                let (addr, skip) =
                    finish_on_fault!(translate_address_write_and_can_skip_dirty(es + dst));
                movs_into_mmio_ram = crate::cpu::mmio_ram::contains_writable(addr);
                rep_fast = rep_fast && (!memory::in_mapped_range(addr) || movs_into_mmio_ram);
                phys_dst = addr;
                skip_dirty_page = skip;
            },
            Instruction::Stos | Instruction::Ins => {
                let (addr, skip) =
                    finish_on_fault!(translate_address_write_and_can_skip_dirty(es + dst));
                rep_fast = rep_fast && !memory::in_mapped_range(addr);
                phys_dst = addr;
                skip_dirty_page = skip;
            },
            Instruction::Cmps | Instruction::Scas => {
                let addr = finish_on_fault!(translate_address_read(es + dst));
                rep_fast = rep_fast && !memory::in_mapped_range(addr);
                phys_dst = addr;
                skip_dirty_page = true;
            },
            _ => {},
        };

        match instruction {
            Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
                let addr = finish_on_fault!(translate_address_read(ds + src));
                rep_fast = rep_fast && !memory::in_mapped_range(addr);
                phys_src = addr;
            },
            _ => {},
        };

        let count_until_end_of_page = u32::min(
            count.min(limit),
            match instruction {
                Instruction::Movs | Instruction::Cmps => u32::min(
                    count_until_end_of_page(direction, size_bytes, phys_src),
                    count_until_end_of_page(direction, size_bytes, phys_dst),
                ),
                Instruction::Stos | Instruction::Ins | Instruction::Scas => {
                    count_until_end_of_page(direction, size_bytes, phys_dst)
                },
                Instruction::Lods | Instruction::Outs => {
                    count_until_end_of_page(direction, size_bytes, phys_src)
                },
            },
        );

        match instruction {
            Instruction::Movs => {
                let c = count_until_end_of_page * size_bytes as u32;

                let overlap_interferes = if phys_src < phys_dst {
                    // backward moves may overlap at the front of the destination string
                    phys_dst - phys_src < c && direction == 1
                }
                else if phys_src > phys_dst {
                    // forward moves may overlap at the front of the source string
                    phys_src - phys_dst < c && direction == -1
                }
                else {
                    false
                };
                // LZ backreferences must observe earlier stores. Ordinary RAM
                // can still use the page-bounded translation once, followed by
                // ordered element copies. SVGA retains its original path.
                movs_overlap = overlap_interferes && !movs_into_mmio_ram;
                rep_fast = rep_fast && (!overlap_interferes || movs_overlap);

                // In case the following page-boundary check fails, re-enter instruction after
                // one iteration of the slow path
                movs_reenter_fast_path = rep_fast;
                rep_fast = rep_fast
                    && (phys_src & 0xFFF <= 0x1000 - size_bytes as u32)
                    && (phys_dst & 0xFFF <= 0x1000 - size_bytes as u32);
            },
            _ => {},
        }

        count_until_end_of_page
    }
    else {
        0 // not used
    };

    if rep_fast {
        dbg_assert!(count_until_end_of_page > 0);

        if !skip_dirty_page {
            jit::jit_dirty_page(Page::page_of(phys_dst));
        }

        let mut rep_cmp_finished = false;

        let mut i = 0;
        while i < count_until_end_of_page {
            i += 1;

            let src_val = match instruction {
                Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
                    match size {
                        Size::B => memory::read8_no_mmap_check(phys_src),
                        Size::W => memory::read16_no_mmap_check(phys_src),
                        Size::D => memory::read32_no_mmap_check(phys_src),
                    }
                },
                Instruction::Scas | Instruction::Stos => data & size_mask,
                Instruction::Ins => match size {
                    Size::B => io_port_read8(port),
                    Size::W => io_port_read16(port),
                    Size::D => io_port_read32(port),
                },
            };

            let mut dst_val = 0;

            match instruction {
                Instruction::Cmps | Instruction::Scas => match size {
                    Size::B => dst_val = memory::read8_no_mmap_check(phys_dst),
                    Size::W => dst_val = memory::read16_no_mmap_check(phys_dst),
                    Size::D => dst_val = memory::read32_no_mmap_check(phys_dst),
                },
                Instruction::Outs => match size {
                    Size::B => io_port_write8(port, src_val),
                    Size::W => io_port_write16(port, src_val),
                    Size::D => io_port_write32(port, src_val),
                },
                Instruction::Lods => match size {
                    Size::B => write_reg8(AL, src_val),
                    Size::W => write_reg16(AX, src_val),
                    Size::D => write_reg32(EAX, src_val),
                },
                Instruction::Ins => match size {
                    Size::B => memory::write8_no_mmap_or_dirty_check(phys_dst, src_val),
                    Size::W => memory::write16_no_mmap_or_dirty_check(phys_dst, src_val),
                    Size::D => memory::write32_no_mmap_or_dirty_check(phys_dst, src_val),
                },
                Instruction::Movs => {
                    if movs_overlap {
                        for element in 0..count_until_end_of_page {
                            let offset = element.wrapping_mul(increment as u32);
                            let from = phys_src.wrapping_add(offset);
                            let to = phys_dst.wrapping_add(offset);
                            // Do not turn this into memmove: each element can
                            // depend on the one written immediately before it.
                            match size {
                                Size::B => memory::write8_no_mmap_or_dirty_check(
                                    to,
                                    memory::read8_no_mmap_check(from),
                                ),
                                Size::W => memory::write16_no_mmap_or_dirty_check(
                                    to,
                                    memory::read16_no_mmap_check(from),
                                ),
                                Size::D => memory::write32_no_mmap_or_dirty_check(
                                    to,
                                    memory::read32_no_mmap_check(from),
                                ),
                            }
                        }
                        i = count_until_end_of_page;
                        break;
                    }
                    if direction == -1 {
                        phys_src -= (count_until_end_of_page - 1) * size_bytes as u32;
                        phys_dst -= (count_until_end_of_page - 1) * size_bytes as u32;
                    }
                    if movs_into_mmio_ram {
                        memory::memcpy_into_mmio_ram(
                            phys_src,
                            phys_dst,
                            count_until_end_of_page * size_bytes as u32,
                        );
                    }
                    else {
                        memory::memcpy_no_mmap_or_dirty_check(
                            phys_src,
                            phys_dst,
                            count_until_end_of_page * size_bytes as u32,
                        );
                    }
                    i = count_until_end_of_page;
                    break;
                },
                Instruction::Stos => match size {
                    Size::B => {
                        if direction == -1 {
                            phys_dst -= count_until_end_of_page - 1
                        }
                        memory::memset_no_mmap_or_dirty_check(
                            phys_dst,
                            src_val as u8,
                            count_until_end_of_page,
                        );
                        i = count_until_end_of_page;
                        break;
                    },
                    Size::W | Size::D => {
                        if direction == -1 {
                            phys_dst -= (count_until_end_of_page - 1) * size_bytes as u32;
                        }
                        memory::memset_pattern_no_mmap_or_dirty_check(
                            phys_dst,
                            src_val as u32,
                            size_bytes as u32,
                            count_until_end_of_page,
                        );
                        i = count_until_end_of_page;
                        break;
                    },
                },
            };

            match instruction {
                Instruction::Movs
                | Instruction::Cmps
                | Instruction::Stos
                | Instruction::Scas
                | Instruction::Ins => {
                    phys_dst += increment as u32;
                },
                _ => {},
            }
            match instruction {
                Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
                    phys_src += increment as u32;
                },
                _ => {},
            };

            match instruction {
                Instruction::Scas | Instruction::Cmps => {
                    let rep_cmp = match rep {
                        Rep::Z => src_val == dst_val,
                        Rep::NZ => src_val != dst_val,
                        Rep::None => {
                            dbg_assert!(false);
                            true
                        },
                    };
                    if !rep_cmp || count == i {
                        match size {
                            Size::B => cmp8(src_val, dst_val),
                            Size::W => cmp16(src_val, dst_val),
                            Size::D => cmp32(src_val, dst_val),
                        };
                        rep_cmp_finished = true;
                        break;
                    }
                },
                _ => {},
            }
        }

        dbg_assert!(i <= count);
        count -= i;
        iterations = i;

        if !rep_cmp_finished && count != 0 {
            // go back to the current instruction, since this loop just handles a single page
            *instruction_pointer = *previous_ip;
            repeat = true;
        }

        src += i as i32 * increment;
        dst += i as i32 * increment;
    }
    else {
        loop {
            match instruction {
                Instruction::Ins => {
                    // check fault *before* reading from port
                    // (technically not necessary according to Intel manuals)
                    break_with_fault!(writable_or_pagefault(es + dst, size_bytes));
                },
                _ => {},
            };
            let src_val = match instruction {
                Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
                    break_with_fault!(match size {
                        Size::B => safe_read8(ds + src),
                        Size::W => safe_read16(ds + src),
                        Size::D => safe_read32s(ds + src),
                    })
                },
                Instruction::Scas | Instruction::Stos => data & size_mask,
                Instruction::Ins => match size {
                    Size::B => io_port_read8(port),
                    Size::W => io_port_read16(port),
                    Size::D => io_port_read32(port),
                },
            };

            let mut dst_val = 0;

            match instruction {
                Instruction::Cmps | Instruction::Scas => match size {
                    Size::B => dst_val = break_with_fault!(safe_read8(es + dst)),
                    Size::W => dst_val = break_with_fault!(safe_read16(es + dst)),
                    Size::D => dst_val = break_with_fault!(safe_read32s(es + dst)),
                },
                Instruction::Outs => match size {
                    Size::B => io_port_write8(port, src_val),
                    Size::W => io_port_write16(port, src_val),
                    Size::D => io_port_write32(port, src_val),
                },
                Instruction::Lods => match size {
                    Size::B => write_reg8(AL, src_val),
                    Size::W => write_reg16(AX, src_val),
                    Size::D => write_reg32(EAX, src_val),
                },
                Instruction::Movs | Instruction::Stos | Instruction::Ins => match size {
                    Size::B => break_with_fault!(safe_write8(es + dst, src_val)),
                    Size::W => break_with_fault!(safe_write16(es + dst, src_val)),
                    Size::D => break_with_fault!(safe_write32(es + dst, src_val)),
                },
            };

            match instruction {
                Instruction::Movs
                | Instruction::Cmps
                | Instruction::Stos
                | Instruction::Scas
                | Instruction::Ins => dst = dst + increment & asize_mask,
                _ => {},
            }
            match instruction {
                Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
                    src = src + increment & asize_mask
                },
                _ => {},
            };

            count -= 1;
            iterations += 1;

            let finished = match rep {
                Rep::Z | Rep::NZ => match (rep, instruction) {
                    (Rep::Z, Instruction::Cmps) => src_val != dst_val || count == 0,
                    (Rep::Z, Instruction::Scas) => src_val != dst_val || count == 0,
                    (Rep::NZ, Instruction::Cmps) => src_val == dst_val || count == 0,
                    (Rep::NZ, Instruction::Scas) => src_val == dst_val || count == 0,
                    (Rep::NZ | Rep::Z, Instruction::Movs) => {
                        if count == 0 {
                            true
                        }
                        else if movs_reenter_fast_path {
                            *instruction_pointer = *previous_ip;
                            repeat = true;
                            true
                        }
                        else {
                            false
                        }
                    },
                    _ => count == 0,
                },
                Rep::None => true,
            };

            if finished {
                match instruction {
                    Instruction::Scas | Instruction::Cmps => match size {
                        Size::B => cmp8(src_val, dst_val),
                        Size::W => cmp16(src_val, dst_val),
                        Size::D => cmp32(src_val, dst_val),
                    },
                    _ => {},
                }
                break;
            }
            if limit != u32::MAX && iterations == limit {
                *instruction_pointer = *previous_ip;
                repeat = true;
                break;
            }
        }
    }

    match instruction {
        Instruction::Movs
        | Instruction::Cmps
        | Instruction::Stos
        | Instruction::Scas
        | Instruction::Ins => set_reg_asize(is_asize_32, EDI, dst),
        _ => {},
    }
    match instruction {
        Instruction::Movs | Instruction::Cmps | Instruction::Lods | Instruction::Outs => {
            set_reg_asize(is_asize_32, ESI, src)
        },
        _ => {},
    };

    match rep {
        Rep::Z | Rep::NZ => {
            set_reg_asize(is_asize_32, ECX, count as i32);
        },
        Rep::None => {},
    };
    StringExecution::new(
        if fault {
            StringOutcome::Fault
        }
        else if repeat {
            StringOutcome::Repeat
        }
        else {
            StringOutcome::Complete
        },
        iterations,
    )
}

#[no_mangle]
pub unsafe fn movsb_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn movsw_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn movsd_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::D, Rep::Z)
}
pub unsafe fn movsb_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::B, Rep::None)
}
pub unsafe fn movsw_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::W, Rep::None)
}
pub unsafe fn movsd_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Movs, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn lodsb_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn lodsw_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn lodsd_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::D, Rep::Z)
}
pub unsafe fn lodsb_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::B, Rep::None)
}
pub unsafe fn lodsw_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::W, Rep::None)
}
pub unsafe fn lodsd_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Lods, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn stosb_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn stosw_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn stosd_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::D, Rep::Z)
}
pub unsafe fn stosb_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::B, Rep::None)
}
pub unsafe fn stosw_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::W, Rep::None)
}
pub unsafe fn stosd_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Stos, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn cmpsb_repz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn cmpsw_repz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn cmpsd_repz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::D, Rep::Z)
}
#[no_mangle]
pub unsafe fn cmpsb_repnz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::B, Rep::NZ)
}
#[no_mangle]
pub unsafe fn cmpsw_repnz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::W, Rep::NZ)
}
#[no_mangle]
pub unsafe fn cmpsd_repnz(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::D, Rep::NZ)
}
#[no_mangle]
pub unsafe fn cmpsb_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::B, Rep::None)
}
#[no_mangle]
pub unsafe fn cmpsw_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::W, Rep::None)
}
#[no_mangle]
pub unsafe fn cmpsd_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Cmps, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn scasb_repz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn scasw_repz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn scasd_repz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::Z)
}
#[no_mangle]
pub unsafe fn scasb_repnz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::NZ)
}
#[no_mangle]
pub unsafe fn scasw_repnz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::NZ)
}
#[no_mangle]
pub unsafe fn scasd_repnz(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::NZ)
}
pub unsafe fn scasb_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::B, Rep::None)
}
pub unsafe fn scasw_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::W, Rep::None)
}
pub unsafe fn scasd_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Scas, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn outsb_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn outsw_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn outsd_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::D, Rep::Z)
}
#[no_mangle]
pub unsafe fn outsb_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::B, Rep::None)
}
#[no_mangle]
pub unsafe fn outsw_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::W, Rep::None)
}
#[no_mangle]
pub unsafe fn outsd_no_rep(is_asize_32: bool, seg: i32) {
    string_instruction(is_asize_32, seg, Instruction::Outs, Size::D, Rep::None)
}

#[no_mangle]
pub unsafe fn insb_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::B, Rep::Z)
}
#[no_mangle]
pub unsafe fn insw_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::W, Rep::Z)
}
#[no_mangle]
pub unsafe fn insd_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::D, Rep::Z)
}
#[no_mangle]
pub unsafe fn insb_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::B, Rep::None)
}
#[no_mangle]
pub unsafe fn insw_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::W, Rep::None)
}
#[no_mangle]
pub unsafe fn insd_no_rep(is_asize_32: bool) {
    string_instruction(is_asize_32, 0, Instruction::Ins, Size::D, Rep::None)
}

/// Execute one non-REP port string instruction with the interpreter's complete
/// observation order, including permission MMIO and address16 register writes.
/// The caller owns decoded PC preparation and instruction retirement.
pub unsafe fn execute_io_once(
    input: bool,
    bytes: u32,
    asize32: bool,
    segment: i32,
) -> StringExecution {
    assert!(segment >= 0 && segment < 6);
    let size = match bytes {
        1 => Size::B,
        2 => Size::W,
        4 => Size::D,
        _ => panic!("I/O width"),
    };
    string_instruction_bounded(
        asize32,
        if input { 0 } else { segment },
        if input { Instruction::Ins } else { Instruction::Outs },
        size,
        Rep::None,
        1,
    )
}

/// Execute a recognized REP family with an explicit element budget. The caller
/// owns decoded PC preparation and scheduling; this function does not count CPU
/// instructions or deliver exceptions a second time.
pub unsafe fn execute_rep(
    kind: u32,
    bytes: u32,
    asize32: bool,
    segment: i32,
    repne: bool,
    limit: u32,
) -> StringExecution {
    assert!(segment >= 0 && segment < 6);
    let instruction = match kind {
        0 => Instruction::Movs,
        1 => Instruction::Cmps,
        2 => Instruction::Stos,
        3 => Instruction::Lods,
        4 => Instruction::Scas,
        5 => Instruction::Ins,
        6 => Instruction::Outs,
        _ => panic!("REP family"),
    };
    let size = match bytes {
        1 => Size::B,
        2 => Size::W,
        4 => Size::D,
        _ => panic!("REP width"),
    };
    let segment = if matches!(
        instruction,
        Instruction::Stos | Instruction::Scas | Instruction::Ins
    ) {
        0
    }
    else {
        segment
    };
    let rep = if repne && matches!(instruction, Instruction::Cmps | Instruction::Scas) {
        Rep::NZ
    }
    else {
        Rep::Z
    };
    string_instruction_bounded(asize32, segment, instruction, size, rep, limit)
}

#[cfg(feature = "ir-test-hooks")]
#[no_mangle]
pub unsafe fn ir_test_rep_batch(
    kind: u32,
    bytes: u32,
    asize32: bool,
    segment: i32,
    repne: bool,
    limit: u32,
) -> u64 {
    let result = execute_rep(kind, bytes, asize32, segment, repne, limit);
    let tag = match result.outcome {
        StringOutcome::Complete => 0,
        StringOutcome::Repeat => 1,
        StringOutcome::Fault => 2,
    };
    ((result.iterations as u64) << 32) | tag
}

/// One interpreted instruction: the oracle the REP and VERR tests step with.
#[cfg(feature = "ir-test-hooks")]
#[no_mangle]
pub unsafe fn ir_test_step() {
    use crate::cpu::{cpu, global_pointers as gp};
    *gp::previous_ip = *gp::instruction_pointer;
    *gp::prefixes = 0;
    if let Ok(opcode) = cpu::read_imm8() {
        cpu::run_instruction(opcode | (*gp::is_32 as i32) << 8);
    }
}
#[cfg(feature = "ir-test-hooks")]
#[no_mangle]
pub unsafe fn ir_test_set_cr0(value: i32) { crate::cpu::cpu::set_cr0(value); }
                                                                                                                                                                                                                                 source/v64/src/rust/cpu/topology.rs                                                                 0000644 0000000 0000000 00000007133 00000000000 014465  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! CPUID topology for one package, one thread per core, contiguous APIC IDs.
//!
//! The one-core machine keeps the historic v86 CPUID profile byte-for-byte.
//! Machines with 2..=8 cores use the `smp32` profile: leaf 0 advertises 1FH,
//! 0BH/1FH enumerate SMT and core domains, and deterministic cache topology
//! agrees with the package. This describes topology, not x2APIC support.
//! Intel SDM Vol. 2, CPUID leaves 01H, 04H, 0BH, and 1FH.

/// Apply topology fields to legacy CPUID output, ordered EAX/EBX/ECX/EDX.
/// The caller must pass the original input ECX as `subleaf`.
pub fn apply(leaf: u32, subleaf: u32, cores: u32, core_id: u32, regs: &mut [u32; 4]) {
    debug_assert!((1..=8).contains(&cores));
    debug_assert!(core_id < cores);
    if cores == 1 {
        return;
    }
    match leaf {
        0 => regs[0] = regs[0].max(0x1F),
        1 => {
            regs[1] = (regs[1] & 0xFFFF) | (cores << 16) | (core_id << 24);
            // HTT qualifies the package logical-processor count. It does not
            // claim SMT siblings when the SMT domain's count is one.
            regs[3] |= 1 << 28;
        },
        4 => {
            if regs[0] & 0x1F != 0 {
                // Keep existing cache geometry. L1 data/instruction caches
                // are private; the unified L2 is shared by the package.
                let level = (regs[0] >> 5) & 7;
                let sharing = if level == 1 { 1 } else { cores };
                regs[0] = (regs[0] & 0x3FFF) | ((sharing - 1) << 14) | ((cores - 1) << 26);
            }
        },
        0xB | 0x1F => {
            let (shift, count, kind) = match subleaf {
                0 => (0, 1, 1), // SMT: one logical processor per core
                1 => (32 - (cores - 1).leading_zeros(), cores, 2),
                _ => (0, 0, 0), // terminal/unsupported level
            };
            *regs = [shift, count, (subleaf & 0xFF) | (kind << 8), core_id];
        },
        _ => {},
    }
}

#[cfg(test)]
mod tests {
    use super::apply;

    #[test]
    fn legacy_single_core_is_unchanged() {
        for leaf in [0, 1, 4, 0xB, 0x1F] {
            let mut regs = [0x16, 0x10203, 0x40506, 0x70809];
            let before = regs;
            apply(leaf, 1, 1, 0, &mut regs);
            assert_eq!(regs, before);
        }
    }

    #[test]
    fn package_shift_rounds_up_for_non_powers_of_two() {
        for (cores, shift) in [(2, 1), (3, 2), (4, 2), (5, 3), (6, 3), (7, 3), (8, 3)] {
            for id in 0..cores {
                for leaf in [0xB, 0x1F] {
                    let mut regs = [0; 4];
                    apply(leaf, 0, cores, id, &mut regs);
                    assert_eq!(regs, [0, 1, 0x100, id]);
                    apply(leaf, 1, cores, id, &mut regs);
                    assert_eq!(regs, [shift, cores, 0x201, id]);
                    apply(leaf, 2, cores, id, &mut regs);
                    assert_eq!(regs, [0, 0, 2, id]);
                    assert_eq!(id >> shift, 0, "all cores belong to package zero");
                }
            }
        }
    }

    #[test]
    fn legacy_package_count_and_cache_domains_agree() {
        let mut regs = [0, 0x10800, 0, 0];
        apply(1, 0, 3, 2, &mut regs);
        assert_eq!(regs[1], 0x02030800);
        assert_eq!(regs[3], 1 << 28);
        let mut l1 = [0x121, 0x1C0003F, 0x3F, 1];
        apply(4, 0, 3, 2, &mut l1);
        assert_eq!(l1[0], 0x08000121);
        let mut l2 = [0x143, 0x5C0003F, 0xFFF, 1];
        apply(4, 2, 3, 2, &mut l2);
        assert_eq!(l2[0], 0x08008143);
        let mut terminal = [0; 4];
        apply(4, 3, 3, 2, &mut terminal);
        assert_eq!(terminal, [0; 4]);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/src/rust/cpu/vex.rs                                                                      0000644 0000000 0000000 00000011273 00000000000 013413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! VEX instructions in the 32-bit interpreter (docs/simd-xsave-plan.md). The
//! VEX prefix and the row it selects follow the rules the IR and x64 decoders
//! share (decode_rules::Vex, vex_row, vex_valid); rows whose semantics come in
//! later phases are #UD after the ModRM byte. The AVX forms run in the shared
//! executor (crate::cpu::avx).
use crate::cpu::avx;
use crate::cpu::cpu::*;
use crate::cpu::global_pointers::*;
use crate::cpu::modrm::{resolve_offset, resolve_offset_vsib};
use crate::decode::ImmediateKind;
use crate::decode_rules::{vex_prefixes_ud, vex_row, vex_valid, Vex};

/// C4 or C5 (`first`) whose ModRM byte as LES/LDS, `byte1`, is a register
/// form: the first byte of a VEX prefix in protected mode. Real and
/// virtual-8086 mode have no VEX: LES/LDS, whose register form is #UD. A
/// 66/F2/F3 prefix is #UD here too, where LOCK was (decode_rules::lock_allowed).
pub unsafe fn run(first: u8, byte1: u8) {
    INTERPRETED_VEX = INTERPRETED_VEX.wrapping_add(1);
    if !*protected_mode || vm86_mode() || vex_prefixes_ud(*prefixes) {
        trigger_ud();
        return;
    }
    let v = if first == 0xC4 {
        Vex::three(byte1, return_on_pagefault!(read_imm8()) as u8, false)
    }
    else {
        Vex::two(byte1, false)
    };
    let key = v.key(return_on_pagefault!(read_imm8()) as u8);
    let rows = crate::decode::candidates(key);
    // (a key without rows, including the reserved maps: #UD at the opcode byte)
    let Some(family) = rows.first()
    else {
        trigger_ud();
        return;
    };
    let modrm =
        if family.fetch_modrm { Some(return_on_pagefault!(read_imm8()) as u8) } else { None };
    let address_size = if is_asize_32() { 32 } else { 16 };
    let Some(row) = vex_row(rows, v, modrm, false)
        .filter(|row| row.exists() && row.implemented() && vex_valid(row, v, modrm, address_size))
    else {
        trigger_ud();
        return;
    };
    // The instruction's remaining bytes, then the AVX state (#UD, #NM), then
    // the operand's segment (SDM vol. 3, 6.9: the faults of fetching and
    // decoding an instruction come before those of executing it)
    let mut vsib = None;
    let memory = match modrm {
        Some(m) if m < 0xC0 && row.vex & crate::decode_rules::vex::VSIB != 0 => {
            let (offset, segment, index, scale) =
                return_on_pagefault!(resolve_offset_vsib(m as i32));
            // (a gather's destination, indices and mask in three registers)
            let reg = m >> 3 & 7;
            if reg == index || v.vvvv == index || reg == v.vvvv {
                trigger_ud();
                return;
            }
            vsib = Some(avx::Vsib { index, scale });
            Some((offset, segment))
        },
        Some(m) if m < 0xC0 => Some(return_on_pagefault!(resolve_offset(m as i32))),
        _ => None,
    };
    let imm8 = if row.immediate == ImmediateKind::Byte {
        return_on_pagefault!(read_imm8()) as u8
    }
    else {
        0
    };
    // BMI1 and BMI2 (exception type 13): general-purpose registers, without
    // the AVX state's requirements; 32-bit operands outside 64-bit mode
    if row.vex & crate::decode_rules::vex::GPR != 0 {
        let reg = modrm.map_or(0, |m| m >> 3 & 7);
        let address = match memory {
            Some((offset, segment)) => {
                return_on_pagefault!(get_seg_prefix(segment)).wrapping_add(offset)
            },
            None => 0,
        };
        let i = crate::cpu::bmi::Instruction {
            op: crate::cpu::bmi::Vex::of(row.opcode, reg).unwrap(),
            reg,
            vvvv: v.vvvv,
            bits: 32,
            imm8,
        };
        let mut machine = crate::cpu::bmi::Interpreter {
            rm: modrm.filter(|m| *m >= 0xC0).map(|m| m & 7),
            address,
        };
        let _ = crate::cpu::bmi::execute(&mut machine, &i);
        return;
    }
    let mut machine = avx::Interpreter { address: 0 };
    if avx::check(&mut machine).is_err() {
        return;
    }
    machine.address = match memory {
        Some((offset, segment)) => {
            return_on_pagefault!(get_seg_prefix(segment)).wrapping_add(offset)
        },
        // VMASKMOVDQU's destination
        None if row.opcode == 0xC40101F7 => {
            return_on_pagefault!(get_seg_prefix_ds(get_reg_asize(EDI)))
        },
        None => 0,
    };
    let i = avx::Instruction {
        key: row.opcode,
        reg: modrm.map_or(0, |m| m >> 3 & 7),
        vvvv: v.vvvv,
        rm: modrm.filter(|m| *m >= 0xC0).map(|m| m & 7),
        // (a VEX.256 form: not a VEX.LIG one's VEX.L)
        l: v.l && row.vex & crate::decode_rules::vex::L1 != 0,
        w: v.w,
        imm8,
        long: false,
        vsib,
    };
    let _ = avx::execute(&mut machine, &i);
}
                                                                                                                                                                                                                                                                                                                                     source/v64/src/rust/cpu/xstate.rs                                                                   0000644 0000000 0000000 00000106072 00000000000 014123  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! XSAVE-managed state (docs/simd-xsave-plan.md 6.1-6.2): XCR0, IA32_XSS,
//! the upper halves of YMM0-YMM15, and the standard format of the XSAVE area.
//! The 32-bit interpreter, the IR's helpers and the x64 engine share the
//! encoding of the state components (encode, decode, in_use) and the rules
//! (XSETBV, XGETBV, the XSAVE header); each checks an instruction's
//! preconditions and address and moves the bytes with its own memory accesses
//! (xsave, xrstor, fxsave and fxrstor here are the 32-bit engines').

use crate::cpu::cpu::{self, MXCSR_MASK};
use crate::cpu::features;
use crate::cpu::global_pointers as gp;

/// State components (XCR0 bits)
pub const X87: u64 = 1 << 0;
pub const SSE: u64 = 1 << 1;
pub const YMM: u64 = 1 << 2;

/// The XSAVE header and the YMM_Hi128 component in the standard format
pub const HEADER: u32 = 512;
pub const YMM_OFFSET: u32 = 576;
/// XCOMP_BV's bit 63: the compacted form (XSAVEC, XSAVES). Its extended
/// region holds the components of XCOMP_BV[62:0] in order from 576, so with
/// YMM_Hi128 the only extended component here (its size 256, no 64-byte
/// alignment: CPUID.(EAX=0DH,ECX=2)) it is at the standard offset.
pub const COMPACTED: u64 = 1 << 63;
/// The standard-format area with every component of this implementation
pub const AREA_SIZE: usize = 832;

/// The XCR0 bits this machine supports (CPUID.(EAX=0DH,ECX=0):EDX:EAX)
pub fn supported() -> u64 {
    use crate::cpu::features::{AVX, XSAVE};
    if !features::has(XSAVE) {
        0
    }
    else if features::has(AVX) {
        X87 | SSE | YMM
    }
    else {
        X87 | SSE
    }
}
/// The size of a standard-format area holding the components `mask`
pub fn standard_size(mask: u64) -> u32 {
    if mask & YMM != 0 {
        832
    }
    else {
        576
    }
}

/// The size of a compacted-form area holding the components `mask`
pub fn compacted_size(mask: u64) -> u32 { standard_size(mask) }

/// The XSAVE-managed registers
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Registers {
    pub fcw: u16,
    /// with TOP
    pub fsw: u16,
    /// the abridged tag word: bit i set when physical register i is not empty
    pub ftw: u8,
    pub fop: u16,
    pub fip: u64,
    pub fcs: u16,
    pub fdp: u64,
    pub fds: u16,
    /// ST(0)..ST(7), counted from the top of the stack: 80 bits each
    pub st: [[u8; 10]; 8],
    pub mxcsr: u32,
    pub xmm: [u128; 16],
    pub ymm_hi: [u128; 16],
}
/// How an instruction lays out and reaches the state
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Format {
    /// REX.W: 64-bit FIP and FDP, without FCS and FDS
    pub wide: bool,
    /// 64-bit mode: XMM8-XMM15 and YMM8_H-YMM15_H, which other modes leave alone
    pub long: bool,
}
impl Format {
    pub fn registers(self) -> usize {
        if self.long {
            16
        }
        else {
            8
        }
    }
}

/// The fields an instruction stores for the components `mask`, and MXCSR
/// with MXCSR_MASK if `with_mxcsr`: (offset, length), adjacent ones merged.
/// Reserved and unused bytes are not stored (nor bytes 464-511).
pub fn fields(mask: u64, with_mxcsr: bool, format: Format) -> Vec<(u32, u32)> {
    let mut fields = Vec::new();
    if mask & X87 != 0 {
        // FCW, FSW, the abridged FTW; FOP and FIP (FCS); FDP (FDS)
        fields.extend([(0, 5), (6, if format.wide { 10 } else { 8 })]);
        fields.push((16, if format.wide { 8 } else { 6 }));
    }
    if with_mxcsr {
        fields.push((24, 8));
    }
    if mask & X87 != 0 {
        fields.extend((0..8).map(|i| (32 + 16 * i, 10)));
    }
    let n = 16 * format.registers() as u32;
    if mask & SSE != 0 {
        fields.push((160, n));
    }
    if mask & YMM != 0 {
        fields.push((YMM_OFFSET, n));
    }
    let mut merged: Vec<(u32, u32)> = Vec::new();
    for (offset, length) in fields {
        match merged.last_mut() {
            Some(last) if last.0 + last.1 == offset => last.1 += length,
            _ => merged.push((offset, length)),
        }
    }
    merged
}

/// The state of the components `mask` (and MXCSR if `with_mxcsr`) at their places
/// in a standard-format area; the other bytes are 0
pub fn encode(r: &Registers, mask: u64, with_mxcsr: bool, format: Format) -> [u8; AREA_SIZE] {
    let mut area = [0; AREA_SIZE];
    let mut put =
        |offset: usize, bytes: &[u8]| area[offset..offset + bytes.len()].copy_from_slice(bytes);
    if mask & X87 != 0 {
        put(0, &r.fcw.to_le_bytes());
        put(2, &r.fsw.to_le_bytes());
        put(4, &[r.ftw]);
        put(6, &r.fop.to_le_bytes());
        if format.wide {
            put(8, &r.fip.to_le_bytes());
            put(16, &r.fdp.to_le_bytes());
        }
        else {
            put(8, &(r.fip as u32).to_le_bytes());
            put(12, &r.fcs.to_le_bytes());
            put(16, &(r.fdp as u32).to_le_bytes());
            put(20, &r.fds.to_le_bytes());
        }
        for i in 0..8 {
            put(32 + 16 * i, &r.st[i]);
        }
    }
    if with_mxcsr {
        put(24, &r.mxcsr.to_le_bytes());
        put(28, &(MXCSR_MASK as u32).to_le_bytes());
    }
    for i in 0..format.registers() {
        if mask & SSE != 0 {
            put(160 + 16 * i, &r.xmm[i].to_le_bytes());
        }
        if mask & YMM != 0 {
            put(YMM_OFFSET as usize + 16 * i, &r.ymm_hi[i].to_le_bytes());
        }
    }
    area
}

/// Load the components `load` from `area`, give the components `init` their
/// initial configuration, and load MXCSR if `with_mxcsr` (the caller checked its
/// reserved bits); other state is left alone. FCS and FDS (FIP and FDP's
/// upper halves) become 0 when the format does not hold them.
pub fn decode(
    r: &mut Registers,
    area: &[u8; AREA_SIZE],
    load: u64,
    init: u64,
    with_mxcsr: bool,
    format: Format,
) {
    let u16_at = |at: usize| u16::from_le_bytes(area[at..at + 2].try_into().unwrap());
    let u32_at = |at: usize| u32::from_le_bytes(area[at..at + 4].try_into().unwrap());
    let u64_at = |at: usize| u64::from_le_bytes(area[at..at + 8].try_into().unwrap());
    let u128_at = |at: usize| u128::from_le_bytes(area[at..at + 16].try_into().unwrap());
    if load & X87 != 0 {
        r.fcw = u16_at(0);
        r.fsw = u16_at(2);
        r.ftw = area[4];
        r.fop = u16_at(6) & 0x7FF;
        if format.wide {
            (r.fip, r.fcs, r.fdp, r.fds) = (u64_at(8), 0, u64_at(16), 0);
        }
        else {
            (r.fip, r.fcs, r.fdp, r.fds) =
                (u32_at(8) as u64, u16_at(12), u32_at(16) as u64, u16_at(20));
        }
        for i in 0..8 {
            r.st[i].copy_from_slice(&area[32 + 16 * i..42 + 16 * i]);
        }
    }
    else if init & X87 != 0 {
        (r.fcw, r.fsw, r.ftw, r.fop, r.fip, r.fcs, r.fdp, r.fds) = (0x37F, 0, 0, 0, 0, 0, 0, 0);
        r.st = [[0; 10]; 8];
    }
    if with_mxcsr {
        r.mxcsr = u32_at(24);
    }
    for i in 0..format.registers() {
        if load & SSE != 0 {
            r.xmm[i] = u128_at(160 + 16 * i);
        }
        else if init & SSE != 0 {
            r.xmm[i] = 0;
        }
        if load & YMM != 0 {
            r.ymm_hi[i] = u128_at(YMM_OFFSET as usize + 16 * i);
        }
        else if init & YMM != 0 {
            r.ymm_hi[i] = 0;
        }
    }
}

/// The components not known to be in their initial configuration (XINUSE,
/// SDM Vol. 1 13.6), here exactly those that are not
pub fn in_use(r: &Registers, format: Format) -> u64 {
    let n = format.registers();
    let x87 = r.fcw != 0x37F
        || r.fsw != 0
        || r.ftw != 0
        || r.fcs != 0
        || r.fds != 0
        || r.fip != 0
        || r.fdp != 0
        || r.st.iter().any(|st| *st != [0; 10]);
    (x87 as u64) * X87
        | (r.xmm[..n].iter().any(|x| *x != 0) as u64) * SSE
        | (r.ymm_hi[..n].iter().any(|x| *x != 0) as u64) * YMM
}

/// XRSTOR's checks of the header (otherwise #GP(0)): Some(false) for a
/// valid standard form (XSTATE_BV within `allowed`, XCR0; bytes 23:8, XCOMP_BV
/// and 8 reserved bytes, zero), Some(true) for a valid compacted one
/// (XCOMP_BV[63], which needs XSAVEC; XCOMP_BV[62:0] within `allowed`,
/// XSTATE_BV within XCOMP_BV, bytes 63:16 zero)
pub fn header_form(header: &[u8; 64], allowed: u64) -> Option<bool> {
    let at = |offset: usize| u64::from_le_bytes(header[offset..offset + 8].try_into().unwrap());
    let (xstate_bv, xcomp_bv) = (at(0), at(8));
    if xcomp_bv & COMPACTED == 0 {
        (xstate_bv & !allowed == 0 && header[8..24].iter().all(|&b| b == 0)).then_some(false)
    }
    else {
        let format = xcomp_bv & !COMPACTED;
        (features::has(features::XSAVEC)
            && format & !allowed == 0
            && xstate_bv & !format == 0
            && header[16..].iter().all(|&b| b == 0))
        .then_some(true)
    }
}

/// An XSETBV of `value` into XCR `index` is valid (otherwise #GP(0)): XCR0
/// only, supported components, x87 always, AVX state only with SSE state
pub fn xsetbv_valid(index: u32, value: u64) -> bool {
    index == 0
        && value & !supported() == 0
        && value & X87 != 0
        && (value & YMM == 0 || value & SSE != 0)
}

/// The XSAVE feature set is enabled (CR4.OSXSAVE, which needs XSAVE)
pub unsafe fn enabled() -> bool { *gp::cr.add(4) & cpu::CR4_OSXSAVE != 0 }

/// At reset: XCR0 has x87 state only (an INIT keeps all of this: cpu.js)
pub unsafe fn reset() {
    *gp::xcr0 = X87;
    *gp::xss = 0;
    for i in 0..16 {
        *gp::ymm_hi.add(i) = cpu::reg128 { u64: [0, 0] };
    }
}

/// CPUID: OSXSAVE (CR4) in leaf 1, the XSAVE feature set in leaf 0xD
/// (the features in leaf 0xD, subleaf 1: crate::cpu::features)
pub unsafe fn cpuid(leaf: u32, subleaf: u32, registers: &mut [u32; 4]) {
    let supported = supported();
    if supported == 0 {
        return;
    }
    match (leaf, subleaf) {
        (1, _) if enabled() => registers[2] |= 1 << 27,
        (0xD, 0) => {
            *registers = [
                supported as u32,
                standard_size(*gp::xcr0),
                standard_size(supported),
                (supported >> 32) as u32,
            ]
        },
        // (with the compacted form: the size of an area of XCR0 and
        // IA32_XSS's components; IA32_XSS supports none, ECX and EDX)
        (0xD, 1) if features::has(features::XSAVEC) => {
            registers[1] = compacted_size(*gp::xcr0 | *gp::xss)
        },
        (0xD, 2) if supported & YMM != 0 => *registers = [256, YMM_OFFSET, 0, 0],
        _ => {},
    }
}

/// XGETBV: XCR `index` (1: XCR0 AND XINUSE, with XGETBV1; `long`: the
/// registers of 64-bit mode count), or None for #GP(0)
pub unsafe fn xgetbv(index: u32, long: bool) -> Option<u64> {
    match index {
        0 => Some(*gp::xcr0),
        1 if features::has(features::XGETBV1) => {
            Some(*gp::xcr0 & in_use(&registers(), Format { wide: false, long }))
        },
        _ => None,
    }
}
/// XSETBV: false for #GP(0), which also comes for CPL > 0 (the caller's)
pub unsafe fn xsetbv(index: u32, value: u64) -> bool {
    if !xsetbv_valid(index, value) {
        return false;
    }
    *gp::xcr0 = value;
    true
}

/// The registers of this core, its x87 cache written back
pub unsafe fn registers() -> Registers {
    crate::cpu::fpu::fpu_sync_all();
    let pair = |lo: i32, hi: u32| lo as u32 as u64 | (hi as u64) << 32;
    let mut r = Registers {
        fcw: *gp::fpu_control_word,
        fsw: crate::cpu::fpu::fpu_load_status_word(),
        ftw: !*gp::fpu_stack_empty,
        fop: *gp::fpu_opcode as u16,
        fip: pair(*gp::fpu_ip, *gp::x64_fpu_ip_hi),
        fcs: *gp::fpu_ip_selector as u16,
        fdp: pair(*gp::fpu_dp, *gp::x64_fpu_dp_hi),
        fds: *gp::fpu_dp_selector as u16,
        mxcsr: *gp::mxcsr as u32,
        ..Registers::default()
    };
    for i in 0..8 {
        let st = *gp::fpu_st.add((i + *gp::fpu_stack_ptr as usize) & 7);
        r.st[i][..8].copy_from_slice(&st.mantissa.to_le_bytes());
        r.st[i][8..].copy_from_slice(&st.sign_exponent.to_le_bytes());
    }
    for i in 0..16 {
        r.xmm[i] = std::mem::transmute(crate::x64::state::read_xmm(i));
        r.ymm_hi[i] = std::mem::transmute(*gp::ymm_hi.add(i));
    }
    r
}
/// Write back the components `mask` of `r`, and MXCSR if `with_mxcsr`
pub unsafe fn set_registers(r: &Registers, mask: u64, with_mxcsr: bool, format: Format) {
    if mask & X87 != 0 {
        crate::cpu::fpu::fpu_cache_barrier();
        crate::cpu::fpu::set_control_word(r.fcw);
        crate::cpu::fpu::fpu_set_status_word(r.fsw);
        *gp::fpu_stack_empty = !r.ftw;
        *gp::fpu_opcode = r.fop as i32;
        *gp::fpu_ip = r.fip as i32;
        *gp::x64_fpu_ip_hi = (r.fip >> 32) as u32;
        *gp::fpu_ip_selector = r.fcs as i32;
        *gp::fpu_dp = r.fdp as i32;
        *gp::x64_fpu_dp_hi = (r.fdp >> 32) as u32;
        *gp::fpu_dp_selector = r.fds as i32;
        for i in 0..8 {
            let st = crate::softfloat::F80 {
                mantissa: u64::from_le_bytes(r.st[i][..8].try_into().unwrap()),
                sign_exponent: u16::from_le_bytes(r.st[i][8..].try_into().unwrap()),
            };
            crate::cpu::fpu::fpu_write_st(((i + *gp::fpu_stack_ptr as usize) & 7) as i32, st);
        }
    }
    if with_mxcsr {
        cpu::set_mxcsr(r.mxcsr as i32);
    }
    for i in 0..format.registers() {
        if mask & SSE != 0 {
            crate::x64::state::write_xmm(i, std::mem::transmute(r.xmm[i]));
        }
        if mask & YMM != 0 {
            *gp::ymm_hi.add(i) = std::mem::transmute(r.ymm_hi[i]);
        }
    }
}

/// An engine's access to an XSAVE area at an aligned address: `check` makes
/// sure the bytes can be read or written (a page fault comes from there), and
/// the instructions call it for every field before any byte moves, so a
/// fault leaves memory and state alone
pub trait Area {
    type Fault;
    unsafe fn check(&mut self, offset: u32, length: u32, write: bool) -> Result<(), Self::Fault>;
    /// 8 bytes, or 1 (after check)
    unsafe fn read(&mut self, offset: u32, bytes: &mut [u8]);
    unsafe fn write(&mut self, offset: u32, bytes: &[u8]);
    /// #GP(0)
    unsafe fn gp(&mut self) -> Self::Fault;
}
unsafe fn write_fields<A: Area>(
    m: &mut A,
    area: &[u8; AREA_SIZE],
    fields: &[(u32, u32)],
) -> Result<(), A::Fault> {
    for &(offset, length) in fields {
        m.check(offset, length, true)?;
    }
    for &(offset, length) in fields {
        let (mut at, end) = (offset as usize, (offset + length) as usize);
        while at < end {
            let n = if at + 8 <= end { 8 } else { 1 };
            m.write(at as u32, &area[at..at + n]);
            at += n;
        }
    }
    Ok(())
}
unsafe fn read_fields<A: Area>(
    m: &mut A,
    area: &mut [u8; AREA_SIZE],
    fields: &[(u32, u32)],
) -> Result<(), A::Fault> {
    for &(offset, length) in fields {
        m.check(offset, length, false)?;
    }
    for &(offset, length) in fields {
        let (mut at, end) = (offset as usize, (offset + length) as usize);
        while at < end {
            let n = if at + 8 <= end { 8 } else { 1 };
            m.read(at as u32, &mut area[at..at + n]);
            at += n;
        }
    }
    Ok(())
}
fn mxcsr_valid(area: &[u8; AREA_SIZE]) -> bool {
    u32::from_le_bytes(area[24..28].try_into().unwrap()) & !(MXCSR_MASK as u32) == 0
}

/// XSAVE of the components `rfbm` (XCR0 AND EDX:EAX)
pub unsafe fn xsave<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 2);
    save_standard(m, rfbm, format, false)
}
/// XSAVEOPT: XSAVE's but for the components in their initial configuration
/// (XINUSE), which it does not store (the init optimization). It has no
/// modified optimization (the SDM lets XSAVEOPT also skip components
/// unmodified since an XRSTOR from the same area; not doing so is allowed).
pub unsafe fn xsaveopt<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 2);
    save_standard(m, rfbm, format, true)
}
/// The standard form's save: the components `rfbm`, or with
/// `init_optimization` those of them in use; MXCSR and MXCSR_MASK with
/// RFBM[1] or RFBM[2] (whatever XINUSE says); XSTATE_BV's bits of `rfbm`
/// from XINUSE, the others kept, and no other header byte
unsafe fn save_standard<A: Area>(
    m: &mut A,
    rfbm: u64,
    format: Format,
    init_optimization: bool,
) -> Result<(), A::Fault> {
    let with_mxcsr = rfbm & (SSE | YMM) != 0;
    let r = registers();
    let in_use = in_use(&r, format);
    let saved = if init_optimization { rfbm & in_use } else { rfbm };
    m.check(HEADER, 8, false)?;
    m.check(HEADER, 8, true)?;
    let mut old = [0; 8];
    m.read(HEADER, &mut old);
    write_fields(
        m,
        &encode(&r, saved, with_mxcsr, format),
        &fields(saved, with_mxcsr, format),
    )?;
    let xstate_bv = u64::from_le_bytes(old) & !rfbm | in_use & rfbm;
    m.write(HEADER, &xstate_bv.to_le_bytes());
    Ok(())
}
/// XSAVEC of the components `rfbm`: the compacted form. It stores the
/// components in use (the init optimization), and SSE state also when MXCSR
/// is not 1F80H (MXCSR, part of SSE state, does not count in XINUSE[1]);
/// MXCSR and MXCSR_MASK with SSE state only. XSTATE_BV: the components
/// stored; XCOMP_BV: `rfbm` with bit 63. No other header byte, nor bytes
/// 464-511.
pub unsafe fn xsavec<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 2);
    let r = registers();
    let mut saved = rfbm & in_use(&r, format);
    if rfbm & SSE != 0 && r.mxcsr != 0x1F80 {
        saved |= SSE;
    }
    let with_mxcsr = saved & SSE != 0;
    m.check(HEADER, 16, true)?;
    write_fields(
        m,
        &encode(&r, saved, with_mxcsr, format),
        &fields(saved, with_mxcsr, format),
    )?;
    m.write(HEADER, &saved.to_le_bytes());
    m.write(HEADER + 8, &(rfbm | COMPACTED).to_le_bytes());
    Ok(())
}
/// XSAVES of the components `rfbm` ((XCR0 OR IA32_XSS) AND EDX:EAX; CPL 0
/// checked): XSAVEC's (no modified optimization, which the SDM allows XSAVES
/// too)
pub unsafe fn xsaves<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    // (xsavec counts it in the step profile)
    xsavec(m, rfbm, format)
}
/// XRSTORS of the components `rfbm` ((XCR0 OR IA32_XSS) AND EDX:EAX; CPL 0
/// checked): the compacted form only (#GP(0) for the standard form), its
/// XCOMP_BV within XCR0 OR IA32_XSS
pub unsafe fn xrstors<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 3);
    let mut area = [0; AREA_SIZE];
    read_fields(m, &mut area, &[(HEADER, 64)])?;
    let header = area[HEADER as usize..][..64].try_into().unwrap();
    if header_form(header, *gp::xcr0 | *gp::xss) != Some(true) {
        return Err(m.gp());
    }
    restore(m, &mut area, rfbm, true, format)
}
/// XRSTOR of the components `rfbm`, from either form
pub unsafe fn xrstor<A: Area>(m: &mut A, rfbm: u64, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 3);
    let mut area = [0; AREA_SIZE];
    read_fields(m, &mut area, &[(HEADER, 64)])?;
    let Some(compacted) = header_form(area[HEADER as usize..][..64].try_into().unwrap(), *gp::xcr0)
    else {
        return Err(m.gp());
    };
    restore(m, &mut area, rfbm, compacted, format)
}
/// The components `rfbm` from `area`, whose header was read and checked:
/// those XSTATE_BV marks loaded, the others initialized. MXCSR: the standard
/// form loads it with RFBM[1] or RFBM[2] whatever XSTATE_BV says; the
/// compacted form with SSE state only, and initializes it to 1F80H with SSE
/// state. Reserved MXCSR bits loaded are #GP(0), before any state changes.
unsafe fn restore<A: Area>(
    m: &mut A,
    area: &mut [u8; AREA_SIZE],
    rfbm: u64,
    compacted: bool,
    format: Format,
) -> Result<(), A::Fault> {
    let xstate_bv = u64::from_le_bytes(area[HEADER as usize..][..8].try_into().unwrap());
    let (load, init) = (rfbm & xstate_bv, rfbm & !xstate_bv);
    let with_mxcsr = if compacted { load & SSE != 0 } else { rfbm & (SSE | YMM) != 0 };
    read_fields(m, area, &fields(load, with_mxcsr, format))?;
    if with_mxcsr && !mxcsr_valid(area) {
        return Err(m.gp());
    }
    let mut r = registers();
    decode(&mut r, area, load, init, with_mxcsr, format);
    let initial_mxcsr = compacted && init & SSE != 0;
    if initial_mxcsr {
        r.mxcsr = 0x1F80;
    }
    set_registers(&r, load | init, with_mxcsr || initial_mxcsr, format);
    Ok(())
}
/// FXSAVE: the x87 and SSE state with MXCSR (bytes 288-511 only in 64-bit
/// mode, and never 416-511)
pub unsafe fn fxsave<A: Area>(m: &mut A, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 0);
    let r = registers();
    write_fields(
        m,
        &encode(&r, X87 | SSE, true, format),
        &fields(X87 | SSE, true, format),
    )
}
/// FXRSTOR: #GP(0) for reserved MXCSR bits
pub unsafe fn fxrstor<A: Area>(m: &mut A, format: Format) -> Result<(), A::Fault> {
    crate::step_profile::note_event(crate::step_profile::event::FXSTATE, 1);
    let mut area = [0; AREA_SIZE];
    read_fields(m, &mut area, &fields(X87 | SSE, true, format))?;
    if !mxcsr_valid(&area) {
        return Err(m.gp());
    }
    let mut r = registers();
    decode(&mut r, &area, X87 | SSE, 0, true, format);
    set_registers(&r, X87 | SSE, true, format);
    Ok(())
}

/// #UD without CR4.OSXSAVE, then #NM with CR0.TS if `nm`: XSAVE, XRSTOR,
/// XGETBV and XSETBV check these before their operands. False: the fault was
/// delivered (32-bit engines).
pub unsafe fn usable(nm: bool) -> bool {
    if !enabled() {
        cpu::trigger_ud();
        return false;
    }
    if nm && *gp::cr & cpu::CR0_TS != 0 {
        cpu::trigger_nm();
        return false;
    }
    true
}
/// XCR0 AND EDX:EAX: the components an instruction asks for (RFBM)
pub unsafe fn requested(edx: u32, eax: u32) -> u64 { *gp::xcr0 & ((edx as u64) << 32 | eax as u64) }
/// XSAVES and XRSTORS's RFBM: (XCR0 OR IA32_XSS) AND EDX:EAX
pub unsafe fn requested_supervisor(edx: u32, eax: u32) -> u64 {
    (*gp::xcr0 | *gp::xss) & ((edx as u64) << 32 | eax as u64)
}
/// The IA32_XSS bits this machine supports: no supervisor state component
pub const XSS_SUPPORTED: u64 = 0;
/// IA32_XSS (MSR 0DA0H, with XSAVES): None for an absent MSR
pub unsafe fn read_xss() -> Option<u64> { features::has(features::XSAVES).then(|| *gp::xss) }
/// WRMSR to IA32_XSS: None for an absent MSR, Some(false) for unsupported
/// bits (#GP(0))
pub unsafe fn write_xss(value: u64) -> Option<bool> {
    if !features::has(features::XSAVES) {
        return None;
    }
    if value & !XSS_SUPPORTED != 0 {
        return Some(false);
    }
    *gp::xss = value;
    Some(true)
}

/// The 32-bit engines (the interpreter, also in compatibility mode, and the
/// IR's helpers): a linear address, faults delivered as they come
struct Linear(i32);
impl Area for Linear {
    type Fault = ();
    unsafe fn check(&mut self, offset: u32, length: u32, write: bool) -> Result<(), ()> {
        let at = self.0.wrapping_add(offset as i32);
        if write {
            cpu::writable_or_pagefault(at, length as i32)
        }
        else {
            cpu::readable_or_pagefault(at, length as i32)
        }
    }
    unsafe fn read(&mut self, offset: u32, bytes: &mut [u8]) {
        let at = self.0.wrapping_add(offset as i32);
        if bytes.len() == 8 {
            bytes.copy_from_slice(&cpu::safe_read64s(at).unwrap().to_le_bytes());
        }
        else {
            bytes[0] = cpu::safe_read8(at).unwrap() as u8;
        }
    }
    unsafe fn write(&mut self, offset: u32, bytes: &[u8]) {
        let at = self.0.wrapping_add(offset as i32);
        if bytes.len() == 8 {
            cpu::safe_write64(at, u64::from_le_bytes(bytes.try_into().unwrap())).unwrap();
        }
        else {
            cpu::safe_write8(at, bytes[0] as i32).unwrap();
        }
    }
    unsafe fn gp(&mut self) { cpu::trigger_gp(0); }
}
const NARROW: Format = Format {
    wide: false,
    long: false,
};
unsafe fn eax_edx() -> (u32, u32) {
    (
        cpu::read_reg32(cpu::EDX) as u32,
        cpu::read_reg32(cpu::EAX) as u32,
    )
}

/// XSAVE at the linear address `addr` (usable() checked): #GP(0) unless
/// aligned to 64 bytes. False if a fault was delivered.
pub unsafe fn xsave_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xsave(&mut Linear(addr), requested(edx, eax), NARROW).is_ok()
}
/// XSAVEOPT at `addr` (usable() checked), like xsave_32
pub unsafe fn xsaveopt_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xsaveopt(&mut Linear(addr), requested(edx, eax), NARROW).is_ok()
}
/// XSAVEC at `addr` (usable() checked), like xsave_32
pub unsafe fn xsavec_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xsavec(&mut Linear(addr), requested(edx, eax), NARROW).is_ok()
}
/// XSAVES at `addr` (usable() and CPL 0 checked), like xsave_32
pub unsafe fn xsaves_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xsaves(&mut Linear(addr), requested_supervisor(edx, eax), NARROW).is_ok()
}
/// XRSTORS from `addr` (usable() and CPL 0 checked), like xsave_32
pub unsafe fn xrstors_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xrstors(&mut Linear(addr), requested_supervisor(edx, eax), NARROW).is_ok()
}
/// XRSTOR from `addr` (usable() checked), like xsave_32
pub unsafe fn xrstor_32(addr: i32) -> bool {
    if addr & 63 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    let (edx, eax) = eax_edx();
    xrstor(&mut Linear(addr), requested(edx, eax), NARROW).is_ok()
}
/// FXSAVE at `addr` (#NM checked): #GP(0) unless aligned to 16 bytes
pub unsafe fn fxsave_32(addr: i32) -> bool {
    if addr & 15 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    fxsave(&mut Linear(addr), NARROW).is_ok()
}
/// FXRSTOR from `addr` (#NM checked), like fxsave_32
pub unsafe fn fxrstor_32(addr: i32) -> bool {
    if addr & 15 != 0 {
        cpu::trigger_gp(0);
        return false;
    }
    fxrstor(&mut Linear(addr), NARROW).is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    fn sample() -> Registers {
        let mut r = Registers {
            fcw: 0x27F,
            fsw: 0x3800 | 0x41,
            ftw: 0x81,
            fop: 0x5D9,
            fip: 0x1234_5678_9ABC_DEF0,
            fcs: 0x23,
            fdp: 0x0FED_CBA9_8765_4321,
            fds: 0x2B,
            mxcsr: 0x1FA0,
            ..Registers::default()
        };
        for i in 0..8 {
            r.st[i] = [i as u8 + 1; 10];
        }
        for i in 0..16 {
            r.xmm[i] = 0x0101_0101_0101_0101_0101_0101_0101_0101 * (i as u128 + 1);
            r.ymm_hi[i] = !r.xmm[i];
        }
        r
    }
    #[test]
    fn layout_follows_the_standard_format() {
        let r = sample();
        let narrow = Format {
            wide: false,
            long: false,
        };
        let area = encode(&r, X87 | SSE | YMM, true, narrow);
        assert_eq!(&area[0..8], &[0x7F, 0x02, 0x41, 0x38, 0x81, 0, 0xD9, 0x05]);
        assert_eq!(
            &area[8..24],
            &[0xF0, 0xDE, 0xBC, 0x9A, 0x23, 0, 0, 0, 0x21, 0x43, 0x65, 0x87, 0x2B, 0, 0, 0]
        );
        assert_eq!(&area[24..32], &[0xA0, 0x1F, 0, 0, 0xFF, 0xFF, 0, 0]);
        assert_eq!(
            &area[32..48],
            &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
        );
        assert_eq!(area[160], 1);
        assert_eq!(&area[288..416], &[0; 128], "XMM8-15 only in 64-bit mode");
        assert_eq!(area[576], 0xFE);
        assert_eq!(&area[704..832], &[0; 128]);
        let wide = encode(
            &r,
            X87,
            false,
            Format {
                wide: true,
                long: true,
            },
        );
        assert_eq!(u64::from_le_bytes(wide[8..16].try_into().unwrap()), r.fip);
        assert_eq!(u64::from_le_bytes(wide[16..24].try_into().unwrap()), r.fdp);
        assert_eq!(&wide[24..32], &[0; 8], "MXCSR only when asked");
        // the fields stored: no reserved bytes, nothing from 416 on but YMM_Hi128
        assert_eq!(
            fields(X87 | SSE | YMM, true, narrow),
            vec![
                (0, 5),
                (6, 8),
                (16, 6),
                (24, 18),
                (48, 10),
                (64, 10),
                (80, 10),
                (96, 10),
                (112, 10),
                (128, 10),
                (144, 10),
                (160, 128),
                (576, 128)
            ]
        );
        assert_eq!(
            fields(
                X87 | SSE,
                true,
                Format {
                    wide: true,
                    long: true
                }
            ),
            vec![
                (0, 5),
                (6, 36),
                (48, 10),
                (64, 10),
                (80, 10),
                (96, 10),
                (112, 10),
                (128, 10),
                (144, 10),
                (160, 256)
            ]
        );
        assert_eq!(fields(YMM, true, narrow), vec![(24, 8), (576, 128)]);
        assert_eq!(fields(0, false, narrow), vec![]);
    }
    #[test]
    fn round_trip_init_and_partial_restores() {
        for format in [
            Format {
                wide: false,
                long: false,
            },
            Format {
                wide: true,
                long: true,
            },
            Format {
                wide: false,
                long: true,
            },
        ] {
            let r = sample();
            let area = encode(&r, X87 | SSE | YMM, true, format);
            let mut back = Registers::default();
            decode(&mut back, &area, X87 | SSE | YMM, 0, true, format);
            let n = format.registers();
            assert_eq!(
                (back.fcw, back.fsw, back.ftw, back.fop, back.mxcsr),
                (r.fcw, r.fsw, r.ftw, r.fop, r.mxcsr)
            );
            assert_eq!(back.st, r.st);
            assert_eq!(&back.xmm[..n], &r.xmm[..n]);
            assert_eq!(&back.ymm_hi[..n], &r.ymm_hi[..n]);
            assert!(
                back.xmm[n..]
                    .iter()
                    .chain(&back.ymm_hi[n..])
                    .all(|x| *x == 0),
                "other modes leave XMM8-15 alone"
            );
            if format.wide {
                assert_eq!(
                    (back.fip, back.fdp, back.fcs, back.fds),
                    (r.fip, r.fdp, 0, 0)
                );
            }
            else {
                assert_eq!(
                    (back.fip, back.fdp, back.fcs, back.fds),
                    (r.fip as u32 as u64, r.fdp as u32 as u64, r.fcs, r.fds)
                );
            }
            // components not asked for are left alone; init gives FNINIT's x87
            // state and zero registers, not MXCSR
            let mut partial = sample();
            decode(&mut partial, &[0; AREA_SIZE], 0, X87 | YMM, false, format);
            assert_eq!(
                (partial.fcw, partial.fsw, partial.ftw, partial.st),
                (0x37F, 0, 0, [[0; 10]; 8])
            );
            assert_eq!((partial.xmm, partial.mxcsr), (r.xmm, r.mxcsr));
            assert!(partial.ymm_hi[..n].iter().all(|x| *x == 0));
            assert_eq!(in_use(&partial, format), SSE);
        }
    }
    #[test]
    fn in_use_header_and_xsetbv_rules() {
        let narrow = Format {
            wide: false,
            long: false,
        };
        let mut r = Registers {
            fcw: 0x37F,
            mxcsr: 0x1F80,
            ..Registers::default()
        };
        assert_eq!(in_use(&r, narrow), 0);
        r.mxcsr = 0x1FA0;
        assert_eq!(in_use(&r, narrow), 0, "MXCSR is not part of XINUSE[1]");
        r.xmm[9] = 1;
        r.ymm_hi[15] = 1;
        assert_eq!(in_use(&r, narrow), 0, "XMM8-15 count only in 64-bit mode");
        assert_eq!(
            in_use(
                &r,
                Format {
                    wide: false,
                    long: true
                }
            ),
            SSE | YMM
        );
        r.fop = 1;
        assert_eq!(
            in_use(&r, narrow),
            0,
            "FOP is not part of the x87 init configuration"
        );
        r.ftw = 1;
        assert_eq!(in_use(&r, narrow), X87);

        let mut header = [0; 64];
        header[0] = 3;
        assert!(header_form(&header, 3) == Some(false) && header_form(&header, 1).is_none());
        header[15] = 0x80;
        assert!(
            header_form(&header, 3).is_none(),
            "the compacted form needs XSAVEC"
        );
        header[15] = 0;
        header[23] = 1;
        assert!(header_form(&header, 3).is_none());
        header[23] = 0;
        header[24] = 1;
        assert_eq!(
            header_form(&header, 3),
            Some(false),
            "bytes 63:24 are not checked by the standard form"
        );
        // the compacted form: XCOMP_BV within XCR0, XSTATE_BV within XCOMP_BV,
        // bytes 63:16 zero
        use crate::cpu::features::XSAVEC;
        TEST_FEATURES.with(|f| f.set(XSAVE | XSAVEC));
        let compacted = |xstate_bv: u64, xcomp_bv: u64, byte: Option<usize>| {
            let mut h = [0; 64];
            h[..8].copy_from_slice(&xstate_bv.to_le_bytes());
            h[8..16].copy_from_slice(&xcomp_bv.to_le_bytes());
            if let Some(at) = byte {
                h[at] = 1;
            }
            header_form(&h, 7)
        };
        assert_eq!(compacted(5, COMPACTED | 7, None), Some(true));
        assert_eq!(compacted(0, COMPACTED, None), Some(true));
        assert_eq!(
            compacted(4, COMPACTED | 3, None),
            None,
            "XSTATE_BV beyond XCOMP_BV"
        );
        assert_eq!(
            compacted(1, COMPACTED | 9, None),
            None,
            "XCOMP_BV beyond XCR0"
        );
        assert_eq!(compacted(1, COMPACTED | 1, Some(16)), None, "bytes 63:16");
        assert_eq!(compacted(1, COMPACTED | 1, Some(63)), None, "bytes 63:16");
        assert_eq!(compacted(0, 1, None), None, "XCOMP_BV without bit 63");
        TEST_FEATURES.with(|f| f.set(0));

        use crate::cpu::features::{ALL, AVX, SSE4_1, SSE4_2, SSSE3, TEST_FEATURES, XSAVE};
        for (features, all) in [
            (0, 0),
            (XSAVE, X87 | SSE),
            (XSAVE | AVX | SSSE3 | SSE4_1 | SSE4_2, X87 | SSE | YMM),
            (ALL, X87 | SSE | YMM),
        ] {
            TEST_FEATURES.with(|f| f.set(features));
            assert_eq!(supported(), all);
            for value in 0..16u64 {
                let valid = all != 0
                    && value & !all == 0
                    && value & 1 != 0
                    && (value & 4 == 0 || value & 2 != 0);
                assert_eq!(xsetbv_valid(0, value), valid, "{features:x} {value:x}");
                assert!(!xsetbv_valid(1, value));
            }
        }
        TEST_FEATURES.with(|f| f.set(0));
        assert_eq!(
            (standard_size(X87 | SSE), standard_size(X87 | SSE | YMM)),
            (576, 832)
        );
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/rust/dbg.rs                                                                          0000644 0000000 0000000 00000004163 00000000000 012556  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #[allow(dead_code)]
pub const DEBUG: bool = cfg!(debug_assertions);

#[cfg(target_arch = "wasm32")]
#[link(wasm_import_module = "env")]
extern "C" {
    pub fn log_from_wasm(ptr: *const u8, len: usize);
    pub fn console_log_from_wasm(ptr: *const u8, len: usize);
    pub fn dbg_trace_from_wasm();
}

#[cfg(target_arch = "wasm32")]
pub fn log_to_js_console<T: std::string::ToString>(s: T) {
    let s = s.to_string();
    let len = s.len();
    unsafe {
        log_from_wasm(s.as_bytes().as_ptr(), len);
    }
}

#[cfg(target_arch = "wasm32")]
pub fn console_log_to_js_console<T: std::string::ToString>(s: T) {
    let s = s.to_string();
    let len = s.len();
    unsafe {
        console_log_from_wasm(s.as_bytes().as_ptr(), len);
    }
}

#[cfg(target_arch = "wasm32")]
pub fn dbg_trace() {
    if DEBUG {
        unsafe {
            dbg_trace_from_wasm();
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
pub fn dbg_trace() {}

#[allow(unused_macros)]
macro_rules! dbg_log {
    ($fmt:expr) => {
        println!($fmt);
    };
    ($fmt:expr, $($arg:tt)*) => {
        println!($fmt, $($arg)*);
    }
}

#[allow(unused_macros)]
macro_rules! console_log {
    ($fmt:expr) => {
        println!($fmt);
    };
    ($fmt:expr, $($arg:tt)*) => {
        println!($fmt, $($arg)*);
    }
}

#[allow(unused_macros)]
macro_rules! dbg_assert {
    ($($arg:tt)*) => {
        debug_assert!($($arg)*)
    };
}

#[cfg(target_arch = "wasm32")]
#[allow(unused_macros)]
macro_rules! console_log {
    ($fmt:expr) => {
        {
            crate::dbg::console_log_to_js_console($fmt);
        }
    };
    ($fmt:expr, $($arg:tt)*) => {
        {
            crate::dbg::console_log_to_js_console(format!($fmt, $($arg)*));
        }
    };
}

#[cfg(target_arch = "wasm32")]
#[allow(unused_macros)]
macro_rules! dbg_log {
    ($fmt:expr) => {
        {
            use crate::dbg::{ DEBUG, log_to_js_console };
            if DEBUG { log_to_js_console($fmt); }
        }
    };
    ($fmt:expr, $($arg:tt)*) => {
        {
            use crate::dbg::{ DEBUG, log_to_js_console };
            if DEBUG { log_to_js_console(format!($fmt, $($arg)*)); }
        }
    };
}
                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/rust/decode/decode.rs                                                                0000644 0000000 0000000 00000046573 00000000000 014503  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Side-effect-free decoding over caller-owned code bytes. Never reads live CPU memory.
#[path = "encodings.rs"]
mod generated;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GuestEip(pub u32);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LinearAddress(pub u32);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PhysicalAddress(pub u32);

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Prefixes {
    pub operand: bool,
    pub address: bool,
    pub lock: bool,
    // Baseline accumulates F2/F3 and chooses F2 first if both are present.
    pub repne: bool,
    pub rep: bool,
    pub segment: Option<u8>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ImmediateKind {
    None,
    Byte,
    SignedByte,
    Word,
    Operand,
    Address,
}
#[derive(Debug)]
pub struct Encoding {
    pub id: u32,
    pub opcode: u32,
    pub group: i8,
    pub immediate: ImmediateKind,
    pub extra_bytes: u8,
    // Interpreter dispatch fetches ModRM before selecting the mandatory-prefix form.
    pub fetch_modrm: bool,
    pub group_ud: bool,
    pub task_switch_test: bool,
    pub custom: bool,
    pub e: bool,
    pub ignore_mod: bool,
    pub reg_ud: bool,
    pub mem_ud: bool,
    pub os: bool,
    pub block_boundary: bool,
    pub no_next_instruction: bool,
    pub absolute_jump: bool,
    pub jump_offset_imm: bool,
    pub conditional_jump: bool,
    pub custom_sti: bool,
    pub is_fpu: bool,
    pub sse: bool,
    /// An SSE row whose register operands are MMX registers (gen/x86_table.js
    /// mmx_form): its task checks ignore CR4.OSFXSR
    pub mmx: bool,
    /// The prefixes that select instructions in this opcode (decode_rules::
    /// mandatory_variant): REFINING_ALL in the SSE maps
    pub refining: u8,
    /// The CPUID feature without which the row does not exist (crate::cpu::
    /// features; 0: always)
    pub feature: u32,
    /// #UD even with the feature (docs/simd-xsave-plan.md: semantics later)
    pub unimplemented: bool,
    /// A VEX row: the VEX fields it accepts (decode_rules::vex; 0: a legacy row)
    pub vex: u16,
    pub is_string: bool,
}
impl Encoding {
    /// A legacy SSE m128 operand of this form, read or written with `bytes`,
    /// must be 16-byte aligned (#GP(0), SDM vol. 2, Table 2-21): of every XMM
    /// form accessing 16 bytes but MOVUPS, MOVUPD, MOVDQU, LDDQU and PCMPxSTRx,
    /// and of UNPCKLPS/UNPCKLPD, which read its low quadword
    pub fn aligned_m128(&self, bytes: u8) -> bool {
        self.sse
            && !self.mmx
            && !matches!(
                self.opcode,
                0x0F10 | 0x660F10 | 0xF30F6F | 0x0F11 | 0x660F11 | 0xF30F7F | 0xF20FF0 | 0x660F3A60
                    ..=0x660F3A63
            )
            && (bytes == 16 || matches!(self.opcode, 0x0F14 | 0x660F14))
    }
    /// The row exists on this machine (its feature is present)
    pub fn exists(&self) -> bool { self.feature == 0 || crate::cpu::features::has(self.feature) }
    /// The row has its semantics (not Encoding::unimplemented). cargo test
    /// may decode the others as if it had (TEST_DECODE_UNIMPLEMENTED).
    pub fn implemented(&self) -> bool {
        #[cfg(test)]
        if TEST_DECODE_UNIMPLEMENTED.with(|t| t.get()) {
            return true;
        }
        !self.unimplemented
    }
}
#[cfg(test)]
thread_local! {
    /// cargo test: decode rows whose semantics come later as if they had
    /// them, for their length, operands and the encodings they refuse
    pub static TEST_DECODE_UNIMPLEMENTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EffectiveAddress {
    pub base: Option<u8>,
    /// (a vector register for a VSIB operand, Encoding::vex)
    pub index: Option<u8>,
    pub scale: u8,
    pub displacement: u32,
    pub address_size: u8,
    pub segment: u8,
}
impl EffectiveAddress {
    /// Offset arithmetic only. Segmentation and translation belong to runtime lowering.
    pub fn offset(&self, gpr: &[u32; 8]) -> u32 {
        let result = self
            .displacement
            .wrapping_add(self.base.map_or(0, |r| gpr[r as usize]))
            .wrapping_add(
                self.index
                    .map_or(0, |r| gpr[r as usize].wrapping_shl(self.scale as u32)),
            );
        if self.address_size == 16 {
            result & 0xFFFF
        }
        else {
            result
        }
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Flow {
    Next,
    Boundary,
    Stop,
    Sti,
    Relative {
        displacement: i32,
        conditional: bool,
        call: bool,
    },
}
#[derive(Clone, Debug)]
pub struct DecodedInstruction {
    pub encoding: &'static Encoding,
    pub instruction_pc: GuestEip,
    pub next_pc: GuestEip,
    pub linear_pc: LinearAddress,
    pub bytes: [u8; 15],
    pub length: u8,
    pub operand_size: u8,
    pub address_size: u8,
    pub prefixes: Prefixes,
    pub modrm: Option<u8>,
    pub modrm_offset: Option<u8>,
    pub ea: Option<EffectiveAddress>,
    pub immediate: Option<u32>,
    pub extra_immediate: Option<u16>,
    pub baseline_ud: bool,
    /// #UD right after the ModRM byte, before EA, immediate and task-switch
    /// guards: a mandatory prefix without a row of its own (decode_rules::
    /// Variant::Undefined), a row whose CPUID feature is absent, or one whose
    /// semantics come later (Encoding::unimplemented). For VEX: also no row
    /// accepting the VEX fields (decode_rules::vex_row, vex_valid), and a
    /// 66/F2/F3/LOCK prefix, which is #UD right after the first VEX byte.
    pub early_ud: bool,
    /// The VEX prefix (C4/C5 with a register ModRM byte, decode_rules::is_vex)
    pub vex: Option<crate::decode_rules::Vex>,
    pub flow: Flow,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DecodeStop {
    Incomplete { available: usize },
    TooLong,
    UnknownEncoding { opcode: u32 },
}

struct Cursor<'a> {
    bytes: &'a [u8],
    position: usize,
}
impl Cursor<'_> {
    fn read(&mut self) -> Result<u8, DecodeStop> {
        if self.position == 15 {
            return Err(DecodeStop::TooLong);
        }
        let byte = *self
            .bytes
            .get(self.position)
            .ok_or(DecodeStop::Incomplete {
                available: self.bytes.len(),
            })?;
        self.position += 1;
        Ok(byte)
    }
    /// The next byte, which the instruction includes whatever it is
    fn peek(&self) -> Result<u8, DecodeStop> {
        if self.position == 15 {
            return Err(DecodeStop::TooLong);
        }
        self.bytes
            .get(self.position)
            .copied()
            .ok_or(DecodeStop::Incomplete {
                available: self.bytes.len(),
            })
    }
    fn integer(&mut self, bytes: u8) -> Result<u32, DecodeStop> {
        let mut value = 0;
        for shift in 0..bytes {
            value |= (self.read()? as u32) << (shift * 8);
        }
        Ok(value)
    }
}

pub fn encodings() -> &'static [Encoding] { generated::ENCODINGS }
/// The iced-x86 form (gen/isa_forms.json) of a VEX row
#[cfg(test)]
pub fn form(e: &Encoding) -> &'static str {
    let i = generated::FORMS
        .binary_search_by_key(&e.id, |&(id, _)| id)
        .unwrap();
    generated::FORMS[i].1
}
/// The rows of a catalogue key
pub fn candidates(opcode: u32) -> &'static [Encoding] {
    match generated::OPCODES.binary_search_by_key(&opcode, |&(key, _, _)| key) {
        Ok(i) => {
            let (_, start, end) = generated::OPCODES[i];
            &generated::ENCODINGS[start..end]
        },
        Err(_) => &[],
    }
}

/// `bytes` is a logical contiguous instruction snapshot; it may span physical pages.
/// Missing bytes return a compile stop. The caller must deliver fetch faults during execution.
pub fn decode(
    bytes: &[u8],
    pc: GuestEip,
    linear: LinearAddress,
    default_32: bool,
) -> Result<DecodedInstruction, DecodeStop> {
    let mut c = Cursor { bytes, position: 0 };
    let mut prefixes = Prefixes::default();
    let first = loop {
        let byte = c.read()?;
        use crate::decode_rules::{prefix, Prefix};
        match prefix(byte) {
            Some(Prefix::Segment(s)) => prefixes.segment = Some(s),
            Some(Prefix::Operand) => prefixes.operand = true,
            Some(Prefix::Address) => prefixes.address = true,
            Some(Prefix::Lock) => prefixes.lock = true,
            // of F2 and F3 the last one counts (decode_rules::apply_prefix)
            Some(Prefix::Repne) => {
                prefixes.rep = false;
                prefixes.repne = true;
            },
            Some(Prefix::Rep) => {
                prefixes.repne = false;
                prefixes.rep = true;
            },
            None => break byte,
        }
    };
    // C4/C5 with a register ModRM byte: a VEX prefix. This decoder does not
    // know the mode; in real and virtual-8086 mode, which have no VEX, the
    // interpreter raises #UD for the register form of LES/LDS instead, so a
    // VEX row needs that guard when it gets semantics.
    if (first == 0xC4 || first == 0xC5) && crate::decode_rules::is_vex(c.peek()?, false) {
        return decode_vex(c, bytes, pc, linear, default_32, prefixes, first);
    }
    // 0F 38 and 0F 3A lead to the three-byte maps (key 0x0F38xx, 0x0F3Axx)
    let base_opcode = if first == 0x0F {
        let second = c.read()?;
        if second == 0x38 || second == 0x3A {
            0x0F0000 | (second as u32) << 8 | c.read()? as u32
        }
        else {
            0x0F00 | second as u32
        }
    }
    else {
        first as u32
    };
    let operand_size = if default_32 != prefixes.operand { 32 } else { 16 };
    let address_size = if default_32 != prefixes.address { 32 } else { 16 };
    let mut available = 0;
    let variants = [
        (0x66, crate::prefix::PREFIX_66),
        (0xF2, crate::prefix::PREFIX_F2),
        (0xF3, crate::prefix::PREFIX_F3),
    ];
    let shift = if base_opcode > 0xFFFF {
        24
    }
    else if first == 0x0F {
        16
    }
    else {
        8
    };
    // the prefixes select instructions where a row of the opcode says so; a
    // row whose feature is absent is not available
    let mut refining = candidates(base_opcode)
        .iter()
        .fold(0, |m, row| m | row.refining);
    let mut family = candidates(base_opcode).first();
    for (prefix, mask) in variants {
        if prefix != 0x66 || first == 0x0F {
            let rows = candidates(prefix << shift | base_opcode);
            refining |= rows.iter().fold(0, |m, row| m | row.refining);
            family = family.or(rows.first());
            if rows.iter().any(Encoding::exists) {
                available |= mask;
            }
        }
    }
    let flags = if prefixes.operand { crate::prefix::PREFIX_66 } else { 0 }
        | if prefixes.repne { crate::prefix::PREFIX_F2 } else { 0 }
        | if prefixes.rep { crate::prefix::PREFIX_F3 } else { 0 };
    use crate::decode_rules::{Variant, REFINING_REP};
    let variant = crate::decode_rules::mandatory_variant(flags, available, refining);
    let refused = if flags & REFINING_REP != 0 {
        flags & REFINING_REP
    }
    else {
        flags & crate::prefix::PREFIX_66
    };
    let opcode = match variant {
        Variant::Prefixed(selected) => variants
            .iter()
            .find(|(_, mask)| *mask == selected)
            .map_or(base_opcode, |(prefix, _)| prefix << shift | base_opcode),
        // (undefined: the rows of the refused prefix, when it has some)
        Variant::Undefined => variants
            .iter()
            .find(|(_, mask)| *mask == refused)
            .map(|(prefix, _)| prefix << shift | base_opcode)
            .filter(|key| !candidates(*key).is_empty())
            .unwrap_or(base_opcode),
        Variant::Plain => base_opcode,
    };
    let rows = candidates(opcode);
    // (an opcode without a row in any variant is unknown: the interpreter
    // raises #UD at its last opcode byte)
    let first = family.ok_or(DecodeStop::UnknownEncoding { opcode })?;
    let modrm_offset = if first.fetch_modrm { Some(c.position as u8) } else { None };
    let modrm = if first.fetch_modrm { Some(c.read()?) } else { None };
    let row = rows
        .iter()
        .find(|row| row.group < 0 || modrm.map(|m| (m >> 3 & 7) as i8) == Some(row.group));
    let early_ud = variant == Variant::Undefined
        || rows.is_empty()
        || row.is_some_and(|row| !row.exists() || !row.implemented());
    let encoding = if early_ud {
        row.unwrap_or(first)
    }
    else {
        row.ok_or(DecodeStop::UnknownEncoding { opcode })?
    };
    let ea = match modrm {
        Some(m) if encoding.e && m < 0xC0 && !encoding.ignore_mod && !early_ud => {
            Some(decode_ea(&mut c, m, address_size, prefixes.segment)?)
        },
        _ => None,
    };
    let immediate = match if early_ud { ImmediateKind::None } else { encoding.immediate } {
        ImmediateKind::None => None,
        ImmediateKind::Byte => Some(c.integer(1)?),
        ImmediateKind::SignedByte => Some(c.read()? as i8 as i32 as u32),
        ImmediateKind::Word => Some(c.integer(2)?),
        ImmediateKind::Operand => Some(c.integer(operand_size / 8)?),
        ImmediateKind::Address => Some(c.integer(address_size / 8)?),
    };
    let extra_immediate = if encoding.extra_bytes > 0 && !early_ud {
        Some(c.integer(encoding.extra_bytes)? as u16)
    }
    else {
        None
    };
    let baseline_ud = early_ud
        || (if ea.is_some() { encoding.mem_ud } else { encoding.reg_ud })
        || prefixes.lock && !crate::decode_rules::lock_allowed(base_opcode, modrm);
    let flow = if encoding.jump_offset_imm {
        Flow::Relative {
            displacement: immediate.unwrap() as i32,
            conditional: encoding.conditional_jump,
            call: base_opcode == 0xE8,
        }
    }
    else if encoding.custom_sti {
        Flow::Sti
    }
    else if encoding.no_next_instruction {
        Flow::Stop
    }
    else if encoding.block_boundary || !encoding.custom && encoding.e || baseline_ud {
        Flow::Boundary
    }
    else {
        Flow::Next
    };
    let mut raw = [0; 15];
    raw[..c.position].copy_from_slice(&bytes[..c.position]);
    Ok(DecodedInstruction {
        encoding,
        instruction_pc: pc,
        next_pc: GuestEip(pc.0.wrapping_add(c.position as u32)),
        linear_pc: linear,
        bytes: raw,
        length: c.position as u8,
        operand_size,
        address_size,
        prefixes,
        modrm,
        modrm_offset,
        ea,
        immediate,
        extra_immediate,
        baseline_ud,
        early_ud,
        vex: None,
        flow,
    })
}

/// A VEX instruction: `first` (C4 or C5) and its prefixes are read
fn decode_vex(
    mut c: Cursor<'_>,
    bytes: &[u8],
    pc: GuestEip,
    linear: LinearAddress,
    default_32: bool,
    prefixes: Prefixes,
    first: u8,
) -> Result<DecodedInstruction, DecodeStop> {
    use crate::decode_rules::{vex_prefixes_ud, vex_row, vex_valid, Vex};
    let address_size = if default_32 != prefixes.address { 32 } else { 16 };
    let byte1 = c.read()?;
    let flags = if prefixes.operand { crate::prefix::PREFIX_66 } else { 0 }
        | if prefixes.repne { crate::prefix::PREFIX_F2 } else { 0 }
        | if prefixes.rep { crate::prefix::PREFIX_F3 } else { 0 }
        | if prefixes.lock { crate::prefix::PREFIX_LOCK } else { 0 };
    let instruction = |c: &Cursor<'_>,
                       encoding,
                       modrm,
                       modrm_offset,
                       ea,
                       immediate,
                       baseline_ud,
                       early_ud,
                       vex| {
        let mut raw = [0; 15];
        raw[..c.position].copy_from_slice(&bytes[..c.position]);
        DecodedInstruction {
            encoding,
            instruction_pc: pc,
            next_pc: GuestEip(pc.0.wrapping_add(c.position as u32)),
            linear_pc: linear,
            bytes: raw,
            length: c.position as u8,
            // (VEX instructions on general-purpose registers are 32-bit
            // outside 64-bit mode)
            operand_size: 32,
            address_size,
            prefixes,
            modrm,
            modrm_offset,
            ea,
            immediate,
            extra_immediate: None,
            baseline_ud,
            early_ud,
            vex,
            flow: if baseline_ud { Flow::Boundary } else { Flow::Next },
        }
    };
    // 66, F2, F3 or LOCK before VEX: #UD at the first VEX byte, where the
    // interpreter's LES/LDS (whose ModRM byte it is) checks LOCK
    if vex_prefixes_ud(flags) {
        let les = &candidates(first as u32)[0];
        return Ok(instruction(
            &c, les, None, None, None, None, true, true, None,
        ));
    }
    let v =
        if first == 0xC4 { Vex::three(byte1, c.read()?, false) } else { Vex::two(byte1, false) };
    let key = v.key(c.read()?);
    let rows = candidates(key);
    // (a key without rows, including the reserved maps, is unknown: #UD at
    // the opcode byte when run)
    let family = rows
        .first()
        .ok_or(DecodeStop::UnknownEncoding { opcode: key })?;
    let modrm_offset = if family.fetch_modrm { Some(c.position as u8) } else { None };
    let modrm = if family.fetch_modrm { Some(c.read()?) } else { None };
    let Some(row) = vex_row(rows, v, modrm, false)
        .filter(|row| row.exists() && row.implemented() && vex_valid(row, v, modrm, address_size))
    else {
        let row = vex_row(rows, v, modrm, false).unwrap_or(family);
        return Ok(instruction(
            &c,
            row,
            modrm,
            modrm_offset,
            None,
            None,
            true,
            true,
            Some(v),
        ));
    };
    use crate::decode_rules::vex;
    // (a VSIB index names a vector register, xmm4/ymm4 included)
    let vsib_index = || bytes[modrm_offset.unwrap() as usize + 1] >> 3 & 7;
    let vsib = row.vex & vex::VSIB != 0;
    let ea = match modrm {
        Some(m) if m < 0xC0 => {
            let mut ea = decode_ea(&mut c, m, address_size, prefixes.segment)?;
            if vsib {
                ea.index = Some(vsib_index());
            }
            Some(ea)
        },
        _ => None,
    };
    let immediate = match row.immediate {
        ImmediateKind::Byte => Some(c.read()? as u32),
        ImmediateKind::None => None,
        _ => unreachable!("VEX rows have no other immediates"),
    };
    // destination, index and mask registers differ (gathers)
    let baseline_ud = row.vex & vex::UNIQUE != 0 && {
        let (reg, mask, index) = (modrm.unwrap() >> 3 & 7, v.vvvv, vsib_index());
        reg == index || mask == index || reg == mask
    };
    Ok(instruction(
        &c,
        row,
        modrm,
        modrm_offset,
        ea,
        immediate,
        baseline_ud,
        false,
        Some(v),
    ))
}

fn decode_ea(
    c: &mut Cursor<'_>,
    modrm: u8,
    size: u8,
    segment: Option<u8>,
) -> Result<EffectiveAddress, DecodeStop> {
    let sib = if size == 32 && modrm & 7 == 4 { Some(c.read()?) } else { None };
    let form = crate::decode_rules::address_form(modrm, size, sib);
    let displacement = if form.displacement_bytes == 1 {
        c.read()? as i8 as i32 as u32
    }
    else {
        c.integer(form.displacement_bytes)?
    };
    Ok(EffectiveAddress {
        base: form.base,
        index: form.index,
        scale: form.scale,
        displacement,
        address_size: size,
        segment: segment.unwrap_or(form.segment),
    })
}

#[cfg(test)]
#[path = "../../../tests/decode/decode.rs"]
mod tests;
                                                                                                                                     source/v64/src/rust/decode/encodings.rs                                                             0000644 0000000 0000000 00003555704 00000000000 015235  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by gen/generate_decoder.js. Do not edit.
use super::{Encoding, ImmediateKind};
use crate::decode_rules::vex;
#[rustfmt::skip]
pub static ENCODINGS: &[Encoding] = &[
    Encoding { id: 0, opcode: 0x0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 16, opcode: 0x1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 32, opcode: 0x2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 48, opcode: 0x3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64, opcode: 0x4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 80, opcode: 0x5, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 96, opcode: 0x6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 112, opcode: 0x7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 128, opcode: 0x8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 144, opcode: 0x9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 160, opcode: 0xA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 176, opcode: 0xB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 192, opcode: 0xC, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 208, opcode: 0xD, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 224, opcode: 0xE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 256, opcode: 0x10, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 272, opcode: 0x11, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 288, opcode: 0x12, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 304, opcode: 0x13, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 320, opcode: 0x14, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 336, opcode: 0x15, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 352, opcode: 0x16, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 368, opcode: 0x17, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 384, opcode: 0x18, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 400, opcode: 0x19, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 416, opcode: 0x1A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 432, opcode: 0x1B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 448, opcode: 0x1C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 464, opcode: 0x1D, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 480, opcode: 0x1E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 496, opcode: 0x1F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 512, opcode: 0x20, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 528, opcode: 0x21, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 544, opcode: 0x22, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 560, opcode: 0x23, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 576, opcode: 0x24, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 592, opcode: 0x25, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 624, opcode: 0x27, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 640, opcode: 0x28, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 656, opcode: 0x29, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 672, opcode: 0x2A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 688, opcode: 0x2B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 704, opcode: 0x2C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 720, opcode: 0x2D, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 752, opcode: 0x2F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 768, opcode: 0x30, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 784, opcode: 0x31, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 800, opcode: 0x32, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 816, opcode: 0x33, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 832, opcode: 0x34, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 848, opcode: 0x35, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 880, opcode: 0x37, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 896, opcode: 0x38, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 912, opcode: 0x39, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 928, opcode: 0x3A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 944, opcode: 0x3B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 960, opcode: 0x3C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 976, opcode: 0x3D, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1008, opcode: 0x3F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1024, opcode: 0x40, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1040, opcode: 0x41, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1056, opcode: 0x42, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1072, opcode: 0x43, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1088, opcode: 0x44, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1104, opcode: 0x45, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1120, opcode: 0x46, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1136, opcode: 0x47, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1152, opcode: 0x48, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1168, opcode: 0x49, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1184, opcode: 0x4A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1200, opcode: 0x4B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1216, opcode: 0x4C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1232, opcode: 0x4D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1248, opcode: 0x4E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1264, opcode: 0x4F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1280, opcode: 0x50, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1296, opcode: 0x51, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1312, opcode: 0x52, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1328, opcode: 0x53, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1344, opcode: 0x54, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1360, opcode: 0x55, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1376, opcode: 0x56, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1392, opcode: 0x57, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1408, opcode: 0x58, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1424, opcode: 0x59, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1440, opcode: 0x5A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1456, opcode: 0x5B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1472, opcode: 0x5C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1488, opcode: 0x5D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1504, opcode: 0x5E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1520, opcode: 0x5F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1536, opcode: 0x60, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1552, opcode: 0x61, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1568, opcode: 0x62, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1584, opcode: 0x63, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1664, opcode: 0x68, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1680, opcode: 0x69, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1696, opcode: 0x6A, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1712, opcode: 0x6B, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1728, opcode: 0x6C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 1744, opcode: 0x6D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 1760, opcode: 0x6E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 1776, opcode: 0x6F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 1792, opcode: 0x70, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1808, opcode: 0x71, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1824, opcode: 0x72, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1840, opcode: 0x73, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1856, opcode: 0x74, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1872, opcode: 0x75, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1888, opcode: 0x76, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1904, opcode: 0x77, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1920, opcode: 0x78, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1936, opcode: 0x79, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1952, opcode: 0x7A, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1968, opcode: 0x7B, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 1984, opcode: 0x7C, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2000, opcode: 0x7D, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2016, opcode: 0x7E, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2032, opcode: 0x7F, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2049, opcode: 0x80, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2050, opcode: 0x80, group: 1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2051, opcode: 0x80, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2052, opcode: 0x80, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2053, opcode: 0x80, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2054, opcode: 0x80, group: 5, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2055, opcode: 0x80, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2056, opcode: 0x80, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2065, opcode: 0x81, group: 0, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2066, opcode: 0x81, group: 1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2067, opcode: 0x81, group: 2, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2068, opcode: 0x81, group: 3, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2069, opcode: 0x81, group: 4, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2070, opcode: 0x81, group: 5, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2071, opcode: 0x81, group: 6, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2072, opcode: 0x81, group: 7, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2081, opcode: 0x82, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2082, opcode: 0x82, group: 1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2083, opcode: 0x82, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2084, opcode: 0x82, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2085, opcode: 0x82, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2086, opcode: 0x82, group: 5, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2087, opcode: 0x82, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2088, opcode: 0x82, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2097, opcode: 0x83, group: 0, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2098, opcode: 0x83, group: 1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2099, opcode: 0x83, group: 2, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2100, opcode: 0x83, group: 3, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2101, opcode: 0x83, group: 4, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2102, opcode: 0x83, group: 5, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2103, opcode: 0x83, group: 6, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2104, opcode: 0x83, group: 7, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2112, opcode: 0x84, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2128, opcode: 0x85, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2144, opcode: 0x86, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2160, opcode: 0x87, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2176, opcode: 0x88, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2192, opcode: 0x89, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2208, opcode: 0x8A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2224, opcode: 0x8B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2240, opcode: 0x8C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2256, opcode: 0x8D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2272, opcode: 0x8E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2289, opcode: 0x8F, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2290, opcode: 0x8F, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2291, opcode: 0x8F, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2292, opcode: 0x8F, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2293, opcode: 0x8F, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2294, opcode: 0x8F, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2295, opcode: 0x8F, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2296, opcode: 0x8F, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2304, opcode: 0x90, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2320, opcode: 0x91, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2336, opcode: 0x92, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2352, opcode: 0x93, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2368, opcode: 0x94, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2384, opcode: 0x95, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2400, opcode: 0x96, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2416, opcode: 0x97, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2432, opcode: 0x98, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2448, opcode: 0x99, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2464, opcode: 0x9A, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 2, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2480, opcode: 0x9B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2496, opcode: 0x9C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2512, opcode: 0x9D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2528, opcode: 0x9E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2544, opcode: 0x9F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2560, opcode: 0xA0, group: -1, immediate: ImmediateKind::Address, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2576, opcode: 0xA1, group: -1, immediate: ImmediateKind::Address, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2592, opcode: 0xA2, group: -1, immediate: ImmediateKind::Address, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2608, opcode: 0xA3, group: -1, immediate: ImmediateKind::Address, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2624, opcode: 0xA4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2640, opcode: 0xA5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2656, opcode: 0xA6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2672, opcode: 0xA7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2688, opcode: 0xA8, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2704, opcode: 0xA9, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2720, opcode: 0xAA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2736, opcode: 0xAB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2752, opcode: 0xAC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2768, opcode: 0xAD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2784, opcode: 0xAE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2800, opcode: 0xAF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 2816, opcode: 0xB0, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2832, opcode: 0xB1, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2848, opcode: 0xB2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2864, opcode: 0xB3, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2880, opcode: 0xB4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2896, opcode: 0xB5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2912, opcode: 0xB6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2928, opcode: 0xB7, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2944, opcode: 0xB8, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2960, opcode: 0xB9, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2976, opcode: 0xBA, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 2992, opcode: 0xBB, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3008, opcode: 0xBC, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3024, opcode: 0xBD, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3040, opcode: 0xBE, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3056, opcode: 0xBF, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3073, opcode: 0xC0, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3074, opcode: 0xC0, group: 1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3075, opcode: 0xC0, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3076, opcode: 0xC0, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3077, opcode: 0xC0, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3078, opcode: 0xC0, group: 5, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3079, opcode: 0xC0, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3080, opcode: 0xC0, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3089, opcode: 0xC1, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3090, opcode: 0xC1, group: 1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3091, opcode: 0xC1, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3092, opcode: 0xC1, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3093, opcode: 0xC1, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3094, opcode: 0xC1, group: 5, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3095, opcode: 0xC1, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3096, opcode: 0xC1, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3104, opcode: 0xC2, group: -1, immediate: ImmediateKind::Word, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: true, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3120, opcode: 0xC3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: true, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3136, opcode: 0xC4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3152, opcode: 0xC5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3169, opcode: 0xC6, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3170, opcode: 0xC6, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3171, opcode: 0xC6, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3172, opcode: 0xC6, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3173, opcode: 0xC6, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3174, opcode: 0xC6, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3175, opcode: 0xC6, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3176, opcode: 0xC6, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3185, opcode: 0xC7, group: 0, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3186, opcode: 0xC7, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3187, opcode: 0xC7, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3188, opcode: 0xC7, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3189, opcode: 0xC7, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3190, opcode: 0xC7, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3191, opcode: 0xC7, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3192, opcode: 0xC7, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3200, opcode: 0xC8, group: -1, immediate: ImmediateKind::Word, extra_bytes: 1, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3216, opcode: 0xC9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3232, opcode: 0xCA, group: -1, immediate: ImmediateKind::Word, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3248, opcode: 0xCB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3264, opcode: 0xCC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3280, opcode: 0xCD, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3296, opcode: 0xCE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3312, opcode: 0xCF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3329, opcode: 0xD0, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3330, opcode: 0xD0, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3331, opcode: 0xD0, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3332, opcode: 0xD0, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3333, opcode: 0xD0, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3334, opcode: 0xD0, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3335, opcode: 0xD0, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3336, opcode: 0xD0, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3345, opcode: 0xD1, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3346, opcode: 0xD1, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3347, opcode: 0xD1, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3348, opcode: 0xD1, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3349, opcode: 0xD1, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3350, opcode: 0xD1, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3351, opcode: 0xD1, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3352, opcode: 0xD1, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3361, opcode: 0xD2, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3362, opcode: 0xD2, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3363, opcode: 0xD2, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3364, opcode: 0xD2, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3365, opcode: 0xD2, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3366, opcode: 0xD2, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3367, opcode: 0xD2, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3368, opcode: 0xD2, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3377, opcode: 0xD3, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3378, opcode: 0xD3, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3379, opcode: 0xD3, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3380, opcode: 0xD3, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3381, opcode: 0xD3, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3382, opcode: 0xD3, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3383, opcode: 0xD3, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3384, opcode: 0xD3, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3392, opcode: 0xD4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3408, opcode: 0xD5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3424, opcode: 0xD6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3440, opcode: 0xD7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3457, opcode: 0xD8, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3458, opcode: 0xD8, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3459, opcode: 0xD8, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3460, opcode: 0xD8, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3461, opcode: 0xD8, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3462, opcode: 0xD8, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3463, opcode: 0xD8, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3464, opcode: 0xD8, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3473, opcode: 0xD9, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3474, opcode: 0xD9, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3475, opcode: 0xD9, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3476, opcode: 0xD9, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3477, opcode: 0xD9, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3478, opcode: 0xD9, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3479, opcode: 0xD9, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3480, opcode: 0xD9, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3489, opcode: 0xDA, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3490, opcode: 0xDA, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3491, opcode: 0xDA, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3492, opcode: 0xDA, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3493, opcode: 0xDA, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3494, opcode: 0xDA, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3495, opcode: 0xDA, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3496, opcode: 0xDA, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3505, opcode: 0xDB, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3506, opcode: 0xDB, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3507, opcode: 0xDB, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3508, opcode: 0xDB, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3509, opcode: 0xDB, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3510, opcode: 0xDB, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3511, opcode: 0xDB, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3512, opcode: 0xDB, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3521, opcode: 0xDC, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3522, opcode: 0xDC, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3523, opcode: 0xDC, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3524, opcode: 0xDC, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3525, opcode: 0xDC, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3526, opcode: 0xDC, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3527, opcode: 0xDC, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3528, opcode: 0xDC, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3537, opcode: 0xDD, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3538, opcode: 0xDD, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3539, opcode: 0xDD, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3540, opcode: 0xDD, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3541, opcode: 0xDD, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3542, opcode: 0xDD, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3543, opcode: 0xDD, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3544, opcode: 0xDD, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3553, opcode: 0xDE, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3554, opcode: 0xDE, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3555, opcode: 0xDE, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3556, opcode: 0xDE, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3557, opcode: 0xDE, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3558, opcode: 0xDE, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3559, opcode: 0xDE, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3560, opcode: 0xDE, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3569, opcode: 0xDF, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3570, opcode: 0xDF, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3571, opcode: 0xDF, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3572, opcode: 0xDF, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3573, opcode: 0xDF, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3574, opcode: 0xDF, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3575, opcode: 0xDF, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3576, opcode: 0xDF, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: true, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3584, opcode: 0xE0, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3600, opcode: 0xE1, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3616, opcode: 0xE2, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3632, opcode: 0xE3, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3648, opcode: 0xE4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3664, opcode: 0xE5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3680, opcode: 0xE6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3696, opcode: 0xE7, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3712, opcode: 0xE8, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3728, opcode: 0xE9, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: true, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3744, opcode: 0xEA, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 2, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3760, opcode: 0xEB, group: -1, immediate: ImmediateKind::SignedByte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: true, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3776, opcode: 0xEC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3792, opcode: 0xED, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3808, opcode: 0xEE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3824, opcode: 0xEF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3856, opcode: 0xF1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3904, opcode: 0xF4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3920, opcode: 0xF5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3937, opcode: 0xF6, group: 0, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3938, opcode: 0xF6, group: 1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3939, opcode: 0xF6, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3940, opcode: 0xF6, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3941, opcode: 0xF6, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3942, opcode: 0xF6, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3943, opcode: 0xF6, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3944, opcode: 0xF6, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3953, opcode: 0xF7, group: 0, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3954, opcode: 0xF7, group: 1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3955, opcode: 0xF7, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3956, opcode: 0xF7, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3957, opcode: 0xF7, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3958, opcode: 0xF7, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3959, opcode: 0xF7, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3960, opcode: 0xF7, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3968, opcode: 0xF8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 3984, opcode: 0xF9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4000, opcode: 0xFA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4016, opcode: 0xFB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: true, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4032, opcode: 0xFC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4048, opcode: 0xFD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4065, opcode: 0xFE, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4066, opcode: 0xFE, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4067, opcode: 0xFE, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4068, opcode: 0xFE, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4069, opcode: 0xFE, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4070, opcode: 0xFE, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4071, opcode: 0xFE, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4072, opcode: 0xFE, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4081, opcode: 0xFF, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4082, opcode: 0xFF, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4083, opcode: 0xFF, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: true, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4084, opcode: 0xFF, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4085, opcode: 0xFF, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: true, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4086, opcode: 0xFF, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4087, opcode: 0xFF, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 4088, opcode: 0xFF, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61441, opcode: 0xF00, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61442, opcode: 0xF00, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61443, opcode: 0xF00, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61444, opcode: 0xF00, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61445, opcode: 0xF00, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61446, opcode: 0xF00, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61447, opcode: 0xF00, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61448, opcode: 0xF00, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61457, opcode: 0xF01, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61458, opcode: 0xF01, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61459, opcode: 0xF01, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61460, opcode: 0xF01, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61461, opcode: 0xF01, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61462, opcode: 0xF01, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61463, opcode: 0xF01, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61464, opcode: 0xF01, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61472, opcode: 0xF02, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61488, opcode: 0xF03, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61504, opcode: 0xF04, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61520, opcode: 0xF05, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61536, opcode: 0xF06, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61552, opcode: 0xF07, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61568, opcode: 0xF08, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61584, opcode: 0xF09, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61600, opcode: 0xF0A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61616, opcode: 0xF0B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61632, opcode: 0xF0C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61648, opcode: 0xF0D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61664, opcode: 0xF0E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61680, opcode: 0xF0F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61696, opcode: 0xF10, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61712, opcode: 0xF11, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61728, opcode: 0xF12, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61744, opcode: 0xF13, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61760, opcode: 0xF14, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61776, opcode: 0xF15, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61792, opcode: 0xF16, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61808, opcode: 0xF17, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61824, opcode: 0xF18, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61840, opcode: 0xF19, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61856, opcode: 0xF1A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61872, opcode: 0xF1B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61888, opcode: 0xF1C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61904, opcode: 0xF1D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61920, opcode: 0xF1E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61936, opcode: 0xF1F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61952, opcode: 0xF20, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: true, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61968, opcode: 0xF21, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: true, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 61984, opcode: 0xF22, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: true, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62000, opcode: 0xF23, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: true, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62016, opcode: 0xF24, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62032, opcode: 0xF25, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62048, opcode: 0xF26, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62064, opcode: 0xF27, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62080, opcode: 0xF28, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62096, opcode: 0xF29, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62112, opcode: 0xF2A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62128, opcode: 0xF2B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62144, opcode: 0xF2C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62160, opcode: 0xF2D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62176, opcode: 0xF2E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62192, opcode: 0xF2F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62208, opcode: 0xF30, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62224, opcode: 0xF31, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62240, opcode: 0xF32, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62256, opcode: 0xF33, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62272, opcode: 0xF34, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62288, opcode: 0xF35, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62304, opcode: 0xF36, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62320, opcode: 0xF37, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62352, opcode: 0xF39, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62384, opcode: 0xF3B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62400, opcode: 0xF3C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62416, opcode: 0xF3D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62432, opcode: 0xF3E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62448, opcode: 0xF3F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62464, opcode: 0xF40, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62480, opcode: 0xF41, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62496, opcode: 0xF42, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62512, opcode: 0xF43, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62528, opcode: 0xF44, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62544, opcode: 0xF45, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62560, opcode: 0xF46, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62576, opcode: 0xF47, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62592, opcode: 0xF48, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62608, opcode: 0xF49, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62624, opcode: 0xF4A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62640, opcode: 0xF4B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62656, opcode: 0xF4C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62672, opcode: 0xF4D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62688, opcode: 0xF4E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62704, opcode: 0xF4F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62720, opcode: 0xF50, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62736, opcode: 0xF51, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62752, opcode: 0xF52, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62768, opcode: 0xF53, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62784, opcode: 0xF54, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62800, opcode: 0xF55, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62816, opcode: 0xF56, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62832, opcode: 0xF57, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62848, opcode: 0xF58, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62864, opcode: 0xF59, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62880, opcode: 0xF5A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62896, opcode: 0xF5B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62912, opcode: 0xF5C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62928, opcode: 0xF5D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62944, opcode: 0xF5E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62960, opcode: 0xF5F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 62976, opcode: 0xF60, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 62992, opcode: 0xF61, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63008, opcode: 0xF62, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63024, opcode: 0xF63, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63040, opcode: 0xF64, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63056, opcode: 0xF65, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63072, opcode: 0xF66, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63088, opcode: 0xF67, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63104, opcode: 0xF68, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63120, opcode: 0xF69, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63136, opcode: 0xF6A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63152, opcode: 0xF6B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63168, opcode: 0xF6C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63184, opcode: 0xF6D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63200, opcode: 0xF6E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63216, opcode: 0xF6F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63232, opcode: 0xF70, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63249, opcode: 0xF71, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63250, opcode: 0xF71, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63251, opcode: 0xF71, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63252, opcode: 0xF71, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63253, opcode: 0xF71, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63254, opcode: 0xF71, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63255, opcode: 0xF71, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63256, opcode: 0xF71, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63265, opcode: 0xF72, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63266, opcode: 0xF72, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63267, opcode: 0xF72, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63268, opcode: 0xF72, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63269, opcode: 0xF72, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63270, opcode: 0xF72, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63271, opcode: 0xF72, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63272, opcode: 0xF72, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63281, opcode: 0xF73, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63282, opcode: 0xF73, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63283, opcode: 0xF73, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63284, opcode: 0xF73, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63285, opcode: 0xF73, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63286, opcode: 0xF73, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63287, opcode: 0xF73, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63288, opcode: 0xF73, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63296, opcode: 0xF74, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63312, opcode: 0xF75, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63328, opcode: 0xF76, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63344, opcode: 0xF77, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63360, opcode: 0xF78, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63376, opcode: 0xF79, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63392, opcode: 0xF7A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63408, opcode: 0xF7B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63424, opcode: 0xF7C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63440, opcode: 0xF7D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63456, opcode: 0xF7E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63472, opcode: 0xF7F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 63488, opcode: 0xF80, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63504, opcode: 0xF81, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63520, opcode: 0xF82, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63536, opcode: 0xF83, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63552, opcode: 0xF84, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63568, opcode: 0xF85, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63584, opcode: 0xF86, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63600, opcode: 0xF87, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63616, opcode: 0xF88, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63632, opcode: 0xF89, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63648, opcode: 0xF8A, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63664, opcode: 0xF8B, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63680, opcode: 0xF8C, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63696, opcode: 0xF8D, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63712, opcode: 0xF8E, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63728, opcode: 0xF8F, group: -1, immediate: ImmediateKind::Operand, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: true, conditional_jump: true, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63744, opcode: 0xF90, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63760, opcode: 0xF91, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63776, opcode: 0xF92, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63792, opcode: 0xF93, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63808, opcode: 0xF94, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63824, opcode: 0xF95, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63840, opcode: 0xF96, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63856, opcode: 0xF97, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63872, opcode: 0xF98, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63888, opcode: 0xF99, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63904, opcode: 0xF9A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63920, opcode: 0xF9B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63936, opcode: 0xF9C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63952, opcode: 0xF9D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63968, opcode: 0xF9E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 63984, opcode: 0xF9F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64000, opcode: 0xFA0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64016, opcode: 0xFA1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64032, opcode: 0xFA2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64048, opcode: 0xFA3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64064, opcode: 0xFA4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64080, opcode: 0xFA5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64096, opcode: 0xFA6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64112, opcode: 0xFA7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64128, opcode: 0xFA8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64144, opcode: 0xFA9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64160, opcode: 0xFAA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64176, opcode: 0xFAB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64192, opcode: 0xFAC, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64208, opcode: 0xFAD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64225, opcode: 0xFAE, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64226, opcode: 0xFAE, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: true, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64227, opcode: 0xFAE, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64228, opcode: 0xFAE, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64229, opcode: 0xFAE, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64230, opcode: 0xFAE, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64231, opcode: 0xFAE, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64232, opcode: 0xFAE, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64240, opcode: 0xFAF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64256, opcode: 0xFB0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64272, opcode: 0xFB1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64288, opcode: 0xFB2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64304, opcode: 0xFB3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64320, opcode: 0xFB4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64336, opcode: 0xFB5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64352, opcode: 0xFB6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64368, opcode: 0xFB7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64384, opcode: 0xFB8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64400, opcode: 0xFB9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64417, opcode: 0xFBA, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64418, opcode: 0xFBA, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64419, opcode: 0xFBA, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64420, opcode: 0xFBA, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64421, opcode: 0xFBA, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64422, opcode: 0xFBA, group: 5, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64423, opcode: 0xFBA, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64424, opcode: 0xFBA, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64432, opcode: 0xFBB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64448, opcode: 0xFBC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64464, opcode: 0xFBD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64480, opcode: 0xFBE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64496, opcode: 0xFBF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64512, opcode: 0xFC0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64528, opcode: 0xFC1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64544, opcode: 0xFC2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64560, opcode: 0xFC3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64576, opcode: 0xFC4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64592, opcode: 0xFC5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64608, opcode: 0xFC6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64625, opcode: 0xFC7, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64626, opcode: 0xFC7, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64627, opcode: 0xFC7, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64628, opcode: 0xFC7, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::XSAVES, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64629, opcode: 0xFC7, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::XSAVEC, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64630, opcode: 0xFC7, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::XSAVES, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64631, opcode: 0xFC7, group: 6, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64632, opcode: 0xFC7, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64640, opcode: 0xFC8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64656, opcode: 0xFC9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64672, opcode: 0xFCA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64688, opcode: 0xFCB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64704, opcode: 0xFCC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64720, opcode: 0xFCD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64736, opcode: 0xFCE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64752, opcode: 0xFCF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64768, opcode: 0xFD0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 64784, opcode: 0xFD1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64800, opcode: 0xFD2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64816, opcode: 0xFD3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64832, opcode: 0xFD4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64848, opcode: 0xFD5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64864, opcode: 0xFD6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64880, opcode: 0xFD7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64896, opcode: 0xFD8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64912, opcode: 0xFD9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64928, opcode: 0xFDA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64944, opcode: 0xFDB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64960, opcode: 0xFDC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64976, opcode: 0xFDD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 64992, opcode: 0xFDE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65008, opcode: 0xFDF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65024, opcode: 0xFE0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65040, opcode: 0xFE1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65056, opcode: 0xFE2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65072, opcode: 0xFE3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65088, opcode: 0xFE4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65104, opcode: 0xFE5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65120, opcode: 0xFE6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65136, opcode: 0xFE7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65152, opcode: 0xFE8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65168, opcode: 0xFE9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65184, opcode: 0xFEA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65200, opcode: 0xFEB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65216, opcode: 0xFEC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65232, opcode: 0xFED, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65248, opcode: 0xFEE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65264, opcode: 0xFEF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65280, opcode: 0xFF0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 65296, opcode: 0xFF1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65312, opcode: 0xFF2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65328, opcode: 0xFF3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65344, opcode: 0xFF4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65360, opcode: 0xFF5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65376, opcode: 0xFF6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65392, opcode: 0xFF7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65408, opcode: 0xFF8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65424, opcode: 0xFF9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65440, opcode: 0xFFA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65456, opcode: 0xFFB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65472, opcode: 0xFFC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65488, opcode: 0xFFD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65504, opcode: 0xFFE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 65520, opcode: 0xFFF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: false, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 992960, opcode: 0xF26C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 992976, opcode: 0xF26D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 992992, opcode: 0xF26E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993008, opcode: 0xF26F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993856, opcode: 0xF2A4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993872, opcode: 0xF2A5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993888, opcode: 0xF2A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993904, opcode: 0xF2A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993952, opcode: 0xF2AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993968, opcode: 0xF2AB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 993984, opcode: 0xF2AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 994000, opcode: 0xF2AD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 994016, opcode: 0xF2AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 994032, opcode: 0xF2AF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997056, opcode: 0xF36C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997072, opcode: 0xF36D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997088, opcode: 0xF36E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997104, opcode: 0xF36F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997952, opcode: 0xF3A4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997968, opcode: 0xF3A5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 997984, opcode: 0xF3A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998000, opcode: 0xF3A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998048, opcode: 0xF3AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998064, opcode: 0xF3AB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998080, opcode: 0xF3AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998096, opcode: 0xF3AD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998112, opcode: 0xF3AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 998128, opcode: 0xF3AF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: true, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: true, unimplemented: false },
    Encoding { id: 268435456, opcode: 0xF3800, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435472, opcode: 0xF3801, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435488, opcode: 0xF3802, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435504, opcode: 0xF3803, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435520, opcode: 0xF3804, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435536, opcode: 0xF3805, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435552, opcode: 0xF3806, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435568, opcode: 0xF3807, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435584, opcode: 0xF3808, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435600, opcode: 0xF3809, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435616, opcode: 0xF380A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435632, opcode: 0xF380B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435904, opcode: 0xF381C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435920, opcode: 0xF381D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268435936, opcode: 0xF381E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 268439296, opcode: 0xF38F0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_REP, feature: crate::cpu::features::MOVBE, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439312, opcode: 0xF38F1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_REP, feature: crate::cpu::features::MOVBE, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268452080, opcode: 0xF3A0F, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: true, is_string: false, unimplemented: false },
    Encoding { id: 107016448, opcode: 0x660F10, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016464, opcode: 0x660F11, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016480, opcode: 0x660F12, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016496, opcode: 0x660F13, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016512, opcode: 0x660F14, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016528, opcode: 0x660F15, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016544, opcode: 0x660F16, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016560, opcode: 0x660F17, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016832, opcode: 0x660F28, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016848, opcode: 0x660F29, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016864, opcode: 0x660F2A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016880, opcode: 0x660F2B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016896, opcode: 0x660F2C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016912, opcode: 0x660F2D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016928, opcode: 0x660F2E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107016944, opcode: 0x660F2F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017472, opcode: 0x660F50, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017488, opcode: 0x660F51, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017536, opcode: 0x660F54, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017552, opcode: 0x660F55, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017568, opcode: 0x660F56, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017584, opcode: 0x660F57, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017600, opcode: 0x660F58, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017616, opcode: 0x660F59, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017632, opcode: 0x660F5A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017648, opcode: 0x660F5B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017664, opcode: 0x660F5C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017680, opcode: 0x660F5D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017696, opcode: 0x660F5E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017712, opcode: 0x660F5F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017728, opcode: 0x660F60, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017744, opcode: 0x660F61, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017760, opcode: 0x660F62, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017776, opcode: 0x660F63, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017792, opcode: 0x660F64, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017808, opcode: 0x660F65, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017824, opcode: 0x660F66, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017840, opcode: 0x660F67, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017856, opcode: 0x660F68, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017872, opcode: 0x660F69, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017888, opcode: 0x660F6A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017904, opcode: 0x660F6B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017920, opcode: 0x660F6C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017936, opcode: 0x660F6D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017952, opcode: 0x660F6E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017968, opcode: 0x660F6F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107017984, opcode: 0x660F70, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018001, opcode: 0x660F71, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018002, opcode: 0x660F71, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018003, opcode: 0x660F71, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018004, opcode: 0x660F71, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018005, opcode: 0x660F71, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018006, opcode: 0x660F71, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018007, opcode: 0x660F71, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018008, opcode: 0x660F71, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018017, opcode: 0x660F72, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018018, opcode: 0x660F72, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018019, opcode: 0x660F72, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018020, opcode: 0x660F72, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018021, opcode: 0x660F72, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018022, opcode: 0x660F72, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018023, opcode: 0x660F72, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018024, opcode: 0x660F72, group: 7, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018033, opcode: 0x660F73, group: 0, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018034, opcode: 0x660F73, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018035, opcode: 0x660F73, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018036, opcode: 0x660F73, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018037, opcode: 0x660F73, group: 4, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018038, opcode: 0x660F73, group: 5, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: true, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: true, mem_ud: true, os: false, block_boundary: true, no_next_instruction: true, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018039, opcode: 0x660F73, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018040, opcode: 0x660F73, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018048, opcode: 0x660F74, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018064, opcode: 0x660F75, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018080, opcode: 0x660F76, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018176, opcode: 0x660F7C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018192, opcode: 0x660F7D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018208, opcode: 0x660F7E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107018224, opcode: 0x660F7F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019296, opcode: 0x660FC2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019328, opcode: 0x660FC4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019344, opcode: 0x660FC5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019360, opcode: 0x660FC6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019520, opcode: 0x660FD0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019536, opcode: 0x660FD1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019552, opcode: 0x660FD2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019568, opcode: 0x660FD3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019584, opcode: 0x660FD4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019600, opcode: 0x660FD5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019616, opcode: 0x660FD6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019632, opcode: 0x660FD7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019648, opcode: 0x660FD8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019664, opcode: 0x660FD9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019680, opcode: 0x660FDA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019696, opcode: 0x660FDB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019712, opcode: 0x660FDC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019728, opcode: 0x660FDD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019744, opcode: 0x660FDE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019760, opcode: 0x660FDF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019776, opcode: 0x660FE0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019792, opcode: 0x660FE1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019808, opcode: 0x660FE2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019824, opcode: 0x660FE3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019840, opcode: 0x660FE4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019856, opcode: 0x660FE5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019872, opcode: 0x660FE6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019888, opcode: 0x660FE7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019904, opcode: 0x660FE8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019920, opcode: 0x660FE9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019936, opcode: 0x660FEA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019952, opcode: 0x660FEB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019968, opcode: 0x660FEC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107019984, opcode: 0x660FED, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020000, opcode: 0x660FEE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020016, opcode: 0x660FEF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020048, opcode: 0x660FF1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020064, opcode: 0x660FF2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020080, opcode: 0x660FF3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020096, opcode: 0x660FF4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020112, opcode: 0x660FF5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020128, opcode: 0x660FF6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020144, opcode: 0x660FF7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020160, opcode: 0x660FF8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020176, opcode: 0x660FF9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020192, opcode: 0x660FFA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020208, opcode: 0x660FFB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020224, opcode: 0x660FFC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020240, opcode: 0x660FFD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 107020256, opcode: 0x660FFE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817088, opcode: 0xF20F10, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817104, opcode: 0xF20F11, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817120, opcode: 0xF20F12, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817504, opcode: 0xF20F2A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817536, opcode: 0xF20F2C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253817552, opcode: 0xF20F2D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818128, opcode: 0xF20F51, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818240, opcode: 0xF20F58, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818256, opcode: 0xF20F59, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818272, opcode: 0xF20F5A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818304, opcode: 0xF20F5C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818320, opcode: 0xF20F5D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818336, opcode: 0xF20F5E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818352, opcode: 0xF20F5F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818624, opcode: 0xF20F70, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818816, opcode: 0xF20F7C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253818832, opcode: 0xF20F7D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253819936, opcode: 0xF20FC2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253820160, opcode: 0xF20FD0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253820256, opcode: 0xF20FD6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253820512, opcode: 0xF20FE6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 253820672, opcode: 0xF20FF0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254865664, opcode: 0xF30F10, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254865680, opcode: 0xF30F11, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254865696, opcode: 0xF30F12, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254865760, opcode: 0xF30F16, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866080, opcode: 0xF30F2A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866112, opcode: 0xF30F2C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866128, opcode: 0xF30F2D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866704, opcode: 0xF30F51, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866720, opcode: 0xF30F52, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866736, opcode: 0xF30F53, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866816, opcode: 0xF30F58, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866832, opcode: 0xF30F59, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866848, opcode: 0xF30F5A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866864, opcode: 0xF30F5B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866880, opcode: 0xF30F5C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866896, opcode: 0xF30F5D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866912, opcode: 0xF30F5E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254866928, opcode: 0xF30F5F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254867184, opcode: 0xF30F6F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254867200, opcode: 0xF30F70, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254867424, opcode: 0xF30F7E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254867440, opcode: 0xF30F7F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254868352, opcode: 0xF30FB8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254868416, opcode: 0xF30FBC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254868432, opcode: 0xF30FBD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::LZCNT, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254868512, opcode: 0xF30FC2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254868832, opcode: 0xF30FD6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 254869088, opcode: 0xF30FE6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: 0, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439552, opcode: 0x660F3800, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439568, opcode: 0x660F3801, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439584, opcode: 0x660F3802, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439600, opcode: 0x660F3803, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439616, opcode: 0x660F3804, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439632, opcode: 0x660F3805, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439648, opcode: 0x660F3806, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439664, opcode: 0x660F3807, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439680, opcode: 0x660F3808, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439696, opcode: 0x660F3809, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439712, opcode: 0x660F380A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439728, opcode: 0x660F380B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439808, opcode: 0x660F3810, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439872, opcode: 0x660F3814, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439888, opcode: 0x660F3815, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268439920, opcode: 0x660F3817, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440000, opcode: 0x660F381C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440016, opcode: 0x660F381D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440032, opcode: 0x660F381E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440064, opcode: 0x660F3820, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440080, opcode: 0x660F3821, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440096, opcode: 0x660F3822, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440112, opcode: 0x660F3823, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440128, opcode: 0x660F3824, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440144, opcode: 0x660F3825, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440192, opcode: 0x660F3828, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440208, opcode: 0x660F3829, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440224, opcode: 0x660F382A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440240, opcode: 0x660F382B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440320, opcode: 0x660F3830, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440336, opcode: 0x660F3831, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440352, opcode: 0x660F3832, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440368, opcode: 0x660F3833, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440384, opcode: 0x660F3834, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440400, opcode: 0x660F3835, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440432, opcode: 0x660F3837, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440448, opcode: 0x660F3838, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440464, opcode: 0x660F3839, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440480, opcode: 0x660F383A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440496, opcode: 0x660F383B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440512, opcode: 0x660F383C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440528, opcode: 0x660F383D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440544, opcode: 0x660F383E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440560, opcode: 0x660F383F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440576, opcode: 0x660F3840, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268440592, opcode: 0x660F3841, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456064, opcode: 0x660F3A08, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456080, opcode: 0x660F3A09, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456096, opcode: 0x660F3A0A, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456112, opcode: 0x660F3A0B, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456128, opcode: 0x660F3A0C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456144, opcode: 0x660F3A0D, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456160, opcode: 0x660F3A0E, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456176, opcode: 0x660F3A0F, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSSE3, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456256, opcode: 0x660F3A14, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456272, opcode: 0x660F3A15, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456288, opcode: 0x660F3A16, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456304, opcode: 0x660F3A17, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456448, opcode: 0x660F3A20, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456464, opcode: 0x660F3A21, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456480, opcode: 0x660F3A22, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456960, opcode: 0x660F3A40, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456976, opcode: 0x660F3A41, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268456992, opcode: 0x660F3A42, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_1, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268457472, opcode: 0x660F3A60, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268457488, opcode: 0x660F3A61, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268457504, opcode: 0x660F3A62, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268457520, opcode: 0x660F3A63, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: crate::decode_rules::REFINING_ALL, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: true, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871168, opcode: 0xC4010010, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871169, opcode: 0xC4010010, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871184, opcode: 0xC4010011, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871185, opcode: 0xC4010011, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871200, opcode: 0xC4010012, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871201, opcode: 0xC4010012, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871216, opcode: 0xC4010013, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871232, opcode: 0xC4010014, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871233, opcode: 0xC4010014, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871248, opcode: 0xC4010015, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871249, opcode: 0xC4010015, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871264, opcode: 0xC4010016, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871265, opcode: 0xC4010016, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871280, opcode: 0xC4010017, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871552, opcode: 0xC4010028, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871553, opcode: 0xC4010028, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871568, opcode: 0xC4010029, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871569, opcode: 0xC4010029, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871600, opcode: 0xC401002B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871601, opcode: 0xC401002B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871648, opcode: 0xC401002E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536871664, opcode: 0xC401002F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872192, opcode: 0xC4010050, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872193, opcode: 0xC4010050, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872194, opcode: 0xC4010050, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872195, opcode: 0xC4010050, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872208, opcode: 0xC4010051, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872209, opcode: 0xC4010051, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872224, opcode: 0xC4010052, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872225, opcode: 0xC4010052, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872240, opcode: 0xC4010053, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872241, opcode: 0xC4010053, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872256, opcode: 0xC4010054, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872257, opcode: 0xC4010054, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872272, opcode: 0xC4010055, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872273, opcode: 0xC4010055, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872288, opcode: 0xC4010056, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872289, opcode: 0xC4010056, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872304, opcode: 0xC4010057, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872305, opcode: 0xC4010057, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872320, opcode: 0xC4010058, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872321, opcode: 0xC4010058, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872336, opcode: 0xC4010059, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872337, opcode: 0xC4010059, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872352, opcode: 0xC401005A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872353, opcode: 0xC401005A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872368, opcode: 0xC401005B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872369, opcode: 0xC401005B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872384, opcode: 0xC401005C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872385, opcode: 0xC401005C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872400, opcode: 0xC401005D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872401, opcode: 0xC401005D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872416, opcode: 0xC401005E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872417, opcode: 0xC401005E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872432, opcode: 0xC401005F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872433, opcode: 0xC401005F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872816, opcode: 0xC4010077, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536872817, opcode: 0xC4010077, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: false, group_ud: false, task_switch_test: false, custom: true, e: false, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536873696, opcode: 0xC40100AE, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536873697, opcode: 0xC40100AE, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536874016, opcode: 0xC40100C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536874017, opcode: 0xC40100C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536874080, opcode: 0xC40100C6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536874081, opcode: 0xC40100C6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875264, opcode: 0xC4010110, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875265, opcode: 0xC4010110, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875280, opcode: 0xC4010111, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875281, opcode: 0xC4010111, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875296, opcode: 0xC4010112, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875312, opcode: 0xC4010113, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875328, opcode: 0xC4010114, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875329, opcode: 0xC4010114, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875344, opcode: 0xC4010115, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875345, opcode: 0xC4010115, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875360, opcode: 0xC4010116, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875376, opcode: 0xC4010117, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875648, opcode: 0xC4010128, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875649, opcode: 0xC4010128, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875664, opcode: 0xC4010129, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875665, opcode: 0xC4010129, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875696, opcode: 0xC401012B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875697, opcode: 0xC401012B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875744, opcode: 0xC401012E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536875760, opcode: 0xC401012F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876288, opcode: 0xC4010150, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876289, opcode: 0xC4010150, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876290, opcode: 0xC4010150, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876291, opcode: 0xC4010150, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876304, opcode: 0xC4010151, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876305, opcode: 0xC4010151, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876352, opcode: 0xC4010154, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876353, opcode: 0xC4010154, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876368, opcode: 0xC4010155, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876369, opcode: 0xC4010155, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876384, opcode: 0xC4010156, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876385, opcode: 0xC4010156, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876400, opcode: 0xC4010157, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876401, opcode: 0xC4010157, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876416, opcode: 0xC4010158, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876417, opcode: 0xC4010158, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876432, opcode: 0xC4010159, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876433, opcode: 0xC4010159, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876448, opcode: 0xC401015A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876449, opcode: 0xC401015A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876464, opcode: 0xC401015B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876465, opcode: 0xC401015B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876480, opcode: 0xC401015C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876481, opcode: 0xC401015C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876496, opcode: 0xC401015D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876497, opcode: 0xC401015D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876512, opcode: 0xC401015E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876513, opcode: 0xC401015E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876528, opcode: 0xC401015F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876529, opcode: 0xC401015F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876544, opcode: 0xC4010160, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876545, opcode: 0xC4010160, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876560, opcode: 0xC4010161, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876561, opcode: 0xC4010161, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876576, opcode: 0xC4010162, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876577, opcode: 0xC4010162, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876592, opcode: 0xC4010163, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876593, opcode: 0xC4010163, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876608, opcode: 0xC4010164, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876609, opcode: 0xC4010164, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876624, opcode: 0xC4010165, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876625, opcode: 0xC4010165, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876640, opcode: 0xC4010166, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876641, opcode: 0xC4010166, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876656, opcode: 0xC4010167, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876657, opcode: 0xC4010167, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876672, opcode: 0xC4010168, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876673, opcode: 0xC4010168, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876688, opcode: 0xC4010169, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876689, opcode: 0xC4010169, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876704, opcode: 0xC401016A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876705, opcode: 0xC401016A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876720, opcode: 0xC401016B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876721, opcode: 0xC401016B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876736, opcode: 0xC401016C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876737, opcode: 0xC401016C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876752, opcode: 0xC401016D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876753, opcode: 0xC401016D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876768, opcode: 0xC401016E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876769, opcode: 0xC401016E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876784, opcode: 0xC401016F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876785, opcode: 0xC401016F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876800, opcode: 0xC4010170, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876801, opcode: 0xC4010170, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876816, opcode: 0xC4010171, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876817, opcode: 0xC4010171, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876818, opcode: 0xC4010171, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876819, opcode: 0xC4010171, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876820, opcode: 0xC4010171, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876821, opcode: 0xC4010171, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876832, opcode: 0xC4010172, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876833, opcode: 0xC4010172, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876834, opcode: 0xC4010172, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876835, opcode: 0xC4010172, group: 4, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876836, opcode: 0xC4010172, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876837, opcode: 0xC4010172, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876848, opcode: 0xC4010173, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876849, opcode: 0xC4010173, group: 2, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876850, opcode: 0xC4010173, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876851, opcode: 0xC4010173, group: 3, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876852, opcode: 0xC4010173, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876853, opcode: 0xC4010173, group: 6, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876854, opcode: 0xC4010173, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876855, opcode: 0xC4010173, group: 7, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876864, opcode: 0xC4010174, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876865, opcode: 0xC4010174, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876880, opcode: 0xC4010175, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876881, opcode: 0xC4010175, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876896, opcode: 0xC4010176, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876897, opcode: 0xC4010176, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876992, opcode: 0xC401017C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536876993, opcode: 0xC401017C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877008, opcode: 0xC401017D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877009, opcode: 0xC401017D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877024, opcode: 0xC401017E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877025, opcode: 0xC401017E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877040, opcode: 0xC401017F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536877041, opcode: 0xC401017F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878112, opcode: 0xC40101C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878113, opcode: 0xC40101C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878144, opcode: 0xC40101C4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878145, opcode: 0xC40101C4, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878160, opcode: 0xC40101C5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878161, opcode: 0xC40101C5, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878176, opcode: 0xC40101C6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878177, opcode: 0xC40101C6, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878336, opcode: 0xC40101D0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878337, opcode: 0xC40101D0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878352, opcode: 0xC40101D1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878353, opcode: 0xC40101D1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878368, opcode: 0xC40101D2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878369, opcode: 0xC40101D2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878384, opcode: 0xC40101D3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878385, opcode: 0xC40101D3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878400, opcode: 0xC40101D4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878401, opcode: 0xC40101D4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878416, opcode: 0xC40101D5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878417, opcode: 0xC40101D5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878432, opcode: 0xC40101D6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878448, opcode: 0xC40101D7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878449, opcode: 0xC40101D7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878450, opcode: 0xC40101D7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878451, opcode: 0xC40101D7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878464, opcode: 0xC40101D8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878465, opcode: 0xC40101D8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878480, opcode: 0xC40101D9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878481, opcode: 0xC40101D9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878496, opcode: 0xC40101DA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878497, opcode: 0xC40101DA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878512, opcode: 0xC40101DB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878513, opcode: 0xC40101DB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878528, opcode: 0xC40101DC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878529, opcode: 0xC40101DC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878544, opcode: 0xC40101DD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878545, opcode: 0xC40101DD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878560, opcode: 0xC40101DE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878561, opcode: 0xC40101DE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878576, opcode: 0xC40101DF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878577, opcode: 0xC40101DF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878592, opcode: 0xC40101E0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878593, opcode: 0xC40101E0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878608, opcode: 0xC40101E1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878609, opcode: 0xC40101E1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878624, opcode: 0xC40101E2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878625, opcode: 0xC40101E2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878640, opcode: 0xC40101E3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878641, opcode: 0xC40101E3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878656, opcode: 0xC40101E4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878657, opcode: 0xC40101E4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878672, opcode: 0xC40101E5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878673, opcode: 0xC40101E5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878688, opcode: 0xC40101E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878689, opcode: 0xC40101E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878704, opcode: 0xC40101E7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878705, opcode: 0xC40101E7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878720, opcode: 0xC40101E8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878721, opcode: 0xC40101E8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878736, opcode: 0xC40101E9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878737, opcode: 0xC40101E9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878752, opcode: 0xC40101EA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878753, opcode: 0xC40101EA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878768, opcode: 0xC40101EB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878769, opcode: 0xC40101EB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878784, opcode: 0xC40101EC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878785, opcode: 0xC40101EC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878800, opcode: 0xC40101ED, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878801, opcode: 0xC40101ED, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878816, opcode: 0xC40101EE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878817, opcode: 0xC40101EE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878832, opcode: 0xC40101EF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878833, opcode: 0xC40101EF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878864, opcode: 0xC40101F1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878865, opcode: 0xC40101F1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878880, opcode: 0xC40101F2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878881, opcode: 0xC40101F2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878896, opcode: 0xC40101F3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878897, opcode: 0xC40101F3, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878912, opcode: 0xC40101F4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878913, opcode: 0xC40101F4, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878928, opcode: 0xC40101F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878929, opcode: 0xC40101F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878944, opcode: 0xC40101F6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878945, opcode: 0xC40101F6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878960, opcode: 0xC40101F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878976, opcode: 0xC40101F8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878977, opcode: 0xC40101F8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878992, opcode: 0xC40101F9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536878993, opcode: 0xC40101F9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879008, opcode: 0xC40101FA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879009, opcode: 0xC40101FA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879024, opcode: 0xC40101FB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879025, opcode: 0xC40101FB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879040, opcode: 0xC40101FC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879041, opcode: 0xC40101FC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879056, opcode: 0xC40101FD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879057, opcode: 0xC40101FD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879072, opcode: 0xC40101FE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879073, opcode: 0xC40101FE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879360, opcode: 0xC4010210, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879361, opcode: 0xC4010210, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879376, opcode: 0xC4010211, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879377, opcode: 0xC4010211, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879392, opcode: 0xC4010212, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879393, opcode: 0xC4010212, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879456, opcode: 0xC4010216, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879457, opcode: 0xC4010216, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879776, opcode: 0xC401022A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879777, opcode: 0xC401022A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::VVVV | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879808, opcode: 0xC401022C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879809, opcode: 0xC401022C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879824, opcode: 0xC401022D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536879825, opcode: 0xC401022D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880400, opcode: 0xC4010251, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880416, opcode: 0xC4010252, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880432, opcode: 0xC4010253, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880512, opcode: 0xC4010258, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880528, opcode: 0xC4010259, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880544, opcode: 0xC401025A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880560, opcode: 0xC401025B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880561, opcode: 0xC401025B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880576, opcode: 0xC401025C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880592, opcode: 0xC401025D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880608, opcode: 0xC401025E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880624, opcode: 0xC401025F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880880, opcode: 0xC401026F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880881, opcode: 0xC401026F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880896, opcode: 0xC4010270, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536880897, opcode: 0xC4010270, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536881120, opcode: 0xC401027E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536881136, opcode: 0xC401027F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536881137, opcode: 0xC401027F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536882208, opcode: 0xC40102C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536882784, opcode: 0xC40102E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536882785, opcode: 0xC40102E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883456, opcode: 0xC4010310, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883457, opcode: 0xC4010310, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883472, opcode: 0xC4010311, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883473, opcode: 0xC4010311, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883488, opcode: 0xC4010312, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883489, opcode: 0xC4010312, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883872, opcode: 0xC401032A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883873, opcode: 0xC401032A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::VVVV | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883904, opcode: 0xC401032C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883905, opcode: 0xC401032C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883920, opcode: 0xC401032D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536883921, opcode: 0xC401032D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884496, opcode: 0xC4010351, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884608, opcode: 0xC4010358, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884624, opcode: 0xC4010359, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884640, opcode: 0xC401035A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884672, opcode: 0xC401035C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884688, opcode: 0xC401035D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884704, opcode: 0xC401035E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884720, opcode: 0xC401035F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884992, opcode: 0xC4010370, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536884993, opcode: 0xC4010370, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536885184, opcode: 0xC401037C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536885185, opcode: 0xC401037C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536885200, opcode: 0xC401037D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536885201, opcode: 0xC401037D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536886304, opcode: 0xC40103C2, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536886528, opcode: 0xC40103D0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536886529, opcode: 0xC40103D0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536886880, opcode: 0xC40103E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536886881, opcode: 0xC40103E6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536887040, opcode: 0xC40103F0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536887041, opcode: 0xC40103F0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891168, opcode: 0xC40200F2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891169, opcode: 0xC40200F2, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891184, opcode: 0xC40200F3, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891185, opcode: 0xC40200F3, group: 1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891186, opcode: 0xC40200F3, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891187, opcode: 0xC40200F3, group: 2, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891188, opcode: 0xC40200F3, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891189, opcode: 0xC40200F3, group: 3, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891216, opcode: 0xC40200F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891217, opcode: 0xC40200F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891248, opcode: 0xC40200F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891249, opcode: 0xC40200F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI1, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891392, opcode: 0xC4020100, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891393, opcode: 0xC4020100, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891408, opcode: 0xC4020101, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891409, opcode: 0xC4020101, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891424, opcode: 0xC4020102, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891425, opcode: 0xC4020102, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891440, opcode: 0xC4020103, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891441, opcode: 0xC4020103, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891456, opcode: 0xC4020104, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891457, opcode: 0xC4020104, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891472, opcode: 0xC4020105, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891473, opcode: 0xC4020105, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891488, opcode: 0xC4020106, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891489, opcode: 0xC4020106, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891504, opcode: 0xC4020107, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891505, opcode: 0xC4020107, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891520, opcode: 0xC4020108, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891521, opcode: 0xC4020108, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891536, opcode: 0xC4020109, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891537, opcode: 0xC4020109, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891552, opcode: 0xC402010A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891553, opcode: 0xC402010A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891568, opcode: 0xC402010B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891569, opcode: 0xC402010B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891584, opcode: 0xC402010C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891585, opcode: 0xC402010C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891600, opcode: 0xC402010D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891601, opcode: 0xC402010D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891616, opcode: 0xC402010E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891617, opcode: 0xC402010E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891632, opcode: 0xC402010F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891633, opcode: 0xC402010F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891696, opcode: 0xC4020113, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::F16C, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891697, opcode: 0xC4020113, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::F16C, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891744, opcode: 0xC4020116, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891760, opcode: 0xC4020117, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891761, opcode: 0xC4020117, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891776, opcode: 0xC4020118, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891777, opcode: 0xC4020118, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891778, opcode: 0xC4020118, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891779, opcode: 0xC4020118, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891792, opcode: 0xC4020119, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891793, opcode: 0xC4020119, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: true, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891808, opcode: 0xC402011A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891840, opcode: 0xC402011C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891841, opcode: 0xC402011C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891856, opcode: 0xC402011D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891857, opcode: 0xC402011D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891872, opcode: 0xC402011E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891873, opcode: 0xC402011E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891904, opcode: 0xC4020120, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891905, opcode: 0xC4020120, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891920, opcode: 0xC4020121, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891921, opcode: 0xC4020121, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891936, opcode: 0xC4020122, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891937, opcode: 0xC4020122, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891952, opcode: 0xC4020123, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891953, opcode: 0xC4020123, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891968, opcode: 0xC4020124, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891969, opcode: 0xC4020124, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891984, opcode: 0xC4020125, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536891985, opcode: 0xC4020125, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892032, opcode: 0xC4020128, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892033, opcode: 0xC4020128, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892048, opcode: 0xC4020129, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892049, opcode: 0xC4020129, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892064, opcode: 0xC402012A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892065, opcode: 0xC402012A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892080, opcode: 0xC402012B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892081, opcode: 0xC402012B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892096, opcode: 0xC402012C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892097, opcode: 0xC402012C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892112, opcode: 0xC402012D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892113, opcode: 0xC402012D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892128, opcode: 0xC402012E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892129, opcode: 0xC402012E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892144, opcode: 0xC402012F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892145, opcode: 0xC402012F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892160, opcode: 0xC4020130, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892161, opcode: 0xC4020130, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892176, opcode: 0xC4020131, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892177, opcode: 0xC4020131, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892192, opcode: 0xC4020132, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892193, opcode: 0xC4020132, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892208, opcode: 0xC4020133, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892209, opcode: 0xC4020133, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892224, opcode: 0xC4020134, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892225, opcode: 0xC4020134, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892240, opcode: 0xC4020135, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892241, opcode: 0xC4020135, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892256, opcode: 0xC4020136, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892272, opcode: 0xC4020137, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892273, opcode: 0xC4020137, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892288, opcode: 0xC4020138, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892289, opcode: 0xC4020138, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892304, opcode: 0xC4020139, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892305, opcode: 0xC4020139, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892320, opcode: 0xC402013A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892321, opcode: 0xC402013A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892336, opcode: 0xC402013B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892337, opcode: 0xC402013B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892352, opcode: 0xC402013C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892353, opcode: 0xC402013C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892368, opcode: 0xC402013D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892369, opcode: 0xC402013D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892384, opcode: 0xC402013E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892385, opcode: 0xC402013E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892400, opcode: 0xC402013F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892401, opcode: 0xC402013F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892416, opcode: 0xC4020140, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892417, opcode: 0xC4020140, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892432, opcode: 0xC4020141, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892496, opcode: 0xC4020145, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892497, opcode: 0xC4020145, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892498, opcode: 0xC4020145, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892499, opcode: 0xC4020145, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892512, opcode: 0xC4020146, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892513, opcode: 0xC4020146, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892528, opcode: 0xC4020147, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892529, opcode: 0xC4020147, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892530, opcode: 0xC4020147, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892531, opcode: 0xC4020147, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892800, opcode: 0xC4020158, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892801, opcode: 0xC4020158, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892816, opcode: 0xC4020159, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892817, opcode: 0xC4020159, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536892832, opcode: 0xC402015A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893312, opcode: 0xC4020178, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893313, opcode: 0xC4020178, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893328, opcode: 0xC4020179, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893329, opcode: 0xC4020179, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893632, opcode: 0xC402018C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893633, opcode: 0xC402018C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893634, opcode: 0xC402018C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893635, opcode: 0xC402018C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893664, opcode: 0xC402018E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893665, opcode: 0xC402018E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893666, opcode: 0xC402018E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893667, opcode: 0xC402018E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893696, opcode: 0xC4020190, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893697, opcode: 0xC4020190, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893698, opcode: 0xC4020190, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893699, opcode: 0xC4020190, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893712, opcode: 0xC4020191, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893713, opcode: 0xC4020191, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893714, opcode: 0xC4020191, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893715, opcode: 0xC4020191, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893728, opcode: 0xC4020192, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893729, opcode: 0xC4020192, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893730, opcode: 0xC4020192, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893731, opcode: 0xC4020192, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893744, opcode: 0xC4020193, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893745, opcode: 0xC4020193, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893746, opcode: 0xC4020193, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893747, opcode: 0xC4020193, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::VSIB | vex::UNIQUE, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: true, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893792, opcode: 0xC4020196, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893793, opcode: 0xC4020196, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893794, opcode: 0xC4020196, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893795, opcode: 0xC4020196, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893808, opcode: 0xC4020197, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893809, opcode: 0xC4020197, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893810, opcode: 0xC4020197, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893811, opcode: 0xC4020197, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893824, opcode: 0xC4020198, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893825, opcode: 0xC4020198, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893826, opcode: 0xC4020198, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893827, opcode: 0xC4020198, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893840, opcode: 0xC4020199, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893841, opcode: 0xC4020199, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893856, opcode: 0xC402019A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893857, opcode: 0xC402019A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893858, opcode: 0xC402019A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893859, opcode: 0xC402019A, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893872, opcode: 0xC402019B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893873, opcode: 0xC402019B, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893888, opcode: 0xC402019C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893889, opcode: 0xC402019C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893890, opcode: 0xC402019C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893891, opcode: 0xC402019C, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893904, opcode: 0xC402019D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893905, opcode: 0xC402019D, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893920, opcode: 0xC402019E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893921, opcode: 0xC402019E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893922, opcode: 0xC402019E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893923, opcode: 0xC402019E, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893936, opcode: 0xC402019F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536893937, opcode: 0xC402019F, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894048, opcode: 0xC40201A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894049, opcode: 0xC40201A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894050, opcode: 0xC40201A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894051, opcode: 0xC40201A6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894064, opcode: 0xC40201A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894065, opcode: 0xC40201A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894066, opcode: 0xC40201A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894067, opcode: 0xC40201A7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894080, opcode: 0xC40201A8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894081, opcode: 0xC40201A8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894082, opcode: 0xC40201A8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894083, opcode: 0xC40201A8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894096, opcode: 0xC40201A9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894097, opcode: 0xC40201A9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894112, opcode: 0xC40201AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894113, opcode: 0xC40201AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894114, opcode: 0xC40201AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894115, opcode: 0xC40201AA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894128, opcode: 0xC40201AB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894129, opcode: 0xC40201AB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894144, opcode: 0xC40201AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894145, opcode: 0xC40201AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894146, opcode: 0xC40201AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894147, opcode: 0xC40201AC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894160, opcode: 0xC40201AD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894161, opcode: 0xC40201AD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894176, opcode: 0xC40201AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894177, opcode: 0xC40201AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894178, opcode: 0xC40201AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894179, opcode: 0xC40201AE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894192, opcode: 0xC40201AF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894193, opcode: 0xC40201AF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894304, opcode: 0xC40201B6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894305, opcode: 0xC40201B6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894306, opcode: 0xC40201B6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894307, opcode: 0xC40201B6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894320, opcode: 0xC40201B7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894321, opcode: 0xC40201B7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894322, opcode: 0xC40201B7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894323, opcode: 0xC40201B7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894336, opcode: 0xC40201B8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894337, opcode: 0xC40201B8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894338, opcode: 0xC40201B8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894339, opcode: 0xC40201B8, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894352, opcode: 0xC40201B9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894353, opcode: 0xC40201B9, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894368, opcode: 0xC40201BA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894369, opcode: 0xC40201BA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894370, opcode: 0xC40201BA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894371, opcode: 0xC40201BA, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894384, opcode: 0xC40201BB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894385, opcode: 0xC40201BB, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894400, opcode: 0xC40201BC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894401, opcode: 0xC40201BC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894402, opcode: 0xC40201BC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894403, opcode: 0xC40201BC, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894416, opcode: 0xC40201BD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894417, opcode: 0xC40201BD, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894432, opcode: 0xC40201BE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894433, opcode: 0xC40201BE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894434, opcode: 0xC40201BE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894435, opcode: 0xC40201BE, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894448, opcode: 0xC40201BF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536894449, opcode: 0xC40201BF, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::FMA, vex: vex::ROW | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536895344, opcode: 0xC40201F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536895345, opcode: 0xC40201F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536899408, opcode: 0xC40202F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536899409, opcode: 0xC40202F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536899440, opcode: 0xC40202F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536899441, opcode: 0xC40202F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903504, opcode: 0xC40203F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903505, opcode: 0xC40203F5, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903520, opcode: 0xC40203F6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903521, opcode: 0xC40203F6, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903536, opcode: 0xC40203F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536903537, opcode: 0xC40203F7, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907776, opcode: 0xC4030100, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907792, opcode: 0xC4030101, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907808, opcode: 0xC4030102, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907809, opcode: 0xC4030102, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907840, opcode: 0xC4030104, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907841, opcode: 0xC4030104, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907856, opcode: 0xC4030105, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907857, opcode: 0xC4030105, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907872, opcode: 0xC4030106, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907904, opcode: 0xC4030108, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907905, opcode: 0xC4030108, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907920, opcode: 0xC4030109, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907921, opcode: 0xC4030109, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907936, opcode: 0xC403010A, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907952, opcode: 0xC403010B, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907968, opcode: 0xC403010C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907969, opcode: 0xC403010C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907984, opcode: 0xC403010D, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536907985, opcode: 0xC403010D, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908000, opcode: 0xC403010E, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908001, opcode: 0xC403010E, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908016, opcode: 0xC403010F, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908017, opcode: 0xC403010F, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908096, opcode: 0xC4030114, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908097, opcode: 0xC4030114, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908112, opcode: 0xC4030115, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908113, opcode: 0xC4030115, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908128, opcode: 0xC4030116, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908129, opcode: 0xC4030116, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908144, opcode: 0xC4030117, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908145, opcode: 0xC4030117, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908160, opcode: 0xC4030118, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908176, opcode: 0xC4030119, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908240, opcode: 0xC403011D, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::F16C, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908241, opcode: 0xC403011D, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::F16C, vex: vex::ROW | vex::L0 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908288, opcode: 0xC4030120, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908289, opcode: 0xC4030120, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908304, opcode: 0xC4030121, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908320, opcode: 0xC4030122, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908321, opcode: 0xC4030122, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::VVVV | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908672, opcode: 0xC4030138, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908688, opcode: 0xC4030139, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908800, opcode: 0xC4030140, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908801, opcode: 0xC4030140, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908816, opcode: 0xC4030141, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908832, opcode: 0xC4030142, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908833, opcode: 0xC4030142, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908896, opcode: 0xC4030146, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908960, opcode: 0xC403014A, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908961, opcode: 0xC403014A, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908976, opcode: 0xC403014B, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908977, opcode: 0xC403014B, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908992, opcode: 0xC403014C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536908993, opcode: 0xC403014C, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX2, vex: vex::ROW | vex::L1 | vex::W0 | vex::VVVV | vex::IS4, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909312, opcode: 0xC4030160, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909313, opcode: 0xC4030160, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909328, opcode: 0xC4030161, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909329, opcode: 0xC4030161, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909344, opcode: 0xC4030162, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536909360, opcode: 0xC4030163, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::AVX, vex: vex::ROW | vex::L0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536919808, opcode: 0xC40303F0, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W0 | vex::WIG32 | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 536919809, opcode: 0xC40303F0, group: -1, immediate: ImmediateKind::Byte, extra_bytes: 0, refining: 0, feature: crate::cpu::features::BMI2, vex: vex::ROW | vex::L0 | vex::W1 | vex::LONG | vex::GPR, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268447488, opcode: 0xF20F38F0, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_REP, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: false, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
    Encoding { id: 268447504, opcode: 0xF20F38F1, group: -1, immediate: ImmediateKind::None, extra_bytes: 0, refining: crate::decode_rules::REFINING_REP, feature: crate::cpu::features::SSE4_2, vex: 0, fetch_modrm: true, group_ud: false, task_switch_test: false, custom: true, e: true, ignore_mod: false, reg_ud: false, mem_ud: false, os: true, block_boundary: false, no_next_instruction: false, absolute_jump: false, jump_offset_imm: false, conditional_jump: false, custom_sti: false, is_fpu: false, sse: false, mmx: false, is_string: false, unimplemented: false },
];
pub static OPCODES: &[(u32, usize, usize)] = &[
    (0x0, 0, 1),
    (0x1, 1, 2),
    (0x2, 2, 3),
    (0x3, 3, 4),
    (0x4, 4, 5),
    (0x5, 5, 6),
    (0x6, 6, 7),
    (0x7, 7, 8),
    (0x8, 8, 9),
    (0x9, 9, 10),
    (0xA, 10, 11),
    (0xB, 11, 12),
    (0xC, 12, 13),
    (0xD, 13, 14),
    (0xE, 14, 15),
    (0x10, 15, 16),
    (0x11, 16, 17),
    (0x12, 17, 18),
    (0x13, 18, 19),
    (0x14, 19, 20),
    (0x15, 20, 21),
    (0x16, 21, 22),
    (0x17, 22, 23),
    (0x18, 23, 24),
    (0x19, 24, 25),
    (0x1A, 25, 26),
    (0x1B, 26, 27),
    (0x1C, 27, 28),
    (0x1D, 28, 29),
    (0x1E, 29, 30),
    (0x1F, 30, 31),
    (0x20, 31, 32),
    (0x21, 32, 33),
    (0x22, 33, 34),
    (0x23, 34, 35),
    (0x24, 35, 36),
    (0x25, 36, 37),
    (0x27, 37, 38),
    (0x28, 38, 39),
    (0x29, 39, 40),
    (0x2A, 40, 41),
    (0x2B, 41, 42),
    (0x2C, 42, 43),
    (0x2D, 43, 44),
    (0x2F, 44, 45),
    (0x30, 45, 46),
    (0x31, 46, 47),
    (0x32, 47, 48),
    (0x33, 48, 49),
    (0x34, 49, 50),
    (0x35, 50, 51),
    (0x37, 51, 52),
    (0x38, 52, 53),
    (0x39, 53, 54),
    (0x3A, 54, 55),
    (0x3B, 55, 56),
    (0x3C, 56, 57),
    (0x3D, 57, 58),
    (0x3F, 58, 59),
    (0x40, 59, 60),
    (0x41, 60, 61),
    (0x42, 61, 62),
    (0x43, 62, 63),
    (0x44, 63, 64),
    (0x45, 64, 65),
    (0x46, 65, 66),
    (0x47, 66, 67),
    (0x48, 67, 68),
    (0x49, 68, 69),
    (0x4A, 69, 70),
    (0x4B, 70, 71),
    (0x4C, 71, 72),
    (0x4D, 72, 73),
    (0x4E, 73, 74),
    (0x4F, 74, 75),
    (0x50, 75, 76),
    (0x51, 76, 77),
    (0x52, 77, 78),
    (0x53, 78, 79),
    (0x54, 79, 80),
    (0x55, 80, 81),
    (0x56, 81, 82),
    (0x57, 82, 83),
    (0x58, 83, 84),
    (0x59, 84, 85),
    (0x5A, 85, 86),
    (0x5B, 86, 87),
    (0x5C, 87, 88),
    (0x5D, 88, 89),
    (0x5E, 89, 90),
    (0x5F, 90, 91),
    (0x60, 91, 92),
    (0x61, 92, 93),
    (0x62, 93, 94),
    (0x63, 94, 95),
    (0x68, 95, 96),
    (0x69, 96, 97),
    (0x6A, 97, 98),
    (0x6B, 98, 99),
    (0x6C, 99, 100),
    (0x6D, 100, 101),
    (0x6E, 101, 102),
    (0x6F, 102, 103),
    (0x70, 103, 104),
    (0x71, 104, 105),
    (0x72, 105, 106),
    (0x73, 106, 107),
    (0x74, 107, 108),
    (0x75, 108, 109),
    (0x76, 109, 110),
    (0x77, 110, 111),
    (0x78, 111, 112),
    (0x79, 112, 113),
    (0x7A, 113, 114),
    (0x7B, 114, 115),
    (0x7C, 115, 116),
    (0x7D, 116, 117),
    (0x7E, 117, 118),
    (0x7F, 118, 119),
    (0x80, 119, 127),
    (0x81, 127, 135),
    (0x82, 135, 143),
    (0x83, 143, 151),
    (0x84, 151, 152),
    (0x85, 152, 153),
    (0x86, 153, 154),
    (0x87, 154, 155),
    (0x88, 155, 156),
    (0x89, 156, 157),
    (0x8A, 157, 158),
    (0x8B, 158, 159),
    (0x8C, 159, 160),
    (0x8D, 160, 161),
    (0x8E, 161, 162),
    (0x8F, 162, 170),
    (0x90, 170, 171),
    (0x91, 171, 172),
    (0x92, 172, 173),
    (0x93, 173, 174),
    (0x94, 174, 175),
    (0x95, 175, 176),
    (0x96, 176, 177),
    (0x97, 177, 178),
    (0x98, 178, 179),
    (0x99, 179, 180),
    (0x9A, 180, 181),
    (0x9B, 181, 182),
    (0x9C, 182, 183),
    (0x9D, 183, 184),
    (0x9E, 184, 185),
    (0x9F, 185, 186),
    (0xA0, 186, 187),
    (0xA1, 187, 188),
    (0xA2, 188, 189),
    (0xA3, 189, 190),
    (0xA4, 190, 191),
    (0xA5, 191, 192),
    (0xA6, 192, 193),
    (0xA7, 193, 194),
    (0xA8, 194, 195),
    (0xA9, 195, 196),
    (0xAA, 196, 197),
    (0xAB, 197, 198),
    (0xAC, 198, 199),
    (0xAD, 199, 200),
    (0xAE, 200, 201),
    (0xAF, 201, 202),
    (0xB0, 202, 203),
    (0xB1, 203, 204),
    (0xB2, 204, 205),
    (0xB3, 205, 206),
    (0xB4, 206, 207),
    (0xB5, 207, 208),
    (0xB6, 208, 209),
    (0xB7, 209, 210),
    (0xB8, 210, 211),
    (0xB9, 211, 212),
    (0xBA, 212, 213),
    (0xBB, 213, 214),
    (0xBC, 214, 215),
    (0xBD, 215, 216),
    (0xBE, 216, 217),
    (0xBF, 217, 218),
    (0xC0, 218, 226),
    (0xC1, 226, 234),
    (0xC2, 234, 235),
    (0xC3, 235, 236),
    (0xC4, 236, 237),
    (0xC5, 237, 238),
    (0xC6, 238, 246),
    (0xC7, 246, 254),
    (0xC8, 254, 255),
    (0xC9, 255, 256),
    (0xCA, 256, 257),
    (0xCB, 257, 258),
    (0xCC, 258, 259),
    (0xCD, 259, 260),
    (0xCE, 260, 261),
    (0xCF, 261, 262),
    (0xD0, 262, 270),
    (0xD1, 270, 278),
    (0xD2, 278, 286),
    (0xD3, 286, 294),
    (0xD4, 294, 295),
    (0xD5, 295, 296),
    (0xD6, 296, 297),
    (0xD7, 297, 298),
    (0xD8, 298, 306),
    (0xD9, 306, 314),
    (0xDA, 314, 322),
    (0xDB, 322, 330),
    (0xDC, 330, 338),
    (0xDD, 338, 346),
    (0xDE, 346, 354),
    (0xDF, 354, 362),
    (0xE0, 362, 363),
    (0xE1, 363, 364),
    (0xE2, 364, 365),
    (0xE3, 365, 366),
    (0xE4, 366, 367),
    (0xE5, 367, 368),
    (0xE6, 368, 369),
    (0xE7, 369, 370),
    (0xE8, 370, 371),
    (0xE9, 371, 372),
    (0xEA, 372, 373),
    (0xEB, 373, 374),
    (0xEC, 374, 375),
    (0xED, 375, 376),
    (0xEE, 376, 377),
    (0xEF, 377, 378),
    (0xF1, 378, 379),
    (0xF4, 379, 380),
    (0xF5, 380, 381),
    (0xF6, 381, 389),
    (0xF7, 389, 397),
    (0xF8, 397, 398),
    (0xF9, 398, 399),
    (0xFA, 399, 400),
    (0xFB, 400, 401),
    (0xFC, 401, 402),
    (0xFD, 402, 403),
    (0xFE, 403, 411),
    (0xFF, 411, 419),
    (0xF00, 419, 427),
    (0xF01, 427, 435),
    (0xF02, 435, 436),
    (0xF03, 436, 437),
    (0xF04, 437, 438),
    (0xF05, 438, 439),
    (0xF06, 439, 440),
    (0xF07, 440, 441),
    (0xF08, 441, 442),
    (0xF09, 442, 443),
    (0xF0A, 443, 444),
    (0xF0B, 444, 445),
    (0xF0C, 445, 446),
    (0xF0D, 446, 447),
    (0xF0E, 447, 448),
    (0xF0F, 448, 449),
    (0xF10, 449, 450),
    (0xF11, 450, 451),
    (0xF12, 451, 452),
    (0xF13, 452, 453),
    (0xF14, 453, 454),
    (0xF15, 454, 455),
    (0xF16, 455, 456),
    (0xF17, 456, 457),
    (0xF18, 457, 458),
    (0xF19, 458, 459),
    (0xF1A, 459, 460),
    (0xF1B, 460, 461),
    (0xF1C, 461, 462),
    (0xF1D, 462, 463),
    (0xF1E, 463, 464),
    (0xF1F, 464, 465),
    (0xF20, 465, 466),
    (0xF21, 466, 467),
    (0xF22, 467, 468),
    (0xF23, 468, 469),
    (0xF24, 469, 470),
    (0xF25, 470, 471),
    (0xF26, 471, 472),
    (0xF27, 472, 473),
    (0xF28, 473, 474),
    (0xF29, 474, 475),
    (0xF2A, 475, 476),
    (0xF2B, 476, 477),
    (0xF2C, 477, 478),
    (0xF2D, 478, 479),
    (0xF2E, 479, 480),
    (0xF2F, 480, 481),
    (0xF30, 481, 482),
    (0xF31, 482, 483),
    (0xF32, 483, 484),
    (0xF33, 484, 485),
    (0xF34, 485, 486),
    (0xF35, 486, 487),
    (0xF36, 487, 488),
    (0xF37, 488, 489),
    (0xF39, 489, 490),
    (0xF3B, 490, 491),
    (0xF3C, 491, 492),
    (0xF3D, 492, 493),
    (0xF3E, 493, 494),
    (0xF3F, 494, 495),
    (0xF40, 495, 496),
    (0xF41, 496, 497),
    (0xF42, 497, 498),
    (0xF43, 498, 499),
    (0xF44, 499, 500),
    (0xF45, 500, 501),
    (0xF46, 501, 502),
    (0xF47, 502, 503),
    (0xF48, 503, 504),
    (0xF49, 504, 505),
    (0xF4A, 505, 506),
    (0xF4B, 506, 507),
    (0xF4C, 507, 508),
    (0xF4D, 508, 509),
    (0xF4E, 509, 510),
    (0xF4F, 510, 511),
    (0xF50, 511, 512),
    (0xF51, 512, 513),
    (0xF52, 513, 514),
    (0xF53, 514, 515),
    (0xF54, 515, 516),
    (0xF55, 516, 517),
    (0xF56, 517, 518),
    (0xF57, 518, 519),
    (0xF58, 519, 520),
    (0xF59, 520, 521),
    (0xF5A, 521, 522),
    (0xF5B, 522, 523),
    (0xF5C, 523, 524),
    (0xF5D, 524, 525),
    (0xF5E, 525, 526),
    (0xF5F, 526, 527),
    (0xF60, 527, 528),
    (0xF61, 528, 529),
    (0xF62, 529, 530),
    (0xF63, 530, 531),
    (0xF64, 531, 532),
    (0xF65, 532, 533),
    (0xF66, 533, 534),
    (0xF67, 534, 535),
    (0xF68, 535, 536),
    (0xF69, 536, 537),
    (0xF6A, 537, 538),
    (0xF6B, 538, 539),
    (0xF6C, 539, 540),
    (0xF6D, 540, 541),
    (0xF6E, 541, 542),
    (0xF6F, 542, 543),
    (0xF70, 543, 544),
    (0xF71, 544, 552),
    (0xF72, 552, 560),
    (0xF73, 560, 568),
    (0xF74, 568, 569),
    (0xF75, 569, 570),
    (0xF76, 570, 571),
    (0xF77, 571, 572),
    (0xF78, 572, 573),
    (0xF79, 573, 574),
    (0xF7A, 574, 575),
    (0xF7B, 575, 576),
    (0xF7C, 576, 577),
    (0xF7D, 577, 578),
    (0xF7E, 578, 579),
    (0xF7F, 579, 580),
    (0xF80, 580, 581),
    (0xF81, 581, 582),
    (0xF82, 582, 583),
    (0xF83, 583, 584),
    (0xF84, 584, 585),
    (0xF85, 585, 586),
    (0xF86, 586, 587),
    (0xF87, 587, 588),
    (0xF88, 588, 589),
    (0xF89, 589, 590),
    (0xF8A, 590, 591),
    (0xF8B, 591, 592),
    (0xF8C, 592, 593),
    (0xF8D, 593, 594),
    (0xF8E, 594, 595),
    (0xF8F, 595, 596),
    (0xF90, 596, 597),
    (0xF91, 597, 598),
    (0xF92, 598, 599),
    (0xF93, 599, 600),
    (0xF94, 600, 601),
    (0xF95, 601, 602),
    (0xF96, 602, 603),
    (0xF97, 603, 604),
    (0xF98, 604, 605),
    (0xF99, 605, 606),
    (0xF9A, 606, 607),
    (0xF9B, 607, 608),
    (0xF9C, 608, 609),
    (0xF9D, 609, 610),
    (0xF9E, 610, 611),
    (0xF9F, 611, 612),
    (0xFA0, 612, 613),
    (0xFA1, 613, 614),
    (0xFA2, 614, 615),
    (0xFA3, 615, 616),
    (0xFA4, 616, 617),
    (0xFA5, 617, 618),
    (0xFA6, 618, 619),
    (0xFA7, 619, 620),
    (0xFA8, 620, 621),
    (0xFA9, 621, 622),
    (0xFAA, 622, 623),
    (0xFAB, 623, 624),
    (0xFAC, 624, 625),
    (0xFAD, 625, 626),
    (0xFAE, 626, 634),
    (0xFAF, 634, 635),
    (0xFB0, 635, 636),
    (0xFB1, 636, 637),
    (0xFB2, 637, 638),
    (0xFB3, 638, 639),
    (0xFB4, 639, 640),
    (0xFB5, 640, 641),
    (0xFB6, 641, 642),
    (0xFB7, 642, 643),
    (0xFB8, 643, 644),
    (0xFB9, 644, 645),
    (0xFBA, 645, 653),
    (0xFBB, 653, 654),
    (0xFBC, 654, 655),
    (0xFBD, 655, 656),
    (0xFBE, 656, 657),
    (0xFBF, 657, 658),
    (0xFC0, 658, 659),
    (0xFC1, 659, 660),
    (0xFC2, 660, 661),
    (0xFC3, 661, 662),
    (0xFC4, 662, 663),
    (0xFC5, 663, 664),
    (0xFC6, 664, 665),
    (0xFC7, 665, 673),
    (0xFC8, 673, 674),
    (0xFC9, 674, 675),
    (0xFCA, 675, 676),
    (0xFCB, 676, 677),
    (0xFCC, 677, 678),
    (0xFCD, 678, 679),
    (0xFCE, 679, 680),
    (0xFCF, 680, 681),
    (0xFD0, 681, 682),
    (0xFD1, 682, 683),
    (0xFD2, 683, 684),
    (0xFD3, 684, 685),
    (0xFD4, 685, 686),
    (0xFD5, 686, 687),
    (0xFD6, 687, 688),
    (0xFD7, 688, 689),
    (0xFD8, 689, 690),
    (0xFD9, 690, 691),
    (0xFDA, 691, 692),
    (0xFDB, 692, 693),
    (0xFDC, 693, 694),
    (0xFDD, 694, 695),
    (0xFDE, 695, 696),
    (0xFDF, 696, 697),
    (0xFE0, 697, 698),
    (0xFE1, 698, 699),
    (0xFE2, 699, 700),
    (0xFE3, 700, 701),
    (0xFE4, 701, 702),
    (0xFE5, 702, 703),
    (0xFE6, 703, 704),
    (0xFE7, 704, 705),
    (0xFE8, 705, 706),
    (0xFE9, 706, 707),
    (0xFEA, 707, 708),
    (0xFEB, 708, 709),
    (0xFEC, 709, 710),
    (0xFED, 710, 711),
    (0xFEE, 711, 712),
    (0xFEF, 712, 713),
    (0xFF0, 713, 714),
    (0xFF1, 714, 715),
    (0xFF2, 715, 716),
    (0xFF3, 716, 717),
    (0xFF4, 717, 718),
    (0xFF5, 718, 719),
    (0xFF6, 719, 720),
    (0xFF7, 720, 721),
    (0xFF8, 721, 722),
    (0xFF9, 722, 723),
    (0xFFA, 723, 724),
    (0xFFB, 724, 725),
    (0xFFC, 725, 726),
    (0xFFD, 726, 727),
    (0xFFE, 727, 728),
    (0xFFF, 728, 729),
    (0xF26C, 729, 730),
    (0xF26D, 730, 731),
    (0xF26E, 731, 732),
    (0xF26F, 732, 733),
    (0xF2A4, 733, 734),
    (0xF2A5, 734, 735),
    (0xF2A6, 735, 736),
    (0xF2A7, 736, 737),
    (0xF2AA, 737, 738),
    (0xF2AB, 738, 739),
    (0xF2AC, 739, 740),
    (0xF2AD, 740, 741),
    (0xF2AE, 741, 742),
    (0xF2AF, 742, 743),
    (0xF36C, 743, 744),
    (0xF36D, 744, 745),
    (0xF36E, 745, 746),
    (0xF36F, 746, 747),
    (0xF3A4, 747, 748),
    (0xF3A5, 748, 749),
    (0xF3A6, 749, 750),
    (0xF3A7, 750, 751),
    (0xF3AA, 751, 752),
    (0xF3AB, 752, 753),
    (0xF3AC, 753, 754),
    (0xF3AD, 754, 755),
    (0xF3AE, 755, 756),
    (0xF3AF, 756, 757),
    (0xF3800, 757, 758),
    (0xF3801, 758, 759),
    (0xF3802, 759, 760),
    (0xF3803, 760, 761),
    (0xF3804, 761, 762),
    (0xF3805, 762, 763),
    (0xF3806, 763, 764),
    (0xF3807, 764, 765),
    (0xF3808, 765, 766),
    (0xF3809, 766, 767),
    (0xF380A, 767, 768),
    (0xF380B, 768, 769),
    (0xF381C, 769, 770),
    (0xF381D, 770, 771),
    (0xF381E, 771, 772),
    (0xF38F0, 772, 773),
    (0xF38F1, 773, 774),
    (0xF3A0F, 774, 775),
    (0x660F10, 775, 776),
    (0x660F11, 776, 777),
    (0x660F12, 777, 778),
    (0x660F13, 778, 779),
    (0x660F14, 779, 780),
    (0x660F15, 780, 781),
    (0x660F16, 781, 782),
    (0x660F17, 782, 783),
    (0x660F28, 783, 784),
    (0x660F29, 784, 785),
    (0x660F2A, 785, 786),
    (0x660F2B, 786, 787),
    (0x660F2C, 787, 788),
    (0x660F2D, 788, 789),
    (0x660F2E, 789, 790),
    (0x660F2F, 790, 791),
    (0x660F50, 791, 792),
    (0x660F51, 792, 793),
    (0x660F54, 793, 794),
    (0x660F55, 794, 795),
    (0x660F56, 795, 796),
    (0x660F57, 796, 797),
    (0x660F58, 797, 798),
    (0x660F59, 798, 799),
    (0x660F5A, 799, 800),
    (0x660F5B, 800, 801),
    (0x660F5C, 801, 802),
    (0x660F5D, 802, 803),
    (0x660F5E, 803, 804),
    (0x660F5F, 804, 805),
    (0x660F60, 805, 806),
    (0x660F61, 806, 807),
    (0x660F62, 807, 808),
    (0x660F63, 808, 809),
    (0x660F64, 809, 810),
    (0x660F65, 810, 811),
    (0x660F66, 811, 812),
    (0x660F67, 812, 813),
    (0x660F68, 813, 814),
    (0x660F69, 814, 815),
    (0x660F6A, 815, 816),
    (0x660F6B, 816, 817),
    (0x660F6C, 817, 818),
    (0x660F6D, 818, 819),
    (0x660F6E, 819, 820),
    (0x660F6F, 820, 821),
    (0x660F70, 821, 822),
    (0x660F71, 822, 830),
    (0x660F72, 830, 838),
    (0x660F73, 838, 846),
    (0x660F74, 846, 847),
    (0x660F75, 847, 848),
    (0x660F76, 848, 849),
    (0x660F7C, 849, 850),
    (0x660F7D, 850, 851),
    (0x660F7E, 851, 852),
    (0x660F7F, 852, 853),
    (0x660FC2, 853, 854),
    (0x660FC4, 854, 855),
    (0x660FC5, 855, 856),
    (0x660FC6, 856, 857),
    (0x660FD0, 857, 858),
    (0x660FD1, 858, 859),
    (0x660FD2, 859, 860),
    (0x660FD3, 860, 861),
    (0x660FD4, 861, 862),
    (0x660FD5, 862, 863),
    (0x660FD6, 863, 864),
    (0x660FD7, 864, 865),
    (0x660FD8, 865, 866),
    (0x660FD9, 866, 867),
    (0x660FDA, 867, 868),
    (0x660FDB, 868, 869),
    (0x660FDC, 869, 870),
    (0x660FDD, 870, 871),
    (0x660FDE, 871, 872),
    (0x660FDF, 872, 873),
    (0x660FE0, 873, 874),
    (0x660FE1, 874, 875),
    (0x660FE2, 875, 876),
    (0x660FE3, 876, 877),
    (0x660FE4, 877, 878),
    (0x660FE5, 878, 879),
    (0x660FE6, 879, 880),
    (0x660FE7, 880, 881),
    (0x660FE8, 881, 882),
    (0x660FE9, 882, 883),
    (0x660FEA, 883, 884),
    (0x660FEB, 884, 885),
    (0x660FEC, 885, 886),
    (0x660FED, 886, 887),
    (0x660FEE, 887, 888),
    (0x660FEF, 888, 889),
    (0x660FF1, 889, 890),
    (0x660FF2, 890, 891),
    (0x660FF3, 891, 892),
    (0x660FF4, 892, 893),
    (0x660FF5, 893, 894),
    (0x660FF6, 894, 895),
    (0x660FF7, 895, 896),
    (0x660FF8, 896, 897),
    (0x660FF9, 897, 898),
    (0x660FFA, 898, 899),
    (0x660FFB, 899, 900),
    (0x660FFC, 900, 901),
    (0x660FFD, 901, 902),
    (0x660FFE, 902, 903),
    (0xF20F10, 903, 904),
    (0xF20F11, 904, 905),
    (0xF20F12, 905, 906),
    (0xF20F2A, 906, 907),
    (0xF20F2C, 907, 908),
    (0xF20F2D, 908, 909),
    (0xF20F51, 909, 910),
    (0xF20F58, 910, 911),
    (0xF20F59, 911, 912),
    (0xF20F5A, 912, 913),
    (0xF20F5C, 913, 914),
    (0xF20F5D, 914, 915),
    (0xF20F5E, 915, 916),
    (0xF20F5F, 916, 917),
    (0xF20F70, 917, 918),
    (0xF20F7C, 918, 919),
    (0xF20F7D, 919, 920),
    (0xF20FC2, 920, 921),
    (0xF20FD0, 921, 922),
    (0xF20FD6, 922, 923),
    (0xF20FE6, 923, 924),
    (0xF20FF0, 924, 925),
    (0xF30F10, 925, 926),
    (0xF30F11, 926, 927),
    (0xF30F12, 927, 928),
    (0xF30F16, 928, 929),
    (0xF30F2A, 929, 930),
    (0xF30F2C, 930, 931),
    (0xF30F2D, 931, 932),
    (0xF30F51, 932, 933),
    (0xF30F52, 933, 934),
    (0xF30F53, 934, 935),
    (0xF30F58, 935, 936),
    (0xF30F59, 936, 937),
    (0xF30F5A, 937, 938),
    (0xF30F5B, 938, 939),
    (0xF30F5C, 939, 940),
    (0xF30F5D, 940, 941),
    (0xF30F5E, 941, 942),
    (0xF30F5F, 942, 943),
    (0xF30F6F, 943, 944),
    (0xF30F70, 944, 945),
    (0xF30F7E, 945, 946),
    (0xF30F7F, 946, 947),
    (0xF30FB8, 947, 948),
    (0xF30FBC, 948, 949),
    (0xF30FBD, 949, 950),
    (0xF30FC2, 950, 951),
    (0xF30FD6, 951, 952),
    (0xF30FE6, 952, 953),
    (0x660F3800, 953, 954),
    (0x660F3801, 954, 955),
    (0x660F3802, 955, 956),
    (0x660F3803, 956, 957),
    (0x660F3804, 957, 958),
    (0x660F3805, 958, 959),
    (0x660F3806, 959, 960),
    (0x660F3807, 960, 961),
    (0x660F3808, 961, 962),
    (0x660F3809, 962, 963),
    (0x660F380A, 963, 964),
    (0x660F380B, 964, 965),
    (0x660F3810, 965, 966),
    (0x660F3814, 966, 967),
    (0x660F3815, 967, 968),
    (0x660F3817, 968, 969),
    (0x660F381C, 969, 970),
    (0x660F381D, 970, 971),
    (0x660F381E, 971, 972),
    (0x660F3820, 972, 973),
    (0x660F3821, 973, 974),
    (0x660F3822, 974, 975),
    (0x660F3823, 975, 976),
    (0x660F3824, 976, 977),
    (0x660F3825, 977, 978),
    (0x660F3828, 978, 979),
    (0x660F3829, 979, 980),
    (0x660F382A, 980, 981),
    (0x660F382B, 981, 982),
    (0x660F3830, 982, 983),
    (0x660F3831, 983, 984),
    (0x660F3832, 984, 985),
    (0x660F3833, 985, 986),
    (0x660F3834, 986, 987),
    (0x660F3835, 987, 988),
    (0x660F3837, 988, 989),
    (0x660F3838, 989, 990),
    (0x660F3839, 990, 991),
    (0x660F383A, 991, 992),
    (0x660F383B, 992, 993),
    (0x660F383C, 993, 994),
    (0x660F383D, 994, 995),
    (0x660F383E, 995, 996),
    (0x660F383F, 996, 997),
    (0x660F3840, 997, 998),
    (0x660F3841, 998, 999),
    (0x660F3A08, 999, 1000),
    (0x660F3A09, 1000, 1001),
    (0x660F3A0A, 1001, 1002),
    (0x660F3A0B, 1002, 1003),
    (0x660F3A0C, 1003, 1004),
    (0x660F3A0D, 1004, 1005),
    (0x660F3A0E, 1005, 1006),
    (0x660F3A0F, 1006, 1007),
    (0x660F3A14, 1007, 1008),
    (0x660F3A15, 1008, 1009),
    (0x660F3A16, 1009, 1010),
    (0x660F3A17, 1010, 1011),
    (0x660F3A20, 1011, 1012),
    (0x660F3A21, 1012, 1013),
    (0x660F3A22, 1013, 1014),
    (0x660F3A40, 1014, 1015),
    (0x660F3A41, 1015, 1016),
    (0x660F3A42, 1016, 1017),
    (0x660F3A60, 1017, 1018),
    (0x660F3A61, 1018, 1019),
    (0x660F3A62, 1019, 1020),
    (0x660F3A63, 1020, 1021),
    (0xC4010010, 1021, 1023),
    (0xC4010011, 1023, 1025),
    (0xC4010012, 1025, 1027),
    (0xC4010013, 1027, 1028),
    (0xC4010014, 1028, 1030),
    (0xC4010015, 1030, 1032),
    (0xC4010016, 1032, 1034),
    (0xC4010017, 1034, 1035),
    (0xC4010028, 1035, 1037),
    (0xC4010029, 1037, 1039),
    (0xC401002B, 1039, 1041),
    (0xC401002E, 1041, 1042),
    (0xC401002F, 1042, 1043),
    (0xC4010050, 1043, 1047),
    (0xC4010051, 1047, 1049),
    (0xC4010052, 1049, 1051),
    (0xC4010053, 1051, 1053),
    (0xC4010054, 1053, 1055),
    (0xC4010055, 1055, 1057),
    (0xC4010056, 1057, 1059),
    (0xC4010057, 1059, 1061),
    (0xC4010058, 1061, 1063),
    (0xC4010059, 1063, 1065),
    (0xC401005A, 1065, 1067),
    (0xC401005B, 1067, 1069),
    (0xC401005C, 1069, 1071),
    (0xC401005D, 1071, 1073),
    (0xC401005E, 1073, 1075),
    (0xC401005F, 1075, 1077),
    (0xC4010077, 1077, 1079),
    (0xC40100AE, 1079, 1081),
    (0xC40100C2, 1081, 1083),
    (0xC40100C6, 1083, 1085),
    (0xC4010110, 1085, 1087),
    (0xC4010111, 1087, 1089),
    (0xC4010112, 1089, 1090),
    (0xC4010113, 1090, 1091),
    (0xC4010114, 1091, 1093),
    (0xC4010115, 1093, 1095),
    (0xC4010116, 1095, 1096),
    (0xC4010117, 1096, 1097),
    (0xC4010128, 1097, 1099),
    (0xC4010129, 1099, 1101),
    (0xC401012B, 1101, 1103),
    (0xC401012E, 1103, 1104),
    (0xC401012F, 1104, 1105),
    (0xC4010150, 1105, 1109),
    (0xC4010151, 1109, 1111),
    (0xC4010154, 1111, 1113),
    (0xC4010155, 1113, 1115),
    (0xC4010156, 1115, 1117),
    (0xC4010157, 1117, 1119),
    (0xC4010158, 1119, 1121),
    (0xC4010159, 1121, 1123),
    (0xC401015A, 1123, 1125),
    (0xC401015B, 1125, 1127),
    (0xC401015C, 1127, 1129),
    (0xC401015D, 1129, 1131),
    (0xC401015E, 1131, 1133),
    (0xC401015F, 1133, 1135),
    (0xC4010160, 1135, 1137),
    (0xC4010161, 1137, 1139),
    (0xC4010162, 1139, 1141),
    (0xC4010163, 1141, 1143),
    (0xC4010164, 1143, 1145),
    (0xC4010165, 1145, 1147),
    (0xC4010166, 1147, 1149),
    (0xC4010167, 1149, 1151),
    (0xC4010168, 1151, 1153),
    (0xC4010169, 1153, 1155),
    (0xC401016A, 1155, 1157),
    (0xC401016B, 1157, 1159),
    (0xC401016C, 1159, 1161),
    (0xC401016D, 1161, 1163),
    (0xC401016E, 1163, 1165),
    (0xC401016F, 1165, 1167),
    (0xC4010170, 1167, 1169),
    (0xC4010171, 1169, 1175),
    (0xC4010172, 1175, 1181),
    (0xC4010173, 1181, 1189),
    (0xC4010174, 1189, 1191),
    (0xC4010175, 1191, 1193),
    (0xC4010176, 1193, 1195),
    (0xC401017C, 1195, 1197),
    (0xC401017D, 1197, 1199),
    (0xC401017E, 1199, 1201),
    (0xC401017F, 1201, 1203),
    (0xC40101C2, 1203, 1205),
    (0xC40101C4, 1205, 1207),
    (0xC40101C5, 1207, 1209),
    (0xC40101C6, 1209, 1211),
    (0xC40101D0, 1211, 1213),
    (0xC40101D1, 1213, 1215),
    (0xC40101D2, 1215, 1217),
    (0xC40101D3, 1217, 1219),
    (0xC40101D4, 1219, 1221),
    (0xC40101D5, 1221, 1223),
    (0xC40101D6, 1223, 1224),
    (0xC40101D7, 1224, 1228),
    (0xC40101D8, 1228, 1230),
    (0xC40101D9, 1230, 1232),
    (0xC40101DA, 1232, 1234),
    (0xC40101DB, 1234, 1236),
    (0xC40101DC, 1236, 1238),
    (0xC40101DD, 1238, 1240),
    (0xC40101DE, 1240, 1242),
    (0xC40101DF, 1242, 1244),
    (0xC40101E0, 1244, 1246),
    (0xC40101E1, 1246, 1248),
    (0xC40101E2, 1248, 1250),
    (0xC40101E3, 1250, 1252),
    (0xC40101E4, 1252, 1254),
    (0xC40101E5, 1254, 1256),
    (0xC40101E6, 1256, 1258),
    (0xC40101E7, 1258, 1260),
    (0xC40101E8, 1260, 1262),
    (0xC40101E9, 1262, 1264),
    (0xC40101EA, 1264, 1266),
    (0xC40101EB, 1266, 1268),
    (0xC40101EC, 1268, 1270),
    (0xC40101ED, 1270, 1272),
    (0xC40101EE, 1272, 1274),
    (0xC40101EF, 1274, 1276),
    (0xC40101F1, 1276, 1278),
    (0xC40101F2, 1278, 1280),
    (0xC40101F3, 1280, 1282),
    (0xC40101F4, 1282, 1284),
    (0xC40101F5, 1284, 1286),
    (0xC40101F6, 1286, 1288),
    (0xC40101F7, 1288, 1289),
    (0xC40101F8, 1289, 1291),
    (0xC40101F9, 1291, 1293),
    (0xC40101FA, 1293, 1295),
    (0xC40101FB, 1295, 1297),
    (0xC40101FC, 1297, 1299),
    (0xC40101FD, 1299, 1301),
    (0xC40101FE, 1301, 1303),
    (0xC4010210, 1303, 1305),
    (0xC4010211, 1305, 1307),
    (0xC4010212, 1307, 1309),
    (0xC4010216, 1309, 1311),
    (0xC401022A, 1311, 1313),
    (0xC401022C, 1313, 1315),
    (0xC401022D, 1315, 1317),
    (0xC4010251, 1317, 1318),
    (0xC4010252, 1318, 1319),
    (0xC4010253, 1319, 1320),
    (0xC4010258, 1320, 1321),
    (0xC4010259, 1321, 1322),
    (0xC401025A, 1322, 1323),
    (0xC401025B, 1323, 1325),
    (0xC401025C, 1325, 1326),
    (0xC401025D, 1326, 1327),
    (0xC401025E, 1327, 1328),
    (0xC401025F, 1328, 1329),
    (0xC401026F, 1329, 1331),
    (0xC4010270, 1331, 1333),
    (0xC401027E, 1333, 1334),
    (0xC401027F, 1334, 1336),
    (0xC40102C2, 1336, 1337),
    (0xC40102E6, 1337, 1339),
    (0xC4010310, 1339, 1341),
    (0xC4010311, 1341, 1343),
    (0xC4010312, 1343, 1345),
    (0xC401032A, 1345, 1347),
    (0xC401032C, 1347, 1349),
    (0xC401032D, 1349, 1351),
    (0xC4010351, 1351, 1352),
    (0xC4010358, 1352, 1353),
    (0xC4010359, 1353, 1354),
    (0xC401035A, 1354, 1355),
    (0xC401035C, 1355, 1356),
    (0xC401035D, 1356, 1357),
    (0xC401035E, 1357, 1358),
    (0xC401035F, 1358, 1359),
    (0xC4010370, 1359, 1361),
    (0xC401037C, 1361, 1363),
    (0xC401037D, 1363, 1365),
    (0xC40103C2, 1365, 1366),
    (0xC40103D0, 1366, 1368),
    (0xC40103E6, 1368, 1370),
    (0xC40103F0, 1370, 1372),
    (0xC40200F2, 1372, 1374),
    (0xC40200F3, 1374, 1380),
    (0xC40200F5, 1380, 1382),
    (0xC40200F7, 1382, 1384),
    (0xC4020100, 1384, 1386),
    (0xC4020101, 1386, 1388),
    (0xC4020102, 1388, 1390),
    (0xC4020103, 1390, 1392),
    (0xC4020104, 1392, 1394),
    (0xC4020105, 1394, 1396),
    (0xC4020106, 1396, 1398),
    (0xC4020107, 1398, 1400),
    (0xC4020108, 1400, 1402),
    (0xC4020109, 1402, 1404),
    (0xC402010A, 1404, 1406),
    (0xC402010B, 1406, 1408),
    (0xC402010C, 1408, 1410),
    (0xC402010D, 1410, 1412),
    (0xC402010E, 1412, 1414),
    (0xC402010F, 1414, 1416),
    (0xC4020113, 1416, 1418),
    (0xC4020116, 1418, 1419),
    (0xC4020117, 1419, 1421),
    (0xC4020118, 1421, 1425),
    (0xC4020119, 1425, 1427),
    (0xC402011A, 1427, 1428),
    (0xC402011C, 1428, 1430),
    (0xC402011D, 1430, 1432),
    (0xC402011E, 1432, 1434),
    (0xC4020120, 1434, 1436),
    (0xC4020121, 1436, 1438),
    (0xC4020122, 1438, 1440),
    (0xC4020123, 1440, 1442),
    (0xC4020124, 1442, 1444),
    (0xC4020125, 1444, 1446),
    (0xC4020128, 1446, 1448),
    (0xC4020129, 1448, 1450),
    (0xC402012A, 1450, 1452),
    (0xC402012B, 1452, 1454),
    (0xC402012C, 1454, 1456),
    (0xC402012D, 1456, 1458),
    (0xC402012E, 1458, 1460),
    (0xC402012F, 1460, 1462),
    (0xC4020130, 1462, 1464),
    (0xC4020131, 1464, 1466),
    (0xC4020132, 1466, 1468),
    (0xC4020133, 1468, 1470),
    (0xC4020134, 1470, 1472),
    (0xC4020135, 1472, 1474),
    (0xC4020136, 1474, 1475),
    (0xC4020137, 1475, 1477),
    (0xC4020138, 1477, 1479),
    (0xC4020139, 1479, 1481),
    (0xC402013A, 1481, 1483),
    (0xC402013B, 1483, 1485),
    (0xC402013C, 1485, 1487),
    (0xC402013D, 1487, 1489),
    (0xC402013E, 1489, 1491),
    (0xC402013F, 1491, 1493),
    (0xC4020140, 1493, 1495),
    (0xC4020141, 1495, 1496),
    (0xC4020145, 1496, 1500),
    (0xC4020146, 1500, 1502),
    (0xC4020147, 1502, 1506),
    (0xC4020158, 1506, 1508),
    (0xC4020159, 1508, 1510),
    (0xC402015A, 1510, 1511),
    (0xC4020178, 1511, 1513),
    (0xC4020179, 1513, 1515),
    (0xC402018C, 1515, 1519),
    (0xC402018E, 1519, 1523),
    (0xC4020190, 1523, 1527),
    (0xC4020191, 1527, 1531),
    (0xC4020192, 1531, 1535),
    (0xC4020193, 1535, 1539),
    (0xC4020196, 1539, 1543),
    (0xC4020197, 1543, 1547),
    (0xC4020198, 1547, 1551),
    (0xC4020199, 1551, 1553),
    (0xC402019A, 1553, 1557),
    (0xC402019B, 1557, 1559),
    (0xC402019C, 1559, 1563),
    (0xC402019D, 1563, 1565),
    (0xC402019E, 1565, 1569),
    (0xC402019F, 1569, 1571),
    (0xC40201A6, 1571, 1575),
    (0xC40201A7, 1575, 1579),
    (0xC40201A8, 1579, 1583),
    (0xC40201A9, 1583, 1585),
    (0xC40201AA, 1585, 1589),
    (0xC40201AB, 1589, 1591),
    (0xC40201AC, 1591, 1595),
    (0xC40201AD, 1595, 1597),
    (0xC40201AE, 1597, 1601),
    (0xC40201AF, 1601, 1603),
    (0xC40201B6, 1603, 1607),
    (0xC40201B7, 1607, 1611),
    (0xC40201B8, 1611, 1615),
    (0xC40201B9, 1615, 1617),
    (0xC40201BA, 1617, 1621),
    (0xC40201BB, 1621, 1623),
    (0xC40201BC, 1623, 1627),
    (0xC40201BD, 1627, 1629),
    (0xC40201BE, 1629, 1633),
    (0xC40201BF, 1633, 1635),
    (0xC40201F7, 1635, 1637),
    (0xC40202F5, 1637, 1639),
    (0xC40202F7, 1639, 1641),
    (0xC40203F5, 1641, 1643),
    (0xC40203F6, 1643, 1645),
    (0xC40203F7, 1645, 1647),
    (0xC4030100, 1647, 1648),
    (0xC4030101, 1648, 1649),
    (0xC4030102, 1649, 1651),
    (0xC4030104, 1651, 1653),
    (0xC4030105, 1653, 1655),
    (0xC4030106, 1655, 1656),
    (0xC4030108, 1656, 1658),
    (0xC4030109, 1658, 1660),
    (0xC403010A, 1660, 1661),
    (0xC403010B, 1661, 1662),
    (0xC403010C, 1662, 1664),
    (0xC403010D, 1664, 1666),
    (0xC403010E, 1666, 1668),
    (0xC403010F, 1668, 1670),
    (0xC4030114, 1670, 1672),
    (0xC4030115, 1672, 1674),
    (0xC4030116, 1674, 1676),
    (0xC4030117, 1676, 1678),
    (0xC4030118, 1678, 1679),
    (0xC4030119, 1679, 1680),
    (0xC403011D, 1680, 1682),
    (0xC4030120, 1682, 1684),
    (0xC4030121, 1684, 1685),
    (0xC4030122, 1685, 1687),
    (0xC4030138, 1687, 1688),
    (0xC4030139, 1688, 1689),
    (0xC4030140, 1689, 1691),
    (0xC4030141, 1691, 1692),
    (0xC4030142, 1692, 1694),
    (0xC4030146, 1694, 1695),
    (0xC403014A, 1695, 1697),
    (0xC403014B, 1697, 1699),
    (0xC403014C, 1699, 1701),
    (0xC4030160, 1701, 1703),
    (0xC4030161, 1703, 1705),
    (0xC4030162, 1705, 1706),
    (0xC4030163, 1706, 1707),
    (0xC40303F0, 1707, 1709),
    (0xF20F38F0, 1709, 1710),
    (0xF20F38F1, 1710, 1711),
];
#[cfg(test)]
pub static FORMS: &[(u32, &str)] = &[
    (536871168, "VEX_Vmovups_xmm_xmmm128"),
    (536871169, "VEX_Vmovups_ymm_ymmm256"),
    (536871184, "VEX_Vmovups_xmmm128_xmm"),
    (536871185, "VEX_Vmovups_ymmm256_ymm"),
    (536871200, "VEX_Vmovhlps_xmm_xmm_xmm"),
    (536871201, "VEX_Vmovlps_xmm_xmm_m64"),
    (536871216, "VEX_Vmovlps_m64_xmm"),
    (536871232, "VEX_Vunpcklps_xmm_xmm_xmmm128"),
    (536871233, "VEX_Vunpcklps_ymm_ymm_ymmm256"),
    (536871248, "VEX_Vunpckhps_xmm_xmm_xmmm128"),
    (536871249, "VEX_Vunpckhps_ymm_ymm_ymmm256"),
    (536871264, "VEX_Vmovhps_xmm_xmm_m64"),
    (536871265, "VEX_Vmovlhps_xmm_xmm_xmm"),
    (536871280, "VEX_Vmovhps_m64_xmm"),
    (536871552, "VEX_Vmovaps_xmm_xmmm128"),
    (536871553, "VEX_Vmovaps_ymm_ymmm256"),
    (536871568, "VEX_Vmovaps_xmmm128_xmm"),
    (536871569, "VEX_Vmovaps_ymmm256_ymm"),
    (536871600, "VEX_Vmovntps_m128_xmm"),
    (536871601, "VEX_Vmovntps_m256_ymm"),
    (536871648, "VEX_Vucomiss_xmm_xmmm32"),
    (536871664, "VEX_Vcomiss_xmm_xmmm32"),
    (536872192, "VEX_Vmovmskps_r32_xmm"),
    (536872193, "VEX_Vmovmskps_r32_ymm"),
    (536872194, "VEX_Vmovmskps_r64_xmm"),
    (536872195, "VEX_Vmovmskps_r64_ymm"),
    (536872208, "VEX_Vsqrtps_xmm_xmmm128"),
    (536872209, "VEX_Vsqrtps_ymm_ymmm256"),
    (536872224, "VEX_Vrsqrtps_xmm_xmmm128"),
    (536872225, "VEX_Vrsqrtps_ymm_ymmm256"),
    (536872240, "VEX_Vrcpps_xmm_xmmm128"),
    (536872241, "VEX_Vrcpps_ymm_ymmm256"),
    (536872256, "VEX_Vandps_xmm_xmm_xmmm128"),
    (536872257, "VEX_Vandps_ymm_ymm_ymmm256"),
    (536872272, "VEX_Vandnps_xmm_xmm_xmmm128"),
    (536872273, "VEX_Vandnps_ymm_ymm_ymmm256"),
    (536872288, "VEX_Vorps_xmm_xmm_xmmm128"),
    (536872289, "VEX_Vorps_ymm_ymm_ymmm256"),
    (536872304, "VEX_Vxorps_xmm_xmm_xmmm128"),
    (536872305, "VEX_Vxorps_ymm_ymm_ymmm256"),
    (536872320, "VEX_Vaddps_xmm_xmm_xmmm128"),
    (536872321, "VEX_Vaddps_ymm_ymm_ymmm256"),
    (536872336, "VEX_Vmulps_xmm_xmm_xmmm128"),
    (536872337, "VEX_Vmulps_ymm_ymm_ymmm256"),
    (536872352, "VEX_Vcvtps2pd_xmm_xmmm64"),
    (536872353, "VEX_Vcvtps2pd_ymm_xmmm128"),
    (536872368, "VEX_Vcvtdq2ps_xmm_xmmm128"),
    (536872369, "VEX_Vcvtdq2ps_ymm_ymmm256"),
    (536872384, "VEX_Vsubps_xmm_xmm_xmmm128"),
    (536872385, "VEX_Vsubps_ymm_ymm_ymmm256"),
    (536872400, "VEX_Vminps_xmm_xmm_xmmm128"),
    (536872401, "VEX_Vminps_ymm_ymm_ymmm256"),
    (536872416, "VEX_Vdivps_xmm_xmm_xmmm128"),
    (536872417, "VEX_Vdivps_ymm_ymm_ymmm256"),
    (536872432, "VEX_Vmaxps_xmm_xmm_xmmm128"),
    (536872433, "VEX_Vmaxps_ymm_ymm_ymmm256"),
    (536872816, "VEX_Vzeroall"),
    (536872817, "VEX_Vzeroupper"),
    (536873696, "VEX_Vldmxcsr_m32"),
    (536873697, "VEX_Vstmxcsr_m32"),
    (536874016, "VEX_Vcmpps_xmm_xmm_xmmm128_imm8"),
    (536874017, "VEX_Vcmpps_ymm_ymm_ymmm256_imm8"),
    (536874080, "VEX_Vshufps_xmm_xmm_xmmm128_imm8"),
    (536874081, "VEX_Vshufps_ymm_ymm_ymmm256_imm8"),
    (536875264, "VEX_Vmovupd_xmm_xmmm128"),
    (536875265, "VEX_Vmovupd_ymm_ymmm256"),
    (536875280, "VEX_Vmovupd_xmmm128_xmm"),
    (536875281, "VEX_Vmovupd_ymmm256_ymm"),
    (536875296, "VEX_Vmovlpd_xmm_xmm_m64"),
    (536875312, "VEX_Vmovlpd_m64_xmm"),
    (536875328, "VEX_Vunpcklpd_xmm_xmm_xmmm128"),
    (536875329, "VEX_Vunpcklpd_ymm_ymm_ymmm256"),
    (536875344, "VEX_Vunpckhpd_xmm_xmm_xmmm128"),
    (536875345, "VEX_Vunpckhpd_ymm_ymm_ymmm256"),
    (536875360, "VEX_Vmovhpd_xmm_xmm_m64"),
    (536875376, "VEX_Vmovhpd_m64_xmm"),
    (536875648, "VEX_Vmovapd_xmm_xmmm128"),
    (536875649, "VEX_Vmovapd_ymm_ymmm256"),
    (536875664, "VEX_Vmovapd_xmmm128_xmm"),
    (536875665, "VEX_Vmovapd_ymmm256_ymm"),
    (536875696, "VEX_Vmovntpd_m128_xmm"),
    (536875697, "VEX_Vmovntpd_m256_ymm"),
    (536875744, "VEX_Vucomisd_xmm_xmmm64"),
    (536875760, "VEX_Vcomisd_xmm_xmmm64"),
    (536876288, "VEX_Vmovmskpd_r32_xmm"),
    (536876289, "VEX_Vmovmskpd_r32_ymm"),
    (536876290, "VEX_Vmovmskpd_r64_xmm"),
    (536876291, "VEX_Vmovmskpd_r64_ymm"),
    (536876304, "VEX_Vsqrtpd_xmm_xmmm128"),
    (536876305, "VEX_Vsqrtpd_ymm_ymmm256"),
    (536876352, "VEX_Vandpd_xmm_xmm_xmmm128"),
    (536876353, "VEX_Vandpd_ymm_ymm_ymmm256"),
    (536876368, "VEX_Vandnpd_xmm_xmm_xmmm128"),
    (536876369, "VEX_Vandnpd_ymm_ymm_ymmm256"),
    (536876384, "VEX_Vorpd_xmm_xmm_xmmm128"),
    (536876385, "VEX_Vorpd_ymm_ymm_ymmm256"),
    (536876400, "VEX_Vxorpd_xmm_xmm_xmmm128"),
    (536876401, "VEX_Vxorpd_ymm_ymm_ymmm256"),
    (536876416, "VEX_Vaddpd_xmm_xmm_xmmm128"),
    (536876417, "VEX_Vaddpd_ymm_ymm_ymmm256"),
    (536876432, "VEX_Vmulpd_xmm_xmm_xmmm128"),
    (536876433, "VEX_Vmulpd_ymm_ymm_ymmm256"),
    (536876448, "VEX_Vcvtpd2ps_xmm_xmmm128"),
    (536876449, "VEX_Vcvtpd2ps_xmm_ymmm256"),
    (536876464, "VEX_Vcvtps2dq_xmm_xmmm128"),
    (536876465, "VEX_Vcvtps2dq_ymm_ymmm256"),
    (536876480, "VEX_Vsubpd_xmm_xmm_xmmm128"),
    (536876481, "VEX_Vsubpd_ymm_ymm_ymmm256"),
    (536876496, "VEX_Vminpd_xmm_xmm_xmmm128"),
    (536876497, "VEX_Vminpd_ymm_ymm_ymmm256"),
    (536876512, "VEX_Vdivpd_xmm_xmm_xmmm128"),
    (536876513, "VEX_Vdivpd_ymm_ymm_ymmm256"),
    (536876528, "VEX_Vmaxpd_xmm_xmm_xmmm128"),
    (536876529, "VEX_Vmaxpd_ymm_ymm_ymmm256"),
    (536876544, "VEX_Vpunpcklbw_xmm_xmm_xmmm128"),
    (536876545, "VEX_Vpunpcklbw_ymm_ymm_ymmm256"),
    (536876560, "VEX_Vpunpcklwd_xmm_xmm_xmmm128"),
    (536876561, "VEX_Vpunpcklwd_ymm_ymm_ymmm256"),
    (536876576, "VEX_Vpunpckldq_xmm_xmm_xmmm128"),
    (536876577, "VEX_Vpunpckldq_ymm_ymm_ymmm256"),
    (536876592, "VEX_Vpacksswb_xmm_xmm_xmmm128"),
    (536876593, "VEX_Vpacksswb_ymm_ymm_ymmm256"),
    (536876608, "VEX_Vpcmpgtb_xmm_xmm_xmmm128"),
    (536876609, "VEX_Vpcmpgtb_ymm_ymm_ymmm256"),
    (536876624, "VEX_Vpcmpgtw_xmm_xmm_xmmm128"),
    (536876625, "VEX_Vpcmpgtw_ymm_ymm_ymmm256"),
    (536876640, "VEX_Vpcmpgtd_xmm_xmm_xmmm128"),
    (536876641, "VEX_Vpcmpgtd_ymm_ymm_ymmm256"),
    (536876656, "VEX_Vpackuswb_xmm_xmm_xmmm128"),
    (536876657, "VEX_Vpackuswb_ymm_ymm_ymmm256"),
    (536876672, "VEX_Vpunpckhbw_xmm_xmm_xmmm128"),
    (536876673, "VEX_Vpunpckhbw_ymm_ymm_ymmm256"),
    (536876688, "VEX_Vpunpckhwd_xmm_xmm_xmmm128"),
    (536876689, "VEX_Vpunpckhwd_ymm_ymm_ymmm256"),
    (536876704, "VEX_Vpunpckhdq_xmm_xmm_xmmm128"),
    (536876705, "VEX_Vpunpckhdq_ymm_ymm_ymmm256"),
    (536876720, "VEX_Vpackssdw_xmm_xmm_xmmm128"),
    (536876721, "VEX_Vpackssdw_ymm_ymm_ymmm256"),
    (536876736, "VEX_Vpunpcklqdq_xmm_xmm_xmmm128"),
    (536876737, "VEX_Vpunpcklqdq_ymm_ymm_ymmm256"),
    (536876752, "VEX_Vpunpckhqdq_xmm_xmm_xmmm128"),
    (536876753, "VEX_Vpunpckhqdq_ymm_ymm_ymmm256"),
    (536876768, "VEX_Vmovd_xmm_rm32"),
    (536876769, "VEX_Vmovq_xmm_rm64"),
    (536876784, "VEX_Vmovdqa_xmm_xmmm128"),
    (536876785, "VEX_Vmovdqa_ymm_ymmm256"),
    (536876800, "VEX_Vpshufd_xmm_xmmm128_imm8"),
    (536876801, "VEX_Vpshufd_ymm_ymmm256_imm8"),
    (536876816, "VEX_Vpsrlw_xmm_xmm_imm8"),
    (536876817, "VEX_Vpsrlw_ymm_ymm_imm8"),
    (536876818, "VEX_Vpsraw_xmm_xmm_imm8"),
    (536876819, "VEX_Vpsraw_ymm_ymm_imm8"),
    (536876820, "VEX_Vpsllw_xmm_xmm_imm8"),
    (536876821, "VEX_Vpsllw_ymm_ymm_imm8"),
    (536876832, "VEX_Vpsrld_xmm_xmm_imm8"),
    (536876833, "VEX_Vpsrld_ymm_ymm_imm8"),
    (536876834, "VEX_Vpsrad_xmm_xmm_imm8"),
    (536876835, "VEX_Vpsrad_ymm_ymm_imm8"),
    (536876836, "VEX_Vpslld_xmm_xmm_imm8"),
    (536876837, "VEX_Vpslld_ymm_ymm_imm8"),
    (536876848, "VEX_Vpsrlq_xmm_xmm_imm8"),
    (536876849, "VEX_Vpsrlq_ymm_ymm_imm8"),
    (536876850, "VEX_Vpsrldq_xmm_xmm_imm8"),
    (536876851, "VEX_Vpsrldq_ymm_ymm_imm8"),
    (536876852, "VEX_Vpsllq_xmm_xmm_imm8"),
    (536876853, "VEX_Vpsllq_ymm_ymm_imm8"),
    (536876854, "VEX_Vpslldq_xmm_xmm_imm8"),
    (536876855, "VEX_Vpslldq_ymm_ymm_imm8"),
    (536876864, "VEX_Vpcmpeqb_xmm_xmm_xmmm128"),
    (536876865, "VEX_Vpcmpeqb_ymm_ymm_ymmm256"),
    (536876880, "VEX_Vpcmpeqw_xmm_xmm_xmmm128"),
    (536876881, "VEX_Vpcmpeqw_ymm_ymm_ymmm256"),
    (536876896, "VEX_Vpcmpeqd_xmm_xmm_xmmm128"),
    (536876897, "VEX_Vpcmpeqd_ymm_ymm_ymmm256"),
    (536876992, "VEX_Vhaddpd_xmm_xmm_xmmm128"),
    (536876993, "VEX_Vhaddpd_ymm_ymm_ymmm256"),
    (536877008, "VEX_Vhsubpd_xmm_xmm_xmmm128"),
    (536877009, "VEX_Vhsubpd_ymm_ymm_ymmm256"),
    (536877024, "VEX_Vmovd_rm32_xmm"),
    (536877025, "VEX_Vmovq_rm64_xmm"),
    (536877040, "VEX_Vmovdqa_xmmm128_xmm"),
    (536877041, "VEX_Vmovdqa_ymmm256_ymm"),
    (536878112, "VEX_Vcmppd_xmm_xmm_xmmm128_imm8"),
    (536878113, "VEX_Vcmppd_ymm_ymm_ymmm256_imm8"),
    (536878144, "VEX_Vpinsrw_xmm_xmm_r32m16_imm8"),
    (536878145, "VEX_Vpinsrw_xmm_xmm_r64m16_imm8"),
    (536878160, "VEX_Vpextrw_r32_xmm_imm8"),
    (536878161, "VEX_Vpextrw_r64_xmm_imm8"),
    (536878176, "VEX_Vshufpd_xmm_xmm_xmmm128_imm8"),
    (536878177, "VEX_Vshufpd_ymm_ymm_ymmm256_imm8"),
    (536878336, "VEX_Vaddsubpd_xmm_xmm_xmmm128"),
    (536878337, "VEX_Vaddsubpd_ymm_ymm_ymmm256"),
    (536878352, "VEX_Vpsrlw_xmm_xmm_xmmm128"),
    (536878353, "VEX_Vpsrlw_ymm_ymm_xmmm128"),
    (536878368, "VEX_Vpsrld_xmm_xmm_xmmm128"),
    (536878369, "VEX_Vpsrld_ymm_ymm_xmmm128"),
    (536878384, "VEX_Vpsrlq_xmm_xmm_xmmm128"),
    (536878385, "VEX_Vpsrlq_ymm_ymm_xmmm128"),
    (536878400, "VEX_Vpaddq_xmm_xmm_xmmm128"),
    (536878401, "VEX_Vpaddq_ymm_ymm_ymmm256"),
    (536878416, "VEX_Vpmullw_xmm_xmm_xmmm128"),
    (536878417, "VEX_Vpmullw_ymm_ymm_ymmm256"),
    (536878432, "VEX_Vmovq_xmmm64_xmm"),
    (536878448, "VEX_Vpmovmskb_r32_xmm"),
    (536878449, "VEX_Vpmovmskb_r32_ymm"),
    (536878450, "VEX_Vpmovmskb_r64_xmm"),
    (536878451, "VEX_Vpmovmskb_r64_ymm"),
    (536878464, "VEX_Vpsubusb_xmm_xmm_xmmm128"),
    (536878465, "VEX_Vpsubusb_ymm_ymm_ymmm256"),
    (536878480, "VEX_Vpsubusw_xmm_xmm_xmmm128"),
    (536878481, "VEX_Vpsubusw_ymm_ymm_ymmm256"),
    (536878496, "VEX_Vpminub_xmm_xmm_xmmm128"),
    (536878497, "VEX_Vpminub_ymm_ymm_ymmm256"),
    (536878512, "VEX_Vpand_xmm_xmm_xmmm128"),
    (536878513, "VEX_Vpand_ymm_ymm_ymmm256"),
    (536878528, "VEX_Vpaddusb_xmm_xmm_xmmm128"),
    (536878529, "VEX_Vpaddusb_ymm_ymm_ymmm256"),
    (536878544, "VEX_Vpaddusw_xmm_xmm_xmmm128"),
    (536878545, "VEX_Vpaddusw_ymm_ymm_ymmm256"),
    (536878560, "VEX_Vpmaxub_xmm_xmm_xmmm128"),
    (536878561, "VEX_Vpmaxub_ymm_ymm_ymmm256"),
    (536878576, "VEX_Vpandn_xmm_xmm_xmmm128"),
    (536878577, "VEX_Vpandn_ymm_ymm_ymmm256"),
    (536878592, "VEX_Vpavgb_xmm_xmm_xmmm128"),
    (536878593, "VEX_Vpavgb_ymm_ymm_ymmm256"),
    (536878608, "VEX_Vpsraw_xmm_xmm_xmmm128"),
    (536878609, "VEX_Vpsraw_ymm_ymm_xmmm128"),
    (536878624, "VEX_Vpsrad_xmm_xmm_xmmm128"),
    (536878625, "VEX_Vpsrad_ymm_ymm_xmmm128"),
    (536878640, "VEX_Vpavgw_xmm_xmm_xmmm128"),
    (536878641, "VEX_Vpavgw_ymm_ymm_ymmm256"),
    (536878656, "VEX_Vpmulhuw_xmm_xmm_xmmm128"),
    (536878657, "VEX_Vpmulhuw_ymm_ymm_ymmm256"),
    (536878672, "VEX_Vpmulhw_xmm_xmm_xmmm128"),
    (536878673, "VEX_Vpmulhw_ymm_ymm_ymmm256"),
    (536878688, "VEX_Vcvttpd2dq_xmm_xmmm128"),
    (536878689, "VEX_Vcvttpd2dq_xmm_ymmm256"),
    (536878704, "VEX_Vmovntdq_m128_xmm"),
    (536878705, "VEX_Vmovntdq_m256_ymm"),
    (536878720, "VEX_Vpsubsb_xmm_xmm_xmmm128"),
    (536878721, "VEX_Vpsubsb_ymm_ymm_ymmm256"),
    (536878736, "VEX_Vpsubsw_xmm_xmm_xmmm128"),
    (536878737, "VEX_Vpsubsw_ymm_ymm_ymmm256"),
    (536878752, "VEX_Vpminsw_xmm_xmm_xmmm128"),
    (536878753, "VEX_Vpminsw_ymm_ymm_ymmm256"),
    (536878768, "VEX_Vpor_xmm_xmm_xmmm128"),
    (536878769, "VEX_Vpor_ymm_ymm_ymmm256"),
    (536878784, "VEX_Vpaddsb_xmm_xmm_xmmm128"),
    (536878785, "VEX_Vpaddsb_ymm_ymm_ymmm256"),
    (536878800, "VEX_Vpaddsw_xmm_xmm_xmmm128"),
    (536878801, "VEX_Vpaddsw_ymm_ymm_ymmm256"),
    (536878816, "VEX_Vpmaxsw_xmm_xmm_xmmm128"),
    (536878817, "VEX_Vpmaxsw_ymm_ymm_ymmm256"),
    (536878832, "VEX_Vpxor_xmm_xmm_xmmm128"),
    (536878833, "VEX_Vpxor_ymm_ymm_ymmm256"),
    (536878864, "VEX_Vpsllw_xmm_xmm_xmmm128"),
    (536878865, "VEX_Vpsllw_ymm_ymm_xmmm128"),
    (536878880, "VEX_Vpslld_xmm_xmm_xmmm128"),
    (536878881, "VEX_Vpslld_ymm_ymm_xmmm128"),
    (536878896, "VEX_Vpsllq_xmm_xmm_xmmm128"),
    (536878897, "VEX_Vpsllq_ymm_ymm_xmmm128"),
    (536878912, "VEX_Vpmuludq_xmm_xmm_xmmm128"),
    (536878913, "VEX_Vpmuludq_ymm_ymm_ymmm256"),
    (536878928, "VEX_Vpmaddwd_xmm_xmm_xmmm128"),
    (536878929, "VEX_Vpmaddwd_ymm_ymm_ymmm256"),
    (536878944, "VEX_Vpsadbw_xmm_xmm_xmmm128"),
    (536878945, "VEX_Vpsadbw_ymm_ymm_ymmm256"),
    (536878960, "VEX_Vmaskmovdqu_rDI_xmm_xmm"),
    (536878976, "VEX_Vpsubb_xmm_xmm_xmmm128"),
    (536878977, "VEX_Vpsubb_ymm_ymm_ymmm256"),
    (536878992, "VEX_Vpsubw_xmm_xmm_xmmm128"),
    (536878993, "VEX_Vpsubw_ymm_ymm_ymmm256"),
    (536879008, "VEX_Vpsubd_xmm_xmm_xmmm128"),
    (536879009, "VEX_Vpsubd_ymm_ymm_ymmm256"),
    (536879024, "VEX_Vpsubq_xmm_xmm_xmmm128"),
    (536879025, "VEX_Vpsubq_ymm_ymm_ymmm256"),
    (536879040, "VEX_Vpaddb_xmm_xmm_xmmm128"),
    (536879041, "VEX_Vpaddb_ymm_ymm_ymmm256"),
    (536879056, "VEX_Vpaddw_xmm_xmm_xmmm128"),
    (536879057, "VEX_Vpaddw_ymm_ymm_ymmm256"),
    (536879072, "VEX_Vpaddd_xmm_xmm_xmmm128"),
    (536879073, "VEX_Vpaddd_ymm_ymm_ymmm256"),
    (536879360, "VEX_Vmovss_xmm_m32"),
    (536879361, "VEX_Vmovss_xmm_xmm_xmm"),
    (536879376, "VEX_Vmovss_m32_xmm"),
    (536879377, "VEX_Vmovss_xmm_xmm_xmm_0F11"),
    (536879392, "VEX_Vmovsldup_xmm_xmmm128"),
    (536879393, "VEX_Vmovsldup_ymm_ymmm256"),
    (536879456, "VEX_Vmovshdup_xmm_xmmm128"),
    (536879457, "VEX_Vmovshdup_ymm_ymmm256"),
    (536879776, "VEX_Vcvtsi2ss_xmm_xmm_rm32"),
    (536879777, "VEX_Vcvtsi2ss_xmm_xmm_rm64"),
    (536879808, "VEX_Vcvttss2si_r32_xmmm32"),
    (536879809, "VEX_Vcvttss2si_r64_xmmm32"),
    (536879824, "VEX_Vcvtss2si_r32_xmmm32"),
    (536879825, "VEX_Vcvtss2si_r64_xmmm32"),
    (536880400, "VEX_Vsqrtss_xmm_xmm_xmmm32"),
    (536880416, "VEX_Vrsqrtss_xmm_xmm_xmmm32"),
    (536880432, "VEX_Vrcpss_xmm_xmm_xmmm32"),
    (536880512, "VEX_Vaddss_xmm_xmm_xmmm32"),
    (536880528, "VEX_Vmulss_xmm_xmm_xmmm32"),
    (536880544, "VEX_Vcvtss2sd_xmm_xmm_xmmm32"),
    (536880560, "VEX_Vcvttps2dq_xmm_xmmm128"),
    (536880561, "VEX_Vcvttps2dq_ymm_ymmm256"),
    (536880576, "VEX_Vsubss_xmm_xmm_xmmm32"),
    (536880592, "VEX_Vminss_xmm_xmm_xmmm32"),
    (536880608, "VEX_Vdivss_xmm_xmm_xmmm32"),
    (536880624, "VEX_Vmaxss_xmm_xmm_xmmm32"),
    (536880880, "VEX_Vmovdqu_xmm_xmmm128"),
    (536880881, "VEX_Vmovdqu_ymm_ymmm256"),
    (536880896, "VEX_Vpshufhw_xmm_xmmm128_imm8"),
    (536880897, "VEX_Vpshufhw_ymm_ymmm256_imm8"),
    (536881120, "VEX_Vmovq_xmm_xmmm64"),
    (536881136, "VEX_Vmovdqu_xmmm128_xmm"),
    (536881137, "VEX_Vmovdqu_ymmm256_ymm"),
    (536882208, "VEX_Vcmpss_xmm_xmm_xmmm32_imm8"),
    (536882784, "VEX_Vcvtdq2pd_xmm_xmmm64"),
    (536882785, "VEX_Vcvtdq2pd_ymm_xmmm128"),
    (536883456, "VEX_Vmovsd_xmm_m64"),
    (536883457, "VEX_Vmovsd_xmm_xmm_xmm"),
    (536883472, "VEX_Vmovsd_m64_xmm"),
    (536883473, "VEX_Vmovsd_xmm_xmm_xmm_0F11"),
    (536883488, "VEX_Vmovddup_xmm_xmmm64"),
    (536883489, "VEX_Vmovddup_ymm_ymmm256"),
    (536883872, "VEX_Vcvtsi2sd_xmm_xmm_rm32"),
    (536883873, "VEX_Vcvtsi2sd_xmm_xmm_rm64"),
    (536883904, "VEX_Vcvttsd2si_r32_xmmm64"),
    (536883905, "VEX_Vcvttsd2si_r64_xmmm64"),
    (536883920, "VEX_Vcvtsd2si_r32_xmmm64"),
    (536883921, "VEX_Vcvtsd2si_r64_xmmm64"),
    (536884496, "VEX_Vsqrtsd_xmm_xmm_xmmm64"),
    (536884608, "VEX_Vaddsd_xmm_xmm_xmmm64"),
    (536884624, "VEX_Vmulsd_xmm_xmm_xmmm64"),
    (536884640, "VEX_Vcvtsd2ss_xmm_xmm_xmmm64"),
    (536884672, "VEX_Vsubsd_xmm_xmm_xmmm64"),
    (536884688, "VEX_Vminsd_xmm_xmm_xmmm64"),
    (536884704, "VEX_Vdivsd_xmm_xmm_xmmm64"),
    (536884720, "VEX_Vmaxsd_xmm_xmm_xmmm64"),
    (536884992, "VEX_Vpshuflw_xmm_xmmm128_imm8"),
    (536884993, "VEX_Vpshuflw_ymm_ymmm256_imm8"),
    (536885184, "VEX_Vhaddps_xmm_xmm_xmmm128"),
    (536885185, "VEX_Vhaddps_ymm_ymm_ymmm256"),
    (536885200, "VEX_Vhsubps_xmm_xmm_xmmm128"),
    (536885201, "VEX_Vhsubps_ymm_ymm_ymmm256"),
    (536886304, "VEX_Vcmpsd_xmm_xmm_xmmm64_imm8"),
    (536886528, "VEX_Vaddsubps_xmm_xmm_xmmm128"),
    (536886529, "VEX_Vaddsubps_ymm_ymm_ymmm256"),
    (536886880, "VEX_Vcvtpd2dq_xmm_xmmm128"),
    (536886881, "VEX_Vcvtpd2dq_xmm_ymmm256"),
    (536887040, "VEX_Vlddqu_xmm_m128"),
    (536887041, "VEX_Vlddqu_ymm_m256"),
    (536891168, "VEX_Andn_r32_r32_rm32"),
    (536891169, "VEX_Andn_r64_r64_rm64"),
    (536891184, "VEX_Blsr_r32_rm32"),
    (536891185, "VEX_Blsr_r64_rm64"),
    (536891186, "VEX_Blsmsk_r32_rm32"),
    (536891187, "VEX_Blsmsk_r64_rm64"),
    (536891188, "VEX_Blsi_r32_rm32"),
    (536891189, "VEX_Blsi_r64_rm64"),
    (536891216, "VEX_Bzhi_r32_rm32_r32"),
    (536891217, "VEX_Bzhi_r64_rm64_r64"),
    (536891248, "VEX_Bextr_r32_rm32_r32"),
    (536891249, "VEX_Bextr_r64_rm64_r64"),
    (536891392, "VEX_Vpshufb_xmm_xmm_xmmm128"),
    (536891393, "VEX_Vpshufb_ymm_ymm_ymmm256"),
    (536891408, "VEX_Vphaddw_xmm_xmm_xmmm128"),
    (536891409, "VEX_Vphaddw_ymm_ymm_ymmm256"),
    (536891424, "VEX_Vphaddd_xmm_xmm_xmmm128"),
    (536891425, "VEX_Vphaddd_ymm_ymm_ymmm256"),
    (536891440, "VEX_Vphaddsw_xmm_xmm_xmmm128"),
    (536891441, "VEX_Vphaddsw_ymm_ymm_ymmm256"),
    (536891456, "VEX_Vpmaddubsw_xmm_xmm_xmmm128"),
    (536891457, "VEX_Vpmaddubsw_ymm_ymm_ymmm256"),
    (536891472, "VEX_Vphsubw_xmm_xmm_xmmm128"),
    (536891473, "VEX_Vphsubw_ymm_ymm_ymmm256"),
    (536891488, "VEX_Vphsubd_xmm_xmm_xmmm128"),
    (536891489, "VEX_Vphsubd_ymm_ymm_ymmm256"),
    (536891504, "VEX_Vphsubsw_xmm_xmm_xmmm128"),
    (536891505, "VEX_Vphsubsw_ymm_ymm_ymmm256"),
    (536891520, "VEX_Vpsignb_xmm_xmm_xmmm128"),
    (536891521, "VEX_Vpsignb_ymm_ymm_ymmm256"),
    (536891536, "VEX_Vpsignw_xmm_xmm_xmmm128"),
    (536891537, "VEX_Vpsignw_ymm_ymm_ymmm256"),
    (536891552, "VEX_Vpsignd_xmm_xmm_xmmm128"),
    (536891553, "VEX_Vpsignd_ymm_ymm_ymmm256"),
    (536891568, "VEX_Vpmulhrsw_xmm_xmm_xmmm128"),
    (536891569, "VEX_Vpmulhrsw_ymm_ymm_ymmm256"),
    (536891584, "VEX_Vpermilps_xmm_xmm_xmmm128"),
    (536891585, "VEX_Vpermilps_ymm_ymm_ymmm256"),
    (536891600, "VEX_Vpermilpd_xmm_xmm_xmmm128"),
    (536891601, "VEX_Vpermilpd_ymm_ymm_ymmm256"),
    (536891616, "VEX_Vtestps_xmm_xmmm128"),
    (536891617, "VEX_Vtestps_ymm_ymmm256"),
    (536891632, "VEX_Vtestpd_xmm_xmmm128"),
    (536891633, "VEX_Vtestpd_ymm_ymmm256"),
    (536891696, "VEX_Vcvtph2ps_xmm_xmmm64"),
    (536891697, "VEX_Vcvtph2ps_ymm_xmmm128"),
    (536891744, "VEX_Vpermps_ymm_ymm_ymmm256"),
    (536891760, "VEX_Vptest_xmm_xmmm128"),
    (536891761, "VEX_Vptest_ymm_ymmm256"),
    (536891776, "VEX_Vbroadcastss_xmm_m32"),
    (536891777, "VEX_Vbroadcastss_xmm_xmm"),
    (536891778, "VEX_Vbroadcastss_ymm_m32"),
    (536891779, "VEX_Vbroadcastss_ymm_xmm"),
    (536891792, "VEX_Vbroadcastsd_ymm_m64"),
    (536891793, "VEX_Vbroadcastsd_ymm_xmm"),
    (536891808, "VEX_Vbroadcastf128_ymm_m128"),
    (536891840, "VEX_Vpabsb_xmm_xmmm128"),
    (536891841, "VEX_Vpabsb_ymm_ymmm256"),
    (536891856, "VEX_Vpabsw_xmm_xmmm128"),
    (536891857, "VEX_Vpabsw_ymm_ymmm256"),
    (536891872, "VEX_Vpabsd_xmm_xmmm128"),
    (536891873, "VEX_Vpabsd_ymm_ymmm256"),
    (536891904, "VEX_Vpmovsxbw_xmm_xmmm64"),
    (536891905, "VEX_Vpmovsxbw_ymm_xmmm128"),
    (536891920, "VEX_Vpmovsxbd_xmm_xmmm32"),
    (536891921, "VEX_Vpmovsxbd_ymm_xmmm64"),
    (536891936, "VEX_Vpmovsxbq_xmm_xmmm16"),
    (536891937, "VEX_Vpmovsxbq_ymm_xmmm32"),
    (536891952, "VEX_Vpmovsxwd_xmm_xmmm64"),
    (536891953, "VEX_Vpmovsxwd_ymm_xmmm128"),
    (536891968, "VEX_Vpmovsxwq_xmm_xmmm32"),
    (536891969, "VEX_Vpmovsxwq_ymm_xmmm64"),
    (536891984, "VEX_Vpmovsxdq_xmm_xmmm64"),
    (536891985, "VEX_Vpmovsxdq_ymm_xmmm128"),
    (536892032, "VEX_Vpmuldq_xmm_xmm_xmmm128"),
    (536892033, "VEX_Vpmuldq_ymm_ymm_ymmm256"),
    (536892048, "VEX_Vpcmpeqq_xmm_xmm_xmmm128"),
    (536892049, "VEX_Vpcmpeqq_ymm_ymm_ymmm256"),
    (536892064, "VEX_Vmovntdqa_xmm_m128"),
    (536892065, "VEX_Vmovntdqa_ymm_m256"),
    (536892080, "VEX_Vpackusdw_xmm_xmm_xmmm128"),
    (536892081, "VEX_Vpackusdw_ymm_ymm_ymmm256"),
    (536892096, "VEX_Vmaskmovps_xmm_xmm_m128"),
    (536892097, "VEX_Vmaskmovps_ymm_ymm_m256"),
    (536892112, "VEX_Vmaskmovpd_xmm_xmm_m128"),
    (536892113, "VEX_Vmaskmovpd_ymm_ymm_m256"),
    (536892128, "VEX_Vmaskmovps_m128_xmm_xmm"),
    (536892129, "VEX_Vmaskmovps_m256_ymm_ymm"),
    (536892144, "VEX_Vmaskmovpd_m128_xmm_xmm"),
    (536892145, "VEX_Vmaskmovpd_m256_ymm_ymm"),
    (536892160, "VEX_Vpmovzxbw_xmm_xmmm64"),
    (536892161, "VEX_Vpmovzxbw_ymm_xmmm128"),
    (536892176, "VEX_Vpmovzxbd_xmm_xmmm32"),
    (536892177, "VEX_Vpmovzxbd_ymm_xmmm64"),
    (536892192, "VEX_Vpmovzxbq_xmm_xmmm16"),
    (536892193, "VEX_Vpmovzxbq_ymm_xmmm32"),
    (536892208, "VEX_Vpmovzxwd_xmm_xmmm64"),
    (536892209, "VEX_Vpmovzxwd_ymm_xmmm128"),
    (536892224, "VEX_Vpmovzxwq_xmm_xmmm32"),
    (536892225, "VEX_Vpmovzxwq_ymm_xmmm64"),
    (536892240, "VEX_Vpmovzxdq_xmm_xmmm64"),
    (536892241, "VEX_Vpmovzxdq_ymm_xmmm128"),
    (536892256, "VEX_Vpermd_ymm_ymm_ymmm256"),
    (536892272, "VEX_Vpcmpgtq_xmm_xmm_xmmm128"),
    (536892273, "VEX_Vpcmpgtq_ymm_ymm_ymmm256"),
    (536892288, "VEX_Vpminsb_xmm_xmm_xmmm128"),
    (536892289, "VEX_Vpminsb_ymm_ymm_ymmm256"),
    (536892304, "VEX_Vpminsd_xmm_xmm_xmmm128"),
    (536892305, "VEX_Vpminsd_ymm_ymm_ymmm256"),
    (536892320, "VEX_Vpminuw_xmm_xmm_xmmm128"),
    (536892321, "VEX_Vpminuw_ymm_ymm_ymmm256"),
    (536892336, "VEX_Vpminud_xmm_xmm_xmmm128"),
    (536892337, "VEX_Vpminud_ymm_ymm_ymmm256"),
    (536892352, "VEX_Vpmaxsb_xmm_xmm_xmmm128"),
    (536892353, "VEX_Vpmaxsb_ymm_ymm_ymmm256"),
    (536892368, "VEX_Vpmaxsd_xmm_xmm_xmmm128"),
    (536892369, "VEX_Vpmaxsd_ymm_ymm_ymmm256"),
    (536892384, "VEX_Vpmaxuw_xmm_xmm_xmmm128"),
    (536892385, "VEX_Vpmaxuw_ymm_ymm_ymmm256"),
    (536892400, "VEX_Vpmaxud_xmm_xmm_xmmm128"),
    (536892401, "VEX_Vpmaxud_ymm_ymm_ymmm256"),
    (536892416, "VEX_Vpmulld_xmm_xmm_xmmm128"),
    (536892417, "VEX_Vpmulld_ymm_ymm_ymmm256"),
    (536892432, "VEX_Vphminposuw_xmm_xmmm128"),
    (536892496, "VEX_Vpsrlvd_xmm_xmm_xmmm128"),
    (536892497, "VEX_Vpsrlvd_ymm_ymm_ymmm256"),
    (536892498, "VEX_Vpsrlvq_xmm_xmm_xmmm128"),
    (536892499, "VEX_Vpsrlvq_ymm_ymm_ymmm256"),
    (536892512, "VEX_Vpsravd_xmm_xmm_xmmm128"),
    (536892513, "VEX_Vpsravd_ymm_ymm_ymmm256"),
    (536892528, "VEX_Vpsllvd_xmm_xmm_xmmm128"),
    (536892529, "VEX_Vpsllvd_ymm_ymm_ymmm256"),
    (536892530, "VEX_Vpsllvq_xmm_xmm_xmmm128"),
    (536892531, "VEX_Vpsllvq_ymm_ymm_ymmm256"),
    (536892800, "VEX_Vpbroadcastd_xmm_xmmm32"),
    (536892801, "VEX_Vpbroadcastd_ymm_xmmm32"),
    (536892816, "VEX_Vpbroadcastq_xmm_xmmm64"),
    (536892817, "VEX_Vpbroadcastq_ymm_xmmm64"),
    (536892832, "VEX_Vbroadcasti128_ymm_m128"),
    (536893312, "VEX_Vpbroadcastb_xmm_xmmm8"),
    (536893313, "VEX_Vpbroadcastb_ymm_xmmm8"),
    (536893328, "VEX_Vpbroadcastw_xmm_xmmm16"),
    (536893329, "VEX_Vpbroadcastw_ymm_xmmm16"),
    (536893632, "VEX_Vpmaskmovd_xmm_xmm_m128"),
    (536893633, "VEX_Vpmaskmovd_ymm_ymm_m256"),
    (536893634, "VEX_Vpmaskmovq_xmm_xmm_m128"),
    (536893635, "VEX_Vpmaskmovq_ymm_ymm_m256"),
    (536893664, "VEX_Vpmaskmovd_m128_xmm_xmm"),
    (536893665, "VEX_Vpmaskmovd_m256_ymm_ymm"),
    (536893666, "VEX_Vpmaskmovq_m128_xmm_xmm"),
    (536893667, "VEX_Vpmaskmovq_m256_ymm_ymm"),
    (536893696, "VEX_Vpgatherdd_xmm_vm32x_xmm"),
    (536893697, "VEX_Vpgatherdd_ymm_vm32y_ymm"),
    (536893698, "VEX_Vpgatherdq_xmm_vm32x_xmm"),
    (536893699, "VEX_Vpgatherdq_ymm_vm32x_ymm"),
    (536893712, "VEX_Vpgatherqd_xmm_vm64x_xmm"),
    (536893713, "VEX_Vpgatherqd_xmm_vm64y_xmm"),
    (536893714, "VEX_Vpgatherqq_xmm_vm64x_xmm"),
    (536893715, "VEX_Vpgatherqq_ymm_vm64y_ymm"),
    (536893728, "VEX_Vgatherdpd_xmm_vm32x_xmm"),
    (536893729, "VEX_Vgatherdpd_ymm_vm32x_ymm"),
    (536893730, "VEX_Vgatherdps_xmm_vm32x_xmm"),
    (536893731, "VEX_Vgatherdps_ymm_vm32y_ymm"),
    (536893744, "VEX_Vgatherqpd_xmm_vm64x_xmm"),
    (536893745, "VEX_Vgatherqpd_ymm_vm64y_ymm"),
    (536893746, "VEX_Vgatherqps_xmm_vm64x_xmm"),
    (536893747, "VEX_Vgatherqps_xmm_vm64y_xmm"),
    (536893792, "VEX_Vfmaddsub132pd_xmm_xmm_xmmm128"),
    (536893793, "VEX_Vfmaddsub132pd_ymm_ymm_ymmm256"),
    (536893794, "VEX_Vfmaddsub132ps_xmm_xmm_xmmm128"),
    (536893795, "VEX_Vfmaddsub132ps_ymm_ymm_ymmm256"),
    (536893808, "VEX_Vfmsubadd132pd_xmm_xmm_xmmm128"),
    (536893809, "VEX_Vfmsubadd132pd_ymm_ymm_ymmm256"),
    (536893810, "VEX_Vfmsubadd132ps_xmm_xmm_xmmm128"),
    (536893811, "VEX_Vfmsubadd132ps_ymm_ymm_ymmm256"),
    (536893824, "VEX_Vfmadd132pd_xmm_xmm_xmmm128"),
    (536893825, "VEX_Vfmadd132pd_ymm_ymm_ymmm256"),
    (536893826, "VEX_Vfmadd132ps_xmm_xmm_xmmm128"),
    (536893827, "VEX_Vfmadd132ps_ymm_ymm_ymmm256"),
    (536893840, "VEX_Vfmadd132sd_xmm_xmm_xmmm64"),
    (536893841, "VEX_Vfmadd132ss_xmm_xmm_xmmm32"),
    (536893856, "VEX_Vfmsub132pd_xmm_xmm_xmmm128"),
    (536893857, "VEX_Vfmsub132pd_ymm_ymm_ymmm256"),
    (536893858, "VEX_Vfmsub132ps_xmm_xmm_xmmm128"),
    (536893859, "VEX_Vfmsub132ps_ymm_ymm_ymmm256"),
    (536893872, "VEX_Vfmsub132sd_xmm_xmm_xmmm64"),
    (536893873, "VEX_Vfmsub132ss_xmm_xmm_xmmm32"),
    (536893888, "VEX_Vfnmadd132pd_xmm_xmm_xmmm128"),
    (536893889, "VEX_Vfnmadd132pd_ymm_ymm_ymmm256"),
    (536893890, "VEX_Vfnmadd132ps_xmm_xmm_xmmm128"),
    (536893891, "VEX_Vfnmadd132ps_ymm_ymm_ymmm256"),
    (536893904, "VEX_Vfnmadd132sd_xmm_xmm_xmmm64"),
    (536893905, "VEX_Vfnmadd132ss_xmm_xmm_xmmm32"),
    (536893920, "VEX_Vfnmsub132pd_xmm_xmm_xmmm128"),
    (536893921, "VEX_Vfnmsub132pd_ymm_ymm_ymmm256"),
    (536893922, "VEX_Vfnmsub132ps_xmm_xmm_xmmm128"),
    (536893923, "VEX_Vfnmsub132ps_ymm_ymm_ymmm256"),
    (536893936, "VEX_Vfnmsub132sd_xmm_xmm_xmmm64"),
    (536893937, "VEX_Vfnmsub132ss_xmm_xmm_xmmm32"),
    (536894048, "VEX_Vfmaddsub213pd_xmm_xmm_xmmm128"),
    (536894049, "VEX_Vfmaddsub213pd_ymm_ymm_ymmm256"),
    (536894050, "VEX_Vfmaddsub213ps_xmm_xmm_xmmm128"),
    (536894051, "VEX_Vfmaddsub213ps_ymm_ymm_ymmm256"),
    (536894064, "VEX_Vfmsubadd213pd_xmm_xmm_xmmm128"),
    (536894065, "VEX_Vfmsubadd213pd_ymm_ymm_ymmm256"),
    (536894066, "VEX_Vfmsubadd213ps_xmm_xmm_xmmm128"),
    (536894067, "VEX_Vfmsubadd213ps_ymm_ymm_ymmm256"),
    (536894080, "VEX_Vfmadd213pd_xmm_xmm_xmmm128"),
    (536894081, "VEX_Vfmadd213pd_ymm_ymm_ymmm256"),
    (536894082, "VEX_Vfmadd213ps_xmm_xmm_xmmm128"),
    (536894083, "VEX_Vfmadd213ps_ymm_ymm_ymmm256"),
    (536894096, "VEX_Vfmadd213sd_xmm_xmm_xmmm64"),
    (536894097, "VEX_Vfmadd213ss_xmm_xmm_xmmm32"),
    (536894112, "VEX_Vfmsub213pd_xmm_xmm_xmmm128"),
    (536894113, "VEX_Vfmsub213pd_ymm_ymm_ymmm256"),
    (536894114, "VEX_Vfmsub213ps_xmm_xmm_xmmm128"),
    (536894115, "VEX_Vfmsub213ps_ymm_ymm_ymmm256"),
    (536894128, "VEX_Vfmsub213sd_xmm_xmm_xmmm64"),
    (536894129, "VEX_Vfmsub213ss_xmm_xmm_xmmm32"),
    (536894144, "VEX_Vfnmadd213pd_xmm_xmm_xmmm128"),
    (536894145, "VEX_Vfnmadd213pd_ymm_ymm_ymmm256"),
    (536894146, "VEX_Vfnmadd213ps_xmm_xmm_xmmm128"),
    (536894147, "VEX_Vfnmadd213ps_ymm_ymm_ymmm256"),
    (536894160, "VEX_Vfnmadd213sd_xmm_xmm_xmmm64"),
    (536894161, "VEX_Vfnmadd213ss_xmm_xmm_xmmm32"),
    (536894176, "VEX_Vfnmsub213pd_xmm_xmm_xmmm128"),
    (536894177, "VEX_Vfnmsub213pd_ymm_ymm_ymmm256"),
    (536894178, "VEX_Vfnmsub213ps_xmm_xmm_xmmm128"),
    (536894179, "VEX_Vfnmsub213ps_ymm_ymm_ymmm256"),
    (536894192, "VEX_Vfnmsub213sd_xmm_xmm_xmmm64"),
    (536894193, "VEX_Vfnmsub213ss_xmm_xmm_xmmm32"),
    (536894304, "VEX_Vfmaddsub231pd_xmm_xmm_xmmm128"),
    (536894305, "VEX_Vfmaddsub231pd_ymm_ymm_ymmm256"),
    (536894306, "VEX_Vfmaddsub231ps_xmm_xmm_xmmm128"),
    (536894307, "VEX_Vfmaddsub231ps_ymm_ymm_ymmm256"),
    (536894320, "VEX_Vfmsubadd231pd_xmm_xmm_xmmm128"),
    (536894321, "VEX_Vfmsubadd231pd_ymm_ymm_ymmm256"),
    (536894322, "VEX_Vfmsubadd231ps_xmm_xmm_xmmm128"),
    (536894323, "VEX_Vfmsubadd231ps_ymm_ymm_ymmm256"),
    (536894336, "VEX_Vfmadd231pd_xmm_xmm_xmmm128"),
    (536894337, "VEX_Vfmadd231pd_ymm_ymm_ymmm256"),
    (536894338, "VEX_Vfmadd231ps_xmm_xmm_xmmm128"),
    (536894339, "VEX_Vfmadd231ps_ymm_ymm_ymmm256"),
    (536894352, "VEX_Vfmadd231sd_xmm_xmm_xmmm64"),
    (536894353, "VEX_Vfmadd231ss_xmm_xmm_xmmm32"),
    (536894368, "VEX_Vfmsub231pd_xmm_xmm_xmmm128"),
    (536894369, "VEX_Vfmsub231pd_ymm_ymm_ymmm256"),
    (536894370, "VEX_Vfmsub231ps_xmm_xmm_xmmm128"),
    (536894371, "VEX_Vfmsub231ps_ymm_ymm_ymmm256"),
    (536894384, "VEX_Vfmsub231sd_xmm_xmm_xmmm64"),
    (536894385, "VEX_Vfmsub231ss_xmm_xmm_xmmm32"),
    (536894400, "VEX_Vfnmadd231pd_xmm_xmm_xmmm128"),
    (536894401, "VEX_Vfnmadd231pd_ymm_ymm_ymmm256"),
    (536894402, "VEX_Vfnmadd231ps_xmm_xmm_xmmm128"),
    (536894403, "VEX_Vfnmadd231ps_ymm_ymm_ymmm256"),
    (536894416, "VEX_Vfnmadd231sd_xmm_xmm_xmmm64"),
    (536894417, "VEX_Vfnmadd231ss_xmm_xmm_xmmm32"),
    (536894432, "VEX_Vfnmsub231pd_xmm_xmm_xmmm128"),
    (536894433, "VEX_Vfnmsub231pd_ymm_ymm_ymmm256"),
    (536894434, "VEX_Vfnmsub231ps_xmm_xmm_xmmm128"),
    (536894435, "VEX_Vfnmsub231ps_ymm_ymm_ymmm256"),
    (536894448, "VEX_Vfnmsub231sd_xmm_xmm_xmmm64"),
    (536894449, "VEX_Vfnmsub231ss_xmm_xmm_xmmm32"),
    (536895344, "VEX_Shlx_r32_rm32_r32"),
    (536895345, "VEX_Shlx_r64_rm64_r64"),
    (536899408, "VEX_Pext_r32_r32_rm32"),
    (536899409, "VEX_Pext_r64_r64_rm64"),
    (536899440, "VEX_Sarx_r32_rm32_r32"),
    (536899441, "VEX_Sarx_r64_rm64_r64"),
    (536903504, "VEX_Pdep_r32_r32_rm32"),
    (536903505, "VEX_Pdep_r64_r64_rm64"),
    (536903520, "VEX_Mulx_r32_r32_rm32"),
    (536903521, "VEX_Mulx_r64_r64_rm64"),
    (536903536, "VEX_Shrx_r32_rm32_r32"),
    (536903537, "VEX_Shrx_r64_rm64_r64"),
    (536907776, "VEX_Vpermq_ymm_ymmm256_imm8"),
    (536907792, "VEX_Vpermpd_ymm_ymmm256_imm8"),
    (536907808, "VEX_Vpblendd_xmm_xmm_xmmm128_imm8"),
    (536907809, "VEX_Vpblendd_ymm_ymm_ymmm256_imm8"),
    (536907840, "VEX_Vpermilps_xmm_xmmm128_imm8"),
    (536907841, "VEX_Vpermilps_ymm_ymmm256_imm8"),
    (536907856, "VEX_Vpermilpd_xmm_xmmm128_imm8"),
    (536907857, "VEX_Vpermilpd_ymm_ymmm256_imm8"),
    (536907872, "VEX_Vperm2f128_ymm_ymm_ymmm256_imm8"),
    (536907904, "VEX_Vroundps_xmm_xmmm128_imm8"),
    (536907905, "VEX_Vroundps_ymm_ymmm256_imm8"),
    (536907920, "VEX_Vroundpd_xmm_xmmm128_imm8"),
    (536907921, "VEX_Vroundpd_ymm_ymmm256_imm8"),
    (536907936, "VEX_Vroundss_xmm_xmm_xmmm32_imm8"),
    (536907952, "VEX_Vroundsd_xmm_xmm_xmmm64_imm8"),
    (536907968, "VEX_Vblendps_xmm_xmm_xmmm128_imm8"),
    (536907969, "VEX_Vblendps_ymm_ymm_ymmm256_imm8"),
    (536907984, "VEX_Vblendpd_xmm_xmm_xmmm128_imm8"),
    (536907985, "VEX_Vblendpd_ymm_ymm_ymmm256_imm8"),
    (536908000, "VEX_Vpblendw_xmm_xmm_xmmm128_imm8"),
    (536908001, "VEX_Vpblendw_ymm_ymm_ymmm256_imm8"),
    (536908016, "VEX_Vpalignr_xmm_xmm_xmmm128_imm8"),
    (536908017, "VEX_Vpalignr_ymm_ymm_ymmm256_imm8"),
    (536908096, "VEX_Vpextrb_r32m8_xmm_imm8"),
    (536908097, "VEX_Vpextrb_r64m8_xmm_imm8"),
    (536908112, "VEX_Vpextrw_r32m16_xmm_imm8"),
    (536908113, "VEX_Vpextrw_r64m16_xmm_imm8"),
    (536908128, "VEX_Vpextrd_rm32_xmm_imm8"),
    (536908129, "VEX_Vpextrq_rm64_xmm_imm8"),
    (536908144, "VEX_Vextractps_r64m32_xmm_imm8"),
    (536908145, "VEX_Vextractps_rm32_xmm_imm8"),
    (536908160, "VEX_Vinsertf128_ymm_ymm_xmmm128_imm8"),
    (536908176, "VEX_Vextractf128_xmmm128_ymm_imm8"),
    (536908240, "VEX_Vcvtps2ph_xmmm128_ymm_imm8"),
    (536908241, "VEX_Vcvtps2ph_xmmm64_xmm_imm8"),
    (536908288, "VEX_Vpinsrb_xmm_xmm_r32m8_imm8"),
    (536908289, "VEX_Vpinsrb_xmm_xmm_r64m8_imm8"),
    (536908304, "VEX_Vinsertps_xmm_xmm_xmmm32_imm8"),
    (536908320, "VEX_Vpinsrd_xmm_xmm_rm32_imm8"),
    (536908321, "VEX_Vpinsrq_xmm_xmm_rm64_imm8"),
    (536908672, "VEX_Vinserti128_ymm_ymm_xmmm128_imm8"),
    (536908688, "VEX_Vextracti128_xmmm128_ymm_imm8"),
    (536908800, "VEX_Vdpps_xmm_xmm_xmmm128_imm8"),
    (536908801, "VEX_Vdpps_ymm_ymm_ymmm256_imm8"),
    (536908816, "VEX_Vdppd_xmm_xmm_xmmm128_imm8"),
    (536908832, "VEX_Vmpsadbw_xmm_xmm_xmmm128_imm8"),
    (536908833, "VEX_Vmpsadbw_ymm_ymm_ymmm256_imm8"),
    (536908896, "VEX_Vperm2i128_ymm_ymm_ymmm256_imm8"),
    (536908960, "VEX_Vblendvps_xmm_xmm_xmmm128_xmm"),
    (536908961, "VEX_Vblendvps_ymm_ymm_ymmm256_ymm"),
    (536908976, "VEX_Vblendvpd_xmm_xmm_xmmm128_xmm"),
    (536908977, "VEX_Vblendvpd_ymm_ymm_ymmm256_ymm"),
    (536908992, "VEX_Vpblendvb_xmm_xmm_xmmm128_xmm"),
    (536908993, "VEX_Vpblendvb_ymm_ymm_ymmm256_ymm"),
    (536909312, "VEX_Vpcmpestrm64_xmm_xmmm128_imm8"),
    (536909313, "VEX_Vpcmpestrm_xmm_xmmm128_imm8"),
    (536909328, "VEX_Vpcmpestri64_xmm_xmmm128_imm8"),
    (536909329, "VEX_Vpcmpestri_xmm_xmmm128_imm8"),
    (536909344, "VEX_Vpcmpistrm_xmm_xmmm128_imm8"),
    (536909360, "VEX_Vpcmpistri_xmm_xmmm128_imm8"),
    (536919808, "VEX_Rorx_r32_rm32_imm8"),
    (536919809, "VEX_Rorx_r64_rm64_imm8"),
];
                                                            source/v64/src/rust/decode_rules.rs                                                                 0000644 0000000 0000000 00000024331 00000000000 014456  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Pure decode rules shared by the snapshot decoder and staged CPU interpreter.
use crate::prefix::*;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Prefix {
    Segment(u8),
    Operand,
    Address,
    Lock,
    Repne,
    Rep,
}
pub fn prefix(byte: u8) -> Option<Prefix> {
    Some(match byte {
        0x26 => Prefix::Segment(0),
        0x2E => Prefix::Segment(1),
        0x36 => Prefix::Segment(2),
        0x3E => Prefix::Segment(3),
        0x64 => Prefix::Segment(4),
        0x65 => Prefix::Segment(5),
        0x66 => Prefix::Operand,
        0x67 => Prefix::Address,
        0xF0 => Prefix::Lock,
        0xF2 => Prefix::Repne,
        0xF3 => Prefix::Rep,
        _ => return None,
    })
}
/// Repeated prefixes accumulate; the last segment wins, and of F2 and F3 the
/// last one counts, as iced-x86 and XED decode (the SDM calls more than one
/// prefix of a group unpredictable).
pub fn apply_prefix(flags: u8, byte: u8) -> Option<u8> {
    Some(match prefix(byte)? {
        Prefix::Segment(s) => flags & !PREFIX_MASK_SEGMENT | (s + 1),
        Prefix::Operand => flags | PREFIX_66,
        Prefix::Address => flags | PREFIX_67,
        Prefix::Repne => flags & !PREFIX_F3 | PREFIX_F2,
        Prefix::Rep => flags & !PREFIX_F2 | PREFIX_F3,
        Prefix::Lock => flags | PREFIX_LOCK,
    })
}

/// LOCK is legal only on the read/modify/write memory-destination forms. Both
/// interpreter dispatch and side-effect-free JIT decoding use this list so a
/// register form or a read-only operand cannot silently become an unlocked op.
pub fn lock_allowed(opcode: u32, modrm: Option<u8>) -> bool {
    let Some(modrm) = modrm
    else {
        return false;
    };
    if modrm >= 0xC0 {
        return false;
    }
    let group = modrm >> 3 & 7;
    match opcode {
        0x00 | 0x01 | 0x08 | 0x09 | 0x10 | 0x11 | 0x18 | 0x19 | 0x20 | 0x21 | 0x28 | 0x29
        | 0x30 | 0x31 | 0x86 | 0x87 | 0x0FAB | 0x0FB0 | 0x0FB1 | 0x0FB3 | 0x0FBB | 0x0FC0
        | 0x0FC1 => true,
        0x80..=0x83 => group != 7,
        0xF6 | 0xF7 => group == 2 || group == 3,
        0xFE | 0xFF => group <= 1,
        0x0FBA => group >= 5,
        0x0FC7 => group == 1,
        _ => false,
    }
}
/// Which row of an opcode the 66/F2/F3 prefixes select
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Variant {
    /// The unprefixed row: 66 is an operand-size prefix, F2/F3 are repeat
    /// prefixes (ignored by most instructions)
    Plain,
    /// The row keyed with this prefix (PREFIX_66, PREFIX_F2 or PREFIX_F3)
    Prefixed(u8),
    /// A mandatory prefix without a row of its own: #UD
    Undefined,
}
/// The variant of an opcode whose prefixed rows in the generated catalogue
/// are `available` (PREFIX_66/F2/F3). F2/F3 (the last one, see apply_prefix)
/// take precedence over 66, which with them is an operand-size prefix: MOVSS is
/// also 66 F3 0F 10, CRC32 r32, r/m16 is 66 F2 0F 38 F1 (iced-x86 and XED
/// decode the same). A `refining` prefix selects instructions (all three in
/// the SSE maps, F2/F3 at MOVBE/CRC32): one without a row of its own is #UD.
/// Otherwise F2/F3 are plain repeat prefixes and 66 sets the operand size.
#[inline]
pub fn mandatory_variant(flags: u8, available: u8, refining: u8) -> Variant {
    let rep = flags & (PREFIX_F2 | PREFIX_F3);
    if rep != 0 {
        if available & rep != 0 {
            return Variant::Prefixed(rep);
        }
        if refining & rep != 0 {
            return Variant::Undefined;
        }
    }
    if refining & PREFIX_66 != 0 && flags & PREFIX_66 != 0 {
        return if available & PREFIX_66 != 0 {
            Variant::Prefixed(PREFIX_66)
        }
        else {
            Variant::Undefined
        };
    }
    Variant::Plain
}
/// The refining prefixes (see mandatory_variant) of a row of the catalogue
pub const REFINING_ALL: u8 = PREFIX_66 | PREFIX_F2 | PREFIX_F3;
pub const REFINING_REP: u8 = PREFIX_F2 | PREFIX_F3;

/// The VEX fields a VEX row of the catalogue (key 0xC4_MM_PP_OO, see
/// Vex::key) accepts and what they encode (gen/vex_table.js)
pub mod vex {
    /// A VEX row
    pub const ROW: u16 = 1 << 0;
    /// VEX.L must be 0 or 1 (neither: ignored)
    pub const L0: u16 = 1 << 1;
    pub const L1: u16 = 1 << 2;
    /// VEX.W must be 0 or 1 (neither: ignored)
    pub const W0: u16 = 1 << 3;
    pub const W1: u16 = 1 << 4;
    /// W0/W1 hold only in 64-bit mode; VEX.W is ignored outside it
    pub const WIG32: u16 = 1 << 5;
    /// VEX.vvvv is an operand; otherwise it must be 1111b
    pub const VVVV: u16 = 1 << 6;
    /// 64-bit mode only
    pub const LONG: u16 = 1 << 7;
    /// imm8[7:4] is a register operand
    pub const IS4: u16 = 1 << 8;
    /// A VSIB memory operand: a SIB byte and 32/64-bit addressing
    pub const VSIB: u16 = 1 << 9;
    /// Destination, index and mask registers must differ
    pub const UNIQUE: u16 = 1 << 10;
    /// A general-purpose register instruction (BMI1, BMI2; SDM exception
    /// type 13): no AVX state requirements
    pub const GPR: u16 = 1 << 11;
}

/// C4 or C5 followed by `next` start a VEX prefix rather than LES or LDS:
/// always in 64-bit mode, elsewhere when `next` would be a register ModRM
/// byte (bits 7:6 11b). Real and virtual-8086 mode have no VEX; there the
/// register form of LES/LDS is #UD, which callers keep.
pub fn is_vex(next: u8, long: bool) -> bool { long || next >= 0xC0 }

/// Prefixes before a VEX prefix that make the instruction #UD (REX too, in
/// 64-bit mode)
pub fn vex_prefixes_ud(flags: u8) -> bool {
    flags & (PREFIX_66 | PREFIX_F2 | PREFIX_F3 | PREFIX_LOCK) != 0
}

/// The fields of a VEX prefix. R, X, B and vvvv are no longer inverted. Outside
/// 64-bit mode R, X and B are 0 and VEX.vvvv has three bits: the two-byte
/// prefix's fourth is 1 there (else LDS), and the three-byte prefix's is
/// ignored, also for the 1111b check (SDM 2.3.5.6; iced-x86 requires it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Vex {
    /// 1: 0F, 2: 0F38, 3: 0F3A (others are #UD)
    pub map: u8,
    /// 0: none, 1: 66, 2: F3, 3: F2
    pub pp: u8,
    pub l: bool,
    pub w: bool,
    pub vvvv: u8,
    pub r: bool,
    pub x: bool,
    pub b: bool,
}
impl Vex {
    /// C5 and its byte
    pub fn two(byte1: u8, long: bool) -> Vex {
        Vex {
            map: 1,
            pp: byte1 & 3,
            l: byte1 & 4 != 0,
            w: false,
            vvvv: !byte1 >> 3 & 15,
            r: long && byte1 & 0x80 == 0,
            x: false,
            b: false,
        }
    }
    /// C4 and its two bytes
    pub fn three(byte1: u8, byte2: u8, long: bool) -> Vex {
        Vex {
            map: byte1 & 0x1F,
            pp: byte2 & 3,
            l: byte2 & 4 != 0,
            w: byte2 & 0x80 != 0,
            vvvv: !byte2 >> 3 & if long { 15 } else { 7 },
            r: long && byte1 & 0x80 == 0,
            x: long && byte1 & 0x40 == 0,
            b: long && byte1 & 0x20 == 0,
        }
    }
    /// The catalogue key of the instruction with this opcode byte
    pub fn key(self, opcode: u8) -> u32 {
        0xC400_0000 | (self.map as u32) << 16 | (self.pp as u32) << 8 | opcode as u32
    }
}

/// The row of `rows` (the rows of one VEX key) that accepts these fields: its
/// ModRM.reg group, register or memory form, VEX.L, VEX.W and mode. No row:
/// #UD.
pub fn vex_row(
    rows: &'static [crate::decode::Encoding],
    v: Vex,
    modrm: Option<u8>,
    long: bool,
) -> Option<&'static crate::decode::Encoding> {
    rows.iter().find(|row| {
        let rule = row.vex;
        let w_counts = long || rule & vex::WIG32 == 0;
        (row.group < 0 || modrm.is_some_and(|m| (m >> 3 & 7) as i8 == row.group))
            && !match modrm {
                Some(m) if m < 0xC0 => row.mem_ud,
                Some(_) => row.reg_ud,
                None => false,
            }
            && !(rule & vex::L0 != 0 && v.l || rule & vex::L1 != 0 && !v.l)
            && !(w_counts && (rule & vex::W0 != 0 && v.w || rule & vex::W1 != 0 && !v.w))
            && (long || rule & vex::LONG == 0)
    })
}
/// Whether the row vex_row selected accepts the remaining fields, known
/// after the ModRM byte: VEX.vvvv is 1111b unless an operand, and a VSIB
/// operand has a SIB byte and 32/64-bit addressing. Otherwise #UD.
pub fn vex_valid(
    row: &crate::decode::Encoding,
    v: Vex,
    modrm: Option<u8>,
    address_size: u8,
) -> bool {
    (row.vex & vex::VVVV != 0 || v.vvvv == 0)
        && (row.vex & vex::VSIB == 0
            || modrm.is_some_and(|m| m < 0xC0 && m & 7 == 4) && address_size != 16)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AddressForm {
    pub base: Option<u8>,
    pub index: Option<u8>,
    pub scale: u8,
    pub displacement_bytes: u8,
    pub segment: u8,
    /// The pinned interpreter checks SIB's segment before its trailing displacement.
    pub segment_before_displacement: bool,
}
pub fn address_form(modrm: u8, size: u8, sib: Option<u8>) -> AddressForm {
    assert!(modrm < 0xC0 && matches!(size, 16 | 32));
    let mode = modrm >> 6;
    let rm = modrm & 7;
    let (base, index, scale, absolute) = if size == 16 {
        let (base, index) = match rm {
            0 => (Some(3), Some(6)),
            1 => (Some(3), Some(7)),
            2 => (Some(5), Some(6)),
            3 => (Some(5), Some(7)),
            4 => (Some(6), None),
            5 => (Some(7), None),
            6 if mode == 0 => (None, None),
            6 => (Some(5), None),
            _ => (Some(3), None),
        };
        (base, index, 0, mode == 0 && rm == 6)
    }
    else if rm == 4 {
        let sib = sib.expect("SIB required");
        let b = sib & 7;
        let i = sib >> 3 & 7;
        (
            if b == 5 && mode == 0 { None } else { Some(b) },
            if i == 4 { None } else { Some(i) },
            sib >> 6,
            b == 5 && mode == 0,
        )
    }
    else {
        (
            if rm == 5 && mode == 0 { None } else { Some(rm) },
            None,
            0,
            rm == 5 && mode == 0,
        )
    };
    AddressForm {
        base,
        index,
        scale,
        displacement_bytes: if mode == 1 {
            1
        }
        else if mode == 2 || absolute {
            size / 8
        }
        else {
            0
        },
        segment: if base == Some(5) || size == 32 && base == Some(4) { 2 } else { 3 },
        segment_before_displacement: size == 32 && rm == 4 && mode != 0,
    }
}
                                                                                                                                                                                                                                                                                                       source/v64/src/rust/extended.rs                                                                     0000644 0000000 0000000 00000042247 00000000000 013627  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Guest RAM beyond the wasm32 backing store, "extended RAM": the engine
//! both cores share (docs/x86-64.md; docs/arm64-virt-android16-plan.md
//! P8.5). Guest physical [base, base + pages * 4 KiB) lives in a host store
//! (JavaScript ArrayBuffers, shared with vCPU workers: `js::extended_load`
//! and `js::extended_store` copy one page, src/extended_memory.js) and is
//! cached in a pool of 4 KiB frames in the wasm heap.
//!
//! What this module does: the frames (a FIFO with a second chance for
//! referenced frames), loading, writing back and evicting them; pinning a
//! frame for a host copy; flushing the store (snapshots) and discarding the
//! frames (restore, power-on); the pages that compiled code was made from
//! (`code`, retired at their next write); one re-entrant lock with cores in
//! workers. What a core adds through crate::isa's hooks: whatever else may
//! hold a frame (an access cache of compiled code may map a frame, which is
//! then CACHED and not reused before `release_cached`; x86:
//! crate::x64::extended::cache_frame), the code of a written page, and the
//! state to drop with the frames (x86: the aperture of compatibility mode).

use crate::parallel::{machine, SpinLock};
use std::ptr;

#[cfg(target_arch = "wasm32")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        /// Copy extended page `page` (index from the start of the range) from
        /// the host store to `pointer` in wasm memory
        pub fn extended_load(page: u32, pointer: u32);
        /// Copy the page at `pointer` to the host store
        pub fn extended_store(page: u32, pointer: u32);
    }
}
// (cargo test: no test configures extended RAM, and a native frame's
// address does not fit the imports' u32)
#[cfg(not(target_arch = "wasm32"))]
mod js {
    pub unsafe fn extended_load(_page: u32, _pointer: u32) { unreachable!() }
    pub unsafe fn extended_store(_page: u32, _pointer: u32) { unreachable!() }
}

pub const PAGE: u64 = 4096;
pub const NONE: u32 = u32::MAX;
pub const REFERENCED: u8 = 1;
pub const DIRTY: u8 = 2;
/// in an access cache of compiled code: not reusable before `release_cached`
pub const CACHED: u8 = 4;
/// in the replacement queue
pub const QUEUED: u8 = 8;

pub struct Extended {
    pub base: u64,
    pub pages: u32,
    pub pool: *mut u8,
    pub frames: u32,
    /// frame of each page, or NONE
    pub page_frame: Vec<u32>,
    /// page of each frame, or NONE
    pub frame_page: Vec<u32>,
    pub frame_state: Vec<u8>,
    pub frame_pins: Vec<u16>,
    /// Replacement order: a FIFO ring of resident frames with a second chance
    /// for referenced ones; cached frames leave it until released. Fixed
    /// capacity (one slot per frame): workers never allocate machine memory.
    queue: Vec<u32>,
    head: u32,
    pub queued: u32,
    /// frames below this were used since the pool was (re)set
    unused_from: u32,
    /// frames marked CACHED
    pub cached: u32,
    /// one more frame, for an access when no frame is reusable
    bounce: *mut u8,
    /// pages with compiled code, one bit each (see `note_write`)
    pub code: Vec<u64>,
    pub stats: [u64; 9],
}
pub const STAT_HITS: usize = 0;
pub const STAT_LOADS: usize = 1;
pub const STAT_STORES: usize = 2;
pub const STAT_EVICTIONS: usize = 3;
pub const STAT_APERTURE: usize = 4;
pub const STAT_LOCKED: usize = 5;
pub const STAT_RELEASES: usize = 6;
pub const STAT_BOUNCES: usize = 7;
pub const STAT_CODE_WRITES: usize = 8;

static mut EXTENDED: Extended = Extended {
    base: 0,
    pages: 0,
    pool: ptr::null_mut(),
    frames: 0,
    page_frame: Vec::new(),
    frame_page: Vec::new(),
    frame_state: Vec::new(),
    frame_pins: Vec::new(),
    queue: Vec::new(),
    head: 0,
    queued: 0,
    unused_from: 0,
    cached: 0,
    bounce: ptr::null_mut(),
    code: Vec::new(),
    stats: [0; 9],
};
/// Too many frames are CACHED, or none was reusable: release them at the
/// next safe point
pub static mut RELEASE_PENDING: bool = false;
// the machine instance's module state and its lock (crate::parallel)
pub fn ext() -> &'static mut Extended { unsafe { &mut *machine(&raw mut EXTENDED) } }

static mut LOCK: SpinLock = SpinLock::new();
/// Owner depth of LOCK (the lock word holds the owner's core + 1)
static mut DEPTH: [u32; crate::parallel::MAX_CORES] = [0; crate::parallel::MAX_CORES];

/// Take the module's lock (re-entrant); a no-op without cores in workers
pub unsafe fn lock() {
    if !crate::parallel::active() {
        return;
    }
    let core = crate::isa::current_core();
    let depth = machine(&raw mut DEPTH).cast::<u32>().add(core);
    if *depth == 0 {
        (*machine(&raw mut LOCK)).lock();
    }
    *depth += 1;
}
pub unsafe fn unlock() {
    if !crate::parallel::active() {
        return;
    }
    let core = crate::isa::current_core();
    let depth = machine(&raw mut DEPTH).cast::<u32>().add(core);
    dbg_assert!(*depth > 0);
    *depth -= 1;
    if *depth == 0 {
        (*machine(&raw mut LOCK)).unlock();
    }
}
/// A failed core's worker holds the lock no more (crate::parallel::parallel_fail)
pub unsafe fn release_held_by(core: usize) {
    *machine(&raw mut DEPTH).cast::<u32>().add(core) = 0;
    (*machine(&raw mut LOCK)).release_held_by(core);
}
pub struct Guard;
impl Guard {
    pub unsafe fn new() -> Guard {
        lock();
        Guard
    }
}
impl Drop for Guard {
    fn drop(&mut self) { unsafe { unlock() } }
}

/// Whether guest physical `address` is extended RAM
#[inline]
pub unsafe fn contains(address: u64) -> bool {
    let e = ext();
    address.wrapping_sub(e.base) < e.pages as u64 * PAGE
}
pub unsafe fn range() -> Option<(u64, u64)> {
    let e = ext();
    (e.pages != 0).then(|| (e.base, e.base + e.pages as u64 * PAGE))
}

/// The resident frame of `page` (loading it, and writing back and reusing
/// another frame when the pool is full), or None if no frame is reusable.
/// Under the lock. Every write to extended RAM comes here first.
pub unsafe fn resident(e: &mut Extended, page: u32, write: bool) -> Option<u32> {
    if write {
        note_write(e, page);
    }
    let mut frame = e.page_frame[page as usize];
    if frame == NONE {
        frame = victim(e)?;
        js::extended_load(page, e.pool.add(frame as usize * PAGE as usize) as u32);
        e.page_frame[page as usize] = frame;
        e.frame_page[frame as usize] = page;
        e.frame_state[frame as usize] = 0;
        enqueue(e, frame);
        e.stats[STAT_LOADS] += 1;
    }
    else {
        e.stats[STAT_HITS] += 1;
    }
    e.frame_state[frame as usize] |= REFERENCED | if write { DIRTY } else { 0 };
    Some(frame)
}

/// Run `access` on the bytes of `page`: in its frame, or, when no frame is
/// reusable, in the bounce frame (written back at once after a write)
pub unsafe fn with_page<T>(
    e: &mut Extended,
    page: u32,
    write: bool,
    access: impl FnOnce(*mut u8) -> T,
) -> T {
    if let Some(frame) = resident(e, page, write) {
        return access(e.pool.add(frame as usize * PAGE as usize));
    }
    RELEASE_PENDING = true;
    e.stats[STAT_BOUNCES] += 1;
    js::extended_load(page, e.bounce as u32);
    let result = access(e.bounce);
    if write {
        js::extended_store(page, e.bounce as u32);
    }
    result
}

pub fn enqueue(e: &mut Extended, frame: u32) {
    dbg_assert!(e.frame_state[frame as usize] & QUEUED == 0 && e.queued < e.frames);
    let at = (e.head + e.queued) % e.frames;
    e.queue[at as usize] = frame;
    e.queued += 1;
    e.frame_state[frame as usize] |= QUEUED;
}
fn dequeue(e: &mut Extended) -> Option<u32> {
    if e.queued == 0 {
        return None;
    }
    let frame = e.queue[e.head as usize];
    e.head = (e.head + 1) % e.frames;
    e.queued -= 1;
    e.frame_state[frame as usize] &= !QUEUED;
    Some(frame)
}

/// A frame to reuse: an unused one, else the oldest resident frame that is
/// not referenced (referenced ones get a second chance), not pinned and not
/// cached (a cached frame leaves the queue until it is released)
unsafe fn victim(e: &mut Extended) -> Option<u32> {
    if e.unused_from < e.frames {
        e.unused_from += 1;
        return Some(e.unused_from - 1);
    }
    for _ in 0..2 * e.queued + 1 {
        let frame = dequeue(e)?;
        let state = e.frame_state[frame as usize];
        if state & CACHED != 0 {
            continue;
        }
        if e.frame_pins[frame as usize] != 0 || state & REFERENCED != 0 {
            e.frame_state[frame as usize] &= !REFERENCED;
            enqueue(e, frame);
            continue;
        }
        evict(e, frame);
        return Some(frame);
    }
    None
}

/// Mark a frame as held by an access cache of compiled code (the core's
/// cache_frame): not reused before `release_cached`
pub fn mark_cached(e: &mut Extended, frame: u32) {
    let state = &mut e.frame_state[frame as usize];
    if *state & CACHED == 0 {
        *state |= CACHED;
        e.cached += 1;
        // (released while half the pool is still reusable)
        if e.cached > e.frames / 2 {
            unsafe { RELEASE_PENDING = true };
        }
    }
}

/// The bytes of extended page `page`, to compile from
pub unsafe fn copy_page(page: u32) -> Vec<u8> {
    let _guard = Guard::new();
    with_page(ext(), page, false, |frame| {
        std::slice::from_raw_parts(frame, PAGE as usize).to_vec()
    })
}

pub fn has_code(e: &Extended, page: u32) -> bool {
    e.code[page as usize / 64] >> (page % 64) & 1 != 0
}

/// Code was compiled from `page`: its next write retires it. Stores through
/// the access caches would not come here: the core retires those.
pub unsafe fn watch_code(page: u32) {
    let e = ext();
    e.code[page as usize / 64] |= 1 << (page % 64);
    let frame = e.page_frame[page as usize];
    // (only a CACHED frame can be in an access cache)
    if frame != NONE && e.frame_state[frame as usize] & CACHED != 0 {
        crate::isa::extended_retire_cached_writes(e.pool.add(frame as usize * PAGE as usize) as u32);
    }
}
/// The code of `page` was retired
pub unsafe fn unwatch_code(page: u32) {
    let e = ext();
    e.code[page as usize / 64] &= !(1 << (page % 64));
}
/// `page` is about to be written: retire the code compiled from it
#[inline]
unsafe fn note_write(e: &mut Extended, page: u32) {
    if has_code(e, page) {
        e.code[page as usize / 64] &= !(1 << (page % 64));
        e.stats[STAT_CODE_WRITES] += 1;
        crate::isa::extended_code_written(page);
    }
}

/// A safe point of the dispatch loop: no compiled code is active
#[inline(always)]
pub unsafe fn safe_point() {
    if RELEASE_PENDING {
        release_cached();
    }
}

/// Retire every access cache entry (the core's), so that no frame is CACHED any more
pub unsafe fn release_cached() {
    RELEASE_PENDING = false;
    let e = ext();
    if e.cached == 0 {
        return;
    }
    crate::isa::extended_release_caches();
    e.stats[STAT_RELEASES] += 1;
    for frame in 0..e.frames {
        let state = e.frame_state[frame as usize];
        if state & CACHED != 0 {
            e.frame_state[frame as usize] &= !CACHED;
            if state & QUEUED == 0 && e.frame_page[frame as usize] != NONE {
                enqueue(e, frame);
            }
        }
    }
    e.cached = 0;
}

unsafe fn evict(e: &mut Extended, frame: u32) {
    let page = e.frame_page[frame as usize];
    if e.frame_state[frame as usize] & DIRTY != 0 {
        js::extended_store(page, e.pool.add(frame as usize * PAGE as usize) as u32);
        e.stats[STAT_STORES] += 1;
    }
    e.page_frame[page as usize] = NONE;
    e.frame_page[frame as usize] = NONE;
    e.frame_state[frame as usize] = 0;
    e.stats[STAT_EVICTIONS] += 1;
}

/// `width` (1, 2, 4 or 8) bytes at `address`, within one page
pub unsafe fn read(address: u64, width: usize) -> u64 {
    let _guard = Guard::new();
    let e = ext();
    let offset = address - e.base;
    dbg_assert!(offset % PAGE + width as u64 <= PAGE);
    with_page(e, (offset / PAGE) as u32, false, |frame| {
        let at = frame.add((offset % PAGE) as usize);
        match width {
            1 => *at as u64,
            2 => ptr::read_unaligned(at as *const u16) as u64,
            4 => ptr::read_unaligned(at as *const u32) as u64,
            _ => ptr::read_unaligned(at as *const u64),
        }
    })
}

pub unsafe fn write(address: u64, width: usize, value: u64) {
    let _guard = Guard::new();
    let e = ext();
    let offset = address - e.base;
    dbg_assert!(offset % PAGE + width as u64 <= PAGE);
    with_page(e, (offset / PAGE) as u32, true, |frame| {
        let at = frame.add((offset % PAGE) as usize);
        match width {
            1 => *at = value as u8,
            2 => ptr::write_unaligned(at as *mut u16, value as u16),
            4 => ptr::write_unaligned(at as *mut u32, value as u32),
            _ => ptr::write_unaligned(at as *mut u64, value),
        }
    })
}

/// Set bits of a qword (paging entry accessed/dirty bits): one step for the
/// other cores, which access extended RAM only under the same lock
pub unsafe fn or64(address: u64, bits: u64) {
    let _guard = Guard::new();
    let value = read(address, 8);
    write(address, 8, value | bits);
}

/// Configure extended RAM (machine instance, before the cores run): `pages`
/// pages at guest physical `base`, cached in `frames` frames (at least 64)
pub unsafe fn configure(base: u64, pages: u32, frames: u32) -> bool {
    if base % PAGE != 0 || pages != 0 && frames < 64 {
        return false;
    }
    let e = &mut *(&raw mut EXTENDED);
    if e.pages != 0 || pages == 0 {
        return pages == 0 && e.pages == 0;
    }
    // (and the bounce frame)
    let layout =
        std::alloc::Layout::from_size_align((frames as usize + 1) * PAGE as usize, PAGE as usize)
            .unwrap();
    let pool = std::alloc::alloc(layout);
    if pool.is_null() {
        return false;
    }
    e.base = base;
    e.pages = pages;
    e.pool = pool;
    e.frames = frames;
    e.page_frame = vec![NONE; pages as usize];
    e.frame_page = vec![NONE; frames as usize];
    e.frame_state = vec![0; frames as usize];
    e.frame_pins = vec![0; frames as usize];
    e.queue = vec![0; frames as usize];
    e.head = 0;
    e.queued = 0;
    e.unused_from = 0;
    e.cached = 0;
    e.bounce = pool.add(frames as usize * PAGE as usize);
    e.code = vec![0; (pages as usize).div_ceil(64)];
    true
}

/// Write back every dirty frame (the store is then complete: snapshots)
pub unsafe fn flush() {
    let _guard = Guard::new();
    // (so that no store bypasses the dirty bits cleared here)
    release_cached();
    let e = ext();
    for frame in 0..e.frames {
        let page = e.frame_page[frame as usize];
        if page != NONE && e.frame_state[frame as usize] & DIRTY != 0 {
            js::extended_store(page, e.pool.add(frame as usize * PAGE as usize) as u32);
            e.frame_state[frame as usize] &= !DIRTY;
            e.stats[STAT_STORES] += 1;
        }
    }
}

/// Forget every frame without writing it back (the store was replaced:
/// snapshot restore, power-on). Every core is stopped.
pub unsafe fn discard() {
    release_cached();
    let e = ext();
    for frame in 0..e.frames as usize {
        dbg_assert!(e.frame_pins[frame] == 0);
        e.frame_page[frame] = NONE;
        e.frame_state[frame] = 0;
    }
    for page in e.page_frame.iter_mut() {
        *page = NONE;
    }
    // (the compiled code goes too: the core clears its caches after this)
    e.code.fill(0);
    e.head = 0;
    e.queued = 0;
    e.unused_from = 0;
    crate::isa::extended_discarded();
}

/// The frame of extended page `page` for a host copy (DMA, debugging),
/// resident until `unpin`: its address in wasm memory (0: no such page)
pub unsafe fn pin(page: u32, write: bool) -> u32 {
    let _guard = Guard::new();
    let e = ext();
    if page >= e.pages {
        return 0;
    }
    // (the host calls this outside compiled code: a safe point)
    let frame = match resident(e, page, write) {
        Some(frame) => frame,
        None => {
            release_cached();
            resident(e, page, write).expect("extended RAM: every frame is pinned")
        },
    };
    e.frame_pins[frame as usize] += 1;
    e.pool.add(frame as usize * PAGE as usize) as u32
}
pub unsafe fn unpin(page: u32) {
    let _guard = Guard::new();
    let e = ext();
    let frame = e.page_frame[page as usize];
    dbg_assert!(frame != NONE && e.frame_pins[frame as usize] > 0);
    e.frame_pins[frame as usize] -= 1;
}

/// 0 hits, 1 loads, 2 write-backs, 3 evictions, 4 aperture mappings (x86),
/// 5 locked instructions (x86); 6 pages, 7 frames; 8 releases of cached frames,
/// 9 accesses through the bounce frame; now: 10 queued frames, 11 frames
/// counted as cached, 12 frames marked CACHED, 13 pinned frames; 14 pages
/// with compiled code now, 15 compiled code retired by writes
pub unsafe fn stat(field: u32) -> f64 {
    let e = ext();
    let frames = || 0..e.frames as usize;
    match field {
        0..=5 => e.stats[field as usize] as f64,
        6 => e.pages as f64,
        7 => e.frames as f64,
        8 => e.stats[STAT_RELEASES] as f64,
        9 => e.stats[STAT_BOUNCES] as f64,
        10 => e.queued as f64,
        11 => e.cached as f64,
        12 => frames().filter(|&f| e.frame_state[f] & CACHED != 0).count() as f64,
        13 => frames().filter(|&f| e.frame_pins[f] != 0).count() as f64,
        14 => e.code.iter().map(|word| word.count_ones()).sum::<u32>() as f64,
        15 => e.stats[STAT_CODE_WRITES] as f64,
        _ => -1.0,
    }
}
                                                                                                                                                                                                                                                                                                                                                         source/v64/src/rust/gen/mod.rs                                                                      0000644 0000000 0000000 00000000242 00000000000 013344  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #[rustfmt::skip]
pub mod interpreter;
#[rustfmt::skip]
pub mod interpreter0f;
#[rustfmt::skip]
pub mod interpreter0f38;
#[rustfmt::skip]
pub mod interpreter0f3a;
                                                                                                                                                                                                                                                                                                                                                              source/v64/src/rust/jit.rs                                                                          0000644 0000000 0000000 00000024775 00000000000 012623  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The x86 core's composition root of compiled code
//! (docs/jit-unification-plan.md P5.1): whether it runs (jit_set_enabled),
//! the wiring of the ISA-neutral runtime crate::jitrt to the CPU (its host
//! environment, the x64 page tier as the client X86Page that hears of writes
//! and resets), and the hot-path compositions that stay here
//! (page_watched). Writes to a physical page compiled code was made from
//! (self-modifying code, DMA, host writes) retire that code. (The IR region
//! tiers shared it until M11 deleted them.)
use std::collections::HashSet;

use crate::cpu::cpu;
use crate::jitrt::host::Env;
use crate::jitrt::table::{Owner, Signature};
use crate::jitrt::watch::Trigger;
use crate::jitrt::{self, ClientId};
use crate::page::Page;
use crate::profiler;
use crate::profiler::stat;

mod unsafe_jit {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn jit_clear_func(wasm_table_index: u16);
    }
}

// needs to be synced to const.js
pub const WASM_TABLE_SIZE: u32 = 12000;

/// Whether compiled code runs (CPU.configure_jit_backend: not disable_jit;
/// the region tiers' scheduler held it until M11)
static mut ENABLED: bool = false;
#[no_mangle]
pub unsafe fn jit_set_enabled(enabled: u32) -> bool {
    if enabled > 1 {
        return false;
    }
    ENABLED = enabled == 1;
    true
}
#[inline(always)]
pub fn enabled() -> bool { unsafe { ENABLED } }
/// Whether the JIT compiles (get_jit_info's ir.enabled)
#[no_mangle]
pub fn jit_is_enabled() -> bool { enabled() }
/// 32-bit and 16-bit code in the x64 page tier (the JIT switch ir_tier0,
/// set by CPU.configure_jit_backend unless its setting ir_tier0 is false;
/// the region tiers' scheduler set it until M11)
#[no_mangle]
pub unsafe fn jit_set_page32(enabled: u32) -> bool {
    if enabled > 1 {
        return false;
    }
    crate::x64::pages::set_page32_tier0(enabled == 1);
    if enabled == 1 {
        reserve_compiler_heap();
    }
    true
}
/// Grow the Wasm heap once for the compiler's working set: every later
/// memory.grow of the (multi-GiB) guest memory makes the host re-account it as
/// external memory and collect, so many small grows cost far more than one.
/// (The region tiers' scheduler did this for the page tier's 32-bit code
/// until M11; CPU.configure_jit_backend sets ir_tier0 before the guest's RAM
/// is allocated, which takes the freed chunks' place: cpu::memory.)
fn reserve_compiler_heap() {
    static mut RESERVED: bool = false;
    unsafe {
        if RESERVED {
            return;
        }
        RESERVED = true;
    }
    // Freed chunks stay in the allocator's free lists.
    let chunks: Vec<Vec<u8>> = (0..16).map(|_| Vec::with_capacity(2 << 20)).collect();
    drop(chunks);
}

/// Whether this build has Wasm SIMD: the portable one (build/v86-fallback.wasm)
/// has none, and the page tier declines the forms whose templates need it
/// (ir_wasm_simd_supported until M11 of docs/jit-unification-plan.md).
#[no_mangle]
pub extern "C" fn jit_wasm_simd_supported() -> u32 { u32::from(cfg!(target_feature = "simd128")) }

#[no_mangle]
pub fn rust_init() {
    #[cfg(target_arch = "wasm32")]
    unsafe {
        *crate::cpu::global_pointers::ir_tlb_base = std::ptr::addr_of!(cpu::tlb_data) as u32;
    }
    jitrt::init(Env {
        table_size: WASM_TABLE_SIZE,
        table_offset: cpu::WASM_TABLE_OFFSET,
        state_base: crate::cpu::global_pointers::state_base(),
        mem8: || unsafe { crate::cpu::memory::mem8 },
        now: || unsafe { cpu::js::microtick() },
        core: crate::cpu::apic::current_core,
        clear_slot: |slot| unsafe { unsafe_jit::jit_clear_func(slot as u16) },
        page_has_code: cpu::tlb_set_has_code,
        pages_gain_code: |pages| {
            cpu::tlb_set_has_code_multiple(pages, true);
            // x64 page functions store through cached write translations of
            // pages without code; these pages may be among them.
            for page in pages {
                unsafe { crate::x64::jac::retire_writes_to(page.to_address()) };
            }
        },
        claim: |page, on| unsafe {
            if on {
                crate::parallel::code::claim(page)
            }
            else {
                crate::parallel::code::release(page)
            }
        },
        release_all: || unsafe { crate::parallel::code::release_all() },
    });
    {
        let mut rt = jitrt::state();
        // (with cores in workers, the other cores hear of every write: crate::parallel::code)
        rt.watch.on_dirty(Trigger::Always, |page, _| {
            unsafe { crate::parallel::code::written(page) };
            Vec::new()
        });
        rt.watch
            .on_dirty(Trigger::WatchedOnly, |page, bytes| match bytes {
                Some((lo, hi)) => crate::x64::pages::dirty_bytes(page, lo, hi),
                None => {
                    crate::x64::pages::dirty_page(page);
                    Vec::new()
                },
            });
        rt.watch.on_reset(crate::x64::pages::reset);
    }
    jitrt::stat::register(ClientId::X86Page, crate::x64::pages::x64_page_stat);
    jitrt::capacity::set_quota(ClientId::X86Page, crate::x64::pages::MAX_FUNCTIONS as u32);
    jitrt::publish::register(
        ClientId::X86Page,
        jitrt::publish::Client {
            install: crate::x64::pages::x64_page_install,
            ready: crate::x64::pages::x64_page_ready,
            cancel: crate::x64::pages::x64_page_cancel,
        },
    );

    use std::panic;

    panic::set_hook(Box::new(|panic_info| {
        console_log!("{}", panic_info.to_string());
    }));
}

/// A write to the page: retire the code compiled from it, here and
/// (crate::parallel::code) in other cores' workers.
fn dirty_page(page: Page) {
    if !jitrt::state().watch.write(page, None) {
        profiler::stat_increment(stat::DIRTY_PAGE_DID_NOT_HAVE_CODE);
    }
}

/// Another core wrote the page (crate::parallel::code::poll): retire this
/// instance's code from it
pub fn jit_retire_page(page: Page) {
    if !jitrt::state().watch.retire(page, None) {
        profiler::stat_increment(stat::DIRTY_PAGE_DID_NOT_HAVE_CODE);
    }
}

#[no_mangle]
pub fn jit_dirty_cache(start_addr: u32, end_addr: u32) {
    dbg_assert!(start_addr < end_addr);

    let start_page = Page::page_of(start_addr);
    let end_page = Page::page_of(end_addr - 1);

    for page in start_page.to_u32()..end_page.to_u32() + 1 {
        dirty_page(Page::page_of(page << 12));
    }
}

#[no_mangle]
pub fn jit_dirty_page(page: Page) { dirty_page(page) }

/// A write of `len` bytes at physical `addr`, within one page: as
/// jit_dirty_page, where code the write misses may stay (the x64 page
/// tier's dirty_bytes)
pub fn jit_dirty_bytes(addr: u32, len: u32) {
    let page = Page::page_of(addr);
    dbg_assert!(Page::page_of(addr + len - 1) == page);
    let lo = addr & 0xFFF;
    if !jitrt::state().watch.write(page, Some((lo, lo + len))) {
        profiler::stat_increment(stat::DIRTY_PAGE_DID_NOT_HAVE_CODE);
    }
}

/// jit_dirty_bytes for the bytes start..end, which span at most two pages
/// (the RAM writers of crate::cpu::memory, through which compatibility-mode
/// code's writes go: M9)
pub fn jit_dirty_bytes_small(start: u32, end: u32) {
    dbg_assert!(start < end);
    let split = (start & !0xFFF).wrapping_add(0x1000);
    if end <= split || split == 0 {
        jit_dirty_bytes(start, end - start);
    }
    else {
        jit_dirty_bytes(start, split - start);
        jit_dirty_bytes(split, end - split);
    }
}

/// dirty pages in the range of start_addr and end_addr, which must span at most two pages
pub fn jit_dirty_cache_small(start_addr: u32, end_addr: u32) {
    dbg_assert!(start_addr < end_addr);

    let start_page = Page::page_of(start_addr);
    let end_page = Page::page_of(end_addr - 1);

    dirty_page(start_page);

    // Note: This can't happen when paging is enabled, as writes across
    //       boundaries are split up on two pages
    if start_page != end_page {
        dbg_assert!(start_page.to_u32() + 1 == end_page.to_u32());
        dirty_page(end_page);
    }
}

#[no_mangle]
pub fn jit_clear_cache_js() { jitrt::state().watch.reset() }

/// Whether compiled code (a published function's source) lies on the page.
pub fn jit_page_has_code(page: Page) -> bool { jitrt::state().watch.watched(page) }

/// Whether stores to the page must take the slow path: this instance or,
/// with cores in workers, another core compiled code from it. Used for new
/// translations (TLB fills, write translation caches).
pub fn page_needs_notification(page: Page) -> bool {
    jit_page_has_code(page) || unsafe { crate::parallel::code::others_own(page.to_u32()) }
}

/// Whether x64 page-tier code was compiled from this backing page, by this
/// instance or (with cores in workers) another: writes must notify.
#[inline(always)]
pub fn page_watched(page: u32) -> bool {
    jitrt::watch::bit(page) || unsafe { crate::parallel::code::others_own(page) }
}

/// Whether every page this code depends on is published to the other cores
/// (crate::parallel::code), so that it may be installed, waiting up to `ms`
/// for their acknowledgements
pub fn wait_pages_published(pages: impl Iterator<Item = Page> + Clone, ms: f64) -> bool {
    unsafe { crate::parallel::code::wait_published(pages.map(|page| page.to_u32()), ms) }
}

/// The fewest free table slots since the last jit_wasm_table_free_low_reset
/// (docs/jit-unification-plan.md P0.10)
#[no_mangle]
pub fn jit_wasm_table_free_low() -> u32 { jitrt::state().table.free_low() }
#[no_mangle]
pub fn jit_wasm_table_free_low_reset() { jitrt::state().table.reset_free_low() }

/// A slot for an x64 page function (the client X86Page, code `id`) compiled
/// from `pages`, which it watches from now on
pub fn reserve_page_slot(id: u64, pages: HashSet<Page>) -> Option<u32> {
    let mut rt = jitrt::state();
    let slot = rt.table.reserve(Owner {
        client: ClientId::X86Page,
        signature: Signature::Fn1Ret,
        id,
    })?;
    rt.watch.attach(slot, pages);
    Some(slot)
}

/// Called only at a cold/quiescent point. The owner protects a reused slot
/// from old callbacks by `id`.
pub fn release_page_slot(slot: u32, id: u64) -> bool {
    let mut rt = jitrt::state();
    if !rt.table.release(slot, ClientId::X86Page, id) {
        return false;
    }
    rt.watch.detach(slot);
    // It is not strictly necessary to clear the function, but it will fail
    // more predictably if we accidentally use the function and may garbage
    // collect unused modules earlier
    (jitrt::host::env().clear_slot)(slot);
    true
}

#[no_mangle]
pub fn jit_get_wasm_table_index_free_list_count() -> u32 { jitrt::state().table.free_count() }
   source/v64/src/rust/jit_switches.rs                                                                 0000644 0000000 0000000 00000036430 00000000000 014523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! One registry of the JIT switches (docs/jit-unification-plan.md, cross-phase
//! rule 1). Each A/B switch of the x64 page tier has a name
//! here, so that the V86 option `jit_switches`, the tests (JIT_SWITCHES, read
//! by tests/lib/jit_switches.mjs) and build-time defaults (JIT_DEFAULTS) set
//! them one way, vCPU workers copy them and measurements can record them
//! (src/jit_switches.js). The older setters (x64_page_set_outline, ...) stay
//! as aliases: jit_switch reads a value however it was set. The engine's tail
//! calls (jit_set_tail_calls) are a host capability, not a switch. (The IR
//! region tiers' switches went with them in docs/jit-unification-plan.md M11.)
//!
//! Values apply in the order of SWITCHES.

use crate::cpu::execution;
use crate::step_profile;
use crate::x64::{pagegen, pages};

pub struct Switch {
    /// the name in jit_switches, JIT_SWITCHES and JIT_DEFAULTS
    pub name: &'static str,
    /// the value of a fresh instance, before src/cpu.js applies its settings
    pub default: u32,
    /// false: the value is out of range, or the module refuses the change now
    /// (most IR settings only change while nothing is compiled)
    set: unsafe fn(u32) -> bool,
    get: unsafe fn(&str) -> Option<u32>,
}

fn flag(value: u32) -> Option<bool> { (value <= 1).then_some(value == 1) }

pub const SWITCHES: &[Switch] = &[
    // the x64 page tier (crate::x64), and compatibility mode's helpers
    Switch {
        name: "x64_page",
        default: 1,
        set: |v| flag(v).map(pages::x64_page_set_enabled).is_some(),
        get: pages::switch_value,
    },
    Switch {
        name: "x64_chaining",
        default: 0,
        // (chained page functions end in a Wasm tail call)
        set: |v| match flag(v) {
            Some(on) if !on || crate::x64::helpers::tail_calls() => {
                unsafe { pages::x64_page_set_chaining(on) };
                true
            },
            _ => false,
        },
        get: pages::switch_value,
    },
    Switch {
        name: "x64_recompile_misses",
        default: 64,
        set: |v| {
            v >= 1 && {
                unsafe { pages::x64_page_set_recompile_misses(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    // (docs/jit-unification-plan.md P4.5b, P4.5c)
    Switch {
        name: "x64_heat_batch",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_heat_batch(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    Switch {
        name: "x64_miss_run",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_miss_run(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    // (docs/jit-unification-plan.md P4.15: the access cache's entries per
    // table; the page tier recompiles)
    Switch {
        name: "x64_jac_entries",
        default: 2048,
        set: |v| unsafe {
            crate::x64::jac::set_entries(v as usize) && {
                pages::reset();
                true
            }
        },
        get: |_| Some(crate::x64::jac::entries() as u32),
    },
    // (docs/jit-unification-plan.md P4.14)
    Switch {
        name: "x64_hot_inline",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_hot_inline(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    Switch {
        // (the execution count of a cold page function that recompiles its
        // page with inline lookups: long after V8 optimized the cold one,
        // so that only pages that stay hot pay for a new function that
        // starts over in Liftoff; docs/jit-unification-plan.md appendix C, M5)
        name: "x64_hot_count",
        default: 1 << 22,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_hot_count(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    // (P7.2b: x64_hot_count of 32-bit compatibility-mode functions)
    Switch {
        name: "x64_compat_hot_count",
        default: 1 << 16,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_compat_hot_count(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    // (docs/jit-unification-plan.md P7.2: 32-bit compatibility-mode code in
    // the page tier instead of Tier-0; on since M9, which passed its D gate)
    Switch {
        name: "x64_page_compat32",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_compat32(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    // (P7.3: 32-bit legacy protected-mode code in the page tier instead of
    // Tier-0; on since M8, which passed its D gate: P7.4)
    Switch {
        name: "x64_page_legacy32",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_legacy32(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    // (P7.7: 16-bit protected-mode code in the page tier, on since M10;
    // off, it runs in the interpreter)
    Switch {
        name: "x64_page_prot16",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_prot16(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    // (real-mode and virtual-8086 code, P7.8)
    Switch {
        name: "x64_page_v86",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_v86(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    // (P7.2b, P7.3: interpreted instructions on a page of legacy-mode code
    // before its first compile, and its unserved entries before a recompile)
    Switch {
        name: "x64_legacy_heat",
        default: 50_000,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_legacy_heat(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    // (P7.3b: multi-page functions of legacy-mode code)
    Switch {
        name: "x64_page_clusters",
        default: 1,
        set: |v| {
            flag(v)
                .map(|on| unsafe { pages::x64_page_set_clusters(on) })
                .is_some()
        },
        get: pages::switch_value,
    },
    Switch {
        name: "x64_span_crossings",
        default: 4096,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_span_crossings(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    Switch {
        name: "x64_span_entries",
        default: 8,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_span_entries(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    Switch {
        name: "x64_legacy_recompile_misses",
        default: 4096,
        set: |v| {
            v >= 1 && {
                unsafe { pages::set_legacy_recompile_misses(v) };
                true
            }
        },
        get: pages::switch_value,
    },
    // (P7.2: compatibility mode's memory operands in the 32-bit TLB, as
    // Tier-0's)
    Switch {
        name: "x64_compat_tlb",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_compat_tlb).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_bucket_dispatch",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_bucket_dispatch).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_block_count",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_block_count).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_outline",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_outline).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_cvt",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_cvt).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_loops",
        default: 2,
        // (2: only in compiles with inline lookups, P4.14's hot recompiles)
        set: pagegen::set_loops,
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_xmm_locals",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_xmm_locals).is_some(),
        get: pagegen::switch_value,
    },
    // (docs/jit-unification-plan.md P4.23)
    Switch {
        name: "x64_exit_flags",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_exit_flags).is_some(),
        get: pagegen::switch_value,
    },
    // (docs/jit-unification-plan.md P4.22; functions of either kind must
    // not chain to each other)
    Switch {
        name: "x64_fast_chain",
        default: 0,
        set: |v| {
            flag(v)
                .map(|on| {
                    pagegen::x64_page_set_fast_chain(on);
                    pages::reset();
                })
                .is_some()
        },
        get: pagegen::switch_value,
    },
    // (docs/jit-unification-plan.md P4.21)
    Switch {
        name: "x64_fast_lookup",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_fast_lookup).is_some(),
        get: pagegen::switch_value,
    },
    // (docs/jit-unification-plan.md P4.20)
    Switch {
        name: "x64_i32_ops",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_i32_ops).is_some(),
        get: pagegen::switch_value,
    },
    // (docs/jit-unification-plan.md P4.18)
    Switch {
        name: "x64_sse_fast_check",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_sse_fast_check).is_some(),
        get: pagegen::switch_value,
    },
    Switch {
        name: "x64_sti_shadow",
        default: 1,
        set: |v| flag(v).map(pagegen::x64_page_set_sti_shadow).is_some(),
        get: pagegen::switch_value,
    },
    // 32-bit and 16-bit code in the page tier (x64_page_legacy32,
    // x64_page_compat32, x64_page_prot16 and x64_page_v86 take effect with
    // it): CPU.configure_jit_backend sets it unless its setting ir_tier0 is
    // false (IR Tier-0's name, which it replaced in P7.5; the region tiers
    // took that code without it until M11 deleted them)
    Switch {
        name: "ir_tier0",
        default: 0,
        set: |v| unsafe { crate::jit::jit_set_page32(v) },
        get: |_| Some(unsafe { pages::page32_tier0() } as u32),
    },
    Switch {
        name: "ir_relaxed_fma",
        default: 0,
        set: |v| unsafe { crate::x64::helpers::ir_set_relaxed_fma(v) },
        get: |_| Some(unsafe { crate::x64::helpers::ir_relaxed_fma() }),
    },
    // measurement: the step profile of both tiers (crate::step_profile)
    Switch {
        name: "step_profile",
        default: 0,
        set: |v| {
            flag(v)
                .map(|on| unsafe { step_profile::set_enabled(on) })
                .is_some()
        },
        get: |_| Some(step_profile::enabled() as u32),
    },
    // measurement: retired instructions by mode and how they ran
    // (crate::cpu::execution's mode ledger)
    Switch {
        name: "mode_ledger",
        default: 0,
        set: |v| {
            flag(v)
                .map(|on| unsafe { execution::set_ledger(on) })
                .is_some()
        },
        get: |_| Some(execution::ledger_on() as u32),
    },
];

const COUNT: usize = SWITCHES.len();
const UNSET: u32 = u32::MAX;

/// name=value pairs, comma separated, set at build time (Makefile JIT_DEFAULTS)
const BUILD_DEFAULTS: &str = match option_env!("JIT_DEFAULTS") {
    Some(defaults) => defaults,
    None => "",
};

/// The values set through jit_set_switch, which vCPU workers copy (UNSET:
/// never set here)
static mut EXPLICIT: [u32; COUNT] = [UNSET; COUNT];
/// In a vCPU worker: the machine's values it applied last
static mut COPIED: [u32; COUNT] = [UNSET; COUNT];
/// "name default\n" for each switch, by id (jit_switch_text)
static mut NAMES: Option<String> = None;

#[no_mangle]
pub fn jit_switch_count() -> u32 { COUNT as u32 }

/// The value of switch `id`, or u32::MAX for an unknown id or a value that
/// cannot be read now (a module busy compiling)
#[no_mangle]
pub unsafe fn jit_switch(id: u32) -> u32 {
    match SWITCHES.get(id as usize) {
        Some(s) => (s.get)(s.name).unwrap_or(UNSET),
        None => UNSET,
    }
}

#[no_mangle]
pub unsafe fn jit_set_switch(id: u32, value: u32) -> bool {
    let Some(s) = SWITCHES.get(id as usize)
    else {
        return false;
    };
    if value == UNSET || !(s.set)(value) {
        return false;
    }
    EXPLICIT[id as usize] = value;
    true
}

/// The value last set through jit_set_switch, or u32::MAX (what a vCPU worker
/// is started with, src/browser/starter.js)
#[no_mangle]
pub unsafe fn jit_switch_explicit(id: u32) -> u32 {
    if (id as usize) < COUNT {
        EXPLICIT[id as usize]
    }
    else {
        UNSET
    }
}

/// The address of a text: 0, the switches ("name default\n" by id); 1, the
/// build-time defaults (JIT_DEFAULTS)
#[no_mangle]
pub unsafe fn jit_switch_text(which: u32) -> u32 { text(which).as_ptr() as u32 }
#[no_mangle]
pub unsafe fn jit_switch_text_length(which: u32) -> u32 { text(which).len() as u32 }

unsafe fn text(which: u32) -> &'static str {
    if which == 1 {
        return BUILD_DEFAULTS;
    }
    (*(&raw mut NAMES)).get_or_insert_with(|| {
        SWITCHES
            .iter()
            .map(|s| format!("{} {}\n", s.name, s.default))
            .collect()
    })
}

/// In a vCPU worker (cpu::copy_machine_configuration): apply the values set on
/// the machine instance since the last call, each change once
pub unsafe fn copy_from_machine() {
    if crate::parallel::machine_instance() {
        return;
    }
    let explicit = *crate::parallel::machine(&raw mut EXPLICIT);
    for id in 0..COUNT {
        let value = explicit[id];
        if value != UNSET && value != COPIED[id] {
            COPIED[id] = value;
            (SWITCHES[id].set)(value);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_are_unique_and_defaults_in_range() {
        for (i, s) in SWITCHES.iter().enumerate() {
            assert!(
                SWITCHES[..i].iter().all(|t| t.name != s.name),
                "{} twice",
                s.name
            );
            assert!(s.default != UNSET, "{}", s.name);
            assert!(
                s.name
                    .bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'),
                "{}",
                s.name
            );
        }
    }

    #[test]
    fn build_defaults_name_switches() {
        for pair in BUILD_DEFAULTS
            .split(',')
            .map(str::trim)
            .filter(|p| !p.is_empty())
        {
            let (name, value) = pair
                .split_once('=')
                .expect("JIT_DEFAULTS: name=value pairs");
            assert!(
                SWITCHES.iter().any(|s| s.name == name.trim()),
                "JIT_DEFAULTS: unknown switch {}",
                name
            );
            value.trim().parse::<u32>().expect("JIT_DEFAULTS: a number");
        }
    }
}
                                                                                                                                                                                                                                        source/v64/src/rust/jitrt/access.rs                                                                 0000644 0000000 0000000 00000026000 00000000000 014411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The access cache of compiled code (docs/jit-unification-plan.md P5.8):
//! per core, per privilege (user: x86 CPL 3, A64 EL0) and per access kind,
//! a direct-mapped table of virtual 4 KiB pages whose current translation is
//! plain guest RAM (and, for writes, holds no compiled code). Page functions
//! look entries up inline or through their module's lookup function
//! (crate::pagegen::frame); a miss goes to the ISA's runtime, which fills
//! the entry from a successful translation.
//!
//! An entry is only ever derived from a translation the ISA made, so a hit
//! is as valid as that translation: every invalidation of the ISA's TLB
//! retires the core's entries, an epoch step (TagLayout: the epoch is part of
//! each entry's tag). Entries that came from a large translation (an x86
//! large page, an A64 block) mark their region: invalidating one page there
//! flushes the core. Entries of global translations survive an address
//! space switch (flush_nonglobal).
//!
//! The memory layout is what generated code reads: four tables of
//! `entries` 16-byte entries (tag: u64, host: u32, delta: u32), read
//! supervisor, read user, write supervisor, write user, in room for
//! MAX_ENTRIES each. The ISA keeps the caches (one per core) and how a
//! physical page reaches the host, through Bus.

/// Room per table; the ISA chooses `entries`, a power of two up to it
pub const MAX_ENTRIES: usize = 4096;
pub const ENTRY_BYTES: u32 = 16;
/// The tables: read supervisor, read user, write supervisor, write user
pub const TABLES: usize = 4;
const LARGE_WORDS: usize = 16;

/// How tags are made: the virtual page number below `epoch_shift`, the
/// core's epoch (never 0) from there; large translations mark regions of
/// 2^`region_shift` bytes
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct TagLayout {
    pub epoch_shift: u32,
    pub region_shift: u32,
}
impl TagLayout {
    /// The epochs a tag holds: past them, the tables are emptied
    pub const fn epoch_limit(self) -> u64 { 1 << (64 - self.epoch_shift) }
    pub const fn tag(self, page: u64, epoch: u64) -> u64 { page | epoch << self.epoch_shift }
    /// The page number of a tag
    pub const fn page(self, tag: u64) -> u64 { tag & !(!0 << self.epoch_shift) }
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct Entry {
    pub tag: u64,
    pub host: u32,
    /// host minus the low 32 bits of the page's virtual address: what an
    /// address's low 32 bits add to (inline lookups that keep translations,
    /// x86's P4.21)
    pub delta: u32,
}
pub const EMPTY: Entry = Entry {
    tag: 0,
    host: 0,
    delta: 0,
};

/// One core's cache
#[repr(C, align(16))]
pub struct AccessCache {
    /// TABLES tables of `entries` each (slot)
    pub tables: [Entry; TABLES * MAX_ENTRIES],
    /// The epoch, which is never 0 (so zeroed entries never match), less
    /// one: a zeroed cache is the initial state, and a static of caches
    /// takes no room in the module's data
    epoch_less_one: u64,
    /// Regions (hashed to LARGE_WORDS * 64 bits) with entries from a large
    /// translation since the last flush
    large: [u64; LARGE_WORDS],
    /// Per entry of `tables`: from a global translation
    global: [u64; TABLES * MAX_ENTRIES / 64],
}

/// The physical memory behind the cache (the ISA's bus, P5.8's extension
/// point: x86's physical bus, the virt board's AddressSpace)
pub trait Bus {
    /// The RAM backing offset of the physical page holding `physical`, if
    /// page functions may access it directly (plain RAM, no device)
    fn ram_backing(&self, physical: u64) -> Option<u32>;
}

impl AccessCache {
    pub const NEW: AccessCache = AccessCache {
        tables: [EMPTY; TABLES * MAX_ENTRIES],
        epoch_less_one: 0,
        large: [0; LARGE_WORDS],
        global: [0; TABLES * MAX_ENTRIES / 64],
    };
    #[inline(always)]
    pub fn epoch(&self) -> u64 { self.epoch_less_one + 1 }
    /// Tag bits of entries in the current epoch
    #[inline(always)]
    pub fn epoch_bits(&self, layout: TagLayout) -> u64 { self.epoch() << layout.epoch_shift }
    /// The entry of page `page` in table `kind` (0-3)
    #[inline(always)]
    pub fn slot(entries: usize, kind: usize, page: u64) -> usize {
        kind * entries + (page as usize & (entries - 1))
    }
    /// The address of table `kind`'s first entry
    pub fn base(&self, entries: usize, kind: usize) -> u32 {
        std::ptr::addr_of!(self.tables[kind * entries]) as u32
    }
    fn region_bit(layout: TagLayout, address: u64) -> (usize, u64) {
        let region = (address >> layout.region_shift) as usize & (LARGE_WORDS * 64 - 1);
        (region / 64, 1 << (region % 64))
    }
    /// Every entry retired by a new epoch: true when the epochs wrapped (the
    /// tables were emptied; anything else tagged with the epoch must go too)
    pub fn flush(&mut self, layout: TagLayout) -> bool {
        self.epoch_less_one += 1;
        self.large = [0; LARGE_WORDS];
        if self.epoch() == layout.epoch_limit() {
            self.tables.fill(EMPTY);
            self.epoch_less_one = 0;
            return true;
        }
        false
    }
    /// Empty the tables (a new number of entries)
    pub fn clear(&mut self) { self.tables.fill(EMPTY) }
    /// An ISA that keeps several epochs live (A64 with a64_asid_tag: one per
    /// ASID) makes `epoch` the current one; it numbers them itself, never
    /// reusing one before the tables were emptied (and never 0). (The x86
    /// core has no use for it.)
    #[allow(dead_code)]
    pub fn set_epoch(&mut self, epoch: u64) { self.epoch_less_one = epoch - 1 }
    /// An address space switch: only the entries of global translations stay
    pub fn flush_nonglobal(&mut self, entries: usize) {
        for (i, entry) in self.tables[..TABLES * entries].iter_mut().enumerate() {
            if self.global[i / 64] >> (i % 64) & 1 == 0 {
                entry.tag = 0;
            }
        }
    }
    /// One page's translations were invalidated: its entries go, or every
    /// entry when the page is in a region with large translations. Whether
    /// that flushed the cache (and its epochs wrapped: Some(true))
    pub fn invalidate_page(
        &mut self,
        layout: TagLayout,
        entries: usize,
        address: u64,
    ) -> Option<bool> {
        let (word, bit) = Self::region_bit(layout, address);
        if self.large[word] & bit != 0 {
            return Some(self.flush(layout));
        }
        let page = address >> 12;
        let tag = layout.tag(page, self.epoch());
        for kind in 0..TABLES {
            let entry = &mut self.tables[Self::slot(entries, kind, page)];
            if entry.tag == tag {
                entry.tag = 0;
            }
        }
        None
    }
    /// The write entries `retire` picks go (a page gained compiled code)
    #[inline]
    pub fn retire_writes(&mut self, entries: usize, retire: impl Fn(&Entry) -> bool) {
        for entry in self.tables[2 * entries..4 * entries].iter_mut() {
            if entry.tag != 0 && retire(entry) {
                entry.tag = 0;
            }
        }
    }
    /// Record that the virtual page of `address` translates to host address
    /// `host` (page aligned) for this access kind and privilege; `large`:
    /// part of a large translation; `global`: kept by address space
    /// switches. Whether it replaced a live entry of another page (a
    /// conflict, for the ISA's statistics)
    #[inline]
    pub fn fill(
        &mut self,
        layout: TagLayout,
        entries: usize,
        user: bool,
        write: bool,
        address: u64,
        host: u32,
        large: bool,
        global: bool,
    ) -> bool {
        let page = address >> 12;
        if large {
            let (word, bit) = Self::region_bit(layout, address);
            self.large[word] |= bit;
        }
        let index = Self::slot(entries, write as usize * 2 + user as usize, page);
        let epoch = self.epoch();
        let entry = &mut self.tables[index];
        let tag = layout.tag(page, epoch);
        let conflict = entry.tag >> layout.epoch_shift == epoch && entry.tag != tag;
        *entry = Entry {
            tag,
            host,
            delta: host.wrapping_sub((page << 12) as u32),
        };
        let (word, bit) = (index / 64, 1u64 << (index % 64));
        if global {
            self.global[word] |= bit;
        }
        else {
            self.global[word] &= !bit;
        }
        conflict
    }
    /// (tests) the entry of table `kind` for `page`
    #[cfg(test)]
    pub fn entry(&self, entries: usize, kind: usize, page: u64) -> Entry {
        self.tables[Self::slot(entries, kind, page)]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    const LAYOUT: TagLayout = TagLayout {
        epoch_shift: 52,
        region_shift: 21,
    };
    static mut CACHE: AccessCache = AccessCache::NEW;

    #[test]
    fn epochs_large_regions_and_globals() {
        let c = unsafe { &mut *(&raw mut CACHE) };
        let address = 0xFFFF_8000_1234_5678u64;
        let page = address >> 12;
        assert!(!c.fill(LAYOUT, 1024, true, true, address, 0x5000, false, true));
        assert_eq!(c.entry(1024, 3, page).tag, LAYOUT.tag(page, c.epoch()));
        assert_eq!(
            c.entry(1024, 3, page).delta,
            0x5000u32.wrapping_sub((page << 12) as u32)
        );
        // a global entry survives an address space switch, a page's invalidation does not
        c.flush_nonglobal(1024);
        assert_ne!(c.entry(1024, 3, page).tag, 0);
        assert_eq!(c.invalidate_page(LAYOUT, 1024, address), None);
        assert_eq!(c.entry(1024, 3, page).tag, 0);
        // an entry of a large translation: invalidating any page of its region flushes
        c.fill(LAYOUT, 1024, false, false, address, 0x6000, true, false);
        let before = c.epoch();
        assert_eq!(
            c.invalidate_page(LAYOUT, 1024, address & !0x1F_FFFF | 0x1000),
            Some(false)
        );
        assert_eq!(c.epoch(), before + 1);
        assert_ne!(c.entry(1024, 0, page).tag, LAYOUT.tag(page, c.epoch()));
        // epochs wrap to an emptied cache, never to 0
        let mut wrapped = false;
        for _ in 0..LAYOUT.epoch_limit() {
            wrapped |= c.flush(LAYOUT);
        }
        assert!(wrapped);
        assert_ne!(c.epoch(), 0);
        assert_eq!(LAYOUT.page(c.entry(1024, 0, page).tag), 0);
    }

    static mut KEPT: AccessCache = AccessCache::NEW;
    #[test]
    fn epochs_kept_side_by_side() {
        // (A64's a64_asid_tag: an epoch per ASID, switched to and back)
        let c = unsafe { &mut *(&raw mut KEPT) };
        let address = 0x0000_7FFF_0000_1000u64;
        let page = address >> 12;
        c.set_epoch(5);
        c.fill(LAYOUT, 1024, true, false, address, 0x5000, false, false);
        c.set_epoch(9);
        assert_ne!(c.entry(1024, 1, page).tag, LAYOUT.tag(page, c.epoch()));
        c.fill(
            LAYOUT,
            1024,
            true,
            false,
            address + 0x1000,
            0x6000,
            false,
            false,
        );
        c.set_epoch(5);
        assert_eq!(c.epoch(), 5);
        assert_eq!(c.entry(1024, 1, page).tag, LAYOUT.tag(page, 5));
    }
}
source/v64/src/rust/jitrt/capacity.rs                                                               0000644 0000000 0000000 00000005240 00000000000 014750  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The table's slot budget (P5.5): each client's soft quota of the core's
//! table. A client that holds its quota evicts its own code before it takes
//! a slot; one that is under its quota while the table is full posts an
//! eviction request to the clients over theirs. Nobody evicts another's
//! code: a request is carried out by its victim at its next cold point
//! (take_request). The composition root sets the quotas: in the x86 core the
//! x64 page tier's is what it held alone (pages::MAX_FUNCTIONS, its mode
//! shares, P7.2b, within it), in the ARM core the whole table is A64Page's.

use super::ClientId;

const CLIENTS: usize = 2;
static mut QUOTA: [u32; CLIENTS] = [0; CLIENTS];
static mut REQUESTS: [u32; CLIENTS] = [0; CLIENTS];

pub fn set_quota(client: ClientId, slots: u32) { unsafe { QUOTA[client as usize] = slots } }
pub fn quota(client: ClientId) -> u32 { unsafe { QUOTA[client as usize] } }

/// Before `client`, holding `held` slots, takes another (`free` slots left
/// in the table): whether it must evict one of its own first. When the table
/// is full but `client` is under its quota, the clients over theirs get a
/// request instead (`held_by` tells how many each holds).
pub fn must_evict(
    client: ClientId,
    held: u32,
    free: u32,
    held_by: impl Fn(ClientId) -> u32,
) -> bool {
    if held >= quota(client) {
        return true;
    }
    if free == 0 {
        for other in [ClientId::X86Page, ClientId::A64Page] {
            if other != client && held_by(other) > quota(other) {
                unsafe { REQUESTS[other as usize] += 1 };
            }
        }
    }
    false
}

/// At `client`'s cold point: an eviction another client asked of it, if any
pub fn take_request(client: ClientId) -> bool {
    unsafe {
        let n = &mut REQUESTS[client as usize];
        if *n == 0 {
            return false;
        }
        *n -= 1;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn quotas_and_requests() {
        set_quota(ClientId::X86Page, 3);
        set_quota(ClientId::A64Page, 2);
        let held = |c: ClientId| if c == ClientId::X86Page { 1 } else { 4 };
        // under its quota with room: no eviction, no request
        assert!(!must_evict(ClientId::X86Page, 1, 5, held));
        assert!(!take_request(ClientId::A64Page));
        // at its quota: its own
        assert!(must_evict(ClientId::X86Page, 3, 5, held));
        // a full table while under: A64Page (4 of 2) is asked once
        assert!(!must_evict(ClientId::X86Page, 1, 0, held));
        assert!(take_request(ClientId::A64Page));
        assert!(!take_request(ClientId::A64Page));
        assert!(!take_request(ClientId::X86Page));
    }
}
                                                                                                                                                                                                                                                                                                                                                                source/v64/src/rust/jitrt/chain.rs                                                                  0000644 0000000 0000000 00000007103 00000000000 014235  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Chaining tables (docs/jit-unification-plan.md P5.8): a page function
//! leaving its page looks the new virtual page up in its core's table for
//! the code mode and privilege it runs in, and tail-calls the function
//! serving it without returning to the dispatch loop
//! (crate::pagegen::frame emits the lookup). Direct mapped by virtual page:
//! the tag is the page with the core's access cache epoch (access::TagLayout,
//! so every flush of the ISA's TLB retires the entries; invalidating a page
//! forgets its entry), and the Wasm table index of a published function
//! whose code page the virtual page executed from when the entry was
//! filled. Retiring a function clears its entries.
//!
//! The memory layout is what generated code reads: ENTRIES entries of
//! ENTRY_BYTES, the tag at 0 (u64), the table index at TABLE_INDEX_OFFSET.

use crate::jitrt::access::TagLayout;

pub const ENTRIES: usize = 1024;
pub const ENTRY_BYTES: u32 = 16;
pub const TABLE_INDEX_OFFSET: u32 = 8;

#[derive(Clone, Copy)]
#[repr(C)]
pub struct ChainEntry {
    pub tag: u64,
    pub table_index: u32,
    /// the code page's translation is global (kept by address space switches)
    pub global: u32,
}
const NO_CHAIN: ChainEntry = ChainEntry {
    tag: 0,
    table_index: 0,
    global: 0,
};

#[repr(C, align(16))]
pub struct ChainTable(pub [ChainEntry; ENTRIES]);
impl ChainTable {
    pub const EMPTY: ChainTable = ChainTable([NO_CHAIN; ENTRIES]);
    /// The address of the first entry (what generated code indexes)
    pub fn base(&self) -> u32 { std::ptr::addr_of!(self.0) as u32 }
    /// Virtual page `page` runs the function at `table_index`
    #[inline]
    pub fn fill(&mut self, page: u64, epoch_bits: u64, table_index: u32, global: bool) {
        self.0[page as usize & (ENTRIES - 1)] = ChainEntry {
            tag: page | epoch_bits,
            table_index,
            global: global as u32,
        };
    }
    /// Page `page`'s translation was invalidated
    pub fn forget_page(&mut self, layout: TagLayout, page: u64) {
        let entry = &mut self.0[page as usize & (ENTRIES - 1)];
        if layout.page(entry.tag) == page {
            entry.tag = 0;
        }
    }
    /// An address space switch: only global pages' entries stay
    pub fn forget_nonglobal(&mut self) {
        for entry in self.0.iter_mut() {
            if entry.global == 0 {
                entry.tag = 0;
            }
        }
    }
    pub fn clear(&mut self) {
        for entry in self.0.iter_mut() {
            entry.tag = 0;
        }
    }
    /// The function at `table_index` was retired
    pub fn unchain(&mut self, table_index: u32) {
        for entry in self.0.iter_mut() {
            if entry.table_index == table_index {
                entry.tag = 0;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    const LAYOUT: TagLayout = TagLayout {
        epoch_shift: 52,
        region_shift: 21,
    };

    #[test]
    fn layout_fill_and_forget() {
        assert_eq!(std::mem::size_of::<ChainEntry>() as u32, ENTRY_BYTES);
        assert_eq!(
            std::mem::offset_of!(ChainEntry, table_index) as u32,
            TABLE_INDEX_OFFSET
        );
        let mut t = Box::new(ChainTable::EMPTY);
        t.fill(0x12345, 1 << 52, 77, false);
        t.fill(0x12346, 1 << 52, 78, true);
        assert_eq!(t.0[0x345].tag, 0x12345 | 1 << 52);
        t.forget_nonglobal();
        assert_eq!(t.0[0x345].tag, 0);
        assert_ne!(t.0[0x346].tag, 0);
        t.forget_page(LAYOUT, 0x22346);
        assert_ne!(t.0[0x346].tag, 0);
        t.unchain(78);
        assert_eq!(t.0[0x346].tag, 0);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/rust/jitrt/heat.rs                                                                   0000644 0000000 0000000 00000005322 00000000000 014075  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Execution heat of code pages (P5.7): what a page tier knows of a code page
//! it has no function for, or one that serves too little of it, and the
//! batch of interpreted execution's heat (P4.5b's HeatBatch, moved here as it
//! was). The thresholds and what a page's state means for compiling are
//! the client's (the x64 page tier's HOT, LEGACY_HEAT and recompile rules).

/// A code page's state; `x` is the client's own
pub struct PageState<X> {
    /// interpreted instructions on it since its last compile
    pub heat: u32,
    /// the offsets it was entered at (far transfers: block starts)
    pub entries: [u64; 64],
    /// entries a function did not serve, seen once
    pub seen: [u64; 64],
    pub entry_count: u32,
    pub misses: u32,
    pub compiles: u32,
    pub x: X,
}
impl<X: Default> Default for PageState<X> {
    fn default() -> Self {
        Self {
            heat: 0,
            entries: [0; 64],
            seen: [0; 64],
            entry_count: 0,
            misses: 0,
            compiles: 0,
            x: X::default(),
        }
    }
}

/// Compiles of a page free of backoff; each one after doubles the heat or
/// misses the next waits for, up to 2^16 times
pub const FREE_RECOMPILES: u32 = 4;
pub fn backoff(compiles: u32) -> u32 { compiles.saturating_sub(FREE_RECOMPILES).min(16) }

/// Interpreted execution's heat, batched (docs/jit-unification-plan.md
/// P4.5b): instructions run outside compiled code on a code page without a
/// function, not yet added to the page's PageState. While the runtime's
/// functions are unchanged (`generation`) a miss on that page needs neither
/// the function nor the page lookup; it is added at the next miss of another
/// page, and at HEAT_BATCH_LIMIT.
#[derive(Clone, Copy)]
pub struct HeatBatch {
    pub page: u32,
    pub count: u32,
    pub generation: u32,
}
impl HeatBatch {
    pub const NONE: HeatBatch = HeatBatch {
        page: u32::MAX,
        count: 0,
        generation: 0,
    };
    pub fn holds(self, page: u32, generation: u32) -> bool {
        self.page == page && self.generation == generation
    }
}
pub const HEAT_BATCH_LIMIT: u32 = 256;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn backoff_and_batch() {
        assert_eq!(backoff(0), 0);
        assert_eq!(backoff(FREE_RECOMPILES), 0);
        assert_eq!(backoff(FREE_RECOMPILES + 3), 3);
        assert_eq!(backoff(1000), 16);
        let b = HeatBatch {
            page: 5,
            count: 1,
            generation: 2,
        };
        assert!(b.holds(5, 2) && !b.holds(5, 3) && !b.holds(6, 2));
        assert!(!HeatBatch::NONE.holds(u32::MAX, 1));
        let s: PageState<u8> = PageState::default();
        assert_eq!((s.heat, s.compiles, s.x), (0, 0, 0));
    }
}
                                                                                                                                                                                                                                                                                                              source/v64/src/rust/jitrt/host.rs                                                                   0000644 0000000 0000000 00000003724 00000000000 014135  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! What the runtime needs of its host (P5.1), filled once at initialisation
//! by the core's composition root (crate::jit::rust_init): the table's
//! geometry and the host's services, which jitrt may not import itself.
//! (The ARM64 plan's P1.0 moves the host imports that both cores use out of
//! crate::cpu; until then the composition root passes the CPU's.)

use crate::page::Page;

// (the geometry and services that the ARM core's client uses too, which the
// x86 client takes from crate::cpu directly until the ARM64 plan's P1.0)
#[allow(dead_code)]
pub struct Env {
    /// The Wasm table: slots 1..table_size are handed out (slot 0 never),
    /// at table_offset in the host's table
    pub table_size: u32,
    pub table_offset: u32,
    /// The CPU state block's address (its fields are at fixed offsets)
    pub state_base: u32,
    /// Guest memory's base in the Wasm memory
    pub mem8: fn() -> *mut u8,
    /// The host's clock, in milliseconds
    pub now: fn() -> f64,
    /// The core this instance runs (0 without cores in workers)
    pub core: fn() -> usize,
    /// Clears a table slot (the host import jit_clear_func)
    pub clear_slot: fn(u32),
    /// A page's code changed: whether stores to it must notify, for the
    /// translations that cache it (TLB fills)
    pub page_has_code: fn(Page, bool),
    /// Code was compiled from these pages: they gain code, and cached write
    /// translations to them retire
    pub pages_gain_code: fn(&std::collections::HashSet<Page>),
    /// This instance watches a page from now on (true) or no longer (false):
    /// with cores in workers, the other cores must hear of its writes
    pub claim: fn(u32, bool),
    /// Every page released at once (a reset)
    pub release_all: fn(),
}

static mut ENV: Option<Env> = None;

pub(super) fn set(env: Env) { unsafe { ENV = Some(env) } }

/// The environment (after super::init)
#[inline(always)]
pub fn env() -> &'static Env { unsafe { (*(&raw const ENV)).as_ref().unwrap() } }
                                            source/v64/src/rust/jitrt/mod.rs                                                                    0000644 0000000 0000000 00000005321 00000000000 013732  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The ISA-neutral runtime of compiled code (docs/jit-unification-plan.md
//! P5, J1a): the Wasm table's slots and their owners (table), the guest
//! pages compiled code was made from and the listeners that hear of writes
//! to them (watch), publication (publish), the slot budget (capacity),
//! execution heat (heat) and the clients' statistics (stat); J1b: single
//! steps (step).
//!
//! Its clients are the ISAs' page tiers: `X86Page` (crate::x64::pages, the
//! only x86 compiler since M11 deleted the IR region tiers) in the x86 core,
//! `A64Page` in the ARM core (docs/arm64-virt-android16-plan.md). Each core
//! registers only its own ISA's clients; its composition root (crate::jit
//! for x86) fills host::Env and registers the listeners. The hot-path
//! compositions (crate::jit::page_watched) stay in the composition root.
//!
//! Imports: std, crate::page, crate::wasmgen and crate::leb only, nothing of
//! an ISA, the CPU or the host's modules; no `feature = "aarch64"`: ISA
//! differences come through host::Env or type parameters
//! (tools/check_x86tpl_imports.mjs checks it, in make jit-gate).

pub mod access;
pub mod capacity;
pub mod chain;
pub mod heat;
pub mod host;
pub mod page;
pub mod publish;
pub mod stat;
pub mod step;
pub mod table;
pub mod watch;

use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
use std::sync::{Mutex, MutexGuard};

/// A client of the runtime: an ISA's page tier
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[repr(u8)]
pub enum ClientId {
    X86Page = 0,
    // (the ARM core's: docs/arm64-virt-android16-plan.md, J2)
    #[allow(dead_code)]
    A64Page = 1,
}
impl ClientId {
    pub fn of(n: u32) -> Option<ClientId> {
        match n {
            0 => Some(ClientId::X86Page),
            1 => Some(ClientId::A64Page),
            _ => None,
        }
    }
}

/// The table and the watched pages of one core instance
pub struct State {
    pub table: table::Table,
    pub watch: watch::Watch,
}

static STATE: Mutex<MaybeUninit<State>> = Mutex::new(MaybeUninit::uninit());

pub struct StateRef(MutexGuard<'static, MaybeUninit<State>>);
impl Deref for StateRef {
    type Target = State;
    fn deref(&self) -> &State { unsafe { self.0.assume_init_ref() } }
}
impl DerefMut for StateRef {
    fn deref_mut(&mut self) -> &mut State { unsafe { self.0.assume_init_mut() } }
}
/// The runtime's state (init first)
pub fn state() -> StateRef { StateRef(STATE.try_lock().unwrap()) }

/// Once, with the host's environment: an empty table of its size, nothing
/// watched
pub fn init(env: host::Env) {
    let size = env.table_size;
    host::set(env);
    let _ = STATE.try_lock().unwrap().write(State {
        table: table::Table::new(size),
        watch: watch::Watch::new(),
    });
}
                                                                                                                                                                                                                                                                                                               source/v64/src/rust/jitrt/page.rs                                                                   0000644 0000000 0000000 00000016421 00000000000 014072  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! A page tier's runtime (P5.7): its functions (one per code page, or a span
//! of pages), the code pages it knows (heat::PageState), the functions'
//! publication phases, least-recently-used eviction and the release of dead
//! functions' slots at the client's cold points. Generic over the client's
//! frontend (PageFrontend), whose types hold what is the ISA's: the x64 page
//! tier (crate::x64::pages, `X86`) is the first client; when, how and in
//! which mode to compile, and how to run a function, stay its own.

use super::heat::PageState;
use super::publish::Phase;
use std::collections::HashMap;

/// A client's types
pub trait PageFrontend {
    /// a function's own data
    type Code;
    /// a code page's own state
    type Page: Default;
    /// the runtime's own state
    type Extra;
}

pub struct Function<C> {
    /// the key of its (first) page: a backing page number with the client's
    /// mode bits
    pub page: u32,
    pub id: u64,
    pub slot: u32,
    pub phase: Phase,
    /// Block starts: a bitmap of offsets, 64 words a page of `members`
    pub served: Vec<u64>,
    /// The keys of the pages it covers, `page` first
    pub members: Vec<u32>,
    pub last_used: u64,
    pub x: C,
}
fn bit(set: &[u64], offset: u16) -> bool { set[offset as usize / 64] >> (offset % 64) & 1 != 0 }
impl<C> Function<C> {
    /// Which of its pages has key `key`, if any
    pub fn member(&self, key: u32) -> Option<usize> { self.members.iter().position(|&m| m == key) }
    /// Whether it serves offset `offset` of its member page `m`
    pub fn serves(&self, m: usize, offset: u16) -> bool {
        bit(&self.served, (m * 4096) as u16 + offset)
    }
}

/// Multiplicative hashing for page numbers.
#[derive(Default)]
pub struct PageHasher(u64);
impl std::hash::Hasher for PageHasher {
    fn finish(&self) -> u64 { self.0 }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0.rotate_left(8) ^ b as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
        }
    }
    fn write_u32(&mut self, value: u32) {
        self.0 = (value as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}
pub type PageMap<V> = HashMap<u32, V, std::hash::BuildHasherDefault<PageHasher>>;

pub struct PageRuntime<F: PageFrontend> {
    pub functions: Vec<Function<F::Code>>,
    pub by_page: PageMap<usize>,
    pub pages: PageMap<PageState<F::Page>>,
    /// slots of dead functions, released at the next cold point
    pub releases: Vec<(u32, u64)>,
    pub next_id: u64,
    pub clock: u64,
    pub enabled: bool,
    /// the client's counters
    pub stats: [u64; 13],
    /// Changes whenever a function is registered or retired (HeatBatch)
    pub generation: u32,
    pub x: F::Extra,
}

impl<F: PageFrontend> PageRuntime<F> {
    pub fn new(x: F::Extra) -> Self {
        PageRuntime {
            functions: Vec::new(),
            by_page: PageMap::default(),
            pages: PageMap::default(),
            releases: Vec::new(),
            next_id: 1,
            clock: 0,
            enabled: true,
            stats: [0; 13],
            generation: 0,
            x,
        }
    }
    /// Its functions that are not dead
    pub fn live(&self) -> u32 {
        self.functions
            .iter()
            .filter(|f| f.phase != Phase::Dead)
            .count() as u32
    }
    /// The function a full quota retires for a compile of code of a class
    /// (`in_class`, a mode of the client's): the least recently used ready
    /// one, of that class when the class holds more than `share` (P7.2b)
    pub fn victim(
        &self,
        in_class: impl Fn(&Function<F::Code>) -> bool,
        share: usize,
    ) -> Option<usize> {
        let held = self
            .functions
            .iter()
            .filter(|f| f.phase != Phase::Dead && in_class(f))
            .count();
        let crowded = held > share;
        self.functions
            .iter()
            .enumerate()
            .filter(|(_, f)| f.phase == Phase::Ready && (!crowded || in_class(f)))
            .min_by_key(|(_, f)| f.last_used)
            .map(|(i, _)| i)
    }
    /// The pending function with code `id` in `slot` (the host asks before it
    /// sets the slot)
    pub fn pending(&self, id: u64, slot: u32) -> Option<usize> {
        self.functions
            .iter()
            .position(|f| f.id == id && f.slot == slot && f.phase == Phase::Pending)
    }
    /// Pending -> Ready for the function with code `id` in `slot`
    pub fn ready(&mut self, id: u64, slot: u32) -> Option<usize> {
        let i = self.pending(id, slot)?;
        self.functions[i].phase.ready();
        Some(i)
    }
    /// The function with code `id` in `slot`, unless dead
    pub fn alive(&self, id: u64, slot: u32) -> Option<usize> {
        self.functions
            .iter()
            .position(|f| f.id == id && f.slot == slot && f.phase != Phase::Dead)
    }
    /// Function `index` dies (false if it was dead): its slot is released at
    /// the next cold point (release_dead), its page keys stay the client's to
    /// unmap
    pub fn kill(&mut self, index: usize) -> bool {
        let f = &mut self.functions[index];
        if !f.phase.kill() {
            return false;
        }
        self.generation = self.generation.wrapping_add(1);
        self.releases.push((f.slot, f.id));
        true
    }
    /// At a cold point (no function running): each dead function's slot,
    /// through `release`
    pub fn release_dead(&mut self, mut release: impl FnMut(u32, u64)) {
        for (slot, id) in self.releases.drain(..) {
            release(slot, id);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Test;
    impl PageFrontend for Test {
        type Code = bool;
        type Page = ();
        type Extra = ();
    }
    fn function(page: u32, id: u64, phase: Phase, last_used: u64, class: bool) -> Function<bool> {
        Function {
            page,
            id,
            slot: id as u32,
            phase,
            served: vec![0; 64],
            members: vec![page],
            last_used,
            x: class,
        }
    }

    #[test]
    fn phases_eviction_and_release() {
        let mut r: PageRuntime<Test> = PageRuntime::new(());
        r.functions.push(function(1, 1, Phase::Ready, 5, false));
        r.functions.push(function(2, 2, Phase::Ready, 3, true));
        r.functions.push(function(3, 3, Phase::Pending, 1, true));
        r.functions.push(function(4, 4, Phase::Ready, 9, true));
        assert_eq!(r.live(), 4);
        // (any class: the least recently used ready one; a crowded class: its own)
        assert_eq!(r.victim(|f| !f.x, 10), Some(1));
        assert_eq!(r.victim(|f| !f.x, 0), Some(0));
        assert_eq!(r.pending(3, 3), Some(2));
        assert_eq!(r.pending(3, 4), None);
        assert_eq!(r.ready(3, 3), Some(2));
        assert_eq!(r.ready(3, 3), None);
        let generation = r.generation;
        assert!(r.kill(1));
        assert!(!r.kill(1));
        assert_eq!(r.generation, generation.wrapping_add(1));
        assert_eq!(r.alive(2, 2), None);
        assert_eq!(r.live(), 3);
        let mut released = Vec::new();
        r.release_dead(|slot, id| released.push((slot, id)));
        assert_eq!(released, [(2, 2)]);
        assert!(r.releases.is_empty());
        let f = &r.functions[0];
        assert_eq!(f.member(1), Some(0));
        assert!(!f.serves(0, 5));
    }
}
                                                                                                                                                                                                                                               source/v64/src/rust/jitrt/publish.rs                                                                0000644 0000000 0000000 00000006262 00000000000 014626  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Publication of compiled code (P5.4): a client hands a module's bytes to
//! the host with publish(); the host instantiates it (at once when it can)
//! and asks jit_install whether the code is still wanted, sets the table
//! slot and calls jit_ready, or calls jit_cancel when either failed. Each
//! piece of code goes Pending -> Ready -> Dead (Phase), Dead from any phase
//! when the client retires it; its slot is freed at the client's next cold
//! point. (The x64 page tier's own import and exports of before J1a,
//! x64_page_publish, x64_page_install, x64_page_ready and x64_page_cancel,
//! were removed at vJ2: cross-phase rule 10.)

use super::ClientId;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Phase {
    Pending,
    Ready,
    Dead,
}
impl Phase {
    /// Pending -> Ready: false in any other phase
    pub fn ready(&mut self) -> bool {
        if *self != Phase::Pending {
            return false;
        }
        *self = Phase::Ready;
        true
    }
    /// -> Dead: false if it was dead
    pub fn kill(&mut self) -> bool {
        if *self == Phase::Dead {
            return false;
        }
        *self = Phase::Dead;
        true
    }
}

/// A client's answers to the host, by the client's id of the code and its
/// slot
pub struct Client {
    /// Before the host sets the slot: whether the code is still wanted
    pub install: fn(id: u64, slot: u32) -> bool,
    /// The slot is set: the code may run
    pub ready: fn(id: u64, slot: u32) -> bool,
    /// The host could not instantiate or install it
    pub cancel: fn(id: u64, slot: u32),
}

static mut CLIENTS: [Option<Client>; 2] = [None, None];

/// By the composition root, once per client
pub fn register(client: ClientId, answers: Client) {
    unsafe { (*(&raw mut CLIENTS))[client as usize] = Some(answers) }
}
fn client(n: u32) -> Option<&'static Client> {
    unsafe { (*(&raw const CLIENTS)).get(n as usize)?.as_ref() }
}

mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn jit_publish(client: u32, id: u64, slot: u32, pointer: u32, length: u32);
    }
}

/// Hands the module `bytes` for `slot` to the host (the code `id` of
/// `client`, Pending until jit_ready)
pub fn publish(client: ClientId, id: u64, slot: u32, bytes: &[u8]) {
    unsafe {
        js::jit_publish(
            client as u32,
            id,
            slot,
            bytes.as_ptr() as u32,
            bytes.len() as u32,
        )
    }
}

#[no_mangle]
pub fn jit_install(client_id: u32, id: u64, slot: u32) -> bool {
    client(client_id).is_some_and(|c| (c.install)(id, slot))
}
#[no_mangle]
pub fn jit_ready(client_id: u32, id: u64, slot: u32) -> bool {
    client(client_id).is_some_and(|c| (c.ready)(id, slot))
}
#[no_mangle]
pub fn jit_cancel(client_id: u32, id: u64, slot: u32) {
    if let Some(c) = client(client_id) {
        (c.cancel)(id, slot)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn phases() {
        let mut p = Phase::Pending;
        assert!(p.ready());
        assert!(!p.ready());
        assert!(p.kill());
        assert!(!p.kill());
        assert!(!p.ready());
        let mut q = Phase::Pending;
        assert!(q.kill());
        assert_eq!(q, Phase::Dead);
    }
}
                                                                                                                                                                                                                                                                                                                                              source/v64/src/rust/jitrt/stat.rs                                                                   0000644 0000000 0000000 00000001431 00000000000 014124  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The clients' statistics through one export (P5.10): jit_stat(client,
//! field) is the client's own counter `field` (the x64 page tier's are
//! x64_page_stat's fields, src/rust/x64/pages.rs), NaN for a client the core
//! does not have. CPU.get_jit_info reads the page tier's through it.

use super::ClientId;

pub type Stat = fn(field: u32) -> f64;
static mut STATS: [Option<Stat>; 2] = [None, None];

/// By the composition root, once per client
pub fn register(client: ClientId, stat: Stat) {
    unsafe { (*(&raw mut STATS))[client as usize] = Some(stat) }
}

#[no_mangle]
pub fn jit_stat(client: u32, field: u32) -> f64 {
    match ClientId::of(client).and_then(|c| unsafe { (*(&raw const STATS))[c as usize] }) {
        Some(stat) => stat(field),
        None => f64::NAN,
    }
}
                                                                                                                                                                                                                                       source/v64/src/rust/jitrt/step.rs                                                                   0000644 0000000 0000000 00000007233 00000000000 014132  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Single steps of compiled code (docs/jit-unification-plan.md P5.6): a page
//! function hands an instruction it has no template for, or whose template
//! refused at run time, to its ISA's interpreter (the step frontend) and goes
//! on as the outcome says. Neutral here: the outcome ABI page functions read,
//! their exit codes, the globals of the ABI as offsets (StepAbi, resolved by
//! the core's composition root into the constants generated code embeds) and
//! the driver; the context a step may change and the reasons it ends an
//! activation are the ISA's (StepFrontend). The x86 page tier's frontend is
//! crate::x64::pages::X86Step; the A64 one is the interpreter's
//! `interpret_one` (docs/arm64-virt-android16-plan.md P2.9, J2).

/// A step's outcome, as a page function reads it (an i32)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum StepOutcome {
    /// Go on in the function at the new PC (its dispatch)
    Continue = 0,
    /// The step changed only what a function checks at its entry (the code
    /// mode among the chained ones, x86's CS of code compiled for segment
    /// bases): leave through the chaining table to the new PC's function
    Chain = 1,
    /// Leave the activation: something the dispatcher must see happened
    Exit = 2,
}
/// (the outcome generated code compares with)
pub const STEP_CHAIN: i32 = StepOutcome::Chain as i32;

/// Why a page function returned (StepAbi::exit_code): it left normally
pub const EXIT_NORMAL: u32 = 0;
/// Interpret the instruction at the PC: a template's precondition failed
/// before any of its effects
pub const EXIT_RETRY: u32 = 1;
/// The PC is in the function's pages but at no compiled block start
pub const EXIT_UNKNOWN: u32 = 2;

/// The globals of the step ABI, as their offsets in the core's memory: the
/// composition root resolves them (crate::x64::pagegen::CompileEnv holds
/// x86's), and generated code embeds them as constants
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct StepAbi {
    /// The word a returning page function leaves its exit code in (EXIT_*)
    pub exit_code: u32,
}

/// An ISA's side of a step
pub trait StepFrontend {
    /// What the step may change that compiled code depends on, as it was
    /// before the step
    type Context: Copy;
    fn context() -> Self::Context;
    /// Interpret the instruction at the PC, with the state in memory
    fn interpret_one();
    /// The outcome, from the context before the step and the state now (a
    /// Chain or Exit notes its reason in the ISA's statistics)
    fn outcome(before: &Self::Context) -> StepOutcome;
}

/// One step through the frontend `F`
#[inline(always)]
pub fn step<F: StepFrontend>() -> StepOutcome {
    let before = F::context();
    F::interpret_one();
    F::outcome(&before)
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Counter;
    static mut STATE: (u32, u32) = (0, 0);
    impl StepFrontend for Counter {
        type Context = u32;
        fn context() -> u32 { unsafe { STATE.0 } }
        fn interpret_one() {
            unsafe {
                STATE.0 += 1;
                STATE.1 += 1
            }
        }
        fn outcome(before: &u32) -> StepOutcome {
            if unsafe { STATE.0 } == before + 1 {
                StepOutcome::Continue
            }
            else {
                StepOutcome::Exit
            }
        }
    }

    #[test]
    fn outcome_abi() {
        assert_eq!(
            (
                StepOutcome::Continue as i32,
                STEP_CHAIN,
                StepOutcome::Exit as i32
            ),
            (0, 1, 2)
        );
        assert_eq!(step::<Counter>(), StepOutcome::Continue);
        assert_eq!(unsafe { STATE.1 }, 1);
    }
}
                                                                                                                                                                                                                                                                                                                                                                     source/v64/src/rust/jitrt/table.rs                                                                  0000644 0000000 0000000 00000010070 00000000000 014237  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The Wasm table's slots (P5.2): which are free and who owns each (a
//! client, the signature of the function in it, the client's id of the
//! code). One table per core instance, of host::Env's size. (The IR's
//! Tier-0 kept slots apart in T0_SLOTS until P7.5; the region tiers shared
//! this table until M11.)

use super::ClientId;
use std::collections::HashMap;

/// The type of a slot's function
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Signature {
    /// (i32) -> () (A64Page's dispatch stubs, ARM64 plan P6.0)
    #[allow(dead_code)]
    Fn1,
    /// (i32) -> i32: page functions (budget in, retired instructions out)
    Fn1Ret,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Owner {
    pub client: ClientId,
    pub signature: Signature,
    pub id: u64,
}

pub struct Table {
    size: u32,
    /// handed out from the end: the highest slot first
    free: Vec<u16>,
    owners: HashMap<u16, Owner>,
    /// the fewest free slots since reset_free_low (P0.10)
    free_low: u32,
}

impl Table {
    /// Slots 1..size, all free (0 is never handed out)
    pub fn new(size: u32) -> Table {
        dbg_assert!(size >= 2 && size <= 0x10000);
        Table {
            size,
            free: (1..size).map(|slot| slot as u16).collect(),
            owners: HashMap::new(),
            free_low: size - 1,
        }
    }
    pub fn reserve(&mut self, owner: Owner) -> Option<u32> {
        let slot = self.free.pop()?;
        self.free_low = self.free_low.min(self.free.len() as u32);
        self.owners.insert(slot, owner);
        self.check();
        Some(slot as u32)
    }
    /// Frees `slot` if `client` owns it with code `id`; called only at the
    /// client's cold point (the client guards a reused slot against late
    /// callbacks by the id)
    pub fn release(&mut self, slot: u32, client: ClientId, id: u64) -> bool {
        if slot == 0 || slot >= self.size {
            return false;
        }
        let slot = slot as u16;
        if !self
            .owners
            .get(&slot)
            .is_some_and(|o| o.client == client && o.id == id)
        {
            return false;
        }
        self.owners.remove(&slot);
        self.free.push(slot);
        self.check();
        true
    }
    #[allow(dead_code)]
    pub fn owner(&self, slot: u32) -> Option<Owner> {
        u16::try_from(slot)
            .ok()
            .and_then(|slot| self.owners.get(&slot).copied())
    }
    /// The slots `client` owns
    pub fn owned_by(&self, client: ClientId) -> usize {
        self.owners.values().filter(|o| o.client == client).count()
    }
    pub fn free_count(&self) -> u32 { self.free.len() as u32 }
    pub fn free_low(&self) -> u32 { self.free_low }
    pub fn reset_free_low(&mut self) { self.free_low = self.free.len() as u32 }

    fn check(&self) {
        if !cfg!(debug_assertions) {
            return;
        }
        dbg_assert!(self.free.iter().all(|slot| !self.owners.contains_key(slot)));
        dbg_assert!(self.free.len() + self.owners.len() == (self.size - 1) as usize);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    const X86: Owner = Owner {
        client: ClientId::X86Page,
        signature: Signature::Fn1Ret,
        id: 7,
    };

    #[test]
    fn slots_from_the_top_owned_and_released() {
        let mut t = Table::new(4);
        assert_eq!(t.reserve(X86), Some(3));
        assert_eq!(t.reserve(Owner { id: 8, ..X86 }), Some(2));
        assert_eq!(t.owner(3), Some(X86));
        assert_eq!(t.owned_by(ClientId::X86Page), 2);
        assert_eq!(t.owned_by(ClientId::A64Page), 0);
        // (another id or client: not the owner)
        assert!(!t.release(3, ClientId::X86Page, 8));
        assert!(!t.release(3, ClientId::A64Page, 7));
        assert!(!t.release(0, ClientId::X86Page, 7));
        assert!(t.release(3, ClientId::X86Page, 7));
        assert_eq!(t.owner(3), None);
        assert_eq!(t.free_low(), 1);
        t.reset_free_low();
        assert_eq!(t.free_low(), 2);
        assert_eq!(t.reserve(X86), Some(3));
        assert_eq!(t.reserve(X86), Some(1));
        assert_eq!(t.reserve(X86), None);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/jitrt/watch.rs                                                                  0000644 0000000 0000000 00000022161 00000000000 014262  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The guest pages compiled code was made from (P5.3): each slot's pages,
//! how many slots depend on each page, a lock-free bit per page for the
//! writers that must notify (crate::jit::page_watched), and the listeners
//! that hear of writes and of a reset.
//!
//! A write: the Always listeners first (with cores in workers, the other
//! cores must hear of it whatever this instance compiled), then, for a page
//! this instance watches, the WatchedOnly listeners, which retire their code
//! from it and name the slots they keep (code a write of a few bytes misses);
//! every other slot made from the page stops watching all its pages. A
//! reset: the listeners, then nothing is watched. Listeners run in the order
//! they were registered. (The IR's orders, live, cache and scheduler around
//! the x64 page tier, went with the region tiers in M11.)

use super::host::env;
use crate::page::Page;
use std::collections::{HashMap, HashSet};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Trigger {
    /// every write
    Always,
    /// writes to pages this instance watches
    WatchedOnly,
}

/// A write to backing page `page` (all of it, or the bytes lo..hi): the
/// slots whose code stays (none for an Always listener)
pub type DirtyListener = fn(page: u32, bytes: Option<(u32, u32)>) -> Vec<u32>;
pub type ResetListener = fn();

pub struct Watch {
    slots: HashMap<u32, HashSet<Page>>,
    /// slots watching each page (TLB fills ask on every page walk; iterating
    /// the slots' sets was measurable)
    counts: Vec<u16>,
    dirty: Vec<(Trigger, DirtyListener)>,
    reset: Vec<ResetListener>,
}

/// Lock-free mirror of `counts != 0`, one bit per page
static mut WATCHED: Vec<u64> = Vec::new();
fn set_bit(page: usize, watched: bool) {
    unsafe {
        let bits = &mut *(&raw mut WATCHED);
        if bits.len() <= page / 64 {
            if !watched {
                return;
            }
            bits.resize(page / 64 + 1, 0);
        }
        if watched {
            bits[page / 64] |= 1 << (page % 64)
        }
        else {
            bits[page / 64] &= !(1 << (page % 64))
        }
    }
}
/// Whether this instance watches the page (no lock)
#[inline(always)]
pub fn bit(page: u32) -> bool {
    unsafe {
        (&*(&raw const WATCHED))
            .get(page as usize / 64)
            .is_some_and(|w| w >> (page % 64) & 1 != 0)
    }
}

impl Watch {
    pub fn new() -> Watch {
        Watch {
            slots: HashMap::new(),
            counts: Vec::new(),
            dirty: Vec::new(),
            reset: Vec::new(),
        }
    }
    pub fn on_dirty(&mut self, trigger: Trigger, listener: DirtyListener) {
        self.dirty.push((trigger, listener))
    }
    pub fn on_reset(&mut self, listener: ResetListener) { self.reset.push(listener) }

    pub fn watched(&self, page: Page) -> bool {
        self.counts
            .get(page.to_u32() as usize)
            .is_some_and(|count| *count != 0)
    }
    fn count(&mut self, page: Page, delta: i32) {
        let index = page.to_u32() as usize;
        if self.counts.len() <= index {
            self.counts.resize(index + 1, 0);
        }
        let before = self.counts[index] != 0;
        self.counts[index] = (self.counts[index] as i32 + delta).max(0) as u16;
        let after = self.counts[index] != 0;
        set_bit(index, after);
        if before != after {
            (env().claim)(index as u32, after);
        }
    }

    /// Slot `slot`'s code was made from `pages`
    pub fn attach(&mut self, slot: u32, pages: HashSet<Page>) {
        for &page in &pages {
            self.count(page, 1);
        }
        (env().pages_gain_code)(&pages);
        self.slots.insert(slot, pages);
    }
    /// Slot `slot` was released: its pages are no longer its
    pub fn detach(&mut self, slot: u32) {
        let Some(pages) = self.slots.remove(&slot)
        else {
            return;
        };
        for &page in &pages {
            self.count(page, -1);
        }
        for page in pages {
            let watched = self.watched(page);
            (env().page_has_code)(page, watched);
        }
    }

    /// A write to `page` (all of it, or the bytes lo..hi): every listener.
    /// False when this instance watches no code there.
    pub fn write(&mut self, page: Page, bytes: Option<(u32, u32)>) -> bool {
        for &(trigger, listener) in &self.dirty {
            if trigger == Trigger::Always {
                listener(page.to_u32(), bytes);
            }
        }
        self.retire(page, bytes)
    }
    /// A write to `page` that the Always listeners have heard of (another
    /// core's, reported back): the code this instance made from it retires.
    /// False when it watches no code there.
    pub fn retire(&mut self, page: Page, bytes: Option<(u32, u32)>) -> bool {
        if !self.watched(page) {
            return false;
        }
        let mut kept = Vec::new();
        for &(trigger, listener) in &self.dirty {
            if trigger == Trigger::WatchedOnly {
                kept.extend(listener(page.to_u32(), bytes));
            }
        }
        let mut unwatched = HashSet::new();
        let mut drained = Vec::new();
        for (&slot, pages) in self.slots.iter_mut() {
            if pages.contains(&page) && !kept.contains(&slot) {
                drained.extend(pages.drain());
            }
        }
        for p in drained {
            self.count(p, -1);
            unwatched.insert(p);
        }
        for page in unwatched {
            let watched = self.watched(page);
            (env().page_has_code)(page, watched);
        }
        true
    }

    /// Every client's code goes (crate::jit::jit_clear_cache_js): the
    /// listeners, then no page is watched
    pub fn reset(&mut self) {
        for listener in &self.reset {
            listener();
        }
        let mut pages = HashSet::new();
        for slot_pages in self.slots.values_mut() {
            pages.extend(slot_pages.drain());
        }
        self.counts.clear();
        unsafe { (*(&raw mut WATCHED)).clear() };
        (env().release_all)();
        for page in pages {
            (env().page_has_code)(page, false);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jitrt::host::{self, Env};
    use std::sync::Mutex;

    static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());
    fn log(s: String) { LOG.lock().unwrap().push(s) }
    fn take() -> Vec<String> { std::mem::take(&mut *LOG.lock().unwrap()) }

    fn env() -> Env {
        Env {
            table_size: 16,
            table_offset: 0,
            state_base: 0,
            mem8: || std::ptr::null_mut(),
            now: || 0.0,
            core: || 0,
            clear_slot: |_| {},
            page_has_code: |page, has| log(format!("has {} {}", page.to_u32(), has)),
            pages_gain_code: |pages| log(format!("gain {}", pages.len())),
            claim: |page, on| log(format!("claim {} {}", page, on)),
            release_all: || log("release all".into()),
        }
    }

    // (one test: the listeners and the log are shared)
    #[test]
    fn listener_order_kept_slots_and_reset() {
        host::set(env());
        let mut w = Watch::new();
        w.on_dirty(Trigger::Always, |page, _| {
            log(format!("always {}", page));
            vec![]
        });
        // (the client keeps slot 2's code for a write of a few bytes)
        w.on_dirty(Trigger::WatchedOnly, |page, bytes| {
            log(format!("client {} {:?}", page, bytes));
            if bytes.is_some() {
                vec![2]
            }
            else {
                vec![]
            }
        });
        w.on_reset(|| log("reset client".into()));
        w.attach(
            1,
            [Page::page_of(0x5000), Page::page_of(0x6000)]
                .into_iter()
                .collect(),
        );
        w.attach(2, [Page::page_of(0x5000)].into_iter().collect());
        let mut attached = take();
        attached.sort();
        assert_eq!(
            attached,
            ["claim 5 true", "claim 6 true", "gain 1", "gain 2"]
        );
        assert!(bit(5) && bit(6) && !bit(7));

        // an unwatched page: only the Always listener
        w.write(Page::page_of(0x7000), None);
        assert_eq!(take(), ["always 7"]);
        assert!(!w.retire(Page::page_of(0x7000), None));

        // a few bytes of page 5: slot 2 kept, slot 1 stops watching 5 and 6
        w.write(Page::page_of(0x5000), Some((8, 12)));
        let mut log = take();
        let mut retired = log.split_off(2);
        assert_eq!(log, ["always 5", "client 5 Some((8, 12))"]);
        retired.sort();
        assert_eq!(retired, ["claim 6 false", "has 5 true", "has 6 false"]);
        assert!(bit(5) && !bit(6));

        // all of page 5, reported back by another core: no Always listener
        assert!(w.retire(Page::page_of(0x5000), None));
        assert_eq!(take(), ["client 5 None", "claim 5 false", "has 5 false"]);
        assert!(!bit(5));

        w.attach(3, [Page::page_of(0x9000)].into_iter().collect());
        take();
        w.reset();
        assert_eq!(take(), ["reset client", "release all", "has 9 false"]);
        assert!(!bit(9));
        w.detach(3);
        assert_eq!(take(), Vec::<String>::new());
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/src/rust/js_api.rs                                                                       0000644 0000000 0000000 00000000270 00000000000 013262  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::cpu::cpu::translate_address_system_read;

#[no_mangle]
pub unsafe fn translate_address_system_read_js(addr: i32) -> u32 {
    translate_address_system_read(addr).unwrap()
}
                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/leb.rs                                                                          0000644 0000000 0000000 00000001427 00000000000 012564  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub fn write_leb_i32(buf: &mut Vec<u8>, v: i32) { write_leb_i64(buf, v as i64); }

pub fn write_leb_i64(buf: &mut Vec<u8>, mut v: i64) {
    // https://en.wikipedia.org/wiki/LEB128#Encode_signed_integer
    loop {
        let mut byte = v as u8 & 0b0111_1111;
        v >>= 7;
        let sign = byte & (1 << 6);
        let done = v == 0 && sign == 0 || v == -1 && sign != 0;
        if !done {
            byte |= 0b1000_0000;
        }
        buf.push(byte);
        if done {
            break;
        }
    }
}

pub fn write_leb_u32(buf: &mut Vec<u8>, mut v: u32) {
    loop {
        let mut byte = v as u8 & 0b0111_1111;
        v >>= 7;
        if v != 0 {
            byte |= 0b1000_0000;
        }
        buf.push(byte);
        if v == 0 {
            break;
        }
    }
}
                                                                                                                                                                                                                                         source/v64/src/rust/lib.rs                                                                          0000644 0000000 0000000 00000004623 00000000000 012571  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #[macro_use]
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod dbg;

// The state block each core declares its fields in (state!)
#[macro_use]
#[cfg_attr(feature = "aarch64", allow(unused_macros))]
mod state_block;

// The two cores (docs/arm64-virt-android16-plan.md, "Wasm core"): one crate,
// the x86 core by default and the ARM core with the feature aarch64. Only
// this file and src/rust/aarch64/ name the feature
// (tools/check_a64_imports.mjs); the shared modules reach the ISA as
// crate::isa, which names the core's hooks. (Until the ARM core has a code
// client, P6, it leaves most of the shared runtime unused.)
#[cfg(not(feature = "aarch64"))]
#[macro_use]
mod paging;

#[cfg(feature = "aarch64")]
pub mod aarch64;
#[cfg(not(feature = "aarch64"))]
pub mod cpu;
#[cfg(not(feature = "aarch64"))]
pub mod x64;

#[cfg(feature = "aarch64")]
use aarch64::isa_hooks as isa;
#[cfg(not(feature = "aarch64"))]
use cpu::isa_hooks as isa;

#[cfg(not(feature = "aarch64"))]
pub mod js_api;
pub mod parallel;
// guest RAM beyond the wasm32 backing store, both cores' (crate::x64::extended, crate::aarch64::extended)
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod extended;
// retired instructions and the other per-core counters of both cores
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod core_stats;
#[cfg(not(feature = "aarch64"))]
pub mod profiler;

#[cfg(not(feature = "aarch64"))]
mod config;
#[cfg(not(feature = "aarch64"))]
#[allow(dead_code)]
#[path = "decode/decode.rs"]
pub(crate) mod decode;
#[cfg(not(feature = "aarch64"))]
mod decode_rules;
#[cfg(not(feature = "aarch64"))]
mod gen;
#[cfg(not(feature = "aarch64"))]
mod jit;
#[cfg(not(feature = "aarch64"))]
mod jit_switches;
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod jitrt;
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod leb;
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod page;
// (the page tiers' neutral code generation: the A64 page tier is J2)
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod pagegen;
#[cfg(not(feature = "aarch64"))]
mod prefix;
#[cfg(all(test, not(feature = "aarch64")))]
#[path = "../../tests/decode/simd_corpus.rs"]
mod simd_corpus;
#[cfg(not(feature = "aarch64"))]
mod softfloat;
#[cfg(not(feature = "aarch64"))]
mod state_flags;
#[cfg(not(feature = "aarch64"))]
mod step_profile;
#[cfg_attr(feature = "aarch64", allow(dead_code))]
mod wasmgen;
#[cfg(not(feature = "aarch64"))]
mod x86tpl;
mod zstd;
                                                                                                             source/v64/src/rust/page.rs                                                                         0000644 0000000 0000000 00000000667 00000000000 012743  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use std::ops::RangeInclusive;

#[derive(Copy, Clone, Eq, Hash, PartialEq)]
pub struct Page(u32);
impl Page {
    pub fn page_of(address: u32) -> Page { Page(address >> 12) }
    pub fn to_address(self) -> u32 { self.0 << 12 }

    pub fn to_u32(self) -> u32 { self.0 }
    pub fn of_u32(page: u32) -> Page { Page(page) }

    pub fn address_range(self) -> RangeInclusive<u32> {
        self.to_address()..=self.to_address() + 4095
    }
}
                                                                         source/v64/src/rust/pagegen/frame.rs                                                                0000644 0000000 0000000 00000077522 00000000000 014533  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The neutral skeleton of a page function (docs/jit-unification-plan.md
//! P5.9): one Wasm function serves the compiled block starts of a guest code
//! page (or a span of consecutive pages). Its frame, from the outside in:
//!
//! - exit: the function's way out (the ISA writes its state back and
//!   returns the instructions retired)
//! - leave: the PC left the function's pages (the ISA may chain to the new
//!   page's function, P5.8)
//! - retry: a template refused before any of its effects (the runtime
//!   interprets the instruction)
//! - dispatch: a loop over the page's units, entered at the head (the
//!   budget) and the dispatch on the PC's offset (a table, or buckets of
//!   compares, PageEmitter::page_dispatch)
//! - step: the instruction at the PC is interpreted in place (jitrt::step),
//!   then the function dispatches again
//!
//! The units are the structured layout of the block graph (P4.16,
//! crate::pagegen::loops): each cycle a Wasm loop with its own head and
//! dispatch over its members, so back edges re-enter the loop, not the page
//! dispatch; `goto` continues at a later block of a level directly, at an
//! earlier one through its level's head. The skeleton also emits the access
//! cache lookups (jitrt::access, P4.14: the module's outlined lookup
//! function and the inline lookup) and the chaining lookup (jitrt::chain).
//! Flags, the PC's representation, the state's write-back, the single-step
//! context and the choice of the memory access path stay with the ISA
//! (crate::x64::pagegen for x86), which implements PageEmitter.
//!
//! Imports: std, crate::wasmgen, crate::leb, crate::jitrt and itself; no ISA
//! and no `feature = "aarch64"` (tools/check_x86tpl_imports.mjs).

use super::loops::{flatten, units, visit_loops, Unit, MAX_LOOP_TABLE, MAX_LOOP_TABLES};
use crate::jitrt::{access, chain};
use crate::wasmgen::wasm_builder::{
    Label, Signature, WasmBuilder, WasmLocal, WasmLocalI64, WasmType,
};
use crate::wasmgen::wasm_opcodes as op;
use std::collections::{BTreeMap, HashMap};

/// The function's labels (see the module's comment)
#[derive(Clone, Copy)]
pub struct Frame {
    pub exit: Label,
    /// the PC left the function's pages (normal exit): chain or return
    pub leave: Label,
    pub retry: Label,
    pub step: Label,
    pub dispatch: Label,
}

/// One level of a page function's structured layout (P4.16): the page's
/// units, or a loop's (each a block or a loop, in address order)
pub struct Level {
    /// re-enters the level: its loop's head (the page level: Frame::dispatch)
    pub repeat: Label,
    /// per block: its unit at this level, or u32::MAX
    pub unit_of: Vec<u32>,
    /// per unit: its label (the unit's code follows the label's end)
    pub labels: Vec<Label>,
    /// per unit: Some(block) for a single block
    pub single: Vec<Option<u32>>,
    /// the unit being emitted (those before it: emitted)
    pub current: usize,
    /// a loop of its header alone, whose head does not dispatch on the PC
    /// (PageEmitter::loop_unit): what continues at the PC goes further out
    pub direct: bool,
}
impl Level {
    /// The level of `units` (no labels yet), re-entered at `repeat`
    pub fn of(units: &[Unit], blocks: usize, repeat: Label) -> Level {
        let mut unit_of = vec![u32::MAX; blocks];
        let mut single = vec![];
        for (u, unit) in units.iter().enumerate() {
            let mut members = vec![];
            unit.blocks(&mut members);
            for k in members {
                unit_of[k as usize] = u as u32;
            }
            single.push(match unit {
                Unit::Block(k) => Some(*k),
                Unit::Loop { .. } => None,
            });
        }
        Level {
            repeat,
            unit_of,
            labels: vec![],
            single,
            current: 0,
            direct: false,
        }
    }
}

/// The offset of `target` in a function covering `span` bytes, if it is in it
pub fn in_page(span: u64, target: u64) -> Option<u16> { (target < span).then_some(target as u16) }

/// The structured layout of a page function (P4.16): each cycle of its
/// block graph a loop, nested (crate::pagegen::loops); with `loops` false
/// every block is a unit of the page level. `successors`: each block's
/// static successors in the function (its dynamic targets dispatch);
/// `start`: a block's offset. Loops whose dispatch table would span too much
/// of the page are flattened (MAX_LOOP_TABLE, and MAX_LOOP_TABLES for all).
pub fn structured(successors: &[Vec<u32>], start: &dyn Fn(u32) -> usize, loops: bool) -> Vec<Unit> {
    let blocks = successors.len() as u32;
    if !loops {
        return (0..blocks).map(Unit::Block).collect();
    }
    let all: Vec<u32> = (0..blocks).collect();
    let mut layout = units(&all, successors, None);
    let range = |unit: &Unit| {
        let mut members = vec![];
        unit.blocks(&mut members);
        members.iter().map(|&k| start(k)).max().unwrap() - start(unit.first()) + 1
    };
    flatten(&mut layout, &|unit| range(unit) > MAX_LOOP_TABLE);
    loop {
        let (mut total, mut widest) = (0, 0);
        visit_loops(&layout, &mut |unit| {
            total += range(unit);
            widest = widest.max(range(unit));
        });
        if total <= MAX_LOOP_TABLES {
            break;
        }
        flatten(&mut layout, &|unit| range(unit) == widest);
    }
    layout
}

/// Block starts in buckets of 2^DISPATCH_SHIFT bytes (DispatchKind::Buckets)
pub const DISPATCH_SHIFT: u32 = 4;
/// The widest span of block starts a DispatchKind::SpanTable covers
pub const SPAN_TABLE: usize = 1024;

/// How the page dispatches on the PC's offset
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum DispatchKind {
    /// a table over the span of the block starts (low..=high)
    SpanTable { low: u16, high: u16 },
    /// a table over 16-byte buckets of the page, then the block starts in
    /// the bucket compared (a page-sized table is most of a small function
    /// and slow to compile)
    Buckets,
    /// a table over every offset of the function's pages
    Full,
}

// ---- the access cache's lookups (jitrt::access; P4.14)

/// The access cache's side of a page function: the globals its lookups read
/// (addresses the composition root resolved) and the runtime's lookup
pub struct AccessAbi {
    /// The running core's epoch bits (u64): what tags hold above the page
    pub epoch: u32,
    /// The address (i32) of the read supervisor table of the activation's
    /// privilege (the module's lookup function reads it)
    pub base: u32,
    /// Entries per table
    pub entries: u32,
    /// The runtime's lookup on a miss: (address: i64, kind: i32) -> host
    /// (i32), 0 when refused; kind: the size, bit 8 a write, bit 9 a write
    /// whose code takes an unaligned host, bit 10 the second bounce slot
    pub slow: &'static str,
    /// (cores in workers) the buffer unaligned reads are copied to: 32
    /// bytes, or with kind bit 10 the next 32 (an access whose first
    /// lookup's copy must survive a second, the ARM core's pairs)
    pub bounce: u32,
}

/// The locals an inline lookup works in (the ISA's): the address and the
/// epoch bits (i64); scratch: the tag (i64), the table base, the entry, the
/// page offset and the host (i32)
pub struct LookupLocals {
    pub addr: WasmLocalI64,
    pub epoch: WasmLocalI64,
    pub tag: WasmLocalI64,
    pub tables: WasmLocal,
    pub entry: WasmLocal,
    pub offset: WasmLocal,
    pub host: WasmLocal,
}

/// The module's internal function (addr: i64, kind: i32) -> i32: the host
/// address for a `kind & 255`-byte access (bit 8: write) at virtual address
/// addr from the access cache, else the runtime's lookup; 0 when refused.
/// The same lookup PageEmitter::inline_lookup otherwise inlines.
pub fn lookup_function(b: &mut WasmBuilder, abi: &AccessAbi) -> u32 {
    use crate::leb::{write_leb_i32, write_leb_u32};
    // (write tables: 2 * entries * 16 bytes on)
    let write_shift = 15 + (abi.entries / 1024).trailing_zeros() as i32;
    debug_assert!(abi.entries.is_power_of_two() && access::ENTRY_BYTES == 16);
    let slow = b.import_index(
        abi.slow,
        Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
    );
    // locals: tag (i64), entry, offset, host, the bounce slot (i32)
    let mut c: Vec<u8> = vec![2, 1, op::TYPE_I64, 4, op::TYPE_I32];
    let i32c = |c: &mut Vec<u8>, v: i32| {
        c.push(op::OP_I32CONST);
        write_leb_i32(c, v);
    };
    // tag = addr >> 12 | epoch bits (local 2)
    c.extend_from_slice(&[op::OP_GETLOCAL, 0, op::OP_I64CONST, 12, op::OP_I64SHRU]);
    i32c(&mut c, abi.epoch as i32);
    c.extend_from_slice(&[op::OP_I64LOAD, 3, 0, op::OP_I64OR, op::OP_TEELOCAL, 2]);
    // entry = table base + (tag & (ENTRIES - 1)) * 16 (+ write tables) (local 3)
    c.push(op::OP_I32WRAPI64);
    i32c(&mut c, abi.entries as i32 - 1);
    c.push(op::OP_I32AND);
    i32c(&mut c, 4);
    c.push(op::OP_I32SHL);
    i32c(&mut c, abi.base as i32);
    c.extend_from_slice(&[op::OP_I32LOAD, 2, 0, op::OP_I32ADD, op::OP_GETLOCAL, 1]);
    i32c(&mut c, 8);
    c.push(op::OP_I32SHRU);
    i32c(&mut c, 1);
    c.push(op::OP_I32AND);
    i32c(&mut c, write_shift);
    c.extend_from_slice(&[op::OP_I32SHL, op::OP_I32ADD, op::OP_SETLOCAL, 3]);
    // offset in the page (local 4)
    c.extend_from_slice(&[op::OP_GETLOCAL, 0, op::OP_I32WRAPI64]);
    i32c(&mut c, 4095);
    c.extend_from_slice(&[op::OP_I32AND, op::OP_SETLOCAL, 4]);
    // hit: tag matches and the access stays in the page
    c.extend_from_slice(&[
        op::OP_GETLOCAL,
        3,
        op::OP_I64LOAD,
        3,
        0,
        op::OP_GETLOCAL,
        2,
        op::OP_I64EQ,
    ]);
    c.extend_from_slice(&[op::OP_GETLOCAL, 4]);
    i32c(&mut c, 4096);
    c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
    i32c(&mut c, 255);
    c.extend_from_slice(&[op::OP_I32AND, op::OP_I32SUB, op::OP_I32LEU, op::OP_I32AND]);
    c.extend_from_slice(&[op::OP_IF, op::TYPE_I32]);
    c.extend_from_slice(&[
        op::OP_GETLOCAL,
        3,
        op::OP_I32LOAD,
        2,
        8,
        op::OP_GETLOCAL,
        4,
        op::OP_I32ADD,
    ]);
    if WasmBuilder::ATOMIC_GUEST_MEMORY {
        // Cores in workers access guest memory with atomics, which need
        // natural alignment (min(size, 8)). An unaligned read is copied
        // with plain loads, then a fence (x86 orders it before later
        // loads), to an aligned buffer (pages::BOUNCE) the caller reads.
        // An unaligned write host is returned as it is when the caller
        // stores unaligned itself (kind bit 9: host_store), else the
        // slow path refuses it (retried).
        c.extend_from_slice(&[op::OP_TEELOCAL, 5, op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 8);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 8);
        c.extend_from_slice(&[op::OP_I32LTU, op::OP_SELECT]);
        i32c(&mut c, 1);
        c.extend_from_slice(&[op::OP_I32SUB, op::OP_I32AND, op::OP_IF, op::TYPE_I32]);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 0x100);
        c.extend_from_slice(&[op::OP_I32AND, op::OP_IF, op::TYPE_I32]);
        // (a write whose code handles unaligned hosts, bit 9: store)
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 0x200);
        c.extend_from_slice(&[
            op::OP_I32AND,
            op::OP_IF,
            op::TYPE_I32,
            op::OP_GETLOCAL,
            5,
            op::OP_ELSE,
        ]);
        c.extend_from_slice(&[op::OP_GETLOCAL, 0, op::OP_GETLOCAL, 1, op::OP_CALL]);
        write_leb_u32(&mut c, slow);
        c.push(op::OP_END);
        c.push(op::OP_ELSE);
        // (the slot: bounce, or with kind bit 10 bounce + 32; local 6)
        i32c(&mut c, abi.bounce as i32);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 5);
        c.push(op::OP_I32SHRU);
        i32c(&mut c, 32);
        c.push(op::OP_I32AND);
        c.extend_from_slice(&[op::OP_I32ADD, op::OP_SETLOCAL, 6]);
        // (sizes 2, 4, 8, 16, 32: the first 8 bytes or fewer, then the
        // rest; 32: a VEX.256 load's)
        let copy = |c: &mut Vec<u8>, load: u8, store: u8, align: u8, offset: u32| {
            c.extend_from_slice(&[op::OP_GETLOCAL, 6]);
            c.extend_from_slice(&[op::OP_GETLOCAL, 5, load, 0]);
            write_leb_u32(c, offset);
            c.extend_from_slice(&[store, align]);
            write_leb_u32(c, offset);
        };
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 4);
        c.extend_from_slice(&[op::OP_I32LTU, op::OP_IF, op::TYPE_VOID_BLOCK]);
        copy(&mut c, op::OP_I32LOAD16U, op::OP_I32STORE16, 1, 0);
        c.push(op::OP_ELSE);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 4);
        c.extend_from_slice(&[op::OP_I32EQ, op::OP_IF, op::TYPE_VOID_BLOCK]);
        copy(&mut c, op::OP_I32LOAD, op::OP_I32STORE, 2, 0);
        c.push(op::OP_ELSE);
        copy(&mut c, op::OP_I64LOAD, op::OP_I64STORE, 3, 0);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 16);
        c.extend_from_slice(&[op::OP_I32GEU, op::OP_IF, op::TYPE_VOID_BLOCK]);
        copy(&mut c, op::OP_I64LOAD, op::OP_I64STORE, 3, 8);
        c.extend_from_slice(&[op::OP_END]);
        c.extend_from_slice(&[op::OP_GETLOCAL, 1]);
        i32c(&mut c, 255);
        c.push(op::OP_I32AND);
        i32c(&mut c, 32);
        c.extend_from_slice(&[op::OP_I32EQ, op::OP_IF, op::TYPE_VOID_BLOCK]);
        copy(&mut c, op::OP_I64LOAD, op::OP_I64STORE, 3, 16);
        copy(&mut c, op::OP_I64LOAD, op::OP_I64STORE, 3, 24);
        c.extend_from_slice(&[op::OP_END, op::OP_END, op::OP_END]);
        c.extend_from_slice(&[0xFE, 0x03, 0x00]); // atomic.fence
        c.extend_from_slice(&[op::OP_GETLOCAL, 6]);
        c.extend_from_slice(&[op::OP_END, op::OP_ELSE, op::OP_GETLOCAL, 5, op::OP_END]);
    }
    c.extend_from_slice(&[
        op::OP_ELSE,
        op::OP_GETLOCAL,
        0,
        op::OP_GETLOCAL,
        1,
        op::OP_CALL,
    ]);
    write_leb_u32(&mut c, slow);
    c.extend_from_slice(&[op::OP_END, op::OP_END]);
    b.add_internal_function(
        Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
        c,
    )
}

// ---- chaining (jitrt::chain)

/// Where a chaining lookup takes the epoch bits from
pub enum ChainEpoch<'l> {
    Global(u32),
    Local(&'l WasmLocalI64),
}

/// The chaining lookup of the page of the PC in `pc` (i64) in the table
/// whose address is in global `table_base` (i32), `tag` (i64) and `entry`
/// (i32) scratch: it opens an `if` taken when the entry is the page's in the
/// current epoch, in which the ISA writes its state back and calls
/// chain_call, then closes it
pub fn chain_lookup(
    b: &mut WasmBuilder,
    pc: &WasmLocalI64,
    tag: &WasmLocalI64,
    entry: &WasmLocal,
    table_base: u32,
    epoch: ChainEpoch,
) {
    b.get_local_i64(pc);
    b.const_i64(12);
    b.shr_u_i64();
    b.set_local_i64(tag);
    b.get_local_i64(tag);
    b.wrap_i64_to_i32();
    b.const_i32(chain::ENTRIES as i32 - 1);
    b.and_i32();
    b.const_i32(chain::ENTRY_BYTES.trailing_zeros() as i32);
    b.shl_i32();
    b.load_fixed_i32(table_base);
    b.add_i32();
    b.set_local(entry);
    b.get_local(entry);
    b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
    b.get_local_i64(tag);
    match epoch {
        ChainEpoch::Global(address) => {
            b.const_i32(address as i32);
            b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
        },
        ChainEpoch::Local(local) => b.get_local_i64(local),
    }
    b.or_i64();
    b.eq_i64();
    b.if_void();
}
/// The tail call to the entry's function (the budget, its argument, pushed)
pub fn chain_call(b: &mut WasmBuilder, entry: &WasmLocal) {
    b.get_local(entry);
    b.load_aligned_i32(chain::TABLE_INDEX_OFFSET);
    b.return_call_indirect_fn1();
}

/// What the skeleton needs of an ISA's emitter, and what it provides
pub trait PageEmitter {
    fn b(&mut self) -> &mut WasmBuilder;
    fn frame(&self) -> Frame;
    fn set_frame(&mut self, frame: Frame);
    fn levels(&mut self) -> &mut Vec<Level>;
    fn levels_ref(&self) -> &[Level];
    /// The bytes the function's offsets cover
    fn span_bytes(&self) -> u64;
    /// Push the i32 offset of the PC in the function's pages
    fn pc_offset(&mut self);
    /// The i32 local the dispatches keep an offset in: tee it, get it
    fn tee_offset(&mut self);
    fn get_offset(&mut self);
    /// The head of the page's and each loop's dispatch: count a round and
    /// leave (Frame::exit) when the budget is spent
    fn head(&mut self);
    /// Emit block `k`
    fn emit_block(&mut self, k: u32, index: &BTreeMap<u16, usize>);
    /// Block `k`'s offset
    fn block_start(&self, k: u32) -> u16;
    /// Branch to `label` with the PC at offset `target` (and what the label
    /// expects in memory)
    fn leave_to(&mut self, label: Label, target: u64);
    /// Before a branch straight into a block's code: what blocks expect in
    /// memory at their start
    fn before_branch(&mut self);
    /// Control passes to `target` in the function's pages (a function of
    /// several pages checks the page)
    fn span_check(&mut self, target: u64);
    /// A loop of its header alone is entered and repeated at the header,
    /// without a dispatch on the PC
    fn direct_loops(&self) -> bool;

    // the frame's ISA parts, in the order the function has them
    /// After the exit block opened: checks of the function's entry that leave
    fn entry_checks(&mut self, _exit: Label) {}
    /// After the page's head: the PC out of the function's pages leaves
    fn bounds(&mut self, leave: Label);
    /// The PC is no compiled block start (Frame::step or Frame::exit)
    fn unknown_offset(&mut self);
    /// Before the units' code
    fn before_units(&mut self) {}
    /// The step block's code: interpret one instruction, dispatch again
    fn step_tail(&mut self);
    /// The retry block's code
    fn retry_tail(&mut self);
    /// The leave block's code (chaining)
    fn leave_tail(&mut self);
    /// The exit block's code, the function's last
    fn exit_tail(&mut self);
    /// (the statistics of where the bytes go)
    fn note_size(&mut self, _what: &str, _bytes: usize) {}
    /// The module's lookup function (lookup_function; made once, the ISA
    /// keeps its index)
    fn lookup_function(&mut self) -> u32;

    /// Push the host address of a `size`-byte access at the address in
    /// `l.addr` through the module's lookup function, with its kind `bits`;
    /// refused: leave for `fallback` with the PC at offset `start`
    fn outlined_lookup(
        &mut self,
        l: &LookupLocals,
        size: u32,
        bits: u32,
        start: u64,
        fallback: Label,
    ) {
        let f = self.lookup_function();
        self.b().get_local_i64(&l.addr);
        self.b().const_i32((size | bits) as i32);
        self.b().call_internal(f);
        self.b().tee_local(&l.host);
        self.b().eqz_i32();
        self.b().if_void();
        self.leave_to(fallback, start);
        self.b().block_end();
        self.b().get_local(&l.host);
    }
    /// The same, inline: the entry's tag compared, the access in the page
    /// (unless `aligned` to its size), naturally aligned with cores in
    /// workers; a miss calls the runtime (with cores in workers the module's
    /// lookup, which takes unaligned accesses the runtime refuses)
    fn inline_lookup(
        &mut self,
        l: &LookupLocals,
        abi: &AccessAbi,
        (size, aligned): (u32, bool),
        bits: u32,
        start: u64,
        fallback: Label,
    ) {
        let write = bits & 0x100 != 0;
        let table = if write { 2 * abi.entries * access::ENTRY_BYTES } else { 0 };
        let b = self.b();
        b.get_local_i64(&l.addr);
        b.const_i64(12);
        b.shr_u_i64();
        b.get_local_i64(&l.epoch);
        b.or_i64();
        b.set_local_i64(&l.tag);
        b.get_local_i64(&l.tag);
        b.wrap_i64_to_i32();
        b.const_i32(abi.entries as i32 - 1);
        b.and_i32();
        b.const_i32(access::ENTRY_BYTES.trailing_zeros() as i32);
        b.shl_i32();
        b.get_local(&l.tables);
        b.add_i32();
        b.set_local(&l.entry);
        b.get_local_i64(&l.addr);
        b.wrap_i64_to_i32();
        b.const_i32(4095);
        b.and_i32();
        b.set_local(&l.offset);
        b.get_local(&l.entry);
        b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, table);
        b.get_local_i64(&l.tag);
        b.eq_i64();
        if !aligned {
            b.get_local(&l.offset);
            b.const_i32((4096 - size) as i32);
            b.leu_i32();
            b.and_i32();
        }
        if WasmBuilder::ATOMIC_GUEST_MEMORY && size > 1 && !aligned {
            // atomic accesses (cores in workers) need natural alignment; the
            // runtime's lookup refuses unaligned ones
            b.get_local(&l.offset);
            b.const_i32(size.min(8) as i32 - 1);
            b.and_i32();
            b.eqz_i32();
            b.and_i32();
        }
        b.hint(true);
        b.if_i32();
        b.get_local(&l.entry);
        b.load_aligned_i32(table + 8);
        b.get_local(&l.offset);
        b.add_i32();
        b.else_();
        b.get_local_i64(&l.addr);
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            let f = self.lookup_function();
            self.b().const_i32((size | bits) as i32);
            self.b().call_internal(f);
        }
        else {
            let b = self.b();
            b.const_i32(size as i32 | (write as i32) << 8);
            b.call_signature(
                abi.slow,
                Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
            );
        }
        self.b().tee_local(&l.host);
        self.b().eqz_i32();
        self.b().if_void();
        self.leave_to(fallback, start);
        self.b().block_end();
        self.b().get_local(&l.host);
        self.b().block_end();
    }

    /// The function's body from the frame's blocks on (the ISA emitted its
    /// prologue): `units` the structured layout of its `blocks`, `index`
    /// block starts to blocks
    fn page(
        &mut self,
        units: &[Unit],
        blocks: usize,
        index: &BTreeMap<u16, usize>,
        kind: DispatchKind,
    ) {
        let exit = self.b().block_void();
        self.entry_checks(exit);
        let leave = self.b().block_void();
        let retry = self.b().block_void();
        let dispatch = self.b().loop_void();
        let step = self.b().block_void();
        self.set_frame(Frame {
            exit,
            leave,
            retry,
            step,
            dispatch,
        });
        // Budget (native instructions and steps), then the page.
        self.head();
        self.bounds(leave);
        // The structured layout (P4.16): the page level's units, each with
        // its label; a block in a loop dispatches to the loop's
        let mut level = Level::of(units, blocks, dispatch);
        level.labels = units.iter().map(|_| self.b().block_void()).collect();
        level.labels.reverse();
        let bad = self.b().block_void();
        let mark = self.b().body_len();
        self.page_dispatch(index, &level, bad, kind);
        let bytes = self.b().body_len() - mark;
        self.note_size("[dispatch br_table]", bytes);
        self.b().block_end();
        // Not a block start (the ISA steps it in place, or leaves)
        self.unknown_offset();
        self.levels().push(level);
        self.before_units();
        self.units(units, index);
        let mark = self.b().body_len();
        self.b().unreachable();
        self.b().block_end(); // step
        self.step_tail();
        self.b().block_end(); // dispatch loop
        self.b().unreachable();
        self.b().block_end(); // retry
        self.retry_tail();
        self.b().block_end(); // leave
        self.leave_tail();
        self.b().block_end(); // exit
        self.exit_tail();
        let bytes = self.b().body_len() - mark;
        self.note_size("[step, retry, chain, exit]", bytes);
    }

    /// The page level's dispatch on the PC's offset to the units' labels
    /// (`bad`: no block start there)
    fn page_dispatch(
        &mut self,
        index: &BTreeMap<u16, usize>,
        level: &Level,
        bad: Label,
        kind: DispatchKind,
    ) {
        let label_of = |level: &Level, i: usize| level.labels[level.unit_of[i] as usize];
        match kind {
            DispatchKind::SpanTable { low, high } => {
                self.pc_offset();
                if low != 0 {
                    self.b().const_i32(low as i32);
                    self.b().sub_i32();
                }
                let targets: Vec<Label> = (low..=high)
                    .map(|o| index.get(&o).map_or(bad, |&i| label_of(level, i)))
                    .collect();
                self.b().brtable(bad, &mut targets.iter());
            },
            DispatchKind::Buckets => {
                let mut buckets: BTreeMap<u16, Vec<(u16, usize)>> = BTreeMap::new();
                for (&o, &i) in index {
                    buckets.entry(o >> DISPATCH_SHIFT).or_default().push((o, i));
                }
                let order: Vec<u16> = buckets.keys().copied().collect();
                let mut bucket_labels: HashMap<u16, Label> = HashMap::new();
                for &b in order.iter().rev() {
                    let label = self.b().block_void();
                    bucket_labels.insert(b, label);
                }
                self.pc_offset();
                self.tee_offset();
                self.b().const_i32(DISPATCH_SHIFT as i32);
                self.b().shr_u_i32();
                let targets: Vec<Label> = (0..(self.span_bytes() >> DISPATCH_SHIFT) as u16)
                    .map(|b| bucket_labels.get(&b).copied().unwrap_or(bad))
                    .collect();
                self.b().brtable(bad, &mut targets.iter());
                for b in order {
                    self.b().block_end();
                    for &(o, i) in &buckets[&b] {
                        self.get_offset();
                        self.b().const_i32(o as i32);
                        self.b().eq_i32();
                        self.b().br_if(label_of(level, i));
                    }
                    self.b().br(bad);
                }
            },
            DispatchKind::Full => {
                self.pc_offset();
                let targets: Vec<Label> = (0..self.span_bytes() as u32)
                    .map(|o| index.get(&(o as u16)).map_or(bad, |&i| label_of(level, i)))
                    .collect();
                self.b().brtable(bad, &mut targets.iter());
            },
        }
    }

    /// Continue at offset `target`: a later block of this function directly,
    /// an earlier one through dispatch (and its budget check), else leave.
    fn goto(&mut self, target: u64, index: &BTreeMap<u16, usize>) {
        let Some(o) = in_page(self.span_bytes(), target)
        else {
            return self.leave_to(self.frame().leave, target);
        };
        self.span_check(target);
        let Some(&k) = index.get(&o)
        else {
            return self.leave_to(self.frame().dispatch, target);
        };
        let Some((emitted, single, label, repeat)) = self.unit_holding(k)
        else {
            return self.leave_to(self.frame().dispatch, target);
        };
        if emitted {
            return self.leave_to(repeat, target);
        }
        if single == Some(k as u32) {
            self.before_branch();
            return self.b().br(label);
        }
        self.leave_to(label, target)
    }
    /// Block `k`'s unit at the innermost level holding it: whether it was
    /// emitted (at or before the one being emitted), the block if the unit
    /// is that one alone, the unit's label and the level's head. A unit
    /// after the one being emitted is reached by its label (a single block
    /// directly), an emitted one by the level's head, which dispatches on
    /// the PC (P4.16; the page level: Frame::dispatch).
    fn unit_holding(&self, k: usize) -> Option<(bool, Option<u32>, Label, Label)> {
        let level = self
            .levels_ref()
            .iter()
            .rev()
            .find(|level| level.unit_of[k] != u32::MAX)?;
        let u = level.unit_of[k] as usize;
        Some((
            u <= level.current,
            level.single[u],
            level.labels[u],
            level.repeat,
        ))
    }
    /// The label that continues straight into the code of the block at `o`
    /// from here, with the PC already there (goto's direct case: a later
    /// single block of its level; the caller checks the span's page)
    fn direct_label(&self, o: u16, index: &BTreeMap<u16, usize>) -> Option<Label> {
        let &k = index.get(&o)?;
        match self.unit_holding(k)? {
            (false, Some(single), label, _) if single == k as u32 => Some(label),
            _ => None,
        }
    }
    /// Whether the block at `o` is the next unit of the innermost level, a
    /// single block, whose code follows (no branch needed)
    fn falls_into(&self, o: u16, index: &BTreeMap<u16, usize>) -> bool {
        let level = self.levels_ref().last().unwrap();
        index
            .get(&o)
            .is_some_and(|&k| level.single.get(level.current + 1) == Some(&Some(k as u32)))
    }
    /// The units of a level, after its labels and dispatch: each one's code
    /// after its label's end
    fn units(&mut self, units: &[Unit], index: &BTreeMap<u16, usize>) {
        for (u, unit) in units.iter().enumerate() {
            self.b().block_end();
            self.levels().last_mut().unwrap().current = u;
            match unit {
                Unit::Block(k) => self.emit_block(*k, index),
                Unit::Loop { header, units } => self.loop_unit(*header, units, index),
            }
        }
    }
    /// A loop (P4.16): its head (budget) and a dispatch on the PC over its
    /// members, the header first; an offset it does not hold goes to the
    /// page dispatch. Back edges re-enter the head instead of the page
    /// dispatch.
    fn loop_unit(&mut self, header: u32, units: &[Unit], index: &BTreeMap<u16, usize>) {
        let repeat = self.b().loop_void();
        self.head();
        let blocks = self.levels_ref()[0].unit_of.len();
        let mut level = Level::of(units, blocks, repeat);
        level.labels = units.iter().map(|_| self.b().block_void()).collect();
        level.labels.reverse();
        let mut members = vec![];
        for unit in units {
            unit.blocks(&mut members);
        }
        let (low, high) = (
            members.iter().map(|&k| self.block_start(k)).min().unwrap(),
            members.iter().map(|&k| self.block_start(k)).max().unwrap(),
        );
        // (a loop of its header alone is entered and repeated at it: no
        // dispatch on the PC each iteration)
        if self.direct_loops() && members.len() == 1 && units.len() == 1 {
            level.direct = true;
            self.levels().push(level);
            self.units(units, index);
            self.levels().pop();
            self.b().block_end();
            return;
        }
        self.pc_offset();
        self.tee_offset();
        let start = self.block_start(header);
        self.b().const_i32(start as i32);
        self.b().eq_i32();
        self.b().br_if(level.labels[0]);
        let dispatch = self.frame().dispatch;
        let table: Vec<Label> = (low..=high)
            .map(|o| match index.get(&o) {
                Some(&k) if level.unit_of[k] != u32::MAX => level.labels[level.unit_of[k] as usize],
                _ => dispatch,
            })
            .collect();
        self.get_offset();
        if low != 0 {
            self.b().const_i32(low as i32);
            self.b().sub_i32();
        }
        self.b().brtable(dispatch, &mut table.iter());
        self.levels().push(level);
        self.units(units, index);
        self.levels().pop();
        self.b().block_end();
    }
}
                                                                                                                                                                              source/v64/src/rust/pagegen/loops.rs                                                                0000644 0000000 0000000 00000012162 00000000000 014562  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The loop structure of a page function (docs/jit-unification-plan.md:
//! from IR Tier-0's page analysis, ir::tier0::analysis until P7.5 deleted
//! Tier-0): each cycle of the block graph (a strongly connected set) is a
//! Wasm loop whose first block, its header, is the member with the lowest
//! address; nested cycles (those left after removing the edges into the
//! header) nest.

/// A page function's blocks in address order, cycles as loops
pub enum Unit {
    Block(u32),
    Loop { header: u32, units: Vec<Unit> },
}
impl Unit {
    pub fn blocks(&self, out: &mut Vec<u32>) {
        match self {
            Unit::Block(k) => out.push(*k),
            Unit::Loop { units, .. } => units.iter().for_each(|u| u.blocks(out)),
        }
    }
    pub fn first(&self) -> u32 {
        match self {
            Unit::Block(k) => *k,
            Unit::Loop { header, .. } => *header,
        }
    }
}

/// Loop dispatch table bounds: per loop, and for all loops of a function
/// (frame::structured; V8 compiles functions with very large tables slowly or
/// not at all, its per-function zone limit)
pub(crate) const MAX_LOOP_TABLE: usize = 1024;
pub(crate) const MAX_LOOP_TABLES: usize = 8192;
pub(crate) fn visit_loops(units: &[Unit], f: &mut dyn FnMut(&Unit)) {
    for unit in units {
        if let Unit::Loop { units, .. } = unit {
            f(unit);
            visit_loops(units, f);
        }
    }
}
/// Replace the loops matching `wide` by their units (in address order).
pub(crate) fn flatten(units: &mut Vec<Unit>, wide: &dyn Fn(&Unit) -> bool) {
    let mut out = Vec::with_capacity(units.len());
    for unit in std::mem::take(units) {
        let flat = matches!(unit, Unit::Loop { .. }) && wide(&unit);
        match unit {
            Unit::Loop {
                header,
                units: mut inner,
            } => {
                flatten(&mut inner, wide);
                if flat {
                    out.extend(inner);
                }
                else {
                    out.push(Unit::Loop {
                        header,
                        units: inner,
                    });
                }
            },
            unit => out.push(unit),
        }
    }
    out.sort_by_key(Unit::first);
    *units = out;
}

/// Units of `members` (sorted), ignoring edges into `header`.
pub(crate) fn units(members: &[u32], successors: &[Vec<u32>], header: Option<u32>) -> Vec<Unit> {
    let n = successors.len();
    let mut member = vec![false; n];
    for &k in members {
        member[k as usize] = true;
    }
    let edges = |k: u32| -> Vec<u32> {
        successors[k as usize]
            .iter()
            .copied()
            .filter(|&t| member[t as usize] && Some(t) != header)
            .collect()
    };
    // Tarjan's strongly connected components.
    let mut index = vec![u32::MAX; n];
    let mut low = vec![0u32; n];
    let mut on_stack = vec![false; n];
    let mut stack = vec![];
    let mut next = 0;
    let mut components: Vec<Vec<u32>> = vec![];
    for &root in members {
        if index[root as usize] != u32::MAX {
            continue;
        }
        // Iterative DFS: (block, successor position).
        let mut work = vec![(root, 0usize)];
        index[root as usize] = next;
        low[root as usize] = next;
        next += 1;
        stack.push(root);
        on_stack[root as usize] = true;
        while let Some(&mut (v, ref mut position)) = work.last_mut() {
            let targets = edges(v);
            if let Some(&w) = targets.get(*position) {
                *position += 1;
                if index[w as usize] == u32::MAX {
                    index[w as usize] = next;
                    low[w as usize] = next;
                    next += 1;
                    stack.push(w);
                    on_stack[w as usize] = true;
                    work.push((w, 0));
                }
                else if on_stack[w as usize] {
                    low[v as usize] = low[v as usize].min(index[w as usize]);
                }
                continue;
            }
            work.pop();
            if let Some(&(parent, _)) = work.last() {
                low[parent as usize] = low[parent as usize].min(low[v as usize]);
            }
            if low[v as usize] == index[v as usize] {
                let mut component = vec![];
                loop {
                    let w = stack.pop().unwrap();
                    on_stack[w as usize] = false;
                    component.push(w);
                    if w == v {
                        break;
                    }
                }
                component.sort_unstable();
                components.push(component);
            }
        }
    }
    let mut result: Vec<Unit> = components
        .into_iter()
        .map(|component| {
            let k = component[0];
            if component.len() == 1 && !edges(k).contains(&k) {
                Unit::Block(k)
            }
            else {
                Unit::Loop {
                    header: k,
                    units: units(&component, successors, Some(k)),
                }
            }
        })
        .collect();
    result.sort_by_key(Unit::first);
    result
}
                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/src/rust/pagegen/mod.rs                                                                  0000644 0000000 0000000 00000000505 00000000000 014203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The page tiers' code generation, ISA-neutral (docs/jit-unification-plan.md
//! P5.9): the skeleton of a page function (frame) and the loop structure of
//! its block graph (loops). The ISAs' modules emit their instructions into
//! it: crate::x64::pagegen for x86; the A64 page tier is J2.

pub mod frame;
pub mod loops;
                                                                                                                                                                                           source/v64/src/rust/paging.rs                                                                       0000644 0000000 0000000 00000000737 00000000000 013272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub type OrPageFault<T> = Result<T, ()>;

macro_rules! return_on_pagefault {
    ($expr:expr) => {
        match $expr {
            Ok(v) => v,
            Err(()) => return,
        }
    };
    ($expr:expr, $ret:expr) => {
        match $expr {
            Ok(v) => v,
            Err(()) => return $ret,
        }
    };
}

macro_rules! break_on_pagefault {
    ($expr:expr) => {
        match $expr {
            Ok(v) => v,
            Err(()) => break,
        }
    };
}
                                 source/v64/src/rust/parallel.rs                                                                     0000644 0000000 0000000 00000106225 00000000000 013620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Host-parallel execution (docs/multicore.md).
//!
//! build/v86-parallel.wasm runs one instance per vCPU in one shared memory
//! (src/parallel/relocate.js). The machine instance, at base 0, runs the
//! bootstrap processor and owns the devices; each application processor runs
//! in a worker with its own relocated copy of the module. A static therefore
//! belongs to one instance, unless it is reached through `machine()`, which
//! maps a static of this instance to the same static of the machine instance:
//! the local APICs, the IOAPIC, the INIT/SIPI/NMI latches, the physical bus
//! and the code page counts are machine state accessed that way.
//!
//! Guest RAM is shared. In the parallel build every aligned access to it is a
//! sequentially consistent atomic (x86 TSO needs ordered loads and stores on
//! weakly ordered hosts), read-modify-write instructions commit with a
//! compare-exchange, and unaligned accesses are fenced on both sides. The
//! normal build compiles these helpers to plain memory accesses.

use std::ptr;
#[cfg(feature = "parallel")]
use std::sync::atomic::{fence, AtomicU16, AtomicU32, AtomicU64, AtomicU8, Ordering::SeqCst};

pub const MAX_CORES: usize = crate::isa::MAX_CORES;

#[cfg(feature = "parallel")]
mod js {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn parallel_notify(address: u32);
    }
}

/// Address at which this instance's static data starts relative to the
/// machine instance (0 in the machine instance)
static mut INSTANCE_BASE: u32 = 0;
/// Set while the machine runs cores in workers: in every instance
static mut ACTIVE: bool = false;

/// Whether this is the machine instance (the BSP and the devices)
pub fn machine_instance() -> bool {
    #[cfg(feature = "parallel")]
    {
        unsafe { INSTANCE_BASE == 0 }
    }
    #[cfg(not(feature = "parallel"))]
    {
        true
    }
}

/// The machine instance's copy of a static of this instance
#[inline(always)]
pub fn machine<T>(p: *mut T) -> *mut T {
    #[cfg(feature = "parallel")]
    {
        (p as u32).wrapping_sub(unsafe { INSTANCE_BASE }) as *mut T
    }
    #[cfg(not(feature = "parallel"))]
    {
        p
    }
}

/// The machine instance's copy of a field of this instance's CPU state block
/// (crate::state_block): the state blocks are in slots below the static
/// data, one per core (src/parallel/relocate.js), the machine's in slot 0
#[inline(always)]
pub fn machine_state<T>(p: *mut T) -> *mut T {
    #[cfg(feature = "parallel")]
    {
        (p as u32).wrapping_sub(crate::state_block::state_base()) as *mut T
    }
    #[cfg(not(feature = "parallel"))]
    {
        p
    }
}

/// Whether other cores may run concurrently in other workers
#[inline(always)]
pub fn active() -> bool {
    #[cfg(feature = "parallel")]
    {
        unsafe { ACTIVE }
    }
    #[cfg(not(feature = "parallel"))]
    {
        false
    }
}

/// This instance runs one application processor in a worker
#[inline(always)]
pub fn is_worker() -> bool { cfg!(feature = "parallel") && unsafe { INSTANCE_BASE } != 0 }

// Machine-wide words of the parallel runtime (accessed through machine()):
// the wake-up sequence each core waits on while halted, and where each core's
// yield flag is (the instance-private cpu::core_yield of its worker).
static mut CORE_WAKE: [u32; MAX_CORES] = [0; MAX_CORES];
static mut CORE_YIELD: [u32; MAX_CORES] = [0; MAX_CORES];

/// Address of the word a halted core waits on (Atomics.wait in its worker)
#[no_mangle]
pub unsafe fn parallel_wake_addr(core: u32) -> u32 {
    assert!((core as usize) < MAX_CORES);
    machine(&raw mut CORE_WAKE).cast::<u32>().add(core as usize) as u32
}

/// Make a core notice new work soon: leave its current slice and, if it
/// waits, wake up. Called after an interrupt, INIT/SIPI or a request was
/// posted for it. Harmless for the core that calls it.
/// Kicks by all cores (diagnostics: parallel_kick_count)
static mut KICKS: u32 = 0;
#[no_mangle]
pub unsafe fn parallel_kick_count() -> u32 { *machine(&raw mut KICKS) }
pub unsafe fn kick(core: usize) {
    #[cfg(feature = "parallel")]
    {
        if !ACTIVE || core >= MAX_CORES {
            return;
        }
        (*(machine(&raw mut KICKS) as *const AtomicU32)).fetch_add(1, SeqCst);
        let flag = *machine(&raw mut CORE_YIELD).cast::<u32>().add(core);
        if flag != 0 {
            (*(flag as *const AtomicU8)).store(1, SeqCst);
        }
        let wake = machine(&raw mut CORE_WAKE).cast::<u32>().add(core);
        (*(wake as *const AtomicU32)).fetch_add(1, SeqCst);
        // (memory.atomic.notify is not available to stable Rust: Atomics.notify)
        js::parallel_notify(wake as u32);
    }
    #[cfg(not(feature = "parallel"))]
    let _ = core;
}

#[no_mangle]
pub unsafe fn parallel_kick(core: u32) { kick(core as usize) }

/// The machine instance starts or stops running cores in workers
#[no_mangle]
pub unsafe fn parallel_set_active(active: bool) {
    assert!(cfg!(feature = "parallel") || !active);
    ACTIVE = active;
    if active {
        let yield_flags = machine(&raw mut CORE_YIELD).cast::<u32>();
        *yield_flags.add(crate::isa::current_core()) = crate::isa::core_yield_address();
        if !is_worker() {
            crate::isa::machine_set_active();
        }
    }
}

/// Attach this relocated instance to the machine: `base` is where its static
/// data was placed, `core` the application processor it runs. RAM, the
/// machine configuration and the machine-shared state are the ones of the
/// machine instance from now on.
#[no_mangle]
pub unsafe fn parallel_attach(base: u32, core: u32) {
    assert!(cfg!(feature = "parallel"));
    assert!(base != 0 && (core as usize) < MAX_CORES && core != 0);
    INSTANCE_BASE = base;
    ACTIVE = true;
    crate::isa::attach_worker(core);
    let yield_flags = machine(&raw mut CORE_YIELD).cast::<u32>();
    *yield_flags.add(core as usize) = crate::isa::core_yield_address();
}

/// After a stop of all cores: the machine may have changed its physical bus
/// windows or ACPI mode while this worker was parked
#[no_mangle]
pub unsafe fn parallel_sync() {
    if is_worker() {
        crate::isa::sync_worker();
        sync_worker_configuration();
    }
}

/// Machine configuration that may change while the cores run (ACPI enable,
/// the CPU profile, TSEG): copied into a worker at the start of each of its
/// slices
pub unsafe fn sync_worker_configuration() {
    if is_worker() {
        crate::isa::sync_worker_configuration();
    }
}

/// A lock in machine memory. Critical sections are short (one IOAPIC or
/// local APIC operation) and never wait for another core. The word holds the
/// owner's core number + 1: when a worker fails, parallel_fail releases the
/// locks its core held, so the other cores do not spin forever.
#[repr(transparent)]
pub struct SpinLock(u32);
impl SpinLock {
    pub const fn new() -> Self { SpinLock(0) }
    #[inline(always)]
    pub fn lock(&self) {
        #[cfg(feature = "parallel")]
        {
            let word = unsafe { &*(&raw const self.0 as *const AtomicU32) };
            let owner = crate::isa::current_core() as u32 + 1;
            while word
                .compare_exchange_weak(0, owner, SeqCst, SeqCst)
                .is_err()
            {
                std::hint::spin_loop();
            }
        }
    }
    #[inline(always)]
    pub fn unlock(&self) {
        #[cfg(feature = "parallel")]
        {
            let word = unsafe { &*(&raw const self.0 as *const AtomicU32) };
            word.store(0, SeqCst);
        }
    }
    /// Whether `core` holds the lock
    pub fn held_by(&self, core: usize) -> bool {
        #[cfg(feature = "parallel")]
        {
            let word = unsafe { &*(&raw const self.0 as *const AtomicU32) };
            word.load(SeqCst) == core as u32 + 1
        }
        #[cfg(not(feature = "parallel"))]
        {
            let _ = core;
            false
        }
    }
    /// Release the lock if `core` holds it
    pub fn release_held_by(&self, core: usize) {
        #[cfg(feature = "parallel")]
        {
            let word = unsafe { &*(&raw const self.0 as *const AtomicU32) };
            let _ = word.compare_exchange(core as u32 + 1, 0, SeqCst, SeqCst);
        }
        #[cfg(not(feature = "parallel"))]
        let _ = core;
    }
}

/// This instance's core failed: its worker caught an error (a trap or an
/// exception of the JS side) and stops. Release the machine's locks the core
/// held and count it as idle, so that the other cores neither spin on its
/// locks nor wait for it to acknowledge code publications. The machine then
/// stops (src/parallel/machine.js).
#[no_mangle]
pub unsafe fn parallel_fail() { release_core(crate::isa::current_core()) }

/// The machine found a core's worker failed or gone (the same as
/// parallel_fail, in case the worker could not run it)
#[no_mangle]
pub unsafe fn parallel_core_failed(core: u32) {
    assert!((core as usize) < MAX_CORES);
    release_core(core as usize)
}

unsafe fn release_core(core: usize) {
    if !active() {
        return;
    }
    #[cfg(feature = "parallel")]
    if split_lock().held_by(core) {
        // (an exclusive locked operation of this core stopped halfway)
        locked_operations().fetch_and(!EXCLUSIVE, SeqCst);
    }
    split_lock().release_held_by(core);
    crate::isa::release_locks_held_by(core);
    code::set_idle(core, true);
}

/// Test hook (tests/parallel/lifecycle.mjs): trap inside the critical
/// sections, as a failing core could
#[no_mangle]
pub unsafe fn parallel_test_fault() {
    split_lock().lock();
    crate::isa::lock_for_test_fault();
    #[cfg(target_arch = "wasm32")]
    std::arch::wasm32::unreachable();
    #[cfg(not(target_arch = "wasm32"))]
    unreachable!("parallel_test_fault");
}

// Guest RAM accesses (host pointers into mem8). Naturally aligned accesses
// are single-copy atomic and sequentially consistent in the parallel build;
// the others are fenced on both sides, which keeps their order with respect
// to every other access (x86 does not make them atomic either).

#[inline(always)]
pub unsafe fn load8(p: *const u8) -> u8 {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU8)).load(SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p
    }
}
#[inline(always)]
pub unsafe fn load16(p: *const u8) -> u16 {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 1 == 0 {
            return (*(p as *const AtomicU16)).load(SeqCst);
        }
        fence(SeqCst);
        let value = ptr::read_unaligned(p as *const u16);
        fence(SeqCst);
        value
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::read_unaligned(p as *const u16)
    }
}
#[inline(always)]
pub unsafe fn load32(p: *const u8) -> u32 {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 3 == 0 {
            return (*(p as *const AtomicU32)).load(SeqCst);
        }
        fence(SeqCst);
        let value = ptr::read_unaligned(p as *const u32);
        fence(SeqCst);
        value
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::read_unaligned(p as *const u32)
    }
}
#[inline(always)]
pub unsafe fn load64(p: *const u8) -> u64 {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 7 == 0 {
            return (*(p as *const AtomicU64)).load(SeqCst);
        }
        fence(SeqCst);
        let value = ptr::read_unaligned(p as *const u64);
        fence(SeqCst);
        value
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::read_unaligned(p as *const u64)
    }
}
/// 16 bytes: two ordered 8-byte halves (SSE accesses are not atomic as a whole)
#[inline(always)]
pub unsafe fn load128(p: *const u8) -> [u64; 2] { [load64(p), load64(p.add(8))] }

#[inline(always)]
pub unsafe fn store8(p: *mut u8, value: u8) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU8)).store(value, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p = value
    }
}
#[inline(always)]
pub unsafe fn store16(p: *mut u8, value: u16) {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 1 == 0 {
            return (*(p as *const AtomicU16)).store(value, SeqCst);
        }
        fence(SeqCst);
        ptr::write_unaligned(p as *mut u16, value);
        fence(SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::write_unaligned(p as *mut u16, value)
    }
}
#[inline(always)]
pub unsafe fn store32(p: *mut u8, value: u32) {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 3 == 0 {
            return (*(p as *const AtomicU32)).store(value, SeqCst);
        }
        fence(SeqCst);
        ptr::write_unaligned(p as *mut u32, value);
        fence(SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::write_unaligned(p as *mut u32, value)
    }
}
#[inline(always)]
pub unsafe fn store64(p: *mut u8, value: u64) {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 7 == 0 {
            return (*(p as *const AtomicU64)).store(value, SeqCst);
        }
        fence(SeqCst);
        ptr::write_unaligned(p as *mut u64, value);
        fence(SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        ptr::write_unaligned(p as *mut u64, value)
    }
}
#[inline(always)]
pub unsafe fn store128(p: *mut u8, value: [u64; 2]) {
    store64(p, value[0]);
    store64(p.add(8), value[1]);
}

/// A full barrier (MFENCE, locked instructions around non-atomic bulk
/// copies); nothing in the normal build
#[inline(always)]
pub fn full_fence() {
    #[cfg(feature = "parallel")]
    fence(SeqCst);
}

/// CMPXCHG16B: no 16-byte atomic exists. It runs exclusively (no other
/// locked operation commits meanwhile) and commits each half with a
/// compare-exchange, so that a plain store to either half in between makes
/// it fail (and the instruction run again) instead of being lost.
pub unsafe fn compare_exchange128(p: *mut u8, expected: u128, value: u128) -> bool {
    #[cfg(not(feature = "parallel"))]
    {
        let equal = ptr::read_unaligned(p as *const u128) == expected;
        if equal {
            ptr::write_unaligned(p as *mut u128, value);
        }
        equal
    }
    #[cfg(feature = "parallel")]
    exclusive(|| {
        let (old_low, old_high) = (expected as u64, (expected >> 64) as u64);
        let (new_low, new_high) = (value as u64, (value >> 64) as u64);
        if p as usize & 7 != 0 {
            // (not for CMPXCHG16B, which requires 16-byte alignment)
            let equal = ptr::read_unaligned(p as *const u128) == expected;
            if equal {
                ptr::write_unaligned(p as *mut u128, value);
            }
            return equal;
        }
        let low = &*(p as *const AtomicU64);
        let high = &*(p.add(8) as *const AtomicU64);
        if high.load(SeqCst) != old_high
            || low
                .compare_exchange(old_low, new_low, SeqCst, SeqCst)
                .is_err()
        {
            return false;
        }
        if high
            .compare_exchange(old_high, new_high, SeqCst, SeqCst)
            .is_err()
        {
            // (if a plain store replaced the low half meanwhile, it stays)
            let _ = low.compare_exchange(new_low, old_low, SeqCst, SeqCst);
            return false;
        }
        true
    })
}

/// Locked operations that no single host atomic covers (unaligned, split,
/// 16 bytes) run exclusively; the aligned ones commit with one atomic
/// compare-exchange while holding a share, so that neither interleaves with
/// the other on the same bytes. Bit 31: an exclusive operation holds it (or
/// waits for the shares to drain); below: aligned operations committing.
#[cfg(feature = "parallel")]
static mut LOCKED_OPERATIONS: u32 = 0;
#[cfg(feature = "parallel")]
const EXCLUSIVE: u32 = 1 << 31;
#[cfg(feature = "parallel")]
fn locked_operations() -> &'static AtomicU32 {
    unsafe { &*(machine(&raw mut LOCKED_OPERATIONS) as *const AtomicU32) }
}
#[cfg(feature = "parallel")]
#[inline(always)]
fn shared<T>(commit: impl FnOnce() -> T) -> T {
    let word = locked_operations();
    loop {
        let current = word.load(SeqCst);
        if current & EXCLUSIVE == 0
            && word
                .compare_exchange_weak(current, current + 1, SeqCst, SeqCst)
                .is_ok()
        {
            break;
        }
        std::hint::spin_loop();
    }
    let result = commit();
    word.fetch_sub(1, SeqCst);
    result
}
#[cfg(feature = "parallel")]
fn exclusive<T>(operation: impl FnOnce() -> T) -> T {
    split_lock().lock();
    let word = locked_operations();
    word.fetch_or(EXCLUSIVE, SeqCst);
    while word.load(SeqCst) & !EXCLUSIVE != 0 {
        std::hint::spin_loop();
    }
    let result = operation();
    word.fetch_and(!EXCLUSIVE, SeqCst);
    split_lock().unlock();
    result
}

/// Replace `expected` by `value` at `p` if it is still there. Unaligned or
/// split operands run exclusively (see `exclusive`): atomic with respect to
/// other locked operations, not to plain stores (a bus lock has no equivalent
/// here). Always succeeds in the normal build.
#[inline(always)]
pub unsafe fn compare_exchange(p: *mut u8, bytes: u32, expected: u64, value: u64) -> bool {
    #[cfg(feature = "parallel")]
    {
        let aligned = p as usize & (bytes as usize - 1) == 0;
        if aligned {
            return shared(|| match bytes {
                1 => (*(p as *const AtomicU8))
                    .compare_exchange(expected as u8, value as u8, SeqCst, SeqCst)
                    .is_ok(),
                2 => (*(p as *const AtomicU16))
                    .compare_exchange(expected as u16, value as u16, SeqCst, SeqCst)
                    .is_ok(),
                4 => (*(p as *const AtomicU32))
                    .compare_exchange(expected as u32, value as u32, SeqCst, SeqCst)
                    .is_ok(),
                _ => (*(p as *const AtomicU64))
                    .compare_exchange(expected, value, SeqCst, SeqCst)
                    .is_ok(),
            });
        }
        exclusive(|| {
            let current = match bytes {
                2 => ptr::read_unaligned(p as *const u16) as u64,
                4 => ptr::read_unaligned(p as *const u32) as u64,
                _ => ptr::read_unaligned(p as *const u64),
            };
            let equal = current == expected;
            if equal {
                match bytes {
                    2 => ptr::write_unaligned(p as *mut u16, value as u16),
                    4 => ptr::write_unaligned(p as *mut u32, value as u32),
                    _ => ptr::write_unaligned(p as *mut u64, value),
                }
            }
            equal
        })
    }
    #[cfg(not(feature = "parallel"))]
    {
        let _ = expected;
        match bytes {
            1 => *p = value as u8,
            2 => ptr::write_unaligned(p as *mut u16, value as u16),
            4 => ptr::write_unaligned(p as *mut u32, value as u32),
            _ => ptr::write_unaligned(p as *mut u64, value),
        }
        true
    }
}

static mut SPLIT_LOCK: SpinLock = SpinLock::new();
/// Serializes locked operations that no single atomic instruction covers
/// (split or unaligned operands, CMPXCHG16B)
pub fn split_lock() -> &'static SpinLock { unsafe { &*machine(&raw mut SPLIT_LOCK) } }

/// Set bits of a guest page table entry (accessed/dirty): other cores may
/// update the same entry at the same time
#[inline(always)]
pub unsafe fn or8(p: *mut u8, bits: u8) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU8)).fetch_or(bits, SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p |= bits
    }
}
#[inline(always)]
pub unsafe fn or32(p: *mut u8, bits: u32) {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 3 == 0 {
            (*(p as *const AtomicU32)).fetch_or(bits, SeqCst);
            return;
        }
    }
    store32(p, load32(p) | bits)
}
#[inline(always)]
pub unsafe fn or64(p: *mut u8, bits: u64) {
    #[cfg(feature = "parallel")]
    {
        if p as usize & 7 == 0 {
            (*(p as *const AtomicU64)).fetch_or(bits, SeqCst);
            return;
        }
    }
    store64(p, load64(p) | bits)
}

/// Add to a machine-shared word: its previous value (a ring's next
/// sequence number, the ARM core's TLB maintenance, P8.3)
#[inline(always)]
pub unsafe fn fetch_add32(p: *mut u32, value: u32) -> u32 {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).fetch_add(value, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        let previous = *p;
        *p = previous.wrapping_add(value);
        previous
    }
}

/// The larger of a machine-shared doubleword and `value`, which it becomes
/// (the ARM core's system counter, P8.2)
#[inline(always)]
pub unsafe fn max64(p: *mut u64, value: u64) -> u64 {
    #[cfg(feature = "parallel")]
    {
        let previous = (*(p as *const AtomicU64)).fetch_max(value, SeqCst);
        previous.max(value)
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p = (*p).max(value);
        *p
    }
}

/// Swap a machine-shared doubleword (device memory's marks, P8.2)
#[inline(always)]
pub unsafe fn swap64(p: *mut u64, value: u64) -> u64 {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU64)).swap(value, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        std::mem::replace(&mut *p, value)
    }
}

/// Atomic bit operations on machine-shared words (APIC registers)
#[inline(always)]
pub unsafe fn word_or(p: *mut u32, bits: u32) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).fetch_or(bits, SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p |= bits
    }
}
#[inline(always)]
pub unsafe fn word_and(p: *mut u32, bits: u32) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).fetch_and(bits, SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p &= bits
    }
}
#[inline(always)]
pub unsafe fn word_load(p: *const u32) -> u32 {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).load(SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p
    }
}
#[inline(always)]
pub unsafe fn word_store(p: *mut u32, value: u32) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).store(value, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p = value
    }
}
#[inline(always)]
pub unsafe fn word_swap(p: *mut u32, value: u32) -> u32 {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU32)).swap(value, SeqCst)
    }
    #[cfg(not(feature = "parallel"))]
    {
        std::mem::replace(&mut *p, value)
    }
}

/// Coherence of compiled code between cores in workers. Each worker
/// compiles from guest RAM on its own; a store by any core to a page another
/// core compiled from must retire that code.
///
/// - OWNERS: one byte per backing page, a bit per core whose instance holds
///   code (or a cached write barrier) compiled from the page.
/// - A core that starts watching a page (jit::ir_page_count 0 -> 1) claims
///   it and publishes it on the publication ring. Every other core, at its
///   next safe point (`poll`), marks its translations of the page so that
///   stores take the slow path, and acknowledges. The claiming core installs
///   the code only when every other core has acknowledged or is idle
///   (`published`), then validates the source bytes once more: a store that
///   bypassed the mark happened before the acknowledgement, and the
///   validation sees it. (Store then check, and publish then read, are
///   ordered by the sequentially consistent accesses on both sides.)
/// - A store that reaches the slow path for a page other cores own posts the
///   page on the invalidation ring; their next `poll` retires their code.
///   Until then they may still run the old code: x86 requires a serializing
///   instruction on the executing core first, and CPUID and interrupt
///   delivery poll.
pub mod code {
    use super::*;
    #[allow(unused_imports)]
    use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::SeqCst};

    const PUBLISH_RING: usize = 1024;
    const INVALIDATE_RING: usize = 4096;

    // machine state (through machine())
    static mut OWNERS: *mut u8 = ptr::null_mut();
    static mut OWNER_PAGES: u32 = 0;
    static mut PUBLISH_NEXT: u32 = 0;
    static mut PUBLISHED: [u64; PUBLISH_RING] = [0; PUBLISH_RING];
    static mut INVALIDATE_NEXT: u32 = 0;
    static mut INVALIDATED: [u64; INVALIDATE_RING] = [0; INVALIDATE_RING];
    static mut ACKED: [u32; MAX_CORES] = [0; MAX_CORES];
    static mut IDLE: [u32; MAX_CORES] = [0; MAX_CORES];
    // this instance
    static mut REFUSED: u32 = 0; // installations given up: other cores had not acknowledged in time
    static mut PUBLISH_SEEN: u32 = 0;
    static mut INVALIDATE_SEEN: u32 = 0;
    static mut CLAIMED: Vec<u32> = Vec::new(); // publication sequence per page, 0: none

    unsafe fn me() -> usize { crate::isa::current_core() }
    /// For generated code that leaves for poll() when other cores published
    /// or invalidated code (x64 page functions chaining): the machine's
    /// PUBLISH_NEXT, this instance's PUBLISH_SEEN, the machine's
    /// INVALIDATE_NEXT and this instance's INVALIDATE_SEEN
    pub unsafe fn pending_addresses() -> [u32; 4] {
        [
            machine(&raw mut PUBLISH_NEXT) as u32,
            &raw mut PUBLISH_SEEN as u32,
            machine(&raw mut INVALIDATE_NEXT) as u32,
            &raw mut INVALIDATE_SEEN as u32,
        ]
    }
    unsafe fn owner(page: u32) -> *mut u8 {
        let owners = *machine(&raw mut OWNERS);
        if owners.is_null() || page >= *machine(&raw mut OWNER_PAGES) {
            return ptr::null_mut();
        }
        owners.add(page as usize)
    }

    /// The machine instance: RAM pages to track (all cores stopped)
    pub unsafe fn allocate(pages: u32) {
        if (*(&raw mut OWNERS)).is_null() || OWNER_PAGES < pages {
            let owners = vec![0u8; pages as usize].leak();
            OWNERS = owners.as_mut_ptr();
            OWNER_PAGES = pages;
        }
        reset();
    }
    /// Machine reset or snapshot restore (all cores stopped): no code anywhere
    #[no_mangle]
    pub unsafe fn parallel_code_reset() { reset() }
    unsafe fn reset() {
        if !(*machine(&raw mut OWNERS)).is_null() {
            ptr::write_bytes(
                *machine(&raw mut OWNERS),
                0,
                *machine(&raw mut OWNER_PAGES) as usize,
            );
        }
    }

    /// jit_clear_cache: this instance has no code any more
    pub unsafe fn release_all() {
        if !active() {
            return;
        }
        let claimed = &mut *(&raw mut CLAIMED);
        for (page, seq) in claimed.iter_mut().enumerate() {
            if *seq != 0 {
                *seq = 0;
                let at = owner(page as u32);
                if !at.is_null() {
                    and8(at, !(1 << me()));
                }
            }
        }
    }

    /// Whether another core has code from this backing page: its stores need
    /// the slow path (TLB fills, write translation caches)
    #[inline]
    pub unsafe fn others_own(page: u32) -> bool {
        if !active() {
            return false;
        }
        let at = owner(page);
        !at.is_null() && load8(at) & !(1u8 << me()) != 0
    }

    /// This core now has code from `page`
    pub unsafe fn claim(page: u32) {
        if !active() {
            return;
        }
        let at = owner(page);
        if at.is_null() {
            return;
        }
        or8(at, 1 << me());
        let seq = append(
            machine(&raw mut PUBLISH_NEXT),
            machine(&raw mut PUBLISHED).cast(),
            PUBLISH_RING,
            page,
        );
        let claimed = &mut *(&raw mut CLAIMED);
        if claimed.len() <= page as usize {
            claimed.resize(page as usize + 1, 0);
        }
        claimed[page as usize] = seq;
        for core in 0..crate::isa::core_count() {
            if core != me() {
                kick(core);
            }
        }
    }
    /// This core has no code from `page` any more
    pub unsafe fn release(page: u32) {
        if !active() {
            return;
        }
        let at = owner(page);
        if !at.is_null() {
            and8(at, !(1 << me()));
        }
        if let Some(seq) = (&mut *(&raw mut CLAIMED)).get_mut(page as usize) {
            *seq = 0;
        }
    }

    /// A write reached `page` through the slow path (or a device wrote it):
    /// retire other cores' code from it
    pub unsafe fn written(page: u32) {
        if !active() {
            return;
        }
        let at = owner(page);
        if at.is_null() {
            return;
        }
        let others = load8(at) & !(1u8 << me());
        if others == 0 {
            return;
        }
        append(
            machine(&raw mut INVALIDATE_NEXT),
            machine(&raw mut INVALIDATED).cast(),
            INVALIDATE_RING,
            page,
        );
        for core in 0..MAX_CORES {
            if others & 1 << core != 0 {
                kick(core);
            }
        }
    }

    /// Whether every other core has marked the pages this core published
    /// (the latest claim of each), so that code compiled from them may run
    pub unsafe fn published(pages: impl Iterator<Item = u32>) -> bool {
        if !active() {
            return true;
        }
        let claimed = &*(&raw const CLAIMED);
        let mut needed = 0u32;
        for page in pages {
            match claimed.get(page as usize) {
                Some(&seq) if seq != 0 => {
                    if (seq.wrapping_sub(needed) as i32) > 0 {
                        needed = seq;
                    }
                },
                // not claimed (no RAM page, or claimed and released again): no code may depend on it
                _ => {
                    if !owner(page).is_null() {
                        return false;
                    }
                },
            }
        }
        if needed == 0 {
            return true;
        }
        let acked = machine(&raw mut ACKED).cast::<u32>();
        let idle = machine(&raw mut IDLE).cast::<u32>();
        for core in 0..crate::isa::core_count() {
            if core == me() {
                continue;
            }
            if word_load(idle.add(core)) != 0 {
                continue;
            }
            if (word_load(acked.add(core)).wrapping_sub(needed) as i32) < 0 {
                return false;
            }
        }
        true
    }

    /// Wait up to `ms` for `published`; count a refusal when it stays false.
    /// The machine clock stands still while the machine is paused, and an
    /// asynchronous installation can complete then (with the other cores
    /// parked), so the wait is bounded by a number of checks as well.
    pub unsafe fn wait_published(pages: impl Iterator<Item = u32> + Clone, ms: f64) -> bool {
        if published(pages.clone()) {
            return true;
        }
        let deadline = crate::isa::microtick() + ms;
        for _ in 0..MAX_PUBLICATION_CHECKS {
            if published(pages.clone()) {
                return true;
            }
            if crate::isa::microtick() >= deadline {
                break;
            }
        }
        REFUSED = REFUSED.wrapping_add(1);
        false
    }
    /// (a few milliseconds of checks at most)
    const MAX_PUBLICATION_CHECKS: u32 = 1 << 14;

    /// Diagnostics: 0 installations this core gave up because other cores
    /// had not acknowledged its pages in time, 1 publications, 2
    /// invalidations posted by all cores
    #[no_mangle]
    pub unsafe fn parallel_code_stat(kind: u32) -> u32 {
        match kind {
            0 => REFUSED,
            1 => *machine(&raw mut PUBLISH_NEXT),
            _ => *machine(&raw mut INVALIDATE_NEXT),
        }
    }

    /// This core waits (halted, parked, not started) or runs again. A waking
    /// core polls before it executes anything.
    #[no_mangle]
    pub unsafe fn parallel_idle(idle: bool) {
        if !active() {
            return;
        }
        set_idle(me(), idle);
        if !idle {
            poll();
        }
    }
    pub unsafe fn set_idle(core: usize, idle: bool) {
        word_store(machine(&raw mut IDLE).cast::<u32>().add(core), idle as u32);
    }
    /// Whether `core` waits (halted, parked, not started): it polls before it runs again
    pub unsafe fn is_idle(core: usize) -> bool {
        word_load(machine(&raw mut IDLE).cast::<u32>().add(core)) != 0
    }

    /// Take other cores' publications and invalidations: at safe points
    #[no_mangle]
    pub unsafe fn parallel_poll() { poll() }
    pub unsafe fn poll() {
        if !active() {
            return;
        }
        let publications = (*(machine(&raw mut PUBLISH_NEXT) as *const AtomicU32)).load(SeqCst);
        let invalidations = (*(machine(&raw mut INVALIDATE_NEXT) as *const AtomicU32)).load(SeqCst);
        if publications == PUBLISH_SEEN && invalidations == INVALIDATE_SEEN {
            return;
        }
        // publications: mark this core's translations of the pages
        let mut pages = Vec::new();
        let overflow = drain(
            machine(&raw mut PUBLISH_NEXT),
            machine(&raw mut PUBLISHED).cast(),
            PUBLISH_RING,
            &raw mut PUBLISH_SEEN,
            &mut pages,
        );
        crate::isa::others_published(&pages, overflow);
        word_store(
            machine(&raw mut ACKED).cast::<u32>().add(me()),
            PUBLISH_SEEN,
        );
        // invalidations: retire this core's code from the pages
        pages.clear();
        let overflow = drain(
            machine(&raw mut INVALIDATE_NEXT),
            machine(&raw mut INVALIDATED).cast(),
            INVALIDATE_RING,
            &raw mut INVALIDATE_SEEN,
            &mut pages,
        );
        crate::isa::others_wrote(pages, overflow);
    }

    unsafe fn append(next: *mut u32, ring: *mut u64, size: usize, page: u32) -> u32 {
        let seq = (*(next as *const AtomicU32))
            .fetch_add(1, SeqCst)
            .wrapping_add(1);
        let slot = ring.add(seq as usize % size);
        (*(slot as *const AtomicU64)).store((seq as u64) << 32 | page as u64, SeqCst);
        seq
    }
    /// The entries after `*seen`; true if some were overwritten before they were read
    unsafe fn drain(
        next: *mut u32,
        ring: *mut u64,
        size: usize,
        seen: *mut u32,
        out: &mut Vec<u32>,
    ) -> bool {
        let current = (*(next as *const AtomicU32)).load(SeqCst);
        let first = *seen;
        *seen = current;
        let count = current.wrapping_sub(first);
        if count == 0 {
            return false;
        }
        if count as usize > size {
            return true;
        }
        for i in 1..=count {
            let seq = first.wrapping_add(i);
            let slot = ring.add(seq as usize % size);
            loop {
                let entry = (*(slot as *const AtomicU64)).load(SeqCst);
                let tag = (entry >> 32) as u32;
                if tag == seq {
                    out.push(entry as u32);
                    break;
                }
                if (tag.wrapping_sub(seq) as i32) > 0 {
                    return true; // overwritten by a later round of the ring
                }
                // the writer reserved this sequence number and stores the entry next
                std::hint::spin_loop();
            }
        }
        false
    }
}

#[inline(always)]
pub unsafe fn and8(p: *mut u8, bits: u8) {
    #[cfg(feature = "parallel")]
    {
        (*(p as *const AtomicU8)).fetch_and(bits, SeqCst);
    }
    #[cfg(not(feature = "parallel"))]
    {
        *p &= bits
    }
}
                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/rust/prefix.rs                                                                       0000644 0000000 0000000 00000000717 00000000000 013320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub const PREFIX_REPZ: u8 = 0b01000;
pub const PREFIX_REPNZ: u8 = 0b10000;

pub const PREFIX_MASK_OPSIZE: u8 = 0b100000;
pub const PREFIX_MASK_ADDRSIZE: u8 = 0b1000000;
pub const PREFIX_LOCK: u8 = 0b10000000;

pub const PREFIX_66: u8 = PREFIX_MASK_OPSIZE;
pub const PREFIX_67: u8 = PREFIX_MASK_ADDRSIZE;
pub const PREFIX_F2: u8 = PREFIX_REPNZ;
pub const PREFIX_F3: u8 = PREFIX_REPZ;

pub const SEG_PREFIX_ZERO: u8 = 7;

pub const PREFIX_MASK_SEGMENT: u8 = 0b111;
                                                 source/v64/src/rust/profiler.rs                                                                     0000644 0000000 0000000 00000002354 00000000000 013644  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Keep in sync with print_stats.js.
#[allow(non_camel_case_types)]
pub enum stat {
    RUN_INTERPRETED,
    RUN_INTERPRETED_STEPS,

    DIRTY_PAGE_DID_NOT_HAVE_CODE,

    PAGE_FAULT,
    TLB_MISS,

    MAIN_LOOP,
    MAIN_LOOP_IDLE,
    DO_MANY_CYCLES,
    CYCLE_INTERNAL,

    CLEAR_TLB,
    FULL_CLEAR_TLB,
    TLB_FULL,
    TLB_GLOBAL_FULL,

    // the path of an F80 add, sub, mul or div (src/rust/softfloat.rs): exact
    // in binary64, SoftFloat, native f64 (fast math)
    X87_EXACT,
    X87_SOFTFLOAT,
    X87_NATIVE_F64,
}

#[allow(non_upper_case_globals)]
pub static mut stat_array: [u64; 500] = [0; 500];

pub fn stat_increment(stat: stat) { stat_increment_by(stat, 1); }

pub fn stat_increment_by(stat: stat, by: u64) {
    if cfg!(feature = "profiler") {
        unsafe { stat_array[stat as usize] += by }
    }
}

#[no_mangle]
pub fn profiler_init() {
    unsafe {
        #[allow(static_mut_refs)]
        for x in stat_array.iter_mut() {
            *x = 0
        }
    }
}

#[no_mangle]
pub fn profiler_stat_get(stat: stat) -> f64 {
    if cfg!(feature = "profiler") {
        unsafe { stat_array[stat as usize] as f64 }
    }
    else {
        0.0
    }
}

#[no_mangle]
pub fn profiler_is_enabled() -> bool { cfg!(feature = "profiler") }
                                                                                                                                                                                                                                                                                    source/v64/src/rust/softfloat.rs                                                                    0000644 0000000 0000000 00000073643 00000000000 014034  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       extern "C" {
    fn extF80M_add(x: *const F80, y: *const F80, ptr: *mut F80);
    fn extF80M_sub(x: *const F80, y: *const F80, ptr: *mut F80);
    fn extF80M_mul(x: *const F80, y: *const F80, ptr: *mut F80);
    fn extF80M_div(x: *const F80, y: *const F80, ptr: *mut F80);
    //fn extF80M_rem(x: *const F80, y: *const F80, ptr: *mut F80);
    fn extF80M_sqrt(x: *const F80, ptr: *mut F80);

    fn extF80M_roundToInt(x: *const F80, rounding_mode: u8, raise_inexact: bool, dst: *mut F80);

    fn extF80M_eq(x: *const F80, y: *const F80) -> bool;
    //fn extF80M_eq_signaling(x: *const F80, y: *const F80) -> bool;

    //fn extF80M_le(x: *const F80, y: *const F80) -> bool;
    //fn extF80M_le_quiet(x: *const F80, y: *const F80) -> bool;
    fn extF80M_lt(x: *const F80, y: *const F80) -> bool;
    fn extF80M_lt_quiet(x: *const F80, y: *const F80) -> bool;

    fn extF80M_to_i32(src: *const F80, rounding_mode: u8, raise_inexact: bool) -> i32;
    fn extF80M_to_i64(src: *const F80, rounding_mode: u8, raise_inexact: bool) -> i64;
    #[allow(dead_code)] // Reference entry point used by differential tests.
    fn i32_to_extF80M(src: i32, dst: *mut F80);
    #[allow(dead_code)] // Reference entry point used by differential tests.
    fn i64_to_extF80M(src: i64, dst: *mut F80);

    fn f32_to_extF80M(src: i32, dst: *mut F80);
    fn f64_to_extF80M(src: u64, dst: *mut F80);
    fn extF80M_to_f32(src: *const F80) -> i32;
    fn extF80M_to_f64(src: *const F80) -> u64;

    static mut softfloat_roundingMode: u8;
    static mut extF80_roundingPrecision: u8;
    static mut softfloat_exceptionFlags: u8;
}

pub enum RoundingMode {
    NearEven,
    Trunc,
    Floor,
    Ceil,
}

// Host execution policy, deliberately outside the serialized guest FPU state.
// CPU.init selects the browser/API option; standalone arithmetic tests start
// in compatible mode. Changing this helper policy does not invalidate JIT code.
static mut X87_FAST_MATH: bool = false;
// The CPU derives its generated-code x87 policy from this flag (see cpu::fpu).
static mut X87_POLICY_OBSERVER: Option<unsafe fn()> = None;

#[no_mangle]
pub unsafe fn set_x87_fast_math(enabled: bool) {
    X87_FAST_MATH = enabled;
    if let Some(observer) = X87_POLICY_OBSERVER {
        observer();
    }
}
pub unsafe fn set_x87_policy_observer(observer: unsafe fn()) {
    X87_POLICY_OBSERVER = Some(observer);
}

/// The host arithmetic policy: native f64 (set_x87_fast_math) or compatible
#[inline(always)]
pub fn x87_fast_math() -> bool { unsafe { X87_FAST_MATH } }

#[no_mangle]
pub fn get_x87_fast_math() -> bool { x87_fast_math() }

/// The path an F80 operation took, in the profiler's statistics (the
/// profiler feature only; tests/rust/x87_fast_path.mjs)
#[inline(always)]
pub fn count_x87_path(path: crate::profiler::stat) { crate::profiler::stat_increment(path); }

pub enum Precision {
    P80,
    P64,
    P32,
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct F80 {
    pub mantissa: u64,
    pub sign_exponent: u16,
}
impl F80 {
    pub const ZERO: F80 = F80 {
        mantissa: 0,
        sign_exponent: 0,
    };
    pub const ONE: F80 = F80 {
        mantissa: 0x8000000000000000,
        sign_exponent: 0x3FFF,
    };
    pub const LN_10: F80 = F80 {
        mantissa: 0x935D8DDDAAA8B000,
        sign_exponent: 0x4000,
    };
    pub const LN_2: F80 = F80 {
        mantissa: 0xB17217F7D1CF7800,
        sign_exponent: 0x3FFE,
    };
    pub const PI: F80 = F80 {
        mantissa: 0xC90FDAA22168C000,
        sign_exponent: 0x4000,
    };
    pub const LOG2_E: F80 = F80 {
        mantissa: 0xB8AA3B295C17F000,
        sign_exponent: 0x3FFF,
    };
    pub const INDEFINITE_NAN: F80 = F80 {
        mantissa: 0xC000000000000000,
        sign_exponent: 0x7FFF,
    };
    pub const POS_INFINITY: F80 = F80 {
        mantissa: 0x8000000000000000,
        sign_exponent: 0x7FFF,
    };
    pub const NEG_INFINITY: F80 = F80 {
        mantissa: 0x8000000000000000,
        sign_exponent: 0xFFFF,
    };

    pub fn sign(&self) -> bool { (self.sign_exponent >> 15) == 1 }
    pub fn exponent(&self) -> i16 { (self.sign_exponent as i16 & 0x7FFF) - 0x3FFF }

    #[inline]
    pub fn of_i32(src: i32) -> F80 { Self::of_i64(src as i64) }
    #[inline]
    pub fn of_i64(src: i64) -> F80 {
        if src == 0 {
            return Self::ZERO;
        }
        let magnitude = src.unsigned_abs();
        let shift = magnitude.leading_zeros();
        F80 {
            mantissa: magnitude << shift,
            sign_exponent: (if src < 0 { 0x8000 } else { 0 }) | (0x403E - shift as u16),
        }
    }

    #[inline]
    pub fn of_f32(src: i32) -> F80 {
        let bits = src as u32;
        let exponent = (bits >> 23) & 0xFF;
        let fraction = bits & 0x7FFFFF;
        let sign = ((bits >> 16) & 0x8000) as u16;
        // Widening finite binary32 is exact in F80, including subnormals.
        // Do not clear sticky flags here: the x87 wrapper owns that operation.
        if exponent != 0 && exponent != 0xFF {
            return F80 {
                mantissa: ((fraction | 0x800000) as u64) << 40,
                sign_exponent: sign | (exponent as u16 + 0x3F80),
            };
        }
        if exponent == 0 {
            if fraction == 0 {
                return F80 {
                    mantissa: 0,
                    sign_exponent: sign,
                };
            }
            let shift = fraction.leading_zeros() - 8;
            return F80 {
                mantissa: ((fraction << shift) as u64) << 40,
                sign_exponent: sign | (0x3F81 - shift as u16),
            };
        }
        // Preserve SoftFloat's signaling-NaN flags and payload conversion.
        let mut x = F80::ZERO;
        unsafe { f32_to_extF80M(src, &mut x) };
        x
    }

    #[inline]
    pub fn of_f64(src: u64) -> F80 {
        let exponent = (src >> 52) & 0x7FF;
        let fraction = src & 0xFFFFFFFFFFFFF;
        let sign = ((src >> 48) & 0x8000) as u16;
        if exponent != 0 && exponent != 0x7FF {
            return F80 {
                mantissa: (fraction | 0x10000000000000) << 11,
                sign_exponent: sign | (exponent as u16 + 0x3C00),
            };
        }
        if exponent == 0 {
            if fraction == 0 {
                return F80 {
                    mantissa: 0,
                    sign_exponent: sign,
                };
            }
            let shift = fraction.leading_zeros() - 11;
            return F80 {
                mantissa: fraction << (shift + 11),
                sign_exponent: sign | (0x3C01 - shift as u16),
            };
        }
        let mut x = F80::ZERO;
        unsafe { f64_to_extF80M(src, &mut x) };
        x
    }
    fn of_f64x(src: f64) -> F80 { F80::of_f64(f64::to_bits(src)) }

    #[inline]
    pub fn to_f32(&self) -> i32 {
        let exponent = self.sign_exponent & 0x7FFF;
        let sign = ((self.sign_exponent as u32) & 0x8000) << 16;
        if exponent == 0 && self.mantissa == 0 {
            return sign as i32;
        }
        // Common normal-to-normal conversion. Round the original 64-bit
        // significand once; a host f64 intermediate could double-round.
        if (0x3F81..=0x407E).contains(&exponent) && self.mantissa >> 63 != 0 {
            let mut significand = (self.mantissa >> 40) as u32;
            let remainder = self.mantissa & 0xFFFFFFFFFF;
            let increment = match unsafe { softfloat_roundingMode } {
                0 => remainder > 0x8000000000 || remainder == 0x8000000000 && significand & 1 != 0,
                1 => false,
                2 => sign != 0 && remainder != 0,
                3 => sign == 0 && remainder != 0,
                _ => return unsafe { extF80M_to_f32(self) },
            };
            significand += increment as u32;
            // Adding the explicit integer bit to exponent - 1 also handles
            // a rounded significand carry. Overflow must use the reference.
            let magnitude = ((exponent as u32 - 0x3F81) << 23) + significand;
            if magnitude < 0x7F800000 {
                if remainder != 0 {
                    unsafe {
                        softfloat_exceptionFlags |= 1;
                    }
                }
                return (sign | magnitude) as i32;
            }
        }
        // Subnormal results, overflow, NaNs and noncanonical F80 encodings.
        unsafe { extF80M_to_f32(self) }
    }
    #[inline]
    pub fn to_f64(&self) -> u64 {
        let exponent = self.sign_exponent & 0x7FFF;
        let sign = ((self.sign_exponent as u64) & 0x8000) << 48;
        if exponent == 0 && self.mantissa == 0 {
            return sign;
        }
        if (0x3C01..=0x43FE).contains(&exponent) && self.mantissa >> 63 != 0 {
            let mut significand = self.mantissa >> 11;
            let remainder = self.mantissa & 0x7FF;
            // Exact normal stores cannot round, overflow or raise an exception.
            // In particular, FLD m64 followed by FST(P) m64 reaches this case:
            // avoid reading and dispatching on the rounding mode for it.
            if remainder == 0 {
                return sign | ((exponent as u64 - 0x3C01) << 52) + significand;
            }
            let increment = match unsafe { softfloat_roundingMode } {
                0 => remainder > 0x400 || remainder == 0x400 && significand & 1 != 0,
                1 => false,
                2 => sign != 0 && remainder != 0,
                3 => sign == 0 && remainder != 0,
                _ => return unsafe { extF80M_to_f64(self) },
            };
            significand += increment as u64;
            let magnitude = ((exponent as u64 - 0x3C01) << 52) + significand;
            if magnitude < 0x7FF0000000000000 {
                if remainder != 0 {
                    unsafe {
                        softfloat_exceptionFlags |= 1;
                    }
                }
                return sign | magnitude;
            }
        }
        unsafe { extF80M_to_f64(self) }
    }
    fn to_f64x(&self) -> f64 { f64::from_bits(self.to_f64()) }

    #[inline]
    fn normal_to_integer(&self, rounding: u8) -> Option<i64> {
        let exponent = self.sign_exponent & 0x7FFF;
        if exponent == 0 && self.mantissa == 0 {
            return Some(0);
        }
        if exponent == 0 || exponent >= 0x403F || self.mantissa >> 63 == 0 {
            return None;
        }
        let power = exponent as i32 - 0x3FFF;
        let (mut magnitude, nonzero, above_half, tie) = if power >= 0 {
            let shift = 63 - power as u32;
            if shift == 0 {
                (self.mantissa, false, false, false)
            }
            else {
                let remainder = self.mantissa & ((1u64 << shift) - 1);
                let half = 1u64 << (shift - 1);
                (
                    self.mantissa >> shift,
                    remainder != 0,
                    remainder > half,
                    remainder == half,
                )
            }
        }
        else {
            (
                0,
                true,
                power == -1 && self.mantissa > 1 << 63,
                power == -1 && self.mantissa == 1 << 63,
            )
        };
        let increment = match rounding {
            0 => above_half || tie && magnitude & 1 != 0,
            1 => false,
            2 => self.sign() && nonzero,
            3 => !self.sign() && nonzero,
            _ => return None,
        };
        magnitude = magnitude.checked_add(increment as u64)?;
        if self.sign() {
            if magnitude > 1 << 63 {
                return None;
            }
            Some((magnitude as i64).wrapping_neg())
        }
        else {
            i64::try_from(magnitude).ok()
        }
    }
    pub fn to_i32(&self) -> i32 {
        let rounding = unsafe { softfloat_roundingMode };
        if let Some(value) = self
            .normal_to_integer(rounding)
            .and_then(|x| i32::try_from(x).ok())
        {
            return value;
        }
        unsafe { extF80M_to_i32(self, rounding, false) }
    }
    pub fn to_i64(&self) -> i64 {
        let rounding = unsafe { softfloat_roundingMode };
        if let Some(value) = self.normal_to_integer(rounding) {
            return value;
        }
        unsafe { extF80M_to_i64(self, rounding, false) }
    }
    pub fn truncate_to_i32(&self) -> i32 {
        if let Some(value) = self
            .normal_to_integer(1)
            .and_then(|x| i32::try_from(x).ok())
        {
            return value;
        }
        unsafe { extF80M_to_i32(self, 1, false) }
    }
    pub fn truncate_to_i64(&self) -> i64 {
        if let Some(value) = self.normal_to_integer(1) {
            return value;
        }
        unsafe { extF80M_to_i64(self, 1, false) }
    }

    pub fn cos(self) -> F80 { F80::of_f64x(self.to_f64x().cos()) }
    pub fn sin(self) -> F80 { F80::of_f64x(self.to_f64x().sin()) }
    pub fn tan(self) -> F80 { F80::of_f64x(self.to_f64x().tan()) }
    pub fn atan(self) -> F80 { F80::of_f64x(self.to_f64x().atan()) }
    pub fn atan2(self, other: F80) -> F80 { F80::of_f64x(self.to_f64x().atan2(other.to_f64x())) }

    pub fn log2(self) -> F80 { F80::of_f64x(self.to_f64x().log2()) }
    pub fn ln(self) -> F80 {
        // Transcendentals currently round through binary64. Keep that conversion
        // (and its SoftFloat exception flags), but never pass a NaN to the host
        // logarithm: Wasm arithmetic may change its sign/payload between tiers.
        let bits = self.to_f64();
        let magnitude = bits & 0x7FFFFFFFFFFFFFFF;
        if magnitude > 0x7FF0000000000000 {
            return F80::of_f64(bits);
        }
        if magnitude == 0 {
            return F80::NEG_INFINITY;
        }
        if bits >> 63 != 0 {
            // Same default indefinite encoding as the bundled SoftFloat. The
            // old host logarithm did not set SoftFloat's invalid-operation flag.
            return F80 {
                mantissa: 0xC000000000000000,
                sign_exponent: 0xFFFF,
            };
        }
        if magnitude == 0x7FF0000000000000 {
            return F80::POS_INFINITY;
        }
        F80::of_f64x(f64::from_bits(bits).ln())
    }

    pub fn abs(self) -> F80 {
        F80 {
            mantissa: self.mantissa,
            sign_exponent: self.sign_exponent & !0x8000,
        }
    }
    pub fn two_pow(self) -> F80 { F80::of_f64x(2.0f64.powf(self.to_f64x())) }
    pub fn round(self) -> F80 {
        let mut result = F80::ZERO;
        unsafe { extF80M_roundToInt(&self, softfloat_roundingMode, false, &mut result) };
        result
    }
    pub fn trunc(self) -> F80 {
        let mut result = F80::ZERO;
        unsafe { extF80M_roundToInt(&self, 1, false, &mut result) };
        result
    }

    /// Common FSCALE exponents have an exact normal binary64 power of two.
    /// Construct that F80 operand directly, preserving the original multiply
    /// (including precision control, rounding and exception handling).
    pub fn scale(self, exponent: F80) -> F80 {
        if let Some(shift) = exponent.normal_to_integer(1) {
            if (-1022..=1023).contains(&shift) {
                return self
                    * F80 {
                        mantissa: 1 << 63,
                        sign_exponent: (0x3FFF + shift) as u16,
                    };
            }
        }
        self * exponent.trunc().two_pow()
    }

    pub fn sqrt(self) -> F80 {
        if unsafe { extF80_roundingPrecision } != 80 {
            if let Some(result) = self.native_sqrt() {
                return result;
            }
        }
        let mut result = F80::ZERO;
        unsafe { extF80M_sqrt(&self, &mut result) };
        result
    }

    pub fn is_finite(self) -> bool {
        // TODO: Can probably be done more efficiently
        self != F80::POS_INFINITY && self != F80::NEG_INFINITY
    }
    pub fn is_nan(self) -> bool {
        // TODO: Can probably be done more efficiently
        self != self
    }

    pub fn set_rounding_mode(mode: RoundingMode) {
        unsafe {
            softfloat_roundingMode = match mode {
                RoundingMode::NearEven => 0,
                RoundingMode::Trunc => 1,
                RoundingMode::Floor => 2,
                RoundingMode::Ceil => 3,
            }
        };
    }
    pub fn set_precision(precision: Precision) {
        unsafe {
            extF80_roundingPrecision = match precision {
                Precision::P80 => 80,
                Precision::P64 => 64,
                Precision::P32 => 32,
            }
        };
    }

    pub fn get_exception_flags() -> u8 {
        let f = unsafe { softfloat_exceptionFlags };
        // translate softfloat's flags to x87 status flags
        f >> 4 & 1 | f >> 1 & 4 | f << 3 & 16
    }
    pub fn clear_exception_flags() { unsafe { softfloat_exceptionFlags = 0 } }

    // These paths do integer significand arithmetic, not a conversion to f64.
    // Accept only canonical normal inputs and exact normal results at the
    // current precision. No rounding or exception-flag updates are then needed.
    #[inline]
    fn normal_exponent(self) -> Option<i32> {
        let exponent = (self.sign_exponent & 0x7FFF) as i32;
        if exponent > 0 && exponent < 0x7FFF && self.mantissa >> 63 != 0 {
            Some(exponent)
        }
        else {
            None
        }
    }

    #[inline]
    fn exact_normal(mantissa: u64, exponent: i32, sign: u16) -> Option<F80> {
        if exponent <= 0 || exponent >= 0x7FFF {
            return None;
        }
        let discarded = match unsafe { extF80_roundingPrecision } {
            80 => 0,
            64 => 0x7FF,
            32 => 0xFFFFFFFFFF,
            _ => return None,
        };
        if mantissa & discarded != 0 {
            return None;
        }
        Some(F80 {
            mantissa,
            sign_exponent: sign | exponent as u16,
        })
    }

    #[inline(always)]
    fn exact_mul(self, other: F80) -> Option<F80> {
        // Two at-most-32-bit significands have an exact 64-bit product. This
        // includes values loaded from binary32, across the full x87 exponent range.
        if (self.mantissa | other.mantissa) & 0xFFFFFFFF != 0 {
            return None;
        }
        let exponent = self.normal_exponent()? + other.normal_exponent()? - 0x3FFF;
        let product = (self.mantissa >> 32) * (other.mantissa >> 32);
        let shift = product.leading_zeros(); // 0 or 1 for canonical normal inputs
        F80::exact_normal(
            product << shift,
            exponent + 1 - shift as i32,
            (self.sign_exponent ^ other.sign_exponent) & 0x8000,
        )
    }

    #[inline(always)]
    fn exact_add(self, other: F80) -> Option<F80> {
        // A cheap rejection for extended-precision intermediates. Binary32
        // inputs (and other short significands) can be aligned exactly here.
        if (self.mantissa | other.mantissa) & 0xFFFFFFFF != 0 {
            return None;
        }
        let ae = self.normal_exponent()?;
        let be = other.normal_exponent()?;
        let (big, small, exponent, distance) = if (ae, self.mantissa) >= (be, other.mantissa) {
            (self, other, ae, ae - be)
        }
        else {
            (other, self, be, be - ae)
        };
        if distance > 32 {
            return None;
        }
        // The low 32 bits are zero, so alignment loses no bits for this range.
        let aligned = small.mantissa >> distance;
        let sign = big.sign_exponent & 0x8000;
        if (big.sign_exponent ^ small.sign_exponent) & 0x8000 == 0 {
            let (sum, carry) = big.mantissa.overflowing_add(aligned);
            if carry {
                if sum & 1 != 0 {
                    return None;
                }
                F80::exact_normal((sum >> 1) | (1 << 63), exponent + 1, sign)
            }
            else {
                F80::exact_normal(sum, exponent, sign)
            }
        }
        else {
            let difference = big.mantissa - aligned;
            if difference == 0 {
                return Some(F80 {
                    mantissa: 0,
                    sign_exponent: if unsafe { softfloat_roundingMode } == 2 { 0x8000 } else { 0 },
                });
            }
            let shift = difference.leading_zeros();
            F80::exact_normal(difference << shift, exponent - shift as i32, sign)
        }
    }

    #[inline]
    fn finite_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        use std::cmp::Ordering;
        let ae = self.sign_exponent & 0x7FFF;
        let be = other.sign_exponent & 0x7FFF;
        // The bundled SoftFloat extF80[_M]_lt/eq order finite encodings by
        // sign/exponent/significand, without normalizing even noncanonical
        // inputs. Preserve that behavior; special exponents still go through
        // SoftFloat for quiet/signaling NaN flags.
        if ae == 0x7FFF || be == 0x7FFF {
            return None;
        }
        if self.sign() != other.sign() {
            if (ae | be) == 0 && (self.mantissa | other.mantissa) == 0 {
                return Some(Ordering::Equal);
            }
            return Some(if self.sign() { Ordering::Less } else { Ordering::Greater });
        }
        let order = (ae, self.mantissa).cmp(&(be, other.mantissa));
        Some(if self.sign() { order.reverse() } else { order })
    }

    #[inline(always)]
    fn exact_div(self, other: F80) -> Option<F80> {
        if other.mantissa != 0x8000000000000000 {
            return None;
        }
        let exponent = self.normal_exponent()? - other.normal_exponent()? + 0x3FFF;
        F80::exact_normal(
            self.mantissa,
            exponent,
            (self.sign_exponent ^ other.sign_exponent) & 0x8000,
        )
    }

    #[inline(never)]
    fn native_sqrt(self) -> Option<F80> {
        if self.sign() || unsafe { softfloat_roundingMode } != 0 {
            return None;
        }
        let exponent = self.normal_exponent()? as u32;
        let result = match unsafe { extF80_roundingPrecision } {
            64 => {
                if self.mantissa & 0x7FF != 0 || !(0x3C01..=0x43FE).contains(&exponent) {
                    return None;
                }
                let bits =
                    ((exponent as u64 - 0x3C00) << 52) | ((self.mantissa >> 11) & 0xFFFFFFFFFFFFF);
                Self::of_f64(f64::from_bits(bits).sqrt().to_bits())
            },
            32 => {
                if self.mantissa & 0xFFFFFFFFFF != 0 || !(0x3F81..=0x407E).contains(&exponent) {
                    return None;
                }
                let bits = ((exponent - 0x3F80) << 23) | ((self.mantissa >> 40) as u32 & 0x7FFFFF);
                Self::of_f32(f32::from_bits(bits).sqrt().to_bits() as i32)
            },
            _ => return None,
        };
        // An exact square root of a <=53-bit binary significand has <=27
        // significant bits. The existing exact integer multiplication can
        // therefore prove exactness without a rounded host multiplication.
        if !result.exact_mul(result).is_some_and(|square| {
            square.mantissa == self.mantissa && square.sign_exponent == self.sign_exponent
        }) {
            unsafe {
                softfloat_exceptionFlags |= 1;
            }
        }
        Some(result)
    }

    // Native division rounds directly to the requested reduced precision.
    // Both inputs must be exact in that format and the result must remain
    // normal. Full extended precision and other rounding modes use SoftFloat.
    #[inline(never)]
    fn native_div(self, other: F80) -> Option<F80> {
        if unsafe { softfloat_roundingMode } != 0 {
            return None;
        }
        let ae = self.normal_exponent()? as u32;
        let be = other.normal_exponent()? as u32;
        let result = match unsafe { extF80_roundingPrecision } {
            64 => {
                if (self.mantissa | other.mantissa) & 0x7FF != 0
                    || !(0x3C01..=0x43FE).contains(&ae)
                    || !(0x3C01..=0x43FE).contains(&be)
                {
                    return None;
                }
                let a = ((self.sign_exponent as u64 & 0x8000) << 48)
                    | ((ae as u64 - 0x3C00) << 52)
                    | ((self.mantissa >> 11) & 0xFFFFFFFFFFFFF);
                let b = ((other.sign_exponent as u64 & 0x8000) << 48)
                    | ((be as u64 - 0x3C00) << 52)
                    | ((other.mantissa >> 11) & 0xFFFFFFFFFFFFF);
                let bits = (f64::from_bits(a) / f64::from_bits(b)).to_bits();
                let exponent = bits >> 52 & 0x7FF;
                if exponent == 0 || exponent == 0x7FF {
                    return None;
                }
                Self::of_f64(bits)
            },
            32 => {
                if (self.mantissa | other.mantissa) & 0xFFFFFFFFFF != 0
                    || !(0x3F81..=0x407E).contains(&ae)
                    || !(0x3F81..=0x407E).contains(&be)
                {
                    return None;
                }
                let a = ((self.sign_exponent as u32 & 0x8000) << 16)
                    | ((ae - 0x3F80) << 23)
                    | ((self.mantissa >> 40) as u32 & 0x7FFFFF);
                let b = ((other.sign_exponent as u32 & 0x8000) << 16)
                    | ((be - 0x3F80) << 23)
                    | ((other.mantissa >> 40) as u32 & 0x7FFFFF);
                let bits = (f32::from_bits(a) / f32::from_bits(b)).to_bits();
                let exponent = bits >> 23 & 0xFF;
                if exponent == 0 || exponent == 0xFF {
                    return None;
                }
                Self::of_f32(bits as i32)
            },
            _ => return None,
        };
        let odd_divisor = other.mantissa >> other.mantissa.trailing_zeros();
        if self.mantissa % odd_divisor != 0 {
            unsafe {
                softfloat_exceptionFlags |= 1;
            }
        }
        Some(result)
    }

    #[inline]
    pub fn partial_cmp_quiet(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if let Some(order) = self.finite_cmp(other) {
            return Some(order);
        }
        if unsafe { extF80M_lt_quiet(self, other) } {
            Some(std::cmp::Ordering::Less)
        }
        else if unsafe { extF80M_lt_quiet(other, self) } {
            Some(std::cmp::Ordering::Greater)
        }
        else if self == other {
            Some(std::cmp::Ordering::Equal)
        }
        else {
            None
        }
    }
}

impl std::ops::Add for F80 {
    type Output = F80;
    #[inline(always)]
    fn add(self, other: Self) -> Self {
        if unsafe { X87_FAST_MATH } {
            count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
            return F80::of_f64x(self.to_f64x() + other.to_f64x());
        }
        if let Some(result) = self.exact_add(other) {
            count_x87_path(crate::profiler::stat::X87_EXACT);
            return result;
        }
        count_x87_path(crate::profiler::stat::X87_SOFTFLOAT);
        let mut result = F80::ZERO;
        unsafe { extF80M_add(&self, &other, &mut result) };
        result
    }
}
impl std::ops::Sub for F80 {
    type Output = F80;
    #[inline(always)]
    fn sub(self, other: Self) -> Self {
        if unsafe { X87_FAST_MATH } {
            count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
            return F80::of_f64x(self.to_f64x() - other.to_f64x());
        }
        if let Some(result) = self.exact_add(-other) {
            count_x87_path(crate::profiler::stat::X87_EXACT);
            return result;
        }
        count_x87_path(crate::profiler::stat::X87_SOFTFLOAT);
        let mut result = F80::ZERO;
        unsafe { extF80M_sub(&self, &other, &mut result) };
        result
    }
}
impl std::ops::Neg for F80 {
    type Output = F80;
    fn neg(self) -> Self {
        let mut result = self;
        result.sign_exponent ^= 1 << 15;
        result
    }
}
impl std::ops::Mul for F80 {
    type Output = F80;
    #[inline(always)]
    fn mul(self, other: Self) -> Self {
        if unsafe { X87_FAST_MATH } {
            count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
            return F80::of_f64x(self.to_f64x() * other.to_f64x());
        }
        if let Some(result) = self.exact_mul(other) {
            count_x87_path(crate::profiler::stat::X87_EXACT);
            return result;
        }
        count_x87_path(crate::profiler::stat::X87_SOFTFLOAT);
        let mut result = F80::ZERO;
        unsafe { extF80M_mul(&self, &other, &mut result) };
        result
    }
}
impl std::ops::Div for F80 {
    type Output = F80;
    #[inline(always)]
    fn div(self, other: Self) -> Self {
        if unsafe { X87_FAST_MATH } {
            count_x87_path(crate::profiler::stat::X87_NATIVE_F64);
            return F80::of_f64x(self.to_f64x() / other.to_f64x());
        }
        if let Some(result) = self.exact_div(other) {
            count_x87_path(crate::profiler::stat::X87_EXACT);
            return result;
        }
        let mut result = F80::ZERO;
        if unsafe { extF80_roundingPrecision } != 80 {
            if let Some(value) = self.native_div(other) {
                count_x87_path(crate::profiler::stat::X87_EXACT);
                return value;
            }
        }
        count_x87_path(crate::profiler::stat::X87_SOFTFLOAT);
        unsafe { extF80M_div(&self, &other, &mut result) };
        result
    }
}
impl std::ops::Rem for F80 {
    type Output = F80;
    fn rem(self, other: Self) -> Self {
        let quot = (self / other).trunc();
        self - quot * other
        // Uses round-to-nearest instead of truncation
        //let mut result = F80::ZERO;
        //unsafe {
        //    extF80M_rem(&self, &other, &mut result)
        //};
        //result
    }
}

impl PartialEq for F80 {
    fn eq(&self, other: &Self) -> bool { unsafe { extF80M_eq(self, other) } }
}
impl PartialOrd for F80 {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if let Some(order) = self.finite_cmp(other) {
            return Some(order);
        }
        if unsafe { extF80M_lt(self, other) } {
            Some(std::cmp::Ordering::Less)
        }
        else if unsafe { extF80M_lt(other, self) } {
            Some(std::cmp::Ordering::Greater)
        }
        else if self == other {
            Some(std::cmp::Ordering::Equal)
        }
        else {
            None
        }
    }
}
                                                                                             source/v64/src/rust/state_block.rs                                                                  0000644 0000000 0000000 00000003107 00000000000 014311  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! A core's CPU state block, shared by both cores (docs/arm64-virt-android16-plan.md
//! P1.0): each core declares its fields with `state!` (the x86 core in
//! cpu::global_pointers, the ARM core in aarch64::state, both generated by
//! gen/state_layout.js). The default build keeps the block at fixed addresses
//! below --global-base (4096), which generated code reads directly. The
//! parallel build (docs/multicore.md) places it in a static instead: every
//! vCPU worker relocates its own copy of the module into the shared memory,
//! and with it this block; generated code of a worker embeds that worker's
//! addresses. Offsets are the same in both. (tools/parallel_wasm.mjs finds the
//! block by the name STATE_BLOCK, which one core has once.)

#[cfg(feature = "parallel")]
#[repr(C, align(64))]
pub struct StateBlock(pub [u8; 4096]);
#[cfg(feature = "parallel")]
pub static mut STATE_BLOCK: StateBlock = StateBlock([0; 4096]);

macro_rules! state {
    ($name:ident: $type:ty = $offset:literal) => {
        #[cfg(not(feature = "parallel"))]
        pub const $name: *mut $type = $offset as *mut $type;
        #[cfg(feature = "parallel")]
        pub const $name: *mut $type = unsafe {
            (&raw mut $crate::state_block::STATE_BLOCK)
                .cast::<u8>()
                .add($offset)
                .cast::<$type>()
        };
    };
}

/// Address of offset 0 of the state layout (src/state_layout.js)
#[no_mangle]
pub fn state_base() -> u32 {
    #[cfg(feature = "parallel")]
    return (&raw mut STATE_BLOCK) as u32;
    #[cfg(not(feature = "parallel"))]
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/rust/state_flags.rs                                                                  0000644 0000000 0000000 00000001721 00000000000 014313  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #[derive(Copy, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct CachedStateFlags(u8);

impl CachedStateFlags {
    const MASK_IS_32: u8 = 1 << 0;
    pub const MASK_SS32: u8 = 1 << 1;
    const MASK_CPL3: u8 = 1 << 2;
    pub const MASK_FLAT_SEGS: u8 = 1 << 3;

    pub const EMPTY: CachedStateFlags = CachedStateFlags(0);

    pub fn of_u32(f: u32) -> CachedStateFlags {
        dbg_assert!(
            f as u8
                & !(Self::MASK_IS_32 | Self::MASK_SS32 | Self::MASK_CPL3 | Self::MASK_FLAT_SEGS)
                == 0
        );
        CachedStateFlags(f as u8)
    }
    pub fn to_u32(&self) -> u32 { self.0 as u32 }

    pub fn cpl3(&self) -> bool { self.0 & CachedStateFlags::MASK_CPL3 != 0 }
    pub fn has_flat_segmentation(&self) -> bool { self.0 & CachedStateFlags::MASK_FLAT_SEGS != 0 }
    pub fn is_32(&self) -> bool { self.0 & CachedStateFlags::MASK_IS_32 != 0 }
    pub fn ssize_32(&self) -> bool { self.0 & CachedStateFlags::MASK_SS32 != 0 }
}
                                               source/v64/src/rust/step_profile.rs                                                                 0000644 0000000 0000000 00000045463 00000000000 014525  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The step profile (docs/jit-unification-plan.md P0.5): which instructions
//! compiled code leaves to the interpreter (the x64 page tier's; IR Tier-0's
//! too until P7.5), keyed by StepKey v1. Off by default (the JIT switch
//! step_profile); while it is on, every step decodes its instruction's
//! prefixes and opcode into a hash table, so measure in rounds that are not
//! timed (tests/bench/run.mjs --fallbacks). tools/step_profile.mjs names keys.
//!
//! StepKey v1, a u32:
//!
//! | bits  | field |
//! | ----- | ----- |
//! | 0-7   | the opcode byte (after the prefixes, VEX and the escape bytes) |
//! | 8-9   | the opcode map: 0 one-byte, 1 0F, 2 0F 38, 3 0F 3A |
//! | 10-11 | VEX.pp: 0 none, 1 66, 2 F3, 3 F2 |
//! | 12    | VEX.L |
//! | 14    | VEX encoded |
//! | 16    | an F2 or F3 prefix (REP, REPNE, or SSE's mandatory prefix) |
//! | 17    | a retry: compiled code refused an access of the instruction (the x64 page tier) |
//! | 18-20 | ModRM.reg, for an opcode it extends (groups, x87) |
//! | 21    | bits 18-20 are valid |
//! | 22    | a 66 prefix |
//! | 23    | the last F2 or F3 prefix was F2 |
//! | 24    | REX.W |
//! | 25-27 | the mode (x64::state::ExecutionMode: 0 real, 1 virtual-8086, 2 and 3 16- and 32-bit protected, 4 and 5 16- and 32-bit compatibility, 6 64-bit) |
//! | 28-29 | the stepper (Stepper) |
//! | 30-31 | the ISA: 0 x86 (A64 is to take 1, ARM64 plan appendix D item 12) |
//!
//! Bits 13 and 15 are 0. Bits 0-17 alone are the x64 page tier's earlier key,
//! which x64_page_profile_get still reads (x64::pages).
//!
//! Events that are not steps share the store (docs/jit-unification-plan.md
//! P4.0) with the stepper Event: bits 0-7 the event (the `event` module),
//! 8-15 its detail, 25-27 the mode; note_event counts them while the profile
//! is on.

use crate::x64::state::ExecutionMode;
use std::collections::HashMap;

pub const MAP_SHIFT: u32 = 8;
pub const VEX_PP_SHIFT: u32 = 10;
pub const VEX_L: u32 = 1 << 12;
pub const VEX: u32 = 1 << 14;
pub const REP: u32 = 1 << 16;
pub const RETRY: u32 = 1 << 17;
pub const REG_SHIFT: u32 = 18;
pub const GROUP: u32 = 1 << 21;
pub const OPERAND_SIZE: u32 = 1 << 22;
pub const REPNE: u32 = 1 << 23;
pub const REX_W: u32 = 1 << 24;
pub const MODE_SHIFT: u32 = 25;
pub const STEPPER_SHIFT: u32 = 28;
pub const ISA_SHIFT: u32 = 30;
/// The bits of the x64 page tier's earlier key
pub const X64_LEGACY_BITS: u32 = 0x3_5FFF;

/// Who stepped the instruction (Event: not a step, see `event`; 0 was IR
/// Tier-0's until P7.5 deleted it)
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Stepper {
    X64Page = 1,
    Event = 2,
}

/// Events counted in the step profile's store (P4.0), with their details;
/// tools/step_profile.mjs names them
pub mod event {
    /// The x64 page tier did not run a function at RIP: MISS_*
    pub const MISS: u32 = 1;
    pub const MISS_DISABLED: u32 = 1;
    pub const MISS_NO_CODE: u32 = 2;
    pub const MISS_COLD: u32 = 3;
    pub const MISS_COMPILING: u32 = 4;
    /// (attempts that compile: the page got hot, an unserved offset is due)
    pub const MISS_COMPILE: u32 = 5;
    pub const MISS_RECOMPILE: u32 = 6;
    /// a function entered at an offset it does not serve, which steps to its
    /// next block start
    pub const MISS_UNSERVED: u32 = 7;
    /// (not allowed, x64::pages::allowed: MISS_DISABLED is the tier or the
    /// JIT off, deterministic execution or no budget) an interrupt
    /// shadow; TF or RF; DR7 breakpoints; core events, an NMI or an SMI
    /// pending; HLT
    pub const MISS_SHADOW: u32 = 8;
    pub const MISS_TRAP_FLAGS: u32 = 9;
    pub const MISS_BREAKPOINTS: u32 = 10;
    pub const MISS_EVENTS: u32 = 11;
    pub const MISS_HALT: u32 = 12;
    /// Why a page function returned: EXIT_*
    pub const EXIT: u32 = 2;
    pub const EXIT_RETRY: u32 = 1;
    pub const EXIT_UNKNOWN: u32 = 2;
    /// a step ended the activation (STEP_EXIT says why)
    pub const EXIT_STEP: u32 = 3;
    pub const EXIT_BUDGET: u32 = 4;
    /// it left the code it serves (a target outside, not chained)
    pub const EXIT_LEAVE: u32 = 5;
    /// Why a step ended its activation (x64::pages::x64_page_step): the
    /// first of STEP_EXIT_*; CHAINABLE: only the CPL, CS, CR3, the epoch, IF,
    /// IOPL or AC changed (P4.3's STEP_CHAIN could continue)
    pub const STEP_EXIT: u32 = 3;
    pub const STEP_EXIT_HALT: u32 = 1;
    pub const STEP_EXIT_YIELD: u32 = 2;
    pub const STEP_EXIT_SHADOW: u32 = 3;
    pub const STEP_EXIT_CORE_EVENT: u32 = 4;
    pub const STEP_EXIT_CODE_WRITE: u32 = 5;
    pub const STEP_EXIT_IRQ: u32 = 6;
    pub const STEP_EXIT_NMI: u32 = 7;
    /// the mode, CR0, CR4, EFER, DR7, TF, VM or RF changed
    pub const STEP_EXIT_BARRIER: u32 = 8;
    pub const STEP_EXIT_CHAINABLE: u32 = 9;
    /// Each part of a step's context that changed: STEP_CONTEXT_*
    pub const STEP_CONTEXT: u32 = 4;
    pub const STEP_CONTEXT_CPL: u32 = 1;
    pub const STEP_CONTEXT_CS: u32 = 2;
    pub const STEP_CONTEXT_MODE: u32 = 3;
    pub const STEP_CONTEXT_CR0: u32 = 4;
    pub const STEP_CONTEXT_CR3: u32 = 5;
    pub const STEP_CONTEXT_CR4: u32 = 6;
    pub const STEP_CONTEXT_EFER: u32 = 7;
    pub const STEP_CONTEXT_IF: u32 = 8;
    pub const STEP_CONTEXT_TF: u32 = 9;
    pub const STEP_CONTEXT_AC: u32 = 10;
    pub const STEP_CONTEXT_VM: u32 = 11;
    pub const STEP_CONTEXT_RF: u32 = 12;
    pub const STEP_CONTEXT_IOPL: u32 = 13;
    pub const STEP_CONTEXT_DR7: u32 = 14;
    pub const STEP_CONTEXT_EPOCH: u32 = 15;
    // (5 was STARVED: P4.6's long-mode frames with IR Tier-0 pages ready,
    // deleted with Tier-0 by P7.5)
    /// #NM delivered; CLTS; a MOV to CR0 that changed TS (the plan's open
    /// question 5: lazy FPU switching)
    pub const NM: u32 = 6;
    pub const CLTS: u32 = 7;
    pub const CR0_TS: u32 = 8;
    /// FXSAVE (detail 0), FXRSTOR (1), the XSAVE family (2) and XRSTOR (3)
    pub const FXSTATE: u32 = 9;
    /// A read of the HPET's registers; of the ACPI PM timer (open question 4:
    /// what QueryPerformanceCounter reads)
    pub const HPET_READ: u32 = 10;
    pub const PM_TIMER_READ: u32 = 11;
    // (12 was FRAME: a CPU frame began, begin_cpu_frame's, deleted with the
    // region scheduler in M11)
    // (src/hpet.js and src/acpi.js pass these numbers)
    const _: () = assert!(HPET_READ == 10 && PM_TIMER_READ == 11);
}

/// StepKeys and how often they were stepped; None while the profile is off
static mut PROFILE: Option<HashMap<u32, u32>> = None;
/// A sample of each key of a step: the last stepped instruction's linear
/// address and first 8 bytes (step_profile_sample: what the key's steps
/// were, such as a template's refused access)
static mut SAMPLES: Option<HashMap<u32, (u32, [u8; 8])>> = None;
/// The profile sorted by count, most stepped first (step_profile_snapshot)
static mut SNAPSHOT: Vec<(u32, u32)> = Vec::new();
/// The x64 page tier's earlier keys summed from the profile
/// (x64_legacy_count), and whether a step came since
static mut X64_LEGACY: Vec<u32> = Vec::new();
static mut X64_LEGACY_STALE: bool = true;

#[inline(always)]
pub fn enabled() -> bool { unsafe { (*(&raw const PROFILE)).is_some() } }

/// Off: the profile is dropped; on: an empty one unless it was on
/// (step_profile_reset empties it)
pub unsafe fn set_enabled(on: bool) {
    if on != enabled() {
        PROFILE = on.then(HashMap::new);
        SAMPLES = None;
        PAIRS = Vec::new();
        PAIRS_FROZEN = false;
        X64_LEGACY_STALE = true;
    }
}

#[no_mangle]
pub unsafe fn step_profile_reset() {
    if let Some(profile) = (*(&raw mut PROFILE)).as_mut() {
        profile.clear();
    }
    SAMPLES = None;
    PAIRS = Vec::new();
    PAIRS_FROZEN = false;
    X64_LEGACY_STALE = true;
}

/// Count `event` with `detail` (the `event` module) while the profile is on
pub unsafe fn note_event(event: u32, detail: u32) {
    if enabled() {
        note(
            (Stepper::Event as u32) << STEPPER_SHIFT
                | (crate::x64::state::mode() as u32) << MODE_SHIFT
                | (detail & 255) << 8
                | event & 255,
        );
    }
}
/// note_event for devices in JS (the HPET, the ACPI PM timer)
#[no_mangle]
pub unsafe fn step_profile_note_event(event: u32, detail: u32) { note_event(event, detail) }

pub unsafe fn note(key: u32) {
    if let Some(profile) = (*(&raw mut PROFILE)).as_mut() {
        *profile.entry(key).or_default() += 1;
        X64_LEGACY_STALE = true;
    }
}

/// Sort the profile into a snapshot, most stepped first: its length
#[no_mangle]
pub unsafe fn step_profile_snapshot() -> u32 {
    let snapshot = &mut *(&raw mut SNAPSHOT);
    snapshot.clear();
    if let Some(profile) = (*(&raw const PROFILE)).as_ref() {
        snapshot.extend(profile.iter().map(|(&key, &count)| (key, count)));
    }
    snapshot.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    snapshot.len() as u32
}
/// The StepKey of the snapshot's entry `index`
#[no_mangle]
pub unsafe fn step_profile_key(index: u32) -> u32 {
    (&*(&raw const SNAPSHOT))
        .get(index as usize)
        .map_or(0, |e| e.0)
}
/// The count of the snapshot's entry `index`
#[no_mangle]
pub unsafe fn step_profile_count(index: u32) -> u32 {
    (&*(&raw const SNAPSHOT))
        .get(index as usize)
        .map_or(0, |e| e.1)
}
/// The count of `key` now
#[no_mangle]
pub unsafe fn step_profile_get(key: u32) -> u32 {
    (*(&raw const PROFILE))
        .as_ref()
        .and_then(|p| p.get(&key).copied())
        .unwrap_or(0)
}

/// The x64 page tier's steps of its earlier key `legacy` (bits 0-17 of
/// StepKey), summed over the other fields
pub unsafe fn x64_legacy_count(legacy: u32) -> u32 {
    let sums = &mut *(&raw mut X64_LEGACY);
    if X64_LEGACY_STALE {
        sums.clear();
        sums.resize(1 << 18, 0);
        if let Some(profile) = (*(&raw const PROFILE)).as_ref() {
            for (&key, &count) in profile {
                if key >> STEPPER_SHIFT & 3 == Stepper::X64Page as u32 && key >> ISA_SHIFT == 0 {
                    let slot = &mut sums[(key & X64_LEGACY_BITS) as usize];
                    *slot = slot.wrapping_add(count);
                }
            }
        }
        X64_LEGACY_STALE = false;
    }
    sums.get(legacy as usize).copied().unwrap_or(0)
}

/// Opcodes whose ModRM.reg field selects the operation: `map` as in
/// StepKey, `vex` for the VEX-encoded forms
fn extends_opcode(map: u32, opcode: u8, vex: bool) -> bool {
    match (map, vex) {
        (0, false) => matches!(
            opcode,
            0x80..=0x83 | 0x8F | 0xC0 | 0xC1 | 0xC6 | 0xC7 | 0xD0..=0xD3 | 0xD8..=0xDF | 0xF6 | 0xF7 | 0xFE | 0xFF
        ),
        (1, false) => matches!(
            opcode,
            0x00 | 0x01 | 0x0D | 0x18 | 0x1F | 0x71..=0x73 | 0xAE | 0xB9 | 0xBA | 0xC7
        ),
        (1, true) => matches!(opcode, 0x71..=0x73 | 0xAE),
        (2, true) => opcode == 0xF3,
        _ => false,
    }
}

/// The StepKey of the x86 instruction whose first bytes are `bytes` (fewer
/// than 15 when the rest could not be read without side effects)
pub fn x86_key(bytes: &[u8], mode: ExecutionMode, stepper: Stepper, retry: bool) -> u32 {
    let mut key = (mode as u32) << MODE_SHIFT
        | (stepper as u32) << STEPPER_SHIFT
        | if retry { RETRY } else { 0 };
    let long = mode == ExecutionMode::Long64;
    let mut at = 0;
    while let Some(&b) = bytes.get(at) {
        match b {
            0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x67 | 0xF0 => {},
            0x66 => key |= OPERAND_SIZE,
            0xF2 => key |= REP | REPNE,
            0xF3 => key = key & !REPNE | REP,
            // (REX counts only right before the opcode)
            0x40..=0x4F if long => {
                key &= !REX_W;
                if b & 8 != 0 && !matches!(bytes.get(at + 1), Some(0x40..=0x4F)) {
                    key |= REX_W;
                }
            },
            _ => break,
        }
        at += 1;
    }
    let byte = |i: usize| bytes.get(at + i).copied();
    let Some(first) = byte(0)
    else {
        return key;
    };
    // C4 and C5 are LES and LDS in real and virtual-8086 mode, and outside
    // 64-bit mode unless their next byte would be a register ModRM
    let vex = matches!(first, 0xC4 | 0xC5)
        && (long
            || !matches!(mode, ExecutionMode::Real | ExecutionMode::Vm86)
                && byte(1).is_some_and(|b| b >> 6 == 3));
    let (map, opcode, modrm) = if vex {
        let Some(b1) = byte(1)
        else {
            return key;
        };
        let (map, b, rest) = if first == 0xC5 {
            (1, b1, 2)
        }
        else {
            let Some(b2) = byte(2)
            else {
                return key;
            };
            if b2 & 0x80 != 0 {
                key |= REX_W;
            }
            ((b1 & 3) as u32, b2, 3)
        };
        key |= VEX | (b as u32 & 3) << VEX_PP_SHIFT | if b & 4 != 0 { VEX_L } else { 0 };
        (map, byte(rest), byte(rest + 1))
    }
    else if first == 0x0F {
        match byte(1) {
            Some(0x38) => (2, byte(2), byte(3)),
            Some(0x3A) => (3, byte(2), byte(3)),
            b => (1, b, byte(2)),
        }
    }
    else {
        (0, Some(first), byte(1))
    };
    key |= map << MAP_SHIFT;
    let Some(opcode) = opcode
    else {
        return key;
    };
    key |= opcode as u32;
    if let Some(modrm) = modrm.filter(|_| extends_opcode(map, opcode, vex)) {
        key |= GROUP | (modrm as u32 >> 3 & 7) << REG_SHIFT;
    }
    key
}

/// The bytes of the instruction at linear `address` in legacy and
/// compatibility mode, whose first byte is at `physical` (a RAM address): as
/// many as translate without side effects to RAM, at most 15
pub unsafe fn read_legacy(address: u32, physical: u32, bytes: &mut [u8; 15]) -> usize {
    use crate::cpu::{cpu, memory};
    let mut page = (address & !0xFFF, physical & !0xFFF);
    for i in 0..15 {
        let linear = address.wrapping_add(i as u32);
        if linear & !0xFFF != page.0 {
            let Ok(next) = cpu::translate_address_read_no_side_effects(linear as i32)
            else {
                return i;
            };
            if memory::in_mapped_range(next) {
                return i;
            }
            page = (linear & !0xFFF, next & !0xFFF);
        }
        bytes[i] = *memory::mem8.add((page.1 | linear & 0xFFF) as usize);
    }
    15
}

/// Steps by their first two bytes (little-endian, as IR Tier-0 counted
/// them before P7.5): the ISA tests' check that a form ran as a template
static mut PAIRS: Vec<u32> = Vec::new();
/// x64_page_steps_freeze: PAIRS keep their counts until the next reset
static mut PAIRS_FROZEN: bool = false;
pub unsafe fn freeze_pairs() { PAIRS_FROZEN = true; }
pub unsafe fn pair_count(pair: u32) -> u32 {
    (&*(&raw const PAIRS))
        .get(pair as usize & 0xFFFF)
        .copied()
        .unwrap_or(0)
}

/// note(key) of a step at linear `address`, whose bytes begin with `bytes`:
/// they are the key's sample (step_profile_sample)
pub unsafe fn note_sampled(key: u32, address: u32, bytes: &[u8]) {
    note(key);
    if let Some(&b0) = bytes.first().filter(|_| !PAIRS_FROZEN) {
        let pairs = &mut *(&raw mut PAIRS);
        pairs.resize(0x10000, 0);
        let pair = b0 as usize | (*bytes.get(1).unwrap_or(&0) as usize) << 8;
        pairs[pair] = pairs[pair].wrapping_add(1);
    }
    let mut first = [0; 8];
    let n = bytes.len().min(8);
    first[..n].copy_from_slice(&bytes[..n]);
    (*(&raw mut SAMPLES))
        .get_or_insert_with(HashMap::new)
        .insert(key, (address, first));
}
/// The sample of the snapshot's entry `index`: 0, the linear
/// address; 1 and 2, the instruction's bytes 0-3 and 4-7 (little-endian);
/// 0 without one
#[no_mangle]
pub unsafe fn step_profile_sample(index: u32, which: u32) -> u32 {
    let Some(&(key, _)) = (&*(&raw const SNAPSHOT)).get(index as usize)
    else {
        return 0;
    };
    let Some(&(address, bytes)) = (*(&raw const SAMPLES)).as_ref().and_then(|s| s.get(&key))
    else {
        return 0;
    };
    match which {
        0 => address,
        1 => u32::from_le_bytes(bytes[..4].try_into().unwrap()),
        _ => u32::from_le_bytes(bytes[4..].try_into().unwrap()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ExecutionMode::*;

    fn key(bytes: &[u8], mode: ExecutionMode) -> u32 {
        x86_key(bytes, mode, Stepper::X64Page, false) & ((1 << MODE_SHIFT) - 1)
    }

    #[test]
    fn opcodes_maps_and_prefixes() {
        assert_eq!(key(&[0x0F, 0xA2], Protected32), 1 << MAP_SHIFT | 0xA2);
        assert_eq!(key(&[0xF3, 0xA5], Protected32), REP | 0xA5);
        assert_eq!(key(&[0xF3, 0xF2, 0xA6], Protected32), REP | REPNE | 0xA6);
        assert_eq!(key(&[0xF2, 0xF3, 0xA6], Protected32), REP | 0xA6);
        assert_eq!(
            key(&[0x66, 0x0F, 0x38, 0x00, 0xC1], Protected32),
            OPERAND_SIZE | 2 << MAP_SHIFT
        );
        assert_eq!(
            key(&[0x0F, 0x3A, 0x0F, 0xC1, 1], Protected32),
            3 << MAP_SHIFT | 0x0F
        );
        // group opcodes carry ModRM.reg: FF /2 (CALL), 0F AE /5 (LFENCE)
        assert_eq!(
            key(&[0xFF, 0xD0], Protected32),
            GROUP | 2 << REG_SHIFT | 0xFF
        );
        assert_eq!(
            key(&[0x0F, 0xAE, 0xE8], Protected32),
            GROUP | 5 << REG_SHIFT | 1 << MAP_SHIFT | 0xAE
        );
        assert_eq!(key(&[0x8B, 0xC0], Protected32), 0x8B);
    }

    #[test]
    fn rex_and_vex() {
        // REX is a prefix in 64-bit mode only, and only right before the opcode
        assert_eq!(
            key(&[0x48, 0x0F, 0xA2], Long64),
            REX_W | 1 << MAP_SHIFT | 0xA2
        );
        assert_eq!(key(&[0x48, 0x40, 0x99], Long64), 0x99);
        assert_eq!(key(&[0x48, 0x99], Protected32), 0x48);
        // VEX.256.66.0F38 18 (VBROADCASTSS) and VEX.128.F2.0F 10, W1
        assert_eq!(
            key(&[0xC4, 0xE2, 0x7D, 0x18, 0xC1], Long64),
            VEX | VEX_L | 1 << VEX_PP_SHIFT | 2 << MAP_SHIFT | 0x18
        );
        assert_eq!(
            key(&[0xC4, 0xE1, 0xFB, 0x10, 0xC1], Long64),
            VEX | REX_W | 3 << VEX_PP_SHIFT | 1 << MAP_SHIFT | 0x10
        );
        assert_eq!(
            key(&[0xC5, 0xF8, 0x77], Protected32),
            VEX | 1 << MAP_SHIFT | 0x77
        );
        // LES and LDS: a memory operand outside 64-bit mode, and in real mode
        assert_eq!(key(&[0xC4, 0x06, 0x00, 0x10], Protected32), 0xC4);
        assert_eq!(key(&[0xC5, 0xF8, 0x77], Real), 0xC5);
        // BLSR (VEX.0F38 F3 /1) is a group
        assert_eq!(
            key(&[0xC4, 0xE2, 0x78, 0xF3, 0xC9], Protected32),
            VEX | GROUP | 1 << REG_SHIFT | 2 << MAP_SHIFT | 0xF3
        );
    }

    #[test]
    fn header_fields() {
        let k = x86_key(&[0x90], Compatibility32, Stepper::X64Page, true);
        assert_eq!(k >> MODE_SHIFT & 7, Compatibility32 as u32);
        assert_eq!(k >> STEPPER_SHIFT & 3, Stepper::X64Page as u32);
        assert_eq!(k >> ISA_SHIFT, 0);
        assert_eq!(k & X64_LEGACY_BITS, RETRY | 0x90);
        // a truncated read keeps the prefixes
        assert_eq!(key(&[0xF3], Protected32), REP);
        assert_eq!(key(&[0x0F], Protected32), 1 << MAP_SHIFT);
    }
}
                                                                                                                                                                                                             source/v64/src/rust/wasmgen/leaves.rs                                                               0000644 0000000 0000000 00000004265 00000000000 014745  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! ISA-neutral v128 leaves (docs/jit-unification-plan.md P2.2): lane
//! permutations and constant shifts that x86tpl builds on and that A64's NEON
//! templates use (ARM64 plan P6.3). Nothing here has an ISA's semantics:
//! callers decide what out-of-range counts and saturation mean.
use crate::wasmgen::wasm_builder::WasmBuilder;

/// i8x16.shuffle lanes that interleave the `element`-byte elements of two
/// `bytes`-wide operands (lanes 0-15 the first, 16-31 the second), their low
/// halves or (`high`) their high halves: x86's PUNPCKL/PUNPCKH, A64's ZIP1
/// and ZIP2
pub fn interleave_lanes(element: u8, high: bool, bytes: u8) -> [u8; 16] {
    let mut lanes = [0; 16];
    let half = bytes / 2;
    for k in 0..bytes {
        let index = k / (element * 2);
        let side = k / element % 2;
        lanes[k as usize] =
            (if high { half } else { 0 }) + index * element + k % element + side * 16;
    }
    lanes
}

/// i8x16.shuffle lanes over (value, zero) that shift the bytes by `count`,
/// toward lane 0 (`down`, x86's PSRLDQ) or away from it (PSLLDQ); A64's EXT
/// with a zero register
pub fn byte_shift_lanes(count: u32, down: bool) -> [u8; 16] {
    let mut lanes = [16; 16];
    for (k, lane) in lanes.iter_mut().enumerate() {
        let index = if down { k as i32 + count as i32 } else { k as i32 - count as i32 };
        if (0..16).contains(&index) {
            *lane = index as u8;
        }
    }
    lanes
}

/// A lane shift (shift_lanes)
#[derive(Clone, Copy)]
pub enum Shift {
    Left,
    Arithmetic,
    Logical,
}

/// Shift the `bits`-wide lanes (16, 32 or 64) of the v128 on the stack by
/// `count`, below `bits`
pub fn shift_lanes(w: &mut WasmBuilder, bits: u8, shift: Shift, count: u32) {
    dbg_assert!(count < bits as u32);
    w.const_i32(count as i32);
    let base = match bits {
        16 => 0x8B,
        32 => 0xAB,
        _ => 0xCB,
    };
    w.simd(
        base + match shift {
            Shift::Left => 0,
            Shift::Arithmetic => 1,
            Shift::Logical => 2,
        },
    );
}

/// Push the i32x4 that has `value` in every lane
pub fn splat_i32(w: &mut WasmBuilder, value: i32) {
    w.const_i32(value);
    w.simd(0x11); // i32x4.splat
}
                                                                                                                                                                                                                                                                                                                                           source/v64/src/rust/wasmgen/mod.rs                                                                  0000644 0000000 0000000 00000000074 00000000000 014237  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       pub mod leaves;
pub mod wasm_builder;
pub mod wasm_opcodes;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/src/rust/wasmgen/wasm_builder.rs                                                         0000644 0000000 0000000 00000127012 00000000000 016137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use crate::leb::{write_leb_i32, write_leb_i64, write_leb_u32};
use crate::wasmgen::wasm_opcodes as op;
use std::collections::HashMap;

/// Multiplicative hashing for the builder's small keys (labels, signatures,
/// import names): SipHash showed in JIT compile profiles.
#[derive(Default)]
pub struct FastHasher(u64);
impl std::hash::Hasher for FastHasher {
    fn finish(&self) -> u64 { self.0 }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0.rotate_left(5) ^ b as u64).wrapping_mul(0x517C_C1B7_2722_0A95);
        }
    }
    fn write_u32(&mut self, v: u32) { self.write_u64(v as u64) }
    fn write_u64(&mut self, v: u64) {
        self.0 = (self.0.rotate_left(5) ^ v).wrapping_mul(0x517C_C1B7_2722_0A95);
    }
    fn write_usize(&mut self, v: usize) { self.write_u64(v as u64) }
}
type FastMap<K, V> = HashMap<K, V, std::hash::BuildHasherDefault<FastHasher>>;

// Wasm indices and vector/section lengths are unsigned 32-bit LEBs.
fn wasm_len(n: usize) -> u32 { u32::try_from(n).expect("Wasm length exceeds u32") }
fn section(output: &mut Vec<u8>, kind: u8, contents: &[u8]) {
    output.push(kind);
    write_leb_u32(output, wasm_len(contents.len()));
    output.extend_from_slice(contents);
}
fn name(output: &mut Vec<u8>, text: &str) {
    write_leb_u32(output, wasm_len(text.len()));
    output.extend_from_slice(text.as_bytes());
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum WasmType {
    I32 = 0x7F,
    I64 = 0x7E,
    F32 = 0x7D,
    F64 = 0x7C,
    V128 = 0x7B,
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct Signature {
    pub params: Vec<WasmType>,
    pub results: Vec<WasmType>,
}
impl Signature {
    pub fn new(params: &[WasmType], results: &[WasmType]) -> Self {
        Self {
            params: params.to_vec(),
            results: results.to_vec(),
        }
    }
}
/// Signature of the module's single exported function.
#[derive(Copy, Clone, PartialEq)]
#[allow(non_camel_case_types)]
enum FunctionType {
    FN1,
    FN1_RET,
}

impl FunctionType {
    fn signature(self) -> Signature {
        use WasmType::*;
        let (params, results): (&[WasmType], &[WasmType]) = match self {
            Self::FN1 => (&[I32], &[]),
            Self::FN1_RET => (&[I32], &[I32]),
        };
        Signature::new(params, results)
    }
}

pub const WASM_MODULE_ARGUMENT_COUNT: u32 = 1;

pub struct WasmBuilder {
    output: Vec<u8>,
    instruction_body: Vec<u8>,
    signatures: Vec<Signature>,
    signature_indices: FastMap<Signature, u32>,
    imports: Vec<(String, u32)>,
    import_indices: FastMap<String, u32>,
    finished: bool,
    next_label: Label,
    label_stack: Vec<Label>,
    label_to_depth: FastMap<Label, usize>,
    free_locals_i32: Vec<WasmLocal>,
    free_locals_i64: Vec<WasmLocalI64>,
    free_locals_f32: Vec<WasmLocalF32>,
    free_locals_f64: Vec<WasmLocalF64>,
    free_locals_v128: Vec<WasmLocalV128>,
    local_types: Vec<WasmType>,
    local_live: Vec<bool>,
    pub arg_local_initial_state: WasmLocal,
    /// Imports the host's function table as ("e", "t") (tail calls).
    table_import: bool,
    /// The module's function returns an i32 (FN1_RET instead of FN1).
    entry_result: bool,
    /// Branch hints (body offset of an if/br_if, likely taken), emitted as
    /// the "metadata.code.branch_hint" section.
    branch_hints: Vec<(usize, bool)>,
    /// The module function's name in the "name" section (profiles).
    function_name: Option<String>,
    /// Functions defined after the entry function: type index and body
    /// (locals declaration, code, END), called with call_internal.
    internal_functions: Vec<(u32, Vec<u8>)>,
    /// Positions of the 5-byte targets of calls to internal functions, and
    /// which one (patched in finish, once the import count is final)
    internal_calls: Vec<(usize, u32)>,
}

#[derive(Eq, PartialEq)]
pub struct WasmLocal(u32);
impl WasmLocal {
    pub fn idx(&self) -> u32 { self.0 }
    /// Only clone locals whose owner keeps them live for the whole use interval.
    pub fn unsafe_clone(&self) -> Self { Self(self.0) }
}
pub struct WasmLocalI64(u32);
impl WasmLocalI64 {
    pub fn idx(&self) -> u32 { self.0 }
    pub fn unsafe_clone(&self) -> Self { Self(self.0) }
}
// F32 locals are exercised by the backend tests; SIMD uses V128.
#[allow(dead_code)]
pub struct WasmLocalF32(u32);
pub struct WasmLocalF64(u32);
pub struct WasmLocalV128(u32);

#[derive(Copy, Clone, Eq, Hash, PartialEq)]
pub struct Label(u32);
impl Label {
    const ZERO: Label = Label(0);
    fn next(&self) -> Label { Label(self.0.checked_add(1).expect("Wasm label overflow")) }
}

impl WasmBuilder {
    pub fn new() -> Self {
        Self {
            output: Vec::with_capacity(256),
            instruction_body: Vec::with_capacity(256),
            signatures: Vec::new(),
            signature_indices: FastMap::default(),
            imports: Vec::new(),
            import_indices: FastMap::default(),
            finished: false,
            next_label: Label::ZERO,
            label_stack: Vec::new(),
            label_to_depth: FastMap::default(),
            free_locals_i32: Vec::new(),
            free_locals_i64: Vec::new(),
            free_locals_f32: Vec::new(),
            free_locals_f64: Vec::new(),
            free_locals_v128: Vec::new(),
            local_types: Vec::new(),
            local_live: Vec::new(),
            arg_local_initial_state: WasmLocal(0),
            table_import: false,
            entry_result: false,
            branch_hints: Vec::new(),
            function_name: None,
            internal_functions: Vec::new(),
            internal_calls: Vec::new(),
        }
    }

    pub fn intern_signature(&mut self, signature: Signature) -> u32 {
        assert!(!self.finished, "reset builder before reuse");
        if let Some(&index) = self.signature_indices.get(&signature) {
            return index;
        }
        let index = wasm_len(self.signatures.len());
        self.signatures.push(signature.clone());
        self.signature_indices.insert(signature, index);
        index
    }

    fn get_fn_idx_signature(&mut self, fn_name: &str, signature: Signature) -> u32 {
        let ty = self.intern_signature(signature);
        if let Some(&index) = self.import_indices.get(fn_name) {
            assert_eq!(
                self.imports[index as usize].1, ty,
                "helper signature mismatch: {}",
                fn_name
            );
            return index;
        }
        let index = wasm_len(self.imports.len());
        self.imports.push((fn_name.to_owned(), ty));
        self.import_indices.insert(fn_name.to_owned(), index);
        index
    }

    /// The function index of an import (imports only grow, so it is final).
    pub fn import_index(&mut self, fn_name: &str, signature: Signature) -> u32 {
        self.get_fn_idx_signature(fn_name, signature)
    }
    /// Define a function after the entry function (`body`: locals
    /// declaration, code and END); returns its number for call_internal.
    pub fn add_internal_function(&mut self, signature: Signature, body: Vec<u8>) -> u32 {
        let ty = self.intern_signature(signature);
        self.internal_functions.push((ty, body));
        wasm_len(self.internal_functions.len() - 1)
    }
    /// Call internal function `number` (its index is patched in finish).
    pub fn call_internal(&mut self, number: u32) {
        self.instruction_body.push(op::OP_CALL);
        self.internal_calls
            .push((self.instruction_body.len(), number));
        self.instruction_body
            .extend_from_slice(&[0x80, 0x80, 0x80, 0x80, 0]);
    }

    /// Vector signatures are for Wasm-to-Wasm calls; JS helpers need a scratch-memory ABI.
    pub fn call_signature(&mut self, fn_name: &str, signature: Signature) {
        let index = self.get_fn_idx_signature(fn_name, signature);
        self.instruction_body.push(op::OP_CALL);
        write_leb_u32(&mut self.instruction_body, index);
    }

    pub fn finish(&mut self) -> usize {
        assert!(!self.finished, "reset builder before reuse");
        assert!(
            self.label_stack.is_empty() && self.label_to_depth.is_empty(),
            "unclosed Wasm blocks"
        );
        assert!(
            self.local_live.iter().all(|&live| !live),
            "all locals must be freed"
        );
        let entry_type = self.intern_signature(self.entry_signature());
        self.output.extend_from_slice(b"\0asm\x01\0\0\0");
        let mut body = Vec::new();
        write_leb_u32(&mut body, wasm_len(self.signatures.len()));
        for signature in &self.signatures {
            body.push(op::TYPE_FUNC);
            write_leb_u32(&mut body, wasm_len(signature.params.len()));
            body.extend(signature.params.iter().map(|t| *t as u8));
            write_leb_u32(&mut body, wasm_len(signature.results.len()));
            body.extend(signature.results.iter().map(|t| *t as u8));
        }
        section(&mut self.output, op::SC_TYPE, &body);
        body.clear();
        write_leb_u32(
            &mut body,
            wasm_len(self.imports.len())
                .checked_add(1 + self.table_import as u32)
                .expect("import overflow"),
        );
        for (fn_name, ty) in &self.imports {
            name(&mut body, "e");
            name(&mut body, fn_name);
            body.push(op::EXT_FUNCTION);
            write_leb_u32(&mut body, *ty);
        }
        name(&mut body, "e");
        name(&mut body, "m");
        #[cfg(not(feature = "parallel"))]
        {
            body.extend_from_slice(&[op::EXT_MEMORY, 0]);
            write_leb_u32(&mut body, 64);
        }
        #[cfg(feature = "parallel")]
        {
            // shared, minimum 64 pages, maximum 4 GiB (the imported memory of tools/parallel_wasm.js)
            body.extend_from_slice(&[op::EXT_MEMORY, 3]);
            write_leb_u32(&mut body, 64);
            write_leb_u32(&mut body, 65536);
        }
        if self.table_import {
            name(&mut body, "e");
            name(&mut body, "t");
            // funcref, no maximum, minimum 0 (indices are checked at run time)
            body.extend_from_slice(&[op::EXT_TABLE, op::TYPE_ANYFUNC, 0, 0]);
        }
        section(&mut self.output, op::SC_IMPORT, &body);
        body.clear();
        write_leb_u32(&mut body, wasm_len(1 + self.internal_functions.len()));
        write_leb_u32(&mut body, entry_type);
        for (ty, _) in &self.internal_functions {
            write_leb_u32(&mut body, *ty);
        }
        section(&mut self.output, op::SC_FUNCTION, &body);
        // internal function k is function imports + 1 + k: 5-byte LEB targets
        let first_internal = wasm_len(self.imports.len() + 1);
        for &(at, number) in &self.internal_calls {
            let index = first_internal + number;
            for i in 0..5 {
                self.instruction_body[at + i] =
                    (index >> (7 * i) & 0x7F) as u8 | if i < 4 { 0x80 } else { 0 };
            }
        }
        body.clear();
        body.push(1);
        name(&mut body, "f");
        body.push(op::EXT_FUNCTION);
        write_leb_u32(&mut body, wasm_len(self.imports.len()));
        section(&mut self.output, op::SC_EXPORT, &body);
        let mut groups: Vec<(WasmType, u32)> = Vec::new();
        for &ty in &self.local_types {
            if let Some((last, count)) = groups.last_mut() {
                if *last == ty {
                    *count = count.checked_add(1).expect("local group overflow");
                    continue;
                }
            }
            groups.push((ty, 1));
        }
        body.clear();
        write_leb_u32(&mut body, wasm_len(groups.len()));
        for (ty, count) in groups {
            write_leb_u32(&mut body, count);
            body.push(ty as u8);
        }
        if !self.branch_hints.is_empty() {
            // Offsets from the start of the function body (its locals).
            let mut hints = Vec::new();
            name(&mut hints, "metadata.code.branch_hint");
            hints.push(1);
            write_leb_u32(&mut hints, wasm_len(self.imports.len()));
            write_leb_u32(&mut hints, wasm_len(self.branch_hints.len()));
            for &(offset, likely) in &self.branch_hints {
                write_leb_u32(&mut hints, wasm_len(body.len() + offset));
                hints.push(1);
                hints.push(likely as u8);
            }
            section(&mut self.output, 0, &hints);
        }
        body.extend_from_slice(&self.instruction_body);
        body.push(op::OP_END);
        let mut code = Vec::new();
        write_leb_u32(&mut code, wasm_len(1 + self.internal_functions.len()));
        write_leb_u32(&mut code, wasm_len(body.len()));
        code.extend_from_slice(&body);
        for (_, internal) in &self.internal_functions {
            write_leb_u32(&mut code, wasm_len(internal.len()));
            code.extend_from_slice(internal);
        }
        section(&mut self.output, op::SC_CODE, &code);
        if let Some(function_name) = &self.function_name {
            let mut names = Vec::new();
            write_leb_u32(&mut names, 1);
            write_leb_u32(&mut names, wasm_len(self.imports.len()));
            name(&mut names, function_name);
            let mut contents = Vec::new();
            name(&mut contents, "name");
            contents.push(1);
            write_leb_u32(&mut contents, wasm_len(names.len()));
            contents.extend_from_slice(&names);
            section(&mut self.output, 0, &contents);
        }
        self.finished = true;
        self.output.len()
    }

    pub fn output(&self) -> &[u8] { &self.output }
    /// Bytes of instructions emitted so far (for size statistics).
    pub fn body_len(&self) -> usize { self.instruction_body.len() }
    /// Declared locals excluding parameters, including temporary staging slots.
    #[cfg(test)]
    pub fn declared_local_count(&self) -> usize { self.local_types.len() }

    /// Declared locals excluding parameters, including temporary staging slots.

    fn new_local_index(&mut self, ty: WasmType) -> u32 {
        assert!(!self.finished, "reset builder before reuse");
        let index = wasm_len(self.local_types.len())
            .checked_add(WASM_MODULE_ARGUMENT_COUNT)
            .expect("local overflow");
        self.local_types.push(ty);
        self.local_live.push(true);
        index
    }
    fn reuse_local_index(&mut self, index: u32, ty: WasmType) {
        let i = (index - WASM_MODULE_ARGUMENT_COUNT) as usize;
        assert_eq!(self.local_types[i], ty);
        assert!(!self.local_live[i], "reusing live local");
        self.local_live[i] = true;
    }
    fn release_local_index(&mut self, index: u32, ty: WasmType) {
        let i = index
            .checked_sub(WASM_MODULE_ARGUMENT_COUNT)
            .expect("cannot free argument") as usize;
        assert_eq!(self.local_types[i], ty);
        assert!(self.local_live[i], "local freed twice");
        self.local_live[i] = false;
    }
    fn open_block(&mut self) -> Label {
        let label = self.next_label;
        self.next_label = self.next_label.next();
        self.label_to_depth
            .insert(label, self.label_stack.len() + 1);
        self.label_stack.push(label);
        label
    }
    fn close_block(&mut self) {
        let label = self.label_stack.pop().unwrap();
        let old_depth = self.label_to_depth.remove(&label).unwrap();
        dbg_assert!(self.label_to_depth.len() + 1 == old_depth);
    }

    fn alloc_local(&mut self) -> WasmLocal {
        if let Some(local) = self.free_locals_i32.pop() {
            self.reuse_local_index(local.0, WasmType::I32);
            local
        }
        else {
            WasmLocal(self.new_local_index(WasmType::I32))
        }
    }
    /// A fresh declaration starts at zero on every function entry. Never reuse
    /// a freed local: its previous runtime value may survive on this CFG path.
    #[must_use]
    pub fn declare_zeroed_local(&mut self) -> WasmLocal {
        WasmLocal(self.new_local_index(WasmType::I32))
    }
    pub fn free_local(&mut self, local: WasmLocal) {
        self.release_local_index(local.0, WasmType::I32);
        self.free_locals_i32.push(local);
    }
    #[must_use]
    pub fn set_new_local(&mut self) -> WasmLocal {
        let local = self.alloc_local();
        self.set_local(&local);
        local
    }
    pub fn set_local(&mut self, local: &WasmLocal) {
        self.instruction_body.push(op::OP_SETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    pub fn get_local(&mut self, local: &WasmLocal) {
        self.instruction_body.push(op::OP_GETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.idx());
    }
    pub fn tee_local(&mut self, local: &WasmLocal) {
        self.instruction_body.push(op::OP_TEELOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    fn alloc_local_i64(&mut self) -> WasmLocalI64 {
        if let Some(local) = self.free_locals_i64.pop() {
            self.reuse_local_index(local.0, WasmType::I64);
            local
        }
        else {
            WasmLocalI64(self.new_local_index(WasmType::I64))
        }
    }
    #[must_use]
    pub fn declare_zeroed_local_i64(&mut self) -> WasmLocalI64 {
        WasmLocalI64(self.new_local_index(WasmType::I64))
    }
    pub fn free_local_i64(&mut self, local: WasmLocalI64) {
        self.release_local_index(local.0, WasmType::I64);
        self.free_locals_i64.push(local);
    }
    #[must_use]
    pub fn set_new_local_i64(&mut self) -> WasmLocalI64 {
        let local = self.alloc_local_i64();
        self.set_local_i64(&local);
        local
    }
    pub fn set_local_i64(&mut self, local: &WasmLocalI64) {
        self.instruction_body.push(op::OP_SETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    pub fn get_local_i64(&mut self, local: &WasmLocalI64) {
        self.instruction_body.push(op::OP_GETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.idx());
    }
    #[allow(dead_code)]
    fn alloc_local_f32(&mut self) -> WasmLocalF32 {
        if let Some(local) = self.free_locals_f32.pop() {
            self.reuse_local_index(local.0, WasmType::F32);
            local
        }
        else {
            WasmLocalF32(self.new_local_index(WasmType::F32))
        }
    }
    #[allow(dead_code)]
    pub fn free_local_f32(&mut self, local: WasmLocalF32) {
        self.release_local_index(local.0, WasmType::F32);
        self.free_locals_f32.push(local);
    }
    #[must_use]
    #[allow(dead_code)]
    pub fn set_new_local_f32(&mut self) -> WasmLocalF32 {
        let local = self.alloc_local_f32();
        self.set_local_f32(&local);
        local
    }
    #[allow(dead_code)]
    pub fn set_local_f32(&mut self, local: &WasmLocalF32) {
        self.instruction_body.push(op::OP_SETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    #[allow(dead_code)]
    pub fn get_local_f32(&mut self, local: &WasmLocalF32) {
        self.instruction_body.push(op::OP_GETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    fn alloc_local_f64(&mut self) -> WasmLocalF64 {
        if let Some(local) = self.free_locals_f64.pop() {
            self.reuse_local_index(local.0, WasmType::F64);
            local
        }
        else {
            WasmLocalF64(self.new_local_index(WasmType::F64))
        }
    }
    pub fn free_local_f64(&mut self, local: WasmLocalF64) {
        self.release_local_index(local.0, WasmType::F64);
        self.free_locals_f64.push(local);
    }
    #[must_use]
    pub fn set_new_local_f64(&mut self) -> WasmLocalF64 {
        let local = self.alloc_local_f64();
        self.set_local_f64(&local);
        local
    }
    pub fn set_local_f64(&mut self, local: &WasmLocalF64) {
        self.instruction_body.push(op::OP_SETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    pub fn get_local_f64(&mut self, local: &WasmLocalF64) {
        self.instruction_body.push(op::OP_GETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    fn alloc_local_v128(&mut self) -> WasmLocalV128 {
        if let Some(local) = self.free_locals_v128.pop() {
            self.reuse_local_index(local.0, WasmType::V128);
            local
        }
        else {
            WasmLocalV128(self.new_local_index(WasmType::V128))
        }
    }
    #[must_use]
    pub fn declare_zeroed_local_v128(&mut self) -> WasmLocalV128 {
        WasmLocalV128(self.new_local_index(WasmType::V128))
    }
    pub fn free_local_v128(&mut self, local: WasmLocalV128) {
        self.release_local_index(local.0, WasmType::V128);
        self.free_locals_v128.push(local);
    }
    #[must_use]
    pub fn set_new_local_v128(&mut self) -> WasmLocalV128 {
        let local = self.alloc_local_v128();
        self.set_local_v128(&local);
        local
    }
    pub fn set_local_v128(&mut self, local: &WasmLocalV128) {
        self.instruction_body.push(op::OP_SETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    pub fn get_local_v128(&mut self, local: &WasmLocalV128) {
        self.instruction_body.push(op::OP_GETLOCAL);
        write_leb_u32(&mut self.instruction_body, local.0);
    }
    pub fn unary_f64(&mut self, negative: bool) {
        self.instruction_body
            .push(if negative { op::OP_F64NEG } else { op::OP_F64ABS });
    }

    pub fn round_f64(&mut self, rc: u8) {
        self.instruction_body.push(match rc {
            0 => op::OP_F64NEAREST,
            1 => op::OP_F64FLOOR,
            2 => op::OP_F64CEIL,
            3 => op::OP_F64TRUNC,
            _ => unreachable!(),
        });
    }

    pub fn compare_f64(&mut self, operation: u8) {
        self.instruction_body.push(match operation {
            0 => op::OP_F64GT,
            1 => op::OP_F64LT,
            2 => op::OP_F64EQ,
            _ => unreachable!(),
        });
    }

    pub fn arithmetic_f64(&mut self, operation: u8) {
        self.instruction_body.push(match operation {
            0 => op::OP_F64ADD,
            1 => op::OP_F64SUB,
            2 => op::OP_F64MUL,
            3 => op::OP_F64DIV,
            _ => unreachable!(),
        });
    }
    pub fn reinterpret_f64_as_i64(&mut self) {
        self.instruction_body.push(op::OP_I64REINTERPRETF64);
    }

    // Standard SIMD binary encoding: 0xfd, unsigned LEB opcode, immediates.
    pub fn simd(&mut self, opcode: u32) {
        self.instruction_body.push(0xFD);
        write_leb_u32(&mut self.instruction_body, opcode);
    }
    pub fn simd_lane(&mut self, opcode: u32, lane: u8) {
        self.simd(opcode);
        self.instruction_body.push(lane);
    }
    pub fn simd_memory(&mut self, opcode: u32, alignment: u8) {
        self.simd(opcode);
        self.instruction_body.push(alignment);
        self.instruction_body.push(0);
    }
    pub fn simd_shuffle(&mut self, lanes: [u8; 16]) {
        dbg_assert!(lanes.iter().all(|&x| x < 32));
        self.simd(0x0D);
        self.instruction_body.extend_from_slice(&lanes);
    }
    pub fn simd_zero(&mut self) {
        self.simd(0x0C);
        self.instruction_body.extend_from_slice(&[0; 16]);
    }
    /// v128.const
    pub fn const_v128(&mut self, bytes: [u8; 16]) {
        self.simd(0x0C);
        self.instruction_body.extend_from_slice(&bytes);
    }
    pub fn if_v128(&mut self) {
        self.open_block();
        self.instruction_body.push(op::OP_IF);
        self.instruction_body.push(0x7B);
    }

    pub fn const_i32(&mut self, v: i32) {
        self.instruction_body.push(op::OP_I32CONST);
        write_leb_i32(&mut self.instruction_body, v);
    }
    pub fn const_i64(&mut self, v: i64) {
        self.instruction_body.push(op::OP_I64CONST);
        write_leb_i64(&mut self.instruction_body, v);
    }

    pub fn load_fixed_u8(&mut self, addr: u32) {
        self.const_i32(addr as i32);
        self.load_u8(0);
    }
    pub fn load_fixed_u16(&mut self, addr: u32) {
        // doesn't cause a failure in the generated code, but it will be much slower
        dbg_assert!((addr & 1) == 0);

        self.const_i32(addr as i32);
        self.instruction_body.push(op::OP_I32LOAD16U);
        self.instruction_body.push(op::MEM_ALIGN16);
        self.instruction_body.push(0); // immediate offset
    }
    pub fn load_fixed_i32(&mut self, addr: u32) {
        // doesn't cause a failure in the generated code, but it will be much slower
        dbg_assert!((addr & 3) == 0);

        self.const_i32(addr as i32);
        self.load_aligned_i32(0);
    }

    pub fn load_u8(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32LOAD8U);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn load_unaligned_i64(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I64LOAD);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn load_unaligned_i32(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32LOAD);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn load_aligned_f64(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_F64LOAD);
        self.instruction_body.push(op::MEM_ALIGN64);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn load_aligned_i32(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32LOAD);
        self.instruction_body.push(op::MEM_ALIGN32);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_u8(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32STORE8);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_aligned_u16(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32STORE16);
        self.instruction_body.push(op::MEM_ALIGN16);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_aligned_i32(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32STORE);
        self.instruction_body.push(op::MEM_ALIGN32);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_aligned_i64(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I64STORE);
        self.instruction_body.push(op::MEM_ALIGN64);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_unaligned_u16(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I32STORE16);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn store_unaligned_i64(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_I64STORE);
        self.instruction_body.push(op::MEM_NO_ALIGN);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }

    pub fn add_i32(&mut self) { self.instruction_body.push(op::OP_I32ADD); }
    pub fn clz_i32(&mut self) { self.instruction_body.push(op::OP_I32CLZ); }
    pub fn ctz_i32(&mut self) { self.instruction_body.push(op::OP_I32CTZ); }
    pub fn popcnt_i32(&mut self) { self.instruction_body.push(op::OP_I32POPCNT); }
    pub fn clz_i64(&mut self) { self.instruction_body.push(op::OP_I64CLZ); }
    pub fn ctz_i64(&mut self) { self.instruction_body.push(op::OP_I64CTZ); }
    pub fn popcnt_i64(&mut self) { self.instruction_body.push(op::OP_I64POPCNT); }
    pub fn sub_i64(&mut self) { self.instruction_body.push(op::OP_I64SUB); }
    pub fn shr_s_i64(&mut self) { self.instruction_body.push(op::OP_I64SHRS); }
    pub fn ltu_i64(&mut self) { self.instruction_body.push(op::OP_I64LTU); }
    pub fn add_i64(&mut self) { self.instruction_body.push(op::OP_I64ADD); }
    pub fn sub_i32(&mut self) { self.instruction_body.push(op::OP_I32SUB); }
    pub fn and_i32(&mut self) { self.instruction_body.push(op::OP_I32AND); }
    pub fn and_i64(&mut self) { self.instruction_body.push(op::OP_I64AND); }
    pub fn or_i32(&mut self) { self.instruction_body.push(op::OP_I32OR); }
    pub fn or_i64(&mut self) { self.instruction_body.push(op::OP_I64OR); }
    pub fn xor_i32(&mut self) { self.instruction_body.push(op::OP_I32XOR); }
    pub fn xor_i64(&mut self) { self.instruction_body.push(op::OP_I64XOR); }
    pub fn mul_i32(&mut self) { self.instruction_body.push(op::OP_I32MUL); }
    pub fn mul_i64(&mut self) { self.instruction_body.push(op::OP_I64MUL); }

    pub fn rotl_i32(&mut self) { self.instruction_body.push(op::OP_I32ROTL); }
    pub fn rotr_i32(&mut self) { self.instruction_body.push(op::OP_I32ROTR); }
    pub fn rotr_i64(&mut self) { self.instruction_body.push(op::OP_I64ROTR); }

    pub fn shl_i32(&mut self) { self.instruction_body.push(op::OP_I32SHL); }
    pub fn shl_i64(&mut self) { self.instruction_body.push(op::OP_I64SHL); }
    pub fn shr_u_i32(&mut self) { self.instruction_body.push(op::OP_I32SHRU); }
    pub fn shr_u_i64(&mut self) { self.instruction_body.push(op::OP_I64SHRU); }
    pub fn shr_s_i32(&mut self) { self.instruction_body.push(op::OP_I32SHRS); }

    pub fn eq_i32(&mut self) { self.instruction_body.push(op::OP_I32EQ); }
    pub fn eq_i64(&mut self) { self.instruction_body.push(op::OP_I64EQ); }
    pub fn ne_i32(&mut self) { self.instruction_body.push(op::OP_I32NE); }
    pub fn ne_i64(&mut self) { self.instruction_body.push(op::OP_I64NE); }

    pub fn gtu_i32(&mut self) { self.instruction_body.push(op::OP_I32GTU); }
    pub fn geu_i32(&mut self) { self.instruction_body.push(op::OP_I32GEU); }
    pub fn ltu_i32(&mut self) { self.instruction_body.push(op::OP_I32LTU); }
    pub fn leu_i32(&mut self) { self.instruction_body.push(op::OP_I32LEU); }

    pub fn gtu_i64(&mut self) { self.instruction_body.push(op::OP_I64GTU); }

    pub fn reinterpret_i32_as_f32(&mut self) {
        self.instruction_body.push(op::OP_F32REINTERPRETI32);
    }
    /// 0 add, 1 sub, 2 mul, 3 div (as arithmetic_f64)
    pub fn arithmetic_f32(&mut self, operation: u8) {
        self.instruction_body.push(match operation {
            0 => op::OP_F32ADD,
            1 => op::OP_F32SUB,
            2 => op::OP_F32MUL,
            3 => op::OP_F32DIV,
            _ => unreachable!(),
        });
    }
    pub fn reinterpret_i64_as_f64(&mut self) {
        self.instruction_body.push(op::OP_F64REINTERPRETI64);
    }
    //pub fn reinterpret_f64_as_i64(&mut self) {
    //    self.instruction_body.push(op::OP_I64REINTERPRETF64);
    //}
    //pub fn promote_f32_to_f64(&mut self) { self.instruction_body.push(op::OP_F64PROMOTEF32); }
    //pub fn demote_f64_to_f32(&mut self) { self.instruction_body.push(op::OP_F32DEMOTEF64); }
    //pub fn convert_i32_to_f64(&mut self) { self.instruction_body.push(op::OP_F64CONVERTSI32); }
    //pub fn convert_i64_to_f64(&mut self) { self.instruction_body.push(op::OP_F64CONVERTSI64); }
    pub fn extend_unsigned_i32_to_i64(&mut self) {
        self.instruction_body.push(op::OP_I64EXTENDUI32);
    }
    pub fn extend_signed_i32_to_i64(&mut self) { self.instruction_body.push(op::OP_I64EXTENDSI32); }
    pub fn wrap_i64_to_i32(&mut self) { self.instruction_body.push(op::OP_I32WRAPI64); }

    pub fn eqz_i32(&mut self) { self.instruction_body.push(op::OP_I32EQZ); }

    pub fn select(&mut self) { self.instruction_body.push(op::OP_SELECT); }

    pub fn if_i32(&mut self) {
        self.open_block();
        self.instruction_body.push(op::OP_IF);
        self.instruction_body.push(op::TYPE_I32);
    }
    #[allow(dead_code)]
    pub fn if_i64(&mut self) {
        self.open_block();
        self.instruction_body.push(op::OP_IF);
        self.instruction_body.push(op::TYPE_I64);
    }
    #[allow(dead_code)]
    pub fn block_i32(&mut self) {
        self.open_block();
        self.instruction_body.push(op::OP_BLOCK);
        self.instruction_body.push(op::TYPE_I32);
    }

    pub fn if_void(&mut self) {
        self.open_block();
        self.instruction_body.push(op::OP_IF);
        self.instruction_body.push(op::TYPE_VOID_BLOCK);
    }

    pub fn else_(&mut self) {
        dbg_assert!(!self.label_stack.is_empty());
        self.instruction_body.push(op::OP_ELSE);
    }

    pub fn loop_void(&mut self) -> Label {
        self.instruction_body.push(op::OP_LOOP);
        self.instruction_body.push(op::TYPE_VOID_BLOCK);
        self.open_block()
    }

    pub fn block_void(&mut self) -> Label {
        self.instruction_body.push(op::OP_BLOCK);
        self.instruction_body.push(op::TYPE_VOID_BLOCK);
        self.open_block()
    }

    pub fn block_end(&mut self) {
        self.close_block();
        self.instruction_body.push(op::OP_END);
    }

    pub fn return_(&mut self) { self.instruction_body.push(op::OP_RETURN); }

    /// Hint the next instruction (an if or br_if) as likely or unlikely
    /// taken (Wasm branch hinting; engines without it ignore the section).
    pub fn hint(&mut self, likely: bool) {
        self.branch_hints
            .push((self.instruction_body.len(), likely));
    }
    /// Name the module function (shown by profilers).
    pub fn set_function_name(&mut self, function_name: String) {
        self.function_name = Some(function_name);
    }
    /// The module function returns an i32 (every return leaves one).
    pub fn set_entry_result(&mut self) { self.entry_result = true; }
    fn entry_signature(&self) -> Signature {
        if self.entry_result {
            FunctionType::FN1_RET.signature()
        }
        else {
            FunctionType::FN1.signature()
        }
    }
    /// Tail call (Wasm tail-call proposal) of the table entry on the stack,
    /// with the module entry signature; the table is the host's ("e", "t").
    pub fn return_call_indirect_fn1(&mut self) {
        let ty = self.intern_signature(self.entry_signature());
        self.table_import = true;
        self.instruction_body.push(op::OP_RETURN_CALL_INDIRECT);
        write_leb_u32(&mut self.instruction_body, ty);
        self.instruction_body.push(0);
    }

    #[allow(dead_code)]
    pub fn drop_(&mut self) { self.instruction_body.push(op::OP_DROP); }

    pub fn brtable(
        &mut self,
        default_case: Label,
        cases: &mut dyn std::iter::ExactSizeIterator<Item = &Label>,
    ) {
        self.instruction_body.push(op::OP_BRTABLE);
        write_leb_u32(&mut self.instruction_body, wasm_len(cases.len()));
        for case in cases {
            self.write_label(*case);
        }
        self.write_label(default_case);
    }

    pub fn br(&mut self, label: Label) {
        self.instruction_body.push(op::OP_BR);
        self.write_label(label);
    }
    pub fn br_if(&mut self, label: Label) {
        self.instruction_body.push(op::OP_BRIF);
        self.write_label(label);
    }

    fn write_label(&mut self, label: Label) {
        let depth = *self.label_to_depth.get(&label).unwrap();
        dbg_assert!(depth <= self.label_stack.len());
        write_leb_u32(
            &mut self.instruction_body,
            wasm_len(self.label_stack.len() - depth),
        );
    }

    pub fn unreachable(&mut self) { self.instruction_body.push(op::OP_UNREACHABLE) }

    /// An instruction without immediates (x64 page tier: i64 compares,
    /// rotates, extensions). The caller keeps the operand stack typed.
    pub fn op(&mut self, opcode: u8) { self.instruction_body.push(opcode); }
    /// A load or store with an explicit alignment hint and offset immediate.
    pub fn memory_op(&mut self, opcode: u8, align: u8, byte_offset: u32) {
        self.instruction_body.push(opcode);
        self.instruction_body.push(align);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }
}

/// Guest RAM accesses of generated code. In the parallel build (cores in
/// workers, crate::parallel) they are sequentially consistent atomics, which
/// keep x86's load/store order on weakly ordered hosts; the address must then
/// be naturally aligned (the RAM guards check it and take the slow path
/// otherwise). In the normal build they are the plain unaligned accesses.
impl WasmBuilder {
    pub const ATOMIC_GUEST_MEMORY: bool = cfg!(feature = "parallel");

    fn atomic_op(&mut self, opcode: u8, align: u8, byte_offset: u32) {
        self.instruction_body.push(0xFE);
        self.instruction_body.push(opcode);
        self.instruction_body.push(align);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }
    /// A full barrier (MFENCE and the like); nothing in the normal build
    pub fn guest_fence(&mut self) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.instruction_body.extend_from_slice(&[0xFE, 0x03, 0x00]);
        }
    }
    pub fn guest_load_u8(&mut self, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.atomic_op(0x12, 0, byte_offset)
        }
        else {
            self.load_u8(byte_offset)
        }
    }
    pub fn guest_load_i32(&mut self, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.atomic_op(0x10, 2, byte_offset)
        }
        else {
            self.load_unaligned_i32(byte_offset)
        }
    }
    pub fn guest_load_i64(&mut self, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.atomic_op(0x11, 3, byte_offset)
        }
        else {
            self.load_unaligned_i64(byte_offset)
        }
    }
    /// i64 loads of 8/16/32 zero-extended bits (the x64 page tier)
    pub fn guest_load_i64_bits(&mut self, bits: u32, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            match bits {
                8 => self.atomic_op(0x14, 0, byte_offset),
                16 => self.atomic_op(0x15, 1, byte_offset),
                32 => self.atomic_op(0x16, 2, byte_offset),
                _ => self.atomic_op(0x11, 3, byte_offset),
            }
        }
        else {
            match bits {
                8 => self.memory_op(op::OP_I64LOAD8U, op::MEM_NO_ALIGN, byte_offset),
                16 => self.memory_op(op::OP_I64LOAD16U, op::MEM_NO_ALIGN, byte_offset),
                32 => self.memory_op(op::OP_I64LOAD32U, op::MEM_NO_ALIGN, byte_offset),
                _ => self.memory_op(op::OP_I64LOAD, op::MEM_NO_ALIGN, byte_offset),
            }
        }
    }
    pub fn guest_store_i64(&mut self, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.atomic_op(0x18, 3, byte_offset)
        }
        else {
            self.store_unaligned_i64(byte_offset)
        }
    }
    /// i64 stores of the low 8/16/32/64 bits (the x64 page tier)
    pub fn guest_store_i64_bits(&mut self, bits: u32, byte_offset: u32) {
        if Self::ATOMIC_GUEST_MEMORY {
            match bits {
                8 => self.atomic_op(0x1B, 0, byte_offset),
                16 => self.atomic_op(0x1C, 1, byte_offset),
                32 => self.atomic_op(0x1D, 2, byte_offset),
                _ => self.atomic_op(0x18, 3, byte_offset),
            }
        }
        else {
            match bits {
                8 => self.memory_op(op::OP_I64STORE8, op::MEM_NO_ALIGN, byte_offset),
                16 => self.memory_op(op::OP_I64STORE16, op::MEM_NO_ALIGN, byte_offset),
                32 => self.memory_op(op::OP_I64STORE32, op::MEM_NO_ALIGN, byte_offset),
                _ => self.memory_op(op::OP_I64STORE, op::MEM_NO_ALIGN, byte_offset),
            }
        }
    }
    /// A v128 guest load: two ordered 8-byte halves in the parallel build
    /// (address 8-aligned), one v128.load otherwise. [address] -> v128
    pub fn guest_load_v128(&mut self, scratch: &WasmLocal) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.tee_local(scratch);
            self.guest_load_i64(0);
            self.simd(0x12); // i64x2.splat
            self.get_local(scratch);
            self.guest_load_i64(8);
            self.simd_lane(0x1E, 1); // i64x2.replace_lane
        }
        else {
            self.simd_memory(0x00, 0);
        }
    }
    /// A v128 guest store. [address, value] ->
    pub fn guest_store_v128(&mut self, address: &WasmLocal, value: &WasmLocalV128) {
        if Self::ATOMIC_GUEST_MEMORY {
            self.get_local(address);
            self.get_local_v128(value);
            self.simd_lane(0x1D, 0); // i64x2.extract_lane
            self.guest_store_i64(0);
            self.get_local(address);
            self.get_local_v128(value);
            self.simd_lane(0x1D, 1);
            self.guest_store_i64(8);
        }
        else {
            self.get_local(address);
            self.get_local_v128(value);
            self.simd_memory(0x0B, 0);
        }
    }
}

/// Scalar floating-point forms used by the experimental IR backend's x87 path.
#[allow(dead_code)]
impl WasmBuilder {
    pub fn reinterpret_f32_as_i32(&mut self) {
        self.instruction_body.push(op::OP_I32REINTERPRETF32);
    }
    pub fn promote_f32_to_f64(&mut self) { self.instruction_body.push(op::OP_F64PROMOTEF32); }
    pub fn demote_f64_to_f32(&mut self) { self.instruction_body.push(op::OP_F32DEMOTEF64); }
    pub fn convert_i32_to_f64(&mut self) { self.instruction_body.push(op::OP_F64CONVERTSI32); }
    pub fn convert_i64_to_f64(&mut self) { self.instruction_body.push(op::OP_F64CONVERTSI64); }
    /// Traps outside the i32 range: callers range-check first.
    pub fn trunc_f64_to_i32(&mut self) { self.instruction_body.push(op::OP_I32TRUNCSF64); }
    /// Traps outside the i64 range: callers range-check first.
    pub fn trunc_f64_to_i64(&mut self) { self.instruction_body.push(op::OP_I64TRUNCSF64); }
    pub fn const_f32(&mut self, v: f32) {
        self.instruction_body.push(op::OP_F32CONST);
        self.instruction_body.extend_from_slice(&v.to_le_bytes());
    }
    pub fn const_f64(&mut self, v: f64) {
        self.instruction_body.push(op::OP_F64CONST);
        self.instruction_body.extend_from_slice(&v.to_le_bytes());
    }
    pub fn ge_f64(&mut self) { self.instruction_body.push(op::OP_F64GE); }
    pub fn le_f64(&mut self) { self.instruction_body.push(op::OP_F64LE); }
    pub fn ne_f64(&mut self) { self.instruction_body.push(op::OP_F64NE); }
    pub fn store_aligned_f64(&mut self, byte_offset: u32) {
        self.instruction_body.push(op::OP_F64STORE);
        self.instruction_body.push(op::MEM_ALIGN64);
        write_leb_u32(&mut self.instruction_body, byte_offset);
    }
}

#[cfg(test)]
mod tests {
    use super::{Signature, WasmBuilder, WasmType, WASM_MODULE_ARGUMENT_COUNT};
    use std::fs::File;
    use std::io::Write;

    #[test]
    fn import_table_management() {
        let mut w = WasmBuilder::new();
        let none = Signature::new(&[], &[]);
        let one = Signature::new(&[WasmType::I32], &[]);
        let two = Signature::new(&[WasmType::I32, WasmType::I32], &[]);

        assert_eq!(0, w.get_fn_idx_signature("foo", none.clone()));
        assert_eq!(1, w.get_fn_idx_signature("bar", one));
        assert_eq!(0, w.get_fn_idx_signature("foo", none));
        assert_eq!(2, w.get_fn_idx_signature("baz", two));
    }

    // tests/rust/verify-wasmgen-dummy-output.js instantiates and runs this module.
    #[test]
    fn builder_test() {
        let mut m = WasmBuilder::new();

        m.const_i32(2);

        m.call_signature("baz", Signature::new(&[WasmType::I32], &[WasmType::I32]));
        m.call_signature("foo", Signature::new(&[WasmType::I32], &[]));

        m.const_i32(10);
        let local1 = m.alloc_local();
        m.tee_local(&local1); // local1 = 10

        m.const_i32(20);
        m.add_i32();
        let local2 = m.alloc_local();
        m.tee_local(&local2); // local2 = 30

        m.free_local(local1);

        let local3 = m.alloc_local();
        assert_eq!(local3.idx(), WASM_MODULE_ARGUMENT_COUNT);

        m.free_local(local2);
        m.free_local(local3);

        m.const_i32(30);
        m.ne_i32();
        m.if_void();
        m.unreachable();
        m.block_end();

        m.finish();

        let mut f = File::create("build/dummy_output.wasm").expect("creating dummy_output.wasm");
        f.write_all(&m.output).expect("write dummy_output.wasm");
    }
}

#[cfg(test)]
#[path = "../../../tests/wasmgen/builder.rs"]
mod capacity_tests;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/rust/wasmgen/wasm_opcodes.rs                                                         0000644 0000000 0000000 00000011670 00000000000 016147  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       macro_rules! c {
    ($x:ident, $y:expr) => {
        #[allow(dead_code)]
        pub const $x: u8 = $y;
    };
}

// https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#high-level-structure
c!(WASM_VERSION, 0x1);

// Section codes
c!(SC_TYPE, 1);
c!(SC_IMPORT, 2);
c!(SC_FUNCTION, 3);
c!(SC_TABLE, 4);
c!(SC_MEMORY, 5);
c!(SC_GLOBAL, 6);
c!(SC_EXPORT, 7);
c!(SC_START, 8);
c!(SC_ELEMENT, 9);
c!(SC_CODE, 10);
c!(SC_DATA, 11);

// https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#language-types
c!(TYPE_I32, 0x7f);
c!(TYPE_I64, 0x7e);
c!(TYPE_F32, 0x7d);
c!(TYPE_F64, 0x7c);
c!(TYPE_ANYFUNC, 0x70);
c!(TYPE_FUNC, 0x60);
c!(TYPE_VOID_BLOCK, 0x40);

// https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#external_kind
c!(EXT_FUNCTION, 0);
c!(EXT_TABLE, 1);
c!(EXT_MEMORY, 2);
c!(EXT_GLOBAL, 3);

// Taken from wasm2ast's source code and modified with vim magic
c!(OP_UNREACHABLE, 0x00);
c!(OP_NOP, 0x01);
c!(OP_BLOCK, 0x02);
c!(OP_LOOP, 0x03);
c!(OP_IF, 0x04);
c!(OP_ELSE, 0x05);
c!(OP_TRY, 0x06);
c!(OP_CATCH, 0x07);
c!(OP_THROW, 0x08);
c!(OP_RETHROW, 0x09);
c!(OP_CATCHALL, 0x0a);
c!(OP_END, 0x0b);
c!(OP_BR, 0x0c);
c!(OP_BRIF, 0x0d);
c!(OP_BRTABLE, 0x0e);
c!(OP_RETURN, 0x0f);
c!(OP_CALL, 0x10);
c!(OP_CALLINDIRECT, 0x11);
c!(OP_RETURN_CALL_INDIRECT, 0x13);
c!(OP_DROP, 0x1a);
c!(OP_SELECT, 0x1b);
c!(OP_GETLOCAL, 0x20);
c!(OP_SETLOCAL, 0x21);
c!(OP_TEELOCAL, 0x22);
c!(OP_GETGLOBAL, 0x23);
c!(OP_SETGLOBAL, 0x24);
c!(OP_I32LOAD, 0x28);
c!(OP_I64LOAD, 0x29);
c!(OP_F32LOAD, 0x2a);
c!(OP_F64LOAD, 0x2b);
c!(OP_I32LOAD8S, 0x2c);
c!(OP_I32LOAD8U, 0x2d);
c!(OP_I32LOAD16S, 0x2e);
c!(OP_I32LOAD16U, 0x2f);
c!(OP_I64LOAD8S, 0x30);
c!(OP_I64LOAD8U, 0x31);
c!(OP_I64LOAD16S, 0x32);
c!(OP_I64LOAD16U, 0x33);
c!(OP_I64LOAD32S, 0x34);
c!(OP_I64LOAD32U, 0x35);
c!(OP_I32STORE, 0x36);
c!(OP_I64STORE, 0x37);
c!(OP_F32STORE, 0x38);
c!(OP_F64STORE, 0x39);
c!(OP_I32STORE8, 0x3a);
c!(OP_I32STORE16, 0x3b);
c!(OP_I64STORE8, 0x3c);
c!(OP_I64STORE16, 0x3d);
c!(OP_I64STORE32, 0x3e);
c!(OP_CURRENTMEMORY, 0x3f);
c!(OP_GROWMEMORY, 0x40);
c!(OP_I32CONST, 0x41);
c!(OP_I64CONST, 0x42);
c!(OP_F32CONST, 0x43);
c!(OP_F64CONST, 0x44);
c!(OP_I32EQZ, 0x45);
c!(OP_I32EQ, 0x46);
c!(OP_I32NE, 0x47);
c!(OP_I32LTS, 0x48);
c!(OP_I32LTU, 0x49);
c!(OP_I32GTS, 0x4a);
c!(OP_I32GTU, 0x4b);
c!(OP_I32LES, 0x4c);
c!(OP_I32LEU, 0x4d);
c!(OP_I32GES, 0x4e);
c!(OP_I32GEU, 0x4f);
c!(OP_I64EQZ, 0x50);
c!(OP_I64EQ, 0x51);
c!(OP_I64NE, 0x52);
c!(OP_I64LTS, 0x53);
c!(OP_I64LTU, 0x54);
c!(OP_I64GTS, 0x55);
c!(OP_I64GTU, 0x56);
c!(OP_I64LES, 0x57);
c!(OP_I64LEU, 0x58);
c!(OP_I64GES, 0x59);
c!(OP_I64GEU, 0x5a);
c!(OP_F32EQ, 0x5b);
c!(OP_F32NE, 0x5c);
c!(OP_F32LT, 0x5d);
c!(OP_F32GT, 0x5e);
c!(OP_F32LE, 0x5f);
c!(OP_F32GE, 0x60);
c!(OP_F64EQ, 0x61);
c!(OP_F64NE, 0x62);
c!(OP_F64LT, 0x63);
c!(OP_F64GT, 0x64);
c!(OP_F64LE, 0x65);
c!(OP_F64GE, 0x66);
c!(OP_I32CLZ, 0x67);
c!(OP_I32CTZ, 0x68);
c!(OP_I32POPCNT, 0x69);
c!(OP_I32ADD, 0x6a);
c!(OP_I32SUB, 0x6b);
c!(OP_I32MUL, 0x6c);
c!(OP_I32DIVS, 0x6d);
c!(OP_I32DIVU, 0x6e);
c!(OP_I32REMS, 0x6f);
c!(OP_I32REMU, 0x70);
c!(OP_I32AND, 0x71);
c!(OP_I32OR, 0x72);
c!(OP_I32XOR, 0x73);
c!(OP_I32SHL, 0x74);
c!(OP_I32SHRS, 0x75);
c!(OP_I32SHRU, 0x76);
c!(OP_I32ROTL, 0x77);
c!(OP_I32ROTR, 0x78);
c!(OP_I64CLZ, 0x79);
c!(OP_I64CTZ, 0x7a);
c!(OP_I64POPCNT, 0x7b);
c!(OP_I64ADD, 0x7c);
c!(OP_I64SUB, 0x7d);
c!(OP_I64MUL, 0x7e);
c!(OP_I64DIVS, 0x7f);
c!(OP_I64DIVU, 0x80);
c!(OP_I64REMS, 0x81);
c!(OP_I64REMU, 0x82);
c!(OP_I64AND, 0x83);
c!(OP_I64OR, 0x84);
c!(OP_I64XOR, 0x85);
c!(OP_I64SHL, 0x86);
c!(OP_I64SHRS, 0x87);
c!(OP_I64SHRU, 0x88);
c!(OP_I64ROTL, 0x89);
c!(OP_I64ROTR, 0x8a);
c!(OP_F32ABS, 0x8b);
c!(OP_F32NEG, 0x8c);
c!(OP_F32CEIL, 0x8d);
c!(OP_F32FLOOR, 0x8e);
c!(OP_F32TRUNC, 0x8f);
c!(OP_F32NEAREST, 0x90);
c!(OP_F32SQRT, 0x91);
c!(OP_F32ADD, 0x92);
c!(OP_F32SUB, 0x93);
c!(OP_F32MUL, 0x94);
c!(OP_F32DIV, 0x95);
c!(OP_F32MIN, 0x96);
c!(OP_F32MAX, 0x97);
c!(OP_F32COPYSIGN, 0x98);
c!(OP_F64ABS, 0x99);
c!(OP_F64NEG, 0x9a);
c!(OP_F64CEIL, 0x9b);
c!(OP_F64FLOOR, 0x9c);
c!(OP_F64TRUNC, 0x9d);
c!(OP_F64NEAREST, 0x9e);
c!(OP_F64SQRT, 0x9f);
c!(OP_F64ADD, 0xa0);
c!(OP_F64SUB, 0xa1);
c!(OP_F64MUL, 0xa2);
c!(OP_F64DIV, 0xa3);
c!(OP_F64MIN, 0xa4);
c!(OP_F64MAX, 0xa5);
c!(OP_F64COPYSIGN, 0xa6);
c!(OP_I32WRAPI64, 0xa7);
c!(OP_I32TRUNCSF32, 0xa8);
c!(OP_I32TRUNCUF32, 0xa9);
c!(OP_I32TRUNCSF64, 0xaa);
c!(OP_I32TRUNCUF64, 0xab);
c!(OP_I64EXTENDSI32, 0xac);
c!(OP_I64EXTENDUI32, 0xad);
c!(OP_I64TRUNCSF32, 0xae);
c!(OP_I64TRUNCUF32, 0xaf);
c!(OP_I64TRUNCSF64, 0xb0);
c!(OP_I64TRUNCUF64, 0xb1);
c!(OP_F32CONVERTSI32, 0xb2);
c!(OP_F32CONVERTUI32, 0xb3);
c!(OP_F32CONVERTSI64, 0xb4);
c!(OP_F32CONVERTUI64, 0xb5);
c!(OP_F32DEMOTEF64, 0xb6);
c!(OP_F64CONVERTSI32, 0xb7);
c!(OP_F64CONVERTUI32, 0xb8);
c!(OP_F64CONVERTSI64, 0xb9);
c!(OP_F64CONVERTUI64, 0xba);
c!(OP_F64PROMOTEF32, 0xbb);
c!(OP_I32REINTERPRETF32, 0xbc);
c!(OP_I64REINTERPRETF64, 0xbd);
c!(OP_F32REINTERPRETI32, 0xbe);
c!(OP_F64REINTERPRETI64, 0xbf);

c!(MEM_NO_ALIGN, 0);
c!(MEM_ALIGN16, 1);
c!(MEM_ALIGN32, 2);
c!(MEM_ALIGN64, 3);
                                                                        source/v64/src/rust/x64/debug.rs                                                                    0000644 0000000 0000000 00000006661 00000000000 013536  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Instruction-boundary debug delivery. Pending data matches are scratch:
//! one guest instruction cannot yield or switch cores before `finish`.
use super::{memory::Fault, state};
use crate::cpu::global_pointers as gp;
static mut PENDING: u8 = 0;

fn overlaps(address: u64, size: usize, watched: u64, length: u64) -> bool {
    (0..size).any(|byte| address.wrapping_add(byte as u64).wrapping_sub(watched) < length)
}
pub unsafe fn begin() -> Result<(), Fault> {
    PENDING = 0;
    // RF is kept in the raw FLAGS word; only arithmetic flags are lazy.
    if *gp::interrupt_shadow != 0 || *gp::flags & 0x10000 != 0 {
        return Ok(());
    }
    let control = state::read_dr(7);
    if control & 0xFF == 0 {
        return Ok(());
    }
    let mut matched = 0;
    for index in 0..4 {
        if control >> (index * 2) & 3 != 0
            && control >> (16 + index * 4) & 3 == 0
            && state::read_dr(index) == state::read_rip()
        {
            matched |= 1 << index;
        }
    }
    if matched != 0 {
        // A code breakpoint fault precedes faults from fetching the
        // instruction (SDM Vol.3A §6.9, Table 6-2: priority 7 before 8).
        state::write_dr(6, state::read_dr(6) | matched);
        state::write_dr(7, control & !0x2000);
        state::write_flags64(state::read_flags64() | 0x10000);
        return Err(Fault {
            vector: 1,
            error: None,
            address: None,
        });
    }
    Ok(())
}
pub unsafe fn data(address: u64, size: usize, write: bool) {
    let control = state::read_dr(7);
    if control & 255 == 0 {
        return;
    }
    for index in 0..4 {
        if control >> (index * 2) & 3 == 0 {
            continue;
        }
        let kind = control >> (16 + index * 4) & 3;
        if kind != 3 && !(kind == 1 && write) {
            continue;
        }
        let length = [1, 2, 8, 4][(control >> (18 + index * 4) & 3) as usize];
        // The architectural comparison uses the naturally aligned range.
        let watched = state::read_dr(index) & !(length - 1);
        if overlaps(address, size, watched, length) {
            PENDING |= 1 << index;
        }
    }
}
pub unsafe fn io(port: u16, size: usize) {
    if state::read_cr(4) & 8 == 0 {
        return;
    }
    let control = state::read_dr(7);
    for index in 0..4 {
        if control >> (index * 2) & 3 == 0 || control >> (16 + index * 4) & 3 != 2 {
            continue;
        }
        let length = [1, 2, 8, 4][(control >> (18 + index * 4) & 3) as usize];
        if overlaps(
            port as u64,
            size,
            state::read_dr(index) & !(length - 1),
            length,
        ) {
            PENDING |= 1 << index;
        }
    }
}
pub unsafe fn finish(completed: bool, single_step: bool) -> bool {
    let matches = PENDING;
    PENDING = 0;
    if !completed || *gp::interrupt_shadow != 0 || matches == 0 && !single_step {
        return false;
    }
    state::write_dr(
        6,
        state::read_dr(6) | matches as u64 | if single_step { 1 << 14 } else { 0 },
    );
    state::write_dr(7, state::read_dr(7) & !0x2000);
    true
}
#[cfg(test)]
mod tests {
    use super::overlaps;
    #[test]
    fn byte_ranges_cover_high_addresses_without_low_aliases() {
        assert!(overlaps(0xFFFF800000001FFE, 8, 0xFFFF800000002000, 4));
        assert!(!overlaps(0x1FFE, 8, 0xFFFF800000002000, 4));
        assert!(!overlaps(0x1000, 8, 0x1008, 1));
        assert!(overlaps(u64::MAX, 2, 0, 1));
    }
}
                                                                               source/v64/src/rust/x64/decode.rs                                                                   0000644 0000000 0000000 00000156066 00000000000 013700  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! One byte decoder for runtime fetch and immutable compiler snapshots. It
//! never performs memory I/O; `decode_with` requests only the bytes required by
//! the opcode and preserves fetch-fault versus #UD/#GP ordering.
use super::state::{ExecutionMode, GuestIp};
use crate::decode::{Encoding, ImmediateKind};

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct PrefixState {
    pub operand: bool,
    pub address: bool,
    pub lock: bool,
    pub rep: Option<u8>,
    pub segment: Option<u8>,
    pub rex: Option<u8>,
}
impl PrefixState {
    pub fn w(self) -> bool { self.rex.is_some_and(|r| r & 8 != 0) }
    pub fn r(self) -> u8 { self.rex.map_or(0, |r| (r >> 2 & 1) << 3) }
    pub fn x(self) -> u8 { self.rex.map_or(0, |r| (r >> 1 & 1) << 3) }
    pub fn b(self) -> u8 { self.rex.map_or(0, |r| (r & 1) << 3) }
    /// Returns true only if byte is a prefix in the current execution mode.
    pub fn consume(&mut self, byte: u8, mode: ExecutionMode) -> bool {
        if mode.is_long() && (0x40..=0x4F).contains(&byte) {
            self.rex = Some(byte);
            return true;
        }
        use crate::decode_rules::Prefix;
        match crate::decode_rules::prefix(byte) {
            Some(Prefix::Operand) => self.operand = true,
            Some(Prefix::Address) => self.address = true,
            Some(Prefix::Lock) => self.lock = true,
            Some(Prefix::Repne) => self.rep = Some(0xF2),
            Some(Prefix::Rep) => self.rep = Some(0xF3),
            Some(Prefix::Segment(s)) => self.segment = Some(s),
            None => return false,
        }
        // A legacy prefix after REX makes the earlier REX ineffective.
        self.rex = None;
        true
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ByteRegister {
    Low(u8),
    HighLegacy(u8),
}
pub fn byte_register(encoded: u8, rex_present: bool) -> ByteRegister {
    assert!(encoded < 16 && (rex_present || encoded < 8));
    if !rex_present && (4..8).contains(&encoded) {
        ByteRegister::HighLegacy(encoded - 4)
    }
    else {
        ByteRegister::Low(encoded)
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AddressBase {
    None,
    Register(u8),
    NextRip,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AddressExpr {
    pub base: AddressBase,
    pub index: Option<u8>,
    pub scale: u8,
    pub displacement: i64,
    pub address_size: u8,
    pub segment: u8,
}
impl AddressExpr {
    /// Segmentation/canonical/page permission checks happen at the access. In long
    /// mode only FS/GS have a nonzero effective base; address32 wraps first.
    pub fn offset(self, registers: &[u64; 16], next_rip: GuestIp) -> u64 {
        let base = match self.base {
            AddressBase::None => 0,
            AddressBase::Register(r) => registers[r as usize],
            AddressBase::NextRip => next_rip.0,
        };
        let value = base
            .wrapping_add(
                self.index
                    .map_or(0, |r| registers[r as usize].wrapping_shl(self.scale as u32)),
            )
            .wrapping_add(self.displacement as u64);
        match self.address_size {
            16 => value as u16 as u64,
            32 => value as u32 as u64,
            64 => value,
            _ => unreachable!(),
        }
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Immediate {
    pub value: u64,
    pub encoded_bytes: u8,
    pub sign_extended: bool,
}
#[derive(Clone, Copy, Debug)]
pub struct Decoded {
    pub encoding: &'static Encoding,
    pub opcode: u32,
    pub prefixes: PrefixState,
    pub mode: ExecutionMode,
    pub operand_size: u8,
    pub address_size: u8,
    pub length: u8,
    pub start: GuestIp,
    pub next: GuestIp,
    pub modrm: Option<u8>,
    pub reg: Option<u8>,
    pub rm_register: Option<u8>,
    pub opcode_register: Option<u8>,
    pub address: Option<AddressExpr>,
    pub immediate: Option<Immediate>,
    pub extra_immediate: Option<u16>,
    pub bytes: [u8; 15],
    /// The VEX prefix (decode_rules::is_vex); `opcode` is its key
    pub vex: Option<crate::decode_rules::Vex>,
}
impl Decoded {
    /// Remove the catalog's mandatory/repeat prefix key while retaining the
    /// 0F opcode map. Executors still inspect `opcode` to distinguish SIMD
    /// variants and `prefixes` for architectural REP/operand semantics.
    pub fn base_opcode(&self) -> u32 {
        if self.vex.is_some() {
            self.opcode
        }
        else if matches!(self.opcode >> 8 & 0xFFFF, 0x0F38 | 0x0F3A) {
            self.opcode & 0xFF_FFFF
        }
        else if self.opcode & 0xFF00 == 0x0F00 {
            self.opcode & 0xFFFF
        }
        else {
            self.opcode & 0xFF
        }
    }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DecodeError<E = ()> {
    Fetch { offset: u8, error: E },
    TooLong,
    InvalidOpcode,
    UnknownOpcode(u32),
}
struct Cursor<F> {
    fetch: F,
    bytes: [u8; 15],
    length: u8,
}
impl<F, E> Cursor<F>
where
    F: FnMut(u8) -> Result<u8, E>,
{
    fn byte(&mut self) -> Result<u8, DecodeError<E>> {
        if self.length == 15 {
            return Err(DecodeError::TooLong);
        }
        let byte = (self.fetch)(self.length).map_err(|error| DecodeError::Fetch {
            offset: self.length,
            error,
        })?;
        self.bytes[self.length as usize] = byte;
        self.length += 1;
        Ok(byte)
    }
    /// The next byte, which the instruction includes whatever it is
    fn peek(&mut self) -> Result<u8, DecodeError<E>> {
        if self.length == 15 {
            return Err(DecodeError::TooLong);
        }
        (self.fetch)(self.length).map_err(|error| DecodeError::Fetch {
            offset: self.length,
            error,
        })
    }
    fn integer(&mut self, bytes: u8) -> Result<u64, DecodeError<E>> {
        let mut value = 0;
        for shift in 0..bytes {
            value |= (self.byte()? as u64) << (shift * 8);
        }
        Ok(value)
    }
    fn signed(&mut self, bytes: u8) -> Result<i64, DecodeError<E>> {
        let value = self.integer(bytes)?;
        Ok(((value << (64 - bytes * 8)) as i64) >> (64 - bytes * 8))
    }
}
fn candidates(opcode: u32) -> &'static [Encoding] {
    let all = crate::decode::encodings();
    let first = all.partition_point(|row| row.opcode < opcode);
    let last = all.partition_point(|row| row.opcode <= opcode);
    &all[first..last]
}
fn invalid_long_opcode(opcode: u32) -> bool {
    matches!(
        opcode,
        0x06 | 0x07
            | 0x0E
            | 0x16
            | 0x17
            | 0x1E
            | 0x1F
            | 0x27
            | 0x2F
            | 0x37
            | 0x3F
            | 0x60
            | 0x61
            | 0x62
            | 0x82
            | 0x9A
            | 0xCE
            | 0xD4
            | 0xD5
            | 0xD6
            | 0xEA
            | 0x0F24
            | 0x0F26
    )
}
fn operand_size(mode: ExecutionMode, prefixes: PrefixState, opcode: u32, modrm: Option<u8>) -> u8 {
    if !mode.is_long() {
        return if prefixes.operand { 48 - mode.operand_default() } else { mode.operand_default() };
    }
    let group = modrm.map_or(0, |m| m >> 3 & 7);
    // Near CALL/JMP/RET, CR/DR transfers, and IRETQ's REX.W are distinct from
    // ordinary GPR defaults. PUSH/POP/ENTER/LEAVE permit a 16-bit override.
    if matches!(opcode, 0xE8 | 0xE9 | 0xEB | 0xC2 | 0xC3 | 0x0F20..=0x0F23)
        || opcode == 0xFF && matches!(group, 2 | 4)
    {
        return 64;
    }
    if opcode == 0x0FC7 && group == 1 {
        return if prefixes.w() { 128 } else { 64 };
    }
    if prefixes.w() {
        return 64;
    }
    if prefixes.operand {
        return 16;
    }
    if matches!(
        opcode,
        0x50..=0x5F
            | 0x68
            | 0x6A
            | 0x8F
            | 0x9C
            | 0x9D
            | 0xC8
            | 0xC9
            | 0x0FA0
            | 0x0FA1
            | 0x0FA8
            | 0x0FA9
    ) || opcode == 0xFF && group == 6
    {
        64
    }
    else {
        32
    }
}
fn address<F, E>(
    c: &mut Cursor<F>,
    m: u8,
    size: u8,
    p: PrefixState,
    mode: ExecutionMode,
) -> Result<AddressExpr, DecodeError<E>>
where
    F: FnMut(u8) -> Result<u8, E>,
{
    let md = m >> 6;
    let rm = m & 7;
    if size == 16 {
        let rule = crate::decode_rules::address_form(m, size, None);
        let disp = match rule.displacement_bytes {
            0 => 0,
            1 => c.signed(1)?,
            2 if md == 2 => c.signed(2)?,
            2 => c.integer(2)? as i64,
            _ => unreachable!(),
        };
        return Ok(AddressExpr {
            base: rule.base.map_or(AddressBase::None, AddressBase::Register),
            index: rule.index,
            scale: 0,
            displacement: disp,
            address_size: size,
            segment: p.segment.unwrap_or(rule.segment),
        });
    }
    let mut base = AddressBase::Register(rm | p.b());
    let mut index = None;
    let mut scale = 0;
    let mut disp32 = md == 2;
    if rm == 4 {
        let sib = c.byte()?;
        let raw_base = sib & 7;
        let raw_index = sib >> 3 & 7;
        scale = sib >> 6;
        if raw_index != 4 || p.x() != 0 {
            index = Some(raw_index | p.x());
        }
        if md == 0 && raw_base == 5 {
            base = AddressBase::None;
            disp32 = true;
        }
        else {
            base = AddressBase::Register(raw_base | p.b());
        }
    }
    else if md == 0 && rm == 5 {
        base = if mode.is_long() { AddressBase::NextRip } else { AddressBase::None };
        disp32 = true;
    }
    let displacement = if md == 1 {
        c.signed(1)?
    }
    else if disp32 {
        c.signed(4)?
    }
    else {
        0
    };
    let segment = p
        .segment
        .unwrap_or(if matches!(base,AddressBase::Register(r) if r == 4 || r == 5) { 2 } else { 3 });
    Ok(AddressExpr {
        base,
        index,
        scale,
        displacement,
        address_size: size,
        segment,
    })
}

pub fn decode(bytes: &[u8], start: GuestIp, mode: ExecutionMode) -> Result<Decoded, DecodeError> {
    decode_with(start, mode, |offset| {
        bytes.get(offset as usize).copied().ok_or(())
    })
}
pub fn decode_with<F, E>(
    start: GuestIp,
    mode: ExecutionMode,
    fetch: F,
) -> Result<Decoded, DecodeError<E>>
where
    F: FnMut(u8) -> Result<u8, E>,
{
    let mut c = Cursor {
        fetch,
        bytes: [0; 15],
        length: 0,
    };
    let mut prefixes = PrefixState::default();
    let first = loop {
        let b = c.byte()?;
        if !prefixes.consume(b, mode) {
            break b;
        }
    };
    // C4/C5: a VEX prefix in 64-bit mode, and with a register ModRM byte in
    // protected and compatibility mode (decode_rules::is_vex). Real and
    // virtual-8086 mode have no VEX: LES/LDS, whose register form is #UD.
    if (first == 0xC4 || first == 0xC5)
        && !matches!(mode, ExecutionMode::Real | ExecutionMode::Vm86)
        && crate::decode_rules::is_vex(c.peek()?, mode.is_long())
    {
        return decode_vex(c, start, mode, prefixes, first);
    }
    // 0F 38 and 0F 3A lead to the three-byte maps (key 0x0F38xx, 0x0F3Axx)
    let base_opcode = if first == 0x0F {
        let second = c.byte()?;
        if second == 0x38 || second == 0x3A {
            0x0F0000 | (second as u32) << 8 | c.byte()? as u32
        }
        else {
            0x0F00 | second as u32
        }
    }
    else {
        first as u32
    };
    if mode.is_long() && invalid_long_opcode(base_opcode) {
        return Err(DecodeError::InvalidOpcode);
    }
    if !mode.is_long() && matches!(base_opcode, 0x0F05 | 0x0F07) {
        return Err(DecodeError::InvalidOpcode);
    }
    // The 66/F2/F3 variants of the opcode in the shared catalogue, chosen by
    // the rule all three decoders share (decode_rules::mandatory_variant): a
    // refining prefix without a row of its own, a row whose CPUID feature is
    // absent or an unimplemented row is #UD after the ModRM byte, as in the
    // 32-bit interpreter.
    use crate::prefix::{PREFIX_66, PREFIX_F2, PREFIX_F3};
    let shift = if base_opcode > 0xFFFF {
        24
    }
    else if first == 0x0F {
        16
    }
    else {
        8
    };
    let variants = [(0x66u32, PREFIX_66), (0xF2, PREFIX_F2), (0xF3, PREFIX_F3)];
    let mut available = 0;
    let mut refining = candidates(base_opcode)
        .iter()
        .fold(0, |m, row| m | row.refining);
    let mut family = candidates(base_opcode).first();
    for (prefix, mask) in variants {
        if prefix != 0x66 || first == 0x0F {
            let rows = candidates(prefix << shift | base_opcode);
            refining |= rows.iter().fold(0, |m, row| m | row.refining);
            family = family.or(rows.first());
            if rows.iter().any(Encoding::exists) {
                available |= mask;
            }
        }
    }
    let flags = if prefixes.operand { PREFIX_66 } else { 0 }
        | match prefixes.rep {
            Some(0xF2) => PREFIX_F2,
            Some(0xF3) => PREFIX_F3,
            _ => 0,
        };
    use crate::decode_rules::Variant;
    let variant = crate::decode_rules::mandatory_variant(flags, available, refining);
    let opcode = match variant {
        Variant::Prefixed(selected) => {
            let prefix = variants.iter().find(|v| v.1 == selected).unwrap().0;
            prefix << shift | base_opcode
        },
        Variant::Plain | Variant::Undefined => base_opcode,
    };
    let rows = candidates(opcode);
    let first_row = family.ok_or(DecodeError::UnknownOpcode(opcode))?;
    // ModRM-taking forms the shared catalog lists without one: the 0F0D
    // prefetch hint, the reserved-NOP hints 0F1A/0F1B (MPX space, NOPs
    // without MPX) and UD1/UD0 (whose length bounds the #UD encoding).
    let hint_0f0d =
        mode.is_long() && matches!(base_opcode, 0x0F0D | 0x0F1A | 0x0F1B | 0x0FB9 | 0x0FFF);
    let modrm = if first_row.fetch_modrm || hint_0f0d { Some(c.byte()?) } else { None };
    let row = rows
        .iter()
        .find(|row| row.group < 0 || modrm.is_some_and(|m| (m >> 3 & 7) as i8 == row.group))
        .ok_or(DecodeError::InvalidOpcode)?;
    if variant == Variant::Undefined || !row.exists() || !row.implemented() {
        return Err(DecodeError::InvalidOpcode);
    }
    if prefixes.lock && !crate::decode_rules::lock_allowed(base_opcode, modrm) {
        return Err(DecodeError::InvalidOpcode);
    }
    let special_0f01 =
        base_opcode == 0x0F01 && (modrm == Some(0xF9) || modrm == Some(0xF8) && mode.is_long());
    if base_opcode == 0x0F01 && modrm == Some(0xF8) && !mode.is_long() {
        return Err(DecodeError::InvalidOpcode);
    }
    let memory = modrm.is_some_and(|m| m < 0xC0) && (row.e || hint_0f0d) && !row.ignore_mod;
    if !special_0f01 && (row.group_ud || if memory { row.mem_ud } else { row.reg_ud }) {
        return Err(DecodeError::InvalidOpcode);
    }
    let operand_size = operand_size(mode, prefixes, base_opcode, modrm);
    let address_size = if prefixes.address {
        if mode.is_long() {
            32
        }
        else {
            48 - mode.address_default()
        }
    }
    else {
        mode.address_default()
    };
    let address = if memory {
        Some(address(
            &mut c,
            modrm.unwrap(),
            address_size,
            prefixes,
            mode,
        )?)
    }
    else {
        None
    };
    let (encoded_bytes, sign_extended) = match row.immediate {
        ImmediateKind::None => (0, false),
        ImmediateKind::Byte => (1, false),
        ImmediateKind::SignedByte => (1, true),
        ImmediateKind::Word => (2, false),
        ImmediateKind::Address => (address_size / 8, false),
        ImmediateKind::Operand => {
            if mode.is_long() && matches!(base_opcode, 0xE8 | 0xE9 | 0x0F80..=0x0F8F) {
                (4, true)
            }
            else if operand_size == 64 && (0xB8..=0xBF).contains(&base_opcode) {
                (8, false)
            }
            else if operand_size == 64 {
                (4, true)
            }
            else {
                (operand_size / 8, false)
            }
        },
    };
    let immediate = if encoded_bytes == 0 {
        None
    }
    else {
        let value = c.integer(encoded_bytes)?;
        let signed = sign_extended
            || mode.is_long()
                && (base_opcode == 0x6A
                    || base_opcode == 0xEB
                    || (0x70..=0x7F).contains(&base_opcode));
        let value = if signed && encoded_bytes < 8 {
            (((value << (64 - encoded_bytes * 8)) as i64) >> (64 - encoded_bytes * 8)) as u64
        }
        else {
            value
        };
        Some(Immediate {
            value,
            encoded_bytes,
            sign_extended: signed,
        })
    };
    let extra_immediate =
        if row.extra_bytes != 0 { Some(c.integer(row.extra_bytes)? as u16) } else { None };
    let next = next_ip(start, c.length, mode);
    Ok(Decoded {
        encoding: row,
        opcode,
        prefixes,
        mode,
        operand_size,
        address_size,
        length: c.length,
        start,
        next,
        modrm,
        reg: modrm.map(|m| (m >> 3 & 7) | prefixes.r()),
        rm_register: modrm
            .filter(|m| *m >= 0xC0 || row.ignore_mod)
            .map(|m| (m & 7) | prefixes.b()),
        opcode_register: if matches!(base_opcode,0x50..=0x5F|0x90..=0x97|0xB0..=0xBF) {
            Some((base_opcode as u8 & 7) | prefixes.b())
        }
        else {
            None
        },
        address,
        immediate,
        extra_immediate,
        bytes: c.bytes,
        vex: None,
    })
}

fn next_ip(start: GuestIp, length: u8, mode: ExecutionMode) -> GuestIp {
    let next = start.0.wrapping_add(length as u64);
    GuestIp(if mode.is_long() {
        next
    }
    else if mode.operand_default() == 16 {
        next as u16 as u64
    }
    else {
        next as u32 as u64
    })
}

/// A VEX instruction: `first` (C4 or C5) and its prefixes are read. #UD (the
/// order the 32-bit interpreter and IR decoder share): a 66/F2/F3/LOCK/REX
/// prefix at the first VEX byte, a key without rows at the opcode byte, and
/// after the ModRM byte when no row accepts the VEX fields
/// (decode_rules::vex_row, vex_valid), the row's feature is absent or its
/// semantics come later. Gathers whose destination, index and mask registers
/// are not distinct are #UD after the SIB byte.
fn decode_vex<F, E>(
    mut c: Cursor<F>,
    start: GuestIp,
    mode: ExecutionMode,
    prefixes: PrefixState,
    first: u8,
) -> Result<Decoded, DecodeError<E>>
where
    F: FnMut(u8) -> Result<u8, E>,
{
    use crate::decode_rules::{vex, vex_row, vex_valid, Vex};
    let long = mode.is_long();
    let byte1 = c.byte()?;
    if prefixes.operand || prefixes.rep.is_some() || prefixes.lock || prefixes.rex.is_some() {
        return Err(DecodeError::InvalidOpcode);
    }
    let v = if first == 0xC4 { Vex::three(byte1, c.byte()?, long) } else { Vex::two(byte1, long) };
    let key = v.key(c.byte()?);
    let rows = candidates(key);
    let family = rows.first().ok_or(DecodeError::UnknownOpcode(key))?;
    let modrm = if family.fetch_modrm { Some(c.byte()?) } else { None };
    let address_size = if !prefixes.address {
        mode.address_default()
    }
    else if long {
        32
    }
    else {
        48 - mode.address_default()
    };
    let row = vex_row(rows, v, modrm, long)
        .filter(|row| row.exists() && row.implemented() && vex_valid(row, v, modrm, address_size))
        .ok_or(DecodeError::InvalidOpcode)?;
    // VEX.R, X and B extend the ModRM and SIB fields as REX does
    let extended = PrefixState {
        rex: Some(0x40 | (v.r as u8) << 2 | (v.x as u8) << 1 | v.b as u8),
        ..prefixes
    };
    let modrm_at = c.length as usize - 1;
    let mut address = match modrm {
        Some(m) if m < 0xC0 => Some(address(&mut c, m, address_size, extended, mode)?),
        _ => None,
    };
    if let (Some(a), true) = (address.as_mut(), row.vex & vex::VSIB != 0) {
        // (a VSIB index names a vector register, xmm4/ymm4 included)
        a.index = Some((c.bytes[modrm_at + 1] >> 3 & 7) | extended.x());
    }
    let immediate = match row.immediate {
        ImmediateKind::None => None,
        ImmediateKind::Byte => Some(Immediate {
            value: c.integer(1)?,
            encoded_bytes: 1,
            sign_extended: false,
        }),
        _ => unreachable!("VEX rows have no other immediates"),
    };
    let reg = modrm.map(|m| (m >> 3 & 7) | extended.r());
    if row.vex & vex::UNIQUE != 0 {
        let (index, mask) = (address.and_then(|a| a.index), v.vvvv);
        if reg == index || Some(mask) == index || reg == Some(mask) {
            return Err(DecodeError::InvalidOpcode);
        }
    }
    Ok(Decoded {
        encoding: row,
        opcode: key,
        prefixes,
        mode,
        // general-purpose operands: 64-bit with W1 rows in 64-bit mode
        operand_size: if long && row.vex & vex::W1 != 0 { 64 } else { 32 },
        address_size,
        length: c.length,
        start,
        next: next_ip(start, c.length, mode),
        modrm,
        reg,
        rm_register: modrm.filter(|m| *m >= 0xC0).map(|m| (m & 7) | extended.b()),
        opcode_register: None,
        address,
        immediate,
        extra_immediate: None,
        bytes: c.bytes,
        vex: Some(v),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    fn d(bytes: &[u8]) -> Decoded {
        decode(bytes, GuestIp(0xFFFF_8000_0000_1000), ExecutionMode::Long64).unwrap()
    }
    #[test]
    fn prefixed_catalog_keys_preserve_base_opcode() {
        let movs = d(&[0xF3, 0x48, 0xA5]);
        assert_eq!(movs.base_opcode(), 0xA5);
        assert_eq!(movs.prefixes.rep, Some(0xF3));
        assert_eq!(movs.operand_size, 64);
        assert_eq!(d(&[0xF3, 0x90]).base_opcode(), 0x90);
        assert_eq!(d(&[0x0F, 0x05]).base_opcode(), 0x0F05);
        assert_eq!(d(&[0x0F, 0x07]).base_opcode(), 0x0F07);
        assert_eq!(d(&[0x0F, 0x01, 0xF9]).modrm, Some(0xF9));
        assert_eq!(d(&[0xF3, 0x48, 0x0F, 0xB8, 0xC1]).base_opcode(), 0x0FB8);
    }
    #[test]
    fn mandatory_prefixes_follow_the_shared_rule_in_every_mode() {
        for mode in [
            ExecutionMode::Long64,
            ExecutionMode::Compatibility32,
            ExecutionMode::Protected32,
        ] {
            let decode = |bytes: &[u8]| decode(bytes, GuestIp(0x1000), mode);
            // 66 with F3/F2 is an operand-size prefix (iced-x86, XED): MOVSS/MOVSD
            assert_eq!(
                decode(&[0x66, 0xF3, 0x0F, 0x10, 0xC1]).unwrap().opcode,
                0xF30F10
            );
            assert_eq!(
                decode(&[0xF3, 0x66, 0x0F, 0x10, 0xC1]).unwrap().opcode,
                0xF30F10
            );
            assert_eq!(
                decode(&[0x66, 0xF2, 0x0F, 0x10, 0xC1]).unwrap().opcode,
                0xF20F10
            );
            // of F2 and F3 the last one counts
            assert_eq!(
                decode(&[0xF2, 0xF3, 0x0F, 0x10, 0xC1]).unwrap().opcode,
                0xF30F10
            );
            assert_eq!(
                decode(&[0xF3, 0xF2, 0x0F, 0x10, 0xC1]).unwrap().opcode,
                0xF20F10
            );
            // a mandatory prefix without a row is #UD in every mode, after ModRM
            for bytes in [
                &[0xF3, 0x0F, 0x2B, 0x00][..],
                &[0x66, 0x0F, 0xC3, 0x00],
                &[0xF2, 0x0F, 0x77],
            ] {
                assert_eq!(
                    decode(bytes).unwrap_err(),
                    DecodeError::InvalidOpcode,
                    "{bytes:02X?} {mode:?}"
                );
                if bytes.len() == 4 {
                    assert!(matches!(
                        decode(&bytes[..3]),
                        Err(DecodeError::Fetch { offset: 3, .. })
                    ));
                }
            }
            // outside the SSE maps F2/F3 are repeat prefixes
            assert_eq!(decode(&[0xF3, 0x0F, 0xAF, 0xC1]).unwrap().opcode, 0x0FAF);
        }
    }
    #[test]
    fn three_byte_maps_are_undefined_after_modrm_without_their_features() {
        use crate::cpu::features::{ALL, TEST_FEATURES};
        for features in [0, ALL] {
            TEST_FEATURES.with(|f| f.set(features));
            for mode in [
                ExecutionMode::Long64,
                ExecutionMode::Compatibility32,
                ExecutionMode::Protected32,
            ] {
                let decode = |bytes: &[u8]| decode(bytes, GuestIp(0x1000), mode);
                // with MOVBE (P10) its forms decode, their memory operands
                // whole; F3 at MOVBE/CRC32 stays #UD
                if features != 0 {
                    assert_eq!(
                        decode(&[0x0F, 0x38, 0xF1, 0x04, 0x24]).unwrap().opcode,
                        0x0F38F1
                    );
                    assert_eq!(decode(&[0x0F, 0x38, 0xF0, 0x00]).unwrap().opcode, 0x0F38F0);
                }
                for bytes in [
                    &[0x0F, 0x38, 0xF1, 0x04][..],
                    &[0x0F, 0x38, 0xF0, 0x00],
                    &[0xF3, 0x0F, 0x38, 0xF0, 0x00],
                ] {
                    if features != 0 && bytes[0] != 0xF3 {
                        continue;
                    }
                    assert_eq!(
                        decode(bytes).unwrap_err(),
                        DecodeError::InvalidOpcode,
                        "{bytes:02X?} {mode:?}"
                    );
                    // ... after the ModRM byte, which is fetched first
                    let n = bytes.len() - 1;
                    assert!(
                        matches!(decode(&bytes[..n]), Err(DecodeError::Fetch { offset, .. }) if offset as usize == n)
                    );
                }
                assert!(matches!(
                    decode(&[0x0F, 0x38, 0xFF, 0xC1]),
                    Err(DecodeError::UnknownOpcode(0x0F38FF))
                ));
            }
        }
        TEST_FEATURES.with(|f| f.set(0));
    }
    #[test]
    fn ssse3_forms_decode_with_their_feature() {
        use crate::cpu::features::{SSSE3, TEST_FEATURES};
        for features in [0, SSSE3] {
            TEST_FEATURES.with(|f| f.set(features));
            for mode in [
                ExecutionMode::Long64,
                ExecutionMode::Compatibility32,
                ExecutionMode::Protected16,
            ] {
                let decode = |bytes: &[u8]| decode(bytes, GuestIp(0x1000), mode);
                for (bytes, opcode, imm8) in [
                    (&[0x66, 0x0F, 0x38, 0x00, 0xC1][..], 0x660F3800, None), // pshufb xmm
                    (&[0x0F, 0x38, 0x1E, 0x08], 0x0F381E, None),             // pabsd mm, [..]
                    (
                        &[0x66, 0x0F, 0x3A, 0x0F, 0xC1, 0x83],
                        0x660F3A0F,
                        Some(0x83),
                    ), // palignr
                    (&[0x0F, 0x3A, 0x0F, 0xC1, 0xFF], 0x0F3A0F, Some(0xFF)),
                ] {
                    if features == 0 {
                        // #UD after the ModRM byte (and before the immediate)
                        let n = if imm8.is_some() { bytes.len() - 1 } else { bytes.len() };
                        assert_eq!(decode(&bytes[..n]).unwrap_err(), DecodeError::InvalidOpcode);
                        continue;
                    }
                    let d = decode(bytes).unwrap();
                    assert_eq!(
                        (d.opcode, d.length as usize),
                        (opcode, bytes.len()),
                        "{bytes:02X?}"
                    );
                    assert_eq!(d.immediate.map(|i| i.value as u8), imm8);
                    assert!(matches!(
                        decode(&bytes[..bytes.len() - 1]),
                        Err(DecodeError::Fetch { .. })
                    ));
                }
                // F2/F3 select no SSSE3 form: #UD, also with 66 (decode_rules::mandatory_variant)
                for bytes in [
                    &[0xF3, 0x0F, 0x38, 0x00, 0xC1][..],
                    &[0x66, 0xF2, 0x0F, 0x38, 0x00, 0xC1],
                    &[0xF3, 0x0F, 0x3A, 0x0F, 0xC1],
                ] {
                    assert_eq!(decode(bytes).unwrap_err(), DecodeError::InvalidOpcode);
                }
            }
            // REX.R and REX.B reach XMM8-15
            if features != 0 {
                let d = decode(
                    &[0x66, 0x45, 0x0F, 0x38, 0x00, 0xC1],
                    GuestIp(0x1000),
                    ExecutionMode::Long64,
                )
                .unwrap();
                assert_eq!(
                    (d.opcode, d.reg, d.rm_register),
                    (0x660F3800, Some(8), Some(9))
                );
            }
        }
        TEST_FEATURES.with(|f| f.set(0));
    }
    #[test]
    fn sse42_forms_decode_with_their_feature() {
        use crate::cpu::features::{SSE4_1, SSE4_2, SSSE3, TEST_FEATURES};
        for features in [SSSE3 | SSE4_1, SSSE3 | SSE4_1 | SSE4_2] {
            TEST_FEATURES.with(|f| f.set(features));
            for mode in [
                ExecutionMode::Long64,
                ExecutionMode::Compatibility32,
                ExecutionMode::Protected16,
            ] {
                let decode = |bytes: &[u8]| decode(bytes, GuestIp(0x1000), mode);
                let w32 = if mode == ExecutionMode::Protected16 { 16 } else { 32 };
                // (the operand size: CRC32's source; none for PCMPxSTRx, whose 66 is mandatory)
                for (bytes, opcode, imm8, operand_size) in [
                    (
                        &[0x66, 0x0F, 0x3A, 0x61, 0xC1, 0x0C][..],
                        0x660F3A61,
                        Some(0x0C),
                        None,
                    ), // pcmpestri
                    (
                        &[0x66, 0x0F, 0x3A, 0x62, 0x00, 0x40],
                        0x660F3A62,
                        Some(0x40),
                        None,
                    ), // pcmpistrm [..]
                    (&[0xF2, 0x0F, 0x38, 0xF0, 0xC1], 0xF20F38F0, None, Some(w32)), // crc32 r32, r/m8
                    (&[0xF2, 0x0F, 0x38, 0xF1, 0x00], 0xF20F38F1, None, Some(w32)), // crc32 r32, r/m32 (16)
                    // (66 is the operand size: CRC32 r32, r/m16, or r/m32 in 16-bit code)
                    (
                        &[0x66, 0xF2, 0x0F, 0x38, 0xF1, 0xC1],
                        0xF20F38F1,
                        None,
                        Some(48 - w32),
                    ),
                ] {
                    if features & SSE4_2 == 0 {
                        // #UD after the ModRM byte (and before the immediate)
                        let n = if imm8.is_some() { bytes.len() - 1 } else { bytes.len() };
                        assert_eq!(decode(&bytes[..n]).unwrap_err(), DecodeError::InvalidOpcode);
                        continue;
                    }
                    let d = decode(bytes).unwrap();
                    assert_eq!(
                        (d.opcode, d.length as usize),
                        (opcode, bytes.len()),
                        "{bytes:02X?} {mode:?}"
                    );
                    assert!(operand_size.is_none_or(|size| d.operand_size == size));
                    assert_eq!(d.immediate.map(|i| i.value as u8), imm8);
                }
                // F3 selects no CRC32 (nor, without a memory operand, MOVBE)
                assert_eq!(
                    decode(&[0xF3, 0x0F, 0x38, 0xF1, 0xC1]).unwrap_err(),
                    DecodeError::InvalidOpcode
                );
            }
            // REX.W: CRC32 r64, r/m64 and r64, r/m8; PCMPESTRI with RAX/RDX
            if features & SSE4_2 != 0 {
                let decode = |bytes: &[u8]| decode(bytes, GuestIp(0x1000), ExecutionMode::Long64);
                let d = decode(&[0xF2, 0x48, 0x0F, 0x38, 0xF1, 0xC1]).unwrap();
                assert_eq!((d.opcode, d.operand_size), (0xF20F38F1, 64));
                let d = decode(&[0xF2, 0x48, 0x0F, 0x38, 0xF0, 0xC1]).unwrap();
                assert_eq!((d.opcode, d.operand_size), (0xF20F38F0, 64));
                let d = decode(&[0x66, 0x4D, 0x0F, 0x3A, 0x61, 0xC1, 0x0C]).unwrap();
                assert_eq!(
                    (d.opcode, d.reg, d.rm_register, d.prefixes.w()),
                    (0x660F3A61, Some(8), Some(9), true)
                );
            }
        }
        TEST_FEATURES.with(|f| f.set(0));
    }
    #[test]
    fn vex_by_mode_prefixes_and_fields() {
        use crate::cpu::features::{ALL, TEST_FEATURES};
        use crate::decode::{form, TEST_DECODE_UNIMPLEMENTED};
        use ExecutionMode::*;
        TEST_FEATURES.with(|f| f.set(ALL));
        TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(true));
        let at = |bytes: &[u8], mode| decode(bytes, GuestIp(0x1000), mode);
        // C4/C5 with a register ModRM byte: VEX, except in real and
        // virtual-8086 mode (LES/LDS, whose register form is #UD)
        for mode in [
            Long64,
            Compatibility32,
            Compatibility16,
            Protected32,
            Protected16,
        ] {
            let v = at(&[0xC5, 0xF8, 0x77], mode).unwrap();
            assert_eq!(
                (form(v.encoding), v.length, v.opcode),
                ("VEX_Vzeroupper", 3, 0xC4010077)
            );
            assert_eq!(v.base_opcode(), 0xC4010077);
        }
        for mode in [Real, Vm86] {
            let lds = at(&[0xC5, 0xF8, 0x77], mode).unwrap();
            assert!(lds.opcode == 0xC5 && lds.vex.is_none() && lds.length == 2);
        }
        // a memory ModRM byte: LES/LDS outside 64-bit mode (where it is
        // VEX, here with a reserved map)
        assert_eq!(
            at(&[0xC4, 0x00, 0x78, 0x77], Compatibility32)
                .unwrap()
                .opcode,
            0xC4
        );
        assert_eq!(
            at(&[0xC4, 0x00, 0x78, 0x77], Long64).unwrap_err(),
            DecodeError::UnknownOpcode(0xC4000077)
        );
        // 66, F2, F3, LOCK and REX before VEX: #UD at the first VEX byte; a
        // REX followed by another prefix is not in effect
        for prefix in [0x66, 0xF2, 0xF3, 0xF0, 0x40, 0x4F] {
            let bytes = [prefix, 0xC4, 0xE1, 0x7C, 0x77];
            let mut seen = Vec::new();
            let result = decode_with(GuestIp(0), Long64, |offset| {
                seen.push(offset);
                bytes.get(offset as usize).copied().ok_or(())
            });
            assert_eq!(result.unwrap_err(), DecodeError::InvalidOpcode);
            assert_eq!(seen.iter().max(), Some(&2));
        }
        assert_eq!(
            form(
                at(&[0x48, 0x2E, 0xC5, 0xF8, 0x77], Long64)
                    .unwrap()
                    .encoding
            ),
            "VEX_Vzeroupper"
        );
        // VPADDD ymm9, ymm10, [r12+r13*2+0x10]: R, X, B and all of VEX.vvvv
        let v = at(&[0xC4, 0x01, 0x2D, 0xFE, 0x4C, 0x6C, 0x10], Long64).unwrap();
        assert_eq!(
            (form(v.encoding), v.length, v.reg),
            ("VEX_Vpaddd_ymm_ymm_ymmm256", 7, Some(9))
        );
        let a = v.address.unwrap();
        assert_eq!(
            (a.base, a.index, a.scale, a.displacement),
            (AddressBase::Register(12), Some(13), 1, 0x10)
        );
        assert_eq!(v.vex.unwrap().vvvv, 10);
        // ... and the same bytes in compatibility mode are LES eax, [ecx]
        let les = at(&[0xC4, 0x01, 0x2D, 0xFE], Compatibility32).unwrap();
        assert!(les.opcode == 0xC4 && les.length == 2);
        // W1: 64-bit operands in 64-bit mode, ignored outside it
        for (bytes, long, compat) in [
            (
                &[0xC4, 0xE1, 0xF9, 0x6E, 0xC8][..],
                "VEX_Vmovq_xmm_rm64",
                "VEX_Vmovd_xmm_rm32",
            ),
            (
                &[0xC4, 0xE2, 0xF0, 0xF2, 0xC1],
                "VEX_Andn_r64_r64_rm64",
                "VEX_Andn_r32_r32_rm32",
            ),
            (
                &[0xC4, 0xE2, 0xB0, 0xF2, 0xC1],
                "VEX_Andn_r64_r64_rm64",
                "VEX_Andn_r32_r32_rm32",
            ),
        ] {
            let (l, c) = (
                at(bytes, Long64).unwrap(),
                at(bytes, Compatibility32).unwrap(),
            );
            assert_eq!((form(l.encoding), l.operand_size), (long, 64));
            assert_eq!((form(c.encoding), c.operand_size), (compat, 32));
        }
        // ANDN's VEX.vvvv names r9 in 64-bit mode, ecx outside it
        let andn = at(&[0xC4, 0xE2, 0xB0, 0xF2, 0xC1], Long64).unwrap();
        assert_eq!(andn.vex.unwrap().vvvv, 9);
        let andn = at(&[0xC4, 0xE2, 0xB0, 0xF2, 0xC1], Compatibility32).unwrap();
        assert_eq!(andn.vex.unwrap().vvvv, 1);
        // VEX.vvvv must be 1111b where it is not an operand; outside 64-bit
        // mode the three-byte prefix's top bit is ignored (SDM 2.3.5.6)
        for mode in [Long64, Compatibility32] {
            assert_eq!(
                at(&[0xC5, 0xF0, 0x77], mode).unwrap_err(),
                DecodeError::InvalidOpcode
            );
            assert_eq!(
                at(&[0xC4, 0xE1, 0x74, 0x77], mode).unwrap_err(),
                DecodeError::InvalidOpcode
            );
        }
        assert_eq!(
            at(&[0xC4, 0xE1, 0x3C, 0x77], Long64).unwrap_err(),
            DecodeError::InvalidOpcode
        );
        assert_eq!(
            form(
                at(&[0xC4, 0xE1, 0x3C, 0x77], Compatibility32)
                    .unwrap()
                    .encoding
            ),
            "VEX_Vzeroall"
        );
        // reserved maps and opcodes without rows: after the opcode byte
        let mut seen = Vec::new();
        let result = decode_with(GuestIp(0), Long64, |offset| {
            seen.push(offset);
            [0xC4, 0xE4, 0x78, 0x77, 0xC0]
                .get(offset as usize)
                .copied()
                .ok_or(())
        });
        assert_eq!(result.unwrap_err(), DecodeError::UnknownOpcode(0xC4040077));
        assert_eq!(seen.iter().max(), Some(&3));
        assert_eq!(
            at(&[0xC5, 0xF8, 0x00], Long64).unwrap_err(),
            DecodeError::UnknownOpcode(0xC4010000)
        );
        // VPGATHERDD xmm2, [rax+xmm9*4], xmm3; the index may not be the
        // destination or mask register
        let g = at(&[0xC4, 0xA2, 0x61, 0x90, 0x14, 0x88], Long64).unwrap();
        assert_eq!(
            (form(g.encoding), g.address.unwrap().index),
            ("VEX_Vpgatherdd_xmm_vm32x_xmm", Some(9))
        );
        assert_eq!(
            at(&[0xC4, 0xE2, 0x61, 0x90, 0x14, 0x98], Long64).unwrap_err(),
            DecodeError::InvalidOpcode
        );
        assert_eq!(
            at(&[0xC4, 0xE2, 0x61, 0x90, 0x14, 0xA0], Long64)
                .unwrap()
                .address
                .unwrap()
                .index,
            Some(4)
        );
        assert_eq!(
            at(&[0xC4, 0xE2, 0x61, 0x90, 0x10], Long64).unwrap_err(),
            DecodeError::InvalidOpcode
        );
        assert_eq!(
            at(&[0x67, 0xC4, 0xE2, 0x61, 0x90, 0x14, 0x88], Compatibility32).unwrap_err(),
            DecodeError::InvalidOpcode
        );
        // without the features: #UD after the ModRM byte (VFMADD132PS ymm;
        // since P11 every row has its semantics)
        for (features, all) in [(0, true)] {
            TEST_FEATURES.with(|f| f.set(features));
            TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(all));
            let bytes = [0xC4, 0x02, 0x2D, 0x98, 0x4C];
            assert_eq!(at(&bytes, Long64).unwrap_err(), DecodeError::InvalidOpcode);
            assert!(matches!(
                at(&bytes[..4], Long64),
                Err(DecodeError::Fetch { offset: 4, .. })
            ));
        }
        TEST_FEATURES.with(|f| f.set(0));
        TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(false));
    }
    #[test]
    fn vex_rows_decode_from_their_own_encodings_in_every_mode() {
        use crate::cpu::features::{ALL, TEST_FEATURES};
        use crate::decode::{encodings, form, TEST_DECODE_UNIMPLEMENTED};
        use crate::decode_rules::vex;
        TEST_FEATURES.with(|f| f.set(ALL));
        TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(true));
        let mut count = 0;
        for row in encodings().iter().filter(|e| e.vex != 0) {
            let (map, pp) = ((row.opcode >> 16) as u8, (row.opcode >> 8 & 3) as u8);
            let (l, w) = (row.vex & vex::L1 != 0, row.vex & vex::W1 != 0);
            let vvvv = if row.vex & vex::VVVV != 0 { 3 } else { 0 };
            let group = if row.group >= 0 { row.group as u8 } else { 2 };
            let vsib = row.vex & vex::VSIB != 0;
            let mut operands = Vec::new();
            if row.fetch_modrm && !row.reg_ud {
                operands.push(vec![0xC0 | group << 3 | 1]);
            }
            if row.fetch_modrm && !row.mem_ud {
                operands.push(if vsib {
                    vec![0x44 | group << 3, 0x08, 0x10]
                }
                else {
                    vec![0x40 | group << 3, 0x10]
                });
            }
            if !row.fetch_modrm {
                operands.push(vec![]);
            }
            for mode in [
                ExecutionMode::Long64,
                ExecutionMode::Compatibility32,
                ExecutionMode::Protected16,
            ] {
                if row.vex & vex::LONG != 0 && !mode.is_long()
                    || vsib && mode == ExecutionMode::Protected16
                {
                    continue;
                }
                for operand in &operands {
                    let mut bytes = vec![
                        0xC4,
                        0xE0 | map,
                        (w as u8) << 7 | (!vvvv & 15) << 3 | (l as u8) << 2 | pp,
                        row.opcode as u8,
                    ];
                    bytes.extend(operand);
                    if row.immediate == ImmediateKind::Byte {
                        bytes.push(0x5A);
                    }
                    let d = decode(&bytes, GuestIp(0x1000), mode)
                        .unwrap_or_else(|e| panic!("{} {bytes:02X?} {mode:?} {e:?}", form(row)));
                    assert_eq!(
                        (form(d.encoding), d.length as usize),
                        (form(row), bytes.len()),
                        "{bytes:02X?} {mode:?}"
                    );
                    assert_eq!(
                        d.address.is_some(),
                        operand.first().is_some_and(|&m| m < 0xC0)
                    );
                    assert_eq!(
                        d.immediate.map(|i| i.value),
                        (row.immediate == ImmediateKind::Byte).then_some(0x5A)
                    );
                    if vsib {
                        assert_eq!(d.address.unwrap().index, Some(1));
                    }
                    count += 1;
                }
            }
        }
        TEST_FEATURES.with(|f| f.set(0));
        TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(false));
        assert!(count > 2000, "{count}");
    }
    #[test]
    fn prefetchw_consumes_the_complete_address_without_reading_data() {
        let prefetch = d(&[0x41, 0x0F, 0x0D, 0x8C, 0x24, 0xFF, 0xFF, 0xFF, 0x7F]);
        assert_eq!(prefetch.length, 9);
        assert_eq!(prefetch.reg, Some(1));
        assert!(prefetch.address.is_some());
    }
    #[test]
    fn rex_order_byte_registers_and_modes() {
        assert_eq!(d(&[0x48, 0x66, 0x89, 0xC0]).operand_size, 16);
        assert_eq!(d(&[0x66, 0x48, 0x89, 0xC0]).operand_size, 64);
        assert_eq!(d(&[0x48, 0x40, 0x89, 0xC0]).operand_size, 32);
        assert_eq!(d(&[0x40, 0x48, 0x89, 0xC0]).operand_size, 64);
        for r in 0..16 {
            assert_eq!(byte_register(r, true), ByteRegister::Low(r));
        }
        for r in 4..8 {
            assert_eq!(byte_register(r, false), ByteRegister::HighLegacy(r - 4));
        }
        for mode in [
            ExecutionMode::Real,
            ExecutionMode::Vm86,
            ExecutionMode::Protected16,
            ExecutionMode::Protected32,
            ExecutionMode::Compatibility16,
            ExecutionMode::Compatibility32,
        ] {
            let decoded = decode(&[0x48], GuestIp(0), mode).unwrap();
            assert_eq!(decoded.opcode, 0x48);
            assert_eq!(decoded.length, 1);
            assert_eq!(decoded.prefixes.rex, None);
        }
        assert_eq!(d(&[0x4D, 0x89, 0xFC]).reg, Some(15));
        assert_eq!(d(&[0x4D, 0x89, 0xFC]).rm_register, Some(12));
    }
    #[test]
    fn full_addresses_sib_and_rip_relative() {
        let decoded = d(&[0x48, 0x8B, 0x05, 0xFF, 0xFF, 0xFF, 0xFF]);
        assert_eq!(
            decoded.address.unwrap().offset(&[0; 16], decoded.next),
            decoded.next.0 - 1
        );
        let decoded = d(&[0x67, 0x48, 0x8B, 0x05, 0xFF, 0xFF, 0xFF, 0xFF]);
        assert_eq!(
            decoded.address.unwrap().offset(&[0; 16], decoded.next),
            ((decoded.next.0 - 1) as u32) as u64
        );
        let decoded = d(&[0x4B, 0x8B, 0x04, 0xA5, 0xFF, 0xFF, 0xFF, 0xFF]);
        let ea = decoded.address.unwrap();
        assert_eq!(ea.base, AddressBase::None);
        assert_eq!(ea.index, Some(12));
        let mut registers = [0; 16];
        registers[12] = 0x1_0000_0000;
        assert_eq!(ea.offset(&registers, decoded.next), 0x3_FFFF_FFFF);
        let ea = d(&[0x49, 0x8B, 0x44, 0x25, 0]).address.unwrap();
        assert_eq!(ea.base, AddressBase::Register(13));
        assert_eq!(ea.segment, 3);
        let decoded = d(&[0x64, 0x48, 0x8B, 0x00]);
        assert_eq!(decoded.address.unwrap().segment, 4);
    }
    #[test]
    fn immediate_width_sign_and_instruction_length() {
        assert_eq!(
            d(&[0x48, 0xB8, 1, 2, 3, 4, 5, 6, 7, 8])
                .immediate
                .unwrap()
                .value,
            0x0807_0605_0403_0201
        );
        let i = d(&[0x48, 0xC7, 0xC0, 0xFF, 0xFF, 0xFF, 0xFF])
            .immediate
            .unwrap();
        assert_eq!(i.value, u64::MAX);
        assert_eq!(i.encoded_bytes, 4);
        assert_eq!(
            d(&[0x48, 0xA1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF])
                .immediate
                .unwrap()
                .value,
            u64::MAX
        );
        assert_eq!(
            d(&[0x67, 0xA1, 0xFF, 0xFF, 0xFF, 0xFF])
                .immediate
                .unwrap()
                .encoded_bytes,
            4
        );
        assert_eq!(
            d(&[0x66, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF])
                .immediate
                .unwrap()
                .encoded_bytes,
            4
        );
        assert_eq!(d(&[0x41, 0x50]).operand_size, 64);
        assert_eq!(d(&[0x66, 0x41, 0x50]).operand_size, 16);
        assert_eq!(d(&[0x48, 0x0F, 0xC7, 0x0F]).operand_size, 128);
    }
    #[test]
    fn fetch_fault_priority_and_no_speculative_operand_reads() {
        let mut seen = Vec::new();
        let result = decode_with(GuestIp(4095), ExecutionMode::Long64, |offset| {
            seen.push(offset);
            if offset == 0 {
                Ok(0x48)
            }
            else {
                Err(14)
            }
        });
        assert_eq!(
            result.unwrap_err(),
            DecodeError::Fetch {
                offset: 1,
                error: 14
            }
        );
        assert_eq!(seen, vec![0, 1]);
        let mut seen = Vec::new();
        let result = decode_with(GuestIp(0), ExecutionMode::Long64, |offset| {
            seen.push(offset);
            Ok::<_, u8>(0x66)
        });
        assert_eq!(result.unwrap_err(), DecodeError::TooLong);
        assert_eq!(seen.len(), 15);
        // Invalid LOCK must not fetch an EA displacement or immediate.
        let mut seen = Vec::new();
        let result = decode_with(GuestIp(0), ExecutionMode::Long64, |offset| {
            seen.push(offset);
            [0xF0, 0x89, 0x05].get(offset as usize).copied().ok_or(14)
        });
        assert_eq!(result.unwrap_err(), DecodeError::InvalidOpcode);
        assert_eq!(seen, vec![0, 1, 2]);
        // (C4 and C5 are VEX prefixes in 64-bit mode)
        for byte in [0x06, 0x60, 0x62, 0x82, 0x9A, 0xCE, 0xD4, 0xEA] {
            assert!(matches!(
                decode(&[byte], GuestIp(0), ExecutionMode::Long64),
                Err(DecodeError::InvalidOpcode)
            ));
        }
        assert!(decode(&[0x0F, 0x01, 0xF8], GuestIp(0), ExecutionMode::Long64).is_ok());
    }
    #[test]
    fn independent_decoder_corpus() {
        let root = std::path::Path::new("build/x64-decode");
        std::fs::create_dir_all(root).unwrap();
        let mut rows = Vec::new();
        let mut add = |bytes: Vec<u8>, mode: ExecutionMode| {
            let decoded = decode(&bytes, GuestIp(0xFFFF_8000_0000_1000), mode).unwrap();
            let ea = decoded.address;
            let base = ea.map_or(-1, |ea| match ea.base {
                AddressBase::None => -1,
                AddressBase::NextRip => -2,
                AddressBase::Register(r) => r as i32,
            });
            let index = ea.and_then(|ea| ea.index).map_or(-1, |r| r as i32);
            let disp = ea.map_or(0, |ea| ea.offset(&[0; 16], decoded.next));
            let scale = ea.map_or(0, |ea| ea.scale);
            let segment = ea.map_or(0, |ea| ea.segment);
            let bitness = if mode.is_long() { 64 } else { mode.operand_default() };
            rows.push(format!(
                "[{:?},{},{},{},{},{},{},{},{},{},{},{}]",
                bytes,
                bitness,
                decoded.length,
                decoded.operand_size,
                decoded.address_size,
                decoded.reg.map_or(-1, |r| r as i32),
                decoded.rm_register.map_or(-1, |r| r as i32),
                base,
                index,
                scale,
                segment,
                disp
            ));
        };
        for mode in [
            ExecutionMode::Real,
            ExecutionMode::Vm86,
            ExecutionMode::Protected16,
            ExecutionMode::Protected32,
            ExecutionMode::Compatibility16,
            ExecutionMode::Compatibility32,
            ExecutionMode::Long64,
        ] {
            for address_override in [false, true] {
                for operand_override in [false, true] {
                    for rex in if mode.is_long() { 0x40..0x50 } else { 0..1 } {
                        for modrm in 0..=255u8 {
                            let sibs: &[u8] = if modrm & 7 == 4 && modrm < 0xC0 {
                                &[0, 0x24, 0x25, 0xA5, 0xFC, 0xFF]
                            }
                            else {
                                &[0]
                            };
                            for &sib in sibs {
                                let mut bytes = Vec::new();
                                if operand_override {
                                    bytes.push(0x66);
                                }
                                if address_override {
                                    bytes.push(0x67);
                                }
                                if mode.is_long() {
                                    bytes.push(rex);
                                }
                                bytes
                                    .extend([0x8B, modrm, sib, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0]);
                                add(bytes, mode);
                            }
                        }
                    }
                }
            }
        }
        std::fs::write(root.join("corpus.json"), format!("[{}]", rows.join(","))).unwrap();
        assert!(rows.len() > 30_000);
    }
    /// Every one-byte, 0F, 0F38 and 0F3A opcode in long mode under common
    /// prefixes and ModRM forms, for tests/x64/oracle (iced-x86 validity,
    /// length and ModRM fields, gated by the advertised CPUID profile).
    #[test]
    fn opcode_map_corpus() {
        let root = std::path::Path::new("build/x64-decode");
        std::fs::create_dir_all(root).unwrap();
        let prefix_byte = |b: u8| matches!(b, 0x26 | 0x2E | 0x36 | 0x3E | 0x40..=0x4F | 0x64..=0x67 | 0xF0 | 0xF2 | 0xF3);
        let mut maps: Vec<Vec<u8>> = (0..=255u8)
            .filter(|&b| !prefix_byte(b) && b != 0x0F)
            .map(|b| vec![b])
            .collect();
        maps.extend(
            (0..=255u8)
                .filter(|&b| b != 0x38 && b != 0x3A)
                .map(|b| vec![0x0F, b]),
        );
        maps.extend((0..=255u8).map(|b| vec![0x0F, 0x38, b]));
        maps.extend((0..=255u8).map(|b| vec![0x0F, 0x3A, b]));
        let prefixes: [&[u8]; 11] = [
            &[],
            &[0x66],
            &[0xF2],
            &[0xF3],
            &[0x48],
            &[0x66, 0x48],
            &[0x67],
            &[0xF3, 0x48],
            &[0x41],
            &[0x44],
            &[0xF0],
        ];
        let mut rows = Vec::new();
        for opcode in &maps {
            for prefix in prefixes {
                for reg in 0..8u8 {
                    // register form, [rsp] via SIB, RIP+disp32, [rsp+disp8] via SIB
                    for modrm in [
                        0xC0 | reg << 3 | 1,
                        reg << 3 | 4,
                        reg << 3 | 5,
                        0x44 | reg << 3,
                    ] {
                        let mut bytes = prefix.to_vec();
                        bytes.extend(opcode);
                        bytes.push(modrm);
                        if modrm & 0xC7 == 0x04 || modrm & 0xC7 == 0x44 {
                            bytes.push(0x24);
                        }
                        bytes.resize(bytes.len() + 12, 0x11);
                        let (ok, length, width, r, rm) = match decode(
                            &bytes,
                            GuestIp(0xFFFF_8000_0000_1000),
                            ExecutionMode::Long64,
                        ) {
                            Ok(d) => (
                                1,
                                d.length as i32,
                                d.operand_size as i32,
                                d.reg.map_or(-1, |r| r as i32),
                                d.rm_register.map_or(-1, |r| r as i32),
                            ),
                            Err(_) => (0, 0, 0, -1, -1),
                        };
                        rows.push(format!(
                            "[{:?},{},{},{},{},{}]",
                            bytes, ok, length, width, r, rm
                        ));
                    }
                }
            }
        }
        std::fs::write(root.join("opcodes.json"), format!("[{}]", rows.join(","))).unwrap();
        assert!(rows.len() > 100_000);
    }
    #[test]
    fn rex_modrm_sib_product() {
        for rex in 0x40..=0x4F {
            for md in 0..4 {
                for rm in 0..8 {
                    for reg in 0..8 {
                        let bytes = [
                            rex,
                            0x8B,
                            md << 6 | reg << 3 | rm,
                            0x24,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                            0,
                        ];
                        let i = d(&bytes);
                        assert_eq!(i.reg, Some(reg | ((rex >> 2 & 1) << 3)));
                        if md == 3 {
                            assert_eq!(i.rm_register, Some(rm | ((rex & 1) << 3)));
                            assert!(i.address.is_none());
                        }
                        else {
                            assert!(i.address.is_some());
                        }
                    }
                }
            }
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/rust/x64/execute.rs                                                                  0000644 0000000 0000000 00000145417 00000000000 014115  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Precise long-mode integer interpreter. Every memory destination is validated
//! before a read/modify/write, and architectural registers/flags commit only
//! after the last faultable access. REP retires one restartable element at a time.
use super::{
    decode::{self, ByteRegister, DecodeError, Decoded},
    memory::{self, Fault},
    state,
};
const CF: u64 = 1;
const PF: u64 = 4;
const AF: u64 = 16;
const ZF: u64 = 64;
const SF: u64 = 128;
const OF: u64 = 2048;
const ARITH: u64 = CF | PF | AF | ZF | SF | OF;
fn mask(w: u8) -> u64 {
    if w == 64 {
        u64::MAX
    }
    else {
        (1u64 << w) - 1
    }
}
fn signed(v: u64, w: u8) -> i128 { ((v << (64 - w)) as i64 >> (64 - w)) as i128 }
fn szp(v: u64, w: u8) -> u64 {
    let v = v & mask(w);
    (if v == 0 { ZF } else { 0 })
        | if v >> (w - 1) != 0 { SF } else { 0 }
        | if (v as u8).count_ones() & 1 == 0 { PF } else { 0 }
}
/// operation codes match the x86 ALU /digit encoding.
pub fn alu(op: u8, a: u64, b: u64, w: u8, flags: u64) -> (u64, u64) {
    let a = a & mask(w);
    let b = b & mask(w);
    let carry = if op == 2 || op == 3 { flags & CF } else { 0 };
    let (r, cf, of, af) = match op {
        0 | 2 => {
            let sum = a as u128 + b as u128 + carry as u128;
            let r = sum as u64 & mask(w);
            (
                r,
                sum >> w != 0,
                (!(a ^ b) & (a ^ r)) >> (w - 1) != 0,
                (a ^ b ^ r) & 16 != 0,
            )
        },
        3 | 5 | 7 => {
            let sub = b as u128 + carry as u128;
            let r = a.wrapping_sub(b).wrapping_sub(carry) & mask(w);
            (
                r,
                (a as u128) < sub,
                ((a ^ b) & (a ^ r)) >> (w - 1) != 0,
                (a ^ b ^ r) & 16 != 0,
            )
        },
        1 => (a | b, false, false, false),
        4 => (a & b, false, false, false),
        6 => (a ^ b, false, false, false),
        _ => unreachable!(),
    };
    (
        r,
        flags & !ARITH
            | szp(r, w)
            | if cf { CF } else { 0 }
            | if of { OF } else { 0 }
            | if af { AF } else { 0 },
    )
}
pub fn condition(cc: u8, f: u64) -> bool {
    let base = match cc >> 1 {
        0 => f & OF != 0,
        1 => f & CF != 0,
        2 => f & ZF != 0,
        3 => f & (CF | ZF) != 0,
        4 => f & SF != 0,
        5 => f & PF != 0,
        6 => (f & SF != 0) != (f & OF != 0),
        7 => f & ZF != 0 || (f & SF != 0) != (f & OF != 0),
        _ => unreachable!(),
    };
    base ^ (cc & 1 != 0)
}
pub fn shift(op: u8, a: u64, count: u8, w: u8, flags: u64) -> (u64, u64) {
    let a = a & mask(w);
    let raw = count & if w == 64 { 63 } else { 31 };
    let count = match op {
        0 | 1 => raw % w,
        2 | 3 => {
            if w < 32 {
                raw % (w + 1)
            }
            else {
                raw
            }
        },
        _ => raw,
    };
    if count == 0 {
        // ROL/ROR mask the rotate amount modulo operand width, but their
        // carry output is still defined when the masked raw count is nonzero.
        if raw != 0 && op <= 1 {
            let carry = if op == 0 { a & 1 } else { a >> (w - 1) };
            return (a, flags & !CF | carry);
        }
        return (a, flags);
    }
    let sign = 1u64 << (w - 1);
    let (r, cf) = match op {
        0 => {
            let r = (((a as u128) << count) | (a as u128 >> (w - count))) as u64 & mask(w);
            (r, r & 1 != 0)
        },
        1 => {
            let r = ((a >> count) | (a << (w - count))) & mask(w);
            (r, r & sign != 0)
        },
        2 | 3 => {
            let total = w + 1;
            let ext = a as u128 | (((flags & CF) as u128) << w);
            let m = (1u128 << total) - 1;
            let r = if op == 2 {
                (ext << count | ext >> (total - count)) & m
            }
            else {
                (ext >> count | ext << (total - count)) & m
            };
            (r as u64 & mask(w), r >> w != 0)
        },
        4 | 6 => (
            a.wrapping_shl(count as u32) & mask(w),
            count <= w && (a >> (w - count)) & 1 != 0,
        ),
        5 => (
            if count >= w { 0 } else { a >> count },
            count <= w && a >> (count - 1) & 1 != 0,
        ),
        7 => (
            (signed(a, w) >> count) as u64 & mask(w),
            if count >= w { a & sign != 0 } else { a >> (count - 1) & 1 != 0 },
        ),
        _ => unreachable!(),
    };
    let mut f = flags & !CF | if cf { CF } else { 0 };
    if op >= 4 {
        f = f & !(SF | ZF | PF) | szp(r, w);
    }
    if raw == 1 {
        let overflow = match op {
            0 | 2 | 4 | 6 => (r & sign != 0) ^ cf,
            1 | 3 => ((r >> (w - 1)) ^ (r >> (w - 2))) & 1 != 0,
            5 => a & sign != 0,
            7 => false,
            _ => unreachable!(),
        };
        f = f & !OF | if overflow { OF } else { 0 };
    }
    (r, f)
}
pub fn popf_flags(old: u64, value: u64, width: u8, cpl: u8) -> u64 {
    let mut preserve = 0x1B0000; // RF, VM, VIF and VIP cannot be loaded by POPF.
    if width == 16 {
        preserve |= !0xFFFF;
    }
    if cpl != 0 {
        preserve |= 0x3000;
    }
    if cpl as u64 > (old >> 12 & 3) {
        preserve |= 0x200;
    }
    (value & !preserve | old & preserve) & crate::cpu::cpu::FLAGS_MASK as u64 | 2
}
unsafe fn register(r: u8, w: u8, rex: bool) -> u64 {
    if w == 8 {
        match decode::byte_register(r, rex) {
            ByteRegister::Low(r) => state::read_gpr(r as usize) & 255,
            ByteRegister::HighLegacy(r) => state::read_high_byte(r as usize) as u64,
        }
    }
    else {
        state::read_gpr(r as usize) & mask(w)
    }
}
unsafe fn set_register(r: u8, v: u64, w: u8, rex: bool) {
    if w == 8 {
        match decode::byte_register(r, rex) {
            ByteRegister::Low(r) => state::write_gpr(r as usize, v, w),
            ByteRegister::HighLegacy(r) => state::write_high_byte(r as usize, v as u8),
        }
    }
    else {
        state::write_gpr(r as usize, v, w)
    }
}
pub unsafe fn address(d: &Decoded) -> (u64, bool) { address_rsp(d, None) }
unsafe fn address_rsp(d: &Decoded, rsp: Option<u64>) -> (u64, bool) {
    let a = d.address.unwrap();
    let mut regs = [0; 16];
    for r in 0..16 {
        regs[r] = state::read_gpr(r);
    }
    if let Some(v) = rsp {
        regs[4] = v;
    }
    let offset = a.offset(&regs, d.next);
    let base = if a.segment >= 4 { state::read_segment_base(a.segment as usize) } else { 0 };
    (offset.wrapping_add(base), a.segment == 2)
}
unsafe fn rm(d: &Decoded, w: u8, writing: bool) -> Result<u64, Fault> {
    if let Some(r) = d.rm_register {
        Ok(register(r, w, d.prefixes.rex.is_some()))
    }
    else {
        let (a, s) = address(d);
        if writing {
            memory::probe_write(a, w, s)?;
        }
        memory::read(a, w, s)
    }
}
unsafe fn put_rm(d: &Decoded, w: u8, value: u64) -> Result<(), Fault> {
    if let Some(r) = d.rm_register {
        set_register(r, value, w, d.prefixes.rex.is_some());
        Ok(())
    }
    else {
        let (a, s) = address(d);
        memory::write(a, w, value, s)
    }
}
unsafe fn push(v: u64, w: u8) -> Result<(), Fault> {
    let rsp = state::read_gpr(4).wrapping_sub((w / 8) as u64);
    memory::write(rsp, w, v, true)?;
    state::write_gpr(4, rsp, 64);
    Ok(())
}
unsafe fn peek(w: u8) -> Result<u64, Fault> { memory::read(state::read_gpr(4), w, true) }
fn branch(target: u64) -> Result<u64, Fault> {
    if state::canonical(target, 48) {
        Ok(target)
    }
    else {
        Err(Fault::gp())
    }
}
fn relative(d: &Decoded) -> u64 {
    let i = d.immediate.unwrap();
    let disp = if i.encoded_bytes == 1 { i.value as i8 as i64 } else { i.value as i32 as i64 };
    d.next.0.wrapping_add(disp as u64)
}
unsafe fn string(d: &Decoded, op: u32) -> Result<bool, Fault> {
    let repeat = d.prefixes.rep.is_some();
    let aw = d.address_size;
    let count = state::read_gpr(1) & mask(aw);
    if repeat && count == 0 {
        crate::cpu::execution::record_string(crate::cpu::string::StringExecution {
            iterations: 0,
            outcome: crate::cpu::string::StringOutcome::Complete,
        });
        return Ok(false);
    }
    let w = if op & 1 == 0 {
        8
    }
    else if op <= 0x6F {
        d.operand_size.min(32)
    }
    else {
        d.operand_size
    };
    let src = state::read_gpr(6) & mask(aw);
    let dst = state::read_gpr(7) & mask(aw);
    let seg = d.prefixes.segment.unwrap_or(3);
    let source =
        src.wrapping_add(if seg >= 4 { state::read_segment_base(seg as usize) } else { 0 });
    let f = state::read_flags64();
    if repeat && matches!(op, 0xA4 | 0xA5 | 0xAA | 0xAB) && state::read_dr(7) & 255 == 0 {
        if let Some(continuing) = bulk_string(
            op,
            w,
            aw,
            count,
            src,
            dst,
            source.wrapping_sub(src),
            f & 0x400 != 0,
        )? {
            return Ok(continuing);
        }
    }
    let mut nf = f;
    match op {
        0x6C..=0x6F => {
            let port = state::read_gpr(2) as u16;
            super::system::check_io_access(port, w)?;
            if op & 2 == 0 {
                // The entire destination must be writable before a device
                // read consumes data, including a second-page fault.
                memory::probe_write(dst, w, false)?;
                let value = match w {
                    8 => crate::cpu::cpu::io_port_read8(port as i32),
                    16 => crate::cpu::cpu::io_port_read16(port as i32),
                    _ => crate::cpu::cpu::io_port_read32(port as i32),
                };
                memory::write(dst, w, value as u32 as u64, false)?;
            }
            else {
                let value = memory::read(source, w, false)? as i32;
                match w {
                    8 => crate::cpu::cpu::io_port_write8(port as i32, value & 255),
                    16 => crate::cpu::cpu::io_port_write16(port as i32, value & 65535),
                    _ => crate::cpu::cpu::io_port_write32(port as i32, value),
                }
            }
            super::debug::io(port, (w / 8) as usize);
        },
        0xA4 | 0xA5 => {
            memory::probe_write(dst, w, false)?;
            let v = memory::read(source, w, false)?;
            memory::write(dst, w, v, false)?;
        },
        0xA6 | 0xA7 => {
            let a = memory::read(source, w, false)?;
            let b = memory::read(dst, w, false)?;
            nf = alu(7, a, b, w, f).1;
        },
        0xAA | 0xAB => memory::write(dst, w, state::read_gpr(0), false)?,
        0xAC | 0xAD => {
            let v = memory::read(source, w, false)?;
            set_register(0, v, w, true);
        },
        0xAE | 0xAF => {
            let b = memory::read(dst, w, false)?;
            nf = alu(7, state::read_gpr(0), b, w, f).1;
        },
        _ => return Err(Fault::ud()),
    }
    let delta = if f & 0x400 == 0 { (w / 8) as u64 } else { 0u64.wrapping_sub((w / 8) as u64) };
    if matches!(op, 0x6E | 0x6F | 0xA4..=0xA7 | 0xAC | 0xAD) {
        state::write_gpr(6, src.wrapping_add(delta), aw);
    }
    if matches!(op, 0x6C | 0x6D | 0xA4..=0xA7 | 0xAA | 0xAB | 0xAE | 0xAF) {
        state::write_gpr(7, dst.wrapping_add(delta), aw);
    }
    state::write_flags64(nf);
    if repeat {
        state::write_gpr(1, count - 1, aw);
        let cmp = matches!(op, 0xA6 | 0xA7 | 0xAE | 0xAF);
        let continuing = count > 1 && (!cmp || (nf & ZF != 0) == (d.prefixes.rep == Some(0xF3)));
        crate::cpu::execution::record_string(crate::cpu::string::StringExecution {
            iterations: 1,
            outcome: if continuing {
                crate::cpu::string::StringOutcome::Repeat
            }
            else {
                crate::cpu::string::StringOutcome::Complete
            },
        });
        return Ok(continuing);
    }
    Ok(false)
}
/// Elements of one REP MOVS/STOS step over RAM (about one page of data).
const BULK_BYTES: u64 = 4096;
/// REP MOVS/STOS over RAM pages without data breakpoints: each chunk is the
/// whole elements inside the current source and destination pages, copied
/// at once, or in element order when an element would read an earlier one's
/// store (so overlapping MOVS keeps its element semantics), and RCX/RSI/RDI
/// then advance as if the elements ran one by one. None when the
/// first element needs the element path (a fault, device memory, an element
/// crossing a page); a later chunk that cannot proceed just ends this step.
unsafe fn bulk_string(
    op: u32,
    w: u8,
    aw: u8,
    count: u64,
    src: u64,
    dst: u64,
    source_base: u64,
    down: bool,
) -> Result<Option<bool>, Fault> {
    let size = (w / 8) as u64;
    let movs = op <= 0xA5;
    let value = state::read_gpr(0);
    let (mut src, mut dst, mut remaining, mut done) = (src, dst, count, 0u64);
    while remaining != 0 && done * size < BULK_BYTES {
        // Whole elements in the current page, in the direction of travel.
        let room = |address: u64| {
            let offset = address & 4095;
            if offset + size > 4096 {
                0
            }
            else if down {
                offset / size + 1
            }
            else {
                (4096 - offset) / size
            }
        };
        let source = src.wrapping_add(source_base);
        let mut n = room(dst)
            .min(remaining)
            .min((BULK_BYTES / size).max(1) - done.min((BULK_BYTES / size).max(1) - 1));
        if movs {
            n = n.min(room(source));
        }
        // Host addresses: RAM through its backing, extended RAM through its
        // frame (which stays until the dispatch loop's next safe point,
        // crate::x64::extended::cache_frame). The flag: RAM (code may watch it).
        let mem8 = crate::cpu::memory::mem8 as u32;
        let mapped = |address: u64, access| -> Option<(u32, bool)> {
            let physical = memory::translate(address, access, false, false).ok()?;
            match super::jac::ram_backing(physical) {
                Some(page) => Some((mem8.wrapping_add(page + (address & 4095) as u32), true)),
                None => super::extended::cache_frame(
                    physical & !4095,
                    access == super::paging::Access::Write,
                )
                .map(|frame| (frame + (address & 4095) as u32, false)),
            }
        };
        let target = if n == 0 { None } else { mapped(dst, super::paging::Access::Write) };
        let from = if movs && target.is_some() {
            mapped(source, super::paging::Access::Read)
        }
        else {
            Some((0, false))
        };
        let (Some((target, target_ram)), Some((from, _))) = (target, from)
        else {
            if done == 0 {
                return Ok(None);
            }
            break;
        };
        // (a backward chunk's lowest byte is below its first element)
        let span = (n * size) as u32;
        let low = |first: u32| {
            if down {
                first.wrapping_add(size as u32).wrapping_sub(span)
            }
            else {
                first
            }
        };
        if movs {
            // One copy, unless an element reads what an earlier one wrote: a
            // forward move whose destination starts inside the source, a
            // backward one whose source starts inside the destination (LZ
            // backreferences; as cpu::string)
            let interferes = if down {
                from > target && from - target < span
            }
            else {
                target > from && target - from < span
            };
            if interferes {
                for i in 0..n {
                    let step = if down { (i * size).wrapping_neg() } else { i * size };
                    std::ptr::copy(
                        from.wrapping_add(step as u32) as usize as *const u8,
                        target.wrapping_add(step as u32) as usize as *mut u8,
                        size as usize,
                    );
                }
            }
            else {
                std::ptr::copy(
                    low(from) as usize as *const u8,
                    low(target) as usize as *mut u8,
                    span as usize,
                );
            }
        }
        else {
            // (every element stores the same value, in any order)
            let t = low(target) as usize as *mut u8;
            match size {
                1 => std::ptr::write_bytes(t, value as u8, n as usize),
                2 => (0..n as usize)
                    .for_each(|i| (t as *mut u16).add(i).write_unaligned(value as u16)),
                4 => (0..n as usize)
                    .for_each(|i| (t as *mut u32).add(i).write_unaligned(value as u32)),
                _ => (0..n as usize).for_each(|i| (t as *mut u64).add(i).write_unaligned(value)),
            }
        }
        if target_ram {
            let target = target.wrapping_sub(mem8);
            let (low, high) = if down {
                (
                    target + size as u32 - (n * size) as u32,
                    target + size as u32,
                )
            }
            else {
                (target, target + (n * size) as u32)
            };
            if crate::jit::page_watched(low >> 12) || crate::jit::page_watched((high - 1) >> 12) {
                crate::jit::jit_dirty_cache(low, high);
            }
        }
        let delta = if down { (n * size).wrapping_neg() } else { n * size };
        src = src.wrapping_add(delta) & mask(aw);
        dst = dst.wrapping_add(delta) & mask(aw);
        remaining -= n;
        done += n;
        if movs {
            state::write_gpr(6, src, aw);
        }
        state::write_gpr(7, dst, aw);
        state::write_gpr(1, remaining, aw);
    }
    crate::cpu::execution::record_string(crate::cpu::string::StringExecution {
        iterations: done as u32,
        outcome: if remaining != 0 {
            crate::cpu::string::StringOutcome::Repeat
        }
        else {
            crate::cpu::string::StringOutcome::Complete
        },
    });
    Ok(Some(remaining != 0))
}
/// Execute one architectural instruction or restartable REP element. The
/// caller delivers faults and accounts the retirement; this function never
/// recursively executes or yields to another core inside an atomic operation.
pub unsafe fn step() -> Result<(), Fault> {
    let start = state::GuestIp(state::read_rip());
    state::write_previous_rip(start.0);
    super::profile::tick(start.0);
    let mode = state::mode();
    // The first byte's translation is the same fault point as a fresh decode.
    let physical = memory::translate(start.0, super::paging::Access::Execute, false, false)?;
    let slot = (start.0 ^ start.0 >> 10) as usize & (DECODE_CACHE_SIZE - 1);
    if let Some(entry) = &(*(&raw const DECODE_CACHE))[slot] {
        if entry.rip == start.0
            && entry.physical == physical
            && entry.decoded.mode == mode
            && code_unchanged(physical, &entry.decoded)
        {
            let d = entry.decoded;
            let mut family = entry.family;
            let result = dispatch(&d, &mut family);
            if let Some(entry) = &mut (*(&raw mut DECODE_CACHE))[slot] {
                if entry.rip == start.0 {
                    entry.family = family;
                }
            }
            return result;
        }
    }
    let mut page = Some((start.0 >> 12, physical & !4095));
    let d = decode::decode_with(start, mode, |offset| {
        memory::fetch_cached(start.0.wrapping_add(offset as u64), &mut page)
    })
    .map_err(|e| match e {
        DecodeError::Fetch { error, .. } => error,
        DecodeError::TooLong => Fault::gp(),
        _ => Fault::ud(),
    })?;
    let mut family = UNKNOWN;
    let result = dispatch(&d, &mut family);
    if (physical & 4095) + d.length as u64 <= 4096
        && super::physical::plain_ram(physical, d.length as usize)
    {
        (*(&raw mut DECODE_CACHE))[slot] = Some(CachedDecode {
            rip: start.0,
            physical,
            decoded: d,
            family,
        });
    }
    result
}
// The executor that owns a decoded instruction. system/vector decline an
// instruction from its decoded fields alone, so the owner can be cached.
const UNKNOWN: u8 = 0;
const SYSTEM: u8 = 1;
const VECTOR: u8 = 2;
const INTEGER: u8 = 3;
unsafe fn dispatch(d: &Decoded, family: &mut u8) -> Result<(), Fault> {
    // LOCK, and XCHG with memory (implicitly locked), with other cores in workers
    if crate::parallel::active()
        && d.rm_register.is_none()
        && d.modrm.is_some()
        && (d.prefixes.lock || matches!(d.base_opcode(), 0x86 | 0x87))
    {
        return memory::run_locked(|| dispatch_unlocked(d, family));
    }
    dispatch_unlocked(d, family)
}
unsafe fn dispatch_unlocked(d: &Decoded, family: &mut u8) -> Result<(), Fault> {
    match *family {
        SYSTEM => {
            if super::system::execute(d)? {
                return Ok(());
            }
        },
        VECTOR => {
            if super::vector::execute(d)? {
                return Ok(());
            }
        },
        INTEGER => return execute(d),
        _ => {},
    }
    match super::system::execute(d) {
        Ok(false) => {},
        result => {
            *family = SYSTEM;
            return result.map(|_| ());
        },
    }
    match super::vector::execute(d) {
        Ok(false) => {},
        result => {
            *family = VECTOR;
            return result.map(|_| ());
        },
    }
    *family = INTEGER;
    execute(d)
}
/// Decoded instructions keyed by full RIP, physical address and mode. Every
/// hit revalidates the translation and the live code bytes, so a stale entry
/// after SMC, DMA or remapping is only a miss.
struct CachedDecode {
    rip: u64,
    physical: u64,
    decoded: Decoded,
    family: u8,
}
const DECODE_CACHE_SIZE: usize = 1024;
static mut DECODE_CACHE: [Option<CachedDecode>; DECODE_CACHE_SIZE] =
    [const { None }; DECODE_CACHE_SIZE];
unsafe fn code_unchanged(physical: u64, d: &Decoded) -> bool {
    let length = d.length as usize;
    super::physical::plain_ram(physical, length)
        && std::slice::from_raw_parts(crate::cpu::memory::mem8.add(physical as usize), length)
            == &d.bytes[..length]
}
/// Opcodes whose `execute` arm neither reads nor merges the FLAGS value.
fn flag_free(op: u32, group: u8) -> bool {
    matches!(op, 0x88..=0x8B | 0x8D | 0xB0..=0xBF | 0xC6 | 0xC7 | 0xA0..=0xA3 | 0x63
        | 0x0FB6 | 0x0FB7 | 0x0FBE | 0x0FBF | 0x86 | 0x87 | 0x90..=0x97 | 0x50..=0x5F | 0x68 | 0x6A
        | 0x8F | 0xC8 | 0xC9 | 0xE8 | 0xE9 | 0xEB | 0xC2 | 0xC3 | 0x98 | 0x99 | 0x0FC8..=0x0FCF
        | 0x0F0D | 0x0F18..=0x0F1F | 0x0FC3 | 0x0F38F0 | 0x0F38F1)
        || op == 0xFF && matches!(group, 2 | 4 | 6)
}
pub unsafe fn execute(d: &Decoded) -> Result<(), Fault> {
    if !d.mode.is_long() {
        return Err(Fault::ud());
    }
    let op = d.base_opcode();
    let w = d.operand_size;
    let rex = d.prefixes.rex.is_some();
    let group = d.modrm.map_or(0, |m| m >> 3 & 7);
    let imm = d.immediate.map_or(0, |i| i.value);
    // Materializing lazy FLAGS is skipped for arms that never read them.
    let flags = if flag_free(op, group) { 0 } else { state::read_flags64() };
    let mut next = d.next.0;
    match op {
        // Cache hints never access the hinted data and do not raise a page
        // fault even for unmapped or noncanonical addresses.
        0x0F0D | 0x0F18 => {},
        0x0FC3 => {
            if w == 16 || d.address.is_none() {
                return Err(Fault::ud());
            }
            let (addr, stack) = address(d);
            memory::write(addr, w, state::read_gpr(d.reg.unwrap() as usize), stack)?;
        },
        0x00..=0x3D if op & 7 <= 5 => {
            let aluop = (op >> 3) as u8;
            let width = if op & 1 == 0 { 8 } else { w };
            let form = op & 7;
            let (a, b) = if form <= 1 {
                (
                    rm(d, width, aluop != 7)?,
                    register(d.reg.unwrap(), width, rex),
                )
            }
            else if form <= 3 {
                (register(d.reg.unwrap(), width, rex), rm(d, width, false)?)
            }
            else {
                (register(0, width, rex), imm)
            };
            let (r, f) = alu(aluop, a, b, width, flags);
            if aluop != 7 {
                if form <= 1 {
                    put_rm(d, width, r)?;
                }
                else {
                    set_register(if form <= 3 { d.reg.unwrap() } else { 0 }, r, width, rex);
                }
            }
            state::write_flags64(f);
        },
        0x80 | 0x81 | 0x83 => {
            let width = if op == 0x80 { 8 } else { w };
            let a = rm(d, width, group != 7)?;
            let (r, f) = alu(group, a, imm, width, flags);
            if group != 7 {
                put_rm(d, width, r)?;
            }
            state::write_flags64(f);
        },
        0x84 | 0x85 | 0xA8 | 0xA9 => {
            let width = if op & 1 == 0 { 8 } else { w };
            let (a, b) = if op < 0xA0 {
                (rm(d, width, false)?, register(d.reg.unwrap(), width, rex))
            }
            else {
                (register(0, width, rex), imm)
            };
            state::write_flags64(alu(4, a, b, width, flags).1);
        },
        0x88..=0x8B => {
            let width = if op & 1 == 0 { 8 } else { w };
            if op & 2 == 0 {
                put_rm(d, width, register(d.reg.unwrap(), width, rex))?;
            }
            else {
                let v = rm(d, width, false)?;
                set_register(d.reg.unwrap(), v, width, rex);
            }
        },
        0x8D => {
            if d.address.is_none() {
                return Err(Fault::ud());
            }
            let mut regs = [0; 16];
            for i in 0..16 {
                regs[i] = state::read_gpr(i);
            }
            set_register(
                d.reg.unwrap(),
                d.address.unwrap().offset(&regs, d.next),
                w,
                rex,
            );
        },
        0xB0..=0xBF => set_register(
            d.opcode_register.unwrap(),
            imm,
            if op < 0xB8 { 8 } else { w },
            rex,
        ),
        0xC6 | 0xC7 => put_rm(d, if op == 0xC6 { 8 } else { w }, imm)?,
        0xA0..=0xA3 => {
            let width = if op & 1 == 0 { 8 } else { w };
            let seg = d.prefixes.segment.unwrap_or(3);
            let a =
                imm.wrapping_add(if seg >= 4 { state::read_segment_base(seg as usize) } else { 0 });
            if op & 2 == 0 {
                let v = memory::read(a, width, false)?;
                set_register(0, v, width, rex);
            }
            else {
                memory::write(a, width, register(0, width, rex), false)?;
            }
        },
        0x63 => {
            let sw = if w == 16 { 16 } else { 32 };
            let v = rm(d, sw, false)?;
            set_register(d.reg.unwrap(), signed(v, sw) as u64, w, rex);
        },
        0x0FB6 | 0x0FB7 | 0x0FBE | 0x0FBF => {
            let sw = if op & 1 == 0 { 8 } else { 16 };
            let v = rm(d, sw, false)?;
            set_register(
                d.reg.unwrap(),
                if op & 8 != 0 { signed(v, sw) as u64 } else { v },
                w,
                rex,
            );
        },
        0x86 | 0x87 => {
            let width = if op == 0x86 { 8 } else { w };
            let a = rm(d, width, true)?;
            let b = register(d.reg.unwrap(), width, rex);
            put_rm(d, width, b)?;
            set_register(d.reg.unwrap(), a, width, rex);
        },
        0x90..=0x97 => {
            let r = d.opcode_register.unwrap();
            // PAUSE (F3 90) is a spin-wait hint: as in the legacy interpreter,
            // end this core's slice so the lock holder can run.
            if r == 0 && d.prefixes.rep == Some(0xF3) && crate::cpu::apic::core_count() > 1 {
                crate::cpu::cpu::yield_to_other_cores();
            }
            if r != 0 {
                let a = register(0, w, rex);
                let b = register(r, w, rex);
                set_register(0, b, w, rex);
                set_register(r, a, w, rex);
            }
        },
        0x50..=0x57 => push(register(d.opcode_register.unwrap(), w, rex), w)?,
        0x58..=0x5F => {
            let v = peek(w)?;
            state::write_gpr(4, state::read_gpr(4).wrapping_add((w / 8) as u64), 64);
            set_register(d.opcode_register.unwrap(), v, w, rex);
        },
        0x68 | 0x6A => push(imm, w)?,
        0x8F => {
            let v = peek(w)?;
            let rsp = state::read_gpr(4).wrapping_add((w / 8) as u64);
            if let Some(r) = d.rm_register {
                state::write_gpr(4, rsp, 64);
                set_register(r, v, w, rex);
            }
            else {
                let (a, s) = address_rsp(d, Some(rsp));
                memory::write(a, w, v, s)?;
                state::write_gpr(4, rsp, 64);
            }
        },
        0x9C => push(flags & !0x30000, w)?,
        0x9D => {
            let v = peek(w)?;
            state::write_gpr(4, state::read_gpr(4).wrapping_add((w / 8) as u64), 64);
            state::write_flags64(popf_flags(flags, v, w, *crate::cpu::global_pointers::cpl));
        },
        0xC8 => {
            let nesting = d.extra_immediate.unwrap_or(0) & 31;
            let old_rsp = state::read_gpr(4);
            let old_rbp = state::read_gpr(5);
            let bytes = (w / 8) as u64;
            let frame = old_rsp.wrapping_sub(bytes);
            let count = if nesting == 0 { 1 } else { nesting as usize + 1 };
            let mut values = [0u64; 32];
            values[0] = old_rbp;
            for i in 0..count {
                memory::probe_write(old_rsp.wrapping_sub(bytes * (i as u64 + 1)), w, true)?;
            }
            for i in 1..nesting as usize {
                values[i] = memory::read(old_rbp.wrapping_sub(bytes * i as u64), w, true)?;
            }
            if nesting != 0 {
                values[nesting as usize] = frame;
            }
            let final_rsp = old_rsp.wrapping_sub(bytes * count as u64).wrapping_sub(imm);
            memory::probe_write(final_rsp, w, true)?;
            for i in 0..count {
                memory::write(
                    old_rsp.wrapping_sub(bytes * (i as u64 + 1)),
                    w,
                    values[i],
                    true,
                )?;
            }
            state::write_gpr(5, frame, w);
            state::write_gpr(4, final_rsp, 64);
        },
        0xC9 => {
            let rsp = state::read_gpr(5);
            let v = memory::read(rsp, w, true)?;
            state::write_gpr(4, rsp.wrapping_add((w / 8) as u64), 64);
            state::write_gpr(5, v, w);
        },
        0xE8 => {
            next = branch(relative(d))?;
            push(d.next.0, 64)?;
        },
        0xE9 | 0xEB => next = branch(relative(d))?,
        0xC2 | 0xC3 => {
            next = branch(peek(64)?)?;
            state::write_gpr(4, state::read_gpr(4).wrapping_add(8 + imm), 64);
        },
        0x70..=0x7F | 0x0F80..=0x0F8F => {
            if condition(op as u8 & 15, flags) {
                next = branch(relative(d))?;
            }
        },
        0xE0..=0xE3 => {
            let old = state::read_gpr(1) & mask(d.address_size);
            let count = old.wrapping_sub(1) & mask(d.address_size);
            let take = match op {
                0xE0 => count != 0 && flags & ZF == 0,
                0xE1 => count != 0 && flags & ZF != 0,
                0xE2 => count != 0,
                _ => old == 0,
            };
            if take {
                next = branch(relative(d))?;
            }
            if op != 0xE3 {
                state::write_gpr(1, count, d.address_size);
            }
        },
        0x0F40..=0x0F4F => {
            let v = rm(d, w, false)?;
            if condition(op as u8 & 15, flags) {
                set_register(d.reg.unwrap(), v, w, rex);
            }
            else if w == 32 {
                // A false 32-bit CMOV still clears the destination's upper
                // half; the source remains faultable regardless of condition.
                let old = register(d.reg.unwrap(), w, rex);
                set_register(d.reg.unwrap(), old, w, rex);
            }
        },
        0x0F90..=0x0F9F => put_rm(d, 8, condition(op as u8 & 15, flags) as u64)?,
        0xC0 | 0xC1 | 0xD0..=0xD3 => {
            let width = if op & 1 == 0 { 8 } else { w };
            let count = if op <= 0xC1 {
                imm as u8
            }
            else if op <= 0xD1 {
                1
            }
            else {
                state::read_gpr(1) as u8
            };
            let a = rm(d, width, true)?;
            let (r, f) = shift(group, a, count, width, flags);
            put_rm(d, width, r)?;
            state::write_flags64(f);
        },
        0xFE | 0xFF if group <= 1 => {
            let width = if op == 0xFE { 8 } else { w };
            let a = rm(d, width, true)?;
            let (r, f) = alu(if group == 0 { 0 } else { 5 }, a, 1, width, flags);
            put_rm(d, width, r)?;
            state::write_flags64(f & !CF | flags & CF);
        },
        0xFF if group == 2 || group == 4 => {
            next = branch(rm(d, 64, false)?)?;
            if group == 2 {
                push(d.next.0, 64)?;
            }
        },
        0xFF if group == 6 => {
            let v = rm(d, w, false)?;
            push(v, w)?;
        },
        0xF6 | 0xF7 => {
            let width = if op == 0xF6 { 8 } else { w };
            let a = rm(d, width, matches!(group, 2 | 3))?;
            match group {
                // F6/F7 /1 is an alias of TEST
                0 | 1 => state::write_flags64(alu(4, a, imm, width, flags).1),
                2 => put_rm(d, width, !a)?,
                3 => {
                    let (r, f) = alu(5, 0, a, width, flags);
                    put_rm(d, width, r)?;
                    state::write_flags64(f);
                },
                4 | 5 => {
                    let lhs = register(0, width, rex);
                    let full = if group == 4 {
                        lhs as u128 * a as u128
                    }
                    else {
                        (signed(lhs, width) * signed(a, width)) as u128
                    };
                    let lo = full as u64 & mask(width);
                    let hi = (full >> width) as u64 & mask(width);
                    let overflow = if group == 4 {
                        hi != 0
                    }
                    else {
                        signed(lo, width) != (signed(lhs, width) * signed(a, width))
                    };
                    if width == 8 {
                        state::write_gpr(0, full as u64, 16);
                    }
                    else {
                        state::write_gpr(0, lo, width);
                        state::write_gpr(2, hi, width);
                    }
                    state::write_flags64(flags & !(CF | OF) | if overflow { CF | OF } else { 0 });
                },
                6 | 7 => {
                    if a == 0 {
                        return Err(Fault::de());
                    }
                    let full = if width == 8 {
                        state::read_gpr(0) & 65535
                    }
                    else {
                        register(0, width, rex) | 0
                    };
                    let dividend = if width == 8 {
                        full as u128
                    }
                    else {
                        full as u128 | ((register(2, width, rex) as u128) << width)
                    };
                    let (q, r) = if group == 6 {
                        let q = dividend / (a as u128);
                        if q > mask(width) as u128 {
                            return Err(Fault::de());
                        }
                        (q as u64, (dividend % (a as u128)) as u64)
                    }
                    else {
                        let bits = width as u32 * 2;
                        let dividend = if bits == 128 {
                            dividend as i128
                        }
                        else {
                            ((dividend << (128 - bits)) as i128) >> (128 - bits)
                        };
                        let divisor = signed(a, width);
                        let q = dividend.checked_div(divisor).ok_or_else(Fault::de)?;
                        if q < -(1i128 << (width - 1)) || q > (1i128 << (width - 1)) - 1 {
                            return Err(Fault::de());
                        }
                        (q as u64, (dividend % divisor) as u64)
                    };
                    if width == 8 {
                        state::write_gpr(0, (q & 255) | ((r & 255) << 8), 16);
                    }
                    else {
                        state::write_gpr(0, q, width);
                        state::write_gpr(2, r, width);
                    }
                },
                _ => return Err(Fault::ud()),
            }
        },
        0x69 | 0x6B | 0x0FAF => {
            let a = rm(d, w, false)?;
            let b = if op == 0x0FAF { register(d.reg.unwrap(), w, rex) } else { imm };
            let full = signed(a, w) * signed(b, w);
            let r = full as u64 & mask(w);
            set_register(d.reg.unwrap(), r, w, rex);
            state::write_flags64(
                flags & !(CF | OF) | if signed(r, w) != full { CF | OF } else { 0 },
            );
        },
        0x98 => {
            let sw = w / 2;
            state::write_gpr(0, signed(state::read_gpr(0), sw) as u64, w);
        },
        0x99 => state::write_gpr(
            2,
            if signed(state::read_gpr(0), w) < 0 { u64::MAX } else { 0 },
            w,
        ),
        0x0FC0 | 0x0FC1 => {
            let width = if op == 0x0FC0 { 8 } else { w };
            let a = rm(d, width, true)?;
            let b = register(d.reg.unwrap(), width, rex);
            let (r, f) = alu(0, a, b, width, flags);
            put_rm(d, width, r)?;
            if d.rm_register != d.reg {
                set_register(d.reg.unwrap(), a, width, rex);
            }
            state::write_flags64(f);
        },
        0x0FB0 | 0x0FB1 => {
            let width = if op == 0x0FB0 { 8 } else { w };
            let old = rm(d, width, true)?;
            let a = register(0, width, rex);
            let (_, f) = alu(7, a, old, width, flags);
            // A failed register compare does not write DEST (and therefore
            // preserves its inaccessible upper half). Memory still gets the
            // mandatory write cycle even when the comparison fails.
            if a == old || d.rm_register.is_none() {
                put_rm(
                    d,
                    width,
                    if a == old { register(d.reg.unwrap(), width, rex) } else { old },
                )?;
            }
            if a != old {
                set_register(0, old, width, rex);
            }
            state::write_flags64(f);
        },
        // XRSTORS, XSAVEC, XSAVES (the decoder required their features)
        0x0FC7 if (3..=5).contains(&group) => crate::x64::vector::compacted_state(d, group)?,
        0x0FC7 if group == 6 => {
            // RDRAND is NFx: an F2/F3 prefix is #UD
            if d.prefixes.rep.is_some() {
                return Err(Fault::ud());
            }
            let r = d.rm_register.ok_or(Fault::ud())?;
            let low = crate::cpu::cpu::js::get_rand_int() as u32 as u64;
            let value = if w == 64 {
                low | (crate::cpu::cpu::js::get_rand_int() as u32 as u64) << 32
            }
            else {
                low
            };
            set_register(r, value, w, rex);
            state::write_flags64(flags & !ARITH | CF);
        },
        0x0FC7 if group == 1 => {
            let (a, s) = address(d);
            if w == 128 {
                if a & 15 != 0 {
                    return Err(Fault::gp());
                }
                memory::probe_write(a, 128, s)?;
                let old = memory::read128(a, s)?;
                let expected = state::read_gpr(0) as u128 | ((state::read_gpr(2) as u128) << 64);
                let equal = old == expected;
                let value = if equal {
                    state::read_gpr(3) as u128 | ((state::read_gpr(1) as u128) << 64)
                }
                else {
                    old
                };
                memory::write128(a, value, s)?;
                if !equal {
                    state::write_gpr(0, old as u64, 64);
                    state::write_gpr(2, (old >> 64) as u64, 64);
                }
                state::write_flags64(flags & !ZF | if equal { ZF } else { 0 });
            }
            else {
                memory::probe_write(a, 64, s)?;
                let old = memory::read(a, 64, s)?;
                let expected =
                    state::read_gpr(0) as u32 as u64 | ((state::read_gpr(2) as u32 as u64) << 32);
                let equal = old == expected;
                let value = if equal {
                    state::read_gpr(3) as u32 as u64 | ((state::read_gpr(1) as u32 as u64) << 32)
                }
                else {
                    old
                };
                memory::write(a, 64, value, s)?;
                if !equal {
                    state::write_gpr(0, old, 32);
                    state::write_gpr(2, old >> 32, 32);
                }
                state::write_flags64(flags & !ZF | if equal { ZF } else { 0 });
            }
        },
        0x0FA3 | 0x0FAB | 0x0FB3 | 0x0FBB | 0x0FBA => {
            let action = if op == 0x0FBA { group - 4 } else { ((op >> 3) & 3) as u8 };
            let index = if op == 0x0FBA { imm } else { register(d.reg.unwrap(), w, rex) };
            let bit = index & (w as u64 - 1);
            let mut memory_address = None;
            let old = if d.rm_register.is_some() {
                rm(d, w, action != 0)?
            }
            else {
                let (a, stack) = address(d);
                let displacement = if op == 0x0FBA {
                    0
                }
                else {
                    (signed(index, w) >> (w.trailing_zeros())) * (w as i128 / 8)
                };
                let a = a.wrapping_add(displacement as u64);
                if action != 0 {
                    memory::probe_write(a, w, stack)?;
                }
                memory_address = Some((a, stack));
                memory::read(a, w, stack)?
            };
            let value = match action {
                0 => old,
                1 => old | (1 << bit),
                2 => old & !(1 << bit),
                3 => old ^ (1 << bit),
                _ => unreachable!(),
            };
            if action != 0 {
                if let Some((a, stack)) = memory_address {
                    memory::write(a, w, value, stack)?;
                }
                else {
                    put_rm(d, w, value)?;
                }
            }
            state::write_flags64(flags & !CF | ((old >> bit) & CF));
        },
        // TZCNT and LZCNT (F3 0F BC/BD: rows of their features; BSF and BSR
        // without): the operand's size for 0, CF
        0x0FBC | 0x0FBD if d.opcode >> 16 == 0xF3 => {
            let v = rm(d, w, false)?;
            let (value, arithmetic) = if op == 0x0FBD {
                crate::cpu::bmi::lzcnt(v, w as u32)
            }
            else {
                crate::cpu::bmi::tzcnt(v, w as u32)
            };
            set_register(d.reg.unwrap(), value, w, rex);
            state::write_flags64(flags & !ARITH | arithmetic as u64);
        },
        0x0FBC | 0x0FBD => {
            let v = rm(d, w, false)?;
            if v == 0 {
                state::write_flags64(flags | ZF);
            }
            else {
                let value = if op == 0x0FBC { v.trailing_zeros() } else { 63 - v.leading_zeros() };
                set_register(d.reg.unwrap(), value as u64, w, rex);
                state::write_flags64(flags & !ZF);
            }
        },
        0x0FB8 if d.opcode == 0xF30FB8 => {
            let v = rm(d, w, false)?;
            set_register(d.reg.unwrap(), v.count_ones() as u64, w, rex);
            state::write_flags64(flags & !ARITH | if v == 0 { ZF } else { 0 });
        },
        // MOVBE (0F 38 F0: load, F1: store; memory only): one access of the
        // operand size, its bytes reversed
        0x0F38F0 if d.opcode == 0x0F38F0 => {
            let v = crate::cpu::bmi::byte_swap(rm(d, w, false)?, w as u32);
            set_register(d.reg.unwrap(), v, w, rex);
        },
        0x0F38F1 if d.opcode == 0x0F38F1 => {
            let v = register(d.reg.unwrap(), w, rex);
            put_rm(d, w, crate::cpu::bmi::byte_swap(v, w as u32))?;
        },
        // CRC32 r32/r64, r/m8 (F2 0F 38 F0) and r/m16/32/64 (F1): the CRC-32C
        // in the low half of the destination, the rest zero; no flags
        0x0F38F0 | 0x0F38F1 if d.opcode >> 24 == 0xF2 => {
            let width = if op == 0x0F38F0 { 8 } else { w };
            let v = rm(d, width, false)?;
            let r = d.reg.unwrap();
            let crc =
                crate::cpu::simd_int::crc32c(register(r, 32, rex) as u32, v, width as u32 / 8);
            set_register(r, crc as u64, 32, rex);
        },
        0x0FA4 | 0x0FA5 | 0x0FAC | 0x0FAD => {
            let count = (if op & 1 == 0 { imm } else { state::read_gpr(1) }) as u8
                & if w == 64 { 63 } else { 31 };
            let a = rm(d, w, true)?;
            let b = register(d.reg.unwrap(), w, rex);
            if count != 0 {
                let count = count % w;
                let left = op & 8 == 0;
                let r = if count == 0 {
                    b
                }
                else if left {
                    (a << count) | (b >> (w - count))
                }
                else {
                    (a >> count) | (b << (w - count))
                };
                let r = r & mask(w);
                let cf = if count == 0 {
                    a & 1 != 0
                }
                else if left {
                    a >> (w - count) & 1 != 0
                }
                else {
                    a >> (count - 1) & 1 != 0
                };
                let mut f = flags & !(CF | SF | ZF | PF) | szp(r, w) | if cf { CF } else { 0 };
                if count == 1 {
                    f = f & !OF | if (a ^ r) >> (w - 1) != 0 { OF } else { 0 };
                }
                put_rm(d, w, r)?;
                state::write_flags64(f);
            }
            else {
                put_rm(d, w, a)?;
            }
        },
        0x0FC8..=0x0FCF => {
            let r = (op as u8 & 7) | d.prefixes.b();
            let v = state::read_gpr(r as usize);
            state::write_gpr(
                r as usize,
                if w == 64 { v.swap_bytes() } else { (v as u32).swap_bytes() as u64 },
                w,
            );
        },
        0x6C..=0x6F | 0xA4..=0xA7 | 0xAA..=0xAF => {
            if string(d, op)? {
                next = d.start.0;
            }
        },
        0xF5 => state::write_flags64(flags ^ CF),
        0xF8 => state::write_flags64(flags & !CF),
        0xF9 => state::write_flags64(flags | CF),
        0xFC => state::write_flags64(flags & !0x400),
        0xFD => state::write_flags64(flags | 0x400),
        0x9E => state::write_flags64(
            flags & !(SF | ZF | AF | PF | CF)
                | (state::read_high_byte(0) as u64) & (SF | ZF | AF | PF | CF),
        ),
        0x9F => state::write_high_byte(0, (flags as u8 & 0xD5) | 2),
        // hint space 0F19-0F1F: reserved NOPs without the matching extension
        0x0F19..=0x0F1F => {},
        0xD7 => {
            // XLAT: AL = [seg:rBX + AL]
            let seg = d.prefixes.segment.unwrap_or(3);
            let offset =
                state::read_gpr(3).wrapping_add(state::read_gpr(0) & 0xFF) & mask(d.address_size);
            let base = if seg >= 4 { state::read_segment_base(seg as usize) } else { 0 };
            let v = memory::read(offset.wrapping_add(base), 8, seg == 2)?;
            set_register(0, v, 8, false);
        },
        0x0FB9 | 0x0FFF => return Err(Fault::ud()),
        _ => return Err(Fault::ud()),
    }
    state::write_rip(next);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn alu_width_boundaries() {
        for w in [8, 16, 32, 64] {
            let m = mask(w);
            let sign = 1u64 << (w - 1);
            assert_eq!(alu(0, m, 1, w, 0).0, 0);
            assert_eq!(alu(0, m, 1, w, 0).1 & (CF | ZF), CF | ZF);
            assert_ne!(alu(0, sign - 1, 1, w, 0).1 & OF, 0);
            assert_ne!(alu(5, sign, 1, w, 0).1 & OF, 0);
            assert_eq!(alu(2, m, 0, w, CF).0, 0);
            assert_ne!(alu(3, 0, m, w, CF).1 & CF, 0);
            assert_eq!(alu(6, m, m, w, u64::MAX).1 & ARITH, ZF | PF);
        }
    }
    #[test]
    fn byte_alu_exhaustive() {
        for a in 0..256 {
            for b in 0..256 {
                for carry in 0..2 {
                    for op in [0, 2, 3, 5, 7] {
                        let (r, f) = alu(op, a, b, 8, carry);
                        let c = if op == 2 || op == 3 { carry as i32 } else { 0 };
                        let exact = if op == 0 || op == 2 {
                            a as i32 + b as i32 + c
                        }
                        else {
                            a as i32 - b as i32 - c
                        };
                        let signed_exact = if op == 0 || op == 2 {
                            a as i8 as i32 + b as i8 as i32 + c
                        }
                        else {
                            a as i8 as i32 - b as i8 as i32 - c
                        };
                        assert_eq!(r, exact as u8 as u64);
                        assert_eq!(f & CF != 0, exact < 0 || exact > 255);
                        assert_eq!(f & OF != 0, !(-128..=127).contains(&signed_exact));
                    }
                }
            }
        }
    }
    #[test]
    fn shifts_counts_and_sign() {
        for w in [8, 16, 32, 64] {
            for count in 0..=255 {
                for op in 0..8 {
                    let (r, f) = shift(op, mask(w), count, w, 0x8D5);
                    assert_eq!(r & !mask(w), 0);
                    if count & (if w == 64 { 63 } else { 31 }) == 0 {
                        assert_eq!(r, mask(w));
                        assert_eq!(f, 0x8D5);
                    }
                }
            }
            assert_eq!(
                shift(7, 1 << (w - 1), 1, w, 0).0,
                (1 << (w - 1)) | (1 << (w - 2))
            );
        }
    }
    #[test]
    fn popf_privilege_masks_and_full_width_rotate_carry() {
        assert_eq!(shift(0, 0x98, 8, 8, CF).1 & CF, 0);
        assert_eq!(shift(1, 0x80, 8, 8, 0).1 & CF, CF);
        assert_eq!(shift(2, 0x98, 9, 8, CF).1 & CF, CF);
        let old = 0x1B0202;
        assert_eq!(popf_flags(old, 0, 64, 3) & 0x1B3200, old & 0x1B3200);
        assert_eq!(popf_flags(0x3202, 0, 64, 0) & 0x3200, 0);
        assert_ne!(popf_flags(2, 0x102, 64, 3) & 0x100, 0);
        assert_eq!(popf_flags(0x240002, 0, 16, 0) & !65535, 0x240000);
    }
}
                                                                                                                                                                                                                                                 source/v64/src/rust/x64/extended.rs                                                                 0000644 0000000 0000000 00000023612 00000000000 014243  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Guest RAM beyond the wasm32 backing store
//! (docs/x86-64.md): "extended RAM" at guest
//! physical [base, base + pages * 4 KiB), above the RAM windows of
//! crate::x64::physical. Its pages live in a host store (JavaScript
//! ArrayBuffers, shared with vCPU workers: `js::extended_load` and
//! `js::extended_store` copy one page) and are cached in a pool of 4 KiB
//! frames in the wasm heap.
//!
//! The bus reports the range as neither RAM nor MMIO (`WindowKind::Extended`):
//! TLBs never treat it as RAM, and the interpreter's
//! accesses come here, so a frame can be written back and reused at any of
//! them. One exception makes extended RAM fast enough for an OS to keep its
//! own data there: the access cache of compiled page functions
//! (crate::x64::jac) and the 32-bit TLB of compatibility mode may map a page
//! to its frame (`cache_frame`, with cores on one thread only). Such a frame is marked CACHED and is never reused
//! while marked; when too many are, the dispatch loop's next safe point
//! (`safe_point`, no compiled code active) retires every access cache entry
//! and unmarks them all. A write entry marks the frame dirty up front, as
//! stores through it bypass this module. (Host copies outside the CPU pin
//! their frame, `x64_ext_pin`; with no reusable frame left, an access goes
//! through a separate bounce frame.)
//!
//! Page functions (crate::x64::pages) are compiled from extended pages too,
//! with cores on one thread only. Such a function is keyed by the page, not
//! its frame, so it survives the frame's eviction. The page is marked in
//! `code`; every write reaches it through `resident` (the interpreter, DMA,
//! the bounce frame), which retires the function, and the access cache gets
//! no write entry for it (`cache_frame`).
//! Compatibility-mode helpers, which work with 32-bit bus addresses, reach
//! extended pages through a small aperture in that bus (`aperture`).
//!
//! With cores in workers, one lock serializes the module. It is re-entrant
//! for its owner: a locked read-modify-write instruction holds it from the
//! operand's read to its write (crate::x64::memory::run_locked), which makes
//! the instruction atomic with respect to every other core's accesses here.
//!
//! The frames, the lock and the store are the engine both cores share
//! (crate::extended, docs/arm64-virt-android16-plan.md P8.5); this module is
//! the x86 core's part: the access caches' frames, the page-tier keys, the
//! aperture and the 32-bit TLBs of compatibility mode (crate::isa's
//! extended_* hooks), the exports.

use crate::extended::{self, ext, CACHED, DIRTY, PAGE};
use crate::parallel::machine;

pub use crate::extended::{
    contains, copy_page, lock, or64, range, read, release_held_by, safe_point, unlock,
    unwatch_code, watch_code, write,
};

/// a 32-bit TLB of compatibility mode holds a frame (crate::cpu::cpu::fill_ia32e_tlb)
static mut LEGACY_TLB_CACHED: bool = false;
pub unsafe fn note_legacy_tlb() { LEGACY_TLB_CACHED = true; }

/// (crate::isa::extended_release_caches) every access cache entry and, if
/// they hold frames, the 32-bit TLBs of compatibility mode
pub unsafe fn release_caches() {
    super::jac::flush_all();
    if LEGACY_TLB_CACHED {
        LEGACY_TLB_CACHED = false;
        crate::cpu::context::invalidate_legacy_tlbs();
    }
}
/// (crate::isa::extended_retire_cached_writes) the write entries to a frame
/// whose page now has code
pub unsafe fn retire_cached_writes(host: u32) {
    super::jac::retire_writes_to_host(host);
    if LEGACY_TLB_CACHED {
        LEGACY_TLB_CACHED = false;
        crate::cpu::context::invalidate_legacy_tlbs();
    }
}

/// The host address of the frame of the extended page at `address` for the
/// access cache of compiled page functions (crate::x64::pages), or None:
/// with cores in workers (their access caches cannot be retired at one
/// safe point), when no frame is reusable before the next safe point, or
/// for a write to a page with page-tier code (the interpreter's write
/// retires that code)
pub unsafe fn cache_frame(address: u64, write: bool) -> Option<u32> {
    if crate::parallel::active() || !contains(address) {
        return None;
    }
    let e = ext();
    let page = ((address - e.base) / PAGE) as u32;
    if write && extended::has_code(e, page) {
        return None;
    }
    let frame = extended::resident(e, page, write)?;
    extended::mark_cached(e, frame);
    // (stores through the entry are not seen here)
    if write {
        e.frame_state[frame as usize] |= DIRTY;
    }
    debug_assert!(e.frame_state[frame as usize] & CACHED != 0);
    Some(e.pool.add(frame as usize * PAGE as usize) as u32)
}

/// Page functions of extended pages have keys from here on
/// (crate::x64::pages): above every RAM backing page number
pub const CODE_KEY_BASE: u32 = 1 << 20;

/// The page-tier key of the extended page at `address`, or None: not
/// extended RAM, or cores run in workers (their writes are not tracked in
/// `code`; see crate::x64::pages::retire_extended)
pub unsafe fn code_key(address: u64) -> Option<u32> {
    if crate::parallel::active() || !contains(address) {
        return None;
    }
    Some(CODE_KEY_BASE + ((address - ext().base) / PAGE) as u32)
}

/// A locked instruction's operand is here: keep the lock until it ends
pub unsafe fn begin_locked_operand() {
    lock();
    ext().stats[extended::STAT_LOCKED] += 1;
}

pub mod aperture {
    //! Compatibility-mode (32-bit) memory helpers take 32-bit bus
    //! addresses (crate::x64::memory::legacy_translate). An extended page
    //! gets a slot of this aperture, a range of the 32-bit bus the platform
    //! leaves unused (above the local APIC, below the BIOS; not between the
    //! IOAPIC and the local APIC, where Q35 has its HPET at 0xFED00000 and
    //! its root complex registers at 0xFED1C000): an address in it reaches
    //! the page through crate::cpu::memory's mapped (MMIO) path, never
    //! cached, never compiled from. Each core reuses its own slots in order,
    //! so the few pages one instruction touches keep theirs.
    use super::*;

    pub const BASE: u32 = 0xFEF0_0000;
    const SLOTS_PER_CORE: u32 = 32;
    pub const SIZE: u32 = crate::parallel::MAX_CORES as u32 * SLOTS_PER_CORE * PAGE as u32;

    static mut SLOT_PAGE: [u64; crate::parallel::MAX_CORES * SLOTS_PER_CORE as usize] =
        [u64::MAX; crate::parallel::MAX_CORES * SLOTS_PER_CORE as usize];
    static mut NEXT: [u32; crate::parallel::MAX_CORES] = [0; crate::parallel::MAX_CORES];

    #[inline]
    pub fn contains(address: u32) -> bool { address.wrapping_sub(BASE) < SIZE }

    /// The bus address of the extended RAM byte at `address`
    pub unsafe fn map(address: u64) -> u32 {
        let core = crate::cpu::apic::current_core();
        let page = address & !(PAGE - 1);
        let slots = machine(&raw mut SLOT_PAGE)
            .cast::<u64>()
            .add(core * SLOTS_PER_CORE as usize);
        let mut slot = SLOTS_PER_CORE;
        for i in 0..SLOTS_PER_CORE {
            if *slots.add(i as usize) == page {
                slot = i;
                break;
            }
        }
        if slot == SLOTS_PER_CORE {
            let next = machine(&raw mut NEXT).cast::<u32>().add(core);
            slot = *next;
            *next = (slot + 1) % SLOTS_PER_CORE;
            *slots.add(slot as usize) = page;
            ext().stats[extended::STAT_APERTURE] += 1;
        }
        BASE + (core as u32 * SLOTS_PER_CORE + slot) * PAGE as u32 + (address % PAGE) as u32
    }

    /// The guest physical address behind an aperture address, if it has one
    pub unsafe fn guest(address: u32) -> Option<u64> {
        if !contains(address) {
            return None;
        }
        let index = ((address - BASE) / PAGE as u32) as usize;
        let page = *machine(&raw mut SLOT_PAGE).cast::<u64>().add(index);
        (page != u64::MAX && super::contains(page)).then_some(page + (address as u64 % PAGE))
    }

    pub unsafe fn clear() {
        let slots = machine(&raw mut SLOT_PAGE).cast::<u64>();
        for i in 0..crate::parallel::MAX_CORES * SLOTS_PER_CORE as usize {
            *slots.add(i) = u64::MAX;
        }
    }

    /// An aperture byte (for the mapped path of crate::cpu::memory)
    pub unsafe fn read8(address: u32) -> Option<u8> {
        guest(address).map(|at| super::read(at, 1) as u8)
    }
    pub unsafe fn write8(address: u32, value: u8) -> bool {
        guest(address)
            .map(|at| super::write(at, 1, value as u64))
            .is_some()
    }
    /// An aligned dword within one aperture page
    pub unsafe fn read32(address: u32) -> Option<u32> {
        guest(address).map(|at| super::read(at, 4) as u32)
    }
    pub unsafe fn write32(address: u32, value: u32) -> bool {
        guest(address)
            .map(|at| super::write(at, 4, value as u64))
            .is_some()
    }
}

/// Configure extended RAM (machine instance, before the cores run): `pages`
/// pages at guest physical `base`, cached in `frames` frames. 0 pages removes it.
#[no_mangle]
pub unsafe fn x64_ext_configure(base_low: u32, base_high: u32, pages: u32, frames: u32) -> bool {
    let base = (base_high as u64) << 32 | base_low as u64;
    if pages != 0 && base < 1 << 32 {
        return false;
    }
    extended::configure(base, pages, frames)
}

/// Write back every dirty frame (the store is then complete: snapshots)
#[no_mangle]
pub unsafe fn x64_ext_flush() { extended::flush() }

/// Forget every frame without writing it back (the store was replaced:
/// snapshot restore, power-on). Every core is stopped.
#[no_mangle]
pub unsafe fn x64_ext_discard() { extended::discard() }

/// The frame of extended page `page` for a host copy (DMA, debugging),
/// resident until x64_ext_unpin: its address in wasm memory
#[no_mangle]
pub unsafe fn x64_ext_pin(page: u32, write: bool) -> u32 { extended::pin(page, write) }
#[no_mangle]
pub unsafe fn x64_ext_unpin(page: u32) { extended::unpin(page) }

/// (crate::extended::stat)
#[no_mangle]
pub unsafe fn x64_ext_stat(field: u32) -> f64 { extended::stat(field) }
                                                                                                                      source/v64/src/rust/x64/helpers.rs                                                                  0000644 0000000 0000000 00000036075 00000000000 014114  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Helpers of the page tier's generated code and their host switches
//! (docs/jit-unification-plan.md P7.5: shared with IR Tier-0 until it was
//! deleted, from its runtime, renamed): the exact SSE floating point and FMA
//! paths on one operand block, PCMPxSTRx, x87 forms (x64_x87, from the
//! region runtime's when M11 deleted the region tiers), and whether the
//! engine has Wasm tail calls and fused relaxed multiply-adds.

/// The operands of x64_sse_fp: the destination (replaced by the result)
/// and the source, written by the page function (x64_fma's: the
/// destination, the first source and the third)
#[repr(C, align(16))]
pub struct SseFpOperands(pub [u128; 3]);
pub static mut SSE_FP_OPERANDS: SseFpOperands = SseFpOperands([0; 3]);
/// Address of SSE_FP_OPERANDS for generated code
pub fn sse_fp_operands() -> u32 { (&raw const SSE_FP_OPERANDS) as u32 }

/// SSE floating point exactly (cpu::simd_fp), for the native templates'
/// refused instructions, on SSE_FP_OPERANDS: `key` is the catalogue key and
/// `imm8` CMPPS' predicate; the result (for conversions to an integer and
/// COMISS, the integer or the EFLAGS bits) replaces the destination and
/// MXCSR's flags are updated. 1 if the instruction faults: only MXCSR's
/// flags are set, as the interpreter, which delivers the fault, sets them
/// again; else 0.
#[no_mangle]
pub unsafe fn x64_sse_fp(key: u32, imm8: u32) -> u32 {
    use crate::cpu::simd_fp;
    SSE_FP_CALLS[(key as usize).wrapping_mul(0x9E37_79B9) >> 24 & 255] += 1;
    let [destination, source, _] = SSE_FP_OPERANDS.0;
    let result = match key {
        // ROUNDPS/PD/SS/SD (SSE4.1)
        0x660F3A08..=0x660F3A0B => simd_fp::round(key, destination, source, imm8 as u8),
        _ => match key as u8 {
            0x52 | 0x53 => Ok(simd_fp::reciprocal(key, destination, source)),
            0x2E | 0x2F => simd_fp::compare_flags(key, destination, source).map(u128::from),
            // (the predicate: imm8[2:0], VEX imm8[4:0])
            0xC2 => simd_fp::compare(key, destination, source, imm8 as u8),
            0x2A | 0x2C | 0x2D | 0x5A | 0x5B | 0xE6 => {
                simd_fp::convert(key, false, destination, source)
            },
            _ => simd_fp::arithmetic(key, destination, source, imm8 as u8),
        },
    };
    match result {
        Ok(result) => {
            SSE_FP_OPERANDS.0[0] = result;
            0
        },
        Err(simd_fp::Unmasked) => 1,
    }
}

/// FMA's VEX.128 and scalar forms exactly (cpu::simd_fp::fused), for the
/// page tier's templates, on SSE_FP_OPERANDS (the destination,
/// the first source and the r/m operand): `op` is the opcode byte, bit 8
/// VEX.W. The result replaces the destination and MXCSR's flags are
/// updated. 1 if the instruction faults: only MXCSR's flags are set, as the
/// interpreter, which delivers the fault, sets them again; else 0.
#[no_mangle]
pub unsafe fn x64_fma(op: u32) -> u32 {
    FMA_CALLS = FMA_CALLS.wrapping_add(1);
    let [destination, first, third] = SSE_FP_OPERANDS.0;
    match crate::cpu::simd_fp::fused(op as u8, op & 0x100 != 0, [destination], [first], [third]) {
        Ok([result]) => {
            SSE_FP_OPERANDS.0[0] = result;
            0
        },
        Err(crate::cpu::simd_fp::Unmasked) => 1,
    }
}

/// PCMPESTRM/PCMPESTRI/PCMPISTRM/PCMPISTRI (`op`: the 66 0F 3A byte) with
/// imm8 on SSE_FP_OPERANDS (destination, source), the explicit forms' lengths `a`
/// and `b` (cpu::simd_int::compare_strings): xSTRM's mask replaces the
/// destination; returns the index | EFLAGS (CF, ZF, SF, OF) << 8. For the page
/// tier's templates.
pub unsafe fn pcmpstr(op: u32, imm8: u32, a: i64, b: i64) -> u32 {
    let [destination, source, _] = SSE_FP_OPERANDS.0;
    let explicit = op & 2 == 0;
    let result = crate::cpu::simd_int::compare_strings(
        imm8 as u8,
        destination.to_le_bytes(),
        source.to_le_bytes(),
        explicit.then_some(a),
        explicit.then_some(b),
    );
    SSE_FP_OPERANDS.0[0] = u128::from_le_bytes(result.xmm0);
    result.index | (result.flags as u32) << 8
}
/// x64_sse_fp's calls by a hash of the catalogue key (a diagnostic of
/// refused native floating point, see x64_sse_fp_calls)
static mut SSE_FP_CALLS: [u32; 256] = [0; 256];
/// The exact-path calls of the form whose catalogue key is `key` (shared
/// with the keys of the same hash)
#[no_mangle]
pub unsafe fn x64_sse_fp_calls(key: u32) -> u32 {
    SSE_FP_CALLS[(key as usize).wrapping_mul(0x9E37_79B9) >> 24 & 255]
}
#[no_mangle]
pub unsafe fn x64_sse_fp_calls_reset() { SSE_FP_CALLS = [0; 256]; }
/// x64_fma's calls: the FMA instructions the templates did not compute
/// natively (see relaxed_fma)
static mut FMA_CALLS: u32 = 0;
#[no_mangle]
pub unsafe fn x64_fma_calls() -> u32 { FMA_CALLS }
#[no_mangle]
pub unsafe fn x64_fma_calls_reset() { FMA_CALLS = 0; }

/// Whether the engine has Wasm tail calls (jit_set_tail_calls, src/cpu.js):
/// the page tier's chaining needs them (x64_chaining)
static mut TAIL_CALLS: bool = false;
pub fn tail_calls() -> bool { unsafe { TAIL_CALLS } }
/// Whether the host engine validates Wasm tail calls and passes its
/// function table to generated modules as ("e", "t")
#[no_mangle]
pub unsafe fn jit_set_tail_calls(supported: u32) -> bool {
    if supported > 1 {
        return false;
    }
    TAIL_CALLS = supported == 1;
    true
}
/// Whether the host engine has Wasm relaxed SIMD and its multiply-adds fuse
/// (cpu.js relaxed_fma_fused, at startup)
static mut RELAXED_FMA_FUSED: bool = false;
/// Whether the page tier computes FMA with them
/// (native_fp::fused): where they fuse, unless switched off. Code compiled
/// before a change keeps its path; both are exact.
static mut RELAXED_FMA: bool = false;
pub fn relaxed_fma() -> bool { unsafe { RELAXED_FMA } }
#[no_mangle]
pub unsafe fn ir_relaxed_fma_fused(fused: u32) {
    RELAXED_FMA_FUSED = fused == 1;
    RELAXED_FMA = RELAXED_FMA_FUSED;
}
/// A/B switch: 0 the exact helper, 1 relaxed multiply-adds (if they fuse)
#[no_mangle]
pub unsafe fn ir_set_relaxed_fma(on: u32) -> bool {
    if on > 1 || on == 1 && !RELAXED_FMA_FUSED {
        return false;
    }
    RELAXED_FMA = on == 1;
    true
}
#[no_mangle]
pub unsafe fn ir_relaxed_fma() -> u32 { RELAXED_FMA as u32 }

// x87 (x64_x87) ---------------------------------------------------------

/// The interpreter's register-only x87 forms (D8-DF, ModRM 0xC0 up)
unsafe fn register_semantics(opcode: u32, group: u32, r: u32) {
    let r = r as i32;
    match (opcode, group) {
        (0xD8, 0) => crate::cpu::instructions::instr_D8_0_reg(r),
        (0xD8, 1) => crate::cpu::instructions::instr_D8_1_reg(r),
        (0xD8, 2) => crate::cpu::instructions::instr_D8_2_reg(r),
        (0xD8, 3) => crate::cpu::instructions::instr_D8_3_reg(r),
        (0xD8, 4) => crate::cpu::instructions::instr_D8_4_reg(r),
        (0xD8, 5) => crate::cpu::instructions::instr_D8_5_reg(r),
        (0xD8, 6) => crate::cpu::instructions::instr_D8_6_reg(r),
        (0xD8, 7) => crate::cpu::instructions::instr_D8_7_reg(r),

        (0xD9, 0) => crate::cpu::instructions::instr16_D9_0_reg(r),
        (0xD9, 1) => crate::cpu::instructions::instr16_D9_1_reg(r),
        (0xD9, 2) => crate::cpu::instructions::instr16_D9_2_reg(r),
        (0xD9, 3) => crate::cpu::instructions::instr16_D9_3_reg(r),
        (0xD9, 4) => crate::cpu::instructions::instr16_D9_4_reg(r),
        (0xD9, 5) => crate::cpu::instructions::instr16_D9_5_reg(r),
        (0xD9, 6) => crate::cpu::instructions::instr16_D9_6_reg(r),
        (0xD9, 7) => crate::cpu::instructions::instr16_D9_7_reg(r),

        (0xDA, 0) => crate::cpu::instructions::instr_DA_0_reg(r),
        (0xDA, 1) => crate::cpu::instructions::instr_DA_1_reg(r),
        (0xDA, 2) => crate::cpu::instructions::instr_DA_2_reg(r),
        (0xDA, 3) => crate::cpu::instructions::instr_DA_3_reg(r),
        (0xDA, 5) => crate::cpu::instructions::instr_DA_5_reg(r),

        (0xDB, 0) => crate::cpu::instructions::instr_DB_0_reg(r),
        (0xDB, 1) => crate::cpu::instructions::instr_DB_1_reg(r),
        (0xDB, 2) => crate::cpu::instructions::instr_DB_2_reg(r),
        (0xDB, 3) => crate::cpu::instructions::instr_DB_3_reg(r),
        (0xDB, 4) => crate::cpu::instructions::instr_DB_4_reg(r),
        (0xDB, 5) => crate::cpu::instructions::instr_DB_5_reg(r),
        (0xDB, 6) => crate::cpu::instructions::instr_DB_6_reg(r),

        (0xDC, 0) => crate::cpu::instructions::instr_DC_0_reg(r),
        (0xDC, 1) => crate::cpu::instructions::instr_DC_1_reg(r),
        (0xDC, 2) => crate::cpu::instructions::instr_DC_2_reg(r),
        (0xDC, 3) => crate::cpu::instructions::instr_DC_3_reg(r),
        (0xDC, 4) => crate::cpu::instructions::instr_DC_4_reg(r),
        (0xDC, 5) => crate::cpu::instructions::instr_DC_5_reg(r),
        (0xDC, 6) => crate::cpu::instructions::instr_DC_6_reg(r),
        (0xDC, 7) => crate::cpu::instructions::instr_DC_7_reg(r),

        (0xDD, 0) => crate::cpu::instructions::instr16_DD_0_reg(r),
        (0xDD, 1) => crate::cpu::instructions::instr16_DD_1_reg(r),
        (0xDD, 2) => crate::cpu::instructions::instr16_DD_2_reg(r),
        (0xDD, 3) => crate::cpu::instructions::instr16_DD_3_reg(r),
        (0xDD, 4) => crate::cpu::instructions::instr16_DD_4_reg(r),
        (0xDD, 5) => crate::cpu::instructions::instr16_DD_5_reg(r),

        (0xDE, 0) => crate::cpu::instructions::instr_DE_0_reg(r),
        (0xDE, 1) => crate::cpu::instructions::instr_DE_1_reg(r),
        (0xDE, 2) => crate::cpu::instructions::instr_DE_2_reg(r),
        (0xDE, 3) => crate::cpu::instructions::instr_DE_3_reg(r),
        (0xDE, 4) => crate::cpu::instructions::instr_DE_4_reg(r),
        (0xDE, 5) => crate::cpu::instructions::instr_DE_5_reg(r),
        (0xDE, 6) => crate::cpu::instructions::instr_DE_6_reg(r),
        (0xDE, 7) => crate::cpu::instructions::instr_DE_7_reg(r),

        (0xDF, 0) => crate::cpu::instructions::instr_DF_0_reg(r),
        (0xDF, 1) => crate::cpu::instructions::instr_DF_1_reg(r),
        (0xDF, 2) => crate::cpu::instructions::instr_DF_2_reg(r),
        (0xDF, 3) => crate::cpu::instructions::instr_DF_3_reg(r),
        (0xDF, 4) => crate::cpu::instructions::instr_DF_4_reg(r),
        (0xDF, 5) => crate::cpu::instructions::instr_DF_5_reg(r),
        (0xDF, 6) => crate::cpu::instructions::instr_DF_6_reg(r),
        _ => unreachable!("validated x87 register dispatch"),
    }
}

/// One x87 form for the x64 page tier's functions (IR Tier-0's until P7.5
/// deleted it, ir_t0_x87; the region tiers' ir_x87_op until M11), which
/// never inline f64 forms (no mirroring) and classify at compile time:
/// `form` is opcode | modrm << 8 | kind << 16 (0 stack, 1 load, 2 store;
/// the transfer width is implied). Operands arrive loaded, and stores leave
/// through the returned (high << 32 | low) word after a write preflight;
/// the bodies are the interpreter's, with the shared f64 shadow cache.
#[no_mangle]
pub unsafe fn x64_x87(form: u32, low: u32, high: u32) -> u64 {
    use crate::x86tpl::x87_forms::Io;
    let (opcode, modrm) = (form as u8, (form >> 8) as u8);
    let io = match form >> 16 {
        0 => Io::Stack,
        1 => Io::Load { bytes: 0 },
        _ => Io::Store { bytes: 0 },
    };
    x87_semantics(opcode, modrm, io, low, high)
}
#[inline(always)]
unsafe fn x87_semantics(
    opcode: u8,
    modrm: u8,
    io: crate::x86tpl::x87_forms::Io,
    low: u32,
    high: u32,
) -> u64 {
    use crate::{cpu::fpu::*, cpu::global_pointers as gp, softfloat::F80, x86tpl::x87_forms::Io};
    let group = modrm >> 3 & 7;
    let wide = (high as u64) << 32 | low as u64;
    match io {
        Io::Stack => register_semantics(opcode.into(), group.into(), (modrm & 7).into()),
        Io::Load { .. } => {
            let value = match opcode {
                0xD8 => f32_to_f80(low as i32),
                0xDA => i32_to_f80(low as i32),
                0xDC => f64_to_f80(wide),
                0xDE => i32_to_f80(low as i16 as i32),
                _ => {
                    match (opcode, group) {
                        (0xD9, 0) => {
                            F80::clear_exception_flags();
                            fpu_push_m32_bits(low as i32);
                        },
                        (0xDD, 0) => {
                            F80::clear_exception_flags();
                            fpu_push_m64_bits(wide);
                        },
                        (0xDB, 0) => fpu_push(i32_to_f80(low as i32)),
                        (0xDF, 0) => fpu_push(i32_to_f80(low as i16 as i32)),
                        (0xDF, 5) => fpu_push(i64_to_f80(wide as i64)),
                        (0xD9, 5) => set_control_word(low as u16),
                        _ => unreachable!(),
                    }
                    return 0;
                },
            };
            match group {
                0 => fpu_fadd(0, value),
                1 => fpu_fmul(0, value),
                2 => fpu_fcom(value),
                3 => fpu_fcomp(value),
                4 => fpu_fsub(0, value),
                5 => fpu_fsubr(0, value),
                6 => fpu_fdiv(0, value),
                7 => fpu_fdivr(0, value),
                _ => unreachable!(),
            }
        },
        Io::Store { .. } => {
            let bits = match (opcode, group) {
                (0xD9, 7) => (*gp::fpu_control_word).into(),
                (0xDD, 7) => fpu_load_status_word().into(),
                (0xD9, 2 | 3) => {
                    let value = fpu_get_st0();
                    F80::clear_exception_flags();
                    let bits = value.to_f32() as u32 as u64;
                    *gp::fpu_status_word |= F80::get_exception_flags() as u16;
                    bits
                },
                (0xDD, 2 | 3) => {
                    if let Some(value) = fpu_cached_st0() {
                        F80::clear_exception_flags();
                        value
                    }
                    else {
                        let value = fpu_get_st0();
                        F80::clear_exception_flags();
                        let bits = value.to_f64();
                        *gp::fpu_status_word |= F80::get_exception_flags() as u16;
                        bits
                    }
                },
                (0xDB, _) => {
                    let value = fpu_get_st0();
                    (if group == 1 {
                        fpu_truncate_to_i32(value)
                    }
                    else {
                        fpu_convert_to_i32(value)
                    }) as u32 as u64
                },
                (0xDD, 1) => fpu_truncate_to_i64(fpu_get_st0()) as u64,
                (0xDF, 7) => fpu_convert_to_i64(fpu_get_st0()) as u64,
                (0xDF, _) => {
                    let value = fpu_get_st0();
                    (if group == 1 {
                        fpu_truncate_to_i16(value)
                    }
                    else {
                        fpu_convert_to_i16(value)
                    }) as u16 as u64
                },
                _ => unreachable!(),
            };
            let pops = match (opcode, group) {
                (0xD9 | 0xDD, 7) => false,
                (0xD9 | 0xDD, 2) | (0xDB | 0xDF, 2) => false,
                _ => true,
            };
            if pops {
                fpu_pop();
            }
            return bits;
        },
    }
    0
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/src/rust/x64/jac.rs                                                                      0000644 0000000 0000000 00000021244 00000000000 013177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Access cache for compiled page functions: x86's caches (one per core) of
//! jitrt::access (docs/jit-unification-plan.md P5.8), whose structure,
//! tags, fills and invalidations are ISA-neutral. Per core, per privilege
//! and per access kind, a direct-mapped table of linear 4 KiB pages whose
//! current translation is plain RAM (and, for writes, holds no compiled
//! code). Page functions look entries up inline; a miss goes to
//! `pages::x64_page_access`.
//!
//! Entries are only ever derived from a successful runtime translation, so a
//! hit is as valid as the x64 TLB entry it came from: every invalidation of a
//! core's x64 TLB (CR writes, INVLPG, EFER, mapping changes, restore) retires
//! that core's entries, and a page that gains compiled code retires the write
//! entries of all cores. Retiring is an epoch step, part of each entry's tag.
use super::physical;
use crate::cpu::memory;
use crate::jitrt::access::{self, AccessCache, Bus, TagLayout};

/// Entries per table: the JIT switch x64_jac_entries (P4.15), 1024, 2048
/// or 4096. The four tables (read supervisor, read user, write supervisor,
/// write user) lie one after another, entries() apart, in room for
/// MAX_ENTRIES each.
pub const MAX_ENTRIES: usize = access::MAX_ENTRIES;
static mut ENTRIES: usize = 2048;
pub fn entries() -> usize { unsafe { ENTRIES } }
pub const ENTRY_BYTES: u32 = access::ENTRY_BYTES;
/// Write tables follow the two read tables (supervisor, user).
pub fn write_offset() -> u32 { 2 * entries() as u32 * ENTRY_BYTES }
/// Tag bits above the largest linear page number of a canonical address.
pub const EPOCH_SHIFT: u32 = 52;
/// x86's tags: the epoch above the linear page number; large pages mark
/// 2 MiB regions
pub const LAYOUT: TagLayout = TagLayout {
    epoch_shift: EPOCH_SHIFT,
    region_shift: 21,
};

static mut JAC: [AccessCache; 8] = [const { AccessCache::NEW }; 8];
fn cache(core: usize) -> &'static mut AccessCache { unsafe { &mut (*(&raw mut JAC))[core] } }

/// x64_jac_entries: every table emptied (the page tier recompiles with the
/// new mask: pages::reset)
pub unsafe fn set_entries(n: usize) -> bool {
    if !matches!(n, 1024 | 2048 | 4096) {
        return false;
    }
    ENTRIES = n;
    for core in 0..8 {
        cache(core).clear();
        flush(core);
    }
    true
}
/// Some write entry maps the VGA frame buffer (see retire_frame_buffer_writes).
static mut FRAME_BUFFER_WRITES: bool = false;

/// Read table base of `core` for the given privilege (host address).
pub unsafe fn base(core: usize, user: bool) -> u32 { cache(core).base(entries(), user as usize) }
/// Tag bits for entries of `core` in its current epoch.
pub unsafe fn epoch_bits(core: usize) -> u64 { cache(core).epoch_bits(LAYOUT) }

pub unsafe fn flush(core: usize) {
    if cache(core).flush(LAYOUT) {
        // (the page tier's code translations carry the epoch too: an old
        // one would match again)
        super::pages::forget_code(core);
    }
}
/// MOV CR3 on `core`: only the entries of global translations stay.
pub unsafe fn flush_nonglobal(core: usize) { cache(core).flush_nonglobal(entries()) }
/// INVLPG `address` on `core`: its x64 TLB entries were invalidated. Entries
/// of 4 KiB translations live only in the page's own slot of each table; an
/// entry from a large page could be in any slot of the large page's range.
pub unsafe fn invlpg(core: usize, address: u64) {
    match cache(core).invalidate_page(LAYOUT, entries(), address) {
        None => {},
        Some(wrapped) => {
            super::pages::COUNTERS[super::pages::COUNT_JAC_LARGE_FLUSH] += 1;
            if wrapped {
                super::pages::forget_code(core);
            }
        },
    }
}
/// The RAM backing page `backing` gained compiled code: page functions must
/// no longer store to it directly (on any core of this instance).
pub unsafe fn retire_writes_to(backing: u32) {
    retire_writes_to_host((memory::mem8 as u32).wrapping_add(backing));
}
/// The same for a page at host address `host` (an extended RAM frame)
pub unsafe fn retire_writes_to_host(host: u32) { retire_writes(|entry| entry.host == host); }
unsafe fn retire_writes(retire: impl Fn(&access::Entry) -> bool) {
    let n = entries();
    for core in 0..crate::cpu::apic::core_count().clamp(1, 8) {
        cache(core).retire_writes(n, &retire);
    }
}
/// With cores in workers: another core published code from the RAM backing
/// page `backing` (crate::parallel::code::poll). Only `core` (this
/// instance's) has entries; its read entries and chaining stay valid.
pub unsafe fn retire_writes_on(core: usize, backing: u32) {
    let host = (memory::mem8 as u32).wrapping_add(backing);
    cache(core).retire_writes(entries(), |entry| entry.host == host);
}
/// Write entries of device memory (a frame buffer) mark their page dirty
/// when they are filled. Once the device has taken its written pages, the
/// next write must mark them again.
pub unsafe fn retire_frame_buffer_writes() {
    if !FRAME_BUFFER_WRITES {
        return;
    }
    FRAME_BUFFER_WRITES = false;
    retire_writes(|entry| crate::cpu::mmio_ram::backs(entry.host));
}
pub unsafe fn flush_all() {
    for core in 0..8 {
        flush(core);
    }
}

/// Record that the linear page of `address` translates to the RAM backing
/// page `backing` (page aligned) for this access kind and privilege; `large`:
/// the translation is part of a 2 MiB or 1 GiB page.
pub unsafe fn fill(
    core: usize,
    user: bool,
    write: bool,
    address: u64,
    backing: u32,
    large: bool,
    global: bool,
) {
    // (P4.15: a live entry of another page in this epoch is a conflict)
    use super::pages::{COUNTERS, COUNT_JAC_CONFLICTS, COUNT_JAC_FILLS};
    COUNTERS[COUNT_JAC_FILLS] += 1;
    let host = (memory::mem8 as u32).wrapping_add(backing);
    if cache(core).fill(LAYOUT, entries(), user, write, address, host, large, global) {
        COUNTERS[COUNT_JAC_CONFLICTS] += 1;
    }
}

/// The backing (relative to mem8) of the device memory page (a frame buffer,
/// crate::cpu::mmio_ram) at physical `address`, which page functions may
/// access directly: it is plain memory in the wasm heap. A write translation
/// marks the page dirty now (retire_frame_buffer_writes undoes it after the
/// device took the page). Not with cores in workers, whose caches the device
/// cannot reach.
pub unsafe fn frame_buffer_backing(address: u64, write: bool) -> Option<u32> {
    let page = address & !4095;
    // (with cores in workers, only the machine instance: it draws the screen)
    if crate::parallel::active() && !crate::parallel::machine_instance() || page >= 1 << 32 {
        return None;
    }
    // decoded by the legacy bus: no relocated RAM or aperture there
    if physical::resolve_backing(page).ok()? != page as u32 {
        return None;
    }
    let host = if write {
        let host = crate::cpu::mmio_ram::write_host(page as u32, 4096)?;
        FRAME_BUFFER_WRITES = true;
        host
    }
    else {
        crate::cpu::mmio_ram::read_host(page as u32, 4096)?
    };
    Some((host as u32).wrapping_sub(memory::mem8 as u32))
}

/// x86's physical bus behind the access cache (jitrt::access::Bus, P5.8)
pub struct X86Bus;
impl Bus for X86Bus {
    /// RAM through the physical bus, never a device or the VGA hole
    #[inline]
    fn ram_backing(&self, physical: u64) -> Option<u32> {
        // ram_page refuses device windows. Not in_mapped_range: the backing of
        // RAM relocated above 4 GiB is a hole of the low bus, yet plain RAM here.
        let page = unsafe { physical::ram_page(physical & !4095) }.ok()?;
        if (0xA0000..0xC0000).contains(&page.backing) {
            return None;
        }
        Some(page.backing)
    }
}
/// The backing page of a guest physical page that page functions may access
/// directly (X86Bus)
pub unsafe fn ram_backing(physical: u64) -> Option<u32> { X86Bus.ram_backing(physical) }

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn tags_retire_by_epoch_and_never_match_zeroed_entries() {
        unsafe {
            let before = epoch_bits(3);
            assert_ne!(before, 0);
            fill(3, true, true, 0xFFFF_8000_1234_5678, 0x5000, false, false);
            let page = 0xFFFF_8000_1234_5678u64 >> 12;
            let e = cache(3).entry(entries(), 3, page);
            assert_eq!(e.tag, page | before);
            // the largest canonical page number stays below the epoch bits
            assert_eq!((u64::MAX >> 12) >> EPOCH_SHIFT, 0);
            flush(3);
            assert_ne!(epoch_bits(3), before);
            assert_ne!(e.tag, page | epoch_bits(3));
            for _ in 0..LAYOUT.epoch_limit() {
                flush(3);
            }
            assert_ne!(cache(3).epoch(), 0);
            assert_eq!(LAYOUT.page(cache(3).entry(entries(), 3, page).tag), 0);
        }
    }
}
                                                                                                                                                                                                                                                                                                                                                            source/v64/src/rust/x64/memory.rs                                                                   0000644 0000000 0000000 00000047241 00000000000 013757  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Wide linear accesses. Validate every touched page before device reads or
//! writes; one element of an atomic/string operation is a complete transaction.
use super::paging::{Access, Controls, Tlb, WalkMode};
use super::state::LinearAddress;
use super::{paging, physical, state};
use crate::cpu::{apic, global_pointers as gp};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Fault {
    pub vector: u8,
    pub error: Option<u32>,
    pub address: Option<u64>,
}
impl Fault {
    pub fn gp() -> Self {
        Self {
            vector: 13,
            error: Some(0),
            address: None,
        }
    }
    pub fn ud() -> Self {
        Self {
            vector: 6,
            error: None,
            address: None,
        }
    }
    pub fn de() -> Self {
        Self {
            vector: 0,
            error: None,
            address: None,
        }
    }
}
static mut X64_TLBS: [Tlb; 8] = [const { Tlb::new() }; 8];

/// A locked instruction in progress while cores run in workers
/// (crate::parallel): its first memory read is the read-modify-write operand,
/// read from RAM, and the write to the same bytes commits with a
/// compare-exchange. If another core changed the operand in between, the
/// instruction runs again from its saved registers.
#[derive(Clone, Copy)]
struct LockedOperand {
    address: u64,
    size: usize,
    backing: u32,
    old: u128,
}
/// (`extended`: the operand is in extended RAM, whose lock the instruction
/// holds until it ends, crate::x64::extended)
struct Locked {
    operand: Option<LockedOperand>,
    conflict: bool,
    extended: bool,
}
static mut LOCKED: Option<Locked> = None;

pub unsafe fn run_locked(mut instruction: impl FnMut() -> Result<(), Fault>) -> Result<(), Fault> {
    #[cfg(feature = "parallel")]
    {
        let saved = crate::cpu::isa_hooks::Registers::save();
        loop {
            LOCKED = Some(Locked {
                operand: None,
                conflict: false,
                extended: false,
            });
            let result = instruction();
            let locked = (*(&raw mut LOCKED)).take();
            if locked.as_ref().is_some_and(|locked| locked.extended) {
                super::extended::unlock();
            }
            let conflict = locked.is_some_and(|locked| locked.conflict);
            if !conflict || result.is_err() {
                return result;
            }
            saved.restore();
        }
    }
    #[cfg(not(feature = "parallel"))]
    instruction()
}

/// The operand read of a locked instruction, if it is in RAM
unsafe fn locked_read(address: u64, size: usize, stack: bool) -> Result<Option<u128>, Fault> {
    let Some(locked) = &mut *(&raw mut LOCKED)
    else {
        return Ok(None);
    };
    if locked.operand.is_some() {
        return Ok(None);
    }
    // (a locked operand is checked for writing before it is read)
    let span = preflight(address, size, Access::Write, stack, false)?;
    let Some(backing) =
        (if span.contiguous() { physical::ram_backing(span.first, size) } else { None })
    else {
        // in extended RAM, the instruction is atomic under that module's lock
        if !locked.extended && super::extended::contains(span.first) {
            super::extended::begin_locked_operand();
            locked.extended = true;
        }
        return Ok(None);
    };
    let old = match size {
        1 => crate::cpu::memory::read8_no_mmap_check(backing) as u8 as u128,
        2 => crate::cpu::memory::read16_no_mmap_check(backing) as u16 as u128,
        4 => crate::cpu::memory::read32_no_mmap_check(backing) as u32 as u128,
        8 => crate::cpu::memory::read64_no_mmap_check(backing) as u128,
        _ => {
            crate::cpu::memory::read64_no_mmap_check(backing) as u128
                | (crate::cpu::memory::read64_no_mmap_check(backing + 8) as u128) << 64
        },
    };
    locked.operand = Some(LockedOperand {
        address,
        size,
        backing,
        old,
    });
    Ok(Some(old))
}

/// The operand write of a locked instruction: true if it was the operand
unsafe fn locked_write(address: u64, size: usize, value: u128) -> bool {
    let Some(locked) = &mut *(&raw mut LOCKED)
    else {
        return false;
    };
    let Some(operand) = locked.operand
    else {
        return false;
    };
    if operand.address != address || operand.size != size {
        return false;
    }
    crate::jit::jit_dirty_cache_small(operand.backing, operand.backing + size as u32);
    let at = crate::cpu::memory::mem8.add(operand.backing as usize);
    let committed = if size == 16 {
        crate::parallel::compare_exchange128(at, operand.old, value)
    }
    else {
        crate::parallel::compare_exchange(at, size as u32, operand.old as u64, value as u64)
    };
    locked.conflict |= !committed;
    true
}
// Compiled-code access cache entries derive from these TLBs: retire them too.
pub unsafe fn invalidate_all_tlbs() {
    for core in 0..8 {
        X64_TLBS[core].clear();
    }
    super::jac::flush_all();
}
pub unsafe fn invalidate_core(core: usize) {
    X64_TLBS[core].clear();
    super::jac::flush(core);
}
/// MOV CR3 with CR4.PGE: translations of global pages survive (in the TLB,
/// the access cache and the chaining table).
pub unsafe fn invalidate_core_nonglobal(core: usize) {
    X64_TLBS[core].clear_nonglobal();
    super::jac::flush_nonglobal(core);
    super::pages::forget_nonglobal_code(core);
}
pub unsafe fn invlpg(address: u64) {
    super::pages::COUNTERS[super::pages::COUNT_INVLPG] += 1;
    let core = apic::current_core();
    X64_TLBS[core].invalidate(LinearAddress(address));
    super::jac::invlpg(core, address);
    super::pages::forget_code_page(core, address);
}

/// Compilation observes the same stale translations as execution, but never
/// fills a cache, updates A/D, reads an MMIO page table, or delivers a fault.
pub unsafe fn snapshot_translation(address: u64, access: Access) -> Option<paging::Translation> {
    let controls = Controls {
        cr3: state::read_cr(3),
        user: *gp::cpl == 3,
        write_protect: state::read_cr(0) & 0x10000 != 0,
        nx_enable: state::efer() & state::EFER_NXE != 0,
    };
    X64_TLBS[apic::current_core()]
        .lookup(LinearAddress(address), access, controls)
        .or_else(|| {
            paging::walk(
                &mut physical::PageTables,
                LinearAddress(address),
                access,
                controls,
                WalkMode::Snapshot,
            )
            .ok()
        })
}

// Snapshot transfer buffers are host-owned allocations (v86_malloc/free), not
// guest physical addresses. Each valid record contains 18 portable DWORDs;
// zero records restores an empty cache. All callers run at a CPU safe point.
#[no_mangle]
pub unsafe extern "C" fn x64_tlb_snapshot_dwords(core: u32) -> i32 {
    if core >= 8 {
        return -1;
    }
    X64_TLBS[core as usize].snapshot().len() as i32
}

#[no_mangle]
pub unsafe extern "C" fn x64_tlb_snapshot_write(core: u32, data: u32, capacity: u32) -> i32 {
    if core >= 8 {
        return -1;
    }
    let records = X64_TLBS[core as usize].snapshot();
    if (capacity as usize) < records.len() || !records.is_empty() && (data == 0 || data & 3 != 0) {
        return -1;
    }
    if !records.is_empty() {
        std::ptr::copy_nonoverlapping(records.as_ptr(), data as *mut u32, records.len());
    }
    records.len() as i32
}

unsafe fn snapshot_records<'a>(data: u32, count: u32) -> Option<&'a [u32]> {
    if count as usize > paging::TLB_CAPACITY * paging::TLB_SNAPSHOT_DWORDS
        || count as usize % paging::TLB_SNAPSHOT_DWORDS != 0
    {
        return None;
    }
    if count == 0 {
        return Some(&[]);
    }
    if data == 0 || data & 3 != 0 {
        return None;
    }
    Some(std::slice::from_raw_parts(
        data as *const u32,
        count as usize,
    ))
}

#[no_mangle]
pub unsafe extern "C" fn x64_tlb_snapshot_validate(data: u32, count: u32) -> bool {
    snapshot_records(data, count).is_some_and(|records| Tlb::new().restore_snapshot(records))
}

#[no_mangle]
pub unsafe extern "C" fn x64_tlb_snapshot_restore(core: u32, data: u32, count: u32) -> bool {
    if core >= 8 {
        return false;
    }
    let restored = snapshot_records(data, count)
        .is_some_and(|records| X64_TLBS[core as usize].restore_snapshot(records));
    if restored {
        super::jac::flush(core as usize);
    }
    restored
}

/// A data translation for the access cache (x64::jac): the physical address,
/// and whether it comes from a large page (conservatively true if the TLB
/// did not keep the entry).
/// translate_page for instruction fetch
pub unsafe fn translate_page_execute(address: u64) -> Result<(u64, bool, bool), Fault> {
    translate_page(address, Access::Execute)
}
/// Also whether it is global (else conservatively false): kept by MOV CR3.
pub unsafe fn translate_page(address: u64, access: Access) -> Result<(u64, bool, bool), Fault> {
    let physical = translate(address, access, false, false)?;
    let c = Controls {
        cr3: state::read_cr(3),
        user: *gp::cpl == 3,
        write_protect: state::read_cr(0) & 0x10000 != 0,
        nx_enable: state::efer() & state::EFER_NXE != 0,
    };
    let t = X64_TLBS[apic::current_core()].lookup(LinearAddress(address), access, c);
    Ok((
        physical,
        t.map_or(true, |t| t.page_shift > 12),
        t.is_some_and(|t| t.global),
    ))
}
pub unsafe fn translate(
    address: u64,
    access: Access,
    stack: bool,
    supervisor: bool,
) -> Result<u64, Fault> {
    translate_user(address, access, stack, !supervisor && *gp::cpl == 3)
}
/// In compatibility mode, x64 translations fill the 32-bit TLB too
/// (cpu::fill_ia32e_tlb) when compiled 32-bit code reads it: the page
/// tier's (x64_page_compat32 with x64_compat_tlb, pagegen::Emitter::host_tlb;
/// the region tiers' until M11)
unsafe fn compat_tlb() -> bool { super::pages::compat32() && super::pagegen::compat_tlb() }
pub unsafe fn translate_user(
    address: u64,
    access: Access,
    stack: bool,
    user: bool,
) -> Result<u64, Fault> {
    if !state::canonical(address, 48) {
        return Err(Fault {
            vector: if stack { 12 } else { 13 },
            error: Some(0),
            address: None,
        });
    }
    let c = Controls {
        cr3: state::read_cr(3),
        user,
        write_protect: state::read_cr(0) & 0x10000 != 0,
        nx_enable: state::efer() & state::EFER_NXE != 0,
    };
    let cache = &mut X64_TLBS[apic::current_core()];
    if let Some(physical) = cache.lookup_physical(LinearAddress(address), access, c) {
        if *gp::x64_cs_long == 0 && compat_tlb() {
            crate::cpu::cpu::fill_ia32e_tlb(address as u32, physical, access, user);
        }
        return Ok(physical);
    }
    super::pages::COUNTERS[super::pages::COUNT_WALKS] += 1;
    let result = paging::walk(
        &mut physical::PageTables,
        LinearAddress(address),
        access,
        c,
        WalkMode::Runtime,
    )
    .map_err(|fault| match fault {
        paging::Fault::Page { address, error, .. } => Fault {
            vector: 14,
            error: Some(error),
            address: Some(address.0),
        },
        paging::Fault::NonCanonical(_) => Fault {
            vector: if stack { 12 } else { 13 },
            error: Some(0),
            address: None,
        },
        paging::Fault::Unavailable(_) => Fault::gp(),
    })?;
    cache.insert(LinearAddress(address), access, c, result);
    // compatibility mode: 32-bit linear addresses, served to compiled code too
    if *gp::x64_cs_long == 0 && compat_tlb() {
        crate::cpu::cpu::fill_ia32e_tlb(address as u32, result.physical.0, access, user);
    }
    Ok(result.physical.0)
}

/// Physical bytes of one linear access: `head` bytes from `first`, the rest
/// from `second` when the access crosses a page.
#[derive(Clone, Copy)]
struct Span {
    first: u64,
    second: u64,
    head: usize,
    size: usize,
}
impl Span {
    fn byte(&self, i: usize) -> u64 {
        if i < self.head {
            self.first + i as u64
        }
        else {
            self.second + (i - self.head) as u64
        }
    }
    fn contiguous(&self) -> bool {
        self.head == self.size || self.second == self.first + self.head as u64
    }
}
unsafe fn preflight(
    address: u64,
    size: usize,
    access: Access,
    stack: bool,
    supervisor: bool,
) -> Result<Span, Fault> {
    assert!(matches!(size, 1 | 2 | 4 | 8 | 16));
    let first = translate(address, access, stack, supervisor)?;
    // Page order: the first page's bus check precedes the second page's walk.
    let head = size.min(4096 - (address & 4095) as usize);
    physical::probe(first, head).map_err(|_| Fault::gp())?;
    let mut second = 0;
    if head < size {
        second = translate(address.wrapping_add(head as u64), access, stack, supervisor)?;
        physical::probe(second, size - head).map_err(|_| Fault::gp())?;
    }
    Ok(Span {
        first,
        second,
        head,
        size,
    })
}
fn read_physical(span: Span) -> Result<u128, Fault> {
    unsafe {
        if span.contiguous() {
            let at = span.first;
            return match span.size {
                1 => physical::read8(at).map(|v| v as u128),
                2 => physical::read16(at).map(|v| v as u128),
                4 => physical::read32(at).map(|v| v as u128),
                8 => physical::read64(at).map(|v| v as u128),
                16 => {
                    let lo = physical::read64(at).map_err(|_| Fault::gp())?;
                    let hi = physical::read64(at + 8).map_err(|_| Fault::gp())?;
                    return Ok(lo as u128 | (hi as u128) << 64);
                },
                _ => unreachable!(),
            }
            .map_err(|_| Fault::gp());
        }
        let mut value = 0;
        for i in 0..span.size {
            value |= (physical::read8(span.byte(i)).map_err(|_| Fault::gp())? as u128) << (i * 8);
        }
        Ok(value)
    }
}
fn write_physical(span: Span, value: u128) -> Result<(), Fault> {
    unsafe {
        if span.contiguous() {
            let at = span.first;
            return match span.size {
                1 => physical::write8(at, value as u8),
                2 => physical::write16(at, value as u16),
                4 => physical::write32(at, value as u32),
                8 => physical::write64(at, value as u64),
                16 => {
                    physical::write64(at, value as u64).map_err(|_| Fault::gp())?;
                    return physical::write64(at + 8, (value >> 64) as u64)
                        .map_err(|_| Fault::gp());
                },
                _ => unreachable!(),
            }
            .map_err(|_| Fault::gp());
        }
        for i in 0..span.size {
            physical::write8(span.byte(i), (value >> (i * 8)) as u8).map_err(|_| Fault::gp())?;
        }
        Ok(())
    }
}
pub unsafe fn read(address: u64, width: u8, stack: bool) -> Result<u64, Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64));
    let size = (width / 8) as usize;
    if let Some(value) = locked_read(address, size, stack)? {
        return Ok(value as u64);
    }
    let value = read_physical(preflight(address, size, Access::Read, stack, false)?)? as u64;
    super::debug::data(address, size, false);
    Ok(value)
}
pub unsafe fn write(address: u64, width: u8, value: u64, stack: bool) -> Result<(), Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64));
    let size = (width / 8) as usize;
    if locked_write(address, size, value as u128) {
        return Ok(());
    }
    write_physical(
        preflight(address, size, Access::Write, stack, false)?,
        value as u128,
    )?;
    super::debug::data(address, size, true);
    Ok(())
}
pub unsafe fn read128(address: u64, stack: bool) -> Result<u128, Fault> {
    if let Some(value) = locked_read(address, 16, stack)? {
        return Ok(value);
    }
    let value = read_physical(preflight(address, 16, Access::Read, stack, false)?)?;
    super::debug::data(address, 16, false);
    Ok(value)
}
pub unsafe fn write128(address: u64, value: u128, stack: bool) -> Result<(), Fault> {
    if locked_write(address, 16, value) {
        return Ok(());
    }
    write_physical(preflight(address, 16, Access::Write, stack, false)?, value)?;
    super::debug::data(address, 16, true);
    Ok(())
}
pub unsafe fn fetch(address: u64) -> Result<u8, Fault> {
    let address = translate(address, Access::Execute, false, false)?;
    fetch_physical(address)
}
/// An instruction byte outside plain RAM (SMRAM serves code fetches in SMM
/// also with D_CLS: crate::cpu::memory::fetch8)
unsafe fn fetch_physical(address: u64) -> Result<u8, Fault> {
    if address >> 32 == 0 {
        if let Some(ram) = crate::cpu::smm::smram_ram(address as u32, 1, true) {
            return Ok(*crate::cpu::memory::mem8.add(ram as usize));
        }
    }
    physical::read8(address).map_err(|_| Fault::gp())
}
/// Instruction fetch within one decode: `page` remembers the last linear to
/// physical code page, so each page is translated once per instruction.
pub unsafe fn fetch_cached(address: u64, page: &mut Option<(u64, u64)>) -> Result<u8, Fault> {
    let physical = match *page {
        Some((linear, physical)) if linear == address >> 12 => physical | (address & 4095),
        _ => {
            let physical = translate(address, Access::Execute, false, false)?;
            *page = Some((address >> 12, physical & !4095));
            physical
        },
    };
    if physical::plain_ram(physical, 1) {
        return Ok(*crate::cpu::memory::mem8.add(physical as usize));
    }
    fetch_physical(physical)
}
pub unsafe fn read_system(address: u64, width: u8) -> Result<u64, Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64));
    let size = (width / 8) as usize;
    Ok(read_physical(preflight(address, size, Access::Read, false, true)?)? as u64)
}
pub unsafe fn write_system(address: u64, width: u8, value: u64) -> Result<(), Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64));
    let size = (width / 8) as usize;
    write_physical(
        preflight(address, size, Access::Write, true, true)?,
        value as u128,
    )
}

pub unsafe fn probe_write(address: u64, width: u8, stack: bool) -> Result<(), Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64 | 128));
    preflight(address, (width / 8) as usize, Access::Write, stack, false).map(|_| ())
}

pub unsafe fn probe_read(address: u64, width: u8, stack: bool) -> Result<(), Fault> {
    assert!(matches!(width, 8 | 16 | 32 | 64 | 128));
    preflight(address, (width / 8) as usize, Access::Read, stack, false).map(|_| ())
}

pub unsafe fn probe_system_write(address: u64, width: u8) -> Result<(), Fault> {
    preflight(address, (width / 8) as usize, Access::Write, true, true).map(|_| ())
}

/// Bridge compatibility-mode instructions to the wide walker while preserving
/// the legacy memory helper ABI. A remapped page resolves to its backing page;
/// mapping changes flush all translations before this identity can change.
pub unsafe fn legacy_translate(
    address: u32,
    access: Access,
    user: bool,
    side_effects: bool,
) -> Result<u32, ()> {
    let physical = if side_effects {
        match translate_user(address as u64, access, false, user) {
            Ok(address) => address,
            Err(fault) => {
                super::system::raise(fault);
                return Err(());
            },
        }
    }
    else {
        let c = Controls {
            cr3: state::read_cr(3),
            user,
            write_protect: state::read_cr(0) & 0x10000 != 0,
            nx_enable: state::efer() & state::EFER_NXE != 0,
        };
        paging::walk(
            &mut physical::PageTables,
            LinearAddress(address as u64),
            access,
            c,
            WalkMode::Snapshot,
        )
        .map_err(|_| ())?
        .physical
        .0
    };
    physical::resolve_backing(physical).map_err(|_| ())
}
                                                                                                                                                                                                                                                                                                                                                               source/v64/src/rust/x64/mod.rs                                                                      0000644 0000000 0000000 00000000670 00000000000 013221  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Wide architectural state and shared decode foundations. The public CPU
//! profile only advertises long mode after execution and OS gates pass.
pub mod debug;
pub mod decode;
pub mod execute;
pub mod extended;
pub mod helpers;
pub mod jac;
pub mod memory;
pub mod pagegen;
pub mod pages;
pub mod paging;
pub mod physical;
pub mod profile;
#[cfg(feature = "ir-test-hooks")]
pub mod replay;
pub mod state;
pub mod system;
pub mod vector;
                                                                        source/v64/src/rust/x64/pagegen.rs                                                                  0000644 0000000 0000000 00001552606 00000000000 014064  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! x64 page tier: one Wasm function per 4 KiB page of long-mode code.
//!
//! The function serves every compiled block start of its page. A dispatch
//! loop branches (br_table over the page offset) to a block; blocks continue
//! into each other without returning to the CPU loop. The 16 GPRs, EFLAGS
//! and RIP live in locals and are written back at every exit and around
//! interpreter steps, so memory is authoritative whenever Rust code runs.
//!
//! Templates cover the frequent integer forms. Everything else, and any
//! template precondition that fails at run time, has the wide interpreter's
//! exact behavior:
//! - step: the instruction is interpreted in place by `x64_page_step`, then
//!   the function dispatches on the new RIP (or returns if the step changed
//!   the execution context).
//! - retry: a memory access missing the access cache (x64::jac) that
//!   `x64_page_access` cannot serve (fault, device, page with compiled code,
//!   page crossing) leaves the function with RIP at the instruction and none
//!   of its effects; the runtime interprets it.
//! EFLAGS arithmetic bits are only computed where a later reader can observe
//! them (page-local liveness; exits and steps read all of them). Condition
//! consumers after CMP/SUB/TEST-like producers in the same block compare the
//! producer's operands directly.
//!
//! The tier also compiles 32-bit compatibility- and legacy-mode code (P7.2,
//! P7.3), which IR Tier-0 compiled until P7.5 deleted it: comments that
//! compare with "Tier-0" describe that code as it was.
use super::decode::{self, AddressBase, AddressExpr, ByteRegister, Decoded};
use super::jac;
use super::state::{gpr_high_offset, gpr_low_offset, ExecutionMode, GuestIp};
use crate::cpu::cpu::{
    TLB_GLOBAL, TLB_HAS_CODE, TLB_IA32E_DATA, TLB_NO_USER, TLB_READONLY, TLB_VALID,
};
use crate::cpu::global_pointers as gp;
use crate::pagegen::frame::{
    self as page_frame, in_page, AccessAbi, ChainEpoch, DispatchKind, Frame, Level, LookupLocals,
    PageEmitter, SPAN_TABLE,
};
use crate::pagegen::loops::Unit;
use crate::wasmgen::leaves::{self, Shift};
use crate::wasmgen::wasm_builder::{
    Label, Signature, WasmBuilder, WasmLocal, WasmLocalI64, WasmLocalV128, WasmType,
};
use crate::wasmgen::wasm_opcodes as op;
use crate::x86tpl::vec::{self, Packed};
use crate::x86tpl::x87::{x87_native, X87Cache, X87Words};
use crate::x86tpl::x87run::{x87_run, X87Run};
use std::collections::{BTreeMap, BTreeSet, HashMap};

/// x64_pagegen_size_stats: Wasm bytes emitted per template kind (count,
/// bytes), for code size work
static mut SIZE_STATS: Option<HashMap<String, (u64, u64)>> = None;
fn size_note(name: String, bytes: usize) {
    unsafe {
        if let Some(stats) = (*(&raw mut SIZE_STATS)).as_mut() {
            let entry = stats.entry(name).or_insert((0, 0));
            entry.0 += 1;
            entry.1 += bytes as u64;
        }
    }
}
#[no_mangle]
pub fn x64_pagegen_size_stats(enabled: bool) { unsafe { SIZE_STATS = enabled.then(HashMap::new) }; }
#[no_mangle]
pub fn x64_pagegen_size_dump() {
    unsafe {
        if let Some(stats) = (*(&raw const SIZE_STATS)).as_ref() {
            let mut rows: Vec<_> = stats.iter().collect();
            rows.sort_by_key(|(_, &(_, bytes))| std::cmp::Reverse(bytes));
            let total: u64 = rows.iter().map(|(_, &(_, b))| b).sum();
            for (name, &(count, bytes)) in rows.iter().take(40) {
                console_log!(
                    "X64_PAGEGEN_SIZE {} count {} bytes {} ({:.1}%) avg {:.1}",
                    name,
                    count,
                    bytes,
                    100.0 * bytes as f64 / total as f64,
                    bytes as f64 / count as f64
                );
            }
        }
    }
}

use crate::jitrt::step::StepAbi;
/// Why a page function returned (CompileEnv::step's exit code word,
/// gp::x64_page_exit), and x64_page_step's outcomes (jitrt::step, P5.6).
/// STEP_CHAIN: the step changed CS but nothing else the function depends on
/// (far calls and returns in code compiled for segment bases, P7.7; M11: or
/// also the mode among those, pages::x64_page_step switching the chaining
/// table): it leaves through the chaining table, to the function of the new
/// RIP, whose prologue checks CS's base in 16-bit code
pub use crate::jitrt::step::{EXIT_NORMAL, EXIT_RETRY, EXIT_UNKNOWN, STEP_CHAIN};

const PAGE: usize = 4096;
/// The consecutive linear pages a legacy-mode function may cover
/// (docs/jit-unification-plan.md P7.3b; CompileEnv::span)
pub const MAX_SPAN: usize = 16;
/// Offsets of a page's volatile instructions a compile takes at most
/// (CompileEnv::volatile)
pub const MAX_VOLATILE: usize = 16;
/// Decoded instructions per page function, including overlapping decodes.
const MAX_INSTRUCTIONS: usize = 3072;
/// An entry of compile's that is a guess (pages.rs: a likely function start
/// after INT3 padding): a block start unless decoded code runs straight into
/// it, where the 0xCC before it was an instruction's last byte
pub const GUESSED: u16 = 0x8000;

const CF: u32 = 1;
const PF: u32 = 4;
const AF: u32 = 0x10;
const ZF: u32 = 0x40;
const SF: u32 = 0x80;
const OF: u32 = 0x800;
const ARITH: u32 = CF | PF | AF | ZF | SF | OF;

fn mask(w: u8) -> u64 {
    if w == 64 {
        u64::MAX
    }
    else {
        (1u64 << w) - 1
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Reg {
    index: u8,
    /// AH, CH, DH or BH (no REX)
    high: bool,
}
#[derive(Clone, Copy, Debug)]
enum Opnd {
    Reg(Reg),
    Mem(AddressExpr),
    Imm(u64),
}
impl Opnd {
    fn reg(self) -> Option<Reg> {
        if let Opnd::Reg(r) = self {
            Some(r)
        }
        else {
            None
        }
    }
}
/// An XMM register (0..15) or a memory operand of an SSE instruction.
#[derive(Clone, Copy, Debug)]
enum Xmm {
    Reg(u8),
    Mem(AddressExpr),
}
/// Op::Mmx's forms (Xmm::Reg: an MM register here)
#[derive(Clone, Copy, Debug)]
enum MmxForm {
    /// MOVQ mm, mm/m64
    Load {
        reg: u8,
        src: Xmm,
    },
    /// MOVQ mm/m64, mm
    Store {
        reg: u8,
        dst: Xmm,
    },
    /// MOVD mm, r/m32
    MovdIn {
        reg: u8,
        src: Opnd,
    },
    /// MOVD r/m32, mm
    MovdOut {
        reg: u8,
        dst: Opnd,
    },
    /// the packed forms and PSHUFW; `bytes` of a memory source (PUNPCKL*:
    /// 4)
    Packed {
        op: Packed,
        reg: u8,
        src: Xmm,
        bytes: u8,
    },
    /// PSRLW/PSRAW/PSLLW and the D, Q forms by an immediate
    Shift {
        reg: u8,
        bits: u8,
        kind: u8,
        count: u8,
    },
    Emms,
}
/// Op::Bmi's operations
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BmiOp {
    Andn,
    Blsr,
    Blsmsk,
    Blsi,
    Bzhi,
    Shlx,
    Shrx,
    Sarx,
    Tzcnt,
    Lzcnt,
    /// RORX by imm8 (no flags)
    Rorx(u8),
}
#[derive(Clone, Copy, Debug)]
enum Op {
    /// ADD OR ADC SBB AND SUB XOR CMP (x86 /digit order)
    Alu {
        code: u8,
        width: u8,
        dst: Opnd,
        src: Opnd,
    },
    Test {
        width: u8,
        a: Opnd,
        b: Opnd,
    },
    Mov {
        width: u8,
        dst: Opnd,
        src: Opnd,
    },
    Extend {
        width: u8,
        from: u8,
        signed: bool,
        dst: Reg,
        src: Opnd,
    },
    Lea {
        width: u8,
        dst: Reg,
        address: AddressExpr,
    },
    IncDec {
        dec: bool,
        width: u8,
        dst: Opnd,
    },
    Neg {
        width: u8,
        dst: Opnd,
    },
    Not {
        width: u8,
        dst: Opnd,
    },
    /// ROL ROR - - SHL SHR SAL SAR; `count` None is CL.
    Shift {
        code: u8,
        width: u8,
        dst: Opnd,
        count: Option<u8>,
    },
    /// Shifts and rotates without a template (8/16-bit by CL, RCL/RCR up to
    /// 32 bits): the interpreter's semantics through x64_page_shift
    ShiftCall {
        code: u8,
        width: u8,
        dst: Opnd,
        count: Option<u8>,
    },
    Imul {
        width: u8,
        dst: Reg,
        a: Opnd,
        b: Opnd,
    },
    MulWide {
        signed: bool,
        width: u8,
        src: Opnd,
    },
    Push {
        src: Opnd,
    },
    Pop {
        dst: Reg,
    },
    // Legacy mode's further templates (legacy_template, P7.3):
    /// LOOPNE, LOOPE, LOOP or JECXZ (`kind` 0-3); CX with a 16-bit address
    /// size
    LoopJump {
        kind: u8,
        cx: bool,
        target: u64,
    },
    /// MOV ES/DS/FS/GS, r/m16 (Emitter::load_segment)
    LoadSreg {
        segment: u8,
        src: Opnd,
    },
    /// POP ES/DS/FS/GS with a `width` operand
    PopSreg {
        segment: u8,
        width: u8,
    },
    /// PUSH Sreg with a `width` operand (a 32-bit one writes the low 16 bits
    /// of its slot, as cpu::misc_instr::push32_sreg)
    PushSreg {
        segment: u8,
        width: u8,
    },
    /// PUSH and POP with a 16-bit operand size
    Push16 {
        src: Opnd,
    },
    Pop16 {
        dst: Opnd,
    },
    /// POP m32: the address computed with ESP after the pop
    PopMem {
        address: AddressExpr,
    },
    /// 16-bit code (P7.7): PUSH and POP with a 32-bit operand size
    Push32 {
        src: Opnd,
    },
    Pop32 {
        dst: Opnd,
    },
    /// 16-bit code: LES and LDS (`segment` ES or DS), the offset of `width`
    /// bits and the selector after it at `address`
    LoadFar {
        segment: u8,
        width: u8,
        dst: Reg,
        address: AddressExpr,
    },
    /// 16-bit code: ENTER size, 0
    Enter {
        size: u16,
    },
    /// 16-bit code: LODS with 16-bit addresses (SI)
    Lods16 {
        width: u8,
        segment: u8,
    },
    /// Far CALL ptr16:16 or ptr16:32 and RETF (imm16) in code compiled for
    /// segment bases (M11): pages::x64_page_far, then through the chaining
    /// table
    FarCall {
        selector: u16,
        offset: u32,
        width: u8,
    },
    FarRet {
        pop: u16,
        width: u8,
    },
    /// PUSHAD and POPAD, whose 32 bytes are in one page (else a retry)
    Pusha,
    Popa,
    /// LODS without REP: AL, AX or EAX from `segment`:ESI
    Lods {
        width: u8,
        segment: u8,
    },
    Pushf,
    Leave,
    Call {
        target: u64,
    },
    CallIndirect {
        src: Opnd,
    },
    Ret {
        pop: u16,
    },
    Jmp {
        target: u64,
    },
    JmpIndirect {
        src: Opnd,
    },
    Jcc {
        cc: u8,
        target: u64,
    },
    Cmov {
        cc: u8,
        width: u8,
        dst: Reg,
        src: Opnd,
    },
    Setcc {
        cc: u8,
        dst: Opnd,
    },
    Xchg {
        width: u8,
        a: Opnd,
        b: Reg,
    },
    Xadd {
        width: u8,
        dst: Opnd,
        src: Reg,
    },
    Cmpxchg {
        width: u8,
        dst: Opnd,
        src: Reg,
    },
    /// CBW/CWDE/CDQE
    SignAcc {
        width: u8,
    },
    /// CWD/CDQ/CQO
    SignDx {
        width: u8,
    },
    /// BT BTS BTR BTC
    Bt {
        action: u8,
        width: u8,
        dst: Opnd,
        index: Opnd,
    },
    BitScan {
        reverse: bool,
        width: u8,
        dst: Reg,
        src: Opnd,
    },
    Popcnt {
        width: u8,
        dst: Reg,
        src: Opnd,
    },
    Bswap {
        width: u8,
        reg: u8,
    },
    /// BMI1 and BMI2's VEX forms, TZCNT and LZCNT on 32- and 64-bit
    /// operands (cpu::bmi): `dst` = `op`(`src`, `other`), where `other` is
    /// VEX.vvvv (ANDN's first source, BZHI's index, the shifts' count); the
    /// destination of BLSR, BLSMSK and BLSI is VEX.vvvv
    Bmi {
        op: BmiOp,
        width: u8,
        dst: Reg,
        src: Opnd,
        other: Reg,
    },
    /// FMA's VEX.128 and scalar forms (P11) through
    /// x64::helpers::x64_fma (`op` the opcode byte, `double` VEX.W1)
    Vfused {
        op: u8,
        double: bool,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// MOVBE r, m (`load`) or m, r: one access, its bytes reversed
    Movbe {
        load: bool,
        width: u8,
        reg: Reg,
        mem: AddressExpr,
    },
    /// CMC CLC STC CLD STD by opcode
    Flag {
        opcode: u8,
    },
    Lahf,
    Sahf,
    Nop,
    Cli,
    /// STI ends the activation: the next instruction runs in the interrupt
    /// shadow in the interpreter.
    Sti,
    /// STI with the instruction in its shadow compiled after it in its block
    /// (x64_sti_shadow), which ends in End::Shadow.
    StiShadowed,
    Swapgs,
    Rdtsc,
    /// DIV/IDIV r/m32/64 whose quotient fits (else retried: #DE or a wide
    /// dividend).
    Div {
        signed: bool,
        width: u8,
        src: Opnd,
    },
    /// MOVS/STOS with 64-bit addresses and no FS/GS source; with REP only
    /// inside one page per operand, forward, RAX 0 for wide STOS.
    Movs {
        width: u8,
        rep: bool,
    },
    Stos {
        width: u8,
        rep: bool,
    },
    /// REPE/REPNE CMPS (SCAS: `scan`) with 64-bit addresses and no FS/GS
    /// source: natively inside one page per operand, forward (else a step)
    RepCompare {
        width: u8,
        scan: bool,
        equal: bool,
    },
    MovSreg {
        segment: u8,
        width: u8,
        dst: Opnd,
    },
    /// Compatibility mode's MMX (P7.2a, as Tier-0's: x86tpl::mmx, the packed
    /// templates at 8 bytes); the MM registers alias the x87 stack
    Mmx {
        form: MmxForm,
    },
    /// Compatibility mode's SHLD/SHRD r/m32, r32, CL (P7.2)
    DoubleShiftCl {
        left: bool,
        dst: Opnd,
        src: Reg,
    },
    /// SHLD/SHRD r/m32/64, r, imm8
    DoubleShift {
        left: bool,
        width: u8,
        dst: Opnd,
        src: Reg,
        count: u8,
    },
    /// CMPXCHG16B (wide) / CMPXCHG8B
    CompareExchange {
        wide: bool,
        address: AddressExpr,
    },
    /// SSE moves of the low `bits` (32, 64 or 128). Register destinations
    /// keep their other bits unless `zero` (always for 32/64-bit loads), or
    /// take them from `upper` (VMOVSS/VMOVSD between registers: VEX.vvvv);
    /// `aligned` memory operands must be 16-byte aligned (else #GP, retried).
    ///
    /// The vector templates serve the VEX forms too (see vex): their
    /// `first` source is read where the legacy forms read the destination
    /// (VEX.vvvv; the legacy forms' `first` is their `dst`), a register
    /// destination's bits 255:128 are zeroed (Emitter::vex_upper), and only
    /// the aligned moves check alignment.
    Vmove {
        bits: u8,
        dst: Xmm,
        src: Xmm,
        aligned: bool,
        zero: bool,
        upper: Option<u8>,
    },
    /// 128-bit AND ANDN OR XOR (PS/PD/integer forms) of `first` and `src`;
    /// legacy memory is aligned.
    Vlogic {
        code: u8,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// ADD MUL SUB DIV (`code` 0x58 0x59 0x5C 0x5E) of single or double
    /// precision lanes: packed (legacy memory aligned) or scalar (the low
    /// lane; the others from `first`). See Emitter::vfp for when it runs
    /// natively. With x64_sse_fast_check (P4.18) also SQRT (0x51), RSQRT
    /// (0x52), RCP (0x53), MIN (0x5D) and MAX (0x5F), all through
    /// x86tpl::ops::float.
    Vfp {
        code: u8,
        double: bool,
        packed: bool,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// MOVD/MOVQ xmm, r/m32/64 (upper bits cleared)
    MovdIn {
        width: u8,
        dst: u8,
        src: Opnd,
    },
    /// MOVD/MOVQ r/m32/64, xmm
    MovdOut {
        width: u8,
        dst: Opnd,
        src: u8,
    },
    /// SSE2 packed integer, shuffle and unpack forms with Wasm SIMD (the
    /// semantics of cpu::sse_instr, as ir::tier0::simd): dst = op(first,
    /// src). Memory sources are 128 bits and legacy ones must be aligned
    /// (else #GP, retried).
    Vpacked {
        op: Packed,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// PCMPESTRM/PCMPESTRI/PCMPISTRM/PCMPISTRI (SSE4.2; `op` the 66 0F 3A
    /// byte) through x64_page_pcmpstr on the operand block; the lengths are
    /// RAX/RDX with REX.W (`wide`), else EAX/EDX. RCX (ECX, zero-extended)
    /// or XMM0, and the arithmetic flags. An m128 needs no alignment.
    Vstrings {
        op: u8,
        imm8: u8,
        wide: bool,
        dst: u8,
        src: Xmm,
    },
    /// ROUNDPS/ROUNDPD/ROUNDSS/ROUNDSD (SSE4.1) with Wasm SIMD, as
    /// ir::tier0::simd's Round: retried in the interpreter for a NaN lane,
    /// MXCSR.DAZ, MXCSR.RC other than nearest with imm8[2], and an inexact
    /// lane whose PE is reported and unmasked; PE is set here. Memory: a
    /// scalar form's lane, or an aligned m128.
    Vround {
        double: bool,
        scalar: bool,
        imm8: u8,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// PSRLW/D/Q PSRAW/D PSLLW/D/Q xmm, imm8 (`kind` is the ModRM reg), and
    /// PSRLDQ/PSLLDQ (`bits` 128): dst = src shifted (VEX: dst is VEX.vvvv,
    /// src the r/m register; legacy: the same register); `wide`: AVX2's
    /// VEX.256 forms, each half alike
    VshiftImm {
        dst: u8,
        src: u8,
        bits: u8,
        kind: u8,
        count: u8,
        wide: bool,
    },
    /// VZEROUPPER: bits 255:128 of YMM0-15 zeroed
    Vzeroupper,
    /// VMOVUPS/UPD/DQU, VMOVAPS/APD/DQA (`aligned`: 32-byte) and
    /// VMOVNTPS/PD/DQ with VEX.256: all 32 bytes (a store's operand checked
    /// whole before it is written)
    Vmove256 {
        dst: Xmm,
        src: Xmm,
        aligned: bool,
    },
    /// VZEROALL: YMM0-15 zeroed
    Vzeroall,
    /// AVX2's packed integer forms (VEX.256, P7): `op` on each half of
    /// `first` (VEX.vvvv) and ymm/m256 (not the shifts by xmm/m128)
    Vpacked256 {
        op: Packed,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// VINSERTF128, VINSERTI128: `first` (VEX.vvvv) with its `high` or low
    /// half replaced by xmm/m128
    Vinsert128 {
        dst: u8,
        first: u8,
        src: Xmm,
        high: bool,
    },
    /// VPERM2F128, VPERM2I128: each half of the destination is a half of
    /// `first` (VEX.vvvv) or of ymm/m256, or zero, as imm8 selects
    Vperm2 {
        dst: u8,
        first: u8,
        src: Xmm,
        imm8: u8,
    },
    /// VPMOVMSKB, VMOVMSKPS, VMOVMSKPD r32/r64, ymm: the sign bits of both
    /// halves' `lane`-byte lanes, zero-extended
    Vmovmsk256 {
        dst: Reg,
        src: u8,
        lane: u8,
    },
    /// VBROADCASTSS/SD (AVX2: also from a register), VPBROADCASTB/W/D/Q: the
    /// element (`bytes`) of memory or of a register's low lane in each lane
    /// of an XMM register (bits 255:128 zeroed) or (`wide`) a YMM register
    Vbroadcast {
        bytes: u8,
        dst: u8,
        src: Xmm,
        wide: bool,
    },
    /// PMOVMSKB MOVMSKPS MOVMSKPD r32/r64, xmm (and their VEX forms): the
    /// sign bits of the `lane`-byte lanes, zero-extended
    Vmovmsk {
        dst: Reg,
        src: u8,
        lane: u8,
    },
    /// CMPPS CMPPD CMPSS CMPSD with `predicate` (imm8[2:0]; VEX imm8[4:0]):
    /// for operands neither NaN nor denormal (else retried), which raise
    /// nothing and whose result imm8[2:0]'s relation decides; a scalar
    /// form's other lanes from `first`
    Vcmp {
        double: bool,
        scalar: bool,
        predicate: u8,
        dst: u8,
        first: u8,
        src: Xmm,
    },
    /// BLENDVPS BLENDVPD PBLENDVB: `src`'s lanes of `lane` bytes whose sign
    /// bit in XMM `mask` (XMM0; VEX imm8[7:4]) is set, else `first`'s
    Vblendv {
        lane: u8,
        dst: u8,
        first: u8,
        src: Xmm,
        mask: u8,
    },
    /// The packed conversions of x86tpl::ops (P2.5, switch x64_cvt; the
    /// decoder steps them while it is off): CVTPS2PD, CVTPD2PS, CVTDQ2PS,
    /// CVTDQ2PD, CVT(T)PS2DQ and CVT(T)PD2DQ
    Vcvt {
        op: Cvt,
        dst: u8,
        src: Xmm,
    },
    /// The scalar conversions (see Emitter::vconvert): retried unless exact
    /// or only inexact, MXCSR to nearest with every exception masked
    Vconvert {
        convert: Convert,
        dst: u8,
        first: u8,
    },
    /// COMISS UCOMISS COMISD UCOMISD: natively when neither operand is a NaN
    /// or a denormal, which leaves MXCSR unchanged; else retried.
    Vcompare {
        double: bool,
        dst: u8,
        src: Xmm,
    },
    /// INVLPG m (CPL 0; see pages::x64_page_invlpg)
    Invlpg {
        address: AddressExpr,
    },
    /// LDMXCSR (`load`) / STMXCSR m32
    Mxcsr {
        load: bool,
        address: AddressExpr,
    },
    /// MOV r64, CR0/CR2/CR3/CR4 (CPL 0)
    ReadCr {
        control: u8,
        reg: Reg,
    },
    /// MOV r64, CR8 / MOV CR8, r64 (the local APIC's TPR)
    Cr8 {
        write: bool,
        reg: Reg,
    },
    Rdtscp,
    /// Compatibility mode's x87 (docs/jit-unification-plan.md P7.2a): a
    /// form crate::x86tpl::x87_forms classifies, its memory operand at `address`,
    /// inlined in f64 against the shadow cache (x86tpl::x87) where it
    /// applies and the fast-math policy allows, else ir_t0_x87 on the CPU
    /// state, as Tier-0 runs it
    X87 {
        opcode: u8,
        modrm: u8,
        io: crate::x86tpl::x87_forms::Io,
        address: Option<AddressExpr>,
    },
    /// FNSTSW AX
    Fnstsw,
    /// FCOMI, FCOMIP, FUCOMI, FUCOMIP: `name`'s helper on the CPU state
    /// sets ZF, PF and CF (and clears OF, SF, AF)
    X87Flags {
        name: &'static str,
        r: u8,
    },
    /// FCMOVcc ST(0), ST(r)
    Fcmov {
        cc: u8,
        r: u8,
    },
    /// Interpreted in place by x64_page_step.
    Step,
}

/// Op::Vcvt's conversions
#[derive(Clone, Copy, Debug)]
enum Cvt {
    /// One Wasm operation (x86tpl::ops::convert): its opcode, the bytes of
    /// the source and of the result
    Convert { opcode: u32, source: u8, result: u8 },
    /// CVT(T)PS2DQ and CVT(T)PD2DQ (x86tpl::ops::convert_to_integers)
    Integers { double: bool, truncate: bool },
}

/// The scalar conversions of Op::Vconvert
#[derive(Clone, Copy, Debug)]
enum Convert {
    /// CVTSI2SS/CVTSI2SD xmm, r/m32/64 (`width`) into the low lane
    FromInteger { double: bool, width: u8, src: Opnd },
    /// CVT(T)SS2SI/CVT(T)SD2SI r32/r64 (`width`; Op::Vconvert's `dst` the
    /// general-purpose register), xmm/m32/m64
    ToInteger {
        double: bool,
        truncate: bool,
        width: u8,
        src: Xmm,
    },
    /// CVTSS2SD (`double`: to double precision) and CVTSD2SS xmm, xmm/m
    Precision { double: bool, src: Xmm },
}

/// x86tpl's packed SSE4 forms but PMULDQ, which this tier steps (its
/// template is Tier-0's alone so far)
fn sse4_packed(opcode: u32, imm8: Option<u64>) -> Option<Packed> {
    vec::sse4_packed(opcode, imm8.map(|imm| imm as u32)).filter(|_| opcode != 0x660F3828)
}

/// PALIGNR xmm, xmm/m128, imm8 (x86tpl::vec::palignr)
fn palignr(imm8: u64) -> Packed { vec::palignr(imm8.min(255) as u8, 16) }

fn register(encoded: u8, width: u8, rex: bool) -> Reg {
    if width == 8 {
        match decode::byte_register(encoded, rex) {
            ByteRegister::Low(index) => Reg { index, high: false },
            ByteRegister::HighLegacy(index) => Reg { index, high: true },
        }
    }
    else {
        Reg {
            index: encoded,
            high: false,
        }
    }
}

/// Branch target relative to the page (decoded at linear address 0; see
/// compile). Whether it is canonical depends on where the page runs.
fn relative(d: &Decoded) -> Option<u64> {
    let i = d.immediate?;
    let displacement = match i.encoded_bytes {
        1 => i.value as i8 as i64,
        2 => i.value as i16 as i64,
        _ => i.value as i32 as i64,
    };
    Some(d.next.0.wrapping_add(displacement as u64))
}
/// 16-bit protected-mode code (P7.7): a near branch's target IP wraps at
/// 64 KiB in CS, so its target relative to the page is that IP less the IP
/// of the page's first byte (CompileEnv::ip_base)
fn wrap_ip(op: Op, ip_base: i32) -> Op {
    let wrap = |target: u64| {
        ((ip_base as i64).wrapping_add(target as i64) & 0xFFFF).wrapping_sub(ip_base as i64) as u64
    };
    match op {
        Op::Jmp { target } => Op::Jmp {
            target: wrap(target),
        },
        Op::Jcc { cc, target } => Op::Jcc {
            cc,
            target: wrap(target),
        },
        Op::Call { target } => Op::Call {
            target: wrap(target),
        },
        Op::LoopJump { kind, cx, target } => Op::LoopJump {
            kind,
            cx,
            target: wrap(target),
        },
        op => op,
    }
}

/// A volatile instruction's op (CompileEnv::volatile): forms whose one
/// immediate is a source operand (Emitter::read loads it, Inst::dynamic),
/// else a step, which interprets the bytes as they are
fn volatile_op(d: &Decoded, op: Op) -> Op {
    let dynamic = d
        .immediate
        .is_some_and(|i| matches!(i.encoded_bytes, 1 | 2 | 4))
        && matches!(
            op,
            Op::Alu {
                src: Opnd::Imm(_),
                ..
            } | Op::Mov {
                src: Opnd::Imm(_),
                ..
            } | Op::Test {
                b: Opnd::Imm(_),
                ..
            } | Op::Imul {
                b: Opnd::Imm(_),
                ..
            } | Op::Push { src: Opnd::Imm(_) }
                | Op::Push16 { src: Opnd::Imm(_) }
        );
    if dynamic {
        op
    }
    else {
        Op::Step
    }
}

/// The mode of 16-bit code (CompileEnv::mode16): protected mode (P7.7),
/// real mode or virtual-8086 mode (P7.8). Real-mode segment bases are the
/// selectors shifted left by 4 (pages::x64_page_load_seg loads them as the
/// interpreter does); virtual-8086 code steps what IOPL governs there.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Mode16 {
    Protected,
    Real,
    V86,
}
/// 16-bit code in the page tier: 16-bit protected mode (P7.7), real and
/// virtual-8086 mode (P7.8)
fn code16(mode: ExecutionMode) -> bool {
    matches!(
        mode,
        ExecutionMode::Protected16 | ExecutionMode::Real | ExecutionMode::Vm86
    )
}

/// The template for a long-mode instruction, or Step. Mirrors
/// x64::execute::execute; anything it does not cover exactly is a Step.
/// 32-bit compatibility-mode code (CompileEnv::compat) shares the long-mode
/// templates the emitter treats in both modes (compat_template), its own
/// forms (INC/DEC 40-4F, the 32-bit stack), and steps the rest.
fn classify(d: &Decoded) -> Op {
    // (16-bit protected-mode code, P7.7, as 32-bit code with 16-bit
    // operands, addresses and stack)
    let prot16 = code16(d.mode);
    let compat = d.mode == ExecutionMode::Compatibility32 || prot16;
    if !d.mode.is_long() && !compat {
        return Op::Step;
    }
    // (the stack width of PUSH, POP, CALL and RET: 64, or 32 in
    // compatibility mode, 16 in 16-bit code; other operand sizes are steps)
    let stack = if prot16 {
        16
    }
    else if compat {
        32
    }
    else {
        64
    };
    let op = d.base_opcode();
    let w = d.operand_size;
    // (near branches: in compatibility mode with 32-bit operands, a 16-bit
    // operand size truncating EIP is a step; in 16-bit code with 16-bit
    // operands, their IP wrapping at 64 KiB: wrap_ip)
    let near = if prot16 { w == 16 } else { !compat || w == 32 };
    let rex = d.prefixes.rex.is_some();
    let group = d.modrm.map_or(0, |m| m >> 3 & 7);
    let imm = d.immediate.map(|i| i.value);
    let memory = d.rm_register.is_none() && d.address.is_some();
    let reg = |r: u8, width: u8| register(r, width, rex);
    let rm = |width: u8| -> Option<Opnd> {
        match d.rm_register {
            Some(r) => Some(Opnd::Reg(reg(r, width))),
            None => d.address.map(Opnd::Mem),
        }
    };
    // REP/REPNE are ignored by these forms in the interpreter (or select
    // their catalog entry); anything else with REP is a step.
    let rep_ok = matches!(op, 0xC2 | 0xC3 | 0xE8 | 0xE9 | 0xEB | 0x70..=0x7F | 0x0F80..=0x0F8F | 0x0FB8 | 0x0FBC | 0x0FBD | 0x0F1E | 0xA4..=0xA7 | 0xAA..=0xAF)
        || op == 0xFF && matches!(group, 2 | 4)
        // F3/F2 that select an SSE instruction are not repeat prefixes
        || matches!(d.opcode >> 16, 0xF2 | 0xF3);
    if d.prefixes.rep.is_some() && !rep_ok {
        return Op::Step;
    }
    // The decoder accepts LOCK only on memory read-modify-write forms.
    let lock_ok = memory
        && match op {
            0x00..=0x3D => op & 7 <= 1 && op >> 3 != 7,
            0x80 | 0x81 | 0x83 => group != 7,
            0xFE | 0xFF => group <= 1,
            0xF6 | 0xF7 => matches!(group, 2 | 3),
            0x86 | 0x87 | 0x0FC0 | 0x0FC1 | 0x0FB0 | 0x0FB1 | 0x0FAB | 0x0FB3 | 0x0FBB => true,
            0x0FBA => group >= 5,
            0x0FC7 => group == 1,
            _ => false,
        };
    if d.prefixes.lock && !lock_ok {
        return Op::Step;
    }
    // With cores in workers, a locked read-modify-write (XCHG with memory is
    // locked) commits with a compare-exchange loop (see locked_rmw), or
    // atomically in the interpreter (x64::memory::run_locked).
    let result = (|| -> Option<Op> {
        if d.vex.is_some() {
            return vex(d);
        }
        Some(match op {
            0x00..=0x3D if op & 7 <= 5 => {
                let code = (op >> 3) as u8;
                let width = if op & 1 == 0 { 8 } else { w };
                match op & 7 {
                    0 | 1 => Op::Alu {
                        code,
                        width,
                        dst: rm(width)?,
                        src: Opnd::Reg(reg(d.reg?, width)),
                    },
                    2 | 3 => Op::Alu {
                        code,
                        width,
                        dst: Opnd::Reg(reg(d.reg?, width)),
                        src: rm(width)?,
                    },
                    _ => Op::Alu {
                        code,
                        width,
                        dst: Opnd::Reg(reg(0, width)),
                        src: Opnd::Imm(imm? & mask(width)),
                    },
                }
            },
            0x80 | 0x81 | 0x83 => {
                let width = if op == 0x80 { 8 } else { w };
                Op::Alu {
                    code: group,
                    width,
                    dst: rm(width)?,
                    src: Opnd::Imm(imm? & mask(width)),
                }
            },
            0x84 | 0x85 => {
                let width = if op == 0x84 { 8 } else { w };
                Op::Test {
                    width,
                    a: rm(width)?,
                    b: Opnd::Reg(reg(d.reg?, width)),
                }
            },
            0xA8 | 0xA9 => {
                let width = if op == 0xA8 { 8 } else { w };
                Op::Test {
                    width,
                    a: Opnd::Reg(reg(0, width)),
                    b: Opnd::Imm(imm? & mask(width)),
                }
            },
            0x88..=0x8B => {
                let width = if op & 1 == 0 { 8 } else { w };
                if op & 2 == 0 {
                    Op::Mov {
                        width,
                        dst: rm(width)?,
                        src: Opnd::Reg(reg(d.reg?, width)),
                    }
                }
                else {
                    Op::Mov {
                        width,
                        dst: Opnd::Reg(reg(d.reg?, width)),
                        src: rm(width)?,
                    }
                }
            },
            0xB0..=0xBF => {
                let width = if op < 0xB8 { 8 } else { w };
                Op::Mov {
                    width,
                    dst: Opnd::Reg(reg(d.opcode_register?, width)),
                    src: Opnd::Imm(imm? & mask(width)),
                }
            },
            0xC6 | 0xC7 if group == 0 => {
                let width = if op == 0xC6 { 8 } else { w };
                Op::Mov {
                    width,
                    dst: rm(width)?,
                    src: Opnd::Imm(imm? & mask(width)),
                }
            },
            0x8D => Op::Lea {
                width: w,
                dst: reg(d.reg?, w),
                address: d.address?,
            },
            0x63 if !compat => Op::Extend {
                width: w,
                from: if w == 16 { 16 } else { 32 },
                signed: true,
                dst: reg(d.reg?, w),
                src: rm(if w == 16 { 16 } else { 32 })?,
            },
            0x0FB6 | 0x0FB7 | 0x0FBE | 0x0FBF => {
                let from = if op & 1 == 0 { 8 } else { 16 };
                Op::Extend {
                    width: w,
                    from,
                    signed: op & 8 != 0,
                    dst: reg(d.reg?, w),
                    src: rm(from)?,
                }
            },
            0xFE | 0xFF if group <= 1 => {
                let width = if op == 0xFE { 8 } else { w };
                Op::IncDec {
                    dec: group == 1,
                    width,
                    dst: rm(width)?,
                }
            },
            0xF6 | 0xF7 => {
                let width = if op == 0xF6 { 8 } else { w };
                match group {
                    0 | 1 => Op::Test {
                        width,
                        a: rm(width)?,
                        b: Opnd::Imm(imm? & mask(width)),
                    },
                    2 => Op::Not {
                        width,
                        dst: rm(width)?,
                    },
                    3 => Op::Neg {
                        width,
                        dst: rm(width)?,
                    },
                    // (16-bit code's DX:AX, P7.7)
                    4 | 5 if width >= 32 || width == 16 && prot16 => Op::MulWide {
                        signed: group == 5,
                        width,
                        src: rm(width)?,
                    },
                    6 | 7 if width >= 32 || width == 16 && prot16 => Op::Div {
                        signed: group == 7,
                        width,
                        src: rm(width)?,
                    },
                    _ => return None,
                }
            },
            0xC0 | 0xC1 | 0xD0 | 0xD1 | 0xD2 | 0xD3 => {
                let width = if op & 1 == 0 { 8 } else { w };
                let count = match op {
                    0xC0 | 0xC1 => Some(imm? as u8),
                    0xD0 | 0xD1 => Some(1),
                    _ => None,
                };
                // Rotates through carry, and narrow CL shifts or rotates,
                // call the interpreter's semantics (64-bit RCL/RCR step).
                if matches!(group, 2 | 3) || count.is_none() && width < 32 {
                    if width == 64 {
                        return None;
                    }
                    return Some(Op::ShiftCall {
                        code: group,
                        width,
                        dst: rm(width)?,
                        count,
                    });
                }
                Op::Shift {
                    code: group,
                    width,
                    dst: rm(width)?,
                    count,
                }
            },
            0x0FAF => Op::Imul {
                width: w,
                dst: reg(d.reg?, w),
                a: rm(w)?,
                b: Opnd::Reg(reg(d.reg?, w)),
            },
            0x69 | 0x6B => Op::Imul {
                width: w,
                dst: reg(d.reg?, w),
                a: rm(w)?,
                b: Opnd::Imm(imm? & mask(w)),
            },
            // (compatibility mode: INC and DEC r32, REX prefixes in 64-bit mode)
            0x40..=0x4F if compat => Op::IncDec {
                dec: op >= 0x48,
                width: w,
                dst: Opnd::Reg(reg(op as u8 & 7, w)),
            },
            0x50..=0x57 if w == stack => Op::Push {
                src: Opnd::Reg(reg(d.opcode_register?, stack)),
            },
            0x58..=0x5F if w == stack => Op::Pop {
                dst: reg(d.opcode_register?, stack),
            },
            0x68 | 0x6A if w == stack => Op::Push {
                src: Opnd::Imm(imm?),
            },
            0xFF if group == 6 && w == stack => Op::Push { src: rm(stack)? },
            // (virtual-8086 mode: IOPL governs it, a step; P7.8)
            0x9C if w == stack && d.mode != ExecutionMode::Vm86 => Op::Pushf,
            0xC9 if w == stack => Op::Leave,
            0xE8 if near => Op::Call {
                target: relative(d)?,
            },
            0xFF if group == 2 && near => Op::CallIndirect { src: rm(stack)? },
            0xFF if group == 4 && near => Op::JmpIndirect { src: rm(stack)? },
            0xC3 if near => Op::Ret { pop: 0 },
            0xC2 if near => Op::Ret { pop: imm? as u16 },
            0xE9 | 0xEB if near => Op::Jmp {
                target: relative(d)?,
            },
            0x70..=0x7F | 0x0F80..=0x0F8F if near => Op::Jcc {
                cc: op as u8 & 15,
                target: relative(d)?,
            },
            0x0F40..=0x0F4F => Op::Cmov {
                cc: op as u8 & 15,
                width: w,
                dst: reg(d.reg?, w),
                src: rm(w)?,
            },
            0x0F90..=0x0F9F => Op::Setcc {
                cc: op as u8 & 15,
                dst: rm(8)?,
            },
            0x86 | 0x87 => {
                let width = if op == 0x86 { 8 } else { w };
                Op::Xchg {
                    width,
                    a: rm(width)?,
                    b: reg(d.reg?, width),
                }
            },
            0x90 if d.opcode_register? & 7 == 0 && d.opcode_register? < 8 => {
                // PAUSE yields the core in the interpreter
                if d.prefixes.rep.is_some() {
                    return None;
                }
                Op::Nop
            },
            0x90..=0x97 => Op::Xchg {
                width: w,
                a: Opnd::Reg(reg(0, w)),
                b: reg(d.opcode_register?, w),
            },
            0x0FC0 | 0x0FC1 => {
                let width = if op == 0x0FC0 { 8 } else { w };
                Op::Xadd {
                    width,
                    dst: rm(width)?,
                    src: reg(d.reg?, width),
                }
            },
            0x0FB0 | 0x0FB1 => {
                let width = if op == 0x0FB0 { 8 } else { w };
                Op::Cmpxchg {
                    width,
                    dst: rm(width)?,
                    src: reg(d.reg?, width),
                }
            },
            0x98 => Op::SignAcc { width: w },
            0x99 => Op::SignDx { width: w },
            0x0FA3 | 0x0FAB | 0x0FB3 | 0x0FBB => Op::Bt {
                action: ((op >> 3) & 3) as u8,
                width: w,
                dst: rm(w)?,
                index: Opnd::Reg(reg(d.reg?, w)),
            },
            0x0FBA if group >= 4 => Op::Bt {
                action: group - 4,
                width: w,
                dst: rm(w)?,
                index: Opnd::Imm(imm?),
            },
            // (TZCNT and LZCNT, F3 0F BC/BD with their features: a step)
            // TZCNT and LZCNT (F3 0F BC/BD with their features; 16-bit: a step)
            0x0FBC | 0x0FBD if d.opcode >> 16 == 0xF3 && w != 16 => Op::Bmi {
                op: if op == 0x0FBC { BmiOp::Tzcnt } else { BmiOp::Lzcnt },
                width: w,
                dst: reg(d.reg?, w),
                src: rm(w)?,
                other: reg(0, w),
            },
            // MOVBE (not CRC32: F2 0F 38 F0/F1; memory only; 16-bit: a step)
            0x0F38F0 | 0x0F38F1 if d.opcode == op && memory && w != 16 => Op::Movbe {
                load: op == 0x0F38F0,
                width: w,
                reg: reg(d.reg?, w),
                mem: d.address?,
            },
            0x0FBC | 0x0FBD if d.opcode >> 16 != 0xF3 => Op::BitScan {
                reverse: op == 0x0FBD,
                width: w,
                dst: reg(d.reg?, w),
                src: rm(w)?,
            },
            0x0FB8 if d.opcode == 0xF30FB8 => Op::Popcnt {
                width: w,
                dst: reg(d.reg?, w),
                src: rm(w)?,
            },
            0x0FC8..=0x0FCF if w != 16 => Op::Bswap {
                width: w,
                reg: (op as u8 & 7) | d.prefixes.b(),
            },
            0xF5 | 0xF8 | 0xF9 | 0xFC | 0xFD => Op::Flag { opcode: op as u8 },
            0x9E => Op::Sahf,
            0x9F => Op::Lahf,
            0x0F0D | 0x0F18..=0x0F1F => Op::Nop,
            0xFA => Op::Cli,
            0xFB => Op::Sti,
            0x0F01 if d.modrm == Some(0xF8) => Op::Swapgs,
            0x0F01 if group == 7 && memory => Op::Invlpg {
                address: d.address?,
            },
            0x0F31 => Op::Rdtsc,
            0xA4 | 0xA5 | 0xAA | 0xAB
                if d.address_size == stack
                    && !(op <= 0xA5 && matches!(d.prefixes.segment, Some(4 | 5))) =>
            {
                let width = if op & 1 == 0 { 8 } else { w };
                let rep = d.prefixes.rep.is_some();
                if op <= 0xA5 {
                    Op::Movs { width, rep }
                }
                else {
                    Op::Stos { width, rep }
                }
            },
            0xA6 | 0xA7 | 0xAE | 0xAF
                if d.address_size == stack
                    && d.prefixes.rep.is_some()
                    && !(op <= 0xA7 && matches!(d.prefixes.segment, Some(4 | 5))) =>
            {
                Op::RepCompare {
                    width: if op & 1 == 0 { 8 } else { w },
                    scan: op >= 0xAE,
                    equal: d.prefixes.rep == Some(0xF3),
                }
            },
            0x8C if group < 6 => Op::MovSreg {
                segment: group,
                width: if memory { 16 } else { w },
                dst: rm(w)?,
            },
            0x0FA5 | 0x0FAD if compat && w == 32 => Op::DoubleShiftCl {
                left: op == 0x0FA5,
                dst: rm(w)?,
                src: reg(d.reg?, w),
            },
            0x0FA4 | 0x0FAC if w >= 32 => Op::DoubleShift {
                left: op == 0x0FA4,
                width: w,
                dst: rm(w)?,
                src: reg(d.reg?, w),
                count: imm? as u8,
            },
            0x0FC7 if group == 1 && memory => Op::CompareExchange {
                wide: w == 128,
                address: d.address?,
            },
            // MOV AL/rAX, moffs and back: an absolute address (FS/GS base added)
            0xA0..=0xA3 => {
                let width = if op & 1 == 0 { 8 } else { w };
                let address = AddressExpr {
                    base: AddressBase::None,
                    index: None,
                    scale: 1,
                    displacement: imm? as i64,
                    address_size: d.address_size,
                    segment: d.prefixes.segment.unwrap_or(3),
                };
                let accumulator = Opnd::Reg(Reg {
                    index: 0,
                    high: false,
                });
                if op & 2 == 0 {
                    Op::Mov {
                        width,
                        dst: accumulator,
                        src: Opnd::Mem(address),
                    }
                }
                else {
                    Op::Mov {
                        width,
                        dst: Opnd::Mem(address),
                        src: accumulator,
                    }
                }
            },
            // MOVNTI: an ordinary store here
            0x0FC3 if memory && w >= 32 => Op::Mov {
                width: w,
                dst: rm(w)?,
                src: Opnd::Reg(reg(d.reg?, w)),
            },
            // LFENCE MFENCE SFENCE: one core runs at a time, in program order
            0x0FAE if d.opcode == 0x0FAE && d.rm_register.is_some() && group >= 5 => Op::Nop,
            0x0FAE if d.opcode == 0x0FAE && memory && matches!(group, 2 | 3) => Op::Mxcsr {
                load: group == 2,
                address: d.address?,
            },
            0x0F01 if d.modrm == Some(0xF9) => Op::Rdtscp,
            0x0F20 if matches!(d.reg, Some(0 | 2 | 3 | 4)) && d.rm_register.is_some() => {
                Op::ReadCr {
                    control: d.reg?,
                    reg: reg(d.rm_register?, 64),
                }
            },
            0x0F20 | 0x0F22 if d.reg == Some(8) && d.rm_register.is_some() => Op::Cr8 {
                write: op == 0x0F22,
                reg: reg(d.rm_register?, 64),
            },
            // (compatibility mode's x87 as Tier-0's, P7.2a)
            0xD8..=0xDF if compat => {
                let modrm = d.modrm?;
                match crate::x86tpl::x87_forms::io(op as u8, modrm) {
                    Some(io) => Op::X87 {
                        opcode: op as u8,
                        modrm,
                        io,
                        address: if modrm < 0xC0 { Some(d.address?) } else { None },
                    },
                    None if op == 0xDF && modrm == 0xE0 => Op::Fnstsw,
                    None if modrm >= 0xC0 && matches!((op, group), (0xDB | 0xDF, 5 | 6)) => {
                        Op::X87Flags {
                            name: match (op, group) {
                                (0xDB, 5) => "fpu_fucomi",
                                (0xDB, _) => "fpu_fcomi",
                                (_, 5) => "fpu_fucomip",
                                _ => "fpu_fcomip",
                            },
                            r: modrm & 7,
                        }
                    },
                    None if modrm >= 0xC0 && matches!(op, 0xDA | 0xDB) && group <= 3 => Op::Fcmov {
                        cc: [2, 4, 6, 10][group as usize] | (op == 0xDB) as u8,
                        r: modrm & 7,
                    },
                    None => return None,
                }
            },
            // (compatibility mode's MMX, P7.2a)
            _ if compat && d.opcode >> 8 == 0x0F && !d.prefixes.lock && mmx(d).is_some() => {
                return mmx(d)
            },
            _ if d.opcode >> 8 & 0xFF == 0x0F
                || d.opcode >> 16 == 0x0F
                || matches!(op >> 8, 0x0F38 | 0x0F3A) =>
            {
                return sse(d)
            },
            _ => return None,
        })
    })();
    match result {
        // (compatibility mode: shifts and rotates by the 32-bit
        // interpreter's rules, 32-bit ROL, ROR, SHL, SHR and SAR inline
        // (Emitter::legacy_shift32), the others through its helper)
        Some(Op::Shift {
            code,
            width,
            dst,
            count,
        }) if compat
            && d.address.map_or(true, |a| a.address_size == 32 || prot16)
            && !(width == 32 && code != 2 && code != 3) =>
        {
            Op::ShiftCall {
                code,
                width,
                dst,
                count,
            }
        },
        Some(op) if !compat || compat_template(&op, d) => op,
        _ => Op::Step,
    }
}

/// Legacy mode's further templates (CompileEnv::legacy, P7.3) for what
/// classify leaves to a step, so that other modes compile as before:
/// Tier-0's forms that Windows 98 and XP code would step through otherwise
/// (P3.7 there): LOOP and JECXZ, segment register loads, pops and pushes,
/// 16-bit pushes and pops, POP m32, PUSHAD and POPAD, LODS without REP,
/// CLI and STI. Memory operands with 32-bit addresses only, as
/// compat_template.
fn legacy_template(d: &Decoded) -> Option<Op> {
    let prot16 = code16(d.mode);
    if d.address.is_some_and(|a| a.address_size != 32 && !prot16)
        || d.prefixes.rep.is_some()
        || d.prefixes.lock
    {
        return None;
    }
    let op = d.base_opcode();
    let w = d.operand_size;
    // (16-bit code, P7.7: LOOP and JCXZ with 16-bit operands, segment
    // register loads, pushes and pops, CLI and STI; the 32-bit forms step)
    if prot16
        && !matches!(op, 0xE0..=0xE3 | 0x8E | 0x06 | 0x07 | 0x0E | 0x16 | 0x1E | 0x1F | 0x0FA0 | 0x0FA1 | 0x0FA8 | 0x0FA9 | 0xFA | 0xFB
            | 0x50..=0x5F | 0x68 | 0x6A | 0xFF | 0x8F | 0xC4 | 0xC5 | 0xC8 | 0xAC | 0xAD | 0x9A | 0xCA | 0xCB)
    {
        return None;
    }
    let group = d.modrm.map_or(0, |m| m >> 3 & 7);
    let rm16 = || match d.rm_register {
        Some(r) => Some(Opnd::Reg(register(r, 16, false))),
        None => d.address.map(Opnd::Mem),
    };
    // (ES, CS, SS, DS, FS, GS)
    let segment = |op: u32| match op {
        0x06 | 0x07 => 0,
        0x0E => 1,
        0x16 => 2,
        0x1E | 0x1F => 3,
        0x0FA0 | 0x0FA1 => 4,
        _ => 5,
    };
    let rm32 = || match d.rm_register {
        Some(r) => Some(Opnd::Reg(register(r, 32, false))),
        None => d.address.map(Opnd::Mem),
    };
    Some(match op {
        // (16-bit code, P7.7: 32-bit pushes and pops, LES and LDS, ENTER at
        // level 0, LODS with 16-bit addresses)
        0x50..=0x57 if prot16 && w == 32 => Op::Push32 {
            src: Opnd::Reg(register(d.opcode_register?, 32, false)),
        },
        0x58..=0x5F if prot16 && w == 32 => Op::Pop32 {
            dst: Opnd::Reg(register(d.opcode_register?, 32, false)),
        },
        0x68 | 0x6A if prot16 && w == 32 => Op::Push32 {
            src: Opnd::Imm(d.immediate?.value & 0xFFFF_FFFF),
        },
        0xFF if prot16 && group == 6 && w == 32 => Op::Push32 { src: rm32()? },
        0x8F if prot16 && group == 0 && w == 32 => Op::Pop32 { dst: rm32()? },
        0xC4 | 0xC5 if prot16 && d.rm_register.is_none() => Op::LoadFar {
            segment: if op == 0xC4 { 0 } else { 3 },
            width: w,
            dst: register(d.reg?, w, false),
            address: d.address?,
        },
        0xC8 if prot16 && w == 16 && d.extra_immediate == Some(0) => Op::Enter {
            size: d.immediate?.value as u16,
        },
        // (far CALL and RETF, M11: for code compiled for segment bases,
        // Decoder::at)
        0x9A => Op::FarCall {
            selector: d.extra_immediate?,
            offset: d.immediate?.value as u32,
            width: w,
        },
        0xCB => Op::FarRet { pop: 0, width: w },
        0xCA => Op::FarRet {
            pop: d.immediate?.value as u16,
            width: w,
        },
        0xAC | 0xAD if prot16 && d.address_size == 16 => Op::Lods16 {
            width: if op == 0xAC { 8 } else { w },
            segment: d.prefixes.segment.unwrap_or(3),
        },
        _ if prot16
            && matches!(
                op,
                0x50..=0x5F | 0x68 | 0x6A | 0xFF | 0xC4 | 0xC5 | 0xC8 | 0xAC | 0xAD
            ) =>
        {
            return None
        },
        // (a 16-bit operand size truncates EIP: a step; 16-bit code's IP
        // wraps, wrap_ip)
        0xE0..=0xE3 if w == 32 && !prot16 || w == 16 && prot16 => Op::LoopJump {
            kind: op as u8 - 0xE0,
            cx: d.address_size == 16,
            target: relative(d)?,
        },
        0x8E if matches!(group, 0 | 3 | 4 | 5) => Op::LoadSreg {
            segment: group,
            src: rm16()?,
        },
        0x07 | 0x1F | 0x0FA1 | 0x0FA9 if w != 64 => Op::PopSreg {
            segment: segment(op),
            width: w,
        },
        0x06 | 0x0E | 0x16 | 0x1E | 0x0FA0 | 0x0FA8 if w != 64 => Op::PushSreg {
            segment: segment(op),
            width: w,
        },
        0x50..=0x57 if w == 16 => Op::Push16 {
            src: Opnd::Reg(register(d.opcode_register?, 16, false)),
        },
        0x58..=0x5F if w == 16 => Op::Pop16 {
            dst: Opnd::Reg(register(d.opcode_register?, 16, false)),
        },
        0x68 | 0x6A if w == 16 => Op::Push16 {
            src: Opnd::Imm(d.immediate?.value),
        },
        0xFF if group == 6 && w == 16 => Op::Push16 { src: rm16()? },
        0x8F if group == 0 && w == 16 => Op::Pop16 { dst: rm16()? },
        0x8F if group == 0 && w == 32 => match d.rm_register {
            Some(r) => Op::Pop {
                dst: register(r, 32, false),
            },
            None => Op::PopMem {
                address: d.address?,
            },
        },
        0x60 if w == 32 => Op::Pusha,
        0x61 if w == 32 => Op::Popa,
        0xAC | 0xAD if d.address_size == 32 && d.prefixes.segment != Some(5) => Op::Lods {
            width: if op == 0xAC { 8 } else { w },
            segment: d.prefixes.segment.unwrap_or(3),
        },
        0xFA => Op::Cli,
        0xFB => Op::Sti,
        _ => return None,
    })
}

/// The templates the emitter treats in 32-bit compatibility mode
/// (CompileEnv::compat, docs/jit-unification-plan.md P7.2): EIP, ESP and
/// addresses wrap at 4 GiB, the stack slots are 4 bytes. Memory operands
/// with 32-bit addresses only (a 16-bit address is a step); the rest steps
/// until its emitter covers the mode.
fn compat_template(op: &Op, d: &Decoded) -> bool {
    // (16-bit code, P7.7: 16-bit addresses, but its string instructions step)
    if code16(d.mode) {
        if matches!(
            op,
            Op::Movs { .. } | Op::Stos { .. } | Op::RepCompare { .. }
        ) {
            return false;
        }
    }
    else if d.address.is_some_and(|a| a.address_size != 32) {
        return false;
    }
    // (BMI as cpu::bmi in every engine; VEX.W1 is no 64-bit operand here and
    // VEX.vvvv names EAX..EDI: others step)
    if let Op::Bmi {
        width, dst, other, ..
    } = op
    {
        return *width == 32 && dst.index < 8 && other.index < 8;
    }
    matches!(
        op,
        Op::Alu { .. }
            | Op::Test { .. }
            | Op::Mov { .. }
            | Op::Lea { .. }
            | Op::Extend { .. }
            | Op::IncDec { .. }
            | Op::Not { .. }
            | Op::Neg { .. }
            | Op::MulWide { .. }
            | Op::Div { .. }
            | Op::Shift { width: 32, .. }
            | Op::ShiftCall { .. }
            | Op::Imul { .. }
            | Op::Push { .. }
            | Op::Pop { .. }
            | Op::Pushf
            | Op::Leave
            | Op::Call { .. }
            | Op::CallIndirect { .. }
            | Op::JmpIndirect { .. }
            | Op::Ret { .. }
            | Op::Jmp { .. }
            | Op::Jcc { .. }
            | Op::Cmov { .. }
            | Op::Setcc { .. }
            | Op::Xchg { .. }
            | Op::Nop
            | Op::Xadd { .. }
            | Op::Cmpxchg { .. }
            | Op::SignAcc { .. }
            | Op::SignDx { .. }
            | Op::Movs { .. }
            | Op::Stos { .. }
            | Op::RepCompare { .. }
            // (EFLAGS as the 32-bit interpreter leaves them, or none)
            | Op::Bt { .. }
            | Op::Bswap { .. }
            | Op::Flag { .. }
            | Op::Lahf
            | Op::Sahf
            | Op::CompareExchange { .. }
            | Op::MovSreg { .. }
            | Op::Movbe { .. }
            | Op::BitScan { .. }
            | Op::Popcnt { .. }
            | Op::DoubleShift { width: 32, .. }
            | Op::DoubleShiftCl { .. }
            | Op::Mmx { .. }
            // SSE, AVX and their templates (XMM0-7 only: no REX or VEX.R)
            | Op::Vmove { .. }
            | Op::Vlogic { .. }
            | Op::Vfp { .. }
            | Op::MovdIn { .. }
            | Op::MovdOut { .. }
            | Op::Vpacked { .. }
            | Op::Vstrings { .. }
            | Op::Vround { .. }
            | Op::VshiftImm { .. }
            | Op::Vzeroupper
            | Op::Vmove256 { .. }
            | Op::Vzeroall
            | Op::Vpacked256 { .. }
            | Op::Vinsert128 { .. }
            | Op::Vperm2 { .. }
            | Op::Vmovmsk256 { .. }
            | Op::Vbroadcast { .. }
            | Op::Vmovmsk { .. }
            | Op::Vcmp { .. }
            | Op::Vblendv { .. }
            | Op::Vcvt { .. }
            | Op::Vconvert { .. }
            | Op::Vcompare { .. }
            | Op::Vfused { .. }
            | Op::Mxcsr { .. }
            // x87 (P7.2a)
            | Op::X87 { .. }
            | Op::Fnstsw
            | Op::X87Flags { .. }
            | Op::Fcmov { .. }
    )
}

/// SSE data movement and bitwise templates (x64::vector semantics).
/// Whether the SSE templates (sse) take the instruction at the start of
/// `bytes`, and its length: the forms x64::replay's corpus covers
#[cfg(feature = "ir-test-hooks")]
pub(crate) fn sse_template(bytes: &[u8]) -> Option<usize> {
    let d = decode::decode_with(GuestIp(0x40_0000), ExecutionMode::Long64, |i| {
        bytes.get(i as usize).copied().ok_or(())
    })
    .ok()?;
    sse(&d).map(|_| d.length as usize)
}

/// Compatibility mode's MMX forms (P7.2a; Tier-0's ir::tier0::simd): no
/// prefix, MM registers 0-7
fn mmx(d: &Decoded) -> Option<Op> {
    let code = d.opcode as u8;
    if code == 0x77 {
        return Some(Op::Mmx {
            form: MmxForm::Emms,
        });
    }
    let modrm = d.modrm?;
    let reg = modrm >> 3 & 7;
    let src = match d.rm_register {
        Some(r) => Xmm::Reg(r & 7),
        None => Xmm::Mem(d.address?),
    };
    let rm32 = match d.rm_register {
        Some(r) => Opnd::Reg(register(r, 32, false)),
        None => Opnd::Mem(d.address?),
    };
    let form = match code {
        0x6F => MmxForm::Load { reg, src },
        0x7F => MmxForm::Store { reg, dst: src },
        0x6E => MmxForm::MovdIn { reg, src: rm32 },
        0x7E => MmxForm::MovdOut { reg, dst: rm32 },
        0x71 | 0x72 | 0x73 if d.rm_register.is_some() => {
            if !matches!(reg, 2 | 4 | 6) || code == 0x73 && reg == 4 {
                return None;
            }
            MmxForm::Shift {
                reg: d.rm_register? & 7,
                bits: 16 << (code - 0x71),
                kind: reg,
                count: d.immediate?.value as u8,
            }
        },
        0x70 => MmxForm::Packed {
            op: vec::shuffle(0x0F70, d.immediate?.value as u32),
            reg,
            src,
            bytes: 8,
        },
        _ => MmxForm::Packed {
            op: vec::packed_op(code, true)?,
            reg,
            src,
            bytes: if matches!(code, 0x60..=0x62) { 4 } else { 8 },
        },
    };
    Some(Op::Mmx { form })
}

fn sse(d: &Decoded) -> Option<Op> {
    let xmm_rm = || -> Option<Xmm> {
        match d.rm_register {
            Some(r) => Some(Xmm::Reg(r)),
            None => d.address.map(Xmm::Mem),
        }
    };
    let register = d.reg?;
    let memory = d.rm_register.is_none();
    let full = |aligned: bool, store: bool| -> Option<Op> {
        Some(if store {
            Op::Vmove {
                bits: 128,
                dst: xmm_rm()?,
                src: Xmm::Reg(register),
                aligned,
                zero: false,
                upper: None,
            }
        }
        else {
            Op::Vmove {
                bits: 128,
                dst: Xmm::Reg(register),
                src: xmm_rm()?,
                aligned,
                zero: false,
                upper: None,
            }
        })
    };
    Some(match d.opcode {
        // MOVUPS MOVUPD MOVDQU / MOVAPS MOVAPD MOVDQA
        0x0F10 | 0x660F10 | 0xF30F6F => full(false, false)?,
        0x0F11 | 0x660F11 | 0xF30F7F => full(false, true)?,
        0x0F28 | 0x660F28 | 0x660F6F => full(true, false)?,
        0x0F29 | 0x660F29 | 0x660F7F => full(true, true)?,
        // MOVNTPS MOVNTPD MOVNTDQ (memory only)
        0x0F2B | 0x660F2B | 0x660FE7 if memory => full(true, true)?,
        // MOVSS MOVSD
        0xF30F10 | 0xF20F10 => {
            let bits = if d.opcode == 0xF30F10 { 32 } else { 64 };
            Op::Vmove {
                bits,
                dst: Xmm::Reg(register),
                src: xmm_rm()?,
                aligned: false,
                zero: memory,
                upper: None,
            }
        },
        0xF30F11 | 0xF20F11 => {
            let bits = if d.opcode == 0xF30F11 { 32 } else { 64 };
            Op::Vmove {
                bits,
                dst: xmm_rm()?,
                src: Xmm::Reg(register),
                aligned: false,
                zero: false,
                upper: None,
            }
        },
        // MOVQ xmm, xmm/m64 and MOVQ xmm/m64, xmm: a register destination's upper half is cleared
        0xF30F7E => Op::Vmove {
            bits: 64,
            dst: Xmm::Reg(register),
            src: xmm_rm()?,
            aligned: false,
            zero: true,
            upper: None,
        },
        0x660FD6 => Op::Vmove {
            bits: 64,
            dst: xmm_rm()?,
            src: Xmm::Reg(register),
            aligned: false,
            zero: true,
            upper: None,
        },
        0x660F6E | 0x660F7E => {
            let width = if d.prefixes.w() { 64 } else { 32 };
            let rm = match d.rm_register {
                Some(r) => Opnd::Reg(Reg {
                    index: r,
                    high: false,
                }),
                None => Opnd::Mem(d.address?),
            };
            if d.opcode == 0x660F6E {
                Op::MovdIn {
                    width,
                    dst: register,
                    src: rm,
                }
            }
            else {
                Op::MovdOut {
                    width,
                    dst: rm,
                    src: register,
                }
            }
        },
        // AND ANDN OR XOR
        0x0F54 | 0x660F54 | 0x660FDB | 0x0F55 | 0x660F55 | 0x660FDF | 0x0F56 | 0x660F56
        | 0x660FEB | 0x0F57 | 0x660F57 | 0x660FEF => Op::Vlogic {
            code: logic_code(d.opcode as u8),
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        // ADDPS/PD/SS/SD MULx SUBx DIVx; SQRTx MINx MAXx, RSQRTPS/SS RCPPS/SS
        // (the latter steps without x64_sse_fast_check: Decoder::at)
        0x0F58 | 0x0F59 | 0x0F5C | 0x0F5E | 0x660F58 | 0x660F59 | 0x660F5C | 0x660F5E
        | 0xF30F58 | 0xF30F59 | 0xF30F5C | 0xF30F5E | 0xF20F58 | 0xF20F59 | 0xF20F5C | 0xF20F5E
        | 0x0F51 | 0x660F51 | 0xF30F51 | 0xF20F51 | 0x0F5D | 0x660F5D | 0xF30F5D | 0xF20F5D
        | 0x0F5F | 0x660F5F | 0xF30F5F | 0xF20F5F | 0x0F52 | 0xF30F52 | 0x0F53 | 0xF30F53 => {
            let prefix = d.opcode >> 16;
            Op::Vfp {
                code: d.opcode as u8,
                double: prefix == 0x66 || prefix == 0xF2,
                packed: prefix == 0 || prefix == 0x66,
                dst: register,
                first: register,
                src: xmm_rm()?,
            }
        },
        0x0F2E | 0x0F2F | 0x660F2E | 0x660F2F => Op::Vcompare {
            double: d.opcode >> 16 == 0x66,
            dst: register,
            src: xmm_rm()?,
        },
        // CVTSI2SS/SD, CVT(T)SS2SI/SD2SI, CVTSS2SD, CVTSD2SS
        0xF30F2A | 0xF20F2A | 0xF30F2C | 0xF20F2C | 0xF30F2D | 0xF20F2D | 0xF30F5A | 0xF20F5A => {
            Op::Vconvert {
                convert: conversion(d, d.opcode, d.prefixes.w())?,
                dst: register,
                first: register,
            }
        },
        // (the forms below emit Wasm SIMD: not in the build for engines without it)
        _ if !cfg!(target_feature = "simd128") => return None,
        0x0F5A | 0x660F5A | 0x0F5B | 0xF30FE6 => {
            let (opcode, source) = match d.opcode {
                0x0F5A => (0x5F, 8),    // CVTPS2PD: f64x2.promote_low_f32x4
                0x660F5A => (0x5E, 16), // CVTPD2PS: f32x4.demote_f64x2_zero
                0x0F5B => (0xFA, 16),   // CVTDQ2PS: f32x4.convert_i32x4_s
                _ => (0xFE, 8),         // CVTDQ2PD: f64x2.convert_low_i32x4_s
            };
            Op::Vcvt {
                op: Cvt::Convert {
                    opcode,
                    source,
                    result: 16,
                },
                dst: register,
                src: xmm_rm()?,
            }
        },
        0x660F5B | 0xF30F5B | 0x660FE6 | 0xF20FE6 => Op::Vcvt {
            op: Cvt::Integers {
                double: d.opcode & 0xFF == 0xE6,
                truncate: matches!(d.opcode, 0xF30F5B | 0x660FE6),
            },
            dst: register,
            src: xmm_rm()?,
        },
        0x660F70 | 0xF20F70 | 0xF30F70 | 0x0FC6 | 0x660FC6 => Op::Vpacked {
            op: vec::shuffle(d.opcode, d.immediate?.value as u32 & 0xFF),
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        // PMOVMSKB MOVMSKPS MOVMSKPD r32/r64, xmm
        0x660FD7 | 0x0F50 | 0x660F50 if !memory => Op::Vmovmsk {
            dst: Reg {
                index: register,
                high: false,
            },
            src: d.rm_register?,
            lane: movmsk_lane(d.opcode),
        },
        // CMPPS CMPPD CMPSS CMPSD (imm8[2:0])
        0x0FC2 | 0x660FC2 | 0xF30FC2 | 0xF20FC2 => Op::Vcmp {
            double: matches!(d.opcode >> 16, 0x66 | 0xF2),
            scalar: matches!(d.opcode >> 16, 0xF2 | 0xF3),
            predicate: d.immediate?.value as u8 & 7,
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        // PBLENDVB BLENDVPS BLENDVPD (the mask in XMM0)
        0x660F3810 | 0x660F3814 | 0x660F3815 => Op::Vblendv {
            lane: blendv_lane(d.opcode as u8),
            dst: register,
            first: register,
            src: xmm_rm()?,
            mask: 0,
        },
        0x660F71 | 0x660F72 | 0x660F73 if !memory => {
            let kind = d.modrm? >> 3 & 7;
            let code = d.opcode as u8;
            let bytes = matches!(kind, 3 | 7) && code == 0x73;
            if !(matches!(kind, 2 | 4 | 6) && !(code == 0x73 && kind == 4) || bytes) {
                return None;
            }
            Op::VshiftImm {
                dst: d.rm_register?,
                src: d.rm_register?,
                bits: if bytes { 128 } else { 16 << (code - 0x71) },
                kind,
                count: d.immediate?.value.min(255) as u8,
                wide: false,
            }
        },
        // UNPCKLPS UNPCKHPS UNPCKLPD UNPCKHPD: bit shuffles, those of
        // PUNPCKLDQ PUNPCKHDQ PUNPCKLQDQ PUNPCKHQDQ (an m128, aligned)
        0x0F14 | 0x0F15 | 0x660F14 | 0x660F15 => Op::Vpacked {
            op: Packed::Unpack(
                if d.opcode >> 16 == 0x66 { 8 } else { 4 },
                d.opcode & 0xFF == 0x15,
            ),
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        op if op >> 8 == 0x660F => Op::Vpacked {
            op: vec::packed_op(op as u8, false)?,
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        // PSHUFB, PALIGNR (SSSE3)
        0x660F3800 => Op::Vpacked {
            op: Packed::Swizzle(0x8F),
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        0x660F3A0F => Op::Vpacked {
            op: palignr(d.immediate?.value),
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        0x660F3A60..=0x660F3A63 => Op::Vstrings {
            op: d.opcode as u8,
            imm8: d.immediate?.value as u8,
            wide: d.prefixes.w(),
            dst: register,
            src: xmm_rm()?,
        },
        0x660F3A08..=0x660F3A0B => Op::Vround {
            double: d.opcode & 1 != 0,
            scalar: d.opcode & 2 != 0,
            imm8: d.immediate?.value as u8,
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        op if matches!(op >> 8, 0x660F38 | 0x660F3A) => Op::Vpacked {
            op: sse4_packed(op, d.immediate.map(|i| i.value))?,
            dst: register,
            first: register,
            src: xmm_rm()?,
        },
        _ => return None,
    })
}

/// Op::Vlogic's code of 0F 54-57 and 66 0F DB DF EB EF: AND, ANDN, OR, XOR
fn logic_code(code: u8) -> u8 {
    match code {
        0x54 | 0xDB => 0,
        0x55 | 0xDF => 1,
        0x56 | 0xEB => 2,
        _ => 3,
    }
}
/// Op::Vmovmsk's lane of PMOVMSKB (66 0F D7), MOVMSKPS (0F 50), MOVMSKPD
/// (66 0F 50), by their (legacy) key
fn movmsk_lane(key: u32) -> u8 {
    match key {
        0x660FD7 => 1,
        0x0F50 => 4,
        _ => 8,
    }
}
/// Op::Vblendv's lane of PBLENDVB (0x10), BLENDVPS (0x14), BLENDVPD (0x15)
fn blendv_lane(code: u8) -> u8 {
    match code {
        0x10 => 1,
        0x14 => 4,
        _ => 8,
    }
}
/// Op::Vconvert's conversion of the (legacy) key `key`: CVTSI2SS/SD,
/// CVT(T)SS2SI/SD2SI (64-bit integers with `wide`: REX.W or VEX.W1),
/// CVTSS2SD, CVTSD2SS
fn conversion(d: &Decoded, key: u32, wide: bool) -> Option<Convert> {
    let width = if wide { 64 } else { 32 };
    let xmm_rm = match d.rm_register {
        Some(r) => Xmm::Reg(r),
        None => Xmm::Mem(d.address?),
    };
    Some(match key {
        0xF30F2A | 0xF20F2A => Convert::FromInteger {
            double: key >> 16 == 0xF2,
            width,
            src: match d.rm_register {
                Some(r) => Opnd::Reg(Reg {
                    index: r,
                    high: false,
                }),
                None => Opnd::Mem(d.address?),
            },
        },
        0xF30F2C | 0xF20F2C | 0xF30F2D | 0xF20F2D => Convert::ToInteger {
            double: key >> 16 == 0xF2,
            truncate: key as u8 == 0x2C,
            width,
            src: xmm_rm,
        },
        0xF30F5A | 0xF20F5A => Convert::Precision {
            double: key >> 16 == 0xF3,
            src: xmm_rm,
        },
        _ => return None,
    })
}

/// The template of a VEX.256 form (P6): the moves and VZEROALL, the hot
/// forms of AVX's 256-bit ones; the others step
fn vex256(d: &Decoded) -> Option<Op> {
    use crate::decode_rules::vex;
    let v = d.vex?;
    if d.encoding.vex & vex::L1 == 0 {
        return None;
    }
    let key = crate::cpu::avx::legacy(d.opcode);
    if key == 0x0F77 {
        return Some(Op::Vzeroall);
    }
    let register = Xmm::Reg(d.reg?);
    let rm = match d.rm_register {
        Some(r) => Xmm::Reg(r),
        None => Xmm::Mem(d.address?),
    };
    let memory = d.rm_register.is_none();
    let (dst, src, aligned) = match (v.map, v.pp, key as u8) {
        // VMOVUPS VMOVUPD VMOVDQU, VMOVAPS VMOVAPD VMOVDQA (aligned)
        (1, 0 | 1, 0x10) | (1, 2, 0x6F) => (register, rm, false),
        (1, 0 | 1, 0x28) | (1, 1, 0x6F) => (register, rm, true),
        (1, 0 | 1, 0x11) | (1, 2, 0x7F) => (rm, register, false),
        (1, 0 | 1, 0x29) | (1, 1, 0x7F) => (rm, register, true),
        // VMOVNTPS VMOVNTPD VMOVNTDQ
        (1, 0 | 1, 0x2B) | (1, 1, 0xE7) if memory => (rm, register, true),
        // (the forms below emit Wasm SIMD: not in the build for engines
        // without it)
        _ if !cfg!(target_feature = "simd128") => return None,
        // AVX2 (P7 part 3): VPMOVMSKB; VMOVMSKPS, VMOVMSKPD
        (1, 1, 0xD7) | (1, 0 | 1, 0x50) if !memory => {
            return Some(Op::Vmovmsk256 {
                dst: Reg {
                    index: d.reg?,
                    high: false,
                },
                src: d.rm_register?,
                lane: movmsk_lane(key),
            })
        },
        // VBROADCASTSS, VBROADCASTSD, VPBROADCASTB/W/D/Q
        (2, 1, 0x18 | 0x19 | 0x58 | 0x59 | 0x78 | 0x79) => {
            return Some(Op::Vbroadcast {
                bytes: broadcast_bytes(key as u8),
                dst: d.reg?,
                src: rm,
                wide: true,
            })
        },
        // AVX2's shifts by imm8 on each half (VEX.vvvv the destination, the
        // r/m register the source), VPSHUFD/VPSHUFHW/VPSHUFLW and VPALIGNR
        // on each half (P12: the kernel's SHA-256/512 code with AVX2)
        (1, 1, code @ 0x71..=0x73) if !memory => {
            let kind = d.modrm? >> 3 & 7;
            let bytes = matches!(kind, 3 | 7) && code == 0x73;
            if !(matches!(kind, 2 | 4 | 6) && !(code == 0x73 && kind == 4) || bytes) {
                return None;
            }
            return Some(Op::VshiftImm {
                dst: v.vvvv,
                src: d.rm_register?,
                bits: if bytes { 128 } else { 16 << (code - 0x71) },
                kind,
                count: d.immediate?.value.min(255) as u8,
                wide: true,
            });
        },
        (1, 1..=3, 0x70) => {
            return Some(Op::Vpacked256 {
                op: vec::shuffle(key, d.immediate?.value as u32 & 0xFF),
                dst: d.reg?,
                first: d.reg?,
                src: rm,
            })
        },
        (3, 1, 0x0F) => {
            return Some(Op::Vpacked256 {
                op: palignr(d.immediate?.value),
                dst: d.reg?,
                first: v.vvvv,
                src: rm,
            })
        },
        // VINSERTF128, VINSERTI128 (AVX2 for I), VPERM2F128, VPERM2I128
        (3, 1, 0x18 | 0x38) => {
            return Some(Op::Vinsert128 {
                dst: d.reg?,
                first: v.vvvv,
                src: rm,
                high: d.immediate?.value & 1 != 0,
            })
        },
        (3, 1, 0x06 | 0x46) => {
            return Some(Op::Vperm2 {
                dst: d.reg?,
                first: v.vvvv,
                src: rm,
                imm8: d.immediate?.value as u8,
            })
        },
        // the packed integer forms of 66 0F, VPSHUFB and SSE4.1's of one
        // operation, on each half
        (1, 1, code) => {
            // (with VPAND VPANDN VPOR VPXOR, whose VEX.128 forms are Op::Vlogic)
            let op = vec::packed_op(code, false)?;
            if let Packed::Shift(..) = op {
                return None;
            }
            return Some(Op::Vpacked256 {
                op,
                dst: d.reg?,
                first: v.vvvv,
                src: rm,
            });
        },
        (2, 1, 0x00 | 0x28 | 0x29 | 0x2B | 0x37..=0x40) => {
            return Some(Op::Vpacked256 {
                op: if key as u8 == 0 { Packed::Swizzle(0x8F) } else { sse4_packed(key, None)? },
                dst: d.reg?,
                first: v.vvvv,
                src: rm,
            })
        },
        _ => return None,
    };
    Some(Op::Vmove256 { dst, src, aligned })
}

/// The element of VBROADCASTSS (18), VBROADCASTSD (19), VPBROADCASTD/Q (58,
/// 59), VPBROADCASTB/W (78, 79)
fn broadcast_bytes(code: u8) -> u8 {
    match code {
        0x78 => 1,
        0x79 => 2,
        0x18 | 0x58 => 4,
        _ => 8,
    }
}

/// VEX.W1's 64-bit general-purpose operands (VMOVQ, VCVTSI2SD, BMI, the
/// lengths of VPCMPESTRI): only in 64-bit mode, elsewhere it is W0's
fn gpr_w(d: &Decoded) -> bool { d.vex.is_some_and(|v| v.w) && d.mode == ExecutionMode::Long64 }
/// BMI1 and BMI2's VEX forms (exception type 13: no AVX state; VEX.W1 for
/// 64-bit operands): the hot ones of plan 5.1 and their siblings (MULX,
/// PDEP, PEXT, BEXTR and RORX step)
fn bmi(d: &Decoded) -> Option<Op> {
    let v = d.vex?;
    let width = if gpr_w(d) { 64 } else { 32 };
    let group = d.modrm? >> 3 & 7;
    let dst = register(d.reg?, width, true);
    let other = register(v.vvvv, width, true);
    let src = match d.rm_register {
        Some(r) => Opnd::Reg(register(r, width, true)),
        None => Opnd::Mem(d.address?),
    };
    let (op, dst) = match d.opcode {
        0xC402_00F2 => (BmiOp::Andn, dst),
        0xC402_00F3 => (
            match group {
                1 => BmiOp::Blsr,
                2 => BmiOp::Blsmsk,
                3 => BmiOp::Blsi,
                _ => return None,
            },
            other,
        ),
        0xC402_00F5 => (BmiOp::Bzhi, dst),
        0xC402_01F7 => (BmiOp::Shlx, dst),
        0xC402_02F7 => (BmiOp::Sarx, dst),
        0xC402_03F7 => (BmiOp::Shrx, dst),
        0xC403_03F0 => (BmiOp::Rorx(d.immediate?.value as u8), dst),
        _ => return None,
    };
    Some(Op::Bmi {
        op,
        width,
        dst,
        src,
        other,
    })
}

/// The template of a VEX form (AVX, P5: VEX.128 and VEX.LIG in 64-bit
/// mode; others step) on the SSE ones, as x64::vector's Avx executes it (see
/// Op::Vmove): VEX.vvvv the first source
fn vex(d: &Decoded) -> Option<Op> {
    use crate::decode_rules::vex;
    let v = d.vex?;
    if d.encoding.unimplemented {
        return None;
    }
    if d.encoding.vex & vex::GPR != 0 {
        return bmi(d);
    }
    // (VEX.L1 of other than VEX.LIG rows: the 256-bit forms)
    if v.l && d.encoding.vex & (vex::L0 | vex::L1) != 0 {
        return vex256(d);
    }
    let key = crate::cpu::avx::legacy(d.opcode);
    let code = key as u8;
    if key == 0x0F77 {
        return Some(Op::Vzeroupper);
    }
    let register = d.reg?;
    // (ModRM.reg of the forms it selects)
    let group = d.modrm? >> 3 & 7;
    let first = v.vvvv;
    let memory = d.rm_register.is_none();
    let xmm_rm = || -> Option<Xmm> {
        match d.rm_register {
            Some(r) => Some(Xmm::Reg(r)),
            None => d.address.map(Xmm::Mem),
        }
    };
    let gpr_rm = || -> Option<Opnd> {
        match d.rm_register {
            Some(r) => Some(Opnd::Reg(Reg {
                index: r,
                high: false,
            })),
            None => d.address.map(Opnd::Mem),
        }
    };
    let imm = d.immediate.map(|i| i.value);
    let move_128 = |aligned: bool, store: bool| -> Option<Op> {
        let (dst, src) =
            if store { (xmm_rm()?, Xmm::Reg(register)) } else { (Xmm::Reg(register), xmm_rm()?) };
        Some(Op::Vmove {
            bits: 128,
            dst,
            src,
            aligned,
            zero: false,
            upper: None,
        })
    };
    // FMA (P11): the VEX.128 and scalar forms
    if v.map == 2 && v.pp == 1 && matches!(code, 0x96..=0x9F | 0xA6..=0xAF | 0xB6..=0xBF) {
        return Some(Op::Vfused {
            op: code,
            double: v.w,
            dst: register,
            first,
            src: xmm_rm()?,
        });
    }
    Some(match (v.map, v.pp, code) {
        // VMOVUPS VMOVUPD VMOVDQU, VMOVAPS VMOVAPD VMOVDQA (aligned)
        (1, 0 | 1, 0x10) | (1, 2, 0x6F) => move_128(false, false)?,
        (1, 0 | 1, 0x28) | (1, 1, 0x6F) => move_128(true, false)?,
        (1, 0 | 1, 0x11) | (1, 2, 0x7F) => move_128(false, true)?,
        (1, 0 | 1, 0x29) | (1, 1, 0x7F) => move_128(true, true)?,
        // VMOVNTPS VMOVNTPD VMOVNTDQ
        (1, 0 | 1, 0x2B) | (1, 1, 0xE7) if memory => move_128(true, true)?,
        // VMOVSS VMOVSD: between registers the other bits from VEX.vvvv
        (1, 2 | 3, 0x10 | 0x11) => {
            let store = code == 0x11;
            let (dst, src) = if store {
                (xmm_rm()?, Xmm::Reg(register))
            }
            else {
                (Xmm::Reg(register), xmm_rm()?)
            };
            Op::Vmove {
                bits: if v.pp == 2 { 32 } else { 64 },
                dst,
                src,
                aligned: false,
                zero: memory && !store,
                upper: (!memory).then_some(first),
            }
        },
        // VMOVQ xmm, xmm/m64 and xmm/m64, xmm
        (1, 2, 0x7E) => Op::Vmove {
            bits: 64,
            dst: Xmm::Reg(register),
            src: xmm_rm()?,
            aligned: false,
            zero: true,
            upper: None,
        },
        (1, 1, 0xD6) => Op::Vmove {
            bits: 64,
            dst: xmm_rm()?,
            src: Xmm::Reg(register),
            aligned: false,
            zero: true,
            upper: None,
        },
        // VMOVD/VMOVQ xmm, r/m32/64 and r/m32/64, xmm
        (1, 1, 0x6E) => Op::MovdIn {
            width: if gpr_w(d) { 64 } else { 32 },
            dst: register,
            src: gpr_rm()?,
        },
        (1, 1, 0x7E) => Op::MovdOut {
            width: if gpr_w(d) { 64 } else { 32 },
            dst: gpr_rm()?,
            src: register,
        },
        // VLDMXCSR VSTMXCSR
        (1, 0, 0xAE) if memory && matches!(group, 2 | 3) => Op::Mxcsr {
            load: group == 2,
            address: d.address?,
        },
        // VANDPS/PD VANDNPS/PD VORPS/PD VXORPS/PD, VPAND VPANDN VPOR VPXOR
        (1, 0 | 1, 0x54..=0x57) | (1, 1, 0xDB | 0xDF | 0xEB | 0xEF) => Op::Vlogic {
            code: logic_code(code),
            dst: register,
            first,
            src: xmm_rm()?,
        },
        // VADD VMUL VSUB VDIV VSQRT VMIN VMAX PS/PD/SS/SD, VRSQRT VRCP PS/SS
        // (the latter steps without x64_sse_fast_check: Decoder::at)
        (1, _, 0x58 | 0x59 | 0x5C | 0x5E | 0x51 | 0x5D | 0x5F) | (1, 0 | 2, 0x52 | 0x53) => {
            Op::Vfp {
                code,
                double: v.pp & 1 != 0,
                packed: v.pp < 2,
                dst: register,
                first,
                src: xmm_rm()?,
            }
        },
        // VUCOMISS/SD VCOMISS/SD
        (1, 0 | 1, 0x2E | 0x2F) => Op::Vcompare {
            double: v.pp == 1,
            dst: register,
            src: xmm_rm()?,
        },
        // VCVTSI2SS/SD, VCVT(T)SS2SI/SD2SI (VEX.W1: 64-bit integers), VCVTSS2SD, VCVTSD2SS
        (1, 2 | 3, 0x2A | 0x2C | 0x2D | 0x5A) => Op::Vconvert {
            convert: conversion(d, key, gpr_w(d))?,
            dst: register,
            first,
        },
        // (the forms below emit Wasm SIMD: not in the build for engines without it)
        _ if !cfg!(target_feature = "simd128") => return None,
        // VBROADCASTSS xmm, m32 (AVX2: also xmm), VPBROADCASTB/W/D/Q (AVX2)
        (2, 1, 0x18 | 0x58 | 0x59 | 0x78 | 0x79) => Op::Vbroadcast {
            bytes: broadcast_bytes(code),
            dst: register,
            src: xmm_rm()?,
            wide: false,
        },
        // VPSHUFD VPSHUFHW VPSHUFLW (the source's lanes), VSHUFPS VSHUFPD
        (1, 1..=3, 0x70) | (1, 0 | 1, 0xC6) => Op::Vpacked {
            op: vec::shuffle(key, imm? as u32 & 0xFF),
            dst: register,
            first: if code == 0x70 { register } else { first },
            src: xmm_rm()?,
        },
        // VUNPCKLPS/PD VUNPCKHPS/PD (an m128)
        (1, 0 | 1, 0x14 | 0x15) => Op::Vpacked {
            op: Packed::Unpack(if v.pp == 1 { 8 } else { 4 }, code == 0x15),
            dst: register,
            first,
            src: xmm_rm()?,
        },
        // the shifts by imm8: VEX.vvvv the destination, the r/m register the source
        (1, 1, 0x71..=0x73) if !memory => {
            let kind = group;
            let bytes = matches!(kind, 3 | 7) && code == 0x73;
            if !(matches!(kind, 2 | 4 | 6) && !(code == 0x73 && kind == 4) || bytes) {
                return None;
            }
            Op::VshiftImm {
                dst: first,
                src: d.rm_register?,
                bits: if bytes { 128 } else { 16 << (code - 0x71) },
                kind,
                count: imm?.min(255) as u8,
                wide: false,
            }
        },
        // VPMOVMSKB VMOVMSKPS VMOVMSKPD
        (1, 1, 0xD7) | (1, 0 | 1, 0x50) if !memory => Op::Vmovmsk {
            dst: Reg {
                index: register,
                high: false,
            },
            src: d.rm_register?,
            lane: movmsk_lane(key),
        },
        // VCMPPS/PD/SS/SD (imm8[4:0])
        (1, _, 0xC2) => Op::Vcmp {
            double: v.pp & 1 != 0,
            scalar: v.pp >= 2,
            predicate: imm? as u8 & 31,
            dst: register,
            first,
            src: xmm_rm()?,
        },
        // the packed integer operations of 66 0F
        (1, 1, _) => Op::Vpacked {
            op: vec::packed_op(code, false)?,
            dst: register,
            first,
            src: xmm_rm()?,
        },
        // VBLENDVPS VBLENDVPD VPBLENDVB: the mask register imm8[7:4] (in
        // 32-bit mode imm8[6:4]: bit 7 is ignored)
        (3, 1, 0x4A..=0x4C) => Op::Vblendv {
            lane: [4, 8, 1][(code - 0x4A) as usize],
            dst: register,
            first,
            src: xmm_rm()?,
            mask: (imm? >> 4 & if d.mode == ExecutionMode::Long64 { 15 } else { 7 }) as u8,
        },
        // VROUNDPS/PD (one source), VROUNDSS/SD
        (3, 1, 0x08..=0x0B) => Op::Vround {
            double: code & 1 != 0,
            scalar: code & 2 != 0,
            imm8: imm? as u8,
            dst: register,
            first: if code & 2 != 0 { first } else { register },
            src: xmm_rm()?,
        },
        // VPCMPESTRM/I VPCMPISTRM/I (VEX.W1: the lengths RAX and RDX)
        (3, 1, 0x60..=0x63) => Op::Vstrings {
            op: code,
            imm8: imm? as u8,
            wide: gpr_w(d),
            dst: register,
            src: xmm_rm()?,
        },
        // VPSHUFB VPALIGNR, the SSE4.1 forms of one operation, the blends by imm8
        (2, 1, 0x00) => Op::Vpacked {
            op: Packed::Swizzle(0x8F),
            dst: register,
            first,
            src: xmm_rm()?,
        },
        (3, 1, 0x0F) => Op::Vpacked {
            op: palignr(imm?),
            dst: register,
            first,
            src: xmm_rm()?,
        },
        (2 | 3, 1, _) => Op::Vpacked {
            op: sse4_packed(key, imm)?,
            dst: register,
            first,
            src: xmm_rm()?,
        },
        _ => return None,
    })
}

fn cond_reads(cc: u8) -> u32 {
    match cc >> 1 {
        0 => OF,
        1 => CF,
        2 => ZF,
        3 => CF | ZF,
        4 => SF,
        5 => PF,
        6 => SF | OF,
        _ => ZF | SF | OF,
    }
}
fn shift_count(width: u8, count: u8) -> u8 { count & if width == 64 { 63 } else { 31 } }
/// (read, written) EFLAGS arithmetic bits.
/// How an instruction uses the XMM registers with XMM locals (P4.17)
enum XmmUse {
    /// none
    None,
    /// these (a mask), through the cached accessors, as v128 values
    Hold(u16),
    /// these by lanes in general registers (vfp, scalar moves): held ones
    /// from their locals, the others from memory, nothing loaded for them
    /// (a lane's way between a v128 register and a general one costs more
    /// than its memory)
    Lanes,
    /// some by their memory (other vector code, helpers): the locals are
    /// written back and dropped first
    Memory,
}
/// Whether an instruction may leave its function (retry, step or exit), as
/// all but arithmetic on registers and immediates may (P4.23)
fn may_leave(inst: &Inst) -> bool {
    if inst.straddle.is_some() || inst.span_straddle || inst.locked {
        return true;
    }
    let mem = |o: &Opnd| matches!(o, Opnd::Mem(_));
    match &inst.op {
        Op::Alu { dst, src, .. } | Op::Mov { dst, src, .. } => mem(dst) || mem(src),
        Op::Test { a, b, .. } => mem(a) || mem(b),
        Op::Imul { a, b, .. } => mem(a) || mem(b),
        Op::Extend { src, .. } | Op::Cmov { src, .. } | Op::MulWide { src, .. } => mem(src),
        Op::IncDec { dst, .. }
        | Op::Neg { dst, .. }
        | Op::Not { dst, .. }
        | Op::Shift { dst, .. }
        | Op::Setcc { dst, .. } => mem(dst),
        Op::Lea { .. } | Op::Bswap { .. } | Op::Nop | Op::Lahf | Op::Sahf => false,
        Op::Flag { opcode } => !matches!(opcode, 0xF5 | 0xF8 | 0xF9),
        _ => true,
    }
}
/// The XMM registers an instruction may write (P4.18's register facts end
/// there)
fn xmm_written(op: &Op) -> u16 {
    let bit = |n: u8| 1u16 << n;
    match *op {
        Op::Vmove {
            dst: Xmm::Reg(d), ..
        }
        | Op::Vmove256 {
            dst: Xmm::Reg(d), ..
        } => bit(d),
        Op::Vmove { .. } | Op::Vmove256 { .. } => 0,
        Op::Vfused { dst, .. }
        | Op::Vlogic { dst, .. }
        | Op::Vfp { dst, .. }
        | Op::MovdIn { dst, .. }
        | Op::Vpacked { dst, .. }
        | Op::Vround { dst, .. }
        | Op::VshiftImm { dst, .. }
        | Op::Vpacked256 { dst, .. }
        | Op::Vinsert128 { dst, .. }
        | Op::Vperm2 { dst, .. }
        | Op::Vbroadcast { dst, .. }
        | Op::Vcmp { dst, .. }
        | Op::Vblendv { dst, .. }
        | Op::Vcvt { dst, .. } => bit(dst),
        Op::Vconvert {
            convert: Convert::ToInteger { .. },
            ..
        } => 0,
        Op::Vconvert { dst, .. } => bit(dst),
        // (bits 255:128 only; general registers, flags, MXCSR)
        Op::Vzeroupper
        | Op::MovdOut { .. }
        | Op::Vmovmsk256 { .. }
        | Op::Vmovmsk { .. }
        | Op::Vcompare { .. }
        | Op::Mxcsr { .. } => 0,
        // (PCMPxSTRM: XMM0)
        Op::Vstrings { .. } | Op::Vzeroall | Op::Step | Op::FarCall { .. } | Op::FarRet { .. } => {
            !0
        },
        _ => 0,
    }
}
/// A kept translation (x64_fast_lookup, P4.21; Emitter::lookup_kept): of
/// the operands with base register `base`, of its kind (`write`) and
/// displacement page (kept_page), the page's tag (0 for none) and its delta
struct Kept {
    base: u8,
    write: bool,
    page: i64,
    tag: KeptTag,
    delta: WasmLocal,
}
/// A kept translation's tag: the access cache's (i64), or with
/// x64_compat_tlb the page | 1 << 20, an i32 as the in-page test is, which
/// V8 then compares in one branch (cmp, ccmp)
enum KeptTag {
    Wide(WasmLocalI64),
    Narrow(WasmLocal),
}
impl KeptTag {
    fn wide(&self) -> &WasmLocalI64 {
        match self {
            KeptTag::Wide(l) => l,
            KeptTag::Narrow(_) => unreachable!("an i32 tag"),
        }
    }
    fn narrow(&self) -> &WasmLocal {
        match self {
            KeptTag::Narrow(l) => l,
            KeptTag::Wide(_) => unreachable!("an i64 tag"),
        }
    }
    /// Forget it (INVLPG, steps)
    fn forget(&self, b: &mut WasmBuilder) {
        match self {
            KeptTag::Wide(l) => {
                b.const_i64(0);
                b.set_local_i64(l);
            },
            KeptTag::Narrow(l) => {
                b.const_i32(0);
                b.set_local(l);
            },
        }
    }
}
/// Kept translations per function
const MAX_KEPT: usize = 32;
/// A lazy record's bit: an INC or DEC whose `a` is its result
/// (Emitter::unit_record, pages::x64_page_flags)
pub const RECORD_UNIT: u32 = 1 << 24;
/// The displacement page of an operand `[r + displacement]`, which kept
/// translations tell apart: two arrays a loop reads through one register,
/// as `[EAX + 0x403000]` and `[EAX + 0x423000]`, would otherwise replace
/// each other's translation at every access (the page of displacements
/// within 2 KiB of 0 is 0: a structure's fields, a frame's slots)
fn kept_page(displacement: i64) -> i64 { displacement.wrapping_add(2048) >> 12 }
/// The i8x16.shuffle of a v128 whose low `bytes` come from the first operand
/// and the others from the second
fn low_lanes(bytes: u8) -> [u8; 16] {
    let mut lanes = [0; 16];
    for (k, lane) in lanes.iter_mut().enumerate() {
        *lane = if k < bytes as usize { k as u8 } else { 16 + k as u8 };
    }
    lanes
}
/// On the stack a v128 `other` and a v128 `low`: `other` with its low 32
/// bits replaced by those of `low`, by f32x4 lane moves (bits unchanged, a
/// vector register move; the i8x16.shuffle of low_lanes(4) is four on
/// ARM64)
fn low_single(b: &mut WasmBuilder) {
    b.simd_lane(0x1F, 0); // f32x4.extract_lane
    b.simd_lane(0x20, 0); // f32x4.replace_lane
}
/// The XMM register an instruction overwrites whole, unconditionally and
/// without reading it (XMM locals: Emitter::xmm_claim)
fn xmm_overwritten(op: &Op) -> u16 {
    let names = |x: Xmm, n: u8| matches!(x, Xmm::Reg(r) if r == n);
    match *op {
        Op::Vmove {
            bits: 128,
            dst: Xmm::Reg(d),
            src,
            ..
        } if !names(src, d) => 1 << d,
        // (a scalar load zeroes the rest, a register move zeroes it or takes
        // it from VEX.vvvv)
        Op::Vmove {
            dst: Xmm::Reg(d),
            src: Xmm::Mem(_),
            ..
        } => 1 << d,
        Op::Vmove {
            dst: Xmm::Reg(d),
            src,
            zero,
            upper,
            ..
        } if !names(src, d) && (zero || upper.is_some_and(|first| first != d)) => 1 << d,
        Op::Vlogic {
            dst, first, src, ..
        }
        | Op::Vpacked {
            dst, first, src, ..
        } if dst != first && !names(src, dst) => 1 << dst,
        Op::VshiftImm {
            dst,
            src,
            wide: false,
            ..
        } if dst != src => 1 << dst,
        Op::Vmove256 {
            dst: Xmm::Reg(d),
            src,
            ..
        } if !names(src, d) => 1 << d,
        Op::Vpacked256 {
            dst, first, src, ..
        } if dst != first && !names(src, dst) => 1 << dst,
        Op::Vbroadcast { dst, src, .. } if !names(src, dst) => 1 << dst,
        Op::Vconvert {
            convert: Convert::FromInteger { .. },
            dst,
            first,
        } if dst != first => 1 << dst,
        _ => 0,
    }
}
/// Vector code that reads or writes XMM registers by their memory (not
/// through the cached accessors of P4.17)
fn touches_vectors(op: &Op) -> bool {
    matches!(
        op,
        Op::Vfused { .. }
            | Op::Vfp { .. }
            | Op::Vstrings { .. }
            | Op::Vround { .. }
            | Op::VshiftImm { .. }
            | Op::Vzeroupper
            | Op::Vmove256 { .. }
            | Op::Vzeroall
            | Op::Vpacked256 { .. }
            | Op::Vinsert128 { .. }
            | Op::Vperm2 { .. }
            | Op::Vmovmsk256 { .. }
            | Op::Vbroadcast { .. }
            | Op::Vmovmsk { .. }
            | Op::Vcmp { .. }
            | Op::Vblendv { .. }
            | Op::Vcvt { .. }
            | Op::Vconvert { .. }
            | Op::Vcompare { .. }
    )
}
/// Per instruction of `block`, the XMM registers worth holding (P4.17):
/// those its stretch of the block (between XmmUse::Memory instructions)
/// names twice or more, so a held register saves memory accesses
/// (`fast_check`: CompileEnv::sse_fast_check, see xmm_use)
fn xmm_worth(block: &Block, fast_check: bool) -> Vec<u16> {
    let mut worth = vec![0; block.insts.len()];
    let mut begin = 0;
    for end in 0..=block.insts.len() {
        let memory = end == block.insts.len()
            || matches!(xmm_use(&block.insts[end].op, fast_check), XmmUse::Memory);
        if !memory {
            continue;
        }
        let (mut once, mut twice) = (0u16, 0u16);
        for inst in &block.insts[begin..end] {
            if let XmmUse::Hold(registers) = xmm_use(&inst.op, fast_check) {
                twice |= once & registers;
                once |= registers;
            }
        }
        for w in &mut worth[begin..end] {
            *w = twice;
        }
        begin = end + 1;
    }
    worth
}
/// (`fast_check`: CompileEnv::sse_fast_check, whose Op::Vfp is a template)
/// The 32-bit TLB entry bits that must read TLB_VALID for a read or a
/// write in compatibility mode (Emitter::host_tlb; Tier-0's masks): valid,
/// for a write writable and without code, for user code a user page; not
/// device memory (TLB_IN_MAPPED_RANGE)
fn tlb_read_mask(user: bool) -> i32 {
    0xFFF
        & !TLB_READONLY
        & !TLB_GLOBAL
        & !TLB_HAS_CODE
        & !TLB_IA32E_DATA
        & if user { !0 } else { !TLB_NO_USER }
}
fn tlb_write_mask(user: bool) -> i32 {
    0xFFF & !TLB_GLOBAL & !TLB_IA32E_DATA & if user { !0 } else { !TLB_NO_USER }
}
/// The run of register-only x87 forms (x86tpl::x87run) that `insts`
/// start with, if three or more (Tier-0's threshold) join it; never an
/// instruction that runs into the next page (Inst::straddle checks it)
fn x87_run_at(insts: &[Inst]) -> Option<X87Run> {
    let mut run = X87Run::new();
    while let Some(inst) = insts.get(run.length) {
        let joins = match inst.op {
            Op::X87 {
                opcode,
                modrm,
                io: crate::x86tpl::x87_forms::Io::Stack,
                ..
            } if inst.straddle.is_none() && !inst.span_straddle => run.append(opcode, modrm),
            _ => false,
        };
        if !joins {
            break;
        }
    }
    (run.length >= 3).then_some(run)
}
fn xmm_use(op: &Op, fast_check: bool) -> XmmUse {
    let bit = |n: u8| 1u16 << n;
    let reg = |x: &Xmm| match x {
        Xmm::Reg(n) => bit(*n),
        Xmm::Mem(_) => 0,
    };
    match op {
        Op::Vmove {
            dst,
            src,
            bits: 128,
            ..
        } => XmmUse::Hold(reg(dst) | reg(src)),
        // (the scalar moves as v128 values: v128.load64_zero, shuffles)
        Op::Vmove {
            dst, src, upper, ..
        } => XmmUse::Hold(reg(dst) | reg(src) | upper.map_or(0, bit)),
        Op::Vlogic {
            dst, first, src, ..
        }
        | Op::Vpacked {
            dst, first, src, ..
        } => XmmUse::Hold(bit(*dst) | bit(*first) | reg(src)),
        Op::VshiftImm {
            dst,
            src,
            wide: false,
            ..
        } => XmmUse::Hold(bit(*dst) | bit(*src)),
        // (x86tpl::ops through pagegen_vec::Operands' 128-bit accessors)
        Op::Vfused {
            dst, first, src, ..
        }
        | Op::Vround {
            dst, first, src, ..
        }
        | Op::Vcmp {
            dst, first, src, ..
        } => XmmUse::Hold(bit(*dst) | bit(*first) | reg(src)),
        Op::Vfp {
            dst, first, src, ..
        } if fast_check => XmmUse::Hold(bit(*dst) | bit(*first) | reg(src)),
        Op::Vblendv {
            dst,
            first,
            src,
            mask,
            ..
        } => XmmUse::Hold(bit(*dst) | bit(*first) | reg(src) | bit(*mask)),
        Op::Vbroadcast { dst, src, .. } => XmmUse::Hold(bit(*dst) | reg(src)),
        // (VEX.256 through the templates: the low halves as XMM registers,
        // bits 255:128 in memory, as Tier-0's)
        Op::Vmove256 { dst, src, .. } => XmmUse::Hold(reg(dst) | reg(src)),
        Op::Vpacked256 {
            dst, first, src, ..
        } => XmmUse::Hold(bit(*dst) | bit(*first) | reg(src)),
        Op::Vmovmsk256 { src, .. } => XmmUse::Hold(bit(*src)),
        // (bits 255:128 only)
        Op::Vzeroupper => XmmUse::None,
        Op::Vmovmsk { src, .. } => XmmUse::Hold(bit(*src)),
        Op::Vcvt { dst, src, .. } => XmmUse::Hold(bit(*dst) | reg(src)),
        // (CVTSI2SS/SD's result by a lane insert, vconvert)
        Op::Vconvert {
            convert: Convert::FromInteger { .. },
            dst,
            first,
        } => XmmUse::Hold(bit(*dst) | bit(*first)),
        // (lanes in general registers)
        Op::Vfp { .. }
        | Op::MovdIn { .. }
        | Op::MovdOut { .. }
        | Op::Vcompare { .. }
        | Op::Vconvert { .. } => XmmUse::Lanes,
        _ if touches_vectors(op) => XmmUse::Memory,
        _ => XmmUse::None,
    }
}

/// The structured layout of a page function (P4.16, x64_loops;
/// pagegen::frame::structured) over its static in-page successors; without
/// the switch every block is a unit of the page level.
fn layout(blocks: &[Block], index: &BTreeMap<u16, usize>, loops: bool, span: u64) -> Vec<Unit> {
    if !loops {
        return (0..blocks.len() as u32).map(Unit::Block).collect();
    }
    // static in-page successors (a step and dynamic targets dispatch)
    let successors: Vec<Vec<u32>> = blocks
        .iter()
        .map(|b| {
            let mut out = vec![];
            let mut to = |o: u16| {
                if let Some(&k) = index.get(&o) {
                    out.push(k as u32);
                }
            };
            match b.insts.last().map(|i| i.op) {
                Some(Op::Step) => return out,
                Some(Op::Jcc { target, .. })
                | Some(Op::LoopJump { target, .. })
                | Some(Op::Jmp { target })
                | Some(Op::Call { target }) => {
                    if let Some(o) = in_page(span, target) {
                        to(o);
                    }
                },
                _ => {},
            }
            if let End::Next(o) | End::Shadow(o) = b.end {
                if (o as u64) < span {
                    to(o);
                }
            }
            out
        })
        .collect();
    crate::pagegen::frame::structured(&successors, &|k| blocks[k as usize].start as usize, true)
}

/// The blocks a walk of a callee's code visits at most (return_sites), and
/// the return addresses a RET compares with at most (Emitter::return_guess)
const RETURN_WALK: usize = 256;
const RETURN_GUESSES: usize = 4;

/// Where each RET of the function may return to: per RET's offset, the
/// return addresses of the in-page calls whose callee reaches it, walking
/// the callee's blocks from its entry (over its own calls to their return
/// addresses; RETURN_WALK blocks a call at most). Only a prediction: a RET
/// compares its address with these (Op::Ret), else dispatches.
fn return_sites(
    blocks: &[Block],
    index: &BTreeMap<u16, usize>,
    span: u64,
) -> BTreeMap<u16, Vec<u16>> {
    let mut sites: BTreeMap<u16, Vec<u16>> = BTreeMap::new();
    let block_at = |o: u64| in_page(span, o).and_then(|o| index.get(&o)).copied();
    let mut seen = vec![usize::MAX; blocks.len()];
    for (c, call) in blocks.iter().enumerate() {
        let Some((Op::Call { target }, after)) = call.insts.last().map(|i| (i.op, i.d.next.0))
        else {
            continue;
        };
        let (Some(entry), Some(_)) = (block_at(target), block_at(after))
        else {
            continue;
        };
        let back = after as u16;
        let mut work = vec![entry];
        seen[entry] = c;
        let mut walked = 0;
        while let Some(k) = work.pop() {
            walked += 1;
            if walked > RETURN_WALK {
                break;
            }
            let block = &blocks[k];
            let mut next = |o: u64, work: &mut Vec<usize>| {
                if let Some(j) = block_at(o) {
                    if seen[j] != c {
                        seen[j] = c;
                        work.push(j);
                    }
                }
            };
            match block.insts.last().map(|i| (i.op, i.d.start.0, i.d.next.0)) {
                Some((Op::Ret { .. }, start, _)) => {
                    let to = sites.entry(start as u16).or_default();
                    if !to.contains(&back) {
                        to.push(back);
                    }
                    continue;
                },
                Some((
                    Op::Jcc { target, .. } | Op::LoopJump { target, .. } | Op::Jmp { target },
                    ..,
                )) => next(target, &mut work),
                Some((Op::Call { .. } | Op::CallIndirect { .. }, _, after)) => {
                    next(after, &mut work)
                },
                _ => {},
            }
            if let End::Next(o) | End::Shadow(o) = block.end {
                next(o as u64, &mut work);
            }
        }
    }
    sites
}

/// Whether the instruction at `next`, in STI's interrupt shadow, compiles
/// into STI's block (x64_sti_shadow): it decodes within the page, is no
/// control transfer, step, STI or REP string instruction (block boundaries),
/// and the instruction after it starts a block (a discovery cut short may
/// not have reached STI) or is on the next page
fn shadowed(decoder: &mut Decoder, next: u16, starts: &BTreeSet<u16>) -> bool {
    let span = decoder.span_bytes;
    if next as usize >= span {
        return false;
    }
    let Some((d, op)) = decoder.at(next)
    else {
        return false;
    };
    let after = next as usize + d.length as usize;
    after <= span
        && (after == span || starts.contains(&(after as u16)))
        && !(cfg!(feature = "parallel") && locked_rmw(&d, &op) && !lockable(&op))
        && !matches!(
            op,
            Op::Jcc { .. }
                | Op::LoopJump { .. }
                | Op::LoadSreg { .. }
                | Op::PopSreg { .. }
                | Op::Step
                | Op::Jmp { .. }
                | Op::Call { .. }
                | Op::CallIndirect { .. }
                | Op::Ret { .. }
                | Op::JmpIndirect { .. }
                | Op::FarCall { .. }
                | Op::FarRet { .. }
                | Op::Sti
                | Op::StiShadowed
                | Op::Movs { rep: true, .. }
                | Op::Stos { rep: true, .. }
                | Op::RepCompare { .. }
        )
}
/// The EFLAGS bits an instruction reads and writes; in compatibility mode
/// (P7.2) a multiply writes them all, as the 32-bit interpreter leaves SF,
/// ZF, PF and AF of its result (see Emitter::legacy_mul_flags)
fn effects(op: &Op, compat: bool) -> (u32, u32) {
    if compat && matches!(op, Op::Imul { .. } | Op::MulWide { .. }) {
        return (0, ARITH);
    }
    // (compatibility mode: INC and DEC keep CF, so the producer before them
    // computes it at once instead of leaving it to the record they replace,
    // whose helper call a loop's DEC ECX paid every iteration)
    if compat && matches!(op, Op::IncDec { .. }) {
        return (CF, ARITH & !CF);
    }
    // (compatibility mode: the 32-bit interpreter's BSF and BSR write every
    // flag (CF clear, SF, PF, AF and OF of their lazy record), and SHLD and
    // SHRD with a nonzero count too)
    match (compat, op) {
        (true, Op::BitScan { .. }) => return (0, ARITH),
        // (a zero count keeps every flag: it reads them)
        (true, Op::DoubleShiftCl { .. }) => return (ARITH, ARITH),
        (true, Op::DoubleShift { width, count, .. }) => {
            return if shift_count(*width, *count) == 0 { (0, 0) } else { (0, ARITH) };
        },
        _ => {},
    }
    // (compatibility mode: the 32-bit interpreter's shifts write OF for any
    // count, and SHL, SHR and SAR AF; a zero count changes nothing)
    if let (true, Op::Shift { code, count, .. }) = (compat, op) {
        let writes = if *code <= 1 { CF | OF } else { ARITH };
        return match count {
            Some(count) if count & 31 == 0 => (0, 0),
            Some(_) => (0, writes),
            None => (writes, writes),
        };
    }
    match *op {
        Op::Alu { code: 2 | 3, .. } => (CF, ARITH),
        Op::Alu { .. }
        | Op::Test { .. }
        | Op::Neg { .. }
        | Op::Xadd { .. }
        | Op::Cmpxchg { .. }
        | Op::Popcnt { .. } => (0, ARITH),
        Op::IncDec { .. } => (0, ARITH & !CF),
        Op::Shift {
            code,
            width,
            count: Some(count),
            ..
        } => {
            let raw = shift_count(width, count);
            if raw == 0 {
                (0, 0)
            }
            else {
                let of = if raw == 1 { OF } else { 0 };
                (0, if code >= 4 { CF | PF | ZF | SF | of } else { CF | of })
            }
        },
        // A zero CL count leaves every flag unchanged; rotates only set CF/OF.
        Op::Shift {
            code: 0 | 1,
            count: None,
            ..
        } => (CF | OF, CF | OF),
        Op::Shift { count: None, .. } => (CF | PF | ZF | SF | OF, CF | PF | ZF | SF | OF),
        // (the helper takes and returns all of EFLAGS)
        Op::ShiftCall { .. } => (ARITH, ARITH),
        Op::Imul { .. } | Op::MulWide { .. } => (0, CF | OF),
        Op::Bt { .. } => (0, CF),
        Op::BitScan { .. } => (0, ZF),
        Op::Bmi {
            op: BmiOp::Shlx | BmiOp::Shrx | BmiOp::Sarx | BmiOp::Rorx(_),
            ..
        } => (0, 0),
        Op::Bmi { .. } => (0, ARITH),
        Op::Jcc { cc, .. } | Op::Cmov { cc, .. } | Op::Setcc { cc, .. } => (cond_reads(cc), 0),
        // (LOOPNE and LOOPE)
        Op::LoopJump { kind: 0 | 1, .. } => (ZF, 0),
        // (the helper keeps FLAGS' other bits: it reads them all)
        Op::X87Flags { .. } => (ARITH, ARITH),
        Op::Fcmov { cc, .. } => (cond_reads(cc), 0),
        Op::Pushf => (ARITH, 0),
        Op::Flag { opcode: 0xF5 } => (CF, CF),
        Op::Flag {
            opcode: 0xF8 | 0xF9,
        } => (0, CF),
        Op::Lahf => (SF | ZF | AF | PF | CF, 0),
        Op::DoubleShift { width, count, .. } => {
            let count = shift_count(width, count);
            (
                0,
                if count == 0 { 0 } else { CF | PF | ZF | SF | if count == 1 { OF } else { 0 } },
            )
        },
        Op::CompareExchange { .. } => (0, ZF),
        Op::Sahf => (0, SF | ZF | AF | PF | CF),
        Op::Vcompare { .. } | Op::Vstrings { .. } => (0, ARITH),
        Op::Step | Op::FarCall { .. } | Op::FarRet { .. } => (ARITH, ARITH),
        // (RCX = 0 leaves EFLAGS as they were)
        Op::RepCompare { .. } => (ARITH, ARITH),
        _ => (0, 0),
    }
}

/// A flags producer whose operands a later condition can compare directly.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Known {
    /// fa - fb = fr (CMP, SUB, NEG, CMPXCHG)
    Sub(u8),
    /// fr, with CF = OF = 0 (AND, OR, XOR, TEST)
    Logic(u8),
    /// only ZF, SF, PF of fr (ADD, XADD, INC, DEC)
    Result(u8),
    /// fa, fb the bits of two ordered floats (single, or double when set),
    /// ZF = fa == fb, CF = fa < fb and the rest clear (COMISS, UCOMISS,
    /// COMISD, UCOMISD: Emitter::vcompare refuses NaNs)
    Float(bool),
}
fn producer(op: &Op) -> Option<Known> {
    match *op {
        Op::Alu {
            code: 5 | 7, width, ..
        }
        | Op::Neg { width, .. }
        | Op::Cmpxchg { width, .. } => Some(Known::Sub(width)),
        Op::Alu {
            code: 1 | 4 | 6,
            width,
            ..
        }
        | Op::Test { width, .. } => Some(Known::Logic(width)),
        Op::Alu { code: 0, width, .. } | Op::Xadd { width, .. } | Op::IncDec { width, .. } => {
            Some(Known::Result(width))
        },
        Op::Vcompare { double, .. } => Some(Known::Float(double)),
        _ => None,
    }
}
fn fusable(known: Known, cc: u8) -> bool {
    match known {
        Known::Sub(_) | Known::Logic(_) | Known::Float(_) => true,
        Known::Result(_) => matches!(cc >> 1, 2 | 4 | 5),
    }
}

struct Inst {
    d: Decoded,
    op: Op,
    /// EFLAGS bits the instruction reads (materialized first when pending)
    flags_read: u32,
    /// Liveness input: flags_read, but 0 for fused consumers and steps
    /// (which materialize everything themselves).
    reads: u32,
    writes: u32,
    live_out: u32,
    /// The EFLAGS bits a way out of the function before they are written
    /// again may observe (a retry, step or exit of a later instruction of
    /// the block, or the block's end), as the interpreter then reads them
    /// from memory: P4.23
    exit_live: u32,
    /// Condition from the producer operands instead of EFLAGS.
    fused: Option<Known>,
    /// Producer: keep operands for a fused consumer.
    keep: bool,
    /// An instruction that continues into the next page: its bytes there
    /// (little endian) and how many. It runs only while the next page
    /// fetches as these bytes (x64_page_straddle), else it is stepped.
    straddle: Option<(u64, u8)>,
    /// An instruction that continues into the next page of its span
    /// (P7.3b): it runs only while that page was verified, else it is
    /// stepped
    span_straddle: bool,
    /// A locked read-modify-write of memory (LOCK, XCHG) with cores in
    /// workers: committed with a compare-exchange loop (Emitter::read_dst)
    locked: bool,
    /// A volatile instruction's immediate (CompileEnv::volatile): its offset
    /// in the span, bytes and sign extension; Emitter::read loads it
    dynamic: Option<(u16, u8, bool)>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum End {
    /// Continue at this page offset (4096: the next page).
    Next(u16),
    /// The last instruction transferred control.
    Stop,
    /// Interpret the instruction at this offset (undecodable here).
    Retry(u16),
    /// Step the instruction at this offset in place: it continues into the
    /// next page (or does not decode), so the interpreter fetches it.
    StepAt(u16),
    /// STI's shadow ended (Op::StiShadowed): leave for a deliverable
    /// interrupt, else continue at this offset.
    Shadow(u16),
}
struct Block {
    start: u16,
    insts: Vec<Inst>,
    end: End,
    live_in: u32,
}

/// The offset of `target` (relative to the function's first page) in its
/// `span` bytes
fn is_rep_string(d: &Decoded) -> bool {
    d.prefixes.rep.is_some() && matches!(d.base_opcode(), 0x6C..=0x6F | 0xA4..=0xA7 | 0xAA..=0xAF)
}

/// With cores in workers: a locked read-modify-write of memory.
fn locked_rmw(d: &Decoded, op: &Op) -> bool {
    crate::parallel::active()
        && d.rm_register.is_none()
        && (d.prefixes.lock
            || matches!(
                op,
                Op::Xchg {
                    a: Opnd::Mem(_),
                    ..
                }
            ))
}
/// Templates that commit a locked memory operand with a compare-exchange
/// loop (Emitter::read_dst and write_dst; the rest are stepped).
fn lockable(op: &Op) -> bool {
    match *op {
        Op::Alu {
            code,
            dst: Opnd::Mem(_),
            ..
        } => code != 7,
        Op::IncDec {
            dst: Opnd::Mem(_), ..
        }
        | Op::Neg {
            dst: Opnd::Mem(_), ..
        }
        | Op::Not {
            dst: Opnd::Mem(_), ..
        }
        | Op::Xadd {
            dst: Opnd::Mem(_), ..
        }
        | Op::Cmpxchg {
            dst: Opnd::Mem(_), ..
        }
        | Op::Xchg {
            a: Opnd::Mem(_), ..
        } => true,
        Op::Bt {
            action,
            dst: Opnd::Mem(_),
            ..
        } => action != 0,
        _ => false,
    }
}

pub struct Compiled {
    pub bytes: Vec<u8>,
    /// Block starts, as a bitmap of offsets (64 words a page of the span)
    pub served: Vec<u64>,
    /// The bytes its instructions were decoded from, as a bitmap of offsets
    /// (as `served`): a write elsewhere leaves the code as it is
    /// (pages::dirty_bytes)
    pub code: Vec<u64>,
    /// The offsets its instructions start at, as `served`
    pub starts: Vec<u64>,
    /// The bytes of its volatile instructions it reads where it runs
    /// (CompileEnv::volatile: an immediate, or a stepped instruction), as
    /// `served`
    pub dynamic: Vec<u64>,
    pub instructions: usize,
    pub templated: usize,
    pub blocks: usize,
}

/// Multiplicative hashing of page offsets (the default SipHash showed in
/// compile profiles).
#[derive(Default)]
struct OffsetHasher(u64);
impl std::hash::Hasher for OffsetHasher {
    fn finish(&self) -> u64 { self.0 }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0.rotate_left(8) ^ b as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
        }
    }
    fn write_u16(&mut self, value: u16) {
        self.0 = (value as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}
struct Decoder<'a> {
    bytes: &'a [u8],
    /// the first bytes of the next page as compiled (may be empty)
    next: &'a [u8],
    page: u64,
    cache: HashMap<u16, Option<(Decoded, Op)>, std::hash::BuildHasherDefault<OffsetHasher>>,
    /// The templates of x64_cvt (CompileEnv::cvt): else they are steps
    cvt: bool,
    /// x64_sse_fast_check (CompileEnv::sse_fast_check): else SQRT, RSQRT,
    /// RCP, MIN and MAX are steps
    sse_fast_check: bool,
    /// Long64, or Compatibility32 (CompileEnv::compat), or Protected16
    /// (CompileEnv::prot16)
    mode: ExecutionMode,
    /// CompileEnv::ip_base of 16-bit code: its near branch targets wrap
    ip_base: Option<i32>,
    /// CompileEnv::legacy: legacy_template's forms; operands in GS are steps
    /// (GS is null in XP and Win98, and a null selector's accesses are #GP:
    /// the interpreter's) unless compiled for segment bases, which check
    /// (CompileEnv::segmented)
    legacy: bool,
    segmented: bool,
    /// CompileEnv::stack16
    stack16: bool,
    /// The bytes of the span (CompileEnv::span: 4096 a page)
    span_bytes: usize,
    /// CompileEnv::volatile
    volatile: [u16; MAX_VOLATILE],
}
impl Decoder<'_> {
    fn at(&mut self, offset: u16) -> Option<(Decoded, Op)> {
        let (bytes, next, page, cvt, fast_check, mode, legacy, segmented, span, ip_base) = (
            self.bytes,
            self.next,
            self.page,
            self.cvt,
            self.sse_fast_check,
            self.mode,
            self.legacy,
            self.segmented,
            self.span_bytes,
            self.ip_base,
        );
        let stack16 = self.stack16;
        let volatile = self.volatile.contains(&offset);
        *self.cache.entry(offset).or_insert_with(|| {
            let d = decode::decode_with(GuestIp(page + offset as u64), mode, |i| {
                let at = offset as usize + i as usize;
                if at < span { bytes.get(at) } else { next.get(at - span) }
                    .copied()
                    .ok_or(())
            })
            .ok()?;
            // (at most 8 bytes in the next page: x64_page_straddle compares
            // one word; a span's last page only: a span's straddles step)
            let end = offset as usize + d.length as usize;
            if end > span + 8 || span > PAGE && end > span {
                return None;
            }
            let op = match classify(&d) {
                Op::Vcvt { .. } if !cvt => Op::Step,
                Op::Vfp {
                    code: 0x51..=0x53 | 0x5D | 0x5F,
                    ..
                } if !fast_check => Op::Step,
                // (legacy mode: GS is null in XP and Win98; LOOP, segment
                // loads and others: legacy_template)
                _ if legacy && !segmented && d.address.is_some_and(|a| a.segment == 5) => Op::Step,
                Op::Step if legacy => legacy_template(&d).unwrap_or(Op::Step),
                op => op,
            };
            // (a stack of the other width than the code's, M11: PUSHA and
            // POPA's 32 bytes wrap at SP 0 push by push, ENTER's template is
            // 16-bit code's on a 16-bit stack)
            let op = match op {
                Op::Pusha | Op::Popa if stack16 && !code16(mode) => Op::Step,
                Op::Enter { .. } if !stack16 => Op::Step,
                // (flat legacy-mode code's far transfers step, as in M10)
                Op::FarCall { .. } | Op::FarRet { .. } if !segmented => Op::Step,
                op => op,
            };
            let op = if volatile { volatile_op(&d, op) } else { op };
            let op = match ip_base {
                Some(ip_base) => wrap_ip(op, ip_base),
                None => op,
            };
            Some((d, op))
        })
    }
}

/// Everything besides the page's bytes, entries and name that a page
/// function's bytes depend on (docs/jit-unification-plan.md P2.0):
/// compile_with reads nothing else, so a recorded compilation replays to the
/// same bytes in another build (x64::replay), which pins the addresses below
/// to fixed pseudo values (cross-phase rule 4).
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct CompileEnv {
    /// x64_page_set_bucket_dispatch, x64_page_set_block_count,
    /// x64_page_set_outline
    pub bucket_dispatch: bool,
    pub block_count: bool,
    pub outline: bool,
    /// Leaving the page, tail-call the function serving the new page when
    /// the chaining table (pages::CHAIN) has it
    pub chaining: bool,
    /// FMA through the host's relaxed multiply-adds (helpers::relaxed_fma)
    pub relaxed_fma: bool,
    /// The packed conversions as templates (x64_page_set_cvt)
    pub cvt: bool,
    /// x64_page_set_sti_shadow (Op::StiShadowed)
    pub sti_shadow: bool,
    /// Access cache entries per table (jac::entries, x64_jac_entries; P4.15)
    pub jac_entries: u32,
    /// Loops of the block graph as Wasm loops (x64_page_set_loops; P4.16)
    pub loops: bool,
    /// XMM registers in v128 locals within a block (x64_page_set_xmm_locals;
    /// P4.17)
    pub xmm_locals: bool,
    /// SSE arithmetic through x86tpl::ops::float, refusals exact in place,
    /// MXCSR and SSE checked once per block (x64_page_set_sse_fast_check;
    /// P4.18)
    pub sse_fast_check: bool,
    /// 32-bit integer operations in i32 (x64_page_set_i32_ops; P4.20)
    pub i32_ops: bool,
    /// Inline lookups by the last byte's tag and the host delta
    /// (x64_page_set_fast_lookup; P4.21)
    pub fast_lookup: bool,
    /// The GPRs passed on in x64_chain_gprs when chaining
    /// (x64_page_set_fast_chain; P4.22)
    pub fast_chain: bool,
    /// Eager EFLAGS only where read or observable (x64_page_set_exit_flags;
    /// P4.23)
    pub exit_flags: bool,
    /// The page's code runs in compatibility mode, 32-bit (CS.L = 0, CS.D =
    /// 1; x64_page_compat32, docs/jit-unification-plan.md P7.2), its data
    /// and stack segments flat (pages::run checks it at entry): EIP, ESP and
    /// addresses wrap at 4 GiB, only the GPRs' low halves are read and
    /// written back, as the 32-bit interpreter does under WOW64
    pub compat: bool,
    /// Compatibility mode's memory operands look up the 32-bit TLB
    /// (x64_compat_tlb, Emitter::host_tlb) instead of the access cache
    pub compat_tlb: bool,
    /// The page's 32-bit code runs in legacy protected mode
    /// (x64_page_legacy32, P7.3), as `compat` (pages::legacy_runnable at
    /// entry) with compat_tlb, whose misses translate through the 32-bit
    /// paging (pages::x64_page_access32); FS is not null there, accesses
    /// through GS step (Decoder::legacy)
    pub legacy: bool,
    /// Legacy-mode code compiled for segment bases (P7.2(3),
    /// pages::segmented_runnable): ES, SS and DS operands, stack slots and
    /// string pointers add their segment's base (read at each access, as
    /// Tier-0's functions for other than flat segments do)
    pub segmented: bool,
    /// 16-bit protected-mode code (P7.7, pages::prot16_runnable), as
    /// `segmented` with 16-bit operands, addresses, IP and stack (SP wraps
    /// at 64 KiB, ESP's high half is kept). `ip_base` is the IP of the page's
    /// first byte (its linear address less CS's base): near branch targets
    /// wrap at 64 KiB by it, near calls push IPs, returns and indirect
    /// branches add CS's base back; the prologue leaves at once when CS's
    /// base differs. Real-mode and virtual-8086 code too (P7.8, `mode16`).
    pub prot16: bool,
    pub ip_base: i32,
    pub mode16: Mode16,
    /// The stack is 16-bit (SS.B clear): SP wraps at 64 KiB, ESP's high
    /// half kept. 16-bit code's but on a 32-bit stack, and 32-bit code
    /// compiled for segment bases on a 16-bit stack (Windows 98's thunks,
    /// M11)
    pub stack16: bool,
    /// The consecutive linear pages the function covers (P7.3b; 1 but in
    /// legacy mode): offsets run over all of them, and span_hosts are their
    /// pages' host addresses as compiled (mem8 + physical). Its prologue
    /// finds where it was entered by the 32-bit TLB entry of the entry page,
    /// verifies each page's entry, and control only passes to a page
    /// verified in that activation (else it leaves; a TLB flush or INVLPG
    /// ends activations)
    pub span: u8,
    pub span_hosts: [u32; MAX_SPAN],
    /// Offsets (u16::MAX: none) of instructions of a page that a write
    /// changed while compiled (P7.3, pages::dirty_bytes; a page compiled
    /// alone, span_hosts its host): an immediate source operand loads from
    /// the page where it runs (Inst::dynamic), other forms step. Their bytes
    /// are no code (Compiled::code): rewriting them keeps the function.
    pub volatile: [u16; MAX_VOLATILE],
    /// The page's execution counter, incremented at each entry and dispatch
    /// (outlined, cold compiles with x64_hot_inline: pages::run recompiles
    /// a page whose counter passes HOT_INLINE with inline lookups; P4.14)
    pub counter: Option<u32>,
    /// The exact helpers' operand block (helpers::SSE_FP_OPERANDS: FMA)
    pub sse_fp_operands: u32,
    /// Cores in workers: the kick a page function polls (cpu::core_yield),
    /// the code publication counters (parallel::code::pending_addresses)
    /// and the bounce buffer of unaligned accesses (pages::bounce_address)
    pub core_yield: u32,
    pub pending: [u32; 4],
    pub bounce: u32,
    /// The step ABI's globals (jitrt::step, P5.6)
    pub step: StepAbi,
}
/// x86's step ABI: the exit code in the state block
fn step_abi() -> StepAbi {
    StepAbi {
        exit_code: gp::x64_page_exit as u32,
    }
}
impl CompileEnv {
    /// The running instance's, chaining or not; `outline`: memory accesses
    /// call the module's lookup function (cold compiles; see OUTLINE_ACCESS),
    /// else inline it; `counter`: CompileEnv::counter; `compat`, `legacy`:
    /// CompileEnv::compat and CompileEnv::legacy
    pub fn current(
        chaining: bool,
        outline: bool,
        counter: Option<u32>,
        compat: bool,
        legacy: bool,
        segmented: bool,
        prot16: Option<(i32, Mode16)>,
        stack16: bool,
        span_hosts: &[u32],
    ) -> CompileEnv {
        let mut hosts = [0; MAX_SPAN];
        hosts[..span_hosts.len()].copy_from_slice(span_hosts);
        unsafe {
            CompileEnv {
                bucket_dispatch: BUCKET_DISPATCH,
                block_count: BLOCK_COUNT,
                outline,
                chaining,
                relaxed_fma: super::helpers::relaxed_fma(),
                cvt: CVT,
                sti_shadow: STI_SHADOW,
                jac_entries: jac::entries() as u32,
                loops: LOOPS == 1 || LOOPS == 2 && !outline,
                xmm_locals: XMM_LOCALS,
                sse_fast_check: SSE_FAST_CHECK,
                i32_ops: I32_OPS,
                fast_lookup: FAST_LOOKUP,
                // (the chained GPRs are 64-bit: not for 32-bit code)
                fast_chain: FAST_CHAIN && !compat,
                exit_flags: EXIT_FLAGS,
                compat,
                // (no access cache in legacy mode)
                compat_tlb: compat && (COMPAT_TLB || legacy),
                legacy,
                segmented,
                prot16: prot16.is_some(),
                ip_base: prot16.map_or(0, |p| p.0),
                mode16: prot16.map_or(Mode16::Protected, |p| p.1),
                stack16,
                span: span_hosts.len().max(1) as u8,
                span_hosts: hosts,
                volatile: [u16::MAX; MAX_VOLATILE],
                counter,
                sse_fp_operands: super::helpers::sse_fp_operands(),
                core_yield: &raw const crate::cpu::cpu::core_yield as u32,
                pending: if cfg!(feature = "parallel") {
                    crate::parallel::code::pending_addresses()
                }
                else {
                    [0; 4]
                },
                bounce: super::pages::bounce_address(),
                step: step_abi(),
            }
        }
    }
    /// Replay's: the recorded switches, fixed pseudo addresses
    pub fn replay(
        bucket_dispatch: bool,
        block_count: bool,
        outline: bool,
        chaining: bool,
        relaxed_fma: bool,
        cvt: bool,
        sti_shadow: bool,
        counting: bool,
        jac_entries: u32,
        loops: bool,
        xmm_locals: bool,
        sse_fast_check: bool,
        i32_ops: bool,
        fast_lookup: bool,
        fast_chain: bool,
        exit_flags: bool,
        compat: bool,
        compat_tlb: bool,
        legacy: bool,
        segmented: bool,
        prot16: Option<(i32, Mode16)>,
        stack16: bool,
        span_hosts: &[u32],
    ) -> CompileEnv {
        let mut hosts = [0; MAX_SPAN];
        hosts[..span_hosts.len()].copy_from_slice(span_hosts);
        CompileEnv {
            bucket_dispatch,
            block_count,
            outline,
            chaining,
            relaxed_fma,
            cvt,
            sti_shadow,
            jac_entries,
            loops,
            xmm_locals,
            sse_fast_check,
            i32_ops,
            fast_lookup,
            fast_chain,
            exit_flags,
            compat,
            compat_tlb,
            legacy,
            segmented,
            prot16: prot16.is_some(),
            ip_base: prot16.map_or(0, |p| p.0),
            mode16: prot16.map_or(Mode16::Protected, |p| p.1),
            stack16,
            span: span_hosts.len().max(1) as u8,
            span_hosts: hosts,
            volatile: [u16::MAX; MAX_VOLATILE],
            counter: counting.then_some(0x0000_0E80),
            sse_fp_operands: 0x0000_0E00,
            core_yield: 0x0000_0D00,
            pending: [0x0000_0D10, 0x0000_0D14, 0x0000_0D18, 0x0000_0D1C],
            bounce: 0x0000_0C00,
            step: step_abi(),
        }
    }
}

/// Compile a page of long-mode code (the bytes of its RAM backing page) for
/// the block starts `entries` (with `compat`, of 32-bit compatibility-mode
/// code: CompileEnv::compat). The function is position independent: it runs
/// wherever the page is mapped (gp::x64_page_linear), so every mapping of the
/// same backing page shares it. Addresses below are relative to the page.
/// `chaining`: leaving the page, tail-call the function serving the new page
/// when the chaining table (pages::CHAIN) has it. `next`: the first bytes of
/// the next linear page where it was compiled, for instructions that
/// straddle into it (empty: those are stepped).
pub fn compile(
    bytes: &[u8],
    next: &[u8],
    entries: &[u16],
    chaining: bool,
    outline: bool,
    counter: Option<u32>,
    compat: bool,
    legacy: bool,
    segmented: bool,
    prot16: Option<(i32, Mode16)>,
    stack16: bool,
    span_hosts: &[u32],
    volatile: &[u16],
    name: String,
) -> Option<Compiled> {
    let mut env = CompileEnv::current(
        chaining, outline, counter, compat, legacy, segmented, prot16, stack16, span_hosts,
    );
    env.volatile[..volatile.len()].copy_from_slice(volatile);
    #[cfg(feature = "ir-test-hooks")]
    super::replay::record(&env, bytes, next, entries, &name);
    let compiled = compile_with(&env, bytes, next, entries, name);
    #[cfg(feature = "ir-test-hooks")]
    super::replay::record_output(compiled.as_ref().map_or(&[][..], |c| &c.bytes[..]));
    compiled
}

/// Discover the block starts of the code at `entries` (offsets in the
/// decoder's span; GUESSED ones once the others' code is decoded), and
/// whether MAX_INSTRUCTIONS cut it short
fn discover(decoder: &mut Decoder, entries: &[u16]) -> (BTreeSet<u16>, bool) {
    let span = decoder.span_bytes;
    // Discover block starts: entries, in-page branch targets, return
    // addresses, and the instruction after every step (steps continue by
    // dispatch). Each REP string instruction starts its own block so a
    // step that repeats it dispatches back to it.
    let mut starts = BTreeSet::new();
    let mut work: Vec<u16> = Vec::new();
    for &e in entries {
        if (e as usize) < span && starts.insert(e) {
            work.push(e);
        }
    }
    // (the guesses join once the entries' code is decoded: GUESSED)
    let mut guesses = entries
        .iter()
        .filter(|&&e| e & GUESSED != 0)
        .map(|&e| e & !GUESSED);
    // (the offsets decoded code runs into straight-line)
    let mut runs_into = vec![0u64; span / 64];
    let mut decoded = 0;
    loop {
        while let Some(start) = work.pop() {
            let add = |o: u64, starts: &mut BTreeSet<u16>, work: &mut Vec<u16>| {
                if o < span as u64 && starts.insert(o as u16) {
                    work.push(o as u16);
                }
            };
            let mut o = start;
            loop {
                if o != start && starts.contains(&o) {
                    break;
                }
                decoded += 1;
                if decoded > MAX_INSTRUCTIONS {
                    // Long runs (padding, data): the rest stays interpreted.
                    break;
                }
                let Some((d, op)) = decoder.at(o)
                else {
                    break;
                };
                let next = o as u64 + d.length as u64;
                match op {
                    Op::Jcc { target, .. } | Op::LoopJump { target, .. } => {
                        if let Some(t) = in_page(span as u64, target) {
                            add(t as u64, &mut starts, &mut work);
                        }
                        add(next, &mut starts, &mut work);
                        break;
                    },
                    Op::Jmp { target } | Op::Call { target } => {
                        if let Some(t) = in_page(span as u64, target) {
                            add(t as u64, &mut starts, &mut work);
                        }
                        if matches!(op, Op::Call { .. }) {
                            add(next, &mut starts, &mut work);
                        }
                        break;
                    },
                    Op::CallIndirect { .. } => {
                        add(next, &mut starts, &mut work);
                        break;
                    },
                    Op::Ret { .. } | Op::JmpIndirect { .. } => break,
                    Op::Sti => {
                        if next < span as u64 {
                            if let Some((shadow, _)) = decoder.at(next as u16) {
                                add(next + shadow.length as u64, &mut starts, &mut work);
                            }
                        }
                        break;
                    },
                    Op::Movs { rep: true, .. }
                    | Op::Stos { rep: true, .. }
                    | Op::RepCompare { .. }
                        if o != start =>
                    {
                        add(o as u64, &mut starts, &mut work);
                        break;
                    },
                    Op::Step => {
                        if is_rep_string(&d) && o != start {
                            add(o as u64, &mut starts, &mut work);
                            break;
                        }
                        add(next, &mut starts, &mut work);
                        break;
                    },
                    // (a far call's return comes back here)
                    Op::FarCall { .. } => {
                        add(next, &mut starts, &mut work);
                        break;
                    },
                    Op::FarRet { .. } => break,
                    _ => {},
                }
                if next >= span as u64 {
                    break;
                }
                // (P7.3b: each page of a span starts a block, where control
                // passes between pages)
                if next as usize / PAGE != o as usize / PAGE {
                    add(next, &mut starts, &mut work);
                    break;
                }
                o = next as u16;
                runs_into[o as usize / 64] |= 1 << (o % 64);
            }
        }
        for g in guesses.by_ref() {
            if (g as usize) < span
                && runs_into[g as usize / 64] >> (g % 64) & 1 == 0
                && starts.insert(g)
            {
                work.push(g);
            }
        }
        if work.is_empty() {
            break;
        }
    }
    (starts, decoded > MAX_INSTRUCTIONS)
}

/// compile in `env`
pub fn compile_with(
    env: &CompileEnv,
    bytes: &[u8],
    next: &[u8],
    entries: &[u16],
    name: String,
) -> Option<Compiled> {
    let page = 0;
    // (P7.3b: the bytes of each page of the span, one after the other)
    let span = PAGE * env.span as usize;
    if bytes.len() != span || entries.is_empty() {
        return None;
    }
    let mut decoder = Decoder {
        bytes,
        next,
        page,
        cache: HashMap::default(),
        cvt: env.cvt,
        sse_fast_check: env.sse_fast_check,
        mode: if env.prot16 {
            match env.mode16 {
                Mode16::Protected => ExecutionMode::Protected16,
                Mode16::Real => ExecutionMode::Real,
                Mode16::V86 => ExecutionMode::Vm86,
            }
        }
        else if env.compat {
            ExecutionMode::Compatibility32
        }
        else {
            ExecutionMode::Long64
        },
        legacy: env.legacy,
        segmented: env.segmented,
        stack16: env.stack16,
        ip_base: env.prot16.then_some(env.ip_base),
        span_bytes: PAGE * env.span as usize,
        volatile: env.volatile,
    };
    let (starts, truncated) = discover(&mut decoder, entries);
    // (a span whose code does not fit: pages::compile_mode compiles its
    // page alone, P7.3b)
    if truncated && span > PAGE {
        return None;
    }
    // Blocks, in page order: from each start to its first control transfer,
    // step, or the next start.
    let mut blocks: Vec<Block> = Vec::new();
    let mut total = 0;
    for &start in &starts {
        let mut insts = Vec::new();
        let mut o = start;
        // (the instruction at o is in STI's shadow: Op::StiShadowed)
        let mut after_sti = false;
        let end = loop {
            if o as usize >= span {
                // (past the page end after a straddling instruction)
                break End::Next(o);
            }
            if o != start && starts.contains(&o) && !after_sti {
                break End::Next(o);
            }
            if total >= MAX_INSTRUCTIONS {
                break End::Retry(o);
            }
            total += 1;
            let Some((d, op)) = decoder.at(o)
            else {
                break End::StepAt(o);
            };
            let next = o + d.length as u16;
            let (reads, writes) = effects(&op, env.compat);
            let liveness = if matches!(op, Op::Step) { 0 } else { reads };
            let locked = cfg!(feature = "parallel") && locked_rmw(&d, &op);
            let op = if locked && !lockable(&op) { Op::Step } else { op };
            let straddle = (next as usize > span).then(|| {
                let count = next as usize - span;
                let word = (0..count).fold(0u64, |w, i| w | (decoder.next[i] as u64) << (8 * i));
                (word, count as u8)
            });
            insts.push(Inst {
                d,
                op,
                flags_read: reads,
                reads: liveness,
                writes,
                live_out: ARITH,
                exit_live: ARITH,
                fused: None,
                keep: false,
                straddle,
                span_straddle: o as usize / PAGE != (next as usize - 1) / PAGE
                    && (next as usize) <= span,
                locked: locked && !matches!(op, Op::Step),
                dynamic: match (env.volatile.contains(&o), op, d.immediate) {
                    (true, Op::Step, _) | (false, ..) | (_, _, None) => None,
                    (true, _, Some(i)) => Some((
                        next - i.encoded_bytes as u16,
                        i.encoded_bytes,
                        i.sign_extended,
                    )),
                },
            });
            if after_sti {
                break End::Shadow(next);
            }
            match op {
                Op::Jcc { .. } | Op::LoopJump { .. } | Op::Step => break End::Next(next),
                Op::Sti
                    if env.sti_shadow
                        && total + 1 < MAX_INSTRUCTIONS
                        && shadowed(&mut decoder, next, &starts) =>
                {
                    insts.last_mut().unwrap().op = Op::StiShadowed;
                    after_sti = true;
                },
                Op::Jmp { .. }
                | Op::Call { .. }
                | Op::CallIndirect { .. }
                | Op::Ret { .. }
                | Op::JmpIndirect { .. }
                | Op::FarCall { .. }
                | Op::FarRet { .. }
                | Op::Sti => break End::Stop,
                _ => {},
            }
            o = next;
        };
        // After a truncated discovery a fall-through may not be a start.
        let end = match end {
            End::Next(o) if (o as usize) < span && !starts.contains(&o) => End::Retry(o),
            end => end,
        };
        blocks.push(Block {
            start,
            insts,
            end,
            live_in: ARITH,
        });
    }
    let index: BTreeMap<u16, usize> = blocks
        .iter()
        .enumerate()
        .map(|(i, b)| (b.start, i))
        .collect();
    // Fusion (per block, forward): a condition consumer reads the operands
    // of the last flags producer when no other flags writer intervenes.
    for block in &mut blocks {
        let mut known: Option<(usize, Known)> = None;
        for i in 0..block.insts.len() {
            let op = block.insts[i].op;
            let cc = match op {
                Op::Jcc { cc, .. } | Op::Cmov { cc, .. } | Op::Setcc { cc, .. } => Some(cc),
                _ => None,
            };
            if let (Some(cc), Some((p, k))) = (cc, known) {
                if fusable(k, cc) {
                    block.insts[i].fused = Some(k);
                    block.insts[i].reads = 0;
                    block.insts[i].flags_read = 0;
                    block.insts[p].keep = true;
                }
            }
            if block.insts[i].writes != 0 {
                known = producer(&op).map(|k| (i, k));
            }
        }
    }
    // EFLAGS liveness to a fixpoint (backward over the page's blocks).
    let successors = |blocks: &Vec<Block>, b: usize| -> u32 {
        let block = &blocks[b];
        // Only a performance estimate: anything reading a flag the lazy
        // record still holds materializes it (exits, steps, other code).
        let live = |o: u16| if (o as usize) < span { blocks[index[&o]].live_in } else { 0 };
        let target = |t: u64| {
            in_page(span as u64, t)
                .and_then(|o| index.get(&o))
                .map_or(0, |&i| blocks[i].live_in)
        };
        let last = block.insts.last().map(|i| i.op);
        match (block.end, last) {
            (End::Retry(_) | End::StepAt(_), _) => 0,
            (End::Next(_), Some(Op::Step)) => 0,
            (End::Next(o), Some(Op::Jcc { target: t, .. }))
            | (End::Next(o), Some(Op::LoopJump { target: t, .. })) => live(o) | target(t),
            (End::Next(o), _) | (End::Shadow(o), _) => live(o),
            (End::Stop, Some(Op::Jmp { target: t }))
            | (End::Stop, Some(Op::Call { target: t })) => target(t),
            (End::Stop, _) => 0,
        }
    };
    loop {
        let mut changed = false;
        for b in (0..blocks.len()).rev() {
            let mut live = successors(&blocks, b);
            let block = &mut blocks[b];
            for inst in block.insts.iter_mut().rev() {
                inst.live_out = live;
                live = inst.reads | (live & !inst.writes);
            }
            if live != block.live_in {
                block.live_in = live;
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
    // (P4.23) what ways out of the function may observe, backward over each
    // block: its end may leave, as may any instruction may_leave admits
    for block in blocks.iter_mut() {
        let mut live = ARITH;
        for inst in block.insts.iter_mut().rev() {
            inst.exit_live = live;
            live = if may_leave(inst) { ARITH } else { live & !inst.writes };
        }
    }
    let mut served = vec![0u64; span / 64];
    for &s in &starts {
        served[s as usize / 64] |= 1 << (s % 64);
    }
    // (an instruction's bytes past the span are checked where it runs:
    // Inst::straddle)
    // A volatile instruction's immediate (or, stepped, all of it) is none:
    // CompileEnv::volatile.
    let mut code = vec![0u64; span / 64];
    let mut instruction_starts = vec![0u64; span / 64];
    let mut dynamic = vec![0u64; span / 64];
    for block in &blocks {
        let mut o = block.start as usize;
        for inst in &block.insts {
            instruction_starts[o / 64] |= 1 << (o % 64);
            let (from, to) = match inst.dynamic {
                Some((at, bytes, _)) => (at as usize, at as usize + bytes as usize),
                None if env.volatile.contains(&(o as u16)) => (o, o + inst.d.length as usize),
                None => (o, o),
            };
            for b in o..(o + inst.d.length as usize).min(span) {
                if !(from..to).contains(&b) {
                    code[b / 64] |= 1 << (b % 64);
                }
                else {
                    dynamic[b / 64] |= 1 << (b % 64);
                }
            }
            o += inst.d.length as usize;
        }
    }
    let instructions = blocks.iter().map(|b| b.insts.len()).sum();
    let templated = blocks
        .iter()
        .flat_map(|b| &b.insts)
        .filter(|i| !matches!(i.op, Op::Step))
        .count();
    let bytes = Emitter::emit(&blocks, &index, env, name);
    Some(Compiled {
        bytes,
        served,
        code,
        starts: instruction_starts,
        dynamic,
        instructions,
        templated,
        blocks: blocks.len(),
    })
}

// i64 locals (0..16 are the GPRs)
const RIP: usize = 16;
const EP: usize = 17;
const FA: usize = 18;
const FB: usize = 19;
const FR: usize = 20;
const TA: usize = 21;
const TB: usize = 22;
const TR: usize = 23;
const TV: usize = 24;
const ADDR: usize = 25;
const TAG: usize = 26;
const TC: usize = 27;
/// scratch of flag and condition computations only
const TX: usize = 28;
/// linear address of the page
const BASE: usize = 29;
/// results of the two halves of an SSE floating point operation (vfp)
const FP0: usize = 30;
const FP1: usize = 31;
/// the value a locked instruction read (read_dst), for its compare-exchange
const OLD: usize = 32;
/// a value being stored (store: cores in workers)
const SV: usize = 33;
const LOCALS64: usize = 34;
// i32 locals
const FL: usize = 0;
const N: usize = 1;
const K: usize = 2;
const JAC: usize = 3;
const ENT: usize = 4;
const OFF: usize = 5;
const HOST: usize = 6;
const HH: usize = 7;
const ST: usize = 8;
const COND: usize = 9;
/// Lazy flags record: kind << 16 | pending EFLAGS bits (operands in FA/FB).
const FK: usize = 10;
/// ADC/SBB carry input
const CI: usize = 11;
/// REP MOVS source host address (host() clobbers HH)
const SRC: usize = 12;
/// an SSE arithmetic lane was inexact (vfp)
const INX: usize = 13;
/// the host address of a store (store, load_any: cores in workers)
const SH: usize = 14;
const LOCALS32: usize = 15;
const RAX: Reg = Reg {
    index: 0,
    high: false,
};
const RDX: Reg = Reg {
    index: 2,
    high: false,
};
const AH: Reg = Reg {
    index: 0,
    high: true,
};

struct Emitter<'a> {
    b: WasmBuilder,
    /// the function's blocks (PageEmitter::emit_block)
    blocks: &'a [Block],
    v: Vec<WasmLocalI64>,
    w: Vec<WasmLocal>,
    budget: WasmLocal,
    frame: Option<Frame>,
    /// the structured layout's levels (P4.16): the page level (its loop is
    /// Frame::dispatch), then each loop being emitted
    levels: Vec<Level>,
    /// per RET, the return addresses it is predicted to return to
    /// (return_sites)
    returns: BTreeMap<u16, Vec<u16>>,
    /// XMM registers in v128 locals (CompileEnv::xmm_locals): the locals,
    /// the registers held in them, those written since they were loaded
    xmm_locals: [Option<WasmLocalV128>; 16],
    xmm_held: u16,
    xmm_dirty: u16,
    /// the registers worth holding for the instruction being emitted: used
    /// twice or more in its stretch of the block (between instructions that
    /// read them from memory)
    xmm_worth: u16,
    /// the vector checks the block passed (VECTOR_SSE, VECTOR_VEX,
    /// VECTOR_X87): P4.18
    vector_checked: u8,
    /// per XMM register, the lanes known to be neither NaN nor denormal
    /// (x86tpl::vec::clean_bits; P4.18, as Tier-0's xmm_clean): from where
    /// the block learns them to the register's next write
    xmm_clean: [u8; 16],
    /// x64_fast_lookup (P4.21): per base register, kind and displacement
    /// page (Kept), the translation of an operand `[r + displacement]` (or a
    /// stack operation, r = RSP) the block's inline lookups found last (see
    /// host_fast and host_tlb; made when first used, MAX_KEPT at most). The
    /// base register of the operand being looked up,
    /// if it has no index, and its displacement's page (kept_page).
    lookup_kept: Vec<Kept>,
    lookup_base: Option<(u8, i64)>,
    /// The start of the instruction being emitted (a segment's null check
    /// retries it, P7.2(3))
    inst_start: u64,
    /// A span's pages verified at entry, a bit each (P7.3b, span_entry),
    /// and the page of the block being emitted
    verified: Option<WasmLocal>,
    current_page: u16,
    /// (the kept translations the current block has set: host_fast,
    /// host_tlb)
    kept_set: u64,
    /// the YMM registers whose bits 255:128 the block zeroed and nothing
    /// wrote since (ymm_zero once per block, as Tier-0's)
    ymm_zeroed: u16,
    /// the module's access-cache lookup function (see access_function)
    access: Option<u32>,
    /// the compare-exchange loop of a locked instruction (read_dst)
    lock_loop: Option<Label>,
    /// compatibility and legacy mode (P7.2, M8): the 32-bit interpreter's
    /// last_op1, which its ADD, ADC, SUB, SBB, CMP, INC and DEC (NEG, XADD,
    /// CMPXCHG, CMPS and SCAS through them) set to their first operand, and
    /// from which a later MUL's AF follows (cpu::misc_instr::getaf): it
    /// stays in the CPU state, written where the operations set it and read
    /// where flags take it, as Tier-0 keeps it (no register for it across
    /// loops and dispatch; M9 for compatibility mode, which kept it in a
    /// local)
    last_op1_memory: bool,
    /// compatibility mode's x87 forms (P7.2a): their operand words (low,
    /// high), made when first used
    x87_words: Option<(WasmLocal, WasmLocal)>,
    /// and TOP, the tags and the shadow cache's VALID/DIRTY masks in
    /// function-wide locals while the runtime flag x87_is_open is set (then
    /// the CPU state is behind), as Tier-0's x87_open/x87_close: opened by
    /// an x87 form, kept open across the function's blocks and loops,
    /// closed before the helpers that read or change the x87 state and at
    /// every way out of the function (exit, chain, step)
    x87_cache: Option<X87Cache>,
    x87_is_open: Option<WasmLocal>,
    /// the emitted code has opened the x87 cache on every path to here
    x87_known_open: bool,
    /// CompileEnv::compat_tlb: the 32-bit TLB's address and the access
    /// masks of the activation's CPL (read, write), set by the prologue
    tlb: Option<[WasmLocal; 3]>,
    /// what else the bytes depend on
    env: CompileEnv,
}

/// The x86 page tier in the neutral skeleton (pagegen::frame, P5.9)
impl PageEmitter for Emitter<'_> {
    fn b(&mut self) -> &mut WasmBuilder { &mut self.b }
    fn frame(&self) -> Frame { self.frame.unwrap() }
    fn set_frame(&mut self, frame: Frame) { self.frame = Some(frame) }
    fn levels(&mut self) -> &mut Vec<Level> { &mut self.levels }
    fn levels_ref(&self) -> &[Level] { &self.levels }
    fn span_bytes(&self) -> u64 { Emitter::span_bytes(self) }
    fn pc_offset(&mut self) { self.rip_offset() }
    fn tee_offset(&mut self) { self.ti(OFF) }
    fn get_offset(&mut self) { self.gi(OFF) }
    fn head(&mut self) { Emitter::head(self) }
    fn emit_block(&mut self, k: u32, index: &BTreeMap<u16, usize>) {
        let blocks = self.blocks;
        self.block(&blocks[k as usize], index)
    }
    fn block_start(&self, k: u32) -> u16 { self.blocks[k as usize].start }
    fn leave_to(&mut self, label: Label, target: u64) { Emitter::leave_to(self, label, target) }
    fn before_branch(&mut self) { self.xmm_writeback() }
    fn span_check(&mut self, target: u64) { Emitter::span_check(self, target) }
    /// (P7.3: in the 32-bit modes a loop of its header alone needs no
    /// dispatch on RIP each iteration, 706.memory)
    fn direct_loops(&self) -> bool { self.env.compat }
    fn entry_checks(&mut self, exit: Label) {
        if self.env.span > 1 {
            self.span_entry(exit);
        }
        if self.env.prot16 {
            self.prot16_entry(exit);
        }
    }
    fn bounds(&mut self, leave: Label) {
        self.g(RIP);
        self.g(BASE);
        self.b.sub_i64();
        self.c64(Emitter::span_bytes(self));
        self.b.op(op::OP_I64GEU);
        self.b.br_if(leave);
        self.span_check_rip();
    }
    /// Not a block start: step it in place, unless the page is due for a
    /// recompile (pages::x64_page_unserved)
    fn unknown_offset(&mut self) {
        self.g(RIP);
        self.b.call_signature(
            "x64_page_unserved",
            Signature::new(&[WasmType::I64], &[WasmType::I32]),
        );
        self.b.eqz_i32();
        self.b.br_if(self.f().step);
        self.set_exit(EXIT_UNKNOWN);
        self.b.br(self.f().exit);
    }
    fn before_units(&mut self) {
        if self
            .blocks
            .iter()
            .any(|b| b.insts.iter().any(|i| matches!(i.op, Op::X87 { .. })))
        {
            self.x87_cache_locals();
        }
    }
    fn step_tail(&mut self) { self.step_code() }
    fn retry_tail(&mut self) {
        self.set_exit(EXIT_RETRY);
        self.b.br(self.f().exit);
    }
    fn leave_tail(&mut self) {
        self.x87_close();
        if self.env.chaining {
            self.chain();
        }
    }
    fn exit_tail(&mut self) {
        self.x87_close();
        self.materialize_if(ARITH);
        self.writeback();
        self.gi(N);
    }
    fn note_size(&mut self, what: &str, bytes: usize) { size_note(what.into(), bytes) }
    fn lookup_function(&mut self) -> u32 { self.access_function() }
}

/// The operand words of an x87 form inlined by x86tpl::x87, and the
/// block's x87 cache (P7.2a)
struct X87Operands<'a> {
    b: &'a mut WasmBuilder,
    words: [&'a WasmLocal; 2],
    cache: Option<X87Cache>,
}
impl X87Words for X87Operands<'_> {
    fn w(&mut self) -> &mut WasmBuilder { self.b }
    fn input(&mut self, k: usize) { self.b.get_local(self.words[k]) }
    fn output(&mut self, k: usize) { self.b.set_local(self.words[k]) }
    fn cache(&mut self) -> Option<X87Cache> { self.cache.as_ref().map(X87Cache::unsafe_clone) }
}
/// Emitter::vector_checked: the legacy SSE check passed, the VEX one passed
const VECTOR_SSE: u8 = 1;
const VECTOR_VEX: u8 = 2;
/// (and the x87 one: CR0.EM and TS clear, P7.2a)
const VECTOR_X87: u8 = 4;
/// The budget's low bits (Emitter::budget_flags): the vector checks that
/// pass (VECTOR_SSE, VECTOR_VEX, VECTOR_X87) and BUDGET_MXCSR, MXCSR
/// admitting native float results
const BUDGET_MXCSR: i32 = 8;
const BUDGET_FLAGS: i32 = 15;
/// Dispatch through a table of 16-byte buckets and compares instead of a
/// page-sized table (x64_page_set_bucket_dispatch).
static mut BUCKET_DISPATCH: bool = true;
#[no_mangle]
pub fn x64_page_set_bucket_dispatch(enabled: bool) { unsafe { BUCKET_DISPATCH = enabled } }
/// Native instructions are counted once per block at its entry instead of
/// after each instruction (smaller code; N is then an upper bound when a
/// block is left early). x64_page_set_block_count.
static mut BLOCK_COUNT: bool = true;
#[no_mangle]
pub fn x64_page_set_block_count(enabled: bool) { unsafe { BLOCK_COUNT = enabled } }
/// Memory accesses call one small lookup function per module instead of
/// inlining the access cache lookup at each (page functions shrink by a
/// third; engines compile them that much faster). x64_page_set_outline:
/// cold compiles; hot pages are compiled inline with x64_hot_inline (P4.14).
static mut OUTLINE_ACCESS: bool = true;
#[no_mangle]
pub fn x64_page_set_outline(enabled: bool) { unsafe { OUTLINE_ACCESS = enabled } }
pub fn outline_access() -> bool { unsafe { OUTLINE_ACCESS } }
/// The values of the three switches above (crate::jit_switches)
/// The packed conversions (Op::Vcvt) as x86tpl::ops templates, else steps
/// (docs/jit-unification-plan.md P2.5, on since P2.8). x64_page_set_cvt.
static mut CVT: bool = true;
#[no_mangle]
pub fn x64_page_set_cvt(enabled: bool) { unsafe { CVT = enabled } }
/// STI and the instruction in its shadow compiled together, then a check
/// for a deliverable interrupt (docs/jit-unification-plan.md P4.5d, on since
/// its F gate), else STI leaves the function. x64_page_set_sti_shadow.
static mut STI_SHADOW: bool = true;
#[no_mangle]
pub fn x64_page_set_sti_shadow(enabled: bool) { unsafe { STI_SHADOW = enabled } }
/// Loops of a page function's block graph as Wasm loops whose back edges
/// skip the page dispatch (docs/jit-unification-plan.md P4.16): 1 in every
/// compile, 2 (the default since M5) only with inline lookups (hot
/// recompiles, x64_hot_inline; loops cost TurboFan an eighth more time,
/// which cold code that V8 seldom optimizes need not pay).
/// x64_page_set_loops sets 0 or 1.
static mut LOOPS: u32 = 2;
#[no_mangle]
pub fn x64_page_set_loops(enabled: bool) { unsafe { LOOPS = enabled as u32 } }
pub fn set_loops(mode: u32) -> bool {
    mode <= 2 && {
        unsafe { LOOPS = mode };
        true
    }
}
/// XMM registers in v128 locals within a block: loaded at the first
/// instruction that uses them, written back before anything that leaves the
/// block or reads them from memory (docs/jit-unification-plan.md P4.17).
/// x64_page_set_xmm_locals.
static mut XMM_LOCALS: bool = true;
#[no_mangle]
pub fn x64_page_set_xmm_locals(enabled: bool) { unsafe { XMM_LOCALS = enabled } }
/// SSE arithmetic (Op::Vfp, with SQRT, MIN, MAX, RSQRT and RCP) through
/// x86tpl::ops::float: the exactness check only while MXCSR.PE is clear,
/// v128 masks, refused instructions exact in place (ir_t0_sse_fp, also for
/// CMPPS and kin), MXCSR's condition and the SSE check once per block
/// (docs/jit-unification-plan.md P4.18). x64_page_set_sse_fast_check.
static mut SSE_FAST_CHECK: bool = true;
#[no_mangle]
pub fn x64_page_set_sse_fast_check(enabled: bool) { unsafe { SSE_FAST_CHECK = enabled } }
/// 32-bit integer operations in i32 (docs/jit-unification-plan.md P4.20):
/// a 32-bit register reads as i64.extend_i32_u(i32.wrap_i64), the operation
/// is an i32 one, its result zero-extended. Engines then emit one 32-bit
/// instruction where masks around a 64-bit one cost three more (V8 does not
/// narrow those). x64_page_set_i32_ops.
static mut I32_OPS: bool = true;
#[no_mangle]
pub fn x64_page_set_i32_ops(enabled: bool) { unsafe { I32_OPS = enabled } }
/// Inline access cache lookups that compare the tag of the operand's last
/// byte (a page crossing misses, no offset compare) and add the entry's host
/// delta to the address (jac::Entry::delta), as QEMU's softmmu does
/// (docs/jit-unification-plan.md P4.21). x64_page_set_fast_lookup.
static mut FAST_LOOKUP: bool = true;
#[no_mangle]
pub fn x64_page_set_fast_lookup(enabled: bool) { unsafe { FAST_LOOKUP = enabled } }
/// A chaining page function passes the GPRs on in gp::x64_chain_gprs, 64
/// bits each, and tells the function it tail-calls by bit 31 of its budget
/// argument (budgets are below it), which then loads them from there: a
/// third of the stores and loads of the GPRs' split halves
/// (docs/jit-unification-plan.md P4.22). Functions compiled with and
/// without it must not chain to each other: the switch resets the page
/// tier. x64_page_set_fast_chain.
static mut FAST_CHAIN: bool = false;
#[no_mangle]
pub fn x64_page_set_fast_chain(enabled: bool) { unsafe { FAST_CHAIN = enabled } }
/// The budget argument's bit for x64_chain_gprs (FAST_CHAIN)
const CHAINED_GPRS: i32 = 1 << 31;
/// Shifts, rotates and IMUL/MUL compute their EFLAGS (they keep no lazy
/// record) only where something reads them or may observe them: a later
/// instruction before they are written again, or a way out of the function
/// (Inst::exit_live), not every time (docs/jit-unification-plan.md P4.23).
/// x64_page_set_exit_flags.
static mut EXIT_FLAGS: bool = true;
#[no_mangle]
pub fn x64_page_set_exit_flags(enabled: bool) { unsafe { EXIT_FLAGS = enabled } }
/// Compatibility mode's memory operands as Tier-0 reads them: inline in the
/// 32-bit TLB that x64 translations fill in compatibility mode
/// (cpu::fill_ia32e_tlb), not in the access cache
/// (docs/jit-unification-plan.md P7.2). x64_page_set_compat_tlb.
static mut COMPAT_TLB: bool = true;
#[no_mangle]
pub fn x64_page_set_compat_tlb(enabled: bool) { unsafe { COMPAT_TLB = enabled } }
pub fn compat_tlb() -> bool { unsafe { COMPAT_TLB } }

pub fn switch_value(name: &str) -> Option<u32> {
    unsafe {
        Some(match name {
            "x64_cvt" => CVT as u32,
            "x64_sti_shadow" => STI_SHADOW as u32,
            "x64_loops" => LOOPS,
            "x64_xmm_locals" => XMM_LOCALS as u32,
            "x64_sse_fast_check" => SSE_FAST_CHECK as u32,
            "x64_i32_ops" => I32_OPS as u32,
            "x64_fast_lookup" => FAST_LOOKUP as u32,
            "x64_fast_chain" => FAST_CHAIN as u32,
            "x64_exit_flags" => EXIT_FLAGS as u32,
            "x64_compat_tlb" => COMPAT_TLB as u32,
            "x64_bucket_dispatch" => BUCKET_DISPATCH as u32,
            "x64_block_count" => BLOCK_COUNT as u32,
            "x64_outline" => OUTLINE_ACCESS as u32,
            _ => return None,
        })
    }
}

impl Emitter<'_> {
    fn emit(
        blocks: &[Block],
        index: &BTreeMap<u16, usize>,
        env: &CompileEnv,
        name: String,
    ) -> Vec<u8> {
        let mut b = WasmBuilder::new();
        b.set_entry_result();
        b.set_function_name(name);
        let budget = b.arg_local_initial_state.unsafe_clone();
        let v = (0..LOCALS64)
            .map(|_| b.declare_zeroed_local_i64())
            .collect();
        let w = (0..LOCALS32).map(|_| b.declare_zeroed_local()).collect();
        let verified = (env.span > 1).then(|| b.declare_zeroed_local());

        let mut e = Emitter {
            b,
            blocks,
            v,
            w,
            budget,
            frame: None,
            levels: Vec::new(),
            returns: return_sites(blocks, index, PAGE as u64 * env.span as u64),
            xmm_locals: Default::default(),
            xmm_held: 0,
            xmm_dirty: 0,
            xmm_worth: 0,
            vector_checked: 0,
            xmm_clean: [0; 16],
            lookup_kept: Vec::new(),
            lookup_base: None,
            inst_start: 0,
            verified,
            current_page: 0,
            kept_set: 0,
            ymm_zeroed: 0,
            access: None,
            lock_loop: None,
            last_op1_memory: env.compat,
            x87_words: None,
            x87_cache: None,
            x87_is_open: None,
            x87_known_open: false,
            tlb: None,
            env: *env,
        };
        let mark = e.b.body_len();
        e.prologue();
        size_note("[prologue]".into(), e.b.body_len() - mark);
        // The structured layout (P4.16) and the page dispatch's kind:
        // compatibility mode's a table over the span of the block starts
        // when that is small, as Tier-0 dispatched (a loop through a switch
        // or a call's return is no loop of the static layout and each of its
        // rounds dispatches here; compare chains in a bucket mispredict
        // there, P7.2), else buckets (x64_page_set_bucket_dispatch) or a
        // table over the page
        let units = layout(blocks, index, e.env.loops, e.span_bytes());
        let (low, high) = (
            index.keys().next().copied().unwrap_or(0),
            index.keys().next_back().copied().unwrap_or(0),
        );
        let kind = if e.env.compat && (high - low) as usize <= SPAN_TABLE {
            DispatchKind::SpanTable { low, high }
        }
        else if e.env.bucket_dispatch {
            DispatchKind::Buckets
        }
        else {
            DispatchKind::Full
        };
        e.page(&units, blocks.len(), index, kind);
        let Emitter {
            mut b,
            v,
            w,
            budget,
            xmm_locals,
            lookup_kept,
            x87_words,
            x87_cache,
            x87_is_open,
            tlb,
            verified,
            env,
            ..
        } = e;
        for l in v {
            b.free_local_i64(l);
        }
        for Kept { tag, delta, .. } in lookup_kept {
            match tag {
                KeptTag::Wide(l) => b.free_local_i64(l),
                KeptTag::Narrow(l) => b.free_local(l),
            }
            b.free_local(delta);
        }
        for l in w {
            b.free_local(l);
        }
        if let Some((low, high)) = x87_words {
            b.free_local(low);
            b.free_local(high);
        }
        if let Some(c) = x87_cache {
            for l in [c.top, c.tags, c.valid, c.dirty]
                .into_iter()
                .chain(x87_is_open)
            {
                b.free_local(l);
            }
        }
        for l in xmm_locals.into_iter().flatten() {
            b.free_local_v128(l);
        }
        // (32-bit modes' write mask is their read mask's local: once)
        for (k, l) in tlb.into_iter().flatten().enumerate() {
            if env.compat && k == 2 {
                std::mem::forget(l);
            }
            else {
                b.free_local(l);
            }
        }
        if let Some(l) = verified {
            b.free_local(l);
        }
        std::mem::forget(budget);
        b.finish();
        b.output().to_vec()
    }
    fn f(&self) -> Frame { self.frame.unwrap() }
    /// The bytes the function's offsets cover (CompileEnv::span)
    fn span_bytes(&self) -> u64 { PAGE as u64 * self.env.span as u64 }
    /// Push the i32 offset of RIP in the function's pages (in a span from
    /// BASE, its first page)
    fn rip_offset(&mut self) {
        self.g(RIP);
        if self.env.span > 1 {
            self.g(BASE);
            self.b.sub_i64();
            self.b.wrap_i64_to_i32();
        }
        else {
            self.b.wrap_i64_to_i32();
            self.c32(4095);
            self.b.and_i32();
        }
    }
    /// [i32 linear page] -> the host address of its page (mem8 + physical)
    /// by its 32-bit TLB entry, or 1 when the entry does not grant reading
    /// (execution) at this CPL (P7.3b)
    fn tlb_page_host(&mut self) {
        let [tlb, read, _] = self
            .tlb
            .as_ref()
            .unwrap()
            .each_ref()
            .map(|l| l.unsafe_clone());
        self.si(OFF);
        self.b.get_local(&tlb);
        self.gi(OFF);
        self.c32(2);
        self.b.shl_i32();
        self.b.add_i32();
        self.b.load_aligned_i32(0);
        self.ti(ENT);
        self.c32(!0xFFF);
        self.b.and_i32();
        self.gi(OFF);
        self.c32(12);
        self.b.shl_i32();
        self.b.xor_i32();
        self.c32(1);
        self.gi(ENT);
        self.b.get_local(&read);
        self.b.and_i32();
        self.c32(TLB_VALID);
        self.b.eq_i32();
        self.b.select();
    }
    /// 16-bit code's entry (P7.7): it leaves at once with RIP unchanged
    /// (pages::run interprets an instruction then) unless the page's linear
    /// address less CS's base is CompileEnv::ip_base, which its IPs assume
    fn prot16_entry(&mut self, exit: Label) {
        self.g(BASE);
        self.b.wrap_i64_to_i32();
        self.c32(gp::segment_offsets as i32 + crate::cpu::cpu::CS * 4);
        self.b.load_aligned_i32(0);
        self.b.sub_i32();
        self.c32(self.env.ip_base);
        self.b.ne_i32();
        self.b.if_void();
        self.set_exit(EXIT_UNKNOWN);
        self.b.br(exit);
        self.b.block_end();
    }
    /// A span's entry (P7.3b): its page by the 32-bit TLB entry of the page
    /// entered (gp::x64_page_linear, BASE so far), then BASE its first
    /// page's address and `verified` the pages whose entries map them as
    /// compiled (CompileEnv::span_hosts). An entry page that maps none of
    /// them leaves at once with RIP unchanged (pages::run interprets an
    /// instruction then).
    fn span_entry(&mut self, exit: Label) {
        let hosts = self.env.span_hosts;
        self.g(BASE);
        self.c64(12);
        self.b.shr_u_i64();
        self.b.wrap_i64_to_i32();
        self.tlb_page_host();
        self.si(HH);
        self.c32(-1);
        self.si(ST);
        for j in (0..self.env.span as usize).rev() {
            self.c32(j as i32);
            self.gi(ST);
            self.gi(HH);
            self.c32(hosts[j] as i32);
            self.b.eq_i32();
            self.b.select();
            self.si(ST);
        }
        self.gi(ST);
        self.c32(-1);
        self.b.eq_i32();
        self.b.if_void();
        self.set_exit(EXIT_UNKNOWN);
        self.b.br(exit);
        self.b.block_end();
        self.g(BASE);
        self.gi(ST);
        self.c32(12);
        self.b.shl_i32();
        self.b.extend_unsigned_i32_to_i64();
        self.b.sub_i64();
        self.s(BASE);
        let verified = self.verified.as_ref().unwrap().unsafe_clone();
        self.c32(0);
        self.b.set_local(&verified);
        for m in 0..self.env.span as usize {
            self.g(BASE);
            self.c64(12);
            self.b.shr_u_i64();
            self.b.wrap_i64_to_i32();
            if m != 0 {
                self.c32(m as i32);
                self.b.add_i32();
            }
            self.tlb_page_host();
            self.c32(hosts[m] as i32);
            self.b.eq_i32();
            if m != 0 {
                self.c32(m as i32);
                self.b.shl_i32();
            }
            self.b.get_local(&verified);
            self.b.or_i32();
            self.b.set_local(&verified);
        }
    }
    /// (P7.3b) Before control passes to `target` in page `page` of the
    /// span from another page: leave unless that page was verified
    fn span_check(&mut self, target: u64) {
        let page = (target / PAGE as u64) as u16;
        if self.env.span > 1 && page != self.current_page {
            self.b.get_local(self.verified.as_ref().unwrap());
            self.c32(1 << page);
            self.b.and_i32();
            self.b.eqz_i32();
            self.b.if_void();
            self.leave_to(self.f().exit, target);
            self.b.block_end();
        }
    }
    /// (P7.3b) RIP is in the span: leave unless its page was verified
    fn span_check_rip(&mut self) {
        if self.env.span > 1 {
            self.b.get_local(self.verified.as_ref().unwrap());
            self.rip_offset();
            self.c32(12);
            self.b.shr_u_i32();
            self.b.shr_u_i32();
            self.c32(1);
            self.b.and_i32();
            self.b.eqz_i32();
            self.b.br_if(self.f().exit);
        }
    }
    /// The page dispatch's and each loop head's: the page's execution
    /// counter (CompileEnv::counter), then exit when the budget is spent
    /// (native instructions and steps; with cores in workers, also when
    /// another core kicked this one, e.g. with an IPI: parallel::kick)
    fn head(&mut self) {
        if let Some(counter) = self.env.counter {
            self.c32(counter as i32);
            self.c32(counter as i32);
            self.b.load_aligned_i32(0);
            self.c32(1);
            self.b.add_i32();
            self.b.store_aligned_i32(0);
        }
        self.n_and_steps();
        self.b.get_local(&self.budget);
        self.b.geu_i32();
        if cfg!(feature = "parallel") {
            self.c32(self.env.core_yield as i32);
            self.b.guest_load_u8(0);
            self.b.or_i32();
        }
        self.b.br_if(self.f().exit);
    }
    /// Push N plus the instructions stepped (K; the 32-bit modes count those
    /// in the budget instead, M8, M9)
    fn n_and_steps(&mut self) {
        self.gi(N);
        if !self.env.compat {
            self.gi(K);
            self.b.add_i32();
        }
    }
    fn g(&mut self, i: usize) { self.b.get_local_i64(&self.v[i]); }
    fn s(&mut self, i: usize) { self.b.set_local_i64(&self.v[i]); }
    fn gi(&mut self, i: usize) { self.b.get_local(&self.w[i]); }
    fn si(&mut self, i: usize) { self.b.set_local(&self.w[i]); }
    fn ti(&mut self, i: usize) { self.b.tee_local(&self.w[i]); }
    fn c64(&mut self, v: u64) { self.b.const_i64(v as i64); }
    fn c32(&mut self, v: i32) { self.b.const_i32(v); }

    fn set_exit(&mut self, code: u32) {
        self.c32(self.env.step.exit_code as i32);
        self.c32(code as i32);
        self.b.store_aligned_i32(0);
    }
    fn load_pair(&mut self, low: u32, high: u32) {
        self.c32(low as i32);
        self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
        self.c32(high as i32);
        self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
        self.c64(32);
        self.b.shl_i64();
        self.b.or_i64();
    }
    fn store_pair(&mut self, low: u32, high: u32, i: usize) {
        self.c32(low as i32);
        self.g(i);
        self.b.memory_op(op::OP_I64STORE32, op::MEM_ALIGN32, 0);
        self.c32(high as i32);
        self.g(i);
        self.c64(32);
        self.b.shr_u_i64();
        self.b.memory_op(op::OP_I64STORE32, op::MEM_ALIGN32, 0);
    }
    fn reload(&mut self) {
        // (compatibility mode: the eight GPRs' low halves, P7.2; the 32-bit
        // code leaves the high halves as they are)
        for i in 0..if self.env.compat { 8 } else { 16 } {
            if self.env.compat {
                self.c32(gpr_low_offset(i) as i32);
                self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
            }
            else {
                self.load_pair(gpr_low_offset(i), gpr_high_offset(i));
            }
            self.s(i);
        }
        self.b.load_fixed_i32(gp::flags as u32);
        self.si(FL);
        self.budget_flags();
    }
    /// The budget's low bits (BUDGET_FLAGS), at entry and after each step
    /// (reload: a stepped CLTS, MOV CR, XSETBV, LDMXCSR or FXRSTOR may change
    /// what they say): which vector_checked kinds may run natively (from
    /// CR0, CR4 and XCR0) and BUDGET_MXCSR, whether MXCSR admits native
    /// float results (native_fp::mxcsr_refused_any_daz clear). The checks
    /// read them there, not CR0, CR4 and MXCSR in each block (5% of a
    /// CPU-Z-like float kernel): every head reads the budget anyway, which
    /// only bounds the activation, while a function-wide local of their own
    /// takes a register the function's other values need (3.7% slower)
    fn budget_flags(&mut self) {
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_FLAGS);
        self.b.and_i32();
        // SSE: CR0.EM and TS clear, CR4.OSFXSR set
        self.b.load_fixed_i32(gp::cr as u32);
        self.c32(0xC);
        self.b.and_i32();
        self.b.eqz_i32();
        self.b.load_fixed_i32(gp::cr as u32 + 16);
        self.c32(0x200);
        self.b.and_i32();
        self.c32(0);
        self.b.ne_i32();
        self.b.and_i32();
        self.b.or_i32();
        // VEX: CR0.TS clear, CR4.OSXSAVE set, XCR0 with SSE and AVX state
        self.b.load_fixed_i32(gp::cr as u32);
        self.c32(crate::cpu::cpu::CR0_TS);
        self.b.and_i32();
        self.b.eqz_i32();
        self.b.load_fixed_i32(gp::cr as u32 + 16);
        self.c32(crate::cpu::cpu::CR4_OSXSAVE);
        self.b.and_i32();
        self.c32(0);
        self.b.ne_i32();
        self.b.and_i32();
        self.b.load_fixed_i32(gp::xcr0 as u32);
        self.c32(6);
        self.b.and_i32();
        self.c32(6);
        self.b.eq_i32();
        self.b.and_i32();
        self.c32(VECTOR_VEX.trailing_zeros() as i32);
        self.b.shl_i32();
        self.b.or_i32();
        // x87: CR0.EM and TS clear
        self.b.load_fixed_i32(gp::cr as u32);
        self.c32(crate::cpu::cpu::CR0_EM | crate::cpu::cpu::CR0_TS);
        self.b.and_i32();
        self.b.eqz_i32();
        self.c32(VECTOR_X87.trailing_zeros() as i32);
        self.b.shl_i32();
        self.b.or_i32();
        self.mxcsr_native();
        self.b.or_i32();
        // (none once the budget is spent: the head leaves, and no step of
        // the 32-bit modes takes a unit it does not have)
        self.c32(0);
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_FLAGS);
        self.b.and_i32();
        self.b.select();
        self.b.set_local(&self.budget);
    }
    /// Push BUDGET_MXCSR if MXCSR admits native float results, else 0
    fn mxcsr_native(&mut self) {
        crate::x86tpl::native_fp::mxcsr_refused_any_daz(&mut self.b);
        self.b.eqz_i32();
        self.c32(BUDGET_MXCSR.trailing_zeros() as i32);
        self.b.shl_i32();
    }
    /// BUDGET_MXCSR again from MXCSR (an LDMXCSR wrote it, an exact helper
    /// may have set PE)
    fn mxcsr_flag(&mut self) {
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_MXCSR);
        self.b.and_i32();
        self.mxcsr_native();
        self.b.or_i32();
        self.b.set_local(&self.budget);
    }
    /// Retry unless the budget's flags have all of `bits` (budget_flags)
    fn budget_check(&mut self, bits: i32, start: u64) {
        self.b.get_local(&self.budget);
        self.c32(bits);
        self.b.and_i32();
        self.c32(bits);
        self.b.ne_i32();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
    }
    /// RIP into its local (in compatibility mode EIP: its high half is 0)
    fn load_rip(&mut self) {
        if self.env.compat {
            self.c32(gp::instruction_pointer as i32);
            self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
        }
        else {
            self.load_pair(gp::instruction_pointer as u32, gp::x64_rip_hi as u32);
        }
        self.s(RIP);
    }
    fn prologue(&mut self) {
        self.set_exit(EXIT_NORMAL);
        // (the budget in units above its flags, BUDGET_FLAGS, rounded down:
        // what a chain passes on only shrinks, and below one unit the head
        // leaves at once, for the interpreter)
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_FLAGS);
        self.b.and_i32();
        self.b.set_local(&self.budget);
        if self.env.fast_chain {
            // (P4.22: the GPRs of a chaining predecessor, see chain)
            self.b.get_local(&self.budget);
            self.c32(CHAINED_GPRS);
            self.b.and_i32();
            self.b.if_void();
            for i in 0..16 {
                self.c32(gp::x64_chain_gprs as i32 + 8 * i as i32);
                self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
                self.s(i);
            }
            self.b.load_fixed_i32(gp::flags as u32);
            self.si(FL);
            self.b.get_local(&self.budget);
            self.c32(!CHAINED_GPRS);
            self.b.and_i32();
            self.b.set_local(&self.budget);
            self.budget_flags();
            self.b.else_();
            self.reload();
            self.b.block_end();
        }
        else {
            self.reload();
        }
        self.load_rip();
        if self.env.compat_tlb {
            // (Tier-0's: supervisor code may use supervisor pages; a step
            // that changes CPL leaves, see pages::context)
            let tlb = self.b.declare_zeroed_local();
            self.b.load_fixed_i32(gp::ir_tlb_base as u32);
            self.b.set_local(&tlb);
            // (M8, the 32-bit modes: the write mask is the read mask with
            // TLB_READONLY and TLB_HAS_CODE, ORed where a write looks up:
            // one register less through the function)
            let masks = if self.env.compat {
                let read = self.b.declare_zeroed_local();
                [read.unsafe_clone(), read]
            }
            else {
                [self.b.declare_zeroed_local(), self.b.declare_zeroed_local()]
            };
            let count = if self.env.compat { 1 } else { 2 };
            for (mask, f) in masks
                .iter()
                .zip([tlb_read_mask as fn(bool) -> i32, tlb_write_mask])
                .take(count)
            {
                self.c32(f(true));
                self.c32(f(false));
                self.b.load_fixed_u8(gp::cpl as u32);
                self.c32(3);
                self.b.eq_i32();
                self.b.select();
                self.b.set_local(mask);
            }
            let [read, write] = masks;
            self.tlb = Some([tlb, read, write]);
        }
        self.b.load_fixed_i32(gp::x64_jac_base as u32);
        self.si(JAC);
        // (M8: the 32-bit modes read the epoch where they chain, its only
        // use, and count steps in the budget, not K: two registers less where
        // dispatch tables merge, which V8 otherwise spills around)
        if !self.env.compat {
            self.c32(gp::x64_jac_epoch as i32);
            self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
            self.s(EP);
        }
        self.c32(gp::x64_page_linear as i32);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
        self.s(BASE);
        // a chaining predecessor passes its lazy EFLAGS record on (see chain)
        self.b.load_fixed_i32(gp::x64_page_lazy_kind as u32);
        self.si(FK);
        self.c32(gp::x64_page_lazy_a as i32);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
        self.s(FA);
        self.c32(gp::x64_page_lazy_b as i32);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
        self.s(FB);
    }
    /// Memory becomes authoritative: GPRs, materialized EFLAGS and RIP.
    fn writeback(&mut self) {
        for i in 0..if self.env.compat { 8 } else { 16 } {
            if self.env.compat {
                self.c32(gpr_low_offset(i) as i32);
                self.g(i);
                self.b.memory_op(op::OP_I64STORE32, op::MEM_ALIGN32, 0);
            }
            else {
                self.store_pair(gpr_low_offset(i), gpr_high_offset(i), i);
            }
        }
        self.writeback_except_gprs();
    }
    /// writeback but the GPRs
    fn writeback_except_gprs(&mut self) {
        self.c32(gp::flags as i32);
        self.gi(FL);
        self.b.store_aligned_i32(0);
        self.c32(gp::flags_changed as i32);
        self.c32(0);
        self.b.store_aligned_i32(0);
        if self.env.compat {
            self.c32(gp::instruction_pointer as i32);
            self.g(RIP);
            self.b.memory_op(op::OP_I64STORE32, op::MEM_ALIGN32, 0);
        }
        else {
            self.store_pair(gp::instruction_pointer as u32, gp::x64_rip_hi as u32, RIP);
        }
        self.c32(gp::last_virt_eip as i32);
        self.c32(-1);
        self.b.store_aligned_i32(0);
    }
    /// Shared: interpret the instruction at RIP, then dispatch on the new RIP
    /// unless the step changed the execution context (memory is current).
    /// Far CALL and RETF (M11, Op::FarCall, Op::FarRet): the state to
    /// memory as for a step, EIP the next instruction's and previous_ip this
    /// one's (a fault restarts it), pages::x64_page_far, then through the
    /// chaining table, or leave
    fn far_transfer(
        &mut self,
        op: u32,
        offset: u32,
        selector: u32,
        width: u8,
        start: u64,
        next: u64,
    ) {
        self.xmm_writeback();
        self.x87_close();
        self.materialize_if(ARITH);
        self.linear(next);
        self.s(RIP);
        self.writeback();
        self.c32(gp::previous_ip as i32);
        self.linear(start);
        self.b.wrap_i64_to_i32();
        self.b.store_aligned_i32(0);
        self.c32((op | (width as u32) << 8) as i32);
        self.c32(offset as i32);
        self.c32(selector as i32);
        self.b.call_signature(
            "x64_page_far",
            Signature::new(
                &[WasmType::I32, WasmType::I32, WasmType::I32],
                &[WasmType::I32],
            ),
        );
        self.si(ST);
        // (counted also when it faulted, as the interpreter counts an
        // instruction whose execution faults)
        self.retired();
        self.gi(ST);
        self.b.if_void();
        self.gi(N);
        self.b.return_();
        self.b.block_end();
        self.reload();
        self.c32(0);
        self.si(FK);
        self.load_rip();
        // (it returns: through the table or to pages::run)
        self.chain();
    }
    fn step_code(&mut self) {
        self.x87_close();
        self.materialize_if(ARITH);
        self.writeback();
        if self.env.compat {
            // (a step's unit above the flags, BUDGET_FLAGS)
            self.b.get_local(&self.budget);
            self.c32(BUDGET_FLAGS + 1);
            self.b.sub_i32();
            self.b.set_local(&self.budget);
        }
        else {
            self.gi(K);
            self.c32(1);
            self.b.add_i32();
            self.si(K);
        }
        self.b
            .call_signature("x64_page_step", Signature::new(&[], &[WasmType::I32]));
        self.si(ST);
        self.gi(ST);
        self.b.if_void();
        // (code compiled for segment bases, 16-bit code among it: a far
        // transfer chains, pages::x64_page_step)
        if self.env.chaining && self.env.segmented {
            self.gi(ST);
            self.c32(STEP_CHAIN);
            self.b.eq_i32();
            self.b.if_void();
            self.reload();
            self.c32(0);
            self.si(FK);
            self.load_rip();
            // (it returns: through the table or to pages::run)
            self.chain();
            self.b.block_end();
        }
        self.gi(N);
        self.b.return_();
        self.b.block_end();
        self.reload();
        self.c32(0);
        self.si(FK);
        self.load_rip();
        // (P4.21: the step may have retired access cache entries without a
        // new epoch, a 4 KiB INVLPG among them: the kept translations go)
        for kept in &self.lookup_kept {
            kept.tag.forget(&mut self.b);
        }
        self.b.br(self.f().dispatch);
    }
    /// Count one native instruction, unless blocks count theirs at entry
    /// (BLOCK_COUNT).
    fn retired(&mut self) {
        if self.env.block_count {
            return;
        }
        self.gi(N);
        self.c32(1);
        self.b.add_i32();
        self.si(N);
    }
    /// Push the return address of a call whose next instruction is at
    /// page-relative `offset`: its linear address, or in 16-bit code its IP
    /// (P7.7: CompileEnv::ip_base)
    fn return_address(&mut self, offset: u64) {
        if self.env.prot16 {
            self.c64(((self.env.ip_base as i64).wrapping_add(offset as i64) & 0xFFFF) as u64);
        }
        else {
            self.linear(offset);
        }
    }
    /// In 16-bit code (P7.7), the IP in local `i` (a return address or an
    /// indirect branch target) to its linear address: plus CS's base, which
    /// is the page's linear address less CompileEnv::ip_base
    fn ip_to_linear(&mut self, i: usize) {
        if !self.env.prot16 {
            return;
        }
        self.g(BASE);
        self.c64(self.env.ip_base as i64 as u64);
        self.b.sub_i64();
        self.g(i);
        self.c64(0xFFFF);
        self.b.and_i64();
        self.b.add_i64();
        self.wrap32();
        self.s(i);
    }
    /// Push the linear address of page-relative address `offset` (in
    /// compatibility mode wrapped at 4 GiB, as EIP is).
    fn linear(&mut self, offset: u64) {
        self.g(BASE);
        if offset != 0 {
            self.c64(offset);
            self.b.add_i64();
            // (compatibility mode wraps at 4 GiB: not inside the page,
            // which is below it)
            if self.env.compat && offset >= PAGE as u64 {
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
            }
        }
    }
    fn leave_to(&mut self, label: Label, offset: u64) {
        self.xmm_writeback();
        self.linear(offset);
        self.s(RIP);
        self.b.br(label);
    }
    /// RIP left the page: with budget left and a chaining entry for the new
    /// linear page (pages::CHAIN, tagged with the access cache epoch), write
    /// the state back and tail-call that page's function, which counts on
    /// from the instructions retired so far (gp::x64_page_chain). Else
    /// return to the dispatch loop.
    fn chain(&mut self) {
        self.n_and_steps();
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_FLAGS);
        self.b.and_i32();
        self.b.ltu_i32();
        if cfg!(feature = "parallel") {
            // (cores in workers: not while code publications or invalidations
            // of other cores wait for this one, see parallel::code::poll)
            let [publish, publish_seen, invalidate, invalidate_seen] = self.env.pending;
            for (next, seen) in [(publish, publish_seen), (invalidate, invalidate_seen)] {
                self.c32(next as i32);
                self.b.guest_load_i32(0);
                self.c32(seen as i32);
                self.b.load_aligned_i32(0);
                self.b.eq_i32();
                self.b.and_i32();
            }
            // nor when another core kicked this one
            self.c32(self.env.core_yield as i32);
            self.b.guest_load_u8(0);
            self.b.eqz_i32();
            self.b.and_i32();
        }
        self.b.if_void();
        // (the chaining lookup, pagegen::frame: the 32-bit modes' epoch from
        // memory, long mode's in EP)
        let epoch = if self.env.compat {
            ChainEpoch::Global(gp::x64_jac_epoch as u32)
        }
        else {
            ChainEpoch::Local(&self.v[EP])
        };
        page_frame::chain_lookup(
            &mut self.b,
            &self.v[RIP],
            &self.v[TAG],
            &self.w[ENT],
            gp::x64_code_base as u32,
            epoch,
        );
        // the state goes to memory, EFLAGS with the lazy record unevaluated:
        // the next function continues with it (its prologue); with
        // x64_fast_chain the GPRs go to x64_chain_gprs (P4.22)
        if self.env.fast_chain {
            for i in 0..16 {
                self.c32(gp::x64_chain_gprs as i32 + 8 * i as i32);
                self.g(i);
                self.b.store_aligned_i64(0);
            }
            self.writeback_except_gprs();
        }
        else {
            self.writeback();
        }
        self.c32(gp::x64_page_lazy_kind as i32);
        self.gi(FK);
        self.b.store_aligned_i32(0);
        self.c32(gp::x64_page_lazy_a as i32);
        self.g(FA);
        self.b.store_aligned_i64(0);
        self.c32(gp::x64_page_lazy_b as i32);
        self.g(FB);
        self.b.store_aligned_i64(0);
        self.c32(gp::x64_page_linear as i32);
        self.g(RIP);
        self.c64(!4095);
        self.b.and_i64();
        self.b.store_aligned_i64(0);
        self.c32(gp::x64_page_chain as i32);
        self.b.load_fixed_i32(gp::x64_page_chain as u32);
        self.gi(N);
        self.b.add_i32();
        self.b.store_aligned_i32(0);
        // (without the flags: the next function's own)
        self.b.get_local(&self.budget);
        self.c32(!BUDGET_FLAGS);
        self.b.and_i32();
        self.gi(N);
        self.b.sub_i32();
        if !self.env.compat {
            self.gi(K);
            self.b.sub_i32();
        }
        if self.env.fast_chain {
            self.c32(CHAINED_GPRS);
            self.b.or_i32();
        }
        page_frame::chain_call(&mut self.b, &self.w[ENT]);
        self.b.block_end();
        self.b.block_end();
        self.materialize_if(ARITH);
        self.writeback();
        self.gi(N);
        self.b.return_();
    }
    /// Retry the branch at `start` unless its target outside the page is
    /// canonical where the page runs (a noncanonical target is #GP at the
    /// branch).
    fn check_target(&mut self, target: u64, start: u64) {
        // (compatibility mode: every 32-bit EIP is valid in a flat CS)
        if in_page(self.span_bytes(), target).is_none() && !self.env.compat {
            self.linear(target);
            self.s(TX);
            self.check_canonical(TX, start);
        }
    }
    /// Continue at the address in RIP (checked by dispatch). In
    /// compatibility mode inside a loop (P4.16), at the innermost loop's
    /// head, which dispatches on RIP over its members (else the page
    /// dispatch): a switch's jump or a call's return in a loop body takes
    /// one table, not the page's buckets and then the loop's (P7.2)
    /// Before a RET's dispatch: its predicted return addresses
    /// (return_sites) whose blocks follow on this page as single units
    /// (PageEmitter::direct_label), RETURN_GUESSES at most, each compared
    /// with RIP and branched to directly (every way on finds the XMM
    /// registers in memory)
    fn return_guess(&mut self, start: u64, index: &BTreeMap<u16, usize>) {
        let Some(sites) = self.returns.get(&(start as u16))
        else {
            return;
        };
        let page = self.current_page;
        let guesses: Vec<(u16, Label)> = sites
            .iter()
            .filter(|&&o| o / PAGE as u16 == page)
            .filter_map(|&o| self.direct_label(o, index).map(|label| (o, label)))
            .take(RETURN_GUESSES)
            .collect();
        if guesses.is_empty() {
            return;
        }
        self.xmm_release();
        self.g(RIP);
        self.g(BASE);
        self.b.sub_i64();
        self.s(TV);
        for (o, label) in guesses {
            self.g(TV);
            self.c64(o as u64);
            self.b.eq_i64();
            self.b.br_if(label);
        }
    }
    fn dispatch(&mut self) {
        self.xmm_writeback();
        if self.env.compat && self.levels.len() > 1 {
            // (out of the page: leave, as the page dispatch does)
            self.g(RIP);
            self.g(BASE);
            self.b.sub_i64();
            self.c64(self.span_bytes());
            self.b.op(op::OP_I64GEU);
            self.b.br_if(self.f().leave);
            self.span_check_rip();
            // (the innermost loop whose head dispatches on RIP, else the page)
            let repeat = self.levels[1..]
                .iter()
                .rev()
                .find(|l| !l.direct)
                .map(|l| l.repeat);
            return self.b.br(repeat.unwrap_or(self.f().dispatch));
        }
        self.b.br(self.f().dispatch);
    }
    fn block(&mut self, block: &Block, index: &BTreeMap<u16, usize>) {
        self.current_page = block.start / PAGE as u16;
        // (every way into a block left the XMM registers in memory; the
        // x87 cache is open on some of them, x87_is_open says which)
        self.xmm_held = 0;
        self.xmm_dirty = 0;
        self.x87_known_open = false;
        // (and what the block learns about the vector checks holds from
        // where it learns it)
        self.vector_checked = 0;
        self.xmm_clean = [0; 16];
        self.kept_set = 0;
        self.ymm_zeroed = 0;
        if self.env.block_count {
            // (a block left early, by a retry or a step, counts the rest of
            // its instructions too: N bounds activations and feeds statistics)
            let native = block
                .insts
                .iter()
                .filter(|i| !matches!(i.op, Op::Step))
                .count();
            if native != 0 {
                self.gi(N);
                self.c32(native as i32);
                self.b.add_i32();
                self.si(N);
            }
        }
        let worth =
            if self.env.xmm_locals { xmm_worth(block, self.env.sse_fast_check) } else { vec![] };
        let mut i = 0;
        while i < block.insts.len() {
            if let Some(run) = self
                .env
                .compat
                .then(|| x87_run_at(&block.insts[i..]))
                .flatten()
            {
                let insts = &block.insts[i..i + run.length];
                self.x87_run(insts, &run, index);
                i += run.length;
                continue;
            }
            self.xmm_worth = worth.get(i).copied().unwrap_or(0);
            self.instruction(&block.insts[i], index);
            i += 1;
        }
        // (the next block, whose code may follow, starts from memory)
        self.xmm_release();
        match block.end {
            End::Stop => {},
            End::Retry(o) => self.leave_to(self.f().retry, o as u64),
            End::StepAt(o) => self.leave_to(self.f().step, o as u64),
            End::Next(o) => {
                if !block.insts.last().is_some_and(|i| matches!(i.op, Op::Step))
                    && !self.falls_into(o, index)
                {
                    self.goto(o as u64, index);
                }
                else if !block.insts.last().is_some_and(|i| matches!(i.op, Op::Step)) {
                    // (into the span's next page, P7.3b)
                    self.span_check(o as u64);
                }
            },
            End::Shadow(o) => {
                // (with IF set and an interrupt deliverable, the dispatcher
                // takes it: pages::x64_page_irq_window)
                self.gi(FL);
                self.b.call_signature(
                    "x64_page_irq_window",
                    Signature::new(&[WasmType::I32], &[WasmType::I32]),
                );
                self.b.if_void();
                self.leave_to(self.f().exit, o as u64);
                self.b.block_end();
                if !self.falls_into(o, index) {
                    self.goto(o as u64, index);
                }
            },
        }
    }

    // Operands ----------------------------------------------------------

    fn get_reg(&mut self, r: Reg, width: u8) {
        self.g(r.index as usize);
        if r.high {
            self.c64(8);
            self.b.shr_u_i64();
            self.c64(0xFF);
            self.b.and_i64();
        }
        else if width == 32 && self.env.i32_ops {
            // (P4.20: what an i32 operation reads for free)
            self.b.wrap_i64_to_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
        else if width < 64 {
            self.c64(mask(width));
            self.b.and_i64();
        }
    }
    /// [i64 a, i64 b] -> the i32 operation `f` on their low halves,
    /// zero-extended (P4.20: one 32-bit instruction on hosts)
    fn op32(&mut self, a: usize, b: Option<usize>, f: impl FnOnce(&mut WasmBuilder)) {
        self.g(a);
        self.b.wrap_i64_to_i32();
        if let Some(b) = b {
            self.g(b);
            self.b.wrap_i64_to_i32();
        }
        f(&mut self.b);
        self.b.extend_unsigned_i32_to_i64();
    }
    /// Write the value on the stack (low `width` bits) with x86-64 register
    /// semantics: 32-bit writes zero-extend, 8/16-bit writes merge.
    fn set_reg(&mut self, r: Reg, width: u8) { self.set_reg_fitting(r, width, false) }
    /// set_reg of a value `fits` in `width` bits already (SETcc's 0 or 1)
    fn set_reg_fitting(&mut self, r: Reg, width: u8, fits: bool) {
        let i = r.index as usize;
        match width {
            64 => self.s(i),
            32 => {
                self.b.wrap_i64_to_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.s(i);
            },
            _ => {
                if !fits {
                    self.c64(mask(width));
                    self.b.and_i64();
                }
                let keep = if r.high {
                    self.c64(8);
                    self.b.shl_i64();
                    !0xFF00u64
                }
                else {
                    !mask(width)
                };
                self.g(i);
                self.c64(keep);
                self.b.and_i64();
                self.b.or_i64();
                self.s(i);
            },
        }
    }
    /// Push the address of a memory operand: the effective address wrapped
    /// to its size, plus the FS/GS base when `segment` (not for LEA).
    fn address(&mut self, a: &AddressExpr, next: u64, segment: bool) {
        self.lookup_base = match (a.base, a.index) {
            (AddressBase::Register(r), None) => Some((r, kept_page(a.displacement))),
            _ => None,
        };
        if self.env.compat {
            // (32-bit addresses in i32, wrapped at 4 GiB for free, as
            // address32; plus a 32-bit FS/GS base)
            // (P7.2(3): ES, SS and DS bases too when compiled for them, CS's
            // is 0; then any but SS may be null: #GP, the interpreter's)
            if segment && self.env.segmented && matches!(a.segment, 0 | 3 | 4 | 5) {
                self.null_check(a.segment);
            }
            self.address32(a, next);
            // (CS's base: 0 in 32-bit code, which runs with a flat CS; 16-bit
            // code's, P7.7, is not)
            if segment
                && (a.segment >= 4 || self.env.segmented && (a.segment != 1 || self.env.prot16))
            {
                self.c32(gp::segment_offsets as i32 + a.segment as i32 * 4);
                self.b.load_aligned_i32(0);
                self.b.add_i32();
            }
            self.b.extend_unsigned_i32_to_i64();
            return;
        }
        let mut have = false;
        let mut displacement = a.displacement;
        match a.base {
            AddressBase::Register(r) => {
                self.g(r as usize);
                have = true;
            },
            AddressBase::NextRip => {
                self.linear((next as i64).wrapping_add(displacement) as u64);
                displacement = 0;
                have = true;
            },
            AddressBase::None => {},
        }
        if let Some(i) = a.index {
            self.g(i as usize);
            if a.scale != 0 {
                self.c64(a.scale as u64);
                self.b.shl_i64();
            }
            if have {
                self.b.add_i64();
            }
            have = true;
        }
        if !have {
            self.c64(displacement as u64);
        }
        else if displacement != 0 {
            self.c64(displacement as u64);
            self.b.add_i64();
        }
        match a.address_size {
            32 => {
                self.b.wrap_i64_to_i32();
                self.b.extend_unsigned_i32_to_i64();
            },
            16 => {
                self.c64(0xFFFF);
                self.b.and_i64();
            },
            _ => {},
        }
        if segment && a.segment >= 4 {
            let s = a.segment as u32;
            if self.env.compat {
                // (a 32-bit base; the linear address wraps at 4 GiB)
                self.c32(gp::segment_offsets as i32 + s as i32 * 4);
                self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
                self.b.add_i64();
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
            }
            else {
                self.load_pair(
                    gp::segment_offsets as u32 + s * 4,
                    gp::x64_segment_base_hi as u32 + s * 4,
                );
                self.b.add_i64();
            }
        }
    }
    /// Push the low half of the effective address of `a` (i32; LEA r32 with
    /// x64_i32_ops, P4.20): its low 32 bits depend only on those of the
    /// registers. No segment base (as LEA).
    fn address32(&mut self, a: &AddressExpr, next: u64) {
        let mut have = false;
        let mut displacement = a.displacement;
        match a.base {
            AddressBase::Register(r) => {
                self.g(r as usize);
                self.b.wrap_i64_to_i32();
                have = true;
            },
            AddressBase::NextRip => {
                self.linear((next as i64).wrapping_add(displacement) as u64);
                self.b.wrap_i64_to_i32();
                displacement = 0;
                have = true;
            },
            AddressBase::None => {},
        }
        if let Some(i) = a.index {
            self.g(i as usize);
            self.b.wrap_i64_to_i32();
            if a.scale != 0 {
                self.c32(a.scale as i32);
                self.b.shl_i32();
            }
            if have {
                self.b.add_i32();
            }
            have = true;
        }
        if !have {
            self.c32(displacement as i32);
        }
        else if displacement as i32 != 0 {
            self.c32(displacement as i32);
            self.b.add_i32();
        }
        if a.address_size == 16 {
            self.c32(0xFFFF);
            self.b.and_i32();
        }
    }
    /// Host address (i32) of a `size`-byte access at the linear address in
    /// ADDR: an access cache hit, else x64_page_access, else a retry of the
    /// instruction at `start`.
    fn host(&mut self, size: u32, write: bool, start: u64) {
        self.host_or(size, write, start, self.f().retry)
    }
    /// host(), leaving for `fallback` (retry, or step) when refused.
    /// The module's internal function (addr: i64, kind: i32) -> i32: the
    /// host address for a `kind & 255`-byte access (bit 8: write) at linear
    /// addr from the access cache (x64::jac), else x64_page_access; 0 when
    /// refused. The same lookup host_or otherwise inlines.
    fn access_function(&mut self) -> u32 {
        if let Some(f) = self.access {
            return f;
        }
        let abi = self.access_abi();
        let f = page_frame::lookup_function(&mut self.b, &abi);
        self.access = Some(f);
        f
    }
    /// The access cache's globals and the runtime's lookup (pagegen::frame::AccessAbi)
    fn access_abi(&self) -> AccessAbi {
        AccessAbi {
            epoch: gp::x64_jac_epoch as u32,
            base: gp::x64_jac_base as u32,
            entries: self.env.jac_entries,
            slow: "x64_page_access",
            bounce: self.env.bounce,
        }
    }
    /// The host address of a store or read-modify-write of `size` bytes at
    /// ADDR (else a retry). With cores in workers it may be unaligned:
    /// store() and load_any() handle that.
    fn host_store(&mut self, size: u32, start: u64) {
        if WasmBuilder::ATOMIC_GUEST_MEMORY && size > 1 {
            self.host_kind((size, false), 0x300, start, self.f().retry)
        }
        else {
            self.host(size, true, start)
        }
    }
    fn host_or(&mut self, size: u32, write: bool, start: u64, fallback: Label) {
        self.host_kind((size, false), (write as u32) << 8, start, fallback)
    }
    /// host_or() of a `size`-byte operand known to be `aligned` to its size
    /// (an inline lookup then compares no page offset) with the lookup's
    /// kind bits (write: 0x100, unaligned write hosts accepted: 0x200;
    /// outlined lookups only)
    fn host_kind(&mut self, (size, aligned): (u32, bool), bits: u32, start: u64, fallback: Label) {
        let write = bits & 0x100 != 0;
        if self.tlb.is_some() {
            return self.host_tlb(size, aligned, write, start, fallback);
        }
        // (the access cache's lookups: pagegen::frame, P5.9)
        if self.env.outline {
            let l = self.lookup_locals();
            return self.outlined_lookup(&l, size, bits, start, fallback);
        }
        let table = if write { 2 * self.env.jac_entries * jac::ENTRY_BYTES } else { 0 };
        if self.env.fast_lookup {
            return self.host_fast(size, aligned, table, bits, start, fallback);
        }
        let (l, abi) = (self.lookup_locals(), self.access_abi());
        self.inline_lookup(&l, &abi, (size, aligned), bits, start, fallback);
    }
    /// The locals of the access cache's lookups (pagegen::frame::LookupLocals)
    fn lookup_locals(&self) -> LookupLocals {
        LookupLocals {
            addr: self.v[ADDR].unsafe_clone(),
            epoch: self.v[EP].unsafe_clone(),
            tag: self.v[TAG].unsafe_clone(),
            tables: self.w[JAC].unsafe_clone(),
            entry: self.w[ENT].unsafe_clone(),
            offset: self.w[OFF].unsafe_clone(),
            host: self.w[HH].unsafe_clone(),
        }
    }
    /// The kept translation of the operand being looked up (lookup_base) of
    /// its kind, made when first used (MAX_KEPT at most)
    fn kept(&mut self, write: bool) -> Option<usize> {
        let (base, page) = self.lookup_base?;
        let key = |k: &Kept| k.base == base && k.write == write && k.page == page;
        if let Some(k) = self.lookup_kept.iter().position(key) {
            return Some(k);
        }
        if self.lookup_kept.len() >= MAX_KEPT {
            return None;
        }
        let tag = if self.tlb.is_some() {
            KeptTag::Narrow(self.b.declare_zeroed_local())
        }
        else {
            KeptTag::Wide(self.b.declare_zeroed_local_i64())
        };
        let delta = self.b.declare_zeroed_local();
        self.lookup_kept.push(Kept {
            base,
            write,
            page,
            tag,
            delta,
        });
        Some(self.lookup_kept.len() - 1)
    }
    /// host_kind in compatibility mode with x64_compat_tlb (P7.2): Tier-0's
    /// lookup (ir::tier0 tlb_miss) in the 32-bit TLB, whose entries x64
    /// translations fill in compatibility mode (cpu::fill_ia32e_tlb, plain
    /// RAM only; every x64 TLB invalidation clears it too, and code pages'
    /// entries carry TLB_HAS_CODE): an entry that grants the access to the
    /// activation's CPL (for a write: writable, no code) for an operand
    /// inside one page gives the host address, (entry & !0xFFF) ^ address;
    /// else x64_page_access, which fills the entry, refuses as for other
    /// lookups (then `fallback`) or serves what the TLB does not hold. With
    /// x64_fast_lookup, an operand `[register + displacement]` first tries
    /// the entry its base register's operands of its kind found last in its
    /// block, as host_fast keeps translations (lookup_kept: the page |
    /// 1 << 20, never 0 as a forgotten one is, and the entry's mask). A
    /// block's first access by its key sets that on every path, so none is
    /// live into a block: kept across the function's loops and dispatch,
    /// they took registers that cost more than the lookups they saved
    /// (702.call, 557.lz)
    fn host_tlb(&mut self, size: u32, aligned: bool, write: bool, start: u64, fallback: Label) {
        let [tlb, read, written] = self
            .tlb
            .as_ref()
            .unwrap()
            .each_ref()
            .map(|l| l.unsafe_clone());
        let kept = if self.env.fast_lookup { self.kept(write) } else { None };
        let split = size > 1 && !aligned;
        self.g(ADDR);
        self.b.wrap_i64_to_i32();
        self.si(OFF);
        let in_page = |e: &mut Self| {
            if split {
                e.gi(OFF);
                e.c32(0xFFF);
                e.b.and_i32();
                e.c32((4096 - size) as i32);
                e.b.leu_i32();
                e.b.and_i32();
                if WasmBuilder::ATOMIC_GUEST_MEMORY {
                    // (atomic accesses need natural alignment: as host_kind)
                    e.gi(OFF);
                    e.c32(size.min(8) as i32 - 1);
                    e.b.and_i32();
                    e.b.eqz_i32();
                    e.b.and_i32();
                }
            }
        };
        let first = kept.is_some_and(|k| self.kept_set >> k & 1 == 0);
        // (the kept tag: the page | 1 << 20)
        let tag = |e: &mut Self| {
            e.gi(OFF);
            e.c32(12);
            e.b.shr_u_i32();
            e.c32(1 << 20);
            e.b.or_i32();
        };
        if let Some(k) = kept {
            self.kept_set |= 1 << k;
        }
        if let Some(k) = kept.filter(|_| !first) {
            tag(self);
            self.b.get_local(self.lookup_kept[k].tag.narrow());
            self.b.eq_i32();
            in_page(self);
            self.b.hint(true);
            self.b.if_i32();
            self.b.get_local(&self.lookup_kept[k].delta);
            self.gi(OFF);
            self.b.xor_i32();
            self.b.else_();
        }
        self.b.get_local(&tlb);
        self.gi(OFF);
        self.c32(12);
        self.b.shr_u_i32();
        self.c32(2);
        self.b.shl_i32();
        self.b.add_i32();
        self.b.load_aligned_i32(0);
        self.ti(ENT);
        if write && self.env.compat {
            self.b.get_local(&read);
            self.c32(tlb_write_mask(true) & !tlb_read_mask(true));
            self.b.or_i32();
        }
        else {
            self.b.get_local(if write { &written } else { &read });
        }
        self.b.and_i32();
        self.c32(TLB_VALID);
        self.b.eq_i32();
        in_page(self);
        self.b.hint(true);
        self.b.if_i32();
        self.gi(ENT);
        self.c32(!0xFFF);
        self.b.and_i32();
        if let Some(k) = kept {
            self.b.tee_local(&self.lookup_kept[k].delta);
            tag(self);
            self.b.set_local(self.lookup_kept[k].tag.narrow());
        }
        self.gi(OFF);
        self.b.xor_i32();
        self.b.else_();
        if let Some(k) = kept.filter(|_| first) {
            // (set, forgotten, on this path too)
            self.lookup_kept[k].tag.forget(&mut self.b);
            self.c32(0);
            self.b.set_local(&self.lookup_kept[k].delta);
        }
        self.g(ADDR);
        if self.env.legacy {
            // (legacy mode's slow path, which translates through the 32-bit
            // paging: P7.3)
            self.c32(size as i32 | (write as i32) << 8);
            self.b.call_signature(
                "x64_page_access32",
                Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
            );
        }
        else if WasmBuilder::ATOMIC_GUEST_MEMORY {
            let f = self.access_function();
            self.c32(size as i32 | (write as i32) << 8);
            self.b.call_internal(f);
        }
        else {
            self.c32(size as i32 | (write as i32) << 8);
            self.b.call_signature(
                "x64_page_access",
                Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
            );
        }
        self.ti(HH);
        self.b.eqz_i32();
        self.b.if_void();
        self.leave_to(fallback, start);
        self.b.block_end();
        // (through two XORs: V8 knows the result of a 32-bit operation is
        // zero-extended, so the fast paths' addresses need no uxtw where
        // they meet this one)
        self.gi(HH);
        self.gi(OFF);
        self.b.xor_i32();
        self.gi(OFF);
        self.b.xor_i32();
        self.b.block_end();
        if kept.is_some() && !first {
            self.b.block_end();
        }
    }
    /// host_kind's inline lookup with x64_fast_lookup (P4.21): the access
    /// cache entry of the operand's first byte is a hit when its tag is
    /// that of the last byte's page (an operand crossing pages misses: the
    /// two pages have different entries), and the host is its delta plus
    /// the address. An operand `[register + displacement]` (a stack
    /// operation's too) first tries the translation of its kind that its
    /// base register's operands found last (lookup_kept, a hit when both
    /// the operand's last byte and its first are in that page; a hit in the
    /// access cache replaces it): those stay valid while the function runs,
    /// as entries retire only between runs, by what leaves the function
    /// (exits) and by what it may run in between: INVLPG (Op::Invlpg) and
    /// steps (step_code), after which it forgets them. (Not indexed
    /// operands: two that alternate between pages, as LZ77's matching loop
    /// reads its input, would miss every time, and a miss costs more than
    /// a hit saves.)
    fn host_fast(
        &mut self,
        size: u32,
        aligned: bool,
        table: u32,
        bits: u32,
        start: u64,
        fallback: Label,
    ) {
        let write = bits & 0x100 != 0;
        let kept = self.kept(write);
        // (a block's first access by the key sets it on every path: none is
        // live into a block, as in host_tlb)
        let first = kept.is_some_and(|k| self.kept_set >> k & 1 == 0);
        if let Some(k) = kept {
            self.kept_set |= 1 << k;
        }
        let atomic = WasmBuilder::ATOMIC_GUEST_MEMORY && size > 1 && !aligned;
        // the last byte's tag
        self.g(ADDR);
        if size > 1 && !aligned {
            self.c64(size as u64 - 1);
            self.b.add_i64();
        }
        self.c64(12);
        self.b.shr_u_i64();
        self.g(EP);
        self.b.or_i64();
        self.s(TAG);
        let aligned_check = |e: &mut Self| {
            if atomic {
                // (atomics need natural alignment: see host_kind)
                e.g(ADDR);
                e.b.wrap_i64_to_i32();
                e.c32(size.min(8) as i32 - 1);
                e.b.and_i32();
                e.b.eqz_i32();
                e.b.and_i32();
            }
        };
        if let Some(k) = kept.filter(|_| !first) {
            self.g(TAG);
            self.b.get_local_i64(self.lookup_kept[k].tag.wide());
            self.b.eq_i64();
            if size > 1 && !aligned {
                // (and the first byte in that page too: unlike an access
                // cache entry, the kept translation is not the first byte's
                // page's by its place)
                self.g(ADDR);
                self.b.wrap_i64_to_i32();
                self.c32(4095);
                self.b.and_i32();
                self.c32((4096 - size) as i32);
                self.b.leu_i32();
                self.b.and_i32();
            }
            aligned_check(self);
            self.b.hint(true);
            self.b.if_i32();
            self.b.get_local(&self.lookup_kept[k].delta);
            self.g(ADDR);
            self.b.wrap_i64_to_i32();
            self.b.add_i32();
            self.b.else_();
        }
        self.g(ADDR);
        self.b.wrap_i64_to_i32();
        self.c32(8);
        self.b.shr_u_i32();
        self.c32(((self.env.jac_entries - 1) * jac::ENTRY_BYTES) as i32);
        self.b.and_i32();
        self.gi(JAC);
        self.b.add_i32();
        self.ti(ENT);
        self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, table);
        self.g(TAG);
        self.b.eq_i64();
        aligned_check(self);
        self.b.hint(true);
        self.b.if_i32();
        if let Some(k) = kept {
            self.g(TAG);
            self.b.set_local_i64(self.lookup_kept[k].tag.wide());
        }
        self.gi(ENT);
        self.b.load_aligned_i32(table + 12);
        if let Some(k) = kept {
            self.b.tee_local(&self.lookup_kept[k].delta);
        }
        self.g(ADDR);
        self.b.wrap_i64_to_i32();
        self.b.add_i32();
        self.b.else_();
        if let Some(k) = kept.filter(|_| first) {
            // (set, forgotten, on this path too)
            self.lookup_kept[k].tag.forget(&mut self.b);
            self.c32(0);
            self.b.set_local(&self.lookup_kept[k].delta);
        }
        self.g(ADDR);
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            let f = self.access_function();
            self.c32((size | bits) as i32);
            self.b.call_internal(f);
        }
        else {
            self.c32(size as i32 | (bits & 0x100) as i32);
            self.b.call_signature(
                "x64_page_access",
                Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
            );
        }
        self.ti(HH);
        self.b.eqz_i32();
        self.b.if_void();
        self.leave_to(fallback, start);
        self.b.block_end();
        self.gi(HH);
        self.b.block_end();
        if kept.is_some() && !first {
            self.b.block_end();
        }
    }
    fn load(&mut self, width: u8) { self.b.guest_load_i64_bits(width as u32, 0); }
    /// [host, value] -> []. With cores in workers, an unaligned host (see
    /// host_store) is a plain store after a fence (x86 orders it after the
    /// accesses before it), as the interpreter does.
    fn store(&mut self, width: u8) {
        if !WasmBuilder::ATOMIC_GUEST_MEMORY || width == 8 {
            return self.b.guest_store_i64_bits(width as u32, 0);
        }
        self.s(SV);
        self.ti(SH);
        self.c32(width as i32 / 8 - 1);
        self.b.and_i32();
        self.b.if_void();
        self.b.guest_fence();
        self.gi(SH);
        self.g(SV);
        self.b.memory_op(
            match width {
                16 => op::OP_I64STORE16,
                32 => op::OP_I64STORE32,
                _ => op::OP_I64STORE,
            },
            op::MEM_NO_ALIGN,
            0,
        );
        self.b.else_();
        self.gi(SH);
        self.g(SV);
        self.b.guest_store_i64_bits(width as u32, 0);
        self.b.block_end();
    }
    /// load() from a host of host_store: [host] -> [value]; unaligned (cores
    /// in workers) a plain load, then a fence
    fn load_any(&mut self, width: u8) {
        if !WasmBuilder::ATOMIC_GUEST_MEMORY || width == 8 {
            return self.load(width);
        }
        self.ti(SH);
        self.c32(width as i32 / 8 - 1);
        self.b.and_i32();
        self.b.if_i64();
        self.gi(SH);
        self.b.memory_op(
            match width {
                16 => op::OP_I64LOAD16U,
                32 => op::OP_I64LOAD32U,
                _ => op::OP_I64LOAD,
            },
            op::MEM_NO_ALIGN,
            0,
        );
        self.b.guest_fence();
        self.b.else_();
        self.gi(SH);
        self.load(width);
        self.b.block_end();
    }
    /// Push the (zero-extended) value of a source operand.
    fn read(&mut self, o: Opnd, width: u8, inst: &Inst) {
        match o {
            Opnd::Reg(r) => self.get_reg(r, width),
            // (a volatile instruction's, from the page as it is: P7.3)
            Opnd::Imm(_) if inst.dynamic.is_some() => {
                let (at, bytes, signed) = inst.dynamic.unwrap();
                let host = self.env.span_hosts[at as usize / PAGE] + at as u32 % PAGE as u32;
                self.c32(host as i32);
                self.b.memory_op(
                    match (bytes, signed) {
                        (1, true) => op::OP_I64LOAD8S,
                        (1, false) => op::OP_I64LOAD8U,
                        (2, true) => op::OP_I64LOAD16S,
                        (2, false) => op::OP_I64LOAD16U,
                        (_, true) => op::OP_I64LOAD32S,
                        (_, false) => op::OP_I64LOAD32U,
                    },
                    op::MEM_NO_ALIGN,
                    0,
                );
                if width < 64 {
                    self.c64(mask(width));
                    self.b.and_i64();
                }
            },
            Opnd::Imm(v) => self.c64(v & mask(width)),
            Opnd::Mem(a) => {
                self.address(&a, inst.d.next.0, true);
                self.s(ADDR);
                self.host(width as u32 / 8, false, inst.d.start.0);
                self.load(width);
            },
        }
    }
    /// Read a destination operand; a memory one is validated for writing
    /// first when `write` (its host address stays in HOST).
    fn read_dst(&mut self, o: Opnd, width: u8, write: bool, inst: &Inst) {
        match o {
            Opnd::Mem(a) if inst.locked => {
                self.address(&a, inst.d.next.0, true);
                self.s(ADDR);
                self.host(width as u32 / 8, true, inst.d.start.0);
                self.si(HOST);
                self.locked_load(width);
            },
            Opnd::Mem(a) if write => {
                self.address(&a, inst.d.next.0, true);
                self.s(ADDR);
                self.host_store(width as u32 / 8, inst.d.start.0);
                self.ti(HOST);
                self.load_any(width);
            },
            Opnd::Mem(a) => {
                self.address(&a, inst.d.next.0, true);
                self.s(ADDR);
                self.host(width as u32 / 8, false, inst.d.start.0);
                self.ti(HOST);
                self.load(width);
            },
            _ => self.read(o, width, inst),
        }
    }
    /// A locked instruction (cores in workers) with its operand's host
    /// address in HOST: from here to write_dst is a loop that computes from
    /// the value read, and commits with a compare-exchange; it starts over
    /// when another core changed the operand meanwhile. Pushes the value.
    fn locked_load(&mut self, width: u8) {
        debug_assert!(self.lock_loop.is_none());
        self.lock_loop = Some(self.b.loop_void());
        self.gi(HOST);
        self.load(width);
        self.s(OLD);
        self.g(OLD);
    }
    /// The locked instruction's write: [] -> [], leaves the loop when the
    /// compare-exchange found the value read. It commits as the
    /// interpreter's does (x64_page_lock_commit: never interleaved with a
    /// split locked operation on the same bytes).
    fn locked_store(&mut self, width: u8, value: usize) {
        let again = self.lock_loop.take().unwrap();
        self.gi(HOST);
        self.g(OLD);
        self.g(value);
        self.c32(width as i32 / 8);
        self.b.call_signature(
            "x64_page_lock_commit",
            Signature::new(
                &[WasmType::I32, WasmType::I64, WasmType::I64, WasmType::I32],
                &[WasmType::I32],
            ),
        );
        self.b.eqz_i32();
        self.b.br_if(again);
        self.b.block_end();
    }
    /// Store local `value` to a destination read by read_dst.
    fn write_dst(&mut self, o: Opnd, width: u8, value: usize) {
        if self.lock_loop.is_some() {
            return self.locked_store(width, value);
        }
        match o {
            Opnd::Reg(r) => {
                self.g(value);
                self.set_reg(r, width);
            },
            Opnd::Mem(_) => {
                self.gi(HOST);
                self.g(value);
                self.store(width);
            },
            Opnd::Imm(_) => unreachable!(),
        }
    }
    /// Validate a memory destination for writing without reading it.
    fn prepare_store(&mut self, a: &AddressExpr, width: u8, inst: &Inst) {
        self.address(a, inst.d.next.0, true);
        self.s(ADDR);
        self.host_store(width as u32 / 8, inst.d.start.0);
        self.si(HOST);
    }
    /// Reverse the bytes of the i64 on the stack: all 8 (`width` 64), or
    /// its low 4 (zero-extended)
    fn byte_swap(&mut self, width: u8) {
        if width == 64 {
            self.s(TV);
            self.g(TV);
            self.c64(8);
            self.b.shr_u_i64();
            self.c64(0x00FF_00FF_00FF_00FF);
            self.b.and_i64();
            self.g(TV);
            self.c64(0x00FF_00FF_00FF_00FF);
            self.b.and_i64();
            self.c64(8);
            self.b.shl_i64();
            self.b.or_i64();
            self.s(TV);
            self.g(TV);
            self.c64(16);
            self.b.shr_u_i64();
            self.c64(0x0000_FFFF_0000_FFFF);
            self.b.and_i64();
            self.g(TV);
            self.c64(0x0000_FFFF_0000_FFFF);
            self.b.and_i64();
            self.c64(16);
            self.b.shl_i64();
            self.b.or_i64();
            self.c64(32);
            self.b.op(op::OP_I64ROTL);
        }
        else {
            self.b.wrap_i64_to_i32();
            self.si(COND);
            // rotl(x & 0x00FF00FF, 24) | rotl(x & 0xFF00FF00, 8)
            self.gi(COND);
            self.c32(0x00FF_00FF);
            self.b.and_i32();
            self.c32(24);
            self.b.rotl_i32();
            self.gi(COND);
            self.c32(0xFF00_FF00u32 as i32);
            self.b.and_i32();
            self.c32(8);
            self.b.rotl_i32();
            self.b.or_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
    }
    /// The flags of BLSR, BLSMSK, BLSI, BZHI, TZCNT and LZCNT
    /// (cpu::bmi::logic_flags): SF, ZF and PF of TR (masked), AF and OF
    /// clear, CF the i32 that `carry` pushes. CF is computed now; the other
    /// flags not needed now become an AND record of TR with itself, which
    /// gives them their values (AND's CF, 0, is not pending).
    fn bmi_flags(&mut self, width: u8, need: u32, inst: &Inst, carry: impl FnOnce(&mut Self)) {
        self.flags_begin(need | CF);
        let mut first = true;
        self.szp(TR, need, width, &mut first);
        carry(self);
        self.join(&mut first);
        self.flags_end(first);
        self.g(TR);
        self.s(TA);
        self.g(TR);
        self.s(TB);
        self.record(4, width, ARITH, need | CF, inst);
    }
    fn mask_to(&mut self, width: u8) {
        if width < 64 {
            self.c64(mask(width));
            self.b.and_i64();
        }
    }
    /// Sign-extend the `width`-bit value on the stack to 64 bits.
    fn sext(&mut self, width: u8) {
        match width {
            8 => self.b.op(0xC2),  // i64.extend8_s
            16 => self.b.op(0xC3), // i64.extend16_s
            32 => self.b.op(0xC4), // i64.extend32_s
            _ => {},
        }
    }
    /// Push local `i`'s low `width` bits sign-extended: an i32 below 64
    /// bits, else the i64
    fn sext32(&mut self, i: usize, width: u8) {
        self.g(i);
        if width < 64 {
            self.b.wrap_i64_to_i32();
            match width {
                8 => self.b.op(0xC0),  // i32.extend8_s
                16 => self.b.op(0xC1), // i32.extend16_s
                _ => {},
            }
        }
    }
    /// condition's signed L (`cc` 0xC), GE, LE and G (0xF) of two sext32
    /// values of `width`
    fn signed_compare(&mut self, cc: u8, width: u8) {
        let (less, invert) = (cc >> 1 == 6, cc & 1 != 0);
        self.b.op(match (less, invert, width == 64) {
            (true, false, false) => op::OP_I32LTS,
            (true, true, false) => op::OP_I32GES,
            (false, false, false) => op::OP_I32LES,
            (false, true, false) => op::OP_I32GTS,
            (true, false, true) => op::OP_I64LTS,
            (true, true, true) => op::OP_I64GES,
            (false, false, true) => op::OP_I64LES,
            (false, true, true) => op::OP_I64GTS,
        });
    }
    /// Retry the instruction unless the address in local `i` is canonical
    /// (compatibility mode has no noncanonical addresses).
    fn check_canonical(&mut self, i: usize, start: u64) {
        if self.env.compat {
            return;
        }
        self.g(i);
        self.c64(16);
        self.b.shl_i64();
        self.c64(16);
        self.b.shr_s_i64();
        self.g(i);
        self.b.ne_i64();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
    }
    /// Push the stack slot `delta` bytes from RSP into ADDR, validated as a
    /// `write` access; host address in HOST.
    fn stack(&mut self, delta: i64, write: bool, start: u64) {
        self.stack_sized(delta, self.slot_bytes() as u32, write, start)
    }
    /// stack() of an access of `size` bytes (legacy mode's 16-bit slots,
    /// PUSHAD and POPAD: P7.3)
    fn stack_sized(&mut self, delta: i64, size: u32, write: bool, start: u64) {
        self.lookup_base = Some((4, 0));
        self.g(4);
        if self.env.compat {
            // (in i32: ESP wraps at 4 GiB for free)
            self.b.wrap_i64_to_i32();
            if delta != 0 {
                self.c32(delta as i32);
                self.b.add_i32();
            }
            if self.env.stack16 {
                // (a 16-bit stack's SP wraps at 64 KiB, P7.7)
                self.c32(0xFFFF);
                self.b.and_i32();
            }
            if self.env.segmented {
                // (P7.2(3): the SS base; commit_sp sets ESP)
                self.c32(gp::segment_offsets as i32 + 2 * 4);
                self.b.load_aligned_i32(0);
                self.b.add_i32();
            }
            self.b.extend_unsigned_i32_to_i64();
        }
        else if delta != 0 {
            self.c64(delta as u64);
            self.b.add_i64();
        }
        self.s(ADDR);
        self.host(size, write, start);
        self.si(HOST);
    }
    /// A stack slot's size: 8 bytes, 4 in compatibility mode (P7.2), 2 in
    /// 16-bit code (P7.7)
    fn slot_bytes(&self) -> u64 {
        if self.env.prot16 {
            2
        }
        else if self.env.compat {
            4
        }
        else {
            8
        }
    }
    /// The 64-bit value on the stack wrapped at 4 GiB (compatibility mode's
    /// EIP, ESP and addresses)
    fn wrap32(&mut self) {
        self.c64(0xFFFF_FFFF);
        self.b.and_i64();
    }
    /// RSP to the slot stack_sized(`delta`) addressed (a push): ADDR, or
    /// with segment bases (P7.2(3)), where ADDR holds the SS base too, ESP
    /// plus `delta`
    fn commit_sp(&mut self, delta: i64) {
        if self.env.segmented {
            self.adjust_sp(delta as u64);
        }
        else {
            self.g(ADDR);
            self.s(4);
        }
    }
    /// Retry the instruction being emitted if `segment` holds a null
    /// selector (P7.2(3))
    fn null_check(&mut self, segment: u8) {
        self.c32(gp::segment_is_null as i32 + segment as i32);
        self.b.load_u8(0);
        self.retry_if(self.inst_start);
    }
    /// The 32-bit address (an i64) on the stack plus the base of `segment`
    /// when compiled for segment bases (P7.2(3): string pointers, LEAVE),
    /// which must not be null
    fn segment_base(&mut self, segment: u8) {
        if self.env.segmented && (segment != 1 || self.env.prot16) {
            if segment != 1 && segment != 2 {
                self.null_check(segment);
            }
            self.b.wrap_i64_to_i32();
            self.c32(gp::segment_offsets as i32 + segment as i32 * 4);
            self.b.load_aligned_i32(0);
            self.b.add_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
    }
    /// RSP += `bytes` (in compatibility mode ESP, wrapped; on a 16-bit stack
    /// SP, ESP's high half kept: P7.7)
    fn adjust_sp(&mut self, bytes: u64) {
        if self.env.stack16 {
            self.g(4);
            self.c64(0xFFFF_0000);
            self.b.and_i64();
            self.g(4);
            self.c64(bytes);
            self.b.add_i64();
            self.c64(0xFFFF);
            self.b.and_i64();
            self.b.or_i64();
            self.s(4);
            return;
        }
        self.g(4);
        if self.env.compat {
            self.b.wrap_i64_to_i32();
            self.c32(bytes as i32);
            self.b.add_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
        else {
            self.c64(bytes);
            self.b.add_i64();
        }
        self.s(4);
    }

    // EFLAGS ------------------------------------------------------------

    /// Combine the i32 terms pushed so far (see flags_begin/flags_end).
    fn join(&mut self, first: &mut bool) {
        if !*first {
            self.b.or_i32();
        }
        *first = false;
    }
    fn flags_begin(&mut self, need: u32) {
        self.gi(FL);
        self.c32(!need as i32);
        self.b.and_i32();
    }
    fn flags_end(&mut self, first: bool) {
        if first {
            self.c32(0);
        }
        self.b.or_i32();
        self.si(FL);
    }
    /// i32: bit `bit` of i64 local `i`, moved to bit `to`.
    fn bit_of(&mut self, i: usize, bit: u8, to: u8) {
        self.g(i);
        if bit != 0 {
            self.c64(bit as u64);
            self.b.shr_u_i64();
        }
        self.b.wrap_i64_to_i32();
        self.c32(1);
        self.b.and_i32();
        if to != 0 {
            self.c32(to as i32);
            self.b.shl_i32();
        }
    }
    /// i32: 1 when the low byte of local `i` has even parity.
    fn parity(&mut self, i: usize) {
        self.g(i);
        self.b.wrap_i64_to_i32();
        self.c32(0xFF);
        self.b.and_i32();
        self.b.popcnt_i32();
        self.c32(1);
        self.b.and_i32();
        self.c32(1);
        self.b.xor_i32();
    }
    fn is_zero(&mut self, i: usize) {
        self.g(i);
        self.b.op(op::OP_I64EQZ);
    }
    /// Compatibility mode: last_op1 = the low 32 bits of i64 local `i` (see
    /// Emitter::last_op1)
    fn note_last_op1(&mut self, i: usize) {
        if self.last_op1_memory {
            self.c32(gp::last_op1 as i32);
            self.g(i);
            self.b.wrap_i64_to_i32();
            self.b.store_aligned_i32(0);
        }
    }
    /// Whether the 32-bit interpreter's last_op1 is kept (compatibility and
    /// legacy mode)
    fn tracks_last_op1(&self) -> bool { self.last_op1_memory }
    /// Push last_op1 (i32)
    fn push_last_op1(&mut self) { self.b.load_fixed_i32(gp::last_op1 as u32); }
    /// Compatibility mode: SF, ZF, PF and AF after a multiply as the 32-bit
    /// interpreter's lazy EFLAGS give them (cpu::arith::mul32 and kin: the
    /// result TR at `width`; AF from last_op1 and that result, getaf), each
    /// in `need`, joined to what is on the stack
    fn legacy_mul_flags(&mut self, width: u8, need: u32, first: &mut bool) {
        self.szp(TR, need, width, first);
        if need & AF != 0 {
            self.legacy_af();
            self.join(first);
        }
    }
    /// i32: the AF the 32-bit interpreter's lazy EFLAGS give a result in TR
    /// that its operation left to last_op1: (last_op1 ^ (result - last_op1)
    /// ^ result) & AF (cpu::misc_instr::getaf, not a subtraction)
    fn legacy_af(&mut self) {
        self.push_last_op1();
        self.g(TR);
        self.b.wrap_i64_to_i32();
        self.push_last_op1();
        self.b.sub_i32();
        self.b.xor_i32();
        self.g(TR);
        self.b.wrap_i64_to_i32();
        self.b.xor_i32();
        self.c32(AF as i32);
        self.b.and_i32();
    }
    /// Compatibility mode: `bits` (of SF, ZF, PF, AF and OF) pending in the
    /// lazy record as the 32-bit interpreter's EFLAGS leave them after a
    /// result TR at `width` of an operation that kept last_op1 (shifts,
    /// multiplies, SHLD, SHRD, BSF, BSR): its getters take SF, ZF and PF of
    /// the result, AF and OF of last_op1 and the result as of an addition
    /// (cpu::misc_instr::getaf, getof), which x64_page_flags gives as ADD of
    /// last_op1 and result - last_op1. It replaces any pending record: these
    /// instructions write every flag.
    fn legacy_record(&mut self, width: u8, bits: u32) {
        self.push_last_op1();
        self.b.extend_unsigned_i32_to_i64();
        self.s(FA);
        self.g(TR);
        self.g(FA);
        self.b.sub_i64();
        self.mask_to(32);
        self.s(FB);
        self.g(TR);
        self.s(FR);
        let size = match width {
            8 => 0,
            16 => 1,
            _ => 2,
        };
        self.c32((size << 20 | bits) as i32);
        self.si(FK);
    }
    /// Compatibility mode (P7.2): a 32-bit ROL, ROR, SHL, SHR or SAR (code
    /// 0, 1, 4 or 6, 5, 7) as the 32-bit interpreter computes it
    /// (cpu::arith::rol32 and kin): the count masked to 5 bits; CF and OF by
    /// its formulas for any nonzero count (ROL: OF = CF ^ MSB, ROR: the two
    /// top bits, SHL: CF ^ MSB, SHR: the operand's MSB, SAR: 0); SHL, SHR
    /// and SAR then leave SF, ZF and PF of the result and AF from last_op1;
    /// a zero count changes no flag. `count`: an immediate, else CL. The
    /// EFLAGS bits in `need` only; of SHL, SHR and SAR, SF, ZF, PF and AF
    /// that no later instruction reads (only a way out may observe them,
    /// P4.23) stay pending (legacy_record), as Tier-0 leaves them to the
    /// interpreter's lazy EFLAGS: returned, they are not written into FL
    fn legacy_shift32(
        &mut self,
        inst: &Inst,
        code: u8,
        dst: Opnd,
        count: Option<u8>,
        need: u32,
    ) -> u32 {
        let rotate = code <= 1;
        self.read_dst(dst, 32, true, inst);
        self.s(TA);
        match count {
            Some(count) => self.c64((count & 31) as u64),
            None => {
                self.g(1);
                self.c64(31);
                self.b.and_i64();
            },
        }
        self.s(TB);
        self.g(TA);
        self.b.wrap_i64_to_i32();
        self.g(TB);
        self.b.wrap_i64_to_i32();
        match code {
            0 => self.b.rotl_i32(),
            1 => self.b.rotr_i32(),
            5 => self.b.shr_u_i32(),
            7 => self.b.shr_s_i32(),
            _ => self.b.shl_i32(),
        }
        self.b.extend_unsigned_i32_to_i64();
        self.s(TR);
        self.write_dst(dst, 32, TR);
        let need = need & if rotate { CF | OF } else { ARITH };
        if need == 0 || count.is_some_and(|c| c & 31 == 0) {
            return 0;
        }
        // (a count of zero keeps every flag: the record too, see Op::Shift)
        let lazy = if rotate || !self.env.exit_flags {
            0
        }
        else {
            need & (SF | ZF | PF | AF) & !inst.live_out
        };
        let need = need & !lazy;
        if count.is_none() {
            self.g(TB);
            self.b.op(op::OP_I64EQZ);
            self.b.eqz_i32();
            self.b.if_void();
        }
        if lazy != 0 {
            self.legacy_record(32, lazy);
        }
        self.flags_begin(need);
        let mut first = true;
        // i32 0/1: bit `bit` of TA (the operand) or TR, or at a count from TB
        let bit = |e: &mut Self, local: usize, shift: Option<(i64, bool)>| {
            e.g(local);
            match shift {
                // (by the count plus a constant, or the constant minus it)
                Some((k, minus)) => {
                    if minus {
                        e.c64(k as u64);
                        e.g(TB);
                        e.b.sub_i64();
                    }
                    else {
                        e.g(TB);
                        e.c64(k as u64);
                        e.b.add_i64();
                    }
                    e.b.shr_u_i64();
                },
                None => {},
            }
            e.b.wrap_i64_to_i32();
            e.c32(1);
            e.b.and_i32();
        };
        let msb = |e: &mut Self, local: usize| {
            e.g(local);
            e.c64(31);
            e.b.shr_u_i64();
            e.b.wrap_i64_to_i32();
            e.c32(1);
            e.b.and_i32();
        };
        let carry = |e: &mut Self| match code {
            0 => bit(e, TR, None),
            1 => msb(e, TR),
            4 | 6 => bit(e, TA, Some((32, true))),
            _ => bit(e, TA, Some((-1, false))),
        };
        if need & CF != 0 {
            carry(self);
            self.join(&mut first);
        }
        if need & OF != 0 && code != 7 {
            match code {
                0 => {
                    bit(self, TR, None);
                    msb(self, TR);
                    self.b.xor_i32();
                },
                1 => {
                    msb(self, TR);
                    self.g(TR);
                    self.c64(30);
                    self.b.shr_u_i64();
                    self.b.wrap_i64_to_i32();
                    self.c32(1);
                    self.b.and_i32();
                    self.b.xor_i32();
                },
                4 | 6 => {
                    carry(self);
                    msb(self, TR);
                    self.b.xor_i32();
                },
                _ => msb(self, TA),
            }
            self.c32(11);
            self.b.shl_i32();
            self.join(&mut first);
        }
        if !rotate {
            self.szp(TR, need, 32, &mut first);
            if need & AF != 0 {
                self.legacy_af();
                self.join(&mut first);
            }
        }
        self.flags_end(first);
        if count.is_none() {
            self.b.block_end();
        }
        lazy
    }
    /// SF, ZF, PF of local `i` (masked to `width`).
    fn szp(&mut self, i: usize, need: u32, width: u8, first: &mut bool) {
        if need & PF != 0 {
            self.parity(i);
            self.c32(2);
            self.b.shl_i32();
            self.join(first);
        }
        if need & ZF != 0 {
            self.is_zero(i);
            self.c32(6);
            self.b.shl_i32();
            self.join(first);
        }
        if need & SF != 0 {
            self.bit_of(i, width - 1, 7);
            self.join(first);
        }
    }
    /// Flags of ALU `code` over TA (a), TB (b), TR (result, masked). ADC and
    /// SBB read their CF input from FL before it is replaced.
    fn alu_flags(&mut self, code: u8, width: u8, need: u32) {
        if need == 0 {
            return;
        }
        let logic = matches!(code, 1 | 4 | 6);
        let add = matches!(code, 0 | 2);
        let carry = matches!(code, 2 | 3);
        self.flags_begin(need);
        let mut first = true;
        self.szp(TR, need, width, &mut first);
        if !logic {
            if need & CF != 0 {
                let (x, y) = if add { (TR, TA) } else { (TA, TB) };
                self.g(x);
                self.g(y);
                self.b.ltu_i64();
                if carry {
                    self.g(x);
                    self.g(y);
                    self.b.eq_i64();
                    self.gi(CI);
                    self.b.and_i32();
                    self.b.or_i32();
                }
                self.join(&mut first);
            }
            if need & AF != 0 {
                self.g(TA);
                self.g(TB);
                self.b.xor_i64();
                self.g(TR);
                self.b.xor_i64();
                self.b.wrap_i64_to_i32();
                self.c32(AF as i32);
                self.b.and_i32();
                self.join(&mut first);
            }
            if need & OF != 0 {
                if add {
                    self.g(TA);
                    self.g(TR);
                    self.b.xor_i64();
                    self.g(TB);
                    self.g(TR);
                    self.b.xor_i64();
                }
                else {
                    self.g(TA);
                    self.g(TB);
                    self.b.xor_i64();
                    self.g(TA);
                    self.g(TR);
                    self.b.xor_i64();
                }
                self.b.and_i64();
                self.s(TX);
                self.bit_of(TX, width - 1, 11);
                self.join(&mut first);
            }
        }
        self.flags_end(first);
    }
    /// After a producer computed the `eager` part of the flags it `writes`:
    /// the rest becomes the lazy record (operands TA, TB; kind; carry CI).
    fn record(&mut self, code: u8, width: u8, writes: u32, eager: u32, inst: &Inst) {
        let pending = writes & !eager;
        if pending != 0 || inst.keep {
            self.g(TA);
            self.s(FA);
            self.g(TB);
            self.s(FB);
            self.g(TR);
            self.s(FR);
        }
        if pending != 0 {
            let kind = (code as u32) << 16 | (width.trailing_zeros() - 3) << 20 | pending;
            self.c32(kind as i32);
            if matches!(code, 2 | 3) {
                self.gi(CI);
                self.c32(23);
                self.b.shl_i32();
                self.b.or_i32();
            }
        }
        else {
            self.c32(0);
        }
        self.si(FK);
    }
    /// record() of INC or DEC in legacy mode (M8): FA holds the result, as FR
    /// does, and RECORD_UNIT says the operands are result -/+ 1 and 1
    /// (pages::x64_page_flags): a loop counter's old value and the constant
    /// are no values the loop carries
    fn unit_record(&mut self, dec: bool, width: u8, writes: u32, eager: u32, inst: &Inst) {
        let pending = writes & !eager;
        if pending != 0 || inst.keep {
            self.g(TR);
            self.s(FA);
            self.g(TR);
            self.s(FR);
        }
        if pending != 0 {
            let code = if dec { 5 } else { 0 };
            self.c32(
                ((code as u32) << 16 | (width.trailing_zeros() - 3) << 20 | RECORD_UNIT | pending)
                    as i32,
            );
        }
        else {
            self.c32(0);
        }
        self.si(FK);
    }
    /// A partial writer computed all of `bits` into FL: they are no longer
    /// pending in the record.
    fn written(&mut self, bits: u32) {
        self.gi(FK);
        self.c32(!bits as i32);
        self.b.and_i32();
        self.si(FK);
    }
    /// Make `bits` of FL current before reading them.
    fn materialize_if(&mut self, bits: u32) {
        if bits & ARITH == 0 {
            return;
        }
        self.gi(FK);
        self.c32((bits & ARITH) as i32);
        self.b.and_i32();
        self.b.hint(false);
        self.b.if_void();
        self.gi(FK);
        self.g(FA);
        self.g(FB);
        self.gi(FL);
        self.b.call_signature(
            "x64_page_flags",
            Signature::new(
                &[WasmType::I32, WasmType::I64, WasmType::I64, WasmType::I32],
                &[WasmType::I32],
            ),
        );
        self.si(FL);
        self.c32(0);
        self.si(FK);
        self.b.block_end();
    }
    /// Push condition `cc` (i32 0/1): from the kept producer operands when
    /// fused, else from FL.
    fn condition(&mut self, cc: u8, fused: Option<Known>) {
        // (an odd condition, the even one's opposite: the opposite
        // comparison where there is one, else i32.eqz at the end)
        let invert = cc & 1 != 0;
        match fused {
            Some(Known::Sub(w)) => match cc >> 1 {
                0 => {
                    self.g(FA);
                    self.g(FB);
                    self.b.xor_i64();
                    self.g(FA);
                    self.g(FR);
                    self.b.xor_i64();
                    self.b.and_i64();
                    self.s(TX);
                    self.bit_of(TX, w - 1, 0);
                },
                1..=3 => {
                    self.g(FA);
                    self.g(FB);
                    self.b.op(match (cc >> 1, invert) {
                        (1, false) => op::OP_I64LTU,
                        (1, true) => op::OP_I64GEU,
                        (2, false) => op::OP_I64EQ,
                        (2, true) => op::OP_I64NE,
                        (3, false) => op::OP_I64LEU,
                        _ => op::OP_I64GTU,
                    });
                    return;
                },
                4 => self.bit_of(FR, w - 1, 0),
                5 => self.parity(FR),
                _ => {
                    // L/GE, LE/G: signed, in i32 below 64 bits
                    for x in [FA, FB] {
                        self.sext32(x, w);
                    }
                    self.signed_compare(cc, w);
                    return;
                },
            },
            Some(Known::Float(double)) => {
                // (ordered: SF, OF and PF clear, so L is false and LE is E)
                let compare = match (cc >> 1, invert) {
                    (1, false) => [op::OP_F32LT, op::OP_F64LT],
                    (1, true) => [op::OP_F32GE, op::OP_F64GE],
                    (2 | 7, false) => [op::OP_F32EQ, op::OP_F64EQ],
                    (2 | 7, true) => [op::OP_F32NE, op::OP_F64NE],
                    (3, false) => [op::OP_F32LE, op::OP_F64LE],
                    (3, true) => [op::OP_F32GT, op::OP_F64GT],
                    _ => return self.c32(invert as i32),
                };
                self.float_of(FA, double);
                self.float_of(FB, double);
                self.b.op(compare[double as usize]);
                return;
            },
            Some(Known::Logic(w)) | Some(Known::Result(w)) => match cc >> 1 {
                0 | 1 => self.c32(0),
                2 | 3 => {
                    self.g(FR);
                    if invert {
                        self.c64(0);
                        self.b.ne_i64();
                    }
                    else {
                        self.b.op(op::OP_I64EQZ);
                    }
                    return;
                },
                4 | 6 => self.bit_of(FR, w - 1, 0),
                5 => self.parity(FR),
                _ => {
                    // LE/G: the result's sign and zero (OF clear)
                    self.sext32(FR, w);
                    if w == 64 {
                        self.c64(0);
                    }
                    else {
                        self.c32(0);
                    }
                    self.signed_compare(cc, w);
                    return;
                },
            },
            None => {
                let bit = |e: &mut Self, shift: i32| {
                    e.gi(FL);
                    if shift != 0 {
                        e.c32(shift);
                        e.b.shr_u_i32();
                    }
                };
                match cc >> 1 {
                    0 => bit(self, 11),
                    1 => bit(self, 0),
                    2 => bit(self, 6),
                    3 => {
                        self.gi(FL);
                        self.c32((CF | ZF) as i32);
                        self.b.and_i32();
                        self.c32(0);
                        self.b.ne_i32();
                    },
                    4 => bit(self, 7),
                    5 => bit(self, 2),
                    6 => {
                        bit(self, 7);
                        bit(self, 11);
                        self.b.xor_i32();
                    },
                    _ => {
                        bit(self, 7);
                        bit(self, 11);
                        self.b.xor_i32();
                        bit(self, 6);
                        self.b.or_i32();
                    },
                }
                if cc >> 1 != 3 {
                    self.c32(1);
                    self.b.and_i32();
                }
            },
        }
        if invert {
            self.b.eqz_i32();
        }
    }
}

impl Emitter<'_> {
    fn instruction(&mut self, inst: &Inst, index: &BTreeMap<u16, usize>) {
        // (an access cache lookup takes a kept translation by the base
        // register of this instruction's operand, P4.21: set by address(),
        // stack() and the string instructions, never left from another)
        self.lookup_base = None;
        self.inst_start = inst.d.start.0;
        // (XMM locals, P4.17: the registers this instruction uses, loaded
        // now, in code every path runs; other vector code finds memory current)
        if self.env.xmm_locals {
            match xmm_use(&inst.op, self.env.sse_fast_check) {
                XmmUse::Hold(registers) => {
                    // (what it overwrites whole needs no load)
                    let overwritten = xmm_overwritten(&inst.op);
                    self.xmm_hold(registers & self.xmm_worth & !overwritten);
                    self.xmm_claim(registers & self.xmm_worth & overwritten);
                },
                XmmUse::Lanes => {},
                XmmUse::Memory => self.xmm_release(),
                XmmUse::None => {},
            }
        }
        if self.env.sse_fast_check {
            self.xmm_facts(&inst.op);
        }
        // (other vector code may write bits 255:128 by their memory)
        if matches!(xmm_use(&inst.op, self.env.sse_fast_check), XmmUse::Memory) {
            self.ymm_zeroed = 0;
        }
        if unsafe { (*(&raw const SIZE_STATS)).is_none() } {
            return self.instruction_inner(inst, index);
        }
        let before = self.b.body_len();
        self.instruction_inner(inst, index);
        let name = format!("{:?}", inst.op);
        let name = name
            .split([' ', '{', '('])
            .next()
            .unwrap_or("?")
            .to_string();
        size_note(name, self.b.body_len() - before);
    }
    fn instruction_inner(&mut self, inst: &Inst, index: &BTreeMap<u16, usize>) {
        let start = inst.d.start.0;
        let next = inst.d.next.0;
        let need = inst.writes & inst.live_out;
        if inst.span_straddle && !matches!(inst.op, Op::Step) {
            // (its bytes on the span's next page: as compiled once that page
            // was verified, else step it; P7.3b)
            self.b.get_local(self.verified.as_ref().unwrap());
            self.c32(1 << ((next - 1) / PAGE as u64));
            self.b.and_i32();
            self.b.eqz_i32();
            self.b.if_void();
            self.leave_to(self.f().step, start);
            self.b.block_end();
        }
        if let (Some((word, count)), false) = (inst.straddle, matches!(inst.op, Op::Step)) {
            // the next page still fetches as compiled, else step it
            self.c64(word);
            self.c32(count as i32);
            self.b.call_signature(
                "x64_page_straddle",
                Signature::new(&[WasmType::I64, WasmType::I32], &[WasmType::I32]),
            );
            self.b.eqz_i32();
            self.b.if_void();
            self.leave_to(self.f().step, start);
            self.b.block_end();
        }
        match inst.op {
            Op::Step => {
                self.leave_to(self.f().step, start);
                return;
            },
            Op::FarCall {
                selector,
                offset,
                width,
            } => self.far_transfer(0, offset, selector as u32, width, start, next),
            Op::FarRet { pop, width } => self.far_transfer(1, pop as u32, 0, width, start, next),
            Op::Nop => {},
            // compatibility mode's x87 (P7.2a)
            Op::X87 {
                opcode,
                modrm,
                io,
                address,
            } => self.x87(inst, opcode, modrm, io, address),
            Op::Fnstsw if self.env.compat => {
                // (P7.3: fpu_load_status_word with TOP from the x87 cache,
                // which stays open: i586 code compares with FCOMP, FNSTSW AX
                // and SAHF, 616.fcompare)
                self.x87_check(start);
                self.x87_cache_open();
                let top = self.x87_cache.as_ref().unwrap().top.unsafe_clone();
                self.b.load_fixed_u16(gp::fpu_status_word as u32);
                self.c32(!(7 << 11));
                self.b.and_i32();
                self.b.get_local(&top);
                self.c32(11);
                self.b.shl_i32();
                self.b.or_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(RAX, 16);
            },
            Op::Fnstsw => {
                self.x87_check(start);
                self.x87_close();
                self.b.call_signature(
                    "fpu_load_status_word",
                    Signature::new(&[], &[WasmType::I32]),
                );
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(RAX, 16);
            },
            Op::X87Flags { name, r } => {
                // (the helper reads and writes FLAGS in memory)
                self.x87_check(start);
                self.materialize_if(ARITH);
                self.c32(gp::flags as i32);
                self.gi(FL);
                self.b.store_aligned_i32(0);
                self.c32(gp::flags_changed as i32);
                self.c32(0);
                self.b.store_aligned_i32(0);
                self.x87_close();
                self.c32(r as i32);
                self.b
                    .call_signature(name, Signature::new(&[WasmType::I32], &[]));
                self.b.load_fixed_i32(gp::flags as u32);
                self.si(FL);
            },
            Op::Fcmov { cc, r } => {
                self.x87_check(start);
                self.materialize_if(inst.flags_read);
                self.x87_close();
                self.condition(cc, None);
                self.c32(r as i32);
                self.b.call_signature(
                    "fpu_fcmovcc",
                    Signature::new(&[WasmType::I32, WasmType::I32], &[]),
                );
            },
            Op::Mov { width, dst, src } => match dst {
                Opnd::Reg(r) => {
                    self.read(src, width, inst);
                    self.set_reg(r, width);
                },
                Opnd::Mem(a) => {
                    self.prepare_store(&a, width, inst);
                    self.gi(HOST);
                    self.read(src, width, inst);
                    self.store(width);
                },
                Opnd::Imm(_) => unreachable!(),
            },
            Op::Extend {
                width,
                from,
                signed,
                dst,
                src,
            } => {
                self.read(src, from, inst);
                if signed {
                    self.sext(from);
                }
                self.set_reg(dst, width);
            },
            Op::Lea {
                width,
                dst,
                address,
            } if width == 32 && self.env.i32_ops => {
                // (P4.20: the low half of the address in i32)
                self.address32(&address, next);
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(dst, 32);
            },
            Op::Lea {
                width,
                dst,
                address,
            } => {
                self.address(&address, next, false);
                self.set_reg(dst, width);
            },
            Op::Alu {
                code,
                width,
                dst,
                src,
            } => {
                if matches!(code, 5 | 6)
                    && matches!((dst, src), (Opnd::Reg(a), Opnd::Reg(b)) if a == b)
                {
                    // SUB/XOR of a register with itself
                    if code == 5 && self.tracks_last_op1() {
                        self.get_reg(dst.reg().unwrap(), width);
                        self.s(TA);
                        self.note_last_op1(TA);
                    }
                    self.c64(0);
                    self.set_reg(dst.reg().unwrap(), width);
                    // (P4.23: its EFLAGS only where read or observable,
                    // not as XOR EDX, EDX's before a CMP)
                    if !self.env.exit_flags
                        || inst.writes & (inst.live_out | inst.exit_live) != 0
                        || inst.keep
                    {
                        self.gi(FL);
                        self.c32(!ARITH as i32);
                        self.b.and_i32();
                        self.c32((ZF | PF) as i32);
                        self.b.or_i32();
                        self.si(FL);
                        self.c32(0);
                        self.si(FK);
                    }
                    if inst.keep {
                        for l in [FA, FB, FR] {
                            self.c64(0);
                            self.s(l);
                        }
                    }
                }
                else {
                    if matches!(code, 2 | 3) {
                        self.materialize_if(CF);
                        self.gi(FL);
                        self.c32(1);
                        self.b.and_i32();
                        self.si(CI);
                    }
                    self.read_dst(dst, width, code != 7, inst);
                    self.s(TA);
                    self.read(src, width, inst);
                    self.s(TB);
                    if matches!(code, 0 | 2 | 3 | 5 | 7) {
                        self.note_last_op1(TA);
                    }
                    if width == 32 && self.env.i32_ops {
                        let carry = matches!(code, 2 | 3).then_some(self.w[CI].unsafe_clone());
                        self.op32(TA, Some(TB), |b| {
                            match code {
                                0 | 2 => b.add_i32(),
                                1 => b.or_i32(),
                                3 | 5 | 7 => b.sub_i32(),
                                4 => b.and_i32(),
                                _ => b.xor_i32(),
                            }
                            if let Some(carry) = carry {
                                b.get_local(&carry);
                                if code == 2 {
                                    b.add_i32();
                                }
                                else {
                                    b.sub_i32();
                                }
                            }
                        });
                    }
                    else {
                        self.g(TA);
                        self.g(TB);
                        match code {
                            0 | 2 => self.b.add_i64(),
                            1 => self.b.or_i64(),
                            3 | 5 | 7 => self.b.sub_i64(),
                            4 => self.b.and_i64(),
                            _ => self.b.xor_i64(),
                        }
                        if matches!(code, 2 | 3) {
                            self.gi(CI);
                            self.b.extend_unsigned_i32_to_i64();
                            if code == 2 {
                                self.b.add_i64();
                            }
                            else {
                                self.b.sub_i64();
                            }
                        }
                        if !matches!(code, 1 | 4 | 6) {
                            self.mask_to(width);
                        }
                    }
                    self.s(TR);
                    if code != 7 {
                        self.write_dst(dst, width, TR);
                    }
                    self.alu_flags(code, width, need);
                    self.record(code, width, ARITH, need, inst);
                }
            },
            Op::Test { width, a, b } => {
                self.read(a, width, inst);
                self.s(TA);
                self.read(b, width, inst);
                self.s(TB);
                if width == 32 && self.env.i32_ops {
                    self.op32(TA, Some(TB), |b| b.and_i32());
                }
                else {
                    self.g(TA);
                    self.g(TB);
                    self.b.and_i64();
                }
                self.s(TR);
                self.alu_flags(4, width, need);
                self.record(4, width, ARITH, need, inst);
            },
            Op::IncDec { dec, width, dst } => {
                // CF survives: its pending value must not be lost with the record
                self.materialize_if(CF);
                self.read_dst(dst, width, true, inst);
                self.s(TA);
                self.note_last_op1(TA);
                self.c64(1);
                self.s(TB);
                if width == 32 && self.env.i32_ops {
                    self.op32(TA, Some(TB), |b| {
                        if dec {
                            b.sub_i32()
                        }
                        else {
                            b.add_i32()
                        }
                    });
                }
                else {
                    self.g(TA);
                    self.c64(1);
                    if dec {
                        self.b.sub_i64();
                    }
                    else {
                        self.b.add_i64();
                    }
                    self.mask_to(width);
                }
                self.s(TR);
                self.write_dst(dst, width, TR);
                self.alu_flags(if dec { 5 } else { 0 }, width, need);
                if self.env.compat {
                    self.unit_record(dec, width, ARITH & !CF, need, inst);
                }
                else {
                    self.record(if dec { 5 } else { 0 }, width, ARITH & !CF, need, inst);
                }
            },
            Op::Neg { width, dst } => {
                self.read_dst(dst, width, true, inst);
                self.s(TB);
                self.c64(0);
                self.s(TA);
                self.note_last_op1(TA);
                if width == 32 && self.env.i32_ops {
                    self.op32(TA, Some(TB), |b| b.sub_i32());
                }
                else {
                    self.c64(0);
                    self.g(TB);
                    self.b.sub_i64();
                    self.mask_to(width);
                }
                self.s(TR);
                self.write_dst(dst, width, TR);
                self.alu_flags(5, width, need);
                self.record(5, width, ARITH, need, inst);
            },
            Op::Not { width, dst } => {
                self.read_dst(dst, width, true, inst);
                if width == 32 && self.env.i32_ops {
                    self.s(TA);
                    self.op32(TA, None, |b| {
                        b.const_i32(-1);
                        b.xor_i32();
                    });
                }
                else {
                    self.c64(mask(width));
                    self.b.xor_i64();
                }
                self.s(TR);
                self.write_dst(dst, width, TR);
            },
            Op::Shift {
                code,
                width,
                dst,
                count: Some(count),
            } => {
                // (P4.23: only what is read or observable)
                let need = if self.env.exit_flags {
                    inst.writes & (inst.live_out | inst.exit_live)
                }
                else {
                    inst.writes
                };
                let lazy = if self.env.compat {
                    self.legacy_shift32(inst, code, dst, Some(count), need)
                }
                else {
                    self.shift_immediate(inst, code, width, dst, count, need);
                    0
                };
                self.written(inst.writes & !lazy);
            },
            Op::Shift {
                code,
                width,
                dst,
                count: None,
            } => {
                // a zero count keeps every flag
                self.materialize_if(inst.flags_read);
                let lazy = if self.env.compat {
                    self.legacy_shift32(inst, code, dst, None, inst.writes)
                }
                else {
                    self.shift_cl(inst, code, width, dst, inst.writes);
                    0
                };
                self.written(inst.writes & !lazy);
            },
            Op::ShiftCall {
                code,
                width,
                dst,
                count,
            } => {
                self.materialize_if(ARITH);
                self.read_dst(dst, width, true, inst);
                self.s(TA);
                self.g(TA);
                match count {
                    Some(count) => self.c32(count as i32),
                    None => {
                        self.g(1);
                        self.b.wrap_i64_to_i32();
                    },
                }
                self.gi(FL);
                self.c32(code as i32 | (width as i32) << 8);
                if self.tracks_last_op1() {
                    // (compatibility mode, P7.2: the 32-bit interpreter's
                    // rules, which leave AF to last_op1)
                    self.push_last_op1();
                    self.b.call_signature(
                        "x64_page_shift32",
                        Signature::new(
                            &[
                                WasmType::I64,
                                WasmType::I32,
                                WasmType::I32,
                                WasmType::I32,
                                WasmType::I32,
                            ],
                            &[WasmType::I64],
                        ),
                    );
                }
                else {
                    self.b.call_signature(
                        "x64_page_shift",
                        Signature::new(
                            &[WasmType::I64, WasmType::I32, WasmType::I32, WasmType::I32],
                            &[WasmType::I64],
                        ),
                    );
                }
                self.s(TV);
                self.g(TV);
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
                self.s(TR);
                self.write_dst(dst, width, TR);
                self.g(TV);
                self.c64(32);
                self.b.shr_u_i64();
                self.b.wrap_i64_to_i32();
                self.si(FL);
                self.written(ARITH);
            },
            Op::Imul { width, dst, a, b } => {
                self.read(a, width, inst);
                self.s(TA);
                self.read(b, width, inst);
                self.s(TB);
                if width == 64 {
                    self.g(TA);
                    self.g(TB);
                    self.b.mul_i64();
                    self.s(TR);
                }
                else if width == 32 && self.env.i32_ops {
                    // (P4.20: the full product from sign-extended halves)
                    for x in [TA, TB] {
                        self.g(x);
                        self.b.wrap_i64_to_i32();
                        self.b.extend_signed_i32_to_i64();
                    }
                    self.b.mul_i64();
                    self.s(TV);
                    self.op32(TV, None, |_| {});
                    self.s(TR);
                }
                else {
                    self.g(TA);
                    self.sext(width);
                    self.g(TB);
                    self.sext(width);
                    self.b.mul_i64();
                    self.s(TV);
                    self.g(TV);
                    self.mask_to(width);
                    self.s(TR);
                }
                self.g(TR);
                self.set_reg(dst, width);
                let need = if self.env.exit_flags {
                    inst.writes & (inst.live_out | inst.exit_live)
                }
                else {
                    inst.writes
                };
                // (compatibility mode: SF, ZF, PF and AF only a way out may
                // observe stay pending, legacy_record)
                let lazy = if self.env.compat && self.env.exit_flags {
                    need & (SF | ZF | PF | AF) & !inst.live_out
                }
                else {
                    0
                };
                if need != 0 {
                    self.flags_begin(need & !lazy);
                    if width == 64 {
                        // the high half is not the sign extension of the low
                        self.mul_high(TA, TB, true);
                        self.g(TR);
                        self.c64(63);
                        self.b.shr_s_i64();
                        self.b.ne_i64();
                    }
                    else {
                        self.g(TR);
                        self.sext(width);
                        self.g(TV);
                        self.b.ne_i64();
                    }
                    self.c32((CF | OF) as i32);
                    self.b.mul_i32();
                    self.c32(need as i32);
                    self.b.and_i32();
                    if self.env.compat {
                        self.legacy_mul_flags(width, need & !lazy, &mut false);
                    }
                    self.flags_end(false);
                    if lazy != 0 {
                        self.legacy_record(width, lazy);
                    }
                    self.written(need & !lazy);
                }
            },
            Op::MulWide { signed, width, src } => {
                self.get_reg(RAX, width);
                self.s(TA);
                self.read(src, width, inst);
                self.s(TB);
                if width == 64 {
                    self.g(TA);
                    self.g(TB);
                    self.b.mul_i64();
                    self.s(TR);
                    self.mul_high(TA, TB, signed);
                    self.s(TV);
                }
                else {
                    // (32 or, in 16-bit code, 16 bits: EDX:EAX or DX:AX)
                    self.g(TA);
                    if signed {
                        self.sext(width);
                    }
                    self.g(TB);
                    if signed {
                        self.sext(width);
                    }
                    self.b.mul_i64();
                    self.s(TC);
                    self.g(TC);
                    self.mask_to(width);
                    self.s(TR);
                    self.g(TC);
                    self.c64(width as u64);
                    self.b.shr_u_i64();
                    self.mask_to(width);
                    self.s(TV);
                }
                self.g(TR);
                self.set_reg(RAX, width);
                self.g(TV);
                self.set_reg(RDX, width);
                let need = if self.env.exit_flags {
                    inst.writes & (inst.live_out | inst.exit_live)
                }
                else {
                    inst.writes
                };
                // (compatibility mode: SF, ZF, PF and AF only a way out may
                // observe stay pending, legacy_record)
                let lazy = if self.env.compat && self.env.exit_flags {
                    need & (SF | ZF | PF | AF) & !inst.live_out
                }
                else {
                    0
                };
                if need != 0 {
                    self.flags_begin(need & !lazy);
                    match (signed, width) {
                        (false, _) => {
                            self.g(TV);
                            self.c64(0);
                            self.b.ne_i64();
                        },
                        (true, 64) => {
                            self.g(TV);
                            self.g(TR);
                            self.c64(63);
                            self.b.shr_s_i64();
                            self.b.ne_i64();
                        },
                        (true, _) => {
                            self.g(TR);
                            self.sext(width);
                            self.g(TC);
                            self.b.ne_i64();
                        },
                    }
                    self.c32((CF | OF) as i32);
                    self.b.mul_i32();
                    self.c32(need as i32);
                    self.b.and_i32();
                    if self.env.compat {
                        self.legacy_mul_flags(width, need & !lazy, &mut false);
                    }
                    self.flags_end(false);
                    if lazy != 0 {
                        self.legacy_record(width, lazy);
                    }
                    self.written(need & !lazy);
                }
            },
            // (compatibility mode: 4-byte slots, ESP and EIP wrapped; P7.2)
            Op::Push { src } => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.read(src, width, inst);
                self.s(TV);
                self.stack(-(bytes as i64), true, start);
                self.gi(HOST);
                self.g(TV);
                self.store(width);
                self.commit_sp(-(bytes as i64));
            },
            Op::Pushf => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.materialize_if(ARITH);
                self.stack(-(bytes as i64), true, start);
                self.gi(HOST);
                self.gi(FL);
                self.c32(!0x30000);
                self.b.and_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.store(width);
                self.commit_sp(-(bytes as i64));
            },
            Op::Pop { dst } => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.stack(0, false, start);
                self.gi(HOST);
                self.load(width);
                self.s(TV);
                self.adjust_sp(bytes);
                self.g(TV);
                self.set_reg(dst, width);
            },
            // (legacy mode, P7.3: legacy_template)
            Op::LoopJump { kind, cx, target } => {
                let (count, width) = (register(1, 32, false), if cx { 16 } else { 32 });
                if kind < 3 {
                    // (LOOP: the count less one, EFLAGS unchanged)
                    self.get_reg(count, width);
                    self.c64(1);
                    self.b.sub_i64();
                    self.set_reg(count, width);
                }
                self.materialize_if(inst.flags_read);
                self.get_reg(count, width);
                self.b.wrap_i64_to_i32();
                self.b.eqz_i32();
                if kind < 3 {
                    self.b.eqz_i32();
                }
                if kind < 2 {
                    // (LOOPE while ZF, LOOPNE while not)
                    self.condition(if kind == 1 { 4 } else { 5 }, None);
                    self.b.and_i32();
                }
                self.b.if_void();
                self.check_target(target, start);
                self.retired();
                self.goto(target, index);
                self.b.block_end();
                self.retired();
            },
            Op::LoadSreg { segment, src } => {
                self.read(src, 16, inst);
                self.load_segment(segment, start);
                self.leave_unless_runnable(next);
            },
            Op::PopSreg { segment, width } => {
                let bytes = width as u64 / 8;
                self.stack_sized(0, bytes as u32, false, start);
                self.gi(HOST);
                self.load(width);
                self.load_segment(segment, start);
                self.adjust_sp(bytes);
                self.leave_unless_runnable(next);
            },
            Op::PushSreg { segment, width } => {
                self.stack_sized(-(width as i64 / 8), 2, true, start);
                self.gi(HOST);
                self.load_selector(segment);
                self.store(16);
                self.commit_sp(-(width as i64 / 8));
            },
            Op::Push16 { src } => {
                self.read(src, 16, inst);
                self.s(TV);
                self.stack_sized(-2, 2, true, start);
                self.gi(HOST);
                self.g(TV);
                self.store(16);
                self.commit_sp(-2);
            },
            Op::Pop16 { dst: Opnd::Reg(r) } => {
                self.stack_sized(0, 2, false, start);
                self.gi(HOST);
                self.load(16);
                self.s(TV);
                self.adjust_sp(2);
                self.g(TV);
                self.set_reg(r, 16);
            },
            Op::Pop16 { dst: Opnd::Mem(a) } => self.pop_memory(a, 16, inst),
            Op::Pop16 { dst: Opnd::Imm(_) } => unreachable!(),
            Op::Push32 { src } => {
                self.read(src, 32, inst);
                self.s(TV);
                self.stack_sized(-4, 4, true, start);
                self.gi(HOST);
                self.g(TV);
                self.store(32);
                self.commit_sp(-4);
            },
            Op::Pop32 { dst: Opnd::Reg(r) } => {
                self.stack_sized(0, 4, false, start);
                self.gi(HOST);
                self.load(32);
                self.s(TV);
                self.adjust_sp(4);
                self.g(TV);
                self.set_reg(r, 32);
            },
            Op::Pop32 { dst: Opnd::Mem(a) } => self.pop_memory(a, 32, inst),
            Op::Pop32 { dst: Opnd::Imm(_) } => unreachable!(),
            Op::LoadFar {
                segment,
                width,
                dst,
                address,
            } => {
                // (the offset and the selector after it, read before the
                // segment loads, which may retry: nothing changed then)
                self.read(Opnd::Mem(address), width, inst);
                self.s(TV);
                let selector = AddressExpr {
                    displacement: address.displacement.wrapping_add(width as i64 / 8),
                    ..address
                };
                self.read(Opnd::Mem(selector), 16, inst);
                self.load_segment(segment, start);
                self.g(TV);
                self.set_reg(dst, width);
                self.leave_unless_runnable(next);
            },
            Op::Enter { size } => {
                // (as enter16 at level 0: BP at SP - 2, BP = SP - 2, SP less
                // size + 2; ESP's and EBP's high halves stay)
                let bp = register(5, 16, false);
                self.stack_sized(-2, 2, true, start);
                self.gi(HOST);
                self.get_reg(bp, 16);
                self.store(16);
                self.g(4);
                self.c64(2);
                self.b.sub_i64();
                self.c64(0xFFFF);
                self.b.and_i64();
                self.s(TV);
                self.g(4);
                self.c64(0xFFFF_0000);
                self.b.and_i64();
                self.g(TV);
                self.c64(size as u64);
                self.b.sub_i64();
                self.c64(0xFFFF);
                self.b.and_i64();
                self.b.or_i64();
                self.s(4);
                self.g(TV);
                self.set_reg(bp, 16);
            },
            Op::Lods16 { width, segment } => {
                let source = AddressExpr {
                    base: AddressBase::Register(6),
                    index: None,
                    scale: 0,
                    displacement: 0,
                    address_size: 16,
                    segment,
                };
                self.address(&source, next, true);
                self.s(ADDR);
                self.host(width as u32 / 8, false, start);
                self.load(width);
                self.set_reg(register(0, width, false), width);
                // SI += the size, or with DF less it, at 16 bits
                let si = register(6, 16, false);
                self.get_reg(si, 16);
                self.b.wrap_i64_to_i32();
                self.c32(-(width as i32 / 8));
                self.c32(width as i32 / 8);
                self.gi(FL);
                self.c32(0x400);
                self.b.and_i32();
                self.b.select();
                self.b.add_i32();
                self.c32(0xFFFF);
                self.b.and_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(si, 16);
            },
            Op::PopMem { address } => self.pop_memory(address, 32, inst),
            Op::Pusha => {
                // (as cpu::misc_instr's pusha32: EAX, ECX, EDX, EBX, the
                // original ESP, EBP, ESI and EDI below ESP; the translation of
                // all 32 bytes stands for each store: all happen or none)
                self.stack_sized(-32, 32, true, start);
                for r in 0..8u8 {
                    self.gi(HOST);
                    self.c32(28 - 4 * r as i32);
                    self.b.add_i32();
                    self.get_reg(register(r, 32, false), 32);
                    self.store(32);
                }
                self.commit_sp(-32);
            },
            Op::Popa => {
                // (as popa32: EDI, ESI, EBP, ESP skipped, EBX, EDX, ECX, EAX)
                self.stack_sized(0, 32, false, start);
                for r in [7u8, 6, 5, 3, 2, 1, 0] {
                    self.gi(HOST);
                    self.c32(28 - 4 * r as i32);
                    self.b.add_i32();
                    self.load(32);
                    self.set_reg(register(r, 32, false), 32);
                }
                self.adjust_sp(32);
            },
            Op::Lods { width, segment } => {
                let source = AddressExpr {
                    base: AddressBase::Register(6),
                    index: None,
                    scale: 0,
                    displacement: 0,
                    address_size: 32,
                    segment,
                };
                self.address(&source, next, true);
                self.s(ADDR);
                self.host(width as u32 / 8, false, start);
                self.load(width);
                self.set_reg(register(0, width, false), width);
                // ESI += the size, or with DF less it
                let esi = register(6, 32, false);
                self.get_reg(esi, 32);
                self.b.wrap_i64_to_i32();
                self.c32(-(width as i32 / 8));
                self.c32(width as i32 / 8);
                self.gi(FL);
                self.c32(0x400);
                self.b.and_i32();
                self.b.select();
                self.b.add_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(esi, 32);
            },
            Op::Leave if self.env.prot16 || self.env.stack16 => {
                // (16-bit code, P7.7, or a 16-bit stack, M11: SP = BP on a
                // 16-bit stack, ESP's high half kept, else ESP = EBP; then
                // POP BP, or EBP in 32-bit code)
                let width = if self.env.prot16 { 16 } else { 32 };
                self.lookup_base = None;
                self.g(5);
                self.b.wrap_i64_to_i32();
                if self.env.stack16 {
                    self.c32(0xFFFF);
                    self.b.and_i32();
                }
                self.c32(gp::segment_offsets as i32 + 2 * 4);
                self.b.load_aligned_i32(0);
                self.b.add_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.s(ADDR);
                self.host(width as u32 / 8, false, start);
                self.load(width);
                self.s(TV);
                if self.env.stack16 {
                    self.g(4);
                    self.c64(0xFFFF_0000);
                    self.b.and_i64();
                    self.g(5);
                    self.c64(width as u64 / 8);
                    self.b.add_i64();
                    self.c64(0xFFFF);
                    self.b.and_i64();
                    self.b.or_i64();
                }
                else {
                    self.g(5);
                    self.c64(width as u64 / 8);
                    self.b.add_i64();
                    self.wrap32();
                }
                self.s(4);
                self.g(TV);
                self.set_reg(register(5, width, false), width);
            },
            Op::Leave => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.lookup_base = Some((5, 0));
                self.g(5);
                self.segment_base(2);
                self.s(ADDR);
                self.host(bytes as u32, false, start);
                self.load(width);
                self.s(TV);
                self.g(5);
                self.c64(bytes);
                self.b.add_i64();
                if self.env.compat {
                    self.wrap32();
                }
                self.s(4);
                self.g(TV);
                self.s(5);
            },
            Op::Call { target } => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.check_target(target, start);
                self.stack(-(bytes as i64), true, start);
                self.gi(HOST);
                self.return_address(next);
                self.store(width);
                self.commit_sp(-(bytes as i64));
                self.retired();
                self.goto(target, index);
            },
            Op::CallIndirect { src } => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.read(src, width, inst);
                self.s(TV);
                self.ip_to_linear(TV);
                self.check_canonical(TV, start);
                self.stack(-(bytes as i64), true, start);
                self.gi(HOST);
                self.return_address(next);
                self.store(width);
                self.commit_sp(-(bytes as i64));
                self.retired();
                self.g(TV);
                self.s(RIP);
                self.dispatch();
            },
            Op::Ret { pop } => {
                let (bytes, width) = (self.slot_bytes(), self.slot_bytes() as u8 * 8);
                self.stack(0, false, start);
                self.gi(HOST);
                self.load(width);
                self.s(TV);
                self.ip_to_linear(TV);
                self.check_canonical(TV, start);
                self.adjust_sp(bytes + pop as u64);
                self.retired();
                self.g(TV);
                self.s(RIP);
                self.return_guess(start, index);
                self.dispatch();
            },
            Op::JmpIndirect { src } => {
                let width = self.slot_bytes() as u8 * 8;
                self.read(src, width, inst);
                self.s(TV);
                self.ip_to_linear(TV);
                self.check_canonical(TV, start);
                self.retired();
                self.g(TV);
                self.s(RIP);
                self.dispatch();
            },
            Op::Jmp { target } => {
                self.check_target(target, start);
                self.retired();
                self.goto(target, index);
            },
            Op::Jcc { cc, target } => {
                self.materialize_if(inst.flags_read);
                self.condition(cc, inst.fused);
                self.b.if_void();
                self.check_target(target, start);
                self.retired();
                self.goto(target, index);
                self.b.block_end();
                self.retired();
            },
            Op::Cmov {
                cc,
                width,
                dst,
                src,
            } if self.env.i32_ops => {
                // (P4.20: without a branch, the destination written either
                // way, as a 32-bit CMOV writes it)
                self.materialize_if(inst.flags_read);
                self.read(src, width, inst);
                self.s(TV);
                if width == 32 {
                    self.g(TV);
                    self.b.wrap_i64_to_i32();
                    self.get_reg(dst, 32);
                    self.b.wrap_i64_to_i32();
                    self.condition(cc, inst.fused);
                    self.b.select();
                    self.b.extend_unsigned_i32_to_i64();
                }
                else {
                    self.g(TV);
                    self.get_reg(dst, width);
                    self.condition(cc, inst.fused);
                    self.b.select();
                }
                self.set_reg(dst, width);
            },
            Op::Cmov {
                cc,
                width,
                dst,
                src,
            } => {
                self.materialize_if(inst.flags_read);
                self.read(src, width, inst);
                self.s(TV);
                self.condition(cc, inst.fused);
                self.b.if_void();
                self.g(TV);
                self.set_reg(dst, width);
                if width == 32 {
                    self.b.else_();
                    self.get_reg(dst, 32);
                    self.set_reg(dst, 32);
                }
                self.b.block_end();
            },
            Op::Setcc { cc, dst } => {
                self.materialize_if(inst.flags_read);
                match dst {
                    Opnd::Reg(r) => {
                        self.condition(cc, inst.fused);
                        self.b.extend_unsigned_i32_to_i64();
                        self.set_reg_fitting(r, 8, true);
                    },
                    Opnd::Mem(a) => {
                        self.prepare_store(&a, 8, inst);
                        self.gi(HOST);
                        self.condition(cc, inst.fused);
                        self.b.extend_unsigned_i32_to_i64();
                        self.store(8);
                    },
                    Opnd::Imm(_) => unreachable!(),
                }
            },
            Op::Xchg { width, a, b } => {
                self.read_dst(a, width, true, inst);
                self.s(TA);
                self.get_reg(b, width);
                self.s(TB);
                self.write_dst(a, width, TB);
                self.g(TA);
                self.set_reg(b, width);
            },
            Op::Xadd { width, dst, src } => {
                self.read_dst(dst, width, true, inst);
                self.s(TA);
                self.note_last_op1(TA);
                self.get_reg(src, width);
                self.s(TB);
                self.g(TA);
                self.g(TB);
                self.b.add_i64();
                self.mask_to(width);
                self.s(TR);
                self.write_dst(dst, width, TR);
                if dst.reg() != Some(src) {
                    self.g(TA);
                    self.set_reg(src, width);
                }
                self.alu_flags(0, width, need);
                self.record(0, width, ARITH, need, inst);
            },
            Op::Cmpxchg { width, dst, src } => {
                self.read_dst(dst, width, true, inst);
                self.s(TB);
                self.get_reg(RAX, width);
                self.s(TA);
                self.note_last_op1(TA);
                self.g(TA);
                self.g(TB);
                self.b.sub_i64();
                self.mask_to(width);
                self.s(TR);
                self.g(TA);
                self.g(TB);
                self.b.eq_i64();
                self.si(COND);
                match dst {
                    Opnd::Mem(_) if inst.locked => {
                        // (unequal: the value read is written back, no change)
                        self.get_reg(src, width);
                        self.g(TB);
                        self.gi(COND);
                        self.b.select();
                        self.s(TV);
                        self.locked_store(width, TV);
                        self.gi(COND);
                        self.b.eqz_i32();
                        self.b.if_void();
                        self.g(TB);
                        self.set_reg(RAX, width);
                        self.b.block_end();
                    },
                    Opnd::Mem(_) => {
                        // the memory operand is always written
                        self.gi(HOST);
                        self.get_reg(src, width);
                        self.g(TB);
                        self.gi(COND);
                        self.b.select();
                        self.store(width);
                        self.gi(COND);
                        self.b.eqz_i32();
                        self.b.if_void();
                        self.g(TB);
                        self.set_reg(RAX, width);
                        self.b.block_end();
                    },
                    Opnd::Reg(d) => {
                        self.gi(COND);
                        self.b.if_void();
                        self.get_reg(src, width);
                        self.set_reg(d, width);
                        self.b.else_();
                        self.g(TB);
                        self.set_reg(RAX, width);
                        self.b.block_end();
                    },
                    Opnd::Imm(_) => unreachable!(),
                }
                self.alu_flags(7, width, need);
                self.record(7, width, ARITH, need, inst);
            },
            Op::SignAcc { width } => {
                self.get_reg(RAX, width / 2);
                self.sext(width / 2);
                self.set_reg(RAX, width);
            },
            Op::SignDx { width } => {
                self.c64(0);
                self.get_reg(RAX, width);
                self.c64(width as u64 - 1);
                self.b.shr_u_i64();
                self.b.sub_i64();
                self.set_reg(RDX, width);
            },
            Op::Bt {
                action,
                width,
                dst,
                index: bit,
            } => {
                let log = width.trailing_zeros() as u64;
                match dst {
                    Opnd::Reg(r) => {
                        self.get_reg(r, width);
                        self.s(TA);
                    },
                    Opnd::Mem(a) => {
                        self.address(&a, next, true);
                        if let Opnd::Reg(i) = bit {
                            // bit string: the index selects the operand
                            self.get_reg(i, width);
                            self.sext(width);
                            self.c64(log);
                            self.b.shr_s_i64();
                            self.c64(log - 3);
                            self.b.shl_i64();
                            self.b.add_i64();
                            if self.env.compat {
                                self.wrap32();
                            }
                        }
                        self.s(ADDR);
                        self.host(width as u32 / 8, action != 0, start);
                        if inst.locked {
                            self.si(HOST);
                            self.locked_load(width);
                        }
                        else {
                            self.ti(HOST);
                            self.load(width);
                        }
                        self.s(TA);
                    },
                    Opnd::Imm(_) => unreachable!(),
                }
                match bit {
                    Opnd::Imm(v) => self.c64(v & (width as u64 - 1)),
                    _ => {
                        self.read(bit, width, inst);
                        self.c64(width as u64 - 1);
                        self.b.and_i64();
                    },
                }
                self.s(TB);
                if action != 0 {
                    self.g(TA);
                    self.c64(1);
                    self.g(TB);
                    self.b.shl_i64();
                    match action {
                        1 => self.b.or_i64(),
                        2 => {
                            self.c64(u64::MAX);
                            self.b.xor_i64();
                            self.b.and_i64();
                        },
                        _ => self.b.xor_i64(),
                    }
                    self.s(TR);
                    self.write_dst(dst, width, TR);
                }
                self.flags_begin(CF);
                self.g(TA);
                self.g(TB);
                self.b.shr_u_i64();
                self.b.wrap_i64_to_i32();
                self.c32(1);
                self.b.and_i32();
                self.flags_end(false);
                self.written(CF);
            },
            Op::BitScan {
                reverse,
                width,
                dst,
                src,
            } if self.env.compat => {
                // (the 32-bit interpreter's bsf32 and kin: the destination
                // kept for a zero source; CF clear, ZF of the source, SF, PF,
                // AF and OF of the index, 0 for a zero source, as its lazy
                // record leaves them: legacy_record)
                self.read(src, width, inst);
                self.s(TA);
                self.is_zero(TA);
                self.b.if_void();
                self.c64(0);
                self.s(TR);
                self.b.else_();
                if reverse {
                    self.c64(63);
                    self.g(TA);
                    self.b.clz_i64();
                    self.b.sub_i64();
                }
                else {
                    self.g(TA);
                    self.b.ctz_i64();
                }
                self.s(TR);
                self.g(TR);
                self.set_reg(dst, width);
                self.b.block_end();
                let need = if self.env.exit_flags {
                    inst.writes & (inst.live_out | inst.exit_live)
                }
                else {
                    inst.writes
                };
                let lazy = need & (SF | PF | AF | OF);
                if need & (CF | ZF) != 0 {
                    self.flags_begin(need & (CF | ZF));
                    if need & ZF != 0 {
                        self.is_zero(TA);
                        self.c32(6);
                        self.b.shl_i32();
                    }
                    self.flags_end(need & ZF == 0);
                }
                if lazy != 0 {
                    self.legacy_record(width, lazy);
                }
                self.written(inst.writes & !lazy);
            },
            Op::BitScan {
                reverse,
                width,
                dst,
                src,
            } => {
                self.read(src, width, inst);
                self.s(TA);
                self.is_zero(TA);
                self.b.if_void();
                self.gi(FL);
                self.c32(ZF as i32);
                self.b.or_i32();
                self.si(FL);
                self.b.else_();
                if reverse {
                    self.c64(63);
                    self.g(TA);
                    self.b.clz_i64();
                    self.b.sub_i64();
                }
                else {
                    self.g(TA);
                    self.b.ctz_i64();
                }
                self.set_reg(dst, width);
                self.gi(FL);
                self.c32(!ZF as i32);
                self.b.and_i32();
                self.si(FL);
                self.b.block_end();
                self.written(ZF);
            },
            Op::Popcnt { width, dst, src } => {
                self.read(src, width, inst);
                self.s(TA);
                self.g(TA);
                self.b.popcnt_i64();
                self.set_reg(dst, width);
                self.flags_begin(ARITH);
                self.is_zero(TA);
                self.c32(6);
                self.b.shl_i32();
                self.flags_end(false);
                self.written(ARITH);
            },
            Op::Bswap { width, reg } => {
                self.g(reg as usize);
                self.byte_swap(width);
                self.s(reg as usize);
            },
            Op::Vfused {
                op,
                double,
                dst,
                first,
                src,
            } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first,
                    src,
                };
                crate::x86tpl::ops::fused(&mut operands, op, double);
                self.vex_upper(inst, dst);
            },
            Op::Movbe {
                load,
                width,
                reg,
                mem,
            } => {
                if load {
                    self.read(Opnd::Mem(mem), width, inst);
                    self.byte_swap(width);
                    self.set_reg(reg, width);
                }
                else {
                    self.prepare_store(&mem, width, inst);
                    self.gi(HOST);
                    self.get_reg(reg, width);
                    self.byte_swap(width);
                    self.store(width);
                }
            },
            Op::Bmi {
                op: BmiOp::Andn,
                width,
                dst,
                src,
                other,
            } => {
                // AND's flags, of NOT VEX.vvvv (TA) and the source (TB)
                self.read(src, width, inst);
                self.s(TB);
                self.get_reg(other, width);
                self.c64(mask(width));
                self.b.xor_i64();
                self.s(TA);
                self.g(TA);
                self.g(TB);
                self.b.and_i64();
                self.s(TR);
                self.g(TR);
                self.set_reg(dst, width);
                self.alu_flags(4, width, need);
                self.record(4, width, ARITH, need, inst);
            },
            Op::Bmi {
                op: op @ (BmiOp::Shlx | BmiOp::Shrx | BmiOp::Sarx),
                width,
                dst,
                src,
                other,
            } => {
                // (Wasm takes the count modulo the operand size, as these)
                self.read(src, width, inst);
                if width == 64 {
                    self.get_reg(other, 64);
                    match op {
                        BmiOp::Shlx => self.b.shl_i64(),
                        BmiOp::Shrx => self.b.shr_u_i64(),
                        _ => self.b.shr_s_i64(),
                    }
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.get_reg(other, 32);
                    self.b.wrap_i64_to_i32();
                    match op {
                        BmiOp::Shlx => self.b.shl_i32(),
                        BmiOp::Shrx => self.b.shr_u_i32(),
                        _ => self.b.shr_s_i32(),
                    }
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_reg(dst, width);
            },
            Op::Bmi {
                op: BmiOp::Rorx(count),
                width,
                dst,
                src,
                ..
            } => {
                // (the count modulo the operand size; no flags)
                self.read(src, width, inst);
                if width == 64 {
                    self.c64(count as u64 & 63);
                    self.b.rotr_i64();
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.c32(count as i32 & 31);
                    self.b.rotr_i32();
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.set_reg(dst, width);
            },
            Op::Bmi {
                op,
                width,
                dst,
                src,
                other,
            } => {
                // the source TA; BZHI's index TB
                self.read(src, width, inst);
                self.s(TA);
                match op {
                    BmiOp::Blsr | BmiOp::Blsmsk => {
                        self.g(TA);
                        self.c64(1);
                        self.b.sub_i64();
                        self.g(TA);
                        if op == BmiOp::Blsr {
                            self.b.and_i64();
                        }
                        else {
                            self.b.xor_i64();
                        }
                        self.mask_to(width);
                    },
                    BmiOp::Blsi => {
                        self.c64(0);
                        self.g(TA);
                        self.b.sub_i64();
                        self.g(TA);
                        self.b.and_i64();
                    },
                    BmiOp::Bzhi => {
                        // TA AND (1 << n) - 1 for an index n below the
                        // operand size, else TA
                        self.get_reg(other, width);
                        self.c64(0xFF);
                        self.b.and_i64();
                        self.s(TB);
                        self.g(TA);
                        self.c64(1);
                        self.g(TB);
                        self.b.shl_i64();
                        self.c64(1);
                        self.b.sub_i64();
                        self.b.and_i64();
                        self.g(TA);
                        self.g(TB);
                        self.c64(width as u64);
                        self.b.ltu_i64();
                        self.b.select();
                    },
                    // (Wasm's count of a zero operand is its size, as theirs)
                    _ if width == 64 => {
                        self.g(TA);
                        if op == BmiOp::Tzcnt {
                            self.b.ctz_i64();
                        }
                        else {
                            self.b.clz_i64();
                        }
                    },
                    _ => {
                        self.g(TA);
                        self.b.wrap_i64_to_i32();
                        if op == BmiOp::Tzcnt {
                            self.b.ctz_i32();
                        }
                        else {
                            self.b.clz_i32();
                        }
                        self.b.extend_unsigned_i32_to_i64();
                    },
                }
                self.s(TR);
                self.g(TR);
                self.set_reg(dst, width);
                self.bmi_flags(width, need, inst, |e| match op {
                    // CF: the source is not 0 (BLSI), the index is beyond
                    // the operand size (BZHI), else the source is 0
                    BmiOp::Blsi => {
                        e.is_zero(TA);
                        e.b.eqz_i32();
                    },
                    BmiOp::Bzhi => {
                        e.g(TB);
                        e.c64(width as u64 - 1);
                        e.b.gtu_i64();
                    },
                    _ => e.is_zero(TA),
                });
            },
            Op::Flag { opcode } => {
                self.materialize_if(inst.flags_read);
                self.gi(FL);
                match opcode {
                    0xF5 => {
                        self.c32(CF as i32);
                        self.b.xor_i32();
                    },
                    0xF8 => {
                        self.c32(!CF as i32);
                        self.b.and_i32();
                    },
                    0xF9 => {
                        self.c32(CF as i32);
                        self.b.or_i32();
                    },
                    0xFC => {
                        self.c32(!0x400);
                        self.b.and_i32();
                    },
                    _ => {
                        self.c32(0x400);
                        self.b.or_i32();
                    },
                }
                self.si(FL);
                self.written(inst.writes);
            },
            Op::Cli | Op::Sti | Op::StiShadowed => {
                // #GP unless CPL <= IOPL
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.gi(FL);
                self.c32(12);
                self.b.shr_u_i32();
                self.c32(3);
                self.b.and_i32();
                self.b.gtu_i32();
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.gi(FL);
                if matches!(inst.op, Op::Cli) {
                    self.c32(!0x200);
                    self.b.and_i32();
                    self.si(FL);
                }
                else if matches!(inst.op, Op::StiShadowed) {
                    // (the shadow instruction follows; End::Shadow checks)
                    self.c32(0x200);
                    self.b.or_i32();
                    self.si(FL);
                }
                else {
                    self.c32(0x200);
                    self.b.or_i32();
                    self.si(FL);
                    // as after the interpreter retired STI: one shadow instruction left
                    self.c32(gp::interrupt_shadow as i32);
                    self.c32(1);
                    self.b.store_u8(0);
                    self.retired();
                    self.leave_to(self.f().exit, next);
                }
            },
            Op::Swapgs => {
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                let (low, high) = (
                    gp::segment_offsets as u32 + 20,
                    gp::x64_segment_base_hi as u32 + 20,
                );
                self.load_pair(low, high);
                self.s(TV);
                self.c32(gp::x64_kernel_gs_base as i32);
                self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
                self.s(TX);
                self.store_pair(low, high, TX);
                self.c32(gp::x64_kernel_gs_base as i32);
                self.g(TV);
                self.b.store_aligned_i64(0);
            },
            Op::Rdtsc => {
                // #GP at CPL > 0 with CR4.TSD
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.c32(0);
                self.b.ne_i32();
                self.b.load_fixed_i32(gp::cr as u32 + 16);
                self.c32(2);
                self.b.shr_u_i32();
                self.c32(1);
                self.b.and_i32();
                self.b.and_i32();
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.b
                    .call_signature("x64_page_rdtsc", Signature::new(&[], &[WasmType::I64]));
                self.s(TV);
                self.g(TV);
                self.set_reg(RAX, 32);
                self.g(TV);
                self.c64(32);
                self.b.shr_u_i64();
                self.set_reg(RDX, 32);
            },
            Op::Div { signed, width, src } => self.divide(inst, signed, width, src),
            Op::RepCompare { width, scan, equal } => self.rep_compare(inst, width, scan, equal),
            Op::Movs { width, rep } | Op::Stos { width, rep } => {
                self.string(inst, matches!(inst.op, Op::Movs { .. }), width, rep)
            },
            Op::MovSreg {
                segment,
                width,
                dst,
            } => match dst {
                Opnd::Mem(a) => {
                    self.prepare_store(&a, 16, inst);
                    self.gi(HOST);
                    self.load_selector(segment);
                    self.store(16);
                },
                Opnd::Reg(r) => {
                    self.load_selector(segment);
                    self.set_reg(r, width);
                },
                Opnd::Imm(_) => unreachable!(),
            },
            Op::Mmx { form } => self.mmx(inst, form, start),
            Op::DoubleShiftCl { left, dst, src } => {
                // (as Op::DoubleShift in compatibility mode, by CL & 31: a
                // zero count keeps the destination, written back as the
                // interpreter writes it, and every flag, made current first)
                self.materialize_if(inst.flags_read);
                self.read_dst(dst, 32, true, inst);
                self.s(TA);
                self.g(1);
                self.c64(31);
                self.b.and_i64();
                self.s(TB);
                self.g(TA);
                self.s(TR);
                self.is_zero(TB);
                self.b.eqz_i32();
                self.b.if_void();
                {
                    self.get_reg(src, 32);
                    self.s(TC);
                    self.g(TA);
                    self.g(TB);
                    if left {
                        self.b.shl_i64()
                    }
                    else {
                        self.b.shr_u_i64()
                    }
                    self.g(TC);
                    self.c64(32);
                    self.g(TB);
                    self.b.sub_i64();
                    if left {
                        self.b.shr_u_i64()
                    }
                    else {
                        self.b.shl_i64()
                    }
                    self.b.or_i64();
                    self.mask_to(32);
                    self.s(TR);
                    let need = inst.writes;
                    let lazy = if self.env.exit_flags {
                        need & (SF | ZF | PF | AF) & !inst.live_out
                    }
                    else {
                        0
                    };
                    let eager = need & !lazy;
                    self.flags_begin(eager);
                    // CF: the last bit shifted out of the destination
                    self.g(TA);
                    if left {
                        self.c64(32);
                        self.g(TB);
                        self.b.sub_i64();
                    }
                    else {
                        self.g(TB);
                        self.c64(1);
                        self.b.sub_i64();
                    }
                    self.b.shr_u_i64();
                    self.b.wrap_i64_to_i32();
                    self.c32(1);
                    self.b.and_i32();
                    self.b.or_i32();
                    // OF: the sign change, for SHLD by 1 only
                    self.g(TA);
                    self.g(TR);
                    self.b.xor_i64();
                    self.c64(31);
                    self.b.shr_u_i64();
                    self.b.wrap_i64_to_i32();
                    self.c32(1);
                    self.b.and_i32();
                    if left {
                        self.g(TB);
                        self.c64(1);
                        self.b.eq_i64();
                        self.b.and_i32();
                    }
                    self.c32(11);
                    self.b.shl_i32();
                    self.b.or_i32();
                    // (CF and OF are in the base now: the terms start over)
                    let mut first = true;
                    self.szp(TR, eager, 32, &mut first);
                    if eager & AF != 0 {
                        self.legacy_af();
                        self.join(&mut first);
                    }
                    self.flags_end(first);
                    if lazy != 0 {
                        self.legacy_record(32, lazy);
                    }
                    self.written(inst.writes & !lazy);
                }
                self.b.block_end();
                self.write_dst(dst, 32, TR);
            },
            Op::DoubleShift {
                left,
                width: 32,
                dst,
                src,
                count,
            } if self.env.compat => {
                // (the 32-bit interpreter's shld32 and shrd32: CF the last
                // bit shifted out, OF for SHLD by 1 the sign change, else
                // clear, for SHRD by any count; SF, ZF, PF and AF of the
                // result as its lazy record leaves them; a zero count keeps
                // every flag)
                let count = shift_count(32, count) as u64;
                self.read_dst(dst, 32, true, inst);
                self.s(TA);
                if count == 0 {
                    self.write_dst(dst, 32, TA);
                }
                else {
                    self.get_reg(src, 32);
                    self.s(TB);
                    self.g(TA);
                    self.c64(count);
                    if left {
                        self.b.shl_i64()
                    }
                    else {
                        self.b.shr_u_i64()
                    }
                    self.g(TB);
                    self.c64(32 - count);
                    if left {
                        self.b.shr_u_i64()
                    }
                    else {
                        self.b.shl_i64()
                    }
                    self.b.or_i64();
                    self.mask_to(32);
                    self.s(TR);
                    self.write_dst(dst, 32, TR);
                    let need = if self.env.exit_flags {
                        inst.writes & (inst.live_out | inst.exit_live)
                    }
                    else {
                        inst.writes
                    };
                    let lazy = need & (SF | ZF | PF | AF) & !inst.live_out;
                    let eager = need & !lazy;
                    self.flags_begin(eager);
                    let mut first = true;
                    if eager & CF != 0 {
                        self.bit_of(
                            TA,
                            if left { (32 - count) as u8 } else { (count - 1) as u8 },
                            0,
                        );
                        self.join(&mut first);
                    }
                    if eager & OF != 0 && (!left || count == 1) {
                        self.g(TA);
                        self.g(TR);
                        self.b.xor_i64();
                        self.s(TX);
                        self.bit_of(TX, 31, 11);
                        self.join(&mut first);
                    }
                    self.szp(TR, eager, 32, &mut first);
                    if eager & AF != 0 {
                        self.legacy_af();
                        self.join(&mut first);
                    }
                    self.flags_end(first);
                    if lazy != 0 {
                        self.legacy_record(32, lazy);
                    }
                    self.written(inst.writes & !lazy);
                }
            },
            Op::DoubleShift {
                left,
                width,
                dst,
                src,
                count,
            } => {
                let count = shift_count(width, count) as u64;
                let w = width as u64;
                self.read_dst(dst, width, true, inst);
                self.s(TA);
                if count == 0 {
                    self.write_dst(dst, width, TA);
                }
                else {
                    self.get_reg(src, width);
                    self.s(TB);
                    self.g(TA);
                    self.c64(if left { count } else { count });
                    if left {
                        self.b.shl_i64()
                    }
                    else {
                        self.b.shr_u_i64()
                    }
                    self.g(TB);
                    self.c64(w - count);
                    if left {
                        self.b.shr_u_i64()
                    }
                    else {
                        self.b.shl_i64()
                    }
                    self.b.or_i64();
                    self.mask_to(width);
                    self.s(TR);
                    self.write_dst(dst, width, TR);
                    let writes = inst.writes;
                    self.flags_begin(writes);
                    let mut first = true;
                    self.bit_of(
                        TA,
                        if left { (w - count) as u8 } else { (count - 1) as u8 },
                        0,
                    );
                    self.join(&mut first);
                    self.szp(TR, writes, width, &mut first);
                    if count == 1 {
                        self.g(TA);
                        self.g(TR);
                        self.b.xor_i64();
                        self.s(TX);
                        self.bit_of(TX, width - 1, 11);
                        self.join(&mut first);
                    }
                    self.flags_end(first);
                    self.written(writes);
                }
            },
            Op::CompareExchange { wide, address } => self.compare_exchange(inst, wide, &address),
            Op::Vmove {
                bits,
                dst,
                src,
                aligned,
                zero,
                upper,
            } => {
                self.vector_check(inst, start);
                match (dst, src) {
                    (Xmm::Reg(d), Xmm::Reg(s)) if bits == 128 && self.env.xmm_locals => {
                        self.xv_push(s);
                        self.xv_pop(d);
                    },
                    // (XMM locals: the scalar moves as v128 values, no lane
                    // through a general register)
                    (Xmm::Reg(d), Xmm::Reg(s)) if bits < 128 && self.env.xmm_locals => {
                        // the low bits of s; the others zero, or from the
                        // destination or VEX.vvvv (a single by low_single)
                        if bits == 32 {
                            if zero {
                                self.b.simd_zero();
                            }
                            else {
                                self.xv_push(upper.unwrap_or(d));
                            }
                            self.xv_push(s);
                            low_single(&mut self.b);
                            self.xv_pop(d);
                        }
                        else {
                            self.xv_push(s);
                            if zero {
                                self.b.simd_zero();
                            }
                            else {
                                self.xv_push(upper.unwrap_or(d));
                            }
                            self.b.simd_shuffle(low_lanes(bits / 8));
                            self.xv_pop(d);
                        }
                    },
                    (Xmm::Reg(d), Xmm::Mem(a)) if bits < 128 && self.env.xmm_locals => {
                        self.vector_address(&a, bits, aligned, false, inst);
                        self.load_scalar_v128(bits);
                        self.xv_pop(d);
                    },
                    (Xmm::Reg(d), Xmm::Reg(s)) => {
                        self.xmm_load(s, 0, bits.min(64));
                        if let Some(first) = upper.filter(|&first| first != d) {
                            // (VMOVSS/VMOVSD: the other bits from VEX.vvvv)
                            self.s(TB);
                            self.xmm_copy(first, d);
                            self.g(TB);
                        }
                        self.xmm_store(d, 0, bits.min(64), !zero && bits == 32);
                        if bits == 128 {
                            self.xmm_load(s, 8, 64);
                            self.xmm_store(d, 8, 64, false);
                        }
                        else if zero {
                            self.clear_upper(d, bits);
                        }
                    },
                    // (XMM locals, P4.17: whole v128 accesses, no lanes)
                    (Xmm::Reg(d), Xmm::Mem(a)) if bits == 128 && self.env.xmm_locals => {
                        self.vector_address(&a, bits, aligned, false, inst);
                        self.gi(HOST);
                        let scratch = self.b.set_new_local();
                        self.b.get_local(&scratch);
                        self.b.guest_load_v128(&scratch);
                        self.b.free_local(scratch);
                        self.xv_pop(d);
                    },
                    (Xmm::Mem(a), Xmm::Reg(s)) if bits == 128 && self.env.xmm_locals => {
                        self.vector_address(&a, bits, aligned, true, inst);
                        self.xv_push(s);
                        let value = self.b.set_new_local_v128();
                        self.gi(HOST);
                        let address = self.b.set_new_local();
                        self.b.guest_store_v128(&address, &value);
                        self.b.free_local(address);
                        self.b.free_local_v128(value);
                    },
                    (Xmm::Reg(d), Xmm::Mem(a)) => {
                        self.vector_address(&a, bits, aligned, false, inst);
                        for half in 0..(bits as u32).div_ceil(64) {
                            self.gi(HOST);
                            self.load_bits(bits.min(64), half * 8);
                            self.xmm_store(d, half * 8, bits.min(64), bits == 32);
                        }
                        if bits < 128 {
                            self.clear_upper(d, bits);
                        }
                    },
                    (Xmm::Mem(a), Xmm::Reg(s)) => {
                        self.vector_address(&a, bits, aligned, true, inst);
                        for half in 0..(bits as u32).div_ceil(64) {
                            self.gi(HOST);
                            self.xmm_load(s, half * 8, bits.min(64));
                            self.b
                                .guest_store_i64_bits(if bits == 32 { 32 } else { 64 }, half * 8);
                        }
                    },
                    (Xmm::Mem(_), Xmm::Mem(_)) => unreachable!(),
                }
                if let Xmm::Reg(d) = dst {
                    self.vex_upper(inst, d);
                }
            },
            Op::Vlogic {
                code,
                dst,
                first,
                src,
            } => {
                self.vector_check(inst, start);
                if !self.env.xmm_locals {
                    self.vlogic_halves(inst, code, dst, first, src);
                    return;
                }
                // (the sources read before the destination is written)
                self.vector_source(src, inst);
                let source = self.b.set_new_local_v128();
                if code == 1 {
                    // ANDN: ~first & src, v128.andnot(src, first)
                    self.b.get_local_v128(&source);
                    self.xv_push(first);
                }
                else {
                    self.xv_push(first);
                    self.b.get_local_v128(&source);
                }
                self.b.simd(match code {
                    0 => 0x4E, // v128.and
                    1 => 0x4F, // v128.andnot
                    2 => 0x50, // v128.or
                    _ => 0x51, // v128.xor
                });
                self.xv_pop(dst);
                self.b.free_local_v128(source);
                self.vex_upper(inst, dst);
            },
            Op::Vfp {
                code,
                double,
                packed,
                dst,
                first,
                src,
            } if self.env.sse_fast_check => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first,
                    src,
                };
                crate::x86tpl::ops::float(&mut operands, code, double, !packed);
                self.vex_upper(inst, dst);
            },
            Op::Vfp {
                code,
                double,
                packed,
                dst,
                first,
                src,
            } => self.vfp(inst, start, code, double, packed, dst, first, src),
            Op::Vpacked {
                op,
                dst,
                first,
                src,
            } => {
                self.vector_check(inst, start);
                self.vector_source(src, inst);
                let source = self.b.set_new_local_v128();
                self.xv_push(first);
                let destination = self.b.set_new_local_v128();
                if self.env.xmm_locals {
                    vec::packed(&mut self.b, op, &destination, &source, 16);
                    self.xv_pop(dst);
                }
                else {
                    self.c32(Self::xmm(dst) as i32);
                    vec::packed(&mut self.b, op, &destination, &source, 16);
                    self.b.simd_memory(0x0B, 0);
                }
                self.b.free_local_v128(source);
                self.b.free_local_v128(destination);
                self.vex_upper(inst, dst);
            },
            Op::VshiftImm {
                dst,
                src,
                bits,
                kind,
                count,
                wide,
            } => {
                self.vector_check(inst, start);
                // (a VEX.256 form: each half alike, the low one first; a
                // half is read before the same half is written)
                let halves: &[u32] = if wide {
                    self.ymm_zeroed &= !(1 << dst);
                    &[0, 16]
                }
                else if self.env.xmm_locals {
                    self.xv_push(src);
                    shift_immediate(&mut self.b, bits, kind, count);
                    self.xv_pop(dst);
                    &[]
                }
                else {
                    &[0]
                };
                for offset in halves {
                    self.c32(Self::ymm(dst, *offset) as i32);
                    self.c32(Self::ymm(src, *offset) as i32);
                    self.b.simd_memory(0x00, 0);
                    shift_immediate(&mut self.b, bits, kind, count);
                    self.b.simd_memory(0x0B, 0);
                }
                if !wide {
                    self.vex_upper(inst, dst);
                }
            },
            Op::Vcompare { double, dst, src } => self.vcompare(inst, start, double, dst, src),
            Op::Vround {
                double,
                scalar,
                imm8,
                dst,
                first,
                src,
            } => self.vround(inst, start, double, scalar, imm8, dst, first, src),
            Op::Vzeroupper => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst: 0,
                    first: 0,
                    src: Xmm::Reg(0),
                };
                crate::x86tpl::ops::zero_upper(&mut operands);
            },
            Op::Vmove256 { dst, src, aligned } => {
                self.vector_check(inst, start);
                // (a register destination loads, a memory one stores)
                let (dst, first, src, load) = match (dst, src) {
                    (Xmm::Reg(d), src) => (d, d, src, true),
                    (Xmm::Mem(a), Xmm::Reg(s)) => (s, s, Xmm::Mem(a), false),
                    (Xmm::Mem(_), Xmm::Mem(_)) => unreachable!(),
                };
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first,
                    src,
                };
                if load {
                    crate::x86tpl::ops::load256(&mut operands, aligned);
                }
                else {
                    crate::x86tpl::ops::store256(&mut operands, aligned);
                }
            },
            Op::Vpacked256 {
                op,
                dst,
                first,
                src,
            } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first,
                    src,
                };
                crate::x86tpl::ops::packed256(&mut operands, op);
            },
            Op::Vinsert128 {
                dst,
                first,
                src,
                high,
            } => {
                self.vector_check(inst, start);
                self.ymm_zeroed &= !(1 << dst);
                // (the inserted 128 bits and the kept half before any write)
                self.vector_source(src, inst);
                let inserted = self.b.set_new_local_v128();
                let (kept, replaced) = if high { (0, 16) } else { (16, 0) };
                self.c32(Self::ymm(first, kept) as i32);
                self.b.simd_memory(0x00, 0);
                let other = self.b.set_new_local_v128();
                self.c32(Self::ymm(dst, kept) as i32);
                self.b.get_local_v128(&other);
                self.b.simd_memory(0x0B, 0);
                self.c32(Self::ymm(dst, replaced) as i32);
                self.b.get_local_v128(&inserted);
                self.b.simd_memory(0x0B, 0);
                self.b.free_local_v128(other);
                self.b.free_local_v128(inserted);
            },
            Op::Vperm2 {
                dst,
                first,
                src,
                imm8,
            } => {
                self.vector_check(inst, start);
                self.ymm_zeroed &= !(1 << dst);
                // (the four halves, VEX.vvvv's then ymm/m256's, before any write)
                let mut halves = Vec::new();
                for offset in [0, 16] {
                    self.c32(Self::ymm(first, offset) as i32);
                    self.b.simd_memory(0x00, 0);
                    halves.push(self.b.set_new_local_v128());
                }
                match src {
                    Xmm::Reg(s) => {
                        for offset in [0, 16] {
                            self.c32(Self::ymm(s, offset) as i32);
                            self.b.simd_memory(0x00, 0);
                            halves.push(self.b.set_new_local_v128());
                        }
                    },
                    Xmm::Mem(a) => {
                        self.vector_address_bytes(&a, 32, false, false, inst);
                        for offset in [0, 16] {
                            self.gi(HOST);
                            self.c32(offset);
                            self.b.add_i32();
                            let scratch = self.b.set_new_local();
                            self.b.get_local(&scratch);
                            self.b.guest_load_v128(&scratch);
                            self.b.free_local(scratch);
                            halves.push(self.b.set_new_local_v128());
                        }
                    },
                }
                for (k, offset) in [0, 16].into_iter().enumerate() {
                    self.c32(Self::ymm(dst, offset) as i32);
                    let selector = imm8 >> (4 * k) & 15;
                    if selector & 8 != 0 {
                        self.b.simd_zero();
                    }
                    else {
                        self.b.get_local_v128(&halves[selector as usize & 3]);
                    }
                    self.b.simd_memory(0x0B, 0);
                }
                for v in halves {
                    self.b.free_local_v128(v);
                }
            },
            Op::Vmovmsk256 { dst, src, lane } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst: dst.index,
                    first: dst.index,
                    src: Xmm::Reg(src),
                };
                crate::x86tpl::ops::move_mask256(&mut operands, lane);
            },
            Op::Vbroadcast {
                bytes,
                dst,
                src,
                wide,
            } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first: dst,
                    src,
                };
                crate::x86tpl::ops::broadcast(&mut operands, bytes, wide);
                if !wide {
                    self.vex_upper(inst, dst);
                }
            },
            Op::Vzeroall => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst: 0,
                    first: 0,
                    src: Xmm::Reg(0),
                };
                crate::x86tpl::ops::zero_all(&mut operands);
            },
            Op::Vmovmsk { dst, src, lane } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst: dst.index,
                    first: dst.index,
                    src: Xmm::Reg(src),
                };
                crate::x86tpl::ops::move_mask(&mut operands, lane);
            },
            Op::Vcmp {
                double,
                scalar,
                predicate,
                dst,
                first,
                src,
            } => self.vcmp(inst, start, double, scalar, predicate, dst, first, src),
            Op::Vblendv {
                lane,
                dst,
                first,
                src,
                mask,
            } => {
                self.vector_check(inst, start);
                let mut operands = pagegen_vec::Operands {
                    e: self,
                    inst,
                    start,
                    dst,
                    first,
                    src,
                };
                crate::x86tpl::ops::blend_variable(&mut operands, lane, mask);
                self.vex_upper(inst, dst);
            },
            Op::Vcvt { op, dst, src } => self.vcvt(inst, start, op, dst, src),
            Op::Vconvert {
                convert,
                dst,
                first,
            } => self.vconvert(inst, start, convert, dst, first),
            Op::Vstrings {
                op,
                imm8,
                wide,
                dst,
                src,
            } => {
                self.vector_check(inst, start);
                // the source first (a fault leaves nothing written); an
                // unaligned m128 is fine (the SDM's exception type 4 note)
                match src {
                    Xmm::Reg(s) => {
                        self.c32(Self::xmm(s) as i32);
                        self.b.simd_memory(0x00, 0);
                    },
                    Xmm::Mem(a) => {
                        self.vector_address(&a, 128, false, false, inst);
                        self.gi(HOST);
                        let scratch = self.b.set_new_local();
                        self.b.get_local(&scratch);
                        self.b.guest_load_v128(&scratch);
                        self.b.free_local(scratch);
                    },
                }
                let source = self.b.set_new_local_v128();
                let operands = super::helpers::sse_fp_operands() as i32;
                self.c32(operands + 16);
                self.b.get_local_v128(&source);
                self.b.simd_memory(0x0B, 0);
                self.c32(operands);
                self.c32(Self::xmm(dst) as i32);
                self.b.simd_memory(0x00, 0);
                self.b.simd_memory(0x0B, 0);
                self.c32(op as i32);
                self.c32(imm8 as i32);
                for r in [0, 2] {
                    self.g(r);
                    if !wide {
                        self.b.wrap_i64_to_i32();
                        self.b.extend_signed_i32_to_i64();
                    }
                }
                self.b.call_signature(
                    "x64_page_pcmpstr",
                    Signature::new(
                        &[WasmType::I32, WasmType::I32, WasmType::I64, WasmType::I64],
                        &[WasmType::I32],
                    ),
                );
                let result = self.b.set_new_local();
                if op & 1 != 0 {
                    self.b.get_local(&result);
                    self.c32(0xFF);
                    self.b.and_i32();
                    self.b.extend_unsigned_i32_to_i64();
                    self.set_reg(
                        Reg {
                            index: 1,
                            high: false,
                        },
                        32,
                    );
                }
                else {
                    self.c32(Self::xmm(0) as i32);
                    self.c32(operands);
                    self.b.simd_memory(0x00, 0);
                    self.b.simd_memory(0x0B, 0);
                    self.vex_upper(inst, 0);
                }
                self.flags_begin(ARITH);
                self.b.get_local(&result);
                self.c32(8);
                self.b.shr_u_i32();
                self.flags_end(false);
                self.written(ARITH);
                self.b.free_local(result);
                self.b.free_local_v128(source);
            },
            Op::Invlpg { address } => {
                // CPL > 0 is #GP (retried)
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.address(&address, next, true);
                self.b.call_signature(
                    "x64_page_invlpg",
                    Signature::new(&[WasmType::I64], &[WasmType::I32]),
                );
                self.b.if_void();
                self.retired();
                self.leave_to(self.f().exit, next);
                self.b.block_end();
                // (P4.21: the page's translation may be one the function
                // keeps)
                for kept in &self.lookup_kept {
                    kept.tag.forget(&mut self.b);
                }
            },
            Op::Mxcsr { load, address } => {
                self.vector_check(inst, start);
                if load {
                    self.address(&address, next, true);
                    self.s(ADDR);
                    self.host(4, false, start);
                    self.load(32);
                    self.b.wrap_i64_to_i32();
                    self.si(ST);
                    // reserved bits: #GP in the interpreter
                    self.gi(ST);
                    self.c32(!crate::cpu::cpu::MXCSR_MASK);
                    self.b.and_i32();
                    self.b.if_void();
                    self.leave_to(self.f().retry, start);
                    self.b.block_end();
                    self.c32(gp::mxcsr as i32);
                    self.gi(ST);
                    self.b.store_aligned_i32(0);
                    self.mxcsr_flag();
                }
                else {
                    self.address(&address, next, true);
                    self.s(ADDR);
                    self.host(4, true, start);
                    self.b.load_fixed_i32(gp::mxcsr as u32);
                    self.b.extend_unsigned_i32_to_i64();
                    self.store(32);
                }
            },
            Op::MovdIn { width, dst, src } => {
                self.vector_check(inst, start);
                self.read(src, width, inst);
                self.xmm_store(dst, 0, 64, false);
                self.clear_upper(dst, 64);
                self.vex_upper(inst, dst);
            },
            Op::MovdOut { width, dst, src } => {
                self.vector_check(inst, start);
                match dst {
                    Opnd::Reg(r) => {
                        self.xmm_load(src, 0, width);
                        self.set_reg(r, width);
                    },
                    Opnd::Mem(a) => {
                        self.prepare_store(&a, width, inst);
                        self.gi(HOST);
                        self.xmm_load(src, 0, width);
                        self.store(width);
                    },
                    Opnd::Imm(_) => unreachable!(),
                }
            },
            Op::ReadCr { control, reg } => {
                // CPL > 0 is #GP (retried)
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.load_pair(
                    gp::cr as u32 + 4 * control as u32,
                    gp::x64_cr_hi as u32 + 4 * control as u32,
                );
                self.set_reg(reg, 64);
            },
            Op::Cr8 { write, reg } => {
                // CPL > 0 is #GP (retried)
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                if write {
                    self.get_reg(reg, 64);
                    self.b.call_signature(
                        "x64_page_set_cr8",
                        Signature::new(&[WasmType::I64], &[WasmType::I32]),
                    );
                    self.ti(ST);
                    self.c32(1);
                    self.b.eq_i32();
                    self.b.if_void();
                    self.leave_to(self.f().retry, start);
                    self.b.block_end();
                    // an interrupt the lower priority unmasks is taken after this instruction
                    self.gi(ST);
                    self.c32(2);
                    self.b.eq_i32();
                    self.b.if_void();
                    self.retired();
                    self.leave_to(self.f().exit, next);
                    self.b.block_end();
                }
                else {
                    self.b
                        .call_signature("x64_page_cr8", Signature::new(&[], &[WasmType::I64]));
                    self.set_reg(reg, 64);
                }
            },
            Op::Rdtscp => {
                // #GP at CPL > 0 with CR4.TSD, as RDTSC
                self.c32(gp::cpl as i32);
                self.b.load_u8(0);
                self.c32(0);
                self.b.ne_i32();
                self.b.load_fixed_i32(gp::cr as u32 + 16);
                self.c32(2);
                self.b.shr_u_i32();
                self.c32(1);
                self.b.and_i32();
                self.b.and_i32();
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.b
                    .call_signature("x64_page_rdtsc", Signature::new(&[], &[WasmType::I64]));
                self.s(TV);
                self.g(TV);
                self.set_reg(RAX, 32);
                self.g(TV);
                self.c64(32);
                self.b.shr_u_i64();
                self.set_reg(RDX, 32);
                self.b.load_fixed_i32(gp::x64_tsc_aux as u32);
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(
                    Reg {
                        index: 1,
                        high: false,
                    },
                    32,
                );
            },
            Op::Lahf => {
                self.materialize_if(inst.flags_read);
                self.gi(FL);
                self.c32(0xD5);
                self.b.and_i32();
                self.c32(2);
                self.b.or_i32();
                self.b.extend_unsigned_i32_to_i64();
                self.set_reg(AH, 8);
            },
            Op::Sahf => {
                self.gi(FL);
                self.c32(!0xD5);
                self.b.and_i32();
                self.get_reg(AH, 8);
                self.b.wrap_i64_to_i32();
                self.c32(0xD5);
                self.b.and_i32();
                self.b.or_i32();
                self.si(FL);
                self.written(inst.writes);
            },
        }
        // Control transfers counted themselves before leaving.
        if !matches!(
            inst.op,
            Op::Call { .. }
                | Op::CallIndirect { .. }
                | Op::FarCall { .. }
                | Op::FarRet { .. }
                | Op::Ret { .. }
                | Op::JmpIndirect { .. }
                | Op::Jmp { .. }
                | Op::Jcc { .. }
                | Op::LoopJump { .. }
                | Op::Sti
        ) {
            self.retired();
        }
    }

    // SSE ---------------------------------------------------------------

    /// Address of XMM register `n` (the legacy bank for 0..7)
    fn xmm(n: u8) -> u32 {
        if n < 8 {
            gp::reg_xmm as u32 + n as u32 * 16
        }
        else {
            gp::x64_xmm_ext as u32 + (n as u32 - 8) * 16
        }
    }
    /// Op::Vlogic without XMM locals (as before P4.17): by 64-bit halves
    fn vlogic_halves(&mut self, inst: &Inst, code: u8, dst: u8, first: u8, src: Xmm) {
        if let Xmm::Mem(a) = src {
            self.vector_address(&a, 128, inst.d.vex.is_none(), false, inst);
        }
        // (each half read before it is written)
        for half in 0..2u32 {
            self.xmm_load(first, half * 8, 64);
            if code == 1 {
                self.c64(u64::MAX);
                self.b.xor_i64();
            }
            match src {
                Xmm::Reg(s) => self.xmm_load(s, half * 8, 64),
                Xmm::Mem(_) => {
                    self.gi(HOST);
                    self.b.guest_load_i64_bits(64, half * 8);
                },
            }
            match code {
                0 | 1 => self.b.and_i64(),
                2 => self.b.or_i64(),
                _ => self.b.xor_i64(),
            }
            self.s(TA);
            self.c32(Self::xmm(dst) as i32 + half as i32 * 8);
            self.g(TA);
            self.b.store_aligned_i64(0);
        }
        self.vex_upper(inst, dst);
    }
    /// Push native_fp::mxcsr_refused_any_daz's i32 as BUDGET_MXCSR says
    /// (x64_sse_fast_check, P4.18): MXCSR changes by LDMXCSR (Op::Mxcsr
    /// sets the flag again) and by steps, while the exact helper only sets
    /// flags (PE too: exact_open sets the flag again)
    fn fp_mxcsr_refused(&mut self) {
        self.b.get_local(&self.budget);
        self.c32(BUDGET_MXCSR);
        self.b.and_i32();
        self.b.eqz_i32();
    }
    /// The x87 cache's locals (Emitter::x87_cache), made once: from the
    /// start in a function with x87 forms, as Tier-0's, so that x87_close
    /// closes it in code emitted before them too (an MMX form at the top of
    /// a loop whose x87 forms, below it, left the cache open)
    fn x87_cache_locals(&mut self) {
        if self.x87_cache.is_none() {
            let b = &mut self.b;
            self.x87_cache = Some(X87Cache {
                top: b.declare_zeroed_local(),
                tags: b.declare_zeroed_local(),
                valid: b.declare_zeroed_local(),
                dirty: b.declare_zeroed_local(),
            });
            self.x87_is_open = Some(b.declare_zeroed_local());
        }
    }
    /// Open the x87 cache (Emitter::x87_cache) unless the emitted code has:
    /// loaded from the CPU state unless the runtime flag says it is open
    fn x87_cache_open(&mut self) {
        if self.x87_known_open {
            return;
        }
        self.x87_cache_locals();
        let c = self.x87_cache.as_ref().unwrap().unsafe_clone();
        let is_open = self.x87_is_open.as_ref().unwrap().unsafe_clone();
        let [_, valid, dirty] = crate::cpu::fpu::x87_cache_addresses();
        self.b.get_local(&is_open);
        self.b.eqz_i32();
        self.b.if_void();
        self.b.load_fixed_u8(gp::fpu_stack_ptr as u32);
        self.b.set_local(&c.top);
        self.b.load_fixed_u8(gp::fpu_stack_empty as u32);
        self.b.set_local(&c.tags);
        self.b.load_fixed_i32(valid);
        self.b.set_local(&c.valid);
        self.b.load_fixed_i32(dirty);
        self.b.set_local(&c.dirty);
        self.c32(1);
        self.b.set_local(&is_open);
        self.b.block_end();
        self.x87_known_open = true;
    }
    /// Write an open x87 cache back to the CPU state and close it (before
    /// the helpers that read or change the x87 state, and at every way out
    /// of the function); nothing in a function without x87 forms
    fn x87_close(&mut self) {
        self.x87_known_open = false;
        let Some(c) = self.x87_cache.as_ref().map(X87Cache::unsafe_clone)
        else {
            return;
        };
        let is_open = self.x87_is_open.as_ref().unwrap().unsafe_clone();
        let [_, valid, dirty] = crate::cpu::fpu::x87_cache_addresses();
        self.b.get_local(&is_open);
        self.b.if_void();
        for (address, local, byte) in [
            (gp::fpu_stack_ptr as u32, &c.top, true),
            (gp::fpu_stack_empty as u32, &c.tags, true),
            (valid, &c.valid, false),
            (dirty, &c.dirty, false),
        ] {
            self.c32(address as i32);
            self.b.get_local(local);
            if byte {
                self.b.store_u8(0);
            }
            else {
                self.b.store_aligned_i32(0);
            }
        }
        self.c32(0);
        self.b.set_local(&is_open);
        self.b.block_end();
    }
    /// Compatibility mode's MMX (P7.2a), as Tier-0's ir::tier0::simd: CR0.EM
    /// and TS clear (else a retry: #UD, #NM), the x87 cache closed (the MM
    /// registers are the x87 mantissas: x86tpl::mmx syncs and invalidates
    /// the f64 shadow slots in memory), every form ending with the switch to
    /// MMX (all tags valid, TOP 0) but EMMS (all empty)
    fn mmx(&mut self, inst: &Inst, form: MmxForm, start: u64) {
        use crate::x86tpl::mmx;
        self.x87_check(start);
        self.x87_close();
        let result = |e: &mut Self, reg: u8| {
            let v = e.b.set_new_local_v128();
            mmx::store(&mut e.b, reg, &v);
            mmx::transition(&mut e.b);
            e.b.free_local_v128(v);
        };
        match form {
            MmxForm::Emms => {
                self.c32(gp::fpu_stack_empty as i32);
                self.c32(0xFF);
                self.b.store_u8(0);
            },
            MmxForm::Load { reg, src } => {
                self.mmx_source(src, 8, inst);
                result(self, reg);
            },
            MmxForm::Store { reg, dst } => match dst {
                Xmm::Reg(r) => {
                    mmx::load(&mut self.b, reg);
                    result(self, r);
                },
                Xmm::Mem(a) => {
                    self.vector_address(&a, 64, false, true, inst);
                    self.gi(HOST);
                    mmx::load(&mut self.b, reg);
                    self.b.simd_lane(0x1D, 0);
                    self.b.guest_store_i64_bits(64, 0);
                    mmx::transition(&mut self.b);
                },
            },
            MmxForm::MovdIn { reg, src } => {
                self.read(src, 32, inst);
                self.b.wrap_i64_to_i32();
                let value = self.b.set_new_local();
                self.b.simd_zero();
                self.b.get_local(&value);
                self.b.simd_lane(0x1C, 0);
                self.b.free_local(value);
                result(self, reg);
            },
            MmxForm::MovdOut { reg, dst } => {
                // (a memory destination's host first, as MOV's: a refused
                // one retries before anything changed)
                if let Opnd::Mem(a) = dst {
                    self.prepare_store(&a, 32, inst);
                }
                mmx::load(&mut self.b, reg);
                self.b.simd_lane(0x1B, 0);
                self.b.extend_unsigned_i32_to_i64();
                self.s(TV);
                self.write_dst(dst, 32, TV);
                mmx::transition(&mut self.b);
            },
            MmxForm::Packed {
                op,
                reg,
                src,
                bytes,
            } => {
                self.mmx_source(src, bytes, inst);
                let source = self.b.set_new_local_v128();
                mmx::load(&mut self.b, reg);
                let destination = self.b.set_new_local_v128();
                vec::packed(&mut self.b, op, &destination, &source, 8);
                result(self, reg);
                self.b.free_local_v128(source);
                self.b.free_local_v128(destination);
            },
            MmxForm::Shift {
                reg,
                bits,
                kind,
                count,
            } => {
                mmx::load(&mut self.b, reg);
                let value = self.b.set_new_local_v128();
                vec::shift_immediate(&mut self.b, &value, bits, kind, count);
                result(self, reg);
                self.b.free_local_v128(value);
            },
        }
    }
    /// Push an MMX form's source (v128, low quadword): an MM register, or
    /// `bytes` of memory zero-extended
    fn mmx_source(&mut self, src: Xmm, bytes: u8, inst: &Inst) {
        match src {
            Xmm::Reg(r) => crate::x86tpl::mmx::load(&mut self.b, r),
            Xmm::Mem(a) => {
                self.vector_address(&a, bytes * 8, false, false, inst);
                self.b.simd_zero();
                self.gi(HOST);
                self.load_bits(bytes * 8, 0);
                self.b.simd_lane(0x1E, 0);
            },
        }
    }
    /// Compatibility mode's x87 (P7.2a): CR0.EM and TS clear, else a retry
    /// (the interpreter raises #NM); once per block
    fn x87_check(&mut self, start: u64) {
        if self.vector_checked & VECTOR_X87 != 0 {
            return;
        }
        self.vector_checked |= VECTOR_X87;
        self.budget_check(VECTOR_X87 as i32, start);
    }
    /// A run of register-only x87 forms (P7.2a, x86tpl::x87run, as Tier-0
    /// compiles it): one guard and f64 locals, else the forms one by one
    fn x87_run(&mut self, insts: &[Inst], run: &X87Run, index: &BTreeMap<u16, usize>) {
        self.x87_check(insts[0].d.start.0);
        self.x87_cache_open();
        let done = self.b.block_void();
        let slow = self.b.block_void();
        self.b.load_fixed_u8(gp::x87_native_policy as u32);
        self.b.eqz_i32();
        self.b.hint(false);
        self.b.br_if(slow);
        let cache = self.x87_cache.as_ref().unwrap().unsafe_clone();
        x87_run(&mut self.b, &cache, run, slow);
        if !self.env.block_count {
            self.gi(N);
            self.c32(insts.len() as i32);
            self.b.add_i32();
            self.si(N);
        }
        self.b.br(done);
        self.b.block_end();
        for inst in insts {
            self.xmm_worth = 0;
            self.instruction(inst, index);
        }
        self.b.block_end();
    }
    /// Compatibility mode's x87 form (P7.2a) as Tier-0 emits it (ir::tier0
    /// Form::X87): its memory operand read into the two words, or for a
    /// store the translation validated first (the form may pop: the store
    /// must not fault after it); the f64 form of x86tpl::x87 where it
    /// applies and gp::x87_native_policy allows, else ir_t0_x87 on the CPU
    /// state from unchanged state; then the store.
    fn x87(
        &mut self,
        inst: &Inst,
        opcode: u8,
        modrm: u8,
        io: crate::x86tpl::x87_forms::Io,
        address: Option<AddressExpr>,
    ) {
        use crate::x86tpl::x87_forms::Io;
        let (start, next) = (inst.d.start.0, inst.d.next.0);
        self.x87_check(start);
        if self.x87_words.is_none() {
            let words = (self.b.declare_zeroed_local(), self.b.declare_zeroed_local());
            self.x87_words = Some(words);
        }
        let (low, high) = {
            let (low, high) = self.x87_words.as_ref().unwrap();
            (low.unsafe_clone(), high.unsafe_clone())
        };
        let kind = match io {
            Io::Stack => 0,
            Io::Load { .. } => 1,
            Io::Store { .. } => 2,
        };
        let form = opcode as i32 | (modrm as i32) << 8 | kind << 16;
        match io {
            Io::Stack => {},
            Io::Load { bytes } => {
                self.address(&address.unwrap(), next, true);
                self.s(ADDR);
                self.host(bytes as u32, false, start);
                self.load(bytes * 8);
                self.s(TV);
                self.g(TV);
                self.b.wrap_i64_to_i32();
                self.b.set_local(&low);
                self.g(TV);
                self.c64(32);
                self.b.shr_u_i64();
                self.b.wrap_i64_to_i32();
                self.b.set_local(&high);
            },
            Io::Store { bytes } => {
                self.address(&address.unwrap(), next, true);
                self.s(ADDR);
                self.host(bytes as u32, true, start);
                self.si(HOST);
            },
        }
        // (M8, legacy mode: FLDCW sets the control word and SoftFloat's
        // rounding and precision, nothing of the stack: the x87 cache stays
        // open, where the helper would close it; 615.ftol's truncating casts
        // take two)
        if self.env.compat && opcode == 0xD9 && modrm < 0xC0 && modrm >> 3 & 7 == 5 {
            self.b.get_local(&low);
            self.b
                .call_signature("x64_page_fldcw", Signature::new(&[WasmType::I32], &[]));
            return;
        }
        let done = self.b.block_void();
        if let Some(native) = crate::x86tpl::x87_forms::native(opcode, modrm) {
            self.x87_cache_open();
            let slow = self.b.block_void();
            self.b.load_fixed_u8(gp::x87_native_policy as u32);
            self.b.eqz_i32();
            self.b.hint(false);
            self.b.br_if(slow);
            let cache = self.x87_cache.as_ref().map(X87Cache::unsafe_clone);
            let mut words = X87Operands {
                b: &mut self.b,
                words: [&low, &high],
                cache,
            };
            x87_native(&mut words, native, slow);
            self.b.br(done);
            self.b.block_end();
        }
        // (the helper works on the CPU state)
        self.x87_close();
        self.c32(form);
        self.b.get_local(&low);
        self.b.get_local(&high);
        self.b.call_signature(
            "x64_x87",
            Signature::new(
                &[WasmType::I32, WasmType::I32, WasmType::I32],
                &[WasmType::I64],
            ),
        );
        self.s(TV);
        self.g(TV);
        self.b.wrap_i64_to_i32();
        self.b.set_local(&low);
        self.g(TV);
        self.c64(32);
        self.b.shr_u_i64();
        self.b.wrap_i64_to_i32();
        self.b.set_local(&high);
        self.b.block_end();
        if let Io::Store { bytes } = io {
            self.gi(HOST);
            self.b.get_local(&high);
            self.b.extend_unsigned_i32_to_i64();
            self.c64(32);
            self.b.shl_i64();
            self.b.get_local(&low);
            self.b.extend_unsigned_i32_to_i64();
            self.b.or_i64();
            self.store(bytes * 8);
        }
    }
    /// Retry unless the vector instruction may execute (the interpreter
    /// raises #UD or #NM): SSE with CR0.EM and TS clear and CR4.OSFXSR set,
    /// a VEX form with CR0.TS clear, CR4.OSXSAVE set and XCR0 with SSE and
    /// AVX state (budget_flags)
    fn vector_check(&mut self, inst: &Inst, start: u64) {
        // (P4.18: once per block; nothing a block compiles changes CR0, CR4
        // or XCR0)
        let kind = if inst.d.vex.is_none() { VECTOR_SSE } else { VECTOR_VEX };
        if self.env.sse_fast_check {
            if self.vector_checked & kind != 0 {
                return;
            }
            self.vector_checked |= kind;
        }
        self.budget_check(kind as i32, start);
    }
    /// The address of the 64 bits at `offset` (0, 8, 16, 24) of YMM
    /// register `n`
    fn ymm(n: u8, offset: u32) -> u32 {
        if offset < 16 {
            Self::xmm(n) + offset
        }
        else {
            unsafe { gp::ymm_hi.add(n as usize) as u32 + offset - 16 }
        }
    }
    /// YMM register `n` = (`low`, `high`): the low half through the XMM
    /// accessors (its v128 local while held, P4.17), bits 255:128 in memory
    fn ymm_store(&mut self, n: u8, low: &WasmLocalV128, high: &WasmLocalV128) {
        self.ymm_zeroed &= !(1 << n);
        if self.env.xmm_locals {
            self.b.get_local_v128(low);
            self.xv_pop(n);
        }
        else {
            self.c32(Self::ymm(n, 0) as i32);
            self.b.get_local_v128(low);
            self.b.simd_memory(0x0B, 0); // v128.store
        }
        self.c32(Self::ymm(n, 16) as i32);
        self.b.get_local_v128(high);
        self.b.simd_memory(0x0B, 0); // v128.store
    }
    /// Zero bits 255:128 of YMM register `n`
    fn ymm_zero(&mut self, n: u8) {
        if self.ymm_zeroed >> n & 1 != 0 {
            return;
        }
        self.ymm_zeroed |= 1 << n;
        for half in 0..2 {
            self.c32(unsafe { gp::ymm_hi.add(n as usize) } as i32 + 8 * half);
            self.c64(0);
            self.b.store_aligned_i64(0);
        }
    }
    /// A VEX form's register destination `n` written (last): its bits
    /// 255:128 zeroed
    fn vex_upper(&mut self, inst: &Inst, n: u8) {
        if inst.d.vex.is_some() {
            self.ymm_zero(n);
        }
    }
    /// XMM register `to` = XMM register `from`
    fn xmm_copy(&mut self, from: u8, to: u8) {
        if self.env.xmm_locals {
            self.xv_push(from);
            self.xv_pop(to);
            return;
        }
        for half in 0..2 {
            self.xmm_load(from, half * 8, 64);
            self.xmm_store(to, half * 8, 64, false);
        }
    }
    /// SSE ADD/MUL/SUB/DIV natively when the result is exactly what the
    /// interpreter (SoftFloat, crate::x64::vector) produces: round to
    /// nearest and every exception masked (FTZ and DAZ may be set: they
    /// affect none of the operands and results admitted here); operands
    /// finite and normal or zero; a divisor that is not zero; and a result
    /// that is normal above the smallest binade (no underflow, whichever way
    /// tininess is detected) or an exact zero. An inexact result sets PE
    /// itself (INX). Otherwise the instruction is retried in the
    /// interpreter; no lane is written before all passed.
    fn vfp(
        &mut self,
        inst: &Inst,
        start: u64,
        code: u8,
        double: bool,
        packed: bool,
        dst: u8,
        first: u8,
        src: Xmm,
    ) {
        self.vector_check(inst, start);
        // (DAZ and FTZ change nothing for the operands and results below;
        // the exception flags other than PE are never set by them)
        self.b.load_fixed_i32(gp::mxcsr as u32);
        self.c32(0x7F80);
        self.b.and_i32();
        self.c32(0x1F80);
        self.b.ne_i32();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
        self.c32(0);
        self.si(INX);
        let bits = if packed {
            128
        }
        else if double {
            64
        }
        else {
            32
        };
        if let Xmm::Mem(a) = src {
            self.vector_address(&a, bits, packed && inst.d.vex.is_none(), false, inst);
        }
        self.c32(0);
        self.si(COND);
        for half in 0..if packed { 2 } else { 1 } {
            self.xmm_load(first, half * 8, 64);
            self.s(TV);
            match src {
                Xmm::Reg(s) => self.xmm_load(s, half * 8, 64),
                Xmm::Mem(_) => {
                    self.gi(HOST);
                    self.load_bits(bits.min(64), half * 8);
                },
            }
            self.s(TC);
            let out = if half == 0 { FP0 } else { FP1 };
            if double {
                self.g(TV);
                self.s(TA);
                self.g(TC);
                self.s(TB);
                self.fp_lane(code, true);
                self.g(TR);
                self.s(out);
                continue;
            }
            for lane in 0..if packed { 2 } else { 1 } {
                for (from, to) in [(TV, TA), (TC, TB)] {
                    self.g(from);
                    if lane == 1 {
                        self.c64(32);
                        self.b.shr_u_i64();
                    }
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                    self.s(to);
                }
                self.fp_lane(code, false);
                if lane == 0 {
                    self.g(TR);
                }
                else {
                    self.g(out);
                    self.g(TR);
                    self.c64(32);
                    self.b.shl_i64();
                    self.b.or_i64();
                }
                self.s(out);
            }
        }
        self.gi(COND);
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
        // an inexact result sets PE (sticky)
        self.gi(INX);
        self.b.if_void();
        self.c32(gp::mxcsr as i32);
        self.b.load_fixed_i32(gp::mxcsr as u32);
        self.c32(0x20);
        self.b.or_i32();
        self.b.store_aligned_i32(0);
        self.b.block_end();
        if !packed && first != dst {
            // (a scalar form's other lanes from VEX.vvvv)
            self.xmm_copy(first, dst);
        }
        self.g(FP0);
        self.xmm_store(dst, 0, if packed || double { 64 } else { 32 }, true);
        if packed {
            self.g(FP1);
            self.xmm_store(dst, 8, 64, false);
        }
        self.vex_upper(inst, dst);
    }
    /// One lane of vfp: operand bit patterns in TA and TB (zero-extended in
    /// single precision), the result's into TR; refusals or'ed into COND
    fn fp_lane(&mut self, code: u8, double: bool) {
        let (shift, max, magnitude) =
            if double { (52, 0x7FF, 0x7FFF_FFFF_FFFF_FFFF) } else { (23, 0xFF, 0x7FFF_FFFF) };
        let zero = |e: &mut Self, x: usize| {
            e.g(x);
            e.c64(magnitude);
            e.b.and_i64();
            e.b.op(op::OP_I64EQZ);
        };
        let exponent = |e: &mut Self, x: usize| {
            e.g(x);
            e.c64(shift);
            e.b.shr_u_i64();
            e.c64(max);
            e.b.and_i64();
            e.s(TX);
        };
        // operands: no NaN or infinity (exponent all ones), no denormal
        for x in [TA, TB] {
            exponent(self, x);
            self.g(TX);
            self.c64(max);
            self.b.eq_i64();
            self.g(TX);
            self.b.op(op::OP_I64EQZ);
            zero(self, x);
            self.b.eqz_i32();
            self.b.and_i32();
            self.b.or_i32();
            self.fp_refuse();
        }
        if code == 0x5E {
            // a zero divisor: #Z, or #I for 0/0
            zero(self, TB);
            self.fp_refuse();
        }
        for x in [TA, TB] {
            self.g(x);
            if double {
                self.b.reinterpret_i64_as_f64();
            }
            else {
                self.b.wrap_i64_to_i32();
                self.b.reinterpret_i32_as_f32();
            }
        }
        let operation = match code {
            0x58 => 0,
            0x5C => 1,
            0x59 => 2,
            _ => 3,
        };
        if double {
            self.b.arithmetic_f64(operation);
            self.b.reinterpret_f64_as_i64();
        }
        else {
            self.b.arithmetic_f32(operation);
            self.b.reinterpret_f32_as_i32();
            self.b.extend_unsigned_i32_to_i64();
        }
        self.s(TR);
        // the result: its exponent 0 or 1 (possible underflow) or all ones
        // (overflow) is refused, unless it is an exact zero
        exponent(self, TR);
        self.g(TX);
        self.c64(!1);
        self.b.and_i64();
        self.b.op(op::OP_I64EQZ);
        self.g(TX);
        self.c64(max);
        self.b.eq_i64();
        self.b.or_i32();
        zero(self, TR);
        match code {
            // a zero sum or difference of finite normal operands is exact
            0x58 | 0x5C => {},
            // a zero product is exact only with a zero factor
            0x59 => {
                zero(self, TA);
                zero(self, TB);
                self.b.or_i32();
                self.b.and_i32();
            },
            // a zero quotient only with a zero dividend
            _ => {
                zero(self, TA);
                self.b.and_i32();
            },
        }
        self.b.eqz_i32();
        self.b.and_i32();
        self.fp_refuse();
        self.fp_inexact(code, double);
        self.gi(INX);
        self.b.or_i32();
        self.si(INX);
    }
    /// Push i32 1 when the lane's result (TR) is not the exact result of the
    /// operation on TA and TB (sets MXCSR.PE), for the operands and results
    /// fp_lane admits. Single precision: the operation is exact in double
    /// (TwoSum for ADD/SUB). Double: TwoSum, and Dekker's TwoProduct for MUL
    /// (and DIV: the product of quotient and divisor is the dividend), which
    /// refuse extreme exponents where its terms would overflow or underflow.
    fn fp_inexact(&mut self, code: u8, double: bool) {
        let value = |e: &mut Self, i: usize| {
            e.g(i);
            if double {
                e.b.reinterpret_i64_as_f64();
            }
            else {
                e.b.wrap_i64_to_i32();
                e.b.reinterpret_i32_as_f32();
                e.b.promote_f32_to_f64();
            }
        };
        value(self, TA);
        let x = self.b.set_new_local_f64();
        value(self, TB);
        if code == 0x5C {
            self.b.unary_f64(true);
        }
        let y = self.b.set_new_local_f64();
        value(self, TR);
        let r = self.b.set_new_local_f64();
        let f = |e: &mut Self, l: &crate::wasmgen::wasm_builder::WasmLocalF64| e.b.get_local_f64(l);
        match (code, double) {
            (0x58 | 0x5C, _) => {
                // TwoSum: s = x + y, err = (x - (s - bb)) + (y - bb), bb = s - x
                f(self, &x);
                f(self, &y);
                self.b.arithmetic_f64(0);
                let s = self.b.set_new_local_f64();
                f(self, &s);
                f(self, &x);
                self.b.arithmetic_f64(1);
                let bb = self.b.set_new_local_f64();
                f(self, &x);
                f(self, &s);
                f(self, &bb);
                self.b.arithmetic_f64(1);
                self.b.arithmetic_f64(1);
                f(self, &y);
                f(self, &bb);
                self.b.arithmetic_f64(1);
                self.b.arithmetic_f64(0);
                self.b.const_f64(0.0);
                self.b.ne_f64();
                f(self, &s);
                f(self, &r);
                self.b.ne_f64();
                self.b.or_i32();
                self.b.free_local_f64(s);
                self.b.free_local_f64(bb);
            },
            (0x59, false) => {
                f(self, &x);
                f(self, &y);
                self.b.arithmetic_f64(2);
                f(self, &r);
                self.b.ne_f64();
            },
            (_, false) => {
                f(self, &r);
                f(self, &y);
                self.b.arithmetic_f64(2);
                f(self, &x);
                self.b.ne_f64();
            },
            (_, true) => {
                // TwoProduct of (a, b) = (x, y) for MUL, (r, y) for DIV;
                // exact when the error term is 0 (and, for DIV, the product
                // is the dividend). Refused: an operand or the result (not
                // zero) outside 2^-450..2^450, where splitting could overflow
                // or the error terms lose bits to underflow.
                for i in [TA, TB, TR] {
                    self.g(i);
                    self.c64(52);
                    self.b.shr_u_i64();
                    self.c64(0x7FF);
                    self.b.and_i64();
                    self.c64(0x3FF - 450);
                    self.b.sub_i64();
                    self.c64(900);
                    self.b.gtu_i64();
                    self.g(i);
                    self.c64(0x7FFF_FFFF_FFFF_FFFF);
                    self.b.and_i64();
                    self.c64(0);
                    self.b.ne_i64();
                    self.b.and_i32();
                    self.fp_refuse();
                }
                let (a, p) = if code == 0x59 { (&x, &r) } else { (&r, &x) };
                let split = |e: &mut Self, v: &crate::wasmgen::wasm_builder::WasmLocalF64| {
                    // hi = c - (c - v), c = v * (2^27 + 1); lo = v - hi
                    e.b.const_f64(134217729.0);
                    f(e, v);
                    e.b.arithmetic_f64(2);
                    let c = e.b.set_new_local_f64();
                    f(e, &c);
                    f(e, &c);
                    f(e, v);
                    e.b.arithmetic_f64(1);
                    e.b.arithmetic_f64(1);
                    let hi = e.b.set_new_local_f64();
                    f(e, v);
                    f(e, &hi);
                    e.b.arithmetic_f64(1);
                    let lo = e.b.set_new_local_f64();
                    e.b.free_local_f64(c);
                    (hi, lo)
                };
                let (ah, al) = split(self, a);
                let (bh, bl) = split(self, &y);
                // product = a * b rounded (MUL: the result; DIV: computed)
                if code == 0x59 {
                    f(self, &r);
                }
                else {
                    f(self, a);
                    f(self, &y);
                    self.b.arithmetic_f64(2);
                }
                let product = self.b.set_new_local_f64();
                // err = ((ah*bh - product) + ah*bl + al*bh) + al*bl
                f(self, &ah);
                f(self, &bh);
                self.b.arithmetic_f64(2);
                f(self, &product);
                self.b.arithmetic_f64(1);
                f(self, &ah);
                f(self, &bl);
                self.b.arithmetic_f64(2);
                self.b.arithmetic_f64(0);
                f(self, &al);
                f(self, &bh);
                self.b.arithmetic_f64(2);
                self.b.arithmetic_f64(0);
                f(self, &al);
                f(self, &bl);
                self.b.arithmetic_f64(2);
                self.b.arithmetic_f64(0);
                self.b.const_f64(0.0);
                self.b.ne_f64();
                if code != 0x59 {
                    f(self, &product);
                    f(self, p);
                    self.b.ne_f64();
                    self.b.or_i32();
                }
                for l in [ah, al, bh, bl, product] {
                    self.b.free_local_f64(l);
                }
            },
        }
        self.b.free_local_f64(x);
        self.b.free_local_f64(y);
        self.b.free_local_f64(r);
    }
    fn fp_refuse(&mut self) {
        self.gi(COND);
        self.b.or_i32();
        self.si(COND);
    }

    /// The register facts across an instruction that does not keep them
    /// itself (P4.18): what it writes loses its facts, but a register copy
    /// passes them on. The templates of x86tpl::ops on pagegen_vec::Operands
    /// end their destination's facts at each write and state new ones.
    fn xmm_facts(&mut self, op: &Op) {
        match *op {
            Op::Vfp { .. } | Op::Vcmp { .. } | Op::Vcvt { .. } => {},
            Op::Vmove {
                bits: 128,
                dst: Xmm::Reg(d),
                src: Xmm::Reg(s),
                ..
            } => self.xmm_clean[d as usize] = self.xmm_clean[s as usize],
            _ => {
                let mut written = xmm_written(op);
                while written != 0 {
                    self.xmm_clean[written.trailing_zeros() as usize] = 0;
                    written &= written - 1;
                }
            },
        }
    }
    /// Whether XMM register `n` is in its v128 local (P4.17)
    fn held(&self, n: u8) -> bool { self.xmm_held >> n & 1 != 0 }
    /// Load the XMM `registers` (a mask) not held yet into their locals;
    /// only where every path runs (an instruction's start)
    fn xmm_hold(&mut self, registers: u16) {
        let mut load = registers & !self.xmm_held;
        while load != 0 {
            let n = load.trailing_zeros() as usize;
            load &= load - 1;
            let b = &mut self.b;
            let local = self.xmm_locals[n].get_or_insert_with(|| b.declare_zeroed_local_v128());
            self.b.const_i32(Self::xmm(n as u8) as i32);
            self.b.simd_memory(0x00, 0);
            self.b.set_local_v128(local);
        }
        self.xmm_held |= registers;
    }
    /// Hold the XMM `registers` (a mask) without loading those not held yet:
    /// the instruction about to be emitted overwrites them whole before
    /// anything reads them (xmm_overwritten), and until it does, a way out
    /// writes back only what is dirty
    fn xmm_claim(&mut self, registers: u16) {
        let mut claim = registers & !self.xmm_held;
        while claim != 0 {
            let n = claim.trailing_zeros() as usize;
            claim &= claim - 1;
            let b = &mut self.b;
            self.xmm_locals[n].get_or_insert_with(|| b.declare_zeroed_local_v128());
        }
        self.xmm_held |= registers;
    }
    /// Store the held registers written since they were loaded (before
    /// leaving the block, or code that reads XMM memory); any path
    fn xmm_writeback(&mut self) {
        let mut dirty = self.xmm_dirty;
        while dirty != 0 {
            let n = dirty.trailing_zeros() as usize;
            dirty &= dirty - 1;
            self.b.const_i32(Self::xmm(n as u8) as i32);
            self.b.get_local_v128(self.xmm_locals[n].as_ref().unwrap());
            self.b.simd_memory(0x0B, 0);
        }
    }
    /// xmm_writeback, and nothing held from here: only where every path runs
    fn xmm_release(&mut self) {
        self.xmm_writeback();
        self.xmm_held = 0;
        self.xmm_dirty = 0;
    }
    /// Push XMM register `n` (v128): its local while held, else memory
    fn xv_push(&mut self, n: u8) {
        if self.held(n) {
            self.b
                .get_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
        }
        else {
            self.c32(Self::xmm(n) as i32);
            self.b.simd_memory(0x00, 0);
        }
    }
    /// Pop a v128 into XMM register `n`
    fn xv_pop(&mut self, n: u8) {
        if self.held(n) {
            self.b
                .set_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            self.xmm_dirty |= 1 << n;
        }
        else {
            let value = self.b.set_new_local_v128();
            self.c32(Self::xmm(n) as i32);
            self.b.get_local_v128(&value);
            self.b.simd_memory(0x0B, 0);
            self.b.free_local_v128(value);
        }
    }
    /// Push the `bits` (32 or 64) at the host address HOST as a v128, the
    /// rest zero: v128.load32_zero or v128.load64_zero (with the workers'
    /// atomic guest memory a scalar load into lane 0)
    fn load_scalar_v128(&mut self, bits: u8) {
        if WasmBuilder::ATOMIC_GUEST_MEMORY {
            self.b.simd_zero();
            self.gi(HOST);
            self.load_bits(bits, 0);
            if bits == 64 {
                self.b.simd_lane(0x1E, 0); // i64x2.replace_lane
            }
            else {
                self.b.wrap_i64_to_i32();
                self.b.simd_lane(0x1C, 0); // i32x4.replace_lane
            }
            return;
        }
        self.gi(HOST);
        self.b.simd_memory(if bits == 64 { 0x5D } else { 0x5C }, 0);
    }
    /// Push the low `bits` (32 or 64) at byte `offset` of XMM register `n`.
    fn xmm_load(&mut self, n: u8, offset: u32, bits: u8) {
        if self.held(n) {
            self.b
                .get_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            if bits == 32 {
                self.b.simd_lane(0x1B, (offset / 4) as u8); // i32x4.extract_lane
                self.b.extend_unsigned_i32_to_i64();
            }
            else {
                self.b.simd_lane(0x1D, (offset / 8) as u8); // i64x2.extract_lane
            }
            return;
        }
        self.c32((Self::xmm(n) + offset) as i32);
        if bits == 32 {
            self.b.memory_op(op::OP_I64LOAD32U, op::MEM_ALIGN32, 0);
        }
        else {
            self.b.memory_op(op::OP_I64LOAD, op::MEM_ALIGN64, 0);
        }
    }
    /// Store the value on the stack into XMM register `n` at byte `offset`;
    /// a 32-bit store keeps the rest of the qword when `merge`.
    fn xmm_store(&mut self, n: u8, offset: u32, bits: u8, merge: bool) {
        if self.held(n) {
            self.s(TA);
            self.b
                .get_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            self.g(TA);
            if bits == 32 && merge {
                self.b.wrap_i64_to_i32();
                self.b.simd_lane(0x1C, (offset / 4) as u8); // i32x4.replace_lane
            }
            else {
                if bits == 32 {
                    self.c64(0xFFFF_FFFF);
                    self.b.and_i64();
                }
                self.b.simd_lane(0x1E, (offset / 8) as u8); // i64x2.replace_lane
            }
            self.b
                .set_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            self.xmm_dirty |= 1 << n;
            return;
        }
        self.s(TA);
        self.c32((Self::xmm(n) + offset) as i32);
        self.g(TA);
        if bits == 32 && merge {
            self.b.memory_op(op::OP_I64STORE32, op::MEM_ALIGN32, 0);
        }
        else {
            if bits == 32 {
                self.c64(0xFFFF_FFFF);
                self.b.and_i64();
            }
            self.b.store_aligned_i64(0);
        }
    }
    /// Zero XMM register `n` above its low `bits` (32 or 64).
    fn clear_upper(&mut self, n: u8, bits: u8) {
        if self.held(n) {
            self.b
                .get_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            if bits == 32 {
                self.c32(0);
                self.b.simd_lane(0x1C, 1); // i32x4.replace_lane
            }
            self.c64(0);
            self.b.simd_lane(0x1E, 1); // i64x2.replace_lane
            self.b
                .set_local_v128(self.xmm_locals[n as usize].as_ref().unwrap());
            self.xmm_dirty |= 1 << n;
            return;
        }
        if bits == 32 {
            self.c32(Self::xmm(n) as i32 + 4);
            self.c32(0);
            self.b.store_aligned_i32(0);
        }
        self.c32(Self::xmm(n) as i32 + 8);
        self.c64(0);
        self.b.store_aligned_i64(0);
    }
    /// Push the 128-bit source of a packed form: an XMM register, or memory
    /// (legacy SSE: aligned, else #GP, retried).
    fn vector_source(&mut self, src: Xmm, inst: &Inst) {
        match src {
            Xmm::Reg(s) => self.xv_push(s),
            Xmm::Mem(a) => {
                self.vector_address(&a, 128, inst.d.vex.is_none(), false, inst);
                self.gi(HOST);
                let scratch = self.b.set_new_local();
                self.b.get_local(&scratch);
                self.b.guest_load_v128(&scratch);
                self.b.free_local(scratch);
            },
        }
    }
    /// ROUNDPS/PD/SS/SD (Op::Vround): x86tpl::ops::round on the page tier's
    /// operands, whose refused instructions retry
    fn vround(
        &mut self,
        inst: &Inst,
        start: u64,
        double: bool,
        scalar: bool,
        imm8: u8,
        dst: u8,
        first: u8,
        src: Xmm,
    ) {
        self.vector_check(inst, start);
        let mut operands = pagegen_vec::Operands {
            e: self,
            inst,
            start,
            dst,
            first,
            src,
        };
        crate::x86tpl::ops::round(&mut operands, double, scalar, imm8);
        self.vex_upper(inst, dst);
    }
    /// COMISS/UCOMISS/COMISD/UCOMISD. With no NaN or denormal operand the
    /// interpreter changes no MXCSR bit and sets ZF (equal) or CF (less),
    /// clearing the other arithmetic flags; anything else is retried.
    fn vcompare(&mut self, inst: &Inst, start: u64, double: bool, dst: u8, src: Xmm) {
        self.vector_check(inst, start);
        let bits = if double { 64 } else { 32 };
        match src {
            Xmm::Reg(s) => self.xmm_load(s, 0, bits),
            Xmm::Mem(a) => {
                self.vector_address(&a, bits, false, false, inst);
                self.gi(HOST);
                self.load_bits(bits, 0);
            },
        }
        self.s(TB);
        self.xmm_load(dst, 0, bits);
        self.s(TA);
        // retry for a NaN or a denormal: each operand zero, or a normal
        // number's magnitude at least (infinities too)
        for v in [TA, TB] {
            self.float_of(v, double);
            if double {
                self.b.op(op::OP_F64ABS);
                self.b.const_f64(f64::MIN_POSITIVE);
                self.b.op(op::OP_F64GE);
            }
            else {
                self.b.op(op::OP_F32ABS);
                self.b.const_f32(f32::MIN_POSITIVE);
                self.b.op(op::OP_F32GE);
            }
            self.float_of(v, double);
            if double {
                self.b.const_f64(0.0);
                self.b.op(op::OP_F64EQ);
            }
            else {
                self.b.const_f32(0.0);
                self.b.op(op::OP_F32EQ);
            }
            self.b.or_i32();
        }
        self.b.and_i32();
        self.b.eqz_i32();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
        // (a fused condition compares the operands: Known::Float)
        if inst.keep {
            self.g(TA);
            self.s(FA);
            self.g(TB);
            self.s(FB);
        }
        // FL = FL & ~arithmetic | ZF (a == b) | CF (a < b), where read or
        // observable (P4.23)
        if !self.env.exit_flags || inst.writes & (inst.live_out | inst.exit_live) != 0 {
            self.gi(FL);
            self.c32(!ARITH as i32);
            self.b.and_i32();
            for (compare, flag) in [
                ([op::OP_F32EQ, op::OP_F64EQ], ZF),
                ([op::OP_F32LT, op::OP_F64LT], CF),
            ] {
                self.float_of(TA, double);
                self.float_of(TB, double);
                self.b.op(compare[double as usize]);
                if flag != 1 {
                    self.c32(flag.trailing_zeros() as i32);
                    self.b.shl_i32();
                }
                self.b.or_i32();
            }
            self.si(FL);
        }
        self.written(ARITH);
    }
    /// Push the float whose bits local `v` holds: double precision, or
    /// single in its low 32 bits
    fn float_of(&mut self, v: usize, double: bool) {
        self.g(v);
        if double {
            self.b.op(op::OP_F64REINTERPRETI64);
        }
        else {
            self.b.wrap_i64_to_i32();
            self.b.op(op::OP_F32REINTERPRETI32);
        }
    }
    /// CMPPS/CMPPD/CMPSS/CMPSD (Op::Vcmp): x86tpl::ops::compare_mask on the
    /// page tier's operands, whose refused instructions retry (a NaN or
    /// denormal operand raises IE or DE, or makes them unordered)
    #[allow(clippy::too_many_arguments)]
    fn vcmp(
        &mut self,
        inst: &Inst,
        start: u64,
        double: bool,
        scalar: bool,
        predicate: u8,
        dst: u8,
        first: u8,
        src: Xmm,
    ) {
        self.vector_check(inst, start);
        let mut operands = pagegen_vec::Operands {
            e: self,
            inst,
            start,
            dst,
            first,
            src,
        };
        crate::x86tpl::ops::compare_mask(&mut operands, double, scalar, predicate);
        self.vex_upper(inst, dst);
    }
    /// Retry if the float in local `v` (`double` or single precision bits)
    /// is a NaN or a denormal: its exponent all zeros or all ones with a
    /// nonzero fraction
    fn refuse_nan_denormal(&mut self, v: usize, double: bool, start: u64) {
        let (fraction, exponent_shift, exponent_max) =
            if double { ((1u64 << 52) - 1, 52, 0x7FF) } else { ((1u64 << 23) - 1, 23, 0xFF) };
        self.g(v);
        self.c64(fraction);
        self.b.and_i64();
        self.c64(0);
        self.b.ne_i64();
        self.g(v);
        self.c64(exponent_shift);
        self.b.shr_u_i64();
        self.c64(exponent_max);
        self.b.and_i64();
        self.s(TX);
        self.g(TX);
        self.b.op(op::OP_I64EQZ);
        self.g(TX);
        self.c64(exponent_max);
        self.b.eq_i64();
        self.b.or_i32();
        self.b.and_i32();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
    }
    /// MXCSR.PE if INX (an inexact result)
    /// CVTSI2SS/SD (Convert::FromInteger) of TA: MXCSR.PE when |x| has more
    /// significant bits than the precision (24 or 53) after its trailing
    /// zeros (|i64::MIN| is 2^63)
    fn from_integer_inexact(&mut self, double: bool) {
        self.g(TA);
        self.c64(63);
        self.b.shr_s_i64();
        self.s(TB);
        self.g(TA);
        self.g(TB);
        self.b.xor_i64();
        self.g(TB);
        self.b.sub_i64();
        self.s(TC);
        self.c64(64);
        self.g(TC);
        self.b.op(op::OP_I64CLZ);
        self.b.sub_i64();
        self.g(TC);
        self.b.op(op::OP_I64CTZ);
        self.c64(if double { 53 } else { 24 });
        self.b.add_i64();
        self.b.gtu_i64();
        self.si(INX);
        self.inexact_pe();
    }
    fn inexact_pe(&mut self) {
        self.gi(INX);
        self.b.if_void();
        self.c32(gp::mxcsr as i32);
        self.b.load_fixed_i32(gp::mxcsr as u32);
        self.c32(0x20);
        self.b.or_i32();
        self.b.store_aligned_i32(0);
        self.b.block_end();
    }
    /// The packed conversions (Op::Vcvt): x86tpl::ops on the page tier's
    /// operands (pagegen_vec), whose refused instructions retry
    fn vcvt(&mut self, inst: &Inst, start: u64, op: Cvt, dst: u8, src: Xmm) {
        self.vector_check(inst, start);
        let mut operands = pagegen_vec::Operands {
            e: self,
            inst,
            start,
            dst,
            first: dst,
            src,
        };
        match op {
            Cvt::Convert {
                opcode,
                source,
                result,
            } => crate::x86tpl::ops::convert(&mut operands, opcode, source, result),
            Cvt::Integers { double, truncate } => {
                crate::x86tpl::ops::convert_to_integers(&mut operands, double, truncate)
            },
        }
        self.vex_upper(inst, dst);
    }
    /// The scalar conversions (Op::Vconvert) natively when they are exact or
    /// only inexact (PE set here), with MXCSR to nearest and every exception
    /// masked; else retried, as for a NaN or denormal operand, a value out of
    /// the integer's range, and a single-precision result that overflows or
    /// is tiny
    fn vconvert(&mut self, inst: &Inst, start: u64, convert: Convert, dst: u8, first: u8) {
        self.vector_check(inst, start);
        // (FZ and DAZ matter only for the denormals refused here)
        self.b.load_fixed_i32(gp::mxcsr as u32);
        self.c32(0x7F80);
        self.b.and_i32();
        self.c32(0x1F80);
        self.b.ne_i32();
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
        let lane = |double: bool| if double { 64 } else { 32 };
        match convert {
            Convert::FromInteger { double, width, src } => {
                self.read(src, width, inst);
                if width == 32 {
                    self.b.wrap_i64_to_i32();
                    self.b.extend_signed_i32_to_i64();
                }
                self.s(TA);
                // (a 32-bit integer is exact in double precision)
                if !(double && width == 32) {
                    self.from_integer_inexact(double);
                }
                if self.env.xmm_locals {
                    // (into lane 0 of the first source by a lane insert:
                    // the value stays in the vector unit)
                    self.xv_push(first);
                    self.g(TA);
                    if double {
                        self.b.op(op::OP_F64CONVERTSI64);
                        self.b.simd_lane(0x22, 0); // f64x2.replace_lane
                    }
                    else {
                        self.b.op(op::OP_F32CONVERTSI64);
                        self.b.simd_lane(0x20, 0); // f32x4.replace_lane
                    }
                    self.xv_pop(dst);
                    self.vex_upper(inst, dst);
                    return;
                }
                self.g(TA);
                if double {
                    self.b.op(op::OP_F64CONVERTSI64);
                    self.b.op(op::OP_I64REINTERPRETF64);
                }
                else {
                    self.b.op(op::OP_F32CONVERTSI64);
                    self.b.op(op::OP_I32REINTERPRETF32);
                    self.b.extend_unsigned_i32_to_i64();
                }
                self.s(TR);
                if first != dst {
                    // (the other lanes from VEX.vvvv)
                    self.xmm_copy(first, dst);
                }
                self.g(TR);
                self.xmm_store(dst, 0, lane(double), true);
                self.vex_upper(inst, dst);
            },
            Convert::ToInteger {
                double,
                truncate,
                width,
                src,
            } => {
                let bits = lane(double);
                match src {
                    Xmm::Reg(s) => self.xmm_load(s, 0, bits),
                    Xmm::Mem(a) => {
                        self.vector_address(&a, bits, false, false, inst);
                        self.gi(HOST);
                        self.load_bits(bits, 0);
                    },
                }
                self.s(TA);
                self.refuse_nan_denormal(TA, double, start);
                self.g(TA);
                if double {
                    self.b.op(op::OP_F64REINTERPRETI64);
                }
                else {
                    self.b.wrap_i64_to_i32();
                    self.b.op(op::OP_F32REINTERPRETI32);
                    self.b.op(op::OP_F64PROMOTEF32);
                }
                let x = self.b.set_new_local_f64();
                self.b.get_local_f64(&x);
                self.b
                    .op(if truncate { op::OP_F64TRUNC } else { op::OP_F64NEAREST });
                let r = self.b.set_new_local_f64();
                // (outside the integer's range: IE)
                let limit = if width == 64 { 9223372036854775808.0 } else { 2147483648.0 };
                self.b.get_local_f64(&r);
                self.b.const_f64(-limit);
                self.b.op(op::OP_F64GE);
                self.b.get_local_f64(&r);
                self.b.const_f64(limit);
                self.b.op(op::OP_F64LT);
                self.b.and_i32();
                self.b.eqz_i32();
                self.b.if_void();
                self.leave_to(self.f().retry, start);
                self.b.block_end();
                self.b.get_local_f64(&r);
                self.b.get_local_f64(&x);
                self.b.op(op::OP_F64NE);
                self.si(INX);
                self.inexact_pe();
                self.b.get_local_f64(&r);
                self.b.op(op::OP_I64TRUNCSF64);
                self.set_reg(
                    Reg {
                        index: dst,
                        high: false,
                    },
                    width,
                );
                self.b.free_local_f64(x);
                self.b.free_local_f64(r);
            },
            Convert::Precision { double, src } => {
                // (the source's precision is the other one)
                let bits = lane(!double);
                match src {
                    Xmm::Reg(s) => self.xmm_load(s, 0, bits),
                    Xmm::Mem(a) => {
                        self.vector_address(&a, bits, false, false, inst);
                        self.gi(HOST);
                        self.load_bits(bits, 0);
                    },
                }
                self.s(TA);
                self.refuse_nan_denormal(TA, !double, start);
                if double {
                    // single to double precision: exact
                    self.g(TA);
                    self.b.wrap_i64_to_i32();
                    self.b.op(op::OP_F32REINTERPRETI32);
                    self.b.op(op::OP_F64PROMOTEF32);
                    self.b.op(op::OP_I64REINTERPRETF64);
                    self.s(TR);
                    self.c32(0);
                    self.si(INX);
                }
                else {
                    // double to single precision, to nearest: refused when
                    // it overflows (an infinity from a finite value) or is
                    // tiny (at most the smallest normal, from a nonzero value)
                    self.g(TA);
                    self.b.op(op::OP_F64REINTERPRETI64);
                    let x = self.b.set_new_local_f64();
                    self.b.get_local_f64(&x);
                    self.b.op(op::OP_F32DEMOTEF64);
                    self.b.op(op::OP_F64PROMOTEF32);
                    let r = self.b.set_new_local_f64();
                    self.b.get_local_f64(&r);
                    self.b.op(op::OP_F64ABS);
                    self.b.const_f64(f64::INFINITY);
                    self.b.op(op::OP_F64EQ);
                    self.b.get_local_f64(&x);
                    self.b.op(op::OP_F64ABS);
                    self.b.const_f64(f64::INFINITY);
                    self.b.op(op::OP_F64NE);
                    self.b.and_i32();
                    self.b.get_local_f64(&r);
                    self.b.op(op::OP_F64ABS);
                    self.b.const_f64(f32::MIN_POSITIVE as f64);
                    self.b.op(op::OP_F64LE);
                    self.b.get_local_f64(&x);
                    self.b.const_f64(0.0);
                    self.b.op(op::OP_F64NE);
                    self.b.and_i32();
                    self.b.or_i32();
                    self.b.if_void();
                    self.leave_to(self.f().retry, start);
                    self.b.block_end();
                    self.b.get_local_f64(&r);
                    self.b.get_local_f64(&x);
                    self.b.op(op::OP_F64NE);
                    self.si(INX);
                    self.b.get_local_f64(&x);
                    self.b.op(op::OP_F32DEMOTEF64);
                    self.b.op(op::OP_I32REINTERPRETF32);
                    self.b.extend_unsigned_i32_to_i64();
                    self.s(TR);
                    self.b.free_local_f64(x);
                    self.b.free_local_f64(r);
                }
                self.inexact_pe();
                if first != dst {
                    // (the other lanes from VEX.vvvv)
                    self.xmm_copy(first, dst);
                }
                self.g(TR);
                self.xmm_store(dst, 0, lane(double), true);
                self.vex_upper(inst, dst);
            },
        }
    }
    fn load_bits(&mut self, bits: u8, offset: u32) {
        self.b
            .guest_load_i64_bits(if bits == 32 { 32 } else { 64 }, offset);
    }
    /// HOST = host address of the `bits` memory operand, retried when an
    /// aligned form is misaligned (#GP) or the access cache refuses it.
    fn vector_address(
        &mut self,
        a: &AddressExpr,
        bits: u8,
        aligned: bool,
        write: bool,
        inst: &Inst,
    ) {
        self.vector_address_bytes(a, bits as u32 / 8, aligned, write, inst)
    }
    /// vector_address of a `bytes` operand (aligned: an m256 32-byte, the
    /// others 16-byte)
    fn vector_address_bytes(
        &mut self,
        a: &AddressExpr,
        bytes: u32,
        aligned: bool,
        write: bool,
        inst: &Inst,
    ) {
        self.address(a, inst.d.next.0, true);
        self.s(ADDR);
        if aligned {
            self.g(ADDR);
            self.b.wrap_i64_to_i32();
            self.c32(if bytes == 32 { 31 } else { 15 });
            self.b.and_i32();
            self.b.if_void();
            self.leave_to(self.f().retry, inst.d.start.0);
            self.b.block_end();
        }
        // (XMM locals, P4.17: an aligned operand stays in its page)
        let aligned = aligned && self.env.xmm_locals;
        self.host_kind(
            (bytes, aligned),
            (write as u32) << 8,
            inst.d.start.0,
            self.f().retry,
        );
        self.si(HOST);
    }

    fn shift_immediate(
        &mut self,
        inst: &Inst,
        code: u8,
        width: u8,
        dst: Opnd,
        count: u8,
        need: u32,
    ) {
        let raw = shift_count(width, count);
        let w = width as u64;
        self.read_dst(dst, width, true, inst);
        self.s(TA);
        if raw == 0 {
            // No flags; the destination is still written (32-bit zero extension).
            self.write_dst(dst, width, TA);
            return;
        }
        let raw64 = raw as u64;
        let rotate = raw64 % w;
        let narrow = width == 32 && self.env.i32_ops;
        match code {
            // (P4.20: the 32-bit forms in i32, the count below 32)
            _ if narrow => {
                let (count, rotate) = (raw as i32, rotate as i32);
                self.op32(TA, None, |b| match code {
                    4 | 6 => {
                        b.const_i32(count);
                        b.shl_i32();
                    },
                    5 => {
                        b.const_i32(count);
                        b.shr_u_i32();
                    },
                    7 => {
                        b.const_i32(count);
                        b.shr_s_i32();
                    },
                    0 => {
                        b.const_i32(rotate);
                        b.rotl_i32();
                    },
                    _ => {
                        b.const_i32(rotate);
                        b.rotr_i32();
                    },
                });
            },
            4 | 6 => {
                self.g(TA);
                self.c64(raw64);
                self.b.shl_i64();
                self.mask_to(width);
            },
            5 => {
                if raw64 >= w {
                    self.c64(0);
                }
                else {
                    self.g(TA);
                    self.c64(raw64);
                    self.b.shr_u_i64();
                }
            },
            7 => {
                self.g(TA);
                self.sext(width);
                self.c64(raw64);
                self.b.shr_s_i64();
                self.mask_to(width);
            },
            _ => {
                if rotate == 0 {
                    self.g(TA);
                }
                else if width == 64 {
                    self.g(TA);
                    self.c64(rotate);
                    self.b
                        .op(if code == 0 { op::OP_I64ROTL } else { op::OP_I64ROTR });
                }
                else {
                    let (left, right) =
                        if code == 0 { (rotate, w - rotate) } else { (w - rotate, rotate) };
                    self.g(TA);
                    self.c64(left);
                    self.b.shl_i64();
                    self.g(TA);
                    self.c64(right);
                    self.b.shr_u_i64();
                    self.b.or_i64();
                    self.mask_to(width);
                }
            },
        }
        self.s(TR);
        self.write_dst(dst, width, TR);
        if need == 0 {
            return;
        }
        self.flags_begin(need);
        let mut first = true;
        if need & CF != 0 {
            match code {
                4 | 6 if raw64 <= w => self.bit_of(TA, (w - raw64) as u8, 0),
                5 if raw64 <= w => self.bit_of(TA, (raw64 - 1) as u8, 0),
                4 | 5 | 6 => self.c32(0),
                7 => self.bit_of(TA, if raw64 >= w { width - 1 } else { raw - 1 }, 0),
                0 => self.bit_of(if rotate == 0 { TA } else { TR }, 0, 0),
                _ => self.bit_of(if rotate == 0 { TA } else { TR }, width - 1, 0),
            }
            self.join(&mut first);
        }
        if code >= 4 {
            self.szp(TR, need, width, &mut first);
        }
        if raw == 1 && need & OF != 0 {
            match code {
                4 | 6 => {
                    self.bit_of(TR, width - 1, 0);
                    self.bit_of(TA, width - 1, 0);
                    self.b.xor_i32();
                },
                5 => self.bit_of(TA, width - 1, 0),
                7 => self.c32(0),
                0 => {
                    self.bit_of(TR, width - 1, 0);
                    self.bit_of(TR, 0, 0);
                    self.b.xor_i32();
                },
                _ => {
                    self.bit_of(TR, width - 1, 0);
                    self.bit_of(TR, width - 2, 0);
                    self.b.xor_i32();
                },
            }
            self.c32(11);
            self.b.shl_i32();
            self.join(&mut first);
        }
        self.flags_end(first);
    }

    /// SHL/SHR/SAR r/m32/64, CL (count below the width once masked).
    fn shift_cl(&mut self, inst: &Inst, code: u8, width: u8, dst: Opnd, need: u32) {
        self.read_dst(dst, width, true, inst);
        self.s(TA);
        self.g(1);
        self.c64(width as u64 - 1);
        self.b.and_i64();
        self.s(TC);
        match code {
            // ROL ROR: the masked count is below the width
            0 | 1 if width == 64 => {
                self.g(TA);
                self.g(TC);
                self.b
                    .op(if code == 0 { op::OP_I64ROTL } else { op::OP_I64ROTR });
            },
            0 | 1 => {
                self.g(TA);
                self.b.wrap_i64_to_i32();
                self.g(TC);
                self.b.wrap_i64_to_i32();
                if code == 0 {
                    self.b.rotl_i32()
                }
                else {
                    self.b.rotr_i32()
                }
                self.b.extend_unsigned_i32_to_i64();
            },
            4 | 6 => {
                self.g(TA);
                self.g(TC);
                self.b.shl_i64();
                self.mask_to(width);
            },
            5 => {
                self.g(TA);
                self.g(TC);
                self.b.shr_u_i64();
            },
            _ => {
                self.g(TA);
                self.sext(width);
                self.g(TC);
                self.b.shr_s_i64();
                self.mask_to(width);
            },
        }
        self.s(TR);
        self.write_dst(dst, width, TR);
        if need == 0 {
            return;
        }
        if code <= 1 {
            // A nonzero count sets CF from the result, OF only for a count of 1.
            self.g(TC);
            self.b.op(op::OP_I64EQZ);
            self.b.eqz_i32();
            self.b.if_void();
            if need & CF != 0 {
                self.flags_begin(CF);
                self.bit_of(TR, if code == 0 { 0 } else { width - 1 }, 0);
                self.flags_end(false);
            }
            if need & OF != 0 {
                self.g(TC);
                self.c64(1);
                self.b.eq_i64();
                self.b.if_void();
                self.flags_begin(OF);
                self.bit_of(TR, width - 1, 0);
                self.bit_of(TR, if code == 0 { 0 } else { width - 2 }, 0);
                self.b.xor_i32();
                self.c32(11);
                self.b.shl_i32();
                self.flags_end(false);
                self.b.block_end();
            }
            self.b.block_end();
            return;
        }
        // A zero count leaves all flags unchanged.
        self.g(TC);
        self.b.op(op::OP_I64EQZ);
        self.b.eqz_i32();
        self.b.if_void();
        let base = need & (CF | PF | ZF | SF);
        if base != 0 {
            self.flags_begin(base);
            let mut first = true;
            if base & CF != 0 {
                self.g(TA);
                if matches!(code, 4 | 6) {
                    self.c64(width as u64);
                    self.g(TC);
                    self.b.sub_i64();
                }
                else {
                    self.g(TC);
                    self.c64(1);
                    self.b.sub_i64();
                }
                self.b.shr_u_i64();
                self.b.wrap_i64_to_i32();
                self.c32(1);
                self.b.and_i32();
                self.join(&mut first);
            }
            self.szp(TR, base, width, &mut first);
            self.flags_end(first);
        }
        if need & OF != 0 {
            self.g(TC);
            self.c64(1);
            self.b.eq_i64();
            self.b.if_void();
            self.flags_begin(OF);
            match code {
                4 | 6 => {
                    self.bit_of(TR, width - 1, 0);
                    self.bit_of(TA, width - 1, 0);
                    self.b.xor_i32();
                },
                5 => self.bit_of(TA, width - 1, 0),
                _ => self.c32(0),
            }
            self.c32(11);
            self.b.shl_i32();
            self.flags_end(false);
            self.b.block_end();
        }
        self.b.block_end();
    }
}

impl Emitter<'_> {
    fn load_selector(&mut self, segment: u8) {
        self.c32(gp::sreg as i32 + segment as i32 * 2);
        self.b.memory_op(op::OP_I64LOAD16U, op::MEM_ALIGN16, 0);
    }
    /// Load segment register `segment` (ES, DS, FS, GS) with the selector in
    /// the i64 on the stack (legacy mode, P7.3): pages::x64_page_load_seg,
    /// as Tier-0's ir_t0_load_seg; a refusal (nothing changed) retries. ST
    /// is then 2 if the code no longer runs here (leave_unless_runnable)
    fn load_segment(&mut self, segment: u8, start: u64) {
        self.b.wrap_i64_to_i32();
        self.si(ST);
        self.c32(segment as i32);
        self.gi(ST);
        self.c32(self.env.segmented as i32);
        self.b.call_signature(
            "x64_page_load_seg",
            Signature::new(
                &[WasmType::I32, WasmType::I32, WasmType::I32],
                &[WasmType::I32],
            ),
        );
        self.ti(ST);
        self.c32(1);
        self.b.eq_i32();
        self.retry_if(start);
    }
    /// After load_segment's instruction: leave for `next` when ST says so
    fn leave_unless_runnable(&mut self, next: u64) {
        self.gi(ST);
        self.b.if_void();
        self.retired();
        self.leave_to(self.f().exit, next);
        self.b.block_end();
    }
    /// POP m16 or m32 (legacy mode, P7.3): the value at ESP stored to the
    /// address computed with ESP after the pop (as instr32_8F_0_mem), then
    /// ESP moves; both accesses are validated before anything changes
    fn pop_memory(&mut self, address: AddressExpr, width: u8, inst: &Inst) {
        let (start, bytes) = (inst.d.start.0, width as u64 / 8);
        self.stack_sized(0, bytes as u32, false, start);
        self.gi(HOST);
        self.load(width);
        self.s(TV);
        let destination = match address.base {
            AddressBase::Register(4) => AddressExpr {
                displacement: address.displacement.wrapping_add(bytes as i64),
                ..address
            },
            _ => address,
        };
        self.prepare_store(&destination, width, inst);
        self.gi(HOST);
        self.g(TV);
        self.store(width);
        self.adjust_sp(bytes);
    }
    /// Step the instruction (in place) when the i32 on the stack is nonzero.
    fn step_if(&mut self, start: u64) {
        self.b.if_void();
        self.leave_to(self.f().step, start);
        self.b.block_end();
    }
    /// Retry when the i32 on the stack is nonzero.
    fn retry_if(&mut self, start: u64) {
        self.b.if_void();
        self.leave_to(self.f().retry, start);
        self.b.block_end();
    }
    fn divide(&mut self, inst: &Inst, signed: bool, width: u8, src: Opnd) {
        let start = inst.d.start.0;
        self.read(src, width, inst);
        self.s(TB);
        self.is_zero(TB);
        self.retry_if(start);
        if width == 64 {
            // RDX must be the (sign) extension of RAX: a wide dividend retries
            self.g(2);
            if signed {
                self.g(0);
                self.c64(63);
                self.b.shr_s_i64();
                self.b.ne_i64();
                self.retry_if(start);
                // MIN / -1 overflows
                self.g(TB);
                self.c64(u64::MAX);
                self.b.eq_i64();
                self.g(0);
                self.c64(1 << 63);
                self.b.eq_i64();
                self.b.and_i32();
                self.retry_if(start);
            }
            else {
                self.c64(0);
                self.b.ne_i64();
                self.retry_if(start);
            }
            self.g(0);
            self.s(TA);
        }
        else if width == 16 {
            // DX:AX (16-bit code, P7.7): a 32-bit dividend, no i64 overflow
            self.g(2);
            self.mask_to(16);
            self.c64(16);
            self.b.shl_i64();
            self.g(0);
            self.mask_to(16);
            self.b.or_i64();
            if signed {
                self.sext(32);
            }
            self.s(TA);
            if signed {
                self.g(TB);
                self.sext(16);
                self.s(TB);
            }
        }
        else {
            // EDX:EAX
            self.g(2);
            self.c64(32);
            self.b.shl_i64();
            self.g(0);
            self.mask_to(32);
            self.b.or_i64();
            self.s(TA);
            if signed {
                self.g(TB);
                self.sext(32);
                self.s(TB);
                self.g(TB);
                self.c64(u64::MAX);
                self.b.eq_i64();
                self.g(TA);
                self.c64(1 << 63);
                self.b.eq_i64();
                self.b.and_i32();
                self.retry_if(start);
            }
        }
        self.g(TA);
        self.g(TB);
        self.b
            .op(if signed { op::OP_I64DIVS } else { op::OP_I64DIVU });
        self.s(TR);
        if width < 64 {
            // the quotient must fit
            self.g(TR);
            if signed {
                self.sext(width);
            }
            else {
                self.mask_to(width);
            }
            self.g(TR);
            self.b.ne_i64();
            self.retry_if(start);
        }
        if self.env.compat {
            // (the 32-bit modes, P7.3: the remainder from the quotient, one
            // multiply where engines emit a second division for i64.rem; the
            // quotient is exact, so the dividend less quotient * divisor)
            self.g(TA);
            self.g(TR);
            self.g(TB);
            self.b.mul_i64();
            self.b.sub_i64();
        }
        else {
            self.g(TA);
            self.g(TB);
            self.b
                .op(if signed { op::OP_I64REMS } else { op::OP_I64REMU });
        }
        self.s(TV);
        self.g(TR);
        self.set_reg(RAX, width);
        self.g(TV);
        self.set_reg(RDX, width);
    }
    /// Direction: +size, or -size with EFLAGS.DF.
    fn step_size(&mut self, size: u64) {
        self.c64(size.wrapping_neg());
        self.c64(size);
        self.gi(FL);
        self.c32(0x400);
        self.b.and_i32();
        self.b.select();
    }
    fn string(&mut self, inst: &Inst, movs: bool, width: u8, rep: bool) {
        let start = inst.d.start.0;
        let size = width as u64 / 8;
        if !rep {
            if movs {
                self.lookup_base = Some((6, 0));
                self.g(6);
                self.segment_base(inst.d.prefixes.segment.unwrap_or(3));
                self.s(ADDR);
                self.host(size as u32, false, start);
                self.load(width);
                self.s(TV);
            }
            self.lookup_base = Some((7, 0));
            self.g(7);
            self.segment_base(0);
            self.s(ADDR);
            self.host(size as u32, true, start);
            if movs {
                self.g(TV);
            }
            else {
                self.get_reg(RAX, width);
            }
            self.store(width);
            self.step_size(size);
            self.s(TX);
            for register in if movs { [6, 7].as_slice() } else { [7].as_slice() } {
                self.g(*register);
                self.g(TX);
                self.b.add_i64();
                if self.env.compat {
                    self.wrap32();
                }
                self.s(*register);
            }
            return;
        }
        // REP: all at once when it stays inside one page per operand, going
        // forward (and, for wide STOS, stores zero); else an interpreter step
        // (an element, or a chunk of RAM) that dispatches back to this block.
        // RCX = 0: nothing happens
        self.g(1);
        self.b.op(op::OP_I64EQZ);
        self.b.eqz_i32();
        self.b.if_void();
        self.gi(FL);
        self.c32(0x400);
        self.b.and_i32();
        self.g(1);
        self.c64(4096 / size);
        self.b.op(op::OP_I64GTU);
        self.b.or_i32();
        if !movs && width != 8 {
            self.get_reg(RAX, width);
            self.c64(0);
            self.b.ne_i64();
            self.b.or_i32();
        }
        self.step_if(start);
        // length in bytes, within 4096
        self.g(1);
        self.c64(size);
        self.b.mul_i64();
        self.b.wrap_i64_to_i32();
        self.si(COND);
        for (register, _) in
            if movs { [(6, false), (7, true)].as_slice() } else { [(7, true)].as_slice() }
        {
            self.g(*register);
            // (the linear address's page offset, with segment bases)
            self.segment_base(if *register == 6 {
                inst.d.prefixes.segment.unwrap_or(3)
            }
            else {
                0
            });
            self.b.wrap_i64_to_i32();
            self.c32(4095);
            self.b.and_i32();
            self.gi(COND);
            self.b.add_i32();
            self.c32(4096);
            self.b.gtu_i32();
            self.step_if(start);
        }
        if movs {
            self.lookup_base = Some((6, 0));
            self.g(6);
            self.segment_base(inst.d.prefixes.segment.unwrap_or(3));
            self.s(ADDR);
            self.host_or(1, false, start, self.f().step);
            self.si(SRC);
            self.lookup_base = Some((7, 0));
            self.g(7);
            self.segment_base(0);
            self.s(ADDR);
            self.host_or(1, true, start, self.f().step);
            self.si(HOST);
            // an overlapping forward copy repeats the source (element order)
            self.gi(HOST);
            self.gi(SRC);
            self.b.gtu_i32();
            self.gi(HOST);
            self.gi(SRC);
            self.gi(COND);
            self.b.add_i32();
            self.b.ltu_i32();
            self.b.and_i32();
            self.step_if(start);
            // (a string operation's elements are not ordered among themselves,
            // but with respect to the other instructions: fenced with workers)
            self.b.guest_fence();
            self.gi(HOST);
            self.gi(SRC);
            self.gi(COND);
            crate::x86tpl::string::memory_copy(&mut self.b);
            self.b.guest_fence();
        }
        else {
            self.lookup_base = Some((7, 0));
            self.g(7);
            self.segment_base(0);
            self.s(ADDR);
            self.host_or(1, true, start, self.f().step);
            self.si(HOST);
            self.b.guest_fence();
            self.gi(HOST);
            self.g(0);
            self.b.wrap_i64_to_i32();
            self.gi(COND);
            crate::x86tpl::string::memory_fill(&mut self.b);
            self.b.guest_fence();
        }
        if self.env.compat {
            self.note_rep(|e| {
                e.g(1);
                e.b.wrap_i64_to_i32();
            });
        }
        self.gi(COND);
        self.b.extend_unsigned_i32_to_i64();
        self.s(TX);
        for register in if movs { [6, 7].as_slice() } else { [7].as_slice() } {
            self.g(*register);
            self.g(TX);
            self.b.add_i64();
            if self.env.compat {
                self.wrap32();
            }
            self.s(*register);
        }
        self.c64(0);
        self.s(1);
        self.b.block_end();
    }
    /// Push the high 64 bits of the 128-bit product of i64 locals `a` and
    /// `b` (signed or unsigned), from 32-bit halves (TC and TX are scratch).
    fn mul_high(&mut self, a: usize, b: usize, signed: bool) {
        let half = |e: &mut Self, l: usize, high: bool| {
            e.g(l);
            if high {
                e.c64(32);
                e.b.shr_u_i64();
            }
            else {
                e.c64(0xFFFF_FFFF);
                e.b.and_i64();
            }
        };
        // TC = lo(a) * lo(b) >> 32
        half(self, a, false);
        half(self, b, false);
        self.b.mul_i64();
        self.c64(32);
        self.b.shr_u_i64();
        self.s(TC);
        // TX = hi(a) * lo(b) + TC (no carry out of 64 bits)
        half(self, a, true);
        half(self, b, false);
        self.b.mul_i64();
        self.g(TC);
        self.b.add_i64();
        self.s(TX);
        // TC = lo(a) * hi(b) + lo(TX)
        half(self, a, false);
        half(self, b, true);
        self.b.mul_i64();
        half(self, TX, false);
        self.b.add_i64();
        self.s(TC);
        // hi(a) * hi(b) + hi(TX) + hi(TC)
        half(self, a, true);
        half(self, b, true);
        self.b.mul_i64();
        half(self, TX, true);
        self.b.add_i64();
        half(self, TC, true);
        self.b.add_i64();
        if signed {
            // minus b when a is negative, minus a when b is negative
            for (x, y) in [(a, b), (b, a)] {
                self.g(x);
                self.c64(63);
                self.b.shr_s_i64();
                self.g(y);
                self.b.and_i64();
                self.b.sub_i64();
            }
        }
    }
    /// REPE/REPNE CMPS or SCAS inside one page per operand, forward: one
    /// loop over the elements, EFLAGS of the last comparison; anything else
    /// is stepped (the step dispatches back here to continue).
    /// Legacy mode: `count`'s i32, elements of a REP string instruction run
    /// here, onto gp::x64_page_rep_elements, which the activation adds to the
    /// core's statistics (a call here would spill the function's registers:
    /// 563.memops 0.92)
    fn note_rep(&mut self, count: impl FnOnce(&mut Self)) {
        self.c32(gp::x64_page_rep_elements as i32);
        self.b.load_fixed_i32(gp::x64_page_rep_elements as u32);
        count(self);
        self.b.add_i32();
        self.b.store_aligned_i32(0);
    }
    fn rep_compare(&mut self, inst: &Inst, width: u8, scan: bool, equal: bool) {
        let start = inst.d.start.0;
        let size = width as u64 / 8;
        self.materialize_if(ARITH);
        // RCX = 0: nothing happens
        self.g(1);
        self.b.op(op::OP_I64EQZ);
        self.b.eqz_i32();
        self.b.if_void();
        self.gi(FL);
        self.c32(0x400);
        self.b.and_i32();
        self.g(1);
        self.c64(4096 / size);
        self.b.op(op::OP_I64GTU);
        self.b.or_i32();
        self.step_if(start);
        // at most this many bytes, within 4096
        self.g(1);
        self.c64(size);
        self.b.mul_i64();
        self.b.wrap_i64_to_i32();
        self.si(COND);
        for register in if scan { [7].as_slice() } else { [6, 7].as_slice() } {
            self.g(*register);
            // (the linear address's page offset, with segment bases)
            self.segment_base(if *register == 6 {
                inst.d.prefixes.segment.unwrap_or(3)
            }
            else {
                0
            });
            self.b.wrap_i64_to_i32();
            self.c32(4095);
            self.b.and_i32();
            self.gi(COND);
            self.b.add_i32();
            self.c32(4096);
            self.b.gtu_i32();
            self.step_if(start);
        }
        if !scan {
            self.lookup_base = Some((6, 0));
            self.g(6);
            self.segment_base(inst.d.prefixes.segment.unwrap_or(3));
            self.s(ADDR);
            self.host_or(1, false, start, self.f().step);
            self.si(SRC);
        }
        self.lookup_base = Some((7, 0));
        self.g(7);
        self.segment_base(0);
        self.s(ADDR);
        self.host_or(1, false, start, self.f().step);
        self.si(HOST);
        // (the elements are plain loads, ordered as a whole by a fence with
        // cores in workers; any alignment)
        let plain = |e: &mut Self, base: usize| {
            e.gi(base);
            e.gi(ENT);
            e.b.add_i32();
            e.b.memory_op(
                match width {
                    8 => op::OP_I64LOAD8U,
                    16 => op::OP_I64LOAD16U,
                    32 => op::OP_I64LOAD32U,
                    _ => op::OP_I64LOAD,
                },
                op::MEM_NO_ALIGN,
                0,
            );
        };
        if scan {
            self.get_reg(RAX, width);
            self.s(TA);
        }
        self.c32(0);
        self.si(ENT);
        let again = self.b.loop_void();
        if !scan {
            plain(self, SRC);
            self.s(TA);
        }
        plain(self, HOST);
        self.s(TB);
        self.gi(ENT);
        self.c32(size as i32);
        self.b.add_i32();
        self.si(ENT);
        self.g(TA);
        self.g(TB);
        if equal {
            self.b.eq_i64();
        }
        else {
            self.b.ne_i64();
        }
        self.gi(ENT);
        self.gi(COND);
        self.b.ltu_i32();
        self.b.and_i32();
        self.b.br_if(again);
        self.b.block_end();
        self.b.guest_fence();
        // elements done: RCX, RSI, RDI
        if self.env.compat {
            let shift = size.trailing_zeros() as i32;
            self.note_rep(|e| {
                e.gi(ENT);
                e.c32(shift);
                e.b.shr_u_i32();
            });
        }
        self.gi(ENT);
        self.b.extend_unsigned_i32_to_i64();
        self.s(TX);
        self.g(1);
        self.g(TX);
        self.c64(size.trailing_zeros() as u64);
        self.b.shr_u_i64();
        self.b.sub_i64();
        self.s(1);
        for register in if scan { [7].as_slice() } else { [6, 7].as_slice() } {
            self.g(*register);
            self.g(TX);
            self.b.add_i64();
            if self.env.compat {
                self.wrap32();
            }
            self.s(*register);
        }
        // EFLAGS: the last comparison (and last_op1, its first operand)
        self.note_last_op1(TA);
        self.g(TA);
        self.g(TB);
        self.b.sub_i64();
        self.mask_to(width);
        self.s(TR);
        self.alu_flags(7, width, 0);
        self.record(7, width, ARITH, 0, inst);
        self.b.block_end();
    }
    fn compare_exchange(&mut self, inst: &Inst, wide: bool, address: &AddressExpr) {
        let start = inst.d.start.0;
        self.address(address, inst.d.next.0, true);
        self.s(ADDR);
        if wide {
            self.g(ADDR);
            self.c64(15);
            self.b.and_i64();
            self.b.wrap_i64_to_i32();
            self.retry_if(start);
        }
        self.host(if wide { 16 } else { 8 }, true, start);
        self.si(HOST);
        self.gi(HOST);
        self.load(64);
        self.s(TA);
        if wide {
            self.gi(HOST);
            self.b.guest_load_i64_bits(64, 8);
            self.s(TB);
            self.g(TA);
            self.g(0);
            self.b.eq_i64();
            self.g(TB);
            self.g(2);
            self.b.eq_i64();
            self.b.and_i32();
            self.si(COND);
            self.gi(HOST);
            self.g(3);
            self.g(TA);
            self.gi(COND);
            self.b.select();
            self.store(64);
            self.gi(HOST);
            self.g(1);
            self.g(TB);
            self.gi(COND);
            self.b.select();
            self.b.guest_store_i64_bits(64, 8);
            self.gi(COND);
            self.b.eqz_i32();
            self.b.if_void();
            self.g(TA);
            self.s(0);
            self.g(TB);
            self.s(2);
            self.b.block_end();
        }
        else {
            // EDX:EAX against the qword, ECX:EBX stored on a match
            self.g(2);
            self.c64(32);
            self.b.shl_i64();
            self.g(0);
            self.mask_to(32);
            self.b.or_i64();
            self.g(TA);
            self.b.eq_i64();
            self.si(COND);
            self.gi(HOST);
            self.g(1);
            self.c64(32);
            self.b.shl_i64();
            self.g(3);
            self.mask_to(32);
            self.b.or_i64();
            self.g(TA);
            self.gi(COND);
            self.b.select();
            self.store(64);
            self.gi(COND);
            self.b.eqz_i32();
            self.b.if_void();
            self.g(TA);
            self.set_reg(RAX, 32);
            self.g(TA);
            self.c64(32);
            self.b.shr_u_i64();
            self.set_reg(RDX, 32);
            self.b.block_end();
        }
        self.flags_begin(ZF);
        self.gi(COND);
        self.c32(6);
        self.b.shl_i32();
        self.flags_end(false);
        self.written(ZF);
    }
}

// The immediate shifts of the v128 on the stack (Tier-0's take a local:
// x86tpl::vec::shift_immediate); tests/x86tpl/pagegen_leaf_digests.rs pins
// the output.

/// PSRLx/PSRAx/PSLLx (`bits` 16, 32 or 64: the lane width) and PSRLDQ/PSLLDQ
/// (128: bytes) by imm8 `count` of the v128 on the stack, `kind` the ModRM
/// reg (2 PSRL, 4 PSRA, 6 PSLL, 3 PSRLDQ, 7 PSLLDQ): replace it by the result
fn shift_immediate(w: &mut WasmBuilder, bits: u8, kind: u8, count: u8) {
    let count = count as u32;
    if bits == 128 {
        w.simd_zero();
        w.simd_shuffle(leaves::byte_shift_lanes(count, kind == 3));
    }
    else if count >= bits as u32 && kind != 4 {
        w.drop_();
        w.simd_zero();
    }
    else {
        let shift = match kind {
            6 => Shift::Left,
            4 => Shift::Arithmetic,
            _ => Shift::Logical,
        };
        leaves::shift_lanes(w, bits, shift, count.min(bits as u32 - 1));
    }
}

#[path = "pagegen_vec.rs"]
mod pagegen_vec;

#[cfg(test)]
#[path = "../../../tests/x86tpl/pagegen_leaf_digests.rs"]
mod pagegen_leaf_digests;

/// STI and the instruction in its shadow compiled together (x64_sti_shadow,
/// docs/jit-unification-plan.md P4.5d)
#[cfg(test)]
mod sti_shadow_tests {
    use super::{compile_with, CompileEnv, PAGE};

    fn compiled(page: &[u8], sti_shadow: bool) -> Vec<u8> {
        let env = CompileEnv::replay(
            true,
            true,
            true,
            false,
            false,
            true,
            sti_shadow,
            false,
            1024,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            None,
            false,
            &[],
        );
        compile_with(&env, page, &[], &[0], "sti".into())
            .expect("compiled")
            .bytes
    }
    fn imports_irq_window(bytes: &[u8]) -> bool {
        bytes.windows(19).any(|w| w == b"x64_page_irq_window")
    }

    #[test]
    fn sti_and_its_shadow_compile_together() {
        // STI; NOP; CLI; RET
        let mut page = vec![0xCC; PAGE];
        page[..4].copy_from_slice(&[0xFB, 0x90, 0xFA, 0xC3]);
        assert!(imports_irq_window(&compiled(&page, true)));
        assert!(!imports_irq_window(&compiled(&page, false)));
    }

    #[test]
    fn a_discovery_cut_short_before_sti_keeps_it_apart() {
        // 20 JZ to 20 runs of 160 NOPs and RET; the first run (discovered
        // last, after the decoding limit) ends in STI; NOP; CLI; RET, so
        // the CLI after the shadow is no block start
        let mut page = vec![0xCC; PAGE];
        let target = |k: usize| 0x100 + k * 0xA8;
        for k in 0..20 {
            let at = k * 6;
            let rel = (target(k) as i32 - (at as i32 + 6)).to_le_bytes();
            page[at..at + 6].copy_from_slice(&[0x0F, 0x84, rel[0], rel[1], rel[2], rel[3]]);
        }
        page[120] = 0xC3;
        for k in 0..20 {
            page[target(k)..target(k) + 160].fill(0x90);
            page[target(k) + 160] = 0xC3;
        }
        page[target(0) + 160..target(0) + 164].copy_from_slice(&[0xFB, 0x90, 0xFA, 0xC3]);
        // (it compiled into End::Shadow at a non-start, which panicked)
        assert!(!imports_irq_window(&compiled(&page, true)));
    }
}
                                                                                                                          source/v64/src/rust/x64/pagegen_vec.rs                                                              0000644 0000000 0000000 00000025713 00000000000 014712  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The page tier's operands for the x86tpl::ops templates
//! (docs/jit-unification-plan.md P2.4, P2.5): the XMM registers in the CPU
//! state, memory operands through the access cache (vector_address, which
//! retries an aligned form's misaligned address). A refused instruction
//! retries in the interpreter, which leaves the CPU as the templates found
//! it (they write after their last retry point); with x64_sse_fast_check
//! (P4.18) SSE arithmetic and compares run the exact helper in place
//! instead, as Tier-0's. MXCSR.PE may be clear: the templates set it for an
//! inexact result. With x64_sse_fast_check the page tier keeps register
//! facts as Tier-0 (Emitter::xmm_clean): every write here ends the
//! destination's, and the arithmetic, compare and conversion templates read
//! and state them. Integer results are i64 here: store_int extends a
//! template's i32 explicitly.
use super::{low_lanes, low_single, Emitter, Inst, Op, Reg, Xmm, HOST};
use crate::wasmgen::wasm_builder::{WasmBuilder, WasmLocalV128};
use crate::x86tpl::native_fp;
use crate::x86tpl::ops::{Facts, VecOperands};
use crate::x86tpl::vec::{sse_fp_call, sse_fp_result};

/// One instruction's operands: destination `dst`, first source `first` (the
/// destination, or VEX.vvvv), r/m operand `src`
pub(super) struct Operands<'e, 'b> {
    pub e: &'e mut Emitter<'b>,
    pub inst: &'e Inst,
    /// the instruction's offset, where a retry resumes
    pub start: u64,
    pub dst: u8,
    pub first: u8,
    pub src: Xmm,
}

impl VecOperands for Operands<'_, '_> {
    fn w(&mut self) -> &mut WasmBuilder { &mut self.e.b }
    // (XMM registers through the emitter's accessors: their v128 locals
    // while held, P4.17)
    fn first(&mut self) { self.e.xv_push(self.first) }
    fn source(&mut self, bytes: u8, whole: bool) {
        match self.src {
            Xmm::Reg(s) => {
                self.e.xv_push(s);
                if bytes < 16 && !whole {
                    // the low `bytes`, zero-extended
                    self.e.b.simd_zero();
                    self.e.b.simd_shuffle(low_lanes(bytes));
                }
            },
            Xmm::Mem(a) => {
                // (legacy SSE's m128 operands are aligned)
                let aligned = bytes == 16 && self.inst.d.vex.is_none();
                self.e
                    .vector_address(&a, bytes * 8, aligned, false, self.inst);
                if bytes == 16 {
                    self.e.gi(HOST);
                    let scratch = self.e.b.set_new_local();
                    self.e.b.get_local(&scratch);
                    self.e.b.guest_load_v128(&scratch);
                    self.e.b.free_local(scratch);
                    return;
                }
                if matches!(bytes, 4 | 8) {
                    self.e.load_scalar_v128(bytes * 8);
                    return;
                }
                // (exactly the operand's bytes: a broadcast's may be 1 or 2)
                self.e.b.simd_zero();
                self.e.gi(HOST);
                self.e.b.guest_load_i64_bits(bytes as u32 * 8, 0);
                if bytes == 8 {
                    self.e.b.simd_lane(0x1E, 0); // i64x2.replace_lane
                }
                else {
                    self.e.b.wrap_i64_to_i32();
                    self.e.b.simd_lane(0x1C, 0); // i32x4.replace_lane
                }
            },
        }
    }
    fn register(&mut self, r: u8) { self.e.xv_push(r) }
    /// (compatibility mode has XMM0-7: VZEROUPPER and VZEROALL keep
    /// YMM8-15 there)
    fn registers(&self) -> u8 {
        if self.e.env.compat {
            8
        }
        else {
            16
        }
    }
    fn memory(&self) -> bool { matches!(self.src, Xmm::Mem(_)) }
    fn first_high(&mut self) {
        self.e.c32(Emitter::ymm(self.first, 16) as i32);
        self.e.b.simd_memory(0x00, 0); // v128.load
    }
    fn source_high(&mut self) {
        let Xmm::Reg(s) = self.src
        else {
            unreachable!("a register form's");
        };
        self.e.c32(Emitter::ymm(s, 16) as i32);
        self.e.b.simd_memory(0x00, 0); // v128.load
    }
    fn source256(&mut self, aligned: bool) -> [WasmLocalV128; 2] {
        let Xmm::Mem(a) = self.src
        else {
            unreachable!("a memory form's");
        };
        self.e
            .vector_address_bytes(&a, 32, aligned, false, self.inst);
        [0, 16].map(|offset| {
            self.e.gi(HOST);
            self.e.c32(offset);
            self.e.b.add_i32();
            let scratch = self.e.b.set_new_local();
            self.e.b.get_local(&scratch);
            self.e.b.guest_load_v128(&scratch);
            self.e.b.free_local(scratch);
            self.e.b.set_new_local_v128()
        })
    }
    fn store256(&mut self, low: &WasmLocalV128, high: &WasmLocalV128) {
        self.e.xmm_clean[self.dst as usize] = 0;
        self.e.ymm_store(self.dst, low, high);
    }
    fn store256_rm(&mut self, halves: &[WasmLocalV128; 2], aligned: bool) {
        match self.src {
            Xmm::Reg(s) => {
                self.e.xmm_clean[s as usize] = 0;
                self.e.ymm_store(s, &halves[0], &halves[1]);
            },
            Xmm::Mem(a) => {
                self.e
                    .vector_address_bytes(&a, 32, aligned, true, self.inst);
                for (half, offset) in [(&halves[0], 0), (&halves[1], 16)] {
                    self.e.gi(HOST);
                    self.e.c32(offset);
                    self.e.b.add_i32();
                    let address = self.e.b.set_new_local();
                    self.e.b.guest_store_v128(&address, half);
                    self.e.b.free_local(address);
                }
            },
        }
    }
    fn zero_upper(&mut self, r: u8) { self.e.ymm_zero(r) }
    fn destination(&mut self) { self.e.xv_push(self.dst) }
    fn relaxed_fma(&self) -> bool { self.e.env.relaxed_fma }
    fn sse_fp_operands(&self) -> u32 { self.e.env.sse_fp_operands }
    fn store_register(&mut self, r: u8, value: &WasmLocalV128) {
        self.e.xmm_clean[r as usize] = 0;
        if self.e.env.xmm_locals {
            self.e.b.get_local_v128(value);
            self.e.xv_pop(r);
        }
        else {
            self.e.c32(Emitter::xmm(r) as i32);
            self.e.b.get_local_v128(value);
            self.e.b.simd_memory(0x0B, 0); // v128.store
        }
        self.e.ymm_zero(r);
    }
    fn store_vec(&mut self, value: &WasmLocalV128, bytes: u8) {
        // (a template states the new facts after its write)
        self.e.xmm_clean[self.dst as usize] = 0;
        if bytes < 16 && self.e.env.xmm_locals && self.e.held(self.dst) {
            // (into the held register, no lane through a general register:
            // the other lanes from the first source; a single's lane by
            // f32x4 lane moves, one vector move where the shuffle took four
            // on ARM64)
            if bytes == 4 {
                self.e.xv_push(self.first);
                self.e.b.get_local_v128(value);
                low_single(&mut self.e.b);
                self.e.xv_pop(self.dst);
                return;
            }
            self.e.b.get_local_v128(value);
            self.e.xv_push(self.first);
            self.e.b.simd_shuffle(low_lanes(bytes));
            self.e.xv_pop(self.dst);
            return;
        }
        if bytes < 16 && self.first != self.dst {
            // (a scalar form's other lanes from VEX.vvvv)
            self.e.xmm_copy(self.first, self.dst);
        }
        if !self.e.env.xmm_locals {
            // (memory only: as before P4.17)
            self.e.c32(Emitter::xmm(self.dst) as i32);
            self.e.b.get_local_v128(value);
            match bytes {
                16 => self.e.b.simd_memory(0x0B, 0), // v128.store
                8 => {
                    self.e.b.simd_lane(0x1D, 0); // i64x2.extract_lane
                    self.e.b.store_aligned_i64(0);
                },
                _ => {
                    self.e.b.simd_lane(0x1B, 0); // i32x4.extract_lane
                    self.e.b.store_aligned_i32(0);
                },
            }
            return;
        }
        self.e.b.get_local_v128(value);
        match bytes {
            16 => self.e.xv_pop(self.dst),
            8 => {
                self.e.b.simd_lane(0x1D, 0); // i64x2.extract_lane
                self.e.xmm_store(self.dst, 0, 64, false);
            },
            _ => {
                self.e.b.simd_lane(0x1B, 0); // i32x4.extract_lane
                self.e.b.extend_unsigned_i32_to_i64();
                self.e.xmm_store(self.dst, 0, 32, true);
            },
        }
    }
    fn store_int(&mut self, wide: bool) {
        if !wide {
            self.e.b.extend_unsigned_i32_to_i64();
        }
        let r = Reg {
            index: self.dst,
            high: false,
        };
        self.e.set_reg(r, if wide { 64 } else { 32 });
    }
    fn retry_if(&mut self) { self.e.retry_if(self.start) }
    /// (x64_sse_fast_check: DAZ either way, see native_fp::mxcsr_refused_any_daz)
    fn mxcsr_refused(&mut self) {
        if self.e.env.sse_fast_check {
            self.e.fp_mxcsr_refused();
        }
        else {
            native_fp::mxcsr_refused(&mut self.e.b);
        }
    }
    /// (only the templates whose code after a refusal suits an exact result:
    /// arithmetic and compares)
    fn in_place(&self) -> bool {
        self.e.env.sse_fast_check && matches!(self.inst.op, Op::Vfp { .. } | Op::Vcmp { .. })
    }
    fn detects_inexact(&self) -> bool { true }
    fn exact_open(
        &mut self,
        destination: &WasmLocalV128,
        source: &WasmLocalV128,
        imm8: Option<u32>,
    ) {
        dbg_assert!(self.in_place());
        self.e.b.hint(false);
        self.e.b.if_void();
        // (a VEX form: its legacy form's key, the first source as the
        // destination)
        let d = &self.inst.d;
        let key = match d.vex {
            Some(_) => crate::cpu::avx::legacy(d.opcode),
            None => d.opcode,
        };
        let imm8 = imm8.unwrap_or(d.immediate.map_or(0, |i| i.value as u32 & 0xFF));
        sse_fp_call(
            &mut self.e.b,
            self.e.env.sse_fp_operands,
            key,
            imm8,
            destination,
            source,
        );
        self.e.retry_if(self.start);
        // (it may have set PE: native results from here on)
        self.e.mxcsr_flag();
    }
    fn exact_result(&mut self) { sse_fp_result(&mut self.e.b, self.e.env.sse_fp_operands) }
    /// (the templates whose facts the page tier follows: arithmetic,
    /// compares, conversions)
    fn facts(&mut self) -> Option<Facts<'_>> {
        if !self.e.env.sse_fast_check
            || !matches!(
                self.inst.op,
                Op::Vfp { .. } | Op::Vcmp { .. } | Op::Vcvt { .. }
            )
        {
            return None;
        }
        Some(Facts {
            clean: &mut self.e.xmm_clean,
            reg: self.dst,
            first: self.first,
            source: match self.src {
                Xmm::Reg(r) => Some(r),
                Xmm::Mem(_) => None,
            },
        })
    }
}
                                                     source/v64/src/rust/x64/pages.rs                                                                    0000644 0000000 0000000 00000346557 00000000000 013562  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Runtime of the x64 page tier (x64::pagegen): which long-mode pages to
//! compile, publication into the shared Wasm table, entry, the helpers that
//! generated code calls, and invalidation.
//!
//! A function is keyed by the RAM backing page of its code alone, and is
//! position independent: every linear page that maps to that backing page
//! runs it. Entry translates RIP for execution first, so a function only runs
//! while its page maps to the bytes it was compiled from; writes to the
//! backing page (CPU, DMA, host) retire it through jit::jit_dirty_page.
//! Code in extended RAM has keys from extended::CODE_KEY_BASE on (the
//! extended page, whichever frame holds it); extended.rs watches its writes.
//! Code in read-only device memory (the UEFI firmware's flash) has keys from
//! DEVICE_KEY_BASE on; mapping changes of device memory retire it
//! (retire_device_code).
//! With x64_page_compat32 (docs/jit-unification-plan.md P7.2), 32-bit code
//! in compatibility mode runs here too: its functions have the key of their
//! page with COMPAT_KEY, so a page run in both modes has a function for each.
//! With x64_page_legacy32 (P7.3), so does 32-bit code in legacy protected
//! mode: compiled as compatibility mode's, translated through the 32-bit
//! paging and TLB (cpu::translate_address), with LEGACY_KEY besides.
use super::{extended, jac, memory, pagegen, paging, physical, state};
use crate::cpu::{apic, cpu, execution, global_pointers as gp};
use crate::jitrt::capacity;
use crate::jitrt::chain::ChainTable;
use crate::jitrt::heat::{self, backoff, HeatBatch, HEAT_BATCH_LIMIT};
use crate::jitrt::page::{self, PageFrontend};
use crate::jitrt::publish::{self, Phase};
use crate::jitrt::step::{self, StepFrontend, StepOutcome};
use crate::jitrt::ClientId;
use crate::page::Page;
use crate::step_profile::{self, event};
use std::collections::{HashMap, HashSet};

extern "C" {
    fn call_indirect1_ret(f: i32, x: u16) -> i32;
}

/// Interpreted instructions on a page before it is compiled.
const HOT: u32 = 2000;
/// Unserved entries reached through a published function before recompiling
/// (x64_page_set_recompile_misses).
static mut RECOMPILE_MISSES: u32 = 64;
#[no_mangle]
pub unsafe fn x64_page_set_recompile_misses(misses: u32) { RECOMPILE_MISSES = misses.max(1); }
/// HOT and RECOMPILE_MISSES of legacy-mode code (x64_legacy_heat and
/// x64_legacy_recompile_misses; P7.2b, P7.3). An XP boot runs one 32-bit
/// OS's code, much of it lukewarm and entered from ever new places, where a
/// compile (each starts V8's tier-up anew) costs more than interpreting:
/// IR Tier-0 (deleted in P7.5) compiled a page at 50000 instructions and
/// never for new entries.
/// (XP to the desktop, i440FX, one core: at 2000 and 64, 1435 compiles of
/// 568 pages, 98 MB of Wasm, 18.2 s; at these, 365 of 247, 27 MB, 13.4 s.)
static mut LEGACY_HEAT: u32 = 50_000;
static mut LEGACY_MISSES: u32 = 4096;
pub unsafe fn set_legacy_heat(heat: u32) { LEGACY_HEAT = heat; }
pub unsafe fn set_legacy_recompile_misses(misses: u32) { LEGACY_MISSES = misses; }
/// Compiles of a page before each further one waits twice as long (heat
/// and unserved entries): a page recompiled for ever new entries, or
/// rewritten over and over, costs ever less; its code stays in use.
/// (`page`: the function's key, which tells legacy-mode code)
fn recompile_due(page: u32, state: &PageState) -> bool {
    let misses = unsafe {
        if page & LEGACY_KEY != 0 {
            LEGACY_MISSES
        }
        else {
            RECOMPILE_MISSES
        }
    };
    state.misses >= misses << backoff(state.compiles)
}
pub const MAX_FUNCTIONS: usize = 9000;
/// The functions of one code mode (long, 32-bit compatibility) beyond which
/// a full table evicts that mode's (P7.2b)
const MODE_SHARE: usize = MAX_FUNCTIONS * 2 / 3;
const MAX_TRACKED_PAGES: usize = 65536;
const FAST_SLOTS: usize = 16384;

/// The x64 page tier as a client of jitrt's page runtime (P5.7): its
/// functions' code facts, its code pages' own state and its own runtime
/// state
struct X86;
impl PageFrontend for X86 {
    type Code = X86Code;
    type Page = X86Page;
    type Extra = X86Extra;
}
type Function = page::Function<X86Code>;
type PageState = heat::PageState<X86Page>;
type Runtime = page::PageRuntime<X86>;

/// A function's own data. (Its key, the page number of its backing page
/// with the code mode's bits, or an extended page's key (see code_key);
/// `served`, its block starts as a bitmap of offsets, 64 words a page of
/// `members`, the keys of the consecutive linear pages it covers: a span of
/// legacy-mode code, P7.3b, else just its page: page::Function's.)
#[derive(Default)]
struct X86Code {
    /// The bytes its instructions were decoded from, as `served`
    /// (pagegen::Compiled::code): dirty_bytes
    code: Vec<u64>,
    /// The offsets its instructions start at, as `served`
    starts: Vec<u64>,
    /// The bytes of its volatile instructions (pagegen::Compiled::dynamic)
    dynamic: Vec<u64>,
    /// the source page's bytes (hash) when compiled: with cores in workers,
    /// checked again after the page is published (crate::parallel::code)
    source: u64,
    /// compiled with outlined access lookups and an execution counter, the
    /// HOT_COUNTS cell (a cold compile with x64_hot_inline, P4.14)
    counter: Option<u32>,
    /// The tier's native instructions when it was compiled (stats[RETIRED]):
    /// how long it ran when its page is written (dirty_page)
    native_at: u64,
    /// 16-bit protected-mode code (P7.7): the IP of its first page's first
    /// byte as compiled (its linear address less CS's base), which the
    /// function requires (pagegen::CompileEnv::ip_base)
    ip_base: i32,
}
fn bit(set: &[u64], offset: u16) -> bool { set[offset as usize / 64] >> (offset % 64) & 1 != 0 }
/// The function a full table retires for a compile of (`compat`) code: the
/// least recently used ready one, of that code's mode when the mode holds
/// more than MODE_SHARE (P7.2b)
fn eviction_victim(r: &Runtime, compat: bool) -> Option<usize> {
    r.victim(|f| (f.page & COMPAT_KEY != 0) == compat, MODE_SHARE)
}
/// A code page's own state (heat::PageState's `x`)
#[derive(Default)]
struct X86Page {
    /// its code ran often: compiled with inline access lookups from then on
    /// (x64_hot_inline, P4.14; not a compile of its own, no backoff)
    hot: bool,
    /// times run() found it entered from the linear page before it (0) or
    /// after it (1), with x64_page_clusters: span_members (P7.3b)
    from: [u16; 2],
    /// a write retired its function (dirty_page): no span takes it, P7.3b
    written: bool,
    /// Offsets of instructions a write changed while compiled
    /// (dirty_bytes), volatile in its compiles alone from then on
    /// (pagegen::CompileEnv::volatile); `volatile_new`: some since its last
    /// compile, which run() repeats at its next miss
    volatile: Vec<u16>,
    volatile_new: bool,
}
/// The runtime's own state
struct X86Extra {
    /// dead functions' HOT_COUNTS cells, free again when their slots are
    /// released
    released_counters: Vec<u32>,
    last_rip: u64,
    /// The linear page the last activation or miss run ended on (P7.3b)
    last_page: u64,
}
static mut RUNTIME: Option<Runtime> = None;
/// Hot path lookup: backing page number and function index + 1, validated
/// against the function on every use.
static mut FAST: [(u32, u32); FAST_SLOTS] = [(0, 0); FAST_SLOTS];
// Statistics (x64_page_stat): compiled, native retired, retries, unknown
// exits, steps, invalidated, entries, compile failures, recompiles,
// instructions compiled, templated, evictions.
const COMPILED: usize = 0;
const RETIRED: usize = 1;
const RETRIES: usize = 2;
const UNKNOWN: usize = 3;
const INVALIDATED: usize = 5;
const ENTRIES: usize = 6;
const FAILED: usize = 7;
const RECOMPILED: usize = 8;
const INSTRUCTIONS: usize = 9;
const TEMPLATED: usize = 10;
const EVICTED: usize = 11;
/// recompiles of hot pages with inline lookups (x64_page_stat 33, P4.14)
const HOT_RECOMPILES: usize = 12;

/// Event counters for profiling (x64_page_stat 13..19, 25): activations of
/// page functions, INVLPG, control register writes, access cache misses
/// (x64_page_access calls), access cache fills of the VGA frame buffer, MOV
/// CR3 keeping global translations, INVLPG flushing a large-page region,
/// unaligned reads served from BOUNCE.
pub static mut COUNTERS: [u64; 23] = [0; 23];
pub const COUNT_ACTIVATIONS: usize = 0;
pub const COUNT_INVLPG: usize = 1;
pub const COUNT_CR_WRITES: usize = 2;
pub const COUNT_ACCESS_MISSES: usize = 3;
pub const COUNT_LFB_FILLS: usize = 4;
pub const COUNT_CR3_KEEP_GLOBAL: usize = 5;
pub const COUNT_JAC_LARGE_FLUSH: usize = 6;
/// (cores in workers) unaligned reads served from BOUNCE
pub const COUNT_UNALIGNED_READS: usize = 7;
/// control register writes by register (x64_page_stat 26..28), and those
/// that flushed every translation (29)
pub const COUNT_CR0_WRITES: usize = 8;
pub const COUNT_CR3_WRITES: usize = 9;
pub const COUNT_CR4_WRITES: usize = 10;
pub const COUNT_FULL_FLUSHES: usize = 11;
/// translations that walked the page tables (x64_page_stat 30); 32-bit TLB
/// entries filled from x64 translations in compatibility mode (31), of which
/// for pages it had already (32)
pub const COUNT_WALKS: usize = 12;
pub const COUNT_COMPAT_FILLS: usize = 13;
pub const COUNT_COMPAT_REFILLS: usize = 14;
/// Access cache fills, and those that replaced another page's live entry
/// (a conflict in the direct-mapped table; P4.15)
pub const COUNT_JAC_FILLS: usize = 15;
pub const COUNT_JAC_CONFLICTS: usize = 16;
/// compiles of compatibility-mode pages (x64_page_stat 36, P7.2)
pub const COUNT_COMPAT_COMPILES: usize = 17;
/// legacy-mode compiles (P7.3)
pub const COUNT_LEGACY_COMPILES: usize = 18;
/// compiles of spans (P7.3b), and their pages
pub const COUNT_SPANS: usize = 19;
pub const COUNT_SPAN_PAGES: usize = 20;
/// 16-bit protected-mode compiles (P7.7)
pub const COUNT_PROT16_COMPILES: usize = 21;
/// real-mode and virtual-8086 compiles (P7.8)
pub const COUNT_V86_COMPILES: usize = 22;
/// (32 bytes: a VEX.256 load's)
#[repr(C, align(16))]
struct Bounce([u8; 32]);
static mut BOUNCE: Bounce = Bounce([0; 32]);
/// (generated code copies unaligned reads there itself: pagegen)
pub unsafe fn bounce_address() -> u32 { &raw mut BOUNCE as u32 }
/// x64_page_timing: milliseconds inside page function calls and in execute
/// as a whole (x64_page_stat 20 and 22; 23: first calls, 24: bytes compiled)
static mut TIMING: bool = false;
#[no_mangle]
pub unsafe fn x64_page_timing(enabled: bool) { TIMING = enabled; }
mod time {
    #[link(wasm_import_module = "env")]
    extern "C" {
        pub fn microtick() -> f64;
    }
}
static mut TIME_IN_CALLS: f64 = 0.0;
static mut TIME_IN_EXECUTE: f64 = 0.0;
/// first calls with budget 0 (the engine compiles the function lazily)
static mut TIME_FIRST_CALLS: f64 = 0.0;
static mut BYTES_COMPILED: u64 = 0;
/// A generated function is running.
static mut ACTIVE: bool = false;
/// An activation is under way, steps and helpers in it too (physical::
/// set_window refuses to change the bus then; M11, as the IR cache's busy)
static mut IN_ACTIVATION: bool = false;
pub fn in_activation() -> bool { unsafe { IN_ACTIVATION } }
/// It was compiled for segment bases (P7.2(3)), as all it chains to
static mut SEGMENTED_ACTIVE: bool = false;
/// Code-page invalidations; a step that changes it ends the activation.
static mut CODE_WRITES: u64 = 0;
static mut STEPS: u64 = 0;

/// The runtime state. Single-threaded, and no caller holds the reference
/// across a call that can re-enter this module (compilation, publication,
/// generated code, the interpreter or jit::).
fn rt() -> &'static mut Runtime {
    unsafe {
        (*(&raw mut RUNTIME)).get_or_insert_with(|| {
            Runtime::new(X86Extra {
                released_counters: Vec::new(),
                last_rip: 0,
                last_page: 0,
            })
        })
    }
}
fn fast_slot(page: u32) -> usize { (page as usize ^ (page as usize >> 12)) & (FAST_SLOTS - 1) }

pub struct Attempt {
    pub retired: u32,
    pub submitted: bool,
}
fn miss() -> Attempt {
    Attempt {
        retired: 0,
        submitted: false,
    }
}

/// Native execution is exact only without instruction-level observers.
/// Deliverable interrupts were taken by handle_irqs before this point; any
/// that become pending meanwhile wait at most one activation budget (steps
/// that make one deliverable end the activation).
pub unsafe fn allowed() -> bool {
    if *gp::in_hlt
        || *gp::interrupt_shadow != 0
        || *gp::flags as u64 & (0x100 | 0x10000) != 0
        || state::read_dr(7) & 255 != 0
        || execution::is_deterministic()
        || !(state::mode().is_long() || runnable32())
    {
        return false;
    }
    crate::jit::enabled()
        && !apic::has_core_events()
        && !apic::nmi_pending()
        && !crate::cpu::smm::smi_deliverable()
}

/// Why run() ran no function although there may be one (a MISS event of
/// the step profile): what allowed() refused, in its order
unsafe fn disallowed(budget: u32) -> u32 {
    if budget == 0 {
        event::MISS_DISABLED
    }
    else if *gp::in_hlt {
        event::MISS_HALT
    }
    else if *gp::interrupt_shadow != 0 {
        event::MISS_SHADOW
    }
    else if *gp::flags as u64 & (0x100 | 0x10000) != 0 {
        event::MISS_TRAP_FLAGS
    }
    else if state::read_dr(7) & 255 != 0 {
        event::MISS_BREAKPOINTS
    }
    else if apic::has_core_events() || apic::nmi_pending() || crate::cpu::smm::smi_deliverable() {
        event::MISS_EVENTS
    }
    else {
        event::MISS_DISABLED
    }
}

/// Per core: code page translations (access cache epoch | user | code mode
/// << 1, linear page, key, global), direct mapped by linear page: code that
/// calls between pages (as 709.smc into the page it rewrites) translates
/// each once. An x64 TLB invalidation changes the epoch, as do legacy-mode
/// flushes (P7.1; INVLPG forgets the page's entry).
const CODE_TLB_SIZE: usize = 16;
type CodeTlb = [(u64, u64, u32, bool); CODE_TLB_SIZE];
static mut CODE_TLB: [CodeTlb; 8] = [[(0, 0, 0, false); CODE_TLB_SIZE]; 8];

/// Chaining (pagegen::Emitter::chain): a page function leaving its page
/// looks the new linear page up here and tail-calls the function serving it,
/// without returning to the dispatch loop: jitrt::chain's tables (P5.8), per
/// core, code mode (P7.2, P7.3) and CPL, tagged with the access cache epoch
/// (so every x64 TLB flush retires the entries; INVLPG retires its page's).
#[repr(C, align(16))]
struct ChainTables([ChainTable; 2 * MODE_KEYS.len()]);
static mut CHAIN: [ChainTables; 8] =
    [const { ChainTables([const { ChainTable::EMPTY }; 2 * MODE_KEYS.len()]) }; 8];
/// Whether generated code may tail-call through the host's function table
/// (x64_page_set_chaining: the engine supports Wasm tail calls).
static mut CHAINING: bool = false;
#[no_mangle]
pub unsafe fn x64_page_set_chaining(enabled: bool) {
    CHAINING = enabled;
    // functions compiled either way stay valid: a function without chaining
    // code only returns
    clear_chains();
}
/// Page functions compiled from now on chain (see CHAINING). With cores in
/// workers each instance chains through its own table and chaining table,
/// and leaves for crate::parallel::code::poll when other cores published or
/// invalidated code (pagegen::Emitter::chain).
pub unsafe fn chaining() -> bool { CHAINING }
unsafe fn chain_base(core: usize, user: bool, mode: usize) -> u32 {
    CHAIN[core].0[mode * 2 + user as usize].base()
}
unsafe fn chain_fill(core: usize, user: bool, mode: usize, rip: u64, slot: u32, global: bool) {
    CHAIN[core].0[mode * 2 + user as usize].fill(
        rip >> 12,
        jac::epoch_bits(core),
        slot + cpu::WASM_TABLE_OFFSET,
        global,
    );
}
/// MOV CR3 (see memory::invalidate_core_nonglobal): code translations of
/// non-global pages go.
pub unsafe fn forget_nonglobal_code(core: usize) {
    for entry in CODE_TLB[core].iter_mut() {
        if !entry.3 {
            entry.0 = 0;
        }
    }
    for table in CHAIN[core].0.iter_mut() {
        table.forget_nonglobal();
    }
}
fn clear_chains() {
    unsafe {
        for core in (*(&raw mut CHAIN)).iter_mut() {
            for table in core.0.iter_mut() {
                table.clear();
            }
        }
    }
}
/// A function is retired: no chaining to its slot any more.
unsafe fn unchain_slot(slot: u32) {
    let index = slot + cpu::WASM_TABLE_OFFSET;
    for core in 0..apic::core_count().clamp(1, 8) {
        for table in CHAIN[core].0.iter_mut() {
            table.unchain(index);
        }
    }
}
/// The key of the code page at `rip` for code of `mode` (see code_key and
/// MODE_KEYS), and whether its translation is global.
unsafe fn code_page(rip: u64, mode: usize) -> Option<(u32, bool)> {
    let core = apic::current_core();
    let tag = jac::epoch_bits(core) | (*gp::cpl == 3) as u64 | (mode as u64) << 1;
    let index = (rip >> 12) as usize & (CODE_TLB_SIZE - 1);
    let (cached_tag, linear, page, global) = CODE_TLB[core][index];
    if cached_tag == tag && linear == rip >> 12 {
        return Some((page, global));
    }
    let (physical, global) = if mode >= MODE_LEGACY {
        legacy_translate(rip as u32, false)?
    }
    else {
        let (physical, _, global) = memory::translate_page_execute(rip).ok()?;
        (physical, global)
    };
    let page = code_key(physical)? | MODE_KEYS[mode];
    CODE_TLB[core][index] = (tag, rip >> 12, page, global);
    Some((page, global))
}
/// The 32-bit translation of linear `address` for the current privilege in
/// legacy mode (P7.3): its physical address and whether it is global. It
/// fills the 32-bit TLB as the interpreter does (accessed and dirty bits)
/// only when it succeeds: a fault is the interpreter's to raise.
unsafe fn legacy_translate(address: u32, write: bool) -> Option<(u64, bool)> {
    let user = *gp::cpl == 3;
    cpu::translate_address(address as i32, write, user, false).ok()?;
    let physical = cpu::translate_address(address as i32, write, user, true).ok()?;
    let entry = cpu::tlb_data[(address >> 12) as usize];
    Some((physical as u64, entry & cpu::TLB_GLOBAL != 0))
}

/// INVLPG `address` on `core`: the cached code translation may be of that
/// page, and so may its chaining entries (a flush of the whole access cache
/// retired the others by epoch).
pub unsafe fn forget_code_page(core: usize, address: u64) {
    let page = address >> 12;
    CODE_TLB[core][page as usize & (CODE_TLB_SIZE - 1)].0 = 0;
    // (the page the running function executes: a stepped INVLPG leaves, as
    // x64_page_invlpg does; in legacy mode any, which may be another page of
    // a span, P7.3b)
    if page == *gp::x64_page_linear >> 12 || state::efer() & state::EFER_LMA == 0 {
        CODE_WRITES += 1;
    }
    for table in CHAIN[core].0.iter_mut() {
        table.forget_page(jac::LAYOUT, page);
    }
}

/// The access cache epoch of `core` wrapped (jac::flush): its code
/// translations of earlier epochs go. (Legacy-mode TLB flushes start epochs
/// too, P7.1: thousands a minute while XP switches processes.)
pub unsafe fn forget_code(core: usize) {
    CODE_TLB[core] = [(0, 0, 0, false); CODE_TLB_SIZE];
    for table in CHAIN[core].0.iter_mut() {
        table.clear();
    }
}

/// The key of the code page at physical `address`: its RAM backing page
/// number, or (above every such number) its extended page's key, or a page
/// of read-only device memory's.
unsafe fn code_key(address: u64) -> Option<u32> {
    if physical::plain_ram(address & !4095, 4096) {
        return Some((address >> 12) as u32);
    }
    match jac::ram_backing(address) {
        Some(backing) => Some(backing >> 12),
        None => match extended::code_key(address) {
            Some(key) => (key < DEVICE_KEY_BASE).then_some(key),
            None => device_code_key(address),
        },
    }
}
/// Keys of pages of read-only device memory -- the UEFI firmware's flash,
/// whose SEC phase runs in place (crate::cpu::mmio_ram) -- in the top 16 MiB
/// below 4 GiB: from here on, above the extended pages' keys and below the
/// mode bits. Their functions are compiled from a copy of the page, as an
/// extended page's; nothing writes such memory while it is read-only.
const DEVICE_KEY_BASE: u32 = STACK_KEY - (1 << 12);
const DEVICE_FIRST_PAGE: u64 = 0xFF000;
unsafe fn device_code_key(address: u64) -> Option<u32> {
    let page = address >> 12;
    // (not with cores in workers: x64_page_install checks RAM pages only)
    if crate::parallel::active()
        || !(DEVICE_FIRST_PAGE..1 << 20).contains(&page)
        || !crate::cpu::mmio_ram::read_only_page(page as u32 * 4096)
    {
        return None;
    }
    Some(DEVICE_KEY_BASE + (page - DEVICE_FIRST_PAGE) as u32)
}
/// The bytes of the device memory page of `key` (a physical key), if it is
/// still mapped and read-only
unsafe fn device_page_bytes(key: u32) -> Option<Vec<u8>> {
    let address = (DEVICE_FIRST_PAGE as u32 + (key - DEVICE_KEY_BASE)) * 4096;
    if !crate::cpu::mmio_ram::read_only_page(address) {
        return None;
    }
    let host = crate::cpu::mmio_ram::read_host(address, 4096)?;
    Some(std::slice::from_raw_parts(host, 4096).to_vec())
}
/// Device memory was mapped, unmapped or made writable: the functions
/// compiled from it go, and the code translations that led there.
pub fn retire_device_code() {
    let r = rt();
    if !r
        .functions
        .iter()
        .any(|f| f.phase != Phase::Dead && is_device(f.page))
    {
        return;
    }
    unsafe {
        CODE_TLB = [[(0, 0, 0, false); CODE_TLB_SIZE]; 8];
    }
    for i in 0..r.functions.len() {
        if is_device(r.functions[i].page) {
            retire(r, i);
        }
    }
}
/// The key bit of a 32-bit function (P7.2; physical keys are below
/// extended::CODE_KEY_BASE plus the extended pages), the one of a
/// legacy-mode function besides (P7.3), of one compiled for segment
/// bases (P7.2(3), segmented_runnable), of 16-bit protected-mode code
/// (P7.7, prot16_runnable) and with that of real-mode and virtual-8086 code
/// (P7.8, real_runnable, v86_runnable)
const COMPAT_KEY: u32 = 1 << 31;
const LEGACY_KEY: u32 = 1 << 30;
const SEGMENTED_KEY: u32 = 1 << 29;
const PROT16_KEY: u32 = 1 << 28;
const REAL_KEY: u32 = 1 << 27;
const V86_KEY: u32 = 1 << 26;
/// (M11) the stack's width is not the code's: 16-bit protected-mode code on
/// a 32-bit stack, 32-bit code compiled for segment bases on a 16-bit stack
/// (prot16_ss32_runnable, segmented_ss16_runnable)
const STACK_KEY: u32 = 1 << 25;
const MODE_BITS: u32 =
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | PROT16_KEY | REAL_KEY | V86_KEY | STACK_KEY;
/// The code key of a function's key: its page as compiled from
fn physical_key(key: u32) -> u32 { key & !MODE_BITS }
/// The code's mode, as function keys, code translations and chaining tables
/// tell it apart: 64-bit, compatibility mode (P7.2), 32-bit legacy protected
/// mode with flat segments (P7.3) and with segment bases (P7.2(3)), 16-bit
/// protected mode (P7.7), real mode and virtual-8086 mode (P7.8)
const MODE_LONG: usize = 0;
const MODE_COMPAT: usize = 1;
const MODE_LEGACY: usize = 2;
const MODE_SEGMENTED: usize = 3;
const MODE_PROT16: usize = 4;
const MODE_REAL: usize = 5;
const MODE_V86: usize = 6;
const MODE_PROT16_SS32: usize = 7;
const MODE_SEGMENTED_SS16: usize = 8;
/// 16-bit code's modes (their functions require CS's base, ip_base)
fn code16(mode: usize) -> bool {
    matches!(mode, MODE_PROT16 | MODE_REAL | MODE_V86 | MODE_PROT16_SS32)
}
const MODE_KEYS: [u32; 9] = [
    0,
    COMPAT_KEY,
    COMPAT_KEY | LEGACY_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | PROT16_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | PROT16_KEY | REAL_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | PROT16_KEY | V86_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | PROT16_KEY | STACK_KEY,
    COMPAT_KEY | LEGACY_KEY | SEGMENTED_KEY | STACK_KEY,
];
unsafe fn code_mode() -> usize {
    let mode = state::mode();
    if mode.is_long() {
        MODE_LONG
    }
    else if state::efer() & state::EFER_LMA != 0 {
        MODE_COMPAT
    }
    else {
        // (legacy mode: runnable_kind's 1 is legacy_runnable)
        match kind_of(mode) {
            1 => MODE_LEGACY,
            3 => MODE_PROT16,
            4 => MODE_REAL,
            5 => MODE_V86,
            6 => MODE_PROT16_SS32,
            7 => MODE_SEGMENTED_SS16,
            _ => MODE_SEGMENTED,
        }
    }
}
/// Code outside RAM: in an extended page, or in device memory (is_device)
fn is_extended(page: u32) -> bool { physical_key(page) >= extended::CODE_KEY_BASE }
fn is_device(page: u32) -> bool { physical_key(page) >= DEVICE_KEY_BASE }

/// Multi-page functions of legacy-mode code (the JIT switch
/// x64_page_clusters, docs/jit-unification-plan.md P7.3b, as Tier-0's
/// neighbour clusters): span_members
static mut CLUSTERS: bool = true;
#[no_mangle]
pub unsafe fn x64_page_set_clusters(enabled: bool) { CLUSTERS = enabled; }
/// Transfers between two pages that make them one span (the JIT switch
/// x64_span_crossings): an XP boot passes once between most neighbours, a
/// loop over pages (708.pages) on every iteration (at 256 an XP boot made
/// 87 spans and compiled 19% more bytes, at 4096 13 spans and 7%)
static mut SPAN_CROSSINGS: u32 = 4096;
pub unsafe fn set_span_crossings(crossings: u32) { SPAN_CROSSINGS = crossings; }
/// Entries (PageState::entry_count) a page of a span has at most: code
/// that runs on from page to page (708.pages: one each) rather than pages
/// of many small functions, one of which runs into the next (an XP boot's
/// spans joined pages of 8 to 117 entries, and made it 1% slower; the JIT
/// switch x64_span_entries)
static mut SPAN_ENTRIES: u32 = 8;
pub unsafe fn set_span_entries(entries: u32) { SPAN_ENTRIES = entries; }
/// The consecutive linear pages of a span of legacy-mode code (P7.3b)
/// around `linear`, whose key is `page`: (key, linear page, physical page),
/// in linear order. A page before (after) the span joins while run() found
/// control passing between it and the span's first (last) page, outside
/// compiled code, SPAN_CROSSINGS times (PageState::from), both have at most
/// SPAN_ENTRIES entries, it maps to plain RAM without a fault, no write
/// retired code of it (PageState::written) and it is no page of the span
/// already; at most pagegen::MAX_SPAN. Not with cores in workers.
unsafe fn span_members(r: &Runtime, page: u32, linear: u64) -> Vec<(u32, u64, u32)> {
    let user = *gp::cpl == 3;
    let mode_key = page & MODE_BITS;
    let at = |linear: u64| -> Option<(u32, u64, u32)> {
        if linear >= 1 << 32 {
            return None;
        }
        let physical = cpu::translate_address(linear as i32, false, user, false).ok()?;
        let key = code_key(physical as u64 & !4095)?;
        (key < extended::CODE_KEY_BASE).then_some((key | mode_key, linear, physical & !4095))
    };
    let Some(own) = at(linear).filter(|&(key, ..)| key == page)
    else {
        return vec![(page, linear, 0)];
    };
    if crate::parallel::active() || !physical::plain_ram((physical_key(page) as u64) << 12, 4096) {
        return vec![own];
    }
    let from = |key: u32, side: usize| r.pages.get(&key).map_or(0, |s| s.x.from[side] as u32);
    let few_entries = |key: u32| {
        r.pages
            .get(&key)
            .is_none_or(|s| s.entry_count <= SPAN_ENTRIES)
    };
    let written = |key: u32| r.pages.get(&key).is_some_and(|s| s.x.written);
    if written(page) {
        return vec![own];
    }
    let mut span = vec![own];
    while span.len() < pagegen::MAX_SPAN && span[0].1 != 0 {
        let Some(before) = at(span[0].1 - 4096)
        else {
            break;
        };
        if from(span[0].0, 0) + from(before.0, 1) < SPAN_CROSSINGS
            || !few_entries(span[0].0)
            || !few_entries(before.0)
            || written(before.0)
            || span.iter().any(|m| m.0 == before.0)
        {
            break;
        }
        span.insert(0, before);
    }
    while span.len() < pagegen::MAX_SPAN {
        let last = *span.last().unwrap();
        let Some(after) = at(last.1 + 4096)
        else {
            break;
        };
        if from(after.0, 0) + from(last.0, 1) < SPAN_CROSSINGS
            || !few_entries(last.0)
            || !few_entries(after.0)
            || written(after.0)
            || span.iter().any(|m| m.0 == after.0)
        {
            break;
        }
        span.push(after);
    }
    span
}
/// compile_mode is compiling its page alone after a span failed (P7.3b)
static mut SPAN_DECLINED: bool = false;
/// Undo compile_mode's count of a compile that it repeats (P7.3b)
fn r_page_uncount(page: u32, hot: bool) {
    if !hot {
        let state = rt().pages.entry(page).or_default();
        state.compiles = state.compiles.saturating_sub(1);
    }
}
/// Before a span's function runs (P7.3b): its prologue finds the page it
/// was entered at by that page's 32-bit TLB entry, which code_page does not
/// fill when its own cache hits
unsafe fn span_translation(rip: u64) {
    if cpu::tlb_data[(rip >> 12) as usize & 0xFFFFF] & cpu::TLB_VALID == 0 {
        legacy_translate(rip as u32, false);
    }
}

/// Compatibility-mode code in the page tier (the JIT switch
/// x64_page_compat32, P7.2; on since M9, which passed its D gate: P7.4):
/// 32-bit code under a 64-bit OS, while its data and stack segments are flat
/// (compat_runnable)
static mut COMPAT32: bool = true;
/// COMPAT32 && PAGE32_TIER0
static mut COMPAT_ACTIVE: bool = false;
#[no_mangle]
pub unsafe fn x64_page_set_compat32(enabled: bool) {
    COMPAT32 = enabled;
    COMPAT_ACTIVE = COMPAT32 && PAGE32_TIER0;
}
pub unsafe fn compat32() -> bool { COMPAT_ACTIVE }
/// The current code runs in the page tier as 32-bit compatibility-mode
/// code: 32-bit CS, a 32-bit stack, and CS, DS, ES and SS with base 0 (as
/// WOW64's are; FS and GS bases are added at each access). Generated code
/// relies on it; a step that changes it leaves (context).
pub unsafe fn compat_runnable() -> bool {
    COMPAT_ACTIVE
        && state::mode() == state::ExecutionMode::Compatibility32
        && *gp::stack_size_32
        && cpu::has_flat_segmentation()
        && *gp::segment_offsets.add(cpu::ES as usize) == 0
        && !*gp::segment_is_null.add(cpu::ES as usize)
}
/// Legacy protected-mode code in the page tier (the JIT switch
/// x64_page_legacy32, P7.3), as 32-bit compatibility-mode code
static mut LEGACY32: bool = true;
/// ir_tier0 (set_page32_tier0): the page tier replaced IR Tier-0, the IR's
/// page-granular compiler (deleted in P7.5); configurations without it
/// interpret 32-bit and 16-bit code (they left it to the region tiers until
/// M11 deleted them)
static mut PAGE32_TIER0: bool = false;
pub unsafe fn page32_tier0() -> bool { PAGE32_TIER0 }
/// LEGACY32 && PAGE32_TIER0
static mut LEGACY_ACTIVE: bool = false;
#[no_mangle]
pub unsafe fn x64_page_set_legacy32(enabled: bool) {
    LEGACY32 = enabled;
    LEGACY_ACTIVE = LEGACY32 && PAGE32_TIER0;
}
/// 16-bit protected-mode code in the page tier (the JIT switch
/// x64_page_prot16, P7.7): Windows 3.x and 9x's 16-bit code
static mut PROT16: bool = true;
/// PROT16 && PAGE32_TIER0
static mut PROT16_ACTIVE: bool = false;
#[no_mangle]
pub unsafe fn x64_page_set_prot16(enabled: bool) {
    PROT16 = enabled;
    PROT16_ACTIVE = PROT16 && PAGE32_TIER0;
}
/// Real-mode and virtual-8086 code in the page tier (the JIT switch
/// x64_page_v86, P7.8): BIOS, DOS and Windows 98's boot, DOS boxes
static mut V86: bool = true;
/// V86 && PAGE32_TIER0
static mut V86_ACTIVE: bool = false;
#[no_mangle]
pub unsafe fn x64_page_set_v86(enabled: bool) {
    V86 = enabled;
    V86_ACTIVE = V86 && PAGE32_TIER0;
}
/// (crate::jit::jit_set_page32, the JIT switch ir_tier0)
pub unsafe fn set_page32_tier0(enabled: bool) {
    PAGE32_TIER0 = enabled;
    LEGACY_ACTIVE = LEGACY32 && PAGE32_TIER0;
    COMPAT_ACTIVE = COMPAT32 && PAGE32_TIER0;
    PROT16_ACTIVE = PROT16 && PAGE32_TIER0;
    V86_ACTIVE = V86 && PAGE32_TIER0;
}
/// Whether a switch hands 32-bit (or 16-bit) code to the page tier (read
/// once a slice)
pub unsafe fn page32() -> bool { COMPAT_ACTIVE || LEGACY_ACTIVE || PROT16_ACTIVE || V86_ACTIVE }
/// The current instruction's linear address, on which the page tier works:
/// RIP in long mode, else CS's base plus EIP (the same with a flat CS, as
/// 32-bit code runs here; 16-bit code's CS has a base, P7.7)
#[inline(always)]
unsafe fn linear_rip() -> u64 {
    if state::mode().is_long() {
        state::read_rip()
    }
    else {
        *gp::instruction_pointer as u32 as u64
    }
}
/// Misses of a 16-bit function compiled under another CS base before its
/// page compiles for the current one (P7.7)
const PROT16_REBASE: u32 = 64;
/// The IP of the first byte of `rip`'s page under the current CS (P7.7)
unsafe fn ip_base_of(rip: u64) -> i32 {
    ((rip & !4095) as u32).wrapping_sub(*gp::segment_offsets.add(cpu::CS as usize) as u32) as i32
}
/// The current code runs in the page tier as 16-bit protected-mode code
/// (P7.7): a 16-bit CS and a 16-bit stack, compiled for segment bases as
/// segmented_runnable (CS's base too: near branches compute IPs in it,
/// pagegen::CompileEnv::ip_base). Data segment limits are not checked, as
/// the interpreter does not.
pub unsafe fn prot16_runnable() -> bool {
    PROT16_ACTIVE
        && state::mode() == state::ExecutionMode::Protected16
        && !*gp::stack_size_32
        && !crate::cpu::smm::smm_active()
}
/// The current code runs in the page tier as real-mode code (P7.8): as
/// prot16_runnable, segment bases the selectors shifted left by 4 (segment
/// loads cannot fault, cpu::switch_seg_without_fault). No A20 wrap: the
/// interpreter has none either. Not in SMM (16-bit code there runs at
/// SMBASE + 0x8000 in SMRAM, which the VGA window hides outside SMM; with
/// the page tier, tests/devices/smm.js failed 11 of 25: the core never left
/// SMM), as prot16_runnable
pub unsafe fn real_runnable() -> bool {
    V86_ACTIVE
        && state::mode() == state::ExecutionMode::Real
        && !*gp::stack_size_32
        && !crate::cpu::smm::smm_active()
}
/// The current code runs in the page tier as virtual-8086 code (P7.8): as
/// real_runnable at CPL 3; the instructions IOPL governs there (PUSHF,
/// POPF, INT n, IRET; CLI and STI check CPL <= IOPL as in protected mode)
/// step, as port I/O does everywhere
pub unsafe fn v86_runnable() -> bool {
    V86_ACTIVE && state::mode() == state::ExecutionMode::Vm86 && !*gp::stack_size_32
}
/// The current code runs in the page tier as 32-bit legacy protected-mode
/// code: as compat_runnable, and with FS not null (its base is added at each
/// access; GS's accesses step, see pagegen Decoder::legacy), paged or not
pub unsafe fn legacy_runnable() -> bool {
    LEGACY_ACTIVE
        && state::mode() == state::ExecutionMode::Protected32
        && *gp::stack_size_32
        && cpu::has_flat_segmentation()
        && *gp::segment_offsets.add(cpu::ES as usize) == 0
        && !*gp::segment_is_null.add(cpu::ES as usize)
        && !*gp::segment_is_null.add(cpu::FS as usize)
}
/// The current code runs in the page tier as legacy-mode code compiled for
/// segment bases (P7.2(3)): 32-bit protected mode with a flat 32-bit CS and
/// a 32-bit stack; each ES, SS, DS, FS or GS access adds its segment's base
/// and, but for SS, checks for a null selector (as Tier-0's functions for
/// other than flat segments do). Windows 98's VMM runs with a nonzero DS
/// base.
pub unsafe fn segmented_runnable() -> bool {
    LEGACY_ACTIVE
        && state::mode() == state::ExecutionMode::Protected32
        && *gp::stack_size_32
        && *gp::segment_offsets.add(cpu::CS as usize) == 0
}
/// The current code runs in the page tier as 32-bit code compiled for
/// segment bases on a 16-bit stack (M11): segmented_runnable but SS.B
/// clear. Windows 98's 16-to-32-bit thunks (2.8% of Diablo's time, 1.4% of
/// Red Alert 2's, left to the region tiers in M10)
pub unsafe fn segmented_ss16_runnable() -> bool {
    LEGACY_ACTIVE
        && state::mode() == state::ExecutionMode::Protected32
        && !*gp::stack_size_32
        && *gp::segment_offsets.add(cpu::CS as usize) == 0
}
/// The current code runs in the page tier as 16-bit protected-mode code on
/// a 32-bit stack (M11): prot16_runnable but SS.B set
pub unsafe fn prot16_ss32_runnable() -> bool {
    PROT16_ACTIVE
        && state::mode() == state::ExecutionMode::Protected16
        && *gp::stack_size_32
        && !crate::cpu::smm::smm_active()
}
/// compat_runnable, legacy_runnable, segmented_runnable, prot16_runnable,
/// real_runnable, v86_runnable, prot16_ss32_runnable or
/// segmented_ss16_runnable
pub unsafe fn runnable32() -> bool { runnable_kind() != 0 }
/// 1 for compat_runnable or legacy_runnable (flat segments), 2 for
/// segmented_runnable only, 3 for prot16_runnable, 4 for real_runnable, 5
/// for v86_runnable, 6 for prot16_ss32_runnable, 7 for
/// segmented_ss16_runnable, else 0: a step that changes it leaves (context;
/// in a function compiled for segment bases, which runs flat segments too,
/// only a change to or from 0)
#[inline(always)]
unsafe fn runnable_kind() -> u8 { kind_of(state::mode()) }
/// runnable_kind for the current state in `mode`: the predicates above with
/// the mode computed once (each computed it; with 7 kinds that cost Theme
/// Hospital 1.5%, M11)
#[inline(always)]
unsafe fn kind_of(mode: state::ExecutionMode) -> u8 {
    use state::ExecutionMode::*;
    let cs_flat = *gp::segment_offsets.add(cpu::CS as usize) == 0;
    let es_flat = || {
        cpu::has_flat_segmentation()
            && *gp::segment_offsets.add(cpu::ES as usize) == 0
            && !*gp::segment_is_null.add(cpu::ES as usize)
    };
    let stack32 = *gp::stack_size_32;
    match mode {
        Protected32 if LEGACY_ACTIVE => {
            if !stack32 {
                if cs_flat {
                    7
                }
                else {
                    0
                }
            }
            else if es_flat() && !*gp::segment_is_null.add(cpu::FS as usize) {
                1
            }
            else if cs_flat {
                2
            }
            else {
                0
            }
        },
        Compatibility32 if COMPAT_ACTIVE && stack32 && es_flat() => 1,
        Protected16 if PROT16_ACTIVE && !crate::cpu::smm::smm_active() => {
            if stack32 {
                6
            }
            else {
                3
            }
        },
        Real if V86_ACTIVE && !stack32 && !crate::cpu::smm::smm_active() => 4,
        Vm86 if V86_ACTIVE && !stack32 => 5,
        _ => 0,
    }
}
/// One interpreted instruction at RIP: the long-mode interpreter, or in
/// compatibility and legacy mode the 32-bit one (as Tier-0's steps)
unsafe fn interpret_one() {
    if state::mode().is_long() {
        cpu::run_long_instruction();
    }
    else {
        cpu::run_compat_instruction();
    }
}

unsafe fn release_dead(r: &mut Runtime) {
    if ACTIVE {
        return;
    }
    r.release_dead(|slot, id| {
        crate::jit::release_page_slot(slot, id);
    });
    (*(&raw mut HOT_FREE)).extend(r.x.released_counters.drain(..));
}

/// Run published code at RIP for up to `budget` instructions, or note the
/// interpreted instruction there. `retired` counts everything this call
/// retired (native instructions and interpreted steps).
pub unsafe fn run(budget: u32) -> Attempt {
    if budget == 0 || !allowed() {
        if step_profile::enabled() {
            step_profile::note_event(event::MISS, disallowed(budget));
        }
        return miss();
    }
    let rip = linear_rip();
    let mode = code_mode();
    let compat = mode != MODE_LONG;
    let Some((page, global)) = code_page(rip, mode)
    else {
        step_profile::note_event(event::MISS, event::MISS_NO_CODE);
        return miss();
    };
    let offset = (rip & 4095) as u16;
    let r = rt();
    if !r.enabled {
        step_profile::note_event(event::MISS, event::MISS_DISABLED);
        return miss();
    }
    if !r.releases.is_empty() {
        release_dead(r);
    }
    let last = r.x.last_rip;
    // (P7.3b: entered from a neighbouring page, the evidence a span takes)
    let here = rip >> 12;
    if CLUSTERS && mode >= MODE_COMPAT && r.x.last_page != here {
        let side = if r.x.last_page.wrapping_add(1) == here {
            Some(0)
        }
        else if r.x.last_page == here.wrapping_add(1) {
            Some(1)
        }
        else {
            None
        };
        if let Some(side) = side {
            let count = &mut r.pages.entry(page).or_default().x.from[side];
            *count = count.saturating_add(1);
        }
    }
    r.x.last_page = here;
    r.x.last_rip = rip;
    // Far transfers (not the next few bytes) start blocks.
    // (and the first instruction a page is entered at from the page before:
    // straight-line code over pages would else step through each page after
    // the first, as no entry of its function, up to its next block start)
    let far = !(last < rip && rip - last <= 15) || last >> 12 != rip >> 12;
    // a page without a function, as at the last miss: its heat goes to the
    // batch (P4.5b)
    if HEAT_BATCH.holds(page, r.generation) && HEAT_BATCH.count < HEAT_BATCH_LIMIT {
        if far {
            note_entry(r, page, offset);
        }
        HEAT_BATCH.count += 1;
        step_profile::note_event(event::MISS, event::MISS_COLD);
        return miss_run(r, page, budget, rip);
    }
    let (fast_page, fast_index) = FAST[fast_slot(page)];
    let index = if fast_page == page && fast_index != 0 {
        Some(fast_index as usize - 1)
    }
    else {
        let found = r.by_page.get(&page).copied();
        if let Some(i) = found {
            FAST[fast_slot(page)] = (page, i as u32 + 1);
        }
        found
    };
    let member = index.and_then(|i| r.functions[i].member(page));
    match index {
        Some(i)
            if member.is_some()
                && r.functions[i].phase == Phase::Ready
                && r.functions[i].serves(member.unwrap(), offset) =>
        {
            // (its code ran often: its recompile with inline lookups)
            if r.functions[i].x.counter.is_some_and(|c| {
                HOT_COUNTS[c as usize] >= if compat { COMPAT_HOT_COUNT } else { HOT_COUNT }
            }) {
                r.stats[HOT_RECOMPILES] += 1;
                return compile_mode(page, true);
            }
            // (P7.7: 16-bit code compiled under a CS of another base, whose
            // prologue would leave at once: the page compiles for this one
            // once that recurs)
            if code16(mode) && r.functions[i].x.ip_base != ip_base_of(rip) {
                step_profile::note_event(event::MISS, event::MISS_UNSERVED);
                let state = r.pages.entry(page).or_default();
                state.misses += 1;
                if state.misses >= PROT16_REBASE {
                    state.misses = 0;
                    return compile(page);
                }
                return miss();
            }
            r.clock += 1;
            r.functions[i].last_used = r.clock;
            let slot = r.functions[i].slot;
            if CHAINING {
                chain_fill(apic::current_core(), *gp::cpl == 3, mode, rip, slot, global);
            }
            if r.functions[i].members.len() > 1 {
                span_translation(rip);
            }
            execute(slot, budget, rip)
        },
        Some(i) if member.is_some() && r.functions[i].phase != Phase::Dead => {
            if r.functions[i].phase == Phase::Ready {
                // An entry the function does not serve: recompile once
                // enough repeated such entries accumulate (note_unserved)
                let state = r.pages.entry(page).or_default();
                if recompile_due(page, state) {
                    state.misses = 0;
                    step_profile::note_event(event::MISS, event::MISS_RECOMPILE);
                    return compile(page);
                }
                step_profile::note_event(event::MISS, event::MISS_UNSERVED);
                // Straight-line code is no entry, as in note_entry's `far`
                // (a block start there would split a loop body in the next,
                // hot, compile): after a retried instruction, or where the
                // interpreter ran up to while the function compiled, the
                // interpreter runs on to an offset the function serves
                if !far && MISS_RUN {
                    // (legacy mode, P7.3: one that recurs, as after an
                    // instruction retried on every iteration, counts towards
                    // a recompile that serves it; Tier-0 continues after
                    // such a step in place)
                    if mode >= MODE_LEGACY {
                        note_unserved(r, page, offset);
                    }
                    return unserved_run(r, i, member.unwrap(), budget, rip);
                }
                // Else the function steps from here to its next block start
                // (pagegen: unserved dispatch) and notes the entry
                if !far {
                    LAST_UNSERVED = last;
                }
                r.clock += 1;
                r.functions[i].last_used = r.clock;
                let slot = r.functions[i].slot;
                if CHAINING {
                    chain_fill(apic::current_core(), *gp::cpl == 3, mode, rip, slot, global);
                }
                if r.functions[i].members.len() > 1 {
                    span_translation(rip);
                }
                return execute(slot, budget, rip);
            }
            step_profile::note_event(event::MISS, event::MISS_COMPILING);
            miss()
        },
        _ => {
            if far {
                note_entry(r, page, offset);
            }
            // (the batch: its count is this page's, or another page's to add first)
            let mut heat = 1;
            if HEAT_BATCH.holds(page, r.generation) {
                heat += HEAT_BATCH.count;
            }
            else {
                flush_heat(r);
            }
            HEAT_BATCH = HeatBatch::NONE;
            let state = r.pages.entry(page).or_default();
            state.heat += heat;
            // (32-bit code's first compile waits for LEGACY_HEAT, which also
            // gathers the page crossings spans take (P7.3b; compatibility
            // mode since M9: compiled at HOT, its pages chained before any
            // crossing reached run); a page compiled before is hot, its
            // function retired by a write. 16-bit code, P7.7, P7.8: every
            // compile waits for LEGACY_HEAT, as DOS and the BIOS write their
            // code pages (a Windows 98 boot: 330 compiles after writes of
            // real-mode and virtual-8086 pages at HOT, 150 at LEGACY_HEAT)
            let hot = if code16(mode) || mode >= MODE_COMPAT && state.compiles == 0 {
                LEGACY_HEAT
            }
            else {
                HOT
            };
            // (instructions a write changed are volatile now: the page's
            // function would stay as they change again, no compile of its
            // own, dirty_bytes)
            if state.x.volatile_new {
                state.x.volatile_new = false;
                state.compiles = state.compiles.saturating_sub(1);
                state.heat = hot << backoff(state.compiles);
            }
            if state.heat >= hot << backoff(state.compiles) {
                state.heat = 0;
                if state.entry_count == 0 {
                    state.entries[offset as usize / 64] |= 1 << (offset % 64);
                    state.entry_count = 1;
                }
                step_profile::note_event(event::MISS, event::MISS_COMPILE);
                return compile(page);
            }
            if BATCH_HEAT {
                HEAT_BATCH = HeatBatch {
                    page,
                    count: 0,
                    generation: r.generation,
                };
            }
            step_profile::note_event(event::MISS, event::MISS_COLD);
            miss_run(r, page, budget, rip)
        },
    }
}

/// Execution counters of cold (outlined) page functions (P4.14), a cell
/// each: the function increments its cell at each entry and dispatch
/// (pagegen Emitter::head), and run() recompiles its page with inline
/// lookups once the cell reaches HOT_COUNT. A cell is free again once its
/// function is released (release_dead): no code increments it then. Cells
/// for every live function and as many retired ones not yet released; a
/// compile that finds none free is not counted (it stays cold).
static mut HOT_COUNTS: [u32; HOT_CELLS] = [0; HOT_CELLS];
const HOT_CELLS: usize = MAX_FUNCTIONS + 1024;
static mut HOT_FREE: Vec<u32> = Vec::new();
/// cells never handed out: HOT_NEXT..HOT_CELLS
static mut HOT_NEXT: u32 = 0;
unsafe fn take_counter() -> Option<u32> {
    let cell = (*(&raw mut HOT_FREE)).pop().or_else(|| {
        (HOT_NEXT < HOT_CELLS as u32).then(|| {
            HOT_NEXT += 1;
            HOT_NEXT - 1
        })
    })?;
    HOT_COUNTS[cell as usize] = 0;
    Some(cell)
}
/// The JIT switches x64_hot_inline and x64_hot_count (P4.14)
static mut HOT_INLINE: bool = true;
static mut HOT_COUNT: u32 = 1 << 22;
#[no_mangle]
pub unsafe fn x64_page_set_hot_inline(enabled: bool) { HOT_INLINE = enabled; }
pub unsafe fn set_hot_count(count: u32) { HOT_COUNT = count; }
/// x64_compat_hot_count: HOT_COUNT of 32-bit compatibility-mode functions
/// (P7.2b): WOW64 code is a small share of what a Windows boot compiles, so
/// its hot pages are recompiled early, as Tier-0 compiles loops at once
static mut COMPAT_HOT_COUNT: u32 = 1 << 16;
pub unsafe fn set_compat_hot_count(count: u32) { COMPAT_HOT_COUNT = count; }

/// Interpreted execution's heat, batched (jitrt::heat::HeatBatch, P4.5b)
static mut HEAT_BATCH: HeatBatch = HeatBatch::NONE;
/// The JIT switches x64_heat_batch (P4.5b) and x64_miss_run (P4.5c)
static mut BATCH_HEAT: bool = true;
static mut MISS_RUN: bool = true;
/// Instructions a miss run interprets at most
const MISS_RUN_LIMIT: u32 = 64;
#[no_mangle]
pub unsafe fn x64_page_set_heat_batch(enabled: bool) {
    flush_heat(rt());
    HEAT_BATCH = HeatBatch::NONE;
    BATCH_HEAT = enabled;
}
#[no_mangle]
pub unsafe fn x64_page_set_miss_run(enabled: bool) { MISS_RUN = enabled; }
/// The batch's heat to its page (whose compile waits for its next miss)
unsafe fn flush_heat(r: &mut Runtime) {
    let b = HEAT_BATCH;
    if b.count != 0 && b.generation == r.generation {
        r.pages.entry(b.page).or_default().heat += b.count;
    }
    HEAT_BATCH.count = 0;
}

/// A miss on code page `page` (at `rip`, which has no function): the
/// interpreter runs the instruction there, and with x64_miss_run (P4.5c)
/// the ones after it on the same linear page, without returning to run():
/// until another page, RIP unchanged (HLT, a REP instruction's batch, a
/// fault restarting it), a change of mode or CPL, a yield or core event,
/// `budget` or MISS_RUN_LIMIT; far transfers within the page are noted as
/// entries on the way, as run() notes them. Without the switch the caller
/// interprets the one instruction (retired 0). Each further instruction is
/// heat for the page, counted in the batch (or directly without
/// x64_heat_batch); its compile waits for the next miss.
unsafe fn miss_run(r: &mut Runtime, page: u32, budget: u32, rip: u64) -> Attempt {
    if !MISS_RUN {
        return miss();
    }
    let (linear, cpl, mode, kind) = (rip >> 12, *gp::cpl, state::mode(), runnable_kind());
    let limit = budget.min(MISS_RUN_LIMIT);
    let span = execution::ledger_begin();
    let (mut n, mut at) = (0, rip);
    // (16-bit code, P7.8: a basic block at a time, as the interpreter runs
    // code without compiled code; one instruction at a time cost a Windows
    // 98 boot, whose real-mode and virtual-8086 code is mostly cold, 3%)
    let blocks = matches!(kind, 3..=6);
    loop {
        crate::x64::extended::safe_point();
        let ran = if blocks {
            cpu::run_interpreted_block(limit - n)
        }
        else {
            *gp::previous_ip = *gp::instruction_pointer;
            interpret_one();
            1
        };
        n += ran;
        // (where the last instruction started)
        let last = if blocks { *gp::previous_ip as u32 as u64 } else { at };
        let next = linear_rip();
        if blocks && (ran == 0 || last >> 12 != linear) {
            break;
        }
        if n >= limit
            || next >> 12 != linear
            || next == at
            || *gp::cpl != cpl
            || state::mode() != mode
            || !mode.is_long() && runnable_kind() != kind
            || *gp::in_hlt
            || cpu::core_yield
            || apic::has_core_events()
        {
            break;
        }
        // (far transfers start blocks, as in run())
        if !(last < next && next - last <= 15) {
            note_entry(r, page, (next & 4095) as u16);
        }
        at = next;
        if HEAT_BATCH.holds(page, r.generation) {
            HEAT_BATCH.count += ran;
        }
        else {
            r.pages.entry(page).or_default().heat += ran;
        }
    }
    // (the next miss compares its RIP with the last instruction run here)
    r.x.last_rip = at;
    r.x.last_page = if *gp::in_hlt { u64::MAX } else { at >> 12 };
    execution::ledger_end(span, execution::Way::Interpreted);
    Attempt {
        retired: n,
        submitted: false,
    }
}

/// unserved_run: run() reached function `i` straight-line at an offset it
/// does not serve (after a retried instruction, as a page-crossing VMOVDQU
/// ymm in a loop's body): the interpreter runs to the next offset the
/// function serves, stopping as miss_run does, instead of entering the
/// function to step each instruction up to its next block start (an
/// activation, a dispatch and a step apiece)
unsafe fn unserved_run(r: &mut Runtime, i: usize, m: usize, budget: u32, rip: u64) -> Attempt {
    let (linear, cpl, mode, kind) = (rip >> 12, *gp::cpl, state::mode(), runnable_kind());
    let limit = budget.min(MISS_RUN_LIMIT);
    let span = execution::ledger_begin();
    let (mut n, mut at) = (0, rip);
    loop {
        crate::x64::extended::safe_point();
        *gp::previous_ip = *gp::instruction_pointer;
        interpret_one();
        n += 1;
        let next = linear_rip();
        if n >= limit
            || next >> 12 != linear
            || !(at < next && next - at <= 15)
            || r.functions[i].serves(m, (next & 4095) as u16)
            || *gp::cpl != cpl
            || state::mode() != mode
            || !mode.is_long() && runnable_kind() != kind
            || *gp::in_hlt
            || cpu::core_yield
            || apic::has_core_events()
        {
            break;
        }
        at = next;
    }
    // (the next miss compares its RIP with the last instruction run here)
    r.x.last_rip = at;
    r.x.last_page = if *gp::in_hlt { u64::MAX } else { at >> 12 };
    execution::ledger_end(span, execution::Way::Interpreted);
    Attempt {
        retired: n,
        submitted: false,
    }
}

/// A published function was entered at `offset`, which it does not serve.
/// Interrupted code resumes at arbitrary instructions, mostly once each; an
/// offset counts as an entry (and towards a recompile) from its second
/// sighting. True when the page is due for a recompile.
fn note_unserved(r: &mut Runtime, page: u32, offset: u16) -> bool {
    let state = r.pages.entry(page).or_default();
    let (word, mask) = (offset as usize / 64, 1u64 << (offset % 64));
    if state.entries[word] & mask != 0 {
        state.misses += 1;
    }
    else if state.seen[word] & mask != 0 {
        state.entries[word] |= mask;
        state.entry_count += 1;
        state.misses += 1;
        r.stats[ENTRIES] += 1;
        if step_profile::enabled() && !is_extended(page) {
            unsafe { ACCESS_REFUSED[6 + late_entry_kind(page, offset)] += 1 };
        }
    }
    else {
        state.seen[word] |= mask;
    }
    recompile_due(page, state)
}
/// (profile) 0: the instruction before looks like a call, 1: 16-byte
/// aligned, 2: other
fn late_entry_kind(page: u32, offset: u16) -> usize {
    let page = physical_key(page);
    let at = |o: u16| unsafe { *crate::cpu::memory::mem8.add(((page << 12) + o as u32) as usize) };
    let o = offset;
    let call = o >= 5 && at(o - 5) == 0xE8
        || o >= 6 && at(o - 6) == 0xFF && at(o - 5) == 0x15
        || o >= 2 && at(o - 2) == 0xFF && at(o - 1) & 0xF8 == 0xD0
        || o >= 3 && at(o - 3) == 0xFF && at(o - 2) & 0x38 == 0x10 && at(o - 2) >> 6 == 1;
    if call {
        0
    }
    else if o % 16 == 0 {
        1
    }
    else {
        2
    }
}
static mut LAST_UNSERVED: u64 = 0;
/// Generated code reached an offset its function does not serve (dispatch
/// after a transfer or a step): 1 to leave (EXIT_UNKNOWN: the page is due for
/// a recompile), 0 to step the instruction there in place. Only the first of
/// consecutive stepped instructions is noted.
#[no_mangle]
pub unsafe fn x64_page_unserved(rip: u64) -> i32 {
    let far =
        !(LAST_UNSERVED < rip && rip - LAST_UNSERVED <= 15) || LAST_UNSERVED >> 12 != rip >> 12;
    LAST_UNSERVED = rip;
    if !far {
        ACCESS_REFUSED[4] += 1;
        return 0;
    }
    let Some((page, _)) = code_page(rip, code_mode())
    else {
        return 1;
    };
    let leave = note_unserved(rt(), page, (rip & 4095) as u16) as i32;
    ACCESS_REFUSED[4] += (leave == 0) as u64;
    leave
}

fn note_entry(r: &mut Runtime, page: u32, offset: u16) {
    if r.pages.len() >= MAX_TRACKED_PAGES && !r.pages.contains_key(&page) {
        // Forget cold pages; published functions keep their own entries.
        r.pages.retain(|_, state| state.compiles != 0);
        if r.pages.len() >= MAX_TRACKED_PAGES / 2 {
            r.pages.clear();
        }
    }
    let state = r.pages.entry(page).or_default();
    let (word, mask) = (offset as usize / 64, 1u64 << (offset % 64));
    if state.entries[word] & mask == 0 {
        state.entries[word] |= mask;
        state.entry_count += 1;
        r.stats[ENTRIES] += 1;
    }
}

unsafe fn execute(slot: u32, budget: u32, rip: u64) -> Attempt {
    if TIMING {
        let t0 = time::microtick();
        let attempt = execute_inner(slot, budget, rip);
        TIME_IN_EXECUTE += time::microtick() - t0;
        return attempt;
    }
    execute_inner(slot, budget, rip)
}
unsafe fn execute_inner(slot: u32, budget: u32, rip: u64) -> Attempt {
    let before = *gp::instruction_counter;
    let span = execution::ledger_begin();
    let core = apic::current_core();
    *gp::x64_jac_base = jac::base(core, *gp::cpl == 3);
    *gp::x64_jac_epoch = jac::epoch_bits(core);
    *gp::x64_page_linear = rip & !4095;
    *gp::x64_page_exit = pagegen::EXIT_NORMAL;
    let mode = code_mode();
    *gp::x64_code_base = chain_base(core, *gp::cpl == 3, mode);
    SEGMENTED_ACTIVE = mode >= MODE_SEGMENTED;
    *gp::x64_page_chain = 0;
    *gp::x64_page_lazy_kind = 0;
    // Generated code keeps EFLAGS materialized.
    if *gp::flags_changed != 0 {
        let flags = state::read_flags64();
        state::write_flags64(flags);
    }
    let interrupts_before = *gp::flags & cpu::FLAG_INTERRUPT;
    ACTIVE = true;
    IN_ACTIVATION = true;
    COUNTERS[COUNT_ACTIVATIONS] += 1;
    STEP_EXITED = false;
    let t_call = if TIMING { time::microtick() } else { 0.0 };
    let native = call_indirect1_ret(
        (slot + cpu::WASM_TABLE_OFFSET) as i32,
        budget.min(u16::MAX as u32) as u16,
    ) as u32;
    if TIMING {
        TIME_IN_CALLS += time::microtick() - t_call;
    }
    ACTIVE = false;
    IN_ACTIVATION = false;
    // (functions this activation tail-called from)
    let native = native.wrapping_add(*gp::x64_page_chain);
    // (REP elements legacy-mode functions ran, pagegen Emitter::note_rep:
    // the core's statistics count them as the interpreter's)
    if *gp::x64_page_rep_elements != 0 {
        execution::note_jit_rep(*gp::x64_page_rep_elements);
        *gp::x64_page_rep_elements = 0;
    }
    *gp::instruction_counter = (*gp::instruction_counter).wrapping_add(native);
    execution::note_native_retired(native);
    execution::ledger_end_count(span, execution::Way::PageNative, native);
    let exit = *gp::x64_page_exit;
    if step_profile::enabled() {
        step_profile::note_event(
            event::EXIT,
            match exit {
                pagegen::EXIT_RETRY => event::EXIT_RETRY,
                pagegen::EXIT_UNKNOWN => event::EXIT_UNKNOWN,
                _ if STEP_EXITED => event::EXIT_STEP,
                _ if native >= budget.min(u16::MAX as u32) => event::EXIT_BUDGET,
                _ => event::EXIT_LEAVE,
            },
        );
    }
    let r = rt();
    r.stats[RETIRED] += native as u64;
    r.x.last_rip = linear_rip();
    // (no evidence for span_members across a halt or an interrupt)
    r.x.last_page = if *gp::in_hlt { u64::MAX } else { *gp::x64_page_linear >> 12 };
    match exit {
        pagegen::EXIT_RETRY => {
            r.stats[RETRIES] += 1;
            if step_profile::enabled() && *gp::mxcsr & 0x20 == 0 {
                ACCESS_REFUSED[5] += 1;
            }
            profile_instruction(true);
            // (native code resumes after the interpreted instruction: an
            // unserved entry, noted when the function steps there)
            let span = execution::ledger_begin();
            interpret_one();
            execution::ledger_end(span, execution::Way::PageRetry);
        },
        pagegen::EXIT_UNKNOWN => r.stats[UNKNOWN] += 1,
        _ => {},
    }
    // (P7.3: legacy-mode code polls for interrupts only where one can have
    // become deliverable: an interpreted instruction, IF set by STI, a held
    // interrupt, events of other cores, NMI, SMI or HLT. Devices raise
    // theirs through handle_irqs, and native code does no device access: a
    // poll after each of XP's activations cost 2% of its boot)
    if mode < MODE_LEGACY
        || exit == pagegen::EXIT_RETRY
        || STEP_EXITED
        || *gp::flags & cpu::FLAG_INTERRUPT & !interrupts_before != 0
        || *gp::in_hlt
        || apic::has_core_events()
        || apic::nmi_pending()
        || crate::cpu::smm::smi_deliverable()
    {
        let rip = linear_rip();
        cpu::handle_irqs();
        if linear_rip() != rip {
            rt().x.last_page = u64::MAX;
        }
    }
    Attempt {
        retired: (*gp::instruction_counter).wrapping_sub(before),
        submitted: false,
    }
}

unsafe fn compile(page: u32) -> Attempt { compile_mode(page, false) }
/// compile(page), or with `hot` its recompile with inline access lookups
/// (P4.14), which is no compile of its own: no backoff
unsafe fn compile_mode(page: u32, hot: bool) -> Attempt {
    let r = rt();
    let state = r.pages.entry(page).or_default();
    if hot {
        state.x.hot = true;
    }
    else {
        state.compiles += 1;
    }
    let recompile = state.compiles > 1 || hot;
    // (P7.2: a 32-bit function's key, of the same page; P7.3: legacy mode's)
    let (compat, physical) = (page & COMPAT_KEY != 0, physical_key(page));
    let legacy = page & LEGACY_KEY != 0;
    let segmented = page & SEGMENTED_KEY != 0;
    let prot16 = page & PROT16_KEY != 0;
    // (M11: a stack of the other width than the code's)
    let stack16 = prot16 != (page & STACK_KEY != 0);
    // (P7.8: real-mode and virtual-8086 code, 16-bit code too)
    let mode16 = if page & REAL_KEY != 0 {
        pagegen::Mode16::Real
    }
    else if page & V86_KEY != 0 {
        pagegen::Mode16::V86
    }
    else {
        pagegen::Mode16::Protected
    };
    // (legacy mode's lookups are inline either way, in the 32-bit TLB: no
    // cold compile and hot recompile, which would start V8's tier-up anew;
    // loops from the first compile)
    let outline = pagegen::outline_access() && !state.x.hot && !legacy;
    let counter = if outline && HOT_INLINE { take_counter() } else { None };
    // (named after the linear page it was compiled for: host profiles)
    let linear = linear_rip() & !4095;
    // (P7.3b: with x64_page_clusters, the consecutive pages of a span of
    // 32-bit code, `page` among them, legacy mode and since M9 compatibility
    // mode; else just `page`)
    // (16-bit protected-mode code: pages alone, P7.7)
    let span: Vec<(u32, u64, u32)> = if compat && !prot16 && CLUSTERS && !hot && !SPAN_DECLINED {
        span_members(r, page, linear)
    }
    else {
        vec![(page, linear, 0)]
    };
    let (first, linear) = (span[0].0, span[0].1);
    // (a recompile serves the unserved offsets seen once so far too: each
    // would otherwise count towards the next recompile)
    let mut entries: Vec<u16> = Vec::new();
    for (m, &(key, ..)) in span.iter().enumerate() {
        let Some(state) = r.pages.get(&key)
        else {
            continue;
        };
        let recompile = key == page && recompile || state.compiles != 0;
        entries.extend(
            (0..4096u16)
                .filter(|&o| bit(&state.entries, o) || recompile && bit(&state.seen, o))
                .map(|o| (m * 4096) as u16 + o),
        );
    }
    let bytes = if is_device(page) {
        match device_page_bytes(physical) {
            Some(bytes) => bytes,
            None => return miss(),
        }
    }
    else if is_extended(page) {
        extended::copy_page(physical - extended::CODE_KEY_BASE)
    }
    else {
        let mut bytes = Vec::with_capacity(4096 * span.len());
        for &(key, ..) in &span {
            bytes.extend_from_slice(std::slice::from_raw_parts(
                crate::cpu::memory::mem8.add((physical_key(key) << 12) as usize),
                4096,
            ));
        }
        bytes
    };
    // Likely function starts: 16-byte aligned after INT3 padding (MSVC x64
    // code). Serving them from the first compile avoids most recompiles for
    // entries that other pages call later. (Guesses: an instruction's last
    // byte may be 0xCC, as MULSD XMM1, XMM4's ModRM; pagegen drops those
    // that code runs into, which would split its block)
    for m in 0..span.len() {
        for o in (16..4096usize).step_by(16) {
            let at = m * 4096 + o;
            if bytes[at - 1] == 0xCC && bytes[at] != 0xCC && !entries.contains(&(at as u16)) {
                entries.push(at as u16 | pagegen::GUESSED);
            }
        }
    }
    // (P7.3: the instructions writes changed, of a 32-bit page compiled
    // alone: their immediates load from its host)
    let volatile: Vec<u16> = if compat && span.len() == 1 && !is_extended(page) {
        r.pages
            .get(&page)
            .map_or(Vec::new(), |s| s.x.volatile.clone())
    }
    else {
        Vec::new()
    };
    // (P7.3b: each page's host address as compiled, which the span's
    // prologue compares with the 32-bit TLB's)
    let hosts: Vec<u32> = if span.len() > 1 {
        span.iter()
            .map(|&(.., physical)| (crate::cpu::memory::mem8 as u32).wrapping_add(physical))
            .collect()
    }
    else if !volatile.is_empty() {
        vec![(crate::cpu::memory::mem8 as u32).wrapping_add(physical << 12)]
    }
    else {
        Vec::new()
    };
    // (P7.7: the IP of the page's first byte under the current CS, which
    // the function requires)
    let ip_base = if prot16 { ip_base_of(linear) } else { 0 };
    let name = format!(
        "x64_page{}_{:x}",
        if prot16 {
            match (mode16, stack16) {
                (pagegen::Mode16::Protected, false) => "16ss32",
                (pagegen::Mode16::Protected, true) => "16",
                (pagegen::Mode16::Real, _) => "r16",
                (pagegen::Mode16::V86, _) => "v16",
            }
        }
        else if segmented && stack16 {
            "s32ss16"
        }
        else if segmented {
            "s32"
        }
        else if legacy {
            "l32"
        }
        else if compat {
            "32"
        }
        else {
            ""
        },
        linear
    );
    let next = next_page_bytes(span.last().unwrap().1);
    let Some(code) = pagegen::compile(
        &bytes,
        next.as_ref().map_or(&[][..], |b| &b[..]),
        &entries,
        chaining(),
        outline,
        counter.map(|c| &raw const HOT_COUNTS[c as usize] as u32),
        compat,
        legacy,
        segmented,
        prot16.then_some((ip_base, mode16)),
        stack16,
        &hosts,
        &volatile,
        name,
    )
    else {
        (*(&raw mut HOT_FREE)).extend(counter);
        if span.len() > 1 {
            // (more code than a function takes: the page alone, P7.3b)
            r_page_uncount(page, hot);
            SPAN_DECLINED = true;
            let attempt = compile_mode(page, hot);
            SPAN_DECLINED = false;
            return attempt;
        }
        rt().stats[FAILED] += 1;
        return miss();
    };
    let r = rt();
    if recompile {
        r.stats[RECOMPILED] += 1;
    }

    // Room in the table: retire the least recently used function; of this
    // code's mode when that holds more than its share (P7.2b: 32-bit
    // compatibility-mode code and long-mode code each keep a third at least)
    let live = r.live();
    // (the slot budget, jitrt::capacity: this client's quota is
    // MAX_FUNCTIONS; an eviction another client asked of it is done here,
    // at its cold point)
    let must_evict = {
        let rt = crate::jitrt::state();
        let free = rt.table.free_count();
        capacity::must_evict(ClientId::X86Page, live, free, |c| {
            rt.table.owned_by(c) as u32
        })
    };
    if capacity::take_request(ClientId::X86Page) || must_evict {
        if let Some(i) = eviction_victim(r, compat) {
            retire(r, i);
            r.stats[EVICTED] += 1;
        }
    }
    release_dead(r);
    let id = r.next_id;
    r.next_id += 1;
    // Watching the page retires cached write translations to it (jac). An
    // extended page is watched by extended.rs, once its old function is gone.
    let watched = if is_extended(page) {
        HashSet::new()
    }
    else {
        span.iter()
            .map(|&(key, ..)| Page::page_of(physical_key(key) << 12))
            .collect()
    };
    let Some(slot) = crate::jit::reserve_page_slot(id, watched)
    else {
        (*(&raw mut HOT_FREE)).extend(counter);
        rt().stats[FAILED] += 1;
        return miss();
    };
    let r = rt();
    for &(key, ..) in &span {
        if let Some(&old) = r.by_page.get(&key) {
            retire(r, old);
        }
    }
    if is_extended(page) && !is_device(page) {
        extended::watch_code(physical - extended::CODE_KEY_BASE);
    }
    let reusable = |f: &Function, releases: &Vec<(u32, u64)>| {
        f.phase == Phase::Dead && !releases.iter().any(|&(s, i)| s == f.slot && i == f.id)
    };
    let index = match r.functions.iter().position(|f| reusable(f, &r.releases)) {
        Some(i) => i,
        None => {
            r.functions.push(Function {
                page,
                id: 0,
                slot: 0,
                phase: Phase::Dead,
                served: Vec::new(),
                members: Vec::new(),
                last_used: 0,
                x: X86Code::default(),
            });
            r.functions.len() - 1
        },
    };
    r.clock += 1;
    r.functions[index] = Function {
        page: first,
        id,
        slot,
        phase: Phase::Pending,
        served: code.served,
        members: span.iter().map(|&(key, ..)| key).collect(),
        last_used: r.clock,
        x: X86Code {
            code: code.code,
            starts: code.starts,
            dynamic: code.dynamic,
            source: source_hash(&bytes),
            counter,
            native_at: r.stats[RETIRED],
            ip_base,
        },
    };
    for &(key, ..) in &span {
        r.by_page.insert(key, index);
        FAST[fast_slot(key)] = (key, index as u32 + 1);
    }
    r.generation = r.generation.wrapping_add(1);
    r.stats[COMPILED] += 1;
    if legacy {
        COUNTERS[COUNT_LEGACY_COMPILES] += 1;
    }
    if prot16 && mode16 == pagegen::Mode16::Protected {
        COUNTERS[COUNT_PROT16_COMPILES] += 1;
    }
    else if prot16 {
        COUNTERS[COUNT_V86_COMPILES] += 1;
    }
    if span.len() > 1 {
        COUNTERS[COUNT_SPANS] += 1;
        COUNTERS[COUNT_SPAN_PAGES] += span.len() as u64;
    }
    else if compat {
        COUNTERS[COUNT_COMPAT_COMPILES] += 1;
    }
    unsafe { BYTES_COMPILED += code.bytes.len() as u64 };
    r.stats[INSTRUCTIONS] += code.instructions as u64;
    r.stats[TEMPLATED] += code.templated as u64;
    // The host installs it synchronously when it can (x64_page_install).
    publish::publish(ClientId::X86Page, id, slot, &code.bytes);
    Attempt {
        retired: 0,
        submitted: false,
    }
}

/// The first bytes of the linear page after `linear_page` as instruction
/// fetch sees them now, when that page is plain RAM (instructions that
/// straddle into it, see pagegen).
unsafe fn next_page_bytes(linear_page: u64) -> Option<[u8; 16]> {
    let next = linear_page.wrapping_add(4096);
    let physical = if state::efer() & state::EFER_LMA == 0 {
        legacy_translate(next as u32, false)?.0
    }
    else {
        memory::translate(next, paging::Access::Execute, false, false).ok()?
    };
    let backing = jac::ram_backing(physical)?;
    let mut bytes = [0u8; 16];
    std::ptr::copy_nonoverlapping(
        crate::cpu::memory::mem8.add(backing as usize),
        bytes.as_mut_ptr(),
        16,
    );
    Some(bytes)
}
/// Generated code, before an instruction that continues into the next page:
/// whether that page (after gp::x64_page_linear) fetches as `word`, its
/// first `count` bytes when compiled. Else the instruction is stepped (the
/// interpreter fetches it, faults included).
#[no_mangle]
pub unsafe fn x64_page_straddle(word: u64, count: u32) -> i32 {
    let Some(bytes) = next_page_bytes(*gp::x64_page_linear)
    else {
        return 0;
    };
    let mask = if count >= 8 { !0 } else { (1u64 << (8 * count)) - 1 };
    (u64::from_le_bytes(bytes[..8].try_into().unwrap()) & mask == word) as i32
}

fn retire(r: &mut Runtime, index: usize) { retire_with(r, index, true) }
/// `unchain`: clear the chaining entries of the function (reset clears all).
fn retire_with(r: &mut Runtime, index: usize, unchain: bool) {
    // (jitrt's: Dead, a new generation, the slot released at the next cold point)
    if !r.kill(index) {
        return;
    }
    let f = &mut r.functions[index];
    let (page, slot) = (f.page, f.slot);
    r.x.released_counters.extend(f.x.counter.take());
    if unchain {
        unsafe { unchain_slot(slot) };
    }
    // (a span's other pages, P7.3b)
    for m in 1..r.functions[index].members.len() {
        let key = r.functions[index].members[m];
        if r.by_page.get(&key) == Some(&index) {
            r.by_page.remove(&key);
        }
        unsafe {
            if FAST[fast_slot(key)].0 == key {
                FAST[fast_slot(key)] = (0, 0);
            }
        }
    }
    if r.by_page.get(&page) == Some(&index) {
        r.by_page.remove(&page);
        // (the page's function in another mode, P7.2, keeps it watched)
        if is_extended(page)
            && !is_device(page)
            && !MODE_KEYS
                .iter()
                .any(|&mode| r.by_page.contains_key(&(physical_key(page) | mode)))
        {
            unsafe { extended::unwatch_code(physical_key(page) - extended::CODE_KEY_BASE) };
        }
    }
    unsafe {
        if FAST[fast_slot(page)].0 == page {
            FAST[fast_slot(page)] = (0, 0);
        }
    }
}

/// Called by the host before table.set (jitrt::publish's install answer):
/// false if the function was retired meanwhile (its source changed, or reset).
pub fn x64_page_install(id: u64, slot: u32) -> bool {
    let r = rt();
    let Some(f) = r.pending(id, slot).map(|i| &r.functions[i])
    else {
        return false;
    };
    if !crate::parallel::active() {
        return true;
    }
    // other cores mark the page first, then its bytes are checked once more
    let (page, source) = (f.page, f.x.source);
    let backing = match r.by_page.get(&page) {
        // (extended pages are not compiled then: retire_extended)
        Some(_) if !is_extended(page) => physical_key(page),
        _ => return false,
    };
    if !crate::jit::wait_pages_published(std::iter::once(Page::page_of(backing << 12)), 0.5) {
        return false;
    }
    let bytes = unsafe {
        std::slice::from_raw_parts(crate::cpu::memory::mem8.add((backing << 12) as usize), 4096)
    };
    source_hash(bytes) == source
}

/// FNV-1a over a code page
fn source_hash(bytes: &[u8]) -> u64 {
    let mut hash = 0xCBF29CE484222325u64;
    for &byte in bytes {
        hash = (hash ^ byte as u64).wrapping_mul(0x100000001B3);
    }
    hash
}
/// (tests) A ready function serves code of the physical page of `address`,
/// in any code mode
#[no_mangle]
pub fn x64_page_published(address: u32) -> bool {
    let r = rt();
    MODE_KEYS.iter().any(|&mode| {
        r.by_page
            .get(&(address >> 12 | mode))
            .is_some_and(|&i| r.functions[i].phase == Phase::Ready)
    })
}
pub fn x64_page_ready(id: u64, slot: u32) -> bool {
    if rt().ready(id, slot).is_none() {
        return false;
    }
    if unsafe { TIMING } {
        unsafe { time_first_call(slot) };
    }
    true
}
/// (x64_page_timing) Call a new function once with budget 0: it returns at
/// its first budget check, having written back the unchanged state, and the
/// time is the engine's lazy compilation.
unsafe fn time_first_call(slot: u32) {
    if ACTIVE {
        return;
    }
    if *gp::flags_changed != 0 {
        let flags = state::read_flags64();
        state::write_flags64(flags);
    }
    *gp::x64_page_lazy_kind = 0;
    *gp::x64_page_linear = linear_rip() & !4095;
    let core = apic::current_core();
    *gp::x64_jac_base = jac::base(core, *gp::cpl == 3);
    *gp::x64_jac_epoch = jac::epoch_bits(core);
    let t0 = time::microtick();
    ACTIVE = true;
    call_indirect1_ret((slot + cpu::WASM_TABLE_OFFSET) as i32, 0);
    ACTIVE = false;
    TIME_FIRST_CALLS += time::microtick() - t0;
    *gp::x64_page_exit = pagegen::EXIT_NORMAL;
}
pub fn x64_page_cancel(id: u64, slot: u32) {
    let r = rt();
    if let Some(i) = r.alive(id, slot) {
        retire(r, i);
        r.stats[FAILED] += 1;
    }
    unsafe { release_dead(r) };
}

/// A write to a watched backing page (see jit::jit_dirty_page), or to an
/// extended page with code (key from extended::CODE_KEY_BASE on).
pub fn dirty_page(page: u32) { retire_written(page, &[]); }
/// A write of bytes `lo..hi` of backing page `page` (jit::jit_dirty_bytes):
/// as dirty_page, but a legacy-mode function stays when the write changes
/// bytes of its volatile instructions, which it reads where it runs, and
/// none of its other instructions' (P7.3: 709.smc). Not for writes of data
/// next to code: the page stays watched while it has a function, and each
/// such write from compiled code would be retried in the interpreter
/// (Red Alert 2 under Windows 98: 2.6 million in 30 s, 0.8x Tier-0); after a
/// retire it is not watched until the page compiles again. The slots of
/// the functions that stay, which jit.rs keeps watching.
pub fn dirty_bytes(page: u32, lo: u32, hi: u32) -> Vec<u32> {
    let r = rt();
    let mut kept = Vec::new();
    if !crate::parallel::active() {
        for mode in MODE_KEYS {
            let key = page | mode;
            let Some(&i) = r.by_page.get(&key)
            else {
                continue;
            };
            let f = &r.functions[i];
            let Some(m) = f.member(key)
            else {
                continue;
            };
            let base = (m * 4096) as u16;
            let range = lo..hi.min(4096);
            if f.page & COMPAT_KEY != 0
                && f.phase != Phase::Dead
                && !range.clone().any(|o| bit(&f.x.code, base + o as u16))
                && range.clone().any(|o| bit(&f.x.dynamic, base + o as u16))
            {
                kept.push(i);
            }
        }
    }
    // (the instructions a write hits are volatile in their page's next
    // compiles, which it then keeps: 709.smc rewrites an immediate every
    // 64 calls, and its page would stay interpreted)
    for mode in MODE_KEYS {
        let key = page | mode;
        let Some(&i) = r.by_page.get(&key)
        else {
            continue;
        };
        let f = &r.functions[i];
        let Some(m) = f.member(key)
        else {
            continue;
        };
        if kept.contains(&i) || f.page & COMPAT_KEY == 0 || f.phase == Phase::Dead {
            continue;
        }
        let base = (m * 4096) as u16;
        let hit: Vec<u16> = (lo..hi.min(4096))
            .filter(|&o| bit(&f.x.code, base + o as u16))
            .filter_map(|o| {
                (0..=o)
                    .rev()
                    .take(15)
                    .find(|&s| bit(&f.x.starts, base + s as u16))
            })
            .map(|s| s as u16)
            .collect();
        let state = r.pages.entry(key).or_default();
        for s in hit {
            if !state.x.volatile.contains(&s) && state.x.volatile.len() < pagegen::MAX_VOLATILE {
                state.x.volatile.push(s);
                state.x.volatile_new = true;
            }
        }
    }
    retire_written(page, &kept);
    kept.iter().map(|&i| r.functions[i].slot).collect()
}
/// dirty_page, but for the functions `kept` (indices)
fn retire_written(page: u32, kept: &[usize]) {
    let r = rt();
    // (the page's functions in every code mode, P7.2, P7.3)
    let dead: Vec<usize> = MODE_KEYS
        .iter()
        .filter_map(|&mode| r.by_page.get(&(page | mode)).copied())
        .filter(|i| !kept.contains(i))
        .collect();
    if dead.is_empty() {
        return;
    }
    unsafe {
        CODE_WRITES += 1;
    }
    // (no span takes a page code writes retire, P7.3b: 709.smc's callee
    // would retire its caller's page with it)
    for key in MODE_KEYS {
        if let Some(state) = r.pages.get_mut(&(page | key)) {
            state.x.written = true;
        }
    }
    for i in dead {
        // (legacy mode, P7.3: a function that ran long before its page was
        // written costs no backoff: the VMM's pages under Windows 98 hold
        // data written twice a second, and backed-off pages stay
        // interpreted; a page rewritten while its code runs, as 709.smc's,
        // still backs off)
        let f = &r.functions[i];
        if f.page & COMPAT_KEY != 0 && r.stats[RETIRED].wrapping_sub(f.x.native_at) >= LIVED {
            let key = f.page;
            if let Some(state) = r.pages.get_mut(&key) {
                state.compiles = state.compiles.min(1);
            }
        }
        retire(r, i);
        r.stats[INVALIDATED] += 1;
    }
    // Slots are released at the next entry, outside the JIT state lock.
}
/// Native instructions of the tier after which a legacy-mode function whose
/// page is written counts as having lived long (dirty_page)
const LIVED: u64 = 1 << 22;

/// Cores start to run in workers (crate::parallel): writes to extended RAM
/// are no longer tracked for code, so its page functions go.
pub fn retire_extended() {
    let r = rt();
    unsafe {
        CODE_TLB = [[(0, 0, 0, false); CODE_TLB_SIZE]; 8];
    }
    for i in 0..r.functions.len() {
        if is_extended(r.functions[i].page) {
            retire(r, i);
        }
    }
}

/// Retire everything (jit_clear_cache: reset, restore, mapping changes).
pub fn reset() {
    let r = rt();
    clear_chains();
    for i in 0..r.functions.len() {
        retire_with(r, i, false);
    }
    r.pages.clear();
    r.x.last_rip = 0;
    r.generation = r.generation.wrapping_add(1);
    unsafe {
        CODE_WRITES += 1;
        HEAT_BATCH = HeatBatch::NONE;
    }
}

#[no_mangle]
pub fn x64_page_set_enabled(enabled: bool) {
    rt().enabled = enabled;
    if !enabled {
        reset();
    }
}

/// The values of x64_page_set_enabled, x64_page_set_chaining and
/// x64_page_set_recompile_misses (crate::jit_switches)
pub fn switch_value(name: &str) -> Option<u32> {
    unsafe {
        Some(match name {
            "x64_page" => rt().enabled as u32,
            "x64_chaining" => CHAINING as u32,
            "x64_recompile_misses" => RECOMPILE_MISSES,
            "x64_heat_batch" => BATCH_HEAT as u32,
            "x64_miss_run" => MISS_RUN as u32,
            "x64_hot_inline" => HOT_INLINE as u32,
            "x64_hot_count" => HOT_COUNT,
            "x64_compat_hot_count" => COMPAT_HOT_COUNT,
            "x64_page_compat32" => COMPAT32 as u32,
            "x64_page_legacy32" => LEGACY32 as u32,
            "x64_page_prot16" => PROT16 as u32,
            "x64_page_v86" => V86 as u32,
            "x64_page_clusters" => CLUSTERS as u32,
            "x64_span_crossings" => SPAN_CROSSINGS,
            "x64_span_entries" => SPAN_ENTRIES,
            "x64_legacy_heat" => LEGACY_HEAT,
            "x64_legacy_recompile_misses" => LEGACY_MISSES,
            _ => return None,
        })
    }
}
#[no_mangle]
pub fn x64_page_stat(field: u32) -> f64 {
    let r = rt();
    match field as usize {
        4 => unsafe { STEPS as f64 },
        12 => r
            .functions
            .iter()
            .filter(|f| f.phase == Phase::Ready)
            .count() as f64,
        f if f < 12 => r.stats[f] as f64,
        f @ 13..=19 => unsafe { COUNTERS[f as usize - 13] as f64 },
        20 => unsafe { TIME_IN_CALLS },
        22 => unsafe { TIME_IN_EXECUTE },
        23 => unsafe { TIME_FIRST_CALLS },
        25 => unsafe { COUNTERS[COUNT_UNALIGNED_READS] as f64 },
        f @ 26..=32 => unsafe { COUNTERS[f as usize - 26 + COUNT_CR0_WRITES] as f64 },
        33 => r.stats[HOT_RECOMPILES] as f64,
        f @ 34..=35 => unsafe { COUNTERS[f as usize - 34 + COUNT_JAC_FILLS] as f64 },
        36 => unsafe { COUNTERS[COUNT_COMPAT_COMPILES] as f64 },
        37 => unsafe { COUNTERS[COUNT_LEGACY_COMPILES] as f64 },
        f @ 38..=39 => unsafe { COUNTERS[f as usize - 38 + COUNT_SPANS] as f64 },
        // (legacy-mode code runs here: x64_page_legacy32 and ir_tier0)
        40 => unsafe { LEGACY_ACTIVE as u32 as f64 },
        // (compatibility-mode code runs here: x64_page_compat32 and ir_tier0)
        41 => unsafe { COMPAT_ACTIVE as u32 as f64 },
        // (16-bit protected-mode code runs here: x64_page_prot16 and
        // ir_tier0; its compiles)
        42 => unsafe { PROT16_ACTIVE as u32 as f64 },
        43 => unsafe { COUNTERS[COUNT_PROT16_COMPILES] as f64 },
        // (real-mode and virtual-8086 code runs here: x64_page_v86 and
        // ir_tier0; its compiles)
        44 => unsafe { V86_ACTIVE as u32 as f64 },
        45 => unsafe { COUNTERS[COUNT_V86_COMPILES] as f64 },
        24 => unsafe { BYTES_COMPILED as f64 },
        // pages compiled at least once (while tracked)
        21 => r.pages.values().filter(|state| state.compiles != 0).count() as f64,
        _ => 0.0,
    }
}

// Helpers called by generated code -------------------------------------

/// Host address for a `kind & 255`-byte access (bit 8: write) at linear
/// `address` for the current privilege, filling the access cache; 0 when the
/// instruction must be interpreted instead (fault, device or VGA memory,
/// page with compiled code, page crossing). No guest-visible effects except
/// the A/D updates of a successful translation.
#[no_mangle]
pub unsafe fn x64_page_access(address: u64, kind: u32) -> u32 {
    COUNTERS[COUNT_ACCESS_MISSES] += 1;
    let size = (kind & 0xFF) as u64;
    let write = kind & 0x100 != 0;
    if (address & 4095) + size > 4096 {
        if let Some(host) = crossing_host(address, write) {
            return host;
        }
        ACCESS_REFUSED[0] += 1;
        return 0;
    }
    // generated accesses are atomic with cores in workers: aligned only. An
    // unaligned read of RAM is served from a copy (a racing write may or may
    // not be in it, as for a split access); an unaligned write is retried,
    // unless its code stores unaligned itself (kind bit 9, pagegen store).
    if crate::wasmgen::wasm_builder::WasmBuilder::ATOMIC_GUEST_MEMORY
        && address & (size.min(8) - 1) != 0
        && !(write && kind & 0x200 != 0)
    {
        if !write {
            if let Ok((physical, _, _)) = memory::translate_page(address, paging::Access::Read) {
                if let Some(backing) = jac::ram_backing(physical) {
                    let bounce = &raw mut BOUNCE as *mut u8;
                    let from =
                        crate::cpu::memory::mem8.add((backing + (address & 4095) as u32) as usize);
                    for i in 0..size as usize {
                        *bounce.add(i) = crate::parallel::load8(from.add(i));
                    }
                    COUNTERS[COUNT_UNALIGNED_READS] += 1;
                    return bounce as u32;
                }
            }
        }
        ACCESS_REFUSED[0] += 1;
        return 0;
    }
    let access = if write { paging::Access::Write } else { paging::Access::Read };
    let Ok((physical, large, global)) = memory::translate_page(address, access)
    else {
        ACCESS_REFUSED[1] += 1;
        return 0;
    };
    let Some(backing) = jac::ram_backing(physical)
    else {
        // extended RAM: its frame, while cores share this thread (never a
        // write entry for a page with a page function: extended::cache_frame)
        if let Some(host) = super::extended::cache_frame(physical, write) {
            let backing = host.wrapping_sub(crate::cpu::memory::mem8 as u32);
            jac::fill(
                apic::current_core(),
                *gp::cpl == 3,
                write,
                address,
                backing,
                large,
                global,
            );
            return host.wrapping_add((address & 4095) as u32);
        }
        // the VGA frame buffer: plain memory with dirty tracking
        if let Some(backing) = jac::frame_buffer_backing(physical, write) {
            COUNTERS[COUNT_LFB_FILLS] += 1;
            jac::fill(
                apic::current_core(),
                *gp::cpl == 3,
                write,
                address,
                backing,
                large,
                global,
            );
            return (crate::cpu::memory::mem8 as u32)
                .wrapping_add(backing)
                .wrapping_add((address & 4095) as u32);
        }
        ACCESS_REFUSED[2] += 1;
        return 0;
    };
    if write && crate::jit::page_needs_notification(Page::page_of(backing)) {
        ACCESS_REFUSED[3] += 1;
        return 0;
    }
    jac::fill(
        apic::current_core(),
        *gp::cpl == 3,
        write,
        address,
        backing,
        large,
        global,
    );
    (crate::cpu::memory::mem8 as u32)
        .wrapping_add(backing)
        .wrapping_add((address & 4095) as u32)
}

/// x64_page_access of an operand that crosses into the next page: served
/// when both pages are plain RAM whose backings are adjacent (guest RAM is
/// one array: so are most), for a write neither with compiled code; else
/// the instruction is retried, then the activation steps up to its next
/// block start (page-crossing VMOVDQU ymm loads and stores in a loop). With
/// cores in workers it is unaligned, which atomic accesses refuse.
unsafe fn crossing_host(address: u64, write: bool) -> Option<u32> {
    if crate::wasmgen::wasm_builder::WasmBuilder::ATOMIC_GUEST_MEMORY {
        return None;
    }
    let access = if write { paging::Access::Write } else { paging::Access::Read };
    let (first, _, _) = memory::translate_page(address, access).ok()?;
    let (second, _, _) =
        memory::translate_page((address & !4095).wrapping_add(4096), access).ok()?;
    let backing = jac::ram_backing(first)?;
    if jac::ram_backing(second)? != backing.wrapping_add(4096) {
        return None;
    }
    if write
        && (crate::jit::page_needs_notification(Page::page_of(backing))
            || crate::jit::page_needs_notification(Page::page_of(backing + 4096)))
    {
        return None;
    }
    Some(
        (crate::cpu::memory::mem8 as u32)
            .wrapping_add(backing)
            .wrapping_add((address & 4095) as u32),
    )
}

/// x64_page_access of legacy-mode code (P7.3; pagegen CompileEnv::legacy):
/// a miss in the 32-bit TLB, which this fills as Tier-0's slow paths do
/// (ir_t0_read_slow, ir_t0_write_slow); what it refuses (0) the
/// interpreter makes
#[no_mangle]
pub unsafe fn x64_page_access32(address: u64, kind: u32) -> u32 {
    COUNTERS[COUNT_ACCESS_MISSES] += 1;
    let address = address as u32;
    let size = kind & 0xFF;
    let write = kind & 0x100 != 0;
    let host = if (address & 4095) + size > 4096 {
        // (both pages served, their hosts adjacent: as crossing_host)
        if crate::wasmgen::wasm_builder::WasmBuilder::ATOMIC_GUEST_MEMORY {
            Err(0)
        }
        else {
            legacy_host(address, write).and_then(|first| {
                let second = legacy_host((address & !4095).wrapping_add(4096), write)?;
                if second == (first & !4095).wrapping_add(4096) {
                    Ok(first)
                }
                else {
                    Err(0)
                }
            })
        }
    }
    else if crate::wasmgen::wasm_builder::WasmBuilder::ATOMIC_GUEST_MEMORY
        && address & (size.min(8) - 1) != 0
        && !(write && kind & 0x200 != 0)
    {
        // (unaligned with cores in workers: as x64_page_access)
        if write {
            Err(0)
        }
        else {
            legacy_host(address, false).map(|host| {
                let bounce = &raw mut BOUNCE as *mut u8;
                for i in 0..size as usize {
                    *bounce.add(i) = crate::parallel::load8((host as *const u8).add(i));
                }
                COUNTERS[COUNT_UNALIGNED_READS] += 1;
                bounce as u32
            })
        }
    }
    else {
        legacy_host(address, write)
    };
    host.unwrap_or_else(|refused| {
        ACCESS_REFUSED[refused] += 1;
        0
    })
}
/// The host address of a legacy-mode access at linear `address` (not
/// crossing a page) for the current privilege, filling the 32-bit TLB, or
/// the ACCESS_REFUSED counter of why the interpreter must make it: it would
/// fault, it reaches device memory other than a frame buffer, or it writes
/// a page with compiled code
unsafe fn legacy_host(address: u32, write: bool) -> Result<u32, usize> {
    let (physical, _) = legacy_translate(address, write).ok_or(1usize)?;
    let entry = cpu::tlb_data[(address >> 12) as usize];
    if entry & cpu::TLB_IN_MAPPED_RANGE != 0 {
        // the VGA frame buffer: plain memory with dirty tracking (no TLB
        // entry hits it inline: each access comes here)
        let backing = jac::frame_buffer_backing(physical & !4095, write).ok_or(2usize)?;
        COUNTERS[COUNT_LFB_FILLS] += 1;
        return Ok((crate::cpu::memory::mem8 as u32)
            .wrapping_add(backing)
            .wrapping_add(address & 4095));
    }
    if write && entry & cpu::TLB_HAS_CODE != 0 {
        return Err(3);
    }
    Ok((entry & !0xFFF ^ address as i32) as u32)
}

#[derive(PartialEq, Clone, Copy)]
struct Context {
    cpl: u8,
    cs: u16,
    long: bool,
    cr0: u64,
    cr3: u64,
    cr4: u64,
    efer: u64,
    control: i32,
    dr7: u64,
    epoch: u64,
    /// in compatibility and legacy mode, runnable_kind (P7.2, P7.3)
    compat: u8,
}
// (inlined into x64_page_step, as before P7.2's field: every long-mode step
// takes it twice; runnable32 only in 32-bit modes)
#[inline(always)]
unsafe fn context() -> Context {
    let long = state::mode().is_long();
    Context {
        cpl: *gp::cpl,
        cs: *gp::sreg.add(1),
        long,
        compat: match (long, runnable_kind()) {
            (true, _) => 0,
            (_, 1) if SEGMENTED_ACTIVE => 2,
            (_, kind) => kind,
        },
        cr0: state::read_cr(0),
        cr3: state::read_cr(3),
        cr4: state::read_cr(4),
        efer: state::efer(),
        // IF, TF, AC, VM, RF and IOPL change what may run natively
        control: *gp::flags & (0x200 | 0x100 | 0x40000 | 0x20000 | 0x10000 | 0x3000),
        dr7: state::read_dr(7),
        epoch: jac::epoch_bits(apic::current_core()),
    }
}

/// Interpret the instruction at RIP (state was written back). Continue the
/// activation only if nothing it depends on changed.
/// Refused cache fills (then retried in the interpreter): page crossing,
/// translation fault, device or VGA memory, page with compiled code; then
/// instructions stepped because the function was entered at an offset it
/// does not serve (x64_page_unserved), and (with the step profile) retries
/// with MXCSR.PE clear; then late entries (unserved offsets seen twice) by
/// kind: after a call, 16-byte aligned, other.
static mut ACCESS_REFUSED: [u64; 9] = [0; 9];
/// The step profile (crate::step_profile, the JIT switch step_profile): on,
/// an empty one; off, dropped
#[no_mangle]
pub unsafe fn x64_page_profile(enabled: bool) {
    step_profile::set_enabled(false);
    step_profile::set_enabled(enabled);
}
/// Steps of this tier by its earlier key (bits 0-17 of StepKey: one-byte
/// opcodes 0..255, 0F xx as 0x100 | xx, 0F 38/3A xx as 0x200/0x300 | xx; VEX
/// forms as 0x4000 | L << 12 | pp << 10 | map << 8 | opcode; +0x10000 with a
/// REP prefix; retries at key + 0x20000), or with key >= 0x40000 the refused
/// access counter key - 0x40000.
#[no_mangle]
pub unsafe fn x64_page_profile_get(key: u32) -> f64 {
    if key >= 0x40000 {
        return (*(&raw const ACCESS_REFUSED))
            .get(key as usize - 0x40000)
            .copied()
            .unwrap_or(0) as f64;
    }
    step_profile::x64_legacy_count(key) as f64
}
/// Steps and retries since x64_page_steps_reset by their first two bytes
/// (step_profile::pair_count); the reset turns the step profile on
#[no_mangle]
pub unsafe fn x64_page_steps(pair: u32) -> u32 { step_profile::pair_count(pair) }
#[no_mangle]
pub unsafe fn x64_page_steps_reset() { x64_page_profile(true) }
/// The counts of x64_page_steps stay as they are until the next reset (the
/// ISA tests: a hot run's, not the cold run's after it)
#[no_mangle]
pub unsafe fn x64_page_steps_freeze() { step_profile::freeze_pairs() }
/// With the step profile: stepped instructions by RIP (x64_page_step_rips)
static mut STEP_RIPS: Option<HashMap<u64, u32>> = None;
unsafe fn profile_step() {
    if !step_profile::enabled() {
        return;
    }
    let rips = (*(&raw mut STEP_RIPS)).get_or_insert_with(HashMap::new);
    if rips.len() < 1 << 16 {
        *rips.entry(linear_rip()).or_default() += 1;
    }
    profile_instruction(false);
}
/// The `n`th most stepped RIP (sorted when n is 0) and its count; clears
/// the histogram when `n` is past its end
#[no_mangle]
pub unsafe fn x64_page_step_rip(n: u32, high: bool, count: bool) -> f64 {
    static mut SORTED: Vec<(u64, u32)> = Vec::new();
    let sorted = &mut *(&raw mut SORTED);
    if n == 0 && !high && !count {
        *sorted = (*(&raw mut STEP_RIPS))
            .take()
            .unwrap_or_default()
            .into_iter()
            .collect();
        sorted.sort_by(|a, b| b.1.cmp(&a.1));
    }
    let Some(&(rip, times)) = sorted.get(n as usize)
    else {
        return -1.0;
    };
    if count {
        times as f64
    }
    else if high {
        (rip >> 32) as f64
    }
    else {
        (rip & 0xFFFF_FFFF) as f64
    }
}
/// A step (or with `retry`, a retried instruction) at RIP into the step
/// profile: its bytes as far as they translate to RAM without side effects
unsafe fn profile_instruction(retry: bool) {
    if !step_profile::enabled() {
        return;
    }
    let rip = linear_rip();
    let mut bytes = [0u8; 15];
    let mut n = 0;
    if state::efer() & state::EFER_LMA == 0 {
        // (legacy mode, P7.3)
        if let Ok(physical) = cpu::translate_address_read_no_side_effects(rip as i32) {
            if !crate::cpu::memory::in_mapped_range(physical) {
                n = step_profile::read_legacy(rip as u32, physical, &mut bytes);
            }
        }
    }
    while n < 15 && state::efer() & state::EFER_LMA != 0 {
        let Some(t) =
            memory::snapshot_translation(rip.wrapping_add(n as u64), paging::Access::Execute)
        else {
            break;
        };
        let Ok(page) = physical::ram_page(t.physical.0 & !4095)
        else {
            break;
        };
        bytes[n] =
            *crate::cpu::memory::mem8.add((page.backing + (t.physical.0 & 4095) as u32) as usize);
        n += 1;
    }
    let key = step_profile::x86_key(
        &bytes[..n],
        state::mode(),
        step_profile::Stepper::X64Page,
        retry,
    );
    step_profile::note_sampled(key, rip as u32, &bytes[..n]);
}

/// The x86 page tier's step frontend (jitrt::step, P5.6): the execution
/// context and CODE_WRITES before the step; the wide interpreter, with the
/// mode ledger's accounting; step_result's outcome
struct X86Step;
impl StepFrontend for X86Step {
    type Context = (Context, u64);
    #[inline(always)]
    fn context() -> (Context, u64) { unsafe { (context(), CODE_WRITES) } }
    #[inline(always)]
    fn interpret_one() {
        unsafe {
            ACTIVE = false;
            let span = execution::ledger_begin();
            interpret_one();
            execution::ledger_end(span, execution::Way::PageStep);
            ACTIVE = true;
            let flags = state::read_flags64();
            state::write_flags64(flags);
        }
    }
    #[inline(always)]
    fn outcome(before: &(Context, u64)) -> StepOutcome {
        unsafe { step_result(&before.0, before.1) }
    }
}

#[no_mangle]
pub unsafe fn x64_page_step() -> i32 {
    STEPS += 1;
    profile_step();
    step::step::<X86Step>() as i32
}

/// After an instruction the interpreter (x64_page_step) or a helper
/// (x64_page_far) ran for a page function, whose context was `before` and
/// CODE_WRITES `writes`
unsafe fn step_result(before: &Context, writes: u64) -> StepOutcome {
    let before = *before;
    let after = context();
    let exit = if *gp::in_hlt {
        event::STEP_EXIT_HALT
    }
    else if cpu::core_yield {
        event::STEP_EXIT_YIELD
    }
    else if *gp::interrupt_shadow != 0 {
        event::STEP_EXIT_SHADOW
    }
    else if apic::has_core_events() {
        event::STEP_EXIT_CORE_EVENT
    }
    else if CODE_WRITES != writes {
        event::STEP_EXIT_CODE_WRITE
    }
    else if after != before {
        // (code compiled for segment bases, 16-bit code among it, P7.7,
        // P7.8: a far call or return to code of the same privilege continues
        // through the chaining table; M11: also to code of another such
        // mode, as Windows 98's thunks between 16-bit code and 32-bit code
        // on a 16-bit stack, through that mode's table, unless the mode
        // ledger, which books an activation to the mode it started in, is on)
        if CHAINING
            && before.compat >= 2
            && after.compat >= 2
            && (after.compat == before.compat || !execution::ledger_on())
            && after
                == (Context {
                    cs: after.cs,
                    compat: after.compat,
                    ..before
                })
        {
            if after.compat != before.compat {
                let mode = code_mode();
                *gp::x64_code_base = chain_base(apic::current_core(), *gp::cpl == 3, mode);
                SEGMENTED_ACTIVE = mode >= MODE_SEGMENTED;
            }
            step_profile::note_event(event::STEP_EXIT, event::STEP_EXIT_CHAINABLE);
            return StepOutcome::Chain;
        }
        if step_profile::enabled() {
            note_context_changes(&before, &after)
        }
        else {
            event::STEP_EXIT_BARRIER
        }
    }
    else if *gp::flags & 0x200 != 0
        && (apic::has_pending_irq() || apic::routed_pic_pending(apic::current_core() as u32))
    {
        event::STEP_EXIT_IRQ
    }
    else if apic::nmi_pending() {
        event::STEP_EXIT_NMI
    }
    else {
        return StepOutcome::Continue;
    };
    STEP_EXITED = true;
    step_profile::note_event(event::STEP_EXIT, exit);
    StepOutcome::Exit
}

/// Whether the last activation ended in a step that left (its exit's reason
/// for the step profile, P4.0)
static mut STEP_EXITED: bool = false;

/// Far CALL ptr16:16 or ptr16:32 and RETF (imm16) for page functions of
/// code compiled for segment bases (M11; 16-bit code's far calls and
/// returns were a tenth of Diablo's instructions, each a step): `op` 0 a
/// call to `selector`:`offset`, 1 a return popping `offset` bytes more,
/// plus the operand size << 8. The state is in memory, EIP the next
/// instruction's, previous_ip this one's. 0: done, continue through the
/// chaining table (x64_page_step's STEP_CHAIN, or STEP_CONTINUE: the same
/// mode); 1: done, leave; 2: a fault was delivered (the instruction counts
/// as retired, as the interpreter counts it).
#[no_mangle]
pub unsafe fn x64_page_far(op: u32, offset: u32, selector: u32) -> i32 {
    let before = context();
    let writes = CODE_WRITES;
    let wide = op >> 8 == 32;
    ACTIVE = false;
    let done = if op & 255 == 0 {
        cpu::far_jump_checked(offset as i32, selector as i32 & 0xFFFF, true, wide)
    }
    else {
        let at = |bytes: i32| crate::cpu::misc_instr::get_stack_pointer(bytes);
        let ip = if wide { cpu::safe_read32s(at(0)) } else { cpu::safe_read16(at(0)) };
        // (RETF32 reads a dword for the selector)
        let cs = if wide { cpu::safe_read32s(at(4)) } else { cpu::safe_read16(at(2)) };
        match (ip, cs) {
            (Ok(ip), Ok(cs)) => cpu::far_return_checked(ip, cs & 0xFFFF, offset as i32, wide),
            _ => false,
        }
    };
    ACTIVE = true;
    if !done {
        return 2;
    }
    let flags = state::read_flags64();
    state::write_flags64(flags);
    match step_result(&before, writes) {
        StepOutcome::Exit => 1,
        _ => 0,
    }
}

/// The parts of a step's context that changed, each a STEP_CONTEXT event:
/// STEP_EXIT_CHAINABLE if only those P4.3's STEP_CHAIN may continue after
/// did (the CPL, CS, CR3, the epoch, IF, IOPL, AC), else STEP_EXIT_BARRIER
unsafe fn note_context_changes(before: &Context, after: &Context) -> u32 {
    let control = before.control ^ after.control;
    let changes = [
        (before.cpl != after.cpl, event::STEP_CONTEXT_CPL, true),
        (before.cs != after.cs, event::STEP_CONTEXT_CS, true),
        (before.long != after.long, event::STEP_CONTEXT_MODE, false),
        (before.cr0 != after.cr0, event::STEP_CONTEXT_CR0, false),
        (before.cr3 != after.cr3, event::STEP_CONTEXT_CR3, true),
        (before.cr4 != after.cr4, event::STEP_CONTEXT_CR4, false),
        (before.efer != after.efer, event::STEP_CONTEXT_EFER, false),
        (control & 0x200 != 0, event::STEP_CONTEXT_IF, true),
        (control & 0x100 != 0, event::STEP_CONTEXT_TF, false),
        (control & 0x40000 != 0, event::STEP_CONTEXT_AC, true),
        (control & 0x20000 != 0, event::STEP_CONTEXT_VM, false),
        (control & 0x10000 != 0, event::STEP_CONTEXT_RF, false),
        (control & 0x3000 != 0, event::STEP_CONTEXT_IOPL, true),
        (before.dr7 != after.dr7, event::STEP_CONTEXT_DR7, false),
        (before.epoch != after.epoch, event::STEP_CONTEXT_EPOCH, true),
    ];
    let mut chainable = true;
    for (changed, part, chain) in changes {
        if changed {
            step_profile::note_event(event::STEP_CONTEXT, part);
            chainable &= chain;
        }
    }
    if chainable {
        event::STEP_EXIT_CHAINABLE
    }
    else {
        event::STEP_EXIT_BARRIER
    }
}

/// EFLAGS with the pending bits of a lazy record (pagegen::Emitter::record)
/// computed: record = ALU code << 16 | log2(width / 8) << 20 | carry << 23 |
/// pending bits; `a`, `b` the operands.
/// With pagegen::RECORD_UNIT (an INC or DEC in legacy mode) `a` is the
/// result.
#[no_mangle]
pub fn x64_page_flags(record: u32, a: u64, b: u64, flags: u32) -> u32 {
    let code = (record >> 16 & 7) as u8;
    let width = 8u8 << (record >> 20 & 3);
    let carry = (record >> 23 & 1) as u64;
    let pending = record & 0x8D5;
    // (an INC or DEC whose `a` is the result: M8, pagegen::RECORD_UNIT)
    let (a, b) = if record & pagegen::RECORD_UNIT != 0 {
        let mask = if width == 64 { !0 } else { (1u64 << width) - 1 };
        (
            if code == 5 { a.wrapping_add(1) } else { a.wrapping_sub(1) } & mask,
            1,
        )
    }
    else {
        (a, b)
    };
    let (_, computed) = super::execute::alu(code, a, b, width, carry);
    flags & !pending | computed as u32 & pending
}

/// FLDCW for generated code in legacy mode, the word read (M8): as
/// fpu::fpu_fldcw, which leaves the x87 stack and its cache as they are
#[no_mangle]
pub unsafe fn x64_page_fldcw(word: i32) { crate::cpu::fpu::set_control_word(word as u16); }

/// INVLPG for generated code (CPL 0 is checked inline). True when the
/// function must leave after it: the access cache was flushed (its epoch
/// changed), or the invalidated page may be the running code page (or in its
/// 2 MiB region).
#[no_mangle]
pub unsafe fn x64_page_invlpg(address: u64) -> bool {
    // Intel defines a noncanonical INVLPG operand as a no-op.
    if !state::canonical(address, 48) {
        return false;
    }
    let core = apic::current_core();
    let before = jac::epoch_bits(core);
    memory::invlpg(address);
    cpu::invlpg(address as i32);
    jac::epoch_bits(core) != before || address >> 21 == *gp::x64_page_linear >> 21
}

/// The commit of a locked instruction (pagegen locked_store, cores in
/// workers): replace `expected` by `value` at the aligned host address, as
/// the interpreter's locked instructions do; 0 when another core changed it.
#[no_mangle]
pub unsafe fn x64_page_lock_commit(host: u32, expected: u64, value: u64, bytes: u32) -> i32 {
    crate::parallel::compare_exchange(host as *mut u8, bytes, expected, value) as i32
}

/// Shifts and rotates without a template (pagegen Op::ShiftCall): `kind` =
/// ALU group code | width << 8 (at most 32); the result in the low half,
/// EFLAGS in the high half.
#[no_mangle]
pub fn x64_page_shift(a: u64, count: u32, flags: u32, kind: u32) -> u64 {
    let (r, f) = super::execute::shift(
        (kind & 7) as u8,
        a,
        count as u8,
        (kind >> 8) as u8,
        flags as u64,
    );
    r & 0xFFFF_FFFF | f << 32
}

/// Compatibility mode (docs/jit-unification-plan.md P7.2): a shift or
/// rotate as the 32-bit interpreter computes it, EFLAGS included
/// (cpu::arith on its lazy EFLAGS, materialized before and after): `kind` =
/// ALU group code | width << 8 (8, 16 or 32), `count` as its instruction
/// handlers mask it, `last_op1` the page function's (pagegen
/// Emitter::last_op1: SHL, SHR and SAR leave AF to it). The result in the
/// low half, EFLAGS in the high half.
#[no_mangle]
pub unsafe fn x64_page_shift32(a: u64, count: u32, flags: u32, kind: u32, last_op1: i32) -> u64 {
    use crate::cpu::arith::*;
    *gp::flags = flags as i32;
    *gp::flags_changed = 0;
    *gp::last_op1 = last_op1;
    let (a, count) = (a as i32, (count & 31) as i32);
    let r = match (kind >> 8, kind & 7) {
        (8, 0) => rol8(a, count),
        (8, 1) => ror8(a, count),
        (8, 2) => rcl8(a, count),
        (8, 3) => rcr8(a, count),
        (8, 5) => shr8(a, count),
        (8, 7) => sar8(a, count),
        (8, _) => shl8(a, count),
        (16, 0) => rol16(a, count),
        (16, 1) => ror16(a, count),
        (16, 2) => rcl16(a, count),
        (16, 3) => rcr16(a, count),
        (16, 5) => shr16(a, count),
        (16, 7) => sar16(a, count),
        (16, _) => shl16(a, count),
        (_, 0) => rol32(a, count),
        (_, 1) => ror32(a, count),
        (_, 2) => rcl32(a, count),
        (_, 3) => rcr32(a, count),
        (_, 5) => shr32(a, count),
        (_, 7) => sar32(a, count),
        _ => shl32(a, count),
    };
    let f = cpu::get_eflags();
    *gp::flags = f;
    *gp::flags_changed = 0;
    r as u32 as u64 | (f as u32 as u64) << 32
}

/// PCMPESTRx/PCMPISTRx for generated code (x64::helpers::pcmpstr on
/// its operand block): the lengths RAX/RDX, or EAX/EDX sign-extended
#[no_mangle]
pub unsafe fn x64_page_pcmpstr(op: u32, imm8: u32, a: i64, b: i64) -> u32 {
    super::helpers::pcmpstr(op, imm8, a, b)
}

/// MOV and POP ES, DS, FS or GS in legacy-mode code (pagegen
/// Emitter::load_segment, P7.3), as Tier-0's ir_t0_load_seg: 1 when refused
/// (nothing changed: the instruction is retried); else the segment is
/// loaded: 2 when the code no longer runs as the function was compiled
/// (legacy_runnable: a null ES or FS, a nonzero ES base; with `segmented`,
/// segmented_runnable: a null ES, DS or FS; switch_seg_without_fault
/// refuses a DS that changes flat segmentation), so it leaves after it
#[no_mangle]
pub unsafe fn x64_page_load_seg(segment: u32, selector: u32, segmented: u32) -> u32 {
    if !cpu::switch_seg_without_fault(segment as i32, selector as i32 & 0xFFFF, segmented == 0) {
        return 1;
    }
    // (a function compiled for segment bases runs flat segments too; 16-bit
    // code, P7.7, P7.8, any)
    if legacy_runnable() || segmented != 0 && runnable_kind() >= 2 {
        0
    }
    else {
        2
    }
}

/// RDTSC for generated code (the privilege check is inline).
#[no_mangle]
pub unsafe fn x64_page_rdtsc() -> u64 { cpu::read_tsc() }

/// STI's interrupt shadow ended in compiled code (pagegen: End::Shadow,
/// x64_sti_shadow): 1 if an interrupt is deliverable under `flags` (the
/// function leaves for the dispatcher, which takes it)
#[no_mangle]
pub unsafe fn x64_page_irq_window(flags: i32) -> i32 {
    (flags & 0x200 != 0
        && (apic::has_pending_irq() || apic::routed_pic_pending(apic::current_core() as u32)))
        as i32
}
/// MOV r64, CR8 for generated code (CPL 0 is checked inline).
#[no_mangle]
pub unsafe fn x64_page_cr8() -> u64 { state::read_cr(8) }
/// MOV CR8, r64 for generated code: 0 continue, 1 retry (reserved bits are
/// #GP), 2 leave after the instruction (an interrupt the new task priority
/// admits is taken at the next boundary).
#[no_mangle]
pub unsafe fn x64_page_set_cr8(value: u64) -> i32 {
    if super::system::write_cr(8, value).is_err() {
        return 1;
    }
    if *gp::flags & cpu::FLAG_INTERRUPT != 0 && apic::has_pending_irq() {
        2
    }
    else {
        0
    }
}

/// Whether the signed 64x64 product of IMUL overflows 64 bits.
#[no_mangle]
pub fn x64_page_imul_overflow(a: u64, b: u64) -> bool { (a as i64).checked_mul(b as i64).is_none() }
/// High 64 bits of the 128-bit product of MUL (or IMUL when `signed`).
#[no_mangle]
pub fn x64_page_mul_high(a: u64, b: u64, signed: bool) -> u64 {
    if signed {
        ((a as i64 as i128 * b as i64 as i128) >> 64) as u64
    }
    else {
        ((a as u128 * b as u128) >> 64) as u64
    }
}

#[cfg(test)]
mod quota_tests {
    use super::*;
    fn function(page: u32, last_used: u64) -> Function {
        Function {
            page,
            id: 0,
            slot: 0,
            phase: Phase::Ready,
            served: vec![0; 64],
            members: vec![page],
            last_used,
            x: X86Code::default(),
        }
    }
    fn runtime(functions: Vec<Function>) -> Runtime {
        let mut r = Runtime::new(X86Extra {
            released_counters: Vec::new(),
            last_rip: 0,
            last_page: 0,
        });
        r.functions = functions;
        r
    }
    /// (P7.2b) A full table retires the least recently used function, but
    /// of the compiling code's mode once that mode holds more than its share
    #[test]
    fn each_mode_keeps_a_share() {
        // the oldest functions are the long mode's: 2000 of them
        let mut functions: Vec<Function> = (0..2000).map(|i| function(i, i as u64)).collect();
        functions.extend(
            (0..MAX_FUNCTIONS as u32 - 2000).map(|i| function(i | COMPAT_KEY, 10_000 + i as u64)),
        );
        let r = runtime(functions);
        // compatibility-mode code beyond its share retires its own
        let victim = eviction_victim(&r, true).unwrap();
        assert!(r.functions[victim].page & COMPAT_KEY != 0);
        assert_eq!(r.functions[victim].last_used, 10_000);
        // long-mode code within its share: the least recently used of all
        let victim = eviction_victim(&r, false).unwrap();
        assert_eq!(r.functions[victim].last_used, 0);
        // a mode within its share takes the oldest of all, the crowded one
        // its own
        let mut few: Vec<Function> = (0..10)
            .map(|i| function(i | COMPAT_KEY, 50 + i as u64))
            .collect();
        few.extend((0..MAX_FUNCTIONS as u32 - 10).map(|i| function(i, 100 + i as u64)));
        let few = runtime(few);
        assert_eq!(
            few.functions[eviction_victim(&few, true).unwrap()].last_used,
            50
        );
        assert_eq!(
            few.functions[eviction_victim(&few, false).unwrap()].last_used,
            100
        );
    }
}
                                                                                                                                                 source/v64/src/rust/x64/paging.rs                                                                   0000644 0000000 0000000 00000071770 00000000000 013720  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Four-level translation for the 48-linear/36-physical Intel profile.
//! The same walk serves execution and compilation. Snapshot walks never set
//! A/D or deliver an exception, and a bus can reject unsafe (MMIO) peeks.
use super::state::{canonical, LinearAddress, PhysicalAddress};

pub const PHYSICAL_BITS: u8 = 36;
pub const PHYSICAL_MASK: u64 = (1 << PHYSICAL_BITS) - 1;
const ADDRESS: u64 = 0x000F_FFFF_FFFF_F000;
const NX: u64 = 1 << 63;
pub const TLB_SNAPSHOT_DWORDS: usize = 18;
pub const TLB_CAPACITY: usize = 256;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Access {
    Read,
    Write,
    Execute,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WalkMode {
    Runtime,
    Snapshot,
}
#[derive(Clone, Copy, Debug)]
pub struct Controls {
    pub cr3: u64,
    pub user: bool,
    pub write_protect: bool,
    pub nx_enable: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Fault {
    NonCanonical(LinearAddress),
    Page {
        address: LinearAddress,
        error: u32,
        level: u8,
    },
    Unavailable(PhysicalAddress),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Translation {
    pub physical: PhysicalAddress,
    pub page_shift: u8,
    pub writable: bool,
    pub user: bool,
    pub executable: bool,
    pub global: bool,
    // Complete physical witnesses, including paging structures above 4 GiB.
    pub witnesses: [PhysicalAddress; 4],
    pub witness_count: u8,
}
pub trait PageTableMemory {
    fn read_entry(&mut self, address: PhysicalAddress, mode: WalkMode) -> Option<u64>;
    fn write_entry(&mut self, address: PhysicalAddress, value: u64) -> bool;
}

pub fn walk<M: PageTableMemory>(
    memory: &mut M,
    address: LinearAddress,
    access: Access,
    controls: Controls,
    mode: WalkMode,
) -> Result<Translation, Fault> {
    if !canonical(address.0, 48) {
        return Err(Fault::NonCanonical(address));
    }
    let error = (access == Access::Write) as u32 * 2
        | (controls.user as u32) * 4
        | ((access == Access::Execute && controls.nx_enable) as u32) * 16;
    let page_fault = |present, reserved, level| Fault::Page {
        address,
        error: error | present as u32 | ((reserved as u32) << 3),
        level,
    };
    let mut table = controls.cr3 & PHYSICAL_MASK & !0xFFF;
    let mut writable = true;
    let mut user = true;
    let mut executable = true;
    let mut witnesses = [PhysicalAddress(0); 4];
    for level in (1u8..=4).rev() {
        let shift = 12 + (level - 1) * 9;
        let entry_address = PhysicalAddress(table + ((address.0 >> shift) & 511) * 8);
        witnesses[(4 - level) as usize] = entry_address;
        let entry = memory
            .read_entry(entry_address, mode)
            .ok_or(Fault::Unavailable(entry_address))?;
        if entry & 1 == 0 {
            return Err(page_fault(false, false, level));
        }
        let large = level > 1 && entry & 0x80 != 0;
        if entry & ADDRESS & !PHYSICAL_MASK != 0
            || !controls.nx_enable && entry & NX != 0
            || large && level != 2
            || large && entry & 0x1F_E000 != 0
        {
            return Err(page_fault(true, true, level));
        }
        writable &= entry & 2 != 0;
        user &= entry & 4 != 0;
        executable &= entry & NX == 0;
        if mode == WalkMode::Runtime
            && entry & 0x20 == 0
            && !memory.write_entry(entry_address, entry | 0x20)
        {
            return Err(Fault::Unavailable(entry_address));
        }
        if level == 1 || large {
            if controls.user && !user
                || access == Access::Write && !writable && (controls.user || controls.write_protect)
                || access == Access::Execute && !executable
            {
                return Err(page_fault(true, false, level));
            }
            if mode == WalkMode::Runtime
                && access == Access::Write
                && entry & 0x40 == 0
                && !memory.write_entry(entry_address, entry | 0x60)
            {
                return Err(Fault::Unavailable(entry_address));
            }
            let page_shift = if large { 21 } else { 12 };
            let offset_mask = (1u64 << page_shift) - 1;
            return Ok(Translation {
                physical: PhysicalAddress(
                    (entry & ADDRESS & !offset_mask) | (address.0 & offset_mask),
                ),
                page_shift,
                writable,
                user,
                executable,
                global: entry & 0x100 != 0,
                witnesses,
                witness_count: 5 - level,
            });
        }
        table = entry & ADDRESS;
    }
    unreachable!()
}

/// A bounded, full-tag translation cache. No allocation proportional to the
/// guest linear page number, and no low-32-bit address aliases.
pub struct Tlb {
    entries: [Option<Cached>; TLB_CAPACITY],
    /// entries of non-global translations (tagged with CR3 as well)
    epoch: u64,
    /// entries of global translations: MOV CR3 keeps them (clear_nonglobal)
    global_epoch: u64,
    /// 2 MiB linear regions (hashed) that may hold entries of large pages
    /// since the last clear; bit 0 of the last word: some entry is a 1 GiB
    /// page. Invalidating a page elsewhere only checks its own slots.
    large: [u64; TLB_LARGE_WORDS],
}
const TLB_LARGE_WORDS: usize = 16;
fn tlb_region_bit(address: u64) -> (usize, u64) {
    let region = (address >> 21) as usize & (TLB_LARGE_WORDS * 64 - 1);
    (region / 64, 1 << (region % 64))
}
#[derive(Clone, Copy)]
struct Cached {
    linear_page: u64,
    cr3: u64,
    control: u8,
    epoch: u64,
    value: Translation,
}
impl Default for Tlb {
    fn default() -> Self { Self::new() }
}
impl Tlb {
    pub const fn new() -> Self {
        Self {
            entries: [None; TLB_CAPACITY],
            epoch: 1,
            global_epoch: 1,
            large: [0; TLB_LARGE_WORDS],
        }
    }
    /// A global entry matches under any CR3 until a full clear; the G bit is
    /// honored only with CR4.PGE, but without it every CR3 write clears
    /// everything (system::write_cr), so the raw bit is enough here.
    #[inline(always)]
    fn current(&self, entry: &Cached, cr3: u64) -> bool {
        if entry.value.global {
            entry.epoch == self.global_epoch
        }
        else {
            entry.epoch == self.epoch && entry.cr3 == cr3
        }
    }
    fn control(access: Access, c: Controls) -> u8 {
        access as u8 | (c.user as u8) << 2 | (c.write_protect as u8) << 3 | (c.nx_enable as u8) << 4
    }
    // Read, write and fetch translations of one page are separate entries;
    // spread them so data and stack traffic do not evict each other.
    fn slot(address: LinearAddress, access: u8) -> usize {
        ((address.0 >> 12) ^ (address.0 >> 32) ^ ((access as u64 & 3) << 6)) as usize & 255
    }
    /// Hot-path hit: only the physical address, without copying witnesses.
    #[inline(always)]
    pub fn lookup_physical(
        &self,
        address: LinearAddress,
        access: Access,
        c: Controls,
    ) -> Option<u64> {
        let entry = self.entries[Self::slot(address, access as u8)].as_ref()?;
        if !self.current(entry, c.cr3)
            || entry.linear_page != address.0 >> 12
            || entry.control != Self::control(access, c)
        {
            return None;
        }
        Some((entry.value.physical.0 & !4095) | (address.0 & 4095))
    }
    pub fn lookup(
        &self,
        address: LinearAddress,
        access: Access,
        c: Controls,
    ) -> Option<Translation> {
        let entry = self.entries[Self::slot(address, access as u8)]?;
        if !self.current(&entry, c.cr3)
            || entry.linear_page != address.0 >> 12
            || entry.control != Self::control(access, c)
        {
            return None;
        }
        let mut value = entry.value;
        value.physical.0 = (value.physical.0 & !4095) | (address.0 & 4095);
        Some(value)
    }
    pub fn insert(
        &mut self,
        address: LinearAddress,
        access: Access,
        c: Controls,
        value: Translation,
    ) {
        if value.page_shift > 12 {
            let (word, bit) = if value.page_shift > 21 {
                (TLB_LARGE_WORDS - 1, 1)
            }
            else {
                tlb_region_bit(address.0)
            };
            self.large[word] |= bit;
            // (a 1 GiB page makes every invalidation a full scan)
            if value.page_shift > 21 {
                self.large = [u64::MAX; TLB_LARGE_WORDS];
            }
        }
        self.entries[Self::slot(address, access as u8)] = Some(Cached {
            linear_page: address.0 >> 12,
            cr3: c.cr3,
            control: Self::control(access, c),
            epoch: if value.global { self.global_epoch } else { self.epoch },
            value,
        });
    }
    pub fn invalidate(&mut self, address: LinearAddress) {
        let (word, bit) = tlb_region_bit(address.0);
        if self.large[word] & bit == 0 {
            // only 4 KiB entries can map this page: they are in its own slots
            for access in [Access::Read, Access::Write, Access::Execute] {
                let slot = &mut self.entries[Self::slot(address, access as u8)];
                if slot.is_some_and(|entry| entry.linear_page == address.0 >> 12) {
                    *slot = None;
                }
            }
            return;
        }
        for slot in &mut self.entries {
            if slot.is_some_and(|entry| {
                (entry.linear_page << 12) >> entry.value.page_shift
                    == address.0 >> entry.value.page_shift
            }) {
                *slot = None;
            }
        }
    }
    pub fn clear(&mut self) {
        self.large = [0; TLB_LARGE_WORDS];
        self.epoch = self.epoch.wrapping_add(1);
        self.global_epoch = self.global_epoch.wrapping_add(1);
        if self.epoch == 0 || self.global_epoch == 0 {
            self.entries = [None; TLB_CAPACITY];
            self.epoch = 1;
            self.global_epoch = 1;
        }
    }
    /// MOV CR3 (CR4.PGE set, no PCID): the non-global entries go.
    pub fn clear_nonglobal(&mut self) {
        self.epoch = self.epoch.wrapping_add(1);
        if self.epoch == 0 {
            self.clear();
        }
    }

    /// Portable architectural cache state. Keep stale translations until an
    /// architectural invalidation, rather than re-walking modified tables on
    /// restore. Epochs and native layout/pointers are deliberately excluded.
    pub fn snapshot(&self) -> Vec<u32> {
        let mut records = Vec::new();
        for entry in self.entries.iter().flatten().filter(|entry| {
            entry.epoch == if entry.value.global { self.global_epoch } else { self.epoch }
        }) {
            let value = entry.value;
            records.extend_from_slice(&[
                entry.linear_page as u32,
                (entry.linear_page >> 32) as u32,
                entry.cr3 as u32,
                (entry.cr3 >> 32) as u32,
                entry.control as u32,
                value.physical.0 as u32,
                (value.physical.0 >> 32) as u32,
                value.page_shift as u32,
                value.writable as u32
                    | (value.user as u32) << 1
                    | (value.executable as u32) << 2
                    | (value.global as u32) << 3,
                value.witness_count as u32,
            ]);
            for witness in value.witnesses {
                records.push(witness.0 as u32);
                records.push((witness.0 >> 32) as u32);
            }
        }
        records
    }

    /// Validate the entire portable cache before committing. No page-table
    /// access, A/D update, guest exception, or implicit invalidation occurs.
    pub fn restore_snapshot(&mut self, records: &[u32]) -> bool {
        if records.len() % TLB_SNAPSHOT_DWORDS != 0
            || records.len() / TLB_SNAPSHOT_DWORDS > TLB_CAPACITY
        {
            return false;
        }
        let mut candidate = Tlb::new();
        for record in records.chunks_exact(TLB_SNAPSHOT_DWORDS) {
            let wide = |index: usize| record[index] as u64 | (record[index + 1] as u64) << 32;
            let linear_page = wide(0);
            let cr3 = wide(2);
            let control = record[4];
            let physical = wide(5);
            let page_shift = record[7];
            let flags = record[8];
            let witness_count = record[9];
            if linear_page > u64::MAX >> 12
                || !canonical(linear_page << 12, 48)
                || cr3 > PHYSICAL_MASK
                || physical > PHYSICAL_MASK
                || control & !31 != 0
                || control & 3 == 3
                || flags & !15 != 0
                || !matches!((page_shift, witness_count), (12, 4) | (21, 3))
            {
                return false;
            }
            let address = LinearAddress(linear_page << 12);
            let slot = Self::slot(address, control as u8);
            if candidate.entries[slot].is_some() {
                return false;
            }
            let mut witnesses = [PhysicalAddress(0); 4];
            for (index, witness) in witnesses.iter_mut().enumerate() {
                let physical = wide(10 + index * 2);
                if index < witness_count as usize {
                    if physical > PHYSICAL_MASK - 7 || physical & 7 != 0 {
                        return false;
                    }
                }
                else if physical != 0 {
                    return false;
                }
                *witness = PhysicalAddress(physical);
            }
            let value = Translation {
                physical: PhysicalAddress(physical),
                page_shift: page_shift as u8,
                writable: flags & 1 != 0,
                user: flags & 2 != 0,
                executable: flags & 4 != 0,
                global: flags & 8 != 0,
                witnesses,
                witness_count: witness_count as u8,
            };
            let user = control & 4 != 0;
            let write_protect = control & 8 != 0;
            let nx_enable = control & 16 != 0;
            if user && !value.user
                || control & 3 == Access::Write as u32 && !value.writable && (user || write_protect)
                || control & 3 == Access::Execute as u32 && !value.executable
                || !nx_enable && !value.executable
                || page_shift == 21 && physical & 0x1FF000 != address.0 & 0x1FF000
            {
                return false;
            }
            if page_shift == 21 {
                let (word, bit) = tlb_region_bit(address.0);
                candidate.large[word] |= bit;
            }
            candidate.entries[slot] = Some(Cached {
                linear_page,
                cr3,
                control: control as u8,
                epoch: if value.global { candidate.global_epoch } else { candidate.epoch },
                value,
            });
        }
        *self = candidate;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;
    #[derive(Clone)]
    struct Memory {
        words: BTreeMap<u64, u64>,
        writes: usize,
    }
    impl PageTableMemory for Memory {
        fn read_entry(&mut self, address: PhysicalAddress, _: WalkMode) -> Option<u64> {
            self.words.get(&address.0).copied()
        }
        fn write_entry(&mut self, address: PhysicalAddress, value: u64) -> bool {
            self.writes += 1;
            self.words.insert(address.0, value);
            true
        }
    }
    fn fixture(address: u64, large: bool) -> (Memory, Controls, Vec<u64>) {
        let c = Controls {
            cr3: 0x1_0000_1000,
            user: false,
            write_protect: true,
            nx_enable: true,
        };
        let mut words = BTreeMap::new();
        let mut entries = Vec::new();
        for level in (if large { 2 } else { 1 }..=4).rev() {
            let table = 0x1_0000_1000 + (4 - level) * 4096;
            let at = table + ((address >> (12 + (level - 1) * 9)) & 511) * 8;
            let value = if level == 1 || large && level == 2 {
                0xF_1000_0000 | if large { 0x87 } else { 7 }
            }
            else {
                table + 4096 | 7
            };
            words.insert(at, value);
            entries.push(at);
        }
        (Memory { words, writes: 0 }, c, entries)
    }
    #[test]
    fn full_addresses_small_large_pages_and_snapshot_purity() {
        for linear in [
            0x1234,
            0x7FFF_FFFF_F234,
            0xFFFF_8000_0000_1234,
            0xFFFF_FFFF_FFFF_F234,
        ] {
            for large in [false, true] {
                let (mut memory, controls, entries) = fixture(linear, large);
                let before = memory.words.clone();
                let result = walk(
                    &mut memory,
                    LinearAddress(linear),
                    Access::Write,
                    controls,
                    WalkMode::Snapshot,
                )
                .unwrap();
                assert_eq!(
                    result.physical.0,
                    0xF_1000_0000 | linear & if large { 0x1F_FFFF } else { 4095 }
                );
                assert_eq!(memory.words, before);
                assert_eq!(memory.writes, 0);
                assert!(result.witnesses[0].0 > u32::MAX as u64);
                assert_eq!(
                    walk(
                        &mut memory,
                        LinearAddress(linear),
                        Access::Write,
                        controls,
                        WalkMode::Runtime
                    ),
                    Ok(result)
                );
                for at in &entries {
                    assert_ne!(memory.words[at] & 0x20, 0);
                }
                assert_ne!(memory.words[entries.last().unwrap()] & 0x40, 0);
            }
        }
    }
    #[test]
    fn faults_permissions_reserved_nx_and_canonical_priority() {
        for level in 0..4 {
            for (bits, access, expected) in [
                (0, Access::Read, 4),
                (1, Access::Read, 5),
                (5, Access::Write, 7),
                (7 | NX, Access::Execute, 21),
                (7 | 1 << 36, Access::Read, 13),
            ] {
                let (mut memory, mut c, entries) = fixture(0x1234, false);
                c.user = true;
                memory.words.insert(
                    entries[level],
                    (memory.words[&entries[level]] & ADDRESS) | bits,
                );
                assert!(
                    matches!(walk(&mut memory, LinearAddress(0x1234), access, c, WalkMode::Runtime),
                    Err(Fault::Page { error, .. }) if error == expected)
                );
            }
        }
        let (mut memory, c, _) = fixture(0, false);
        assert!(matches!(
            walk(
                &mut memory,
                LinearAddress(0x8000_0000_0000),
                Access::Read,
                c,
                WalkMode::Runtime
            ),
            Err(Fault::NonCanonical(_))
        ));
        assert_eq!(memory.writes, 0);
        for nx in [false, true] {
            let (mut memory, mut c, entries) = fixture(0, false);
            c.nx_enable = nx;
            memory
                .words
                .insert(entries[0], memory.words[&entries[0]] | NX);
            assert!(
                matches!(walk(&mut memory, LinearAddress(0), Access::Execute, c, WalkMode::Runtime),
                Err(Fault::Page { error, .. }) if error == if nx { 17 } else { 9 })
            );
        }
    }
    #[test]
    fn rejects_unadvertised_gigabyte_pages_and_reserved_large_address_bits() {
        for (level, bit) in [(0, 7), (1, 7), (2, 13), (2, 20), (2, 36)] {
            let (mut memory, c, entries) = fixture(0, true);
            memory
                .words
                .insert(entries[level], memory.words[&entries[level]] | 1 << bit);
            assert!(matches!(
                walk(
                    &mut memory,
                    LinearAddress(0),
                    Access::Read,
                    c,
                    WalkMode::Snapshot
                ),
                Err(Fault::Page { error: 9, .. })
            ));
        }
    }
    #[test]
    fn supervisor_write_protect_and_full_tag_tlb_isolation() {
        let (mut memory, mut c, entries) = fixture(0x1234, false);
        let last = *entries.last().unwrap();
        memory.words.insert(last, memory.words[&last] & !2);
        c.write_protect = false;
        let translated = walk(
            &mut memory,
            LinearAddress(0x1234),
            Access::Write,
            c,
            WalkMode::Runtime,
        )
        .unwrap();
        let mut a = Tlb::new();
        let mut b = Tlb::new();
        a.insert(LinearAddress(0x1234), Access::Write, c, translated);
        b.insert(LinearAddress(0x1234), Access::Write, c, translated);
        assert_eq!(
            a.lookup(LinearAddress(0x1_0000_1234), Access::Write, c),
            None
        );
        assert_eq!(
            a.lookup(LinearAddress(0xFFFF_8000_0000_1234), Access::Write, c),
            None
        );
        assert_eq!(
            a.lookup(LinearAddress(0x1235), Access::Write, c)
                .unwrap()
                .physical
                .0,
            translated.physical.0 + 1
        );
        a.invalidate(LinearAddress(0x1234));
        assert!(a.lookup(LinearAddress(0x1234), Access::Write, c).is_none());
        assert!(b.lookup(LinearAddress(0x1234), Access::Write, c).is_some());
        b.clear();
        assert!(b.lookup(LinearAddress(0x1234), Access::Write, c).is_none());
    }

    #[test]
    fn portable_tlb_preserves_high_tags_witnesses_and_stale_translation() {
        for linear in [0x1234, 0x7FFF_FFFF_F234, 0xFFFF_8000_0000_1234] {
            for large in [false, true] {
                let address = LinearAddress(linear);
                let (mut memory, controls, entries) = fixture(linear, large);
                let translated = walk(
                    &mut memory,
                    address,
                    Access::Write,
                    controls,
                    WalkMode::Runtime,
                )
                .unwrap();
                let mut before = Tlb::new();
                before.insert(address, Access::Write, controls, translated);
                let records = before.snapshot();
                assert_eq!(records.len(), TLB_SNAPSHOT_DWORDS);
                assert_eq!(records[6], 15, "physical high DWORD survives");
                assert_eq!(records[11], 1, "page-table witness high DWORD survives");
                let leaf = *entries.last().unwrap();
                memory.words.insert(leaf, memory.words[&leaf] ^ 0x200000);
                let writes_before_restore = memory.writes;
                let mut after = Tlb::new();
                assert!(after.restore_snapshot(&records));
                assert_eq!(after.snapshot(), records);
                assert_eq!(
                    after.lookup(address, Access::Write, controls),
                    Some(translated)
                );
                assert_eq!(
                    after.lookup(LinearAddress(linear + 1), Access::Write, controls),
                    before.lookup(LinearAddress(linear + 1), Access::Write, controls)
                );
                assert!(after.lookup(address, Access::Read, controls).is_none());
                let other_cr3 = Controls {
                    cr3: controls.cr3 + 4096,
                    ..controls
                };
                assert!(after.lookup(address, Access::Write, other_cr3).is_none());
                assert_eq!(
                    memory.writes, writes_before_restore,
                    "restore performs no page walk or A/D updates"
                );
                after.invalidate(address);
                assert!(after.lookup(address, Access::Write, controls).is_none());
                let fresh = walk(
                    &mut memory,
                    address,
                    Access::Write,
                    controls,
                    WalkMode::Runtime,
                )
                .unwrap();
                assert_ne!(fresh.physical, translated.physical);
            }
        }
    }

    #[test]
    fn portable_tlb_exports_only_live_epoch_and_empty_restore_clears() {
        let address = LinearAddress(0x1234);
        let (mut memory, controls, _) = fixture(address.0, false);
        let value = walk(
            &mut memory,
            address,
            Access::Read,
            controls,
            WalkMode::Runtime,
        )
        .unwrap();
        let mut cache = Tlb::new();
        cache.insert(address, Access::Read, controls, value);
        cache.clear();
        assert!(cache.snapshot().is_empty());
        cache.insert(address, Access::Read, controls, value);
        assert!(cache.restore_snapshot(&[]));
        assert!(cache.lookup(address, Access::Read, controls).is_none());
        assert!(cache.snapshot().is_empty());
    }

    #[test]
    fn portable_tlb_invalid_record_rejects_entire_transaction() {
        let address = LinearAddress(0x1234);
        let (mut memory, controls, _) = fixture(address.0, false);
        let value = walk(
            &mut memory,
            address,
            Access::Write,
            controls,
            WalkMode::Runtime,
        )
        .unwrap();
        let mut cache = Tlb::new();
        cache.insert(address, Access::Write, controls, value);
        let records = cache.snapshot();
        for (index, invalid) in [
            (1, 8),
            (1, 0x100000),
            (3, 16),
            (4, 32),
            (4, 3),
            (6, 16),
            (7, 13),
            (8, 16),
            (8, 6),
            (9, 3),
            (10, 1),
            (11, 16),
        ] {
            let mut bad = records.clone();
            bad[index] = invalid;
            assert!(
                !cache.restore_snapshot(&bad),
                "field {index}, invalid {invalid}"
            );
            assert_eq!(cache.snapshot(), records);
            assert_eq!(cache.lookup(address, Access::Write, controls), Some(value));
        }
        for bad in [
            records[..17].to_vec(),
            records.repeat(2),
            records.repeat(TLB_CAPACITY + 1),
        ] {
            assert!(!cache.restore_snapshot(&bad));
            assert_eq!(cache.snapshot(), records);
        }
        let mut colliding = records.repeat(2);
        colliding[TLB_SNAPSHOT_DWORDS] += 256;
        assert!(
            !cache.restore_snapshot(&colliding),
            "different tags cannot occupy the same direct-mapped slot"
        );
        assert_eq!(cache.snapshot(), records);
    }

    #[test]
    fn portable_large_page_invlpg_and_unused_witness_validation() {
        let controls = fixture(0, true).1;
        let mut cache = Tlb::new();
        for linear in [0x1234, 0x2345] {
            let (mut memory, _, _) = fixture(linear, true);
            let mut value = walk(
                &mut memory,
                LinearAddress(linear),
                Access::Read,
                controls,
                WalkMode::Runtime,
            )
            .unwrap();
            value.global = true;
            cache.insert(LinearAddress(linear), Access::Read, controls, value);
        }
        let records = cache.snapshot();
        let mut restored = Tlb::new();
        assert!(restored.restore_snapshot(&records));
        assert!(
            restored
                .lookup(LinearAddress(0x1234), Access::Read, controls)
                .unwrap()
                .global
        );
        let mut bad = records.clone();
        bad[16] = 8;
        assert!(
            !restored.restore_snapshot(&bad),
            "unused witness must remain zero"
        );
        assert_eq!(restored.snapshot(), records);
        bad = records.clone();
        bad[5] ^= 4096;
        assert!(
            !restored.restore_snapshot(&bad),
            "large page must preserve the linear subpage offset"
        );
        restored.invalidate(LinearAddress(0x1F_F000));
        assert!(
            restored.snapshot().is_empty(),
            "INVLPG evicts all cached subpages of the large translation"
        );
    }

    #[test]
    fn portable_tlb_preserves_supervisor_wp_bypass_permissions() {
        let address = LinearAddress(0x1234);
        let (mut memory, mut controls, entries) = fixture(address.0, false);
        controls.write_protect = false;
        let leaf = *entries.last().unwrap();
        memory.words.insert(leaf, memory.words[&leaf] & !2);
        let value = walk(
            &mut memory,
            address,
            Access::Write,
            controls,
            WalkMode::Runtime,
        )
        .unwrap();
        assert!(!value.writable);
        let mut cache = Tlb::new();
        cache.insert(address, Access::Write, controls, value);
        let records = cache.snapshot();
        assert!(cache.restore_snapshot(&records));
        assert_eq!(cache.lookup(address, Access::Write, controls), Some(value));
        let protected = Controls {
            write_protect: true,
            ..controls
        };
        assert!(cache.lookup(address, Access::Write, protected).is_none());
    }
}
        source/v64/src/rust/x64/physical.rs                                                                 0000644 0000000 0000000 00000113636 00000000000 014265  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! A 36-bit guest physical bus over the existing wasm32 backing store.
//!
//! Guest addresses never become host pointers by truncation. High RAM windows
//! relocate existing backing bytes: their old low physical range becomes a
//! hole in this bus. MMIO windows explicitly decode to an existing 32-bit
//! device address; this does not extend that device's DMA address width.
//!
//! Mapping changes are host operations at a CPU safe point. They invalidate
//! all core translations and shared generated code, never from a memory helper
//! while a compiled frame is active. RAM capacity remains bounded by wasm32.

use crate::cpu::{context, global_pointers, memory};
use crate::x64::state::PhysicalAddress;

pub const PHYSICAL_BITS: u32 = 36;
pub const PHYSICAL_LIMIT: u64 = 1 << PHYSICAL_BITS;
pub const HIGH_MEMORY_BASE: u64 = 1 << 32;
pub const MAX_WINDOWS: usize = 16;
const PAGE_MASK: u64 = 0xFFF;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PhysicalError {
    AddressWidth,
    Unmapped,
    InvalidWindow,
    Overlap,
    SideEffecting,
    Busy,
    GenerationExhausted,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WindowKind {
    Ram,
    Mmio,
    /// RAM beyond the wasm32 backing store (crate::x64::extended): no window
    /// has this kind; the bus resolves the extended range to it. It is never
    /// plain RAM for caches, so every access goes through the bus helpers.
    Extended,
}

/// `backing` is an address in the old 32-bit RAM/MMIO bus, not a host pointer
/// and not the low dword of `guest_base`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Window {
    pub guest_base: PhysicalAddress,
    pub backing: u32,
    pub length: u32,
    pub kind: WindowKind,
}

/// A code/page-table snapshot may use this page only while its generation
/// still matches. Code-write dependencies must watch `backing` as well as
/// retain the full guest physical identity; writes still use the bus helpers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RamPage {
    pub guest: PhysicalAddress,
    pub backing: u32,
    pub generation: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct Resolved {
    backing: u32,
    kind: WindowKind,
}

#[derive(Clone, Copy)]
struct PhysicalBus {
    windows: [Option<Window>; MAX_WINDOWS],
    generation: u64,
}

impl PhysicalBus {
    const fn new() -> Self {
        Self {
            windows: [None; MAX_WINDOWS],
            generation: 1,
        }
    }

    fn validate(&self, slot: usize, window: Window, ram_size: u32) -> Result<(), PhysicalError> {
        if slot >= MAX_WINDOWS
            || window.length == 0
            || window.guest_base.0 < HIGH_MEMORY_BASE
            || (window.guest_base.0 | window.backing as u64 | window.length as u64) & PAGE_MASK != 0
        {
            return Err(PhysicalError::InvalidWindow);
        }
        checked_range(window.guest_base.0, window.length as u64)?;
        let backing_end = window.backing as u64 + window.length as u64;
        if backing_end > HIGH_MEMORY_BASE {
            return Err(PhysicalError::InvalidWindow);
        }
        let backing_is_ram = backing_end <= ram_size as u64
            && !overlaps(window.backing as u64, backing_end, 0xA0000, 0xC0000);
        let backing_is_mmio =
            window.backing >= ram_size || window.backing >= 0xA0000 && backing_end <= 0xC0000;
        if match window.kind {
            WindowKind::Ram => !backing_is_ram,
            WindowKind::Mmio => !backing_is_mmio,
            WindowKind::Extended => true,
        } {
            return Err(PhysicalError::InvalidWindow);
        }
        if let Some((start, end)) = unsafe { super::extended::range() } {
            if overlaps(
                window.guest_base.0,
                window.guest_base.0 + window.length as u64,
                start,
                end,
            ) {
                return Err(PhysicalError::Overlap);
            }
        }
        for (index, other) in self.windows.iter().enumerate() {
            if index == slot {
                continue;
            }
            let Some(other) = other
            else {
                continue;
            };
            if overlaps(
                window.guest_base.0,
                window.guest_base.0 + window.length as u64,
                other.guest_base.0,
                other.guest_base.0 + other.length as u64,
            ) || window.kind == WindowKind::Ram
                && other.kind == WindowKind::Ram
                && overlaps(
                    window.backing as u64,
                    backing_end,
                    other.backing as u64,
                    other.backing as u64 + other.length as u64,
                )
            {
                return Err(PhysicalError::Overlap);
            }
        }
        Ok(())
    }

    fn replace(
        &mut self,
        slot: usize,
        window: Option<Window>,
        ram_size: u32,
    ) -> Result<bool, PhysicalError> {
        if slot >= MAX_WINDOWS {
            return Err(PhysicalError::InvalidWindow);
        }
        if let Some(window) = window {
            self.validate(slot, window, ram_size)?;
        }
        if self.windows[slot] == window {
            return Ok(false);
        }
        let next = self
            .generation
            .checked_add(1)
            .ok_or(PhysicalError::GenerationExhausted)?;
        self.windows[slot] = window;
        self.generation = next;
        Ok(true)
    }

    fn resolve(&self, address: u64, ram_size: u32) -> Result<Resolved, PhysicalError> {
        checked_range(address, 1)?;
        if address < HIGH_MEMORY_BASE {
            // (the extended RAM aperture is not guest physical memory)
            if super::extended::aperture::contains(address as u32) {
                return Err(PhysicalError::Unmapped);
            }
            // A relocated RAM range is absent at its original guest address.
            // Its backing remains accessible only after a high-window lookup.
            for window in self.windows.iter().flatten() {
                if window.kind == WindowKind::Ram
                    && address >= window.backing as u64
                    && address < window.backing as u64 + window.length as u64
                {
                    return Err(PhysicalError::Unmapped);
                }
            }
            return Ok(Resolved {
                backing: address as u32,
                kind: if address >= ram_size as u64
                    || (0xA0000..0xC0000).contains(&address)
                    // (TSEG outside SMM: the legacy bus's all-ones hole)
                    || unsafe { crate::cpu::smm::tseg_blackhole(address as u32) }
                {
                    WindowKind::Mmio
                }
                else {
                    WindowKind::Ram
                },
            });
        }
        for window in self.windows.iter().flatten() {
            if address >= window.guest_base.0
                && address - window.guest_base.0 < window.length as u64
            {
                return Ok(Resolved {
                    backing: (window.backing as u64 + address - window.guest_base.0) as u32,
                    kind: window.kind,
                });
            }
        }
        if unsafe { super::extended::contains(address) } {
            return Ok(Resolved {
                backing: 0,
                kind: WindowKind::Extended,
            });
        }
        Err(PhysicalError::Unmapped)
    }

    fn probe(&self, address: u64, size: usize, ram_size: u32) -> Result<(), PhysicalError> {
        if size == 0 || size > 16 {
            return Err(PhysicalError::InvalidWindow);
        }
        checked_range(address, size as u64)?;
        for offset in 0..size {
            self.resolve(address + offset as u64, ram_size)?;
        }
        Ok(())
    }

    fn ram_page(&self, address: u64, ram_size: u32) -> Result<RamPage, PhysicalError> {
        if address & PAGE_MASK != 0 {
            return Err(PhysicalError::InvalidWindow);
        }
        checked_range(address, 0x1000)?;
        let first = self.resolve(address, ram_size)?;
        let last = self.resolve(address + PAGE_MASK, ram_size)?;
        if first.kind != WindowKind::Ram || last.kind != WindowKind::Ram {
            return Err(PhysicalError::SideEffecting);
        }
        // Windows and the VGA hole have page-aligned boundaries. Checking
        // both ends also excludes a final partial page of the backing RAM.
        if first.backing.checked_add(PAGE_MASK as u32) != Some(last.backing) {
            return Err(PhysicalError::Unmapped);
        }
        Ok(RamPage {
            guest: PhysicalAddress(address),
            backing: first.backing,
            generation: self.generation,
        })
    }

    // Resolve the entire access before any backing read/write. Thus an absent
    // trailing window cannot produce partial RAM writes or a leading MMIO read.
    fn access(
        &self,
        address: u64,
        width: usize,
        ram_size: u32,
    ) -> Result<[Resolved; 8], PhysicalError> {
        if ![1, 2, 4, 8].contains(&width) {
            return Err(PhysicalError::InvalidWindow);
        }
        checked_range(address, width as u64)?;
        let mut bytes = [Resolved {
            backing: 0,
            kind: WindowKind::Ram,
        }; 8];
        for (offset, byte) in bytes.iter_mut().enumerate().take(width) {
            *byte = self.resolve(address + offset as u64, ram_size)?;
        }
        Ok(bytes)
    }
}

// Machine-owned mapping state; no CPU register or TLB state lives here.
static mut PHYSICAL_BUS: PhysicalBus = PhysicalBus::new();

/// A worker instance (crate::parallel) maps the machine's windows. They
/// change only while every worker is stopped, which copies them again.
pub unsafe fn copy_from_machine() {
    PHYSICAL_BUS = *crate::parallel::machine(&raw mut PHYSICAL_BUS);
}

fn checked_range(address: u64, length: u64) -> Result<(), PhysicalError> {
    if length == 0
        || address >= PHYSICAL_LIMIT
        || address
            .checked_add(length - 1)
            .is_none_or(|last| last >= PHYSICAL_LIMIT)
    {
        Err(PhysicalError::AddressWidth)
    }
    else {
        Ok(())
    }
}

fn overlaps(start: u64, end: u64, other_start: u64, other_end: u64) -> bool {
    start < other_end && other_start < end
}

fn contiguous(bytes: &[Resolved]) -> bool {
    let first = bytes[0];
    // (extended RAM has no backing address: see read_allowed and write)
    first.kind != WindowKind::Extended && bytes.iter().enumerate().all(|(offset, byte)| {
        first.backing.checked_add(offset as u32) == Some(byte.backing) && first.kind == byte.kind
            // Keep a fast MMIO access inside one device page. Cross-page or
            // split-window accesses are performed in ascending byte order.
            && (first.kind == WindowKind::Ram || first.backing >> 12 == byte.backing >> 12)
    })
}

/// Mapping generation must accompany any cached RAM view/translation.
pub unsafe fn generation() -> u64 { PHYSICAL_BUS.generation }

/// Portable configuration for snapshots; restoring it uses `restore_windows`
/// so old generation values cannot accidentally revalidate stale code/views.
pub unsafe fn windows() -> [Option<Window>; MAX_WINDOWS] { PHYSICAL_BUS.windows }

/// Validate a complete scalar/SIMD transaction without reading any MMIO byte
/// or committing a RAM write. Adjacent, separately backed windows are valid.
pub unsafe fn probe(address: u64, size: usize) -> Result<(), PhysicalError> {
    // (extended RAM does not overlap any window: see PhysicalBus::validate)
    if size != 0
        && size <= 16
        && (plain_ram(address, size)
            || super::extended::contains(address) && same_page(address, size))
    {
        return Ok(());
    }
    (&*(&raw const PHYSICAL_BUS)).probe(address, size, *global_pointers::memory_size)
}

/// Below the first relocated RAM byte and outside the VGA hole, physical
/// bytes are their own RAM backing: the window search cannot change the
/// result, so hot accesses skip it. Anything else takes the full decode.
#[inline(always)]
pub unsafe fn plain_ram(address: u64, width: usize) -> bool {
    let end = address.wrapping_add(width as u64);
    end >= address && end <= memory::ram_fast_limit as u64 && (end <= 0xA0000 || address >= 0xC0000)
}

/// Resolve one physical byte to the legacy RAM/MMIO bus. This is address
/// decoding, not truncation; callers accessing more than one byte must probe
/// or resolve the complete range first.
pub unsafe fn resolve_backing(address: u64) -> Result<u32, PhysicalError> {
    if plain_ram(address, 1) {
        return Ok(address as u32);
    }
    let resolved = (&*(&raw const PHYSICAL_BUS)).resolve(address, *global_pointers::memory_size)?;
    Ok(match resolved.kind {
        // (a slot of the aperture: extended RAM through the 32-bit bus)
        WindowKind::Extended => super::extended::aperture::map(address),
        _ => resolved.backing,
    })
}

/// The backing address of `size` bytes of RAM at `address` that are
/// contiguous in the backing store, or None (MMIO, holes, split windows)
pub unsafe fn ram_backing(address: u64, size: usize) -> Option<u32> {
    if plain_ram(address, size) {
        return Some(address as u32);
    }
    let bytes = (&*(&raw const PHYSICAL_BUS))
        .access(address, size, *global_pointers::memory_size)
        .ok()?;
    (contiguous(&bytes[..size])
        && bytes[..size]
            .iter()
            .all(|byte| byte.kind == WindowKind::Ram))
    .then_some(bytes[0].backing)
}

/// Called only above the legacy RAM fast limit. A high RAM window removes
/// this range from the low guest bus while keeping its host backing alive.
pub unsafe fn is_low_ram_hole(address: u32) -> bool {
    (&*(&raw const PHYSICAL_BUS))
        .windows
        .iter()
        .flatten()
        .any(|window| {
            window.kind == WindowKind::Ram
                && address >= window.backing
                && (address as u64) < window.backing as u64 + window.length as u64
        })
}

#[no_mangle]
pub unsafe extern "C" fn x64_phys_kind(low: u32, high: u32) -> u32 {
    match (&*(&raw const PHYSICAL_BUS)).resolve(
        (high as u64) << 32 | low as u64,
        *global_pointers::memory_size,
    ) {
        Ok(Resolved {
            kind: WindowKind::Ram,
            ..
        }) => 1,
        Ok(Resolved {
            kind: WindowKind::Mmio,
            ..
        }) => 2,
        Ok(Resolved {
            kind: WindowKind::Extended,
            ..
        }) => 3,
        Err(_) => 0,
    }
}

#[no_mangle]
pub unsafe extern "C" fn x64_phys_resolve(low: u32, high: u32) -> f64 {
    resolve_backing((high as u64) << 32 | low as u64).map_or(-1.0, |value| value as f64)
}

#[no_mangle]
pub unsafe extern "C" fn x64_phys_probe(low: u32, high: u32, size: u32) -> bool {
    probe((high as u64) << 32 | low as u64, size as usize).is_ok()
}

/// Host configuration only, while the CPU is stopped at a machine safe point.
/// kind: 0 removes a window, 1 relocates RAM, 2 aliases a device decode.
#[no_mangle]
pub unsafe extern "C" fn x64_phys_set_window(
    slot: u32,
    low: u32,
    high: u32,
    backing: u32,
    length: u32,
    kind: u32,
) -> bool {
    let window = match kind {
        0 => None,
        1 | 2 => Some(Window {
            guest_base: PhysicalAddress((high as u64) << 32 | low as u64),
            backing,
            length,
            kind: if kind == 1 { WindowKind::Ram } else { WindowKind::Mmio },
        }),
        _ => return false,
    };
    set_window(slot as usize, window).is_ok()
}

/// Fields: guest low, guest high, backing, length, kind (0/1/2).
/// Invalid slot/field returns -1; an empty slot has five zero fields.
#[no_mangle]
pub unsafe extern "C" fn x64_phys_get_window(slot: u32, field: u32) -> f64 {
    if slot as usize >= MAX_WINDOWS || field > 4 {
        return -1.0;
    }
    let Some(window) = PHYSICAL_BUS.windows[slot as usize]
    else {
        return 0.0;
    };
    match field {
        0 => window.guest_base.0 as u32 as f64,
        1 => (window.guest_base.0 >> 32) as f64,
        2 => window.backing as f64,
        3 => window.length as f64,
        4 => {
            if window.kind == WindowKind::Ram {
                1.0
            }
            else {
                2.0
            }
        },
        _ => unreachable!(),
    }
}

#[no_mangle]
pub unsafe extern "C" fn x64_phys_generation(high: bool) -> u32 {
    if high {
        (generation() >> 32) as u32
    }
    else {
        generation() as u32
    }
}

/// Restore all windows in one transaction. `data` must be a host-owned,
/// 4-byte-aligned wasm allocation containing exactly 16 records of 5 u32s:
/// [guest_low, guest_high, backing, length, kind]. The host can use v86_malloc
/// and v86_free for this 320-byte transfer; no guest-memory pointer is accepted
/// by a device path. Kind 0 ignores the other four fields. Invalid contents
/// leave every live mapping and its generation unchanged.
unsafe fn window_records(data: u32, dwords: u32) -> Option<[Option<Window>; MAX_WINDOWS]> {
    if data == 0 || data & 3 != 0 || dwords as usize != MAX_WINDOWS * 5 {
        return None;
    }
    let records = std::slice::from_raw_parts(data as *const u32, MAX_WINDOWS * 5);
    let mut windows = [None; MAX_WINDOWS];
    for (slot, record) in records.chunks_exact(5).enumerate() {
        windows[slot] = match record[4] {
            0 => None,
            1 | 2 => Some(Window {
                guest_base: PhysicalAddress((record[1] as u64) << 32 | record[0] as u64),
                backing: record[2],
                length: record[3],
                kind: if record[4] == 1 { WindowKind::Ram } else { WindowKind::Mmio },
            }),
            _ => return None,
        };
    }
    Some(windows)
}

fn validated_windows(
    windows: [Option<Window>; MAX_WINDOWS],
    ram_size: u32,
) -> Result<PhysicalBus, PhysicalError> {
    let mut candidate = PhysicalBus::new();
    for (slot, window) in windows.into_iter().enumerate() {
        candidate.replace(slot, window, ram_size)?;
    }
    Ok(candidate)
}

/// Parse and validate portable window records without invalidation, generation
/// changes, or other mutation of the running machine.
#[no_mangle]
pub unsafe extern "C" fn x64_phys_validate_windows(data: u32, dwords: u32) -> bool {
    window_records(data, dwords)
        .is_some_and(|windows| validated_windows(windows, *global_pointers::memory_size).is_ok())
}

#[no_mangle]
pub unsafe extern "C" fn x64_phys_restore_windows(data: u32, dwords: u32) -> bool {
    window_records(data, dwords).is_some_and(|windows| restore_windows(windows).is_ok())
}

// f64 keeps every unsigned DWORD exact and reserves -1 for an address error.
// JS can reject invalid guest DMA without confusing it with 0xFFFF_FFFF data.
macro_rules! physical_exports {
    ($read_export:ident, $write_export:ident, $read:ident, $write:ident, $value:ty) => {
        #[no_mangle]
        pub unsafe extern "C" fn $read_export(low: u32, high: u32) -> f64 {
            $read((high as u64) << 32 | low as u64).map_or(-1.0, |value| value as f64)
        }

        #[no_mangle]
        pub unsafe extern "C" fn $write_export(low: u32, high: u32, value: u32) -> bool {
            $write((high as u64) << 32 | low as u64, value as $value).is_ok()
        }
    };
}

physical_exports!(x64_phys_read8, x64_phys_write8, read8, write8, u8);
physical_exports!(x64_phys_read16, x64_phys_write16, read16, write16, u16);
physical_exports!(x64_phys_read32, x64_phys_write32, read32, write32, u32);

/// A page-bounded RAM witness, never an MMIO view or a raw host pointer.
pub unsafe fn ram_page(address: u64) -> Result<RamPage, PhysicalError> {
    if address & PAGE_MASK == 0 && plain_ram(address, 0x1000) {
        return Ok(RamPage {
            guest: PhysicalAddress(address),
            backing: address as u32,
            generation: generation(),
        });
    }
    // (extended RAM is never plain RAM: no window search needed to say so)
    if super::extended::contains(address) {
        return Err(PhysicalError::SideEffecting);
    }
    (&*(&raw const PHYSICAL_BUS)).ram_page(address, *global_pointers::memory_size)
}

/// Replace/remove one high mapping. Caller must be outside any CPU frame,
/// including interpreted I/O callbacks. Active JIT frames are rejected too.
pub unsafe fn set_window(slot: usize, window: Option<Window>) -> Result<(), PhysicalError> {
    if crate::x64::pages::in_activation() {
        return Err(PhysicalError::Busy);
    }
    let changed =
        (&mut *(&raw mut PHYSICAL_BUS)).replace(slot, window, *global_pointers::memory_size)?;
    if changed {
        invalidate_mapping();
    }
    Ok(())
}

/// Validate all restored mappings before replacing any live state. The local
/// generation advances instead of trusting a serialized host-cache epoch.
pub unsafe fn restore_windows(windows: [Option<Window>; MAX_WINDOWS]) -> Result<(), PhysicalError> {
    if crate::x64::pages::in_activation() {
        return Err(PhysicalError::Busy);
    }
    let mut candidate = validated_windows(windows, *global_pointers::memory_size)?;
    candidate.generation = PHYSICAL_BUS
        .generation
        .checked_add(1)
        .ok_or(PhysicalError::GenerationExhausted)?;
    PHYSICAL_BUS = candidate;
    invalidate_mapping();
    Ok(())
}

/// The chipset changed what the low bus decodes (TSEG, crate::cpu::smm)
/// while cores may run: a new generation for cached RAM views, the fast RAM
/// limit and this instance's translations (cores in workers take the change
/// over at their next slice: crate::cpu::smm::sync_worker). Compiled code
/// stays; what it reads and writes goes through the translations.
pub unsafe fn memory_map_changed() {
    let bus = &mut *(&raw mut PHYSICAL_BUS);
    bus.generation = bus
        .generation
        .checked_add(1)
        .expect("physical bus generation");
    memory::ram_fast_limit = fast_limit();
    context::invalidate_all_tlbs();
}

/// The first relocated low RAM byte, or the first byte of TSEG (at the top of
/// low RAM), or the end of RAM
unsafe fn fast_limit() -> u32 {
    (&*(&raw const PHYSICAL_BUS))
        .windows
        .iter()
        .flatten()
        .filter(|window| window.kind == WindowKind::Ram)
        .map(|window| window.backing)
        .min()
        .unwrap_or(*global_pointers::memory_size)
        .min(*global_pointers::memory_size)
        .min(crate::cpu::smm::tseg_floor())
}

unsafe fn invalidate_mapping() {
    memory::ram_fast_limit = fast_limit();
    context::invalidate_all_tlbs();
    crate::jit::jit_clear_cache_js();
}

unsafe fn read_allowed(address: u64, width: usize, allow_mmio: bool) -> Result<u64, PhysicalError> {
    if plain_ram(address, width) {
        return Ok(read_ram(address as u32, width));
    }
    // extended RAM does not overlap any window (see PhysicalBus::validate)
    if super::extended::contains(address) && same_page(address, width) {
        return Ok(super::extended::read(address, width));
    }
    let bytes =
        (&*(&raw const PHYSICAL_BUS)).access(address, width, *global_pointers::memory_size)?;
    if !allow_mmio
        && bytes[..width]
            .iter()
            .any(|byte| byte.kind == WindowKind::Mmio)
    {
        return Err(PhysicalError::SideEffecting);
    }
    if bytes[..width]
        .iter()
        .all(|byte| byte.kind == WindowKind::Extended)
        && same_page(address, width)
    {
        return Ok(super::extended::read(address, width));
    }
    if contiguous(&bytes[..width]) {
        let address = bytes[0].backing;
        if bytes[0].kind == WindowKind::Ram {
            return Ok(read_ram(address, width));
        }
        return Ok(match width {
            1 => memory::read8(address) as u8 as u64,
            2 => memory::read16(address) as u16 as u64,
            4 => memory::read32s(address) as u32 as u64,
            8 => memory::read64s(address) as u64,
            _ => unreachable!(),
        });
    }
    let mut value = 0;
    for (offset, byte) in bytes.iter().enumerate().take(width) {
        let part = match byte.kind {
            WindowKind::Ram => memory::read8_no_mmap_check(byte.backing),
            WindowKind::Mmio => memory::read8(byte.backing),
            WindowKind::Extended => super::extended::read(address + offset as u64, 1) as i32,
        };
        value |= (part as u8 as u64) << (offset * 8);
    }
    Ok(value)
}

fn same_page(address: u64, width: usize) -> bool { address % 4096 + width as u64 <= 4096 }

#[inline(always)]
unsafe fn read_ram(address: u32, width: usize) -> u64 {
    match width {
        1 => memory::read8_no_mmap_check(address) as u8 as u64,
        2 => memory::read16_no_mmap_check(address) as u16 as u64,
        4 => memory::read32_no_mmap_check(address) as u32 as u64,
        // (one access: aligned 8-byte loads are single-copy atomic on x86)
        8 => memory::read64_no_mmap_check(address),
        _ => unreachable!(),
    }
}

#[inline(always)]
unsafe fn write_ram(address: u32, width: usize, value: u64) {
    // Long-mode writes only notify pages with compiled code: the 32-bit IR
    // cannot run meanwhile and validates its snapshots' bytes on publication.
    let last = address.wrapping_add(width as u32 - 1);
    if !crate::jit::page_watched(address >> 12) && !crate::jit::page_watched(last >> 12) {
        match width {
            1 => memory::write8_no_mmap_or_dirty_check(address, value as u8 as i32),
            2 => memory::write16_no_mmap_or_dirty_check(address, value as u16 as i32),
            4 => memory::write32_no_mmap_or_dirty_check(address, value as i32),
            _ => memory::write64_no_mmap_or_dirty_check(address, value),
        }
        return;
    }
    match width {
        1 => memory::write8_ram(address, value as u8 as i32),
        2 => memory::write16_ram(address, value as u16 as i32),
        4 => memory::write32_ram(address, value as i32),
        8 => {
            crate::jit::jit_dirty_bytes_small(address, address + 8);
            memory::write64_no_mmap_or_dirty_check(address, value);
        },
        _ => unreachable!(),
    }
}

/// Set accessed/dirty bits of a long-mode paging entry with a locked OR
/// (another core may change the entry concurrently); `bits` within 0x60
unsafe fn set_entry_bits(address: u64, bits: u64) -> Result<(), PhysicalError> {
    if plain_ram(address, 8) && address & 7 == 0 {
        crate::jit::jit_dirty_cache_small(address as u32, address as u32 + 8);
        crate::parallel::or64(memory::mem8.add(address as usize), bits);
        return Ok(());
    }
    if super::extended::contains(address) && address & 7 == 0 {
        super::extended::or64(address, bits);
        return Ok(());
    }
    let value = read_allowed(address, 8, true)?;
    write(address, 8, value | bits)
}

unsafe fn write(address: u64, width: usize, value: u64) -> Result<(), PhysicalError> {
    if plain_ram(address, width) {
        write_ram(address as u32, width, value);
        return Ok(());
    }
    if super::extended::contains(address) && same_page(address, width) {
        super::extended::write(address, width, value);
        return Ok(());
    }
    let bytes =
        (&*(&raw const PHYSICAL_BUS)).access(address, width, *global_pointers::memory_size)?;
    if bytes[..width]
        .iter()
        .all(|byte| byte.kind == WindowKind::Extended)
        && same_page(address, width)
    {
        super::extended::write(address, width, value);
        return Ok(());
    }
    if contiguous(&bytes[..width]) {
        let address = bytes[0].backing;
        if bytes[0].kind == WindowKind::Ram {
            write_ram(address, width, value);
            return Ok(());
        }
        match width {
            1 => memory::write8(address, value as u8 as i32),
            2 => memory::write16(address, value as u16 as i32),
            4 => memory::write32(address, value as i32),
            8 => {
                // Preserve the existing shared CPU/DMA/debug code-write
                // barrier on both touched backing pages. MMIO also uses two
                // 32-bit transactions, including Rust-owned LAPIC/IOAPIC.
                memory::write32(address, value as i32);
                memory::write32(address + 4, (value >> 32) as i32);
            },
            _ => unreachable!(),
        }
    }
    else {
        for (offset, byte) in bytes.iter().enumerate().take(width) {
            let part = (value >> (offset * 8)) as u8 as i32;
            match byte.kind {
                WindowKind::Ram => memory::write8_ram(byte.backing, part),
                WindowKind::Mmio => memory::write8(byte.backing, part),
                WindowKind::Extended => {
                    super::extended::write(address + offset as u64, 1, part as u64)
                },
            }
        }
    }
    Ok(())
}

pub unsafe fn read8(address: u64) -> Result<u8, PhysicalError> {
    read_allowed(address, 1, true).map(|v| v as u8)
}
pub unsafe fn read16(address: u64) -> Result<u16, PhysicalError> {
    read_allowed(address, 2, true).map(|v| v as u16)
}
pub unsafe fn read32(address: u64) -> Result<u32, PhysicalError> {
    read_allowed(address, 4, true).map(|v| v as u32)
}
pub unsafe fn read64(address: u64) -> Result<u64, PhysicalError> { read_allowed(address, 8, true) }
/// Compiler inspection rejects an access touching any device byte before
/// invoking the backing bus; it neither updates A/D nor delivers a fault.
pub unsafe fn peek64(address: u64) -> Result<u64, PhysicalError> { read_allowed(address, 8, false) }
pub unsafe fn write8(address: u64, value: u8) -> Result<(), PhysicalError> {
    write(address, 1, value as u64)
}
pub unsafe fn write16(address: u64, value: u16) -> Result<(), PhysicalError> {
    write(address, 2, value as u64)
}
pub unsafe fn write32(address: u64, value: u32) -> Result<(), PhysicalError> {
    write(address, 4, value as u64)
}
pub unsafe fn write64(address: u64, value: u64) -> Result<(), PhysicalError> {
    write(address, 8, value)
}

/// Execution and compiler walks use the same full-width address resolution.
pub struct PageTables;
impl crate::x64::paging::PageTableMemory for PageTables {
    fn read_entry(
        &mut self,
        address: PhysicalAddress,
        mode: crate::x64::paging::WalkMode,
    ) -> Option<u64> {
        unsafe {
            match mode {
                crate::x64::paging::WalkMode::Runtime => read64(address.0),
                crate::x64::paging::WalkMode::Snapshot => peek64(address.0),
            }
            .ok()
        }
    }
    /// The walker only sets A (0x20) and D (0x40)
    fn write_entry(&mut self, address: PhysicalAddress, value: u64) -> bool {
        unsafe { set_entry_bits(address.0, value & 0x60).is_ok() }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    const RAM: u32 = 16 << 20;
    fn ram(guest_base: u64, backing: u32, length: u32) -> Window {
        Window {
            guest_base: PhysicalAddress(guest_base),
            backing,
            length,
            kind: WindowKind::Ram,
        }
    }

    #[test]
    fn high_ram_is_relocated_without_low_dword_aliasing() {
        let mut bus = PhysicalBus::new();
        bus.replace(
            0,
            Some(ram(HIGH_MEMORY_BASE + 0x1000, 0x800000, 0x2000)),
            RAM,
        )
        .unwrap();
        assert_eq!(
            bus.resolve(HIGH_MEMORY_BASE + 0x1234, RAM).unwrap().backing,
            0x800234
        );
        assert_eq!(bus.resolve(0x1234, RAM).unwrap().backing, 0x1234);
        assert_eq!(bus.resolve(0x800234, RAM), Err(PhysicalError::Unmapped));
        assert_eq!(
            bus.resolve(HIGH_MEMORY_BASE + 0x3000, RAM),
            Err(PhysicalError::Unmapped)
        );
        bus.replace(0, None, RAM).unwrap();
        assert_eq!(bus.resolve(0x800234, RAM).unwrap().backing, 0x800234);
    }

    #[test]
    fn full_access_obeys_the_36_bit_limit_and_does_not_wrap() {
        assert_eq!(checked_range(PHYSICAL_LIMIT - 8, 8), Ok(()));
        for (address, length) in [
            (PHYSICAL_LIMIT - 7, 8),
            (PHYSICAL_LIMIT, 1),
            (u64::MAX, 2),
            (0, 0),
        ] {
            assert_eq!(
                checked_range(address, length),
                Err(PhysicalError::AddressWidth)
            );
        }
        let mut bus = PhysicalBus::new();
        bus.replace(0, Some(ram(PHYSICAL_LIMIT - 0x1000, 0x800000, 0x1000)), RAM)
            .unwrap();
        assert_eq!(
            bus.access(PHYSICAL_LIMIT - 8, 8, RAM).unwrap()[7].backing,
            0x800FFF
        );
        assert_eq!(
            bus.access(PHYSICAL_LIMIT - 7, 8, RAM),
            Err(PhysicalError::AddressWidth)
        );
    }

    #[test]
    fn crossing_four_gib_resolves_both_sides_before_backing_access() {
        let mut bus = PhysicalBus::new();
        assert_eq!(
            bus.access(HIGH_MEMORY_BASE - 4, 8, RAM),
            Err(PhysicalError::Unmapped)
        );
        bus.replace(0, Some(ram(HIGH_MEMORY_BASE, 0x800000, 0x1000)), RAM)
            .unwrap();
        let access = bus.access(HIGH_MEMORY_BASE - 4, 8, RAM).unwrap();
        assert_eq!(access[3].backing, u32::MAX);
        assert_eq!(access[4].backing, 0x800000);
        assert!(!contiguous(&access));
    }

    #[test]
    fn split_windows_and_low_ram_mmio_edges_disable_wide_fast_access() {
        let mut bus = PhysicalBus::new();
        bus.replace(0, Some(ram(HIGH_MEMORY_BASE, 0x800000, 0x1000)), RAM)
            .unwrap();
        assert_eq!(
            bus.access(HIGH_MEMORY_BASE + 0xFFD, 8, RAM),
            Err(PhysicalError::Unmapped)
        );
        bus.replace(
            1,
            Some(ram(HIGH_MEMORY_BASE + 0x1000, 0x900000, 0x1000)),
            RAM,
        )
        .unwrap();
        let access = bus.access(HIGH_MEMORY_BASE + 0xFFD, 8, RAM).unwrap();
        assert_eq!(access[2].backing, 0x800FFF);
        assert_eq!(access[3].backing, 0x900000);
        assert!(!contiguous(&access));
        assert!(!contiguous(&bus.access(0x9FFFE, 4, RAM).unwrap()[..4]));
        assert!(!contiguous(
            &bus.access(RAM as u64 - 2, 4, RAM).unwrap()[..4]
        ));
    }

    #[test]
    fn mmio_aliases_are_explicit_and_preserve_a_contiguous_register_access() {
        let mut bus = PhysicalBus::new();
        let window = Window {
            guest_base: PhysicalAddress(HIGH_MEMORY_BASE + 0x10000),
            backing: 0xFEE00000,
            length: 0x1000,
            kind: WindowKind::Mmio,
        };
        bus.replace(0, Some(window), RAM).unwrap();
        let access = bus.access(window.guest_base.0 + 0xF0, 4, RAM).unwrap();
        assert_eq!(
            access[0],
            Resolved {
                backing: 0xFEE000F0,
                kind: WindowKind::Mmio
            }
        );
        assert!(contiguous(&access[..4]));
        assert_eq!(bus.resolve(0xFEE000F0, RAM).unwrap(), access[0]);
    }

    #[test]
    fn mapping_validation_rejects_invalid_backing_overlap_and_alignment_atomically() {
        let mut bus = PhysicalBus::new();
        let first = ram(HIGH_MEMORY_BASE, 0x800000, 0x2000);
        bus.replace(0, Some(first), RAM).unwrap();
        let before = bus.generation;
        for invalid in [
            ram(HIGH_MEMORY_BASE + 1, 0x900000, 0x1000),
            ram(HIGH_MEMORY_BASE + 0x4000, RAM, 0x1000),
            ram(HIGH_MEMORY_BASE + 0x4000, 0x9F000, 0x2000),
            ram(HIGH_MEMORY_BASE + 0x4000, 0x900000, 0),
        ] {
            assert_eq!(
                bus.replace(1, Some(invalid), RAM),
                Err(PhysicalError::InvalidWindow)
            );
            assert_eq!(bus.generation, before);
        }
        assert_eq!(
            bus.replace(
                1,
                Some(ram(HIGH_MEMORY_BASE + 0x1000, 0x900000, 0x1000)),
                RAM
            ),
            Err(PhysicalError::Overlap)
        );
        assert_eq!(
            bus.replace(
                1,
                Some(ram(HIGH_MEMORY_BASE + 0x4000, 0x801000, 0x1000)),
                RAM
            ),
            Err(PhysicalError::Overlap)
        );
        assert_eq!(bus.windows[0], Some(first));
        assert_eq!(bus.windows[1], None);
    }

    #[test]
    fn epochs_advance_only_on_changes_and_never_reuse_an_exhausted_generation() {
        let mut bus = PhysicalBus::new();
        let window = Some(ram(HIGH_MEMORY_BASE, 0x800000, 0x1000));
        assert_eq!(bus.replace(0, window, RAM), Ok(true));
        assert_eq!(bus.generation, 2);
        assert_eq!(bus.replace(0, window, RAM), Ok(false));
        assert_eq!(bus.generation, 2);
        bus.generation = u64::MAX;
        assert_eq!(
            bus.replace(0, None, RAM),
            Err(PhysicalError::GenerationExhausted)
        );
        assert_eq!(bus.windows[0], window);
    }

    #[test]
    fn vector_probe_checks_a_missing_second_half_and_allows_separate_windows() {
        let mut bus = PhysicalBus::new();
        bus.replace(0, Some(ram(HIGH_MEMORY_BASE, 0x800000, 0x1000)), RAM)
            .unwrap();
        assert_eq!(bus.probe(HIGH_MEMORY_BASE + 0xFF8, 8, RAM), Ok(()));
        assert_eq!(
            bus.probe(HIGH_MEMORY_BASE + 0xFF8, 16, RAM),
            Err(PhysicalError::Unmapped)
        );
        bus.replace(
            1,
            Some(ram(HIGH_MEMORY_BASE + 0x1000, 0x900000, 0x1000)),
            RAM,
        )
        .unwrap();
        assert_eq!(bus.probe(HIGH_MEMORY_BASE + 0xFF8, 16, RAM), Ok(()));
        assert_eq!(
            bus.probe(PHYSICAL_LIMIT - 8, 16, RAM),
            Err(PhysicalError::AddressWidth)
        );
    }

    #[test]
    fn ram_witness_preserves_full_identity_and_changes_epoch_with_backing() {
        let mut bus = PhysicalBus::new();
        bus.replace(0, Some(ram(HIGH_MEMORY_BASE, 0x800000, 0x1000)), RAM)
            .unwrap();
        let first = bus.ram_page(HIGH_MEMORY_BASE, RAM).unwrap();
        assert_eq!(first.guest, PhysicalAddress(HIGH_MEMORY_BASE));
        assert_eq!(first.backing, 0x800000);
        assert_eq!(
            bus.ram_page(0xA0000, RAM),
            Err(PhysicalError::SideEffecting)
        );
        assert_eq!(
            bus.ram_page(0xFEE00000, RAM),
            Err(PhysicalError::SideEffecting)
        );
        bus.replace(0, Some(ram(HIGH_MEMORY_BASE, 0x900000, 0x1000)), RAM)
            .unwrap();
        let second = bus.ram_page(HIGH_MEMORY_BASE, RAM).unwrap();
        assert_eq!(second.guest, first.guest);
        assert_eq!(second.backing, 0x900000);
        assert!(second.generation > first.generation);
    }
}
                                                                                                  source/v64/src/rust/x64/profile.rs                                                                  0000644 0000000 0000000 00000002573 00000000000 014106  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Diagnostic instruction-count sampling for the wide interpreter: every
//! `period`-th executed instruction records its full RIP and core. Unlike
//! host-side polling, samples are not biased toward slice or IRQ boundaries.
static mut PERIOD: u32 = 0;
static mut COUNTDOWN: u32 = 0;
static mut SAMPLES: Vec<(u64, u8)> = Vec::new();
const LIMIT: usize = 1 << 20;

#[inline(always)]
pub unsafe fn tick(rip: u64) {
    if PERIOD == 0 {
        return;
    }
    COUNTDOWN -= 1;
    if COUNTDOWN == 0 {
        COUNTDOWN = PERIOD;
        let samples = &mut *(&raw mut SAMPLES);
        if samples.len() < LIMIT {
            samples.push((rip, crate::cpu::apic::current_core() as u8));
        }
    }
}

/// period 0 stops sampling; any other value clears and restarts it.
#[no_mangle]
pub unsafe fn x64_profile_start(period: u32) {
    PERIOD = period;
    COUNTDOWN = period;
    if period != 0 {
        (&mut *(&raw mut SAMPLES)).clear();
    }
}
#[no_mangle]
pub unsafe fn x64_profile_count() -> u32 { (&*(&raw const SAMPLES)).len() as u32 }
/// field 0: RIP low DWORD, 1: RIP high DWORD, 2: core.
#[no_mangle]
pub unsafe fn x64_profile_sample(index: u32, field: u32) -> u32 {
    let Some(&(rip, core)) = (&*(&raw const SAMPLES)).get(index as usize)
    else {
        return 0;
    };
    match field {
        0 => rip as u32,
        1 => (rip >> 32) as u32,
        _ => core as u32,
    }
}
                                                                                                                                     source/v64/src/rust/x64/replay.rs                                                                   0000644 0000000 0000000 00000034170 00000000000 013740  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Record and replay of x64 page tier compilations
//! (docs/jit-unification-plan.md P2.0, cross-phase rule 4), in test builds
//! (ir-test-hooks), as ir::tier0::replay for Tier-0: a record holds every
//! input of pagegen::compile_with but the addresses, which replay pins
//! (pagegen::CompileEnv::replay). tools/replay_check.mjs compares a base
//! build's bytes with the working tree's.
//!
//! A record, little-endian: "X6R1"; flags (bit 0: the recording build's
//! parallel memory, then bucket dispatch, block counts, outlined accesses,
//! chaining, relaxed FMA, the conversion templates, the STI shadow); the
//! entries (count u16, then each offset u16, bit 15 a guess:
//! pagegen::GUESSED); the next page's first bytes
//! (count u16, then them); the page (4096 bytes); the function's name
//! (length u16, then it); a trailer that older records lack (u8: the
//! execution counter, loops, XMM locals, the fast SSE checks, 32-bit
//! operations in i32, the fast lookups, the chained GPRs, EFLAGS by what
//! observes them; u16: the access cache's entries; u8: the code's mode, 1
//! for 32-bit compatibility mode, bit 1 its lookups in the 32-bit TLB, then
//! what its bits say follows: a span's or volatile instructions' hosts,
//! the volatile offsets, 16-bit code's IP base, P7.7).

use super::pagegen::{compile_with, CompileEnv};
use crate::wasmgen::wasm_builder::WasmBuilder;

const MAGIC: &[u8; 4] = b"X6R1";

static mut RECORDS: Option<Vec<Vec<u8>>> = None;
/// What each recorded compilation made, as it ran (its own addresses, not
/// replay's pinned ones; empty for a failed one): tools/page_profile.mjs
/// maps profiler ticks onto it
static mut OUTPUTS: Option<Vec<Vec<u8>>> = None;
static mut INPUT: Vec<u8> = Vec::new();
static mut OUTPUT: Vec<u8> = Vec::new();

fn encode(env: &CompileEnv, bytes: &[u8], next: &[u8], entries: &[u16], name: &str) -> Vec<u8> {
    let mut r = Vec::with_capacity(4200);
    r.extend_from_slice(MAGIC);
    r.push(
        WasmBuilder::ATOMIC_GUEST_MEMORY as u8
            | (env.bucket_dispatch as u8) << 1
            | (env.block_count as u8) << 2
            | (env.outline as u8) << 3
            | (env.chaining as u8) << 4
            | (env.relaxed_fma as u8) << 5
            | (env.cvt as u8) << 6
            | (env.sti_shadow as u8) << 7,
    );
    r.extend_from_slice(&(entries.len() as u16).to_le_bytes());
    for &e in entries {
        r.extend_from_slice(&e.to_le_bytes());
    }
    r.extend_from_slice(&(next.len() as u16).to_le_bytes());
    r.extend_from_slice(next);
    // (a span's first page here, the others after its trailer: P7.3b)
    r.extend_from_slice(&bytes[..4096]);
    r.extend_from_slice(&(name.len() as u16).to_le_bytes());
    r.extend_from_slice(name.as_bytes());
    // (a trailer, absent from older records: the execution counter, P4.14;
    // loops, P4.16; XMM locals, P4.17; the fast SSE checks, P4.18; 32-bit
    // operations in i32, P4.20; the fast lookups, P4.21; the chained
    // GPRs, P4.22; EFLAGS by what observes them, P4.23; the access cache's
    // entries, P4.15)
    r.push(
        env.counter.is_some() as u8
            | (env.loops as u8) << 1
            | (env.xmm_locals as u8) << 2
            | (env.sse_fast_check as u8) << 3
            | (env.i32_ops as u8) << 4
            | (env.fast_lookup as u8) << 5
            | (env.fast_chain as u8) << 6
            | (env.exit_flags as u8) << 7,
    );
    r.extend_from_slice(&(env.jac_entries as u16).to_le_bytes());
    // (P7.2: the code's mode, absent from older records; bit 1: its
    // lookups in the 32-bit TLB, x64_compat_tlb; bit 2: legacy mode, P7.3;
    // bit 3: segment bases, P7.2(3))
    // bit 4: a span, P7.3b, or volatile instructions: then its page count
    // and pages' hosts; bit 5: volatile instructions, P7.3: their count and
    // offsets)
    let volatile: Vec<u16> = env
        .volatile
        .iter()
        .copied()
        .filter(|&o| o != u16::MAX)
        .collect();
    let hosts = env.span > 1 || !volatile.is_empty();
    // (bit 6: 16-bit code, P7.7: then its IP base, i32, and its mode, a
    // byte: 0 protected, 1 real, 2 virtual-8086 mode, P7.8, last; bit 7: a
    // stack of the other width, M11)
    r.push(
        env.compat as u8
            | (env.compat_tlb as u8) << 1
            | (env.legacy as u8) << 2
            | (env.segmented as u8) << 3
            | (hosts as u8) << 4
            | (!volatile.is_empty() as u8) << 5
            | (env.prot16 as u8) << 6
            | ((env.stack16 != env.prot16) as u8) << 7,
    );
    if hosts {
        r.push(env.span);
        for host in &env.span_hosts[..env.span as usize] {
            r.extend_from_slice(&host.to_le_bytes());
        }
        r.extend_from_slice(&bytes[4096..]);
    }
    if !volatile.is_empty() {
        r.push(volatile.len() as u8);
        for offset in volatile {
            r.extend_from_slice(&offset.to_le_bytes());
        }
    }
    if env.prot16 {
        r.extend_from_slice(&env.ip_base.to_le_bytes());
        r.push(env.mode16 as u8);
    }
    r
}

struct Reader<'a>(&'a [u8]);
impl Reader<'_> {
    fn bytes(&mut self, n: usize) -> Option<&[u8]> {
        let (head, rest) = (self.0.get(..n)?, self.0.get(n..)?);
        self.0 = rest;
        Some(head)
    }
    fn u16(&mut self) -> Option<u16> { Some(u16::from_le_bytes(self.bytes(2)?.try_into().ok()?)) }
}

/// The page function's bytes for a record under CompileEnv::replay, or None
pub fn replay(record: &[u8]) -> Option<Vec<u8>> {
    let mut r = Reader(record);
    if r.bytes(4)? != MAGIC {
        return None;
    }
    let flags = r.bytes(1)?[0];
    if flags & 1 != WasmBuilder::ATOMIC_GUEST_MEMORY as u8 {
        return None;
    }
    let bit = |n: u8| flags & 1 << n != 0;
    let mut entries = Vec::new();
    for _ in 0..r.u16()? {
        entries.push(r.u16()?);
    }
    let count = r.u16()? as usize;
    let next = r.bytes(count)?.to_vec();
    let mut bytes = r.bytes(4096)?.to_vec();
    let count = r.u16()? as usize;
    let name = String::from_utf8(r.bytes(count)?.to_vec()).ok()?;
    let trailer = r.bytes(1).map_or(0, |b| b[0]);
    let (counting, loops, xmm_locals, sse_fast_check, i32_ops, fast_lookup, fast_chain) = (
        trailer & 1 != 0,
        trailer & 2 != 0,
        trailer & 4 != 0,
        trailer & 8 != 0,
        trailer & 16 != 0,
        trailer & 32 != 0,
        trailer & 64 != 0,
    );
    let exit_flags = trailer & 128 != 0;
    let jac_entries = r.u16().map_or(1024, u32::from);
    let mode = r.bytes(1).map_or(0, |b| b[0]);
    let (compat, compat_tlb, legacy, segmented) =
        (mode & 1 != 0, mode & 2 != 0, mode & 4 != 0, mode & 8 != 0);
    let mut hosts = Vec::new();
    if mode & 16 != 0 {
        let span = r.bytes(1)?[0] as usize;
        for _ in 0..span {
            hosts.push(u32::from_le_bytes(r.bytes(4)?.try_into().ok()?));
        }
        bytes.extend_from_slice(r.bytes(4096 * (span - 1))?);
    }
    let mut volatile = [u16::MAX; super::pagegen::MAX_VOLATILE];
    if mode & 32 != 0 {
        let count = r.bytes(1)?[0] as usize;
        for v in volatile.iter_mut().take(count) {
            *v = u16::from_le_bytes(r.bytes(2)?.try_into().ok()?);
        }
    }
    let prot16 = if mode & 64 != 0 {
        let ip_base = i32::from_le_bytes(r.bytes(4)?.try_into().ok()?);
        let mode16 = match r.bytes(1)?[0] {
            0 => super::pagegen::Mode16::Protected,
            1 => super::pagegen::Mode16::Real,
            2 => super::pagegen::Mode16::V86,
            _ => return None,
        };
        Some((ip_base, mode16))
    }
    else {
        None
    };
    let mut env = CompileEnv::replay(
        bit(1),
        bit(2),
        bit(3),
        bit(4),
        bit(5),
        bit(6),
        bit(7),
        counting,
        jac_entries,
        loops,
        xmm_locals,
        sse_fast_check,
        i32_ops,
        fast_lookup,
        fast_chain,
        exit_flags,
        compat,
        compat_tlb,
        legacy,
        segmented,
        prot16,
        // (bit 7: the stack's width is not the code's)
        prot16.is_some() != (mode & 128 != 0),
        &hosts,
    );
    env.volatile = volatile;
    compile_with(&env, &bytes, &next, &entries, name).map(|compiled| compiled.bytes)
}

/// pagegen::compile's inputs into the recording, when recording
pub fn record(env: &CompileEnv, bytes: &[u8], next: &[u8], entries: &[u16], name: &str) {
    if let Some(records) = unsafe { (*(&raw mut RECORDS)).as_mut() } {
        records.push(encode(env, bytes, next, entries, name));
    }
}
/// What the compilation just recorded made (OUTPUTS)
pub fn record_output(module: &[u8]) {
    if let Some(outputs) = unsafe { (*(&raw mut OUTPUTS)).as_mut() } {
        outputs.push(module.to_vec());
    }
}

#[no_mangle]
pub unsafe fn x64_page_record_start() {
    RECORDS = Some(Vec::new());
    OUTPUTS = Some(Vec::new());
}
#[no_mangle]
pub unsafe fn x64_page_record_stop() {
    RECORDS = None;
    OUTPUTS = None;
}
/// The module record `index`'s compilation made (OUTPUTS; not for the
/// corpus, which has no outputs): its address and length
#[no_mangle]
pub unsafe fn x64_page_record_output_address(index: u32) -> u32 {
    (*(&raw const OUTPUTS))
        .as_ref()
        .and_then(|o| o.get(index as usize))
        .map_or(0, |o| o.as_ptr() as u32)
}
#[no_mangle]
pub unsafe fn x64_page_record_output_length(index: u32) -> u32 {
    (*(&raw const OUTPUTS))
        .as_ref()
        .and_then(|o| o.get(index as usize))
        .map_or(0, |o| o.len() as u32)
}
#[no_mangle]
pub unsafe fn x64_page_record_count() -> u32 {
    (*(&raw const RECORDS))
        .as_ref()
        .map_or(0, |r| r.len() as u32)
}
#[no_mangle]
pub unsafe fn x64_page_record_address(index: u32) -> u32 {
    (*(&raw const RECORDS))
        .as_ref()
        .and_then(|r| r.get(index as usize))
        .map_or(0, |r| r.as_ptr() as u32)
}
#[no_mangle]
pub unsafe fn x64_page_record_length(index: u32) -> u32 {
    (*(&raw const RECORDS))
        .as_ref()
        .and_then(|r| r.get(index as usize))
        .map_or(0, |r| r.len() as u32)
}
/// Replace the records by the synthetic corpus: one page per form the SSE
/// templates take. Returns their number.
#[no_mangle]
pub unsafe fn x64_page_record_corpus() -> u32 {
    let records = corpus();
    let n = records.len() as u32;
    RECORDS = Some(records);
    n
}
#[no_mangle]
pub unsafe fn x64_page_replay_input(length: u32) -> u32 {
    let input = &mut *(&raw mut INPUT);
    input.clear();
    input.resize(length as usize, 0);
    input.as_ptr() as u32
}
#[no_mangle]
pub unsafe fn x64_page_replay() -> u32 {
    let output = &mut *(&raw mut OUTPUT);
    *output = replay(&*(&raw const INPUT)).unwrap_or_default();
    output.len() as u32
}
#[no_mangle]
pub unsafe fn x64_page_replay_output() -> u32 { (*(&raw const OUTPUT)).as_ptr() as u32 }

/// One record per form the SSE templates take (pagegen::sse): the
/// instruction at the start of a page, then RET. Candidates: the 0F, 0F 38
/// and 0F 3A maps with no, 66, F2 or F3 prefix and with no REX, REX.W or
/// REX.R, and the VEX maps with each pp, L and W; each opcode with a
/// register and a memory ([rcx]) operand, ModRM reg 0 and 2 (all eight for
/// opcode groups), and an immediate byte.
pub fn corpus() -> Vec<Vec<u8>> {
    // (the templates of every switch, so that their bytes are pinned)
    let env = CompileEnv::replay(
        true,
        true,
        true,
        false,
        false,
        true,
        false,
        false,
        1024,
        false,
        false,
        true,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        None,
        false,
        &[],
    );
    let mut records = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let mut take = |instruction: Vec<u8>| {
        let Some(length) = super::pagegen::sse_template(&instruction)
        else {
            return;
        };
        if !seen.insert(instruction[..length].to_vec()) {
            return;
        }
        let mut page = vec![0xCC; 4096];
        page[..length].copy_from_slice(&instruction[..length]);
        page[length] = 0xC3;
        records.push(encode(&env, &page, &[], &[0], "x64_corpus"));
    };
    let groups = |map: u8, opcode: u8, vex: bool| match (map, vex) {
        (1, _) => matches!(opcode, 0x71..=0x73 | 0xAE | 0xC7),
        (2, true) => opcode == 0xF3,
        _ => false,
    };
    for map in 1..=3u8 {
        let escape: &[u8] = match map {
            1 => &[0x0F],
            2 => &[0x0F, 0x38],
            _ => &[0x0F, 0x3A],
        };
        for prefix in [None, Some(0x66u8), Some(0xF2), Some(0xF3)] {
            for rex in [None, Some(0x48u8), Some(0x44)] {
                for opcode in 0..=255u8 {
                    let regs: &[u8] = if groups(map, opcode, false) {
                        &[0, 1, 2, 3, 4, 5, 6, 7]
                    }
                    else {
                        &[0, 2]
                    };
                    for &reg in regs {
                        for modrm in [0xC1 | reg << 3, 0x01 | reg << 3] {
                            let mut i: Vec<u8> = prefix.into_iter().chain(rex).collect();
                            i.extend_from_slice(escape);
                            i.extend_from_slice(&[opcode, modrm, 0x05, 0x90, 0x90, 0x90]);
                            take(i);
                        }
                    }
                }
            }
        }
    }
    for map in 1..=3u8 {
        for w in 0..2u8 {
            for l in 0..2u8 {
                for pp in 0..4u8 {
                    let byte1 = 0xE0 | map;
                    let byte2 = w << 7 | (!2u8 & 15) << 3 | l << 2 | pp;
                    for opcode in 0..=255u8 {
                        let regs: &[u8] = if groups(map, opcode, true) {
                            &[0, 1, 2, 3, 4, 5, 6, 7]
                        }
                        else {
                            &[0, 2]
                        };
                        for &reg in regs {
                            for modrm in [0xC1 | reg << 3, 0x01 | reg << 3] {
                                take(vec![0xC4, byte1, byte2, opcode, modrm, 0x05, 0x90, 0x90]);
                            }
                        }
                    }
                }
            }
        }
    }
    records
}
                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/x64/state.rs                                                                    0000644 0000000 0000000 00000025045 00000000000 013565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! A single architectural register file: existing legacy slots are the low
//! bank, not a second shadow copy. Wide helpers and future JIT materialization
//! address the same bytes as the existing 16/32-bit execution paths.
use crate::cpu::{cpu, global_pointers as gp};

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct GuestIp(pub u64);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct LinearAddress(pub u64);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PhysicalAddress(pub u64);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HostOffset(pub u32);

pub const EFER_SCE: u64 = 1;
pub const EFER_LME: u64 = 1 << 8;
pub const EFER_LMA: u64 = 1 << 10;
pub const EFER_NXE: u64 = 1 << 11;

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ExecutionMode {
    Real,
    Vm86,
    Protected16,
    Protected32,
    Compatibility16,
    Compatibility32,
    Long64,
}
impl ExecutionMode {
    pub fn is_long(self) -> bool { self == Self::Long64 }
    pub fn operand_default(self) -> u8 {
        if matches!(
            self,
            Self::Protected32 | Self::Compatibility32 | Self::Long64
        ) {
            32
        }
        else {
            16
        }
    }
    pub fn address_default(self) -> u8 {
        if self.is_long() {
            64
        }
        else {
            self.operand_default()
        }
    }
}

pub fn derive_mode(
    pe: bool,
    vm: bool,
    lma: bool,
    cs_long: bool,
    cs_default32: bool,
) -> ExecutionMode {
    if !pe {
        ExecutionMode::Real
    }
    else if lma {
        if cs_long {
            ExecutionMode::Long64
        }
        else if cs_default32 {
            ExecutionMode::Compatibility32
        }
        else {
            ExecutionMode::Compatibility16
        }
    }
    else if vm {
        ExecutionMode::Vm86
    }
    else if cs_default32 {
        ExecutionMode::Protected32
    }
    else {
        ExecutionMode::Protected16
    }
}

pub fn canonical(address: u64, width: u8) -> bool {
    assert!((2..64).contains(&width));
    (((address << (64 - width)) as i64) >> (64 - width)) as u64 == address
}

/// The result of a register write, shared by live accessors and pure tests.
/// Legacy/compatibility paths retain inaccessible high bits; the architectural
/// zero-extension guarantee applies to 32-bit writes in the 64-bit submode.
pub fn merge_gpr(old: u64, value: u64, width: u8, mode: ExecutionMode) -> u64 {
    match width {
        8 => old & !0xFF | value & 0xFF,
        16 => old & !0xFFFF | value & 0xFFFF,
        32 if mode.is_long() => value as u32 as u64,
        32 => old & !0xFFFF_FFFF | value as u32 as u64,
        64 => value,
        _ => panic!("invalid GPR width"),
    }
}

pub unsafe fn mode() -> ExecutionMode {
    derive_mode(
        *gp::protected_mode,
        *gp::flags & cpu::FLAG_VM != 0,
        efer() & EFER_LMA != 0,
        *gp::x64_cs_long != 0,
        *gp::is_32,
    )
}
pub unsafe fn efer() -> u64 { *gp::x64_efer }
pub unsafe fn set_efer_raw(value: u64) { *gp::x64_efer = value; }
#[inline]
pub fn gpr_low_offset(r: usize) -> u32 {
    assert!(r < 16);
    if r < 8 {
        gp::reg32 as u32 + r as u32 * 4
    }
    else {
        gp::x64_gpr_ext_lo as u32 + (r as u32 - 8) * 4
    }
}
#[inline]
pub fn gpr_high_offset(r: usize) -> u32 {
    assert!(r < 16);
    gp::x64_gpr_hi as u32 + r as u32 * 4
}
#[inline]
pub unsafe fn read_gpr(r: usize) -> u64 {
    *(gpr_low_offset(r) as *const u32) as u64 | (*(gpr_high_offset(r) as *const u32) as u64) << 32
}
#[inline]
pub unsafe fn write_gpr(r: usize, value: u64, width: u8) {
    let value = merge_gpr(read_gpr(r), value, width, mode());
    *(gpr_low_offset(r) as *mut u32) = value as u32;
    *(gpr_high_offset(r) as *mut u32) = (value >> 32) as u32;
}
pub unsafe fn read_high_byte(r: usize) -> u8 {
    assert!(r < 4);
    (read_gpr(r) >> 8) as u8
}
pub unsafe fn write_high_byte(r: usize, value: u8) {
    assert!(r < 4);
    write_gpr(r, read_gpr(r) & !0xFF00 | (value as u64) << 8, 64);
}
pub fn xmm_offset(r: usize) -> u32 {
    assert!(r < 16);
    if r < 8 {
        gp::reg_xmm as u32 + r as u32 * 16
    }
    else {
        gp::x64_xmm_ext as u32 + (r as u32 - 8) * 16
    }
}
pub unsafe fn read_xmm(r: usize) -> cpu::reg128 { *(xmm_offset(r) as *const cpu::reg128) }
pub unsafe fn write_xmm(r: usize, value: cpu::reg128) {
    *(xmm_offset(r) as *mut cpu::reg128) = value;
}

unsafe fn read_pair(lo: *const i32, hi: *const u32) -> u64 {
    *lo as u32 as u64 | (*hi as u64) << 32
}
unsafe fn write_pair(lo: *mut i32, hi: *mut u32, value: u64) {
    *lo = value as i32;
    *hi = (value >> 32) as u32;
}
pub unsafe fn read_rip() -> u64 {
    if mode().is_long() {
        read_pair(gp::instruction_pointer, gp::x64_rip_hi)
    }
    else {
        cpu::get_real_eip() as u32 as u64
    }
}
pub unsafe fn write_rip(value: u64) {
    if mode().is_long() {
        write_pair(gp::instruction_pointer, gp::x64_rip_hi, value);
    }
    else {
        let value = if *gp::is_32 { value as u32 } else { value as u16 as u32 };
        *gp::instruction_pointer = cpu::get_seg_cs().wrapping_add(value as i32);
        *gp::x64_rip_hi = 0;
    }
    *gp::last_virt_eip = -1;
}
pub unsafe fn read_previous_rip() -> u64 {
    if mode().is_long() {
        read_pair(gp::previous_ip, gp::x64_previous_ip_hi)
    }
    else {
        let offset = (*gp::previous_ip).wrapping_sub(cpu::get_seg_cs()) as u32;
        if *gp::is_32 {
            offset as u64
        }
        else {
            offset as u16 as u64
        }
    }
}
pub unsafe fn write_previous_rip(value: u64) {
    if mode().is_long() {
        write_pair(gp::previous_ip, gp::x64_previous_ip_hi, value);
    }
    else {
        *gp::previous_ip = cpu::get_seg_cs().wrapping_add(value as i32);
        *gp::x64_previous_ip_hi = 0;
    }
}
pub unsafe fn read_cr(r: usize) -> u64 {
    assert!(r <= 8);
    if r == 8 {
        // CR8 is TPR[7:4] of the local APIC, also written through its MMIO.
        (crate::cpu::apic::read32(0x80) >> 4 & 15) as u64
    }
    else {
        read_pair(gp::cr.add(r), gp::x64_cr_hi.add(r))
    }
}
pub unsafe fn write_cr_raw(r: usize, value: u64) {
    assert!(r <= 8);
    if r == 8 {
        *gp::x64_cr8 = value;
    }
    else {
        write_pair(gp::cr.add(r), gp::x64_cr_hi.add(r), value);
    }
}
pub unsafe fn read_dr(r: usize) -> u64 {
    assert!(r < 8);
    read_pair(gp::dreg.add(r), gp::x64_dr_hi.add(r))
}
pub unsafe fn write_dr(r: usize, value: u64) {
    assert!(r < 8);
    write_pair(gp::dreg.add(r), gp::x64_dr_hi.add(r), value);
}
pub unsafe fn read_segment_base(r: usize) -> u64 {
    assert!(r < 8);
    read_pair(gp::segment_offsets.add(r), gp::x64_segment_base_hi.add(r))
}
pub unsafe fn write_segment_base(r: usize, value: u64) {
    assert!(r < 8);
    write_pair(
        gp::segment_offsets.add(r),
        gp::x64_segment_base_hi.add(r),
        value,
    );
}
pub unsafe fn read_gdtr_base() -> u64 { read_pair(gp::gdtr_offset, gp::x64_gdtr_base_hi) }
pub unsafe fn write_gdtr_base(value: u64) {
    write_pair(gp::gdtr_offset, gp::x64_gdtr_base_hi, value);
}
pub unsafe fn read_idtr_base() -> u64 { read_pair(gp::idtr_offset, gp::x64_idtr_base_hi) }
pub unsafe fn write_idtr_base(value: u64) {
    write_pair(gp::idtr_offset, gp::x64_idtr_base_hi, value);
}
pub unsafe fn read_flags64() -> u64 { cpu::get_eflags() as u32 as u64 }
pub unsafe fn write_flags64(value: u64) {
    *gp::flags = value as i32 & cpu::FLAGS_MASK | cpu::FLAGS_DEFAULT;
    *gp::flags_changed = 0;
}
/// Used on machine reset/INIT and importing pre-wide snapshots. Ordinary mode
/// changes preserve banks; x64::system owns transition validation and mode
/// side effects.
pub unsafe fn reset_extension() {
    core::ptr::write_bytes(gp::x64_gpr_hi as *mut u8, 0, 1788 - 1360);
    *gp::x64_pat = 0x0007_0406_0007_0406;
    // MTRRs disabled, machine-check banks clear (an INIT keeps them: cpu.js)
    core::ptr::write_bytes(gp::x64_mtrr_def_type as *mut u8, 0, 2424 - 2056);
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn all_seven_modes_and_zero_extension() {
        let modes = [
            derive_mode(false, false, false, false, false),
            derive_mode(true, true, false, false, false),
            derive_mode(true, false, false, false, false),
            derive_mode(true, false, false, false, true),
            derive_mode(true, false, true, false, false),
            derive_mode(true, false, true, false, true),
            derive_mode(true, false, true, true, false),
        ];
        assert_eq!(
            modes,
            [
                ExecutionMode::Real,
                ExecutionMode::Vm86,
                ExecutionMode::Protected16,
                ExecutionMode::Protected32,
                ExecutionMode::Compatibility16,
                ExecutionMode::Compatibility32,
                ExecutionMode::Long64
            ]
        );
        for mode in modes {
            for old in [u64::MAX, 0x1234_5678_9ABC_DEF0, 0] {
                assert_eq!(merge_gpr(old, 0x12, 8, mode), old & !255 | 0x12);
                assert_eq!(merge_gpr(old, 0x1234, 16, mode), old & !65535 | 0x1234);
                assert_eq!(
                    merge_gpr(old, u64::MAX, 32, mode),
                    if mode.is_long() { 0xFFFF_FFFF } else { old | 0xFFFF_FFFF }
                );
                assert_eq!(
                    merge_gpr(old, 0xFEDC_BA98_7654_3210, 64, mode),
                    0xFEDC_BA98_7654_3210
                );
            }
        }
    }
    #[test]
    fn banks_are_unique_and_do_not_overlap_legacy_flags() {
        let mut bytes = std::collections::BTreeSet::new();
        for r in 0..16 {
            for base in [gpr_low_offset(r), gpr_high_offset(r)] {
                for b in base..base + 4 {
                    assert!(bytes.insert(b));
                }
            }
        }
        assert!(!bytes.contains(&96));
        assert_eq!(bytes.len(), 128);
        assert_eq!(xmm_offset(7), 944);
        assert_eq!(xmm_offset(8), 1456);
        assert_eq!(xmm_offset(15), 1568);
    }
    #[test]
    fn canonical_boundaries_keep_the_full_address() {
        for address in [0, 0x7FFF_FFFF_FFFF, 0xFFFF_8000_0000_0000, u64::MAX] {
            assert!(canonical(address, 48));
        }
        for address in [
            0x8000_0000_0000,
            0xFFFF_7FFF_FFFF_FFFF,
            0x1000_0000_0000_0000,
        ] {
            assert!(!canonical(address, 48));
        }
        assert_ne!(GuestIp(1), GuestIp(0x1_0000_0001));
        assert_ne!(PhysicalAddress(0), PhysicalAddress(0x1_0000_0000));
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/rust/x64/system.rs                                                                   0000644 0000000 0000000 00000153553 00000000000 013777  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Long-mode control state and privileged instruction semantics.
use super::state::{EFER_LMA, EFER_LME, EFER_NXE, EFER_SCE};
use super::{
    decode::Decoded,
    memory::{self, Fault},
    state,
};
use crate::cpu::{cpu, global_pointers as gp, xstate};

const PE: u64 = 1;
const PG: u64 = 1 << 31;
const PAE: u64 = 1 << 5;
const CR0_VALID: u64 = 0xE005_003F;
/// The bits of CR0 and CR4 that translations depend on: PE, WP, PG; PSE, PAE, PGE
const TRANSLATION_CR0: u64 = PE | 1 << 16 | PG;
const TRANSLATION_CR4: u64 = 1 << 4 | PAE | 1 << 7;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ControlState {
    pub cr0: u64,
    pub cr3: u64,
    pub cr4: u64,
    pub efer: u64,
    pub cs_long: bool,
}
impl ControlState {
    pub fn write_cr(&mut self, index: usize, value: u64) -> Result<(), Fault> {
        match index {
            0 => {
                if value & !CR0_VALID != 0
                    || value & PG != 0 && value & PE == 0
                    || value & (1 << 29) != 0 && value & (1 << 30) == 0
                    || self.cs_long && value & PG == 0
                {
                    return Err(Fault::gp());
                }
                if self.cr0 & PG == 0 && value & PG != 0 && self.efer & EFER_LME != 0 {
                    if self.cr4 & PAE == 0 || self.cs_long {
                        return Err(Fault::gp());
                    }
                    self.efer |= EFER_LMA;
                }
                if value & PG == 0 {
                    self.efer &= !EFER_LMA;
                }
                self.cr0 = value | 0x10;
            },
            3 => {
                if value >> 36 != 0 {
                    return Err(Fault::gp());
                }
                self.cr3 = value & !0xFE7;
            },
            4 => {
                if value & !(cpu::cr4_valid_bits() as u64) != 0
                    || self.efer & EFER_LMA != 0 && value & PAE == 0
                {
                    return Err(Fault::gp());
                }
                self.cr4 = value;
            },
            _ => return Err(Fault::ud()),
        }
        Ok(())
    }
    pub fn write_efer(&mut self, value: u64) -> Result<(), Fault> {
        if value & !(EFER_SCE | EFER_LME | EFER_LMA | EFER_NXE) != 0
            || self.cr0 & PG != 0 && (value ^ self.efer) & EFER_LME != 0
        {
            return Err(Fault::gp());
        }
        self.efer = value & !EFER_LMA | self.efer & EFER_LMA;
        Ok(())
    }
}
pub unsafe fn controls() -> ControlState {
    ControlState {
        cr0: state::read_cr(0),
        cr3: state::read_cr(3),
        cr4: state::read_cr(4),
        efer: state::efer(),
        cs_long: *gp::x64_cs_long != 0,
    }
}
pub unsafe fn write_cr(index: usize, value: u64) -> Result<(), Fault> {
    if *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    if index == 2 {
        state::write_cr_raw(2, value);
        return Ok(());
    }
    if index == 8 {
        if value & !15 != 0 {
            return Err(Fault::gp());
        }
        state::write_cr_raw(8, value);
        crate::cpu::apic::write32(0x80, (value << 4) as u32);
        return Ok(());
    }
    use crate::x64::pages::{COUNTERS, COUNT_CR0_WRITES, COUNT_CR_WRITES, COUNT_FULL_FLUSHES};
    COUNTERS[COUNT_CR_WRITES] += 1;
    // (CR0, CR3, CR4)
    let counter = match index {
        0 => COUNT_CR0_WRITES,
        3 => COUNT_CR0_WRITES + 1,
        _ => COUNT_CR0_WRITES + 2,
    };
    COUNTERS[counter] += 1;
    let old = controls();
    let mut c = controls();
    c.write_cr(index, value)?;
    if (c.cr0 ^ old.cr0) & 8 != 0 {
        crate::step_profile::note_event(crate::step_profile::event::CR0_TS, 0);
    }
    state::write_cr_raw(0, c.cr0);
    state::write_cr_raw(3, c.cr3);
    state::write_cr_raw(4, c.cr4);
    state::set_efer_raw(c.efer);
    *gp::protected_mode = c.cr0 & PE != 0;
    // MOV CR3 with CR4.PGE (and no PCID) keeps global translations
    if index == 3
        && c.cr0 == old.cr0
        && c.cr4 == old.cr4
        && c.efer == old.efer
        && c.cr4 & 0x80 != 0
        && c.cr4 & 0x20000 == 0
    {
        crate::x64::pages::COUNTERS[crate::x64::pages::COUNT_CR3_KEEP_GLOBAL] += 1;
        cpu::clear_tlb();
        memory::invalidate_core_nonglobal(crate::cpu::apic::current_core());
    }
    // CR0 and CR4 writes that change no bit translations depend on (CR0.TS,
    // for one): nothing to flush, as on hardware
    else if index != 3
        && (c.cr0 ^ old.cr0) & TRANSLATION_CR0 == 0
        && (c.cr4 ^ old.cr4) & TRANSLATION_CR4 == 0
        && c.efer == old.efer
    {
    }
    else {
        COUNTERS[COUNT_FULL_FLUSHES] += 1;
        cpu::full_clear_tlb();
        memory::invalidate_core(crate::cpu::apic::current_core());
    }
    Ok(())
}
pub unsafe fn write_msr(index: u32, value: u64) -> Result<bool, Fault> {
    if *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    match index {
        0xC0000080 => {
            let mut c = controls();
            c.write_efer(value)?;
            state::set_efer_raw(c.efer);
            memory::invalidate_core(crate::cpu::apic::current_core());
            cpu::full_clear_tlb();
        },
        0xC0000081 => *gp::x64_star = value,
        0xC0000082 | 0xC0000083 => {
            if !state::canonical(value, 48) {
                return Err(Fault::gp());
            }
            if index == 0xC0000082 {
                *gp::x64_lstar = value;
            }
            else {
                *gp::x64_cstar = value;
            } // Intel compat SYSCALL remains #UD
        },
        0xC0000084 => *gp::x64_sfmask = value as u32 as u64,
        0xC0000103 => {
            if value >> 32 != 0 {
                return Err(Fault::gp());
            }
            *gp::x64_tsc_aux = value as u32;
        },
        0xC0000100..=0xC0000102 => {
            if !state::canonical(value, 48) {
                return Err(Fault::gp());
            }
            if index == 0xC0000102 {
                *gp::x64_kernel_gs_base = value;
            }
            else {
                state::write_segment_base(if index == 0xC0000100 { 4 } else { 5 }, value);
            }
        },
        0x174 => *gp::sysenter_cs = value as i32 & 65535,
        0x175 | 0x176 => {
            if !state::canonical(value, 48) {
                return Err(Fault::gp());
            }
            if index == 0x175 {
                *gp::sysenter_esp = value as i32;
                *gp::x64_sysenter_esp_hi = (value >> 32) as u32;
            }
            else {
                *gp::sysenter_eip = value as i32;
                *gp::x64_sysenter_eip_hi = (value >> 32) as u32;
            }
        },
        0x8B => {}, // no microcode revision; CPUID leaves the signature zero
        0x10 => cpu::set_tsc(value as u32, (value >> 32) as u32),
        0x1B => {
            // xAPIC only: the address and BSP bit are fixed by the machine.
            if value & !0x900 != 0xFEE00000 {
                return Err(Fault::gp());
            }
            let enabled = value & 0x800 != 0;
            if *gp::apic_enabled && !enabled {
                crate::cpu::apic::software_disable();
            }
            *gp::apic_enabled = enabled;
            crate::cpu::apic::apic_set_hardware_enabled(
                crate::cpu::apic::current_core() as u32,
                enabled,
            );
        },
        // read-only
        0x10A if crate::cpu::instructions_0f::arch_capabilities().is_some() => {
            return Err(Fault::gp())
        },
        _ => return Ok(false),
    }
    Ok(true)
}
pub unsafe fn read_msr(index: u32) -> Result<Option<u64>, Fault> {
    if *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    Ok(Some(match index {
        0xC0000080 => state::efer(),
        0xC0000081 => *gp::x64_star,
        0xC0000082 => *gp::x64_lstar,
        0xC0000083 => *gp::x64_cstar,
        0xC0000084 => *gp::x64_sfmask,
        0xC0000100 => state::read_segment_base(4),
        0xC0000101 => state::read_segment_base(5),
        0xC0000102 => *gp::x64_kernel_gs_base,
        0xC0000103 => *gp::x64_tsc_aux as u64,
        0x174 => *gp::sysenter_cs as u32 as u64,
        0x175 => *gp::sysenter_esp as u32 as u64 | (*gp::x64_sysenter_esp_hi as u64) << 32,
        0x176 => *gp::sysenter_eip as u32 as u64 | (*gp::x64_sysenter_eip_hi as u64) << 32,
        0x8B => 0,
        0x10 => cpu::read_tsc(),
        0x1B => {
            0xFEE00000
                | if *gp::apic_enabled { 0x800 } else { 0 }
                | if crate::cpu::apic::current_core() == 0 { 0x100 } else { 0 }
        },
        0x10A => match crate::cpu::instructions_0f::arch_capabilities() {
            Some(value) => value,
            None => return Ok(None),
        },
        _ => return Ok(None),
    }))
}

/// System opcodes used by the wide interpreter. Returning false means that
/// the instruction belongs to another executor, never silently succeeds.
pub unsafe fn execute(instruction: &Decoded) -> Result<bool, Fault> {
    let op = instruction.base_opcode();
    match op {
        0x0F00 => descriptor_instruction(instruction)?,
        0x0F02 | 0x0F03 => query_descriptor(instruction)?,
        0x0F21 | 0x0F23 => debug_register(instruction)?,
        0x0FA0 | 0x0FA1 | 0x0FA8 | 0x0FA9 => {
            let segment = if op & 8 == 0 { 4 } else { 5 };
            let width = if instruction.operand_size == 16 { 16 } else { 64 };
            let rsp = state::read_gpr(4);
            if op & 1 == 0 {
                let next = rsp.wrapping_sub((width / 8) as u64);
                memory::write(next, width, *gp::sreg.add(segment) as u64, true)?;
                state::write_gpr(4, next, 64);
            }
            else {
                let selector = memory::read(rsp, width, true)? as u16;
                load_segment(segment, selector)?;
                state::write_gpr(4, rsp.wrapping_add((width / 8) as u64), 64);
            }
        },
        0x0F01 => table_instruction(instruction)?,
        0x0F05 | 0x0F07 | 0x0F34 | 0x0F35 => {
            fast_call(op, instruction.operand_size == 64, instruction.next.0)?;
            return Ok(true);
        },
        0xCA | 0xCB => {
            far_return(
                instruction.operand_size,
                instruction.immediate.map_or(0, |value| value.value as u16),
            )?;
            return Ok(true);
        },
        0xFF if matches!(instruction.modrm.map(|m| m >> 3 & 7), Some(3 | 5)) => {
            far_transfer(instruction, instruction.modrm.unwrap() >> 3 & 7 == 3)?;
            return Ok(true);
        },
        0x0F06 => {
            if *gp::cpl != 0 {
                return Err(Fault::gp());
            }
            crate::step_profile::note_event(crate::step_profile::event::CLTS, 0);
            state::write_cr_raw(0, state::read_cr(0) & !8);
        },
        0x0F08 | 0x0F09 => {
            if *gp::cpl != 0 {
                return Err(Fault::gp());
            }
        },
        0x8C | 0x8E => {
            let segment = (instruction.modrm.ok_or(Fault::ud())? >> 3 & 7) as usize;
            if segment >= 6 || op == 0x8E && segment == 1 {
                return Err(Fault::ud());
            }
            if op == 0x8E {
                load_segment(segment, read_rm(instruction, 16)? as u16)?;
            }
            else {
                write_rm(
                    instruction,
                    if instruction.rm_register.is_some() { instruction.operand_size } else { 16 },
                    *gp::sreg.add(segment) as u64,
                )?;
            }
        },
        0xCC | 0xCD => {
            let vector =
                if op == 0xCC { 3 } else { instruction.immediate.ok_or(Fault::ud())?.value as i32 };
            state::write_rip(instruction.next.0);
            crate::cpu::exceptions::interrupt(vector, true, None);
            return Ok(true);
        },
        0xCF => {
            iret(instruction.operand_size)?;
            return Ok(true);
        },
        0xF1 => {
            // INT1 (ICEBP): #DB as a trap, without the gate DPL check
            state::write_rip(instruction.next.0);
            crate::cpu::exceptions::interrupt(1, false, None);
            return Ok(true);
        },
        0x0FB2 | 0x0FB4 | 0x0FB5 => {
            // LSS/LFS/LGS m16:16/32/64
            let width = instruction.operand_size;
            let (addr, stack) = operand_address(instruction)?;
            let offset = memory::read(addr, width, stack)?;
            let selector = memory::read(addr.wrapping_add((width / 8) as u64), 16, stack)? as u16;
            let segment = match op {
                0x0FB2 => 2,
                0x0FB4 => 4,
                _ => 5,
            };
            load_segment(segment, selector)?;
            state::write_gpr(instruction.reg.ok_or(Fault::ud())? as usize, offset, width);
        },
        0xE4..=0xE7 | 0xEC..=0xEF => port_instruction(instruction)?,
        0xF4 => {
            if *gp::cpl != 0 {
                return Err(Fault::gp());
            }
            *gp::in_hlt = true;
            cpu::core_yield = true;
            crate::cpu::execution::note_halt();
        },
        0xFA | 0xFB => {
            if *gp::cpl as i32 > cpu::getiopl() {
                return Err(Fault::gp());
            }
            if op == 0xFA {
                *gp::flags &= !cpu::FLAG_INTERRUPT;
            }
            else {
                *gp::flags |= cpu::FLAG_INTERRUPT;
                *gp::interrupt_shadow = 2;
            }
        },
        0x0F20 | 0x0F22 => {
            // an undefined control register is #UD before the privilege #GP
            let control = instruction.reg.ok_or(Fault::ud())? as usize;
            let register = instruction.rm_register.ok_or(Fault::ud())? as usize;
            if !matches!(control, 0 | 2 | 3 | 4 | 8) {
                return Err(Fault::ud());
            }
            if *gp::cpl != 0 {
                return Err(Fault::gp());
            }
            if op == 0x0F22 {
                write_cr(control, state::read_gpr(register))?;
            }
            else {
                state::write_gpr(register, state::read_cr(control), 64);
            }
        },
        0x0F30 => {
            let index = state::read_gpr(1) as u32;
            let value = state::read_gpr(0) as u32 as u64 | (state::read_gpr(2) as u32 as u64) << 32;
            // then the model's other MSRs (e.g. IA32_PLATFORM_ID, MISC_ENABLE)
            if !write_msr(index, value)?
                && crate::cpu::instructions_0f::write_msr_table(
                    index as i32,
                    value as i32,
                    (value >> 32) as i32,
                ) != Ok(true)
            {
                return Err(Fault::gp());
            }
        },
        0x0F32 => {
            let index = state::read_gpr(1) as u32;
            let value = match read_msr(index)? {
                Some(value) => value,
                None => crate::cpu::instructions_0f::read_msr_table(index as i32)
                    .map(|(low, high)| low as u32 as u64 | (high as u32 as u64) << 32)
                    .ok_or(Fault::gp())?,
            };
            state::write_gpr(0, value, 32);
            state::write_gpr(2, value >> 32, 32);
        },
        0x0F31 => {
            if *gp::cpl != 0 && state::read_cr(4) & 4 != 0 {
                return Err(Fault::gp());
            }
            let value = cpu::read_tsc();
            state::write_gpr(0, value, 32);
            state::write_gpr(2, value >> 32, 32);
        },
        0x0FAA => {
            // RSM (a 64-bit SMM handler's)
            if !crate::cpu::smm::smm_active() {
                return Err(Fault::ud());
            }
            crate::cpu::smm::rsm();
            return Ok(true);
        },
        0x0FA2 => {
            crate::cpu::instructions_0f::instr_0FA2();
            for r in 0..4 {
                state::write_gpr(r, state::read_gpr(r), 32);
            }
        },
        _ => return Ok(false),
    }
    state::write_rip(instruction.next.0);
    Ok(true)
}

unsafe fn operand_address(d: &Decoded) -> Result<(u64, bool), Fault> {
    let expr = d.address.ok_or(Fault::ud())?;
    let mut regs = [0; 16];
    for (index, value) in regs.iter_mut().enumerate() {
        *value = state::read_gpr(index);
    }
    let base = if expr.segment >= 4 { state::read_segment_base(expr.segment as usize) } else { 0 };
    Ok((
        expr.offset(&regs, d.next).wrapping_add(base),
        expr.segment == 2,
    ))
}
unsafe fn read_rm(d: &Decoded, width: u8) -> Result<u64, Fault> {
    if let Some(reg) = d.rm_register {
        Ok(state::read_gpr(reg as usize))
    }
    else {
        let (addr, stack) = operand_address(d)?;
        memory::read(addr, width, stack)
    }
}
unsafe fn write_rm(d: &Decoded, width: u8, value: u64) -> Result<(), Fault> {
    if let Some(reg) = d.rm_register {
        state::write_gpr(reg as usize, value, width);
        Ok(())
    }
    else {
        let (addr, stack) = operand_address(d)?;
        memory::write(addr, width, value, stack)
    }
}

/// Fast entry/exit instructions install architectural fixed segment caches;
/// they deliberately do not consult the descriptor tables.
unsafe fn flat_segments(cs: u16, ss: u16, privilege: u8, long: bool) {
    *gp::sreg.add(1) = cs & !3 | privilege as u16;
    *gp::sreg.add(2) = ss & !3 | privilege as u16;
    for segment in [1, 2] {
        *gp::segment_is_null.add(segment) = false;
        *gp::segment_limits.add(segment) = u32::MAX;
        *gp::segment_access_bytes.add(segment) =
            (if segment == 1 { 0x9B } else { 0x93 }) | privilege << 5;
        state::write_segment_base(segment, 0);
    }
    *gp::x64_cs_long = long as u8;
    *gp::is_32 = !long;
    *gp::stack_size_32 = true;
    *gp::cpl = privilege;
    cpu::update_state_flags();
    cpu::cpl_changed();
}
pub unsafe fn fast_call(op: u32, wide: bool, next: u64) -> Result<(), Fault> {
    match op {
        0x0F05 | 0x0F07 => {
            if !state::mode().is_long() || state::efer() & EFER_SCE == 0 {
                return Err(Fault::ud());
            }
            if op == 0x0F05 {
                let target = *gp::x64_lstar;
                if !state::canonical(target, 48) {
                    return Err(Fault::gp());
                }
                state::write_gpr(1, next, 64);
                state::write_gpr(11, state::read_flags64(), 64);
                state::write_flags64(state::read_flags64() & !*gp::x64_sfmask);
                let cs = (*gp::x64_star >> 32) as u16 & !3;
                flat_segments(cs, cs.wrapping_add(8), 0, true);
                state::write_rip(target);
            }
            else {
                if *gp::cpl != 0 {
                    return Err(Fault::gp());
                }
                let target =
                    if wide { state::read_gpr(1) } else { state::read_gpr(1) as u32 as u64 };
                if !state::canonical(target, 48) {
                    return Err(Fault::gp());
                }
                let selectors = (*gp::x64_star >> 48) as u16;
                let flags = state::read_gpr(11) & 0x3C7FD7 | 2;
                flat_segments(
                    selectors.wrapping_add(if wide { 16 } else { 0 }),
                    selectors.wrapping_add(8),
                    3,
                    wide,
                );
                state::write_flags64(flags);
                state::write_rip(target);
            }
        },
        0x0F34 => {
            let cs = *gp::sysenter_cs as u16 & !3;
            if cs == 0 || state::read_cr(0) & PE == 0 {
                return Err(Fault::gp());
            }
            let ip = *gp::sysenter_eip as u32 as u64 | (*gp::x64_sysenter_eip_hi as u64) << 32;
            let sp = *gp::sysenter_esp as u32 as u64 | (*gp::x64_sysenter_esp_hi as u64) << 32;
            if !state::canonical(ip, 48) || !state::canonical(sp, 48) {
                return Err(Fault::gp());
            }
            state::write_flags64(state::read_flags64() & !0x20200);
            flat_segments(cs, cs.wrapping_add(8), 0, true);
            state::write_gpr(4, sp, 64);
            state::write_rip(ip);
        },
        0x0F35 => {
            let cs = *gp::sysenter_cs as u16 & !3;
            if cs == 0 || *gp::cpl != 0 || state::read_cr(0) & PE == 0 {
                return Err(Fault::gp());
            }
            let ip = if wide { state::read_gpr(2) } else { state::read_gpr(2) as u32 as u64 };
            let sp = if wide { state::read_gpr(1) } else { state::read_gpr(1) as u32 as u64 };
            if !state::canonical(ip, 48) || !state::canonical(sp, 48) {
                return Err(Fault::gp());
            }
            let target_cs = cs.wrapping_add(if wide { 32 } else { 16 });
            // The full RSP is cleared for a compatibility return too.
            state::write_gpr(4, sp, 64);
            flat_segments(target_cs, target_cs.wrapping_add(8), 3, wide);
            state::write_rip(ip);
        },
        _ => unreachable!(),
    }
    Ok(())
}

unsafe fn load_segment(segment: usize, selector: u16) -> Result<(), Fault> {
    let privilege = *gp::cpl;
    let stack = segment == 2;
    if selector & !3 == 0 {
        if stack && (privilege == 3 || selector as u8 & 3 != privilege) {
            return Err(Fault::gp());
        }
        *gp::sreg.add(segment) = selector;
        *gp::segment_is_null.add(segment) = !stack;
        state::write_segment_base(segment, 0);
    }
    else {
        let (desc, at) = descriptor(selector)?;
        let error = selector as u32 & !3;
        if desc.is_system()
            || if stack {
                !desc.is_writable() || desc.dpl() != privilege || selector as u8 & 3 != privilege
            }
            else {
                !desc.is_readable()
                    || !desc.is_conforming_executable()
                        && (privilege > desc.dpl() || selector as u8 & 3 > desc.dpl())
            }
        {
            return Err(exception(13, error));
        }
        if !desc.is_present() {
            return Err(exception(if stack { 12 } else { 11 }, error));
        }
        if !desc.accessed() {
            memory::write_system(at.wrapping_add(5), 8, (desc.access_byte() | 1) as u64)?;
        }
        *gp::sreg.add(segment) = selector;
        *gp::segment_is_null.add(segment) = false;
        *gp::segment_access_bytes.add(segment) = desc.access_byte() | 1;
        *gp::segment_limits.add(segment) = desc.effective_limit();
        state::write_segment_base(segment, desc.base() as u32 as u64);
        if stack {
            *gp::stack_size_32 = desc.is_32();
        }
    }
    if stack {
        *gp::interrupt_shadow = 2;
    }
    cpu::update_state_flags();
    Ok(())
}

// MOV DR uses the complete address width in long mode. The GD condition is
// a fault: leave the GPR/RIP unchanged and clear GD before delivering #DB.
unsafe fn debug_register(d: &Decoded) -> Result<(), Fault> {
    let mut index = d.reg.ok_or(Fault::ud())? as usize;
    let register = d.rm_register.ok_or(Fault::ud())? as usize;
    if index >= 8 || matches!(index, 4 | 5) && state::read_cr(4) & 8 != 0 {
        return Err(Fault::ud());
    }
    if *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    if state::read_dr(7) & 0x2000 != 0 {
        state::write_dr(7, state::read_dr(7) & !0x2000);
        state::write_dr(6, state::read_dr(6) | 0x2000);
        return Err(Fault {
            vector: 1,
            error: None,
            address: None,
        });
    }
    if index == 4 || index == 5 {
        index += 2;
    }
    if d.base_opcode() == 0x0F21 {
        state::write_gpr(register, state::read_dr(index), 64);
    }
    else {
        let mut value = state::read_gpr(register);
        if index >= 6 && value >> 32 != 0 {
            return Err(Fault::gp());
        }
        if index == 6 {
            value = value & 0xE00F | 0xFFFF0FF0;
        }
        if index == 7 {
            value = value & !0xD800 | 0x400;
        }
        state::write_dr(index, value);
    }
    Ok(())
}

// LAR/LSL/VERR/VERW reject an inaccessible selector by clearing ZF. Only
// faults while actually reading a descriptor propagate as exceptions.
unsafe fn visible_descriptor(selector: u16) -> Result<Option<cpu::SegmentDescriptor>, Fault> {
    if selector & !3 == 0 {
        return Ok(None);
    }
    let local = selector & 4 != 0;
    if local && *gp::segment_is_null.add(7) {
        return Ok(None);
    }
    let limit = if local { *gp::segment_limits.add(7) } else { *gp::gdtr_size as u32 };
    if (selector as u32 & !7) + 7 > limit {
        return Ok(None);
    }
    let (desc, _) = descriptor(selector)?;
    if !(desc.is_executable() && !desc.is_system() && desc.is_dc())
        && desc.dpl() < (*gp::cpl).max((selector & 3) as u8)
    {
        return Ok(None);
    }
    Ok(Some(desc))
}
unsafe fn query_descriptor(d: &Decoded) -> Result<(), Fault> {
    let selector = read_rm(d, 16)? as u16;
    let desc = visible_descriptor(selector)?;
    let limit = d.base_opcode() == 0x0F03;
    let valid = desc.as_ref().is_some_and(|v| {
        !v.is_system()
            || if limit {
                matches!(v.system_type(), 2 | 9 | 11)
            }
            else {
                matches!(v.system_type(), 2 | 9 | 11 | 12)
            }
    });
    let flags = state::read_flags64() & !0x40;
    if valid {
        let v = desc.unwrap();
        let value = if limit { v.effective_limit() as u64 } else { v.raw >> 32 & 0x00F0FF00 };
        state::write_gpr(d.reg.ok_or(Fault::ud())? as usize, value, d.operand_size);
    }
    state::write_flags64(flags | if valid { 0x40 } else { 0 });
    Ok(())
}

unsafe fn descriptor_instruction(d: &Decoded) -> Result<(), Fault> {
    let group = d.modrm.ok_or(Fault::ud())? >> 3 & 7;
    if group <= 1 {
        return write_rm(
            d,
            if d.rm_register.is_some() { d.operand_size } else { 16 },
            *gp::sreg.add(if group == 0 { 7 } else { 6 }) as u64,
        );
    }
    if matches!(group, 4 | 5) {
        let desc = visible_descriptor(read_rm(d, 16)? as u16)?;
        let valid = desc.is_some_and(|v| {
            !v.is_system()
                && if group == 5 {
                    !v.is_executable() && v.is_writable()
                }
                else {
                    !v.is_executable() || v.is_readable()
                }
        });
        state::write_flags64(state::read_flags64() & !0x40 | if valid { 0x40 } else { 0 });
        return Ok(());
    }
    if !matches!(group, 2 | 3) {
        return Err(Fault::ud());
    }
    if *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    let selector = read_rm(d, 16)? as u16;
    let target = if group == 2 { 7 } else { 6 };
    if selector & !3 == 0 {
        if group == 3 {
            return Err(Fault::gp());
        }
        *gp::sreg.add(target) = selector;
        *gp::segment_is_null.add(target) = true;
        return Ok(());
    }
    let error = selector as u32 & !3;
    if selector & 4 != 0 || (selector as u32 & !7) + 15 > *gp::gdtr_size as u32 {
        return Err(exception(13, error));
    }
    let (desc, at) = descriptor(selector)?;
    let high = memory::read_system(at.wrapping_add(8), 64)?;
    if !desc.is_system()
        || desc.access_byte() & 15 != if group == 2 { 2 } else { 9 }
        || high >> 32 != 0
    {
        return Err(exception(13, error));
    }
    if !desc.is_present() {
        return Err(exception(11, error));
    }
    let base = desc.base() as u32 as u64 | high << 32;
    if !state::canonical(base, 48) {
        return Err(exception(13, error));
    }
    if group == 3 {
        memory::write_system(at.wrapping_add(5), 8, (desc.access_byte() | 2) as u64)?;
    }
    *gp::sreg.add(target) = selector;
    *gp::segment_is_null.add(target) = false;
    *gp::segment_access_bytes.add(target) = desc.access_byte() | if group == 3 { 2 } else { 0 };
    *gp::segment_limits.add(target) = desc.effective_limit();
    state::write_segment_base(target, base);
    Ok(())
}

/// XGETBV and XSETBV (cpu::xstate): #UD without CR4.OSXSAVE, then #GP(0)
unsafe fn xgetbv_xsetbv(set: bool, long: bool) -> Result<(), Fault> {
    if !xstate::enabled() {
        return Err(Fault::ud());
    }
    let index = state::read_gpr(1) as u32;
    if !set {
        let value = xstate::xgetbv(index, long).ok_or(Fault::gp())?;
        state::write_gpr(0, value & 0xFFFF_FFFF, 32);
        state::write_gpr(2, value >> 32, 32);
        return Ok(());
    }
    let value = state::read_gpr(2) << 32 | state::read_gpr(0) & 0xFFFF_FFFF;
    if *gp::cpl != 0 || !xstate::xsetbv(index, value) {
        return Err(Fault::gp());
    }
    Ok(())
}
unsafe fn table_instruction(d: &Decoded) -> Result<(), Fault> {
    let modrm = d.modrm.ok_or(Fault::ud())?;
    // XGETBV, XSETBV: without a mandatory prefix
    if matches!(modrm, 0xD0 | 0xD1) && !d.prefixes.operand && d.prefixes.rep.is_none() {
        return xgetbv_xsetbv(modrm == 0xD1, d.mode.is_long());
    }
    // Register forms outside SMSW/LMSW/SWAPGS/RDTSCP belong to extensions
    // this profile lacks (VMX, SVM, MONITOR, SMAP, ...): #UD before any
    // privilege check. So is /5 on memory (RSTORSSP).
    let group = modrm >> 3 & 7;
    if modrm >= 0xC0 && !matches!(group, 4 | 6) && !matches!(modrm, 0xF8 | 0xF9)
        || modrm < 0xC0 && group == 5
    {
        return Err(Fault::ud());
    }
    if modrm == 0xF8 {
        if *gp::cpl != 0 {
            return Err(Fault::gp());
        }
        let old = state::read_segment_base(5);
        state::write_segment_base(5, *gp::x64_kernel_gs_base);
        *gp::x64_kernel_gs_base = old;
        return Ok(());
    }
    if modrm == 0xF9 {
        if *gp::cpl != 0 && state::read_cr(4) & 4 != 0 {
            return Err(Fault::gp());
        }
        let time = cpu::read_tsc();
        state::write_gpr(0, time, 32);
        state::write_gpr(2, time >> 32, 32);
        state::write_gpr(1, *gp::x64_tsc_aux as u64, 32);
        return Ok(());
    }
    let group = modrm >> 3 & 7;
    if group == 4 {
        return write_rm(
            d,
            if d.rm_register.is_some() { d.operand_size } else { 16 },
            state::read_cr(0) & 65535,
        );
    }
    if group >= 2 && *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    if group == 6 {
        let value = read_rm(d, 16)?;
        return write_cr(0, state::read_cr(0) & !14 | value & 15);
    }
    let (addr, stack) = operand_address(d)?;
    match group {
        0 | 1 => {
            memory::probe_write(addr, 16, stack)?;
            memory::probe_write(addr.wrapping_add(2), 64, stack)?;
            memory::write(
                addr,
                16,
                if group == 0 { *gp::gdtr_size } else { *gp::idtr_size } as u64,
                stack,
            )?;
            memory::write(
                addr.wrapping_add(2),
                64,
                if group == 0 { state::read_gdtr_base() } else { state::read_idtr_base() },
                stack,
            )?;
        },
        2 | 3 => {
            let limit = memory::read(addr, 16, stack)? as i32;
            let base = memory::read(addr.wrapping_add(2), 64, stack)?;
            if !state::canonical(base, 48) {
                return Err(Fault::gp());
            }
            if group == 2 {
                *gp::gdtr_size = limit;
                state::write_gdtr_base(base);
            }
            else {
                *gp::idtr_size = limit;
                state::write_idtr_base(base);
            }
        },
        7 => {
            // Intel defines a noncanonical INVLPG operand as a no-op.
            if state::canonical(addr, 48) {
                memory::invlpg(addr);
                cpu::invlpg(addr as i32);
            }
        },
        _ => return Err(Fault::ud()),
    }
    Ok(())
}

pub unsafe fn check_io_access(port: u16, width: u8) -> Result<(), Fault> {
    if port as i32 == cpu::VMWARE_BACKDOOR_PORT {
        return Ok(());
    }
    if *gp::cpl as i32 > cpu::getiopl() {
        if *gp::segment_is_null.add(6) || *gp::segment_limits.add(6) < 103 {
            return Err(Fault::gp());
        }
        let base = state::read_segment_base(6);
        let bitmap = memory::read_system(base.wrapping_add(102), 16)? as u32;
        for bit in port as u32..port as u32 + (width / 8) as u32 {
            let offset = bitmap + bit / 8;
            if offset > *gp::segment_limits.add(6)
                || memory::read_system(base.wrapping_add(offset as u64), 8)? & (1 << (bit & 7)) != 0
            {
                return Err(Fault::gp());
            }
        }
    }
    Ok(())
}

unsafe fn port_instruction(d: &Decoded) -> Result<(), Fault> {
    let op = d.base_opcode();
    let width = if op & 1 == 0 { 8 } else { d.operand_size.min(32) };
    let port = if op & 8 == 0 {
        d.immediate.ok_or(Fault::ud())?.value as u16
    }
    else {
        state::read_gpr(2) as u16
    };
    check_io_access(port, width)?;
    if op & 2 == 0 {
        let value = match width {
            8 => cpu::io_port_read8(port as i32),
            16 => cpu::io_port_read16(port as i32),
            _ => cpu::io_port_read32(port as i32),
        };
        state::write_gpr(0, value as u32 as u64, width);
    }
    else {
        let value = state::read_gpr(0) as i32;
        match width {
            8 => cpu::io_port_write8(port as i32, value & 255),
            16 => cpu::io_port_write16(port as i32, value & 65535),
            _ => cpu::io_port_write32(port as i32, value),
        }
    }
    super::debug::io(port as u16, (width / 8) as usize);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    fn initial() -> ControlState {
        ControlState {
            cr0: PE | 16,
            cr3: 0,
            cr4: 0,
            efer: 0,
            cs_long: false,
        }
    }
    #[test]
    fn long_mode_entry_exit_round_trip_and_rejected_transitions_are_atomic() {
        let mut state = initial();
        state.write_efer(EFER_LME | EFER_NXE | EFER_SCE).unwrap();
        let unchanged = state;
        assert_eq!(state.write_cr(0, PE | PG), Err(Fault::gp()));
        assert_eq!(state, unchanged);
        state.write_cr(4, PAE).unwrap();
        state.write_cr(3, 0xA_1234_5000).unwrap();
        state.write_cr(0, PE | PG).unwrap();
        assert_ne!(state.efer & EFER_LMA, 0);
        let unchanged = state;
        assert_eq!(state.write_cr(4, 0), Err(Fault::gp()));
        assert_eq!(state, unchanged);
        assert_eq!(state.write_efer(EFER_NXE), Err(Fault::gp()));
        assert_eq!(state, unchanged);
        state.cs_long = true;
        let unchanged = state;
        assert_eq!(state.write_cr(0, PE), Err(Fault::gp()));
        assert_eq!(state, unchanged);
        state.cs_long = false;
        state.write_cr(0, PE).unwrap();
        assert_eq!(state.efer & EFER_LMA, 0);
        state.write_efer(0).unwrap();
        state.write_cr(4, 0).unwrap();
    }
    #[test]
    fn reserved_control_bits_and_readonly_lma() {
        let mut state = initial();
        state.write_efer(EFER_LMA).unwrap();
        assert_eq!(state.efer, 0);
        for (register, value) in [
            (0, PG),
            (0, 1 << 29 | PE),
            (0, 1 << 32 | PE),
            (3, 1 << 36),
            (4, 1 << 12),
            (4, 1 << 17),
            (4, 1 << 18),
        ] {
            let unchanged = state;
            assert!(state.write_cr(register, value).is_err());
            assert_eq!(state, unchanged);
        }
        for bit in [1, 2, 9, 12, 63] {
            assert!(state.write_efer(1 << bit).is_err());
        }
    }
}

fn exception(vector: u8, code: u32) -> Fault {
    Fault {
        vector,
        error: Some(code),
        address: None,
    }
}
pub unsafe fn descriptor(selector: u16) -> Result<(cpu::SegmentDescriptor, u64), Fault> {
    if selector & !3 == 0 {
        return Err(Fault::gp());
    }
    let local = selector & 4 != 0;
    let base = if local { state::read_segment_base(7) } else { state::read_gdtr_base() };
    let limit = if local { *gp::segment_limits.add(7) } else { *gp::gdtr_size as u32 };
    let offset = selector as u32 & !7;
    if offset + 7 > limit {
        return Err(exception(13, selector as u32 & !3));
    }
    let address = base.wrapping_add(offset as u64);
    Ok((
        cpu::SegmentDescriptor::of_u64(memory::read_system(address, 64)?),
        address,
    ))
}
unsafe fn install_cs(selector: u16, descriptor: &cpu::SegmentDescriptor, privilege: u8) {
    *gp::sreg.add(1) = selector & !3 | privilege as u16;
    *gp::segment_is_null.add(1) = false;
    *gp::segment_access_bytes.add(1) = descriptor.access_byte();
    *gp::segment_limits.add(1) = descriptor.effective_limit();
    *gp::is_32 = descriptor.is_32();
    *gp::x64_cs_long = (descriptor.flags() & 2 != 0) as u8;
    state::write_segment_base(
        1,
        if *gp::x64_cs_long != 0 { 0 } else { descriptor.base() as u32 as u64 },
    );
    *gp::cpl = privilege;
    cpu::update_state_flags();
    *gp::last_virt_eip = -1;
}
pub unsafe fn interrupt(vector: u8, software: bool, code: Option<u32>) -> Result<(), Fault> {
    let offset = vector as u32 * 16;
    let idt_error = (vector as u32) << 3 | 2;
    if offset + 15 > *gp::idtr_size as u32 {
        return Err(exception(13, idt_error));
    }
    let address = state::read_idtr_base().wrapping_add(offset as u64);
    let low = memory::read_system(address, 64)?;
    let high = memory::read_system(address.wrapping_add(8), 64)?;
    let access = (low >> 40) as u8;
    let kind = access & 15;
    if !matches!(kind, 14 | 15) || access & 16 != 0 || high >> 32 != 0 || low >> 32 & 0xF8 != 0 {
        return Err(exception(13, idt_error));
    }
    if software && *gp::cpl > (access >> 5 & 3) {
        return Err(exception(13, idt_error));
    }
    if access & 128 == 0 {
        return Err(exception(11, idt_error));
    }
    let selector = (low >> 16) as u16;
    let (cs, _) = descriptor(selector)?;
    if cs.is_system()
        || !cs.is_executable()
        || cs.dpl() > *gp::cpl
        || cs.flags() & 2 == 0
        || cs.is_32()
    {
        return Err(exception(13, selector as u32 & !3));
    }
    if !cs.is_present() {
        return Err(exception(11, selector as u32 & !3));
    }
    let target = low & 65535 | (low >> 48) << 16 | (high & 0xFFFF_FFFF) << 32;
    if !state::canonical(target, 48) {
        return Err(Fault::gp());
    }
    // (exceptions only: Windows also sends itself APC interrupts at vector 0x1F)
    if USER_TRACE_ENABLED
        && !software
        && matches!(vector, 0..=8 | 10..=14 | 16..=21)
        && *gp::cpl == 3
        && (*gp::x64_cs_long == 0 || vector != 14)
    {
        USER_TRACE[USER_TRACE_NEXT % USER_TRACE_LEN] = [
            vector as u64,
            code.map_or(u64::MAX, |c| c as u64),
            state::read_rip(),
            if vector == 14 { state::read_cr(2) } else { u64::MAX },
            state::read_gpr(4),
            *gp::sreg.add(1) as u64,
            state::read_cr(3),
        ];
        USER_TRACE_NEXT += 1;
    }
    let old_rsp = state::read_gpr(4);
    let old_ss = *gp::sreg.add(2);
    let old_cs = *gp::sreg.add(1);
    let old_rip = state::read_rip();
    let old_flags = state::read_flags64();
    let new_cpl = if cs.is_dc() { *gp::cpl } else { cs.dpl() };
    let ist = (low >> 32 & 7) as u8;
    let switch_stack = ist != 0 || new_cpl < *gp::cpl;
    let mut rsp = old_rsp;
    if switch_stack {
        let at = if ist != 0 { 36 + (ist as u32 - 1) * 8 } else { 4 + new_cpl as u32 * 8 };
        if at + 7 > *gp::segment_limits.add(6) {
            return Err(exception(10, *gp::sreg.add(6) as u32 & !3));
        }
        rsp = memory::read_system(state::read_segment_base(6).wrapping_add(at as u64), 64)?;
    }
    rsp &= !15;
    let values = [
        old_ss as u64,
        old_rsp,
        old_flags,
        old_cs as u64,
        old_rip,
        code.unwrap_or(0) as u64,
    ];
    let count = if code.is_some() { 6 } else { 5 };
    // Check the entire frame before stores or cached privilege/segment state.
    for i in 0..count {
        memory::probe_system_write(rsp.wrapping_sub((i + 1) as u64 * 8), 64)?;
    }
    for value in &values[..count] {
        rsp = rsp.wrapping_sub(8);
        memory::write_system(rsp, 64, *value)?;
    }
    install_cs(selector, &cs, new_cpl);
    if switch_stack {
        *gp::sreg.add(2) = new_cpl as u16;
        *gp::segment_is_null.add(2) = false;
        *gp::segment_access_bytes.add(2) = 0x93 | new_cpl << 5;
        *gp::segment_limits.add(2) = u32::MAX;
        state::write_segment_base(2, 0);
    }
    state::write_gpr(4, rsp, 64);
    state::write_flags64(
        old_flags
            & !(0x100 | 0x4000 | 0x10000 | 0x20000)
            & if kind == 14 { !0x200 } else { u64::MAX },
    );
    state::write_rip(target);
    Ok(())
}
/// JMP/CALL m16:16/32/64 in 64-bit mode (SDM Vol.2A JMP/CALL, Vol.3A §5.8.3):
/// a code segment at the current privilege, or a 64-bit call gate, which a
/// CALL may use to reach a more privileged 64-bit code segment. Task gates
/// and TSS selectors do not exist in IA-32e mode. Every access and check
/// precedes the first architectural change.
unsafe fn far_transfer(instruction: &Decoded, call: bool) -> Result<(), Fault> {
    if instruction.address.is_none() {
        return Err(Fault::ud());
    }
    let width = instruction.operand_size;
    let (pointer, stack_access) = super::execute::address(instruction);
    let offset = memory::read(pointer, width, stack_access)?;
    let selector = memory::read(pointer.wrapping_add((width / 8) as u64), 16, stack_access)? as u16;
    let next = instruction.next.0;
    let cpl = *gp::cpl;
    let error = selector as u32 & !3;
    let (target, at) = descriptor(selector)?;
    if !target.is_system() {
        let long = target.flags() & 2 != 0;
        if !target.is_executable()
            || long && target.is_32()
            || if target.is_dc() {
                target.dpl() > cpl
            }
            else {
                (selector & 3) as u8 > cpl || target.dpl() != cpl
            }
        {
            return Err(exception(13, error));
        }
        if !target.is_present() {
            return Err(exception(11, error));
        }
        if long && !state::canonical(offset, 48)
            || !long && offset > target.effective_limit() as u64
        {
            return Err(Fault::gp());
        }
        if call {
            let rsp = state::read_gpr(4);
            let unit = (width / 8) as u64;
            memory::probe_write(rsp.wrapping_sub(2 * unit), width, true)?;
            memory::probe_write(rsp.wrapping_sub(unit), width, true)?;
            memory::write(rsp.wrapping_sub(unit), width, *gp::sreg.add(1) as u64, true)?;
            memory::write(rsp.wrapping_sub(2 * unit), width, next, true)?;
            state::write_gpr(4, rsp.wrapping_sub(2 * unit), 64);
        }
        if !target.accessed() {
            memory::write_system(at.wrapping_add(5), 8, (target.access_byte() | 1) as u64)?;
        }
        install_cs(selector, &target, cpl);
        state::write_rip(offset);
        return Ok(());
    }
    // A 64-bit call gate occupies 16 bytes; the upper type field must be 0.
    let limit = if selector & 4 != 0 { *gp::segment_limits.add(7) } else { *gp::gdtr_size as u32 };
    if target.system_type() != 12
        || target.dpl() < cpl
        || target.dpl() < (selector & 3) as u8
        || (selector as u32 & !7) + 15 > limit
    {
        return Err(exception(13, error));
    }
    if !target.is_present() {
        return Err(exception(11, error));
    }
    let high = memory::read_system(at.wrapping_add(8), 64)?;
    if high >> 40 & 0x1F != 0 {
        return Err(exception(13, error));
    }
    let code_selector = (target.raw >> 16) as u16;
    let entry = target.raw & 0xFFFF | (target.raw >> 48) << 16 | (high & 0xFFFF_FFFF) << 32;
    let code_error = code_selector as u32 & !3;
    let (code, code_at) = descriptor(code_selector)?;
    if code.is_system()
        || !code.is_executable()
        || code.flags() & 2 == 0
        || code.is_32()
        || if call {
            code.dpl() > cpl
        }
        else if code.is_dc() {
            code.dpl() > cpl
        }
        else {
            code.dpl() != cpl
        }
    {
        return Err(exception(13, code_error));
    }
    if !code.is_present() {
        return Err(exception(11, code_error));
    }
    if !state::canonical(entry, 48) {
        return Err(Fault::gp());
    }
    let new_cpl = if call && !code.is_dc() { code.dpl() } else { cpl };
    let mut frame: [u64; 4] = [0; 4];
    let mut count = 0;
    let mut rsp = state::read_gpr(4);
    if call {
        if new_cpl < cpl {
            // Inner privilege: RSPn from the 64-bit TSS; SS becomes a null
            // selector with RPL = new CPL. Call gates do not align RSP.
            let tss = 4 + new_cpl as u32 * 8;
            if tss + 7 > *gp::segment_limits.add(6) {
                return Err(exception(10, *gp::sreg.add(6) as u32 & !3));
            }
            let inner =
                memory::read_system(state::read_segment_base(6).wrapping_add(tss as u64), 64)?;
            if !state::canonical(inner, 48) {
                return Err(exception(12, 0));
            }
            frame = [*gp::sreg.add(2) as u64, rsp, *gp::sreg.add(1) as u64, next];
            count = 4;
            rsp = inner;
        }
        else {
            frame[..2].copy_from_slice(&[*gp::sreg.add(1) as u64, next]);
            count = 2;
        }
        for i in 0..count {
            if new_cpl < cpl {
                memory::probe_system_write(rsp.wrapping_sub((i + 1) as u64 * 8), 64)?;
            }
            else {
                memory::probe_write(rsp.wrapping_sub((i + 1) as u64 * 8), 64, true)?;
            }
        }
    }
    if !code.accessed() {
        memory::write_system(code_at.wrapping_add(5), 8, (code.access_byte() | 1) as u64)?;
    }
    for value in &frame[..count] {
        rsp = rsp.wrapping_sub(8);
        if new_cpl < cpl {
            memory::write_system(rsp, 64, *value)?;
        }
        else {
            memory::write(rsp, 64, *value, true)?;
        }
    }
    if new_cpl < cpl {
        *gp::sreg.add(2) = new_cpl as u16;
        *gp::segment_is_null.add(2) = false;
        *gp::segment_access_bytes.add(2) = 0x93 | new_cpl << 5;
        *gp::segment_limits.add(2) = u32::MAX;
        state::write_segment_base(2, 0);
    }
    state::write_gpr(4, rsp, 64);
    install_cs(code_selector, &code, new_cpl);
    state::write_rip(entry);
    Ok(())
}
pub unsafe fn far_return(width: u8, discard: u16) -> Result<(), Fault> {
    let unit = (width / 8) as u64;
    let rsp = state::read_gpr(4);
    let ip = memory::read(rsp, width, true)?;
    let selector = memory::read(rsp.wrapping_add(unit), width, true)? as u16;
    let (cs, at) = descriptor(selector)?;
    let new_cpl = (selector & 3) as u8;
    let long = cs.flags() & 2 != 0;
    if cs.is_system()
        || !cs.is_executable()
        || new_cpl < *gp::cpl
        || long && cs.is_32()
        || if cs.is_dc() { cs.dpl() > new_cpl } else { cs.dpl() != new_cpl }
    {
        return Err(exception(13, selector as u32 & !3));
    }
    if !cs.is_present() {
        return Err(exception(11, selector as u32 & !3));
    }
    if !state::canonical(ip, 48) || !long && ip > cs.effective_limit() as u64 {
        return Err(Fault::gp());
    }
    let mut next_rsp = rsp.wrapping_add(unit * 2).wrapping_add(discard as u64);
    let stack = if new_cpl != *gp::cpl {
        let pointer = memory::read(next_rsp, width, true)?;
        let ss_selector = memory::read(next_rsp.wrapping_add(unit), width, true)? as u16;
        let (ss, _) = descriptor(ss_selector)?;
        if ss.is_system()
            || !ss.is_writable()
            || ss.dpl() != new_cpl
            || (ss_selector & 3) as u8 != new_cpl
        {
            return Err(exception(13, ss_selector as u32 & !3));
        }
        if !ss.is_present() {
            return Err(exception(12, ss_selector as u32 & !3));
        }
        if !state::canonical(pointer, 48) {
            return Err(exception(12, 0));
        }
        next_rsp = pointer.wrapping_add(discard as u64);
        Some((ss_selector, ss))
    }
    else {
        None
    };
    if !cs.accessed() {
        memory::write_system(at.wrapping_add(5), 8, (cs.access_byte() | 1) as u64)?;
    }
    if let Some((selector, ss)) = stack {
        *gp::sreg.add(2) = selector;
        *gp::segment_is_null.add(2) = false;
        *gp::segment_access_bytes.add(2) = ss.access_byte();
        *gp::segment_limits.add(2) = ss.effective_limit();
        *gp::stack_size_32 = ss.is_32();
        state::write_segment_base(2, if long { 0 } else { ss.base() as u32 as u64 });
    }
    state::write_gpr(4, next_rsp, 64);
    install_cs(selector, &cs, new_cpl);
    state::write_rip(ip);
    Ok(())
}

/// IRETQ, or IRETD/IRETW (the same five slots, 4 or 2 bytes each).
pub unsafe fn iret(width: u8) -> Result<(), Fault> {
    crate::parallel::code::poll();
    if state::read_flags64() & 0x4000 != 0 {
        return Err(Fault::gp());
    }
    let rsp = state::read_gpr(4);
    let slot = (width / 8) as u64;
    let ip = memory::read(rsp, width, true)?;
    let selector = memory::read(rsp.wrapping_add(slot), width, true)? as u16;
    let mut flags = memory::read(rsp.wrapping_add(2 * slot), width, true)?;
    if width == 16 {
        flags = flags & 0xFFFF | state::read_flags64() & !0xFFFF;
    }
    let new_rsp = memory::read(rsp.wrapping_add(3 * slot), width, true)?;
    let ss_selector = memory::read(rsp.wrapping_add(4 * slot), width, true)? as u16;
    *gp::nmi_blocked = false;
    *gp::interrupt_shadow = 0;
    let (cs, _) = descriptor(selector)?;
    let new_cpl = (selector & 3) as u8;
    if cs.is_system()
        || !cs.is_executable()
        || new_cpl < *gp::cpl
        || if cs.is_dc() { cs.dpl() > new_cpl } else { cs.dpl() != new_cpl }
    {
        return Err(exception(13, selector as u32 & !3));
    }
    let long = cs.flags() & 2 != 0;
    if long && cs.is_32() {
        return Err(exception(13, selector as u32 & !3));
    }
    if !cs.is_present() {
        return Err(exception(11, selector as u32 & !3));
    }
    if !state::canonical(ip, 48) || !long && ip > cs.effective_limit() as u64 {
        return Err(Fault::gp());
    }
    if !state::canonical(new_rsp, 48) {
        return Err(exception(12, 0));
    }
    let ss = if ss_selector & !3 == 0 {
        if !long || new_cpl == 3 || (ss_selector & 3) as u8 != new_cpl {
            return Err(Fault::gp());
        }
        None
    }
    else {
        let (ss, _) = descriptor(ss_selector)?;
        if ss.is_system()
            || !ss.is_writable()
            || ss.dpl() != new_cpl
            || (ss_selector & 3) as u8 != new_cpl
        {
            return Err(exception(13, ss_selector as u32 & !3));
        }
        if !ss.is_present() {
            return Err(exception(12, ss_selector as u32 & !3));
        }
        Some(ss)
    };
    // Flags privilege checks use the returning CPL, before installing target CS.
    let mut next_flags = flags;
    if *gp::cpl != 0 {
        next_flags = next_flags & !0x3000 | state::read_flags64() & 0x3000;
    }
    if *gp::cpl as i32 > cpu::getiopl() {
        next_flags = next_flags & !0x200 | state::read_flags64() & 0x200;
    }
    state::write_flags64(next_flags & !0x20000);
    install_cs(selector, &cs, new_cpl);
    *gp::sreg.add(2) = ss_selector;
    *gp::segment_is_null.add(2) = false;
    *gp::segment_access_bytes.add(2) = ss.as_ref().map_or(0x93 | new_cpl << 5, |s| s.access_byte());
    *gp::segment_limits.add(2) = ss.as_ref().map_or(u32::MAX, |s| s.effective_limit());
    *gp::stack_size_32 = ss.as_ref().is_none_or(|s| s.is_32());
    state::write_segment_base(
        2,
        if long { 0 } else { ss.as_ref().map_or(0, |s| s.base() as u32 as u64) },
    );
    state::write_gpr(4, new_rsp, 64);
    state::write_rip(ip);
    Ok(())
}
/// Diagnostics: the last faults raised in IA-32e mode, most recent at
/// FAULT_NEXT - 1: vector, error code (or u64::MAX), faulting RIP, fault
/// address (or u64::MAX), RSP, CS.
const FAULT_LOG_LEN: usize = 16;
static mut FAULT_LOG: [[u64; 6]; FAULT_LOG_LEN] = [[0; 6]; FAULT_LOG_LEN];
static mut FAULT_NEXT: usize = 0;
/// `index` 0 is the most recent fault; `field` as in FAULT_LOG, halves by `high`.
#[no_mangle]
pub unsafe fn x64_fault_log(index: u32, field: u32, high: bool) -> u32 {
    if index as usize >= FAULT_LOG_LEN || index as usize >= FAULT_NEXT || field >= 6 {
        return 0;
    }
    let value = FAULT_LOG[(FAULT_NEXT - 1 - index as usize) % FAULT_LOG_LEN][field as usize];
    (if high { value >> 32 } else { value }) as u32
}
/// Diagnostics: where this instance keeps FAULT_LOG (`which` 0) and
/// FAULT_NEXT (1), so that the machine thread can read a vCPU worker's
/// (at the worker instance's base plus these, crate::parallel)
#[no_mangle]
pub unsafe fn x64_fault_log_location(which: u32) -> u32 {
    if which == 0 {
        &raw const FAULT_LOG as u32
    }
    else {
        &raw const FAULT_NEXT as u32
    }
}
/// Diagnostics: exceptions taken from CPL 3, as delivered (compatibility
/// mode: every vector; 64-bit mode: all but #PF), in FAULT_LOG's layout with
/// CR2 as the address, plus CR3. Off unless enabled; enabling clears it.
const USER_TRACE_LEN: usize = 1024;
static mut USER_TRACE: [[u64; 7]; USER_TRACE_LEN] = [[0; 7]; USER_TRACE_LEN];
static mut USER_TRACE_NEXT: usize = 0;
static mut USER_TRACE_ENABLED: bool = false;
#[no_mangle]
pub unsafe fn x64_user_trace_enable(enabled: bool) {
    USER_TRACE_ENABLED = enabled;
    USER_TRACE_NEXT = 0;
}
#[no_mangle]
pub unsafe fn x64_user_trace_count() -> u32 { USER_TRACE_NEXT as u32 }
/// `index` 0 is the oldest entry still held.
#[no_mangle]
pub unsafe fn x64_user_trace(index: u32, field: u32, high: bool) -> u32 {
    let first = USER_TRACE_NEXT.saturating_sub(USER_TRACE_LEN);
    let at = first + index as usize;
    if at >= USER_TRACE_NEXT || field >= 7 {
        return 0;
    }
    let value = USER_TRACE[at % USER_TRACE_LEN][field as usize];
    (if high { value >> 32 } else { value }) as u32
}
pub unsafe fn raise(fault: Fault) {
    FAULT_LOG[FAULT_NEXT % FAULT_LOG_LEN] = [
        fault.vector as u64,
        fault.error.map_or(u64::MAX, |e| e as u64),
        state::read_previous_rip(),
        fault.address.unwrap_or(u64::MAX),
        state::read_gpr(4),
        *gp::sreg.add(1) as u64,
    ];
    FAULT_NEXT += 1;
    crate::cpu::execution::mark_fault();
    state::write_rip(state::read_previous_rip());
    if fault.vector != 1 {
        state::write_flags64(state::read_flags64() | 0x10000);
    }
    if let Some(address) = fault.address {
        state::write_cr_raw(2, address);
    }
    crate::cpu::exceptions::fault(fault.vector as i32, fault.error.map(|e| e as i32));
}
                                                                                                                                                     source/v64/src/rust/x64/vector.rs                                                                   0000644 0000000 0000000 00000226150 00000000000 013747  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Long-mode SIMD/x87 front end. Addressing and register banks stay wide;
//! packed integer semantics are shared with the legacy interpreter. Floating
//! arithmetic uses SoftFloat with per-instruction MXCSR exception commit.
use super::{
    decode::Decoded,
    execute::address,
    memory::{self, Fault},
    state,
};
use crate::cpu::{
    avx, cpu, fpu, global_pointers as gp, instructions_0f as sem, instructions_0f38 as sem38,
    instructions_0f3a as sem3a, simd_fp, simd_int, xstate,
};
use crate::softfloat::F80;

extern "C" {
    fn extF80M_to_i32(a: *const F80, rounding: u8, exact: bool) -> i32;
    fn extF80M_to_i64(a: *const F80, rounding: u8, exact: bool) -> i64;
    fn extF80M_to_f32(a: *const F80) -> i32;
    fn extF80M_to_f64(a: *const F80) -> u64;
    static mut softfloat_roundingMode: u8;
    static mut softfloat_exceptionFlags: u8;
}
fn fault(vector: u8) -> Fault {
    Fault {
        vector,
        error: None,
        address: None,
    }
}
unsafe fn guard(sse: bool) -> Result<(), Fault> {
    if state::read_cr(0) & 4 != 0 || sse && state::read_cr(4) & 0x200 == 0 {
        return Err(Fault::ud());
    }
    if state::read_cr(0) & 8 != 0 {
        return Err(fault(7));
    }
    Ok(())
}
unsafe fn xmm(r: u8) -> u128 { std::mem::transmute(state::read_xmm(r as usize)) }
unsafe fn put_xmm(r: u8, v: u128) { state::write_xmm(r as usize, std::mem::transmute(v)); }
fn alignment(a: u64, stack: bool, align: u64) -> Result<(), Fault> {
    if !state::canonical(a, 48) {
        return Err(Fault {
            vector: if stack { 12 } else { 13 },
            error: Some(0),
            address: None,
        });
    }
    if a & (align - 1) != 0 {
        return Err(Fault::gp());
    }
    Ok(())
}
unsafe fn source(d: &Decoded, width: u8, aligned: bool, mmx: bool) -> Result<u128, Fault> {
    if let Some(r) = d.rm_register {
        return Ok(if mmx { cpu::read_mmx64s((r & 7) as i32) as u128 } else { xmm(r) });
    }
    let (a, stack) = address(d);
    if aligned {
        alignment(a, stack, 16)?;
    }
    if width == 128 {
        memory::read128(a, stack)
    }
    else {
        memory::read(a, width, stack).map(|v| v as u128)
    }
}
unsafe fn store(
    d: &Decoded,
    width: u8,
    value: u128,
    aligned: bool,
    mmx: bool,
) -> Result<(), Fault> {
    if let Some(r) = d.rm_register {
        if mmx {
            cpu::write_mmx_reg64((r & 7) as i32, value as u64);
        }
        else {
            put_xmm(r, value);
        }
        return Ok(());
    }
    let (a, stack) = address(d);
    if aligned {
        alignment(a, stack, 16)?;
    }
    if width == 128 {
        memory::write128(a, value, stack)
    }
    else {
        memory::write(a, width, value as u64, stack)
    }
}
unsafe fn gpr_source(d: &Decoded, width: u8) -> Result<u64, Fault> {
    if let Some(r) = d.rm_register {
        Ok(state::read_gpr(r as usize))
    }
    else {
        let (a, s) = address(d);
        memory::read(a, width, s)
    }
}
unsafe fn gpr_store(d: &Decoded, width: u8, v: u64) -> Result<(), Fault> {
    if let Some(r) = d.rm_register {
        state::write_gpr(r as usize, v, width);
        Ok(())
    }
    else {
        let (a, s) = address(d);
        memory::write(a, width, v, s)
    }
}
/// An unmasked SIMD floating-point exception: #XM, or #UD without CR4.OSXMMEXCPT
unsafe fn simd_fault(_: simd_fp::Unmasked) -> Fault {
    fault(if state::read_cr(4) & 0x400 != 0 { 19 } else { 6 })
}
unsafe fn arithmetic(d: &Decoded) -> Result<bool, Fault> {
    let op = d.base_opcode() as u8;
    if !matches!(
        op,
        0x51 | 0x58 | 0x59 | 0x5C..=0x5F | 0xC2 | 0x2E | 0x2F | 0x7C | 0x7D | 0xD0
    ) {
        return Ok(false);
    }
    let prefix = d.opcode >> 16;
    if matches!(op, 0x7C | 0x7D | 0xD0) && !matches!(prefix, 0x66 | 0xF2) {
        return Ok(false);
    }
    if matches!(op, 0x2E | 0x2F) && !matches!(prefix, 0 | 0x66) {
        return Ok(false);
    }
    guard(true)?;
    let scalar = matches!(prefix, 0xF2 | 0xF3) && !matches!(op, 0x7C | 0x7D | 0xD0)
        || matches!(op, 0x2E | 0x2F);
    let double = matches!(prefix, 0x66 | 0xF2) && !matches!(op, 0x7C | 0x7D | 0xD0)
        || matches!(op, 0x7C | 0x7D | 0xD0) && prefix == 0x66;
    let width = if double { 64 } else { 32 };
    let src = source(d, if scalar { width } else { 128 }, !scalar, false)?;
    let r = d.reg.unwrap();
    if matches!(op, 0x2E | 0x2F) {
        let flags = simd_fp::compare_flags(d.opcode, xmm(r), src).map_err(|e| simd_fault(e))?;
        state::write_flags64(state::read_flags64() & !0x8D5 | flags as u64);
        return Ok(true);
    }
    let imm8 = d.immediate.map_or(0, |i| i.value as u8);
    let result = simd_fp::arithmetic(d.opcode, xmm(r), src, imm8).map_err(|e| simd_fault(e))?;
    put_xmm(r, result);
    Ok(true)
}

unsafe fn conversion(d: &Decoded) -> Result<bool, Fault> {
    let op = d.opcode;
    let p = op >> 16;
    let low = op as u8;
    if !matches!(
        op,
        0x0F2A
            | 0x660F2A
            | 0xF20F2A
            | 0xF30F2A
            | 0x0F2C
            | 0x660F2C
            | 0xF20F2C
            | 0xF30F2C
            | 0x0F2D
            | 0x660F2D
            | 0xF20F2D
            | 0xF30F2D
            | 0x0F5A
            | 0x660F5A
            | 0xF20F5A
            | 0xF30F5A
            | 0x0F5B
            | 0x660F5B
            | 0xF30F5B
            | 0x660FE6
            | 0xF20FE6
            | 0xF30FE6
    ) {
        return Ok(false);
    }
    guard(true)?;
    let r = d.reg.unwrap();
    let wide = d.prefixes.w();
    let scalar = matches!(p, 0xF2 | 0xF3) && matches!(low, 0x2A | 0x2C | 0x2D | 0x5A);
    let size = if scalar {
        if p == 0xF2 {
            64
        }
        else {
            32
        }
    }
    else if matches!(op, 0x0F2A | 0x660F2A | 0x0F2C | 0x0F2D | 0x0F5A | 0xF30FE6) {
        64
    }
    else {
        128
    };
    let src = if low == 0x2A && scalar {
        gpr_source(d, if wide { 64 } else { 32 })? as u128
    }
    else {
        source(d, size, size == 128, low == 0x2A)?
    };
    let result = simd_fp::convert(op, wide, xmm(r), src).map_err(|e| simd_fault(e))?;
    if matches!(low, 0x2C | 0x2D) {
        if scalar {
            state::write_gpr(r as usize, result as u64, if wide { 64 } else { 32 });
        }
        else {
            cpu::write_mmx_reg64((r & 7) as i32, result as u64);
            cpu::transition_fpu_to_mmx();
        }
        return Ok(true);
    }
    put_xmm(r, result);
    // (CVTPI2PS/CVTPI2PD: only from an MMX register, not from memory)
    if low == 0x2A && !scalar && d.rm_register.is_some() {
        cpu::transition_fpu_to_mmx();
    }
    Ok(true)
}

unsafe fn packed_arithmetic(d: &Decoded) -> Result<bool, Fault> {
    let r = d.reg.unwrap_or(0);
    let imm = d.immediate.map_or(0, |i| i.value as i32);
    match d.opcode {
        0x0F54 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_0F54(std::mem::transmute(v), r as i32);
        },
        0x660F54 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F54(std::mem::transmute(v), r as i32);
        },
        0x0F55 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_0F55(std::mem::transmute(v), r as i32);
        },
        0x660F55 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F55(std::mem::transmute(v), r as i32);
        },
        0x0F56 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_0F56(std::mem::transmute(v), r as i32);
        },
        0x660F56 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F56(std::mem::transmute(v), r as i32);
        },
        0x0F57 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_0F57(std::mem::transmute(v), r as i32);
        },
        0x660F57 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F57(std::mem::transmute(v), r as i32);
        },
        0x0F60 => {
            guard(false)?;
            let v = source(d, 32, false, true)?;
            sem::instr_0F60(v as i32, (r & 7) as i32);
        },
        0x660F60 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F60(std::mem::transmute(v), r as i32);
        },
        0x0F61 => {
            guard(false)?;
            let v = source(d, 32, false, true)?;
            sem::instr_0F61(v as i32, (r & 7) as i32);
        },
        0x660F61 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F61(std::mem::transmute(v), r as i32);
        },
        0x0F62 => {
            guard(false)?;
            let v = source(d, 32, false, true)?;
            sem::instr_0F62(v as i32, (r & 7) as i32);
        },
        0x660F62 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F62(std::mem::transmute(v), r as i32);
        },
        0x0F63 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F63(v as u64, (r & 7) as i32);
        },
        0x660F63 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F63(std::mem::transmute(v), r as i32);
        },
        0x0F64 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F64(v as u64, (r & 7) as i32);
        },
        0x660F64 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F64(std::mem::transmute(v), r as i32);
        },
        0x0F65 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F65(v as u64, (r & 7) as i32);
        },
        0x660F65 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F65(std::mem::transmute(v), r as i32);
        },
        0x0F66 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F66(v as u64, (r & 7) as i32);
        },
        0x660F66 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F66(std::mem::transmute(v), r as i32);
        },
        0x0F67 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F67(v as u64, (r & 7) as i32);
        },
        0x660F67 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F67(std::mem::transmute(v), r as i32);
        },
        0x0F68 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F68(v as u64, (r & 7) as i32);
        },
        0x660F68 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F68(std::mem::transmute(v), r as i32);
        },
        0x0F69 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F69(v as u64, (r & 7) as i32);
        },
        0x660F69 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F69(std::mem::transmute(v), r as i32);
        },
        0x0F6A => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F6A(v as u64, (r & 7) as i32);
        },
        0x660F6A => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F6A(std::mem::transmute(v), r as i32);
        },
        0x0F6B => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F6B(v as u64, (r & 7) as i32);
        },
        0x660F6B => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F6B(std::mem::transmute(v), r as i32);
        },
        0x660F6C => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F6C(std::mem::transmute(v), r as i32);
        },
        0x660F6D => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F6D(std::mem::transmute(v), r as i32);
        },
        0x0F70 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F70(v as u64, (r & 7) as i32, imm);
        },
        0x660F70 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F70(std::mem::transmute(v), r as i32, imm);
        },
        0xF20F70 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_F20F70(std::mem::transmute(v), r as i32, imm);
        },
        0xF30F70 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_F30F70(std::mem::transmute(v), r as i32, imm);
        },
        0x0F74 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F74(v as u64, (r & 7) as i32);
        },
        0x660F74 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F74(std::mem::transmute(v), r as i32);
        },
        0x0F75 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F75(v as u64, (r & 7) as i32);
        },
        0x660F75 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F75(std::mem::transmute(v), r as i32);
        },
        0x0F76 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0F76(v as u64, (r & 7) as i32);
        },
        0x660F76 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660F76(std::mem::transmute(v), r as i32);
        },
        0x0FC6 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_0FC6(std::mem::transmute(v), r as i32, imm);
        },
        0x660FC6 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FC6(std::mem::transmute(v), r as i32, imm);
        },
        0x0FD1 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD1(v as u64, (r & 7) as i32);
        },
        0x660FD1 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD1(std::mem::transmute(v), r as i32);
        },
        0x0FD2 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD2(v as u64, (r & 7) as i32);
        },
        0x660FD2 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD2(std::mem::transmute(v), r as i32);
        },
        0x0FD3 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD3(v as u64, (r & 7) as i32);
        },
        0x660FD3 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD3(std::mem::transmute(v), r as i32);
        },
        0x0FD4 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD4(v as u64, (r & 7) as i32);
        },
        0x660FD4 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD4(std::mem::transmute(v), r as i32);
        },
        0x0FD5 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD5(v as u64, (r & 7) as i32);
        },
        0x660FD5 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD5(std::mem::transmute(v), r as i32);
        },
        0x0FD8 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD8(v as u64, (r & 7) as i32);
        },
        0x660FD8 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD8(std::mem::transmute(v), r as i32);
        },
        0x0FD9 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FD9(v as u64, (r & 7) as i32);
        },
        0x660FD9 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FD9(std::mem::transmute(v), r as i32);
        },
        0x0FDA => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDA(v as u64, (r & 7) as i32);
        },
        0x660FDA => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDA(std::mem::transmute(v), r as i32);
        },
        0x0FDB => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDB(v as u64, (r & 7) as i32);
        },
        0x660FDB => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDB(std::mem::transmute(v), r as i32);
        },
        0x0FDC => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDC(v as u64, (r & 7) as i32);
        },
        0x660FDC => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDC(std::mem::transmute(v), r as i32);
        },
        0x0FDD => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDD(v as u64, (r & 7) as i32);
        },
        0x660FDD => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDD(std::mem::transmute(v), r as i32);
        },
        0x0FDE => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDE(v as u64, (r & 7) as i32);
        },
        0x660FDE => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDE(std::mem::transmute(v), r as i32);
        },
        0x0FDF => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FDF(v as u64, (r & 7) as i32);
        },
        0x660FDF => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FDF(std::mem::transmute(v), r as i32);
        },
        0x0FE0 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE0(v as u64, (r & 7) as i32);
        },
        0x660FE0 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE0(std::mem::transmute(v), r as i32);
        },
        0x0FE1 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE1(v as u64, (r & 7) as i32);
        },
        0x660FE1 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE1(std::mem::transmute(v), r as i32);
        },
        0x0FE2 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE2(v as u64, (r & 7) as i32);
        },
        0x660FE2 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE2(std::mem::transmute(v), r as i32);
        },
        0x0FE3 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE3(v as u64, (r & 7) as i32);
        },
        0x660FE3 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE3(std::mem::transmute(v), r as i32);
        },
        0x0FE4 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE4(v as u64, (r & 7) as i32);
        },
        0x660FE4 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE4(std::mem::transmute(v), r as i32);
        },
        0x0FE5 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE5(v as u64, (r & 7) as i32);
        },
        0x660FE5 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE5(std::mem::transmute(v), r as i32);
        },
        0x0FE8 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE8(v as u64, (r & 7) as i32);
        },
        0x660FE8 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE8(std::mem::transmute(v), r as i32);
        },
        0x0FE9 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FE9(v as u64, (r & 7) as i32);
        },
        0x660FE9 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FE9(std::mem::transmute(v), r as i32);
        },
        0x0FEA => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FEA(v as u64, (r & 7) as i32);
        },
        0x660FEA => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FEA(std::mem::transmute(v), r as i32);
        },
        0x0FEB => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FEB(v as u64, (r & 7) as i32);
        },
        0x660FEB => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FEB(std::mem::transmute(v), r as i32);
        },
        0x0FEC => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FEC(v as u64, (r & 7) as i32);
        },
        0x660FEC => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FEC(std::mem::transmute(v), r as i32);
        },
        0x0FED => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FED(v as u64, (r & 7) as i32);
        },
        0x660FED => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FED(std::mem::transmute(v), r as i32);
        },
        0x0FEE => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FEE(v as u64, (r & 7) as i32);
        },
        0x660FEE => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FEE(std::mem::transmute(v), r as i32);
        },
        0x0FEF => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FEF(v as u64, (r & 7) as i32);
        },
        0x660FEF => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FEF(std::mem::transmute(v), r as i32);
        },
        0x0FF1 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF1(v as u64, (r & 7) as i32);
        },
        0x660FF1 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF1(std::mem::transmute(v), r as i32);
        },
        0x0FF2 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF2(v as u64, (r & 7) as i32);
        },
        0x660FF2 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF2(std::mem::transmute(v), r as i32);
        },
        0x0FF3 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF3(v as u64, (r & 7) as i32);
        },
        0x660FF3 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF3(std::mem::transmute(v), r as i32);
        },
        0x0FF4 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF4(v as u64, (r & 7) as i32);
        },
        0x660FF4 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF4(std::mem::transmute(v), r as i32);
        },
        0x0FF5 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF5(v as u64, (r & 7) as i32);
        },
        0x660FF5 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF5(std::mem::transmute(v), r as i32);
        },
        0x0FF6 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF6(v as u64, (r & 7) as i32);
        },
        0x660FF6 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF6(std::mem::transmute(v), r as i32);
        },
        0x0FF8 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF8(v as u64, (r & 7) as i32);
        },
        0x660FF8 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF8(std::mem::transmute(v), r as i32);
        },
        0x0FF9 => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FF9(v as u64, (r & 7) as i32);
        },
        0x660FF9 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FF9(std::mem::transmute(v), r as i32);
        },
        0x0FFA => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FFA(v as u64, (r & 7) as i32);
        },
        0x660FFA => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FFA(std::mem::transmute(v), r as i32);
        },
        0x0FFB => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FFB(v as u64, (r & 7) as i32);
        },
        0x660FFB => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FFB(std::mem::transmute(v), r as i32);
        },
        0x0FFC => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FFC(v as u64, (r & 7) as i32);
        },
        0x660FFC => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FFC(std::mem::transmute(v), r as i32);
        },
        0x0FFD => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FFD(v as u64, (r & 7) as i32);
        },
        0x660FFD => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FFD(std::mem::transmute(v), r as i32);
        },
        0x0FFE => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            sem::instr_0FFE(v as u64, (r & 7) as i32);
        },
        0x660FFE => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            sem::instr_660FFE(std::mem::transmute(v), r as i32);
        },
        _ => return Ok(false),
    }
    Ok(true)
}

unsafe fn moves(d: &Decoded) -> Result<bool, Fault> {
    let r = d.reg.unwrap_or(0);
    let op = d.opcode;
    let b = op as u8;
    let p = op >> 16;
    let register_only = matches!(
        op,
        0xF20FD6
            | 0xF30FD6
            | 0x0F50
            | 0x660F50
            | 0x0FD7
            | 0x660FD7
            | 0x0FC5
            | 0x660FC5
            | 0x0FF7
            | 0x660FF7
    );
    let memory_only = matches!(
        op,
        0x0F2B
            | 0x660F2B
            | 0x660FE7
            | 0x0FE7
            | 0x0F13
            | 0x660F13
            | 0x0F17
            | 0x660F17
            | 0x660F12
            | 0x660F16
            | 0xF20FF0
    );
    if register_only && d.rm_register.is_none() || memory_only && d.address.is_none() {
        return Err(Fault::ud());
    }
    match op {
        0x0F10 | 0x660F10 | 0x0F28 | 0x660F28 | 0x660F6F | 0xF30F6F | 0xF20FF0 => {
            guard(true)?;
            let v = source(d, 128, matches!(b, 0x28 | 0x6F) && p != 0xF3, false)?;
            put_xmm(r, v);
        },
        0x0F11 | 0x660F11 | 0x0F29 | 0x660F29 | 0x660F7F | 0xF30F7F | 0x0F2B | 0x660F2B
        | 0x660FE7 => {
            guard(true)?;
            store(
                d,
                128,
                xmm(r),
                matches!(b, 0x29 | 0x2B | 0xE7) || op == 0x660F7F,
                false,
            )?;
        },
        0xF20F10 | 0xF30F10 => {
            guard(true)?;
            let width = if p == 0xF2 { 64 } else { 32 };
            let mask = (1u128 << width) - 1;
            let v = source(d, width, false, false)? & mask;
            put_xmm(
                r,
                if d.rm_register.is_some() { xmm(r) & !mask | v } else { v },
            );
        },
        0xF20F11 | 0xF30F11 => {
            guard(true)?;
            let width = if p == 0xF2 { 64 } else { 32 };
            let mask = (1u128 << width) - 1;
            let v = xmm(r) & mask;
            if let Some(dst) = d.rm_register {
                put_xmm(dst, xmm(dst) & !mask | v);
            }
            else {
                store(d, width, v, false, false)?;
            }
        },
        0x0F12 | 0x660F12 | 0x0F16 | 0x660F16 | 0xF20F12 => {
            guard(true)?;
            let src = source(d, 64, false, false)?;
            let value = if op == 0x0F12 && d.rm_register.is_some() {
                src >> 64
            }
            else {
                src & u64::MAX as u128
            };
            let old = xmm(r);
            put_xmm(
                r,
                if op == 0xF20F12 {
                    value | value << 64
                }
                else if b == 0x16 {
                    old & u64::MAX as u128 | value << 64
                }
                else {
                    old & !(u64::MAX as u128) | value
                },
            );
        },
        0x0F13 | 0x660F13 | 0x0F17 | 0x660F17 => {
            guard(true)?;
            store(
                d,
                64,
                xmm(r) >> if b == 0x17 { 64 } else { 0 },
                false,
                false,
            )?;
        },
        0xF30F12 | 0xF30F16 => {
            // MOVSLDUP/MOVSHDUP: an aligned m128 (SDM exception type 4; QEMU
            // too), unlike MOVDDUP's m64
            guard(true)?;
            let v = source(d, 128, true, false)?;
            let first = if b == 0x12 { 0 } else { 32 };
            let lo = (v >> first) & u32::MAX as u128;
            let hi = (v >> (first + 64)) & u32::MAX as u128;
            put_xmm(r, lo | lo << 32 | hi << 64 | hi << 96);
        },
        0x0F14 | 0x660F14 | 0x0F15 | 0x660F15 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            let a = xmm(r);
            let width = if p == 0x66 { 64 } else { 32 };
            let n = 128 / width;
            let base = if b == 0x15 { n / 2 } else { 0 };
            let mask = (1u128 << width) - 1;
            let mut out = 0;
            for i in 0..n / 2 {
                out |= ((a >> ((base + i) * width)) & mask) << (i * 2 * width);
                out |= ((v >> ((base + i) * width)) & mask) << ((i * 2 + 1) * width);
            }
            put_xmm(r, out);
        },
        0x0F6E | 0x660F6E => {
            guard(p == 0x66)?;
            let v = gpr_source(d, if d.prefixes.w() { 64 } else { 32 })?
                & if d.prefixes.w() { u64::MAX } else { u32::MAX as u64 };
            if p == 0x66 {
                put_xmm(r, v as u128);
            }
            else {
                cpu::write_mmx_reg64((r & 7) as i32, v);
                cpu::transition_fpu_to_mmx();
            }
        },
        0x0F7E | 0x660F7E => {
            guard(p == 0x66)?;
            let v = if p == 0x66 { xmm(r) as u64 } else { cpu::read_mmx64s((r & 7) as i32) };
            gpr_store(d, if d.prefixes.w() { 64 } else { 32 }, v)?;
            if p == 0 {
                cpu::transition_fpu_to_mmx();
            }
        },
        0xF30F7E => {
            guard(true)?;
            let v = source(d, 64, false, false)?;
            put_xmm(r, v & u64::MAX as u128);
        },
        0x660FD6 => {
            guard(true)?;
            let v = xmm(r) & u64::MAX as u128;
            store(d, 64, v, false, false)?;
        },
        0xF20FD6 => {
            guard(true)?;
            cpu::write_mmx_reg64((r & 7) as i32, xmm(d.rm_register.unwrap()) as u64);
            cpu::transition_fpu_to_mmx();
        },
        0xF30FD6 => {
            guard(true)?;
            put_xmm(
                r,
                cpu::read_mmx64s((d.rm_register.unwrap() & 7) as i32) as u128,
            );
            cpu::transition_fpu_to_mmx();
        },
        0x0F6F => {
            guard(false)?;
            let v = source(d, 64, false, true)?;
            cpu::write_mmx_reg64((r & 7) as i32, v as u64);
            cpu::transition_fpu_to_mmx();
        },
        0x0F7F | 0x0FE7 => {
            guard(false)?;
            if b == 0xE7 && address(d).0 & 7 != 0 {
                return Err(Fault::gp());
            }
            store(d, 64, cpu::read_mmx64s((r & 7) as i32) as u128, false, true)?;
            cpu::transition_fpu_to_mmx();
        },
        0x0F50 | 0x660F50 | 0x0FD7 | 0x660FD7 => {
            let mmx = op == 0x0FD7;
            guard(!mmx)?;
            let v = source(d, if mmx { 64 } else { 128 }, false, mmx)?;
            let width = if b == 0xD7 {
                8
            }
            else if p == 0x66 {
                64
            }
            else {
                32
            };
            let n = if mmx { 64 } else { 128 } / width;
            let mut out = 0;
            for i in 0..n {
                out |= ((v >> (i * width + width - 1)) as u64 & 1) << i;
            }
            state::write_gpr(r as usize, out, 32);
            if mmx {
                cpu::transition_fpu_to_mmx();
            }
        },
        0x0FC4 | 0x660FC4 => {
            let mmx = p == 0;
            guard(!mmx)?;
            let v = gpr_source(d, 16)? as u16 as u128;
            let at = (d.immediate.unwrap().value & if mmx { 3 } else { 7 }) * 16;
            let old = if mmx { cpu::read_mmx64s((r & 7) as i32) as u128 } else { xmm(r) };
            let out = old & !(0xFFFFu128 << at) | v << at;
            if mmx {
                cpu::write_mmx_reg64((r & 7) as i32, out as u64);
                cpu::transition_fpu_to_mmx();
            }
            else {
                put_xmm(r, out);
            }
        },
        0x0FC5 | 0x660FC5 => {
            let mmx = p == 0;
            guard(!mmx)?;
            let v = source(d, if mmx { 64 } else { 128 }, false, mmx)?;
            let at = (d.immediate.unwrap().value & if mmx { 3 } else { 7 }) * 16;
            state::write_gpr(r as usize, (v >> at) as u64 & 0xFFFF, 32);
            if mmx {
                cpu::transition_fpu_to_mmx();
            }
        },
        0x0FF7 | 0x660FF7 => {
            let mmx = p == 0;
            guard(!mmx)?;
            let mask = source(d, if mmx { 64 } else { 128 }, false, mmx)?;
            let value = if mmx { cpu::read_mmx64s((r & 7) as i32) as u128 } else { xmm(r) };
            let seg = d.prefixes.segment.unwrap_or(3);
            let base = if seg >= 4 { state::read_segment_base(seg as usize) } else { 0 };
            let off = state::read_gpr(7);
            let off = if d.address_size == 32 { off as u32 as u64 } else { off };
            let a = off.wrapping_add(base);
            for i in 0..if mmx { 8 } else { 16 } {
                if mask >> (i * 8 + 7) & 1 != 0 {
                    memory::probe_write(a.wrapping_add(i), 8, false)?;
                }
            }
            for i in 0..if mmx { 8 } else { 16 } {
                if mask >> (i * 8 + 7) & 1 != 0 {
                    memory::write(a.wrapping_add(i), 8, (value >> (i * 8)) as u64, false)?;
                }
            }
            if mmx {
                cpu::transition_fpu_to_mmx();
            }
        },
        0x0F77 => {
            guard(false)?;
            *gp::fpu_stack_empty = 0xFF;
        },
        0x0F52 | 0x0F53 | 0xF30F52 | 0xF30F53 => {
            guard(true)?;
            let scalar = p == 0xF3;
            let src = source(d, if scalar { 32 } else { 128 }, !scalar, false)?;
            put_xmm(r, simd_fp::reciprocal(d.opcode, xmm(r), src));
        },
        _ => return Ok(false),
    }
    Ok(true)
}
unsafe fn immediate_shift(d: &Decoded) -> Result<bool, Fault> {
    if !matches!(
        d.opcode,
        0x0F71 | 0x0F72 | 0x0F73 | 0x660F71 | 0x660F72 | 0x660F73
    ) {
        return Ok(false);
    }
    let mmx = d.opcode >> 16 == 0;
    guard(!mmx)?;
    let r = d.rm_register.ok_or_else(Fault::ud)?;
    let group = d.modrm.unwrap() >> 3 & 7;
    let n = d.immediate.unwrap().value;
    let op = d.opcode as u8;
    let mut value = if mmx { cpu::read_mmx64s((r & 7) as i32) as u128 } else { xmm(r) };
    if op == 0x73 && matches!(group, 3 | 7) && !mmx {
        value = if n >= 16 {
            0
        }
        else if group == 3 {
            value >> (n * 8)
        }
        else {
            value << (n * 8)
        };
    }
    else {
        let width = match op {
            0x71 => 16,
            0x72 => 32,
            _ => 64,
        };
        let count = if mmx { 64 } else { 128 } / width;
        let mask = (1u128 << width) - 1;
        let mut out = 0;
        for i in 0..count {
            let lane = (value >> (i * width)) & mask;
            let shifted = match group {
                2 => {
                    if n >= width {
                        0
                    }
                    else {
                        lane >> n
                    }
                },
                6 => {
                    if n >= width {
                        0
                    }
                    else {
                        lane << n
                    }
                },
                4 if width < 64 => {
                    let signed = ((lane as u64) << (64 - width)) as i64 >> (64 - width);
                    (signed >> (n.min(width - 1))) as u64 as u128
                },
                _ => return Err(Fault::ud()),
            };
            out |= (shifted & mask) << (i * width);
        }
        value = out;
    }
    if mmx {
        cpu::write_mmx_reg64((r & 7) as i32, value as u64);
        cpu::transition_fpu_to_mmx();
    }
    else {
        put_xmm(r, value);
    }
    Ok(true)
}

unsafe fn bytes_read(a: u64, n: usize, stack: bool) -> Result<Vec<u8>, Fault> {
    for i in 0..n {
        memory::probe_read(a.wrapping_add(i as u64), 8, stack)?;
    }
    let mut v = vec![0; n];
    for (i, b) in v.iter_mut().enumerate() {
        *b = memory::read(a.wrapping_add(i as u64), 8, stack)? as u8;
    }
    Ok(v)
}
unsafe fn bytes_write(a: u64, data: &[u8], stack: bool) -> Result<(), Fault> {
    for i in 0..data.len() {
        memory::probe_write(a.wrapping_add(i as u64), 8, stack)?;
    }
    for (i, b) in data.iter().enumerate() {
        memory::write(a.wrapping_add(i as u64), 8, *b as u64, stack)?;
    }
    Ok(())
}
fn u16_at(v: &[u8], at: usize) -> u16 { u16::from_le_bytes(v[at..at + 2].try_into().unwrap()) }
fn u32_at(v: &[u8], at: usize) -> u32 { u32::from_le_bytes(v[at..at + 4].try_into().unwrap()) }
fn u64_at(v: &[u8], at: usize) -> u64 { u64::from_le_bytes(v[at..at + 8].try_into().unwrap()) }
/// An XSAVE or FXSAVE area at a checked linear address (cpu::xstate::Area)
struct Area {
    a: u64,
    stack: bool,
}
impl xstate::Area for Area {
    type Fault = Fault;
    unsafe fn check(&mut self, offset: u32, length: u32, write: bool) -> Result<(), Fault> {
        // (a field is shorter than a page: its first byte and, when it
        // crosses into the next page, that page's first byte cover it, which
        // a page fault reports in CR2)
        let first = self.a.wrapping_add(offset as u64);
        let last = first.wrapping_add(length as u64 - 1);
        let next = (last >> 12 != first >> 12).then_some(last & !0xFFF);
        for at in std::iter::once(first).chain(next) {
            if write {
                memory::probe_write(at, 8, self.stack)?;
            }
            else {
                memory::probe_read(at, 8, self.stack)?;
            }
        }
        Ok(())
    }
    unsafe fn read(&mut self, offset: u32, bytes: &mut [u8]) {
        let value = memory::read(
            self.a.wrapping_add(offset as u64),
            bytes.len() as u8 * 8,
            self.stack,
        )
        .unwrap();
        bytes.copy_from_slice(&value.to_le_bytes()[..bytes.len()]);
    }
    unsafe fn write(&mut self, offset: u32, bytes: &[u8]) {
        let mut value = [0; 8];
        value[..bytes.len()].copy_from_slice(bytes);
        let at = self.a.wrapping_add(offset as u64);
        memory::write(
            at,
            bytes.len() as u8 * 8,
            u64::from_le_bytes(value),
            self.stack,
        )
        .unwrap();
    }
    unsafe fn gp(&mut self) -> Fault { Fault::gp() }
}
unsafe fn fxstate(d: &Decoded) -> Result<bool, Fault> {
    if d.base_opcode() != 0x0FAE {
        return Ok(false);
    }
    let group = d.modrm.unwrap() >> 3 & 7;
    if d.rm_register.is_some() {
        // LFENCE, MFENCE, SFENCE ignore the r/m field
        return Ok(group >= 5);
    }
    if group == 7 {
        let (a, s) = address(d);
        memory::probe_read(a, 8, s)?;
        return Ok(true); // CLFLUSH: guest caches share the coherent RAM image.
    }
    // (XSAVEOPT: CPUID.(EAX=0DH,ECX=1):EAX[0])
    if group == 6 && !crate::cpu::features::has(crate::cpu::features::XSAVEOPT) {
        return Ok(false);
    }
    // XSAVE and XRSTOR: #UD without CR4.OSXSAVE before #NM
    if group >= 4 && !xstate::enabled() {
        return Err(Fault::ud());
    }
    if state::read_cr(0) & 8 != 0 {
        return Err(fault(7));
    }
    let (a, s) = address(d);
    if group == 2 || group == 3 {
        guard(true)?;
        if group == 2 {
            let v = memory::read(a, 32, s)? as u32;
            if v & !(cpu::MXCSR_MASK as u32) != 0 {
                return Err(Fault::gp());
            }
            *gp::mxcsr = v as i32;
        }
        else {
            memory::write(a, 32, *gp::mxcsr as u32 as u64, s)?;
        }
        return Ok(true);
    }
    alignment(a, s, if group >= 4 { 64 } else { 16 })?;
    // the 64-bit format with REX.W; XMM8-15 and YMM8-15 in 64-bit mode
    let format = xstate::Format {
        wide: d.prefixes.w(),
        long: d.mode.is_long(),
    };
    let area = &mut Area { a, stack: s };
    let rfbm = || xstate::requested(state::read_gpr(2) as u32, state::read_gpr(0) as u32);
    match group {
        0 => xstate::fxsave(area, format)?,
        1 => xstate::fxrstor(area, format)?,
        4 => xstate::xsave(area, rfbm(), format)?,
        6 => xstate::xsaveopt(area, rfbm(), format)?,
        _ => xstate::xrstor(area, rfbm(), format)?,
    }
    Ok(true)
}
/// XRSTORS (0F C7 /3), XSAVEC (/4) and XSAVES (/5) on memory, without a
/// mandatory prefix: XSAVE's checks and their order (#UD without
/// CR4.OSXSAVE, #NM, #GP(0) unless aligned to 64 bytes), and #GP(0) for CPL
/// > 0 before the operand for XRSTORS and XSAVES; the 64-bit forms with REX.W
pub(super) unsafe fn compacted_state(d: &Decoded, group: u8) -> Result<(), Fault> {
    if d.rm_register.is_some() || d.prefixes.operand || d.prefixes.rep.is_some() {
        return Err(Fault::ud());
    }
    if !xstate::enabled() {
        return Err(Fault::ud());
    }
    if state::read_cr(0) & 8 != 0 {
        return Err(fault(7));
    }
    if group != 4 && *gp::cpl != 0 {
        return Err(Fault::gp());
    }
    let (a, s) = address(d);
    alignment(a, s, 64)?;
    let format = xstate::Format {
        wide: d.prefixes.w(),
        long: d.mode.is_long(),
    };
    let area = &mut Area { a, stack: s };
    let (edx, eax) = (state::read_gpr(2) as u32, state::read_gpr(0) as u32);
    match group {
        3 => xstate::xrstors(area, xstate::requested_supervisor(edx, eax), format),
        4 => xstate::xsavec(area, xstate::requested(edx, eax), format),
        _ => xstate::xsaves(area, xstate::requested_supervisor(edx, eax), format),
    }
}
unsafe fn x87_environment(d: &Decoded, restore: bool, registers: bool) -> Result<(), Fault> {
    let (a, s) = address(d);
    let short = d.prefixes.operand;
    let env = if short { 14 } else { 28 };
    let size = env + if registers { 80 } else { 0 };
    fpu::fpu_cache_barrier();
    if restore {
        let v = bytes_read(a, size, s)?;
        let step = if short { 2 } else { 4 };
        fpu::set_control_word(u16_at(&v, 0));
        fpu::fpu_set_status_word(u16_at(&v, step));
        fpu::fpu_set_tag_word(u16_at(&v, step * 2) as i32);
        *gp::fpu_ip = if short { u16_at(&v, 6) as i32 } else { u32_at(&v, 12) as i32 };
        *gp::fpu_dp = if short { u16_at(&v, 10) as i32 } else { u32_at(&v, 20) as i32 };
        *gp::x64_fpu_ip_hi = 0;
        *gp::x64_fpu_dp_hi = 0;
        *gp::fpu_ip_selector = u16_at(&v, if short { 8 } else { 16 }) as i32;
        *gp::fpu_dp_selector = u16_at(&v, if short { 12 } else { 24 }) as i32;
        if !short {
            *gp::fpu_opcode = u16_at(&v, 18) as i32 & 0x7FF;
        }
        if registers {
            for i in 0..8 {
                fpu::fpu_write_st(
                    ((i + *gp::fpu_stack_ptr as usize) & 7) as i32,
                    F80 {
                        mantissa: u64_at(&v, env + i * 10),
                        sign_exponent: u16_at(&v, env + i * 10 + 8),
                    },
                );
            }
        }
    }
    else {
        let mut v = vec![0xFF; size];
        let step = if short { 2 } else { 4 };
        v[0..2].copy_from_slice(&(*gp::fpu_control_word).to_le_bytes());
        v[step..step + 2].copy_from_slice(&fpu::fpu_load_status_word().to_le_bytes());
        v[step * 2..step * 2 + 2].copy_from_slice(&(fpu::fpu_load_tag_word() as u16).to_le_bytes());
        if short {
            v[6..8].copy_from_slice(&(*gp::fpu_ip as u16).to_le_bytes());
            v[8..10].copy_from_slice(&(*gp::fpu_ip_selector as u16).to_le_bytes());
            v[10..12].copy_from_slice(&(*gp::fpu_dp as u16).to_le_bytes());
            v[12..14].copy_from_slice(&(*gp::fpu_dp_selector as u16).to_le_bytes());
        }
        else {
            v[12..16].copy_from_slice(&(*gp::fpu_ip as u32).to_le_bytes());
            v[16..18].copy_from_slice(&(*gp::fpu_ip_selector as u16).to_le_bytes());
            v[18..20].copy_from_slice(&(*gp::fpu_opcode as u16).to_le_bytes());
            v[20..24].copy_from_slice(&(*gp::fpu_dp as u32).to_le_bytes());
            v[24..26].copy_from_slice(&(*gp::fpu_dp_selector as u16).to_le_bytes());
        }
        if registers {
            for i in 0..8 {
                let f = *gp::fpu_st.add((i + *gp::fpu_stack_ptr as usize) & 7);
                v[env + i * 10..env + i * 10 + 8].copy_from_slice(&f.mantissa.to_le_bytes());
                v[env + i * 10 + 8..env + i * 10 + 10]
                    .copy_from_slice(&f.sign_exponent.to_le_bytes());
            }
        }
        bytes_write(a, &v, s)?;
        if registers {
            fpu::fpu_finit();
        }
        else {
            fpu::set_control_word(*gp::fpu_control_word | 63);
        }
    }
    Ok(())
}

// Legacy callers may select approximate x87 host arithmetic. Long mode keeps
// architectural rounding and exception delivery irrespective of that policy.
struct X87Strict {
    old_fast: bool,
    old_flags: u8,
}
impl X87Strict {
    unsafe fn new() -> Self {
        let old_fast = crate::softfloat::x87_fast_math();
        let old_flags = softfloat_exceptionFlags;
        if old_fast {
            crate::softfloat::set_x87_fast_math(false);
        }
        softfloat_exceptionFlags = 0;
        Self {
            old_fast,
            old_flags,
        }
    }
}
impl Drop for X87Strict {
    fn drop(&mut self) {
        unsafe {
            softfloat_exceptionFlags = self.old_flags;
            if self.old_fast {
                crate::softfloat::set_x87_fast_math(true);
            }
        }
    }
}
unsafe fn x87_exception_flags() -> u16 {
    let f = softfloat_exceptionFlags as u16;
    (f >> 4 & 1) | (f >> 1 & 4) | (f << 1 & 8) | (f << 3 & 16) | (f << 5 & 32)
}
unsafe fn x87_pending() -> bool { *gp::fpu_status_word & !*gp::fpu_control_word & 63 != 0 }
unsafe fn x87_memory(d: &Decoded, group: u8) -> Result<(), Fault> {
    let op = d.base_opcode() as u8;
    let (a, s) = address(d);
    if matches!(op, 0xD8 | 0xDA | 0xDC | 0xDE) {
        let width = match op {
            0xD8 | 0xDA => 32,
            0xDC => 64,
            _ => 16,
        };
        let raw = memory::read(a, width, s)?;
        F80::clear_exception_flags();
        let value = match op {
            0xD8 => F80::of_f32(raw as i32),
            0xDC => F80::of_f64(raw),
            0xDA => F80::of_i32(raw as i32),
            _ => F80::of_i32(raw as i16 as i32),
        };
        *gp::fpu_status_word |= x87_exception_flags();
        match group {
            0 => fpu::fpu_fadd(0, value),
            1 => fpu::fpu_fmul(0, value),
            2 => fpu::fpu_fcom(value),
            3 => fpu::fpu_fcomp(value),
            4 => fpu::fpu_fsub(0, value),
            5 => fpu::fpu_fsubr(0, value),
            6 => fpu::fpu_fdiv(0, value),
            7 => fpu::fpu_fdivr(0, value),
            _ => unreachable!(),
        }
        return Ok(());
    }
    if op == 0xD9 && matches!(group, 4 | 6) {
        return x87_environment(d, group == 4, false);
    }
    if op == 0xDD && matches!(group, 4 | 6) {
        return x87_environment(d, group == 4, true);
    }
    if op == 0xD9 && group == 5 {
        let cw = memory::read(a, 16, s)?;
        fpu::set_control_word(cw as u16);
        return Ok(());
    }
    if op == 0xD9 && group == 7 {
        return memory::write(a, 16, *gp::fpu_control_word as u64, s);
    }
    if op == 0xDD && group == 7 {
        return memory::write(a, 16, fpu::fpu_load_status_word() as u64, s);
    }
    let load = group == 0 || op == 0xDB && group == 5 || op == 0xDF && matches!(group, 4 | 5);
    if load {
        let value = if op == 0xDB && group == 5 {
            let v = bytes_read(a, 10, s)?;
            F80 {
                mantissa: u64_at(&v, 0),
                sign_exponent: u16_at(&v, 8),
            }
        }
        else if op == 0xDF && group == 4 {
            let v = bytes_read(a, 10, s)?;
            let mut n = 0i64;
            for i in (0..9).rev() {
                n = n * 100 + (v[i] >> 4) as i64 * 10 + (v[i] & 15) as i64;
            }
            if v[9] & 128 != 0 {
                n = -n;
            }
            F80::of_i64(n)
        }
        else {
            let width = match (op, group) {
                (0xD9, _) | (0xDB, _) => 32,
                (0xDD, _) | (0xDF, 5) => 64,
                _ => 16,
            };
            let raw = memory::read(a, width, s)?;
            F80::clear_exception_flags();
            let v = match op {
                0xD9 => F80::of_f32(raw as i32),
                0xDD => F80::of_f64(raw),
                0xDB => F80::of_i32(raw as i32),
                _ => F80::of_i64(if width == 16 { raw as i16 as i64 } else { raw as i64 }),
            };
            *gp::fpu_status_word |= x87_exception_flags();
            v
        };
        fpu::fpu_push(value);
        return Ok(());
    }
    let width = match (op, group) {
        (0xD9, 2 | 3) | (0xDB, 1..=3) => 32,
        (0xDD, 1..=3) | (0xDF, 7) => 64,
        (0xDF, 1..=3) => 16,
        (0xDB, 7) | (0xDF, 6) => 80,
        _ => return Err(Fault::ud()),
    };
    for i in 0..width / 8 {
        memory::probe_write(a.wrapping_add(i as u64), 8, s)?;
    }
    let v = fpu::fpu_get_st0();
    F80::clear_exception_flags();
    let raw = if op == 0xD9 {
        extF80M_to_f32(&v) as u32 as u64
    }
    else if op == 0xDD && group != 1 {
        extF80M_to_f64(&v)
    }
    else if width == 80 {
        0
    }
    else {
        let rounding = if group == 1 { 1 } else { softfloat_roundingMode };
        if width == 64 {
            extF80M_to_i64(&v, rounding, true) as u64
        }
        else {
            let integer = extF80M_to_i32(&v, rounding, true);
            if width == 16 && (integer < i16::MIN as i32 || integer > i16::MAX as i32) {
                softfloat_exceptionFlags |= 16;
                0x8000
            }
            else {
                integer as u32 as u64
            }
        }
    };
    *gp::fpu_status_word |= x87_exception_flags();
    if width == 80 {
        let mut data = vec![0; 10];
        if op == 0xDF {
            let integer = extF80M_to_i64(&v, softfloat_roundingMode, true);
            *gp::fpu_status_word |= x87_exception_flags();
            let mut n = integer.unsigned_abs();
            if n > 999_999_999_999_999_999 {
                *gp::fpu_status_word |= 1;
                data[7] = 0xC0;
                data[8] = 0xFF;
                data[9] = 0xFF;
            }
            else {
                for byte in &mut data[..9] {
                    *byte = (n % 10) as u8;
                    n /= 10;
                    *byte |= ((n % 10) as u8) << 4;
                    n /= 10;
                }
                data[9] = if integer < 0 { 128 } else { 0 };
            }
        }
        else {
            data[..8].copy_from_slice(&v.mantissa.to_le_bytes());
            data[8..].copy_from_slice(&v.sign_exponent.to_le_bytes());
        }
        if !x87_pending() {
            bytes_write(a, &data, s)?;
        }
    }
    else if !x87_pending() {
        memory::write(a, width, raw, s)?;
    }
    if !x87_pending() && (group == 1 || group == 3 || width == 80 || op == 0xDF && group == 7) {
        fpu::fpu_pop();
    }
    Ok(())
}
unsafe fn x87(d: &Decoded) -> Result<bool, Fault> {
    let op = d.base_opcode();
    if op == 0x9B {
        if state::read_cr(0) & 10 == 10 {
            return Err(fault(7));
        }
        if x87_pending() {
            return Err(fault(16));
        }
        return Ok(true);
    }
    if !(0xD8..=0xDF).contains(&op) {
        return Ok(false);
    }
    if state::read_cr(0) & 12 != 0 {
        return Err(fault(7));
    }
    let m = d.modrm.unwrap();
    let group = m >> 3 & 7;
    let r = (m & 7) as i32;
    let no_wait = op == 0xDB && matches!(m, 0xE2 | 0xE3)
        || d.address.is_some()
            && (op == 0xD9 && matches!(group, 6 | 7) || op == 0xDD && matches!(group, 6 | 7))
        || op == 0xDF && m == 0xE0;
    if !no_wait && x87_pending() {
        return Err(fault(16));
    }
    let _strict = X87Strict::new();
    fpu::fpu_cache_barrier();
    let old_top = *gp::fpu_stack_ptr;
    let old_status = *gp::fpu_status_word;
    let old_empty = *gp::fpu_stack_empty;
    let old_flags = state::read_flags64();
    let old_regs = std::ptr::read(gp::fpu_st as *const [F80; 8]);
    if d.address.is_some() {
        x87_memory(d, group)?;
    }
    else {
        let valid = match op {
            0xD9 => match group {
                2 => r == 0,
                4 => matches!(r, 0 | 1 | 4 | 5),
                5 => r < 7,
                _ => true,
            },
            0xDA => group < 4 || group == 5 && r == 1,
            0xDB => group < 4 || group == 4 && r < 5 || matches!(group, 5 | 6),
            0xDD => group < 6,
            0xDE => group != 3 || r == 1,
            0xDF => group < 4 || group == 4 && r == 0 || matches!(group, 5 | 6),
            _ => true,
        };
        if !valid {
            return Err(Fault::ud());
        }
        use crate::cpu::instructions as ins;
        match (op, group) {
            (0xD8, 0) => ins::instr_D8_0_reg(r),
            (0xD8, 1) => ins::instr_D8_1_reg(r),
            (0xD8, 2) => ins::instr_D8_2_reg(r),
            (0xD8, 3) => ins::instr_D8_3_reg(r),
            (0xD8, 4) => ins::instr_D8_4_reg(r),
            (0xD8, 5) => ins::instr_D8_5_reg(r),
            (0xD8, 6) => ins::instr_D8_6_reg(r),
            (0xD8, 7) => ins::instr_D8_7_reg(r),
            (0xD9, 0) => ins::instr32_D9_0_reg(r),
            (0xD9, 1) => ins::instr32_D9_1_reg(r),
            (0xD9, 2) => ins::instr32_D9_2_reg(r),
            (0xD9, 3) => ins::instr32_D9_3_reg(r),
            (0xD9, 4) => ins::instr32_D9_4_reg(r),
            (0xD9, 5) => ins::instr32_D9_5_reg(r),
            (0xD9, 6) => ins::instr32_D9_6_reg(r),
            (0xD9, 7) => ins::instr32_D9_7_reg(r),
            (0xDA, 0) => ins::instr_DA_0_reg(r),
            (0xDA, 1) => ins::instr_DA_1_reg(r),
            (0xDA, 2) => ins::instr_DA_2_reg(r),
            (0xDA, 3) => ins::instr_DA_3_reg(r),
            (0xDA, 4) => ins::instr_DA_4_reg(r),
            (0xDA, 5) => ins::instr_DA_5_reg(r),
            (0xDA, 6) => ins::instr_DA_6_reg(r),
            (0xDA, 7) => ins::instr_DA_7_reg(r),
            (0xDB, 0) => ins::instr_DB_0_reg(r),
            (0xDB, 1) => ins::instr_DB_1_reg(r),
            (0xDB, 2) => ins::instr_DB_2_reg(r),
            (0xDB, 3) => ins::instr_DB_3_reg(r),
            (0xDB, 4) => ins::instr_DB_4_reg(r),
            (0xDB, 5) => ins::instr_DB_5_reg(r),
            (0xDB, 6) => ins::instr_DB_6_reg(r),
            (0xDB, 7) => ins::instr_DB_7_reg(r),
            (0xDC, 0) => ins::instr_DC_0_reg(r),
            (0xDC, 1) => ins::instr_DC_1_reg(r),
            (0xDC, 2) => ins::instr_DC_2_reg(r),
            (0xDC, 3) => ins::instr_DC_3_reg(r),
            (0xDC, 4) => ins::instr_DC_4_reg(r),
            (0xDC, 5) => ins::instr_DC_5_reg(r),
            (0xDC, 6) => ins::instr_DC_6_reg(r),
            (0xDC, 7) => ins::instr_DC_7_reg(r),
            (0xDD, 0) => ins::instr32_DD_0_reg(r),
            (0xDD, 1) => ins::instr32_DD_1_reg(r),
            (0xDD, 2) => ins::instr32_DD_2_reg(r),
            (0xDD, 3) => ins::instr32_DD_3_reg(r),
            (0xDD, 4) => ins::instr32_DD_4_reg(r),
            (0xDD, 5) => ins::instr32_DD_5_reg(r),
            (0xDD, 6) => ins::instr32_DD_6_reg(r),
            (0xDD, 7) => ins::instr32_DD_7_reg(r),
            (0xDE, 0) => ins::instr_DE_0_reg(r),
            (0xDE, 1) => ins::instr_DE_1_reg(r),
            (0xDE, 2) => ins::instr_DE_2_reg(r),
            (0xDE, 3) => ins::instr_DE_3_reg(r),
            (0xDE, 4) => ins::instr_DE_4_reg(r),
            (0xDE, 5) => ins::instr_DE_5_reg(r),
            (0xDE, 6) => ins::instr_DE_6_reg(r),
            (0xDE, 7) => ins::instr_DE_7_reg(r),
            (0xDF, 0) => ins::instr_DF_0_reg(r),
            (0xDF, 1) => ins::instr_DF_1_reg(r),
            (0xDF, 2) => ins::instr_DF_2_reg(r),
            (0xDF, 3) => ins::instr_DF_3_reg(r),
            (0xDF, 4) => ins::instr_DF_4_reg(r),
            (0xDF, 5) => ins::instr_DF_5_reg(r),
            (0xDF, 6) => ins::instr_DF_6_reg(r),
            (0xDF, 7) => ins::instr_DF_7_reg(r),
            _ => unreachable!(),
        }
    }
    *gp::fpu_status_word |= x87_exception_flags();
    if op == 0xDB && m == 0xE2 {
        *gp::fpu_status_word = old_status & !0x80FF;
    }
    if x87_pending() {
        for i in 0..8 {
            fpu::fpu_write_st(i as i32, old_regs[i]);
        }
        *gp::fpu_stack_ptr = old_top;
        *gp::fpu_stack_empty = old_empty;
        state::write_flags64(old_flags);
        *gp::fpu_status_word |= 0x8080;
    }
    let control = op == 0xDB && group == 4
        || op == 0xD9 && d.address.is_some() && group >= 4
        || op == 0xDD && d.address.is_some() && group >= 4
        || op == 0xDF && m == 0xE0;
    if !control {
        *gp::fpu_ip = d.start.0 as i32;
        *gp::x64_fpu_ip_hi = (d.start.0 >> 32) as u32;
        *gp::fpu_ip_selector = 0;
        *gp::fpu_opcode = ((op & 7) << 8 | m as u32) as i32;
        if d.address.is_some() {
            let (a, _) = address(d);
            *gp::fpu_dp = a as i32;
            *gp::x64_fpu_dp_hi = (a >> 32) as u32;
            *gp::fpu_dp_selector = 0;
        }
    }
    Ok(true)
}

/// Returns false only for instructions outside this semantic family. A true
/// result commits RIP; exceptions leave the faulting RIP and destination intact.
/// SSSE3 (0F 38 and PALIGNR, 0F 3A 0F): the MMX forms without prefix, the
/// XMM forms with 66. The semantics are crate::cpu::simd_int's.
unsafe fn ssse3(d: &Decoded) -> Result<bool, Fault> {
    let base = d.base_opcode();
    if !matches!(base, 0x0F3800..=0x0F380B | 0x0F381C..=0x0F381E | 0x0F3A0F)
        || !matches!(d.opcode >> 24, 0 | 0x66)
    {
        return Ok(false);
    }
    let xmm = d.opcode >> 24 == 0x66;
    let r = d.reg.unwrap_or(0);
    let imm = d.immediate.map_or(0, |i| i.value as i32);
    guard(xmm)?;
    if xmm {
        let v = std::mem::transmute(source(d, 128, true, false)?);
        if base == 0x0F3A0F {
            sem3a::instr_660F3A0F(v, r as i32, imm);
        }
        else {
            sem38::ssse3_xmm(base as u8, v, r as i32);
        }
    }
    else {
        let v = source(d, 64, false, true)? as u64;
        if base == 0x0F3A0F {
            sem3a::instr_0F3A0F(v, (r & 7) as i32, imm);
        }
        else {
            sem38::ssse3_mmx(base as u8, v, (r & 7) as i32);
        }
    }
    Ok(true)
}

/// SSE4.1 and SSE4.2 forms with 66 (0F 38 and 0F 3A), with the semantics of
/// crate::cpu::simd_int and simd_fp (ROUND, DPPS/DPPD). REX.W selects PEXTRQ and PINSRQ; a
/// register destination of PEXTRB/PEXTRW/PEXTRD/EXTRACTPS is zero-extended.
/// PCMPESTRx take their lengths from EAX and EDX (RAX and RDX with REX.W).
unsafe fn sse4(d: &Decoded) -> Result<bool, Fault> {
    let base = d.base_opcode();
    if d.opcode >> 24 != 0x66 {
        return Ok(false);
    }
    let r = d.reg.unwrap_or(0);
    let imm = d.immediate.map_or(0, |i| i.value as u8);
    let vector = |v: u128| v.to_le_bytes();
    match base {
        0x0F3810
        | 0x0F3814
        | 0x0F3815
        | 0x0F3820..=0x0F3825
        | 0x0F3828
        | 0x0F3829
        | 0x0F382B
        | 0x0F3830..=0x0F3835
        | 0x0F3837..=0x0F3841 => {
            guard(true)?;
            let op = base as u8;
            let bytes = sem38::sse4_source_bytes(op);
            let v = source(d, bytes * 8, bytes == 16, false)?;
            let result = simd_int::sse4(op, vector(xmm(r)), vector(v), vector(xmm(0)));
            put_xmm(r, u128::from_le_bytes(result));
        },
        0x0F3817 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            let (zero, carry) = simd_int::ptest(vector(xmm(r)), vector(v));
            state::write_flags64(
                state::read_flags64() & !0x8D5 | (zero as u64) << 6 | carry as u64,
            );
        },
        0x0F382A => {
            guard(true)?;
            if d.rm_register.is_some() {
                return Err(Fault::ud());
            }
            put_xmm(r, source(d, 128, true, false)?);
        },
        0x0F3A08..=0x0F3A0B => {
            guard(true)?;
            let v = match base {
                0x0F3A0A => source(d, 32, false, false)?,
                0x0F3A0B => source(d, 64, false, false)?,
                _ => source(d, 128, true, false)?,
            };
            put_xmm(
                r,
                simd_fp::round(base, xmm(r), v, imm).map_err(|e| simd_fault(e))?,
            );
        },
        0x0F3A40 | 0x0F3A41 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            put_xmm(
                r,
                simd_fp::dot_product(base == 0x0F3A41, xmm(r), v, imm)
                    .map_err(|e| simd_fault(e))?,
            );
        },
        // PCMPESTRM, PCMPESTRI, PCMPISTRM, PCMPISTRI: the index to ECX (RCX
        // zero-extended) or the mask to XMM0, and the flags; the m128 needs no
        // alignment (SDM, exception type 4)
        0x0F3A60..=0x0F3A63 => {
            guard(true)?;
            let v = source(d, 128, false, false)?;
            let explicit = base & 2 == 0;
            let length = |r: usize| {
                let value = state::read_gpr(r);
                explicit.then(|| {
                    if d.prefixes.w() {
                        value as i64
                    }
                    else {
                        value as i32 as i64
                    }
                })
            };
            let result =
                simd_int::compare_strings(imm, vector(xmm(r)), vector(v), length(0), length(2));
            if base & 1 != 0 {
                state::write_gpr(1, result.index as u64, 32);
            }
            else {
                put_xmm(0, u128::from_le_bytes(result.xmm0));
            }
            state::write_flags64(state::read_flags64() & !0x8D5 | result.flags as u64);
        },
        0x0F3A0C..=0x0F3A0E | 0x0F3A42 => {
            guard(true)?;
            let v = source(d, 128, true, false)?;
            put_xmm(
                r,
                u128::from_le_bytes(simd_int::sse4_imm(
                    base as u8,
                    vector(xmm(r)),
                    vector(v),
                    imm,
                )),
            );
        },
        // PEXTRB, PEXTRW, PEXTRD/PEXTRQ, EXTRACTPS
        0x0F3A14..=0x0F3A17 => {
            guard(true)?;
            let bytes = match base {
                0x0F3A14 => 1,
                0x0F3A15 => 2,
                0x0F3A16 if d.prefixes.w() => 8,
                _ => 4,
            };
            let at = (imm as u32 & (16 / bytes - 1)) * bytes * 8;
            let value = (xmm(r) >> at) as u64 & (u64::MAX >> (64 - bytes * 8));
            if let Some(rm) = d.rm_register {
                state::write_gpr(rm as usize, value, if bytes == 8 { 64 } else { 32 });
            }
            else {
                let (a, stack) = address(d);
                memory::write(a, bytes as u8 * 8, value, stack)?;
            }
        },
        // PINSRB, INSERTPS, PINSRD/PINSRQ
        0x0F3A20..=0x0F3A22 => {
            guard(true)?;
            if base == 0x0F3A21 {
                let value = match d.rm_register {
                    Some(rm) => (xmm(rm) >> ((imm >> 6 & 3) * 32)) as u32,
                    None => source(d, 32, false, false)? as u32,
                };
                put_xmm(
                    r,
                    u128::from_le_bytes(simd_int::insertps(vector(xmm(r)), value, imm)),
                );
            }
            else {
                let bytes = if base == 0x0F3A20 {
                    1
                }
                else if d.prefixes.w() {
                    8
                }
                else {
                    4
                };
                let value =
                    gpr_source(d, bytes as u8 * 8)? as u128 & (u128::MAX >> (128 - bytes * 8));
                let at = (imm as u32 & (16 / bytes - 1)) * bytes * 8;
                put_xmm(
                    r,
                    xmm(r) & !((u128::MAX >> (128 - bytes * 8)) << at) | value << at,
                );
            }
        },
        _ => return Ok(false),
    }
    Ok(true)
}

/// The x64 engine's side of an AVX instruction (crate::cpu::avx)
struct Avx<'a>(&'a Decoded);
impl avx::Machine for Avx<'_> {
    type Fault = Fault;
    /// (the address without its index, plus `offset`, wrapped to the
    /// address size; FS and GS bases)
    unsafe fn gather(&mut self, offset: u64, bytes: u8) -> Result<u64, Fault> {
        let mut a = self.0.address.unwrap();
        a.index = None;
        a.displacement = a.displacement.wrapping_add(offset as i64);
        let mut regs = [0; 16];
        for (r, value) in regs.iter_mut().enumerate() {
            *value = state::read_gpr(r);
        }
        let base = if a.segment >= 4 { state::read_segment_base(a.segment as usize) } else { 0 };
        memory::read(
            a.offset(&regs, self.0.next).wrapping_add(base),
            bytes * 8,
            a.segment == 2,
        )
    }
    unsafe fn raise(&mut self, e: avx::Exception) -> Fault {
        match e {
            avx::Exception::InvalidOpcode => Fault::ud(),
            avx::Exception::DeviceNotAvailable => fault(7),
            avx::Exception::GeneralProtection => Fault::gp(),
            avx::Exception::SimdFloatingPoint => simd_fault(simd_fp::Unmasked),
        }
    }
    unsafe fn read(&mut self, bytes: u8, aligned: bool) -> Result<u128, Fault> {
        let (a, stack) = address(self.0);
        if aligned {
            alignment(a, stack, 16)?;
        }
        if bytes == 16 {
            memory::read128(a, stack)
        }
        else {
            memory::read(a, bytes * 8, stack).map(|v| v as u128)
        }
    }
    unsafe fn write(&mut self, bytes: u8, value: u128, aligned: bool) -> Result<(), Fault> {
        let (a, stack) = address(self.0);
        if aligned {
            alignment(a, stack, 16)?;
        }
        if bytes == 16 {
            memory::write128(a, value, stack)
        }
        else {
            memory::write(a, bytes * 8, value as u64, stack)
        }
    }
    /// (as MASKMOVDQU: the selected bytes writable first)
    unsafe fn write_masked(&mut self, value: u128, mask: u16) -> Result<(), Fault> {
        let d = self.0;
        let seg = d.prefixes.segment.unwrap_or(3);
        let base = if seg >= 4 { state::read_segment_base(seg as usize) } else { 0 };
        let off = state::read_gpr(7);
        let off = if d.address_size == 32 { off as u32 as u64 } else { off };
        let a = off.wrapping_add(base);
        for i in 0..16 {
            if mask >> i & 1 != 0 {
                memory::probe_write(a.wrapping_add(i), 8, false)?;
            }
        }
        for i in 0..16 {
            if mask >> i & 1 != 0 {
                memory::write(a.wrapping_add(i), 8, (value >> (i * 8)) as u64, false)?;
            }
        }
        Ok(())
    }
    unsafe fn read256(&mut self, aligned: bool) -> Result<(u128, u128), Fault> {
        let (a, stack) = address(self.0);
        if aligned {
            alignment(a, stack, 32)?;
        }
        let low = memory::read128(a, stack)?;
        Ok((low, memory::read128(a.wrapping_add(16), stack)?))
    }
    unsafe fn write256(&mut self, value: (u128, u128), aligned: bool) -> Result<(), Fault> {
        let (a, stack) = address(self.0);
        if aligned {
            alignment(a, stack, 32)?;
        }
        memory::probe_write(a, 128, stack)?;
        memory::probe_write(a.wrapping_add(16), 128, stack)?;
        memory::write128(a, value.0, stack)?;
        memory::write128(a.wrapping_add(16), value.1, stack)
    }
    unsafe fn read_lanes(
        &mut self,
        size: u8,
        count: u8,
        selected: u8,
    ) -> Result<(u128, u128), Fault> {
        let (a, stack) = address(self.0);
        let mut v = (0, 0);
        for n in 0..count {
            if selected >> n & 1 != 0 {
                let lane =
                    memory::read(a.wrapping_add((n * size) as u64), size * 8, stack)? as u128;
                let offset = n as u32 * size as u32;
                if offset < 16 {
                    v.0 |= lane << (offset * 8);
                }
                else {
                    v.1 |= lane << ((offset - 16) * 8);
                }
            }
        }
        Ok(v)
    }
    unsafe fn write_lanes(
        &mut self,
        size: u8,
        count: u8,
        value: (u128, u128),
        selected: u8,
    ) -> Result<(), Fault> {
        let (a, stack) = address(self.0);
        let lanes = (0..count).filter(|n| selected >> n & 1 != 0);
        for n in lanes.clone() {
            memory::probe_write(a.wrapping_add((n * size) as u64), size * 8, stack)?;
        }
        for n in lanes {
            let lane = avx::lane256(value, n as u32 * size as u32, size as u32);
            memory::write(a.wrapping_add((n * size) as u64), size * 8, lane, stack)?;
        }
        Ok(())
    }
    unsafe fn gpr(&mut self, r: u8) -> u64 { state::read_gpr(r as usize) }
    unsafe fn set_gpr(&mut self, r: u8, value: u64, wide: bool) {
        state::write_gpr(r as usize, value, if wide { 64 } else { 32 });
    }
    unsafe fn set_flags(&mut self, flags: u32) {
        state::write_flags64(state::read_flags64() & !0x8D5 | flags as u64);
    }
}
/// The x64 engine's operands of a BMI1 or BMI2 instruction (cpu::bmi)
struct Bmi<'a>(&'a Decoded);
impl crate::cpu::bmi::Machine for Bmi<'_> {
    type Fault = Fault;
    unsafe fn source(&mut self, bits: u32) -> Result<u64, Fault> {
        match self.0.rm_register {
            Some(r) => Ok(state::read_gpr(r as usize) & u64::MAX >> (64 - bits)),
            None => {
                let (a, stack) = address(self.0);
                memory::read(a, bits as u8, stack)
            },
        }
    }
    unsafe fn gpr(&mut self, r: u8) -> u64 { state::read_gpr(r as usize) }
    unsafe fn set_gpr(&mut self, r: u8, value: u64, bits: u32) {
        state::write_gpr(r as usize, value, bits as u8);
    }
    unsafe fn set_flags(&mut self, flags: u32) {
        state::write_flags64(state::read_flags64() & !0x8D5 | flags as u64);
    }
}
pub unsafe fn execute(d: &Decoded) -> Result<bool, Fault> {
    // BMI1 and BMI2 (exception type 13): general-purpose registers, without
    // the AVX state's requirements; 64-bit operands with VEX.W1 in 64-bit
    // mode, otherwise 32-bit
    if let Some(v) = d
        .vex
        .filter(|_| d.encoding.vex & crate::decode_rules::vex::GPR != 0)
    {
        use crate::cpu::bmi;
        let long = d.mode.is_long();
        let group = d.modrm.map_or(0, |m| m >> 3 & 7);
        let i = bmi::Instruction {
            op: bmi::Vex::of(d.opcode, group).ok_or(Fault::ud())?,
            reg: d.reg.unwrap_or(0),
            vvvv: v.vvvv & if long { 15 } else { 7 },
            bits: if long && v.w { 64 } else { 32 },
            imm8: d.immediate.map_or(0, |i| i.value as u8),
        };
        bmi::execute(&mut Bmi(d), &i)?;
        state::write_rip(d.next.0);
        return Ok(true);
    }
    if let Some(v) = d.vex {
        let mut machine = Avx(d);
        avx::check(&mut machine)?;
        let i = avx::Instruction {
            key: d.opcode,
            reg: d.reg.unwrap_or(0),
            vvvv: v.vvvv,
            rm: d.rm_register,
            // (a VEX.256 form: not a VEX.LIG one's VEX.L)
            l: v.l && d.encoding.vex & crate::decode_rules::vex::L1 != 0,
            w: v.w,
            imm8: d.immediate.map_or(0, |i| i.value as u8),
            long: true,
            // (a gather's VSIB operand: the address's index is its vector
            // register)
            vsib: (d.encoding.vex & crate::decode_rules::vex::VSIB != 0).then(|| {
                let a = d.address.unwrap();
                avx::Vsib {
                    index: a.index.unwrap(),
                    scale: a.scale,
                }
            }),
        };
        avx::execute(&mut machine, &i)?;
        state::write_rip(d.next.0);
        return Ok(true);
    }
    if x87(d)? {
        state::write_rip(d.next.0);
        return Ok(true);
    }
    if matches!(d.base_opcode() >> 8, 0x0F38 | 0x0F3A) {
        if !ssse3(d)? && !sse4(d)? {
            return Ok(false);
        }
        state::write_rip(d.next.0);
        return Ok(true);
    }
    if d.base_opcode() & 0xFF00 != 0x0F00 {
        return Ok(false);
    }
    if fxstate(d)?
        || arithmetic(d)?
        || conversion(d)?
        || moves(d)?
        || immediate_shift(d)?
        || packed_arithmetic(d)?
    {
        state::write_rip(d.next.0);
        Ok(true)
    }
    else {
        Ok(false)
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/rust/x86tpl/mmx.rs                                                                   0000644 0000000 0000000 00000003574 00000000000 013775  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! MMX leaves (docs/jit-unification-plan.md P2.2). The MMX registers alias
//! the x87 mantissas: a read first syncs its slot from the f64 shadow cache,
//! a write invalidates the slot and sets its exponent to 0xFFFF, and a form
//! ends with the transition to MMX (all tags valid, TOP 0).
use crate::cpu::{fpu, global_pointers as gp};
use crate::wasmgen::wasm_builder::{Signature, WasmBuilder, WasmLocalV128, WasmType};

/// Push MMX `r` (cpu::read_mmx64s: sync the slot from the f64 cache first)
pub fn load(w: &mut WasmBuilder, r: u8) {
    let [_, _, dirty] = fpu::x87_cache_addresses();
    w.load_fixed_i32(dirty);
    w.const_i32(1 << r);
    w.and_i32();
    w.hint(false);
    w.if_void();
    w.const_i32(r as i32);
    w.call_signature("fpu_sync_slot", Signature::new(&[WasmType::I32], &[]));
    w.block_end();
    w.const_i32(gp::get_reg_mmx_offset(r as u32) as i32);
    w.simd_memory(0x5D, 0);
}
/// cpu::write_mmx_reg64 of the low quadword of `value`
pub fn store(w: &mut WasmBuilder, r: u8, value: &WasmLocalV128) {
    invalidate(w, r);
    let address = gp::get_reg_mmx_offset(r as u32);
    w.const_i32(address as i32);
    w.get_local_v128(value);
    w.simd_lane(0x1D, 0);
    w.store_unaligned_i64(0);
    w.const_i32(address as i32 + 8);
    w.const_i32(0xFFFF);
    w.store_unaligned_u16(0);
}
/// fpu_invalidate_slot(r)
pub fn invalidate(w: &mut WasmBuilder, r: u8) {
    let [_, valid, dirty] = fpu::x87_cache_addresses();
    for address in [valid, dirty] {
        w.const_i32(address as i32);
        w.load_fixed_i32(address);
        w.const_i32(!(1 << r));
        w.and_i32();
        w.store_aligned_i32(0);
    }
}
/// cpu::transition_fpu_to_mmx: all tags valid, TOP 0
pub fn transition(w: &mut WasmBuilder) {
    for address in [gp::fpu_stack_empty as u32, gp::fpu_stack_ptr as u32] {
        w.const_i32(address as i32);
        w.const_i32(0);
        w.store_u8(0);
    }
}
                                                                                                                                    source/v64/src/rust/x86tpl/mod.rs                                                                   0000644 0000000 0000000 00000000741 00000000000 013744  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! x86 leaf templates (docs/jit-unification-plan.md P2.2): the code that
//! every x86 engine generates alike, of x86 semantics. The page tier uses
//! them (IR Tier-0 too until P7.5, the region backend until M11 deleted it,
//! P7.9). The ISA-neutral parts are in wasmgen::leaves, which A64 shares.
//!
//! Imports: nothing of x64 or jit (P2.10 checks it).
pub mod mmx;
pub mod native_fp;
pub mod ops;
pub mod string;
pub mod vec;
pub mod x87;
pub mod x87_forms;
pub mod x87run;
                               source/v64/src/rust/x86tpl/native_fp.rs                                                             0000644 0000000 0000000 00000070365 00000000000 015151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Native SSE floating point in compiled code (docs/simd-xsave-plan.md 7.4):
//! Wasm's IEEE arithmetic, admitted only where it gives exactly the results
//! and MXCSR effects of cpu::simd_fp (whose interpreter fast path applies the
//! same rule). The page tier emits these checks (the region backend too until M11); a refused
//! instruction runs in the exact interpreter or helper.
//!
//! MXCSR's flags are sticky. When every exception is masked, the rounding is
//! to nearest, DAZ and FZ are clear and PE is set already (`mxcsr_refused`), a
//! native result equals the exact one and an inexact result changes nothing.
//! The other flags must not become set, so each operation refuses the lanes
//! that could set one: a denormal operand (DE), a NaN or infinite result (IE,
//! ZE, OE; and NaN payloads, which Wasm leaves open) and, for MUL, DIV and the
//! conversion to single precision, a result that is tiny after rounding (at
//! most the smallest normal in magnitude) unless it is the exact zero of a
//! zero factor (UE). A denormal sum or difference of normal operands is
//! exact, so it raises nothing (masked, UE needs inexactness). Operations that
//! cannot round and raise nothing for normal operands (MIN, MAX, compares,
//! widening conversions, reciprocal approximations) need only their operand
//! checks; the `*_refused` functions leave MXCSR's condition to the caller
//! (the page tier evaluates it once per block).
//!
//! FMA (`fused`) uses relaxed SIMD's multiply-adds, but only where the host
//! fuses them (cpu.js checks at startup, see x64::helpers::relaxed_fma):
//! then they round once, as IEEE 754's fusedMultiplyAdd and x86's FMA, and
//! the admitted lanes' results are exact and the same on every host.
//!
//! The checks build a mask of the admitted lanes with integer and float
//! comparisons. Their constants have the same value in every 32-bit lane, so
//! that each is one move of an immediate (arbitrary v128 constants cost a
//! general-purpose register and a transfer per use on ARM64):
//! - finite x: x - x is 0 (else NaN);
//! - 2|x| - 1 (`x << 1` plus all ones) is all ones for a zero and below
//!   2 * smallest normal - 1 exactly for denormals;
//! - tiny x: |x| <= smallest normal.
//!
//! In double precision the integer comparisons see only the high half of
//! each lane (lanes 1 and 3; 2|x| - 1 and 2|x| compared to their bound's high
//! half), which also refuses a few normals just above the smallest one. The
//! low halves of such masks are left over: a scalar form reads lane 1 of the
//! result and packed forms copy the high halves down first (`high_half`).

use crate::cpu::global_pointers as gp;
use crate::wasmgen::wasm_builder::{WasmBuilder, WasmLocalV128};

/// Push i32 nonzero unless MXCSR admits native rounding operations: every
/// exception masked, round to nearest, no DAZ or FZ, PE set
pub fn mxcsr_refused(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0xFFE0);
    w.and_i32();
    w.const_i32(0x1FA0);
    w.ne_i32();
}

/// mxcsr_refused with PE either way: for an engine that finds inexact
/// results itself and sets PE (inexact_pe; the page tier)
pub fn mxcsr_refused_any_pe(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0xFFC0);
    w.and_i32();
    w.const_i32(0x1F80);
    w.ne_i32();
}

/// mxcsr_refused with DAZ either way: for the templates that refuse every
/// denormal operand, which DAZ then cannot change (the page tier's
/// arithmetic and FMA, P4.18; FZ is mxcsr_refused's)
pub fn mxcsr_refused_any_daz(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0xFFA0);
    w.and_i32();
    w.const_i32(0x1FA0);
    w.ne_i32();
}
/// Push i32 nonzero unless every exception is masked and MXCSR rounds to
/// nearest (DAZ, FZ and the flags either way)
pub fn masked_nearest_refused(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0x7F80);
    w.and_i32();
    w.const_i32(0x1F80);
    w.ne_i32();
}
/// Push i32 1 if MXCSR.FZ is set, else 0
pub fn flush_to_zero(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(15);
    w.shr_u_i32();
    w.const_i32(1);
    w.and_i32();
}
/// Push i32 nonzero if MXCSR.PE is clear
pub fn precision_clear(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0x20);
    w.and_i32();
    w.eqz_i32();
}

/// Push i32 nonzero unless MXCSR rounds to nearest with PE masked: what an
/// inexact result of an operation that raises nothing else needs
pub fn rounding_refused(w: &mut WasmBuilder) {
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0x7000);
    w.and_i32();
    w.const_i32(0x1000);
    w.ne_i32();
}

/// Set MXCSR.PE if the i32 on the stack is nonzero: an inexact result, every
/// exception masked (mxcsr_refused_any_pe)
pub fn inexact_pe(w: &mut WasmBuilder) {
    w.if_void();
    w.const_i32(gp::mxcsr as i32);
    w.load_fixed_i32(gp::mxcsr as u32);
    w.const_i32(0x20);
    w.or_i32();
    w.store_aligned_i32(0);
    w.block_end();
}

/// Push i32 nonzero if a lane read of the mask on the stack is set (a
/// scalar form's: lane 0)
fn any_lane(w: &mut WasmBuilder, scalar: bool) {
    if scalar {
        w.simd_lane(0x1B, 0); // i32x4.extract_lane
    }
    else {
        w.simd(0x53); // v128.any_true
    }
}
/// f64x2.splat of `v`
fn splat64(w: &mut WasmBuilder, v: f64) {
    w.const_f64(v);
    w.simd(0x14); // f64x2.splat
}
/// Push the mask of the f64x2 lanes of `x` that Dekker's splitting cannot
/// take: not zero and outside 2^-450..2^451, where the split could overflow
/// or the error terms lose bits to underflow
fn outside_dekker(w: &mut WasmBuilder, x: &WasmLocalV128) {
    w.get_local_v128(x);
    w.simd(0xEC); // f64x2.abs
    splat64(w, f64::from_bits((0x3FF - 450) << 52));
    w.simd(0x49); // f64x2.lt
    w.get_local_v128(x);
    w.simd_zero();
    w.simd(0x48); // f64x2.ne
    w.simd(0x4E); // v128.and
    w.get_local_v128(x);
    w.simd(0xEC);
    splat64(w, f64::from_bits((0x3FF + 451) << 52));
    w.simd(0x4C); // f64x2.ge
    w.simd(0x50); // v128.or
}
/// Dekker's split of the f64x2 lanes of `v`: (hi, lo), hi = c - (c - v)
/// with c = v * (2^27 + 1), lo = v - hi
fn split(w: &mut WasmBuilder, v: &WasmLocalV128) -> (WasmLocalV128, WasmLocalV128) {
    w.get_local_v128(v);
    splat64(w, 134217729.0);
    w.simd(0xF2); // f64x2.mul
    let c = w.set_new_local_v128();
    w.get_local_v128(&c);
    w.get_local_v128(&c);
    w.get_local_v128(v);
    w.simd(0xF1); // f64x2.sub
    w.simd(0xF1);
    let hi = w.set_new_local_v128();
    w.get_local_v128(v);
    w.get_local_v128(&hi);
    w.simd(0xF1);
    let lo = w.set_new_local_v128();
    w.free_local_v128(c);
    (hi, lo)
}
/// Push the mask of the f64x2 lanes where `p` is not exactly `a` * `b`
/// (Dekker's TwoProduct: its error term is not zero)
fn product_error(w: &mut WasmBuilder, a: &WasmLocalV128, b: &WasmLocalV128, p: &WasmLocalV128) {
    let (ah, al) = split(w, a);
    let (bh, bl) = split(w, b);
    // ((ah * bh - p) + ah * bl + al * bh) + al * bl
    for (k, (x, y)) in [(&ah, &bh), (&ah, &bl), (&al, &bh), (&al, &bl)]
        .into_iter()
        .enumerate()
    {
        w.get_local_v128(x);
        w.get_local_v128(y);
        w.simd(0xF2); // f64x2.mul
        if k == 0 {
            w.get_local_v128(p);
            w.simd(0xF1); // f64x2.sub
        }
        else {
            w.simd(0xF0); // f64x2.add
        }
    }
    w.simd_zero();
    w.simd(0x48); // f64x2.ne
    for v in [ah, al, bh, bl] {
        w.free_local_v128(v);
    }
}
/// Push the mask of the f64x2 lanes where `s` is not exactly `x` + `y`
/// (TwoSum: bb = s - x, its error (x - (s - bb)) + (y - bb) is not zero)
fn sum_error(w: &mut WasmBuilder, x: &WasmLocalV128, y: &WasmLocalV128, s: &WasmLocalV128) {
    w.get_local_v128(s);
    w.get_local_v128(x);
    w.simd(0xF1); // f64x2.sub
    let bb = w.set_new_local_v128();
    w.get_local_v128(x);
    w.get_local_v128(s);
    w.get_local_v128(&bb);
    w.simd(0xF1);
    w.simd(0xF1);
    w.get_local_v128(y);
    w.get_local_v128(&bb);
    w.simd(0xF1);
    w.simd(0xF0); // f64x2.add
    w.simd_zero();
    w.simd(0x48); // f64x2.ne
    w.free_local_v128(bb);
}

/// Push i32 nonzero if a lane read of `r` is tiny and not zero: what MXCSR.FZ
/// would flush (the exact sum or difference of normal operands that
/// arithmetic_refused admits without FZ)
pub fn flushed(w: &mut WasmBuilder, double: bool, scalar: bool, r: &WasmLocalV128) {
    tiny(w, r, double);
    zero(w, r, double);
    w.simd(0x4F); // v128.andnot
    high_half(w, double, scalar);
    if scalar {
        w.simd_lane(0x1B, double as u8); // i32x4.extract_lane
    }
    else {
        w.simd(0x53); // v128.any_true
    }
}

/// Whether `inexact` takes the operation (`op` as there) at all: all but
/// double precision SQRT
pub fn inexact_decides(op: u8, double: bool) -> bool { !(double && op == 0x51) }
/// For an engine that sets PE itself (the page tier, P4.18), where
/// inexact_decides: push i32 nonzero where `inexact` cannot decide whether
/// the result `r` of ADD (0x58), MUL (0x59), SUB (0x5C), DIV (0x5E) or
/// single precision SQRT (0x51, of `b`) of `a` and `b` is exact, in a lane
/// read: double precision MUL and DIV of an operand or result
/// outside_dekker. False: nothing pushed (it decides every lane).
pub fn inexact_undecided(
    w: &mut WasmBuilder,
    op: u8,
    double: bool,
    scalar: bool,
    [a, b]: [&WasmLocalV128; 2],
    r: &WasmLocalV128,
) -> bool {
    match (double, op) {
        (true, 0x59 | 0x5E) => {
            for (k, x) in [a, b, r].into_iter().enumerate() {
                outside_dekker(w, x);
                if k > 0 {
                    w.simd(0x50); // v128.or
                }
            }
            any_lane(w, scalar);
        },
        _ => return false,
    }
    true
}

/// For an engine that sets PE itself (the page tier, P4.18): with the lanes
/// admitted (arithmetic_refused), MXCSR to nearest and every exception
/// masked, and inexact_undecided clear, push i32 nonzero if the result `r`
/// of SQRT (0x51, of `b`; inexact_decides: single precision), ADD (0x58),
/// MUL (0x59), SUB (0x5C) or DIV (0x5E) of `a` and `b` is inexact in a lane
/// read. Single precision: each
/// operation is exact in double precision but a sum, whose error TwoSum
/// gives. Double: TwoSum, and Dekker's TwoProduct for MUL (and DIV: the
/// product of quotient and divisor is the dividend).
pub fn inexact(
    w: &mut WasmBuilder,
    op: u8,
    double: bool,
    scalar: bool,
    [a, b]: [&WasmLocalV128; 2],
    r: &WasmLocalV128,
) {
    if double {
        match op {
            0x58 | 0x5C => {
                let negated = (op == 0x5C).then(|| {
                    w.get_local_v128(b);
                    w.simd(0xED); // f64x2.neg
                    w.set_new_local_v128()
                });
                sum_error(w, a, negated.as_ref().unwrap_or(b), r);
                if let Some(local) = negated {
                    w.free_local_v128(local);
                }
            },
            0x59 => product_error(w, a, b, r),
            _ => {
                dbg_assert!(op == 0x5E, "double SQRT: not inexact_decides");
                w.get_local_v128(r);
                w.get_local_v128(b);
                w.simd(0xF2); // f64x2.mul
                let p = w.set_new_local_v128();
                product_error(w, r, b, &p);
                w.get_local_v128(&p);
                w.get_local_v128(a);
                w.simd(0x48); // f64x2.ne
                w.simd(0x50); // v128.or
                w.free_local_v128(p);
            },
        }
        any_lane(w, scalar);
        return;
    }
    // single precision: lanes 0 and 1, then 2 and 3, in double precision
    for half in 0..if scalar { 1 } else { 2 } {
        let promote = |w: &mut WasmBuilder, x: &WasmLocalV128| {
            w.get_local_v128(x);
            if half == 1 {
                w.get_local_v128(x);
                w.simd_shuffle([8, 9, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 13, 14, 15]);
            }
            w.simd(0x5F); // f64x2.promote_low_f32x4
            w.set_new_local_v128()
        };
        let (x, y, s) = (promote(w, a), promote(w, b), promote(w, r));
        match op {
            0x58 | 0x5C => {
                if op == 0x5C {
                    w.get_local_v128(&y);
                    w.simd(0xED); // f64x2.neg
                    w.set_local_v128(&y);
                }
                w.get_local_v128(&x);
                w.get_local_v128(&y);
                w.simd(0xF0); // f64x2.add
                let sum = w.set_new_local_v128();
                sum_error(w, &x, &y, &sum);
                w.get_local_v128(&sum);
                w.get_local_v128(&s);
                w.simd(0x48); // f64x2.ne
                w.simd(0x50); // v128.or
                w.free_local_v128(sum);
            },
            // x * y, s * y and s * s are exact (48 significant bits)
            0x59 => {
                w.get_local_v128(&x);
                w.get_local_v128(&y);
                w.simd(0xF2); // f64x2.mul
                w.get_local_v128(&s);
                w.simd(0x48); // f64x2.ne
            },
            0x5E => {
                w.get_local_v128(&s);
                w.get_local_v128(&y);
                w.simd(0xF2);
                w.get_local_v128(&x);
                w.simd(0x48);
            },
            _ => {
                w.get_local_v128(&s);
                w.get_local_v128(&s);
                w.simd(0xF2);
                w.get_local_v128(&y);
                w.simd(0x48);
            },
        }
        if half == 1 {
            w.simd(0x50); // v128.or
        }
        for v in [x, y, s] {
            w.free_local_v128(v);
        }
    }
    any_lane(w, scalar);
}

/// v128.const with `v` in every 32-bit lane
fn splat32(w: &mut WasmBuilder, v: u32) {
    let mut bytes = [0; 16];
    for (i, b) in bytes.iter_mut().enumerate() {
        *b = (v >> (i % 4 * 8)) as u8;
    }
    w.const_v128(bytes);
}

/// The lanes an instruction reads
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Lanes {
    /// lane 0
    Scalar,
    /// all lanes
    Packed,
    /// single-precision lanes 0 and 1 (CVTPS2PD)
    LowPair,
}
/// Pop an admitted-lanes mask, push i32 nonzero if a lane read is refused
fn refused(w: &mut WasmBuilder, double: bool, lanes: Lanes) {
    match lanes {
        // (lane 1: the high half of a double, see above)
        Lanes::Scalar => w.simd_lane(0x1B, double as u8), // i32x4.extract_lane
        Lanes::Packed => w.simd(0xA3),                    // i32x4.all_true
        Lanes::LowPair => {
            w.simd_lane(0x1D, 0); // i64x2.extract_lane
            w.const_i64(-1);
            w.ne_i64();
            return;
        },
    }
    w.eqz_i32();
}
/// Make a mask of double-precision lanes from its high halves (packed forms)
fn high_half(w: &mut WasmBuilder, double: bool, scalar: bool) {
    if double && !scalar {
        w.const_i32(32);
        w.simd(0xCC); // i64x2.shr_s
    }
}

/// Push the mask of finite lanes
fn finite(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    w.get_local_v128(x);
    w.get_local_v128(x);
    w.simd(if double { 0xF1 } else { 0xE5 }); // sub
    w.simd_zero();
    w.simd(if double { 0x47 } else { 0x41 }); // eq
}
/// Push the mask of ordered (not NaN) lanes
fn ordered(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    w.get_local_v128(x);
    w.get_local_v128(x);
    w.simd(if double { 0x47 } else { 0x41 }); // eq
}
/// Push the mask of zero lanes
fn zero(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    w.get_local_v128(x);
    w.simd_zero();
    w.simd(if double { 0x47 } else { 0x41 }); // eq
}
/// Push the mask of tiny lanes: magnitudes at most the smallest normal (a
/// zero too)
fn tiny(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    w.get_local_v128(x);
    if double {
        w.const_i32(1);
        w.simd(0xCB); // i64x2.shl: 2|x|
        splat32(w, 0x0020_0000);
        w.simd(0x3E); // i32x4.le_u
    }
    else {
        w.simd(0xE0); // f32x4.abs
        splat32(w, 0x0080_0000);
        w.simd(0x45); // f32x4.le
    }
}
/// Push 2|x| - 1 per lane
fn twice_less_one(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    w.get_local_v128(x);
    w.const_i32(1);
    w.simd(if double { 0xCB } else { 0xAB }); // shl
    w.const_v128([0xFF; 16]);
    w.simd(if double { 0xCE } else { 0xAE }); // add
}
/// Pop 2|x| - 1, push the mask of denormal lanes
fn denormal_of(w: &mut WasmBuilder, double: bool) {
    splat32(w, if double { 0x0020_0000 } else { 0x00FF_FFFF });
    w.simd(0x3A); // i32x4.lt_u
}
/// Push the mask of denormal lanes of `x`
fn denormal(w: &mut WasmBuilder, x: &WasmLocalV128, double: bool) {
    twice_less_one(w, x, double);
    denormal_of(w, double);
}
/// Push the mask of lanes where `x` or `y` is denormal
fn denormal2(w: &mut WasmBuilder, x: &WasmLocalV128, y: &WasmLocalV128, double: bool) {
    twice_less_one(w, x, double);
    twice_less_one(w, y, double);
    w.simd(0xB7); // i32x4.min_u
    denormal_of(w, double);
}

/// Push the mask of lanes where an operand not known to be `clean` has a
/// zero exponent: a zero or a denormal (or nothing when all are clean)
fn exponent_zero_unknown(
    w: &mut WasmBuilder,
    operands: [(&WasmLocalV128, bool); 2],
    double: bool,
) -> bool {
    let mut unknown = operands.iter().filter(|(_, clean)| !clean).map(|(x, _)| x);
    let Some(x) = unknown.next()
    else {
        return false;
    };
    for (k, x) in std::iter::once(x).chain(unknown).enumerate() {
        w.get_local_v128(x);
        w.const_i32(1);
        w.simd(if double { 0xCB } else { 0xAB }); // shl: 2|x|
        if k > 0 {
            w.simd(0xB7); // i32x4.min_u
        }
    }
    splat32(w, if double { 0x0020_0000 } else { 0x0100_0000 });
    w.simd(0x3A); // i32x4.lt_u
    true
}

/// The cheap first test of arithmetic_refused: push i32 zero only if that
/// check would admit the instruction (its operands not known to be clean
/// have no zero exponent, a product or quotient is not tiny), else nonzero:
/// arithmetic_refused decides. None where it would be arithmetic_refused.
pub fn arithmetic_unsure(
    w: &mut WasmBuilder,
    op: u8,
    double: bool,
    scalar: bool,
    [a, b]: [&WasmLocalV128; 2],
    [a_clean, b_clean]: [bool; 2],
    r: &WasmLocalV128,
) -> bool {
    // Where it pays: the zero-exempt tininess test of a scalar product or
    // quotient. (Packed data, vectors and matrices, often holds zeros that
    // would fail the first test every time.)
    let operands = [(a, a_clean), (b, b_clean)];
    if !matches!(op, 0x59 | 0x5E) || !scalar {
        return false;
    }
    if matches!(op, 0x5D | 0x5F) {
        let mut unknown = operands.iter().filter(|(_, clean)| !clean);
        let (x, _) = unknown.next().unwrap();
        ordered(w, x, double);
        if let Some((y, _)) = unknown.next() {
            ordered(w, y, double);
            w.simd(0x4E); // v128.and
        }
        exponent_zero_unknown(w, operands, double);
    }
    else {
        finite(w, r, double);
        let mut suspect = exponent_zero_unknown(w, operands, double);
        if op == 0x59 || op == 0x5E {
            tiny(w, r, double);
            if suspect {
                w.simd(0x50); // v128.or
            }
            suspect = true;
        }
        dbg_assert!(suspect);
    }
    high_half(w, double, scalar);
    w.simd(0x4F); // v128.andnot
    refused(
        w,
        double,
        if scalar { Lanes::Scalar } else { Lanes::Packed },
    );
    true
}

/// Push the mask of lanes where an operand not known to be `clean` is
/// denormal (or nothing when all are clean)
fn denormal_unknown(
    w: &mut WasmBuilder,
    operands: [(&WasmLocalV128, bool); 2],
    double: bool,
) -> bool {
    match operands {
        [(x, false), (y, false)] => denormal2(w, x, y, double),
        [(x, false), _] | [_, (x, false)] => denormal(w, x, double),
        _ => return false,
    }
    true
}

/// Push the mask of lanes where the operands not known to be `clean` are
/// neither NaN nor denormal (false: all are clean, nothing pushed)
fn clean_operands(
    w: &mut WasmBuilder,
    operands: [(&WasmLocalV128, bool); 2],
    double: bool,
    scalar: bool,
) -> bool {
    let mut unknown = operands.iter().filter(|(_, clean)| !clean);
    let Some((x, _)) = unknown.next()
    else {
        return false;
    };
    ordered(w, x, double);
    if let Some((y, _)) = unknown.next() {
        ordered(w, y, double);
        w.simd(0x4E); // v128.and
    }
    denormal_unknown(w, operands, double);
    high_half(w, double, scalar);
    w.simd(0x4F); // v128.andnot
    true
}

/// SQRT (0x51, of `b`), ADD (0x58), MUL (0x59), SUB (0x5C), MIN (0x5D), DIV
/// (0x5E) and MAX (0x5F) of `a` (the destination) and `b` (the source) with
/// the native result `r`: push i32 nonzero to refuse. MIN and MAX of
/// operands that are neither NaN nor denormal raise nothing and do not
/// round: they do not depend on MXCSR; the others need mxcsr_refused too.
///
/// An operand known to be clean (`a_clean`, `b_clean`: neither NaN nor
/// denormal in the lanes read) is not checked again. All operands of an
/// admitted instruction are clean afterwards, and so are its results except
/// those of ADD and SUB (possibly an exact denormal).
pub fn arithmetic_refused(
    w: &mut WasmBuilder,
    op: u8,
    double: bool,
    scalar: bool,
    [a, b]: [&WasmLocalV128; 2],
    [a_clean, b_clean]: [bool; 2],
    r: &WasmLocalV128,
) {
    let operands =
        if op == 0x51 { [(b, b_clean), (b, true)] } else { [(a, a_clean), (b, b_clean)] };
    if matches!(op, 0x5D | 0x5F) {
        if !clean_operands(w, operands, double, scalar) {
            w.const_i32(0);
            return;
        }
    }
    else {
        finite(w, r, double);
        let mut refused_lanes = denormal_unknown(w, operands, double);
        if op == 0x59 || op == 0x5E {
            // a tiny product or quotient is exact only as the zero of a zero
            // factor (dividend)
            tiny(w, r, double);
            zero(w, a, double);
            if op == 0x59 {
                zero(w, b, double);
                w.simd(0x50); // v128.or
            }
            w.simd(0x4F); // v128.andnot
            if refused_lanes {
                w.simd(0x50);
            }
            refused_lanes = true;
        }
        if refused_lanes {
            high_half(w, double, scalar);
            w.simd(0x4F); // finite and not refused
        }
    }
    refused(
        w,
        double,
        if scalar { Lanes::Scalar } else { Lanes::Packed },
    );
}

/// FMA of the factors `x`, `y` and the addend `z` with the native fused
/// result `r` (see fused): push i32 nonzero to refuse a denormal operand
/// (DE), a result that is NaN or infinite (IE, OE; also NaN and infinite
/// operands, whose results are such) and a tiny result (UE) unless it is the
/// exact zero of a zero factor and a zero addend. Rounded once, as
/// cpu::simd_fp::fused; with mxcsr_refused's condition only PE (set) could
/// be raised.
pub fn fused_refused(
    w: &mut WasmBuilder,
    double: bool,
    scalar: bool,
    [x, y, z]: [&WasmLocalV128; 3],
    r: &WasmLocalV128,
) {
    finite(w, r, double);
    twice_less_one(w, x, double);
    twice_less_one(w, y, double);
    w.simd(0xB7); // i32x4.min_u
    twice_less_one(w, z, double);
    w.simd(0xB7);
    denormal_of(w, double);
    tiny(w, r, double);
    zero(w, x, double);
    zero(w, y, double);
    w.simd(0x50); // v128.or
    zero(w, z, double);
    w.simd(0x4E); // v128.and
    w.simd(0x4F); // v128.andnot: tiny, not the zero of zeros
    w.simd(0x50); // or denormal
    high_half(w, double, scalar);
    w.simd(0x4F); // finite and not refused
    refused(
        w,
        double,
        if scalar { Lanes::Scalar } else { Lanes::Packed },
    );
}

/// FMA (the 0F 38 opcode byte `op` of VFMADD/VFMSUB/VFNMADD/VFNMSUB
/// 132/213/231 PS/PD/SS/SD and VFMADDSUB/VFMSUBADD) of the destination `d`,
/// the first source `f` (VEX.vvvv) and the r/m operand `t` with the host's
/// relaxed_madd/relaxed_nmadd, which must fuse (runtime::tier0::relaxed_fma):
/// returns the native result (a scalar form's in its low lane) and pushes
/// fused_refused's i32 (MXCSR's condition is the caller's).
pub fn fused(
    w: &mut WasmBuilder,
    op: u8,
    double: bool,
    scalar: bool,
    [d, f, t]: [&WasmLocalV128; 3],
) -> WasmLocalV128 {
    // the factors and the addend: 132 d * t + f, 213 f * d + t, 231 f * t + d
    let [x, y, z] = match op >> 4 {
        0x9 => [d, t, f],
        0xA => [f, d, t],
        _ => [f, t, d],
    };
    // a subtraction adds the negated addend (exact): VFMSUB and VFNMSUB in
    // every lane, VFMADDSUB in the even ones, VFMSUBADD in the odd ones
    let negated = match op & 0xF {
        0xA | 0xB | 0xE | 0xF => {
            w.get_local_v128(z);
            w.simd(if double { 0xED } else { 0xE1 }); // neg
            Some(w.set_new_local_v128())
        },
        k @ (6 | 7) => {
            let sign: [u32; 4] = match (double, k == 6) {
                (true, true) => [0, 0x8000_0000, 0, 0],
                (true, false) => [0, 0, 0, 0x8000_0000],
                (false, true) => [0x8000_0000, 0, 0x8000_0000, 0],
                (false, false) => [0, 0x8000_0000, 0, 0x8000_0000],
            };
            let mut bytes = [0; 16];
            for (i, b) in bytes.iter_mut().enumerate() {
                *b = (sign[i / 4] >> (i % 4 * 8)) as u8;
            }
            w.get_local_v128(z);
            w.const_v128(bytes);
            w.simd(0x51); // v128.xor
            Some(w.set_new_local_v128())
        },
        _ => None,
    };
    let z = negated.as_ref().unwrap_or(z);
    w.get_local_v128(x);
    w.get_local_v128(y);
    w.get_local_v128(z);
    // relaxed_madd x * y + z, relaxed_nmadd -(x * y) + z (VFNMADD, VFNMSUB)
    let negative = op & 0xF >= 0xC;
    w.simd(match (double, negative) {
        (false, false) => 0x105,
        (false, true) => 0x106,
        (true, false) => 0x107,
        (true, true) => 0x108,
    });
    let r = w.set_new_local_v128();
    fused_refused(w, double, scalar, [x, y, z], &r);
    if let Some(local) = negated {
        w.free_local_v128(local);
    }
    r
}

/// CVTPD2PS/CVTSD2SS of `x` with the native result `r`: push i32 nonzero to
/// refuse a denormal source and a result that is NaN, infinite or tiny
/// unless of a zero source (MXCSR's condition is the caller's)
pub fn narrowing_refused(w: &mut WasmBuilder, scalar: bool, x: &WasmLocalV128, r: &WasmLocalV128) {
    // the single-precision result lanes 0 and 1 at the source's lanes
    w.get_local_v128(r);
    w.get_local_v128(r);
    w.simd_shuffle([0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 4, 5, 6, 7]);
    let s = w.set_new_local_v128();
    finite(w, &s, false);
    tiny(w, &s, false);
    zero(w, x, true);
    w.simd(0x4F); // v128.andnot
    denormal(w, x, true);
    w.simd(0x50); // v128.or
    high_half(w, true, scalar);
    w.simd(0x4F);
    w.free_local_v128(s);
    refused(w, true, if scalar { Lanes::Scalar } else { Lanes::Packed });
}

/// COMISS/UCOMISS/COMISD/UCOMISD of `x` and `y` (Lanes::Scalar) and
/// CVTPS2PD/CVTSS2SD of `x` (pass `y` clean, Lanes::LowPair or Scalar): push
/// i32 nonzero to refuse a NaN or denormal operand not known to be `clean`.
/// Exact, and without those operands nothing is raised.
pub fn operands_refused(
    w: &mut WasmBuilder,
    double: bool,
    lanes: Lanes,
    [x, y]: [&WasmLocalV128; 2],
    [x_clean, y_clean]: [bool; 2],
) {
    if clean_operands(
        w,
        [(x, x_clean), (y, y_clean)],
        double,
        lanes != Lanes::Packed,
    ) {
        refused(w, double, lanes);
    }
    else {
        w.const_i32(0);
    }
}

/// RCPPS/RCPSS (0x53) and RSQRTPS/RSQRTSS (0x52) of `x` with the native
/// result `r` (1 / x, 1 / sqrt(x)): push i32 nonzero to refuse a source that
/// is zero, denormal, NaN or infinite (or negative for 0x52) and a result in
/// the denormal range (which simd_fp::reciprocal makes zero). No exceptions.
pub fn reciprocal_refused(
    w: &mut WasmBuilder,
    op: u8,
    scalar: bool,
    x: &WasmLocalV128,
    r: &WasmLocalV128,
) {
    finite(w, x, false);
    tiny(w, x, false);
    // (a result in the denormal range: below the smallest normal)
    w.get_local_v128(r);
    w.simd(0xE0); // f32x4.abs
    splat32(w, 0x0080_0000);
    w.simd(0x43); // f32x4.lt
    w.simd(0x50); // v128.or
    if op == 0x52 {
        w.get_local_v128(x);
        w.simd_zero();
        w.simd(0x43); // negative
        w.simd(0x50);
    }
    w.simd(0x4F); // v128.andnot
    refused(w, false, if scalar { Lanes::Scalar } else { Lanes::Packed });
}
                                                                                                                                                                                                                                                                           source/v64/src/rust/x86tpl/ops.rs                                                                   0000644 0000000 0000000 00000067412 00000000000 013776  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Vector templates that every x86 engine instantiates alike
//! (docs/jit-unification-plan.md P2.4): the SSE arithmetic, the masked
//! compares and the conversions, over an engine's VecOperands. Their
//! admission is native_fp's. What differs between the engines is a property
//! of the operands: where a refused instruction goes (in_place: the exact
//! helper x64::helpers::x64_sse_fp where it stands, as IR Tier-0 ran it until
//! P7.5; else the page tier retries in the interpreter), and the register
//! facts an engine keeps (facts).
//!
//! A template reads its operands and passes every retry point before its
//! first write (store_vec, store_int), so a retry finds the CPU as it was.
use super::native_fp::{self, Lanes};
use super::vec::{
    clean_bits, compare_relation, conversion_inexact, convert_facts, convert_integer,
    float_arithmetic, float_claims, float_facts, integer_conversion_inexact, known_clean, packed,
    Packed,
};
use crate::cpu::global_pointers as gp;
use crate::wasmgen::wasm_builder::{Signature, WasmBuilder, WasmLocalV128, WasmType};

/// An engine's register facts (the page tier's Emitter::xmm_clean: per register, the lanes known to be neither NaN nor
/// denormal) and the instruction's registers
pub struct Facts<'a> {
    pub clean: &'a mut [u8],
    /// The destination
    pub reg: u8,
    /// The first source: the destination, or VEX.vvvv
    pub first: u8,
    /// The r/m register (None: memory)
    pub source: Option<u8>,
}

/// One instruction's operands in an engine (see the module comment)
pub trait VecOperands {
    fn w(&mut self) -> &mut WasmBuilder;
    /// Push the first source register (the destination, or VEX.vvvv)
    fn first(&mut self);
    /// Push the r/m operand: `bytes` of memory, zero-extended (an aligned
    /// m128 checked), or an XMM register, its low `bytes` zero-extended, or
    /// `whole` (the forms that use only the low lane)
    fn source(&mut self, bytes: u8, whole: bool);
    /// Push XMM `r`, whole (another register the form names, such as
    /// BLENDV's mask)
    fn register(&mut self, r: u8);
    /// The XMM/YMM registers there are: 8 outside 64-bit mode, else 16
    fn registers(&self) -> u8;
    /// Whether the r/m operand is memory
    fn memory(&self) -> bool;
    /// Push bits 255:128 of the first source (VEX.256)
    fn first_high(&mut self);
    /// Push bits 255:128 of the r/m register (VEX.256 register forms)
    fn source_high(&mut self);
    /// The m256 r/m operand's halves in two locals, low and high (VEX.256;
    /// `aligned`: 32-byte aligned, else a retry)
    fn source256(&mut self, aligned: bool) -> [WasmLocalV128; 2];
    /// Write YMM destination = (`low`, `high`)
    fn store256(&mut self, low: &WasmLocalV128, high: &WasmLocalV128);
    /// Write `halves` to the r/m operand: the m256 (`aligned`: 32-byte, else
    /// a retry, before anything is written) or the YMM register
    fn store256_rm(&mut self, halves: &[WasmLocalV128; 2], aligned: bool);
    /// Zero bits 255:128 of YMM `r`
    fn zero_upper(&mut self, r: u8);
    /// Push the destination register's value (FMA reads it)
    fn destination(&mut self);
    /// Whether the host's relaxed multiply-adds fuse (FMA natively,
    /// native_fp::fused)
    fn relaxed_fma(&self) -> bool;
    /// The address of the exact helpers' operand block
    /// (runtime::tier0::T0_SSE_FP, pinned when compilations replay)
    fn sse_fp_operands(&self) -> u32;
    /// XMM `r` = `value`, bits 255:128 zeroed (a VEX form's write)
    fn store_register(&mut self, r: u8, value: &WasmLocalV128);
    /// Write the low `bytes` of `value` to the destination, keeping the
    /// first source's other bytes (16: all of `value`)
    fn store_vec(&mut self, value: &WasmLocalV128, bytes: u8);
    /// Write the integer on the stack, an i32 (an i64 if `wide`), to the
    /// destination register
    fn store_int(&mut self, wide: bool);
    /// Retry the instruction in the interpreter if the i32 on the stack is
    /// nonzero
    fn retry_if(&mut self);
    /// Push i32 nonzero if MXCSR refuses native results
    /// (native_fp::mxcsr_refused: PE set; the templates that find inexact
    /// results themselves, where detects_inexact, ask
    /// native_fp::mxcsr_refused_any_pe instead)
    fn mxcsr_refused(&mut self);
    /// Whether a refused instruction runs exactly in place (exact_open);
    /// else it retries
    fn in_place(&self) -> bool;
    /// Whether the conversion templates may run with MXCSR.PE clear and set
    /// it for an inexact result themselves (the page tier); else they ask
    /// mxcsr_refused, which wants PE set
    fn detects_inexact(&self) -> bool { false }
    /// If the i32 on the stack is nonzero, open a block that runs the
    /// instruction exactly on (`destination`, `source`) with `imm8` (None:
    /// the instruction's own); a fault retries
    fn exact_open(
        &mut self,
        destination: &WasmLocalV128,
        source: &WasmLocalV128,
        imm8: Option<u32>,
    );
    /// Push the v128 result of exact_open's run
    fn exact_result(&mut self);
    /// The register facts, if the engine keeps them
    fn facts(&mut self) -> Option<Facts<'_>> { None }

    /// Refuse the instruction if the i32 on the stack is nonzero: `result`
    /// is the exact one (in place), or it retries
    fn refused(
        &mut self,
        destination: &WasmLocalV128,
        source: &WasmLocalV128,
        imm8: Option<u32>,
        result: &WasmLocalV128,
    ) {
        if self.in_place() {
            self.exact_open(destination, source, imm8);
            self.exact_result();
            self.w().set_local_v128(result);
            self.w().block_end();
        }
        else {
            self.retry_if();
        }
    }
}

/// Whether the first source and the r/m register are known to hold `lanes`
/// clean (nothing is known without facts)
fn known<T: VecOperands>(t: &mut T, lanes: u8) -> [bool; 2] {
    t.facts().map_or([false; 2], |f| {
        known_clean(f.clean, lanes, f.first, f.source)
    })
}
/// The first source's facts, read before the destination is written
fn first_facts<T: VecOperands>(t: &mut T) -> u8 {
    t.facts().map_or(0, |f| f.clean[f.first as usize])
}

/// The bytes a form reads and writes: 16 packed, else the low lane
fn lane_bytes(double: bool, scalar: bool) -> u8 {
    match (scalar, double) {
        (false, _) => 16,
        (true, true) => 8,
        (true, false) => 4,
    }
}

/// SQRT (`opcode` 0x51), RSQRT (0x52), RCP (0x53), ADD (0x58), MUL (0x59),
/// SUB (0x5C), MIN (0x5D), DIV (0x5E) and MAX (0x5F), PS, PD, SS and SD:
/// natively only where the result is cpu::simd_fp's, MXCSR too
pub fn float<T: VecOperands>(t: &mut T, opcode: u8, double: bool, scalar: bool) {
    if t.detects_inexact() && matches!(opcode, 0x51 | 0x58 | 0x59 | 0x5C | 0x5E) {
        return float_inexact(t, opcode, double, scalar);
    }
    let bytes = lane_bytes(double, scalar);
    // Scalar forms compute (and NaN-check) only the low lane.
    t.source(bytes, true);
    let src = t.w().set_new_local_v128();
    t.first();
    let dst = t.w().set_new_local_v128();
    float_arithmetic(t.w(), opcode, double, &dst, &src);
    let result = t.w().set_new_local_v128();
    if matches!(opcode, 0x52 | 0x53) {
        native_fp::reciprocal_refused(t.w(), opcode, scalar, &src, &result);
    }
    else {
        let lanes = clean_bits(double, scalar);
        let source = t.facts().and_then(|f| f.source);
        let known = known(t, lanes);
        // a cheap first test where it saves work (zeros fail it)
        let unsure = native_fp::arithmetic_unsure(
            t.w(),
            opcode,
            double,
            scalar,
            [&dst, &src],
            known,
            &result,
        );
        if unsure {
            // (no hint: zero-heavy data takes this path every time)
            t.w().if_void();
        }
        native_fp::arithmetic_refused(t.w(), opcode, double, scalar, [&dst, &src], known, &result);
        // (the facts of an admitted form hold only for admitted operands:
        // float_claims; an engine without facts claims nothing)
        let claims = t.facts().is_some() && float_claims(opcode, source, known);
        if claims {
            t.retry_if();
        }
        else {
            t.refused(&dst, &src, None, &result);
        }
        if unsure {
            t.w().block_end();
        }
        if !matches!(opcode, 0x5D | 0x5F) {
            // (a second exact run after refused lanes is harmless)
            t.mxcsr_refused();
            t.refused(&dst, &src, None, &result);
        }
    }
    if matches!(opcode, 0x52 | 0x53) {
        t.refused(&dst, &src, None, &result);
    }
    let before = first_facts(t);
    t.store_vec(&result, bytes);
    for v in [src, dst, result] {
        t.w().free_local_v128(v);
    }
    if let Some(f) = t.facts() {
        float_facts(f.clean, opcode, double, scalar, f.reg, f.source, before);
    }
}

/// float's SQRT, ADD, MUL, SUB and DIV for an engine that sets PE itself
/// (detects_inexact: the page tier, docs/jit-unification-plan.md P4.18),
/// where MXCSR.PE may be clear and DAZ or FZ set. With mxcsr_refused's
/// condition an admitted result is final, as for Tier-0. Else (rarely),
/// with every exception masked and rounding to nearest: FZ refuses a sum or
/// difference it would flush, and with PE clear an inexact result sets PE
/// (native_fp::inexact). Refused lanes, any other MXCSR and what
/// native_fp::inexact cannot decide take the engine's refused path (in
/// place: the exact helper).
fn float_inexact<T: VecOperands>(t: &mut T, opcode: u8, double: bool, scalar: bool) {
    let bytes = lane_bytes(double, scalar);
    t.source(bytes, true);
    let src = t.w().set_new_local_v128();
    t.first();
    let dst = t.w().set_new_local_v128();
    float_arithmetic(t.w(), opcode, double, &dst, &src);
    let result = t.w().set_new_local_v128();
    let lanes = clean_bits(double, scalar);
    let source = t.facts().and_then(|f| f.source);
    let known = known(t, lanes);
    // (facts that hold only for admitted operands retry the refused ones:
    // float_claims)
    let claims = t.facts().is_some() && float_claims(opcode, source, known);
    t.w().const_i32(0);
    let refused = t.w().set_new_local();
    let unsure =
        native_fp::arithmetic_unsure(t.w(), opcode, double, scalar, [&dst, &src], known, &result);
    if unsure {
        t.w().if_void();
    }
    native_fp::arithmetic_refused(t.w(), opcode, double, scalar, [&dst, &src], known, &result);
    if claims {
        t.retry_if();
    }
    else {
        t.w().set_local(&refused);
    }
    if unsure {
        t.w().block_end();
    }
    t.mxcsr_refused();
    t.w().hint(false);
    t.w().if_void();
    t.w().get_local(&refused);
    t.w().eqz_i32();
    t.w().if_void();
    native_fp::masked_nearest_refused(t.w());
    if matches!(opcode, 0x58 | 0x5C) {
        native_fp::flush_to_zero(t.w());
        native_fp::flushed(t.w(), double, scalar, &result);
        t.w().and_i32();
        t.w().or_i32();
    }
    t.w().tee_local(&refused);
    t.w().eqz_i32();
    t.w().if_void();
    native_fp::precision_clear(t.w());
    t.w().if_void();
    if native_fp::inexact_decides(opcode, double) {
        if native_fp::inexact_undecided(t.w(), opcode, double, scalar, [&dst, &src], &result) {
            t.w().tee_local(&refused);
            t.w().eqz_i32();
            t.w().if_void();
        }
        native_fp::inexact(t.w(), opcode, double, scalar, [&dst, &src], &result);
        native_fp::inexact_pe(t.w());
        if double && matches!(opcode, 0x59 | 0x5E) {
            t.w().block_end();
        }
    }
    else {
        t.w().const_i32(1);
        t.w().set_local(&refused);
    }
    t.w().block_end();
    t.w().block_end();
    t.w().block_end();
    t.w().block_end();
    t.w().get_local(&refused);
    t.refused(&dst, &src, None, &result);
    t.w().free_local(refused);
    let before = first_facts(t);
    t.store_vec(&result, bytes);
    for v in [src, dst, result] {
        t.w().free_local_v128(v);
    }
    if let Some(f) = t.facts() {
        float_facts(f.clean, opcode, double, scalar, f.reg, f.source, before);
    }
}

/// CMPPS, CMPPD, CMPSS and CMPSD with `predicate` (imm8[2:0], VEX
/// imm8[4:0]): natively for operands neither NaN nor denormal, which raise
/// nothing and whose result imm8[2:0] decides (simd_fp::Fp::compare)
pub fn compare_mask<T: VecOperands>(t: &mut T, double: bool, scalar: bool, predicate: u8) {
    let bytes = lane_bytes(double, scalar);
    t.source(bytes, true);
    let src = t.w().set_new_local_v128();
    t.first();
    let dst = t.w().set_new_local_v128();
    compare_relation(t.w(), double, predicate, &dst, &src);
    let result = t.w().set_new_local_v128();
    let known = known(t, clean_bits(double, scalar));
    if known != [true, true] {
        // a NaN or denormal operand raises IE or DE, and a NaN makes them
        // unordered
        let lanes = if scalar { Lanes::Scalar } else { Lanes::Packed };
        native_fp::operands_refused(t.w(), double, lanes, [&dst, &src], known);
        t.refused(&dst, &src, Some(predicate as u32), &result);
    }
    t.store_vec(&result, bytes);
    for v in [src, dst, result] {
        t.w().free_local_v128(v);
    }
}

/// The conversions of one Wasm operation (`opcode`: f64x2.promote_low_f32x4
/// 0x5F, f32x4.demote_f64x2_zero 0x5E, f32x4.convert_i32x4_s 0xFA,
/// f64x2.convert_low_i32x4_s 0xFE) from `source` bytes to `result` bytes:
/// CVTPS2PD, CVTSS2SD, CVTPD2PS, CVTSD2SS, CVTDQ2PS and CVTDQ2PD
pub fn convert<T: VecOperands>(t: &mut T, opcode: u32, source: u8, result: u8) {
    t.source(source, false);
    let x = t.w().set_new_local_v128();
    t.w().get_local_v128(&x);
    t.w().simd(opcode);
    let v = t.w().set_new_local_v128();
    // (the scalar forms CVTSS2SD and CVTSD2SS write less than 16 bytes and
    // keep the destination's upper bytes)
    let scalar = result < 16;
    if scalar {
        t.first();
    }
    else {
        t.w().simd_zero();
    }
    let destination = t.w().set_new_local_v128();
    match opcode {
        // f32 to f64: exact
        0x5F => {
            let lanes = if scalar { Lanes::Scalar } else { Lanes::LowPair };
            let known = known(t, clean_bits(false, scalar))[1];
            native_fp::operands_refused(t.w(), false, lanes, [&x, &x], [known, true]);
        },
        0x5E => native_fp::narrowing_refused(t.w(), scalar, &x, &v),
        _ => t.w().const_i32(0),
    }
    // (an admitted result is a fact: convert_facts)
    t.retry_if();
    if opcode == 0xFA && t.detects_inexact() {
        // CVTDQ2PS raises nothing but PE: an exact result is right in every
        // MXCSR state, an inexact one needs rounding to nearest and PE
        // masked, and sets PE
        conversion_inexact(t.w(), opcode, scalar, &x, &v);
        let inexact = t.w().set_new_local();
        t.w().get_local(&inexact);
        native_fp::rounding_refused(t.w());
        t.w().and_i32();
        t.retry_if();
        t.w().get_local(&inexact);
        native_fp::inexact_pe(t.w());
        t.w().free_local(inexact);
    }
    else if matches!(opcode, 0x5E | 0xFA) {
        // (CVTDQ2PS: only PE)
        if t.detects_inexact() {
            native_fp::mxcsr_refused_any_pe(t.w());
        }
        else {
            t.mxcsr_refused();
        }
        t.refused(&destination, &x, None, &v);
        if t.detects_inexact() {
            conversion_inexact(t.w(), opcode, scalar, &x, &v);
            native_fp::inexact_pe(t.w());
        }
    }
    let before = first_facts(t);
    t.store_vec(&v, result);
    for local in [v, x, destination] {
        t.w().free_local_v128(local);
    }
    if let Some(f) = t.facts() {
        convert_facts(f.clean, opcode, scalar, f.reg, f.source, before);
    }
}

/// CVT(T)PS2DQ and CVT(T)PD2DQ: natively unless a lane is NaN, out of the
/// i32 range or, with MXCSR's condition, inexact
pub fn convert_to_integers<T: VecOperands>(t: &mut T, double: bool, truncate: bool) {
    t.source(16, false);
    let x = t.w().set_new_local_v128();
    t.w().get_local_v128(&x);
    let out_of_range = convert_integer(t.w(), double, truncate);
    let v = t.w().set_new_local_v128();
    // a NaN or out-of-range lane raises IE; an inexact one PE
    t.w().get_local(&out_of_range);
    if t.detects_inexact() {
        native_fp::mxcsr_refused_any_pe(t.w());
    }
    else {
        t.mxcsr_refused();
    }
    t.w().or_i32();
    t.refused(&v, &x, None, &v);
    if t.detects_inexact() {
        integer_conversion_inexact(t.w(), double, truncate, &x);
        native_fp::inexact_pe(t.w());
    }
    t.w().free_local(out_of_range);
    t.store_vec(&v, 16);
    t.w().free_local_v128(v);
    t.w().free_local_v128(x);
}

/// PMOVMSKB (`lane` 1), MOVMSKPS (4) and MOVMSKPD (8) r32, xmm: the sign bits
/// of the lanes (register forms only)
pub fn move_mask<T: VecOperands>(t: &mut T, lane: u8) {
    t.source(16, true);
    t.w().simd(match lane {
        1 => 0x64, // i8x16.bitmask
        4 => 0xA4, // i32x4.bitmask
        _ => 0xC4, // i64x2.bitmask
    });
    t.store_int(false);
}

/// BLENDVPS, BLENDVPD and PBLENDVB (`lane` 4, 8, 1): the source's lanes
/// whose sign bit in XMM `mask` (XMM0, VEX imm8[7:4]) is set
pub fn blend_variable<T: VecOperands>(t: &mut T, lane: u8, mask: u8) {
    t.source(16, false);
    let src = t.w().set_new_local_v128();
    t.first();
    let dst = t.w().set_new_local_v128();
    // the source's lanes where the mask's lane is negative
    t.w().get_local_v128(&src);
    t.w().get_local_v128(&dst);
    t.register(mask);
    t.w().const_i32(lane as i32 * 8 - 1);
    t.w().simd(match lane {
        1 => 0x6C, // i8x16.shr_s
        4 => 0xAC, // i32x4.shr_s
        _ => 0xCC, // i64x2.shr_s
    });
    t.w().simd(0x52); // v128.bitselect
    let result = t.w().set_new_local_v128();
    t.store_vec(&result, 16);
    for v in [src, dst, result] {
        t.w().free_local_v128(v);
    }
}

/// ROUNDPS, ROUNDPD, ROUNDSS and ROUNDSD with `imm8`: Wasm's rounding of the
/// lanes (a scalar form's low one into the destination), imm8[1:0]'s mode,
/// or MXCSR.RC's with imm8[2], admitted to nearest only. Refused: a NaN lane
/// (its payload; an SNaN raises IE), DAZ, and an inexact lane while PE is
/// reported (imm8[3] clear) and unmasked. Denormals need no DE (ROUND has
/// none); a result is integral, never tiny. PE is set here, after the last
/// refusal.
pub fn round<T: VecOperands>(t: &mut T, double: bool, scalar: bool, imm8: u8) {
    let bytes = if double { 8 } else { 4 };
    if scalar {
        t.source(bytes, true);
    }
    else {
        t.source(16, false);
    }
    let source = t.w().set_new_local_v128();
    t.first();
    let destination = t.w().set_new_local_v128();
    let mode = if imm8 & 4 != 0 { 0 } else { imm8 & 3 };
    t.w().get_local_v128(&source);
    t.w().simd(match (double, mode) {
        (false, 0) => 0x6A, // f32x4.nearest
        (false, 1) => 0x68, // f32x4.floor
        (false, 2) => 0x67, // f32x4.ceil
        (false, _) => 0x69, // f32x4.trunc
        (true, 0) => 0x94,  // f64x2.nearest
        (true, 1) => 0x75,  // f64x2.floor
        (true, 2) => 0x74,  // f64x2.ceil
        (true, _) => 0x7A,  // f64x2.trunc
    });
    let rounded = t.w().set_new_local_v128();
    // per lane: a NaN (x != x), an inexact result (r != x); the lanes that
    // count: all, or the low one
    let ne = if double { 0x48 } else { 0x42 };
    let any = |w: &mut WasmBuilder, a: &WasmLocalV128, b: &WasmLocalV128| {
        w.get_local_v128(a);
        w.get_local_v128(b);
        w.simd(ne);
        if scalar {
            w.simd_lane(0x1B, 0); // i32x4.extract_lane
        }
        else {
            w.simd(0x53); // v128.any_true
        }
    };
    any(t.w(), &rounded, &source);
    let inexact = t.w().set_new_local();
    t.w().load_fixed_i32(gp::mxcsr as u32);
    let mxcsr = t.w().set_new_local();
    any(t.w(), &source, &source);
    t.w().get_local(&mxcsr);
    t.w()
        .const_i32(0x40 | if imm8 & 4 != 0 { 0x6000 } else { 0 });
    t.w().and_i32();
    t.w().or_i32();
    if imm8 & 8 == 0 {
        // (PE unmasked: PM, MXCSR bit 12, clear)
        t.w().get_local(&inexact);
        t.w().get_local(&mxcsr);
        t.w().const_i32(0x1000);
        t.w().and_i32();
        t.w().eqz_i32();
        t.w().and_i32();
        t.w().or_i32();
    }
    let refused = t.w().set_new_local();
    if scalar {
        t.w().get_local_v128(&rounded);
        t.w().get_local_v128(&destination);
        let mut lanes = [0; 16];
        for (k, lane) in lanes.iter_mut().enumerate() {
            *lane = if k < bytes as usize { k as u8 } else { 16 + k as u8 };
        }
        t.w().simd_shuffle(lanes);
    }
    else {
        t.w().get_local_v128(&rounded);
    }
    let v = t.w().set_new_local_v128();
    if imm8 & 8 == 0 {
        // MXCSR.PE for an inexact lane (when not refused)
        t.w().get_local(&inexact);
        t.w().get_local(&refused);
        t.w().eqz_i32();
        t.w().and_i32();
        t.w().if_void();
        t.w().const_i32(gp::mxcsr as i32);
        t.w().get_local(&mxcsr);
        t.w().const_i32(0x20);
        t.w().or_i32();
        t.w().store_aligned_i32(0);
        t.w().block_end();
    }
    t.w().get_local(&refused);
    t.refused(&destination, &source, None, &v);
    t.store_vec(&v, if scalar { bytes } else { 16 });
    // (no lane facts: the exact path may produce a NaN)
    if let Some(f) = t.facts() {
        f.clean[f.reg as usize] = 0;
    }
    for local in [refused, mxcsr, inexact] {
        t.w().free_local(local);
    }
    for v128 in [v, rounded, destination, source] {
        t.w().free_local_v128(v128);
    }
}

/// VZEROUPPER: bits 255:128 of every YMM register zeroed
pub fn zero_upper<T: VecOperands>(t: &mut T) {
    for r in 0..t.registers() {
        t.zero_upper(r);
    }
}

/// VZEROALL: every YMM register zeroed
pub fn zero_all<T: VecOperands>(t: &mut T) {
    t.w().simd_zero();
    let zero = t.w().set_new_local_v128();
    for r in 0..t.registers() {
        t.store_register(r, &zero);
    }
    t.w().free_local_v128(zero);
}

/// The r/m operand of a VEX.256 form in two locals, low and high (both
/// halves read before anything is written)
fn source256<T: VecOperands>(t: &mut T, aligned: bool) -> [WasmLocalV128; 2] {
    if t.memory() {
        return t.source256(aligned);
    }
    t.source(16, true);
    let low = t.w().set_new_local_v128();
    t.source_high();
    [low, t.w().set_new_local_v128()]
}

/// VMOVUPS/UPD/DQU and VMOVAPS/APD/DQA ymm, ymm/m256 (`aligned`: the A forms)
pub fn load256<T: VecOperands>(t: &mut T, aligned: bool) {
    let memory = t.memory();
    let halves = source256(t, aligned);
    t.store256(&halves[0], &halves[1]);
    if let Some(f) = t.facts().filter(|_| !memory) {
        // (a register's lanes keep their facts)
        if let Some(source) = f.source {
            f.clean[f.reg as usize] = f.clean[source as usize];
        }
    }
    for v in halves {
        t.w().free_local_v128(v);
    }
}

/// VMOVUPS/UPD/DQU, VMOVAPS/APD/DQA and VMOVNTPS/PD/DQ ymm/m256, ymm
/// (`aligned`: the A and NT forms)
pub fn store256<T: VecOperands>(t: &mut T, aligned: bool) {
    let memory = t.memory();
    t.first();
    let low = t.w().set_new_local_v128();
    t.first_high();
    let halves = [low, t.w().set_new_local_v128()];
    t.store256_rm(&halves, aligned);
    if let Some(f) = t.facts().filter(|_| !memory) {
        if let Some(source) = f.source {
            f.clean[source as usize] = f.clean[f.reg as usize];
        }
    }
    for v in halves {
        t.w().free_local_v128(v);
    }
}

/// The packed integer operations of AVX2 (VEX.256): `op` on each half of
/// the first source and the r/m operand
pub fn packed256<T: VecOperands>(t: &mut T, op: Packed) {
    // (both halves of both sources before the destination is written)
    let source = source256(t, false);
    t.first();
    let low = t.w().set_new_local_v128();
    t.first_high();
    let first = [low, t.w().set_new_local_v128()];
    packed(t.w(), op, &first[0], &source[0], 16);
    let low = t.w().set_new_local_v128();
    packed(t.w(), op, &first[1], &source[1], 16);
    let result = [low, t.w().set_new_local_v128()];
    t.store256(&result[0], &result[1]);
    for v in source.into_iter().chain(first).chain(result) {
        t.w().free_local_v128(v);
    }
}

/// VPMOVMSKB (`lane` 1), VMOVMSKPS (4) and VMOVMSKPD (8) r32, ymm: the sign
/// bits of both halves (register forms only)
pub fn move_mask256<T: VecOperands>(t: &mut T, lane: u8) {
    let bitmask = match lane {
        1 => 0x64, // i8x16.bitmask
        4 => 0xA4, // i32x4.bitmask
        _ => 0xC4, // i64x2.bitmask
    };
    t.source(16, true);
    t.w().simd(bitmask);
    t.source_high();
    t.w().simd(bitmask);
    t.w().const_i32(16 / lane as i32);
    t.w().shl_i32();
    t.w().or_i32();
    t.store_int(false);
}

/// VBROADCASTSS, VBROADCASTSD and VPBROADCASTB/W/D/Q: the element (`bytes`)
/// in every lane, of both halves (`wide`, VEX.256) or of the low one
pub fn broadcast<T: VecOperands>(t: &mut T, bytes: u8, wide: bool) {
    t.source(bytes, false);
    let element = t.w().set_new_local_v128();
    t.w().get_local_v128(&element);
    t.w().get_local_v128(&element);
    t.w().simd_shuffle(std::array::from_fn(|k| k as u8 % bytes));
    let value = t.w().set_new_local_v128();
    if wide {
        t.store256(&value, &value);
    }
    else {
        t.store_vec(&value, 16);
    }
    t.w().free_local_v128(element);
    t.w().free_local_v128(value);
}

/// FMA's VEX.128 and scalar forms (`op` the opcode byte, `double` VEX.W1):
/// natively where the host's relaxed multiply-adds fuse
/// (native_fp::fused), a scalar form's other lanes the destination's; the
/// exact helper runtime::tier0::ir_t0_fma in place where a lane or MXCSR is
/// refused, or always without fusing multiply-adds (its fault retries)
pub fn fused<T: VecOperands>(t: &mut T, op: u8, double: bool) {
    // (the r/m operand first: its access may retry; a scalar form's 32 or
    // 64 bits)
    let scalar = op & 0xF >= 9 && op & 1 == 1;
    t.source(
        if !scalar {
            16
        }
        else if double {
            8
        }
        else {
            4
        },
        false,
    );
    let third = t.w().set_new_local_v128();
    // (both registers read before the branch)
    let native = t.relaxed_fma().then(|| {
        t.destination();
        let d = t.w().set_new_local_v128();
        t.first();
        let f = t.w().set_new_local_v128();
        let r = native_fp::fused(t.w(), op, double, scalar, [&d, &f, &third]);
        t.mxcsr_refused();
        t.w().or_i32();
        let refused = t.w().set_new_local();
        if scalar {
            let bytes = if double { 8 } else { 4 };
            t.w().get_local_v128(&r);
            t.w().get_local_v128(&d);
            let mut lanes = [0; 16];
            for (k, lane) in lanes.iter_mut().enumerate() {
                *lane = if k < bytes { k as u8 } else { 16 + k as u8 };
            }
            t.w().simd_shuffle(lanes);
            t.w().set_local_v128(&r);
        }
        t.w().get_local(&refused);
        t.w().free_local(refused);
        t.w().free_local_v128(d);
        t.w().free_local_v128(f);
        t.w().hint(false);
        t.w().if_void();
        r
    });
    let operands = t.sse_fp_operands();
    t.w().const_i32(operands as i32);
    t.destination();
    t.w().simd_memory(0x0B, 4); // v128.store
    t.w().const_i32((operands + 16) as i32);
    t.first();
    t.w().simd_memory(0x0B, 4);
    t.w().const_i32((operands + 32) as i32);
    t.w().get_local_v128(&third);
    t.w().simd_memory(0x0B, 4);
    t.w().const_i32(op as i32 | (double as i32) << 8);
    t.w().call_signature(
        "x64_fma",
        Signature::new(&[WasmType::I32], &[WasmType::I32]),
    );
    t.retry_if();
    t.w().const_i32(operands as i32);
    t.w().simd_memory(0x00, 4); // v128.load
    let result = match native {
        Some(r) => {
            t.w().set_local_v128(&r);
            t.w().block_end();
            r
        },
        None => t.w().set_new_local_v128(),
    };
    t.store_vec(&result, 16);
    t.w().free_local_v128(third);
    t.w().free_local_v128(result);
}
                                                                                                                                                                                                                                                      source/v64/src/rust/x86tpl/string.rs                                                                0000644 0000000 0000000 00000001226 00000000000 014472  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Leaves of the REP string templates (docs/jit-unification-plan.md P3.1b):
//! the bulk operations a REP MOVS or STOS becomes when it is done at once,
//! for every x86 engine (Tier-0's template, the page tier's Op::Movs and
//! Op::Stos)
use crate::wasmgen::wasm_builder::WasmBuilder;

/// memory.copy over the guest memory: (destination, source, length) on
/// the stack, host addresses
pub fn memory_copy(w: &mut WasmBuilder) {
    w.op(0xFC);
    w.op(10);
    w.op(0);
    w.op(0);
}
/// memory.fill over the guest memory: (destination, byte, length) on the
/// stack
pub fn memory_fill(w: &mut WasmBuilder) {
    w.op(0xFC);
    w.op(11);
    w.op(0);
}
                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/rust/x86tpl/vec.rs                                                                   0000644 0000000 0000000 00000053676 00000000000 013761  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Vector leaves of x86 semantics (docs/jit-unification-plan.md P2.2): the
//! table of packed integer and logic operations (Packed) and its emission,
//! the immediate shifts, the SSE arithmetic, compares and conversions, the
//! call of the exact SSE helper (x64::helpers::x64_sse_fp) and the
//! register facts behind native_fp's admission. The page tier uses them
//! (P2.3 on; IR Tier-0 until P7.5); tests/x86tpl/pagegen_leaf_digests.rs
//! pins their output.
use crate::wasmgen::leaves::{self, Shift};
use crate::wasmgen::wasm_builder::{Signature, WasmBuilder, WasmLocal, WasmLocalV128, WasmType};

/// Register facts (the page tier's Emitter::xmm_clean): lanes known to be neither NaN
/// nor denormal, as single precision (the low lane, all lanes) or double
/// precision.
pub const CLEAN_SS: u8 = 1;
pub const CLEAN_PS: u8 = 2;
pub const CLEAN_SD: u8 = 4;
pub const CLEAN_PD: u8 = 8;

#[derive(Clone, Copy, Debug)]
pub enum Packed {
    /// i8x16.shuffle over (destination, source)
    Shuffle([u8; 16]),
    /// i8x16.shuffle over (destination, zero)
    ShuffleZero([u8; 16]),
    /// PSHUFB: the destination's bytes by the source's indices, masked
    /// (bit 7 selects zero)
    Swizzle(u8),
    Binary(u32),
    AndNot,
    Unpack(u8, bool),
    Pack(u32),
    /// Shift by the source's low quadword: (opcode, lane bits, arithmetic).
    Shift(u32, u32, bool),
    MulHigh(bool),
    /// PMULUDQ (false), PMULDQ (true): the even dwords' 64-bit products
    MulDwords(bool),
    Sad,
}

/// Packed integer and logic operations (Wasm SIMD opcodes).
pub fn packed_op(code: u8, mmx: bool) -> Option<Packed> {
    Some(match code {
        0xFC => Packed::Binary(0x6E),
        0xFD => Packed::Binary(0x8E),
        0xFE => Packed::Binary(0xAE),
        0xD4 => Packed::Binary(0xCE),
        0xF8 => Packed::Binary(0x71),
        0xF9 => Packed::Binary(0x91),
        0xFA => Packed::Binary(0xB1),
        0xFB => Packed::Binary(0xD1),
        0xEC => Packed::Binary(0x6F),
        0xED => Packed::Binary(0x8F),
        0xDC => Packed::Binary(0x70),
        0xDD => Packed::Binary(0x90),
        0xE8 => Packed::Binary(0x72),
        0xE9 => Packed::Binary(0x92),
        0xD8 => Packed::Binary(0x73),
        0xD9 => Packed::Binary(0x93),
        0x64 => Packed::Binary(0x27),
        0x65 => Packed::Binary(0x31),
        0x66 => Packed::Binary(0x3B),
        0x74 => Packed::Binary(0x23),
        0x75 => Packed::Binary(0x2D),
        0x76 => Packed::Binary(0x37),
        0xDA => Packed::Binary(0x77),
        0xDE => Packed::Binary(0x79),
        0xEA => Packed::Binary(0x96),
        0xEE => Packed::Binary(0x98),
        0xE0 => Packed::Binary(0x7B),
        0xE3 => Packed::Binary(0x9B),
        0xE4 => Packed::MulHigh(false),
        0xE5 => Packed::MulHigh(true),
        0xF4 => Packed::MulDwords(false),
        0xF6 => Packed::Sad,
        0xD5 => Packed::Binary(0x95),
        0xF5 => Packed::Binary(0xBA),
        0xDB => Packed::Binary(0x4E),
        0xDF => Packed::AndNot,
        0xEB => Packed::Binary(0x50),
        0xEF => Packed::Binary(0x51),
        0x60 => Packed::Unpack(1, false),
        0x61 => Packed::Unpack(2, false),
        0x62 => Packed::Unpack(4, false),
        0x68 => Packed::Unpack(1, true),
        0x69 => Packed::Unpack(2, true),
        0x6A => Packed::Unpack(4, true),
        0x6C if !mmx => Packed::Unpack(8, false),
        0x6D if !mmx => Packed::Unpack(8, true),
        0x63 => Packed::Pack(0x65),
        0x67 => Packed::Pack(0x66),
        0x6B => Packed::Pack(0x85),
        0xD1 => Packed::Shift(0x8D, 16, false),
        0xD2 => Packed::Shift(0xAD, 32, false),
        0xD3 => Packed::Shift(0xCD, 64, false),
        0xE1 => Packed::Shift(0x8C, 16, true),
        0xE2 => Packed::Shift(0xAC, 32, true),
        0xF1 => Packed::Shift(0x8B, 16, false),
        0xF2 => Packed::Shift(0xAB, 32, false),
        0xF3 => Packed::Shift(0xCB, 64, false),
        _ => return None,
    })
}

/// Shuffle lanes of PSHUFW/PSHUFD/PSHUFLW/PSHUFHW/SHUFPS/SHUFPD over
/// (first, source); `two`: the first operand is the destination, else the
/// source itself.
pub fn shuffle_lanes(op: u32, imm: u32) -> ([u8; 16], bool) {
    let mut lanes = [0; 16];
    for i in 0..16u32 {
        lanes[i as usize] = match op {
            0x0F70 => ((imm >> (2 * (i / 2 % 4)) & 3) * 2 + i % 2) as u8,
            0x660F70 => ((imm >> (2 * (i / 4)) & 3) * 4 + i % 4) as u8,
            0xF20F70 if i < 8 => ((imm >> (2 * (i / 2)) & 3) * 2 + i % 2) as u8,
            0xF30F70 if i >= 8 => (8 + (imm >> (2 * ((i - 8) / 2)) & 3) * 2 + i % 2) as u8,
            0x0FC6 => ((imm >> (2 * (i / 4)) & 3) * 4 + i % 4 + if i >= 8 { 16 } else { 0 }) as u8,
            0x660FC6 => ((imm >> (i / 8) & 1) * 8 + i % 8 + if i >= 8 { 16 } else { 0 }) as u8,
            _ => i as u8,
        };
    }
    (lanes, matches!(op, 0x0FC6 | 0x660FC6))
}

/// The shuffle of PSHUFW/PSHUFD/PSHUFLW/PSHUFHW/SHUFPS/SHUFPD with `imm` over
/// (destination, source) (shuffle_lanes; the one-operand forms select from
/// the source only)
pub fn shuffle(op: u32, imm: u32) -> Packed {
    let (mut lanes, two) = shuffle_lanes(op, imm);
    if !two {
        for lane in &mut lanes {
            *lane += 16;
        }
    }
    Packed::Shuffle(lanes)
}

impl Packed {
    /// The byte lanes of a shuffle over (destination, source)
    pub fn lanes(self, bytes: u8) -> Option<[u8; 16]> {
        match self {
            Packed::Shuffle(lanes) => Some(lanes),
            Packed::Unpack(width, high) => Some(leaves::interleave_lanes(width, high, bytes)),
            _ => None,
        }
    }
}

/// PALIGNR with `imm8` on `n`-byte operands (simd_int::palignr_lanes)
pub fn palignr(imm8: u8, n: u32) -> Packed {
    match crate::cpu::simd_int::palignr_lanes(imm8, n as usize) {
        (lanes, true) => Packed::ShuffleZero(lanes),
        (lanes, false) => Packed::Shuffle(lanes),
    }
}

/// The packed SSE4.1/SSE4.2 forms of one Wasm SIMD operation over
/// (destination, source), by catalogue key `op` (a VEX form's legacy one):
/// the hot PMINUD and its siblings, and the blends with `imm8` as shuffles
pub fn sse4_packed(op: u32, imm8: Option<u32>) -> Option<Packed> {
    let blend = |size: u8, mask: u32| {
        let mut lanes = [0; 16];
        for (k, lane) in lanes.iter_mut().enumerate() {
            *lane = k as u8 + if mask >> (k as u8 / size) & 1 != 0 { 16 } else { 0 };
        }
        Packed::Shuffle(lanes)
    };
    Some(match op {
        0x660F3828 => Packed::MulDwords(true), // pmuldq
        0x660F3829 => Packed::Binary(0xD6),    // pcmpeqq: i64x2.eq
        0x660F382B => Packed::Pack(0x86),      // packusdw: i16x8.narrow_i32x4_u
        0x660F3837 => Packed::Binary(0xD9),    // pcmpgtq: i64x2.gt_s
        0x660F3838 => Packed::Binary(0x76),    // pminsb: i8x16.min_s
        0x660F3839 => Packed::Binary(0xB6),    // pminsd: i32x4.min_s
        0x660F383A => Packed::Binary(0x97),    // pminuw: i16x8.min_u
        0x660F383B => Packed::Binary(0xB7),    // pminud: i32x4.min_u
        0x660F383C => Packed::Binary(0x78),    // pmaxsb: i8x16.max_s
        0x660F383D => Packed::Binary(0xB8),    // pmaxsd: i32x4.max_s
        0x660F383E => Packed::Binary(0x99),    // pmaxuw: i16x8.max_u
        0x660F383F => Packed::Binary(0xB9),    // pmaxud: i32x4.max_u
        0x660F3840 => Packed::Binary(0xB5),    // pmulld: i32x4.mul
        0x660F3A0C => blend(4, imm8? & 0xF),
        0x660F3A0D => blend(8, imm8? & 3),
        0x660F3A0E => blend(2, imm8? & 0xFF),
        _ => return None,
    })
}

/// Push op(dst, src) on `bytes`-wide registers (8: MMX, low quadword).
pub fn packed(
    w: &mut WasmBuilder,
    op: Packed,
    dst: &WasmLocalV128,
    src: &WasmLocalV128,
    bytes: u8,
) {
    match op {
        Packed::ShuffleZero(lanes) => {
            w.get_local_v128(dst);
            w.simd_zero();
            w.simd_shuffle(lanes);
        },
        Packed::Swizzle(mask) => {
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.const_i32(mask as i32);
            w.simd(0x0F); // i8x16.splat
            w.simd(0x4E); // v128.and
            w.simd(0x0E); // i8x16.swizzle
        },
        Packed::MulHigh(signed) => {
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.simd(if signed { 0xBC } else { 0xBE });
            if bytes == 16 {
                w.get_local_v128(dst);
                w.get_local_v128(src);
                w.simd(if signed { 0xBD } else { 0xBF });
            }
            else {
                w.simd_zero();
            }
            w.simd_shuffle([2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31]);
        },
        Packed::MulDwords(signed) => {
            for v in [dst, src] {
                w.get_local_v128(v);
                w.simd_zero();
                w.simd_shuffle([0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 22, 23]);
            }
            // i64x2.extmul_low_i32x4_s/u
            w.simd(if signed { 0xDC } else { 0xDE });
        },
        Packed::Sad => {
            // |dst - src| per byte, summed per quadword.
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.simd(0x79);
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.simd(0x77);
            w.simd(0x71);
            w.simd(0x7D);
            w.simd(0x7F);
            let sums = w.set_new_local_v128();
            w.get_local_v128(&sums);
            w.get_local_v128(&sums);
            w.get_local_v128(&sums);
            w.simd_shuffle([4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11]);
            w.simd(0xAE);
            w.simd_zero();
            w.simd_shuffle([0, 1, 2, 3, 16, 17, 18, 19, 8, 9, 10, 11, 16, 17, 18, 19]);
            w.free_local_v128(sums);
        },
        Packed::Shift(opcode, bits, arithmetic) => {
            w.get_local_v128(src);
            w.simd_lane(0x1D, 0);
            let count = w.set_new_local_i64();
            w.get_local_i64(&count);
            w.const_i64((bits - 1) as i64);
            w.gtu_i64();
            w.if_v128();
            if arithmetic {
                w.get_local_v128(dst);
                w.const_i32((bits - 1) as i32);
                w.simd(opcode);
            }
            else {
                w.simd_zero();
            }
            w.else_();
            w.get_local_v128(dst);
            w.get_local_i64(&count);
            w.wrap_i64_to_i32();
            w.simd(opcode);
            w.block_end();
            w.free_local_i64(count);
        },
        _ => {
            if let Packed::AndNot = op {
                w.get_local_v128(src);
                w.get_local_v128(dst);
            }
            else {
                w.get_local_v128(dst);
                w.get_local_v128(src);
            }
            match op {
                Packed::Shuffle(lanes) => w.simd_shuffle(lanes),
                Packed::Binary(opcode) => w.simd(opcode),
                Packed::AndNot => w.simd(0x4F),
                Packed::Pack(opcode) => {
                    w.simd(opcode);
                    if bytes == 8 {
                        w.simd_zero();
                        w.simd_shuffle([0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 22, 23]);
                    }
                },
                Packed::Unpack(..) => w.simd_shuffle(op.lanes(bytes).unwrap()),
                _ => unreachable!(),
            }
        },
    }
}

/// CVT(T)PS2DQ/CVT(T)PD2DQ of the vector on the stack, rounded to nearest
/// (or truncated): push the integer vector and return an i32 local,
/// nonzero if a lane was out of the i32 range (or NaN)
pub fn convert_integer(w: &mut WasmBuilder, double: bool, truncate: bool) -> WasmLocal {
    let input = w.set_new_local_v128();
    if truncate {
        w.get_local_v128(&input);
        w.simd(if double { 0x7A } else { 0x69 });
    }
    else {
        // (admitted only with MXCSR.RC to nearest)
        w.get_local_v128(&input);
        w.simd(if double { 0x94 } else { 0x6A }); // nearest
    }
    let rounded = w.set_new_local_v128();
    w.get_local_v128(&rounded);
    if double {
        w.const_i64(0xC1E0000000000000u64 as i64);
        w.simd(0x12);
    }
    else {
        w.const_i32(0xCF000000u32 as i32);
        w.simd(0x11);
    }
    w.simd(if double { 0x4C } else { 0x46 });
    w.get_local_v128(&rounded);
    if double {
        w.const_i64(0x41E0000000000000);
        w.simd(0x12);
    }
    else {
        w.const_i32(0x4F000000);
        w.simd(0x11);
    }
    w.simd(if double { 0x49 } else { 0x43 });
    w.simd(0x4E);
    if double {
        w.simd_zero();
        w.simd_shuffle([0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 22, 23]);
    }
    let valid = w.set_new_local_v128();
    // (the lanes that exist: 0 and 1 for double precision)
    w.get_local_v128(&valid);
    w.simd(0xA4); // i32x4.bitmask
    w.const_i32(if double { 3 } else { 15 });
    w.and_i32();
    w.const_i32(if double { 3 } else { 15 });
    w.ne_i32();
    let out_of_range = w.set_new_local();
    w.get_local_v128(&rounded);
    w.simd(if double { 0xFC } else { 0xF8 });
    w.const_i32(i32::MIN);
    w.simd(0x11);
    w.get_local_v128(&valid);
    w.simd(0x52);
    if double {
        w.simd_zero();
        w.simd_shuffle([0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23]);
    }
    w.free_local_v128(input);
    w.free_local_v128(rounded);
    w.free_local_v128(valid);
    out_of_range
}

/// Push i32 nonzero if a lane of the conversion `opcode` (ops::convert: 0x5E
/// f64 to f32, 0xFA i32 to f32; the others are exact) of `x` into `v` is
/// inexact, for the lanes it admitted: the low one if `scalar`
pub fn conversion_inexact(
    w: &mut WasmBuilder,
    opcode: u32,
    scalar: bool,
    x: &WasmLocalV128,
    v: &WasmLocalV128,
) {
    if opcode == 0x5E {
        // f32 back to f64 differs
        w.get_local_v128(v);
        w.simd(0x5F); // f64x2.promote_low_f32x4
        w.get_local_v128(x);
        w.simd(0x48); // f64x2.ne
    }
    else {
        // the f32 back to i32 differs, or the f32 is 2^31 (trunc_sat
        // saturates it to i32::MAX)
        w.get_local_v128(v);
        w.simd(0xF8); // i32x4.trunc_sat_f32x4_s
        w.get_local_v128(x);
        w.simd(0x38); // i32x4.ne
        w.get_local_v128(v);
        leaves::splat_i32(w, 0x4F000000);
        w.simd(0x41); // f32x4.eq
        w.simd(0x50); // v128.or
    }
    if scalar {
        w.simd_lane(0x1B, 0); // i32x4.extract_lane
    }
    else {
        w.simd(0x53); // v128.any_true
    }
}

/// Push i32 nonzero if a lane of `x` is not integral after CVT(T)PS2DQ's or
/// CVT(T)PD2DQ's rounding (to nearest, or `truncate`): an inexact result
pub fn integer_conversion_inexact(
    w: &mut WasmBuilder,
    double: bool,
    truncate: bool,
    x: &WasmLocalV128,
) {
    w.get_local_v128(x);
    w.simd(match (double, truncate) {
        (false, false) => 0x6A, // f32x4.nearest
        (false, true) => 0x69,  // f32x4.trunc
        (true, false) => 0x94,  // f64x2.nearest
        (true, true) => 0x7A,   // f64x2.trunc
    });
    w.get_local_v128(x);
    w.simd(if double { 0x48 } else { 0x42 }); // f64x2.ne, f32x4.ne
    w.simd(0x53); // v128.any_true
}

/// PSRLx/PSRAx/PSLLx (`bits` 16, 32 or 64: the lane width) and PSRLDQ/PSLLDQ
/// (128: bytes) of `value` by imm8 `count`, `kind` the ModRM reg (2 PSRL, 4
/// PSRA, 6 PSLL, 3 PSRLDQ, 7 PSLLDQ): push the result
pub fn shift_immediate(w: &mut WasmBuilder, value: &WasmLocalV128, bits: u8, kind: u8, count: u8) {
    let count = count as u32;
    if bits == 128 {
        w.get_local_v128(value);
        w.simd_zero();
        w.simd_shuffle(leaves::byte_shift_lanes(count, kind == 3));
    }
    else if count >= bits as u32 && kind != 4 {
        w.simd_zero();
    }
    else {
        w.get_local_v128(value);
        let shift = match kind {
            6 => Shift::Left,
            4 => Shift::Arithmetic,
            _ => Shift::Logical,
        };
        leaves::shift_lanes(w, bits, shift, count.min(bits as u32 - 1));
    }
}

/// The native operation of SQRT (`opcode` 0x51), RSQRT (0x52), RCP (0x53),
/// ADD (0x58), MUL (0x59), SUB (0x5C), MIN (0x5D), DIV (0x5E) and MAX (0x5F)
/// on (`dst`, `src`), PS or PD (scalar forms use the low lane): push it
pub fn float_arithmetic(
    w: &mut WasmBuilder,
    opcode: u8,
    double: bool,
    dst: &WasmLocalV128,
    src: &WasmLocalV128,
) {
    let base = if double { 0xF0 } else { 0xE4 };
    match opcode {
        0x51 => {
            w.get_local_v128(src);
            w.simd(base - 1); // sqrt
        },
        0x52 | 0x53 => {
            // rsqrt/rcp as the interpreter computes them: 1 / sqrt(x), 1 / x.
            leaves::splat_i32(w, 0x3F800000); // 1.0f
            w.get_local_v128(src);
            if opcode == 0x52 {
                w.simd(0xE3);
            }
            w.simd(0xE7);
        },
        0x5D | 0x5F => {
            // dst where dst < src (> for max), else src (NaNs, zeros).
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.simd(if double { 0x49 } else { 0x43 } + (opcode == 0x5F) as u32);
            w.simd(0x52);
        },
        _ => {
            w.get_local_v128(dst);
            w.get_local_v128(src);
            w.simd(
                base + match opcode {
                    0x58 => 0,
                    0x5C => 1,
                    0x59 => 2,
                    _ => 3,
                },
            );
        },
    }
}

/// CMPPS/CMPPD/CMPSS/CMPSD's relation of imm8[2:0] (`predicate`) for ordered
/// operands (`dst`, `src`): EQ, LT, LE, UNORD (false), NEQ, NLT (ge), NLE
/// (gt), ORD (true); push the mask
pub fn compare_relation(
    w: &mut WasmBuilder,
    double: bool,
    predicate: u8,
    dst: &WasmLocalV128,
    src: &WasmLocalV128,
) {
    match predicate & 7 {
        3 => w.simd_zero(),
        7 => leaves::splat_i32(w, -1),
        relation => {
            w.get_local_v128(dst);
            w.get_local_v128(src);
            // (f32x4/f64x2: eq ne lt gt le ge)
            let offset = [0, 2, 4, 0, 1, 5, 3][relation as usize];
            w.simd(if double { 0x47 } else { 0x41 } + offset);
        },
    }
}

/// Call runtime::tier0::ir_t0_sse_fp, the exact path of a refused
/// instruction: (`destination`, `source`) into its operand block at
/// `operands` (Tier-0's Page::env.sse_fp_operands), the form `key` (a catalogue key:
/// a VEX form's legacy one) with `imm8`. Push its i32, nonzero if the
/// instruction faults; the result is sse_fp_result's.
pub fn sse_fp_call(
    w: &mut WasmBuilder,
    operands: u32,
    key: u32,
    imm8: u32,
    destination: &WasmLocalV128,
    source: &WasmLocalV128,
) {
    for (k, value) in [destination, source].into_iter().enumerate() {
        w.const_i32((operands + 16 * k as u32) as i32);
        w.get_local_v128(value);
        w.simd_memory(0x0B, 4); // v128.store
    }
    w.const_i32(key as i32);
    w.const_i32(imm8 as i32);
    w.call_signature(
        "x64_sse_fp",
        Signature::new(&[WasmType::I32, WasmType::I32], &[WasmType::I32]),
    );
}
/// Push the result of sse_fp_call
pub fn sse_fp_result(w: &mut WasmBuilder, operands: u32) {
    w.const_i32(operands as i32);
    w.simd_memory(0x00, 4); // v128.load
}

/// The register-fact bit of a lane format: the low lane or all lanes,
/// single or double precision (all lanes clean implies the low lane)
pub fn clean_bits(double: bool, scalar: bool) -> u8 {
    match (double, scalar) {
        (false, true) => CLEAN_SS,
        (false, false) => CLEAN_PS | CLEAN_SS,
        (true, true) => CLEAN_SD,
        (true, false) => CLEAN_PD | CLEAN_SD,
    }
}
/// Whether XMM `first` and `source` (None: memory) are known to hold `lanes`
/// clean (the register facts): native_fp's `known` operands
pub fn known_clean(clean: &[u8], lanes: u8, first: u8, source: Option<u8>) -> [bool; 2] {
    let holds = |r: u8| clean[r as usize] & lanes == lanes;
    [holds(first), source.is_some_and(holds)]
}
/// Whether an SSE arithmetic form (Simd::Float, not RSQRT or RCP) leaves
/// facts that hold only for admitted operands (float_facts): a clean result
/// (all but ADD and SUB), or a source register found clean. Its refused
/// operands then retry, as the exact path would not make the facts true.
pub fn float_claims(opcode: u8, source: Option<u8>, known: [bool; 2]) -> bool {
    !matches!(opcode, 0x58 | 0x5C) || source.is_some() && !known[1]
}
/// The register facts after an admitted SSE arithmetic form (Simd::Float) wrote
/// XMM `reg`, of operands that passed native_fp::arithmetic_refused: a source
/// register (None: memory) is clean, and so is the result of all but ADD and
/// SUB, whose clean operands can cancel to a denormal; a scalar result keeps
/// the other lanes of the first source (its facts `before` the write).
/// RSQRT and RCP check only their operand and leave nothing.
pub fn float_facts(
    clean: &mut [u8],
    opcode: u8,
    double: bool,
    scalar: bool,
    reg: u8,
    source: Option<u8>,
    before: u8,
) {
    if matches!(opcode, 0x52 | 0x53) {
        return;
    }
    // (see native_fp::arithmetic_refused)
    let lanes = clean_bits(double, scalar);
    if let Some(source) = source.filter(|&r| r != reg) {
        clean[source as usize] |= lanes;
    }
    if !matches!(opcode, 0x58 | 0x5C) {
        // a scalar result keeps the destination's other lanes
        clean[reg as usize] = lanes | if scalar { before & clean_bits(double, false) } else { 0 };
    }
}
/// The register facts after a conversion of one Wasm operation
/// (ops::convert, `opcode`) wrote XMM `reg`: an admitted result is neither
/// NaN nor denormal (integers convert to normals or zeros), a scalar one
/// keeps the first source's other lanes (its facts `before` the write), and
/// the source register of CVTPS2PD and CVTSS2SD passed operands_refused
pub fn convert_facts(
    clean: &mut [u8],
    opcode: u32,
    scalar: bool,
    reg: u8,
    source: Option<u8>,
    before: u8,
) {
    let double = matches!(opcode, 0x5F | 0xFE);
    let lanes = clean_bits(double, scalar);
    clean[reg as usize] = lanes | if scalar { before & clean_bits(double, false) } else { 0 };
    if let (0x5F, Some(source)) = (opcode, source.filter(|&r| r != reg)) {
        clean[source as usize] |= CLEAN_SS;
    }
}
                                                                  source/v64/src/rust/x86tpl/x87.rs                                                                   0000644 0000000 0000000 00000046225 00000000000 013622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Inlined fast-math x87 against the shared f64 shadow cache (moved from the
//! region backend in docs/jit-unification-plan.md P2.2; the x64 page tier's
//! templates use it since M11 deleted the region backend).
//!
//! Semantics match `cpu::fpu`'s cached paths: operands are read only from
//! full, VALID cache slots, results are written as VALID|DIRTY f64 values
//! (F80 materializes lazily), and TOP/tags/status change as the interpreter's
//! helpers change them. Every check precedes the first CPU write; any failed
//! check runs the canonical helper (`x64_x87`) instead, from unchanged state.
use crate::cpu::{fpu, global_pointers as gp};
use crate::wasmgen::wasm_builder::{Label, WasmBuilder, WasmLocal, WasmLocalF64};
use crate::x86tpl::x87_forms::{Arithmetic, Native, Operand, Source, Stored};

const C1: i32 = 0x200;
const CONDITION_CODES: i32 = 0x4700;

/// Mutable view of the stack registers while one instruction is inlined.
struct Stack {
    top: WasmLocal,
    tags: WasmLocal,
    /// VALID & !tags at entry: slots that hold an exact cached f64.
    ready: WasmLocal,
    written: Vec<(WasmLocal, WasmLocalF64)>,
    tags_changed: bool,
    top_changed: bool,
    /// top/tags are these caller-owned locals; VALID/DIRTY live in them too.
    cache: Option<X87Cache>,
}

/// Operand words of a natively inlined x87 form: the loaded memory operand
/// (words 0 and 1) and the value to store (outputs 0 and 1).
pub trait X87Words {
    fn w(&mut self) -> &mut WasmBuilder;
    /// Push input word `k`.
    fn input(&mut self, k: usize);
    /// Pop into output word `k`.
    fn output(&mut self, k: usize);
    /// Caller-owned locals holding the CPU's x87 bookkeeping across forms,
    /// or None: the form loads and stores it itself.
    fn cache(&mut self) -> Option<X87Cache> { None }
}
/// TOP, tags (fpu_stack_empty) and the shadow cache VALID/DIRTY masks in
/// locals (Tier-0 keeps them across a run of x87 forms). The caller writes
/// them back before anything else reads the CPU state.
pub struct X87Cache {
    pub top: WasmLocal,
    pub tags: WasmLocal,
    pub valid: WasmLocal,
    pub dirty: WasmLocal,
}
impl X87Cache {
    pub fn unsafe_clone(&self) -> Self {
        Self {
            top: self.top.unsafe_clone(),
            tags: self.tags.unsafe_clone(),
            valid: self.valid.unsafe_clone(),
            dirty: self.dirty.unsafe_clone(),
        }
    }
}

pub fn x87_native<T: X87Words>(t: &mut T, native: Native, slow: Label) {
    let [_, valid_address, _] = fpu::x87_cache_addresses();
    let cache = t.cache();
    let (top, tags) = match &cache {
        Some(c) => (c.top.unsafe_clone(), c.tags.unsafe_clone()),
        None => {
            t.w().load_fixed_u8(gp::fpu_stack_ptr as u32);
            let top = t.w().set_new_local();
            t.w().load_fixed_u8(gp::fpu_stack_empty as u32);
            (top, t.w().set_new_local())
        },
    };
    match &cache {
        Some(c) => t.w().get_local(&c.valid),
        None => t.w().load_fixed_i32(valid_address),
    }
    t.w().get_local(&tags);
    t.w().const_i32(-1);
    t.w().xor_i32();
    t.w().and_i32();
    let ready = t.w().set_new_local();
    let mut s = Stack {
        top,
        tags,
        ready,
        written: vec![],
        tags_changed: false,
        top_changed: false,
        cache,
    };
    // Phase 1: checks and results in locals. Phase 2 (commit) writes CPU state.
    let mut status: Option<WasmLocal> = None;
    let mut pops = 0;
    let mut clear_c1 = false;
    match native {
        Native::Push(source) => {
            let value = x87_source(t, &s, source, slow);
            let slot = x87_slot(t, &s, 7);
            // The destination must be empty: overflow sets flags in F80.
            t.w().get_local(&s.tags);
            t.w().get_local(&slot);
            t.w().shr_u_i32();
            t.w().const_i32(1);
            t.w().and_i32();
            t.w().eqz_i32();
            t.w().hint(false);
            t.w().br_if(slow);
            t.w().get_local(&slot);
            t.w().set_local(&s.top);
            s.top_changed = true;
            x87_clear_tag(t, &mut s, &slot);
            s.written.push((slot, value));
            clear_c1 = true;
        },
        Native::Arithmetic {
            op,
            source,
            target,
            pops: n,
        } => {
            let x = x87_read(t, &s, 0, slow);
            let y = x87_source(t, &s, source, slow);
            let (a, b) = match op {
                Arithmetic::SubR | Arithmetic::DivR => (&y, &x),
                _ => (&x, &y),
            };
            t.w().get_local_f64(a);
            t.w().get_local_f64(b);
            t.w().arithmetic_f64(match op {
                Arithmetic::Add => 0,
                Arithmetic::Sub | Arithmetic::SubR => 1,
                Arithmetic::Mul => 2,
                Arithmetic::Div | Arithmetic::DivR => 3,
            });
            let result = t.w().set_new_local_f64();
            t.w().free_local_f64(x);
            t.w().free_local_f64(y);
            let slot = x87_slot(t, &s, target);
            s.written.push((slot, result));
            pops = n;
        },
        Native::Compare { source, pops: n } => {
            let x = x87_read(t, &s, 0, slow);
            let y = x87_source(t, &s, source, slow);
            // Unordered compares raise #IA in F80; leave NaNs to it.
            for v in [&x, &y] {
                t.w().get_local_f64(v);
                t.w().get_local_f64(v);
                t.w().ne_f64();
                t.w().hint(false);
                t.w().br_if(slow);
            }
            t.w().load_fixed_u16(gp::fpu_status_word as u32);
            t.w().const_i32(!CONDITION_CODES);
            t.w().and_i32();
            t.w().get_local_f64(&x);
            t.w().get_local_f64(&y);
            t.w().compare_f64(1); // C0: x < y
            t.w().const_i32(8);
            t.w().shl_i32();
            t.w().or_i32();
            t.w().get_local_f64(&x);
            t.w().get_local_f64(&y);
            t.w().compare_f64(2); // C3: x == y
            t.w().const_i32(14);
            t.w().shl_i32();
            t.w().or_i32();
            status = Some(t.w().set_new_local());
            t.w().free_local_f64(x);
            t.w().free_local_f64(y);
            pops = n;
        },
        Native::Exchange(r) => {
            let a = x87_read(t, &s, 0, slow);
            let b = x87_read(t, &s, r, slow);
            let slot = x87_slot(t, &s, 0);
            s.written.push((slot, b));
            let slot = x87_slot(t, &s, r);
            s.written.push((slot, a));
        },
        Native::Copy { r, pops: n } => {
            let value = x87_read(t, &s, 0, slow);
            let slot = x87_slot(t, &s, r);
            x87_clear_tag(t, &mut s, &slot);
            s.written.push((slot, value));
            pops = n;
        },
        Native::Unary { negate } => {
            let value = x87_read(t, &s, 0, slow);
            t.w().get_local_f64(&value);
            t.w().unary_f64(negate);
            t.w().set_local_f64(&value);
            let slot = x87_slot(t, &s, 0);
            s.written.push((slot, value));
        },
        Native::Free { r, pops: n } => {
            let slot = x87_slot(t, &s, r);
            t.w().get_local(&s.tags);
            t.w().const_i32(1);
            t.w().get_local(&slot);
            t.w().shl_i32();
            t.w().or_i32();
            t.w().set_local(&s.tags);
            s.tags_changed = true;
            t.w().free_local(slot);
            pops = n;
        },
        Native::Store { to, pops: n } => {
            let value = x87_read(t, &s, 0, slow);
            x87_store(t, to, &value, slow);
            t.w().free_local_f64(value);
            pops = n;
        },
        Native::StoreControl => {
            t.w().load_fixed_u16(gp::fpu_control_word as u32);
            t.output(0);
            t.w().const_i32(0);
            t.output(1);
        },
        Native::StoreStatus => {
            t.w().load_fixed_u16(gp::fpu_status_word as u32);
            t.w().const_i32(!(7 << 11));
            t.w().and_i32();
            t.w().get_local(&s.top);
            t.w().const_i32(11);
            t.w().shl_i32();
            t.w().or_i32();
            t.output(0);
            t.w().const_i32(0);
            t.output(1);
        },
    }
    for _ in 0..pops {
        // fpu_pop: tag the old TOP empty, then TOP += 1.
        t.w().get_local(&s.tags);
        t.w().const_i32(1);
        t.w().get_local(&s.top);
        t.w().shl_i32();
        t.w().or_i32();
        t.w().set_local(&s.tags);
        t.w().get_local(&s.top);
        t.w().const_i32(1);
        t.w().add_i32();
        t.w().const_i32(7);
        t.w().and_i32();
        t.w().set_local(&s.top);
        s.tags_changed = true;
        s.top_changed = true;
    }
    x87_commit(t, s, status, clear_c1);
}

/// ST(r)'s physical slot: (TOP + r) & 7.
fn x87_slot<T: X87Words>(t: &mut T, s: &Stack, r: u8) -> WasmLocal {
    t.w().get_local(&s.top);
    t.w().const_i32(r as i32);
    t.w().add_i32();
    t.w().const_i32(7);
    t.w().and_i32();
    t.w().set_new_local()
}

/// ST(r) from a full, exactly cached slot; anything else takes `slow`.
fn x87_read<T: X87Words>(t: &mut T, s: &Stack, r: u8, slow: Label) -> WasmLocalF64 {
    let [values, _, _] = fpu::x87_cache_addresses();
    let slot = x87_slot(t, s, r);
    t.w().get_local(&s.ready);
    t.w().get_local(&slot);
    t.w().shr_u_i32();
    t.w().const_i32(1);
    t.w().and_i32();
    t.w().eqz_i32();
    t.w().hint(false);
    t.w().br_if(slow);
    t.w().get_local(&slot);
    t.w().const_i32(3);
    t.w().shl_i32();
    t.w().load_aligned_f64(values);
    t.w().free_local(slot);
    t.w().set_new_local_f64()
}

fn x87_clear_tag<T: X87Words>(t: &mut T, s: &mut Stack, slot: &WasmLocal) {
    t.w().get_local(&s.tags);
    t.w().const_i32(1);
    t.w().get_local(slot);
    t.w().shl_i32();
    t.w().const_i32(-1);
    t.w().xor_i32();
    t.w().and_i32();
    t.w().set_local(&s.tags);
    s.tags_changed = true;
}

/// A memory operand, register or constant as an f64. NaN memory operands
/// take `slow` (the F80 conversion may quiet them and raise #IA).
fn x87_source<T: X87Words>(t: &mut T, s: &Stack, source: Source, slow: Label) -> WasmLocalF64 {
    match source {
        Source::Register(r) => return x87_read(t, s, r, slow),
        Source::Constant(one) => {
            t.w().const_f64(if one { 1.0 } else { 0.0 });
            return t.w().set_new_local_f64();
        },
        Source::Memory(operand) => match operand {
            Operand::F32 => {
                t.input(0);
                t.w().reinterpret_i32_as_f32();
                t.w().promote_f32_to_f64();
            },
            Operand::F64 | Operand::I64 => {
                t.input(1);
                t.w().extend_unsigned_i32_to_i64();
                t.w().const_i64(32);
                t.w().shl_i64();
                t.input(0);
                t.w().extend_unsigned_i32_to_i64();
                t.w().or_i64();
                if operand == Operand::F64 {
                    t.w().reinterpret_i64_as_f64();
                }
                else {
                    // Only |v| <= 2^53 converts exactly to binary64.
                    let integer = t.w().set_new_local_i64();
                    t.w().get_local_i64(&integer);
                    t.w().const_i64(1 << 53);
                    t.w().add_i64();
                    t.w().const_i64(1 << 54);
                    t.w().gtu_i64();
                    t.w().hint(false);
                    t.w().br_if(slow);
                    t.w().get_local_i64(&integer);
                    t.w().convert_i64_to_f64();
                    t.w().free_local_i64(integer);
                }
            },
            Operand::I32 => {
                t.input(0);
                t.w().convert_i32_to_f64();
            },
            Operand::I16 => {
                t.input(0);
                t.w().const_i32(16);
                t.w().shl_i32();
                t.w().const_i32(16);
                t.w().shr_s_i32();
                t.w().convert_i32_to_f64();
            },
        },
    }
    let value = t.w().set_new_local_f64();
    if matches!(source, Source::Memory(Operand::F32 | Operand::F64)) {
        t.w().get_local_f64(&value);
        t.w().get_local_f64(&value);
        t.w().ne_f64();
        t.w().hint(false);
        t.w().br_if(slow);
    }
    value
}

/// FST(P) m32/m64 and FIST(P)/FISTTP bits. Results needing F80 rounding
/// flags (tiny f32, NaN, integer overflow) or directed f32 rounding take `slow`.
fn x87_store<T: X87Words>(t: &mut T, to: Stored, value: &WasmLocalF64, slow: Label) {
    match to {
        Stored::F64 => {
            t.w().get_local_f64(value);
            t.w().reinterpret_f64_as_i64();
            x87_set_wide(t);
        },
        Stored::F32 => {
            t.w().load_fixed_u16(gp::fpu_control_word as u32);
            t.w().const_i32(0xC00);
            t.w().and_i32();
            t.w().hint(false);
            t.w().br_if(slow);
            t.w().get_local_f64(value);
            t.w().demote_f64_to_f32();
            t.w().reinterpret_f32_as_i32();
            let bits = t.w().set_new_local();
            // Accept zero or a strictly normal/infinite result: no underflow.
            t.w().get_local(&bits);
            t.w().const_i32(0x7FFFFFFF);
            t.w().and_i32();
            t.w().const_i32(0x00800000);
            t.w().gtu_i32();
            t.w().get_local_f64(value);
            t.w().const_f64(0.0);
            t.w().compare_f64(2);
            t.w().or_i32();
            t.w().get_local(&bits);
            t.w().const_i32(0x7FFFFFFF);
            t.w().and_i32();
            t.w().const_i32(0x7F800000);
            t.w().leu_i32();
            t.w().and_i32();
            t.w().eqz_i32();
            t.w().hint(false);
            t.w().br_if(slow);
            t.w().get_local(&bits);
            t.output(0);
            t.w().const_i32(0);
            t.output(1);
            t.w().free_local(bits);
        },
        Stored::Integer { bytes, truncate } => {
            if truncate {
                t.w().get_local_f64(value);
                t.w().round_f64(3);
            }
            else {
                // RC 0..3: nearest, down, up, toward zero.
                t.w().load_fixed_u16(gp::fpu_control_word as u32);
                t.w().const_i32(10);
                t.w().shr_u_i32();
                t.w().const_i32(3);
                t.w().and_i32();
                let rc = t.w().set_new_local();
                t.w().get_local_f64(value);
                t.w().round_f64(0);
                let rounded = t.w().set_new_local_f64();
                for mode in 1..4 {
                    // select(a, b, c) = c ? a : b
                    t.w().get_local_f64(value);
                    t.w().round_f64(mode);
                    t.w().get_local_f64(&rounded);
                    t.w().get_local(&rc);
                    t.w().const_i32(mode as i32);
                    t.w().eq_i32();
                    t.w().select();
                    t.w().set_local_f64(&rounded);
                }
                t.w().get_local_f64(&rounded);
                t.w().free_local_f64(rounded);
                t.w().free_local(rc);
            }
            let rounded = t.w().set_new_local_f64();
            // In range after rounding; NaN fails both comparisons.
            let (low, high, below) = match bytes {
                2 => (-32768.0, 32767.0, false),
                4 => (-2147483648.0, 2147483647.0, false),
                _ => (-9223372036854775808.0, 9223372036854775808.0, true),
            };
            t.w().get_local_f64(&rounded);
            t.w().const_f64(low);
            t.w().ge_f64();
            t.w().get_local_f64(&rounded);
            t.w().const_f64(high);
            if below {
                t.w().compare_f64(1);
            }
            else {
                t.w().le_f64();
            }
            t.w().and_i32();
            t.w().eqz_i32();
            t.w().hint(false);
            t.w().br_if(slow);
            t.w().get_local_f64(&rounded);
            if bytes == 8 {
                t.w().trunc_f64_to_i64();
                x87_set_wide(t);
            }
            else {
                t.w().trunc_f64_to_i32();
                if bytes == 2 {
                    t.w().const_i32(0xFFFF);
                    t.w().and_i32();
                }
                t.output(0);
                t.w().const_i32(0);
                t.output(1);
            }
            t.w().free_local_f64(rounded);
        },
    }
}

fn x87_set_wide<T: X87Words>(t: &mut T) {
    let wide = t.w().set_new_local_i64();
    t.w().get_local_i64(&wide);
    t.w().wrap_i64_to_i32();
    t.output(0);
    t.w().get_local_i64(&wide);
    t.w().const_i64(32);
    t.w().shr_u_i64();
    t.w().wrap_i64_to_i32();
    t.output(1);
    t.w().free_local_i64(wide);
}

fn x87_commit<T: X87Words>(t: &mut T, s: Stack, status: Option<WasmLocal>, clear_c1: bool) {
    let [values, valid, dirty] = fpu::x87_cache_addresses();
    if !s.written.is_empty() {
        let mut mask: Option<WasmLocal> = None;
        for (slot, value) in &s.written {
            t.w().get_local(slot);
            t.w().const_i32(3);
            t.w().shl_i32();
            t.w().get_local_f64(value);
            t.w().store_aligned_f64(values);
            t.w().const_i32(1);
            t.w().get_local(slot);
            t.w().shl_i32();
            if let Some(mask) = &mask {
                t.w().get_local(mask);
                t.w().or_i32();
                t.w().set_local(mask);
            }
            else {
                mask = Some(t.w().set_new_local());
            }
        }
        let mask = mask.unwrap();
        match &s.cache {
            Some(c) => {
                for local in [&c.valid, &c.dirty] {
                    t.w().get_local(local);
                    t.w().get_local(&mask);
                    t.w().or_i32();
                    t.w().set_local(local);
                }
            },
            None => {
                for address in [valid, dirty] {
                    t.w().const_i32(address as i32);
                    t.w().load_fixed_i32(address);
                    t.w().get_local(&mask);
                    t.w().or_i32();
                    t.w().store_aligned_i32(0);
                }
            },
        }
        t.w().free_local(mask);
    }
    for (slot, value) in s.written {
        t.w().free_local(slot);
        t.w().free_local_f64(value);
    }
    if s.top_changed && s.cache.is_none() {
        t.w().const_i32(gp::fpu_stack_ptr as i32);
        t.w().get_local(&s.top);
        t.w().store_u8(0);
    }
    if s.tags_changed && s.cache.is_none() {
        t.w().const_i32(gp::fpu_stack_empty as i32);
        t.w().get_local(&s.tags);
        t.w().store_u8(0);
    }
    if let Some(status) = status {
        t.w().const_i32(gp::fpu_status_word as i32);
        t.w().get_local(&status);
        t.w().store_aligned_u16(0);
        t.w().free_local(status);
    }
    else if clear_c1 {
        t.w().const_i32(gp::fpu_status_word as i32);
        t.w().load_fixed_u16(gp::fpu_status_word as u32);
        t.w().const_i32(!C1);
        t.w().and_i32();
        t.w().store_aligned_u16(0);
    }
    if s.cache.is_none() {
        t.w().free_local(s.top);
        t.w().free_local(s.tags);
    }
    t.w().free_local(s.ready);
}
                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/rust/x86tpl/x87_forms.rs                                                             0000644 0000000 0000000 00000016763 00000000000 015034  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The x87 forms the page tier inlines or hands to its helper (x86tpl::x87
//! and x87run; x64::helpers::x64_x87): which register forms are valid, how
//! each form moves its memory operand, and the f64 forms inlined against the
//! shadow cache. (ir::x87 until docs/jit-unification-plan.md M11 deleted
//! the region tiers, which split continuing x87 instructions the same way.)

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Io {
    /// Consumes the loaded operand as (low, high) 32-bit words.
    Load { bytes: u8 },
    /// Produces the operand to store as (low, high) 32-bit words.
    Store { bytes: u8 },
    /// Register form: stack/status only.
    Stack,
}

/// The register encoding is architecturally defined (no nested #UD).
pub fn valid_register(opcode: u8, group: u8, r: u8) -> bool {
    match opcode {
        0xD8 | 0xDC => true,
        0xD9 => match group {
            0 | 1 | 3 | 6 | 7 => true,
            2 => r == 0,
            4 => matches!(r, 0 | 1 | 4 | 5),
            5 => r <= 6,
            _ => false,
        },
        0xDA => match group {
            0..=3 => true,
            5 => r == 1,
            _ => false,
        },
        0xDB => match group {
            0..=3 | 5 | 6 => true,
            4 => r <= 4,
            _ => false,
        },
        0xDD => group <= 5,
        0xDE => group != 3 || r == 1,
        0xDF => match group {
            0..=3 | 5 | 6 => true,
            4 => r == 0,
            _ => false,
        },
        _ => false,
    }
}

/// FCMOVcc reads FLAGS; FCOMI/FUCOMI(P) write FLAGS; FNSTSW AX writes AX.
fn register_touches_cpu(opcode: u8, group: u8) -> bool {
    matches!(
        (opcode, group),
        (0xDA, 0..=3) | (0xDB, 0..=3 | 5 | 6) | (0xDF, 4..=6)
    )
}

/// Operand transfer of a continuing form, or None for forms that keep helpers.
pub fn io(opcode: u8, modrm: u8) -> Option<Io> {
    let group = modrm >> 3 & 7;
    if modrm >= 0xC0 {
        let r = modrm & 7;
        return (valid_register(opcode, group, r) && !register_touches_cpu(opcode, group))
            .then_some(Io::Stack);
    }
    Some(match (opcode, group) {
        (0xD8 | 0xDA, _) | (0xD9 | 0xDB, 0) => Io::Load { bytes: 4 },
        (0xDC, _) | (0xDD, 0) | (0xDF, 5) => Io::Load { bytes: 8 },
        (0xDE, _) | (0xDF, 0) | (0xD9, 5) => Io::Load { bytes: 2 },
        (0xD9, 2 | 3) | (0xDB, 1..=3) => Io::Store { bytes: 4 },
        (0xDD, 1..=3) | (0xDF, 7) => Io::Store { bytes: 8 },
        (0xDF, 1..=3) | (0xD9, 7) | (0xDD, 7) => Io::Store { bytes: 2 },
        _ => return None,
    })
}

/// Memory operand encodings of an inlined form.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operand {
    F32,
    F64,
    I16,
    I32,
    I64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Source {
    Memory(Operand),
    /// ST(r), relative to TOP before the instruction.
    Register(u8),
    /// FLD1/FLDZ.
    Constant(bool),
}
/// `x` is ST(0), `y` the source: Sub = x - y, SubR = y - x, likewise Div.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Arithmetic {
    Add,
    Mul,
    Sub,
    SubR,
    Div,
    DivR,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Stored {
    F32,
    F64,
    Integer { bytes: u8, truncate: bool },
}
/// Fast-math semantics that generated code may inline against the shared f64
/// shadow cache, falling back to the helper (`x64_x87`) whenever an operand is not an
/// exact cached value, a result needs F80 flags, or the stack would fault.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Native {
    Push(Source),
    /// ST(target) = op(ST(0), source), then `pops`.
    Arithmetic {
        op: Arithmetic,
        source: Source,
        target: u8,
        pops: u8,
    },
    /// C0/C3 from ST(0) ? source (C1/C2 cleared), then `pops`.
    Compare {
        source: Source,
        pops: u8,
    },
    Exchange(u8),
    /// FST(P) ST(r).
    Copy {
        r: u8,
        pops: u8,
    },
    Unary {
        negate: bool,
    },
    Free {
        r: u8,
        pops: u8,
    },
    Store {
        to: Stored,
        pops: u8,
    },
    StoreControl,
    StoreStatus,
}
fn arithmetic(group: u8) -> Option<Arithmetic> {
    Some(match group {
        0 => Arithmetic::Add,
        1 => Arithmetic::Mul,
        4 => Arithmetic::Sub,
        5 => Arithmetic::SubR,
        6 => Arithmetic::Div,
        7 => Arithmetic::DivR,
        _ => return None,
    })
}
pub fn native(opcode: u8, modrm: u8) -> Option<Native> {
    io(opcode, modrm)?;
    let group = modrm >> 3 & 7;
    let r = modrm & 7;
    if modrm < 0xC0 {
        let operand = |opcode| match opcode {
            0xD8 => Operand::F32,
            0xDA => Operand::I32,
            0xDC => Operand::F64,
            _ => Operand::I16,
        };
        return Some(match (opcode, group) {
            (0xD8 | 0xDA | 0xDC | 0xDE, 2 | 3) => Native::Compare {
                source: Source::Memory(operand(opcode)),
                pops: group - 2,
            },
            (0xD8 | 0xDA | 0xDC | 0xDE, _) => Native::Arithmetic {
                op: arithmetic(group)?,
                source: Source::Memory(operand(opcode)),
                target: 0,
                pops: 0,
            },
            (0xD9, 0) => Native::Push(Source::Memory(Operand::F32)),
            (0xDD, 0) => Native::Push(Source::Memory(Operand::F64)),
            (0xDB, 0) => Native::Push(Source::Memory(Operand::I32)),
            (0xDF, 0) => Native::Push(Source::Memory(Operand::I16)),
            (0xDF, 5) => Native::Push(Source::Memory(Operand::I64)),
            (0xD9, 2 | 3) => Native::Store {
                to: Stored::F32,
                pops: group - 2,
            },
            (0xDD, 2 | 3) => Native::Store {
                to: Stored::F64,
                pops: group - 2,
            },
            (0xDB | 0xDD | 0xDF, 1..=3) | (0xDF, 7) => Native::Store {
                to: Stored::Integer {
                    bytes: match (opcode, group) {
                        (0xDB, _) => 4,
                        (0xDD, _) | (_, 7) => 8,
                        _ => 2,
                    },
                    truncate: group == 1,
                },
                pops: (group != 2) as u8,
            },
            (0xD9, 7) => Native::StoreControl,
            (0xDD, 7) => Native::StoreStatus,
            _ => return None,
        });
    }
    let register = Source::Register(r);
    Some(match (opcode, group) {
        (0xD8 | 0xDC, 2 | 3) => Native::Compare {
            source: register,
            pops: group - 2,
        },
        (0xDE, 2) => Native::Compare {
            source: register,
            pops: 1,
        },
        (0xDE, 3) | (0xDA, 5) => Native::Compare {
            source: Source::Register(1),
            pops: 2,
        },
        (0xDD, 4 | 5) => Native::Compare {
            source: register,
            pops: group - 4,
        },
        (0xD8 | 0xDC | 0xDE, _) => Native::Arithmetic {
            op: arithmetic(group)?,
            source: register,
            target: if opcode == 0xD8 { 0 } else { r },
            pops: (opcode == 0xDE) as u8,
        },
        (0xD9, 0) => Native::Push(register),
        (0xD9 | 0xDD | 0xDF, 1) => Native::Exchange(r),
        (0xD9, 3) | (0xDD, 3) | (0xDF, 2 | 3) => Native::Copy { r, pops: 1 },
        (0xDD, 2) => Native::Copy { r, pops: 0 },
        (0xD9, 4) if r <= 1 => Native::Unary { negate: r == 0 },
        (0xD9, 5) if r == 0 || r == 6 => Native::Push(Source::Constant(r == 0)),
        (0xDD, 0) => Native::Free { r, pops: 0 },
        (0xDF, 0) => Native::Free { r, pops: 1 },
        _ => return None,
    })
}
             source/v64/src/rust/x86tpl/x87run.rs                                                                0000644 0000000 0000000 00000025763 00000000000 014353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Runs of register-only x87 forms (FLD ST(i)/FLD1/FLDZ, arithmetic on
//! ST(i), FXCH, FST(P) ST(i), FCHS/FABS, FFREE) with their stack positions
//! known relative to the TOP at the run's start: one guard checks that every
//! slot read holds an exact cached f64 and every slot pushed is empty, then
//! the run computes in f64 locals and commits once. The results are exactly
//! those of the per-form native path (x86tpl::x87), which runs the
//! instructions one by one when the guard fails. Tier-0 and the page tier's
//! compatibility mode (docs/jit-unification-plan.md P7.2a) emit them; the
//! caller checks CR0 (#NM) and gp::x87_native_policy first.
use super::x87::X87Cache;
use crate::cpu::{fpu, global_pointers as gp};
use crate::wasmgen::wasm_builder::{Label, WasmBuilder, WasmLocalF64};
use crate::x86tpl::x87_forms::{Arithmetic, Io, Native, Source};

const C1: i32 = 0x200;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Tag {
    Unknown,
    Full,
    Empty,
}
#[derive(Clone, Copy)]
enum Value {
    /// Loaded at the run's start from the slot `k` (relative to entry TOP).
    Entry(u8),
    Constant(bool),
    /// The result of step `n`.
    Step(usize),
}
#[derive(Clone, Copy)]
enum Step {
    Arithmetic(Arithmetic, Value, Value),
    Unary(bool, Value),
}

/// Compile-time stack of one run, positions relative to the entry TOP.
#[derive(Clone)]
pub struct X87Run {
    /// Current TOP relative to the entry TOP.
    top: u8,
    tags: [Tag; 8],
    values: [Option<Value>; 8],
    steps: Vec<Step>,
    need_full: u8,
    need_empty: u8,
    written: u8,
    pushed: bool,
    /// The forms in the run.
    pub length: usize,
}
impl X87Run {
    pub fn new() -> Self {
        X87Run {
            top: 0,
            tags: [Tag::Unknown; 8],
            values: [None; 8],
            steps: vec![],
            need_full: 0,
            need_empty: 0,
            written: 0,
            pushed: false,
            length: 0,
        }
    }
    fn rel(&self, r: u8) -> usize { (self.top + r) as usize & 7 }
    fn read(&mut self, r: u8) -> Option<Value> {
        let k = self.rel(r);
        match self.tags[k] {
            Tag::Empty => None,
            Tag::Full => Some(self.values[k].unwrap_or(Value::Entry(k as u8))),
            Tag::Unknown => {
                self.need_full |= 1 << k;
                self.tags[k] = Tag::Full;
                self.values[k] = Some(Value::Entry(k as u8));
                self.values[k]
            },
        }
    }
    fn write(&mut self, r: u8, value: Value) {
        let k = self.rel(r);
        self.values[k] = Some(value);
        self.written |= 1 << k;
    }
    fn pop(&mut self) {
        let k = self.rel(0);
        self.tags[k] = Tag::Empty;
        self.top = (self.top + 1) & 7;
    }
    /// Add the form `opcode` (0xD8..0xDF) `modrm`; false (run unchanged) if
    /// it cannot join the run: only register forms (crate::x86tpl::x87_forms::io's
    /// Stack) with a native form can.
    pub fn append(&mut self, opcode: u8, modrm: u8) -> bool {
        if !(0xD8..=0xDF).contains(&opcode)
            || crate::x86tpl::x87_forms::io(opcode, modrm) != Some(Io::Stack)
        {
            return false;
        }
        let Some(native) = crate::x86tpl::x87_forms::native(opcode, modrm)
        else {
            return false;
        };
        let mut next = self.clone();
        let ok = (|| {
            match native {
                Native::Push(source) => {
                    let value = match source {
                        Source::Register(r) => next.read(r)?,
                        Source::Constant(one) => Value::Constant(one),
                        Source::Memory(_) => return None,
                    };
                    let k = next.rel(7);
                    match next.tags[k] {
                        Tag::Full => return None,
                        Tag::Unknown => next.need_empty |= 1 << k,
                        Tag::Empty => {},
                    }
                    next.tags[k] = Tag::Full;
                    next.top = k as u8;
                    next.write(0, value);
                    next.pushed = true;
                },
                Native::Arithmetic {
                    op,
                    source: Source::Register(r),
                    target,
                    pops,
                } => {
                    let x = next.read(0)?;
                    let y = next.read(r)?;
                    next.steps.push(Step::Arithmetic(op, x, y));
                    next.write(target, Value::Step(next.steps.len() - 1));
                    for _ in 0..pops {
                        next.pop();
                    }
                },
                Native::Exchange(r) => {
                    let a = next.read(0)?;
                    let b = next.read(r)?;
                    next.write(0, b);
                    next.write(r, a);
                },
                Native::Copy { r, pops } => {
                    let value = next.read(0)?;
                    let k = next.rel(r);
                    next.tags[k] = Tag::Full;
                    next.write(r, value);
                    for _ in 0..pops {
                        next.pop();
                    }
                },
                Native::Unary { negate } => {
                    let value = next.read(0)?;
                    next.steps.push(Step::Unary(negate, value));
                    next.write(0, Value::Step(next.steps.len() - 1));
                },
                Native::Free { r, pops } => {
                    let k = next.rel(r);
                    next.tags[k] = Tag::Empty;
                    for _ in 0..pops {
                        next.pop();
                    }
                },
                _ => return None,
            }
            Some(())
        })();
        if ok.is_none() {
            return false;
        }
        next.length += 1;
        *self = next;
        true
    }
}

/// Emit the run's fast path: to `slow` unless the guard holds, else the
/// run's effect on the open x87 cache `c` and the f64 shadow values.
pub fn x87_run(w: &mut WasmBuilder, c: &X87Cache, plan: &X87Run, slow: Label) {
    let [values, _, _] = fpu::x87_cache_addresses();
    // Masks relative to TOP: rotate right by TOP (8 bits).
    let rotate = |w: &mut WasmBuilder, mask: &dyn Fn(&mut WasmBuilder)| {
        mask(w);
        w.get_local(&c.top);
        w.shr_u_i32();
        mask(w);
        w.const_i32(8);
        w.get_local(&c.top);
        w.sub_i32();
        w.shl_i32();
        w.or_i32();
        w.const_i32(255);
        w.and_i32();
    };
    if plan.need_full != 0 {
        // Every slot read: nonempty and an exact cached value.
        rotate(w, &|w: &mut WasmBuilder| {
            w.get_local(&c.valid);
            w.const_i32(-1);
            w.xor_i32();
            w.get_local(&c.tags);
            w.or_i32();
            w.const_i32(255);
            w.and_i32();
        });
        w.const_i32(plan.need_full as i32);
        w.and_i32();
        w.hint(false);
        w.br_if(slow);
    }
    if plan.need_empty != 0 {
        rotate(w, &|w: &mut WasmBuilder| w.get_local(&c.tags));
        w.const_i32(plan.need_empty as i32);
        w.and_i32();
        w.const_i32(plan.need_empty as i32);
        w.ne_i32();
        w.hint(false);
        w.br_if(slow);
    }
    let slot = |w: &mut WasmBuilder, k: u8| {
        w.get_local(&c.top);
        w.const_i32(k as i32);
        w.add_i32();
        w.const_i32(7);
        w.and_i32();
    };
    let mut entry: [Option<WasmLocalF64>; 8] = Default::default();
    for k in 0..8u8 {
        if plan.need_full & 1 << k != 0 {
            slot(w, k);
            w.const_i32(3);
            w.shl_i32();
            w.load_aligned_f64(values);
            entry[k as usize] = Some(w.set_new_local_f64());
        }
    }
    let mut results: Vec<WasmLocalF64> = vec![];
    let push = |w: &mut WasmBuilder,
                v: Value,
                results: &[WasmLocalF64],
                entry: &[Option<WasmLocalF64>; 8]| match v {
        Value::Entry(k) => w.get_local_f64(entry[k as usize].as_ref().unwrap()),
        Value::Constant(one) => w.const_f64(if one { 1.0 } else { 0.0 }),
        Value::Step(n) => w.get_local_f64(&results[n]),
    };
    for step in &plan.steps {
        match *step {
            Step::Arithmetic(op, x, y) => {
                let (a, b) = match op {
                    Arithmetic::SubR | Arithmetic::DivR => (y, x),
                    _ => (x, y),
                };
                push(w, a, &results, &entry);
                push(w, b, &results, &entry);
                w.arithmetic_f64(match op {
                    Arithmetic::Add => 0,
                    Arithmetic::Sub | Arithmetic::SubR => 1,
                    Arithmetic::Mul => 2,
                    Arithmetic::Div | Arithmetic::DivR => 3,
                });
            },
            Step::Unary(negate, v) => {
                push(w, v, &results, &entry);
                w.unary_f64(negate);
            },
        }
        results.push(w.set_new_local_f64());
    }
    // Commit: values of written slots (VALID|DIRTY), tags, TOP, C1.
    for k in 0..8u8 {
        if plan.written & 1 << k == 0 {
            continue;
        }
        slot(w, k);
        w.const_i32(3);
        w.shl_i32();
        push(w, plan.values[k as usize].unwrap(), &results, &entry);
        w.store_aligned_f64(values);
    }
    let mut full = 0u8;
    let mut empty = 0u8;
    for k in 0..8 {
        match plan.tags[k] {
            // Pushed/copied slots were set full; read slots stay full.
            Tag::Full if plan.written & 1 << k != 0 || plan.need_empty & 1 << k != 0 => {
                full |= 1 << k
            },
            Tag::Empty => empty |= 1 << k,
            _ => {},
        }
    }
    // Rotate compile-time relative masks left by TOP into physical bits.
    let physical = |w: &mut WasmBuilder, mask: u8| {
        w.const_i32(mask as i32);
        w.get_local(&c.top);
        w.shl_i32();
        w.const_i32(mask as i32);
        w.const_i32(8);
        w.get_local(&c.top);
        w.sub_i32();
        w.shr_u_i32();
        w.or_i32();
        w.const_i32(255);
        w.and_i32();
    };
    if plan.written != 0 {
        for local in [&c.valid, &c.dirty] {
            w.get_local(local);
            physical(w, plan.written);
            w.or_i32();
            w.set_local(local);
        }
    }
    if full != 0 || empty != 0 {
        w.get_local(&c.tags);
        physical(w, empty);
        w.or_i32();
        physical(w, full);
        w.const_i32(-1);
        w.xor_i32();
        w.and_i32();
        w.set_local(&c.tags);
    }
    if plan.top != 0 {
        w.get_local(&c.top);
        w.const_i32(plan.top as i32);
        w.add_i32();
        w.const_i32(7);
        w.and_i32();
        w.set_local(&c.top);
    }
    if plan.pushed {
        w.const_i32(gp::fpu_status_word as i32);
        w.load_fixed_u16(gp::fpu_status_word as u32);
        w.const_i32(!C1);
        w.and_i32();
        w.store_aligned_u16(0);
    }
    for local in entry.into_iter().flatten().chain(results) {
        w.free_local_f64(local);
    }
}
             source/v64/src/rust/zstd.rs                                                                         0000644 0000000 0000000 00000005375 00000000000 013014  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use std::alloc;

extern "C" {
    fn ZSTD_createDStream() -> u32;
    fn ZSTD_freeDStream(ctx: u32) -> i32;
    fn ZSTD_decompressStream_simpleArgs(
        ctx: u32,
        dst: *mut u8,
        dstCapacity: u32,
        dstPos: *mut u32,
        src: *const u8,
        srcSize: u32,
        srcPos: *mut u32,
    ) -> i32;

    fn ZSTD_isError(err: i32) -> bool;
}

const MALLOC_ALIGN: usize = 16;

// malloc and free are needed by the zstd library
#[no_mangle]
pub unsafe fn v86_malloc(size: u32) -> u32 {
    let layout = alloc::Layout::from_size_align(size as usize + 4, MALLOC_ALIGN).unwrap();
    let addr = alloc::alloc(layout);
    *(addr as *mut u32) = size as u32;
    addr as u32 + 4
}
#[no_mangle]
pub unsafe fn v86_free(addr: u32) {
    let size = *((addr - 4) as *mut u32);
    let layout = alloc::Layout::from_size_align(size as usize + 4, MALLOC_ALIGN).unwrap();
    alloc::dealloc((addr - 4) as *mut u8, layout)
}

pub struct ZstdContext {
    ctx: u32,
    src: *mut u8,
    src_size: u32,
    src_pos: u32,
}

#[no_mangle]
pub unsafe fn zstd_create_ctx(src_size: u32) -> *mut ZstdContext {
    let src = alloc::alloc(alloc::Layout::from_size_align(src_size as usize, 1).unwrap());
    let ctx = ZSTD_createDStream();
    let result = alloc::alloc(alloc::Layout::new::<ZstdContext>()) as *mut ZstdContext;
    *result = ZstdContext {
        ctx,
        src,
        src_size,
        src_pos: 0,
    };
    result
}

#[no_mangle]
pub unsafe fn zstd_get_src_ptr(ctx: *mut ZstdContext) -> *mut u8 { (*ctx).src }

#[no_mangle]
pub unsafe fn zstd_free_ctx(ctx: *mut ZstdContext) {
    alloc::dealloc(
        (*ctx).src,
        alloc::Layout::from_size_align((*ctx).src_size as usize, 1).unwrap(),
    );
    ZSTD_freeDStream((*ctx).ctx);
    std::ptr::drop_in_place(ctx);
}

#[no_mangle]
pub unsafe fn zstd_read(ctx: *mut ZstdContext, length: u32) -> *mut u8 {
    let dst = alloc::alloc(alloc::Layout::from_size_align(length as usize, 1).unwrap());
    let mut dst_pos = 0;
    let result = ZSTD_decompressStream_simpleArgs(
        (*ctx).ctx,
        dst,
        length,
        &mut dst_pos,
        (*ctx).src,
        (*ctx).src_size,
        &mut (*ctx).src_pos,
    );
    if ZSTD_isError(result) {
        dbg_log!(
            "ZSTD_decompressStream_simpleArgs returned error: {}",
            result
        );
        dbg_assert!(false);
        zstd_read_free(dst, length);
        return std::ptr::null_mut::<u8>();
    }
    if dst_pos != length {
        dbg_assert!(false, "ZSTD: Partial read");
        zstd_read_free(dst, length);
        return std::ptr::null_mut::<u8>();
    }
    dst
}
#[no_mangle]
pub unsafe fn zstd_read_free(ptr: *mut u8, length: u32) {
    alloc::dealloc(
        ptr,
        alloc::Layout::from_size_align(length as usize, 1).unwrap(),
    );
}
                                                                                                                                                                                                                                                                   source/v64/src/smbios.js                                                                            0000644 0000000 0000000 00000021344 00000000000 012311  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SMBIOS for the UEFI firmware (docs/uefi.md): QEMU's fw_cfg files
// etc/smbios/smbios-tables (the structures, the last of type 127) and
// etc/smbios/smbios-anchor (an SMBIOS 2.8 entry point whose table length is
// the structures'), which OVMF validates (DetectSmbiosVersionLib) and installs
// (SmbiosPlatformDxe), adding its own type 0. SeaBIOS builds its own tables.
//
// The structures are those QEMU's machines have: system (1), chassis (3),
// processor (4), memory array (16), memory devices (17, one per 16 GiB),
// mapped address ranges (19), boot information (32).

import { dbg_assert } from "./log.js";

// For Types Only
import { Platform } from "./platform.js";

const SMBIOS_MAJOR = 2;
const SMBIOS_MINOR = 8;
/** The largest memory device a type 17 describes */
const DIMM_MAX = 16 * 2 ** 30;

/**
 * A structure: its formatted part (type, length and handle first) and its
 * strings, which string fields number from 1 (0: no string)
 * @param {number} type
 * @param {number} handle
 * @param {!Array<number>} formatted the bytes after the header
 * @param {!Array<string>} strings
 * @return {!Array<number>}
 */
function structure(type, handle, formatted, strings)
{
    const bytes = [type, 4 + formatted.length, handle & 0xFF, handle >> 8, ...formatted];
    for(const text of strings)
    {
        dbg_assert(text.length > 0 && /^[\x20-\x7E]*$/.test(text));
        for(let i = 0; i < text.length; i++) bytes.push(text.charCodeAt(i));
        bytes.push(0);
    }
    // (the string set ends with a second NUL; without strings, two)
    bytes.push(0);
    if(!strings.length) bytes.push(0);
    return bytes;
}

/** @param {number} value @param {number} bytes */
function le(value, bytes)
{
    const result = [];
    for(let i = 0; i < bytes; i++)
    {
        result.push(Number(BigInt(value) >> BigInt(8 * i) & 0xFFn));
    }
    return result;
}

/**
 * The two files
 * @param {Platform} platform
 * @param {{low_memory: number, high_memory: number, cpuid: function(number, number):!Array<number>}} machine
 *     RAM below 4 GiB and from 4 GiB on, in bytes; CPUID of the boot core (EAX, EBX, ECX, EDX)
 * @return {{tables: !Uint8Array, anchor: !Uint8Array}}
 */
export function build_smbios(platform, machine)
{
    const q35 = platform.machine === "q35";
    const total = machine.low_memory + machine.high_memory;
    const structures = [];

    // type 1: system; no serial number or UUID (all zero: not present)
    structures.push(structure(1, 0x0100, [
        1, 2, 3, 0,             // manufacturer, product, version, serial number
        ...new Array(16).fill(0), // UUID
        0x06,                   // wake-up type: power switch
        0, 0,                   // SKU number, family
    ], ["v86", q35 ? "v86 PC (Q35 + ICH9)" : "v86 PC (i440FX + PIIX)", "1.0"]));

    // type 3: chassis
    structures.push(structure(3, 0x0300, [
        1, 0x01, 0, 0, 0,       // manufacturer, type (other), version, serial number, asset tag
        0x03, 0x03, 0x03, 0x02, // boot-up, power supply and thermal state (safe), security (unknown)
        ...le(0, 4),            // OEM-defined
        0, 0, 0, 0,             // height, power cords, contained elements, their record length
        0,                      // SKU number
    ], ["v86"]));

    // type 4: the processor (one socket)
    const [signature, , , features] = machine.cpuid(1, 0);
    const vendor = machine.cpuid(0, 0);
    const vendor_name = String.fromCharCode(...[vendor[1], vendor[3], vendor[2]].flatMap(word => le(word, 4)));
    const long_mode = (machine.cpuid(0x80000000, 0)[0] >>> 0) >= 0x80000001 && (machine.cpuid(0x80000001, 0)[3] >>> 29 & 1) === 1;
    const cores = platform.topology.cores_per_socket;
    const threads = platform.topology.logical_processors;
    structures.push(structure(4, 0x0400, [
        1, 0x03, 0x01, 2,       // socket designation, type (central), family (other), manufacturer
        ...le(signature, 4), ...le(features, 4), // processor ID: CPUID 1's EAX and EDX
        3, 0,                   // version, voltage
        ...le(0, 2),            // external clock (unknown)
        ...le(2000, 2), ...le(2000, 2), // maximum and current speed in MHz
        0x41,                   // status: socket populated, enabled
        0x01,                   // upgrade: other
        ...le(0xFFFF, 2), ...le(0xFFFF, 2), ...le(0xFFFF, 2), // no L1, L2, L3 cache information
        0, 0, 0,                // serial number, asset tag, part number
        Math.min(cores, 0xFF), Math.min(cores, 0xFF), Math.min(threads, 0xFF),
        ...le(long_mode ? 0x0004 : 0x0002, 2), // characteristics: 64-bit capable, or unknown
        ...le(0x0001, 2),       // family 2: other
    ], ["CPU 0", vendor_name, "v86"]));

    // type 16: the memory array; type 17: its devices
    const dimms = Math.max(1, Math.ceil(total / DIMM_MAX));
    const total_kib = Math.ceil(total / 1024);
    structures.push(structure(16, 0x1000, [
        0x01, 0x03, 0x06,       // location (other), use (system memory), error correction (multi-bit ECC, as QEMU)
        ...le(total_kib < 0x80000000 ? total_kib : 0x80000000, 4), // maximum capacity in KiB, or see below
        ...le(0xFFFE, 2),       // no memory error information
        ...le(dimms, 2),
        ...le(total_kib < 0x80000000 ? 0 : total, 8), // extended maximum capacity in bytes
    ], []));
    for(let i = 0; i < dimms; i++)
    {
        // (in whole MiB: a 2048 MB x86_64 machine has 2 GiB less 128 KiB of heap RAM)
        const size_mib = Math.ceil(Math.min(DIMM_MAX, total - i * DIMM_MAX) / 2 ** 20);
        structures.push(structure(17, 0x1100 + i, [
            ...le(0x1000, 2),   // the memory array
            ...le(0xFFFE, 2),   // no memory error information
            ...le(64, 2), ...le(64, 2), // total and data width
            ...le(size_mib < 0x7FFF ? size_mib : 0x7FFF, 2), // size in MiB, or see the extended size
            0x09, 0,            // form factor (DIMM), device set
            1, 0,               // device locator, bank locator
            0x07,               // type: RAM
            ...le(0x0002, 2),   // type detail: other
            ...le(0, 2),        // speed (unknown)
            2, 0, 0, 0,         // manufacturer, serial number, asset tag, part number
            0,                  // attributes
            ...le(size_mib < 0x7FFF ? 0 : size_mib, 4), // extended size in MiB
            ...le(0, 2),        // configured speed (unknown)
            ...le(0, 2), ...le(0, 2), ...le(0, 2), // minimum, maximum, configured voltage (unknown)
        ], ["DIMM " + i, "v86"]));
    }

    // type 19: the address ranges of RAM
    const ranges = [[0, machine.low_memory]];
    if(machine.high_memory) ranges.push([2 ** 32, machine.high_memory]);
    ranges.forEach(([start, length], i) => {
        const end = start + length - 1;
        const fits = end / 1024 < 0xFFFFFFFF;
        structures.push(structure(19, 0x1300 + i, [
            ...le(fits ? start / 1024 : 0xFFFFFFFF, 4), // starting address in KiB, or see the extended one
            ...le(fits ? Math.floor(end / 1024) : 0xFFFFFFFF, 4), // ending address in KiB
            ...le(0x1000, 2),   // the memory array
            dimms,              // partition width
            ...le(fits ? 0 : start, 8), ...le(fits ? 0 : end, 8), // extended starting and ending address
        ], []));
    });

    // type 32: boot information: no errors
    structures.push(structure(32, 0x2000, [0, 0, 0, 0, 0, 0, 0], []));
    // type 127: the end
    structures.push(structure(127, 0x7F00, [], []));

    const tables = new Uint8Array(structures.flat());
    const largest = Math.max(...structures.map(s => s.length));

    const anchor = new Uint8Array(0x1F);
    anchor.set([0x5F, 0x53, 0x4D, 0x5F]);       // "_SM_"
    anchor[5] = 0x1F;
    anchor[6] = SMBIOS_MAJOR;
    anchor[7] = SMBIOS_MINOR;
    anchor.set(le(largest, 2), 8);
    anchor.set([0x5F, 0x44, 0x4D, 0x49, 0x5F], 0x10); // "_DMI_"
    anchor.set(le(tables.length, 2), 0x16);
    // (the table's address, at 0x18, is the firmware's to fill in)
    anchor.set(le(structures.length, 2), 0x1C);
    anchor[0x1E] = SMBIOS_MAJOR << 4 | SMBIOS_MINOR;
    anchor[0x15] = -anchor.subarray(0x10, 0x1F).reduce((a, b) => a + b, 0) & 0xFF;
    anchor[4] = -anchor.reduce((a, b) => a + b, 0) & 0xFF;
    dbg_assert(tables.length < 0x10000);

    return { tables, anchor };
}

/**
 * The fw_cfg file etc/e820: RAM below and above 4 GiB, as QEMU's (each entry
 * a 64-bit address and length and a 32-bit type, 1: RAM)
 * @param {number} low_memory
 * @param {number} high_memory
 * @return {!Uint8Array}
 */
export function build_e820(low_memory, high_memory)
{
    const entries = [[0, low_memory]];
    if(high_memory) entries.push([2 ** 32, high_memory]);
    return new Uint8Array(entries.flatMap(([address, length]) => [...le(address, 8), ...le(length, 8), ...le(1, 4)]));
}
                                                                                                                                                                                                                                                                                            source/v64/src/smbus.js                                                                             0000644 0000000 0000000 00000041326 00000000000 012150  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The SMBus host controller of the Q35 machine's ICH9 (00:1f.3,
// settings.smbus) and the devices on its bus: eight 256-byte SPD EEPROMs at
// 0x50-0x57, zeroed, as QEMU's Q35 has them.
//
// The host interface (ICH9 datasheet 316972, 19.2; QEMU hw/i2c/pm_smbus.c):
// quick, byte, byte data, word data and block commands, process calls, the
// 32-byte block buffer (AUX_CTL.E32B), byte-by-byte block transfers with
// BYTE_DONE_STS, I2C block reads; INTA when a command ends with INTREN set.
// Transfers complete at once. The I/O BAR (BAR4) is decoded by the device
// while HOSTC.HST_EN is set: SeaBIOS puts it at the PM base + 0x100, among
// the legacy ports.

import { LOG_ACPI } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";
import { QEMU_PCI_SUBSYSTEM } from "./platform.js";

// For Types Only
import { CPU } from "./cpu.js";

export const ICH9_SMBUS_PCI_ID = 0x1F << 3 | 3;
const IO_SIZE = 32;
const HOSTC = 0x40;
const HOSTC_HST_EN = 1 << 0;
const HOSTC_I2C_EN = 1 << 2;
const HOSTC_WRITABLE = 0x1F;

// Host registers
const HST_STS = 0x00;
const HST_CNT = 0x02;
const HST_CMD = 0x03;
const XMIT_SLVA = 0x04;
const HST_D0 = 0x05;
const HST_D1 = 0x06;
const HOST_BLOCK_DB = 0x07;
const PEC = 0x08;
const AUX_STS = 0x0C;
const AUX_CTL = 0x0D;
const SMBUS_PIN_CTL = 0x0F;

const STS_HOST_BUSY = 1 << 0;
const STS_INTR = 1 << 1;
const STS_DEV_ERR = 1 << 2;
const STS_BUS_ERR = 1 << 3;
const STS_FAILED = 1 << 4;
const STS_SMBALERT = 1 << 5;
const STS_INUSE = 1 << 6;
const STS_BYTE_DONE = 1 << 7;
/** The statuses that end a command (and interrupt with INTREN), and BYTE_DONE */
const STS_INTERRUPTS = STS_INTR | STS_DEV_ERR | STS_BUS_ERR | STS_FAILED | STS_BYTE_DONE;

const CNT_INTREN = 1 << 0;
const CNT_KILL = 1 << 1;
const CNT_LAST_BYTE = 1 << 5;
const CNT_START = 1 << 6;

const PROT_QUICK = 0;
const PROT_BYTE = 1;
const PROT_BYTE_DATA = 2;
const PROT_WORD_DATA = 3;
const PROT_PROCESS_CALL = 4;
const PROT_BLOCK = 5;
const PROT_I2C_READ = 6;
const PROT_BLOCK_PROCESS = 7;

const AUX_E32B = 1 << 1;
const BLOCK_MAX = 32;

const STATE_FORMAT = 1;

/**
 * A 256-byte EEPROM (as an SPD EEPROM, or QEMU's smbus_eeprom): a current
 * offset that receive byte reads advance; send byte sets it; byte and word
 * reads and writes at the command's offset
 * @constructor
 * @param {number} address
 */
function SMBusEEPROM(address)
{
    this.address = address;
    this.data = new Uint8Array(256);
    this.offset = 0;
}

SMBusEEPROM.prototype.receive_byte = function()
{
    const value = this.data[this.offset];
    this.offset = this.offset + 1 & 0xFF;
    return value;
};

/** @param {number} value */
SMBusEEPROM.prototype.send_byte = function(value)
{
    this.offset = value & 0xFF;
};

/**
 * @param {number} offset
 * @param {number} value
 */
SMBusEEPROM.prototype.write_byte = function(offset, value)
{
    this.data[offset & 0xFF] = value;
    this.offset = offset + 1 & 0xFF;
};

/**
 * @constructor
 * @param {CPU} cpu
 */
export function SMBus(cpu)
{
    /** @const @type {CPU} */
    this.cpu = cpu;
    this.name = "smbus";
    this.pci_id = ICH9_SMBUS_PCI_ID;

    const qemu = cpu.platform.qemu_compatible;
    const space = new Array(256).fill(0);
    // 00:1f.3 SMBus: Intel Corporation 82801I (ICH9 Family) SMBus Controller (rev 02)
    space.splice(0, 16, 0x86, 0x80, 0x30, 0x29, 0x00, 0x00, 0x80, 0x02, 0x02, 0x00, 0x05, 0x0C, 0x00, 0x00, 0x00, 0x00);
    space.splice(0x20, 4, 0x01, 0x00, 0x00, 0x00);  // SMB_BASE: I/O, not placed yet
    space.splice(0x2C, 4, ...qemu ? QEMU_PCI_SUBSYSTEM : [0x86, 0x80, 0x30, 0x29]);
    space[0x3D] = 1; // INTA (as QEMU's)
    this.pci_space = space;
    this.pci_bars = [undefined, undefined, undefined, undefined,
        { size: IO_SIZE, on_move: port => this.update_decode() }];
    this.on_command_change = () => this.update_decode();
    this.on_config_restore = () => this.update_decode();
    this.on_config_write = (offset, size) => {
        if(offset <= HOSTC && offset + size > HOSTC)
        {
            const bytes = this.cpu.devices.pci.space_bytes(this.pci_id);
            bytes[HOSTC] &= HOSTC_WRITABLE;
            this.update_decode();
        }
    };

    /** @type {!Array<SMBusEEPROM>} */
    this.devices = [];
    for(let address = 0x50; address < 0x58; address++)
    {
        this.devices.push(new SMBusEEPROM(address));
    }

    /** Where the registers are decoded, or -1 */
    this.io_base = -1;
    this.irq_level = false;
    this.block = new Uint8Array(BLOCK_MAX);
    this.reset();

    /** @const @type {!Int32Array} */
    this.pci_config = cpu.devices.pci.register_device(this);
    this.update_decode();
}

SMBus.prototype.reset = function()
{
    this.status = 0;
    this.control = 0;
    this.command = 0;
    this.address = 0;
    this.data0 = 0;
    this.data1 = 0;
    this.pec = 0;
    this.aux_status = 0;
    this.aux_control = 0;
    this.block.fill(0);
    /** The block buffer's index (E32B), or the byte of a byte-by-byte transfer */
    this.index = 0;
    /** HOST_BLOCK_DB of a byte-by-byte transfer */
    this.block_byte = 0;
    /** A byte-by-byte transfer under way: "read", "write", "i2c", or none: "" */
    this.transfer = "";
    this.update_irq();
};

/** Decode the registers at SMB_BASE while I/O space and HST_EN are on (and I2C_EN off) */
SMBus.prototype.update_decode = function()
{
    const pci = this.cpu.devices.pci;
    const hostc = pci.function_read(this.pci_id, HOSTC, 1);
    const bar = this.pci_bars[4];
    const base = pci.is_io_enabled(this.pci_id) && hostc & HOSTC_HST_EN && !(hostc & HOSTC_I2C_EN) &&
        bar.base && bar.base + IO_SIZE <= 0x10000 ? bar.base : -1;
    if(base === this.io_base)
    {
        return;
    }
    const io = this.cpu.io;
    if(this.io_base !== -1)
    {
        io.unregister_range(this.io_base, IO_SIZE, this);
    }
    dbg_log("SMBus " + (base === -1 ? "not decoded" : "at " + h(base, 4)), LOG_ACPI);
    this.io_base = base;
    if(base !== -1)
    {
        for(let offset = 0; offset < IO_SIZE; offset++)
        {
            const bytes = size => {
                let value = 0;
                for(let i = 0; i < size; i++) value |= this.read(offset + i) << (i << 3);
                return value;
            };
            io.register_read(base + offset, this, () => bytes(1), () => bytes(2), () => bytes(4));
            io.register_write(base + offset, this,
                value => this.write(offset, value & 0xFF),
                value => { this.write(offset, value & 0xFF); this.write(offset + 1, value >> 8 & 0xFF); },
                value => { for(let i = 0; i < 4; i++) this.write(offset + i, value >>> (i << 3) & 0xFF); });
        }
    }
};

/**
 * @param {number} offset
 * @return {number}
 */
SMBus.prototype.read = function(offset)
{
    switch(offset)
    {
        case HST_STS:
        {
            // INUSE_STS: a semaphore, set by the read that finds it clear
            const value = this.status;
            this.status |= STS_INUSE;
            return value;
        }
        case HST_CNT:
            // (reading it resets the block buffer's index)
            this.index = 0;
            return this.control;
        case HST_CMD: return this.command;
        case XMIT_SLVA: return this.address;
        case HST_D0: return this.data0;
        case HST_D1: return this.data1;
        case HOST_BLOCK_DB:
            if(this.aux_control & AUX_E32B && !this.transfer)
            {
                const value = this.block[this.index];
                this.index = this.index + 1 & BLOCK_MAX - 1;
                return value;
            }
            return this.block_byte;
        case PEC: return this.pec;
        case AUX_STS: return this.aux_status;
        case AUX_CTL: return this.aux_control;
        case SMBUS_PIN_CTL: return 0x07; // SMBCLK, SMBDATA high; SMBCLK_CTL
    }
    return 0;
};

/**
 * @param {number} offset
 * @param {number} value
 */
SMBus.prototype.write = function(offset, value)
{
    dbg_log("SMBus write " + h(offset, 2) + " <- " + h(value, 2), LOG_ACPI);
    switch(offset)
    {
        case HST_STS:
        {
            const byte_done = this.status & value & STS_BYTE_DONE;
            // write one to clear (HOST_BUSY is read-only)
            this.status &= ~(value & ~STS_HOST_BUSY);
            if(byte_done)
            {
                this.next_byte();
            }
            this.update_irq();
            break;
        }
        case HST_CNT:
            this.control = value & ~CNT_START;
            if(value & CNT_KILL)
            {
                // the command in progress ends, failed
                if(this.status & STS_HOST_BUSY || this.transfer)
                {
                    this.transfer = "";
                    this.status = this.status & ~(STS_HOST_BUSY | STS_BYTE_DONE) | STS_FAILED;
                }
                this.index = 0;
            }
            else if(value & CNT_START)
            {
                this.start();
            }
            this.update_irq();
            break;
        case HST_CMD: this.command = value; break;
        case XMIT_SLVA: this.address = value; break;
        case HST_D0: this.data0 = value; break;
        case HST_D1: this.data1 = value; break;
        case HOST_BLOCK_DB:
            if(this.aux_control & AUX_E32B && !this.transfer)
            {
                this.block[this.index] = value;
                this.index = this.index + 1 & BLOCK_MAX - 1;
            }
            else
            {
                this.block_byte = value;
            }
            break;
        case PEC: this.pec = value; break;
        case AUX_STS: this.aux_status &= ~value; break;
        case AUX_CTL: this.aux_control = value & 0x03; break;
    }
};

/**
 * The device at a 7-bit address
 * @param {number} address
 * @return {SMBusEEPROM|undefined}
 */
SMBus.prototype.device = function(address)
{
    return this.devices.find(device => device.address === address);
};

/** START: run the command in HST_CNT */
SMBus.prototype.start = function()
{
    const protocol = this.control >> 2 & 7;
    const read = (this.address & 1) !== 0;
    const device = this.device(this.address >> 1);
    dbg_log("SMBus command " + protocol + (read ? " read" : " write") + " at " + h(this.address >> 1, 2), LOG_ACPI);

    if(this.status & (STS_DEV_ERR | STS_BUS_ERR | STS_FAILED) || this.transfer)
    {
        // (a previous error not cleared: the command does not run)
        this.status |= STS_DEV_ERR;
        return;
    }
    if(!device)
    {
        // no acknowledge
        this.status |= STS_DEV_ERR;
        return;
    }

    switch(protocol)
    {
        case PROT_QUICK:
            break;
        case PROT_BYTE:
            if(read) this.data0 = device.receive_byte();
            else device.send_byte(this.command);
            break;
        case PROT_BYTE_DATA:
            if(read)
            {
                device.send_byte(this.command);
                this.data0 = device.receive_byte();
            }
            else
            {
                device.write_byte(this.command, this.data0);
            }
            break;
        case PROT_WORD_DATA:
            if(read)
            {
                device.send_byte(this.command);
                this.data0 = device.receive_byte();
                this.data1 = device.receive_byte();
            }
            else
            {
                device.write_byte(this.command, this.data0);
                device.write_byte(this.command + 1, this.data1);
            }
            break;
        case PROT_PROCESS_CALL:
        {
            // write a word, read one back
            device.write_byte(this.command, this.data0);
            device.write_byte(this.command + 1, this.data1);
            device.send_byte(this.command);
            this.data0 = device.receive_byte();
            this.data1 = device.receive_byte();
            break;
        }
        case PROT_BLOCK:
        case PROT_BLOCK_PROCESS:
            if(read && protocol === PROT_BLOCK)
            {
                // the device sends the byte count first
                device.send_byte(this.command);
                const count = Math.min(device.receive_byte(), BLOCK_MAX);
                const data = new Uint8Array(BLOCK_MAX);
                for(let i = 0; i < count; i++) data[i] = device.receive_byte();
                this.data0 = count;
                this.block.set(data);
                this.index = 0;
                if(!(this.aux_control & AUX_E32B))
                {
                    // (also with a count of 0: software reads it with the first byte)
                    this.transfer = "read";
                    this.block_byte = this.block[0];
                    this.status |= STS_HOST_BUSY | STS_BYTE_DONE;
                    return;
                }
            }
            else
            {
                if(!(this.aux_control & AUX_E32B))
                {
                    // the bytes come one by one through HOST_BLOCK_DB
                    this.transfer = "write";
                    this.block[0] = this.block_byte;
                    this.index = 0;
                    this.status |= STS_HOST_BUSY | STS_BYTE_DONE;
                    return;
                }
                this.write_block(device);
                if(protocol === PROT_BLOCK_PROCESS)
                {
                    device.send_byte(this.command);
                    const count = Math.min(device.receive_byte(), BLOCK_MAX);
                    for(let i = 0; i < count; i++) this.block[i] = device.receive_byte();
                    this.data0 = count;
                }
                this.index = 0;
            }
            break;
        case PROT_I2C_READ:
            // I2C: the offset (HST_D1) sent, then bytes read one by one
            // until LAST_BYTE (QEMU ignores the R/W bit here, as Linux sets
            // it either way)
            device.send_byte(this.data1);
            this.transfer = "i2c";
            this.block_byte = device.receive_byte();
            this.status |= STS_HOST_BUSY | STS_BYTE_DONE;
            return;
    }
    this.status |= STS_INTR;
};

/**
 * A block write from the block buffer: the command, the byte count (HST_D0),
 * the bytes; an EEPROM stores the count and the bytes from the command's
 * offset on (as QEMU's), so that a block read returns them
 * @param {SMBusEEPROM} device
 */
SMBus.prototype.write_block = function(device)
{
    const count = Math.min(this.data0, BLOCK_MAX);
    device.write_byte(this.command, count);
    for(let i = 0; i < count; i++)
    {
        device.write_byte(this.command + 1 + i, this.block[i]);
    }
};

/** Byte-by-byte transfers: software cleared BYTE_DONE_STS, the next byte */
SMBus.prototype.next_byte = function()
{
    const device = this.device(this.address >> 1);
    if(!this.transfer || !device)
    {
        return;
    }
    this.index++;
    if(this.transfer === "write")
    {
        if(this.index >= Math.min(this.data0, BLOCK_MAX))
        {
            this.write_block(device);
            this.end_transfer();
            return;
        }
        this.block[this.index] = this.block_byte;
        this.status |= STS_BYTE_DONE;
        return;
    }
    // a read: the next byte, or with LAST_BYTE the end (software set it
    // before taking the last byte; as QEMU's, one more byte is fetched)
    this.block_byte = this.transfer === "i2c" ? device.receive_byte() : this.block[this.index & BLOCK_MAX - 1];
    if(this.control & CNT_LAST_BYTE)
    {
        this.end_transfer();
    }
    else
    {
        this.status |= STS_BYTE_DONE;
    }
};

SMBus.prototype.end_transfer = function()
{
    this.transfer = "";
    this.index = 0;
    this.status = this.status & ~STS_HOST_BUSY | STS_INTR;
};

/** INTA: a command ended (or a byte is done) with INTREN */
SMBus.prototype.update_irq = function()
{
    const level = (this.control & CNT_INTREN) !== 0 && (this.status & STS_INTERRUPTS) !== 0;
    if(level !== this.irq_level)
    {
        this.irq_level = level;
        level ? this.cpu.devices.pci.raise_irq(this.pci_id) : this.cpu.devices.pci.lower_irq(this.pci_id);
    }
};

SMBus.prototype.get_state = function()
{
    const state = [];
    state[0] = STATE_FORMAT;
    state[1] = [this.status, this.control, this.command, this.address, this.data0, this.data1,
        this.pec, this.aux_status, this.aux_control, this.index, this.block_byte, this.irq_level ? 1 : 0];
    state[2] = this.transfer;
    state[3] = this.block;
    state[4] = this.devices.map(device => [device.data, device.offset]);
    return state;
};

SMBus.prototype.set_state = function(state)
{
    [this.status, this.control, this.command, this.address, this.data0, this.data1,
        this.pec, this.aux_status, this.aux_control, this.index, this.block_byte] = state[1];
    this.irq_level = !!state[1][11];
    this.transfer = state[2];
    this.block.set(state[3]);
    state[4].forEach(([data, offset], i) => {
        this.devices[i].data.set(data);
        this.devices[i].offset = offset;
    });
};
                                                                                                                                                                                                                                                                                                          source/v64/src/state.js                                                                             0000644 0000000 0000000 00000067760 00000000000 012151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { h } from "./lib.js";
import { STATE_MAX_SINGLE_BUFFER } from "./const.js";
import { dbg_assert, dbg_log } from "./log.js";
import { CPU } from "./cpu.js";
import { check_no_disk_holds } from "./block_backend.js";

// Version 8 (and the stream's 9): the NE2000 and the SB16 are plugins
// (docs/modern-pc-devices-plan.md M1), their slots tagged. Versions 6 and 7,
// from before, are read too: their untagged state[59] and state[61] are the
// NE2000's and the SB16's own states, which their plugins read as they are
// (src/device_plugin.js). An older v86 refuses 8 and 9 ("Version mismatch")
// rather than read the tagged slots as registers. Single files have even
// versions, streams odd ones (pages tell them apart by the header).
const STATE_VERSION = 8;
const STATE_VERSIONS_READ = [6, STATE_VERSION];
const STATE_MAGIC = 0x86768676|0;
const STATE_INDEX_MAGIC = 0;
const STATE_INDEX_VERSION = 1;
const STATE_INDEX_TOTAL_LEN = 2;
const STATE_INDEX_INFO_LEN = 3;
const STATE_INFO_BLOCK_START = 16;

const ZSTD_MAGIC = 0xFD2FB528;

/** @constructor */
function StateLoadError(msg)
{
    this.message = msg;
}
StateLoadError.prototype = new Error;

const CONSTRUCTOR_TABLE = {
    "Map": Map,
    "Uint8Array": Uint8Array,
    "Int8Array": Int8Array,
    "Uint16Array": Uint16Array,
    "Int16Array": Int16Array,
    "Uint32Array": Uint32Array,
    "Int32Array": Int32Array,
    "Float32Array": Float32Array,
    "Float64Array": Float64Array,
};

function save_object(obj, saved_buffers)
{
    if(typeof obj !== "object" || obj === null)
    {
        dbg_assert(typeof obj !== "function");
        return obj;
    }

    if(Array.isArray(obj))
    {
        return obj.map(x => save_object(x, saved_buffers));
    }

    if(obj instanceof Map)
    {
        return {
            "__state_type__": "Map",
            "args": Array.from(obj.entries()).map(([k, v]) => [
                save_object(k, saved_buffers),
                save_object(v, saved_buffers),
            ]),
        };
    }

    if(obj.constructor === Object)
    {
        console.log(obj);
        dbg_assert(obj.constructor !== Object, "Expected non-object");
    }

    if(obj.BYTES_PER_ELEMENT)
    {
        // Uint8Array, etc.
        var buffer = new Uint8Array(obj.buffer, obj.byteOffset, obj.length * obj.BYTES_PER_ELEMENT);

        const constructor = obj.constructor.name.replace("bound ", "");

        dbg_assert(CONSTRUCTOR_TABLE[constructor]);

        return {
            "__state_type__": constructor,
            "buffer_id": saved_buffers.push(buffer) - 1,
        };
    }

    if(DEBUG && !obj.get_state)
    {
        console.log("Object without get_state: ", obj);
    }

    var state = obj.get_state();
    var result = [];

    for(var i = 0; i < state.length; i++)
    {
        var value = state[i];

        dbg_assert(typeof value !== "function");

        result[i] = save_object(value, saved_buffers);
    }

    return result;
}

function restore_buffers(obj, buffers)
{
    if(typeof obj !== "object" || obj === null)
    {
        dbg_assert(typeof obj !== "function");
        return obj;
    }

    if(Array.isArray(obj))
    {
        for(let i = 0; i < obj.length; i++)
        {
            obj[i] = restore_buffers(obj[i], buffers);
        }

        return obj;
    }

    const type = obj["__state_type__"];
    dbg_assert(type !== undefined);

    const constructor = CONSTRUCTOR_TABLE[type];
    dbg_assert(constructor, "Unkown type: " + type);

    if(obj["args"] !== undefined) {
        return new constructor(restore_buffers(obj["args"], buffers));
    }

    const buffer = buffers[obj["buffer_id"]];
    return new constructor(buffer);
}

/* @param {CPU} cpu */
export function save_state(cpu)
{
    // (not while disk requests are held after an I/O error: src/block_backend.js)
    check_no_disk_holds(cpu);
    var saved_buffers = [];
    var state = save_object(cpu, saved_buffers);

    var buffer_infos = [];
    var total_buffer_size = 0;

    for(var i = 0; i < saved_buffers.length; i++)
    {
        var len = saved_buffers[i].byteLength;

        buffer_infos[i] = {
            offset: total_buffer_size,
            length: len,
        };

        total_buffer_size += len;

        // align (not with 32-bit operators: the sum may pass 2 GiB)
        total_buffer_size += (4 - total_buffer_size % 4) % 4;
    }
    if(total_buffer_size > STATE_MAX_SINGLE_BUFFER)
    {
        throw new RangeError("The state (" + Math.ceil(total_buffer_size / 1048576) + " MB) is larger than a single-buffer " +
            "snapshot can be (2 GiB): use save_state_stream");
    }

    var info_object = JSON.stringify({
        "buffer_infos": buffer_infos,
        "state": state,
    });
    var info_block = new TextEncoder().encode(info_object);

    var buffer_block_start = STATE_INFO_BLOCK_START + info_block.length;
    buffer_block_start = buffer_block_start + 3 & ~3;
    var total_size = buffer_block_start + total_buffer_size;
    if(total_size > STATE_MAX_SINGLE_BUFFER)
    {
        throw new RangeError("The state (" + Math.ceil(total_size / 1048576) + " MB) is larger than a single-buffer " +
            "snapshot can be (2 GiB): use save_state_stream");
    }

    //console.log("State: json_size=" + Math.ceil(buffer_block_start / 1024 / 1024) + "MB " +
    //               "buffer_size=" + Math.ceil(total_buffer_size / 1024 / 1024) + "MB");

    var result = new ArrayBuffer(total_size);

    var header_block = new Int32Array(
        result,
        0,
        STATE_INFO_BLOCK_START / 4
    );
    new Uint8Array(result, STATE_INFO_BLOCK_START, info_block.length).set(info_block);
    var buffer_block = new Uint8Array(
        result,
        buffer_block_start
    );

    header_block[STATE_INDEX_MAGIC] = STATE_MAGIC;
    header_block[STATE_INDEX_VERSION] = STATE_VERSION;
    header_block[STATE_INDEX_TOTAL_LEN] = total_size;
    header_block[STATE_INDEX_INFO_LEN] = info_block.length;

    for(var i = 0; i < saved_buffers.length; i++)
    {
        var buffer = saved_buffers[i];
        dbg_assert(buffer.constructor === Uint8Array);
        buffer_block.set(buffer, buffer_infos[i].offset);
    }

    dbg_log("State: json size " + (info_block.byteLength >> 10) + "k");
    dbg_log("State: Total buffers size " + (buffer_block.byteLength >> 10) + "k");

    return result;
}

/* @param {CPU} cpu */
export function restore_state(cpu, state)
{
    state = new Uint8Array(state);
    if(state.length < 4) throw new StateLoadError("Invalid snapshot length: " + state.length);

    function read_state_header(state, check_length)
    {
        const len = state.length;

        if(len < STATE_INFO_BLOCK_START)
        {
            throw new StateLoadError("Invalid length: " + len);
        }

        const header_block = new Int32Array(state.buffer, state.byteOffset, 4);

        if(header_block[STATE_INDEX_MAGIC] !== STATE_MAGIC)
        {
            throw new StateLoadError("Invalid header: " + h(header_block[STATE_INDEX_MAGIC] >>> 0));
        }

        if(!STATE_VERSIONS_READ.includes(header_block[STATE_INDEX_VERSION]))
        {
            throw new StateLoadError(
                    "Version mismatch: dump=" + header_block[STATE_INDEX_VERSION] +
                    " we=" + STATE_VERSION);
        }

        if(check_length && header_block[STATE_INDEX_TOTAL_LEN] !== len)
        {
            throw new StateLoadError(
                    "Length doesn't match header: " +
                    "real=" + len + " header=" + header_block[STATE_INDEX_TOTAL_LEN]);
        }

        return header_block[STATE_INDEX_INFO_LEN];
    }

    function read_info_block(info_block_buffer)
    {
        const info_block = new TextDecoder().decode(info_block_buffer);
        return JSON.parse(info_block);
    }

    if(new Uint32Array(state.buffer, 0, 1)[0] === ZSTD_MAGIC)
    {
        const ctx = cpu.zstd_create_ctx(state.length);

        new Uint8Array(cpu.wasm_memory.buffer, cpu.zstd_get_src_ptr(ctx) >>> 0, state.length).set(state);

        let ptr = cpu.zstd_read(ctx, 16);
        const header_block = new Uint8Array(cpu.wasm_memory.buffer, ptr >>> 0, 16);
        const info_block_len = read_state_header(header_block, false);
        cpu.zstd_read_free(ptr, 16);

        ptr = cpu.zstd_read(ctx, info_block_len);
        const info_block_buffer = new Uint8Array(cpu.wasm_memory.buffer, ptr >>> 0, info_block_len);
        const info_block_obj = read_info_block(info_block_buffer);
        cpu.zstd_read_free(ptr, info_block_len);

        let state_object = info_block_obj["state"];
        const buffer_infos = info_block_obj["buffer_infos"];
        const buffers = [];

        let position = STATE_INFO_BLOCK_START + info_block_len;

        for(const buffer_info of buffer_infos)
        {
            const front_padding = (position + 3 & ~3) - position;
            const CHUNK_SIZE = 1 * 1024 * 1024;

            if(buffer_info.length > CHUNK_SIZE)
            {
                const ptr = cpu.zstd_read(ctx, front_padding) >>> 0;
                cpu.zstd_read_free(ptr, front_padding);

                const buffer = new Uint8Array(buffer_info.length);
                buffers.push(buffer.buffer);

                let have = 0;
                while(have < buffer_info.length)
                {
                    const remaining = buffer_info.length - have;
                    dbg_assert(remaining >= 0);
                    const to_read = Math.min(remaining, CHUNK_SIZE);

                    const ptr = cpu.zstd_read(ctx, to_read);
                    buffer.set(new Uint8Array(cpu.wasm_memory.buffer, ptr >>> 0, to_read), have);
                    cpu.zstd_read_free(ptr, to_read);

                    have += to_read;
                }
            }
            else
            {
                const ptr = cpu.zstd_read(ctx, front_padding + buffer_info.length);
                const offset = (ptr >>> 0) + front_padding;
                buffers.push(cpu.wasm_memory.buffer.slice(offset, offset + buffer_info.length));
                cpu.zstd_read_free(ptr, front_padding + buffer_info.length);
            }

            position += front_padding + buffer_info.length;
        }

        state_object = restore_buffers(state_object, buffers);
        cpu.set_state(state_object);

        cpu.zstd_free_ctx(ctx);
    }
    else
    {
        const info_block_len = read_state_header(state, true);

        if(info_block_len < 0 || info_block_len + 12 >= state.length)
        {
            throw new StateLoadError("Invalid info block length: " + info_block_len);
        }

        const info_block_buffer = state.subarray(STATE_INFO_BLOCK_START, STATE_INFO_BLOCK_START + info_block_len);
        const info_block_obj = read_info_block(info_block_buffer);
        let state_object = info_block_obj["state"];
        const buffer_infos = info_block_obj["buffer_infos"];
        let buffer_block_start = STATE_INFO_BLOCK_START + info_block_len;
        buffer_block_start = buffer_block_start + 3 & ~3;

        const buffers = buffer_infos.map(buffer_info => {
            const offset = buffer_block_start + buffer_info.offset;
            return state.buffer.slice(offset, offset + buffer_info.length);
        });

        state_object = restore_buffers(state_object, buffers);
        cpu.set_state(state_object);
    }
}

// V7 (header versions 7 and, since M1, 9: see STATE_VERSION) is a stream of
// a small manifest and independently checked records. RAM is
// packed directly from backing pages into one reusable-size record, never into
// the V6 packed_memory allocation. Guest physical addresses are only metadata.
export const STATE_STREAM_CHUNK_SIZE = 1024 * 1024;
const STREAM_VERSION = 9;
/** (7: before M1, see STATE_VERSION) */
const STREAM_VERSIONS_READ = [7, STREAM_VERSION];
const STREAM_HEADER_SIZE = 32;
const STREAM_RECORD_SIZE = 20;
const STREAM_RAM_CHUNK = STATE_STREAM_CHUNK_SIZE - 4096;
const STREAM_INFO_LIMIT = 16 * 1024 * 1024;

function stream_error(message)
{
    throw new StateLoadError("Invalid V7 snapshot: " + message);
}

// CRC-32 (IEEE, as zlib's), slicing-by-16: 16 tables, 16 bytes a step read as
// four little-endian words, five times as fast as a byte a step (which made
// about half the time of saving a snapshot of gigabytes)
const STREAM_CRC_TABLE = new Int32Array(16 * 256);
for(let i = 0; i < 256; i++)
{
    let value = i;
    for(let bit = 0; bit < 8; bit++) value = value >>> 1 ^ (value & 1 ? 0xEDB88320 : 0);
    STREAM_CRC_TABLE[i] = value;
}
for(let i = 256; i < 16 * 256; i++)
{
    const previous = STREAM_CRC_TABLE[i - 256];
    STREAM_CRC_TABLE[i] = previous >>> 8 ^ STREAM_CRC_TABLE[previous & 255];
}
function stream_crc(bytes)
{
    const table = STREAM_CRC_TABLE, length = bytes.length;
    let crc = -1, i = 0;
    // byte by byte up to a word boundary, then 16 bytes a step, then the rest
    for(const head = Math.min(length, -bytes.byteOffset & 3); i < head; i++) crc = crc >>> 8 ^ table[(crc ^ bytes[i]) & 255];
    const count = (length - i) >> 4 << 2;
    if(count)
    {
        const words = new Int32Array(bytes.buffer, bytes.byteOffset + i, count);
        for(let w = 0; w < count; w += 4)
        {
            const a = crc ^ words[w], b = words[w + 1], c = words[w + 2], d = words[w + 3];
            crc = table[3840 + (a & 255)] ^ table[3584 + (a >>> 8 & 255)] ^ table[3328 + (a >>> 16 & 255)] ^ table[3072 + (a >>> 24)] ^
                table[2816 + (b & 255)] ^ table[2560 + (b >>> 8 & 255)] ^ table[2304 + (b >>> 16 & 255)] ^ table[2048 + (b >>> 24)] ^
                table[1792 + (c & 255)] ^ table[1536 + (c >>> 8 & 255)] ^ table[1280 + (c >>> 16 & 255)] ^ table[1024 + (c >>> 24)] ^
                table[768 + (d & 255)] ^ table[512 + (d >>> 8 & 255)] ^ table[256 + (d >>> 16 & 255)] ^ table[d >>> 24];
        }
        i += count * 4;
    }
    for(; i < length; i++) crc = crc >>> 8 ^ table[(crc ^ bytes[i]) & 255];
    return (crc ^ -1) >>> 0;
}

function stream_record(kind, id, offset, data)
{
    const bytes = new Uint8Array(STREAM_RECORD_SIZE + data.length);
    const words = new DataView(bytes.buffer);
    words.setUint32(0, kind, true);
    words.setUint32(4, id, true);
    words.setUint32(8, offset, true);
    words.setUint32(12, data.length, true);
    bytes.set(data, 16);
    words.setUint32(16 + data.length, stream_crc(bytes.subarray(0, 16 + data.length)), true);
    return bytes;
}

// Pulling one chunk at a time also gives the Worker transport real backpressure.
export function create_state_stream(cpu)
{
    check_no_disk_holds(cpu);
    const memory_size = cpu.memory_size[0] >>> 0;
    if(memory_size > cpu.mem8.length || memory_size % 4096) stream_error("RAM size");
    const bitmap = new Uint8Array(Math.ceil(memory_size / 4096 / 8));
    let packed_size = 0;
    for(let page = 0; page < memory_size / 4096; page++)
    {
        if(!cpu.is_memory_zeroed(page * 4096, 4096))
        {
            bitmap[page >> 3] |= 1 << (page & 7);
            packed_size += 4096;
        }
    }
    // extended RAM: the pages that are not zero, after the RAM records
    const extended = cpu.extended_store;
    let extended_bitmap = null, extended_packed = 0;
    if(extended)
    {
        cpu.flush_extended_memory();
        extended_bitmap = new Uint8Array(Math.ceil(extended.pages / 8));
        for(let page = 0; page < extended.pages; page++)
        {
            if(!extended.is_zero(page))
            {
                extended_bitmap[page >> 3] |= 1 << (page & 7);
                extended_packed++;
            }
        }
    }
    const state = cpu.get_state(true);
    state[77] = null;
    state[78] = bitmap;
    state[99] = extended_bitmap;
    const buffers = [];
    const manifest = new TextEncoder().encode(JSON.stringify({
        "state": save_object(state, buffers),
        "buffers": buffers.map(buffer => buffer.length),
        "extended_pages": extended_packed,
    }));
    if(manifest.length > STREAM_INFO_LIMIT) stream_error("manifest too large");
    const header = new Uint8Array(STREAM_HEADER_SIZE);
    const words = new DataView(header.buffer);
    [STATE_MAGIC, STREAM_VERSION, STATE_STREAM_CHUNK_SIZE, manifest.length, buffers.length,
        memory_size, packed_size, stream_crc(manifest)].forEach((value, index) => words.setUint32(index * 4, value, true));
    let phase = 0, position = 0, buffer_id = 0, ram_page = 0, extended_page = 0;
    const extended_size = extended_packed * 4096;
    return {
        "next": () => {
            if(phase === 0) { phase = 1; return header; }
            if(phase === 1)
            {
                if(position < manifest.length)
                {
                    const part = manifest.slice(position, position + STATE_STREAM_CHUNK_SIZE);
                    position += part.length;
                    return part;
                }
                phase = 2;
                position = 0;
            }
            if(phase === 2)
            {
                while(buffer_id < buffers.length)
                {
                    const buffer = buffers[buffer_id];
                    if(position < buffer.length)
                    {
                        const part = stream_record(1, buffer_id, position,
                            buffer.subarray(position, position + STATE_STREAM_CHUNK_SIZE - STREAM_RECORD_SIZE));
                        position += part.length - STREAM_RECORD_SIZE;
                        return part;
                    }
                    buffer_id++;
                    position = 0;
                }
                phase = 3;
                position = 0;
            }
            if(phase === 3)
            {
                if(position < packed_size)
                {
                    const length = Math.min(STREAM_RAM_CHUNK, packed_size - position);
                    const data = new Uint8Array(length);
                    for(let offset = 0; offset < length; offset += 4096)
                    {
                        while(!(bitmap[ram_page >> 3] & 1 << (ram_page & 7))) ram_page++;
                        data.set(cpu.mem8.subarray(ram_page * 4096, (ram_page + 1) * 4096), offset);
                        ram_page++;
                    }
                    const result = stream_record(2, 0, position, data);
                    position += length;
                    return result;
                }
                phase = 4;
                position = 0;
            }
            // extended RAM: records of kind 3; id and offset are the high and
            // low 32 bits of the position in its packed pages
            if(position === extended_size) return null;
            const length = Math.min(STREAM_RAM_CHUNK, extended_size - position);
            const data = new Uint8Array(length);
            for(let offset = 0; offset < length; offset += 4096)
            {
                while(!(extended_bitmap[extended_page >> 3] & 1 << (extended_page & 7))) extended_page++;
                data.set(extended.page(extended_page), offset);
                extended_page++;
            }
            const result = stream_record(3, Math.floor(position / 0x100000000), position >>> 0, data);
            position += length;
            return result;
        },
    };
}

export async function save_state_stream(cpu, write)
{
    if(typeof write !== "function") throw new TypeError("Snapshot writer must be a function");
    const stream = create_state_stream(cpu);
    for(let chunk; (chunk = stream["next"]()) !== null;) await write(chunk);
}

export function state_stream_source(source)
{
    if(typeof Blob !== "undefined" && source instanceof Blob)
    {
        return { "size": source.size,
            "read": async (offset, length) => new Uint8Array(await source.slice(offset, offset + length).arrayBuffer()) };
    }
    if(!source || !Number.isSafeInteger(source["size"]) || source["size"] < STREAM_HEADER_SIZE ||
        typeof source["read"] !== "function") throw new TypeError("Snapshot source requires size and read(offset, length)");
    return source;
}

async function stream_read(source, offset, length)
{
    if(length > STATE_STREAM_CHUNK_SIZE || offset + length > source["size"]) stream_error("truncated record");
    const bytes = await source["read"](offset, length);
    if(!(bytes instanceof Uint8Array) || bytes.length !== length) stream_error("short read");
    return bytes;
}

function validate_stream_tree(obj, buffers, depth = 0)
{
    if(depth > 256) stream_error("state nesting");
    if(obj === null || typeof obj !== "object") return;
    if(Array.isArray(obj))
    {
        for(const child of obj) validate_stream_tree(child, buffers, depth + 1);
        return;
    }
    const type = obj["__state_type__"];
    if(type === "Map" && Array.isArray(obj["args"]))
    {
        validate_stream_tree(obj["args"], buffers, depth + 1);
        return;
    }
    const constructor = CONSTRUCTOR_TABLE[type], id = obj["buffer_id"];
    if(!Object.prototype.hasOwnProperty.call(CONSTRUCTOR_TABLE, type) || type === "Map" ||
        !Number.isInteger(id) || id < 0 || id >= buffers.length ||
        buffers[id] % constructor.BYTES_PER_ELEMENT) stream_error("typed buffer reference");
}

// The source must remain immutable for both passes (Blob/File are convenient).
// Pass 1 checks every byte before live RAM changes. Pass 2 writes directly into
// existing backing RAM. A late I/O failure leaves the machine stopped; it cannot
// promise rollback without retaining a second RAM image.
export async function restore_state_stream(cpu, input)
{
    const source = state_stream_source(input);
    const header = await stream_read(source, 0, STREAM_HEADER_SIZE);
    const words = new DataView(header.buffer, header.byteOffset, header.byteLength);
    if(words.getUint32(0, true) !== (STATE_MAGIC >>> 0) || !STREAM_VERSIONS_READ.includes(words.getUint32(4, true)) ||
        words.getUint32(8, true) !== STATE_STREAM_CHUNK_SIZE) stream_error("header/version");
    const info_size = words.getUint32(12, true), buffer_count = words.getUint32(16, true);
    const memory_size = words.getUint32(20, true), packed_size = words.getUint32(24, true);
    if(!info_size || info_size > STREAM_INFO_LIMIT || memory_size > cpu.mem8.length || memory_size % 4096 ||
        packed_size > memory_size || packed_size % 4096) stream_error("manifest/RAM size");
    const manifest = new Uint8Array(info_size);
    for(let offset = 0; offset < info_size; offset += STATE_STREAM_CHUNK_SIZE)
        manifest.set(await stream_read(source, STREAM_HEADER_SIZE + offset, Math.min(STATE_STREAM_CHUNK_SIZE, info_size - offset)), offset);
    if(stream_crc(manifest) !== words.getUint32(28, true)) stream_error("manifest checksum");
    let info;
    try { info = JSON.parse(new TextDecoder("utf-8", { "fatal": true }).decode(manifest)); }
    catch(_) { stream_error("manifest JSON"); }
    const lengths = info["buffers"];
    if(!Array.isArray(lengths) || lengths.length !== buffer_count || buffer_count > 65536 ||
        lengths.some(length => !Number.isSafeInteger(length) || length < 0 || length > 0xFFFFFFFF)) stream_error("buffer lengths");
    let total = STREAM_HEADER_SIZE + info_size;
    for(const length of lengths) total += length + Math.ceil(length / (STATE_STREAM_CHUNK_SIZE - STREAM_RECORD_SIZE)) * STREAM_RECORD_SIZE;
    total += packed_size + Math.ceil(packed_size / STREAM_RAM_CHUNK) * STREAM_RECORD_SIZE;
    const extended_packed = info["extended_pages"] === undefined ? 0 : info["extended_pages"];
    if(!Number.isSafeInteger(extended_packed) || extended_packed < 0 || extended_packed > cpu.extended_pages) stream_error("extended RAM size");
    const extended_size = extended_packed * 4096;
    total += extended_size + Math.ceil(extended_size / STREAM_RAM_CHUNK) * STREAM_RECORD_SIZE;
    if(total !== source["size"]) stream_error("total length");
    validate_stream_tree(info["state"], lengths);
    const buffers = [];
    let position = STREAM_HEADER_SIZE + info_size;
    const read_record = async (kind, id, offset, length) => {
        const bytes = await stream_read(source, position, STREAM_RECORD_SIZE + length);
        const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
        if(view.getUint32(0, true) !== kind || view.getUint32(4, true) !== id ||
            view.getUint32(8, true) !== offset || view.getUint32(12, true) !== length ||
            view.getUint32(16 + length, true) !== stream_crc(bytes.subarray(0, 16 + length))) stream_error("record/checksum");
        position += bytes.length;
        return bytes;
    };
    for(let id = 0; id < lengths.length; id++)
    {
        const buffer = new Uint8Array(lengths[id]);
        for(let offset = 0; offset < buffer.length;)
        {
            const length = Math.min(STATE_STREAM_CHUNK_SIZE - STREAM_RECORD_SIZE, buffer.length - offset);
            const bytes = await read_record(1, id, offset, length);
            buffer.set(bytes.subarray(16, 16 + length), offset);
            offset += length;
        }
        buffers.push(buffer.buffer);
    }
    const state = restore_buffers(info["state"], buffers);
    if(!Array.isArray(state) || state[0] !== memory_size || state[77] !== null ||
        !(state[78] instanceof Uint8Array) || state[78].length !== Math.ceil(memory_size / 4096 / 8)) stream_error("RAM bitmap");
    const bitmap = state[78];
    let count = 0;
    for(let page = 0; page < bitmap.length * 8; page++) if(bitmap[page >> 3] & 1 << (page & 7))
    {
        if(page >= memory_size / 4096) stream_error("bitmap beyond RAM");
        count++;
    }
    if(count * 4096 !== packed_size) stream_error("bitmap count");
    const extended_bitmap = state[99] || null;
    if(extended_packed || extended_bitmap)
    {
        if(!(extended_bitmap instanceof Uint8Array) || extended_bitmap.length !== Math.ceil(cpu.extended_pages / 8)) stream_error("extended RAM bitmap");
        let pages = 0;
        for(let page = 0; page < extended_bitmap.length * 8; page++) if(extended_bitmap[page >> 3] & 1 << (page & 7))
        {
            if(page >= cpu.extended_pages) stream_error("extended bitmap beyond RAM");
            pages++;
        }
        if(pages !== extended_packed) stream_error("extended bitmap count");
    }
    cpu.validate_state(state);
    const ram_start = position, checksums = [];
    for(let offset = 0; offset < packed_size; offset += STREAM_RAM_CHUNK)
    {
        const length = Math.min(STREAM_RAM_CHUNK, packed_size - offset);
        const bytes = await read_record(2, 0, offset, length);
        checksums.push(new DataView(bytes.buffer, bytes.byteOffset).getUint32(16 + length, true));
    }
    for(let offset = 0; offset < extended_size; offset += STREAM_RAM_CHUNK)
    {
        const length = Math.min(STREAM_RAM_CHUNK, extended_size - offset);
        const bytes = await read_record(3, Math.floor(offset / 0x100000000), offset >>> 0, length);
        checksums.push(new DataView(bytes.buffer, bytes.byteOffset).getUint32(16 + length, true));
    }
    // No architectural or RAM mutation has occurred before this point.
    cpu.zero_memory(0, memory_size);
    position = ram_start;
    let page = 0, record = 0;
    for(let offset = 0; offset < packed_size; offset += STREAM_RAM_CHUNK)
    {
        const length = Math.min(STREAM_RAM_CHUNK, packed_size - offset);
        const bytes = await read_record(2, 0, offset, length);
        if(new DataView(bytes.buffer, bytes.byteOffset).getUint32(16 + length, true) !== checksums[record++]) stream_error("source changed between passes");
        for(let part = 0; part < length; part += 4096)
        {
            while(!(bitmap[page >> 3] & 1 << (page & 7))) page++;
            cpu.mem8.set(bytes.subarray(16 + part, 16 + part + 4096), page * 4096);
            page++;
        }
    }
    cpu.clear_extended_memory();
    let extended_page = 0;
    for(let offset = 0; offset < extended_size; offset += STREAM_RAM_CHUNK)
    {
        const length = Math.min(STREAM_RAM_CHUNK, extended_size - offset);
        const bytes = await read_record(3, Math.floor(offset / 0x100000000), offset >>> 0, length);
        if(new DataView(bytes.buffer, bytes.byteOffset).getUint32(16 + length, true) !== checksums[record++]) stream_error("source changed between passes");
        for(let part = 0; part < length; part += 4096)
        {
            while(!(extended_bitmap[extended_page >> 3] & 1 << (extended_page & 7))) extended_page++;
            cpu.extended_store.write(extended_page, bytes.subarray(16 + part, 16 + part + 4096));
            extended_page++;
        }
    }
    cpu.set_state(state, true);
}
                source/v64/src/state_io.js                                                                          0000644 0000000 0000000 00000001330 00000000000 012615  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Host I/O started by a guest command must finish before an asynchronous
// snapshot reads device state or RAM. Completion is idempotent for abort races.
export function begin_state_io(cpu)
{
    cpu["snapshot_io_pending"] = (cpu["snapshot_io_pending"] || 0) + 1;
    let complete = false;
    return () => {
        if(!complete)
        {
            complete = true;
            cpu["snapshot_io_pending"]--;
        }
    };
}

export function track_state_io(cpu, start, callback)
{
    const complete = begin_state_io(cpu);
    try
    {
        return start((...args) => {
            try { return callback(...args); }
            finally { complete(); }
        });
    }
    catch(error) { complete(); throw error; }
}
                                                                                                                                                                                                                                                                                                        source/v64/src/state_layout.js                                                                      0000644 0000000 0000000 00000006642 00000000000 013536  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by gen/state_layout.js from the CPU state layout; do not edit.

/** Offsets of the CPU state fields in the Wasm memory */
export const STATE_OFFSETS = {
    reg8: 64,
    reg16: 64,
    reg32: 64,
    last_op_size: 96,
    flags_changed: 100,
    last_op1: 104,
    state_flags: 108,
    last_result: 112,
    flags: 120,
    segment_access_bytes: 512,
    apic_enabled: 548,
    acpi_enabled: 552,
    instruction_pointer: 556,
    previous_ip: 560,
    idtr_size: 564,
    idtr_offset: 568,
    gdtr_size: 572,
    gdtr_offset: 576,
    cr: 580,
    cpl: 612,
    in_hlt: 616,
    last_virt_eip: 620,
    eip_phys: 624,
    nmi_blocked: 628,
    interrupt_shadow: 632,
    sysenter_cs: 636,
    sysenter_esp: 640,
    sysenter_eip: 644,
    prefixes: 648,
    instruction_counter: 664,
    sreg: 668,
    dreg: 684,
    svga_dirty_bitmap_min_offset: 716,
    svga_dirty_bitmap_max_offset: 720,
    segment_is_null: 724,
    segment_offsets: 736,
    segment_limits: 768,
    protected_mode: 800,
    is_32: 804,
    stack_size_32: 808,
    memory_size: 812,
    fpu_stack_empty: 816,
    mxcsr: 824,
    reg_xmm: 832,
    current_tsc: 960,
    reg_pdpte: 968,
    fpu_stack_ptr: 1032,
    fpu_control_word: 1036,
    fpu_status_word: 1040,
    fpu_opcode: 1044,
    fpu_ip: 1048,
    fpu_ip_selector: 1052,
    fpu_dp: 1056,
    fpu_dp_selector: 1060,
    tss_size_32: 1128,
    sse_scratch_register: 1136,
    fpu_st: 1152,
    x87_shadow_values: 1280,
    x87_shadow_valid: 1344,
    x87_shadow_dirty: 1348,
    x87_native_policy: 1352,
    slice_budget: 1356,
    x64_gpr_hi: 1360,
    x64_gpr_ext_lo: 1424,
    x64_xmm_ext: 1456,
    x64_rip_hi: 1584,
    x64_previous_ip_hi: 1588,
    x64_idtr_base_hi: 1592,
    x64_gdtr_base_hi: 1596,
    x64_cr_hi: 1600,
    x64_dr_hi: 1632,
    x64_segment_base_hi: 1664,
    x64_efer: 1696,
    x64_kernel_gs_base: 1704,
    x64_star: 1712,
    x64_lstar: 1720,
    x64_cstar: 1728,
    x64_sfmask: 1736,
    x64_cs_long: 1744,
    x64_rex: 1748,
    x64_cr8: 1752,
    x64_sysenter_esp_hi: 1760,
    x64_sysenter_eip_hi: 1764,
    x64_fpu_ip_hi: 1768,
    x64_fpu_dp_hi: 1772,
    x64_pat: 1776,
    x64_tsc_aux: 1784,
    x64_page_exit: 1792,
    x64_jac_base: 1796,
    x64_jac_epoch: 1800,
    x64_page_linear: 1808,
    x64_page_chain: 1816,
    x64_code_base: 1820,
    x64_page_lazy_kind: 1824,
    x64_page_lazy_a: 1832,
    x64_page_lazy_b: 1840,
    x64_page_rep_elements: 1848,
    smm_state: 1856,
    smbase: 1860,
    x64_chain_gprs: 1864,
    ir_tlb_base: 2048,
    x64_mtrr_def_type: 2056,
    x64_mtrr_fixed: 2064,
    x64_mtrr_var: 2152,
    x64_mcg_status: 2280,
    x64_mcg_ctl: 2288,
    x64_mc_banks: 2296,
    xcr0: 2432,
    xss: 2440,
    ymm_hi: 2448,
};

/**
 * Byte ranges [start, end) of the per-core state; copied when the active core
 * changes (CPU.prototype.save_core_state/load_core_state)
 */
export const CORE_STATE_RANGES = [
    [64, 108],
    [112, 552],
    [556, 620],
    [628, 652],
    [668, 716],
    [724, 812],
    [816, 960],
    [968, 1132],
    [1152, 1280],
    [1360, 1748],
    [1752, 1788],
    [1856, 1864],
    [2056, 2424],
    [2432, 2704],
];

/** [offset, size] of the core state that INIT keeps (the rest takes its reset value) */
export const INIT_PRESERVED = [
    [816, 1],
    [824, 4],
    [832, 128],
    [1032, 1],
    [1036, 2],
    [1040, 2],
    [1044, 20],
    [1152, 128],
    [1456, 128],
    [1768, 16],
    [1860, 4],
    [2056, 368],
    [2432, 272],
];
                                                                                              source/v64/src/tpm/crb.js                                                                           0000644 0000000 0000000 00000016665 00000000000 012375  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The TPM's Command Response Buffer interface (docs/tpm.md; TCG PC Client
// Platform TPM Profile (PTP) specification, the CRB registers): five
// localities of 4 KiB from 0xFED40000, each with its locality registers;
// the control area (request, status, cancel, start, the buffer's addresses
// and sizes) and the data buffer are the same in each. A command written
// into the data buffer runs when 1 is written to start, synchronously: the
// response is in the buffer and start reads 0 again at once. No interrupts
// (the ACPI tables give none: drivers poll). The TPM2 table's control area
// address is the base's + CTRL_REQ.

import { TPM_BUFFER_SIZE } from "./libtpms.js";

export const CRB_BASE = 0xFED40000;
export const CRB_LOCALITIES = 5;
export const CRB_SIZE = CRB_LOCALITIES * 0x1000;

const LOC_STATE = 0x00;
const LOC_CTRL = 0x08;
const LOC_STS = 0x0C;
const INTF_ID = 0x30;
const INTF_ID_HIGH = 0x34;
const CTRL_EXT = 0x38;
export const CTRL_REQ = 0x40;
const CTRL_STS = 0x44;
const CTRL_CANCEL = 0x48;
const CTRL_START = 0x4C;
const INT_ENABLE = 0x50;
const INT_STS = 0x54;
const CMD_SIZE = 0x58;
const CMD_LADDR = 0x5C;
const CMD_HADDR = 0x60;
const RSP_SIZE = 0x64;
const RSP_LADDR = 0x68;
const RSP_HADDR = 0x6C;
const DATA = 0x80;

// LOC_STATE
const STATE_ESTABLISHED = 1 << 0;
const STATE_ASSIGNED = 1 << 1;
const STATE_REG_VALID = 1 << 7;
// LOC_CTRL
const CTRL_REQUEST_ACCESS = 1 << 0;
const CTRL_RELINQUISH = 1 << 1;
const CTRL_SEIZE = 1 << 2;
const CTRL_RESET_ESTABLISHMENT = 1 << 3;
// LOC_STS
const STS_GRANTED = 1 << 0;
const STS_BEEN_SEIZED = 1 << 1;
// CTRL_REQ
const REQ_CMD_READY = 1 << 0;
const REQ_GO_IDLE = 1 << 1;
// CTRL_STS
const CTRL_STS_IDLE = 1 << 1;

/**
 * The interface identifier: CRB active (type 1, version 1), five localities,
 * 64-byte transfers, CRB only (the interface selector fixed); QEMU's vendor
 * and device ID (IBM's libtpms)
 */
const INTERFACE_ID = 1 | 1 << 4 | 1 << 8 | 3 << 11 | 1 << 14 | 1 << 17 | 1 << 19;
const INTERFACE_ID_HIGH = 0x1014 | 0x0001 << 16;

/**
 * @constructor
 * @param {function(!Uint8Array, number): !Uint8Array} process a command at a locality: its response
 */
export function TpmCrb(process)
{
    this.process = process;
    this.buffer = new Uint8Array(TPM_BUFFER_SIZE);
    this.reset();
}

/** Power-on values: no locality, idle */
TpmCrb.prototype.reset = function()
{
    /** The active locality, or -1 */
    this.locality = -1;
    this.established = true;
    this.seized = 0;
    this.idle = true;
    this.cancel = 0;
    this.interrupts = 0;
    this.buffer.fill(0);
};

/**
 * A 32-bit register's value (or the data buffer's bytes) at an offset of a
 * locality's window
 * @param {number} locality
 * @param {number} offset within the window, 4-byte aligned below DATA
 * @return {number}
 */
TpmCrb.prototype.read32 = function(locality, offset)
{
    if(offset >= DATA)
    {
        const at = offset - DATA;
        const b = this.buffer;
        return (b[at] | (b[at + 1] | 0) << 8 | (b[at + 2] | 0) << 16 | (b[at + 3] | 0) << 24) >>> 0;
    }
    switch(offset)
    {
        case LOC_STATE:
            return (this.established ? STATE_ESTABLISHED : 0) | (this.locality >= 0 ? STATE_ASSIGNED | this.locality << 2 : 0) | STATE_REG_VALID;
        case LOC_STS:
            return (this.locality === locality ? STS_GRANTED : 0) | (this.seized & 1 << locality ? STS_BEEN_SEIZED : 0);
        case INTF_ID:
            return INTERFACE_ID >>> 0;
        case INTF_ID_HIGH:
            return INTERFACE_ID_HIGH >>> 0;
        case CTRL_STS:
            return this.idle ? CTRL_STS_IDLE : 0;
        case CTRL_CANCEL:
            return this.cancel;
        case INT_ENABLE:
            return this.interrupts;
        case CMD_SIZE:
        case RSP_SIZE:
            return TPM_BUFFER_SIZE;
        case CMD_LADDR:
        case RSP_LADDR:
            return CRB_BASE + DATA;
        default:
            // (CTRL_EXT, CTRL_REQ and START, which the TPM has done with at
            // once, INT_STS, the high addresses, the reserved registers)
            return 0;
    }
};

/**
 * @param {number} locality
 * @param {number} offset
 * @param {number} value
 */
TpmCrb.prototype.write32 = function(locality, offset, value)
{
    if(offset >= DATA)
    {
        for(let i = 0; i < 4 && offset - DATA + i < TPM_BUFFER_SIZE; i++)
        {
            this.buffer[offset - DATA + i] = value >>> 8 * i & 0xFF;
        }
        return;
    }
    switch(offset)
    {
        case LOC_CTRL:
            if(value & CTRL_REQUEST_ACCESS && this.locality < 0) this.locality = locality;
            if(value & CTRL_SEIZE && locality > this.locality)
            {
                if(this.locality >= 0) this.seized |= 1 << this.locality;
                this.locality = locality;
            }
            if(value & CTRL_RELINQUISH && this.locality === locality) this.locality = -1;
            // (a dynamic launch's bit: the locality 3 and 4 software's)
            if(value & CTRL_RESET_ESTABLISHMENT && locality >= 3) this.established = false;
            if(value & (CTRL_REQUEST_ACCESS | CTRL_SEIZE) && this.locality === locality) this.seized &= ~(1 << locality);
            break;
        case CTRL_REQ:
            if(value & REQ_CMD_READY) this.idle = false;
            if(value & REQ_GO_IDLE) this.idle = true;
            break;
        case CTRL_CANCEL:
            this.cancel = value & 1;
            break;
        case CTRL_START:
            if(value & 1 && this.locality === locality) this.start(locality);
            break;
        case INT_ENABLE:
            this.interrupts = value & 0x80000000;
            break;
        case CTRL_EXT:
        case INT_STS:
        case CMD_SIZE:
        case CMD_LADDR:
        case CMD_HADDR:
        case RSP_SIZE:
        case RSP_LADDR:
        case RSP_HADDR:
            break;
    }
};

/**
 * Run the command in the buffer: its length from its header (bytes 2 to
 * 5), the response into the buffer
 * @param {number} locality
 */
TpmCrb.prototype.start = function(locality)
{
    this.idle = false;
    const length = (this.buffer[2] << 24 | this.buffer[3] << 16 | this.buffer[4] << 8 | this.buffer[5]) >>> 0;
    const response = this.process(this.buffer.slice(0, Math.min(Math.max(length, 10), TPM_BUFFER_SIZE)), locality);
    this.buffer.set(response.subarray(0, TPM_BUFFER_SIZE));
};

/**
 * A byte of the window of `address` (offset from the base)
 * @param {number} offset
 * @return {number}
 */
TpmCrb.prototype.read8 = function(offset)
{
    const locality = offset >>> 12, at = offset & 0xFFF;
    return this.read32(locality, at & ~3) >>> 8 * (at & 3) & 0xFF;
};

/**
 * @param {number} offset
 * @param {number} value
 */
TpmCrb.prototype.write8 = function(offset, value)
{
    const locality = offset >>> 12, at = offset & 0xFFF;
    if(at >= DATA)
    {
        if(at - DATA < TPM_BUFFER_SIZE) this.buffer[at - DATA] = value;
        return;
    }
    // (a register written a byte at a time: the other bytes as they read)
    const shift = 8 * (at & 3);
    const old = this.read32(locality, at & ~3);
    this.write32(locality, at & ~3, old & ~(0xFF << shift) | (value & 0xFF) << shift);
};

TpmCrb.prototype.get_state = function()
{
    return [this.locality, this.established, this.seized, this.idle, this.cancel, this.interrupts, this.buffer.slice()];
};

TpmCrb.prototype.set_state = function(state)
{
    this.locality = state[0];
    this.established = state[1];
    this.seized = state[2];
    this.idle = state[3];
    this.cancel = state[4];
    this.interrupts = state[5];
    this.buffer.set(state[6]);
};
                                                                           source/v64/src/tpm/libtpms.js                                                                       0000644 0000000 0000000 00000014372 00000000000 013272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The TPM 2.0 behind the TPM device (docs/tpm.md): libtpms with OpenSSL's
// cryptography, built for WebAssembly (tools/libtpms/build.sh:
// bios/libtpms.wasm, its interface tools/libtpms/v86_tpm.c). A command in, a
// response out, synchronously; the TPM's permanent state comes in at power-on
// and goes out at every store; its volatile state on request, for snapshots.
// Entropy is the host's (crypto.getRandomValues, never Math.random).

/** The largest command or response: the CRB's data buffer (4 KiB less the registers before it) */
export const TPM_BUFFER_SIZE = 0xF80;

/** The state blobs libtpms stores: permanent, volatile, save state (TPM2_Shutdown(STATE)) */
export const BLOB_PERMANENT = 0;
export const BLOB_VOLATILE = 1;
export const BLOB_SAVE_STATE = 2;

const ERRNO_NOSYS = 52;
const ERRNO_BADF = 8;

/**
 * Compile the module (asynchronously: browsers refuse large modules
 * compiled synchronously on the page's thread)
 * @param {!ArrayBuffer|!Uint8Array} bytes
 * @return {!Promise<!WebAssembly.Module>}
 */
export function compile_libtpms(bytes)
{
    return WebAssembly.compile(bytes);
}

/**
 * A TPM: an instance of the module
 * @param {!WebAssembly.Module} module
 * @param {function(number, ?Uint8Array)} on_store the TPM stored a blob (BLOB_*; null: deleted)
 * @return {!Promise<!Libtpms>}
 */
export async function create_libtpms(module, on_store)
{
    const tpm = new Libtpms(on_store);
    const instance = await WebAssembly.instantiate(/** @type {?} */ (module), tpm.imports());
    tpm.exports = instance.exports;
    tpm.exports["_initialize"]();
    return tpm;
}

/**
 * @constructor
 * @param {function(number, ?Uint8Array)} on_store
 */
export function Libtpms(on_store)
{
    this.on_store = on_store;
    /** @type {!Object} */
    this.exports = {};
    /** The locality of the command being processed */
    this.locality = 0;
    this.powered = false;
    /** libtpms's own messages (TPM failure mode, ...) */
    this.log = "";
}

/** @return {!Uint8Array} the module's memory as it is (it may grow) */
Libtpms.prototype.memory = function()
{
    return new Uint8Array(this.exports["memory"].buffer);
};

Libtpms.prototype.imports = function()
{
    const view = () => new DataView(this.exports["memory"].buffer);
    return {
        "env": {
            "tpm_nv_store": (kind, pointer, length) =>
            {
                this.on_store(kind, pointer ? this.memory().slice(pointer, pointer + length) : null);
            },
            "tpm_locality": () => this.locality,
            "emscripten_notify_memory_growth": () => {},
            "__syscall_getdents64": () => -ERRNO_NOSYS,
        },
        "wasi_snapshot_preview1": {
            "random_get": (pointer, length) =>
            {
                // (at most 64 KiB a call: crypto.getRandomValues's limit)
                for(let done = 0; done < length; done += 0x10000)
                {
                    globalThis.crypto.getRandomValues(this.memory().subarray(pointer + done, pointer + Math.min(length, done + 0x10000)));
                }
                return 0;
            },
            "clock_time_get": (id, precision, out) =>
            {
                view().setBigUint64(out, BigInt(Date.now()) * 1000000n, true);
                return 0;
            },
            "fd_write": (fd, iovs, count, written) =>
            {
                let total = 0;
                for(let i = 0; i < count; i++)
                {
                    const pointer = view().getUint32(iovs + i * 8, true), length = view().getUint32(iovs + i * 8 + 4, true);
                    this.log += String.fromCharCode(...this.memory().subarray(pointer, pointer + length));
                    total += length;
                }
                if(this.log.length > 0x10000) this.log = this.log.slice(-0x8000);
                view().setUint32(written, total, true);
                return 0;
            },
            "fd_read": () => ERRNO_BADF,
            "fd_close": () => ERRNO_BADF,
            "fd_seek": () => ERRNO_BADF,
            "environ_sizes_get": (count, size) =>
            {
                view().setUint32(count, 0, true);
                view().setUint32(size, 0, true);
                return 0;
            },
            "environ_get": () => 0,
        },
    };
};

/**
 * Bytes into the module's memory (the TPM frees them)
 * @param {!Uint8Array} bytes
 * @return {number}
 */
Libtpms.prototype.copy_in = function(bytes)
{
    const pointer = this.exports["v86_tpm_alloc"](Math.max(bytes.length, 1));
    if(!pointer) throw new Error("tpm: out of memory");
    this.memory().set(bytes, pointer);
    return pointer;
};

/**
 * Power on: from the permanent state (null: a TPM that manufactures itself)
 * and, resuming a snapshot, the volatile state
 * @param {?Uint8Array} permanent
 * @param {?Uint8Array=} volatile
 * @return {number} 0, or libtpms's error
 */
Libtpms.prototype.power_on = function(permanent, volatile)
{
    for(const [kind, blob] of [[BLOB_PERMANENT, permanent], [BLOB_VOLATILE, volatile]])
    {
        if(blob) this.exports["v86_tpm_set_blob"](kind, this.copy_in(blob), blob.length);
    }
    const result = this.exports["v86_tpm_init"](TPM_BUFFER_SIZE) >>> 0;
    this.powered = result === 0;
    return result;
};

/** Power off: the TPM's memory released (the permanent state was stored with every change) */
Libtpms.prototype.power_off = function()
{
    if(this.powered) this.exports["v86_tpm_terminate"]();
    this.powered = false;
};

/**
 * A command
 * @param {!Uint8Array} command
 * @param {number} locality
 * @return {!Uint8Array} the response
 */
Libtpms.prototype.process = function(command, locality)
{
    this.locality = locality;
    const pointer = this.copy_in(command);
    const length = this.exports["v86_tpm_process"](pointer, command.length);
    this.exports["v86_tpm_free"](pointer);
    const response = this.exports["v86_tpm_response"]();
    return this.memory().slice(response, response + length);
};

/**
 * The volatile state of the running TPM (for a snapshot), or null
 * @return {?Uint8Array}
 */
Libtpms.prototype.volatile_state = function()
{
    if(!this.powered) return null;
    const length = this.exports["v86_tpm_get_state"](2);
    if(!length) return null;
    const pointer = this.exports["v86_tpm_state"]();
    return this.memory().slice(pointer, pointer + length);
};
                                                                                                                                                                                                                                                                      source/v64/src/tpm/plugin.js                                                                        0000644 0000000 0000000 00000015030 00000000000 013106  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // tpm: { version: "2.0", interface: "crb", state } -- a TPM 2.0 on the PC
// machines (docs/tpm.md; docs/modern-pc-devices-plan.md T1): its CRB
// interface at 0xFED40000 (src/tpm/crb.js) in front of libtpms in
// WebAssembly (src/tpm/libtpms.js), its permanent state in a store
// (src/tpm/store.js). Built into build/v86-tpm.js; from the source tree,
// src/device_plugin.js imports this file directly.
//
// A TPM not yet manufactured is made as swtpm_setup makes one by default: its
// SHA-256 PCR bank allocated, the others not. A machine reset is the TPM's
// (_TPM_Init): its volatile state goes, the firmware or the OS starts it.

import { register_device_plugin } from "../device_machine.js";
import { compile_libtpms, create_libtpms, BLOB_PERMANENT } from "./libtpms.js";
import { CRB_BASE, CRB_SIZE, TpmCrb } from "./crb.js";
import { TpmStore } from "./store.js";

/** The memory map's blocks: 128 KiB from the base */
const MAP_SIZE = 0x20000;

/**
 * A command's bytes: tag, size and code, then the rest
 * @param {number} tag
 * @param {number} code
 * @param {!Array<number>} rest
 * @return {!Uint8Array}
 */
function command(tag, code, rest)
{
    const length = 10 + rest.length;
    return new Uint8Array([tag >> 8, tag & 0xFF, length >>> 24, length >> 16 & 0xFF, length >> 8 & 0xFF, length & 0xFF,
        code >>> 24, code >> 16 & 0xFF, code >> 8 & 0xFF, code & 0xFF, ...rest]);
}

/** @param {!Uint8Array} response @return {number} its response code */
const response_code = response => (response[6] << 24 | response[7] << 16 | response[8] << 8 | response[9]) >>> 0;

const TPM_ST_NO_SESSIONS = 0x8001;
const TPM_ST_SESSIONS = 0x8002;
const TPM2_CC_STARTUP = 0x144;
const TPM2_CC_SHUTDOWN = 0x145;
const TPM2_CC_PCR_ALLOCATE = 0x12B;
const TPM_SU_CLEAR = [0, 0];
const TPM_RH_PLATFORM = [0x40, 0, 0, 0x0C];
/** The password session with an empty password: TPM_RS_PW, no nonce, no attributes, no HMAC */
const EMPTY_PASSWORD = [0, 0, 0, 9, 0x40, 0, 0, 9, 0, 0, 0, 0, 0];
/** SHA-256 for every PCR; SHA-1, SHA-384 and SHA-512 for none */
const PCR_ALLOCATION = [0, 0, 0, 4, 0, 0x04, 3, 0, 0, 0, 0, 0x0B, 3, 0xFF, 0xFF, 0xFF, 0, 0x0C, 3, 0, 0, 0, 0, 0x0D, 3, 0, 0, 0];

/**
 * A new TPM's manufacture: started, its PCR banks allocated, shut down
 * @param {!Object} tpm a powered Libtpms
 */
function allocate_pcr_banks(tpm)
{
    const steps = [
        ["Startup", command(TPM_ST_NO_SESSIONS, TPM2_CC_STARTUP, TPM_SU_CLEAR)],
        ["PCR_Allocate", command(TPM_ST_SESSIONS, TPM2_CC_PCR_ALLOCATE, [...TPM_RH_PLATFORM, ...EMPTY_PASSWORD, ...PCR_ALLOCATION])],
        ["Shutdown", command(TPM_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN, TPM_SU_CLEAR)],
    ];
    for(const [name, bytes] of steps)
    {
        const code = response_code(tpm.process(bytes, 0));
        if(code !== 0) throw new Error("tpm: the new TPM's " + name + " failed (" + code.toString(16) + ")\n" + tpm.log);
    }
}

register_device_plugin("V86TpmDevices", {
    "name": "tpm",

    /**
     * Before the machine: libtpms compiled and instantiated (asynchronous)
     * @param {!Object} options "wasm": the module's bytes
     * @return {!Promise<!Object>}
     */
    "prepare": async options =>
    {
        const module = await compile_libtpms(options["wasm"]);
        return create_libtpms(module, () => {});
    },

    /**
     * @param {!Object} handle
     * @param {!Object} options "prepared": prepare's result; "state": the store's buffer object
     */
    "create": (handle, options) =>
    {
        const tpm = options["prepared"];
        const store = new TpmStore(options["state"]);
        tpm.on_store = (kind, blob) =>
        {
            if(kind === BLOB_PERMANENT && blob) store.save(blob);
        };
        const permanent = store.load();
        if(!permanent)
        {
            const result = tpm.power_on(null);
            if(result) throw new Error("tpm: the new TPM cannot be made (" + result.toString(16) + ")\n" + tpm.log);
            allocate_pcr_banks(tpm);
            tpm.power_off();
        }
        /**
         * @param {?Uint8Array} blob
         * @param {?Uint8Array=} volatile
         */
        const power_on = (blob, volatile) =>
        {
            const result = tpm.power_on(blob, volatile);
            if(result) throw new Error("tpm: the TPM cannot be powered on (" + result.toString(16) + ")\n" + tpm.log);
        };
        // (without a blob: the one libtpms stored last, which it kept)
        power_on(permanent);

        // (each command from the guest, its response and the time it took,
        // to the device's "on_command" when a host sets one: diagnostics)
        const crb = new TpmCrb((bytes, locality) =>
        {
            const on_command = device["on_command"];
            if(!on_command) return tpm.process(bytes, locality);
            const start = performance.now();
            const response = tpm.process(bytes, locality);
            on_command(bytes, response, performance.now() - start);
            return response;
        });
        const in_crb = address => (address >>> 0) - CRB_BASE < CRB_SIZE;
        handle["mmap_register"](CRB_BASE, MAP_SIZE,
            address => in_crb(address) ? crb.read8((address >>> 0) - CRB_BASE) : 0xFF,
            (address, value) => { if(in_crb(address)) crb.write8((address >>> 0) - CRB_BASE, value); },
            address => in_crb(address) ? crb.read32((address >>> 0) - CRB_BASE >>> 12, (address >>> 0) - CRB_BASE & 0xFFF) | 0 : -1,
            (address, value) => { if(in_crb(address)) crb.write32((address >>> 0) - CRB_BASE >>> 12, (address >>> 0) - CRB_BASE & 0xFFF, value >>> 0); });

        const device = {
            // (the platform's reset is the TPM's _TPM_Init)
            "reset": () =>
            {
                crb.reset();
                tpm.power_off();
                power_on(null);
            },
            "destroy": () => tpm.power_off(),
            // the CRB and the TPM's volatile state; the store's part of a
            // snapshot is the machine's (src/cpu.js, as a disk's)
            "get_state": () => [crb.get_state(), tpm.volatile_state()],
            "set_state": state =>
            {
                crb.set_state(state[0]);
                tpm.power_off();
                power_on(store.load(), state[1]);
            },
            /** libtpms's own messages */
            "log": () => tpm.log,
            /** A command from the host (tests), at a locality */
            "process": (bytes, locality) => tpm.process(bytes, locality || 0),
            /** @type {?function(!Uint8Array, !Uint8Array, number)} */
            "on_command": null,
        };
        return device;
    },
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/tpm/store.js                                                                         0000644 0000000 0000000 00000010577 00000000000 012757  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The TPM's permanent state in a store of its own (docs/tpm.md): a buffer
// object (src/buffer.js's, or a disk written back: tpm.state with
// disk_option "read_write"), as the UEFI variables have theirs. Two slots
// of STORE_SIZE / 2 bytes each, written alternately: a header (magic,
// format, sequence number, length, CRC-32 of the blob) and the blob. The
// newer valid slot is the state; a store of zeros is a TPM not yet
// manufactured. Anything else is refused, never cleared: a TPM's state
// holds keys (BitLocker's) that a new TPM would not have.

/** The store's size: two slots of 256 KiB (libtpms's permanent state is under 140 KiB) */
export const STORE_SIZE = 512 * 1024;
const SLOT_SIZE = STORE_SIZE / 2;
const HEADER_SIZE = 64;
const MAGIC = "V86TPMS1";
const FORMAT = 1;

const CRC_TABLE = (() =>
{
    const table = new Int32Array(256);
    for(let n = 0; n < 256; n++)
    {
        let c = n;
        for(let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1;
        table[n] = c;
    }
    return table;
})();

/**
 * @param {!Uint8Array} bytes
 * @return {number}
 */
function crc32(bytes)
{
    let c = -1;
    for(let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xFF] ^ c >>> 8;
    return (c ^ -1) >>> 0;
}

/**
 * @constructor
 * @param {!Object} buffer get, set (synchronous), byteLength
 */
export function TpmStore(buffer)
{
    if(buffer.byteLength < STORE_SIZE)
    {
        throw new Error("tpm.state: the store has " + buffer.byteLength + " bytes, it needs " + STORE_SIZE);
    }
    this.buffer = buffer;
    /** The sequence number of the slot read or written last */
    this.sequence = 0;
    this.slot = 1;
}

/**
 * @param {number} offset
 * @param {number} length
 * @return {!Uint8Array}
 */
TpmStore.prototype.read = function(offset, length)
{
    let result = null;
    this.buffer.get(offset, length, data => { result = data; });
    if(!result) throw new Error("tpm.state: the store cannot be read");
    return result;
};

/**
 * The permanent state: null for a store of zeros (a TPM to manufacture)
 * @return {?Uint8Array}
 */
TpmStore.prototype.load = function()
{
    let best = null;
    for(let slot = 0; slot < 2; slot++)
    {
        const header = this.read(slot * SLOT_SIZE, HEADER_SIZE);
        if(String.fromCharCode(...header.subarray(0, 8)) !== MAGIC) continue;
        const view = new DataView(header.buffer, header.byteOffset, header.length);
        const format = view.getUint32(8, true), sequence = view.getUint32(12, true), length = view.getUint32(16, true), crc = view.getUint32(20, true);
        if(format !== FORMAT || length > SLOT_SIZE - HEADER_SIZE) continue;
        const blob = this.read(slot * SLOT_SIZE + HEADER_SIZE, length);
        if(crc32(blob) !== crc) continue;
        if(!best || (sequence - best.sequence | 0) > 0)
        {
            best = { slot, sequence, blob };
        }
    }
    if(best)
    {
        this.slot = best.slot;
        this.sequence = best.sequence;
        return best.blob;
    }
    // (no whole slot: a new TPM only where the store is all zeros)
    if(this.read(0, STORE_SIZE).some(byte => byte !== 0))
    {
        throw new Error("tpm.state: the TPM's state is damaged (neither of its copies is whole); " +
            "it is not replaced by a new TPM: clear it explicitly to start over");
    }
    this.slot = 1;
    this.sequence = 0;
    return null;
};

/**
 * The permanent state, into the slot not holding the current one: the blob
 * first, then its header
 * @param {!Uint8Array} blob
 */
TpmStore.prototype.save = function(blob)
{
    if(blob.length > SLOT_SIZE - HEADER_SIZE)
    {
        throw new Error("tpm.state: the TPM's state (" + blob.length + " bytes) is larger than a slot of the store");
    }
    const slot = this.slot ^ 1;
    const sequence = this.sequence + 1 >>> 0;
    const header = new Uint8Array(HEADER_SIZE);
    for(let i = 0; i < 8; i++) header[i] = MAGIC.charCodeAt(i);
    const view = new DataView(header.buffer);
    view.setUint32(8, FORMAT, true);
    view.setUint32(12, sequence, true);
    view.setUint32(16, blob.length, true);
    view.setUint32(20, crc32(blob), true);
    const failed = error => { if(error) throw new Error("tpm.state: the store cannot be written (" + error.message + ")"); };
    this.buffer.set(slot * SLOT_SIZE + HEADER_SIZE, blob, failed);
    this.buffer.set(slot * SLOT_SIZE, header, failed);
    this.slot = slot;
    this.sequence = sequence;
};
                                                                                                                                 source/v64/src/uart.js                                                                              0000644 0000000 0000000 00000030065 00000000000 011770  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_SERIAL } from "./const.js";
import { h } from "./lib.js";
import { dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

/*
 * Serial ports
 * http://wiki.osdev.org/UART
 * https://github.com/s-macke/jor1k/blob/master/js/worker/dev/uart.js
 * https://www.freebsd.org/doc/en/articles/serial-uart/
 */

const DLAB = 0x80;

const UART_IER_MSI  = 0x08; /* Modem Status Changed int. */
const UART_IER_THRI = 0x02; /* Enable Transmitter holding register int. */
const UART_IER_RDI = 0x01; /* Enable receiver data interrupt */

const UART_IIR_MSI = 0x00; /* Modem status interrupt (Low priority) */
const UART_IIR_NO_INT = 0x01;
const UART_IIR_THRI = 0x02; /* Transmitter holding register empty */
const UART_IIR_RDI = 0x04; /* Receiver data interrupt */
const UART_IIR_RLSI = 0x06; /* Receiver line status interrupt (High p.) */
const UART_IIR_CTI = 0x0c; /* Character timeout */

// Modem control register
const UART_MCR_LOOPBACK = 0x10;
const UART_MCR_RTS = 0x2;
const UART_MCR_DTR = 0x1;

const UART_LSR_DATA_READY        = 0x1;  // data available
const UART_LSR_TX_EMPTY        = 0x20; // TX (THR) buffer is empty
const UART_LSR_TRANSMITTER_EMPTY = 0x40; // TX empty and line is idle

// Modem status register
const UART_MSR_DCD = 0x7; // Data Carrier Detect
const UART_MSR_RI = 0x6; // Ring Indicator
const UART_MSR_DSR = 0x5; // Data Set Ready
const UART_MSR_CTS = 0x4; // Clear To Send
// Delta bits
const UART_MSR_DDCD = 0x3; // Delta DCD
const UART_MSR_TERI = 0x2; // Trailing Edge RI
const UART_MSR_DDSR = 0x1; // Delta DSR
const UART_MSR_DCTS = 0x0; // Delta CTS


/**
 * @constructor
 * @param {CPU} cpu
 * @param {number} port
 * @param {BusConnector} bus
 */
export function UART(cpu, port, bus)
{
    /** @const @type {BusConnector} */
    this.bus = bus;

    /** @const @type {CPU} */
    this.cpu = cpu;

    this.ints = 1 << UART_IIR_THRI;

    this.baud_rate = 0;

    this.line_control = 0;

    // line status register
    this.lsr = UART_LSR_TRANSMITTER_EMPTY | UART_LSR_TX_EMPTY;

    this.fifo_control = 0;

    // interrupts enable
    this.ier = 0;

    // interrupt identification register
    this.iir = UART_IIR_NO_INT;

    this.modem_control = 0;
    this.modem_status = 0;

    this.scratch_register = 0;

    this.irq = 0;

    this.input = [];

    this.current_line = "";

    switch(port)
    {
        case 0x3F8:
            this.com = 0;
            this.irq = 4;
            break;
        case 0x2F8:
            this.com = 1;
            this.irq = 3;
            break;
        case 0x3E8:
            this.com = 2;
            this.irq = 4;
            break;
        case 0x2E8:
            this.com = 3;
            this.irq = 3;
            break;
        default:
            dbg_log("Invalid serial port: " + h(port), LOG_SERIAL);
            this.com = 0;
            this.irq = 4;
    }

    this.bus.register("serial" + this.com + "-input", function(data)
    {
        this.data_received(data);
    }, this);

    // Set individual modem status bits

    this.bus.register("serial" + this.com + "-carrier-detect-input", function(data)
    {
        this.set_modem_status_bit(UART_MSR_DCD, data);
    }, this);

    this.bus.register("serial" + this.com + "-ring-indicator-input", function(data)
    {
        this.set_modem_status_bit(UART_MSR_RI, data);
    }, this);

    this.bus.register("serial" + this.com + "-data-set-ready-input", function(data)
    {
        this.set_modem_status_bit(UART_MSR_DSR, data);
    }, this);

    this.bus.register("serial" + this.com + "-clear-to-send-input", function(data)
    {
        this.set_modem_status_bit(UART_MSR_CTS, data);
    }, this);

    var io = cpu.io;

    io.register_write(port, this, function(out_byte)
    {
        this.write_data(out_byte);
    }, function(out_word)
    {
        this.write_data(out_word & 0xFF);
        this.write_data(out_word >> 8);
    });

    io.register_write(port | 1, this, function(out_byte)
    {
        if(this.line_control & DLAB)
        {
            this.baud_rate = this.baud_rate & 0xFF | out_byte << 8;
            dbg_log("baud rate: " + h(this.baud_rate), LOG_SERIAL);
        }
        else
        {
            if((this.ier & UART_IIR_THRI) === 0 && (out_byte & UART_IIR_THRI))
            {
                // re-throw THRI if it was masked
                this.ThrowInterrupt(UART_IIR_THRI);
            }

            this.ier = out_byte & 0xF;
            dbg_log("interrupt enable: " + h(out_byte), LOG_SERIAL);
            this.CheckInterrupt();
        }
    });

    io.register_read(port, this, function()
    {
        if(this.line_control & DLAB)
        {
            return this.baud_rate & 0xFF;
        }
        else
        {
            let data = 0;

            if(this.input.length === 0)
            {
                dbg_log("Read input empty", LOG_SERIAL);
            }
            else
            {
                data = this.input.shift();
                dbg_log("Read input: " + h(data), LOG_SERIAL);
            }

            if(this.input.length === 0)
            {
                this.lsr &= ~UART_LSR_DATA_READY;
                this.ClearInterrupt(UART_IIR_CTI);
                this.ClearInterrupt(UART_IIR_RDI);
            }

            return data;
        }
    });

    io.register_read(port | 1, this, function()
    {
        if(this.line_control & DLAB)
        {
            return this.baud_rate >> 8;
        }
        else
        {
            return this.ier & 0xF;
        }
    });

    io.register_read(port | 2, this, function()
    {
        var ret = this.iir & 0xF;
        dbg_log("read interrupt identification: " + h(this.iir), LOG_SERIAL);

        if(this.iir === UART_IIR_THRI) {
            this.ClearInterrupt(UART_IIR_THRI);
        }

        if(this.fifo_control & 1) ret |= 0xC0;

        return ret;
    });
    io.register_write(port | 2, this, function(out_byte)
    {
        dbg_log("fifo control: " + h(out_byte), LOG_SERIAL);
        this.fifo_control = out_byte;
    });

    io.register_read(port | 3, this, function()
    {
        dbg_log("read line control: " + h(this.line_control), LOG_SERIAL);
        return this.line_control;
    });
    io.register_write(port | 3, this, function(out_byte)
    {
        dbg_log("line control: " + h(out_byte), LOG_SERIAL);
        this.line_control = out_byte;
    });


    io.register_read(port | 4, this, function()
    {
        return this.modem_control;
    });
    io.register_write(port | 4, this, function(out_byte)
    {
        dbg_log("modem control: " + h(out_byte), LOG_SERIAL);
        const bits_changed = this.modem_control ^ out_byte;
        this.modem_control = out_byte;
        if(bits_changed & UART_MCR_DTR)
        {
            this.bus.send("serial" + this.com + "-data-terminal-ready-output", !!(out_byte & UART_MCR_DTR));
        }
        if(bits_changed & UART_MCR_RTS)
        {
            this.bus.send("serial" + this.com + "-request-to-send-output", !!(out_byte & UART_MCR_RTS));
        }
    });

    io.register_read(port | 5, this, function()
    {
        dbg_log("read line status: " + h(this.lsr), LOG_SERIAL);
        return this.lsr;
    });
    io.register_write(port | 5, this, function(out_byte)
    {
        dbg_log("Factory test write", LOG_SERIAL);
    });

    io.register_read(port | 6, this, function()
    {
        dbg_log("read modem status: " + h(this.modem_status), LOG_SERIAL);
        const result = this.modem_status;
        // clear MSR delta bits and interrupt flag
        this.modem_status &= 0xF0;
        this.ClearInterrupt(UART_IIR_MSI);
        return result;
    });

    io.register_read(port | 7, this, function()
    {
        return this.scratch_register;
    });
    io.register_write(port | 7, this, function(out_byte)
    {
        this.scratch_register = out_byte;
    });
}

UART.prototype.get_state = function()
{
    var state = [];

    state[0] = this.ints;
    state[1] = this.baud_rate;
    state[2] = this.line_control;
    state[3] = this.lsr;
    state[4] = this.fifo_control;
    state[5] = this.ier;
    state[6] = this.iir;
    state[7] = this.modem_control;
    state[8] = this.modem_status;
    state[9] = this.scratch_register;
    state[10] = this.irq;
    // the bytes the guest has not read yet (a restore must not keep the
    // queue of the timeline it discards: Linux's 8250 driver sizes the FIFO
    // by looping 256 bytes back, which a stale queue hands to the console)
    state[11] = this.input.slice();

    return state;
};

UART.prototype.set_state = function(state)
{
    this.ints = state[0];
    this.baud_rate = state[1];
    this.line_control = state[2];
    this.lsr = state[3];
    this.fifo_control = state[4];
    this.ier = state[5];
    this.iir = state[6];
    this.modem_control = state[7];
    this.modem_status = state[8];
    this.scratch_register = state[9];
    this.irq = state[10];
    this.input = state[11] ? Array.from(state[11]) : [];
};

UART.prototype.CheckInterrupt = function()
{
    if((this.ints & (1 << UART_IIR_CTI)) && (this.ier & UART_IER_RDI))
    {
        this.iir = UART_IIR_CTI;
        this.cpu.device_raise_irq(this.irq);
    }
    else if((this.ints & (1 << UART_IIR_RDI)) && (this.ier & UART_IER_RDI))
    {
        this.iir = UART_IIR_RDI;
        this.cpu.device_raise_irq(this.irq);
    }
    else if((this.ints & (1 << UART_IIR_THRI)) && (this.ier & UART_IER_THRI))
    {
        this.iir = UART_IIR_THRI;
        this.cpu.device_raise_irq(this.irq);
    }
    else if((this.ints & (1 << UART_IIR_MSI)) && (this.ier & UART_IER_MSI))
    {
        this.iir = UART_IIR_MSI;
        this.cpu.device_raise_irq(this.irq);
    }
    else
    {
        this.iir = UART_IIR_NO_INT;
        this.cpu.device_lower_irq(this.irq);
    }
};

UART.prototype.ThrowInterrupt = function(line)
{
    this.ints |= (1 << line);
    this.CheckInterrupt();
};

UART.prototype.ClearInterrupt = function(line)
{
    this.ints &= ~(1 << line);
    this.CheckInterrupt();
};

/**
 * @param {number} data
 */
UART.prototype.data_received = function(data)
{
    dbg_log("input: " + h(data), LOG_SERIAL);
    this.input.push(data);

    this.lsr |= UART_LSR_DATA_READY;

    if(this.fifo_control & 1)
    {
        this.ThrowInterrupt(UART_IIR_CTI);
    }
    else
    {
        this.ThrowInterrupt(UART_IIR_RDI);
    }
};

UART.prototype.write_data = function(out_byte)
{
    if(this.line_control & DLAB)
    {
        this.baud_rate = this.baud_rate & ~0xFF | out_byte;
        return;
    }

    dbg_log("data: " + h(out_byte), LOG_SERIAL);

    this.ThrowInterrupt(UART_IIR_THRI);

    if(this.modem_control & UART_MCR_LOOPBACK) {
        this.data_received(out_byte);
    } else {
        this.bus.send("serial" + this.com + "-output-byte", out_byte);
    }

    if(DEBUG)
    {
        var char = String.fromCharCode(out_byte);
        this.current_line += char;

        if(char === "\n")
        {
            const line = this.current_line.trimRight().replace(/[\x00-\x08\x0b-\x1f\x7f\x80-\xff]/g, "");
            dbg_log("SERIAL: " + line);
            this.current_line = "";
        }
    }
};

/**
 * Set or clear bit "msr_bit" in the Modem Status Register (MSR).
 *
 * The upper nibble of the MSR reflects the current status of the 4
 * control lines (CTS/DSR/RI/DCD), the lower nibble (the delta bits)
 * indicates which of of these have changed since the last time the
 * MSR was read.
 *
 * If any delta bit is set at the end of this operation and interrupts
 * are enabled, raise a Modem Status Register interrupt.
 *
 * The MSR is a read-only register for the PC, its upper nibble is
 * controlled by the Modem, and its lower nibble by the UART. The UART
 * clears all delta bits (and lowers the interrupt) after the MSR has
 * been read by the PC.
 *
 * @param {number} msr_bit
 * @param {boolean} set_bit
 */
UART.prototype.set_modem_status_bit = function(msr_bit, set_bit)
{
    const new_modem_status = set_bit ?
        this.modem_status | (1 << msr_bit) :
        this.modem_status & ~(1 << msr_bit);
    const new_delta_bits = (this.modem_status ^ new_modem_status) >> 4;
    this.modem_status = new_modem_status | new_delta_bits;
    if(this.modem_status & 0x0F)
    {
        this.ThrowInterrupt(UART_IIR_MSI);
    }
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/src/usb/ehci.js                                                                          0000644 0000000 0000000 00000101076 00000000000 012517  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // An EHCI USB 2.0 host controller (Enhanced Host Controller Interface 1.0):
// ICH9's EHCI1 (8086:293A, function 7 of the USB device) with its three
// UHCI companions (8086:2934, 2935, 2936, functions 0-2, uhci.js), as
// QEMU's ich9-usb-ehci1 with ich9-usb-uhci1..3 (masterbus, firstport 0, 2,
// 4). Windows binds usbport.inf by the class (PCI\CC_0C0320), Linux
// ehci-pci. Six root ports: a high-speed device stays on the EHCI, a full-
// or low-speed one goes to the companion of its port (CONFIGFLAG 0, or the
// driver's Port Owner after a reset that left the port disabled). BAR0 is
// memory (the capability and operational registers), the interrupt INTD.
//
// While it runs, the controller goes through micro-frames of 125 µs of the
// machine clock (FRINDEX), caught up a millisecond at a time: the periodic
// schedule's frame list entry for each micro-frame (interrupt queue heads by
// their S-mask; isochronous descriptors are skipped: no device has them),
// then the asynchronous schedule's ring of queue heads (control and bulk),
// pass after pass while transactions happen, up to a budget of bytes; a
// pass without any ends it (the reclamation). Interrupt on Async Advance is
// at once: nothing of the schedule is kept between passes. No split
// transactions (no hubs), no 64-bit buffer pointers above the guest's
// memory, no isochronous transfers.

import { LOG_PCI } from "../const.js";
import { h } from "../lib.js";
import { dbg_log } from "../log.js";
import { PID_IN, PID_OUT, PID_SETUP, SPEED_FULL, SPEED_HIGH, SPEED_LOW, USB_NAK, USB_STALL } from "./usb.js";

const MMIO_SIZE = 0x1000;
/** The operational registers' offset (CAPLENGTH) */
const OP = 0x20;
export const EHCI_PORTS = 6;
const PORTS_PER_COMPANION = 2, COMPANIONS = 3;

const PCI_VENDOR = 0x8086, PCI_DEVICE = 0x293A, PCI_REVISION = 0x03;
const PCI_SUBSYSTEM_VENDOR = 0x1AF4, PCI_SUBSYSTEM = 0x1100;
// the legacy support capability (USBLEGSUP, USBLEGCTLSTS): EECP
const LEGSUP = 0x68;
const LEGSUP_BIOS_OWNED = 1 << 16, LEGSUP_OS_OWNED = 1 << 24;

// capability registers: N_PORTS, N_PCC, N_CC (no port power control); 64-bit
// addressing, the isochronous threshold (a whole frame), EECP
const HCSPARAMS = EHCI_PORTS | PORTS_PER_COMPANION << 8 | COMPANIONS << 12;
const HCCPARAMS = 1 | 0x80 | LEGSUP << 8;

// operational registers (from OP)
const R_USBCMD = 0x00, R_USBSTS = 0x04, R_USBINTR = 0x08, R_FRINDEX = 0x0C, R_CTRLDSSEGMENT = 0x10,
    R_PERIODICLISTBASE = 0x14, R_ASYNCLISTADDR = 0x18, R_CONFIGFLAG = 0x40, R_PORTSC = 0x44;

const CMD_RS = 1 << 0, CMD_HCRESET = 1 << 1, CMD_PSE = 1 << 4, CMD_ASE = 1 << 5, CMD_IAAD = 1 << 6,
    CMD_ITC_DEFAULT = 8 << 16, CMD_MASK = 0x00FF0B7F;
const STS_USBINT = 1 << 0, STS_USBERRINT = 1 << 1, STS_PCD = 1 << 2, STS_FLR = 1 << 3, STS_HSE = 1 << 4, STS_IAA = 1 << 5,
    STS_HALTED = 1 << 12, STS_PSS = 1 << 14, STS_ASS = 1 << 15;
const STS_WRITE_CLEAR = 0x3F;

const PORT_CCS = 1 << 0, PORT_CSC = 1 << 1, PORT_PED = 1 << 2, PORT_PEDC = 1 << 3, PORT_OCC = 1 << 5, PORT_FPR = 1 << 6,
    PORT_SUSPEND = 1 << 7, PORT_PR = 1 << 8, PORT_LS_J = 2 << 10, PORT_LS_K = 1 << 10, PORT_PP = 1 << 12, PORT_PO = 1 << 13;
const PORT_WRITE_CLEAR = PORT_CSC | PORT_PEDC | PORT_OCC;
/** what the driver sets as it likes: resume, suspend, the indicators, test control, wake enables */
const PORT_DRIVER = PORT_FPR | PORT_SUSPEND | 0x7FC000;

// link pointers: T, the type (0 iTD, 1 QH, 2 siTD, 3 FSTN)
const LINK_TERMINATE = 1, TYPE_QH = 1;
// a queue head's endpoint speed (0 full, 1 low: split transactions, behind a hub)
const EPS_HIGH = 2;
// a qTD's token
const TOKEN_ACTIVE = 1 << 7, TOKEN_HALTED = 1 << 6, TOKEN_BUFFER_ERROR = 1 << 5, TOKEN_BABBLE = 1 << 4,
    TOKEN_XACTERR = 1 << 3, TOKEN_PING = 1 << 0, TOKEN_IOC = 1 << 15, TOKEN_DT = 1 << 31;
const PID_CODES = [PID_OUT, PID_IN, PID_SETUP];

/** Per millisecond: the asynchronous schedule's bytes, its queue heads */
const ASYNC_BYTES = 256 * 1024;
const ASYNC_QHS = 512;
/** Per micro-frame: the periodic schedule's nodes */
const PERIODIC_NODES = 128;
/** Milliseconds caught up per timer round, and the most behind before skipping */
const MS_PER_ROUND = 4;
const MS_BEHIND = 100;

/**
 * @constructor
 * @param {!Object} machine the EHCI function's machine (src/device_machine.js)
 * @param {!Array<!Object>} companions the UHCI controllers of ports 0-1, 2-3, 4-5
 */
export function EHCIController(machine, companions)
{
    this.machine = machine;
    this.companions = companions;
    this.name = "ehci";
    /** @type {!Array<?Object>} the device in each root port, whichever controller has it */
    this.devices = new Array(EHCI_PORTS).fill(null);
    this.irq_level = false;
    this.bar0 = 0;
    this.mmio = -1;
    /** the asynchronous schedule's bytes left in this millisecond; the interrupts the transfers raise */
    this.async_bytes = 0;
    this.interrupts = 0;
    this.reset();

    machine.register_pci({
        pci_space: create_pci_space(),
        pci_bars: [{ size: MMIO_SIZE, on_move: base => { this.bar0 = base; this.update_decode(); } }],
        on_command_change: () => { this.update_decode(); this.update_irq(); },
        on_config_restore: () => this.update_decode(),
        on_upstream_change: () => this.update_decode(),
        on_config_write: (offset, size) => this.config_written(offset, size),
    });
    machine.add_timer(now => this.timer(now));
}

/** @return {!Array<number>} */
function create_pci_space()
{
    const space = new Array(256).fill(0);
    const put16 = (offset, value) => { space[offset] = value & 0xFF; space[offset + 1] = value >> 8 & 0xFF; };
    put16(0x00, PCI_VENDOR);
    put16(0x02, PCI_DEVICE);
    put16(0x06, 0x0290);
    space[0x08] = PCI_REVISION;
    // class 0C/03/20: an EHCI USB controller
    space[0x09] = 0x20;
    space[0x0A] = 0x03;
    space[0x0B] = 0x0C;
    put16(0x2C, PCI_SUBSYSTEM_VENDOR);
    put16(0x2E, PCI_SUBSYSTEM);
    space[0x3D] = 4;
    // SBRN: USB 2.0; FLADJ; no port wake capability
    space[0x60] = 0x20;
    space[0x61] = 0x20;
    // USBLEGSUP (capability 1, the last), USBLEGCTLSTS
    space[LEGSUP] = 0x01;
    return space;
}

/**
 * The legacy support capability: the driver taking the controller from the
 * firmware (OS owned) gets it at once: v86 has no USB legacy SMI
 * @param {number} offset
 * @param {number} size
 */
EHCIController.prototype.config_written = function(offset, size)
{
    if(offset + size <= LEGSUP || offset >= LEGSUP + 8) return;
    const space = this.machine.pci_config();
    let legsup = (space[LEGSUP] | space[LEGSUP + 1] << 8 | space[LEGSUP + 2] << 16 | space[LEGSUP + 3] << 24) >>> 0;
    legsup = (legsup & (LEGSUP_BIOS_OWNED | LEGSUP_OS_OWNED) | 0x01) >>> 0;
    if(legsup & LEGSUP_OS_OWNED) legsup &= ~LEGSUP_BIOS_OWNED;
    space.set([legsup & 0xFF, legsup >> 8 & 0xFF, legsup >> 16 & 0xFF, legsup >>> 24], LEGSUP);
};

EHCIController.prototype.update_decode = function()
{
    const base = this.bar0 && this.machine.memory_decoded(this.bar0, MMIO_SIZE) ? this.bar0 : -1;
    if(base === this.mmio) return;
    if(this.mmio !== -1) this.machine.mmap_unregister_range(this.mmio, MMIO_SIZE);
    this.mmio = base;
    if(base !== -1)
    {
        this.machine.mmap_register_range(base, MMIO_SIZE,
            address => this.read(address - this.mmio, 1),
            (address, value) => this.write(address - this.mmio, 1, value),
            address => this.read(address - this.mmio, 4),
            (address, value) => this.write(address - this.mmio, 4, value));
    }
};

/** Everything to its reset value (power on, HCRESET): every port the companions' */
EHCIController.prototype.reset = function()
{
    this.cmd = CMD_ITC_DEFAULT;
    this.status = STS_HALTED;
    this.intr = 0;
    this.frindex = 0;
    this.segment = 0;
    this.periodic_base = 0;
    this.async_address = 0;
    this.configflag = 0;
    this.portsc = new Array(EHCI_PORTS).fill(PORT_PP | PORT_PO);
    /** the machine time of the next millisecond's work (while running) */
    this.next_ms = 0;
    for(let port = 0; port < EHCI_PORTS; port++) this.route(port);
    this.update_irq();
};

/** A machine reset (PCIRST#): the companions too */
EHCIController.prototype.reset_all = function()
{
    for(const companion of this.companions) companion.reset();
    this.reset();
    this.update_decode();
};

/**
 * @param {number} port
 * @return {boolean} whether the EHCI has the port (otherwise its companion)
 */
EHCIController.prototype.owns = function(port)
{
    return this.configflag !== 0 && !(this.portsc[port] & PORT_PO);
};

/**
 * Put the port's device where the port's owner sees it: the companion's
 * port, or the EHCI's (each side sees a device arrive and leave)
 * @param {number} port
 */
EHCIController.prototype.route = function(port)
{
    const device = this.devices[port];
    const companion = this.companions[port / PORTS_PER_COMPANION | 0], companion_port = port % PORTS_PER_COMPANION;
    if(!this.owns(port))
    {
        if(this.portsc[port] & PORT_CCS) this.disconnected(port);
        // (also a device that left while the snapshot had it there)
        if(companion.devices[companion_port] !== device || !device && companion.port_connected(companion_port))
        {
            if(device) device.set_speed(device.speeds.includes(SPEED_FULL) ? SPEED_FULL : SPEED_LOW);
            companion.attach(companion_port, device);
        }
        return;
    }
    if(companion.devices[companion_port]) companion.attach(companion_port, null);
    if(device && !(this.portsc[port] & PORT_CCS))
    {
        this.portsc[port] = this.portsc[port] & ~(PORT_PED | PORT_SUSPEND) | PORT_CCS | PORT_CSC;
        this.port_change();
    }
    else if(!device && this.portsc[port] & PORT_CCS)
    {
        this.disconnected(port);
    }
};

/** @param {number} port the EHCI's port lost its device */
EHCIController.prototype.disconnected = function(port)
{
    const enabled = this.portsc[port] & PORT_PED;
    this.portsc[port] = this.portsc[port] & ~(PORT_CCS | PORT_PED | PORT_SUSPEND) | PORT_CSC | (enabled ? PORT_PEDC : 0);
    this.port_change();
};

EHCIController.prototype.port_change = function()
{
    this.status |= STS_PCD;
    this.update_irq();
};

/**
 * Plug a device into a root port (or take it out: null). One that leaves a
 * companion's port gives the port back to the EHCI (EHCI 4.2.2).
 * @param {number} port
 * @param {?Object} device
 */
EHCIController.prototype.attach = function(port, device)
{
    const owned_by_companion = !this.owns(port) && this.devices[port];
    this.devices[port] = device;
    if(device) device.reset();
    this.route(port);
    if(!device && owned_by_companion && this.configflag)
    {
        this.portsc[port] &= ~PORT_PO;
        this.route(port);
    }
};

/** After a snapshot's registers and devices: the companions' ports have the devices their owners had */
EHCIController.prototype.restore_routing = function()
{
    for(let port = 0; port < EHCI_PORTS; port++)
    {
        this.companions[port / PORTS_PER_COMPANION | 0].devices[port % PORTS_PER_COMPANION] = this.owns(port) ? null : this.devices[port];
    }
};

/**
 * @param {number} port
 * @return {boolean} whether the port has a device connected, on whichever side
 */
EHCIController.prototype.port_connected = function(port)
{
    const companion = this.companions[port / PORTS_PER_COMPANION | 0];
    return !!(this.portsc[port] & PORT_CCS) || companion.port_connected(port % PORTS_PER_COMPANION);
};

// registers

/**
 * A register's value
 * @param {number} offset its first byte
 * @return {number}
 */
EHCIController.prototype.register = function(offset)
{
    switch(offset)
    {
        // CAPLENGTH, HCIVERSION
        case 0x00: return OP | 0x0100 << 16;
        case 0x04: return HCSPARAMS;
        case 0x08: return HCCPARAMS;
        case OP + R_USBCMD: return this.cmd;
        case OP + R_USBSTS: return this.status;
        case OP + R_USBINTR: return this.intr;
        case OP + R_FRINDEX: return this.frindex;
        case OP + R_CTRLDSSEGMENT: return this.segment;
        case OP + R_PERIODICLISTBASE: return this.periodic_base;
        case OP + R_ASYNCLISTADDR: return this.async_address;
        case OP + R_CONFIGFLAG: return this.configflag;
    }
    if(offset >= OP + R_PORTSC && offset < OP + R_PORTSC + 4 * EHCI_PORTS)
    {
        const port = offset - OP - R_PORTSC >> 2;
        let value = this.portsc[port];
        // the line status of a connected, not enabled port: J for a
        // full-speed device, K for a low-speed one
        if(value & PORT_CCS && !(value & PORT_PED) && this.devices[port])
        {
            value |= this.devices[port].speeds.includes(SPEED_FULL) || this.devices[port].speeds.includes(SPEED_HIGH) ? PORT_LS_J : PORT_LS_K;
        }
        return value;
    }
    return 0;
};

/**
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
EHCIController.prototype.read = function(offset, size)
{
    const value = this.register(offset & ~3);
    if(size === 4) return value >>> 0;
    return value >>> ((offset & 3) << 3) & (size === 1 ? 0xFF : 0xFFFF);
};

/**
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
EHCIController.prototype.write = function(offset, size, value)
{
    const shift = (offset & 3) << 3;
    const mask = (size === 4 ? -1 : (size === 1 ? 0xFF : 0xFFFF) << shift) >>> 0;
    this.write_register(offset & ~3, value << shift >>> 0, mask);
};

/**
 * @param {number} offset
 * @param {number} bits
 * @param {number} mask
 */
EHCIController.prototype.write_register = function(offset, bits, mask)
{
    const merge = old => (old & ~mask | bits & mask) >>> 0;
    switch(offset)
    {
        case OP + R_USBCMD:
        {
            const value = merge(this.cmd) & CMD_MASK;
            if(value & CMD_HCRESET)
            {
                dbg_log("ehci: host controller reset", LOG_PCI);
                this.reset();
                return;
            }
            const was_running = this.cmd & CMD_RS;
            // (the frame list's size stays 1024)
            this.cmd = value & ~(3 << 2);
            if(value & CMD_RS && !was_running)
            {
                this.status &= ~STS_HALTED;
                this.next_ms = this.machine.now();
            }
            else if(!(value & CMD_RS) && was_running)
            {
                this.status |= STS_HALTED;
            }
            this.status = this.status & ~(STS_PSS | STS_ASS) | (this.cmd & CMD_PSE ? STS_PSS : 0) | (this.cmd & CMD_ASE ? STS_ASS : 0);
            if(this.cmd & CMD_IAAD)
            {
                // Interrupt on Async Advance: no queue head of the
                // schedule is kept between passes, so the driver may free
                // the one it took out at once
                this.cmd &= ~CMD_IAAD;
                this.status |= STS_IAA;
            }
            this.update_irq();
            break;
        }
        case OP + R_USBSTS:
            this.status &= ~(bits & mask & STS_WRITE_CLEAR);
            this.update_irq();
            break;
        case OP + R_USBINTR:
            this.intr = merge(this.intr) & 0x3F;
            this.update_irq();
            break;
        case OP + R_FRINDEX:
            // (only while halted)
            if(this.status & STS_HALTED) this.frindex = merge(this.frindex) & 0x3FFF;
            break;
        case OP + R_CTRLDSSEGMENT:
            this.segment = merge(this.segment);
            break;
        case OP + R_PERIODICLISTBASE:
            this.periodic_base = merge(this.periodic_base) & ~0xFFF;
            break;
        case OP + R_ASYNCLISTADDR:
            this.async_address = merge(this.async_address) & ~0x1F;
            break;
        case OP + R_CONFIGFLAG:
        {
            const value = merge(this.configflag) & 1;
            if(value === this.configflag) break;
            this.configflag = value;
            // (set: every port the EHCI's, to be reset; cleared: the companions')
            for(let port = 0; port < EHCI_PORTS; port++)
            {
                this.portsc[port] = value ? this.portsc[port] & ~PORT_PO : this.portsc[port] | PORT_PO;
                this.route(port);
            }
            break;
        }
        default:
            if(offset >= OP + R_PORTSC && offset < OP + R_PORTSC + 4 * EHCI_PORTS)
            {
                this.write_port(offset - OP - R_PORTSC >> 2, bits & mask);
            }
    }
};

/**
 * @param {number} port
 * @param {number} value
 */
EHCIController.prototype.write_port = function(port, value)
{
    let portsc = this.portsc[port] & ~(value & PORT_WRITE_CLEAR);
    // (the driver may disable the port, not enable it)
    if(!(value & PORT_PED)) portsc &= ~PORT_PED;
    // the port to the other controller (Port Owner, with CONFIGFLAG set)
    const owner = value & PORT_PO;
    if(owner !== (portsc & PORT_PO) && this.configflag)
    {
        this.portsc[port] = portsc & ~PORT_PO | owner;
        this.route(port);
        portsc = this.portsc[port];
    }
    const device = this.devices[port];
    if(!(value & PORT_PR) && portsc & PORT_PR)
    {
        // the end of a port reset: a high-speed device is enabled; a
        // full- or low-speed one is not (its driver gives it to the companion)
        portsc &= ~PORT_PR;
        if(device && this.owns(port))
        {
            device.reset();
            if(device.speeds.includes(SPEED_HIGH))
            {
                device.set_speed(SPEED_HIGH);
                portsc |= PORT_PED;
            }
        }
    }
    else if(value & PORT_PR && !(portsc & PORT_PR))
    {
        portsc = portsc & ~PORT_PED | PORT_PR;
    }
    // (a resume ends the suspend)
    if(!(value & PORT_FPR) && portsc & PORT_FPR) value &= ~PORT_SUSPEND;
    portsc = portsc & ~PORT_DRIVER | value & PORT_DRIVER;
    if(!(portsc & PORT_PED)) portsc &= ~PORT_SUSPEND;
    this.portsc[port] = portsc;
};

EHCIController.prototype.update_irq = function()
{
    const level = !!(this.status & this.intr & 0x3F);
    if(level === this.irq_level) return;
    this.irq_level = level;
    if(level) this.machine.raise_irq();
    else this.machine.lower_irq();
};

// the schedules

/**
 * @param {number} now the machine time
 * @return {number} milliseconds until the next work
 */
EHCIController.prototype.timer = function(now)
{
    if(!(this.cmd & CMD_RS)) return 100;
    if(now - this.next_ms > MS_BEHIND)
    {
        // (far behind: the time of the gap passes without its work)
        const skipped = Math.floor(now - this.next_ms) - MS_PER_ROUND;
        this.frindex = this.frindex + 8 * skipped & 0x3FFF;
        this.next_ms += skipped;
    }
    for(let i = 0; i < MS_PER_ROUND && now >= this.next_ms; i++)
    {
        this.process_ms();
        this.next_ms += 1;
        if(!(this.cmd & CMD_RS)) return 100;
    }
    return Math.max(0, this.next_ms - now);
};

/** A millisecond: eight micro-frames of the periodic schedule, then the asynchronous one */
EHCIController.prototype.process_ms = function()
{
    if(!this.machine.is_bus_master())
    {
        this.advance_frindex(8);
        return;
    }
    this.interrupts = 0;
    for(let i = 0; i < 8; i++)
    {
        if(this.cmd & CMD_PSE && !this.process_periodic()) return;
        this.advance_frindex(1);
    }
    if(this.cmd & CMD_ASE && !this.process_async()) return;
    if(this.interrupts)
    {
        this.status |= this.interrupts;
        this.update_irq();
    }
};

/** @param {number} uframes */
EHCIController.prototype.advance_frindex = function(uframes)
{
    const before = this.frindex;
    this.frindex = this.frindex + uframes & 0x3FFF;
    // (the frame list's index wrapped: Frame List Rollover)
    if((before ^ this.frindex) & 0x2000)
    {
        this.status |= STS_FLR;
        this.update_irq();
    }
};

/**
 * The periodic schedule of the current micro-frame
 * @return {boolean} false after a host system error
 */
EHCIController.prototype.process_periodic = function()
{
    const uframe = this.frindex & 7;
    let link = this.dma_read32(this.address(this.periodic_base + 4 * (this.frindex >> 3 & 0x3FF)));
    for(let n = 0; n < PERIODIC_NODES; n++)
    {
        if(link === null) return this.host_error();
        if(link & LINK_TERMINATE) break;
        const node = link & ~0x1F, type = link >> 1 & 3;
        if(type === TYPE_QH)
        {
            const caps = this.dma_read32(this.address(node + 8));
            if(caps === null) return this.host_error();
            // (an interrupt endpoint's queue head, in the micro-frames of its S-mask)
            if(caps & 1 << uframe && this.process_qh(node, Math.max(1, caps >>> 30)) === null) return this.host_error();
        }
        // (an iTD, siTD or FSTN: skipped, by its next link, also dword 0)
        link = this.dma_read32(this.address(node));
    }
    return true;
};

/**
 * The asynchronous schedule: its ring from ASYNCLISTADDR, pass after pass
 * while transactions happen
 * @return {boolean} false after a host system error
 */
EHCIController.prototype.process_async = function()
{
    this.async_bytes = ASYNC_BYTES;
    let qh = this.async_address, start = qh, progress = false;
    for(let n = 0; n < ASYNC_QHS && this.async_bytes > 0; n++)
    {
        const result = this.process_qh(qh, 0);
        if(result === null) return this.host_error();
        progress = progress || result;
        const link = this.dma_read32(this.address(qh));
        if(link === null) return this.host_error();
        // (the ring is of queue heads; anything else ends the pass)
        if(link & LINK_TERMINATE || (link >> 1 & 3) !== TYPE_QH) break;
        qh = link & ~0x1F;
        if(qh === start)
        {
            if(!progress) break;
            progress = false;
        }
    }
    this.async_address = qh;
    return true;
};

/**
 * A 64-bit data structure address from its low dword (CTRLDSSEGMENT)
 * @param {number} low
 * @return {number}
 */
EHCIController.prototype.address = function(low)
{
    return this.segment ? this.segment * 0x100000000 + (low >>> 0) : low >>> 0;
};

/**
 * The device at an address on an enabled port the EHCI owns
 * @param {number} address
 * @return {?Object}
 */
EHCIController.prototype.device_at = function(address)
{
    for(let port = 0; port < EHCI_PORTS; port++)
    {
        const device = this.devices[port];
        if(device && this.owns(port) && this.portsc[port] & PORT_PED && !(this.portsc[port] & PORT_SUSPEND) && device.address === address)
        {
            return device;
        }
    }
    return null;
};

/**
 * A queue head: its current qTD's transactions, then the next qTDs while
 * they are active (at most `limit` transactions: a periodic one's, or 0)
 * @param {number} qh
 * @param {number} limit
 * @return {?boolean} whether transactions happened; null where the queue head is not in memory
 */
EHCIController.prototype.process_qh = function(qh, limit)
{
    const words = this.dma_read(this.address(qh), 68);
    if(!words) return null;
    const view = new DataView(words.buffer);
    const dw = i => view.getUint32(4 * i, true);
    const characteristics = dw(1);
    const device_address = characteristics & 0x7F, endpoint = characteristics >> 8 & 0xF, speed = characteristics >> 12 & 3;
    const dtc = characteristics & 1 << 14, max_packet = characteristics >> 16 & 0x7FF;
    const reload = characteristics >>> 28;
    // the overlay: current qTD, next, alternate next (and the NAK counter), token, five buffer pointers (and their high dwords)
    const overlay = [dw(3), dw(4), dw(5), dw(6), dw(7), dw(8), dw(9), dw(10), dw(11), dw(12), dw(13), dw(14), dw(15), dw(16)];
    let progress = false, transactions = 0;

    for(let qtds = 0; qtds < 64; qtds++)
    {
        let token = overlay[3];
        if(token & TOKEN_HALTED) break;
        if(!(token & TOKEN_ACTIVE))
        {
            // the next qTD: the alternate one after a short packet
            const left = token >> 16 & 0x7FFF;
            const next = left && !(overlay[2] & LINK_TERMINATE) ? overlay[2] : overlay[1];
            if(next & LINK_TERMINATE) break;
            const qtd = next & ~0x1F;
            const words2 = this.dma_read(this.address(qtd), 52);
            if(!words2) return null;
            const q = new DataView(words2.buffer);
            const qtd_token = q.getUint32(8, true);
            if(!(qtd_token & TOKEN_ACTIVE)) break;
            // (the overlay: the data toggle stays the queue head's unless
            // the qTDs carry it; the ping state stays)
            let new_token = qtd_token;
            if(!dtc) new_token = (new_token & ~TOKEN_DT | token & TOKEN_DT) >>> 0;
            if(speed === EPS_HIGH) new_token = new_token & ~TOKEN_PING | token & TOKEN_PING;
            overlay[0] = qtd;
            overlay[1] = q.getUint32(0, true);
            overlay[2] = q.getUint32(4, true) & ~0x1E | reload << 1;
            overlay[3] = new_token >>> 0;
            for(let i = 0; i < 5; i++) overlay[4 + i] = q.getUint32(12 + 4 * i, true);
            for(let i = 0; i < 5; i++) overlay[9 + i] = q.getUint32(32 + 4 * i, true);
            // (the C-prog-mask and S-bytes, split transactions' fields, start at 0)
            overlay[5] &= ~0xFF;
            overlay[6] &= ~0xFFF;
            this.write_overlay(qh, overlay);
            continue;
        }

        const pid = PID_CODES[token >> 8 & 3];
        const device = speed === EPS_HIGH ? this.device_at(device_address) : null;
        let bytes = token >> 16 & 0x7FFF;
        let page = token >> 12 & 7, offset = overlay[4] & 0xFFF;
        let done = false, error = 0, short = false;
        while(!done)
        {
            if(limit && transactions >= limit || this.async_bytes <= 0 && !limit) break;
            if(pid === undefined || !device)
            {
                // no answer (no device, a split transaction): CERR down, at 0 the qTD halts
                let errors = token >> 10 & 3;
                if(errors) errors--;
                token = (token & ~(3 << 10) | errors << 10 | TOKEN_XACTERR) >>> 0;
                if(!errors || pid === undefined)
                {
                    error = TOKEN_HALTED;
                    done = true;
                }
                break;
            }
            const length = pid === PID_SETUP ? 8 : Math.min(bytes, max_packet || 8);
            let data = null;
            if(pid !== PID_IN)
            {
                data = this.read_buffer(overlay, page, offset, length);
                if(!data) { error = TOKEN_HALTED | TOKEN_BUFFER_ERROR; done = true; break; }
            }
            const result = device.transaction(pid, endpoint, data, length);
            transactions++;
            if(result === USB_NAK)
            {
                // (tried again later; a high-speed OUT pings meanwhile)
                if(pid === PID_OUT && speed === EPS_HIGH) token |= TOKEN_PING;
                break;
            }
            token &= ~TOKEN_PING;
            if(result === USB_STALL)
            {
                error = TOKEN_HALTED;
                done = true;
                break;
            }
            let moved = length;
            if(result instanceof Uint8Array)
            {
                if(result.length > length)
                {
                    error = TOKEN_HALTED | TOKEN_BABBLE;
                    done = true;
                    break;
                }
                moved = result.length;
                if(moved && !this.write_buffer(overlay, page, offset, result)) { error = TOKEN_HALTED | TOKEN_BUFFER_ERROR; done = true; break; }
            }
            progress = true;
            if(!limit) this.async_bytes -= Math.max(moved, 64);
            // the bytes on, the page and offset on, the data toggle over
            bytes -= Math.min(bytes, moved);
            offset += moved;
            page += offset >> 12;
            offset &= 0xFFF;
            token = (token ^ TOKEN_DT) >>> 0;
            if(pid === PID_IN && moved < length) short = true;
            if(!bytes || short || pid === PID_SETUP) done = true;
        }
        token = (token & ~(0x7FFF << 16 | 7 << 12) | bytes << 16 | (page & 7) << 12) >>> 0;
        overlay[4] = (overlay[4] & ~0xFFF | offset) >>> 0;
        if(done)
        {
            token = (token & ~TOKEN_ACTIVE | error) >>> 0;
            overlay[3] = token;
            this.write_overlay(qh, overlay);
            // the qTD's token, as it ended
            this.dma_write32(this.address(overlay[0] + 8), token);
            if(token & TOKEN_IOC || short) this.interrupts |= STS_USBINT;
            if(error) this.interrupts |= STS_USBERRINT;
            if(error) break;
            continue;
        }
        overlay[3] = token;
        this.write_overlay(qh, overlay);
        break;
    }
    return progress;
};

/**
 * The overlay into the queue head (dwords 3 to 16)
 * @param {number} qh
 * @param {!Array<number>} overlay
 */
EHCIController.prototype.write_overlay = function(qh, overlay)
{
    const bytes = new Uint8Array(overlay.length * 4);
    const view = new DataView(bytes.buffer);
    overlay.forEach((value, i) => view.setUint32(4 * i, value >>> 0, true));
    this.dma_write(bytes, this.address(qh + 12));
};

/**
 * The guest memory of a qTD's buffer at its page and offset
 * @param {!Array<number>} overlay
 * @param {number} page
 * @return {number} -1 past the fifth page
 */
EHCIController.prototype.buffer_address = function(overlay, page)
{
    if(page > 4) return -1;
    return (overlay[9 + page] >>> 0) * 0x100000000 + ((overlay[4 + page] & ~0xFFF) >>> 0);
};

/**
 * @param {!Array<number>} overlay
 * @param {number} page
 * @param {number} offset
 * @param {number} length
 * @return {Uint8Array}
 */
EHCIController.prototype.read_buffer = function(overlay, page, offset, length)
{
    const data = new Uint8Array(length);
    for(let at = 0; at < length;)
    {
        const base = this.buffer_address(overlay, page);
        if(base < 0) return null;
        const n = Math.min(length - at, 0x1000 - offset);
        const part = this.dma_read(base + offset, n);
        if(!part) return null;
        data.set(part, at);
        at += n;
        page++;
        offset = 0;
    }
    return data;
};

/**
 * @param {!Array<number>} overlay
 * @param {number} page
 * @param {number} offset
 * @param {!Uint8Array} data
 * @return {boolean}
 */
EHCIController.prototype.write_buffer = function(overlay, page, offset, data)
{
    for(let at = 0; at < data.length;)
    {
        const base = this.buffer_address(overlay, page);
        if(base < 0) return false;
        const n = Math.min(data.length - at, 0x1000 - offset);
        if(!this.dma_write(data.subarray(at, at + n), base + offset)) return false;
        at += n;
        page++;
        offset = 0;
    }
    return true;
};

/**
 * A schedule outside memory: the controller stops (host system error)
 * @return {boolean} false
 */
EHCIController.prototype.host_error = function()
{
    dbg_log("ehci: schedule outside memory (async " + h(this.async_address >>> 0, 8) + ", periodic " + h(this.periodic_base >>> 0, 8) + ")", LOG_PCI);
    this.status |= STS_HSE | STS_HALTED;
    this.cmd &= ~CMD_RS;
    this.update_irq();
    return false;
};

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array}
 */
EHCIController.prototype.dma_read = function(address, length)
{
    try { return this.machine.read_physical(address, length); }
    catch(e) { return null; }
};

/**
 * @param {number} address
 * @return {?number}
 */
EHCIController.prototype.dma_read32 = function(address)
{
    try { return this.machine.read32_physical(address) >>> 0; }
    catch(e) { return null; }
};

/**
 * @param {number} address
 * @param {number} value
 */
EHCIController.prototype.dma_write32 = function(address, value)
{
    try { this.machine.write32_physical(address, value | 0); }
    catch(e) { dbg_log("ehci: write outside memory at " + h(address >>> 0, 8), LOG_PCI); }
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 * @return {boolean}
 */
EHCIController.prototype.dma_write = function(bytes, address)
{
    try { this.machine.write_physical(bytes, address); return true; }
    catch(e) { dbg_log("ehci: write outside memory at " + h(address >>> 0, 8), LOG_PCI); return false; }
};

EHCIController.prototype.get_state = function()
{
    const now = this.machine.now();
    return [this.cmd, this.status, this.intr, this.frindex, this.segment, this.periodic_base, this.async_address, this.configflag,
        this.portsc.slice(), this.next_ms - now, +this.irq_level, 0, this.bar0, this.companions.map(companion => companion.get_state())];
};

EHCIController.prototype.set_state = function(state)
{
    this.cmd = state[0];
    this.status = state[1];
    this.intr = state[2];
    this.frindex = state[3];
    this.segment = state[4];
    this.periodic_base = state[5];
    this.async_address = state[6];
    this.configflag = state[7];
    this.portsc = state[8].slice();
    this.next_ms = this.machine.now() + state[9];
    this.irq_level = !!state[10];
    if(this.irq_level) this.machine.raise_irq();
    else this.machine.lower_irq();
    this.bar0 = state[12];
    this.update_decode();
    state[13].forEach((companion, i) => this.companions[i].set_state(companion));
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/usb/hid_tablet.js                                                                    0000644 0000000 0000000 00000017531 00000000000 013710  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A USB HID tablet: an absolute pointer (X and Y from 0 to 32767 over the
// guest's screen), three buttons and a wheel, a full-speed device with one
// interrupt IN endpoint (as QEMU's usb-tablet; HID 1.11). Not a boot
// device (it does not claim the boot mouse protocol it could not keep).
// Reports go out when something changed, or after the idle time SET_IDLE
// asks for; otherwise the endpoint NAKs.

import { USBDevice } from "./usb_device.js";
import {
    DESCRIPTOR_HID, DESCRIPTOR_REPORT, ENDPOINT_INTERRUPT, SPEED_FULL, USB_NAK, USB_STALL,
    configuration_descriptor, device_descriptor, endpoint_descriptor, interface_descriptor,
} from "./usb.js";

/** The report: buttons, X, Y (16 bits each), the wheel */
const REPORT_DESCRIPTOR = [
    0x05, 0x01, // Usage Page (Generic Desktop)
    0x09, 0x02, // Usage (Mouse)
    0xA1, 0x01, // Collection (Application)
    0x09, 0x01, //   Usage (Pointer)
    0xA1, 0x00, //   Collection (Physical)
    0x05, 0x09, //     Usage Page (Button)
    0x19, 0x01, //     Usage Minimum (1)
    0x29, 0x03, //     Usage Maximum (3)
    0x15, 0x00, //     Logical Minimum (0)
    0x25, 0x01, //     Logical Maximum (1)
    0x95, 0x03, //     Report Count (3)
    0x75, 0x01, //     Report Size (1)
    0x81, 0x02, //     Input (Data, Variable, Absolute)
    0x95, 0x01, //     Report Count (1)
    0x75, 0x05, //     Report Size (5)
    0x81, 0x01, //     Input (Constant)
    0x05, 0x01, //     Usage Page (Generic Desktop)
    0x09, 0x30, //     Usage (X)
    0x09, 0x31, //     Usage (Y)
    0x15, 0x00, //     Logical Minimum (0)
    0x26, 0xFF, 0x7F, // Logical Maximum (32767)
    0x35, 0x00, //     Physical Minimum (0)
    0x46, 0xFF, 0x7F, // Physical Maximum (32767)
    0x75, 0x10, //     Report Size (16)
    0x95, 0x02, //     Report Count (2)
    0x81, 0x02, //     Input (Data, Variable, Absolute)
    0x05, 0x01, //     Usage Page (Generic Desktop)
    0x09, 0x38, //     Usage (Wheel)
    0x15, 0x81, //     Logical Minimum (-127)
    0x25, 0x7F, //     Logical Maximum (127)
    0x35, 0x00, //     Physical Minimum (0)
    0x45, 0x00, //     Physical Maximum (0)
    0x75, 0x08, //     Report Size (8)
    0x95, 0x01, //     Report Count (1)
    0x81, 0x06, //     Input (Data, Variable, Relative)
    0xC0,       //   End Collection
    0xC0,       // End Collection
];
const REPORT_SIZE = 6;
export const TABLET_MAX = 0x7FFF;

const HID_DESCRIPTOR = [9, DESCRIPTOR_HID, 0x11, 0x01, 0x00, 0x01, DESCRIPTOR_REPORT, REPORT_DESCRIPTOR.length & 0xFF, REPORT_DESCRIPTOR.length >> 8];

// HID class requests
const HID_GET_REPORT = 0x01, HID_GET_IDLE = 0x02, HID_GET_PROTOCOL = 0x03, HID_SET_REPORT = 0x09, HID_SET_IDLE = 0x0A,
    HID_SET_PROTOCOL = 0x0B;

/**
 * @constructor
 * @extends {USBDevice}
 * @param {function():number} now the machine clock (milliseconds), for the idle rate
 */
export function HIDTablet(now)
{
    this.now = now;
    /** @type {?function(boolean)} whether the guest has the tablet configured, when that changes */
    this.on_use = null;
    this.in_use = false;
    USBDevice.call(this, {
        name: "tablet",
        speeds: [SPEED_FULL],
        device: device_descriptor({ usb: 0x0110, class: 0, subclass: 0, protocol: 0, max_packet0: 8,
            // (QEMU's tablet's IDs, which drivers know)
            vendor: 0x0627, product: 0x0001, release: 0x0000, manufacturer: 1, product_string: 2, serial: 3, configurations: 1 }),
        configurations: [configuration_descriptor({ value: 1, attributes: 0x80, max_power: 50, interfaces: 1 }, [
            interface_descriptor({ number: 0, alternate: 0, endpoints: 1, class: 3, subclass: 0, protocol: 0 }),
            HID_DESCRIPTOR,
            endpoint_descriptor({ address: 0x81, type: ENDPOINT_INTERRUPT, max_packet: 8, interval: 10 }),
        ])],
        strings: ["v86", "v86 USB Tablet", "1"],
        endpoints: [0x81],
    });
    this.x = TABLET_MAX >> 1;
    this.y = TABLET_MAX >> 1;
    this.buttons = 0;
    this.wheel = 0;
    /** something to report */
    this.changed = false;
    this.last_report = 0;
}

HIDTablet.prototype = Object.create(USBDevice.prototype);

HIDTablet.prototype.reset = function()
{
    USBDevice.prototype.reset.call(this);
    /** SET_IDLE: in 4 ms units, 0 only on change */
    this.idle = 0;
    this.protocol = 1;
    this.update_use();
};

/** Tell on_use whether the guest has the tablet configured */
HIDTablet.prototype.update_use = function()
{
    const in_use = this.configuration !== 0;
    if(in_use === this.in_use) return;
    this.in_use = in_use;
    if(this.on_use) this.on_use(in_use);
};

/**
 * The pointer moved: the position over the screen, each from 0 to 1
 * @param {number} x
 * @param {number} y
 */
HIDTablet.prototype.move = function(x, y)
{
    const tx = Math.max(0, Math.min(TABLET_MAX, Math.round(x * TABLET_MAX)));
    const ty = Math.max(0, Math.min(TABLET_MAX, Math.round(y * TABLET_MAX)));
    if(tx === this.x && ty === this.y) return;
    this.x = tx;
    this.y = ty;
    this.changed = true;
};

/**
 * @param {boolean} left
 * @param {boolean} middle
 * @param {boolean} right
 */
HIDTablet.prototype.press = function(left, middle, right)
{
    const buttons = (left ? 1 : 0) | (right ? 2 : 0) | (middle ? 4 : 0);
    if(buttons === this.buttons) return;
    this.buttons = buttons;
    this.changed = true;
};

/** @param {number} delta the wheel's steps, positive away from the user */
HIDTablet.prototype.scroll = function(delta)
{
    if(!delta) return;
    this.wheel += delta;
    this.changed = true;
};

/** @return {!Uint8Array} the current report (the wheel's steps taken from it) */
HIDTablet.prototype.report = function()
{
    const wheel = Math.max(-127, Math.min(127, this.wheel));
    this.wheel -= wheel;
    return Uint8Array.of(this.buttons, this.x & 0xFF, this.x >> 8, this.y & 0xFF, this.y >> 8, wheel & 0xFF);
};

HIDTablet.prototype.data_in = function(endpoint, max_length)
{
    const now = this.now();
    if(!this.changed && !(this.idle && now - this.last_report >= this.idle * 4)) return USB_NAK;
    const report = this.report();
    this.changed = this.wheel !== 0;
    this.last_report = now;
    return report.subarray(0, Math.min(max_length, REPORT_SIZE));
};

HIDTablet.prototype.interface_descriptor = function(type, index, interface_number)
{
    if(interface_number !== 0) return null;
    if(type === DESCRIPTOR_HID) return HID_DESCRIPTOR;
    if(type === DESCRIPTOR_REPORT) return REPORT_DESCRIPTOR;
    return null;
};

HIDTablet.prototype.class_request = function(setup, data)
{
    // (requests to the interface)
    if((setup.type & 0x1F) !== 1 || (setup.index & 0xFF) !== 0) return USB_STALL;
    switch(setup.request)
    {
        case HID_GET_REPORT:
            return (setup.value >> 8) === 1 ? this.report() : USB_STALL;
        case HID_SET_REPORT:
            // (no output or feature reports)
            return USB_STALL;
        case HID_GET_IDLE:
            return Uint8Array.of(this.idle);
        case HID_SET_IDLE:
            this.idle = setup.value >> 8;
            return new Uint8Array(0);
        case HID_GET_PROTOCOL:
            return Uint8Array.of(this.protocol);
        case HID_SET_PROTOCOL:
            this.protocol = setup.value & 1;
            return new Uint8Array(0);
    }
    return USB_STALL;
};

HIDTablet.prototype.configured = function(value)
{
    // (the guest's driver takes the pointer from a fresh report)
    this.changed = true;
    this.update_use();
};

HIDTablet.prototype.get_state = function()
{
    return [USBDevice.prototype.get_state.call(this), this.x, this.y, this.buttons, this.wheel, +this.changed, this.idle, this.protocol];
};

HIDTablet.prototype.set_state = function(state)
{
    USBDevice.prototype.set_state.call(this, state[0]);
    [, this.x, this.y, this.buttons, this.wheel] = state;
    this.changed = !!state[5];
    this.idle = state[6];
    this.protocol = state[7];
    this.last_report = this.now();
    this.in_use = !this.configuration;
    this.update_use();
};
                                                                                                                                                                       source/v64/src/usb/machine.js                                                                       0000644 0000000 0000000 00000003103 00000000000 013203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The USB plugin's view of the machine (usb: { controller, tablet,
// mass_storage }): the device handle of src/device_machine.js plus the bus
// messages it takes (the page's pointer for the tablet) and sends (which
// pointer device is in use), and the disk images' block backends. Built into
// build/v86-usb.js.

import { DeviceMachine, register_device_plugin } from "../device_machine.js";

/**
 * Make the USB plugin known to v86 (its file calls this when it loads)
 * @param {!Object} descriptor { "name": "usb", "create": function(handle, options) }
 */
export function register_usb_plugin(descriptor)
{
    register_device_plugin("V86UsbControllers", descriptor);
}

/**
 * @constructor
 * @extends {DeviceMachine}
 * @param {!Object} handle
 */
export function UsbMachine(handle)
{
    DeviceMachine.call(this, handle);
    /** @const @type {!Object} */
    this.bus = handle["bus"];
}

UsbMachine.prototype = Object.create(DeviceMachine.prototype);

/**
 * A bus message for the plugin: "mouse-absolute", "mouse-click",
 * "mouse-wheel", "mouse-pointer-lock"
 * @param {string} name
 * @param {function(*)} handler
 */
UsbMachine.prototype.on = function(name, handler)
{
    this.bus["register"](name, handler);
};

/**
 * @param {string} name
 * @param {*} value
 */
UsbMachine.prototype.send = function(name, value)
{
    this.bus["send"](name, value);
};

/**
 * A disk image's block backend (src/device_plugin.js block_handle)
 * @param {!Object} buffer
 * @return {!Object}
 */
UsbMachine.prototype.block_backend = function(buffer)
{
    return this.handle["block_backend"](buffer);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/usb/mass_storage.js                                                                  0000644 0000000 0000000 00000066143 00000000000 014303  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A USB disk: a disk image as a USB mass storage device, Bulk-Only Transport
// (USB Mass Storage Class BOT 1.0) with the SCSI transparent command set
// (SPC-3, SBC-3): one LUN of 512-byte sectors, removable (as USB sticks
// are), full or high speed (on EHCI), SuperSpeed (on an xHCI USB 3 port).
// The host sends a command block wrapper (CBW) on the bulk OUT
// endpoint, the data goes on bulk IN or OUT, and the device ends the command
// with a command status wrapper (CSW) on bulk IN. The image is the core's
// block backend (src/block_backend.js, through the plugin's handle): reads a
// reset cancels, a flush after the writes before it, I/O a snapshot waits
// for. An IN whose data was not read yet, or a CSW whose writes are not done,
// NAKs: the controller tries again in a later frame.

import { USBDevice } from "./usb_device.js";
import {
    DESCRIPTOR_BOS, DESCRIPTOR_DEVICE_CAPABILITY, DESCRIPTOR_SS_ENDPOINT_COMPANION, ENDPOINT_BULK, SPEED_FULL, SPEED_HIGH,
    SPEED_SUPER, USB_NAK, USB_STALL, configuration_descriptor, device_descriptor, endpoint_descriptor, interface_descriptor,
} from "./usb.js";

const CBW_SIGNATURE = 0x43425355, CSW_SIGNATURE = 0x53425355;
const CBW_LENGTH = 31, CSW_LENGTH = 13;
// BOT's class requests
const REQUEST_RESET = 0xFF, REQUEST_GET_MAX_LUN = 0xFE;
// where the device is: waiting for a CBW, in the data stage (to the host or
// from it), the CSW next; after an invalid CBW both bulk endpoints STALL
// until a reset recovery (BOT 6.6.1)
const PHASE_CBW = 0, PHASE_IN = 1, PHASE_OUT = 2, PHASE_CSW = 3, PHASE_STALLED = 4;
const STATUS_PASSED = 0, STATUS_FAILED = 1, STATUS_PHASE_ERROR = 2;
export const SECTOR_SIZE = 512;
// The image is read and written in pieces of at most this many bytes (a
// read ahead while the host takes the one before)
const CHUNK = 64 << 10;

// sense data: [sense key, additional sense code, its qualifier]
const NO_SENSE = [0, 0, 0], NOT_PRESENT = [2, 0x3A, 0], READ_ERROR = [3, 0x11, 0], WRITE_ERROR = [3, 0x0C, 0],
    INVALID_OPCODE = [5, 0x20, 0], OUT_OF_RANGE = [5, 0x21, 0], INVALID_FIELD = [5, 0x24, 0], NO_LUN = [5, 0x25, 0],
    NO_SAVING = [5, 0x39, 0], REMOVAL_PREVENTED = [5, 0x53, 0x02], MEDIUM_CHANGED = [6, 0x28, 0], WRITE_PROTECTED = [7, 0x27, 0];

// SCSI operation codes
const TEST_UNIT_READY = 0x00, REQUEST_SENSE = 0x03, READ_6 = 0x08, WRITE_6 = 0x0A, INQUIRY = 0x12, MODE_SELECT_6 = 0x15,
    MODE_SENSE_6 = 0x1A, START_STOP_UNIT = 0x1B, PREVENT_ALLOW = 0x1E, READ_FORMAT_CAPACITIES = 0x23, READ_CAPACITY_10 = 0x25,
    READ_10 = 0x28, WRITE_10 = 0x2A, VERIFY_10 = 0x2F, SYNCHRONIZE_CACHE_10 = 0x35, MODE_SELECT_10 = 0x55, MODE_SENSE_10 = 0x5A,
    READ_16 = 0x88, WRITE_16 = 0x8A, VERIFY_16 = 0x8F, SYNCHRONIZE_CACHE_16 = 0x91, SERVICE_ACTION_IN = 0x9E, REPORT_LUNS = 0xA0,
    READ_12 = 0xA8, WRITE_12 = 0xAA, VERIFY_12 = 0xAF;
const READ_CAPACITY_16 = 0x10;

// what the data stage carries
const DATA_IN = 1, DATA_OUT = 2;

// the commands that need the medium
const NEED_MEDIUM = new Set([READ_6, READ_10, READ_12, READ_16, WRITE_6, WRITE_10, WRITE_12, WRITE_16, VERIFY_10, VERIFY_12,
    VERIFY_16, READ_CAPACITY_10, SERVICE_ACTION_IN, SYNCHRONIZE_CACHE_10, SYNCHRONIZE_CACHE_16, MODE_SENSE_6, MODE_SENSE_10,
    TEST_UNIT_READY]);

/**
 * @param {!Uint8Array} bytes
 * @param {number} at
 * @return {number}
 */
function be32(bytes, at)
{
    return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
}

/**
 * @param {!Uint8Array} bytes
 * @param {number} at
 * @param {number} value
 */
function put_be32(bytes, at, value)
{
    bytes[at] = value >>> 24;
    bytes[at + 1] = value >>> 16;
    bytes[at + 2] = value >>> 8;
    bytes[at + 3] = value;
}

/**
 * @param {!Uint8Array} bytes
 * @param {number} at
 * @param {string} text
 */
function put_ascii(bytes, at, text)
{
    for(let i = 0; i < text.length; i++) bytes[at + i] = text.charCodeAt(i);
}

/**
 * A command's first sector and sector count (READ, WRITE, VERIFY and
 * SYNCHRONIZE CACHE: 6, 10, 12, 16 bytes)
 * @param {!Uint8Array} cb
 * @return {!Array<number>}
 */
function lba_and_count(cb)
{
    switch(cb[0])
    {
        case READ_6:
        case WRITE_6:
            // (0 sectors means 256)
            return [(cb[1] & 0x1F) << 16 | cb[2] << 8 | cb[3], cb[4] || 256];
        case READ_12:
        case WRITE_12:
        case VERIFY_12:
            return [be32(cb, 2), be32(cb, 6)];
        case READ_16:
        case WRITE_16:
        case VERIFY_16:
        case SYNCHRONIZE_CACHE_16:
            return [be32(cb, 2) * 0x100000000 + be32(cb, 6), be32(cb, 10)];
        default:
            return [be32(cb, 2), cb[7] << 8 | cb[8]];
    }
}

/**
 * The serial number from the disk's ID: hexadecimal (USB MSC requires 12
 * digits or more), the same for the same ID
 * @param {string} id
 * @return {string}
 */
export function serial_of(id)
{
    let hash = 0x811C9DC5, hash2 = 0x01000193;
    for(let i = 0; i < id.length; i++)
    {
        hash = Math.imul(hash ^ id.charCodeAt(i), 0x01000193) >>> 0;
        hash2 = Math.imul(hash2 ^ id.charCodeAt(i), 0x811C9DC5) >>> 0;
    }
    return (hash.toString(16).padStart(8, "0") + hash2.toString(16).padStart(8, "0")).toUpperCase();
}

/**
 * @constructor
 * @extends {USBDevice}
 * @param {!Object} backend the image: the handle's block backend ("read",
 *     "write", "flush", "reset", "byte_length")
 * @param {{id: string, read_only: boolean}} options
 */
export function MassStorage(backend, options)
{
    this.backend = backend;
    this.id = options.id;
    this.read_only = options.read_only;
    this.sectors = Math.floor(backend["byte_length"] / SECTOR_SIZE);
    this.serial = serial_of(options.id);
    /** @type {?function()} the guest ejected the medium (START STOP UNIT) */
    this.on_eject = null;
    /** a command's host I/O: what completes after a reset or another command does nothing */
    this.epoch = 0;
    // mass storage, SCSI transparent command set, Bulk-Only Transport; bulk
    // packets of 64 bytes at full speed, 512 at high speed
    const configuration = max_packet => configuration_descriptor({ value: 1, attributes: 0x80, max_power: 50, interfaces: 1 }, [
        interface_descriptor({ number: 0, alternate: 0, endpoints: 2, class: 8, subclass: 6, protocol: 0x50 }),
        endpoint_descriptor({ address: 0x81, type: ENDPOINT_BULK, max_packet, interval: 0 }),
        endpoint_descriptor({ address: 0x02, type: ENDPOINT_BULK, max_packet, interval: 0 }),
    ]);
    // at SuperSpeed: packets of 1024 bytes, each endpoint with its
    // SuperSpeed companion (no bursts, no streams: Bulk-Only, not UAS)
    const companion = [6, DESCRIPTOR_SS_ENDPOINT_COMPANION, 0, 0, 0, 0];
    const super_configuration = configuration_descriptor({ value: 1, attributes: 0x80, max_power: 12, interfaces: 1 }, [
        interface_descriptor({ number: 0, alternate: 0, endpoints: 2, class: 8, subclass: 6, protocol: 0x50 }),
        endpoint_descriptor({ address: 0x81, type: ENDPOINT_BULK, max_packet: 1024, interval: 0 }), companion,
        endpoint_descriptor({ address: 0x02, type: ENDPOINT_BULK, max_packet: 1024, interval: 0 }), companion,
    ]);
    // (QEMU's USB disk's IDs)
    const device = (usb, max_packet0) => device_descriptor({ usb, class: 0, subclass: 0, protocol: 0, max_packet0, vendor: 0x46F4,
        product: 0x0001, release: 0x0000, manufacturer: 1, product_string: 2, serial: 3, configurations: 1 });
    USBDevice.call(this, {
        name: options.id,
        speeds: [SPEED_FULL, SPEED_HIGH, SPEED_SUPER],
        device: device(0x0200, 64),
        configurations: [configuration(64)],
        high_configurations: [configuration(512)],
        // USB 3: endpoint 0's packets 2^9; the BOS: a USB 2.0 extension
        // without LPM, the SuperSpeed capability (full, high and SuperSpeed,
        // all of it from full speed on, no U1/U2 exit latencies: no U1/U2)
        super_device: device(0x0300, 9),
        super_configurations: [super_configuration],
        bos: [5, DESCRIPTOR_BOS, 22, 0, 2,
            7, DESCRIPTOR_DEVICE_CAPABILITY, 0x02, 0, 0, 0, 0,
            10, DESCRIPTOR_DEVICE_CAPABILITY, 0x03, 0, 0x0E, 0x00, 1, 0, 0, 0],
        strings: ["v86", "v86 USB Disk", this.serial],
        endpoints: [0x81, 0x02],
    });
}

MassStorage.prototype = Object.create(USBDevice.prototype);

/** A bus reset: also the disk's state (a medium the guest ejected is back) */
MassStorage.prototype.reset = function()
{
    USBDevice.prototype.reset.call(this);
    this.bot_reset();
    /** @type {!Array<number>} */
    this.sense = NO_SENSE;
    this.medium = true;
    /** PREVENT ALLOW MEDIUM REMOVAL */
    this.prevent = false;
    /** a medium loaded again: the next command fails with UNIT ATTENTION */
    this.unit_attention = false;
};

/**
 * BOT's reset (and the start of a bus reset): the command under way is
 * dropped. Reads are cancelled; writes issued are in the image or get there.
 */
MassStorage.prototype.bot_reset = function()
{
    this.epoch++;
    this.backend["reset"]();
    this.phase = PHASE_CBW;
    this.tag = 0;
    /** the CBW's: the bytes of the data stage, its direction */
    this.host_length = 0;
    this.host_in = false;
    /** bytes of the data stage done */
    this.done = 0;
    /** bytes of them that are the device's (the rest: padding to the host, or ignored) */
    this.device_length = 0;
    this.status = STATUS_PASSED;
    /** host I/O of the command not finished */
    this.io = 0;
    /** @type {!Array<!Uint8Array>} data to the host, read and not taken yet */
    this.queue = [];
    this.queued = 0;
    /** the image's bytes to read: where, how many not asked for yet, how many being read */
    this.read_at = 0;
    this.read_left = 0;
    this.reading = 0;
    /** writing: where the next piece goes; the piece being filled (null: the data is ignored) */
    this.write_at = 0;
    /** @type {Uint8Array} */
    this.chunk = null;
    this.fill = 0;
    this.received = 0;
    /** SYNCHRONIZE CACHE under way */
    this.flushing = false;
};

/**
 * GET_MAX_LUN and BOT's reset
 * @param {{type: number, request: number, value: number, index: number, length: number}} setup
 * @param {Uint8Array} data
 * @return {!Uint8Array|number}
 */
MassStorage.prototype.class_request = function(setup, data)
{
    if(setup.type === 0xA1 && setup.request === REQUEST_GET_MAX_LUN && setup.value === 0 && setup.length === 1)
    {
        return Uint8Array.of(0);
    }
    if(setup.type === 0x21 && setup.request === REQUEST_RESET && setup.value === 0 && setup.length === 0)
    {
        this.bot_reset();
        return new Uint8Array(0);
    }
    return USB_STALL;
};

/**
 * Bulk OUT: a CBW, or the data of a command
 * @param {number} endpoint
 * @param {!Uint8Array} data
 * @return {number}
 */
MassStorage.prototype.data_out = function(endpoint, data)
{
    if(this.phase === PHASE_CBW) return this.receive_cbw(data);
    if(this.phase !== PHASE_OUT) return USB_STALL;
    // (two pieces being written: the host waits)
    if(this.io >= 2) return USB_NAK;
    const length = Math.min(data.length, this.host_length - this.done);
    const device = Math.max(0, Math.min(length, this.device_length - this.done));
    if(device) this.accept(data.subarray(0, device));
    this.done += length;
    if(this.done === this.host_length) this.phase = PHASE_CSW;
    return 0;
};

/**
 * Bulk IN: the data of a command, or its CSW
 * @param {number} endpoint
 * @param {number} max_length
 * @return {!Uint8Array|number}
 */
MassStorage.prototype.data_in = function(endpoint, max_length)
{
    if(this.phase === PHASE_IN)
    {
        const length = Math.min(max_length, this.host_length - this.done);
        const device = Math.max(0, Math.min(length, this.device_length - this.done));
        if(device > this.queued) return USB_NAK;
        // (the device's bytes, then zeros up to the CBW's length: BOT's case Hi > Di)
        const packet = new Uint8Array(length);
        this.take(packet, device);
        this.done += length;
        if(this.done === this.host_length) this.phase = PHASE_CSW;
        return packet;
    }
    if(this.phase === PHASE_CSW)
    {
        if(this.io) return USB_NAK;
        const csw = new Uint8Array(CSW_LENGTH);
        put_le32(csw, 0, CSW_SIGNATURE);
        put_le32(csw, 4, this.tag);
        put_le32(csw, 8, this.host_length - this.device_length);
        csw[12] = this.status;
        this.phase = PHASE_CBW;
        return csw;
    }
    return this.phase === PHASE_STALLED ? USB_STALL : USB_NAK;
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} at
 * @param {number} value
 */
function put_le32(bytes, at, value)
{
    bytes[at] = value;
    bytes[at + 1] = value >>> 8;
    bytes[at + 2] = value >>> 16;
    bytes[at + 3] = value >>> 24;
}

/**
 * @param {!Uint8Array} bytes
 * @return {number}
 */
MassStorage.prototype.receive_cbw = function(bytes)
{
    const signature = (bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) >>> 0;
    if(bytes.length !== CBW_LENGTH || signature !== CBW_SIGNATURE || bytes[14] < 1 || bytes[14] > 16)
    {
        this.phase = PHASE_STALLED;
        this.halted.add(0x81);
        this.halted.add(0x02);
        return 0;
    }
    this.epoch++;
    this.io = 0;
    this.reading = 0;
    this.flushing = false;
    this.tag = (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) >>> 0;
    this.host_length = (bytes[8] | bytes[9] << 8 | bytes[10] << 16 | bytes[11] << 24) >>> 0;
    this.host_in = !!(bytes[12] & 0x80);
    this.done = 0;
    this.device_length = 0;
    this.status = STATUS_PASSED;
    this.queue = [];
    this.queued = 0;
    this.read_left = 0;
    this.chunk = null;
    this.fill = 0;
    this.received = 0;
    // (a LUN other than 0, which GET_MAX_LUN did not offer, fails the command)
    if(bytes[13] & 0xF) this.fail(NO_LUN);
    else this.execute(bytes.slice(15, 15 + bytes[14]));
    if(this.phase === PHASE_CBW) this.phase = this.host_length === 0 ? PHASE_CSW : this.host_in ? PHASE_IN : PHASE_OUT;
    return 0;
};

/**
 * The data stage the device means against the CBW's: the same direction,
 * as many bytes or fewer (BOT 6.7: otherwise a phase error, and the stage
 * carries nothing of the device's)
 * @param {number} direction DATA_IN, DATA_OUT (or 0: none)
 * @param {number} length
 * @return {boolean} whether the device's data goes
 */
MassStorage.prototype.begin = function(direction, length)
{
    if(length === 0) return false;
    if(this.host_length === 0 || this.host_in !== (direction === DATA_IN) || this.host_length < length)
    {
        this.status = STATUS_PHASE_ERROR;
        return false;
    }
    this.device_length = length;
    return true;
};

/**
 * The command failed: its sense, no data (the data stage is padded or ignored)
 * @param {!Array<number>} sense
 */
MassStorage.prototype.fail = function(sense)
{
    this.sense = sense;
    this.status = STATUS_FAILED;
};

/**
 * Data to the host (at most the command's allocation length)
 * @param {!Uint8Array} bytes
 * @param {number} allocation
 */
MassStorage.prototype.reply = function(bytes, allocation)
{
    bytes = bytes.subarray(0, Math.min(bytes.length, allocation));
    if(this.begin(DATA_IN, bytes.length))
    {
        this.queue.push(bytes);
        this.queued = bytes.length;
    }
};

/**
 * A SCSI command
 * @param {!Uint8Array} cb
 */
MassStorage.prototype.execute = function(cb)
{
    const op = cb[0];
    if(op !== REQUEST_SENSE) this.sense = NO_SENSE;
    if(this.unit_attention && op !== INQUIRY && op !== REQUEST_SENSE)
    {
        this.unit_attention = false;
        this.fail(MEDIUM_CHANGED);
        return;
    }
    if(!this.medium && NEED_MEDIUM.has(op))
    {
        this.fail(NOT_PRESENT);
        return;
    }
    switch(op)
    {
        case TEST_UNIT_READY:
            return;
        case REQUEST_SENSE:
        {
            // (fixed format; the sense is the last command's, and then gone)
            const sense = new Uint8Array(18);
            sense[0] = 0x70;
            sense[2] = this.sense[0];
            sense[7] = 10;
            sense[12] = this.sense[1];
            sense[13] = this.sense[2];
            this.sense = NO_SENSE;
            this.reply(sense, cb[4]);
            return;
        }
        case INQUIRY:
            this.inquiry(cb);
            return;
        case MODE_SENSE_6:
        case MODE_SENSE_10:
            this.mode_sense(cb);
            return;
        case MODE_SELECT_6:
        case MODE_SELECT_10:
            // (the parameters are taken and ignored: nothing is changeable)
            this.begin(DATA_OUT, op === MODE_SELECT_6 ? cb[4] : cb[7] << 8 | cb[8]);
            return;
        case START_STOP_UNIT:
            // LoEj: Start 0 ejects the medium, 1 loads it again
            if(cb[4] & 2)
            {
                if(!(cb[4] & 1))
                {
                    if(this.prevent) { this.fail(REMOVAL_PREVENTED); return; }
                    if(this.medium)
                    {
                        this.medium = false;
                        if(this.on_eject) this.on_eject();
                    }
                }
                else if(!this.medium)
                {
                    this.medium = true;
                    this.unit_attention = true;
                }
            }
            return;
        case PREVENT_ALLOW:
            this.prevent = (cb[4] & 3) !== 0;
            return;
        case READ_FORMAT_CAPACITIES:
        {
            const list = new Uint8Array(12);
            list[3] = 8;
            put_be32(list, 4, this.medium ? Math.min(this.sectors, 0xFFFFFFFF) : 0xFFFFFFFF);
            // (2: formatted media, 3: no media)
            list[8] = this.medium ? 2 : 3;
            list[10] = SECTOR_SIZE >> 8;
            list[11] = SECTOR_SIZE & 0xFF;
            this.reply(list, cb[7] << 8 | cb[8]);
            return;
        }
        case READ_CAPACITY_10:
        {
            const capacity = new Uint8Array(8);
            // (a disk too large for it says so: READ CAPACITY(16) then)
            put_be32(capacity, 0, Math.min(this.sectors - 1, 0xFFFFFFFF));
            put_be32(capacity, 4, SECTOR_SIZE);
            this.reply(capacity, 8);
            return;
        }
        case SERVICE_ACTION_IN:
        {
            if((cb[1] & 0x1F) !== READ_CAPACITY_16) { this.fail(INVALID_OPCODE); return; }
            const capacity = new Uint8Array(32);
            const last = this.sectors - 1;
            put_be32(capacity, 0, Math.floor(last / 0x100000000));
            put_be32(capacity, 4, last % 0x100000000);
            put_be32(capacity, 8, SECTOR_SIZE);
            this.reply(capacity, be32(cb, 10));
            return;
        }
        case READ_6:
        case READ_10:
        case READ_12:
        case READ_16:
        {
            const range = lba_and_count(cb), lba = range[0], count = range[1];
            if(lba + count > this.sectors) { this.fail(OUT_OF_RANGE); return; }
            if(this.begin(DATA_IN, count * SECTOR_SIZE))
            {
                this.read_at = lba * SECTOR_SIZE;
                this.read_left = count * SECTOR_SIZE;
                this.read_ahead();
            }
            return;
        }
        case WRITE_6:
        case WRITE_10:
        case WRITE_12:
        case WRITE_16:
        {
            const range = lba_and_count(cb), lba = range[0], count = range[1];
            if(this.read_only) { this.fail(WRITE_PROTECTED); return; }
            if(lba + count > this.sectors) { this.fail(OUT_OF_RANGE); return; }
            if(this.begin(DATA_OUT, count * SECTOR_SIZE))
            {
                this.write_at = lba * SECTOR_SIZE;
                this.chunk = new Uint8Array(Math.min(CHUNK, count * SECTOR_SIZE));
            }
            return;
        }
        case VERIFY_10:
        case VERIFY_12:
        case VERIFY_16:
        {
            const range = lba_and_count(cb), lba = range[0], count = range[1];
            if(lba + count > this.sectors) { this.fail(OUT_OF_RANGE); return; }
            // (BYTCHK: the host's data, taken and not compared)
            if(cb[1] & 2) this.begin(DATA_OUT, count * SECTOR_SIZE);
            return;
        }
        case SYNCHRONIZE_CACHE_10:
        case SYNCHRONIZE_CACHE_16:
            this.flush();
            return;
        case REPORT_LUNS:
        {
            const luns = new Uint8Array(16);
            luns[3] = 8;
            this.reply(luns, be32(cb, 6));
            return;
        }
    }
    this.fail(INVALID_OPCODE);
};

/** @param {!Uint8Array} cb */
MassStorage.prototype.inquiry = function(cb)
{
    const allocation = cb[3] << 8 | cb[4];
    if(cb[1] & 1)
    {
        // vital product data: the pages there are, the serial number
        if(cb[2] === 0x00)
        {
            this.reply(Uint8Array.of(0, 0x00, 0, 2, 0x00, 0x80), allocation);
        }
        else if(cb[2] === 0x80)
        {
            const page = new Uint8Array(4 + this.serial.length);
            page[1] = 0x80;
            page[3] = this.serial.length;
            put_ascii(page, 4, this.serial);
            this.reply(page, allocation);
        }
        else
        {
            this.fail(INVALID_FIELD);
        }
        return;
    }
    if(cb[2]) { this.fail(INVALID_FIELD); return; }
    const data = new Uint8Array(36);
    // a direct access block device, removable; SPC-3; response data format 2
    data[1] = 0x80;
    data[2] = 0x05;
    data[3] = 0x02;
    data[4] = data.length - 5;
    put_ascii(data, 8, "v86     ");
    put_ascii(data, 16, "USB Disk        ");
    put_ascii(data, 32, "1.0 ");
    this.reply(data, allocation);
};

/** @param {!Uint8Array} cb */
MassStorage.prototype.mode_sense = function(cb)
{
    const ten = cb[0] === MODE_SENSE_10;
    const control = cb[2] >> 6, code = cb[2] & 0x3F;
    if(control === 3) { this.fail(NO_SAVING); return; }
    // the caching page (write cache enabled: SYNCHRONIZE CACHE flushes the
    // writes before it), informational exceptions control; nothing changeable
    const caching = [0x08, 0x12, control === 1 ? 0 : 0x04, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    const exceptions = [0x1C, 0x0A, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    const pages = code === 0x08 ? caching : code === 0x1C ? exceptions : code === 0x3F ? caching.concat(exceptions) : null;
    if(!pages) { this.fail(INVALID_FIELD); return; }
    // (no block descriptors; the write protect bit)
    const protect = this.read_only ? 0x80 : 0;
    const header = ten ? [0, 0, 0, protect, 0, 0, 0, 0] : [0, 0, protect, 0];
    const data = Uint8Array.from(header.concat(pages));
    if(ten)
    {
        data[0] = data.length - 2 >> 8;
        data[1] = data.length - 2 & 0xFF;
    }
    else
    {
        data[0] = data.length - 1;
    }
    this.reply(data, ten ? cb[7] << 8 | cb[8] : cb[4]);
};

/** Read the next piece of the image while there is room for it */
MassStorage.prototype.read_ahead = function()
{
    if(this.reading || !this.read_left || this.queued >= CHUNK) return;
    const at = this.read_at, length = Math.min(CHUNK, this.read_left);
    this.read_at += length;
    this.read_left -= length;
    this.reading = length;
    this.io++;
    const epoch = this.epoch;
    this.backend["read"](at, length, bytes =>
    {
        if(epoch !== this.epoch) return;
        this.reading = 0;
        this.io--;
        // (a view the backend may reuse)
        this.queue.push(bytes.slice(0, length));
        this.queued += length;
        this.read_ahead();
    }, () =>
    {
        if(epoch !== this.epoch) return;
        // the backend's error (a disk whose policy reports them): what was
        // read goes, then padding
        this.reading = 0;
        this.io--;
        this.read_left = 0;
        this.device_length = this.done + this.queued;
        this.fail(READ_ERROR);
    });
};

/**
 * Data to the host from what was read
 * @param {!Uint8Array} packet
 * @param {number} length
 */
MassStorage.prototype.take = function(packet, length)
{
    let at = 0;
    while(at < length)
    {
        const head = this.queue[0];
        const n = Math.min(length - at, head.length);
        packet.set(head.subarray(0, n), at);
        at += n;
        if(n === head.length) this.queue.shift();
        else this.queue[0] = head.subarray(n);
    }
    this.queued -= length;
    this.read_ahead();
};

/**
 * Data from the host, into the piece being filled; a full piece (or the
 * last) goes to the image
 * @param {!Uint8Array} bytes
 */
MassStorage.prototype.accept = function(bytes)
{
    this.received += bytes.length;
    if(!this.chunk) return;
    let at = 0;
    while(at < bytes.length)
    {
        const n = Math.min(bytes.length - at, this.chunk.length - this.fill);
        this.chunk.set(bytes.subarray(at, at + n), this.fill);
        this.fill += n;
        at += n;
        if(this.fill === this.chunk.length || this.received === this.device_length) this.write_chunk();
    }
};

MassStorage.prototype.write_chunk = function()
{
    const data = this.chunk.slice(0, this.fill), at = this.write_at;
    this.write_at += this.fill;
    this.fill = 0;
    this.io++;
    const epoch = this.epoch;
    this.backend["write"](at, data, () =>
    {
        if(epoch === this.epoch) this.io--;
    }, () =>
    {
        if(epoch !== this.epoch) return;
        // (the rest of the data is taken and not written)
        this.io--;
        this.chunk = null;
        this.fail(WRITE_ERROR);
    });
};

/** SYNCHRONIZE CACHE: the CSW once the writes before it are in the image */
MassStorage.prototype.flush = function()
{
    this.flushing = true;
    this.io++;
    const epoch = this.epoch;
    const done = () =>
    {
        if(epoch !== this.epoch) return;
        this.flushing = false;
        this.io--;
    };
    this.backend["flush"](done, () =>
    {
        if(epoch !== this.epoch) return;
        this.fail(WRITE_ERROR);
        done();
    });
};

/** Taken out of its port: what is under way is dropped */
MassStorage.prototype.unplugged = function()
{
    this.bot_reset();
};

MassStorage.prototype.get_state = function()
{
    // (a snapshot waits for host I/O; a read still under way is read again)
    const queued = new Uint8Array(this.queued);
    let at = 0;
    for(const part of this.queue) { queued.set(part, at); at += part.length; }
    return [USBDevice.prototype.get_state.call(this), this.phase, this.tag, this.host_length, +this.host_in, this.done,
        this.device_length, this.status, this.sense.slice(), queued, this.read_at - this.reading, this.read_left + this.reading,
        this.chunk ? this.chunk.length : 0, this.chunk ? this.chunk.slice(0, this.fill) : null, this.write_at, this.received,
        +this.flushing, +this.medium, +this.prevent, +this.unit_attention];
};

MassStorage.prototype.set_state = function(state)
{
    this.bot_reset();
    USBDevice.prototype.set_state.call(this, state[0]);
    this.phase = state[1];
    this.tag = state[2];
    this.host_length = state[3];
    this.host_in = !!state[4];
    this.done = state[5];
    this.device_length = state[6];
    this.status = state[7];
    this.sense = state[8].slice();
    this.queue = state[9].length ? [state[9]] : [];
    this.queued = state[9].length;
    this.read_at = state[10];
    this.read_left = state[11];
    if(state[12])
    {
        this.chunk = new Uint8Array(state[12]);
        this.chunk.set(state[13]);
        this.fill = state[13].length;
    }
    this.write_at = state[14];
    this.received = state[15];
    this.medium = !!state[17];
    this.prevent = !!state[18];
    this.unit_attention = !!state[19];
    if(state[16]) this.flush();
    this.read_ahead();
};
                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/usb/plugin.js                                                                        0000644 0000000 0000000 00000020474 00000000000 013107  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // usb: { controller: "uhci" | "ehci" | "xhci", tablet: true, mass_storage } --
// a USB host controller and its devices (docs/usb.md,
// docs/modern-pc-devices-plan.md U1 to U4): UHCI (PIIX3's on i440FX, ICH9's
// on Q35), ICH9's EHCI with its three UHCI companions (the plugin's PCI
// function is the EHCI's, 7; the companions are functions 0 to 2), or xHCI
// (QEMU's qemu-xhci); the HID tablet on the first port,
// USB disks (disk images, src/usb/mass_storage.js) on the ports after it.
// Built into build/v86-usb.js; from the source tree, src/device_plugin.js
// imports this file directly.

import { UsbMachine, register_usb_plugin } from "./machine.js";
import { COMPANION_IDENTITY, PORTS as UHCI_PORTS, UHCIController } from "./uhci.js";
import { EHCI_PORTS, EHCIController } from "./ehci.js";
import { XHCI_PORTS, XHCIController } from "./xhci.js";
import { HIDTablet } from "./hid_tablet.js";
import { MassStorage } from "./mass_storage.js";

register_usb_plugin({
    "name": "usb",
    "create": (handle, options) =>
    {
        const machine = new UsbMachine(handle);
        const ehci = options["controller"] === "ehci", xhci = options["controller"] === "xhci";
        const controller = ehci ?
            new EHCIController(machine, COMPANION_IDENTITY.map((identity, i) => new UHCIController(machine.function_machine(i), identity, i === 0))) :
            xhci ? new XHCIController(machine) : new UHCIController(machine);
        const PORTS = ehci ? EHCI_PORTS : xhci ? XHCI_PORTS : UHCI_PORTS;
        const NAME = ehci ? "EHCI" : xhci ? "xHCI" : "UHCI";
        const tablet = options["tablet"] ? new HIDTablet(() => machine.now()) : null;
        /**
         * The devices by their IDs: the device, its port (kept while it is
         * out of it), a disk's block backend
         * @type {!Map<string, {device: !Object, port: number, backend: ?Object}>}
         */
        const devices = new Map();
        if(tablet)
        {
            devices.set("tablet", { device: tablet, port: 0, backend: null });
            controller.attach(0, tablet);
            connect_pointer(machine, tablet);
        }

        const free_port = () =>
        {
            const used = Array.from(devices.values(), entry => entry.port);
            for(let port = 0; port < PORTS; port++) if(!used.includes(port)) return port;
            return -1;
        };
        // a disk image as a USB disk in the first free port
        const attach_disk = (id, buffer, read_only) =>
        {
            if(typeof id !== "string" || !id) throw new Error("usb: a USB disk needs an id");
            if(devices.has(id)) throw new Error("usb: there is a USB device " + JSON.stringify(id) + " already");
            const port = free_port();
            if(port < 0) throw new Error("usb: no free port for " + JSON.stringify(id) + " (the " + NAME + " controller has " + PORTS + ")");
            const backend = machine.block_backend(buffer);
            const disk = new MassStorage(backend, { id, read_only });
            disk.on_eject = () => machine.send("usb-disk-ejected", id);
            devices.set(id, { device: disk, port, backend });
            controller.attach(port, disk);
            return port;
        };
        // out of its port and gone: what it had under way is dropped (writes
        // issued are in the image)
        const detach_disk = id =>
        {
            const entry = devices.get(id);
            if(!entry || !entry.backend) throw new Error("usb: no USB disk " + JSON.stringify(id));
            entry.device.unplugged();
            if(controller.devices[entry.port] === entry.device) controller.attach(entry.port, null);
            entry.backend["drop"]();
            devices.delete(id);
        };
        for(const disk of options["mass_storage"] || []) attach_disk(disk["id"], disk["buffer"], !!disk["read_only"]);

        // V86.usb_plug: a device out of its port and back in ("usb-plugged"
        // answers: the ID, whether it is in, an error)
        machine.on("usb-plug", data =>
        {
            const id = data[0], plugged = !!data[1];
            const entry = devices.get(id);
            if(!entry)
            {
                machine.send("usb-plugged", [id, false, "no USB device " + JSON.stringify(id)]);
                return;
            }
            if(!plugged) entry.device.reset();
            controller.attach(entry.port, plugged ? entry.device : null);
            machine.send("usb-plugged", [id, plugged, null]);
        });
        return {
            "controller": controller,
            "tablet": tablet,
            "devices": devices,
            "attach_disk": attach_disk,
            "detach_disk": detach_disk,
            // V86.usb_devices: each device's port, whether it is in, the
            // controller that has it and its speed in Mbit/s
            "device_list": () => Array.from(devices, ([id, { device, port }]) => ({
                "id": id,
                "port": port,
                "plugged": controller.devices[port] === device,
                "controller": xhci ? "xhci" : ehci && controller.owns(port) ? "ehci" : "uhci",
                "speed": [1.5, 12, 480, 5000][device.speed],
            })),
            "reset": () => ehci || xhci ? controller.reset_all() : controller.reset(),
            "get_state": () => [controller.get_state(), tablet ? tablet.get_state() : null,
                Array.from(devices, ([id, { port }]) => controller.devices[port] ? id : null).filter(Boolean),
                Array.from(devices, ([id, { device, port, backend }]) => backend ? [id, port, device.get_state()] : null).filter(Boolean)],
            "set_state": state =>
            {
                controller.set_state(state[0]);
                const saved_disks = new Map((state[3] || []).map(disk => [disk[0], disk]));
                const arriving = [];
                for(const [id, { device, port, backend }] of devices)
                {
                    const saved = saved_disks.get(id);
                    if(!backend || saved && saved[1] === port)
                    {
                        controller.devices[port] = state[2].includes(id) ? device : null;
                        if(saved) device.set_state(saved[2]);
                    }
                    else
                    {
                        controller.devices[port] = null;
                        arriving.push([port, device]);
                    }
                }
                if(tablet && state[1]) tablet.set_state(state[1]);
                // (EHCI: each device on the side its port's owner had)
                if(ehci) controller.restore_routing();
                // a disk the snapshot does not have (there): it arrives now
                for(const [port, device] of arriving) controller.attach(port, device);
                // a device the snapshot had that this machine has not: it leaves now
                for(let port = 0; port < PORTS; port++)
                {
                    if(!controller.devices[port] && controller.port_connected(port)) controller.attach(port, null);
                }
            },
        };
    },
});

/**
 * The page's pointer to the tablet: its absolute position, buttons and
 * wheel while the guest has the tablet configured and the pointer is not
 * locked (locked, the pointer is relative: the PS/2 mouse's). The tablet's
 * use is announced ("usb-tablet-active"), so that the PS/2 mouse and the
 * VMware backdoor leave the pointer to it.
 * @param {UsbMachine} machine
 * @param {HIDTablet} tablet
 */
function connect_pointer(machine, tablet)
{
    let locked = false;
    const active = () => tablet.in_use && !locked;
    tablet.on_use = in_use => machine.send("usb-tablet-active", in_use);
    // (the middle of the page's pixel: guests take the pixel a position falls
    // in, and the pixel's left or top edge would round into its neighbour)
    machine.on("mouse-absolute", data =>
    {
        if(active() && data[2] > 0 && data[3] > 0) tablet.move((data[0] + 0.5) / data[2], (data[1] + 0.5) / data[3]);
    });
    machine.on("mouse-click", data => { if(active()) tablet.press(!!data[0], !!data[1], !!data[2]); });
    machine.on("mouse-wheel", data => { if(active()) tablet.scroll(data[0] | 0); });
    machine.on("mouse-pointer-lock", value =>
    {
        locked = !!value;
        // (the buttons held go up: the other path has them from now on)
        if(locked) tablet.press(false, false, false);
    });
}
                                                                                                                                                                                                    source/v64/src/usb/uhci.js                                                                          0000644 0000000 0000000 00000053655 00000000000 012550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A UHCI USB 1.1 host controller (Intel's Universal Host Controller
// Interface, revision 1.1): PIIX3's (8086:7020) on i440FX, ICH9's first
// (8086:2934) on Q35, as QEMU's piix3-usb-uhci and ich9-usb-uhci1, or one of
// ICH9's three companions of EHCI (ehci.js); Windows binds usbport.inf by
// its class (PCI\CC_0C0300), Linux uhci-hcd. Two root ports, the 32 I/O
// ports of BAR4, INTx.
//
// While it runs, a frame of 1 ms of the machine clock is processed at a
// time: the frame list's entry, its queue heads (QH) and transfer
// descriptors (TD) in guest memory, each TD a transaction with the device at
// its address (usb_device.js). Frames that fall due while the timer was late
// are caught up a few at a time, up to a budget: the interrupt endpoints'
// polling only NAKs meanwhile. A frame has a budget of TDs and bytes, and a
// queue head visited again without progress ends it (the full-speed
// bandwidth reclamation loop of the drivers' schedules).

import { LOG_PCI } from "../const.js";
import { h } from "../lib.js";
import { dbg_log } from "../log.js";
import { PID_IN, PID_OUT, PID_SETUP, SPEED_LOW, USB_NAK, USB_STALL } from "./usb.js";

const IO_SIZE = 32;
export const PORTS = 2;

/** The controller of each machine: [device, revision, interrupt pin] */
const IDENTITY = { "i440fx": [0x7020, 0x01, 4], "q35": [0x2934, 0x03, 1] };
/** EHCI's companions (functions 0, 1, 2 of its device): ICH9's UHCI1 to 3 */
export const COMPANION_IDENTITY = [[0x2934, 0x03, 1], [0x2935, 0x03, 2], [0x2936, 0x03, 3]];
const PCI_VENDOR = 0x8086;
const PCI_SUBSYSTEM_VENDOR = 0x1AF4, PCI_SUBSYSTEM = 0x1100;

// registers (offsets in the I/O window)
const R_USBCMD = 0x00, R_USBSTS = 0x02, R_USBINTR = 0x04, R_FRNUM = 0x06, R_FLBASEADD = 0x08, R_SOFMOD = 0x0C,
    R_PORTSC1 = 0x10;

const CMD_RS = 1 << 0, CMD_HCRESET = 1 << 1, CMD_GRESET = 1 << 2, CMD_EGSM = 1 << 3, CMD_FGR = 1 << 4, CMD_MASK = 0xFF;
const STS_USBINT = 1 << 0, STS_ERROR = 1 << 1, STS_RD = 1 << 2, STS_HSE = 1 << 3, STS_HCPE = 1 << 4, STS_HALTED = 1 << 5;
const INTR_TIMEOUT_CRC = 1 << 0, INTR_RESUME = 1 << 1, INTR_IOC = 1 << 2, INTR_SHORT = 1 << 3;

// (bits 5:4, the line status, read J for a full-speed device that is there)
const PORT_CCS = 1 << 0, PORT_CSC = 1 << 1, PORT_PE = 1 << 2, PORT_PEC = 1 << 3, PORT_RD = 1 << 6, PORT_RESERVED = 1 << 7, PORT_LSDA = 1 << 8, PORT_PR = 1 << 9, PORT_SUSPEND = 1 << 12;
const PORT_WRITE_CLEAR = PORT_CSC | PORT_PEC;
const PORT_WRITABLE = PORT_PE | PORT_RD | PORT_PR | PORT_SUSPEND;

// link pointers
const LINK_TERMINATE = 1, LINK_QH = 2, LINK_DEPTH = 4;
// a TD's control and status
const TD_ACTLEN = 0x7FF, TD_BITSTUFF = 1 << 17, TD_CRC_TIMEOUT = 1 << 18, TD_NAK = 1 << 19, TD_BABBLE = 1 << 20,
    TD_BUFFER_ERROR = 1 << 21, TD_STALLED = 1 << 22, TD_ACTIVE = 1 << 23, TD_IOC = 1 << 24, TD_ERRORS_SHIFT = 27,
    TD_SPD = 1 << 29;
const TD_STATUS = TD_BITSTUFF | TD_CRC_TIMEOUT | TD_NAK | TD_BABBLE | TD_BUFFER_ERROR | TD_STALLED;

// What a TD's processing leads to
const TD_COMPLETE = 0, TD_NEXT_QH = 1;

/** Per frame at most this many TDs and bytes; per timer round at most this many frames */
const FRAME_TDS = 256;
const FRAME_BYTES = 16 * 1024;
const FRAMES_PER_ROUND = 16;
/** Frames further behind than this are skipped (the clock jumped, the host stalled) */
const FRAMES_BEHIND = 100;

/**
 * @constructor
 * @param {!Object} machine the plugin's machine (src/usb/machine.js), or a function's
 * @param {Array<number>=} identity [device, revision, interrupt pin] (a companion's); the machine's by default
 * @param {boolean=} multifunction function 0 of a device of several (EHCI's)
 */
export function UHCIController(machine, identity, multifunction)
{
    this.machine = machine;
    this.name = "uhci";
    /** @type {!Array<?Object>} the device on each root port */
    this.devices = new Array(PORTS).fill(null);
    this.irq_level = false;

    this.io_base = machine.allocate_io(IO_SIZE);
    this.reset();
    this.register_ports();

    const [device, revision, pin] = identity || IDENTITY[machine.machine_type] || IDENTITY["i440fx"];
    const space = create_pci_space(device, revision, pin, this.io_base);
    if(multifunction) space[0x0E] = 0x80;
    machine.register_pci({
        pci_space: space,
        pci_bars: [null, null, null, null, { size: IO_SIZE, on_move: undefined }],
        on_command_change: () => { this.update_irq(); },
        on_config_restore: () => {},
        on_upstream_change: () => {},
        on_config_write: () => {},
    });
    machine.add_timer(now => this.timer(now));
}

/**
 * @param {number} device
 * @param {number} revision
 * @param {number} pin
 * @param {number} io_base
 * @return {!Array<number>}
 */
function create_pci_space(device, revision, pin, io_base)
{
    const space = new Array(256).fill(0);
    const put16 = (offset, value) => { space[offset] = value & 0xFF; space[offset + 1] = value >> 8 & 0xFF; };
    put16(0x00, PCI_VENDOR);
    put16(0x02, device);
    put16(0x06, 0x0280);
    space[0x08] = revision;
    // class 0C/03/00: a UHCI USB controller
    space[0x0A] = 0x03;
    space[0x0B] = 0x0C;
    // BAR4: the I/O ports
    put16(0x20, io_base | 1);
    put16(0x2C, PCI_SUBSYSTEM_VENDOR);
    put16(0x2E, PCI_SUBSYSTEM);
    space[0x3D] = pin;
    // SBRN: USB 1.0; LEGSUP: the PIRQ enabled, no legacy support traps (v86 has no USB SMI)
    space[0x60] = 0x10;
    put16(0xC0, 0x2000);
    return space;
}

/** Everything to its reset value (power on, HCRESET) */
UHCIController.prototype.reset = function()
{
    this.cmd = 0;
    this.status = STS_HALTED;
    /** what set USBINT: 1 IOC, 2 a short packet */
    this.status2 = 0;
    this.intr = 0;
    this.frnum = 0;
    this.flbase = 0;
    this.sofmod = 64;
    this.portsc = new Array(PORTS).fill(0);
    /** the machine time of the next frame (while running) */
    this.next_frame = 0;
    for(let i = 0; i < PORTS; i++)
    {
        if(this.devices[i])
        {
            this.devices[i].reset();
            this.portsc[i] = PORT_CCS | PORT_CSC | (this.devices[i].speed === SPEED_LOW ? PORT_LSDA : 0);
        }
    }
    this.update_irq();
};

/**
 * @param {number} port
 * @return {boolean} whether the port has a device connected (as the guest sees it)
 */
UHCIController.prototype.port_connected = function(port)
{
    return !!(this.portsc[port] & PORT_CCS);
};

/**
 * Plug a device into a root port (or take it out: null)
 * @param {number} port
 * @param {?Object} device
 */
UHCIController.prototype.attach = function(port, device)
{
    this.devices[port] = device;
    if(device)
    {
        device.reset();
        this.portsc[port] = this.portsc[port] & ~(PORT_LSDA | PORT_PE) | PORT_CCS | PORT_CSC | (device.speed === SPEED_LOW ? PORT_LSDA : 0);
    }
    else
    {
        this.portsc[port] = this.portsc[port] & ~(PORT_CCS | PORT_PE | PORT_LSDA) | PORT_CSC | (this.portsc[port] & PORT_PE ? PORT_PEC : 0);
    }
    // (a connect while the bus is suspended is a resume)
    if(this.cmd & CMD_EGSM)
    {
        this.status |= STS_RD;
        this.update_irq();
    }
};

UHCIController.prototype.register_ports = function()
{
    const machine = this.machine;
    for(let offset = 0; offset < IO_SIZE; offset++)
    {
        machine.register_read(this.io_base + offset, this,
            function() { return this.read(offset, 1); },
            function() { return this.read(offset, 2); },
            function() { return this.read(offset, 4); });
        machine.register_write(this.io_base + offset, this,
            function(value) { this.write(offset, 1, value); },
            function(value) { this.write(offset, 2, value); },
            function(value) { this.write(offset, 4, value); });
    }
};

/**
 * A register's value
 * @param {number} offset
 * @return {number}
 */
UHCIController.prototype.register = function(offset)
{
    switch(offset)
    {
        case R_USBCMD: return this.cmd;
        case R_USBSTS: return this.status;
        case R_USBINTR: return this.intr;
        case R_FRNUM: return this.frnum;
        case R_FLBASEADD: return this.flbase;
        case R_SOFMOD: return this.sofmod;
    }
    if(offset >= R_PORTSC1 && offset < R_PORTSC1 + 2 * PORTS)
    {
        const port = offset - R_PORTSC1 >> 1;
        // (bit 7 always reads 1: drivers count the ports by it)
        return this.portsc[port] | PORT_RESERVED | (this.portsc[port] & PORT_CCS && !(this.portsc[port] & PORT_LSDA) ? 1 << 4 : 0);
    }
    return 0;
};

/** The registers by first byte: [size] */
const SIZES = new Map([[R_USBCMD, 2], [R_USBSTS, 2], [R_USBINTR, 2], [R_FRNUM, 2], [R_FLBASEADD, 4], [R_SOFMOD, 1]]);
for(let i = 0; i < PORTS; i++) SIZES.set(R_PORTSC1 + 2 * i, 2);

/**
 * @param {number} offset
 * @return {Array<number>} [first byte, size] of the register the byte is in
 */
function register_at(offset)
{
    for(const [start, size] of SIZES)
    {
        if(offset >= start && offset < start + size) return [start, size];
    }
    return null;
}

/**
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
UHCIController.prototype.read = function(offset, size)
{
    let value = 0;
    for(let i = 0; i < size; i++)
    {
        const at = register_at(offset + i);
        if(!at) continue;
        value |= (this.register(at[0]) >>> ((offset + i - at[0]) << 3) & 0xFF) << (i << 3);
    }
    return value >>> 0;
};

/**
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
UHCIController.prototype.write = function(offset, size, value)
{
    for(let i = 0; i < size;)
    {
        const at = register_at(offset + i);
        if(!at) { i++; continue; }
        const [start, length] = at;
        let mask = 0, bits = 0;
        for(; i < size && offset + i < start + length; i++)
        {
            const shift = (offset + i - start) << 3;
            mask |= 0xFF << shift;
            bits |= (value >>> (i << 3) & 0xFF) << shift;
        }
        this.write_register(start, bits >>> 0, mask >>> 0);
    }
};

/**
 * @param {number} offset
 * @param {number} bits
 * @param {number} mask
 */
UHCIController.prototype.write_register = function(offset, bits, mask)
{
    const merge = old => (old & ~mask | bits & mask) >>> 0;
    switch(offset)
    {
        case R_USBCMD:
        {
            const value = merge(this.cmd) & CMD_MASK;
            if(value & CMD_HCRESET)
            {
                dbg_log("uhci: host controller reset", LOG_PCI);
                this.reset();
                return;
            }
            if(value & CMD_GRESET && !(this.cmd & CMD_GRESET))
            {
                // the bus's reset: every device to its default state
                for(const device of this.devices) if(device) device.reset();
            }
            const was_running = this.cmd & CMD_RS;
            this.cmd = value;
            if(value & CMD_RS && !was_running)
            {
                this.status &= ~STS_HALTED;
                this.next_frame = this.machine.now() + 1;
            }
            else if(!(value & CMD_RS) && was_running)
            {
                this.status |= STS_HALTED;
            }
            if(value & CMD_FGR && this.status & STS_RD) this.status &= ~STS_RD;
            break;
        }
        case R_USBSTS:
            this.status &= ~(bits & mask & (STS_USBINT | STS_ERROR | STS_RD | STS_HSE | STS_HCPE));
            if(!(this.status & STS_USBINT)) this.status2 = 0;
            this.update_irq();
            break;
        case R_USBINTR:
            this.intr = merge(this.intr) & 0xF;
            this.update_irq();
            break;
        case R_FRNUM:
            // (only while halted)
            if(this.status & STS_HALTED) this.frnum = merge(this.frnum) & 0x7FF;
            break;
        case R_FLBASEADD:
            this.flbase = merge(this.flbase) & ~0xFFF;
            break;
        case R_SOFMOD:
            this.sofmod = merge(this.sofmod) & 0x7F;
            break;
        default:
            this.write_port(offset - R_PORTSC1 >> 1, bits, mask);
    }
};

/**
 * PORTSC
 * @param {number} port
 * @param {number} bits
 * @param {number} mask
 */
UHCIController.prototype.write_port = function(port, bits, mask)
{
    const old = this.portsc[port];
    const device = this.devices[port];
    let value = old & ~(bits & mask & PORT_WRITE_CLEAR);
    value = value & ~(PORT_WRITABLE & mask) | bits & mask & PORT_WRITABLE;
    if(value & PORT_PR && !(old & PORT_PR) && device)
    {
        // a port reset: the device to its default state, the port disabled
        device.reset();
        value &= ~PORT_PE;
    }
    if(!(value & PORT_CCS)) value &= ~PORT_PE;
    if(value & PORT_PR) value &= ~PORT_PE;
    this.portsc[port] = value;
};

/** INTx: the status bits USBINTR enables */
UHCIController.prototype.update_irq = function()
{
    const level = !!(this.status2 & 1 && this.intr & INTR_IOC || this.status2 & 2 && this.intr & INTR_SHORT ||
        this.status & STS_ERROR && this.intr & INTR_TIMEOUT_CRC || this.status & STS_RD && this.intr & INTR_RESUME ||
        this.status & (STS_HSE | STS_HCPE));
    if(level === this.irq_level) return;
    this.irq_level = level;
    if(level) this.machine.raise_irq();
    else this.machine.lower_irq();
};

// the schedule

/**
 * The machine's timers run: the frames due
 * @param {number} now
 * @return {number} milliseconds until it needs to run again
 */
UHCIController.prototype.timer = function(now)
{
    if(!(this.cmd & CMD_RS) || this.cmd & CMD_EGSM) return 100;
    if(now - this.next_frame > FRAMES_BEHIND)
    {
        // (far behind: the frames of the gap are not processed)
        const skipped = Math.floor(now - this.next_frame) - FRAMES_PER_ROUND;
        this.frnum = this.frnum + skipped & 0x7FF;
        this.next_frame += skipped;
    }
    for(let i = 0; i < FRAMES_PER_ROUND && now >= this.next_frame; i++)
    {
        this.process_frame();
        this.next_frame += 1;
        if(!(this.cmd & CMD_RS)) return 100;
    }
    return Math.max(0, this.next_frame - now);
};

/** One frame: its frame list entry's schedule, then FRNUM on and the interrupts */
UHCIController.prototype.process_frame = function()
{
    if(!this.machine.is_bus_master())
    {
        this.frnum = this.frnum + 1 & 0x7FF;
        return;
    }
    const entry = this.dma_read32(this.flbase + 4 * (this.frnum & 0x3FF));
    if(entry === null)
    {
        this.host_error();
        return;
    }
    let link = entry, tds = 0, interrupts = 0;
    this.frame_bytes = 0;
    /** queue heads seen in this frame: the TDs completed when last seen */
    const seen = new Map();
    let completed = 0;
    let qh = 0, qh_head = 0;
    while(!(link & LINK_TERMINATE) && tds < FRAME_TDS && this.frame_bytes < FRAME_BYTES)
    {
        if(link & LINK_QH)
        {
            qh = link & ~0xF;
            if(seen.has(qh) && seen.get(qh) === completed) break;
            seen.set(qh, completed);
            qh_head = this.dma_read32(qh);
            const element = this.dma_read32(qh + 4);
            if(qh_head === null || element === null) { this.host_error(); return; }
            if(element & LINK_TERMINATE) { link = qh_head; qh = 0; continue; }
            if(element & LINK_QH) { link = element; qh = 0; continue; }
            link = element;
        }
        const td = link & ~0xF;
        tds++;
        const result = this.process_td(td);
        if(result === null) { this.host_error(); return; }
        interrupts |= result.interrupts;
        if(result.outcome === TD_COMPLETE)
        {
            completed++;
            const next = result.link;
            if(qh)
            {
                // the queue goes on: its element the next TD
                this.dma_write32(qh + 4, next);
                if(!(next & LINK_DEPTH) || next & (LINK_TERMINATE | LINK_QH))
                {
                    link = qh_head;
                    qh = 0;
                }
                else
                {
                    link = next;
                }
            }
            else
            {
                link = next;
            }
        }
        else
        {
            link = qh ? qh_head : result.link;
            qh = 0;
        }
    }
    this.frnum = this.frnum + 1 & 0x7FF;
    if(interrupts)
    {
        this.status |= STS_USBINT;
        this.status2 |= interrupts;
        this.update_irq();
    }
};

/**
 * One TD: its transaction with the device at its address
 * @param {number} address
 * @return {?{outcome: number, link: number, interrupts: number}} null where the TD is not in memory
 */
UHCIController.prototype.process_td = function(address)
{
    const words = this.dma_read(address, 16);
    if(!words) return null;
    const view = new DataView(words.buffer);
    const link = view.getUint32(0, true);
    let control = view.getUint32(4, true);
    const token = view.getUint32(8, true), buffer = view.getUint32(12, true);
    if(!(control & TD_ACTIVE)) return { outcome: TD_NEXT_QH, link, interrupts: 0 };

    const pid = token & 0xFF, device_address = token >> 8 & 0x7F, endpoint = token >> 15 & 0xF;
    const max_length = (token >>> 21) + 1 & 0x7FF;
    const device = this.device_at(device_address);
    let interrupts = 0;
    const complete = (status, length) =>
    {
        control = control & ~(TD_STATUS | TD_ACTIVE | TD_ACTLEN) | status | (length - 1 & TD_ACTLEN);
        if(status & (TD_STALLED | TD_BABBLE | TD_CRC_TIMEOUT))
        {
            this.status |= STS_ERROR;
            this.update_irq();
        }
        if(control & TD_IOC) interrupts |= 1;
    };

    if(!device)
    {
        // no answer: a timeout, the error counter down, at 0 the TD is retired
        let errors = control >> TD_ERRORS_SHIFT & 3;
        control |= TD_CRC_TIMEOUT;
        if(errors)
        {
            errors--;
            if(!errors)
            {
                control &= ~TD_ACTIVE;
                this.status |= STS_ERROR;
                if(control & TD_IOC) interrupts |= 1;
                this.update_irq();
            }
        }
        control = control & ~(3 << TD_ERRORS_SHIFT) | errors << TD_ERRORS_SHIFT;
        this.dma_write32(address + 4, control);
        return { outcome: TD_NEXT_QH, link, interrupts };
    }

    let result;
    if(pid === PID_IN)
    {
        result = device.transaction(PID_IN, endpoint, null, max_length);
    }
    else if(pid === PID_OUT || pid === PID_SETUP)
    {
        const data = max_length ? this.dma_read(buffer, max_length) : new Uint8Array(0);
        if(!data) return null;
        result = device.transaction(pid, endpoint, data, max_length);
    }
    else
    {
        // (a PID that is not a token: the controller's process error)
        this.status |= STS_HCPE;
        this.cmd &= ~CMD_RS;
        this.status |= STS_HALTED;
        this.update_irq();
        return { outcome: TD_NEXT_QH, link, interrupts };
    }

    if(result === USB_NAK)
    {
        // (the TD stays active; it is tried again in a later frame)
        return { outcome: TD_NEXT_QH, link, interrupts };
    }
    if(result === USB_STALL)
    {
        complete(TD_STALLED, 0);
        this.dma_write32(address + 4, control);
        return { outcome: TD_NEXT_QH, link, interrupts };
    }
    let length;
    if(result instanceof Uint8Array)
    {
        if(result.length > max_length)
        {
            complete(TD_BABBLE | TD_STALLED, max_length);
            this.dma_write32(address + 4, control);
            return { outcome: TD_NEXT_QH, link, interrupts };
        }
        if(result.length) this.dma_write(result, buffer);
        length = result.length;
    }
    else
    {
        length = max_length;
    }
    this.frame_bytes += length;
    complete(0, length);
    this.dma_write32(address + 4, control);
    if(pid === PID_IN && length < max_length && control & TD_SPD)
    {
        // a short packet: the queue stops here (the driver goes on with it)
        interrupts |= 2;
        return { outcome: TD_NEXT_QH, link, interrupts };
    }
    return { outcome: TD_COMPLETE, link, interrupts };
};

/**
 * The device at an address, on an enabled port
 * @param {number} address
 * @return {?Object}
 */
UHCIController.prototype.device_at = function(address)
{
    for(let i = 0; i < PORTS; i++)
    {
        const device = this.devices[i];
        if(device && this.portsc[i] & PORT_PE && !(this.portsc[i] & PORT_SUSPEND) && device.address === address) return device;
    }
    return null;
};

/** A schedule outside memory: the controller stops (host system error) */
UHCIController.prototype.host_error = function()
{
    dbg_log("uhci: schedule outside memory (frame list " + h(this.flbase >>> 0, 8) + ")", LOG_PCI);
    this.status |= STS_HSE | STS_HALTED;
    this.cmd &= ~CMD_RS;
    this.update_irq();
};

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array}
 */
UHCIController.prototype.dma_read = function(address, length)
{
    try { return this.machine.read_physical(address, length); }
    catch(e) { return null; }
};

/**
 * @param {number} address
 * @return {?number}
 */
UHCIController.prototype.dma_read32 = function(address)
{
    try { return this.machine.read32_physical(address) >>> 0; }
    catch(e) { return null; }
};

/**
 * @param {number} address
 * @param {number} value
 */
UHCIController.prototype.dma_write32 = function(address, value)
{
    try { this.machine.write32_physical(address, value | 0); }
    catch(e) { dbg_log("uhci: write outside memory at " + h(address >>> 0, 8), LOG_PCI); }
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 */
UHCIController.prototype.dma_write = function(bytes, address)
{
    try { this.machine.write_physical(bytes, address); }
    catch(e) { dbg_log("uhci: write outside memory at " + h(address >>> 0, 8), LOG_PCI); }
};

UHCIController.prototype.get_state = function()
{
    const now = this.machine.now();
    return [this.cmd, this.status, this.status2, this.intr, this.frnum, this.flbase, this.sofmod, this.portsc.slice(),
        this.next_frame - now, +this.irq_level];
};

UHCIController.prototype.set_state = function(state)
{
    [this.cmd, this.status, this.status2, this.intr, this.frnum, this.flbase, this.sofmod] = state;
    this.portsc = state[7].slice();
    this.next_frame = this.machine.now() + state[8];
    this.irq_level = !!state[9];
    if(this.irq_level) this.machine.raise_irq();
    else this.machine.lower_irq();
};
                                                                                   source/v64/src/usb/usb.js                                                                           0000644 0000000 0000000 00000011172 00000000000 012375  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // USB: what the controllers (uhci.js, later EHCI and xHCI) and the devices
// (usb_device.js and its kinds) share: the speeds, the packets and their
// outcomes, the standard requests and descriptors (USB 2.0, chapter 9). A
// controller hands a device packets (SETUP, IN, OUT) for an endpoint; the
// device answers with data, NAK or STALL. No electrical signalling: a
// transaction is the unit.

// Device speeds (a device's descriptors may differ by speed)
export const SPEED_LOW = 0, SPEED_FULL = 1, SPEED_HIGH = 2, SPEED_SUPER = 3;

// Token PIDs, as UHCI's TDs carry them
export const PID_SETUP = 0x2D, PID_IN = 0x69, PID_OUT = 0xE1;

// A transaction's outcome: data (an IN's) or none, or a handshake that is not ACK
export const USB_NAK = -2, USB_STALL = -3, USB_NODEV = -1, USB_BABBLE = -4;

// requests (bRequest) and request types
export const REQUEST_GET_STATUS = 0x00, REQUEST_CLEAR_FEATURE = 0x01, REQUEST_SET_FEATURE = 0x03,
    REQUEST_SET_ADDRESS = 0x05, REQUEST_GET_DESCRIPTOR = 0x06, REQUEST_SET_DESCRIPTOR = 0x07,
    REQUEST_GET_CONFIGURATION = 0x08, REQUEST_SET_CONFIGURATION = 0x09, REQUEST_GET_INTERFACE = 0x0A,
    REQUEST_SET_INTERFACE = 0x0B, REQUEST_SYNCH_FRAME = 0x0C, REQUEST_SET_SEL = 0x30, REQUEST_SET_ISOCH_DELAY = 0x31;
export const TYPE_STANDARD = 0x00, TYPE_CLASS = 0x20, TYPE_VENDOR = 0x40;
export const RECIPIENT_DEVICE = 0, RECIPIENT_INTERFACE = 1, RECIPIENT_ENDPOINT = 2;
export const FEATURE_ENDPOINT_HALT = 0, FEATURE_DEVICE_REMOTE_WAKEUP = 1;

// descriptor types
export const DESCRIPTOR_DEVICE = 1, DESCRIPTOR_CONFIGURATION = 2, DESCRIPTOR_STRING = 3, DESCRIPTOR_INTERFACE = 4,
    DESCRIPTOR_ENDPOINT = 5, DESCRIPTOR_DEVICE_QUALIFIER = 6, DESCRIPTOR_OTHER_SPEED = 7, DESCRIPTOR_BOS = 0x0F,
    DESCRIPTOR_DEVICE_CAPABILITY = 0x10, DESCRIPTOR_HID = 0x21, DESCRIPTOR_REPORT = 0x22, DESCRIPTOR_SS_ENDPOINT_COMPANION = 0x30;

// endpoint types (bmAttributes)
export const ENDPOINT_CONTROL = 0, ENDPOINT_ISOCHRONOUS = 1, ENDPOINT_BULK = 2, ENDPOINT_INTERRUPT = 3;

/**
 * A setup packet's fields
 * @typedef {{type: number, request: number, value: number, index: number, length: number}}
 */
export let SetupPacket;

/**
 * @param {!Uint8Array} bytes a setup packet's 8 bytes
 * @return {SetupPacket}
 */
export function parse_setup(bytes)
{
    return {
        type: bytes[0],
        request: bytes[1],
        value: bytes[2] | bytes[3] << 8,
        index: bytes[4] | bytes[5] << 8,
        length: bytes[6] | bytes[7] << 8,
    };
}

/**
 * A device descriptor
 * @param {{usb: number, class: number, subclass: number, protocol: number, max_packet0: number, vendor: number,
 *     product: number, release: number, manufacturer: number, product_string: number, serial: number, configurations: number}} d
 * @return {!Array<number>}
 */
export function device_descriptor(d)
{
    return [18, DESCRIPTOR_DEVICE, d.usb & 0xFF, d.usb >> 8, d.class, d.subclass, d.protocol, d.max_packet0,
        d.vendor & 0xFF, d.vendor >> 8, d.product & 0xFF, d.product >> 8, d.release & 0xFF, d.release >> 8,
        d.manufacturer, d.product_string, d.serial, d.configurations];
}

/**
 * A configuration descriptor with what follows it (interfaces, class
 * descriptors, endpoints), its total length filled in
 * @param {{value: number, attributes: number, max_power: number, interfaces: number}} c
 * @param {!Array<!Array<number>>} parts
 * @return {!Array<number>}
 */
export function configuration_descriptor(c, parts)
{
    const rest = [].concat(...parts);
    const total = 9 + rest.length;
    return [9, DESCRIPTOR_CONFIGURATION, total & 0xFF, total >> 8, c.interfaces, c.value, 0, c.attributes, c.max_power, ...rest];
}

/**
 * @param {{number: number, alternate: number, endpoints: number, class: number, subclass: number, protocol: number}} i
 * @return {!Array<number>}
 */
export function interface_descriptor(i)
{
    return [9, DESCRIPTOR_INTERFACE, i.number, i.alternate, i.endpoints, i.class, i.subclass, i.protocol, 0];
}

/**
 * @param {{address: number, type: number, max_packet: number, interval: number}} e
 * @return {!Array<number>}
 */
export function endpoint_descriptor(e)
{
    return [7, DESCRIPTOR_ENDPOINT, e.address, e.type, e.max_packet & 0xFF, e.max_packet >> 8, e.interval];
}

/**
 * A string descriptor (UTF-16LE); index 0 is the list of languages
 * @param {string} text
 * @return {!Array<number>}
 */
export function string_descriptor(text)
{
    const bytes = [2 + 2 * text.length, DESCRIPTOR_STRING];
    for(let i = 0; i < text.length; i++)
    {
        const code = text.charCodeAt(i);
        bytes.push(code & 0xFF, code >> 8);
    }
    return bytes;
}

/** The languages: US English */
export const LANGUAGES = [4, DESCRIPTOR_STRING, 0x09, 0x04];
                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/usb/usb_device.js                                                                    0000644 0000000 0000000 00000036414 00000000000 013722  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A USB device as the controllers see it (usb.js): an address, a
// configuration, endpoint 0's control transfers (setup, data and status
// stages, a new SETUP ending one that was under way) with the standard
// requests, and the other endpoints' transactions, which the device's kind
// (hid_tablet.js, mass_storage.js) answers. Halted endpoints STALL until
// CLEAR_FEATURE(ENDPOINT_HALT). Speeds are the device's: it runs at one of
// them, the port's (EHCI's high speed, a UHCI companion's full speed, an
// xHCI USB 3 port's SuperSpeed), and answers with that speed's
// configurations; a device of full and high speed describes the other in
// its device qualifier and other speed configuration; at SuperSpeed its
// device descriptor is USB 3's and it has a BOS.

import {
    DESCRIPTOR_CONFIGURATION, DESCRIPTOR_DEVICE, DESCRIPTOR_DEVICE_QUALIFIER, DESCRIPTOR_OTHER_SPEED, DESCRIPTOR_STRING,
    FEATURE_DEVICE_REMOTE_WAKEUP,
    FEATURE_ENDPOINT_HALT, LANGUAGES, PID_IN, PID_OUT, PID_SETUP, RECIPIENT_DEVICE, RECIPIENT_ENDPOINT,
    RECIPIENT_INTERFACE, REQUEST_CLEAR_FEATURE, SetupPacket, REQUEST_GET_CONFIGURATION, REQUEST_GET_DESCRIPTOR,
    REQUEST_GET_INTERFACE, REQUEST_GET_STATUS, REQUEST_SET_ADDRESS, REQUEST_SET_CONFIGURATION,
    REQUEST_SET_FEATURE, REQUEST_SET_INTERFACE, REQUEST_SET_ISOCH_DELAY, REQUEST_SET_SEL, SPEED_FULL, SPEED_HIGH, SPEED_SUPER,
    TYPE_STANDARD, USB_NAK, USB_STALL, parse_setup, DESCRIPTOR_BOS,
    string_descriptor,
} from "./usb.js";

// endpoint 0's stages
const STAGE_IDLE = 0, STAGE_DATA_IN = 1, STAGE_DATA_OUT = 2, STAGE_STATUS_IN = 3, STAGE_STALLED = 4;

/**
 * @constructor
 * @param {{name: string, speeds: (!Array<number>|undefined), device: !Array<number>, configurations: !Array<!Array<number>>,
 *     high_configurations: (!Array<!Array<number>>|undefined), super_device: (!Array<number>|undefined),
 *     super_configurations: (!Array<!Array<number>>|undefined), bos: (!Array<number>|undefined), strings: !Array<string>,
 *     endpoints: !Array<number>}} d
 *     the device's descriptors: the device descriptor, each configuration's (with its interfaces and
 *     endpoints) at full speed and, for a high-speed device, at high speed; for a SuperSpeed one its
 *     USB 3 device descriptor, configurations and BOS; the strings (index 1 on), the addresses of its
 *     endpoints other than 0
 */
export function USBDevice(d)
{
    this.name = d.name;
    /** The speeds the device runs at (full speed, and high), and the one it runs at */
    this.speeds = d.speeds || [SPEED_FULL];
    this.speed = this.speeds[0];
    this.descriptors = d;
    this.max_packet0 = d.device[7];
    this.set_speed(this.speed);
    this.endpoint_addresses = d.endpoints;
    this.reset();
}

/** A bus reset (the port's): the default state, address 0, not configured */
USBDevice.prototype.reset = function()
{
    this.address = 0;
    this.configuration = 0;
    this.alternates = [0];
    this.remote_wakeup = false;
    /** @type {!Set<number>} halted endpoint addresses */
    this.halted = new Set();
    this.stage = STAGE_IDLE;
    /** @type {?SetupPacket} */
    this.setup = null;
    this.control_data = new Uint8Array(0);
    this.control_offset = 0;
    this.out_data = [];
    this.out_length = 0;
    this.pending_address = -1;
};

/**
 * A transaction for this device (its address matched)
 * @param {number} pid PID_SETUP, PID_IN, PID_OUT
 * @param {number} endpoint 0 to 15
 * @param {Uint8Array} data SETUP's and OUT's bytes
 * @param {number} max_length IN: at most this many bytes
 * @return {!Uint8Array|number} IN: the bytes; SETUP, OUT: 0 (ACK); or USB_NAK, USB_STALL
 */
USBDevice.prototype.transaction = function(pid, endpoint, data, max_length)
{
    if(endpoint === 0) return this.control(pid, data, max_length);
    const address = endpoint | (pid === PID_IN ? 0x80 : 0);
    if(!this.configuration || !this.endpoint_addresses.includes(address) || pid === PID_SETUP) return USB_STALL;
    if(this.halted.has(address)) return USB_STALL;
    return pid === PID_IN ? this.data_in(endpoint, max_length) : this.data_out(endpoint, /** @type {!Uint8Array} */ (data));
};

/**
 * Endpoint 0
 * @param {number} pid
 * @param {Uint8Array} data
 * @param {number} max_length
 * @return {!Uint8Array|number}
 */
USBDevice.prototype.control = function(pid, data, max_length)
{
    if(pid === PID_SETUP)
    {
        // (a new SETUP ends any transfer under way)
        if(!data || data.length !== 8) return USB_STALL;
        const setup = this.setup = parse_setup(data);
        this.pending_address = -1;
        if(setup.type & 0x80)
        {
            const result = this.request(setup, null);
            if(result === USB_STALL)
            {
                this.stage = STAGE_STALLED;
            }
            else
            {
                this.control_data = /** @type {!Uint8Array} */ (result).subarray(0, setup.length);
                this.control_offset = 0;
                this.stage = STAGE_DATA_IN;
            }
        }
        else if(setup.length)
        {
            this.out_data = [];
            this.out_length = 0;
            this.stage = STAGE_DATA_OUT;
        }
        else
        {
            // (the request runs at its status stage: SET_ADDRESS takes effect after it)
            this.stage = STAGE_STATUS_IN;
        }
        return 0;
    }
    if(this.stage === STAGE_STALLED) return USB_STALL;
    if(pid === PID_IN)
    {
        if(this.stage === STAGE_DATA_IN)
        {
            const length = Math.min(max_length, this.max_packet0, this.control_data.length - this.control_offset);
            const chunk = this.control_data.slice(this.control_offset, this.control_offset + length);
            this.control_offset += length;
            return chunk;
        }
        if(this.stage === STAGE_STATUS_IN)
        {
            const result = this.request(/** @type {SetupPacket} */ (this.setup), concat(this.out_data, this.out_length));
            if(result === USB_STALL)
            {
                this.stage = STAGE_STALLED;
                return USB_STALL;
            }
            this.stage = STAGE_IDLE;
            if(this.pending_address >= 0)
            {
                this.address = this.pending_address;
                this.pending_address = -1;
            }
            return new Uint8Array(0);
        }
        return USB_STALL;
    }
    if(pid === PID_OUT)
    {
        if(this.stage === STAGE_DATA_OUT)
        {
            const bytes = /** @type {!Uint8Array} */ (data);
            this.out_data.push(bytes.slice());
            this.out_length += bytes.length;
            if(this.out_length >= this.setup.length) this.stage = STAGE_STATUS_IN;
            return 0;
        }
        if(this.stage === STAGE_DATA_IN)
        {
            // the status stage of a transfer to the host (also before all its data was read)
            this.stage = STAGE_IDLE;
            return 0;
        }
        return USB_STALL;
    }
    return USB_STALL;
};

/**
 * @param {!Array<!Uint8Array>} parts
 * @param {number} length
 * @return {!Uint8Array}
 */
function concat(parts, length)
{
    const bytes = new Uint8Array(length);
    let at = 0;
    for(const part of parts) { bytes.set(part, at); at += part.length; }
    return bytes;
}

/**
 * A control request: its data to the host, an empty array, or USB_STALL
 * @param {SetupPacket} setup
 * @param {Uint8Array} data the data stage's bytes, to the device
 * @return {!Uint8Array|number}
 */
USBDevice.prototype.request = function(setup, data)
{
    if((setup.type & 0x60) !== TYPE_STANDARD) return this.class_request(setup, data);
    const recipient = setup.type & 0x1F;
    switch(setup.request)
    {
        case REQUEST_GET_STATUS:
            if(recipient === RECIPIENT_DEVICE) return Uint8Array.of(this.self_powered() | (this.remote_wakeup ? 2 : 0), 0);
            if(recipient === RECIPIENT_ENDPOINT) return Uint8Array.of(this.halted.has(setup.index & 0x8F) ? 1 : 0, 0);
            return new Uint8Array(2);
        case REQUEST_CLEAR_FEATURE:
        case REQUEST_SET_FEATURE:
        {
            const set = setup.request === REQUEST_SET_FEATURE;
            if(recipient === RECIPIENT_DEVICE && setup.value === FEATURE_DEVICE_REMOTE_WAKEUP)
            {
                this.remote_wakeup = set;
                return new Uint8Array(0);
            }
            if(recipient === RECIPIENT_ENDPOINT && setup.value === FEATURE_ENDPOINT_HALT)
            {
                const endpoint = setup.index & 0x8F;
                if(endpoint & 0xF && !this.endpoint_addresses.includes(endpoint)) return USB_STALL;
                if(set && endpoint & 0xF) this.halted.add(endpoint);
                else
                {
                    this.halted.delete(endpoint);
                    this.halt_cleared(endpoint);
                }
                return new Uint8Array(0);
            }
            return USB_STALL;
        }
        case REQUEST_SET_ADDRESS:
            if(setup.value > 127) return USB_STALL;
            this.pending_address = setup.value;
            return new Uint8Array(0);
        case REQUEST_GET_DESCRIPTOR:
        {
            const bytes = recipient === RECIPIENT_INTERFACE ? this.interface_descriptor(setup.value >> 8, setup.value & 0xFF, setup.index) :
                this.descriptor(setup.value >> 8, setup.value & 0xFF, setup.index);
            return bytes ? Uint8Array.from(bytes) : USB_STALL;
        }
        case REQUEST_GET_CONFIGURATION:
            return Uint8Array.of(this.configuration);
        case REQUEST_SET_CONFIGURATION:
        {
            const value = setup.value & 0xFF;
            if(value && !this.configurations(this.speed).some(c => c[5] === value)) return USB_STALL;
            this.configuration = value;
            this.alternates = [0];
            this.halted.clear();
            this.configured(value);
            return new Uint8Array(0);
        }
        case REQUEST_GET_INTERFACE:
            if(!this.configuration) return USB_STALL;
            return Uint8Array.of(this.alternates[setup.index] || 0);
        case REQUEST_SET_INTERFACE:
            if(!this.configuration || setup.value !== 0) return USB_STALL;
            this.alternates[setup.index] = 0;
            return new Uint8Array(0);
        case REQUEST_SET_SEL:
        case REQUEST_SET_ISOCH_DELAY:
            // (USB 3's system exit latencies and isochronous delay: taken; the
            // device has no U1/U2 link states and no isochronous endpoints)
            return this.speed === SPEED_SUPER ? new Uint8Array(0) : USB_STALL;
    }
    return USB_STALL;
};

/**
 * A standard descriptor
 * @param {number} type
 * @param {number} index
 * @param {number} language
 * @return {Array<number>}
 */
USBDevice.prototype.descriptor = function(type, index, language)
{
    switch(type)
    {
        case DESCRIPTOR_DEVICE:
            return this.speed === SPEED_SUPER && this.descriptors.super_device || this.descriptors.device;
        case DESCRIPTOR_BOS:
            return this.descriptors.bos || null;
        case DESCRIPTOR_CONFIGURATION:
            return this.configurations(this.speed)[index] || null;
        case DESCRIPTOR_STRING:
            if(index === 0) return LANGUAGES;
            return index <= this.descriptors.strings.length ? string_descriptor(this.descriptors.strings[index - 1]) : null;
        case DESCRIPTOR_DEVICE_QUALIFIER:
        {
            // the device at the other speed (a full-speed only device STALLs
            // it, and so does one at SuperSpeed)
            if(!this.speeds.includes(SPEED_HIGH) || this.speed === SPEED_SUPER) return null;
            const d = this.descriptors.device;
            return [10, DESCRIPTOR_DEVICE_QUALIFIER, d[2], d[3], d[4], d[5], d[6], d[7], d[17], 0];
        }
        case DESCRIPTOR_OTHER_SPEED:
        {
            if(!this.speeds.includes(SPEED_HIGH) || this.speed === SPEED_SUPER) return null;
            const other = this.configurations(this.speed === SPEED_HIGH ? SPEED_FULL : SPEED_HIGH)[index];
            return other ? [other[0], DESCRIPTOR_OTHER_SPEED].concat(other.slice(2)) : null;
        }
    }
    return null;
};

/**
 * The configurations' descriptors at a speed
 * @param {number} speed
 * @return {!Array<!Array<number>>}
 */
USBDevice.prototype.configurations = function(speed)
{
    if(speed === SPEED_SUPER && this.descriptors.super_configurations) return this.descriptors.super_configurations;
    return speed >= SPEED_HIGH && this.descriptors.high_configurations ? this.descriptors.high_configurations : this.descriptors.configurations;
};

/**
 * The port's speed (EHCI's high speed, or a companion's full speed): the
 * device runs at it from its next bus reset on
 * @param {number} speed
 */
USBDevice.prototype.set_speed = function(speed)
{
    if(!this.speeds.includes(speed)) return;
    this.speed = speed;
    // (endpoint 0's packets: 512 bytes at SuperSpeed, its device descriptor's 2^9)
    this.max_packet0 = speed === SPEED_SUPER ? 512 : this.descriptors.device[7];
};

/**
 * A class descriptor of an interface (HID's): none by default
 * @param {number} type
 * @param {number} index
 * @param {number} interface_number
 * @return {Array<number>}
 */
USBDevice.prototype.interface_descriptor = function(type, index, interface_number)
{
    return null;
};

/** @return {number} GET_STATUS's self-powered bit */
USBDevice.prototype.self_powered = function()
{
    return 0;
};

/**
 * A class or vendor request: STALL by default
 * @param {SetupPacket} setup
 * @param {Uint8Array} data
 * @return {!Uint8Array|number}
 */
USBDevice.prototype.class_request = function(setup, data)
{
    return USB_STALL;
};

/**
 * SET_CONFIGURATION
 * @param {number} value 0: back to the address state
 */
USBDevice.prototype.configured = function(value) {};

/** @param {number} endpoint CLEAR_FEATURE(ENDPOINT_HALT) of this endpoint */
USBDevice.prototype.halt_cleared = function(endpoint) {};

/**
 * An IN transaction of an endpoint other than 0: NAK by default
 * @param {number} endpoint
 * @param {number} max_length
 * @return {!Uint8Array|number}
 */
USBDevice.prototype.data_in = function(endpoint, max_length)
{
    return USB_NAK;
};

/**
 * An OUT transaction of an endpoint other than 0
 * @param {number} endpoint
 * @param {!Uint8Array} data
 * @return {number} 0, or USB_NAK, USB_STALL
 */
USBDevice.prototype.data_out = function(endpoint, data)
{
    return USB_STALL;
};

/** The device's part of a snapshot (its kind adds its own) */
USBDevice.prototype.get_state = function()
{
    return [this.address, this.configuration, this.alternates.slice(), +this.remote_wakeup, Array.from(this.halted),
        this.stage, this.setup ? [this.setup.type, this.setup.request, this.setup.value, this.setup.index, this.setup.length] : null,
        this.control_data, this.control_offset, concat(this.out_data, this.out_length), this.pending_address, this.speed];
};

USBDevice.prototype.set_state = function(state)
{
    [this.address, this.configuration] = state;
    this.alternates = state[2].slice();
    this.remote_wakeup = !!state[3];
    this.halted = new Set(state[4]);
    this.stage = state[5];
    this.setup = state[6] ? { type: state[6][0], request: state[6][1], value: state[6][2], index: state[6][3], length: state[6][4] } : null;
    this.control_data = state[7];
    this.control_offset = state[8];
    this.out_data = state[9].length ? [state[9]] : [];
    this.out_length = state[9].length;
    this.pending_address = state[10];
    if(state[11] !== undefined) this.set_speed(state[11]);
};
                                                                                                                                                                                                                                                    source/v64/src/usb/xhci.js                                                                          0000644 0000000 0000000 00000146216 00000000000 012547  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // An xHCI USB 3 host controller (eXtensible Host Controller Interface 1.2),
// as QEMU's qemu-xhci (1B36:000D, class 0C/03/30): Windows 8 and later bind
// usbxhci.inf by the class, Linux xhci-pci. Four physical ports, each a USB 3
// root port (1 to 4: a SuperSpeed device) and a USB 2 one (5 to 8: the
// others), 32 device slots, one interrupter (single-vector MSI, or INTA),
// 32-byte contexts, 4 KiB pages, no scratchpad, 64-bit addresses. BAR0 is
// 16 KiB of memory (32-bit: v86's PC host has no 64-bit BARs): the
// capability registers, the operational ones with the ports at 0x400, the
// runtime ones at 0x1000, the doorbells at 0x2000, the extended
// capabilities at 0x3000 (USB legacy support, the two supported protocols).
//
// The driver gives the controller rings of TRBs in guest memory: the
// command ring (doorbell 0, executed at once: slots, contexts, endpoints),
// a transfer ring per endpoint (its doorbell starts it: TDs of Setup, Data,
// Status, Normal and Event Data TRBs, each transaction with the device at
// the slot's port, max packet at a time), and an event ring the controller
// writes (command completions, transfer events, port status changes).
// Transfers a device NAKs are tried again each millisecond of the machine
// clock, as are endpoints with more to do than a doorbell's budget. Not
// emulated: hubs (route strings), streams, isochronous transfers, U1/U2,
// the debug capability, more interrupters, MSI-X.

import { LOG_PCI } from "../const.js";
import { h } from "../lib.js";
import { dbg_log } from "../log.js";
import { PID_IN, PID_OUT, PID_SETUP, SPEED_FULL, SPEED_HIGH, SPEED_LOW, SPEED_SUPER, USB_NAK, USB_STALL } from "./usb.js";

const MMIO_SIZE = 0x4000;
const OP = 0x40, PORTS_BASE = OP + 0x400, RUNTIME = 0x1000, DOORBELLS = 0x2000, XECP = 0x3000;
/** Physical ports: each a USB 3 root port (1 to 4) and a USB 2 one (5 to 8) */
export const XHCI_PORTS = 4;
const ROOT_PORTS = 2 * XHCI_PORTS, USB3_FIRST = 1, USB2_FIRST = XHCI_PORTS + 1;
const MAX_SLOTS = 32;

const PCI_VENDOR = 0x1B36, PCI_DEVICE = 0x000D, PCI_REVISION = 0x01;
const PCI_SUBSYSTEM_VENDOR = 0x1AF4, PCI_SUBSYSTEM = 0x1100;
const PM_CAP = 0x50, MSI_CAP = 0x70;
// power management 1.2, D0 and D3hot
const PM_PMC = 0x0003;

// capability registers: 32 slots, 1 interrupter, 8 ports; IST (a frame),
// one event ring segment, no scratchpad; 64-bit, 32-byte contexts, the
// extended capabilities
const HCSPARAMS1 = MAX_SLOTS | 1 << 8 | ROOT_PORTS << 24;
const HCSPARAMS2 = 0x0000000F;
const HCCPARAMS1 = 1 | (XECP >> 2) << 16;
// extended capabilities: USB legacy support, then USB 3 and USB 2
const LEGSUP_BIOS_OWNED = 1 << 16, LEGSUP_OS_OWNED = 1 << 24;
const EXTENDED = [
    [1 | 4 << 8, 0],
    [2 | 4 << 8 | 0x03 << 24, 0x20425355, USB3_FIRST | XHCI_PORTS << 8, 0],
    [2 | 0x02 << 24, 0x20425355, USB2_FIRST | XHCI_PORTS << 8, 0],
];

// operational registers (from OP)
const R_USBCMD = 0x00, R_USBSTS = 0x04, R_PAGESIZE = 0x08, R_DNCTRL = 0x14, R_CRCR = 0x18, R_CRCR_HIGH = 0x1C, R_DCBAAP = 0x30,
    R_DCBAAP_HIGH = 0x34, R_CONFIG = 0x38;
const CMD_RS = 1 << 0, CMD_HCRST = 1 << 1, CMD_INTE = 1 << 2, CMD_CSS = 1 << 8, CMD_CRS = 1 << 9, CMD_MASK = 0x3F0F;
const STS_HCH = 1 << 0, STS_HSE = 1 << 2, STS_EINT = 1 << 3, STS_PCD = 1 << 4, STS_SRE = 1 << 10, STS_HCE = 1 << 12;
const CRCR_RCS = 1 << 0, CRCR_CS = 1 << 1, CRCR_CA = 1 << 2, CRCR_CRR = 1 << 3;

// PORTSC
const PORT_CCS = 1 << 0, PORT_PED = 1 << 1, PORT_PR = 1 << 4, PORT_PLS_SHIFT = 5, PORT_PLS = 0xF << PORT_PLS_SHIFT, PORT_PP = 1 << 9,
    PORT_SPEED_SHIFT = 10, PORT_LWS = 1 << 16, PORT_CSC = 1 << 17, PORT_PEC = 1 << 18, PORT_WRC = 1 << 19, PORT_OCC = 1 << 20,
    PORT_PRC = 1 << 21, PORT_PLC = 1 << 22, PORT_CEC = 1 << 23, PORT_WAKE = 7 << 25, PORT_WPR = 1 << 31;
const PORT_CHANGES = PORT_CSC | PORT_PEC | PORT_WRC | PORT_OCC | PORT_PRC | PORT_PLC | PORT_CEC;
// link states
const PLS_U0 = 0, PLS_U3 = 3, PLS_DISABLED = 4, PLS_RX_DETECT = 5, PLS_POLLING = 7, PLS_RESUME = 15;
// the port's speed IDs by the device's speed (low, full, high, super)
const SPEED_IDS = [2, 1, 3, 4];

// runtime registers: MFINDEX, interrupter 0 (IMAN, IMOD, ERSTSZ, ERSTBA, ERDP)
const IMAN_IP = 1 << 0, IMAN_IE = 1 << 1;
const ERDP_EHB = 1 << 3;

// TRBs
const TRB_CYCLE = 1 << 0, TRB_TC = 1 << 1, TRB_ENT = 1 << 1, TRB_ISP = 1 << 2, TRB_CH = 1 << 4, TRB_IOC = 1 << 5, TRB_IDT = 1 << 6,
    TRB_BSR = 1 << 9, TRB_DC = 1 << 9, TRB_DIR_IN = 1 << 16;
const TRB_NORMAL = 1, TRB_SETUP = 2, TRB_DATA = 3, TRB_STATUS = 4, TRB_ISOCH = 5, TRB_LINK = 6, TRB_EVENT_DATA = 7, TRB_NOOP = 8,
    CMD_ENABLE_SLOT = 9, CMD_DISABLE_SLOT = 10, CMD_ADDRESS_DEVICE = 11, CMD_CONFIGURE_ENDPOINT = 12, CMD_EVALUATE_CONTEXT = 13,
    CMD_RESET_ENDPOINT = 14, CMD_STOP_ENDPOINT = 15, CMD_SET_TR_DEQUEUE = 16, CMD_RESET_DEVICE = 17, CMD_GET_PORT_BANDWIDTH = 21,
    CMD_NOOP = 23, EVENT_TRANSFER = 32, EVENT_COMMAND = 33, EVENT_PORT = 34, EVENT_HOST = 37;
// completion codes
const CC_SUCCESS = 1, CC_DATA_BUFFER = 2, CC_BABBLE = 3, CC_TRANSACTION = 4, CC_TRB = 5, CC_STALL = 6, CC_NO_SLOTS = 9,
    CC_SLOT_NOT_ENABLED = 11, CC_EP_NOT_ENABLED = 12, CC_SHORT_PACKET = 13, CC_PARAMETER = 17, CC_CONTEXT_STATE = 19,
    CC_EVENT_RING_FULL = 21, CC_COMMAND_RING_STOPPED = 24, CC_STOPPED = 26;
// slot and endpoint states
const SLOT_DEFAULT = 1, SLOT_ADDRESSED = 2, SLOT_CONFIGURED = 3;
const EP_DISABLED = 0, EP_RUNNING = 1, EP_HALTED = 2, EP_STOPPED = 3;
// endpoint types (an endpoint context's): 4 control; 1, 5 isochronous
const EP_CONTROL = 4, EP_ISOCH_OUT = 1, EP_ISOCH_IN = 5;

// a doorbell's budget of bytes, a millisecond's; links followed in a row; TRBs of a TD
const DOORBELL_BYTES = 64 * 1024, MS_BYTES = 1024 * 1024, LINK_LIMIT = 32, TD_TRBS = 512;

/**
 * @constructor
 * @param {!Object} machine the plugin's machine (src/usb/machine.js)
 */
export function XHCIController(machine)
{
    this.machine = machine;
    this.name = "xhci";
    /** @type {!Array<?Object>} the device in each physical port */
    this.devices = new Array(XHCI_PORTS).fill(null);
    this.irq_level = false;
    this.bar0 = 0;
    this.mmio = -1;
    this.legsup = LEGSUP_BIOS_OWNED;
    this.reset();

    const space = create_pci_space();
    machine.msi_capability(0).forEach((byte, i) => { space[MSI_CAP + i] = byte; });
    machine.register_pci({
        pci_space: space,
        pci_bars: [{ size: MMIO_SIZE, on_move: base => { this.bar0 = base; this.update_decode(); } }],
        on_command_change: () => { this.update_decode(); this.update_irq(); },
        on_config_restore: () => this.update_decode(),
        on_upstream_change: () => this.update_decode(),
        on_config_write: (offset, size) => this.config_written(offset, size),
    });
    machine.add_timer(now => this.timer(now));
}

/** @return {!Array<number>} */
function create_pci_space()
{
    const space = new Array(256).fill(0);
    const put16 = (offset, value) => { space[offset] = value & 0xFF; space[offset + 1] = value >> 8 & 0xFF; };
    put16(0x00, PCI_VENDOR);
    put16(0x02, PCI_DEVICE);
    // status: a capabilities list
    put16(0x06, 0x0010);
    space[0x08] = PCI_REVISION;
    // class 0C/03/30: an xHCI USB controller
    space[0x09] = 0x30;
    space[0x0A] = 0x03;
    space[0x0B] = 0x0C;
    put16(0x2C, PCI_SUBSYSTEM_VENDOR);
    put16(0x2E, PCI_SUBSYSTEM);
    space[0x34] = PM_CAP;
    space[0x3D] = 1;
    // SBRN: USB 3.0; FLADJ
    space[0x60] = 0x30;
    space[0x61] = 0x20;
    space[PM_CAP] = 0x01;
    space[PM_CAP + 1] = MSI_CAP;
    put16(PM_CAP + 2, PM_PMC);
    return space;
}

/** The capabilities keep their read-only bytes after the driver's writes */
XHCIController.prototype.config_written = function(offset, size)
{
    if(offset < MSI_CAP + 14 && offset + size > MSI_CAP)
    {
        this.machine.msi_config_written(MSI_CAP, 0);
        // (MSI on releases INTA; off may need it)
        this.update_irq();
    }
    if(offset < PM_CAP + 8 && offset + size > PM_CAP)
    {
        const space = this.machine.pci_config();
        const pmcsr = (space[PM_CAP + 4] | space[PM_CAP + 5] << 8) & 0x0103;
        space.set([0x01, MSI_CAP, PM_PMC & 0xFF, PM_PMC >> 8, pmcsr & 0xFF, pmcsr >> 8, 0, 0], PM_CAP);
    }
};

XHCIController.prototype.update_decode = function()
{
    const base = this.bar0 && this.machine.memory_decoded(this.bar0, MMIO_SIZE) ? this.bar0 : -1;
    if(base === this.mmio) return;
    if(this.mmio !== -1) this.machine.mmap_unregister_range(this.mmio, MMIO_SIZE);
    this.mmio = base;
    if(base !== -1)
    {
        this.machine.mmap_register_range(base, MMIO_SIZE,
            address => this.read(address - this.mmio, 1),
            (address, value) => this.write(address - this.mmio, 1, value),
            address => this.read(address - this.mmio, 4),
            (address, value) => this.write(address - this.mmio, 4, value));
    }
};

/** Everything to its reset value (power on, HCRST): slots disabled, the ports as their devices are */
XHCIController.prototype.reset = function()
{
    this.cmd = 0;
    this.status = STS_HCH;
    this.dnctrl = 0;
    this.crcr = [0, 0];
    /** the command ring: where the next command is, its cycle state, whether it runs */
    this.command_ring = { dequeue: 0, ccs: 1 };
    this.crr = false;
    this.dcbaap = [0, 0];
    this.config = 0;
    /** the interrupter's registers, the event ring (its one segment), where the next event goes */
    this.iman = 0;
    this.imod = 0;
    this.erstsz = 0;
    this.erstba = [0, 0];
    this.erdp = [0, 0];
    this.event_ring = { start: 0, size: 0, enqueue: 0, pcs: 1 };
    /** the time MFINDEX counts from; the next millisecond's transfers */
    this.mf_start = this.machine.now();
    this.next_ms = 0;
    this.budget = 0;
    /** @type {!Array<?Object>} slots 1 to MAX_SLOTS (index 0 unused) */
    this.slots = new Array(MAX_SLOTS + 1).fill(null);
    /** endpoints with transfers to go on with: "slot:dci" */
    this.active = new Set();
    this.portsc = new Array(ROOT_PORTS + 1).fill(0);
    for(let port = 0; port < XHCI_PORTS; port++) this.update_port(port, false);
    this.update_irq();
};

/** A machine reset (PCIRST#) */
XHCIController.prototype.reset_all = function()
{
    this.legsup = LEGSUP_BIOS_OWNED;
    this.reset();
    this.update_decode();
};

// ports

/**
 * The root port a physical port's device is on: USB 3 for a SuperSpeed device, USB 2 for the others
 * @param {number} port
 * @param {?Object} device
 * @return {number}
 */
function root_port(port, device)
{
    return device && device.speeds.includes(SPEED_SUPER) ? USB3_FIRST + port : USB2_FIRST + port;
}

/**
 * A physical port's root ports as its device has them: the one with the
 * device connected (a SuperSpeed device's link up and the port enabled at
 * once; the others polling, enabled by a port reset), the other empty
 * @param {number} port
 * @param {boolean} notify a Port Status Change Event where the connection changed
 */
XHCIController.prototype.update_port = function(port, notify)
{
    const device = this.devices[port];
    for(const root of [USB3_FIRST + port, USB2_FIRST + port])
    {
        const connected = !!device && root === root_port(port, device);
        const before = this.portsc[root];
        let value = PORT_PP | before & PORT_WAKE;
        if(connected)
        {
            const speed = root < USB2_FIRST ? SPEED_SUPER : device.speeds.includes(SPEED_HIGH) ? SPEED_HIGH :
                device.speeds.includes(SPEED_FULL) ? SPEED_FULL : SPEED_LOW;
            device.set_speed(speed);
            value |= PORT_CCS | SPEED_IDS[speed] << PORT_SPEED_SHIFT;
            value |= speed === SPEED_SUPER ? PORT_PED | PLS_U0 << PORT_PLS_SHIFT : PLS_POLLING << PORT_PLS_SHIFT;
        }
        else
        {
            value |= (root < USB2_FIRST ? PLS_RX_DETECT : PLS_DISABLED) << PORT_PLS_SHIFT;
        }
        if(!!(before & PORT_CCS) !== connected) value |= PORT_CSC;
        this.portsc[root] = value | before & PORT_CHANGES;
        if(notify && value & PORT_CSC) this.port_event(root);
    }
};

/**
 * Plug a device into a physical port (or take it out: null): its slot's
 * transfers end
 * @param {number} port
 * @param {?Object} device
 */
XHCIController.prototype.attach = function(port, device)
{
    if(this.devices[port])
    {
        for(const slot of this.slots) if(slot && slot.port === port) slot.gone = true;
    }
    this.devices[port] = device;
    if(device) device.reset();
    this.update_port(port, true);
};

/**
 * @param {number} port
 * @return {boolean} whether the physical port has a device connected
 */
XHCIController.prototype.port_connected = function(port)
{
    return !!((this.portsc[USB3_FIRST + port] | this.portsc[USB2_FIRST + port]) & PORT_CCS);
};

/** @param {number} root a Port Status Change Event (while running) */
XHCIController.prototype.port_event = function(root)
{
    this.status |= STS_PCD;
    if(!(this.status & STS_HCH)) this.event(root << 24, 0, CC_SUCCESS << 24, EVENT_PORT << 10);
};

/**
 * PORTSC written: change bits cleared, a reset, the link state, the port disabled
 * @param {number} root
 * @param {number} value
 */
XHCIController.prototype.write_port = function(root, value)
{
    const port = (root - 1) % XHCI_PORTS;
    const device = this.devices[port];
    const here = device && root === root_port(port, device);
    if(value & (PORT_PR | PORT_WPR))
    {
        // a reset (a warm one: USB 3's): the device to its default state, the link up, enabled
        if(here)
        {
            device.reset();
            this.portsc[root] = this.portsc[root] & ~(PORT_PLS | PORT_PR) | PLS_U0 << PORT_PLS_SHIFT | PORT_PED | PORT_PRC |
                (value & PORT_WPR && root < USB2_FIRST ? PORT_WRC : 0);
            this.port_event(root);
        }
        return;
    }
    let portsc = this.portsc[root] & ~(value & PORT_CHANGES);
    // (PED written 1: the driver disables the port)
    if(value & PORT_PED) portsc &= ~PORT_PED;
    if(value & PORT_LWS)
    {
        const pls = value >> PORT_PLS_SHIFT & 0xF, before = portsc >> PORT_PLS_SHIFT & 0xF;
        // suspend (U3) and resume (U0: Port Link State Change); the others are not the driver's
        if(pls === PLS_U3 && before === PLS_U0) portsc = portsc & ~PORT_PLS | PLS_U3 << PORT_PLS_SHIFT;
        else if((pls === PLS_U0 || pls === PLS_RESUME) && before === PLS_U3)
        {
            portsc = portsc & ~PORT_PLS | PLS_U0 << PORT_PLS_SHIFT | PORT_PLC;
            this.portsc[root] = portsc;
            this.port_event(root);
            return;
        }
    }
    this.portsc[root] = portsc & ~PORT_WAKE | value & PORT_WAKE;
};

// registers

/**
 * A register's value
 * @param {number} offset its first byte
 * @return {number}
 */
XHCIController.prototype.register = function(offset)
{
    if(offset < OP)
    {
        switch(offset)
        {
            // CAPLENGTH, HCIVERSION 1.0
            case 0x00: return OP | 0x0100 << 16;
            case 0x04: return HCSPARAMS1;
            case 0x08: return HCSPARAMS2;
            case 0x10: return HCCPARAMS1;
            case 0x14: return DOORBELLS;
            case 0x18: return RUNTIME;
        }
        return 0;
    }
    if(offset >= PORTS_BASE && offset < PORTS_BASE + 0x10 * ROOT_PORTS)
    {
        return (offset & 0xF) === 0 ? this.portsc[(offset - PORTS_BASE >> 4) + 1] : 0;
    }
    if(offset < RUNTIME)
    {
        switch(offset - OP)
        {
            case R_USBCMD: return this.cmd;
            case R_USBSTS: return this.status;
            // 4 KiB pages
            case R_PAGESIZE: return 1;
            case R_DNCTRL: return this.dnctrl;
            case R_CRCR: return this.crr ? CRCR_CRR : 0;
            case R_CRCR_HIGH: return 0;
            case R_DCBAAP: return this.dcbaap[0];
            case R_DCBAAP_HIGH: return this.dcbaap[1];
            case R_CONFIG: return this.config;
        }
        return 0;
    }
    if(offset < DOORBELLS)
    {
        switch(offset - RUNTIME)
        {
            case 0x00: return this.mfindex();
            case 0x20: return this.iman;
            case 0x24: return this.imod;
            case 0x28: return this.erstsz;
            case 0x30: return this.erstba[0];
            case 0x34: return this.erstba[1];
            case 0x38: return this.erdp[0];
            case 0x3C: return this.erdp[1];
        }
        return 0;
    }
    if(offset >= XECP && offset < XECP + 16 * EXTENDED.length)
    {
        const capability = EXTENDED[offset - XECP >> 4];
        const word = (offset & 0xF) >> 2;
        // (USB legacy support: its semaphores)
        if(offset === XECP) return (capability[0] | this.legsup) >>> 0;
        return word < capability.length ? capability[word] >>> 0 : 0;
    }
    // (doorbells read 0)
    return 0;
};

/** @return {number} the micro-frame index: 125 µs of the machine clock since the controller ran */
XHCIController.prototype.mfindex = function()
{
    return this.status & STS_HCH ? 0 : Math.floor((this.machine.now() - this.mf_start) * 8) & 0x3FFF;
};

/**
 * @param {number} offset
 * @param {number} size
 * @return {number}
 */
XHCIController.prototype.read = function(offset, size)
{
    const value = this.register(offset & ~3);
    if(size === 4) return value >>> 0;
    return value >>> ((offset & 3) << 3) & (size === 1 ? 0xFF : 0xFFFF);
};

/**
 * @param {number} offset
 * @param {number} size
 * @param {number} value
 */
XHCIController.prototype.write = function(offset, size, value)
{
    const shift = (offset & 3) << 3;
    const mask = (size === 4 ? -1 : (size === 1 ? 0xFF : 0xFFFF) << shift) >>> 0;
    this.write_register(offset & ~3, value << shift >>> 0, mask);
};

/**
 * @param {number} offset
 * @param {number} bits
 * @param {number} mask
 */
XHCIController.prototype.write_register = function(offset, bits, mask)
{
    const merge = old => (old & ~mask | bits & mask) >>> 0;
    if(offset >= PORTS_BASE && offset < PORTS_BASE + 0x10 * ROOT_PORTS)
    {
        if((offset & 0xF) === 0) this.write_port((offset - PORTS_BASE >> 4) + 1, merge(this.portsc[(offset - PORTS_BASE >> 4) + 1]) & ~PORT_CHANGES | bits & mask & PORT_CHANGES);
        return;
    }
    if(offset === XECP)
    {
        // the OS taking the controller from the firmware gets it at once (no USB SMI)
        this.legsup = merge(this.legsup) & (LEGSUP_BIOS_OWNED | LEGSUP_OS_OWNED);
        if(this.legsup & LEGSUP_OS_OWNED) this.legsup &= ~LEGSUP_BIOS_OWNED;
        return;
    }
    if(offset >= DOORBELLS && offset < DOORBELLS + 4 * (MAX_SLOTS + 1))
    {
        this.doorbell(offset - DOORBELLS >> 2, merge(0));
        return;
    }
    switch(offset)
    {
        case OP + R_USBCMD:
        {
            const value = merge(this.cmd);
            if(value & CMD_HCRST)
            {
                dbg_log("xhci: host controller reset", LOG_PCI);
                this.reset();
                return;
            }
            if(value & CMD_RS && this.status & STS_HCH)
            {
                this.status &= ~STS_HCH;
                this.mf_start = this.machine.now();
                this.next_ms = this.machine.now() + 1;
            }
            else if(!(value & CMD_RS) && !(this.status & STS_HCH))
            {
                this.status |= STS_HCH;
            }
            // (save and restore state: nothing to save)
            if(value & CMD_CSS) this.status &= ~STS_SRE;
            this.cmd = value & CMD_MASK & ~(CMD_CSS | CMD_CRS);
            this.update_irq();
            break;
        }
        case OP + R_USBSTS:
            this.status &= ~(bits & mask & (STS_HSE | STS_EINT | STS_PCD | STS_SRE));
            this.update_irq();
            break;
        case OP + R_DNCTRL:
            this.dnctrl = merge(this.dnctrl) & 0xFFFF;
            break;
        case OP + R_CRCR:
        {
            const value = merge(this.crcr[0]);
            if(value & (CRCR_CS | CRCR_CA) && this.crr)
            {
                // stopped (or aborted: commands run at once, none is under way)
                this.crr = false;
                this.event(this.command_ring.dequeue % 0x100000000, Math.floor(this.command_ring.dequeue / 0x100000000),
                    CC_COMMAND_RING_STOPPED << 24, EVENT_COMMAND << 10);
                break;
            }
            this.crcr[0] = value & ~0x3F | value & CRCR_RCS;
            if(!this.crr) this.command_ring = { dequeue: this.crcr[1] * 0x100000000 + ((this.crcr[0] & ~0x3F) >>> 0), ccs: value & CRCR_RCS };
            break;
        }
        case OP + R_CRCR_HIGH:
            this.crcr[1] = merge(this.crcr[1]);
            if(!this.crr) this.command_ring = { dequeue: this.crcr[1] * 0x100000000 + ((this.crcr[0] & ~0x3F) >>> 0), ccs: this.crcr[0] & CRCR_RCS };
            break;
        case OP + R_DCBAAP:
            this.dcbaap[0] = merge(this.dcbaap[0]) & ~0x3F;
            break;
        case OP + R_DCBAAP_HIGH:
            this.dcbaap[1] = merge(this.dcbaap[1]);
            break;
        case OP + R_CONFIG:
            this.config = merge(this.config) & 0x3FF;
            break;
        case RUNTIME + 0x20:
        {
            // IMAN: IP written 1 is cleared; IE
            const value = merge(this.iman);
            this.iman = this.iman & ~(value & IMAN_IP) & ~IMAN_IE | value & IMAN_IE;
            this.update_irq();
            break;
        }
        case RUNTIME + 0x24:
            this.imod = merge(this.imod);
            break;
        case RUNTIME + 0x28:
            this.erstsz = merge(this.erstsz) & 0xFFFF;
            break;
        case RUNTIME + 0x30:
            this.erstba[0] = merge(this.erstba[0]) & ~0x3F;
            this.event_ring_reset();
            break;
        case RUNTIME + 0x34:
            this.erstba[1] = merge(this.erstba[1]);
            this.event_ring_reset();
            break;
        case RUNTIME + 0x38:
        {
            // ERDP: the driver's dequeue pointer; EHB written 1 is cleared,
            // and events still to read interrupt again
            const value = merge(this.erdp[0]);
            this.erdp[0] = (value & ~ERDP_EHB | this.erdp[0] & ERDP_EHB & ~(value & ERDP_EHB)) >>> 0;
            if(value & ERDP_EHB && this.event_ring.size && this.event_dequeue() !== this.event_ring.enqueue) this.interrupt();
            break;
        }
        case RUNTIME + 0x3C:
            this.erdp[1] = merge(this.erdp[1]);
            break;
    }
};

XHCIController.prototype.update_irq = function()
{
    const msi = this.machine.msi_enabled(MSI_CAP);
    const level = !!(this.iman & IMAN_IP && this.iman & IMAN_IE && this.cmd & CMD_INTE) && !msi;
    if(level === this.irq_level) return;
    this.irq_level = level;
    if(level) this.machine.raise_irq();
    else this.machine.lower_irq();
};

// the event ring

/** The event ring's one segment from ERSTBA's first entry: events start at its beginning */
XHCIController.prototype.event_ring_reset = function()
{
    const base = this.erstba[1] * 0x100000000 + this.erstba[0];
    this.event_ring = { start: 0, size: 0, enqueue: 0, pcs: 1 };
    if(!this.erstsz || !base) return;
    const entry = this.dma_read(base, 16);
    if(!entry) return;
    const view = new DataView(entry.buffer);
    const size = view.getUint32(8, true) & 0xFFFF;
    if(size < 16 || size > 4096) return;
    this.event_ring = { start: view.getUint32(4, true) * 0x100000000 + ((view.getUint32(0, true) & ~0x3F) >>> 0), size, enqueue: 0, pcs: 1 };
};

/** @return {number} the index of the driver's dequeue pointer in the event ring */
XHCIController.prototype.event_dequeue = function()
{
    const erdp = this.erdp[1] * 0x100000000 + ((this.erdp[0] & ~0xF) >>> 0);
    return Math.floor((erdp - this.event_ring.start) / 16);
};

/**
 * Write an event TRB (its dwords) to the event ring, and interrupt. A full
 * ring drops the event; the last free entry takes an Event Ring Full Error.
 * @param {number} parameter_low
 * @param {number} parameter_high
 * @param {number} status
 * @param {number} control (no cycle bit)
 */
XHCIController.prototype.event = function(parameter_low, parameter_high, status, control)
{
    const ring = this.event_ring;
    if(!ring.size) return;
    const dequeue = this.event_dequeue();
    if(dequeue < 0 || dequeue >= ring.size)
    {
        dbg_log("xhci: the event ring's dequeue pointer outside the ring", LOG_PCI);
        this.status |= STS_HCE;
        return;
    }
    if((ring.enqueue + 1) % ring.size === dequeue) return;
    if((ring.enqueue + 2) % ring.size === dequeue)
    {
        parameter_low = parameter_high = 0;
        status = CC_EVENT_RING_FULL << 24;
        control = EVENT_HOST << 10;
    }
    const trb = new Uint8Array(16);
    const view = new DataView(trb.buffer);
    view.setUint32(0, parameter_low >>> 0, true);
    view.setUint32(4, parameter_high >>> 0, true);
    view.setUint32(8, status >>> 0, true);
    view.setUint32(12, (control | ring.pcs) >>> 0, true);
    if(!this.dma_write(trb, ring.start + 16 * ring.enqueue)) return;
    ring.enqueue++;
    if(ring.enqueue === ring.size)
    {
        ring.enqueue = 0;
        ring.pcs ^= 1;
    }
    this.interrupt();
};

/** An event for the driver: EHB, IP, EINT; an interrupt unless one is pending */
XHCIController.prototype.interrupt = function()
{
    const pending = this.erdp[0] & ERDP_EHB;
    this.erdp[0] |= ERDP_EHB;
    this.iman |= IMAN_IP;
    this.status |= STS_EINT;
    if(pending || !(this.iman & IMAN_IE) || !(this.cmd & CMD_INTE)) return;
    if(this.machine.msi_enabled(MSI_CAP))
    {
        // (a message: IP clears once it is sent)
        if(this.machine.msi_notify(MSI_CAP)) this.iman &= ~IMAN_IP;
    }
    this.update_irq();
};

// rings

/**
 * The next TRB of a ring (Link TRBs followed), or null where the driver
 * has not put one yet (its cycle bit is not the ring's)
 * @param {{dequeue: number, ccs: number}} ring advanced past it
 * @return {?{address: number, low: number, high: number, status: number, control: number, type: number, ccs: number}}
 */
XHCIController.prototype.fetch = function(ring)
{
    for(let links = 0; links < LINK_LIMIT; links++)
    {
        const bytes = this.dma_read(ring.dequeue, 16);
        if(!bytes) return null;
        const view = new DataView(bytes.buffer);
        const control = view.getUint32(12, true);
        if((control & TRB_CYCLE) !== ring.ccs) return null;
        const type = control >> 10 & 0x3F;
        const low = view.getUint32(0, true), high = view.getUint32(4, true);
        if(type === TRB_LINK)
        {
            ring.dequeue = high * 0x100000000 + ((low & ~0xF) >>> 0);
            if(control & TRB_TC) ring.ccs ^= 1;
            continue;
        }
        const trb = { address: ring.dequeue, low, high, status: view.getUint32(8, true), control, type, ccs: ring.ccs };
        ring.dequeue += 16;
        return trb;
    }
    return null;
};

// commands

/**
 * A doorbell: the command ring (0), or an endpoint of a slot's (its DCI)
 * @param {number} target
 * @param {number} value
 */
XHCIController.prototype.doorbell = function(target, value)
{
    if(this.status & STS_HCH) return;
    if(target === 0)
    {
        if(value === 0) this.run_commands();
        return;
    }
    const dci = value & 0xFF;
    if(target > MAX_SLOTS || dci < 1 || dci > 31) return;
    const slot = this.slots[target];
    if(!slot || !slot.endpoints[dci]) return;
    // (a stopped endpoint runs again; a halted one waits for Reset Endpoint)
    if(slot.endpoints[dci].state === EP_STOPPED) this.set_endpoint_state(slot, slot.endpoints[dci], EP_RUNNING);
    this.active.add(target + ":" + dci);
    this.budget = DOORBELL_BYTES;
    this.run_endpoint(slot, slot.endpoints[dci]);
};

XHCIController.prototype.run_commands = function()
{
    this.crr = true;
    for(let count = 0; count < 256; count++)
    {
        const trb = this.fetch(this.command_ring);
        if(!trb) break;
        let slot_id = trb.control >>> 24;
        let code = CC_SUCCESS;
        switch(trb.type)
        {
            case CMD_ENABLE_SLOT:
                slot_id = this.slots.findIndex((slot, i) => i > 0 && !slot);
                if(slot_id < 0) { slot_id = 0; code = CC_NO_SLOTS; }
                else this.slots[slot_id] = { port: -1, root: 0, context: 0, state: SLOT_DEFAULT, endpoints: new Array(32).fill(null), gone: false };
                break;
            case CMD_NOOP:
                slot_id = 0;
                break;
            case CMD_GET_PORT_BANDWIDTH:
                // (80% of every port free, as QEMU)
                code = this.dma_write(Uint8Array.of(0, ...new Array(ROOT_PORTS).fill(80)), trb.high * 0x100000000 + trb.low) ? CC_SUCCESS : CC_TRB;
                slot_id = 0;
                break;
            case CMD_DISABLE_SLOT: case CMD_ADDRESS_DEVICE: case CMD_CONFIGURE_ENDPOINT: case CMD_EVALUATE_CONTEXT:
            case CMD_RESET_ENDPOINT: case CMD_STOP_ENDPOINT: case CMD_SET_TR_DEQUEUE: case CMD_RESET_DEVICE:
                code = slot_id < 1 || slot_id > MAX_SLOTS ? CC_TRB : !this.slots[slot_id] ? CC_SLOT_NOT_ENABLED : this.slot_command(trb, slot_id);
                break;
            default:
                code = CC_TRB;
        }
        this.event(trb.address % 0x100000000, Math.floor(trb.address / 0x100000000), code << 24, EVENT_COMMAND << 10 | slot_id << 24);
    }
};

/**
 * A command for an enabled slot
 * @param {!Object} trb
 * @param {number} id
 * @return {number} its completion code
 */
XHCIController.prototype.slot_command = function(trb, id)
{
    const slot = this.slots[id];
    const dci = trb.control >> 16 & 0x1F;
    const pointer = trb.high * 0x100000000 + ((trb.low & ~0xF) >>> 0);
    switch(trb.type)
    {
        case CMD_DISABLE_SLOT:
            for(let i = 1; i <= 31; i++) if(slot.endpoints[i]) this.disable_endpoint(id, i);
            this.slots[id] = null;
            return CC_SUCCESS;
        case CMD_ADDRESS_DEVICE:
            return this.address_device(id, pointer, !!(trb.control & TRB_BSR));
        case CMD_CONFIGURE_ENDPOINT:
            return this.configure_endpoints(id, pointer, !!(trb.control & TRB_DC));
        case CMD_EVALUATE_CONTEXT:
            return this.evaluate_context(id, pointer);
        case CMD_RESET_ENDPOINT:
        {
            const ep = slot.endpoints[dci];
            if(!ep) return CC_EP_NOT_ENABLED;
            if(ep.state !== EP_HALTED) return CC_CONTEXT_STATE;
            ep.td = null;
            this.set_endpoint_state(slot, ep, EP_STOPPED);
            return CC_SUCCESS;
        }
        case CMD_STOP_ENDPOINT:
        {
            const ep = slot.endpoints[dci];
            if(!ep) return CC_EP_NOT_ENABLED;
            if(ep.td)
            {
                // the TD under way: a Transfer Event, Stopped, at its TRB; the ring from there
                const trb_now = ep.td.trbs[Math.min(ep.td.index, ep.td.trbs.length - 1)];
                const left = (trb_now.status & 0x1FFFF) - (ep.td.done[ep.td.index] || 0);
                this.event(trb_now.address % 0x100000000, Math.floor(trb_now.address / 0x100000000), CC_STOPPED << 24 | Math.max(0, left),
                    EVENT_TRANSFER << 10 | dci << 16 | id << 24);
                ep.ring = { dequeue: trb_now.address, ccs: trb_now.ccs };
                ep.td = null;
            }
            this.set_endpoint_state(slot, ep, EP_STOPPED);
            return CC_SUCCESS;
        }
        case CMD_SET_TR_DEQUEUE:
        {
            const ep = slot.endpoints[dci];
            if(!ep) return CC_EP_NOT_ENABLED;
            if(ep.state !== EP_STOPPED && ep.state !== EP_HALTED) return CC_CONTEXT_STATE;
            ep.ring = { dequeue: pointer, ccs: trb.low & 1 };
            ep.td = null;
            this.set_endpoint_state(slot, ep, ep.state);
            return CC_SUCCESS;
        }
        case CMD_RESET_DEVICE:
        {
            if(slot.state < SLOT_ADDRESSED) return CC_CONTEXT_STATE;
            for(let i = 2; i <= 31; i++) if(slot.endpoints[i]) this.disable_endpoint(id, i);
            const device = this.slot_device(slot);
            if(device) device.reset();
            slot.state = SLOT_DEFAULT;
            this.write_slot_state(slot, SLOT_DEFAULT, 0, 1);
            return CC_SUCCESS;
        }
    }
    return CC_TRB;
};

/**
 * The device a slot was addressed to (still in its port)
 * @param {!Object} slot
 * @return {?Object}
 */
XHCIController.prototype.slot_device = function(slot)
{
    if(slot.port < 0 || slot.gone) return null;
    const device = this.devices[slot.port];
    return device && root_port(slot.port, device) === slot.root && this.portsc[slot.root] & PORT_PED ? device : null;
};

/**
 * Address Device: the input context's slot and endpoint 0 into the output
 * context (DCBAA's entry); the device's address the slot's ID (BSR: not
 * yet: the default state)
 * @param {number} id
 * @param {number} input
 * @param {boolean} bsr
 * @return {number}
 */
XHCIController.prototype.address_device = function(id, input, bsr)
{
    const slot = this.slots[id];
    const control = this.dma_read(input, 8);
    const words = this.dma_read(input + 32, 32 + 32);
    const entry = this.dma_read(this.dcbaap[1] * 0x100000000 + this.dcbaap[0] + 8 * id, 8);
    if(!control || !words || !entry) return CC_TRB;
    const c = new DataView(control.buffer), w = new DataView(words.buffer), e = new DataView(entry.buffer);
    if(c.getUint32(0, true) !== 0 || (c.getUint32(4, true) & 3) !== 3) return CC_TRB;
    const slot_context = [0, 1, 2, 3].map(i => w.getUint32(4 * i, true));
    const ep0 = [0, 1, 2, 3, 4].map(i => w.getUint32(32 + 4 * i, true));
    // the root port (no hubs: no route string)
    const root = slot_context[1] >>> 16 & 0xFF;
    if(root < 1 || root > ROOT_PORTS || slot_context[0] & 0xFFFFF) return CC_PARAMETER;
    const port = (root - 1) % XHCI_PORTS;
    const device = this.devices[port];
    if(!device || root_port(port, device) !== root || !(this.portsc[root] & PORT_PED)) return CC_TRANSACTION;
    if(this.slots.some((other, i) => other && i !== id && other.port === port && !other.gone && other.state >= SLOT_ADDRESSED)) return CC_TRB;
    slot.port = port;
    slot.root = root;
    slot.gone = false;
    slot.context = e.getUint32(4, true) * 0x100000000 + ((e.getUint32(0, true) & ~0x3F) >>> 0);
    device.reset();
    if(!bsr)
    {
        // SET_ADDRESS to the slot's ID
        device.transaction(PID_SETUP, 0, Uint8Array.of(0x00, 0x05, id, 0, 0, 0, 0, 0), 8);
        device.transaction(PID_IN, 0, null, 0);
    }
    slot.state = bsr ? SLOT_DEFAULT : SLOT_ADDRESSED;
    slot_context[3] = slot.state << 27 | (bsr ? 0 : id);
    this.write_dwords(slot.context, slot_context);
    if(slot.endpoints[1]) this.disable_endpoint(id, 1);
    this.enable_endpoint(slot, 1, ep0);
    return CC_SUCCESS;
};

/**
 * Configure Endpoint: the endpoints the input context drops and adds
 * (DC: every endpoint but 0 dropped, back to Addressed)
 * @param {number} id
 * @param {number} input
 * @param {boolean} deconfigure
 * @return {number}
 */
XHCIController.prototype.configure_endpoints = function(id, input, deconfigure)
{
    const slot = this.slots[id];
    if(slot.state < SLOT_ADDRESSED) return CC_CONTEXT_STATE;
    if(deconfigure)
    {
        for(let i = 2; i <= 31; i++) if(slot.endpoints[i]) this.disable_endpoint(id, i);
        slot.state = SLOT_ADDRESSED;
        this.write_slot_state(slot, SLOT_ADDRESSED, id, -1);
        return CC_SUCCESS;
    }
    const bytes = this.dma_read(input, 32 * 33);
    if(!bytes) return CC_TRB;
    const view = new DataView(bytes.buffer);
    const drop = view.getUint32(0, true), add = view.getUint32(4, true);
    if(drop & 3 || (add & 3) !== 1) return CC_TRB;
    for(let i = 2; i <= 31; i++)
    {
        if(drop & 1 << i || add & 1 << i) this.disable_endpoint(id, i);
        if(add & 1 << i)
        {
            const context = [0, 1, 2, 3, 4].map(k => view.getUint32(32 * (i + 1) + 4 * k, true));
            const type = context[1] >> 3 & 7;
            if(type === EP_ISOCH_OUT || type === EP_ISOCH_IN || type === 0) return CC_PARAMETER;
            this.enable_endpoint(slot, i, context);
        }
    }
    // the slot: its context entries, configured
    const entries = view.getUint32(32, true) >>> 27;
    const any = slot.endpoints.some((ep, i) => ep && i > 1);
    slot.state = any ? SLOT_CONFIGURED : SLOT_ADDRESSED;
    this.write_slot_state(slot, slot.state, id, entries);
    return CC_SUCCESS;
};

/**
 * Evaluate Context: the slot's max exit latency and interrupter, endpoint 0's max packet
 * @param {number} id
 * @param {number} input
 * @return {number}
 */
XHCIController.prototype.evaluate_context = function(id, input)
{
    const slot = this.slots[id];
    const bytes = this.dma_read(input, 96);
    const output = this.dma_read(slot.context, 64);
    if(!bytes || !output || !slot.context) return CC_TRB;
    const view = new DataView(bytes.buffer), out = new DataView(output.buffer);
    const drop = view.getUint32(0, true), add = view.getUint32(4, true);
    if(drop || add & ~3) return CC_TRB;
    if(add & 1)
    {
        out.setUint32(4, (out.getUint32(4, true) & ~0xFFFF | view.getUint32(32 + 4, true) & 0xFFFF) >>> 0, true);
        out.setUint32(8, (out.getUint32(8, true) & 0x3FFFFF | view.getUint32(32 + 8, true) & ~0x3FFFFF) >>> 0, true);
    }
    if(add & 2)
    {
        const max_packet = view.getUint32(64 + 4, true) >>> 16;
        out.setUint32(32 + 4, (out.getUint32(32 + 4, true) & 0xFFFF | max_packet << 16) >>> 0, true);
        if(slot.endpoints[1]) slot.endpoints[1].max_packet = max_packet;
    }
    this.dma_write(output, slot.context);
    return CC_SUCCESS;
};

/**
 * @param {!Object} slot
 * @param {number} dci
 * @param {!Array<number>} context the input endpoint context's five dwords
 */
XHCIController.prototype.enable_endpoint = function(slot, dci, context)
{
    const ep = {
        dci,
        type: context[1] >> 3 & 7,
        max_packet: context[1] >>> 16,
        interval: context[0] >> 16 & 0xFF,
        ring: { dequeue: context[3] * 0x100000000 + ((context[2] & ~0xF) >>> 0), ccs: context[2] & 1 },
        state: EP_RUNNING,
        /** @type {Object} the TD under way */
        td: null,
    };
    slot.endpoints[dci] = ep;
    context[0] = context[0] & ~7 | EP_RUNNING;
    this.write_dwords(slot.context + 32 * dci, context);
};

/**
 * @param {number} id
 * @param {number} dci
 */
XHCIController.prototype.disable_endpoint = function(id, dci)
{
    const slot = this.slots[id];
    const ep = slot.endpoints[dci];
    if(!ep) return;
    this.set_endpoint_state(slot, ep, EP_DISABLED);
    slot.endpoints[dci] = null;
    this.active.delete(id + ":" + dci);
};

/**
 * An endpoint's state and dequeue pointer into its output context
 * @param {!Object} slot
 * @param {!Object} ep
 * @param {number} state
 */
XHCIController.prototype.set_endpoint_state = function(slot, ep, state)
{
    ep.state = state;
    if(!slot.context) return;
    const at = slot.context + 32 * ep.dci;
    const bytes = this.dma_read(at, 16);
    if(!bytes) return;
    const view = new DataView(bytes.buffer);
    view.setUint32(0, (view.getUint32(0, true) & ~7 | state) >>> 0, true);
    view.setUint32(8, (ep.ring.dequeue % 0x100000000 & ~0xF | ep.ring.ccs) >>> 0, true);
    view.setUint32(12, Math.floor(ep.ring.dequeue / 0x100000000), true);
    this.dma_write(bytes, at);
};

/**
 * The slot context's state, address and context entries (-1: kept)
 * @param {!Object} slot
 * @param {number} state
 * @param {number} address
 * @param {number} entries
 */
XHCIController.prototype.write_slot_state = function(slot, state, address, entries)
{
    if(!slot.context) return;
    const bytes = this.dma_read(slot.context, 16);
    if(!bytes) return;
    const view = new DataView(bytes.buffer);
    if(entries >= 0) view.setUint32(0, (view.getUint32(0, true) & 0x7FFFFFF | entries << 27) >>> 0, true);
    view.setUint32(12, (state << 27 | address & 0xFF) >>> 0, true);
    this.dma_write(bytes, slot.context);
};

// transfers

/**
 * An endpoint's TDs while it runs and the budget lasts; one a device NAKs
 * waits (the endpoint stays active: the timer tries again)
 * @param {!Object} slot
 * @param {!Object} ep
 */
XHCIController.prototype.run_endpoint = function(slot, ep)
{
    const key = this.slots.indexOf(slot) + ":" + ep.dci;
    for(let tds = 0; tds < 256 && this.budget > 0; tds++)
    {
        if(ep.state !== EP_RUNNING) { this.active.delete(key); return; }
        if(!ep.td)
        {
            ep.td = this.fetch_td(ep);
            if(!ep.td) { this.active.delete(key); return; }
        }
        if(!this.run_td(slot, ep)) return;
        ep.td = null;
    }
};

/**
 * The next TD of an endpoint's ring: its TRBs (to the last without the chain
 * bit; a control transfer's Setup to its Status, and an Event Data chained
 * after it), or null where it is not all there yet
 * @param {!Object} ep
 * @return {Object}
 */
XHCIController.prototype.fetch_td = function(ep)
{
    const ring = { dequeue: ep.ring.dequeue, ccs: ep.ring.ccs };
    const trbs = [];
    let status = false;
    while(trbs.length < TD_TRBS)
    {
        const trb = this.fetch(ring);
        if(!trb) return null;
        trbs.push(trb);
        // (a control transfer: until its Status stage and what is chained to it)
        if(trb.type === TRB_STATUS) status = true;
        if(ep.type === EP_CONTROL && !status) continue;
        if(!(trb.control & TRB_CH)) break;
    }
    return { trbs, index: 0, offset: 0, done: trbs.map(() => 0), short: -1, error: 0, error_index: -1, after: ring };
};

/**
 * A TD's transactions from where it was: true once it is over (its events
 * written, the ring past it, or the endpoint halted), false while the
 * device NAKs
 * @param {!Object} slot
 * @param {!Object} ep
 * @return {boolean}
 */
XHCIController.prototype.run_td = function(slot, ep)
{
    const td = ep.td;
    const device = this.slot_device(slot);
    const endpoint = ep.dci >> 1;
    for(; td.index < td.trbs.length && !td.error; td.index++)
    {
        const trb = td.trbs[td.index];
        if(trb.type === TRB_EVENT_DATA || trb.type === TRB_NOOP) continue;
        // (after a short packet the TD's data is over; a control transfer's Status stage still runs)
        if(td.short >= 0 && (trb.type === TRB_NORMAL || trb.type === TRB_DATA)) continue;
        if(trb.type === TRB_ISOCH || trb.type !== TRB_NORMAL && trb.type !== TRB_SETUP && trb.type !== TRB_DATA && trb.type !== TRB_STATUS)
        {
            td.error = CC_TRB;
            break;
        }
        if(!device)
        {
            td.error = CC_TRANSACTION;
            break;
        }
        if(trb.type === TRB_SETUP)
        {
            // (immediate data: the request's eight bytes)
            const setup = new Uint8Array(8);
            new DataView(setup.buffer).setUint32(0, trb.low, true);
            new DataView(setup.buffer).setUint32(4, trb.high, true);
            const result = device.transaction(PID_SETUP, 0, setup, 8);
            if(result === USB_NAK) return false;
            if(result === USB_STALL) { td.error = CC_STALL; break; }
            td.done[td.index] = 8;
            continue;
        }
        if(trb.type === TRB_STATUS)
        {
            // the status stage: no data, the other way from the data stage
            const result = trb.control & TRB_DIR_IN ? device.transaction(PID_IN, 0, null, 0) : device.transaction(PID_OUT, 0, new Uint8Array(0), 0);
            if(result === USB_NAK) return false;
            if(result === USB_STALL) { td.error = CC_STALL; break; }
            continue;
        }
        const length = trb.status & 0x1FFFF;
        const into = trb.type === TRB_DATA ? !!(trb.control & TRB_DIR_IN) : !!(ep.dci & 1);
        const buffer = trb.high * 0x100000000 + (trb.low >>> 0);
        const max_packet = ep.max_packet || 8;
        while(td.done[td.index] < length)
        {
            if(this.budget <= 0) return false;
            const n = Math.min(max_packet, length - td.done[td.index]);
            let result;
            if(into)
            {
                result = device.transaction(PID_IN, endpoint, null, n);
            }
            else
            {
                const data = trb.control & TRB_IDT ? immediate(trb).subarray(td.done[td.index], td.done[td.index] + n) :
                    this.dma_read(buffer + td.done[td.index], n);
                if(!data) { td.error = CC_DATA_BUFFER; break; }
                result = device.transaction(PID_OUT, endpoint, data, n);
            }
            if(result === USB_NAK) return false;
            if(result === USB_STALL) { td.error = CC_STALL; break; }
            let moved = n;
            if(result instanceof Uint8Array)
            {
                if(result.length > n) { td.error = CC_BABBLE; break; }
                if(result.length && !this.dma_write(result, buffer + td.done[td.index])) { td.error = CC_DATA_BUFFER; break; }
                moved = result.length;
            }
            td.done[td.index] += moved;
            this.budget -= Math.max(moved, 64);
            if(into && moved < n)
            {
                td.short = td.index;
                break;
            }
        }
        if(td.error) break;
    }
    if(td.error) td.error_index = Math.min(td.index, td.trbs.length - 1);
    this.report(slot, ep, td);
    return true;
};

/**
 * @param {!Object} trb an IDT TRB
 * @return {!Uint8Array} its eight bytes of data
 */
function immediate(trb)
{
    const bytes = new Uint8Array(8);
    const view = new DataView(bytes.buffer);
    view.setUint32(0, trb.low, true);
    view.setUint32(4, trb.high, true);
    return bytes;
}

/**
 * A TD over: its Transfer Events (the first TRB with IOC, a short packet's
 * with ISP, an error's; a control transfer's Status stage again; Event Data
 * TRBs with the bytes so far), the ring past it, or the endpoint halted
 * at it
 * @param {!Object} slot
 * @param {!Object} ep
 * @param {!Object} td
 */
XHCIController.prototype.report = function(slot, ep, td)
{
    const id = this.slots.indexOf(slot);
    let reported = false, short = false, edtla = 0;
    for(let i = 0; i < td.trbs.length; i++)
    {
        const trb = td.trbs[i];
        const length = trb.type === TRB_SETUP ? 8 : trb.status & 0x1FFFF;
        if(trb.type === TRB_STATUS) { reported = false; short = false; }
        if(i === td.short) short = true;
        if(trb.type === TRB_NORMAL || trb.type === TRB_DATA) edtla += td.done[i];
        const error = td.error && i === td.error_index;
        if(!reported && (trb.control & TRB_IOC || short && trb.control & TRB_ISP || error))
        {
            const code = error ? td.error : short ? CC_SHORT_PACKET : CC_SUCCESS;
            if(trb.type === TRB_EVENT_DATA)
            {
                // (the Event Data TRB's parameter, the bytes transferred so far; ED)
                this.event(trb.low, trb.high, code << 24 | edtla & 0xFFFFFF, EVENT_TRANSFER << 10 | 1 << 2 | ep.dci << 16 | id << 24);
                edtla = 0;
            }
            else
            {
                const left = trb.type === TRB_STATUS ? 0 : Math.max(0, length - td.done[i]);
                this.event(trb.address % 0x100000000, Math.floor(trb.address / 0x100000000), code << 24 | left,
                    EVENT_TRANSFER << 10 | ep.dci << 16 | id << 24);
            }
            reported = true;
            if(error) break;
        }
        if(trb.type === TRB_SETUP) { reported = false; short = false; }
        if(error) break;
    }
    if(td.error)
    {
        // halted: the ring at the TD's first TRB (the driver resets the endpoint and moves on)
        ep.ring = { dequeue: td.trbs[0].address, ccs: td.trbs[0].ccs };
        this.set_endpoint_state(slot, ep, EP_HALTED);
        return;
    }
    ep.ring = td.after;
};

/**
 * @param {number} now the machine time
 * @return {number} milliseconds until the next work
 */
XHCIController.prototype.timer = function(now)
{
    if(this.status & STS_HCH || !this.active.size) return 100;
    if(now < this.next_ms) return this.next_ms - now;
    this.next_ms = now + 1;
    if(!this.machine.is_bus_master()) return 1;
    this.budget = MS_BYTES;
    for(const key of Array.from(this.active))
    {
        const [id, dci] = key.split(":").map(Number);
        const slot = this.slots[id];
        const ep = slot && slot.endpoints[dci];
        if(!ep) { this.active.delete(key); continue; }
        this.run_endpoint(/** @type {!Object} */ (slot), ep);
    }
    return 1;
};

/**
 * @param {number} address
 * @param {!Array<number>} words
 */
XHCIController.prototype.write_dwords = function(address, words)
{
    const bytes = new Uint8Array(4 * words.length);
    const view = new DataView(bytes.buffer);
    words.forEach((word, i) => view.setUint32(4 * i, word >>> 0, true));
    this.dma_write(bytes, address);
};

/**
 * @param {number} address
 * @param {number} length
 * @return {Uint8Array}
 */
XHCIController.prototype.dma_read = function(address, length)
{
    try { return this.machine.read_physical(address, length); }
    catch(e)
    {
        dbg_log("xhci: read outside memory at " + h(address >>> 0, 8), LOG_PCI);
        this.status |= STS_HSE;
        return null;
    }
};

/**
 * @param {!Uint8Array} bytes
 * @param {number} address
 * @return {boolean}
 */
XHCIController.prototype.dma_write = function(bytes, address)
{
    try { this.machine.write_physical(bytes, address); return true; }
    catch(e)
    {
        dbg_log("xhci: write outside memory at " + h(address >>> 0, 8), LOG_PCI);
        this.status |= STS_HSE;
        return false;
    }
};

// snapshots

/** @param {Object} td */
function td_state(td)
{
    return td && [td.trbs.map(t => [t.address, t.low, t.high, t.status, t.control, t.ccs]), td.index, td.done.slice(), td.short, td.error,
        td.error_index, td.after.dequeue, td.after.ccs];
}

/** @param {Array} state */
function td_of_state(state)
{
    return state && {
        trbs: state[0].map(t => ({ address: t[0], low: t[1], high: t[2], status: t[3], control: t[4], type: t[4] >> 10 & 0x3F, ccs: t[5] })),
        index: state[1], offset: 0, done: state[2].slice(), short: state[3], error: state[4], error_index: state[5],
        after: { dequeue: state[6], ccs: state[7] },
    };
}

XHCIController.prototype.get_state = function()
{
    const er = this.event_ring;
    return [this.cmd, this.status, this.dnctrl, this.crcr.slice(), this.command_ring.dequeue, this.command_ring.ccs, +this.crr,
        this.dcbaap.slice(), this.config, this.iman, this.imod, this.erstsz, this.erstba.slice(), this.erdp.slice(),
        [er.start, er.size, er.enqueue, er.pcs], this.machine.now() - this.mf_start, this.portsc.slice(),
        this.slots.map(slot => slot && [slot.port, slot.root, slot.context, slot.state, +slot.gone,
            slot.endpoints.map(ep => ep && [ep.dci, ep.type, ep.max_packet, ep.interval, ep.ring.dequeue, ep.ring.ccs, ep.state, td_state(ep.td)])]),
        Array.from(this.active), this.legsup, +this.irq_level, this.bar0];
};

XHCIController.prototype.set_state = function(state)
{
    this.cmd = state[0];
    this.status = state[1];
    this.dnctrl = state[2];
    this.crcr = state[3].slice();
    this.command_ring = { dequeue: state[4], ccs: state[5] };
    this.crr = !!state[6];
    this.dcbaap = state[7].slice();
    this.config = state[8];
    this.iman = state[9];
    this.imod = state[10];
    this.erstsz = state[11];
    this.erstba = state[12].slice();
    this.erdp = state[13].slice();
    this.event_ring = { start: state[14][0], size: state[14][1], enqueue: state[14][2], pcs: state[14][3] };
    this.mf_start = this.machine.now() - state[15];
    this.next_ms = this.machine.now();
    this.portsc = state[16].slice();
    this.slots = state[17].map(s => s && {
        port: s[0], root: s[1], context: s[2], state: s[3], gone: !!s[4],
        endpoints: s[5].map(e => e && {
            dci: e[0], type: e[1], max_packet: e[2], interval: e[3], ring: { dequeue: e[4], ccs: e[5] }, state: e[6], td: td_of_state(e[7]),
        }),
    });
    this.active = new Set(state[18]);
    this.legsup = state[19];
    this.irq_level = !!state[20];
    if(this.irq_level) this.machine.raise_irq();
    else this.machine.lower_irq();
    this.bar0 = state[21];
    this.update_decode();
};
                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/virt/dtb.js                                                                          0000644 0000000 0000000 00000024674 00000000000 012563  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virt machine's device tree (docs/arm64-virt-android16-plan.md P4.1): a
// flattened device tree (devicetree specification v0.4, version 17) of what
// the machine has, laid out as the reference's (QEMU 9.2 virt, dumpdtb): the
// same nodes, properties and phandle numbering (the clock 0x8000, the cores
// from the last one up, then the GIC), so the two compare node for node.
// v86 has no flash, fw-cfg, PL061 and gpio-keys, or platform bus; those
// nodes are absent (allowed differences, tests/platform/a64-profile.json).
// The PCIe host bridge (P5.6) is the reference's: its ECAM, windows and
// interrupt map.

import {
    VIRT_GIC_DIST, VIRT_GIC_DIST_SIZE, VIRT_GIC_REDIST, VIRT_MMIO, VIRT_MMIO_COUNT, VIRT_MMIO_SIZE, VIRT_PCIE_ECAM_HIGH,
    VIRT_PCIE_ECAM_SIZE, VIRT_PCIE_MMIO, VIRT_PCIE_MMIO_HIGH, VIRT_PCIE_MMIO_HIGH_SIZE, VIRT_PCIE_MMIO_SIZE, VIRT_PCIE_PIO,
    VIRT_PCIE_PIO_SIZE, VIRT_RAM_BASE, VIRT_RTC, VIRT_UART,
} from "./platform.js";

const FDT_MAGIC = 0xD00DFEED;
const FDT_BEGIN_NODE = 1, FDT_END_NODE = 2, FDT_PROP = 3, FDT_END = 9;

/** The size of the low redistributor region in the reference's map (room for 123 cores) */
const GIC_REDIST_REGION_SIZE = 0xF60000;
/** The reference's PCLK for the PrimeCells: 24 MHz */
const APB_PCLK_HZ = 24000000;

/**
 * A node: its name, properties in order ([name, value]: a string, an array
 * of strings, an array of 32-bit cells, true for an empty property, or a
 * Uint8Array), and its children
 * @typedef {{name: string, props: !Array, children: !Array}}
 */
export var DtNode;

/**
 * @param {string} name
 * @param {!Array} props
 * @param {!Array=} children
 * @return {DtNode}
 */
export function node(name, props, children = [])
{
    return { name, props, children };
}

/** Cells of a 64-bit value: high, low */
const u64 = value => [Math.floor(value / 0x100000000), value >>> 0];

function encode_value(value)
{
    if(value === true) return new Uint8Array(0);
    if(value instanceof Uint8Array) return value;
    if(typeof value === "string") value = [value];
    if(typeof value[0] === "string")
    {
        const parts = value.map(s => new TextEncoder().encode(s + "\0"));
        const bytes = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
        let at = 0;
        for(const p of parts) { bytes.set(p, at); at += p.length; }
        return bytes;
    }
    const bytes = new Uint8Array(4 * value.length);
    const view = new DataView(bytes.buffer);
    value.forEach((cell, i) => view.setUint32(4 * i, cell >>> 0));
    return bytes;
}

/**
 * The flattened device tree of `root`
 * @param {DtNode} root
 * @param {number=} boot_cpu
 * @return {!Uint8Array}
 */
export function flatten(root, boot_cpu = 0)
{
    const structure = [];
    const strings = [];
    const string_offsets = new Map();
    let strings_size = 0;
    const word = w => structure.push(w >>> 0);
    const bytes_padded = bytes => {
        for(let i = 0; i < bytes.length; i += 4)
        {
            word((bytes[i] << 24 | (bytes[i + 1] || 0) << 16 | (bytes[i + 2] || 0) << 8 | (bytes[i + 3] || 0)) >>> 0);
        }
    };
    const string_offset = name => {
        if(!string_offsets.has(name))
        {
            string_offsets.set(name, strings_size);
            const bytes = new TextEncoder().encode(name + "\0");
            strings.push(bytes);
            strings_size += bytes.length;
        }
        return string_offsets.get(name);
    };
    const emit = n => {
        word(FDT_BEGIN_NODE);
        bytes_padded(new TextEncoder().encode(n.name + "\0"));
        for(const [name, value] of n.props)
        {
            const bytes = encode_value(value);
            word(FDT_PROP);
            word(bytes.length);
            word(string_offset(name));
            bytes_padded(bytes);
        }
        for(const child of n.children) emit(child);
        word(FDT_END_NODE);
    };
    emit(root);
    word(FDT_END);
    const header_size = 40, rsvmap_size = 16;
    const off_struct = header_size + rsvmap_size;
    const size_struct = 4 * structure.length;
    const off_strings = off_struct + size_struct;
    const total = off_strings + strings_size;
    const out = new Uint8Array((total + 7) & ~7);
    const view = new DataView(out.buffer);
    [FDT_MAGIC, out.length, off_struct, off_strings, header_size, 17, 16, boot_cpu, strings_size, size_struct]
        .forEach((value, i) => view.setUint32(4 * i, value >>> 0));
    // (the memory reservation block: empty, its terminating entry)
    structure.forEach((w, i) => view.setUint32(off_struct + 4 * i, w));
    let at = off_strings;
    for(const s of strings) { out.set(s, at); at += s.length; }
    return out;
}

/**
 * The virt machine's tree
 * (`arm32`: cpu_type "arm32"'s: PSCI's 32-bit function numbers, Cortex-A15
 * cores, no PCIe, whose ECAM and window are above 4 GiB)
 * @param {{cores: number, memory_size: number, bootargs: (string|undefined),
 *          initrd: ({start: number, end: number}|undefined), rng_seed: (Uint8Array|undefined),
 *          extended: ({base: number, size: number}|undefined), arm32: (boolean|undefined)}} m
 * @return {DtNode}
 */
export function virt_tree(m)
{
    const clock = 0x8000;
    const cpu_phandle = i => 0x8000 + m.cores - i;
    const gic = 0x8000 + m.cores + 1;
    const spi = (n, type) => [0, n, type];
    const children = [];
    // (SMC64's function numbers, SMC32's for a 32-bit kernel)
    const smc = m.arm32 ? 0x84000000 : 0xC4000000;
    children.push(node("psci", [
        ["migrate", [smc | 5]], ["cpu_on", [smc | 3]], ["cpu_off", [0x84000002]], ["cpu_suspend", [smc | 1]],
        ["method", "hvc"], ["compatible", ["arm,psci-1.0", "arm,psci-0.2", "arm,psci"]],
    ]));
    children.push(node("memory@" + VIRT_RAM_BASE.toString(16), [
        ["reg", [...u64(VIRT_RAM_BASE), ...u64(m.memory_size)]], ["device_type", "memory"],
    ]));
    // (extended RAM, P8.5: a second range from 4 GiB; the reference has one)
    if(m.extended)
    {
        children.push(node("memory@" + m.extended.base.toString(16), [
            ["reg", [...u64(m.extended.base), ...u64(m.extended.size)]], ["device_type", "memory"],
        ]));
    }
    for(let n = 0; n < VIRT_MMIO_COUNT; n++)
    {
        const base = VIRT_MMIO + n * VIRT_MMIO_SIZE;
        children.push(node("virtio_mmio@" + base.toString(16), [
            ["dma-coherent", true], ["interrupts", spi(16 + n, 1)], ["reg", [...u64(base), ...u64(VIRT_MMIO_SIZE)]],
            ["compatible", "virtio,mmio"],
        ]));
    }
    // (the PCIe host: pin p (1-4) of slot s is SPI 3 + (s + p - 1) % 4, level-triggered,
    // for the slots modulo 4; the windows: I/O, 32-bit memory, 64-bit memory)
    const interrupt_map = [];
    for(let slot = 0; slot < 4; slot++)
    {
        for(let pin = 1; pin <= 4; pin++)
        {
            interrupt_map.push(slot << 11, 0, 0, pin, gic, 0, 0, ...spi(3 + (slot + pin - 1) % 4, 4));
        }
    }
    const high = ([low, high_half]) => high_half * 0x100000000 + low;
    if(!m.arm32) children.push(node("pcie@" + VIRT_PCIE_MMIO.toString(16), [
        ["interrupt-map-mask", [0x1800, 0, 0, 7]], ["interrupt-map", interrupt_map], ["#interrupt-cells", [1]],
        ["ranges", [
            0x1000000, 0, 0, ...u64(VIRT_PCIE_PIO), ...u64(VIRT_PCIE_PIO_SIZE),
            0x2000000, ...u64(VIRT_PCIE_MMIO), ...u64(VIRT_PCIE_MMIO), ...u64(VIRT_PCIE_MMIO_SIZE),
            0x3000000, ...u64(high(VIRT_PCIE_MMIO_HIGH)), ...u64(high(VIRT_PCIE_MMIO_HIGH)), ...u64(VIRT_PCIE_MMIO_HIGH_SIZE),
        ]],
        ["reg", [...u64(high(VIRT_PCIE_ECAM_HIGH)), ...u64(VIRT_PCIE_ECAM_SIZE)]], ["dma-coherent", true],
        ["bus-range", [0, 0xFF]], ["linux,pci-domain", [0]], ["#size-cells", [2]], ["#address-cells", [3]],
        ["device_type", "pci"], ["compatible", "pci-host-ecam-generic"],
    ]));
    children.push(node("pl031@" + VIRT_RTC.toString(16), [
        ["clock-names", "apb_pclk"], ["clocks", [clock]], ["interrupts", spi(2, 4)], ["reg", [...u64(VIRT_RTC), ...u64(0x1000)]],
        ["compatible", ["arm,pl031", "arm,primecell"]],
    ]));
    children.push(node("pl011@" + VIRT_UART.toString(16), [
        ["clock-names", ["uartclk", "apb_pclk"]], ["clocks", [clock, clock]], ["interrupts", spi(1, 4)],
        ["reg", [...u64(VIRT_UART), ...u64(0x1000)]], ["compatible", ["arm,pl011", "arm,primecell"]],
    ]));
    children.push(node("intc@" + VIRT_GIC_DIST.toString(16), [
        ["phandle", [gic]],
        ["reg", [...u64(VIRT_GIC_DIST), ...u64(VIRT_GIC_DIST_SIZE), ...u64(VIRT_GIC_REDIST), ...u64(GIC_REDIST_REGION_SIZE)]],
        ["#redistributor-regions", [1]], ["compatible", "arm,gic-v3"], ["ranges", true], ["#size-cells", [2]],
        ["#address-cells", [2]], ["interrupt-controller", true], ["#interrupt-cells", [3]],
    ]));
    const cores = [], map = [];
    for(let i = 0; i < m.cores; i++)
    {
        map.push(node("core" + i, [["cpu", [cpu_phandle(i)]]]));
        // (enable-method only with secondary cores to start, as the reference writes it)
        cores.push(node("cpu@" + i, [
            ["phandle", [cpu_phandle(i)]], ["reg", [i]], ...(m.cores > 1 ? [["enable-method", "psci"]] : []),
            ["compatible", m.arm32 ? "arm,cortex-a15" : "arm,armv8"], ["device_type", "cpu"],
        ]));
    }
    children.push(node("cpus", [["#size-cells", [0]], ["#address-cells", [1]]], [
        node("cpu-map", [], [node("socket0", [], [node("cluster0", [], map)])]),
        ...cores,
    ]));
    // (the timers' PPIs in Linux's order: secure physical 29, non-secure physical 30, virtual 27, hypervisor 26)
    children.push(node("timer", [
        ["interrupts", [1, 13, 4, 1, 14, 4, 1, 11, 4, 1, 10, 4]], ["always-on", true],
        ["compatible", ["arm,armv8-timer", "arm,armv7-timer"]],
    ]));
    children.push(node("apb-pclk", [
        ["phandle", [clock]], ["clock-output-names", "clk24mhz"], ["clock-frequency", [APB_PCLK_HZ]], ["#clock-cells", [0]],
        ["compatible", "fixed-clock"],
    ]));
    children.push(node("aliases", [["serial0", "/pl011@" + VIRT_UART.toString(16)]]));
    const chosen = [["stdout-path", "/pl011@" + VIRT_UART.toString(16)]];
    if(m.bootargs !== undefined) chosen.push(["bootargs", m.bootargs]);
    if(m.initrd)
    {
        chosen.push(["linux,initrd-end", u64(m.initrd.end)], ["linux,initrd-start", u64(m.initrd.start)]);
    }
    if(m.rng_seed) chosen.push(["rng-seed", m.rng_seed]);
    children.push(node("chosen", chosen));
    return node("", [
        ["interrupt-parent", [gic]], ["dma-coherent", true], ["model", "linux,dummy-virt"], ["#size-cells", [2]],
        ["#address-cells", [2]], ["compatible", "linux,dummy-virt"],
    ], children);
}
                                                                    source/v64/src/virt/goldfish.js                                                                     0000644 0000000 0000000 00000101006 00000000000 013572  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Android emulator's goldfish devices, as the ranchu machine has them
// (docs/aarch32-plan.md R6.2; src/virt/ranchu.js): what its system images'
// kernels drive (Linux 3.10's drivers/video/goldfishfb.c,
// drivers/input/keyboard/goldfish_events.c, drivers/power/goldfish_battery.c,
// drivers/staging/goldfish/goldfish_audio.c, drivers/platform/goldfish/
// goldfish_pipe.c) with the emulator's register interfaces:
//
// - the framebuffer: RGB565, the size the machine gives, its base set by the
//   driver (a pan: the frame shown, and BASE_UPDATE_DONE); or, with
//   `scanout` (the ranchu machine's 32-bit kernel, whose goldfish_fb cannot
//   allocate its memory: LPAE without ZONE_DMA), a simple-framebuffer of the
//   device tree at a fixed place, shown at up to 20 frames a second when it changed;
// - the events: one device, "qwerty2" (the image's qwerty2.idc makes it a
//   touch screen and a keyboard): the bus's set-1 scancodes as EV_KEY, the
//   pointer and its left button as one touch (ABS_X/Y, MT slot 0, BTN_TOUCH);
//   one event per three reads of REG_READ, the interrupt up while any wait;
// - the battery: AC online, charging, full;
// - the audio output: two write buffers, each consumed in the time its
//   samples (16-bit stereo, 44.1 kHz) take, then BUFFER_EMPTY; nothing is
//   played; no input;
// - the pipe (version 1, no batch buffer: every command through the
//   registers): channels the guest opens, named by their first write
//   ("pipe:<service>\0"); the services are qemud's boot-properties (the
//   machine's properties, then an empty frame), hw-control and sensors
//   (accepted: no sensors, every control ignored), and those the machine
//   adds (the GLES host's "opengles" and "GLProcessPipe": src/gles/,
//   ranchu_gpu "host"); any other name is refused (the guest's open
//   fails, as for a service the emulator lacks).

/** Linux's input event types and codes (include/uapi/linux/input-event-codes.h) */
const EV_SYN = 0;
const EV_KEY = 1;
const EV_ABS = 3;
const SYN_REPORT = 0;
const ABS_X = 0;
const ABS_Y = 1;
const ABS_MT_SLOT = 0x2F;
const ABS_MT_POSITION_X = 0x35;
const ABS_MT_POSITION_Y = 0x36;
const ABS_MT_TRACKING_ID = 0x39;
const BTN_TOUCH = 0x14A;
const ABS_RANGE = 0x7FFF;
/** Set-1 scancodes after 0xE0 and their evdev key codes (src/virtio_input.js's) */
const EXTENDED_KEYS = new Map([
    [0x10, 165], [0x19, 163], [0x1C, 96], [0x1D, 97], [0x20, 113], [0x22, 164], [0x24, 166], [0x2E, 114], [0x30, 115],
    [0x35, 98], [0x37, 99], [0x38, 100], [0x47, 102], [0x48, 103], [0x49, 104], [0x4B, 105], [0x4D, 106], [0x4F, 107],
    [0x50, 108], [0x51, 109], [0x52, 110], [0x53, 111], [0x5B, 125], [0x5C, 126], [0x5D, 127], [0x5E, 116],
    [0x5F, 142], [0x63, 143],
]);
const plain_key = code => code >= 0x01 && code <= 0x58 && code !== 0x54 && code !== 0x55 ? code : 0;
/** The keys besides the keyboard's: HOME, BACK, MENU, POWER, the volume, SEARCH, APPSELECT */
const ANDROID_KEYS = [102, 158, 139, 116, 114, 115, 217, 580];

/**
 * @param {!Array<number>} bits
 * @return {!Uint8Array} a bitmap of them
 */
function bitmap(bits)
{
    const bytes = new Uint8Array(bits.length ? (Math.max(...bits) >> 3) + 1 : 0);
    for(const bit of bits) bytes[bit >> 3] |= 1 << (bit & 7);
    return bytes;
}

// ---- the framebuffer

const FB_GET_WIDTH = 0x00;
const FB_GET_HEIGHT = 0x04;
const FB_INT_STATUS = 0x08;
const FB_INT_ENABLE = 0x0C;
const FB_SET_BASE = 0x10;
const FB_SET_ROTATION = 0x14;
const FB_SET_BLANK = 0x18;
const FB_GET_PHYS_WIDTH = 0x1C;
const FB_GET_PHYS_HEIGHT = 0x20;
const FB_INT_VSYNC = 1;
const FB_INT_BASE_UPDATE_DONE = 2;

/**
 * @constructor
 * @param {?} cpu the ARM CPU (src/arm/cpu.js)
 * @param {number} base
 * @param {number} intid
 * @param {{width: number, height: number, dpi: number}} display
 * @param {number=} scanout a simple-framebuffer's base, shown without the driver's pans
 */
export function GoldfishFb(cpu, base, intid, display, scanout = 0)
{
    this.scanout = scanout;
    /** (scanout) the frame last shown, and the vblanks since */
    this.shown = null;
    this.vblanks = 0;
    /** the frames drawn to the screen (diagnostics) */
    this.frames = 0;
    this.name = "goldfish-fb";
    this.cpu = cpu;
    this.intid = intid;
    this.width = display.width;
    this.height = display.height;
    this.dpi = display.dpi;
    this.rgba = new Uint8ClampedArray(this.width * this.height * 4);
    this.reset();
    cpu.io.register_mmio(base, 0x1000, {
        read: offset => this.read(offset),
        write: (offset, width, value) => this.write(offset, Number(value)),
        name: this.name,
    });
    /** @type {?} the display hub (src/display.js) */
    this.hub = cpu.devices.display;
    this.hub.add_source(this);
    this.hub.set_mode(true);
    this.hub.set_size_graphical(this.width, this.height, this.width, this.height, 32);
}

GoldfishFb.prototype.reset = function()
{
    this.base = this.scanout;
    this.int_status = 0;
    this.int_enable = 0;
    this.blank = 0;
    this.rotation = 0;
    this.dirty = true;
};

GoldfishFb.prototype.update_irq = function()
{
    this.cpu.set_irq(this.intid, (this.int_status & this.int_enable) !== 0);
};

GoldfishFb.prototype.read = function(offset)
{
    switch(offset)
    {
        case FB_GET_WIDTH: return this.width;
        case FB_GET_HEIGHT: return this.height;
        case FB_INT_STATUS:
        {
            const status = this.int_status & this.int_enable;
            this.int_status = 0;
            this.update_irq();
            return status;
        }
        case FB_INT_ENABLE: return this.int_enable;
        // (the screen's size in millimetres at its density)
        case FB_GET_PHYS_WIDTH: return Math.round(this.width * 25.4 / this.dpi);
        case FB_GET_PHYS_HEIGHT: return Math.round(this.height * 25.4 / this.dpi);
    }
    return 0;
};

GoldfishFb.prototype.write = function(offset, value)
{
    switch(offset)
    {
        case FB_INT_ENABLE:
            this.int_enable = value;
            this.update_irq();
            break;
        case FB_SET_BASE:
            // (a pan: this frame is the one shown)
            this.base = value >>> 0;
            this.dirty = true;
            this.render();
            this.int_status |= FB_INT_BASE_UPDATE_DONE;
            this.update_irq();
            break;
        case FB_SET_ROTATION: this.rotation = value; break;
        case FB_SET_BLANK: this.blank = value; this.dirty = true; break;
    }
};

// (DisplaySource: src/display.js)
GoldfishFb.prototype.vblank_period = function() { return 1000 / 60; };
GoldfishFb.prototype.on_vblank = function()
{
    // (a simple-framebuffer: every third retrace, if its bytes changed)
    if(this.scanout && ++this.vblanks % 3 === 0) this.render_changed();
    if(this.int_enable & FB_INT_VSYNC)
    {
        this.int_status |= FB_INT_VSYNC;
        this.update_irq();
    }
};
GoldfishFb.prototype.invalidate = function() { this.dirty = true; };

/** (scanout) the frame, if it is not the one shown */
GoldfishFb.prototype.render_changed = function()
{
    let bytes;
    try { bytes = this.cpu.read_blob_physical(this.base, this.width * this.height * 2); }
    catch(e) { return; }
    const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.length >> 2);
    const shown = this.shown;
    if(shown && !this.dirty)
    {
        let same = true;
        for(let i = 0; i < words.length; i++) if(words[i] !== shown[i]) { same = false; break; }
        if(same) return;
    }
    this.shown = words;
    this.dirty = true;
    this.render(bytes);
};

/**
 * The frame at the base, RGB565, to the screen
 * @param {Uint8Array=} source its bytes, read already
 */
GoldfishFb.prototype.render = function(source)
{
    if(!this.dirty || !this.base) return;
    this.dirty = false;
    this.frames++;
    const pixels = this.width * this.height;
    const rgba = this.rgba;
    if(this.blank)
    {
        rgba.fill(0);
        for(let i = 3; i < rgba.length; i += 4) rgba[i] = 255;
    }
    else
    {
        if(!source)
        {
            try { source = this.cpu.read_blob_physical(this.base, pixels * 2); }
            catch(e) { return; }
        }
        const words = new Uint16Array(source.buffer, source.byteOffset, pixels);
        for(let i = 0, o = 0; i < pixels; i++, o += 4)
        {
            const p = words[i];
            const r = p >> 11, g = p >> 5 & 63, b = p & 31;
            rgba[o] = r << 3 | r >> 2;
            rgba[o + 1] = g << 2 | g >> 4;
            rgba[o + 2] = b << 3 | b >> 2;
            rgba[o + 3] = 255;
        }
    }
    this.hub.update_buffer([{ pixels: { data: rgba, width: this.width, height: this.height }, screen_x: 0, screen_y: 0,
        buffer_x: 0, buffer_y: 0, buffer_width: this.width, buffer_height: this.height }]);
};

/**
 * A frame from the GLES host (ranchu_gpu "host": SurfaceFlinger's posts,
 * read back from the page), RGBA rows from the top, shown in place of the
 * framebuffer's: its size the display's, or cut to it
 * @param {!Uint8Array} rgba
 * @param {number} width
 * @param {number} height
 */
GoldfishFb.prototype.present = function(rgba, width, height)
{
    this.frames++;
    const w = Math.min(width, this.width), h = Math.min(height, this.height);
    if(w === this.width && h === this.height && width === this.width) this.rgba.set(rgba.subarray(0, this.rgba.length));
    else for(let y = 0; y < h; y++) this.rgba.set(rgba.subarray(y * width * 4, (y * width + w) * 4), y * this.width * 4);
    this.hub.update_buffer([{ pixels: { data: this.rgba, width: this.width, height: this.height }, screen_x: 0, screen_y: 0,
        buffer_x: 0, buffer_y: 0, buffer_width: this.width, buffer_height: this.height }]);
};

GoldfishFb.prototype.get_state = function()
{
    return [this.base, this.int_status, this.int_enable, this.blank, this.rotation];
};
GoldfishFb.prototype.set_state = function(state)
{
    [this.base, this.int_status, this.int_enable, this.blank, this.rotation] = state;
    this.dirty = true;
    this.update_irq();
};

// ---- the events

const REG_READ = 0x00;
const REG_SET_PAGE = 0x00;
const REG_LEN = 0x04;
const REG_DATA = 0x08;
const PAGE_NAME = 0x00000;
const PAGE_EVBITS = 0x10000;
const PAGE_ABSDATA = 0x20000 | EV_ABS;
const EVENTS_LIMIT = 1024;

/**
 * @constructor
 * @param {?} cpu
 * @param {?} bus the device bus (the host's keyboard and pointer)
 * @param {number} base
 * @param {number} intid
 */
export function GoldfishEvents(cpu, bus, base, intid)
{
    this.name = "goldfish-events";
    this.cpu = cpu;
    this.bus = bus;
    this.intid = intid;
    /** @type {boolean|undefined} a driver probed (mouse-enable said) */
    this.driver = undefined;
    const keys = [];
    for(let k = 1; k < 256; k++) keys.push(k);
    keys.push(...ANDROID_KEYS, BTN_TOUCH);
    const abs = [ABS_X, ABS_Y, ABS_MT_SLOT, ABS_MT_POSITION_X, ABS_MT_POSITION_Y, ABS_MT_TRACKING_ID];
    /** the pages: the name, each event type's bits, the axes' ranges (min, max, fuzz, flat) */
    this.pages = new Map([
        [PAGE_NAME, new TextEncoder().encode("qwerty2")],
        [PAGE_EVBITS | EV_SYN, bitmap([EV_SYN, EV_KEY, EV_ABS])],
        [PAGE_EVBITS | EV_KEY, bitmap(keys)],
        [PAGE_EVBITS | EV_ABS, bitmap(abs)],
    ]);
    const ranges = new Uint32Array(4 * (ABS_MT_TRACKING_ID + 1));
    for(const axis of [ABS_X, ABS_Y, ABS_MT_POSITION_X, ABS_MT_POSITION_Y]) ranges.set([0, ABS_RANGE, 0, 0], 4 * axis);
    ranges.set([0, 0, 0, 0], 4 * ABS_MT_SLOT);
    ranges.set([0, 0xFFFF, 0, 0], 4 * ABS_MT_TRACKING_ID);
    this.pages.set(PAGE_ABSDATA, new Uint8Array(ranges.buffer));
    this.reset();
    cpu.io.register_mmio(base, 0x1000, {
        read: (offset, width) => this.read(offset, width),
        write: (offset, width, value) => this.write(offset, Number(value)),
        name: this.name,
    });
    bus.register("keyboard-code", code => this.scancode(code), this);
    bus.register("mouse-absolute", data => this.absolute(data), this);
    bus.register("mouse-click", data => this.click(data), this);
}

GoldfishEvents.prototype.reset = function()
{
    this.page = PAGE_NAME;
    /** @type {!Array<number>} type, code, value, ... */
    this.queue = [];
    this.read_index = 0;
    this.prefix = 0;
    this.touching = false;
    this.tracking_id = 0;
    this.x = 0;
    this.y = 0;
    this.update_irq();
    this.driver_ready(false);
};

/**
 * The guest's driver probes (it selects the pages: the name, the event bits,
 * the axes) or the machine resets: the page's mouse adapter takes the mouse
 * and touches over the screen only while a driver runs (src/browser/mouse.js:
 * "mouse-enable", as the PS/2 controller says for its mouse; ranchu has none).
 * A touch screen's positions are absolute and it has no cursor of its own
 * ("absolute-pointer"): the page locks no pointer and keeps the host's cursor.
 * @param {boolean} ready
 */
GoldfishEvents.prototype.driver_ready = function(ready)
{
    if(ready === this.driver) return;
    this.driver = ready;
    this.bus.send("mouse-enable", ready);
    this.bus.send("absolute-pointer", [ready, false]);
};

GoldfishEvents.prototype.update_irq = function()
{
    this.cpu.set_irq(this.intid, this.queue.length > 0);
};

GoldfishEvents.prototype.read = function(offset, width)
{
    if(offset === REG_READ)
    {
        if(!this.queue.length) return 0;
        const value = this.queue.shift();
        if(!this.queue.length) this.update_irq();
        return value >>> 0;
    }
    const page = this.pages.get(this.page) || new Uint8Array(0);
    if(offset === REG_LEN) return page.length;
    if(offset >= REG_DATA)
    {
        let value = 0;
        for(let i = 0; i < width; i++) value |= (page[offset - REG_DATA + i] || 0) << (8 * i);
        return value >>> 0;
    }
    return 0;
};

GoldfishEvents.prototype.write = function(offset, value)
{
    if(offset === REG_SET_PAGE)
    {
        this.page = value >>> 0;
        this.driver_ready(true);
    }
};

/** @param {!Array<!Array<number>>} events [type, code, value]..., SYN_REPORT after them */
GoldfishEvents.prototype.send = function(events)
{
    for(const [type, code, value] of events) this.queue.push(type, code, value);
    this.queue.push(EV_SYN, SYN_REPORT, 0);
    // (a guest that does not read them: the oldest go)
    if(this.queue.length > 3 * EVENTS_LIMIT) this.queue.splice(0, this.queue.length - 3 * EVENTS_LIMIT);
    this.update_irq();
};

/** @param {number} code a set-1 scancode byte */
GoldfishEvents.prototype.scancode = function(code)
{
    code &= 0xFF;
    if(code === 0xE0)
    {
        this.prefix = 0xE0;
        return;
    }
    const extended = this.prefix === 0xE0;
    this.prefix = 0;
    const make = code & 0x7F;
    const key = extended ? EXTENDED_KEYS.get(make) || 0 : plain_key(make);
    if(key) this.send([[EV_KEY, key, code & 0x80 ? 0 : 1]]);
};

/** @param {!Array<number>} data [x, y, width, height] of the pointer on the screen */
GoldfishEvents.prototype.absolute = function(data)
{
    this.x = Math.max(0, Math.min(ABS_RANGE, Math.round(data[0] / data[2] * ABS_RANGE)));
    this.y = Math.max(0, Math.min(ABS_RANGE, Math.round(data[1] / data[3] * ABS_RANGE)));
    if(this.touching)
    {
        this.send([[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_POSITION_X, this.x], [EV_ABS, ABS_MT_POSITION_Y, this.y],
            [EV_ABS, ABS_X, this.x], [EV_ABS, ABS_Y, this.y]]);
    }
};

/** @param {!Array<boolean>} data [left, middle, right]: the left button touches */
GoldfishEvents.prototype.click = function(data)
{
    const down = !!data[0];
    if(down === this.touching) return;
    this.touching = down;
    if(down)
    {
        this.tracking_id = this.tracking_id + 1 & 0xFFFF;
        this.send([[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_TRACKING_ID, this.tracking_id], [EV_ABS, ABS_MT_POSITION_X, this.x],
            [EV_ABS, ABS_MT_POSITION_Y, this.y], [EV_KEY, BTN_TOUCH, 1], [EV_ABS, ABS_X, this.x], [EV_ABS, ABS_Y, this.y]]);
    }
    else
    {
        this.send([[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_TRACKING_ID, -1], [EV_KEY, BTN_TOUCH, 0]]);
    }
};

/**
 * A touch at (x, y) in the screen's pixels of width by height, down and up (tests)
 * @param {number} x @param {number} y @param {number} width @param {number} height
 */
GoldfishEvents.prototype.tap = function(x, y, width, height)
{
    this.absolute([x, y, width, height]);
    this.click([true]);
    this.click([false]);
};

GoldfishEvents.prototype.get_state = function() { return [this.page, this.queue.slice(), this.tracking_id, this.driver]; };
GoldfishEvents.prototype.set_state = function(state)
{
    [this.page, this.queue, this.tracking_id] = state;
    this.touching = false;
    this.update_irq();
    // (older states: a driver that probed left another page selected)
    this.driver = undefined;
    this.driver_ready(state[3] ?? this.page !== PAGE_NAME);
};

// ---- the battery

const BATTERY_INT_STATUS = 0x00;
const BATTERY_INT_ENABLE = 0x04;
const BATTERY_AC_ONLINE = 0x08;
const BATTERY_STATUS = 0x0C;
const BATTERY_HEALTH = 0x10;
const BATTERY_PRESENT = 0x14;
const BATTERY_CAPACITY = 0x18;

/**
 * @constructor
 * @param {?} cpu
 * @param {number} base
 */
export function GoldfishBattery(cpu, base)
{
    this.name = "goldfish-battery";
    this.int_enable = 0;
    cpu.io.register_mmio(base, 0x1000, {
        read: offset => this.read(offset),
        write: (offset, width, value) => { if(offset === BATTERY_INT_ENABLE) this.int_enable = Number(value); },
        name: this.name,
    });
}

GoldfishBattery.prototype.read = function(offset)
{
    switch(offset)
    {
        case BATTERY_INT_STATUS: return 0;
        case BATTERY_INT_ENABLE: return this.int_enable;
        case BATTERY_AC_ONLINE: return 1;
        // (POWER_SUPPLY_STATUS_CHARGING, POWER_SUPPLY_HEALTH_GOOD)
        case BATTERY_STATUS: return 1;
        case BATTERY_HEALTH: return 1;
        case BATTERY_PRESENT: return 1;
        case BATTERY_CAPACITY: return 100;
    }
    return 0;
};

GoldfishBattery.prototype.get_state = function() { return [this.int_enable]; };
GoldfishBattery.prototype.set_state = function(state) { [this.int_enable] = state; };

// ---- the audio output

const AUDIO_INT_STATUS = 0x00;
const AUDIO_INT_ENABLE = 0x04;
const AUDIO_SET_WRITE_BUFFER_1 = 0x08;
const AUDIO_SET_WRITE_BUFFER_2 = 0x0C;
const AUDIO_WRITE_BUFFER_1 = 0x10;
const AUDIO_WRITE_BUFFER_2 = 0x14;
const AUDIO_READ_SUPPORTED = 0x18;
const AUDIO_INT_WRITE_BUFFER_1_EMPTY = 1;
const AUDIO_INT_WRITE_BUFFER_2_EMPTY = 2;
/** 16-bit stereo at 44.1 kHz, in bytes a millisecond */
const AUDIO_BYTES_PER_MS = 44100 * 4 / 1000;

/**
 * @constructor
 * @param {?} cpu
 * @param {number} base
 * @param {number} intid
 */
export function GoldfishAudio(cpu, base, intid)
{
    this.name = "goldfish-audio";
    this.cpu = cpu;
    this.intid = intid;
    this.reset();
    cpu.io.register_mmio(base, 0x1000, {
        read: offset => this.read(offset),
        write: (offset, width, value) => this.write(offset, Number(value)),
        name: this.name,
    });
}

GoldfishAudio.prototype.reset = function()
{
    this.int_status = 0;
    this.int_enable = 0;
    /** when each buffer is consumed (machine milliseconds), or -1 */
    this.done = [-1, -1];
};

GoldfishAudio.prototype.update_irq = function()
{
    this.cpu.set_irq(this.intid, (this.int_status & this.int_enable) !== 0);
};

GoldfishAudio.prototype.read = function(offset)
{
    if(offset === AUDIO_INT_STATUS)
    {
        this.timer(this.cpu.clock.now());
        const status = this.int_status;
        this.int_status = 0;
        this.update_irq();
        return status;
    }
    if(offset === AUDIO_INT_ENABLE) return this.int_enable;
    if(offset === AUDIO_READ_SUPPORTED) return 0;
    return 0;
};

GoldfishAudio.prototype.write = function(offset, value)
{
    switch(offset)
    {
        case AUDIO_INT_ENABLE:
            this.int_enable = value;
            this.update_irq();
            break;
        case AUDIO_SET_WRITE_BUFFER_1:
        case AUDIO_SET_WRITE_BUFFER_2:
            break;
        case AUDIO_WRITE_BUFFER_1:
        case AUDIO_WRITE_BUFFER_2:
        {
            const which = offset === AUDIO_WRITE_BUFFER_1 ? 0 : 1;
            this.done[which] = this.cpu.clock.now() + (value >>> 0) / AUDIO_BYTES_PER_MS;
            break;
        }
    }
};

/**
 * (the machine's timers) the buffers whose samples have been played; milliseconds until the next
 * @param {number} now
 * @return {number}
 */
GoldfishAudio.prototype.timer = function(now)
{
    let next = Infinity;
    for(let i = 0; i < 2; i++)
    {
        if(this.done[i] < 0) continue;
        if(now >= this.done[i])
        {
            this.done[i] = -1;
            this.int_status |= i === 0 ? AUDIO_INT_WRITE_BUFFER_1_EMPTY : AUDIO_INT_WRITE_BUFFER_2_EMPTY;
            this.update_irq();
        }
        else next = Math.min(next, this.done[i] - now);
    }
    return next;
};

GoldfishAudio.prototype.get_state = function() { return [this.int_status, this.int_enable, this.done.slice()]; };
GoldfishAudio.prototype.set_state = function(state)
{
    [this.int_status, this.int_enable, this.done] = state;
    // (the clock's restored time: the buffers' times stay as they were)
    this.update_irq();
};

// ---- the pipe

const PIPE_REG_COMMAND = 0x00;
const PIPE_REG_STATUS = 0x04;
const PIPE_REG_CHANNEL = 0x08;
const PIPE_REG_SIZE = 0x0C;
const PIPE_REG_ADDRESS = 0x10;
const PIPE_REG_WAKES = 0x14;
const PIPE_REG_PARAMS_ADDR_LOW = 0x18;
const PIPE_REG_PARAMS_ADDR_HIGH = 0x1C;
const PIPE_REG_CHANNEL_HIGH = 0x30;
const PIPE_REG_ADDRESS_HIGH = 0x34;
const PIPE_REG_VERSION = 0x24;
const CMD_OPEN = 1;
const CMD_CLOSE = 2;
const CMD_POLL = 3;
const CMD_WRITE_BUFFER = 4;
const CMD_WAKE_ON_WRITE = 5;
const CMD_READ_BUFFER = 6;
const CMD_WAKE_ON_READ = 7;
const PIPE_POLL_IN = 1;
const PIPE_POLL_OUT = 2;
const PIPE_POLL_HUP = 4;
const PIPE_ERROR_INVAL = -1;
const PIPE_ERROR_AGAIN = -2;
const PIPE_ERROR_IO = -4;
const PIPE_WAKE_CLOSED = 1;
const PIPE_WAKE_READ = 2;
const PIPE_WAKE_WRITE = 4;

/**
 * A pipe's service: write(bytes) what the guest wrote, read(max) at most
 * max bytes for the guest (null: none now), available() whether there are
 * any, close() the guest closed the channel; get_state() what a snapshot
 * keeps of it (without one, its channel is closed at the restore)
 * @typedef {{write: function(!Uint8Array), read: function(number): ?Uint8Array, available: function(): boolean, close: function(),
 *     get_state: (function(): *|undefined)}}
 */
export let PipeService;

/**
 * A qemud service over a pipe: framed messages (four hex digits of length, then the bytes)
 * @param {function(string): (!Array<string>|undefined)} answer the frames to send back for one received
 * @param {*=} saved its state in a snapshot
 * @return {!PipeService}
 */
function qemud_service(answer, saved)
{
    let input = saved ? saved[0] : new Uint8Array(0);
    let output = saved ? saved[1] : new Uint8Array(0);
    return {
        get_state: () => [input.slice(), output.slice()],
        write(bytes)
        {
            const joined = new Uint8Array(input.length + bytes.length);
            joined.set(input);
            joined.set(bytes, input.length);
            input = joined;
            const frames = [];
            while(input.length >= 4)
            {
                const length = parseInt(new TextDecoder().decode(input.subarray(0, 4)), 16);
                if(!(length >= 0) || input.length < 4 + length) break;
                const message = new TextDecoder().decode(input.subarray(4, 4 + length));
                input = input.slice(4 + length);
                for(const frame of answer(message) || [])
                {
                    const body = new TextEncoder().encode(frame);
                    frames.push(...new TextEncoder().encode(body.length.toString(16).padStart(4, "0")), ...body);
                }
            }
            if(frames.length)
            {
                const joined_output = new Uint8Array(output.length + frames.length);
                joined_output.set(output);
                joined_output.set(frames, output.length);
                output = joined_output;
            }
        },
        read(max)
        {
            if(!output.length) return null;
            const bytes = output.subarray(0, max);
            output = output.subarray(bytes.length);
            return bytes;
        },
        available() { return output.length > 0; },
        close() {},
    };
}

/**
 * @constructor
 * @param {?} cpu
 * @param {number} base
 * @param {number} intid
 * @param {!Object<string, string>} properties the boot properties (qemu-props sets them)
 * @param {(function(string, function(), *=): ?PipeService)=} services the machine's
 *     other services: a name, the call that wakes the channel's reader
 *     (bytes became readable later) and at a restore the service's state,
 *     to the service, or null
 */
export function GoldfishPipe(cpu, base, intid, properties, services)
{
    this.name = "goldfish-pipe";
    this.cpu = cpu;
    this.intid = intid;
    this.properties = properties;
    this.services = services || (() => null);
    /** register accesses and the bytes moved, by command (diagnostics: the cost of pipe v1's traps) */
    this.stats = { mmio: 0, writes: 0, reads: 0, bytes_written: 0, bytes_read: 0 };
    this.reset();
    cpu.io.register_mmio(base, 0x2000, {
        read: offset => { this.stats.mmio++; return this.read(offset); },
        write: (offset, width, value) => { this.stats.mmio++; this.write(offset, Number(value)); },
        name: this.name,
    });
}

GoldfishPipe.prototype.reset = function()
{
    this.channel = 0;
    this.wake_channel = 0;
    this.size = 0;
    this.address = 0;
    this.status = 0;
    // (the guest's channels go: their services are closed)
    for(const pipe of this.pipes ? this.pipes.values() : []) if(pipe.service) pipe.service.close();
    /** @type {!Map<number, {name: string, pending: !Array<number>, service: ?PipeService, wake_read: boolean, wakes: number, closed: boolean}>} */
    this.pipes = new Map();
    this.update_irq();
};

GoldfishPipe.prototype.update_irq = function()
{
    let any = false;
    for(const pipe of this.pipes.values()) if(pipe.wakes) any = true;
    this.cpu.set_irq(this.intid, any);
};

/**
 * The service a pipe's name connects it to, or null
 * @param {string} name
 * @param {function()} wake
 * @param {*=} saved the service's state in a snapshot
 * @return {?PipeService}
 */
GoldfishPipe.prototype.connect = function(name, wake, saved)
{
    if(name === "qemud:boot-properties")
    {
        return qemud_service(message => message === "list" ?
            [...Object.entries(this.properties).map(([key, value]) => key + "=" + value), "\0"] : [], saved);
    }
    // (sensors.ranchu: no sensors; lights, vibrator and power: ignored)
    if(name === "qemud:sensors") return qemud_service(message => message === "list-sensors" ? ["0"] : [], saved);
    if(name === "qemud:hw-control") return qemud_service(() => [], saved);
    return this.services(name, wake, saved);
};

GoldfishPipe.prototype.read = function(offset)
{
    switch(offset)
    {
        case PIPE_REG_STATUS: return this.status >>> 0;
        case PIPE_REG_CHANNEL:
        {
            // (the next channel with wakes, which REG_WAKES then gives; 0: none)
            for(const [channel, pipe] of this.pipes)
            {
                if(pipe.wakes)
                {
                    this.wake_channel = channel;
                    return channel;
                }
            }
            this.update_irq();
            return 0;
        }
        case PIPE_REG_CHANNEL_HIGH: return 0;
        case PIPE_REG_WAKES:
        {
            const pipe = this.pipes.get(this.wake_channel);
            if(!pipe) return 0;
            const wakes = pipe.wakes;
            pipe.wakes = 0;
            if(pipe.closed) this.pipes.delete(this.wake_channel);
            this.update_irq();
            return wakes;
        }
        // (no batch buffer: the driver reads back what it wrote and finds it 0)
        case PIPE_REG_PARAMS_ADDR_LOW:
        case PIPE_REG_PARAMS_ADDR_HIGH: return 0;
        case PIPE_REG_VERSION: return 1;
    }
    return 0;
};

GoldfishPipe.prototype.write = function(offset, value)
{
    switch(offset)
    {
        case PIPE_REG_CHANNEL: this.channel = value >>> 0; break;
        case PIPE_REG_CHANNEL_HIGH: break;
        case PIPE_REG_SIZE: this.size = value >>> 0; break;
        case PIPE_REG_ADDRESS: this.address = value >>> 0; break;
        case PIPE_REG_ADDRESS_HIGH: break;
        case PIPE_REG_COMMAND: this.status = this.command(value); break;
    }
};

/**
 * @param {number} command
 * @return {number} the status
 */
GoldfishPipe.prototype.command = function(command)
{
    const channel = this.channel;
    if(command === CMD_OPEN)
    {
        const old = this.pipes.get(channel);
        if(old && old.service) old.service.close();
        this.pipes.set(channel, { name: "", pending: [], service: null, wake_read: false, wakes: 0, closed: false });
        return 0;
    }
    const pipe = this.pipes.get(channel);
    if(!pipe) return PIPE_ERROR_INVAL;
    switch(command)
    {
        case CMD_CLOSE:
            if(pipe.service) pipe.service.close();
            this.pipes.delete(channel);
            this.update_irq();
            return 0;
        case CMD_POLL:
            return (pipe.service && pipe.service.available() ? PIPE_POLL_IN : 0) | PIPE_POLL_OUT | (pipe.closed ? PIPE_POLL_HUP : 0);
        case CMD_WRITE_BUFFER:
        {
            if(pipe.closed) return PIPE_ERROR_IO;
            let bytes;
            try { bytes = this.cpu.read_blob_physical(this.address, this.size); }
            catch(e) { return PIPE_ERROR_INVAL; }
            if(!pipe.service)
            {
                // (the name: up to its NUL, "pipe:" first)
                const end = bytes.indexOf(0);
                pipe.pending.push(...(end < 0 ? bytes : bytes.subarray(0, end)));
                if(end < 0) return bytes.length;
                const name = new TextDecoder().decode(new Uint8Array(pipe.pending)).replace(/^pipe:/, "");
                pipe.name = name;
                pipe.service = this.connect(name, () => this.wake_reader(pipe));
                if(!pipe.service) return PIPE_ERROR_INVAL;
                if(end + 1 < bytes.length) pipe.service.write(bytes.subarray(end + 1));
                this.wake_reader(pipe);
                return bytes.length;
            }
            pipe.service.write(bytes);
            this.stats.writes++;
            this.stats.bytes_written += bytes.length;
            this.wake_reader(pipe);
            return bytes.length;
        }
        case CMD_READ_BUFFER:
        {
            const bytes = pipe.service && pipe.service.read(this.size);
            if(!bytes || !bytes.length) return pipe.closed ? 0 : PIPE_ERROR_AGAIN;
            this.cpu.write_blob_physical(bytes, this.address);
            this.stats.reads++;
            this.stats.bytes_read += bytes.length;
            return bytes.length;
        }
        case CMD_WAKE_ON_READ:
            pipe.wake_read = true;
            this.wake_reader(pipe);
            return 0;
        case CMD_WAKE_ON_WRITE:
            // (writes never wait)
            pipe.wakes |= PIPE_WAKE_WRITE;
            this.update_irq();
            return 0;
    }
    return PIPE_ERROR_INVAL;
};

/** A waiting reader woken when the service has bytes for it */
GoldfishPipe.prototype.wake_reader = function(pipe)
{
    if(pipe.wake_read && pipe.service && pipe.service.available())
    {
        pipe.wake_read = false;
        pipe.wakes |= PIPE_WAKE_READ;
        this.update_irq();
    }
};

// A snapshot keeps each channel with its service's state (docs/gles-proxy-plan.md
// E5); a channel whose service keeps none is closed at the restore (its client
// sees its pipe closed), as every channel was before (a list of channels)
const PIPE_STATE_VERSION = 2;

GoldfishPipe.prototype.get_state = function()
{
    return [PIPE_STATE_VERSION, [...this.pipes].map(([channel, p]) => [channel, p.name, new Uint8Array(p.pending), p.wake_read, p.wakes, p.closed,
        p.service && p.service.get_state ? p.service.get_state() : null])];
};

GoldfishPipe.prototype.set_state = function(state)
{
    this.reset();
    const saved = state && state[0] === PIPE_STATE_VERSION && Array.isArray(state[1]) ? state[1] :
        (state || []).map(channel => [channel, "", null, false, PIPE_WAKE_CLOSED, true, null]);
    for(const [channel, name, pending, wake_read, wakes, closed, service_state] of saved)
    {
        // (a channel whose name is not whole yet goes on with its bytes)
        const pipe = { name, pending: pending ? [...pending] : [], service: null, wake_read, wakes, closed };
        if(name && !closed)
        {
            pipe.service = service_state === null ? null : this.connect(name, () => this.wake_reader(pipe), service_state);
            if(!pipe.service)
            {
                pipe.closed = true;
                pipe.wakes |= PIPE_WAKE_CLOSED;
            }
        }
        this.pipes.set(channel, pipe);
    }
    this.update_irq();
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/src/virt/inflate.js                                                                      0000644 0000000 0000000 00000020110 00000000000 013411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // DEFLATE (RFC 1951) and gzip (RFC 1952) decompression, synchronous, for
// the kernels the virt machine loads (docs/arm64-virt-android16-plan.md
// P4.6: an EFI zboot vmlinuz carries its Image gzipped; the browser's
// DecompressionStream is asynchronous and machine setup is not).

const LENGTH_BASE = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258];
const LENGTH_EXTRA = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0];
const DIST_BASE = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
    4097, 6145, 8193, 12289, 16385, 24577];
const DIST_EXTRA = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13];
const CODE_LENGTH_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];

/**
 * A canonical Huffman code from its code lengths: counts per length and
 * the symbols sorted by code
 */
function huffman(lengths)
{
    const counts = new Uint16Array(16);
    for(const l of lengths) counts[l]++;
    counts[0] = 0;
    const offsets = new Uint16Array(16);
    for(let l = 1; l < 16; l++) offsets[l] = offsets[l - 1] + counts[l - 1];
    const symbols = new Uint16Array(lengths.length);
    lengths.forEach((l, symbol) => { if(l) symbols[offsets[l]++] = symbol; });
    return { counts, symbols };
}

// (thrown inside inflate when the output reaches its limit)
const LIMIT_REACHED = {};

/**
 * Inflate a raw DEFLATE stream
 * @param {!Uint8Array} input
 * @param {number=} start
 * @param {number=} size_hint the output's size, if known
 * @param {number=} limit the most bytes to produce: decoding stops there,
 *     even inside the stream (a disk image's compressed cluster:
 *     docs/disk-image-formats-plan.md P2)
 * @return {{output: !Uint8Array, end: number}} the data and where the stream ended (or stopped)
 */
export function inflate(input, start = 0, size_hint = 0, limit = Infinity)
{
    let pos = start, bitbuf = 0, bitcount = 0;
    let out = new Uint8Array(Math.max(Math.min(size_hint, limit), Math.min(1 << 16, limit))), out_len = 0;
    const ensure = n => {
        if(out_len + n <= out.length) return;
        let size = out.length * 2;
        while(size < out_len + n) size *= 2;
        const bigger = new Uint8Array(size);
        bigger.set(out.subarray(0, out_len));
        out = bigger;
    };
    const bits = n => {
        while(bitcount < n)
        {
            if(pos >= input.length) throw new Error("inflate: the stream ends early");
            bitbuf |= input[pos++] << bitcount;
            bitcount += 8;
        }
        const value = bitbuf & ((1 << n) - 1);
        bitbuf >>>= n;
        bitcount -= n;
        return value;
    };
    const decode = h => {
        let code = 0, first = 0, index = 0;
        for(let l = 1; l < 16; l++)
        {
            code |= bits(1);
            const count = h.counts[l];
            if(code - count < first) return h.symbols[index + (code - first)];
            index += count;
            first += count;
            first <<= 1;
            code <<= 1;
        }
        throw new Error("inflate: a bad Huffman code");
    };
    const fixed_lengths = new Uint8Array(288);
    fixed_lengths.fill(8, 0, 144); fixed_lengths.fill(9, 144, 256); fixed_lengths.fill(7, 256, 280); fixed_lengths.fill(8, 280, 288);
    const fixed_literal = huffman(fixed_lengths), fixed_distance = huffman(new Uint8Array(30).fill(5));
    try
    {
        for(;;)
        {
            const last = bits(1);
            const type = bits(2);
            if(type === 0)
            {
                bitbuf = 0; bitcount = 0;
                if(pos + 4 > input.length) throw new Error("inflate: the stream ends early");
                const len = input[pos] | input[pos + 1] << 8;
                if((input[pos + 2] | input[pos + 3] << 8) !== (len ^ 0xFFFF)) throw new Error("inflate: a stored block's length check fails");
                pos += 4;
                if(pos + len > input.length) throw new Error("inflate: the stream ends early");
                const n = Math.min(len, limit - out_len);
                ensure(n);
                out.set(input.subarray(pos, pos + n), out_len);
                out_len += n;
                pos += len;
                if(n < len) throw LIMIT_REACHED;
            }
            else
            {
                let literal = fixed_literal, distance = fixed_distance;
                if(type === 2)
                {
                    const hlit = bits(5) + 257, hdist = bits(5) + 1, hclen = bits(4) + 4;
                    const code_lengths = new Uint8Array(19);
                    for(let i = 0; i < hclen; i++) code_lengths[CODE_LENGTH_ORDER[i]] = bits(3);
                    const code_length_code = huffman(code_lengths);
                    const lengths = new Uint8Array(hlit + hdist);
                    for(let i = 0; i < hlit + hdist;)
                    {
                        const symbol = decode(code_length_code);
                        if(symbol < 16) lengths[i++] = symbol;
                        else if(symbol === 16)
                        {
                            if(i === 0) throw new Error("inflate: a repeat of no code length");
                            const prev = lengths[i - 1];
                            for(let r = 3 + bits(2); r > 0; r--) lengths[i++] = prev;
                        }
                        else if(symbol === 17) i += 3 + bits(3);
                        else i += 11 + bits(7);
                        if(i > hlit + hdist) throw new Error("inflate: code lengths past their count");
                    }
                    literal = huffman(lengths.subarray(0, hlit));
                    distance = huffman(lengths.subarray(hlit));
                }
                else if(type !== 1)
                {
                    throw new Error("inflate: a reserved block type");
                }
                for(;;)
                {
                    const symbol = decode(literal);
                    if(symbol < 256)
                    {
                        if(out_len >= limit) throw LIMIT_REACHED;
                        ensure(1);
                        out[out_len++] = symbol;
                    }
                    else if(symbol === 256)
                    {
                        break;
                    }
                    else
                    {
                        const l = symbol - 257;
                        if(l >= 29) throw new Error("inflate: an invalid length code");
                        const length = LENGTH_BASE[l] + bits(LENGTH_EXTRA[l]);
                        const d = decode(distance);
                        if(d >= 30) throw new Error("inflate: an invalid distance code");
                        const dist = DIST_BASE[d] + bits(DIST_EXTRA[d]);
                        if(dist > out_len) throw new Error("inflate: a distance before the start of the data");
                        const n = Math.min(length, limit - out_len);
                        ensure(n);
                        for(let i = 0; i < n; i++, out_len++) out[out_len] = out[out_len - dist];
                        if(n < length) throw LIMIT_REACHED;
                    }
                }
            }
            if(last) break;
        }
    }
    catch(e)
    {
        if(e !== LIMIT_REACHED) throw e;
    }
    return { output: out.subarray(0, out_len), end: pos };
}

/**
 * The data of a gzip member
 * @param {!Uint8Array} input
 * @return {!Uint8Array}
 */
export function gunzip(input)
{
    if(input[0] !== 0x1F || input[1] !== 0x8B || input[2] !== 8) throw new Error("gunzip: not gzip (deflate) data");
    const flags = input[3];
    let pos = 10;
    if(flags & 4) pos += 2 + (input[pos] | input[pos + 1] << 8);
    if(flags & 8) while(input[pos++]) {}
    if(flags & 16) while(input[pos++]) {}
    if(flags & 2) pos += 2;
    // (ISIZE, the size modulo 2^32, closes the member)
    const size = (input[input.length - 4] | input[input.length - 3] << 8 | input[input.length - 2] << 16 | input[input.length - 1] << 24) >>> 0;
    return inflate(input, pos, size).output;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/src/virt/io.js                                                                           0000644 0000000 0000000 00000005706 00000000000 012414  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virt machine's device registers (docs/arm64-virt-android16-plan.md
// P1.7): the interface of src/io.js's memory-mapped ranges (register and
// unregister a range, handlers per access width), but with 64-bit addresses
// and exact ranges of any size. The ranges are regions of the ARM core's
// address space (src/rust/aarch64/bus.rs); an access reaches its handler with
// the offset in the range and its width (1, 2, 4 or 8 bytes). 64-bit
// addresses and values cross the boundary as [low, high] halves or BigInt.

/**
 * @typedef {{
 *     read: function(number, number): (number|bigint),
 *     write: function(number, number, (number|bigint)),
 *     name: (string|undefined),
 * }}
 * read(offset, width) returns the value (a BigInt or a number below 2^53);
 * write(offset, width, value) gets a BigInt for 8-byte writes, else a number
 */
export var MmioHandler;

/**
 * @constructor
 * @param {!Object} exports the ARM core's exports
 */
export function VirtDeviceSpace(exports)
{
    this.exports = exports;
    /** @type {!Array<{base: number, base_high: number, size: number, handler: MmioHandler}|null>} by owner */
    this.ranges = [null];
}

/**
 * Map [base, base + size) to `handler`
 * @param {number|Array<number>} base an address below 4 GiB or [low, high]
 * @param {number} size
 * @param {MmioHandler} handler
 * @return {number} the owner id
 */
VirtDeviceSpace.prototype.register_mmio = function(base, size, handler)
{
    const low = typeof base === "number" ? base >>> 0 : base[0];
    const high = typeof base === "number" ? Math.floor(base / 0x100000000) : base[1];
    const owner = this.ranges.length;
    if(!this.exports["a64_bus_map_mmio"](low, high, size >>> 0, Math.floor(size / 0x100000000), owner))
    {
        throw new Error("register_mmio: [0x" + (high * 0x100000000 + low).toString(16) + ", +0x" + size.toString(16) +
            ") overlaps RAM or another range, or lies beyond the 40-bit physical address space");
    }
    this.ranges.push({ base: low, base_high: high, size, handler });
    return owner;
};

/**
 * Unmap the range that `owner` names
 * @param {number} owner
 */
VirtDeviceSpace.prototype.unregister_mmio = function(owner)
{
    const range = this.ranges[owner];
    if(!range) throw new Error("unregister_mmio: no range " + owner);
    this.exports["a64_bus_unmap"](range.base, range.base_high);
    this.ranges[owner] = null;
};

/** (env.a64_mmio_read) */
VirtDeviceSpace.prototype.mmio_read = function(owner, offset, width)
{
    const range = this.ranges[owner];
    const value = range ? range.handler.read(Number(offset), width) : 0;
    return BigInt.asUintN(width * 8, typeof value === "bigint" ? value : BigInt(Math.trunc(value)));
};

/** (env.a64_mmio_write) */
VirtDeviceSpace.prototype.mmio_write = function(owner, offset, width, value)
{
    const range = this.ranges[owner];
    if(!range) return;
    value = BigInt.asUintN(64, value);
    range.handler.write(Number(offset), width, width === 8 ? value : Number(value));
};
                                                          source/v64/src/virt/loader.js                                                                       0000644 0000000 0000000 00000014216 00000000000 013247  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Loading Linux (or a bare-metal program) on the virt machine
// (docs/arm64-virt-android16-plan.md P4.6): an arm64 Image (the boot
// protocol of Documentation/arch/arm64/booting.rst), or an EFI zboot image
// holding one gzipped (Alpine's vmlinuz-virt), goes where the reference
// QEMU 9.2 puts it (hw/arm/boot.c): RAM + text_offset (0x80000 when
// image_size is 0, 2 MiB more below 4 KiB); the initrd at RAM + min(RAM / 2,
// 128 MiB), or above the kernel; the device tree after the initrd, 2 MiB
// aligned (some kernels map its 2 MiB block early). The core starts at the
// kernel's first byte with x0 the device tree's address. A kernel built for
// 16 or 64 KiB pages needs those granules (profiles v1.1 and v2, the
// default; v1 declares the 4 KiB granule only). A 32-bit kernel (cpu_type
// "arm32": a zImage, or a raw binary) goes where QEMU puts one, RAM +
// 0x10000, the device tree after the initrd 4 KiB aligned; the core starts
// in SVC mode with r0 0, r1 ~0 and r2 the device tree.

import { VIRT_RAM_BASE } from "./platform.js";
import { gunzip } from "./inflate.js";
import { flatten, virt_tree } from "./dtb.js";
import { ranchu_dtb } from "./ranchu.js";

const IMAGE_MAGIC = 0x644D5241; // "ARM\x64" at 56
const ZBOOT_MAGIC = 0x676D697A; // "zimg" at 4
const DEFAULT_TEXT_OFFSET = 0x80000;
/** a 32-bit kernel's place (QEMU's hw/arm/boot.c KERNEL_LOAD_ADDR) */
const ARM32_KERNEL_OFFSET = 0x10000;
const MiB = 1024 * 1024;

/**
 * The Image inside a kernel file: the file itself, or an EFI zboot image's gzipped payload
 * @param {!Uint8Array} kernel
 * @return {!Uint8Array}
 */
export function unpack_kernel(kernel)
{
    const view = new DataView(kernel.buffer, kernel.byteOffset, kernel.byteLength);
    if(kernel.length >= 64 && kernel[0] === 0x4D && kernel[1] === 0x5A && view.getUint32(4, true) === ZBOOT_MAGIC)
    {
        const offset = view.getUint32(8, true), size = view.getUint32(12, true);
        const type = new TextDecoder().decode(kernel.subarray(0x18, 0x38)).replace(/\0.*$/s, "");
        if(type !== "gzip") throw new Error("kernel: EFI zboot with " + type + " compression; only gzip is supported");
        return gunzip(kernel.subarray(offset, offset + size));
    }
    return kernel;
}

/**
 * Where an arm64 Image goes in RAM (its offset from RAM's base), and how far it reaches
 * @param {!Uint8Array} image
 * @return {{offset: number, size: number}}
 */
export function image_placement(image, granules = 1)
{
    const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
    if(image.length < 64 || view.getUint32(56, true) !== IMAGE_MAGIC)
    {
        // (a raw binary: where QEMU loads one that is not an Image)
        return { offset: DEFAULT_TEXT_OFFSET, size: image.length };
    }
    // (flags bits 2:1, the kernel's page size: unspecified, 4, 16 or 64 KiB:
    // the profile's granules, `granules` bit 1 16 KiB, bit 2 64 KiB; v1 has the 4 KiB one only)
    const page_size = view.getUint32(24, true) >> 1 & 3;
    if(page_size > 1 && !(granules & (page_size === 2 ? 2 : 4)))
    {
        throw new Error("kernel: built for " + (page_size === 2 ? 16 : 64) + " KiB pages; the CPU profile does not have that granule " +
            "(cpu_profile: \"generic-arm64\" and \"generic-arm64-v1.1\" have 16 and 64 KiB)");
    }
    const text_offset = view.getUint32(8, true) + view.getUint32(12, true) * 0x100000000;
    const image_size = view.getUint32(16, true) + view.getUint32(20, true) * 0x100000000;
    let offset = image_size ? text_offset : DEFAULT_TEXT_OFFSET;
    if(offset < 4096) offset += 2 * MiB;
    return { offset, size: Math.max(image.length, image_size) };
}

/**
 * Load a kernel, an initrd and the device tree into the CPU's RAM
 * @param {Object} cpu the arm64 CPU (src/arm/cpu.js)
 * @param {!Object} boot kernel (an ArrayBuffer), initrd and dtb (ArrayBuffers or undefined), cmdline, cores
 * @return {{entry: number, x0: number}}
 */
export function load_linux(cpu, boot)
{
    const ram_size = cpu.memory_size[0];
    const ram_end = VIRT_RAM_BASE + ram_size;
    const arm32 = cpu.cpu_type === "arm32";
    const image = arm32 ? new Uint8Array(boot.kernel) : unpack_kernel(new Uint8Array(boot.kernel));
    const { offset, size } = arm32 ? { offset: ARM32_KERNEL_OFFSET, size: image.length } :
        image_placement(image, cpu.wm.exports["a64_granules"] ? cpu.wm.exports["a64_granules"]() : 1);
    if(offset + image.length > ram_size)
    {
        throw new Error("kernel: " + image.length + " bytes at RAM + 0x" + offset.toString(16) + " do not fit in RAM");
    }
    const entry = VIRT_RAM_BASE + offset;
    cpu.write_blob_physical(image, entry);

    const page_align = a => Math.ceil(a / 4096) * 4096;
    const initrd_start = page_align(Math.max(VIRT_RAM_BASE + Math.min(ram_size / 2, 128 * MiB), entry + size));
    let initrd;
    if(boot.initrd)
    {
        const bytes = new Uint8Array(boot.initrd);
        if(initrd_start + bytes.length > ram_end) throw new Error("initrd: " + bytes.length + " bytes do not fit in RAM after the kernel");
        cpu.write_blob_physical(bytes, initrd_start);
        initrd = { start: initrd_start, end: initrd_start + bytes.length };
    }
    const dtb_align = arm32 ? 4096 : 2 * MiB;
    const dtb_start = Math.ceil((initrd_start + (initrd ? initrd.end - initrd.start : 0)) / dtb_align) * dtb_align;
    let dtb;
    if(boot.dtb)
    {
        dtb = new Uint8Array(boot.dtb);
    }
    else
    {
        const rng_seed = new Uint8Array(32);
        globalThis.crypto?.getRandomValues?.(rng_seed);
        dtb = cpu.machine_type === "ranchu" ?
            ranchu_dtb({ cores: boot.cores, memory_size: ram_size, bootargs: boot.cmdline || undefined, initrd, arm32,
                framebuffer: cpu.ranchu_framebuffer || undefined }) :
            flatten(virt_tree({
                cores: boot.cores, memory_size: ram_size, bootargs: boot.cmdline || undefined, initrd, rng_seed, arm32,
                extended: cpu.extended_pages ? { base: cpu.extended_base, size: cpu.extended_pages * 4096 } : undefined,
            }));
    }
    if(dtb_start + dtb.length > ram_end) throw new Error("dtb: not enough RAM after the kernel and initrd");
    cpu.write_blob_physical(dtb, dtb_start);
    return { entry, x0: dtb_start };
}
                                                                                                                                                                                                                                                                                                                                                                                  source/v64/src/virt/pl011.js                                                                        0000644 0000000 0000000 00000015432 00000000000 012637  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virt machine's PL011 UART at 0x0900_0000 (docs/arm64-virt-android16-plan.md
// P4.5), as the reference's (QEMU 9.2 hw/char/pl011.c): a receive FIFO of
// 16 bytes (1 without LCR_H.FEN) fed by serial0-input, the receive
// interrupt as soon as a byte waits (the reference's trigger level 1), the
// transmit interrupt after every byte written (transmission is immediate,
// out as serial0-output-byte), loopback, the registers as written, and the
// PrimeCell identification the AMBA bus binds the driver by. The combined
// interrupt is SPI 1 (INTID 33), level-sensitive. Bytes that arrive while
// the FIFO is full wait in a backlog, as the reference's character device
// holds them back.

import { VIRT_UART } from "./platform.js";

const UARTDR = 0x000;
const UARTRSR = 0x004;
const UARTFR = 0x018;
const UARTILPR = 0x020;
const UARTIBRD = 0x024;
const UARTFBRD = 0x028;
const UARTLCR_H = 0x02C;
const UARTCR = 0x030;
const UARTIFLS = 0x034;
const UARTIMSC = 0x038;
const UARTRIS = 0x03C;
const UARTMIS = 0x040;
const UARTICR = 0x044;
const UARTDMACR = 0x048;

const FR_RXFE = 1 << 4;
const FR_TXFF = 1 << 5;
const FR_RXFF = 1 << 6;
const FR_TXFE = 1 << 7;

const INT_TX = 1 << 5;
const INT_RX = 1 << 4;

const LCR_FEN = 1 << 4;
const CR_LBE = 1 << 7;

const FIFO_DEPTH = 16;
export const PL011_INTID = 33;

/** PeriphID0-3 (PL011 r1p5) and PCellID0-3 at 0xFE0-0xFFC */
const ID = [0x11, 0x10, 0x14, 0x00, 0x0D, 0xF0, 0x05, 0xB1];

/**
 * @constructor
 * @param {Object} cpu the arm64 CPU (src/arm/cpu.js)
 * @param {Object} bus
 */
export function PL011(cpu, bus)
{
    this.name = "pl011";
    this.cpu = cpu;
    this.bus = bus;
    /** @type {!Array<number>} what arrived while the FIFO was full */
    this.backlog = [];
    this.reset();
    this.owner = cpu.io.register_mmio(VIRT_UART, 0x1000, {
        read: (offset, width) => this.read(offset, width),
        write: (offset, width, value) => this.write(offset, width, Number(value)),
        name: this.name,
    });
    bus.register("serial0-input", byte => this.receive(byte & 0xFF), this);
}

PL011.prototype.reset = function()
{
    this.lcr = 0;
    this.rsr = 0;
    this.dmacr = 0;
    this.int_enabled = 0;
    this.int_level = 0;
    this.ilpr = 0;
    this.ibrd = 0;
    this.fbrd = 0;
    this.read_trigger = 1;
    this.ifl = 0x12;
    this.cr = 0x300;
    this.flags = 0;
    this.read_fifo = new Array(FIFO_DEPTH).fill(0);
    this.reset_fifos();
    this.update();
};

PL011.prototype.reset_fifos = function()
{
    this.read_count = 0;
    this.read_pos = 0;
    this.flags = this.flags & ~(FR_RXFF | FR_TXFF) | FR_RXFE | FR_TXFE;
};

PL011.prototype.depth = function()
{
    return this.lcr & LCR_FEN ? FIFO_DEPTH : 1;
};

/** The combined interrupt line to the GIC */
PL011.prototype.update = function()
{
    this.cpu.set_irq(PL011_INTID, (this.int_level & this.int_enabled) !== 0);
};

PL011.prototype.fifo_put = function(value)
{
    const depth = this.depth();
    this.read_fifo[(this.read_pos + this.read_count) & (depth - 1)] = value;
    this.read_count++;
    this.flags &= ~FR_RXFE;
    if(this.read_count === depth) this.flags |= FR_RXFF;
    if(this.read_count === this.read_trigger)
    {
        this.int_level |= INT_RX;
        this.update();
    }
};

/** A byte from serial0-input (ignored in loopback; held back while the FIFO is full) */
PL011.prototype.receive = function(byte)
{
    if(this.cr & CR_LBE) return;
    if(this.read_count < this.depth() && !this.backlog.length) this.fifo_put(byte);
    else this.backlog.push(byte);
};

PL011.prototype.read_data = function()
{
    this.flags &= ~FR_RXFF;
    const c = this.read_fifo[this.read_pos];
    if(this.read_count > 0)
    {
        this.read_count--;
        this.read_pos = (this.read_pos + 1) & (this.depth() - 1);
    }
    if(this.read_count === 0) this.flags |= FR_RXFE;
    if(this.read_count === this.read_trigger - 1) this.int_level &= ~INT_RX;
    this.rsr = c >> 8;
    this.update();
    this.refill();
    return c;
};

/** The backlog into the FIFO, as far as it has room (as it drains, and after the FIFOs are reset) */
PL011.prototype.refill = function()
{
    while(this.backlog.length && this.read_count < this.depth() && !(this.cr & CR_LBE)) this.fifo_put(this.backlog.shift());
};

PL011.prototype.read = function(offset, width)
{
    switch(offset)
    {
        case UARTDR: return this.read_data();
        case UARTRSR: return this.rsr;
        case UARTFR: return this.flags;
        case UARTILPR: return this.ilpr;
        case UARTIBRD: return this.ibrd;
        case UARTFBRD: return this.fbrd;
        case UARTLCR_H: return this.lcr;
        case UARTCR: return this.cr;
        case UARTIFLS: return this.ifl;
        case UARTIMSC: return this.int_enabled;
        case UARTRIS: return this.int_level;
        case UARTMIS: return this.int_level & this.int_enabled;
        case UARTDMACR: return this.dmacr;
    }
    if(offset >= 0xFE0 && offset < 0x1000) return ID[offset - 0xFE0 >> 2];
    return 0;
};

PL011.prototype.write = function(offset, width, value)
{
    switch(offset)
    {
        case UARTDR:
            this.bus.send("serial0-output-byte", value & 0xFF);
            if(this.cr & CR_LBE) this.fifo_put(value & 0xFF);
            this.int_level |= INT_TX;
            this.update();
            break;
        case UARTRSR: this.rsr = 0; break;
        case UARTILPR: this.ilpr = value; break;
        case UARTIBRD: this.ibrd = value & 0xFFFF; break;
        case UARTFBRD: this.fbrd = value & 0x3F; break;
        case UARTLCR_H:
            // (enabling or disabling the FIFOs empties them; what the host
            // held back while the FIFO was full comes in then: a driver that
            // set FEN would otherwise never see another byte)
            if((this.lcr ^ value) & LCR_FEN) this.reset_fifos();
            this.lcr = value;
            this.read_trigger = 1;
            this.refill();
            break;
        case UARTCR: this.cr = value; break;
        case UARTIFLS: this.ifl = value; this.read_trigger = 1; break;
        case UARTIMSC: this.int_enabled = value; this.update(); break;
        case UARTICR: this.int_level &= ~value; this.update(); break;
        case UARTDMACR: this.dmacr = value; break;
    }
};

PL011.prototype.get_state = function()
{
    return [this.lcr, this.rsr, this.dmacr, this.int_enabled, this.int_level, this.ilpr, this.ibrd, this.fbrd, this.read_trigger,
        this.ifl, this.cr, this.flags, this.read_fifo.slice(), this.read_count, this.read_pos, this.backlog.slice()];
};

PL011.prototype.set_state = function(state)
{
    [this.lcr, this.rsr, this.dmacr, this.int_enabled, this.int_level, this.ilpr, this.ibrd, this.fbrd, this.read_trigger,
        this.ifl, this.cr, this.flags] = state;
    this.read_fifo = state[12].slice();
    this.read_count = state[13];
    this.read_pos = state[14];
    this.backlog = state[15].slice();
    this.update();
};
                                                                                                                                                                                                                                      source/v64/src/virt/pl031.js                                                                        0000644 0000000 0000000 00000007310 00000000000 012635  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virt machine's PL031 real-time clock at 0x0901_0000
// (docs/arm64-virt-android16-plan.md P4.5), as the reference's (QEMU 9.2
// hw/rtc/pl031.c): seconds since the epoch from the machine clock's wall
// time (MachineClock.wall_time), the load register setting them, always
// enabled, an alarm (the match register) whose interrupt is SPI 2 (INTID
// 34, level-sensitive), and the PrimeCell identification.

import { VIRT_RTC } from "./platform.js";

const RTC_DR = 0x00;
const RTC_MR = 0x04;
const RTC_LR = 0x08;
const RTC_CR = 0x0C;
const RTC_IMSC = 0x10;
const RTC_RIS = 0x14;
const RTC_MIS = 0x18;
const RTC_ICR = 0x1C;

export const PL031_INTID = 34;

/** PeriphID0-3 (PL031) and PCellID0-3 at 0xFE0-0xFFC */
const ID = [0x31, 0x10, 0x14, 0x00, 0x0D, 0xF0, 0x05, 0xB1];

/**
 * @constructor
 * @param {Object} cpu the arm64 CPU (src/arm/cpu.js)
 * @param {number=} base the virt machine's, or the ranchu machine's
 * @param {number=} intid
 */
export function PL031(cpu, base = VIRT_RTC, intid = PL031_INTID)
{
    this.name = "pl031";
    this.cpu = cpu;
    this.intid = intid;
    this.reset();
    this.owner = cpu.io.register_mmio(base, 0x1000, {
        read: (offset, width) => this.read(offset),
        write: (offset, width, value) => this.write(offset, Number(value)),
        name: this.name,
    });
}

PL031.prototype.reset = function()
{
    // (seconds to add to the machine clock's wall time; the load register moves them)
    this.tick_offset = 0;
    this.mr = 0;
    this.lr = 0;
    this.im = 0;
    this.is = 0;
    /** the counter's value the alarm waits for, or -1 */
    this.alarm = -1;
    this.update();
};

/** The counter: seconds of wall time, as an unsigned 32-bit value */
PL031.prototype.count = function()
{
    return (Math.floor(this.cpu.clock.wall_time() / 1000) + this.tick_offset) >>> 0;
};

PL031.prototype.update = function()
{
    this.cpu.set_irq(this.intid, (this.is & this.im) !== 0);
};

PL031.prototype.set_alarm = function()
{
    if(this.mr === this.count())
    {
        this.alarm = -1;
        this.is = 1;
        this.update();
    }
    else
    {
        this.alarm = this.mr;
    }
};

/**
 * (the machine's timers) the alarm; milliseconds until it is next due
 * @return {number}
 */
PL031.prototype.timer = function()
{
    if(this.alarm < 0) return Infinity;
    const now = this.count();
    if(now === this.alarm || ((this.alarm - now) >>> 0) > 0x80000000)
    {
        this.alarm = -1;
        this.is = 1;
        this.update();
        return Infinity;
    }
    return 1000 * ((this.alarm - now) >>> 0);
};

PL031.prototype.read = function(offset)
{
    switch(offset)
    {
        case RTC_DR: return this.count();
        case RTC_MR: return this.mr;
        case RTC_IMSC: return this.im;
        case RTC_RIS: return this.is;
        case RTC_LR: return this.lr;
        case RTC_CR: return 1;
        case RTC_MIS: return this.is & this.im;
    }
    if(offset >= 0xFE0 && offset < 0x1000) return ID[offset - 0xFE0 >> 2];
    return 0;
};

PL031.prototype.write = function(offset, value)
{
    switch(offset)
    {
        case RTC_LR:
            this.lr = value >>> 0;
            this.tick_offset += (value >>> 0) - this.count();
            this.set_alarm();
            break;
        case RTC_MR:
            this.mr = value >>> 0;
            this.set_alarm();
            break;
        case RTC_IMSC: this.im = value & 1; this.update(); break;
        case RTC_ICR: this.is &= ~value; this.update(); break;
    }
};

PL031.prototype.get_state = function()
{
    return [this.tick_offset, this.mr, this.lr, this.im, this.is, this.alarm];
};

PL031.prototype.set_state = function(state)
{
    [this.tick_offset, this.mr, this.lr, this.im, this.is, this.alarm] = state;
    this.update();
};
                                                                                                                                                                                                                                                                                                                        source/v64/src/virt/platform.js                                                                     0000644 0000000 0000000 00000006760 00000000000 013632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virt machine of cpu_type "arm64" (docs/virt.md,
// docs/arm64-virt-android16-plan.md): its physical address map, which copies
// QEMU's virt-9.2 (the fixed reference), and the identity snapshots record.

/** Version of the virt machine's device layout, recorded in snapshots (2: the PCIe host, P5.6) */
export const VIRT_LAYOUT_VERSION = 2;

/** The CPU profile (tests/platform/a64-profile.json) */
/** The CPU profiles' base name: v1; v1.1 adds ".1"; v2 is the default (src/arm/cpu.js) */
export const A64_PROFILE = "v86-aarch64-v1";
/**
 * The arm64 CPU's profiles (docs/arm64-virt-android16-plan.md, "CPU profile")
 * by their CPU model (cpu_profile, src/machine_options.js): [name (the
 * snapshots record it), granules (bit 0 4 KiB, 1 16 KiB, 2 64 KiB),
 * optional features (bit 0 FEAT_PAN, bit 1 AArch32 at EL0)]
 * @type {!Object<string, !Array>}
 */
export const A64_PROFILES = {
    "generic-arm64-v1": [A64_PROFILE, 1, 0],
    "generic-arm64-v1.1": [A64_PROFILE + ".1", 7, 0],
    "generic-arm64": ["v86-aarch64-v2", 7, 1],
    // (v2 and 32-bit processes: docs/aarch32-plan.md)
    "generic-arm64-compat32": ["v86-aarch64-v3", 7, 3],
};

/**
 * cpu_type "arm32"'s profiles by their CPU model (docs/aarch32-plan.md part
 * 2): AArch32 throughout (feature bit 2), with AArch32's instructions (bit
 * 1); name, granules (none of AArch64's: the 4 KiB one), features
 * @type {!Object<string, !Array>}
 */
export const ARM32_PROFILES = {
    "cortex-a15": ["v86-arm32-v1", 1, 6],
};

/** Must match MAX_CORES in src/rust/aarch64/isa_hooks.rs */
export const VIRT_MAX_CORES = 8;

/** Guest RAM's base (src/rust/aarch64/bus.rs RAM_BASE) */
export const VIRT_RAM_BASE = 0x40000000;
/** extended RAM (P8.5): from 4 GiB, to where the reference's RAM ends (256 GiB, before the high ECAM) */
export const VIRT_EXTENDED_RAM_BASE = 0x100000000;
export const VIRT_EXTENDED_RAM_END = 0x4000000000;

// QEMU virt-9.2 with highmem-ecam/-mmio/-redists on (docs/virt.md)
export const VIRT_GIC_DIST = 0x08000000;
export const VIRT_GIC_DIST_SIZE = 0x10000;
export const VIRT_GIC_REDIST = 0x080A0000;
export const VIRT_GIC_REDIST_STRIDE = 0x20000;
export const VIRT_UART = 0x09000000;
export const VIRT_RTC = 0x09010000;
export const VIRT_MMIO = 0x0A000000;
export const VIRT_MMIO_SIZE = 0x200;
export const VIRT_MMIO_COUNT = 32;
export const VIRT_PCIE_MMIO = 0x10000000;
export const VIRT_PCIE_MMIO_SIZE = 0x2EFF0000;
export const VIRT_PCIE_PIO = 0x3EFF0000;
export const VIRT_PCIE_PIO_SIZE = 0x10000;
/** above 4 GiB: as [low, high] 32-bit halves */
export const VIRT_PCIE_ECAM_HIGH = [0x10000000, 0x40];
/** 256 buses */
export const VIRT_PCIE_ECAM_SIZE = 0x10000000;
export const VIRT_PCIE_MMIO_HIGH = [0x00000000, 0x80];
export const VIRT_PCIE_MMIO_HIGH_SIZE = 0x8000000000;

/**
 * The machine's settings, validated: cores and RAM
 * @param {Object} settings
 * @return {{cores: number, memory_size: number}}
 */
export function virt_machine(settings)
{
    const cores = settings.cpu_cores === undefined ? 1 : settings.cpu_cores;
    if(!Number.isInteger(cores) || cores < 1 || cores > VIRT_MAX_CORES)
    {
        throw new Error("cpu_cores must be an integer from 1 to " + VIRT_MAX_CORES + ", got " + cores);
    }
    const memory_size = settings.memory_size === undefined ? 512 * 1024 * 1024 : settings.memory_size;
    if(!Number.isInteger(memory_size) || memory_size < 1024 * 1024 || memory_size % 4096)
    {
        throw new Error("memory_size must be a multiple of 4096 of at least 1 MiB, got " + memory_size);
    }
    return { cores, memory_size };
}
                source/v64/src/virt/ranchu.js                                                                       0000644 0000000 0000000 00000021532 00000000000 013260  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The ranchu machine (machine_type "ranchu", docs/aarch32-plan.md R6): the
// Android emulator's board, which the SDK's system images (kernel-ranchu,
// ramdisk.img, system.img, userdata.img) are built for. The virt machine's
// RAM, PL011, generic timer and virtio-mmio slots; a GICv2 with cpu_type
// "arm32" (Linux 3.10's ranchu kernel has no GICv3 driver), the virt
// machine's GICv3 with "arm64"; the emulator's goldfish devices
// (src/virt/goldfish.js) where its board has them; a PL031 (the kernels'
// RTC); no PCIe. The kernels find all of it in the device tree, whose
// compatible strings are the emulator's ("generic," for Linux 3.10,
// "google," for newer kernels).

import { node, flatten } from "./dtb.js";
import { VIRT_GIC_DIST, VIRT_GIC_DIST_SIZE, VIRT_GIC_REDIST, VIRT_MMIO, VIRT_MMIO_COUNT, VIRT_MMIO_SIZE, VIRT_RAM_BASE, VIRT_UART } from "./platform.js";

/** Version of the ranchu machine's device layout, recorded in snapshots */
export const RANCHU_LAYOUT_VERSION = 1;

export const RANCHU_GIC_CPU = 0x08010000;
export const RANCHU_GIC_CPU_SIZE = 0x10000;
export const RANCHU_GOLDFISH_FB = 0x09010000;
export const RANCHU_GOLDFISH_BATTERY = 0x09020000;
export const RANCHU_GOLDFISH_AUDIO = 0x09030000;
export const RANCHU_GOLDFISH_EVENTS = 0x09040000;
export const RANCHU_RTC = 0x09050000;
export const RANCHU_GOLDFISH_PIPE = 0x0A010000;
/** The devices' SPIs (the virtio-mmio slots': 16 + slot, as the virt machine's) */
export const RANCHU_SPI = { uart: 1, fb: 2, battery: 3, audio: 4, events: 5, rtc: 6, pipe: 7 };
/** The low redistributor region (the virt machine's) */
const GIC_REDIST_REGION_SIZE = 0xF60000;
const APB_PCLK_HZ = 24000000;

/** The display the framebuffer has unless the machine's settings say otherwise: a phone's, hdpi */
export const RANCHU_DISPLAY = { width: 480, height: 800, dpi: 240 };

/**
 * (arm32) the simple-framebuffer's place: the top of RAM, in 2 MiB
 * @param {number} memory_size
 * @param {{width: number, height: number}} display
 * @return {{base: number, size: number, width: number, height: number}}
 */
export function ranchu_framebuffer(memory_size, display)
{
    const size = Math.ceil(display.width * display.height * 2 / 0x200000) * 0x200000;
    return { base: VIRT_RAM_BASE + memory_size - size, size, width: display.width, height: display.height };
}

const u64 = value => [Math.floor(value / 0x100000000), value >>> 0];

/**
 * The kernel command line the emulator gives an SDK image (its
 * android/kernel/kernel_utils's): the hardware's name, the console, host
 * GLES or not (qemu.gles=1: the GL libraries are the emulator's, over the
 * pipe's "opengles", ranchu_gpu "host"; qemu.gles=0: the guest renders),
 * no RIL (no android.qemud), no Wi-Fi namespace (eth0 with DHCP), no boot
 * animation when asked
 * @param {{arm32: boolean, gles: (boolean|undefined), bootanim: (boolean|undefined), extra: (string|undefined)}} m
 * @return {string}
 */
export function ranchu_cmdline(m)
{
    // (the kernel's console the PL011; init's console service then opens
    // /dev/console, which the image's SELinux policy lets its shell use: it
    // labels no ttyAMA device)
    return ["qemu=1", "androidboot.hardware=ranchu", "console=ttyAMA0",
        "android.checkjni=1", "qemu.gles=" + (m.gles ? 1 : 0), "qemu.encrypt=0", "qemu.wifi=0", "loop.max_part=7",
        ...(m.bootanim === false ? ["android.bootanim=0"] : []), ...(m.extra ? [m.extra] : [])].join(" ");
}

/**
 * The ranchu machine's tree
 * (`framebuffer`: a simple-framebuffer at the top of RAM, kept out of the
 * memory node, instead of the goldfish framebuffer: arm32's)
 * @param {{cores: number, memory_size: number, bootargs: (string|undefined), arm32: boolean,
 *          initrd: ({start: number, end: number}|undefined),
 *          framebuffer: ({base: number, size: number, width: number, height: number}|undefined)}} m
 * @return {!Uint8Array} the flattened tree
 */
export function ranchu_dtb(m)
{
    const clock = 0x8000;
    const gic = 0x8000 + m.cores + 1;
    const cpu_phandle = i => 0x8000 + m.cores - i;
    const spi = (n, type) => [0, n, type];
    // (a GICv2's PPIs name the cores they go to: bits 15:8)
    const ppi_flags = m.arm32 ? ((1 << m.cores) - 1) << 8 | 4 : 4;
    const smc = m.arm32 ? 0x84000000 : 0xC4000000;
    const children = [];
    children.push(node("psci", [
        ["migrate", [smc | 5]], ["cpu_on", [smc | 3]], ["cpu_off", [0x84000002]], ["cpu_suspend", [smc | 1]],
        ["method", "hvc"], ["compatible", ["arm,psci-0.2", "arm,psci"]],
    ]));
    const fb = m.framebuffer;
    children.push(node("memory@" + VIRT_RAM_BASE.toString(16), [
        ["reg", [...u64(VIRT_RAM_BASE), ...u64(m.memory_size - (fb ? fb.size : 0))]], ["device_type", "memory"],
    ]));
    if(fb)
    {
        children.push(node("framebuffer@" + fb.base.toString(16), [
            ["format", "r5g6b5"], ["stride", [2 * fb.width]], ["height", [fb.height]], ["width", [fb.width]],
            ["reg", [...u64(fb.base), ...u64(fb.size)]], ["compatible", "simple-framebuffer"],
        ]));
    }
    // (from the last slot down, where the machine puts its first device: the
    // kernel probes them in this order, the first disk becoming vda as fstab.ranchu wants)
    for(let n = VIRT_MMIO_COUNT - 1; n >= 0; n--)
    {
        const base = VIRT_MMIO + n * VIRT_MMIO_SIZE;
        children.push(node("virtio_mmio@" + base.toString(16), [
            ["interrupts", spi(16 + n, 1)], ["reg", [...u64(base), ...u64(VIRT_MMIO_SIZE)]], ["compatible", "virtio,mmio"],
        ]));
    }
    const goldfish = (name, base, size, irq, kind) => node(name + "@" + base.toString(16), [
        ["interrupts", spi(irq, 4)], ["reg", [...u64(base), ...u64(size)]], ["compatible", ["google," + kind, "generic," + kind]],
    ]);
    children.push(goldfish("goldfish_pipe", RANCHU_GOLDFISH_PIPE, 0x2000, RANCHU_SPI.pipe, "android-pipe"));
    children.push(goldfish("goldfish_events", RANCHU_GOLDFISH_EVENTS, 0x1000, RANCHU_SPI.events, "goldfish-events-keypad"));
    children.push(goldfish("goldfish_audio", RANCHU_GOLDFISH_AUDIO, 0x1000, RANCHU_SPI.audio, "goldfish-audio"));
    children.push(goldfish("goldfish_battery", RANCHU_GOLDFISH_BATTERY, 0x1000, RANCHU_SPI.battery, "goldfish-battery"));
    if(!fb) children.push(goldfish("goldfish_fb", RANCHU_GOLDFISH_FB, 0x1000, RANCHU_SPI.fb, "goldfish-fb"));
    children.push(node("pl031@" + RANCHU_RTC.toString(16), [
        ["clock-names", "apb_pclk"], ["clocks", [clock]], ["interrupts", spi(RANCHU_SPI.rtc, 4)], ["reg", [...u64(RANCHU_RTC), ...u64(0x1000)]],
        ["compatible", ["arm,pl031", "arm,primecell"]],
    ]));
    children.push(node("pl011@" + VIRT_UART.toString(16), [
        ["clock-names", ["uartclk", "apb_pclk"]], ["clocks", [clock, clock]], ["interrupts", spi(RANCHU_SPI.uart, 4)],
        ["reg", [...u64(VIRT_UART), ...u64(0x1000)]], ["compatible", ["arm,pl011", "arm,primecell"]],
    ]));
    children.push(node("intc@" + VIRT_GIC_DIST.toString(16), m.arm32 ? [
        ["phandle", [gic]],
        ["reg", [...u64(VIRT_GIC_DIST), ...u64(VIRT_GIC_DIST_SIZE), ...u64(RANCHU_GIC_CPU), ...u64(RANCHU_GIC_CPU_SIZE)]],
        ["compatible", "arm,cortex-a15-gic"], ["interrupt-controller", true], ["#interrupt-cells", [3]],
    ] : [
        ["phandle", [gic]],
        ["reg", [...u64(VIRT_GIC_DIST), ...u64(VIRT_GIC_DIST_SIZE), ...u64(VIRT_GIC_REDIST), ...u64(GIC_REDIST_REGION_SIZE)]],
        ["#redistributor-regions", [1]], ["compatible", "arm,gic-v3"], ["interrupt-controller", true], ["#interrupt-cells", [3]],
    ]));
    const cores = [];
    for(let i = 0; i < m.cores; i++)
    {
        cores.push(node("cpu@" + i, [
            ["phandle", [cpu_phandle(i)]], ["reg", [i]], ...(m.cores > 1 ? [["enable-method", "psci"]] : []),
            ["compatible", m.arm32 ? "arm,cortex-a15" : "arm,armv8"], ["device_type", "cpu"],
        ]));
    }
    children.push(node("cpus", [["#size-cells", [0]], ["#address-cells", [1]]], cores));
    children.push(node("timer", [
        ["interrupts", [1, 13, ppi_flags, 1, 14, ppi_flags, 1, 11, ppi_flags, 1, 10, ppi_flags]], ["always-on", true],
        ["compatible", m.arm32 ? ["arm,armv7-timer"] : ["arm,armv8-timer", "arm,armv7-timer"]],
    ]));
    children.push(node("apb-pclk", [
        ["phandle", [clock]], ["clock-output-names", "clk24mhz"], ["clock-frequency", [APB_PCLK_HZ]], ["#clock-cells", [0]],
        ["compatible", "fixed-clock"],
    ]));
    children.push(node("aliases", [["serial0", "/pl011@" + VIRT_UART.toString(16)]]));
    const chosen = [["stdout-path", "/pl011@" + VIRT_UART.toString(16)]];
    if(m.bootargs !== undefined) chosen.push(["bootargs", m.bootargs]);
    if(m.initrd) chosen.push(["linux,initrd-end", u64(m.initrd.end)], ["linux,initrd-start", u64(m.initrd.start)]);
    children.push(node("chosen", chosen));
    return flatten(node("", [
        ["interrupt-parent", [gic]], ["model", "ranchu"], ["#size-cells", [2]], ["#address-cells", [2]],
        ["compatible", ["ranchu", "linux,dummy-virt"]],
    ], children));
}
                                                                                                                                                                      source/v64/src/virtio.js                                                                            0000644 0000000 0000000 00000204355 00000000000 012336  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { LOG_VIRTIO, MMAP_BLOCK_SIZE } from "./const.js";
import { h, int_log2 } from "./lib.js";
import { dbg_assert, dbg_log } from "./log.js";

// For Types Only
import { CPU } from "./cpu.js";
import { PCI } from "./pci.js";

// http://docs.oasis-open.org/virtio/virtio/v1.0/virtio-v1.0.html

const VIRTIO_PCI_VENDOR_ID = 0x1AF4;
// Identifies vendor-specific PCI capability.
const VIRTIO_PCI_CAP_VENDOR = 0x09;
// Length (bytes) of VIRTIO_PCI_CAP linked list entry.
const VIRTIO_PCI_CAP_LENGTH = 16;

// Capability types.

const VIRTIO_PCI_CAP_COMMON_CFG = 1;
const VIRTIO_PCI_CAP_NOTIFY_CFG = 2;
const VIRTIO_PCI_CAP_ISR_CFG = 3;
const VIRTIO_PCI_CAP_DEVICE_CFG = 4;
const VIRTIO_PCI_CAP_PCI_CFG = 5;
const VIRTIO_PCI_CAP_SHARED_MEMORY_CFG = 8;

// On the virt machine's generic PCIe host (docs/arm64-virt-android16-plan.md
// P5.7) the capabilities are where QEMU v9.2.0's virtio-pci puts them: in
// BAR 4, a 64-bit prefetchable memory BAR, the common, ISR, device and
// notification configuration at 4 KiB steps; and the functions have QEMU's
// class codes and subsystem
const GENERIC_CAPABILITY_BAR = 4;
const GENERIC_CAPABILITY_WINDOW = 0x1000;
const GENERIC_CAPABILITY_OFFSETS = {
    [VIRTIO_PCI_CAP_COMMON_CFG]: 0,
    [VIRTIO_PCI_CAP_ISR_CFG]: 0x1000,
    [VIRTIO_PCI_CAP_DEVICE_CFG]: 0x2000,
    [VIRTIO_PCI_CAP_NOTIFY_CFG]: 0x3000,
};
/** by PCI device ID: network, mass storage (SCSI), communication (other), other, input (other), display (other) */
const GENERIC_CLASS_CODES = { 0x1041: 0x020000, 0x1042: 0x010000, 0x1043: 0x078000, 0x1044: 0x00FF00, 0x1052: 0x098000, 0x1050: 0x038000 };
const GENERIC_SUBSYSTEM_ID = 0x1100;

// Status bits (device_status values).

const VIRTIO_STATUS_ACKNOWLEDGE = 1;
const VIRTIO_STATUS_DRIVER = 2;
export const VIRTIO_STATUS_DRIVER_OK = 4;
const VIRTIO_STATUS_FEATURES_OK = 8;
export const VIRTIO_STATUS_DEVICE_NEEDS_RESET = 64;
export const VIRTIO_STATUS_FAILED = 128;

// ISR bits (isr_status values).

const VIRTIO_ISR_QUEUE = 1;
const VIRTIO_ISR_DEVICE_CFG = 2;

// Feature bits (bit positions).

export const VIRTIO_F_RING_INDIRECT_DESC = 28;
export const VIRTIO_F_RING_EVENT_IDX = 29;
export const VIRTIO_F_VERSION_1 = 32;

// Queue struct sizes.

// Size (bytes) of the virtq_desc struct per queue size.
const VIRTQ_DESC_ENTRYSIZE = 16;
// Size (bytes) of the virtq_avail struct ignoring ring entries.
const VIRTQ_AVAIL_BASESIZE = 6;
// Size (bytes) of the virtq_avail struct per queue size.
const VIRTQ_AVAIL_ENTRYSIZE = 2;
// Size (bytes) of the virtq_used struct ignoring ring entries.
const VIRTQ_USED_BASESIZE = 6;
// Size (bytes) of the virtq_desc struct per queue size.
const VIRTQ_USED_ENTRYSIZE = 8;
// Mask for wrapping the idx field of the virtq_used struct so that the value
// naturally overflows after 65535 (idx is a word).
const VIRTQ_IDX_MASK = 0xFFFF;

// Queue flags.

const VIRTQ_DESC_F_NEXT = 1;
const VIRTQ_DESC_F_WRITE = 2;
const VIRTQ_DESC_F_INDIRECT = 4;
const VIRTQ_AVAIL_F_NO_INTERRUPT = 1;
const VIRTQ_USED_F_NO_NOTIFY = 1;

// Closure Compiler Types.

/**
 * @typedef {!Array<{
 *     bytes: number,
 *     name: string,
 *     read: function():number,
 *     write: function(number)
 * }>}
 */
var VirtIO_CapabilityStruct;

/**
 * @typedef {
 * {
 *     type: number,
 *     bar: number,
 *     port: number,
 *     use_mmio: boolean,
 *     offset: number,
 *     extra: Uint8Array,
 *     struct: VirtIO_CapabilityStruct,
 * }}
 */
var VirtIO_CapabilityInfo;

/**
 * @typedef {
 * {
 *     size_supported: number,
 *     notify_offset: number,
 * }}
 */
var VirtQueue_Options;

/**
 * @typedef {
 * {
 *     initial_port: (undefined | number),
 *     queues: !Array<VirtQueue_Options>,
 *     features: !Array<number>,
 *     on_driver_ok: function(),
 * }}
 */
var VirtIO_CommonCapabilityOptions;

/**
 * @typedef {
 * {
 *     initial_port: (undefined | number),
 *     single_handler: boolean,
 *     handlers: !Array<function()>,
 * }}
 */
var VirtIO_NotificationCapabilityOptions;

/**
 * @typedef {
 * {
 *     initial_port: (undefined | number),
 * }}
 */
var VirtIO_ISRCapabilityOptions;

/**
 * @typedef {
 * {
 *     initial_port: (undefined | number),
 *     struct: VirtIO_CapabilityStruct,
 * }}
 */
var VirtIO_DeviceSpecificCapabilityOptions;

/**
 * @typedef {
 * {
 *     name: string,
 *     pci_id: (undefined | number),
 *     device_id: number,
 *     subsystem_device_id: number,
 *     on_reset: (undefined | function()),
 *     common: VirtIO_CommonCapabilityOptions,
 *     notification: VirtIO_NotificationCapabilityOptions,
 *     isr_status: VirtIO_ISRCapabilityOptions,
 *     device_specific: (undefined | VirtIO_DeviceSpecificCapabilityOptions),
 *     class_code: (undefined | number),
 *     revision: (undefined | number),
 *     bars: (undefined | !Array<{bar: number, size: number, address: number, prefetchable: boolean, on_move: function(number)}>),
 *     capability_bar: (undefined | number),
 *     shared_memory: (undefined | !Array<{id: number, bar: number, offset: number, length: number}>),
 *     rom_size: (undefined | number),
 *     rom_address: (undefined | number),
 *     qemu_compatible: (undefined | boolean),
 *     irq_line: (undefined | {raise: function(), lower: function()}),
 *     transport: (undefined | VirtIO_Transport),
 * }}
 */
var VirtIO_Options;

/**
 * A transport other than virtio-pci (P5.1): attach() maps the device's
 * registers (the capabilities' fields, by name) and shared memory regions;
 * irq_line is the device's interrupt; present() whether it is on its bus;
 * kind() names it in snapshots, which a device restores only on the same
 * transport; get_state/set_state are the transport's own registers.
 * @typedef {{
 *     attach: function(!VirtIO, !Array<VirtIO_CapabilityInfo>, !Array<{id: number, bar: number, offset: number, length: number}>),
 *     irq_line: {raise: function(), lower: function()},
 *     present: function(): boolean,
 *     kind: function(): string,
 *     get_state: function(): !Array,
 *     set_state: function(!Array),
 * }}
 */
var VirtIO_Transport;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {VirtIO_Options} options
 */
export function VirtIO(cpu, options)
{
    const io = cpu.io;

    /** @const @type {CPU} */
    this.cpu = cpu;

    /**
     * The transport (docs/arm64-virt-android16-plan.md P5.1): null for
     * virtio-pci, the default, on the machine's PCI bus; or one that brings
     * its own registers and interrupt line (src/virtio_mmio.js). This object
     * is the device's core either way: features, status, the configuration
     * generation, the queues and their requests.
     * @const @type {?VirtIO_Transport}
     */
    this.transport = options.transport || null;

    /** @const @type {PCI} */
    this.pci = this.transport ? null : cpu.devices.pci;
    /** on the virt machine's generic PCIe host (P5.7) */
    this.generic = !!(this.pci && this.pci.generic);
    const class_code = options.class_code === undefined && this.generic ? GENERIC_CLASS_CODES[options.device_id] : options.class_code;

    this.device_id = options.device_id;
    this.on_reset = options.on_reset;

    this.pci_space =
    [
        // Vendor ID
        VIRTIO_PCI_VENDOR_ID & 0xFF, VIRTIO_PCI_VENDOR_ID >> 8,
        // Device ID
        options.device_id & 0xFF, options.device_id >> 8,
        // Command
        0x07, 0x05,
        // Status - enable capabilities list
        0x10, 0x00,
        // Revision ID
        options.revision === undefined ? 0x01 : options.revision,
        // Prof IF, Subclass, Class code (by default 0x000200, as v86's
        // virtio devices always had; virtio-vga is a VGA controller, 0x030000)
        ...(class_code === undefined ? [0x00, 0x02, 0x00] :
            [class_code & 0xFF, class_code >> 8 & 0xFF, class_code >> 16 & 0xFF]),
        // Cache line size
        0x00,
        // Latency Timer
        0x00,
        // Header Type
        0x00,
        // Built-in self test
        0x00,
        // BAR0
        0x01, 0xa8, 0x00, 0x00,
        // BAR1
        0x00, 0x10, 0xbf, 0xfe,
        // BAR2
        0x00, 0x00, 0x00, 0x00,
        // BAR3
        0x00, 0x00, 0x00, 0x00,
        // BAR4
        0x00, 0x00, 0x00, 0x00,
        // BAR5
        0x00, 0x00, 0x00, 0x00,
        // CardBus CIS pointer
        0x00, 0x00, 0x00, 0x00,
        // Subsystem vendor ID
        VIRTIO_PCI_VENDOR_ID & 0xFF, VIRTIO_PCI_VENDOR_ID >> 8,
        // Subsystem ID
        ...(this.generic ? [GENERIC_SUBSYSTEM_ID & 0xFF, GENERIC_SUBSYSTEM_ID >> 8] :
            [options.subsystem_device_id & 0xFF, options.subsystem_device_id >> 8]),
        // Expansion ROM base address
        0x00, 0x00, 0x00, 0x00,
        // Capabilities pointer
        0x40,
        // Reserved
        0x00, 0x00, 0x00,
        // Reserved
        0x00, 0x00, 0x00, 0x00,
        // Interrupt line
        0x00,
        // Interrupt pin
        0x01,
        // Min grant
        0x00,
        // Max latency
        0x00,
    ];

    // Prevent sparse arrays by preallocating.
    this.pci_space = this.pci_space.concat(Array(256 - this.pci_space.length).fill(0));
    // Remaining PCI space is appended by capabilities further below.

    this.pci_id = options.pci_id;
    // How the device signals its interrupt: the PCI function's INTx (the
    // virtio-mmio transport of the virt machine brings its own line,
    // docs/arm64-virt-android16-plan.md P1.8)
    this.irq_line = options.irq_line || (this.transport ? this.transport.irq_line : {
        raise: () => this.pci.raise_irq(this.pci_id),
        lower: () => this.pci.lower_irq(this.pci_id),
    });

    // PCI bars gets filled in by capabilities further below, and by the
    // device's own memory BARs (virtio-vga's frame buffer)
    this.pci_bars = [];
    for(const bar of options.bars || [])
    {
        // (on the generic host: 64 bits wide, the next register its upper half)
        this.pci_bars[bar.bar] = { size: bar.size, on_move: bar.on_move, bits64: this.generic };
        const at = 0x10 + 4 * bar.bar;
        const value = (bar.address & ~0xF | (bar.prefetchable ? 8 : 0) | (this.generic ? 4 : 0)) >>> 0;
        this.pci_space[at] = value & 0xFF;
        this.pci_space[at + 1] = value >>> 8 & 0xFF;
        this.pci_space[at + 2] = value >>> 16 & 0xFF;
        this.pci_space[at + 3] = value >>> 24;
    }

    this.name = options.name;

    // virtio-vga: the VGA BIOS, as the expansion ROM (PCI sizes and places it)
    this.pci_rom_size = options.rom_size || 0;
    this.pci_rom_address = options.rom_address || 0;

    // Registers as QEMU's virtio-pci has them, where drivers depend on it
    // (viogpudo): the vector registers keep what the driver writes, though
    // there is no MSI-X (viogpudo always asks for a configuration vector and
    // gives up when it does not read back; interrupts stay INTx), and a
    // configuration change sets both ISR bits (viogpudo's INTx handler takes
    // only 1 and 3)
    this.qemu_compatible = !!options.qemu_compatible;
    this.msix_config_vector = 0xFFFF;

    // Feature bits grouped in dwords, dword selected by decive_feature_select.
    this.device_feature_select = 0;
    this.driver_feature_select = 0;

    // Unspecified upper bound. Assume 4*32=128 bits.
    this.device_feature = new Uint32Array(4);
    this.driver_feature = new Uint32Array(4);
    for(const f of options.common.features)
    {
        dbg_assert(f >= 0,
            "VirtIO device<" + this.name + "> feature bit numbers must be non-negative");
        dbg_assert(f < 128,
            "VirtIO device<" + this.name + "> feature bit numbers assumed less than 128 in implementation");

        // Feature bits are grouped in 32 bits.
        this.device_feature[f >>> 5] |= 1 << (f & 0x1F);
        this.driver_feature[f >>> 5] |= 1 << (f & 0x1F);
    }

    dbg_assert(options.common.features.includes(VIRTIO_F_VERSION_1),
        "VirtIO device<" + this.name + "> only non-transitional devices are supported");

    // Indicates whether driver_feature bits is subset of device_feature bits.
    this.features_ok = true;

    this.device_status = 0;

    this.config_has_changed = false;
    this.config_generation = 0;
    /**
     * Counts the times the function left the bus (a hot plug slot emptied
     * or switched off): requests taken before are not completed after
     */
    this.plug_generation = 0;

    /** @type {!Array<VirtQueue>} */
    this.queues = [];
    for(const queue_options of options.common.queues)
    {
        this.queues.push(new VirtQueue(cpu, this, queue_options));
    }
    this.queue_select = 0;
    this.queue_selected = this.queues[0];

    this.isr_status = 0;

    // Verify notification options.
    if(DEBUG)
    {
        const offsets = new Set();
        for(const offset of this.queues.map(q => q.notify_offset))
        {
            const effective_offset = options.notification.single_handler ? 0 : offset;
            offsets.add(effective_offset);
            dbg_assert(options.notification.handlers[effective_offset],
                "VirtIO device<" + this.name + "> every queue's notifier must exist");
        }
        for(const [index, handler] of options.notification.handlers.entries())
        {
            dbg_assert(!handler || offsets.has(index),
                "VirtIO device<" + this.name +"> no defined notify handler should be unused");
        }
    }

    /** @type {!Array<VirtIO_CapabilityInfo>} */
    const capabilities = [];
    capabilities.push(this.create_common_capability(options.common));
    capabilities.push(this.create_notification_capability(options.notification));
    capabilities.push(this.create_isr_capability(options.isr_status));
    if(options.device_specific)
    {
        capabilities.push(this.create_device_specific_capability(options.device_specific));
    }
    // virtio-vga: every capability in one memory BAR (viogpudo maps only
    // memory BARs), each at its window's distance from the common
    // configuration's, which starts the BAR
    /** @type {!Array<{offset: number, bytes: number, read: function():number, write: function(number), pending: number}>} */
    this.mmio_fields = [];
    /** @type {Int16Array} the field at each offset of the BAR, or -1 */
    this.mmio_index = null;
    this.mmio_base = 0;
    this.mmio_size = 0;
    /** Where the guest put the capabilities' memory BAR (decoded at mmio_base, or not: 0) */
    this.mmio_assigned = 0;
    this.on_upstream_change = () => this.update_mmio();
    if(this.generic)
    {
        // (decoded while its memory space is enabled: update_mmio)
        this.on_command_change = () => this.update_mmio();
        this.on_config_restore = () => this.update_mmio();
        for(const cap of capabilities)
        {
            cap.offset = GENERIC_CAPABILITY_OFFSETS[cap.type];
            cap.port = 0;
            cap.bar = GENERIC_CAPABILITY_BAR;
            cap.use_mmio = true;
        }
    }
    else if(options.capability_bar !== undefined)
    {
        const base = options.common.initial_port;
        for(const cap of capabilities)
        {
            cap.offset = cap.port - base;
            cap.port = 0;
            cap.bar = options.capability_bar;
            cap.use_mmio = true;
        }
    }
    if(this.transport)
    {
        // (another transport maps the same registers its own way)
        this.transport.attach(this, capabilities, options.shared_memory || []);
    }
    else
    {
        this.init_capabilities(capabilities, options.shared_memory || []);
        // (the template's BARs that nothing took read as none)
        for(let bar = 0; bar < 6; bar++)
        {
            if(!this.pci_bars[bar]) this.pci_space.fill(0, 0x10 + 4 * bar, 0x14 + 4 * bar);
        }
        if(this.generic)
        {
            // (at power-on: no decode, no bus mastering, INTx enabled)
            this.pci_space[4] = this.pci_space[5] = 0;
        }

        cpu.devices.pci.register_device(this);
    }
    this.reset();
}

/**
 * Whether the device is on its bus (a PCI function can be unplugged; a
 * virtio-mmio slot always holds its device): requests are not completed
 * while it is not
 * @return {boolean}
 */
VirtIO.prototype.present = function()
{
    return this.transport ? this.transport.present() : !this.pci.absent[/** @type {number} */ (this.pci_id)];
};

/**
 * @param {VirtIO_CommonCapabilityOptions} options
 * @return {VirtIO_CapabilityInfo}
 */
VirtIO.prototype.create_common_capability = function(options)
{
    return {
        type: VIRTIO_PCI_CAP_COMMON_CFG,
        bar: 0,
        // (another transport has no ports)
        port: options.initial_port || 0,
        use_mmio: false,
        offset: 0,
        extra: new Uint8Array(0),
        struct:
        [
            {
                bytes: 4,
                name: "device_feature_select",
                read: () => this.device_feature_select,
                write: data =>
                {
                    this.device_feature_select = data;
                },
            },
            {
                bytes: 4,
                name: "device_feature",
                read: () => this.device_feature[this.device_feature_select] || 0,
                write: data => { /* read only */ },
            },
            {
                bytes: 4,
                name: "driver_feature_select",
                read: () => this.driver_feature_select,
                write: data =>
                {
                    this.driver_feature_select = data;
                },
            },
            {
                bytes: 4,
                name: "driver_feature",
                read: () => this.driver_feature[this.driver_feature_select] || 0,
                write: data =>
                {
                    const supported_feature = this.device_feature[this.driver_feature_select];

                    if(this.driver_feature_select < this.driver_feature.length)
                    {
                        // Note: only set subset of device_features is set.
                        // Required in our implementation for is_feature_negotiated().
                        this.driver_feature[this.driver_feature_select] = data & supported_feature;
                    }

                    // Check that driver features is an inclusive subset of device features.
                    const invalid_bits = data & ~supported_feature;
                    this.features_ok = this.features_ok && !invalid_bits;
                },
            },
            {
                bytes: 2,
                name: "msix_config",
                read: () =>
                {
                    dbg_log("No msi-x capability supported.", LOG_VIRTIO);
                    return this.msix_config_vector;
                },
                write: data =>
                {
                    dbg_log("No msi-x capability supported.", LOG_VIRTIO);
                    if(this.qemu_compatible) this.msix_config_vector = data;
                },
            },
            {
                bytes: 2,
                name: "num_queues",
                read: () => this.queues.length,
                write: data => { /* read only */ },
            },
            {
                bytes: 1,
                name: "device_status",
                read: () => this.device_status,
                write: data =>
                {
                    if(data === 0)
                    {
                        dbg_log("Reset device<" + this.name + ">", LOG_VIRTIO);
                        this.reset();
                    }
                    else if(data & VIRTIO_STATUS_FAILED)
                    {
                        dbg_log("Warning: Device<" + this.name + "> status failed", LOG_VIRTIO);
                    }
                    else
                    {
                        dbg_log("Device<" + this.name +"> status: " +
                                ((data & VIRTIO_STATUS_ACKNOWLEDGE) ? "ACKNOWLEDGE " : "") +
                                ((data & VIRTIO_STATUS_DRIVER) ? "DRIVER " : "") +
                                ((data & VIRTIO_STATUS_DRIVER_OK) ? "DRIVER_OK" : "") +
                                ((data & VIRTIO_STATUS_FEATURES_OK) ? "FEATURES_OK " : "") +
                                ((data & VIRTIO_STATUS_DEVICE_NEEDS_RESET) ? "DEVICE_NEEDS_RESET" : ""),
                                LOG_VIRTIO);
                    }

                    if((data & ~this.device_status & VIRTIO_STATUS_DRIVER_OK) &&
                        (this.device_status & VIRTIO_STATUS_DEVICE_NEEDS_RESET))
                    {
                        // We couldn't notify NEEDS_RESET earlier because DRIVER_OK was not set.
                        // Now it has been set, notify now.
                        this.notify_config_changes();
                    }

                    // Don't set FEATURES_OK if our device doesn't support requested features.
                    if(!this.features_ok)
                    {
                        if(DEBUG && (data & VIRTIO_STATUS_FEATURES_OK))
                        {
                            dbg_log("Removing FEATURES_OK", LOG_VIRTIO);
                        }
                        data &= ~VIRTIO_STATUS_FEATURES_OK;
                    }

                    // (DRIVER_OK newly set: compared with the status before the write)
                    const before = this.device_status;
                    this.device_status = data;

                    if(data & ~before & VIRTIO_STATUS_DRIVER_OK)
                    {
                        options.on_driver_ok();
                    }
                },
            },
            {
                bytes: 1,
                name: "config_generation",
                read: () => this.config_generation,
                write: data => { /* read only */ },
            },
            {
                bytes: 2,
                name: "queue_select",
                read: () => this.queue_select,
                write: data =>
                {
                    this.queue_select = data;

                    if(this.queue_select < this.queues.length)
                    {
                        this.queue_selected = this.queues[this.queue_select];
                    }
                    else
                    {
                        // Allow queue_select >= num_queues.
                        this.queue_selected = null;
                        // Drivers can then detect that the queue is not available
                        // using the below fields.
                    }
                },
            },
            {
                bytes: 2,
                name: "queue_size",
                read: () => this.queue_selected ? this.queue_selected.size : 0,
                write: data =>
                {
                    if(!this.queue_selected)
                    {
                        return;
                    }
                    if(data & data - 1)
                    {
                        dbg_log("Warning: dev<" + this.name +"> " +
                                "Given queue size was not a power of 2. " +
                                "Rounding up to next power of 2.", LOG_VIRTIO);
                        data = 1 << (int_log2(data - 1) + 1);
                    }
                    if(data > this.queue_selected.size_supported)
                    {
                        dbg_log("Warning: dev<" + this.name +"> " +
                                "Trying to set queue size greater than supported. " +
                                "Clamping to supported size.", LOG_VIRTIO);
                        data = this.queue_selected.size_supported;
                    }
                    this.queue_selected.set_size(data);
                },
            },
            {
                bytes: 2,
                name: "queue_msix_vector",
                read: () =>
                {
                    dbg_log("No msi-x capability supported.", LOG_VIRTIO);
                    return this.queue_selected ? this.queue_selected.msix_vector : 0xFFFF;
                },
                write: data =>
                {
                    dbg_log("No msi-x capability supported.", LOG_VIRTIO);
                    if(this.qemu_compatible && this.queue_selected) this.queue_selected.msix_vector = data;
                },
            },
            {
                bytes: 2,
                name: "queue_enable",
                read: () => this.queue_selected ? this.queue_selected.enabled | 0 : 0,
                write: data =>
                {
                    if(!this.queue_selected)
                    {
                        return;
                    }
                    if(data === 1)
                    {
                        if(this.queue_selected.is_configured())
                        {
                            this.queue_selected.enable();
                        }
                        else
                        {
                            dbg_log("Driver bug: tried enabling unconfigured queue", LOG_VIRTIO);
                        }
                    }
                    else if(data === 0)
                    {
                        dbg_log("Driver bug: tried writing 0 to queue_enable", LOG_VIRTIO);
                    }
                },
            },
            {
                bytes: 2,
                name: "queue_notify_off",
                read: () => this.queue_selected ? this.queue_selected.notify_offset : 0,
                write: data => { /* read only */ },
            },
            {
                bytes: 4,
                name: "queue_desc (low dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[0] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(0, data);
                },
            },
            {
                bytes: 4,
                name: "queue_desc (high dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[1] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(1, data);
                },
            },
            {
                bytes: 4,
                name: "queue_avail (low dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[2] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(2, data);
                },
            },
            {
                bytes: 4,
                name: "queue_avail (high dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[3] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(3, data);
                },
            },
            {
                bytes: 4,
                name: "queue_used (low dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[4] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(4, data);
                },
            },
            {
                bytes: 4,
                name: "queue_used (high dword)",
                read: () => this.queue_selected ? this.queue_selected.address_words[5] : 0,
                write: data =>
                {
                    if(this.queue_selected) this.queue_selected.set_address_word(5, data);
                },
            },
        ],
    };
};

/**
 * @param {VirtIO_NotificationCapabilityOptions} options
 * @return {VirtIO_CapabilityInfo}
 */
VirtIO.prototype.create_notification_capability = function(options)
{
    const notify_struct = [];
    let notify_off_multiplier;

    if(options.single_handler)
    {
        dbg_assert(options.handlers.length === 1,
            "VirtIO device<" + this.name + "> too many notify handlers specified: expected single handler");

        // Forces all queues to use the same address for notifying.
        notify_off_multiplier = 0;
    }
    else
    {
        notify_off_multiplier = 2;
    }

    for(const [i, handler] of options.handlers.entries())
    {
        const notify_handler = /** @type {function(number)} */ (handler);
        notify_struct.push(
        {
            bytes: 2,
            name: "notify" + i,
            read: () => 0xFFFF,
            write: data =>
            {
                if(!notify_handler || this.device_status & VIRTIO_STATUS_DEVICE_NEEDS_RESET) return;
                try
                {
                    notify_handler(data);
                }
                catch(error)
                {
                    if(!(error instanceof RangeError)) throw error;
                    this.needs_reset();
                }
            },
        });
    }

    return {
        type: VIRTIO_PCI_CAP_NOTIFY_CFG,
        bar: 1,
        // (another transport has no ports)
        port: options.initial_port || 0,
        use_mmio: false,
        offset: 0,
        extra: new Uint8Array(
        [
            notify_off_multiplier & 0xFF,
            (notify_off_multiplier >> 8) & 0xFF,
            (notify_off_multiplier >> 16) & 0xFF,
            notify_off_multiplier >> 24,
        ]),
        struct: notify_struct,
    };
};

/**
 * @param {VirtIO_ISRCapabilityOptions} options
 * @return {VirtIO_CapabilityInfo}
 */
VirtIO.prototype.create_isr_capability = function(options)
{
    return {
        type: VIRTIO_PCI_CAP_ISR_CFG,
        bar: 2,
        // (another transport has no ports)
        port: options.initial_port || 0,
        use_mmio: false,
        offset: 0,
        extra: new Uint8Array(0),
        struct:
        [
            {
                bytes: 1,
                name: "isr_status",
                read: () =>
                {
                    const isr_status = this.isr_status;
                    this.lower_irq();
                    return isr_status;
                },
                write: data => { /* read only */ },
            },
        ],
    };
};

/**
 * @param {VirtIO_DeviceSpecificCapabilityOptions} options
 * @return {VirtIO_CapabilityInfo}
 */
VirtIO.prototype.create_device_specific_capability = function(options)
{
    dbg_assert(~options.offset & 0x3,
            "VirtIO device<" + this.name + "> device specific cap offset must be 4-byte aligned");

    return {
        type: VIRTIO_PCI_CAP_DEVICE_CFG,
        bar: 3,
        // (another transport has no ports)
        port: options.initial_port || 0,
        use_mmio: false,
        offset: 0,
        extra: new Uint8Array(0),
        struct: options.struct,
    };
};

/**
 * Writes capabilities into pci_space and hook up IO/MMIO handlers.
 * Call only within constructor.
 * @param {!Array<VirtIO_CapabilityInfo>} capabilities
 * @param {!Array<{id: number, bar: number, offset: number, length: number}>} shared_memory
 *     shared memory regions (the device's own memory BARs, options.bars)
 */
VirtIO.prototype.init_capabilities = function(capabilities, shared_memory)
{
    // Next available offset for capabilities linked list.
    let cap_next = this.pci_space[0x34] = 0x40;

    // Current offset.
    let cap_ptr = cap_next;

    // Capabilities may share a BAR (at their offsets): it spans the furthest
    const bar_extent = [];
    for(const cap of capabilities)
    {
        const end = cap.offset + cap.struct.reduce((bytes, field) => bytes + field.bytes, 0);
        bar_extent[cap.bar] = Math.max(bar_extent[cap.bar] || 0, end);
    }

    for(const cap of capabilities)
    {
        const cap_len = VIRTIO_PCI_CAP_LENGTH + cap.extra.length;

        cap_ptr = cap_next;
        cap_next = cap_ptr + cap_len;

        dbg_assert(cap_next <= 256,
            "VirtIO device<" + this.name + "> can't fit all capabilities into 256byte configspace");

        dbg_assert(0 <= cap.bar && cap.bar < 6,
            "VirtIO device<" + this.name + "> capability invalid bar number");

        let bar_size = bar_extent[cap.bar];

        // Round up to next power of 2,
        // Minimum 16 bytes for its size to be detectable in general (esp. mmio).
        bar_size = bar_size < 16 ? 16 : 1 << (int_log2(bar_size - 1) + 1);
        // (memory is decoded in blocks: the BAR has whole ones to itself;
        // not on the generic host, whose BARs are decoded exactly)
        if(cap.use_mmio && !this.generic) bar_size = Math.max(bar_size, MMAP_BLOCK_SIZE);
        // (this capability's own length: its struct)
        const cap_size = cap.struct.reduce((bytes, field) => bytes + field.bytes, 0);

        dbg_assert((cap.port & (bar_size - 1)) === 0,
            "VirtIO device<" + this.name + "> capability port should be aligned to pci bar size");

        this.pci_bars[cap.bar] = cap.use_mmio ?
            { size: bar_size, on_move: base => this.move_mmio(base), bits64: this.generic } :
            { size: bar_size };
        if(cap.use_mmio) this.mmio_size = bar_size;

        this.pci_space[cap_ptr] = VIRTIO_PCI_CAP_VENDOR;
        this.pci_space[cap_ptr + 1] = cap_next;
        this.pci_space[cap_ptr + 2] = cap_len;
        this.pci_space[cap_ptr + 3] = cap.type;
        this.pci_space[cap_ptr + 4] = cap.bar;

        this.pci_space[cap_ptr + 5] = 0; // Padding.
        this.pci_space[cap_ptr + 6] = 0; // Padding.
        this.pci_space[cap_ptr + 7] = 0; // Padding.

        this.pci_space[cap_ptr + 8] = cap.offset & 0xFF;
        this.pci_space[cap_ptr + 9] = (cap.offset >>> 8) & 0xFF;
        this.pci_space[cap_ptr + 10] = (cap.offset >>> 16) & 0xFF;
        this.pci_space[cap_ptr + 11] = cap.offset >>> 24;

        // (the length of the capability's window: the whole BAR when it has
        // it alone, as before; its struct when it shares)
        const shared = capabilities.filter(other => other.bar === cap.bar).length > 1;
        const cap_window = this.generic ? GENERIC_CAPABILITY_WINDOW : shared ? Math.max(cap_size, 4) : bar_size;
        this.pci_space[cap_ptr + 12] = cap_window & 0xFF;
        this.pci_space[cap_ptr + 13] = (cap_window >>> 8) & 0xFF;
        this.pci_space[cap_ptr + 14] = (cap_window >>> 16) & 0xFF;
        this.pci_space[cap_ptr + 15] = cap_window >>> 24;

        for(const [i, extra_byte] of cap.extra.entries())
        {
            this.pci_space[cap_ptr + 16 + i] = extra_byte;
        }

        const bar_offset = 0x10 + 4 * cap.bar;
        // (the generic host's: 64-bit, prefetchable)
        this.pci_space[bar_offset] = this.generic ? 0x0C : (cap.port & 0xFE) | !cap.use_mmio;
        this.pci_space[bar_offset + 1] = (cap.port >>> 8) & 0xFF;
        this.pci_space[bar_offset + 2] = (cap.port >>> 16) & 0xFF;
        this.pci_space[bar_offset + 3] = (cap.port >>> 24) & 0xFF;

        let port = cap.port + cap.offset;

        for(const field of cap.struct)
        {
            let read = field.read;
            let write = field.write;

            if(DEBUG)
            {
                read = () =>
                {
                    const val = field.read();

                    dbg_log("Device<" + this.name + "> " +
                            "cap[" + cap.type + "] " +
                            "read[" + field.name + "] " +
                            "=> " + h(val, field.bytes * 8),
                        LOG_VIRTIO);

                    return val;
                };
                write = data =>
                {
                    dbg_log("Device<" + this.name + "> " +
                            "cap[" + cap.type + "] " +
                            "write[" + field.name + "] " +
                            "<= " + h(data, field.bytes * 8),
                        LOG_VIRTIO);

                    field.write(data);
                };
            }

            if(cap.use_mmio)
            {
                // (port is the offset in the BAR: move_mmio maps it)
                this.mmio_fields.push({ offset: port, bytes: field.bytes, read, write, pending: 0 });
            }
            else
            {
                // DSL (2.4 kernel) does these reads
                const shim_read8_on_16 = function(addr)
                {
                    dbg_log("Warning: 8-bit read from 16-bit virtio port", LOG_VIRTIO);
                    return read(addr & ~1) >> ((addr & 1) << 3) & 0xFF;
                };
                const shim_read8_on_32 = function(addr)
                {
                    dbg_log("Warning: 8-bit read from 32-bit virtio port", LOG_VIRTIO);
                    return read(addr & ~3) >> ((addr & 3) << 3) & 0xFF;
                };

                // archhurd does these reads
                const shim_read32_on_16 = function(addr)
                {
                    dbg_log("Warning: 32-bit read from 16-bit virtio port", LOG_VIRTIO);
                    return read(addr);
                };

                switch(field.bytes)
                {
                    case 4:
                        this.cpu.io.register_read(port, this, shim_read8_on_32, undefined, read);
                        this.cpu.io.register_read(port + 1, this, shim_read8_on_32);
                        this.cpu.io.register_read(port + 2, this, shim_read8_on_32);
                        this.cpu.io.register_read(port + 3, this, shim_read8_on_32);
                        this.cpu.io.register_write(port, this, undefined, undefined, write);
                        break;
                    case 2:
                        this.cpu.io.register_read(port, this, shim_read8_on_16, read, shim_read32_on_16);
                        this.cpu.io.register_read(port + 1, this, shim_read8_on_16);
                        this.cpu.io.register_write(port, this, undefined, write);
                        break;
                    case 1:
                        this.cpu.io.register_read(port, this, read);
                        this.cpu.io.register_write(port, this, write);
                        break;
                    default:
                        dbg_assert(false,
                            "VirtIO device <" + this.name + "> invalid capability field width of " +
                            field.bytes + " bytes");
                        break;
                }
            }

            port += field.bytes;
        }
    }

    if(this.mmio_fields.length)
    {
        const end = Math.max(...this.mmio_fields.map(field => field.offset + field.bytes));
        this.mmio_index = new Int16Array(end).fill(-1);
        this.mmio_fields.forEach((field, i) => this.mmio_index.fill(i, field.offset, field.offset + field.bytes));
    }

    // Shared memory regions: struct virtio_pci_cap64, the id in the byte
    // after the BAR, the offset's and length's high dwords after the struct
    for(const region of shared_memory)
    {
        const cap_len = VIRTIO_PCI_CAP_LENGTH + 8;
        cap_ptr = cap_next;
        cap_next = cap_ptr + cap_len;
        dbg_assert(cap_next <= 256,
            "VirtIO device<" + this.name + "> can't fit all capabilities into 256byte configspace");
        this.pci_space[cap_ptr] = VIRTIO_PCI_CAP_VENDOR;
        this.pci_space[cap_ptr + 1] = cap_next;
        this.pci_space[cap_ptr + 2] = cap_len;
        this.pci_space[cap_ptr + 3] = VIRTIO_PCI_CAP_SHARED_MEMORY_CFG;
        this.pci_space[cap_ptr + 4] = region.bar;
        this.pci_space[cap_ptr + 5] = region.id;
        for(let i = 0; i < 4; i++)
        {
            this.pci_space[cap_ptr + 8 + i] = region.offset >>> 8 * i & 0xFF;
            this.pci_space[cap_ptr + 12 + i] = region.length >>> 8 * i & 0xFF;
        }
        this.pci_space.fill(0, cap_ptr + 16, cap_ptr + 24);
    }

    // Terminate linked list with the pci config access capability.

    const cap_len = VIRTIO_PCI_CAP_LENGTH + 4;
    dbg_assert(cap_next + cap_len <= 256,
        "VirtIO device<" + this.name + "> can't fit all capabilities into 256byte configspace");
    this.pci_space[cap_next] = VIRTIO_PCI_CAP_VENDOR;
    this.pci_space[cap_next + 1] = 0; // cap next (null terminator)
    this.pci_space[cap_next + 2] = cap_len;
    this.pci_space[cap_next + 3] = VIRTIO_PCI_CAP_PCI_CFG; // cap type
    this.pci_space[cap_next + 4] = 0; // bar (written by device)
    this.pci_space[cap_next + 5] = 0; // Padding.
    this.pci_space[cap_next + 6] = 0; // Padding.
    this.pci_space[cap_next + 7] = 0; // Padding.

    // Remaining fields are configured by driver when needed.

    // offset
    this.pci_space[cap_next + 8] = 0;
    this.pci_space[cap_next + 9] = 0;
    this.pci_space[cap_next + 10] = 0;
    this.pci_space[cap_next + 11] = 0;

    // bar size
    this.pci_space[cap_next + 12] = 0;
    this.pci_space[cap_next + 13] = 0;
    this.pci_space[cap_next + 14] = 0;
    this.pci_space[cap_next + 15] = 0;

    // cfg_data
    this.pci_space[cap_next + 16] = 0;
    this.pci_space[cap_next + 17] = 0;
    this.pci_space[cap_next + 18] = 0;
    this.pci_space[cap_next + 19] = 0;

    //
    // TODO
    // The pci config access capability is required by spec, but so far, devices
    // seem to work well without it.
    // This capability provides a cfg_data field (at cap_next + 16 for 4 bytes)
    // that acts like a window to the previous bars. The driver writes the bar number,
    // offset, and length values in this capability, and the cfg_data field should
    // mirror the data referred by the bar, offset and length. Here, length can be
    // 1, 2, or 4.
    //
    // This requires some sort of pci devicespace read and write handlers.
};

/**
 * The function left the bus (src/pci.js set_function_present): what the
 * driver handed over before is gone with the card
 */
VirtIO.prototype.on_unplug = function()
{
    this.plug_generation++;
};

/**
 * The capabilities' memory BAR moved (the BIOS or the OS placed it)
 * @param {number} base
 */
VirtIO.prototype.move_mmio = function(base)
{
    this.mmio_assigned = base;
    this.update_mmio();
};

/**
 * Decode the capabilities' memory BAR where it is assigned; behind a bridge
 * only while the bridges forward it (on_upstream_change)
 */
VirtIO.prototype.update_mmio = function()
{
    if(this.generic)
    {
        this.update_generic_decode();
        return;
    }
    const assigned = this.mmio_assigned;
    const base = assigned && this.cpu.devices.pci.upstream_forwards_memory(this.pci_id, assigned >>> 0, this.mmio_size) ? assigned : 0;
    if(base === this.mmio_base)
    {
        return;
    }
    if(this.mmio_base) this.cpu.io.mmap_unregister(this.mmio_base, this.mmio_size);
    this.mmio_base = base;
    if(base)
    {
        this.cpu.io.mmap_register(base, this.mmio_size,
            addr => this.mmio_read8(addr), (addr, value) => this.mmio_write8(addr, value),
            addr => this.mmio_read32(addr), (addr, value) => this.mmio_write32(addr, value));
    }
};

/**
 * The generic host (P5.7): the capabilities' BAR decoded where it is
 * assigned while the function's memory space is enabled, by offset and
 * width (an 8-byte access is two 4-byte ones, a 2-byte one two bytes)
 */
VirtIO.prototype.update_generic_decode = function()
{
    const assigned = this.mmio_assigned;
    const base = assigned && this.pci.is_memory_enabled(/** @type {number} */ (this.pci_id)) ? assigned : 0;
    if(base === this.mmio_base)
    {
        return;
    }
    this.mmio_base = base;
    const at = offset => this.mmio_base + offset;
    this.pci.set_memory_decoder(this, base || -1, this.mmio_size, {
        read: (offset, width) => {
            if(width === 1) return this.mmio_read8(at(offset));
            if(width === 2) return this.mmio_read8(at(offset)) | this.mmio_read8(at(offset + 1)) << 8;
            if(width === 4) return this.mmio_read32(at(offset)) >>> 0;
            return BigInt(this.mmio_read32(at(offset)) >>> 0) | BigInt(this.mmio_read32(at(offset + 4)) >>> 0) << 32n;
        },
        write: (offset, width, value) => {
            if(width === 8)
            {
                const wide = /** @type {bigint} */ (value);
                this.mmio_write32(at(offset), Number(BigInt.asUintN(32, wide)) | 0);
                this.mmio_write32(at(offset + 4), Number(wide >> 32n) | 0);
            }
            else if(width === 4) this.mmio_write32(at(offset), value | 0);
            else
            {
                for(let i = 0; i < width; i++) this.mmio_write8(at(offset + i), value >>> 8 * i & 0xFF);
            }
        },
    });
};

/**
 * @param {number} addr
 * @return {?{offset: number, bytes: number, read: function():number, write: function(number), pending: number}}
 */
VirtIO.prototype.mmio_field = function(addr)
{
    // (addresses above 2 GiB arrive as negative int32s)
    const offset = addr - this.mmio_base >>> 0;
    const i = offset < this.mmio_index.length ? this.mmio_index[offset] : -1;
    return i >= 0 ? this.mmio_fields[i] : null;
};

VirtIO.prototype.mmio_read8 = function(addr)
{
    const field = this.mmio_field(addr);
    return field ? field.read() >>> 8 * ((addr - this.mmio_base >>> 0) - field.offset) & 0xFF : 0;
};

/**
 * A byte of a field. The CPU writes 16-bit values a byte at a time, so a
 * wider field takes effect with its last byte.
 */
VirtIO.prototype.mmio_write8 = function(addr, value)
{
    const field = this.mmio_field(addr);
    if(!field) return;
    const at = (addr - this.mmio_base >>> 0) - field.offset;
    field.pending = (at ? field.pending & (1 << 8 * at) - 1 : 0) | value << 8 * at;
    if(at === field.bytes - 1) field.write(field.bytes === 4 ? field.pending | 0 : field.pending);
};

VirtIO.prototype.mmio_read32 = function(addr)
{
    const field = this.mmio_field(addr);
    if(field && field.bytes === 4 && (addr - this.mmio_base >>> 0) === field.offset) return field.read() | 0;
    return this.mmio_read8(addr) | this.mmio_read8(addr + 1) << 8 | this.mmio_read8(addr + 2) << 16 | this.mmio_read8(addr + 3) << 24;
};

VirtIO.prototype.mmio_write32 = function(addr, value)
{
    const field = this.mmio_field(addr);
    if(field && field.bytes === 4 && (addr - this.mmio_base >>> 0) === field.offset)
    {
        field.write(value);
        return;
    }
    for(let i = 0; i < 4; i++) this.mmio_write8(addr + i, value >>> 8 * i & 0xFF);
};

VirtIO.prototype.get_state = function()
{
    let state = [];

    state[0] = this.device_feature_select;
    state[1] = this.driver_feature_select;
    state[2] = this.device_feature;
    state[3] = this.driver_feature;
    state[4] = this.features_ok;
    state[5] = this.device_status;
    state[6] = this.config_has_changed;
    state[7] = this.config_generation;
    state[8] = this.isr_status;
    state[9] = this.queue_select;
    // (P5.9: the transport, and its own registers)
    state[10] = this.transport ? [this.transport.kind(), this.transport.get_state()] : ["pci"];
    state = state.concat(this.queues);

    return state;
};

VirtIO.prototype.set_state = function(state)
{
    this.device_feature_select = state[0];
    this.driver_feature_select = state[1];
    this.device_feature = state[2];
    this.driver_feature = state[3];
    this.features_ok = state[4];
    this.device_status = state[5];
    this.config_has_changed = state[6];
    this.config_generation = state[7];
    this.isr_status = state[8];
    this.queue_select = state[9];
    // (snapshots before P5.9: no transport, the queues from 10; virtio-pci)
    const tagged = Array.isArray(state[10]) && typeof state[10][0] === "string";
    const kind = tagged ? state[10][0] : "pci";
    const own = this.transport ? this.transport.kind() : "pci";
    if(kind !== own)
    {
        throw new Error("The snapshot has " + this.name + " on " + kind + ", this machine on " + own);
    }
    if(this.transport && tagged) this.transport.set_state(state[10][1]);
    let i = 0;
    for(const queue of state.slice(tagged ? 11 : 10))
    {
        this.queues[i].set_state(queue);
        i++;
    }
    this.queue_selected = this.queues[this.queue_select] || null;
};

VirtIO.prototype.reset = function()
{
    this.device_feature_select = 0;
    this.driver_feature_select = 0;
    this.driver_feature.set(this.device_feature);

    this.features_ok = true;
    this.device_status = 0;
    this.msix_config_vector = 0xFFFF;

    this.queue_select = 0;
    this.queue_selected = this.queues[0];

    for(const queue of this.queues)
    {
        queue.reset();
    }

    this.config_has_changed = false;
    this.config_generation = 0;

    this.lower_irq();
    if(this.on_reset) this.on_reset();
};

/**
 * Call this when device-specific configuration state changes.
 * Also called when status DEVICE_NEEDS_RESET is set.
 */
VirtIO.prototype.notify_config_changes = function()
{
    this.config_has_changed = true;

    if(this.device_status & VIRTIO_STATUS_DRIVER_OK)
    {
        this.raise_irq(this.qemu_compatible ? VIRTIO_ISR_DEVICE_CFG | VIRTIO_ISR_QUEUE : VIRTIO_ISR_DEVICE_CFG);
    }
    else
    {
        dbg_assert(false,
            "VirtIO device<" + this.name + "> attempted to notify driver before DRIVER_OK");
    }
};

/**
 * To be called after reading any field whose write can trigger notify_config_changes().
 */
VirtIO.prototype.update_config_generation = function()
{
    if(this.config_has_changed)
    {
        this.config_generation++;
        this.config_generation &= 0xFF;
        this.config_has_changed = false;
    }
};

VirtIO.prototype.is_feature_negotiated = function(feature)
{
    // Feature bits are grouped in 32 bits.
    // Note: earlier we chose not to set invalid features into driver_feature.
    return (this.driver_feature[feature >>> 5] & (1 << (feature & 0x1F))) > 0;
};

/**
 * Call this if an irrecoverable error has been occured.
 * Notifies driver if DRIVER_OK, or when DRIVER_OK gets set.
 */
VirtIO.prototype.needs_reset = function()
{
    dbg_log("Device<" + this.name + "> experienced error - requires reset", LOG_VIRTIO);
    this.device_status |= VIRTIO_STATUS_DEVICE_NEEDS_RESET;

    if(this.device_status & VIRTIO_STATUS_DRIVER_OK)
    {
        this.notify_config_changes();
    }
};

VirtIO.prototype.raise_irq = function(type)
{
    dbg_log("Raise irq " + h(type), LOG_VIRTIO);
    this.isr_status |= type;
    this.irq_line.raise();
};

VirtIO.prototype.lower_irq = function()
{
    dbg_log("Lower irq ", LOG_VIRTIO);
    this.isr_status = 0;
    this.irq_line.lower();
};

/**
 * @constructor
 * @param {CPU} cpu
 * @param {VirtQueue_Options} options
 */
function VirtQueue(cpu, virtio, options)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    /** @const @type {VirtIO} */
    this.virtio = virtio;

    // Number of entries.
    this.size = options.size_supported;
    this.size_supported = options.size_supported;
    this.mask = this.size - 1;
    this.enabled = false;
    this.notify_offset = options.notify_offset;

    this.address_words = new Uint32Array(6);
    // (see VirtIO.qemu_compatible)
    this.msix_vector = 0xFFFF;
    this.desc_addr = 0;

    this.avail_addr = 0;
    this.avail_last_idx = 0;

    this.used_addr = 0;
    this.num_staged_replies = 0;

    this.reset();
}

VirtQueue.prototype.get_state = function()
{
    const state = [];

    state[0] = this.size;
    state[1] = this.size_supported;
    state[2] = this.enabled;
    state[3] = this.notify_offset;
    state[4] = this.desc_addr;
    state[5] = this.avail_addr;
    state[6] = this.avail_last_idx;
    state[7] = this.used_addr;
    state[8] = this.num_staged_replies;
    state[9] = 1;
    state[10] = this.address_words;

    return state;
};

VirtQueue.prototype.set_state = function(state)
{
    this.size = state[0];
    this.size_supported = state[1];
    this.enabled = state[2];
    this.notify_offset = state[3];
    this.desc_addr = state[10] ? state[4] : state[4] >>> 0;
    this.avail_addr = state[10] ? state[5] : state[5] >>> 0;
    this.avail_last_idx = state[6];
    this.used_addr = state[10] ? state[7] : state[7] >>> 0;
    this.num_staged_replies = state[8];

    this.address_words = state[10] || new Uint32Array([
        this.desc_addr, 0, this.avail_addr, 0, this.used_addr, 0,
    ]);
    this.mask = this.size - 1;
    this.fix_wrapping = state[9] !== 1;
};

VirtQueue.prototype.reset = function()
{
    this.enabled = false;
    this.address_words.fill(0);
    this.desc_addr = 0;
    this.avail_addr = 0;
    this.avail_last_idx = 0;
    this.used_addr = 0;
    this.num_staged_replies = 0;
    this.msix_vector = 0xFFFF;
    this.set_size(this.size_supported);
};

// Retain raw DWORDs even for unsupported 64-bit values, so register readback
// and snapshots never round an invalid address into a usable low address.
VirtQueue.prototype.set_address_word = function(index, value)
{
    if(this.enabled) return;
    this.address_words[index] = value;
    this.desc_addr = this.address_words[0] + this.address_words[1] * 0x100000000;
    this.avail_addr = this.address_words[2] + this.address_words[3] * 0x100000000;
    this.used_addr = this.address_words[4] + this.address_words[5] * 0x100000000;
};

VirtQueue.prototype.is_configured = function()
{
    return this.size > 0 && this.desc_addr > 0 && this.avail_addr > 0 && this.used_addr > 0;
};

VirtQueue.prototype.enable = function()
{
    dbg_assert(this.is_configured(), "VirtQueue must be configured before enabled");
    try
    {
        if((this.desc_addr % 16) || (this.avail_addr % 2) || (this.used_addr % 4))
        {
            throw new RangeError("Unaligned VirtIO queue");
        }
        this.cpu.validate_physical_range(this.desc_addr, this.size * VIRTQ_DESC_ENTRYSIZE);
        this.cpu.validate_physical_range(this.avail_addr, VIRTQ_AVAIL_BASESIZE + this.size * VIRTQ_AVAIL_ENTRYSIZE);
        this.cpu.validate_physical_range(this.used_addr, VIRTQ_USED_BASESIZE + this.size * VIRTQ_USED_ENTRYSIZE);
        this.enabled = true;
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.virtio.needs_reset();
    }
};

VirtQueue.prototype.set_size = function(size)
{
    dbg_assert((size & size - 1) === 0, "VirtQueue size must be power of 2 or zero");
    dbg_assert(size <= this.size_supported, "VirtQueue size must be within supported size");
    this.size = size;
    this.mask = size - 1;
};

/**
 * @return {number}
 */
VirtQueue.prototype.count_requests = function()
{
    dbg_assert(this.avail_addr, "VirtQueue addresses must be configured before use");
    if(this.fix_wrapping) {
        this.fix_wrapping = false;
        this.avail_last_idx = (this.avail_get_idx() & ~this.mask) + (this.avail_last_idx & this.mask);
    }
    return (this.avail_get_idx() - this.avail_last_idx) & 0xFFFF;
};

/**
 * @return {boolean}
 */
VirtQueue.prototype.has_request = function()
{
    if(!this.enabled || this.virtio.device_status & VIRTIO_STATUS_DEVICE_NEEDS_RESET) return false;
    // (off the bus: a hot plug slot that is empty or switched off)
    if(!this.virtio.present()) return false;
    try
    {
        return this.count_requests() !== 0;
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.virtio.needs_reset();
        return false;
    }
};

/**
 * @return {VirtQueueBufferChain}
 */
VirtQueue.prototype.pop_request = function()
{
    dbg_assert(this.avail_addr, "VirtQueue addresses must be configured before use");
    dbg_assert(this.has_request(), "VirtQueue must not pop nonexistent request");

    const desc_idx = this.avail_get_entry(this.avail_last_idx);
    dbg_log("Pop request: avail_last_idx=" + this.avail_last_idx +
        " desc_idx=" + desc_idx, LOG_VIRTIO);

    const bufchain = new VirtQueueBufferChain(this, desc_idx);

    this.avail_last_idx = (this.avail_last_idx + 1) & 0xFFFF;

    return bufchain;
};

/**
 * Stage a buffer chain into the used ring.
 * Can call push_reply many times before flushing to batch replies together.
 * Note: this reply is not visible to driver until flush_replies is called.
 * @param {VirtQueueBufferChain} bufchain
 */
VirtQueue.prototype.push_reply = function(bufchain)
{
    if(!bufchain.valid || bufchain.plug_generation !== this.virtio.plug_generation) return;
    dbg_assert(this.used_addr, "VirtQueue addresses must be configured before use");
    dbg_assert(this.num_staged_replies < this.size, "VirtQueue replies must not exceed queue size");

    const used_idx = this.used_get_idx() + this.num_staged_replies & this.mask;
    dbg_log("Push reply: used_idx=" + used_idx +
        " desc_idx=" + bufchain.head_idx, LOG_VIRTIO);

    this.used_set_entry(used_idx, bufchain.head_idx, bufchain.length_written);
    this.num_staged_replies++;
};

/**
 * Makes replies visible to driver by updating the used ring idx and
 * firing appropriate interrupt if needed.
 */
VirtQueue.prototype.flush_replies = function()
{
    if(!this.virtio.present())
    {
        // (off the bus: nothing reaches the driver's rings)
        this.num_staged_replies = 0;
        return;
    }
    dbg_assert(this.used_addr, "VirtQueue addresses must be configured before use");

    if(this.num_staged_replies === 0)
    {
        dbg_log("flush_replies: Nothing to flush", LOG_VIRTIO);
        return;
    }

    dbg_log("Flushing " + this.num_staged_replies + " replies", LOG_VIRTIO);
    const old_idx = this.used_get_idx();
    const new_idx = old_idx + this.num_staged_replies & VIRTQ_IDX_MASK;
    this.used_set_idx(new_idx);

    this.num_staged_replies = 0;

    if(this.virtio.is_feature_negotiated(VIRTIO_F_RING_EVENT_IDX))
    {
        const used_event = this.avail_get_used_event();

        // Fire irq when idx values associated with the pushed reply buffers
        // has reached or gone past used_event.
        let has_passed = old_idx <= used_event && used_event < new_idx;

        // Has overflowed? Assumes num_staged_replies > 0.
        if(new_idx <= old_idx)
        {
            has_passed = used_event < new_idx || old_idx <= used_event;
        }

        // Commented out: Workaround for sometimes loading from the filesystem hangs and the emulator stays idle
        //if(has_passed)
        {
            this.virtio.raise_irq(VIRTIO_ISR_QUEUE);
        }
    }
    else
    {
        if(~this.avail_get_flags() & VIRTQ_AVAIL_F_NO_INTERRUPT)
        {
            this.virtio.raise_irq(VIRTIO_ISR_QUEUE);
        }
    }
};

/**
 * If using VIRTIO_F_RING_EVENT_IDX, device must tell driver when
 * to get notifications or else driver won't notify regularly.
 * If not using VIRTIO_F_RING_EVENT_IDX, driver will ignore avail_event
 * and notify every request regardless unless NO_NOTIFY is set (TODO implement when needed).
 * @param {number} num_skipped_requests Zero = get notified in the next request.
 */
VirtQueue.prototype.notify_me_after = function(num_skipped_requests)
{
    dbg_assert(num_skipped_requests >= 0, "Must skip a non-negative number of requests");

    // The 16 bit idx field wraps around after 2^16.
    const avail_event = this.avail_get_idx() + num_skipped_requests & 0xFFFF;
    this.used_set_avail_event(avail_event);
};

/**
 * @param {number} table_address The physical address of the start of the desc table.
 * @param {number} i
 */
VirtQueue.prototype.get_descriptor = function(table_address, i)
{
    const addr_low = this.cpu.read32_physical(table_address + i * VIRTQ_DESC_ENTRYSIZE);
    const addr_high = this.cpu.read32_physical(table_address + i * VIRTQ_DESC_ENTRYSIZE + 4);
    return {
        addr_low,
        addr_high,
        address: addr_low + addr_high * 0x100000000,
        len: this.cpu.read32_physical(table_address + i * VIRTQ_DESC_ENTRYSIZE + 8),
        flags: this.cpu.read16_physical(table_address + i * VIRTQ_DESC_ENTRYSIZE + 12),
        next: this.cpu.read16_physical(table_address + i * VIRTQ_DESC_ENTRYSIZE + 14),
    };
};

// Avail ring fields

VirtQueue.prototype.avail_get_flags = function()
{
    return this.cpu.read16_physical(this.avail_addr);
};

VirtQueue.prototype.avail_get_idx = function()
{
    return this.cpu.read16_physical(this.avail_addr + 2);
};

VirtQueue.prototype.avail_get_entry = function(i)
{
    return this.cpu.read16_physical(this.avail_addr + 4 + VIRTQ_AVAIL_ENTRYSIZE * (i & this.mask));
};

VirtQueue.prototype.avail_get_used_event = function()
{
    return this.cpu.read16_physical(this.avail_addr + 4 + VIRTQ_AVAIL_ENTRYSIZE * this.size);
};

// Used ring fields

VirtQueue.prototype.used_get_flags = function()
{
    return this.cpu.read16_physical(this.used_addr);
};

VirtQueue.prototype.used_set_flags = function(value)
{
    this.cpu.write16_physical(this.used_addr, value);
};

VirtQueue.prototype.used_get_idx = function()
{
    return this.cpu.read16_physical(this.used_addr + 2);
};

VirtQueue.prototype.used_set_idx = function(value)
{
    this.cpu.write16_physical(this.used_addr + 2, value);
};

VirtQueue.prototype.used_set_entry = function(i, desc_idx, length_written)
{
    this.cpu.write32_physical(this.used_addr + 4 + VIRTQ_USED_ENTRYSIZE * i, desc_idx);
    this.cpu.write32_physical(this.used_addr + 8 + VIRTQ_USED_ENTRYSIZE * i, length_written);
};

VirtQueue.prototype.used_set_avail_event = function(value)
{
    this.cpu.write16_physical(this.used_addr + 4 + VIRTQ_USED_ENTRYSIZE * this.size, value);
};

/**
 * Traverses through descriptor chain starting at head_id.
 * Provides means to read/write to buffers represented by the descriptors.
 * @constructor
 * @param {VirtQueue} virtqueue
 * @param {number} head_idx
 */
export function VirtQueueBufferChain(virtqueue, head_idx)
{
    /** @const @type {CPU} */
    this.cpu = virtqueue.cpu;

    /** @const @type {VirtIO} */
    this.virtio = virtqueue.virtio;

    this.head_idx = head_idx;

    this.read_buffers = [];
    // Pointers for sequential consumption via get_next_blob.
    this.read_buffer_idx = 0;
    this.read_buffer_offset = 0;
    this.length_readable = 0;

    this.write_buffers = [];
    // Pointers for sequential write via set_next_blob.
    this.write_buffer_idx = 0;
    this.write_buffer_offset = 0;
    this.length_written = 0;
    this.length_writable = 0;
    this.valid = false;
    /** (see VirtIO.plug_generation) */
    this.plug_generation = virtqueue.virtio.plug_generation;

    try
    {
        this.collect_buffers(virtqueue);
        this.valid = true;
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.read_buffers.length = 0;
        this.write_buffers.length = 0;
        this.length_readable = this.length_writable = 0;
        this.virtio.needs_reset();
    }
}

VirtQueueBufferChain.prototype.collect_buffers = function(virtqueue)
{
    // Traverse chain to discover buffers.
    // - There shouldn't be an excessive amount of descriptor elements.
    let table_address = virtqueue.desc_addr;
    let desc_idx = this.head_idx;
    let chain_length = 0;
    let chain_max = virtqueue.size;
    let writable_region = false;
    let indirect = false;
    const has_indirect_feature = this.virtio.is_feature_negotiated(VIRTIO_F_RING_INDIRECT_DESC);
    dbg_log("<<< Descriptor chain start", LOG_VIRTIO);
    do
    {
        if(desc_idx >= chain_max || ++chain_length > chain_max)
        {
            throw new RangeError("Invalid VirtIO descriptor chain");
        }
        const desc = virtqueue.get_descriptor(table_address, desc_idx);
        this.cpu.validate_physical_range(desc.address, desc.len);

        dbg_log("descriptor: idx=" + desc_idx + " addr=" + h(desc.addr_high, 8) + ":" + h(desc.addr_low, 8) +
            " len=" + h(desc.len, 8) + " flags=" + h(desc.flags, 4) + " next=" + h(desc.next, 4), LOG_VIRTIO);

        if(desc.flags & VIRTQ_DESC_F_INDIRECT)
        {
            if(!has_indirect_feature || indirect || desc.flags & VIRTQ_DESC_F_NEXT ||
                desc.len === 0 || desc.len % VIRTQ_DESC_ENTRYSIZE || desc.len / VIRTQ_DESC_ENTRYSIZE > 65536)
            {
                throw new RangeError("Invalid VirtIO indirect descriptor");
            }

            // Carry on using indirect table, starting at first entry.
            indirect = true;
            table_address = desc.address;
            desc_idx = 0;
            chain_length = 0;
            chain_max = desc.len / VIRTQ_DESC_ENTRYSIZE;
            dbg_log("start indirect", LOG_VIRTIO);
            continue;
        }

        if(desc.flags & VIRTQ_DESC_F_WRITE)
        {
            writable_region = true;
            this.write_buffers.push(desc);
            this.length_writable += desc.len;
        }
        else
        {
            if(writable_region)
            {
                throw new RangeError("VirtIO readable buffer follows writable buffer");
            }
            this.read_buffers.push(desc);
            this.length_readable += desc.len;
        }

        if(desc.flags & VIRTQ_DESC_F_NEXT)
        {
            desc_idx = desc.next;
        }
        else
        {
            break;
        }
    }
    while(true);
    dbg_log("Descriptor chain end >>>", LOG_VIRTIO);
};

/**
 * Reads the next blob of memory represented by the buffer chain into dest_buffer.
 * @param {Uint8Array} dest_buffer
 * @return {number} Number of bytes successfully read.
 */
VirtQueueBufferChain.prototype.get_next_blob = function(dest_buffer)
{
    let dest_offset = 0;
    let remaining = dest_buffer.length;

    while(remaining)
    {
        if(this.read_buffer_idx === this.read_buffers.length)
        {
            dbg_log("Device<" + this.virtio.name + "> Read more than device-readable buffers has", LOG_VIRTIO);
            break;
        }

        const buf = this.read_buffers[this.read_buffer_idx];
        const read_address = buf.address + this.read_buffer_offset;
        let read_length = buf.len - this.read_buffer_offset;

        if(read_length > remaining)
        {
            read_length = remaining;
            this.read_buffer_offset += remaining;
        }
        else
        {
            this.read_buffer_idx++;
            this.read_buffer_offset = 0;
        }

        dest_buffer.set(this.cpu.read_blob_physical(read_address, read_length), dest_offset);

        dest_offset += read_length;
        remaining -= read_length;
    }

    return dest_offset;
};

/**
 * Appends contents of src_buffer into the memory represented by the buffer chain.
 * @param {Uint8Array} src_buffer
 * @return {number} Number of bytes successfully written.
 */
VirtQueueBufferChain.prototype.set_next_blob = function(src_buffer)
{
    if(this.plug_generation !== this.virtio.plug_generation)
    {
        // (the function left the bus since: its buffers are not its own anymore)
        return 0;
    }
    let src_offset = 0;
    let remaining = src_buffer.length;

    while(remaining)
    {
        if(this.write_buffer_idx === this.write_buffers.length)
        {
            dbg_log("Device<" + this.virtio.name + "> Write more than device-writable capacity", LOG_VIRTIO);
            break;
        }

        const buf = this.write_buffers[this.write_buffer_idx];
        const write_address = buf.address + this.write_buffer_offset;
        let write_length = buf.len - this.write_buffer_offset;

        if(write_length > remaining)
        {
            write_length = remaining;
            this.write_buffer_offset += remaining;
        }
        else
        {
            this.write_buffer_idx++;
            this.write_buffer_offset = 0;
        }

        const src_end = src_offset + write_length;
        this.cpu.write_blob_physical(src_buffer.subarray(src_offset, src_end), write_address);

        src_offset += write_length;
        remaining -= write_length;
    }

    this.length_written += src_offset;
    return src_offset;
};
                                                                                                                                                                                                                                                                                   source/v64/src/virtio_balloon.js                                                                    0000644 0000000 0000000 00000016767 00000000000 014054  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-2900003

import { LOG_PCI } from "./const.js";
import { dbg_log } from "./log.js";
import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import * as marshall from "../lib/marshall.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

const VIRTIO_BALLOON_F_MUST_TELL_HOST = 0;
const VIRTIO_BALLOON_F_STATS_VQ = 1;
const VIRTIO_BALLOON_F_DEFLATE_ON_OOM = 2;
const VIRTIO_BALLOON_F_FREE_PAGE_HINT = 3;

const STAT_NAMES = [
    "SWAP_IN",
    "SWAP_OUT",
    "MAJFLT",
    "MINFLT",
    "MEMFREE",
    "MEMTOT",
    "AVAIL",
    "CACHES",
    "HTLB_PGALLOC",
    "HTLB_PGFAIL",
];

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 * @param {number=} pci_id where the machine puts it (behind a root port), or
 *     its usual slot
 */
export function VirtioBalloon(cpu, bus, pci_id)
{
    /** @const @type {BusConnector} */
    this.bus = bus;
    this.num_pages = 0;
    this.actual = 0;
    this.fp_cmd = 0;
    this.zeroed = 0;

    const queues = [
        {size_supported: 32, notify_offset: 0},
        {size_supported: 32, notify_offset: 0},
        {size_supported: 2, notify_offset: 1},
        {size_supported: 64, notify_offset: 2},
    ];

    //setInterval(() => this.GetStats(console.log.bind(console, "STATS")), 10000);

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-balloon",
        pci_id: pci_id === undefined ? 0x0B << 3 : pci_id,
        device_id: 0x1045,
        subsystem_device_id: 5,
        common:
        {
            initial_port: 0xD800,
            queues: queues,
            features:
            [
                VIRTIO_BALLOON_F_STATS_VQ,
                VIRTIO_BALLOON_F_FREE_PAGE_HINT,
                VIRTIO_F_VERSION_1,
            ],
            on_driver_ok: () => {
                dbg_log("Balloon setup", LOG_PCI);
            },
        },
        notification:
        {
            initial_port: 0xD900,
            single_handler: false,
            handlers:
            [
                (queue_id) =>
                {
                    const queue = this.virtio.queues[queue_id];
                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);
                        this.virtio.queues[queue_id].push_reply(bufchain);
                        let n = buffer.byteLength / 4;
                        this.actual += (queue_id === 0 ? n : -n);
                        //console.log(queue_id === 0 ? "Inflate" : "Deflate", this.num_pages, this.actual, bufchain.read_buffers);
                    }
                    this.virtio.queues[queue_id].flush_replies();
                },
                (queue_id) =>
                {
                    const queue = this.virtio.queues[queue_id];
                    if(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);
                        let result = {};
                        for(let i = 0; i < bufchain.length_readable; i += 10) {
                            let [cat, value] = marshall.Unmarshall(["h", "d"], buffer, { offset : i });
                            result[STAT_NAMES[cat]] = value;
                        }
                        this.virtio.queues[queue_id].push_reply(bufchain);
                        if(this.stats_cb) this.stats_cb(result);
                    }
                },
                (queue_id) =>
                {
                    const queue = this.virtio.queues[queue_id];
                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        if(bufchain.length_readable > 0) {
                            const buffer = new Uint8Array(bufchain.length_readable);
                            bufchain.get_next_blob(buffer);
                            let [cmd] = marshall.Unmarshall(["w"], buffer, { offset : 0 });
                            if(cmd === 0) {
                                if(this.free_cb) this.free_cb(this.zeroed);
                                if(this.fp_cmd > 1) this.fp_cmd = 1; // Signal done
                                this.virtio.notify_config_changes();
                            }
                        }
                        if(bufchain.length_writable > 0) {
                            // console.log("Free pages hinted", bufchain.read_buffers, bufchain.write_buffers);
                            for(let i = 0; i < bufchain.write_buffers.length; ++i) {
                                let b = bufchain.write_buffers[i];
                                const zeros = new Uint8Array(Math.min(b.len, 65536));
                                for(let done = 0; done < b.len; done += zeros.length) {
                                    this.virtio.cpu.write_blob_physical(zeros.subarray(0, Math.min(zeros.length, b.len - done)), b.address + done);
                                }
                                this.zeroed += b.len;
                            }
                        }
                        this.virtio.queues[queue_id].push_reply(bufchain);
                    }
                    this.virtio.queues[queue_id].flush_replies();
                },
            ],
        },
        isr_status:
        {
            initial_port: 0xD700,
        },
        device_specific:
        {
            initial_port: 0xD600,
            struct:
            [
                {
                    bytes: 4,
                    name: "num_pages",
                    read: () => this.num_pages,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 4,
                    name: "actual",
                    read: () => {
                        return this.actual;
                    },
                    write: data => { /* read only */ },
                },
                {
                    bytes: 4,
                    name: "free_page_hint_cmd_id",
                    read: () => this.fp_cmd,
                    write: data => { /* read only */ },
                }
           ]
        },
    });
}

VirtioBalloon.prototype.Inflate = function(amount) {
    this.num_pages += amount;
    this.virtio.notify_config_changes();
};

VirtioBalloon.prototype.Deflate = function(amount) {
    this.num_pages -= amount;
    this.virtio.notify_config_changes();
};

VirtioBalloon.prototype.Cleanup = function(cb) {
    this.fp_cmd = 2;
    this.free_cb = cb;
    this.zeroed = 0;
    this.virtio.notify_config_changes();
};


VirtioBalloon.prototype.get_state = function()
{
    const state = [];
    state[0] = this.virtio;
    state[1] = this.num_pages;
    state[2] = this.actual;
    return state;
};

VirtioBalloon.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    this.num_pages = state[1];
    this.actual = state[2];
};

VirtioBalloon.prototype.GetStats = function(data)
{
    this.stats_cb = data;
    const queue = this.virtio.queues[2];
    while(queue.has_request())
    {
        const bufchain = queue.pop_request();
        this.virtio.queues[2].push_reply(bufchain);
    }
    this.virtio.queues[2].flush_replies();
};

VirtioBalloon.prototype.Reset = function() {

};
         source/v64/src/virtio_blk.js                                                                        0000644 0000000 0000000 00000022052 00000000000 013156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-blk (virtio 1.2 section 5.2; docs/arm64-virt-android16-plan.md
// P5.4) as a built-in device of the virt machine: reads, writes, FLUSH,
// read-only disks, the capacity, SEG_MAX and BLK_SIZE, and GET_ID (the
// disk's `id`, e.g. the probe disk's "a64probe", which Linux shows as
// /dev/disk/by-id/virtio-<id>). The image is behind a BlockBackend: writes
// stay in its in-memory overlay for the session. The image may be in a
// container format (src/image/, docs/disk-image-formats-plan.md): a read or
// write the image fails ends with VIRTIO_BLK_S_IOERR, and a snapshot's
// changes are restored only onto the same image. BLK_SIZE is the image's
// logical sector size (512, or 4096: logical_sector_size); the requests and
// the capacity still count 512-byte sectors, as the specification has them,
// and, as in QEMU, a read or write must cover whole logical sectors (IOERR
// otherwise).

import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import { BlockBackend } from "./block_backend.js";
import { check_disk_state, restore_disk_state } from "./disk_writeback.js";
import { dbg_assert } from "./log.js";

// feature bits
const VIRTIO_BLK_F_SEG_MAX = 2;
const VIRTIO_BLK_F_RO = 5;
const VIRTIO_BLK_F_BLK_SIZE = 6;
const VIRTIO_BLK_F_FLUSH = 9;

// request types
const VIRTIO_BLK_T_IN = 0;
const VIRTIO_BLK_T_OUT = 1;
const VIRTIO_BLK_T_FLUSH = 4;
const VIRTIO_BLK_T_GET_ID = 8;

// request status
const VIRTIO_BLK_S_OK = 0;
const VIRTIO_BLK_S_IOERR = 1;
const VIRTIO_BLK_S_UNSUPP = 2;

const SECTOR = 512;
const QUEUE_SIZE = 256;
const ID_BYTES = 20;

/**
 * @constructor
 * @param {?} cpu
 * @param {?} buffer the image (src/buffer.js)
 * @param {{id: (string|undefined), readonly: (boolean|undefined), name: (string|undefined)}} options
 *   name: the disk's (hda, hdb, virtio_disk<n>): export_disk_image, errors
 * @param {?} transport the device's transport (src/virtio_mmio.js), or null: on the PCIe host at `pci_id`
 * @param {number=} pci_id
 */
export function VirtioBlk(cpu, buffer, options, transport, pci_id)
{
    dbg_assert(transport || pci_id !== undefined && cpu.devices.pci.generic, "virtio-blk: on the virt machine's transports only");
    this.cpu = cpu;
    this.name = options.name || "virtio-blk";
    this.backend = new BlockBackend(cpu, buffer);
    this.readonly = !!options.readonly;
    this.id = new Uint8Array(ID_BYTES);
    this.id.set(new TextEncoder().encode(options.id || "").subarray(0, ID_BYTES));
    this.sectors = Math.floor(buffer.byteLength / SECTOR);
    /** the disk's logical sectors, in bytes (blk_size) */
    this.block_size = buffer.logical_sector_size || SECTOR;
    /**
     * The image's SHA-256 as it was loaded (P5.9: a snapshot records it, a
     * restore checks it), once computed; images held in memory only
     * @type {string}
     */
    this.image_sha256 = "";
    if(buffer.buffer instanceof ArrayBuffer && globalThis.crypto?.subtle)
    {
        globalThis.crypto.subtle.digest("SHA-256", buffer.buffer).then(digest =>
        {
            this.image_sha256 = Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, "0")).join("");
        }, () => {});
    }

    const features = [VIRTIO_BLK_F_SEG_MAX, VIRTIO_BLK_F_BLK_SIZE, VIRTIO_BLK_F_FLUSH, VIRTIO_F_VERSION_1];
    if(this.readonly) features.push(VIRTIO_BLK_F_RO);
    const constant = (bytes, name, value) => ({ bytes, name, read: () => value, write: () => {} });

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-blk",
        device_id: 0x1042,
        subsystem_device_id: 2,
        common:
        {
            queues: [{ size_supported: QUEUE_SIZE, notify_offset: 0 }],
            features,
            on_driver_ok: () => {},
        },
        notification:
        {
            single_handler: true,
            handlers: [queue_id => this.process(this.virtio.queues[queue_id])],
        },
        isr_status: {},
        device_specific:
        {
            offset: 0,
            struct:
            [
                // capacity, in 512-byte sectors (a u64: the driver reads it as two words)
                constant(4, "capacity (low dword)", this.sectors >>> 0),
                constant(4, "capacity (high dword)", Math.floor(this.sectors / 0x100000000)),
                constant(4, "size_max", 0),
                constant(4, "seg_max", QUEUE_SIZE - 2),
                constant(2, "cylinders", 0),
                constant(1, "heads", 0),
                constant(1, "sectors", 0),
                constant(4, "blk_size", this.block_size),
            ],
        },
        on_reset: () => this.backend.reset(),
        transport: transport || undefined,
        pci_id,
    });
}

/**
 * The requests the driver queued
 * @param {?} queue
 */
VirtioBlk.prototype.process = function(queue)
{
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const header = new Uint8Array(16);
        chain.get_next_blob(header);
        const view = new DataView(header.buffer);
        const type = view.getUint32(0, true);
        const sector = view.getUint32(8, true) + view.getUint32(12, true) * 0x100000000;
        // (the status byte is the last writable one)
        const readable = chain.length_readable - 16;
        const writable = chain.length_writable - 1;
        const done = status =>
        {
            // (a read that failed, or a short GET_ID: the status goes after
            // the data area all the same, which reads as zeroes)
            if(chain.length_written < writable) chain.set_next_blob(new Uint8Array(writable - chain.length_written));
            chain.set_next_blob(new Uint8Array([status]));
            queue.push_reply(chain);
            queue.flush_replies();
        };
        // (QEMU's virtio_blk_sect_range_ok: whole logical sectors, within the disk)
        const in_range = length => sector * SECTOR + length <= this.sectors * SECTOR &&
            sector * SECTOR % this.block_size === 0 && length % this.block_size === 0;
        switch(type)
        {
            case VIRTIO_BLK_T_IN:
                if(writable < 0 || !in_range(writable)) { done(VIRTIO_BLK_S_IOERR); break; }
                if(writable === 0) { done(VIRTIO_BLK_S_OK); break; }
                this.backend.read(sector * SECTOR, writable, data =>
                {
                    chain.set_next_blob(data);
                    done(VIRTIO_BLK_S_OK);
                }, () => done(VIRTIO_BLK_S_IOERR));
                break;
            case VIRTIO_BLK_T_OUT:
            {
                if(this.readonly || !in_range(readable)) { done(VIRTIO_BLK_S_IOERR); break; }
                const data = new Uint8Array(readable);
                chain.get_next_blob(data);
                this.backend.write(sector * SECTOR, data, () => done(VIRTIO_BLK_S_OK), () => done(VIRTIO_BLK_S_IOERR));
                break;
            }
            case VIRTIO_BLK_T_FLUSH:
                this.backend.when_writes_done(() => done(VIRTIO_BLK_S_OK), () => done(VIRTIO_BLK_S_IOERR));
                break;
            case VIRTIO_BLK_T_GET_ID:
                chain.set_next_blob(this.id.subarray(0, Math.max(0, Math.min(ID_BYTES, writable))));
                done(VIRTIO_BLK_S_OK);
                break;
            default:
                done(VIRTIO_BLK_S_UNSUPP);
        }
    }
};

VirtioBlk.prototype.reset = function()
{
    this.virtio.reset();
};

/**
 * (P5.9) the device; a writable disk's contents as the controllers' do
 * (src/ide.js: the buffer's own state, all of it or the blocks written); a
 * read-only one's only the image's size and SHA-256, checked on restore
 */
VirtioBlk.prototype.get_state = function()
{
    return [this.virtio, this.readonly ? null : this.backend.buffer, this.backend.byte_length, this.image_sha256, this.block_size];
};

/**
 * Whether a snapshot's state of this disk can be restored, checked before
 * anything is (A64CPU.validate_state): the same size, the same image (an
 * image in memory by its SHA-256; a disk image in a container format by
 * its identity, docs/disk-image-formats-plan.md P1)
 * @param {*} state
 */
VirtioBlk.prototype.check_state = function(state)
{
    if(state[2] !== undefined && state[2] !== this.backend.byte_length)
    {
        throw new Error("The snapshot's virtio-blk disk has " + state[2] + " bytes, this one " + this.backend.byte_length);
    }
    if((state[4] || SECTOR) !== this.block_size)
    {
        throw new Error("The snapshot's virtio-blk disk has " + (state[4] || SECTOR) + "-byte sectors, this one " + this.block_size);
    }
    if(state[3] && this.image_sha256 && state[3] !== this.image_sha256)
    {
        throw new Error("The snapshot's virtio-blk disk is another image (SHA-256 " + state[3] + ", this one " + this.image_sha256 + ")");
    }
    if(this.readonly) return;
    // (and a disk written back: src/disk_writeback.js)
    check_disk_state(this.name, this.backend.buffer, state[1]);
};

VirtioBlk.prototype.set_state = function(state)
{
    this.check_state(state);
    // (requests in flight belong to the state left behind)
    this.backend.reset();
    this.virtio.set_state(state[0]);
    if(state[1] && !this.readonly) restore_disk_state(this.backend.buffer, state[1]);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/src/virtio_console.js                                                                    0000644 0000000 0000000 00000025463 00000000000 014061  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { dbg_assert } from "./log.js";
import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import * as marshall from "../lib/marshall.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

// https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-2900003

const VIRTIO_CONSOLE_DEVICE_READY     = 0;
const VIRTIO_CONSOLE_DEVICE_ADD       = 1;
const VIRTIO_CONSOLE_DEVICE_REMOVE    = 2;
const VIRTIO_CONSOLE_PORT_READY       = 3;
const VIRTIO_CONSOLE_CONSOLE_PORT     = 4;
const VIRTIO_CONSOLE_RESIZE           = 5;
const VIRTIO_CONSOLE_PORT_OPEN        = 6;
const VIRTIO_CONSOLE_PORT_NAME        = 7;

const VIRTIO_CONSOLE_F_SIZE           = 0;
const VIRTIO_CONSOLE_F_MULTIPORT      = 1;
const VIRTIO_CONSOLE_F_EMERG_WRITE    = 2;

/**
 * @constructor
 *
 * @param {CPU} cpu
 * @param {BusConnector} bus
 * @param {number=} pci_id where the machine puts it (behind a root port), or
 *     its usual slot
 * @param {?=} transport another transport than virtio-pci (the virt
 *     machine's virtio-mmio, src/virtio_mmio.js)
 * @param {boolean=} generic_ports ports 1-3 as generic ports (the virt machine)
 * @param {number=} port_count the number of ports, 4 by default (the virt
 *     machine's Android guests: 18 consoles, hvc0-hvc17, as Cuttlefish's)
 */
export function VirtioConsole(cpu, bus, pci_id, transport, generic_ports, port_count)
{
    /** @const @type {BusConnector} */
    this.bus = bus;
    /** Ports 1-3 as generic ports named org.v86.port<N> (/dev/vport<D>p<N>,
     * QEMU's virtserialport: the virt machine's host service channels), else
     * consoles (hvc1-hvc3) */
    this.generic_ports = !!generic_ports;
    this.rows = 25;
    this.cols = 80;
    this.ports = port_count || 4;
    /** control messages waiting for the guest's buffers (many ports send
     * more of them at once than the control receive queue holds) */
    this.control_pending = [];

    const queues = [
        {
            size_supported: 16,
            notify_offset: 0,
        },
        {
            size_supported: 16,
            notify_offset: 1,
        },
        {
            size_supported: 16,
            notify_offset: 2,
        },
        {
            size_supported: 16,
            notify_offset: 3,
        },
    ];

    for(let i = 1; i < this.ports; ++i)
    {
        queues.push({size_supported: 16, notify_offset: 0});
        queues.push({size_supported: 8, notify_offset: 1});
    }

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-console",
        transport,
        pci_id: pci_id === undefined ? 0x0C << 3 : pci_id,
        device_id: 0x1043,
        subsystem_device_id: 3,
        common:
        {
            initial_port: 0xB800,
            queues: queues,
            features:
            [
                VIRTIO_CONSOLE_F_SIZE,
                VIRTIO_CONSOLE_F_MULTIPORT,
                VIRTIO_F_VERSION_1,
            ],
            on_driver_ok: () => {},
        },
        notification:
        {
            initial_port: 0xB900,
            single_handler: false,
            handlers:
            [
                (queue_id) =>
                {

                },
                (queue_id) =>
                {
                    const queue = this.virtio.queues[queue_id];
                    const port = queue_id > 3 ? (queue_id-3 >> 1) : 0;
                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);
                        this.bus.send("virtio-console" + port + "-output-bytes", buffer);
                        this.Ack(queue_id, bufchain);
                    }
                },
                (queue_id) =>
                {
                    if(queue_id !== 2)
                    {
                        dbg_assert(false, "VirtioConsole Notified for wrong queue: " + queue_id +
                            " (expected queue_id of 2)");
                        return;
                    }
                    // (the guest's new control buffers)
                    this.FlushControl();
                },
                (queue_id) =>
                {
                    if(queue_id !== 3)
                    {
                        dbg_assert(false, "VirtioConsole Notified for wrong queue: " + queue_id +
                            " (expected queue_id of 3)");
                        return;
                    }
                    const queue = this.virtio.queues[queue_id];

                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);


                        const parts = marshall.Unmarshall(["w", "h", "h"], buffer, { offset : 0 });
                        const port = parts[0];
                        const event = parts[1];
                        const value = parts[2];


                        this.Ack(queue_id, bufchain);

                        switch(event) {
                            case VIRTIO_CONSOLE_DEVICE_READY:
                                for(let i = 0; i < this.ports; ++i) {
                                    this.SendEvent(i, VIRTIO_CONSOLE_DEVICE_ADD, 0);
                                }
                                break;
                            case VIRTIO_CONSOLE_PORT_READY:
                                // (the request was acknowledged above: a second
                                // acknowledgement of it breaks the guest's queue)
                                if(port === 0 || !this.generic_ports) this.SendEvent(port, VIRTIO_CONSOLE_CONSOLE_PORT, 1);
                                this.SendName(port, port !== 0 && this.generic_ports ? "org.v86.port" + port : "virtio-" + port);
                                this.SendEvent(port, VIRTIO_CONSOLE_PORT_OPEN, 1);

                                break;
                            case VIRTIO_CONSOLE_PORT_OPEN:
                                if(port === 0) {
                                    this.SendWindowSize(port);
                                }
                                break;
                            default:
                                dbg_assert(false," VirtioConsole received unknown event: " + event[1]);
                                return;

                        }
                    }
                },
            ],
        },
        isr_status:
        {
            initial_port: 0xB700,
        },
        device_specific:
        {
            initial_port: 0xB600,
            struct:
            [
                {
                    bytes: 2,
                    name: "cols",
                    read: () => this.cols,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 2,
                    name: "rows",
                    read: () => this.rows,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 4,
                    name: "max_nr_ports",
                    read: () => this.ports,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 4,
                    name: "emerg_wr",
                    read: () => 0,
                    write: data => {
                        dbg_assert(false, "Emergency write!");
                    },
                },
           ]
        },
    });

    for(let port = 0; port < this.ports; ++port) {
        const queue_id = port === 0 ? 0 : port * 2 + 2;
        this.bus.register("virtio-console" + port + "-input-bytes", function(data) {
            const queue = this.virtio.queues[queue_id];
            if(queue.has_request()) {
                const bufchain = queue.pop_request();
                this.Send(queue_id, bufchain, new Uint8Array(data));
            } else {
                //TODO: Buffer
            }
        }, this);

        this.bus.register("virtio-console" + port + "-resize", function(size) {
            if(port === 0) {
                this.cols = size[0];
                this.rows = size[1];
            }

            if(this.virtio.queues[2].is_configured()) {
                this.SendWindowSize(port, size[0], size[1]);
            }
        }, this);
    }
}

VirtioConsole.prototype.SendWindowSize = function(port, cols = undefined, rows = undefined)
{
    rows = rows || this.rows;
    cols = cols || this.cols;
    const buf = new Uint8Array(12);
    marshall.Marshall(["w", "h", "h", "h", "h"], [port, VIRTIO_CONSOLE_RESIZE, 0, rows, cols], buf, 0);
    this.SendControl(buf);
};

VirtioConsole.prototype.SendName = function(port, name)
{
    const namex = new TextEncoder().encode(name);
    const buf = new Uint8Array(8 + namex.length + 1);
    marshall.Marshall(["w", "h", "h"], [port, VIRTIO_CONSOLE_PORT_NAME, 1], buf, 0);
    for( let i = 0; i < namex.length; ++i ) {
        buf[i+8] = namex[i];
    }
    buf[8 + namex.length] = 0;
    this.SendControl(buf);
};


VirtioConsole.prototype.get_state = function()
{
    const state = [];

    state[0] = this.virtio;
    state[1] = this.rows;
    state[2] = this.cols;
    state[3] = this.ports;

    return state;
};

VirtioConsole.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    this.rows = state[1];
    this.cols = state[2];
    this.ports = state[3];
};

VirtioConsole.prototype.reset = function() {
    this.control_pending = [];
    this.virtio.reset();
};

VirtioConsole.prototype.SendEvent = function(port, event, value)
{
    const buf = new Uint8Array(8);
    marshall.Marshall(["w","h","h"], [port, event, value], buf, 0);
    this.SendControl(buf);
};

/** a control message to the guest, now or once it has a buffer for it */
VirtioConsole.prototype.SendControl = function(blob)
{
    this.control_pending.push(blob);
    this.FlushControl();
};

VirtioConsole.prototype.FlushControl = function()
{
    const queue = this.virtio.queues[2];
    let sent = false;
    while(this.control_pending.length && queue.has_request())
    {
        const bufchain = queue.pop_request();
        bufchain.set_next_blob(this.control_pending.shift());
        queue.push_reply(bufchain);
        sent = true;
    }
    if(sent) queue.flush_replies();
};

VirtioConsole.prototype.Send = function (queue_id, bufchain, blob)
{
    bufchain.set_next_blob(blob);
    this.virtio.queues[queue_id].push_reply(bufchain);
    this.virtio.queues[queue_id].flush_replies();
};

VirtioConsole.prototype.Ack = function (queue_id, bufchain)
{
    bufchain.set_next_blob(new Uint8Array(0));
    this.virtio.queues[queue_id].push_reply(bufchain);
    this.virtio.queues[queue_id].flush_replies();
};
                                                                                                                                                                                                             source/v64/src/virtio_devices.js                                                                    0000644 0000000 0000000 00000063143 00000000000 014036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Virtio devices supplied by the embedder (the virtio_devices option). v86 owns
// the transport: the PCI function, its capabilities, the rings, the interrupt
// and the transport's part of a snapshot. The descriptor owns what the device
// does. Descriptors come from code that Closure does not compile, so every
// field and every method of the handle uses a quoted name.
// See docs/graphics-proxy-plugin-plan.md.

import { dbg_log } from "./log.js";
import { LOG_PCI } from "./const.js";
import {
    VirtIO, VIRTIO_F_VERSION_1, VIRTIO_STATUS_DRIVER_OK,
    VIRTIO_STATUS_DEVICE_NEEDS_RESET, VIRTIO_STATUS_FAILED, VirtQueueBufferChain,
} from "./virtio.js";

// For Types Only
import { CPU } from "./cpu.js";

// state[92] is ["virtio_devices", 1, <one entry per device>]
const STATE_TAG = "virtio_devices";
const STATE_VERSION = 1;

// Slots and I/O windows handed out when a descriptor asks for none
const FIRST_FREE_SLOT = 0x10;
const LAST_SLOT = 0x1F;
// One 256-byte window each for the common configuration, the notification
// register, the ISR status and the device configuration
const IO_WINDOW_BYTES = 0x400;
const IO_POOL_START = 0xE000;
const DEVICE_CONFIG_MAX_BYTES = 0x100;


/**
 * @param {CPU} cpu
 * @param {*} descriptors
 * @return {!Array<VirtioDevice>}
 */
export function create_virtio_devices(cpu, descriptors)
{
    if(!Array.isArray(descriptors))
    {
        throw new TypeError("virtio_devices must be an array of device descriptors");
    }

    const names = new Set();
    const slots = new Set();
    const windows = new Set();
    const root_ports = new Set();

    // Fixed slots and windows first, so that allocation steps around them
    for(const descriptor of descriptors)
    {
        check_descriptor(descriptor, names);
        const name = descriptor["name"];
        const slot = descriptor["pci_slot"];
        const io_base = descriptor["io_base"];
        const root_port = descriptor["pcie_root_port"];
        if(root_port !== undefined)
        {
            // behind a PCI Express root port (machine_type "q35", pcie_root_ports)
            const count = cpu.devices.pcie_root_ports ? cpu.devices.pcie_root_ports.length : 0;
            if(root_port >= count)
            {
                throw new Error("virtio_devices: \"" + name + "\" asks for root port " + root_port +
                    ", the machine has " + count + " (pcie_root_ports)");
            }
            if(root_ports.has(root_port) ||
                cpu.devices.pci.device_spaces[cpu.devices.pcie_root_ports[root_port].pci_secondary_bus << 8] !== undefined)
            {
                throw new Error("virtio_devices: \"" + name + "\" asks for root port " + root_port + ", which is taken");
            }
            root_ports.add(root_port);
        }
        else if(slot !== undefined)
        {
            if(slots.has(slot) || !is_slot_free(cpu, slot))
            {
                throw new Error("virtio_devices: \"" + name + "\" asks for PCI slot 0x" + slot.toString(16) + ", which is taken");
            }
            slots.add(slot);
        }
        if(io_base !== undefined)
        {
            if(windows.has(io_base) || !is_io_window_free(cpu, io_base))
            {
                throw new Error("virtio_devices: \"" + name + "\" asks for I/O ports 0x" + io_base.toString(16) + ", which are taken");
            }
            windows.add(io_base);
        }
    }

    return descriptors.map(descriptor => {
        const root_port = descriptor["pcie_root_port"];
        let slot = descriptor["pci_slot"];
        if(root_port !== undefined)
        {
            // device 0 on the root port's secondary bus
            slot = -1;
        }
        else if(slot === undefined)
        {
            slot = FIRST_FREE_SLOT;
            while(slot <= LAST_SLOT && (slots.has(slot) || !is_slot_free(cpu, slot))) slot++;
            if(slot > LAST_SLOT)
            {
                throw new Error("virtio_devices: no free PCI slot for \"" + descriptor["name"] + "\"");
            }
            slots.add(slot);
        }

        let io_base = descriptor["io_base"];
        if(io_base === undefined)
        {
            io_base = IO_POOL_START;
            while(io_base + IO_WINDOW_BYTES <= 0x10000 && (windows.has(io_base) || !is_io_window_free(cpu, io_base)))
            {
                io_base += IO_WINDOW_BYTES;
            }
            if(io_base + IO_WINDOW_BYTES > 0x10000)
            {
                throw new Error("virtio_devices: no free I/O ports for \"" + descriptor["name"] + "\"");
            }
            windows.add(io_base);
        }

        const pci_id = root_port !== undefined ? cpu.devices.pcie_root_ports[root_port].pci_secondary_bus << 8 : slot << 3;
        dbg_log("virtio device " + descriptor["name"] + " at " + (root_port !== undefined ? "root port " + root_port : "slot 0x" + slot.toString(16)) +
            ", ports 0x" + io_base.toString(16), LOG_PCI);
        return new VirtioDevice(cpu, descriptor, pci_id, io_base);
    });
}

/**
 * A display adapter's virtio function (virtio-vga, in the VGA slot): the
 * descriptor's fields as for virtio_devices, plus "class_code", "revision",
 * the adapter's own memory BARs ("bars": quoted { bar, size, address,
 * prefetchable, on_move }), "capability_bar", the one memory BAR that holds
 * all four capabilities at their windows' offsets (viogpudo maps no I/O
 * BARs), the VGA BIOS as its
 * expansion ROM ("pci_rom_size", "pci_rom_address"), and "qemu_compatible"
 * (see VirtIO.qemu_compatible). Its state belongs to the
 * adapter's snapshot entry (the handle's "transport" and "set_transport").
 * @param {CPU} cpu
 * @param {*} descriptor
 * @param {number} pci_id
 * @param {?=} transport the virt machine's virtio-mmio slot instead of the PCI function
 * @return {!VirtioDevice}
 */
export function create_adapter_virtio_device(cpu, descriptor, pci_id, transport)
{
    check_descriptor(descriptor, new Set());
    const bars = descriptor["bars"] || [];
    if(!Array.isArray(bars) || bars.some(bar => !bar || !Number.isInteger(bar["bar"]) || bar["bar"] < 0 || bar["bar"] > 5 ||
        !Number.isInteger(bar["size"]) || bar["size"] < 16 || (bar["size"] & (bar["size"] - 1))))
    {
        throw new TypeError("virtio device \"" + descriptor["name"] + "\": bars must be { bar, size (a power of two) }");
    }
    // (virtio-gpu's host visible memory: a region of one of those BARs)
    const shared_memory = descriptor["shared_memory"] || [];
    if(!Array.isArray(shared_memory) || shared_memory.some(region => !region ||
        !Number.isInteger(region["id"]) || region["id"] < 0 || region["id"] > 0xFF ||
        !bars.some(bar => bar["bar"] === region["bar"] && (region["offset"] || 0) + region["length"] <= bar["size"])))
    {
        throw new TypeError("virtio device \"" + descriptor["name"] + "\": shared_memory must be { id, bar, offset, length } within one of the bars");
    }
    // (no I/O ports: the windows' offsets in the memory BAR are 0x000, 0x100, 0x200, 0x300)
    return new VirtioDevice(cpu, /** @type {!Object} */ (descriptor), pci_id, 0, {
        class_code: descriptor["class_code"],
        revision: descriptor["revision"],
        bars: bars.map(bar => ({
            bar: bar["bar"],
            size: bar["size"],
            address: bar["address"] || 0,
            prefetchable: !!bar["prefetchable"],
            on_move: bar["on_move"],
        })),
        capability_bar: descriptor["capability_bar"],
        shared_memory: shared_memory.map(region => ({
            id: region["id"],
            bar: region["bar"],
            offset: region["offset"] || 0,
            length: region["length"],
        })),
        rom_size: descriptor["pci_rom_size"],
        rom_address: descriptor["pci_rom_address"],
        qemu_compatible: !!descriptor["qemu_compatible"],
        transport,
    });
}

/**
 * The value of state[92]: nothing when no device is configured, so that
 * snapshots of machines without custom devices do not change
 * @param {Array<VirtioDevice>|undefined} devices
 */
export function get_virtio_devices_state(devices)
{
    if(!devices || !devices.length) return undefined;
    return [STATE_TAG, STATE_VERSION].concat(devices);
}

/**
 * Match the entries of state[92] to the configured devices. Changes nothing,
 * so that CPU.set_state can call it before it restores anything.
 * @param {Array<VirtioDevice>|undefined} devices
 * @param {*} slot
 * @return {!Map<string, !Array>}
 */
export function resolve_virtio_devices_state(devices, slot)
{
    devices = devices || [];
    const entries = new Map();

    if(Array.isArray(slot) && slot[0] === STATE_TAG)
    {
        if(slot[1] !== STATE_VERSION)
        {
            throw new Error("Unsupported virtio devices state version " + slot[1]);
        }
        for(const entry of slot.slice(2))
        {
            entries.set(entry[0], entry);
        }
    }
    else if(slot !== undefined && slot !== null)
    {
        // A slot written before custom devices existed belongs to the
        // device that recognizes it
        for(const device of devices)
        {
            const upgrade_state = device.descriptor["upgrade_state"];
            const upgraded = upgrade_state && upgrade_state(slot);
            if(upgraded)
            {
                entries.set(device.name, [device.name, upgraded[0], upgraded[1], upgraded[2]]);
                break;
            }
        }
        if(!entries.size)
        {
            throw new Error("The snapshot contains device state that no configured virtio device recognizes");
        }
    }

    for(const name of entries.keys())
    {
        if(!devices.some(device => device.name === name))
        {
            throw new Error("The snapshot contains virtio device \"" + name + "\", which is not configured");
        }
    }

    return entries;
}

/**
 * @param {Array<VirtioDevice>|undefined} devices
 * @param {!Map<string, !Array>} entries from resolve_virtio_devices_state
 */
export function set_virtio_devices_state(devices, entries)
{
    for(const device of devices || [])
    {
        const entry = entries.get(device.name);
        if(entry)
        {
            device.set_state(entry);
        }
        else
        {
            // The snapshot is from a machine without this device
            device.reset();
            device.restored_host_state = undefined;
        }
    }
}

/**
 * @param {*} descriptor
 * @param {!Set<string>} names
 */
function check_descriptor(descriptor, names)
{
    if(!descriptor || typeof descriptor !== "object")
    {
        throw new TypeError("virtio_devices: a device descriptor must be an object");
    }

    const name = descriptor["name"];
    if(typeof name !== "string" || !name)
    {
        throw new TypeError("virtio_devices: a device descriptor needs a name");
    }
    if(names.has(name))
    {
        throw new Error("virtio_devices: more than one device is named \"" + name + "\"");
    }
    names.add(name);

    const fail = message => { throw new TypeError("virtio_devices: \"" + name + "\": " + message); };
    const is_u16 = value => Number.isInteger(value) && value >= 0 && value <= 0xFFFF;

    if(!is_u16(descriptor["device_id"])) fail("device_id must be a 16-bit integer");
    if(descriptor["subsystem_device_id"] !== undefined && !is_u16(descriptor["subsystem_device_id"]))
    {
        fail("subsystem_device_id must be a 16-bit integer");
    }

    const slot = descriptor["pci_slot"];
    if(slot !== undefined && !(Number.isInteger(slot) && slot >= 1 && slot <= LAST_SLOT))
    {
        fail("pci_slot must be between 1 and 31");
    }
    const root_port = descriptor["pcie_root_port"];
    if(root_port !== undefined && !(Number.isInteger(root_port) && root_port >= 0))
    {
        fail("pcie_root_port must be the number of a root port (0 and up)");
    }
    if(root_port !== undefined && slot !== undefined)
    {
        fail("pci_slot and pcie_root_port exclude each other");
    }
    const plugged = descriptor["pcie_plugged"];
    if(plugged !== undefined && (typeof plugged !== "boolean" || root_port === undefined))
    {
        fail("pcie_plugged must be a boolean, for a device behind a root port (pcie_root_port)");
    }
    const io_base = descriptor["io_base"];
    if(io_base !== undefined && !(Number.isInteger(io_base) && io_base > 0 && !(io_base & 0xFF) &&
        io_base + IO_WINDOW_BYTES <= 0x10000))
    {
        fail("io_base must be 256-byte aligned and leave room for four 256-byte windows");
    }

    const queues = descriptor["queues"];
    if(!Array.isArray(queues) || !queues.length)
    {
        fail("queues must be a non-empty array");
    }
    for(const queue of queues)
    {
        const size = queue && queue["size"];
        if(!Number.isInteger(size) || size < 1 || size > 32768 || (size & (size - 1)))
        {
            fail("a queue size must be a power of two up to 32768");
        }
    }

    const features = descriptor["features"];
    if(features !== undefined && !(Array.isArray(features) &&
        features.every(bit => Number.isInteger(bit) && bit >= 0 && bit < 128)))
    {
        fail("features must be an array of bit numbers below 128");
    }

    const config = descriptor["config"];
    if(config !== undefined)
    {
        if(!Array.isArray(config)) fail("config must be an array");
        let bytes = 0;
        for(const field of config)
        {
            if(!field || ![1, 2, 4].includes(field["bytes"])) fail("a config field has 1, 2 or 4 bytes");
            if(typeof field["read"] !== "function") fail("a config field needs a read function");
            if(field["write"] !== undefined && typeof field["write"] !== "function") fail("config write must be a function");
            bytes += field["bytes"];
        }
        if(bytes > DEVICE_CONFIG_MAX_BYTES) fail("the device configuration is limited to 256 bytes");
    }

    if(typeof descriptor["notify"] !== "function") fail("notify must be a function");
    for(const hook of ["init", "reset", "busy", "get_state", "set_state", "upgrade_state"])
    {
        if(descriptor[hook] !== undefined && typeof descriptor[hook] !== "function")
        {
            fail(hook + " must be a function");
        }
    }
}

/**
 * @param {CPU} cpu
 * @param {number} slot
 */
function is_slot_free(cpu, slot)
{
    // (the chipset's device numbers, e.g. Q35's 00:1f.*, even before its functions are registered)
    return !cpu.devices.pci.devices[slot << 3] && !cpu.platform.reserved_pci_slots.includes(slot);
}

/**
 * @param {CPU} cpu
 * @param {number} io_base
 */
function is_io_window_free(cpu, io_base)
{
    for(let port = io_base; port < io_base + IO_WINDOW_BYTES; port++)
    {
        if(cpu.io.ports[port].device) return false;
    }
    return true;
}

/**
 * @constructor
 * @param {CPU} cpu
 * @param {!Object} descriptor
 * @param {number} pci_id its function (behind a root port: device 0 of the port's bus)
 * @param {number} io_base
 * @param {{class_code: (number|undefined), revision: (number|undefined), bars: !Array,
 *     capability_bar: (number|undefined), shared_memory: (!Array|undefined),
 *     rom_size: (number|undefined), rom_address: (number|undefined),
 *     qemu_compatible: (boolean|undefined), transport: (?|undefined)}=} transport
 *     a display adapter's layout (create_adapter_virtio_device); its
 *     transport: the virt machine's virtio-mmio instead of the PCI function
 */
function VirtioDevice(cpu, descriptor, pci_id, io_base, transport)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    this.descriptor = descriptor;
    this.name = descriptor["name"];

    // Bumped by resets and restores: requests popped before one must not
    // complete into the new rings
    this.generation = 0;
    this.initialized = false;

    // Set by the embedder before a save, read by it after a restore
    this.host_state = undefined;
    this.restored_host_state = undefined;

    const features = descriptor["features"] || [];
    const config = descriptor["config"] || [];

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-" + this.name,
        pci_id,
        device_id: descriptor["device_id"],
        subsystem_device_id: descriptor["subsystem_device_id"] || 0,
        class_code: transport && transport.class_code,
        revision: transport && transport.revision,
        bars: transport && transport.bars,
        capability_bar: transport && transport.capability_bar,
        shared_memory: transport && transport.shared_memory,
        rom_size: transport && transport.rom_size,
        rom_address: transport && transport.rom_address,
        qemu_compatible: transport && transport.qemu_compatible,
        transport: transport && transport.transport || undefined,
        on_reset: () =>
        {
            this.generation++;
            const reset = this.descriptor["reset"];
            if(this.initialized && reset) reset();
        },
        common:
        {
            initial_port: io_base,
            queues: descriptor["queues"].map(queue => ({ size_supported: queue["size"], notify_offset: 0 })),
            features: features.includes(VIRTIO_F_VERSION_1) ? features : features.concat([VIRTIO_F_VERSION_1]),
            on_driver_ok: () => {},
        },
        notification:
        {
            initial_port: io_base + 0x100,
            single_handler: true,
            handlers: [
                (queue_id) => this.notify(queue_id),
            ],
        },
        isr_status:
        {
            initial_port: io_base + 0x200,
        },
        device_specific: config.length ? {
            initial_port: io_base + 0x300,
            struct: config.map((field, i) => ({
                bytes: field["bytes"],
                name: field["name"] || "config" + i,
                // (port reads are int32, or the field's width)
                read: field["bytes"] === 4 ? () => field["read"]() | 0 :
                    () => field["read"]() & (field["bytes"] === 2 ? 0xFFFF : 0xFF),
                write: data => { field["write"] && field["write"](data); },
            })),
        } : undefined,
    });

    this.handle = this.create_handle();
    this.initialized = true;

    const init = descriptor["init"];
    init && init(this.handle);
}

/**
 * What the descriptor gets to work with
 */
VirtioDevice.prototype.create_handle = function()
{
    return {
        "name": this.name,
        "is_ready": () => this.is_ready(),
        "has_request": queue_id => this.has_request(queue_id),
        "pop_request": queue_id => this.pop_request(queue_id),
        "request_at": (queue_id, head) => this.request_at(queue_id, head),
        "flush": queue_id => this.flush(queue_id),
        "is_ram": (address, length) => this.is_ram(address, length),
        "read_memory": (address, length) => this.read_memory(address, length),
        "write_memory": (bytes, address) => this.write_memory(bytes, address),
        "is_feature_negotiated": bit => this.virtio.is_feature_negotiated(bit),
        "needs_reset": () => this.virtio.needs_reset(),
        "config_changed": () => { if(this.is_ready()) this.virtio.notify_config_changes(); },
        // (a display adapter's function: its transport in the adapter's
        // snapshot entry, and the adapter's resets)
        "transport": () => this.virtio,
        "set_transport": state => { this.generation++; this.virtio.set_state(state); },
        "reset": () => this.reset(),
    };
};

/**
 * The driver has set DRIVER_OK, and neither side has given up
 */
VirtioDevice.prototype.is_ready = function()
{
    const status = this.virtio.device_status;
    return (status & (VIRTIO_STATUS_DRIVER_OK | VIRTIO_STATUS_DEVICE_NEEDS_RESET | VIRTIO_STATUS_FAILED)) ===
        VIRTIO_STATUS_DRIVER_OK;
};

VirtioDevice.prototype.notify = function(queue_id)
{
    if(!this.is_ready() || queue_id >= this.virtio.queues.length) return;
    try
    {
        this.descriptor["notify"](queue_id);
    }
    catch(error)
    {
        // A RangeError is a malformed ring or buffer; anything else is a bug in the device
        if(!(error instanceof RangeError)) console.error("virtio device " + this.name + ":", error);
        this.virtio.needs_reset();
    }
};

VirtioDevice.prototype.get_queue = function(queue_id)
{
    const queue = this.virtio.queues[queue_id];
    if(!queue) throw new Error("virtio device " + this.name + " has no queue " + queue_id);
    return queue;
};

VirtioDevice.prototype.has_request = function(queue_id)
{
    const queue = this.get_queue(queue_id);
    if(!this.is_ready() || !queue.is_configured()) return false;
    // The rings, like every buffer, are DMA: guest RAM, never a device's window
    if(!this.is_ram(queue.desc_addr, queue.size * 16) ||
        !this.is_ram(queue.avail_addr, 6 + queue.size * 2) ||
        !this.is_ram(queue.used_addr, 6 + queue.size * 8))
    {
        this.virtio.needs_reset();
        return false;
    }
    return queue.has_request();
};

/**
 * @return {Object} a request, or null when there is none or the chain is malformed
 * (the driver has been told to reset then)
 */
VirtioDevice.prototype.pop_request = function(queue_id)
{
    const queue = this.get_queue(queue_id);
    if(!this.has_request(queue_id)) return null;

    let chain;
    try
    {
        chain = queue.pop_request();
    }
    catch(error)
    {
        if(!(error instanceof RangeError)) throw error;
        this.virtio.needs_reset();
        return null;
    }
    return this.request(queue, chain);
};

/**
 * A request popped before, again: its chain from its head (a snapshot keeps
 * the heads of the requests a device had not answered yet)
 * @return {Object} null when the chain is malformed
 */
VirtioDevice.prototype.request_at = function(queue_id, head)
{
    const queue = this.get_queue(queue_id);
    if(!this.is_ready() || !queue.is_configured() || !(head >= 0 && head < queue.size)) return null;
    return this.request(queue, new VirtQueueBufferChain(queue, head));
};

/**
 * @param {!Object} queue its VirtQueue
 * @param {!VirtQueueBufferChain} chain
 * @return {Object}
 */
VirtioDevice.prototype.request = function(queue, chain)
{
    if(!chain.valid) return null;
    for(const buffer of chain.read_buffers.concat(chain.write_buffers))
    {
        if(buffer.len && !this.is_ram(buffer.address, buffer.len))
        {
            this.virtio.needs_reset();
            return null;
        }
    }

    const generation = this.generation;
    let completed = false;
    return {
        "head": chain.head_idx,
        "readable": chain.length_readable,
        "writable": chain.length_writable,
        "read": () =>
        {
            const bytes = new Uint8Array(chain.length_readable);
            chain.get_next_blob(bytes);
            return bytes;
        },
        "write": bytes =>
        {
            return generation === this.generation ? chain.set_next_blob(bytes) : 0;
        },
        // Staged until flush
        "complete": () =>
        {
            if(completed || generation !== this.generation) return;
            completed = true;
            queue.push_reply(chain);
        },
    };
};

VirtioDevice.prototype.flush = function(queue_id)
{
    const queue = this.get_queue(queue_id);
    if(queue.is_configured() && queue.num_staged_replies) queue.flush_replies();
};

/**
 * Plain or extended RAM on the physical bus: not a device window, not the
 * legacy VGA/ROM range and not a hole
 * @param {number} address
 * @param {number} length
 */
VirtioDevice.prototype.is_ram = function(address, length)
{
    return this.classify(address, length) !== -2;
};

/**
 * @param {number} address
 * @param {number} length
 * @return {number} the offset of one contiguous plain-RAM backing,
 *     -1 for other RAM, -2 for anything that is not RAM
 */
VirtioDevice.prototype.classify = function(address, length)
{
    // (the machine's DMA facade: docs/arm64-virt-android16-plan.md P1.6)
    return this.cpu.dma_classify(address, length);
};

/**
 * @param {number} address
 * @param {number} length
 * @return {!Uint8Array} a view of guest RAM where one contiguous backing
 *     holds the range, a copy otherwise
 */
VirtioDevice.prototype.read_memory = function(address, length)
{
    const backing = this.classify(address, length);
    if(backing === -2)
    {
        throw new RangeError("virtio device " + this.name + ": 0x" + address.toString(16) +
            " (" + length + " bytes) is not guest RAM");
    }
    return backing >= 0 ? this.cpu.mem8.subarray(backing, backing + length) :
        this.cpu.read_blob_physical(address, length);
};

/**
 * Through the bus, which invalidates compiled code
 * @param {!Uint8Array} bytes
 * @param {number} address
 */
VirtioDevice.prototype.write_memory = function(bytes, address)
{
    // (off the bus: a hot plug slot that is empty or switched off)
    if(!bytes.length || !this.virtio.present()) return;
    if(!this.is_ram(address, bytes.length))
    {
        throw new RangeError("virtio device " + this.name + ": 0x" + address.toString(16) +
            " (" + bytes.length + " bytes) is not guest RAM");
    }
    this.cpu.write_blob_physical(bytes, address);
};

/**
 * What the device still waits for from its host side (its optional busy hook):
 * a snapshot needs none
 */
VirtioDevice.prototype.busy = function()
{
    const busy = this.descriptor["busy"];
    return busy ? busy() : 0;
};

/**
 * A machine reset; also used when a snapshot restores without this device
 */
VirtioDevice.prototype.reset = function()
{
    this.virtio.reset();
};

VirtioDevice.prototype.get_state = function()
{
    const get_state = this.descriptor["get_state"];
    return [this.name, this.virtio, get_state ? get_state() : undefined, this.host_state];
};

/**
 * @param {!Array} entry [name, transport state, device state, host state]
 */
VirtioDevice.prototype.set_state = function(entry)
{
    this.generation++;
    this.virtio.set_state(entry[1]);
    const set_state = this.descriptor["set_state"];
    set_state && set_state(entry[2]);
    this.restored_host_state = entry[3];
};
                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/src/virtio_input.js                                                                      0000644 0000000 0000000 00000042701 00000000000 013550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-input (virtio 1.2 section 5.8; docs/arm64-virt-android16-plan.md
// P5.8, P7.4) as built-in devices of the virt machine: a keyboard, which
// takes the PS/2 set-1 scancodes of the bus's "keyboard-code"
// (src/browser/keyboard.js) and sends evdev EV_KEY events; a tablet, which
// takes "mouse-absolute", "mouse-click" and "mouse-wheel"
// (src/browser/mouse.js) and sends EV_ABS (0-0x7FFF), the buttons and
// REL_WHEEL; and a multi-touch screen, which takes "touch" (the touches on
// the screen) and sends the slots of the MT protocol (type B: ABS_MT_SLOT,
// ABS_MT_TRACKING_ID, ABS_MT_POSITION_X/Y) and BTN_TOUCH, and, with no
// tablet beside it, the mouse as one finger (as Android's emulator: the
// left button down touches, moves drag, up lifts it). Their
// configuration (the select/subsel window: name, IDs, properties, event
// bits, the axes' ranges) is that of QEMU v9.2.0's virtio-keyboard,
// virtio-tablet and virtio-multitouch (hw/input/virtio-input-hid.c,
// wheel-axis on), so a guest sees the reference's devices. Events go out a
// batch at a time, ended by SYN_REPORT, as the driver offers buffers on the
// event queue; LED events on the status queue are taken and dropped.

import { VirtIO, VIRTIO_F_VERSION_1, VIRTIO_STATUS_DRIVER_OK } from "./virtio.js";
import { dbg_assert } from "./log.js";

// configuration selectors
const CFG_ID_NAME = 0x01;
const CFG_ID_DEVIDS = 0x03;
const CFG_PROP_BITS = 0x10;
const CFG_EV_BITS = 0x11;
const CFG_ABS_INFO = 0x12;

// event types and codes (Linux include/uapi/linux/input-event-codes.h)
const EV_SYN = 0, EV_KEY = 1, EV_REL = 2, EV_ABS = 3, EV_LED = 0x11, EV_REP = 0x14;
const SYN_REPORT = 0;
const REL_WHEEL = 8;
const ABS_X = 0, ABS_Y = 1;
const ABS_MT_SLOT = 0x2F, ABS_MT_POSITION_X = 0x35, ABS_MT_POSITION_Y = 0x36, ABS_MT_TRACKING_ID = 0x39;
const INPUT_PROP_DIRECT = 0x01;
/** the multi-touch screen's slots: 0-10, as QEMU's (INPUT_EVENT_SLOTS_MAX) */
const MT_SLOTS = 11;
const BTN_LEFT = 0x110, BTN_RIGHT = 0x111, BTN_MIDDLE = 0x112, BTN_SIDE = 0x113, BTN_EXTRA = 0x114;
const BTN_TOUCH = 0x14A, BTN_GEAR_DOWN = 0x150, BTN_GEAR_UP = 0x151;
const LED_NUML = 0, LED_CAPSL = 1, LED_SCROLLL = 2;
const KEY_PAUSE = 119;
const BUS_VIRTUAL = 6;
const ABS_MAX = 0x7FFF;

/** Set-1 scancodes after 0xE0 and their evdev key codes */
const EXTENDED_KEYS = new Map([
    [0x10, 165], [0x19, 163], [0x1C, 96], [0x1D, 97], [0x20, 113], [0x22, 164], [0x24, 166], [0x2E, 114], [0x30, 115],
    [0x35, 98], [0x37, 99], [0x38, 100], [0x47, 102], [0x48, 103], [0x49, 104], [0x4B, 105], [0x4D, 106], [0x4F, 107],
    [0x50, 108], [0x51, 109], [0x52, 110], [0x53, 111], [0x5B, 125], [0x5C, 126], [0x5D, 127], [0x5E, 116], [0x5F, 142],
    [0x63, 143],
]);
/** (the make codes 0x01-0x58 are the key codes themselves, but 0x54 and 0x55) */
const plain_key = code => code >= 0x01 && code <= 0x58 && code !== 0x54 && code !== 0x55 ? code : 0;

const EVENT_BYTES = 8;
/** Events kept while the driver has no buffers for them */
const PENDING_LIMIT = 256;

/**
 * A bitmap of `bits`, as long as its highest set bit needs
 * @param {!Array<number>} bits
 * @return {!Uint8Array}
 */
function bitmap(bits)
{
    const bytes = new Uint8Array(bits.length ? (Math.max(...bits) >> 3) + 1 : 0);
    for(const bit of bits) bytes[bit >> 3] |= 1 << (bit & 7);
    return bytes;
}

/** @param {!Array<number>} words little-endian 16-bit values */
const u16s = words => new Uint8Array(new Uint16Array(words).buffer);

/**
 * @constructor
 * @param {?} cpu
 * @param {?} bus
 * @param {string} kind "keyboard", "tablet" or "multitouch"
 * @param {?} transport the device's transport (src/virtio_mmio.js), or null: on the PCIe host at `pci_id`
 * @param {number=} pci_id
 * @param {boolean=} mouse_as_touch (multitouch) the mouse as one finger: no tablet takes it
 */
export function VirtioInput(cpu, bus, kind, transport, pci_id, mouse_as_touch)
{
    dbg_assert(transport || pci_id !== undefined && cpu.devices.pci.generic, "virtio-input: on the virt machine's transports only");
    dbg_assert(kind === "keyboard" || kind === "tablet" || kind === "multitouch");
    this.kind = kind;
    /** it takes the page's mouse (a tablet; a touch screen with no tablet beside it) */
    this.takes_mouse = kind === "tablet" || kind === "multitouch" && !!mouse_as_touch;
    /** @type {!Map<string, !Uint8Array>} the configuration by select and subsel ("select,subsel") */
    this.config = new Map();
    const name = { "keyboard": "QEMU Virtio Keyboard", "tablet": "QEMU Virtio Tablet", "multitouch": "QEMU Virtio MultiTouch" }[kind];
    this.config.set(CFG_ID_NAME + ",0", new TextEncoder().encode(name + "\0"));
    this.config.set(CFG_ID_DEVIDS + ",0", u16s([BUS_VIRTUAL, 0x0627, kind === "keyboard" ? 1 : 3, kind === "tablet" ? 2 : 1]));
    // (min, max, fuzz, flat, res)
    const axis = max => new Uint8Array(new Uint32Array([0, max, 0, 0, 0]).buffer);
    const buttons = [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_SIDE, BTN_EXTRA, BTN_TOUCH, BTN_GEAR_DOWN, BTN_GEAR_UP];
    if(kind === "keyboard")
    {
        const keys = [];
        for(let code = 1; code <= 0x58; code++) if(plain_key(code)) keys.push(code);
        keys.push(...EXTENDED_KEYS.values(), KEY_PAUSE);
        this.config.set(CFG_EV_BITS + "," + EV_KEY, bitmap(keys));
        this.config.set(CFG_EV_BITS + "," + EV_REP, new Uint8Array(1));
        this.config.set(CFG_EV_BITS + "," + EV_LED, bitmap([LED_NUML, LED_CAPSL, LED_SCROLLL]));
    }
    else if(kind === "tablet")
    {
        this.config.set(CFG_EV_BITS + "," + EV_KEY, bitmap(buttons));
        this.config.set(CFG_EV_BITS + "," + EV_ABS, bitmap([ABS_X, ABS_Y]));
        this.config.set(CFG_EV_BITS + "," + EV_REL, new Uint8Array([0, 1 << REL_WHEEL - 8]));
        this.config.set(CFG_ABS_INFO + "," + ABS_X, axis(ABS_MAX));
        this.config.set(CFG_ABS_INFO + "," + ABS_Y, axis(ABS_MAX));
    }
    else
    {
        this.config.set(CFG_PROP_BITS + ",0", bitmap([INPUT_PROP_DIRECT]));
        this.config.set(CFG_EV_BITS + "," + EV_KEY, bitmap(buttons));
        this.config.set(CFG_EV_BITS + "," + EV_ABS, bitmap([ABS_MT_SLOT, ABS_MT_TRACKING_ID, ABS_MT_POSITION_X, ABS_MT_POSITION_Y]));
        this.config.set(CFG_ABS_INFO + "," + ABS_MT_SLOT, axis(MT_SLOTS - 1));
        this.config.set(CFG_ABS_INFO + "," + ABS_MT_TRACKING_ID, axis(MT_SLOTS - 1));
        this.config.set(CFG_ABS_INFO + "," + ABS_MT_POSITION_X, axis(ABS_MAX));
        this.config.set(CFG_ABS_INFO + "," + ABS_MT_POSITION_Y, axis(ABS_MAX));
    }
    this.select = 0;
    this.subsel = 0;
    /** @type {!Array<!Array<number>>} [type, code, value] not yet in the guest's buffers */
    this.pending = [];
    // the host side's state: a scancode sequence in progress, buttons and position
    this.prefix = 0;
    this.pause_bytes = 0;
    this.buttons = [false, false, false];
    this.last_x = -1;
    this.last_y = -1;
    /** @type {!Array<?{id: *, x: number, y: number}>} the multi-touch slots: the touch in each (by the host's identifier) */
    this.slots = new Array(MT_SLOTS).fill(null);

    const selected = () => this.config.get(this.select + "," + this.subsel) || new Uint8Array(0);
    const struct = [
        { bytes: 1, name: "select", read: () => this.select, write: value => { this.select = value & 0xFF; } },
        { bytes: 1, name: "subsel", read: () => this.subsel, write: value => { this.subsel = value & 0xFF; } },
        { bytes: 1, name: "size", read: () => selected().length, write: () => {} },
        { bytes: 1, name: "reserved0", read: () => 0, write: () => {} },
        { bytes: 4, name: "reserved1", read: () => 0, write: () => {} },
    ];
    for(let i = 0; i < 128; i += 4)
    {
        struct.push({
            bytes: 4,
            name: "u" + i,
            read: () => { const b = selected(); return (b[i] | 0) | (b[i + 1] | 0) << 8 | (b[i + 2] | 0) << 16 | (b[i + 3] | 0) << 24; },
            write: () => {},
        });
    }

    this.bus = bus;
    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-input-" + kind,
        device_id: 0x1052,
        subsystem_device_id: 18,
        // (on the PCIe host: a keyboard, or another input device, as QEMU's)
        class_code: kind === "keyboard" ? 0x090000 : 0x098000,
        common:
        {
            queues: [{ size_supported: 64, notify_offset: 0 }, { size_supported: 64, notify_offset: 1 }],
            features: [VIRTIO_F_VERSION_1],
            on_driver_ok: () =>
            {
                this.flush();
                this.pointer_ready(true);
            },
        },
        notification:
        {
            single_handler: false,
            handlers: [
                () => this.flush(),
                () => this.take_status(),
            ],
        },
        isr_status: {},
        device_specific: { struct },
        on_reset: () =>
        {
            this.pending = [];
            this.pointer_ready(false);
        },
        transport: transport || undefined,
        pci_id,
    });

    if(kind === "keyboard")
    {
        bus.register("keyboard-code", code => this.scancode(code), this);
    }
    else if(kind === "tablet")
    {
        bus.register("mouse-absolute", data => this.absolute(data), this);
        bus.register("mouse-click", data => this.click(data), this);
        bus.register("mouse-wheel", data => this.wheel(data), this);
    }
    else
    {
        bus.register("touch", data => this.touch({ touches: data["touches"], width: data["width"], height: data["height"] }), this);
        if(mouse_as_touch)
        {
            /** the mouse on the screen: x, y, the screen's width and height (mouse-absolute) */
            this.pointer = null;
            this.pointer_down = false;
            bus.register("mouse-absolute", data => { this.pointer = data; if(this.pointer_down) this.touch_pointer(); }, this);
            bus.register("mouse-click", data =>
            {
                if(!!data[0] === this.pointer_down) return;
                this.pointer_down = !!data[0];
                this.touch_pointer();
            }, this);
        }
    }
}

/** The mouse as a finger: touching while the left button is down, where the mouse is */
VirtioInput.prototype.touch_pointer = function()
{
    const p = this.pointer;
    if(!p) return;
    this.touch({ touches: this.pointer_down ? [["mouse", p[0], p[1]]] : [], width: p[2], height: p[3] });
};

/**
 * The touches on the screen now: [[identifier, x, y], ...], width, height.
 * A new touch takes a free slot and a tracking ID (its slot's number, as
 * QEMU's); one that ended frees its slot (tracking ID -1); BTN_TOUCH is
 * down while any touch is.
 * @param {{touches: !Array<!Array<?>>, width: number, height: number}} data
 */
VirtioInput.prototype.touch = function(data)
{
    const events = [];
    const scale = (value, size) => Math.max(0, Math.min(ABS_MAX, Math.round(value / size * ABS_MAX)));
    const was_down = this.slots.some(s => !!s);
    const ids = new Set(data.touches.map(t => t[0]));
    // (ABS_MT_SLOT only where the slot changes)
    let selected = -1;
    const select = i => { if(i !== selected) events.push([EV_ABS, ABS_MT_SLOT, i]); selected = i; };
    this.slots.forEach((slot, i) => {
        if(slot && !ids.has(slot.id))
        {
            select(i);
            events.push([EV_ABS, ABS_MT_TRACKING_ID, -1]);
            this.slots[i] = null;
        }
    });
    for(const [id, x, y] of data.touches)
    {
        const at_x = scale(x, data.width), at_y = scale(y, data.height);
        let i = this.slots.findIndex(s => !!s && s.id === id);
        if(i < 0)
        {
            i = this.slots.indexOf(null);
            if(i < 0) continue;
            this.slots[i] = { id, x: -1, y: -1 };
            select(i);
            events.push([EV_ABS, ABS_MT_TRACKING_ID, i]);
        }
        const slot = /** @type {{id: *, x: number, y: number}} */ (this.slots[i]);
        if(at_x === slot.x && at_y === slot.y) continue;
        select(i);
        if(at_x !== slot.x) events.push([EV_ABS, ABS_MT_POSITION_X, at_x]);
        if(at_y !== slot.y) events.push([EV_ABS, ABS_MT_POSITION_Y, at_y]);
        slot.x = at_x;
        slot.y = at_y;
    }
    const down = this.slots.some(s => !!s);
    if(down !== was_down) events.push([EV_KEY, BTN_TOUCH, down ? 1 : 0]);
    if(events.length) this.send(events);
};

/**
 * One byte of a set-1 scancode sequence: a key goes down (make) or up
 * (break, bit 7); 0xE0 prefixes the extended keys, 0xE1 1D 45 (and E1 9D C5)
 * is Pause; the fake shifts around extended keys (E0 2A, E0 36) are dropped
 * @param {number} code
 */
VirtioInput.prototype.scancode = function(code)
{
    code &= 0xFF;
    if(this.pause_bytes)
    {
        // (E1 1D 45: Pause down; E1 9D C5: up)
        if(--this.pause_bytes === 0) this.send([[EV_KEY, KEY_PAUSE, code & 0x80 ? 0 : 1]]);
        return;
    }
    if(code === 0xE1)
    {
        this.pause_bytes = 2;
        return;
    }
    if(code === 0xE0)
    {
        this.prefix = 0xE0;
        return;
    }
    const extended = this.prefix === 0xE0;
    this.prefix = 0;
    const make = code & 0x7F;
    const key = extended ? EXTENDED_KEYS.get(make) || 0 : plain_key(make);
    if(key)
    {
        this.send([[EV_KEY, key, code & 0x80 ? 0 : 1]]);
    }
};

/** @param {!Array<number>} data [x, y, width, height] of the pointer on the screen */
VirtioInput.prototype.absolute = function(data)
{
    const x = Math.max(0, Math.min(ABS_MAX, Math.round(data[0] / data[2] * ABS_MAX)));
    const y = Math.max(0, Math.min(ABS_MAX, Math.round(data[1] / data[3] * ABS_MAX)));
    const events = [];
    if(x !== this.last_x) events.push([EV_ABS, ABS_X, x]);
    if(y !== this.last_y) events.push([EV_ABS, ABS_Y, y]);
    this.last_x = x;
    this.last_y = y;
    if(events.length) this.send(events);
};

/** @param {!Array<boolean>} data [left, middle, right] */
VirtioInput.prototype.click = function(data)
{
    const codes = [BTN_LEFT, BTN_MIDDLE, BTN_RIGHT];
    const events = [];
    for(let i = 0; i < 3; i++)
    {
        if(!!data[i] !== this.buttons[i]) events.push([EV_KEY, codes[i], data[i] ? 1 : 0]);
        this.buttons[i] = !!data[i];
    }
    if(events.length) this.send(events);
};

/** @param {!Array<number>} data [vertical, horizontal]: positive is up */
VirtioInput.prototype.wheel = function(data)
{
    if(data[0]) this.send([[EV_REL, REL_WHEEL, data[0] | 0]]);
};

/**
 * A batch of events, then SYN_REPORT; while the driver is not ready, or
 * has no buffers, they wait (at most PENDING_LIMIT events: older batches go)
 * @param {!Array<!Array<number>>} events
 */
VirtioInput.prototype.send = function(events)
{
    this.pending.push(...events, [EV_SYN, SYN_REPORT, 0]);
    while(this.pending.length > PENDING_LIMIT)
    {
        // (drop the oldest batch, through its SYN_REPORT)
        const end = this.pending.findIndex(([type]) => type === EV_SYN);
        this.pending.splice(0, end + 1);
    }
    this.flush();
};

/** The pending events into the event queue's buffers */
VirtioInput.prototype.flush = function()
{
    const queue = this.virtio.queues[0];
    if(!this.pending.length || !queue.is_configured() || !this.virtio.present()) return;
    let sent = 0;
    while(sent < this.pending.length && queue.has_request())
    {
        const chain = queue.pop_request();
        const [type, code, value] = this.pending[sent++];
        const event = new Uint8Array(EVENT_BYTES);
        const view = new DataView(event.buffer);
        view.setUint16(0, type, true);
        view.setUint16(2, code, true);
        view.setInt32(4, value, true);
        chain.set_next_blob(event);
        queue.push_reply(chain);
    }
    this.pending.splice(0, sent);
    if(sent) queue.flush_replies();
};

/** The driver's events (LEDs) on the status queue: taken and dropped */
VirtioInput.prototype.take_status = function()
{
    const queue = this.virtio.queues[1];
    let taken = 0;
    while(queue.has_request())
    {
        queue.push_reply(queue.pop_request());
        taken++;
    }
    if(taken) queue.flush_replies();
};

VirtioInput.prototype.reset = function()
{
    this.virtio.reset();
};

/**
 * A pointing device (the tablet, the multi-touch screen) the guest's driver
 * runs (DRIVER_OK) or no longer runs (a reset): the page's mouse adapter
 * takes the mouse and touches over the screen only while one does
 * (src/browser/mouse.js: "mouse-enable", as the PS/2 controller says for its
 * mouse; the virt machine has none, and without this a MacBook's trackpad
 * reached no device). The one that takes the mouse says its positions are
 * absolute ("absolute-pointer"): the page locks no pointer, and a tablet's
 * guest draws its own cursor (a touch screen beside a tablet leaves the
 * cursor to the tablet's).
 * @param {boolean} ready
 */
VirtioInput.prototype.pointer_ready = function(ready)
{
    if(this.kind === "keyboard") return;
    this.bus.send("mouse-enable", ready);
    if(this.takes_mouse) this.bus.send("absolute-pointer", [ready, this.kind === "tablet"]);
};

VirtioInput.prototype.get_state = function()
{
    return [this.virtio, this.select, this.subsel, [].concat(...this.pending),
        this.slots.map(slot => slot && [slot.id, slot.x, slot.y])];
};

VirtioInput.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    this.select = state[1];
    this.subsel = state[2];
    this.pending = [];
    const flat = state[3] || [];
    for(let i = 0; i + 2 < flat.length; i += 3) this.pending.push([flat[i], flat[i + 1], flat[i + 2]]);
    this.slots = (state[4] || new Array(MT_SLOTS).fill(null)).map(slot => slot && { id: slot[0], x: slot[1], y: slot[2] });
    // (a state whose driver ran: the page takes the pointer again)
    if(this.virtio.device_status & VIRTIO_STATUS_DRIVER_OK) this.pointer_ready(true);
};
                                                               source/v64/src/virtio_mmio.js                                                                       0000644 0000000 0000000 00000034260 00000000000 013353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The virtio-mmio transport, version 2 (virtio 1.2 section 4.2;
// docs/arm64-virt-android16-plan.md P5.3) of the virt machine: a slot of
// 0x200 bytes in VIRT_MMIO's block (src/virt/platform.js) with the device's
// registers, its configuration from 0x100, and an edge-triggered SPI
// (16 + the slot, as the reference's: QEMU's hw/arm/virt.c create_virtio_devices).
// The device itself is src/virtio.js's core: the registers map onto the
// fields of the capabilities it describes for virtio-pci, by name.
//
// The legacy transport, version 1 (virtio 1.2 section 4.2.4; the ranchu
// machine's: Linux 3.10 drives no other): the features without
// VIRTIO_F_VERSION_1, a queue placed by its page frame number (GuestPageSize,
// QueueAlign, QueuePFN: the descriptors, the available ring after them, the
// used ring aligned after that), no QueueReady.

import { dbg_assert } from "./log.js";

const MAGIC = 0x74726976; // "virt"
const VERSION = 2;
const VENDOR = 0x554D4551; // "QEMU", as the reference's

// register offsets (the legacy transport's own: GuestPageSize, QueueAlign, QueuePFN)
const R_GUEST_PAGE_SIZE = 0x028;
const R_QUEUE_ALIGN = 0x03C;
const R_QUEUE_PFN = 0x040;
const R_MAGIC = 0x000;
const R_VERSION = 0x004;
const R_DEVICE_ID = 0x008;
const R_VENDOR_ID = 0x00C;
const R_DEVICE_FEATURES = 0x010;
const R_DEVICE_FEATURES_SEL = 0x014;
const R_DRIVER_FEATURES = 0x020;
const R_DRIVER_FEATURES_SEL = 0x024;
const R_QUEUE_SEL = 0x030;
const R_QUEUE_NUM_MAX = 0x034;
const R_QUEUE_NUM = 0x038;
const R_QUEUE_READY = 0x044;
const R_QUEUE_NOTIFY = 0x050;
const R_INTERRUPT_STATUS = 0x060;
const R_INTERRUPT_ACK = 0x064;
const R_STATUS = 0x070;
const R_QUEUE_DESC_LOW = 0x080;
const R_QUEUE_DESC_HIGH = 0x084;
const R_QUEUE_DRIVER_LOW = 0x090;
const R_QUEUE_DRIVER_HIGH = 0x094;
const R_QUEUE_DEVICE_LOW = 0x0A0;
const R_QUEUE_DEVICE_HIGH = 0x0A4;
const R_SHM_SEL = 0x0AC;
const R_SHM_LEN_LOW = 0x0B0;
const R_SHM_LEN_HIGH = 0x0B4;
const R_SHM_BASE_LOW = 0x0B8;
const R_SHM_BASE_HIGH = 0x0BC;
const R_CONFIG_GENERATION = 0x0FC;
const R_CONFIG = 0x100;

/** A virtio PCI device ID's virtio device ID (0x1040 + id for modern devices) */
export function virtio_device_id(pci_device_id)
{
    dbg_assert(pci_device_id >= 0x1041 && pci_device_id <= 0x107F, "not a modern virtio PCI device ID");
    return pci_device_id - 0x1040;
}

/**
 * The transport of one slot. The machine (src/arm/cpu.js) owns the slots'
 * address ranges and hands this transport the slot's accesses.
 * @constructor
 * @param {{set_irq: function(number, boolean)}} cpu
 * @param {number} slot 0-31
 * @param {number} intid the slot's interrupt (SPI 16 + slot: INTID 48 + slot)
 * @param {boolean=} legacy the legacy transport (version 1)
 */
export function VirtioMmio(cpu, slot, intid, legacy = false)
{
    this.cpu = cpu;
    this.slot = slot;
    this.intid = intid;
    this.legacy = legacy;
    /** (legacy) the guest's page size, the queues' alignment and page frame numbers */
    this.guest_page_size = 4096;
    this.queue_align = 4096;
    /** @type {!Array<number>} */
    this.queue_pfn = [];
    /** @type {?Object} the device's core (src/virtio.js VirtIO), once attached */
    this.virtio = null;
    /** @type {!Object<string, {read: function():number, write: function(number)}>} the common fields by name */
    this.common = {};
    /** @type {!Array<{offset: number, bytes: number, read: function():number, write: function(number)}>} */
    this.config = [];
    this.config_size = 0;
    /** @type {!Array<{write: function(number)}>} queue notification fields by queue (common config's, written with the queue's index) */
    this.notify = [];
    /** @type {!Array<{id: number, bar: number, offset: number, length: number, base: number}>} shared memory regions */
    this.shared_memory = [];
    this.shm_select = 0;
    this.level = false;
    this.irq_line = {
        raise: () => this.update_irq(),
        lower: () => this.update_irq(),
    };
}

VirtioMmio.prototype.kind = function() { return "mmio"; };
VirtioMmio.prototype.present = function() { return true; };

/**
 * (VirtIO's constructor) the device's capabilities: the common
 * configuration's fields, the notification handlers, the device's
 * configuration, its shared memory regions (the base: where the machine put
 * the BAR, VirtioMmio.set_shared_memory_base)
 */
VirtioMmio.prototype.attach = function(virtio, capabilities, shared_memory)
{
    this.virtio = virtio;
    for(const cap of capabilities)
    {
        if(cap.type === 1)
        {
            for(const field of cap.struct) this.common[field.name] = field;
        }
        else if(cap.type === 2)
        {
            // (queue q notifies the handler at its notify_offset, or the single one)
            const handlers = cap.struct;
            this.notify = virtio.queues.map(queue => handlers.length === 1 ? handlers[0] : handlers[queue.notify_offset]);
        }
        else if(cap.type === 4)
        {
            let offset = 0;
            for(const field of cap.struct)
            {
                this.config.push({ offset, bytes: field.bytes, read: field.read, write: field.write });
                offset += field.bytes;
            }
            this.config_size = offset;
        }
    }
    this.shared_memory = shared_memory.map(region => ({ id: region.id, bar: region.bar, offset: region.offset, length: region.length, base: -1 }));
};

/**
 * The device's shared memory regions: id, the device's memory (as a BAR
 * number) and the offset in it, length
 * @return {!Array<{id: number, bar: number, offset: number, length: number}>}
 */
VirtioMmio.prototype.shared_memory_regions = function()
{
    return this.shared_memory.map(({ id, bar, offset, length }) => ({ id, bar, offset, length }));
};

/** Where a shared memory region (by id) is in the physical address space */
VirtioMmio.prototype.set_shared_memory_base = function(id, base)
{
    const region = this.shared_memory.find(r => r.id === id);
    if(region) region.base = base;
};

VirtioMmio.prototype.update_irq = function()
{
    // (the line is high while InterruptStatus has a bit: an edge per 0 -> 1)
    const level = this.virtio.isr_status !== 0;
    if(level !== this.level)
    {
        this.level = level;
        this.cpu.set_irq(this.intid, level);
    }
};

/** A field of the common configuration */
VirtioMmio.prototype.field = function(name)
{
    const field = this.common[name];
    dbg_assert(field, "virtio-mmio: no common field " + name);
    return field;
};

/** The bytes [offset, offset + width) of the device's configuration, little endian */
VirtioMmio.prototype.config_read = function(offset, width)
{
    const exact = this.config.find(f => f.offset === offset && f.bytes === width);
    if(exact)
    {
        const value = exact.read();
        return width === 4 ? value >>> 0 : value;
    }
    let value = 0;
    for(let i = 0; i < width; i++)
    {
        const at = offset + i;
        const field = this.config.find(f => at >= f.offset && at < f.offset + f.bytes);
        const byte = field ? field.read() >>> 8 * (at - field.offset) & 0xFF : 0;
        value += byte * 2 ** (8 * i);
    }
    return value;
};

VirtioMmio.prototype.config_write = function(offset, width, value)
{
    const exact = this.config.find(f => f.offset === offset && f.bytes === width);
    if(exact)
    {
        exact.write(value);
        return;
    }
    // (part of a field: read, merge, write it whole)
    for(let i = 0; i < width; i++)
    {
        const at = offset + i;
        const field = this.config.find(f => at >= f.offset && at < f.offset + f.bytes);
        if(!field) continue;
        const shift = 8 * (at - field.offset);
        const old = field.read();
        field.write((old & ~(0xFF << shift) | (Math.floor(value / 2 ** (8 * i)) & 0xFF) << shift) >>> 0);
    }
};

/** (the machine's MmioHandler) a register read */
VirtioMmio.prototype.read = function(offset, width)
{
    const virtio = this.virtio;
    if(offset >= R_CONFIG)
    {
        // (the driver reads the generation around the configuration: it stays fresh)
        virtio.update_config_generation();
        return this.config_read(offset - R_CONFIG, width);
    }
    if(width !== 4) return 0;
    const queue = virtio.queue_selected;
    switch(offset)
    {
        case R_MAGIC: return MAGIC;
        case R_VERSION: return this.legacy ? 1 : VERSION;
        case R_DEVICE_ID: return virtio_device_id(virtio.device_id);
        case R_VENDOR_ID: return VENDOR;
        case R_DEVICE_FEATURES:
        {
            const features = this.field("device_feature").read() >>> 0;
            // (a legacy device: not VIRTIO_F_VERSION_1, bit 32)
            return this.legacy && virtio.device_feature_select === 1 ? (features & ~1) >>> 0 : features;
        }
        case R_QUEUE_PFN: return this.legacy ? this.queue_pfn[virtio.queue_select] || 0 : 0;
        case R_DEVICE_FEATURES_SEL: return virtio.device_feature_select;
        case R_QUEUE_NUM_MAX: return queue ? queue.size_supported : 0;
        case R_QUEUE_READY: return queue ? queue.enabled | 0 : 0;
        case R_INTERRUPT_STATUS: return virtio.isr_status;
        case R_STATUS: return virtio.device_status;
        case R_QUEUE_DESC_LOW: return queue ? queue.address_words[0] >>> 0 : 0;
        case R_QUEUE_DESC_HIGH: return queue ? queue.address_words[1] >>> 0 : 0;
        case R_QUEUE_DRIVER_LOW: return queue ? queue.address_words[2] >>> 0 : 0;
        case R_QUEUE_DRIVER_HIGH: return queue ? queue.address_words[3] >>> 0 : 0;
        case R_QUEUE_DEVICE_LOW: return queue ? queue.address_words[4] >>> 0 : 0;
        case R_QUEUE_DEVICE_HIGH: return queue ? queue.address_words[5] >>> 0 : 0;
        case R_SHM_LEN_LOW:
        case R_SHM_LEN_HIGH:
        case R_SHM_BASE_LOW:
        case R_SHM_BASE_HIGH:
        {
            // (a region that does not exist: all ones)
            const region = this.shared_memory.find(r => r.id === this.shm_select);
            if(!region || region.base < 0) return 0xFFFFFFFF;
            const value = offset < R_SHM_BASE_LOW ? region.length : region.base;
            return offset & 4 ? Math.floor(value / 0x100000000) >>> 0 : value >>> 0;
        }
        case R_CONFIG_GENERATION:
            virtio.update_config_generation();
            return virtio.config_generation;
        default: return 0;
    }
};

/** (the machine's MmioHandler) a register write */
VirtioMmio.prototype.write = function(offset, width, value)
{
    const virtio = this.virtio;
    if(offset >= R_CONFIG)
    {
        this.config_write(offset - R_CONFIG, width, Number(value));
        return;
    }
    if(width !== 4) return;
    value = Number(value) >>> 0;
    const queue = virtio.queue_selected;
    switch(offset)
    {
        case R_DEVICE_FEATURES_SEL: this.field("device_feature_select").write(value); break;
        case R_DRIVER_FEATURES: this.field("driver_feature").write(value); break;
        case R_DRIVER_FEATURES_SEL: this.field("driver_feature_select").write(value); break;
        case R_QUEUE_SEL: this.field("queue_select").write(value); break;
        case R_QUEUE_NUM: this.field("queue_size").write(value); break;
        case R_QUEUE_READY:
            if(!queue) break;
            if(value & 1) this.field("queue_enable").write(1);
            // (0: the queue is taken back, its state forgotten)
            else if(queue.enabled) queue.reset();
            break;
        case R_QUEUE_NOTIFY:
        {
            const handler = this.notify[value & 0xFFFF];
            if(handler) handler.write(value & 0xFFFF);
            break;
        }
        case R_INTERRUPT_ACK:
            virtio.isr_status &= ~value;
            this.update_irq();
            break;
        case R_STATUS:
            this.field("device_status").write(value & 0xFF);
            // (a legacy driver's reset: the queues' pages too)
            if(this.legacy && value === 0) this.queue_pfn = [];
            break;
        case R_GUEST_PAGE_SIZE: if(this.legacy) this.guest_page_size = value || 4096; break;
        case R_QUEUE_ALIGN: if(this.legacy) this.queue_align = value || 4096; break;
        case R_QUEUE_PFN:
        {
            if(!this.legacy || !queue) break;
            this.queue_pfn[virtio.queue_select] = value;
            if(!value)
            {
                if(queue.enabled) queue.reset();
                break;
            }
            // (the split ring in one place: 16 bytes a descriptor; the
            // available ring's flags, index, ring and used_event; the used ring aligned)
            const size = queue.size;
            const desc = value * this.guest_page_size;
            const avail = desc + 16 * size;
            const used = Math.ceil((avail + 6 + 2 * size) / this.queue_align) * this.queue_align;
            const set = (name, address) => {
                this.field(name + " (low dword)").write(address >>> 0);
                this.field(name + " (high dword)").write(Math.floor(address / 0x100000000) >>> 0);
            };
            set("queue_desc", desc);
            set("queue_avail", avail);
            set("queue_used", used);
            this.field("queue_enable").write(1);
            break;
        }
        case R_QUEUE_DESC_LOW: this.field("queue_desc (low dword)").write(value); break;
        case R_QUEUE_DESC_HIGH: this.field("queue_desc (high dword)").write(value); break;
        case R_QUEUE_DRIVER_LOW: this.field("queue_avail (low dword)").write(value); break;
        case R_QUEUE_DRIVER_HIGH: this.field("queue_avail (high dword)").write(value); break;
        case R_QUEUE_DEVICE_LOW: this.field("queue_used (low dword)").write(value); break;
        case R_QUEUE_DEVICE_HIGH: this.field("queue_used (high dword)").write(value); break;
        case R_SHM_SEL: this.shm_select = value; break;
    }
};

/** (snapshots, P5.9) the transport's own registers */
VirtioMmio.prototype.get_state = function()
{
    return [this.slot, this.shm_select, this.level, this.legacy ? [this.guest_page_size, this.queue_align, this.queue_pfn.slice()] : null];
};

VirtioMmio.prototype.set_state = function(state)
{
    if(state[0] !== this.slot)
    {
        throw new Error("The snapshot has the virtio device in slot " + state[0] + ", this machine in " + this.slot);
    }
    this.shm_select = state[1];
    this.level = state[2];
    if(this.legacy && state[3]) [this.guest_page_size, this.queue_align, this.queue_pfn] = state[3];
    this.cpu.set_irq(this.intid, this.level);
};
                                                                                                                                                                                                                                                                                                                                                source/v64/src/virtio_net.js                                                                        0000644 0000000 0000000 00000021434 00000000000 013177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-2900003

import { dbg_assert } from "./log.js";
import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import { format_mac } from "./mac_address.js";
import * as marshall from "../lib/marshall.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

const MTU_DEFAULT = 1500;

const VIRTIO_NET_F_MAC = 5;
const VIRTIO_NET_F_CTRL_VQ = 17;
const VIRTIO_NET_F_STATUS = 16;
const VIRTIO_NET_F_MQ = 22;
const VIRTIO_NET_F_CTRL_MAC_ADDR = 23;
const VIRTIO_NET_F_MTU = 3;

const VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET = 0;
const VIRTIO_NET_CTRL_MAC_ADDR_SET = 1;

/**
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 * @param {Boolean} preserve_mac_from_state_image
 * @param {number=} mtu
 * @param {number=} pci_id where the machine puts it (behind a root port), or
 *     its usual slot
 * @param {?=} transport another transport than virtio-pci (the virt
 *     machine's virtio-mmio, src/virtio_mmio.js)
 * @param {number=} id its bus events' number (net<id>-send, ...): the
 *     virt machine's several functions; else 0, or 1 beside the PC's first NIC
 */
export function VirtioNet(cpu, bus, preserve_mac_from_state_image, mtu = MTU_DEFAULT, pci_id = undefined, transport = undefined, id = undefined)
{
    /** @const @type {BusConnector} */
    this.bus = bus;
    this.id = id !== undefined ? id : cpu.devices.net ? 1 : 0;
    this.pairs = 1;
    this.status = 1;
    this.preserve_mac_from_state_image = preserve_mac_from_state_image;
    this.mac = new Uint8Array([
        0x00, 0x22, 0x15,
        Math.random() * 255 | 0,
        Math.random() * 255 | 0,
        Math.random() * 255 | 0,
    ]);

    this.bus.send("net" + this.id + "-mac", format_mac(this.mac));

    const queues = [];

    for(let i = 0; i < this.pairs; ++i)
    {
        queues.push({size_supported: 1024, notify_offset: 0});
        queues.push({size_supported: 1024, notify_offset: 1});
    }
    queues.push({
        size_supported: 16,
        notify_offset: 2,
    });

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-net",
        transport,
        pci_id: pci_id === undefined ? 0x0A << 3 : pci_id,
        device_id: 0x1041,
        subsystem_device_id: 1,
        common:
        {
            initial_port: 0xC800,
            queues: queues,
            features:
            [
                VIRTIO_NET_F_MAC,
                VIRTIO_NET_F_STATUS,
                VIRTIO_NET_F_MQ,
                VIRTIO_NET_F_MTU,
                VIRTIO_NET_F_CTRL_VQ,
                VIRTIO_NET_F_CTRL_MAC_ADDR,
                VIRTIO_F_VERSION_1,
            ],
            on_driver_ok: () => {},
        },
        notification:
        {
            initial_port: 0xC900,
            single_handler: false,
            handlers:
            [
                (queue_id) =>
                {

                },
                (queue_id) =>
                {
                    const queue = this.virtio.queues[queue_id];

                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);
                        const header = this.header_size();
                        this.bus.send("net" + this.id + "-send", buffer.subarray(header));
                        this.bus.send("eth-transmit-end", [buffer.length - header]);
                        this.virtio.queues[queue_id].push_reply(bufchain);
                    }
                    this.virtio.queues[queue_id].flush_replies();
                },
                (queue_id) =>
                {
                    if(queue_id !== this.pairs * 2)
                    {
                        dbg_assert(false, "VirtioNet Notified for wrong queue: " + queue_id +
                            " (expected queue_id of 3)");
                        return;
                    }
                    const queue = this.virtio.queues[queue_id];

                    while(queue.has_request())
                    {
                        const bufchain = queue.pop_request();
                        const buffer = new Uint8Array(bufchain.length_readable);
                        bufchain.get_next_blob(buffer);


                        const parts = marshall.Unmarshall(["b", "b"], buffer, { offset : 0 });
                        const xclass = parts[0];
                        const command = parts[1];


                        //this.Ack(queue_id, bufchain);

                        switch(xclass << 8 | command) {
                            case 4 << 8 | VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET:
                                const data =  marshall.Unmarshall(["h"], buffer, { offset : 2 });
                                dbg_assert(data[0] === 1);
                                this.Send(queue_id, bufchain, new Uint8Array([0]));
                                break;
                            case 1 << 8 | VIRTIO_NET_CTRL_MAC_ADDR_SET:
                                this.mac = buffer.subarray(2, 8);
                                this.Send(queue_id, bufchain, new Uint8Array([0]));
                                this.bus.send("net" + this.id + "-mac", format_mac(this.mac));
                                break;
                            default:
                                dbg_assert(false," VirtioNet received unknown command: " + xclass + ":" + command);
                                this.Send(queue_id, bufchain, new Uint8Array([1]));
                                return;

                        }
                    }
                },
            ],
        },
        isr_status:
        {
            initial_port: 0xC700,
        },
        device_specific:
        {
            initial_port: 0xC600,
            struct:
            [0,1,2,3,4,5].map((v,k) => ({
                bytes: 1,
                name: "mac_" + k,
                read: () => this.mac[k],
                write: data => { /* read only */ },
            })).concat(
            [
                {
                    bytes: 2,
                    name: "status",
                    read: () => this.status,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 2,
                    name: "max_pairs",
                    read: () => this.pairs,
                    write: data => { /* read only */ },
                },
                {
                    bytes: 2,
                    name: "mtu",
                    read: () => mtu,
                    write: data => {},
                }
           ])
        },
    });

    this.bus.register("net" + this.id + "-receive", data => {
        this.bus.send("eth-receive-end", [data.length]);
        const header = this.header_size();
        const with_header = new Uint8Array(header + data.byteLength);
        const view = new DataView(with_header.buffer, with_header.byteOffset, with_header.byteLength);
        // (num_buffers: the modern header's)
        if(header === 12) view.setInt16(10, 1);
        with_header.set(data, header);

        const queue = this.virtio.queues[0];
        if(queue.has_request()) {
            const bufchain = queue.pop_request();
            bufchain.set_next_blob(with_header);
            this.virtio.queues[0].push_reply(bufchain);
            this.virtio.queues[0].flush_replies();
        } else {
            console.log("No buffer to write into!");
        }
    }, this);

}


VirtioNet.prototype.get_state = function()
{
    const state = [];
    state[0] = this.virtio;
    state[1] = this.id;
    state[2] = this.mac;
    return state;
};

VirtioNet.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    this.id = state[1];
    if(this.preserve_mac_from_state_image)
    {
        this.mac = state[2];
        this.bus.send("net" + this.id + "-mac", format_mac(this.mac));
    }
};

VirtioNet.prototype.reset = function() {
    this.virtio.reset();
};

VirtioNet.prototype.Send = function (queue_id, bufchain, blob)
{
    bufchain.set_next_blob(blob);
    this.virtio.queues[queue_id].push_reply(bufchain);
    this.virtio.queues[queue_id].flush_replies();
};

VirtioNet.prototype.Ack = function (queue_id, bufchain)
{
    //bufchain.set_next_blob(new Uint8Array(0));
    this.virtio.queues[queue_id].push_reply(bufchain);
    this.virtio.queues[queue_id].flush_replies();
};

/**
 * The bytes of struct virtio_net_hdr before each packet: 12 (num_buffers
 * too) with VIRTIO_F_VERSION_1, 10 for a legacy driver (the ranchu
 * machine's legacy virtio-mmio; no VIRTIO_NET_F_MRG_RXBUF is offered)
 * @return {number}
 */
VirtioNet.prototype.header_size = function()
{
    return this.virtio.is_feature_negotiated(VIRTIO_F_VERSION_1) ? 12 : 10;
};
                                                                                                                                                                                                                                    source/v64/src/virtio_rng.js                                                                        0000644 0000000 0000000 00000004067 00000000000 013202  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-rng (virtio 1.2 section 5.4; docs/arm64-virt-android16-plan.md
// P5.5) as a built-in device of the virt machine: every buffer the driver
// offers on its one queue is filled from crypto.getRandomValues (the
// guest's /dev/hwrng).

import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import { dbg_assert } from "./log.js";

/** crypto.getRandomValues fills at most this many bytes per call */
const ENTROPY_CHUNK = 65536;

/**
 * @constructor
 * @param {?} cpu
 * @param {?} transport the device's transport (src/virtio_mmio.js), or null: on the PCIe host at `pci_id`
 * @param {number=} pci_id
 */
export function VirtioRng(cpu, transport, pci_id)
{
    dbg_assert(transport || pci_id !== undefined && cpu.devices.pci.generic, "virtio-rng: on the virt machine's transports only");
    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-rng",
        device_id: 0x1044,
        subsystem_device_id: 4,
        common:
        {
            queues: [{ size_supported: 64, notify_offset: 0 }],
            features: [VIRTIO_F_VERSION_1],
            on_driver_ok: () => {},
        },
        notification:
        {
            single_handler: true,
            handlers: [queue_id => this.fill(this.virtio.queues[queue_id])],
        },
        isr_status: {},
        transport: transport || undefined,
        pci_id,
    });
}

/** @param {?} queue */
VirtioRng.prototype.fill = function(queue)
{
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const bytes = new Uint8Array(chain.length_writable);
        for(let at = 0; at < bytes.length; at += ENTROPY_CHUNK)
        {
            globalThis.crypto.getRandomValues(bytes.subarray(at, at + ENTROPY_CHUNK));
        }
        chain.set_next_blob(bytes);
        queue.push_reply(chain);
    }
    queue.flush_replies();
};

VirtioRng.prototype.reset = function()
{
    this.virtio.reset();
};

VirtioRng.prototype.get_state = function()
{
    return [this.virtio];
};

VirtioRng.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/src/virtio_snd.js                                                                        0000644 0000000 0000000 00000034620 00000000000 013176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-snd (virtio 1.2 section 5.14; docs/arm64-virt-android16-plan.md
// P7.5, P12.5) as a built-in device of the virt machine: one output stream
// (PCM, 1 or 2 channels, S16 or S32, 8000 to 48000 Hz), no jacks, one
// channel map (front left, front right).
//
// The driver's PCM buffers (the tx queue) are played at the stream's rate:
// each comes back when the time it lasts has passed on the machine's clock
// since the stream started, as a sound card's period would, its status
// telling the bytes still queued. The samples go to the speaker
// (src/browser/speaker.js: "dac-send-data") and, as the bytes they are, to
// "virtio-snd-pcm" listeners on the bus ({stream, rate, channels, format,
// bytes}: tests compare checksums).

import { VirtIO, VIRTIO_F_VERSION_1, VirtQueueBufferChain } from "./virtio.js";
import { dbg_assert, dbg_log } from "./log.js";
import { LOG_VIRTIO } from "./const.js";

// requests and statuses (struct virtio_snd_hdr's code)
const R_JACK_INFO = 1, R_PCM_INFO = 0x0100, R_PCM_SET_PARAMS = 0x0101, R_PCM_PREPARE = 0x0102,
    R_PCM_RELEASE = 0x0103, R_PCM_START = 0x0104, R_PCM_STOP = 0x0105, R_CHMAP_INFO = 0x0200;
const S_OK = 0x8000, S_BAD_MSG = 0x8001, S_NOT_SUPP = 0x8002;

// formats and rates (their numbers in the PCM info's bit masks)
const FMT_S16 = 5, FMT_S32 = 17;
const RATES = [5512, 8000, 11025, 16000, 22050, 32000, 44100, 48000];
const RATE_FIRST = 1, RATE_LAST = 7;
const DIRECTION_OUTPUT = 0;
const CHMAP_FL = 3, CHMAP_FR = 4;

const QUEUE_CONTROL = 0, QUEUE_EVENT = 1, QUEUE_TX = 2, QUEUE_RX = 3;
const PCM_INFO_BYTES = 32, CHMAP_INFO_BYTES = 24;

/**
 * @constructor
 * @param {?} cpu
 * @param {?} bus
 * @param {?} transport the device's transport (src/virtio_mmio.js), or null: on the PCIe host at `pci_id`
 * @param {number=} pci_id
 */
export function VirtioSnd(cpu, bus, transport, pci_id)
{
    dbg_assert(transport || pci_id !== undefined && cpu.devices.pci.generic, "virtio-snd: on the virt machine's transports only");
    this.cpu = cpu;
    this.bus = bus;
    this.stream = new_stream();

    const struct = [
        { bytes: 4, name: "jacks", read: () => 0, write: () => {} },
        { bytes: 4, name: "streams", read: () => 1, write: () => {} },
        { bytes: 4, name: "chmaps", read: () => 1, write: () => {} },
    ];

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-snd",
        device_id: 0x1059,
        subsystem_device_id: 25,
        // (a multimedia audio controller, as QEMU's)
        class_code: 0x040100,
        common:
        {
            queues: [0, 1, 2, 3].map(i => ({ size_supported: 64, notify_offset: i })),
            features: [VIRTIO_F_VERSION_1],
            on_driver_ok: () => {},
        },
        notification:
        {
            single_handler: false,
            handlers: [
                () => this.control(),
                // (the event queue's buffers stay with the device: no jack or period events are sent)
                () => {},
                () => this.take_pcm(),
                () => this.take_input(),
            ],
        },
        isr_status: {},
        device_specific: { struct },
        on_reset: () => this.reset_streams(),
        transport: transport || undefined,
        pci_id,
    });
}

/** A stream's state: its parameters, whether it plays, the buffers queued */
function new_stream()
{
    return {
        // the parameters (PCM_SET_PARAMS), null until set
        params: null,
        prepared: false,
        running: false,
        // the machine time the bytes played so far started at, and those bytes
        started: 0,
        played: 0,
        /** @type {!Array<{chain: ?, bytes: !Uint8Array}>} the driver's buffers, in order */
        queue: [],
        // the bytes in the queue's buffers before the first's that have played
        queued_bytes: 0,
    };
}

VirtioSnd.prototype.reset_streams = function()
{
    this.stream = new_stream();
};

/** The control queue: each request answered at once */
VirtioSnd.prototype.control = function()
{
    const queue = this.virtio.queues[QUEUE_CONTROL];
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const request = new Uint8Array(chain.length_readable);
        chain.get_next_blob(request);
        chain.set_next_blob(this.request(request));
        queue.push_reply(chain);
    }
    queue.flush_replies();
};

/**
 * @param {!Uint8Array} request
 * @return {!Uint8Array} the response: a status, then a query's information
 */
VirtioSnd.prototype.request = function(request)
{
    if(request.length < 4) return status(S_BAD_MSG);
    const view = new DataView(request.buffer, request.byteOffset, request.byteLength);
    const code = view.getUint32(0, true);
    const word = at => request.length >= at + 4 ? view.getUint32(at, true) : -1;
    if(code === R_JACK_INFO || code === R_PCM_INFO || code === R_CHMAP_INFO)
    {
        // a query: start_id, count, size of each item
        const [start, count, size] = [word(4), word(8), word(12)];
        const items = code === R_PCM_INFO || code === R_CHMAP_INFO ? 1 : 0;
        const minimum = code === R_PCM_INFO ? PCM_INFO_BYTES : CHMAP_INFO_BYTES;
        if(start < 0 || count < 0 || size < minimum || start + count > items) return status(S_BAD_MSG);
        const response = new Uint8Array(4 + count * size);
        new DataView(response.buffer).setUint32(0, S_OK, true);
        for(let i = 0; i < count; i++)
        {
            const item = new DataView(response.buffer, 4 + i * size, size);
            if(code === R_PCM_INFO)
            {
                // hda_fn_nid, features, formats (u64), rates (u64), direction, channels_min, channels_max
                item.setUint32(0, 0, true);
                item.setUint32(4, 0, true);
                item.setUint32(8, (1 << FMT_S16 | 1 << FMT_S32) >>> 0, true);
                item.setUint32(12, 0, true);
                let rates = 0;
                for(let r = RATE_FIRST; r <= RATE_LAST; r++) rates |= 1 << r;
                item.setUint32(16, rates, true);
                item.setUint32(20, 0, true);
                item.setUint8(24, DIRECTION_OUTPUT);
                item.setUint8(25, 1);
                item.setUint8(26, 2);
            }
            else
            {
                // hda_fn_nid, direction, channels, positions[18]
                item.setUint32(0, 0, true);
                item.setUint8(4, DIRECTION_OUTPUT);
                item.setUint8(5, 2);
                item.setUint8(6, CHMAP_FL);
                item.setUint8(7, CHMAP_FR);
            }
        }
        return response;
    }
    // the stream's requests: stream_id first
    const id = word(4);
    if(id !== 0) return status(S_BAD_MSG);
    const stream = this.stream;
    switch(code)
    {
        case R_PCM_SET_PARAMS:
        {
            if(request.length < 24) return status(S_BAD_MSG);
            const [buffer_bytes, period_bytes] = [word(8), word(12)];
            const [channels, format, rate] = [request[20], request[21], request[22]];
            if(stream.running || channels < 1 || channels > 2 || format !== FMT_S16 && format !== FMT_S32 ||
                rate < RATE_FIRST || rate > RATE_LAST || !period_bytes || buffer_bytes < period_bytes)
            {
                return status(S_NOT_SUPP);
            }
            stream.params = { channels, format, rate: RATES[rate], buffer_bytes, period_bytes,
                frame_bytes: channels * (format === FMT_S16 ? 2 : 4) };
            stream.prepared = false;
            return status(S_OK);
        }
        case R_PCM_PREPARE:
            if(!stream.params || stream.running) return status(S_BAD_MSG);
            stream.prepared = true;
            stream.played = 0;
            return status(S_OK);
        case R_PCM_START:
            if(!stream.prepared || stream.running) return status(S_BAD_MSG);
            stream.running = true;
            stream.started = this.now();
            stream.played = 0;
            this.bus.send("dac-tell-sampling-rate", stream.params.rate);
            this.bus.send("dac-enable");
            return status(S_OK);
        case R_PCM_STOP:
            if(!stream.running) return status(S_BAD_MSG);
            this.play(this.now());
            stream.running = false;
            return status(S_OK);
        case R_PCM_RELEASE:
            if(stream.running) return status(S_BAD_MSG);
            // (every buffer still queued comes back)
            this.complete(stream.queue.length);
            stream.prepared = false;
            return status(S_OK);
    }
    dbg_log("virtio-snd: request 0x" + code.toString(16) + " not supported", LOG_VIRTIO);
    return status(S_NOT_SUPP);
};

/** @param {number} code @return {!Uint8Array} */
function status(code)
{
    const bytes = new Uint8Array(4);
    new DataView(bytes.buffer).setUint32(0, code, true);
    return bytes;
}

/** The tx queue: the driver's PCM buffers, played in order */
VirtioSnd.prototype.take_pcm = function()
{
    const queue = this.virtio.queues[QUEUE_TX];
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const data = new Uint8Array(Math.max(0, chain.length_readable - 4));
        const header = new Uint8Array(4);
        chain.get_next_blob(header);
        chain.get_next_blob(data);
        this.stream.queue.push({ chain, bytes: data });
    }
    if(this.stream.running) this.play(this.now());
    else if(!this.stream.prepared) this.complete(this.stream.queue.length);
};

/** The rx queue: no input stream, so its buffers come back empty with an error */
VirtioSnd.prototype.take_input = function()
{
    const queue = this.virtio.queues[QUEUE_RX];
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const reply = new Uint8Array(8);
        new DataView(reply.buffer).setUint32(0, S_BAD_MSG, true);
        chain.set_next_blob(reply);
        queue.push_reply(chain);
    }
    queue.flush_replies();
};

/** The machine's time in milliseconds (it stops while the machine does) */
VirtioSnd.prototype.now = function()
{
    return this.cpu.clock ? this.cpu.clock.now() : performance.now();
};

/**
 * The buffers whose time has come: those the time since the start covers
 * @param {number} now
 */
VirtioSnd.prototype.play = function(now)
{
    const stream = this.stream;
    if(!stream.running) return;
    const due = Math.floor((now - stream.started) / 1000 * stream.params.rate) * stream.params.frame_bytes;
    let count = 0, played = stream.played;
    while(count < stream.queue.length && played + stream.queue[count].bytes.length <= due)
    {
        played += stream.queue[count].bytes.length;
        count++;
    }
    if(count) this.complete(count);
};

/**
 * The first `count` queued buffers played and back to the driver
 * @param {number} count
 */
VirtioSnd.prototype.complete = function(count)
{
    const stream = this.stream;
    const queue = this.virtio.queues[QUEUE_TX];
    const done = stream.queue.splice(0, count);
    let left = 0;
    for(const item of stream.queue) left += item.bytes.length;
    for(const { chain, bytes } of done)
    {
        stream.played += bytes.length;
        if(stream.params && bytes.length) this.output(bytes);
        // (struct virtio_snd_pcm_status: status, latency_bytes)
        const reply = new Uint8Array(8);
        const view = new DataView(reply.buffer);
        view.setUint32(0, S_OK, true);
        view.setUint32(4, left, true);
        chain.set_next_blob(reply);
        queue.push_reply(chain);
    }
    queue.flush_replies();
};

/** @param {!Uint8Array} bytes the samples played, interleaved */
VirtioSnd.prototype.output = function(bytes)
{
    const { channels, format, rate } = this.stream.params;
    this.bus.send("virtio-snd-pcm", { "stream": 0, "rate": rate, "channels": channels, "format": format === FMT_S16 ? "s16" : "s32",
        "bytes": bytes });
    // the speaker's two channels, as floats
    const width = format === FMT_S16 ? 2 : 4;
    const frames = Math.floor(bytes.length / (width * channels));
    const left = new Float32Array(frames), right = new Float32Array(frames);
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    for(let i = 0; i < frames; i++)
    {
        const at = i * width * channels;
        const l = width === 2 ? view.getInt16(at, true) / 32768 : view.getInt32(at, true) / 2147483648;
        const r = channels === 1 ? l : width === 2 ? view.getInt16(at + 2, true) / 32768 : view.getInt32(at + 4, true) / 2147483648;
        left[i] = l;
        right[i] = r;
    }
    this.bus.send("dac-send-data", [left, right]);
};

/**
 * (the machine's device timers) the buffers due by now
 * @param {number} now
 * @return {number} milliseconds until it needs to run again
 */
VirtioSnd.prototype.timer = function(now)
{
    const stream = this.stream;
    if(!stream.running || !stream.queue.length) return 100;
    this.play(now);
    if(!stream.queue.length) return 100;
    // (when the next buffer ends)
    const next = (stream.played + stream.queue[0].bytes.length) / stream.params.frame_bytes / stream.params.rate * 1000 + stream.started;
    return Math.max(1, Math.min(100, Math.ceil(next - now)));
};

VirtioSnd.prototype.reset = function()
{
    this.virtio.reset();
    this.reset_streams();
};

VirtioSnd.prototype.get_state = function()
{
    const stream = this.stream;
    // (the buffers queued by their chains' heads: made again from the ring on a restore)
    return [this.virtio, stream.params ? [stream.params.channels, stream.params.format, stream.params.rate,
        stream.params.buffer_bytes, stream.params.period_bytes] : null, stream.prepared, stream.running,
        stream.started, stream.played, stream.queue.map(({ chain }) => chain.head_idx)];
};

VirtioSnd.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    const stream = this.stream = new_stream();
    if(state[1])
    {
        const [channels, format, rate, buffer_bytes, period_bytes] = state[1];
        stream.params = { channels, format, rate, buffer_bytes, period_bytes, frame_bytes: channels * (format === FMT_S16 ? 2 : 4) };
    }
    stream.prepared = state[2];
    stream.running = state[3];
    stream.started = state[4];
    stream.played = state[5];
    const queue = this.virtio.queues[QUEUE_TX];
    for(const head of state[6] || [])
    {
        const chain = new VirtQueueBufferChain(queue, head);
        const header = new Uint8Array(4), bytes = new Uint8Array(Math.max(0, chain.length_readable - 4));
        chain.get_next_blob(header);
        chain.get_next_blob(bytes);
        stream.queue.push({ chain, bytes });
    }
};
                                                                                                                source/v64/src/virtio_vsock.js                                                                      0000644 0000000 0000000 00000026524 00000000000 013543  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // virtio-vsock (virtio 1.2 section 5.10; docs/arm64-virt-android16-plan.md
// P10.7) on the virt machine: stream sockets between the guest (CID 3) and
// the host (CID 2, this side), the channel Cuttlefish's host uses for adb
// (the guest's adbd listens on vsock:5555 as well as tcp:5555). The host
// side connects to the guest's ports; connections the guest makes to the
// host are refused (RST). The page or test drives it through the bus:
//   "virtio-vsock-connect"   [id, port]   connect to the guest's port
//   "virtio-vsock-send"      [id, bytes]
//   "virtio-vsock-close"     [id]
// and is told
//   "virtio-vsock-connected" [id], "virtio-vsock-data" [id, bytes],
//   "virtio-vsock-closed"    [id]         (also when refused or reset)
// Flow control is the protocol's credit: what the guest has room for
// (buf_alloc - (sent - fwd_cnt)) limits what is sent to it; the host side
// takes everything at once and tells the guest so (CREDIT_UPDATE) after
// every half of its window. Connections do not survive a saved state: after
// a restore the guest is sent TRANSPORT_RESET and the host side is told
// every connection closed.

import { VirtIO, VIRTIO_F_VERSION_1 } from "./virtio.js";
import { dbg_assert, dbg_log } from "./log.js";
import { LOG_VIRTIO } from "./const.js";

// For Types Only
import { BusConnector } from "./bus.js";

const HOST_CID = 2;
export const VSOCK_GUEST_CID = 3;
const HEADER = 44;
const TYPE_STREAM = 1;
const OP_REQUEST = 1, OP_RESPONSE = 2, OP_RST = 3, OP_SHUTDOWN = 4, OP_RW = 5, OP_CREDIT_UPDATE = 6, OP_CREDIT_REQUEST = 7;
const SHUTDOWN_BOTH = 3;
const EVENT_TRANSPORT_RESET = 0;
/** the host side's receive window */
const HOST_BUF_ALLOC = 256 * 1024;
const RX = 0, TX = 1, EVENT = 2;

/**
 * @constructor
 * @param {?} cpu
 * @param {BusConnector} bus
 * @param {?} transport the device's transport (src/virtio_mmio.js), or null: on the PCIe host at `pci_id`
 * @param {number=} pci_id
 */
export function VirtioVsock(cpu, bus, transport, pci_id)
{
    dbg_assert(transport || pci_id !== undefined, "virtio-vsock: on the virt machine's transports only");
    /** @const @type {BusConnector} */
    this.bus = bus;
    /** id -> connection: { id, local_port, port, state, peer_buf_alloc, peer_fwd_cnt, tx_cnt, rx_cnt, rx_reported, pending: !Array<!Uint8Array> } */
    this.connections = new Map();
    /** packets for the guest that wait for receive buffers */
    this.rx_pending = [];
    this.next_local_port = 1024;

    /** @type {VirtIO} */
    this.virtio = new VirtIO(cpu,
    {
        name: "virtio-vsock",
        device_id: 0x1053,
        subsystem_device_id: 19,
        common:
        {
            queues: [
                { size_supported: 128, notify_offset: 0 },
                { size_supported: 128, notify_offset: 0 },
                { size_supported: 16, notify_offset: 0 },
            ],
            features: [VIRTIO_F_VERSION_1],
            on_driver_ok: () => {},
        },
        notification:
        {
            single_handler: true,
            handlers: [queue_id => {
                if(queue_id === RX) this.flush_rx();
                else if(queue_id === TX) this.receive();
            }],
        },
        isr_status: {},
        device_specific:
        {
            struct: [
                { bytes: 4, name: "guest_cid_low", read: () => VSOCK_GUEST_CID, write: () => {} },
                { bytes: 4, name: "guest_cid_high", read: () => 0, write: () => {} },
            ],
        },
        transport: transport || undefined,
        pci_id,
    });

    bus.register("virtio-vsock-connect", ([id, port]) => this.connect(id, port), this);
    bus.register("virtio-vsock-send", ([id, bytes]) => this.send(id, bytes), this);
    bus.register("virtio-vsock-close", ([id]) => this.close(id), this);
}

/** a packet for the guest: header and payload */
VirtioVsock.prototype.packet = function(connection, op, payload, flags = 0)
{
    const bytes = new Uint8Array(HEADER + (payload ? payload.length : 0));
    const view = new DataView(bytes.buffer);
    view.setUint32(0, HOST_CID, true);
    view.setUint32(8, VSOCK_GUEST_CID, true);
    view.setUint32(16, connection.local_port, true);
    view.setUint32(20, connection.port, true);
    view.setUint32(24, payload ? payload.length : 0, true);
    view.setUint16(28, TYPE_STREAM, true);
    view.setUint16(30, op, true);
    view.setUint32(32, flags, true);
    view.setUint32(36, HOST_BUF_ALLOC, true);
    view.setUint32(40, connection.rx_cnt, true);
    if(payload) bytes.set(payload, HEADER);
    connection.rx_reported = connection.rx_cnt;
    return bytes;
};

VirtioVsock.prototype.to_guest = function(bytes)
{
    this.rx_pending.push(bytes);
    this.flush_rx();
};

VirtioVsock.prototype.flush_rx = function()
{
    const queue = this.virtio.queues[RX];
    if(!queue || !queue.is_configured()) return;
    let sent = false;
    while(this.rx_pending.length && queue.has_request())
    {
        const chain = queue.pop_request();
        let bytes = this.rx_pending[0];
        if(bytes.length > chain.length_writable)
        {
            // (a data packet longer than the guest's buffer: the rest in the
            // next one, with its own header)
            dbg_assert(chain.length_writable > HEADER, "virtio-vsock: receive buffer without room for data");
            const view = new DataView(bytes.buffer, bytes.byteOffset);
            const take = chain.length_writable - HEADER;
            const first = bytes.slice(0, HEADER + take);
            new DataView(first.buffer).setUint32(24, take, true);
            const rest = new Uint8Array(bytes.length - take);
            rest.set(bytes.subarray(0, HEADER));
            rest.set(bytes.subarray(HEADER + take), HEADER);
            new DataView(rest.buffer).setUint32(24, view.getUint32(24, true) - take, true);
            this.rx_pending[0] = rest;
            bytes = first;
        }
        else this.rx_pending.shift();
        chain.set_next_blob(bytes);
        queue.push_reply(chain);
        sent = true;
    }
    if(sent) queue.flush_replies();
};

/** the guest's packets */
VirtioVsock.prototype.receive = function()
{
    const queue = this.virtio.queues[TX];
    while(queue.has_request())
    {
        const chain = queue.pop_request();
        const bytes = new Uint8Array(chain.length_readable);
        chain.get_next_blob(bytes);
        queue.push_reply(chain);
        if(bytes.length >= HEADER) this.handle(bytes);
    }
    queue.flush_replies();
};

VirtioVsock.prototype.find = function(local_port, port)
{
    for(const connection of this.connections.values())
    {
        if(connection.local_port === local_port && connection.port === port) return connection;
    }
    return null;
};

VirtioVsock.prototype.handle = function(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const src_port = view.getUint32(16, true), dst_port = view.getUint32(20, true);
    const length = view.getUint32(24, true), type = view.getUint16(28, true), op = view.getUint16(30, true);
    const connection = this.find(dst_port, src_port);
    if(!connection)
    {
        // a connection the host side does not know (the guest's own, to the
        // host): refused
        if(op !== OP_RST)
        {
            this.to_guest(this.packet({ local_port: dst_port, port: src_port, rx_cnt: 0 }, OP_RST, null));
        }
        return;
    }
    if(type !== TYPE_STREAM) return;
    connection.peer_buf_alloc = view.getUint32(36, true);
    connection.peer_fwd_cnt = view.getUint32(40, true);
    switch(op)
    {
        case OP_RESPONSE:
            if(connection.state === "connecting")
            {
                connection.state = "open";
                this.bus.send("virtio-vsock-connected", [connection.id]);
            }
            break;
        case OP_RW:
        {
            const payload = bytes.slice(HEADER, HEADER + length);
            connection.rx_cnt = connection.rx_cnt + payload.length >>> 0;
            this.bus.send("virtio-vsock-data", [connection.id, payload]);
            if((connection.rx_cnt - connection.rx_reported >>> 0) >= HOST_BUF_ALLOC / 2)
            {
                this.to_guest(this.packet(connection, OP_CREDIT_UPDATE, null));
            }
            break;
        }
        case OP_CREDIT_REQUEST:
            this.to_guest(this.packet(connection, OP_CREDIT_UPDATE, null));
            break;
        case OP_CREDIT_UPDATE:
            break;
        case OP_SHUTDOWN:
            this.to_guest(this.packet(connection, OP_RST, null));
            this.drop(connection);
            return;
        case OP_RST:
            this.drop(connection);
            return;
        default:
            dbg_log("virtio-vsock: op " + op + " from the guest", LOG_VIRTIO);
    }
    this.flush_tx(connection);
};

/** the host side's data that the guest's credit allows */
VirtioVsock.prototype.flush_tx = function(connection)
{
    while(connection.state === "open" && connection.pending.length)
    {
        const credit = connection.peer_buf_alloc - (connection.tx_cnt - connection.peer_fwd_cnt >>> 0);
        if(credit <= 0) break;
        let chunk = connection.pending[0];
        if(chunk.length > credit)
        {
            connection.pending[0] = chunk.subarray(credit);
            chunk = chunk.subarray(0, credit);
        }
        else connection.pending.shift();
        connection.tx_cnt = connection.tx_cnt + chunk.length >>> 0;
        this.to_guest(this.packet(connection, OP_RW, chunk));
    }
};

VirtioVsock.prototype.connect = function(id, port)
{
    const connection = { id, local_port: this.next_local_port++, port, state: "connecting",
        peer_buf_alloc: 0, peer_fwd_cnt: 0, tx_cnt: 0, rx_cnt: 0, rx_reported: 0, pending: [] };
    if(this.next_local_port > 0xFFFF) this.next_local_port = 1024;
    this.connections.set(id, connection);
    this.to_guest(this.packet(connection, OP_REQUEST, null));
};

VirtioVsock.prototype.send = function(id, bytes)
{
    const connection = this.connections.get(id);
    if(!connection) return;
    connection.pending.push(new Uint8Array(bytes));
    this.flush_tx(connection);
};

VirtioVsock.prototype.close = function(id)
{
    const connection = this.connections.get(id);
    if(!connection) return;
    this.to_guest(this.packet(connection, OP_SHUTDOWN, null, SHUTDOWN_BOTH));
    this.drop(connection);
};

VirtioVsock.prototype.drop = function(connection)
{
    this.connections.delete(connection.id);
    this.bus.send("virtio-vsock-closed", [connection.id]);
};

/** every connection closed; the guest told so once it has an event buffer */
VirtioVsock.prototype.reset_connections = function(tell_guest)
{
    for(const connection of [...this.connections.values()]) this.drop(connection);
    this.rx_pending = [];
    if(tell_guest)
    {
        const queue = this.virtio.queues[EVENT];
        if(queue && queue.is_configured() && queue.has_request())
        {
            const chain = queue.pop_request();
            const event = new Uint8Array(4);
            new DataView(event.buffer).setUint32(0, EVENT_TRANSPORT_RESET, true);
            chain.set_next_blob(event);
            queue.push_reply(chain);
            queue.flush_replies();
        }
    }
};

VirtioVsock.prototype.reset = function()
{
    this.reset_connections(false);
    this.virtio.reset();
};

VirtioVsock.prototype.get_state = function()
{
    return [this.virtio];
};

VirtioVsock.prototype.set_state = function(state)
{
    this.virtio.set_state(state[0]);
    this.reset_connections(true);
};
                                                                                                                                                                            source/v64/src/vmware.js                                                                            0000644 0000000 0000000 00000045133 00000000000 012320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import { REG_EAX, REG_EBX, REG_ECX, REG_EDX, REG_ESI, REG_EDI, LOG_OTHER } from "./const.js";
import { dbg_log } from "./log.js";
import { STATE_OFFSETS } from "./state_layout.js";

// For Types Only
import { CPU } from "./cpu.js";
import { BusConnector } from "./bus.js";

const VMWARE_PORT = 0x5658;
const VMWARE_MAGIC = 0x564D5868;

const CMD_GETSELLENGTH = 6;
const CMD_GETNEXTPIECE = 7;
const CMD_SETSELLENGTH = 8;
const CMD_SETNEXTPIECE = 9;
const CMD_GETVERSION = 10;
const CMD_GETHWVERSION = 17;
const CMD_GETTIME = 23;
const CMD_ABSPOINTER_DATA = 39;
const CMD_ABSPOINTER_STATUS = 40;
const CMD_ABSPOINTER_COMMAND = 41;
const CMD_MESSAGE = 30;
// The display adapter's capabilities before the driver has the device: VMware's
// Windows driver (vm3dmp) loads as a full WDDM driver only if subcommand 0
// shows SVGA_CAP_3D and either SVGA_CAP_GBOBJECTS or, from subcommand 2, a
// 3D hardware version of at least 0x20000; else as a display-only driver
const CMD_GET_SVGA_CAPABILITIES = 75;

// The message channel (open-vm-tools lib/message): ECX's high word is the
// step, the status comes back in ECX's high word, the channel in EDX's
const MESSAGE_OPEN = 0;
const MESSAGE_SENDSIZE = 1;
const MESSAGE_SENDPAYLOAD = 2;
const MESSAGE_RECVSIZE = 3;
const MESSAGE_RECVPAYLOAD = 4;
const MESSAGE_RECVSTATUS = 5;
const MESSAGE_CLOSE = 6;
const MESSAGE_STATUS_SUCCESS = 0x0001;
const MESSAGE_STATUS_DORECV = 0x0002;
const RPCI_PROTOCOL = 0x49435052;
const GUESTMSG_FLAG_COOKIE = 0x80000000;
const MESSAGE_CHANNELS = 8;
const MESSAGE_MAX = 0x10000;

const ABSPOINTER_ENABLE = 0x45414552;
const ABSPOINTER_DISABLE = 0x000000F5;
const ABSPOINTER_RELATIVE = 0x4C455252;
const ABSPOINTER_ABSOLUTE = 0x53424152;

const READ_ID = 0x3442554A;

/** GETVERSION's product type (VMX_TYPE_WORKSTATION in open-vm-tools' backdoor_def.h) */
const VMX_TYPE_WORKSTATION = 4;
/** What GETHWVERSION reports: Workstation 12.5's, the first with SVGA 3D on Windows 8.1 guests through WDDM 1.3 */
const VIRTUAL_HARDWARE_VERSION = 13;

const BUTTON_LEFT = 0x20;
const BUTTON_RIGHT = 0x10;
const BUTTON_MIDDLE = 0x08;

// Flag in the status dword marking a packet whose x/y are signed deltas
// rather than absolute positions (VMMOUSE_RELATIVE_PACKET in the guest
// drivers). Used while the host pointer is locked and no meaningful absolute
// position exists.
const RELATIVE_PACKET = 0x00010000;

const QUEUE_MAX = 1024;
const CLIP_MAX = 0x10000;

/**
 * VMware backdoor (port 0x5658). Lets a guest driver read absolute pointer
 * position so the guest cursor can track the host cursor 1:1 without pointer
 * lock, lets a guest agent sync the clipboard with the host using the legacy
 * text commands (6–9), and implements GETTIME (23) so a guest agent can keep
 * the guest clock in sync with the host (guests only read the RTC at boot, so
 * a restored state resumes with a stale clock). PS/2 still supplies the mouse
 * IRQ; the driver reads this port on each IRQ12. While the host pointer is
 * locked
 * (e.g. for games), movement is reported as relative packets instead, since
 * no meaningful absolute position exists.
 *
 * @constructor
 * @param {CPU} cpu
 * @param {BusConnector} bus
 */
export function VMwareMouse(cpu, bus)
{
    /** @const @type {CPU} */
    this.cpu = cpu;

    /** @const @type {BusConnector} */
    this.bus = bus;

    /** @type {boolean} */
    this.enabled = false;

    /** @type {boolean} */
    this.absolute = false;

    /** @type {!Array<number>} */
    this.queue = [];

    this.buttons = 0;
    this.last_x = -1;
    this.last_y = -1;
    this.tail_is_move = false;

    /** @type {!Array<?{send: Uint8Array, sent: number, reply: Uint8Array, read: number}>}
     *  RPCI channels (CMD_MESSAGE): guests' logs and guestinfo queries */
    this.channels = [];
    /** @type {!Map<string, string>} what "info-get guestinfo.<key>" answers */
    this.guestinfo = new Map();

    /** @type {Uint8Array} host→guest text staged for the guest to read */
    this.clip_out = new Uint8Array(0);
    this.clip_out_cursor = 0;
    this.clip_out_fresh = false;

    /** @type {Uint8Array} guest→host text being received */
    this.clip_in = new Uint8Array(0);
    this.clip_in_cursor = 0;

    this.bus.register("vmware-clipboard-host", function(data)
    {
        this.clip_out = data.length > CLIP_MAX ? data.subarray(0, CLIP_MAX) : data;
        this.clip_out_cursor = 0;
        this.clip_out_fresh = true;
    }, this);

    /**
     * Whether the host pointer is currently locked (browser pointer lock).
     * While locked, the host cursor position is meaningless, so movement is
     * reported as relative packets instead of absolute ones.
     * @type {boolean}
     */
    this.host_pointer_locked = false;

    // sub-pixel remainders of relative movement
    this.rel_dx = 0;
    this.rel_dy = 0;

    // (while the guest uses the USB tablet, the pointer is the tablet's)
    this.usb_tablet_active = false;
    this.bus.register("usb-tablet-active", function(active)
    {
        this.usb_tablet_active = !!active;
    }, this);

    this.bus.register("mouse-absolute", function(data)
    {
        if(this.usb_tablet_active)
        {
            return;
        }
        const x = Math.max(0, Math.min(0xFFFF, Math.round(data[0] / data[2] * 0xFFFF)));
        const y = Math.max(0, Math.min(0xFFFF, Math.round(data[1] / data[3] * 0xFFFF)));
        if(x === this.last_x && y === this.last_y)
        {
            return;
        }
        this.last_x = x;
        this.last_y = y;
        this.push_absolute(0, true);
    }, this);

    this.bus.register("mouse-delta", function(data)
    {
        if(!this.host_pointer_locked)
        {
            return;
        }
        this.rel_dx += data[0];
        this.rel_dy += data[1];
        const dx = this.rel_dx | 0;
        const dy = this.rel_dy | 0;
        if(!dx && !dy)
        {
            return;
        }
        this.rel_dx -= dx;
        this.rel_dy -= dy;
        this.push_relative(dx, dy, 0, true);
    }, this);

    this.bus.register("mouse-pointer-lock", function(locked)
    {
        this.host_pointer_locked = locked;
        this.rel_dx = 0;
        this.rel_dy = 0;
    }, this);

    this.bus.register("mouse-click", function(data)
    {
        if(this.usb_tablet_active && !this.host_pointer_locked)
        {
            return;
        }
        this.buttons =
            (data[0] ? BUTTON_LEFT : 0) |
            (data[1] ? BUTTON_MIDDLE : 0) |
            (data[2] ? BUTTON_RIGHT : 0);
        if(this.host_pointer_locked)
        {
            this.push_relative(0, 0, 0, false);
        }
        else
        {
            this.push_absolute(0, false);
        }
    }, this);

    this.bus.register("mouse-wheel", function(data)
    {
        if(this.usb_tablet_active && !this.host_pointer_locked)
        {
            return;
        }
        if(this.host_pointer_locked)
        {
            this.push_relative(0, 0, -data[0] | 0, false);
        }
        else
        {
            this.push_absolute(-data[0] | 0, false);
        }
    }, this);

    // The backdoor protocol is 32-bit only, but guests probe the port at
    // narrower widths during detection — answer those as an empty port.
    const nop = function() {};
    cpu.io.register_read(VMWARE_PORT, this,
        function() { return 0xFF; }, function() { return 0xFFFF; }, this.port_read32);
    cpu.io.register_write(VMWARE_PORT, this, nop, nop, nop);
}

VMwareMouse.prototype.push_absolute = function(wheel, move_only)
{
    if(!this.enabled || !this.absolute || this.last_x < 0)
    {
        return;
    }
    // Absolute pointing has no use for move history — if the guest hasn't
    // drained the previous move yet, overwrite it in place. Clicks and wheel
    // are never coalesced. This keeps the guest cursor at most one frame
    // behind regardless of how slowly it drains, and makes overflow
    // unreachable in practice.
    if(move_only && this.tail_is_move && this.queue.length >= 4 &&
        !(this.queue[this.queue.length - 4] & RELATIVE_PACKET))
    {
        this.queue[this.queue.length - 3] = this.last_x;
        this.queue[this.queue.length - 2] = this.last_y;
        return;
    }
    this.push_packet(this.buttons, this.last_x, this.last_y, wheel, move_only);
};

// Relative fallback, used while the host pointer is locked (e.g. for games).
// The sign convention follows the Linux vmmouse driver: positive x is right,
// positive y is up, like PS/2.
VMwareMouse.prototype.push_relative = function(dx, dy, wheel, move_only)
{
    if(!this.enabled)
    {
        return;
    }
    // Same idea as in push_absolute, but pending deltas accumulate instead of
    // being overwritten.
    if(move_only && this.tail_is_move && this.queue.length >= 4 &&
        (this.queue[this.queue.length - 4] & RELATIVE_PACKET))
    {
        this.queue[this.queue.length - 3] += dx;
        this.queue[this.queue.length - 2] += dy;
        return;
    }
    this.push_packet(this.buttons | RELATIVE_PACKET, dx, dy, wheel, move_only);
};

VMwareMouse.prototype.push_packet = function(status, x, y, wheel, move_only)
{
    if(this.queue.length + 4 > QUEUE_MAX)
    {
        this.enabled = false;
        this.queue.length = 0;
        dbg_log("vmware mouse: queue overflow, disabling", LOG_OTHER);
        return;
    }
    this.queue.push(status, x, y, wheel);
    this.tail_is_move = move_only;
};

VMwareMouse.prototype.port_read32 = function()
{
    const reg32 = this.cpu.reg32;
    if(reg32[REG_EAX] !== VMWARE_MAGIC)
    {
        return 0xFFFFFFFF | 0;
    }

    switch(reg32[REG_ECX] & 0xFFFF)
    {
        case CMD_GETVERSION:
            // EAX: the backdoor's version; ECX: the product. VMware Tools'
            // installer refuses a machine whose product it does not know
            this.set_reg(REG_EBX, VMWARE_MAGIC);
            this.set_reg(REG_ECX, VMX_TYPE_WORKSTATION);
            return 6;

        case CMD_GETHWVERSION:
            // the virtual hardware version (a VM's "hardware compatibility")
            this.set_reg(REG_EBX, VMWARE_MAGIC);
            return VIRTUAL_HARDWARE_VERSION;

        case CMD_GETSELLENGTH:
            if(!this.clip_out_fresh)
            {
                return 0xFFFFFFFF | 0;
            }
            this.clip_out_fresh = false;
            this.clip_out_cursor = 0;
            return this.clip_out.length;

        case CMD_GETNEXTPIECE:
        {
            const c = this.clip_out;
            let i = this.clip_out_cursor;
            const v = (c[i] | 0) | (c[i + 1] | 0) << 8 |
                      (c[i + 2] | 0) << 16 | (c[i + 3] | 0) << 24;
            this.clip_out_cursor = i + 4;
            return v;
        }

        case CMD_SETSELLENGTH:
        {
            const n = Math.min(reg32[REG_EBX] >>> 0, CLIP_MAX);
            this.clip_in = new Uint8Array(n);
            this.clip_in_cursor = 0;
            if(n === 0)
            {
                this.bus.send("vmware-clipboard-guest", this.clip_in);
            }
            return 0;
        }

        case CMD_SETNEXTPIECE:
        {
            const c = this.clip_in;
            const v = reg32[REG_EBX] >>> 0;
            let i = this.clip_in_cursor;
            if(i < c.length) c[i++] = v;
            if(i < c.length) c[i++] = v >>> 8;
            if(i < c.length) c[i++] = v >>> 16;
            if(i < c.length) c[i++] = v >>> 24;
            this.clip_in_cursor = i;
            if(i >= c.length)
            {
                this.bus.send("vmware-clipboard-guest", c);
                this.clip_in = new Uint8Array(0);
                this.clip_in_cursor = 0;
            }
            return 0;
        }

        case CMD_GETTIME:
        {
            // EAX = host time in seconds since the Unix epoch (UTC),
            // EBX = remaining microseconds, ECX = maximum time lag in
            // microseconds, EDX = host's offset from UTC in minutes (east
            // positive). Deprecated upstream in favour of GETTIMEFULL because
            // EAX overflows as a signed value in 2038, but it's the simplest
            // command a 32-bit guest agent can consume — read unsigned it's
            // good until 2106.
            const now = Date.now();
            reg32[REG_EBX] = now % 1000 * 1000;
            reg32[REG_ECX] = 1000000;
            reg32[REG_EDX] = -new Date(now).getTimezoneOffset();
            return now / 1000 >>> 0;
        }

        case CMD_MESSAGE:
            return this.message(reg32);

        case CMD_GET_SVGA_CAPABILITIES:
        {
            const adapter = this.cpu.devices.graphics_adapter;
            const svga = adapter && adapter.svga_capabilities();
            if(!svga) break;
            this.set_reg(REG_EBX, VMWARE_MAGIC);
            const subcommand = reg32[REG_ECX] >>> 16;
            return (subcommand === 0 ? svga.capabilities : subcommand === 2 ? svga.hardware_version : 0) | 0;
        }

        case CMD_ABSPOINTER_STATUS:
            return this.enabled ? this.queue.length : 0xFFFF0000 | 0;

        case CMD_ABSPOINTER_DATA:
        {
            const n = Math.min(reg32[REG_EBX] >>> 0, 4, this.queue.length);
            const v = [0, 0, 0, 0];
            for(let i = 0; i < n; i++)
            {
                v[i] = this.queue.shift();
            }
            reg32[REG_EBX] = v[1];
            reg32[REG_ECX] = v[2];
            reg32[REG_EDX] = v[3];
            return v[0];
        }

        case CMD_ABSPOINTER_COMMAND:
            switch(reg32[REG_EBX])
            {
                case ABSPOINTER_ENABLE:
                    this.enabled = true;
                    this.queue.length = 0;
                    this.tail_is_move = false;
                    this.queue.push(READ_ID);
                    break;
                case ABSPOINTER_DISABLE:
                    this.enabled = false;
                    this.absolute = false;
                    this.queue.length = 0;
                    this.bus.send("vmware-absolute-mouse", false);
                    break;
                case ABSPOINTER_ABSOLUTE:
                    this.absolute = true;
                    this.bus.send("vmware-absolute-mouse", true);
                    break;
                case ABSPOINTER_RELATIVE:
                    this.absolute = false;
                    this.bus.send("vmware-absolute-mouse", false);
                    break;
            }
            return 0;
    }

    // (what guests ask that this does not know: for the harnesses' logs)
    this.bus.send("vmware-backdoor-unknown", reg32[REG_ECX] & 0xFFFF);
    return 0xFFFFFFFF | 0;
};

/**
 * Set a register from the backdoor: a 32-bit write, which in long mode
 * clears the upper half
 */
VMwareMouse.prototype.set_reg = function(reg, value)
{
    this.cpu.reg32[reg] = value;
    if(this.cpu.state_base !== undefined)
    {
        new Int32Array(this.cpu.wasm_memory.buffer, this.cpu.state_base + STATE_OFFSETS.x64_gpr_hi, 16)[reg] = 0;
    }
};

/**
 * CMD_MESSAGE: one step of the RPCI exchange, the low-bandwidth way (four
 * bytes per port access)
 * @return {number} EAX
 */
VMwareMouse.prototype.message = function(reg32)
{
    const step = reg32[REG_ECX] >>> 16, id = reg32[REG_EDX] >>> 16;
    // the status, and EAX
    const ok = status => { this.set_reg(REG_ECX, (status | MESSAGE_STATUS_SUCCESS) << 16); return 0; };
    const fail = () => { this.set_reg(REG_ECX, 0); return 0; };
    if(step === MESSAGE_OPEN)
    {
        if(((reg32[REG_EBX] >>> 0) & ~GUESTMSG_FLAG_COOKIE) !== RPCI_PROTOCOL) return fail();
        let free = this.channels.findIndex(channel => !channel);
        if(free < 0)
        {
            if(this.channels.length >= MESSAGE_CHANNELS) return fail();
            free = this.channels.length;
        }
        this.channels[free] = { send: null, sent: 0, reply: null, read: 0 };
        this.set_reg(REG_EDX, free << 16 | VMWARE_PORT);
        // (cookies: any values do, the guest gives them back)
        this.set_reg(REG_ESI, 0x56383601);
        this.set_reg(REG_EDI, 0x76383602);
        return ok(0);
    }
    const channel = this.channels[id];
    if(!channel) return fail();
    switch(step)
    {
        case MESSAGE_SENDSIZE:
        {
            const size = reg32[REG_EBX] >>> 0;
            if(size > MESSAGE_MAX) return fail();
            channel.send = new Uint8Array(size);
            channel.sent = 0;
            if(!size) this.rpci(channel);
            return ok(0);
        }
        case MESSAGE_SENDPAYLOAD:
        {
            const send = channel.send;
            if(!send) return fail();
            const v = reg32[REG_EBX];
            for(let i = 0; i < 4 && channel.sent < send.length; i++) send[channel.sent++] = v >>> 8 * i;
            if(channel.sent >= send.length) this.rpci(channel);
            return ok(0);
        }
        case MESSAGE_RECVSIZE:
            if(!channel.reply) return ok(0);
            this.set_reg(REG_EBX, channel.reply.length);
            // (EDX's high word: what the host sends next)
            this.set_reg(REG_EDX, MESSAGE_SENDSIZE << 16 | VMWARE_PORT);
            return ok(MESSAGE_STATUS_DORECV);
        case MESSAGE_RECVPAYLOAD:
        {
            const reply = channel.reply;
            if(!reply) return fail();
            let v = 0;
            for(let i = 0; i < 4; i++) v |= (reply[channel.read + i] | 0) << 8 * i;
            channel.read += 4;
            this.set_reg(REG_EBX, v);
            this.set_reg(REG_EDX, MESSAGE_SENDPAYLOAD << 16 | VMWARE_PORT);
            return ok(0);
        }
        case MESSAGE_RECVSTATUS:
            channel.reply = null;
            channel.read = 0;
            return ok(0);
        case MESSAGE_CLOSE:
            this.channels[id] = null;
            return ok(0);
    }
    return fail();
};

/**
 * A whole RPCI request has come: answer it ("1 <result>" or "0 <error>")
 */
VMwareMouse.prototype.rpci = function(channel)
{
    const request = new TextDecoder().decode(channel.send).replace(/\0+$/, "");
    channel.send = null;
    let reply = "0 Unknown command";
    if(!request.startsWith("log ")) this.bus.send("vmware-rpci", request);
    if(request.startsWith("log "))
    {
        // the drivers' logs (vmwgfx, VMware's WDDM driver): to whoever listens
        this.bus.send("vmware-log", request.slice(4));
        reply = "1 ";
    }
    else if(request.startsWith("info-get guestinfo."))
    {
        const value = this.guestinfo.get(request.slice(19));
        reply = value === undefined ? "0 No value found" : "1 " + value;
    }
    else if(request.startsWith("tools.capability.") || request.startsWith("tools.set.version"))
    {
        reply = "1 ";
    }
    channel.reply = new TextEncoder().encode(reply);
    channel.read = 0;
};

VMwareMouse.prototype.get_state = function()
{
    return [this.enabled, this.absolute];
};

VMwareMouse.prototype.set_state = function(state)
{
    this.enabled = state[0];
    this.absolute = state[1];
    this.bus.send("vmware-absolute-mouse", this.absolute);
};
                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/Readme.md                                                                          0000644 0000000 0000000 00000007331 00000000000 012551  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       Use the corresponding `make` target in the root directory to run a test. The
following list is roughtly sorted from most interesting/useful to least.

- [nasm](nasm/): Small unit tests written in assembly, which are run using gdb
  on the host.
- [qemu](qemu/): Based on tests from qemu. Builds a Linux binary, which tests
  many CPU features, which are then compared to a run on qemu.
- [kvm-unit-test](kvm-unit-tests/): Based on tests from the KVM project, tests
  various CPU features.
- [full](full/): Starts several OSes and checks if they boot correctly.
- [jit-paging](jit-paging/): Tests jit and paging interaction.
- [api](api/): Tests for several API functions of v86.
- [devices](devices/): Device tests.
- [rust](rust/): Rust unit test helpers.
- [smp](smp/): Cooperative multicore building blocks. `make smp-tests` checks
  state switching against independent single-core runs. `make multicore-boot-tests`
  checks bounded interpreter scheduling, APIC routing, guest INIT/SIPI trampolines
  on 2/4/8 cores and real SeaBIOS POST/floppy boot on 2/3/4/8 cores. The
  `multicore-boot-tests-release` target runs the same gate with release JS/Wasm.
  Multicore JIT, OS topology and multicore snapshots remain separate plan gates.

The following environmental variables are respected by most tests if applicable:

- `TEST_RELEASE_BUILD=1`: Test the release build (libv86.js, v86.wasm) instead of the
  debug build (source files with v86-debug.wasm)
- `MAX_PARALLEL_TESTS=n`: Maximum number of tests to run in parallel. Defaults
  to the number of cores in your system or less.
- `TEST_NAME="…"`: Run only the specified test (only full, nasm)

## JIT tests

The JIT is the x64 page tier ([JIT design](../docs/ir-design.md)); its local
gates are `make jit-gate` before each commit and `make jit-gate-full` before a
default changes ([jit-unification-plan.md](../docs/jit-unification-plan.md)
P0.9). The targets they run:

- `make x64-page-tier-tests`: long-mode and compatibility-mode code in the page
  tier ([x86-64.md](../docs/x86-64.md)).
- `make x64-legacy32-tests`: 32-bit and 16-bit code in the page tier against
  the interpreter: random programs (`ir/differential/tier0_fuzz.mjs` for 32-bit
  code, `ir/differential/prot16_fuzz.mjs` for 16-bit protected-mode, real-mode
  and virtual-8086 code, `FUZZ_KIND` and `FUZZ_MODE` select the forms), faults,
  interrupts, self-modifying code, multi-page functions, far transfers between
  modes, the step profile and the mode ledger. (The `tier0_` names are IR
  Tier-0's, which the page tier replaced.)
- `make jit-core-tests`: the Rust unit tests, the Wasm builder's output, and:
  - `make decode-tests`: the decoder catalogue over every encoding/ModRM/SIB
    form, instruction boundaries against NDISASM, and the interpreter's staged
    ModRM resolver against a pinned one (`decode/`);
  - `make rep-engine-tests`: the interpreter's REP engine in bounded batches
    against the pinned pre-refactor string body;
  - `make verr-flags-tests`: VERR/VERW's computed ZF against the raw flag;
  - `make decode-rules-tests`: mandatory prefixes, F2/F3 order and #UD for
    unlisted prefixes in the interpreter and the page tier, VEX by mode.
- `make jit-switch-tests`, `make jit-leaf-tests`, `make jit-disabled-tests`:
  the switch registry, the x86 leaf templates' golden digests, and the JIT
  turned off and on at run time.

The ISA suites (`make sse3-tests`, `ssse3-tests`, `sse4-tests`, `sse-fp-tests`,
`sse-fault-tests`, `avx-tests`, `bmi-tests`, `fma-tests`, `xsave-tests`, ...)
compare the interpreter and the page tier with SDM models and QEMU.

The IR region pipeline's tests (`make ir-*-tests`, `tests/expect`,
`tests/ir/semantics`, `tests/ir/wasm` and most of `tests/ir/differential`)
went with the region pipeline in M11 of the plan.
                                                                                                                                                                                                                                                                                                       source/v64/tests/a32/android/v86arm32.c                                                             0000644 0000000 0000000 00000004270 00000000000 014472  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The library of the 32-bit app (tests/a64/apk.mjs build_apk with native
// and abi armeabi-v7a, android.app.NativeActivity; the NDK's armv7a target:
// Thumb-2 code with VFP). Loaded, it logs its pointers' width and a sum
// computed in floating point (logcat tag v86arm32: "V86_ARM32_LOADED
// bits=32 sum=<s>", the sum of 1/sqrt(i) for i from 1 to 1000). Built with
// -DV86_FINISH it then finishes its activity, with no window (aarch32 plan
// Q5.2: an arm64-only vendor has no 32-bit gralloc mapper for window
// buffers); otherwise (R7.1) on its window, drawn with the CPU
// (ANativeWindow's buffer), the top half magenta and the bottom half cyan,
// and it logs "V86_ARM32_DREW <w>x<h> sum=<s> bits=32", keeping the window.
#include <android/log.h>
#include <android/native_activity.h>
#include <android/native_window.h>
#include <math.h>
#include <stdint.h>

#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "v86arm32", __VA_ARGS__)

static double sum(void)
{
    double s = 0;
    for(int i = 1; i <= 1000; i++) s += sqrt((double)i) / i;
    return s;
}

static void window_created(ANativeActivity *activity, ANativeWindow *window)
{
    (void)activity;
    ANativeWindow_setBuffersGeometry(window, 0, 0, WINDOW_FORMAT_RGBX_8888);
    ANativeWindow_Buffer buffer;
    if(ANativeWindow_lock(window, &buffer, NULL) != 0)
    {
        LOG("V86_ARM32_LOCK_FAILED");
        return;
    }
    for(int y = 0; y < buffer.height; y++)
    {
        uint32_t *row = (uint32_t *)buffer.bits + y * buffer.stride;
        // (RGBX in memory: R in the low byte)
        uint32_t color = y < buffer.height / 2 ? 0xFFFF00FF : 0xFFFFFF00;
        for(int x = 0; x < buffer.width; x++) row[x] = color;
    }
    ANativeWindow_unlockAndPost(window);
    LOG("V86_ARM32_DREW %dx%d sum=%.6f bits=%d", buffer.width, buffer.height, sum(), (int)sizeof(void *) * 8);
}

void ANativeActivity_onCreate(ANativeActivity *activity, void *saved_state, size_t saved_state_size)
{
    (void)saved_state;
    (void)saved_state_size;
    LOG("V86_ARM32_LOADED bits=%d sum=%.6f", (int)sizeof(void *) * 8, sum());
#ifdef V86_FINISH
    ANativeActivity_finish(activity);
#else
    activity->callbacks->onNativeWindowCreated = window_created;
#endif
}
                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a32/android/v86gles.c                                                              0000644 0000000 0000000 00000110527 00000000000 014503  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A NativeActivity that draws fixed GLES 2.0 and GLES 1.1 scenes into its
// window and reads them back (docs/gles-proxy-plan.md E4, the self-built
// test APK): each scene logs "V86_GLES <scene> <x>,<y>=<r>,<g>,<b>,<a> ..."
// for the pixels tests/a32/android_gles.mjs checks, then "V86_GLES_DONE".
// The scenes: a clear and a scissored clear; a textured quad (RGBA, nearest)
// over a blended triangle; render to a texture through a framebuffer, then
// sampled; an ETC1 texture; GLES 1.1: glOrthof with a vertex array and the
// current color, a texture modulated by a color array, a directional light,
// glDrawTexiOES; EGL: swap intervals, a fence sync, a pbuffer surface, a
// texture shared between two contexts. GLES 3.0 (docs/gles3-plan.md L4), with
// a host that announces it: instanced quads from a vertex array object
// colored by a uniform block, two draw buffers and glClearBufferfv, an
// unsigned integer buffer read as integers, transform feedback mapped, a 3D
// texture's layer, a multisampled renderbuffer resolved by a blit, and a
// read into a pixel pack buffer mapped. GLES 3.1 (L5), with a host that
// announces it: a compute shader's storage buffer and atomic counter mapped,
// an image a dispatch stored sampled by a draw, an indirect draw of
// parameters a dispatch wrote. Last, GLES 3.0's frame rate (L7): 49 lit,
// textured cubes drawn and swapped (interval 0) frame after frame, in one
// instanced draw and in a draw each, logged as "V86_GLES <fps|fpsdraws>
// frames=<n> draws=<a frame's> guest_ms=<the guest clock's time>".
#define GL_GLEXT_PROTOTYPES
#include <android/log.h>
#include <android/native_activity.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GLES3/gl31.h>
#include <GLES/gl.h>
#include <GLES/glext.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <pthread.h>
#include <time.h>

#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "v86gles", __VA_ARGS__)

static EGLDisplay display;
static EGLSurface surface;
static EGLConfig config;
static int width, height;

/** a few pixels of the window, logged (GL's rows: y from the bottom) */
static void report(const char* scene, const int* points, int count)
{
    char line[512];
    int at = snprintf(line, sizeof line, "V86_GLES %s", scene);
    for(int i = 0; i < count; i++)
    {
        unsigned char p[4];
        glReadPixels(points[2 * i], points[2 * i + 1], 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, p);
        at += snprintf(line + at, sizeof line - at, " %d,%d=%d,%d,%d,%d", points[2 * i], points[2 * i + 1], p[0], p[1], p[2], p[3]);
    }
    LOG("%s glerror=%x", line, glGetError());
}

static GLuint compile(GLenum type, const char* source)
{
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &source, 0);
    glCompileShader(shader);
    GLint ok = 0;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
    if(!ok)
    {
        char log[512];
        glGetShaderInfoLog(shader, sizeof log, 0, log);
        LOG("V86_GLES compile failed: %s", log);
    }
    return shader;
}

static void gles2_scenes(void)
{
    const char* vs = "attribute vec2 p; attribute vec2 uv; varying vec2 v; void main() { v = uv; gl_Position = vec4(p, 0.0, 1.0); }";
    const char* fs = "precision mediump float; uniform sampler2D t; uniform vec4 c; uniform float k; varying vec2 v; "
        "void main() { gl_FragColor = mix(c, texture2D(t, v), k); }";
    GLuint program = glCreateProgram();
    glAttachShader(program, compile(GL_VERTEX_SHADER, vs));
    glAttachShader(program, compile(GL_FRAGMENT_SHADER, fs));
    glBindAttribLocation(program, 0, "p");
    glBindAttribLocation(program, 1, "uv");
    glLinkProgram(program);
    glUseProgram(program);
    GLint c = glGetUniformLocation(program, "c"), k = glGetUniformLocation(program, "k"), t = glGetUniformLocation(program, "t");
    glUniform1i(t, 0);
    glViewport(0, 0, width, height);

    // a clear, then a scissored one (the bottom left quarter)
    glClearColor(1, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_SCISSOR_TEST);
    glScissor(0, 0, width / 2, height / 2);
    glClearColor(0, 1, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable(GL_SCISSOR_TEST);
    int clear_points[] = { 10, 10, width - 10, height - 10 };
    report("clear", clear_points, 2);

    // a blended triangle (half blue over red), then a 2 by 2 texture on the right half
    glClearColor(1, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    const float tri[] = { -1, -1, 0, -1, -1, 1 };
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, tri);
    glVertexAttrib2f(1, 0, 0);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glUniform4f(c, 0, 0, 1, 0.5f);
    glUniform1f(k, 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisable(GL_BLEND);
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    const unsigned char texels[] = { 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255 };
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    const float quad[] = { 0, -1, 0, 0, 1, -1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1 };
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 16, quad);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 16, quad + 2);
    glUniform1f(k, 1);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    int draw_points[] = { 10, 10, width / 2 + 10, 10, width - 10, 10, width / 2 + 10, height - 10, width - 10, height - 10, 10, height - 10 };
    report("draw", draw_points, 6);

    // render to a texture (yellow, a cyan triangle), then sample it over the window
    GLuint target, framebuffer;
    glGenTextures(1, &target);
    glBindTexture(GL_TEXTURE_2D, target);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 64, 64, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glGenFramebuffers(1, &framebuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target, 0);
    LOG("V86_GLES fbo status=%x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
    glViewport(0, 0, 64, 64);
    glClearColor(1, 1, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisableVertexAttribArray(1);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, tri);
    glUniform4f(c, 0, 1, 1, 1);
    glUniform1f(k, 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, width, height);
    const float full[] = { -1, -1, 0, 0, 1, -1, 1, 0, 1, 1, 1, 1, -1, 1, 0, 1 };
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 16, full);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 16, full + 2);
    glUniform1f(k, 1);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    int fbo_points[] = { 10, 10, width - 10, 10, width - 10, height - 10 };
    report("fbo", fbo_points, 3);

    // ETC1: one block, colors 136 each, every pixel +2
    const unsigned char block[] = { 0x88, 0x88, 0x88, 0x00, 0, 0, 0, 0 };
    glBindTexture(GL_TEXTURE_2D, texture);
    glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_ETC1_RGB8_OES, 4, 4, 0, 8, block);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    int etc1_points[] = { width / 2, height / 2 };
    report("etc1", etc1_points, 1);
    eglSwapBuffers(display, surface);
}

static GLuint link(const char* vs, const char* fs, const char* varying)
{
    GLuint program = glCreateProgram();
    glAttachShader(program, compile(GL_VERTEX_SHADER, vs));
    glAttachShader(program, compile(GL_FRAGMENT_SHADER, fs));
    if(varying) glTransformFeedbackVaryings(program, 1, &varying, GL_INTERLEAVED_ATTRIBS);
    glLinkProgram(program);
    GLint ok = 0;
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    if(!ok)
    {
        char log[512];
        glGetProgramInfoLog(program, sizeof log, 0, log);
        LOG("V86_GLES link failed: %s", log);
    }
    glUseProgram(program);
    return program;
}

static void gles3_scenes(void)
{
    glViewport(0, 0, width, height);
    // two quads, an instance each (the offset's divisor 1), the uniform block's color
    GLuint flat = link("#version 300 es\nlayout(location = 0) in vec2 p; layout(location = 1) in vec2 offset;\n"
        "void main() { gl_Position = vec4(p * 0.25 + offset, 0.0, 1.0); }",
        "#version 300 es\nprecision mediump float; layout(std140) uniform Colors { vec4 color; }; out vec4 o;\nvoid main() { o = color; }", 0);
    GLuint vao, buffers[6];
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glGenBuffers(6, buffers);
    const float quad[] = { -1, -1, 1, -1, -1, 1, 1, 1 };
    glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof quad, quad, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    const float offsets[] = { -0.5f, 0, 0.5f, 0 };
    glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof offsets, offsets, GL_STATIC_DRAW);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexAttribDivisor(1, 1);
    const float color[] = { 1, 0.5f, 0, 1 };
    glBindBuffer(GL_UNIFORM_BUFFER, buffers[2]);
    glBufferData(GL_UNIFORM_BUFFER, sizeof color, color, GL_STATIC_DRAW);
    glUniformBlockBinding(flat, glGetUniformBlockIndex(flat, "Colors"), 1);
    glBindBufferBase(GL_UNIFORM_BUFFER, 1, buffers[2]);
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, 2);
    int instanced_points[] = { width / 4, height / 2, width * 3 / 4, height / 2, width / 2, height / 2 };
    report("instanced", instanced_points, 3);

    // two draw buffers: red and blue, then the second cleared green
    link("#version 300 es\nlayout(location = 0) in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }",
        "#version 300 es\nprecision mediump float; layout(location = 0) out vec4 a; layout(location = 1) out vec4 b;\n"
        "void main() { a = vec4(1.0, 0.0, 0.0, 1.0); b = vec4(0.0, 0.0, 1.0, 1.0); }", 0);
    GLuint textures[4], framebuffers[3];
    glGenTextures(4, textures);
    glGenFramebuffers(3, framebuffers);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffers[0]);
    for(int i = 0; i < 2; i++)
    {
        glBindTexture(GL_TEXTURE_2D, textures[i]);
        glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 16, 16);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, textures[i], 0);
    }
    const GLenum draw[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
    glDrawBuffers(2, draw);
    glViewport(0, 0, 16, 16);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    int middle[] = { 8, 8 };
    glReadBuffer(GL_COLOR_ATTACHMENT1);
    report("mrt1", middle, 1);
    const float green[] = { 0, 1, 0, 1 };
    glClearBufferfv(GL_COLOR, 1, green);
    report("mrtclear", middle, 1);
    glReadBuffer(GL_COLOR_ATTACHMENT0);
    report("mrt0", middle, 1);

    // an unsigned integer color buffer, cleared and read as integers
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffers[1]);
    glBindTexture(GL_TEXTURE_2D, textures[2]);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32UI, 4, 4);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[2], 0);
    const GLuint big[] = { 4000000000u, 0, 0, 0 };
    glClearBufferuiv(GL_COLOR, 0, big);
    GLuint value[4] = { 0 };
    glReadPixels(0, 0, 1, 1, GL_RGBA_INTEGER, GL_UNSIGNED_INT, value);
    LOG("V86_GLES integer %u,%u,%u,%u glerror=%x", value[0], value[1], value[2], value[3], glGetError());

    // transform feedback: three points' positions doubled, mapped
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, width, height);
    link("#version 300 es\nlayout(location = 0) in vec2 p; out vec2 doubled; void main() { doubled = p * 2.0; gl_Position = vec4(p, 0.0, 1.0); }",
        "#version 300 es\nprecision mediump float; out vec4 o; void main() { o = vec4(1.0); }", "doubled");
    glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, buffers[3]);
    glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 24, 0, GL_STREAM_READ);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, buffers[3]);
    glEnable(GL_RASTERIZER_DISCARD);
    glBeginTransformFeedback(GL_POINTS);
    glDrawArrays(GL_POINTS, 0, 3);
    glEndTransformFeedback();
    glDisable(GL_RASTERIZER_DISCARD);
    const float* captured = glMapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 24, GL_MAP_READ_BIT);
    if(captured) LOG("V86_GLES feedback %g,%g,%g,%g,%g,%g glerror=%x", captured[0], captured[1], captured[2], captured[3], captured[4], captured[5], glGetError());
    glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);

    // a 3D texture of two layers (red, blue), sampled at the second
    link("#version 300 es\nlayout(location = 0) in vec2 p; out vec2 uv; void main() { uv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        "#version 300 es\nprecision mediump float; uniform mediump sampler3D volume; in vec2 uv; out vec4 o;\n"
        "void main() { o = texture(volume, vec3(uv, 0.75)); }", 0);
    glBindTexture(GL_TEXTURE_3D, textures[3]);
    const unsigned char layers[] = { 255, 0, 0, 255, 0, 0, 255, 255 };
    glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, 1, 1, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, layers);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    int center[] = { width / 2, height / 2 };
    report("volume", center, 1);

    // a multisampled renderbuffer cleared magenta, resolved into the window's corner by a blit
    GLuint renderbuffer;
    glGenRenderbuffers(1, &renderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
    glRenderbufferStorageMultisample(GL_RENDERBUFFER, 4, GL_RGBA8, 16, 16);
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffers[2]);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
    glClearColor(1, 0, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
    glBlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    report("resolve", middle, 1);

    // that pixel into a pixel pack buffer, mapped
    glBindBuffer(GL_PIXEL_PACK_BUFFER, buffers[4]);
    glBufferData(GL_PIXEL_PACK_BUFFER, 4, 0, GL_STREAM_READ);
    glReadPixels(8, 8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    const unsigned char* packed = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, 4, GL_MAP_READ_BIT);
    if(packed) LOG("V86_GLES pack %d,%d,%d,%d glerror=%x", packed[0], packed[1], packed[2], packed[3], glGetError());
    glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
    eglSwapBuffers(display, surface);
}

static GLuint link_compute(const char* source)
{
    GLuint program = glCreateProgram();
    glAttachShader(program, compile(GL_COMPUTE_SHADER, source));
    glLinkProgram(program);
    GLint ok = 0;
    glGetProgramiv(program, GL_LINK_STATUS, &ok);
    if(!ok) LOG("V86_GLES compute link failed");
    glUseProgram(program);
    return program;
}

/** out = a * b, column-major 4x4 */
static void multiply(float* out, const float* a, const float* b)
{
    float r[16];
    for(int column = 0; column < 4; column++)
        for(int row = 0; row < 4; row++)
        {
            r[column * 4 + row] = 0;
            for(int k = 0; k < 4; k++) r[column * 4 + row] += a[k * 4 + row] * b[column * 4 + k];
        }
    memcpy(out, r, sizeof r);
}

static double guest_ms(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec * 1000.0 + t.tv_nsec / 1e6;
}

/**
 * Frames of the cubes (fps_scene's) swapped one after another: five to warm
 * up (the pipelines), then up to 100 frames or 5 s of the guest's clock
 * timed; one instanced draw a frame, or (`separate`) a draw a cube, the
 * offset a constant attribute. The last frame drawn again, unswapped, for a
 * pixel of the middle cube.
 */
static void timed_frames(const char* name, float* frame, const float* offsets, int separate)
{
    int frames = 0;
    double start = 0, now = 0;
    if(separate) glDisableVertexAttribArray(3);
    for(int i = 0; ; i++)
    {
        // the model: about y, then about x
        const float a = i * 0.05f, b = i * 0.035f;
        const float ry[16] = { cosf(a), 0, -sinf(a), 0, 0, 1, 0, 0, sinf(a), 0, cosf(a), 0, 0, 0, 0, 1 };
        const float rx[16] = { 1, 0, 0, 0, 0, cosf(b), sinf(b), 0, 0, -sinf(b), cosf(b), 0, 0, 0, 0, 1 };
        multiply(frame + 16, ry, rx);
        glBufferSubData(GL_UNIFORM_BUFFER, 0, 36 * sizeof(float), frame);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        if(!separate) glDrawElementsInstanced(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0, 49);
        else for(int k = 0; k < 49; k++)
        {
            glVertexAttrib3fv(3, offsets + 3 * k);
            glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);
        }
        now = guest_ms();
        if(i == 5) start = now;
        if(i > 5 && (frames >= 100 || now - start >= 5000)) break;
        eglSwapBuffers(display, surface);
        if(i >= 5) frames++;
    }
    int middle[] = { width / 2, height / 2 };
    report(name, middle, 1);
    LOG("V86_GLES %s frames=%d draws=%d guest_ms=%.1f", name, frames, separate ? 49 : 1, now - start);
    if(separate) glEnableVertexAttribArray(3);
}

// GLES 3.0's frame rate (docs/gles3-plan.md L7): 7x7 cubes from a vertex
// array object (interleaved positions, normals and coordinates, an index
// buffer, an offset a cube), their rotation in a uniform block written every
// frame, a mipmapped texture through a sampler object, a depth test; swapped
// at interval 0, so as fast as the guest and the host draw them, not at
// vsync's pace (the host lets the guest be at most two frames ahead):
// instanced, one draw a frame ("fps"), then a draw a cube ("fpsdraws").
static void fps_scene(void)
{
    const char* block = "layout(std140) uniform Frame { mat4 view_projection; mat4 model; vec4 light; };\n";
    char vs[1024], fs[1024];
    snprintf(vs, sizeof vs, "#version 300 es\n%s"
        "layout(location = 0) in vec3 p; layout(location = 1) in vec3 n; layout(location = 2) in vec2 uv; layout(location = 3) in vec3 offset;\n"
        "out vec3 v_normal; out vec2 v_uv;\n"
        "void main() { v_normal = mat3(model) * n; v_uv = uv; gl_Position = view_projection * (model * vec4(p * 0.3, 1.0) + vec4(offset, 0.0)); }", block);
    snprintf(fs, sizeof fs, "#version 300 es\nprecision mediump float;\n%s"
        "uniform sampler2D tex; in vec3 v_normal; in vec2 v_uv; out vec4 o;\n"
        "void main() { float d = max(dot(normalize(v_normal), light.xyz), 0.0) * 0.8 + 0.2; o = vec4(texture(tex, v_uv).rgb * d, 1.0); }", block);
    GLuint program = link(vs, fs, 0);
    // a cube: 4 vertices a face (position, normal, coordinates), 2 triangles
    float vertices[24 * 8];
    GLushort indices[36];
    for(int face = 0; face < 6; face++)
    {
        const int axis = face / 2, u = (axis + 1) % 3, v = (axis + 2) % 3;
        const float sign = face % 2 ? 1 : -1;
        for(int corner = 0; corner < 4; corner++)
        {
            float* x = vertices + (face * 4 + corner) * 8;
            const int i = corner & 1, j = corner >> 1;
            memset(x, 0, 8 * sizeof(float));
            x[axis] = sign;
            x[u] = 2 * i - 1;
            x[v] = 2 * j - 1;
            x[3 + axis] = sign;
            x[6] = i;
            x[7] = j;
        }
        const GLushort order[] = { 0, 1, 2, 2, 1, 3 };
        for(int k = 0; k < 6; k++) indices[face * 6 + k] = face * 4 + order[k];
    }
    float offsets[49 * 3];
    for(int k = 0; k < 49; k++)
    {
        offsets[3 * k] = (k % 7 - 3) * 0.5f;
        offsets[3 * k + 1] = (k / 7 - 3) * 0.5f;
        offsets[3 * k + 2] = 0;
    }
    GLuint vao, buffers[4], texture, sampler;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glGenBuffers(4, buffers);
    glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
    for(int a = 0; a < 3; a++)
    {
        glEnableVertexAttribArray(a);
        glVertexAttribPointer(a, a == 2 ? 2 : 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (const void*)(a * 3 * sizeof(float)));
    }
    glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof offsets, offsets, GL_STATIC_DRAW);
    glEnableVertexAttribArray(3);
    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glVertexAttribDivisor(3, 1);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STATIC_DRAW);
    glBindBuffer(GL_UNIFORM_BUFFER, buffers[3]);
    glBufferData(GL_UNIFORM_BUFFER, 36 * sizeof(float), 0, GL_DYNAMIC_DRAW);
    glUniformBlockBinding(program, glGetUniformBlockIndex(program, "Frame"), 0);
    glBindBufferBase(GL_UNIFORM_BUFFER, 0, buffers[3]);
    // an orange and white checkerboard, mipmapped, sampled trilinear
    static unsigned char texels[64 * 64 * 4];
    for(int y = 0; y < 64; y++)
        for(int x = 0; x < 64; x++)
        {
            const int white = (x / 8 + y / 8) % 2;
            unsigned char* t = texels + (y * 64 + x) * 4;
            t[0] = 255; t[1] = white ? 255 : 128; t[2] = white ? 255 : 0; t[3] = 255;
        }
    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexStorage2D(GL_TEXTURE_2D, 7, GL_RGBA8, 64, 64);
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 64, 64, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    glGenerateMipmap(GL_TEXTURE_2D);
    glGenSamplers(1, &sampler);
    glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glBindSampler(0, sampler);
    glUniform1i(glGetUniformLocation(program, "tex"), 0);
    // a perspective of 60 degrees, the cubes 6 away
    const float f = 1 / tanf(3.14159265f / 6), aspect = (float)width / height, near = 0.1f, far = 20;
    const float projection[16] = { f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / (near - far), -1, 0, 0, 2 * far * near / (near - far), 0 };
    const float view[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -6, 1 };
    float frame[36];
    multiply(frame, projection, view);
    frame[32] = 0.3f; frame[33] = 0.5f; frame[34] = 0.81f; frame[35] = 0;
    glViewport(0, 0, width, height);
    glEnable(GL_DEPTH_TEST);
    glClearColor(0.1f, 0.1f, 0.2f, 1);
    eglSwapInterval(display, 0);
    timed_frames("fps", frame, offsets, 0);
    timed_frames("fpsdraws", frame, offsets, 1);
    eglSwapInterval(display, 1);
    glDisable(GL_DEPTH_TEST);
    glBindSampler(0, 0);
    glBindVertexArray(0);
}

static void gles31_scenes(void)
{
    GLuint buffers[3], vao, image;
    glGenBuffers(3, buffers);
    // a storage buffer and an atomic counter, a dispatch of two groups of four
    link_compute("#version 310 es\nlayout(local_size_x = 4) in;\nlayout(std430, binding = 0) buffer Data { uint values[]; };\n"
        "layout(binding = 0, offset = 0) uniform atomic_uint counter;\n"
        "void main() { values[gl_GlobalInvocationID.x] = gl_GlobalInvocationID.x * 3u; atomicCounterIncrement(counter); }");
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffers[0]);
    glBufferData(GL_SHADER_STORAGE_BUFFER, 32, 0, GL_DYNAMIC_COPY);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, buffers[0]);
    const GLuint start = 10;
    glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, buffers[1]);
    glBufferData(GL_ATOMIC_COUNTER_BUFFER, 4, &start, GL_DYNAMIC_COPY);
    glBindBufferBase(GL_ATOMIC_COUNTER_BUFFER, 0, buffers[1]);
    glDispatchCompute(2, 1, 1);
    glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT);
    const GLuint* values = glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, 32, GL_MAP_READ_BIT);
    if(values) LOG("V86_GLES storage %u,%u,%u,%u,%u,%u,%u,%u glerror=%x", values[0], values[1], values[2], values[3], values[4], values[5], values[6],
        values[7], glGetError());
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    const GLuint* counted = glMapBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, 4, GL_MAP_READ_BIT);
    if(counted) LOG("V86_GLES counter %u glerror=%x", counted[0], glGetError());
    glUnmapBuffer(GL_ATOMIC_COUNTER_BUFFER);

    // an image a dispatch stored (green), and an indirect draw's parameters a dispatch wrote, drawn sampling it
    glGenTextures(1, &image);
    glBindTexture(GL_TEXTURE_2D, image);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, 8, 8);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    link_compute("#version 310 es\nlayout(local_size_x = 8, local_size_y = 8) in;\nlayout(rgba8, binding = 0) writeonly uniform highp image2D target;\n"
        "layout(std430, binding = 1) buffer Command { uint count; uint instances; uint first; uint reserved; };\n"
        "void main() { imageStore(target, ivec2(gl_GlobalInvocationID.xy), vec4(0.0, 1.0, 0.0, 1.0));\n"
        "  if(gl_LocalInvocationIndex == 0u) { count = 4u; instances = 1u; first = 0u; reserved = 0u; } }");
    glBindImageTexture(0, image, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, buffers[2]);
    glBufferData(GL_SHADER_STORAGE_BUFFER, 16, 0, GL_DYNAMIC_COPY);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, buffers[2]);
    glDispatchCompute(1, 1, 1);
    glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT | GL_TEXTURE_FETCH_BARRIER_BIT | GL_COMMAND_BARRIER_BIT);
    link("#version 310 es\nlayout(location = 0) in vec2 p; out vec2 uv; void main() { uv = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        "#version 310 es\nprecision mediump float; uniform sampler2D t; in vec2 uv; out vec4 o; void main() { o = texture(t, uv); }", 0);
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    GLuint quad;
    glGenBuffers(1, &quad);
    const float corners[] = { -1, -1, 1, -1, -1, 1, 1, 1 };
    glBindBuffer(GL_ARRAY_BUFFER, quad);
    glBufferData(GL_ARRAY_BUFFER, sizeof corners, corners, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glBindBuffer(GL_DRAW_INDIRECT_BUFFER, buffers[2]);
    glViewport(0, 0, width, height);
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    glDrawArraysIndirect(GL_TRIANGLE_STRIP, 0);
    int center[] = { width / 2, height / 2 };
    report("computed", center, 1);
    eglSwapBuffers(display, surface);
}

static void gles1_scenes(void)
{
    glViewport(0, 0, width, height);
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrthof(0, 2, 0, 2, -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    // the left half: the current color
    const float half[] = { 0, 0, 1, 0, 1, 2, 0, 0, 1, 2, 0, 2 };
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 0, half);
    glColor4f(1, 0.5f, 0, 1);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    // the right half: a white texture modulated by a green color array
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    const unsigned char white[] = { 255, 255, 255, 255 };
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, white);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glEnable(GL_TEXTURE_2D);
    unsigned char colors[24];
    for(int i = 0; i < 24; i++) colors[i] = (i % 4 == 1 || i % 4 == 3) ? 255 : 0;
    glEnableClientState(GL_COLOR_ARRAY);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
    const float uv[12] = { 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f };
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glTexCoordPointer(2, GL_FLOAT, 0, uv);
    glTranslatef(1, 0, 0);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    int fixed_points[] = { 10, 10, width - 10, 10 };
    report("gles1", fixed_points, 2);
    // a light along +z on the left half: the material's diffuse
    glDisable(GL_TEXTURE_2D);
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glLoadIdentity();
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    const float position[] = { 0, 0, 1, 0 }, diffuse[] = { 0.5f, 0.5f, 0.5f, 1 }, black[] = { 0, 0, 0, 1 };
    glLightfv(GL_LIGHT0, GL_POSITION, position);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
    glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, black);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, black);
    glNormal3f(0, 0, 1);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glDisable(GL_LIGHTING);
    int light_points[] = { 10, 10 };
    report("light", light_points, 1);
    // draw_texture: a 2 by 1 texture's right texel (blue) at the top right quarter
    const unsigned char texels[] = { 255, 0, 0, 0, 0, 255 };
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 1, 0, GL_RGB, GL_UNSIGNED_BYTE, texels);
    const GLint crop[] = { 1, 0, 1, 1 };
    glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, crop);
    // (the texture's own filtering applies: LINEAR with REPEAT would blend the red texel in at the edge)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glEnable(GL_TEXTURE_2D);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glDrawTexiOES(width / 2, height / 2, 0, width / 2, height / 2);
    int tex_points[] = { width - 10, height - 10, 10, 10 };
    report("drawtex", tex_points, 2);
    eglSwapBuffers(display, surface);
}

/** EGL: swap intervals, a fence, a pbuffer surface, a texture made in one context and sampled in another of its share group */
static void egl_scenes(EGLContext context2)
{
    PFNEGLCREATESYNCKHRPROC create_sync = (PFNEGLCREATESYNCKHRPROC)eglGetProcAddress("eglCreateSyncKHR");
    PFNEGLCLIENTWAITSYNCKHRPROC wait_sync = (PFNEGLCLIENTWAITSYNCKHRPROC)eglGetProcAddress("eglClientWaitSyncKHR");
    PFNEGLGETSYNCATTRIBKHRPROC sync_attrib = (PFNEGLGETSYNCATTRIBKHRPROC)eglGetProcAddress("eglGetSyncAttribKHR");
    PFNEGLDESTROYSYNCKHRPROC destroy_sync = (PFNEGLDESTROYSYNCKHRPROC)eglGetProcAddress("eglDestroySyncKHR");
    eglMakeCurrent(display, surface, surface, context2);
    EGLBoolean interval0 = eglSwapInterval(display, 0), interval1 = eglSwapInterval(display, 1);
    glClearColor(0, 0, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    EGLSyncKHR sync = create_sync ? create_sync(display, EGL_SYNC_FENCE_KHR, 0) : EGL_NO_SYNC_KHR;
    EGLint waited = 0, status = 0;
    if(sync != EGL_NO_SYNC_KHR)
    {
        waited = wait_sync(display, sync, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 1000000000ull);
        sync_attrib(display, sync, EGL_SYNC_STATUS_KHR, &status);
        destroy_sync(display, sync);
    }
    LOG("V86_GLES egl intervals=%d,%d sync=%d wait=%x status=%x", interval0, interval1, sync != EGL_NO_SYNC_KHR, waited, status);
    // a 32 by 32 pbuffer, cleared yellow
    const EGLint pbuffer_attributes[] = { EGL_WIDTH, 32, EGL_HEIGHT, 32, EGL_NONE };
    EGLSurface pbuffer = eglCreatePbufferSurface(display, config, pbuffer_attributes);
    eglMakeCurrent(display, pbuffer, pbuffer, context2);
    glViewport(0, 0, 32, 32);
    glClearColor(1, 1, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    int pbuffer_points[] = { 16, 16 };
    report("pbuffer", pbuffer_points, 1);
    // a magenta texture made in context2, sampled in context3 (context2's share group)
    GLuint texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    const unsigned char magenta[] = { 255, 0, 255, 255 };
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, magenta);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glFinish();
    const EGLint version2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
    EGLContext context3 = eglCreateContext(display, config, context2, version2);
    eglMakeCurrent(display, pbuffer, pbuffer, context3);
    glViewport(0, 0, 32, 32);
    GLuint program = glCreateProgram();
    glAttachShader(program, compile(GL_VERTEX_SHADER, "attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }"));
    glAttachShader(program, compile(GL_FRAGMENT_SHADER, "precision mediump float; uniform sampler2D t; void main() { gl_FragColor = texture2D(t, vec2(0.5)); }"));
    glBindAttribLocation(program, 0, "p");
    glLinkProgram(program);
    glUseProgram(program);
    glBindTexture(GL_TEXTURE_2D, texture);
    const float triangle[] = { -1, -1, 3, -1, -1, 3 };
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, triangle);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    report("shared", pbuffer_points, 1);
    eglMakeCurrent(display, surface, surface, context2);
    eglDestroyContext(display, context3);
    eglDestroySurface(display, pbuffer);
}

static void* run(void* argument)
{
    ANativeWindow* window = (ANativeWindow*)argument;
    display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    eglInitialize(display, 0, 0);
    const EGLint attributes[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_NONE };
    EGLint count = 0;
    eglChooseConfig(display, attributes, &config, 1, &count);
    surface = eglCreateWindowSurface(display, config, window, 0);
    eglQuerySurface(display, surface, EGL_WIDTH, &width);
    eglQuerySurface(display, surface, EGL_HEIGHT, &height);
    LOG("V86_GLES window %dx%d configs %d vendor", width, height, count);
    const EGLint version2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
    EGLContext context2 = eglCreateContext(display, config, EGL_NO_CONTEXT, version2);
    eglMakeCurrent(display, surface, surface, context2);
    LOG("V86_GLES gles2 %s / %s", glGetString(GL_VERSION), glGetString(GL_RENDERER));
    gles2_scenes();
    const EGLint version1[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE };
    EGLContext context1 = eglCreateContext(display, config, EGL_NO_CONTEXT, version1);
    eglMakeCurrent(display, surface, surface, context1);
    LOG("V86_GLES gles1 %s", glGetString(GL_VERSION));
    gles1_scenes();
    egl_scenes(context2);
    // (GLES 3.0: when the host announces it)
    const EGLint version3[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
    EGLContext context3 = eglCreateContext(display, config, EGL_NO_CONTEXT, version3);
    if(context3 != EGL_NO_CONTEXT && eglMakeCurrent(display, surface, surface, context3))
    {
        LOG("V86_GLES gles3 %s / %s", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION));
        gles3_scenes();
        GLint minor = 0;
        glGetIntegerv(GL_MINOR_VERSION, &minor);
        if(minor >= 1) gles31_scenes();
        // (GLES 3.2's reach through the guest's library: each step's GL error, the host's or the library's own)
        if(minor >= 2)
        {
            while(glGetError()) {}
            GLuint geometry = glCreateShader(0x8DD9);
            GLenum geometry_error = glGetError();
            GLuint tess = glCreateShader(0x8E88);
            GLenum tess_error = glGetError();
            GLuint texture;
            glGenTextures(1, &texture);
            glBindTexture(0x9009, texture);
            GLenum cube_array_error = glGetError();
            glBindTexture(0x9009, 0);
            glBindTexture(GL_TEXTURE_2D, texture);
            const GLfloat border[] = { 1, 0, 0, 1 };
            glTexParameterfv(GL_TEXTURE_2D, 0x1004, border);
            GLenum border_error = glGetError();
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, 0x812D);
            GLenum clamp_error = glGetError();
            glBlendEquation(0x9294);
            GLenum advanced_error = glGetError();
            glBlendEquation(GL_FUNC_ADD);
            LOG("V86_GLES gles32 geometry=%u/%x tess=%u/%x cube_array=%x border=%x clamp_to_border=%x advanced_blend=%x",
                geometry, geometry_error, tess, tess_error, cube_array_error, border_error, clamp_error, advanced_error);
        }
        fps_scene();
    }
    else LOG("V86_GLES gles3 none: %x", eglGetError());
    LOG("V86_GLES_DONE");
    return 0;
}

static void window_created(ANativeActivity* activity, ANativeWindow* window)
{
    (void)activity;
    pthread_t thread;
    pthread_create(&thread, 0, run, window);
}

void ANativeActivity_onCreate(ANativeActivity* activity, void* state, size_t size)
{
    (void)state;
    (void)size;
    activity->callbacks->onNativeWindowCreated = window_created;
}
                                                                                                                                                                         source/v64/tests/a32/android_boot.mjs                                                               0000644 0000000 0000000 00000156672 00000000000 014612  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The official Android 7.1.1 emulator image (armeabi-v7a-25_r18, Google
// APIs) on cpu_type "arm32" and the ranchu machine (docs/aarch32-plan.md
// R7.1): its kernel-ranchu, ramdisk.img, system.img (read-only, vda), an
// empty /cache (vdb, src/android/ext4.js) and userdata.img (vdc, its
// changes kept in memory), the emulator's kernel command line
// (src/virt/ranchu.js). The test waits for the console's shell
// (userdebug), then asks it for sys.boot_completed until it is 1, and
// takes a screenshot of the framebuffer.
//
// The image (build/a32-android/armeabi-v7a-25_r18.zip, from Google's SDK
// repository) is unpacked into build/a32-android/armeabi-v7a/ once.
// A32_ANDROID_CORES (default 2), A32_ANDROID_MEMORY_MB (1024),
// A32_ANDROID_TIMEOUT (ms), A32_JIT=0 the interpreter only, A32_ANDROID_TAG the run's
// directory's name, A32_ANDROID_SAVE_STATE=<file> a state saved after
// boot_completed, A32_ANDROID_RESTORE_STATE=<file> that state restored
// instead of booting (the same disks), A32_ANDROID_LOGCAT=1
// the log's warnings and errors on the console. A32_ANDROID_DISK=1: as the
// VM manager boots an imported image (docs/android-images-plan.md I6): the
// zip made into one disk (tools/android_import.mjs's, build/a32-android/
// disk.img, its changes in memory), booted by the android option (device
// model ranchu_25_armeabi_v7a: the kernel and ramdisk from its partitions,
// the system, cache and userdata partitions as the virtio disks).
// A32_ANDROID_APP=1: after the home screen, a touch on its hotseat
// (goldfish_events) opens an app (the focused window changes), and a 32-bit
// APK (tests/a32/android/v86arm32.c as armeabi-v7a, tests/a64/apk.mjs) goes
// over the console (base64), is installed (pm install) and started: its log
// line and its frame. A32_ANDROID_PROBE: shell commands (";;" between
// them) whose output is printed after boot or restore (A32_ANDROID_PROBE_HOME:
// after the home screen's screenshot). A32_ANDROID_SCREEN:
// am start's arguments (-a android.settings.SETTINGS): after the home
// screen the activity is started and its screen taken (screen.png), then
// swiped up and down for a minute: the frames a second the screen shows
// (A32_ANDROID_RATE_AFTER=<rate>: the clock's rate changed first;
// A32_ANDROID_PROBE_SCREEN: shell commands run with it up).
// A32_ANDROID_GPU=host: the device model's GPU mode "host" (qemu.gles=1,
// ranchu_gpu "host": the GLES host, docs/gles-proxy-plan.md); the GLES
// calls' counts go to the run's gles.json, its batches to gles-batches.bin
// (read by tools/gles/batches.mjs), and an opcode the host does not know,
// or a command it cannot decode, fails the test. A32_ANDROID_RENDERER=chrome:
// the renderer is a real GPU's (headless Chrome, tests/gles/chrome_renderer.mjs),
// the screen SurfaceFlinger's frames; otherwise nothing is drawn.
// A32_ANDROID_PROPS="name=value,...": boot properties changed (an empty
// value removes one: "ro.config.low_ram="); A32_ANDROID_BOOTANIM=1: the boot
// animation on (both for the files' boot, not A32_ANDROID_DISK);
// A32_ANDROID_BOOT_SHOTS=1: a screenshot every 20 s until the boot completes.
// A32_ANDROID_GLES_APP=1 (with A32_ANDROID_GPU=host): after the home screen,
// tests/a32/android/v86gles.c's APK (GLES 2.0, 1.1 and 3.0 scenes read back with
// glReadPixels: docs/gles-proxy-plan.md E4) is installed and started, and
// the pixels it logs are checked against GLES's rules.
// A32_ANDROID_DEQP=1 (with A32_ANDROID_GPU=host): dEQP-GLES2 and dEQP-EGL
// from CTS 7.1_r29 (tools/a32_cts.mjs fetches them) on a fourth virtio disk
// (ext2, mke2fs -d), copied in with su, installed, run by its
// instrumentation in chunks (the results from its status lines); the subset (docs/gles-proxy-plan.md E4): every
// state_query and negative_api case, dEQP-EGL.info, and every ninth other
// functional case (A32_ANDROID_DEQP_STEP another; A32_ANDROID_DEQP_FILTER a
// pattern of cases to keep; A32_ANDROID_DEQP_IMAGES=1 the log with its images
// and shader sources in the instrumentation's output, kept); each case's status into the run's deqp.json.
// A32_ANDROID_DEQP_SUITE=gles3 (or gles31): that suite's case list in GLES 2's
// place (docs/gles3-plan.md L4). A32_ANDROID_DEQP_RESUME: an earlier run's
// deqp.json, whose passed and unsupported cases are not run again (the rest,
// failures among them, are); the run's deqp.json has both. A32_ANDROID_GLES_VERSION: the GLES version
// the host announces (src/android/devices.js's default otherwise).
// A32_ANDROID_MEDIA=1 (with A32_ANDROID_GPU=host): Replica Island (GLES 1)
// and Shattered Pixel Dungeon (libGDX, GLES 2) from F-Droid on a fourth
// disk, each played for a minute; a green H.264 clip in Gallery's player
// (the decoder's YUV frames, converted by gralloc).
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { ROOT } from "../lib/alpine_image.mjs";
import { PictureSink, save_png } from "../lib/picture_sink.mjs";
import { make_empty_ext4 } from "../../src/android/ext4.js";
import { ranchu_cmdline } from "../../src/virt/ranchu.js";
import { build_apk, build_native_lib } from "../a64/apk.mjs";
import { RANCHU_25_ARMEABI_V7A, ranchu_gpu_mode } from "../../src/android/devices.js";
import { recording_renderer } from "../gles/lib.mjs";
import { chrome_renderer } from "../gles/chrome_renderer.mjs";
import { ramdisk_overlay } from "../../src/android/ramdisk_overlay.js";

const directory = ROOT + "build/a32-android/";
const image = directory + "armeabi-v7a/";
const zip = directory + "armeabi-v7a-25_r18.zip";
const FILES = ["kernel-ranchu", "ramdisk.img", "system.img", "userdata.img", "build.prop"];
if(!FILES.every(f => fs.existsSync(image + f)))
{
    assert.ok(fs.existsSync(zip), zip + " is missing (Google's SDK repository: system-images/android-25/google_apis/armeabi-v7a)");
    const unpack = spawnSync("bsdtar", ["-xf", zip, "-C", directory, ...FILES.map(f => "armeabi-v7a/" + f)], { encoding: "utf8" });
    assert.equal(unpack.status, 0, unpack.stderr);
}
const cores = Number(process.env.A32_ANDROID_CORES || 2);
const memory_mb = Number(process.env.A32_ANDROID_MEMORY_MB || 1024);
const timeout = Number(process.env.A32_ANDROID_TIMEOUT || 3600000);
const jit = process.env.A32_JIT !== "0";
const from_disk = process.env.A32_ANDROID_DISK === "1";
const gpu_mode = process.env.A32_ANDROID_GPU || "guest";
// (A32_ANDROID_GLES_VERSION: the version the GLES host announces, the device model's default unless given)
const gpu = ranchu_gpu_mode(RANCHU_25_ARMEABI_V7A, gpu_mode, process.env.A32_ANDROID_GLES_VERSION);
const tag = process.env.A32_ANDROID_TAG || `v86-${jit ? "jit-" : ""}${from_disk ? "disk-" : ""}${gpu.gles ? "gles-" : ""}${cores}c`;
const disk = directory + "disk.img";
if(from_disk && !fs.existsSync(disk))
{
    const made = spawnSync(process.execPath, [ROOT + "tools/android_import.mjs", zip, disk], { encoding: "utf8" });
    assert.equal(made.status, 0, made.stdout + made.stderr);
}
const run_directory = directory + "runs/" + tag + "/";
fs.mkdirSync(run_directory, { recursive: true });

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const gles_renderer = !gpu.gles ? null : process.env.A32_ANDROID_RENDERER === "chrome" ?
    await chrome_renderer({ record: run_directory + "gles-batches.bin" }) : recording_renderer(run_directory + "gles-batches.bin");
const sink = new PictureSink();
const cmdline = ranchu_cmdline({ arm32: true, bootanim: process.env.A32_ANDROID_BOOTANIM === "1", gles: gpu.gles, extra: process.env.A32_ANDROID_CMDLINE });
const properties = Object.assign({}, RANCHU_25_ARMEABI_V7A.properties, gpu.properties);
for(const pair of (process.env.A32_ANDROID_PROPS || "").split(",").filter(Boolean))
{
    const [name, value] = [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)];
    if(value) properties[name] = value;
    else delete properties[name];
}
const restore = process.env.A32_ANDROID_RESTORE_STATE, save = process.env.A32_ANDROID_SAVE_STATE;

/**
 * A copy of system.img (a clone: APFS shares its blocks) whose
 * libEGL_emulation names EGL_KHR_create_context: dEQP wants the name for a
 * GLES 3.x context. The guest's EGL takes the extension's attributes (the
 * major and minor versions, "no ES 3.1 support") but its extension string is
 * a constant without the name; the name goes over the native sync
 * extensions' names after the constant, which it uses only with a host that
 * announces native sync (ours does not).
 * @return {string} the copy's path
 */
function create_context_system(source, target)
{
    const constant = "EGL_ANDROID_image_native_buffer EGL_KHR_fence_sync EGL_KHR_image_base EGL_KHR_gl_texture_2d_image ";
    const old = Buffer.from(constant + "\0EGL_ANDROID_native_fence_sync \0EGL_KHR_wait_sync \0", "latin1");
    const patched = Buffer.alloc(old.length);
    Buffer.from(constant + "EGL_KHR_create_context ", "latin1").copy(patched);
    if(fs.existsSync(target) && fs.statSync(target).mtimeMs >= fs.statSync(source).mtimeMs) return target;
    const partial = target + ".partial";
    fs.copyFileSync(source, partial, fs.constants.COPYFILE_FICLONE);
    const fd = fs.openSync(partial, "r+");
    const chunk = Buffer.alloc(64 << 20);
    let found = 0;
    for(let at = 0; ; at += chunk.length - old.length)
    {
        const n = fs.readSync(fd, chunk, 0, chunk.length, at);
        for(let i = chunk.subarray(0, n).indexOf(old); i >= 0; i = chunk.subarray(0, n).indexOf(old, i + 1))
        {
            fs.writeSync(fd, patched, 0, patched.length, at + i);
            found++;
        }
        if(n < chunk.length) break;
    }
    fs.closeSync(fd);
    assert.ok(found > 0, "libEGL_emulation's extension string in system.img");
    fs.renameSync(partial, target);
    return target;
}

// (dEQP: its files on an ext2 disk of their own, and the cases to run)
let deqp = null;
/** The dEQP results a resumed run does not run again */
const DEQP_DONE = new Set(["Pass", "NotSupported", "QualityWarning", "CompatibilityWarning"]);
if(process.env.A32_ANDROID_DEQP === "1")
{
    const { fetch_files, DEQP_FILES } = await import("../../tools/a32_cts.mjs");
    // (A32_ANDROID_DEQP_SUITE: gles2, or gles3 / gles31 (docs/gles3-plan.md L4): its case list instead of GLES 2's)
    const suite = process.env.A32_ANDROID_DEQP_SUITE || "gles2";
    const [apk, list, egl] = await fetch_files([DEQP_FILES[0], suite + "-master.txt", ...DEQP_FILES.slice(2)], true);
    const prefix = "dEQP-" + suite.toUpperCase();
    const step = Number(process.env.A32_ANDROID_DEQP_STEP || 9);
    const filter = new RegExp(process.env.A32_ANDROID_DEQP_FILTER || ".");
    const all = fs.readFileSync(list, "utf8").split("\n").filter(Boolean);
    const sampled = all.filter((c, i) => /\.(state_query|negative_api)\./.test(c) || c.startsWith(prefix + ".info.") ||
        c.startsWith(prefix + ".functional.") && i % step === 0);
    // (A32_ANDROID_DEQP_RESUME: an earlier run's results; its passed and unsupported cases kept, not run)
    const earlier = process.env.A32_ANDROID_DEQP_RESUME ? JSON.parse(fs.readFileSync(process.env.A32_ANDROID_DEQP_RESUME, "utf8")) : {};
    const kept = Object.fromEntries(Object.entries(earlier).filter(([, status]) => DEQP_DONE.has(status)));
    const keep = c => filter.test(c) && !(c in kept);
    const cases = { [prefix]: sampled.filter(keep),
        "dEQP-EGL": fs.readFileSync(egl, "utf8").split("\n").filter(c => c.startsWith("dEQP-EGL.info.") && keep(c)) };
    const root = run_directory + "deqp-disk/";
    fs.rmSync(root, { recursive: true, force: true });
    fs.mkdirSync(root, { recursive: true });
    fs.copyFileSync(apk, root + "deqp.apk");
    const chunks = [];
    for(const [pkg, list] of Object.entries(cases))
    {
        for(let i = 0; i < list.length; i += 150) chunks.push({ pkg, cases: list.slice(i, i + 150), name: `${pkg}-${chunks.length}.txt` });
    }
    for(const chunk of chunks) fs.writeFileSync(root + chunk.name, chunk.cases.join("\n") + "\n");
    const image = run_directory + "deqp.img";
    fs.rmSync(image, { force: true });
    const made = spawnSync("/opt/homebrew/opt/e2fsprogs/sbin/mke2fs", ["-q", "-t", "ext2", "-b", "4096", "-d", root, image, "160M"], { encoding: "utf8" });
    assert.equal(made.status, 0, made.stderr);
    // (GLES 3.x's suites: EGL_KHR_create_context named, create_context_system)
    deqp = { image, chunks, kept, system: suite === "gles2" ? null : create_context_system(directory + "armeabi-v7a/system.img",
        directory + "system-egl-create-context.img") };
    console.log(`dEQP: ${cases[prefix].length} ${prefix} and ${cases["dEQP-EGL"].length} EGL cases in ${chunks.length} runs` +
        (Object.keys(kept).length ? `, ${Object.keys(kept).length} kept from ${process.env.A32_ANDROID_DEQP_RESUME}` : ""));
}
// A32_ANDROID_MEDIA=1: two open-source games from F-Droid (Replica Island
// 1.4, archive; Shattered Pixel Dungeon 4.0.2, F-Droid's build) and a green
// H.264 clip (ffmpeg) on a fourth virtio disk, as dEQP's
let media = null;
if(process.env.A32_ANDROID_MEDIA === "1")
{
    assert.ok(!deqp, "A32_ANDROID_MEDIA and A32_ANDROID_DEQP both want the fourth disk");
    const apks = ROOT + "build/a32-android/apks/";
    const games = [
        // (steps, each with a screenshot after it: into the game. [x, y] a tap in the screen's pixels; {view} the
        // view uiautomator finds by that pattern (its text or resource id) tapped, wherever the app's slow start
        // left it ({at} the tap when it finds none). Replica Island's menus are views, in landscape: the control
        // setup's "Leave it this way", the news' "Rock on!", Start, the middle difficulty, then the first
        // conversation; playing: its game activity, or the conversations it opens over the level, the arrow keys
        // (the control scheme it picks for the emulator's keyboard). Shattered Pixel Dungeon draws everything
        // itself: "Enter the Dungeon", the warrior, Start, the story's Continue (four times: it shows once the
        // level is made, but has never answered a tap here), the story's fold arrow (it hides the text: taps do
        // reach the scene), a tap that brings the text back, and Enter (a key's release is Continue too: into the
        // level, where taps walk); {key} set-1 scancodes)
        { name: "replicaisland", package: "com.replica.replicaisland", file: "replicaisland_14.apk",
            steps: [{ view: 'text="Leave it this way"', at: [90, 225] }, { view: 'text="Rock on!"', at: [90, 365] },
                { view: 'resource-id="[^"]*startButton"' }, { view: 'resource-id="[^"]*kidsButton"' }, [240, 400]],
            playing: /AndouKun|ConversationDialogActivity/, keys: true,
            url: "https://f-droid.org/archive/com.replica.replicaisland_14.apk", sha256: "35d900fabe6bbc05899c3fcc0fb5926a5a901d807889d0d111b34a1e87d7acde" },
        { name: "shatteredpixeldungeon", package: "com.shatteredpixel.shatteredpixeldungeon", file: "shatteredpixeldungeon_921.apk",
            steps: [[240, 750], [40, 770], [240, 700], [240, 565], [240, 565], [240, 565], [240, 565], [370, 570], [240, 400],
                { key: [0x1C, 0x9C] }], log: true,
            url: "https://f-droid.org/repo/com.shatteredpixel.shatteredpixeldungeon_921.apk", sha256: "dbd8205680e89758babf608212a1fb3f498f732118b1e3c0b9fd33bf67486a99" },
    ];
    const root = run_directory + "media-disk/";
    fs.rmSync(root, { recursive: true, force: true });
    fs.mkdirSync(root, { recursive: true });
    for(const game of games)
    {
        if(!fs.existsSync(apks + game.file))
        {
            fs.mkdirSync(apks, { recursive: true });
            const response = await fetch(game.url);
            assert.equal(response.status, 200, game.url);
            fs.writeFileSync(apks + game.file, Buffer.from(await response.arrayBuffer()));
        }
        const { createHash: create_hash } = await import("node:crypto");
        assert.equal(create_hash("sha256").update(fs.readFileSync(apks + game.file)).digest("hex"), game.sha256, game.file);
        fs.copyFileSync(apks + game.file, root + game.name + ".apk");
    }
    // (3 s of green, 176 by 144, H.264 baseline: the software decoder's YUV frames through gralloc)
    const clip = spawnSync("ffmpeg", ["-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=0x00FF00:s=176x144:d=3:r=15", "-c:v", "libx264",
        "-profile:v", "baseline", "-pix_fmt", "yuv420p", root + "green.mp4"], { encoding: "utf8" });
    assert.equal(clip.status, 0, clip.stderr);
    const image = run_directory + "media.img";
    fs.rmSync(image, { force: true });
    const made = spawnSync("/opt/homebrew/opt/e2fsprogs/sbin/mke2fs", ["-q", "-t", "ext2", "-b", "4096", "-d", root, image, "96M"], { encoding: "utf8" });
    assert.equal(made.status, 0, made.stderr);
    media = { image, games };
}
const ramdisk = await ramdisk_overlay(new Uint8Array(fs.readFileSync(image + "ramdisk.img")), RANCHU_25_ARMEABI_V7A);
const emulator = new V86({
    cpu_type: "arm32", machine_type: "ranchu", cpu_cores: cores, memory_size: memory_mb << 20, log_level: 0, autostart: !restore,
    wasm_path: process.env.A32_WASM || ROOT + "build/v86-arm64.wasm",
    ...(from_disk ? {
        android: { device: "ranchu_25_armeabi_v7a", gpu_mode }, cmdline: process.env.A32_ANDROID_CMDLINE,
        virtio_disks: [{ url: disk, async: true, size: fs.statSync(disk).size }],
    } : {
        // (the ramdisk with the device model's init additions, as the bootloader gives it)
        kernel: { url: image + "kernel-ranchu" }, initrd: { buffer: ramdisk.buffer.slice(ramdisk.byteOffset, ramdisk.byteOffset + ramdisk.length) }, cmdline,
        ranchu_properties: properties, ranchu_gpu: gpu.ranchu_gpu, ...(gpu.gles_version ? { ranchu_gles_version: gpu.gles_version } : {}),
        // (the device model's clock rate, as the bootloader hands it over; A32_ANDROID_RATE another)
        ...(process.env.A32_PARALLEL === "1" ? {} : { cpu_clock: { rate: Number(process.env.A32_ANDROID_RATE || RANCHU_25_ARMEABI_V7A.clock_rate) } }),
        virtio_disks: [
            { url: deqp && deqp.system || image + "system.img", async: true, size: fs.statSync(image + "system.img").size, readonly: true },
            { buffer: make_empty_ext4(64 << 20, "cache", 1595289711).buffer },
            { url: image + "userdata.img", async: true, size: fs.statSync(image + "userdata.img").size },
            // (dEQP's disk: vdd)
            ...(deqp ? [{ url: deqp.image, async: true, size: fs.statSync(deqp.image).size, readonly: true }] : []),
            ...(media ? [{ url: media.image, async: true, size: fs.statSync(media.image).size, readonly: true }] : []),
        ],
    }),
    net_device: { type: "virtio", relay_url: "fetch" },
    // (the GLES host's batches into the run's directory; drawn by Chrome's GPU, or not)
    ...(gpu.gles ? { graphics_adapter_renderer_channel: gles_renderer } : {}),
    // (ranchu's display: the goldfish framebuffer, no display adapter)
    graphics_adapter: "none", screen_adapter: sink,
    // (A32_PARALLEL=1: the cores in vCPU workers)
    ...(process.env.A32_PARALLEL === "1" ? { parallel: true, parallel_wasm_path: ROOT + "build/v86-arm64-parallel.wasm" } : {}),
    // (A32_JIT_SWITCHES: more of them, "name=value,...")
    ...(jit ? { jit_switches: { a64_page: 1, ...Object.fromEntries((process.env.A32_JIT_SWITCHES || "").split(",").filter(Boolean)
        .map(p => [p.split("=")[0], +p.split("=")[1]])) } } : {}),
});
emulator.add_listener("emulator-error", error => { console.error("emulator-error:", error); process.exit(1); });
let transcript = "";
emulator.add_listener("serial0-output-byte", byte => { transcript += String.fromCharCode(byte); });
const log = run_directory + "serial.log";
// (the GLES host's counts, A32_ANDROID_GPU=host)
const gles_summary = () => emulator.v86?.cpu?.devices?.gles?.device["summary"]();
const write_gles = () => { const summary = gles_summary(); if(summary) fs.writeFileSync(run_directory + "gles.json", JSON.stringify(summary, null, 1)); };
const flush = setInterval(() => { fs.writeFileSync(log, transcript); write_gles(); }, 2000);
const started = performance.now();
const seconds = () => ((performance.now() - started) / 1000).toFixed(0);
const wait = (test, what, limit = timeout) => new Promise((resolve, reject) => {
    const deadline = performance.now() + limit;
    const poll = setInterval(() => {
        const found = test();
        if(found) { clearInterval(poll); resolve(found); }
        else if(performance.now() > deadline)
        {
            clearInterval(poll);
            reject(new Error(`no ${what} after ${seconds()} s: ` + JSON.stringify(emulator.v86?.cpu?.get_diagnostics?.() ?? {}).slice(0, 3000) +
                "\n" + transcript.slice(-4000)));
        }
    }, 250);
});
const marks = {};
const mark = name => { if(!marks[name]) { marks[name] = Math.round(performance.now() - started); console.log(`${seconds()} s: ${name}`); } };
try
{
    if(restore)
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const bytes = fs.readFileSync(restore);
        await emulator.restore_state(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length));
        await emulator.run();
        mark("restored");
    }
    else
    {
        // (A32_ANDROID_BOOT_SHOTS=1: the screen every 20 s until the boot completes: the boot animation)
        let shot_number = 0;
        const boot_shots = process.env.A32_ANDROID_BOOT_SHOTS === "1" ?
            setInterval(() => save_png(sink, run_directory, "boot-" + String(++shot_number).padStart(2, "0")), 20000) : null;
        await wait(() => /Freeing unused kernel memory/.test(transcript), "the kernel's init");
        mark("kernel");
        await wait(() => /init: .*(starting|Starting) service|init: .*console/.test(transcript) || /\n[^\n]*[$#] $/.test(transcript), "Android's init");
        mark("init");
        // the console's shell (ro.debuggable): until it answers (the typed line's
        // echo cannot match: the answer is computed)
        let tick = 0;
        await wait(() => {
            if(/A32_SHELL_42/.test(transcript)) return true;
            if(tick++ % 20 === 0) emulator.serial0_send("\necho A32_SHELL_$((40+2))\n");
            return false;
        }, "the console's shell");
        mark("shell");
        // (A32_ANDROID_LOGCAT=1: the log's warnings and errors on the console too)
        if(process.env.A32_ANDROID_LOGCAT === "1") emulator.serial0_send("logcat -b main -b system -b crash -v brief '*:W' &\n");
        tick = 0;
        await wait(() => {
            if(/A32_BOOT_1_X/.test(transcript)) return true;
            if(tick++ % 40 === 0) emulator.serial0_send("echo A32_BOOT_$(getprop sys.boot_completed)_X\n");
            return false;
        }, "sys.boot_completed");
        mark("boot_completed");
        if(boot_shots) clearInterval(boot_shots);
        // (the launcher's first frames)
        await new Promise(resolve => setTimeout(resolve, 20000));
        save_png(sink, run_directory, "boot-completed");
        if(save)
        {
            fs.writeFileSync(save, new Uint8Array(await emulator.save_state()));
            console.log("saved " + save);
        }
    }
    // (the page tier's steps and helper calls: what is not compiled natively)
    const cpu = emulator.v86.cpu;
    if(cpu.step_stats) fs.writeFileSync(run_directory + "steps.json", JSON.stringify(cpu.step_stats(40), null, 1));
    // the screen woken and unlocked, the home screen; what the system says of them
    const fb = emulator.v86.cpu.devices.goldfish_fb;
    const ask = async (command, marker, limit = 120000) =>
    {
        const from = transcript.length;
        emulator.serial0_send(command + "; echo " + marker + "_$((1+1))\n");
        await wait(() => transcript.indexOf(marker + "_2", from) >= 0, marker, limit);
        return transcript.slice(from, transcript.indexOf(marker + "_2", from));
    };
    // (A32_ANDROID_PROBE: shell commands, ";;" between them, run and printed first)
    for(const command of (process.env.A32_ANDROID_PROBE || "").split(";;").filter(c => c.trim()))
    {
        console.log(`probe: ${command}\n` + (await ask(command, "A32_PROBE", 600000)).split("\n").slice(1).join("\n").slice(0, 8000));
    }
    const state = await ask("getprop ro.config.low_ram; getprop qemu.gles; getprop qemu.sf.lcd_density; " +
        "dumpsys power | grep -E 'mWakefulness=|mScreenOn|Display Power' ; dumpsys window | grep -E 'mCurrentFocus|mShowingLockscreen|mScreenOnFully'", "A32_STATE", 600000);
    console.log("before: " + state.replace(/\s+/g, " ").slice(0, 600) + "; frames " + fb.frames);
    // (each input or wm starts a Dalvik VM: a minute or more here)
    await ask("input keyevent 224; sleep 2; wm dismiss-keyguard; sleep 2; input keyevent 3", "A32_HOME", 900000);
    await new Promise(resolve => setTimeout(resolve, 40000));
    const after = await ask("dumpsys window | grep -E 'mCurrentFocus|mShowingLockscreen'", "A32_AFTER", 600000);
    console.log("after: " + after.replace(/\s+/g, " ").slice(0, 400) + "; frames " + fb.frames);
    const shot = save_png(sink, run_directory, "home");
    // (A32_ANDROID_PROBE_HOME: likewise, with the home screen up)
    for(const command of (process.env.A32_ANDROID_PROBE_HOME || "").split(";;").filter(c => c.trim()))
    {
        console.log(`probe (home): ${command}\n` + (await ask(command, "A32_PROBE", 600000)).split("\n").slice(1).join("\n").slice(0, 8000));
    }
    const focus = async () =>
    {
        // (between two windows there is none: asked again)
        for(let i = 0; i < 3; i++)
        {
            const now = (await ask("dumpsys window | grep mCurrentFocus", "A32_FOCUS", 600000)).match(/mCurrentFocus=\S+ \S+ ([^}]+)\}/)?.[1];
            if(now) return now;
            await new Promise(resolve => setTimeout(resolve, 5000));
        }
        return "";
    };
    // (background ANRs are shown, not killed: their dialogs' Wait, found by uiautomator)
    const dismiss_dialogs = async () =>
    {
        for(let i = 0; i < 8 && /Not Responding|Application Error/.test(await focus()); i++)
        {
            // (an ANR's Wait; a crash's "Close app")
            const dump = await ask("uiautomator dump /data/local/tmp/ui.xml >/dev/null 2>&1; " +
                "grep -o -E 'text=\"(Wait|Close app|OK)\"[^>]*bounds=\"[^\"]*\"' /data/local/tmp/ui.xml | head -1", "A32_UI", 900000);
            const m = /bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/.exec(dump);
            if(!m) break;
            await ask(`input tap ${(+m[1] + +m[3]) >> 1} ${(+m[2] + +m[4]) >> 1}`, "A32_TAP", 600000);
        }
    };
    // (A32_ANDROID_SCREEN: an activity started, its screen taken: the same
    // picture in both GPU modes, docs/gles-proxy-plan.md E3's comparison)
    // (A32_ANDROID_RATE_AFTER: the machine clock's rate from here on, e.g. 1
    // after a boot at the device model's tenth: how fast the screen can go)
    if(process.env.A32_ANDROID_RATE_AFTER)
    {
        emulator.v86.cpu.clock.rate = Number(process.env.A32_ANDROID_RATE_AFTER);
        console.log("clock rate now " + emulator.v86.cpu.clock.rate);
    }
    if(process.env.A32_ANDROID_SCREEN)
    {
        await dismiss_dialogs();
        const started = await ask("am start -W " + process.env.A32_ANDROID_SCREEN, "A32_SCREEN", 900000);
        console.log("screen: " + started.replace(/\s+/g, " ").slice(-200));
        // (until the screen below its app bar has content: more than a few
        // colors in the middle rows; the guest's clock is slow, a list loads
        // late; at most ten minutes)
        const colors = () =>
        {
            const seen = new Set();
            for(let y = Math.round(fb.height * 0.2); y < fb.height * 0.85; y += 4)
            {
                for(let x = 0; x < fb.width; x += 4)
                {
                    const at = (y * sink.width + x) * 4;
                    seen.add(sink.rgba[at] << 16 | sink.rgba[at + 1] << 8 | sink.rgba[at + 2]);
                }
            }
            return seen.size;
        };
        const loaded_by = performance.now() + 600000;
        while(colors() < 16 && performance.now() < loaded_by)
        {
            await new Promise(resolve => setTimeout(resolve, 15000));
            await dismiss_dialogs();
        }
        console.log("screen focus: " + await focus() + "; frames " + fb.frames + "; " + colors() + " colors");
        save_png(sink, run_directory, "screen");
        // (A32_ANDROID_PROBE_SCREEN: shell commands with the activity up)
        for(const command of (process.env.A32_ANDROID_PROBE_SCREEN || "").split(";;").filter(c => c.trim()))
        {
            console.log(`probe (screen): ${command}\n` + (await ask(command, "A32_PROBE", 900000)).split("\n").slice(1).join("\n").slice(0, 8000));
        }
        const events = emulator.v86.cpu.devices.goldfish_events;
        const swipe = async (y0, y1, settle = 2500) =>
        {
            events.absolute([fb.width / 2, y0, fb.width, fb.height]);
            events.click([true]);
            for(let i = 1; i <= 10; i++)
            {
                await new Promise(resolve => setTimeout(resolve, 50));
                events.absolute([fb.width / 2, y0 + (y1 - y0) * i / 10, fb.width, fb.height]);
            }
            events.click([false]);
            await new Promise(resolve => setTimeout(resolve, settle));
        };
        // (a scroll: Android's own swipe up inside the list, 1 s of the guest's
        // time; the harness's swipes are 50 ms of it at the slowed clock,
        // which Android takes for other gestures), the list's rows moved
        await dismiss_dialogs();
        const before_scroll = sink.rgba.slice();
        await ask(`input swipe ${fb.width / 2} ${fb.height * 0.75 | 0} ${fb.width / 2} ${fb.height * 0.35 | 0} 1000`, "A32_SCROLL", 900000);
        await new Promise(resolve => setTimeout(resolve, 20000));
        let moved = 0;
        for(let i = 0; i < sink.rgba.length; i += 4) if(sink.rgba[i] !== before_scroll[i] || sink.rgba[i + 1] !== before_scroll[i + 1]) moved++;
        console.log(`scroll: ${(100 * moved / (sink.rgba.length / 4)).toFixed(1)}% of the pixels changed`);
        save_png(sink, run_directory, "screen-scrolled-once");
        // (the frames a scrolled list draws: swipes up and down inside it for
        // a minute, the screen's frames counted, in the host's seconds)
        const pipe = emulator.v86.cpu.devices.goldfish_pipe, pipe_before = { ...pipe.stats };
        const instructions_before = emulator.get_instruction_counter();
        const frames_before = fb.frames, gles_before = gles_summary(), fps_start = performance.now();
        for(let i = 0; i < 12; i++) await swipe(i % 2 ? fb.height * 0.35 : fb.height * 0.75, i % 2 ? fb.height * 0.75 : fb.height * 0.35);
        const fps_seconds = (performance.now() - fps_start) / 1000;
        const gles_after = gles_summary();
        console.log(`fps: ${((fb.frames - frames_before) / fps_seconds).toFixed(2)} frames a second over ${fps_seconds.toFixed(0)} s of swipes` +
            (gles_after ? `; GLES host ${(gles_after.batches.cpu_ms - gles_before.batches.cpu_ms).toFixed(0)} ms of CPU, ` +
                `${gles_after.batches.batches - gles_before.batches.batches} batches, ${((gles_after.batches.bytes - gles_before.batches.bytes) / 1048576).toFixed(1)} MiB` : ""));
        // (the pipe's traps and transfers in that time: what pipe v2 would save)
        const delta = name => pipe.stats[name] - pipe_before[name];
        console.log(`pipe: ${(delta("mmio") / fps_seconds).toFixed(0)} register accesses a second, ${(delta("writes") / fps_seconds).toFixed(0)} writes ` +
            `(${(delta("bytes_written") / fps_seconds / 1024).toFixed(0)} KiB/s) and ${(delta("reads") / fps_seconds).toFixed(0)} reads a second; ` +
            `${(((emulator.get_instruction_counter() - instructions_before + 0x100000000) % 0x100000000) / fps_seconds / 1e6).toFixed(1)} M guest instructions a second`);
        save_png(sink, run_directory, "screen-scrolled");
        await ask("input keyevent 3", "A32_SCREEN_HOME", 600000);
    }
    if(process.env.A32_ANDROID_APP === "1")
    {
        await dismiss_dialogs();
        // a touch: the hotseat's icons, from the left, until one opens its app
        const home = await focus();
        const events = emulator.v86.cpu.devices.goldfish_events;
        let opened = "";
        for(const column of [0, 1, 3, 4])
        {
            events.tap(fb.width * (column + 0.5) / 5, fb.height * 0.86, fb.width, fb.height);
            await new Promise(resolve => setTimeout(resolve, 60000));
            opened = await focus();
            if(/Not Responding/.test(opened)) { await dismiss_dialogs(); opened = await focus(); }
            if(opened && opened !== home) break;
        }
        console.log(`touch: ${home} -> ${opened}`);
        save_png(sink, run_directory, "touched");
        assert.ok(opened && opened !== home, "a touch on the hotseat opens an app");
        await ask("input keyevent 3", "A32_HOME2", 600000);

        // the 32-bit APK, base64 over the console
        const lib = build_native_lib(4096, "v86arm32", ["-landroid", "-llog", "-lm"],
            { abi: "armeabi-v7a", source: ROOT + "tests/a32/android/v86arm32.c" });
        const apk = build_apk({ label: "v86 arm32", package_name: "org.v86.arm32", min_sdk: 21, target_sdk: 25,
            native: { name: "v86arm32", lib, extract: true, abi: "armeabi-v7a", software: true } });
        const text = apk.toString("base64");
        await ask("rm -f /data/local/tmp/app.b64", "A32_RM", 600000);
        for(let at = 0; at < text.length; at += 768) await ask(`echo ${text.slice(at, at + 768)} >> /data/local/tmp/app.b64`, "A32_PUT", 600000);
        const installed = await ask("base64 -d /data/local/tmp/app.b64 > /data/local/tmp/app.apk && pm install -r /data/local/tmp/app.apk", "A32_INSTALL", 900000);
        console.log("install: " + installed.replace(/\s+/g, " ").slice(-200));
        assert.match(installed, /Success/, "pm install");
        await dismiss_dialogs();
        const started = await ask("am start -W -n org.v86.arm32/android.app.NativeActivity", "A32_START", 900000);
        console.log("start: " + started.replace(/\s+/g, " ").slice(-300));
        let drew = "";
        for(let i = 0; i < 20 && !drew; i++)
        {
            await new Promise(resolve => setTimeout(resolve, 10000));
            drew = (await ask("logcat -d -s v86arm32:I", "A32_LOG", 600000)).match(/V86_ARM32_DREW \S+ sum=\S+ bits=\d+/)?.[0] || "";
        }
        console.log("app: " + drew + "; focus " + await focus() + "; frames " + fb.frames);
        assert.ok(drew, "the 32-bit app drew its frame");
        await new Promise(resolve => setTimeout(resolve, 20000));
        save_png(sink, run_directory, "app");
    }
    const gles = gles_summary();
    if(gles)
    {
        write_gles();
        const calls = Object.values(gles.counts).reduce((n, c) => n + c, 0);
        console.log(`gles: ${gles.connections} connections, ${gles.processes} processes, ${calls} calls of ${Object.keys(gles.counts).length} kinds; ` +
            "renderControl " + JSON.stringify(gles.render_control) + "; " + run_directory + "gles.json");
        assert.deepEqual(gles.unknown, {}, "no opcode the GLES host does not know");
        assert.deepEqual(gles.malformed, {}, "every command decoded");
        assert.equal(gles.broken, 0, "no broken stream");
    }
    if(process.env.A32_ANDROID_GLES_APP === "1")
    {
        const lib = build_native_lib(4096, "v86gles", ["-landroid", "-llog", "-lm", "-lEGL", "-lGLESv3", "-lGLESv2", "-lGLESv1_CM"],
            { abi: "armeabi-v7a", source: ROOT + "tests/a32/android/v86gles.c" });
        const apk = build_apk({ label: "v86 gles", package_name: "org.v86.gles", min_sdk: 21, target_sdk: 25,
            native: { name: "v86gles", lib, extract: true, abi: "armeabi-v7a" } });
        const text = apk.toString("base64");
        await ask("rm -f /data/local/tmp/gles.b64", "A32_RM", 600000);
        for(let at = 0; at < text.length; at += 768) await ask(`echo ${text.slice(at, at + 768)} >> /data/local/tmp/gles.b64`, "A32_PUT", 600000);
        const installed = await ask("base64 -d /data/local/tmp/gles.b64 > /data/local/tmp/gles.apk && pm install -r /data/local/tmp/gles.apk", "A32_INSTALL", 900000);
        assert.match(installed, /Success/, "pm install");
        await ask("logcat -c; am start -n org.v86.gles/android.app.NativeActivity", "A32_START", 900000);
        let log = "";
        for(let i = 0; i < 60 && !/V86_GLES_DONE/.test(log); i++)
        {
            await new Promise(resolve => setTimeout(resolve, 10000));
            log = await ask("logcat -d -s v86gles:I", "A32_GLES_LOG", 600000);
        }
        console.log(log.split("\n").filter(l => /V86_GLES/.test(l)).join("\n"));
        assert.match(log, /V86_GLES_DONE/, "the GLES app finished");
        // each scene's pixels: GL's rows (y from the bottom), RGB within 3
        const scenes = {};
        for(const m of log.matchAll(/V86_GLES (\w+)((?: \d+,\d+=\d+,\d+,\d+,\d+)+) glerror=(\w+)/g))
        {
            scenes[m[1]] = { error: m[3], pixels: [...m[2].matchAll(/(\d+),(\d+)=(\d+),(\d+),(\d+),(\d+)/g)].map(p => p.slice(3, 6).map(Number)) };
        }
        const expect = (scene, colors) =>
        {
            const got = scenes[scene];
            assert.ok(got, "scene " + scene);
            assert.equal(got.error, "0", scene + ": no GL error");
            colors.forEach((color, i) => assert.ok(color.every((v, j) => Math.abs(v - got.pixels[i][j]) <= 3),
                `${scene} pixel ${i}: ${got.pixels[i]} is not ${color}`));
        };
        expect("clear", [[0, 255, 0], [255, 0, 0]]);
        expect("draw", [[128, 0, 128], [255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255], [255, 0, 0]]);
        expect("fbo", [[0, 255, 255], [255, 255, 0], [255, 255, 0]]);
        expect("etc1", [[138, 138, 138]]);
        expect("gles1", [[255, 128, 0], [0, 255, 0]]);
        expect("light", [[128, 128, 128]]);
        expect("drawtex", [[0, 0, 255], [128, 128, 128]]);
        // EGL: both swap intervals taken, a fence signaled (EGL_CONDITION_SATISFIED_KHR, EGL_SIGNALED_KHR),
        // a pbuffer cleared, a texture of a share group sampled in its other context
        const egl = /V86_GLES egl intervals=(\d+),(\d+) sync=(\d+) wait=(\w+) status=(\w+)/.exec(log);
        assert.ok(egl, "the EGL scene");
        assert.deepEqual(egl.slice(1), ["1", "1", "1", "30f6", "30f2"], "swap intervals, the fence");
        expect("pbuffer", [[255, 255, 0]]);
        expect("shared", [[255, 0, 255]]);
        // GLES 3.0's scenes (docs/gles3-plan.md L4) where the host announces it
        if(gpu.gles_version !== "2.0")
        {
            assert.match(log, /V86_GLES gles3 OpenGL ES 3\./, "a GLES 3 context");
            expect("instanced", [[255, 128, 0], [255, 128, 0], [0, 0, 0]]);
            expect("mrt1", [[0, 0, 255]]);
            expect("mrtclear", [[0, 255, 0]]);
            expect("mrt0", [[255, 0, 0]]);
            assert.match(log, /V86_GLES integer 4000000000,0,0,1 glerror=0/, "an unsigned integer buffer read as integers");
            assert.match(log, /V86_GLES feedback -2,-2,2,-2,-2,2 glerror=0/, "transform feedback, mapped");
            expect("volume", [[0, 0, 255]]);
            expect("resolve", [[255, 0, 255]]);
            assert.match(log, /V86_GLES pack 255,0,255,255 glerror=0/, "a read into a pixel pack buffer, mapped");
        }
        // GLES 3.1's (L5) where the host announces it
        if(gpu.gles_version === "3.1" || gpu.gles_version === "3.2")
        {
            assert.match(log, /V86_GLES storage 0,3,6,9,12,15,18,21 glerror=0/, "a dispatch's storage buffer, mapped");
            assert.match(log, /V86_GLES counter 18 glerror=0/, "an atomic counter incremented 8 times from 10, mapped");
            expect("computed", [[0, 255, 0]]);
        }
        // (GLES 3.2's reach through the guest's library, where the host announces it: printed)
        const reach = /V86_GLES gles32 .*/.exec(log);
        if(reach) console.log("gles app: " + reach[0].replace(/^V86_GLES /, ""));
        // GLES 3.0's frame rate (docs/gles3-plan.md L7), one instanced draw a frame ("fps") and a draw a cube
        // ("fpsdraws"): the middle cube drawn (not the clear color), the frames in the guest's time; the host's
        // frame rate that time at the clock's rate (a tenth of the host's)
        if(gpu.gles_version !== "2.0")
        {
            const rate = Number(process.env.A32_ANDROID_RATE || RANCHU_25_ARMEABI_V7A.clock_rate);
            const clear = [26, 26, 51];
            const timed = [];
            for(const name of ["fps", "fpsdraws"])
            {
                assert.ok(scenes[name] && scenes[name].error === "0", "the frame rate scene " + name);
                assert.ok(scenes[name].pixels[0].some((v, i) => Math.abs(v - clear[i]) > 10), name + ": the middle cube: " + scenes[name].pixels[0]);
                const m = new RegExp(`V86_GLES ${name} frames=(\\d+) draws=(\\d+) guest_ms=([\\d.]+)`).exec(log);
                assert.ok(m && +m[1] > 0, name + ": frames timed");
                const result = { name, draws: +m[2], frames: +m[1], guest_ms: +m[3], guest_fps: +m[1] / (+m[3] / 1000) };
                result.host_fps = result.guest_fps * rate;
                timed.push(result);
                console.log(`gles app: GLES 3.0 scene, ${result.draws} draw(s) a frame: ${result.frames} frames, ` +
                    `${result.guest_fps.toFixed(1)} fps of the guest's clock, ${result.host_fps.toFixed(2)} fps of the host's`);
            }
            fs.writeFileSync(run_directory + "fps.json", JSON.stringify({ clock_rate: rate, timed }, null, 1));
        }
        save_png(sink, run_directory, "gles-app");
        console.log("gles app: every scene as GLES draws it");
    }
    if(media)
    {
        // the disk's files in as root, given to the shell (as dEQP's)
        for(const step of ["mkdir -p /data/local/tmp/media-disk", "mount -t ext2 -o ro /dev/block/vdd /data/local/tmp/media-disk",
            "cp /data/local/tmp/media-disk/*.apk /data/local/tmp/", "cp /data/local/tmp/media-disk/green.mp4 /sdcard/green.mp4",
            "umount /data/local/tmp/media-disk", "chown shell:shell /data/local/tmp/*.apk", "chmod 644 /data/local/tmp/*.apk"])
        {
            const out = await ask(`su 0 sh -c '${step}' 2>&1`, "A32_MEDIA_COPY", 900000);
            if(/denied|No such|failed|Invalid/i.test(out)) console.log("media copy: " + out.replace(/\s+/g, " ").slice(-300));
        }
        // a video: Gallery's player, the frame's middle green (YV12 from the decoder, RGB from gralloc);
        // the GLES test app closed first (its frame has green in it)
        await ask("am force-stop org.v86.gles; input keyevent 3", "A32_VIDEO_CLEAN", 600000);
        // (YouTube's native code died of SIGILL again and again on T32's LDM.W of one register until the
        // arm32 core transferred it: its "keeps stopping" dialogs covered the video and the games. It
        // launches and stays up now; still disabled until a media run without this line passes)
        await ask("su 0 pm disable com.google.android.youtube", "A32_NO_YOUTUBE", 900000);
        // (Gallery's player opens the file itself: its storage permission, which nothing has granted yet, as Gallery
        // asks for it when it is opened from the launcher; the games' immersive mode without its first-time overlay,
        // which takes their touches)
        await ask("pm grant com.android.gallery3d android.permission.READ_EXTERNAL_STORAGE; " +
            "settings put secure immersive_mode_confirmations confirmed", "A32_MEDIA_SETUP", 900000);
        await dismiss_dialogs();
        console.log("video: " + (await ask("am start -a android.intent.action.VIEW -d file:///sdcard/green.mp4 -t video/mp4 " +
            "-n com.android.gallery3d/.app.MovieActivity", "A32_VIDEO", 900000)).replace(/\s+/g, " ").slice(-160));
        const green = () =>
        {
            let n = 0;
            for(let y = fb.height * 0.3 | 0; y < fb.height * 0.7; y += 8)
            {
                for(let x = fb.width * 0.2 | 0; x < fb.width * 0.8; x += 8)
                {
                    const at = (y * sink.width + x) * 4;
                    if(sink.rgba[at + 1] > 200 && sink.rgba[at] < 80 && sink.rgba[at + 2] < 80) n++;
                }
            }
            return n;
        };
        const video_by = performance.now() + 600000;
        while(green() < 20 && performance.now() < video_by)
        {
            await new Promise(resolve => setTimeout(resolve, 5000));
            await dismiss_dialogs();
        }
        const player = await focus();
        console.log(`video: ${green()} green samples; focus ${player}; frames ${fb.frames}`);
        save_png(sink, run_directory, "video");
        // (checked after the games: a video that does not play leaves them to be tried; its log first)
        const media_failures = [];
        if(!/MovieActivity/.test(player)) media_failures.push("Gallery's player has the focus: " + player);
        if(green() < 20)
        {
            media_failures.push("the video's frame is shown (green)");
            console.log("video log: " + await ask("logcat -d -v brief -s VideoView:W MediaPlayer:W NuPlayer:W NuPlayerDriver:W " +
                "ACodec:W MediaCodec:W OMXNodeInstance:W SoftAVC:W | grep -v -E '[[:space:]]at [a-z]' | head -30", "A32_VIDEO_LOG", 600000));
        }
        await ask("input keyevent 4; input keyevent 3", "A32_VIDEO_HOME", 600000);
        // the games: installed, started, a minute of taps and swipes, still running and drawing
        for(const game of media.games)
        {
            const installed = await ask(`pm install -r -g /data/local/tmp/${game.name}.apk`, "A32_GAME_INSTALL", 1800000);
            assert.match(installed, /Success/, game.name + " installed");
            await dismiss_dialogs();
            await ask(`monkey -p ${game.package} -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1`, "A32_GAME_START", 900000);
            await new Promise(resolve => setTimeout(resolve, 120000));
            await dismiss_dialogs();
            save_png(sink, run_directory, game.name + "-start");
            const events = emulator.v86.cpu.devices.goldfish_events;
            for(const [i, step] of game.steps.entries())
            {
                let at = Array.isArray(step) ? step : null;
                if(step.view)
                {
                    // (uiautomator's bounds are the rotated screen's, as input tap's)
                    const view = await ask("uiautomator dump /data/local/tmp/ui.xml >/dev/null 2>&1; grep -o -E '<node [^>]*>' " +
                        `/data/local/tmp/ui.xml | grep -E '${step.view}' | grep -o -E 'bounds="[^"]*"' | head -1`, "A32_UI_STEP", 900000);
                    const m = /bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/.exec(view);
                    if(m) await ask(`input tap ${(+m[1] + +m[3]) >> 1} ${(+m[2] + +m[4]) >> 1}`, "A32_TAP", 600000);
                    else at = step.at || null;
                    console.log(`game ${game.name} step ${i + 1}: ${step.view} ` + (m ? "found" : at ? "not found, tapped at " + at : "not found"));
                }
                if(at) events.tap(at[0], at[1], fb.width, fb.height);
                for(const code of step.key || []) events.scancode(code);
                await new Promise(resolve => setTimeout(resolve, 45000));
                await dismiss_dialogs();
                save_png(sink, run_directory, `${game.name}-step${i + 1}`);
            }
            // (log: the game's warnings after the steps, and the compile filter its code got)
            if(game.log)
            {
                const pid = (await ask(`pidof ${game.package}`, "A32_GAME_PID", 600000)).match(/\n\s*(\d+)/)?.[1];
                if(pid)
                {
                    // (its own report of a slow level, "waited more than 10 seconds on levelgen", among them; the
                    // sound's errors left out: this machine has no audio output)
                    console.log(`game ${game.name} log: ` + await ask(`getprop pm.dexopt.install; logcat -d -v brief '*:W' | ` +
                        `grep -E '\\( *${pid}\\)' | grep -v -E 'AudioTrack|SoundPool|AndroidMusic' | head -40`, "A32_GAME_LOG", 600000));
                }
            }
            const frames_before = fb.frames, calls_before = Object.values(gles_summary()?.counts || {}).reduce((n, c) => n + c, 0);
            const play_until = performance.now() + 60000;
            for(let i = 0; performance.now() < play_until; i++)
            {
                // (a game played with keys: the right arrow held a second, the up arrow tapped)
                if(game.keys)
                {
                    for(const code of [0xE0, 0x4D]) events.scancode(code);
                    await new Promise(resolve => setTimeout(resolve, 1000));
                    for(const code of [0xE0, 0xCD, 0xE0, 0x48, 0xE0, 0xC8]) events.scancode(code);
                }
                // (taps across the middle, then a swipe)
                if(i % 4 === 3)
                {
                    events.absolute([fb.width * 0.3, fb.height * 0.5, fb.width, fb.height]);
                    events.click([true]);
                    for(let k = 1; k <= 8; k++) { await new Promise(r => setTimeout(r, 60)); events.absolute([fb.width * (0.3 + 0.05 * k), fb.height * 0.5, fb.width, fb.height]); }
                    events.click([false]);
                }
                else events.tap(fb.width * (0.3 + 0.2 * (i % 3)), fb.height * (0.45 + 0.1 * (i % 2)), fb.width, fb.height);
                await new Promise(resolve => setTimeout(resolve, 4000));
            }
            const running = (await ask(`pidof ${game.package}`, "A32_GAME_PID", 600000)).match(/\n\s*(\d+)/);
            const now = await focus();
            const calls = Object.values(gles_summary()?.counts || {}).reduce((n, c) => n + c, 0) - calls_before;
            console.log(`game ${game.name}: focus ${now}; ${fb.frames - frames_before} frames and ${calls} GLES calls in the minute; ` +
                (running ? "running, pid " + running[1] : "not running"));
            save_png(sink, run_directory, game.name + "-play");
            assert.ok(running, game.name + " still runs after a minute");
            if(game.playing && !game.playing.test(now)) media_failures.push(game.name + " plays: " + now);
            assert.ok(calls > 0 && fb.frames > frames_before, game.name + " draws");
            await ask(`am force-stop ${game.package}; input keyevent 3`, "A32_GAME_STOP", 600000);
        }
        assert.deepEqual(media_failures, [], "the video and the games");
    }
    if(deqp)
    {
        // copied in as root (the shell cannot read another filesystem's files), installed, run
        // (each step on its own: the files then belong to the shell, which pm install's reads need)
        for(const step of ["mkdir -p /data/local/tmp/deqp-disk", "mount -t ext2 -o ro /dev/block/vdd /data/local/tmp/deqp-disk",
            "cp /data/local/tmp/deqp-disk/deqp.apk /data/local/tmp/deqp-disk/dEQP-* /data/local/tmp/", "umount /data/local/tmp/deqp-disk",
            "chown shell:shell /data/local/tmp/deqp.apk /data/local/tmp/dEQP-*", "chmod 644 /data/local/tmp/deqp.apk /data/local/tmp/dEQP-*"])
        {
            const out = await ask(`su 0 sh -c '${step}' 2>&1`, "A32_DEQP_COPY", 900000);
            if(/denied|No such|failed|Invalid/i.test(out)) console.log("dEQP copy: " + out.replace(/\s+/g, " ").slice(-300));
        }
        console.log(await ask("ls -l /data/local/tmp | head", "A32_DEQP_LS", 600000));
        // (A32_ANDROID_DEQP_INSTALL_MS: the install's time, dex2oat's; 30 minutes, more on a loaded host)
        const installed = await ask("pm install -r -g /data/local/tmp/deqp.apk", "A32_DEQP_INSTALL", Number(process.env.A32_ANDROID_DEQP_INSTALL_MS || 1800000));
        assert.match(installed, /Success/, "dEQP installed");
        const results = Object.assign({}, deqp.kept), details_of = {};
        const started_deqp = performance.now();
        for(const chunk of deqp.chunks)
        {
            // (A32_ANDROID_DEQP_IMAGES=1: the log's images and shader sources too, its data in the instrumentation's output, kept in deqp-run-<n>.txt)
            const images = process.env.A32_ANDROID_DEQP_IMAGES === "1";
            const command_line = `--deqp-caselist-file=/sdcard/deqp-cases.txt --deqp-gl-config-name=rgba8888d24s8ms0 --deqp-surface-type=window ` +
                `--deqp-screen-rotation=unspecified --deqp-log-images=${images ? "enable" : "disable"} --deqp-log-shader-sources=${images ? "enable" : "disable"} --deqp-watchdog=enable`;
            // (the console's shell has no access to /sdcard, which the tester reads and writes: as root)
            await ask(`su 0 sh -c 'cp /data/local/tmp/${chunk.name} /sdcard/deqp-cases.txt'`, "A32_DEQP_CASES", 600000);
            const run = await ask(`am instrument -w -e deqpLogFileName /sdcard/deqp.qpa -e deqpCmdLine "${command_line}" -e deqpLogData ${images} ` +
                `com.drawelements.deqp/com.drawelements.deqp.testercore.DeqpInstrumentation`, "A32_DEQP_RUN", 7200000);
            if(images) fs.writeFileSync(run_directory + `deqp-run-${chunk.name}`, run);
            // (the results: the instrumentation's status lines, as CTS's runner reads them; no log file is written)
            let current = null;
            for(const line of run.replace(/\r/g, "").split("\n"))
            {
                const begin = /dEQP-BeginTestCase-TestCasePath=(\S+)/.exec(line);
                if(begin) { current = begin[1]; results[current] = "Crash"; continue; }
                const code = /dEQP-TestCaseResult-Code=(\w+)/.exec(line);
                if(code && current) results[current] = code[1];
                const terminated = /dEQP-TerminateTestCase-Reason=(.*)/.exec(line);
                if(terminated && current) results[current] = "Terminated";
                const details = /dEQP-TestCaseResult-Details=(.*)/.exec(line);
                if(details && current && results[current] !== "Pass") details_of[current] = details[1].slice(0, 200);
            }
            for(const c of chunk.cases) if(!(c in results)) results[c] = "NotRun";
            const counts = {};
            for(const c of chunk.cases) counts[results[c]] = (counts[results[c]] || 0) + 1;
            // (the instrumentation's last words when it stopped early: a crash, or cases it never began)
            console.log(`${chunk.name}: ${JSON.stringify(counts)} (${((performance.now() - started_deqp) / 1000).toFixed(0)} s)` +
                (/INSTRUMENTATION_FAILED|Process crashed|Exception=/.test(run) || counts.NotRun ? " " + run.replace(/\s+/g, " ").slice(-600) : ""));
            // (a run that ran nothing: its tester's crash, if any, from the log)
            if(chunk.cases.every(c => results[c] === "NotRun"))
            {
                console.log((await ask("logcat -d -v brief -b crash -b main '*:E' | grep -i -E 'deqp|drawelements|Fatal|backtrace|#0[0-9] pc' | tail -25",
                    "A32_DEQP_CRASH", 600000)).replace(/\r/g, "").split("\n").slice(1).join("\n").slice(0, 3000));
            }
            fs.writeFileSync(run_directory + "deqp.json", JSON.stringify(results, null, 1));
            fs.writeFileSync(run_directory + "deqp-details.json", JSON.stringify(details_of, null, 1));
        }
        const by_status = {};
        for(const status of Object.values(results)) by_status[status] = (by_status[status] || 0) + 1;
        const supported = Object.values(results).filter(s => s !== "NotSupported").length;
        const passed = Object.values(results).filter(s => s === "Pass" || s === "QualityWarning" || s === "CompatibilityWarning").length;
        console.log(`dEQP: ${JSON.stringify(by_status)}; ${passed} of ${supported} supported cases pass (${(100 * passed / supported).toFixed(1)}%)`);
    }
    console.log(JSON.stringify({ tag, marks, screenshot: shot, cmdline }));
    console.log("A32_ANDROID_BOOT_OK " + tag);
}
finally
{
    clearInterval(flush);
    fs.writeFileSync(log, transcript);
    write_gles();
    if(gles_renderer && gles_renderer.close) gles_renderer.close();
    save_png(sink, run_directory, "last");
    await emulator.destroy();
}
process.exit(0);
                                                                      source/v64/tests/a32/baremetal.mjs                                                                  0000644 0000000 0000000 00000004370 00000000000 014066  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The bare-metal AArch32 guests (tests/a32/runner.mjs) on QEMU's cortex-a15
// and on v86 (cpu_type "arm32"): each the same output (docs/aarch32-plan.md
// R2-R4). system.c: the modes, the exceptions, CP15, VFP's enables; mmu.c:
// the short and long descriptors; platform.c: PSCI, the timers and the
// GICv3 CPU interface, a second core.
//
//   node tests/a32/baremetal.mjs [name...]     A32_TARGET=qemu|v86 runs one side
import { build32, compare, root, QEMU_MACHINE32 } from "./runner.mjs";

const TESTS = {
    system: { sources: ["system.c", "system_asm.S"] },
    mmu: { sources: ["mmu.c", "mmu_asm.S", "system_asm.S"] },
    platform: { sources: ["platform.c"], cores: 2 },
    // (the ranchu board's GICv2: QEMU's virt with gic-version=2, v86's GIC in its v2 mode)
    gicv2: { sources: ["gicv2.c"], cores: 2, gic: 2 },
};
const names = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(TESTS);
let failures = 0;
for(const name of names)
{
    const test = TESTS[name];
    if(!test) throw new Error("no test " + name + "; there are " + Object.keys(TESTS).join(", "));
    const directory = build32(name, test.sources.map(s => root + "tests/a32/" + s));
    const results = await compare(directory, { timeout: 30000, cores: test.cores || 1, ...(test.gic === 2 ? {
        machine: QEMU_MACHINE32.replace("gic-version=3", "gic-version=2"),
        setup: cpu => { cpu.wm.exports["a64_gic_set_version"](2); cpu.wm.exports["a64_set_cores"](test.cores); },
    } : {}) });
    let failed = false;
    for(const [target, r] of Object.entries(results))
    {
        if(r.status !== "ok") { console.log(`${name} on ${target}: ${r.status}\n${r.text}`); failed = true; }
    }
    if(results.qemu && results.v86)
    {
        const a = results.qemu.text.split("\n"), b = results.v86.text.split("\n");
        for(let i = 0; i < Math.max(a.length, b.length); i++)
        {
            if(a[i] !== b[i]) { console.log(`${name}: line ${i + 1}\n  qemu: ${a[i]}\n  v86:  ${b[i]}`); failed = true; }
        }
        if(!failed) console.log(`PASS: ${name}: ${a.length} lines the same`);
    }
    else for(const [target, r] of Object.entries(results)) console.log(`${name} on ${target}:\n${r.text}`);
    failures += failed;
}
process.exit(failures ? 1 : 0);
                                                                                                                                                                                                                                                                        source/v64/tests/a32/baremetal/aeabi.S                                                              0000644 0000000 0000000 00000001774 00000000000 014545  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AEABI's 64-bit division helpers (the 32-bit ones are UDIV and SDIV):
// the quotient in r0:r1, the remainder in r2:r3, from a32_divmod64 (runtime.c)

    .syntax unified
    .arm
    .text
    // (functions: a T32 caller's BL becomes BLX)
    .global __aeabi_uldivmod
    .type __aeabi_uldivmod, %function
__aeabi_uldivmod:
    push    {r4, lr}
    sub     sp, sp, #16
    // (a32_divmod64(n r0:r1, d r2:r3, remainder at sp + 8, signed 0): the last two on the stack)
    add     r4, sp, #8
    str     r4, [sp]
    mov     r4, #0
    str     r4, [sp, #4]
    bl      a32_divmod64
    ldr     r2, [sp, #8]
    ldr     r3, [sp, #12]
    add     sp, sp, #16
    pop     {r4, pc}

    .global __aeabi_ldivmod
    .type __aeabi_ldivmod, %function
__aeabi_ldivmod:
    push    {r4, lr}
    sub     sp, sp, #16
    add     r4, sp, #8
    str     r4, [sp]
    mov     r4, #1
    str     r4, [sp, #4]
    bl      a32_divmod64
    ldr     r2, [sp, #8]
    ldr     r3, [sp, #12]
    add     sp, sp, #16
    pop     {r4, pc}
    source/v64/tests/a32/baremetal/include/a32.h                                                        0000644 0000000 0000000 00000005514 00000000000 015535  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bare-metal AArch32 guests' runtime (tests/a32/runner.mjs, cpu_type
// "arm32" and QEMU's cortex-a15): a raw image at RAM + 0x10000 (where QEMU's
// -kernel and the v86 virt loader put a 32-bit kernel), entered in SVC mode
// with the MMU off, r2 the DTB's address. Memory and the result block are
// the AArch64 guests' (a64.h, whose libc this runtime shares).
#ifndef A32_H
#define A32_H

#include <a64.h>

// the exception kinds (the vectors' offsets / 4)
enum { A32_UND = 1, A32_SVC = 2, A32_PABT = 3, A32_DABT = 4, A32_IRQ = 6, A32_FIQ = 7 };

// the modes
enum { A32_USR = 0x10, A32_FIQ_MODE = 0x11, A32_IRQ_MODE = 0x12, A32_SVC_MODE = 0x13, A32_ABT = 0x17,
    A32_UND_MODE = 0x1B, A32_SYS = 0x1F };

// An exception's frame (start.S): the interrupted R0-R12, the address to
// return to (the preferred return address: the instruction for UND, PABT
// and DABT, the next one for SVC, IRQ and FIQ) and its CPSR
struct a32_frame
{
    uint32_t r[13], pc, cpsr;
};

// An exception the test expects (a32_expect arms it; the next UND, SVC,
// PABT or DABT is recorded and returns past the instruction: `skip` bytes,
// 4 by default, 2 for a 16-bit T32 one), a32_caught disarms and reports it.
struct a32_fault
{
    int taken, kind;
    uint32_t fsr, far, pc, spsr, lr;
};
void a32_expect(int skip);
int a32_caught(struct a32_fault *fault);
// (instead of the skip: an expected exception returns here, and with this CPSR, when set)
extern volatile uint32_t a32_return_pc, a32_return_cpsr;

// Interrupts (IRQ, FIQ) go to this handler when it is set
extern void (*volatile a32_interrupt_handler)(struct a32_frame *frame, int kind);
// Every exception goes here first when it is set; it returns whether it took it
extern int (*volatile a32_exception_hook)(struct a32_frame *frame, int kind);

// PSCI over HVC (SMC32 function numbers): r0 returned
int32_t a32_hvc(uint32_t function, uint32_t a1, uint32_t a2, uint32_t a3);
// starts core `core` (MPIDR Aff0) at a32_secondary, calling a64_core_main(core)
int32_t a32_cpu_on(unsigned core);

#define a32_mrc(opc1, crn, crm, opc2) ({ uint32_t _v; \
    __asm__ volatile("mrc p15, " #opc1 ", %0, " #crn ", " #crm ", " #opc2 : "=r"(_v)); _v; })
#define a32_mcr(opc1, crn, crm, opc2, v) \
    __asm__ volatile("mcr p15, " #opc1 ", %0, " #crn ", " #crm ", " #opc2 :: "r"((uint32_t)(v)) : "memory")
#define a32_mrrc(opc1, crm) ({ uint32_t _l, _h; \
    __asm__ volatile("mrrc p15, " #opc1 ", %0, %1, " #crm : "=r"(_l), "=r"(_h)); (uint64_t)_h << 32 | _l; })
#define a32_mcrr(opc1, crm, v) ({ uint64_t _v = (v); \
    __asm__ volatile("mcrr p15, " #opc1 ", %0, %1, " #crm :: "r"((uint32_t)_v), "r"((uint32_t)(_v >> 32)) : "memory"); })
#define a32_cpsr() ({ uint32_t _v; __asm__ volatile("mrs %0, cpsr" : "=r"(_v)); _v; })
#define a32_isb() __asm__ volatile("isb" ::: "memory")
#define a32_dsb() __asm__ volatile("dsb sy" ::: "memory")

#endif
                                                                                                                                                                                    source/v64/tests/a32/baremetal/include/inttypes.h                                                   0000644 0000000 0000000 00000000455 00000000000 017026  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A32_INTTYPES_H
#define A32_INTTYPES_H
#include <stdint.h>
// ILP32, as glibc on armhf
#define PRId32 "d"
#define PRIi32 "i"
#define PRIu32 "u"
#define PRIx32 "x"
#define PRIX32 "X"
#define PRId64 "lld"
#define PRIi64 "lli"
#define PRIu64 "llu"
#define PRIx64 "llx"
#define PRIX64 "llX"
#endif
                                                                                                                                                                                                                   source/v64/tests/a32/baremetal/link.ld                                                              0000644 0000000 0000000 00000001120 00000000000 014617  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The bare-metal AArch32 guests' layout (tests/a32/baremetal/include/a32.h):
   the image at RAM + 0x10000, the heap after it, the stacks below the
   result block (a64.h's). */
ENTRY(_start)
SECTIONS
{
    . = 0x40010000;
    .text : { KEEP(*(.text.head)) *(.text .text.*) }
    .rodata : { *(.rodata .rodata.*) }
    .ARM.exidx : { *(.ARM.exidx*) }
    .data : { *(.data .data.*) }
    . = ALIGN(16);
    __bss_start = .;
    .bss : { *(.bss .bss.*) *(COMMON) }
    . = ALIGN(16);
    _end = .;
    __stack_top = 0x40800000;
    ASSERT(_end <= 0x40400000, "the image overlaps the heap")
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/a32/baremetal/runtime.c                                                            0000644 0000000 0000000 00000011765 00000000000 015210  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bare-metal AArch32 guests' C runtime (include/a32.h): output into the
// result block's text, the startup and finish of a run, the exceptions;
// printf and the allocator are the AArch64 guests' libc.c.

#include <a32.h>
#include <stdio.h>

static volatile unsigned text_length;
void (*volatile a64_core_main)(unsigned core);
void (*volatile a32_interrupt_handler)(struct a32_frame *frame, int kind);
int (*volatile a32_exception_hook)(struct a32_frame *frame, int kind);

static void finish(uint32_t status)
{
    a64_result->length = text_length;
    a64_result->status = status;
    a32_dsb();
    a64_result->magic = A64_DONE;
    a32_dsb();
    for(;;) __asm__ volatile("wfi");
}

void a64_putc(char c)
{
    if(text_length >= A64_TEXT_SIZE) finish(A64_TEXT_OVERFLOW);
    ((volatile char *)A64_TEXT)[text_length++] = c;
    // (the length so far too: a run that hangs shows its output)
    a64_result->length = text_length;
}

void a64_fail(const char *why)
{
    printf("A32_FAIL %s\n", why);
    finish(A64_FAILED);
}

void a32_start(uint32_t dtb)
{
    a64_result->magic = 0;
    a64_result->status = 0;
    a64_result->length = 0;
    a64_result->cores = 1;
    a64_result->dtb = dtb;
    char *argv[] = { "a32", 0 };
    int status = main(1, argv);
    finish(status ? A64_FAILED : A64_OK);
}

void a64_secondary_start(unsigned core)
{
    if(a64_core_main) a64_core_main(core);
    for(;;) __asm__ volatile("wfi");
}

void exit(int status) { finish(status ? A64_FAILED : A64_OK); }
void abort(void) { a64_fail("abort"); for(;;); }

int32_t a32_hvc(uint32_t function, uint32_t a1, uint32_t a2, uint32_t a3)
{
    register uint32_t r0 __asm__("r0") = function, r1 __asm__("r1") = a1, r2 __asm__("r2") = a2, r3 __asm__("r3") = a3;
    __asm__ volatile(".arch_extension virt\n hvc #0" : "+r"(r0), "+r"(r1), "+r"(r2), "+r"(r3) :: "memory");
    return r0;
}

extern char a32_secondary[];
int32_t a32_cpu_on(unsigned core)
{
    return a32_hvc(0x84000003, core, (uint32_t)a32_secondary, core); // PSCI CPU_ON (SMC32)
}

// -------- exceptions

static volatile struct a32_fault expected;
static volatile int armed, skip_bytes;
volatile uint32_t a32_return_pc, a32_return_cpsr;

void a32_expect(int skip)
{
    expected.taken = 0;
    skip_bytes = skip ? skip : 4;
    __asm__ volatile("" ::: "memory");
    armed = 1;
}

int a32_caught(struct a32_fault *fault)
{
    armed = 0;
    __asm__ volatile("" ::: "memory");
    fault->taken = expected.taken;
    fault->kind = expected.kind;
    fault->fsr = expected.fsr;
    fault->far = expected.far;
    fault->pc = expected.pc;
    fault->spsr = expected.spsr;
    fault->lr = expected.lr;
    return fault->taken;
}

// (the fault status and address: DFSR and DFAR for a data abort, IFSR and IFAR for a prefetch abort)
static uint32_t fsr_of(int kind) { return kind == A32_DABT ? a32_mrc(0, c5, c0, 0) : kind == A32_PABT ? a32_mrc(0, c5, c0, 1) : 0; }
static uint32_t far_of(int kind) { return kind == A32_DABT ? a32_mrc(0, c6, c0, 0) : kind == A32_PABT ? a32_mrc(0, c6, c0, 2) : 0; }

void a32_exception(struct a32_frame *frame, int kind)
{
    // (UND's return address: the instruction, LR - 4 in A32, LR - 2 in T32)
    uint32_t lr = frame->pc;
    if(kind == A32_UND) frame->pc -= frame->cpsr & 1 << 5 ? 2 : 4;
    if(a32_exception_hook && a32_exception_hook(frame, kind)) return;
    if((kind == A32_IRQ || kind == A32_FIQ) && a32_interrupt_handler)
    {
        a32_interrupt_handler(frame, kind);
        return;
    }
    if(kind != A32_IRQ && kind != A32_FIQ && armed && !expected.taken)
    {
        expected.taken = 1;
        expected.kind = kind;
        expected.fsr = fsr_of(kind);
        expected.far = far_of(kind);
        expected.pc = frame->pc;
        expected.spsr = frame->cpsr;
        expected.lr = lr;
        // (SVC returns to the next instruction already)
        if(a32_return_pc)
        {
            frame->pc = a32_return_pc;
            if(a32_return_cpsr) frame->cpsr = a32_return_cpsr;
        }
        else if(kind != A32_SVC) frame->pc += skip_bytes;
        return;
    }
    a64_result->vector = kind;
    a64_result->esr = fsr_of(kind);
    a64_result->far = far_of(kind);
    a64_result->elr = frame->pc;
    a64_result->spsr = frame->cpsr;
    printf("A32_EXCEPTION kind=%d fsr=%#x pc=%#x far=%#x cpsr=%#x\n", kind, (unsigned)fsr_of(kind),
        (unsigned)frame->pc, (unsigned)far_of(kind), (unsigned)frame->cpsr);
    finish(A64_UNEXPECTED_EXCEPTION);
}

// -------- the AEABI's 64-bit division (aeabi.S): shift and subtract
uint64_t a32_divmod64(uint64_t n, uint64_t d, uint64_t *remainder, int is_signed)
{
    int negative_q = 0, negative_r = 0;
    if(is_signed)
    {
        if((int64_t)n < 0) { n = -n; negative_q ^= 1; negative_r = 1; }
        if((int64_t)d < 0) { d = -d; negative_q ^= 1; }
    }
    uint64_t q = 0, r = 0;
    if(d == 0) { *remainder = n; return ~(uint64_t)0; }
    for(int i = 63; i >= 0; i--)
    {
        r = r << 1 | (n >> i & 1);
        if(r >= d) { r -= d; q |= (uint64_t)1 << i; }
    }
    *remainder = negative_r ? -r : r;
    return negative_q ? -q : q;
}
           source/v64/tests/a32/baremetal/start.S                                                              0000644 0000000 0000000 00000005315 00000000000 014634  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Entry of the bare-metal AArch32 guests (tests/a32/runner.mjs): a raw
// image at RAM + 0x10000, entered in SVC mode with the MMU off and r2 the
// DTB's address (QEMU's -kernel of a 32-bit kernel, the v86 virt loader's
// cpu_type "arm32"). Secondary cores, started with PSCI CPU_ON, enter at
// a32_secondary with their core number in r0.
//
// Each core has 64 KiB below __stack_top - 64 KiB * core: SVC's stack at the
// top, then System's (and User's) 16 KiB down, and 4 KiB each for ABT,
// UND, IRQ and FIQ further down.

    .syntax unified
    .arm
    .section .text.head, "ax"
    .global _start
_start:
    mov     r4, r2
    mov     r0, #0
    bl      cpu_setup
    ldr     r1, =__bss_start
    ldr     r2, =_end
    mov     r3, #0
1:  cmp     r1, r2
    strlo   r3, [r1], #4
    blo     1b
    mov     r0, r4
    bl      a32_start
2:  wfi
    b       2b

    .global a32_secondary
a32_secondary:
    mov     r4, r0
    bl      cpu_setup
    mov     r0, r4
    bl      a64_secondary_start
3:  wfi
    b       3b

// the modes' stacks for core r0, VFP and Advanced SIMD on (CPACR cp10 and
// cp11 full access, FPEXC.EN), the vectors at VBAR; ends in SVC mode
cpu_setup:
    ldr     r1, =__stack_top
    sub     r1, r1, r0, lsl #16
    mov     r2, lr
    cps     #0x1F
    sub     sp, r1, #0x4000
    cps     #0x17
    sub     sp, r1, #0xC000
    cps     #0x1B
    sub     sp, r1, #0xD000
    cps     #0x12
    sub     sp, r1, #0xE000
    cps     #0x11
    sub     sp, r1, #0xF000
    cps     #0x13
    mov     sp, r1
    mov     r1, #(0xF << 20)
    mcr     p15, 0, r1, c1, c0, 2
    isb
    mov     r1, #(1 << 30)
    vmsr    fpexc, r1
    ldr     r1, =a32_vectors
    mcr     p15, 0, r1, c12, c0, 0
    isb
    bx      r2

// The vectors: each saves R0-R12, its preferred return address and SPSR
// (struct a32_frame, SRS) on its mode's stack and calls
// a32_exception(frame, kind), then returns with RFE to the (possibly
// changed) frame
    .macro vector kind, mode, adjust
    .if \adjust
    sub     lr, lr, #\adjust
    .endif
    srsdb   sp!, #\mode
    push    {r0-r12}
    mov     r0, sp
    mov     r1, #\kind
    // (AAPCS: an 8-byte aligned stack; the frame is 15 words)
    sub     sp, sp, #4
    bl      a32_exception
    add     sp, sp, #4
    pop     {r0-r12}
    rfeia   sp!
    .endm

    .balign 32
    .global a32_vectors
a32_vectors:
    b       .
    b       und_vector
    b       svc_vector
    b       pabt_vector
    b       dabt_vector
    b       .
    b       irq_vector
    b       fiq_vector

und_vector:
    vector  1, 0x1B, 0
svc_vector:
    vector  2, 0x13, 0
pabt_vector:
    vector  3, 0x17, 4
dabt_vector:
    vector  4, 0x17, 8
irq_vector:
    vector  6, 0x12, 4
fiq_vector:
    vector  7, 0x11, 4

    .ltorg
                                                                                                                                                                                                                                                                                                                   source/v64/tests/a32/bench.c                                                                        0000644 0000000 0000000 00000003212 00000000000 012634  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The PL1 driver of tests/a64/aarch32_bench.mjs --arm32 (docs/aarch32-plan.md
// R5.3's E level): one kernel of tests/bench (bench_main(iterations)) built
// for A32 or T32 and run at PL1 on cpu_type "arm32" with the MMU on (short
// descriptors: RAM's sections normal memory, write-back, the rest device
// memory; the page tier compiles code with the MMU on), as a 32-bit kernel
// runs; the checksum and the counter's ticks it took are printed.
#include <a32.h>
#include <stdio.h>

unsigned bench_main(unsigned iterations);
static uint32_t l1[4096] __attribute__((aligned(16384)));

int main(int argc, char **argv)
{
    // 1 MiB sections, identity: AP 11, domain 0; RAM (1 GiB at 0x40000000)
    // TEX 001 C B (write-back, write-allocate), the rest B (shareable device)
    for(uint32_t mb = 0; mb < 4096; mb++)
    {
        const int ram = mb >= 0x400 && mb < 0x800;
        l1[mb] = mb << 20 | 2 | 3 << 10 | (ram ? 1 << 12 | 1 << 3 | 1 << 2 : 1 << 2);
    }
    a32_dsb();
    a32_mcr(0, c2, c0, 2, 0);
    a32_mcr(0, c2, c0, 0, (uint32_t)l1);
    a32_mcr(0, c3, c0, 0, 0x55555555);
    a32_mcr(0, c8, c7, 0, 0);
    a32_dsb();
    a32_mcr(0, c1, c0, 0, a32_mrc(0, c1, c0, 0) | 1 | 1 << 2 | 1 << 12);
    a32_isb();
    const uint64_t start = a32_mrrc(1, c14);
    const unsigned value = bench_main(ITERATIONS);
    const uint64_t end = a32_mrrc(1, c14);
    // (the runtime's printf takes %x and %u as 32 bits here: the ticks in microseconds)
    const uint32_t frequency = a32_mrc(0, c14, c0, 0);
    printf("bench %s checksum %08x ticks %u us frequency %u\n", NAME, value, (unsigned)((end - start) / (frequency / 1000000)), (unsigned)frequency);
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/a32/gicv2.c                                                                        0000644 0000000 0000000 00000007420 00000000000 012574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The GICv2 (the ranchu board's, docs/aarch32-plan.md R4.2) against QEMU's
// virt with gic-version=2: the distributor's banked and shared registers,
// ITARGETSR, the CPU interface, the virtual timer's PPI, SGIs by GICD_SGIR
// (to this core, and from core 1 with its source in GICC_IAR), the
// priority mask and EOI (run with 2 cores).
#include <a32.h>
#include <stdio.h>

#define GICD 0x08000000u
#define GICC 0x08010000u
#define MMIO32(a) (*(volatile uint32_t *)(a))
#define MMIO8(a) (*(volatile uint8_t *)(a))

static volatile uint32_t iars[8], interrupts;

static void irq(struct a32_frame *frame, int kind)
{
    uint32_t iar = MMIO32(GICC + 0x0C);
    if(interrupts < 8) iars[interrupts] = iar;
    interrupts++;
    if((iar & 0x3FF) == 27) a32_mcr(0, c14, c3, 1, 3);
    MMIO32(GICC + 0x10) = iar;
    (void)frame;
    (void)kind;
}

static void wait_interrupts(uint32_t count)
{
    __asm__ volatile("cpsie i" ::: "memory");
    for(uint32_t spins = 0; interrupts < count && spins < 20000000; spins++) __asm__ volatile("" ::: "memory");
    __asm__ volatile("cpsid i" ::: "memory");
}

static void cpu_interface_on(void)
{
    MMIO32(GICD + 0x100) = 1 << 3 | 1 << 5 | 1 << 27;   // SGIs 3, 5, PPI 27
    for(int i = 0; i < 8; i++) MMIO32(GICD + 0x400 + 4 * i) = 0xA0A0A0A0;
    MMIO32(GICC + 0x04) = 0xF0;
    MMIO32(GICC) = 1;
}

static volatile uint32_t core1_done;
static void core_main(unsigned core)
{
    cpu_interface_on();
    printf("core %u: itargetsr0 %#x isenabler0 %#x\n", core, (unsigned)MMIO32(GICD + 0x800), (unsigned)MMIO32(GICD + 0x100));
    // (SGI 5 to core 0)
    MMIO32(GICD + 0xF00) = 1 << 16 | 5;
    a32_dsb();
    core1_done = 1;
}

int main(int argc, char **argv)
{
    printf("typer %#x iidr %#x ctlr %#x\n", (unsigned)MMIO32(GICD + 0x4) & 0xFF, (unsigned)MMIO32(GICD + 0x8), (unsigned)MMIO32(GICD));
    printf("itargetsr0 %#x itargetsr8 %#x icfgr0 %#x icfgr1 %#x\n", (unsigned)MMIO32(GICD + 0x800), (unsigned)MMIO32(GICD + 0x820),
        (unsigned)MMIO32(GICD + 0xC00), (unsigned)MMIO32(GICD + 0xC04));
    MMIO32(GICD + 0x820) = 0x01020301;
    MMIO32(GICD + 0xC08) = 0xAAAA0000;
    printf("itargetsr8 written %#x icfgr2 %#x priority32 %#x\n", (unsigned)MMIO32(GICD + 0x820), (unsigned)MMIO32(GICD + 0xC08),
        (unsigned)(MMIO8(GICD + 0x420) = 0xFF, MMIO8(GICD + 0x420)));
    MMIO32(GICD) = 1;
    a32_interrupt_handler = irq;
    cpu_interface_on();
    printf("gicc ctlr %#x pmr %#x bpr %#x rpr %#x hppir %#x\n", (unsigned)MMIO32(GICC), (unsigned)MMIO32(GICC + 4), (unsigned)MMIO32(GICC + 8),
        (unsigned)MMIO32(GICC + 0x14), (unsigned)MMIO32(GICC + 0x18));

    // the virtual timer
    a32_mcr(0, c14, c3, 0, 10000);
    a32_mcr(0, c14, c3, 1, 1);
    a32_isb();
    wait_interrupts(1);
    a32_mcr(0, c14, c3, 1, 0);
    // SGI 3 to this core (TargetListFilter 2)
    MMIO32(GICD + 0xF00) = 2 << 24 | 3;
    wait_interrupts(2);
    // SGI 5 from core 1
    a64_core_main = core_main;
    a32_dsb();
    printf("cpu_on: %d\n", (int)a32_cpu_on(1));
    for(int spins = 0; !core1_done && spins < 10000000; spins++) __asm__ volatile("" ::: "memory");
    wait_interrupts(3);
    for(uint32_t i = 0; i < interrupts && i < 8; i++) printf("iar %u: intid %u cpu %u\n", (unsigned)i, (unsigned)(iars[i] & 0x3FF), (unsigned)(iars[i] >> 10 & 7));
    // the priority mask: pending SGI 3 with PMR below its priority stays pending
    MMIO32(GICC + 4) = 0x80;
    MMIO32(GICD + 0xF00) = 2 << 24 | 3;
    a32_dsb();
    printf("masked: ispendr0 %#x hppir %#x iar %#x\n", (unsigned)(MMIO32(GICD + 0x200) & 0xFFFF), (unsigned)MMIO32(GICC + 0x18),
        (unsigned)MMIO32(GICC + 0x0C));
    MMIO32(GICC + 4) = 0xF0;
    wait_interrupts(4);
    printf("interrupts %u, last intid %u, ispendr0 %#x\n", (unsigned)interrupts, (unsigned)(iars[3] & 0x3FF), (unsigned)(MMIO32(GICD + 0x200) & 0xFFFF));
    return 0;
}
                                                                                                                                                                                                                                                source/v64/tests/a32/hello.c                                                                        0000644 0000000 0000000 00000000617 00000000000 012666  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The smallest AArch32 guest (tests/a32/runner.mjs): the runtime's start,
// printf, the mode it runs in and the DTB's address
#include <a32.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    printf("hello from AArch32, cpsr mode %#x\n", (unsigned)(a32_cpsr() & 0x1F));
    printf("sctlr %#x midr %#x\n", (unsigned)a32_mrc(0, c1, c0, 0), (unsigned)a32_mrc(0, c0, c0, 0));
    return 0;
}
                                                                                                                 source/v64/tests/a32/linux_boot.mjs                                                                 0000644 0000000 0000000 00000043414 00000000000 014316  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unmodified Alpine Linux 3.24.3 armv7 on cpu_type "arm32" (docs/aarch32-plan.md
// R5.2) and on the reference, QEMU 9.2's cortex-a15 on the 32-bit virt board
// (tests/a32/runner.mjs's machine): the netboot release's kernel (a zImage),
// initramfs and modloop, pinned and downloaded once into build/a32-linux/.
// A32_STAGE:
//
// - "initramfs" (the default): the initramfs and a cpio of /a32-init and the
//   32-bit workload (tests/lib/aarch32_workload.mjs: the probe built for A32
//   and T32, Alpine's armv7 programs in a chroot), rdinit=/a32-init: the
//   workload, /proc/interrupts, poweroff. The workload's lines must be the
//   reference's but where the CPUs differ on purpose: profile arm32-v1 has
//   the crypto instructions and CRC32, QEMU's cortex-a15 not (HWCAP2, the
//   Features, the probe's AES, SHA and VMULL.P64 answers, which must be
//   the known ones of the 64-bit reference's compat tasks instead).
// - "single": Alpine's init in single mode to its shell (a root that does
//   not exist), /proc/interrupts, A32_SINGLE_OK, poweroff.
// - "lifecycle" (v86): single mode, a snapshot saved there and restored
//   into a new machine whose shell goes on, "reboot -f" (PSCI SYSTEM_RESET)
//   back to single mode, "poweroff -f" (SYSTEM_OFF) stopping the machine.
// - "live": boot media on a virtio-blk disk (a FAT image: the rpi
//   release's apks/ and the netboot modloop); Alpine's init installs
//   alpine-base from it, OpenRC boots to "localhost login:", root logs in,
//   uname, /proc/cpuinfo and a few commands, poweroff.
//
// A32_LINUX_TARGET=qemu|v86|both (both: the reference first, its transcript
// kept for the comparison), A32_CORES (1, 2, 4), A32_LINUX_TIMEOUT (ms),
// A32_JIT=1 the page tier (once it runs arm32's code, R5.3).
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { ROOT, sha256 } from "../lib/alpine_image.mjs";
import { aarch32_workload } from "../lib/aarch32_workload.mjs";
import { qemu_binary, smp } from "../a64/guest_runner.mjs";
import { QEMU_MACHINE32, QEMU_CPU32 } from "./runner.mjs";

const RELEASE = "https://dl-cdn.alpinelinux.org/alpine/v3.24/releases/armv7/";
// (the SHA-256s of 2026-10-24's downloads; the rpi tarball's matches its published .sha256)
const FILES = {
    "vmlinuz-lts": { url: RELEASE + "netboot-3.24.3/vmlinuz-lts", sha256: "e8dc515bbd3b7eaff8839c1c99acf85abf7b1c38eeeb5f18f97adf326fa6b137" },
    "initramfs-lts": { url: RELEASE + "netboot-3.24.3/initramfs-lts", sha256: "f46df12efee6e009a59649b7ff75a53b341d469806bf017ec8db3c8d3ea3379f" },
    "modloop-lts": { url: RELEASE + "netboot-3.24.3/modloop-lts", sha256: "5caa967c2613c0d44b5febc402052dc6950dfc207e157ce41aa7146010f55acb" },
    "alpine-rpi-3.24.3-armv7.tar.gz": { url: RELEASE + "alpine-rpi-3.24.3-armv7.tar.gz",
        sha256: "555ce15b7fc1460ce1286dc9f2e3c1875d4235a21e19c963be1650cd32bfef95" },
};
// the crypto instructions' answers (tests/a64/linux_probe32.c; QEMU's cortex-a35 running the probe as a compat task)
const KNOWN = { aes: "02833fe0ccba6526f2e061546d959bd4", sha: "2c0657a2c2d6e0dfc2c43f321a2a21ec", pmull: "02ecfcfc0154ff4403fcfdec0044fe54" };
// (and ThumbEE, which the cortex-a15 has and ARMv8 not; HWCAP's bit 11)
const DIFFERENT_FEATURES = ["thumbee", "aes", "pmull", "sha1", "sha2", "crc32"];
const HWCAP_THUMBEE = 1 << 11;
// v86's HWCAP2: AES, PMULL, SHA1, SHA2, CRC32
const V86_HWCAP2 = 0x1F;

const stage = process.env.A32_STAGE || "initramfs";
assert.ok(["initramfs", "single", "lifecycle", "live"].includes(stage), "A32_STAGE is initramfs, single, lifecycle or live");
const cores = Number(process.env.A32_CORES || 1);
assert.ok([1, 2, 4].includes(cores), "A32_CORES is 1, 2 or 4");
const target = process.env.A32_LINUX_TARGET || (stage === "lifecycle" ? "v86" : "both");
assert.ok(["qemu", "v86", "both"].includes(target), "A32_LINUX_TARGET is qemu, v86 or both");
assert.ok(stage !== "lifecycle" || target === "v86", "the lifecycle stage is v86's");
const jit = !!+process.env.A32_JIT;
const timeout = Number(process.env.A32_LINUX_TIMEOUT || (stage === "initramfs" || stage === "live" ? 1800000 : 600000));
const directory = ROOT + "build/a32-linux/";
fs.mkdirSync(directory, { recursive: true });

function run(program, args, options = {})
{
    const result = spawnSync(program, args, { encoding: "utf8", ...options });
    assert.equal(result.status, 0, `${program} ${args.join(" ")}: ${result.stderr || result.error}`);
    return result.stdout.trim();
}

for(const [name, file] of Object.entries(FILES))
{
    if(name.startsWith("alpine-rpi") && stage !== "live") continue;
    const local = directory + name;
    if(!fs.existsSync(local))
    {
        const response = await fetch(file.url);
        assert.ok(response.ok, `${file.url}: HTTP ${response.status}`);
        fs.writeFileSync(local + ".tmp", Buffer.from(await response.arrayBuffer()));
        fs.renameSync(local + ".tmp", local);
    }
    assert.equal(sha256(fs.readFileSync(local)), file.sha256, "the pinned " + name);
}
const kernel = directory + "vmlinuz-lts";
const tar_args = ["--uid", "0", "--gid", "0", "--no-xattrs", "--no-mac-metadata"];

// the initramfs stage's initrd: Alpine's and the workload's cpio after it
let initrd = directory + "initramfs-lts";
if(stage === "initramfs")
{
    const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
    const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
    const staging = directory + "root/";
    await aarch32_workload({ staging, objects: directory, run, lld, prefix: "a32" });
    fs.writeFileSync(staging + "a32-init", [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "$B mount -t proc proc /proc; $B mount -t sysfs sys /sys; $B mount -t devtmpfs dev /dev",
        "$B mkdir -p /tmp; $B mount -t tmpfs tmp /tmp",
        "$B echo A32_INIT_START cpus=$($B nproc) machine=$($B uname -m)",
        "/a32-aarch32-workload",
        "$B cat /proc/interrupts",
        "$B echo A32_INIT_DONE",
        "$B poweroff -f",
        ""].join("\n"), { mode: 0o755 });
    run("bsdtar", ["--format", "newc", ...tar_args, "-cf", directory + "root.cpio", "-C", staging, "."]);
    initrd = directory + "initramfs-lts+root.cpio";
    // (the next archive starts 4-byte aligned after a compressed one: init/initramfs.c)
    const alpine = fs.readFileSync(directory + "initramfs-lts");
    fs.writeFileSync(initrd, Buffer.concat([alpine, Buffer.alloc(-alpine.length & 3), fs.readFileSync(directory + "root.cpio")]));
}

// the live stage's boot media: a FAT disk of the rpi release's apks and the modloop
const media = directory + "media.img";
if(stage === "live" && !fs.existsSync(media))
{
    const tree = directory + "media/";
    fs.rmSync(tree, { recursive: true, force: true });
    fs.mkdirSync(tree + "boot", { recursive: true });
    run("bsdtar", ["-xf", directory + "alpine-rpi-3.24.3-armv7.tar.gz", "-C", tree, "./apks", "./.alpine-release"]);
    fs.copyFileSync(directory + "modloop-lts", tree + "boot/modloop-lts");
    // (macOS: a raw MBR disk with one FAT32 partition of the tree)
    run("hdiutil", ["create", "-quiet", "-size", "256m", "-fs", "MS-DOS FAT32", "-volname", "ALPINE", "-srcfolder", tree,
        "-format", "UDTO", "-layout", "MBRSPUD", "-ov", directory + "media"]);
    fs.renameSync(directory + "media.cdr", media);
}

const EARLY = "console=ttyAMA0 earlycon=pl011,0x09000000 panic=-1";
// (v86 interpreted on more than one core: the soft lockup detector's threshold at 60 s)
const watchdog = !jit && cores > 1 ? " watchdog_thresh=30" : "";
const CMDLINES = {
    initramfs: EARLY + " rdinit=/a32-init",
    // (a root that does not exist: init looks for it, then enters single mode before mounting it)
    single: EARLY + " single root=/dev/vda",
    lifecycle: EARLY + " single root=/dev/vda",
    live: EARLY + " modules=loop,squashfs,virtio_mmio,virtio_blk,vfat modloop=/boot/modloop-lts",
};
const SINGLE_COMMANDS = "cat /proc/interrupts; echo A32_SINGLE_$((6*7)) && echo A32_SINGLE_OK; /bin/busybox poweroff -f\n";
const LIVE_COMMANDS = "uname -m; grep -m1 Features /proc/cpuinfo; cat /etc/alpine-release; rc-status -s 2>/dev/null | head -3; " +
    "echo $((6*7)) | md5sum; cat /proc/interrupts; echo A32_LIVE_DONE; poweroff -f\n";
const DONE = { initramfs: /A32_INIT_DONE/, single: /A32_SINGLE_42\r?\nA32_SINGLE_OK/, live: /A32_LIVE_DONE/ };

/** The serial console's driver: what to type when the transcript reaches a prompt */
function driver(write)
{
    let ran = false, logged_in = false, login_ms;
    const started = performance.now();
    return {
        output(transcript)
        {
            if((stage === "single" || stage === "lifecycle") && !ran && /Entering single mode[^\n]*\n/.test(transcript))
            {
                ran = true;
                if(stage === "single") write(SINGLE_COMMANDS);
            }
            if(stage === "live" && !logged_in && /localhost login: ?$/.test(transcript))
            {
                logged_in = true;
                login_ms = Math.round(performance.now() - started);
                write("root\n");
            }
            if(stage === "live" && logged_in && !ran && /localhost:~# ?$/.test(transcript))
            {
                ran = true;
                write(LIVE_COMMANDS);
            }
        },
        get login_ms() { return login_ms; },
        get shell() { return ran; },
    };
}

async function reference()
{
    const qemu = qemu_binary();
    const args = ["-machine", QEMU_MACHINE32, "-cpu", QEMU_CPU32, "-m", "512M", "-smp", smp(cores),
        "-global", "virtio-mmio.force-legacy=false", "-display", "none", "-no-reboot", "-serial", "stdio", "-monitor", "none",
        "-kernel", kernel, "-initrd", initrd, "-append", CMDLINES[stage],
        ...(stage === "live" ? ["-drive", `if=none,id=media,file=${media},format=raw,readonly=on`, "-device", "virtio-blk-device,drive=media"] : [])];
    const child = spawn(qemu, args, { stdio: ["pipe", "pipe", "pipe"] });
    let transcript = "";
    const d = driver(text => child.stdin.write(text));
    const started = performance.now();
    let timer;
    try
    {
        await new Promise((resolve, reject) => {
            timer = setTimeout(() => reject(new Error(`QEMU ${stage} deadline (${timeout} ms)\n${transcript.slice(-3000)}`)), timeout);
            child.on("error", reject);
            child.on("exit", code => (DONE[stage].test(transcript) ? resolve() : reject(new Error(`QEMU exited ${code}\n${transcript.slice(-3000)}`))));
            const output = bytes => { transcript += bytes; d.output(transcript); };
            child.stdout.on("data", output);
            child.stderr.on("data", output);
        });
    }
    finally
    {
        clearTimeout(timer);
        child.kill();
        fs.writeFileSync(directory + `qemu-${stage}-${cores}c.log`, transcript);
    }
    return { transcript, ms: Math.round(performance.now() - started), login_ms: d.login_ms };
}

const v86_options = () => ({
    cpu_type: "arm32", graphics_adapter: "none", cpu_cores: cores, memory_size: 512 << 20, log_level: 0,
    wasm_path: process.env.A32_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { url: kernel }, initrd: { url: initrd }, cmdline: CMDLINES[stage] + watchdog,
    ...(stage === "live" ? { virtio_disks: [{ buffer: new Uint8Array(fs.readFileSync(media)).buffer, readonly: true }] } : {}),
    ...(jit ? { jit_switches: { a64_page: 1 } } : {}),
    // (A32_PARALLEL=1: the cores in vCPU workers)
    ...(process.env.A32_PARALLEL === "1" ? { parallel: true, parallel_wasm_path: ROOT + "build/v86-arm64-parallel.wasm" } : {}),
});

async function actual()
{
    const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    let emulator = new V86({ ...v86_options(), autostart: true });
    let transcript = "";
    const attach = e => e.add_listener("serial0-output-byte", byte => { transcript += String.fromCharCode(byte); d.output(transcript); });
    const d = driver(text => emulator.serial0_send(text));
    attach(emulator);
    const started = performance.now();
    // (the transcript so far, every 2 s: a run that hangs shows where)
    const log = directory + `v86-${stage}-${cores}c${jit ? "-jit" : ""}.log`;
    const flush = setInterval(() => fs.writeFileSync(log, transcript), 2000);
    const wait = (pattern, from = 0, what = String(pattern)) => new Promise((resolve, reject) => {
        const limit = performance.now() + timeout;
        const poll = setInterval(() => {
            if(pattern.test(transcript.slice(from))) { clearInterval(poll); resolve(); }
            else if(performance.now() > limit)
            {
                clearInterval(poll);
                reject(new Error(`v86 ${stage}: no ${what} after ${timeout} ms: ` + JSON.stringify(emulator.v86?.cpu?.get_diagnostics?.() ?? {}) +
                    "\n" + transcript.slice(-3000)));
            }
        }, 50);
    });
    const result = {};
    try
    {
        if(stage !== "lifecycle")
        {
            await wait(DONE[stage]);
        }
        else
        {
            // (the shell's prompt, with the kernel's messages maybe after it)
            await wait(/Entering single mode[^\n]*\n[\s\S]*# /);
            await new Promise(r => setTimeout(r, 2000));
            // a snapshot in the shell, restored into a new machine
            await emulator.stop();
            const state = await emulator.save_state();
            await emulator.destroy();
            emulator = new V86({ ...v86_options(), autostart: false });
            await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
            await emulator.restore_state(state);
            attach(emulator);
            let mark = transcript.length;
            emulator.run();
            emulator.serial0_send("echo A32_RESTORED_$((6*7))\n");
            await wait(/A32_RESTORED_42/, mark, "the restored shell's answer");
            result.snapshot_bytes = state.byteLength;
            // reboot -f (SYSTEM_RESET): single mode again
            mark = transcript.length;
            emulator.serial0_send("reboot -f\n");
            await wait(/Booting Linux[\s\S]*Entering single mode[^\n]*\n[\s\S]*# /, mark, "single mode after reboot -f");
            await new Promise(r => setTimeout(r, 2000));
            // poweroff -f (SYSTEM_OFF): the machine stops
            mark = transcript.length;
            emulator.serial0_send("poweroff -f\n");
            await wait(/reboot: Power down/, mark, "the power down");
            const cpu = emulator.v86.cpu;
            const off_limit = performance.now() + 30000;
            while(!(cpu.powered_off?.() ?? true) && performance.now() < off_limit) await new Promise(r => setTimeout(r, 100));
            result.powered_off = cpu.powered_off?.() ?? null;
            assert.ok(result.powered_off !== false, "the machine is off after poweroff -f");
        }
    }
    finally
    {
        clearInterval(flush);
        fs.writeFileSync(log, transcript);
        result.diagnostics = emulator.v86?.cpu?.get_diagnostics?.();
        await emulator.destroy();
    }
    return { transcript, ms: Math.round(performance.now() - started), login_ms: d.login_ms, ...result };
}

/** The workload's lines, the CPUs' intended differences taken out */
function workload_lines(transcript, side)
{
    const text = transcript.replace(/\r/g, "");
    const begin = text.indexOf("A32_WORKLOAD_BEGIN\n"), end = text.indexOf("A32_WORKLOAD_END");
    assert.ok(begin >= 0 && end > begin, side + ": no workload between its markers");
    return text.slice(begin, end).split("\n").filter(line => !/^\[ *\d+\.\d+\]/.test(line)).map(line => {
        if(line.startsWith("A32_PROBE "))
        {
            if(side === "v86")
            {
                for(const [name, value] of Object.entries(KNOWN)) assert.ok(line.includes(` ${name}=${value}`), `v86's ${name} answer: ${line}`);
                assert.equal(parseInt(line.match(/ hwcap2=(0x[0-9a-f]+)/)[1], 16), V86_HWCAP2, "v86's HWCAP2");
            }
            line = line.replace(/ hwcap2=0x[0-9a-f]+/, "").replace(/ (aes|sha|pmull)=([0-9a-f]+|none)/g, "")
                .replace(/ hwcap=(0x[0-9a-f]+)/, (_, v) => ` hwcap=${(parseInt(v, 16) & ~HWCAP_THUMBEE) >>> 0}`);
        }
        return line.replace(new RegExp(` (${DIFFERENT_FEATURES.join("|")})(?= |"|$)`, "g"), "");
    });
}

const results = {};
if(target !== "v86") results.qemu = await reference();
if(target !== "qemu") results.v86 = await actual();
const summary = { stage, cores, jit };
for(const [side, r] of Object.entries(results))
{
    summary[side] = { ms: r.ms, login_ms: r.login_ms, snapshot_bytes: r.snapshot_bytes, powered_off: r.powered_off };
    if(stage === "initramfs")
    {
        assert.match(r.transcript, new RegExp(`A32_INIT_START cpus=${cores} machine=armv7l`), side + ": the cores and the machine");
        assert.ok(!/A32_PROBE_FAIL/.test(r.transcript), side + ": " + r.transcript.match(/A32_PROBE_FAIL[^\n]*/)?.[0]);
    }
}
if(stage === "initramfs")
{
    // (the reference's transcript of an earlier run, when this one is v86's alone)
    const qemu_log = directory + `qemu-${stage}-${cores}c.log`;
    const qemu_text = results.qemu?.transcript ?? (fs.existsSync(qemu_log) ? fs.readFileSync(qemu_log, "latin1") : null);
    if(results.v86) workload_lines(results.v86.transcript, "v86");
    if(qemu_text && results.v86)
    {
        const a = workload_lines(qemu_text, "qemu"), b = workload_lines(results.v86.transcript, "v86");
        for(let i = 0; i < Math.max(a.length, b.length); i++) assert.equal(b[i], a[i], `workload line ${i + 1}`);
        summary.workload_lines = a.length;
    }
}
if(stage === "live") for(const [side, r] of Object.entries(results)) assert.ok(r.login_ms, side + ": no login prompt");
fs.writeFileSync(directory + `result-${stage}-${cores}c${jit ? "-jit" : ""}.json`, JSON.stringify(summary, null, 2) + "\n");
console.log(JSON.stringify(summary));
console.log(`A32_LINUX_BOOT_OK ${stage} ${cores}c`);
process.exit(0);
                                                                                                                                                                                                                                                    source/v64/tests/a32/mmu.c                                                                          0000644 0000000 0000000 00000031626 00000000000 012365  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AArch32 MMU against QEMU's cortex-a15 (docs/aarch32-plan.md R3): the
// short descriptors (sections and supersections, small and large pages,
// AP[2:0], XN and PXN, the domains, TTBCR.N and TTBR1, SCTLR.AFE's access
// flag, TEX remap and Device memory's alignment, ASIDs and TLB maintenance)
// and the long ones (LPAE: blocks and pages, AP, XN, PXN, AF, the levels'
// faults). Each probe is a privileged and an unprivileged read, write and
// execution; a fault prints its FSR and whether FAR is the address.
#include <a32.h>
#include <stdio.h>

uint32_t probe_ldr(uint32_t va), probe_ldrt(uint32_t va), probe_exec(uint32_t va);
void probe_str(uint32_t va, uint32_t value), probe_strt(uint32_t va, uint32_t value);
uint32_t run_user(void (*function)(void), uint32_t argument);
extern char probe_return[], user_returned[];

static uint32_t l1[4096] __attribute__((aligned(16384)));
static uint32_t l1b[4096] __attribute__((aligned(16384)));
static uint32_t l2[4][256] __attribute__((aligned(1024)));
static uint64_t lpae1[4] __attribute__((aligned(32)));
static uint64_t lpae2[2][512] __attribute__((aligned(4096)));
static uint64_t lpae3[512] __attribute__((aligned(4096)));

// the test memory: physical 0x41000000 up, 4 MiB
#define TEST_PA 0x41000000u

#define XN (1 << 4)
#define PXN 1
#define NG (1 << 17)
#define SECTION(pa, ap, domain, flags) \
    (((pa) & 0xFFF00000) | ((ap) & 3) << 10 | ((ap) >> 2 & 1) << 15 | (domain) << 5 | 2 | (flags))
#define TABLE(pa, domain, pxn) (((uint32_t)(pa) & 0xFFFFFC00) | (domain) << 5 | (pxn) << 2 | 1)
#define SMALL(pa, ap, flags) (((pa) & 0xFFFFF000) | ((ap) & 3) << 4 | ((ap) >> 2 & 1) << 9 | 2 | (flags))
#define LARGE(pa, ap, flags) (((pa) & 0xFFFF0000) | ((ap) & 3) << 4 | ((ap) >> 2 & 1) << 9 | 1 | (flags))

static int hook(struct a32_frame *frame, int kind)
{
    // (SVC #0xFF from User mode: back to run_user's caller)
    if(kind == A32_SVC && !(frame->cpsr & 1 << 5) && (*(volatile uint32_t *)(frame->pc - 4) & 0xFFFFFF) == 0xFF)
    {
        frame->pc = (uint32_t)user_returned;
        frame->cpsr = 0x1D3;
        return 1;
    }
    return 0;
}

static void tlb_flush(void)
{
    a32_dsb();
    a32_mcr(0, c8, c7, 0, 0);
    a32_mcr(0, c7, c5, 0, 0);
    a32_dsb();
    a32_isb();
}

static void sctlr_set(uint32_t set, uint32_t clear)
{
    a32_mcr(0, c1, c0, 0, (a32_mrc(0, c1, c0, 0) | set) & ~clear);
    a32_isb();
}

// one access's outcome: its value or "-" for a write that went through, else
// "f" and the FSR, "!" when FAR is not the address
static void outcome(char kind, uint32_t va, int faulted, uint32_t value)
{
    struct a32_fault f;
    a32_caught(&f);
    if(f.taken)
        printf(" %c:f%x%s", kind, (unsigned)f.fsr, f.far == va ? "" : "!");
    else if(faulted < 0)
        printf(" %c:-", kind);
    else
        printf(" %c:%x", kind, (unsigned)value);
}

// (code at a probe's page: offset 0x800 privileged, 0x810 User's)
static void plant_code(uint32_t pa)
{
    volatile uint32_t *code = (volatile uint32_t *)(pa + 0x800);
    code[0] = 0xE3A00077; // mov r0, #0x77
    code[1] = 0xE12FFF1E; // bx lr
    code[4] = 0xE3A00078; // mov r0, #0x78
    code[5] = 0xEF0000FF; // svc #0xff
    a32_dsb();
    a32_mcr(0, c7, c5, 0, 0);
    a32_isb();
}

static void probe(const char *name, uint32_t va)
{
    printf("%s:", name);
    a32_expect(4);
    uint32_t v = probe_ldr(va);
    outcome('r', va, 0, v);
    a32_expect(4);
    probe_str(va + 4, 0x5A5A0000 | (va >> 20));
    outcome('w', va + 4, -1, 0);
    a32_expect(4);
    v = probe_ldrt(va + 8);
    outcome('R', va + 8, 0, v);
    a32_expect(4);
    probe_strt(va + 12, 0xA5A50000 | (va >> 20));
    outcome('W', va + 12, -1, 0);
    // (execution: a prefetch abort returns to probe_exec's caller, or to run_user's)
    a32_return_pc = (uint32_t)probe_return;
    a32_expect(4);
    v = probe_exec(va + 0x800);
    outcome('x', va + 0x800, 0, v);
    a32_return_pc = (uint32_t)user_returned;
    a32_return_cpsr = 0x1D3;
    a32_expect(4);
    v = run_user((void (*)(void))(va + 0x810), 0);
    outcome('X', va + 0x810, 0, v);
    a32_return_pc = a32_return_cpsr = 0;
    printf("\n");
}

static void short_descriptors(void)
{
    // identity sections of RAM, normal write-back (TEX 001, C, B), full access, domain 0
    for(uint32_t mb = 0x400; mb < 0x480; mb++) l1[mb] = SECTION(mb << 20, 3, 0, 1 << 12 | 1 << 3 | 1 << 2);
    for(uint32_t i = 0; i < 4; i++)
    {
        uint32_t pa = TEST_PA + (i << 20);
        for(uint32_t w = 0; w < 4; w++) *(volatile uint32_t *)(pa + 4 * w) = 0x1000 * (i + 1) + w;
        plant_code(pa);
        for(uint32_t page = 1; page < 32; page++)
        {
            *(volatile uint32_t *)(pa + (page << 12)) = 0x2000 * (i + 1) + page;
            *(volatile uint32_t *)(pa + (page << 12) + 8) = 0x3000 * (i + 1) + page;
            plant_code(pa + (page << 12));
        }
    }
    // sections at 0x80000000 up (domain 1): AP 001, 010, 011 XN, 101, 110, 000, 011 PXN, 111
    const uint32_t aps[] = { 1, 2, 3, 5, 6, 0, 3, 7 };
    const uint32_t flags[] = { 0, 0, XN, 0, 0, 0, PXN, 0 };
    for(int i = 0; i < 8; i++) l1[0x800 + i] = SECTION(TEST_PA, aps[i], 1, flags[i]);
    // pages at 0x80800000 (domain 2): small AP 011, 010 XN, none, 001; large AP 011 at + 64 KiB;
    // a table with PXN at 0x80900000 (domain 2, small AP 011)
    l1[0x808] = TABLE(l2[0], 2, 0);
    l2[0][0] = SMALL(TEST_PA + 0x1000, 3, 0);
    l2[0][1] = SMALL(TEST_PA + 0x2000, 2, 1);
    l2[0][2] = 0;
    l2[0][3] = SMALL(TEST_PA + 0x4000, 1, 0);
    for(int i = 16; i < 32; i++) l2[0][i] = LARGE(TEST_PA + 0x10000, 3, 0);
    l1[0x809] = TABLE(l2[1], 2, 1);
    l2[1][0] = SMALL(TEST_PA + 0x5000, 3, 0);
    // a supersection at 0x81000000 (TEST_PA's 16 MiB: 0x41000000), domain 0
    for(int i = 0; i < 16; i++) l1[0x810 + i] = SECTION(TEST_PA, 3, 0, 1 << 18);
    tlb_flush();
    a32_mcr(0, c2, c0, 2, 0);
    a32_mcr(0, c2, c0, 0, (uint32_t)l1);
    a32_mcr(0, c3, c0, 0, 0x5); // domains 0 and 1 client, 2 none
    a32_mcr(0, c3, c0, 0, 0x15); // and 2 client
    a32_isb();
    sctlr_set(1 | 1 << 2 | 1 << 12, 0);
    printf("mmu on: sctlr %#x\n", (unsigned)a32_mrc(0, c1, c0, 0));

    probe("section ap1", 0x80000000);
    probe("section ap2", 0x80100000);
    probe("section ap3 xn", 0x80200000);
    probe("section ap5", 0x80300000);
    probe("section ap6", 0x80400000);
    probe("section ap0", 0x80500000);
    probe("section ap3 pxn", 0x80600000);
    probe("section ap7", 0x80700000);
    probe("page ap3", 0x80800000);
    probe("page ap2 xn", 0x80801000);
    probe("page none", 0x80802000);
    probe("page ap1", 0x80803000);
    probe("large page", 0x80810000);
    probe("large page + 4k", 0x80811000);
    probe("table pxn", 0x80900000);
    probe("no section", 0x80A00000);
    probe("supersection", 0x81000000);
    probe("supersection + 3m", 0x81300000);

    // the domains: 1 none, 2 manager; then 1 manager, 2 none (no TLB maintenance)
    a32_mcr(0, c3, c0, 0, 0x31);
    a32_isb();
    probe("domain 1 none", 0x80000000);
    probe("domain 2 manager, page none", 0x80802000);
    probe("domain 2 manager, page ap1", 0x80803000);
    probe("domain 2 manager, table pxn", 0x80900000);
    a32_mcr(0, c3, c0, 0, 0x0D);
    a32_isb();
    probe("domain 1 manager, ap0", 0x80500000);
    probe("domain 1 manager, xn", 0x80200000);
    probe("domain 2 none", 0x80800000);
    a32_mcr(0, c3, c0, 0, 0x15);
    a32_isb();

    // TTBCR.N 1: 0x80000000 up from TTBR1 (its own sections), then PD1
    for(uint32_t mb = 0x800; mb < 0x1000; mb++) l1b[mb] = SECTION(TEST_PA + 0x100000, 3, 0, 0);
    a32_mcr(0, c2, c0, 1, (uint32_t)l1b);
    a32_mcr(0, c2, c0, 2, 1);
    tlb_flush();
    probe("ttbr1", 0x80000000);
    probe("ttbr0 below", 0x40900000);
    a32_mcr(0, c2, c0, 2, 0);
    tlb_flush();

    // SCTLR.AFE: AP[0] the access flag (AP[2:1] the permissions)
    l1[0x80B] = SECTION(TEST_PA, 2, 1, 0);
    l1[0x80C] = SECTION(TEST_PA, 3, 1, 0);
    l2[2][0] = SMALL(TEST_PA + 0x1000, 2, 0);
    l2[2][1] = SMALL(TEST_PA + 0x2000, 3, 0);
    l2[2][2] = SMALL(TEST_PA + 0x3000, 7, 0);
    l1[0x80D] = TABLE(l2[2], 1, 0);
    tlb_flush();
    sctlr_set(1 << 29, 0);
    probe("afe section af 0", 0x80B00000);
    probe("afe section ap 01", 0x80C00000);
    probe("afe page af 0", 0x80D00000);
    probe("afe page ap 01", 0x80D01000);
    probe("afe page ap 11", 0x80D02000);
    sctlr_set(0, 1 << 29);
    tlb_flush();

    // Normal memory: unaligned loads without SCTLR.A, and with TEX remap
    // (index 7, TEX[0]:C:B, Normal). (Device memory's alignment faults: QEMU
    // has none with the short descriptors, v86 takes them, docs/arm32.md)
    l1[0x80F] = SECTION(TEST_PA, 3, 0, 1 << 12 | 1 << 3 | 1 << 2);
    tlb_flush();
    struct a32_fault f;
    uint32_t v;
    const uint32_t unaligned[] = { 0x80F00001, 0x80F00003 };
    for(int i = 0; i < 2; i++)
    {
        a32_expect(4);
        v = probe_ldr(unaligned[i]);
        a32_caught(&f);
        printf("unaligned %#x: %s %#x\n", (unsigned)unaligned[i], f.taken ? "fault" : "value", (unsigned)(f.taken ? f.fsr : v));
    }
    a32_mcr(0, c10, c2, 0, 0x000A0004 | 0xAAA8);
    a32_mcr(0, c10, c2, 1, 0x44E048E0);
    sctlr_set(1 << 28, 0);
    tlb_flush();
    for(int i = 0; i < 2; i++)
    {
        a32_expect(4);
        v = probe_ldr(unaligned[i]);
        a32_caught(&f);
        printf("tre unaligned %#x: %s %#x\n", (unsigned)unaligned[i], f.taken ? "fault" : "value", (unsigned)(f.taken ? f.fsr : v));
    }
    sctlr_set(0, 1 << 28);
    tlb_flush();

    // ASIDs: a non-global section under ASID 1 in l1, under ASID 2 in l1b
    l1[0x811] = SECTION(TEST_PA, 3, 0, NG);
    for(uint32_t mb = 0x400; mb < 0x480; mb++) l1b[mb] = l1[mb];
    l1b[0x811] = SECTION(TEST_PA + 0x200000, 3, 0, NG);
    tlb_flush();
    a32_mcr(0, c13, c0, 1, 1);
    a32_isb();
    printf("asid 1: %#x\n", (unsigned)probe_ldr(0x81100000));
    a32_mcr(0, c13, c0, 1, 2);
    a32_mcr(0, c2, c0, 0, (uint32_t)l1b);
    a32_isb();
    printf("asid 2: %#x\n", (unsigned)probe_ldr(0x81100000));
    a32_mcr(0, c13, c0, 1, 1);
    a32_mcr(0, c2, c0, 0, (uint32_t)l1);
    a32_isb();
    printf("asid 1 again: %#x\n", (unsigned)probe_ldr(0x81100000));
    // TLBIMVA: a changed descriptor after its maintenance; TLBIASID
    l1[0x811] = SECTION(TEST_PA + 0x300000, 3, 0, NG);
    a32_dsb();
    a32_mcr(0, c8, c7, 1, 0x81100000 | 1);
    a32_dsb();
    a32_isb();
    printf("after tlbimva: %#x\n", (unsigned)probe_ldr(0x81100000));
    l1[0x811] = SECTION(TEST_PA + 0x100000, 3, 0, NG);
    a32_dsb();
    a32_mcr(0, c8, c7, 2, 1);
    a32_dsb();
    a32_isb();
    printf("after tlbiasid: %#x\n", (unsigned)probe_ldr(0x81100000));
    a32_mcr(0, c13, c0, 1, 0);
    a32_isb();

    sctlr_set(0, 1 | 1 << 2 | 1 << 12);
    tlb_flush();
    printf("mmu off\n");
}

// LPAE: TTBCR.EAE, MAIR0 (attribute 0 Normal write-back, 1 Device)
#define BLOCK(pa, ap, flags) ((uint64_t)(pa) | 1 | 0 << 2 | (uint64_t)(ap) << 6 | 3 << 8 | 1 << 10 | (flags))
#define PAGE3(pa, ap, flags) ((uint64_t)(pa) | 3 | 0 << 2 | (uint64_t)(ap) << 6 | 3 << 8 | 1 << 10 | (flags))
#define LXN ((uint64_t)1 << 54)
#define LPXN ((uint64_t)1 << 53)
#define LNOAF ((uint64_t)1 << 10)

static void long_descriptors(void)
{
    // level 1: 0x40000000 (RAM) and 0x80000000 (the probes) through level 2 tables
    lpae1[0] = 0;
    lpae1[1] = (uint32_t)lpae2[0] | 3;
    lpae1[2] = (uint32_t)lpae2[1] | 3;
    lpae1[3] = 0;
    for(int i = 0; i < 512; i++) lpae2[0][i] = BLOCK(0x40000000u + (i << 21), 0, 0);
    for(int i = 0; i < 512; i++) lpae2[1][i] = 0;
    // 2 MiB blocks at 0x80000000 up: AP 00 (PL1 RW), 01 (all RW), 10 (PL1 RO), 11 (all RO), 01 XN, 01 PXN, AF 0
    const uint64_t ap[] = { 0, 1, 2, 3, 1, 1, 1 };
    const uint64_t flags[] = { 0, 0, 0, 0, LXN, LPXN, 0 };
    for(int i = 0; i < 7; i++) lpae2[1][i] = BLOCK(TEST_PA, ap[i], flags[i]);
    lpae2[1][6] &= ~LNOAF;
    // 4 KiB pages at 0x80E00000: AP 01, invalid, AP 01 AF 0
    lpae2[1][7] = (uint32_t)lpae3 | 3;
    for(int i = 0; i < 512; i++) lpae3[i] = 0;
    lpae3[0] = PAGE3(TEST_PA + 0x1000, 1, 0);
    lpae3[2] = PAGE3(TEST_PA + 0x3000, 1, 0) & ~LNOAF;
    a32_dsb();
    // MAIR0 (PRRR's register): attribute 0 0xFF, 1 0x04
    a32_mcr(0, c10, c2, 0, 0x04FF);
    a32_mcrr(0, c2, (uint64_t)(uint32_t)lpae1);
    a32_mcr(0, c2, c0, 2, 1u << 31);
    tlb_flush();
    sctlr_set(1 | 1 << 2 | 1 << 12, 0);
    printf("lpae on: ttbcr %#x\n", (unsigned)a32_mrc(0, c2, c0, 2));
    probe("lpae block ap0", 0x80000000);
    probe("lpae block ap1", 0x80200000);
    probe("lpae block ap2", 0x80400000);
    probe("lpae block ap3", 0x80600000);
    probe("lpae block xn", 0x80800000);
    probe("lpae block pxn", 0x80A00000);
    probe("lpae block af 0", 0x80C00000);
    probe("lpae page", 0x80E00000);
    probe("lpae page invalid", 0x80E01000);
    probe("lpae page af 0", 0x80E02000);
    probe("lpae level 2 invalid", 0x81000000);
    probe("lpae level 1 invalid", 0xC0000000);
    sctlr_set(0, 1 | 1 << 2 | 1 << 12);
    a32_mcr(0, c2, c0, 2, 0);
    tlb_flush();
    printf("lpae off\n");
}

int main(int argc, char **argv)
{
    a32_exception_hook = hook;
    short_descriptors();
    long_descriptors();
    return 0;
}
                                                                                                          source/v64/tests/a32/mmu_asm.S                                                                      0000644 0000000 0000000 00000001407 00000000000 013177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The probes of tests/a32/mmu.c: one access each, its fault (if any)
// recorded by the runtime's expected exception (a32_expect(4) skips it)

    .syntax unified
    .arm
    .text
    .global probe_ldr, probe_str, probe_ldrt, probe_strt, probe_exec, probe_return
probe_ldr:
    ldr     r0, [r0]
    bx      lr
probe_str:
    str     r1, [r0]
    bx      lr
probe_ldrt:
    // (Rt and Rn apart: LDRT writes Rn back)
    ldrt    r1, [r0]
    mov     r0, r1
    bx      lr
probe_strt:
    strt    r1, [r0]
    bx      lr
// probe_exec(va): calls the code at va (mov r0, #0x77; bx lr); a prefetch
// abort returns to probe_return (tests/a32/mmu.c's hook)
probe_exec:
    push    {r4, lr}
    mov     r1, r0
    mov     r0, #0
    blx     r1
probe_return:
    pop     {r4, pc}
                                                                                                                                                                                                                                                         source/v64/tests/a32/platform.c                                                                     0000644 0000000 0000000 00000010627 00000000000 013411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The 32-bit virt platform against QEMU's (docs/aarch32-plan.md R4): PSCI
// over HVC with the SMC32 function numbers, the generic timer's CP15
// registers and its interrupts through the GICv3 CPU interface's CP15
// registers, an SGI to itself, a second core started with CPU_ON in SVC
// mode (run with 2 cores).
#include <a32.h>
#include <stdio.h>

#define GICD 0x08000000u
#define GICR(core) (0x080A0000u + (core) * 0x20000u)
#define MMIO32(a) (*(volatile uint32_t *)(a))

static volatile uint32_t last_intid = 1023, interrupts;

static void irq(struct a32_frame *frame, int kind)
{
    uint32_t intid = a32_mrc(0, c12, c12, 0); // ICC_IAR1
    last_intid = intid;
    interrupts++;
    // (the timers' interrupts are levels: masked before the EOI)
    if(intid == 27) a32_mcr(0, c14, c3, 1, 3);
    if(intid == 30) a32_mcr(0, c14, c2, 1, 3);
    a32_mcr(0, c12, c12, 1, intid); // ICC_EOIR1
    a32_isb();
    (void)frame;
    (void)kind;
}

static void gic_init(unsigned core)
{
    if(core == 0) MMIO32(GICD) = 1 << 4 | 1 << 1 | 1;
    MMIO32(GICR(core) + 0x14) &= ~2u;
    while(MMIO32(GICR(core) + 0x14) & 4) {}
    MMIO32(GICR(core) + 0x10000 + 0x80) = ~0u;      // GICR_IGROUPR0: group 1
    for(int i = 0; i < 8; i++) MMIO32(GICR(core) + 0x10000 + 0x400 + 4 * i) = 0x80808080;
    MMIO32(GICR(core) + 0x10000 + 0x100) = 1 << 5 | 1 << 27 | 1 << 30; // SGI 5, PPI 27, 30
    a32_mcr(0, c12, c12, 5, 7);  // ICC_SRE
    a32_isb();
    a32_mcr(0, c4, c6, 0, 0xFF); // ICC_PMR
    a32_mcr(0, c12, c12, 7, 1);  // ICC_IGRPEN1
    a32_isb();
}

static void wait_interrupt(uint32_t count)
{
    // (interrupts on, spinning: a lost interrupt shows as the count it reached)
    __asm__ volatile("cpsie i" ::: "memory");
    for(uint32_t spins = 0; interrupts < count && spins < 20000000; spins++) __asm__ volatile("" ::: "memory");
    __asm__ volatile("cpsid i" ::: "memory");
}

static volatile uint32_t core1_mpidr, core1_cpsr, core1_context, core1_up;
static void core_main(unsigned core)
{
    core1_mpidr = a32_mrc(0, c0, c0, 5);
    core1_cpsr = a32_cpsr();
    core1_context = core;
    a32_dsb();
    core1_up = 1;
    a32_dsb();
    __asm__ volatile("sev");
}

int main(int argc, char **argv)
{
    printf("psci version %#x migrate_info_type %d\n", (unsigned)a32_hvc(0x84000000, 0, 0, 0), (int)a32_hvc(0x84000006, 0, 0, 0));
    printf("psci affinity_info core 0: %d core 1: %d\n", (int)a32_hvc(0x84000004, 0, 0, 0), (int)a32_hvc(0x84000004, 1, 0, 0));
    printf("cntfrq %u cntkctl %#x\n", (unsigned)a32_mrc(0, c14, c0, 0), (unsigned)a32_mrc(0, c14, c1, 0));
    uint64_t a = a32_mrrc(1, c14);
    for(volatile int i = 0; i < 10000; i++) {}
    uint64_t b = a32_mrrc(1, c14), p = a32_mrrc(0, c14);
    printf("cntvct increases %d, cntpct %d\n", b > a, p >= a);
    printf("icc_sre %#x\n", (unsigned)a32_mrc(0, c12, c12, 5));

    a32_interrupt_handler = irq;
    gic_init(0);
    printf("icc_sre %#x icc_pmr %#x icc_igrpen1 %#x\n", (unsigned)a32_mrc(0, c12, c12, 5), (unsigned)a32_mrc(0, c4, c6, 0),
        (unsigned)a32_mrc(0, c12, c12, 7));

    // the virtual timer: TVAL 10 us on
    a32_mcr(0, c14, c3, 0, 10000);
    a32_mcr(0, c14, c3, 1, 1);
    a32_isb();
    wait_interrupt(1);
    printf("virtual timer: interrupts %u intid %u ctl %#x\n", (unsigned)interrupts, (unsigned)last_intid, (unsigned)a32_mrc(0, c14, c3, 1));
    a32_mcr(0, c14, c3, 1, 0);

    // the physical timer: CVAL 10 us on
    a32_mcrr(2, c14, a32_mrrc(0, c14) + 10000);
    a32_mcr(0, c14, c2, 1, 1);
    a32_isb();
    wait_interrupt(2);
    printf("physical timer: interrupts %u intid %u ctl %#x\n", (unsigned)interrupts, (unsigned)last_intid, (unsigned)a32_mrc(0, c14, c2, 1));
    a32_mcr(0, c14, c2, 1, 0);

    // SGI 5 to this core (ICC_SGI1R: INTID 5, target list core 0)
    a32_dsb();
    a32_mcrr(0, c12, (uint64_t)5 << 24 | 1);
    a32_isb();
    wait_interrupt(3);
    printf("sgi: interrupts %u intid %u\n", (unsigned)interrupts, (unsigned)last_intid);

    // the second core
    a64_core_main = core_main;
    a32_dsb();
    printf("cpu_on core 1: %d\n", (int)a32_cpu_on(1));
    for(int spins = 0; !core1_up && spins < 10000000; spins++) __asm__ volatile("wfe");
    printf("core 1: up %u mpidr %#x mode %#x context %u\n", (unsigned)core1_up, (unsigned)core1_mpidr, (unsigned)(core1_cpsr & 0x1F),
        (unsigned)core1_context);
    printf("cpu_on core 1 again: %d\n", (int)a32_cpu_on(1));
    printf("psci affinity_info core 1: %d\n", (int)a32_hvc(0x84000004, 1, 0, 0));
    return 0;
}
                                                                                                         source/v64/tests/a32/ranchu_devices.mjs                                                             0000755 0000000 0000000 00000057031 00000000000 015121  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The ranchu machine's devices (docs/aarch32-plan.md R6.1, R6.2) on
// cpu_type "arm32", driven through their registers as the Android
// emulator image's Linux 3.10 drives them:
// - the device tree (src/virt/ranchu.js, decompiled by dtc): the GICv2, the
//   simple-framebuffer at the top of RAM kept out of the memory node, the
//   goldfish devices with both compatible strings, the virtio-mmio slots
//   from the last one down; the kernel command line;
// - virtio-mmio's legacy transport (version 1): VIRTIO_F_VERSION_1 hidden, a
//   queue placed by GuestPageSize and QueuePFN, a virtio-blk read through
//   it, a reset clearing the page frame numbers;
// - goldfish_events: its pages (the name, the event bits, the axes), keys
//   from the keyboard's scancodes, a touch, the interrupt while events wait;
// - goldfish_battery, goldfish_audio (a buffer empty after its samples' time);
// - goldfish_pipe: qemud's boot-properties over a channel (the frames, the
//   wake on read), an unknown service refused, a snapshot closing channels;
//   with ranchu_gpu "host", the GLES host's services (src/gles/,
//   docs/gles-proxy-plan.md E1): GLProcessPipe's process id, an
//   "opengles" connection's replies read in pages, the reader woken, the
//   process's objects gone with its pipe;
// - the framebuffer: RGB565 written to the simple-framebuffer reaches the
//   screen at the next third vblank, and only when it changed;
// - /cache's empty filesystem (src/android/ext4.js): the superblock, the
//   group, the root directory and lost+found;
// - a snapshot of the machine restores (machine type, GICv2 state, the
//   GLES host's slot) and is refused by the virt machine and by a ranchu
//   machine without the GLES host.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import { fileURLToPath } from "node:url";
import { PictureSink } from "../lib/picture_sink.mjs";
import { make_empty_ext4, ext4_writes } from "../../src/android/ext4.js";
import { ranchu_cmdline, ranchu_dtb, ranchu_framebuffer, RANCHU_DISPLAY } from "../../src/virt/ranchu.js";
import { decode_reply, encode_command } from "../../src/gles/gles_wire.js";
import { fake_renderer } from "../gles/lib.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const RAM = 0x40000000, MEMORY = 64 << 20;

// ---- the device tree and the command line

{
    const framebuffer = ranchu_framebuffer(MEMORY, RANCHU_DISPLAY);
    assert.deepEqual(framebuffer, { base: RAM + MEMORY - 0x200000, size: 0x200000, width: 480, height: 800 });
    const directory = fs.mkdtempSync(os.tmpdir() + "/ranchu-dtb-");
    fs.writeFileSync(directory + "/ranchu.dtb", ranchu_dtb({ cores: 2, memory_size: MEMORY, bootargs: "x", arm32: true, framebuffer }));
    const dts = execFileSync("dtc", ["-q", "-I", "dtb", "-O", "dts", directory + "/ranchu.dtb"], { encoding: "utf8" });
    const has = (pattern, what) => assert.match(dts, pattern, what);
    has(/model = "ranchu"/, "the board's name");
    has(/memory@40000000 \{[^}]*reg = <0x00 0x40000000 0x00 0x3e00000>/, "RAM without the framebuffer");
    has(/framebuffer@43e00000 \{[^}]*format = "r5g6b5";[^}]*stride = <0x3c0>;[^}]*height = <0x320>;[^}]*width = <0x1e0>;[^}]*compatible = "simple-framebuffer"/,
        "the simple-framebuffer");
    assert.doesNotMatch(dts, /goldfish_fb@/, "no goldfish framebuffer with the simple-framebuffer");
    for(const [name, kind] of [["goldfish_pipe@a010000", "android-pipe"], ["goldfish_events@9040000", "goldfish-events-keypad"],
        ["goldfish_audio@9030000", "goldfish-audio"], ["goldfish_battery@9020000", "goldfish-battery"]])
    {
        has(new RegExp(name + " \\{[^}]*compatible = \"google," + kind + "\", \"generic," + kind + "\""), name);
    }
    has(/intc@8000000 \{[^}]*reg = <0x00 0x8000000 0x00 0x10000 0x00 0x8010000 0x00 0x10000>;[^}]*compatible = "arm,cortex-a15-gic"/, "a GICv2");
    has(/interrupts = <0x01 0x0d 0x304 0x01 0x0e 0x304 0x01 0x0b 0x304 0x01 0x0a 0x304>/, "the timer's PPIs for both cores");
    const slots = [...dts.matchAll(/virtio_mmio@([0-9a-f]+)/g)].map(m => parseInt(m[1], 16));
    assert.equal(slots.length, 32);
    assert.ok(slots.every((base, i) => i === 0 || base < slots[i - 1]), "the slots from the last one down");
    has(/psci \{[^}]*cpu_on = <0x84000003>/, "32-bit PSCI calls");
    has(/cpu@1 \{[^}]*enable-method = "psci";[^}]*compatible = "arm,cortex-a15"/, "the cores");
    // (arm64's: the virt machine's GICv3, the goldfish framebuffer)
    fs.writeFileSync(directory + "/ranchu64.dtb", ranchu_dtb({ cores: 1, memory_size: MEMORY, arm32: false }));
    const dts64 = execFileSync("dtc", ["-q", "-I", "dtb", "-O", "dts", directory + "/ranchu64.dtb"], { encoding: "utf8" });
    assert.match(dts64, /compatible = "arm,gic-v3"/);
    assert.match(dts64, /goldfish_fb@9010000 \{[^}]*compatible = "google,goldfish-fb", "generic,goldfish-fb"/);
    assert.match(dts64, /memory@40000000 \{[^}]*reg = <0x00 0x40000000 0x00 0x4000000>/);
    fs.rmSync(directory, { recursive: true });

    const cmdline = ranchu_cmdline({ arm32: true, bootanim: false });
    assert.equal(cmdline, "qemu=1 androidboot.hardware=ranchu console=ttyAMA0 android.checkjni=1 qemu.gles=0 qemu.encrypt=0 qemu.wifi=0 " +
        "loop.max_part=7 android.bootanim=0");
    assert.match(ranchu_cmdline({ arm32: true, gles: true }), / qemu\.gles=1 /, "ranchu_gpu \"host\"");
    console.log("PASS: the device tree and the command line");
}

// ---- the machine

const DISK = 1 << 20;
const disk = new Uint8Array(DISK).map((_, i) => i * 7 + (i >> 9) & 0xFF);
const sink = new PictureSink();
const emulator = new V86({
    cpu_type: "arm32", machine_type: "ranchu", memory_size: MEMORY, autostart: false, log_level: 0,
    wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
    virtio_disks: [{ buffer: disk.slice().buffer }], net_device: { type: "none" },
    graphics_adapter: "none", screen_adapter: sink,
    ranchu_properties: { "ro.test.answer": "42" }, ranchu_gpu: "host",
    // (the GLES host's renderer: the page's, here one that keeps the batches)
    graphics_adapter_renderer_channel: fake_renderer(),
});
await new Promise((resolve, reject) => {
    emulator.add_listener("emulator-loaded", resolve);
    emulator.add_listener("emulator-error", reject);
});
const cpu = emulator.v86.cpu;
assert.equal(cpu.machine_type, "ranchu");
assert.equal(cpu.gic_v2, true, "arm32's ranchu has a GICv2");
assert.equal(cpu.devices.pci, undefined, "no PCIe host");
/** the interrupt lines' levels the devices set */
const levels = new Map();
const set_irq = cpu.set_irq.bind(cpu);
cpu.set_irq = (intid, level) => { levels.set(intid, level); set_irq(intid, level); };
const SPI = n => 32 + n;
const u16 = (address, value) => cpu.write_blob_physical(new Uint8Array([value & 0xFF, value >> 8]), address);
const u32 = (address, value) => cpu.write_blob_physical(new Uint8Array(new Uint32Array([value]).buffer), address);
const bytes_at = (address, length) => cpu.read_blob_physical(address, length);

// ---- virtio-mmio's legacy transport, with virtio-blk

{
    const transport = cpu.virtio_mmio[31];
    const reg = (offset, value) => value === undefined ? transport.read(offset, 4) >>> 0 : transport.write(offset, 4, value);
    assert.equal(reg(0x000), 0x74726976);
    assert.equal(reg(0x004), 1, "version 1: the legacy transport");
    assert.equal(reg(0x008), 2, "virtio-blk in the last slot");
    const empty = cpu.io.ranges.find(range => range && range.base === 0x0A000000 + 30 * 0x200);
    assert.equal(empty.handler.read(0x004, 4), 1, "an empty slot is legacy too");
    reg(0x070, 0);
    reg(0x070, 1 | 2);
    reg(0x014, 1);
    assert.equal(reg(0x010) & 1, 0, "VIRTIO_F_VERSION_1 is not offered");
    reg(0x014, 0);
    reg(0x024, 0); reg(0x020, 0);
    reg(0x028, 4096);
    const QUEUE = 8, PFN = (RAM + 0x10000) / 4096;
    const DESC = PFN * 4096, AVAIL = DESC + 16 * QUEUE, USED = Math.ceil((AVAIL + 6 + 2 * QUEUE) / 4096) * 4096;
    cpu.write_blob_physical(new Uint8Array(0x3000), DESC);
    reg(0x030, 0);
    assert.ok(reg(0x034) >= QUEUE);
    reg(0x038, QUEUE);
    reg(0x03C, 4096);
    reg(0x040, PFN);
    assert.equal(reg(0x040), PFN, "QueuePFN reads back");
    reg(0x070, 1 | 2 | 4);
    // (a read of sectors 3 and 4: the header, the data, the status)
    const header = RAM + 0x20000, data = RAM + 0x21000, status = RAM + 0x22000;
    cpu.write_blob_physical(new Uint8Array(16), header);
    u32(header, 0); u32(header + 8, 3);
    cpu.write_blob_physical(new Uint8Array([0xFF]), status);
    const descriptor = (n, address, length, flags, next) => {
        u32(DESC + 16 * n, address); u32(DESC + 16 * n + 4, 0); u32(DESC + 16 * n + 8, length);
        u16(DESC + 16 * n + 12, flags); u16(DESC + 16 * n + 14, next);
    };
    descriptor(0, header, 16, 1, 1);
    descriptor(1, data, 1024, 1 | 2, 2);
    descriptor(2, status, 1, 2, 0);
    u16(AVAIL + 4, 0);
    u16(AVAIL + 2, 1);
    reg(0x050, 0);
    for(let i = 0; i < 100 && cpu.read16_physical(USED + 2) !== 1; i++) await new Promise(resolve => setTimeout(resolve, 10));
    assert.equal(cpu.read16_physical(USED + 2), 1, "the used ring, aligned after the available ring");
    assert.equal(bytes_at(status, 1)[0], 0, "VIRTIO_BLK_S_OK");
    assert.deepEqual(bytes_at(data, 1024), disk.subarray(3 * 512, 5 * 512), "sectors 3 and 4");
    assert.equal(reg(0x060) & 1, 1, "the used buffer's interrupt");
    assert.equal(levels.get(SPI(16 + 31)), true);
    reg(0x064, 1);
    assert.equal(levels.get(SPI(16 + 31)), false);
    reg(0x070, 0);
    assert.equal(reg(0x040), 0, "a reset forgets the queue's page");
    console.log("PASS: virtio-mmio's legacy transport (virtio-blk)");
}

// ---- goldfish_events

{
    const events = cpu.devices.goldfish_events;
    const said = [];
    emulator.add_listener("mouse-enable", enabled => said.push(enabled));
    const absolute = [];
    emulator.add_listener("absolute-pointer", state => absolute.push(state));
    const page = (n) => {
        events.write(0x00, n);
        const length = events.read(0x04, 4);
        return Uint8Array.from({ length }, (_, i) => events.read(0x08 + i, 1));
    };
    assert.equal(new TextDecoder().decode(page(0)), "qwerty2");
    assert.deepEqual(said, [true], "the driver probes: the page takes the pointer (once)");
    assert.deepEqual(absolute, [[true, false]], "a touch screen: absolute, the host's cursor stays");
    const bit = (bytes, n) => (bytes[n >> 3] >> (n & 7) & 1) === 1;
    const types = page(0x10000);
    assert.ok(bit(types, 0) && bit(types, 1) && bit(types, 3), "EV_SYN, EV_KEY, EV_ABS");
    const keys = page(0x10001);
    assert.ok(bit(keys, 30) && bit(keys, 102) && bit(keys, 158) && bit(keys, 0x14A), "KEY_A, HOME, BACK, BTN_TOUCH");
    const abs = page(0x10003);
    assert.ok(bit(abs, 0) && bit(abs, 1) && bit(abs, 0x35) && bit(abs, 0x36) && bit(abs, 0x39), "the axes");
    const ranges = new Uint32Array(page(0x20003).slice().buffer);
    assert.deepEqual([...ranges.subarray(0, 4)], [0, 0x7FFF, 0, 0], "ABS_X's range");
    const take = () => {
        const out = [];
        while(levels.get(SPI(5))) out.push([events.read(0, 4), events.read(0, 4), events.read(0, 4) | 0]);
        return out;
    };
    assert.deepEqual(take(), [], "nothing waits");
    emulator.bus.send("keyboard-code", 0x1E);
    emulator.bus.send("keyboard-code", 0x9E);
    emulator.bus.send("keyboard-code", 0xE0);
    emulator.bus.send("keyboard-code", 0x48);
    assert.deepEqual(take(), [[1, 30, 1], [0, 0, 0], [1, 30, 0], [0, 0, 0], [1, 103, 1], [0, 0, 0]], "A down and up, Up (extended) down");
    events.tap(240, 400, 480, 800);
    const x = Math.round(240 / 480 * 0x7FFF), y = Math.round(400 / 800 * 0x7FFF);
    assert.deepEqual(take(), [
        [3, 0x2F, 0], [3, 0x39, 1], [3, 0x35, x], [3, 0x36, y], [1, 0x14A, 1], [3, 0, x], [3, 1, y], [0, 0, 0],
        [3, 0x2F, 0], [3, 0x39, -1], [1, 0x14A, 0], [0, 0, 0],
    ], "a touch down and up");
    events.reset();
    assert.deepEqual(said, [true, false], "a reset: no driver takes the pointer");
    page(0x10000);
    console.log("PASS: goldfish_events");
}

// ---- goldfish_battery and goldfish_audio

{
    const battery = cpu.devices.goldfish_battery;
    assert.deepEqual([0x08, 0x0C, 0x10, 0x14, 0x18].map(r => battery.read(r)), [1, 1, 1, 1, 100], "AC online, charging, good, present, full");
    const audio = cpu.devices.goldfish_audio;
    assert.equal(audio.read(0x18), 0, "no input");
    audio.write(0x04, 3);
    const now = cpu.clock.now();
    audio.write(0x10, 44100 * 4 / 10);
    assert.equal(audio.timer(now + 50) > 0, true, "the buffer plays");
    assert.equal(levels.get(SPI(4)) || false, false);
    audio.timer(now + 101);
    assert.equal(levels.get(SPI(4)), true, "BUFFER_1_EMPTY after 100 ms of samples");
    assert.equal(audio.read(0x00), 1);
    assert.equal(levels.get(SPI(4)), false);
    console.log("PASS: goldfish_battery, goldfish_audio");
}

// ---- goldfish_pipe: qemud's boot properties

{
    const pipe = cpu.devices.goldfish_pipe;
    assert.equal(pipe.read(0x24), 1, "version 1");
    const BUFFER = RAM + 0x30000;
    const command = (channel, cmd, bytes, size) => {
        pipe.write(0x08, channel);
        if(bytes) cpu.write_blob_physical(bytes, BUFFER);
        pipe.write(0x0C, size ?? (bytes ? bytes.length : 0));
        pipe.write(0x10, BUFFER);
        pipe.write(0x00, cmd);
        return pipe.read(0x04) | 0;
    };
    const text = s => new TextEncoder().encode(s);
    assert.equal(command(7, 1), 0, "OPEN");
    assert.equal(command(7, 4, text("pipe:qemud:boot-properties\0")), 27, "the service's name");
    assert.equal(command(7, 6, null, 64), -2, "nothing to read yet: AGAIN");
    assert.equal(command(7, 7), 0, "WAKE_ON_READ");
    assert.equal(levels.get(SPI(7)) || false, false);
    assert.equal(command(7, 4, text("0004list")), 8);
    assert.equal(levels.get(SPI(7)), true, "the reader woken");
    assert.equal(pipe.read(0x08), 7, "the channel with wakes");
    assert.equal(pipe.read(0x14), 2, "PIPE_WAKE_READ");
    assert.equal(levels.get(SPI(7)), false);
    assert.equal(command(7, 3), 1 | 2, "POLL: readable and writable");
    const count = command(7, 6, null, 4096);
    const answer = new TextDecoder().decode(bytes_at(BUFFER, count));
    const frames = [];
    for(let at = 0; at < answer.length;)
    {
        const length = parseInt(answer.slice(at, at + 4), 16);
        frames.push(answer.slice(at + 4, at + 4 + length));
        at += 4 + length;
    }
    assert.deepEqual(frames, ["qemu.sf.lcd_density=240", "qemu.hw.mainkeys=0", "ro.test.answer=42", "\0"], "the properties, then the end");
    assert.equal(command(8, 1), 0);
    assert.equal(command(8, 4, text("pipe:camera\0")), -1, "an unknown service is refused");
    assert.equal(command(8, 2), 0, "CLOSE");
    assert.equal(command(8, 3), -1, "a closed channel is gone");
    // (a snapshot: the channels come back with their services' state,
    // docs/gles-proxy-plan.md E5; one of the old kind, channels only, closed)
    pipe.set_state(pipe.get_state());
    assert.equal(levels.get(SPI(7)) || false, false, "no wakes");
    assert.equal(command(7, 3), 2, "POLL: writable, nothing to read");
    assert.equal(command(7, 4, text("0004list")), 8, "the service goes on");
    assert.equal(command(7, 3), 1 | 2, "readable again");
    assert.ok(command(7, 6, null, 4096) > 0);
    pipe.set_state([7]);
    assert.equal(levels.get(SPI(7)), true);
    assert.equal(pipe.read(0x08), 7);
    assert.equal(pipe.read(0x14), 1, "PIPE_WAKE_CLOSED");
    assert.equal(pipe.read(0x08), 0, "no more wakes");
    console.log("PASS: goldfish_pipe");
}

// ---- goldfish_pipe: the GLES host's services (ranchu_gpu "host")

{
    const pipe = cpu.devices.goldfish_pipe;
    const gles = cpu.devices.gles.device;
    const BUFFER = RAM + 0x30000;
    const command = (channel, cmd, bytes, size) => {
        pipe.write(0x08, channel);
        if(bytes) cpu.write_blob_physical(bytes, BUFFER);
        pipe.write(0x0C, size ?? (bytes ? bytes.length : 0));
        pipe.write(0x10, BUFFER);
        pipe.write(0x00, cmd);
        return pipe.read(0x04) | 0;
    };
    const text = s => new TextEncoder().encode(s);
    // the process's id: the library's confirmation (100) answered with a u64
    assert.equal(command(9, 1), 0);
    assert.equal(command(9, 4, text("pipe:GLProcessPipe\0")), 19);
    assert.equal(command(9, 4, new Uint8Array([100, 0, 0, 0])), 4);
    assert.equal(command(9, 6, null, 8), 8);
    const puid = new DataView(bytes_at(BUFFER, 8).buffer).getUint32(0, true);
    assert.ok(puid >= 1);
    // a connection: the flags, then commands; a reply larger than one read
    assert.equal(command(10, 1), 0);
    assert.equal(command(10, 4, text("pipe:opengles\0")), 14);
    assert.equal(command(10, 6, null, 64), -2, "nothing to read: AGAIN");
    assert.equal(command(10, 7), 0, "WAKE_ON_READ");
    const flags_and_puid = new Uint8Array([0, 0, 0, 0, ...encode_command("rcSetPuid", [puid])]);
    assert.equal(command(10, 4, flags_and_puid), flags_and_puid.length);
    assert.equal(pipe.read(0x08), 0, "no reply: no wake");
    assert.equal(command(10, 4, encode_command("rcGetNumConfigs", [4])), 12);
    assert.equal(pipe.read(0x08), 10, "the reader woken");
    assert.equal(pipe.read(0x14), 2, "PIPE_WAKE_READ");
    assert.equal(command(10, 3), 1 | 2, "POLL: readable");
    assert.equal(command(10, 6, null, 64), 8);
    const counts = decode_reply("rcGetNumConfigs", [4], bytes_at(BUFFER, 8));
    const size = (counts.ret + 1) * new DataView(counts.outs[0].slice().buffer).getUint32(0, true) * 4;
    assert.equal(command(10, 4, encode_command("rcGetConfigs", [size, size])), 16);
    const reply = new Uint8Array(size + 4);
    for(let at = 0; at < reply.length;)
    {
        const n = command(10, 6, null, Math.min(1024, reply.length - at));
        assert.ok(n > 0, "the reply in pages");
        reply.set(bytes_at(BUFFER, n), at);
        at += n;
    }
    assert.equal(command(10, 6, null, 64), -2, "all read");
    assert.equal(decode_reply("rcGetConfigs", [size, size], reply).ret, counts.ret);
    // (gralloc's buffer, which the process's end frees)
    assert.equal(command(10, 4, encode_command("rcCreateColorBuffer", [480, 800, 0x1908])), 20);
    assert.equal(command(10, 6, null, 4), 4);
    assert.equal(gles.summary().render_control.color_buffers, 1);
    assert.equal(command(10, 2), 0, "the connection closed");
    assert.equal(gles.summary().render_control.color_buffers, 1, "the process still has it");
    assert.equal(command(9, 2), 0, "the process's pipe closed");
    assert.equal(gles.summary().render_control.color_buffers, 0);
    const summary = gles.summary();
    assert.deepEqual([summary.connections, summary.processes, summary.counts.rcGetConfigs, summary.unknown], [1, 1, 1, {}]);
    console.log("PASS: goldfish_pipe's GLES services");
}

// ---- the framebuffer (the simple-framebuffer's scanout)

{
    const fb = cpu.devices.goldfish_fb;
    const frame = cpu.ranchu_framebuffer;
    assert.equal(frame.base, RAM + MEMORY - 0x200000);
    assert.equal(fb.read(0x00), 480);
    assert.equal(fb.read(0x04), 800);
    assert.equal(fb.read(0x1C), Math.round(480 * 25.4 / 240), "the width in millimetres");
    const pixels = new Uint16Array(480 * 800);
    pixels.fill(0xF800);
    pixels[481] = 0x07E0;
    pixels[480 * 800 - 1] = 0x001F;
    cpu.write_blob_physical(new Uint8Array(pixels.buffer), frame.base);
    let renders = 0;
    const render = fb.render.bind(fb);
    fb.render = source => { renders++; render(source); };
    for(let i = 0; i < 3; i++) fb.on_vblank();
    assert.equal(renders, 1, "drawn at the third vblank");
    const rgb = n => [...sink.rgba.subarray(4 * n, 4 * n + 3)];
    assert.deepEqual(rgb(0), [255, 0, 0]);
    assert.deepEqual(rgb(481), [0, 255, 0]);
    assert.deepEqual(rgb(480 * 800 - 1), [0, 0, 255]);
    for(let i = 0; i < 3; i++) fb.on_vblank();
    assert.equal(renders, 1, "not again while it is the same");
    u16(frame.base, 0xFFFF);
    for(let i = 0; i < 3; i++) fb.on_vblank();
    assert.equal(renders, 2, "again when it changed");
    assert.deepEqual(rgb(0), [255, 255, 255]);
    console.log("PASS: the framebuffer");
}

// ---- /cache's filesystem

{
    const image = make_empty_ext4(64 << 20, "cache", 1595289711);
    const view = new DataView(image.buffer);
    const sb = 1024;
    assert.equal(view.getUint16(sb + 56, true), 0xEF53, "the magic");
    assert.equal(view.getUint32(sb + 4, true), 16384, "the blocks");
    assert.equal(view.getUint32(sb + 24, true), 2, "4 KiB blocks");
    assert.equal(new TextDecoder().decode(image.subarray(sb + 120, sb + 125)), "cache");
    const table = view.getUint32(4096 + 8, true);
    const inode = n => table * 4096 + (n - 1) * 256;
    assert.equal(view.getUint16(inode(2), true), 0x41ED, "the root: a directory");
    const entries = block => {
        const out = [];
        for(let at = block * 4096; at < (block + 1) * 4096;)
        {
            const length = view.getUint16(at + 4, true);
            out.push([view.getUint32(at, true), new TextDecoder().decode(image.subarray(at + 8, at + 8 + image[at + 6]))]);
            at += length;
        }
        return out;
    };
    assert.deepEqual(entries(view.getUint32(inode(2) + 40, true)), [[2, "."], [2, ".."], [11, "lost+found"]]);
    assert.deepEqual(entries(view.getUint32(inode(11) + 40, true)), [[11, "."], [2, ".."]]);
    // (the free counts: the superblock's are the group's)
    assert.equal(view.getUint32(sb + 12, true), view.getUint16(4096 + 12, true));
    assert.equal(view.getUint32(sb + 16, true), view.getUint16(4096 + 14, true));
    // (a larger one, as the metadata's writes: groups of 128 MiB, the superblock's copies in groups 0, 1, 3, 5, 7, 9)
    const writes = ext4_writes(1200 << 20, "userdata", 1);
    const copies = writes.filter(w => w.bytes.length === 1024 && new DataView(w.bytes.buffer).getUint16(56, true) === 0xEF53);
    assert.deepEqual(copies.map(w => [w.offset / 4096 / 32768, new DataView(w.bytes.buffer).getUint16(90, true)]),
        [[1024 / 4096 / 32768, 0], [1, 1], [3, 3], [5, 5], [7, 7], [9, 9]]);
    assert.equal(new DataView(copies[0].bytes.buffer).getUint32(4, true), 1200 << 8, "the blocks");
    assert.throws(() => make_empty_ext4(1000), /a multiple of 4 KiB/);
    console.log("PASS: /cache's filesystem");
}

// ---- snapshots

{
    const state = await emulator.save_state();
    const said = [];
    emulator.add_listener("mouse-enable", enabled => said.push(enabled));
    await emulator.restore_state(state);
    assert.equal(cpu.devices.goldfish_fb.read(0x00), 480);
    assert.deepEqual(said, [true], "goldfish_events' driver ran: the page takes the pointer again");
    const virt = new V86({
        cpu_type: "arm32", memory_size: MEMORY, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", graphics_adapter: "none", net_device: { type: "none" },
    });
    await new Promise(resolve => virt.add_listener("emulator-loaded", resolve));
    await assert.rejects(virt.restore_state(state), /machine_type: "ranchu"/, "the virt machine refuses ranchu's snapshot");
    await virt.destroy();
    const guest = new V86({
        cpu_type: "arm32", machine_type: "ranchu", memory_size: MEMORY, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", graphics_adapter: "none", net_device: { type: "none" },
        virtio_disks: [{ buffer: disk.slice().buffer }],
    });
    await new Promise(resolve => guest.add_listener("emulator-loaded", resolve));
    await assert.rejects(guest.restore_state(state), /ranchu_gpu "host"/, "a machine without the GLES host refuses it");
    await guest.destroy();
    console.log("PASS: snapshots");
}
await emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/a32/runner.mjs                                                                     0000644 0000000 0000000 00000010422 00000000000 013436  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Bare-metal AArch32 guests for cpu_type "arm32" (docs/aarch32-plan.md R2,
// R3): C and assembly built with clang --target=armv7a-none-eabi (ARMv8-A's
// AArch32, VFP and Advanced SIMD, hard float) against tests/a32/baremetal
// and the AArch64 guests' libc, a raw image at RAM + 0x10000; run on QEMU
// 9.2 (-cpu cortex-a15, the 32-bit virt board) and on v86. The result block
// is tests/a64/guest_runner.mjs's.
//
//   build32(name, sources, { cflags, thumb }) -> the directory of guest.bin
//   reference32(directory, { cores })         -> { status, text, ... } from QEMU
//   actual32(directory, { cores })            -> the same from v86
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { root, reference, actual } from "../a64/guest_runner.mjs";

export { root };
const runtime = root + "tests/a32/baremetal/";
const libc = root + "tests/a64/baremetal/";

// the 32-bit reference: cortex-a15 (its generic timer at the v86 frequency),
// everything below 4 GiB
export const QEMU_MACHINE32 = "virt-9.2,gic-version=3,its=off,highmem=off,virtualization=off,secure=off,acpi=off,dtb-randomness=off";
export const QEMU_CPU32 = "cortex-a15,pmu=off,cntfrq=1000000000";

const host = spawnSync("rustc", ["-vV"], { encoding: "utf8" }).stdout.match(/host: (.*)/)[1];
const lld = process.env.LD_LLD || `${spawnSync("rustc", ["--print", "sysroot"], { encoding: "utf8" }).stdout.trim()}/lib/rustlib/${host}/bin/rust-lld`;
const clang = process.env.CLANG || "clang";

function run(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, `${program} ${args.join(" ")}\n${result.stdout}${result.stderr}`);
    return result.stdout;
}

/**
 * Build a guest from `sources` (.c or .S) and the runtime into
 * build/a32-<name>/guest.bin (and guest.elf); `thumb`: the C as T32
 */
export function build32(name, sources, { cflags = [], optimize = "-O2", thumb = false } = {})
{
    const directory = `${root}build/a32-${name}/`;
    fs.mkdirSync(directory, { recursive: true });
    const common = ["--target=armv7a-none-eabihf", "-march=armv8-a+crc", "-mfpu=crypto-neon-fp-armv8", "-mfloat-abi=hard",
        "-ffreestanding", "-fno-builtin", "-fno-stack-protector", "-fno-pic", "-mno-unaligned-access", "-mno-implicit-float", "-nostdlibinc",
        "-isystem", runtime + "include", "-isystem", libc + "include", "-g"];
    const objects = [];
    const compile = (source, extra) => {
        const object = directory + path.basename(source).replace(/\.[cS]$/, "") + ".o";
        assert.ok(!objects.includes(object), "two sources named like " + source);
        run(clang, [...common, ...extra, "-c", "-o", object, source]);
        objects.push(object);
    };
    compile(runtime + "start.S", ["-marm"]);
    compile(runtime + "aeabi.S", ["-marm"]);
    compile(runtime + "runtime.c", ["-O2", "-marm"]);
    compile(libc + "libc.c", ["-O2", "-marm"]);
    for(const source of sources) compile(source, [optimize, thumb ? "-mthumb" : "-marm", ...cflags]);
    const link = ["-flavor", "gnu", "-m", "armelf", "-static", "-T", runtime + "link.ld", ...objects];
    run(lld, [...link, "-o", directory + "guest.elf"]);
    run(lld, [...link, "--oformat=binary", "-o", directory + "guest.bin"]);
    return directory;
}

/** guest.bin on QEMU's cortex-a15 */
export function reference32(directory, options = {})
{
    return reference(directory, { machine: QEMU_MACHINE32, cpu: QEMU_CPU32, ...options });
}

/**
 * guest.bin on v86 with cpu_type "arm32", the machine's clock running (the
 * runner drives the slices without run(), which would start it: the timers
 * need it)
 */
export function actual32(directory, { options = {}, setup = null, ...rest } = {})
{
    return actual(directory, { ...rest, options: { cpu_type: "arm32", ...options }, setup: cpu => {
        cpu.clock.resume();
        setup?.(cpu);
    } });
}

/** Both, by A32_TARGET=qemu|v86|both (default both): the outputs must be the same */
export async function compare(directory, options = {})
{
    const which = process.env.A32_TARGET || "both";
    const results = {};
    if(which !== "v86") results.qemu = await reference32(directory, options);
    if(which !== "qemu") results.v86 = await actual32(directory, options);
    return results;
}
                                                                                                                                                                                                                                              source/v64/tests/a32/system.c                                                                       0000644 0000000 0000000 00000023657 00000000000 013120  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 at PL1 against QEMU's cortex-a15 (docs/aarch32-plan.md R2): the
// modes and their banked registers, CPSR and the SPSRs, the exceptions'
// entry (vectors at VBAR, modes, return addresses, fault status) and
// returns, LDM and STM of the User registers, User mode's view, CP15 at
// PL1, VFP's enables. Every line printed must be QEMU's.
#include <a32.h>
#include <stdio.h>

void banks(uint32_t *out);
void fiq_banks(uint32_t *out);
void spsrs(uint32_t *out, uint32_t value);
void user_lsm(uint32_t *out);
void exception_returns(uint32_t *out);
uint32_t run_user(void (*function)(void), uint32_t argument);
extern char user_returned[];
void user_cpsr(void), user_mrs_spsr(void), user_sctlr(void), user_tpidr(void), user_tpidrprw(void),
    user_cntvct(void), user_svc(void), user_vfp(void), user_fpexc(void), user_ldm_user(void), user_hvc(void);
void t32_svc(uint32_t *at), t32_udf16(uint32_t *at), t32_udf32(uint32_t *at), t32_cps(uint32_t *out);

static void print_words(const char *name, const uint32_t *w, int n)
{
    printf("%s:", name);
    for(int i = 0; i < n; i++) printf(" %x", (unsigned)w[i]);
    printf("\n");
}

// (SVC #0xFF from User mode: back to run_user's caller, in SVC mode)
static int hook(struct a32_frame *frame, int kind)
{
    if(kind != A32_SVC) return 0;
    uint32_t imm = frame->cpsr & 1 << 5 ? *(volatile uint16_t *)(frame->pc - 2) & 0xFF : *(volatile uint32_t *)(frame->pc - 4) & 0xFFFFFF;
    if(imm != 0xFF) return 0;
    frame->pc = (uint32_t)user_returned;
    frame->cpsr = 0x1D3;
    return 1;
}

static void report(const char *name, struct a32_fault *f, uint32_t at)
{
    if(!f->taken) { printf("%s: no exception\n", name); return; }
    printf("%s: kind %d spsr %#x pc-at %d lr-at %d fsr %#x far %#x mode %#x\n", name, f->kind, (unsigned)f->spsr,
        (int)(f->pc - at), (int)(f->lr - at), (unsigned)f->fsr, (unsigned)f->far, (unsigned)(a32_cpsr() & 0x1F));
}

static void exceptions(void)
{
    struct a32_fault f;
    uint32_t at, v;
    static uint32_t buffer[4] = { 0x11223344, 0x55667788, 0x99AABBCC, 0xDDEEFF00 };

    a32_expect(0);
    __asm__ volatile("adr %0, 1f\n1: svc #0x42" : "=r"(at) :: "lr", "memory");
    a32_caught(&f);
    report("svc a32", &f, at);

    a32_expect(0);
    t32_svc(&at);
    a32_caught(&f);
    report("svc t32", &f, at);

    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: udf #0" : "=r"(at) :: "memory");
    a32_caught(&f);
    report("udf a32", &f, at);

    a32_expect(2);
    t32_udf16(&at);
    a32_caught(&f);
    report("udf t32", &f, at);

    a32_expect(4);
    t32_udf32(&at);
    a32_caught(&f);
    report("udf.w t32", &f, at);

    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: bkpt #0x11" : "=r"(at) :: "memory");
    a32_caught(&f);
    report("bkpt a32", &f, at);

    // (alignment: SCTLR.A, the MMU off)
    a32_mcr(0, c1, c0, 0, a32_mrc(0, c1, c0, 0) | 2);
    a32_isb();
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: ldr %1, [%2]" : "=&r"(at), "=r"(v) : "r"((char *)buffer + 1) : "memory");
    a32_caught(&f);
    f.far -= (uint32_t)buffer;
    report("ldr unaligned, A", &f, at);
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: str %1, [%2]" : "=&r"(at) : "r"(0), "r"((char *)buffer + 2) : "memory");
    a32_caught(&f);
    f.far -= (uint32_t)buffer;
    report("str unaligned, A", &f, at);
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: ldrh %1, [%2]" : "=&r"(at), "=r"(v) : "r"((char *)buffer + 1) : "memory");
    a32_caught(&f);
    f.far -= (uint32_t)buffer;
    report("ldrh unaligned, A", &f, at);
    a32_mcr(0, c1, c0, 0, a32_mrc(0, c1, c0, 0) & ~2u);
    a32_isb();
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: ldr %1, [%2]" : "=&r"(at), "=r"(v) : "r"((char *)buffer + 1) : "memory");
    a32_caught(&f);
    f.far -= (uint32_t)buffer;
    report("ldr unaligned, MMU off", &f, at);
    uint64_t pair;
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: ldrd %1, %H1, [%2]" : "=&r"(at), "=r"(pair) : "r"((char *)buffer + 4) : "memory");
    a32_caught(&f);
    report("ldrd word-aligned", &f, at);
    printf("ldrd %#llx\n", (unsigned long long)pair);
}

static void cp15(void)
{
    printf("sctlr %#x ttbcr %#x dacr %#x contextidr %#x\n", (unsigned)a32_mrc(0, c1, c0, 0), (unsigned)a32_mrc(0, c2, c0, 2),
        (unsigned)a32_mrc(0, c3, c0, 0), (unsigned)a32_mrc(0, c13, c0, 1));
    printf("midr %#x mpidr %#x ctr %#x clidr %#x actlr %#x\n", (unsigned)a32_mrc(0, c0, c0, 0), (unsigned)a32_mrc(0, c0, c0, 5),
        (unsigned)a32_mrc(0, c0, c0, 1), (unsigned)a32_mrc(1, c0, c0, 1), (unsigned)a32_mrc(0, c1, c0, 1));
    printf("id_pfr1 timer %#x id_mmfr0 vmsa %#x\n", (unsigned)(a32_mrc(0, c0, c1, 1) >> 16 & 15), (unsigned)(a32_mrc(0, c0, c1, 4) & 15));
    // writes and reads back
    a32_mcr(0, c13, c0, 4, 0x12345678);
    a32_mcr(0, c13, c0, 2, 0x9ABCDEF0);
    a32_mcr(0, c13, c0, 3, 0x0F1E2D3C);
    a32_mcr(0, c13, c0, 1, 0x00000105);
    a32_mcr(0, c3, c0, 0, 0x55555555);
    a32_mcr(0, c2, c0, 2, 0x00000002);
    a32_mcr(0, c2, c0, 0, 0x4000406A);
    a32_mcr(0, c2, c0, 1, 0x40008000);
    a32_mcr(0, c10, c2, 0, 0xFF0A81A8);
    a32_mcr(0, c10, c2, 1, 0x40E040E0);
    a32_mcr(0, c5, c0, 0, 0x00000805);
    a32_mcr(0, c5, c0, 1, 0x0000000D);
    a32_mcr(0, c6, c0, 0, 0xDEADBEEF);
    a32_mcr(0, c6, c0, 2, 0xFEEDF00D);
    a32_mcr(0, c1, c0, 1, 0x00000040);
    a32_mcr(0, c1, c0, 2, 0xFFFFFFFF);
    a32_isb();
    uint32_t w[] = { a32_mrc(0, c13, c0, 4), a32_mrc(0, c13, c0, 2), a32_mrc(0, c13, c0, 3), a32_mrc(0, c13, c0, 1),
        a32_mrc(0, c3, c0, 0), a32_mrc(0, c2, c0, 2), a32_mrc(0, c2, c0, 0), a32_mrc(0, c2, c0, 1), a32_mrc(0, c10, c2, 0),
        a32_mrc(0, c10, c2, 1), a32_mrc(0, c5, c0, 0), a32_mrc(0, c5, c0, 1), a32_mrc(0, c6, c0, 0), a32_mrc(0, c6, c0, 2),
        a32_mrc(0, c1, c0, 1), a32_mrc(0, c1, c0, 2) };
    print_words("cp15 written", w, 16);
    // (the 64-bit TTBR0 view)
    uint64_t ttbr0 = a32_mrrc(0, c2);
    printf("ttbr0 64 %#llx\n", (unsigned long long)ttbr0);
    a32_mcr(0, c13, c0, 1, 0);
    a32_mcr(0, c3, c0, 0, 0);
    a32_mcr(0, c2, c0, 2, 0);
    a32_mcr(0, c1, c0, 2, 0xF << 20);
    // (maintenance: TLB, caches, barriers and the branch predictor, no faults)
    a32_mcr(0, c8, c7, 0, 0);
    a32_mcr(0, c8, c3, 0, 0);
    a32_mcr(0, c8, c7, 1, 0x40001000);
    a32_mcr(0, c8, c7, 2, 1);
    a32_mcr(0, c8, c7, 3, 0x40001000);
    a32_mcr(0, c7, c5, 0, 0);
    a32_mcr(0, c7, c5, 6, 0);
    a32_mcr(0, c7, c10, 1, 0x40001000);
    a32_mcr(0, c7, c14, 1, 0x40001000);
    a32_mcr(0, c7, c6, 1, 0x40001000);
    a32_mcr(0, c7, c10, 5, 0);
    a32_mcr(0, c7, c10, 4, 0);
    a32_mcr(0, c7, c5, 4, 0);
    a32_mcr(2, c0, c0, 0, 0);
    printf("csselr %#x\n", (unsigned)a32_mrc(2, c0, c0, 0));
    printf("maintenance done\n");
}

static void vfp(void)
{
    struct a32_fault f;
    uint32_t at, v;
    uint32_t fpsid, mvfr0, fpexc;
    __asm__ volatile("vmrs %0, fpsid\n vmrs %1, mvfr0\n vmrs %2, fpexc" : "=r"(fpsid), "=r"(mvfr0), "=r"(fpexc));
    printf("fpsid %#x mvfr0 %#x fpexc %#x\n", (unsigned)fpsid, (unsigned)mvfr0, (unsigned)fpexc);
    // FPEXC.EN 0: VFP instructions and VMRS FPSCR UNDEFINED, VMRS FPEXC not
    a32_expect(4);
    __asm__ volatile("vmsr fpexc, %2\n adr %0, 1f\n1: vadd.f32 s0, s0, s0\n vmrs %1, fpexc" : "=&r"(at), "=&r"(v) : "r"(0) : "memory");
    a32_caught(&f);
    report("vadd, fpexc.en 0", &f, at);
    printf("fpexc then %#x\n", (unsigned)v);
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: vmrs %1, fpscr" : "=&r"(at), "=r"(v) :: "memory");
    a32_caught(&f);
    report("vmrs fpscr, fpexc.en 0", &f, at);
    __asm__ volatile("vmsr fpexc, %0" :: "r"(1 << 30));
    // CPACR's cp10 and cp11 0: UNDEFINED
    a32_mcr(0, c1, c0, 2, 0);
    a32_isb();
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: vadd.f32 s0, s0, s0" : "=r"(at) :: "memory");
    a32_caught(&f);
    report("vadd, cpacr 0", &f, at);
    a32_expect(4);
    __asm__ volatile("adr %0, 1f\n1: vmrs %1, fpexc" : "=&r"(at), "=r"(v) :: "memory");
    a32_caught(&f);
    report("vmrs fpexc, cpacr 0", &f, at);
    a32_mcr(0, c1, c0, 2, 0xF << 20);
    a32_isb();
    __asm__ volatile("vmov s0, %1\n vadd.f32 s0, s0, s0\n vmov %0, s0" : "=r"(v) : "r"(0x3F800000));
    printf("vadd 1 + 1 = %#x\n", (unsigned)v);
}

static void user(void)
{
    struct a32_fault f;
    a32_mcr(0, c13, c0, 3, 0x300);
    a32_mcr(0, c13, c0, 2, 0x21);
    struct { const char *name; void (*function)(void); uint32_t argument; } probes[] = {
        { "cpsr", user_cpsr, 0 },
        { "mrs spsr", user_mrs_spsr, 0 },
        { "mrc sctlr", user_sctlr, 0 },
        { "tpidruro + tpidrurw", user_tpidr, 0 },
        { "mrc tpidrprw", user_tpidrprw, 0 },
        { "mrrc cntvct", user_cntvct, 0 },
        { "svc", user_svc, 0x55 },
        { "vadd", user_vfp, 0x40000000 },
        { "vmrs fpexc", user_fpexc, 0 },
        { "ldm user registers", user_ldm_user, 0 },
        { "hvc", user_hvc, 0 },
    };
    for(unsigned i = 0; i < sizeof probes / sizeof probes[0]; i++)
    {
        a32_expect(4);
        uint32_t r = run_user(probes[i].function, probes[i].argument);
        a32_caught(&f);
        if(f.taken)
            printf("user %s: kind %d spsr %#x\n", probes[i].name, f.kind, (unsigned)f.spsr);
        else
            printf("user %s: %#x\n", probes[i].name, (unsigned)r);
    }
    printf("back in mode %#x\n", (unsigned)(a32_cpsr() & 0x1F));
}

int main(int argc, char **argv)
{
    uint32_t out[64];
    a32_exception_hook = hook;
    printf("mode %#x cpsr %#x vbar ok %d\n", (unsigned)(a32_cpsr() & 0x1F), (unsigned)a32_cpsr(),
        a32_mrc(0, c12, c0, 0) != 0);

    banks(out);
    print_words("mode cpsrs", out, 5);
    print_words("banked sp lr", out + 5, 10);
    print_words("restored", out + 15, 10);
    fiq_banks(out);
    print_words("fiq banks", out, 10);
    spsrs(out, 0xF9FF0200);
    print_words("spsrs", out, 14);
    user_lsm(out);
    print_words("user lsm", out, 5);
    exception_returns(out);
    print_words("exception returns", out, 9);
    t32_cps(out);
    print_words("t32 cps, subs pc", out, 3);

    exceptions();
    cp15();
    vfp();
    user();
    return 0;
}
                                                                                 source/v64/tests/a32/system_asm.S                                                                   0000644 0000000 0000000 00000021176 00000000000 013732  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The assembly half of tests/a32/system.c: what C cannot do (it needs its
// stack): the modes' banked registers, the SPSRs, LDM and STM of the User
// registers, running code in User mode, T32 exceptions.

    .syntax unified
    .arch_extension virt
    .arm
    .text

// banks(out): per mode (FIQ, IRQ, ABT, UND, SYS) its CPSR, then SP and LR
// set to markers; read back in each mode after a round through SVC, the
// originals restored there. (MRS and MSR of banked registers: QEMU's
// cortex-a15 without its Virtualization Extensions has none.)
    .global banks
banks:
    push    {r4-r11, lr}
    mov     r7, r0
    ldr     r6, =saved
    .irp m, 0x11, 0x12, 0x17, 0x1B, 0x1F
    msr     cpsr_c, #(\m | 0xC0)
    mrs     r1, cpsr
    str     r1, [r7], #4
    str     sp, [r6], #4
    str     lr, [r6], #4
    movw    sp, #(0x1000 | \m)
    movw    lr, #(0x2000 | \m)
    msr     cpsr_c, #0xD3
    .endr
    ldr     r6, =saved
    .irp m, 0x11, 0x12, 0x17, 0x1B, 0x1F
    msr     cpsr_c, #(\m | 0xC0)
    mov     r1, sp
    mov     r2, lr
    ldm     r6!, {r3-r4}
    mov     sp, r3
    mov     lr, r4
    msr     cpsr_c, #0xD3
    stm     r7!, {r1-r2}
    .endr
    // (each mode sees its own again: the difference from the saved values, 0)
    ldr     r6, =saved
    .irp m, 0x11, 0x12, 0x17, 0x1B, 0x1F
    msr     cpsr_c, #(\m | 0xC0)
    ldm     r6!, {r1-r2}
    sub     r1, sp, r1
    sub     r2, lr, r2
    msr     cpsr_c, #0xD3
    stm     r7!, {r1-r2}
    .endr
    pop     {r4-r11, pc}

// fiq_banks(out): R8-R12 of SVC (User's) and FIQ
    .global fiq_banks
fiq_banks:
    push    {r4-r11, lr}
    mov     r7, r0
    mov     r8, #0x88
    mov     r9, #0x89
    mov     r10, #0x8A
    mov     r11, #0x8B
    mov     r12, #0x8C
    msr     cpsr_c, #0xD1
    mov     r8, #0xF8
    mov     r9, #0xF9
    mov     r10, #0xFA
    mov     r11, #0xFB
    mov     r12, #0xFC
    msr     cpsr_c, #0xD3
    stm     r7!, {r8-r12}
    // (System mode's are User's, SVC's)
    msr     cpsr_c, #0xDF
    mov     r1, r8
    mov     r2, r12
    msr     cpsr_c, #0xD1
    mov     r3, r8
    mov     r4, r10
    mov     r5, r12
    msr     cpsr_c, #0xD3
    stm     r7!, {r1-r5}
    pop     {r4-r11, pc}

// spsrs(out, value): per mode with an SPSR (FIQ, IRQ, ABT, UND, SVC) MSR
// SPSR_fsxc of value + mode, its MRS; then all five again after a round
// through SVC; then MSR SPSR_f, _c, _x and _s alone in SVC
    .global spsrs
spsrs:
    push    {r4-r11, lr}
    mov     r7, r0
    mov     r5, r1
    mrs     r9, spsr
    .irp m, 0x11, 0x12, 0x17, 0x1B, 0x13
    msr     cpsr_c, #(\m | 0xC0)
    add     r2, r5, #\m
    msr     spsr_fsxc, r2
    mrs     r3, spsr
    msr     cpsr_c, #0xD3
    str     r3, [r7], #4
    .endr
    .irp m, 0x11, 0x12, 0x17, 0x1B, 0x13
    msr     cpsr_c, #(\m | 0xC0)
    mrs     r3, spsr
    msr     cpsr_c, #0xD3
    str     r3, [r7], #4
    .endr
    mov     r1, #0
    msr     spsr_fsxc, r1
    mvn     r1, #0
    msr     spsr_f, r1
    mrs     r2, spsr
    msr     spsr_c, r1
    mrs     r3, spsr
    msr     spsr_x, r1
    mrs     r4, spsr
    msr     spsr_s, r1
    mrs     r5, spsr
    stm     r7!, {r2-r5}
    msr     spsr_fsxc, r9
    pop     {r4-r11, pc}

// user_lsm(out): STM and LDM of the User registers from SVC
    .global user_lsm
user_lsm:
    push    {r4-r11, lr}
    mov     r7, r0
    // (System mode's SP and LR are User's: markers there)
    msr     cpsr_c, #0xDF
    mov     r4, sp
    mov     sp, #0x5000
    movw    lr, #0x5004
    msr     cpsr_c, #0xD3
    ldr     r1, =scratch
    stmia   r1, {r13, r14}^
    ldr     r2, [r1]
    ldr     r3, [r1, #4]
    stm     r7!, {r2-r3}
    mov     r2, #0x6000
    movw    r3, #0x6004
    stmia   r1, {r2, r3}
    ldmia   r1, {r13, r14}^
    // (SVC's SP is its own still)
    mov     r5, sp
    msr     cpsr_c, #0xDF
    mov     r2, sp
    mov     r3, lr
    mov     sp, r4
    msr     cpsr_c, #0xD3
    sub     r5, sp, r5
    stm     r7!, {r2, r3, r5}
    pop     {r4-r11, pc}

// exception_returns(out): SUBS PC, LR to SVC with an SPSR, MOVS PC, LR
// to T32, LDM with the PC and ^, RFE; each records where it arrived and its CPSR
    .global exception_returns
exception_returns:
    push    {r4-r11, lr}
    mov     r7, r0
    mrs     r9, spsr
    // SUBS PC, LR, #4: to 1f with the flags of the SPSR
    mov     r1, #0xD3
    orr     r1, r1, #0xA0000000
    msr     spsr_fsxc, r1
    adr     lr, 1f + 4
    subs    pc, lr, #4
    b       .
1:  mrs     r1, cpsr
    str     r1, [r7], #4
    // MOVS PC, LR: to the T32 code at 2f (SPSR.T)
    mov     r1, #0xF3
    msr     spsr_fsxc, r1
    adr     lr, 2f
    orr     lr, lr, #1
    movs    pc, lr
    b       .
    .thumb
2:  mrs     r1, cpsr
    str     r1, [r7], #4
    adr     r1, 3f
    bx      r1
    .balign 4
    .arm
3:  // LDM SP!, {..., PC}^: to 4f, CPSR from SPSR (V set)
    mov     r1, #0xD3
    orr     r1, r1, #0x10000000
    msr     spsr_fsxc, r1
    adr     r1, 4f
    mov     r2, #0x77
    push    {r1}
    push    {r2}
    ldmia   sp!, {r3, pc}^
    b       .
4:  mrs     r1, cpsr
    stm     r7!, {r1, r3}
    // RFE from a two-word frame: to 5f with C set
    adr     r1, 5f
    mov     r2, #0xD3
    orr     r2, r2, #0x20000000
    ldr     r3, =scratch
    stm     r3, {r1, r2}
    rfeia   r3!
    b       .
5:  mrs     r1, cpsr
    ldr     r2, =scratch
    sub     r3, r3, r2
    stm     r7!, {r1, r3}
    // SRS to SVC's stack (DB, writeback): LR and SPSR
    mov     r1, #0xD3
    orr     r1, r1, #0x40000000
    msr     spsr_fsxc, r1
    mov     r4, lr
    movw    lr, #0x1234
    mov     r5, sp
    srsdb   sp!, #0x13
    ldm     sp, {r1, r2}
    sub     r3, r5, sp
    mov     sp, r5
    mov     lr, r4
    stm     r7!, {r1-r3}
    msr     spsr_fsxc, r9
    pop     {r4-r11, pc}

// run_user(function, argument): function(argument) in User mode (T32 when
// bit 0); it returns with SVC #0xFF (user_exit), its r0 run_user's
    .global run_user
run_user:
    push    {r4-r11, lr}
    ldr     r2, =user_sp
    str     sp, [r2]
    mov     r3, #0xD0
    tst     r0, #1
    orrne   r3, r3, #0x20
    msr     spsr_fsxc, r3
    mov     lr, r0
    mov     r0, r1
    movs    pc, lr
    .global user_returned
user_returned:
    ldr     r2, =user_sp
    ldr     sp, [r2]
    pop     {r4-r11, pc}

// (User mode code) back to run_user's caller with r0
    .global user_exit
user_exit:
    svc     #0xFF

// User mode probes: each returns what it found in r0 (an exception's kind
// comes from the handler), then exits
    .global user_cpsr
user_cpsr:
    // (CPS and MSR of the control field ignored; MSR of the flags written)
    cpsid   i
    msr     cpsr_c, #0xD3
    mov     r1, #0x80000000
    msr     cpsr_f, r1
    mrs     r0, cpsr
    b       user_exit
    .global user_mrs_spsr
user_mrs_spsr:
    mrs     r0, spsr
    b       user_exit
    .global user_sctlr
user_sctlr:
    mrc     p15, 0, r0, c1, c0, 0
    b       user_exit
    .global user_tpidr
user_tpidr:
    mrc     p15, 0, r0, c13, c0, 3
    mrc     p15, 0, r1, c13, c0, 2
    add     r0, r0, r1
    b       user_exit
    .global user_tpidrprw
user_tpidrprw:
    mrc     p15, 0, r0, c13, c0, 4
    b       user_exit
    .global user_cntvct
user_cntvct:
    mrrc    p15, 1, r0, r1, c14
    b       user_exit
    .global user_svc
user_svc:
    svc     #0x21
    b       user_exit
    .global user_vfp
user_vfp:
    vmov    s0, r0
    vadd.f32 s0, s0, s0
    vmov    r0, s0
    b       user_exit
    .global user_fpexc
user_fpexc:
    vmrs    r0, fpexc
    b       user_exit
    .global user_ldm_user
user_ldm_user:
    ldr     r1, =scratch
    ldmia   r1, {r13, r14}^
    b       user_exit
    .global user_hvc
user_hvc:
    hvc     #0
    b       user_exit

// T32 exceptions: SVC, the 16-bit and 32-bit UDF; each address in r0's word
    .thumb
    .global t32_svc
    .thumb_func
t32_svc:
    // (SVC in SVC mode: LR_svc becomes the return address)
    push    {r4, lr}
    adr     r1, 1f
    str     r1, [r0]
1:  svc     #0x43
    pop     {r4, pc}
    .global t32_udf16
    .thumb_func
t32_udf16:
    adr     r1, 1f
    str     r1, [r0]
1:  udf     #1
    bx      lr
    .global t32_udf32
    .thumb_func
t32_udf32:
    .balign 4
    adr     r1, 1f
    str     r1, [r0]
1:  udf.w   #2
    bx      lr
    .global t32_cps
    .thumb_func
t32_cps:
    // CPS (16-bit) and SUBS PC, LR (T32's exception return) at PL1
    cpsie   f
    mrs     r1, cpsr
    cpsid   f
    mrs     r2, cpsr
    str     r1, [r0]
    str     r2, [r0, #4]
    mrs     r3, spsr
    movs    r1, #0xD3
    msr     spsr_fsxc, r1
    adr     r1, 2f
    adds    r1, #4
    mov     r2, lr
    mov     lr, r1
    subs    pc, lr, #4
    .balign 4
    .arm
2:  mrs     r1, cpsr
    str     r1, [r0, #8]
    msr     spsr_fsxc, r3
    bx      r2

    .data
    .balign 8
saved:  .space 64
scratch: .space 16
user_sp: .word 0
                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/a64/aarch32/bench.c                                                                0000644 0000000 0000000 00000003653 00000000000 014075  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The EL1 driver of tests/a64/aarch32_bench.mjs (docs/aarch32-plan.md
// Q6.4): one kernel of tests/bench (bench_main(iterations)), built for A64
// and run here at EL1, or built for A32 or T32 (BENCH32: its flat binary,
// linked at EL0's alias of BENCH32_PHYSICAL, el0_map.h) and run at EL0;
// the checksum and the counter's ticks it took are printed.
#include <a64.h>
#include <stdio.h>
#include <string.h>
#include "el0_map.h"

#ifdef BENCH32
extern const unsigned char bench32[], bench32_end[];
void a32_run(uint64_t entry, uint64_t spsr, const uint32_t regs[15]);
extern char a32_resume_el1[];
static volatile uint64_t result, esr;
static void lower(struct a64_frame *frame, uint64_t vector)
{
    result = frame->x[0];
    esr = a64_read(esr_el1);
    frame->elr = (uint64_t)a32_resume_el1;
    frame->spsr = 0x3C5;
}
#else
unsigned bench_main(unsigned iterations);
#endif

int main(int argc, char **argv)
{
    uint64_t start, end, value;
#ifdef BENCH32
    a64_lower_handler = lower;
    el0_map();
    // the program where it was linked (its BSS zeroed), entered at its start
    unsigned char *at = (unsigned char *)BENCH32_PHYSICAL;
    memcpy(at, bench32, bench32_end - bench32);
    memset(at + (BENCH32_BSS_START - BENCH32_BASE), 0, BENCH32_BSS_END - BENCH32_BSS_START);
    __asm__ volatile("dsb ish\n ic iallu\n dsb ish\n isb" ::: "memory");
    uint32_t regs[15] = { ITERATIONS };
    start = a64_read(cntvct_el0);
    a32_run(BENCH32_ENTRY, 0x10 | 0x1C0 | (BENCH32_THUMB ? 0x20 : 0), regs);
    end = a64_read(cntvct_el0);
    value = result;
    if(esr >> 26 != 0x11) printf("bench: an exception: esr %08lx\n", (unsigned long)esr);
#else
    start = a64_read(cntvct_el0);
    value = bench_main(ITERATIONS);
    end = a64_read(cntvct_el0);
#endif
    printf("bench %s checksum %08lx ticks %lu frequency %lu\n", NAME, (unsigned long)(uint32_t)value, (unsigned long)(end - start),
        (unsigned long)a64_read(cntfrq_el0));
    return 0;
}
                                                                                     source/v64/tests/a64/aarch32/bench_rt.c                                                             0000644 0000000 0000000 00000001674 00000000000 014603  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The string primitives of tests/a64/aarch32_bench.mjs's builds, as the
// bare-metal runtime has them (tests/a64/baremetal/libc.c: byte loops),
// so that A64 and the 32-bit builds run the same code; memmove both lack.
typedef __SIZE_TYPE__ size_t;
#ifdef BENCH32
void *memcpy(void *to, const void *from, size_t n)
{
    char *t = to;
    const char *f = from;
    while(n--) *t++ = *f++;
    return to;
}
void *memset(void *to, int c, size_t n)
{
    char *t = to;
    while(n--) *t++ = c;
    return to;
}
int memcmp(const void *a, const void *b, size_t n)
{
    const unsigned char *x = a, *y = b;
    for(; n; n--, x++, y++) if(*x != *y) return *x - *y;
    return 0;
}
#endif
void *memmove(void *to, const void *from, size_t n)
{
    char *t = to;
    const char *f = from;
    if(t <= f || t >= f + n)
    {
        while(n--) *t++ = *f++;
    }
    else
    {
        t += n;
        f += n;
        while(n--) *--t = *--f;
    }
    return to;
}
                                                                    source/v64/tests/a64/aarch32/bench_start.S                                                          0000644 0000000 0000000 00000000530 00000000000 015261  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       @ The A32 or T32 build's start (tests/a64/aarch32_bench.mjs): R0 the
@ iterations; bench_main's result in R0 to EL1 by an SVC.
    .syntax unified
    .section .text.start, "ax"
    .global _start
#ifdef THUMB
    .thumb
    .thumb_func
#else
    .arm
#endif
_start:
    ldr     sp, =__stack_top
    bl      bench_main
    svc     #0
    .pool
                                                                                                                                                                        source/v64/tests/a64/aarch32/debug.c                                                                0000644 0000000 0000000 00000011277 00000000000 014105  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AArch32 EL0 debug cases' driver (docs/aarch32-plan.md Q1.5,
// tests/a64/aarch32_el0.mjs with A64_AARCH32_DRIVER=debug): each case of an
// AArch32 binary (its table: the count, then per case its offset with bit 0
// for T32, how many times to resume it, a control word, a breakpoint's
// offset) runs at EL0 with the debug registers the control word asks for;
// every exception that comes back is printed (vector, ESR, ELR and FAR as
// offsets, SPSR, R0-R14) and the case resumes at ELR, as many times as it
// says. The control word: bits 3:0 the NZCV it starts with; bit 4 software
// step (MDSCR_EL1.SS, SPSR.SS set on each entry); bit 5 breakpoint 0 at the
// breakpoint's offset, BAS 1111, or with bits 7:6 1 0011, 2 1100; bit 8
// watchpoint 0 on the first 8 bytes of the data buffer (R1 points at it),
// bits 10:9 LSC. A breakpoint or watchpoint is disabled once it fired.
// The same output from QEMU (cortex-a35) and v86 is the test.
#include <a64.h>
#include <stdio.h>

#ifndef CASES
#define CASES qdebug_a32
#endif
extern const uint32_t CASES[];

struct exit_state
{
    uint64_t x[15], esr, far, elr, spsr, vector;
};
static volatile struct exit_state last;
extern char a32_resume_el1[];
void a32_run(uint64_t entry, uint64_t spsr, const uint32_t regs[15]);
static uint32_t stack[1024] __attribute__((aligned(16)));
static uint8_t data[64] __attribute__((aligned(16)));

static void lower(struct a64_frame *frame, uint64_t vector)
{
    for(int i = 0; i < 15; i++) last.x[i] = frame->x[i];
    last.esr = a64_read(esr_el1);
    last.far = a64_read(far_el1);
    last.elr = frame->elr;
    last.spsr = frame->spsr;
    last.vector = vector;
    frame->elr = (uint64_t)a32_resume_el1;
    frame->spsr = 0x3C5;
}

int main(int argc, char **argv)
{
    a64_lower_handler = lower;
    // (the OS Lock off: debug exceptions on)
    a64_write(oslar_el1, 0);
    __asm__ volatile("isb");
    const uint32_t *table = CASES;
    const uint64_t base = (uint64_t)CASES;
    const unsigned n = table[0];
    for(unsigned c = 0; c < n; c++)
    {
        const uint32_t *t = table + 1 + 4 * c;
        const uint32_t offset = t[0], resumes = t[1], control = t[2], breakpoint = t[3];
        uint32_t regs[15];
        for(int i = 0; i < 13; i++) regs[i] = 0x01010101u * (i + 1) + c;
        regs[1] = (uint32_t)(uintptr_t)data;
        regs[13] = (uint32_t)(uintptr_t)(stack + 1024);
        regs[14] = 0xE14E14E1u;
        for(int i = 0; i < 64; i++) data[i] = (uint8_t)(i * 7 + c);
        uint64_t entry = base + (offset & ~1u);
        const uint64_t ss = control & 0x10 ? 1ul << 21 : 0;
        uint64_t spsr = 0x10 | 0x1C0 | (offset & 1 ? 0x20 : 0) | (uint64_t)(control & 15) << 28;
        a64_write(mdscr_el1, 1ul << 15 | (control & 0x10 ? 1 : 0));
        if(control & 0x20)
        {
            const uint64_t bas = (uint64_t[]){ 15, 3, 12, 15 }[control >> 6 & 3];
            a64_write(dbgbvr0_el1, (base + breakpoint) & ~3ul);
            a64_write(dbgbcr0_el1, 1 | 2 << 1 | bas << 5);
        }
        if(control & 0x100)
        {
            a64_write(dbgwvr0_el1, (uint64_t)(uintptr_t)data);
            a64_write(dbgwcr0_el1, 1 | 2 << 1 | (uint64_t)(control >> 9 & 3) << 3 | 0xFF << 5);
        }
        __asm__ volatile("isb");
        for(unsigned r = 0;; r++)
        {
            last.vector = ~0ul;
            a32_run(entry, spsr | ss, regs);
            const uint32_t ec = last.esr >> 26;
            printf("case %u.%u: vector %lu esr %08lx elr %+ld spsr %08lx", c, r, last.vector, last.esr, (long)(last.elr - base), last.spsr);
            if(ec >= 0x20 && ec <= 0x25) printf(" far %+ld", (long)(last.far - base));
            if(ec == 0x34 || ec == 0x35) printf(" far data%+ld", (long)(last.far - (uint64_t)(uintptr_t)data));
            printf("\n ");
            for(int i = 0; i < 15; i++)
            {
                const uint64_t v = last.x[i];
                if(i == 13) printf(" sp%+ld", (long)(v - (uint64_t)(uintptr_t)(stack + 1024)));
                else if(v - (uint64_t)(uintptr_t)data < 64) printf(" data%+ld", (long)(v - (uint64_t)(uintptr_t)data));
                else printf(" %lx", v);
            }
            printf("\n");
            if(r == resumes || last.vector != 12) break;
            // (a breakpoint or watchpoint that fired: off, so that the case goes on)
            if(ec == 0x30) a64_write(dbgbcr0_el1, 0);
            if(ec == 0x34) a64_write(dbgwcr0_el1, 0);
            __asm__ volatile("isb");
            for(int i = 0; i < 15; i++) regs[i] = (uint32_t)last.x[i];
            entry = last.elr;
            spsr = last.spsr;
        }
        a64_write(mdscr_el1, 0);
        a64_write(dbgbcr0_el1, 0);
        a64_write(dbgwcr0_el1, 0);
        __asm__ volatile("isb");
    }
    printf("done\n");
    return 0;
}
                                                                                                                                                                                                                                                                                                                                 source/v64/tests/a64/aarch32/el0.c                                                                  0000644 0000000 0000000 00000006342 00000000000 013474  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AArch32 EL0 cases' driver (docs/aarch32-plan.md Q0.2, Q1): each case
// of an AArch32 binary (its table: the count, then per case its offset with
// bit 0 for T32, how many times to resume it, the NZCV it starts with) runs
// at EL0 until it takes an exception to EL1; what came back is printed (the
// vector, ESR, ELR and FAR as offsets into the binary, SPSR, R0-R14 as X0-X14),
// then the case resumes at ELR with R0 + 0x100, as many times as it says.
// The same output from QEMU (cortex-a35) and v86 is the test. The NZCV word's
// bit 8 runs the case with CPACR_EL1.FPEN from its bits 5:4.
#include <a64.h>
#include <stdio.h>
#include "el0_map.h"

#ifndef CASES
#define CASES q1_a32
#endif
extern const uint32_t CASES[];

struct exit_state
{
    uint64_t x[15], esr, far, elr, spsr, vector;
};
static volatile struct exit_state last;
extern char a32_resume_el1[];
void a32_run(uint64_t entry, uint64_t spsr, const uint32_t regs[15]);
static uint32_t stack[1024] __attribute__((aligned(16)));

static void lower(struct a64_frame *frame, uint64_t vector)
{
    for(int i = 0; i < 15; i++) last.x[i] = frame->x[i];
    last.esr = a64_read(esr_el1);
    last.far = a64_read(far_el1);
    last.elr = frame->elr;
    last.spsr = frame->spsr;
    last.vector = vector;
    frame->elr = (uint64_t)a32_resume_el1;
    frame->spsr = 0x3C5;
}

int main(int argc, char **argv)
{
    a64_lower_handler = lower;
    el0_map();
    const uint32_t *table = CASES;
    // (EL0's addresses: el0_map.h)
    const uint64_t base = el0_address(CASES);
    const unsigned n = table[0];
    for(unsigned c = 0; c < n; c++)
    {
        const uint32_t offset = table[1 + 3 * c], resumes = table[2 + 3 * c], nzcv = table[3 + 3 * c];
        uint32_t regs[15];
        for(int i = 0; i < 13; i++) regs[i] = 0x01010101u * (i + 1) + c;
        regs[13] = (uint32_t)el0_address(stack + 1024);
        regs[14] = 0xE14E14E1u;
        uint64_t entry = base + (offset & ~1u);
        // AArch32 User, A I F masked, T for a T32 case
        uint64_t spsr = 0x10 | 0x1C0 | (offset & 1 ? 0x20 : 0) | (uint64_t)(nzcv & 15) << 28;
        // (EL1's printf uses FP registers: FPEN as the case says only around its run)
        const uint64_t cpacr = a64_read(cpacr_el1);
        for(unsigned r = 0;; r++)
        {
            last.vector = ~0ul;
            if(nzcv & 0x100) a64_write(cpacr_el1, (cpacr & ~(3ul << 20)) | (uint64_t)(nzcv >> 4 & 3) << 20);
            __asm__ volatile("isb");
            a32_run(entry, spsr, regs);
            a64_write(cpacr_el1, cpacr);
            __asm__ volatile("isb");
            const uint32_t ec = last.esr >> 26;
            printf("case %u.%u: vector %lu esr %08lx elr %+ld spsr %08lx", c, r, last.vector, last.esr, (long)(last.elr - base), last.spsr);
            if(ec >= 0x20 && ec <= 0x25) printf(" far %+ld", (long)(last.far - base));
            printf("\n ");
            for(int i = 0; i < 15; i++) printf(" %lx", i == 13 ? last.x[i] - el0_address(stack) : last.x[i]);
            printf("\n");
            if(r == resumes || last.vector != 12) break;
            for(int i = 0; i < 15; i++) regs[i] = (uint32_t)last.x[i];
            regs[0] += 0x100;
            entry = last.elr;
            spsr = last.spsr;
        }
    }
    printf("done\n");
    return 0;
}
                                                                                                                                                                                                                                                                                              source/v64/tests/a64/aarch32/el0_map.h                                                              0000644 0000000 0000000 00000002167 00000000000 014337  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // EL0's view of RAM for the AArch32 drivers (el0.c, fuzz.c). With the MMU
// off (the default) EL0 reaches everything; with A64_MMU (the page tier's
// runs: tests/a64/aarch32_page.mjs, aarch32_page_fuzz.mjs) the runtime's
// identity map gives EL0 no access, and RAM that EL0 may write cannot be
// EL1's code: RAM (1 GiB at 0x40000000) is mapped a second time at
// 0xC0000000 for EL0 (read, write and execute; EL1 never executes there),
// and EL0's code, stack and data are used through that alias.
#include <a64.h>

#ifdef A64_MMU
#define EL0_ALIAS 0x80000000ul
static void el0_map(void)
{
    uint64_t *table = (uint64_t *)a64_read(ttbr0_el1);
    // a 1 GiB block: normal memory (MAIR index 0), AP 01 (EL1 and EL0 read
    // and write), inner shareable, the access flag, PXN
    table[3] = 0x40000000ul | 1 | 0 << 2 | 1 << 6 | 3 << 8 | 1 << 10 | 1ul << 53;
    __asm__ volatile("dsb ish\n tlbi vmalle1\n dsb ish\n isb" ::: "memory");
}
#else
#define EL0_ALIAS 0ul
static void el0_map(void) {}
#endif

/** The address EL0 uses for `p` */
static inline uint64_t el0_address(const void *p) { return (uint64_t)(uintptr_t)p + EL0_ALIAS; }
                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/a64/aarch32/el0_run.S                                                              0000644 0000000 0000000 00000005170 00000000000 014336  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 from the bare-metal EL1 (docs/aarch32-plan.md Q0.2):
// a32_run(entry, spsr, regs) ERETs to `entry` with SPSR_EL1 `spsr` and
// R0-R14 (W0-W14) from regs[15]; the lower-EL handler (el0.c) makes the
// exception that comes back return to a32_resume_el1, which returns from
// a32_run with the callee-saved registers and the stack it had.
// a32_run_fp(entry, spsr, regs, fp) also sets V0-V15, FPSR and FPCR from
// fp (16 Q registers, then FPSR, FPCR) and stores them back there on the
// way out (the EL1 code in between uses no FP or SIMD register).

    .text
    .global a32_run_fp
a32_run_fp:
    adrp    x9, a32_fp_state
    str     x3, [x9, :lo12:a32_fp_state]
    ldp     q0, q1, [x3, #0]
    ldp     q2, q3, [x3, #32]
    ldp     q4, q5, [x3, #64]
    ldp     q6, q7, [x3, #96]
    ldp     q8, q9, [x3, #128]
    ldp     q10, q11, [x3, #160]
    ldp     q12, q13, [x3, #192]
    ldp     q14, q15, [x3, #224]
    ldr     x10, [x3, #256]
    msr     fpsr, x10
    ldr     x10, [x3, #264]
    msr     fpcr, x10
    b       1f

    .global a32_run
a32_run:
    adrp    x9, a32_fp_state
    str     xzr, [x9, :lo12:a32_fp_state]
1:  adrp    x9, a32_context
    add     x9, x9, :lo12:a32_context
    stp     x19, x20, [x9, #0]
    stp     x21, x22, [x9, #16]
    stp     x23, x24, [x9, #32]
    stp     x25, x26, [x9, #48]
    stp     x27, x28, [x9, #64]
    stp     x29, x30, [x9, #80]
    mov     x10, sp
    str     x10, [x9, #96]
    msr     elr_el1, x0
    msr     spsr_el1, x1
    mov     x16, x2
    ldp     w0, w1, [x16, #0]
    ldp     w2, w3, [x16, #8]
    ldp     w4, w5, [x16, #16]
    ldp     w6, w7, [x16, #24]
    ldp     w8, w9, [x16, #32]
    ldp     w10, w11, [x16, #40]
    ldp     w12, w13, [x16, #48]
    ldr     w14, [x16, #56]
    mov     x16, #0
    isb
    eret

    .global a32_resume_el1
a32_resume_el1:
    adrp    x9, a32_fp_state
    ldr     x3, [x9, :lo12:a32_fp_state]
    cbz     x3, 1f
    stp     q0, q1, [x3, #0]
    stp     q2, q3, [x3, #32]
    stp     q4, q5, [x3, #64]
    stp     q6, q7, [x3, #96]
    stp     q8, q9, [x3, #128]
    stp     q10, q11, [x3, #160]
    stp     q12, q13, [x3, #192]
    stp     q14, q15, [x3, #224]
    mrs     x10, fpsr
    str     x10, [x3, #256]
    mrs     x10, fpcr
    str     x10, [x3, #264]
1:  adrp    x9, a32_context
    add     x9, x9, :lo12:a32_context
    ldp     x19, x20, [x9, #0]
    ldp     x21, x22, [x9, #16]
    ldp     x23, x24, [x9, #32]
    ldp     x25, x26, [x9, #48]
    ldp     x27, x28, [x9, #64]
    ldp     x29, x30, [x9, #80]
    ldr     x10, [x9, #96]
    mov     sp, x10
    ret

    .bss
    .balign 16
a32_context:
    .space  112
a32_fp_state:
    .space  8
                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/aarch32/fuzz.c                                                                 0000644 0000000 0000000 00000004050 00000000000 014004  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The EL1 driver of tests/a64/aarch32_page_fuzz.mjs (docs/aarch32-plan.md
// Q6.2): the generated AArch32 program (fuzz.a32.S: its entry at offset 0,
// bit 0 of the first word saying T32) runs at EL0 on a buffer whose address
// it gets in R8, ROUNDS times over, and ends with an SVC; the buffer (its
// registers and NZCV in the last words) and the registers are printed.
#include <a64.h>
#include <stdio.h>
#include "el0_map.h"

extern const uint32_t fuzz_a32[];
void a32_run(uint64_t entry, uint64_t spsr, const uint32_t regs[15]);

struct exit_state
{
    uint64_t x[15], esr, elr, spsr;
};
static volatile struct exit_state last;
extern char a32_resume_el1[];
static uint32_t stack[2048] __attribute__((aligned(16)));
static uint32_t buffer[1024] __attribute__((aligned(64)));

static void lower(struct a64_frame *frame, uint64_t vector)
{
    for(int i = 0; i < 15; i++) last.x[i] = frame->x[i];
    last.esr = a64_read(esr_el1);
    last.elr = frame->elr;
    last.spsr = frame->spsr;
    frame->elr = (uint64_t)a32_resume_el1;
    frame->spsr = 0x3C5;
}

int main(int argc, char **argv)
{
    a64_lower_handler = lower;
    el0_map();
    uint64_t s = SEED;
    for(unsigned i = 0; i < 1024; i++)
    {
        s ^= s << 13;
        s ^= s >> 7;
        s ^= s << 17;
        buffer[i] = (uint32_t)s;
    }
    const uint32_t header = fuzz_a32[0];
    uint32_t regs[15];
    for(int i = 0; i < 15; i++) regs[i] = 0;
    regs[8] = (uint32_t)el0_address(buffer);
    regs[13] = (uint32_t)el0_address(stack + 2048);
    // AArch32 User, A I F masked, T for a T32 program; its code after the header word
    const uint64_t base = el0_address(fuzz_a32), entry = base + 4;
    const uint64_t spsr = 0x10 | 0x1C0 | (header & 1 ? 0x20 : 0);
    a32_run(entry, spsr, regs);
    printf("exit esr %08lx elr %lx\n", last.esr, (unsigned long)(last.elr - base));
    for(unsigned i = 0; i < 1024; i++) printf("%08x%c", buffer[i], i % 8 == 7 ? '\n' : ' ');
    for(int i = 0; i < 15; i++) printf(" %lx", i == 13 ? last.x[i] - el0_address(stack) : last.x[i]);
    printf("\n");
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/aarch32/oracle.c                                                               0000644 0000000 0000000 00000016026 00000000000 014261  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AArch32 single-instruction oracle's driver (docs/aarch32-plan.md Q0.3,
// tests/a64/aarch32_oracle.mjs): each case of the generated binary is one
// instruction followed by SVC #0, run at EL0 with registers from its seed
// (those of its pointer mask at the data buffer, of its small mask small),
// its NZCV, Q and GE; what comes back is printed: the registers, NZCV Q GE
// (SPSR), the exception if it was not the SVC, and a hash of the data
// buffer, which is set again before each case. The same output from QEMU
// (cortex-a35) and v86 is the test.
// A case with bit 0 of its PSR word is a floating-point one: D0-D31 from the
// seed too (special values among them), FPSCR's AHP, DN, FZ and RMode from
// the PSR word's bits 26:22; printed after: FPSCR and the D registers that
// changed. A register of the small mask's bits 30:16 has FPSCR's Len and
// Stride clear (a value for VMSR).
#include <a64.h>
#include <stdio.h>

extern const uint32_t oracle_a32[];

struct exit_state
{
    uint64_t x[15], esr, far, elr, spsr, vector;
};
static volatile struct exit_state last;
extern char a32_resume_el1[];
void a32_run(uint64_t entry, uint64_t spsr, const uint32_t regs[15]);
struct fp_state
{
    uint64_t d[32], fpsr, fpcr;
};
void a32_run_fp(uint64_t entry, uint64_t spsr, const uint32_t regs[15], struct fp_state *fp);
static struct fp_state fp_state __attribute__((aligned(16)));
static uint8_t buffer[8192] __attribute__((aligned(4096)));
static uint32_t stack[256] __attribute__((aligned(16)));

static void lower(struct a64_frame *frame, uint64_t vector)
{
    for(int i = 0; i < 15; i++) last.x[i] = frame->x[i];
    last.esr = a64_read(esr_el1);
    last.far = a64_read(far_el1);
    last.elr = frame->elr;
    last.spsr = frame->spsr;
    last.vector = vector;
    frame->elr = (uint64_t)a32_resume_el1;
    frame->spsr = 0x3C5;
}

static uint32_t next(uint32_t *state)
{
    // xorshift32
    uint32_t x = *state;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    return *state = x;
}

// Special singles and doubles: zeros, ones, infinities, NaNs (quiet and
// signaling, both signs), denormals, the normal range's ends, the integer
// conversions' limits, half precision's
static const uint32_t singles[] = {
    0x00000000, 0x80000000, 0x3f800000, 0xbf800000, 0x7f800000, 0xff800000, 0x7fc00000, 0xffc12345,
    0x7f800001, 0xff8abcde, 0x00000001, 0x807fffff, 0x00800000, 0x7f7fffff, 0x3f000000, 0x4f000000,
    0x4effffff, 0xcf000000, 0x4f800000, 0x477fe000, 0x477ff000, 0x33800000, 0x387fc000, 0x3fc00000,
    0x40200000, 0xbfc00000, 0x3effffff, 0x46fffe00, 0xc7000100, 0x5f000000, 0x40490fdb, 0x34000000,
};
static const uint64_t doubles[] = {
    0x0000000000000000, 0x8000000000000000, 0x3ff0000000000000, 0xbff0000000000000,
    0x7ff0000000000000, 0xfff0000000000000, 0x7ff8000000000000, 0xfff8123456789abc,
    0x7ff0000000000001, 0xfff4000000000000, 0x0000000000000001, 0x800fffffffffffff,
    0x0010000000000000, 0x7fefffffffffffff, 0x3fe0000000000000, 0x41e0000000000000,
    0x41dfffffffc00000, 0xc1e0000000000000, 0x41efffffffe00000, 0x47efffffe0000000,
    0x47efffffffffffff, 0x36a0000000000000, 0x380fffffe0000000, 0x3810000000000000,
    0x40effc0000000000, 0x3ff8000000000000, 0xc004000000000000, 0x400921fb54442d18,
    0x3e70000000000000, 0x43e0000000000000, 0x4330000000000001, 0x3fdfffffffffffff,
};

static uint32_t random_single(uint32_t *seed)
{
    uint32_t r = next(seed);
    if(r & 1) return singles[r >> 1 & 31];
    // (near one: an exponent 127 +- 15)
    return (r & 0x80000000) | (112 + (r >> 6) % 31) << 23 | (next(seed) & 0x7fffff);
}

static uint64_t random_fp(uint32_t *seed)
{
    uint32_t r = next(seed);
    switch(r % 6)
    {
        case 0:
        case 1:
            return (uint64_t)random_single(seed) << 32 | random_single(seed);
        case 2:
            return doubles[r >> 8 & 31];
        case 3:
        case 4:
            return (uint64_t)(r & 0x80000000) << 32 | (uint64_t)(1008 + (r >> 8) % 31) << 52 |
                (uint64_t)(next(seed) & 0xfffff) << 32 | next(seed);
        default:
            return (uint64_t)next(seed) << 32 | next(seed);
    }
}

int main(int argc, char **argv)
{
    a64_lower_handler = lower;
    // (the thread ID registers the CP15 cases read)
    a64_write(tpidr_el0, 0x1234567890abcdefUL);
    a64_write(tpidrro_el0, 0xfedcba0987654321UL);
    const uint32_t *table = oracle_a32;
    const uint64_t base = (uint64_t)oracle_a32;
    const unsigned n = table[0];
    for(unsigned c = 0; c < n; c++)
    {
        const uint32_t *t = table + 1 + 6 * c;
        const uint32_t offset = t[0], psr = t[1], pointers = t[2], small = t[3], pointer_offset = t[5];
        uint32_t seed = t[4] | 1;
        for(int i = 0; i < 8192; i++) buffer[i] = (uint8_t)(i * 131 + 7);
        uint32_t regs[15];
        for(int i = 0; i < 15; i++)
        {
            uint32_t v = next(&seed);
            if(pointers >> i & 1) v = (uint32_t)(uintptr_t)buffer + 4096 + (pointer_offset & 0xFF) + ((v & 7) << 2) * ((pointer_offset >> 8) & 1);
            else if(small >> i & 1) v &= 0x3C;
            if(small >> (16 + i) & 1) v &= ~0x3F0000u;
            regs[i] = v;
        }
        // (a stack for the cases that use R13 as a pointer: the buffer's)
        if(!(pointers >> 13 & 1) && !(small >> 13 & 1)) regs[13] = (uint32_t)(uintptr_t)(stack + 256);
        a64_write(tpidr_el0, 0x1234567890abcdefUL);
        uint64_t entry = base + (offset & ~1u);
        uint64_t spsr = 0x10 | 0x1C0 | (offset & 1 ? 0x20 : 0) | (psr & 0xF80F0000u);
        last.vector = ~0ul;
        uint64_t initial[32];
        if(psr & 1)
        {
            for(int i = 0; i < 32; i++) initial[i] = fp_state.d[i] = random_fp(&seed);
            fp_state.fpsr = 0;
            fp_state.fpcr = psr & 0x07C00000u;
            a32_run_fp(entry, spsr, regs, &fp_state);
        }
        else a32_run(entry, spsr, regs);
        uint32_t hash = 2166136261u;
        for(int i = 0; i < 8192; i++) hash = (hash ^ buffer[i]) * 16777619u;
        const uint32_t ec = last.esr >> 26;
        printf("%u", c);
        if(last.vector != 12 || last.esr != (offset & 1 ? 0x44000000ul : 0x46000000ul))
        {
            printf(" exception %lu esr %08lx elr %+ld", last.vector, last.esr, (long)(last.elr - base));
            if(ec >= 0x20 && ec <= 0x25) printf(" far %08lx", last.far & 0xFFF);
        }
        else if(last.elr - base != (offset & ~1u) + (t[5] >> 16))
        {
            printf(" elr %+ld", (long)(last.elr - base));
        }
        printf(" psr %08lx", last.spsr & 0xF80F0000u);
        for(int i = 0; i < 15; i++)
        {
            uint64_t v = last.x[i];
            if((uint32_t)v - (uint32_t)(uintptr_t)buffer < 8192u) printf(" b+%lx", v - (uint64_t)(uintptr_t)buffer);
            else printf(" %lx", v);
        }
        printf(" mem %08x", hash);
        if(psr & 1)
        {
            printf(" fpscr %08lx", fp_state.fpsr | fp_state.fpcr);
            for(int i = 0; i < 32; i++)
            {
                if(fp_state.d[i] != initial[i]) printf(" d%d=%lx", i, fp_state.d[i]);
            }
        }
        printf("\n");
    }
    printf("done\n");
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/a64/aarch32/q1.a32.S                                                               0000644 0000000 0000000 00000002124 00000000000 013673  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 cases of docs/aarch32-plan.md Q1 (tests/a64/aarch32_el0.mjs):
// the exception entry and return between AArch32 EL0 and AArch64 EL1 with
// the instructions Q1 has: NOP, B, SVC (and UDF), in A32 and T32.
// The table: count, then per case offset (+1: T32), resumes, NZCV.
    .syntax unified
    .arm
base:
    .word   10
    .word   a32_svc - base, 0, 0
    .word   a32_branch - base, 0, 0
    .word   a32_svc_imm - base, 0, 0
    .word   a32_resume - base, 2, 0
    .word   a32_udf - base, 0, 0
    .word   a32_cond - base, 0, 4       @ Z
    .word   a32_flags - base, 0, 0xA    @ N and C
    .word   t32_svc - base + 1, 0, 0
    .word   t32_resume - base + 1, 1, 0
    .word   t32_udf - base + 1, 0, 0

a32_svc:
    nop
    svc     #0
a32_branch:
    b       1f
    udf     #1
1:  svc     #1
a32_svc_imm:
    svc     #0x12abcd
a32_resume:
    svc     #2
    svc     #3
    svc     #4
a32_udf:
    udf     #0x1234
a32_cond:
    svcne   #5
    svceq   #6
a32_flags:
    svc     #7

    .thumb
t32_svc:
    nop
    svc     #8
t32_resume:
    svc     #9
    svc     #10
t32_udf:
    udf     #3
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/a64/aarch32/q3.a32.S                                                               0000644 0000000 0000000 00000014215 00000000000 013701  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 cases of docs/aarch32-plan.md Q2.3, Q3.2, Q3.3
// (tests/a64/aarch32_el0.mjs, A64_AARCH32_CASES=q3): branches and
// interworking in both directions (B, BL, BX, BLX, loads of the PC, the
// ALU's writes of it), CBZ and CBNZ, TBB and TBH, conditional branches,
// and IT blocks: conditions, the flags 16-bit instructions do not set in
// them, and an exception in the middle of one (ITSTATE in SPSR_EL1) whose
// return goes on with the block. A load-exclusive that spins (the same
// doubleword again and again: the interpreter's yield) overwriting its
// base register. An IT block the end of a page cuts, in a loop. A native
// IT block (all its instructions native) that something which is not code
// "branches" into, run from an offset the page's function does not serve
// (it steps the instructions up to the IT and the IT itself).
// The table: count, then per case offset (+1: T32), resumes, NZCV.
    .syntax unified
    .arm
base:
    .word   22
    .word   a32_branches - base, 0, 0
    .word   a32_bl - base, 0, 0
    .word   a32_bx_t32 - base, 0, 0
    .word   a32_blx_imm - base, 0, 0
    .word   a32_ldr_pc - base, 0, 0
    .word   a32_alu_pc - base, 0, 0
    .word   a32_ldm_pc - base, 0, 0
    .word   a32_cond_branch - base, 0, 6     @ Z, C
    .word   t32_branches - base + 1, 0, 0
    .word   t32_bl_blx - base + 1, 0, 0
    .word   t32_cbz - base + 1, 0, 0
    .word   t32_tbb - base + 1, 0, 0
    .word   t32_pop_pc - base + 1, 0, 0
    .word   t32_cond_branch - base + 1, 0, 8 @ N
    .word   t32_it - base + 1, 0, 0
    .word   t32_it_flags - base + 1, 0, 0
    .word   t32_it_svc - base + 1, 2, 0
    .word   t32_it_else - base + 1, 0, 0
    .word   a32_ldrexd_spin - base, 0, 0
    .word   t32_ldrexd_spin - base + 1, 0, 0
    .word   t32_it_page - base + 1, 0, 0
    .word   t32_it_bogus - base + 1, 0, 0

a32_branches:
    b       1f
    udf     #1
2:  svc     #1
1:  b       2b

a32_bl:
    bl      1f
    svc     #2
1:  mov     r0, lr
    sub     r0, r0, pc
    svc     #3

a32_bx_t32:
    adr     r1, 1f + 1
    bx      r1
    .thumb
1:  movs    r2, #42
    adr     r3, 2f
    bx      r3
    .balign 4
    .arm
2:  svc     #4

a32_blx_imm:
    blx     1f
    svc     #5
    .thumb
    .balign 2
1:  movs    r4, #7
    bx      lr
    .arm

a32_ldr_pc:
    adr     r0, 1f + 1
    str     r0, [sp, #-4]!
    ldr     pc, [sp], #4
    udf     #2
    .thumb
1:  movs    r5, #9
    svc     #6
    .arm
    .balign 4

a32_alu_pc:
    adr     r6, 1f + 1
    mov     pc, r6
    udf     #3
    .thumb
1:  movs    r7, #11
    svc     #7
    .arm
    .balign 4

a32_ldm_pc:
    adr     r3, 1f + 1
    movw    r2, #0x5678
    push    {r2, r3}
    ldm     sp!, {r2, pc}
    udf     #4
    .thumb
1:  svc     #8
    .arm
    .balign 4

a32_cond_branch:
    bne     1f
    bcc     1f
    beq     2f
1:  udf     #5
2:  svc     #9

    .thumb
    .balign 2
t32_branches:
    b       1f
    udf     #6
2:  b.w     3f
    udf     #7
1:  b       2b
3:  svc     #10

t32_bl_blx:
    bl      1f
    svc     #11
1:  mov     r8, lr
    blx     2f
    svc     #12
    .arm
    .balign 4
2:  mov     r9, lr
    bx      lr
    .thumb

t32_cbz:
    movs    r0, #0
    movs    r1, #1
    cbz     r1, 1f
    cbz     r0, 2f
1:  udf     #8
2:  cbnz    r0, 4f
    cbnz    r1, 3f
4:  udf     #9
3:  svc     #13

t32_tbb:
    movs    r0, #2
    tbb     [pc, r0]
4:  .byte   (5f - 4b) / 2, (5f - 4b) / 2, (6f - 4b) / 2, (5f - 4b) / 2
5:  udf     #10
6:  movs    r1, #1
    tbh     [pc, r1, lsl #1]
7:  .hword  (8f - 7b) / 2, (9f - 7b) / 2
8:  udf     #11
9:  svc     #14

t32_pop_pc:
    adr     r0, 1f + 1
    push    {r0}
    pop     {pc}
    udf     #12
    .balign 2
1:  adr     r3, 2f + 1
    str     r3, [sp, #-4]!
    ldr.w   pc, [sp], #4
    udf     #13
    .balign 4
2:  mov     r1, pc
    adds    r1, #4
    mov     pc, r1
    udf     #16
    svc     #15

t32_cond_branch:
    beq     1f
    bmi.w   2f
1:  udf     #14
2:  bpl     1b
    bmi     3f
    udf     #15
3:  svc     #16

t32_it:
    movs    r0, #5
    cmp     r0, #5
    ittet   eq
    moveq   r1, #1
    addeq   r1, r1, #2
    movne   r2, #3
    moveq   r3, #4
    svc     #17

t32_it_flags:
    movs    r0, #0
    cmp     r0, #1                  @ N, not Z, not C
    it      ne
    addne   r0, r0, #1              @ 16-bit ADD: no flags in the block
    svc     #18

t32_it_svc:
    movs    r0, #1
    cmp     r0, #1
    itttt   eq
    moveq   r1, #1
    svceq   #19
    moveq   r2, #2
    svceq   #20
    movs    r3, #3
    svc     #21

t32_it_else:
    movs    r0, #1
    cmp     r0, #2
    itete   eq
    moveq   r1, #1
    movne   r2, #2
    moveq   r3, #3
    movne   r4, #4
    svc     #22

t32_ldrexd_spin:
    mov     r3, sp
    movs    r4, #0x55
    movs    r5, #0x66
    strd    r4, r5, [r3]
    movs    r2, #100
1:  mov     r0, r3
    ldrexd  r4, r0, [r0]
    clrex
    subs    r2, #1
    bne     1b
    svc     #23

    .arm
    .balign 4
a32_ldrexd_spin:
    mov     r3, sp
    mov     r4, #0x77
    mov     r5, #0x88
    strd    r4, r5, [r3]
    mov     r2, #100
1:  mov     r1, r3
    ldrexd  r0, r1, [r1]
    clrex
    subs    r2, r2, #1
    bne     1b
    svc     #24

    .thumb
    .balign 4096
    .space  4096 - 16
t32_it_page:
    movs    r2, #250
    movs    r3, #0
1:  subs    r2, #1
    cmp     r2, #100
    nop
    nop
    nop
    itt     gt                  @ the last halfword of the page
    addgt   r3, #1              @ the next page's first instructions
    addgt   r3, #2
    cmp     r2, #0
    bne     1b
    svc     #25

    .balign 4096
t32_it_bogus:
    movs    r0, #4
    movs    r5, #3
    movs    r6, #0
1:  cmp     r5, #0
    bne     2f
    blx     t32_it_bogus_arm    @ never runs: a step (to A32), after it
    bne.n   4f                  @ what discovery takes for code: a target in the IT block
2:  adr     r1, 3f + 1
    bx      r1                  @ to an offset no block starts at: stepped from there
    .balign 4
3:  mov     r4, r0
    cmp     r0, #0
    it      ne
4:  addne   r0, #8              @ the native IT block
    str     r0, [sp, #-4]
    itt     ne                  @ a helper's IT block (a load in it)
    ldrne   r7, [sp, #-4]
    addne   r6, r7
    subs    r5, #1
    bne     1b
    svc     #26
    .arm
t32_it_bogus_arm:
    bx      lr
                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/aarch32/q4.a32.S                                                               0000644 0000000 0000000 00000003651 00000000000 013704  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 cases of docs/aarch32-plan.md Q4.4 (tests/a64/aarch32_el0.mjs,
// A64_AARCH32_CASES=q4): CPACR_EL1.FPEN traps floating point and Advanced
// SIMD at EL0 (EC 0x07, CV 1, COND 0xE) when it is 00 or 01; an encoding
// that is UNDEFINED is UNDEFINED first; an instruction that fails its
// condition does not trap; with 11 they run.
// The table: count, then per case offset (+1: T32), resumes, NZCV (bit 8:
// CPACR_EL1.FPEN from bits 5:4).
    .syntax unified
    .arm
    .fpu crypto-neon-fp-armv8
base:
    .word   10
    .word   a32_vadd - base, 0, 0x100           @ FPEN 00
    .word   t32_vmrs - base + 1, 0, 0x110       @ FPEN 01: EL1 only
    .word   a32_vadd_ne - base, 0, 0x104        @ FPEN 00, Z: VADDNE does not run
    .word   a32_vmov_scalar - base, 0, 0x100
    .word   a32_vjcvt - base, 0, 0x100          @ UNDEFINED: not in the profile
    .word   a32_vsel - base, 0, 0x100
    .word   t32_vldr - base + 1, 0, 0x110
    .word   a32_vstm - base, 0, 0x100
    .word   a32_fp_on - base, 0, 0x130          @ FPEN 11
    .word   t32_it_vmov - base + 1, 0, 0x104    @ FPEN 00, Z: in an IT block

a32_vadd:
    vadd.f32 s0, s1, s2
    svc     #1

    .thumb
    .balign 2
t32_vmrs:
    vmrs    r0, fpscr
    svc     #2
    .arm
    .balign 4

a32_vadd_ne:
    vaddne.f32 s0, s1, s2
    svc     #3

a32_vmov_scalar:
    vmov.u8 r0, d1[3]
    svc     #4

a32_vjcvt:
    .word   0xeef90bc0                          @ VJCVT.S32.F64 s1, d0
    svc     #5

a32_vsel:
    vseleq.f64 d0, d1, d2
    svc     #6

    .thumb
    .balign 2
t32_vldr:
    vldr    d0, [sp, #-8]
    svc     #7
    .arm
    .balign 4

a32_vstm:
    vpush   {d8-d9}
    svc     #8

a32_fp_on:
    vmov    s0, r1
    vmov.f32 s1, #1.5
    vadd.f32 s2, s0, s1
    vmov    r2, s2
    vmrs    r3, fpscr
    vcmp.f32 s2, s1
    vmrs    APSR_nzcv, fpscr
    svc     #9

    .thumb
    .balign 2
t32_it_vmov:
    it      ne
    vmovne  s0, r1
    vmov    r0, s0
    svc     #10
                                                                                       source/v64/tests/a64/aarch32/qdebug.a32.S                                                           0000644 0000000 0000000 00000003435 00000000000 014627  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 debug cases of docs/aarch32-plan.md Q1.5
// (tests/a64/aarch32_el0.mjs, A64_AARCH32_DRIVER=debug
// A64_AARCH32_CASES=qdebug): software step through A32 and T32 code (an IT
// block, a 32-bit instruction, a load exclusive: ESR's EX), breakpoints on an
// A32 instruction and on either halfword of a T32 word, watchpoints on loads
// and stores (FAR, WnR), a breakpoint on an instruction that fails its
// condition. The table: count, then per case offset (+1: T32), resumes, the
// control word (tests/a64/aarch32/debug.c), the breakpoint's offset.
    .syntax unified
    .arm
base:
    .word   9
    .word   a32_steps - base, 6, 0x10, 0
    .word   t32_steps - base + 1, 9, 0x10, 0
    .word   a32_ldrex - base, 3, 0x10, 0
    .word   a32_steps - base, 1, 0x20, a32_target - base
    .word   t32_steps - base + 1, 1, 0x60, t32_low - base       @ BAS 0011
    .word   t32_steps - base + 1, 1, 0xA0, t32_high - base - 2  @ BAS 1100
    .word   a32_watch - base, 1, 0x300, 0                       @ LSC 01: loads
    .word   a32_watch - base, 1, 0x500, 0                       @ LSC 10: stores
    .word   a32_cond - base, 1, 0x26, a32_cond_target - base    @ Z, C

a32_steps:
    mov     r0, #1
    add     r0, r0, #2
a32_target:
    lsl     r0, r0, #3
    nop
    svc     #1

    .thumb
    .balign 4
t32_steps:
    movs    r2, #5
    cmp     r2, #5
    itte    eq
    moveq   r3, #1
t32_low:
    addeq   r3, r3, #1
t32_high:
    movne   r4, #9
    add.w   r5, r3, r2, lsl #2
    nop
    svc     #2
    .arm
    .balign 4

a32_ldrex:
    ldrex   r2, [r1]
    strex   r3, r2, [r1]
    svc     #3

a32_watch:
    ldr     r2, [r1, #4]
    str     r2, [r1, #16]
    strh    r2, [r1, #6]
    ldrb    r3, [r1, #20]
    svc     #4

a32_cond:
a32_cond_target:
    movne   r0, #5
    moveq   r0, #6
    svc     #5
                                                                                                                                                                                                                                   source/v64/tests/a64/aarch32/unpredictable.a32.S                                                    0000644 0000000 0000000 00000011565 00000000000 016204  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AArch32 EL0 cases for v86's choices among CONSTRAINED UNPREDICTABLE
// behaviours (tests/a64/aarch32_unpredictable.mjs, which knows the values:
// QEMU 9.2 takes some of these as UNDEFINED). T32's LDM and STM (encoding
// T2) of one register transfer it, as Cortex-A cores do: IA and DB, with
// and without writeback, LR and the PC (a return), in an IT block, in a
// loop; A32's LDM of one register (not UNPREDICTABLE) the same. The other
// UNPREDICTABLE lists stay UNDEFINED: the base in the list with writeback,
// an empty list, SP in the list, STM of the PC. The instructions are words
// (.inst.w) so that the assembler cannot turn them into LDR and STR.
// The table: count, then per case offset (+1: T32), resumes, NZCV.
    .syntax unified
    .arm
base:
    .word   15
    .word   t32_ldm_wb - base + 1, 0, 0
    .word   t32_ldm - base + 1, 0, 0
    .word   t32_stm_wb - base + 1, 0, 0
    .word   t32_stm - base + 1, 0, 0
    .word   t32_ldmdb_wb - base + 1, 0, 0
    .word   t32_stmdb_wb - base + 1, 0, 0
    .word   t32_ldm_lr - base + 1, 0, 0
    .word   t32_ldm_pc - base + 1, 0, 0
    .word   t32_ldm_it - base + 1, 0, 0
    .word   t32_ldm_loop - base + 1, 0, 0
    .word   a32_ldm_wb - base, 0, 0
    .word   t32_ldm_base_wb - base + 1, 0, 0
    .word   t32_ldm_empty - base + 1, 0, 0
    .word   t32_ldm_sp - base + 1, 0, 0
    .word   t32_stm_pc - base + 1, 0, 0

    .thumb
// (each: r8 a buffer below SP, r9 its address, r10 how far r8 moved)
t32_ldm_wb:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0x3344
    movt    r1, #0x1122
    str     r1, [r8]
    .inst.w 0xe8b80001          @ ldm.w r8!, {r0}
    sub     r10, r8, r9
    svc     #1

t32_ldm:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0x7788
    movt    r1, #0x5566
    str     r1, [r8]
    .inst.w 0xe8980001          @ ldm.w r8, {r0}
    sub     r10, r8, r9
    svc     #2

t32_stm_wb:
    sub     r8, sp, #64
    mov     r9, r8
    movs    r0, #0
    str     r0, [r8]
    str     r0, [r8, #4]
    movw    r1, #0xBBCC
    movt    r1, #0x99AA
    .inst.w 0xe8a80002          @ stm.w r8!, {r1}
    ldr     r0, [r9]
    ldr     r2, [r9, #4]
    sub     r10, r8, r9
    svc     #3

t32_stm:
    sub     r8, sp, #64
    mov     r9, r8
    movs    r0, #0
    str     r0, [r8]
    movw    r1, #0xFF00
    movt    r1, #0xDDEE
    .inst.w 0xe8880002          @ stm.w r8, {r1}
    ldr     r0, [r9]
    sub     r10, r8, r9
    svc     #4

t32_ldmdb_wb:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0x2468
    movt    r1, #0x1357
    str     r1, [r8, #-4]
    .inst.w 0xe9380001          @ ldmdb r8!, {r0}
    sub     r10, r8, r9
    svc     #5

t32_stmdb_wb:
    sub     r8, sp, #64
    mov     r9, r8
    movs    r0, #0
    str     r0, [r8, #-4]
    str     r0, [r8]
    movw    r1, #0x8642
    movt    r1, #0x7531
    .inst.w 0xe9280002          @ stmdb r8!, {r1}
    ldr     r0, [r9, #-4]
    ldr     r2, [r9]
    sub     r10, r8, r9
    svc     #6

t32_ldm_lr:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0xCAFE
    movt    r1, #0xC0DE
    str     r1, [r8]
    .inst.w 0xe8b84000          @ ldm.w r8!, {lr}
    sub     r10, r8, r9
    svc     #7

t32_ldm_pc:
    sub     r8, sp, #64
    mov     r9, r8
    adr     r1, 1f + 1
    str     r1, [r8]
    .inst.w 0xe8988000          @ ldm.w r8, {pc}
    udf     #1
    .balign 4
1:  movs    r0, #0x42
    sub     r10, r8, r9
    svc     #8

t32_ldm_it:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0x1111
    movt    r1, #0x2222
    str     r1, [r8]
    str     r1, [r8, #4]
    movs    r0, #0
    movs    r2, #0
    cmp     r0, #0
    .inst.n 0xbf08              @ it eq
    .inst.w 0xe8b80001          @ ldmeq.w r8!, {r0}
    .inst.n 0xbf18              @ it ne
    .inst.w 0xe8b80004          @ ldmne.w r8!, {r2} (not taken)
    sub     r10, r8, r9
    svc     #9

t32_ldm_loop:
    sub     r8, sp, #64
    mov     r9, r8
    movs    r0, #1
    str     r0, [r8]
    movs    r0, #2
    str     r0, [r8, #4]
    movs    r0, #3
    str     r0, [r8, #8]
    movs    r5, #3
    movs    r6, #0
1:  .inst.w 0xe8b80001          @ ldm.w r8!, {r0}
    add     r6, r0
    subs    r5, #1
    bne     1b
    sub     r10, r8, r9
    svc     #10

    .arm
    .balign 4
a32_ldm_wb:
    sub     r8, sp, #64
    mov     r9, r8
    movw    r1, #0x5A5A
    movt    r1, #0xA5A5
    str     r1, [r8]
    .inst   0xe8b80001          @ ldm r8!, {r0}
    sub     r10, r8, r9
    svc     #11

    .thumb
    .balign 2
// (UNDEFINED: the driver prints the exit, ELR at the instruction)
t32_ldm_base_wb:
    sub     r8, sp, #64
    .inst.w 0xe8b80100          @ ldm.w r8!, {r8}
    svc     #12

t32_ldm_empty:
    sub     r8, sp, #64
    .inst.w 0xe8980000          @ ldm.w r8, {}
    svc     #13

t32_ldm_sp:
    sub     r8, sp, #64
    .inst.w 0xe8982000          @ ldm.w r8, {sp}
    svc     #14

t32_stm_pc:
    sub     r8, sp, #64
    .inst.w 0xe8888000          @ stm.w r8, {pc}
    svc     #15
                                                                                                                                           source/v64/tests/a64/aarch32_bench.mjs                                                              0000755 0000000 0000000 00000020533 00000000000 014523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AArch32's speed against A64's (docs/aarch32-plan.md Q6.4): the integer
// kernels of tests/bench/src, the same C, built for A64 (run at EL1), A32
// and T32 (armv7, run at EL0 under the 64-bit EL1: tests/a64/aarch32/bench.c)
// and timed on v86 with the page tier (A64_JIT=1 unless A64_BENCH_JIT=0;
// a64_page_aarch32 as A64_AARCH32_PAGE says, default 1): the host's time of
// each run less that of a run of no iterations (the machine's start; the
// guest's counter is the harness's clock); the checksums of the three
// builds must agree. The gate: 32-bit takes at most twice A64's time (the
// geometric mean of the kernels). --arm32 (R5.3's E level): the A32 and T32
// builds run at PL1 on cpu_type "arm32" instead (tests/a32/bench.c: the
// 32-bit kernel's view, the MMU on with short descriptors).
//
//   node tests/a64/aarch32_bench.mjs [--kernels hash,sort,...] [--scale N] [--arm32]
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { build, actual, root } from "./guest_runner.mjs";
import { build32 as build_arm32, actual32 } from "../a32/runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
// (tests/bench/suite.json's iterations, divided by the scale; not chase,
// whose 2 MiB list the A64 image's layout has no room for, nor muldiv,
// whose 64-bit divisions are AEABI library calls on armv7)
const KERNELS = { bytecode: 310, vcall: 490, strings: 85, bitboard: 370, recursion: 390, lz: 13, hash: 66, sort: 24 };
const names = option("--kernels", Object.keys(KERNELS).join(",")).split(",");
const SCALE = +option("--scale", 0.1);
const arm32 = args.includes("--arm32");

const host = spawnSync("rustc", ["-vV"], { encoding: "utf8" }).stdout.match(/host: (\S+)/)[1];
const lld = process.env.LD_LLD || `${spawnSync("rustc", ["--print", "sysroot"], { encoding: "utf8" }).stdout.trim()}/lib/rustlib/${host}/bin/rust-lld`;
const clang = process.env.CLANG || "clang";
const run = (program, list) => {
    const r = spawnSync(program, list, { encoding: "utf8" });
    assert.equal(r.status, 0, program + " " + list.join(" ") + "\n" + r.stderr);
    return r.stdout;
};

// the 32-bit builds: linked at EL0's alias of PHYSICAL (el0_map.h), stack 8 MiB up
const PHYSICAL = 0x44000000, BASE = PHYSICAL + 0x80000000;
const COMMON = ["-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector", "-fno-vectorize", "-fno-slp-vectorize"];

function build32(name, source, iterations, thumb)
{
    const directory = `${root}build/a64-aarch32-bench/${name}-${iterations}-${thumb ? "t32" : "a32"}/`;
    fs.mkdirSync(directory, { recursive: true });
    const target = ["--target=armv7a-none-eabi", "-march=armv8-a", "-mfloat-abi=soft", thumb ? "-mthumb" : "-marm"];
    const objects = [];
    for(const [file, extra] of [[source, []], [root + "tests/a64/aarch32/bench_rt.c", ["-DBENCH32"]],
        [root + "tests/a64/aarch32/bench_start.S", thumb ? ["-DTHUMB"] : []]])
    {
        const object = directory + path.basename(file).replace(/\.[cS]$/, ".o");
        run(clang, [...target, ...COMMON, ...extra, "-c", "-o", object, file]);
        objects.push(object);
    }
    // (data in pages of its own, as a program's: writes into a page of code recompile it)
    const script = directory + "link.ld";
    fs.writeFileSync(script, `ENTRY(_start)
SECTIONS
{
    . = 0x${BASE.toString(16)};
    .text : { *(.text.start) *(.text .text.*) }
    .rodata : { *(.rodata .rodata.*) }
    . = ALIGN(4096);
    .data : { *(.data .data.*) }
    . = ALIGN(16);
    __bss_start = .;
    .bss : { *(.bss .bss.* COMMON) }
    __bss_end = ALIGN(16);
    __stack_top = 0x${(BASE + 0x800000).toString(16)};
}
`);
    run(lld, ["-flavor", "gnu", "-m", "armelf", "-T", script, "-o", directory + "bench.elf", ...objects]);
    run(lld, ["-flavor", "gnu", "-m", "armelf", "-T", script, "--oformat=binary", "-o", directory + "bench.bin", ...objects]);
    const symbols = Object.fromEntries(run(process.env.NM || "nm", [directory + "bench.elf"])
        .split("\n").map(l => l.split(" ")).filter(p => p.length === 3).map(([a, , s]) => [s, parseInt(a, 16)]));
    const wrapper = directory + "bench32.S";
    fs.writeFileSync(wrapper, `    .section .rodata\n    .balign 4096\n    .global bench32\nbench32:\n    .incbin "${directory}bench.bin"\n` +
        `    .global bench32_end\nbench32_end:\n`);
    return build(`aarch32-bench-${name}-${iterations}-${thumb ? "t32" : "a32"}`, [root + "tests/a64/aarch32/bench.c", root + "tests/a64/aarch32/el0_run.S", wrapper], {
        cflags: [`-DITERATIONS=${iterations}`, `-DNAME="${name}"`, "-DBENCH32", "-DA64_MMU", `-DBENCH32_PHYSICAL=0x${PHYSICAL.toString(16)}UL`,
            `-DBENCH32_BASE=0x${BASE.toString(16)}UL`, `-DBENCH32_ENTRY=0x${symbols._start.toString(16)}UL`, `-DBENCH32_BSS_START=0x${symbols.__bss_start.toString(16)}UL`,
            `-DBENCH32_BSS_END=0x${symbols.__bss_end.toString(16)}UL`, `-DBENCH32_THUMB=${thumb ? 1 : 0}`],
    });
}

process.env.A64_MMU = "1";
if(process.env.A64_BENCH_JIT !== "0")
{
    process.env.A64_JIT = "1";
    process.env.A64_JIT_HOT = process.env.A64_JIT_HOT || "2000";
    process.env.A64_JIT_SWITCHES = "a64_page_aarch32=" + (process.env.A64_AARCH32_PAGE || "1");
}
const builds = (name, source, iterations) => [
    ["a64", build(`aarch32-bench-${name}-${iterations}-a64`, [root + "tests/a64/aarch32/bench.c", source, root + "tests/a64/aarch32/bench_rt.c"],
        { cflags: [`-DITERATIONS=${iterations}`, `-DNAME="${name}"`, "-fno-vectorize", "-fno-slp-vectorize"], general_regs_only: true })],
    ...(arm32 ? [false, true].map(thumb => [thumb ? "t32" : "a32", build_arm32(`bench-${name}-${iterations}-${thumb ? "t32" : "a32"}`,
        [root + "tests/a32/bench.c", source, root + "tests/a64/aarch32/bench_rt.c"],
        { cflags: [`-DITERATIONS=${iterations}`, `-DNAME="${name}"`, "-fno-vectorize", "-fno-slp-vectorize"], thumb })]) : [
        ["a32", build32(name, source, iterations, false)],
        ["t32", build32(name, source, iterations, true)],
    ]),
];
/** a run: its checksum and the host's milliseconds */
async function measure(directory, what, kind)
{
    const started = performance.now();
    const r = arm32 && kind !== "a64" ?
        await actual32(directory, { timeout: +(process.env.A64_BENCH_TIMEOUT || 600000) }) :
        await actual(directory, { timeout: +(process.env.A64_BENCH_TIMEOUT || 600000), options: { cpu_profile: "generic-arm64-compat32" } });
    const ms = performance.now() - started;
    assert.equal(r.status, "ok", `${what}: ${r.status}\n${r.text}`);
    assert.ok(!/an exception/.test(r.text), `${what}: ${r.text}`);
    const m = r.text.match(/checksum (\w+)/);
    assert.ok(m, `${what}: ${r.text}`);
    return { checksum: m[1], ms };
}
// (the machine's start: a run of no iterations, the best of three)
const baseline = {};
for(const [kind, directory] of builds(names[0], `${root}tests/bench/src/${names[0]}.c`, 0))
{
    const times = [];
    for(let i = 0; i < 3; i++) times.push((await measure(directory, kind + " baseline", kind)).ms);
    baseline[kind] = Math.min(...times);
}
console.log(`baseline (the machine's start): ${Object.entries(baseline).map(([k, v]) => k + " " + v.toFixed(0) + " ms").join(", ")}`);
const results = [];
for(const name of names)
{
    const source = `${root}tests/bench/src/${name}.c`;
    const iterations = Math.max(1, Math.round(KERNELS[name] / SCALE));
    const row = { name, iterations };
    for(const [kind, directory] of builds(name, source, iterations))
    {
        const m = await measure(directory, `${name} ${kind}`, kind);
        row[kind] = { checksum: m.checksum, ms: Math.max(1, m.ms - baseline[kind]) };
    }
    assert.equal(row.a32.checksum, row.a64.checksum, name + ": A32's checksum is A64's");
    assert.equal(row.t32.checksum, row.a64.checksum, name + ": T32's checksum is A64's");
    console.log(`${name}: A64 ${row.a64.ms.toFixed(0)} ms, A32 ${row.a32.ms.toFixed(0)} ms (x${(row.a32.ms / row.a64.ms).toFixed(2)}), ` +
        `T32 ${row.t32.ms.toFixed(0)} ms (x${(row.t32.ms / row.a64.ms).toFixed(2)})`);
    results.push(row);
}
const mean = kind => Math.exp(results.reduce((n, r) => n + Math.log(r[kind].ms / r.a64.ms), 0) / results.length);
console.log(`aarch32 bench${arm32 ? " (arm32, PL1)" : ""}: 32-bit against A64 (geometric means): A32 x${mean("a32").toFixed(2)}, T32 x${mean("t32").toFixed(2)}`);
                                                                                                                                                                     source/v64/tests/a64/aarch32_el0.mjs                                                                0000644 0000000 0000000 00000003471 00000000000 014123  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AArch32 EL0 under the bare-metal AArch64 EL1 (docs/aarch32-plan.md Q0.2,
// Q1): the cases of tests/a64/aarch32/*.a32.S, run by tests/a64/aarch32/el0.c
// on QEMU (cortex-a35, which has AArch32 EL0) and on v86 with profile v3;
// the outputs must be the same. A64_AARCH32_CASES=q1 (default): which binary.
// A64_AARCH32_REFERENCE_ONLY=1: QEMU's output only. A64_AARCH32_DRIVER: the
// EL1 driver, tests/a64/aarch32/<driver>.c (default el0).
import assert from "node:assert/strict";
import { build, reference, actual, root } from "./guest_runner.mjs";

const cases = process.env.A64_AARCH32_CASES || "q1";
// (A64_AARCH32_DRIVER=debug: tests/a64/aarch32/debug.c, the cases with the debug registers)
const driver = process.env.A64_AARCH32_DRIVER || "el0";
const directory = build("aarch32-" + cases, [root + `tests/a64/aarch32/${driver}.c`, root + "tests/a64/aarch32/el0_run.S",
    root + `tests/a64/aarch32/${cases}.a32.S`], { cflags: [`-DCASES=${cases}_a32`] });
const expected = await reference(directory);
assert.equal(expected.status, "ok", "QEMU: " + expected.status + "\n" + expected.text);
if(+process.env.A64_AARCH32_REFERENCE_ONLY)
{
    console.log(expected.text);
    process.exit(0);
}
const got = await actual(directory, { options: { cpu_profile: "generic-arm64-compat32" } });
const a = expected.text.split("\n"), b = got.text.split("\n");
for(let i = 0; i < Math.max(a.length, b.length); i++)
{
    if(a[i] !== b[i])
    {
        console.log(`first difference at line ${i + 1}:\n  QEMU: ${a[i]}\n  v86:  ${b[i]}\n(context: ${a.slice(Math.max(0, i - 2), i).join(" | ")})`);
        break;
    }
}
assert.equal(got.status, "ok", "v86: " + got.status);
assert.equal(got.text, expected.text, "v86's output is QEMU's");
console.log(`PASS: ${cases}: ${a.filter(l => l.startsWith("case")).length} exits as QEMU's`);
                                                                                                                                                                                                       source/v64/tests/a64/aarch32_oracle.mjs                                                             0000644 0000000 0000000 00000111517 00000000000 014711  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The AArch32 single-instruction oracle (docs/aarch32-plan.md Q0.3): random
// instructions of each encoding class, generated here with the operands an
// instruction may have without being UNPREDICTABLE (no PC where it is one,
// pointers into the data buffer for the loads and stores, small indexes),
// each run once at EL0 by tests/a64/aarch32/oracle.c on QEMU (cortex-a35)
// and on v86 (profile v3), with random registers, NZCV, Q and GE; the two
// outputs must be the same. The classes are A32's integer instructions (Q2),
// T32's (Q3) and the VFP and Advanced SIMD ones (Q4) as they come.
//
// A64_AARCH32_SEED (default 1), A64_AARCH32_COUNT (cases per class, default
// 40), A64_AARCH32_ONLY=<class,...>, A64_AARCH32_SET=a32|t32 (default both
// that have classes)
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

let seed = +(process.env.A64_AARCH32_SEED || 1) >>> 0 || 1;
const random = () => {
    seed ^= seed << 13; seed >>>= 0;
    seed ^= seed >>> 17;
    seed ^= seed << 5; seed >>>= 0;
    return seed;
};
const bits = n => n >= 32 ? random() : random() & ((1 << n) - 1) >>> 0;
const pick = list => list[random() % list.length];
/** a register 0-14 (no PC), other than those given */
const reg = (...not) => { for(;;) { const r = random() % 15; if(!not.includes(r) && r !== 13) return r; } };
/** a register 0-14 with R13 allowed (a pointer's base) */
const cond = () => random() % 4 === 0 ? random() % 15 : 14;

// A case: the instruction's encoding, its set, the masks of the registers
// that point into the buffer and are small, the pointer offset
const A32 = {
    // (the fields that should be zero are: QEMU's decoder takes them as UNDEFINED)
    dp_imm() {
        const op = bits(4), s = op >= 8 && op <= 11 ? 1 : bits(1);
        const rd = op >= 8 && op <= 11 ? 0 : reg(), rn = op === 13 || op === 15 ? 0 : reg();
        return { word: cond() << 28 | 1 << 25 | op << 21 | s << 20 | rn << 16 | rd << 12 | bits(12) };
    },
    dp_shift() {
        const op = bits(4), s = op >= 8 && op <= 11 ? 1 : bits(1);
        const rd = op >= 8 && op <= 11 ? 0 : reg(), rn = op === 13 || op === 15 ? 0 : reg();
        return { word: cond() << 28 | op << 21 | s << 20 | rn << 16 | rd << 12 | bits(5) << 7 | bits(2) << 5 | reg() };
    },
    dp_register_shift() {
        const op = bits(4), s = op >= 8 && op <= 11 ? 1 : bits(1);
        const rd = op >= 8 && op <= 11 ? 0 : reg(), rn = op === 13 || op === 15 ? 0 : reg();
        return { word: cond() << 28 | op << 21 | s << 20 | rn << 16 | rd << 12 | reg() << 8 | bits(2) << 5 | 1 << 4 | reg() };
    },
    movw_movt() {
        return { word: cond() << 28 | 0x03 << 24 | pick([0, 4]) << 20 | bits(4) << 16 | reg() << 12 | bits(12) };
    },
    multiply() {
        const op = pick([0, 1, 2, 3, 4, 5, 6, 7]);
        const s = op === 2 || op === 3 ? 0 : bits(1);
        const rd = reg(), ra = op === 0 ? 0 : op >= 4 || op === 2 ? reg(rd) : reg();
        return { word: cond() << 28 | op << 21 | s << 20 | rd << 16 | ra << 12 | reg() << 8 | 0x9 << 4 | reg() };
    },
    halfword_multiply() {
        const op = bits(2), rd = reg(), xy = bits(2);
        // (SMULxy, SMULWy: no accumulator, its field 0)
        const ra = op === 2 ? reg(rd) : op === 3 || op === 1 && xy & 1 ? 0 : reg();
        return { word: cond() << 28 | 0x10 << 20 | op << 21 | rd << 16 | ra << 12 | reg() << 8 | 1 << 7 | xy << 5 | reg() };
    },
    signed_multiply() {
        const [op1, op2] = pick([[0, 0], [0, 1], [0, 2], [0, 3], [4, 0], [4, 1], [4, 2], [4, 3], [5, 0], [5, 1], [5, 6], [5, 7], [1, 0], [3, 0]]);
        const rd = reg();
        // (SMMLS's accumulator is not optional)
        const ra = op1 === 1 || op1 === 3 ? 15 : op1 === 4 || op1 === 5 && op2 >= 6 ? reg(rd) : random() % 3 === 0 ? 15 : reg();
        return { word: cond() << 28 | 0x7 << 24 | op1 << 20 | rd << 16 | ra << 12 | reg() << 8 | op2 << 5 | 1 << 4 | reg() };
    },
    parallel() {
        const kind = pick([1, 2, 3, 5, 6, 7]), op = pick([0, 1, 2, 3, 4, 7]);
        return { word: cond() << 28 | 0x6 << 24 | kind << 20 | reg() << 16 | reg() << 12 | 0xF << 8 | op << 5 | 1 << 4 | reg() };
    },
    pack_extend() {
        const [op1, op2] = pick([[0, 0], [0, 2], [0, 4], [0, 6], [0, 3], [0, 5], [2, 1], [2, 3], [3, 1], [3, 3], [3, 5], [4, 3], [6, 1], [6, 3],
            [7, 1], [7, 3], [7, 5]]);
        const rn = op2 === 3 && random() % 2 ? 15 : reg();
        let word = cond() << 28 | 0x6 << 24 | 1 << 23 | op1 << 20 | rn << 16 | reg() << 12 | op2 << 5 | 1 << 4 | reg();
        if(op2 === 3) word |= bits(2) << 10;
        else if(op2 === 1 || op2 === 5) word |= 0xF << 8 | (op1 === 2 || op1 === 6 || op1 === 0 ? 0 : 0xF << 16);
        else word |= bits(5) << 7;
        // (SSAT16, USAT16: the saturation in 19:16, 11:8 1111)
        if(op2 === 1 && (op1 === 2 || op1 === 6)) word = word & ~(0xF << 16) | bits(4) << 16;
        if(op2 === 5 && op1 === 0) word = word & ~(0xF << 8) | 0xF << 8;
        return { word };
    },
    saturate() {
        const unsigned = bits(1);
        return { word: cond() << 28 | 0x6 << 24 | 1 << 23 | (unsigned ? 6 : 2) << 20 | bits(5) << 16 | reg() << 12 | bits(5) << 7 | bits(1) << 6 | 1 << 4 | reg() };
    },
    reverse_clz() {
        if(random() % 4 === 0) return { word: cond() << 28 | 0x016F0F10 | reg() << 12 | reg() };
        const [op1, op2] = pick([[3, 1], [3, 5], [7, 1], [7, 5]]);
        return { word: cond() << 28 | 0x6 << 24 | 1 << 23 | op1 << 20 | 0xF << 16 | reg() << 12 | 0xF << 8 | op2 << 5 | 1 << 4 | reg() };
    },
    bitfield() {
        const kind = pick(["sbfx", "ubfx", "bfi", "bfc"]);
        const lsb = bits(5);
        if(kind === "sbfx" || kind === "ubfx")
        {
            const width = 1 + random() % (32 - lsb);
            return { word: cond() << 28 | (kind === "sbfx" ? 0x07A : 0x07E) << 20 | (width - 1) << 16 | reg() << 12 | lsb << 7 | 0x5 << 4 | reg() };
        }
        const msb = lsb + random() % (32 - lsb);
        return { word: cond() << 28 | 0x07C << 20 | msb << 16 | reg() << 12 | lsb << 7 | 0x1 << 4 | (kind === "bfc" ? 15 : reg()) };
    },
    usad() {
        return { word: cond() << 28 | 0x078 << 20 | reg() << 16 | (random() % 2 ? 15 : reg()) << 12 | reg() << 8 | 0x1 << 4 | reg() };
    },
    saturating_add() {
        return { word: cond() << 28 | 0x01 << 24 | bits(2) << 21 | reg() << 16 | reg() << 12 | 0x05 << 4 | reg() };
    },
    status() {
        const k = random() % 3;
        if(k === 0) return { word: cond() << 28 | 0x010F0000 | reg() << 12 };
        if(k === 1) return { word: cond() << 28 | 0x0120F000 | pick([1, 2, 3]) << 18 | reg() };
        return { word: cond() << 28 | 0x0320F000 | pick([1, 2, 3]) << 18 | bits(12) };
    },
    crc32() {
        return { word: cond() << 28 | 0x01 << 24 | bits(2) % 3 << 21 | reg() << 16 | reg() << 12 | bits(1) << 9 | 0x04 << 4 | reg() };
    },
    load_store() {
        const register = bits(1), p = bits(1), u = bits(1), b = bits(1), w = p ? bits(1) : 0, l = bits(1);
        const rn = reg(), rt = reg(rn);
        let word = cond() << 28 | 1 << 26 | register << 25 | p << 24 | u << 23 | b << 22 | w << 21 | l << 20 | rn << 16 | rt << 12;
        let small = 0;
        if(register)
        {
            const rm = reg(rn, rt);
            word |= bits(2) << 7 | pick([0, 1]) << 5 | rm;
            small |= 1 << rm;
        }
        else word |= bits(8);
        return { word, pointers: 1 << rn, small, offset: 0x100 * (random() % 2) | 0x100 };
    },
    extra_load_store() {
        const op2 = pick([1, 2, 3]), p = bits(1), u = bits(1), imm = bits(1), w = p ? bits(1) : 0;
        let l = bits(1);
        const dual = op2 >= 2 && !l;
        const rn = reg();
        let rt = reg(rn);
        if(dual) { rt = rt & ~1; if(rt === 12 || rt === rn || rt + 1 === rn) rt = (rn + 2) & ~1 % 12; if(rt === rn || rt + 1 === rn || rt >= 12) rt = rn < 6 ? 8 : 2; }
        let word = cond() << 28 | p << 24 | u << 23 | imm << 22 | w << 21 | l << 20 | rn << 16 | rt << 12 | 1 << 7 | op2 << 5 | 1 << 4;
        let small = 0;
        if(imm) word |= bits(4) << 8 | bits(4);
        else { const rm = reg(rn, rt, rt + 1); word |= rm; small |= 1 << rm; }
        return { word, pointers: 1 << rn, small, offset: 0x100 };
    },
    block() {
        const p = bits(1), u = bits(1), w = bits(1), l = bits(1);
        const rn = reg();
        let list = bits(15) & ~(1 << 13);
        if(w || l) list &= ~(1 << rn);
        if(!list) list = 1 << reg(rn);
        return { word: cond() << 28 | 0x4 << 25 | p << 24 | u << 23 | w << 21 | l << 20 | rn << 16 | list, pointers: 1 << rn, offset: 0x80 };
    },
    exclusive() {
        const size = bits(2), l = bits(1), kind = pick([3, 2, 0]);
        const rn = reg();
        let rt = reg(rn);
        if(size === 1) rt = rt & ~1 === rn || (rt & ~1) + 1 === rn ? (rn < 6 ? 8 : 2) : rt & ~1;
        if(size === 1 && rt >= 12) rt = rn < 6 ? 8 : 2;
        const status = kind === 0 ? 15 : l ? 15 : reg(rn, rt, rt + 1);
        const word = cond() << 28 | 0x1 << 24 | 1 << 23 | size << 21 | l << 20 | rn << 16 | (l ? rt : status) << 12 | 0x3 << 10 | kind << 8 | 0x9 << 4 |
            (l ? 15 : rt);
        return { word: kind === 0 && !l ? word | 0xF << 12 : word, pointers: 1 << rn, offset: 0 };
    },
    cp15() {
        const k = random() % 4;
        if(k === 0) return { word: cond() << 28 | 0x0E1D0F50 | 1 << 20 | reg() << 12 };            // MRC TPIDRURW
        if(k === 1) return { word: cond() << 28 | 0x0E0D0F50 | reg() << 12 };                    // MCR TPIDRURW
        if(k === 2) return { word: cond() << 28 | 0x0E1D0F70 | reg() << 12 };                    // MRC TPIDRURO
        return { word: cond() << 28 | 0x0E070FBA | (random() % 2 ? 0x10 : 0) | reg() << 12 };    // MCR CP15DMB, CP15DSB
    },
};

// T32: 16-bit instructions are their halfword, 32-bit ones first << 16 | second
const lo = (...not) => { for(;;) { const r = random() % 8; if(!not.includes(r)) return r; } };
/** a T32 register 0-14 but SP */
const treg = (...not) => reg(...not);
/** T32's data processing op (bits 8:5 of the first halfword) */
const T32_OPS = [0, 1, 2, 3, 4, 8, 10, 11, 13, 14];
const T32 = {
    t16_shift_add_mov() { return { word: bits(14) }; },
    t16_data_processing() { return { word: 0x4000 | bits(10) }; },
    t16_special() {
        const op = pick([0, 1, 2]);
        let rdn = treg(), rm = treg();
        if(op === 1 && rdn < 8 && rm < 8) rdn = 8 + random() % 5;
        return { word: 0x4400 | op << 8 | (rdn & 8) << 4 | rm << 3 | rdn & 7 };
    },
    t16_load_store() {
        const k = random() % 4;
        if(k === 0)
        {
            const rn = lo(), rm = lo(rn), rt = lo(rn);
            return { word: 0x5000 | bits(3) << 9 | rm << 6 | rn << 3 | rt, pointers: 1 << rn, small: 1 << rm, offset: 0x100 };
        }
        if(k === 1 || k === 2)
        {
            const rn = lo(), rt = lo();
            const top = pick([0x6000, 0x7000, 0x8000]);
            return { word: top | bits(1) << 11 | bits(5) << 6 | rn << 3 | rt, pointers: 1 << rn, offset: 0 };
        }
        return { word: 0x9000 | bits(1) << 11 | lo() << 8 | bits(6), pointers: 1 << 13, offset: 0 };
    },
    t16_misc() {
        const k = random() % 6;
        if(k === 0) return { word: 0xB000 | bits(8) };
        if(k === 1) return { word: 0xB200 | bits(6) };
        if(k === 2) return { word: 0xBA00 | pick([0, 1, 3]) << 6 | bits(6) };
        if(k === 3) return { word: 0xA000 | bits(11) };
        if(k === 4) return { word: 0xB400 | bits(9) | 1, pointers: 1 << 13, offset: 0x80 };
        return { word: 0xBC00 | (bits(8) | 1), pointers: 1 << 13, offset: 0 };
    },
    t16_ldm_stm() {
        const rn = lo();
        let list = bits(8) & ~(1 << rn) | 1 << lo(rn);
        if(random() % 4 === 0) list |= 1 << rn;
        const l = bits(1);
        // (STM with the base in the list: only as the lowest register)
        if(!l && list & 1 << rn && list & ((1 << rn) - 1)) list &= ~(1 << rn);
        return { word: 0xC000 | l << 11 | rn << 8 | list, pointers: 1 << rn, offset: 0 };
    },
    t32_modified_immediate() {
        const op = pick(T32_OPS), s = bits(1);
        let rn = treg(), rd = treg();
        let sbit = s;
        if(random() % 5 === 0 && (op === 0 || op === 4 || op === 8 || op === 13)) { rd = 15; sbit = 1; }
        if(random() % 5 === 0 && (op === 2 || op === 3)) rn = 15;
        return { word: (0xF000 | bits(1) << 10 | op << 5 | sbit << 4 | rn) << 16 | bits(3) << 12 | rd << 8 | bits(8) };
    },
    t32_shifted_register() {
        const op = pick([...T32_OPS, 6]), s = op === 6 ? 0 : bits(1);
        let rn = treg(), rd = treg();
        let sbit = s;
        if(random() % 5 === 0 && (op === 0 || op === 4 || op === 8 || op === 13)) { rd = 15; sbit = 1; }
        if(random() % 5 === 0 && (op === 2 || op === 3)) rn = 15;
        const type = op === 6 ? bits(1) << 1 : bits(2);
        return { word: (0xEA00 | op << 5 | sbit << 4 | rn) << 16 | bits(3) << 12 | rd << 8 | bits(2) << 6 | type << 4 | treg() };
    },
    t32_plain_immediate() {
        const k = random() % 6;
        const rd = treg(), rn = treg();
        if(k === 0) return { word: (0xF200 | bits(1) << 10 | pick([0, 0xA]) << 4 | (random() % 4 ? rn : 15)) << 16 | bits(3) << 12 | rd << 8 | bits(8) };
        if(k === 1) return { word: (0xF240 | bits(1) << 10 | pick([0, 8]) << 4 | bits(4)) << 16 | bits(3) << 12 | rd << 8 | bits(8) };
        if(k === 2)
        {
            const op = pick([0x10, 0x12, 0x18, 0x1A]);
            const sixteen = random() % 3 === 0;
            const h1 = 0xF300 | (op & 0xF) << 4 | (sixteen ? 0x20 : bits(1) << 5) | rn;
            if(sixteen) return { word: (0xF300 | (op | 2) << 4 & 0xF0 | 0x20 | rn) << 16 | rd << 8 | bits(4) };
            const imm = bits(5);
            return { word: h1 << 16 | (imm >> 2) << 12 | rd << 8 | (imm & 3) << 6 | (imm === 0 && h1 & 0x20 ? 1 : bits(5)) };
        }
        const lsb = bits(5);
        if(k === 3 || k === 4)
        {
            const width = 1 + random() % (32 - lsb);
            return { word: (0xF340 | (k === 3 ? 0 : 0x80) | rn) << 16 | (lsb >> 2) << 12 | rd << 8 | (lsb & 3) << 6 | width - 1 };
        }
        const msb = lsb + random() % (32 - lsb);
        return { word: (0xF360 | (random() % 3 ? rn : 15)) << 16 | (lsb >> 2) << 12 | rd << 8 | (lsb & 3) << 6 | msb };
    },
    t32_data_register() {
        const k = random() % 6;
        const rd = treg(), rn = treg(), rm = treg();
        if(k === 0) return { word: (0xFA00 | bits(2) << 5 | bits(1) << 4 | rn) << 16 | 0xF000 | rd << 8 | rm };
        if(k === 1) return { word: (0xFA00 | pick([0, 1, 2, 3, 4, 5]) << 4 | (random() % 2 ? rn : 15)) << 16 | 0xF000 | rd << 8 | 0x80 | bits(2) << 4 | rm };
        if(k === 2) return { word: (0xFA80 | pick([1, 2, 6, 5, 0, 4]) << 4 | rn) << 16 | 0xF000 | rd << 8 | pick([0, 1, 2, 4, 5, 6]) << 4 | rm };
        if(k === 3) return { word: (0xFA80 | rn) << 16 | 0xF000 | rd << 8 | 0x80 | bits(2) << 4 | rm };
        if(k === 4)
        {
            const [op1, op2] = pick([[1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [3, 0]]);
            const n = op1 === 2 ? rn : rm;
            return { word: (0xFA80 | (8 | op1) << 4 | n) << 16 | 0xF000 | rd << 8 | (8 | op2) << 4 | rm };
        }
        return { word: (0xFAC0 | bits(1) << 4 | rn) << 16 | 0xF000 | rd << 8 | 0x80 | (random() % 3) << 4 | rm };
    },
    t32_multiply() {
        const rd = treg(), rn = treg(), rm = treg();
        if(random() % 2)
        {
            const [op1, op2s] = pick([[0, [0, 1]], [1, [0, 1, 2, 3]], [2, [0, 1]], [3, [0, 1]], [4, [0, 1]], [5, [0, 1]], [6, [0, 1]], [7, [0]]]);
            const op2 = pick(op2s);
            const ra = op1 === 6 || op1 === 0 && op2 === 1 ? treg() : random() % 3 ? treg() : 15;
            return { word: (0xFB00 | op1 << 4 | rn) << 16 | ra << 12 | rd << 8 | op2 << 4 | rm };
        }
        const [op1, op2] = pick([[0, 0], [1, 15], [2, 0], [3, 15], [4, 0], [4, 8], [4, 9], [4, 10], [4, 11], [4, 12], [4, 13], [5, 12], [5, 13], [6, 0], [6, 6]]);
        const lo_ = op2 === 15 ? 15 : treg(rd);
        return { word: (0xFB80 | op1 << 4 | rn) << 16 | lo_ << 12 | rd << 8 | op2 << 4 | rm };
    },
    t32_load_store() {
        const size = random() % 3, signed = size < 2 ? bits(1) : 0, l = signed ? 1 : bits(1);
        const rn = treg(), rt = treg(rn);
        const h1 = 0xF800 | signed << 8 | size << 5 | l << 4;
        const k = random() % 4;
        if(k === 0) return { word: (h1 | 0x80 | rn) << 16 | rt << 12 | bits(8), pointers: 1 << rn, offset: 0 };
        if(k === 1)
        {
            const p = bits(1), w = p ? bits(1) : 1;
            return { word: (h1 | rn) << 16 | rt << 12 | 0x800 | p << 10 | bits(1) << 9 | w << 8 | bits(8), pointers: 1 << rn, offset: 0x100 };
        }
        if(k === 2)
        {
            const rm = treg(rn, rt);
            return { word: (h1 | rn) << 16 | rt << 12 | bits(2) << 4 | rm, pointers: 1 << rn, small: 1 << rm, offset: 0 };
        }
        return { word: (h1 | rn) << 16 | rt << 12 | 0xE00 | bits(8), pointers: 1 << rn, offset: 0 };
    },
    t32_ldm_stm() {
        const rn = treg(), l = bits(1), w = bits(1);
        let list = bits(13) & ~(1 << rn);
        if(list.toString(2).replace(/0/g, "").length < 2) list |= 1 << treg(rn) | 1 << treg(rn);
        list &= ~(1 << rn) & ~(1 << 13);
        if(list.toString(2).replace(/0/g, "").length < 2) list = (rn === 0 ? 6 : 1 | 1 << (rn === 1 ? 2 : 1));
        return { word: (0xE800 | pick([1, 2]) << 7 | w << 5 | l << 4 | rn) << 16 | list, pointers: 1 << rn, offset: 0x80 };
    },
    t32_ldrd_strd() {
        const rn = treg(), l = bits(1);
        const rt = treg(rn), rt2 = treg(rn, rt);
        const p = bits(1), w = p ? bits(1) : 1;
        return { word: (0xE840 | p << 8 | bits(1) << 7 | w << 5 | l << 4 | rn) << 16 | rt << 12 | rt2 << 8 | bits(6) & ~3, pointers: 1 << rn, offset: 0x100 };
    },
    t32_exclusive() {
        const rn = treg(), l = bits(1), rt = treg(rn);
        const k = random() % 3;
        if(k === 0)
        {
            const rd = l ? 15 : treg(rn, rt);
            return { word: (0xE840 | l << 4 | rn) << 16 | rt << 12 | rd << 8 | bits(2), pointers: 1 << rn, offset: 0 };
        }
        if(k === 1)
        {
            const op = pick([4, 5, 7]);
            const rt2 = op === 7 ? treg(rn, rt) : 15;
            const rd = l ? 15 : treg(rn, rt, rt2);
            return { word: (0xE8C0 | l << 4 | rn) << 16 | rt << 12 | rt2 << 8 | op << 4 | rd, pointers: 1 << rn, offset: 0 };
        }
        const op = pick([8, 9, 10, 12, 13, 14, 15]);
        const rt2 = op === 15 ? treg(rn, rt) : 15;
        const rd = l || op < 12 ? 15 : treg(rn, rt, rt2);
        return { word: (0xE8C0 | l << 4 | rn) << 16 | rt << 12 | rt2 << 8 | op << 4 | rd, pointers: 1 << rn, offset: 0 };
    },
    // (one instruction in an IT block: the 16-bit ones do not set the flags there)
    t16_in_it() {
        const c = random() % 14, first = c;
        // (IT <cond> with one instruction: mask 1000)
        const it = 0xBF00 | first << 4 | 0x8;
        let word;
        do word = random() % 2 ? bits(14) : 0x4000 | bits(10); while(word >> 11 === 0 && (word >> 6 & 31) === 0);
        return { word, prefix: it };
    },
    t32_in_it() {
        const c = random() % 14;
        const inner = pick([T32.t32_modified_immediate, T32.t32_shifted_register, T32.t32_data_register, T32.t32_multiply])();
        return { ...inner, prefix: 0xBF00 | c << 4 | 0x8 };
    },
    t32_status() {
        if(random() % 2) return { word: 0xF3EF8000 | treg() << 8 };
        return { word: (0xF380 | treg()) << 16 | 0x8000 | pick([1, 2, 3]) << 10 };
    },
};

// VFP (Q4.1): A32 encodings (`c` the condition); T32's are the same with
// the condition 1110, the unconditional ones the same. A floating-point
// case (fp) runs with random D0-D31 and FPSCR controls.
const vd = (r, double) => double ? (r & 15) << 12 | (r >> 4) << 22 : (r >> 1) << 12 | (r & 1) << 22;
const vn = (r, double) => double ? (r & 15) << 16 | (r >> 4) << 7 : (r >> 1) << 16 | (r & 1) << 7;
const vm = (r, double) => double ? (r & 15) | (r >> 4) << 5 : (r >> 1) | (r & 1) << 5;
const VFP = {
    vfp_three(c) {
        const double = bits(1);
        // (opc1: bits 23, 21:20; op: bit 6)
        const [opc1, op] = pick([[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1], [3, 0], [3, 1], [8, 0], [9, 0], [9, 1], [10, 0], [10, 1]]);
        return { word: c << 28 | 0xE << 24 | (opc1 & 8) << 20 | (opc1 & 3) << 20 | 0xA << 8 | double << 8 | op << 6 |
            vd(bits(5), double) | vn(bits(5), double) | vm(bits(5), double) };
    },
    vfp_two(c) {
        const double = bits(1);
        const base = c << 28 | 0x0EB00A40 | double << 8;
        const k = random() % 6;
        // VMOV (immediate)
        if(k === 0) return { word: c << 28 | 0x0EB00A00 | double << 8 | vd(bits(5), double) | bits(4) << 16 | bits(4) };
        // VMOV, VABS, VNEG, VSQRT
        if(k === 1) return { word: base | bits(1) << 16 | bits(1) << 7 | vd(bits(5), double) | vm(bits(5), double) };
        // VCMP, VCMPE (with zero: Vm 0)
        if(k === 2)
        {
            const zero = bits(1);
            return { word: base | (4 | zero) << 16 | bits(1) << 7 | vd(bits(5), double) | (zero ? 0 : vm(bits(5), double)) };
        }
        // VRINTR, VRINTZ, VRINTX
        if(k === 3)
        {
            const [opc2, b7] = pick([[6, 0], [6, 1], [7, 0]]);
            return { word: base | opc2 << 16 | b7 << 7 | vd(bits(5), double) | vm(bits(5), double) };
        }
        // VCVTB, VCVTT from half precision, to half precision
        if(k === 4)
        {
            const to = bits(1);
            return { word: base | (2 | to) << 16 | bits(1) << 7 | vd(bits(5), double && !to) | vm(bits(5), double && to) };
        }
        // VCVT between single and double
        return { word: base | 7 << 16 | 1 << 7 | vd(bits(5), !double) | vm(bits(5), double) };
    },
    vfp_convert(c) {
        const double = bits(1);
        const base = c << 28 | 0x0EB00A40 | double << 8;
        const k = random() % 3;
        // VCVT from a 32-bit integer (bit 7: signed)
        if(k === 0) return { word: base | 8 << 16 | bits(1) << 7 | vd(bits(5), double) | vm(bits(5), false) };
        // VCVT, VCVTR to one (bit 16: signed; bit 7: toward zero)
        if(k === 1) return { word: base | (12 | bits(1)) << 16 | bits(1) << 7 | vd(bits(5), false) | vm(bits(5), double) };
        // VCVT between floating and fixed point (bit 18: to fixed, 16: unsigned, 7: 32 bits)
        // (the fraction bits, size - imm4:i, at least 0: imm up to 16 for 16 bits)
        const sx = bits(1);
        const imm = random() % (sx ? 32 : 17);
        return { word: base | (10 | bits(1) << 2 | bits(1)) << 16 | sx << 7 | vd(bits(5), double) | (imm >> 1) | (imm & 1) << 5 };
    },
    vfp_transfer(c) {
        const k = random() % 6, rt = reg(), l = bits(1);
        // VMOV between a core register and S
        if(k === 0) return { word: c << 28 | 0x0E000A10 | l << 20 | vn(bits(5), false) | rt << 12 };
        // VMRS (to APSR_nzcv too), VMSR (Len and Stride clear)
        if(k === 1)
        {
            if(l) return { word: c << 28 | 0x0EF10A10 | (random() % 3 ? rt : 15) << 12 };
            return { word: c << 28 | 0x0EE10A10 | rt << 12, small: 1 << (16 + rt) };
        }
        // VMOV between core registers and two S or a D
        if(k === 2)
        {
            const double = bits(1), rt2 = reg(l ? rt : 99);
            return { word: c << 28 | 0x0C400A10 | l << 20 | rt2 << 16 | rt << 12 | double << 8 | vm(double ? bits(5) : random() % 31, double) };
        }
        // VDUP (core): bytes, halfwords or words, D or Q
        if(k === 3)
        {
            const [b, e] = pick([[0, 0], [0, 1], [1, 0]]), q = bits(1);
            return { word: c << 28 | 0x0E800B10 | b << 22 | q << 21 | vn(bits(5) & ~q, true) | rt << 12 | e << 5 };
        }
        // VMOV (scalar to core, core to scalar): a byte, halfword or word
        const size = random() % 3, u = l && size < 2 ? bits(1) : 0;
        const index = size === 0 ? bits(3) : size === 1 ? bits(2) : bits(1);
        const fields = size === 0 ? 1 << 22 | (index >> 2) << 21 | (index & 3) << 5 : size === 1 ? (index >> 1) << 21 | (index & 1) << 6 | 1 << 5 : index << 21;
        return { word: c << 28 | 0x0E000B10 | u << 23 | fields | l << 20 | vn(bits(5), true) | rt << 12 };
    },
    vfp_load_store(c) {
        const double = bits(1), l = bits(1), rn = reg();
        // (an unaligned base now and then)
        const offset = random() % 8 === 0 ? 0x102 : 0x100;
        if(random() % 2)
        {
            // VLDR, VSTR (A32's literal VLDR: the code's words)
            const literal = l && c !== 15 && random() % 6 === 0;
            return { word: c << 28 | 0x0D000A00 | bits(1) << 23 | l << 20 | (literal ? 15 : rn) << 16 | vd(bits(5), double) | double << 8 | bits(8),
                pointers: literal ? 0 : 1 << rn, offset, literal };
        }
        // VLDM, VSTM: IA, IA!, DB!; FLDMX, FSTMX: an odd count
        const [p, u, w] = pick([[0, 1, 0], [0, 1, 1], [1, 0, 1]]);
        const d = bits(5), regs = 1 + random() % Math.min(double ? 16 : 32, 32 - d);
        const imm8 = double ? regs * 2 + (random() % 4 === 0 ? 1 : 0) : regs;
        return { word: c << 28 | 0x0C000A00 | p << 24 | u << 23 | w << 21 | l << 20 | rn << 16 | vd(d, double) | double << 8 | imm8,
            pointers: 1 << rn, offset };
    },
    vfp_unconditional() {
        const double = bits(1), k = random() % 4;
        // VSEL
        if(k === 0) return { word: 0xFE000A00 | bits(2) << 20 | double << 8 | vd(bits(5), double) | vn(bits(5), double) | vm(bits(5), double) };
        // VMAXNM, VMINNM
        if(k === 1) return { word: 0xFE800A00 | bits(1) << 6 | double << 8 | vd(bits(5), double) | vn(bits(5), double) | vm(bits(5), double) };
        // VRINTA, VRINTN, VRINTP, VRINTM
        if(k === 2) return { word: 0xFEB80A40 | bits(2) << 16 | double << 8 | vd(bits(5), double) | vm(bits(5), double) };
        // VCVTA, VCVTN, VCVTP, VCVTM (bit 7 signed)
        return { word: 0xFEBC0A40 | bits(2) << 16 | bits(1) << 7 | double << 8 | vd(bits(5), false) | vm(bits(5), double) };
    },
};
// (random encodings of the data processing and transfer spaces, the
// UNDEFINED ones among them; without what is UNPREDICTABLE: the PC or SP
// as a core register, VMOV of S31 and S32, a 16-bit VCVT with fewer than
// zero fraction bits; no loads or stores at random addresses)
VFP.vfp_random = c => {
    for(;;)
    {
        const unconditional = random() % 4 === 0;
        let word = (unconditional ? 0xFE000000 : c << 28 | pick([0x0C, 0x0E]) << 24) | bits(24) & ~(7 << 9) | 5 << 9;
        if((word >> 24 & 15) === 0xC) word = word & ~(7 << 21) | 2 << 21;
        const rt = word >> 12 & 15, rt2 = word >> 16 & 15, l = word >> 20 & 1, double = word >> 8 & 1;
        if(rt === 13 || rt === 15) continue;
        if((word >> 24 & 15) === 0xC && (rt2 === 13 || rt2 === 15 || l && rt === rt2 || !double && (word & 15) === 15 && word & 1 << 5)) continue;
        const opc2 = word >> 16 & 15;
        if(!unconditional && (word >> 24 & 15) === 0xE && !(word & 1 << 4) && (word >> 20 & 0xB) === 0xB && word & 1 << 6 &&
            [10, 11, 14, 15].includes(opc2) && !(word & 1 << 7) && ((word & 15) << 1 | word >> 5 & 1) > 16) continue;
        const vmsr = (word >> 24 & 15) === 0xE && word & 1 << 4 && !double && (word >> 21 & 7) === 7 && !l;
        return { word, small: vmsr ? 1 << (16 + rt) : 0 };
    }
};
for(const [name, make] of Object.entries(VFP))
{
    A32[name] = () => ({ ...make(cond()), fp: true });
    // (T32: the condition 1110; in an IT block now and then)
    T32["t32_" + name] = () => {
        const c = make(14);
        const unconditional = c.word >>> 28 === 15;
        const it = !unconditional && random() % 4 === 0 ? 0xBF00 | (random() % 14) << 4 | 0x8 : undefined;
        if(c.literal)
        {
            c.word = c.word & ~(15 << 16) | reg() << 16;
            c.pointers = 1 << (c.word >>> 16 & 15);
        }
        return { ...c, word: unconditional ? c.word >>> 0 : (c.word & 0x0FFFFFFF | 0xE0000000) >>> 0, prefix: it, fp: true };
    };
}

// Advanced SIMD (Q4.2, Q4.3): A32 encodings, random within each group of
// QEMU's neon-dp.decode (so the UNDEFINED ones are there too); a Q form
// names even registers nine times in ten. T32's: 111U 1111 for data
// processing, 1111 1001 for the loads and stores.
const dreg = q => q && random() % 10 ? bits(5) & ~1 : bits(5);
const NEON = {
    neon_three_same() {
        const q = bits(1);
        // (the floating point opcodes, 1100-1111, a third of the time)
        const opc = random() % 3 ? bits(4) : 12 + bits(2);
        return { word: 0xF2000000 | bits(1) << 24 | bits(2) << 20 | vd(dreg(q), true) | vn(dreg(q), true) | opc << 8 | q << 6 |
            vm(dreg(q), true) | bits(1) << 4 };
    },
    neon_three_different() {
        return { word: 0xF2800000 | bits(1) << 24 | random() % 3 << 20 | vd(dreg(1), true) | vn(dreg(random() % 2), true) | bits(4) << 8 |
            vm(dreg(random() % 2), true) };
    },
    neon_two_scalar() {
        const q = bits(1);
        return { word: 0xF2800040 | q << 24 | random() % 3 << 20 | vd(dreg(q), true) | vn(dreg(q), true) | bits(4) << 8 | bits(5) };
    },
    neon_shift() {
        const q = bits(1), l = bits(1);
        // (L:imm6 at least 8: below, the modified immediates)
        const imm6 = l ? bits(6) : 8 + random() % 56;
        return { word: 0xF2800010 | bits(1) << 24 | imm6 << 16 | vd(dreg(q), true) | bits(4) << 8 | l << 7 | q << 6 | vm(dreg(q), true) };
    },
    neon_immediate() {
        const q = bits(1);
        return { word: 0xF2800010 | bits(1) << 24 | bits(3) << 16 | vd(dreg(q), true) | bits(4) << 8 | q << 6 | bits(1) << 5 | bits(4) };
    },
    neon_misc() {
        const q = bits(1), k = random() % 6;
        // VEXT
        if(k === 0) return { word: 0xF2B00000 | vd(dreg(q), true) | vn(dreg(q), true) | (q ? bits(4) : bits(3)) << 8 | q << 6 | vm(dreg(q), true) };
        // VTBL, VTBX
        if(k === 1) return { word: 0xF3B00800 | vd(bits(5), true) | vn(random() % 29, true) | bits(2) << 8 | bits(1) << 6 | vm(bits(5), true) };
        // VDUP (scalar)
        if(k === 2) return { word: 0xF3B00C00 | bits(4) << 16 | vd(dreg(q), true) | q << 6 | vm(bits(5), true) };
        // two registers, miscellaneous (VTRN, VUZP, VZIP of a register with itself: UNPREDICTABLE)
        const opc1 = bits(2), opc2 = bits(4), d = dreg(q);
        let m = dreg(q);
        while(opc1 === 2 && opc2 >= 1 && opc2 <= 3 && m === d) m = dreg(q);
        return { word: 0xF3B00000 | bits(2) << 18 | opc1 << 16 | vd(d, true) | opc2 << 7 | q << 6 | vm(m, true) };
    },
    neon_load_store() {
        const rn = reg(), l = bits(1);
        const small = reg(rn);
        const rm = pick([15, 13, small]);
        const k = random() % 3;
        let word, span;
        // multiple structures: a type, a size, an alignment
        if(k === 0)
        {
            const type = random() % 11;
            const [registers, interleave, spacing] = [[1, 4, 1], [1, 4, 2], [4, 1, 1], [2, 2, 2], [1, 3, 1], [1, 3, 2], [3, 1, 1], [1, 1, 1],
                [1, 2, 1], [1, 2, 2], [2, 1, 1]][type];
            span = registers - 1 + spacing * (interleave - 1);
            word = 0xF4000000 | l << 21 | rn << 16 | type << 8 | bits(2) << 6 | bits(2) << 4 | rm;
        }
        // one lane: the register stride in bit 5 (halfwords), 6 (words)
        else if(k === 1)
        {
            const size = random() % 3, n = bits(2), index_align = bits(4);
            const stride = size === 1 && index_align & 2 || size === 2 && index_align & 4 ? 2 : 1;
            span = stride * n;
            word = 0xF4800000 | l << 21 | rn << 16 | size << 10 | n << 8 | index_align << 4 | rm;
        }
        // all lanes (T: two registers for VLD1, else the stride)
        else
        {
            const n = bits(2), t = bits(1);
            span = n === 0 ? t : (t + 1) * n;
            word = 0xF4A00C00 | rn << 16 | n << 8 | bits(2) << 6 | t << 5 | bits(1) << 4 | rm;
        }
        // (no register past D31: UNPREDICTABLE)
        word |= vd(random() % (32 - span), true);
        // (the buffer's 4096-aligned middle: the MMU is off, Device memory
        // faults an unaligned access, and QEMU makes VLD1's elements one
        // access per register)
        return { word, pointers: 1 << rn, small: rm === small ? 1 << small : 0, offset: 0 };
    },
    neon_crypto() {
        const even = () => bits(5) & ~1;
        const k = random() % 4;
        // SHA1C, SHA1P, SHA1M, SHA1SU0, SHA256H, SHA256H2, SHA256SU1
        if(k === 0)
        {
            const [u, size] = pick([[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2]]);
            return { word: 0xF2000C40 | u << 24 | size << 20 | vd(even(), true) | vn(even(), true) | vm(even(), true) };
        }
        // AESE, AESD, AESMC, AESIMC
        if(k === 1) return { word: 0xF3B00300 | pick([0x00, 0x40, 0x80, 0xC0]) | vd(even(), true) | vm(even(), true) };
        // SHA1H, SHA1SU1, SHA256SU0
        if(k === 2) return { word: pick([0xF3B902C0, 0xF3BA0380, 0xF3BA03C0]) | vd(even(), true) | vm(even(), true) };
        // VMULL.P64, VMULL.P8
        return { word: 0xF2800E00 | pick([0, 2]) << 20 | vd(even(), true) | vn(bits(5), true) | vm(bits(5), true) };
    },
};
for(const [name, make] of Object.entries(NEON))
{
    A32[name] = () => ({ ...make(), fp: true });
    T32["t32_" + name] = () => {
        const c = make();
        const t32 = name === "neon_load_store" ? c.word & 0x00FFFFFF | 0xF9000000 : c.word & 0x00FFFFFF | 0xEF000000 | (c.word >>> 24 & 1) << 28;
        return { ...c, word: t32 >>> 0, fp: true };
    };
}

const sets = (process.env.A64_AARCH32_SET || "a32,t32").split(",");
const only = process.env.A64_AARCH32_ONLY ? process.env.A64_AARCH32_ONLY.split(",") : null;
const count = +process.env.A64_AARCH32_COUNT || 40;
const cases = [];
for(const [set, classes] of [["a32", A32], ["t32", T32]])
{
    if(!sets.includes(set)) continue;
    for(const [name, make] of Object.entries(classes))
    {
        if(only && !only.includes(name)) continue;
        for(let i = 0; i < count; i++)
        {
            const c = make();
            // (a floating-point case: bit 0, FPSCR's RMode, FZ, DN half the time, AHP a quarter)
            const fp = c.fp ? 1 | bits(2) << 22 | bits(1) << 24 | bits(1) << 25 | (random() % 4 === 0) << 26 : 0;
            cases.push({ set, name, word: c.word >>> 0, prefix: c.prefix, pointers: c.pointers || 0, small: c.small || 0, offset: c.offset || 0,
                psr: ((random() & 0xF80F0000) | fp) >>> 0, seed: random() });
        }
    }
}
assert.ok(cases.length, "no cases");

// the binary: the table, then each case's code (the instruction, SVC #0) in 8 bytes
const lines = ["// Generated by tests/a64/aarch32_oracle.mjs; do not edit.", "    .syntax unified", "    .arm", "base:", `    .word ${cases.length}`];
const code = [];
cases.forEach((c, i) => {
    const at = `code_${i} - base`;
    const thumb = c.set === "t32";
    const wide = thumb && c.word > 0xFFFF;
    const delta = thumb ? (wide ? 6 : 4) + (c.prefix ? 2 : 0) : 8;
    const prefix = c.prefix ? `0x${c.prefix.toString(16)}, ` : "";
    lines.push(`    .word ${at}${thumb ? " + 1" : ""}, 0x${c.psr.toString(16)}, 0x${c.pointers.toString(16)}, 0x${c.small.toString(16)}, 0x${c.seed.toString(16)}, ` +
        `0x${(delta << 16 | c.offset).toString(16)}`);
    if(thumb)
    {
        code.push(`    .balign 8`, `code_${i}:`, wide ? `    .hword ${prefix}0x${(c.word >>> 16).toString(16)}, 0x${(c.word & 0xFFFF).toString(16)}, 0xdf00` :
            `    .hword ${prefix}0x${c.word.toString(16)}, 0xdf00`);
    }
    else code.push(`    .balign 8`, `code_${i}:`, `    .word 0x${c.word.toString(16)}, 0xef000000`);
});
const source = root + "build/a64-aarch32-oracle-cases/oracle.a32.S";
fs.mkdirSync(root + "build/a64-aarch32-oracle-cases", { recursive: true });
fs.writeFileSync(source, lines.join("\n") + "\n" + code.join("\n") + "\n");

const directory = build("aarch32-oracle", [root + "tests/a64/aarch32/oracle.c", root + "tests/a64/aarch32/el0_run.S", source]);
const expected = await reference(directory, { timeout: 120000 });
assert.equal(expected.status, "ok", "QEMU: " + expected.status + "\n" + expected.text.slice(-2000));
const got = await actual(directory, { options: { cpu_profile: "generic-arm64-compat32" }, timeout: 120000 });
const a = expected.text.split("\n"), b = got.text.split("\n");
const differences = [];
for(let i = 0; i < cases.length; i++)
{
    if(a[i] !== b[i]) differences.push(i);
}
const by_class = {};
for(const i of differences) (by_class[cases[i].set + ":" + cases[i].name] = by_class[cases[i].set + ":" + cases[i].name] || []).push(i);
for(const [name, list] of Object.entries(by_class))
{
    console.log(`${name}: ${list.length} differences`);
    for(const i of list.slice(0, 3))
    {
        console.log(`  ${cases[i].set} ${cases[i].word.toString(16).padStart(8, "0")} psr ${cases[i].psr.toString(16)}\n    QEMU: ${a[i]}\n    v86:  ${b[i]}`);
    }
}
assert.equal(got.status, "ok", "v86: " + got.status + "\n" + got.text.slice(-500));
const classes = new Set(cases.map(c => c.set + ":" + c.name)).size;
assert.equal(differences.length, 0, `${differences.length} of ${cases.length} cases differ`);
console.log(`aarch32 oracle: ${cases.length} cases (${classes} classes, seed ${process.env.A64_AARCH32_SEED || 1}), 0 differences`);
                                                                                                                                                                                 source/v64/tests/a64/aarch32_page.mjs                                                               0000755 0000000 0000000 00000004112 00000000000 014353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AArch32's page functions against the interpreter (docs/aarch32-plan.md
// Q6): the AArch32 EL0 cases (tests/a64/aarch32/*.a32.S: branches and
// interworking, IT blocks and an exception inside one, VFP and Advanced
// SIMD traps) on v86 with the MMU on, interpreted and with the page tier
// (a64_page_aarch32, compiling at the first boundary); the outputs must be
// the same. A64_AARCH32_CASES: the case files (default q1,q3,q4);
// A64_AARCH32_PAGE: the switch's value (1; 2 helper calls only, 3 native
// branches only).
import assert from "node:assert/strict";
import { build, actual, root } from "./guest_runner.mjs";

process.env.A64_MMU = "1";
let failures = 0;
for(const cases of (process.env.A64_AARCH32_CASES || "q1,q3,q4").split(","))
{
    const directory = build("aarch32-page-" + cases, [root + "tests/a64/aarch32/el0.c", root + "tests/a64/aarch32/el0_run.S",
        root + `tests/a64/aarch32/${cases}.a32.S`], { cflags: [`-DCASES=${cases}_a32`, "-DA64_MMU"] });
    delete process.env.A64_JIT;
    const interpreted = await actual(directory, { options: { cpu_profile: "generic-arm64-compat32" } });
    process.env.A64_JIT = "1";
    process.env.A64_JIT_HOT = "1";
    process.env.A64_JIT_SWITCHES = "a64_page_aarch32=" + (process.env.A64_AARCH32_PAGE || "1");
    const compiled = await actual(directory, { options: { cpu_profile: "generic-arm64-compat32" } });
    assert.equal(interpreted.status, "ok", cases + " (interpreter): " + interpreted.status);
    assert.equal(compiled.status, "ok", cases + " (page tier): " + compiled.status);
    const a = interpreted.text.split("\n"), b = compiled.text.split("\n");
    const first = a.findIndex((line, i) => line !== b[i]);
    if(first >= 0 || a.length !== b.length)
    {
        failures++;
        console.log(`${cases}: differs at line ${first + 1}\n  interpreter: ${a[first]}\n  page tier:   ${b[first]}`);
        continue;
    }
    const t = compiled.page_tier;
    console.log(`PASS: ${cases}: the same (page tier: ${t.compiled} compiles, ${t.helpers} helper calls, ${t.steps} steps)`);
}
process.exit(failures ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/a64/aarch32_page_fuzz.mjs                                                          0000755 0000000 0000000 00000047655 00000000000 015454  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AArch32's page functions against the interpreter (docs/aarch32-plan.md
// Q6.2, Q6.3; page_fuzz.mjs's A64 counterpart): random A32 and T32 programs
// of the forms the page tier compiles natively or by helper calls (data
// processing with every shift and condition, MOVW and MOVT, multiplies,
// extends, bit fields, loads and stores in every addressing mode, LDM, STM,
// PUSH and POP, IT blocks, forward branches, counted loops, calls, CBZ and
// CBNZ, VFP and its loads and stores, VLD1 and VST1), run at EL0 (tests/a64/aarch32/fuzz.c) ROUNDS times on their
// registers and a buffer; the buffer, the registers and NZCV at the end
// must be the same interpreted and with the page tier (a64_page_aarch32,
// compiling at the first boundary), bit for bit.
//
//   node tests/a64/aarch32_page_fuzz.mjs [--programs N] [--length N] [--rounds N] [--seed S] [--write DIR]
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const PROGRAMS = +option("--programs", 40);
const LENGTH = +option("--length", 100);
const ROUNDS = +option("--rounds", 32);
const SEED = +option("--seed", 1);

let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
function next64()
{
    state ^= state << 13n & (1n << 64n) - 1n;
    state ^= state >> 7n;
    state ^= state << 17n & (1n << 64n) - 1n;
    return state;
}
const rand = n => Number(next64() % BigInt(n));
const pick = list => list[rand(list.length)];

// the registers programs compute in (r8 holds the buffer, r11 counts loops,
// r12 is addressing scratch)
const REGS = [0, 1, 2, 3, 4, 5, 6, 7, 9, 10];
const LOW = [0, 1, 2, 3, 4, 5, 6, 7];
const r = () => "r" + pick(REGS);
/** k distinct registers of REGS, in order */
const distinct = k => { const all = REGS.slice(); for(let i = all.length - 1; i > 0; i--) { const j = rand(i + 1); [all[i], all[j]] = [all[j], all[i]]; } return all.slice(0, k).sort((a, b) => a - b).map(n => "r" + n); };
const lo = () => "r" + pick(LOW);
const CONDS = ["eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le"];
const SHIFTS = ["lsl", "lsr", "asr", "ror"];
// immediates both instruction sets encode
const IMMS = () => pick([rand(256), rand(256), 0xFF000000, 0x3FC00, 0x80000000, 0xF0000000, 0]);
const shift = () => { const kind = pick(SHIFTS); return rand(3) ? "" : rand(8) === 0 ? ", rrx" : `, ${kind} #${kind === "lsl" || kind === "ror" ? 1 + rand(31) : 1 + rand(32)}`; };

let label = 0;
let thumb = false;
/** an instruction's condition suffix: A32's any, T32's only in an IT block (it()) */
const cond = () => !thumb && rand(4) === 0 ? pick(CONDS) : "";

/** An Advanced SIMD data processing instruction (Q6.3 part 3): on D or Q
 * registers its operands from the buffer (VLDR), its result back there
 * (VSTR: both halves of a Q register), sometimes another D register too */
function neon_op()
{
    const q = rand(2) === 1;
    const R = () => q ? rand(16) : rand(32);
    const name = x => (q ? "q" : "d") + x;
    const [d, n, m] = [R(), R(), R()];
    const halves = x => q ? [2 * x, 2 * x + 1] : [x];
    const load = x => halves(x).map(h => `vldr d${h}, [r8, #${8 * rand(128)}]`);
    const store = x => halves(x).map(h => `vstr d${h}, [r8, #${8 * rand(128)}]`);
    const size = pick([8, 16, 32]);
    const shifted = (bits, shifts) => rand(256) * 2 ** pick(shifts) >>> 0;
    let op;
    switch(rand(9))
    {
        case 0: op = `${pick(["vadd", "vsub"])}.i${pick([8, 16, 32, 64])} ${name(d)}, ${name(n)}, ${name(m)}`; break;
        case 1: op = `${pick(["vand", "vbic", "vorr", "vorn", "veor", "vbsl", "vbit", "vbif"])} ${name(d)}, ${name(n)}, ${name(m)}`; break;
        case 2: op = `${pick(["vceq.i", "vtst.", "vcgt.s", "vcgt.u", "vcge.s", "vcge.u", "vmax.s", "vmax.u", "vmin.s", "vmin.u"])}${size} ${name(d)}, ${name(n)}, ${name(m)}`; break;
        case 3: op = `vmul.i${pick([16, 32])} ${name(d)}, ${name(n)}, ${name(m)}`; break;
        case 4: {
            const e = pick([8, 16, 32, 64]);
            op = rand(2) ? `vshl.i${e} ${name(d)}, ${name(m)}, #${rand(e)}` : `vshr.${pick(["s", "u"])}${e} ${name(d)}, ${name(m)}, #${1 + rand(e)}`;
            break;
        }
        case 5: op = pick([`vmov.i8 ${name(d)}, #${rand(256)}`, `vmov.i16 ${name(d)}, #${shifted(16, [0, 8])}`,
            `vmov.i32 ${name(d)}, #${shifted(32, [0, 8, 16, 24])}`, `vmvn.i32 ${name(d)}, #${shifted(32, [0, 8, 16, 24])}`,
            `vorr.i32 ${name(d)}, #${shifted(32, [0, 8, 16, 24])}`, `vbic.i16 ${name(d)}, #${shifted(16, [0, 8])}`,
            `vmov.i64 ${name(d)}, #0xff00ff0000ffff00`, `vmov.f32 ${name(d)}, #${pick(["1.0", "-2.5", "0.125"])}`,
            `vmov.i32 ${name(d)}, #0x${rand(256).toString(16)}ff`]); break;
        case 6: { const e = pick([8, 16, 32]); op = `vdup.${e} ${name(d)}, d${rand(32)}[${rand(64 / e)}]`; break; }
        case 7: op = rand(2) ? `vext.8 ${name(d)}, ${name(n)}, ${name(m)}, #${rand(q ? 16 : 8)}` :
            pick([`vrev64.${pick([8, 16, 32])}`, `vrev32.${pick([8, 16])}`, "vrev16.8"]) + ` ${name(d)}, ${name(m)}`; break;
        default: op = pick(["vmvn", "vcnt.8", `vabs.s${size}`, `vneg.s${size}`]) + ` ${name(d)}, ${name(m)}`; break;
    }
    return [...load(n), ...load(m), ...load(d), op, ...store(d), ...(rand(2) ? [`vstr d${rand(32)}, [r8, #${8 * rand(128)}]`] : [])].join("\n    ");
}

/** One instruction that may run conditionally (in an IT block or with a condition): no branch */
function plain(c = "")
{
    const s = c ? (rand(4) === 0 ? "s" : "") : (rand(3) === 0 ? "s" : "");
    switch(rand(30))
    {
        case 25: case 26: return c ? plain(c) : neon_op();
        case 27: case 28: {
            // transfers (Q6.3 part 4): the thread ID registers, VMRS, VMOV
            // between core registers and scalars, VDUP (core)
            const [a, b] = distinct(2), d = rand(32);
            const lane = e => rand(64 / e);
            switch(rand(5))
            {
                case 0: return `mcr${c} p15, 0, ${a}, c13, c0, 2
    mrc${c} p15, 0, ${b}, c13, c0, ${pick([2, 3])}`;
                case 1: return `vmov${c} s${rand(8)}, ${a}
    vmov${c} s${8 + rand(8)}, ${b}
    vcmp${c}.f32 s${rand(8)}, s${8 + rand(8)}
    ` +
                    (rand(2) ? `vmrs${c} APSR_nzcv, fpscr` : `vmrs${c} ${a}, fpscr`);
                case 2: { const t = pick(["s8", "u8", "s16", "u16", "32"]); return `vldr d${d}, [r8, #${8 * rand(128)}]
    vmov${c}.${t} ${a}, d${d}[${lane(+t.replace(/[su]/, ""))}]`; }
                case 3: { const e = pick([8, 16, 32]); return `vmov${c}.${e} d${d}[${lane(e)}], ${a}
    vmov${c} ${a}, ${b}, d${d}`; }
                default: {
                    const e = pick([8, 16, 32]), q = rand(2) ? rand(16) : -1;
                    return q >= 0 ? `vdup${c}.${e} q${q}, ${a}
    vstr d${2 * q + rand(2)}, [r8, #${8 * rand(128)}]` :
                        `vdup${c}.${e} d${d}, ${a}
    vmov${c} ${a}, ${b}, d${d}`;
                }
            }
        }
        case 0: case 1: return `${pick(["add", "adc", "sub", "sbc", "rsb", "and", "orr", "eor", "bic"])}${s}${c} ${r()}, ${r()}, ${r()}${shift()}`;
        case 2: case 3: return `${pick(["add", "adc", "sub", "sbc", "rsb", "and", "orr", "eor", "bic"])}${s}${c} ${r()}, ${r()}, #${IMMS()}`;
        case 4: return `${pick(["mov", "mvn"])}${s}${c} ${r()}, ${r()}${shift()}`;
        case 5: return `${pick(["mov", "mvn"])}${s}${c} ${r()}, #${IMMS()}`;
        case 6: return `${pick(["cmp", "cmn", "tst", "teq"])}${c} ${r()}, ${rand(2) ? r() + shift() : "#" + IMMS()}`;
        case 7: return `${pick(["lsl", "lsr", "asr", "ror"])}${s}${c} ${r()}, ${r()}, ${rand(2) ? "#" + (1 + rand(31)) : r()}`;
        case 8: return `${rand(2) ? "movw" : "movt"}${c} ${r()}, #${rand(65536)}`;
        case 9: return pick([`mul${c} ${r()}, ${r()}, ${r()}`, `mla${c} ${r()}, ${r()}, ${r()}, ${r()}`, `mls${c} ${r()}, ${r()}, ${r()}, ${r()}`]);
        case 10: { const [low, high] = distinct(2); return `${pick(["umull", "smull", "umlal", "smlal"])}${c} ${low}, ${high}, ${r()}, ${r()}`; }
        case 11: return `${pick(["uxtb", "uxth", "sxtb", "sxth"])}${c} ${r()}, ${r()}${rand(2) ? ", ror #" + pick([8, 16, 24]) : ""}`;
        case 12: return pick([`clz${c} ${r()}, ${r()}`, `rev${c} ${r()}, ${r()}`, `rev16${c} ${r()}, ${r()}`, `rbit${c} ${r()}, ${r()}`, `revsh${c} ${r()}, ${r()}`]);
        case 13: { const lsb = rand(32), width = 1 + rand(32 - lsb); return pick([`ubfx${c} ${r()}, ${r()}, #${lsb}, #${width}`, `sbfx${c} ${r()}, ${r()}, #${lsb}, #${width}`, `bfi${c} ${r()}, ${r()}, #${lsb}, #${width}`, `bfc${c} ${r()}, #${lsb}, #${width}`]); }
        case 14: case 15: {
            // a load or store of the buffer: an immediate offset
            // (A32's halfword and signed forms have 8 bits of offset)
            const [op, align] = pick([["ldr", 4], ["str", 4], ["ldrb", 1], ["strb", 1], ["ldrh", 2], ["strh", 2], ["ldrsb", 1], ["ldrsh", 2]]);
            const most = /h|sb/.test(op) ? 256 : 2048;
            return `${op}${c} ${r()}, [r8, #${align * rand(Math.min(255, most / align))}]`;
        }
        case 16: {
            // a register offset (the index masked into the buffer, as a byte offset of words)
            const [op, k] = pick([["ldr", 2], ["str", 2], ["ldrb", 0], ["strb", 0], ["ldrh", 1], ["strh", 1], ["ldrsh", 1], ["ldrsb", 0]]);
            // (A32 and T32 both shift a word's index by LSL #2)
            return k === 2 && rand(2) ? `and${c} r12, ${r()}, #0xff\n    ${op}${c} ${r()}, [r8, r12, lsl #2]` :
                `and${c} r12, ${r()}, #${k ? "0x3fc" : "0xff"}\n    ${op}${c} ${r()}, [r8, r12]`;
        }
        case 17: {
            // pre- and post-indexed with writeback, through r12
            const [op, a] = pick([["ldr", 4], ["str", 4], ["ldrb", 1], ["strb", 1], ["ldrh", 2], ["strh", 2]]);
            const off = a * (1 + rand(16));
            return `add${c} r12, r8, #${16 * rand(64)}\n    ` + (rand(2) ? `${op}${c} ${r()}, [r12, #${off}]!` : `${op}${c} ${r()}, [r12], #${rand(2) ? off : -off}`);
        }
        case 18: { const t = pick([0, 2, 4, 6]); return `${rand(2) ? "ldrd" : "strd"}${c} r${t}, r${t + 1}, [r8, #${8 * rand(32)}]`; }
        case 19: {
            // (T32's LDM and STM of one register are CONSTRAINED UNPREDICTABLE:
            // v86 transfers it; the assembler makes LDM IA! and STMDB! of one LDR and STR)
            const list = distinct(1 + rand(5)).join(", ");
            return `add${c} r12, r8, #${16 * rand(64)}\n    ${pick(["ldm", "stm", "ldmdb", "stmdb"])}${c} r12${rand(2) ? "!" : ""}, {${list}}`;
        }
        case 20: return `${pick(["qadd", "qsub", "uadd8", "usub16", "sadd16", "uhadd8", "sel"])}${c} ${r()}, ${r()}, ${r()}`;
        case 21: case 22: {
            // VFP's loads and stores (Q6.3): VLDR, VSTR of S and D, observed
            // through core registers; VLDM, VSTM through r12
            const [a, b] = distinct(2), d = rand(32), sr = rand(32);
            switch(rand(5))
            {
                case 0: return `vldr${c} d${d}, [r8, #${4 * rand(256)}]\n    vmov${c} ${a}, ${b}, d${d}`;
                case 1: return `vmov${c} d${d}, ${a}, ${b}\n    vstr${c} d${d}, [r8, #${4 * rand(256)}]`;
                case 2: return `vldr${c} s${sr}, [r8, #${4 * rand(256)}]\n    vmov${c} ${a}, s${sr}`;
                case 3: return `vmov${c} s${sr}, ${a}\n    vstr${c} s${sr}, [r8, #${4 * rand(256)}]`;
                default: {
                    const n = 1 + rand(4), f = rand(32 - n), wb = rand(2) ? "!" : "";
                    const list = `{d${f}-d${f + n - 1}}`;
                    return `add${c} r12, r8, #${16 * rand(48) + 64}\n    ` + pick([`vldmia${c} r12${wb}, ${list}`, `vstmia${c} r12${wb}, ${list}`,
                        `vldmdb${c} r12!, ${list}`, `vstmdb${c} r12!, ${list}`]) + `\n    vmov${c} ${a}, ${b}, d${f}`;
                }
            }
        }
        case 24: {
            // VFP's arithmetic and moves (Q6.3): values from integers, an
            // operation, back to a core register; D's through two core registers
            const [a, b] = distinct(2), x = rand(8), y = rand(8), z = rand(8), dd = rand(16);
            const op = pick(["vadd", "vsub", "vmul", "vnmul", "vdiv"]);
            const unary = pick(["vmov", "vabs", "vneg"]);
            return rand(2) ?
                `vmov${c} s${x}, ${a}\n    vcvt${c}.f32.s32 s${x}, s${x}\n    vmov${c} s${y}, ${b}\n    vcvt${c}.f32.s32 s${y}, s${y}\n    ` +
                `${op}${c}.f32 s${z}, s${x}, s${y}\n    ${unary}${c}.f32 s${z + 8}, s${z}\n    vmov${c} ${a}, s${z + 8}` :
                `vmov${c} s${x}, ${a}\n    vcvt${c}.f64.s32 d${x}, s${x}\n    vmov${c} s${y + 8}, ${b}\n    vcvt${c}.f64.s32 d${y + 8}, s${y + 8}\n    ` +
                `${op}${c}.f64 d${dd}, d${x}, d${y + 8}\n    ${unary}${c}.f64 d${dd + 16}, d${dd}\n    vmov${c} ${a}, ${b}, d${dd + 16}`;
        }
        case 23: {
            // VLD1, VST1 (multiple, all lanes): unconditional; through r12,
            // word aligned or not, with an alignment specifier or not
            if(c) return plain(c);
            const n = pick([1, 2, 3, 4]), f = rand(33 - n), [a, b] = distinct(2);
            const list = `{${Array.from({ length: n }, (_, i) => "d" + (f + i)).join(", ")}}`;
            const aligned = rand(3) === 0;
            const spec = aligned ? pick([":64", n === 2 || n === 4 ? ":128" : ":64"]) : "";
            // (constants both sets encode: 16 * k, then a small one)
            const skew = aligned ? 0 : 4 * rand(4) + pick([0, 0, 1, 2]);
            const op = rand(2) ? "vld1" : "vst1";
            return `add r12, r8, #${16 * rand(96)}\n    ${skew ? `add r12, r12, #${skew}\n    ` : ""}${op}.${pick([8, 16, 32, 64])} ${list}, [r12${spec}]${rand(2) ? "!" : ""}\n    vmov ${a}, ${b}, d${f}`;
        }
        default: return `vmov${c} s${rand(8)}, ${r()}\n    vcvt${c}.f32.s32 s${rand(8)}, s${rand(8)}\n    vadd${c}.f32 s${rand(8)}, s${rand(8)}, s${rand(8)}\n    vmov${c} ${r()}, s${rand(8)}`;
    }
}

/** One construct of the body: an instruction, an IT block, control flow */
function construct(depth)
{
    switch(rand(depth ? 6 : 14))
    {
        case 0: case 1: case 2: case 3: case 4: {
            const c = cond();
            return plain(c).split("\n    ").map(line => line).join("\n    ");
        }
        case 5: {
            if(!thumb) return plain(pick(CONDS));
            // an IT block: up to four instructions, each its own condition or the inverse
            const c = pick(CONDS), n = 1 + rand(4);
            const inverse = { eq: "ne", ne: "eq", cs: "cc", cc: "cs", mi: "pl", pl: "mi", vs: "vc", vc: "vs", hi: "ls", ls: "hi", ge: "lt", lt: "ge", gt: "le", le: "gt" };
            const pattern = Array.from({ length: n - 1 }, () => rand(2) ? "t" : "e");
            const conds = [c, ...pattern.map(p => p === "t" ? c : inverse[c])];
            // (an IT block's instructions one each: no multi-instruction plain forms)
            const body = conds.map(x => {
                let line;
                do line = plain(x); while(line.includes("\n"));
                return line;
            });
            return `it${pattern.join("")} ${c}\n    ${body.join("\n    ")}`;
        }
        case 6: { const l = label++; return `b${pick(CONDS)} 1${l}f\n    ${plain()}\n1${l}:`; }
        case 7: { const l = label++; return `b 1${l}f\n    ${plain()}\n1${l}:`; }
        case 8: {
            // a counted loop (r11 its counter)
            const l = label++;
            return `mov r11, #${2 + rand(5)}\n2${l}:\n    ${construct(depth + 1)}\n    ${construct(depth + 1)}\n    subs r11, r11, #1\n    bne 2${l}b`;
        }
        case 9: return `bl leaf_${rand(3)}`;
        case 10: {
            if(!thumb) return plain(cond());
            const l = label++;
            return `${pick(["cbz", "cbnz"])} ${lo()}, 1${l}f\n    ${plain()}\n1${l}:`;
        }
        case 11: {
            // (balanced: as many popped as pushed, into other registers maybe)
            const k = 1 + rand(4);
            return `push {${distinct(k).join(", ")}}\n    ${plain()}\n    pop {${distinct(k).join(", ")}}`;
        }
        case 12: return `mrs r12, apsr\n    eor r12, r12, #0x${pick(["40000000", "20000000", "80000000", "10000000"])}\n    msr apsr_nzcvq, r12`;
        default: return plain(cond());
    }
}

function program(n)
{
    thumb = n % 2 === 1;
    label = 0;
    const body = Array.from({ length: LENGTH }, () => construct(0)).join("\n    ");
    // (leaves return by BX LR, by POP of the PC or LDR of it from the
    // stack, A32's maybe early by a conditional BX)
    const leaf = k => {
        const body = Array.from({ length: 3 }, () => plain()).join("\n    ");
        const early = !thumb && rand(2) ? `cmp ${r()}, ${r()}\n    bx${pick(CONDS)} lr\n    ` : "";
        switch(k)
        {
            case 0: return `leaf_0:\n    ${early}${body}\n    bx lr`;
            case 1: return `leaf_1:\n    push {r4, lr}\n    ${early}${body}\n    pop {r4, pc}`;
            default: return `leaf_2:\n    push {lr}\n    ${body}\n    ldr pc, [sp], #4`;
        }
    };
    return `@ generated by tests/a64/aarch32_page_fuzz.mjs (seed ${SEED}, program ${n})
    .syntax unified
    .${thumb ? "thumb" : "arm"}
header:
    .word   ${thumb ? 1 : 0}
entry:
${[...REGS, 11].map(i => `    ldr r${i}, [r8, #${3072 + 4 * i}]`).join("\n")}
    ldr r12, [r8, #${3072 + 64}]
    msr apsr_nzcvq, r12
    mov r12, #${ROUNDS}
    str r12, [r8, #4092]
round:
    ${body}
    ldr r12, [r8, #4092]
    subs r12, r12, #1
    str r12, [r8, #4092]
    bne round
${[...REGS, 11].map(i => `    str r${i}, [r8, #${3072 + 4 * i}]`).join("\n")}
    mrs r12, apsr
    str r12, [r8, #${3072 + 64}]
    svc #0
    .balign 4
${[0, 1, 2].map(leaf).join("\n")}
`;
}

// (--write DIR: the programs written there, not run)
if(option("--write", null))
{
    for(let n = 0; n < PROGRAMS; n++) fs.writeFileSync(option("--write") + `/fuzz-${n}.a32.S`, program(n));
    process.exit(0);
}
const directory = root + "build/a64-aarch32-page-fuzz/";
fs.mkdirSync(directory, { recursive: true });
process.env.A64_MMU = "1";
let differences = 0, helpers = 0, retired = 0, steps = 0, finished = 0;
for(let n = 0; n < PROGRAMS; n++)
{
    const seed = next64();
    fs.writeFileSync(directory + "fuzz.a32.S", program(n));
    const guest = build("aarch32-page-fuzz", [root + "tests/a64/aarch32/fuzz.c", root + "tests/a64/aarch32/el0_run.S", directory + "fuzz.a32.S"],
        { cflags: [`-DSEED=${seed}ULL`, "-DA64_MMU"] });
    delete process.env.A64_JIT;
    const interpreted = await actual(guest, { options: { cpu_profile: "generic-arm64-compat32" } });
    process.env.A64_JIT = "1";
    process.env.A64_JIT_HOT = "1";
    process.env.A64_JIT_SWITCHES = "a64_page_aarch32=" + (process.env.A64_AARCH32_PAGE || "1");
    const compiled = await actual(guest, { options: { cpu_profile: "generic-arm64-compat32" } });
    assert.equal(interpreted.status, "ok", `program ${n} (interpreter): ${interpreted.status}\n${interpreted.text}`);
    assert.equal(compiled.status, "ok", `program ${n} (page tier): ${compiled.status}\n${compiled.text}`);
    const t = compiled.page_tier;
    // (a program that ends with its SVC, not an exception on the way)
    if(/^exit esr 4[46]000000/.test(interpreted.text)) finished++;
    else console.log(`program ${n}: ${interpreted.text.split("\n")[0]}`);
    helpers += t.helpers;
    retired += t.retired;
    steps += t.steps;
    if(interpreted.text !== compiled.text)
    {
        differences++;
        fs.copyFileSync(directory + "fuzz.a32.S", directory + `fuzz-diff-${n}.a32.S`);
        const a = interpreted.text.split("\n"), b = compiled.text.split("\n");
        const first = a.findIndex((line, i) => line !== b[i]);
        console.log(`program ${n} (${n % 2 ? "T32" : "A32"}): differs at line ${first + 1} (kept as fuzz-diff-${n}.a32.S)\n  interpreter: ${a[first]}\n  page tier:   ${b[first]}`);
    }
}
delete process.env.A64_JIT;
console.log(`aarch32 page fuzz: ${PROGRAMS} programs of ${LENGTH} constructs x ${ROUNDS} rounds (${finished} to their end), ${differences} differences ` +
    `(page tier: ${retired} retired, ${helpers} helper calls, ${steps} steps)`);
process.exit(differences ? 1 : 0);
                                                                                   source/v64/tests/a64/aarch32_unpredictable.mjs                                                      0000644 0000000 0000000 00000012302 00000000000 016255  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// v86's choices among AArch32's CONSTRAINED UNPREDICTABLE behaviours at EL0
// (docs/arm32.md, docs/aarch32-plan.md): the cases of
// tests/a64/aarch32/unpredictable.a32.S under tests/a64/aarch32/el0.c with
// profile v3, interpreted and on the page tier (a64_page_aarch32 1, native,
// and 2, helper calls only; compiling at the first boundary). QEMU 9.2 takes
// T32's LDM and STM of one register as UNDEFINED where v86 (like Cortex-A
// cores and the Android emulator's QEMU) transfers it, so the exits are
// checked against the values here; the three runs must print the same.
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, actual, root } from "./guest_runner.mjs";

process.env.A64_MMU = "1";
const directory = build("aarch32-unpredictable", [root + "tests/a64/aarch32/el0.c", root + "tests/a64/aarch32/el0_run.S",
    root + "tests/a64/aarch32/unpredictable.a32.S"], { cflags: ["-DCASES=unpredictable_a32", "-DA64_MMU"] });
const binary = fs.readFileSync(directory + "unpredictable.a32.bin");

// per case: the SVC it ends with and registers' values (r10: how far the
// base moved), or the instruction (hw1 << 16 | hw2) that is UNDEFINED
const CASES = [
    { name: "ldm.w r8!, {r0}", svc: 1, r: { 0: 0x11223344, 10: 4 } },
    { name: "ldm.w r8, {r0}", svc: 2, r: { 0: 0x55667788, 10: 0 } },
    { name: "stm.w r8!, {r1}", svc: 3, r: { 0: 0x99AABBCC, 2: 0, 10: 4 } },
    { name: "stm.w r8, {r1}", svc: 4, r: { 0: 0xDDEEFF00, 10: 0 } },
    { name: "ldmdb r8!, {r0}", svc: 5, r: { 0: 0x13572468, 10: -4 } },
    { name: "stmdb r8!, {r1}", svc: 6, r: { 0: 0x75318642, 2: 0, 10: -4 } },
    { name: "ldm.w r8!, {lr}", svc: 7, r: { 14: 0xC0DECAFE, 10: 4 } },
    { name: "ldm.w r8, {pc}", svc: 8, r: { 0: 0x42, 10: 0 } },
    { name: "ldm.w in IT blocks", svc: 9, r: { 0: 0x22221111, 2: 0, 10: 4 } },
    { name: "ldm.w r8!, {r0} in a loop", svc: 10, r: { 6: 6, 10: 12 } },
    { name: "A32 ldm r8!, {r0}", svc: 11, r: { 0: 0xA5A55A5A, 10: 4 } },
    { name: "ldm.w r8!, {r8}", undefined: 0xE8B80100 },
    { name: "ldm.w r8, {}", undefined: 0xE8980000 },
    { name: "ldm.w r8, {sp}", undefined: 0xE8982000 },
    { name: "stm.w r8, {pc}", undefined: 0xE8888000 },
];

/** The driver's exits: per case its ESR, ELR (an offset into the binary) and R0-R14 */
function exits(text)
{
    const lines = text.split("\n");
    const result = [];
    for(let i = 0; i < lines.length; i++)
    {
        const m = lines[i].match(/^case (\d+)\.0: vector \d+ esr ([0-9a-f]+) elr ([+-]\d+)/);
        if(!m) continue;
        const r = lines[i + 1].trim().split(" ").map(v => Number(BigInt("0x" + v) & 0xFFFFFFFFn));
        result[+m[1]] = { esr: parseInt(m[2], 16), elr: +m[3], r };
    }
    return result;
}

const runs = [["interpreter", null], ["page tier", 1], ["page tier, helper calls", 2]];
let reference_text = null;
let failures = 0;
for(const [name, page] of runs)
{
    if(page === null) delete process.env.A64_JIT;
    else
    {
        process.env.A64_JIT = "1";
        process.env.A64_JIT_HOT = "1";
        process.env.A64_JIT_SWITCHES = "a64_page_aarch32=" + page;
    }
    const result = await actual(directory, { options: { cpu_profile: "generic-arm64-compat32" } });
    assert.equal(result.status, "ok", name + ": " + result.status + "\n" + result.text);
    if(page !== null) assert.ok(result.page_tier.compiled > 0, name + ": nothing compiled " + JSON.stringify(result.page_tier));
    const got = exits(result.text);
    assert.equal(got.length, CASES.length, name + ": the exits\n" + result.text);
    CASES.forEach((c, i) => {
        const e = got[i];
        const problems = [];
        if(c.undefined !== undefined)
        {
            const word = binary.readUInt16LE(e.elr) << 16 | binary.readUInt16LE(e.elr + 2);
            if(e.esr >>> 26 !== 0) problems.push(`ESR ${e.esr.toString(16)}, not an UNDEFINED instruction's`);
            else if(word >>> 0 !== c.undefined) problems.push(`ELR at ${(word >>> 0).toString(16)}`);
        }
        else
        {
            if(e.esr >>> 26 !== 0x11 || (e.esr & 0xFFFF) !== c.svc) problems.push(`ESR ${e.esr.toString(16)}, not SVC #${c.svc}'s`);
            for(const [r, value] of Object.entries(c.r))
            {
                if(e.r[r] !== value >>> 0) problems.push(`r${r} ${e.r[r].toString(16)}, not ${(value >>> 0).toString(16)}`);
            }
        }
        if(problems.length)
        {
            failures++;
            console.log(`FAIL: ${name}: case ${i} (${c.name}): ${problems.join(", ")}`);
        }
    });
    if(reference_text === null) reference_text = result.text;
    else if(result.text !== reference_text)
    {
        failures++;
        const a = reference_text.split("\n"), b = result.text.split("\n");
        const first = a.findIndex((line, i) => line !== b[i]);
        console.log(`FAIL: ${name}: differs from the interpreter at line ${first + 1}\n  interpreter: ${a[first]}\n  ${name}: ${b[first]}`);
    }
    const t = result.page_tier;
    console.log(`${name}: ${CASES.length} cases checked` + (page === null ? "" : ` (${t.compiled} compiles, ${t.helpers} helper calls, ${t.steps} steps)`));
}
if(!failures) console.log(`PASS: ${CASES.length} cases, the same interpreted and on the page tier`);
process.exit(failures ? 1 : 0);
                                                                                                                                                                                                                                                                                                                              source/v64/tests/a64/adb.mjs                                                                        0000644 0000000 0000000 00000016275 00000000000 012674  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A minimal ADB client (docs/arm64-virt-android16-plan.md P10.7): the
// transport protocol of system/adb/protocol.txt over any byte stream with
// write(bytes) and an on_data callback (a TCP socket to QEMU's forwarded
// port, or a connection through v86's network adapter to the guest's
// 5555). Without authentication: the guest's adbd runs with ro.adb.secure=0
// (the debug vendor ramdisk, tools/a64_android.mjs). Version 0x01000001, so
// neither side checks the data checksum; no features (no delayed acks).
//
//   const adb = new AdbClient(stream); await adb.connect();
//   const output = await adb.shell("getprop sys.boot_completed");
//   await adb.push("/data/local/tmp/app.apk", bytes);   (the sync service's SEND)

const A_CNXN = 0x4e584e43, A_OPEN = 0x4e45504f, A_OKAY = 0x59414b4f, A_CLSE = 0x45534c43, A_WRTE = 0x45545257, A_AUTH = 0x48545541;
const VERSION = 0x01000001;
const MAX_DATA = 256 * 1024;

function message(command, arg0, arg1, data = Buffer.alloc(0))
{
    const header = Buffer.alloc(24);
    header.writeUInt32LE(command, 0);
    header.writeUInt32LE(arg0 >>> 0, 4);
    header.writeUInt32LE(arg1 >>> 0, 8);
    header.writeUInt32LE(data.length, 12);
    header.writeUInt32LE(data.reduce((sum, byte) => sum + byte, 0) >>> 0, 16);
    header.writeUInt32LE((command ^ 0xFFFFFFFF) >>> 0, 20);
    return Buffer.concat([header, data]);
}

export class AdbClient
{
    /** @param {{write: function(!Buffer), on_data: ?function(!Buffer), close?: function()}} stream */
    constructor(stream)
    {
        this.stream = stream;
        this.input = Buffer.alloc(0);
        this.next_id = 1;
        /** local id -> { on_message } */
        this.streams = new Map();
        this.on_connect = null;
        this.banner = null;
        stream.on_data = bytes => this.receive(bytes);
    }

    receive(bytes)
    {
        this.input = Buffer.concat([this.input, bytes]);
        while(this.input.length >= 24)
        {
            const length = this.input.readUInt32LE(12);
            if(this.input.length < 24 + length) break;
            const command = this.input.readUInt32LE(0), arg0 = this.input.readUInt32LE(4), arg1 = this.input.readUInt32LE(8);
            const data = this.input.subarray(24, 24 + length);
            this.input = this.input.subarray(24 + length);
            if(command === A_CNXN)
            {
                this.banner = data.toString("latin1");
                this.max_data = Math.min(arg1, MAX_DATA);
                this.on_connect?.(this.banner);
            }
            else if(command === A_AUTH)
            {
                this.on_connect?.(null, new Error("adbd asks for authentication (ro.adb.secure=1)"));
            }
            else
            {
                // OKAY, WRTE, CLSE: arg1 is our id
                this.streams.get(arg1)?.on_message(command, arg0, data);
            }
        }
    }

    /** @return {!Promise<string>} the device's banner */
    connect(timeout_ms = 30000)
    {
        return new Promise((resolve, reject) => {
            const timer = setTimeout(() => reject(new Error("no CNXN from adbd")), timeout_ms);
            this.on_connect = (banner, error) => { clearTimeout(timer); error ? reject(error) : resolve(banner); };
            this.stream.write(message(A_CNXN, VERSION, MAX_DATA, Buffer.from("host::\0")));
        });
    }

    /** a service's whole output (e.g. "shell:getprop"), until the device closes it */
    run(service, timeout_ms = 60000)
    {
        const id = this.next_id++;
        return new Promise((resolve, reject) => {
            const chunks = [];
            const timer = setTimeout(() => { this.streams.delete(id); reject(new Error(`${service}: no answer`)); }, timeout_ms);
            this.streams.set(id, { on_message: (command, remote, data) => {
                if(command === A_WRTE)
                {
                    chunks.push(Buffer.from(data));
                    this.stream.write(message(A_OKAY, id, remote));
                }
                else if(command === A_CLSE)
                {
                    clearTimeout(timer);
                    this.streams.delete(id);
                    this.stream.write(message(A_CLSE, id, remote));
                    resolve(Buffer.concat(chunks).toString("utf8"));
                }
            } });
            this.stream.write(message(A_OPEN, id, 0, Buffer.from(service + "\0")));
        });
    }

    shell(command, timeout_ms)
    {
        return this.run("shell:" + command, timeout_ms);
    }

    /** a file onto the device (sync: SEND path,mode; DATA chunks; DONE mtime), each write after the device's OKAY */
    push(remote_path, bytes, mode = 0o100644, timeout_ms = 120000)
    {
        const id = this.next_id++;
        let remote = 0, acked = null, closed = false, reply = Buffer.alloc(0);
        const ack = () => new Promise(resolve => { acked = resolve; });
        let replied = null;
        this.streams.set(id, { on_message: (command, from, data) => {
            if(command === A_OKAY) { remote = from; acked?.(); acked = null; }
            else if(command === A_WRTE)
            {
                reply = Buffer.concat([reply, data]);
                this.stream.write(message(A_OKAY, id, from));
                if(reply.length >= 8) replied?.();
            }
            else if(command === A_CLSE) { closed = true; acked?.(); replied?.(); }
        } });
        const request = (tag, length, payload = Buffer.alloc(0)) => {
            const header = Buffer.alloc(8);
            header.write(tag, 0, "latin1");
            header.writeUInt32LE(length, 4);
            return Buffer.concat([header, payload]);
        };
        const write = async bytes => {
            const done = ack();
            this.stream.write(message(A_WRTE, id, remote, bytes));
            await done;
            if(closed) throw new Error("adb push: the device closed the stream");
        };
        const work = (async () => {
            const opened = ack();
            this.stream.write(message(A_OPEN, id, 0, Buffer.from("sync:\0")));
            await opened;
            if(closed) throw new Error("adb push: no sync service");
            const target = Buffer.from(`${remote_path},${mode}`);
            await write(request("SEND", target.length, target));
            for(let at = 0; at < bytes.length; at += 65536)
            {
                const chunk = Buffer.from(bytes.subarray(at, at + 65536));
                await write(request("DATA", chunk.length, chunk));
            }
            const answer = new Promise(resolve => { replied = resolve; });
            await write(request("DONE", Math.floor(Date.now() / 1000)));
            if(reply.length < 8) await answer;
            const tag = reply.toString("latin1", 0, 4);
            if(tag !== "OKAY") throw new Error("adb push: " + tag + " " + reply.toString("utf8", 8, 8 + reply.readUInt32LE(4)));
            // (QUIT: the device closes the stream, perhaps before it acknowledges)
            if(!closed) this.stream.write(message(A_WRTE, id, remote, request("QUIT", 0)));
            this.stream.write(message(A_CLSE, id, remote));
            this.streams.delete(id);
        })();
        return Promise.race([work, new Promise((_, reject) => setTimeout(() => reject(new Error("adb push: timed out")), timeout_ms))]);
    }
}
                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/address_space.mjs                                                              0000644 0000000 0000000 00000024165 00000000000 014743  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The ARM core's physical address space through the emulator
// (docs/arm64-virt-android16-plan.md P1.5, P1.7; src/rust/aarch64/bus.rs,
// src/virt/io.js): new V86 with cpu_type "arm64" loads the ARM core and the
// arm64 CPU; RAM at 0x4000_0000, device ranges above 4 GiB (one at
// 0x50_1000_0000, a device at 0x60_0000_0000) and two 0x200 windows
// inside one 128 KiB block, holes, 16- and 64-bit accesses (a FIFO's 16-bit
// read pops once), the map's generation, an access across regions that
// writes nothing, code keys and the writes that retire watched code; the
// PCIe host (P5.6, P5.10): a virtio-rng function's 64-bit BAR sized, placed
// above and below 4 GiB and moved through the high ECAM, decoded only with
// its memory space enabled.
//
//   node tests/a64/address_space.mjs   (A64_WASM: the core, default build/v86-arm64.wasm)
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const emulator = new V86({
    cpu_type: "arm64", graphics_adapter: "none", memory_size: 64 << 20, autostart: false, log_level: 0,
    virtio_transport: "pci", virtio_rng: true,
    wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
});
await new Promise((resolve, reject) => {
    emulator.add_listener("emulator-loaded", resolve);
    emulator.add_listener("emulator-error", reject);
});
const cpu = emulator.v86.cpu;
// (the test takes the first three virtio-mmio slots, empty until P5.1: two devices and a hole)
for(const owner of cpu.virtio_mmio_slots.slice(0, 3)) cpu.io.unregister_mmio(owner);
const e = cpu.wm.exports;
try
{
    assert.equal(cpu.cpu_type, "arm64");
    assert.equal(e.isa_aarch64(), 1);
    const split = pa => [Number(BigInt(pa) & 0xFFFFFFFFn), Number(BigInt(pa) >> 32n)];
    const kind = pa => e.a64_bus_lookup(...split(pa));
    const detail = pa => e.a64_bus_lookup_detail(...split(pa));
    const read = (pa, width) => { const v = e.a64_bus_read(...split(pa), width); return [e.a64_bus_status(), v]; };
    const write = (pa, width, value) => e.a64_bus_write(...split(pa), width, BigInt(value));

    // RAM from 0x4000_0000, holes around it
    assert.equal(kind(0x40000000), 1);
    assert.equal(detail(0x40000000 + 0x1234), 0x1234);
    assert.equal(kind(0x3FFFFFFF), 0);
    assert.equal(kind(0x40000000 + (64 << 20)), 0);
    assert.equal(cpu.memory_size[0], 64 << 20);
    console.log("PASS RAM at 0x4000_0000, 64 MiB");

    // device ranges: a FIFO of 16-bit words, a 64-bit register, two windows of 0x200
    const fifo = [0x1111, 0x2222, 0x3333];
    const accesses = [];
    const generation = e.a64_bus_generation();
    const fifo_owner = cpu.io.register_mmio(0x0a000000, 0x200, {
        read: (offset, width) => { accesses.push(["fifo", offset, width]); return offset === 0 && width === 2 ? fifo.shift() : 0xFFFF; },
        write: () => {},
    });
    const window_owner = cpu.io.register_mmio(0x0a000200, 0x200, {
        read: (offset, width) => { accesses.push(["window", offset, width]); return offset; },
        write: (offset, width, value) => accesses.push(["window-write", offset, width, value]),
    });
    let register = 0n;
    const ecam = cpu.io.register_mmio([0x10000000, 0x50], 0x10000000, {
        read: (offset, width) => offset + width,
        write: () => {},
    });
    const high = cpu.io.register_mmio([0, 0x60], 0x1000, {
        read: (offset, width) => { accesses.push(["high", offset, width]); return register; },
        write: (offset, width, value) => { accesses.push(["high-write", offset, width]); register = value; },
    });
    assert.notEqual(e.a64_bus_generation(), generation, "mapping changes the generation");
    assert.equal(kind(0x0a000000), 3);
    assert.equal(detail(0x0a000000), fifo_owner);
    assert.equal(detail(0x0a0001ff), fifo_owner);
    assert.equal(detail(0x0a000200), window_owner);
    assert.equal(kind(0x0a000400), 0, "the next 0x200 is a hole");
    assert.equal(detail(0x5010000000n + 0x123n), ecam);
    assert.equal(detail(0x6000000000n), high);
    assert.throws(() => cpu.io.register_mmio(0x0a000100, 0x200, { read: () => 0, write: () => {} }), /overlaps/);
    assert.throws(() => cpu.io.register_mmio(0x40000000, 0x1000, { read: () => 0, write: () => {} }), /overlaps RAM/);
    assert.throws(() => cpu.io.register_mmio([0, 0x100], 0x1000, { read: () => 0, write: () => {} }), /40-bit/);
    console.log("PASS device ranges: narrow windows in one 128 KiB block, above 4 GiB, overlaps refused");

    // widths: one 16-bit read pops one FIFO entry, 64-bit values round-trip
    accesses.length = 0;
    assert.deepEqual(read(0x0a000000, 2), [0, 0x1111n]);
    assert.deepEqual(accesses, [["fifo", 0, 2]]);
    assert.deepEqual(fifo, [0x2222, 0x3333]);
    assert.deepEqual(read(0x0a000204, 4), [0, 4n]);
    assert.equal(write(0x6000000008n, 8, 0x1122334455667788n), 0);
    assert.deepEqual(read(0x6000000008n, 8), [0, 0x1122334455667788n]);
    assert.deepEqual(read(0x5010000010n, 4), [0, 0x14n]);
    console.log("PASS 16- and 64-bit device accesses (a 16-bit FIFO read pops once)");

    // holes, the PA range, accesses across regions write nothing
    assert.equal(read(0x0b000000, 4)[0], 1, "a hole: external abort");
    assert.equal(read(1n << 40n, 1)[0], 2, "beyond 40 bits: address size fault");
    const end = 0x40000000 + (64 << 20);
    assert.equal(write(end - 8, 8, 0), 0);
    assert.equal(write(end - 4, 8, -1n), 1);
    assert.deepEqual(read(end - 8, 8), [0, 0n], "nothing written before the end of RAM");
    assert.equal(read(0x0a0001fe, 4)[0], 1, "across two devices");
    console.log("PASS holes, the 40-bit range and accesses across regions (nothing written)");

    // code keys and the writes that retire code compiled from a page
    assert.equal(e.a64_bus_code_key(0x40003000, 0), 3);
    assert.equal(e.a64_bus_code_key(0x0a000000, 0), -1);
    assert.ok(e.a64_test_watch_page(5));
    const retired = e.a64_test_retired();
    assert.equal(write(0x40004ff8, 8, 1), 0, "the page before");
    assert.equal(e.a64_test_retired(), retired);
    assert.equal(write(0x40005010, 4, 1), 0);
    assert.equal(e.a64_test_retired(), retired + 1, "a CPU store to the watched page");
    assert.ok(e.a64_test_watch_page(5));
    cpu.write_blob_physical(new Uint8Array([1, 2, 3]), 0x40005800);
    assert.equal(e.a64_test_retired(), retired + 2, "a write from JavaScript (loader, DMA)");
    console.log("PASS code keys and write notification");

    // the PCIe host (P5.6, P5.10): configuration through the high ECAM;
    // virtio-rng at 00:01.0 with BAR 4 (64-bit, prefetchable, 16 KiB)
    const config = (devfn, register) => 0x4010000000n + BigInt(devfn << 12 | register);
    const cfg_read = (devfn, register, width = 4) => { const [status, value] = read(config(devfn, register), width); assert.equal(status, 0); return Number(value); };
    const cfg_write = (devfn, register, value, width = 4) => assert.equal(write(config(devfn, register), width, BigInt(value >>> 0)), 0);
    const RNG = 1 << 3;
    assert.equal(cfg_read(0, 0), 0x00081B36, "00:00.0: the QEMU PCIe host bridge");
    assert.equal(cfg_read(0, 8) >>> 8, 0x060000, "a host bridge");
    assert.equal(cfg_read(RNG, 0), 0x10441AF4, "00:01.0: virtio-rng, non-transitional");
    assert.equal(cfg_read(RNG, 0x2C), 0x11001AF4, "QEMU's subsystem");
    assert.equal(cfg_read(RNG, 8) >>> 8, 0x00FF00, "class: other");
    assert.equal(cfg_read(2 << 3, 0), 0xFFFFFFFF, "00:02.0: nothing");
    assert.equal(cfg_read(RNG, 0x3D, 1), 1, "INTA");
    assert.equal(cfg_read(RNG, 0x20), 0xC, "BAR 4: 64-bit, prefetchable, unassigned");
    assert.equal(cfg_read(RNG, 4, 2), 0, "no decode at power-on");
    cfg_write(RNG, 0x20, -1);
    cfg_write(RNG, 0x24, -1);
    assert.deepEqual([cfg_read(RNG, 0x20), cfg_read(RNG, 0x24)], [0xFFFFC00C, 0xFFFFFFFF], "sizing: 16 KiB, both halves");
    const map_generation = e.a64_bus_generation();
    cfg_write(RNG, 0x20, 0x4000);
    cfg_write(RNG, 0x24, 0x80);
    assert.deepEqual([cfg_read(RNG, 0x20), cfg_read(RNG, 0x24)], [0x400C, 0x80]);
    // (the common configuration: num_queues at 0x12, the features' second word: VERSION_1)
    assert.deepEqual(read(0x8000004012n, 2), [0, 0xFFFFn], "memory space disabled: nothing decodes");
    cfg_write(RNG, 4, 2, 2);
    assert.deepEqual(read(0x8000004012n, 2), [0, 1n], "above 4 GiB: one queue");
    assert.equal(write(0x8000004000n, 4, 1n), 0);
    assert.deepEqual(read(0x8000004004n, 4), [0, 1n], "VERSION_1");
    cfg_write(RNG, 0x20, 0x10004000);
    assert.deepEqual(read(0x8010004012n, 2), [0, 1n], "half moved: at 0x80_1000_4000");
    cfg_write(RNG, 0x24, 0);
    assert.deepEqual(read(0x8010004012n, 2), [0, 0xFFFFn], "the old place reads all ones");
    assert.deepEqual(read(0x10004012, 2), [0, 1n], "below 4 GiB, in the 32-bit window");
    assert.deepEqual(read(0x10004000, 8), [0, 1n | 1n << 32n], "an 8-byte access is two 4-byte ones");
    assert.equal(e.a64_bus_generation(), map_generation, "the windows stay where they are: the map does not change");
    cfg_write(RNG, 4, 0, 2);
    assert.deepEqual(read(0x10004012, 2), [0, 0xFFFFn], "memory space disabled again");
    cfg_write(RNG, 4, 2, 2);
    cpu.devices.pci.reset();
    assert.deepEqual([cfg_read(RNG, 0x20), cfg_read(RNG, 0x24), cfg_read(RNG, 4, 2)], [0xC, 0, 0], "a reset: power-on configuration");
    assert.deepEqual(read(0x10004012, 2), [0, 0xFFFFn], "and nothing decoded");
    console.log("PASS the PCIe host: high ECAM, a 64-bit BAR sized, above and below 4 GiB, decode with memory space enabled, reset");

    // unmapping
    cpu.io.unregister_mmio(window_owner);
    assert.equal(kind(0x0a000200), 0);
    console.log("PASS unmapping");

    // snapshot identity
    const state = cpu.get_state(true);
    // (the default profile, v2)
    assert.deepEqual(state[103], ["virt", 2, "v86-aarch64-v2"]);
    assert.throws(() => cpu.validate_state(Object.assign([], state, { 103: ["i440fx", 1] })), /machine_type: "i440fx"/);
    assert.throws(() => cpu.validate_state(Object.assign([], state, { 103: undefined })), /machine_type: "i440fx"/);
    console.log("PASS snapshot identity");
}
finally
{
    await emulator.destroy();
}
                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/a64/android/futex_stress.c                                                         0000644 0000000 0000000 00000021406 00000000000 015745  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Condition variables across cores (docs/aarch64.md's known defects: Android
// stalled after a restore with Launcher3's RenderThread waiting for good in
// ANGLE's AsyncWaitableEvent::wait): bionic's pthread mutexes and condition
// variables used the way ANGLE's worker pool uses them (src/common/
// WorkerThread.cpp: a queue of tasks under one mutex and condition
// variable, each task's event its own mutex, condition variable and flag),
// and ping-pong pairs, while the host saves and restores the machine.
//
// Built with the NDK as a static executable (it runs on Android and on
// Alpine's kernel alike):
//   futex_stress <seconds> [pairs] [workers] [tasks]
// Every second a line "FS <second> pp=<round trips> pool=<batches> ..."; a
// group that made no progress for 10 s is reported once on a line
// "FS_STALL ..." with the waiters' places, and the run ends with
// "FS_DONE stalls=<n>".
//   futex_stress clock <cpus>
// On each CPU in turn, CLOCK_MONOTONIC read for 200 ms of its own time: the
// largest step between two readings, "FS_CLOCK cpu=<n> reads=<n>
// max_step_us=<n>" (a core whose counter only moves when another core
// reads it steps by up to the machine's idle sleep).
#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define MAX_PAIRS 16
#define MAX_WORKERS 16
#define MAX_TASKS 64

static atomic_int stop;

static double now(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

// ---- ping-pong pairs: one mutex, one condition variable, a turn

struct pair
{
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int turn;
    atomic_long rounds;
    atomic_int where[2];        // 0 running, 1 waiting
};
static struct pair pairs[MAX_PAIRS];

struct side { struct pair *p; int me; };

static void *pair_thread(void *arg)
{
    struct side *s = arg;
    struct pair *p = s->p;
    while(!atomic_load(&stop))
    {
        pthread_mutex_lock(&p->mutex);
        while(p->turn != s->me && !atomic_load(&stop))
        {
            atomic_store(&p->where[s->me], 1);
            pthread_cond_wait(&p->cond, &p->mutex);
            atomic_store(&p->where[s->me], 0);
        }
        p->turn = !s->me;
        if(s->me) atomic_fetch_add(&p->rounds, 1);
        pthread_cond_signal(&p->cond);
        pthread_mutex_unlock(&p->mutex);
    }
    return NULL;
}

// ---- ANGLE's worker pool: tasks in a queue, an event per task

struct event
{
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int ready;
};

static struct
{
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int queue[MAX_TASKS];
    int head, tail;
} pool = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER };

static struct event events[MAX_TASKS];
static atomic_long work[MAX_TASKS];
static atomic_long batches;
static atomic_int worker_where[MAX_WORKERS];    // 0 running a task, 1 waiting for one
static atomic_int producer_waits = -1;          // the task whose event the producer waits for
static int tasks = 8;

static void *worker_thread(void *arg)
{
    int me = (int)(long)arg;
    for(;;)
    {
        pthread_mutex_lock(&pool.mutex);
        while(pool.head == pool.tail && !atomic_load(&stop))
        {
            atomic_store(&worker_where[me], 1);
            pthread_cond_wait(&pool.cond, &pool.mutex);
            atomic_store(&worker_where[me], 0);
        }
        if(pool.head == pool.tail)
        {
            pthread_mutex_unlock(&pool.mutex);
            return NULL;
        }
        int task = pool.queue[pool.head++ % MAX_TASKS];
        pthread_mutex_unlock(&pool.mutex);
        // (a little work: ANGLE's tasks compile and create pipelines)
        volatile unsigned x = task;
        for(int i = 0; i < 2000; i++) x = x * 1103515245 + 12345;
        atomic_fetch_add(&work[task], 1);
        struct event *e = &events[task];
        pthread_mutex_lock(&e->mutex);
        e->ready = 1;
        pthread_cond_broadcast(&e->cond);
        pthread_mutex_unlock(&e->mutex);
    }
}

static void *producer_thread(void *arg)
{
    (void)arg;
    while(!atomic_load(&stop))
    {
        for(int t = 0; t < tasks; t++)
        {
            pthread_mutex_lock(&events[t].mutex);
            events[t].ready = 0;
            pthread_mutex_unlock(&events[t].mutex);
            pthread_mutex_lock(&pool.mutex);
            pool.queue[pool.tail++ % MAX_TASKS] = t;
            pthread_cond_signal(&pool.cond);
            pthread_mutex_unlock(&pool.mutex);
        }
        for(int t = 0; t < tasks; t++)
        {
            struct event *e = &events[t];
            pthread_mutex_lock(&e->mutex);
            atomic_store(&producer_waits, t);
            while(!e->ready) pthread_cond_wait(&e->cond, &e->mutex);
            atomic_store(&producer_waits, -1);
            pthread_mutex_unlock(&e->mutex);
        }
        atomic_fetch_add(&batches, 1);
    }
    return NULL;
}

static int clock_steps(int cpus)
{
    for(int cpu = 0; cpu < cpus; cpu++)
    {
        cpu_set_t set;
        CPU_ZERO(&set);
        CPU_SET(cpu, &set);
        if(sched_setaffinity(0, sizeof set, &set)) { printf("FS_CLOCK cpu=%d affinity failed\n", cpu); continue; }
        double start = now(), last = start, max_step = 0;
        long reads = 0;
        for(double t = start; t < start + 0.2; t = now())
        {
            reads++;
            if(t - last > max_step) max_step = t - last;
            last = t;
        }
        printf("FS_CLOCK cpu=%d reads=%ld max_step_us=%.0f\n", cpu, reads, max_step * 1e6);
    }
    return 0;
}

int main(int argc, char **argv)
{
    if(argc > 2 && !strcmp(argv[1], "clock")) return clock_steps(atoi(argv[2]));
    int seconds = argc > 1 ? atoi(argv[1]) : 60;
    int npairs = argc > 2 ? atoi(argv[2]) : 4;
    int workers = argc > 3 ? atoi(argv[3]) : 4;
    if(argc > 4) tasks = atoi(argv[4]);
    if(npairs > MAX_PAIRS) npairs = MAX_PAIRS;
    if(workers > MAX_WORKERS) workers = MAX_WORKERS;
    if(tasks > MAX_TASKS) tasks = MAX_TASKS;
    setvbuf(stdout, NULL, _IOLBF, 0);

    static struct side sides[MAX_PAIRS][2];
    pthread_t threads[2 * MAX_PAIRS + MAX_WORKERS + 1];
    int n = 0;
    for(int i = 0; i < npairs; i++)
    {
        pthread_mutex_init(&pairs[i].mutex, NULL);
        pthread_cond_init(&pairs[i].cond, NULL);
        for(int me = 0; me < 2; me++)
        {
            sides[i][me] = (struct side){ &pairs[i], me };
            pthread_create(&threads[n++], NULL, pair_thread, &sides[i][me]);
        }
    }
    for(int t = 0; t < MAX_TASKS; t++)
    {
        pthread_mutex_init(&events[t].mutex, NULL);
        pthread_cond_init(&events[t].cond, NULL);
    }
    for(int w = 0; w < workers; w++) pthread_create(&threads[n++], NULL, worker_thread, (void *)(long)w);
    pthread_create(&threads[n++], NULL, producer_thread, NULL);

    long last_pp[MAX_PAIRS] = { 0 }, last_pool = 0;
    double since_pp[MAX_PAIRS], since_pool, start = now();
    int stalled_pp[MAX_PAIRS] = { 0 }, stalled_pool = 0, stalls = 0;
    for(int i = 0; i < npairs; i++) since_pp[i] = start;
    since_pool = start;
    for(int second = 1; second <= seconds; second++)
    {
        while(now() < start + second) usleep(50000);
        double t = now();
        char line[512];
        int at = snprintf(line, sizeof line, "FS %d pp=", second);
        for(int i = 0; i < npairs; i++)
        {
            long r = atomic_load(&pairs[i].rounds);
            at += snprintf(line + at, sizeof line - at, "%s%ld", i ? "," : "", r);
            if(r != last_pp[i]) { last_pp[i] = r; since_pp[i] = t; stalled_pp[i] = 0; }
            else if(t - since_pp[i] >= 10 && !stalled_pp[i])
            {
                stalled_pp[i] = 1;
                stalls++;
                printf("FS_STALL pair=%d rounds=%ld turn=%d waiting=%d,%d\n", i, r, pairs[i].turn,
                    atomic_load(&pairs[i].where[0]), atomic_load(&pairs[i].where[1]));
            }
        }
        long b = atomic_load(&batches);
        snprintf(line + at, sizeof line - at, " pool=%ld", b);
        puts(line);
        if(b != last_pool) { last_pool = b; since_pool = t; stalled_pool = 0; }
        else if(t - since_pool >= 10 && !stalled_pool)
        {
            stalled_pool = 1;
            stalls++;
            int task = atomic_load(&producer_waits);
            char where[128] = "";
            for(int w = 0, a = 0; w < workers; w++) a += snprintf(where + a, sizeof where - a, "%d", atomic_load(&worker_where[w]));
            printf("FS_STALL pool batches=%ld producer_waits=%d ready=%d work=%ld queue=%d..%d workers_waiting=%s\n", b, task,
                task >= 0 ? events[task].ready : -1, task >= 0 ? atomic_load(&work[task]) : -1L, pool.head, pool.tail, where);
        }
    }
    printf("FS_DONE stalls=%d\n", stalls);
    // (the threads may be stuck: no joins)
    _exit(stalls ? 1 : 0);
}
                                                                                                                                                                                                                                                          source/v64/tests/a64/android/v86frames.c                                                            0000644 0000000 0000000 00000011214 00000000000 015024  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The library of P12.3's sustained frame rate app (tests/a64/apk.mjs
// build_apk with native, android.app.NativeActivity): on its window, OpenGL
// ES 2 through EGL (ANGLE on the guest's Vulkan), each frame a cleared screen
// and a turning triangle, swapped with the display's pacing, for SECONDS
// seconds; then it logs the frames and their rate (logcat tag v86frames:
// "V86_FRAMES frames=<n> seconds=<s> fps=<f>") and finishes its activity.
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <android/log.h>
#include <android/native_activity.h>
#include <math.h>
#include <pthread.h>
#include <stdatomic.h>
#include <time.h>

#define SECONDS 60
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "v86frames", __VA_ARGS__)

static ANativeActivity *the_activity;
static ANativeWindow *the_window;
static atomic_int stop;
static pthread_t thread;
static int running;

static double now(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

static GLuint shader(GLenum type, const char *source)
{
    GLuint s = glCreateShader(type);
    glShaderSource(s, 1, &source, NULL);
    glCompileShader(s);
    return s;
}

static void *render(void *unused)
{
    (void)unused;
    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    eglInitialize(display, NULL, NULL);
    const EGLint config_attributes[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE };
    EGLConfig config;
    EGLint count = 0;
    eglChooseConfig(display, config_attributes, &config, 1, &count);
    const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
    EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attributes);
    EGLSurface surface = eglCreateWindowSurface(display, config, the_window, NULL);
    if(!count || context == EGL_NO_CONTEXT || surface == EGL_NO_SURFACE || !eglMakeCurrent(display, surface, surface, context))
    {
        LOG("V86_FRAMES error=egl 0x%x", eglGetError());
        ANativeActivity_finish(the_activity);
        return NULL;
    }
    GLuint program = glCreateProgram();
    glAttachShader(program, shader(GL_VERTEX_SHADER,
        "attribute vec2 p; uniform float a; void main() { gl_Position = vec4(cos(a) * p.x - sin(a) * p.y, sin(a) * p.x + cos(a) * p.y, 0.0, 1.0); }"));
    glAttachShader(program, shader(GL_FRAGMENT_SHADER, "precision mediump float; void main() { gl_FragColor = vec4(1.0, 0.8, 0.2, 1.0); }"));
    glBindAttribLocation(program, 0, "p");
    glLinkProgram(program);
    glUseProgram(program);
    const GLfloat triangle[] = { 0.0f, 0.6f, -0.5f, -0.4f, 0.5f, -0.4f };
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, triangle);
    glEnableVertexAttribArray(0);
    GLint angle = glGetUniformLocation(program, "a");
    LOG("V86_FRAMES start renderer=%s", (const char *)glGetString(GL_RENDERER));
    double start = now(), last = start;
    int frames = 0, frames_last = 0;
    while(!atomic_load(&stop) && now() - start < SECONDS)
    {
        double t = now() - start;
        glClearColor(0.1f, 0.2f + 0.2f * (float)sin(t), 0.4f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        glUniform1f(angle, (float)t);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        eglSwapBuffers(display, surface);
        frames++;
        if(now() - last >= 10)
        {
            LOG("V86_FRAMES progress frames=%d fps=%.2f", frames, (frames - frames_last) / (now() - last));
            last = now();
            frames_last = frames;
        }
    }
    double seconds = now() - start;
    LOG("V86_FRAMES frames=%d seconds=%.1f fps=%.2f", frames, seconds, frames / seconds);
    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    eglDestroySurface(display, surface);
    eglDestroyContext(display, context);
    ANativeActivity_finish(the_activity);
    return NULL;
}

static void window_created(ANativeActivity *activity, ANativeWindow *window)
{
    (void)activity;
    if(running) return;
    the_window = window;
    running = 1;
    atomic_store(&stop, 0);
    pthread_create(&thread, NULL, render, NULL);
}

static void window_destroyed(ANativeActivity *activity, ANativeWindow *window)
{
    (void)activity;
    (void)window;
    if(!running) return;
    atomic_store(&stop, 1);
    pthread_join(thread, NULL);
    running = 0;
}

void ANativeActivity_onCreate(ANativeActivity *activity, void *saved_state, size_t saved_state_size)
{
    (void)saved_state;
    (void)saved_state_size;
    the_activity = activity;
    activity->callbacks->onNativeWindowCreated = window_created;
    activity->callbacks->onNativeWindowDestroyed = window_destroyed;
}
                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/a64/android/v86native.c                                                            0000644 0000000 0000000 00000001135 00000000000 015036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The library of P12.1's native APK test (tests/a64/apk.mjs build_apk with
// native, android.app.NativeActivity): loaded, it logs the page size it runs
// with (logcat tag v86native), then finishes its activity.
#include <android/log.h>
#include <android/native_activity.h>
#include <unistd.h>

void ANativeActivity_onCreate(ANativeActivity *activity, void *saved_state, size_t saved_state_size)
{
    (void)saved_state;
    (void)saved_state_size;
    __android_log_print(ANDROID_LOG_INFO, "v86native", "V86_NATIVE_LOADED page_size=%ld", sysconf(_SC_PAGESIZE));
    ANativeActivity_finish(activity);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/android/v86tone.c                                                              0000644 0000000 0000000 00000006031 00000000000 014515  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The library of P12.5's framework sound check (tests/a64/apk.mjs build_apk
// with native, android.app.NativeActivity): an AAudio output stream (media,
// 48 kHz stereo 16-bit) playing a 1 kHz tone for SECONDS seconds, through
// AudioFlinger and the audio HAL to the device's card; then it logs what it
// wrote (logcat tag v86tone: "V86_TONE frames=<n> rate=<hz> channels=<n>",
// or "V86_TONE error=<text>") and finishes its activity.
#include <aaudio/AAudio.h>
#include <android/log.h>
#include <android/native_activity.h>
#include <math.h>
#include <pthread.h>
#include <stdint.h>

#define SECONDS 2
#define FREQUENCY 1000
#define LOG(...) __android_log_print(ANDROID_LOG_INFO, "v86tone", __VA_ARGS__)

static ANativeActivity *the_activity;

static void *play(void *unused)
{
    (void)unused;
    AAudioStreamBuilder *builder;
    AAudioStream *stream = NULL;
    aaudio_result_t r = AAudio_createStreamBuilder(&builder);
    if(r == AAUDIO_OK)
    {
        AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
        AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
        AAudioStreamBuilder_setChannelCount(builder, 2);
        AAudioStreamBuilder_setSampleRate(builder, 48000);
        AAudioStreamBuilder_setUsage(builder, AAUDIO_USAGE_MEDIA);
        r = AAudioStreamBuilder_openStream(builder, &stream);
        AAudioStreamBuilder_delete(builder);
    }
    if(r == AAUDIO_OK) r = AAudioStream_requestStart(stream);
    if(r != AAUDIO_OK)
    {
        LOG("V86_TONE error=%s", AAudio_convertResultToText(r));
        if(stream) AAudioStream_close(stream);
        ANativeActivity_finish(the_activity);
        return NULL;
    }
    int32_t rate = AAudioStream_getSampleRate(stream), channels = AAudioStream_getChannelCount(stream);
    int16_t buffer[2 * 480];
    int64_t frames = 0, total = (int64_t)rate * SECONDS;
    while(frames < total)
    {
        for(int i = 0; i < 480; i++)
        {
            int16_t v = (int16_t)(16000 * sin(2 * M_PI * FREQUENCY * (double)(frames + i) / rate));
            buffer[2 * i] = v;
            buffer[2 * i + 1] = v;
        }
        aaudio_result_t written = AAudioStream_write(stream, buffer, 480, 2000000000LL);
        if(written < 0)
        {
            LOG("V86_TONE error=%s", AAudio_convertResultToText(written));
            break;
        }
        frames += written;
    }
    // (until the stream has played what it holds)
    AAudioStream_requestStop(stream);
    aaudio_stream_state_t state = AAUDIO_STREAM_STATE_STOPPING;
    AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_STOPPING, &state, 2000000000LL);
    AAudioStream_close(stream);
    LOG("V86_TONE frames=%lld rate=%d channels=%d", (long long)frames, rate, channels);
    ANativeActivity_finish(the_activity);
    return NULL;
}

void ANativeActivity_onCreate(ANativeActivity *activity, void *saved_state, size_t saved_state_size)
{
    (void)saved_state;
    (void)saved_state_size;
    the_activity = activity;
    pthread_t thread;
    pthread_create(&thread, NULL, play, NULL);
    pthread_detach(thread);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/a64/android/vkahb.c                                                                0000644 0000000 0000000 00000023256 00000000000 014307  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // An AHardwareBuffer drawn by Vulkan and read by the CPU (P11.4 V2): what
// ANGLE, SurfaceFlinger and HWUI do with gralloc's buffers. The buffer is
// allocated by gralloc (minigbm), imported into Vulkan (venus turns it into
// VkImportMemoryResourceInfoMESA: the virtio-gpu resource), cleared to a
// known colour on the GPU, handed back (the foreign queue family) and read
// through AHardwareBuffer_lock. Prints each step and PASS or FAIL.
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_android.h>

// (the VNDK's: libnativewindow exports it, the NDK neither declares nor links it)
typedef struct native_handle { int version, numFds, numInts, data[]; } native_handle_t;
typedef const native_handle_t *(*get_native_handle_t)(const AHardwareBuffer *buffer);

#define CHECK(call) do { VkResult r_ = (call); if(r_ != VK_SUCCESS) { printf("FAIL %s: %d\n", #call, r_); return 1; } } while(0)

static const uint32_t WIDTH = 64, HEIGHT = 64;

int main(void)
{
    AHardwareBuffer_Desc desc = {
        .width = WIDTH, .height = HEIGHT, .layers = 1, .format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
        .usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
            AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN,
    };
    AHardwareBuffer *buffer = NULL;
    if(AHardwareBuffer_allocate(&desc, &buffer) != 0) { printf("FAIL AHardwareBuffer_allocate\n"); return 1; }
    AHardwareBuffer_describe(buffer, &desc);
    printf("ahb: %ux%u stride %u format %u\n", desc.width, desc.height, desc.stride, desc.format);
    // (gralloc's handle, word by word: the layout Mesa's gralloc helper reads)
    get_native_handle_t get_native_handle = (get_native_handle_t)dlsym(dlopen("libnativewindow.so", RTLD_NOW), "AHardwareBuffer_getNativeHandle");
    const native_handle_t *handle = get_native_handle ? get_native_handle(buffer) : NULL;
    if(handle)
    {
        printf("handle: version %d, %d fds, %d ints:", handle->version, handle->numFds, handle->numInts);
        for(int i = 0; i < handle->numFds + handle->numInts; i++) printf(" %08x", (unsigned)handle->data[i]);
        printf("\n");
    }

    VkApplicationInfo app = { VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "vkahb", 1, NULL, 0, VK_API_VERSION_1_1 };
    VkInstanceCreateInfo instance_info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &app, 0, NULL, 0, NULL };
    VkInstance instance;
    CHECK(vkCreateInstance(&instance_info, NULL, &instance));
    uint32_t count = 1;
    VkPhysicalDevice physical;
    CHECK(vkEnumeratePhysicalDevices(instance, &count, &physical));
    if(!count) { printf("FAIL no Vulkan device\n"); return 1; }
    VkPhysicalDeviceProperties properties;
    vkGetPhysicalDeviceProperties(physical, &properties);
    printf("device: %s\n", properties.deviceName);

    // (the rest of what the AHardwareBuffer extension needs is Vulkan 1.1's)
    const char *extensions[] = {
        VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME,
    };
    // (the extensions the device lacks, if any)
    uint32_t available_count = 0;
    vkEnumerateDeviceExtensionProperties(physical, NULL, &available_count, NULL);
    VkExtensionProperties available[512];
    if(available_count > 512) available_count = 512;
    vkEnumerateDeviceExtensionProperties(physical, NULL, &available_count, available);
    for(size_t i = 0; i < sizeof(extensions) / sizeof(extensions[0]); i++)
    {
        int found = 0;
        for(uint32_t j = 0; j < available_count; j++) found |= !strcmp(available[j].extensionName, extensions[i]);
        if(!found) printf("missing: %s\n", extensions[i]);
    }
    float priority = 1;
    VkDeviceQueueCreateInfo queue_info = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, NULL, 0, 0, 1, &priority };
    VkDeviceCreateInfo device_info = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, NULL, 0, 1, &queue_info, 0, NULL,
        sizeof(extensions) / sizeof(extensions[0]), extensions, NULL };
    VkDevice device;
    CHECK(vkCreateDevice(physical, &device_info, NULL, &device));
    VkQueue queue;
    vkGetDeviceQueue(device, 0, 0, &queue);

    PFN_vkGetAndroidHardwareBufferPropertiesANDROID get_properties =
        (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vkGetDeviceProcAddr(device, "vkGetAndroidHardwareBufferPropertiesANDROID");
    VkAndroidHardwareBufferFormatPropertiesANDROID format = { VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID };
    VkAndroidHardwareBufferPropertiesANDROID buffer_properties = { VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, &format };
    CHECK(get_properties(device, buffer, &buffer_properties));
    printf("ahb properties: size %llu, memory types 0x%x, format %d\n",
        (unsigned long long)buffer_properties.allocationSize, buffer_properties.memoryTypeBits, format.format);

    VkExternalMemoryImageCreateInfo external = { VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, NULL,
        VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID };
    VkImageCreateInfo image_info = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, &external, 0, VK_IMAGE_TYPE_2D,
        VK_FORMAT_R8G8B8A8_UNORM, { WIDTH, HEIGHT, 1 }, 1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL,
        VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
        VK_SHARING_MODE_EXCLUSIVE, 0, NULL, VK_IMAGE_LAYOUT_UNDEFINED };
    VkImage image;
    CHECK(vkCreateImage(device, &image_info, NULL, &image));

    VkMemoryDedicatedAllocateInfo dedicated = { VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, NULL, image, VK_NULL_HANDLE };
    VkImportAndroidHardwareBufferInfoANDROID import = { VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, &dedicated, buffer };
    uint32_t type = 0;
    while(type < 32 && !(buffer_properties.memoryTypeBits & 1u << type)) type++;
    VkMemoryAllocateInfo allocate = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &import, buffer_properties.allocationSize, type };
    VkDeviceMemory memory;
    CHECK(vkAllocateMemory(device, &allocate, NULL, &memory));
    CHECK(vkBindImageMemory(device, image, memory, 0));
    printf("imported: memory type %u\n", type);

    VkCommandPoolCreateInfo pool_info = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL, 0, 0 };
    VkCommandPool pool;
    CHECK(vkCreateCommandPool(device, &pool_info, NULL, &pool));
    VkCommandBufferAllocateInfo command_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 };
    VkCommandBuffer commands;
    CHECK(vkAllocateCommandBuffers(device, &command_info, &commands));
    VkCommandBufferBeginInfo begin = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL };
    CHECK(vkBeginCommandBuffer(commands, &begin));
    VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
    VkImageMemoryBarrier to_clear = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
        VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, range };
    vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &to_clear);
    VkClearColorValue colour = { .float32 = { 0.25f, 0.5f, 0.75f, 1.0f } };
    vkCmdClearColorImage(commands, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &colour, 1, &range);
    // (released to the foreign queue family: the CPU and other users of the buffer)
    VkImageMemoryBarrier release = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, 0,
        VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, 0, VK_QUEUE_FAMILY_FOREIGN_EXT, image, range };
    vkCmdPipelineBarrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &release);
    CHECK(vkEndCommandBuffer(commands));
    VkFenceCreateInfo fence_info = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, 0 };
    VkFence fence;
    CHECK(vkCreateFence(device, &fence_info, NULL, &fence));
    VkSubmitInfo submit = { VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &commands, 0, NULL };
    CHECK(vkQueueSubmit(queue, 1, &submit, fence));
    CHECK(vkWaitForFences(device, 1, &fence, VK_TRUE, 60ull * 1000 * 1000 * 1000));
    printf("cleared\n");

    void *pixels = NULL;
    if(AHardwareBuffer_lock(buffer, AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN, -1, NULL, &pixels) != 0 || !pixels)
    {
        printf("FAIL AHardwareBuffer_lock\n");
        return 1;
    }
    const uint8_t expected[4] = { 64, 128, 191, 255 };
    int bad = 0;
    for(uint32_t y = 0; y < HEIGHT; y++)
    {
        for(uint32_t x = 0; x < WIDTH; x++)
        {
            const uint8_t *p = (const uint8_t *)pixels + (y * desc.stride + x) * 4;
            for(int c = 0; c < 4; c++)
            {
                // (0.75 may round to 191 or 192)
                if(p[c] < expected[c] - 1 || p[c] > expected[c] + 1)
                {
                    if(bad++ < 4) printf("pixel %u,%u: %u %u %u %u\n", x, y, p[0], p[1], p[2], p[3]);
                    break;
                }
            }
        }
    }
    const uint8_t *first = (const uint8_t *)pixels;
    printf("pixel 0,0: %u %u %u %u\n", first[0], first[1], first[2], first[3]);
    AHardwareBuffer_unlock(buffer, NULL);
    printf(bad ? "FAIL %d pixels differ\n" : "PASS\n", bad);

    vkDestroyFence(device, fence, NULL);
    vkDestroyCommandPool(device, pool, NULL);
    vkDestroyImage(device, image, NULL);
    vkFreeMemory(device, memory, NULL);
    vkDestroyDevice(device, NULL);
    vkDestroyInstance(instance, NULL);
    AHardwareBuffer_release(buffer);
    return bad ? 1 : 0;
}
                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/a64/android/vkprobe.c                                                              0000644 0000000 0000000 00000002522 00000000000 014655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Vulkan devices the system loader finds (P11.4 V1): instance, physical
// devices and their properties, on stdout.
#include <stdio.h>
#include <vulkan/vulkan.h>

int main(void)
{
    VkApplicationInfo app = { VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "vkprobe", 1, NULL, 0, VK_API_VERSION_1_1 };
    VkInstanceCreateInfo info = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &app, 0, NULL, 0, NULL };
    VkInstance instance;
    VkResult result = vkCreateInstance(&info, NULL, &instance);
    printf("vkCreateInstance: %d\n", result);
    if(result != VK_SUCCESS) return 1;
    uint32_t count = 0;
    result = vkEnumeratePhysicalDevices(instance, &count, NULL);
    printf("vkEnumeratePhysicalDevices: %d, %u devices\n", result, count);
    VkPhysicalDevice devices[8];
    if(count > 8) count = 8;
    vkEnumeratePhysicalDevices(instance, &count, devices);
    for(uint32_t i = 0; i < count; i++)
    {
        VkPhysicalDeviceProperties p;
        vkGetPhysicalDeviceProperties(devices[i], &p);
        printf("device %u: %s, Vulkan %u.%u.%u, driver 0x%x, vendor 0x%x, device 0x%x, type %d\n", i, p.deviceName,
            VK_VERSION_MAJOR(p.apiVersion), VK_VERSION_MINOR(p.apiVersion), VK_VERSION_PATCH(p.apiVersion),
            p.driverVersion, p.vendorID, p.deviceID, p.deviceType);
    }
    vkDestroyInstance(instance, NULL);
    return 0;
}
                                                                                                                                                                              source/v64/tests/a64/android_boot.mjs                                                               0000644 0000000 0000000 00000145612 00000000000 014607  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Android 16 on the virt machine (docs/arm64-virt-android16-plan.md P10.3,
// P10.7, P11): tools/a64_android.mjs's Image, initrd.img and disk.img (the
// pinned Cuttlefish arm64-only phone, direct kernel boot, unlocked, SELinux
// enforcing) booted on the QEMU reference or on v86. The first boot each
// time: the disk's writes stay in memory (QEMU's snapshot=on, v86's buffer)
// for as long as the machine runs, across its reboots.
//
// QEMU (A64_ANDROID_TARGET=qemu, the default): tests/a64/android_qemu.mjs's
// machine, cortex-a35 under TCG (A64_ANDROID_ACCEL=hvf: the host's CPU, for
// quick runs). Passes when the Android console answers
// `getprop sys.boot_completed` with 1. A64_QEMU_PLUGINS=1 counts the
// instructions to that point (libinsn, and libhowvec's classes), for
// P10.3's budget.
//
// v86 (A64_ANDROID_TARGET=v86): the same materials and the devices in the
// same PCI order (virtio-blk 00:01.0, virtio-gpu 00:02.0 at 720x1280, three
// virtio-net (the third, under Cuttlefish's Wi-Fi, on the fetch adapter), 18
// console ports with the kernel's console on hvc0 and logcat on hvc2, rng,
// a keyboard and a multitouch screen, vsock), RAM above 1536 MiB as extended
// RAM. Passes when system_server has started and adbd answers over
// vsock:5555 (tests/a64/adb.mjs; A8's acceptance), and reports how far the
// boot got by the deadline (A64_ANDROID_WAIT=boot_completed: until
// sys.boot_completed=1). The fetch adapter only reaches the test's own
// server: every other URL is refused, nothing leaves the host.
//
// A64_ANDROID_SCENARIO=a9 (either target): after boot_completed, A9's
// acceptance (tests/a64/android_scenario.mjs): the desktop, the network,
// touch (v86), an app installed and started, a reboot with /data kept. On
// QEMU adb goes to tcp:5555 on Wi-Fi through a forwarded port once the
// console has turned Wi-Fi on; screenshots come from the monitor's screendump
// (QEMU) or the display (v86), into the run's directory.
//
//   A64_CORES (4), A64_MEMORY_MB (1536: about 1 GiB is the least that boots, P10.3), A64_JIT=1 (the page tier),
//   A64_PARALLEL=1 (vCPU workers), A64_ANDROID_GPU=venus (v86: virtio-gpu with Venus, the renderer in a headless
//   Chrome, the guest's driver initrd-venus.img's), A64_ANDROID_SAVE_STATE=<file> / A64_ANDROID_RESTORE_STATE=<file> (v86: a state after boot_completed, saved
//   or restored instead of booting), A64_ANDROID_TIMEOUT (ms), A64_ANDROID_PROBE=<file> (shell commands to run
//   over adb after boot_completed, one per line, with their output; A64_ANDROID_PUSH=<local>=<remote>,... first),
//   A64_ANDROID_PAGE_SIZE=16k (P12.1: tools/a64_android.mjs --page-size 16k's materials, build/a64-android/out-16k/; the
//   guest's page size and kernel are checked over adb or the console; A64_ANDROID_SCENARIO=pagesize records how native
//   APKs aligned to 4 and 16 KiB fare, android_scenario.mjs), A64_ANDROID_SCENARIO=cts (P12.3's CTS subset, android_cts.mjs;
//   A64_ANDROID_CTS_MODULES=<module>,... and A64_ANDROID_CTS_FILTER=<module>=<gtest filter>;... to try parts of it),
//   A64_ANDROID_SCENARIO=deqp (appendix F6: a dEQP subset through CtsDeqpTestCases's APK, android_deqp.mjs;
//   A64_ANDROID_DEQP=<package>=<prefix>,...;... for other cases), A64_ANDROID_SCENARIO=compat32 (the aarch32
//   plan's Q5.2: 32-bit apps on tools/a64_android.mjs --build a14's materials, A64_ANDROID_OUT=build/a64-android/out-a14;
//   on v86 with A64_PROFILE=v3, which has AArch32 at EL0; QEMU's cortex-a35 has it, HVF does not),
//   A64_PROFILE=v1.1 (the CPU profile without FEAT_PAN; v2, the default, has it), TEST_RELEASE_BUILD=1 (build/libv86.mjs),
//   A64_ANDROID_BOOTLOADER=1 (v86: the android option, the kernel and initrd from the disk),
//   A64_ANDROID_OUT=<dir> (tools/a64_android.mjs --out's materials in place of out/ or out-16k/), A64_ANDROID_CONSOLE=0 (QEMU:
//   a user build, such as a GSI with the release vendor ramdisk, has no console; boot_completed from the kernel's log)
// Logs: build/a64-android/runs/<tag>/ (kernel.log, logcat.log, console.log, *.png, result.json)
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import net from "node:net";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { android_qemu_args, AndroidConsole, qemu_screendump, qmp_connect, qemu_touch, qemu_picture_digest } from "./android_qemu.mjs";
import { createHash as create_hash } from "node:crypto";
import { qemu_binary } from "./guest_runner.mjs";
import { AdbClient } from "./adb.mjs";
import { a9_scenario, a10_scenario, pagesize_scenario, compat32_scenario, prepare_device, PREPARE_COMMAND, device_prepared } from "./android_scenario.mjs";
import { cts_scenario } from "./android_cts.mjs";
import { deqp_scenario } from "./android_deqp.mjs";
import { PictureSink, save_png } from "../lib/picture_sink.mjs";
import { create_remote_renderer } from "../x64/gpu_remote_renderer.mjs";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const page_size = { "": 4096, "4k": 4096, "16k": 16384 }[process.env.A64_ANDROID_PAGE_SIZE || ""];
assert.ok(page_size, "A64_ANDROID_PAGE_SIZE: 4k or 16k");
// (A64_ANDROID_OUT=<dir>: another tools/a64_android.mjs output, as --out gave it: --release --no-venus's, --gsi's)
const OUT = process.env.A64_ANDROID_OUT ? path.resolve(process.env.A64_ANDROID_OUT) + "/" :
    ROOT + (page_size === 4096 ? "build/a64-android/out/" : "build/a64-android/out-16k/");
for(const file of ["Image", "initrd.img", "disk.img", "cmdline.txt"])
{
    assert.ok(fs.existsSync(OUT + file), OUT + file + ` is missing: node tools/a64_android.mjs --download${page_size === 4096 ? "" : " --page-size 16k"}`);
}
/** the page size and kernel release the guest reports ("S=<getconf PAGE_SIZE> K=<uname -r>"), checked */
function check_page_size(output)
{
    const m = /S=(\d+) K=(\S+)/.exec(output);
    assert.ok(m && +m[1] === page_size, `the guest's page size: ${JSON.stringify(output)}, expected ${page_size}`);
    return { page_size: +m[1], kernel_release: m[2] };
}
const target = process.env.A64_ANDROID_TARGET || "qemu";
assert.ok(target === "qemu" || target === "v86", "A64_ANDROID_TARGET: qemu or v86");
const accel = process.env.A64_ANDROID_ACCEL || "tcg";
const cores = +process.env.A64_CORES || 4;
const memory_mb = +process.env.A64_MEMORY_MB || 1536;
const plugins = !!+process.env.A64_QEMU_PLUGINS;
const jit = !!+process.env.A64_JIT;
const parallel = !!+process.env.A64_PARALLEL;
const scenario = process.env.A64_ANDROID_SCENARIO || "";
// A64_ANDROID_BOOTLOADER=1 (v86): the android option in place of kernel, initrd and cmdline: v64's
// bootloader reads them from disk.img (docs/android-images-plan.md I2.3), the vendor ramdisk the tool's
const bootloader = !!+process.env.A64_ANDROID_BOOTLOADER;
assert.ok(!bootloader || target === "v86" && page_size === 4096, "A64_ANDROID_BOOTLOADER=1: v86, 4K (the 16K kernel is not on the disk)");
// A64_ANDROID_CONSOLE=0 (QEMU): no console (a user build's: ro.debuggable=0), boot_completed from the kernel's log
const use_console = process.env.A64_ANDROID_CONSOLE !== "0";
assert.ok(use_console || target === "qemu" && !scenario && !process.env.A64_ANDROID_PROBE, "A64_ANDROID_CONSOLE=0: QEMU, no scenario or probes");
assert.ok(!scenario || ["a9", "a10", "pagesize", "cts", "deqp", "compat32"].includes(scenario), "A64_ANDROID_SCENARIO: a9, a10, pagesize, cts, deqp or compat32");
assert.ok(!scenario || !plugins, "A64_ANDROID_SCENARIO and A64_QEMU_PLUGINS do not go together");
const wait_for_boot_completed = target === "qemu" || !!scenario || process.env.A64_ANDROID_WAIT === "boot_completed";
const tag = (target === "qemu" ? `qemu-${accel}${plugins ? "-plugins" : ""}` : `v86${jit ? "-jit" : ""}${parallel ? "-par" : ""}`) +
    `${process.env.A64_ANDROID_GPU ? "-" + process.env.A64_ANDROID_GPU : ""}${scenario ? "-" + scenario : ""}${page_size === 4096 ? "" : "-16k"}${bootloader ? "-bl" : ""}-${memory_mb}m-${cores}c` +
    (process.env.A64_ANDROID_OUT ? "-" + path.basename(OUT) : "");
const timeout = +process.env.A64_ANDROID_TIMEOUT || (target === "qemu" && !scenario ? (accel === "hvf" ? 600000 : plugins ? 14400000 : 3600000) : 14400000);
const directory = ROOT + `build/a64-android/runs/${tag}/`;
fs.mkdirSync(directory, { recursive: true });
const started = performance.now();
const elapsed = () => Math.round(performance.now() - started);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const marks = {};
const mark = (name, text) =>
{
    if(marks[name] === undefined)
    {
        marks[name] = elapsed();
        console.log(`${(marks[name] / 1000).toFixed(1)} s: ${name}${text ? " " + text : ""}`);
    }
};
/** boot milestones in the kernel's log (hvc0) and logcat (hvc2) */
const MILESTONES = [
    ["first_stage", /init: init first stage started/],
    ["second_stage", /init: init second stage started/],
    ["zygote", /init: starting service 'zygote'/],
    ["system_server", /SystemServer: Entered the Android system server/],
    ["adbd", /init: starting service 'adbd'/],
    ["boot_animation", /init: starting service 'bootanim'/],
    ["boot_completed", /init: processing action \(sys\.boot_completed=1\)/],
];
const watch = (name, file) =>
{
    let text = "";
    const out = fs.openSync(directory + file, "w");
    return bytes =>
    {
        fs.writeSync(out, bytes);
        // (the new bytes with the end of the old ones, for lines split between them)
        const window = text + Buffer.from(bytes).toString("latin1");
        for(const [milestone, pattern] of MILESTONES) if(marks[milestone] === undefined && pattern.test(window)) mark(milestone);
        const panic = /Kernel panic[^\n]*/.exec(window);
        if(panic) fail(new Error(panic[0]));
        // (init's fatal errors reboot into the bootloader: an SELinux policy that does not compile, ...)
        if(/reboot: Restarting system with command 'bootloader'/.test(window)) fail(new Error("the guest rebooted into the bootloader (init failed: kernel.log)"));
        text = window.slice(-512);
    };
};
let fail;
const failed = new Promise((_, reject) => { fail = reject; });
failed.catch(() => {});

/**
 * adb over a byte stream that open() makes: a shell command's output, and
 * push; each a new connection, retried (adbd is away while the guest boots
 * or reboots) for up to retry_ms
 */
function adb_over(open, retry_ms = 600000)
{
    const session = async (fn, ms) => {
        const deadline = Date.now() + retry_ms;
        for(;;)
        {
            let stream;
            try
            {
                stream = await open();
                const client = new AdbClient(stream.adapter);
                await client.connect(60000);
                return await fn(client, ms);
            }
            catch(e)
            {
                if(Date.now() > deadline || /deadline|panic/.test(e.message)) throw e;
                await sleep(5000);
            }
            finally
            {
                stream?.close();
            }
        }
    };
    return {
        shell: (command, ms = 120000) => session((client, ms) => client.shell(command, ms), ms),
        push: (remote, bytes) => session(client => client.push(remote, bytes)),
        banner: () => session(client => client.banner),
        // (once: "reboot" must not run again on the rebooted guest)
        reboot: async () => {
            const stream = await open();
            try
            {
                const client = new AdbClient(stream.adapter);
                await client.connect(60000);
                await client.shell("reboot", 30000).catch(() => {});
            }
            finally
            {
                stream.close();
            }
        },
    };
}

/** the scenario's result, with its screenshots, into the result */
// A64_ANDROID_PROBE=<file>: after boot_completed, each line of the file a
// shell command over adb, with its time, length and output (debugging); a
// line "@screenshot <name>" saves the display as <name>.png;
// A64_ANDROID_PUSH=<local>=<remote>,...: files pushed first
const probe_file = process.env.A64_ANDROID_PROBE || "";
/** the rows whose change ends a timed tap (below the status bar, above the navigation bar) */
const LATENCY_ROWS = [300, 1000];
// A64_ANDROID_A10_MONKEY_MINUTES: A10's long run (30, P10.3's budget)
const monkey_minutes = +process.env.A64_ANDROID_A10_MONKEY_MINUTES || 30;
// A64_ANDROID_A10_STEPS=<step>,...: only these of A10's steps after the desktop (touch, frames, sound, monkey, memory; all by default)
const a10_steps = process.env.A64_ANDROID_A10_STEPS ? process.env.A64_ANDROID_A10_STEPS.split(",") : null;
async function run_probes(shell, push, screenshot)
{
    if(!probe_file) return;
    for(const pair of (process.env.A64_ANDROID_PUSH || "").split(",").filter(Boolean))
    {
        const [local, remote] = pair.split("=");
        await push(remote, fs.readFileSync(local));
        console.log(`push: ${local} -> ${remote}`);
    }
    let probe_number = 0;
    for(const command of fs.readFileSync(probe_file, "utf8").split("\n").filter(line => line.trim() && !line.startsWith("#")))
    {
        if(command.startsWith("@screenshot "))
        {
            console.log(`probe: screenshot ${await screenshot(command.slice(12).trim())}`);
            continue;
        }
        const start = Date.now();
        let output;
        try { output = await shell(command, 900000); }
        catch(e) { output = "(error: " + e.message + ")"; }
        // (the whole output in the run's directory, probe-<n>.txt)
        fs.writeFileSync(directory + `probe-${++probe_number}.txt`, command + "\n\n" + output);
        console.log(`probe: ${command}\n  ${Date.now() - start} ms, ${output.length} chars: ${JSON.stringify(output.slice(0, 4000))}`);
    }
}

async function run_scenario(env, result)
{
    console.log("scenario " + scenario);
    // (cts: A64_ANDROID_CTS_MODULES=<module>,... some of the subset only; A64_ANDROID_CTS_FILTER=<module>=<gtest filter>;...)
    const cts = env => cts_scenario(env, {
        modules: process.env.A64_ANDROID_CTS_MODULES ? process.env.A64_ANDROID_CTS_MODULES.split(",") : undefined,
        filter: process.env.A64_ANDROID_CTS_FILTER ? Object.fromEntries(process.env.A64_ANDROID_CTS_FILTER.split(";").map(f => f.split(/=(.*)/s).slice(0, 2))) : undefined });
    const found = await ({ a9: a9_scenario, a10: a10_scenario, pagesize: pagesize_scenario, cts, deqp: deqp_scenario, compat32: compat32_scenario })[scenario]({ ...env,
        log: text => console.log(`${(elapsed() / 1000).toFixed(0)} s: ${scenario}: ${text}`) });
    result[scenario] = found;
    mark(scenario + "_done");
    if(scenario === "cts") assert.ok(found.passed, "the CTS subset: " + JSON.stringify(found.modules));
    if(scenario === "deqp") assert.ok(found.passed, "the dEQP subset: " + JSON.stringify(found.packages).slice(0, 4000));
}

if(target === "qemu")
{
    const qemu = qemu_binary();
    const socket = `/tmp/v86-a64-android-${process.pid}.sock`, monitor = `/tmp/v86-a64-android-${process.pid}-m.sock`;
    const qmp_socket = `/tmp/v86-a64-android-${process.pid}-q.sock`;
    const adb_port = 15600 + process.pid % 1000;
    const args = android_qemu_args(OUT, { accel, memory_mb, cores, console_socket: socket,
        kernel_log: directory + "kernel.log", logcat: directory + "logcat.log",
        ...(scenario || probe_file ? { monitor_socket: monitor, adb_port } : {}), ...(scenario === "a10" ? { qmp_socket } : {}),
        sound_wav: directory + "sound.wav" });
    const plugin_log = directory + "plugins.log";
    if(plugins)
    {
        assert.equal(accel, "tcg", "A64_QEMU_PLUGINS: under TCG");
        const qemu_build = path.dirname(qemu) + "/../../qemu-9.2.0/build/";
        const library = name => [".dylib", ".so"].map(suffix => qemu_build + name + suffix).find(file => fs.existsSync(file));
        const insn = library("tests/tcg/plugins/libinsn"), howvec = library("contrib/plugins/libhowvec");
        assert.ok(insn && howvec, "QEMU's insn and howvec plugins are missing: tools/a64_qemu/build.sh");
        // (libinsn counting inline; no -icount, which would serialize the
        // four vCPUs onto one thread: hours under the plugins. Time-driven
        // waits then run longer than without them, so the counts are an
        // upper bound)
        args.push("-plugin", insn + ",inline=on", "-plugin", howvec, "-d", "plugin", "-D", plugin_log);
    }
    const child = spawn(qemu, args, { stdio: ["ignore", "inherit", "inherit"] });
    const exited = new Promise(resolve => child.on("exit", resolve));
    // (the logs are QEMU's files: followed by polling)
    const follow = (file, on_bytes) =>
    {
        let at = 0;
        return setInterval(() => {
            if(!fs.existsSync(directory + file)) return;
            const size = fs.statSync(directory + file).size;
            if(size <= at) return;
            const fd = fs.openSync(directory + file, "r"), bytes = Buffer.alloc(size - at);
            fs.readSync(fd, bytes, 0, bytes.length, at);
            fs.closeSync(fd);
            at = size;
            on_bytes(bytes);
        }, 1000);
    };
    const kernel_watch = watch("kernel", "kernel-watch.log"), logcat_watch = watch("logcat", "logcat-watch.log");
    const timers = [follow("kernel.log", kernel_watch), follow("logcat.log", logcat_watch)];
    const terminal = new AndroidConsole(socket);
    try
    {
        if(!use_console)
        {
            // (a user build has no console: boot_completed from init's line in the kernel's log)
            const qemu_failed = exited.then(code => { throw new Error("QEMU exited " + code); });
            qemu_failed.catch(() => {});
            await Promise.race([(async () => { while(marks.boot_completed === undefined) await sleep(1000); })(), failed, qemu_failed,
                new Promise((_, reject) => setTimeout(() => reject(new Error(`no sys.boot_completed=1 in the kernel's log in ${timeout} ms`)), timeout))]);
            const result = { tag, console: false, marks, ms: elapsed() };
            child.kill("SIGKILL");
            await exited;
            fs.writeFileSync(directory + "result.json", JSON.stringify(result, null, 2) + "\n");
            console.log(JSON.stringify(result));
            console.log(`A64_ANDROID_BOOT_OK ${tag}`);
            process.exit(0);
        }
        await terminal.open();
        // (with a scenario, the device's settings from the console as soon as
        // the services take them, as v86 does over adb: on a slow boot the
        // lock screen must be off before SystemUI sets up its keyguard,
        // prepare_device in android_scenario.mjs)
        let prepared = !scenario;
        const until_booted = async () =>
        {
            for(;;)
            {
                if(!prepared)
                {
                    const p = await terminal.run(PREPARE_COMMAND, 60000);
                    if(p && device_prepared(p.output)) { prepared = true; mark("device_prepared"); }
                }
                const r = await terminal.run("getprop sys.boot_completed", 30000);
                if(r && r.output.trim() === "1") return;
                await sleep(5000);
            }
        };
        const qemu_failed = exited.then(code => { throw new Error("QEMU exited " + code); });
        qemu_failed.catch(() => {});
        await Promise.race([until_booted(), failed, qemu_failed,
            new Promise((_, reject) => setTimeout(() => reject(new Error(`no sys.boot_completed=1 in ${timeout} ms`)), timeout))]);
        mark("boot_completed_getprop");
        const fingerprint = (await terminal.run("getprop ro.build.fingerprint")).output.trim();
        const result = { tag, fingerprint, marks, ...check_page_size((await terminal.run("echo S=$(getconf PAGE_SIZE) K=$(uname -r)")).output) };
        console.log(`page size ${result.page_size}, kernel ${result.kernel_release}`);
        if(scenario || probe_file)
        {
            // (Wi-Fi first, from the console: adb reaches the guest through it;
            // a user build's GSI has no su, and the shell may run cmd wifi)
            await terminal.run("S=; command -v su >/dev/null 2>&1 && S='su 0'; " +
                "$S cmd wifi set-wifi-enabled enabled; sleep 10; $S cmd wifi connect-network VirtWifi open", 120000);
            const tcp = () => new Promise((resolve, reject) => {
                const s = net.connect(adb_port, "127.0.0.1");
                s.once("connect", () => {
                    const adapter = { write: bytes => s.write(bytes), on_data: null };
                    s.on("data", bytes => adapter.on_data?.(bytes));
                    s.on("error", () => {});
                    resolve({ adapter, close: () => s.destroy() });
                });
                s.once("error", reject);
            });
            const adb = adb_over(tcp);
            await run_probes(adb.shell, adb.push, name => qemu_screendump(monitor, directory, name));
            if(scenario)
            {
                // (A10: taps through QMP, and their latency to the screen's first change in screendumps)
                const qmp = scenario === "a10" ? await qmp_connect(qmp_socket) : null;
                const touch = qmp ? (x, y) => qemu_touch(qmp, x, y, 720, 1280) : null;
                const digest = () => qemu_picture_digest(monitor, directory + "latency.ppm", LATENCY_ROWS[0], LATENCY_ROWS[1]);
                const tap_latency = touch ? async (x, y) => {
                    const before = await digest();
                    const started = performance.now();
                    await touch(x, y);
                    while(performance.now() - started < 60000)
                    {
                        if(await digest() !== before) return Math.round(performance.now() - started);
                    }
                    return null;
                } : null;
                // (what the sound card played: the WAV's samples written since reset)
                let sound_from = -1;
                const sound = { reset: () => { sound_from = fs.existsSync(directory + "sound.wav") ? fs.statSync(directory + "sound.wav").size : 44; },
                    played: () => {
                        const wav = fs.existsSync(directory + "sound.wav") ? fs.readFileSync(directory + "sound.wav") : Buffer.alloc(0);
                        const from = Math.max(44, sound_from);
                        return wav.subarray(from, from + (wav.length - from & ~3));
                    } };
                await run_scenario({ target, directory, adb: adb.shell, push: adb.push, reboot: adb.reboot,
                    screenshot: name => qemu_screendump(monitor, directory, name), touch, tap_latency, http: null, wait_reboot: () => sleep(30000), monkey_minutes, steps: a10_steps,
                    sound }, result);
                qmp?.close();
            }
        }
        fs.writeFileSync(directory + "console.log", terminal.text);
        terminal.close();
        child.kill(plugins ? "SIGINT" : "SIGKILL");
        await exited;
        result.ms = elapsed();
        if(plugins)
        {
            // (libinsn: "total insns: N"; libhowvec: the classes and their
            // counts, which QEMU may still be writing as it exits)
            await sleep(2000);
            const log = fs.readFileSync(plugin_log, "utf8");
            result.instructions = Number(/total insns: (\d+)/.exec(log)?.[1]);
            result.classes = Object.fromEntries([...log.matchAll(/^Class: (.+?)\s+\((\d+) hits\)/gm)].map(m => [m[1].trim(), +m[2]]));
        }
        fs.writeFileSync(directory + "result.json", JSON.stringify(result, null, 2) + "\n");
        console.log(JSON.stringify(result));
        console.log(`A64_ANDROID_BOOT_OK ${tag}`);
        process.exit(0);
    }
    catch(e)
    {
        fs.writeFileSync(directory + "console.log", terminal.text);
        child.kill("SIGKILL");
        console.error(e);
        console.error("marks: " + JSON.stringify(marks));
        process.exit(1);
    }
    finally
    {
        timers.forEach(clearInterval);
    }
}

// v86
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
// (the fetch adapter's requests: the test's own server only)
const local_fetch = globalThis.fetch;
globalThis.fetch = (url, options) => {
    const target_url = new URL(typeof url === "string" ? url : url.url);
    if(target_url.hostname !== "localhost" && target_url.hostname !== "127.0.0.1")
    {
        return Promise.resolve(new Response("not from this test", { status: 403 }));
    }
    return local_fetch(url, options);
};
const http_token = "v86-a9-" + Math.random().toString(36).slice(2);
const server = http.createServer((request, response) => {
    response.writeHead(200, { "content-type": "text/plain" });
    response.end(`${http_token} ${request.url}\n`);
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const http_port = server.address().port;

// (RAM: below 2 GiB with the display adapter's device memory, the rest extended RAM from 4 GiB)
const LOW_LIMIT_MB = 1536;
const low_mb = Math.min(memory_mb, LOW_LIMIT_MB);
const sink = new PictureSink();
// A64_ANDROID_GPU=venus (v86): virtio-gpu's level with Venus, drawn by the
// renderer in a headless Chrome (tests/x64/gpu_remote_renderer.mjs, GL_CHROME)
// A64_ANDROID_GPU=gfxstream (v86, A64_ANDROID_BOOTLOADER=1): virtio-gpu's
// level gfxstream, the image's own driver (vulkan.ranchu: gpu mode
// gfxstream's bootconfig), docs/gfxstream-plan.md
const gpu_level = process.env.A64_ANDROID_GPU || "";
assert.ok(!gpu_level || gpu_level === "venus" || gpu_level === "gfxstream", "A64_ANDROID_GPU: venus or gfxstream");
assert.ok(gpu_level !== "gfxstream" || bootloader, "A64_ANDROID_GPU=gfxstream: with A64_ANDROID_BOOTLOADER=1");
// (and tools/a64_android.mjs's initrd-venus.img: libvulkan's driver the odm's vulkan.virtio.so)
const initrd = gpu_level === "venus" ? "initrd-venus.img" : "initrd.img";
assert.ok(fs.existsSync(OUT + initrd), OUT + initrd + " is missing: make android-venus, then node tools/a64_android.mjs");
// (A64_ANDROID_SHADER_DIR=<dir>: Venus's shaders and pipelines written there, a corpus for VX's translation)
const remote = gpu_level ? await create_remote_renderer({ shader_dir: process.env.A64_ANDROID_SHADER_DIR }) : null;
// A64_ANDROID_SAVE_STATE=<file>: a V7 state saved after boot_completed;
// A64_ANDROID_RESTORE_STATE=<file>: such a state restored instead of booting
// (the same options otherwise), for quick rounds of probes
const save_state_file = process.env.A64_ANDROID_SAVE_STATE || "", restore_state_file = process.env.A64_ANDROID_RESTORE_STATE || "";
// virtio-snd (P12.5): the audio HAL's card; what it plays is collected
// while a scenario's sound step listens (sound.reset to sound.played)
let sound_chunks = null;
const sound = { reset: () => { sound_chunks = []; }, played: () => { const pcm = Buffer.concat(sound_chunks || []); sound_chunks = null; return pcm; } };
const emulator = new V86({
    cpu_type: "arm64", cpu_cores: cores, memory_size: low_mb * 1048576, log_level: 0, autostart: !restore_state_file,
    // (A64_PROFILE: the CPU profile by its short name, as its CPU model; v2, the default, has FEAT_PAN)
    ...(process.env.A64_PROFILE ? { cpu_profile: { "v1": "generic-arm64-v1", "v1.1": "generic-arm64-v1.1", "v2": "generic-arm64",
        "v3": "generic-arm64-compat32" }[process.env.A64_PROFILE] } : {}),
    ...(memory_mb > low_mb ? { extended_memory_size: (memory_mb - low_mb) * 1048576 } : {}),
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    ...(bootloader ? { android: { gpu_mode: gpu_level || "swiftshader",
        vendor_ramdisk: JSON.parse(fs.readFileSync(OUT + "manifest.json", "utf8")).vendor_ramdisk === "vendor_ramdisk-debug.img" ?
            { url: ROOT + "build/a64-android/dl/vendor_ramdisk-debug.img" } : undefined } } :
        { kernel: { url: OUT + "Image" }, initrd: { url: OUT + initrd }, cmdline: fs.readFileSync(OUT + "cmdline.txt", "utf8").trim() }),
    virtio_transport: "pci", virtio_disks: [{ url: OUT + "disk.img", async: true, size: fs.statSync(OUT + "disk.img").size }],
    graphics_adapter: "virtio_gpu", virtio_gpu_pci_slot: 2, screen_adapter: sink,
    ...(remote ? { graphics_adapter_test: { level: gpu_level, renderer: remote.renderer } } : {}),
    net_device: { type: "virtio", count: 3, relay_url: "fetch", id: 2 },
    virtio_console: true, virtio_console_ports: 18, virtio_rng: true, virtio_input: ["keyboard", "multitouch"], virtio_vsock: true,
    virtio_sound: true,
    // (A64_JIT_SWITCHES: more page tier switches, "name=value,...", e.g. a64_system=0)
    ...(jit ? { jit_switches: { a64_page: 1, ...Object.fromEntries((process.env.A64_JIT_SWITCHES || "").split(",").filter(Boolean)
        .map(p => [p.split("=")[0], +p.split("=")[1]])) } } : {}),
    ...(parallel ? { parallel: true, parallel_wasm_path: process.env.A64_PARALLEL_WASM || ROOT + "build/v86-arm64-parallel.wasm" } : {}),
    // (the bundle's own default is build/vcpu-worker.js of the working directory)
    ...(parallel && +process.env.TEST_RELEASE_BUILD ? { vcpu_worker_url: ROOT + "build/vcpu-worker.js" } : {}),
});
// (a machine that fails to start, e.g. a worker script not found, says so here only)
emulator.add_listener("emulator-error", error => { console.error("emulator-error:", error); process.exit(1); });
const loaded = new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
let sound_bytes = 0;
emulator.add_listener("virtio-snd-pcm", pcm => { sound_bytes += pcm["bytes"].length; if(sound_chunks) sound_chunks.push(Buffer.from(pcm["bytes"])); });
// A64_ANDROID_GFXSTREAM_TRACE=1 (with the sources): gfxstream's Vulkan
// commands (but a command buffer's vkCmd*), each process's, with their
// results and the stats' errors when they change, into gfxstream-trace.txt
if(process.env.A64_ANDROID_GFXSTREAM_TRACE)
{
    const trace = fs.openSync(directory + "gfxstream-trace.txt", "w"), started = Date.now();
    let lines = 0, last_error = "";
    const install = setInterval(() => {
        const gpu = emulator.v86?.cpu?.devices?.graphics_adapter?.device?.["virtio_gpu"];
        const vulkan = gpu && gpu.gfxstream && gpu.gfxstream.vulkan;
        if(!vulkan) return;
        clearInterval(install);
        const now = () => ((Date.now() - started) / 1000).toFixed(3);
        // (the imports of gralloc's resources, what the GPU wrote, the transfers: G3's color buffers)
        const model = gpu.gfxstream.vk;
        let imports = 0;
        const wrote = gpu.virgl.wrote.bind(gpu.virgl), from_host = gpu.virgl.transfer_from_host.bind(gpu.virgl);
        gpu.virgl.wrote = resource => { if(lines < 200000) fs.writeSync(trace, `${now()} wrote resource ${resource.id}\n`); return wrote(resource); };
        gpu.virgl.transfer_from_host = (resource, ...rest) => {
            fs.writeSync(trace, `${now()} TRANSFER_FROM_HOST resource ${resource.id} ${resource.width}x${resource.height} format ${resource.format}\n`);
            return from_host(resource, ...rest);
        };
        vulkan.on_command = (name, a) => {
            if(model.imports.size !== imports)
            {
                imports = model.imports.size;
                fs.writeSync(trace, `${now()} imports ${JSON.stringify([...model.imports.values()].map(([rid, resource]) => rid + ":" + resource))}\n`);
            }
            if(name.startsWith("vkCmd") || ++lines > 200000) return;
            const t = now();
            const ext = name === "vkCreateDevice" || name === "vkCreateInstance" ? " " + JSON.stringify(a.pCreateInfo.ppEnabledExtensionNames) : "";
            let detail = "";
            if(name === "vkAllocateMemory")
            {
                const chain = [];
                for(let c = a.pAllocateInfo.pNext; c; c = c.pNext) chain.push(c.sType + (c.resourceId !== undefined ? ":" + c.resourceId : ""));
                detail = ` type=${a.pAllocateInfo.memoryTypeIndex} size=${a.pAllocateInfo.allocationSize} chain=${chain.join(",")} memory=${a.pMemory}`;
            }
            else if(name === "vkBindImageMemory") detail = ` image=${a.image} memory=${a.memory}`;
            else if(name === "vkBindImageMemory2") detail = " " + JSON.stringify((a.pBindInfos || []).map(b => [b.image, b.memory]));
            fs.writeSync(trace, `${t} ${name}${a.ret !== undefined ? " ret=" + a.ret : ""}${ext}${detail}\n`);
            if(vulkan.stats.last_error !== last_error) { last_error = vulkan.stats.last_error; fs.writeSync(trace, `${t} ERROR ${last_error}\n`); }
        };
    }, 100);
    install.unref();
}
// A64_ANDROID_VENUS_TRACE=1 (with the sources, not the release build): the
// device's fence commands, with their answers and the fences' state, and its
// small readbacks (fence feedback slots), into venus-trace.txt
if(process.env.A64_ANDROID_VENUS_TRACE)
{
    const trace = fs.openSync(directory + "venus-trace.txt", "w"), started = Date.now();
    const line = text => fs.writeSync(trace, ((Date.now() - started) / 1000).toFixed(3) + " " + text + "\n");
    const FENCES = /Fence|QueueSubmit/;
    const install = setInterval(() => {
        const gpu = emulator.v86?.cpu?.devices?.graphics_adapter?.device?.["virtio_gpu"];
        const vk = gpu && gpu.venus && gpu.venus.vk;
        if(!vk) return;
        clearInterval(install);
        const handle = vk.handle.bind(vk);
        vk.handle = (ctx, name, a) => {
            const wait = handle(ctx, name, a);
            if(FENCES.test(name))
            {
                const ids = [a.fence, ...(a.pFences || [])].filter(id => id);
                const state = ids.map(id => { const f = ctx.objects.get(id); return id + (f ? (f.signaled ? ":S" : ":-") + f.pending : ":gone"); });
                line(name + " " + state.join(" ") + (wait ? " (waits)" : " ret=" + a.ret));
            }
            return wait;
        };
        vk.debug = text => {
            const m = /^readback memory \d+ \[(\d+),(\d+)\)/.exec(text);
            if(m && m[2] - m[1] <= 64 || /^readback skipped/.test(text)) line(text);
        };
    }, 1000);
}
// A64_ANDROID_GPU_DEBUG=1 (with the sources, not the release build: the
// device's names): virtio-gpu's control queue and Venus's queues every 30 s
if(process.env.A64_ANDROID_GPU_DEBUG)
{
    let debug_lines = 0;
    setInterval(() => {
        const gpu = emulator.v86?.cpu?.devices?.graphics_adapter?.device?.["virtio_gpu"];
        if(!gpu) return;
        // (and the display every 5 minutes: what reached it)
        if(++debug_lines % 10 === 0) try { screenshot("gpu-debug-" + debug_lines / 10); } catch(e) { console.log("gpu-debug: no screenshot: " + e.message); }
        if(gpu.gfxstream)
        {
            // gfxstream: each context's rings (W waiting, B after another ring's command, - idle), Vulkan's stats
            const g = gpu.gfxstream, v = g.vulkan;
            // (the commands that did not decode: their payloads into the run's directory)
            for(const [i, u] of (v ? v.stats.undecoded : []).entries())
            {
                const file = `${directory}gfxstream-undecoded-${i}-${u.name}.bin`;
                if(!fs.existsSync(file)) fs.writeFileSync(file, u.payload);
            }
            console.log(`gpu-debug: held=${gpu.held} pending=${gpu.pending.length} gfxstream pings=${g.stats.pings} commands=${g.stats.commands}` +
                ` errors=${g.stats.errors}${g.stats.last_error ? " last=" + JSON.stringify(g.stats.last_error) : ""}` +
                ` contexts=${[...g.contexts.values()].map(c => c.capset + ":" + [...c.rings.values()].map(r => r.waiting ? "W" : r.blocked ? "B" : "-").join("")).join(" ")}` +
                (v ? ` vulkan commands=${v.stats.commands} flushed=${v.stats.flushed} errors=${v.stats.errors}` +
                    `${v.stats.last_error ? " last=" + JSON.stringify(v.stats.last_error) : ""} unknown=${JSON.stringify(v.stats.unknown)}` +
                    ` unimplemented=${JSON.stringify(v.stats.unimplemented)} failures=${JSON.stringify(v.stats.failures)}` +
                    ` queues=${[...g.vk.queues].map(q => q.pending.length + "p/" + q.inflight + "i").join(",")} waiters=${g.vk.waiters.length}` : "") +
                ` unknown=${JSON.stringify(g.stats.unknown)} syncs=${JSON.stringify(g.stats.syncs)}` +
                ` execbuffer=${JSON.stringify(g.stats.execbuffer)} fences=${JSON.stringify(gpu.stats.fences)}` +
                // (the host visible memory the guest has mapped: its rings and memory, MiB, of the whole)
                ` hostmem=${([...gpu.mapped.values()].reduce((sum, r) => sum + r.blob_size, 0) / 1048576).toFixed(1)}` +
                `/${gpu.hostmem_size >> 20} in ${gpu.mapped.size}` +
                // (the control queue's commands by type, flushes: KMS's scanouts)
                ` control=${JSON.stringify(gpu.stats.commands)} flushes=${gpu.stats.flushes} gpu-errors=${gpu.stats.errors}/${gpu.stats.last_error.toString(16)}` +
                (gpu.stats.failed_command ? ` failed=${JSON.stringify(gpu.stats.failed_command.slice(0, 300))}` : ""));
            return;
        }
        const first = gpu.pending.find(entry => !entry.ready);
        const vk = gpu.venus && gpu.venus.vk;
        console.log(`gpu-debug: held=${gpu.held} pending=${gpu.pending.length} first-waiting=${first ? "0x" + new DataView(first.bytes.buffer, first.bytes.byteOffset).getUint32(0, true).toString(16) : "-"}` +
            (vk ? ` venus queues=${[...vk.queues].map(q => q.pending.length + "p/" + q.inflight + "i/ring" + q.ring_idx).join(",")} waiters=${vk.waiters.length}` +
                ` submissions=${vk.stats.submissions} batches=${vk.stats.batches}` : "") +
            (gpu.venus ? ` errors=${gpu.venus.stats.errors}${gpu.venus.stats.last_error ? " last=" + JSON.stringify(gpu.venus.stats.last_error) : ""}` +
                // (the commands that answered an error, with the last one's VkResult)
                ` failures=${JSON.stringify(gpu.venus.stats.failures)}` +
                // (each context's rings: - idle, R running, W:<command> waiting in it, F fatal)
                ` rings=${[...gpu.venus.contexts.values()].map(c => [...c.rings.values()].map(r => r.fatal ? "F" : !r.run ? "-" :
                    r.run.waiting ? "W:" + r.run.waiting_on.replace(/^vk/, "") : "R").join("")).filter(r => /[RWF]/.test(r)).join(" ")}` : ""));
        // (=2: every ring: context, id, its blob's mapping, head, the tail and status in its memory)
        if(process.env.A64_ANDROID_GPU_DEBUG === "2" && gpu.venus)
        {
            const bytes = gpu.venus.bytes(), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            for(const c of gpu.venus.contexts.values())
            {
                for(const r of c.rings.values())
                {
                    const mapped = r.blob.map_offset >= 0;
                    console.log(`gpu-ring: ctx=${c.id} ring=${r.id} blob=${r.blob.id} map=${r.blob.map_offset} head=${r.head}` +
                        (mapped ? ` tail=${view.getUint32(r.blob.map_offset + r.tail_offset, true)} mem-head=${view.getUint32(r.blob.map_offset + r.head_offset, true)}` +
                            ` status=${view.getUint32(r.blob.map_offset + r.status_offset, true)}` : "") +
                        ` fatal=${r.fatal} run=${r.run ? (r.run.waiting ? "W:" + r.run.waiting_on : "R") : "-"}`);
                }
            }
        }
    }, 30000).unref();
}
// (Cuttlefish's phone display: 720x1280, lcd_density 320)
emulator.add_listener("emulator-ready", () => emulator.set_display_size(720, 1280));
// (Node has no animation frames: the display draws into the sink when asked, as tests/x64/linux_gpu.mjs's)
const screenshot = name => { emulator.v86?.cpu?.devices?.display?.request_frame(true); return save_png(sink, directory, name); };
const kernel_watch = watch("kernel", "kernel.log"), logcat_watch = watch("logcat", "logcat.log");
const serial_out = fs.openSync(directory + "console.log", "w");
emulator.add_listener("serial0-output-byte", byte => { fs.writeSync(serial_out, Buffer.from([byte])); });
emulator.add_listener("virtio-console0-output-bytes", kernel_watch);
emulator.add_listener("virtio-console2-output-bytes", logcat_watch);
// (the DHCP messages between the guest and the fetch adapter on the third
// NIC, net2: dhcp.log, for A9's network step)
const dhcp_log = fs.openSync(directory + "dhcp.log", "w");
const DHCP_TYPES = ["", "DISCOVER", "OFFER", "REQUEST", "DECLINE", "ACK", "NAK", "RELEASE", "INFORM"];
const log_dhcp = direction => frame => {
    if(frame.length < 14 + 20 + 8 + 240 || frame[12] !== 0x08 || frame[13] !== 0x00 || frame[14 + 9] !== 17) return;
    const udp = 14 + (frame[14] & 15) * 4;
    const ports = [frame[udp] << 8 | frame[udp + 1], frame[udp + 2] << 8 | frame[udp + 3]];
    if(!ports.includes(67)) return;
    const dhcp = udp + 8;
    let type = 0;
    for(let i = dhcp + 240; i < frame.length && frame[i] !== 255; i += frame[i] === 0 ? 1 : 2 + frame[i + 1])
    {
        if(frame[i] === 53) type = frame[i + 2];
    }
    const xid = (frame[dhcp + 4] << 24 | frame[dhcp + 5] << 16 | frame[dhcp + 6] << 8 | frame[dhcp + 7]) >>> 0;
    fs.writeSync(dhcp_log, `${(elapsed() / 1000).toFixed(1)} s ${direction} ${DHCP_TYPES[type] || type} xid=${xid.toString(16)}\n`);
};
emulator.add_listener("net2-send", log_dhcp("guest->host"));
{
    // (the fetch adapter sends its frames from this end of the bus, where
    // listeners do not see them)
    const send = emulator.bus.send.bind(emulator.bus), to_guest = log_dhcp("host->guest");
    emulator.bus.send = (name, value, ...rest) => { if(name === "net2-receive") to_guest(value); return send(name, value, ...rest); };
}
const deadline = new Promise((_, reject) => setTimeout(() => reject(new Error(`deadline (${timeout} ms)`)), timeout));
deadline.catch(() => {});
const progress = setInterval(() => {
    console.log(`${(elapsed() / 1000).toFixed(0)} s: ${Object.keys(marks).join(", ") || "booting"}`);
}, 60000);
const vsock = async () => {
    const s = await emulator.vsock_connect(5555);
    return { adapter: { write: bytes => s.write(Uint8Array.from(bytes)), set on_data(fn) { s.on_data = bytes => fn(Buffer.from(bytes)); } },
        close: () => s.close() };
};
const adb = adb_over(vsock);
const with_deadline = p => Promise.race([p, failed, deadline]);

try
{
    if(restore_state_file)
    {
        await loaded;
        const file = await fs.promises.open(restore_state_file, "r");
        const size = (await file.stat()).size;
        await emulator.restore_state_stream({ size, read: async (offset, length) => {
            const data = new Uint8Array(length);
            const read = (await file.read(data, 0, length, offset))["bytesRead"];
            return read === length ? data : data.subarray(0, read);
        } });
        await file.close();
        for(const name of ["restored", "system_server", "adbd", "boot_completed"]) mark(name);
        console.log(`restored ${restore_state_file} (${(size / 1048576).toFixed(0)} MiB)`);
        emulator.run();
    }
    // system_server, then adbd's answer (retried: adbd starts before its vsock listener is ready)
    await with_deadline(new Promise(resolve => { const t = setInterval(() => { if(marks.system_server !== undefined && marks.adbd !== undefined) { clearInterval(t); resolve(); } }, 1000); }));
    const banner = await with_deadline(adb.banner());
    const answer = await with_deadline(adb.shell("echo B=$(getprop sys.boot_completed) P=$(pidof system_server) F=$(getprop ro.build.fingerprint) S=$(getconf PAGE_SIZE) K=$(uname -r)"));
    mark("adb");
    console.log("adb banner: " + banner.slice(0, 120));
    console.log("adb: " + JSON.stringify(answer));
    const fields = /B=(\S*) P=(\d*) F=(\S*)/.exec(answer);
    assert.ok(fields && fields[2], "system_server's pid over adb: " + JSON.stringify(answer));
    assert.ok(/:16\/BP4A\.251205\.006\//.test(fields[3]), "the build's fingerprint over adb");
    const result = { tag, marks, system_server_pid: +fields[2], fingerprint: fields[3], ...check_page_size(answer) };
    // (the scenario's device settings, from now on: see prepare_device)
    const prepared = scenario ? prepare_device(adb.shell).then(() => mark("device_prepared")) : null;
    prepared?.catch(() => {});
    if(wait_for_boot_completed)
    {
        while((await with_deadline(adb.shell("getprop sys.boot_completed"))).trim() !== "1") await sleep(30000);
        mark("boot_completed_adb");
        screenshot("boot-completed");
    }
    if(save_state_file)
    {
        await emulator.stop();
        const file = await fs.promises.open(save_state_file, "w");
        let bytes = 0;
        await emulator.save_state_stream(async chunk => { await file.write(chunk, 0, chunk.length, bytes); bytes += chunk.length; });
        await file.close();
        mark("state_saved");
        console.log(`saved ${save_state_file} (${(bytes / 1048576).toFixed(0)} MiB)`);
        emulator.run();
    }
    // (A10 runs the probes after its snapshot instead: debugging what follows a restore)
    if(scenario !== "a10") await with_deadline(run_probes(adb.shell, adb.push, async name => screenshot(name)));
    if(scenario)
    {
        await with_deadline(prepared);
        // (a tap held 100 ms: a busy guest that reads the release late would otherwise
        // see more than the long press timeout, 400 ms, and Launcher3 opens the icon's menu)
        const touch = async (x, y) => {
            emulator.bus.send("touch", { "touches": [[1, x, y]], "width": 720, "height": 1280 });
            await sleep(100);
            emulator.bus.send("touch", { "touches": [], "width": 720, "height": 1280 });
        };
        // (A10's input latency: from the touch to the first change of the screen's middle rows)
        const digest = () => {
            emulator.v86?.cpu?.devices?.display?.request_frame(true);
            const row = sink.width * 4;
            return create_hash("sha1").update(sink.rgba.subarray(LATENCY_ROWS[0] * row, LATENCY_ROWS[1] * row)).digest("hex");
        };
        const tap_latency = async (x, y) => {
            const before = digest();
            const started = performance.now();
            await touch(x, y);
            while(performance.now() - started < 60000)
            {
                if(digest() !== before) return Math.round(performance.now() - started);
                await sleep(20);
            }
            return null;
        };
        // (after "reboot" adbd goes away, the machine resets and boots again: wait for adb, up to 2 hours)
        const wait_reboot = async () => { await sleep(60000); await adb_over(vsock, 7200000).shell("echo up"); };
        // (A10: the desktop saved to A64_ANDROID_A10_SAVE, which a second run
        // restores into a new machine; A64_ANDROID_SNAPSHOT=inprocess: saved
        // and restored into this one, debugging: see docs/aarch64.md's known
        // defects; =pause: only stopped for 20 s)
        const a10_save = process.env.A64_ANDROID_A10_SAVE || "";
        const snapshot = async () => {
            const name = a10_save || directory + "snapshot.v7";
            await emulator.stop();
            if(a10_save)
            {
                const started = performance.now();
                let bytes = 0;
                const out = await fs.promises.open(name, "w");
                await emulator.save_state_stream(async chunk => { await out.write(chunk, 0, chunk.length, bytes); bytes += chunk.length; });
                await out.close();
                emulator.run();
                return { saved: name, mib: Math.round(bytes / 1048576), save_ms: Math.round(performance.now() - started) };
            }
            // (A64_ANDROID_SNAPSHOT=pause: the machine only stopped for 20 s, debugging)
            if(process.env.A64_ANDROID_SNAPSHOT === "pause")
            {
                await sleep(20000);
                emulator.run();
                await adb_over(vsock, 600000).shell("echo up");
                return { paused_ms: 20000 };
            }
            let started = performance.now(), bytes = 0;
            const out = await fs.promises.open(name, "w");
            await emulator.save_state_stream(async chunk => { await out.write(chunk, 0, chunk.length, bytes); bytes += chunk.length; });
            await out.close();
            const save_ms = Math.round(performance.now() - started);
            started = performance.now();
            const file = await fs.promises.open(name, "r");
            await emulator.restore_state_stream({ size: bytes, read: async (offset, length) => {
                const data = new Uint8Array(length);
                const read = (await file.read(data, 0, length, offset))["bytesRead"];
                return read === length ? data : data.subarray(0, read);
            } });
            await file.close();
            const restore_ms = Math.round(performance.now() - started);
            emulator.run();
            if(!process.env.A64_ANDROID_KEEP_SNAPSHOT) fs.rmSync(name, { force: true });
            await adb_over(vsock, 600000).shell("echo up");
            return { mib: Math.round(bytes / 1048576), save_ms, restore_ms };
        };
        await with_deadline(run_scenario({ target, directory, adb: adb.shell, push: adb.push, reboot: adb.reboot,
            screenshot: async name => screenshot(name),
            touch, tap_latency, http: { port: http_port, token: http_token }, wait_reboot, monkey_minutes, steps: a10_steps,
            snapshot: scenario === "a10" && (a10_save && !restore_state_file || process.env.A64_ANDROID_SNAPSHOT) ? snapshot : null,
            restored: restore_state_file || null,
            sound,
            probe: probe_file ? () => run_probes(adb.shell, adb.push, async name => screenshot(name)) : null }, result));
    }
    clearInterval(progress);
    result.ms = elapsed();
    if(remote) result.renderer = remote.stats;
    // (P12.3's metrics: the instructions each core retired, MIPS over the
    // run, the page tier's counters (core 0's instance; the workers' compile
    // their own), the host process's peak resident memory)
    {
        const cpu = emulator.v86.cpu;
        const retired = Array.from({ length: cores }, (_, core) => cpu.retired_instructions(core));
        const total = retired.reduce((sum, n) => sum + n, 0);
        const t = jit ? cpu.page_tier_stats() : null;
        result.metrics = { retired, mips: Math.round(total / result.ms / 100) / 10,
            ...(t ? { compiles: t.compiled, compile_ms: Math.round(t.compile_ms), evictions: t.evictions, live_code_mib: Math.round(t.live_code_bytes / 1048576) } : {}),
            // (core 0's page tier counters in full: its instance's)
            ...(t ? { page_tier: t, retired_core0: cpu.retired_instructions(0) } : {}),
            // (the workers' counters: slices, waits, device accesses served by the machine's thread)
            ...(cpu.parallel ? { parallel: cpu.parallel.status() } : {}),
            // (the instructions the page tier steps, and those of them that end its activations)
            ...(t && cpu.step_stats ? { steps: cpu.step_stats(25) } : {}),
            max_rss_mib: Math.round(process.resourceUsage().maxRSS / 1024),
            // (what the sound card played over the run: the audio HAL's output)
            sound_mib: Math.round(sound_bytes / 1048576 * 10) / 10 };
    }
    fs.writeFileSync(directory + "result.json", JSON.stringify(result, null, 2) + "\n");
    console.log(JSON.stringify(result));
    console.log(`A64_ANDROID_BOOT_OK ${tag}`);
    await emulator.destroy();
    remote?.close();
    process.exit(0);
}
catch(e)
{
    clearInterval(progress);
    screenshot("failure");
    console.error(e);
    console.error("marks: " + JSON.stringify(marks));
    remote?.close();
    process.exit(1);
}
                                                                                                                      source/v64/tests/a64/android_cts.mjs                                                                0000644 0000000 0000000 00000014100 00000000000 014420  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A CTS subset on a booted Android 16 (docs/arm64-virt-android16-plan.md
// P12.3), over adb, the same on the QEMU reference and on v86
// (tests/a64/android_boot.mjs A64_ANDROID_SCENARIO=cts): native gtest
// modules of CTS 16.1_r1 (tools/a64_cts.mjs fetches them), their arm64 files
// pushed where the module's configuration has Tradefed's FilePusher put
// them, the binary run as its GTest runner runs it, without Tradefed (the
// test host here is macOS and the guest's adb is this harness's). A module
// passes when gtest reports no failed test; a filter, when it has one, is
// part of the subset (see CTS_SUBSET).
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fetch_module, CTS, CTS_DIR } from "../../tools/a64_cts.mjs";

/**
 * The subset, frozen with P10.3's budget (A10). Native gtest modules that
 * exercise what v86 emulates: the CPU and MMU through bionic (libc, the
 * dynamic linker, threads, signals, memory mappings, floating point), the
 * kernel's ABI and configuration, file-based encryption's ciphers, ASLR.
 * device: the configuration's native-test-device-path (with the module's
 * own directory when FilePusher pushes one); binary: under it.
 */
export const CTS_SUBSET = [
    { module: "CtsKernelConfigTestCases", device: "/data/local/tmp", binary: "CtsKernelConfigTestCases64" },
    { module: "CtsNativeEncryptionTestCases", device: "/data/local/tmp", binary: "CtsNativeEncryptionTestCases64" },
    { module: "CtsAslrMallocTestCases", device: "/data/local/tmp", binary: "CtsAslrMallocTestCases64" },
    { module: "CtsFsMgrTestCases", device: "/data/local/tmp", binary: "CtsFsMgrTestCases64" },
    { module: "CtsBionicTestCases", device: "/data/local/tests/unrestricted/CtsBionicTestCases", binary: "CtsBionicTestCases" },
];

/** a ustar archive of [name, data, mode] (directories implied) */
export function ustar(files)
{
    const blocks = [];
    for(const [name, data, mode = 0o644] of files)
    {
        const header = Buffer.alloc(512);
        let prefix = "", base = name;
        if(Buffer.byteLength(name) > 100)
        {
            const cut = name.lastIndexOf("/", 155);
            prefix = name.slice(0, cut);
            base = name.slice(cut + 1);
            assert.ok(cut > 0 && Buffer.byteLength(base) <= 100, "ustar: " + name);
        }
        header.write(base, 0, "utf8");
        header.write(mode.toString(8).padStart(7, "0"), 100, "latin1");
        header.write("0000000", 108, "latin1");
        header.write("0000000", 116, "latin1");
        header.write(data.length.toString(8).padStart(11, "0"), 124, "latin1");
        header.write("00000000000", 136, "latin1");
        header.write("        ", 148, "latin1");
        header.write("0", 156, "latin1");
        header.write("ustar\0" + "00", 257, "latin1");
        header.write(prefix, 345, "utf8");
        header.write(header.reduce((sum, b) => sum + b, 0).toString(8).padStart(6, "0") + "\0 ", 148, "latin1");
        blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
    }
    blocks.push(Buffer.alloc(1024));
    return Buffer.concat(blocks);
}

/** gtest's summary in a run's output: passed, failed (names), skipped, the count it ran */
export function gtest_summary(output)
{
    const count = (label) => +(new RegExp(`^\\[ +${label} +\\] (\\d+) tests?`, "m").exec(output)?.[1] ?? 0);
    const ran = /^\[==========\] (\d+) tests? from \d+ test (?:suites?|cases?) ran/m.exec(output);
    const failed = [...output.matchAll(/^\[ +FAILED +\] ([\w/.]+)(?:, where|\s*$| \()/gm)].map(m => m[1]).filter(n => n.includes("."));
    return { ran: ran ? +ran[1] : null, passed: count("PASSED"), skipped: count("SKIPPED"), failed: [...new Set(failed)] };
}

/**
 * The subset on the device.
 * @param {!Object} env as android_scenario.mjs's (adb, push, log)
 * @param {{modules: (Array<string>|undefined), filter: (Object<string, string>|undefined), timeout_ms: (number|undefined)}=} options
 *     modules: some of CTS_SUBSET's only; filter: a gtest filter by module, to time a module's suites
 * @return {!Promise<!Object>} by module: gtest's summary, ms, the run's exit status
 */
export async function cts_scenario(env, options = {})
{
    const { adb, log } = env;
    const result = { cts: CTS.version, modules: {} };
    for(const m of CTS_SUBSET)
    {
        if(options.modules && !options.modules.includes(m.module)) continue;
        const dir = await fetch_module(m.module, false);
        const files = [];
        const walk = (at, relative) =>
        {
            for(const name of fs.readdirSync(at).sort())
            {
                const file = path.join(at, name);
                if(fs.statSync(file).isDirectory()) walk(file, relative + name + "/");
                else files.push([relative + name, fs.readFileSync(file), fs.statSync(file).mode & 0o777 | (name === m.binary && !relative ? 0o755 : 0)]);
            }
        };
        walk(dir + "arm64", "");
        assert.ok(files.some(([name]) => name === m.binary), `${m.module}: no arm64/${m.binary}`);
        const tar = `/data/local/tmp/${m.module}.tar`;
        await env.push(tar, ustar(files));
        await adb(`mkdir -p ${m.device} && tar -xf ${tar} -C ${m.device} && rm ${tar}`, 600000);
        const filter = options.filter?.[m.module] || m.filter;
        const log_file = `/data/local/tmp/${m.module}.log`;
        const started = Date.now();
        const status = (await adb(`cd ${m.device} && ./${m.binary}${filter ? ` --gtest_filter='${filter}'` : ""} > ${log_file} 2>&1; echo EXIT=$?`,
            options.timeout_ms || 14400000)).trim();
        const ms = Date.now() - started;
        const output = await adb(`grep -E '^\\[(==========| +(PASSED|FAILED|SKIPPED) +)\\]' ${log_file}`, 600000);
        const summary = gtest_summary(output);
        result.modules[m.module] = { ...summary, ms, exit: +(/EXIT=(\d+)/.exec(status)?.[1] ?? -1), ...(filter ? { filter } : {}) };
        log(`${m.module}: ${JSON.stringify(result.modules[m.module]).slice(0, 1500)}`);
    }
    result.passed = Object.values(result.modules).every(r => r.ran && !r.failed.length && r.exit === 0);
    return result;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/a64/android_deqp.mjs                                                               0000644 0000000 0000000 00000024150 00000000000 014566  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // dEQP on a booted Android 16 (docs/arm64-virt-android16-plan.md appendix
// F6), over adb, the same on the QEMU reference (SwiftShader) and on v86
// (Venus through WebGPU, ANGLE above it for GL ES): CTS 16.1_r1's
// CtsDeqpTestCases (tools/a64_cts.mjs fetches it), its APK installed and run
// as Tradefed's DeqpTestRunner runs it, the instrumentation with a case list
// and a command line per package, without Tradefed; the log (.qpa) read back
// and each case's status counted. The subset (DEQP_SUBSET): dEQP-VK's API
// smoke tests, dEQP-EGL's info, and GLES 2's prerequisites, implementation
// limits, info, clears, buffer writes and constant expressions; GLES 3's info,
// limits, transform feedback, uniform blocks and flat shading;
// A64_ANDROID_DEQP=<package>=<prefix>,...;... replaces it (a prefix "!..."
// is an instrumentation run of its own, and so is "@<file>": the cases
// that file names).
import assert from "node:assert/strict";
import fs from "node:fs";
import { fetch_module } from "../../tools/a64_cts.mjs";
import { prepare_device } from "./android_scenario.mjs";

const MODULE = "CtsDeqpTestCases";
const APK = "com.drawelements.deqp";
const INSTRUMENTATION = APK + "/com.drawelements.deqp.testercore.DeqpInstrumentation";

/** package -> [case list file of the module, the case prefixes] */
export const DEQP_SUBSET = {
    "dEQP-VK": ["vk-main-2019-03-01.txt", ["dEQP-VK.api.smoke."]],
    "dEQP-EGL": ["egl-main-2020-03-01.txt", ["dEQP-EGL.info."]],
    "dEQP-GLES2": ["gles2-main-2020-03-01.txt", ["dEQP-GLES2.info.", "dEQP-GLES2.functional.prerequisite.",
        "dEQP-GLES2.functional.implementation_limits.", "dEQP-GLES2.functional.color_clear.single_rgb",
        "dEQP-GLES2.functional.color_clear.single_rgba", "dEQP-GLES2.functional.depth_stencil_clear.depth",
        "dEQP-GLES2.functional.buffer.write.basic.", "dEQP-GLES2.functional.shaders.constant_expressions.trivial."]],
    // (F2: what ES 3.0 asks of Venus, transform feedback and uniform blocks; flat shading's provoking vertex)
    "dEQP-GLES3": ["gles3-main-2020-03-01.txt", ["dEQP-GLES3.info.", "dEQP-GLES3.functional.implementation_limits.",
        "dEQP-GLES3.functional.transform_feedback.position.", "dEQP-GLES3.functional.transform_feedback.point_size.",
        "dEQP-GLES3.functional.transform_feedback.basic_types.separate.points.highp_",
        "dEQP-GLES3.functional.transform_feedback.basic_types.interleaved.triangles.highp_",
        "dEQP-GLES3.functional.transform_feedback.interpolation.flat.", "dEQP-GLES3.functional.ubo.single_basic_type.std140.highp_vec4",
        "dEQP-GLES3.functional.rasterization.flatshading.", "!dEQP-GLES3.functional.ubo.random.all_per_block_buffers.1"]],
};

/** Cases in dEQP's trie format ({a{b,c{d}}}: a.b and a.c.d) */
export function case_trie(cases)
{
    const root = new Map();
    for(const c of cases)
    {
        let node = root;
        for(const part of c.split(".")) node = node.get(part) || node.set(part, new Map()).get(part);
    }
    const write = node => [...node].map(([name, children]) => children.size ? name + "{" + write(children) + "}" : name).join(",");
    return "{" + write(root) + "}";
}

/**
 * A package's command line (DeqpTestRunner's: GL ones with the module's GL
 * configuration and a window); the cases inline (the app reads no file the
 * shell writes: scoped storage)
 */
function command_line(name, cases)
{
    const gl = name === "dEQP-VK" ? "" : " --deqp-gl-config-name=rgba8888d24s8ms0 --deqp-surface-type=window --deqp-screen-rotation=unspecified";
    return `--deqp-caselist=${case_trie(cases)}${gl} --deqp-watchdog=enable`;
}

/** The cases of a .qpa log: name -> status code (Pass, Fail, NotSupported, QualityWarning, ...; Crash when it did not end) */
export function qpa_results(text)
{
    const results = {};
    for(const block of text.split("#beginTestCaseResult ").slice(1))
    {
        const name = block.slice(0, block.indexOf("\n")).trim();
        const status = /<Result StatusCode="([^"]+)"/.exec(block)?.[1];
        results[name] = block.includes("#terminateTestCaseResult") ? "Crash" : status || "Crash";
    }
    return results;
}

/**
 * @param {!Object} env as the other scenarios' (adb, push, log)
 * @return {!Promise<!Object>} per package the cases, their statuses and counts
 */
export async function deqp_scenario(env)
{
    const { adb, log } = env;
    const dir = await fetch_module(MODULE, false);
    // (the test activity must come to the front: user 0 unlocked, awake, no keyguard)
    await prepare_device(adb);
    for(let deadline = Date.now() + 3600000; !/RUNNING_UNLOCKED/.test(await adb("am get-started-user-state 0 2>&1")); )
    {
        assert.ok(Date.now() < deadline, "user 0 unlocked");
        await new Promise(resolve => setTimeout(resolve, 15000));
    }
    await adb("settings put system screen_off_timeout 2147483647; input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard");
    const subset = process.env.A64_ANDROID_DEQP ? Object.fromEntries(process.env.A64_ANDROID_DEQP.split(";").map(p => {
        const [name, prefixes] = p.split("=");
        return [name, [DEQP_SUBSET[name][0], prefixes.split(",")]];
    })) : DEQP_SUBSET;
    await env.push("/data/local/tmp/deqp.apk", fs.readFileSync(dir + "com.drawelements.deqp.apk"));
    assert.match(await adb("pm install -r -g /data/local/tmp/deqp.apk 2>&1", 1800000), /^Success/m, "pm install the dEQP APK");
    const result = { module: MODULE, packages: {} };
    for(const [name, [list, prefixes]] of Object.entries(subset))
    {
        // (a list is cases, or the lists it is made of: vk-main-2019-03-01.txt names vk-main-2019-03-01/*.txt)
        const lines = file => fs.readFileSync(dir + file, "utf8").split("\n").map(c => c.trim()).filter(Boolean)
            .flatMap(c => c.endsWith(".txt") ? lines(c) : [c]);
        // (a prefix "!..." runs on its own: a failing ubo.random case leaves
        // the context answering GL_INVALID_OPERATION to every later case,
        // and dEQP runs a package's cases in its own order)
        // ("@<file>": that file's cases, by name, also a run of their own)
        const all = lines(list), match = p => all.filter(c => c.startsWith(p.replace(/^!/, "")));
        const named = file => { const wanted = new Set(fs.readFileSync(file, "utf8").split("\n").map(c => c.trim())); return all.filter(c => wanted.has(c)); };
        const runs = [prefixes.filter(p => !/^[!@]/.test(p)).flatMap(match), ...prefixes.filter(p => p.startsWith("!")).map(match),
            ...prefixes.filter(p => p.startsWith("@")).map(p => named(p.slice(1)))].filter(r => r.length);
        const cases = [...new Set(runs.flat())];
        assert.ok(cases.length, `${name}: no case of ${prefixes} in ${list}`);
        // (the log in the app's own external directory: scoped storage gives it nothing else of /sdcard, and the shell reads it)
        const files = `/sdcard/Android/data/${APK}/files`, qpa = `${files}/${name}.qpa`;
        const started = Date.now();
        let out = "", text = "", logcat = "";
        for(const [index, first] of runs.entries())
        {
            // (a case that ends the instrumentation, a crash or dEQP's watchdog: the run's
            // other cases again, without those that have a result, while some do)
            let run = first;
            for(let pass = 0; run.length; pass++)
            {
                await adb(`mkdir -p ${files}; rm -f ${qpa}; logcat -c`);
                // (DeqpTestRunner's: deqpLogFilename, the log's path; again when the
                // instrumentation gave up waiting for the tester to start its log,
                // which a slow first start of the app outlasts)
                for(let attempt = 0; attempt < 3; attempt++)
                {
                    out = await adb(`am instrument -w -r -e deqpLogFilename ${qpa} -e deqpCmdLine "${command_line(name, run)}" ` +
                        `-e deqpLogData false ${INSTRUMENTATION} 2>&1 | tail -5`, 4 * 3600000);
                    if(!/Timeout while waiting for log file/.test(out)) break;
                    log(`${name}: the instrumentation timed out waiting for the log, again`);
                }
                const got = await adb(`cat ${qpa}`, 600000);
                text += got;
                logcat = (await adb("logcat -d -s dEQP:* DeqpInstrumentation:* AndroidRuntime:E 2>&1 | tail -25", 600000)).trim();
                // (all of it, for what the drivers said: ANGLE, the Vulkan loader, Mesa)
                if(env.directory) fs.writeFileSync(env.directory + `deqp-${name}-logcat${index ? "-" + index : ""}${pass ? "." + pass : ""}.txt`,
                    await adb("logcat -d 2>&1 | tail -4000", 600000));
                const done = qpa_results(got), rest = run.filter(c => !(c in done));
                if(rest.length === run.length || pass >= 50) break;
                if(rest.length) log(`${name}: the run ended at ${Object.keys(done).length} of ${run.length} cases; the other ${rest.length} again`);
                run = rest;
            }
        }
        const ms = Date.now() - started, results = qpa_results(text);
        const counts = {};
        for(const status of Object.values(results)) counts[status] = (counts[status] || 0) + 1;
        const missing = cases.filter(c => !(c in results));
        const failed = Object.entries(results).filter(([, s]) => !["Pass", "NotSupported", "QualityWarning", "CompatibilityWarning"].includes(s));
        result.packages[name] = { cases: cases.length, ran: Object.keys(results).length, counts, ms,
            failed: failed.slice(0, 50).map(([c, s]) => c + ": " + s), missing: missing.slice(0, 20), instrumentation: out.trim().slice(-300),
            ...(Object.keys(results).length ? {} : { logcat: logcat.slice(-3000) }) };
        if(env.directory) fs.writeFileSync(env.directory + `deqp-${name}.json`, JSON.stringify(results, null, 1));
        // (the log itself when a case did not pass: what it saw)
        if(env.directory && failed.length) fs.writeFileSync(env.directory + `deqp-${name}.qpa`, text);
        log(`${name}: ${JSON.stringify(result.packages[name]).slice(0, 2000)}`);
    }
    await adb(`pm uninstall ${APK} >/dev/null 2>&1`);
    result.passed = Object.values(result.packages).every(p => p.ran === p.cases && !p.failed.length);
    return result;
}
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/android_qemu.mjs                                                               0000644 0000000 0000000 00000025234 00000000000 014610  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The Android 16 reference on QEMU (docs/arm64-virt-android16-plan.md
// P10.3): the machine of the Alpine reference (QEMU 9.2.0, virt-9.2 with
// GICv3 and high ECAM, cortex-a35, P0) with Cuttlefish's devices as its
// launcher gives them to QEMU (host/libs/vm_manager/qemu_manager.cpp:
// virtio-pci, 18 virtconsole ports with the kernel's console on hvc0 and
// logcat on hvc2, the GPU at 00:02.0 where Cuttlefish's sepolicy expects it,
// three NICs), booting tools/a64_android.mjs's Image, initrd.img and disk.img
// directly (no U-Boot). The Android console is on the PL011 (ttyAMA0),
// driven through a Unix socket.
import fs from "node:fs";
import net from "node:net";
import { createHash as create_hash } from "node:crypto";
import { QEMU_MACHINE, QEMU_CPU, smp } from "./guest_runner.mjs";
import { save_png } from "../lib/picture_sink.mjs";

/**
 * QEMU's arguments
 * @param {string} out tools/a64_android.mjs's output directory (with a slash)
 * @param {{accel?: string, memory_mb: number, cores: number, console_socket: string, kernel_log: string,
 *     logcat: string, extract?: string, snapshot?: boolean, monitor_socket?: string, adb_port?: number, qmp_socket?: string,
 *     sound_wav?: string}} o
 *     accel "tcg" (the reference: cortex-a35) or "hvf" (the host's CPU, for
 *     quick runs); extract: the Unix socket of a virtserialport named
 *     org.v86.extract (a socket: a file's backend never opens the port for
 *     the guest, whose writes then block); monitor_socket: the human monitor
 *     on a Unix socket (screendump); adb_port: the host's port forwarded to
 *     adbd's tcp:5555 on the third NIC, the one under Cuttlefish's Wi-Fi
 *     (VirtWifi; DHCP gives it 10.0.3.15); qmp_socket: QMP on a Unix socket
 *     (qemu_touch); sound_wav: where virtio-sound-pci's output goes (WAV,
 *     without QEMU's mixing engine: the guest's bytes in its stream's format),
 *     else nowhere (P12.5: the audio HAL's card, as v86's virtio_sound)
 */
export function android_qemu_args(out, o)
{
    const cmdline = fs.readFileSync(out + "cmdline.txt", "utf8").trim();
    const consoles = [];
    for(let i = 0; i < 18; i++)
    {
        // hvc0 the kernel's console, hvc2 logcat (Cuttlefish's seriallogging);
        // the others' host ends (keymint, gatekeeper, ...) are sinks: the guest
        // uses its own nonsecure HALs (bootconfig)
        const file = i === 0 ? o.kernel_log : i === 2 ? o.logcat : null;
        consoles.push("-chardev", file ? `file,id=hvc${i},path=${file}` : `null,id=hvc${i}`,
            "-device", `virtconsole,bus=virtio-serial.0,chardev=hvc${i}`);
    }
    return [
        "-machine", QEMU_MACHINE,
        ...(o.accel === "hvf" ? ["-accel", "hvf", "-cpu", "host"] : ["-accel", "tcg,thread=multi", "-cpu", QEMU_CPU]),
        "-m", o.memory_mb + "M", "-smp", smp(o.cores),
        "-kernel", out + "Image", "-initrd", out + "initrd.img", "-append", cmdline,
        "-drive", `if=none,id=disk0,file=${out}disk.img,format=raw${o.snapshot === false ? "" : ",snapshot=on"}`,
        "-device", "virtio-blk-pci-non-transitional,drive=disk0,addr=01.0",
        "-device", "virtio-gpu-pci,xres=720,yres=1280,addr=02.0",
        "-device", "virtio-serial-pci-non-transitional,max_ports=31,id=virtio-serial,addr=03.0", ...consoles,
        ...(o.extract ? ["-chardev", `socket,id=extract,path=${o.extract},server=on,wait=off`,
            "-device", "virtserialport,bus=virtio-serial.0,chardev=extract,name=org.v86.extract,nr=30"] : []),
        "-device", "virtio-rng-pci-non-transitional,addr=04.0",
        // (a touch screen: QEMU's virtio-multitouch, as v86's)
        "-device", "virtio-keyboard-pci,addr=05.0", "-device", "virtio-multitouch-pci,addr=06.0",
        // (eth0, eth1, eth2: Cuttlefish's mobile, ethernet and wifi; init renames eth0 and eth2)
        "-netdev", "user,id=n0,net=10.0.1.0/24,restrict=on", "-device", "virtio-net-pci-non-transitional,netdev=n0,addr=07.0,romfile=",
        "-netdev", "user,id=n1,net=10.0.2.0/24,restrict=on", "-device", "virtio-net-pci-non-transitional,netdev=n1,addr=08.0,romfile=",
        "-netdev", "user,id=n2,net=10.0.3.0/24,restrict=on" + (o.adb_port ? `,hostfwd=tcp:127.0.0.1:${o.adb_port}-10.0.3.15:5555` : ""),
        "-device", "virtio-net-pci-non-transitional,netdev=n2,addr=09.0,romfile=",
        "-audiodev", o.sound_wav ? `wav,id=snd0,path=${o.sound_wav},out.mixing-engine=off` : "none,id=snd0",
        "-device", "virtio-sound-pci,audiodev=snd0,addr=0a.0",
        "-display", "none", "-monitor", o.monitor_socket ? `unix:${o.monitor_socket},server,nowait` : "none",
        ...(o.qmp_socket ? ["-qmp", `unix:${o.qmp_socket},server,nowait`] : []),
        "-chardev", `socket,id=ser0,path=${o.console_socket},server=on,wait=off`, "-serial", "chardev:ser0",
        // (a reboot restarts the machine with the disk's writes kept: snapshot=on's overlay lives as long as QEMU)
    ];
}

/** a screenshot through the human monitor (screendump, PPM) as <directory>/<name>.png */
export async function qemu_screendump(monitor_socket, directory, name)
{
    const ppm = directory + name + ".ppm";
    fs.rmSync(ppm, { force: true });
    await new Promise((resolve, reject) => {
        const s = net.connect(monitor_socket);
        s.on("connect", () => { s.write(`screendump ${ppm}\n`); setTimeout(() => { s.end(); resolve(); }, 1500); });
        s.on("error", reject);
    });
    for(let i = 0; i < 40 && !fs.existsSync(ppm); i++) await new Promise(resolve => setTimeout(resolve, 250));
    const bytes = fs.readFileSync(ppm);
    const m = /^P6\s+(\d+)\s+(\d+)\s+255\s/.exec(bytes.toString("latin1", 0, 40));
    const width = +m[1], height = +m[2], rgba = new Uint8Array(width * height * 4);
    for(let i = 0; i < width * height; i++)
    {
        rgba.set(bytes.subarray(m[0].length + i * 3, m[0].length + i * 3 + 3), i * 4);
        rgba[i * 4 + 3] = 255;
    }
    fs.rmSync(ppm);
    return save_png({ width, height, rgba }, directory, name);
}

/**
 * QMP on a Unix socket: commands, each answered in turn
 * @param {string} socket_path
 * @return {!Promise<{command: function(string, Object=): !Promise<*>, close: function()}>}
 */
export async function qmp_connect(socket_path)
{
    const s = await new Promise((resolve, reject) => { const c = net.connect(socket_path); c.once("connect", () => resolve(c)); c.once("error", reject); });
    let text = "";
    const waiting = [];
    s.on("data", bytes => {
        text += bytes.toString("utf8");
        for(let at; (at = text.indexOf("\n")) >= 0;)
        {
            const line = text.slice(0, at);
            text = text.slice(at + 1);
            const message = JSON.parse(line);
            if(("return" in message || "error" in message) && waiting.length) waiting.shift()(message);
        }
    });
    s.on("error", () => {});
    const command = (execute, args) => new Promise((resolve, reject) => {
        waiting.push(message => message.error ? reject(new Error(execute + ": " + message.error.desc)) : resolve(message.return));
        s.write(JSON.stringify(args ? { execute, arguments: args } : { execute }) + "\n");
    });
    await command("qmp_capabilities");
    return { command, close: () => s.destroy() };
}

/**
 * A tap on QEMU's virtio-multitouch (QMP input-send-event): touched at (x, y)
 * of a width x height screen, released 300 ms later
 */
export async function qemu_touch(qmp, x, y, width, height)
{
    // (the absolute axes' range, INPUT_EVENT_ABS_MAX)
    const vx = Math.round(x * 0x7FFF / (width - 1)), vy = Math.round(y * 0x7FFF / (height - 1));
    const mtt = (type, axis, value) => ({ type: "mtt", data: { type, slot: 0, "tracking-id": 1, axis, value } });
    await qmp.command("input-send-event", { events: [mtt("begin", "x", vx), mtt("data", "x", vx), mtt("data", "y", vy),
        { type: "btn", data: { button: "touch", down: true } }] });
    await new Promise(resolve => setTimeout(resolve, 300));
    await qmp.command("input-send-event", { events: [mtt("end", "x", vx), { type: "btn", data: { button: "touch", down: false } }] });
}

/**
 * The picture's rows [from, to) through the human monitor (screendump), as
 * a digest: quick, for noticing a change
 */
export async function qemu_picture_digest(monitor_socket, file, from, to)
{
    fs.rmSync(file, { force: true });
    await new Promise((resolve, reject) => {
        const s = net.connect(monitor_socket);
        s.on("connect", () => { s.write(`screendump ${file}\n`); setTimeout(() => { s.end(); resolve(); }, 50); });
        s.on("error", reject);
    });
    let bytes = null;
    for(let i = 0; i < 100; i++)
    {
        await new Promise(resolve => setTimeout(resolve, 20));
        if(!fs.existsSync(file)) continue;
        bytes = fs.readFileSync(file);
        const m = /^P6\s+(\d+)\s+(\d+)\s+255\s/.exec(bytes.toString("latin1", 0, 40));
        if(m && bytes.length >= m[0].length + +m[1] * +m[2] * 3)
        {
            const row = +m[1] * 3, start = m[0].length;
            return create_hash("sha1").update(bytes.subarray(start + from * row, start + to * row)).digest("hex");
        }
    }
    return null;
}

/** The Android console (a shell on ttyAMA0) through QEMU's serial socket */
export class AndroidConsole
{
    constructor(socket_path)
    {
        this.socket_path = socket_path;
        this.text = "";
        this.socket = null;
    }

    async open(timeout_ms = 30000)
    {
        const deadline = Date.now() + timeout_ms;
        for(;;)
        {
            try
            {
                this.socket = await new Promise((resolve, reject) => {
                    const s = net.connect(this.socket_path);
                    s.once("connect", () => resolve(s));
                    s.once("error", reject);
                });
                break;
            }
            catch(e)
            {
                if(Date.now() > deadline) throw e;
                await new Promise(r => setTimeout(r, 200));
            }
        }
        this.socket.on("data", bytes => { this.text += bytes.toString("latin1"); });
        return this;
    }

    /** a command's output (between markers), or null when the shell does not answer in time */
    async run(command, timeout_ms = 60000)
    {
        const tag = "V86_" + Math.random().toString(36).slice(2, 10);
        const start = this.text.length;
        this.socket.write(`\necho ${tag}_B; ${command}; echo ${tag}_E $?\n`);
        const deadline = Date.now() + timeout_ms;
        const pattern = new RegExp(`\\n${tag}_B\\r?\\n([\\s\\S]*?)${tag}_E (\\d+)`);
        while(Date.now() < deadline)
        {
            const m = pattern.exec(this.text.slice(start));
            if(m) return { output: m[1].replace(/\r/g, ""), status: +m[2] };
            await new Promise(r => setTimeout(r, 200));
        }
        return null;
    }

    close()
    {
        this.socket?.destroy();
    }
}
                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/a64/android_restore_stall.mjs                                                      0000644 0000000 0000000 00000040504 00000000000 016520  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Debugging docs/aarch64.md's known defect "Android after a restore:
// Launcher3's RenderThread waits for good for ANGLE's post-link tasks":
// Android on v86 (Venus, 4 cores in workers, the page tier) restored from
// A64_STALL_STATE (build/a64-android/android-venus-booted.v7), Launcher3's
// first frames, then A64_STALL_SNAPSHOTS saves and restores into the same
// machine A64_STALL_DELAY_MS after them (while its first programs link);
// after each, a swipe and Launcher3's frames, and if its RenderThread waits
// in ANGLE: every thread's futex and the memory around it.
//
// While a snapshot is saved: which pages of guest RAM and device memory
// changed between the state's capture (get_state) and the end of the
// stream, the renderer's messages and the workers' I/O meanwhile.
//
//   node tests/a64/android_restore_stall.mjs
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { AdbClient } from "./adb.mjs";
import { prepare_device } from "./android_scenario.mjs";
import { PictureSink, save_png } from "../lib/picture_sink.mjs";
import { create_remote_renderer } from "../x64/gpu_remote_renderer.mjs";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const OUT = ROOT + "build/a64-android/out/";
const state_file = process.env.A64_STALL_STATE || ROOT + "build/a64-android/android-venus-booted.v7";
const rounds = +(process.env.A64_STALL_SNAPSHOTS || 1);
const delay = +(process.env.A64_STALL_DELAY_MS ?? 10000);
const directory = ROOT + "build/a64-android/runs/restore-stall/";
fs.mkdirSync(directory, { recursive: true });
const started = performance.now();
const elapsed = () => ((performance.now() - started) / 1000).toFixed(0) + " s";
const log = text => console.log(`${elapsed()}: ${text}`);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const remote = await create_remote_renderer();
// (the renderer's messages to the device while a snapshot is saved)
let saving = false;
const during_save = { messages: {} };
{
    const listen = remote.renderer["listen"];
    remote.renderer["listen"] = handler => listen(message => {
        if(saving) during_save.messages[message["type"]] = (during_save.messages[message["type"]] || 0) + 1;
        handler(message);
    });
}
const sink = new PictureSink();
const emulator = new V86({
    cpu_type: "arm64", cpu_cores: 4, memory_size: 1536 << 20, log_level: 0, autostart: false,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { url: OUT + "Image" }, initrd: { url: OUT + "initrd-venus.img" },
    cmdline: fs.readFileSync(OUT + "cmdline.txt", "utf8").trim(),
    virtio_transport: "pci", virtio_disks: [{ url: OUT + "disk.img", async: true, size: fs.statSync(OUT + "disk.img").size }],
    graphics_adapter: "virtio_gpu", virtio_gpu_pci_slot: 2, screen_adapter: sink,
    graphics_adapter_test: { level: "venus", renderer: remote.renderer },
    net_device: { type: "virtio", count: 3, relay_url: "fetch", id: 2 },
    virtio_console: true, virtio_console_ports: 18, virtio_rng: true, virtio_input: ["keyboard", "multitouch"], virtio_vsock: true,
    // (as android_boot.mjs's machine since P12.5: states saved since have the sound card)
    virtio_sound: true,
    jit_switches: { a64_page: 1 },
    parallel: true, parallel_wasm_path: process.env.A64_PARALLEL_WASM || ROOT + "build/v86-arm64-parallel.wasm",
    // (the bundle's own default is build/vcpu-worker.js of the working directory)
    ...(+process.env.TEST_RELEASE_BUILD ? { vcpu_worker_url: ROOT + "build/vcpu-worker.js" } : {}),
});
emulator.add_listener("emulator-error", error => { console.error("emulator-error:", error); process.exit(1); });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
emulator.add_listener("emulator-ready", () => emulator.set_display_size(720, 1280));
const logcat = fs.openSync(directory + "logcat.log", "w"), kernel = fs.openSync(directory + "kernel.log", "w");
emulator.add_listener("virtio-console2-output-bytes", bytes => fs.writeSync(logcat, bytes));
emulator.add_listener("virtio-console0-output-bytes", bytes => fs.writeSync(kernel, bytes));
const screenshot = name => { emulator.v86?.cpu?.devices?.display?.request_frame(true); return save_png(sink, directory, name); };

async function restore_from(file_name, size)
{
    const file = await fs.promises.open(file_name, "r");
    await emulator.restore_state_stream({ size, read: async (offset, length) => {
        const data = new Uint8Array(length);
        const read = (await file.read(data, 0, length, offset))["bytesRead"];
        return read === length ? data : data.subarray(0, read);
    } });
    await file.close();
}
await restore_from(state_file, fs.statSync(state_file).size);
// (Venus's rings: a vkCreateRingMESA whose ring id is a ring's already, as
// the host's map key, is a collision: the new ring takes the old one's place)
const ring_events = { created: 0, destroyed: 0, collisions: [] };
{
    // (the ids are exact since the fix, 16 hex digits; before it they were
    // numbers: two rings whose numbers are equal shared one id)
    // ("~<number>": a ring of a snapshot saved before the fix)
    const rounded = id => typeof id === "number" ? id : id.startsWith("~") ? Number(id.slice(1)) : Number(BigInt("0x" + id));
    const venus = emulator.v86.cpu.devices.graphics_adapter.device["virtio_gpu"].venus;
    venus.on_command = (name, args) => {
        if(name === "vkDestroyRingMESA") ring_events.destroyed++;
        if(name !== "vkCreateRingMESA") return;
        ring_events.created++;
        for(const ctx of venus.contexts.values())
        {
            for(const id of ctx.rings.keys())
            {
                if(id === args.ring || rounded(id) === rounded(args.ring))
                {
                    const text = `context ${ctx.id}: ring ${args.ring} and ring ${id}`;
                    ring_events.collisions.push(text);
                    log("COLLISION (as numbers): " + text);
                }
            }
        }
    };
}
emulator.run();
log("restored " + state_file);

// adb over vsock (tests/a64/android_boot.mjs's adb_over)
async function shell(command, ms = 300000)
{
    const deadline = Date.now() + 600000;
    for(;;)
    {
        let s;
        try
        {
            s = await emulator.vsock_connect(5555);
            const client = new AdbClient({ write: bytes => s.write(Uint8Array.from(bytes)), set on_data(fn) { s.on_data = bytes => fn(Buffer.from(bytes)); } });
            await client.connect(60000);
            return await client.shell(command, ms);
        }
        catch(e)
        {
            if(Date.now() > deadline) throw e;
            await sleep(5000);
        }
        finally { s?.close(); }
    }
}
const poll = async (command, test, what, ms = 1800000, every = 15000) => {
    const deadline = Date.now() + ms;
    for(let output; ; await sleep(every))
    {
        output = await shell(command);
        if(test(output)) return output;
        assert.ok(Date.now() < deadline, `${what}: ${JSON.stringify(output.slice(-300))}`);
    }
};
const frames = async () => +((await shell("dumpsys -t 300 gfxinfo com.android.launcher3 2>&1 | grep 'Total frames rendered'")).match(/(\d+)/)?.[1] ?? -1);
const top_resumed = "dumpsys -t 300 activity activities 2>&1 | grep -m1 -E 'topResumedActivity|TIMEOUT'";

await prepare_device(shell);
log("device prepared");
await poll("am get-started-user-state 0 2>&1", o => /RUNNING_UNLOCKED/.test(o), "user 0 unlocked", 3600000);
await shell("settings put global captive_portal_mode 0; settings put global stay_on_while_plugged_in 7; settings put system screen_off_timeout 2147483647");
log("user 0 unlocked");
await poll("input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard; " + top_resumed, o => /com\.android\.launcher3\//.test(o), "Launcher3 resumed");
log("Launcher3 resumed");
try
{
    await poll("dumpsys -t 300 gfxinfo com.android.launcher3 2>&1 | grep 'Total frames rendered'", o => /Total frames rendered: [1-9]/.test(o), "first frames",
        +(process.env.A64_STALL_FIRST_FRAMES_MS || 1800000));
}
catch(e)
{
    // (no frames before any snapshot of this run: the restore of A64_STALL_STATE itself)
    log("no first frames: " + e.message);
    await diagnose("before");
    process.exit(2);
}
log("Launcher3's first frames: " + await frames());

// ---- the snapshot, instrumented
const cpu = emulator.v86.cpu;
const page_hashes = (bytes, pages) => {
    const words = new Int32Array(bytes.buffer, bytes.byteOffset, pages * 1024);
    const hashes = new Int32Array(pages);
    for(let page = 0, at = 0; page < pages; page++)
    {
        let h = 0;
        for(const end = at + 1024; at < end; at++) h = Math.imul(h, 31) + words[at] | 0;
        hashes[page] = h;
    }
    return hashes;
};
const ram = () => cpu.mem8.subarray(0, cpu.memory_size[0]);
const device_memory = () => cpu.device_memory ? new Uint8Array(cpu.wasm_memory.buffer, cpu.mem8.byteOffset + cpu.device_memory.start,
    cpu.device_memory.end - cpu.device_memory.start) : null;
let captured = null;
{
    const get_state = cpu.get_state;
    cpu.get_state = function(...args)
    {
        if(saving)
        {
            const t = performance.now();
            const dm = device_memory();
            captured = { ram: page_hashes(ram(), cpu.memory_size[0] / 4096), device: dm && page_hashes(dm, dm.length >> 12),
                served: cpu.parallel.served, ms: 0, rings: venus_rings(), pending: gpu()?.pending.length, held: gpu()?.held };
            captured.ms = Math.round(performance.now() - t);
        }
        return get_state.apply(this, args);
    };
}
const gpu = () => cpu.devices.graphics_adapter?.device?.["virtio_gpu"];
/** Venus's rings and submissions as the save sees them: R running, W:<command> waiting, - idle, F fatal; head/tail */
const venus_rings = () => {
    const g = gpu();
    if(!g?.venus) return null;
    const bytes = g.hostmem_bytes(), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    return [...g.venus.contexts.values()].map(c => ({ ctx: c.id, submissions: c.submissions.length, seqno_waits: c.seqno_waits.length,
        rings: [...c.rings.values()].map(r => (r.fatal ? "F" : !r.run ? "-" : r.run.waiting ? "W:" + r.run.waiting_on.replace(/^vk/, "") : "R") +
            ` ${r.head}/${r.blob.map_offset >= 0 ? view.getUint32(r.blob.map_offset + r.tail_offset, true) : "unmapped"}`) }))
        .filter(c => c.submissions || c.seqno_waits || c.rings.some(r => !r.startsWith("-") || !/ (\d+)\/\1$/.test(r)));
};
async function snapshot(round)
{
    const name = directory + "snapshot.v7";
    await emulator.stop();
    during_save.messages = {};
    const g = gpu();
    const before = { pending: g?.pending.length, held: g?.held, rings: venus_rings(), venus_queues: g?.venus ? [...g.venus.vk.queues].map(q => q.pending.length + "p/" + q.inflight + "i") : null };
    saving = true;
    let bytes = 0;
    const out = await fs.promises.open(name, "w");
    const t0 = performance.now();
    await emulator.save_state_stream(async chunk => { await out.write(chunk, 0, chunk.length, bytes); bytes += chunk.length; });
    await out.close();
    saving = false;
    const save_ms = Math.round(performance.now() - t0);
    // (what changed after the state was captured, with every core parked)
    const changed = { ram: [], device: [] };
    const now_ram = page_hashes(ram(), cpu.memory_size[0] / 4096);
    for(let p = 0; p < now_ram.length; p++) if(now_ram[p] !== captured.ram[p]) changed.ram.push("0x" + (0x40000000 + p * 4096).toString(16));
    const dm = device_memory();
    if(dm)
    {
        const now_device = page_hashes(dm, dm.length >> 12);
        for(let p = 0; p < now_device.length; p++) if(now_device[p] !== captured.device[p]) changed.device.push("+0x" + (p * 4096).toString(16));
    }
    const after = { pending: g?.pending.length, held: g?.held, rings: venus_rings(), venus_queues: g?.venus ? [...g.venus.vk.queues].map(q => q.pending.length + "p/" + q.inflight + "i") : null };
    log(`snapshot ${round}: ${Math.round(bytes / 1048576)} MiB in ${save_ms} ms; hashing ${captured.ms} ms; ` +
        `changed during the save: ${changed.ram.length} RAM pages ${JSON.stringify(changed.ram.slice(0, 16))}, ` +
        `${changed.device.length} device pages ${JSON.stringify(changed.device.slice(0, 16))}; renderer messages ${JSON.stringify(during_save.messages)}; ` +
        `worker I/O served ${cpu.parallel.served - captured.served}; at the capture ${JSON.stringify({ pending: captured.pending, held: captured.held, rings: captured.rings })}; gpu before ${JSON.stringify(before)} after ${JSON.stringify(after)}`);
    if(!+process.env.A64_STALL_SAVE_ONLY)
    {
        // (the renderer's messages while the state is restored: they belong to the machine left behind)
        during_save.messages = {};
        saving = true;
        await restore_from(name, bytes);
        saving = false;
        log(`restored in place; renderer messages meanwhile ${JSON.stringify(during_save.messages)}; gpu pending ${g?.pending.length} held ${g?.held}`);
    }
    emulator.run();
    if(!process.env.A64_KEEP_SNAPSHOT) fs.rmSync(name, { force: true });
}

// ---- after it: does Launcher3 draw?
/**
 * Launcher3's threads (debuggerd -b: every futex wait is interrupted and
 * restarted, so a wait that goes on has an unchanged futex word), each
 * thread's state and syscall, and the memory around the futex words its
 * RenderThread, hwui and ANGLE threads wait on: files named after `tag`
 */
async function diagnose(tag)
{
    const pid = (await shell("pidof com.android.launcher3")).trim();
    const stacks = await shell(`su 0 debuggerd -b ${pid} 2>&1`, 300000);
    fs.writeFileSync(directory + `stacks-${tag}.txt`, stacks);
    const render = /"RenderThread"[\s\S]*?(?=\n"|\n----- end)/.exec(stacks)?.[0] || "";
    const stuck = /waitForPostLinkTasks|AsyncWaitableEvent::wait/.test(render);
    const threads = await shell(`su 0 sh -c 'for t in /proc/${pid}/task/*; do echo "$(basename $t) $(cat $t/comm | tr " " _) $(cut -d" " -f3 $t/stat) $(cat $t/wchan) $(cat $t/syscall)"; done'`);
    fs.writeFileSync(directory + `threads-${tag}.txt`, threads);
    const words = [];
    for(const line of threads.split("\n"))
    {
        const [tid, comm, state, wchan, number, a0, a1, a2] = line.trim().split(/\s+/);
        if(number !== "98" || !/RenderThread|ANGLE|hwui/.test(comm)) continue;
        const address = BigInt(a0);
        const from = address - 128n;
        const dump = await shell(`su 0 dd if=/proc/${pid}/mem bs=8 skip=${from / 8n} count=48 2>/dev/null | od -A x -t x8`);
        words.push(`${tid} ${comm} ${state} ${wchan} futex(0x${address.toString(16)}, op=${a1}, val=${a2}); from 0x${from.toString(16)}:\n${dump}`);
    }
    fs.writeFileSync(directory + `futexes-${tag}.txt`, words.join("\n"));
    // (SystemUI too; the threads of either inside the Venus driver)
    const systemui = await shell(`su 0 debuggerd -b $(pidof com.android.systemui) 2>&1`, 300000);
    fs.writeFileSync(directory + `stacks-systemui-${tag}.txt`, systemui);
    for(const [name, text] of [["launcher3", stacks], ["systemui", systemui]])
    {
        const inside = text.split(/\n(?=")/).filter(t => /vulkan\.virtio\.so/.test(t)).map(t => t.split("\n")[0] + " " + (/\((vn_\w+)\+/.exec(t)?.[1] || ""));
        if(inside.length) log(`${tag}: ${name}'s threads in the Venus driver: ${inside.join(", ")}`);
    }
    log(`${tag}: RenderThread ${stuck ? "WAITS IN ANGLE" : "not in ANGLE's wait"}; threads and futexes in ${directory}`);
    return stuck;
}

async function check(round)
{
    await sleep(30000);
    const f0 = await frames();
    // (the all-apps list, and back)
    await shell("input swipe 360 1100 360 300 300");
    await sleep(45000);
    await shell("input keyevent KEYCODE_BACK");
    await sleep(30000);
    const f1 = await frames();
    await screenshot(`after-${round}`);
    log(`round ${round}: frames ${f0} -> ${f1}`);
    if(f1 > f0) return false;
    await diagnose(`round-${round}`);
    return true;
}

let stalled = false;
for(let round = 1; round <= rounds && !stalled; round++)
{
    await sleep(delay);
    await snapshot(round);
    log("Launcher3 top: " + (await shell(top_resumed)).trim());
    stalled = await check(round);
}
log((stalled ? "STALLED" : "no stall") + "; rings " + JSON.stringify(ring_events));
await emulator.destroy();
remote.close();
process.exit(stalled ? 1 : 0);
                                                                                                                                                                                            source/v64/tests/a64/android_scenario.mjs                                                           0000644 0000000 0000000 00000133706 00000000000 015450  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A9's acceptance on a booted Android 16 (docs/arm64-virt-android16-plan.md
// P11), over adb, the same steps on the QEMU reference and on v86
// (tests/a64/android_boot.mjs A64_ANDROID_SCENARIO=a9):
//
// - the desktop: SELinux enforcing, no keyguard, Launcher3 resumed, a
//   screenshot of it (SurfaceFlinger composing SwiftShader's frames, P11.1);
// - the network (P11.2): Wi-Fi on Cuttlefish's VirtWifi (on the third NIC)
//   gets an address by DHCP; on v86 also DNS and an HTTP request through the
//   fetch adapter to the test's own server (http://<port>.external/), again
//   after Wi-Fi was turned off and on;
// - touch (v86): the virtio multitouch screen is a touch screen, a tap on
//   Gallery's icon opens it;
// - an app (tests/a64/apk.mjs) pushed, installed and started (am start -W);
// - a reboot (PSCI SYSTEM_RESET; the disk's writes kept): boot_completed
//   again, the app and a file in /data still there (P11.3);
// - no service restarting over and over (init's "exited 4 times").
//
// Also A10's (a10_scenario, below), P12.1's native APK record
// (pagesize_scenario, A64_ANDROID_SCENARIO=pagesize) and 32-bit apps on
// arm64 (compat32_scenario, A64_ANDROID_SCENARIO=compat32: the aarch32
// plan's Q5.2, on tools/a64_android.mjs --build a14).
import assert from "node:assert/strict";
import { createHash as create_hash } from "node:crypto";
import fs from "node:fs";
import { build_apk, build_native_lib, APK_PACKAGE } from "./apk.mjs";

const hash = bytes => create_hash("sha256").update(bytes).digest("hex");

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

/**
 * A WAV for the sound step: 16-bit stereo PCM at 48 kHz, two seconds of two
 * tones in which neighbouring samples differ, then half a second of silence
 * (the last period, which a closing tinyplay may not play)
 * @return {{wav: !Buffer, tone: !Buffer}} the file, and the tone's bytes in it
 */
export function sound_wav()
{
    const rate = 48000, frames = rate * 2, silence = rate / 2;
    const data = Buffer.alloc((frames + silence) * 4);
    for(let i = 0; i < frames; i++)
    {
        data.writeInt16LE(Math.round(12000 * Math.sin(2 * Math.PI * 440 * i / rate)) + (i & 7), i * 4);
        data.writeInt16LE(Math.round(9000 * Math.sin(2 * Math.PI * 660 * i / rate)) - (i & 3), i * 4 + 2);
    }
    const header = Buffer.alloc(44);
    header.write("RIFF", 0, "latin1");
    header.writeUInt32LE(36 + data.length, 4);
    header.write("WAVEfmt ", 8, "latin1");
    header.writeUInt32LE(16, 16);
    header.writeUInt16LE(1, 20);
    header.writeUInt16LE(2, 22);
    header.writeUInt32LE(rate, 24);
    header.writeUInt32LE(rate * 4, 28);
    header.writeUInt16LE(4, 32);
    header.writeUInt16LE(16, 34);
    header.write("data", 36, "latin1");
    header.writeUInt32LE(data.length, 40);
    return { wav: Buffer.concat([header, data]), tone: data.subarray(0, frames * 4) };
}

/**
 * The tone in what the card played (48 kHz stereo S16, the left channel):
 * the loud part (samples beyond 1/8 of the peak), its length, its frequency
 * from its zero crossings, its peak
 * @param {!Buffer} pcm
 * @return {{bytes: number, peak: number, seconds: number, frequency: number}}
 */
export function tone_of(pcm)
{
    const frames = pcm.length >> 2;
    let peak = 0;
    for(let i = 0; i < frames; i++) peak = Math.max(peak, Math.abs(pcm.readInt16LE(i * 4)));
    const loud = Math.max(1, peak >> 3);
    let first = -1, last = -1, crossings = 0, previous = 0;
    for(let i = 0; i < frames; i++)
    {
        const v = pcm.readInt16LE(i * 4);
        if(Math.abs(v) >= loud)
        {
            if(first < 0) first = i;
            last = i;
        }
        if(first >= 0 && v !== 0)
        {
            if(previous && (v > 0) !== (previous > 0)) crossings++;
            previous = v;
        }
    }
    const seconds = first < 0 ? 0 : (last - first + 1) / 48000;
    return { bytes: pcm.length, peak, seconds: Math.round(seconds * 1000) / 1000, frequency: seconds ? Math.round(crossings / 2 / seconds) : 0 };
}

/**
 * The device's settings for the test, retried until the services answer: on
 * v86 as soon as adb answers, long before SystemUI starts.
 * - The lock screen off (locksettings set-disabled). SystemUI sets up its
 *   keyguard as showing unless the lock screen is disabled; on v86's slow
 *   first boot its SYSTEM_READY then never shows it (no SHOW: provisioning
 *   had not finished), so its mediator ignores every dismissal while the
 *   window manager keeps the keyguard's sleep token, and the home activity
 *   stays paused. QEMU's TCG boot usually shows and dismisses it in time,
 *   but not always (2026-10-19): there the console sets these while
 *   booting (tests/a64/android_boot.mjs).
 * - No window, transition or animator animations: SwiftShader draws every
 *   frame on the CPU, and on v86 Launcher3's first frames took minutes (its
 *   ReferenceQueueDaemon then timed out, ART's finalizer watchdog killed it),
 *   as test setups do (CTS turns the animations off). Blur is asked off too,
 *   unchecked: "wm disable-blur true" leaves this build's window manager
 *   reporting "Blur enabled: true".
 * - No bug reports from UWB's device errors (DeviceConfig uwb's
 *   device_error_bugreport_enabled false; the session one is not on the
 *   shell's allowlist): Cuttlefish's UWB HAL talks to the host's pica on
 *   hvc9, which neither v86 nor the reference has, so UWB's initialisation
 *   times out, and on a userdebug build UwbServiceCore then asks for a full
 *   bug report: dumpstate for minutes on v86 (every process's native
 *   stacks), Android barely moving meanwhile.
 * @param {function(string, number=): !Promise<string>} adb
 * @return {!Promise<void>}
 */
export async function prepare_device(adb, ms = 3600000)
{
    const deadline = Date.now() + ms;
    for(let output; ; await sleep(15000))
    {
        output = await adb(PREPARE_COMMAND);
        if(device_prepared(output)) return;
        assert.ok(Date.now() < deadline, "the device's settings: " + JSON.stringify(output.slice(-300)));
    }
}

/** prepare_device's command (one try; also from QEMU's console while booting) */
export const PREPARE_COMMAND = "locksettings set-disabled true >/dev/null 2>&1; " +
    "for s in window_animation_scale transition_animation_scale animator_duration_scale; do settings put global $s 0 >/dev/null 2>&1; done; " +
    "settings put global disable_window_blurs 1 >/dev/null 2>&1; wm disable-blur true >/dev/null 2>&1; " +
    "device_config put uwb device_error_bugreport_enabled false >/dev/null 2>&1; " +
    "echo L=$(locksettings get-disabled 2>&1) W=$(settings get global window_animation_scale 2>&1) " +
    "T=$(settings get global transition_animation_scale 2>&1) A=$(settings get global animator_duration_scale 2>&1) " +
    "U=$(device_config get uwb device_error_bugreport_enabled 2>&1)";

/** whether PREPARE_COMMAND's output says every setting took */
export const device_prepared = output => /L=true W=0(\.0)? T=0(\.0)? A=0(\.0)? U=false\s*$/.test(output);

/**
 * @param {{target: string, adb: function(string, number=): !Promise<string>, push: function(string, !Buffer): !Promise<void>,
 *     reboot: function(): !Promise<void>, screenshot: function(string): !Promise<?string>, touch: ?function(number, number): !Promise<void>,
 *     http: ?{port: number, token: string}, wait_reboot: function(): !Promise<void>, log: function(string)}} env
 *     adb: a shell command's output (a new connection each time, retried while adbd is away)
 * @return {!Promise<!Object>} what it found
 */
export async function a9_scenario(env)
{
    const result = {};
    const { adb, log } = env;
    const poll = async (command, test, what, ms = 600000, every = 5000) => {
        const deadline = Date.now() + ms;
        for(let output; ; await sleep(every))
        {
            output = await adb(command, 600000);
            if(test(output)) return output;
            assert.ok(Date.now() < deadline, `${what}: ${JSON.stringify(output.slice(-300))}`);
        }
    };

    // (dumpsys gives up on a service after 10 s, on stderr; a dump of the
    // activities takes longer than that on v86)
    const top_resumed = "dumpsys -t 300 activity activities 2>&1 | grep -m1 -E 'topResumedActivity|TIMEOUT'";

    // the desktop. sys.boot_completed comes before the user is unlocked: on
    // v86's first boot the receivers of PRE_BOOT_COMPLETED and BOOT_COMPLETED
    // take another ten minutes, with FallbackHome on the screen; Launcher3
    // starts after the unlock. The lock screen is off (prepare_device, on
    // v86 already since adb answered); a keyguard that shows anyway is
    // dismissed while waiting for Launcher3
    result.selinux = (await adb("getenforce")).trim();
    assert.equal(result.selinux, "Enforcing", "SELinux enforcing");
    await prepare_device(adb);
    const booted = Date.now();
    await poll("am get-started-user-state 0 2>&1", o => /RUNNING_UNLOCKED/.test(o), "user 0 unlocked", 3600000, 15000);
    result.unlock_after_boot_ms = Date.now() - booted;
    await adb("settings put global captive_portal_mode 0; settings put global stay_on_while_plugged_in 7; " +
        "settings put system screen_off_timeout 2147483647");
    result.home = (await poll("input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard; " + top_resumed,
        o => /com\.android\.launcher3\//.test(o), "Launcher3 resumed", 1200000, 15000)).trim();
    await sleep(5000);
    result.screenshots = { home: await env.screenshot("home") };
    log("desktop: " + result.home);
    // what draws (ANGLE's renderer string: SwiftShader or Venus), and frame
    // times (P11.4 V4): Launcher3's all-apps list opened by a swipe up and
    // closed by Back, once (cold: its shaders and pipelines made on the way)
    // and then three times (warm), with Launcher3's frame statistics of each;
    // pictures of the list and of the desktop (the one above can be the
    // FallbackHome's, Launcher3's first frame still to come)
    result.gles = (await adb("dumpsys -t 300 SurfaceFlinger 2>&1 | grep -m1 '^GLES'")).trim();
    // (the OpenGL ES version apps are told: the bootconfig's, 3.0 on Venus, 3.1 on SwiftShader)
    result.opengles = +(await adb("getprop ro.opengles.version")).trim();
    log("ro.opengles.version: " + result.opengles + " (" + (result.opengles >> 16) + "." + (result.opengles & 0xFFFF) + ")");
    const frames = async cycles => {
        await adb("dumpsys gfxinfo com.android.launcher3 reset >/dev/null 2>&1");
        for(let i = 0; i < cycles; i++)
        {
            await adb("input swipe 360 1100 360 300 300");
            await sleep(5000);
            if(cycles === 1) result.screenshots.all_apps = await env.screenshot("all-apps");
            await adb("input keyevent KEYCODE_BACK");
            await sleep(5000);
        }
        // (again after 10 s when the statistics are not in it, F6: once at
        // 16K the cold ones were missing; then the start of what it said)
        let gfxinfo = "";
        for(let attempt = 0; attempt < 2 && !/Total frames rendered: \d+/.test(gfxinfo); attempt++)
        {
            if(attempt) await sleep(10000);
            gfxinfo = await adb("dumpsys -t 300 gfxinfo com.android.launcher3 2>&1", 600000);
        }
        const stat = name => +(gfxinfo.match(new RegExp(name + ": (\\d+)"))?.[1] ?? NaN);
        return { total: stat("Total frames rendered"), janky: stat("Janky frames"), p50_ms: stat("50th percentile"),
            p90_ms: stat("90th percentile"), p99_ms: stat("99th percentile"),
            ...(/Total frames rendered: \d+/.test(gfxinfo) ? {} : { gfxinfo: gfxinfo.slice(0, 1500) }) };
    };
    result.frames_cold = await frames(1);
    result.frames = await frames(3);
    result.screenshots.desktop = await env.screenshot("desktop");
    log("frames: cold " + JSON.stringify(result.frames_cold) + ", warm " + JSON.stringify(result.frames) + ", " + result.gles);

    // the network: Cuttlefish's VirtWifi (on v86, enabled from here; the reference's harness did it before adb)
    await adb("cmd wifi set-wifi-enabled enabled");
    await poll("cmd wifi status | grep -m1 -i 'wifi is enabled'", o => /enabled/i.test(o), "Wi-Fi on", 120000);
    // (on v86 DHCP on wlan0 can fail: the network is then disabled for five
    // minutes after two failures; connecting again by hand lifts that, every
    // two minutes without an address)
    const wifi_address = async what => {
        const deadline = Date.now() + 2400000;
        for(let tries = 0; ; tries++)
        {
            if(tries % 8 === 0) await adb("cmd wifi connect-network VirtWifi open");
            const output = await adb("ip -4 -o addr show wlan0 2>&1");
            if(/inet \d+\.\d+\.\d+\.\d+/.test(output)) return output.match(/inet (\S+)/)[1];
            assert.ok(Date.now() < deadline, `${what}: ${JSON.stringify(output.slice(-300))}`);
            await sleep(15000);
        }
    };
    result.wifi_address = await wifi_address("an address on wlan0");
    log("network: wlan0 " + result.wifi_address);
    if(env.http)
    {
        const host = `${env.http.port}.external`;
        const get = `printf 'GET /v86-android HTTP/1.0\\r\\nHost: ${host}\\r\\n\\r\\n' | nc -w 30 ${host} 80`;
        const fetched = await poll(get, o => o.includes(env.http.token), "HTTP through the fetch adapter", 300000, 10000);
        assert.match(fetched, /^HTTP\/1\.[01] 200/m, "HTTP 200");
        // (recovery: Wi-Fi off and on reconnects to the saved network)
        await adb("cmd wifi set-wifi-enabled disabled");
        await poll("ip -4 -o addr show wlan0 2>&1", o => !/inet \d/.test(o), "wlan0 without an address after Wi-Fi off", 120000);
        await adb("cmd wifi set-wifi-enabled enabled");
        await wifi_address("an address on wlan0 after Wi-Fi off and on");
        await poll(get, o => o.includes(env.http.token), "HTTP again after Wi-Fi off and on", 600000, 10000);
        result.http = "ok, and after Wi-Fi off and on";
        log("network: HTTP via " + host);
    }

    // touch: the virtio multitouch screen, a tap on Gallery's icon in the
    // default workspace, once Launcher3 has drawn it (its bounds from
    // uiautomator: on v86 the first frames of the workspace come minutes
    // after Launcher3 is resumed)
    if(env.touch)
    {
        const input = await adb("dumpsys -t 300 input 2>&1", 600000);
        assert.match(input, /QEMU Virtio MultiTouch[\s\S]*?DeviceType: TOUCH_SCREEN/, "the multitouch device is a touch screen");
        const node = await poll("uiautomator dump /data/local/tmp/ui.xml >/dev/null 2>&1; grep -o 'text=\"Gallery\"[^>]*bounds=\"[^\"]*\"' /data/local/tmp/ui.xml",
            o => /bounds="\[\d+,\d+\]\[\d+,\d+\]"/.test(o), "Gallery's icon on the workspace", 1800000, 15000);
        const [x1, y1, x2, y2] = node.match(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/).slice(1).map(Number);
        result.gallery_icon = [x1, y1, x2, y2];
        await env.touch(Math.round((x1 + x2) / 2), Math.round((y1 + y2) / 2));
        result.touch = (await poll(top_resumed, o => /gallery/i.test(o), "Gallery opened by the tap", 600000, 15000)).trim();
        await sleep(5000);
        result.screenshots.touch = await env.screenshot("touch");
        await adb("input keyevent KEYCODE_HOME");
        log("touch: " + result.touch);
    }

    // an app: pushed, installed, started
    await env.push("/data/local/tmp/v86-hello.apk", build_apk());
    result.install = (await adb("pm install -r /data/local/tmp/v86-hello.apk 2>&1", 600000)).trim();
    assert.match(result.install, /^Success/m, "pm install");
    const started = await adb(`am start -W -n ${APK_PACKAGE}/android.app.Activity 2>&1`, 600000);
    assert.match(started, /Status: ok/, "am start: " + started);
    result.app_start_ms = +started.match(/TotalTime: (\d+)/)?.[1];
    await sleep(5000);
    result.screenshots.app = await env.screenshot("app");
    log(`app: installed, started in ${result.app_start_ms} ms`);

    // a reboot: the app and a file in /data stay
    await adb("echo v86-a9 > /data/local/tmp/v86-marker; sync");
    const rebooted = Date.now();
    await env.reboot();
    await env.wait_reboot();
    await poll("getprop sys.boot_completed", o => o.trim() === "1", "boot_completed after the reboot", 7200000, 10000);
    result.second_boot_ms = Date.now() - rebooted;
    assert.equal((await adb("cat /data/local/tmp/v86-marker")).trim(), "v86-a9", "the file in /data after the reboot");
    assert.match(await adb(`pm list packages ${APK_PACKAGE}`), new RegExp(`package:${APK_PACKAGE.replace(/\./g, "\\.")}`), "the app after the reboot");
    assert.equal((await adb("getenforce")).trim(), "Enforcing", "SELinux enforcing after the reboot");
    log(`reboot: boot_completed again after ${Math.round(result.second_boot_ms / 1000)} s, the app and /data kept`);

    // no service restarting over and over (init's "exited 4 times before boot completed"),
    // and the apps that crashed or did not respond since the reboot (for the record)
    const crashing = await adb("logcat -d -b all 2>/dev/null | grep 'exited 4 times' | sort -u | head -5");
    result.crashing = crashing.trim().split("\n").filter(Boolean);
    result.dhcp_failures = +(await adb("logcat -d -b all 2>/dev/null | grep -c 'Disable counter for network VirtWifi for reason NETWORK_SELECTION_DISABLED_DHCP_FAILURE'")).trim();
    result.app_crashes = (await adb("logcat -d -b events 2>/dev/null | grep -E 'am_crash|am_anr' | cut -c1-200 | head -20")).trim().split("\n").filter(Boolean);
    result.screenshots.after_reboot = await env.screenshot("after-reboot");
    return result;
}

/**
 * A10's runs on the desktop (P12.2, P12.3; tests/a64/android_boot.mjs
 * A64_ANDROID_SCENARIO=a10, on v86 with Venus):
 * - the desktop, as A9's, with Launcher3's first frames drawn;
 * - a snapshot of it: the first run saves it (env.snapshot,
 *   A64_ANDROID_A10_SAVE) and ends there; a second run restores it into a
 *   new machine (env.restored) and goes on: a tap (the multitouch screen)
 *   that opens Gallery, and what follows;
 * - input latency (env.tap_latency): five taps on Gallery's icon, each
 *   timed on the host from the touch to the first change of the screen's
 *   middle (Gallery's starting window), then Home (Android's own latency
 *   histograms stay empty here); a tap that opens nothing leaves the
 *   stalled guest's interrupts, run queues and UI threads' stacks
 *   (stall_diagnostics);
 * - sustained frame rate (P12.3): tests/a64/android/v86frames.c's app draws
 *   OpenGL ES frames for a minute and reports its rate;
 * - a long run: monkey for 30 minutes (env.monkey_minutes) with a fixed seed, on apps that can
 *   neither turn adb off nor call out (no Settings, Dialer, browser);
 * - sound (env.sound: v86's virtio_sound, QEMU's virtio-sound-pci into a
 *   WAV): sound_wav()'s file played with tinyplay on the virtio-snd card,
 *   the bytes the device played, as the host received them, hold the tone
 *   exactly; then v86tone.c's AAudio tone through AudioFlinger and the audio
 *   HAL, its frequency and length on the host (P12.5);
 * - memory pressure: the launcher's apps started one after another until
 *   lmkd kills a process; zram swap holds what twelve apps need, so then
 *   random bytes (zram cannot compress them) fill a tmpfs file 100 MiB at a
 *   time until it does, and the file goes;
 * - system_server, surfaceflinger and zygote64 the same processes from the
 *   desktop to the end (P10.3's budget: none of them may restart), and no
 *   service restarting over and over.
 * @param {!Object} env as a9_scenario's, with snapshot: ?function(): !Promise<!Object>,
 *     steps: the steps after the desktop to take (touch, frames, sound, monkey, memory; null: all)
 * @return {!Promise<!Object>} what it found
 */
export async function a10_scenario(env)
{
    const result = { screenshots: {} };
    const { adb, log } = env;
    const step = name => !env.steps || env.steps.includes(name);
    const poll = async (command, test, what, ms = 600000, every = 5000) => {
        const deadline = Date.now() + ms;
        for(let output; ; await sleep(every))
        {
            output = await adb(command, 600000);
            if(test(output)) return output;
            assert.ok(Date.now() < deadline, `${what}: ${JSON.stringify(output.slice(-300))}`);
        }
    };
    const top_resumed = "dumpsys -t 300 activity activities 2>&1 | grep -m1 -E 'topResumedActivity|TIMEOUT'";
    const core_pids = async () => {
        const pids = {};
        // (the oldest, the lowest pid, of each name: zygote64's prespecialized app processes have its name too)
        for(const name of ["system_server", "surfaceflinger", "zygote64"]) pids[name] = (await adb(`pidof ${name} | tr ' ' '\\n' | sort -n | head -1`)).trim();
        return pids;
    };

    // the desktop, drawn
    assert.equal((await adb("getenforce")).trim(), "Enforcing", "SELinux enforcing");
    await prepare_device(adb);
    await poll("am get-started-user-state 0 2>&1", o => /RUNNING_UNLOCKED/.test(o), "user 0 unlocked", 3600000, 15000);
    await adb("settings put global captive_portal_mode 0; settings put global stay_on_while_plugged_in 7; " +
        "settings put system screen_off_timeout 2147483647");
    result.home = (await poll("input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard; " + top_resumed,
        o => /com\.android\.launcher3\//.test(o), "Launcher3 resumed", 1200000, 15000)).trim();
    await poll("dumpsys -t 300 gfxinfo com.android.launcher3 2>&1 | grep 'Total frames rendered'",
        o => /Total frames rendered: [1-9]/.test(o), "Launcher3's first frames", 1800000, 15000);
    await sleep(10000);
    result.pids = await core_pids();
    result.screenshots.desktop = await env.screenshot("desktop");
    result.opengles = +(await adb("getprop ro.opengles.version")).trim();
    log("desktop: drawn; " + JSON.stringify(result.pids) + "; ro.opengles.version " + result.opengles);

    // a snapshot of the desktop: saved (the first run ends there), or restored and going on.
    // (saved when Launcher3 is quiet, its frame count the same for a minute:
    // a settled desktop. The RenderThreads that once waited for ANGLE's
    // post-link tasks for good after a restore had lost a Venus ring before
    // the save, two threads' ring ids merged, fixed in 5238279c)
    if(env.snapshot)
    {
        const frames = async () => +((await adb("dumpsys -t 300 gfxinfo com.android.launcher3 2>&1 | grep 'Total frames rendered'")).match(/(\d+)/)?.[1] ?? -1);
        for(let last = -2, same = 0, deadline = Date.now() + 900000; same < 3 && Date.now() < deadline; await sleep(20000))
        {
            const now = await frames();
            same = now === last ? same + 1 : 0;
            last = now;
        }
        result.snapshot = await env.snapshot();
        log("snapshot: " + JSON.stringify(result.snapshot));
        if(result.snapshot.saved) return result;
        result.screenshots.restored = await env.screenshot("restored");
    }
    if(env.restored) result.snapshot = { restored: env.restored };
    if(env.probe) await env.probe();
    if(env.snapshot || env.restored)
    {
        assert.match(await adb(top_resumed), /com\.android\.launcher3\//, "Launcher3 after the snapshot");
    }
    if(env.touch && step("touch"))
    {
        const node = await poll("uiautomator dump /data/local/tmp/ui.xml >/dev/null 2>&1; grep -o 'text=\"Gallery\"[^>]*bounds=\"[^\"]*\"' /data/local/tmp/ui.xml",
            o => /bounds="\[\d+,\d+\]\[\d+,\d+\]"/.test(o), "Gallery's icon on the workspace", 1800000, 15000);
        const [x1, y1, x2, y2] = node.match(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/).slice(1).map(Number);
        const [x, y] = [Math.round((x1 + x2) / 2), Math.round((y1 + y2) / 2)];
        const home = async () => {
            await adb("input keyevent KEYCODE_HOME");
            await poll(top_resumed, o => /com\.android\.launcher3\//.test(o), "Launcher3 again", 600000, 15000);
            await sleep(10000);
        };
        await env.touch(x, y);
        try
        {
            result.touch = (await poll(top_resumed, o => /gallery/i.test(o), "Gallery opened by the tap", 600000, 15000)).trim();
        }
        catch(e)
        {
            // (the restore stall, docs/aarch64.md: what the CPUs and the UI's threads are doing)
            result.stall = await stall_diagnostics(adb, env.directory || null);
            log("stall: " + JSON.stringify(result.stall).slice(0, 30000));
            throw e;
        }
        await home();
        log("touch: " + result.touch);

        // input latency: the tap again, timed to the screen's first change
        if(env.tap_latency)
        {
            result.input_latency_ms = [];
            for(let i = 0; i < 5; i++)
            {
                result.input_latency_ms.push(await env.tap_latency(x, y));
                await poll(top_resumed, o => /gallery/i.test(o), "Gallery opened by the timed tap", 600000, 15000);
                await home();
            }
            const sorted = result.input_latency_ms.filter(ms => ms !== null).sort((a, b) => a - b);
            result.input_latency_median_ms = sorted.length ? sorted[sorted.length >> 1] : null;
            log("input latency: " + JSON.stringify(result.input_latency_ms) + ", median " + result.input_latency_median_ms + " ms");
        }
    }

    // sustained frame rate (P12.3): tests/a64/android/v86frames.c's app, a
    // minute of OpenGL ES frames on its window (ANGLE over the guest's
    // Vulkan), its own count and rate: its swaps wait for the buffers
    // SurfaceFlinger has not released, so they are the frames that reach the
    // screen (this SurfaceFlinger has no frame counter: transaction 1013 is
    // gone)
    if(step("frames"))
    {
        const lib = build_native_lib(16384, "v86frames", ["-landroid", "-llog", "-lEGL", "-lGLESv2", "-lm"]);
        await env.push("/data/local/tmp/v86-frames.apk", build_apk({ label: "v86 frames", package_name: "org.v86.frames",
            native: { name: "v86frames", lib, extract: true, zip_align: 16384 } }));
        assert.match(await adb("pm install -r /data/local/tmp/v86-frames.apk 2>&1", 600000), /^Success/m, "pm install v86-frames.apk");
        await adb("logcat -c");
        await adb("am start -W -n org.v86.frames/android.app.NativeActivity >/dev/null 2>&1", 600000);
        const line = await poll("logcat -d -s v86frames:I 2>&1 | grep -E 'V86_FRAMES (frames|error)'", o => /V86_FRAMES (frames|error)/.test(o),
            "the frame rate app's result", 1800000, 10000);
        const m = /V86_FRAMES frames=(\d+) seconds=([\d.]+) fps=([\d.]+)/.exec(line);
        result.frame_rate = { app_frames: m ? +m[1] : null, seconds: m ? +m[2] : null, fps: m ? +m[3] : null,
            renderer: (await adb("logcat -d -s v86frames:I 2>&1 | grep -o 'renderer=.*' | head -1")).trim(),
            progress: (await adb("logcat -d -s v86frames:I 2>&1 | grep -o 'progress.*'")).trim().split("\n").filter(Boolean) };
        await adb("am force-stop org.v86.frames; pm uninstall org.v86.frames >/dev/null 2>&1; input keyevent KEYCODE_HOME");
        log("frame rate: " + JSON.stringify(result.frame_rate));
        assert.ok(m, "the frame rate app ran: " + JSON.stringify(line));
    }

    // sound: tinyplay on the virtio-snd card, the PCM compared on the host
    if(env.sound && step("sound"))
    {
        const { wav, tone } = sound_wav();
        await env.push("/data/local/tmp/v86-tone.wav", wav);
        const cards = await adb("su 0 cat /proc/asound/cards");
        const card = cards.match(/^\s*(\d+)\s+\[[^\]]*\]:\s*virtio/im)?.[1];
        assert.ok(card !== undefined, "a virtio-snd card: " + JSON.stringify(cards));
        env.sound.reset();
        // (the largest buffer the kernel's virtio-snd driver allows, 160 ms of
        // its widest format, 320 ms of this one: tinyplay's 85 ms underran
        // on v86 while the system still dealt with the frame step's
        // uninstall, and the restart lost a period, as a card would)
        const played_out = await adb(`su 0 tinyplay /data/local/tmp/v86-tone.wav -D ${card} -d 0 -p 1920 -n 8 2>&1`, 600000);
        await sleep(3000);
        const played = env.sound.played();
        const at = played.indexOf(tone.subarray(0, 4096));
        result.sound = { card: +card, tinyplay: played_out.trim().slice(-200), bytes: played.length, tone_at: at,
            sha256: hash(played.subarray(Math.max(0, at), Math.max(0, at) + tone.length)), expected: hash(tone) };
        log("sound: " + JSON.stringify(result.sound));
        // (v86's device must play every byte; QEMU's virtio-sound-pci drops
        // samples when the emulator runs slower than real time, TCG: there
        // it is recorded)
        result.sound.exact = at >= 0 && result.sound.sha256 === result.sound.expected;
        assert.ok(result.sound.exact || env.target !== "v86" && at >= 0, "the tone played, byte for byte: " + JSON.stringify(result.sound));

        // the framework's path: tests/a64/android/v86tone.c's AAudio stream
        // through AudioFlinger and the audio HAL (tinyalsa, card 0 device 0)
        // to the card; mixed at the stream's volume, so its frequency and
        // length are checked. The HAL (AHAL_StreamPrimary) skips a transfer,
        // the frames accepted but not written, whenever its writes have
        // fallen behind real time ("a workaround for the emulator
        // implementation", b/302587331): a guest slower than real time hears
        // nothing. So the HAL must open the card; the tone must arrive whole
        // unless transfers were skipped, which is recorded with the HAL's
        // offsets (its verbose log)
        const lib = build_native_lib(16384, "v86tone", ["-landroid", "-llog", "-laaudio", "-lm"]);
        await env.push("/data/local/tmp/v86-tone.apk", build_apk({ label: "v86 tone", package_name: "org.v86.tone",
            native: { name: "v86tone", lib, extract: true, zip_align: 16384 } }));
        assert.match(await adb("pm install -r /data/local/tmp/v86-tone.apk 2>&1", 600000), /^Success/m, "pm install v86-tone.apk");
        await adb("logcat -c; setprop log.tag.AHAL_StreamPrimary V");
        env.sound.reset();
        // (A64_ANDROID_SOUND_PROFILE=1: simpleperf's cpu-clock samples of
        // every CPU while the tone plays, the report in the run's directory)
        const profile = !!process.env.A64_ANDROID_SOUND_PROFILE;
        let recording = null;
        if(profile)
        {
            // (Android hardens perf events: security.perf_harden 0 lets root sample)
            await adb("su 0 setprop security.perf_harden 0; sleep 1");
            recording = adb("su 0 simpleperf record -e cpu-clock -f 1000 -a --duration 25 " +
                "-o /data/local/tmp/sound.perf 2>&1", 900000);
            await sleep(5000);
        }
        await adb("am start -W -n org.v86.tone/android.app.NativeActivity >/dev/null 2>&1", 600000);
        const line = await poll("logcat -d -s v86tone:I 2>&1 | grep -E 'V86_TONE (frames|error)'", o => /V86_TONE (frames|error)/.test(o),
            "the tone app's result", 900000, 5000);
        await sleep(3000);
        result.sound_framework = { app: line.trim().replace(/^.*V86_TONE /s, ""), ...tone_of(env.sound.played()) };
        // (for the run's directory: the HAL's log by the guest's monotonic
        // clock, and AudioFlinger's output threads' timing statistics)
        const timing = await adb("logcat -d -v monotonic 2>&1 | grep -E 'AHAL_Stream|v86tone' | cut -c1-200; " +
            "dumpsys -t 300 media.audio_flinger 2>&1 | grep -E 'Output thread|frame count|Process time|jitter|latency stats|writes|Standby|Sample rate|underrun' | cut -c1-200", 600000);
        if(env.directory) fs.writeFileSync(env.directory + "sound-timing.txt", timing);
        if(profile)
        {
            const recorded = await recording;
            const report = recorded + await adb("su 0 sh -c '" +
                "simpleperf report -i /data/local/tmp/sound.perf --sort pid,comm --percent-limit 0.3 2>&1 | head -60; " +
                "simpleperf report -i /data/local/tmp/sound.perf --sort dso,symbol --percent-limit 0.4 2>&1 | head -100; " +
                "simpleperf report -i /data/local/tmp/sound.perf --sort tid,comm --percent-limit 0.3 2>&1 | head -60'", 900000);
            if(env.directory) fs.writeFileSync(env.directory + "sound-profile.txt", report);
            log("sound profile: " + report.split("\n").slice(0, 40).join("\n"));
        }
        const hal = await adb("logcat -d 2>&1 | grep -E 'proxy_open|skipping transfer|totalOffsetUs' | cut -c1-160");
        await adb("setprop log.tag.AHAL_StreamPrimary ''; am force-stop org.v86.tone; pm uninstall org.v86.tone >/dev/null 2>&1; input keyevent KEYCODE_HOME");
        const offsets = [...hal.matchAll(/totalOffsetUs (-?\d+)/g)].map(m => +m[1]);
        result.sound_framework.hal = { opened: /proxy_open\(card:0 device:0 PCM_OUT\)/.test(hal), skipped: (hal.match(/skipping transfer/g) || []).length,
            offsets_us: offsets.length ? [offsets[0], Math.min(...offsets), offsets.at(-1)] : [] };
        log("sound through the framework: " + JSON.stringify(result.sound_framework));
        assert.ok(result.sound_framework.hal.opened, "the audio HAL opened the virtio-snd card: " + JSON.stringify(result.sound_framework));
        const whole = Math.abs(result.sound_framework.frequency - 1000) <= 20 && result.sound_framework.seconds >= 1.5;
        assert.ok(whole || result.sound_framework.hal.skipped > 0,
            "AAudio's 1 kHz tone through AudioFlinger and the HAL: " + JSON.stringify(result.sound_framework));
    }

    // a long run: 30 minutes of monkey (seed 86), crashes and ANRs ignored and counted
    if(step("monkey"))
    {
        const monkey_apps = ["com.android.launcher3", "com.android.gallery3d", "com.android.calendar", "com.android.contacts",
            "com.android.deskclock", "com.android.messaging", "com.android.documentsui"];
        const started_monkey = Date.now();
        const minutes = env.monkey_minutes || 30;
        const monkey = await adb(`timeout ${minutes * 60} monkey -s 86 --throttle 500 --pct-syskeys 0 --pct-anyevent 0 ` +
            "--ignore-crashes --ignore-timeouts --ignore-security-exceptions " + monkey_apps.map(p => "-p " + p).join(" ") +
            " -v 1000000 2>&1 | grep -c -E '^:Sending|^    // '; echo monkey-done", (minutes + 15) * 60000);
        result.monkey = { minutes: Math.round((Date.now() - started_monkey) / 60000), lines: +(monkey.match(/^(\d+)/m)?.[1] ?? 0) };
        result.monkey.crashes = (await adb("logcat -d -b events 2>/dev/null | grep -E 'am_crash|am_anr' | cut -c1-200 | tail -20")).trim().split("\n").filter(Boolean);
        await adb("input keyevent KEYCODE_HOME");
        log("long run: " + JSON.stringify(result.monkey).slice(0, 300));
    }

    // memory pressure: the launcher's apps, one after another, until lmkd kills
    if(step("memory"))
    {
        await adb("logcat -c");
        const apps = (await adb("cmd package query-activities --brief -a android.intent.action.MAIN -c android.intent.category.LAUNCHER 2>&1"))
            .split("\n").map(line => line.trim()).filter(line => /^[\w.]+\/[\w.$]+$/.test(line));
        result.memory = { apps: apps.length, started: 0, kills: 0 };
        for(let round = 0; round < 3 && !result.memory.kills; round++)
        {
            for(const app of apps)
            {
                await adb(`am start -W -n ${app} >/dev/null 2>&1`, 600000);
                result.memory.started++;
                await sleep(5000);
                result.memory.kills = +(await adb("logcat -d -s lowmemorykiller 2>/dev/null | grep -c 'Kill'")).trim() || 0;
                if(result.memory.kills) break;
            }
        }
        result.memory.hog_mib = 0;
        while(!result.memory.kills && result.memory.hog_mib < 1500)
        {
            await adb("su 0 sh -c 'dd if=/dev/urandom bs=1048576 count=100 >> /dev/v86-hog 2>/dev/null'", 900000);
            result.memory.hog_mib += 100;
            await sleep(5000);
            result.memory.kills = +(await adb("logcat -d -s lowmemorykiller 2>/dev/null | grep -c 'Kill'")).trim() || 0;
        }
        result.memory.hog_bytes = +(await adb("su 0 stat -c %s /dev/v86-hog 2>/dev/null")).trim() || 0;
        await adb("su 0 rm -f /dev/v86-hog");
        result.memory.killed = (await adb("logcat -d -s lowmemorykiller 2>/dev/null | grep 'Kill' | cut -c1-200 | head -5")).trim().split("\n").filter(Boolean);
        result.memory.meminfo = (await adb("grep -E 'MemTotal|MemAvailable|SwapTotal|SwapFree' /proc/meminfo")).trim();
        await adb("input keyevent KEYCODE_HOME");
        log("memory pressure: " + JSON.stringify({ ...result.memory, killed: result.memory.killed.length }));
        assert.ok(result.memory.kills > 0, "lmkd killed a process: " + JSON.stringify(result.memory));
    }

    // the core services kept, nothing restarting over and over
    result.pids_after = await core_pids();
    assert.deepEqual(result.pids_after, result.pids, "system_server, surfaceflinger and zygote64 not restarted");
    result.crashing = (await adb("logcat -d -b all 2>/dev/null | grep 'exited 4 times' | sort -u | head -5")).trim().split("\n").filter(Boolean);
    result.screenshots.end = await env.screenshot("end");
    return result;
}

/**
 * What a stalled guest is doing (A10's restore stall, docs/aarch64.md):
 * each CPU's interrupts (timer, IPIs) over ten seconds, the scheduler's
 * run queues (a CPU idle with runnable tasks: a wakeup lost), and the native
 * stacks of SystemUI's and Launcher3's threads that are not idle in epoll;
 * every stack in directory/stall-<process>.txt
 * @param {function(string, number=): !Promise<string>} adb
 * @param {?string} directory the run's
 * @return {!Promise<!Object>}
 */
export async function stall_diagnostics(adb, directory)
{
    const interrupts = () => adb("grep -E 'CPU0|arch_timer|IPI[0-9]' /proc/interrupts");
    const first = await interrupts();
    await sleep(10000);
    const second = await interrupts();
    const sched = await adb("su 0 sh -c 'mount -t debugfs debugfs /sys/kernel/debug 2>/dev/null; cat /sys/kernel/debug/sched/debug /proc/sched_debug 2>/dev/null' | " +
        "grep -E '^cpu#|\\.nr_running|\\.curr->pid|\\.nr_switches|^ *[>RS] ' | head -200", 300000);
    const stacks = {};
    for(const name of ["com.android.systemui", "com.android.launcher3"])
    {
        const pid = (await adb(`pidof ${name}`)).trim();
        if(!pid) continue;
        const dump = await adb(`su 0 debuggerd -b ${pid} 2>&1`, 600000);
        if(directory) fs.writeFileSync(`${directory}stall-${name}.txt`, dump);
        // (the threads drawing: the main one, hwui's, ANGLE's and the Vulkan driver's)
        stacks[name] = dump.split(/\n(?=")/).filter((t, i) => i === 1 || /RenderThread|hwui|libGLESv2|libEGL|vulkan|ANGLE|angle::/i.test(t))
            .map(t => t.split("\n").slice(0, 24).join("\n"));
    }
    return { interrupts: [first.trim(), second.trim()], sched: sched.trim(), stacks };
}

/**
 * P12.1's native APK record (A64_ANDROID_SCENARIO=pagesize, on either page
 * size's materials): the kernel, the page size, /data's file system, then an
 * app per variant of tests/a64/apk.mjs's native APK (NativeActivity, its
 * library tests/a64/android/v86native.c) installed and started: the
 * library's LOAD segments aligned to 16 or 4 KiB, stored in the APK at an
 * offset aligned to 16 or 4 KiB and loaded from there
 * (extractNativeLibs=false), or extracted at install. For each: pm install's
 * answer, whether the library ran (its V86_NATIVE_LOADED line and the page
 * size it saw), what the system logged about page sizes and compatibility,
 * the window in focus (a compatibility dialog) and a screenshot. Records,
 * asserts only that the 16 KiB variant runs.
 * @param {!Object} env as a9_scenario's
 * @return {!Promise<!Object>} what it found
 */
export async function pagesize_scenario(env)
{
    const result = { screenshots: {} };
    const { adb, log } = env;
    result.kernel = (await adb("uname -r")).trim();
    result.page_size = +(await adb("getconf PAGE_SIZE")).trim();
    result.data = (await adb("mount | grep ' /data '")).trim().split(" ").slice(0, 5).join(" ");
    await prepare_device(adb);
    for(let deadline = Date.now() + 3600000; !/RUNNING_UNLOCKED/.test(await adb("am get-started-user-state 0 2>&1")); await sleep(15000))
    {
        assert.ok(Date.now() < deadline, "user 0 unlocked");
    }
    await adb("input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard; settings put system screen_off_timeout 2147483647");
    log(`kernel ${result.kernel}, page size ${result.page_size}, /data ${result.data}`);
    const variants = [
        { name: "elf16-zip16", align: 16384, extract: false, zip_align: 16384 },
        { name: "elf16-zip4", align: 16384, extract: false, zip_align: 4096 },
        { name: "elf4-zip4", align: 4096, extract: false, zip_align: 4096 },
        { name: "elf4-extracted", align: 4096, extract: true, zip_align: 4096 },
    ];
    for(const v of variants)
    {
        const pkg = "org.v86.native." + v.name.replace(/-/g, "_");
        const apk = build_apk({ label: "v86 " + v.name, package_name: pkg, native: { lib: build_native_lib(v.align), extract: v.extract, zip_align: v.zip_align } });
        await env.push(`/data/local/tmp/${v.name}.apk`, apk);
        const r = { install: (await adb(`pm install -r /data/local/tmp/${v.name}.apk 2>&1`, 600000)).trim() };
        if(/^Success/m.test(r.install))
        {
            await adb("logcat -c");
            r.start = (await adb(`am start -W -n ${pkg}/android.app.NativeActivity 2>&1`, 600000)).trim();
            await sleep(10000);
            r.loaded = (await adb("logcat -d -s v86native:I 2>&1 | grep -o 'V86_NATIVE_LOADED.*'")).trim();
            r.log = (await adb(`logcat -d 2>&1 | grep -iE '16 ?KB|page.?size|linker|nativeloader|${pkg}' | grep -vE 'V86_NATIVE_LOADED|AppCompat|Transition' | tail -12`)).trim().split("\n");
            r.focus = (await adb("dumpsys window 2>&1 | grep -m1 mCurrentFocus")).trim();
            r.warning = (await adb("logcat -d 2>&1 | grep -o 'AppWarnings.*'")).trim();
            r.crash = (await adb(`logcat -d -b crash 2>&1 | grep -A4 'Process: ${pkg}' | cut -c1-200`)).trim().split("\n").filter(Boolean);
            // (a dialog's text, such as the page size compatibility one)
            if(/Window\{\w+ u0 android\}/.test(r.focus))
            {
                r.dialog = (await adb("uiautomator dump /data/local/tmp/ui.xml >/dev/null 2>&1; grep -o 'text=\"[^\"]*\"' /data/local/tmp/ui.xml", 600000))
                    .trim().split("\n").map(t => t.slice(6, -1)).filter(Boolean);
            }
            result.screenshots[v.name] = await env.screenshot("native-" + v.name);
            await adb(`am force-stop ${pkg}; pm uninstall ${pkg} >/dev/null 2>&1; input keyevent KEYCODE_BACK; input keyevent KEYCODE_HOME`);
        }
        result[v.name] = r;
        log(`${v.name}: ${JSON.stringify(r).slice(0, 1500)}`);
    }
    assert.match(result["elf16-zip16"].loaded || "", new RegExp(`page_size=${result.page_size}`), "the 16 KiB aligned library runs");
    return result;
}

/**
 * The aarch32 plan's Q5.2 (A64_ANDROID_SCENARIO=compat32, on a build with
 * a 32-bit second architecture: tools/a64_android.mjs --build a14): the
 * 32-bit zygote (zygote_secondary, app_process32) running, then an APK
 * whose only library is armeabi-v7a's (tests/a32/android/v86arm32.c, the
 * NDK's armv7a target: Thumb-2 and VFP) installed, its primary ABI
 * armeabi-v7a, started: in the 32-bit process (the 32-bit zygote's child)
 * the library logs that its pointers are 32 bits and a floating-point sum,
 * the host's (V86_ARM32_LOADED), then finishes the activity. No window: a
 * window's buffers need the vendor's gralloc mapper in the process, and an
 * arm64-only vendor (Cuttlefish's, --zygote64-32) has no 32-bit one
 * (mapper.minigbm.so), nor 32-bit EGL and Vulkan drivers for hwui. Android
 * 16 shows its DeprecatedAbiDialog for a 32-bit app; it is dismissed.
 * @param {!Object} env as a9_scenario's
 * @return {!Promise<!Object>} what it found
 */
export async function compat32_scenario(env)
{
    const result = {};
    const { adb, log } = env;
    result.zygote = (await adb("getprop ro.zygote")).trim();
    result.abilist = (await adb("getprop ro.product.cpu.abilist")).trim();
    result.zygotes = (await adb("ps -A -o PID,NAME | grep -E 'zygote|app_process'")).trim().split("\n").map(l => l.trim());
    log(`ro.zygote ${result.zygote}, abilist ${result.abilist}, ${JSON.stringify(result.zygotes)}`);
    assert.match(result.abilist, /armeabi-v7a/, "a 32-bit ABI");
    assert.ok(result.zygotes.some(l => /\bzygote$/.test(l)), "the 32-bit zygote (zygote_secondary) runs");
    await prepare_device(adb);
    await adb("input keyevent KEYCODE_WAKEUP; wm dismiss-keyguard; settings put system screen_off_timeout 2147483647");
    const lib = build_native_lib(4096, "v86arm32", ["-landroid", "-llog", "-lm", "-DV86_FINISH"],
        { abi: "armeabi-v7a", source: new URL("../a32/android/v86arm32.c", import.meta.url).pathname });
    const pkg = "org.v86.arm32";
    await env.push("/data/local/tmp/v86-arm32.apk", build_apk({ label: "v86 arm32", package_name: pkg,
        native: { name: "v86arm32", lib, extract: true, abi: "armeabi-v7a", software: true } }));
    result.install = (await adb("pm install -r /data/local/tmp/v86-arm32.apk 2>&1", 600000)).trim();
    log("install: " + result.install);
    assert.match(result.install, /^Success/m, "pm install");
    result.abi = (await adb(`pm dump ${pkg} | grep -m1 primaryCpuAbi`)).trim();
    await adb("logcat -c");
    result.start = (await adb(`am start -W -n ${pkg}/android.app.NativeActivity 2>&1`, 600000)).trim();
    result.dialog = (await adb("dumpsys window 2>&1 | grep -m1 mCurrentFocus")).trim();
    if(/DeprecatedAbiDialog/.test(result.dialog)) await adb("input keyevent KEYCODE_ENTER; sleep 5");
    for(let i = 0; i < 30 && !result.loaded; i++)
    {
        await sleep(10000);
        result.loaded = (await adb("logcat -d -s v86arm32:I 2>&1 | grep -o 'V86_ARM32_LOADED.*'")).trim();
    }
    result.focus = (await adb("dumpsys window 2>&1 | grep -m1 mCurrentFocus")).trim();
    result.crash = (await adb(`logcat -d -b crash 2>&1 | grep -A4 'Process: ${pkg}' | cut -c1-200`)).trim().split("\n").filter(Boolean);
    result.screenshot = await env.screenshot("compat32");
    log(JSON.stringify(result).slice(0, 2000));
    assert.match(result.abi, /armeabi-v7a/, "the app's primary ABI");
    let expected = 0;
    for(let i = 1; i <= 1000; i++) expected += Math.sqrt(i) / i;
    assert.equal(result.loaded, `V86_ARM32_LOADED bits=32 sum=${expected.toFixed(6)}`, "the 32-bit library ran in its 32-bit process");
    return result;
}
                                                          source/v64/tests/a64/apk.mjs                                                                        0000644 0000000 0000000 00000027533 00000000000 012720  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A minimal Android app for P11's "install and start an app"
// (docs/arm64-virt-android16-plan.md P11.2): package org.v86.hello, no code
// (android:hasCode="false"), one launcher activity that is the framework's
// own android.app.Activity, which shows an empty window titled with the
// app's label. Built here without the SDK: the manifest in Android's binary
// XML, a stored zip, and the JAR signature (v1) with a key and certificate
// made by openssl (build/a64-android/apk-key/, once). targetSdkVersion 29:
// Android 16 installs from 24 on and asks for the v2 signature only from 30.
//
// With native (P12.1's native APK test, P12.3's frame rate app): the
// activity is the framework's android.app.NativeActivity, which loads
// lib/arm64-v8a/lib<native.name>.so (tests/a64/android/v86native.c or
// v86frames.c, built by build_native_lib with its LOAD segments aligned to 4
// or 16 KiB); stored in the zip at an offset aligned to native.zip_align,
// android:extractNativeLibs native.extract.
//
//   const bytes = build_apk({ label: "v86 hello" });
//   const native = build_apk({ label: "v86 native", package_name: "org.v86.native16k",
//       native: { lib: build_native_lib(16384), extract: false, zip_align: 16384 } });
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { crc32 } from "node:zlib";
import { fileURLToPath } from "node:url";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
export const APK_PACKAGE = "org.v86.hello";
const ANDROID_NS = "http://schemas.android.com/apk/res/android";
/** android:* attributes' resource IDs (frameworks/base/core/res/res/values/public*.xml) */
const ATTR_IDS = {
    label: 0x01010001, name: 0x01010003, hasCode: 0x0101000c, exported: 0x01010010, value: 0x01010024,
    minSdkVersion: 0x0101020c, versionCode: 0x0101021b, versionName: 0x0101021c, targetSdkVersion: 0x01010270,
    hardwareAccelerated: 0x010102d3, extractNativeLibs: 0x010104ea,
};
const TYPE_STRING = 0x03, TYPE_INT_DEC = 0x10, TYPE_INT_BOOLEAN = 0x12;

/**
 * Binary XML (frameworks/base/libs/androidfw/include/androidfw/ResourceTypes.h)
 * of a tree [name, { attr: value }, children]; android:* attributes by name,
 * numbers as decimal integers, booleans as booleans, strings as strings
 */
export function binary_xml(tree)
{
    // the strings: the android attributes' names first (the resource map's), then the rest
    const attr_names = new Set();
    const others = new Set(["android", ANDROID_NS]);
    const walk = ([name, attributes, children]) => {
        others.add(name);
        for(const [key, value] of Object.entries(attributes))
        {
            if(key.startsWith("android:")) attr_names.add(key.slice(8));
            else others.add(key);
            if(typeof value === "string") others.add(value);
        }
        children.forEach(walk);
    };
    walk(tree);
    const mapped = [...attr_names].sort((a, b) => ATTR_IDS[a] - ATTR_IDS[b]);
    for(const name of mapped) if(!ATTR_IDS[name]) throw new Error("no resource ID for android:" + name);
    const strings = [...mapped, ...[...others].filter(s => !attr_names.has(s))];
    const index = s => { const i = strings.indexOf(s); if(i < 0) throw new Error(s); return i; };

    const u16 = v => { const b = Buffer.alloc(2); b.writeUInt16LE(v); return b; };
    const u32 = v => { const b = Buffer.alloc(4); b.writeUInt32LE(v >>> 0); return b; };
    const chunk = (type, header_size, header_rest, body) => {
        const size = 8 + header_rest.length + body.length;
        return Buffer.concat([u16(type), u16(header_size), u32(size), header_rest, body]);
    };
    // string pool, UTF-16
    const data = strings.map(s => Buffer.concat([u16(s.length), Buffer.from(s, "utf16le"), u16(0)]));
    const offsets = [];
    let at = 0;
    for(const d of data) { offsets.push(at); at += d.length; }
    let string_data = Buffer.concat(data);
    string_data = Buffer.concat([string_data, Buffer.alloc((4 - string_data.length % 4) % 4)]);
    const pool_header = 28;
    const pool = chunk(0x0001, pool_header, Buffer.concat([u32(strings.length), u32(0), u32(0),
        u32(pool_header + strings.length * 4), u32(0)]), Buffer.concat([...offsets.map(u32), string_data]));
    const resource_map = chunk(0x0180, 8, Buffer.alloc(0), Buffer.concat(mapped.map(n => u32(ATTR_IDS[n]))));

    const node = (type, body) => chunk(type, 16, Buffer.concat([u32(1), u32(0xFFFFFFFF)]), body);
    const nodes = [node(0x0100, Buffer.concat([u32(index("android")), u32(index(ANDROID_NS))]))];
    const element = ([name, attributes, children]) => {
        const attrs = Object.entries(attributes).map(([key, value]) => {
            const android = key.startsWith("android:");
            const attr_name = android ? key.slice(8) : key;
            let raw = 0xFFFFFFFF, type, data_value;
            if(typeof value === "string") { raw = index(value); type = TYPE_STRING; data_value = index(value); }
            else if(typeof value === "boolean") { type = TYPE_INT_BOOLEAN; data_value = value ? 0xFFFFFFFF : 0; }
            else { type = TYPE_INT_DEC; data_value = value; }
            return { id: android ? ATTR_IDS[attr_name] : 0, bytes: Buffer.concat([u32(android ? index(ANDROID_NS) : 0xFFFFFFFF),
                u32(index(attr_name)), u32(raw), u16(8), Buffer.from([0, type]), u32(data_value)]) };
        }).sort((a, b) => a.id - b.id);
        nodes.push(node(0x0102, Buffer.concat([u32(0xFFFFFFFF), u32(index(name)), u16(20), u16(20), u16(attrs.length),
            u16(0), u16(0), u16(0), ...attrs.map(a => a.bytes)])));
        children.forEach(element);
        nodes.push(node(0x0103, Buffer.concat([u32(0xFFFFFFFF), u32(index(name))])));
    };
    element(tree);
    nodes.push(node(0x0101, Buffer.concat([u32(index("android")), u32(index(ANDROID_NS))])));
    return chunk(0x0003, 8, Buffer.alloc(0), Buffer.concat([pool, resource_map, ...nodes]));
}

/** a zip of stored entries [[name, bytes, align?], ...]: an entry with
 * align has its data at an offset that is a multiple of it (zipalign's way:
 * zeros in the local header's extra field) */
export function stored_zip(entries)
{
    const local = [], central = [];
    let offset = 0;
    for(const [name, data, align = 1] of entries)
    {
        const n = Buffer.from(name), crc = crc32(data);
        const extra = (align - (offset + 30 + n.length) % align) % align;
        const header = Buffer.alloc(30 + extra);
        header.writeUInt32LE(0x04034B50, 0); header.writeUInt16LE(10, 4); header.writeUInt16LE(0x0800, 6);
        header.writeUInt32LE(crc, 14); header.writeUInt32LE(data.length, 18); header.writeUInt32LE(data.length, 22);
        header.writeUInt16LE(n.length, 26);
        header.writeUInt16LE(extra, 28);
        local.push(header.subarray(0, 30), n, header.subarray(30), data);
        const c = Buffer.alloc(46);
        c.writeUInt32LE(0x02014B50, 0); c.writeUInt16LE(10, 4); c.writeUInt16LE(10, 6); c.writeUInt16LE(0x0800, 8);
        c.writeUInt32LE(crc, 16); c.writeUInt32LE(data.length, 20); c.writeUInt32LE(data.length, 24);
        c.writeUInt16LE(n.length, 28); c.writeUInt32LE(offset, 42);
        central.push(c, n);
        offset += 30 + n.length + extra + data.length;
    }
    const directory = Buffer.concat(central);
    const end = Buffer.alloc(22);
    end.writeUInt32LE(0x06054B50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10);
    end.writeUInt32LE(directory.length, 12); end.writeUInt32LE(offset, 16);
    return Buffer.concat([...local, directory, end]);
}

function openssl(args, input)
{
    const r = spawnSync("openssl", args, { input, maxBuffer: 1 << 24 });
    if(r.status !== 0) throw new Error("openssl " + args[0] + ": " + r.stderr);
    return r.stdout;
}

/** the test key and certificate (RSA 2048, self-signed), made once */
function signing_key()
{
    const dir = ROOT + "build/a64-android/apk-key/";
    if(!fs.existsSync(dir + "cert.pem"))
    {
        fs.mkdirSync(dir, { recursive: true });
        openssl(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", dir + "key.pem", "-out", dir + "cert.pem",
            "-days", "36500", "-subj", "/CN=v86 test app", "-sha256"]);
    }
    return { key: dir + "key.pem", cert: dir + "cert.pem" };
}

/** the NDK's compiler targets of the ABIs (the 32-bit one's oldest API level) */
const NDK_TARGETS = { "arm64-v8a": "aarch64-linux-android29", "armeabi-v7a": "armv7a-linux-androideabi21" };

/** tests/a64/android/<name>.c (or source) as lib<name>.so for abi, its LOAD
 * segments aligned to align (4096 or 16384), by the NDK (r26b under
 * ~/Library/Android/sdk/ndk, or $ANDROID_NDK_HOME), linked with libraries */
export function build_native_lib(align, name = "v86native", libraries = ["-landroid", "-llog"],
    { abi = "arm64-v8a", source = ROOT + `tests/a64/android/${name}.c` } = {})
{
    const ndk = process.env.ANDROID_NDK_HOME || os.homedir() + "/Library/Android/sdk/ndk/26.1.10909125";
    const out = ROOT + `build/a64-android/native/lib${name}-${align}${abi === "arm64-v8a" ? "" : "-" + abi}.so`;
    fs.mkdirSync(path.dirname(out), { recursive: true });
    const r = spawnSync(ndk + `/toolchains/llvm/prebuilt/darwin-x86_64/bin/${NDK_TARGETS[abi]}-clang`,
        ["-O2", "-Wall", "-shared", "-fPIC", `-Wl,-z,max-page-size=${align}`, source, ...libraries, "-o", out]);
    if(r.status !== 0) throw new Error(`${name}.c: ` + r.stderr);
    return fs.readFileSync(out);
}

/** the APK's bytes (native.abi: its library's ABI, arm64-v8a if not given;
 * native.software: its activity not hardware accelerated, no GL in its
 * process; min_sdk and target_sdk: the versions it asks for) */
export function build_apk({ label = "v86 hello", package_name = APK_PACKAGE, native = null, min_sdk = 29, target_sdk = 29 } = {})
{
    const activity = native ?
        ["activity", { "android:name": "android.app.NativeActivity", "android:label": label, "android:exported": true,
            ...(native.software ? { "android:hardwareAccelerated": false } : {}) }, [
            ["meta-data", { "android:name": "android.app.lib_name", "android:value": native.name || "v86native" }, []]]] :
        ["activity", { "android:name": "android.app.Activity", "android:label": label, "android:exported": true }, []];
    activity[2].push(["intent-filter", {}, [
        ["action", { "android:name": "android.intent.action.MAIN" }, []],
        ["category", { "android:name": "android.intent.category.LAUNCHER" }, []],
    ]]);
    const manifest = binary_xml(["manifest", { "package": package_name, "android:versionCode": 1, "android:versionName": "1" }, [
        ["uses-sdk", { "android:minSdkVersion": min_sdk, "android:targetSdkVersion": target_sdk }, []],
        ["application", { "android:label": label, "android:hasCode": false, ...(native ? { "android:extractNativeLibs": native.extract } : {}) }, [activity]],
    ]]);
    const files = [["AndroidManifest.xml", manifest], ...(native ? [[`lib/${native.abi || "arm64-v8a"}/lib${native.name || "v86native"}.so`, native.lib, native.zip_align]] : [])];
    // the JAR signature: MANIFEST.MF, CERT.SF, CERT.RSA (PKCS #7, detached)
    const b64 = data => create_hash("sha256").update(data).digest("base64");
    const sections = files.map(([name, data]) => `Name: ${name}\r\nSHA-256-Digest: ${b64(data)}\r\n\r\n`);
    const mf = Buffer.from(`Manifest-Version: 1.0\r\nCreated-By: v86\r\n\r\n` + sections.join(""));
    const sf = Buffer.from(`Signature-Version: 1.0\r\nCreated-By: v86\r\nSHA-256-Digest-Manifest: ${b64(mf)}\r\n\r\n` +
        files.map(([name], i) => `Name: ${name}\r\nSHA-256-Digest: ${b64(Buffer.from(sections[i]))}\r\n\r\n`).join(""));
    const { key, cert } = signing_key();
    const rsa = openssl(["smime", "-sign", "-binary", "-noattr", "-md", "sha256", "-outform", "DER", "-signer", cert, "-inkey", key], sf);
    return stored_zip([...files, ["META-INF/MANIFEST.MF", mf], ["META-INF/CERT.SF", sf], ["META-INF/CERT.RSA", rsa]]);
}
                                                                                                                                                                     source/v64/tests/a64/asid.c                                                                         0000644 0000000 0000000 00000011366 00000000000 012513  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The A64 page tier's access cache across ASIDs (tests/a64/asid.mjs;
// docs/jit-unification-plan.md P6.4, a64_asid_tag): one VA mapped non-global
// to a different page under each of 20 ASIDs (16-bit), switched with TTBR0
// writes and no TLBI; remaps of a non-running ASID's page with TLBI VAE1 and
// ASIDE1; a global page in the lower half invalidated through another ASID;
// more ASIDs than the tier keeps epochs for. A hot loop reads and writes the
// page each time; the sums and the pages' contents are printed.
#include <a64.h>
#include <stdio.h>
#include <stdint.h>

#define TEST_VA 0x1000000000UL // (L1 index 64, L2 index 0, L3 index 0)
#define GLOBAL_VA (TEST_VA + 0x1000)
#define ROOTS 20
#define PAGES 24

static uint64_t l1[ROOTS][512] __attribute__((aligned(4096)));
static uint64_t l2[ROOTS][512] __attribute__((aligned(4096)));
static uint64_t l3[ROOTS][512] __attribute__((aligned(4096)));
static uint64_t data[PAGES][512] __attribute__((aligned(4096)));

static uint64_t page(int k, int global)
{
    return (uint64_t)data[k] | 3 | 1UL << 10 | 3UL << 8 | (global ? 0 : 1UL << 11);
}
static void barrier(void) { __asm__ volatile("dsb ish\n isb" ::: "memory"); }
static void use_root(int r, unsigned asid)
{
    a64_write(ttbr0_el1, (uint64_t)l1[r] | (uint64_t)asid << 48);
    __asm__ volatile("isb" ::: "memory");
}
static void tlbi_va(uint64_t va, unsigned asid)
{
    __asm__ volatile("dsb ishst\n tlbi vae1, %0\n dsb ish\n isb" :: "r"(va >> 12 | (uint64_t)asid << 48) : "memory");
}
static void tlbi_asid(unsigned asid)
{
    __asm__ volatile("dsb ishst\n tlbi aside1, %0\n dsb ish\n isb" :: "r"((uint64_t)asid << 48) : "memory");
}
static uint64_t __attribute__((noinline)) hot(uint64_t va, int rounds)
{
    volatile uint64_t *p = (volatile uint64_t *)va;
    uint64_t sum = 0;
    for(int i = 0; i < rounds; i++)
    {
        sum += p[i & 63] * (i | 1);
        p[(i * 7) & 63] += i;
    }
    return sum;
}

int main(int argc, char **argv)
{
    for(int k = 0; k < PAGES; k++) for(int i = 0; i < 512; i++) data[k][i] = k * 1000 + i;
    for(int r = 0; r < ROOTS; r++)
    {
        l1[r][0] = 0x00000000UL | 1 | 1 << 2 | 1 << 10;
        l1[r][1] = 0x40000000UL | 1 | 3 << 8 | 1 << 10;
        l1[r][2] = 0x80000000UL | 1 | 3 << 8 | 1 << 10;
        l1[r][64] = (uint64_t)l2[r] | 3;
        l2[r][0] = (uint64_t)l3[r] | 3;
        l3[r][0] = page(r, 0);
        l3[r][1] = page(22, 1);
    }
    barrier();
    a64_write(mair_el1, 0x00FF);
    // (T0SZ 25, write-back inner shareable walks, 4 KiB, no TTBR1 walks, 40-bit PA, 16-bit ASIDs)
    a64_write(tcr_el1, 25 | 1 << 8 | 1 << 10 | 3 << 12 | 1 << 23 | 2UL << 32 | 1UL << 36);
    use_root(0, 1);
    __asm__ volatile("dsb ish\n tlbi vmalle1\n dsb ish\n isb" ::: "memory");
    a64_write(sctlr_el1, a64_read(sctlr_el1) | 1 | 1 << 2 | 1 << 12);
    __asm__ volatile("isb" ::: "memory");

    const int N = 3000;
    // ASIDs switched back and forth, no TLBI
    use_root(0, 1); printf("1: %lx\n", hot(TEST_VA, N));
    use_root(1, 2); printf("2: %lx\n", hot(TEST_VA, N));
    use_root(0, 1); printf("1 again: %lx\n", hot(TEST_VA, N));
    use_root(1, 2); printf("2 again: %lx\n", hot(TEST_VA, N));
    // ASID 1's page remapped while ASID 2 runs, which does not touch it (so
    // that ASID 1's entry is still in its slot): TLBI VAE1 for ASID 1
    use_root(0, 1); printf("1 before: %lx\n", hot(TEST_VA, N));
    use_root(1, 2);
    l3[0][0] = page(20, 0);
    tlbi_va(TEST_VA, 1);
    use_root(0, 1); printf("1 remapped: %lx\n", hot(TEST_VA, N));
    // ASID 2's page remapped while ASID 1 runs, untouched: TLBI ASIDE1 for ASID 2
    use_root(1, 2); printf("2 before: %lx\n", hot(TEST_VA, N));
    use_root(0, 1);
    l3[1][0] = page(21, 0);
    tlbi_asid(2);
    use_root(1, 2); printf("2 remapped: %lx\n", hot(TEST_VA, N));
    // a global page in the lower half, read under ASID 1; remapped in every
    // table while ASID 2 runs, untouched, and invalidated by VA for ASID 2
    // (which a global translation matches too)
    use_root(0, 1); printf("global 1: %lx\n", hot(GLOBAL_VA, N));
    use_root(1, 2);
    for(int r = 0; r < ROOTS; r++) l3[r][1] = page(23, 1);
    tlbi_va(GLOBAL_VA, 2);
    use_root(0, 1); printf("global 1 remapped: %lx\n", hot(GLOBAL_VA, N));
    use_root(1, 2); printf("global 2: %lx\n", hot(GLOBAL_VA, N));
    // more ASIDs than the page tier keeps epochs for, three times around
    for(int round = 0; round < 3; round++)
    {
        uint64_t sum = 0;
        for(int r = 0; r < ROOTS; r++)
        {
            use_root(r, 0x100 + r * 0x111);
            sum = sum * 31 + hot(TEST_VA, N / 10);
        }
        printf("round %d: %lx\n", round, sum);
    }
    uint64_t check = 0;
    for(int k = 0; k < PAGES; k++) for(int i = 0; i < 512; i++) check = check * 131 + data[k][i];
    printf("pages: %lx\n", check);
    return 0;
}
                                                                                                                                                                                                                                                                          source/v64/tests/a64/asid.mjs                                                                       0000644 0000000 0000000 00000002275 00000000000 013061  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 page tier's access cache across ASID switches and TLBIs
// (docs/jit-unification-plan.md P6.4; tests/a64/asid.c): the same output on
// QEMU, the interpreter, and the page tier with a64_asid_tag 0, 1 and 2 (auto)
import assert from "node:assert/strict";
import { build, reference, actual } from "./guest_runner.mjs";

const directory = build("asid", [new URL("asid.c", import.meta.url).pathname]);
const text = result => {
    assert.equal(result.status, "ok", result.text);
    return result.text.trim();
};
const expected = text(await reference(directory));
delete process.env.A64_MMU;
delete process.env.A64_JIT;
assert.equal(text(await actual(directory)), expected, "the interpreter against QEMU");
process.env.A64_JIT = "1";
for(const tag of [0, 1, 2])
{
    process.env.A64_JIT_SWITCHES = `a64_asid_tag=${tag}`;
    const result = await actual(directory);
    assert.equal(text(result), expected, `the page tier with a64_asid_tag=${tag} against QEMU`);
    const t = result.page_tier;
    console.log(`a64_asid_tag=${tag}: ${t.retired} native instructions, ${t.access_fills} access cache fills`);
}
console.log(expected.split("\n").slice(-1)[0]);
console.log("asid: passed");
                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/baremetal/exception.c                                                          0000644 0000000 0000000 00000003045 00000000000 015520  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The exception entry's C half (start.S vector_common), built with
// -mgeneral-regs-only: an expected fault returns to the interrupted code,
// whose FP and SIMD registers the vectors do not save.

#include <a64.h>

static volatile struct a64_fault expected;
static volatile int armed;
uint64_t (*volatile a64_fault_probe)(void);
void (*volatile a64_lower_handler)(struct a64_frame *frame, uint64_t vector);

void a64_unexpected(struct a64_frame *frame, uint64_t vector);

void a64_expect(void)
{
    expected.taken = 0;
    __asm__ volatile("" ::: "memory");
    armed = 1;
}

int a64_caught(struct a64_fault *fault)
{
    armed = 0;
    __asm__ volatile("" ::: "memory");
    fault->taken = expected.taken;
    fault->esr = expected.esr;
    fault->far = expected.far;
    fault->elr = expected.elr;
    fault->spsr = expected.spsr;
    fault->probe = expected.probe;
    return fault->taken;
}

// (vector 4 is a synchronous exception from EL1 with SP_EL1; 8-15 come from
// EL0, AArch64's then AArch32's)
void a64_exception(struct a64_frame *frame, uint64_t vector)
{
    if(vector >= 8 && a64_lower_handler)
    {
        a64_lower_handler(frame, vector);
        return;
    }
    if(vector == 4 && armed && !expected.taken)
    {
        expected.taken = 1;
        expected.esr = a64_read(esr_el1);
        expected.far = a64_read(far_el1);
        expected.elr = frame->elr;
        expected.spsr = frame->spsr;
        expected.probe = a64_fault_probe ? a64_fault_probe() : 0;
        frame->elr += 4;
        return;
    }
    a64_unexpected(frame, vector);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/a64/baremetal/include/a64.h                                                        0000644 0000000 0000000 00000004676 00000000000 015557  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bare-metal AArch64 guests' runtime (tests/a64/guest_runner.mjs).
//
// Memory (RAM at 0x4000_0000, at least 128 MiB): the image at 0x4008_0000,
// the heap from its end to 0x4070_0000, 64 KiB of stack per core below
// 0x4080_0000, then the result block (struct a64_result) at 0x4080_0000 and
// the output text at 0x4080_1000. The guest is done when the result block's
// magic is A64_DONE; the runner then reads the block and the text.
#ifndef A64_H
#define A64_H

#include <stdint.h>
#include <stddef.h>

#define A64_RESULT 0x40800000UL
#define A64_TEXT (A64_RESULT + 0x1000)
#define A64_TEXT_SIZE (0x100000 - 0x1000)
#define A64_HEAP_END 0x40700000UL
#define A64_DONE 0xA64D0E00u

enum a64_status { A64_OK = 0, A64_FAILED = 1, A64_UNEXPECTED_EXCEPTION = 2, A64_TEXT_OVERFLOW = 3 };

struct a64_result
{
    uint32_t magic, status, length, cores;
    // the unexpected exception, if any
    uint64_t vector, esr, elr, far, spsr;
    uint64_t dtb;
};

struct a64_frame
{
    uint64_t x[31], elr, spsr, pad;
};

#define a64_result ((volatile struct a64_result *)A64_RESULT)

// An exception the test expects: a64_expect() arms it, the next synchronous
// exception at EL1 is recorded instead of failing the run and returns past
// the faulting instruction (ELR + 4), a64_caught() disarms and reports it.
struct a64_fault
{
    int taken;
    uint64_t esr, far, elr;
    // SPSR_EL1 at the exception, and what a64_fault_probe (if set) returned in the handler
    uint64_t spsr, probe;
};
void a64_expect(void);
int a64_caught(struct a64_fault *fault);
extern uint64_t (*volatile a64_fault_probe)(void);

// Exceptions from EL0 (vectors 8-11 from AArch64, 12-15 from AArch32) go
// to this handler when it is set; it may change the frame to return elsewhere
extern void (*volatile a64_lower_handler)(struct a64_frame *frame, uint64_t vector);

void a64_putc(char c);
void a64_fail(const char *why);

// PSCI over HVC (SMCCC): function id and up to 3 arguments, x0 returned
int64_t a64_hvc(uint64_t function, uint64_t a1, uint64_t a2, uint64_t a3);
int64_t a64_hvc_imm1(uint64_t function); // HVC #1
// starts core `core` (MPIDR Aff0) at a64_secondary, calling a64_core_main(core)
int64_t a64_cpu_on(unsigned core);
extern void (*volatile a64_core_main)(unsigned core);

#define a64_read(reg) ({ uint64_t _v; __asm__ volatile("mrs %0, " #reg : "=r"(_v)); _v; })
#define a64_write(reg, v) __asm__ volatile("msr " #reg ", %0" :: "r"((uint64_t)(v)))

int main(int argc, char **argv);

#endif
                                                                  source/v64/tests/a64/baremetal/include/fenv.h                                                       0000644 0000000 0000000 00000002115 00000000000 016105  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_FENV_H
#define A64_FENV_H
// FPSR's cumulative flags and FPCR.RMode, with glibc's aarch64 values
#define FE_INVALID 1
#define FE_DIVBYZERO 2
#define FE_OVERFLOW 4
#define FE_UNDERFLOW 8
#define FE_INEXACT 16
#define FE_ALL_EXCEPT 31
#define FE_TONEAREST 0
#define FE_UPWARD 0x400000
#define FE_DOWNWARD 0x800000
#define FE_TOWARDZERO 0xc00000

static inline unsigned long a64_fpsr(void) { unsigned long v; __asm__ volatile("mrs %0, fpsr" : "=r"(v)); return v; }
static inline unsigned long a64_fpcr(void) { unsigned long v; __asm__ volatile("mrs %0, fpcr" : "=r"(v)); return v; }

static inline int feclearexcept(int excepts)
{
    __asm__ volatile("msr fpsr, %0" :: "r"(a64_fpsr() & ~(unsigned long)(excepts & FE_ALL_EXCEPT)));
    return 0;
}
static inline int fetestexcept(int excepts) { return a64_fpsr() & excepts & FE_ALL_EXCEPT; }
static inline int fegetround(void) { return a64_fpcr() & 0xc00000; }
static inline int fesetround(int round)
{
    if(round & ~0xc00000) return 1;
    __asm__ volatile("msr fpcr, %0" :: "r"((a64_fpcr() & ~0xc00000ul) | round));
    return 0;
}
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/baremetal/include/inttypes.h                                                   0000644 0000000 0000000 00000000451 00000000000 017027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_INTTYPES_H
#define A64_INTTYPES_H
#include <stdint.h>
// LP64, as glibc on aarch64
#define PRId32 "d"
#define PRIi32 "i"
#define PRIu32 "u"
#define PRIx32 "x"
#define PRIX32 "X"
#define PRId64 "ld"
#define PRIi64 "li"
#define PRIu64 "lu"
#define PRIx64 "lx"
#define PRIX64 "lX"
#endif
                                                                                                                                                                                                                       source/v64/tests/a64/baremetal/include/math.h                                                       0000644 0000000 0000000 00000000571 00000000000 016104  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_MATH_H
#define A64_MATH_H
#define NAN (__builtin_nanf(""))
#define INFINITY (__builtin_inff())
#define M_E 2.7182818284590452354
#define M_PI 3.14159265358979323846
#define signbit(x) __builtin_signbit(x)
#define isnan(x) __builtin_isnan(x)
#define isinf(x) __builtin_isinf(x)
float fmaf(float a, float b, float c);
double fma(double a, double b, double c);
#endif
                                                                                                                                       source/v64/tests/a64/baremetal/include/stdio.h                                                      0000644 0000000 0000000 00000001231 00000000000 016267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_STDIO_H
#define A64_STDIO_H
#include <stdarg.h>
#include <stddef.h>
int printf(const char *format, ...) __attribute__((format(printf, 1, 2)));
int sprintf(char *out, const char *format, ...) __attribute__((format(printf, 2, 3)));
int snprintf(char *out, size_t size, const char *format, ...) __attribute__((format(printf, 3, 4)));
int asprintf(char **out, const char *format, ...) __attribute__((format(printf, 2, 3)));
int vprintf(const char *format, va_list args);
int vsnprintf(char *out, size_t size, const char *format, va_list args);
int vasprintf(char **out, const char *format, va_list args);
int puts(const char *s);
int putchar(int c);
#endif
                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/a64/baremetal/include/stdlib.h                                                     0000644 0000000 0000000 00000000400 00000000000 016423  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_STDLIB_H
#define A64_STDLIB_H
#include <stddef.h>
void *malloc(size_t size);
void *calloc(size_t count, size_t size);
void free(void *pointer);
void abort(void) __attribute__((noreturn));
void exit(int status) __attribute__((noreturn));
#endif
                                                                                                                                                                                                                                                                source/v64/tests/a64/baremetal/include/string.h                                                     0000644 0000000 0000000 00000000436 00000000000 016461  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef A64_STRING_H
#define A64_STRING_H
#include <stddef.h>
void *memcpy(void *to, const void *from, size_t n);
void *memset(void *to, int c, size_t n);
int memcmp(const void *a, const void *b, size_t n);
size_t strlen(const char *s);
int strcmp(const char *a, const char *b);
#endif
                                                                                                                                                                                                                                  source/v64/tests/a64/baremetal/libc.c                                                               0000644 0000000 0000000 00000023435 00000000000 014440  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bare-metal guests' small libc (tests/a64/guest_runner.mjs, and the
// AArch32 guests of tests/a32/runner.mjs): a bump allocator from the image's
// end to A64_HEAP_END, the string functions, printf with glibc's formatting
// (the QEMU .ref files come from glibc) into the result block's text
// (a64_putc, the runtime's).

#include <a64.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern char _end[];
static char *heap;

// -------- memory

void *malloc(size_t size)
{
    if(!heap) heap = (char *)(((uintptr_t)_end + 15) & ~(uintptr_t)15);
    char *p = heap;
    if((uintptr_t)p + size > A64_HEAP_END) a64_fail("out of heap");
    heap = (char *)(((uintptr_t)p + size + 15) & ~(uintptr_t)15);
    return p;
}

void *calloc(size_t count, size_t size)
{
    void *p = malloc(count * size);
    memset(p, 0, count * size);
    return p;
}

void free(void *pointer) { (void)pointer; }

void *memcpy(void *to, const void *from, size_t n)
{
    char *t = to;
    const char *f = from;
    while(n--) *t++ = *f++;
    return to;
}

void *memset(void *to, int c, size_t n)
{
    char *t = to;
    while(n--) *t++ = c;
    return to;
}

int memcmp(const void *a, const void *b, size_t n)
{
    const unsigned char *x = a, *y = b;
    for(; n; n--, x++, y++) if(*x != *y) return *x - *y;
    return 0;
}

size_t strlen(const char *s)
{
    size_t n = 0;
    while(s[n]) n++;
    return n;
}

int strcmp(const char *a, const char *b)
{
    while(*a && *a == *b) a++, b++;
    return (unsigned char)*a - (unsigned char)*b;
}

// -------- printf

struct sink
{
    char *out;
    size_t size, length;
    int to_text;
};

static void put(struct sink *s, char c)
{
    if(s->to_text) a64_putc(c);
    else if(s->length + 1 < s->size) s->out[s->length] = c;
    s->length++;
}

static void repeat(struct sink *s, char c, int n) { while(n-- > 0) put(s, c); }

enum { LEFT = 1, PLUS = 2, SPACE = 4, ALT = 8, ZERO = 16 };

// (prefix, then zero padding to `zeros`, then the digits, padded to `width`)
static void field(struct sink *s, int flags, int width, const char *prefix, int zeros, const char *digits, int n)
{
    int p = strlen(prefix), total = p + (zeros > n ? zeros : n);
    if(!(flags & LEFT)) repeat(s, ' ', width - total);
    for(int i = 0; i < p; i++) put(s, prefix[i]);
    repeat(s, '0', zeros - n);
    for(int i = 0; i < n; i++) put(s, digits[i]);
    if(flags & LEFT) repeat(s, ' ', width - total);
}

static void integer(struct sink *s, int flags, int width, int precision, char conversion, uint64_t value, int negative)
{
    char digits[24], prefix[4] = "";
    int n = 0, base = conversion == 'o' ? 8 : conversion == 'x' || conversion == 'X' ? 16 : 10;
    const char *alphabet = conversion == 'X' ? "0123456789ABCDEF" : "0123456789abcdef";
    char reversed[24];
    while(value) { reversed[n++] = alphabet[value % base]; value /= base; }
    for(int i = 0; i < n; i++) digits[i] = reversed[n - 1 - i];
    if(negative) prefix[0] = '-';
    else if(flags & PLUS && base == 10) prefix[0] = '+';
    else if(flags & SPACE && base == 10) prefix[0] = ' ';
    if(flags & ALT && n && base == 16) { prefix[0] = '0'; prefix[1] = conversion; prefix[2] = 0; }
    if(flags & ALT && base == 8 && (precision <= n)) precision = n + 1;
    int zeros = precision >= 0 ? precision : n ? n : 1;
    if(precision < 0 && flags & ZERO && !(flags & LEFT)) { int z = width - (int)strlen(prefix); if(z > zeros) zeros = z; }
    if(precision == 0 && n == 0) zeros = 0;
    field(s, flags, width, prefix, zeros, digits, n);
}

#ifndef A64_GENERAL_REGS_ONLY
// %a and %A of a double, as glibc: subnormals as 0x0.<digits>p-1022, "nan"
// and "inf" with the sign bit's '-'
static void hexfloat(struct sink *s, int flags, int width, int precision, char conversion, double value)
{
    uint64_t bits;
    memcpy(&bits, &value, 8);
    int upper = conversion == 'A', negative = bits >> 63, exponent = bits >> 52 & 0x7FF;
    uint64_t mantissa = bits & 0xFFFFFFFFFFFFFull;
    char prefix[4] = "", buffer[64];
    if(negative) prefix[0] = '-';
    else if(flags & PLUS) prefix[0] = '+';
    else if(flags & SPACE) prefix[0] = ' ';
    if(exponent == 0x7FF)
    {
        const char *text = mantissa ? (upper ? "NAN" : "nan") : (upper ? "INF" : "inf");
        field(s, flags & ~ZERO, width, prefix, 0, text, 3);
        return;
    }
    int lead = exponent != 0, e = mantissa == 0 && exponent == 0 ? 0 : exponent ? exponent - 1023 : -1022;
    // round to `precision` hex digits (to nearest, ties to even)
    if(precision >= 0 && precision < 13)
    {
        int drop = 4 * (13 - precision);
        uint64_t half = 1ull << (drop - 1), rest = mantissa & ((1ull << drop) - 1);
        mantissa >>= drop;
        if(rest > half || (rest == half && (mantissa & 1))) mantissa++;
        if(mantissa >> (4 * precision)) { mantissa &= (1ull << (4 * precision)) - 1; if(lead) e++; else lead = 1; }
        mantissa <<= drop;
    }
    const char *alphabet = upper ? "0123456789ABCDEF" : "0123456789abcdef";
    int n = 0;
    buffer[n++] = '0' + lead;
    int digits = 13;
    if(precision < 0) while(digits && !(mantissa >> (4 * (13 - digits)) & 0xF)) digits--;
    int shown = precision < 0 ? digits : precision;
    if(shown || flags & ALT) buffer[n++] = '.';
    for(int i = 0; i < shown; i++) buffer[n++] = i < 13 ? alphabet[mantissa >> (4 * (12 - i)) & 0xF] : '0';
    buffer[n++] = upper ? 'P' : 'p';
    buffer[n++] = e < 0 ? '-' : '+';
    unsigned magnitude = e < 0 ? -e : e;
    char exp[8];
    int m = 0;
    do { exp[m++] = '0' + magnitude % 10; magnitude /= 10; } while(magnitude);
    while(m) buffer[n++] = exp[--m];
    int p = strlen(prefix);
    prefix[p++] = '0';
    prefix[p++] = upper ? 'X' : 'x';
    prefix[p] = 0;
    int zeros = flags & ZERO && !(flags & LEFT) ? width - p : 0;
    field(s, flags, width, prefix, zeros, buffer, n);
}

#endif

static void format(struct sink *s, const char *f, va_list args)
{
    for(; *f; f++)
    {
        if(*f != '%') { put(s, *f); continue; }
        int flags = 0, width = 0, precision = -1, length = 0;
        for(;; f++)
        {
            if(f[1] == '-') flags |= LEFT;
            else if(f[1] == '+') flags |= PLUS;
            else if(f[1] == ' ') flags |= SPACE;
            else if(f[1] == '#') flags |= ALT;
            else if(f[1] == '0') flags |= ZERO;
            else break;
        }
        f++;
        if(*f == '*') { width = va_arg(args, int); if(width < 0) { flags |= LEFT; width = -width; } f++; }
        else while(*f >= '0' && *f <= '9') width = width * 10 + *f++ - '0';
        if(*f == '.')
        {
            f++;
            precision = 0;
            if(*f == '*') { precision = va_arg(args, int); f++; }
            else while(*f >= '0' && *f <= '9') precision = precision * 10 + *f++ - '0';
        }
        while(*f == 'h' || *f == 'l' || *f == 'z' || *f == 'j' || *f == 't' || *f == 'L')
        {
            length += *f == 'h' ? -1 : 1;
            f++;
        }
        switch(*f)
        {
            case 'd':
            case 'i':
            {
                int64_t v = length > 0 ? va_arg(args, int64_t) : va_arg(args, int);
                if(length == -1) v = (short)v;
                if(length == -2) v = (signed char)v;
                integer(s, flags, width, precision, 'd', v < 0 ? -(uint64_t)v : (uint64_t)v, v < 0);
                break;
            }
            case 'u':
            case 'x':
            case 'X':
            case 'o':
            {
                uint64_t v = length > 0 ? va_arg(args, uint64_t) : va_arg(args, unsigned);
                if(length == -1) v = (unsigned short)v;
                if(length == -2) v = (unsigned char)v;
                integer(s, flags, width, precision, *f, v, 0);
                break;
            }
            case 'p':
                integer(s, flags | ALT, width, precision, 'x', (uintptr_t)va_arg(args, void *), 0);
                break;
            case 'c':
            {
                char c = va_arg(args, int);
                field(s, flags & ~ZERO, width, "", 0, &c, 1);
                break;
            }
            case 's':
            {
                const char *text = va_arg(args, const char *);
                if(!text) text = "(null)";
                int n = strlen(text);
                if(precision >= 0 && precision < n) n = precision;
                field(s, flags & ~ZERO, width, "", 0, text, n);
                break;
            }
#ifndef A64_GENERAL_REGS_ONLY
            case 'a':
            case 'A':
                hexfloat(s, flags, width, precision, *f, va_arg(args, double));
                break;
#endif
            case '%':
                put(s, '%');
                break;
            default:
                a64_fail("printf: unsupported conversion");
        }
    }
}

int vsnprintf(char *out, size_t size, const char *f, va_list args)
{
    struct sink s = { out, size, 0, 0 };
    format(&s, f, args);
    if(size) out[s.length < size ? s.length : size - 1] = 0;
    return s.length;
}

int vprintf(const char *f, va_list args)
{
    struct sink s = { 0, 0, 0, 1 };
    format(&s, f, args);
    return s.length;
}

int vasprintf(char **out, const char *f, va_list args)
{
    va_list copy;
    va_copy(copy, args);
    int n = vsnprintf(0, 0, f, copy);
    va_end(copy);
    *out = malloc(n + 1);
    return vsnprintf(*out, n + 1, f, args);
}

#define VARIADIC(call) ({ va_list args; va_start(args, f); int n = call; va_end(args); n; })
int printf(const char *f, ...) { return VARIADIC(vprintf(f, args)); }
int sprintf(char *out, const char *f, ...) { return VARIADIC(vsnprintf(out, (size_t)-1 >> 1, f, args)); }
int snprintf(char *out, size_t size, const char *f, ...) { return VARIADIC(vsnprintf(out, size, f, args)); }
int asprintf(char **out, const char *f, ...) { return VARIADIC(vasprintf(out, f, args)); }
int putchar(int c) { a64_putc(c); return c; }
int puts(const char *s) { while(*s) a64_putc(*s++); a64_putc('\n'); return 0; }

                                                                                                                                                                                                                                   source/v64/tests/a64/baremetal/link.ld                                                              0000644 0000000 0000000 00000001065 00000000000 014634  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The bare-metal guests' layout (tests/a64/baremetal/a64.h): the image at
   RAM + 0x80000, the heap after it, the stacks below the result block. */
ENTRY(_start)
SECTIONS
{
    . = 0x40080000;
    .text : { KEEP(*(.text.head)) *(.text .text.*) }
    .rodata : { *(.rodata .rodata.*) }
    .data : { *(.data .data.*) }
    . = ALIGN(16);
    __bss_start = .;
    .bss : { *(.bss .bss.*) *(COMMON) }
    . = ALIGN(16);
    _end = .;
    __image_size = _end - 0x40080000;
    __stack_top = 0x40800000;
    ASSERT(_end <= 0x40400000, "the image overlaps the heap")
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/a64/baremetal/runtime.c                                                            0000644 0000000 0000000 00000007744 00000000000 015217  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The bare-metal guests' C runtime: output into the result block's text,
// the startup and finish of a run (include/a64.h); printf with glibc's
// formatting and a bump allocator are libc.c's.

#include <a64.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static volatile unsigned text_length;
void (*volatile a64_core_main)(unsigned core);

static void finish(uint32_t status)
{
    a64_result->length = text_length;
    a64_result->status = status;
    __asm__ volatile("dsb sy" ::: "memory");
    a64_result->magic = A64_DONE;
    __asm__ volatile("dsb sy" ::: "memory");
    for(;;) __asm__ volatile("wfi");
}

void a64_putc(char c)
{
    if(text_length >= A64_TEXT_SIZE) finish(A64_TEXT_OVERFLOW);
    ((volatile char *)A64_TEXT)[text_length++] = c;
}

void a64_fail(const char *why)
{
    printf("A64_FAIL %s\n", why);
    finish(A64_FAILED);
}

#ifdef A64_MMU
// (A64_MMU=1, tests/a64/guest_runner.mjs: the MMU on from the start, an
// identity map of 1 GiB blocks, devices below RAM and normal write-back
// RAM, so that the A64 page tier, which needs it, runs the guest's code)
static uint64_t identity[512] __attribute__((aligned(4096)));
static void mmu_on(void)
{
    if(!identity[1])
    {
        identity[0] = 0x00000000UL | 1 | 1 << 2 | 1 << 10;
        identity[1] = 0x40000000UL | 1 | 0 << 2 | 3 << 8 | 1 << 10;
        identity[2] = 0x80000000UL | 1 | 0 << 2 | 3 << 8 | 1 << 10;
        __asm__ volatile("dsb ish" ::: "memory");
    }
    a64_write(mair_el1, 0x00FF);
    a64_write(tcr_el1, 25 | 1 << 8 | 1 << 10 | 3 << 12 | 1 << 23 | 2UL << 32);
    a64_write(ttbr0_el1, (uint64_t)identity);
    __asm__ volatile("dsb ish\n tlbi vmalle1\n dsb ish\n isb" ::: "memory");
    a64_write(sctlr_el1, a64_read(sctlr_el1) | 1 | 1 << 2 | 1 << 12);
    __asm__ volatile("isb" ::: "memory");
}
#endif

void a64_start(uint64_t dtb)
{
#ifdef A64_MMU
    mmu_on();
#endif
    a64_result->magic = 0;
    a64_result->status = 0;
    a64_result->length = 0;
    a64_result->cores = 1;
    a64_result->dtb = dtb;
    char *argv[] = { "a64", 0 };
    int status = main(1, argv);
    finish(status ? A64_FAILED : A64_OK);
}

void a64_secondary_start(unsigned core)
{
#ifdef A64_MMU
    mmu_on();
#endif
    __atomic_fetch_add((uint32_t *)&a64_result->cores, 1, __ATOMIC_SEQ_CST);
    if(a64_core_main) a64_core_main(core);
}

void exit(int status) { finish(status ? A64_FAILED : A64_OK); }
void abort(void) { a64_fail("abort"); for(;;); }

// (unexpected exceptions, called from a64_exception in exception.c)
void a64_unexpected(struct a64_frame *frame, uint64_t vector)
{
    a64_result->vector = vector;
    a64_result->esr = a64_read(esr_el1);
    a64_result->far = a64_read(far_el1);
    a64_result->elr = frame->elr;
    a64_result->spsr = frame->spsr;
    printf("A64_EXCEPTION vector=%lu esr=%#lx elr=%#lx far=%#lx\n", (unsigned long)vector,
        (unsigned long)a64_result->esr, (unsigned long)frame->elr, (unsigned long)a64_result->far);
    finish(A64_UNEXPECTED_EXCEPTION);
}

int64_t a64_hvc(uint64_t function, uint64_t a1, uint64_t a2, uint64_t a3)
{
    register uint64_t x0 __asm__("x0") = function, x1 __asm__("x1") = a1, x2 __asm__("x2") = a2, x3 __asm__("x3") = a3;
    __asm__ volatile("hvc #0" : "+r"(x0), "+r"(x1), "+r"(x2), "+r"(x3) :: "memory");
    return x0;
}

int64_t a64_hvc_imm1(uint64_t function)
{
    register uint64_t x0 __asm__("x0") = function;
    __asm__ volatile("hvc #1" : "+r"(x0) :: "x1", "x2", "x3", "memory");
    return x0;
}

extern char a64_secondary[];
int64_t a64_cpu_on(unsigned core)
{
    return a64_hvc(0xC4000003, core, (uint64_t)a64_secondary, core); // PSCI CPU_ON (SMC64)
}

#ifndef A64_GENERAL_REGS_ONLY
// -------- math (the instructions themselves)

float fmaf(float a, float b, float c)
{
    float r;
    __asm__ volatile("fmadd %s0, %s1, %s2, %s3" : "=w"(r) : "w"(a), "w"(b), "w"(c));
    return r;
}

double fma(double a, double b, double c)
{
    double r;
    __asm__ volatile("fmadd %d0, %d1, %d2, %d3" : "=w"(r) : "w"(a), "w"(b), "w"(c));
    return r;
}
#endif
                            source/v64/tests/a64/baremetal/start.S                                                              0000644 0000000 0000000 00000006170 00000000000 014641  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Entry of the bare-metal AArch64 guests (tests/a64/guest_runner.mjs): an
// arm64 Image header (Linux Documentation/arch/arm64/booting.rst), so QEMU's
// -kernel and the v86 virt loader both load it at RAM + 0x80000 and enter at
// EL1 with the MMU off and x0 = the DTB's address. Secondary cores, started
// with PSCI CPU_ON, enter at a64_secondary with their core number in x0.

    .section .text.head, "ax"
    .global _start
_start:
    b       entry
    .word   0
    .quad   0x80000                 // text_offset
    .quad   __image_size            // image_size (with the BSS)
    .quad   0                       // flags: little-endian
    .quad   0, 0, 0
    .word   0x644d5241              // "ARM\x64"
    .word   0

entry:
    mov     x19, x0
    bl      cpu_setup
    ldr     x1, =__stack_top
    mov     sp, x1
    ldr     x1, =__bss_start
    ldr     x2, =_end
1:  cmp     x1, x2
    b.hs    2f
    str     xzr, [x1], #8
    b       1b
2:  mov     x0, x19
    bl      a64_start
3:  wfi
    b       3b

    .global a64_secondary
a64_secondary:
    mov     x19, x0
    bl      cpu_setup
    ldr     x1, =__stack_top
    lsl     x2, x19, #16            // 64 KiB of stack per core
    sub     x1, x1, x2
    mov     sp, x1
    mov     x0, x19
    bl      a64_secondary_start
4:  wfi
    b       4b

// FP and SIMD on (CPACR_EL1.FPEN), the vectors installed
cpu_setup:
    mov     x1, #(3 << 20)
    msr     cpacr_el1, x1
    adr     x1, a64_vectors
    msr     vbar_el1, x1
    isb
    ret

// Each vector saves x0-x30, ELR_EL1 and SPSR_EL1 (struct a64_frame) and calls
// a64_exception(frame, vector), which returns to the (possibly changed) ELR.
    .macro vector n
    .balign 128
    sub     sp, sp, #272
    stp     x0, x1, [sp]
    mov     x1, #\n
    b       vector_common
    .endm

    .text
    .balign 2048
    .global a64_vectors
a64_vectors:
    .irp n, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
    vector \n
    .endr

vector_common:
    stp     x2, x3, [sp, #16]
    stp     x4, x5, [sp, #32]
    stp     x6, x7, [sp, #48]
    stp     x8, x9, [sp, #64]
    stp     x10, x11, [sp, #80]
    stp     x12, x13, [sp, #96]
    stp     x14, x15, [sp, #112]
    stp     x16, x17, [sp, #128]
    stp     x18, x19, [sp, #144]
    stp     x20, x21, [sp, #160]
    stp     x22, x23, [sp, #176]
    stp     x24, x25, [sp, #192]
    stp     x26, x27, [sp, #208]
    stp     x28, x29, [sp, #224]
    mrs     x2, elr_el1
    stp     x30, x2, [sp, #240]
    mrs     x2, spsr_el1
    str     x2, [sp, #256]
    mov     x0, sp
    bl      a64_exception
    ldr     x2, [sp, #256]
    msr     spsr_el1, x2
    ldp     x30, x2, [sp, #240]
    msr     elr_el1, x2
    ldp     x28, x29, [sp, #224]
    ldp     x26, x27, [sp, #208]
    ldp     x24, x25, [sp, #192]
    ldp     x22, x23, [sp, #176]
    ldp     x20, x21, [sp, #160]
    ldp     x18, x19, [sp, #144]
    ldp     x16, x17, [sp, #128]
    ldp     x14, x15, [sp, #112]
    ldp     x12, x13, [sp, #96]
    ldp     x10, x11, [sp, #80]
    ldp     x8, x9, [sp, #64]
    ldp     x6, x7, [sp, #48]
    ldp     x4, x5, [sp, #32]
    ldp     x2, x3, [sp, #16]
    ldp     x0, x1, [sp]
    add     sp, sp, #272
    eret
                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/binder_pingpong.c                                                              0000644 0000000 0000000 00000015563 00000000000 014742  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Binder across cores (docs/arm64-virt-android16-plan.md P9.1): a context
 * manager and a client, each bound to its own CPU, exchange ROUNDS
 * transactions through a binderfs device with BINDER_WRITE_READ: the client
 * sends a counter (BC_TRANSACTION to handle 0), the manager answers it plus
 * one (BC_REPLY), both free the buffers the driver gave them. Built by
 * tools/a64_kernel.mjs with Alpine's GCC and musl against the kernel's UAPI
 * headers; run on the androidish kernel (tests/a64/linux_boot.mjs).
 *
 *   binder_pingpong <binderfs mount or device> [rounds] [cpu_a] [cpu_b]
 *
 * Given binderfs's mount, it adds a device "pingpong" through binder-control
 * (BINDER_CTL_ADD) and uses that.
 *
 * A64_BINDER_OK rounds=N cpus=a,b on success, A64_BINDER_FAIL <why> else. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/android/binder.h>
#include <linux/android/binderfs.h>

#define MAP_BYTES (128 * 1024)

static void fail(const char *what)
{
    printf("A64_BINDER_FAIL %s (errno %d)\n", what, errno);
    fflush(stdout);
    exit(1);
}

static void pin(int cpu)
{
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    if(sched_setaffinity(0, sizeof(set), &set) < 0) fail("sched_setaffinity");
}

struct conn
{
    int fd;
    uint8_t read_buffer[512];
};

static void open_binder(struct conn *c, const char *path)
{
    c->fd = open(path, O_RDWR | O_CLOEXEC);
    if(c->fd < 0) fail("open");
    struct binder_version version;
    if(ioctl(c->fd, BINDER_VERSION, &version) < 0) fail("BINDER_VERSION");
    if(version.protocol_version != BINDER_CURRENT_PROTOCOL_VERSION) fail("protocol version");
    if(mmap(NULL, MAP_BYTES, PROT_READ, MAP_PRIVATE, c->fd, 0) == MAP_FAILED) fail("mmap");
}

/* Write `write` (len bytes), then read until a command of `want` arrives: its transaction data */
static struct binder_transaction_data read_until(struct conn *c, const void *write, size_t len, uint32_t want)
{
    struct binder_write_read bwr = {
        .write_size = len, .write_consumed = 0, .write_buffer = (binder_uintptr_t)write,
    };
    for(;;)
    {
        bwr.read_size = sizeof(c->read_buffer);
        bwr.read_consumed = 0;
        bwr.read_buffer = (binder_uintptr_t)c->read_buffer;
        if(ioctl(c->fd, BINDER_WRITE_READ, &bwr) < 0)
        {
            if(errno == EINTR) continue;
            fail("BINDER_WRITE_READ");
        }
        bwr.write_size = 0;
        for(size_t at = 0; at < bwr.read_consumed;)
        {
            uint32_t command;
            memcpy(&command, c->read_buffer + at, 4);
            at += 4;
            size_t size = _IOC_SIZE(command);
            if(command == want)
            {
                struct binder_transaction_data txn;
                memcpy(&txn, c->read_buffer + at, sizeof(txn));
                return txn;
            }
            if(command == BR_DEAD_REPLY || command == BR_FAILED_REPLY) fail("dead or failed reply");
            at += size;
        }
    }
}

struct reply_and_free
{
    uint32_t free_command;
    binder_uintptr_t buffer;
    uint32_t reply_command;
    struct binder_transaction_data txn;
} __attribute__((packed));

static void manager(const char *path, int rounds, int cpu)
{
    pin(cpu);
    struct conn c;
    open_binder(&c, path);
    if(ioctl(c.fd, BINDER_SET_CONTEXT_MGR, 0) < 0) fail("BINDER_SET_CONTEXT_MGR");
    uint32_t enter = BC_ENTER_LOOPER;
    struct binder_transaction_data txn = read_until(&c, &enter, sizeof(enter), BR_TRANSACTION);
    for(int round = 0;; round++)
    {
        uint32_t value;
        if(txn.data_size != 4) fail("transaction size");
        memcpy(&value, (const void *)(uintptr_t)txn.data.ptr.buffer, 4);
        if(value != (uint32_t)round * 2) fail("transaction value");
        uint32_t answer = value + 1;
        struct reply_and_free w = {
            .free_command = BC_FREE_BUFFER, .buffer = txn.data.ptr.buffer, .reply_command = BC_REPLY,
            .txn = { .data_size = 4, .data.ptr.buffer = (binder_uintptr_t)&answer },
        };
        if(round + 1 == rounds)
        {
            /* (the last reply: written, then the manager is done) */
            struct binder_write_read bwr = { .write_size = sizeof(w), .write_buffer = (binder_uintptr_t)&w };
            if(ioctl(c.fd, BINDER_WRITE_READ, &bwr) < 0) fail("last reply");
            exit(0);
        }
        txn = read_until(&c, &w, sizeof(w), BR_TRANSACTION);
    }
}

struct transact
{
    uint32_t command;
    struct binder_transaction_data txn;
} __attribute__((packed));

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    if(argc < 2) fail("usage");
    const char *path = argv[1];
    static char device[512];
    struct stat st;
    if(stat(path, &st) == 0 && S_ISDIR(st.st_mode))
    {
        snprintf(device, sizeof(device), "%s/binder-control", path);
        int control = open(device, O_RDONLY | O_CLOEXEC);
        if(control < 0) fail("open binder-control");
        struct binderfs_device add = { .name = "pingpong" };
        if(ioctl(control, BINDER_CTL_ADD, &add) < 0 && errno != EEXIST) fail("BINDER_CTL_ADD");
        close(control);
        snprintf(device, sizeof(device), "%s/pingpong", path);
        path = device;
    }
    int rounds = argc > 2 ? atoi(argv[2]) : 10000;
    int cpu_a = argc > 3 ? atoi(argv[3]) : 0, cpu_b = argc > 4 ? atoi(argv[4]) : 1;
    pid_t child = fork();
    if(child < 0) fail("fork");
    if(child == 0) manager(path, rounds, cpu_b);
    pin(cpu_a);
    /* (the manager registers first) */
    usleep(200000);
    struct conn c;
    open_binder(&c, path);
    binder_uintptr_t last = 0;
    for(int round = 0; round < rounds; round++)
    {
        uint32_t value = (uint32_t)round * 2;
        struct
        {
            uint32_t free_command;
            binder_uintptr_t buffer;
            struct transact t;
        } __attribute__((packed)) w = {
            .free_command = BC_FREE_BUFFER, .buffer = last,
            .t = { .command = BC_TRANSACTION, .txn = { .target.handle = 0, .code = 1, .data_size = 4,
                .data.ptr.buffer = (binder_uintptr_t)&value } },
        };
        const void *write = last ? (const void *)&w : (const void *)&w.t;
        size_t len = last ? sizeof(w) : sizeof(w.t);
        struct binder_transaction_data reply = read_until(&c, write, len, BR_REPLY);
        uint32_t answer;
        if(reply.data_size != 4) fail("reply size");
        memcpy(&answer, (const void *)(uintptr_t)reply.data.ptr.buffer, 4);
        if(answer != value + 1) fail("reply value");
        last = reply.data.ptr.buffer;
    }
    int status;
    if(waitpid(child, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) fail("manager");
    printf("A64_BINDER_OK rounds=%d cpus=%d,%d\n", rounds, cpu_a, cpu_b);
    return 0;
}
                                                                                                                                             source/v64/tests/a64/browser.mjs                                                                    0000644 0000000 0000000 00000011634 00000000000 013623  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The arm64 virt machine in a headless Chrome (docs/arm64-virt-android16-plan.md
// P8.7): tests/a64/browser_test.html from a local server boots Alpine 3.24
// aarch64 from its ISO to a shell and runs the probe, from the source tree,
// from build/libv86.mjs, and in the CPU worker. The files come from
// tests/a64/linux_boot.mjs (A64_LINUX_PREPARE_ONLY=1). BROWSER_CHROME
// selects the browser.
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const chrome = process.env.BROWSER_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
for(const file of ["build/a64-linux/boot/vmlinuz-virt", "build/a64-linux/boot/initramfs-virt", "build/a64-linux/probe/probe.tar",
    "build/a64-linux/alpine-virt-3.24.0-aarch64.iso", "build/v86-arm64.wasm"])
{
    if(!fs.existsSync(root + file)) throw new Error(file + " is missing: A64_LINUX_PREPARE_ONLY=1 node tests/a64/linux_boot.mjs, make build/v86-arm64.wasm");
}

function run(query)
{
    return new Promise((resolve, reject) => {
        const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-a64-browser-"));
        let browser, timer;
        const server = http.createServer((req, res) => {
            if(req.method === "POST" && req.url === "/__result")
            {
                let body = "";
                req.on("data", data => { body += data; });
                req.on("end", () => { res.end("OK"); finish(body); });
                return;
            }
            const file = path.resolve(root, "." + decodeURIComponent(new URL(req.url, "http://localhost").pathname));
            if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
            fs.stat(file, (error, stat) => {
                if(error || !stat.isFile()) { res.writeHead(404).end(); return; }
                res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" :
                    /\.(js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".html") ? "text/html" : "application/octet-stream");
                res.setHeader("Accept-Ranges", "bytes");
                // (the ISO is read in ranges: async virtio-blk)
                const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers["range"] || "");
                if(range)
                {
                    const start = +range[1], end = Math.min(+range[2], stat.size - 1);
                    res.writeHead(206, { "Content-Range": `bytes ${start}-${end}/${stat.size}`, "Content-Length": end - start + 1 });
                    fs.createReadStream(file, { start, end }).pipe(res);
                    return;
                }
                if(file.endsWith(".html"))
                {
                    const data = Buffer.concat([fs.readFileSync(file), Buffer.from(`<script>
                        new MutationObserver((_, observer) => {
                            const text = document.getElementById("result").textContent;
                            if(!/^(PASS|FAIL)/.test(text)) return;
                            observer.disconnect();
                            fetch("/__result", { method: "POST", body: text + "\\n" + document.getElementById("log").textContent });
                        }).observe(document.body, { subtree: true, childList: true, characterData: true });
                    </script>`)]);
                    res.end(data);
                    return;
                }
                res.setHeader("Content-Length", stat.size);
                fs.createReadStream(file).pipe(res);
            });
        });
        const finish = text => {
            clearTimeout(timer);
            browser?.kill();
            server.close();
            try { fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5 }); } catch(e) { /* left in the temporary directory */ }
            (text.startsWith("PASS") ? resolve : reject)(text);
        };
        server.listen(0, "127.0.0.1", () => {
            const url = `http://127.0.0.1:${server.address().port}/tests/a64/browser_test.html?${query}`;
            browser = spawn(chrome, ["--headless=new", "--no-first-run", "--no-default-browser-check",
                "--disable-background-networking", `--user-data-dir=${profile}`, url], { stdio: "ignore" });
            browser.on("error", error => finish("FAIL " + error));
            timer = setTimeout(() => finish("FAIL timeout"), 900000);
        });
    });
}

let failed = 0;
for(const query of (process.env.A64_BROWSER_QUERIES || "build=source;build=bundle;build=bundle&cpu_worker=1;build=bundle&transport=pci").split(";"))
{
    try
    {
        console.log((await run(query)).split("\n")[0] + "  (" + query + ")");
    }
    catch(error)
    {
        failed++;
        console.log(String(error).slice(0, 3000) + "  (" + query + ")");
    }
}
process.exit(failed ? 1 : 0);
                                                                                                    source/v64/tests/a64/browser_caps.html                                                              0000644 0000000 0000000 00000003554 00000000000 015006  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Host Wasm capabilities</title>
<!--
The host capability matrix of docs/arm64-virt-android16-plan.md P0.8 (results
in its appendix A): what an ARM guest's cores need from the browser. Serve
the checkout with tools/dev-server.py (cross-origin isolation, for
SharedArrayBuffer) and open /tests/a64/browser_caps.html; the JSON at the end
of the page goes into the appendix. `node tests/a64/browser_caps.html` is not
a thing: Node's V8 is checked with tests/a64/browser_caps.mjs.
-->
<style>
    :root { --bg: #fff; --fg: #111; --muted: #666; --ok: #0a7a2f; --no: #b3261e; }
    @media (prefers-color-scheme: dark) { :root { --bg: #111; --fg: #eee; --muted: #999; --ok: #5bd17f; --no: #ff8a80; } }
    body { background: var(--bg); color: var(--fg); font: 15px/1.5 system-ui, sans-serif; margin: 0 auto; max-width: 52rem; padding: 16px; }
    table { border-collapse: collapse; width: 100%; }
    td { border-bottom: 1px solid var(--muted); padding: 4px 8px; vertical-align: top; }
    .yes { color: var(--ok); } .no { color: var(--no); }
    pre { white-space: pre-wrap; word-break: break-all; color: var(--muted); }
</style>
<h1>Host Wasm capabilities</h1>
<table id="table"></table>
<pre id="json"></pre>
<script type="module">
import { probe } from "./browser_caps.mjs";
const result = await probe();
const table = document.getElementById("table");
for(const [key, value] of Object.entries(result))
{
    const row = table.insertRow();
    row.insertCell().textContent = key;
    const cell = row.insertCell();
    cell.textContent = typeof value === "object" ? JSON.stringify(value) : String(value);
    if(value === true) cell.className = "yes";
    if(value === false) cell.className = "no";
}
document.getElementById("json").textContent = JSON.stringify(result, null, 1);
</script>
                                                                                                                                                    source/v64/tests/a64/browser_caps.mjs                                                               0000644 0000000 0000000 00000011607 00000000000 014631  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The probes of tests/a64/browser_caps.html (docs/arm64-virt-android16-plan.md
// P0.8): every result comes from compiling or running a module here, not from
// the user agent string. Run under Node it checks Node's V8:
//
//   node tests/a64/browser_caps.mjs

const leb = n => {
    const out = [];
    do { out.push(n > 127 ? n & 127 | 128 : n); n >>>= 7; } while(n);
    return out;
};
const simd = op => [0xFD, ...leb(op)];

// A module of one function `f` of type `type` (bytes of a functype) with body
// `body` (locals and code), plus an optional memory section
function module(type, body, memory = [])
{
    const code = [...leb(body.length), ...body];
    return new Uint8Array([0, 0x61, 0x73, 0x6D, 1, 0, 0, 0,
        1, ...leb(type.length + 1), 1, ...type,
        3, 2, 1, 0,
        ...(memory.length ? [5, ...leb(memory.length), ...memory] : []),
        7, 5, 1, 1, 0x66, 0, 0,
        10, ...leb(code.length + 1), 1, ...code]);
}
const validate = bytes => { try { return WebAssembly.validate(bytes); } catch{ return false; } };
const RESULT_I32 = [0x60, 0, 1, 0x7F];

// (cpu.js relaxed_fma_fused: (1 + ulp)^2 plus an addend that cancels all but
// the product's last bit, which only a fused multiply-add keeps)
function relaxed_madd()
{
    const lanes = (double, ...words) => [...simd(0x0C), ...(double ? [...words, ...words] : [words[0], words[0], words[0], words[0]])
        .flatMap(w => [w & 255, w >>> 8 & 255, w >>> 16 & 255, w >>> 24 & 255])];
    const check = (op, double, a, c, expected) => [...lanes(double, ...a), ...lanes(double, ...a), ...lanes(double, ...c),
        ...simd(op), ...lanes(double, ...expected), ...simd(double ? 0xD6 : 0x37), ...simd(double ? 0xC3 : 0xA3)];
    const bytes = module(RESULT_I32, [0,
        ...check(0x107, true, [1, 0x3FF00000], [2, 0xBFF00000], [0, 0x39700000]),
        ...check(0x108, true, [1, 0x3FF00000], [2, 0x3FF00000], [0, 0xB9700000]), 0x71,
        ...check(0x105, false, [0x3F800001], [0xBF800002], [0x28800000]), 0x71,
        ...check(0x106, false, [0x3F800001], [0x3F800002], [0xA8800000]), 0x71,
        0x0B]);
    if(!validate(bytes)) return { relaxed_simd: false, relaxed_madd_fused: false };
    try
    {
        return { relaxed_simd: true, relaxed_madd_fused: new WebAssembly.Instance(new WebAssembly.Module(bytes)).exports.f() === 1 };
    }
    catch{ return { relaxed_simd: true, relaxed_madd_fused: false }; }
}

/** The largest memory (in 64 KiB pages) of `candidates` this host creates */
function largest_memory(shared)
{
    for(const pages of [65536, 49152, 32768, 16384, 8192])
    {
        try
        {
            const memory = new WebAssembly.Memory({ initial: pages, maximum: pages, ...(shared ? { shared: true } : {}) });
            const ok = memory.buffer.byteLength === pages * 65536;
            if(ok) return pages * 65536 / 1048576 + " MiB";
        }
        catch{}
    }
    return "below 512 MiB";
}

export async function probe()
{
    const g = globalThis;
    const host = {};
    if(g.process?.versions?.node)
    {
        Object.assign(host, { node: g.process.version, v8: g.process.versions.v8, architecture: g.process.arch, platform: g.process.platform });
    }
    else if(g.navigator)
    {
        host.user_agent = g.navigator.userAgent;
        host.hardware_concurrency = g.navigator.hardwareConcurrency;
        try
        {
            const data = await g.navigator.userAgentData?.getHighEntropyValues(["architecture", "bitness", "platform", "platformVersion", "fullVersionList"]);
            if(data) Object.assign(host, { architecture: data.architecture, bitness: data.bitness, platform: data.platform,
                platform_version: data.platformVersion, browser: data.fullVersionList?.map(b => b.brand + " " + b.version).join(", ") });
        }
        catch{}
    }
    return {
        ...host,
        date: new Date().toISOString().slice(0, 10),
        cross_origin_isolated: g.crossOriginIsolated ?? null,
        shared_array_buffer: typeof SharedArrayBuffer === "function",
        largest_memory: largest_memory(false),
        largest_shared_memory: typeof SharedArrayBuffer === "function" ? largest_memory(true) : "no SharedArrayBuffer",
        // i32x4.splat, i32x4.extract_lane 0
        simd128: validate(module(RESULT_I32, [0, 0x41, 1, ...simd(0x11), ...simd(0x1B), 0, 0x0B])),
        // return_call 0
        tail_calls: validate(module(RESULT_I32, [0, 0x12, 0, 0x0B])),
        ...relaxed_madd(),
        // a 64-bit memory (limits flag 4), i64.const 0, i32.load
        memory64: validate(module(RESULT_I32, [0, 0x42, 0, 0x28, 2, 0, 0x0B], [1, 4, 1])),
        // atomic.fence
        threads: validate(module(RESULT_I32, [0, 0xFE, 0x03, 0, 0x41, 0, 0x0B])),
        bulk_memory: validate(module([0x60, 0, 0], [0, 0x41, 0, 0x41, 0, 0x41, 0, 0xFC, 11, 0, 0x0B], [1, 0, 1])),
    };
}

if(typeof window === "undefined" && import.meta.url === `file://${process.argv[1]}`)
{
    console.log(JSON.stringify(await probe(), null, 1));
}
                                                                                                                         source/v64/tests/a64/browser_test.html                                                              0000644 0000000 0000000 00000007103 00000000000 015031  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>v86 arm64 in a browser</title>
<!-- The arm64 virt machine in a browser (docs/arm64-virt-android16-plan.md
     P8.7): Alpine 3.24 aarch64 from its ISO on virtio-blk (the kernel and
     initramfs unpacked from it, build/a64-linux/) to a login on the serial
     console, a command, then the probe from its disk. ?build=bundle loads
     build/libv86.mjs; ?cpu_worker=1 runs the machine in the CPU worker;
     ?jit=0 the interpreter; ?transport=pci the devices on the PCIe host. -->
<pre id="log"></pre>
<div id="result"></div>
<script type="module">
const params = new URLSearchParams(location.search);
const log = text => { document.getElementById("log").textContent += text + "\n"; };
const done = text => { document.getElementById("result").textContent = text; };
const bundle = params.get("build") === "bundle", cpu_worker = params.get("cpu_worker") === "1", jit = params.get("jit") !== "0";
try
{
    const { V86 } = await import(bundle ? "../../build/libv86.mjs" : "../../src/main.js");
    const files = "../../build/a64-linux/";
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 512 << 20, log_level: 0, autostart: true,
        wasm_path: "../../build/v86-arm64.wasm",
        kernel: { url: files + "boot/vmlinuz-virt" }, initrd: { url: files + "boot/initramfs-virt" },
        cmdline: "console=ttyAMA0 modules=loop,squashfs,sd-mod,usb-storage",
        virtio_disks: [{ url: files + "alpine-virt-3.24.0-aarch64.iso", async: true, readonly: true },
            { url: files + "probe/probe.tar", id: "a64probe" }],
        virtio_rng: true, virtio_transport: params.get("transport") || "mmio",
        ...(jit ? { jit_switches: { a64_page: 1 } } : {}),
        cpu_worker, ...(cpu_worker && bundle ? { cpu_worker_url: "../../build/cpu-worker.js" } : {}),
    });
    let serial = "";
    emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
    const t0 = performance.now();
    const wait = async (pattern, what, from = 0) => {
        while(!pattern.test(serial.slice(from)))
        {
            if(performance.now() - t0 > 600000) throw new Error("no " + what + ": " + serial.slice(-800));
            await new Promise(resolve => setTimeout(resolve, 50));
        }
    };
    await wait(/localhost login: ?$/, "login prompt");
    const login_ms = Math.round(performance.now() - t0);
    emulator.serial0_send("root\n");
    await wait(/localhost:~# ?(\x1b\[[0-9;]*[A-Za-z])*$/, "shell");
    const from = serial.length;
    emulator.serial0_send("uname -m; for d in /sys/block/vd*; do [ \"$(cat $d/serial 2>/dev/null)\" = a64probe ] && " +
        "tar -xf /dev/${d##*/} -C /tmp; done; /tmp/a64-probe ref=browser 2>&1 | grep -E 'A64_PROBE_(OK|XC|FAIL)'; echo BROWSER_$((6*7))\n");
    await wait(/\nBROWSER_42\r?\n/, "the commands' end", from);
    const output = serial.slice(from);
    if(!/\naarch64\r?\n/.test(output)) throw new Error("uname -m: " + output.slice(0, 300));
    if(!/A64_PROBE_XC arch=aarch64/.test(output) || /A64_PROBE_FAIL/.test(output)) throw new Error("the probe: " + output.slice(-600));
    log(output.replace(/\r/g, "").split("\n").filter(line => /^A64_PROBE/.test(line)).join("\n"));
    await emulator.destroy();
    done(`PASS ${bundle ? "bundle" : "source"}${cpu_worker ? " cpu_worker" : ""}${jit ? " page tier" : " interpreter"}: ` +
        `login after ${(login_ms / 1000).toFixed(1)} s, the probe after ${((performance.now() - t0) / 1000).toFixed(1)} s`);
}
catch(error)
{
    log(String(error && error.stack || error));
    done("FAIL " + error);
}
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/a64/cil2bin.c                                                                      0000644 0000000 0000000 00000003275 00000000000 013115  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Compile a CIL policy to a binary one with libsepol's CIL compiler (Alpine
 * 3.24 has libsepol but no checkpolicy or secilc): tools/a64_kernel.mjs runs it
 * in its VM for tests/a64/minimal.cil (docs/arm64-virt-android16-plan.md P9.2).
 *
 *   cil2bin in.cil out.bin [policy version, 33] */
#include <stdio.h>
#include <stdlib.h>
#include <sepol/cil/cil.h>
#include <sepol/policydb.h>

int main(int argc, char **argv)
{
    if(argc < 3) { fprintf(stderr, "usage: cil2bin in.cil out.bin [version]\n"); return 2; }
    FILE *in = fopen(argv[1], "rb");
    if(!in) { perror(argv[1]); return 1; }
    fseek(in, 0, SEEK_END);
    long size = ftell(in);
    fseek(in, 0, SEEK_SET);
    char *text = malloc(size + 1);
    if(fread(text, 1, size, in) != (size_t)size) { perror("read"); return 1; }
    fclose(in);
    struct cil_db *db = NULL;
    cil_db_init(&db);
    cil_set_policy_version(db, argc > 3 ? atoi(argv[3]) : 33);
    if(cil_add_file(db, argv[1], text, size) != SEPOL_OK) { fprintf(stderr, "cil_add_file failed\n"); return 1; }
    if(cil_compile(db) != SEPOL_OK) { fprintf(stderr, "cil_compile failed\n"); return 1; }
    sepol_policydb_t *policy = NULL;
    if(cil_build_policydb(db, &policy) != SEPOL_OK) { fprintf(stderr, "cil_build_policydb failed\n"); return 1; }
    FILE *out = fopen(argv[2], "wb");
    if(!out) { perror(argv[2]); return 1; }
    struct sepol_policy_file *file = NULL;
    if(sepol_policy_file_create(&file) < 0) return 1;
    sepol_policy_file_set_fp(file, out);
    if(sepol_policydb_write(policy, file) < 0) { fprintf(stderr, "sepol_policydb_write failed\n"); return 1; }
    fclose(out);
    printf("cil2bin: %s, version %d\n", argv[2], argc > 3 ? atoi(argv[3]) : 33);
    return 0;
}
                                                                                                                                                                                                                                                                                                                                   source/v64/tests/a64/core_loader.mjs                                                                0000644 0000000 0000000 00000004266 00000000000 014421  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The loader picks the core of the CPU's family and refuses the other
// (docs/arm64-virt-android16-plan.md P1.3): the ARM core with cpu_type x86 or
// the x86 core with cpu_type arm64 is an error at startup, never a machine
// that runs the wrong instruction set.
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

async function start(options)
{
    const emulator = new V86({ autostart: false, log_level: 0, ...options });
    try
    {
        return await new Promise((resolve, reject) => {
            emulator.add_listener("emulator-loaded", () => resolve(emulator.v86.cpu.cpu_type || "x86"));
            emulator.add_listener("emulator-error", reject);
        });
    }
    finally
    {
        await emulator.destroy();
    }
}

assert.equal(await start({ cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, wasm_path: root + "build/v86-arm64.wasm" }), "arm64");
console.log("PASS cpu_type arm64 with the ARM core");
await assert.rejects(start({ cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, wasm_path: root + "build/v86.wasm" }),
    /The Wasm core is the x86 core \(v86.wasm\), cpu_type is "arm64"/);
console.log("PASS the x86 core with cpu_type arm64 is refused");
await assert.rejects(start({ graphics_adapter: "none", memory_size: 16 << 20, wasm_path: root + "build/v86-arm64.wasm",
    bios: { url: root + "bios/seabios.bin" } }), /The Wasm core is the ARM core \(v86-arm64.wasm\), cpu_type is "x86"/);
console.log("PASS the ARM core with cpu_type x86 is refused");
assert.equal(await start({ cpu_type: "arm32", graphics_adapter: "none", memory_size: 16 << 20, wasm_path: root + "build/v86-arm64.wasm" }), "arm32");
console.log("PASS cpu_type arm32 with the ARM core");
await assert.rejects(start({ cpu_type: "arm32", graphics_adapter: "none", memory_size: 16 << 20, wasm_path: root + "build/v86.wasm" }),
    /The Wasm core is the x86 core \(v86.wasm\), cpu_type is "arm32"/);
console.log("PASS the x86 core with cpu_type arm32 is refused");
                                                                                                                                                                                                                                                                                                                                          source/v64/tests/a64/crypto_oracle.mjs                                                              0000644 0000000 0000000 00000022123 00000000000 015000  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The crypto extension against QEMU and known answers
// (docs/arm64-virt-android16-plan.md P2.11): AESE/AESD/AESMC/AESIMC,
// SHA1C/P/M/H/SU0/SU1, SHA256H/H2/SU0/SU1 and PMULL/PMULL2 (8- and 64-bit) as
// random single-instruction cases (tests/a64/vector_oracle.mjs), then a
// guest that computes FIPS-197's AES-128 example (encrypt and decrypt), the
// FIPS 180-4 digests of "abc" (SHA-1, SHA-256) and the tag of GCM test case 2
// (AES-128 and GHASH through PMULL) with the instructions, on QEMU and v86.
//
//   node tests/a64/crypto_oracle.mjs [--cases N] [--seed S] [--filter mnemonic]
import assert from "node:assert/strict";
import fs from "node:fs";
import { options, run } from "./vector_oracle.mjs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const MNEMONICS = ["aese", "aesd", "aesmc", "aesimc", "sha1c", "sha1p", "sha1m", "sha1su0", "sha256h", "sha256h2", "sha256su1",
    "sha1h", "sha1su1", "sha256su0", "pmull", "pmull2"];
const { differences } = await run({ name: "crypto", classes: ["aes", "sha3", "sha2", "three_different"], mnemonics: MNEMONICS,
    ...options({ cases: 1600 }) });

const KAT = String.raw`#include <a64.h>
#include <stdio.h>
#include <arm_neon.h>

static void print(const char *name, const uint8_t *bytes, int count)
{
    printf("%s ", name);
    for(int i = 0; i < count; i++) printf("%02x", bytes[i]);
    printf("\n");
}

// ---- AES-128 (FIPS-197 appendix C.1); SubWord through AESE: every column the same word, so ShiftRows does nothing
static uint32_t sub_word(uint32_t w)
{
    uint8x16_t v = vreinterpretq_u8_u32(vdupq_n_u32(w));
    return vgetq_lane_u32(vreinterpretq_u32_u8(vaeseq_u8(v, vdupq_n_u8(0))), 0);
}
static void expand(const uint8_t key[16], uint8x16_t rk[11], uint8x16_t dk[11])
{
    uint32_t w[44];
    static const uint8_t rcon[10] = { 1, 2, 4, 8, 16, 32, 64, 128, 0x1b, 0x36 };
    for(int i = 0; i < 4; i++) w[i] = key[4 * i] | key[4 * i + 1] << 8 | key[4 * i + 2] << 16 | (uint32_t)key[4 * i + 3] << 24;
    for(int i = 4; i < 44; i++)
    {
        uint32_t t = w[i - 1];
        if(i % 4 == 0) t = sub_word(t >> 8 | t << 24) ^ rcon[i / 4 - 1];
        w[i] = w[i - 4] ^ t;
    }
    for(int r = 0; r < 11; r++) rk[r] = vreinterpretq_u8_u32(vld1q_u32(&w[4 * r]));
    dk[0] = rk[10];
    for(int r = 1; r < 10; r++) dk[r] = vaesimcq_u8(rk[10 - r]);
    dk[10] = rk[0];
}
static uint8x16_t encrypt(uint8x16_t s, const uint8x16_t rk[11])
{
    for(int r = 0; r < 9; r++) s = vaesmcq_u8(vaeseq_u8(s, rk[r]));
    return veorq_u8(vaeseq_u8(s, rk[9]), rk[10]);
}
static uint8x16_t decrypt(uint8x16_t s, const uint8x16_t dk[11])
{
    for(int r = 0; r < 9; r++) s = vaesimcq_u8(vaesdq_u8(s, dk[r]));
    return veorq_u8(vaesdq_u8(s, dk[9]), dk[10]);
}

// ---- SHA-256 and SHA-1 of "abc" (one padded block)
static const uint32_t K256[64] = {
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};
static void block_abc(uint8_t block[64])
{
    for(int i = 0; i < 64; i++) block[i] = 0;
    block[0] = 'a', block[1] = 'b', block[2] = 'c', block[3] = 0x80, block[63] = 24;
}
static void sha256(uint8_t digest[32])
{
    uint8_t block[64];
    block_abc(block);
    uint32x4_t msg[4];
    for(int i = 0; i < 4; i++) msg[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block + 16 * i)));
    uint32x4_t s0 = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a }, s1 = { 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
    uint32x4_t a = s0, b = s1;
    for(int g = 0; g < 16; g++)
    {
        uint32x4_t w = vaddq_u32(msg[g % 4], vld1q_u32(&K256[4 * g]));
        if(g < 12) msg[g % 4] = vsha256su1q_u32(vsha256su0q_u32(msg[g % 4], msg[(g + 1) % 4]), msg[(g + 2) % 4], msg[(g + 3) % 4]);
        uint32x4_t t = a;
        a = vsha256hq_u32(a, b, w);
        b = vsha256h2q_u32(b, t, w);
    }
    a = vaddq_u32(a, s0), b = vaddq_u32(b, s1);
    vst1q_u8(digest, vrev32q_u8(vreinterpretq_u8_u32(a)));
    vst1q_u8(digest + 16, vrev32q_u8(vreinterpretq_u8_u32(b)));
}
static void sha1(uint8_t digest[20])
{
    uint8_t block[64];
    block_abc(block);
    uint32x4_t msg[4];
    for(int i = 0; i < 4; i++) msg[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(block + 16 * i)));
    uint32x4_t abcd = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 }, start = abcd;
    uint32_t e = 0xc3d2e1f0, e_start = e;
    static const uint32_t k[4] = { 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 };
    for(int g = 0; g < 20; g++)
    {
        uint32x4_t w = vaddq_u32(msg[g % 4], vdupq_n_u32(k[g / 5]));
        uint32_t next = vsha1h_u32(vgetq_lane_u32(abcd, 0));
        if(g < 5) abcd = vsha1cq_u32(abcd, e, w);
        else if(g < 10 || g >= 15) abcd = vsha1pq_u32(abcd, e, w);
        else abcd = vsha1mq_u32(abcd, e, w);
        e = next;
        if(g < 16) msg[g % 4] = vsha1su1q_u32(vsha1su0q_u32(msg[g % 4], msg[(g + 1) % 4], msg[(g + 2) % 4]), msg[(g + 3) % 4]);
    }
    abcd = vaddq_u32(abcd, start);
    e += e_start;
    vst1q_u8(digest, vrev32q_u8(vreinterpretq_u8_u32(abcd)));
    for(int i = 0; i < 4; i++) digest[16 + i] = e >> (24 - 8 * i);
}

// ---- GHASH through PMULL (bits reflected within each byte: bit i of the integer is x^i)
static uint8x16_t gf_multiply(uint8x16_t x_block, uint8x16_t h_block)
{
    uint64x2_t x = vreinterpretq_u64_u8(vrbitq_u8(x_block)), h = vreinterpretq_u64_u8(vrbitq_u8(h_block));
    poly64_t x0 = vgetq_lane_u64(x, 0), x1 = vgetq_lane_u64(x, 1), h0 = vgetq_lane_u64(h, 0), h1 = vgetq_lane_u64(h, 1);
    uint64x2_t low = vreinterpretq_u64_p128(vmull_p64(x0, h0)), high = vreinterpretq_u64_p128(vmull_p64(x1, h1));
    uint64x2_t mid = veorq_u64(vreinterpretq_u64_p128(vmull_p64(x0, h1)), vreinterpretq_u64_p128(vmull_p64(x1, h0)));
    uint64_t p0 = vgetq_lane_u64(low, 0), p1 = vgetq_lane_u64(low, 1) ^ vgetq_lane_u64(mid, 0);
    uint64_t p2 = vgetq_lane_u64(high, 0) ^ vgetq_lane_u64(mid, 1), p3 = vgetq_lane_u64(high, 1);
    // (x^128 = x^7 + x^2 + x + 1: fold p3:p2 down twice)
    uint64x2_t r = vreinterpretq_u64_p128(vmull_p64(p2, 0x87)), s = vreinterpretq_u64_p128(vmull_p64(p3, 0x87));
    uint64_t t0 = vgetq_lane_u64(r, 0), t1 = vgetq_lane_u64(r, 1) ^ vgetq_lane_u64(s, 0), t2 = vgetq_lane_u64(s, 1);
    uint64_t u = vgetq_lane_u64(vreinterpretq_u64_p128(vmull_p64(t2, 0x87)), 0);
    uint64x2_t result = { p0 ^ t0 ^ u, p1 ^ t1 };
    return vrbitq_u8(vreinterpretq_u8_u64(result));
}

int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    uint8_t key[16], plain[16], out[32];
    for(int i = 0; i < 16; i++) key[i] = i, plain[i] = 0x11 * i;
    uint8x16_t rk[11], dk[11];
    expand(key, rk, dk);
    uint8x16_t cipher = encrypt(vld1q_u8(plain), rk);
    vst1q_u8(out, cipher);
    print("aes128-encrypt", out, 16);
    vst1q_u8(out, decrypt(cipher, dk));
    print("aes128-decrypt", out, 16);
    sha256(out);
    print("sha256-abc", out, 32);
    sha1(out);
    print("sha1-abc", out, 20);
    // GCM test case 2: K = 0, P = 0^128, IV = 0^96
    for(int i = 0; i < 16; i++) key[i] = 0;
    expand(key, rk, dk);
    uint8x16_t zero = vdupq_n_u8(0);
    uint8x16_t h = encrypt(zero, rk);
    uint8_t counter[16] = { 0 };
    counter[15] = 1;
    uint8x16_t ey0 = encrypt(vld1q_u8(counter), rk);
    counter[15] = 2;
    uint8x16_t c = encrypt(vld1q_u8(counter), rk);
    uint8_t lengths[16] = { 0 };
    lengths[15] = 128;
    uint8x16_t x = gf_multiply(c, h);
    x = gf_multiply(veorq_u8(x, vld1q_u8(lengths)), h);
    vst1q_u8(out, c);
    print("gcm2-ciphertext", out, 16);
    vst1q_u8(out, veorq_u8(x, ey0));
    print("gcm2-tag", out, 16);
    return 0;
}
`;
const EXPECTED = [
    "aes128-encrypt 69c4e0d86a7b0430d8cdb78070b4c55a",
    "aes128-decrypt 00112233445566778899aabbccddeeff",
    "sha256-abc ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
    "sha1-abc a9993e364706816aba3e25717850c26c9cd0d89d",
    "gcm2-ciphertext 0388dace60b6a392f328c2b971b2fe78",
    "gcm2-tag ab6e47d42cec13bdf53a67b21257bddf",
].join("\n") + "\n";

const source = root + "build/a64-crypto-kat.c";
fs.writeFileSync(source, KAT);
const directory = build("crypto-kat", [source]);
let failed = differences ? 1 : 0;
for(const [name, machine] of [["QEMU", reference], ["v86", actual]])
{
    const result = await machine(directory);
    assert.equal(result.status, "ok", name);
    if(result.text === EXPECTED)
    {
        console.log(`known answers (FIPS-197, FIPS 180-4, GCM test case 2): ${name} ok`);
    }
    else
    {
        failed = 1;
        console.log(`known answers on ${name}:\n${result.text}expected:\n${EXPECTED}`);
    }
}
process.exit(failed);
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/a64/decode_check.mjs                                                               0000644 0000000 0000000 00000023720 00000000000 014517  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 decoder against the decode oracle (docs/arm64-virt-android16-plan.md
// P2.1): every word of a set is decoded by v86 (a64_decode_mnemonic of the
// ARM core) and by llvm-mc with the profile's features
// (tests/a64/oracle/decode.mjs); they must agree on whether it is an
// instruction and which. llvm-mc names an instruction by its preferred
// alias (mov, cmp, lsl, ...), v86 by the base instruction: ALIASES maps them.
//
// The set: every encoding of the classes whose fields are few enough
// (hints, system registers, system instructions, exception generation, the
// one- and two-source data processing opcodes, the PSTATE fields; every
// field of the FP/SIMD data processing group with a few register values,
// the AdvSIMD structure loads and stores), and a stratified sample of the
// rest of the 2^32 space. --no-fp-simd leaves out the FP and SIMD groups
// (as A1's decoder, which had none, was checked).
//
// --words FILE checks the words of a file instead (hexadecimal, one per line:
// the corpus of tests/a64/trace_replay.mjs, P2.10).
//
//   node tests/a64/decode_check.mjs [--sample N] [--seed S] [--no-fp-simd] [--words FILE]
import fs from "node:fs";
import { decode as oracle } from "./oracle/decode.mjs";
import { root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const SAMPLE = +option("--sample", 1000000);
const SEED = +option("--seed", 1);
const ALL_GROUPS = !args.includes("--no-fp-simd");

// llvm-mc's spelling -> v86's base mnemonics it may stand for
const ALIASES = {
    mov: ["add", "orr", "movz", "movn"], cmn: ["adds"], cmp: ["subs"], negs: ["subs"], neg: ["sub"], tst: ["ands"], mvn: ["orn"],
    asr: ["sbfm", "asrv"], sxtb: ["sbfm"], sxth: ["sbfm"], sxtw: ["sbfm"], sbfiz: ["sbfm"], sbfx: ["sbfm"],
    lsl: ["ubfm", "lslv"], lsr: ["ubfm", "lsrv"], uxtb: ["ubfm"], uxth: ["ubfm"], ubfiz: ["ubfm"], ubfx: ["ubfm"],
    bfi: ["bfm"], bfxil: ["bfm"], bfc: ["bfm"], ror: ["extr", "rorv"],
    cset: ["csinc"], cinc: ["csinc"], csetm: ["csinv"], cinv: ["csinv"], cneg: ["csneg"],
    mul: ["madd"], mneg: ["msub"], smull: ["smaddl"], smnegl: ["smsubl"], umull: ["umaddl"], umnegl: ["umsubl"],
    ngc: ["sbc"], ngcs: ["sbcs"],
    nop: ["hint"], yield: ["hint"], wfe: ["hint"], wfi: ["hint"], sev: ["hint"], sevl: ["hint"], esb: ["hint"], psb: ["hint"],
    csdb: ["hint"], dgh: ["hint"], tsb: ["hint"], bti: ["hint"], xpaclri: ["hint"], clrbhb: ["hint"],
    dc: ["sys"], ic: ["sys"], at: ["sys"], tlbi: ["sys"], ssbb: ["dsb"], pssbb: ["dsb"],
    rev64: ["rev"], ldur: ["ldur"], stur: ["stur"],
    // (the hint and prefetch spaces of later extensions: NOPs in v8.0)
    rprfm: ["prfm"], stshh: ["hint"], shuh: ["hint"], stcph: ["hint"], apas: ["sys"],
    // AdvSIMD
    sxtl: ["sshll"], sxtl2: ["sshll2"], uxtl: ["ushll"], uxtl2: ["ushll2"],
};
ALIASES.mov.push("ins", "dup", "umov", "orr");
ALIASES.mvn.push("not");
const same = (llvm, v86, text) => llvm === v86 || (ALIASES[llvm] || []).includes(v86) || llvm === "b" && /^b\./.test(text) && v86 === "b.cond";

/**
 * Where llvm-mc decodes more than the architecture allocates for profile v1
 * (its decoder ignores the features of these, or reads a field wider than
 * the encoding has): these words are not instructions, whatever it says
 */
function oracle_over_accepts(word, mnemonic, text)
{
    const system = (word & 0xFFC00000) >>> 0 === 0xD5000000;
    // MRS/MSR (register) need op0 = 1x (bit 20); with op0 = 0x they are
    // unallocated (MSR (immediate), "msr <pstatefield>, #imm", is another class)
    if(system && (mnemonic === "mrs" || mnemonic === "msr") && !(word >>> 20 & 1) && !/, #/.test(text)) return true;
    // FEAT_SYSREG128, FEAT_SME, FEAT_EBEP (PSTATE.PM)
    return ["mrrs", "msrr", "sysp", "smstart", "smstop"].includes(mnemonic) || /^msr PM, #/.test(text);
}

// ---- v86's decoder: the ARM core on its own
const wasm = fs.readFileSync(process.env.A64_WASM || root + "build/v86-arm64.wasm");
const module = new WebAssembly.Module(wasm);
const env = {};
for(const { name, kind } of WebAssembly.Module.imports(module))
{
    if(kind === "function") env[name] = () => 0n;
    if(kind === "table") env[name] = new WebAssembly.Table({ element: "anyfunc", initial: 13100 });
}
const core = new WebAssembly.Instance(module, { env }).exports;
const v86 = word => {
    const at = core.a64_decode_mnemonic(word) >>> 0;
    const bytes = new Uint8Array(core.memory.buffer, at, 16);
    return new TextDecoder().decode(bytes.subarray(0, bytes.indexOf(0)));
};

// ---- the words
/** Whether a word is in a group the decoder implements now */
function in_scope(word)
{
    if(ALL_GROUPS) return true;
    const op0 = word >>> 25 & 0xF;
    if((op0 & 0b0111) === 0b0111) return false; // scalar FP and AdvSIMD
    if((op0 & 0b0101) === 0b0100 && word >>> 26 & 1) return false; // SIMD&FP loads and stores
    return true;
}

const words = new Set();
const add = w => { if(in_scope(w >>> 0)) words.add(w >>> 0); };
// hints, barriers, PSTATE, system instructions and registers: every field (Rt 1 or 31)
for(let f = 0; f < 1 << 16; f++)
{
    for(const l of [0, 1]) for(const rt of [1, 31]) add(0xD5000000 | l << 21 | f << 5 | rt);
}
// exception generation: opc, op2, LL (imm16 1)
for(let opc = 0; opc < 8; opc++) for(let op2 = 0; op2 < 8; op2++) for(let ll = 0; ll < 4; ll++) add(0xD4000000 | opc << 21 | 1 << 5 | op2 << 2 | ll);
// unconditional branch (register): opc, op2, op3, Rn, op4
for(let opc = 0; opc < 16; opc++) for(let op3 = 0; op3 < 64; op3++) for(const op4 of [0, 1, 31]) for(const op2 of [31, 30]) for(const rn of [1, 31])
{
    add(0xD6000000 | opc << 21 | op2 << 16 | op3 << 10 | rn << 5 | op4);
}
// data processing (1 and 2 source), carry, conditional compare and select, 3 source: the opcode fields
for(let sf = 0; sf < 2; sf++) for(let s = 0; s < 2; s++) for(let opcode = 0; opcode < 64; opcode++)
{
    for(const opcode2 of [0, 1, 31]) add(sf << 31 | 1 << 30 | s << 29 | 0b11010110 << 21 | opcode2 << 16 | opcode << 10 | 2 << 5 | 3);
    add(sf << 31 | s << 29 | 0b11010110 << 21 | 4 << 16 | opcode << 10 | 2 << 5 | 3);
    add(sf << 31 | s << 29 | 0b11010000 << 21 | 4 << 16 | opcode << 10 | 2 << 5 | 3);
}
for(let w = 0; w < 1 << 16; w++)
{
    // conditional compare (op 30, S 29, cond, o2, o3, bit 11) and select (op2)
    add(0x1A400000 | (w & 0x7) << 29 | (w >> 3 & 0xF) << 12 | (w >> 7 & 3) << 10 | (w >> 9 & 1) << 4 | (w >> 10 & 1) << 31 | 0x1F << 16);
    add(0x1A800000 | (w & 0x7) << 29 | (w >> 3 & 0xF) << 12 | (w >> 7 & 3) << 10 | (w >> 10 & 1) << 31 | 2 << 16 | 3 << 5 | 4);
    // 3 source: sf, op54, op31, o0
    add(0x1B000000 | (w & 1) << 31 | (w >> 1 & 3) << 29 | (w >> 3 & 7) << 21 | (w >> 6 & 1) << 15 | 2 << 16 | 3 << 10 | 4 << 5 | 5);
}
// loads and stores: every top-level field with registers 1-3 (V = 0 and 1)
for(let w = 0; w < 1 << 16; w++)
{
    for(const v of [0, 1 << 26])
    {
        const word = (w & 0x3) << 30 | 0b111 << 27 | v | (w >> 2 & 3) << 24 | (w >> 4 & 3) << 22 | (w >> 6 & 1) << 21 |
            (w >> 7 & 0x1F) << 16 | (w >> 12 & 3) << 10 | (w >> 14 & 3) << 12 | 2 << 5 | 1;
        add(word);
        add(word & ~(1 << 27) | 1 << 28);
        add(word & ~(3 << 27) | 1 << 29 | (w >> 7 & 1) << 15);
    }
}
// FP/SIMD data processing (bits 28:25 = x111): every value of bits 31:28, 24:10, with Rn/Rd 2/1 and
// the low fields the FP classes use (imm5, opcode2, nzcv) and the modified immediates' defgh
for(let top = 0; top < 16; top++) for(let b24 = 0; b24 < 2; b24++) for(let mid = 0; mid < 1 << 14; mid++)
{
    const base = top << 28 | 0b111 << 25 | b24 << 24 | mid << 10;
    for(const low of [2 << 5 | 1, 0, 0b01000, 0b10000, 0b11000, 0x3FF, 1 << 5 | 0x11]) add(base | low);
}
// AdvSIMD structures: Q, bits 24:21, Rm, opcode, S, size (Rn 2, Rt 1; Rm 0, 3 and 31)
for(let q = 0; q < 2; q++) for(let b = 0; b < 16; b++) for(const rm of [0, 3, 31]) for(let op = 0; op < 64; op++)
{
    add(q << 30 | 0b0011 << 26 | b << 21 | rm << 16 | op << 10 | 2 << 5 | 1);
}
// the rest: stratified by the top 8 bits
let rng = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
for(let i = 0; i < SAMPLE; i++)
{
    rng ^= rng << 13n & (1n << 64n) - 1n; rng ^= rng >> 7n; rng ^= rng << 17n & (1n << 64n) - 1n;
    add((i & 0xFF) << 24 | Number(rng & 0xFFFFFFn));
}

const words_file = option("--words", null);
const list = words_file ? fs.readFileSync(words_file, "utf8").split("\n").filter(Boolean).map(w => parseInt(w, 16) >>> 0) : [...words];
// (the decoder decodes every profile's encodings, the widest's: v2, with
// FEAT_PAN's MSR PAN; the executor refuses what the machine's profile lacks)
const decoded = oracle(list, JSON.parse(fs.readFileSync(root + "tests/platform/a64-profile.json", "utf8")).v2.llvm_mattr);
const differences = new Map();
let different = 0;
list.forEach((word, i) => {
    const mine = v86(word), theirs = decoded[i];
    const valid = mine !== "";
    const their_valid = theirs.valid && !oracle_over_accepts(word, theirs.mnemonic, theirs.text);
    let problem = null;
    if(valid !== their_valid) problem = `v86 ${valid ? mine : "UNDEF"}, llvm-mc ${theirs.valid ? theirs.text : "invalid"}`;
    else if(valid && !same(theirs.mnemonic, mine, theirs.text)) problem = `v86 ${mine}, llvm-mc ${theirs.text}`;
    if(!problem) return;
    different++;
    const key = (theirs.mnemonic || "invalid") + " / " + (mine || "UNDEF");
    if(!differences.has(key)) differences.set(key, { count: 0, example: (word >>> 0).toString(16).padStart(8, "0") + ": " + problem });
    differences.get(key).count++;
});
for(const [key, { count, example }] of [...differences].sort((a, b) => b[1].count - a[1].count).slice(0, 60))
{
    console.log(`${key} x${count}  e.g. ${example}`);
}
const instructions = decoded.filter((d, i) => d.valid && !oracle_over_accepts(list[i], d.mnemonic, d.text)).length;
console.log(`decode check: ${list.length} words${words_file ? " of " + words_file + ` (${instructions} instructions of profile v1)` : ""}` +
    `${ALL_GROUPS ? "" : " (no FP/SIMD)"}, ${different} differences`);
process.exit(different ? 1 : 0);
                                                source/v64/tests/a64/device_io_reset.mjs                                                            0000644 0000000 0000000 00000015123 00000000000 015265  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// virtio-blk I/O in flight on the virt machine (docs/arm64-virt-android16-plan.md
// P5.9; as tests/devices/device_io_reset.mjs for the PC's disks). The disk is
// an in-memory image whose reads and writes complete 100 ms later; the test
// is the driver, through the virtio-mmio registers and a queue in guest RAM:
// - a reset (PSCI SYSTEM_RESET's path) while a read is in flight: its reply
//   never reaches the used ring, it is no longer pending for snapshots;
// - a reset while a write is in flight: the write lands in the image, its
//   reply does not reach the reset device;
// - a snapshot while a read is in flight: it waits for the read, whose reply
//   is in the snapshot's used ring;
// - a snapshot of another device layout (other disks, other slots) is refused.
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { SyncBuffer } = await import("../../src/buffer.js");

const SIZE = 1 << 20, LATENCY = 100;
const image = new Uint8Array(SIZE).map((_, i) => i * 7 & 0xFF);
let writes_landed = 0;
const base = new SyncBuffer(image.buffer);
const disk = Object.create(base);
disk.get = (start, length, callback) => setTimeout(() => base.get(start, length, callback), LATENCY);
disk.set = (start, data, callback) => setTimeout(() => base.set(start, data, () => { writes_landed++; callback(); }), LATENCY);

async function machine(disks)
{
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", virtio_disks: disks,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}
const emulator = await machine([{ buffer: disk, id: "slow" }]);
const cpu = emulator.v86.cpu;
// (no kernel: a machine reset restarts the boot core at RAM's start)
Object.assign(cpu, { booted: true, boot_entry: 0x40000000, boot_x0: 0 });
const slot = 31, transport = cpu.virtio_mmio[slot];
const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
assert.equal(reg(0x008), 2, "the disk is virtio-blk, in the last slot");

// the queue in RAM: descriptors, the driver's ring, the device's ring
const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUFFERS = RAM + 0x20000;
const QUEUE = 8;
const u16 = (address, value) => cpu.write_blob_physical(new Uint8Array([value & 0xFF, value >> 8]), address);
const u32 = (address, value) => cpu.write_blob_physical(new Uint8Array(new Uint32Array([value]).buffer), address);
const used_idx = () => cpu.read16_physical(USED + 2);
function driver_init()
{
    reg(0x070, 0);
    reg(0x070, 1 | 2);
    reg(0x024, 1); reg(0x020, 1); // VIRTIO_F_VERSION_1
    reg(0x024, 0); reg(0x020, 0);
    reg(0x070, 1 | 2 | 8);
    assert.equal(reg(0x070) & 8, 8, "FEATURES_OK");
    reg(0x030, 0); reg(0x038, QUEUE);
    reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
    cpu.write_blob_physical(new Uint8Array(0x3000), DESC);
    reg(0x044, 1);
    reg(0x070, 1 | 2 | 8 | 4);
}
let avail = 0;
/** One request: header, data (written by the device for a read), status */
function request(type, sector, data_length, data)
{
    const header = BUFFERS, payload = BUFFERS + 0x100, status = BUFFERS + 0x2000;
    const head = new Uint8Array(16), view = new DataView(head.buffer);
    view.setUint32(0, type, true); view.setUint32(8, sector, true);
    cpu.write_blob_physical(head, header);
    if(data) cpu.write_blob_physical(data, payload);
    cpu.write_blob_physical(new Uint8Array([0xFF]), status);
    const descriptor = (i, address, length, flags, next) => {
        u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length);
        u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next);
    };
    const WRITE = 2, NEXT = 1;
    descriptor(0, header, 16, NEXT, 1);
    descriptor(1, payload, data_length, NEXT | (type === 0 ? WRITE : 0), 2);
    descriptor(2, status, 1, WRITE, 0);
    u16(AVAIL + 4 + 2 * (avail % QUEUE), 0);
    u16(AVAIL + 2, ++avail);
    reg(0x050, 0);
    return { status: () => cpu.read8_physical(status), payload: length => cpu.read_blob_physical(payload, length) };
}

// a read in flight, then a reset of the machine
driver_init();
let r = request(0, 0, 512);
assert.equal(cpu["snapshot_io_pending"], 1, "the read is in flight");
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.equal(used_idx(), 0, "the read's reply did not reach the used ring after the reset");
assert.equal(cpu["snapshot_io_pending"], 0, "and the read is no longer pending");
assert.equal(reg(0x070), 0, "the device is reset");
console.log("ok - a virtio-blk read in flight across a reset is dropped");

// a write in flight, then a reset
avail = 0;
driver_init();
const pattern = new Uint8Array(512).fill(0x5A);
r = request(1, 8, 512, pattern);
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.equal(writes_landed, 1, "the write landed in the image");
assert.deepEqual(image.subarray(8 * 512, 9 * 512), pattern, "with its data");
assert.equal(used_idx(), 0, "its reply did not reach the reset device");
console.log("ok - a virtio-blk write in flight across a reset lands, unanswered");

// a snapshot while a read is in flight waits for it
avail = 0;
driver_init();
r = request(0, 1, 512);
const state = await emulator.save_state();
assert.equal(used_idx(), 1, "the read completed before the snapshot was taken");
assert.equal(r.status(), 0, "VIRTIO_BLK_S_OK");
assert.deepEqual(r.payload(512), image.subarray(512, 1024), "the sector's bytes");
cpu.write_blob_physical(new Uint8Array(0x100), USED);
await emulator.restore_state(state);
assert.equal(used_idx(), 1, "the restored used ring has the reply");
console.log("ok - a snapshot waits for a virtio-blk read in flight");

// another layout's snapshot is refused
const other = await machine([{ buffer: new SyncBuffer(new ArrayBuffer(SIZE)) }, { buffer: new SyncBuffer(new ArrayBuffer(SIZE)) }]);
await assert.rejects(other.restore_state(state), /virtio devices/, "a snapshot of other virtio devices");
console.log("ok - a snapshot of another virtio layout is refused");
await other.destroy();
await emulator.destroy();
console.log("device_io_reset (virt): passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/a64/dm_verity.c                                                                    0000644 0000000 0000000 00000005370 00000000000 013573  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* A dm-verity device through the device mapper's ioctls on
 * /dev/mapper/control (docs/arm64-virt-android16-plan.md P9.2), what
 * Android's first-stage init does with libdm, without dmsetup:
 * DM_DEV_CREATE, DM_TABLE_LOAD with one verity target, DM_DEV_SUSPEND
 * without the suspend flag (resume: the table goes live). Built by
 * tools/a64_kernel.mjs.
 *
 *   dm_verity <name> <sectors> <verity's parameters...>
 *
 * Prints the device's node, /dev/dm-<minor>; A64_VERITY_FAIL <why> on stderr else. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <unistd.h>
#include <linux/dm-ioctl.h>

static void fail(const char *what)
{
    fprintf(stderr, "A64_VERITY_FAIL %s (errno %d)\n", what, errno);
    exit(1);
}

static union
{
    struct dm_ioctl io;
    uint8_t bytes[16384];
} buffer;

static void prepare(const char *name, size_t data_size)
{
    memset(&buffer, 0, sizeof(buffer));
    buffer.io.version[0] = DM_VERSION_MAJOR;
    buffer.io.data_size = sizeof(struct dm_ioctl) + data_size;
    buffer.io.data_start = sizeof(struct dm_ioctl);
    /* (verity's table must be read-only: its devices are opened without write) */
    buffer.io.flags = DM_READONLY_FLAG;
    snprintf(buffer.io.name, sizeof(buffer.io.name), "%s", name);
}

int main(int argc, char **argv)
{
    if(argc < 4) fail("usage");
    const char *name = argv[1];
    char parameters[8192] = "";
    for(int i = 3; i < argc; i++)
    {
        if(strlen(parameters) + strlen(argv[i]) + 2 > sizeof(parameters)) fail("parameters too long");
        if(i > 3) strcat(parameters, " ");
        strcat(parameters, argv[i]);
    }
    int control = open("/dev/mapper/control", O_RDWR | O_CLOEXEC);
    if(control < 0) fail("open /dev/mapper/control");
    prepare(name, 0);
    if(ioctl(control, DM_DEV_CREATE, &buffer) < 0) fail("DM_DEV_CREATE");
    unsigned minor_number = minor(buffer.io.dev);
    /* (one target spec, its parameters after it, 8-byte aligned) */
    size_t spec_bytes = (sizeof(struct dm_target_spec) + strlen(parameters) + 1 + 7) & ~(size_t)7;
    prepare(name, spec_bytes);
    buffer.io.target_count = 1;
    struct dm_target_spec *spec = (struct dm_target_spec *)(buffer.bytes + sizeof(struct dm_ioctl));
    spec->sector_start = 0;
    spec->length = strtoull(argv[2], NULL, 10);
    spec->next = spec_bytes;
    snprintf(spec->target_type, sizeof(spec->target_type), "verity");
    strcpy((char *)(spec + 1), parameters);
    if(ioctl(control, DM_TABLE_LOAD, &buffer) < 0) fail("DM_TABLE_LOAD");
    prepare(name, 0);
    if(ioctl(control, DM_DEV_SUSPEND, &buffer) < 0) fail("DM_DEV_SUSPEND (resume)");
    printf("/dev/dm-%u\n", minor_number);
    return 0;
}
                                                                                                                                                                                                                                                                        source/v64/tests/a64/dtb.mjs                                                                        0000644 0000000 0000000 00000007656 00000000000 012722  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The virt machine's device tree against the reference's
// (docs/arm64-virt-android16-plan.md P4.1): src/virt/dtb.js's tree and
// QEMU 9.2's dumpdtb for the same machine (1, 2 and 4 cores, a kernel
// command line and an initrd), both decompiled by dtc with sorted nodes and
// properties, must differ only by the allowed differences of
// tests/platform/a64-profile.json: the nodes of devices v86 does not have
// (flash, fw-cfg, PL061 and gpio-keys, the platform bus), the cores'
// compatible (v86 is no Cortex part) and /chosen/rng-seed (v86 writes one).
// The PCIe host bridge's node (P5.6) is the reference's.
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
import { QEMU_MACHINE, QEMU_CPU, qemu_binary, smp, root } from "./guest_runner.mjs";
import { flatten, virt_tree } from "../../src/virt/dtb.js";

const directory = root + "build/a64-dtb/";
fs.mkdirSync(directory, { recursive: true });
const dts = file => execFileSync("dtc", ["-q", "-s", "-I", "dtb", "-O", "dts", file], { encoding: "utf8" });

/** Remove a node block (by its name's start) or a property line from dtc's output */
function without(text, { nodes = [], props = [] })
{
    const lines = text.split("\n");
    const out = [];
    for(let i = 0; i < lines.length; i++)
    {
        const line = lines[i];
        const name = line.trim().replace(/ \{$/, "");
        if(line.trim().endsWith("{") && nodes.some(n => name === n || name.startsWith(n + "@")))
        {
            let depth = 1;
            while(depth) { i++; depth += (lines[i].match(/\{/g) || []).length - (lines[i].match(/\}/g) || []).length; }
            continue;
        }
        if(props.some(p => line.trim().startsWith(p + " =") || line.trim() === p + ";")) continue;
        out.push(line);
    }
    return out.join("\n").replace(/\n\n+/g, "\n\n");
}

const kernel = directory + "kernel.bin", initrd = directory + "initrd.bin";
// (a minimal Image the reference loads: the header and a branch to itself)
const image = Buffer.alloc(4096);
image.writeUInt32LE(0x14000000, 0);
image.writeUInt32LE(0x80000, 8);
image.writeUInt32LE(4096, 16);
image.writeUInt32LE(0x644D5241, 56);
fs.writeFileSync(kernel, image);
fs.writeFileSync(initrd, Buffer.alloc(300000, 7));
const memory = 512;
const bootargs = "console=ttyAMA0 earlycon rdinit=/a64-init";
let failed = 0;
for(const cores of [1, 2, 4])
{
    const reference = directory + `qemu-${cores}.dtb`;
    const r = spawnSync(qemu_binary(), ["-machine", QEMU_MACHINE + ",dumpdtb=" + reference, "-cpu", QEMU_CPU, "-m", memory + "M",
        "-smp", smp(cores), "-nodefaults", "-display", "none", "-kernel", kernel, "-initrd", initrd, "-append", bootargs], { encoding: "utf8" });
    assert.ok(fs.existsSync(reference), "QEMU dumpdtb: " + r.stderr);
    // (the reference's initrd: at RAM + min(RAM / 2, 128 MiB))
    const start = 0x40000000 + Math.min(memory / 2, 128) * 1024 * 1024;
    const ours = directory + `v86-${cores}.dtb`;
    fs.writeFileSync(ours, flatten(virt_tree({ cores, memory_size: memory << 20, bootargs, initrd: { start, end: start + 300000 },
        rng_seed: new Uint8Array(32) })));
    const allowed = { nodes: ["flash", "fw-cfg", "pl061", "gpio-keys", "platform-bus"], props: ["rng-seed", "compatible = \"arm,cortex-a35\"", "compatible = \"arm,armv8\""] };
    const want = without(dts(reference), allowed), have = without(dts(ours), allowed);
    fs.writeFileSync(directory + `qemu-${cores}.dts`, want);
    fs.writeFileSync(directory + `v86-${cores}.dts`, have);
    if(want === have)
    {
        console.log(`PASS ${cores} core(s): the device trees agree but for the allowed differences`);
    }
    else
    {
        failed++;
        const diff = spawnSync("diff", ["-u", directory + `qemu-${cores}.dts`, directory + `v86-${cores}.dts`], { encoding: "utf8" });
        console.log(`FAIL ${cores} core(s):\n${diff.stdout.slice(0, 3000)}`);
    }
}
process.exit(failed ? 1 : 0);
                                                                                  source/v64/tests/a64/encodings.json                                                                 0000644 0000000 0000000 00000034017 00000000000 014271  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
  "about": "The encoding coverage list of the A64 decoder (docs/arm64-virt-android16-plan.md P2.1): every class of the Arm ARM's encoding index (DDI 0487 L.b, C4.1) with its status in profile v86-aarch64-v1 (implemented; undef: unallocated or a feature v1 does not declare; hint: executes as NOP; id-space: reads as zero at EL1), the feature, what the class raises, and the tests that cover it. tests/a64/decode_check.mjs holds the decoder to llvm-mc over every listed class (all fields of the small classes, the FP/SIMD group exhaustively but for registers, a stratified sample of the rest); the oracles hold the execution to QEMU and, for FP/SIMD/crypto, to an Apple M1 Pro.",
  "profile": "v86-aarch64-v1",
  "statuses": {
    "implemented": "decoded and executed",
    "undef": "UNDEFINED (EC 0x00): unallocated, or a feature profile v1 does not declare",
    "hint": "a HINT the profile does not implement: executes as NOP",
    "id-space": "an unallocated ID register: reads 0 at EL1, UNDEF at EL0"
  },
  "classes": [
    { "group": "Reserved", "class": "UDF and the rest of op0 = 0000", "status": "undef", "tests": ["decode_check"] },
    { "group": "SME, SVE", "class": "op0 = 1xxx 000x, 0010", "status": "undef", "feature": "FEAT_SME, FEAT_SVE", "tests": ["decode_check"] },

    { "group": "Data Processing -- Immediate", "class": "PC-rel. addressing", "status": "implemented", "instructions": ["adr", "adrp"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Immediate", "class": "Add/subtract (immediate)", "status": "implemented", "instructions": ["add", "adds", "sub", "subs"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Immediate", "class": "Add/subtract (immediate, with tags)", "status": "undef", "feature": "FEAT_MTE", "tests": ["decode_check"] },
    { "group": "Data Processing -- Immediate", "class": "Min/max (immediate)", "status": "undef", "feature": "FEAT_CSSC", "tests": ["decode_check"] },
    { "group": "Data Processing -- Immediate", "class": "Logical (immediate)", "status": "implemented", "instructions": ["and", "orr", "eor", "ands"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Immediate", "class": "Move wide (immediate)", "status": "implemented", "instructions": ["movn", "movz", "movk"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Immediate", "class": "Bitfield", "status": "implemented", "instructions": ["sbfm", "bfm", "ubfm"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Immediate", "class": "Extract", "status": "implemented", "instructions": ["extr"], "tests": ["decode_check", "integer_oracle"] },

    { "group": "Branches, Exception Generating and System", "class": "Conditional branch (immediate)", "status": "implemented", "instructions": ["b.cond"], "notes": "BC.cond (FEAT_HBC) is undef", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Branches, Exception Generating and System", "class": "Exception generation", "status": "implemented", "instructions": ["svc", "hvc", "brk", "hlt"], "exceptions": "SVC EC 0x15; HVC is PSCI/SMCCC (P4.4); SMC undef (no EL3); BRK EC 0x3C; HLT, DCPS1-3 undef outside Debug state; TCANCEL undef (FEAT_TME)", "tests": ["decode_check", "platform_probe"] },
    { "group": "Branches, Exception Generating and System", "class": "System instructions with register argument", "status": "undef", "feature": "FEAT_WFxT", "tests": ["decode_check"] },
    { "group": "Branches, Exception Generating and System", "class": "Hints", "status": "implemented", "instructions": ["nop", "yield", "wfe", "wfi", "sev", "sevl"], "notes": "every other HINT #0-#127 (ESB, PSB, CSDB, PACIASP, AUTIASP, BTI, XPACLRI, ...) is a NOP", "tests": ["decode_check"] },
    { "group": "Branches, Exception Generating and System", "class": "Barriers", "status": "implemented", "instructions": ["clrex", "dsb", "dmb", "isb"], "notes": "every CRm is a full barrier; SB (FEAT_SB), DSB nXS (FEAT_XS), TCOMMIT (FEAT_TME) undef", "tests": ["decode_check"] },
    { "group": "Branches, Exception Generating and System", "class": "PSTATE", "status": "implemented", "instructions": ["msr (immediate)"], "notes": "SPSel, DAIFSet, DAIFClr; UAO, PAN, DIT, SSBS, TCO, SVCR, ALLINT undef (not in v1)", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Branches, Exception Generating and System", "class": "System instructions", "status": "implemented", "instructions": ["sys", "sysl"], "notes": "DC, IC, AT, TLBI (P3); SYSL has no v1 operation and undefs; unlisted SYS operations undef", "tests": ["decode_check", "kvm-unit-tests"] },
    { "group": "Branches, Exception Generating and System", "class": "System register move", "status": "implemented", "instructions": ["mrs", "msr (register)"], "exceptions": "EL0 traps by SCTLR_EL1.UCT/UCI/DZE/UMA and CNTKCTL_EL1 (EC 0x18); unlisted registers undef; the ID space: id-space", "tests": ["decode_check", "integer_oracle", "id_registers"] },
    { "group": "Branches, Exception Generating and System", "class": "System register move (ID space, op0=3 op1=0 CRn=0 CRm=1-7 unallocated)", "status": "id-space", "tests": ["id_registers", "cpu_contract"] },
    { "group": "Branches, Exception Generating and System", "class": "System pair instructions, 128-bit system register move", "status": "undef", "feature": "FEAT_SYSINSTR128, FEAT_SYSREG128", "tests": ["decode_check"] },
    { "group": "Branches, Exception Generating and System", "class": "Unconditional branch (register)", "status": "implemented", "instructions": ["br", "blr", "ret", "eret"], "notes": "BRAA/RETAA and the other PAuth forms undef (FEAT_PAuth); DRPS undefs outside Debug state", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Branches, Exception Generating and System", "class": "Unconditional branch (immediate)", "status": "implemented", "instructions": ["b", "bl"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Branches, Exception Generating and System", "class": "Compare and branch (immediate)", "status": "implemented", "instructions": ["cbz", "cbnz"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Branches, Exception Generating and System", "class": "Test and branch (immediate)", "status": "implemented", "instructions": ["tbz", "tbnz"], "tests": ["decode_check", "integer_oracle"] },

    { "group": "Loads and Stores", "class": "Compare and swap pair, LSE atomics, LDAPR, LDAPUR/STLUR, RCPC3, LSE128, GCS, MOPS, LD64B", "status": "undef", "feature": "FEAT_LSE, FEAT_LRCPC, FEAT_LRCPC2, FEAT_LRCPC3, FEAT_LSE128, FEAT_GCS, FEAT_MOPS, FEAT_LS64", "tests": ["decode_check"] },
    { "group": "Loads and Stores", "class": "Load/store exclusive pair, register; load-acquire/store-release", "status": "implemented", "instructions": ["stxr", "ldxr", "stlxr", "ldaxr", "stxp", "ldxp", "stlxp", "ldaxp", "stlr", "ldar"], "exceptions": "alignment fault (EC 0x24/0x25, FSC 0x21) when unaligned; LDLAR/STLLR undef (FEAT_LOR); CAS undef (FEAT_LSE)", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Loads and Stores", "class": "Load register (literal)", "status": "implemented", "instructions": ["ldr", "ldrsw", "prfm", "ldr (SIMD&FP)"], "tests": ["decode_check", "integer_oracle", "simd_oracle"] },
    { "group": "Loads and Stores", "class": "Load/store no-allocate pair (offset)", "status": "implemented", "instructions": ["stnp", "ldnp"], "tests": ["decode_check", "integer_oracle", "simd_oracle"] },
    { "group": "Loads and Stores", "class": "Load/store register pair (post-indexed, offset, pre-indexed)", "status": "implemented", "instructions": ["stp", "ldp", "ldpsw"], "notes": "STGP undef (FEAT_MTE)", "tests": ["decode_check", "integer_oracle", "simd_oracle"] },
    { "group": "Loads and Stores", "class": "Load/store register (unscaled immediate, immediate post-indexed, unprivileged, immediate pre-indexed, register offset, unsigned immediate)", "status": "implemented", "instructions": ["str*", "ldr*", "stur*", "ldur*", "sttr*", "ldtr*", "prfm", "prfum"], "notes": "SIMD&FP B/H/S/D/Q; no unprivileged SIMD&FP form", "exceptions": "data abort (EC 0x24/0x25), SP alignment (EC 0x26); a fault writes nothing", "tests": ["decode_check", "integer_oracle", "simd_oracle"] },
    { "group": "Loads and Stores", "class": "Atomic memory operations, load/store register (pac)", "status": "undef", "feature": "FEAT_LSE, FEAT_PAuth", "tests": ["decode_check"] },
    { "group": "Loads and Stores", "class": "AdvSIMD load/store multiple structures (and post-indexed)", "status": "implemented", "instructions": ["ld1", "ld2", "ld3", "ld4", "st1", "st2", "st3", "st4"], "tests": ["decode_check", "simd_oracle", "native_oracle"] },
    { "group": "Loads and Stores", "class": "AdvSIMD load/store single structure (and post-indexed)", "status": "implemented", "instructions": ["ld1", "ld2", "ld3", "ld4", "st1", "st2", "st3", "st4", "ld1r", "ld2r", "ld3r", "ld4r"], "tests": ["decode_check", "simd_oracle", "native_oracle"] },
    { "group": "Loads and Stores", "class": "Load/store memory tags", "status": "undef", "feature": "FEAT_MTE", "tests": ["decode_check"] },

    { "group": "Data Processing -- Register", "class": "Data-processing (2 source)", "status": "implemented", "instructions": ["udiv", "sdiv", "lslv", "lsrv", "asrv", "rorv", "crc32b", "crc32h", "crc32w", "crc32x", "crc32cb", "crc32ch", "crc32cw", "crc32cx"], "notes": "SUBP/IRG/GMI (FEAT_MTE), PACGA (FEAT_PAuth), SMAX/UMIN... (FEAT_CSSC) undef", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Register", "class": "Data-processing (1 source)", "status": "implemented", "instructions": ["rbit", "rev16", "rev32", "rev", "clz", "cls"], "notes": "PAC*/AUT*/XPAC* (FEAT_PAuth), ABS/CNT/CTZ (FEAT_CSSC) undef", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Register", "class": "Logical (shifted register)", "status": "implemented", "instructions": ["and", "bic", "orr", "orn", "eor", "eon", "ands", "bics"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Register", "class": "Add/subtract (shifted register), (extended register), (with carry)", "status": "implemented", "instructions": ["add", "adds", "sub", "subs", "adc", "adcs", "sbc", "sbcs"], "notes": "RMIF, SETF8/16 undef (FEAT_FlagM)", "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Register", "class": "Conditional compare (register), (immediate); conditional select", "status": "implemented", "instructions": ["ccmn", "ccmp", "csel", "csinc", "csinv", "csneg"], "tests": ["decode_check", "integer_oracle"] },
    { "group": "Data Processing -- Register", "class": "Data-processing (3 source)", "status": "implemented", "instructions": ["madd", "msub", "smaddl", "smsubl", "smulh", "umaddl", "umsubl", "umulh"], "tests": ["decode_check", "integer_oracle"] },

    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Cryptographic AES", "status": "implemented", "instructions": ["aese", "aesd", "aesmc", "aesimc"], "feature": "FEAT_AES", "tests": ["decode_check", "crypto_oracle", "native_oracle"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Cryptographic three-register SHA, two-register SHA", "status": "implemented", "instructions": ["sha1c", "sha1p", "sha1m", "sha1su0", "sha256h", "sha256h2", "sha256su1", "sha1h", "sha1su1", "sha256su0"], "feature": "FEAT_SHA1, FEAT_SHA256", "tests": ["decode_check", "crypto_oracle", "native_oracle"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Cryptographic three-register imm2, three-register SHA512, four-register, two-register SHA512, XAR", "status": "undef", "feature": "FEAT_SM3, FEAT_SHA512, FEAT_SHA3", "tests": ["decode_check"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "AdvSIMD scalar copy, scalar pairwise, scalar three different, scalar three same, scalar two-register miscellaneous, scalar shift by immediate, scalar x indexed element", "status": "implemented", "tests": ["decode_check", "simd_oracle", "native_oracle"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "AdvSIMD table lookup, permute, extract, copy, three different, three same, two-register miscellaneous, across lanes, modified immediate, shift by immediate, vector x indexed element", "status": "implemented", "notes": "PMULL 1Q (FEAT_PMULL) included", "tests": ["decode_check", "simd_oracle", "native_oracle"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "AdvSIMD (scalar) three same FP16, two-register miscellaneous FP16, three same extra, three-register extension; FMOV (vector, half); FP16 forms of the FP classes", "status": "undef", "feature": "FEAT_FP16, FEAT_RDM, FEAT_DotProd, FEAT_FCMA, FEAT_FHM, FEAT_I8MM, FEAT_BF16", "tests": ["decode_check"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Conversion between floating-point and fixed-point, and integer", "status": "implemented", "instructions": ["scvtf", "ucvtf", "fcvtzs", "fcvtzu", "fcvtns", "fcvtnu", "fcvtas", "fcvtau", "fcvtps", "fcvtpu", "fcvtms", "fcvtmu", "fmov"], "notes": "FJCVTZS (FEAT_JSCVT) undef", "tests": ["decode_check", "fp_oracle", "native_oracle", "float_ref"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Floating-point data-processing (1 source)", "status": "implemented", "instructions": ["fmov", "fabs", "fneg", "fsqrt", "fcvt", "frintn", "frintp", "frintm", "frintz", "frinta", "frintx", "frinti"], "notes": "FRINT32/64 (FEAT_FRINTTS), BFCVT (FEAT_BF16) undef; half precision only as FCVT's source", "tests": ["decode_check", "fp_oracle", "native_oracle", "float_ref"] },
    { "group": "Data Processing -- Scalar FP and AdvSIMD", "class": "Floating-point compare, immediate, conditional compare, data-processing (2 source), conditional select, data-processing (3 source)", "status": "implemented", "instructions": ["fcmp", "fcmpe", "fmov", "fccmp", "fccmpe", "fmul", "fdiv", "fadd", "fsub", "fmax", "fmin", "fmaxnm", "fminnm", "fnmul", "fcsel", "fmadd", "fmsub", "fnmadd", "fnmsub"], "notes": "the zero forms of FCMP/FCMPE ignore Rm (should-be-zero), as QEMU does", "tests": ["decode_check", "fp_oracle", "native_oracle", "float_ref"] }
  ]
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/a64/extended_memory.mjs                                                            0000644 0000000 0000000 00000032302 00000000000 015323  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The ARM core's extended RAM (docs/arm64-virt-android16-plan.md P8.5;
// src/rust/aarch64/extended.rs): 64 MiB of RAM and 8 MiB of extended RAM at
// 4 GiB, cached in 1 MiB of frames, so that most accesses page. The bus's
// view of it (a hole after it, accesses of each width, across pages, Q
// registers), eviction under a pattern over all of it, the DMA facade
// (blobs across pages, scalars), the device tree's second memory range,
// code at 4 GiB (through an identity map: the page tier needs the MMU on),
// rewritten by DMA after its frame was evicted, run again (interpreter and
// page tier: the page tier compiles it from extended RAM, the DMA write
// retires it), a walk storing to and loading from 512 pages of it through
// the 256 frames (the page tier's access cache holds frames, released at
// the run loop's safe points, P9.2), a single-buffer snapshot
// refused, a snapshot stream restored into another machine, power-on
// clearing it.
//
//   node tests/a64/extended_memory.mjs   (A64_WASM: the core, default build/v86-arm64.wasm)
//   (A64_VERBOSE=1: the page tier's statistics)
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { virt_tree } from "../../src/virt/dtb.js";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const MiB = 1 << 20, EXT = 2 ** 32, EXTENDED = 8 * MiB;
const RAM = 0x40000000;
const options = jit => ({
    cpu_type: "arm64", graphics_adapter: "none", memory_size: 64 * MiB, autostart: false, log_level: 0,
    extended_memory_size: EXTENDED, extended_memory_cache: MiB,
    wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
    ...(jit ? { jit_switches: { a64_page: 1 }, ir_sync_publication: true } : {}),
});
const start = async jit => {
    const emulator = new V86(options(jit));
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
};
const split = pa => [pa >>> 0, Math.floor(pa / 2 ** 32)];
// (a pattern word of each 8 bytes of extended RAM)
const pattern = pa => BigInt.asUintN(64, BigInt(pa) * 0x9E3779B97F4A7C15n);

// the bootstrap in RAM at BOOT (assembled here): the MMU on with an identity
// map of 1 GiB blocks at TABLE (RAM's first GiB, extended RAM's), then to the program
const BOOT = RAM + 0x1000, TABLE = RAM + 0x100000;
const directory = root + "build/a64-extended/";
fs.mkdirSync(directory, { recursive: true });
fs.writeFileSync(directory + "boot.S", `.global start
start:
    movz x0, #0xFF
    msr mair_el1, x0
    ldr x0, =0x200803519
    msr tcr_el1, x0
    ldr x0, =${TABLE}
    msr ttbr0_el1, x0
    isb
    mrs x0, sctlr_el1
    orr x0, x0, #1
    msr sctlr_el1, x0
    isb
    ldr x0, =${EXT + 0x10000}
    br x0
.ltorg
`);
// the walk at 4 GiB + CODE: three rounds of a store of page + round to a
// word of each of the 512 pages from 4 GiB + 1 MiB, then their loads, summed
// into RAM's first word, then 0xD0E after it, then a loop on itself
fs.writeFileSync(directory + "walk.S", `.global walk
walk:
    mov x2, #0
    mov x7, #0
    ldr x0, =${EXT + MiB}
1:  mov x3, #0
2:  add x4, x3, x2
    and x6, x3, #511
    lsl x5, x3, #12
    add x5, x5, x6, lsl #3
    str x4, [x0, x5]
    add x3, x3, #1
    cmp x3, #512
    b.ne 2b
    mov x3, #0
3:  and x6, x3, #511
    lsl x5, x3, #12
    add x5, x5, x6, lsl #3
    ldr x4, [x0, x5]
    add x7, x7, x4
    add x3, x3, #1
    cmp x3, #512
    b.ne 3b
    add x2, x2, #1
    cmp x2, #3
    b.ne 1b
    ldr x8, =${RAM}
    str w7, [x8]
    mov w9, #0xD0E
    str w9, [x8, #4]
4:  b 4b
.ltorg
`);
const WALK_SUM = 3 * (511 * 512 / 2) + 512 * (0 + 1 + 2);
const host = spawnSync("rustc", ["-vV"], { encoding: "utf8" }).stdout.match(/^host: (.*)$/m)[1];
const lld = process.env.LD_LLD || `${spawnSync("rustc", ["--print", "sysroot"], { encoding: "utf8" }).stdout.trim()}/lib/rustlib/${host}/bin/rust-lld`;
for(const [program, args] of [[process.env.CLANG || "clang", ["--target=aarch64-none-elf", "-c", "-o", directory + "boot.o", directory + "boot.S"]],
    [lld, ["-flavor", "gnu", "-m", "aarch64elf", "-static", "-e", "start", "-Ttext=" + BOOT.toString(16), "--oformat=binary", "-o", directory + "boot.bin", directory + "boot.o"]],
    [process.env.CLANG || "clang", ["--target=aarch64-none-elf", "-c", "-o", directory + "walk.o", directory + "walk.S"]],
    [lld, ["-flavor", "gnu", "-m", "aarch64elf", "-static", "-e", "walk", "-Ttext=" + (EXT + 0x10000).toString(16), "--oformat=binary", "-o", directory + "walk.bin", directory + "walk.o"]]])
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, program + ": " + result.stderr);
}
const boot_code = fs.readFileSync(directory + "boot.bin");
const walk_code = fs.readFileSync(directory + "walk.bin");
const table = new Uint8Array(4096);
for(const block of [RAM, EXT]) new DataView(table.buffer).setBigUint64(8 * (block / 2 ** 30), BigInt(block) | 0x701n, true);

// the program at 4 GiB + CODE: 20000 times a constant stored to RAM, then
// 0xD0E after it, then a loop on itself
const CODE = 0x10000;
const LOOP_VALUE = 1;
const program = value => [0xD2A80002, 0x5289C404, 0x52800001 | value << 5, 0xB9000041, 0x71000484, 0x54FFFFA1, 0x5281A1C5, 0xB9000445, 0x14000000];
const code_bytes = value => new Uint8Array(new Uint32Array(program(value)).buffer);
const run_program = (cpu, what) => {
    cpu.mem8.fill(0, 0, 8);
    cpu.write_blob_physical(boot_code, BOOT);
    cpu.write_blob_physical(table, TABLE);
    cpu.boot(BOOT, 0);
    const deadline = performance.now() + 60000;
    const word = i => cpu.mem8[4 * i] | cpu.mem8[4 * i + 1] << 8 | cpu.mem8[4 * i + 2] << 16 | cpu.mem8[4 * i + 3] << 24;
    while(word(1) !== 0xD0E)
    {
        assert.ok(performance.now() < deadline, what + ": the program did not finish, PC " + cpu.read_pc());
        cpu.run_cores();
    }
    return word(0);
};

const stats = [];
for(const jit of [false, true])
{
    const emulator = await start(jit);
    const cpu = emulator.v86.cpu;
    const e = cpu.wm.exports;
    const mode = jit ? "page tier" : "interpreter";
    try
    {
        const kind = pa => e.a64_bus_lookup(...split(pa));
        const read = (pa, width) => { const v = e.a64_bus_read(...split(pa), width); assert.equal(e.a64_bus_status(), 0, "read " + pa.toString(16)); return BigInt.asUintN(64, v); };
        const write = (pa, width, value) => assert.equal(e.a64_bus_write(...split(pa), width, BigInt(value)), 0, "write " + pa.toString(16));
        assert.equal(kind(EXT), 4);
        assert.equal(e.a64_bus_lookup_detail(...split(EXT + 5 * 4096 + 12)), 5);
        assert.equal(kind(EXT + EXTENDED), 0, "a hole after extended RAM");
        assert.equal(kind(EXT - 1), 0, "a hole before it");
        assert.equal(cpu.dma_classify(EXT + 4000, 200), -1, "the DMA facade: extended RAM, not one backing");
        assert.equal(cpu.dma_classify(EXT + EXTENDED - 8, 16), -2, "past its end");
        // (what virtio checks of a virtqueue or a buffer before its DMA)
        cpu.validate_physical_range(EXT + 4000, 200);
        assert.throws(() => cpu.validate_physical_range(EXT + EXTENDED - 8, 16), RangeError, "validated: past its end");

        // each width; an 8-byte access across a page
        write(EXT + 0x1001, 1, 0xAB);
        write(EXT + 0x1002, 2, 0xCDEF);
        write(EXT + 0x1004, 4, 0x12345678);
        write(EXT + 0x1FFC, 8, 0x1122334455667788n);
        assert.equal(read(EXT + 0x1000, 8), 0x12345678CDEFAB00n);
        assert.equal(read(EXT + 0x1FFC, 8), 0x1122334455667788n);
        assert.equal(read(EXT + 0x2000, 4), 0x11223344n);

        // a pattern over all of it: 8192 frames' worth through 256 frames
        for(let pa = EXT; pa < EXT + EXTENDED; pa += 512) write(pa, 8, pattern(pa));
        for(let pa = EXT; pa < EXT + EXTENDED; pa += 512) assert.equal(read(pa, 8), pattern(pa), "the pattern at " + pa.toString(16));
        assert.ok(e.a64_ext_stat(3) > EXTENDED / 4096, "frames reused: " + e.a64_ext_stat(3));

        // DMA: a blob across pages, scalars
        const blob = Uint8Array.from({ length: 10000 }, (_, i) => i * 7 + 3);
        cpu.write_blob_physical(blob, EXT + 3 * MiB + 1234);
        assert.deepEqual(cpu.read_blob_physical(EXT + 3 * MiB + 1234, 10000), blob);
        cpu.write32_physical(EXT + 4 * MiB - 2, 0xA1B2C3D4);
        assert.equal(cpu.read32_physical(EXT + 4 * MiB - 2), 0xA1B2C3D4);
        assert.equal(cpu.read16_physical(EXT + 4 * MiB), 0xA1B2);
        assert.equal(read(EXT + 4 * MiB - 2, 4), 0xA1B2C3D4n, "the core sees the DMA write");
        assert.throws(() => cpu.read_blob_physical(EXT + EXTENDED - 4, 8), RangeError);

        // code from extended RAM, rewritten by DMA after its frame went
        cpu.write_blob_physical(code_bytes(LOOP_VALUE), EXT + CODE);
        assert.equal(run_program(cpu, mode), LOOP_VALUE, mode + ": the program at 4 GiB");
        for(let pa = EXT + MiB; pa < EXT + 3 * MiB; pa += 4096) read(pa, 8);
        cpu.write_blob_physical(code_bytes(0x777), EXT + CODE);
        assert.equal(run_program(cpu, mode), 0x777, mode + ": the program after its rewrite");
        const fetched = e.a64_ext_stat(16), compiled = e.a64_ext_stat(17), retired = e.a64_ext_stat(15);
        if(+process.env.A64_VERBOSE) console.log(mode, JSON.stringify(cpu.page_tier_stats()));
        if(jit)
        {
            assert.ok(compiled > 50000, "the page tier ran the loop from extended RAM: " + compiled);
            assert.ok(retired >= 1, "the DMA write retired its code: " + retired);
        }
        else
        {
            assert.ok(fetched > 100000 && compiled === 0, "interpreted from extended RAM: " + [fetched, compiled]);
        }
        stats.push(Array.from({ length: 18 }, (_, i) => e.a64_ext_stat(i)));

        // the walk: compiled loads and stores to 512 pages through 256 frames
        const releases = e.a64_ext_stat(8);
        cpu.write_blob_physical(walk_code, EXT + CODE);
        assert.equal(run_program(cpu, mode + " walk"), WALK_SUM, mode + ": the walk's sum");
        for(let page = 0; page < 512; page += 37)
        {
            assert.equal(read(EXT + MiB + page * 4096 + page * 8, 8), BigInt(page + 2), "the walk's last store to page " + page);
        }
        if(jit)
        {
            assert.ok(e.a64_ext_stat(8) > releases, "the access caches' frames were released: " + (e.a64_ext_stat(8) - releases));
        }
        // (V86.get_instruction_counter, the demo page's speed: the instructions the ARM core retired)
        assert.ok(emulator.get_instruction_counter() > 100000, "get_instruction_counter: " + emulator.get_instruction_counter());
        // (the program again, for the snapshot below)
        cpu.write_blob_physical(code_bytes(0x777), EXT + CODE);

        if(jit)
        {
            // a single-buffer snapshot does not hold extended RAM; a stream does
            await assert.rejects(emulator.save_state(), /save_state_stream/);
            const chunks = [];
            await emulator.save_state_stream(chunk => { chunks.push(chunk.slice()); });
            const snapshot = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
            let at = 0;
            for(const chunk of chunks) { snapshot.set(chunk, at); at += chunk.length; }
            const second = await start(true);
            try
            {
                await second.restore_state_stream({ size: snapshot.length, read: async (offset, length) => snapshot.subarray(offset, offset + length) });
                const c = second.v86.cpu;
                assert.deepEqual(c.read_blob_physical(EXT + 3 * MiB + 1234, 10000), blob, "the restored DMA blob");
                for(let pa = EXT + 5 * MiB; pa < EXT + EXTENDED; pa += 512) assert.equal(BigInt.asUintN(64, c.wm.exports.a64_bus_read(...split(pa), 8)), pattern(pa));
                assert.equal(run_program(c, "restored"), 0x777, "the restored program");
                console.log(`PASS snapshot stream: ${(snapshot.length / MiB).toFixed(1)} MiB restored into another machine`);
            }
            finally
            {
                await second.destroy();
            }
            // power-on: extended RAM reads as zero again
            cpu.reboot_internal("power-on");
            assert.equal(read(EXT + 0x1FFC, 8), 0n, "power-on cleared extended RAM");
            assert.equal(read(EXT + 7 * MiB, 8), 0n);
        }
        console.log(`PASS ${mode}: hits ${stats.at(-1)[0]}, loads ${stats.at(-1)[1]}, write-backs ${stats.at(-1)[2]}, ` +
            `evictions ${stats.at(-1)[3]}, code retired by writes ${retired}, instructions fetched ${fetched}, compiled ${compiled}`);
    }
    finally
    {
        await emulator.destroy();
    }
}

// the device tree's second memory range
{
    const tree = virt_tree({ cores: 1, memory_size: 64 * MiB, extended: { base: EXT, size: 6 * 2 ** 30 } });
    const memory = tree.children.filter(n => n.name.startsWith("memory@"));
    assert.deepEqual(memory.map(n => n.name), ["memory@40000000", "memory@100000000"]);
    assert.deepEqual(memory[1].props.find(([name]) => name === "reg")[1], [1, 0, 1, 0x80000000]);
    console.log("PASS the device tree's memory@100000000");
}
console.log("A64_EXTENDED_MEMORY_PASS");
                                                                                                                                                                                                                                                                                                                              source/v64/tests/a64/float_ref.mjs                                                                  0000644 0000000 0000000 00000003515 00000000000 014100  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// QEMU's float_convs and float_madds (tests/tcg/multiarch, built from the
// fixed QEMU source tree as bare-metal guests, -O0 as QEMU builds them)
// against tests/tcg/aarch64/*.ref (docs/arm64-virt-android16-plan.md P0.5).
// The sources and references stay in the QEMU tree (A64_QEMU_SRC, default
// build/a64-ref/qemu-9.2.0); A64_TARGET=qemu|v86 picks the machine.
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, root, target } from "./guest_runner.mjs";

const source = process.env.A64_QEMU_SRC || root + "build/a64-ref/qemu-9.2.0/";
const multiarch = source + "tests/tcg/multiarch/";
assert.ok(fs.existsSync(multiarch + "float_convs.c"), "no QEMU source tree at " + source + " (P0.11)");
const machine = target();
let failed = 0;
for(const test of ["float_convs", "float_madds"])
{
    const directory = build(test.replace("_", "-"), [multiarch + test + ".c", multiarch + "libs/float_helpers.c"],
        { optimize: "-O0", cflags: ["-I", multiarch, "-fno-strict-aliasing"] });
    const result = await machine.run(directory);
    fs.writeFileSync(directory + machine.name + ".out", result.text);
    const expected = fs.readFileSync(source + `tests/tcg/aarch64/${test}.ref`, "latin1");
    if(result.status !== "ok" || result.text !== expected)
    {
        failed++;
        const lines = result.text.split("\n"), wanted = expected.split("\n");
        const first = lines.findIndex((line, i) => line !== wanted[i]);
        console.log(`${test}: ${result.status}, ${lines.length} lines (expected ${wanted.length}); first difference at line ${first + 1}:\n` +
            `  got:      ${lines[first]}\n  expected: ${wanted[first]}`);
    }
    else
    {
        console.log(`${test}: ${machine.name} matches ${test}.ref (${expected.split("\n").length - 1} lines)`);
    }
}
process.exit(failed ? 1 : 0);
                                                                                                                                                                                   source/v64/tests/a64/fma.c                                                                          0000644 0000000 0000000 00000006577 00000000000 012346  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A hot loop of scalar multiply-adds, divisions and the rest of the FP fast
// path's forms, and one of vector FMLA and FMLS (tests/a64/fma.mjs): FPSR.IXC
// set first, ordinary values; the results' bits and FPSR at the end
#include <a64.h>
#include <stdio.h>
#include <stdint.h>

static double run_double(int rounds)
{
    // (bounded: every value stays between 0.25 and 2)
    double a = 1.0000001, b = 0.9999997, h = 0.5, s = 0.0;
    for(int i = 0; i < rounds; i++)
    {
        double t, u, v, w;
        __asm__ volatile("fmadd %d0, %d1, %d2, %d3" : "=w"(t) : "w"(s), "w"(h), "w"(a));
        __asm__ volatile("fmsub %d0, %d1, %d2, %d3" : "=w"(u) : "w"(t), "w"(h), "w"(a));
        __asm__ volatile("fnmadd %d0, %d1, %d2, %d3" : "=w"(v) : "w"(u), "w"(h), "w"(b));
        __asm__ volatile("fnmsub %d0, %d1, %d2, %d3" : "=w"(w) : "w"(v), "w"(h), "w"(b));
        s = w / 1.0001 + a * 0.5 - b * 0.25;
        a = a * 1.0000003;
    }
    return s;
}
static float run_single(int rounds)
{
    float a = 1.25f, b = 0.75f, s = 1.0f;
    for(int i = 0; i < rounds; i++)
    {
        float t;
        __asm__ volatile("fmadd %s0, %s1, %s2, %s3" : "=w"(t) : "w"(a), "w"(b), "w"(s));
        s = t / 1.001f - b * 0.125f;
    }
    return s;
}

// FMLA and FMLS on 4S, 2S and 2D vectors (bounded: acc -> 1.2 c)
typedef float f32x4 __attribute__((vector_size(16)));
typedef float f32x2 __attribute__((vector_size(8)));
typedef double f64x2 __attribute__((vector_size(16)));
static f32x4 acc4;
static f32x2 acc2;
static f64x2 accd;
static void run_vector(int rounds)
{
    f32x4 c4 = { 1.1f, 2.2f, 3.3f, 1.7f }, h4 = { 0.5f, 0.5f, 0.5f, 0.5f }, q4 = { 0.25f, 0.25f, 0.25f, 0.25f };
    f32x2 c2 = { 1.9f, 0.7f }, h2 = { 0.5f, 0.5f }, q2 = { 0.25f, 0.25f };
    f64x2 cd = { 1.3, 2.9 }, hd = { 0.5, 0.5 }, qd = { 0.25, 0.25 };
    f32x4 a4 = c4;
    f32x2 a2 = c2;
    f64x2 ad = cd;
    for(int i = 0; i < rounds; i++)
    {
        f32x4 t4 = c4, u4;
        __asm__ volatile("fmla %0.4s, %1.4s, %2.4s" : "+w"(t4) : "w"(a4), "w"(h4));
        u4 = t4;
        __asm__ volatile("fmls %0.4s, %1.4s, %2.4s" : "+w"(u4) : "w"(t4), "w"(q4));
        a4 = u4;
        f32x2 t2 = c2, u2;
        __asm__ volatile("fmla %0.2s, %1.2s, %2.2s" : "+w"(t2) : "w"(a2), "w"(h2));
        u2 = t2;
        __asm__ volatile("fmls %0.2s, %1.2s, %2.2s" : "+w"(u2) : "w"(t2), "w"(q2));
        a2 = u2;
        f64x2 td = cd, ud;
        __asm__ volatile("fmla %0.2d, %1.2d, %2.2d" : "+w"(td) : "w"(ad), "w"(hd));
        ud = td;
        __asm__ volatile("fmls %0.2d, %1.2d, %2.2d" : "+w"(ud) : "w"(td), "w"(qd));
        ad = ud;
    }
    acc4 = a4;
    acc2 = a2;
    accd = ad;
}

int main(int argc, char **argv)
{
    __asm__ volatile("msr fpsr, %0" :: "r"(1UL << 4));
    double d = run_double(ROUNDS);
    float f = run_single(ROUNDS);
    run_vector(ROUNDS);
    uint64_t fpsr, dbits;
    uint32_t fbits;
    __asm__ volatile("mrs %0, fpsr" : "=r"(fpsr));
    __builtin_memcpy(&dbits, &d, 8);
    __builtin_memcpy(&fbits, &f, 4);
    uint32_t v4[4], v2[2];
    uint64_t vd[2];
    __builtin_memcpy(v4, &acc4, 16);
    __builtin_memcpy(v2, &acc2, 8);
    __builtin_memcpy(vd, &accd, 16);
    printf("double %016lx single %08x fpsr %lx\n", (unsigned long)dbits, fbits, (unsigned long)fpsr);
    printf("4s %08x %08x %08x %08x 2s %08x %08x 2d %016lx %016lx\n", v4[0], v4[1], v4[2], v4[3], v2[0], v2[1],
        (unsigned long)vd[0], (unsigned long)vd[1]);
    return 0;
}
                                                                                                                                 source/v64/tests/a64/fma.mjs                                                                        0000644 0000000 0000000 00000003554 00000000000 012705  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 page tier's FP fast path (docs/arm64-virt-android16-plan.md P6,
// "A64 JIT 的语义红线"; J2): a hot loop of the four scalar multiply-adds,
// divisions, multiplications and additions, and of vector FMLA and FMLS (4S,
// 2S, 2D), with FPSR.IXC set (tests/a64/fma.c)
// gives the same bits and FPSR on QEMU, the interpreter, and the page tier
// with a64_relaxed_fma off and on; where the host fuses relaxed SIMD's
// multiply-adds, the compiled loop calls no helper (SoftFloat) at all.
import assert from "node:assert/strict";
import { build, reference, actual } from "./guest_runner.mjs";

process.env.A64_MMU = "1";
const ROUNDS = 20000;
const directory = build("fma", [new URL("fma.c", import.meta.url).pathname], { cflags: [`-DROUNDS=${ROUNDS}`] });
const line = result => {
    assert.equal(result.status, "ok", result.text);
    return result.text.trim();
};
const expected = line(await reference(directory));
delete process.env.A64_JIT;
assert.equal(line(await actual(directory)), expected, "the interpreter against QEMU");
process.env.A64_JIT = "1";
for(const fma of [0, 1])
{
    process.env.A64_JIT_SWITCHES = `a64_relaxed_fma=${fma}`;
    let result;
    try
    {
        result = await actual(directory);
    }
    catch(e)
    {
        // (a host that does not fuse refuses a64_relaxed_fma=1)
        if(fma && /cannot be 1/.test(String(e))) { console.log("fma: the host does not fuse relaxed multiply-adds"); continue; }
        throw e;
    }
    assert.equal(line(result), expected, `the page tier with a64_relaxed_fma=${fma} against QEMU`);
    const t = result.page_tier;
    console.log(`a64_relaxed_fma=${fma}: ${t.retired} native instructions, ${t.helpers} helper calls`);
    if(fma) assert.ok(t.helpers < 100, `the fused loop calls the SoftFloat helpers ${t.helpers} times`);
}
console.log(`fma: ${expected.replace(/\n/g, "; ")}; passed`);
                                                                                                                                                    source/v64/tests/a64/fp_oracle.mjs                                                                  0000644 0000000 0000000 00000001635 00000000000 014072  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Scalar FP against QEMU (docs/arm64-virt-android16-plan.md P2.6: results and
// FPSR bit for bit under all 16 combinations of RMode, FZ and DN; AHP random).
// Each mnemonic's cases cycle through the combinations (tests/a64/vector_oracle.mjs
// makes and runs the cases).
//
//   node tests/a64/fp_oracle.mjs [--cases N] [--seed S] [--filter class|mnemonic]
import { options, run } from "./vector_oracle.mjs";

const FP = ["fp_fixed", "fp_int", "fp_dp1", "fp_compare", "fp_imm", "fp_cond_compare", "fp_dp2", "fp_cond_select", "fp_dp3"];
// (the round-th case of a mnemonic: combination round mod 16 of RMode, FZ, DN; AHP from the next bit)
const fpcr = (n, r) => BigInt(r & 3) << 22n | BigInt(r >> 2 & 1) << 24n | BigInt(r >> 3 & 1) << 25n | BigInt(r >> 4 & 1) << 26n;
const { differences } = await run({ name: "fp", classes: FP, fpcr, ...options({ cases: 4800 }) });
process.exit(differences ? 1 : 0);
                                                                                                   source/v64/tests/a64/fscrypt_test.c                                                                 0000644 0000000 0000000 00000016447 00000000000 014331  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* f2fs with fscrypt across a reboot (docs/arm64-virt-android16-plan.md P9.2;
 * Android's file-based encryption): "setup" adds a 64-byte key to the
 * filesystem, sets a v2 policy (AES-256-XTS contents, AES-256-CTS names) on
 * an empty directory and writes two files into it, one in a subdirectory;
 * the caller unmounts and reboots. "verify", after the reboot, without the
 * key: the policy is there, the key absent, the names encrypted and the
 * files refuse to open (ENOKEY); then the same key added again: its
 * identifier the policy's, the names and the contents back. Built by
 * tools/a64_kernel.mjs.
 *
 *   fscrypt_test setup|verify <mount>
 *
 * A64_FSCRYPT_SETUP id=<identifier> and A64_FSCRYPT_OK id=<identifier> ...
 * on success, A64_FSCRYPT_FAIL <why> else. */
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/fscrypt.h>

#define SECRET "A64 fscrypt: written before the reboot\n"
#define DEEPER_BYTES (64 * 1024)

static void fail(const char *what)
{
    printf("A64_FSCRYPT_FAIL %s (errno %d)\n", what, errno);
    exit(1);
}

static void hex(char *out, const uint8_t *bytes, int n)
{
    for(int i = 0; i < n; i++) sprintf(out + 2 * i, "%02x", bytes[i]);
}

static void add_key(int fd, uint8_t identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
{
    struct fscrypt_add_key_arg *arg = calloc(1, sizeof(*arg) + 64);
    arg->key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
    arg->raw_size = 64;
    for(int i = 0; i < 64; i++) arg->raw[i] = (uint8_t)(i * 37 + 11);
    if(ioctl(fd, FS_IOC_ADD_ENCRYPTION_KEY, arg) < 0) fail("FS_IOC_ADD_ENCRYPTION_KEY");
    memcpy(identifier, arg->key_spec.u.identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
    free(arg);
}

static uint32_t key_status(int fd, const uint8_t identifier[FSCRYPT_KEY_IDENTIFIER_SIZE])
{
    struct fscrypt_get_key_status_arg arg = { 0 };
    arg.key_spec.type = FSCRYPT_KEY_SPEC_TYPE_IDENTIFIER;
    memcpy(arg.key_spec.u.identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
    if(ioctl(fd, FS_IOC_GET_ENCRYPTION_KEY_STATUS, &arg) < 0) fail("FS_IOC_GET_ENCRYPTION_KEY_STATUS");
    return arg.status;
}

static void write_file(const char *path, const void *data, size_t size)
{
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
    if(fd < 0) fail(path);
    if(write(fd, data, size) != (ssize_t)size) fail("write");
    if(fsync(fd) < 0) fail("fsync");
    close(fd);
}

static size_t read_file(const char *path, void *data, size_t size)
{
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if(fd < 0) fail(path);
    size_t total = 0;
    for(ssize_t n; (n = read(fd, (uint8_t *)data + total, size - total)) > 0;) total += n;
    close(fd);
    return total;
}

static void deeper_contents(uint8_t *bytes)
{
    for(int i = 0; i < DEEPER_BYTES; i++) bytes[i] = (uint8_t)(i * 131 + (i >> 9));
}

/* The entries of `directory` but . and ..: how many, whether one is named `name`; each regular file's open errno in *open_errno */
static int entries(const char *directory, const char *name, int *named, int *open_errno)
{
    DIR *d = opendir(directory);
    if(!d) fail("opendir");
    int count = 0;
    *named = 0;
    *open_errno = 0;
    for(struct dirent *e; (e = readdir(d));)
    {
        if(!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
        count++;
        if(!strcmp(e->d_name, name)) *named = 1;
        if(e->d_type == DT_REG)
        {
            int fd = openat(dirfd(d), e->d_name, O_RDONLY | O_CLOEXEC);
            if(fd >= 0) close(fd);
            *open_errno = fd >= 0 ? 0 : errno;
        }
    }
    closedir(d);
    return count;
}

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    if(argc < 3) fail("usage");
    const char *mount = argv[2];
    char directory[512], path[600], id[2 * FSCRYPT_KEY_IDENTIFIER_SIZE + 1];
    snprintf(directory, sizeof(directory), "%s/enc", mount);
    int root = open(mount, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
    if(root < 0) fail("open the mount");
    static uint8_t deeper[DEEPER_BYTES], back[DEEPER_BYTES + 1];
    deeper_contents(deeper);
    uint8_t identifier[FSCRYPT_KEY_IDENTIFIER_SIZE];
    if(!strcmp(argv[1], "setup"))
    {
        if(mkdir(directory, 0700) < 0) fail("mkdir");
        add_key(root, identifier);
        int dir = open(directory, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
        if(dir < 0) fail("open the directory");
        struct fscrypt_policy_v2 policy = {
            .version = FSCRYPT_POLICY_V2, .contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS,
            .filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS, .flags = FSCRYPT_POLICY_FLAGS_PAD_32,
        };
        memcpy(policy.master_key_identifier, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
        if(ioctl(dir, FS_IOC_SET_ENCRYPTION_POLICY, &policy) < 0) fail("FS_IOC_SET_ENCRYPTION_POLICY");
        close(dir);
        snprintf(path, sizeof(path), "%s/secret.txt", directory);
        write_file(path, SECRET, strlen(SECRET));
        snprintf(path, sizeof(path), "%s/sub", directory);
        if(mkdir(path, 0700) < 0) fail("mkdir sub");
        snprintf(path, sizeof(path), "%s/sub/deeper.bin", directory);
        write_file(path, deeper, DEEPER_BYTES);
        if(syncfs(root) < 0) fail("syncfs");
        hex(id, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
        printf("A64_FSCRYPT_SETUP id=%s\n", id);
        return 0;
    }
    if(strcmp(argv[1], "verify")) fail("usage");
    /* (without the key) */
    struct fscrypt_get_policy_ex_arg got = { .policy_size = sizeof(got.policy) };
    int dir = open(directory, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
    if(dir < 0) fail("open the directory");
    if(ioctl(dir, FS_IOC_GET_ENCRYPTION_POLICY_EX, &got) < 0) fail("FS_IOC_GET_ENCRYPTION_POLICY_EX");
    close(dir);
    if(got.policy.version != FSCRYPT_POLICY_V2 || got.policy.v2.contents_encryption_mode != FSCRYPT_MODE_AES_256_XTS ||
        got.policy.v2.filenames_encryption_mode != FSCRYPT_MODE_AES_256_CTS) fail("the policy");
    if(key_status(root, got.policy.v2.master_key_identifier) != FSCRYPT_KEY_STATUS_ABSENT) fail("the key is not absent");
    int named, open_errno;
    int locked = entries(directory, "secret.txt", &named, &open_errno);
    if(locked != 2 || named) fail("the names without the key");
    if(open_errno != ENOKEY) { errno = open_errno; fail("a file opens without the key"); }
    /* (with the key) */
    add_key(root, identifier);
    if(memcmp(identifier, got.policy.v2.master_key_identifier, FSCRYPT_KEY_IDENTIFIER_SIZE)) fail("the key's identifier");
    if(key_status(root, identifier) != FSCRYPT_KEY_STATUS_PRESENT) fail("the key is not present");
    if(entries(directory, "secret.txt", &named, &open_errno) != 2 || !named || open_errno) fail("the names with the key");
    snprintf(path, sizeof(path), "%s/secret.txt", directory);
    size_t n = read_file(path, back, sizeof(back));
    if(n != strlen(SECRET) || memcmp(back, SECRET, n)) fail("secret.txt's contents");
    snprintf(path, sizeof(path), "%s/sub/deeper.bin", directory);
    n = read_file(path, back, sizeof(back));
    if(n != DEEPER_BYTES || memcmp(back, deeper, n)) fail("deeper.bin's contents");
    hex(id, identifier, FSCRYPT_KEY_IDENTIFIER_SIZE);
    printf("A64_FSCRYPT_OK id=%s locked_entries=%d enokey=1 files=2\n", id, locked);
    return 0;
}
                                                                                                                                                                                                                         source/v64/tests/a64/futex_snapshot.mjs                                                             0000644 0000000 0000000 00000015150 00000000000 015207  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Condition variables across snapshots (docs/aarch64.md's known defects:
// Android stalled after a restore, a thread waiting for good for a task the
// others had finished): tests/a64/android/futex_stress.c, bionic's mutexes
// and condition variables in ping-pong pairs and in ANGLE's worker pool's
// pattern, runs in Alpine's initramfs on v86's cores while this test saves
// and restores the machine in place every few seconds; any group that
// stops making progress for 10 s fails it.
//
//   node tests/a64/futex_snapshot.mjs
//
// A64_CORES (4), A64_PARALLEL (1: cores in vCPU workers), A64_JIT (1: the
// page tier), A64_FUTEX_SECONDS (the stress's run, 120),
// A64_FUTEX_SNAPSHOT_MS (between snapshots, 3000; 0: none),
// A64_FUTEX_SNAPSHOT=inplace (save and restore into this machine, the
// default), fresh (into a new machine each time) or pause (only stopped),
// A64_FUTEX_ARGS (pairs, workers, tasks: "4 4 8"), A64_KERNEL_FILE (another
// Image, e.g. Android's GKI kernel), A64_VERBOSE=1 (the serial console).
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import { spawnSync } from "node:child_process";
import { prepare, ROOT } from "../lib/alpine_image.mjs";

const cores = +(process.env.A64_CORES || 4);
const parallel = !!+(process.env.A64_PARALLEL ?? 1);
const jit = !!+(process.env.A64_JIT ?? 1);
const seconds = +(process.env.A64_FUTEX_SECONDS || 120);
const period = +(process.env.A64_FUTEX_SNAPSHOT_MS ?? 3000);
const mode = process.env.A64_FUTEX_SNAPSHOT || "inplace";
assert.ok(["inplace", "fresh", "pause"].includes(mode), "A64_FUTEX_SNAPSHOT: inplace, fresh or pause");
const verbose = !!+process.env.A64_VERBOSE;

function run(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, `${program} ${args.join(" ")}: ${result.stderr || result.error}`);
    return result.stdout;
}

const prepared = await prepare("aarch64-virt", ["boot/vmlinuz-virt", "boot/initramfs-virt"]);
const directory = prepared.directory + "futex/";
fs.mkdirSync(directory + "root", { recursive: true });
const ndk = process.env.ANDROID_NDK_HOME || os.homedir() + "/Library/Android/sdk/ndk/26.1.10909125";
run(ndk + "/toolchains/llvm/prebuilt/darwin-x86_64/bin/aarch64-linux-android29-clang",
    ["-static", "-O2", "-Wall", ROOT + "tests/a64/android/futex_stress.c", "-o", directory + "root/futex-stress"]);
fs.writeFileSync(directory + "root/futex-init", [
    "#!/bin/busybox sh",
    "B=/bin/busybox",
    "$B mount -t proc proc /proc; $B mount -t sysfs sys /sys; $B mount -t devtmpfs dev /dev",
    // (the CPUs' clocks before and after: tests/a64/android/futex_stress.c's clock mode)
    `/futex-stress clock ${cores}; $B echo FS_START; /futex-stress ${seconds} ${process.env.A64_FUTEX_ARGS || "4 4 8"}; $B echo FS_EXIT=$?; ` +
        `/futex-stress clock ${cores}; $B echo FS_CLOCKS_DONE`,
    "$B poweroff -f",
    ""].join("\n"), { mode: 0o755 });
run("bsdtar", ["--format", "newc", "--uid", "0", "--gid", "0", "--no-xattrs", "--no-mac-metadata", "-cf", directory + "futex.cpio",
    "-C", directory + "root", "futex-init", "futex-stress"]);
const initrd = directory + "initramfs-virt+futex.cpio";
fs.writeFileSync(initrd, Buffer.concat([fs.readFileSync(prepared.initrd), fs.readFileSync(directory + "futex.cpio")]));

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const options = {
    cpu_type: "arm64", graphics_adapter: "none", cpu_cores: cores, memory_size: 512 << 20, log_level: 0,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { url: process.env.A64_KERNEL_FILE || prepared.kernel }, initrd: { url: initrd },
    cmdline: "console=ttyAMA0 nokaslr panic=-1 rdinit=/futex-init",
    ...(jit ? { jit_switches: { a64_page: 1 } } : {}),
    ...(parallel ? { parallel: true, parallel_wasm_path: process.env.A64_PARALLEL_WASM || ROOT + "build/v86-arm64-parallel.wasm" } : {}),
};

let transcript = "";
const on_byte = byte => {
    const c = String.fromCharCode(byte);
    transcript += c;
    if(verbose) process.stdout.write(c);
    else if(c === "\n")
    {
        const line = transcript.slice(transcript.lastIndexOf("\n", transcript.length - 2) + 1, -1);
        if(/^FS(_STALL|_DONE|_EXIT|_START|_CLOCK)/.test(line)) console.log(line);
    }
};
let emulator = new V86({ ...options, autostart: true });
emulator.add_listener("serial0-output-byte", on_byte);

const started = performance.now();
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const snapshots = [];
async function snapshot()
{
    await emulator.stop();
    const t0 = performance.now();
    if(mode === "pause")
    {
        await sleep(500);
    }
    else if(mode === "inplace")
    {
        const state = await emulator.save_state();
        await emulator.restore_state(state);
    }
    else
    {
        const state = await emulator.save_state();
        await emulator.destroy();
        emulator = new V86({ ...options, autostart: false });
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        await emulator.restore_state(state);
        emulator.add_listener("serial0-output-byte", on_byte);
    }
    snapshots.push(Math.round(performance.now() - t0));
    emulator.run();
}

const deadline = started + (seconds + 240) * 1000;
let next = 0;
while(!/FS_CLOCKS_DONE/.test(transcript))
{
    assert.ok(performance.now() < deadline, "deadline; the console's last lines:\n" + transcript.split("\n").slice(-20).join("\n"));
    await sleep(100);
    if(period && /^FS 2 /m.test(transcript) && !/FS_DONE/.test(transcript) && performance.now() >= next)
    {
        if(next) await snapshot();
        next = performance.now() + period;
    }
}
await emulator.destroy();
const stalls = transcript.split("\n").filter(line => line.startsWith("FS_STALL"));
const last = transcript.split("\n").filter(line => /^FS \d+ /.test(line)).pop();
// (each CPU's largest clock step, before the stress and after its snapshots)
const clock_steps = [...transcript.matchAll(/^FS_CLOCK cpu=(\d+) reads=\d+ max_step_us=(\d+)/gm)].map(m => +m[2]);
const result = { cores, parallel, jit, mode, period, snapshots: snapshots.length, snapshot_ms_median: snapshots.sort((a, b) => a - b)[snapshots.length >> 1] ?? null,
    last, stalls, clock_steps_us: { before: clock_steps.slice(0, cores), after: clock_steps.slice(cores) }, ms: Math.round(performance.now() - started) };
console.log(JSON.stringify(result));
assert.equal(stalls.length, 0, "a group stopped making progress: " + stalls.join("; "));
assert.match(transcript, /FS_EXIT=0/);
console.log("futex_snapshot: passed");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/guest_runner.mjs                                                               0000644 0000000 0000000 00000033562 00000000000 014664  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Bare-metal AArch64 guests (docs/arm64-virt-android16-plan.md P0.5): C and
// assembly built with clang --target=aarch64-none-elf and rust-lld against
// tests/a64/baremetal (an arm64 Image at RAM + 0x80000, a small libc with
// glibc's printf), run on the fixed QEMU reference and, from A1, on v86. A
// guest writes its output into the result block (baremetal/include/a64.h);
// the runner polls the block's magic over QMP and reads it with pmemsave.
//
//   build(name, sources, { cflags })  -> the directory of guest.bin
//   reference(directory, { cores })   -> { status, text, serial, ... } from QEMU
//   actual(directory, { cores })      -> the same from v86
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";

export const root = fileURLToPath(new URL("../../", import.meta.url));
const runtime = root + "tests/a64/baremetal/";

// the fixed reference: QEMU 9.2.0 built from source (P0.11), the virt board
// with every default the plan names spelled out, cortex-a35 without a PMU
export const QEMU_MACHINE = "virt-9.2,gic-version=3,its=off,highmem-ecam=on,highmem-mmio=on,highmem-redists=on," +
    "virtualization=off,secure=off,acpi=off,dtb-randomness=off";
export const QEMU_CPU = "cortex-a35,pmu=off,cntfrq=1000000000";
export function qemu_binary()
{
    const qemu = process.env.A64_QEMU || root + "build/a64-ref/qemu-9.2.0-install/bin/qemu-system-aarch64";
    assert.ok(fs.existsSync(qemu), qemu + " is missing: build QEMU 9.2.0 (docs/arm64-virt-android16-plan.md P0.11)");
    return qemu;
}
export const smp = cores => `${cores},sockets=1,cores=${cores},threads=1`;

// (baremetal/include/a64.h)
export const RESULT = 0x40800000, TEXT = RESULT + 0x1000, TEXT_SIZE = 0x100000 - 0x1000, DONE = 0xA64D0E00;
const STATUS = ["ok", "failed", "unexpected exception", "text overflow"];

const host = spawnSync("rustc", ["-vV"], { encoding: "utf8" }).stdout.match(/host: (.*)/)[1];
const lld = process.env.LD_LLD || `${spawnSync("rustc", ["--print", "sysroot"], { encoding: "utf8" }).stdout.trim()}/lib/rustlib/${host}/bin/rust-lld`;
const clang = process.env.CLANG || "clang";

function run(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, `${program} ${args.join(" ")}\n${result.stdout}${result.stderr}`);
    return result.stdout;
}

/**
 * Build a guest from `sources` (paths, .c or .S) and the runtime into
 * build/a64-<name>/guest.bin (and guest.elf for disassembly)
 */
export function build(name, sources, { cflags = [], optimize = "-O2", general_regs_only = false } = {})
{
    const directory = `${root}build/a64-${name}/`;
    fs.mkdirSync(directory, { recursive: true });
    const common = ["--target=aarch64-none-elf", "-march=armv8-a+crc+crypto", "-ffreestanding", "-fno-builtin",
        "-fno-stack-protector", "-fno-pic", "-mstrict-align", "-nostdlibinc", "-isystem", runtime + "include", "-g"];
    const objects = [];
    const compile = (source, extra) => {
        const object = directory + path.basename(source).replace(/\.[cS]$/, "") + ".o";
        assert.ok(!objects.includes(object), "two sources named like " + source);
        run(clang, [...common, ...extra, "-c", "-o", object, source]);
        objects.push(object);
    };
    compile(runtime + "start.S", []);
    // (general_regs_only: no FP or SIMD register anywhere, for the integer
    // core before P2.5; printf has no %a then)
    const no_fp = general_regs_only ? ["-mgeneral-regs-only", "-DA64_GENERAL_REGS_ONLY"] : [];
    // (A64_MMU=1: the runtime turns the MMU on, an identity map, before main: see runtime.c)
    compile(runtime + "runtime.c", ["-O2", ...no_fp, ...(+process.env.A64_MMU ? ["-DA64_MMU"] : [])]);
    compile(runtime + "exception.c", ["-O2", "-mgeneral-regs-only"]);
    compile(runtime + "libc.c", ["-O2", ...no_fp]);
    for(const source of sources)
    {
        // (AArch32 code, foo.a32.S: assembled for ARMv8-A AArch32 into a flat
        // binary that the image carries as foo_a32 .. foo_a32_end, page aligned;
        // position independent, with .arm and .thumb as it needs)
        if(source.endsWith(".a32.S"))
        {
            const base = path.basename(source, ".a32.S");
            const object = directory + base + ".a32.o", binary = directory + base + ".a32.bin", wrapper = directory + base + ".a32.wrap.S";
            run(clang, ["--target=armv8a-none-eabi", "-march=armv8-a+crc+crypto", "-mfpu=crypto-neon-fp-armv8", "-c", "-o", object, source]);
            run(lld, ["-flavor", "gnu", "-m", "armelf", "--image-base=0", "-Ttext=0", "--oformat=binary", "-o", binary, object]);
            fs.writeFileSync(wrapper, `    .section .rodata\n    .balign 4096\n    .global ${base}_a32\n${base}_a32:\n    .incbin "${binary}"\n` +
                `    .global ${base}_a32_end\n${base}_a32_end:\n`);
            compile(wrapper, []);
            continue;
        }
        compile(source, [optimize, ...no_fp, ...cflags]);
    }
    const link = ["-flavor", "gnu", "-m", "aarch64elf", "-static", "-T", runtime + "link.ld", ...objects];
    run(lld, [...link, "-o", directory + "guest.elf"]);
    run(lld, [...link, "--oformat=binary", "-o", directory + "guest.bin"]);
    const image = fs.readFileSync(directory + "guest.bin");
    assert.equal(image.readUInt32LE(56), 0x644D5241, "guest.bin: no arm64 Image header");
    return directory;
}

/** The result block and its text */
export function parse(bytes)
{
    const magic = bytes.readUInt32LE(0), status = bytes.readUInt32LE(4), length = bytes.readUInt32LE(8);
    assert.ok(length <= TEXT_SIZE, "result text length " + length);
    const big = at => bytes.readBigUInt64LE(at);
    return {
        done: magic === DONE, status: STATUS[status] || "status " + status, cores: bytes.readUInt32LE(12),
        exception: { vector: big(16), esr: big(24), elr: big(32), far: big(40), spsr: big(48) }, dtb: big(56),
        text: bytes.toString("latin1", TEXT - RESULT, TEXT - RESULT + length),
    };
}

// A test interrupted by a signal skips `finally`; QEMU would outlive it. The
// handlers are there only while QEMU runs: Node runs them on the event loop,
// and a test busy in the emulator (a hang included) would never see SIGTERM
// (`timeout` could not stop it)
const references = new Set();
process.on("exit", () => { for(const child of references) child.kill("SIGKILL"); });
const SIGNALS = [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]].map(([signal, code]) => [signal, () => process.exit(code)]);
function track(child)
{
    if(!references.size) for(const [signal, handler] of SIGNALS) process.on(signal, handler);
    references.add(child);
    child.on("exit", () => {
        references.delete(child);
        if(!references.size) for(const [signal, handler] of SIGNALS) process.off(signal, handler);
    });
}

/**
 * Run guest.bin on QEMU until its result block is done (or `timeout` ms)
 * and return parse() of the block (`machine`, `cpu`: other than the
 * reference's, tests/a32/runner.mjs)
 */
export async function reference(directory, { cores = 1, memory = 128, timeout = 60000, extra = [], machine = QEMU_MACHINE, cpu = QEMU_CPU } = {})
{
    const args = ["-machine", machine, "-cpu", cpu, "-m", memory + "M", "-smp", smp(cores),
        "-display", "none", "-serial", "file:" + directory + "qemu-serial.txt", "-monitor", "none", "-qmp", "stdio", "-no-reboot", "-no-shutdown",
        "-kernel", directory + "guest.bin", ...extra,
        ...(process.env.A64_QEMU_TRACE ? ["-d", "int,guest_errors", "-D", directory + "qemu.log"] : [])];
    const child = spawn(qemu_binary(), args, { stdio: ["pipe", "pipe", "pipe"] });
    track(child);
    let input = "", error = "", id = 0;
    const pending = new Map();
    child.stderr.on("data", data => error += data);
    const fail_pending = reason => {
        for(const callback of pending.values()) callback({ error: { desc: String(reason) } });
        pending.clear();
    };
    child.on("error", fail_pending);
    child.on("exit", (code, signal) => fail_pending(`QEMU exited (${code}, ${signal}): ${error}`));
    child.stdin.on("error", fail_pending);
    child.stdout.on("data", data => {
        input += data;
        while(input.includes("\n"))
        {
            const end = input.indexOf("\n"), line = input.slice(0, end);
            input = input.slice(end + 1);
            let message;
            try { message = JSON.parse(line); } catch{ continue; }
            if(message.id !== undefined)
            {
                const callback = pending.get(message.id);
                pending.delete(message.id);
                callback?.(message);
            }
        }
    });
    const request = (execute, args = {}) => new Promise((resolve, reject) => {
        const n = id++;
        const timer = setTimeout(() => {
            pending.delete(n);
            reject(new Error(`QEMU monitor timeout for ${execute}: ${error}`));
        }, 20000);
        pending.set(n, message => {
            clearTimeout(timer);
            if(message.error) reject(new Error(JSON.stringify(message.error)));
            else resolve(message.return);
        });
        child.stdin.write(JSON.stringify({ execute, arguments: args, id: n }) + "\n");
    });
    const hmp = command => request("human-monitor-command", { "command-line": command });
    const dump = directory + "qemu.bin";
    try
    {
        await request("qmp_capabilities");
        const deadline = performance.now() + timeout;
        let seen = false;
        while(performance.now() < deadline)
        {
            if((await hmp(`xp /1wx ${RESULT}`)).includes(DONE.toString(16))) { seen = true; break; }
            await delay(20);
        }
        await request("stop");
        await hmp(`pmemsave ${RESULT} ${TEXT - RESULT + TEXT_SIZE} "${dump}"`);
        if(!seen)
        {
            const registers = await hmp("info registers");
            const result = parse(fs.readFileSync(dump));
            throw new Error(`QEMU guest timed out after ${timeout} ms: ${error}\n${registers}\noutput so far:\n${result.text}`);
        }
        await request("quit");
    }
    // (SIGTERM is only a shutdown request, which -no-shutdown turns into a pause)
    finally { child.kill("SIGKILL"); }
    const result = parse(fs.readFileSync(dump));
    result.serial = fs.existsSync(directory + "qemu-serial.txt") ? fs.readFileSync(directory + "qemu-serial.txt", "latin1") : "";
    return result;
}

/**
 * The A64 page tier for v86 runs (docs/jit-unification-plan.md J2): A64_JIT=1
 * turns it on, with synchronous publication (the runners drive the slices
 * themselves) and the compile threshold A64_JIT_HOT (default 1: code is
 * compiled at its first block boundary, so even code that runs once runs
 * compiled)
 */
export function jit_options()
{
    if(!+process.env.A64_JIT) return {};
    // (A64_JIT_SWITCHES: more switches, "name=value,...")
    const more = Object.fromEntries((process.env.A64_JIT_SWITCHES || "").split(",").filter(Boolean).map(p => [p.split("=")[0], +p.split("=")[1]]));
    return { jit_switches: { a64_page: 1, a64_page_hot: +(process.env.A64_JIT_HOT || 1), ...more }, ir_sync_publication: true };
}

/**
 * The same on v86: the arm64 CPU boots guest.bin as its kernel (an arm64
 * Image at RAM + 0x80000, src/virt/loader.js); the slices run until the
 * result block is done (or `timeout` ms). A64_WASM selects the core
 * (default build/v86-arm64.wasm), TEST_RELEASE_BUILD=1 the compiled library,
 * A64_JIT=1 the page tier (jit_options); `setup(cpu)` runs before the first
 * instruction.
 */
export async function actual(directory, { cores = 1, memory = 128, timeout = 60000, options = {}, setup = null } = {})
{
    const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", cpu_cores: cores, memory_size: memory << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
        kernel: { url: directory + "guest.bin" },
        ...jit_options(),
        ...options,
    });
    try
    {
        await new Promise((resolve, reject) => {
            emulator.add_listener("emulator-loaded", resolve);
            emulator.add_listener("emulator-error", reject);
        });
        const cpu = emulator.v86.cpu;
        // (setup(cpu): a test's own configuration of the core, e.g. the granules)
        setup?.(cpu);
        let serial = "";
        emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
        const at = RESULT - 0x40000000;
        const block = () => Buffer.from(cpu.mem8.buffer, cpu.mem8.byteOffset + at, TEXT - RESULT + TEXT_SIZE);
        const deadline = performance.now() + timeout;
        while(block().readUInt32LE(0) !== DONE)
        {
            if(performance.now() > deadline)
            {
                const result = parse(Buffer.from(block()));
                throw new Error(`v86 guest timed out after ${timeout} ms at PC ${cpu.read_pc()}: ` +
                    JSON.stringify(cpu.get_diagnostics()) + `\noutput so far:\n${result.text}`);
            }
            cpu.run_cores();
        }
        const result = parse(Buffer.from(block()));
        result.serial = serial;
        // (with A64_JIT=1 on stderr: what the page tier did)
        result.page_tier = cpu.page_tier_stats();
        if(+process.env.A64_JIT) console.error("page tier: " + JSON.stringify(result.page_tier));
        fs.writeFileSync(directory + "v86.bin", Buffer.from(block()));
        return result;
    }
    finally
    {
        await emulator.destroy();
    }
}

/** reference() or actual(), by A64_TARGET=qemu|v86 (default qemu until A1) */
export function target()
{
    const name = process.env.A64_TARGET || "qemu";
    assert.ok(name === "qemu" || name === "v86", "A64_TARGET=" + name);
    return { name, run: name === "qemu" ? reference : actual };
}
                                                                                                                                              source/v64/tests/a64/id_registers.c                                                                 0000644 0000000 0000000 00000006562 00000000000 014260  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Reads the CPU's identification registers at EL1 (tools/cpu_contract.mjs,
// docs/arm64-virt-android16-plan.md P0.3): every encoding of the ID space
// (op0=3, op1=0, CRn=0, CRm=0-7), the cache geometry (CLIDR_EL1, CCSIDR_EL1
// per CSSELR_EL1), AIDR_EL1, CTR_EL0, DCZID_EL0, CNTFRQ_EL0, and MPIDR_EL1 of
// every core (the secondaries started with PSCI CPU_ON).
//
//   A64_ID <encoding> <value> | UNDEF esr=<ESR_EL1>
//   A64_MPIDR <core> <value>

#include <a64.h>
#include <stdio.h>

#define MRS(name) ({ uint64_t _v; __asm__ volatile("mrs %0, " name : "=r"(_v)); _v; })
#define C(m, o) case m * 8 + o: value = MRS("S3_0_C0_C" #m "_" #o); break;
#define ROW(m) C(m, 0) C(m, 1) C(m, 2) C(m, 3) C(m, 4) C(m, 5) C(m, 6) C(m, 7)

static void show(const char *name, uint64_t value, struct a64_fault *fault)
{
    if(fault && fault->taken) printf("A64_ID %s UNDEF esr=%#010lx\n", name, (unsigned long)fault->esr);
    else printf("A64_ID %s 0x%016lx\n", name, (unsigned long)value);
}

static void id_space(void)
{
    for(int m = 0; m < 8; m++)
    {
        for(int o = 0; o < 8; o++)
        {
            uint64_t value = 0;
            struct a64_fault fault;
            char name[24];
            a64_expect();
            switch(m * 8 + o) { ROW(0) ROW(1) ROW(2) ROW(3) ROW(4) ROW(5) ROW(6) ROW(7) }
            a64_caught(&fault);
            snprintf(name, sizeof name, "S3_0_C0_C%d_%d", m, o);
            show(name, value, &fault);
        }
    }
}

// (op1=1: CCSIDR_EL1 op2=0, CLIDR_EL1 op2=1, CCSIDR2_EL1 op2=2, AIDR_EL1 op2=7)
static void caches(void)
{
    struct a64_fault fault;
    uint64_t value = 0;
    show("CLIDR_EL1", MRS("clidr_el1"), 0);
    show("AIDR_EL1", MRS("aidr_el1"), 0);
    for(int level = 0; level < 3; level++)
    {
        for(int instruction = 0; instruction < 2; instruction++)
        {
            char name[24];
            int csselr = level << 1 | instruction;
            a64_write(csselr_el1, csselr);
            __asm__ volatile("isb");
            snprintf(name, sizeof name, "CCSIDR_EL1.%d", csselr);
            show(name, MRS("ccsidr_el1"), 0);
            snprintf(name, sizeof name, "CSSELR_EL1.%d", csselr);
            show(name, MRS("csselr_el1"), 0);
        }
    }
    a64_write(csselr_el1, 0);
    a64_expect();
    value = MRS("S3_1_C0_C0_2");
    a64_caught(&fault);
    show("CCSIDR2_EL1", value, &fault);
}

static volatile uint64_t mpidr[8];
static volatile int reported[8];

static void secondary(unsigned core)
{
    mpidr[core] = MRS("mpidr_el1");
    __asm__ volatile("dmb ish" ::: "memory");
    reported[core] = 1;
}

int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    id_space();
    caches();
    show("CTR_EL0", MRS("ctr_el0"), 0);
    show("DCZID_EL0", MRS("dczid_el0"), 0);
    show("CNTFRQ_EL0", MRS("cntfrq_el0"), 0);
    show("FPCR", MRS("fpcr"), 0);
    show("FPSR", MRS("fpsr"), 0);
    printf("A64_MPIDR 0 0x%016lx\n", (unsigned long)MRS("mpidr_el1"));
    a64_core_main = secondary;
    for(unsigned core = 1; core < 8; core++)
    {
        int64_t started = a64_cpu_on(core);
        if(started) break; // (PSCI INVALID_PARAMETERS: no such core)
        for(unsigned long spin = 0; !reported[core]; spin++)
        {
            if(spin == 100000000ul) a64_fail("a secondary core did not report");
        }
        printf("A64_MPIDR %u 0x%016lx\n", core, (unsigned long)mpidr[core]);
    }
    printf("A64_ID_DONE\n");
    return 0;
}
                                                                                                                                              source/v64/tests/a64/integer_oracle.mjs                                                             0000644 0000000 0000000 00000037267 00000000000 015134  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Integer, branch, load/store and exclusive instructions of the A64
// interpreter against QEMU (docs/arm64-virt-android16-plan.md P2.2: at least
// 2,000 cases, 0 differences). Each case is one instruction (or a branch
// with its two outcomes) with random X0-X14 and NZCV; X15 points at a
// 128-byte window of random memory. The guest (tests/a64/guest_runner.mjs)
// runs the cases and prints, per case, X0-X15, NZCV and a checksum of the
// window; QEMU's lines and v86's must be equal.
//
//   node tests/a64/integer_oracle.mjs [--cases N] [--seed S] [--filter family]
//   A64_TARGET=qemu runs QEMU only (to check the generator)
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const CASES = +option("--cases", 2400);
const SEED = +option("--seed", 1);
const FILTER = option("--filter", null);
const BATCH = 400;

// ---- random values (a xorshift generator: the same cases everywhere)
let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
function next64()
{
    state ^= state << 13n & (1n << 64n) - 1n;
    state ^= state >> 7n;
    state ^= state << 17n & (1n << 64n) - 1n;
    return state;
}
const rand = (n) => Number(next64() % BigInt(n));
const pick = list => list[rand(list.length)];
const SPECIAL = [0n, 1n, 2n, 0xFFFFFFFFFFFFFFFFn, 0x7FFFFFFFFFFFFFFFn, 0x8000000000000000n, 0xFFFFFFFFn, 0x7FFFFFFFn,
    0x80000000n, 0xFFFFFFFF80000000n, 0x100000000n, 0x8000n, 0xFFn, 0xFF00FF00FF00FF00n];
function value()
{
    switch(rand(4))
    {
        case 0: return pick(SPECIAL);
        case 1: return next64() & 0xFFFFFFFFn;
        case 2: return BigInt(rand(64)) - 32n & (1n << 64n) - 1n;
        default: return next64();
    }
}
const hex = v => "0x" + v.toString(16);

// ---- the cases: assembly for one instruction, with the registers it uses
const X = () => "x" + rand(15);
const W = () => "w" + rand(15);
const Rboth = sf => sf ? X() : W();
const COND = ["eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al"];

/** A valid logical immediate of a 64-bit (or 32-bit) operation */
function bitmask(sf)
{
    for(;;)
    {
        const esize = pick(sf ? [2, 4, 8, 16, 32, 64] : [2, 4, 8, 16, 32]);
        const ones = 1 + rand(esize - 1);
        const rotation = rand(esize);
        let element = (1n << BigInt(ones)) - 1n;
        const emask = (1n << BigInt(esize)) - 1n;
        if(rotation) element = (element >> BigInt(rotation) | element << BigInt(esize - rotation)) & emask;
        let result = 0n;
        for(let at = 0; at < (sf ? 64 : 32); at += esize) result |= element << BigInt(at);
        return result;
    }
}

const FAMILIES = {
    add_imm: () => { const sf = rand(2); return `${pick(["add", "adds", "sub", "subs"])} ${Rboth(sf)}, ${Rboth(sf)}, #${rand(4096)}${pick(["", ", lsl #12"])}`; },
    logical_imm: () => { const sf = rand(2); return `${pick(["and", "orr", "eor", "ands"])} ${Rboth(sf)}, ${Rboth(sf)}, #${hex(bitmask(sf))}`; },
    move_wide: () => { const sf = rand(2); return `${pick(["movz", "movn", "movk"])} ${Rboth(sf)}, #${rand(65536)}, lsl #${pick(sf ? [0, 16, 32, 48] : [0, 16])}`; },
    bitfield: () => {
        const sf = rand(2), width = sf ? 64 : 32;
        return `${pick(["sbfm", "bfm", "ubfm"])} ${Rboth(sf)}, ${Rboth(sf)}, #${rand(width)}, #${rand(width)}`;
    },
    extr: () => { const sf = rand(2); const r = Rboth(sf); return `extr ${r}, ${Rboth(sf)}, ${Rboth(sf)}, #${rand(sf ? 64 : 32)}`; },
    add_shifted: () => {
        const sf = rand(2);
        return `${pick(["add", "adds", "sub", "subs"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}, ${pick(["lsl", "lsr", "asr"])} #${rand(sf ? 64 : 32)}`;
    },
    add_extended: () => {
        const sf = rand(2);
        const ext = pick(sf ? ["uxtb", "uxth", "uxtw", "uxtx", "sxtb", "sxth", "sxtw", "sxtx"] : ["uxtb", "uxth", "uxtw", "sxtb", "sxth", "sxtw"]);
        const m = sf && (ext === "uxtx" || ext === "sxtx") ? X() : W();
        return `${pick(["add", "adds", "sub", "subs"])} ${Rboth(sf)}, ${Rboth(sf)}, ${m}, ${ext} #${rand(5)}`;
    },
    carry: () => { const sf = rand(2); return `${pick(["adc", "adcs", "sbc", "sbcs"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}`; },
    logical_shifted: () => {
        const sf = rand(2);
        return `${pick(["and", "bic", "orr", "orn", "eor", "eon", "ands", "bics"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}, ${pick(["lsl", "lsr", "asr", "ror"])} #${rand(sf ? 64 : 32)}`;
    },
    cond_compare: () => {
        const sf = rand(2);
        const operand = rand(2) ? Rboth(sf) : "#" + rand(32);
        return `${pick(["ccmn", "ccmp"])} ${Rboth(sf)}, ${operand}, #${rand(16)}, ${pick(COND)}`;
    },
    cond_select: () => { const sf = rand(2); return `${pick(["csel", "csinc", "csinv", "csneg"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}, ${pick(COND)}`; },
    multiply: () => {
        switch(rand(4))
        {
            case 0: { const sf = rand(2); return `${pick(["madd", "msub"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}`; }
            case 1: return `${pick(["smaddl", "smsubl", "umaddl", "umsubl"])} ${X()}, ${W()}, ${W()}, ${X()}`;
            default: return `${pick(["smulh", "umulh"])} ${X()}, ${X()}, ${X()}`;
        }
    },
    divide: () => { const sf = rand(2); return `${pick(["udiv", "sdiv"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}`; },
    variable_shift: () => { const sf = rand(2); return `${pick(["lslv", "lsrv", "asrv", "rorv"])} ${Rboth(sf)}, ${Rboth(sf)}, ${Rboth(sf)}`; },
    crc32: () => {
        const op = pick(["crc32b", "crc32h", "crc32w", "crc32x", "crc32cb", "crc32ch", "crc32cw", "crc32cx"]);
        return `${op} ${W()}, ${W()}, ${op.endsWith("x") ? X() : W()}`;
    },
    one_source: () => {
        const sf = rand(2);
        const op = pick(sf ? ["rbit", "rev16", "rev32", "rev", "clz", "cls"] : ["rbit", "rev16", "rev", "clz", "cls"]);
        return `${op} ${Rboth(sf)}, ${Rboth(sf)}`;
    },
    load_store: () => {
        // (naturally aligned: the MMU is off, so memory is Device memory)
        const size = rand(4), bytes = 1 << size;
        const offset = rand(128 / bytes) * bytes;
        const ops = [["strb", "ldrb", "ldrsb"], ["strh", "ldrh", "ldrsh"], ["str", "ldr", "ldrsw"], ["str", "ldr"]][size];
        const op = pick(ops);
        const r = op === "ldrsb" || op === "ldrsh" ? (rand(2) ? X() : W()) : size === 3 || op === "ldrsw" ? X() : W();
        const unscaled = (o) => o.replace(/^ldr/, "ldur").replace(/^str/, "stur");
        switch(rand(5))
        {
            case 0: return `${op} ${r}, [x15, #${offset}]`;
            case 1: return `${unscaled(op)} ${r}, [x15, #${offset - (offset >= bytes ? bytes : 0)}]`;
            case 2: return `${op} ${r}, [x15, #${Math.min(offset, 64)}]!`;
            case 3: return `${op} ${r}, [x15], #${pick([bytes, -bytes, 0, 2 * bytes])}`;
            default: {
                // (register offset: the index in X14 or W14, extended and scaled)
                const ext = pick(["lsl", "uxtw", "sxtw", "sxtx"]);
                const index = ext === "uxtw" || ext === "sxtw" ? "w14" : "x14";
                const scale = pick([0, size]);
                // (an element index, scaled by the shift or already in bytes)
                const element = BigInt(rand(128 / bytes / 2));
                return { asm: `${op} ${r === "x14" || r === "w14" ? (size === 3 ? "x13" : "w13") : r}, [x15, ${index}, ${ext} #${scale}]`,
                    x14: scale === size ? element : element * BigInt(bytes) };
            }
        }
    },
    pair: () => {
        const sf = rand(2), bytes = sf ? 8 : 4;
        const offset = rand(64 / bytes) * bytes;
        const op = pick(sf ? ["stp", "ldp"] : ["stp", "ldp", "ldpsw"]);
        const a = op === "ldpsw" ? "x" + rand(7) : (sf ? "x" : "w") + rand(7);
        const b = op === "ldpsw" ? "x" + (7 + rand(7)) : (sf ? "x" : "w") + (7 + rand(7));
        switch(rand(4))
        {
            case 0: return `${op} ${a}, ${b}, [x15, #${offset}]`;
            case 1: return `${op} ${a}, ${b}, [x15, #${offset}]!`;
            case 2: return `${op} ${a}, ${b}, [x15], #${pick([bytes, -2 * bytes, 0])}`;
            default: return `${op.replace("p", "np").replace("npsw", "psw")} ${a}, ${b}, [x15, #${offset}]`.replace("ldnpsw", "ldpsw");
        }
    },
    exclusive: () => {
        const size = rand(4), bytes = 1 << size;
        const suffix = ["b", "h", "", ""][size];
        const r = size === 3 ? X : W;
        const offset = rand(64 / bytes) * bytes;
        const acquire = rand(2) ? "a" : "";
        const release = rand(2) ? "l" : "";
        // (the store's status register differs from the others)
        const t = size === 3 ? "x" + rand(7) : "w" + rand(7);
        switch(rand(4))
        {
            case 0: return `add x15, x15, #${offset}\n    ld${acquire}xr${suffix} ${t}, [x15]\n    st${release}xr${suffix} w13, ${r().replace(/\d+/, d => String(7 + +d % 6))}, [x15]`;
            case 1: return `add x15, x15, #${offset}\n    st${release}xr${suffix} w13, ${r().replace(/\d+/, d => String(7 + +d % 6))}, [x15]`;
            case 2: return `add x15, x15, #${offset}\n    ld${acquire}xr${suffix} ${t}, [x15]\n    clrex\n    st${release}xr${suffix} w13, ${r().replace(/\d+/, d => String(7 + +d % 6))}, [x15]`;
            default: return `add x15, x15, #${offset}\n    ${rand(2) ? `ldar${suffix} ${t}` : `stlr${suffix} ${t}`}, [x15]`;
        }
    },
    exclusive_pair: () => {
        const sf = rand(2), bytes = sf ? 16 : 8;
        const reg = sf ? "x" : "w";
        const offset = rand(64 / bytes) * bytes;
        return `add x15, x15, #${offset}\n    ld${pick(["", "a"])}xp ${reg}1, ${reg}2, [x15]\n    st${pick(["", "l"])}xp w13, ${reg}${3 + rand(4)}, ${reg}${7 + rand(4)}, [x15]`;
    },
    branch: () => {
        const taken = (instruction) => `${instruction}, 1f\n    mov x0, #1\n    b 2f\n1:  mov x0, #2\n2:`;
        switch(rand(4))
        {
            case 0: return taken(`b.${pick(COND.concat(["nv"]))}`).replace("b.nv,", "b.nv").replace(/b\.(\w+), 1f/, "b.$1 1f");
            case 1: return taken(`${pick(["cbz", "cbnz"])} ${pick(["x", "w"])}${1 + rand(14)}`);
            case 2: { const sf = rand(2); return taken(`${pick(["tbz", "tbnz"])} ${sf ? "x" : "w"}${1 + rand(14)}, #${rand(sf ? 64 : 32)}`); }
            default: return `adr x1, .\n    adrp x2, .\n    adr x3, . + ${4 * rand(1000) - 2000}`;
        }
    },
    flags: () => pick([
        `mrs ${X()}, nzcv`,
        `msr nzcv, ${X()}`,
        `msr daifset, #${rand(16)}\n    mrs ${X()}, daif\n    msr daifclr, #15`,
        `mrs ${X()}, currentel`,
        `cmp ${X()}, ${X()}\n    cset ${X()}, ${pick(COND.slice(0, 14))}`,
    ]),
};

const families = Object.keys(FAMILIES).filter(name => !FILTER || name === FILTER);
const cases = [];
for(let n = 0; n < CASES; n++)
{
    const family = families[n % families.length];
    let generated = FAMILIES[family]();
    let x14 = null;
    if(typeof generated === "object") { x14 = generated.x14; generated = generated.asm; }
    const registers = Array.from({ length: 15 }, () => value());
    if(x14 !== null) registers[14] = x14;
    const flags = BigInt(rand(16)) << 28n;
    const memory = Array.from({ length: 16 }, () => next64());
    cases.push({ family, asm: generated, registers, flags, memory });
}

// ---- the guest of one batch
function guest(batch, first)
{
    const lines = [".text", ".balign 4", ".global run_cases", "run_cases:", "    stp x29, x30, [sp, #-96]!",
        "    stp x19, x20, [sp, #16]", "    stp x21, x22, [sp, #32]", "    stp x23, x24, [sp, #48]", "    stp x25, x26, [sp, #64]",
        "    stp x27, x28, [sp, #80]"];
    batch.forEach((c, i) => {
        const n = first + i;
        lines.push(`// case ${n}: ${c.family}`, `    adrp x28, input_${n}`, `    add x28, x28, :lo12:input_${n}`,
            "    ldr x16, [x28, #128]", "    msr nzcv, x16");
        for(let r = 0; r < 14; r += 2) lines.push(`    ldp x${r}, x${r + 1}, [x28, #${8 * r}]`);
        lines.push("    ldr x14, [x28, #112]", `    adrp x15, memory_${n}`, `    add x15, x15, :lo12:memory_${n}`, "    add x15, x15, #64");
        lines.push("    sub x15, x15, #64");
        lines.push("    " + c.asm);
        lines.push(`    adrp x28, output_${n}`, `    add x28, x28, :lo12:output_${n}`);
        for(let r = 0; r < 16; r += 2) lines.push(`    stp x${r}, x${r + 1}, [x28, #${8 * r}]`);
        lines.push("    mrs x16, nzcv", "    str x16, [x28, #128]");
    });
    lines.push("    ldp x19, x20, [sp, #16]", "    ldp x21, x22, [sp, #32]", "    ldp x23, x24, [sp, #48]", "    ldp x25, x26, [sp, #64]",
        "    ldp x27, x28, [sp, #80]", "    ldp x29, x30, [sp], #96", "    ret", ".data", ".balign 64");
    batch.forEach((c, i) => {
        const n = first + i;
        lines.push(`input_${n}:`, ...c.registers.map(v => `    .quad ${hex(v)}`), "    .quad 0", `    .quad ${hex(c.flags)}`, "    .quad 0",
            ".balign 64", `memory_${n}:`, ...c.memory.map(v => `    .quad ${hex(v)}`), ".balign 64",
            `output_${n}:`, "    .zero 136", ".balign 64");
    });
    lines.push(".text", ".global case_table", ".balign 8", "case_table:");
    batch.forEach((_, i) => lines.push(`    .quad output_${first + i}`, `    .quad memory_${first + i}`));
    return lines.join("\n") + "\n";
}

const MAIN = `#include <a64.h>
#include <stdio.h>
void run_cases(void);
extern const unsigned long case_table[][2];
int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    run_cases();
    for(int i = 0; i < CASE_COUNT; i++)
    {
        const unsigned long *out = (const unsigned long *)case_table[i][0];
        const unsigned long *memory = (const unsigned long *)case_table[i][1];
        unsigned long sum = 0;
        for(int k = 0; k < 16; k++) sum = (sum ^ memory[k]) * 0x100000001B3ul + k;
        printf("%d", FIRST + i);
        for(int r = 0; r < 17; r++) printf(" %lx", out[r]);
        printf(" %lx\\n", sum);
    }
    return 0;
}
`;

const directory_base = root + "build/a64-integer-oracle/";
fs.mkdirSync(directory_base, { recursive: true });
let differences = 0, compared = 0;
const only_qemu = process.env.A64_TARGET === "qemu";
for(let first = 0; first < cases.length; first += BATCH)
{
    const batch = cases.slice(first, first + BATCH);
    fs.writeFileSync(directory_base + `cases-${first}.S`, guest(batch, first));
    fs.writeFileSync(directory_base + `main-${first}.c`, MAIN.replace(/CASE_COUNT/g, String(batch.length)).replace(/FIRST/g, String(first)));
    const directory = build(`integer-oracle-${first}`, [directory_base + `cases-${first}.S`, directory_base + `main-${first}.c`],
        { general_regs_only: true });
    const expected = await reference(directory, { timeout: 120000 });
    assert.equal(expected.status, "ok", "QEMU: " + expected.text.slice(-2000));
    if(only_qemu) { compared += batch.length; continue; }
    const got = await actual(directory, { timeout: 300000 });
    assert.equal(got.status, "ok", "v86: " + got.text.slice(-2000));
    const want = expected.text.trim().split("\n"), have = got.text.trim().split("\n");
    assert.equal(have.length, want.length, "line count");
    for(let i = 0; i < want.length; i++)
    {
        compared++;
        if(want[i] !== have[i])
        {
            differences++;
            if(differences <= 20)
            {
                const c = cases[first + i];
                console.log(`DIFF case ${first + i} (${c.family}): ${c.asm.replace(/\n\s*/g, "; ")}\n  inputs ${c.registers.map(hex).join(" ")} nzcv ${hex(c.flags)}\n` +
                    `  qemu ${want[i]}\n  v86  ${have[i]}`);
            }
        }
    }
}
console.log(`integer oracle: ${compared} cases (${families.length} families, seed ${SEED}), ${differences} differences` + (only_qemu ? " (QEMU only)" : ""));
process.exit(differences ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                         source/v64/tests/a64/jit_workload/Hello.java                                                        0000644 0000000 0000000 00000002233 00000000000 016016  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The guest JIT workload's HotSpot part (tests/a64/linux_boot.mjs,
// A64_WORKLOAD=jit; P6.7), run as `java Hello.java` (javac in the JVM, then
// C1 and C2): a checksum that only depends on exact arithmetic
import java.util.HashMap;
import java.util.Map;

public class Hello
{
    public static void main(String[] args)
    {
        long s = 0;
        for(int i = 1; i < 5_000_000; i++) s = (s * 31 + i) % 1_000_000_007L;
        Map<Integer, Integer> m = new HashMap<>();
        for(int i = 0; i < 200_000; i++) m.merge(i % 1000, i, Integer::sum);
        long acc = 0;
        for(Map.Entry<Integer, Integer> e : m.entrySet()) acc = (acc * 131 + e.getKey() * 7L + e.getValue()) % 1_000_000_007L;
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 20_000; i++) sb.append(Long.toHexString(i * 2654435761L & 0xFFFFFFFFL)).append(',');
        int letters = 0;
        for(int i = 0; i < sb.length(); i++) if(Character.isLetter(sb.charAt(i))) letters++;
        double f = 0;
        for(int i = 1; i < 300_000; i++) f += StrictMath.sin(i) / i;
        System.out.println("java " + s + " " + acc + " " + sb.length() + " " + letters + " " + f);
    }
}
                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/a64/jit_workload/pcre2.txt                                                         0000644 0000000 0000000 00000000637 00000000000 015672  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # The guest JIT workload's PCRE2 part (tests/a64/linux_boot.mjs,
# A64_WORKLOAD=jit; P6.7): pcre2test -jit compiles each pattern to machine code

/(\d{3})-(\d{4})/
    call 555-1234 now
    no match here

/^(?:a|b)*c$/
    ababababc
    ababd

/(?<year>\d{4})-(?<month>\d\d)/g
    2026-10 and 1999-12 but not 12-2026

/(\w+)\s+\1/i
    the The quick
    no repeats

/[\x{100}-\x{2ff}]+/utf
    abc\x{101}\x{2fe}def
                                                                                                 source/v64/tests/a64/jit_workload/work.js                                                           0000644 0000000 0000000 00000002423 00000000000 015431  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The guest JIT workload's V8 part (tests/a64/linux_boot.mjs, A64_WORKLOAD=jit;
// docs/arm64-virt-android16-plan.md P6.7): calls, numbers, objects, strings,
// regular expressions and typed arrays, hot enough for V8's tiers; a
// checksum that only depends on exact arithmetic
let h = 0x811c9dc5;
const mix = x => { h = Math.imul(h ^ (x | 0), 16777619) >>> 0; };
function fib(n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
mix(fib(24));
let s = 0;
for(let i = 1; i < 3000000; i++) s = (s * 31 + i) % 1000000007;
mix(s);
const counts = {};
for(let i = 0; i < 100000; i++) counts["k" + i % 997] = (counts["k" + i % 997] | 0) + i;
const json = JSON.stringify(counts);
mix(json.length);
for(let i = 0; i < json.length; i += 7) mix(json.charCodeAt(i));
const words = [];
for(let i = 0; i < 20000; i++) words.push((Math.imul(i, 2654435761) >>> 0).toString(16) + "-" + i);
let matches = 0;
for(const m of words.join(" ").matchAll(/([a-f]+)\d*-(\d+)/g)) matches += m[1].length + Number(m[2]) % 7;
mix(matches);
const a = new Float64Array(50000);
for(let i = 0; i < a.length; i++) a[i] = Math.sqrt(i) / (1 + i % 13);
let f = 0;
for(let k = 0; k < 20; k++) for(let i = 0; i < a.length; i++) f += a[i] * (k + 1);
console.log(`node ${h.toString(16)} ${s} ${json.length} ${matches} ${f.toPrecision(15)}`);
                                                                                                                                                                                                                                             source/v64/tests/a64/jit_workload/work.lua                                                          0000644 0000000 0000000 00000001332 00000000000 015574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       -- The guest JIT workload's LuaJIT part (tests/a64/linux_boot.mjs,
-- A64_WORKLOAD=jit; P6.7), run with -jon and -joff: the same line both ways
local s = 0
for i = 1, 3000000 do s = (s * 31 + i) % 1000000007 end
local t = {}
for i = 1, 100000 do t[i] = (i * 7919) % 100003 end
table.sort(t)
local acc = 0
for i = 1, #t, 97 do acc = (acc + t[i] * i) % 1000000007 end
local parts = {}
for i = 1, 5000 do parts[#parts + 1] = string.format("%x", (i * 2654435761) % 4294967296) end
local str = table.concat(parts, ",")
local letters = 0
for w in str:gmatch("[a-f]+") do letters = letters + #w end
local f = 0.0
for i = 1, 200000 do f = f + math.sin(i) / i end
print(string.format("luajit %d %d %d %d %.12g", s, acc, #str, letters, f))
                                                                                                                                                                                                                                                                                                      source/v64/tests/a64/linux_boot.mjs                                                                 0000644 0000000 0000000 00000225641 00000000000 014327  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unmodified Alpine Linux 3.24.0 aarch64 (docs/arm64-virt-android16-plan.md
// P0.1, P0.2; the v86 runs from A2): the pinned virt ISO's EFI zboot kernel
// and initramfs, and the aarch64 probe (tests/a64/linux_probe.c) built with
// clang and rust-lld as a static ELF, delivered two ways:
//
// - stage "initramfs" (A64_STAGE, the default): the initrd is
//   initramfs-virt followed by a newc cpio with /a64-init and /a64-probe
//   (Linux takes concatenated cpio archives), rdinit=/a64-init mounts proc,
//   sys, devtmpfs and a tmpfs with Alpine's busybox, runs the probe with
//   "nodisk", lists /proc/interrupts and powers off. No virtio.
// - stage "single": initramfs-virt alone and Alpine's own init with
//   "single" (and a root that does not exist): it says "Entering single
//   mode" and opens a shell, which lists /proc/interrupts, echoes
//   A64_SINGLE_OK and powers off.
// - stage "lifecycle" (v86, P4.8): single mode to its shell, a snapshot
//   saved there and restored into a new machine where the shell goes on,
//   "reboot -f" (PSCI SYSTEM_RESET) back to single mode, "poweroff -f"
//   (SYSTEM_OFF) stopping the emulator.
// - stage "live": the ISO as a read-only virtio-blk disk, the probe in a
//   ustar image on a second virtio-blk disk with serial a64probe; Alpine's
//   initramfs finds the modloop and the packages on the ISO and boots to
//   "localhost login:", where the probe runs from the disk it reads.
//   A64_TRANSPORT=pci: the same devices as virtio-pci functions on the PCIe
//   host instead of virtio-mmio (P5.7; the reference's are non-transitional,
//   without MSI-X or an option ROM); both machines list their PCI functions
//   (A64_PCI: IDs, class, subsystem, pin and each BAR's place, size and
//   flags from /sys), which must be the reference's, for either transport.
//   The live stage has a virtio keyboard and tablet too (P5.8): on v86 the
//   test injects keys, a pointer position and a click, which the guest reads
//   from /dev/input/event* (dd and hexdump: struct input_event).
//   A64_LINUX_SLEEP=N (v86, the live stage; P8.1): after the probe, N
//   cycles of suspend to idle (s2idle) woken by the PL031's alarm, then N of
//   hibernation onto a swap disk (serial a64swap): the kernel powers off
//   (PSCI SYSTEM_OFF), the machine is powered on (V86.power_button: RAM
//   cleared) with resume=UUID=<the swap's> and the shell goes on in the
//   restored kernel; a tmpfs file's MD5 and the online CPUs are checked
//   after every cycle.
//   A64_LIVE_QCOW2=1 (v86, the live stage): the ISO's disk is a compressed
//   QCOW2 image of it (qemu-img convert -c, build/a64-linux/live-iso.qcow2),
//   read by the disk image layer (docs/disk-image-formats-plan.md).
//
// A64_KERNEL selects v86's kernel: 16k, 64k and androidish are
// tools/a64_kernel.mjs's (P8.6, P9.1, P9.2); gki is Android 16's GKI kernel
// from tools/a64_android.mjs (P10.6's bridge, on the reference too): the
// initramfs stage with the vendor ramdisk's virtual-device modules loaded
// before the probe, the virtio drivers they register checked against the
// reference's.
//
// A64_LINUX_QEMU=1 runs the fixed reference (QEMU 9.2.0 built from source,
// build/a64-ref or A64_QEMU, virt-9.2 with cortex-a35 and every default the
// plan names spelled out) and passes ref=qemu to the probe; A64_CORES (1, 2,
// 4), A64_LINUX_TIMEOUT (ms, 180000); A64_QEMU_PLUGINS=1 adds QEMU's insn and
// howvec plugins (the guest's instruction count and classes, P0.9).
// A64_LINUX_PREPARE_ONLY=1 only prepares
// the files and the manifest (build/a64-linux/manifest.json): the ISO, the
// kernel, the Image inside it, the initramfs, the probe and, after a QEMU
// run, the reference DTB (dumpdtb) and QEMU's version.
//
// The measurements (P0.9), in build/a64-linux/result-<tag>.json:
// boot_to_login_ms, from the start until "localhost login:" on the serial
// console (live stage); probe_done_ms, until the probe's A64_PROBE_XC line;
// with the plugins, the guest's retired instructions and their classes.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { gunzipSync as gunzip } from "node:zlib";
import { prepare, unzboot, sha256, ROOT } from "../lib/alpine_image.mjs";
import { QEMU_MACHINE, QEMU_CPU, qemu_binary, smp } from "./guest_runner.mjs";
import { aarch32_workload as stage_aarch32_workload } from "../lib/aarch32_workload.mjs";

const stage = process.env.A64_STAGE || "initramfs";
assert.ok(["initramfs", "single", "lifecycle", "live"].includes(stage), "A64_STAGE is initramfs, single, lifecycle or live");
const sleep_cycles = Number(process.env.A64_LINUX_SLEEP || 0);
assert.ok(!sleep_cycles || (process.env.A64_STAGE === "live" && !+process.env.A64_LINUX_QEMU), "A64_LINUX_SLEEP is a variant of v86's live stage");
const transport = process.env.A64_TRANSPORT || "mmio";
assert.ok(["mmio", "pci"].includes(transport), "A64_TRANSPORT is mmio or pci");
assert.ok(transport === "mmio" || stage === "live", "A64_TRANSPORT=pci is a variant of the live stage");
const cores = Number(process.env.A64_CORES || 1);
assert.ok([1, 2, 4, 8].includes(cores), "A64_CORES is 1, 2, 4 or 8");
const qemu_reference = !!+process.env.A64_LINUX_QEMU;
const config_name = "boot/config-6.18.35-0-virt";
const prepared = await prepare("aarch64-virt", ["boot/vmlinuz-virt", "boot/initramfs-virt", "boot/modloop-virt", config_name]);
const directory = prepared.directory;

function run(program, args, options = {})
{
    const result = spawnSync(program, args, { encoding: "utf8", ...options });
    assert.equal(result.status, 0, `${program} ${args.join(" ")}: ${result.stderr || result.error}`);
    return result.stdout.trim();
}

// the Image inside the zboot kernel (what QEMU's -kernel and v86's loader boot)
const image = unzboot(fs.readFileSync(prepared.kernel));

// the probe: clang for aarch64-unknown-linux-gnu, freestanding, rust-lld
const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
const probe_directory = directory + "probe/";
fs.mkdirSync(probe_directory + "root", { recursive: true });
run(process.env.CLANG || "clang", ["--target=aarch64-unknown-linux-gnu", "-O2", "-ffreestanding", "-fno-stack-protector",
    "-fno-pic", "-fno-builtin", "-c", ROOT + "tests/a64/linux_probe.c", "-o", probe_directory + "probe.o"]);
run(lld, ["-flavor", "gnu", "-m", "aarch64linux", "-static", "-e", "_start", "-o", probe_directory + "root/a64-probe", probe_directory + "probe.o"]);
fs.chmodSync(probe_directory + "root/a64-probe", 0o755);
// (rdinit: Alpine's initramfs has busybox but no applet links yet; the
// kernel passes what follows "--" on its command line to init)
fs.writeFileSync(probe_directory + "root/a64-init", [
    "#!/bin/busybox sh",
    "B=/bin/busybox",
    "$B mount -t proc proc /proc; $B mount -t sysfs sys /sys; $B mount -t devtmpfs dev /dev",
    "$B mkdir -p /tmp; $B mount -t tmpfs tmp /tmp",
    // (the androidish kernel's cpio, P9.1, P9.2: its tests before and after the probe)
    "[ -x /a64-android/pre ] && /a64-android/pre",
    "/a64-probe nodisk \"$@\"",
    "[ -x /a64-android/post ] && /a64-android/post",
    // (smpN: N copies of the workload at once, between two readings of the uptime: P8.2's speed-up)
    "case \"$A64_WORKLOAD\" in '') ;; jit) /a64-jit-workload ;; aarch32) /a64-aarch32-workload ;; " +
        "smp*) $B echo A64_SMP_START $($B cat /proc/uptime); for i in $($B seq 1 ${A64_WORKLOAD#smp}); do /a64-workload 3 > /dev/null & done; wait; " +
        "$B echo A64_SMP_END $($B cat /proc/uptime) ;; " +
        // (soakN, P8.4: N minutes of rounds of four workloads at once and the probe; a failing probe's output shows)
        "soak*) E=$(( $($B cut -d. -f1 /proc/uptime) + ${A64_WORKLOAD#soak} * 60 )); R=0; " +
        "while [ $($B cut -d. -f1 /proc/uptime) -lt $E ]; do for i in 1 2 3 4; do /a64-workload 1 > /dev/null & done; " +
        "/a64-probe nodisk \"$@\" > /tmp/soak.out 2>&1 || $B cat /tmp/soak.out; wait; R=$((R+1)); done; " +
        "$B echo A64_SOAK_DONE rounds=$R ;; *) /a64-workload \"$A64_WORKLOAD\" ;; esac",
    "$B cat /proc/interrupts",
    "for f in /sys/devices/system/cpu/vulnerabilities/*; do $B echo \"A64_VULN ${f##*/}: $($B cat $f)\"; done",
    "$B echo A64_INIT_DONE",
    "$B poweroff -f",
    ""].join("\n"), { mode: 0o755 });
// (A64_WORKLOAD=N on the command line: busybox and musl at work, N times
// over, between A64_WORKLOAD_BEGIN and A64_WORKLOAD_END: floating point in
// awk and printf, hashing, compression, sorting, sed; the output must equal
// the reference's, P2b, and tests/a64/trace_replay.mjs samples it, P2.10)
fs.writeFileSync(probe_directory + "root/a64-workload", [
    "#!/bin/busybox sh",
    "B=/bin/busybox",
    "N=${1:-1}",
    "$B echo A64_WORKLOAD_BEGIN",
    "$B awk -v n=$((N*20000)) 'BEGIN { s = 0; for (i = 1; i <= n; i++) s += sin(i) * sqrt(i) / (1 + log(i)); " +
        "printf \"awk-math %.12g %.6e %.9f %.15g\\n\", s, exp(10.5), atan2(1, 1) * 4, cos(0.5) ^ 3.5 }'",
    "$B awk -v n=$((N*5000)) 'BEGIN { for (i = 0; i < n; i++) { x = i * 0.1; s += x * x - int(x) / 3; t = t (i % 10) } " +
        "printf \"awk-loop %.10f %d %s %d\\n\", s, length(t), substr(t, 1, 20), index(t, \"789012\") }'",
    "$B seq 1 $((N*20000)) | $B sha256sum",
    "$B seq 1 $((N*20000)) | $B md5sum",
    "$B seq 1 $((N*5000)) | $B gzip -9 | $B gzip -d | $B sha1sum",
    "$B seq 1 $((N*3000)) | $B sort -rn | $B head -3 | $B tr '\\n' ' '; $B echo",
    "$B seq 1 $((N*2000)) | $B sed -e 's/1/one/g' -e 's/\\([0-9]\\)\\([0-9]\\)/\\2\\1/' | $B md5sum",
    "$B printf '%.6f %e %g %x %o\\n' 3.14159265 1234.5678 0.000012345 3735928559 511",
    "$B echo A64_WORKLOAD_END",
    ""].join("\n"), { mode: 0o755 });
const tar_args = ["--uid", "0", "--gid", "0", "--no-xattrs", "--no-mac-metadata"];
run("bsdtar", ["--format", "newc", ...tar_args, "-cf", probe_directory + "probe.cpio", "-C", probe_directory + "root", "a64-init", "a64-probe", "a64-workload"]);
run("bsdtar", ["--format", "ustar", ...tar_args, "-cf", probe_directory + "probe.tar", "-C", probe_directory + "root", "a64-probe"]);
const initrd_probe = probe_directory + "initramfs-virt+probe.cpio";
fs.writeFileSync(initrd_probe, Buffer.concat([fs.readFileSync(prepared.initrd), fs.readFileSync(probe_directory + "probe.cpio")]));

const manifest_file = directory + "manifest.json";
const manifest = {
    source: prepared.source, iso: prepared.image.name, iso_sha256: prepared.image.sha256,
    vmlinuz_sha256: sha256(fs.readFileSync(prepared.kernel)), image_sha256: sha256(image), image_bytes: image.length,
    initramfs_sha256: sha256(fs.readFileSync(prepared.initrd)), modloop_sha256: sha256(fs.readFileSync(directory + "boot/modloop-virt")),
    config_sha256: sha256(fs.readFileSync(directory + config_name)),
    probe_sha256: sha256(fs.readFileSync(probe_directory + "root/a64-probe")),
    probe_cpio_sha256: sha256(fs.readFileSync(probe_directory + "probe.cpio")),
    probe_tar_sha256: sha256(fs.readFileSync(probe_directory + "probe.tar")),
    ...(fs.existsSync(manifest_file) ? (({ qemu, dtb_sha256 }) => ({ qemu, dtb_sha256 }))(JSON.parse(fs.readFileSync(manifest_file, "utf8"))) : {}),
};
fs.writeFileSync(manifest_file, JSON.stringify(manifest, null, 2) + "\n");
if(+process.env.A64_LINUX_PREPARE_ONLY) process.exit(0);

// (A64_WORKLOAD=jit: the guest JIT workloads of docs/arm64-virt-android16-plan.md
// P6.7 between A64_WORKLOAD_BEGIN and A64_WORKLOAD_END: V8 in nodejs, HotSpot
// running `java Hello.java`, LuaJIT with -jon and -joff, PCRE2's JIT; sources
// in tests/a64/jit_workload/. Their packages (tools/alpine_repo.mjs --arch
// aarch64 --set jit) are unpacked into one more cpio after the probe's (no
// disk yet: P5), without the JDK's jmods; 1.5 GiB of RAM: the arm64 core takes less than 2 GiB)
const jit_workload = process.env.A64_WORKLOAD === "jit";
const JIT_EXCLUDED = ["openjdk21-jmods", "busybox", "busybox-binsh"];
let initrd = initrd_probe;
if(jit_workload)
{
    const { output_directory } = await import("../../tools/alpine_repo.mjs");
    const repo = path.join(output_directory("aarch64"), "jit-repo");
    assert.ok(fs.existsSync(repo), repo + " is missing: node tools/alpine_repo.mjs --arch aarch64 --set jit");
    const staging = directory + "jit-root/";
    fs.rmSync(staging, { recursive: true, force: true });
    fs.mkdirSync(staging + "jit", { recursive: true });
    for(const section of ["main", "community"])
    {
        const apks = path.join(repo, section, "aarch64");
        for(const file of fs.readdirSync(apks).filter(f => f.endsWith(".apk")).sort())
        {
            if(JIT_EXCLUDED.some(name => new RegExp(`^${name}-\\d`).test(file))) continue;
            run("bsdtar", ["-xf", path.join(apks, file), "-C", staging, "--exclude", ".PKGINFO", "--exclude", ".SIGN.*",
                "--exclude", ".*-install", "--exclude", ".*-upgrade", "--exclude", ".*-deinstall", "--exclude", ".trigger"]);
        }
    }
    for(const file of fs.readdirSync(ROOT + "tests/a64/jit_workload")) fs.copyFileSync(ROOT + "tests/a64/jit_workload/" + file, staging + "jit/" + file);
    fs.writeFileSync(staging + "a64-jit-workload", [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "export PATH=/usr/bin:/usr/sbin:/bin:/sbin HOME=/tmp TMPDIR=/tmp",
        "$B echo A64_WORKLOAD_BEGIN",
        "/usr/bin/node /jit/work.js 2>&1",
        "cd /tmp && /usr/lib/jvm/java-21-openjdk/bin/java -Xmx256m -XX:+UseSerialGC /jit/Hello.java 2>&1",
        "/usr/bin/luajit -jon /jit/work.lua 2>&1",
        "/usr/bin/luajit -joff /jit/work.lua 2>&1",
        "/usr/bin/pcre2test -C jit | $B cat; /usr/bin/pcre2test -jit /jit/pcre2.txt 2>&1 | $B cat",
        "$B echo A64_WORKLOAD_END",
        ""].join("\n"), { mode: 0o755 });
    run("bsdtar", ["--format", "newc", ...tar_args, "-cf", directory + "jit.cpio", "-C", staging, "."]);
    initrd = directory + "initramfs-virt+probe+jit.cpio";
    fs.writeFileSync(initrd, Buffer.concat([fs.readFileSync(initrd_probe), fs.readFileSync(directory + "jit.cpio")]));
}
// (A64_WORKLOAD=aarch32, docs/aarch32-plan.md Q5.1: 32-bit processes on the
// 64-bit kernel, between A64_WORKLOAD_BEGIN and A64_WORKLOAD_END:
// tests/a64/linux_probe32.c built for A32 and for T32, then Alpine's armv7
// programs (tools/alpine_repo.mjs --arch armv7 --set aarch32) in a chroot:
// BusyBox and musl's dynamic linker, Lua, xz, OpenSSL's digests and ciphers
// (the crypto instructions), SQLite, forks; v86 needs profile v3
// (A64_PROFILE=v3), the reference runs them as they are)
const aarch32_workload = process.env.A64_WORKLOAD === "aarch32";
assert.ok(!aarch32_workload || +process.env.A64_LINUX_QEMU || process.env.A64_PROFILE === "v3", "A64_WORKLOAD=aarch32 on v86 needs A64_PROFILE=v3");
if(aarch32_workload)
{
    const staging = directory + "aarch32-root/";
    await stage_aarch32_workload({ staging, objects: directory, run, lld, prefix: "a64" });
    run("bsdtar", ["--format", "newc", ...tar_args, "-cf", directory + "aarch32.cpio", "-C", staging, "."]);
    initrd = directory + "initramfs-virt+probe+aarch32.cpio";
    fs.writeFileSync(initrd, Buffer.concat([fs.readFileSync(initrd_probe), fs.readFileSync(directory + "aarch32.cpio")]));
}
const memory_mb = +process.env.A64_MEMORY_MB || (jit_workload ? 1536 : 512);
// (A64_EXTENDED_MEMORY=<bytes>: v86's extended RAM from 4 GiB, P8.5, the
// RAM below it A64_MEMORY_MB; A64_LINUX_MEMTEST=<MiB>: the initramfs stage's
// probe maps, writes and checks that much first, A64_MEMTEST)
const extended_memory = Number(process.env.A64_EXTENDED_MEMORY || 0);
// (A64_PARALLEL=1: v86's cores 1 and up in vCPU workers, P8.2; the probe's
// exclusive ABA is then only reported, the deviation docs/aarch64.md declares)
const parallel = !!+process.env.A64_PARALLEL;
assert.ok(!parallel || !+process.env.A64_LINUX_QEMU && cores > 1, "A64_PARALLEL is a variant of v86 on more than one core");
// (A64_KERNEL=16k|64k: v86 boots tools/a64_kernel.mjs's kernel of that page
// size, P8.6, the drivers the stages need built in; A64_KERNEL_FILE another
// Image. The probe must report the page size)
// (A64_KERNEL=gki, P10.6's bridge: Android's GKI kernel, tools/a64_android.mjs's,
// on the reference too, in the initramfs stage with the virtual-device modules
// of its vendor ramdisk loaded before the probe)
const kernel_variant = process.env.A64_KERNEL || "stock";
const PAGE_SIZES = { stock: 4096, "16k": 16384, "64k": 65536, androidish: 4096, gki: 4096 };
assert.ok(PAGE_SIZES[kernel_variant], "A64_KERNEL: stock, 16k, 64k, androidish or gki");
const gki = kernel_variant === "gki";
assert.ok(kernel_variant === "stock" || gki || !+process.env.A64_LINUX_QEMU, "A64_KERNEL is a variant of v86's runs (gki: of both)");
assert.ok(!gki || stage === "initramfs", "A64_KERNEL=gki: the initramfs stage");
const GKI_FILES = ROOT + "build/a64-android/out/";
const v86_kernel = process.env.A64_KERNEL_FILE ||
    (kernel_variant === "stock" ? prepared.kernel : gki ? GKI_FILES + "Image" : ROOT + `build/a64-kernel/${kernel_variant}/Image`);
assert.ok(fs.existsSync(v86_kernel), v86_kernel + " is missing: node tools/" + (gki ? "a64_android.mjs" : "a64_kernel.mjs"));
// (A64_KERNEL=androidish, the initramfs stage, P9.1, P9.2: the programs and
// images built with it in one more cpio, under /a64-android with the
// scripts a64-init runs before and after the probe, a bootconfig after the
// initrd, an f2fs disk. Before the probe: f2fs with fscrypt (the first boot
// writes and reboots, the second reads, without the key and with it),
// /proc/bootconfig, the minimal SELinux policy, enforcing from then on.
// After it: binderfs's selftest, binder between the first and the last CPU,
// userfaultfd, erofs on dm-verity (and the same tree over an image with one
// byte changed: reads fail), zram as swap under a 16 MiB memory cgroup with
// PSI's trigger)
const android = kernel_variant === "androidish" && stage === "initramfs";
const ANDROID_FILES = ROOT + "build/a64-kernel/androidish/";
const ANDROID_PROGRAMS = ["binder_pingpong", "binderfs_test", "uffd_test", "selinux_load", "dm_verity", "fscrypt_test", "psi_test"];
const BOOTCONFIG = { "androidboot.hardware": "v86", "androidboot.serialno": "a64-p9", "kernel.printk.devkmsg": "on" };
const VERITY_SALT = Buffer.alloc(32, 0xa6);
let android_expect, f2fs_disk;
/**
 * dm-verity's hash tree, format 1 (the salt before each block), SHA-256,
 * 4 KiB blocks, the top level first (hash_start 0), as veritysetup lays it out
 * @param {!Buffer} data more than one block
 * @return {{tree: !Buffer, root: !Buffer}}
 */
function verity_tree(data)
{
    const BLOCK = 4096, PER_BLOCK = BLOCK / 32;
    assert.ok(data.length > BLOCK && data.length % BLOCK === 0, "verity: whole blocks, more than one");
    const digest = block => create_hash("sha256").update(VERITY_SALT).update(block).digest();
    let digests = [];
    for(let at = 0; at < data.length; at += BLOCK) digests.push(digest(data.subarray(at, at + BLOCK)));
    const levels = [];
    while(digests.length > 1)
    {
        const blocks = [];
        for(let i = 0; i < digests.length; i += PER_BLOCK) blocks.push(Buffer.concat(digests.slice(i, i + PER_BLOCK), BLOCK));
        levels.push(Buffer.concat(blocks));
        digests = blocks.map(digest);
    }
    return { tree: Buffer.concat(levels.reverse()), root: digests[0] };
}
/** The initrd with a bootconfig after it: the text, its NUL, padding to 4 bytes, size, checksum, magic (tools/bootconfig) */
function with_bootconfig(initrd_bytes, keys)
{
    const text = Buffer.from(Object.entries(keys).map(([key, value]) => `${key} = "${value}"\n`).join("") + "\0");
    const pad = (4 - (initrd_bytes.length + text.length + 8 + 12) % 4) % 4;
    const data = Buffer.concat([text, Buffer.alloc(pad)]);
    const footer = Buffer.alloc(8);
    footer.writeUInt32LE(data.length, 0);
    footer.writeUInt32LE(data.reduce((sum, byte) => sum + byte, 0) >>> 0, 4);
    return Buffer.concat([initrd_bytes, data, footer, Buffer.from("#BOOTCONFIG\n")]);
}
if(android)
{
    const staging = directory + "android-root/";
    fs.rmSync(staging, { recursive: true, force: true });
    fs.mkdirSync(staging + "a64-android", { recursive: true });
    const put = (name, bytes, mode = 0o644) => fs.writeFileSync(staging + "a64-android/" + name, bytes, { mode });
    for(const name of [...ANDROID_PROGRAMS, "policy.33", "erofs.img", "f2fs.img.gz"])
    {
        assert.ok(fs.existsSync(ANDROID_FILES + name), ANDROID_FILES + name + " is missing: node tools/a64_kernel.mjs --variants androidish");
    }
    for(const program of ANDROID_PROGRAMS) put(program, fs.readFileSync(ANDROID_FILES + program), 0o755);
    put("policy.33", fs.readFileSync(ANDROID_FILES + "policy.33"));
    // (erofs, its tree, and a copy with one byte of the payload changed in the middle)
    const erofs = fs.readFileSync(ANDROID_FILES + "erofs.img");
    const { tree, root } = verity_tree(erofs);
    const bad = Buffer.from(erofs);
    const middle = bad.indexOf("\n20000\n");
    assert.ok(middle > 0, "the payload's middle in erofs.img");
    bad[middle + 1] ^= 1;
    put("erofs.img", erofs);
    put("erofs-bad.img", bad);
    put("erofs.hash", tree);
    const table = (data, hash) => `${erofs.length / 512} 1 ${data} ${hash} 4096 4096 ${erofs.length / 4096} 0 sha256 ` +
        `${root.toString("hex")} ${VERITY_SALT.toString("hex")}\n`;
    put("verity-good", table("/dev/loop0", "/dev/loop1"));
    put("verity-bad", table("/dev/loop2", "/dev/loop3"));
    const payload = Array.from({ length: 40000 }, (_, i) => i + 1).join("\n") + "\n";
    android_expect = { payload_sha256: sha256(payload), erofs_sha256: sha256(erofs), bad_block: Math.floor((middle + 1) / 4096) };
    put("pre", [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "A=/a64-android",
        "F=; for d in /sys/block/vd*; do [ \"$($B cat $d/serial 2>/dev/null)\" = a64f2fs ] && F=/dev/${d##*/}; done",
        "$B mkdir -p /mnt/f2fs",
        "if $B mount -t f2fs $F /mnt/f2fs; then",
        "    if [ ! -e /mnt/f2fs/enc ] && $A/fscrypt_test setup /mnt/f2fs; then",
        "        $B umount /mnt/f2fs; $B sync; $B echo A64_REBOOTING; $B reboot -f; $B sleep 600",
        "    fi",
        "    $A/fscrypt_test verify /mnt/f2fs; $B umount /mnt/f2fs",
        "else $B echo A64_FSCRYPT_FAIL mount; fi",
        "$B sed 's/^/A64_BOOTCONFIG /' /proc/bootconfig",
        "$B echo \"A64_CMDLINE $($B cat /proc/cmdline)\"",
        "$A/selinux_load $A/policy.33",
        ""].join("\n"), 0o755);
    put("post", [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "A=/a64-android",
        "$B mkdir -p /dev/binderfs && $B mount -t binder binder /dev/binderfs && " +
            "$A/binderfs_test 2>&1 | $B grep -E '^(ok|not ok|# Totals|# FAILED|# [a-z_]+: Test|# binderfs_test\\.c:)'",
        "$A/binder_pingpong /dev/binderfs 10000 0 $(( $($B nproc) - 1 ))",
        "$A/uffd_test 64",
        "$B losetup -r /dev/loop0 $A/erofs.img && $B losetup -r /dev/loop1 $A/erofs.hash && " +
            "$B losetup -r /dev/loop2 $A/erofs-bad.img && $B losetup -r /dev/loop3 $A/erofs.hash",
        "G=$($A/dm_verity a64verity $($B cat $A/verity-good)) && $B mkdir -p /mnt/erofs && $B mount -t erofs -o ro $G /mnt/erofs && " +
            "$B echo \"A64_EROFS $G $($B sha256sum < /mnt/erofs/payload.txt | $B cut -d' ' -f1) $($B cat /mnt/erofs/hello.txt) " +
            "$($B dd if=$G bs=4096 2>/dev/null | $B sha256sum | $B cut -d' ' -f1)\"",
        "X=$($A/dm_verity a64verity_bad $($B cat $A/verity-bad)) && " +
            "if $B dd if=$X of=/dev/null bs=4096 2>/dev/null; then $B echo \"A64_VERITY_BAD $X read\"; else $B echo \"A64_VERITY_BAD $X eio\"; fi",
        "$B mount -t cgroup2 cgroup2 /sys/fs/cgroup && $B echo +memory > /sys/fs/cgroup/cgroup.subtree_control && " +
            "$B mkdir /sys/fs/cgroup/a64 && $B echo 16M > /sys/fs/cgroup/a64/memory.max",
        "$B echo 256M > /sys/block/zram0/disksize && $B mkswap /dev/zram0 > /dev/null && $B swapon /dev/zram0",
        "$A/psi_test /sys/fs/cgroup/a64 40",
        "$B echo \"A64_MEMINFO $($B grep MemTotal /proc/meminfo)\"",
        ""].join("\n"), 0o755);
    run("bsdtar", ["--format", "newc", ...tar_args, "-cf", directory + "android.cpio", "-C", staging, "."]);
    const combined = directory + "initramfs-virt+probe+android.cpio";
    fs.writeFileSync(combined, with_bootconfig(Buffer.concat([fs.readFileSync(initrd), fs.readFileSync(directory + "android.cpio")]), BOOTCONFIG));
    initrd = combined;
    // (a fresh copy of the 64 MiB f2fs, made with the encrypt feature, for each run)
    const f2fs = gunzip(fs.readFileSync(ANDROID_FILES + "f2fs.img.gz"));
    f2fs_disk = f2fs.buffer.slice(f2fs.byteOffset, f2fs.byteOffset + f2fs.byteLength);
}
// (A64_KERNEL=gki: the modules in one more cpio, loaded before the probe as
// modprobe would load modules.load's: each one's modules.dep first, with
// their modules.options)
let gki_modules = 0;
if(gki)
{
    const staging = directory + "gki-root/";
    fs.rmSync(staging, { recursive: true, force: true });
    fs.mkdirSync(staging + "a64-gki", { recursive: true });
    fs.mkdirSync(staging + "a64-android");
    const load = fs.readFileSync(GKI_FILES + "modules/modules.load", "utf8").trim().split("\n");
    const deps = new Map(fs.readFileSync(GKI_FILES + "modules/modules.dep", "utf8").trim().split("\n").map(line => {
        const [name, list] = line.split(":");
        return [path.basename(name), list.trim().split(/\s+/).filter(Boolean).map(d => path.basename(d))];
    }));
    const order = [];
    const visit = name => { if(order.includes(name)) return; for(const d of [...(deps.get(name) || [])].reverse()) visit(d); order.push(name); };
    load.forEach(visit);
    gki_modules = order.length;
    for(const name of [...order, "modules.options"]) fs.copyFileSync(GKI_FILES + "modules/" + name, staging + "a64-gki/" + name);
    fs.writeFileSync(staging + "a64-gki/order", order.join("\n") + "\n");
    fs.writeFileSync(staging + "a64-android/pre", [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "N=0",
        "for m in $($B cat /a64-gki/order); do",
        "    O=$($B grep \"^options ${m%.ko} \" /a64-gki/modules.options | $B cut -d' ' -f3-)",
        "    if $B insmod /a64-gki/$m $O; then N=$((N+1)); else $B echo \"A64_GKI_FAIL $m\"; fi",
        "done",
        "$B echo \"A64_GKI_MODULES loaded=$N virtio=$($B ls /sys/bus/virtio/drivers | $B tr '\\n' ,) $($B uname -r)\"",
        ""].join("\n"), { mode: 0o755 });
    run("bsdtar", ["--format", "newc", ...tar_args, "-cf", directory + "gki.cpio", "-C", staging, "."]);
    const combined = directory + "initramfs-virt+probe+gki.cpio";
    fs.writeFileSync(combined, Buffer.concat([fs.readFileSync(initrd), fs.readFileSync(directory + "gki.cpio")]));
    initrd = combined;
}
const PARALLEL_OPTIONS = parallel ? { parallel: true, parallel_wasm_path: process.env.A64_PARALLEL_WASM || ROOT + "build/v86-arm64-parallel.wasm" } : {};
const memtest_mib = Number(process.env.A64_LINUX_MEMTEST || 0);
const EXTENDED_BASE = 0x100000000;
assert.ok(!(extended_memory || memtest_mib) || stage === "initramfs" && !+process.env.A64_LINUX_QEMU,
    "A64_EXTENDED_MEMORY and A64_LINUX_MEMTEST are variants of v86's initramfs stage");
const soak_minutes = /^soak\d+$/.test(process.env.A64_WORKLOAD || "") ? +process.env.A64_WORKLOAD.slice(4) : 0;
const timeout = Number(process.env.A64_LINUX_TIMEOUT || (soak_minutes ? (soak_minutes + 10) * 60000 :
    jit_workload ? 3600000 : aarch32_workload ? 1800000 : stage === "live" ? 1800000 : android ? 900000 : 180000));
// (a root that does not exist: init looks for it, then enters single mode before mounting it)
const SINGLE_CMDLINE = "console=ttyAMA0 earlycon nokaslr panic=-1 single root=/dev/vda";
const SINGLE_COMMANDS = "cat /proc/interrupts; echo A64_SINGLE_$((6*7)) && echo A64_SINGLE_OK; /bin/busybox poweroff -f\n";
// (the live stage: from the ISO on virtio-blk, modloop's modules; logged in
// as root, the probe from the disk whose serial is a64probe)
const LIVE_CMDLINE = "console=ttyAMA0 earlycon nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage";
// (the live stage's devices besides the disks, on both machines in this
// order: virtio-net, virtio-rng, virtio-console; v86 echoes the probe's raw
// frames and lets the test log in on hvc0, then A64_LIVE_PROBED ends the
// first part; QEMU, without a host side for either, goes straight on)
// (the PCI functions, from /sys: vendor, device, class, subsystem, revision, interrupt pin, each BAR's start, end and flags)
const PCI_LIST = "for d in /sys/bus/pci/devices/*; do echo A64_PCI ${d##*/} $(cat $d/vendor $d/device $d/class $d/subsystem_vendor " +
    "$d/subsystem_device $d/revision) pin=$(od -An -tu1 -j61 -N1 $d/config | tr -d ' ') $(awk 'NR <= 7 && $1 != \"0x0000000000000000\" " +
    "{ printf \"bar%d=%s-%s/%s \", NR - 1, $1, $2, $3 }' $d/resource); done; ";
const pci_functions = text => [...text.matchAll(/^A64_PCI ([0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.\d [^\r\n]*)/gm)].map(m => m[1].trim());
const LIVE_COMMANDS = ref => PCI_LIST + "modprobe virtio_net 2>/dev/null; modprobe virtio-rng 2>/dev/null; ifconfig eth0 up; " +
    "for d in /sys/block/vd*; do [ \"$(cat $d/serial 2>/dev/null)\" = a64probe ] && tar -xf /dev/${d##*/} -C /tmp; done; " +
    `/tmp/a64-probe ${ref === "v86" ? "net " : ""}${ref === "v86" && parallel ? "parallel " : ""}ref=${ref}; echo A64_HWRNG=$(head -c 64 /dev/hwrng | wc -c); ` +
    "cat /proc/cpuinfo | head -12; cat /proc/interrupts; " +
    "for f in /sys/devices/system/cpu/vulnerabilities/*; do echo \"A64_VULN ${f##*/}: $(cat $f)\"; done; " +
    (ref === "v86" ? INPUT_COMMANDS + VPORT_COMMANDS + "(/sbin/getty -L hvc0 115200 vt100 &); echo A64_LIVE_PROBED\n" : "echo A64_LIVE_DONE; poweroff -f\n");
// (P9.1: virtio-console's ports 1-3, generic ports named org.v86.port<N>,
// found under /sys/class/virtio-ports, whose device numbers follow the
// enumeration: a line to each, which the host echoes)
const VPORT_COMMANDS = "for d in /sys/class/virtio-ports/vport*; do n=$(cat $d/name 2>/dev/null); case \"$n\" in org.v86.port*) " +
    "exec 3<>/dev/${d##*/}; echo \"VPING_${n#org.v86.port}\" >&3; read -t 5 r <&3; echo \"A64_VPORT $n ${d##*/} $r\"; exec 3<&-;; esac; done; ";
const LIVE_FINISH = "echo A64_LIVE_DONE; poweroff -f\n";
// (virtio-input, P5.8: each device's events as hex, 24 bytes each, while the test injects them after A64_INPUT_READY)
const input_reader = (name, count, tag) => `(dd if=/dev/input/$${name} bs=24 count=${count} 2>/dev/null | ` +
    `hexdump -v -e '24/1 "%02x" "\\n"' | sed 's/^/${tag} /') & `;
const INPUT_COMMANDS = "modprobe evdev 2>/dev/null; modprobe virtio_input 2>/dev/null; sleep 1; K=; T=; " +
    "for e in /sys/class/input/event*; do case \"$(cat $e/device/name)\" in *Keyboard) K=${e##*/};; *Tablet) T=${e##*/};; esac; done; " +
    input_reader("K", 8, "A64_EVK") + input_reader("T", 7, "A64_EVT") + "sleep 1; echo A64_INPUT_READY; wait; ";
/** The events (type, code, value) of `tag`'s lines */
const input_events = (text, tag) => [...text.matchAll(new RegExp(`^${tag} ([0-9a-f]{48})`, "gm"))].map(m => {
    const b = Buffer.from(m[1], "hex");
    return [b.readUInt16LE(16), b.readUInt16LE(18), b.readInt32LE(20)];
});
// (A64_KPTI=1: the initramfs stage with kpti=1, KPTI forced on although CSV3 says it is not needed, P3.9)
const kpti = !!+process.env.A64_KPTI;
assert.ok(!kpti || stage === "initramfs", "A64_KPTI is a variant of the initramfs stage");
// (A64_WORKLOAD=N: the initramfs stage runs /a64-workload N after the probe;
// A64_WORKLOAD=jit: the guest JIT workloads, aarch32: 32-bit processes, below)
const workload = ["jit", "aarch32"].includes(process.env.A64_WORKLOAD) ? process.env.A64_WORKLOAD : /^(smp|soak)\d+$/.test(process.env.A64_WORKLOAD || "") ?
    process.env.A64_WORKLOAD : +process.env.A64_WORKLOAD || 0;
assert.ok(!workload || stage === "initramfs", "A64_WORKLOAD is a variant of the initramfs stage");
// (androidish: bootconfig, and pseudo-NMIs, GKI's: interrupts masked by the GIC's priority mask, not PSTATE.I)
const INITRAMFS_CMDLINE = ref => `console=ttyAMA0 earlycon nokaslr panic=-1${kpti ? " kpti=1" : ""}` +
    `${android ? " bootconfig irqchip.gicv3_pseudo_nmi=1" : ""}` +
    `${workload ? " A64_WORKLOAD=" + workload : ""}${ref === "v86" ? V86_WATCHDOG : ""} rdinit=/a64-init -- ref=${ref}${ref === "v86" && parallel ? " parallel" : ""}` +
    `${ref === "v86" && process.env.A64_PROFILE === "v3" ? " aarch32" : ""}` +
    `${memtest_mib ? " memtest=" + memtest_mib : ""}${extended_memory ? " high=" + EXTENDED_BASE / 4096 : ""}`;
// (A64_JIT=1: the v86 runs with the A64 page tier, docs/jit-unification-plan.md J2;
// A64_JIT_HOT its compile threshold)
const jit = !!+process.env.A64_JIT;
// (v86 interpreted on more than one core: the guest's clock is the host's,
// so every core's timer ticks share the one host thread for the whole slow
// boot; the jitter entropy self-test then takes 17-18 s on 4 cores, beyond
// the soft lockup threshold's 20 s whenever the host is busy. 60 s here; a
// core that hangs is still reported, or misses the run's deadline)
const V86_WATCHDOG = !jit && cores > 1 ? " watchdog_thresh=30" : "";
// A64_PROFILE: the CPU profile by its short name (v86-aarch64-v1, -v1.1, v2
// with FEAT_PAN, the default, or v3 with AArch32 at EL0), run as its CPU model
const A64_CPU_PROFILES = { "v1": "generic-arm64-v1", "v1.1": "generic-arm64-v1.1", "v2": "generic-arm64", "v3": "generic-arm64-compat32" };
assert.ok(!process.env.A64_PROFILE || A64_CPU_PROFILES[process.env.A64_PROFILE], "A64_PROFILE is v1, v1.1, v2 or v3");
const PROFILE_OPTIONS = process.env.A64_PROFILE ? { cpu_profile: A64_CPU_PROFILES[process.env.A64_PROFILE] } : {};
const profile_name = process.env.A64_PROFILE || "v2";
const JIT_OPTIONS = jit ? { jit_switches: { a64_page: 1, ...(process.env.A64_JIT_HOT ? { a64_page_hot: +process.env.A64_JIT_HOT } : {}),
    ...(process.env.A64_JIT_SWITCHES ? Object.fromEntries(process.env.A64_JIT_SWITCHES.split(",").map(p => [p.split("=")[0], +p.split("=")[1]])) : {}) } } : {};
const tag_of = target => `${target}${target === "v86" && jit ? "-jit" : ""}-${stage}${transport === "pci" ? "-pci" : ""}` +
    `${kpti ? "-kpti" : ""}${workload ? "-wl" + workload : ""}${target === "v86" && sleep_cycles ? "-sleep" : ""}` +
    `${extended_memory ? "-ext" + Math.round((memory_mb * 1048576 + extended_memory) / 1048576) + "m" : ""}` +
    `${target === "v86" && parallel ? "-par" : ""}${(target === "v86" || gki) && kernel_variant !== "stock" ? "-" + kernel_variant : ""}-${cores}c`;
// (without the kernel's messages, which may land between the workload's lines)
const workload_output = text => text.match(/A64_WORKLOAD_BEGIN\r?\n([\s\S]*?)A64_WORKLOAD_END/)?.[1].replace(/\r/g, "")
    .split("\n").filter(line => !/^\[\s*\d+\.\d+\] /.test(line)).join("\n");
const tag = tag_of(qemu_reference ? "qemu" : "v86");

// The "CPU features: detected" lines may differ from the reference's only
// where the profile's register differences lead (tests/platform/a64-profile.json):
// the reference's 32-bit EL0 and EL1 (no AArch32 in v1); Spectre-v4 and
// Spectre-BHB on v86, whose MIDR is on none of Linux's safe lists (the
// reference's Cortex-A35 is on all of them)
// (profile v3 has AArch32 at EL0: "32-bit EL0 Support" on both)
const FEATURES_ONLY_ON_REFERENCE = profile_name === "v3" ? ["32-bit EL1 Support"] : ["32-bit EL0 Support", "32-bit EL1 Support"];
// (and profile v2's own, which v3 has too, tests/platform/a64-profile.json: the reference has not got them)
const FEATURES_ONLY_ON_V86 = ["Spectre-v4", "Spectre-BHB",
    ...(profile_name === "v2" || profile_name === "v3" ? JSON.parse(fs.readFileSync(ROOT + "tests/platform/a64-profile.json", "utf8")).v2.linux_cpu_features : [])];
const detected = text => [...new Set([...text.matchAll(/CPU features: detected: ([^\r\n]+)/g)].map(m => m[1].trim()))].sort();

/** The probe's lines in `text`, judged against `cores` and the stage */
function check_probe(text, reference)
{
    const fail = text.match(/A64_PROBE_FAIL[^\r\n]*/);
    assert.ok(!fail, fail?.[0]);
    const ok = text.match(/A64_PROBE_OK arch=aarch64 cpus=(\d+) threads=(\d+) counter=(\d+) cpu_checks=([\d,]+) fault=page esr=(\w+) child=7 tlb_stale=(\d+) page_size=(\d+)[^\r\n]* high_pages=(\d+)/);
    assert.ok(ok, "no A64_PROBE_OK line");
    assert.deepEqual(ok.slice(1, 4).map(Number), [cores, cores, cores * 20000], "CPUs, threads and the exclusive counter");
    if(!reference) assert.equal(+ok[7], PAGE_SIZES[kernel_variant], "the kernel's page size (AT_PAGESZ)");
    assert.equal(ok[4], Array.from({ length: cores }, (_, i) => i).join(","), "each thread on its CPU");
    assert.equal(+ok[6], 0, "no stale TLB entry after the remap");
    const xc = text.match(/A64_PROBE_XC arch=aarch64 packages=1 cores=(\d+) threads_per_core=1 migrations=(\d+) signals=(\d+) smc_rounds=(\d+) dual_map=(\d+) excl_aba=(\d) futex=(\d+) clocks=1 fp_threads=(\d+) fp_steps=(\d+) fp_bad=(\d+) aarch32=(\w+) direct_io=(\d)/);
    assert.ok(xc, "no A64_PROBE_XC line");
    assert.deepEqual([xc[1], xc[2], xc[3], xc[4], xc[5]].map(Number), [cores, cores * 24, cores * 16, 64, 64], "topology, migrations, signals, cross-modified and dual-mapped code");
    assert.deepEqual([+xc[8], +xc[9], +xc[10]], [2 * cores, 2 * cores * 20, 0], "FPCR, FPSR and V0-V31 across context switches");
    assert.equal(+xc[12], stage === "initramfs" ? 0 : 1, "O_DIRECT read of the probe disk");
    if(!reference && !parallel) assert.equal(xc[6], "1", "exclusive ABA: the store-exclusive fails");
    // (AArch32 at EL0: the reference's, profile v3's; ENOEXEC before it)
    if(!reference) assert.equal(xc[11], profile_name === "v3" ? "ran" : "enoexec", "the AArch32 ELF (profile " + profile_name + ")");
    return { ok: ok[0], xc: xc[0] };
}

/** P10.6: every module of modules.load loaded; the virtio drivers they register */
function check_gki(text)
{
    const m = text.match(/A64_GKI_MODULES loaded=(\d+) virtio=(\S*) (\S+)/);
    assert.ok(m, "no A64_GKI_MODULES line");
    assert.equal(+m[1], gki_modules, "the GKI modules loaded: " + ([...text.matchAll(/A64_GKI_FAIL[^\r\n]*/g)].map(f => f[0]).join(", ") || "-"));
    return { gki_modules: +m[1], virtio_drivers: m[2], kernel_release: m[3] };
}

if(qemu_reference)
{
    const qemu = qemu_binary();
    const version = run(qemu, ["--version"]).split("\n")[0];
    assert.match(version, /QEMU emulator version 9\.2\./, "the fixed reference is QEMU 9.2.x");
    const machine = QEMU_MACHINE;
    // (virtio-mmio, or non-transitional virtio-pci functions without MSI-X)
    // (virtio-input is non-transitional anyway: virtio-*-pci)
    const device = (name, options) => (transport === "pci" ? name + (/keyboard|tablet/.test(name) ? "-pci" : "-pci-non-transitional") +
        ",vectors=0" : name + "-device") + (options ? "," + options : "");
    const base = ["-cpu", QEMU_CPU, "-m", memory_mb + "M", "-smp", smp(cores),
        "-global", "virtio-mmio.force-legacy=false", "-display", "none", "-no-reboot"];
    // the DTB QEMU gives this machine (dumpdtb), once
    const dtb = directory + `qemu-virt-${cores}c.dtb`;
    run(qemu, ["-machine", machine + ",dumpdtb=" + dtb, ...base, "-kernel", prepared.kernel]);
    if(cores === 1) Object.assign(manifest, { qemu: version, dtb_sha256: sha256(fs.readFileSync(dtb)) });
    fs.writeFileSync(manifest_file, JSON.stringify(manifest, null, 2) + "\n");
    const live = stage === "live", single = stage === "single";
    const args = ["-machine", machine, ...base, "-serial", "stdio", "-monitor", "none", "-kernel", gki ? v86_kernel : prepared.kernel,
        "-initrd", live || single ? prepared.initrd : initrd,
        "-append", live ? LIVE_CMDLINE
            : single ? SINGLE_CMDLINE : INITRAMFS_CMDLINE("qemu"),
        ...(live ? ["-drive", `if=none,id=iso,file=${prepared.iso},format=raw,readonly=on`, "-device", device("virtio-blk", "drive=iso"),
            "-drive", `if=none,id=probe,file=${probe_directory}probe.tar,format=raw,snapshot=on`, "-device", device("virtio-blk", "drive=probe,serial=a64probe"),
            // (the same devices as v86's, in its order; their host sides are empty)
            "-netdev", "hubport,id=net0,hubid=0", "-device", device("virtio-net", "netdev=net0" + (transport === "pci" ? ",romfile=" : "")),
            "-device", device("virtio-rng"), "-chardev", "null,id=hvc", "-device", device("virtio-serial"), "-device", "virtconsole,chardev=hvc",
            "-device", device("virtio-keyboard"), "-device", device("virtio-tablet")] : [])];
    const plugins = !!+process.env.A64_QEMU_PLUGINS;
    const plugin_log = directory + `${tag}-plugins.log`;
    if(plugins)
    {
        const qemu_build = path.dirname(qemu) + "/../../qemu-9.2.0/build/";
        const library = name => [".dylib", ".so"].map(suffix => qemu_build + name + suffix).find(file => fs.existsSync(file));
        const insn = library("tests/tcg/plugins/libinsn"), howvec = library("contrib/plugins/libhowvec");
        assert.ok(insn && howvec, "QEMU's insn and howvec plugins are missing: tools/a64_qemu/build.sh");
        // (-icount: the guest's clock follows its instructions, 1 ns each, so
        // the plugins' slowdown does not lengthen time-driven loops)
        args.push("-plugin", insn, "-plugin", howvec, "-d", "plugin", "-D", plugin_log, "-icount", "shift=0,sleep=on");
    }
    const child = spawn(qemu, args, { stdio: ["pipe", "pipe", "pipe"] });
    let transcript = "", logged_in = false, ran = false, login_ms, probe_ms;
    const started = performance.now();
    let timer;
    try
    {
        await new Promise((resolve, reject) => {
            timer = setTimeout(() => reject(new Error(`QEMU ${stage} deadline (${timeout} ms)`)), timeout);
            child.on("error", reject);
            child.on("exit", code => (/A64_INIT_DONE|A64_LIVE_DONE|A64_SINGLE_42\r?\nA64_SINGLE_OK/.test(transcript) ? resolve() : reject(new Error(`QEMU exited ${code}`))));
            const output = bytes => {
                transcript += bytes;
                if(single && /Entering single mode[^\n]*\n/.test(transcript) && !ran)
                {
                    ran = true;
                    child.stdin.write(SINGLE_COMMANDS);
                }
                if(probe_ms === undefined && transcript.includes("A64_PROBE_XC")) probe_ms = Math.round(performance.now() - started);
                if(live && !logged_in && /localhost login: ?$/.test(transcript))
                {
                    login_ms = Math.round(performance.now() - started);
                    logged_in = true;
                    child.stdin.write("root\n");
                }
                if(live && logged_in && !ran && /localhost:~# ?$/.test(transcript))
                {
                    ran = true;
                    child.stdin.write(LIVE_COMMANDS("qemu"));
                }
            };
            child.stdout.on("data", output);
            child.stderr.on("data", output);
        });
    }
    finally
    {
        clearTimeout(timer);
        child.kill();
        fs.writeFileSync(directory + `${tag}.log`, transcript);
    }
    const lines = single ? { single: /A64_SINGLE_42\r?\nA64_SINGLE_OK/.test(transcript) } : check_probe(transcript, true);
    if(gki) Object.assign(lines, check_gki(transcript));
    if(live) assert.match(transcript, /\nA64_HWRNG=64\r?\n/, "64 bytes from /dev/hwrng (virtio-rng)");
    if(live) lines.pci = pci_functions(transcript);
    const result = { tag, ms: Math.round(performance.now() - started), boot_to_login_ms: login_ms, probe_done_ms: probe_ms, ...lines,
        login: live ? /localhost login:/.test(transcript) : undefined };
    if(plugins)
    {
        const log = fs.readFileSync(plugin_log, "utf8");
        result.instructions = Number(log.match(/total insns: (\d+)/)?.[1]);
        result.classes = Object.fromEntries([...log.matchAll(/^Class: (.+?)\s+\((\d+) hits\)/gm)].map(m => [m[1].trim(), +m[2]]));
    }
    fs.writeFileSync(directory + `result-${tag}.json`, JSON.stringify({ ...manifest, ...result }, null, 2) + "\n");
    console.log(JSON.stringify(result));
    console.log(`A64_LINUX_BOOT_OK ${tag}`);
    process.exit(0);
}
// ---- v86 (the ARM core; P4.7): the same kernel, initrd and command line
const v86_options = {
    cpu_type: "arm64", graphics_adapter: "none", cpu_cores: cores, memory_size: 512 << 20, log_level: 0,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm", ...JIT_OPTIONS, ...PROFILE_OPTIONS, ...PARALLEL_OPTIONS,
};
if(stage === "lifecycle")
{
    const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    const options = { ...v86_options, kernel: { url: v86_kernel }, initrd: { url: prepared.initrd }, cmdline: SINGLE_CMDLINE + V86_WATCHDOG };
    let transcript = "";
    const started = performance.now();
    const attach = emulator => emulator.add_listener("serial0-output-byte", byte => { transcript += String.fromCharCode(byte); });
    const wait_for = (pattern, what, ms = timeout) => new Promise((resolve, reject) => {
        const t0 = transcript.length;
        const timer = setTimeout(() => reject(new Error(`v86 lifecycle: no ${what} after ${ms} ms:\n${transcript.slice(-1500)}`)), ms);
        const poll = setInterval(() => {
            if(pattern.test(transcript.slice(t0)))
            {
                clearInterval(poll);
                clearTimeout(timer);
                resolve();
            }
        }, 20);
    });
    // (the prompt: "~ # ", then busybox asks the terminal where the cursor is)
    const marks = {};
    const first = new V86({ ...options, autostart: true });
    attach(first);
    await wait_for(/Entering single mode[^\n]*\n[\s\S]*# /, "single mode's prompt");
    marks.single_ms = Math.round(performance.now() - started);
    // (a snapshot at the prompt, restored into a new machine)
    await first.stop();
    const saved = await first.save_state();
    await first.destroy();
    marks.state_bytes = saved.byteLength;
    const second = new V86({ ...options, autostart: false });
    await new Promise(resolve => second.add_listener("emulator-loaded", resolve));
    await second.restore_state(saved);
    attach(second);
    second.run();
    second.serial0_send("echo A64_RESTORED_$((6*7))\n");
    await wait_for(/A64_RESTORED_42/, "the restored shell's answer", 60000);
    marks.restored = true;
    // (PSCI SYSTEM_RESET: the kernel loads again and boots to single mode again)
    second.serial0_send("/bin/busybox reboot -f\n");
    await wait_for(/Entering single mode[^\n]*\n[\s\S]*# /, "single mode after the reboot");
    marks.rebooted = true;
    // (PSCI SYSTEM_OFF: the emulator stops)
    const stopped = new Promise(resolve => second.add_listener("emulator-stopped", resolve));
    second.serial0_send("/bin/busybox poweroff -f\n");
    await Promise.race([stopped, new Promise((_, reject) => setTimeout(() => reject(new Error("no emulator-stopped after poweroff")), 60000))]);
    marks.powered_off = second.v86.cpu.powered_off();
    assert.ok(marks.powered_off, "the machine is off");
    await second.destroy();
    fs.writeFileSync(directory + `${tag}.log`, transcript);
    const result = { tag, ms: Math.round(performance.now() - started), ...marks };
    console.log(JSON.stringify(result));
    console.log(`A64_LINUX_BOOT_OK ${tag}`);
    process.exit(0);
}
const single = stage === "single", live = stage === "live";
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const array_buffer = file => { const b = fs.readFileSync(file); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };
// (A64_LIVE_QCOW2: the ISO as a compressed QCOW2 image)
const live_qcow2 = live && +process.env.A64_LIVE_QCOW2 ? directory + "live-iso.qcow2" : "";
if(live_qcow2 && !fs.existsSync(live_qcow2))
{
    run(process.env.QEMU_IMG || "qemu-img", ["convert", "-c", "-f", "raw", "-O", "qcow2", prepared.iso, live_qcow2 + ".tmp"]);
    fs.renameSync(live_qcow2 + ".tmp", live_qcow2);
}
const machine_options = {
    cpu_type: "arm64", graphics_adapter: "none", cpu_cores: cores, memory_size: memory_mb * 1048576, log_level: 0,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { url: v86_kernel }, initrd: { url: single || live ? prepared.initrd : initrd },
    cmdline: single ? SINGLE_CMDLINE + V86_WATCHDOG : live ? LIVE_CMDLINE + V86_WATCHDOG : INITRAMFS_CMDLINE("v86"), ...JIT_OPTIONS, ...PROFILE_OPTIONS, ...PARALLEL_OPTIONS,
    ...(extended_memory ? { extended_memory_size: extended_memory } : {}),
    ...(process.env.A64_EXTENDED_CACHE ? { extended_memory_cache: +process.env.A64_EXTENDED_CACHE } : {}),
    ...(android ? { virtio_disks: [{ buffer: f2fs_disk, id: "a64f2fs" }] } : {}),
    // (the live stage's disks and devices, in the reference's -device order: P5.3)
    ...(live ? { virtio_disks: [live_qcow2 ? { buffer: array_buffer(live_qcow2), format: "qcow2", readonly: true } :
        { buffer: array_buffer(prepared.iso), readonly: true },
        { buffer: array_buffer(probe_directory + "probe.tar"), id: "a64probe" },
        // (A64_LINUX_SLEEP: hibernation's swap, after the reference's disks)
        ...(sleep_cycles ? [{ buffer: new ArrayBuffer(512 << 20), id: "a64swap" }] : [])],
        net_device: { type: "virtio" }, virtio_rng: true, virtio_console: true, virtio_input: true, virtio_transport: transport } : {}),
};
let emulator = new V86({ ...machine_options, autostart: true });
// (A64_MIDWAY_SNAPSHOT=1 with A64_WORKLOAD: a snapshot 1.5 s into the
// workload, while its code runs compiled, restored into a new machine that
// finishes it; its output must still be the reference's: P6.5)
const midway = !!+process.env.A64_MIDWAY_SNAPSHOT;
assert.ok(!midway || workload, "A64_MIDWAY_SNAPSHOT needs A64_WORKLOAD");
let snapped = false, snapshot_bytes;
const verbose = !!+process.env.A64_VERBOSE;
let transcript = "", probe_ms, typed = false, logged_in = false, login_ms;
// (the live stage: raw frames of EtherType 88B5 come back with source 02:00:00:00:00:02; hvc0's transcript)
let echoed = 0, hvc = "", hvc_state = 0, injected = false;
// (P5.8: two keys, one of them extended, down and up; a position and a left click)
const INJECTED_KEYS = [[1, 30, 1], [0, 0, 0], [1, 30, 0], [0, 0, 0], [1, 103, 1], [0, 0, 0], [1, 103, 0], [0, 0, 0]];
const INJECTED_TABLET = [[3, 0, 16384], [3, 1, 8192], [0, 0, 0], [1, 272, 1], [0, 0, 0], [1, 272, 0], [0, 0, 0]];
const inject_input = emulator =>
{
    for(const code of [0x1E, 0x9E, 0xE0, 0x48, 0xE0, 0xC8]) emulator.bus.send("keyboard-code", code);
    emulator.bus.send("mouse-absolute", [400, 150, 800, 600]);
    emulator.bus.send("mouse-click", [true, false, false]);
    emulator.bus.send("mouse-click", [false, false, false]);
};
const attach_live = emulator =>
{
    emulator.bus.register("net0-send", packet => {
        if(packet.length < 14 || packet[12] !== 0x88 || packet[13] !== 0xB5 || packet[11] !== 1) return;
        const reply = Uint8Array.from(packet);
        reply.set([2, 0, 0, 0, 0, 2], 6);
        echoed++;
        setTimeout(() => emulator.bus.send("net0-receive", reply), 0);
    });
    // (virtio-console's ports 1-3: the host echoes what the guest writes)
    for(const port of [1, 2, 3])
    {
        emulator.add_listener(`virtio-console${port}-output-bytes`, bytes => {
            const copy = Uint8Array.from(bytes);
            setTimeout(() => emulator.bus.send(`virtio-console${port}-input-bytes`, copy), 0);
        });
    }
    emulator.add_listener("virtio-console0-output-bytes", bytes => {
        hvc += String.fromCharCode(...bytes);
        const send = text => emulator.bus.send("virtio-console0-input-bytes", Uint8Array.from(Buffer.from(text)));
        if(hvc_state === 0 && /login: ?$/.test(hvc)) { hvc_state = 1; send("root\n"); }
        else if(hvc_state === 1 && /# ?$/.test(hvc)) { hvc_state = 2; send("echo A64_HVC_$((6*7)); exit\n"); }
        else if(hvc_state === 2 && /\nA64_HVC_42\r?\n/.test(hvc))
        {
            hvc_state = 3;
            if(sleep_cycles) sleep_and_hibernate(emulator).then(() => emulator.serial0_send(LIVE_FINISH), error => { sleep_error = error; fail_run?.(error); });
            else emulator.serial0_send(LIVE_FINISH);
        }
    });
};
if(live) attach_live(emulator);
// (A64_LINUX_SLEEP: what the cycles found, and a failure of theirs)
const sleep_results = [];
let sleep_error = null;
/** @type {?function(*)} the run's reject, for a failure outside the serial console's bytes */
let fail_run = null;
/** Wait until `pattern` matches the transcript after `from` (the serial console's) */
function serial_wait(pattern, from, what, limit_ms = timeout)
{
    return new Promise((resolve, reject) => {
        const limit = performance.now() + limit_ms;
        const poll = setInterval(() => {
            if(pattern.test(transcript.slice(from))) { clearInterval(poll); resolve(transcript.slice(from)); }
            else if(performance.now() > limit) { clearInterval(poll); reject(new Error("sleep: " + what + "\n" + transcript.slice(-2000))); }
        }, 20);
    });
}
/**
 * P8.1: s2idle woken by the PL031's alarm, then hibernation onto the swap
 * disk, powered on again and resumed, each `sleep_cycles` times
 * @param {!Object} emulator
 */
async function sleep_and_hibernate(emulator)
{
    const run = async (command, marker) => {
        const from = transcript.length;
        emulator.serial0_send(command + "; echo " + marker + "_$((6*7))\n");
        return serial_wait(new RegExp("\n" + marker + "_42\r?\n"), from, command);
    };
    const value = (text, key) => text.match(new RegExp("\n" + key + "=([^\r\n]*)"))?.[1];
    const online = cores === 1 ? "0" : "0-" + (cores - 1);
    const states = await run("echo STATE=$(cat /sys/power/state); echo MEM_SLEEP=$(cat /sys/power/mem_sleep); echo DISK=$(cat /sys/power/disk)", "STATES");
    sleep_results.push({ states: value(states, "STATE"), mem_sleep: value(states, "MEM_SLEEP"), disk: value(states, "DISK") });
    assert.match(value(states, "STATE"), /\bfreeze\b[\s\S]*\bdisk\b/, "s2idle and hibernation: " + value(states, "STATE"));
    await run("dd if=/dev/urandom of=/tmp/sleep.bin bs=1024 count=4096 2>/dev/null; md5sum /tmp/sleep.bin > /tmp/sleep.md5", "PATTERN");
    const check = async what => {
        const text = await run("md5sum -c /tmp/sleep.md5 >/dev/null && echo INTACT=1; echo ONLINE=$(cat /sys/devices/system/cpu/online)", "CHECK");
        assert.equal(value(text, "INTACT"), "1", what + ": the tmpfs file is intact");
        assert.equal(value(text, "ONLINE"), online, what + ": every CPU is online");
    };
    for(let cycle = 1; cycle <= sleep_cycles; cycle++)
    {
        // (the alarm 3 s on: the PL031's interrupt wakes the cores from their WFI)
        const from = transcript.length, started = performance.now();
        emulator.serial0_send("echo 0 > /sys/class/rtc/rtc0/wakealarm; echo +3 > /sys/class/rtc/rtc0/wakealarm; " +
            "echo freeze > /sys/power/state; echo RESUMED_$((" + cycle + "*7))\n");
        await serial_wait(new RegExp("\nRESUMED_" + cycle * 7 + "\r?\n"), from, "s2idle " + cycle);
        await check("s2idle " + cycle);
        sleep_results.push({ s2idle: cycle, ms: Math.round(performance.now() - started) });
    }
    const swap = await run("S=; for d in /sys/block/vd*; do [ \"$(cat $d/serial 2>/dev/null)\" = a64swap ] && S=/dev/${d##*/}; done; " +
        "mkswap $S >/dev/null && swapon $S && echo SWAP_UUID=$(blkid $S | grep -o ' UUID=\"[^\"]*\"' | cut -d'\"' -f2)", "SWAP");
    const uuid = value(swap, "SWAP_UUID");
    assert.ok(uuid && uuid.length >= 32, "the swap's UUID");
    // (the live ISO's init resumes before it looks for the boot media, which
    // loads the disk's driver: the swap's driver loaded first)
    emulator.v86.cpu.boot_files = { ...emulator.v86.cpu.boot_files,
        cmdline: LIVE_CMDLINE.replace("modules=loop,", "modules=virtio_mmio,virtio_blk,loop,") + V86_WATCHDOG + " resume=UUID=" + uuid };
    for(let cycle = 1; cycle <= sleep_cycles; cycle++)
    {
        const marker = 5000 + cycle;
        await run(`echo ${marker} > /tmp/s4-marker`, "MARK");
        const from = transcript.length, started = performance.now();
        emulator.serial0_send("echo disk > /sys/power/state; echo THAWED=$(cat /tmp/s4-marker)\n");
        // (the image written, the kernel powers off: PSCI SYSTEM_OFF)
        await new Promise((resolve, reject) => {
            const limit = performance.now() + timeout;
            const poll = setInterval(() => {
                if(emulator.v86.cpu.powered_off()) { clearInterval(poll); resolve(); }
                else if(performance.now() > limit) { clearInterval(poll); reject(new Error("hibernation: no SYSTEM_OFF\n" + transcript.slice(-2000))); }
            }, 50);
        });
        const off_ms = Math.round(performance.now() - started);
        assert.ok(await emulator.power_button(), "the machine powers on");
        const thawed = await serial_wait(/\nTHAWED=\d+\r?\n/, from, "restore " + cycle);
        assert.equal(value(thawed, "THAWED"), String(marker), "the shell goes on in the restored kernel");
        await check("hibernation " + cycle);
        sleep_results.push({ hibernate: cycle, off_ms, ms: Math.round(performance.now() - started) });
    }
}
// (A64_LINUX_SNAPSHOT=1: the whole machine saved and restored at three of the
// probe's markers, while its threads, signals and the virtio devices' I/O
// are under way: rounds alternate between the chunked V7 stream, written to
// and read back from a file, and the single-buffer V6 format; as
// tests/x64/linux_boot.mjs's X64_LINUX_SNAPSHOT, P5.9)
const SNAPSHOT_MARKERS = ["A64_PROBE_START", "A64_PROBE_OK", "A64_PROBE_XC"];
const snapshots = !!+process.env.A64_LINUX_SNAPSHOT;
const snapshots_taken = [], snapshot_rounds = [];
let snapshot_busy = false;
async function snapshot_round(marker)
{
    snapshot_busy = true;
    await emulator.stop();
    if(snapshots_taken.length % 2)
    {
        const file_name = directory + `snapshot-${tag}.v7`;
        const file = await fs.promises.open(file_name, "w+");
        let bytes = 0, largest = 0, chunks = 0;
        try
        {
            await emulator.save_state_stream(async chunk => {
                await file.write(chunk, 0, chunk.length, bytes);
                bytes += chunk.length; chunks++; largest = Math.max(largest, chunk.length);
            });
            await emulator.restore_state_stream({ size: bytes, read: async (offset, length) => {
                const data = new Uint8Array(length);
                const read = (await file.read(data, 0, length, offset))["bytesRead"];
                return read === length ? data : data.subarray(0, read);
            } });
        }
        finally { await file.close(); fs.rmSync(file_name, { force: true }); }
        assert.ok(largest <= 1 << 20, "V7 chunks are at most 1 MiB");
        snapshot_rounds.push({ marker, format: "V7 stream", bytes, chunks, largest_chunk: largest });
    }
    else
    {
        const state = await emulator.save_state();
        await emulator.restore_state(state);
        snapshot_rounds.push({ marker, format: "V6 buffer", bytes: state.byteLength });
    }
    snapshot_busy = false;
    emulator.run();
}
const started = performance.now();
/** (A64 inspect: where the core is, for a run that does not finish) */
function inspect()
{
    const cpu = emulator.v86?.cpu;
    return JSON.stringify(cpu?.get_diagnostics?.() ?? {}) + "\n--- the serial console's last lines:\n" + transcript.split("\n").slice(-25).join("\n");
}
try
{
    await new Promise((resolve, reject) => {
        fail_run = reject;
        const timer = setTimeout(() => reject(new Error(`v86 ${stage} deadline (${timeout} ms): ${inspect()}`)), timeout);
        const on_byte = byte => {
            const c = String.fromCharCode(byte);
            transcript += c;
            if(verbose) process.stdout.write(c);
            if(midway && !snapped && transcript.includes("A64_WORKLOAD_BEGIN"))
            {
                snapped = true;
                setTimeout(async () => {
                    await emulator.stop();
                    const saved = await emulator.save_state();
                    snapshot_bytes = saved.byteLength;
                    await emulator.destroy();
                    emulator = new V86({ ...machine_options, autostart: false });
                    await new Promise(r => emulator.add_listener("emulator-loaded", r));
                    await emulator.restore_state(saved);
                    emulator.add_listener("serial0-output-byte", on_byte);
                    emulator.run();
                }, 1500);
            }
            if(probe_ms === undefined && transcript.includes("A64_PROBE_XC")) probe_ms = Math.round(performance.now() - started);
            for(const marker of SNAPSHOT_MARKERS)
            {
                // (the probe's line, not the shell echoing the command)
                if(snapshots && !snapshot_busy && !snapshots_taken.includes(marker) && transcript.includes("\n" + marker))
                {
                    snapshots_taken.push(marker);
                    snapshot_round(marker).catch(reject);
                }
            }
            if(single && !typed && /Entering single mode[^\n]*\n/.test(transcript))
            {
                typed = true;
                emulator.serial0_send(SINGLE_COMMANDS);
            }
            if(live && !logged_in && /localhost login: ?$/.test(transcript))
            {
                login_ms = Math.round(performance.now() - started);
                logged_in = true;
                emulator.serial0_send("root\n");
            }
            if(live && logged_in && !typed && /localhost:~# ?$/.test(transcript))
            {
                typed = true;
                emulator.serial0_send(LIVE_COMMANDS("v86"));
            }
            if(live && !injected && /\nA64_INPUT_READY\r?\n/.test(transcript))
            {
                injected = true;
                inject_input(emulator);
            }
            // (a line of its own: the shell echoes the command, which names it too)
            if(sleep_error) { clearTimeout(timer); reject(sleep_error); return; }
            const done = single ? /A64_SINGLE_42\r?\nA64_SINGLE_OK/ : live ? /\nA64_LIVE_DONE\r?\n/ : /A64_INIT_DONE/;
            if(done.test(transcript) || /Kernel panic/.test(transcript) && transcript.endsWith("\n"))
            {
                clearTimeout(timer);
                setTimeout(() => (done.test(transcript) ? resolve() : reject(new Error("kernel panic: " + inspect()))), 200);
            }
        };
        emulator.add_listener("serial0-output-byte", on_byte);
        emulator.add_listener("emulator-error", error => reject(error));
    });
}
finally
{
    fs.writeFileSync(directory + `${tag}.log`, transcript);
}
// (no UNDEF in the kernel, P2.3; no trouble in its log; the timer's and the UART's interrupts counted)
const undefined_instructions = emulator.v86.cpu.undefined_instructions();
const page_tier = jit ? emulator.v86.cpu.page_tier_stats() : undefined;
// (every core's; MIPS over the whole run, P0.9)
const retired_per_core = Array.from({ length: cores }, (_, core) => emulator.v86.cpu.retired_instructions(core));
const retired_instructions = retired_per_core.reduce((sum, n) => sum + n, 0);
// (cores in workers: what each did, src/parallel/machine.js)
const parallel_status = parallel ? emulator.v86.cpu.get_diagnostics().parallel : undefined;
// (extended RAM: its frames' traffic, and the instructions from it, interpreted and compiled)
// (P9.3: TTBR writes and ASID changes, the machine thread's instance's cores)
const mmu_stat = emulator.v86.cpu.wm.exports["a64_mmu_stat"];
const mmu = mmu_stat ? { ttbr_writes: mmu_stat(0), asid_changes: mmu_stat(1) } : undefined;
const ext_stat = field => emulator.v86.cpu.wm.exports["a64_ext_stat"](field);
const extended_stats = extended_memory ? { hits: ext_stat(0), loads: ext_stat(1), write_backs: ext_stat(2), evictions: ext_stat(3),
    code_pages: ext_stat(14), code_writes: ext_stat(15), interpreted: ext_stat(16), compiled: ext_stat(17) } : undefined;
await emulator.destroy();
assert.equal(undefined_instructions.el1, 0, "UNDEF at EL1: " + JSON.stringify(undefined_instructions));
const trouble = transcript.match(/^.*(Oops|BUG:|WARNING:|SError|rcu_.*stall|Internal error|undefined instruction).*$/m);
assert.ok(!trouble, "the kernel reports: " + trouble?.[0]);
// (the UART's interrupts come with input: the single stage types its commands; the
// initramfs stage writes the console by polling, on the reference too)
{
    for(const name of single ? ["arch_timer", "uart-pl011"] : ["arch_timer"])
    {
        const line = transcript.match(new RegExp("^\\s*\\d+:\\s+(\\d+)\\s.*" + name + ".*$", "m"));
        assert.ok(line && +line[1] > 0, name + " interrupts in /proc/interrupts");
    }
}
const lines = single ? { single: /A64_SINGLE_42\r?\nA64_SINGLE_OK/.test(transcript) } : check_probe(transcript, false);
if(extended_memory)
{
    // (the device tree's second memory range, as the kernel took it)
    const end = (EXTENDED_BASE + extended_memory - 1).toString(16).padStart(16, "0");
    assert.match(transcript, new RegExp(`node\\s+0: \\[mem 0x0000000100000000-0x${end}\\]`), "extended RAM in the kernel's memory map");
    extended_stats.share = Math.round((extended_stats.interpreted + extended_stats.compiled) / retired_instructions * 1e4) / 1e4;
    lines.extended = extended_stats;
}
if(android)
{
    // (P9.1: binderfs's selftest and the cross-core binder ping-pong)
    const totals = transcript.match(/# Totals: pass:(\d+) fail:(\d+)/);
    assert.ok(totals && +totals[1] > 0 && +totals[2] === 0, "binderfs's selftest: " + (totals?.[0] || "no totals"));
    const pingpong = transcript.match(/A64_BINDER_OK rounds=(\d+) cpus=(\d+),(\d+)/);
    assert.ok(pingpong && +pingpong[1] === 10000, "binder ping-pong: " + (transcript.match(/A64_BINDER_FAIL[^\r\n]*/)?.[0] || "no result"));
    // (P9.2: userfaultfd)
    const uffd = transcript.match(/A64_UFFD_OK faults=(\d+)/);
    assert.ok(uffd && +uffd[1] === 64, "userfaultfd: " + (transcript.match(/A64_UFFD_FAIL[^\r\n]*/)?.[0] || "no result"));
    lines.binder = { selftest: totals[0], pingpong: pingpong[0] };
    lines.uffd = uffd[0];
    const failure = what => transcript.match(new RegExp(`A64_${what}_FAIL[^\\r\\n]*`))?.[0] || "no result";
    // (P9.2: f2fs with fscrypt, written, one reboot, read without the key and with it)
    const setup = transcript.match(/A64_FSCRYPT_SETUP id=([0-9a-f]{32})/);
    const fscrypt = transcript.match(/A64_FSCRYPT_OK id=([0-9a-f]{32})[^\r\n]*/);
    assert.ok(setup && fscrypt && setup[1] === fscrypt[1], "fscrypt across the reboot: " + failure("FSCRYPT"));
    assert.equal(transcript.split("\nA64_REBOOTING").length - 1, 1, "one reboot (PSCI SYSTEM_RESET) after writing");
    assert.equal(transcript.match(/Booting Linux on physical CPU 0x0+ /g)?.length, 2, "two boots");
    assert.ok(transcript.indexOf("A64_FSCRYPT_OK") > transcript.indexOf("A64_REBOOTING"), "read after the reboot");
    // (bootconfig: /proc/bootconfig, and kernel.* on the command line)
    // (after the keys, as comments, the command line the bootloader gave)
    const bootconfig = [...transcript.matchAll(/^A64_BOOTCONFIG ([^#\r\n][^\r\n]*)/gm)].map(m => m[1]);
    assert.deepEqual(bootconfig, Object.entries(BOOTCONFIG).map(([key, value]) => `${key} = "${value}"`), "/proc/bootconfig");
    assert.match(transcript, /^A64_BOOTCONFIG # [^\r\n]*\bbootconfig\b/m, "/proc/bootconfig's parameters from the bootloader");
    assert.match(transcript, /^A64_CMDLINE printk\.devkmsg=on [^\r\n]*\bbootconfig\b/m, "bootconfig's kernel.* keys first on the command line");
    // (pseudo-NMIs: the GIC's priority masking in use)
    assert.ok(detected(transcript).includes("IRQ priority masking"), "pseudo-NMIs (CPU features: detected: IRQ priority masking)");
    // (SELinux enforcing before the probe)
    const selinux = transcript.match(/A64_SELINUX_OK enforce=1 context=(\S+)[^\r\n]*/);
    assert.ok(selinux, "SELinux: " + failure("SELINUX"));
    assert.equal(selinux[1], "u:r:t", "the processes' context, from the policy's initial SIDs");
    assert.ok(selinux.index < transcript.lastIndexOf("A64_PROBE_OK"), "the probe passed under enforcing");
    // (erofs on dm-verity: the file and the whole device as built; the changed byte's block fails)
    const erofs = transcript.match(/^A64_EROFS (\S+) ([0-9a-f]{64}) A64_EROFS_HELLO ([0-9a-f]{64})/m);
    assert.ok(erofs, "erofs on dm-verity: " + failure("VERITY"));
    assert.deepEqual([erofs[2], erofs[3]], [android_expect.payload_sha256, android_expect.erofs_sha256], "erofs's file and the verity device's bytes");
    const bad = transcript.match(/^A64_VERITY_BAD (\S+) (\w+)/m);
    assert.equal(bad?.[2], "eio", "dm-verity over the changed image: reads fail");
    assert.match(transcript, new RegExp(`data block ${android_expect.bad_block} is corrupted`), "dm-verity names the changed block");
    // (zram and PSI)
    const psi = transcript.match(/A64_PSI_OK events=(\d+)[^\r\n]*/);
    assert.ok(psi && +psi[1] > 0, "PSI's trigger: " + failure("PSI"));
    const swapped = transcript.match(/A64_PSI_CHILD swap=(\d+) zram=(\d+)\s+(\d+)/);
    assert.ok(swapped && +swapped[1] > 0 && +swapped[2] > +swapped[3], "pages in zram, compressed: " + swapped?.[0]);
    const memory_kib = +transcript.match(/A64_MEMINFO MemTotal:\s+(\d+) kB/)?.[1];
    Object.assign(lines, { fscrypt: fscrypt[0], bootconfig: bootconfig.length, selinux: selinux[0], erofs_verity: true, psi: psi[0],
        zram: swapped[0], mem_total_kib: memory_kib });
}
if(gki)
{
    // (the reference's run, A64_LINUX_QEMU=1 A64_KERNEL=gki, gives the expected drivers)
    Object.assign(lines, check_gki(transcript));
    const reference_log = directory + tag_of("qemu") + ".log";
    assert.ok(fs.existsSync(reference_log), "the GKI bridge compares with the reference's run: " + reference_log);
    assert.equal(lines.virtio_drivers, check_gki(fs.readFileSync(reference_log, "latin1")).virtio_drivers, "the virtio drivers, against the reference's");
}
if(/^soak/.test(workload))
{
    const done = transcript.match(/A64_SOAK_DONE rounds=(\d+)/);
    assert.ok(done && +done[1] > 0, "the soak's rounds");
    assert.ok(!/A64_PROBE_FAIL/.test(transcript.slice(transcript.indexOf("A64_PROBE_XC"))), "no probe failed during the soak");
    lines.soak = { minutes: soak_minutes, rounds: +done[1] };
}
if(/^smp/.test(workload))
{
    const start = transcript.match(/A64_SMP_START ([\d.]+)/), end = transcript.match(/A64_SMP_END ([\d.]+)/);
    assert.ok(start && end, "the smp workload's start and end");
    lines.smp = { copies: +workload.slice(3), seconds: Math.round((end[1] - start[1]) * 100) / 100 };
}
if(memtest_mib)
{
    const line = transcript.match(/A64_MEMTEST mib=(\d+) pages=(\d+) errors=(\d+) extended_pages=(\d+) code=(\d) exclusive=(\d) zva=(\d)/);
    assert.ok(line, "the memtest's line");
    assert.equal(+line[3], 0, "memtest contents");
    if(extended_memory)
    {
        assert.ok(+line[4] > +line[2] / 4, "memtest pages in extended RAM: " + line[0]);
        assert.deepEqual(line.slice(5, 8).map(Number), [1, 1, 1], "code, an exclusive counter and DC ZVA in extended RAM: " + line[0]);
    }
    lines.memtest = line[0];
}
if(live)
{
    // (P5.4, P5.5: the frames through virtio-net, /dev/hwrng, a login on hvc0)
    assert.match(transcript, /A64_PROBE_NET arch=aarch64 frames=16/, "raw frames through eth0 (virtio-net) and back");
    assert.equal(echoed, 16, "the host echoed every probe frame");
    assert.match(transcript, /\nA64_HWRNG=64\r?\n/, "64 bytes from /dev/hwrng (virtio-rng)");
    assert.equal(hvc_state, 3, "a login on hvc0 (virtio-console): " + JSON.stringify(hvc.slice(-300)));
    // (P9.1: each of the ports 1-3 echoed its line)
    const vports = [...transcript.matchAll(/^A64_VPORT org\.v86\.port(\d) vport\d+p(\d) VPING_(\d)\r?$/gm)].map(m => m.slice(1).join(""));
    assert.deepEqual(vports.sort(), ["111", "222", "333"], "virtio-console's ports 1-3 echo (/dev/vport<N>p1-p3)");
    // (P5.8: the injected events, as the guest's evdev read them)
    assert.deepEqual(input_events(transcript, "A64_EVK"), INJECTED_KEYS, "the keyboard's events (virtio-input)");
    assert.deepEqual(input_events(transcript, "A64_EVT"), INJECTED_TABLET, "the tablet's events (virtio-input)");
    Object.assign(lines, { net_frames: echoed, hvc0: true, input_events: INJECTED_KEYS.length + INJECTED_TABLET.length, pci: pci_functions(transcript) });
    // (the PCI functions, against the reference's: needed for the pci variant;
    // not with A64_LINUX_SLEEP's swap disk, which the reference does not have)
    const reference_log = directory + tag_of("qemu") + ".log";
    assert.ok(transport === "mmio" || sleep_cycles || fs.existsSync(reference_log), "the pci variant compares with the reference's run: " + reference_log);
    if(!sleep_cycles && fs.existsSync(reference_log))
    {
        assert.deepEqual(lines.pci, pci_functions(fs.readFileSync(reference_log, "latin1")), "the PCI functions, against the reference's");
        lines.pci_compared = true;
    }
    assert.equal(lines.pci.length, transport === "pci" ? 1 + machine_options.virtio_disks.length + 5 : 1,
        "the PCI functions: the host bridge and the devices on pci");
    if(sleep_cycles)
    {
        assert.equal(sleep_results.filter(r => r.s2idle).length + sleep_results.filter(r => r.hibernate).length, 2 * sleep_cycles, "every sleep cycle");
        lines.sleep = sleep_results;
    }
}
if(snapshots)
{
    assert.deepEqual(snapshots_taken, SNAPSHOT_MARKERS, "a snapshot at each marker");
    lines.snapshots = snapshot_rounds;
}
const features = detected(transcript);
let reference_features;
if(!single)
{
    // (CSV3: meltdown is not a concern, with or without kpti=1; kpti=1 turns KPTI on all the same)
    const meltdown = transcript.match(/A64_VULN meltdown: ([^\r\n]*)/);
    assert.equal(meltdown?.[1], "Not affected", "vulnerabilities/meltdown");
    assert.equal(features.some(f => /^Kernel page table isolation/.test(f)), kpti, "KPTI " + (kpti ? "on" : "off"));
    // (the same stage on the reference, if it ran: A64_LINUX_QEMU=1)
    const reference_log = directory + tag_of("qemu") + ".log";
    if(fs.existsSync(reference_log))
    {
        const reference_text = fs.readFileSync(reference_log, "latin1");
        reference_features = detected(reference_text);
        if(workload)
        {
            assert.ok(workload_output(transcript), "the workload's output");
            assert.equal(workload_output(transcript), workload_output(reference_text), "the workload's output, against the reference's");
        }
        // (and the androidish runs' pseudo-NMIs, their command line's, not the reference's)
        const only_v86 = features.filter(f => !reference_features.includes(f) && !FEATURES_ONLY_ON_V86.includes(f) &&
            !(android && f === "IRQ priority masking"));
        const only_reference = reference_features.filter(f => !features.includes(f) && !FEATURES_ONLY_ON_REFERENCE.includes(f));
        assert.deepEqual([only_v86, only_reference], [[], []], "CPU features: detected, beyond the allowed differences (v86, reference)");
    }
}
const vulnerabilities = Object.fromEntries([...transcript.matchAll(/A64_VULN (\S+): ([^\r\n]*)/g)].map(m => [m[1], m[2]]));
if(midway) assert.ok(snapped && snapshot_bytes, "the snapshot in the workload's middle was taken and restored");
const ms = Math.round(performance.now() - started);
const result = { tag, ms, ...(live ? { boot_to_login_ms: login_ms } : {}), probe_done_ms: probe_ms, retired_instructions,
    retired_per_core, mips: Math.round(retired_instructions / ms / 100) / 10, page_tier, mmu, ...(parallel ? { parallel: parallel_status } : {}),
    ...(midway ? { midway_snapshot_bytes: snapshot_bytes } : {}), ...lines, features,
    reference_features: reference_features ? "compared" : "no reference log", vulnerabilities };
fs.writeFileSync(directory + `result-${tag}.json`, JSON.stringify({ ...manifest, ...result }, null, 2) + "\n");
console.log(JSON.stringify(result));
console.log(`A64_LINUX_BOOT_OK ${tag}`);
process.exit(0);
                                                                                               source/v64/tests/a64/linux_gpu.mjs                                                                  0000644 0000000 0000000 00000001151 00000000000 014143  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Alpine 3.24 aarch64 on the virt machine's virtio_gpu (no VGA;
// docs/arm64-virt-android16-plan.md P7.1, P7.2): the scenarios of
// tests/x64/linux_gpu.mjs (drm, gl, gltest, virgl, venus, vkcube, resize)
// with GPU_ARCH=aarch64, the packages from build/a64-linux/gpu-repo.tar
// (node tools/alpine_repo.mjs --arch aarch64 --set gpu), the ISO's kernel
// and initramfs (tests/a64/linux_boot.mjs prepares them).
//
//     [GPU_SCENARIO=drm] [GPU_LEVEL=virgl43-hostmem] [GPU_TRANSPORT=pci|mmio] node tests/a64/linux_gpu.mjs
process.env.GPU_ARCH = "aarch64";
await import("../x64/linux_gpu.mjs");
                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/a64/linux_install.mjs                                                              0000644 0000000 0000000 00000021460 00000000000 015023  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Alpine 3.24 aarch64 installed to a virtio-blk disk on v86
// (docs/arm64-virt-android16-plan.md P5.4, A3), in one machine session:
// 1. from the ISO, `setup-disk -m sys` (no swap, no boot loader: the machine
//    boots its kernel directly, as the reference does) installs onto an
//    empty disk from a local repository disk, offline (the virt ISO has no
//    kernel package: tools/alpine_repo.mjs --arch aarch64 --set sys); the
//    installed files' MD5s, fsck -n; the installed /boot's kernel and
//    initramfs written to an export disk;
// 2. the machine reboots into the installed system: its own kernel and
//    initramfs (read from the export disk), its root by UUID; the same
//    files' MD5s; a clean reboot;
// 3. back into the ISO: the root file system is clean (fsck -n).
// Writes stay in the disks' in-memory overlays for the session. The disks
// are found by their virtio-blk serials. A64_TRANSPORT=pci: the disks are
// virtio-pci functions on the PCIe host (P5.7) instead of virtio-mmio.
//
//     [A64_JIT=1] [A64_CORES=N] [A64_TRANSPORT=pci] node tests/a64/linux_install.mjs
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { prepare, ROOT } from "../lib/alpine_image.mjs";
import { output_directory } from "../../tools/alpine_repo.mjs";

const cores = Number(process.env.A64_CORES || 1);
const jit = !!+process.env.A64_JIT;
const transport = process.env.A64_TRANSPORT || "mmio";
assert.ok(["mmio", "pci"].includes(transport), "A64_TRANSPORT is mmio or pci");
const timeout = Number(process.env.A64_LINUX_TIMEOUT || 1800000);
const prepared = await prepare("aarch64-virt", ["boot/vmlinuz-virt", "boot/initramfs-virt", "boot/modloop-virt"]);
const repo_image = path.join(output_directory("aarch64"), "sys-repo.tar");
assert.ok(fs.existsSync(repo_image), repo_image + " is missing: node tools/alpine_repo.mjs --arch aarch64 --set sys");
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const array_buffer = file => { const b = fs.readFileSync(file); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };
const MiB = 1 << 20;
const disks = [
    { buffer: array_buffer(prepared.iso), id: "a64iso", readonly: true },
    { buffer: new ArrayBuffer(768 * MiB), id: "a64target" },
    { buffer: array_buffer(repo_image), id: "a64repo", readonly: true },
    { buffer: new ArrayBuffer(128 * MiB), id: "a64export" },
];
const export_disk = disks[3].buffer;

const LIVE_CMDLINE = "console=ttyAMA0 earlycon nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage";
const disk_cmdline = uuid => `console=ttyAMA0 earlycon nokaslr panic=-1 root=UUID=${uuid} rootfstype=ext4 modules=ext4`;
// (shell: the disk with a serial, as $name)
const find = (name, serial) => `${name}=; for d in /sys/block/vd*; do [ "$(cat $d/serial 2>/dev/null)" = ${serial} ] && ${name}=/dev/\${d##*/}; done; `;
const DISKS = find("T", "a64target") + find("R", "a64repo") + find("E", "a64export");
// (the repository disk's tar, as the only repository: setup-disk stops the
// modloop service, which unmounts the boot media)
const REPOSITORY = "mkdir -p /tmp/repo && tar -xf $R -C /tmp/repo && echo /tmp/repo/main > /etc/apk/repositories; ";
const MD5 = root => `md5sum ${root}/bin/busybox ${root}/etc/alpine-release ${root}/sbin/apk | sed -e 's, ${root}/, /,' -e 's/^/A64_MD5 /'; `;

const iso_boot = { kernel: array_buffer(prepared.kernel), initrd: array_buffer(prepared.initrd), cmdline: LIVE_CMDLINE };
const emulator = new V86({
    cpu_type: "arm64", graphics_adapter: "none", cpu_cores: cores, memory_size: 512 << 20, log_level: 0,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { buffer: iso_boot.kernel }, initrd: { buffer: iso_boot.initrd }, cmdline: LIVE_CMDLINE,
    virtio_disks: disks, virtio_transport: transport, autostart: true, ...(jit ? { jit_switches: { a64_page: 1 } } : {}),
});
let transcript = "";
emulator.add_listener("serial0-output-byte", byte => {
    transcript += String.fromCharCode(byte);
    if(+process.env.A64_VERBOSE) process.stdout.write(String.fromCharCode(byte));
});
const text = () => transcript.replace(/\r/g, "");
/** Wait until `pattern` matches the transcript after `from` */
function wait_for(pattern, what, from)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => { clearInterval(poll); reject(new Error(`no ${what} after ${timeout} ms:\n${text().slice(-2000)}`)); }, timeout);
        const poll = setInterval(() => {
            const match = text().slice(from).match(pattern);
            if(match) { clearTimeout(timer); clearInterval(poll); resolve(match); }
            else if(/Kernel panic/.test(text().slice(from))) { clearTimeout(timer); clearInterval(poll); reject(new Error(`${what}: kernel panic:\n${text().slice(-2000)}`)); }
        }, 50);
    });
}
/** Log in on the serial console (the boot from `from`) and run `commands`; the transcript from there */
async function session(name, commands, done)
{
    const from = text().length;
    const started = performance.now();
    await wait_for(/login: ?(\x1b\[[0-9;]*[A-Za-z])*$/, name + " login prompt", from);
    emulator.serial0_send("root\n");
    // (busybox's ash asks the terminal for the cursor position after its prompt: ESC [ 6 n)
    await wait_for(/:~# ?(\x1b\[[0-9;]*[A-Za-z])*$/, name + " shell", from);
    const at = text().length;
    emulator.serial0_send(commands);
    await wait_for(done, name + " end", at);
    console.log(`${name}: ${Math.round(performance.now() - started)} ms`);
    return text().slice(at);
}
const md5s = output => [...output.matchAll(/^A64_MD5 (\w+) +(\S+)$/gm)].map(m => m[2] + " " + m[1]).sort();
const value = (output, name) => output.match(new RegExp(`^${name}=(\\S+)$`, "m"))?.[1];

/** The files of a ustar image on a disk */
function untar(buffer)
{
    const bytes = new Uint8Array(buffer), files = {};
    for(let at = 0; at + 512 <= bytes.length;)
    {
        const name = new TextDecoder().decode(bytes.subarray(at, at + 100)).replace(/\0.*$/s, "");
        if(!name) break;
        const size = parseInt(new TextDecoder().decode(bytes.subarray(at + 124, at + 136)), 8) || 0;
        files[name.replace(/^\.\//, "")] = bytes.slice(at + 512, at + 512 + size).buffer;
        at += 512 + Math.ceil(size / 512) * 512;
    }
    return files;
}

try
{
    // 1. from the ISO: setup-disk, the installed files' MD5s, fsck, /boot exported
    const setup = await session("setup", DISKS + REPOSITORY +
        "ERASE_DISKS=$T setup-disk -m sys -s 0 -B none $T > /tmp/setup.log 2>&1; echo A64_SETUP=$?; tail -3 /tmp/setup.log; " +
        "echo A64_UUID=$(blkid ${T}2 | grep -o ' UUID=\"[^\"]*\"' | cut -d'\"' -f2); mount ${T}2 /mnt && " + MD5("/mnt") + "umount /mnt; " +
        "fsck.ext4 -fn ${T}2; echo A64_FSCK=$?; mount ${T}1 /mnt && tar -cf $E -C /mnt vmlinuz-virt initramfs-virt && umount /mnt; " +
        "sync; echo A64_EXPORTED\n", /\nA64_EXPORTED\n/);
    assert.equal(value(setup, "A64_SETUP"), "0", "setup-disk -m sys:\n" + setup.slice(-1500));
    assert.equal(value(setup, "A64_FSCK"), "0", "the installed root file system, fsck -n");
    const uuid = value(setup, "A64_UUID");
    assert.ok(uuid && uuid.length >= 32, "the root file system's UUID");
    const installed = md5s(setup);
    assert.equal(installed.length, 3, "the installed files' MD5s");

    // 2. reboot into the installed system: its kernel and initramfs, its root
    const boot = untar(export_disk);
    assert.ok(boot["vmlinuz-virt"] && boot["initramfs-virt"], "the installed kernel and initramfs on the export disk");
    emulator.v86.cpu.boot_files = { ...emulator.v86.cpu.boot_files, kernel: boot["vmlinuz-virt"], initrd: boot["initramfs-virt"],
        cmdline: disk_cmdline(uuid) };
    emulator.serial0_send("reboot\n");
    const system = await session("installed", "cat /proc/cmdline; uname -r; " + MD5("") + "echo A64_INSTALLED_UP\n",
        /\nA64_INSTALLED_UP\n/);
    assert.ok(system.includes("root=UUID=" + uuid), "booted with the installed root");
    assert.deepEqual(md5s(system), installed, "the installed files, as the installer left them");

    // 3. back into the ISO: the root file system after the installed system's clean reboot
    emulator.v86.cpu.boot_files = { ...emulator.v86.cpu.boot_files, ...iso_boot };
    emulator.serial0_send("reboot\n");
    const check = await session("fsck", DISKS + REPOSITORY + "apk add -q e2fsprogs > /dev/null 2>&1; fsck.ext4 -fn ${T}2; echo A64_FSCK=$?\n",
        /\nA64_FSCK=\d+\n/);
    assert.equal(value(check, "A64_FSCK"), "0", "the root file system after the installed system ran, fsck -n");
    console.log(`linux_install: ${uuid}; ${installed.join(", ")}; passed`);
}
finally
{
    fs.writeFileSync(prepared.directory + `v86${jit ? "-jit" : ""}-install${transport === "pci" ? "-pci" : ""}-${cores}c.log`, transcript);
    await emulator.destroy();
}
process.exit(0);
                                                                                                                                                                                                                source/v64/tests/a64/linux_loader.mjs                                                               0000644 0000000 0000000 00000005735 00000000000 014632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The virt machine's Linux loader (docs/arm64-virt-android16-plan.md P4.6):
// src/virt/loader.js unpacks Alpine's EFI zboot vmlinuz-virt with its own
// inflate (src/virt/inflate.js) to the Image the host's gunzip gives
// (tests/lib/alpine_image.mjs, the manifest's SHA-256), and places the
// kernel, the initrd and the device tree where the reference does.
import assert from "node:assert/strict";
import { createHash as create_hash } from "node:crypto";
import fs from "node:fs";
import zlib from "node:zlib";
import { root } from "./guest_runner.mjs";
import { unpack_kernel, image_placement } from "../../src/virt/loader.js";
import { gunzip } from "../../src/virt/inflate.js";

const directory = root + "build/a64-linux/";
const manifest = JSON.parse(fs.readFileSync(directory + "manifest.json", "utf8"));
const vmlinuz = fs.readFileSync(directory + "boot/vmlinuz-virt");
const sha256 = bytes => create_hash("sha256").update(bytes).digest("hex");
assert.equal(sha256(vmlinuz), manifest.vmlinuz_sha256, "vmlinuz-virt is the fixed one (tests/a64/linux_boot.mjs prepares it)");

let start = performance.now();
const image = unpack_kernel(new Uint8Array(vmlinuz.buffer, vmlinuz.byteOffset, vmlinuz.length));
const ms = (performance.now() - start).toFixed(0);
assert.equal(image.length, manifest.image_bytes, "Image size");
assert.equal(sha256(image), manifest.image_sha256, "Image SHA-256");
console.log(`PASS vmlinuz-virt unpacks to the Image (${image.length} bytes, ${ms} ms, SHA-256 ${manifest.image_sha256.slice(0, 8)}…)`);

const { offset, size } = image_placement(image);
assert.equal(offset, 0x200000, "the Image's text_offset is 0: it goes 2 MiB into RAM");
assert.ok(size >= image.length, "image_size covers the BSS");
console.log(`PASS the kernel at RAM + 0x${offset.toString(16)}, reaching 0x${size.toString(16)} bytes`);
// (the header's page size: a 16 or 64 KiB kernel is refused under profile v1)
for(const [bits, ok] of [[0, true], [1, true], [2, false], [3, false]])
{
    const header = image.slice(0, 64);
    new DataView(header.buffer).setUint32(24, bits << 1, true);
    if(ok) image_placement(header);
    else assert.throws(() => image_placement(header), /KiB pages/);
}
console.log("PASS kernels for 16 and 64 KiB pages are refused");

// inflate against zlib on random data of every kind (stored, fixed and dynamic blocks)
for(const level of [0, 1, 6, 9])
{
    const data = Buffer.alloc(300000);
    for(let i = 0; i < data.length; i++) data[i] = level === 0 || i % 7 ? (i * 2654435761 >>> 24) & (i % 3 ? 0xFF : 0x0F) : 0x41;
    start = performance.now();
    assert.deepEqual(Buffer.from(gunzip(zlib.gzipSync(data, { level }))), data, "gunzip at level " + level);
    const fixed = zlib.deflateRawSync(data.subarray(0, 1000), { level, strategy: zlib.constants.Z_FIXED });
    assert.deepEqual(Buffer.from((await import("../../src/virt/inflate.js")).inflate(fixed).output), data.subarray(0, 1000));
}
console.log("PASS inflate agrees with zlib (stored, fixed and dynamic blocks)");
                                   source/v64/tests/a64/linux_probe.c                                                                  0000644 0000000 0000000 00000124367 00000000000 014127  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Freestanding Linux user probe for aarch64 (docs/arm64-virt-android16-plan.md
 * "aarch64 probe", P0.4): the multicore OS contract of tests/x64/linux_probe.c
 * on arm64's system call ABI (svc #0, asm-generic numbers), with arm64's own
 * checks. No libc; the page size comes from AT_PAGESZ.
 *
 * A64_PROBE_OK: uname, mmap/mprotect with a SIGSEGV round trip (the fault
 * address from siginfo and from sigcontext, the ESR from esr_context),
 * fork/wait4, a thread bound to each online CPU incrementing a counter 20000
 * times with LDXR/STXR, a cross-CPU TLB shootdown after MAP_FIXED (arm64
 * Linux uses TLBI broadcasts, no IPI), tmpfs file I/O, the frames of 16 MiB
 * of touched pages at or above a PFN (pagemap; the argument "high=<pfn>"),
 * AT_HWCAP and /proc/cpuinfo's Features against the profile, MRS of
 * ID_AA64ISAR0_EL1 at EL0 (the kernel's sanitized value), DC ZVA.
 *
 * A64_PROBE_XC: /sys topology, migrations, signals to threads on other CPUs,
 * code rewritten on one CPU and executed on another (DC CVAU, DSB, IC IVAU,
 * DSB, ISB, the steps CTR_EL0 makes unnecessary skipped), a memfd mapped RW
 * and RX (an ART JIT code page's stand-in), exclusive ABA (another CPU writes
 * the same value back: the STXR must fail), futex ping-pong across CPUs,
 * CNTVCT and the vDSO's clock never going back across CPUs, FPCR, FPSR and
 * V0-V31 across system calls, migration and signals, an AArch32 ELF
 * (ENOEXEC: v1 has no AArch32), and an O_DIRECT read of the probe disk found
 * by its virtio-blk serial "a64probe" (direct_io=1; "nodisk": direct_io=0).
 *
 * A64_PROBE_NET (argument "net"): raw frames of EtherType 88B5 through eth0
 * come back unchanged from the host's echo, the socket with a cBPF filter
 * (the kernel's BPF JIT makes A64 code for it).
 *
 * A64_MEMTEST (arguments "memtest=<MiB>" and "high=<pfn>", P8.5): first,
 * that much memory mapped, written and checked in 64 MiB pieces, its frames
 * counted at or above the PFN (extended RAM); in a page there, code run
 * until it is compiled, rewritten and run again, an exclusive counter and
 * DC ZVA. Then the probe goes on.
 *
 * "ref=qemu": the reference run on QEMU's cortex-a35 (which has AArch32 and
 * whose STXR compares values): excl_aba and aarch32 are only reported.
 * "parallel": v86 with its cores in workers, whose STXR compares values too
 * (the deviation docs/aarch64.md declares): excl_aba is only reported. */
typedef long word;
typedef unsigned long uword;
enum { SYS_getcwd = 17, SYS_ioctl = 29, SYS_unlinkat = 35, SYS_ftruncate = 46, SYS_openat = 56, SYS_close = 57,
    SYS_pipe2 = 59, SYS_getdents64 = 61, SYS_lseek = 62, SYS_read = 63, SYS_write = 64, SYS_exit = 93,
    SYS_exit_group = 94, SYS_futex = 98, SYS_clock_gettime = 113, SYS_sched_setaffinity = 122,
    SYS_sched_getaffinity = 123, SYS_sched_yield = 124, SYS_tgkill = 131, SYS_rt_sigaction = 134,
    SYS_rt_sigreturn = 139, SYS_uname = 160, SYS_getcpu = 168, SYS_getpid = 172, SYS_gettid = 178,
    SYS_socket = 198, SYS_bind = 200, SYS_sendto = 206, SYS_recvfrom = 207, SYS_setsockopt = 208,
    SYS_munmap = 215, SYS_clone = 220, SYS_execve = 221, SYS_mmap = 222, SYS_mprotect = 226, SYS_wait4 = 260,
    SYS_memfd_create = 279 };
#define AT_FDCWD (-100)
static word sc(word n, word a, word b, word c, word d, word e, word f)
{
    register word x8 __asm__("x8") = n;
    register word x0 __asm__("x0") = a;
    register word x1 __asm__("x1") = b;
    register word x2 __asm__("x2") = c;
    register word x3 __asm__("x3") = d;
    register word x4 __asm__("x4") = e;
    register word x5 __asm__("x5") = f;
    __asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory", "cc");
    return x0;
}
__asm__(".text\n.global signal_return\nsignal_return:\nmov x8, #139\nsvc #0\nbrk #0\n"
    /* spawn(fn, arg, stack_top, flags): the child takes fn and arg from its stack */
    ".global spawn\nspawn:\nsub x2, x2, #16\nstp x0, x1, [x2]\nmov x0, x3\nmov x1, x2\n"
    "mov x2, xzr\nmov x3, xzr\nmov x4, xzr\nmov x8, #220\nsvc #0\ncbnz x0, 1f\n"
    "ldp x9, x0, [sp], #16\nblr x9\nmov x0, xzr\nmov x8, #93\nsvc #0\nbrk #0\n1:\nret\n"
    ".global _start\n_start:\nmov x0, sp\nbl entry\nbrk #0\n");
#define S(n, a, b, c) sc(n, (word)(a), (word)(b), (word)(c), 0, 0, 0)

void *memset(void *d, int v, unsigned long n) { unsigned char *p = d; while(n--) *p++ = (unsigned char)v; return d; }
void *memcpy(void *d, const void *s, unsigned long n) { unsigned char *p = d; const unsigned char *q = s; while(n--) *p++ = *q++; return d; }
extern void signal_return(void);
extern word spawn(void (*fn)(word), word arg, void *stack_top, word flags);

static int length(const char *s) { int n = 0; while(s[n]) n++; return n; }
static void out(const char *s) { S(SYS_write, 1, s, length(s)); }
static void number(unsigned long n) { char b[24]; int i = 23; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); out(b + i); }
static void hex(unsigned long n) { char b[20]; int i = 19; b[i] = 0; do { b[--i] = "0123456789abcdef"[n & 15]; n >>= 4; } while(n); b[--i] = 'x'; b[--i] = '0'; out(b + i); }
static void die(const char *s) { out("A64_PROBE_FAIL arch=aarch64 "); out(s); out("\n"); S(SYS_exit_group, 1, 0, 0); for(;;); }
static word check(word n, const char *s) { if(n < 0 && n > -4096) die(s); return n; }
static int same(const char *a, const char *b) { while(*a && *a == *b) { a++; b++; } return *a == *b; }
static int starts(const char *a, const char *prefix) { while(*prefix) if(*a++ != *prefix++) return 0; return 1; }
static unsigned long parse(const char *s) { unsigned long n = 0; while(*s >= '0' && *s <= '9') n = n * 10 + (unsigned long)(*s++ - '0'); return n; }

/* atomics: LDAXR/STLXR loops (Alpine's musl builds them the same way) */
static void add(volatile unsigned *p, unsigned v)
{
    unsigned value, failed;
    __asm__ volatile("1: ldaxr %w0, [%2]\nadd %w0, %w0, %w3\nstlxr %w1, %w0, [%2]\ncbnz %w1, 1b"
        : "=&r"(value), "=&r"(failed) : "r"(p), "r"(v) : "memory");
}
static void barrier(void) { __asm__ volatile("dmb ish" ::: "memory"); }

static word *mapping(word size, int prot) { return (word *)sc(SYS_mmap, 0, size, prot, 0x22, -1, 0); }
static int failed_mapping(void *p) { return (uword)p >= (uword)-4096; }
static uword page_size;

struct sigaction_arm64 { void *handler; uword flags; void *restorer; uword mask; };
static void on_signal(int sig, void (*handler)(int, void *, void *))
{
    /* SA_SIGINFO | SA_RESTORER */
    struct sigaction_arm64 action = {(void *)handler, 0x04000004, (void *)signal_return, 0};
    check(sc(SYS_rt_sigaction, sig, (word)&action, 0, 8, 0, 0), "sigaction");
}

/* The signal frame: siginfo's si_addr at 16; the ucontext's mcontext at
 * 176 (uc_flags, uc_link, uc_stack, uc_sigmask and arm64's padding of the
 * mask to 1024 bits, aligned to 16): fault_address, x0-x30, sp, pc, pstate,
 * then the 16-aligned __reserved records ({magic, size}: fpsimd 0x46508001,
 * esr 0x45535201, end 0). */
#define MCONTEXT 176
static uword record(void *context, unsigned magic)
{
    unsigned char *r = (unsigned char *)context + MCONTEXT + 8 + 31 * 8 + 3 * 8;
    r = (unsigned char *)(((uword)r + 15) & ~(uword)15);
    for(int n = 0; n < 64; n++)
    {
        unsigned m = *(unsigned *)r, size = *(unsigned *)(r + 4);
        if(m == magic) return (uword)r;
        if(m == 0 || size == 0) return 0;
        r += size;
    }
    return 0;
}
static volatile uword fault_address, fault_far, fault_esr;
static volatile word *protected_page;
static void segv(int sig, void *info, void *context)
{
    (void)sig;
    fault_address = *(uword *)((char *)info + 16);
    fault_far = *(uword *)((char *)context + MCONTEXT);
    uword esr = record(context, 0x45535201);
    fault_esr = esr ? *(uword *)(esr + 8) : ~0ul;
    check(S(SYS_mprotect, protected_page, page_size, 3), "mprotect restore");
}

#define THREADS 8
#define ITERATIONS 20000
static unsigned cpus;
static volatile unsigned counter, finished, bound[THREADS];
static volatile word *watched;
static volatile unsigned readers, remapped, stale;
static char stacks[THREADS][32768] __attribute__((aligned(16)));
static void set_cpu(unsigned cpu)
{
    uword mask = 1ul << cpu;
    check(S(SYS_sched_setaffinity, 0, sizeof(mask), &mask), "affinity");
}
static unsigned current_cpu(void) { unsigned cpu = ~0u; check(S(SYS_getcpu, &cpu, 0, 0), "getcpu"); return cpu; }
static void worker(word id)
{
    set_cpu((unsigned)id % cpus);
    if(current_cpu() != (unsigned)id % cpus) die("thread migration");
    bound[id] = current_cpu() + 1;
    for(int i = 0; i < ITERATIONS; i++)
    {
        add(&counter, 1);
        if((i & 1023) == 0) S(SYS_sched_yield, 0, 0, 0);
    }
    word seen = 0;
    add(&readers, 1);
    while(!remapped) seen += *watched;
    barrier();
    if(*watched != 2) add(&stale, 1);
    (void)seen;
    add(&finished, 1);
}

static word read_file(const char *path, char *buffer, word size)
{
    word fd = check(sc(SYS_openat, AT_FDCWD, (word)path, 0, 0, 0, 0), path);
    word n = 0, k;
    while(n < size - 1 && (k = check(S(SYS_read, fd, buffer + n, size - 1 - n), path)) > 0) n += k;
    S(SYS_close, fd, 0, 0);
    buffer[n] = 0;
    return n;
}

/* The auxiliary vector follows argv and envp on the initial stack */
static word *initial_stack;
static uword auxv(uword type)
{
    word *p = initial_stack + 1 + initial_stack[0] + 1;
    while(*p) p++;
    for(p++; p[0]; p += 2) if((uword)p[0] == type) return (uword)p[1];
    return 0;
}
static const char *argument(const char *prefix)
{
    for(word i = 1; i < initial_stack[0]; i++)
        if(starts((const char *)initial_stack[1 + i], prefix)) return (const char *)initial_stack[1 + i] + length(prefix);
    return 0;
}
static int reference, value_compare, aarch32_profile;

/* --- the multicore matrix (A64_PROBE_XC) --- */
#define MIGRATIONS 24
#define SIGNALS 16
#define SMC_ROUNDS 64
static volatile word tids[THREADS];
static volatile unsigned signalled[THREADS], moved[THREADS], xc_done, xc_ready;
static volatile unsigned smc_sequence, smc_ack, smc_bad;
static char xc_stacks[THREADS][32768] __attribute__((aligned(16)));
static unsigned *smc_code;
static uword ctr;
static void rt_signal(int sig, void *info, void *context)
{
    (void)sig; (void)info; (void)context;
    word tid = S(SYS_gettid, 0, 0, 0);
    for(unsigned id = 0; id < THREADS; id++) if(tids[id] == tid) add(&signalled[id], 1);
}
/* Make `count` instruction words at `code` (written through `data`, the same
 * memory) visible to instruction fetch on every CPU */
static void sync_code(void *data, void *code, uword count)
{
    uword dline = 4u << (ctr >> 16 & 15), iline = 4u << (ctr & 15);
    if(!(ctr >> 28 & 1)) /* IDC */
        for(uword a = (uword)data & ~(dline - 1); a < (uword)data + count * 4; a += dline) __asm__ volatile("dc cvau, %0" :: "r"(a) : "memory");
    __asm__ volatile("dsb ish" ::: "memory");
    if(!(ctr >> 29 & 1)) /* DIC */
        for(uword a = (uword)code & ~(iline - 1); a < (uword)code + count * 4; a += iline) __asm__ volatile("ic ivau, %0" :: "r"(a) : "memory");
    __asm__ volatile("dsb ish" ::: "memory");
}
/* movz w0, #value; mov w1, #100; 1: subs w1, w1, #1; b.ne 1b; ret */
static void write_function(unsigned *at, unsigned value)
{
    at[0] = 0x52800000u | (value & 0xFFFF) << 5;
    at[1] = 0x52800C81u;
    at[2] = 0x71000421u;
    at[3] = 0x54FFFFE1u;
    at[4] = 0xD65F03C0u;
}
static unsigned call(void *code) { __asm__ volatile("isb" ::: "memory"); return ((unsigned (*)(void))code)(); }

/* --- A64_MEMTEST: extended RAM (P8.5) --- */
#define MEMTEST_PIECE (64ul << 20)
static unsigned long long memtest_frames[512];
/* The frames of `pages` pages from `at` (pagemap), each present */
static void frames_of(word map, unsigned char *at, uword pages)
{
    check(S(SYS_lseek, map, (uword)at / page_size * 8, 0), "pagemap seek");
    for(word done = 0, n; done < (word)(pages * 8); done += n)
        if((n = check(S(SYS_read, map, (char *)memtest_frames + done, pages * 8 - done), "pagemap read")) == 0) die("pagemap eof");
    for(uword i = 0; i < pages; i++) if(!(memtest_frames[i] >> 63)) die("memtest page not present");
}
static void memtest(uword mib, uword threshold)
{
    static unsigned char *pieces[1024];
    uword count = mib / 64, errors = 0, above = 0, pages = 0, last = page_size / 8 - 1;
    if(count == 0 || count > 1024) die("memtest size");
    for(uword p = 0; p < count; p++)
    {
        pieces[p] = (unsigned char *)mapping(MEMTEST_PIECE, 3);
        if(failed_mapping(pieces[p])) die("memtest mmap");
        for(uword offset = 0; offset < MEMTEST_PIECE; offset += page_size)
        {
            uword *w = (uword *)(pieces[p] + offset);
            w[0] = (uword)(pieces[p] + offset) ^ 0x5A5A5A5A5A5A5A5Aul;
            w[last] = p * MEMTEST_PIECE + offset;
        }
    }
    word map = check(sc(SYS_openat, AT_FDCWD, (word)"/proc/self/pagemap", 0, 0, 0, 0), "open pagemap");
    unsigned char *high = 0;
    for(uword p = 0; p < count; p++)
    {
        for(uword offset = 0; offset < MEMTEST_PIECE; offset += page_size)
        {
            uword *w = (uword *)(pieces[p] + offset);
            if(w[0] != ((uword)(pieces[p] + offset) ^ 0x5A5A5A5A5A5A5A5Aul) || w[last] != p * MEMTEST_PIECE + offset) errors++;
        }
        for(uword first = 0; first < MEMTEST_PIECE / page_size; first += 512)
        {
            uword n = MEMTEST_PIECE / page_size - first < 512 ? MEMTEST_PIECE / page_size - first : 512;
            frames_of(map, pieces[p] + first * page_size, n);
            for(uword i = 0; i < n; i++)
            {
                if((memtest_frames[i] & ((1ull << 55) - 1)) >= threshold)
                {
                    above++;
                    if(!high) high = pieces[p] + (first + i) * page_size;
                }
                pages++;
            }
        }
    }
    /* code, an exclusive counter and DC ZVA in a page of extended RAM: the
     * function runs until the page tier has compiled it (its 2000th call),
     * then each rewrite (the store retires the compiled code) must show */
    unsigned code = 0, exclusive = 0, zva = 0;
    if(high)
    {
        __asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr));
        check(S(SYS_mprotect, high, page_size, 7), "mprotect exec");
        unsigned *function = (unsigned *)(high + 1024);
        code = 1;
        for(unsigned round = 1; round <= 16; round++)
        {
            write_function(function, round * 7 + 1);
            sync_code(function, function, 5);
            for(unsigned n = 0; n < 2000; n++) if(call(function) != round * 7 + 1) { code = 0; break; }
        }
        volatile unsigned *counter_there = (volatile unsigned *)(high + 64);
        *counter_there = 0;
        for(unsigned n = 0; n < 10000; n++) add(counter_there, 1);
        exclusive = *counter_there == 10000;
        memset(high + 2048, 0xFF, 256);
        __asm__ volatile("dc zva, %0" :: "r"(high + 2048 + 64) : "memory");
        zva = 1;
        for(int i = 0; i < 256; i++) if(high[2048 + i] != (i >= 64 && i < 128 ? 0 : 0xFF)) zva = 0;
        /* (still in extended RAM after all that) */
        frames_of(map, high, 1);
        if((memtest_frames[0] & ((1ull << 55) - 1)) < threshold) die("memtest page moved");
    }
    S(SYS_close, map, 0, 0);
    for(uword p = 0; p < count; p++) check(S(SYS_munmap, pieces[p], MEMTEST_PIECE, 0), "memtest munmap");
    out("A64_MEMTEST mib="); number(mib); out(" pages="); number(pages); out(" errors="); number(errors);
    out(" extended_pages="); number(above); out(" code="); number(code); out(" exclusive="); number(exclusive);
    out(" zva="); number(zva); out("\n");
    if(errors) die("memtest contents");
}

static void xc_worker(word id)
{
    tids[id] = S(SYS_gettid, 0, 0, 0);
    for(unsigned k = 0; k < MIGRATIONS; k++)
    {
        unsigned target = ((unsigned)id + k) % cpus;
        set_cpu(target);
        if(current_cpu() != target) die("migration");
        add(&moved[id], 1);
    }
    set_cpu((unsigned)id % cpus);
    add(&xc_ready, 1);
    while(signalled[id] < SIGNALS) S(SYS_sched_yield, 0, 0, 0);
    /* the last worker executes the code the main thread (on CPU 0) rewrites */
    if((unsigned)id == cpus - 1)
    {
        for(unsigned round = 1; round <= SMC_ROUNDS; round++)
        {
            while(smc_sequence != round) S(SYS_sched_yield, 0, 0, 0);
            barrier();
            if(call(smc_code) != round * 3 + 1) add(&smc_bad, 1);
            barrier();
            smc_ack = round;
        }
    }
    add(&xc_done, 1);
}

/* exclusive ABA: CPU A loads a word exclusively, CPU B writes the same value
 * back, A's store-exclusive must fail (QEMU compares values: reported only) */
static volatile unsigned aba_word __attribute__((aligned(64)));
static volatile unsigned aba_phase __attribute__((aligned(64)));
static volatile unsigned aba_failures;
#define ABA_ROUNDS 32
static char aba_stack[32768] __attribute__((aligned(16)));
static void aba_writer(word unused)
{
    (void)unused;
    set_cpu(cpus > 1 ? 1 : 0);
    for(unsigned round = 1; round <= ABA_ROUNDS; round++)
    {
        while(aba_phase != round * 2 - 1) __asm__ volatile("yield");
        barrier();
        unsigned v = aba_word;
        aba_word = v;
        barrier();
        aba_phase = round * 2;
    }
}
static void exclusive_aba(void)
{
    set_cpu(0);
    check(spawn(aba_writer, 0, aba_stack + sizeof(aba_stack), 0x00050F00), "clone aba");
    for(unsigned round = 1; round <= ABA_ROUNDS; round++)
    {
        unsigned value, status;
        __asm__ volatile("ldxr %w0, [%1]" : "=&r"(value) : "r"(&aba_word) : "memory");
        __asm__ volatile("stlr %w1, [%0]" :: "r"(&aba_phase), "r"(round * 2 - 1) : "memory");
        while(aba_phase != round * 2) __asm__ volatile("yield");
        __asm__ volatile("stxr %w0, %w2, [%1]" : "=&r"(status) : "r"(&aba_word), "r"(value + 1) : "memory");
        if(status) aba_failures++;
    }
}

/* futex ping-pong across two CPUs */
#define FUTEX_ROUNDS 200
static volatile int futex_word;
static char futex_stack[32768] __attribute__((aligned(16)));
static volatile unsigned futex_done;
static void futex_partner(word unused)
{
    (void)unused;
    set_cpu(cpus > 1 ? 1 : 0);
    for(int round = 0; round < FUTEX_ROUNDS; round++)
    {
        while(futex_word != 1) sc(SYS_futex, (word)&futex_word, 0 /* WAIT */, 0, 0, 0, 0);
        futex_word = 0;
        sc(SYS_futex, (word)&futex_word, 1 /* WAKE */, 1, 0, 0, 0);
    }
    add(&futex_done, 1);
}
static void futex_pingpong(void)
{
    set_cpu(0);
    check(spawn(futex_partner, 0, futex_stack + sizeof(futex_stack), 0x00050F00), "clone futex");
    for(int round = 0; round < FUTEX_ROUNDS; round++)
    {
        futex_word = 1;
        sc(SYS_futex, (word)&futex_word, 1, 1, 0, 0, 0);
        while(futex_word != 0) sc(SYS_futex, (word)&futex_word, 0, 1, 0, 0, 0);
    }
    while(!futex_done) S(SYS_sched_yield, 0, 0, 0);
}

/* The vDSO's __kernel_clock_gettime, from its section headers */
static word (*vdso_clock_gettime)(int, void *);
static void find_vdso(void)
{
    unsigned char *base = (unsigned char *)auxv(33 /* AT_SYSINFO_EHDR */);
    if(!base) die("AT_SYSINFO_EHDR");
    uword shoff = *(uword *)(base + 40);
    unsigned shentsize = *(unsigned short *)(base + 58), shnum = *(unsigned short *)(base + 60);
    uword phoff = *(uword *)(base + 32);
    unsigned phnum = *(unsigned short *)(base + 56), phentsize = *(unsigned short *)(base + 54);
    uword load = 0;
    for(unsigned i = 0; i < phnum; i++)
    {
        unsigned char *ph = base + phoff + i * phentsize;
        if(*(unsigned *)ph == 1) { load = *(uword *)(ph + 16); break; }
    }
    for(unsigned i = 0; i < shnum; i++)
    {
        unsigned char *sh = base + shoff + i * shentsize;
        if(*(unsigned *)(sh + 4) != 11 /* SHT_DYNSYM */) continue;
        unsigned char *strtab = base + *(uword *)(base + shoff + *(unsigned *)(sh + 40) * shentsize + 24);
        unsigned char *symbols = base + *(uword *)(sh + 24);
        uword count = *(uword *)(sh + 32) / 24;
        for(uword k = 0; k < count; k++)
        {
            unsigned char *sym = symbols + k * 24;
            if(same((const char *)strtab + *(unsigned *)sym, "__kernel_clock_gettime"))
                vdso_clock_gettime = (word (*)(int, void *))(base + *(uword *)(sym + 8) - load);
        }
    }
    if(!vdso_clock_gettime) die("vDSO __kernel_clock_gettime");
}
/* CNTVCT and the vDSO's monotonic clock read on every CPU in turn: neither
 * may go back */
#define CLOCK_ROUNDS 64
static int clocks_monotonic(void)
{
    uword last_counter = 0;
    word last_ns = 0;
    for(unsigned round = 0; round < CLOCK_ROUNDS; round++)
    {
        set_cpu(round % cpus);
        uword value;
        __asm__ volatile("isb\nmrs %0, cntvct_el0" : "=r"(value) :: "memory");
        if(value < last_counter) return 0;
        last_counter = value;
        struct { word seconds, nanoseconds; } now;
        if(vdso_clock_gettime(1 /* CLOCK_MONOTONIC */, &now)) return 0;
        word ns = now.seconds * 1000000000 + now.nanoseconds;
        if(ns < last_ns) return 0;
        last_ns = ns;
    }
    return 1;
}

/* FPCR, FPSR and V0-V31 across a system call, sched_yield, a migration, a
 * signal whose handler changes them all, and a spin during which other
 * threads run; twice as many threads as CPUs */
#define FP_THREADS (2 * THREADS)
#define FP_ROUNDS 4
#define FP_SPIN 100000
static unsigned char fp_in[FP_THREADS][32 * 16 + 16] __attribute__((aligned(16)));
static unsigned char fp_out[FP_THREADS][32 * 16 + 16] __attribute__((aligned(16)));
static volatile unsigned fp_bad, fp_steps, fp_done, fp_handled;
static volatile word fp_tids[FP_THREADS];
static char fp_stacks[FP_THREADS][32768] __attribute__((aligned(16)));
static unsigned fp_threads;
#define Q_LOAD(a, b) "ldp q" #a ", q" #b ", [%[in], #" #a "*16]\n"
#define Q_STORE(a, b) "stp q" #a ", q" #b ", [%[out], #" #a "*16]\n"
#define Q_ALL(m) m(0, 1) m(2, 3) m(4, 5) m(6, 7) m(8, 9) m(10, 11) m(12, 13) m(14, 15) \
    m(16, 17) m(18, 19) m(20, 21) m(22, 23) m(24, 25) m(26, 27) m(28, 29) m(30, 31)
static word fp_step(const unsigned char *in, unsigned char *out, word n, word a, word b, word c, word spin)
{
    register word x8 __asm__("x8") = n;
    register word x0 __asm__("x0") = a;
    register word x1 __asm__("x1") = b;
    register word x2 __asm__("x2") = c;
    __asm__ volatile(Q_ALL(Q_LOAD)
        "ldr x9, [%[in], #512]\nmsr fpcr, x9\nldr x9, [%[in], #520]\nmsr fpsr, x9\n"
        "svc #0\n1: subs %[spin], %[spin], #1\nb.ne 1b\n"
        Q_ALL(Q_STORE)
        "mrs x9, fpcr\nstr x9, [%[out], #512]\nmrs x9, fpsr\nstr x9, [%[out], #520]\n"
        : "+r"(x0), [spin] "+r"(spin) : "r"(x8), "r"(x1), "r"(x2), [in] "r"(in), [out] "r"(out)
        : "x9", "memory", "cc", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12",
          "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27",
          "v28", "v29", "v30", "v31");
    return x0;
}
static void fp_signal(int sig, void *info, void *context)
{
    (void)sig; (void)info; (void)context;
    __asm__ volatile("movi v0.16b, #0xff\nmovi v15.16b, #0x5a\nmovi v31.16b, #0\nmsr fpsr, xzr\nmov x9, #0x00c00000\nmsr fpcr, x9"
        ::: "x9", "v0", "v15", "v31", "memory");
    add(&fp_handled, 1);
}
static void fp_worker(word id)
{
    fp_tids[id] = S(SYS_gettid, 0, 0, 0);
    word tgid = S(SYS_getpid, 0, 0, 0);
    for(unsigned round = 0; round < FP_ROUNDS; round++)
    {
        for(unsigned kind = 0; kind < 5; kind++)
        {
            unsigned char *in = fp_in[id], *o = fp_out[id];
            for(int i = 0; i < 512; i++) { in[i] = (unsigned char)(id * 37 + round * 11 + kind * 5 + i * 3 + (i >> 4)); o[i] = 0; }
            /* FPCR: a rounding mode and FZ/DN by round; FPSR: some cumulative flags and QC */
            *(uword *)(in + 512) = (uword)(round & 3) << 22 | (uword)(kind & 1) << 24 | (uword)(id & 1) << 25;
            *(uword *)(in + 520) = 0x0800001Fu & (0x08000000u | (unsigned)(id + round + kind));
            uword mask = 1ul << (((unsigned)id + round + kind) % cpus);
            switch(kind)
            {
            case 0: fp_step(in, o, SYS_getpid, 0, 0, 0, 1); break;
            case 1: fp_step(in, o, SYS_sched_yield, 0, 0, 0, 1); break;
            case 2: check(fp_step(in, o, SYS_sched_setaffinity, 0, sizeof(mask), (word)&mask, 1), "fp migration"); break;
            case 3: check(fp_step(in, o, SYS_tgkill, tgid, fp_tids[id], 42, 1), "fp tgkill"); break;
            default: fp_step(in, o, SYS_getpid, 0, 0, 0, FP_SPIN); break;
            }
            for(int i = 0; i < 528; i++) if(o[i] != in[i]) { add(&fp_bad, 1); break; }
            add(&fp_steps, 1);
        }
    }
    add(&fp_done, 1);
}
static void fp_matrix(void)
{
    on_signal(42, fp_signal);
    fp_threads = 2 * cpus;
    for(unsigned id = 0; id < fp_threads; id++)
        check(spawn(fp_worker, id, fp_stacks[id] + sizeof(fp_stacks[id]), 0x00050F00), "clone fp");
    while(fp_done != fp_threads) S(SYS_sched_yield, 0, 0, 0);
}

/* An AArch32 ELF (mov r0, #42; mov r7, #1; svc #0): ENOEXEC without AArch32 */
static const char *aarch32(void)
{
    static const unsigned char elf[] = {
        0x7F, 'E', 'L', 'F', 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        2, 0, 40, 0, 1, 0, 0, 0, 0x54, 0x80, 0, 0, 0x34, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 0x34, 0, 0x20, 0, 1, 0,
        0, 0, 0, 0, 0, 0,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0x80, 0, 0, 0x60, 0, 0, 0, 0x60, 0, 0, 0, 5, 0, 0, 0, 0, 0x10, 0, 0,
        0x2A, 0x00, 0xA0, 0xE3, 0x01, 0x70, 0xA0, 0xE3, 0x00, 0x00, 0x00, 0xEF };
    word fd = check(sc(SYS_openat, AT_FDCWD, (word)"/tmp/a64-arm32", 01101, 0755, 0, 0), "open arm32");
    check(S(SYS_write, fd, elf, sizeof(elf)), "write arm32");
    S(SYS_close, fd, 0, 0);
    word child = check(sc(SYS_clone, 17 /* SIGCHLD */, 0, 0, 0, 0, 0), "fork arm32");
    if(child == 0)
    {
        const char *argv[] = {"/tmp/a64-arm32", 0}, *envp[] = {0};
        word r = sc(SYS_execve, (word)argv[0], (word)argv, (word)envp, 0, 0, 0);
        S(SYS_exit, r == -8 ? 8 : 1, 0, 0);
    }
    int status = 0;
    check(sc(SYS_wait4, child, (word)&status, 0, 0, 0, 0), "wait arm32");
    sc(SYS_unlinkat, AT_FDCWD, (word)"/tmp/a64-arm32", 0, 0, 0, 0);
    int code = status >> 8 & 255;
    return code == 8 ? "enoexec" : code == 42 ? "ran" : "other";
}

/* The probe disk: the virtio-blk device whose serial is a64probe */
static int direct_read(void)
{
    static char names[4096] __attribute__((aligned(8)));
    static char direct[8192] __attribute__((aligned(4096)));
    /* (arm64's own O_DIRECTORY and O_DIRECT: 040000 and 0200000) */
    word dir = check(sc(SYS_openat, AT_FDCWD, (word)"/sys/block", 040000 /* O_DIRECTORY */, 0, 0, 0), "/sys/block");
    word n = check(S(SYS_getdents64, dir, names, sizeof(names)), "getdents");
    S(SYS_close, dir, 0, 0);
    for(word at = 0; at < n; at += *(unsigned short *)(names + at + 16))
    {
        const char *name = names + at + 19;
        if(!starts(name, "vd")) continue;
        char path[64], serial[64], device[32];
        int k = 0;
        for(const char *q = "/sys/block/"; *q; q++) path[k++] = *q;
        for(const char *q = name; *q; q++) path[k++] = *q;
        for(const char *q = "/serial"; *q; q++) path[k++] = *q;
        path[k] = 0;
        word probe = sc(SYS_openat, AT_FDCWD, (word)path, 0, 0, 0, 0);
        if(probe < 0) continue;
        S(SYS_close, probe, 0, 0);
        read_file(path, serial, sizeof(serial));
        if(!starts(serial, "a64probe")) continue;
        k = 0;
        for(const char *q = "/dev/"; *q; q++) device[k++] = *q;
        for(const char *q = name; *q; q++) device[k++] = *q;
        device[k] = 0;
        word disk = check(sc(SYS_openat, AT_FDCWD, (word)device, 0200000 /* O_DIRECT */, 0, 0, 0), "open O_DIRECT");
        if(check(S(SYS_read, disk, direct, 4096), "direct read") != 4096) die("direct read length");
        S(SYS_close, disk, 0, 0);
        if(!(direct[257] == 'u' && direct[258] == 's' && direct[259] == 't' && direct[260] == 'a' && direct[261] == 'r')) die("direct read contents");
        return 1;
    }
    die("no virtio-blk disk with serial a64probe");
    return 0;
}

static void matrix(int disk)
{
    char path[80], text[64];
    unsigned cores_seen = 0;
    for(unsigned cpu = 0; cpu < cpus; cpu++)
    {
        const char *parts[3] = {"physical_package_id", "core_id", "thread_siblings_list"};
        unsigned long values[3];
        for(int k = 0; k < 3; k++)
        {
            int n = 0;
            for(const char *q = "/sys/devices/system/cpu/cpu"; *q; q++) path[n++] = *q;
            char digits[8]; int d = 0; unsigned v = cpu; do { digits[d++] = '0' + v % 10; v /= 10; } while(v);
            while(d) path[n++] = digits[--d];
            for(const char *q = "/topology/"; *q; q++) path[n++] = *q;
            for(const char *q = parts[k]; *q; q++) path[n++] = *q;
            path[n] = 0;
            read_file(path, text, sizeof(text));
            values[k] = parse(text);
        }
        if(values[0] != 0) die("package id");
        if(values[2] != cpu) die("thread siblings");
        if(cores_seen >> values[1] & 1) die("core id");
        cores_seen |= 1u << values[1];
    }
    int direct = disk ? direct_read() : 0;

    __asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr));
    smc_code = (unsigned *)mapping(page_size, 7);
    if(failed_mapping(smc_code)) die("mmap exec");
    write_function(smc_code, 0);
    sync_code(smc_code, smc_code, 5);
    on_signal(40, rt_signal);
    set_cpu(0);
    for(unsigned id = 0; id < cpus; id++)
        check(spawn(xc_worker, id, xc_stacks[id] + sizeof(xc_stacks[id]), 0x00050F00), "clone xc");
    while(xc_ready != cpus) S(SYS_sched_yield, 0, 0, 0);
    word tgid = S(SYS_getpid, 0, 0, 0);
    for(unsigned n = 0; n < SIGNALS; n++)
        for(unsigned id = 0; id < cpus; id++)
            check(sc(SYS_tgkill, tgid, tids[id], 40, 0, 0, 0), "tgkill");
    for(unsigned round = 1; round <= SMC_ROUNDS; round++)
    {
        write_function(smc_code, round * 3 + 1);
        sync_code(smc_code, smc_code, 5);
        barrier();
        smc_sequence = round;
        while(smc_ack != round) S(SYS_sched_yield, 0, 0, 0);
    }
    while(xc_done != cpus) S(SYS_sched_yield, 0, 0, 0);
    unsigned migrated = 0, signals = 0;
    for(unsigned id = 0; id < cpus; id++) { migrated += moved[id]; signals += signalled[id]; }
    if(migrated != cpus * MIGRATIONS) die("migration count");
    if(signals != cpus * SIGNALS) die("signal count");
    if(smc_bad) die("cross-modified code");

    /* a memfd mapped writable and executable at two addresses */
    word memfd = check(sc(SYS_memfd_create, (word)"a64-jit", 0, 0, 0, 0, 0), "memfd_create");
    check(S(SYS_ftruncate, memfd, page_size, 0), "memfd size");
    unsigned *rw = (unsigned *)sc(SYS_mmap, 0, page_size, 3, 1 /* MAP_SHARED */, memfd, 0);
    unsigned *rx = (unsigned *)sc(SYS_mmap, 0, page_size, 5, 1, memfd, 0);
    if(failed_mapping(rw) || failed_mapping(rx)) die("memfd mappings");
    unsigned dual = 0;
    for(unsigned round = 1; round <= SMC_ROUNDS; round++)
    {
        write_function(rw + (round & 7) * 8, round * 5 + 2);
        sync_code(rw + (round & 7) * 8, rx + (round & 7) * 8, 5);
        if(call(rx + (round & 7) * 8) == round * 5 + 2) dual++;
    }
    if(dual != SMC_ROUNDS) die("dual-mapped code");

    exclusive_aba();
    if(!reference && !value_compare && aba_failures != ABA_ROUNDS)
        die("exclusive ABA: a store-exclusive succeeded after another CPU's write");
    futex_pingpong();
    find_vdso();
    if(!clocks_monotonic()) die("clock went back across CPUs");
    fp_matrix();
    if(fp_handled != fp_threads * FP_ROUNDS) die("fp signals");
    if(fp_bad) die("FPCR, FPSR or V registers across a context switch");
    const char *arm32 = aarch32();
    if(!reference && !aarch32_profile && !same(arm32, "enoexec")) die("AArch32 ELF executed");
    if(aarch32_profile && !same(arm32, "ran")) die("AArch32 ELF did not run");

    out("A64_PROBE_XC arch=aarch64 packages=1 cores="); number(cpus); out(" threads_per_core=1 migrations="); number(migrated);
    out(" signals="); number(signals); out(" smc_rounds="); number(SMC_ROUNDS); out(" dual_map="); number(dual);
    out(" excl_aba="); number(aba_failures == ABA_ROUNDS); out(" futex="); number(FUTEX_ROUNDS);
    out(" clocks=1 fp_threads="); number(fp_threads); out(" fp_steps="); number(fp_steps); out(" fp_bad="); number(fp_bad);
    out(" aarch32="); out(arm32); out(" direct_io="); number(direct); out("\n");
}

/* AF_PACKET socket on eth0 with a cBPF filter for EtherType 88B5: send
 * frames, receive the host's echoes */
#define NET_FRAMES 16
static void network(void)
{
    struct { unsigned short family, protocol; int ifindex; unsigned short hatype; unsigned char pkttype, halen, addr[8]; } address = {0};
    word fd = check(sc(SYS_socket, 17 /* AF_PACKET */, 3 /* SOCK_RAW */, 0xB588 /* htons(0x88B5) */, 0, 0, 0), "packet socket");
    /* ldh [12]; jeq #0x88b5, accept; ret #0; accept: ret #0xffff */
    static const struct { unsigned short code; unsigned char jt, jf; unsigned k; } filter[] = {
        {0x28, 0, 0, 12}, {0x15, 0, 1, 0x88B5}, {0x06, 0, 0, 0xFFFF}, {0x06, 0, 0, 0} };
    struct { unsigned short count; const void *code; } program = {4, filter};
    check(sc(SYS_setsockopt, fd, 1 /* SOL_SOCKET */, 26 /* SO_ATTACH_FILTER */, (word)&program, sizeof(program), 0), "socket filter");
    char request[40] = {'e', 't', 'h', '0', 0};
    check(S(SYS_ioctl, fd, 0x8933 /* SIOCGIFINDEX */, request), "eth0 index");
    address.family = 17; address.protocol = 0xB588; address.ifindex = *(int *)(request + 16); address.halen = 6;
    for(int i = 0; i < 6; i++) address.addr[i] = 255;
    check(sc(SYS_bind, fd, (word)&address, sizeof(address), 0, 0, 0), "bind packet socket");
    struct { long seconds, microseconds; } timeout = {10, 0};
    check(sc(SYS_setsockopt, fd, 1, 20 /* SO_RCVTIMEO */, (word)&timeout, sizeof(timeout), 0), "receive timeout");
    for(unsigned round = 0; round < NET_FRAMES; round++)
    {
        unsigned char frame[96] = {0}, received[160];
        for(int i = 0; i < 6; i++) frame[i] = 255;
        frame[6] = 2; frame[11] = 1; frame[12] = 0x88; frame[13] = 0xB5;
        for(unsigned i = 14; i < sizeof(frame); i++) frame[i] = (unsigned char)(i * 7 + round * 13 + 'a');
        if(check(sc(SYS_sendto, fd, (word)frame, sizeof(frame), 0, 0, 0), "send frame") != sizeof(frame)) die("short frame");
        for(;;)
        {
            word n = sc(SYS_recvfrom, fd, (word)received, sizeof(received), 0, 0, 0);
            if(n == -4) continue; /* EINTR */
            if(check(n, "receive frame") < (word)sizeof(frame)) die("short echo");
            if(received[11] != 2) continue; /* our own transmitted frame */
            for(unsigned i = 14; i < sizeof(frame); i++) if(received[i] != frame[i]) die("echo payload");
            break;
        }
    }
    S(SYS_close, fd, 0, 0);
    out("A64_PROBE_NET arch=aarch64 frames="); number(NET_FRAMES); out("\n");
}

/* AT_HWCAP of the profile v86-aarch64-v1 (tests/platform/a64-profile.json):
 * fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid */
#define HWCAP_PROFILE 0x8FFul
static const char *const FEATURES = "fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid";

void entry(word *stack)
{
    initial_stack = stack;
    reference = argument("ref=qemu") != 0;
    value_compare = argument("parallel") != 0;
    /* (v86's profile v3, docs/aarch32-plan.md: AArch32 at EL0, as the reference) */
    aarch32_profile = argument("aarch32") != 0;
    int disk = !argument("nodisk");
    out("A64_PROBE_START arch=aarch64\n");
    page_size = auxv(6 /* AT_PAGESZ */);
    if(page_size != 4096 && page_size != 16384 && page_size != 65536) die("AT_PAGESZ");
    struct { char sysname[65], nodename[65], release[65], version[65], machine[65], domain[65]; } names;
    check(S(SYS_uname, &names, 0, 0), "uname");
    if(!same(names.machine, "aarch64")) die("uname machine");

    uword affinity[16] = {0};
    word bytes = check(S(SYS_sched_getaffinity, 0, sizeof(affinity), affinity), "getaffinity");
    for(word i = 0; i < bytes / (word)sizeof(affinity[0]); i++)
        for(uword m = affinity[i]; m; m &= m - 1) cpus++;
    if(cpus == 0 || cpus > THREADS) die("cpu count");

    /* HWCAP, /proc/cpuinfo, the ID register as EL0 sees it */
    uword hwcap = auxv(16), hwcap2 = auxv(26);
    if(!reference && (hwcap != HWCAP_PROFILE || hwcap2 != 0)) die("AT_HWCAP");
    static char cpuinfo[16384];
    read_file("/proc/cpuinfo", cpuinfo, sizeof(cpuinfo));
    const char *features = 0;
    for(const char *p = cpuinfo; *p; p++) if(starts(p, "Features\t: ")) { features = p + 11; break; }
    if(!features) die("/proc/cpuinfo Features");
    int features_match = 1;
    for(int i = 0; FEATURES[i]; i++) if(features[i] != FEATURES[i]) features_match = 0;
    if(features[length(FEATURES)] != '\n') features_match = 0;
    if(!reference && !features_match) die("/proc/cpuinfo Features");
    uword isar0, midr;
    __asm__ volatile("mrs %0, id_aa64isar0_el1\nmrs %1, midr_el1" : "=r"(isar0), "=r"(midr));
    if(isar0 != 0x11120) die("ID_AA64ISAR0_EL1 at EL0");

    /* DC ZVA: DCZID_EL0 says 64-byte blocks, allowed */
    uword dczid;
    __asm__ volatile("mrs %0, dczid_el0" : "=r"(dczid));
    static unsigned char zva[256] __attribute__((aligned(64)));
    memset(zva, 0xFF, sizeof(zva));
    int dczva = 0;
    if((dczid & 31) == 4)
    {
        __asm__ volatile("dc zva, %0" :: "r"(zva + 64) : "memory");
        dczva = 1;
        for(int i = 0; i < 256; i++) if(zva[i] != (i >= 64 && i < 128 ? 0 : 0xFF)) dczva = 0;
    }
    if(!reference && !dczva) die("DC ZVA");

    const char *memtest_size = argument("memtest=");
    if(memtest_size) memtest(parse(memtest_size), argument("high=") ? parse(argument("high=")) : ~0ul);

    /* mmap, then write to a read-only page: the handler sees the exact
     * address (siginfo, sigcontext's FAR) and the ESR (a data abort from
     * EL0, a write, a permission fault), restores write access, and the
     * faulting store is retried */
    word *pages = mapping(2 * page_size, 3);
    if(failed_mapping(pages)) die("mmap");
    for(uword i = 0; i < page_size / sizeof(word); i++) pages[i] = (word)i * 0x01010101;
    protected_page = (word *)((char *)pages + page_size);
    /* (present before mprotect: the write is a permission fault, not a
     * translation fault) */
    protected_page[0] = 1;
    on_signal(11, segv);
    check(S(SYS_mprotect, protected_page, page_size, 1), "mprotect");
    protected_page[3] = 0x5A5A;
    uword target = (uword)protected_page + 3 * sizeof(word);
    if(fault_address != target || fault_far != target || protected_page[3] != 0x5A5A) die("SIGSEGV round trip");
    /* EC 0x24 (data abort from a lower EL), WnR, a level-3 permission fault */
    if((fault_esr >> 26) != 0x24 || !(fault_esr >> 6 & 1) || (fault_esr & 0x3C) != 0xC) { out("A64_PROBE_ESR "); hex(fault_esr); out("\n"); die("ESR of the fault"); }
    if(pages[5] != 5 * 0x01010101) die("mapping contents");

    int fds[2];
    check(S(SYS_pipe2, fds, 0, 0), "pipe2");
    word child = check(sc(SYS_clone, 17 /* SIGCHLD */, 0, 0, 0, 0, 0), "fork");
    if(child == 0)
    {
        word pid = S(SYS_getpid, 0, 0, 0);
        S(SYS_write, fds[1], &pid, sizeof(pid));
        S(SYS_exit, 7, 0, 0);
    }
    word reported = 0;
    if(check(S(SYS_read, fds[0], &reported, sizeof(reported)), "pipe read") != sizeof(reported) || reported != child) die("pipe pid");
    int status = 0;
    if(check(sc(SYS_wait4, child, (word)&status, 0, 0, 0, 0), "wait4") != child || status != 7 << 8) die("child status");

    watched = mapping(page_size, 3);
    if(failed_mapping((void *)watched)) die("mmap watched");
    *watched = 1;
    /* CLONE_VM|FS|FILES|SIGHAND|THREAD|SYSVSEM */
    for(unsigned id = 0; id < cpus; id++)
        check(spawn(worker, id, stacks[id] + sizeof(stacks[id]), 0x00050F00), "clone");
    while(readers != cpus) S(SYS_sched_yield, 0, 0, 0);
    /* MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED over the page */
    if(sc(SYS_mmap, (word)watched, page_size, 3, 0x32, -1, 0) != (word)watched) die("mmap fixed");
    *watched = 2;
    barrier();
    remapped = 1;
    while(finished != cpus) S(SYS_sched_yield, 0, 0, 0);
    if(stale) die("stale TLB entry after remap");
    if(counter != cpus * ITERATIONS) die("exclusive counter");
    for(unsigned id = 0; id < cpus; id++) if(bound[id] != id + 1) die("thread binding");

    static char data[4096], back[4096];
    for(int i = 0; i < 4096; i++) data[i] = (char)(i * 7 + 3);
    word fd = check(sc(SYS_openat, AT_FDCWD, (word)"/tmp/a64-probe-file", 0102, 0644, 0, 0), "open");
    if(check(S(SYS_write, fd, data, sizeof(data)), "file write") != sizeof(data)) die("short write");
    check(S(SYS_lseek, fd, 0, 0), "lseek");
    if(check(S(SYS_read, fd, back, sizeof(back)), "file read") != sizeof(back)) die("short read");
    for(int i = 0; i < 4096; i++) if(back[i] != data[i]) die("file contents");
    S(SYS_close, fd, 0, 0);
    check(sc(SYS_unlinkat, AT_FDCWD, (word)"/tmp/a64-probe-file", 0, 0, 0, 0), "unlink");

    /* Physical placement: touched pages whose frame is at or above the PFN
     * of "high=<pfn>" (extended RAM; none without it), contents verified */
    const char *high = argument("high=");
    uword threshold = high ? parse(high) : ~0ul;
    enum { BLOCK = 16 << 20 };
    uword count = BLOCK / page_size;
    static unsigned long long frames[4096];
    unsigned char *block = (unsigned char *)mapping(BLOCK, 3);
    if(failed_mapping(block)) die("mmap block");
    for(uword i = 0; i < count; i++) block[i * page_size + (i & 4095)] = (unsigned char)(i * 13 + 1);
    word map = check(sc(SYS_openat, AT_FDCWD, (word)"/proc/self/pagemap", 0, 0, 0, 0), "open pagemap");
    check(S(SYS_lseek, map, (uword)block / page_size * 8, 0), "pagemap seek");
    for(word done = 0, n; done < (word)(count * 8); done += n)
        if((n = check(S(SYS_read, map, (char *)frames + done, count * 8 - done), "pagemap read")) == 0) die("pagemap eof");
    S(SYS_close, map, 0, 0);
    unsigned high_pages = 0;
    for(uword i = 0; i < count; i++)
    {
        if(!(frames[i] >> 63)) die("page not present");
        if((frames[i] & ((1ull << 55) - 1)) >= threshold) high_pages++;
        if(block[i * page_size + (i & 4095)] != (unsigned char)(i * 13 + 1)) die("block contents");
    }

    out("A64_PROBE_OK arch=aarch64 cpus="); number(cpus);
    out(" threads="); number(cpus); out(" counter="); number(counter);
    out(" cpu_checks="); for(unsigned id = 0; id < cpus; id++) { if(id) out(","); number(bound[id] - 1); }
    out(" fault=page esr="); hex(fault_esr); out(" child=7 tlb_stale="); number(stale);
    out(" page_size="); number(page_size); out(" hwcap="); hex(hwcap); out(" hwcap2="); hex(hwcap2);
    out(" features="); number(features_match); out(" isar0="); hex(isar0); out(" midr="); hex(midr);
    out(" dczva="); number(dczva); out(" high_pages="); number(high_pages); out("\n");
    matrix(disk);
    if(argument("net")) network();
    S(SYS_exit_group, 0, 0, 0);
    for(;;);
}
                                                                                                                                                                                                                                                                         source/v64/tests/a64/linux_probe32.c                                                                0000644 0000000 0000000 00000035157 00000000000 014272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The AArch32 process probe (docs/aarch32-plan.md Q5.1): a static
 * freestanding ARM EABI program, built for A32 and for T32
 * (tests/a64/linux_boot.mjs with A64_WORKLOAD=aarch32), that a 64-bit
 * kernel runs as a compat task. It prints one A32_PROBE line of what it
 * found, the same on the reference (QEMU's cortex-a35) and on v86's
 * profile v3: the compat syscalls (uname, getpid, clock_gettime64, mmap2,
 * mprotect, the ARM private set_tls and cacheflush), the auxiliary vector's
 * HWCAP and HWCAP2, /proc/cpuinfo's Features as a 32-bit process sees
 * them, signals through the kernel's return trampoline (the VFP registers
 * and FPSCR restored after a handler changed them), SIGILL of an UNDEFINED
 * instruction (its address, the handler stepping over it), threads that
 * count with LDREX/STREX and keep their own D0-D31 and FPSCR across
 * sched_yield, the TLS registers (TPIDRURO from set_tls, TPIDRURW written
 * at EL0), unaligned loads, SDIV and UDIV, a generated function run after
 * cacheflush, and known answers of NEON, AES, SHA-256 and VMULL.P64. */
typedef unsigned int u32;
typedef int s32;
typedef unsigned long long u64;
/* (the mode the compiler's code is in, after the file's own A32 assembly) */
#ifdef __thumb__
#define MODE ".thumb\n"
#else
#define MODE ".arm\n"
#endif

/* (what the compiler may call: it is freestanding) */
void *memset(void *d, int c, unsigned n) { unsigned char *p = d; while(n--) *p++ = (unsigned char)c; return d; }
void *memcpy(void *d, const void *s, unsigned n) { unsigned char *p = d; const unsigned char *q = s; while(n--) *p++ = *q++; return d; }
void __aeabi_memset(void *d, unsigned n, int c) { memset(d, c, n); }
void __aeabi_memclr(void *d, unsigned n) { memset(d, 0, n); }
void __aeabi_memcpy(void *d, const void *s, unsigned n) { memcpy(d, s, n); }
void __aeabi_memset4(void *d, unsigned n, int c) { memset(d, c, n); }
void __aeabi_memclr4(void *d, unsigned n) { memset(d, 0, n); }
void __aeabi_memcpy4(void *d, const void *s, unsigned n) { memcpy(d, s, n); }

enum { NR_exit = 1, NR_read = 3, NR_write = 4, NR_close = 6, NR_getpid = 20, NR_uname = 122,
    NR_mprotect = 125, NR_sched_yield = 158, NR_rt_sigaction = 174, NR_mmap2 = 192, NR_gettid = 224,
    NR_futex = 240, NR_exit_group = 248, NR_tgkill = 268, NR_openat = 322, NR_clock_gettime64 = 403,
    NR_clone = 120, NR_cacheflush = 0xf0002, NR_set_tls = 0xf0005 };

static s32 sc(u32 n, u32 a, u32 b, u32 c, u32 d, u32 e, u32 f)
{
    register u32 r7 __asm__("r7") = n;
    register u32 r0 __asm__("r0") = a;
    register u32 r1 __asm__("r1") = b;
    register u32 r2 __asm__("r2") = c;
    register u32 r3 __asm__("r3") = d;
    register u32 r4 __asm__("r4") = e;
    register u32 r5 __asm__("r5") = f;
    __asm__ volatile("svc #0" : "+r"(r0) : "r"(r7), "r"(r1), "r"(r2), "r"(r3), "r"(r4), "r"(r5) : "memory", "cc");
    return (s32)r0;
}
#define S(n, a, b, c) sc(n, (u32)(a), (u32)(b), (u32)(c), 0, 0, 0)

static u32 length(const char *s) { u32 n = 0; while(s[n]) n++; return n; }
static void out(const char *s) { S(NR_write, 1, s, length(s)); }
static void hex(u32 v) { char b[11] = "0x"; for(int i = 0; i < 8; i++) b[2 + i] = "0123456789abcdef"[v >> (28 - 4 * i) & 15]; b[10] = 0; out(b); }
static void number(u32 v) { char b[12]; int i = 11; b[i] = 0; do b[--i] = '0' + v % 10; while(v /= 10); out(b + i); }
static void die(const char *why) { out("A32_PROBE_FAIL "); out(why); out("\n"); S(NR_exit_group, 1, 0, 0); for(;;); }
static s32 check(s32 r, const char *what) { if(r < 0 && r > -4096) die(what); return r; }
static int same(const char *a, const char *b) { while(*a && *a == *b) a++, b++; return *a == *b; }

static u32 *initial_stack;
static u32 auxv(u32 type)
{
    u32 *p = initial_stack + 1 + initial_stack[0] + 1;
    while(*p) p++;
    for(p++; p[0]; p += 2) if(p[0] == type) return p[1];
    return 0;
}

/* --- signals: the kernel's trampoline (no SA_RESTORER), siginfo, ucontext --- */
struct sigaction32 { void *handler; u32 flags; void *restorer; u32 mask[2]; };
#define SA_SIGINFO 4
#define SIGILL 4
#define SIGUSR1 10
static volatile u32 usr1_seen, ill_seen, ill_address, ill_code;

static void usr1(int sig, void *info, void *context)
{
    (void)info; (void)context;
    usr1_seen = sig;
    /* (D8, D31 and FPSCR changed here: the return restores the interrupted ones) */
    __asm__ volatile("vmov.i32 d8, #0x55\n vmov.i32 d31, #0x66\n vmrs r0, fpscr\n bic r0, r0, #0xC00000\n vmsr fpscr, r0"
        ::: "r0", "d8", "d31", "memory");
}

static void ill(int sig, void *info, void *context)
{
    ill_seen = sig;
    ill_code = ((u32 *)info)[2];
    ill_address = ((u32 *)info)[3];
    /* uc_mcontext at 20: trap_no, error_code, oldmask, r0-r10, fp, ip, sp, lr, pc (92), cpsr (96) */
    u32 *pc = (u32 *)((char *)context + 92), cpsr = *(u32 *)((char *)context + 96);
    *pc += cpsr & 0x20 ? 2 : 4;
}

static void handle(int sig, void (*fn)(int, void *, void *))
{
    struct sigaction32 a = { (void *)fn, SA_SIGINFO, 0, { 0, 0 } };
    check(sc(NR_rt_sigaction, sig, (u32)&a, 0, 8, 0, 0), "rt_sigaction");
}

/* D8 and D31 with known values, FPSCR to round toward zero, SIGUSR1 to
 * itself, then what came back: the handler's changes must be gone */
static u32 signal_vfp(void)
{
    u32 d8[2], d31[2], fpscr;
    u32 pid = S(NR_getpid, 0, 0, 0), tid = S(NR_gettid, 0, 0, 0);
    __asm__ volatile(
        "vmov.i32 d8, #0x11\n vmov.i32 d31, #0x22\n"
        "vmrs r0, fpscr\n orr r0, r0, #0xC00000\n vmsr fpscr, r0\n"
        "mov r0, %[pid]\n mov r1, %[tid]\n mov r2, #10\n mov r7, #0x10C\n svc #0\n"
        "vstr d8, [%[d8]]\n vstr d31, [%[d31]]\n vmrs r0, fpscr\n str r0, [%[fpscr]]\n"
        "vmrs r0, fpscr\n bic r0, r0, #0xC00000\n vmsr fpscr, r0"
        : : [pid] "r"(pid), [tid] "r"(tid), [d8] "r"(d8), [d31] "r"(d31), [fpscr] "r"(&fpscr)
        : "r0", "r1", "r2", "r7", "d8", "d31", "memory");
    return d8[0] == 0x11 && d8[1] == 0x11 && d31[0] == 0x22 && d31[1] == 0x22 && (fpscr >> 22 & 3) == 3;
}

/* --- threads: LDREX/STREX counting, their own VFP state across yields --- */
#define THREADS 4
#define ROUNDS 20000
#define YIELDS 40
static volatile u32 counter, vfp_bad;
static volatile s32 child_tids[THREADS];
static u32 stacks[THREADS][2048] __attribute__((aligned(16)));

static void add_one(volatile u32 *p)
{
    u32 tmp, failed;
    __asm__ volatile("1: ldrex %0, [%2]\n add %0, %0, #1\n strex %1, %0, [%2]\n cmp %1, #0\n bne 1b\n dmb ish"
        : "=&r"(tmp), "=&r"(failed) : "r"(p) : "cc", "memory");
}

static void vfp_rounds(u32 seed)
{
    u32 in[64], back[64];
    for(int i = 0; i < 64; i++) in[i] = seed * 0x9E3779B9u ^ (u32)i * 0x85EBCA6Bu;
    for(int r = 0; r < YIELDS; r++)
    {
        u32 fpscr_in = ((seed + r) & 3) << 22, fpscr_out;
        __asm__ volatile(
            "vldmia %[in], {d0-d15}\n add r0, %[in], #128\n vldmia r0, {d16-d31}\n"
            "vmrs r1, fpscr\n bic r1, r1, #0xC00000\n orr r1, r1, %[mode]\n vmsr fpscr, r1\n"
            "mov r7, #158\n svc #0\n"
            "vstmia %[back], {d0-d15}\n add r0, %[back], #128\n vstmia r0, {d16-d31}\n vmrs r1, fpscr\n str r1, [%[out]]"
            : : [in] "r"(in), [back] "r"(back), [mode] "r"(fpscr_in), [out] "r"(&fpscr_out)
            : "r0", "r1", "r7", "memory", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12",
              "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27",
              "d28", "d29", "d30", "d31");
        for(int i = 0; i < 64; i++) if(back[i] != in[i]) vfp_bad++;
        if((fpscr_out >> 22 & 3) != ((seed + r) & 3)) vfp_bad++;
    }
}

static void worker(u32 n)
{
    for(int i = 0; i < ROUNDS; i++) add_one(&counter);
    vfp_rounds(n + 1);
}

/* spawn(fn, arg, stack_top, child_tid): a thread (CLONE_VM ... THREAD,
 * CHILD_CLEARTID: its tid word cleared and woken at exit) */
extern s32 spawn(void (*fn)(u32), u32 arg, void *stack_top, volatile s32 *child_tid);
__asm__(".text\n.arm\n.global spawn\n.type spawn, %function\nspawn:\n"
    "push {r4, r7}\n"
    "stmdb r2!, {r0, r1}\n"
    "mov r4, r3\n"
    "ldr r0, =0x350F00\n"        /* VM FS FILES SIGHAND THREAD SYSVSEM CHILD_CLEARTID */
    "mov r1, r2\n mov r2, #0\n mov r3, #0\n mov r7, #120\n svc #0\n"
    "cmp r0, #0\n bne 1f\n"
    "pop {r0, r1}\n mov r2, r0\n mov r0, r1\n blx r2\n"
    "mov r0, #0\n mov r7, #1\n svc #0\n"
    "1: pop {r4, r7}\n bx lr\n.ltorg\n" MODE);

static void join(volatile s32 *tid)
{
    for(;;)
    {
        s32 t = *tid;
        if(t == 0) return;
        sc(NR_futex, (u32)tid, 0 /* FUTEX_WAIT */, (u32)t, 0, 0, 0);
    }
}

/* --- known answers --- */
static void vector(const char *name, const u32 *v, int words)
{
    out(" "); out(name); out("=");
    for(int i = words - 1; i >= 0; i--) { char b[9]; for(int k = 0; k < 8; k++) b[k] = "0123456789abcdef"[v[i] >> (28 - 4 * k) & 15]; b[8] = 0; out(b); }
}

static void known_answers(void)
{
    static const u32 a[4] = { 0x00112233, 0x44556677, 0x8899aabb, 0xccddeeff }, b[4] = { 0x0f0e0d0c, 0x0b0a0908, 0x07060504, 0x03020100 };
    u32 r[4];
    /* NEON: VQADD.S16, VMUL.F32 and VMLA.F32 (unfused), VPADD.I32, VCNT.8 */
    __asm__ volatile("vld1.32 {q0}, [%1]\n vld1.32 {q1}, [%2]\n vqadd.s16 q2, q0, q1\n vmul.f32 q3, q0, q1\n vmla.f32 q2, q3, q1\n"
        "vpadd.i32 d4, d4, d5\n vcnt.8 d5, d6\n vst1.32 {q2}, [%0]" : : "r"(r), "r"(a), "r"(b) : "q0", "q1", "q2", "q3", "memory");
    vector("neon", r, 4);
    /* (the crypto instructions only where HWCAP2 has them: AES 1, PMULL 2,
     * SHA1 4, SHA2 8; a CPU without them, the 32-bit reference's cortex-a15, says none) */
    u32 hwcap2 = auxv(26);
    if((hwcap2 & 15) != 15)
    {
        out(" aes=none sha=none pmull=none");
        goto vfp;
    }
    /* AES: one round (AESE, AESMC), its inverse (AESD, AESIMC) */
    __asm__ volatile("vld1.32 {q0}, [%1]\n vld1.32 {q1}, [%2]\n aese.8 q0, q1\n aesmc.8 q0, q0\n aesd.8 q0, q1\n aesimc.8 q0, q0\n vst1.32 {q0}, [%0]"
        : : "r"(r), "r"(a), "r"(b) : "q0", "q1", "memory");
    vector("aes", r, 4);
    /* SHA-256: SHA256H, SHA256H2, SHA256SU0, SHA256SU1; SHA-1: SHA1C, SHA1H */
    __asm__ volatile("vld1.32 {q0}, [%1]\n vld1.32 {q1}, [%2]\n vmov q2, q0\n sha256h.32 q0, q1, q2\n sha256h2.32 q1, q2, q0\n"
        "sha256su0.32 q2, q1\n sha256su1.32 q2, q0, q1\n sha1h.32 q3, q2\n sha1c.32 q2, q3, q0\n vst1.32 {q2}, [%0]"
        : : "r"(r), "r"(a), "r"(b) : "q0", "q1", "q2", "q3", "memory");
    vector("sha", r, 4);
    /* VMULL.P64 */
    __asm__ volatile("vld1.32 {d0}, [%1]\n vld1.32 {d1}, [%2]\n vmull.p64 q1, d0, d1\n vst1.32 {q1}, [%0]"
        : : "r"(r), "r"(a), "r"(b) : "q0", "q1", "memory");
    vector("pmull", r, 4);
vfp:;
    /* VFP: VDIV, VSQRT, VFMA.F64, VCVT to and from fixed point */
    u32 v[4];
    __asm__ volatile("vmov.f64 d0, #3.0\n vmov.f64 d1, #7.0\n vdiv.f64 d2, d1, d0\n vsqrt.f64 d3, d2\n vfma.f64 d3, d2, d1\n"
        "vmov.f32 s8, #-2.5\n vcvt.s32.f32 s8, s8, #3\n vmov s9, %1\n vcvt.f32.u32 s9, s9, #8\n vstmia %0, {d3, d4}"
        : : "r"(v), "r"(0x12345u) : "d0", "d1", "d2", "d3", "d4", "memory");
    vector("vfp", v, 4);
}

/* --- the TLS registers, unaligned loads, the divides, generated code --- */
static u32 tls_check(void)
{
    u32 ro, rw;
    check(S(NR_set_tls, 0x12345678, 0, 0), "set_tls");
    __asm__ volatile("mcr p15, 0, %2, c13, c0, 2\n mrc p15, 0, %0, c13, c0, 3\n mrc p15, 0, %1, c13, c0, 2" : "=r"(ro), "=r"(rw) : "r"(0xCAFEF00Du));
    return ro == 0x12345678 && rw == 0xCAFEF00D;
}

static u32 unaligned(void)
{
    static const unsigned char bytes[16] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    u32 word, half;
    __asm__ volatile("ldr %0, [%2, #1]\n ldrh %1, [%2, #3]" : "=r"(word), "=r"(half) : "r"(bytes));
    return word == 0x05040302 && half == 0x0504;
}

static u32 divides(u32 x, u32 y)
{
    s32 q;
    u32 u;
    __asm__ volatile("sdiv %0, %2, %3\n udiv %1, %2, %3" : "=r"(q), "=r"(u) : "r"(x), "r"(y));
    return (u32)q ^ u << 1;
}

static u32 generated(void)
{
    /* an A32 function in a fresh page: mov r0, #0x2A; orr r0, r0, #0x100; bx lr */
    u32 *page = (u32 *)check(sc(NR_mmap2, 0, 4096, 3 /* RW */, 0x22 /* PRIVATE ANONYMOUS */, (u32)-1, 0), "mmap2");
    page[0] = 0xE3A0002A;
    page[1] = 0xE3800C01;
    page[2] = 0xE12FFF1E;
    check(S(NR_cacheflush, page, page + 3, 0), "cacheflush");
    check(S(NR_mprotect, page, 4096, 5 /* RX */), "mprotect");
    u32 (*fn)(void) = (u32 (*)(void))page;
    return fn();
}

static void cpuinfo_features(void)
{
    static char text[4096];
    s32 fd = check(sc(NR_openat, (u32)-100, (u32)"/proc/cpuinfo", 0, 0, 0, 0), "open cpuinfo");
    s32 n = 0, r;
    while(n < (s32)sizeof(text) - 1 && (r = S(NR_read, fd, text + n, sizeof(text) - 1 - n)) > 0) n += r;
    S(NR_close, fd, 0, 0);
    text[n] = 0;
    for(char *p = text; *p; p++)
    {
        if(p[0] == 'F' && p[1] == 'e' && p[2] == 'a' && p[3] == 't')
        {
            char *e = p;
            while(*e && *e != '\n') e++;
            *e = 0;
            while(*p && *p != ':') p++;
            out(" cpuinfo=\""); out(p + 2); out("\"");
            return;
        }
    }
    out(" cpuinfo=none");
}

void entry(u32 *stack)
{
    initial_stack = stack;
    struct { char sysname[65], nodename[65], release[65], version[65], machine[65], domain[65]; } names;
    check(S(NR_uname, &names, 0, 0), "uname");
    out("A32_PROBE isa=");
#ifdef __thumb__
    out("t32");
#else
    out("a32");
#endif
    out(" machine="); out(names.machine);
    out(" hwcap="); hex(auxv(16)); out(" hwcap2="); hex(auxv(26));
    out(" platform="); out(auxv(15) ? (const char *)auxv(15) : "none");
    out(" vdso="); out(auxv(33) ? "yes" : "no");
    cpuinfo_features();
    u32 ts[4] = { 0 };
    check(sc(NR_clock_gettime64, 1 /* CLOCK_MONOTONIC */, (u32)ts, 0, 0, 0, 0), "clock_gettime64");
    out(" clock="); out(ts[0] || ts[2] ? "ok" : "zero");
    out(" tls="); number(tls_check());
    out(" unaligned="); number(unaligned());
    out(" divides="); hex(divides(0xFFFFFF85, 7));
    out(" generated="); hex(generated());

    handle(SIGUSR1, usr1);
    u32 restored = signal_vfp();
    out(" signal="); number(usr1_seen); out(" vfp_restored="); number(restored);
    handle(SIGILL, ill);
    u32 here;
    __asm__ volatile("adr %0, 1f\n 1: udf #7" : "=r"(here));
    out(" sigill="); number(ill_seen); out(" ill_code="); number(ill_code); out(" ill_at_udf="); number(ill_address == here);

    for(u32 i = 0; i < THREADS; i++)
    {
        child_tids[i] = -1;
        check(spawn(worker, i, stacks[i] + 2048, &child_tids[i]), "clone");
    }
    vfp_rounds(0);
    for(u32 i = 0; i < THREADS; i++) join(&child_tids[i]);
    out(" counter="); number(counter); out(" vfp_bad="); number(vfp_bad);
    known_answers();
    out("\n");
    S(NR_exit_group, 0, 0, 0);
}

__asm__(".text\n.arm\n.global _start\n.type _start, %function\n_start:\nmov r0, sp\nbl entry\nmov r7, #248\nmov r0, #1\nsvc #0\n" MODE);
                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/a64/linux_sector_size.mjs                                                          0000755 0000000 0000000 00000015356 00000000000 015720  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Linux on virtio-blk disks of 4096-byte logical sectors (docs/disk-image-formats-plan.md,
// the appendix's "4K 逻辑扇区"): the pinned Alpine 3.24 aarch64 kernel and
// initramfs (tests/lib/alpine_image.mjs; ALPINE_CACHE=<dir> where another
// worktree keeps the ISO) on the virt machine, with an init of the test's
// (rdinit) that loads virtio_mmio and virtio_blk. Three disks: a RAW one
// with logical_sector_size 4096, a VHDX image with 4096-byte sectors
// (tests/image/tiny_vhdx.mjs) and a RAW one of 512-byte sectors. The guest
// must see each disk's logical block size (blk_size) and size, read what
// the host put there, write 2 MiB that it reads back after dropping its
// caches and that the host finds in the image, and report no I/O errors.

import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { prepare, unzboot, ROOT } from "../lib/alpine_image.mjs";
import { build_vhdx } from "../image/tiny_vhdx.mjs";

process.on("unhandledRejection", exn => { throw exn; });

const SHOW_LOGS = +process.env.SHOW_LOGS;
const TIMEOUT = Number(process.env.A64_LINUX_TIMEOUT || 300000);
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const prepared = await prepare("aarch64-virt", ["boot/vmlinuz-virt", "boot/initramfs-virt"]);
const directory = prepared.directory + "sector-size/";
fs.mkdirSync(directory + "root", { recursive: true });
const disk_commands = "for d in /sys/block/vd*; do n=${d##*/}; s=$($B cat $d/serial); " +
    "$B echo \"S4K_DISK $s $($B cat $d/queue/logical_block_size) $($B cat $d/queue/physical_block_size) $($B cat $d/size) " +
    "$($B dd if=/dev/$n bs=4096 count=1024 2>/dev/null | $B md5sum | $B cut -c1-32)\"; " +
    "$B dd if=/tmp/x of=/dev/$n bs=4096 seek=1000 conv=fsync 2>/dev/null || $B echo \"S4K_WRITE_FAILED $s\"; done; " +
    "$B echo 3 > /proc/sys/vm/drop_caches; " +
    "for d in /sys/block/vd*; do n=${d##*/}; $B echo \"S4K_BACK $($B cat $d/serial) " +
    "$($B dd if=/dev/$n bs=4096 skip=1000 count=512 2>/dev/null | $B md5sum | $B cut -c1-32)\"; done";
fs.writeFileSync(directory + "root/s4k-init", [
    "#!/bin/busybox sh",
    "B=/bin/busybox",
    "PATH=/usr/sbin:/usr/bin:/sbin:/bin; export PATH",
    "$B mount -t proc proc /proc; $B mount -t sysfs sys /sys; $B mount -t devtmpfs dev /dev",
    "$B mkdir -p /tmp; $B mount -t tmpfs tmp /tmp",
    "modprobe virtio_mmio; modprobe virtio_blk",
    "for i in 1 2 3 4 5 6 7 8 9 10; do [ -e /sys/block/vdc ] && break; $B sleep 1; done",
    "$B dd if=/dev/urandom of=/tmp/x bs=4096 count=512 2>/dev/null",
    "$B echo \"S4K_DATA $($B md5sum /tmp/x | $B cut -c1-32)\"",
    disk_commands,
    "$B dmesg | $B grep -i -E 'I/O error|virtio_blk' | $B sed 's/^/S4K_DMESG /'",
    "$B echo S4K_DONE",
    "$B poweroff -f",
    ""].join("\n"), { mode: 0o755 });
const tar = spawnSync("bsdtar", ["--format", "newc", "--uid", "0", "--gid", "0", "--no-xattrs", "--no-mac-metadata",
    "-cf", directory + "s4k.cpio", "-C", directory + "root", "s4k-init"], { encoding: "utf8" });
assert.equal(tar.status, 0, tar.stderr);
const initrd = Buffer.concat([fs.readFileSync(prepared.initrd), fs.readFileSync(directory + "s4k.cpio")]);
const kernel = unzboot(fs.readFileSync(prepared.kernel));
const array_buffer = b => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);

const md5 = bytes => create_hash("md5").update(bytes).digest("hex");
const RAW_SIZE = 16 << 20, VHDX_SIZE = 24 << 20;
const raw = new Uint8Array(RAW_SIZE).map((_, i) => i * 7 + (i >> 12) & 0xFF);
const raw512 = new Uint8Array(RAW_SIZE).map((_, i) => i * 5 + (i >> 9) & 0xFF);
const vhdx_data = new Uint8Array(4 << 20).map((_, i) => i * 13 + (i >> 9) & 0xFF);
const vhdx = build_vhdx({ size: VHDX_SIZE, logical_sector_size: 4096, data: [[0, vhdx_data]] });
// (before the guest writes into the RAW disks' buffers)
const expected = {
    raw4k: [4096, RAW_SIZE, md5(raw.subarray(0, 4 << 20))],
    vhdx4k: [4096, VHDX_SIZE, md5(vhdx_data)],
    raw512: [512, RAW_SIZE, md5(raw512.subarray(0, 4 << 20))],
};

const emulator = new V86({
    cpu_type: "arm64", graphics_adapter: "none", memory_size: 512 << 20, log_level: 0, autostart: true,
    wasm_path: process.env.A64_WASM || ROOT + "build/v86-arm64.wasm",
    kernel: { buffer: array_buffer(kernel) }, initrd: { buffer: array_buffer(initrd) },
    cmdline: "console=ttyAMA0 earlycon nokaslr panic=-1 rdinit=/s4k-init",
    virtio_disks: [
        { buffer: raw.buffer, logical_sector_size: 4096, id: "raw4k" },
        { buffer: vhdx.image.buffer, format: "vhdx", id: "vhdx4k" },
        { buffer: raw512.buffer, id: "raw512" },
    ],
});
let serial = "";
emulator.add_listener("serial0-output-byte", byte =>
{
    const c = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(c);
    serial += c;
});
const started = Date.now();
while(!/S4K_DONE/.test(serial))
{
    if(Date.now() - started > TIMEOUT)
    {
        console.log(serial.slice(-4000));
        throw new Error("timed out waiting for S4K_DONE");
    }
    await new Promise(resolve => setTimeout(resolve, 100));
}
const text = serial.replace(/\r/g, "");
const data_sum = text.match(/^S4K_DATA ([0-9a-f]{32})/m)?.[1];
assert.ok(data_sum, "the data written");
const disks = Object.fromEntries([...text.matchAll(/^S4K_DISK (\S+) (\d+) (\d+) (\d+) ([0-9a-f]{32})/gm)].map(m => [m[1], m.slice(2)]));
const back = Object.fromEntries([...text.matchAll(/^S4K_BACK (\S+) ([0-9a-f]{32})/gm)].map(m => [m[1], m[2]]));
for(const [id, [block, size, sum]] of Object.entries(expected))
{
    assert.ok(disks[id], id + ": seen by the guest: " + text.slice(-3000));
    assert.deepEqual(disks[id], [String(block), String(block), String(size / 512), sum], id + ": block sizes, size, the first 4 MiB");
    assert.equal(back[id], data_sum, id + ": the 2 MiB written, read back");
}
assert.ok(!/S4K_WRITE_FAILED|S4K_DMESG.*I\/O error/.test(text), "no I/O errors: " + text.slice(-3000));
assert.equal(md5(raw.subarray(1000 * 4096, 1512 * 4096)), data_sum, "raw4k: the image holds the guest's data");
assert.equal(md5(raw512.subarray(1000 * 4096, 1512 * 4096)), data_sum, "raw512: likewise");
const vhdx_disk = emulator.disk_buffer("virtio_disk1");
const in_vhdx = await new Promise((resolve, reject) => vhdx_disk.get(1000 * 4096, 2 << 20, (data, error) => error ? reject(error) : resolve(data)));
assert.equal(md5(in_vhdx), data_sum, "vhdx4k: the disk image holds it (in its overlay)");
await emulator.destroy();
console.log("ok - Linux (Alpine 3.24 aarch64) on virtio-blk: 4096-byte logical blocks on the RAW and the VHDX disk, 512 on the other; " +
    "reads, 2 MiB written and read back, in the images; " + Math.round((Date.now() - started) / 1000) + " s");
console.log("linux_sector_size: passed");
                                                                                                                                                                                                                                                                                  source/v64/tests/a64/litmus.c                                                                       0000644 0000000 0000000 00000030321 00000000000 013100  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Litmus tests of the A64 cores (docs/arm64-virt-android16-plan.md P3.9),
// bare metal on 2 or 4 cores (tests/a64/litmus.mjs): every core turns the
// MMU on (RAM normal write-back, devices nGnRnE), then for ROUNDS rounds
// each of
//
// - MP with DMB, and with STLR/LDAR: flag=1 && data=0 is forbidden
// - SB with DMB: r0=0 && r1=0 is forbidden
// - LB with DMB: r0=1 && r1=1 is forbidden
// - IRIW with DMB (4 cores): the readers seeing the writes in opposite orders is forbidden
// - 2+2W with DMB: x=1 && y=1 at the end is forbidden
//
// and the checks that have no allowed failure: a LDXR/STXR counter on every
// core, a store-exclusive failing after another core's plain store of the
// same value to the granule, a TLBI VAE1IS shootdown that other cores
// observe without an IPI, a ring of SGIs between cores waiting in WFI, and
// a ring of WFE/SEV. Spin waits use YIELD (the cooperative cores' turns
// end there). Each line of output is "name key=count ...", "forbidden=N"
// last on the lines of the litmus tests.

#include <a64.h>
#include <stdio.h>

#ifndef ROUNDS
#define ROUNDS 1000
#endif
#define RING_ROUNDS 100
#define MAX_CORES 8

static unsigned cores;

// ---- synchronization

static volatile unsigned barrier_count, barrier_sense;

static inline void spin(void) { __asm__ volatile("yield" ::: "memory"); }

static void barrier(void)
{
    unsigned sense = !__atomic_load_n(&barrier_sense, __ATOMIC_ACQUIRE);
    if(__atomic_add_fetch(&barrier_count, 1, __ATOMIC_ACQ_REL) == cores)
    {
        barrier_count = 0;
        __atomic_store_n(&barrier_sense, sense, __ATOMIC_RELEASE);
    }
    else
    {
        while(__atomic_load_n(&barrier_sense, __ATOMIC_ACQUIRE) != sense) spin();
    }
}

#define DMB() __asm__ volatile("dmb ish" ::: "memory")

// ---- the MMU: 39-bit VAs, 4 KiB granule, level 1 blocks but for the test page at TEST_VA

#define TEST_VA 0x80000000UL
static uint64_t l1[512] __attribute__((aligned(4096)));
static uint64_t l2[512] __attribute__((aligned(4096)));
static uint64_t l3[512] __attribute__((aligned(4096)));
static volatile uint64_t pages[2][512] __attribute__((aligned(4096)));

#define ATTR_NORMAL (0 << 2)
#define ATTR_DEVICE (1 << 2)
#define SH_INNER (3 << 8)
#define AF (1 << 10)

static void build_tables(void)
{
    l1[0] = 0x00000000UL | 1 | ATTR_DEVICE | AF;          // devices (GIC, PL011)
    l1[1] = 0x40000000UL | 1 | ATTR_NORMAL | SH_INNER | AF; // RAM
    l1[2] = (uint64_t)l2 | 3;
    l2[0] = (uint64_t)l3 | 3;
    pages[0][0] = 0xA0A0;
    pages[1][0] = 0xB1B1;
    l3[0] = (uint64_t)pages[0] | 3 | ATTR_NORMAL | SH_INNER | AF;
    __asm__ volatile("dsb ish" ::: "memory");
}

static void mmu_on(void)
{
    a64_write(mair_el1, 0x00FF);  // attr0 normal write-back, attr1 device nGnRnE
    a64_write(tcr_el1, 25 | 1 << 8 | 1 << 10 | 3 << 12 | 1 << 23 | 2UL << 32);
    a64_write(ttbr0_el1, (uint64_t)l1);
    __asm__ volatile("dsb ish\n tlbi vmalle1\n dsb ish\n isb" ::: "memory");
    a64_write(sctlr_el1, a64_read(sctlr_el1) | 1 | 1 << 2 | 1 << 12);
    __asm__ volatile("isb" ::: "memory");
}

// ---- the litmus tests

static volatile unsigned x, y, data, flag, r[4];
static unsigned histogram[5][16];
static unsigned forbidden[5];
enum { MP_DMB, MP_ACQ_REL, SB, LB, IRIW };
static unsigned final_x1_y1;

static void litmus_round(unsigned core)
{
    // MP with DMB: core 0 writes data then flag, core 1 reads flag then data
    if(core == 0) { data = 1; DMB(); flag = 1; }
    else if(core == 1) { unsigned f = flag; DMB(); unsigned d = data; r[0] = f; r[1] = d; }
    barrier();
    if(core == 0)
    {
        histogram[MP_DMB][r[0] << 1 | r[1]]++;
        forbidden[MP_DMB] += r[0] == 1 && r[1] == 0;
        data = flag = 0;
    }
    barrier();
    // MP with STLR/LDAR
    if(core == 1)
    {
        data = 1;
        __atomic_store_n(&flag, 1, __ATOMIC_RELEASE);
    }
    else if(core == 0)
    {
        unsigned f = __atomic_load_n(&flag, __ATOMIC_ACQUIRE);
        unsigned d = data;
        r[0] = f;
        r[1] = d;
    }
    barrier();
    if(core == 0)
    {
        histogram[MP_ACQ_REL][r[0] << 1 | r[1]]++;
        forbidden[MP_ACQ_REL] += r[0] == 1 && r[1] == 0;
        data = flag = 0;
    }
    barrier();
    // SB: each writes its variable and reads the other's
    if(core == 0) { x = 1; DMB(); r[0] = y; }
    else if(core == 1) { y = 1; DMB(); r[1] = x; }
    barrier();
    if(core == 0)
    {
        histogram[SB][r[0] << 1 | r[1]]++;
        forbidden[SB] += r[0] == 0 && r[1] == 0;
        x = y = 0;
    }
    barrier();
    // LB: each reads the other's variable, then writes its own
    if(core == 0) { r[0] = x; DMB(); y = 1; }
    else if(core == 1) { r[1] = y; DMB(); x = 1; }
    barrier();
    if(core == 0)
    {
        histogram[LB][r[0] << 1 | r[1]]++;
        forbidden[LB] += r[0] == 1 && r[1] == 1;
        x = y = 0;
    }
    barrier();
    // 2+2W: x=1, y=2 against y=1, x=2
    if(core == 0) { x = 1; DMB(); y = 2; }
    else if(core == 1) { y = 1; DMB(); x = 2; }
    barrier();
    if(core == 0)
    {
        final_x1_y1 += x == 1 && y == 1;
        x = y = 0;
    }
    barrier();
    // IRIW: two writers, two readers in opposite orders
    if(cores >= 4)
    {
        if(core == 0) x = 1;
        else if(core == 1) y = 1;
        else if(core == 2) { r[0] = x; DMB(); r[1] = y; }
        else if(core == 3) { r[2] = y; DMB(); r[3] = x; }
        barrier();
        if(core == 0)
        {
            histogram[IRIW][r[0] << 3 | r[1] << 2 | r[2] << 1 | r[3]]++;
            forbidden[IRIW] += r[0] == 1 && r[1] == 0 && r[2] == 1 && r[3] == 0;
            x = y = 0;
        }
        barrier();
    }
}

// ---- exclusives

static volatile uint64_t counter;
static volatile unsigned aba_word __attribute__((aligned(64))), aba_phase;
static unsigned aba_failures;

static void exclusive_counter(void)
{
    for(int i = 0; i < ROUNDS; i++)
    {
        uint64_t value;
        unsigned failed;
        do
        {
            __asm__ volatile("ldxr %0, [%2]\n add %0, %0, #1\n stxr %w1, %0, [%2]" : "=&r"(value), "=&r"(failed) : "r"(&counter) : "memory");
        } while(failed);
    }
}

// core 0 holds a reservation while core 1 stores the same value: the store-exclusive must fail
static void exclusive_cleared(unsigned core)
{
    for(unsigned round = 1; round <= ROUNDS / 10; round++)
    {
        if(core == 0)
        {
            unsigned value, failed;
            __asm__ volatile("ldxr %w0, [%1]" : "=&r"(value) : "r"(&aba_word) : "memory");
            __atomic_store_n(&aba_phase, round * 2 - 1, __ATOMIC_RELEASE);
            while(__atomic_load_n(&aba_phase, __ATOMIC_ACQUIRE) != round * 2) spin();
            __asm__ volatile("stxr %w0, %w2, [%1]" : "=&r"(failed) : "r"(&aba_word), "r"(value + 1) : "memory");
            aba_failures += failed != 0;
        }
        else if(core == 1)
        {
            while(__atomic_load_n(&aba_phase, __ATOMIC_ACQUIRE) != round * 2 - 1) spin();
            aba_word = aba_word;
            __atomic_store_n(&aba_phase, round * 2, __ATOMIC_RELEASE);
        }
        barrier();
    }
}

// ---- TLBI VAE1IS: core 0 remaps TEST_VA, the others see the new page with no IPI

static volatile unsigned remap_round;
static unsigned stale[MAX_CORES];

static void shootdown(unsigned core)
{
    for(unsigned round = 1; round <= ROUNDS / 10; round++)
    {
        unsigned page = round & 1;
        // (every core has the old translation cached: it reads the page first)
        (void)*(volatile uint64_t *)TEST_VA;
        barrier();
        if(core == 0)
        {
            l3[0] = (uint64_t)pages[page] | 3 | ATTR_NORMAL | SH_INNER | AF;
            __asm__ volatile("dsb ishst\n tlbi vae1is, %0\n dsb ish\n isb" :: "r"(TEST_VA >> 12) : "memory");
            __atomic_store_n(&remap_round, round, __ATOMIC_RELEASE);
        }
        else
        {
            while(__atomic_load_n(&remap_round, __ATOMIC_ACQUIRE) != round) spin();
        }
        __asm__ volatile("isb" ::: "memory");
        stale[core] += *(volatile uint64_t *)TEST_VA != pages[page][0];
        barrier();
    }
}

// ---- the GIC: SGI 0 around a ring of cores waiting in WFI (IRQs masked: WFI wakes all the same)

#define GICD 0x08000000UL
#define GICR(core) (0x080A0000UL + (core) * 0x20000UL)
#define MMIO32(a) (*(volatile uint32_t *)(a))
static volatile unsigned sgi_seen[MAX_CORES];

static void gic_setup(unsigned core)
{
    if(core == 0) MMIO32(GICD) = 1 << 4 | 1 << 1 | 1;
    MMIO32(GICR(core) + 0x14) &= ~2u;                 // GICR_WAKER.ProcessorSleep
    while(MMIO32(GICR(core) + 0x14) & 4) spin();      // ChildrenAsleep
    MMIO32(GICR(core) + 0x10000 + 0x80) = ~0u;        // GICR_IGROUPR0: group 1
    MMIO32(GICR(core) + 0x10000 + 0x400) = 0x80;      // SGI 0's priority
    MMIO32(GICR(core) + 0x10000 + 0x100) = 1;         // GICR_ISENABLER0: SGI 0
    __asm__ volatile("msr S3_0_C12_C12_5, %0" :: "r"(7UL));   // ICC_SRE_EL1
    __asm__ volatile("msr S3_0_C4_C6_0, %0" :: "r"(0xFFUL));  // ICC_PMR_EL1
    __asm__ volatile("msr S3_0_C12_C12_7, %0\n isb" :: "r"(1UL)); // ICC_IGRPEN1_EL1
}

static void sgi_to(unsigned core)
{
    __asm__ volatile("dsb ish\n msr S3_0_C12_C11_5, %0\n isb" :: "r"((uint64_t)1 << core) : "memory"); // ICC_SGI1R_EL1, INTID 0
}

static void wait_sgi(void)
{
    for(;;)
    {
        uint64_t intid;
        __asm__ volatile("wfi\n mrs %0, S3_0_C12_C12_0" : "=r"(intid) :: "memory"); // ICC_IAR1_EL1
        if(intid == 1023) continue;
        __asm__ volatile("msr S3_0_C12_C12_1, %0\n isb" :: "r"(intid)); // ICC_EOIR1_EL1
        if(intid == 0) return;
    }
}

static void sgi_ring(unsigned core)
{
    for(unsigned round = 0; round < RING_ROUNDS; round++)
    {
        if(core == 0)
        {
            sgi_to(1);
            wait_sgi();
            sgi_seen[0]++;
        }
        else
        {
            wait_sgi();
            sgi_seen[core]++;
            sgi_to((core + 1) % cores);
        }
    }
    barrier();
}

// ---- WFE and SEV: a token around the cores

static volatile unsigned token, wfe_passes[MAX_CORES];

static void wfe_ring(unsigned core)
{
    for(unsigned round = 0; round < RING_ROUNDS; round++)
    {
        while(__atomic_load_n(&token, __ATOMIC_ACQUIRE) != round * cores + core) __asm__ volatile("wfe" ::: "memory");
        wfe_passes[core]++;
        __atomic_store_n(&token, round * cores + core + 1, __ATOMIC_RELEASE);
        __asm__ volatile("dsb ish\n sev" ::: "memory");
    }
    barrier();
}

// ---- running

static volatile unsigned started;

static void run(unsigned core)
{
    mmu_on();
    gic_setup(core);
    barrier();
    for(int i = 0; i < ROUNDS; i++) litmus_round(core);
    exclusive_counter();
    barrier();
    exclusive_cleared(core);
    shootdown(core);
    sgi_ring(core);
    wfe_ring(core);
}

static void secondary(unsigned core)
{
    __atomic_add_fetch(&started, 1, __ATOMIC_ACQ_REL);
    while(!__atomic_load_n(&cores, __ATOMIC_ACQUIRE)) spin();
    run(core);
    for(;;) __asm__ volatile("wfi");
}

int main(int argc, char **argv)
{
    build_tables();
    a64_core_main = secondary;
    unsigned n = 1;
    while(n < MAX_CORES && a64_cpu_on(n) == 0) n++;
    while(__atomic_load_n(&started, __ATOMIC_ACQUIRE) != n - 1) spin();
    __atomic_store_n(&cores, n, __ATOMIC_RELEASE);
    run(0);

    printf("cores=%u rounds=%u\n", cores, ROUNDS);
    static const char *names[] = { "MP+dmb", "MP+stlr+ldar", "SB+dmb", "LB+dmb", "IRIW+dmb" };
    for(int t = 0; t < 5; t++)
    {
        if(t == IRIW && cores < 4) continue;
        printf("%s", names[t]);
        for(int k = 0; k < (t == IRIW ? 16 : 4); k++) if(histogram[t][k]) printf(" %x=%u", k, histogram[t][k]);
        printf(" forbidden=%u\n", forbidden[t]);
    }
    printf("2+2W+dmb x1y1=%u forbidden=%u\n", final_x1_y1, final_x1_y1);
    printf("exclusive-counter count=%lu expected=%u\n", (unsigned long)counter, cores * ROUNDS);
    printf("exclusive-cleared failures=%u expected=%u\n", aba_failures, ROUNDS / 10);
    unsigned stale_total = 0;
    for(unsigned c = 0; c < cores; c++) stale_total += stale[c];
    printf("tlbi-vae1is-shootdown stale=%u rounds=%u\n", stale_total, ROUNDS / 10);
    unsigned sgi_total = 0, wfe_total = 0;
    for(unsigned c = 0; c < cores; c++) { sgi_total += sgi_seen[c]; wfe_total += wfe_passes[c]; }
    printf("wfi-sgi-ring received=%u expected=%u\n", sgi_total, cores * RING_ROUNDS);
    printf("wfe-sev-ring passes=%u expected=%u\n", wfe_total, cores * RING_ROUNDS);
    return 0;
}
                                                                                                                                                                                                                                                                                                               source/v64/tests/a64/litmus.mjs                                                                     0000644 0000000 0000000 00000007007 00000000000 013454  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 litmus tests (tests/a64/litmus.c; docs/arm64-virt-android16-plan.md
// P3.9) on v86's cooperative cores, and with --qemu on the fixed reference
// too: every forbidden outcome must count 0 (the cooperative cores run one
// at a time, so their accesses are sequentially consistent and the weak
// outcomes do not occur at all; only the forbidden ones are judged), the
// LDXR/STXR counter must be exact, every store-exclusive after another
// core's store must fail, no core may read through a stale translation
// after TLBI VAE1IS, and the SGI and WFE/SEV rings must go round. (QEMU's
// store-exclusive compares values, so on the reference a store of the same
// value does not make it fail: that line is only reported there, as
// tests/a64/linux_probe.c's excl_aba is.)
//
// LITMUS_MODES (P8.4): comma-separated from cooperative, cooperative-jit
// (the A64 page tier), parallel and parallel-jit (cores 1 and up in vCPU
// workers, v86-arm64-parallel.wasm: their accesses really interleave, so
// weak outcomes may occur; the store-exclusive compares values there, as on
// the reference, so exclusive-cleared is only reported); default cooperative.
//
//   node tests/a64/litmus.mjs [--qemu] [--cores 2,4] [--rounds N]
import assert from "node:assert/strict";
import { build, reference, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const core_counts = option("--cores", "2,4").split(",").map(Number);
const rounds = +option("--rounds", 1000);
const directory = build("litmus", [new URL("litmus.c", import.meta.url).pathname], { cflags: [`-DROUNDS=${rounds}`] });
const modes = (process.env.LITMUS_MODES || "cooperative").split(",");
const MODE_OPTIONS = {
    "cooperative": {},
    "cooperative-jit": { jit_switches: { a64_page: 1 }, ir_sync_publication: true },
    "parallel": { parallel: true, parallel_wasm_path: root + "build/v86-arm64-parallel.wasm" },
    "parallel-jit": { parallel: true, parallel_wasm_path: root + "build/v86-arm64-parallel.wasm", jit_switches: { a64_page: 1 } },
};
for(const mode of modes) assert.ok(MODE_OPTIONS[mode], "LITMUS_MODES: " + mode);

function check(label, result, reference = false)
{
    assert.equal(result.status, "ok", `${label}: ${result.status}\n${result.text}`);
    const lines = result.text.trim().split("\n");
    const field = (line, key) => +line.match(new RegExp(`\\b${key}=(\\d+)`))[1];
    for(const line of lines)
    {
        if(/forbidden=/.test(line)) assert.equal(field(line, "forbidden"), 0, `${label}: ${line}`);
        if(/expected=/.test(line) && !(reference && /^exclusive-cleared/.test(line)))
        {
            const key = line.match(/ (\w+)=\d+ expected=/)[1];
            assert.equal(field(line, key), field(line, "expected"), `${label}: ${line}`);
        }
        if(/stale=/.test(line)) assert.equal(field(line, "stale"), 0, `${label}: ${line}`);
    }
    console.log(`${label}:\n  ${lines.join("\n  ")}`);
}

for(const cores of core_counts)
{
    for(const mode of modes)
    {
        const start = performance.now();
        check(`v86 ${mode}, ${cores} cores`, await actual(directory, { cores, timeout: 600000, options: MODE_OPTIONS[mode] }),
            mode.startsWith("parallel"));
        console.log(`  (${((performance.now() - start) / 1000).toFixed(1)} s)`);
    }
    if(args.includes("--qemu")) check(`QEMU, ${cores} cores`, await reference(directory, { cores, timeout: 120000 }), true);
}
console.log("litmus: passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/a64/lockstep.mjs                                                                   0000644 0000000 0000000 00000017034 00000000000 013764  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// A bare-metal guest in lockstep on QEMU and v86 (docs/arm64-virt-android16-plan.md
// P2, a debugging aid): QEMU runs it with its execlog plugin logging every
// instruction and the registers it changed (X0-X30, SP, CPSR's NZCV, V0-V31,
// FPSR); v86 then single-steps it (a64_step) and logs the same. The first
// instruction where the PC or a changed register differs is printed with the
// instructions before it. QEMU clears NZCV when it takes an exception
// (pstate_write); AArch64.TakeException leaves it, as v86 does: at an
// exception entry v86 adopts QEMU's flags and the difference is not reported.
//
//   node tests/a64/lockstep.mjs <directory of guest.bin> [--max N] [--context N] [--memory MiB] [--granules-all]
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import readline from "node:readline";
import { reference, qemu_binary, root, RESULT, DONE } from "./guest_runner.mjs";
import { STATE_OFFSETS } from "../../src/arm/state_layout.js";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const directory = path.resolve(args[0]) + "/";
const MAX = +option("--max", 5000000);
const CONTEXT = +option("--context", 8);

// ---- QEMU's trace
const plugin = path.dirname(qemu_binary()) + "/../../qemu-9.2.0/build/contrib/plugins/libexeclog." +
    (process.platform === "darwin" ? "dylib" : "so");
assert.ok(fs.existsSync(plugin), "no execlog plugin at " + plugin + " (tools/a64_qemu/build.sh)");
const log = directory + "lockstep-qemu.log";
fs.rmSync(log, { force: true });
const expected = await reference(directory, {
    memory: +option("--memory", 256),
    timeout: 600000,
    extra: ["-plugin", plugin + ",reg=x*,reg=sp,reg=cpsr,reg=v*,reg=fpsr", "-d", "plugin", "-D", log],
});
console.log(`QEMU: ${expected.status}`);

const LINE = /^\d+, 0x([0-9a-f]+), 0x([0-9a-f]+), "([^"]*)"(.*)$/;
const qemu = [];
// (streamed: a trace can be gigabytes)
for await (const line of readline.createInterface({ input: fs.createReadStream(log, { encoding: "latin1" }), crlfDelay: Infinity }))
{
    const m = LINE.exec(line);
    if(!m) continue;
    const changes = new Map();
    for(const [, name, value] of m[4].matchAll(/, ([a-z0-9_]+) -> 0x([0-9a-f]+)/g))
    {
        if(!/^(x\d+|sp|cpsr|v\d+|fpsr)$/.test(name)) continue;
        changes.set(name, name === "cpsr" ? (BigInt("0x" + value) & 0xF0000000n).toString(16) : BigInt("0x" + value).toString(16));
    }
    qemu.push({ pc: BigInt("0x" + m[1]), word: m[2], text: m[3], changes });
    if(qemu.length >= MAX) break;
}
console.log(`QEMU: ${qemu.length} instructions traced`);

// ---- v86, one instruction at a time
const { V86 } = await import("../../src/main.js");
const emulator = new V86({
    cpu_type: "arm64", graphics_adapter: "none", memory_size: +option("--memory", 256) << 20, autostart: false, log_level: 0,
    wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
    kernel: { url: directory + "guest.bin" },
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu;
if(args.includes("--granules-all")) cpu.wm.exports["a64_set_granules"](7);
const memory = () => new DataView(cpu.wasm_memory.buffer);
const base = cpu.state_base;
function registers()
{
    const view = memory();
    const r = new Map();
    for(let i = 0; i < 31; i++) r.set("x" + i, view.getBigUint64(base + STATE_OFFSETS.x + 8 * i, true).toString(16));
    r.set("sp", view.getBigUint64(base + STATE_OFFSETS.x + 8 * 31, true).toString(16));
    r.set("cpsr", ((view.getUint32(base + STATE_OFFSETS.nzcv, true) & 0xF0000000) >>> 0).toString(16));
    for(let i = 0; i < 32; i++)
    {
        const at = base + STATE_OFFSETS.v + 16 * i;
        r.set("v" + i, (view.getBigUint64(at, true) | view.getBigUint64(at + 8, true) << 64n).toString(16));
    }
    r.set("fpsr", view.getUint32(base + STATE_OFFSETS.fpsr, true).toString(16));
    return r;
}
const pc = () => memory().getBigUint64(base + STATE_OFFSETS.pc, true);
const done = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset + RESULT - 0x40000000, 4).getUint32(0, true) === DONE;
const step = cpu.wm.exports["a64_step"];

let before = registers();
const history = [];
let diverged = false;
// (QEMU's boot stub at the start of RAM runs first: skip to v86's entry)
const first = qemu.findIndex(q => q.pc === pc());
assert.ok(first >= 0, "QEMU never reached v86's entry " + pc().toString(16));
// (and leaves X0-X3 as the boot protocol says, X0 the DTB, which v86 does not have yet: take QEMU's)
for(const q of qemu.slice(0, first))
{
    for(const [name, value] of q.changes)
    {
        const r = /^x(\d+)$/.exec(name);
        if(r) memory().setBigUint64(base + STATE_OFFSETS.x + 8 * +r[1], BigInt("0x" + value), true);
    }
}
before = registers();
for(let i = first; i < qemu.length; i++)
{
    const q = qemu[i];
    const at = pc();
    const record = { i, pc: at, q, changes: null };
    history.push(record);
    if(history.length > CONTEXT) history.shift();
    if(at !== q.pc)
    {
        console.log(`PC differs at instruction ${i}: QEMU ${q.pc.toString(16)} v86 ${at.toString(16)}`);
        diverged = true;
        break;
    }
    const previous = before;
    step();
    // (a fetch that aborts is a step of its own in v86; QEMU's log folds it into the instruction before)
    if(i + 1 < qemu.length && pc() !== qemu[i + 1].pc) step();
    const vbar = memory().getBigUint64(base + STATE_OFFSETS.vbar_el1, true);
    if(pc() >= vbar && pc() < vbar + 0x800n && q.changes.has("cpsr"))
    {
        memory().setUint32(base + STATE_OFFSETS.nzcv, Number(BigInt("0x" + q.changes.get("cpsr"))), true);
    }
    const after = registers();
    const changes = new Map();
    for(const [name, value] of after) if(before.get(name) !== value) changes.set(name, value);
    record.changes = changes;
    before = after;
    // (compare what either side says changed)
    const names = new Set([...changes.keys(), ...q.changes.keys()]);
    const wrong = [...names].filter(name => (q.changes.get(name) ?? null) !== (changes.get(name) ?? null) &&
        !(q.changes.has(name) && !changes.has(name) && q.changes.get(name) === after.get(name)));
    if(wrong.length)
    {
        console.log(`registers differ after instruction ${i}:`);
        for(const r of history)
        {
            const fmt = map => [...(map || new Map())].map(([k, v]) => `${k}=${v}`).join(" ");
            console.log(`  #${r.i} ${r.pc.toString(16)} ${r.q.word} ${r.q.text}\n      qemu ${fmt(r.q.changes)}\n      v86  ${fmt(r.changes)}`);
        }
        for(const name of wrong) console.log(`  ${name}: QEMU ${q.changes.get(name) ?? "(unchanged)"} v86 ${changes.get(name) ?? "(unchanged) " + after.get(name)}`);
        // (every register QEMU reported, as it stands before this instruction, against v86's before it)
        const state = new Map();
        for(const r of qemu.slice(0, i)) for(const [name, value] of r.changes) state.set(name, value);
        const mismatched = [...state].filter(([name, value]) => previous.get(name) !== value);
        console.log(`  before it: v2 ${previous.get("v2")} v3 ${previous.get("v3")} qemu-state v2 ${state.get("v2")} v3 ${state.get("v3")}`);
        console.log("  before it, registers that differ: " + (mismatched.map(([name, value]) => `${name} qemu ${value} v86 ${previous.get(name)}`).join(", ") || "none"));
        diverged = true;
        break;
    }
}
if(!diverged) console.log(`v86: the same ${qemu.length} instructions` + (done() ? ", guest done" : ""));
await emulator.destroy();
process.exit(diverged ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/a64/minimal.cil                                                                    0000644 0000000 0000000 00000004666 00000000000 013553  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; A minimal SELinux policy for the androidish kernel (docs/arm64-virt-android16-plan.md
; P9.2), compiled by tests/a64/cil2bin.c in tools/a64_kernel.mjs's VM: one user,
; role and type for every process and object; the classes the kernel knows and
; this policy does not are allowed (handleunknown), so that the probe runs in
; enforcing mode, while the process permissions declared here are enforced:
; fork, transition and sigchld allowed, setrlimit denied (the check that
; enforcing is real, tests/a64/selinux_load.c); the kernel requires
; transition and dyntransition to be declared.
(handleunknown allow)
(mls false)
(class process (fork transition sigchld setrlimit dyntransition))
(classorder (process))
; the kernel's initial SIDs, in its numbering (security/selinux/include/initial_sid_to_string.h)
(sid kernel) (sid security) (sid unlabeled) (sid fs) (sid file) (sid file_labels) (sid init) (sid any_socket)
(sid port) (sid netif) (sid netmsg) (sid node) (sid igmp_packet) (sid icmp_socket) (sid tcp_socket)
(sid sysctl_modprobe) (sid sysctl) (sid sysctl_fs) (sid sysctl_kernel) (sid sysctl_net) (sid sysctl_net_unix)
(sid sysctl_vm) (sid sysctl_dev) (sid kmod) (sid policy) (sid scmp_packet) (sid devnull)
(sidorder (kernel security unlabeled fs file file_labels init any_socket port netif netmsg node igmp_packet
    icmp_socket tcp_socket sysctl_modprobe sysctl sysctl_fs sysctl_kernel sysctl_net sysctl_net_unix sysctl_vm
    sysctl_dev kmod policy scmp_packet devnull))
(sensitivity s0)
(sensitivityorder (s0))
(category c0)
(categoryorder (c0))
(sensitivitycategory s0 (c0))
(user u)
(role r)
(type t)
(roletype r t)
(userrole u r)
(userlevel u (s0))
(userrange u ((s0) (s0)))
(allow t self (process (fork transition sigchld)))
(context ctx (u r t ((s0) (s0))))
(sidcontext kernel ctx) (sidcontext security ctx) (sidcontext unlabeled ctx) (sidcontext fs ctx)
(sidcontext file ctx) (sidcontext file_labels ctx) (sidcontext init ctx) (sidcontext any_socket ctx)
(sidcontext port ctx) (sidcontext netif ctx) (sidcontext netmsg ctx) (sidcontext node ctx)
(sidcontext igmp_packet ctx) (sidcontext icmp_socket ctx) (sidcontext tcp_socket ctx)
(sidcontext sysctl_modprobe ctx) (sidcontext sysctl ctx) (sidcontext sysctl_fs ctx) (sidcontext sysctl_kernel ctx)
(sidcontext sysctl_net ctx) (sidcontext sysctl_net_unix ctx) (sidcontext sysctl_vm ctx) (sidcontext sysctl_dev ctx)
(sidcontext kmod ctx) (sidcontext policy ctx) (sidcontext scmp_packet ctx) (sidcontext devnull ctx)
                                                                          source/v64/tests/a64/mmu.mjs                                                                        0000644 0000000 0000000 00000064211 00000000000 012735  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The stage 1 MMU against QEMU (docs/arm64-virt-android16-plan.md P3.3-P3.5;
// `--granules` all: P3.4's 16 and 64 KiB too, profile v1.1's).
// Each case programs TCR_EL1 (TnSZ, TGn, TBIn, IPS, A1, AS, EPDn), MAIR_EL1,
// SCTLR_EL1.A and both TTBRs with an ASID, builds random translation tables
// (pages and blocks, APTable/XNTable/PXNTable, AF clear, nG, output and
// table addresses beyond the 40-bit PA space or in a hole) next to an
// identity map of the guest, turns the MMU on and runs a list of probes:
// loads and stores (aligned and not, on Normal and Device memory), LDTR and
// STTR, the four AT S1E* with PAR_EL1, an instruction fetch at EL1 (BLR to
// a page of RETs) and at EL0 (ERET to a page of SVCs), and descriptor
// rewrites followed by each kind of TLBI. A probe records its value, or
// the exception's ESR and FAR; QEMU's records and v86's must be equal.
//
//   node tests/a64/mmu.mjs [--cases N] [--seed S] [--granules 4k|all]
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const CASES = +option("--cases", 300);
const SEED = +option("--seed", 1);
const ALL_GRANULES = option("--granules", "4k") === "all";
const BATCH = 50;
const MEMORY_MB = 256;

let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
function next64()
{
    state ^= state << 13n & (1n << 64n) - 1n;
    state ^= state >> 7n;
    state ^= state << 17n & (1n << 64n) - 1n;
    return state;
}
const rand = n => Number(next64() % BigInt(n));
const pick = list => list[rand(list.length)];
const chance = p => rand(1000) < p * 1000;
const hex = v => "0x" + BigInt.asUintN(64, BigInt(v)).toString(16);
const M64 = (1n << 64n) - 1n;

// ---- the physical layout (RAM from 0x4000_0000)
const IDENTITY = [0x40000000n, 0x46000000n];  // the guest, its data pages and the table pool: identity mapped
const DATA = 0x41000000n;                       // 16 data pages of 64 KiB, a pattern each
const RET_PAGE = DATA + 16n * 0x10000n;         // 64 KiB of RET
const SVC_PAGE = RET_PAGE + 0x10000n;           // 64 KiB of SVC #0
const BLOCK_2M = 0x41400000n;                   // 2 MiB-aligned (4 KiB granule blocks)
const BLOCK_32M = 0x42000000n;                  // 32 MiB-aligned (16 KiB granule blocks)
const POOL = 0x44000000n;                       // translation tables (each case starts it zeroed)
const POOL_SIZE = 0x01000000n;
// (no RAM or device, aligned for every block size; below 1 GiB QEMU has flash and devices v86 lacks)
const HOLE = 0x80000000n;

// ---- MAIR: index 0 is the identity map's Normal memory
const MAIR_ATTRS = [0xFFn, 0x00n, 0x04n, 0x08n, 0x0Cn, 0x44n, 0xBBn, 0x4Fn, 0xF4n];

/** One case's tables: a pool allocator and the descriptor writes */
class Tables
{
    constructor()
    {
        this.next = POOL;
        this.writes = new Map();
    }
    alloc(bytes)
    {
        const size = BigInt(Math.max(bytes, 64));
        this.next = (this.next + size - 1n) / size * size;
        const at = this.next;
        this.next += size;
        assert.ok(this.next <= POOL + POOL_SIZE, "table pool exhausted");
        return at;
    }
    write(pa, value) { this.writes.set(pa, BigInt.asUintN(64, value)); }
    read(pa) { return this.writes.get(pa) ?? 0n; }
}

/** A translation regime half: granule log2, input size; the root table */
class Region
{
    constructor(tables, granule, inputsize)
    {
        this.tables = tables;
        this.granule = granule;
        this.stride = granule - 3;
        this.inputsize = inputsize;
        this.start = 4 - Math.floor((inputsize - 4) / this.stride);
        const root_bits = inputsize - (this.stride * (4 - this.start) + 3);
        this.root = tables.alloc(Math.max(8 << root_bits, 1 << granule));
    }
    shift(level) { return BigInt(this.stride * (4 - level) + 3); }
    index(va, level)
    {
        const bits = level === this.start ? this.inputsize - Number(this.shift(level)) : this.stride;
        return (va >> this.shift(level)) & ((1n << BigInt(bits)) - 1n);
    }
    /** The table at `level` holding `va` (made as needed); its descriptor's address */
    slot(va, level, table_bits = 0n)
    {
        let table = this.root;
        for(let l = this.start; l < level; l++)
        {
            const at = table + 8n * this.index(va, l);
            let d = this.tables.read(at);
            if((d & 3n) !== 3n)
            {
                const next = this.tables.alloc(1 << this.granule);
                d = next | 3n | (l === level - 1 ? table_bits : 0n);
                this.tables.write(at, d);
            }
            table = d & 0xFFFFFFFFF000n & ~((1n << BigInt(this.granule)) - 1n);
        }
        return table + 8n * this.index(va, level);
    }
    map(va, level, descriptor, table_bits = 0n)
    {
        const at = this.slot(va, level, table_bits);
        this.tables.write(at, descriptor);
        return at;
    }
    block_levels() { return this.granule === 12 ? [1, 2] : [2]; }
}

function leaf(oa, level, { ap = 0n, attr = 0n, af = 1n, ng = 0n, pxn = 0n, uxn = 0n, sh = 3n, contiguous = 0n } = {})
{
    return oa | (level === 3 ? 3n : 1n) | attr << 2n | ap << 6n | sh << 8n | af << 10n | ng << 11n | contiguous << 52n |
        pxn << 53n | uxn << 54n;
}

// ---- probes
const OP = { ldr: 0, ldrb: 1, str: 2, ldtr: 3, sttr: 4, at_e1r: 5, at_e1w: 6, at_e0r: 7, at_e0w: 8, fetch_el1: 9, fetch_el0: 10,
    write: 11, tlbi: 12, ldr_q: 13, str_q: 14 };

function make_case()
{
    const tables = new Tables();
    const granules = ALL_GRANULES ? [12, 14, 16] : [12];
    const g0 = pick(granules), g1 = pick(granules);
    // (T0SZ keeps the identity map, at 0x4000_0000, reachable: at most 33)
    const t0sz = 16 + rand(18);
    const t1sz = chance(0.05) ? pick([8, 12, 40, 48]) : 16 + rand(24);
    const tbi0 = BigInt(rand(2)), tbi1 = BigInt(rand(2));
    const ips = BigInt(rand(6)), a1 = BigInt(rand(2)), as = BigInt(rand(2));
    const epd1 = chance(0.05) ? 1n : 0n;
    const tg0 = { 12: 0n, 14: 2n, 16: 1n }[g0], tg1 = { 12: 2n, 14: 1n, 16: 3n }[g1];
    const tcr = BigInt(t0sz) | tg0 << 14n | 3n << 12n | BigInt(t1sz) << 16n | a1 << 22n | epd1 << 23n | tg1 << 30n | 3n << 28n |
        ips << 32n | as << 36n | tbi0 << 37n | tbi1 << 38n;
    const mair = [0xFFn, ...Array.from({ length: 7 }, () => pick(MAIR_ATTRS))].reduce((m, a, i) => m | a << BigInt(8 * i), 0n);
    const asid0 = BigInt(rand(1 << 16)), asid1 = BigInt(rand(1 << 16));
    const low = new Region(tables, g0, 64 - t0sz);
    const t1_in_range = t1sz >= 16 && t1sz <= 39;
    const high = new Region(tables, g1, t1_in_range ? 64 - t1sz : 48);
    // the identity map: Normal, EL1 read/write, global, EL1-executable
    const identity_level = g0 === 12 ? 2 : 2;
    const identity_size = 1n << low.shift(identity_level);
    for(let pa = IDENTITY[0] & ~(identity_size - 1n); pa < IDENTITY[1]; pa += identity_size)
    {
        low.map(pa, identity_level, leaf(pa, identity_level, { uxn: 1n }));
    }
    const identity_end = (IDENTITY[1] + identity_size - 1n) & ~(identity_size - 1n);
    const identity_start = IDENTITY[0] & ~(identity_size - 1n);

    // random mappings in both halves
    const mappings = [];
    const random_va = region => {
        for(;;)
        {
            const va = next64() & ((1n << BigInt(region.inputsize)) - 1n);
            if(region === low && va + 0x10000000n > identity_start && va < identity_end) continue;
            return region === low ? va : BigInt.asUintN(64, va - (1n << BigInt(region.inputsize)));
        }
    };
    for(let k = 0; k < 6 + rand(6); k++)
    {
        const region = rand(2) ? low : high;
        if(region === high && !t1_in_range) continue;
        const block = chance(0.3);
        const level = block ? pick(region.block_levels()) : 3;
        const size = 1n << region.shift(level);
        const va = random_va(region) & ~(size - 1n);
        // (nothing may replace the identity map's entries)
        const overlaps = (start, length) => region === low && start < identity_end && start + length > identity_start;
        if(overlaps(va, size)) continue;
        let oa;
        if(block)
        {
            oa = region.granule === 12 ? (level === 2 ? BLOCK_2M : 0x40000000n) : region.granule === 14 ? BLOCK_32M : 0x40000000n;
            if(level === 1 && region.granule === 12) oa = 0x40000000n;
        }
        else
        {
            oa = DATA + BigInt(rand(16)) * 0x10000n;
            if(chance(0.1)) oa = RET_PAGE;
            if(chance(0.1)) oa = SVC_PAGE;
            oa &= ~(size - 1n);
        }
        if(chance(0.05)) oa = HOLE;                              // a hole: an external abort on the access
        if(chance(0.05)) oa |= 1n << BigInt(40 + rand(8));   // beyond 40 bits: an address size fault
        const attrs = {
            ap: BigInt(rand(4)), attr: BigInt(rand(8)), af: chance(0.1) ? 0n : 1n, ng: BigInt(rand(2)),
            pxn: chance(0.2) ? 1n : 0n, uxn: chance(0.3) ? 1n : 0n, sh: BigInt(rand(4)), contiguous: chance(0.1) ? 1n : 0n,
        };
        // (aliases of the guest's own memory and the code pages are read-only: stores must not reach them)
        if(oa === 0x40000000n || oa === RET_PAGE || oa === SVC_PAGE) attrs.ap |= 2n;
        let descriptor = leaf(oa, level, attrs);
        if(chance(0.05)) descriptor &= ~1n;                      // invalid
        if(chance(0.03) && level === 3) descriptor &= ~2n;       // a block at level 3: invalid
        const table_bits = chance(0.15) ? BigInt(rand(16)) << 59n : 0n;
        try
        {
            const slot = region.map(va, level, descriptor, table_bits);
            mappings.push({ va, size, slot, level, region, oa, descriptor });
        }
        catch(e)
        {
            // (a table already a block, or the other way round: skip)
        }
    }
    // table descriptors pointing beyond 40 bits or at a hole
    if(chance(0.2) && mappings.length)
    {
        // (the table entry above a mapping, unless its range holds the identity map)
        const m = pick(mappings);
        const level = m.level - 1;
        const span = 1n << m.region.shift(level);
        const start = m.va & ~(span - 1n);
        if(level >= m.region.start && !(m.region === low && start < identity_end && start + span > identity_start))
        {
            const at = m.region.slot(m.va, level);
            const d = tables.read(at);
            if((d & 3n) === 3n) tables.write(at, chance(0.5) ? d | 1n << 42n : HOLE | 3n);
        }
    }

    // probes: on the mappings (sometimes off by an offset or tagged), and anywhere
    const probes = [];
    const target = () => {
        if(!mappings.length || chance(0.15)) return pick([random_va(low), t1_in_range ? random_va(high) : random_va(low), next64()]);
        const m = pick(mappings);
        // (a block at the start of RAM: the reference keeps its boot stub there, so read the data pages through it)
        const base = m.oa === 0x40000000n ? DATA - 0x40000000n : 0n;
        let va = m.va + base + (next64() & (m.size < 0x10000n ? m.size - 1n : 0xFFFFn));
        if(chance(0.15)) va = va & ~(0xFFn << 56n) | BigInt(rand(256)) << 56n;
        return BigInt.asUintN(64, va);
    };
    // (the reference does not alignment-fault on Device memory with the MMU on, an allowed difference:
    // misaligned probes only where the mapping is Normal memory)
    const device = va => {
        const d = leaf_descriptor(va >> 55n & 1n ? high : low, tables, va);
        if(d === null) return true;
        const attr = mair >> (8n * (d >> 2n & 7n)) & 0xFFn;
        return (attr & 0xF0n) === 0n;
    };
    for(let k = 0; k < 10 + rand(10); k++)
    {
        const kind = pick(["ldr", "ldr", "ldrb", "str", "ldtr", "sttr", "at_e1r", "at_e1w", "at_e0r", "at_e0w", "fetch_el1", "fetch_el0",
            "remap", "ldr_q", "str_q"]);
        let va = target();
        if(["ldr", "str", "ldtr", "sttr", "ldr_q", "str_q"].includes(kind) && (!chance(0.2) || device(va))) va &= ~7n;
        if(kind === "ldr_q" || kind === "str_q") va &= chance(0.8) || device(va) ? ~15n : ~7n;
        if(kind === "ldrb" && device(va) && chance(0.5)) va &= ~7n;
        if(kind.startsWith("fetch"))
        {
            // (only the pages of RET or SVC run: a data page would run its pattern)
            const code = mappings.filter(m => m.oa === RET_PAGE || m.oa === SVC_PAGE);
            if(code.length && !chance(0.2))
            {
                const m = pick(code);
                va = m.va + (next64() & (m.size - 1n) & 0xFFFCn);
            }
            else
            {
                va = random_va(rand(2) || !t1_in_range ? low : high);
                if(mappings.some(m => va >= m.va && va < m.va + m.size)) continue;
            }
            va &= ~3n;
        }
        const data_mappings = mappings.filter(m => m.oa !== RET_PAGE && m.oa !== SVC_PAGE);
        if(kind === "remap" && data_mappings.length)
        {
            // rewrite a leaf (not a code page's) to another data page, then a TLBI, then read through it
            const m = pick(data_mappings);
            const target_pa = DATA + BigInt(rand(16)) * 0x10000n;
            const new_oa = target_pa & ~(m.size - 1n);
            const new_descriptor = leaf(new_oa, m.level, { ap: 0n, attr: 0n, ng: BigInt(rand(2)) });
            probes.push({ op: OP.write, va: m.slot, arg: new_descriptor });
            // (a cached entry is the old descriptor's: global or not decides which TLBI must drop it)
            const old_descriptor = m.descriptor;
            m.descriptor = new_descriptor;
            const asid = a1 ? asid1 : asid0;
            // (ASIDE1 leaves a global entry: then either translation is allowed, so only for nG ones)
            const op2 = pick((old_descriptor >> 11n & 1n) ? [0, 1, 2, 3, 5, 7] : [0, 1, 3, 5, 7]);
            const is = rand(2);
            const xt = op2 === 0 ? 0n : op2 === 2 ? asid << 48n : (asid << 48n | (m.va >> 12n) & 0xFFFFFFFFFFFn);
            probes.push({ op: OP.tlbi, va: xt, arg: BigInt(op2 | is << 3) });
            probes.push({ op: OP.ldr, va: m.va + (target_pa - new_oa), arg: 0n });
            continue;
        }
        if(kind === "remap") continue;
        probes.push({ op: OP[kind], va, arg: next64() });
    }
    const sctlr_a = chance(0.15) ? 1n : 0n;
    const ttbr0 = low.root | asid0 << 48n, ttbr1 = high.root | asid1 << 48n;
    return { tcr, mair, ttbr0, ttbr1, sctlr_a, writes: [...tables.writes], probes, pool_end: tables.next, low, high, tables };
}

/** The leaf descriptor a walk of `va` reaches in the tables (now), or null */
function leaf_descriptor(region, tables, va)
{
    let table = region.root;
    for(let level = region.start; level <= 3; level++)
    {
        const d = tables.read(table + 8n * region.index(va, level));
        if((d & 1n) === 0n) return null;
        if((d & 2n) === 0n || level === 3) return d;
        table = d & 0xFFFFFFFFF000n & ~((1n << BigInt(region.granule)) - 1n);
    }
    return null;
}

const cases = Array.from({ length: CASES }, make_case);
if(process.env.MMU_DUMP)
{
    // (diagnostics: one case's probes and the walks they start with)
    const c = cases[+process.env.MMU_DUMP];
    c.probes.forEach((p, k) => console.log(`${k} ${Object.keys(OP).find(key => OP[key] === p.op)} va ${hex(p.va)} arg ${hex(p.arg)}` +
        (p.op === OP.write || p.op === OP.tlbi ? "" : "\n    " + explain(c, p.va))));
    process.exit(0);
}

/** (diagnostics) the descriptors a walk of `va` reads in a case's tables */
function explain(c, va)
{
    const select = va >> 55n & 1n;
    const region = select ? c.high : c.low;
    let table = region.root, out = [];
    for(let level = region.start; level <= 3; level++)
    {
        const at = table + 8n * region.index(va, level);
        const d = c.tables.read(at);
        out.push(`L${level}@${hex(at)}=${hex(d)}`);
        if((d & 1n) === 0n || (d & 2n) === 0n || level === 3) break;
        table = d & 0xFFFFFFFFF000n & ~((1n << BigInt(region.granule)) - 1n);
    }
    return out.join(" ");
}

// ---- the guest of a batch: a probe interpreter in assembly
// probe record (32 bytes): status (0 done, 1 sync exception at EL1, 2 from EL0), ESR, FAR, value
function guest(batch, first)
{
    const L = [];
    L.push(".text", ".balign 4", ".global run_cases", "run_cases:",
        "    stp x29, x30, [sp, #-96]!", "    stp x19, x20, [sp, #16]", "    stp x21, x22, [sp, #32]", "    stp x23, x24, [sp, #48]",
        "    stp x25, x26, [sp, #64]", "    stp x27, x28, [sp, #80]", "    mrs x27, vbar_el1", "    mrs x26, sctlr_el1", "    mov x19, #0",
        "    adrp x25, case_list", "    add x25, x25, :lo12:case_list",
        "next_case:", "    ldr x0, [x25], #8", "    cbz x0, all_done",
        // case header: tcr, mair, ttbr0, ttbr1, sctlr_a, pool_end, writes count, probes count, writes..., probes..., then output pointer
        "    mov x24, x0",
        // zero the pool up to pool_end
        `    ldr x1, =${hex(POOL)}`, "    ldr x2, [x24, #40]",
        "1:  stp xzr, xzr, [x1], #16", "    cmp x1, x2", "    b.lo 1b",
        // descriptor writes (physical, the MMU is off)
        "    ldr x3, [x24, #48]", "    add x4, x24, #72",
        "2:  cbz x3, 3f", "    ldp x5, x6, [x4], #16", "    str x6, [x5]", "    sub x3, x3, #1", "    b 2b",
        "3:  ldr x23, [x24, #56]", "    mov x22, x4", "    ldr x20, [x24, #64]",
        "    ldr x1, [x24, #0]", "    msr tcr_el1, x1", "    ldr x1, [x24, #8]", "    msr mair_el1, x1",
        "    ldr x1, [x24, #16]", "    msr ttbr0_el1, x1", "    ldr x1, [x24, #24]", "    msr ttbr1_el1, x1",
        "    adr x1, test_vectors", "    msr vbar_el1, x1",
        "    dsb sy", "    tlbi vmalle1", "    dsb sy", "    isb",
        "    ldr x1, [x24, #32]", "    orr x2, x26, #1", "    bic x2, x2, #(1 << 19)", "    bic x2, x2, #2", "    orr x2, x2, x1, lsl #1",
        "    msr sctlr_el1, x2", "    isb",
        "next_probe:", "    cbz x23, case_done",
        "    ldp x2, x0, [x22], #16", "    ldr x3, [x22], #8",
        "    stp xzr, xzr, [x20]", "    stp xzr, xzr, [x20, #16]",
        "    adr x4, op_table", "    ldr w5, [x4, x2, lsl #2]", "    add x4, x4, x5", "    br x4",
        "probe_done:", "    add x20, x20, #32", "    sub x23, x23, #1", "    b next_probe",
        "case_done:", "    msr sctlr_el1, x26", "    isb", "    msr vbar_el1, x27", "    isb", "    b next_case",
        "all_done:", "    ldp x19, x20, [sp, #16]", "    ldp x21, x22, [sp, #32]", "    ldp x23, x24, [sp, #48]",
        "    ldp x25, x26, [sp, #64]", "    ldp x27, x28, [sp, #80]", "    ldp x29, x30, [sp], #96", "    ret",
        ".ltorg");
    // the probes (x0 the VA, x3 the argument, x20 the record; a fault records itself and returns past the instruction)
    const ops = [
        ["p_ldr", ["ldr x1, [x0]", "str x1, [x20, #24]"]],
        ["p_ldrb", ["ldrb w1, [x0]", "str x1, [x20, #24]"]],
        ["p_str", ["str x3, [x0]"]],
        ["p_ldtr", ["ldtr x1, [x0]", "str x1, [x20, #24]"]],
        ["p_sttr", ["sttr x3, [x0]"]],
        ["p_at_e1r", ["at s1e1r, x0", "isb", "mrs x1, par_el1", "str x1, [x20, #24]"]],
        ["p_at_e1w", ["at s1e1w, x0", "isb", "mrs x1, par_el1", "str x1, [x20, #24]"]],
        ["p_at_e0r", ["at s1e0r, x0", "isb", "mrs x1, par_el1", "str x1, [x20, #24]"]],
        ["p_at_e0w", ["at s1e0w, x0", "isb", "mrs x1, par_el1", "str x1, [x20, #24]"]],
        ["p_fetch_el1", ["mov x1, #7", "mov x19, #1", "blr x0", "mov x19, #0", "str x1, [x20, #24]"]],
        ["p_fetch_el0", ["adr x21, 4f", "msr elr_el1, x0", "msr spsr_el1, xzr", "eret", "4:"]],
        ["p_write", ["str x3, [x0]", "dsb sy"]],
        ["p_tlbi", ["and x1, x3, #7", "tst x3, #8", "b.ne 5f",
            "cmp x1, #0", "b.ne 6f", "tlbi vmalle1", "b 9f", "6: cmp x1, #1", "b.ne 6f", "tlbi vae1, x0", "b 9f",
            "6: cmp x1, #2", "b.ne 6f", "tlbi aside1, x0", "b 9f", "6: cmp x1, #3", "b.ne 6f", "tlbi vaae1, x0", "b 9f",
            "6: cmp x1, #5", "b.ne 6f", "tlbi vale1, x0", "b 9f", "6: tlbi vaale1, x0", "b 9f",
            "5: cmp x1, #0", "b.ne 6f", "tlbi vmalle1is", "b 9f", "6: cmp x1, #1", "b.ne 6f", "tlbi vae1is, x0", "b 9f",
            "6: cmp x1, #2", "b.ne 6f", "tlbi aside1is, x0", "b 9f", "6: cmp x1, #3", "b.ne 6f", "tlbi vaae1is, x0", "b 9f",
            "6: cmp x1, #5", "b.ne 6f", "tlbi vale1is, x0", "b 9f", "6: tlbi vaale1is, x0",
            "9: dsb sy", "isb"]],
        ["p_ldr_q", ["ldr q0, [x0]", "fmov x1, d0", "str x1, [x20, #24]", "mov x1, v0.d[1]", "str x1, [x20, #16]"]],
        ["p_str_q", ["fmov d0, x3", "mov v0.d[1], x3", "str q0, [x0]"]],
    ];
    L.push(".balign 4", "op_table:");
    for(const [label] of ops) L.push(`    .word ${label} - op_table`);
    for(const [label, body] of ops) L.push(`${label}:`, ...body.map(line => /^\d:/.test(line) || /^\d+:$/.test(line) ? line : "    " + line), "    b probe_done");
    // the vectors: record the exception; from EL1, skip the instruction (in the EL1 fetch probe, x19 1, return to the link register);
    // from EL0 (the SVC or the abort of the EL0 fetch probe), return to x21 at EL1
    L.push(".balign 2048", "test_vectors:", ".skip 0x200",
        "    mrs x1, esr_el1", "    str x1, [x20, #8]", "    mrs x1, far_el1", "    str x1, [x20, #16]", "    mov x1, #1", "    str x1, [x20]",
        "    cbnz x19, 7f",
        "    mrs x1, elr_el1", "    add x1, x1, #4", "    msr elr_el1, x1", "    eret",
        "7:  msr elr_el1, x30", "    eret",
        ".balign 0x80", ".skip 0x400 - 0x280",
        "    mrs x1, esr_el1", "    str x1, [x20, #8]", "    mrs x1, far_el1", "    str x1, [x20, #16]", "    mov x1, #2", "    str x1, [x20]",
        "    msr elr_el1, x21", "    mov x1, #0x3c5", "    msr spsr_el1, x1", "    eret");
    // the cases
    L.push(".data", ".balign 8", "case_list:");
    batch.forEach((_, i) => L.push(`    .quad case_${first + i}`));
    L.push("    .quad 0");
    batch.forEach((c, i) => {
        const n = first + i;
        L.push(".balign 8", `case_${n}:`, ...[c.tcr, c.mair, c.ttbr0, c.ttbr1, c.sctlr_a, c.pool_end, BigInt(c.writes.length),
            BigInt(c.probes.length)].map(v => `    .quad ${hex(v)}`), `    .quad output_${n}`);
        for(const [pa, value] of c.writes) L.push(`    .quad ${hex(pa)}, ${hex(value)}`);
        for(const p of c.probes) L.push(`    .quad ${p.op}, ${hex(p.va)}, ${hex(p.arg)}`);
    });
    batch.forEach((c, i) => L.push(".balign 8", `output_${first + i}:`, `    .zero ${32 * c.probes.length}`));
    L.push(".text", ".global case_outputs", ".balign 8", "case_outputs:");
    batch.forEach((c, i) => L.push(`    .quad output_${first + i}`, `    .quad ${c.probes.length}`));
    return L.join("\n") + "\n";
}

const MAIN = `#include <a64.h>
#include <stdio.h>
void run_cases(void);
extern const unsigned long case_outputs[][2];
static void fill(unsigned long at, unsigned long size, unsigned long seed)
{
    for(unsigned long i = 0; i < size; i += 8) *(volatile unsigned long *)(at + i) = (seed << 40) ^ (at + i) * 0x9E3779B97F4A7C15ul;
}
int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    for(int p = 0; p < 16; p++) fill(${hex(DATA)} + 0x10000ul * p, 0x10000, p + 1);
    for(unsigned long i = 0; i < 0x10000; i += 4) *(volatile unsigned *)(${hex(RET_PAGE)} + i) = 0xd65f03c0;  // RET
    for(unsigned long i = 0; i < 0x10000; i += 4) *(volatile unsigned *)(${hex(SVC_PAGE)} + i) = 0xd4000001;  // SVC #0
    fill(${hex(BLOCK_2M)}, 0x10000, 17);
    fill(${hex(BLOCK_32M)}, 0x10000, 18);
    __asm__ volatile("dsb sy; ic iallu; isb" ::: "memory");
    run_cases();
    for(int i = 0; i < CASE_COUNT; i++)
    {
        const unsigned long *out = (const unsigned long *)case_outputs[i][0];
        printf("case %d", FIRST + i);
        for(unsigned long k = 0; k < case_outputs[i][1]; k++)
            printf(" | %lx %lx %lx %lx", out[4 * k], out[4 * k + 1], out[4 * k + 2], out[4 * k + 3]);
        unsigned long sum = 0;
        for(unsigned long a = ${hex(DATA)}; a < ${hex(DATA)} + 0x100000; a += 8) sum = (sum ^ *(volatile unsigned long *)a) * 0x100000001B3ul;
        printf(" | memory %lx\\n", sum);
    }
    return 0;
}
`;

const directory_base = root + "build/a64-mmu-oracle/";
fs.mkdirSync(directory_base, { recursive: true });
const only_qemu = process.env.A64_TARGET === "qemu";
let differences = 0, compared = 0, probes = 0;
const setup = ALL_GRANULES ? cpu => cpu.wm.exports["a64_set_granules"](7) : null;
for(let first = 0; first < cases.length; first += BATCH)
{
    const batch = cases.slice(first, first + BATCH);
    fs.writeFileSync(directory_base + `cases-${first}.S`, guest(batch, first));
    fs.writeFileSync(directory_base + `main-${first}.c`, MAIN.replace(/CASE_COUNT/g, String(batch.length)).replace(/FIRST/g, String(first)));
    const directory = build(`mmu-oracle-${first}`, [directory_base + `cases-${first}.S`, directory_base + `main-${first}.c`]);
    const expected = await reference(directory, { memory: MEMORY_MB, timeout: 120000 });
    assert.equal(expected.status, "ok", "QEMU: " + expected.status + " " + expected.text.slice(-500));
    if(only_qemu) { compared += batch.length; continue; }
    const got = await actual(directory, { memory: MEMORY_MB, timeout: 600000, setup });
    assert.equal(got.status, "ok", "v86: " + got.status + " " + got.text.slice(-500));
    const want = expected.text.trim().split("\n"), have = got.text.trim().split("\n");
    assert.equal(have.length, want.length, "line count");
    for(let i = 0; i < want.length; i++)
    {
        compared++;
        probes += batch[i].probes.length;
        if(want[i] === have[i]) continue;
        differences++;
        if(differences > 12) continue;
        const c = batch[i];
        const w = want[i].split(" | "), h = have[i].split(" | ");
        console.log(`DIFF case ${first + i}: tcr ${hex(c.tcr)} mair ${hex(c.mair)} ttbr0 ${hex(c.ttbr0)} ttbr1 ${hex(c.ttbr1)} A ${c.sctlr_a}`);
        for(let k = 1; k < w.length; k++)
        {
            if(w[k] === h[k]) continue;
            const p = c.probes[k - 1];
            const name = p ? Object.keys(OP).find(key => OP[key] === p.op) + " " + hex(p.va) : "";
            console.log(`  probe ${k - 1} ${name}: qemu ${w[k]} v86 ${h[k]}`);
            if(p && process.env.MMU_EXPLAIN) console.log("    " + explain(c, p.va));
        }
    }
}
console.log(`mmu oracle: ${compared} cases, ${probes} probes (${ALL_GRANULES ? "4/16/64 KiB granules, profile v1.1" : "4 KiB granule"}, seed ${SEED}), ` +
    `${differences} differences` + (only_qemu ? " (QEMU only)" : ""));
process.exit(differences ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/a64/mmu_granule.mjs                                                                0000644 0000000 0000000 00000000513 00000000000 014445  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The 16 and 64 KiB granules (docs/arm64-virt-android16-plan.md P3.4):
// tests/a64/mmu.mjs with every granule, on profile v1.1 (the default since
// P8.6; v1 declares 4 KiB only).
//
//   node tests/a64/mmu_granule.mjs [--cases N] [--seed S]
process.argv.push("--granules", "all");
await import("./mmu.mjs");
                                                                                                                                                                                     source/v64/tests/a64/native_oracle.mjs                                                              0000644 0000000 0000000 00000003633 00000000000 014753  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The FP, AdvSIMD and crypto cases on real arm64 hardware (docs/arm64-virt-android16-plan.md
// P2.12): the owner's Mac (Apple M1 Pro: AES, PMULL, SHA1, SHA256) runs the
// cases of simd_oracle, fp_oracle and crypto_oracle natively (the same
// seeds; FPCR set per case, the 16 RMode/FZ/DN combinations per mnemonic for
// scalar FP) and v86 must match it bit for bit: the third oracle beside
// QEMU and the .ref files. The host has more features than profile v1; the
// cases use v1's encodings only.
//
//   node tests/a64/native_oracle.mjs [--cases N] [--seed S] [--filter class|mnemonic]
import { options, run } from "./vector_oracle.mjs";

const opts = options({ cases: 8000 });
let differences = 0;
differences += (await run({ name: "native-simd", against: "native", classes: ["table", "permute", "extract", "copy", "three_same",
    "three_different", "two_misc", "across", "modified_immediate", "shift_immediate", "indexed", "scalar_copy", "scalar_three_same",
    "scalar_three_different", "scalar_two_misc", "scalar_pairwise", "scalar_shift_immediate", "scalar_indexed", "structure", "memory"], ...opts })).differences;
const fpcr = (n, r) => BigInt(r & 3) << 22n | BigInt(r >> 2 & 1) << 24n | BigInt(r >> 3 & 1) << 25n | BigInt(r >> 4 & 1) << 26n;
differences += (await run({ name: "native-fp", against: "native", fpcr, classes: ["fp_fixed", "fp_int", "fp_dp1", "fp_compare", "fp_imm",
    "fp_cond_compare", "fp_dp2", "fp_cond_select", "fp_dp3"], ...opts, cases: Math.ceil(opts.cases * 0.6) })).differences;
differences += (await run({ name: "native-crypto", against: "native", classes: ["aes", "sha3", "sha2", "three_different"],
    mnemonics: ["aese", "aesd", "aesmc", "aesimc", "sha1c", "sha1p", "sha1m", "sha1su0", "sha256h", "sha256h2", "sha256su1", "sha1h",
        "sha1su1", "sha256su0", "pmull", "pmull2"], ...opts, cases: Math.ceil(opts.cases * 0.2) })).differences;
process.exit(differences ? 1 : 0);
                                                                                                     source/v64/tests/a64/oracle/decode.mjs                                                              0000644 0000000 0000000 00000017575 00000000000 014642  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 decode oracle (docs/arm64-virt-android16-plan.md P0.5; P2.1
// compares the v86 decoder with it): llvm-mc --disassemble with the
// profile's -mattr (tests/platform/a64-profile.json llvm_mattr), so an
// encoding of a feature outside the profile is invalid. UDF is the
// permanently undefined encoding and counts as invalid; LLVM's "potentially
// undefined" (CONSTRAINED UNPREDICTABLE) encodings are valid and flagged.
// System register accesses decode whatever the register: whether one exists
// is the system register table's business (P3.1), not the decoder's.
//
//   node tests/a64/oracle/decode.mjs --self-test
//   node tests/a64/oracle/decode.mjs --sample N [--seed S]
//       N encodings, stratified over the top 8 bits, decoded into
//       build/a64-oracle/sample-<S>.json: [[hex, valid, mnemonic], ...]
//   node tests/a64/oracle/decode.mjs --check FILE
//       FILE holds the v86 decoder's [[hex, valid, mnemonic], ...] (P2.1);
//       fails on a different validity or mnemonic
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../../", import.meta.url));
const profile = JSON.parse(fs.readFileSync(root + "tests/platform/a64-profile.json", "utf8"));

export function llvm_mc()
{
    const candidates = [process.env.LLVM_MC, "/opt/homebrew/opt/llvm/bin/llvm-mc", "/usr/local/opt/llvm/bin/llvm-mc", "llvm-mc"].filter(Boolean);
    for(const candidate of candidates)
    {
        const result = spawnSync(candidate, ["--version"], { encoding: "utf8" });
        if(result.status === 0) return { path: candidate, version: result.stdout.match(/LLVM version ([\d.]+)/)?.[1] };
    }
    throw new Error("llvm-mc not found (Homebrew llvm, or LLVM_MC=<path>)");
}

/**
 * Decode 32-bit words: [{ word, valid, text, mnemonic, unpredictable }]
 */
export function decode(words, mattr = profile.llvm_mattr)
{
    const { path } = llvm_mc();
    const results = [];
    const CHUNK = 100000;
    for(let start = 0; start < words.length; start += CHUNK)
    {
        const chunk = words.slice(start, start + CHUNK);
        const input = chunk.map(w => [0, 8, 16, 24].map(s => "0x" + ((w >>> s) & 0xFF).toString(16)).join(" ")).join("\n") + "\n";
        const run = spawnSync(path, ["--disassemble", "-triple=aarch64", "-mattr=" + mattr], { input, encoding: "utf8", maxBuffer: 1 << 30 });
        assert.equal(run.status, 0, run.stderr.slice(0, 2000));
        const invalid = new Set(), unpredictable = new Set();
        for(const m of run.stderr.matchAll(/^<stdin>:(\d+):\d+: warning: (invalid instruction encoding|potentially undefined instruction encoding)/gm))
        {
            (m[2].startsWith("invalid") ? invalid : unpredictable).add(+m[1] - 1);
        }
        const lines = run.stdout.split("\n").filter(line => line.startsWith("\t")).map(line => line.trim().replace(/\s+/g, " "));
        let next = 0;
        chunk.forEach((word, i) => {
            if(invalid.has(i)) { results.push({ word, valid: false, text: "", mnemonic: "", unpredictable: false }); return; }
            const text = lines[next++];
            assert.ok(text !== undefined, "llvm-mc printed fewer instructions than it decoded");
            const mnemonic = text.split(/[ .]/)[0];
            results.push({ word, valid: mnemonic !== "udf", text, mnemonic, unpredictable: unpredictable.has(i) });
        });
        assert.equal(next, lines.length, "llvm-mc printed more instructions than it decoded");
    }
    return results;
}

// (a xorshift generator: the same sample on every host)
function sample(count, seed)
{
    let state = BigInt(seed) * 0x9E3779B97F4A7C15n & 0xFFFFFFFFFFFFFFFFn || 1n;
    const next = () => {
        state ^= state << 13n & 0xFFFFFFFFFFFFFFFFn;
        state ^= state >> 7n;
        state ^= state << 17n & 0xFFFFFFFFFFFFFFFFn;
        return Number(state & 0xFFFFFFn);
    };
    const words = [];
    for(let i = 0; i < count; i++) words.push(((i & 0xFF) << 24 | next()) >>> 0);
    return words;
}

const hex = w => (w >>> 0).toString(16).padStart(8, "0");

// Encodings whose result the profile fixes (A64 encodings, little-endian words)
const SELF_TEST = [
    [0xD503201F, "nop"], [0x4E284800, "aese"], [0x0EE0E000, "pmull"], [0x5E004000, "sha256h"], [0x5E280800, "sha1h"],
    [0x1AC04000, "crc32b"], [0xC85FFC20, "ldaxr"], [0x8B020020, "add"], [0x1E602820, "fadd"], [0x4EA01C00, "mov"],
    [0xD503233F, "hint"], [0xD5380000, "mrs"], [0xD508871F, "tlbi"], [0xD50B7520, "ic"], [0xD50B7420, "dc"],
    [0x00000000, null],     // UDF #0
    [0xB8200020, null],     // LDADD (LSE)
    [0x4E809400, null],     // SDOT (DotProd)
    [0x1EE02800, null],     // FADD Hd (FP16)
    [0x04200000, null],     // SVE ADD
    [0xD50B7E20, "dc"],     // DC CIVAC
    [0xCE608000, null],     // SHA512H (FEAT_SHA512 is not in v1)
    [0xDAC10000 | 0x3E0, null], // PACIA (PAuth)
];

if(import.meta.url === `file://${process.argv[1]}`)
{
    const args = process.argv.slice(2);
    const { path, version } = llvm_mc();
    if(args[0] === "--self-test")
    {
        const results = decode(SELF_TEST.map(([w]) => w));
        let failed = 0;
        results.forEach((r, i) => {
            const want = SELF_TEST[i][1];
            const ok = want === null ? !r.valid : r.valid && r.mnemonic === want;
            if(!ok) { failed++; console.log(`${hex(r.word)}: llvm-mc "${r.text}" (valid ${r.valid}), expected ${want || "invalid"}`); }
        });
        console.log(`A64 decode oracle self-test: llvm-mc ${version} (${path}), -mattr=${profile.llvm_mattr}: ${results.length - failed}/${results.length}`);
        process.exit(failed ? 1 : 0);
    }
    else if(args[0] === "--sample")
    {
        const count = +args[1], seed = args[2] === "--seed" ? +args[3] : 1;
        const results = decode(sample(count, seed));
        const directory = root + "build/a64-oracle/";
        fs.mkdirSync(directory, { recursive: true });
        fs.writeFileSync(directory + `sample-${seed}.json`, "[\n" + results.map(r => JSON.stringify([hex(r.word), r.valid ? 1 : 0, r.mnemonic])).join(",\n") + "\n]\n");
        const groups = new Map();
        for(const r of results)
        {
            const op0 = (r.word >>> 25 & 0xF).toString(2).padStart(4, "0");
            const g = groups.get(op0) || { total: 0, valid: 0 };
            g.total++;
            g.valid += r.valid;
            groups.set(op0, g);
        }
        console.log(`llvm-mc ${version}: ${count} encodings (seed ${seed}), ${results.filter(r => r.valid).length} valid; by op0 (bits 28:25):`);
        for(const [op0, g] of [...groups].sort()) console.log(`  ${op0}: ${g.valid}/${g.total}`);
    }
    else if(args[0] === "--check")
    {
        const rows = JSON.parse(fs.readFileSync(args[1], "utf8"));
        const results = decode(rows.map(([w]) => parseInt(w, 16) >>> 0));
        const differences = new Map();
        rows.forEach(([w, valid, mnemonic], i) => {
            const r = results[i];
            const problem = !!valid !== r.valid ? `v86 ${valid ? "valid" : "UNDEF"}, llvm-mc ${r.valid ? r.text : "invalid"}` :
                valid && mnemonic !== r.mnemonic ? `mnemonic v86 ${mnemonic}, llvm-mc ${r.mnemonic}` : null;
            if(problem)
            {
                const key = (r.mnemonic || mnemonic || "?") + ": " + problem.replace(/ .*/, "");
                if(!differences.has(key)) differences.set(key, { count: 0, example: `${w}: ${problem}` });
                differences.get(key).count++;
            }
        });
        for(const [key, { count, example }] of differences) console.log(`${key} x${count} (e.g. ${example})`);
        console.log(`${rows.length} encodings, ${[...differences.values()].reduce((n, d) => n + d.count, 0)} differences`);
        process.exit(differences.size ? 1 : 0);
    }
    else
    {
        console.log("usage: decode.mjs --self-test | --sample N [--seed S] | --check FILE");
        process.exit(2);
    }
}
                                                                                                                                   source/v64/tests/a64/page_fuzz.mjs                                                                  0000644 0000000 0000000 00000046166 00000000000 014142  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The A64 page tier against the interpreter (docs/jit-unification-plan.md
// P6.5, J2): random programs of the integer forms the page tier compiles
// (arithmetic, logical, moves, bitfields, shifts, multiply and divide, flags
// and their readers, loads and stores with every addressing mode, pairs,
// literals, acquire/release), mixed with control flow (forward conditional
// branches, counted loops, calls, indirect branches) and with forms it steps
// (CRC32, RBIT, FP moves and arithmetic, exclusives and their spins, system
// register reads).
// Each program is a function the bare-metal guest (MMU on: A64_MMU) calls
// ROUNDS times on its registers and a 1 KiB buffer kept across the calls;
// the registers, NZCV and the buffer at the end must be the same on the
// interpreter and on the page tier (compiling at the first boundary:
// A64_JIT_HOT=1), bit for bit.
//
//   node tests/a64/page_fuzz.mjs [--programs N] [--length N] [--rounds N] [--seed S]
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const PROGRAMS = +option("--programs", 40);
const LENGTH = +option("--length", 120);
const ROUNDS = +option("--rounds", 64);
const SEED = +option("--seed", 1);

let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
function next64()
{
    state ^= state << 13n & (1n << 64n) - 1n;
    state ^= state >> 7n;
    state ^= state << 17n & (1n << 64n) - 1n;
    return state;
}
const rand = n => Number(next64() % BigInt(n));
const pick = list => list[rand(list.length)];

// registers the program computes in (x8 holds the buffer, x16 and x17 are addressing and loop scratch)
const REGS = [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15];
const x = () => "x" + pick(REGS);
const w = () => "w" + pick(REGS);
const r = () => (rand(2) ? x : w)();
const same = () => { const n = pick(REGS); return rand(2) ? ["x" + n, "x" + pick(REGS), "x" + pick(REGS)] : ["w" + n, "w" + pick(REGS), "w" + pick(REGS)]; };
const CONDS = ["eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al"];
// (CSET and its kin take no AL)
const CONDS_NOT_AL = CONDS.slice(0, -1);
const SHIFTS = ["lsl", "lsr", "asr"];
const EXTENDS = ["uxtb", "uxth", "uxtw", "sxtb", "sxth", "sxtw"];
const imm12 = () => rand(4096);
const LOGICAL_IMMS = ["#0xff", "#0xffff", "#0xf0f0f0f0f0f0f0f0", "#0x5555555555555555", "#0x7ffffffffffffffe", "#0xfffffff0", "#0x3c"];
const LOGICAL_IMMS32 = ["#0xff", "#0xffff", "#0xf0f0f0f0", "#0x55555555", "#0x7ffffffe", "#0xfffffff0", "#0x3c"];

// (vector registers v0-v7 in an arrangement)
const ARRANGEMENTS = ["8b", "16b", "4h", "8h", "2s", "4s", "2d"];
const v = t => `v${rand(8)}.${t}`;

let label = 0;
/** One random instruction, or a short sequence (a construct) */
function instruction(depth)
{
    const kind = rand(55);
    const [d, a, b] = same();
    const wide = d.startsWith("x");
    switch(kind)
    {
        case 0: return `add ${d}, ${a}, #${imm12()}`;
        case 1: return `subs ${d}, ${a}, #${imm12()}${rand(2) ? ", lsl #12" : ""}`;
        case 2: return `${pick(["add", "sub", "adds", "subs"])} ${d}, ${a}, ${b}, ${pick(SHIFTS)} #${rand(wide ? 64 : 32)}`;
        case 3: return `${pick(["add", "sub", "adds", "subs"])} ${d}, ${a}, ${wide ? "w" + b.slice(1) : b}, ${pick(EXTENDS)} #${rand(5)}`;
        case 4: return `${pick(["and", "orr", "eor", "ands"])} ${d}, ${a}, ${pick(wide ? LOGICAL_IMMS : LOGICAL_IMMS32)}`;
        case 5: return `${pick(["and", "orr", "eor", "bic", "orn", "eon", "ands", "bics"])} ${d}, ${a}, ${b}, ${pick([...SHIFTS, "ror"])} #${rand(wide ? 64 : 32)}`;
        case 6: return `${pick(["movz", "movn", "movk"])} ${d}, #${rand(65536)}, lsl #${wide ? 16 * rand(4) : 16 * rand(2)}`;
        case 7: return `${pick(["ubfm", "sbfm", "bfm"])} ${d}, ${a}, #${rand(wide ? 64 : 32)}, #${rand(wide ? 64 : 32)}`;
        case 8: return `extr ${d}, ${a}, ${b}, #${rand(wide ? 64 : 32)}`;
        case 9: return `${pick(["adc", "adcs", "sbc", "sbcs"])} ${d}, ${a}, ${b}`;
        case 10: return `${pick(["ccmp", "ccmn"])} ${a}, ${rand(2) ? b : "#" + rand(32)}, #${rand(16)}, ${pick(CONDS)}`;
        case 11: return `${pick(["csel", "csinc", "csinv", "csneg"])} ${d}, ${a}, ${b}, ${pick(CONDS)}`;
        case 12: return `${pick(["madd", "msub"])} ${d}, ${a}, ${b}, ${wide ? x() : w()}`;
        case 13: return `${pick(["smaddl", "smsubl", "umaddl", "umsubl"])} ${x()}, ${w()}, ${w()}, ${x()}`;
        case 14: return `${pick(["smulh", "umulh"])} ${x()}, ${x()}, ${x()}`;
        case 15: return `${pick(["udiv", "sdiv", "lslv", "lsrv", "asrv", "rorv"])} ${d}, ${a}, ${b}`;
        case 16: return `${pick(["rev16", "rev", "clz", "cls"])} ${d}, ${a}`;
        case 17: return `cmp ${a}, ${b}\n    cset ${d}, ${pick(CONDS_NOT_AL)}`;
        case 18: return `adr ${x()}, .`;
        // loads and stores: x8 + an offset in the buffer
        case 19: case 20: {
            const size = pick([["b", 1, w], ["h", 2, w], ["", 4, w], ["", 8, x], ["sb", 1, x], ["sh", 2, x], ["sw", 4, x], ["sb", 1, w], ["sh", 2, w]]);
            const load = size[0].startsWith("s") || rand(2);
            const reg = size[2]();
            const op = load ? "ldr" + size[0] : "str" + size[0];
            const offset = rand(1024 / size[1]) * size[1];
            return `${op} ${reg}, [x8, #${offset}]`;
        }
        case 21: {
            // unscaled, pre- and post-index through x16
            const sz = pick([["", 8, x], ["", 4, w], ["b", 1, w], ["h", 2, w]]);
            const base = 256 + rand(512);
            const imm = rand(64) - 32;
            const load = rand(2);
            const form = pick([`[x16, #${imm}]`, `[x16, #${imm}]!`, `[x16], #${imm}`]);
            const op = (form.startsWith("[x16, #") && !form.endsWith("!") ? (load ? "ldur" : "stur") : load ? "ldr" : "str") + sz[0];
            return `add x16, x8, #${base}\n    ${op} ${sz[2]()}, ${form}`;
        }
        case 22: {
            // register offset
            const sz = pick([["", 8, x, 3], ["", 4, w, 2], ["h", 2, w, 1], ["b", 1, w, 0]]);
            return `mov x16, #${rand(64)}\n    ${rand(2) ? "ldr" : "str"}${sz[0]} ${sz[2]()}, [x8, x16, lsl #${rand(2) ? sz[3] : 0}]`;
        }
        case 23: {
            const pair = rand(2) ? ["x", 8] : ["w", 4];
            const offset = rand(16) * pair[1];
            const form = pick([`[x16, #${offset}]`, `[x16, #${offset}]!`, `[x16], #${offset}`]);
            const r1 = pair[0] + pick(REGS);
            let r2 = pair[0] + pick(REGS);
            while(r2 === r1) r2 = pair[0] + pick(REGS);
            return `add x16, x8, #${rand(512)}\n    ${rand(2) ? "ldp" : "stp"} ${r1}, ${r2}, ${form}`;
        }
        case 24: return `ldr ${x()}, ${label++ % 2 ? "." : ".+8"}`;
        case 25: return `add x16, x8, #${8 * rand(64)}\n    ${pick(["ldar", "stlr"])} ${x()}, [x16]`;
        // control flow
        case 26: case 27: {
            if(depth > 1) return "nop";
            const n = ++label;
            const test = pick([`b.${pick(CONDS)}`, `cbz ${r()},`, `cbnz ${r()},`, `tbz ${x()}, #${rand(64)},`, `tbnz ${x()}, #${rand(64)},`]);
            const body = Array.from({ length: 1 + rand(3) }, () => instruction(depth + 1)).join("\n    ");
            return `${test} 1${n}f\n    ${body}\n1${n}:`;
        }
        case 28: {
            if(depth > 0) return "nop";
            const n = ++label;
            const body = Array.from({ length: 1 + rand(4) }, () => instruction(depth + 1)).join("\n    ");
            return `mov x17, #${2 + rand(6)}\n2${n}:\n    ${body}\n    subs x17, x17, #1\n    b.ne 2${n}b`;
        }
        // (calls only from the body: a leaf calling a leaf could recurse forever)
        case 29: return depth === 0 ? `bl leaf_${rand(3)}` : "nop";
        case 30: { const n = ++label; return `adr x16, 3${n}f\n    br x16\n    ${instruction(depth + 1)}\n3${n}:`; }
        // forms the page tier steps
        case 31: return `${pick(["crc32b", "crc32h", "crc32w", "crc32cb"])} ${w()}, ${w()}, ${w()}`;
        case 32: return `rbit ${d}, ${a}`;
        case 33: return `fmov d0, ${x()}\n    fmov d1, ${x()}\n    fadd d2, d0, d1\n    fmov ${x()}, d2`;
        case 34: {
            // (not in a loop: the status register is the loop's counter)
            if(depth > 0) return "clrex";
            const value = x();
            let status = pick(REGS);
            while("x" + status === value) status = pick(REGS);
            return `add x16, x8, #${8 * rand(64)}\n    ldxr ${x()}, [x16]\n    stxr w${status}, ${value}, [x16]`;
        }
        case 35: return `mrs ${x()}, nzcv`;
        case 36: return `msr nzcv, ${x()}`;
        case 37: return `${pick(["lsl", "lsr", "asr", "ror"])} ${d}, ${a}, #${rand(wide ? 64 : 32)}`;
        case 38: {
            const op = pick(["sxtb", "sxth", "uxtb", "uxth"]);
            return `${op} ${op.startsWith("u") ? "w" + d.slice(1) : d}, w${a.slice(1)}`;
        }
        // SIMD&FP loads and stores (S, D, Q; single and pair), and moves into general registers
        case 39: {
            const [reg, size] = pick([["s", 4], ["d", 8], ["q", 16]]);
            return `${rand(2) ? "ldr" : "str"} ${reg}${rand(8)}, [x8, #${rand(1024 / size) * size}]`;
        }
        case 40: {
            const [reg, size] = pick([["s", 4], ["d", 8], ["q", 16]]);
            const a1 = rand(8);
            const a2 = (a1 + 1 + rand(7)) % 8;
            const form = pick([`[x16, #${size * rand(4)}]`, `[x16, #${size * rand(4)}]!`, `[x16], #${size * rand(4)}`]);
            // (aligned, or not: with cores in workers an unaligned store is a plain one)
            return `add x16, x8, #${rand(2) ? 16 * rand(32) : 256 + rand(256)}\n    ${rand(2) ? "ldp" : "stp"} ${reg}${a1}, ${reg}${a2}, ${form}`;
        }
        case 41: return `${pick(["fmov " + x() + ", d" + rand(8), "umov " + x() + ", v" + rand(8) + ".d[1]", "fmov " + w() + ", s" + rand(8)])}`;
        case 42: return `add x16, x8, #${256 + rand(512)}\n    ${rand(2) ? "ldr" : "str"} q${rand(8)}, [x16, #${16 * (rand(8) - 4)}]!`;
        // scalar FP on ordinary values (the page tier's fast path) and back into a general register
        case 43: case 44: {
            const p = rand(2) ? "d" : "s";
            const [f1, f2, f3, f4] = [rand(8), rand(8), rand(8), rand(8)];
            const op = pick(["fadd", "fsub", "fmul", "fdiv", "fnmul"]);
            return `scvtf ${p}${f1}, ${x()}\n    scvtf ${p}${f2}, ${w()}\n    ${op} ${p}${f3}, ${p}${f1}, ${p}${f2}\n` +
                `    ${pick(["fmadd", "fmsub", "fnmadd", "fnmsub"])} ${p}${f4}, ${p}${f3}, ${p}${f2}, ${p}${f1}\n    fcvtzs ${x()}, ${p}${f4}`;
        }
        case 45: {
            const p = rand(2) ? "d" : "s";
            return `${pick(["fabs", "fneg", "fmov"])} ${p}${rand(8)}, ${p}${rand(8)}\n    fcmp${rand(2) ? "e" : ""} ${p}${rand(8)}, ${rand(2) ? p + rand(8) : "#0.0"}\n    cset ${d}, ${pick(CONDS_NOT_AL)}`;
        }
        // AdvSIMD vector forms (the page tier's NEON templates, and helper calls)
        case 47: {
            const op = pick(["add", "sub", "cmeq", "cmtst", "cmgt", "cmge", "cmhi", "cmhs", "smax", "umax", "smin", "umin", "mul", "urhadd", "sqadd"]);
            const arrangements = ["add", "sub", "cmeq", "cmtst", "cmgt", "cmge", "cmhi", "cmhs", "sqadd"].includes(op) ? ARRANGEMENTS : ARRANGEMENTS.slice(0, 6);
            const t = pick(arrangements);
            return `${op} ${v(t)}, ${v(t)}, ${v(t)}`;
        }
        case 48: {
            const t = pick(["8b", "16b"]);
            return `${pick(["and", "bic", "orr", "orn", "eor", "bsl", "bit", "bif"])} ${v(t)}, ${v(t)}, ${v(t)}`;
        }
        case 49: {
            const t = pick(ARRANGEMENTS);
            switch(rand(6))
            {
                case 0: { const b8 = pick(["8b", "16b"]); return `${pick(["not", "cnt"])} ${v(b8)}, ${v(b8)}`; }
                case 1: return `${pick(["abs", "neg"])} ${v(t)}, ${v(t)}`;
                case 2: return `${pick(["cmeq", "cmgt", "cmge", "cmle", "cmlt"])} ${v(t)}, ${v(t)}, #0`;
                case 3: { const [op, ts] = pick([["rev64", ARRANGEMENTS.slice(0, 6)], ["rev32", ARRANGEMENTS.slice(0, 4)], ["rev16", ["8b", "16b"]]]); const r = pick(ts); return `${op} ${v(r)}, ${v(r)}`; }
                case 4: { const [narrow, source] = pick([["8b", "8h"], ["4h", "4s"], ["2s", "2d"]]); return `xtn ${v(narrow)}, ${v(source)}`; }
                default: { const [narrow, source] = pick([["16b", "8h"], ["8h", "4s"], ["4s", "2d"]]); return `xtn2 ${v(narrow)}, ${v(source)}`; }
            }
        }
        case 50: {
            const t = pick(ARRANGEMENTS);
            const esize = { b: 8, h: 16, s: 32, d: 64 }[t.slice(-1)];
            const op = pick(["shl", "sshr", "ushr"]);
            return `${op} ${v(t)}, ${v(t)}, #${op === "shl" ? rand(esize) : 1 + rand(esize)}`;
        }
        case 51: switch(rand(9))
        {
            case 0: return pick([`movi ${v("16b")}, #${rand(256)}`, `movi ${v("8b")}, #${rand(256)}`, `movi ${v("2d")}, #0xff00ff0000ffff00`, `movi d${rand(8)}, #0x00ff00ff00ff00ff`,
                `movi ${v("4s")}, #${rand(256)}, lsl #${8 * rand(4)}`, `mvni ${v("2s")}, #${rand(256)}, msl #${pick([8, 16])}`, `fmov ${v("4s")}, #1.5`, `fmov ${v("2d")}, #-2.0`]);
            case 1: return `${pick(["orr", "bic"])} ${v(pick(["4s", "2s"]))}, #${rand(256)}, lsl #${8 * rand(4)}`;
            case 2: { const [t, r] = pick([["8b", w], ["16b", w], ["4h", w], ["8h", w], ["2s", w], ["4s", w], ["2d", x]]); return `dup ${v(t)}, ${r()}`; }
            case 3: { const [t, e, n] = pick([["16b", "b", 16], ["8h", "h", 8], ["4s", "s", 4], ["2d", "d", 2], ["8b", "b", 16], ["2s", "s", 4]]); return `dup ${v(t)}, v${rand(8)}.${e}[${rand(n)}]`; }
            case 4: { const [e, n, r] = pick([["b", 16, w], ["h", 8, w], ["s", 4, w], ["d", 2, x]]); return `mov v${rand(8)}.${e}[${rand(n)}], ${r()}`; }
            case 5: { const [e, n] = pick([["b", 16], ["h", 8], ["s", 4], ["d", 2]]); return `mov v${rand(8)}.${e}[${rand(n)}], v${rand(8)}.${e}[${rand(n)}]`; }
            case 6: return pick([`umov ${w()}, v${rand(8)}.b[${rand(16)}]`, `umov ${w()}, v${rand(8)}.h[${rand(8)}]`, `mov ${w()}, v${rand(8)}.s[${rand(4)}]`,
                `mov ${x()}, v${rand(8)}.d[${rand(2)}]`, `smov ${x()}, v${rand(8)}.b[${rand(16)}]`, `smov ${w()}, v${rand(8)}.h[${rand(8)}]`, `smov ${x()}, v${rand(8)}.s[${rand(4)}]`]);
            case 7: return pick([`fmov d${rand(8)}, ${x()}`, `fmov s${rand(8)}, ${w()}`, `fmov v${rand(8)}.d[1], ${x()}`, `fmov ${x()}, v${rand(8)}.d[1]`]);
            default: { const [e, n] = pick([["b", 16], ["h", 8], ["s", 4], ["d", 2]]); return `mov ${e}${rand(8)}, v${rand(8)}.${e}[${rand(n)}]`; }
        }
        case 52: {
            if(rand(3) === 0) { const q = rand(2); return `ext ${v(q ? "16b" : "8b")}, ${v(q ? "16b" : "8b")}, ${v(q ? "16b" : "8b")}, #${rand(q ? 16 : 8)}`; }
            const t = pick([...ARRANGEMENTS.slice(0, 6), "2d"]);
            return `${pick(["zip1", "zip2", "uzp1", "uzp2", "trn1", "trn2"])} ${v(t)}, ${v(t)}, ${v(t)}`;
        }
        case 53: {
            // vector FP on ordinary values (converted integers): the fast path, FMLA and FMLS fused
            const t = pick(["2s", "4s", "2d"]);
            const [f1, f2, f3] = [rand(8), rand(8), rand(8)];
            return `scvtf v${f1}.${t}, v${f1}.${t}\n    scvtf v${f2}.${t}, v${f2}.${t}\n` +
                `    ${pick(["fadd", "fsub", "fmul", "fdiv", "fmla", "fmls"])} v${f3}.${t}, v${f1}.${t}, v${f2}.${t}`;
        }
        case 54: {
            // a load-exclusive spin (the same value at the same load: a yield from the helper,
            // P3.9), its result used after it and the register changed before the next one
            if(depth > 0) return "nop";
            const n = ++label;
            const loaded = x();
            let sum = x();
            while(sum === loaded) sum = x();
            return `mov x17, #${6 + rand(6)}\n4${n}:\n    add x16, x8, #${8 * rand(64)}\n    ldxr ${loaded}, [x16]\n` +
                `    add ${sum}, ${sum}, ${loaded}\n    eor ${loaded}, ${loaded}, #1\n    subs x17, x17, #1\n    b.ne 4${n}b\n    clrex`;
        }
        default: return `${pick(["ubfx", "sbfx"])} ${d}, ${a}, #${rand(wide ? 32 : 16)}, #${1 + rand(wide ? 32 : 16)}`;
    }
}

function program(n)
{
    // (half the programs start with FPSR.IXC set: the FP fast path's condition)
    const fpsr = n % 2 ? "mov x16, #0x10\n    msr fpsr, x16" : "msr fpsr, xzr";
    const body = Array.from({ length: LENGTH }, () => instruction(0)).join("\n    ");
    const leaf = k => `leaf_${k}:\n    ${Array.from({ length: 3 }, () => instruction(2)).join("\n    ")}\n    ret`;
    return `// generated by tests/a64/page_fuzz.mjs (seed ${SEED}, program ${n})
    .text
    .balign 4096
    .global fuzz_body
fuzz_body:
    stp x29, x30, [sp, #-16]!
    mov x8, x0
${REGS.map(i => `    ldr x${i}, [x8, #${1024 + 8 * i}]`).join("\n")}
    ldr x16, [x8, #${1024 + 8 * 16}]
    msr nzcv, x16
    ${fpsr}
    ${body}
${REGS.map(i => `    str x${i}, [x8, #${1024 + 8 * i}]`).join("\n")}
    mrs x16, nzcv
    str x16, [x8, #${1024 + 8 * 16}]
    ldp x29, x30, [sp], #16
    ret
${[0, 1, 2].map(leaf).join("\n")}
`;
}

const HARNESS = `#include <a64.h>
#include <stdio.h>
#include <stdint.h>
void fuzz_body(uint64_t *buffer);
static uint64_t buffer[(1024 + 8 * 17) / 8 + 1] __attribute__((aligned(64)));
int main(int argc, char **argv)
{
    uint64_t s = SEED;
    for(unsigned i = 0; i < sizeof(buffer) / 8; i++) { s ^= s << 13; s ^= s >> 7; s ^= s << 17; buffer[i] = s; }
    for(int round = 0; round < ROUNDS; round++) fuzz_body(buffer);
    for(unsigned i = 0; i < sizeof(buffer) / 8; i++) printf("%016lx%c", (unsigned long)buffer[i], i % 4 == 3 ? '\\n' : ' ');
    printf("\\n");
    return 0;
}
`;

const directory = root + "build/a64-page-fuzz/";
fs.mkdirSync(directory, { recursive: true });
process.env.A64_MMU = "1";
let differences = 0, compiled = 0, native = 0, steps = 0;
for(let n = 0; n < PROGRAMS; n++)
{
    const seed = next64();
    fs.writeFileSync(directory + "fuzz.S", program(n));
    fs.writeFileSync(directory + "harness.c", HARNESS);
    const guest = build("page-fuzz", [directory + "harness.c", directory + "fuzz.S"], { cflags: [`-DSEED=${seed}ULL`, `-DROUNDS=${ROUNDS}`] });
    delete process.env.A64_JIT;
    const interpreted = await actual(guest);
    process.env.A64_JIT = "1";
    process.env.A64_JIT_HOT = "1";
    const jit = await actual(guest);
    assert.equal(interpreted.status, "ok", `program ${n} (interpreter): ${interpreted.status}\n${interpreted.text}`);
    assert.equal(jit.status, "ok", `program ${n} (page tier): ${jit.status}\n${jit.text}`);
    const t = jit.page_tier;
    compiled += t.compiled;
    native += t.retired;
    steps += t.steps;
    if(interpreted.text !== jit.text)
    {
        differences++;
        fs.copyFileSync(directory + "fuzz.S", directory + `fuzz-diff-${n}.S`);
        console.log(`program ${n}: differs (kept as fuzz-diff-${n}.S)\n interpreter:\n${interpreted.text}\n page tier:\n${jit.text}`);
    }
}
delete process.env.A64_JIT;
console.log(`page fuzz: ${PROGRAMS} programs of ${LENGTH} constructs x ${ROUNDS} rounds, ${differences} differences ` +
    `(page tier: ${compiled} compiles, ${native} native instructions, ${steps} steps)`);
assert.ok(native > 0, "the page tier ran code");
process.exit(differences ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/a64/pan.c                                                                          0000644 0000000 0000000 00000021617 00000000000 012351  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // FEAT_PAN (profile v2; tests/a64/pan.mjs against QEMU's -cpu max): with
// PSTATE.PAN set, EL1's loads, stores, exclusives and DC ZVA to a page EL0
// may access (AP[1] set: read/write or read-only) take a permission fault,
// pages only EL1 may access do not; the unprivileged LDTR and STTR are
// checked as EL0's; AT S1E1R and S1E1W and instruction fetches ignore PAN.
// MSR PAN (immediate and register), SPSR_EL1's PAN bit, an exception with
// SCTLR_EL1.SPAN clear (PAN set) and set (PAN kept), and ERET restoring
// PAN. Each probe prints its value or the exception's ESR and FAR.
#include <a64.h>
#include <stdio.h>
#include <stdint.h>

#define TEST_VA 0x1000000000UL // (L1 index 64, L2 index 0, L3 index 0)
#define UNMAPPED_VA (TEST_VA + 0x100000)

static uint64_t l1[512] __attribute__((aligned(4096)));
static uint64_t l2[512] __attribute__((aligned(4096)));
static uint64_t l3[512] __attribute__((aligned(4096)));
static uint64_t data[4][512] __attribute__((aligned(4096)));
static uint32_t code[1024] __attribute__((aligned(4096)));

// the test pages: AP[2:1] 00 EL1 read/write, 01 EL1 and EL0 read/write,
// 10 EL1 read-only, 11 EL1 and EL0 read-only; and a page of code EL0 may
// read (AP 11, UXN), executable at EL1
enum { EL1_RW, BOTH_RW, EL1_RO, BOTH_RO, CODE };
#define PAGE_VA(k) (TEST_VA + (uint64_t)(k) * 0x1000)

// (MSR PAN, #1 and #0, encoded: the assembler takes them for Armv8.1 only)
static void set_pan(int on)
{
    if(on) __asm__ volatile(".inst 0xd500419f" ::: "memory");
    else __asm__ volatile(".inst 0xd500409f" ::: "memory");
}
static uint64_t read_pan(void) { uint64_t v; __asm__ volatile("mrs %0, S3_0_C4_C2_3" : "=r"(v)); return v; }

static void report(const char *what, int taken, struct a64_fault *f, uint64_t value)
{
    if(taken) printf("%s: fault esr %lx far %lx\n", what, f->esr, f->far);
    else printf("%s: %lx\n", what, value);
}

static void probe_load(const char *what, uint64_t va)
{
    struct a64_fault f;
    uint64_t v = 0;
    a64_expect();
    __asm__ volatile("ldr %0, [%1]" : "+r"(v) : "r"(va) : "memory");
    report(what, a64_caught(&f), &f, v);
}
// (a store to page k at offset 16: the value there afterwards, read through the identity map)
static void probe_store(const char *what, int k)
{
    struct a64_fault f;
    data[k][2] = 0;
    a64_expect();
    __asm__ volatile("str %0, [%1]" :: "r"(0x5A5A5A5A5A5A5A5AUL), "r"(PAGE_VA(k) + 16) : "memory");
    report(what, a64_caught(&f), &f, *(volatile uint64_t *)&data[k][2]);
}
static void probe_ldtr(const char *what, uint64_t va)
{
    struct a64_fault f;
    uint64_t v = 0;
    a64_expect();
    __asm__ volatile("ldtr %0, [%1]" : "+r"(v) : "r"(va) : "memory");
    report(what, a64_caught(&f), &f, v);
}
static void probe_sttr(const char *what, uint64_t va)
{
    struct a64_fault f;
    a64_expect();
    __asm__ volatile("sttr %0, [%1]" :: "r"(0x1234UL), "r"(va) : "memory");
    report(what, a64_caught(&f), &f, 0);
}
static void probe_ldxr(const char *what, uint64_t va)
{
    struct a64_fault f;
    uint64_t v = 0;
    a64_expect();
    __asm__ volatile("ldxr %0, [%1]\n clrex" : "+r"(v) : "r"(va) : "memory");
    report(what, a64_caught(&f), &f, v);
}
static void probe_zva(const char *what, uint64_t va)
{
    struct a64_fault f;
    a64_expect();
    __asm__ volatile("dc zva, %0" :: "r"(va) : "memory");
    report(what, a64_caught(&f), &f, 0);
}
static void probe_at(const char *what, uint64_t va, int write)
{
    if(write) __asm__ volatile("at s1e1w, %0\n isb" :: "r"(va) : "memory");
    else __asm__ volatile("at s1e1r, %0\n isb" :: "r"(va) : "memory");
    // (the fault bit and status, or success: the address and the attributes are the walk's)
    uint64_t par = a64_read(par_el1);
    printf("%s: par %lx\n", what, par & 1 ? par & 0x7F : par & 0xFFFFFFFFF001UL);
}
static void probe_fetch(const char *what, uint64_t va)
{
    struct a64_fault f;
    uint64_t v = 0;
    a64_expect();
    __asm__ volatile("mov x0, #0\n blr %1\n mov %0, x0" : "+r"(v) : "r"(va) : "x0", "x30", "memory");
    report(what, a64_caught(&f), &f, v);
}

static uint64_t pan_in_handler(void) { return read_pan(); }

// an exception (a translation fault) taken with PAN `pan` and SCTLR_EL1.SPAN
// `span`: PAN in the handler, SPSR_EL1's PAN, and PAN after the return
static void probe_exception(int pan, int span)
{
    uint64_t sctlr = a64_read(sctlr_el1);
    a64_write(sctlr_el1, span ? sctlr | 1UL << 23 : sctlr & ~(1UL << 23));
    __asm__ volatile("isb" ::: "memory");
    set_pan(pan);
    struct a64_fault f;
    uint64_t v = 0;
    a64_fault_probe = pan_in_handler;
    a64_expect();
    __asm__ volatile("ldr %0, [%1]" : "+r"(v) : "r"(UNMAPPED_VA) : "memory");
    int taken = a64_caught(&f);
    a64_fault_probe = 0;
    uint64_t after = read_pan();
    set_pan(0);
    a64_write(sctlr_el1, sctlr);
    __asm__ volatile("isb" ::: "memory");
    printf("exception with pan %d span %d: taken %d, pan in the handler %lx, spsr pan %lx, pan after %lx\n",
        pan, span, taken, f.probe, f.spsr & 1UL << 22, after);
}

// ERET to EL1h with SPSR_EL1.PAN `pan`
static void probe_eret(int pan)
{
    uint64_t spsr = 5 | (a64_read(daif) & 0xFUL << 6) | (pan ? 1UL << 22 : 0);
    __asm__ volatile(
        "adr x9, 1f\n"
        "msr elr_el1, x9\n"
        "msr spsr_el1, %0\n"
        "eret\n"
        "1:\n" :: "r"(spsr) : "x9", "memory");
    uint64_t after = read_pan();
    set_pan(0);
    printf("eret with spsr pan %d: pan %lx\n", pan, after);
}

int main(int argc, char **argv)
{
    uint64_t mmfr1 = 0;
    __asm__ volatile("mrs %0, S3_0_C0_C7_1" : "=r"(mmfr1));
    printf("FEAT_PAN: %s\n", (mmfr1 >> 20 & 15) ? "yes" : "no");
    if(!(mmfr1 >> 20 & 15)) return 1;

    for(int k = 0; k < 4; k++) for(int i = 0; i < 512; i++) data[k][i] = 0x1111111111111111UL * (k + 1) + i;
    for(int i = 0; i < 1024; i++) code[i] = 0xD65F03C0; // RET
    code[0] = 0xD2800540; // MOV X0, #42
    code[1] = 0xD65F03C0;
    __asm__ volatile("dc cvau, %0\n dsb ish\n ic ivau, %0\n dsb ish\n isb" :: "r"(code) : "memory");
    l1[0] = 0x00000000UL | 1 | 1 << 2 | 1 << 10;
    l1[1] = 0x40000000UL | 1 | 3 << 8 | 1 << 10;
    l1[2] = 0x80000000UL | 1 | 3 << 8 | 1 << 10;
    l1[64] = (uint64_t)l2 | 3;
    l2[0] = (uint64_t)l3 | 3;
    // (Normal, inner shareable, AF; EL0 never executes them)
    const uint64_t attr = 3 | 3 << 8 | 1 << 10 | 1UL << 54;
    l3[EL1_RW] = (uint64_t)data[0] | attr | 0UL << 6;
    l3[BOTH_RW] = (uint64_t)data[1] | attr | 1UL << 6;
    l3[EL1_RO] = (uint64_t)data[2] | attr | 2UL << 6;
    l3[BOTH_RO] = (uint64_t)data[3] | attr | 3UL << 6;
    l3[CODE] = (uint64_t)code | attr | 3UL << 6;
    __asm__ volatile("dsb ish" ::: "memory");
    a64_write(mair_el1, 0x00FF);
    // (T0SZ 25, write-back inner shareable walks, 4 KiB, no TTBR1 walks, 40-bit PA, 16-bit ASIDs)
    a64_write(tcr_el1, 25 | 1 << 8 | 1 << 10 | 3 << 12 | 1 << 23 | 2UL << 32 | 1UL << 36);
    a64_write(ttbr0_el1, (uint64_t)l1);
    __asm__ volatile("dsb ish\n tlbi vmalle1\n dsb ish\n isb" ::: "memory");
    // (MMU, caches, SPAN set: exceptions keep PAN until probe_exception says otherwise)
    a64_write(sctlr_el1, a64_read(sctlr_el1) | 1 | 1 << 2 | 1 << 12 | 1UL << 23);
    __asm__ volatile("isb" ::: "memory");

    static const char *const names[] = { "el1 rw", "both rw", "el1 ro", "both ro" };
    char what[64];
    for(int pan = 0; pan < 2; pan++)
    {
        set_pan(pan);
        printf("pan %d: PAN reads %lx\n", pan, read_pan());
        for(int k = 0; k < 4; k++)
        {
            snprintf(what, sizeof what, "pan %d load %s", pan, names[k]); probe_load(what, PAGE_VA(k) + 8);
            snprintf(what, sizeof what, "pan %d store %s", pan, names[k]); probe_store(what, k);
            snprintf(what, sizeof what, "pan %d ldtr %s", pan, names[k]); probe_ldtr(what, PAGE_VA(k) + 24);
            snprintf(what, sizeof what, "pan %d sttr %s", pan, names[k]); probe_sttr(what, PAGE_VA(k) + 32);
            snprintf(what, sizeof what, "pan %d ldxr %s", pan, names[k]); probe_ldxr(what, PAGE_VA(k) + 40);
            snprintf(what, sizeof what, "pan %d dc zva %s", pan, names[k]); probe_zva(what, PAGE_VA(k) + 0x800);
            snprintf(what, sizeof what, "pan %d at s1e1r %s", pan, names[k]); probe_at(what, PAGE_VA(k), 0);
            snprintf(what, sizeof what, "pan %d at s1e1w %s", pan, names[k]); probe_at(what, PAGE_VA(k), 1);
        }
        snprintf(what, sizeof what, "pan %d fetch from code EL0 may read", pan); probe_fetch(what, PAGE_VA(CODE));
    }
    set_pan(0);

    // MSR PAN with a register, SPSR_EL1's PAN bit
    __asm__ volatile("msr S3_0_C4_C2_3, %0" :: "r"(1UL << 22) : "memory");
    printf("msr pan (register) 1<<22: %lx\n", read_pan());
    __asm__ volatile("msr S3_0_C4_C2_3, %0" :: "r"(0UL) : "memory");
    printf("msr pan (register) 0: %lx\n", read_pan());
    a64_write(spsr_el1, 1UL << 22 | 5);
    printf("spsr_el1 keeps pan: %lx\n", a64_read(spsr_el1) & 1UL << 22);

    for(int pan = 0; pan < 2; pan++) for(int span = 0; span < 2; span++) probe_exception(pan, span);
    probe_eret(1);
    probe_eret(0);
    return 0;
}
                                                                                                                 source/v64/tests/a64/pan.mjs                                                                        0000644 0000000 0000000 00000002641 00000000000 012714  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// FEAT_PAN (profile v2, cpu_profile: "generic-arm64"; tests/a64/pan.c): the same
// output on QEMU's -cpu max (the cortex-a35 reference has no PAN), the
// interpreter and the page tier; profile v1.1 has no PAN (the test says so
// and stops).
import assert from "node:assert/strict";
import { build, reference, actual } from "./guest_runner.mjs";

const directory = build("pan", [new URL("pan.c", import.meta.url).pathname]);
const text = result => {
    assert.equal(result.status, "ok", result.text);
    return result.text.trim();
};
const expected = text(await reference(directory, { extra: ["-cpu", "max,pmu=off,sve=off,cntfrq=1000000000"] }));
assert.match(expected, /^FEAT_PAN: yes/, "QEMU's -cpu max has PAN");
delete process.env.A64_MMU;
delete process.env.A64_JIT;
const v2 = { options: { cpu_profile: "generic-arm64" } };
assert.equal(text(await actual(directory, v2)), expected, "the interpreter against QEMU");
process.env.A64_JIT = "1";
const jit = await actual(directory, v2);
assert.equal(text(jit), expected, "the page tier against QEMU");
console.log(`page tier: ${jit.page_tier.retired} native instructions, ${jit.page_tier.access_fills} access cache fills`);
delete process.env.A64_JIT;
const v1 = await actual(directory, { options: { cpu_profile: "generic-arm64-v1.1" } });
assert.equal(v1.text.trim(), "FEAT_PAN: no", "profile v1.1 has no PAN");
console.log(expected);
console.log("pan: passed");
                                                                                               source/v64/tests/a64/perf-baseline.json                                                             0000644 0000000 0000000 00000005774 00000000000 015044  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
  "about": "The frozen Alpine performance baseline (docs/arm64-virt-android16-plan.md P9.4): tools/a64_jit_metrics.mjs's medians",
  "build": "vA6-2-gd4f03ada",
  "release_build": true,
  "date": "2026-10-17",
  "sessions": 3,
  "results": {
    "interpreter-1c": {
      "probe_done_ms": 35571,
      "ms": 38688,
      "mips": 26.2
    },
    "jit-1c": {
      "probe_done_ms": 6314,
      "ms": 7256,
      "mips": 122.8,
      "compiles": 1797,
      "compile_ms": 451,
      "evictions": 0,
      "table_free_low": 11106,
      "native_share": 0.9718160134485438,
      "steps_per_instruction": 0.003112810431490725,
      "chained_share": 0.4443245769546356
    },
    "interpreter-2c": {
      "probe_done_ms": 41827,
      "ms": 45451,
      "mips": 25.4
    },
    "jit-2c": {
      "probe_done_ms": 6860,
      "ms": 7972,
      "mips": 116.2,
      "compiles": 1949,
      "compile_ms": 511,
      "evictions": 0,
      "table_free_low": 11071,
      "native_share": 0.9737345370487824,
      "steps_per_instruction": 0.002902903153622607,
      "chained_share": 0.6168893357586831
    },
    "interpreter-4c": {
      "probe_done_ms": 57407,
      "ms": 61667,
      "mips": 24.2
    },
    "jit-4c": {
      "probe_done_ms": 7038,
      "ms": 8068,
      "mips": 120.3,
      "compiles": 2010,
      "compile_ms": 496,
      "evictions": 0,
      "table_free_low": 11058,
      "native_share": 0.9732387749058619,
      "steps_per_instruction": 0.003031604314402525,
      "chained_share": 0.6128027771143628
    },
    "live-interpreter-1c": {
      "boot_to_login_ms": 238327,
      "probe_done_ms": 246544,
      "ms": 253012,
      "mips": 22.9
    },
    "live-jit-1c": {
      "boot_to_login_ms": 34687,
      "probe_done_ms": 35654,
      "ms": 38690,
      "mips": 122.2,
      "compiles": 4126,
      "compile_ms": 1151,
      "evictions": 0,
      "table_free_low": 10603,
      "native_share": 0.9665831215676226,
      "steps_per_instruction": 0.004531118960712459,
      "chained_share": 0.6602280286413204
    },
    "live-interpreter-2c": {
      "boot_to_login_ms": 280983,
      "probe_done_ms": 291832,
      "ms": 299342,
      "mips": 22.8
    },
    "live-jit-2c": {
      "boot_to_login_ms": 39549,
      "probe_done_ms": 40618,
      "ms": 43769,
      "mips": 112.2,
      "compiles": 4272,
      "compile_ms": 1255,
      "evictions": 0,
      "table_free_low": 10509,
      "native_share": 0.966531487133411,
      "steps_per_instruction": 0.004510157162998465,
      "chained_share": 0.7002856514063931
    },
    "live-interpreter-4c": {
      "boot_to_login_ms": 362226,
      "probe_done_ms": 375837,
      "ms": 385054,
      "mips": 22.7
    },
    "live-jit-4c": {
      "boot_to_login_ms": 40629,
      "probe_done_ms": 41955,
      "ms": 45160,
      "mips": 114.3,
      "compiles": 4341,
      "compile_ms": 1224,
      "evictions": 0,
      "table_free_low": 10469,
      "native_share": 0.9664380212740012,
      "steps_per_instruction": 0.004568992396272941,
      "chained_share": 0.6946122914009033
    }
  }
}
    source/v64/tests/a64/pl011_hello.mjs                                                                0000644 0000000 0000000 00000002735 00000000000 014162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The first A64 program prints through the PL011 (docs/arm64-virt-android16-plan.md
// A1): a bare-metal guest writes a line to the UART's data register while
// it polls the flag register, on QEMU and on v86; both serial outputs and
// the result blocks are equal.
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const source = root + "build/a64-pl011-hello.c";
fs.writeFileSync(source, `#include <a64.h>
#include <stdio.h>
#define UART ((volatile unsigned *)0x09000000)
static void put(char c)
{
    while(UART[0x18 / 4] & 1 << 5) {}  // TXFF
    UART[0] = c;
}
int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    unsigned fr = UART[0x18 / 4], id = UART[0xFE0 / 4] | UART[0xFE4 / 4] << 8 | UART[0xFE8 / 4] << 16;
    for(const char *s = "Hello from A64 through the PL011\\n"; *s; s++) put(*s);
    printf("fr %#x periph %#x\\n", fr & 0x90, id & 0xFFFFF);
    return 0;
}
`);
const directory = build("pl011-hello", [source], { general_regs_only: true });
const expected = await reference(directory);
const got = await actual(directory);
assert.equal(expected.status, "ok");
assert.equal(got.status, "ok");
assert.equal(got.serial, expected.serial, "serial output");
assert.equal(got.text, expected.text);
assert.match(got.serial, /^Hello from A64 through the PL011\n$/);
console.log("PASS " + JSON.stringify(got.serial) + " " + JSON.stringify(got.text) + " on QEMU and v86");
                                   source/v64/tests/a64/platform_probe.c                                                               0000644 0000000 0000000 00000005127 00000000000 014604  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Directed bare-metal checks of the reference's platform behaviour that the
// v86 virt machine copies (docs/arm64-virt-android16-plan.md P0.2): PSCI over
// HVC (version, features, an unknown function), HVC with a non-zero
// immediate, SMC, and loads from physical addresses with nothing mapped.
//
//   A64_PLATFORM <check> <result>

#include <a64.h>
#include <stdio.h>

static void hvc(const char *name, uint64_t function)
{
    printf("A64_PLATFORM %s %ld\n", name, (long)a64_hvc(function, 0, 0, 0));
}

static void faulting_load(const char *name, uint64_t address)
{
    struct a64_fault fault;
    uint64_t value = 0;
    a64_expect();
    __asm__ volatile("ldr %w0, [%1]" : "=r"(value) : "r"(address) : "memory");
    if(a64_caught(&fault))
    {
        printf("A64_PLATFORM %s fault esr=%#010lx far=%#lx\n", name, (unsigned long)fault.esr, (unsigned long)fault.far);
    }
    else
    {
        printf("A64_PLATFORM %s value=%#lx\n", name, (unsigned long)value);
    }
}

int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    struct a64_fault fault;
    hvc("psci_version", 0x84000000);
    hvc("psci_features.cpu_on64", 0x8400000A); // (PSCI_FEATURES needs an argument; x1 = 0 here)
    printf("A64_PLATFORM psci_features.cpu_on64.arg %ld\n", (long)a64_hvc(0x8400000A, 0xC4000003, 0, 0));
    printf("A64_PLATFORM psci_features.unknown.arg %ld\n", (long)a64_hvc(0x8400000A, 0x840000FF, 0, 0));
    printf("A64_PLATFORM smccc_version %ld\n", (long)a64_hvc(0x80000000, 0, 0, 0));
    printf("A64_PLATFORM smccc_arch_features.workaround_1 %ld\n", (long)a64_hvc(0x80000001, 0x80008000, 0, 0));
    hvc("psci_unknown_function", 0x840000FF);
    hvc("smccc_unknown_function", 0xC2000000);
    a64_expect();
    int64_t imm1 = a64_hvc_imm1(0x84000000);
    if(a64_caught(&fault)) printf("A64_PLATFORM hvc_imm1 fault esr=%#010lx\n", (unsigned long)fault.esr);
    else printf("A64_PLATFORM hvc_imm1 %ld\n", (long)imm1);
    a64_expect();
    __asm__ volatile("mov x0, #0x84000000\n smc #0" ::: "x0", "x1", "x2", "x3", "memory");
    if(a64_caught(&fault)) printf("A64_PLATFORM smc fault esr=%#010lx\n", (unsigned long)fault.esr);
    else printf("A64_PLATFORM smc returned\n");
    // (the virt map: 0x0A00_0000 virtio-mmio, 0x0C00_0000 platform bus,
    // 0x0800_0000 GIC distributor; holes and the space above RAM)
    faulting_load("load_0x0a100000", 0x0A100000);
    faulting_load("load_0x09040000", 0x09040000);
    faulting_load("load_0x40000000_plus_ram", 0x40000000 + 128 * 0x100000ul);
    faulting_load("load_0x100_0000_0000", 0x10000000000ul);
    faulting_load("load_0x80_0000_0000", 0x8000000000ul);
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/a64/platform_probe.expected                                                        0000644 0000000 0000000 00000001276 00000000000 016164  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       A64_PLATFORM psci_version 65537
A64_PLATFORM psci_features.cpu_on64 -1
A64_PLATFORM psci_features.cpu_on64.arg 0
A64_PLATFORM psci_features.unknown.arg -1
A64_PLATFORM smccc_version -1
A64_PLATFORM smccc_arch_features.workaround_1 -1
A64_PLATFORM psci_unknown_function -1
A64_PLATFORM smccc_unknown_function -1
A64_PLATFORM hvc_imm1 65537
A64_PLATFORM smc fault esr=0x02000000
A64_PLATFORM load_0x0a100000 fault esr=0x96000010 far=0xa100000
A64_PLATFORM load_0x09040000 fault esr=0x96000010 far=0x9040000
A64_PLATFORM load_0x40000000_plus_ram fault esr=0x96000010 far=0x48000000
A64_PLATFORM load_0x100_0000_0000 fault esr=0x96000000 far=0x10000000000
A64_PLATFORM load_0x80_0000_0000 value=0xffffffff
                                                                                                                                                                                                                                                                                                                                  source/v64/tests/a64/platform_probe.mjs                                                             0000644 0000000 0000000 00000002362 00000000000 015151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// tests/a64/platform_probe.c (PSCI over HVC, HVC #1, SMC, loads from
// physical addresses with nothing mapped) against the reference's results in
// tests/a64/platform_probe.expected, which v86's virt machine copies
// (docs/arm64-virt-android16-plan.md P0.2 and the profile's IMPLEMENTATION
// DEFINED choices). A64_TARGET=qemu|v86; A64_PLATFORM_RECORD=1 rewrites the
// expected file from the QEMU reference.
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, root, target } from "./guest_runner.mjs";

const machine = target();
const expected_file = root + "tests/a64/platform_probe.expected";
const result = await machine.run(build("platform-probe", [root + "tests/a64/platform_probe.c"]));
assert.equal(result.status, "ok", result.text);
if(process.env.A64_PLATFORM_RECORD)
{
    assert.equal(machine.name, "qemu", "the expected results come from the reference");
    fs.writeFileSync(expected_file, result.text);
    console.log("wrote " + expected_file);
}
else
{
    assert.equal(result.text, fs.readFileSync(expected_file, "latin1"), machine.name + " differs from platform_probe.expected");
    console.log(`platform probe: ${machine.name} matches (${result.text.trim().split("\n").length} checks)`);
}
                                                                                                                                                                                                                                                                              source/v64/tests/a64/psi_test.c                                                                     0000644 0000000 0000000 00000010330 00000000000 013413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* PSI triggers under memory pressure, with zram as swap
 * (docs/arm64-virt-android16-plan.md P9.2; what Android's lmkd waits on):
 * a trigger on /proc/pressure/memory, "some" stall of 100 ms in a 1 s
 * window; a child in the memory cgroup CGROUP (the caller limits it) writes
 * MIB MiB of compressible pages, which reclaim moves to zram, and reads them
 * back twice. The trigger must fire meanwhile, the pages come back intact.
 * Built by tools/a64_kernel.mjs.
 *
 *   psi_test <cgroup> <MiB>
 *
 * A64_PSI_CHILD swap=<bytes in swap> zram=<mm_stat> once written,
 * A64_PSI_OK events=N on success, A64_PSI_FAIL <why> else. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

static void fail(const char *what)
{
    printf("A64_PSI_FAIL %s (errno %d)\n", what, errno);
    exit(1);
}

static void read_line(const char *path, char *buffer, size_t size)
{
    buffer[0] = 0;
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if(fd < 0) return;
    ssize_t n = read(fd, buffer, size - 1);
    close(fd);
    buffer[n > 0 ? n : 0] = 0;
    char *end = strchr(buffer, '\n');
    if(end) *end = 0;
}

static void child(const char *cgroup, long mib)
{
    char path[512], swap[64], zram[256];
    snprintf(path, sizeof(path), "%s/cgroup.procs", cgroup);
    int fd = open(path, O_WRONLY | O_CLOEXEC);
    if(fd < 0 || write(fd, "0", 1) != 1) fail("join the cgroup");
    close(fd);
    long page = sysconf(_SC_PAGESIZE), words = page / 8;
    size_t size = (size_t)mib << 20, pages = size / page;
    uint64_t *memory = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if(memory == MAP_FAILED) fail("mmap");
    /* (a 64-byte pattern that names the page: compressible, not one value repeated, which zram would keep without compressing) */
    for(size_t p = 0; p < pages; p++) for(long w = 0; w < words; w++) memory[p * words + w] = (uint64_t)p << 32 | (uint64_t)(w & 7);
    snprintf(path, sizeof(path), "%s/memory.swap.current", cgroup);
    read_line(path, swap, sizeof(swap));
    read_line("/sys/block/zram0/mm_stat", zram, sizeof(zram));
    printf("A64_PSI_CHILD swap=%s zram=%s\n", swap, zram);
    size_t bad = 0;
    for(int pass = 0; pass < 2; pass++)
    {
        for(size_t p = 0; p < pages; p++)
        {
            for(long w = 0; w < words; w++) bad += memory[p * words + w] != ((uint64_t)p << 32 | (uint64_t)(w & 7));
        }
    }
    _exit(bad ? 3 : 0);
}

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    if(argc < 3) fail("usage");
    int trigger = open("/proc/pressure/memory", O_RDWR | O_NONBLOCK | O_CLOEXEC);
    if(trigger < 0) fail("open /proc/pressure/memory");
    const char *threshold = "some 100000 1000000";
    if(write(trigger, threshold, strlen(threshold) + 1) < 0) fail("write the trigger");
    pid_t pid = fork();
    if(pid < 0) fail("fork");
    if(pid == 0) child(argv[1], atol(argv[2]));
    int events = 0, status = 0;
    struct timespec start, now;
    clock_gettime(CLOCK_MONOTONIC, &start);
    for(;;)
    {
        struct pollfd p = { .fd = trigger, .events = POLLPRI };
        int ready = poll(&p, 1, 100);
        if(ready < 0 && errno != EINTR) fail("poll");
        if(ready > 0 && (p.revents & POLLERR)) fail("POLLERR on the trigger");
        if(ready > 0 && (p.revents & POLLPRI)) events++;
        pid_t done = waitpid(pid, &status, WNOHANG);
        if(done == pid) break;
        clock_gettime(CLOCK_MONOTONIC, &now);
        if(now.tv_sec - start.tv_sec > 900) { kill(pid, SIGKILL); fail("the child takes more than 900 s"); }
    }
    clock_gettime(CLOCK_MONOTONIC, &now);
    if(!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    {
        printf("A64_PSI_FAIL the child: %s %d\n", WIFEXITED(status) ? "exit" : "signal",
            WIFEXITED(status) ? WEXITSTATUS(status) : WTERMSIG(status));
        return 1;
    }
    if(events == 0) fail("no trigger event");
    char some[256];
    read_line("/proc/pressure/memory", some, sizeof(some));
    printf("A64_PSI_OK events=%d seconds=%ld pressure=%s\n", events, (long)(now.tv_sec - start.tv_sec), some);
    return 0;
}
                                                                                                                                                                                                                                                                                                        source/v64/tests/a64/selinux_load.c                                                                 0000644 0000000 0000000 00000006527 00000000000 014264  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SELinux enforcing on the androidish kernel (docs/arm64-virt-android16-plan.md
 * P9.2), what Android's first-stage init does before the second stage: the
 * minimal policy (tests/a64/minimal.cil, compiled by tests/a64/cil2bin.c)
 * written to selinuxfs's load in one write, then enforce. Then a check that
 * the policy is enforced: it declares process:setrlimit and allows no one
 * it, so changing a hard limit fails with EACCES (in a child, which fork and
 * sigchld, allowed, let run and report). Built by tools/a64_kernel.mjs.
 *
 *   selinux_load <policy>
 *
 * A64_SELINUX_OK enforce=1 context=<the process's> denied=setrlimit on
 * success, A64_SELINUX_FAIL <why> else. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>

#define SELINUXFS "/sys/fs/selinux"

static void fail(const char *what)
{
    printf("A64_SELINUX_FAIL %s (errno %d)\n", what, errno);
    exit(1);
}

static int read_text(const char *path, char *buffer, size_t size)
{
    int fd = open(path, O_RDONLY | O_CLOEXEC);
    if(fd < 0) return -1;
    ssize_t n = read(fd, buffer, size - 1);
    close(fd);
    if(n < 0) return -1;
    buffer[n] = 0;
    while(n > 0 && (buffer[n - 1] == '\n' || buffer[n - 1] == 0)) buffer[--n] = 0;
    return 0;
}

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    if(argc < 2) fail("usage");
    if(mount("selinuxfs", SELINUXFS, "selinuxfs", 0, NULL) < 0 && errno != EBUSY) fail("mount selinuxfs");
    int in = open(argv[1], O_RDONLY | O_CLOEXEC);
    if(in < 0) fail("open policy");
    struct stat st;
    if(fstat(in, &st) < 0) fail("stat policy");
    char *policy = malloc(st.st_size);
    if(read(in, policy, st.st_size) != st.st_size) fail("read policy");
    close(in);
    /* (selinuxfs takes the policy in one write from offset 0) */
    int load = open(SELINUXFS "/load", O_WRONLY | O_CLOEXEC);
    if(load < 0) fail("open load");
    if(write(load, policy, st.st_size) != st.st_size) fail("load the policy");
    close(load);
    int enforce = open(SELINUXFS "/enforce", O_RDWR | O_CLOEXEC);
    if(enforce < 0) fail("open enforce");
    if(write(enforce, "1", 1) != 1) fail("set enforce");
    close(enforce);
    char text[256], context[256], version[32];
    if(read_text(SELINUXFS "/enforce", text, sizeof(text)) < 0 || strcmp(text, "1")) fail("enforce is not 1");
    if(read_text("/proc/self/attr/current", context, sizeof(context)) < 0) fail("attr/current");
    if(read_text(SELINUXFS "/policyvers", version, sizeof(version)) < 0) fail("policyvers");
    pid_t child = fork();
    if(child < 0) fail("fork");
    if(child == 0)
    {
        struct rlimit limit;
        getrlimit(RLIMIT_NOFILE, &limit);
        limit.rlim_max = limit.rlim_cur;
        if(setrlimit(RLIMIT_NOFILE, &limit) == 0) _exit(1);
        _exit(errno == EACCES ? 0 : 2);
    }
    int status;
    if(waitpid(child, &status, 0) < 0 || !WIFEXITED(status)) fail("waitpid");
    if(WEXITSTATUS(status) == 1) fail("setrlimit of the hard limit was allowed");
    if(WEXITSTATUS(status) != 0) fail("setrlimit failed, not with EACCES");
    printf("A64_SELINUX_OK enforce=1 context=%s policy_bytes=%ld kernel_policyvers=%s denied=setrlimit\n",
        context, (long)st.st_size, version);
    return 0;
}
                                                                                                                                                                         source/v64/tests/a64/simd_oracle.mjs                                                                0000644 0000000 0000000 00000001606 00000000000 014417  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AdvSIMD (integer and FP, vector and scalar), the SIMD&FP loads, stores and
// moves against QEMU (docs/arm64-virt-android16-plan.md P2.5, P2.7, P2.8: at
// least 1,500 cases, 0 differences; tests/a64/vector_oracle.mjs makes and
// runs the cases, FPCR random per case).
//
//   node tests/a64/simd_oracle.mjs [--cases N] [--seed S] [--filter class|mnemonic]
import { options, run } from "./vector_oracle.mjs";

const SIMD = ["table", "permute", "extract", "copy", "three_same", "three_different", "two_misc", "across",
    "modified_immediate", "shift_immediate", "indexed", "scalar_copy", "scalar_three_same", "scalar_three_different",
    "scalar_two_misc", "scalar_pairwise", "scalar_shift_immediate", "scalar_indexed", "structure", "memory"];
const { differences } = await run({ name: "simd", classes: SIMD, ...options({ cases: 8000 }) });
process.exit(differences ? 1 : 0);
                                                                                                                          source/v64/tests/a64/system_oracle.mjs                                                              0000644 0000000 0000000 00000032643 00000000000 015014  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Exceptions and the system controls of the A64 core against QEMU
// (docs/arm64-virt-android16-plan.md P3.2): every fault point records the
// syndrome (ESR_EL1), FAR_EL1 where the class defines it, ELR_EL1,
// SPSR_EL1, X0-X7 and NZCV as the exception left them, and the vector it
// came through; QEMU's records and v86's must be equal. The cases run at
// EL1 and at EL0 (an ERET to the case's code; the EL0 code ends with SVC
// #0xFFFF), with the MMU off, under the SCTLR_EL1, CPACR_EL1 and
// CNTKCTL_EL1 settings they name: UNDEF in its forms (UDF, SMC and HVC
// where they UNDEF, HLT, unallocated and read-only system registers, EL1
// registers from EL0), the WFI/WFE, FP/SIMD, system register and cache
// maintenance traps, an illegal exception return, SVC, BRK, instruction
// and data aborts, PC and SP alignment, exclusives, and the SP0 vectors.
// (DC ZVA with the MMU off and NZCV on entry differ by the allowed list;
// where QEMU deviates from the Arm ARM, SP alignment, WFE at EL0 and the
// DAIFSet trap's syndrome, v86 is held to the architecture's syndrome.)
//
//   node tests/a64/system_oracle.mjs [--rounds N] [--seed S]
import assert from "node:assert/strict";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const ROUNDS = +option("--rounds", 3);
const SEED = +option("--seed", 1);

let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
function next64()
{
    state ^= state << 13n & (1n << 64n) - 1n;
    state ^= state >> 7n;
    state ^= state << 17n & (1n << 64n) - 1n;
    return state;
}
const hex = v => "0x" + BigInt.asUintN(64, BigInt(v)).toString(16);

// SCTLR_EL1 bits the cases change (the rest stays as the runtime set it)
const UCI = 1n << 26n, UCT = 1n << 15n, DZE = 1n << 14n, UMA = 1n << 9n, NTWI = 1n << 16n, NTWE = 1n << 18n, SA = 1n << 3n, SA0 = 1n << 4n;
const ALL_EL0 = UCI | UCT | DZE | UMA | NTWI | NTWE;
const HOLE = "0x0b000000";

// [name, level, { sctlr_clear, sctlr_set, cpacr, cntkctl }, body, v86_only]: the body runs with x0-x7
// random and x8 pointing at a 64-byte scratch block in RAM. A v86_only case is one where the
// reference deviates from the Arm ARM (tests/platform/a64-profile.json's allowed list): v86's record
// is held to the architecture's syndrome instead ([taken, ESR])
const CASES = [
    ["udf", 1, {}, "udf #0"],
    ["smc", 1, {}, "smc #0"],
    ["hlt", 1, {}, "hlt #0"],
    ["brk", 1, {}, "brk #0x1234"],
    ["svc", 1, {}, "svc #0x42"],
    ["unallocated sysreg", 1, {}, "mrs x0, s3_7_c15_c15_7"],
    ["msr to MIDR", 1, {}, "msr s3_0_c0_c0_0, x1"],
    ["fp off", 1, { cpacr: 0 }, "fmov d0, x1"],
    ["simd off", 1, { cpacr: 0 }, "add v0.4s, v1.4s, v2.4s"],
    ["fp off: FPCR", 1, { cpacr: 0 }, "mrs x0, fpcr"],
    ["fp EL0 only at EL1", 1, { cpacr: 1 }, "fmov d0, x1\n    fmov x2, d0"],
    ["load from a hole", 1, {}, `mov x1, #${HOLE}\n    ldr x0, [x1]`],
    ["store to a hole", 1, {}, `mov x1, #${HOLE}\n    str x2, [x1, #8]`],
    ["load pair from a hole", 1, {}, `mov x1, #${HOLE}\n    ldp x2, x3, [x1]`],
    ["unaligned load (Device)", 1, {}, "add x1, x8, #3\n    ldr x0, [x1]"],
    ["unaligned store (Device)", 1, {}, "add x1, x8, #2\n    str w0, [x1]"],
    ["unaligned exclusive", 1, {}, "add x1, x8, #4\n    ldxr x0, [x1]"],
    ["unaligned acquire", 1, {}, "add x1, x8, #2\n    ldar w0, [x1]"],
    ["write-back then fault", 1, {}, `mov x1, #${HOLE}\n    ldr x0, [x1, #16]!`],
    ["PC alignment", 1, {}, "adr x1, 1f\n    add x1, x1, #2\n    br x1\n1:  nop"],
    ["instruction abort", 1, {}, `mov x1, #${HOLE}\n    blr x1`],
    ["SP alignment", 1, { sctlr_set: SA }, "mov x3, sp\n    add x2, x3, #8\n    mov sp, x2\n    ldr x0, [sp]\n    mov sp, x3", [1, 0x9a000000n]],
    ["illegal exception return", 1, {}, "adr x1, 1f\n    msr elr_el1, x1\n    mov x2, #0x9\n    msr spsr_el1, x2\n    eret\n1:  add x0, x0, #1"],
    ["svc on SP0", 1, {}, "msr spsel, #0\n    svc #0x7\n    msr spsel, #1"],
    ["undef on SP0", 1, {}, "msr spsel, #0\n    udf #1\n    msr spsel, #1"],
    ["drps", 1, {}, ".inst 0xd6bf03e0"],
    ["dcps1", 1, {}, ".inst 0xd4a00001"],
    ["flags and svc", 1, {}, "cmp x0, x1\n    svc #0x9"],
    // EL0
    ["EL0: EL1 register", 0, {}, "mrs x0, sctlr_el1"],
    ["EL0: CTR_EL0 trapped", 0, { sctlr_clear: UCT }, "mrs x0, ctr_el0"],
    // (L1Ip differs by the allowed list: the profile's PIPT, the reference's VIPT)
    ["EL0: CTR_EL0 allowed", 0, { sctlr_set: UCT }, "mrs x0, ctr_el0\n    bic x0, x0, #0xC000"],
    ["EL0: DCZID allowed", 0, {}, "mrs x0, dczid_el0"],
    ["EL0: DC ZVA trapped", 0, { sctlr_clear: DZE }, "dc zva, x8"],
    ["EL0: DAIF trapped", 0, { sctlr_clear: UMA }, "msr daifset, #2", [3, 0x620cd3e4n]],
    ["EL0: DAIF read trapped", 0, { sctlr_clear: UMA }, "mrs x0, daif"],
    ["EL0: DAIF allowed", 0, { sctlr_set: UMA }, "mrs x0, daif"],
    ["EL0: WFI trapped", 0, { sctlr_clear: NTWI }, "wfi"],
    // (the ERET into EL0 set the event register: the first WFE consumes it, the second would wait and traps)
    ["EL0: WFE trapped", 0, { sctlr_clear: NTWE }, "wfe\n    wfe", [3, 0x07e00001n]],
    ["EL0: FP trapped", 0, { cpacr: 1 }, "fmov d0, x1"],
    ["EL0: FP off", 0, { cpacr: 0 }, "fmov d0, x1"],
    ["EL0: SVC", 0, {}, "svc #7"],
    ["EL0: HVC", 0, {}, "hvc #0"],
    ["EL0: SMC", 0, {}, "smc #0"],
    ["EL0: BRK", 0, {}, "brk #1"],
    ["EL0: load from a hole", 0, {}, `mov x1, #${HOLE}\n    ldr x0, [x1]`],
    ["EL0: PC alignment", 0, {}, "adr x1, 1f\n    add x1, x1, #1\n    br x1\n1:  nop"],
    ["EL0: instruction abort", 0, {}, `mov x1, #${HOLE}\n    br x1`],
    ["EL0: DC CIVAC trapped", 0, { sctlr_clear: UCI }, "dc civac, x8"],
    ["EL0: DC CIVAC allowed", 0, { sctlr_set: UCI }, "dc civac, x8"],
    ["EL0: IC IVAU trapped", 0, { sctlr_clear: UCI }, "ic ivau, x8"],
    ["EL0: CNTVCT trapped", 0, { cntkctl: 0 }, "mrs x0, cntvct_el0\n    mov x0, #1"],
    ["EL0: CNTFRQ allowed", 0, { cntkctl: 2 }, "mrs x0, cntfrq_el0"],
    ["EL0: CNTP_CTL trapped", 0, { cntkctl: 3 }, "mrs x0, cntp_ctl_el0"],
    ["EL0: SP alignment", 0, { sctlr_set: SA0 }, "mov x3, #0x4080\n    movk x3, #0x4060, lsl #16\n    add x3, x3, #4\n    mov sp, x3\n    ldr x0, [sp]", [3, 0x9a000000n]],
    ["EL0: MSR SPSel", 0, {}, "msr spsel, #1"],
    ["EL0: unaligned exclusive", 0, {}, "add x1, x8, #1\n    ldaxr w0, [x1]"],
];

// one entry per case and round: its random registers
const runs = [];
for(let round = 0; round < ROUNDS; round++)
{
    for(const [name, level, setup, body, v86_only] of CASES)
    {
        runs.push({ name, level, setup, body, v86_only, x: Array.from({ length: 8 }, next64), nzcv: next64() & 0xF0000000n });
    }
}

// record (88 bytes): taken (1 current SPx, 2 current SP0, 3 lower), ESR, FAR, ELR, SPSR, X0-X7 at the exception, NZCV after
function guest()
{
    const L = [".text", ".balign 4", ".global run_cases", "run_cases:",
        "    stp x29, x30, [sp, #-96]!", "    stp x19, x20, [sp, #16]", "    stp x21, x22, [sp, #32]", "    stp x23, x24, [sp, #48]",
        "    stp x25, x26, [sp, #64]", "    stp x27, x28, [sp, #80]",
        "    mrs x27, vbar_el1", "    mrs x26, sctlr_el1", "    mrs x25, cpacr_el1", "    mov x19, sp",
        "    adr x1, sys_vectors", "    msr vbar_el1, x1", "    isb"];
    runs.forEach((r, n) => {
        const sctlr_clear = r.setup.sctlr_clear ?? 0n, sctlr_set = r.setup.sctlr_set ?? 0n;
        const cpacr = r.setup.cpacr === undefined ? 3n << 20n : BigInt(r.setup.cpacr) << 20n;
        const cntkctl = BigInt(r.setup.cntkctl ?? 0);
        L.push(`// case ${n}: ${r.name}`,
            `    adrp x20, record_${n}`, `    add x20, x20, :lo12:record_${n}`, `    adr x21, done_${n}`,
            // (EL0 cases: everything allowed but what the case clears)
            `    ldr x1, =${hex(sctlr_clear)}`, `    ldr x2, =${hex(sctlr_set | (r.level === 0 ? ALL_EL0 & ~sctlr_clear : 0n))}`,
            "    bic x1, x26, x1", "    orr x1, x1, x2", "    msr sctlr_el1, x1",
            `    ldr x1, =${hex(cpacr)}`, "    msr cpacr_el1, x1", `    ldr x1, =${hex(cntkctl)}`, "    msr cntkctl_el1, x1", "    isb",
            `    adrp x8, scratch_${n}`, `    add x8, x8, :lo12:scratch_${n}`, `    adrp x9, regs_${n}`, `    add x9, x9, :lo12:regs_${n}`,
            "    ldr x10, [x9, #64]", "    msr nzcv, x10",
            "    ldp x0, x1, [x9]", "    ldp x2, x3, [x9, #16]", "    ldp x4, x5, [x9, #32]", "    ldp x6, x7, [x9, #48]");
        if(r.level === 0)
        {
            L.push(`    adr x10, el0_${n}`, "    msr elr_el1, x10", "    ldr x10, [x9, #64]", "    msr spsr_el1, x10", "    eret",
                `el0_${n}:`, "    " + r.body, "    svc #0xFFFF");
        }
        else
        {
            L.push("    " + r.body, "    svc #0xFFFF");
        }
        L.push(`done_${n}:`, "    mov sp, x19", "    msr sctlr_el1, x26", "    msr cpacr_el1, x25", "    msr cntkctl_el1, xzr", "    isb",
            "    mrs x10, nzcv", "    str x10, [x20, #104]");
    });
    L.push("    msr vbar_el1, x27", "    isb", "    mov sp, x19",
        "    ldp x19, x20, [sp, #16]", "    ldp x21, x22, [sp, #32]", "    ldp x23, x24, [sp, #48]", "    ldp x25, x26, [sp, #64]",
        "    ldp x27, x28, [sp, #80]", "    ldp x29, x30, [sp], #96", "    ret", ".ltorg");
    // the vectors: record and return to x21 at EL1h, the record's "taken" says which vector
    const handler = kind => [
        "    stp x0, x1, [x20, #40]", "    stp x2, x3, [x20, #56]", "    stp x4, x5, [x20, #72]", "    stp x6, x7, [x20, #88]",
        "    mrs x0, esr_el1", "    str x0, [x20, #8]",
        // (FAR where the class defines it: aborts, PC alignment)
        "    lsr x1, x0, #26", "    mov x2, xzr", "    cmp x1, #0x20", "    b.lo 8f", "    cmp x1, #0x25", "    b.hi 8f", "    cmp x1, #0x23", "    b.eq 8f",
        "    mrs x2, far_el1", "8:  str x2, [x20, #16]",
        "    mrs x0, elr_el1", "    str x0, [x20, #24]", "    mrs x0, spsr_el1", "    str x0, [x20, #32]",
        // (the end marker, SVC #0xFFFF: ESR 0x5600FFFF, is no fault)
        "    mrs x0, esr_el1", "    mov x1, #0xFFFF", "    movk x1, #0x5600, lsl #16", "    cmp x0, x1", "    b.eq 9f",
        `    mov x0, #${kind}`, "    str x0, [x20]",
        "9:  msr elr_el1, x21", "    mov x0, #0x3c5", "    msr spsr_el1, x0", "    eret"];
    // (each vector branches to its handler: 0x000 current EL with SP0, 0x200 with SPx, 0x400 a lower EL)
    L.push(".balign 2048", "sys_vectors:", "    b sync_sp0", ".balign 0x200", "    b sync_spx", ".balign 0x200", "    b sync_lower",
        ".balign 0x800", "sync_sp0:", ...handler(2), "sync_spx:", ...handler(1), "sync_lower:", ...handler(3));
    L.push(".data", ".balign 64");
    runs.forEach((r, n) => {
        L.push(`regs_${n}:`, ...r.x.map(v => `    .quad ${hex(v)}`), `    .quad ${hex(r.nzcv)}`, ".balign 64",
            `scratch_${n}:`, "    .zero 64", `record_${n}:`, "    .zero 112", ".balign 64");
    });
    L.push(".text", ".global case_records", ".balign 8", "case_records:");
    runs.forEach((_, n) => L.push(`    .quad record_${n}`));
    return L.join("\n") + "\n";
}

const MAIN = `#include <a64.h>
#include <stdio.h>
void run_cases(void);
extern const unsigned long case_records[];
int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    run_cases();
    for(int i = 0; i < ${runs.length}; i++)
    {
        const unsigned long *r = (const unsigned long *)case_records[i];
        printf("%d", i);
        for(int k = 0; k < 14; k++) printf(" %lx", r[k]);
        printf("\\n");
    }
    return 0;
}
`;

const NAMES = ["taken", "esr", "far", "elr", "spsr", "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "nzcv"];
const directory_base = root + "build/a64-system-oracle/";
fs.mkdirSync(directory_base, { recursive: true });
fs.writeFileSync(directory_base + "cases.S", guest());
fs.writeFileSync(directory_base + "main.c", MAIN);
const directory = build("system-oracle", [directory_base + "cases.S", directory_base + "main.c"]);
const expected = await reference(directory, { timeout: 120000 });
assert.equal(expected.status, "ok", "QEMU: " + expected.status + " " + expected.text.slice(-500));
const got = await actual(directory, { timeout: 300000 });
assert.equal(got.status, "ok", "v86: " + got.status + " " + got.text.slice(-500));
const want = expected.text.trim().split("\n"), have = got.text.trim().split("\n");
assert.equal(have.length, want.length, "line count");
let differences = 0;
const kinds = new Set();
for(let i = 0; i < want.length; i++)
{
    const w = want[i].split(" "), h = have[i].split(" ");
    if(w[1] !== "0") kinds.add(BigInt("0x" + w[2]) >> 26n);
    if(runs[i].v86_only)
    {
        // (the reference deviates here: v86 against the architecture's syndrome)
        const [taken, esr] = runs[i].v86_only;
        if(+h[1] === taken && BigInt("0x" + h[2]) === esr) continue;
        differences++;
        console.log(`DIFF ${runs[i].name} (EL${runs[i].level}): v86 taken ${h[1]} esr ${h[2]}, the architecture ${taken} ${esr.toString(16)}`);
        continue;
    }
    if(want[i] === have[i]) continue;
    differences++;
    const fields = w.slice(1).map((value, k) => value === h[k + 1] ? null : `${NAMES[k]} qemu ${value} v86 ${h[k + 1]}`).filter(Boolean);
    console.log(`DIFF ${runs[i].name} (EL${runs[i].level}): ${fields.join(", ")}`);
}
console.log(`system oracle: ${want.length} fault points (${CASES.length} cases x ${ROUNDS}, ` +
    `exception classes ${[...kinds].sort((a, b) => Number(a - b)).map(k => "0x" + k.toString(16)).join(" ")}), ${differences} differences`);
process.exit(differences ? 1 : 0);
                                                                                             source/v64/tests/a64/trace_replay.mjs                                                               0000644 0000000 0000000 00000040410 00000000000 014604  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The Alpine corpus and trace differential (docs/arm64-virt-android16-plan.md
// P2.10). The plan's qemu-aarch64 (user mode) does not exist on macOS, so
// the reference is qemu-system-aarch64 running the initramfs stage of
// tests/a64/linux_boot.mjs with its workload (A64_WORKLOAD: busybox and musl
// at work, after the probe) under -icount, with the plugin
// tools/a64_qemu/trace_sample.c: it samples instructions run at EL0 (one in
// --period on average, so the sample follows how often each encoding runs),
// with the registers before and after and every memory value read or
// written, and collects the corpus of translated instruction words.
//
// Each sample is replayed on v86's ARM core at EL0: the code page and the
// pages the instruction touched are mapped at their addresses (48-bit VAs,
// 4 KiB pages, tables built here), the values read are in memory, the
// registers are the sample's; after one step the registers (X0-X30, SP, PC,
// NZCV, FPCR, FPSR, TPIDR_EL0, and V0-V31 for the FP/SIMD and branch
// classes) and every byte written must be what the reference had. Left out
// (the state they depend on is not in a sample, or the allowed list covers
// them): store-exclusives (the monitor), reads of the counters and CTR_EL0,
// DC ZVA (QEMU reports no writes for it).
//
// The corpus: every word translated (EL1 too) must decode on v86 as
// llvm-mc decodes it for profile v1 (tests/a64/decode_check.mjs --words).
//
//   node tests/a64/trace_replay.mjs [--samples N] [--period N] [--workload N] [--seed S]
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { root, QEMU_MACHINE, QEMU_CPU, qemu_binary } from "./guest_runner.mjs";
import { STATE_OFFSETS } from "../../src/arm/state_layout.js";

const args = process.argv.slice(2);
const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
const SAMPLES = +option("--samples", 10_000_000);
const PERIOD = +option("--period", 24);
const WORKLOAD = +option("--workload", 40);
const SEED = +option("--seed", 1);

const directory = root + "build/a64-trace/";
fs.mkdirSync(directory, { recursive: true });
function run(program, program_args, options = {})
{
    const result = spawnSync(program, program_args, { encoding: "utf8", ...options });
    assert.equal(result.status, 0, `${program} ${program_args.join(" ")}\n${result.stdout}${result.stderr}`);
    return result.stdout.trim();
}

// ---- the plugin and the guest's files
const qemu = qemu_binary();
const qemu_source = root + "build/a64-ref/qemu-9.2.0/";
const plugin = directory + "trace_sample.dylib";
run(process.env.CLANG || "clang", ["-O2", "-fPIC", "-bundle", "-Wl,-undefined,dynamic_lookup", "-Wall",
    ...run("pkg-config", ["--cflags", "glib-2.0"]).split(/\s+/), "-I", qemu_source + "include/qemu",
    "-o", plugin, root + "tools/a64_qemu/trace_sample.c", ...run("pkg-config", ["--libs", "glib-2.0"]).split(/\s+/)]);
run("node", [root + "tests/a64/linux_boot.mjs"], { env: { ...process.env, A64_LINUX_PREPARE_ONLY: "1" } });
const linux = root + "build/a64-linux/";
const fifo = directory + "samples.fifo";
fs.rmSync(fifo, { force: true });
run("mkfifo", [fifo]);
const corpus = directory + "corpus.txt";

const child = spawn(qemu, ["-machine", QEMU_MACHINE, "-cpu", QEMU_CPU, "-m", "512M", "-smp", "1",
    "-global", "virtio-mmio.force-legacy=false", "-display", "none", "-no-reboot", "-monitor", "none",
    "-serial", "file:" + directory + "serial.txt", "-icount", "shift=0,sleep=off",
    "-kernel", linux + "boot/vmlinuz-virt", "-initrd", linux + "probe/initramfs-virt+probe.cpio",
    "-append", `console=ttyAMA0 earlycon nokaslr panic=-1 A64_WORKLOAD=${WORKLOAD} rdinit=/a64-init -- ref=qemu`,
    "-plugin", `${plugin},out=${fifo},corpus=${corpus},period=${PERIOD},seed=${SEED},limit=${SAMPLES}`],
    { stdio: ["ignore", "inherit", "pipe"] });
let qemu_errors = "";
child.stderr.on("data", data => { qemu_errors += data; });
process.on("exit", () => child.exitCode === null && child.kill("SIGKILL"));
for(const [signal, status] of [["SIGINT", 130], ["SIGTERM", 143]]) process.once(signal, () => process.exit(status));
const exited = new Promise(resolve => child.on("exit", resolve));

// ---- v86's ARM core, as an EL0 harness
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const RAM = 0x40000000, RAM_SIZE = 256 << 20;
const emulator = new V86({ cpu_type: "arm64", graphics_adapter: "none", memory_size: RAM_SIZE, autostart: false, log_level: 0,
    wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm" });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu, exports = cpu.wm.exports;
exports["a64_boot"](RAM, 0, 0, 0);
// (guest RAM directly: cpu.mem8 is a checked view; the ARM core's memory does not grow)
const mem8 = new Uint8Array(cpu.wasm_memory.buffer, cpu.mem8.byteOffset, RAM_SIZE);
const ram = new DataView(mem8.buffer, mem8.byteOffset, mem8.byteLength);
let state_view, state_bytes;
function attach_state()
{
    state_view = new DataView(cpu.wasm_memory.buffer, cpu.state_base, 4096);
    state_bytes = new Uint8Array(cpu.wasm_memory.buffer, cpu.state_base, 4096);
}
attach_state();
const set64 = (offset, value) => state_view.setBigUint64(offset, value, true);
// (the bytes a sample's stores wrote: their physical addresses and values)
const write_pa = new Float64Array(4096), write_value = new Uint8Array(4096);

// the regime: Linux's for EL0 (TBI0, 16-bit ASIDs, 4 KiB pages, 48-bit VAs; UCT, DZE, UCI, nTWI, nTWE, SA0)
const SCTLR = 0x00C50838n | 1n | 1n << 2n | 1n << 12n | 1n << 4n | 1n << 3n | 1n << 15n | 1n << 14n | 1n << 26n | 1n << 16n | 1n << 18n;
const TCR = 16n | 1n << 8n | 1n << 10n | 3n << 12n | 16n << 16n | 1n << 23n | 2n << 32n | 1n << 36n | 1n << 37n;
// pages for tables and for the guest's pages (the first 1 MiB of RAM holds nothing)
const POOL = RAM + 0x100000, POOL_PAGES = (RAM_SIZE - 0x100000) / 4096;
let next_page, root_table;
const mapped = new Map();
function allocate()
{
    const pa = POOL + 4096 * next_page++;
    mem8.fill(0, pa - RAM, pa - RAM + 4096);
    return pa;
}
function reset_tables()
{
    next_page = 0;
    mapped.clear();
    root_table = allocate();
    set64(STATE_OFFSETS.ttbr0_el1, BigInt(root_table));
    exports["a64_restored"](); // (the TLBs flushed)
}
/** The physical address of VA page `page` (va >> 12), mapped now if it was not */
function page_pa(page)
{
    let pa = mapped.get(page);
    if(pa !== undefined) return pa;
    assert.ok(next_page + 4 <= POOL_PAGES, "the page pool");
    let table = root_table;
    for(let level = 0; level < 3; level++)
    {
        const index = Math.floor(page / 2 ** (27 - 9 * level)) % 512;
        const at = table - RAM + 8 * index;
        let entry = ram.getBigUint64(at, true);
        if(!(entry & 1n))
        {
            entry = BigInt(allocate()) | 3n;
            ram.setBigUint64(at, entry, true);
        }
        table = Number(entry & 0xFFFFFFFFF000n);
    }
    pa = allocate();
    // a page: AttrIndx 0 (normal), EL0 and EL1 read/write, inner shareable, AF
    ram.setBigUint64(table - RAM + 8 * (page & 511), BigInt(pa) | 3n | 1n << 6n | 3n << 8n | 1n << 10n, true);
    mapped.set(page, pa);
    return pa;
}
function setup_regime()
{
    set64(STATE_OFFSETS.sctlr_el1, SCTLR);
    set64(STATE_OFFSETS.tcr_el1, TCR);
    set64(STATE_OFFSETS.mair_el1, 0xFFn);
    set64(STATE_OFFSETS.cpacr_el1, 3n << 20n);
    set64(STATE_OFFSETS.cntkctl_el1, 2n);
    set64(STATE_OFFSETS.vbar_el1, BigInt(RAM));
    reset_tables();
}
setup_regime();

// ---- the samples
const NAMED = 38, HEADER = 16, REGS = NAMED * 8, VECTORS = 32 * 16, ACCESS = 32;
const R_SP = 31, R_PC = 32, R_CPSR = 33, R_FPSR = 34, R_FPCR = 35, R_TPIDR = 36, R_TPIDRRO = 37;

/** Words whose result depends on state a sample does not carry, or the allowed list */
function left_out(word)
{
    if((word & 0x3FC00000) >>> 0 === 0x08000000) return "store-exclusive"; // STXR, STLXR, STXP, STLXP (o2 0, L 0)
    const mrs = (word & 0xFFF00000) >>> 0 === 0xD5300000 ? (word & 0xFFFE0) >>> 0 : -1;
    if(mrs === 0xBE040 || mrs === 0xBE020 || mrs === 0xBE0C0 || mrs === 0xBE0A0) return "counter"; // CNTVCT, CNTPCT (and the SS forms)
    if(mrs === 0xB0020) return "CTR_EL0";
    if((word & 0xFFFFFFE0) >>> 0 === 0xD50B7420) return "DC ZVA";
    return null;
}

const stats = { samples: 0, replayed: 0, left_out: {}, differences: 0, words: new Set() };
const examples = [];
function difference(word, what)
{
    stats.differences++;
    if(examples.length < 40)
    {
        examples.push(`${(word >>> 0).toString(16).padStart(8, "0")}: ${what}`);
        console.log("DIFF " + examples.at(-1));
    }
}

const hex64 = (bytes, at) => Buffer.from(bytes.subarray(at, at + 8)).reverse().toString("hex").replace(/^0{1,15}/, "");

function replay(buffer, at)
{
    const view = new DataView(buffer.buffer, buffer.byteOffset + at);
    const bytes = buffer.subarray(at);
    const word = view.getUint32(4, true), accesses = view.getUint32(8, true), vectors = view.getUint32(12, true) & 1;
    const block = REGS + (vectors ? VECTORS : 0);
    const before = HEADER, after = HEADER + block, memory = HEADER + 2 * block;
    stats.samples++;
    const excluded = left_out(word);
    if(excluded)
    {
        stats.left_out[excluded] = (stats.left_out[excluded] || 0) + 1;
        return;
    }
    stats.words.add(word);
    if(state_bytes.byteLength === 0) attach_state();
    // (a fresh set of tables when the pool runs low: never within a sample)
    if(next_page + 4 * (2 + 2 * accesses) + 8 > POOL_PAGES) reset_tables();
    // the code page and the instruction
    const pc_low = view.getUint32(before + 8 * R_PC, true), pc_high = view.getUint32(before + 8 * R_PC + 4, true);
    const code = page_pa(pc_high * 0x100000 + (pc_low >>> 12));
    ram.setUint32(code - RAM + (pc_low & 0xFFF), word, true);
    // the memory read (in place before) and written (checked after); TBI: the top byte is no part of the address
    let writes = 0;
    for(let k = 0; k < accesses; k++)
    {
        const a = memory + ACCESS * k;
        const low = view.getUint32(a, true), high = view.getUint32(a + 4, true) & 0xFFFFFF;
        const size = view.getUint32(a + 24, true), store = view.getUint32(a + 28, true);
        for(let b = 0; b < size; b++)
        {
            const offset = low + b; // (no carry out of the low word can matter: accesses stay below 2^32 - 16 of a page)
            const page = (high + (offset >= 0x100000000 ? 1 : 0)) * 0x100000 + ((offset >>> 12) & 0xFFFFF);
            const pa = page_pa(page) + (offset & 0xFFF);
            if(store)
            {
                write_pa[writes] = pa;
                write_value[writes++] = bytes[a + 8 + b];
            }
            else
            {
                mem8[pa - RAM] = bytes[a + 8 + b];
            }
        }
    }
    // the registers: X0-X30 and SP in the record's order are the state block's x[0..31]; V0-V31 likewise
    state_bytes.set(bytes.subarray(before, before + 256), STATE_OFFSETS.x);
    state_bytes.set(bytes.subarray(before + 8 * R_PC, before + 8 * R_PC + 8), STATE_OFFSETS.pc);
    const cpsr = view.getUint32(before + 8 * R_CPSR, true);
    state_view.setUint32(STATE_OFFSETS.nzcv, cpsr & 0xF0000000, true);
    state_view.setUint32(STATE_OFFSETS.pstate, cpsr & 0x3C0, true);
    state_view.setUint32(STATE_OFFSETS.fpcr, view.getUint32(before + 8 * R_FPCR, true), true);
    state_view.setUint32(STATE_OFFSETS.fpsr, view.getUint32(before + 8 * R_FPSR, true), true);
    state_bytes.set(bytes.subarray(before + 8 * R_TPIDR, before + 8 * R_TPIDR + 16), STATE_OFFSETS.tpidr_el0);
    if(vectors) state_bytes.set(bytes.subarray(before + REGS, before + REGS + VECTORS), STATE_OFFSETS.v);
    exports["a64_step"]();
    stats.replayed++;
    if(state_bytes.byteLength === 0) attach_state();
    // the registers after
    const pstate = state_view.getUint32(STATE_OFFSETS.pstate, true);
    if(pstate >> 2 & 3)
    {
        difference(word, `took an exception to EL1: ESR ${hex64(state_bytes, STATE_OFFSETS.esr_el1)}, FAR ${hex64(state_bytes, STATE_OFFSETS.far_el1)}` +
            `, at ${hex64(bytes, before + 8 * R_PC)}`);
        return;
    }
    const same = (offset, record, length) => {
        for(let i = 0; i < length; i++) if(state_bytes[offset + i] !== bytes[record + i]) return false;
        return true;
    };
    let problems = null;
    const problem = text => (problems ||= []).push(text);
    for(let i = 0; i < 32; i++)
    {
        if(!same(STATE_OFFSETS.x + 8 * i, after + 8 * i, 8))
        {
            problem(`${i === 31 ? "sp" : "x" + i} ${hex64(state_bytes, STATE_OFFSETS.x + 8 * i)} want ${hex64(bytes, after + 8 * i)}`);
        }
    }
    if(!same(STATE_OFFSETS.pc, after + 8 * R_PC, 8)) problem(`pc ${hex64(state_bytes, STATE_OFFSETS.pc)} want ${hex64(bytes, after + 8 * R_PC)}`);
    const nzcv = state_view.getUint32(STATE_OFFSETS.nzcv, true) >>> 0, want_nzcv = (view.getUint32(after + 8 * R_CPSR, true) & 0xF0000000) >>> 0;
    if(nzcv !== want_nzcv) problem(`nzcv ${nzcv.toString(16)} want ${want_nzcv.toString(16)}`);
    for(const [name, offset, record] of [["fpcr", STATE_OFFSETS.fpcr, R_FPCR], ["fpsr", STATE_OFFSETS.fpsr, R_FPSR]])
    {
        const have = state_view.getUint32(offset, true) >>> 0, want = view.getUint32(after + 8 * record, true) >>> 0;
        if(have !== want) problem(`${name} ${have.toString(16)} want ${want.toString(16)}`);
    }
    if(!same(STATE_OFFSETS.tpidr_el0, after + 8 * R_TPIDR, 8)) problem(`tpidr_el0 ${hex64(state_bytes, STATE_OFFSETS.tpidr_el0)} want ${hex64(bytes, after + 8 * R_TPIDR)}`);
    if(vectors)
    {
        for(let i = 0; i < 32; i++)
        {
            if(!same(STATE_OFFSETS.v + 16 * i, after + REGS + 16 * i, 16))
            {
                problem(`v${i} ${hex64(state_bytes, STATE_OFFSETS.v + 16 * i + 8)}:${hex64(state_bytes, STATE_OFFSETS.v + 16 * i)} ` +
                    `want ${hex64(bytes, after + REGS + 16 * i + 8)}:${hex64(bytes, after + REGS + 16 * i)}`);
            }
        }
    }
    for(let k = 0; k < writes; k++)
    {
        if(mem8[write_pa[k] - RAM] !== write_value[k]) problem(`byte at pa ${write_pa[k].toString(16)}: ${mem8[write_pa[k] - RAM]} want ${write_value[k]}`);
    }
    if(problems) difference(word, `at ${hex64(bytes, before + 8 * R_PC)}: ` + problems.slice(0, 6).join(", "));
}

// the records from the FIFO, as they come (QEMU waits while this falls behind)
const started = performance.now();
let pending = Buffer.alloc(0), reported = 0;
for await (const chunk of fs.createReadStream(fifo, { highWaterMark: 1 << 22 }))
{
    let buffer = pending.length ? Buffer.concat([pending, chunk]) : chunk;
    let at = 0;
    for(;;)
    {
        if(buffer.length - at < HEADER) break;
        assert.equal(buffer.readUInt32LE(at), 0x53343641, "record magic at " + at);
        const vectors = buffer.readUInt32LE(at + 12) & 1;
        const size = HEADER + 2 * (REGS + (vectors ? VECTORS : 0)) + ACCESS * buffer.readUInt32LE(at + 8);
        if(buffer.length - at < size) break;
        replay(buffer, at);
        at += size;
    }
    pending = buffer.subarray(at);
    if(stats.samples - reported >= 1000000)
    {
        reported = stats.samples;
        console.log(`${stats.samples} samples, ${stats.differences} differences, ${((performance.now() - started) / 1000).toFixed(0)} s`);
    }
}
const code = await exited;
await emulator.destroy();
const serial = fs.readFileSync(directory + "serial.txt", "latin1");
assert.ok(/A64_WORKLOAD_END/.test(serial), "the workload ran to its end on the reference");
assert.equal(code, 0, "QEMU: " + qemu_errors);
const summary = qemu_errors.match(/trace_sample: .*/)?.[0] || "";
console.log(`trace replay: ${stats.samples} samples (${stats.replayed} replayed, ${stats.words.size} distinct words; left out ` +
    `${JSON.stringify(stats.left_out)}), ${stats.differences} differences, ${((performance.now() - started) / 1000).toFixed(0)} s; ${summary}`);
assert.ok(stats.samples >= SAMPLES || !SAMPLES, `only ${stats.samples} samples: a larger --workload`);

// ---- the corpus
const check = spawnSync("node", [root + "tests/a64/decode_check.mjs", "--words", corpus], { encoding: "utf8" });
console.log(check.stdout.trim().split("\n").slice(-8).join("\n"));
assert.equal(check.status, 0, "the corpus decodes on v86 as on llvm-mc");
assert.equal(stats.differences, 0, "trace replay differences");
console.log("trace replay: passed");
                                                                                                                                                                                                                                                        source/v64/tests/a64/uffd_test.c                                                                    0000644 0000000 0000000 00000007476 00000000000 013565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* userfaultfd on the androidish kernel (docs/arm64-virt-android16-plan.md
 * P9.2; ART's concurrent compaction uses it): a region registered for
 * missing-page faults, PAGES pages touched by a thread on another CPU, each
 * fault served by UFFDIO_COPY of a page whose words name it, the contents
 * checked; then UFFDIO_ZEROPAGE for one more page. Built by
 * tools/a64_kernel.mjs with Alpine's GCC and musl.
 *
 *   uffd_test [pages]
 *
 * A64_UFFD_OK faults=N on success, A64_UFFD_FAIL <why> else. */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/userfaultfd.h>

static long page;
static int pages = 64;
static uint8_t *region;
static volatile int done;

static void fail(const char *what)
{
    printf("A64_UFFD_FAIL %s (errno %d)\n", what, errno);
    exit(1);
}

static void pin(int cpu)
{
    cpu_set_t set;
    CPU_ZERO(&set);
    CPU_SET(cpu, &set);
    sched_setaffinity(0, sizeof(set), &set);
}

static void *toucher(void *arg)
{
    (void)arg;
    pin((int)(sysconf(_SC_NPROCESSORS_ONLN) - 1));
    uint64_t sum = 0;
    for(int p = 0; p < pages; p++)
    {
        uint64_t *words = (uint64_t *)(region + p * page);
        for(long w = 0; w < page / 8; w += 64) sum += words[w] == ((uint64_t)p << 32 | (uint64_t)w) ? 0 : 1;
    }
    done = 1;
    return (void *)(uintptr_t)sum;
}

int main(int argc, char **argv)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    if(argc > 1) pages = atoi(argv[1]);
    page = sysconf(_SC_PAGESIZE);
    pin(0);
    int uffd = (int)syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK);
    if(uffd < 0) fail("userfaultfd");
    struct uffdio_api api = { .api = UFFD_API, .features = 0 };
    if(ioctl(uffd, UFFDIO_API, &api) < 0) fail("UFFDIO_API");
    region = mmap(NULL, (pages + 1) * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if(region == MAP_FAILED) fail("mmap");
    struct uffdio_register reg = {
        .range = { .start = (uintptr_t)region, .len = (pages + 1) * page }, .mode = UFFDIO_REGISTER_MODE_MISSING,
    };
    if(ioctl(uffd, UFFDIO_REGISTER, &reg) < 0) fail("UFFDIO_REGISTER");
    uint64_t *source = aligned_alloc(page, page);
    pthread_t thread;
    if(pthread_create(&thread, NULL, toucher, NULL) != 0) fail("pthread_create");
    int faults = 0;
    while(!done)
    {
        struct pollfd pfd = { .fd = uffd, .events = POLLIN };
        int ready = poll(&pfd, 1, 2000);
        if(ready < 0) fail("poll");
        if(ready == 0) { if(done) break; fail("no fault in 2 s"); }
        struct uffd_msg msg;
        ssize_t n = read(uffd, &msg, sizeof(msg));
        if(n < 0 && errno == EAGAIN) continue;
        if(n != sizeof(msg)) fail("read");
        if(msg.event != UFFD_EVENT_PAGEFAULT) fail("event");
        uintptr_t address = (uintptr_t)msg.arg.pagefault.address & ~(uintptr_t)(page - 1);
        long p = (long)(address - (uintptr_t)region) / page;
        for(long w = 0; w < page / 8; w++) source[w] = (uint64_t)p << 32 | (uint64_t)w;
        struct uffdio_copy copy = { .dst = address, .src = (uintptr_t)source, .len = page, .mode = 0 };
        if(ioctl(uffd, UFFDIO_COPY, &copy) < 0 && errno != EEXIST) fail("UFFDIO_COPY");
        faults++;
    }
    void *result;
    pthread_join(thread, &result);
    if(result != NULL) fail("contents");
    struct uffdio_zeropage zero = { .range = { .start = (uintptr_t)region + pages * page, .len = page }, .mode = 0 };
    if(ioctl(uffd, UFFDIO_ZEROPAGE, &zero) < 0) fail("UFFDIO_ZEROPAGE");
    for(long b = 0; b < page; b++) if(region[pages * page + b]) fail("zero page");
    if(faults != pages) fail("fault count");
    printf("A64_UFFD_OK faults=%d page=%ld\n", faults, page);
    return 0;
}
                                                                                                                                                                                                  source/v64/tests/a64/vector_oracle.mjs                                                              0000644 0000000 0000000 00000045457 00000000000 015001  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Scalar FP, AdvSIMD, crypto and the SIMD&FP loads and stores of the A64
// interpreter against QEMU (docs/arm64-virt-android16-plan.md P2.5-P2.8,
// P2.11), the module behind tests/a64/simd_oracle.mjs, fp_oracle.mjs and
// crypto_oracle.mjs. Each case is one instruction
// word: random bits inside one class of the FP/SIMD encoding group that
// v86's decoder accepts (tests/a64/decode_check.mjs holds the decoder to
// llvm-mc), drawn so every mnemonic gets about the same share, registers
// limited to V0-V7 and X0-X9; or a SIMD&FP load or store on a 256-byte
// window (X8 points into it, X9 is an offset). V0-V7 start with random bits
// and special values (zeros, infinities, quiet and signaling NaNs,
// denormals, limits) in 32- and 64-bit lanes, X0-X7 random, NZCV random,
// FPCR random (RMode, FZ, DN, AHP), FPSR 0. The guest prints V0-V7, X0-X9,
// NZCV, FPSR and a checksum of the window per case; QEMU's lines and v86's
// must be equal.
//
// run({ name, classes, mnemonics, cases, seed, filter, fpcr, against }):
// `classes` the class names below (and "memory"), `mnemonics` only these,
// `filter` a class or mnemonic, `fpcr(n, round)` FPCR for case n, the
// round-th case of its mnemonic (default: random RMode, FZ, DN, AHP),
// `against` "qemu" (default) or "native": the same cases assembled as a
// macOS arm64 program and run on the host (P2.12, an Apple M1 Pro here).
// A64_TARGET=qemu runs QEMU only (to check the generator).
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import { build, reference, actual, root } from "./guest_runner.mjs";

const BATCH = 400;
let rand, rand32, pick, next64;

/** The command line of the entry scripts: --cases N --seed S --filter F */
export function options(defaults)
{
    const args = process.argv.slice(2);
    const option = (name, value) => { const i = args.indexOf(name); return i < 0 ? value : args[i + 1]; };
    return { ...defaults, cases: +option("--cases", defaults.cases), seed: +option("--seed", defaults.seed || 1),
        filter: option("--filter", defaults.filter || null) };
}

const hex = v => "0x" + v.toString(16);

const F32 = [0x00000000n, 0x80000000n, 0x7F800000n, 0xFF800000n, 0x7FC00000n, 0xFFC00000n, 0x7F800001n, 0xFFA00001n,
    0x7FC12345n, 0x00000001n, 0x807FFFFFn, 0x00400000n, 0x00800000n, 0x80800000n, 0x3F800000n, 0xBF800000n, 0x7F7FFFFFn,
    0xFF7FFFFFn, 0x4B000000n, 0x3F000000n, 0x3FC00000n, 0x4F000000n, 0xCF000000n, 0x5F000000n, 0xDF000000n, 0x477FE000n,
    0x387FC000n, 0x33800000n, 0x40490FDBn, 0x4EFFFFFFn, 0x3EAAAAABn, 0x00200000n, 0x7E800000n];
const F64 = [0x0000000000000000n, 0x8000000000000000n, 0x7FF0000000000000n, 0xFFF0000000000000n, 0x7FF8000000000000n,
    0x7FF0000000000001n, 0xFFF4000000000001n, 0x7FF8123456789ABCn, 0x0000000000000001n, 0x800FFFFFFFFFFFFFn,
    0x0010000000000000n, 0x3FF0000000000000n, 0xBFF0000000000000n, 0x7FEFFFFFFFFFFFFFn, 0x4330000000000000n,
    0x3FE0000000000000n, 0x41E0000000000000n, 0xC1E0000000000000n, 0x43E0000000000000n, 0xC3E0000000000000n,
    0x400921FB54442D18n, 0x47EFFFFFE0000000n, 0x3810000000000000n, 0x36A0000000000000n, 0x0004000000000000n,
    0x7FD0000000000000n, 0x41DFFFFFFFC00000n];
function lane64()
{
    switch(rand(6))
    {
        case 0: return pick(F64);
        case 1: return pick(F32) | pick(F32) << 32n;
        case 2: return (next64() & 0x8000FFFFFFFFFFFFn) | BigInt(rand(4) + 0x3FE) << 52n;
        case 3: return BigInt(rand(256)) - 128n & (1n << 64n) - 1n;
        default: return next64();
    }
}
const vector = () => lane64() | lane64() << 64n;
const SPECIAL = [0n, 1n, 2n, 0xFFFFFFFFFFFFFFFFn, 0x7FFFFFFFFFFFFFFFn, 0x8000000000000000n, 0xFFFFFFFFn, 0x7FFFFFFFn,
    0x80000000n, 0x100000000n];
const xvalue = () => rand(3) ? next64() : pick(SPECIAL);

// ---- v86's decoder (the ARM core on its own)
const core = (() => {
    const module = new WebAssembly.Module(fs.readFileSync(process.env.A64_WASM || root + "build/v86-arm64.wasm"));
    const env = {};
    for(const { name, kind } of WebAssembly.Module.imports(module))
    {
        if(kind === "function") env[name] = () => 0n;
        if(kind === "table") env[name] = new WebAssembly.Table({ element: "anyfunc", initial: 13100 });
    }
    return new WebAssembly.Instance(module, { env }).exports;
})();
const mnemonic = word => {
    const at = core.a64_decode_mnemonic(word >>> 0) >>> 0;
    const bytes = new Uint8Array(core.memory.buffer, at, 16);
    return new TextDecoder().decode(bytes.subarray(0, bytes.indexOf(0)));
};

// ---- the classes (src/rust/aarch64/simd_decode.rs): mask, value, which fields are registers
const R = { d: 1, n: 2, m: 4, a: 8, table: 16, index: 32 };
const CLASSES = {
    aes: [0xFF3E0C00, 0x4E280800, R.d | R.n],
    table: [0xBF208C00, 0x0E000000, R.d | R.table | R.m],
    permute: [0xBF208C00, 0x0E000800, R.d | R.n | R.m],
    extract: [0xBF208400, 0x2E000000, R.d | R.n | R.m],
    copy: [0x9FE08400, 0x0E000400, R.d | R.n],
    three_same: [0x9F200400, 0x0E200400, R.d | R.n | R.m],
    three_different: [0x9F200C00, 0x0E200000, R.d | R.n | R.m],
    two_misc: [0x9F3E0C00, 0x0E200800, R.d | R.n],
    across: [0x9F3E0C00, 0x0E300800, R.d | R.n],
    modified_immediate: [0x9FF80400, 0x0F000400, R.d],
    shift_immediate: [0x9F800400, 0x0F000400, R.d | R.n],
    indexed: [0x9F000400, 0x0F000000, R.d | R.n | R.index],
    sha3: [0xFF208C00, 0x5E000000, R.d | R.n | R.m],
    sha2: [0xFF3E0C00, 0x5E280800, R.d | R.n],
    scalar_copy: [0xDFE08400, 0x5E000400, R.d | R.n],
    scalar_three_same: [0xDF200400, 0x5E200400, R.d | R.n | R.m],
    scalar_three_different: [0xDF200C00, 0x5E200000, R.d | R.n | R.m],
    scalar_two_misc: [0xDF3E0C00, 0x5E200800, R.d | R.n],
    scalar_pairwise: [0xDF3E0C00, 0x5E300800, R.d | R.n],
    scalar_shift_immediate: [0xDF800400, 0x5F000400, R.d | R.n],
    scalar_indexed: [0xDF000400, 0x5F000000, R.d | R.n | R.index],
    fp_fixed: [0x7F200000, 0x1E000000, R.d | R.n],
    fp_int: [0x7F20FC00, 0x1E200000, R.d | R.n],
    fp_dp1: [0xFF207C00, 0x1E204000, R.d | R.n],
    fp_compare: [0xFF203C00, 0x1E202000, R.n | R.m],
    fp_imm: [0xFF201FE0, 0x1E201000, R.d],
    fp_cond_compare: [0xFF200C00, 0x1E200400, R.n | R.m],
    fp_dp2: [0xFF200C00, 0x1E200800, R.d | R.n | R.m],
    fp_cond_select: [0xFF200C00, 0x1E200C00, R.d | R.n | R.m],
    fp_dp3: [0xFF000000, 0x1F000000, R.d | R.n | R.m | R.a],
    structure: [0xBE000000, 0x0C000000, 0],
};

function sanitize(word, regs)
{
    if(regs & R.d) word = word & ~0x1F | word & 7;
    if(regs & R.n) word = word & ~(0x1F << 5) | (word >>> 5 & 7) << 5;
    if(regs & R.table) word = word & ~(0x1F << 5) | (word >>> 5 & 3) << 5;
    if(regs & R.m) word = word & ~(0x1F << 16) | (word >>> 16 & 7) << 16;
    if(regs & R.a) word = word & ~(0x1F << 10) | (word >>> 10 & 7) << 10;
    if(regs & R.index)
    {
        // (Rm: bits 19:16; M, bit 20, is part of the index for 16-bit elements and of Rm otherwise)
        word = word & ~(0xF << 16) | (word >>> 16 & 7) << 16;
        if((word >>> 22 & 3) !== 1) word &= ~(1 << 20);
    }
    return word >>> 0;
}

/** A structure load or store: base X8, Rt 0-4 (four registers stay in V0-V7), Rm X9 or 31 */
function structure_word(word)
{
    word = word & ~0x3FF | 8 << 5 | rand(5);
    if(word >>> 23 & 1) word = word & ~(0x1F << 16) | (rand(2) ? 9 : 31) << 16;
    else word &= ~(0x1F << 16);
    return word >>> 0;
}

// the SIMD&FP register loads and stores, as assembly
const REG = ["b", "h", "s", "d", "q"];
/** Two different registers of a pair (a load of one register twice is CONSTRAINED UNPREDICTABLE) */
const pair = s => { const t = rand(8); return `${REG[s]}${t}, ${REG[s]}${(t + 1 + rand(7)) % 8}`; };
const MEMORY = [
    () => { const s = rand(5); return `${pick(["ldr", "str"])} ${REG[s]}${rand(8)}, [x8, #${(rand(8) << s)}]`; },
    () => { const s = rand(5); return `${pick(["ldur", "stur"])} ${REG[s]}${rand(8)}, [x8, #${-(rand(4) << s)}]`; },
    () => { const s = rand(5); return `${pick(["ldr", "str"])} ${REG[s]}${rand(8)}, [x8, #${(rand(4) << s) - (2 << s)}]!`; },
    () => { const s = rand(5); return `${pick(["ldr", "str"])} ${REG[s]}${rand(8)}, [x8], #${(rand(4) << s) - (2 << s)}`; },
    () => { const s = rand(5); return `${pick(["ldr", "str"])} ${REG[s]}${rand(8)}, [x8, x9${s ? pick(["", ", lsl #" + s]) : ""}]`; },
    () => { const s = 2 + rand(3); return `${pick(["ldp", "stp", "ldnp", "stnp"])} ${pair(s)}, [x8, #${(rand(4) << s) - (2 << s)}]`; },
    () => { const s = 2 + rand(3); return `${pick(["ldp", "stp"])} ${pair(s)}, [x8, #${(rand(3) << s) - (1 << s)}]!`; },
    () => { const s = 2 + rand(3); return `${pick(["ldp", "stp"])} ${pair(s)}, [x8], #${(rand(3) << s) - (1 << s)}`; },
    () => ({ literal: true, asm: `ldr ${pick(["s", "d", "q"])}${rand(8)}, LITERAL` }),
];
// ---- the guest of one batch (input: V0-V7 at 0, X0-X7 at 128, X9 at 192, NZCV 200, FPCR 208)
function guest(batch, first)
{
    const lines = [".text", ".balign 4", ".global run_cases", "run_cases:", "    stp x29, x30, [sp, #-96]!",
        "    stp x19, x20, [sp, #16]", "    stp x21, x22, [sp, #32]", "    stp x23, x24, [sp, #48]", "    stp x25, x26, [sp, #64]",
        "    stp x27, x28, [sp, #80]", "    stp d8, d9, [sp, #-64]!", "    stp d10, d11, [sp, #16]", "    stp d12, d13, [sp, #32]",
        "    stp d14, d15, [sp, #48]"];
    batch.forEach((c, i) => {
        const n = first + i;
        lines.push(`// case ${n}: ${c.key}`, `    adrp x28, input_${n}`, `    add x28, x28, :lo12:input_${n}`,
            "    ldr x16, [x28, #200]", "    msr nzcv, x16", "    ldr x16, [x28, #208]", "    msr fpcr, x16", "    msr fpsr, xzr");
        for(let r = 0; r < 8; r += 2) lines.push(`    ldp q${r}, q${r + 1}, [x28, #${16 * r}]`);
        for(let r = 0; r < 8; r += 2) lines.push(`    ldp x${r}, x${r + 1}, [x28, #${128 + 8 * r}]`);
        lines.push("    ldr x9, [x28, #192]", `    adrp x8, memory_${n}`, `    add x8, x8, :lo12:memory_${n}`, "    add x8, x8, #64");
        lines.push("    " + c.asm.replace("LITERAL", `literal_${n}`));
        lines.push(`    adrp x28, output_${n}`, `    add x28, x28, :lo12:output_${n}`);
        for(let r = 0; r < 8; r += 2) lines.push(`    stp q${r}, q${r + 1}, [x28, #${16 * r}]`);
        for(let r = 0; r < 10; r += 2) lines.push(`    stp x${r}, x${r + 1}, [x28, #${128 + 8 * r}]`);
        lines.push("    mrs x16, nzcv", "    str x16, [x28, #208]", "    mrs x16, fpsr", "    str x16, [x28, #216]", "    msr fpcr, xzr");
    });
    lines.push("    ldp d10, d11, [sp, #16]", "    ldp d12, d13, [sp, #32]", "    ldp d14, d15, [sp, #48]", "    ldp d8, d9, [sp], #64",
        "    ldp x19, x20, [sp, #16]", "    ldp x21, x22, [sp, #32]", "    ldp x23, x24, [sp, #48]", "    ldp x25, x26, [sp, #64]",
        "    ldp x27, x28, [sp, #80]", "    ldp x29, x30, [sp], #96", "    ret");
    lines.push(".balign 16");
    batch.forEach((c, i) => {
        lines.push(`literal_${first + i}:`, `    .quad ${hex(c.literal_value & (1n << 64n) - 1n)}`, `    .quad ${hex(c.literal_value >> 64n)}`);
    });
    lines.push(".data", ".balign 64");
    batch.forEach((c, i) => {
        const n = first + i;
        lines.push(`input_${n}:`);
        for(const v of c.v) lines.push(`    .quad ${hex(v & (1n << 64n) - 1n)}`, `    .quad ${hex(v >> 64n)}`);
        lines.push(...c.x.map(v => `    .quad ${hex(v)}`), `    .quad ${hex(c.x9)}`, `    .quad ${hex(c.nzcv)}`, `    .quad ${hex(c.fpcr)}`,
            "    .quad 0", ".balign 64", `memory_${n}:`, ...c.memory.map(v => `    .quad ${hex(v)}`), ".balign 64",
            `output_${n}:`, "    .zero 224", ".balign 64");
    });
    lines.push(".text", ".global case_table", ".balign 8", "case_table:");
    batch.forEach((_, i) => lines.push(`    .quad output_${first + i}`, `    .quad memory_${first + i}`));
    return lines.join("\n") + "\n";
}

const MAIN = `#include <a64.h>
#include <stdio.h>
void run_cases(void);
extern const unsigned long case_table[][2];
int main(int argc, char **argv)
{
    (void)argc, (void)argv;
    run_cases();
    for(int i = 0; i < CASE_COUNT; i++)
    {
        const unsigned long *out = (const unsigned long *)case_table[i][0];
        const unsigned long *memory = (const unsigned long *)case_table[i][1];
        unsigned long sum = 0;
        for(int k = 0; k < 32; k++) sum = (sum ^ memory[k]) * 0x100000001B3ul + k;
        printf("%d", FIRST + i);
        // (X8 relative to the window: the hosts place it differently)
        for(int r = 0; r < 28; r++) printf(" %lx", r == 24 ? out[r] - (unsigned long)memory : out[r]);
        printf(" %lx\\n", sum);
    }
    return 0;
}
`;

const NAMES = [...Array.from({ length: 8 }, (_, r) => [`v${r}.lo`, `v${r}.hi`]).flat(), ...Array.from({ length: 10 }, (_, r) => "x" + r),
    "nzcv", "fpsr", "memory"];
function explain(want, have)
{
    const w = want.split(" "), h = have.split(" ");
    return w.slice(1).map((value, i) => value === h[i + 1] ? null : `${NAMES[i]} qemu ${value} v86 ${h[i + 1]}`).filter(Boolean).join(", ");
}

/**
 * The cases of a batch on the host (macOS arm64): the guest's assembly in
 * Mach-O syntax, its main with the host's libc; the lines it prints
 */
function native(batch, first, directory)
{
    assert.ok(process.platform === "darwin" && process.arch === "arm64", "the native oracle needs macOS on arm64");
    const asm = guest(batch, first)
        .replace(/adrp (x\d+), ([a-z_0-9]+)$/gm, "adrp $1, $2@PAGE")
        .replace(/:lo12:([a-z_0-9]+)/g, "$1@PAGEOFF")
        .replace(/\brun_cases\b/g, "_run_cases")
        // (absolute addresses belong in data on Mach-O)
        .replace(/\.text\n\.global case_table\n\.balign 8\ncase_table:/, ".data\n.global _case_table\n.balign 8\n_case_table:");
    fs.writeFileSync(directory + "native.S", asm);
    fs.writeFileSync(directory + "native.c", MAIN.replace("#include <a64.h>\n", "").replace(/CASE_COUNT/g, String(batch.length)).replace(/FIRST/g, String(first)));
    execFileSync("clang", ["-arch", "arm64", "-O1", "-o", directory + "native", directory + "native.c", directory + "native.S"]);
    return execFileSync(directory + "native", { encoding: "latin1", maxBuffer: 64 << 20 });
}

export async function run({ name = "simd", classes = null, mnemonics = null, cases: CASES = 6000, seed: SEED = 1, filter: FILTER = null,
    fpcr: FPCR = null, against = "qemu" })
{
    // ---- random values (xorshift: the same cases everywhere)
    let state = BigInt(SEED) * 0x9E3779B97F4A7C15n & (1n << 64n) - 1n || 1n;
    next64 = () => {
        state ^= state << 13n & (1n << 64n) - 1n;
        state ^= state >> 7n;
        state ^= state << 17n & (1n << 64n) - 1n;
        return state;
    };
    rand = n => Number(next64() % BigInt(n));
    rand32 = () => Number(next64() & 0xFFFFFFFFn) >>> 0;
    pick = list => list[rand(list.length)];

    // the pools: valid words of each class by mnemonic
    const pools = new Map();
    for(const [class_name, [mask, value, regs]] of Object.entries(CLASSES))
    {
        if(classes && !classes.includes(class_name)) continue;
        for(let k = 0; k < 6000; k++)
        {
            let word = (value | rand32() & ~mask) >>> 0;
            word = class_name === "structure" ? structure_word(word) : sanitize(word, regs);
            const m = mnemonic(word);
            if(!m) continue;
            const key = class_name === "structure" ? "struct:" + m : m;
            if(FILTER && FILTER !== class_name && FILTER !== m || mnemonics && !mnemonics.includes(m)) continue;
            if(!pools.has(key)) pools.set(key, { class: class_name, words: new Set() });
            pools.get(key).words.add(word);
        }
    }
    if((!classes || classes.includes("memory")) && (!FILTER || FILTER === "memory")) pools.set("memory", { class: "memory", words: null });

    const keys = [...pools.keys()].sort();
    const cases = [];
    for(let n = 0; n < CASES; n++)
    {
        const key = keys[n % keys.length];
        const pool = pools.get(key);
        let asm, word = null, literal = false;
        if(pool.words)
        {
            word = pick([...pool.words]);
            asm = `.inst ${hex(word)} // ${key}`;
        }
        else
        {
            const generated = pick(MEMORY)();
            if(typeof generated === "object") { literal = true; asm = generated.asm; }
            else asm = generated;
        }
        const fpcr = FPCR ? FPCR(n, Math.floor(n / keys.length)) : BigInt(rand(4)) << 22n | BigInt(rand(2)) << 24n | BigInt(rand(2)) << 25n | BigInt(rand(2)) << 26n;
        cases.push({
            key, class: pool.class, asm, word, literal, fpcr,
            v: Array.from({ length: 8 }, vector),
            x: Array.from({ length: 8 }, xvalue),
            x9: BigInt(rand(4) * 16),
            nzcv: BigInt(rand(16)) << 28n,
            memory: Array.from({ length: 32 }, () => lane64()),
            literal_value: vector(),
        });
    }

    const directory_base = root + `build/a64-${name}-oracle/`;
    fs.mkdirSync(directory_base, { recursive: true });
    let differences = 0, compared = 0;
    const by_key = new Map();
    const only_qemu = process.env.A64_TARGET === "qemu";
    for(let first = 0; first < cases.length; first += BATCH)
    {
        const batch = cases.slice(first, first + BATCH);
        fs.writeFileSync(directory_base + `cases-${first}.S`, guest(batch, first));
        fs.writeFileSync(directory_base + `main-${first}.c`, MAIN.replace(/CASE_COUNT/g, String(batch.length)).replace(/FIRST/g, String(first)));
        const directory = build(`${name}-oracle-${first}`, [directory_base + `cases-${first}.S`, directory_base + `main-${first}.c`]);
        const expected = against === "native" ? { status: "ok", text: native(batch, first, directory) } : await reference(directory, { timeout: 120000 });
        assert.equal(expected.status, "ok", "QEMU: " + JSON.stringify(expected.exception, (k, v) => typeof v === "bigint" ? hex(v) : v) + expected.text.slice(-2000));
        if(only_qemu) { compared += batch.length; continue; }
        const got = await actual(directory, { timeout: 300000 });
        assert.equal(got.status, "ok", "v86: " + JSON.stringify(got.exception, (k, v) => typeof v === "bigint" ? hex(v) : v) + got.text.slice(-2000));
        const want = expected.text.trim().split("\n"), have = got.text.trim().split("\n");
        assert.equal(have.length, want.length, "line count");
        for(let i = 0; i < want.length; i++)
        {
            compared++;
            if(want[i] === have[i]) continue;
            differences++;
            const c = cases[first + i];
            by_key.set(c.key, (by_key.get(c.key) || 0) + 1);
            if(differences <= 40)
            {
                console.log(`DIFF case ${first + i} (${c.key}): ${c.asm} fpcr ${hex(c.fpcr)}\n  ${explain(want[i], have[i]).replaceAll("qemu", against)}`);
            }
        }
    }
    if(by_key.size) console.log("differences by mnemonic: " + [...by_key].sort((a, b) => b[1] - a[1]).map(([k, n]) => `${k} ${n}`).join(", "));
    console.log(`${name} oracle: ${compared} cases (${keys.length} mnemonics and forms, seed ${SEED}), ${differences} differences` + (only_qemu ? " (QEMU only)" : ""));
    return { compared, differences, keys };
}
                                                                                                                                                                                                                 source/v64/tests/a64/virtio_blk_disk_error.mjs                                                      0000755 0000000 0000000 00000022040 00000000000 016523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// virtio-blk's failed requests and FLUSH (docs/disk-persistence-plan.md D0),
// the test the driver through the virtio-mmio registers and a queue in
// guest RAM (as tests/a64/device_io_reset.mjs). The disk's writes complete
// after a delay the test sets per write; its reads and writes fail on
// request.
// - FLUSH waits for the writes issued before it, not for those issued
//   after it (write A, FLUSH, a slower write B: FLUSH completes before B);
// - disk_error "stop" (the default): a failed write is held, the FLUSH
//   behind it waits; run() retries the write, then the FLUSH completes; a
//   failed read is held and retried; "disk-error" tells the host;
// - disk_error "report": a failed read and write complete with
//   VIRTIO_BLK_S_IOERR at once.
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SIZE = 1 << 20;
// (a class: state images take no plain objects)
class SlowDisk
{
    constructor(policy)
    {
        this.byteLength = SIZE;
        this.data = new Uint8Array(SIZE).map((_, i) => i * 7 + (i >> 9) & 0xFF);
        /** @type {!Map<number, number>} the delay of a write, by its offset */
        this.latency = new Map();
        this.fail_reads = 0;
        this.fail_writes = 0;
        this.writes_landed = [];
        if(policy) this.disk_error = policy;
    }
    load() { this.onload?.({}); }
    get(start, length, done)
    {
        if(this.fail_reads) { this.fail_reads--; done(undefined, new Error("the test's disk failed the read")); return; }
        done(this.data.slice(start, start + length));
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done)
    {
        if(this.fail_writes) { this.fail_writes--; done(new Error("the test's disk failed the write")); return; }
        const land = () => { this.data.set(data, start); this.writes_landed.push(start); done(); };
        const delay = this.latency.get(start);
        if(delay) setTimeout(land, delay); else land();
    }
    get_buffer(done) { done(undefined); }
    get_state() { return [this.data]; }
    set_state(state) { this.data.set(state[0]); }
}

async function machine(disk)
{
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", virtio_disks: [{ buffer: disk }],
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    const events = [];
    emulator.add_listener("disk-error", event => events.push(event));
    const cpu = emulator.v86.cpu;
    const transport = cpu.virtio_mmio[31];
    const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
    const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUFFERS = RAM + 0x20000;
    const QUEUE = 16;
    const u16 = (address, value) => cpu.write_blob_physical(new Uint8Array([value & 0xFF, value >> 8]), address);
    const u32 = (address, value) => cpu.write_blob_physical(new Uint8Array(new Uint32Array([value]).buffer), address);
    const used_idx = () => cpu.read16_physical(USED + 2);
    reg(0x070, 0);
    reg(0x070, 1 | 2);
    reg(0x024, 1); reg(0x020, 1); // VIRTIO_F_VERSION_1
    reg(0x024, 0); reg(0x020, 0);
    reg(0x070, 1 | 2 | 8);
    reg(0x030, 0); reg(0x038, QUEUE);
    reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
    cpu.write_blob_physical(new Uint8Array(0x3000), DESC);
    reg(0x044, 1);
    reg(0x070, 1 | 2 | 8 | 4);
    let avail = 0, slot = 0;
    /** Queue one request (not notified yet): its head and its status */
    const queue = (type, sector, data_length, data) =>
    {
        const n = slot++ % 5, head = n * 3;
        const header = BUFFERS + n * 0x2000, payload = header + 0x100, status = header + 0x1F00;
        const bytes = new Uint8Array(16), view = new DataView(bytes.buffer);
        view.setUint32(0, type, true); view.setUint32(8, sector, true);
        cpu.write_blob_physical(bytes, header);
        if(data) cpu.write_blob_physical(data, payload);
        cpu.write_blob_physical(new Uint8Array([0xFF]), status);
        const descriptor = (i, address, length, flags, next) => {
            u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length);
            u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next);
        };
        const WRITE = 2, NEXT = 1;
        descriptor(head, header, 16, NEXT, data_length ? head + 1 : head + 2);
        if(data_length) descriptor(head + 1, payload, data_length, NEXT | (type === 0 ? WRITE : 0), head + 2);
        descriptor(head + 2, status, 1, WRITE, 0);
        u16(AVAIL + 4 + 2 * (avail % QUEUE), head);
        u16(AVAIL + 2, ++avail);
        return { head, status: () => cpu.read8_physical(status), payload: length => cpu.read_blob_physical(payload, length) };
    };
    const notify = () => reg(0x050, 0);
    /** the heads in the used ring, in their order */
    const used = () => Array.from({ length: used_idx() }, (_, i) =>
        new DataView(cpu.read_blob_physical(USED + 4 + 8 * (i % QUEUE), 4).slice().buffer).getUint32(0, true));
    return { emulator, cpu, events, queue, notify, used, used_idx };
}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what)
{
    for(let i = 0; i < 2000 && !condition(); i++) await wait(2);
    assert.ok(condition(), what);
}
const T_IN = 0, T_OUT = 1, T_FLUSH = 4, S_OK = 0, S_IOERR = 1;

// FLUSH waits for the writes before it only
{
    const disk = new SlowDisk();
    disk.latency.set(0, 50);
    disk.latency.set(8 * 512, 400);
    const m = await machine(disk);
    const a = m.queue(T_OUT, 0, 512, new Uint8Array(512).fill(0xAA));
    const flush = m.queue(T_FLUSH, 0, 0);
    const b = m.queue(T_OUT, 8, 512, new Uint8Array(512).fill(0xBB));
    m.notify();
    await until(() => m.used_idx() === 3, "the three requests complete");
    assert.deepEqual(m.used(), [a.head, flush.head, b.head], "write A, then FLUSH, then the slower write B issued after it");
    assert.deepEqual([a.status(), flush.status(), b.status()], [S_OK, S_OK, S_OK]);
    assert.deepEqual(disk.writes_landed, [0, 8 * 512]);
    await m.emulator.destroy();
    console.log("ok - FLUSH waits for the writes issued before it, not for a slower one issued after it");
}

// disk_error "stop": held, run() retries
{
    const disk = new SlowDisk();
    const m = await machine(disk);
    disk.fail_writes = 1;
    const a = m.queue(T_OUT, 2, 512, new Uint8Array(512).fill(0x5A));
    const flush = m.queue(T_FLUSH, 0, 0);
    m.notify();
    await wait(50);
    assert.equal(m.used_idx(), 0, "the failed write is held, the FLUSH behind it waits");
    assert.equal(m.cpu.disk_holds.length, 1);
    assert.deepEqual(m.events, [{ disk: "virtio_disk0", operation: "write", offset: 1024, length: 512,
        reason: "the test's disk failed the write", retryable: true, policy: "stop" }]);
    await assert.rejects(m.emulator.save_state(), /held after an I\/O error/);
    m.emulator.v86.run();
    m.emulator.v86.stop();
    await until(() => m.used_idx() === 2, "the write and the FLUSH complete after run()");
    assert.deepEqual(m.used(), [a.head, flush.head]);
    assert.equal(a.status(), S_OK);
    assert.deepEqual(disk.data.subarray(1024, 1536), new Uint8Array(512).fill(0x5A), "the write landed");
    disk.fail_reads = 1;
    const r = m.queue(T_IN, 2, 512);
    m.notify();
    assert.equal(m.used_idx(), 2, "the failed read is held");
    m.emulator.v86.run();
    m.emulator.v86.stop();
    await until(() => m.used_idx() === 3, "the read completes after run()");
    assert.equal(r.status(), S_OK);
    assert.deepEqual(r.payload(512), new Uint8Array(512).fill(0x5A));
    assert.equal(m.events.length, 2);
    await m.emulator.destroy();
    console.log("ok - stop: a failed write is held (and the FLUSH behind it), a failed read too; run() retries them");
}

// disk_error "report": IOERR at once
{
    const disk = new SlowDisk("report");
    const m = await machine(disk);
    disk.fail_reads = 1;
    disk.fail_writes = 1;
    const r = m.queue(T_IN, 0, 512);
    const w = m.queue(T_OUT, 1, 512, new Uint8Array(512));
    m.notify();
    await until(() => m.used_idx() === 2, "both complete");
    assert.equal(r.status(), S_IOERR, "the read: VIRTIO_BLK_S_IOERR");
    assert.equal(w.status(), S_IOERR, "the write: VIRTIO_BLK_S_IOERR");
    assert.deepEqual(m.events.map(e => [e.operation, e.policy]), [["read", "report"], ["write", "report"]]);
    assert.equal(m.cpu.disk_holds?.length || 0, 0);
    await m.emulator.destroy();
    console.log("ok - report: a failed read and write end with VIRTIO_BLK_S_IOERR at once");
}
console.log("virtio_blk_disk_error: passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/a64/virtio_blk_disk_image.mjs                                                      0000755 0000000 0000000 00000022541 00000000000 016462  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// virtio-blk on a disk image in a container format (docs/disk-image-formats-plan.md,
// the merge of disk-formats with arm64): a QCOW2 image built in memory
// (tests/image/tiny_qcow2.mjs) behind the virt machine's virtio-blk, the
// test the driver through the virtio-mmio registers and a queue in guest
// RAM (as tests/a64/device_io_reset.mjs):
// - reads of data and unallocated clusters, and of the guest's writes;
// - a read of a damaged cluster (the image fails it) ends with
//   VIRTIO_BLK_S_IOERR, and the next read is fine;
// - a write beyond the overlay's memory budget ends with VIRTIO_BLK_S_IOERR
//   and leaves the disk as it was; FLUSH is fine;
// - a snapshot restores the guest's writes, and is refused, before anything
//   is restored, onto another image or onto a RAW disk;
// - export_disk_image and disk_image_info know the disk as virtio_disk0
//   (hda when given as hda); the export of the damaged image fails.
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { build_qcow2 } from "../image/tiny_qcow2.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { SyncBuffer } = await import("../../src/buffer.js");

const SIZE = 4 << 20, CLUSTER = 1 << 16;
const first = new Uint8Array(CLUSTER).map((_, i) => i * 13 + 5 & 0xFF);
const image = build_qcow2({ size: SIZE, data: [[0, first]], damaged: [CLUSTER] });
// (the same size, other data: another image)
const other_image = build_qcow2({ size: SIZE, data: [[0, new Uint8Array(CLUSTER).fill(1)], [2 * CLUSTER, new Uint8Array(CLUSTER).fill(2)]] });
const BUDGET = 16 * 256;

async function machine(options)
{
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", ...options,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}
const qcow2_disk = (bytes, id) => ({ buffer: bytes.slice().buffer, format: "qcow2", overlay_limit: BUDGET, id, disk_error: "report" });

const emulator = await machine({ virtio_disks: [qcow2_disk(image, "qcow2disk")] });
const cpu = emulator.v86.cpu;
const slot = 31, transport = cpu.virtio_mmio[slot];
const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
assert.equal(reg(0x008), 2, "the disk is virtio-blk, in the last slot");
assert.equal(reg(0x100) + reg(0x104) * 2 ** 32, SIZE / 512, "the capacity is the image's virtual size");

const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUFFERS = RAM + 0x20000;
const QUEUE = 8;
const u16 = (address, value) => cpu.write_blob_physical(new Uint8Array([value & 0xFF, value >> 8]), address);
const u32 = (address, value) => cpu.write_blob_physical(new Uint8Array(new Uint32Array([value]).buffer), address);
const used_idx = () => cpu.read16_physical(USED + 2);
let avail = 0;
function driver_init()
{
    avail = 0;
    reg(0x070, 0);
    reg(0x070, 1 | 2);
    reg(0x024, 1); reg(0x020, 1); // VIRTIO_F_VERSION_1
    reg(0x024, 0); reg(0x020, 0);
    reg(0x070, 1 | 2 | 8);
    assert.equal(reg(0x070) & 8, 8, "FEATURES_OK");
    reg(0x030, 0); reg(0x038, QUEUE);
    reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
    cpu.write_blob_physical(new Uint8Array(0x3000), DESC);
    reg(0x044, 1);
    reg(0x070, 1 | 2 | 8 | 4);
}
const T_IN = 0, T_OUT = 1, T_FLUSH = 4, S_OK = 0, S_IOERR = 1;
/** One request, completed: its status and (a read's) data */
async function request(type, sector, data_length, data)
{
    const header = BUFFERS, payload = BUFFERS + 0x100, status = BUFFERS + 0x40000;
    const head = new Uint8Array(16), view = new DataView(head.buffer);
    view.setUint32(0, type, true); view.setUint32(8, sector, true);
    cpu.write_blob_physical(head, header);
    cpu.write_blob_physical(data || new Uint8Array(data_length).fill(0xEE), payload);
    cpu.write_blob_physical(new Uint8Array([0xFF]), status);
    const descriptor = (i, address, length, flags, next) => {
        u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length);
        u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next);
    };
    const WRITE = 2, NEXT = 1;
    descriptor(0, header, 16, NEXT, data_length ? 1 : 2);
    if(data_length) descriptor(1, payload, data_length, NEXT | (type === T_IN ? WRITE : 0), 2);
    descriptor(2, status, 1, WRITE, 0);
    u16(AVAIL + 4 + 2 * (avail % QUEUE), 0);
    const expected = ++avail;
    u16(AVAIL + 2, expected);
    reg(0x050, 0);
    for(let i = 0; used_idx() !== expected; i++)
    {
        assert.ok(i < 1000, "the request completes");
        await new Promise(resolve => setTimeout(resolve, 1));
    }
    assert.equal(cpu["snapshot_io_pending"], 0, "nothing is left in flight");
    return { status: cpu.read8_physical(status), data: data_length ? cpu.read_blob_physical(payload, data_length) : undefined };
}

driver_init();
let r = await request(T_IN, 0, 4096);
assert.equal(r.status, S_OK);
assert.deepEqual(r.data, first.subarray(0, 4096), "a data cluster's bytes");
r = await request(T_IN, 2 * CLUSTER / 512, 4096);
assert.equal(r.status, S_OK);
assert.deepEqual(r.data, new Uint8Array(4096), "an unallocated cluster reads as zeroes");
console.log("ok - virtio-blk reads a QCOW2 image's virtual disk");

r = await request(T_IN, CLUSTER / 512, 512);
assert.equal(r.status, S_IOERR, "a read of a damaged cluster: VIRTIO_BLK_S_IOERR");
r = await request(T_IN, CLUSTER / 512 - 1, 1024);
assert.equal(r.status, S_IOERR, "also a read that ends in it");
r = await request(T_IN, 8, 512);
assert.equal(r.status, S_OK, "the next read is fine");
assert.deepEqual(r.data, first.subarray(8 * 512, 9 * 512));
console.log("ok - a read the disk image fails ends with VIRTIO_BLK_S_IOERR");

const written = new Uint8Array(1024).fill(0x5A);
r = await request(T_OUT, 4, 1024, written);
assert.equal(r.status, S_OK, "a write within the budget");
r = await request(T_OUT, 64, BUDGET, new Uint8Array(BUDGET).fill(0x77));
assert.equal(r.status, S_IOERR, "a write beyond the overlay's budget: VIRTIO_BLK_S_IOERR");
r = await request(T_FLUSH, 0, 0);
assert.equal(r.status, S_OK, "FLUSH");
r = await request(T_IN, 0, 4096);
const expected = first.slice(0, 4096);
expected.set(written, 4 * 512);
assert.deepEqual(r.data, expected, "the write within the budget is read back");
r = await request(T_IN, 64, BUDGET);
assert.deepEqual(r.data, first.subarray(64 * 512, 64 * 512 + BUDGET), "the failed write changed nothing");
console.log("ok - a write beyond the budget ends with VIRTIO_BLK_S_IOERR, FLUSH is fine");

// snapshots: the guest's writes come back, onto the same image only
const state = await emulator.save_state();
r = await request(T_OUT, 4, 512, new Uint8Array(512).fill(0x11));
assert.equal(r.status, S_OK);
await emulator.restore_state(state);
driver_init();
r = await request(T_IN, 0, 4096);
assert.deepEqual(r.data, expected, "the snapshot's disk: the later write is gone");
console.log("ok - a snapshot restores the disk image's changes");

const marker = new Uint8Array([0xC0, 0xFF, 0xEE, 0x42]);
for(const [what, options, pattern] of [
    ["another image", { virtio_disks: [qcow2_disk(other_image)] }, /another image/],
    ["a RAW disk", { virtio_disks: [{ buffer: new SyncBuffer(new ArrayBuffer(SIZE)) }] }, /container format/],
])
{
    const target = await machine(options);
    target.v86.cpu.write_blob_physical(marker, RAM);
    await assert.rejects(target.restore_state(state), pattern, "the snapshot onto " + what);
    assert.deepEqual(target.v86.cpu.read_blob_physical(RAM, 4), marker, "nothing was restored (" + what + ")");
    await target.destroy();
}
console.log("ok - the snapshot is refused onto another image and onto a RAW disk, before anything is restored");

// export, by the disk's name
const info = await emulator.disk_image_info("virtio_disk0");
assert.equal(info.format, "qcow2");
assert.equal(info.size, SIZE);
assert.equal(info.file_size, image.length);
assert.ok(info.written >= 1024, "the guest's writes are counted");
await assert.rejects(emulator.export_disk_image("virtio_disk0", { write: () => {} }), /reserved bits set/,
    "the export of the image with the damaged cluster fails");
await assert.rejects(emulator.export_disk_image("virtio_disk1", { write: () => {} }), /No disk virtio_disk1/);
await emulator.destroy();

// (hda on virt: the first virtio-blk disk, by the name hda)
const clean = build_qcow2({ size: SIZE, data: [[0, first]] });
const as_hda = await machine({ hda: qcow2_disk(clean) });
assert.equal((await as_hda.disk_image_info("hda")).format, "qcow2");
const chunks = [];
const total = await as_hda.export_disk_image("hda", { write: chunk => { chunks.push(chunk.slice()); } });
assert.equal(total, SIZE);
const exported = new Uint8Array(SIZE);
let at = 0;
for(const chunk of chunks) { exported.set(chunk, at); at += chunk.length; }
assert.equal(at, SIZE);
const raw = new Uint8Array(SIZE);
raw.set(first);
assert.deepEqual(exported, raw, "the export is the virtual disk");
await as_hda.destroy();
console.log("ok - export_disk_image and disk_image_info know the virtio disks");
console.log("virtio_blk_disk_image: passed");
                                                                                                                                                               source/v64/tests/a64/virtio_blk_sector_size.mjs                                                     0000755 0000000 0000000 00000020344 00000000000 016716  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// virtio-blk disks with logical sectors of 4096 bytes (docs/disk-image-formats-plan.md,
// the appendix's "4K 逻辑扇区") on the virt machine, the test the driver
// through the virtio-mmio registers and a queue in guest RAM (as
// tests/a64/virtio_blk_disk_image.mjs): a RAW disk with logical_sector_size
// 4096, a VHDX image with 4096-byte sectors (tests/image/tiny_vhdx.mjs) and a
// 512-byte disk.
// - BLK_SIZE offered, blk_size the disk's sector size; the capacity and the
//   requests' sector numbers in 512-byte units;
// - reads and writes of whole 4096-byte sectors; one that starts or ends
//   inside a sector ends with VIRTIO_BLK_S_IOERR (as QEMU's) and writes
//   nothing;
// - a snapshot is restored onto the same disks and refused, before anything
//   is restored, where a disk's sector size is another.
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { build_vhdx } from "../image/tiny_vhdx.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SIZE = 4 << 20, S = 4096;
const raw_bytes = new Uint8Array(SIZE).map((_, i) => i * 7 + (i >> 12) & 0xFF);
const vhdx_data = new Uint8Array(1 << 20).map((_, i) => i * 3 + 1 & 0xFF);
const vhdx = build_vhdx({ size: SIZE, logical_sector_size: 4096, data: [[0, vhdx_data]] });
const disks = () => [
    { buffer: raw_bytes.buffer, logical_sector_size: 4096, id: "raw4k" },
    { buffer: vhdx.image.slice().buffer, format: "vhdx", id: "vhdx4k" },
    { buffer: new ArrayBuffer(SIZE), id: "raw512" },
];

async function machine(virtio_disks)
{
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", virtio_disks,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}

const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUFFERS = RAM + 0x20000;
const QUEUE = 8;
const T_IN = 0, T_OUT = 1, S_OK = 0, S_IOERR = 1;

/** The driver of the disk in a virtio-mmio slot (the disks take the slots from 31 down) */
function driver(emulator, slot)
{
    const cpu = emulator.v86.cpu, transport = cpu.virtio_mmio[slot];
    const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
    const u16 = (address, value) => cpu.write_blob_physical(new Uint8Array([value & 0xFF, value >> 8]), address);
    const u32 = (address, value) => cpu.write_blob_physical(new Uint8Array(new Uint32Array([value]).buffer), address);
    let avail = 0;
    reg(0x070, 0);
    reg(0x070, 1 | 2);
    reg(0x014, 0);
    const features = reg(0x010);
    reg(0x024, 1); reg(0x020, 1); // VIRTIO_F_VERSION_1
    reg(0x024, 0); reg(0x020, 1 << 6); // VIRTIO_BLK_F_BLK_SIZE
    reg(0x070, 1 | 2 | 8);
    assert.equal(reg(0x070) & 8, 8, "FEATURES_OK");
    reg(0x030, 0); reg(0x038, QUEUE);
    reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
    cpu.write_blob_physical(new Uint8Array(0x3000), DESC);
    reg(0x044, 1);
    reg(0x070, 1 | 2 | 8 | 4);
    return {
        features,
        capacity: reg(0x100) + reg(0x104) * 2 ** 32,
        blk_size: reg(0x114),
        /** One request, completed: its status and (a read's) data */
        async request(type, sector, data_length, data)
        {
            const header = BUFFERS, payload = BUFFERS + 0x100, status = BUFFERS + 0x40000;
            const head = new Uint8Array(16), view = new DataView(head.buffer);
            view.setUint32(0, type, true); view.setUint32(8, sector, true);
            cpu.write_blob_physical(head, header);
            cpu.write_blob_physical(data || new Uint8Array(data_length).fill(0xEE), payload);
            cpu.write_blob_physical(new Uint8Array([0xFF]), status);
            const descriptor = (i, address, length, flags, next) => {
                u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length);
                u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next);
            };
            const WRITE = 2, NEXT = 1;
            descriptor(0, header, 16, NEXT, 1);
            descriptor(1, payload, data_length, NEXT | (type === T_IN ? WRITE : 0), 2);
            descriptor(2, status, 1, WRITE, 0);
            u16(AVAIL + 4 + 2 * (avail % QUEUE), 0);
            const expected = ++avail;
            u16(AVAIL + 2, expected);
            reg(0x050, 0);
            for(let i = 0; cpu.read16_physical(USED + 2) !== expected; i++)
            {
                assert.ok(i < 1000, "the request completes");
                await new Promise(resolve => setTimeout(resolve, 1));
            }
            return { status: cpu.read8_physical(status), data: cpu.read_blob_physical(payload, data_length) };
        },
    };
}

const emulator = await machine(disks());
for(const [slot, name, contents] of [[31, "RAW", raw_bytes], [30, "VHDX", null]])
{
    const disk = driver(emulator, slot);
    const at = (offset, length) => contents ? contents.slice(offset, offset + length) :
        Uint8Array.from({ length }, (_, i) => offset + i < vhdx_data.length ? vhdx_data[offset + i] : 0);
    assert.ok(disk.features & 1 << 6, name + ": VIRTIO_BLK_F_BLK_SIZE");
    assert.equal(disk.blk_size, 4096, name + ": blk_size");
    assert.equal(disk.capacity, SIZE / 512, name + ": the capacity in 512-byte sectors");
    let r = await disk.request(T_IN, 8, 2 * S);
    assert.equal(r.status, S_OK);
    assert.deepEqual(r.data, at(S, 2 * S), name + ": sector 8 (512-byte units) is the second 4096-byte sector");
    for(const [sector, length] of [[1, S], [8, 512], [12, S], [8, S + 512]])
    {
        r = await disk.request(T_IN, sector, length);
        assert.equal(r.status, S_IOERR, name + ": a read of " + length + " bytes at sector " + sector + " is not of whole sectors");
    }
    const data = new Uint8Array(2 * S).map((_, i) => 255 - (i * 5 & 0xFF));
    r = await disk.request(T_OUT, 2 * 8, 2 * S, data);
    assert.equal(r.status, S_OK);
    r = await disk.request(T_OUT, 4 * 8 + 4, S, new Uint8Array(S).fill(0x11));
    assert.equal(r.status, S_IOERR, name + ": a write inside a sector");
    r = await disk.request(T_OUT, 6 * 8, 1024, new Uint8Array(1024).fill(0x22));
    assert.equal(r.status, S_IOERR, name + ": a write of part of a sector");
    r = await disk.request(T_IN, 0, 8 * S);
    const expected = at(0, 8 * S);
    expected.set(data, 2 * S);
    assert.deepEqual(r.data, expected, name + ": the write read back, the failed ones wrote nothing");
    if(contents) assert.deepEqual(raw_bytes.subarray(2 * S, 4 * S), data, name + ": in the image");
}
{
    const disk = driver(emulator, 29);
    assert.equal(disk.blk_size, 512, "the 512-byte disk: blk_size 512");
    const r = await disk.request(T_IN, 1, 512);
    assert.equal(r.status, S_OK, "the 512-byte disk: a read of one sector");
}
console.log("ok - virtio-blk: blk_size 4096 (RAW and VHDX), the capacity and sectors in 512-byte units, " +
    "reads and writes of whole sectors, IOERR for parts of one");

// snapshots: onto the same disks; refused where a disk's sector size is another
const state = await emulator.save_state();
await emulator.destroy();
{
    const same = await machine(disks());
    await same.restore_state(state);
    const r = await driver(same, 31).request(T_IN, 16, S);
    assert.equal(r.status, S_OK);
    await same.destroy();
    const other_disks = disks();
    delete other_disks[0].logical_sector_size;
    const other = await machine(other_disks);
    const marker = new Uint8Array([0xC0, 0xFF, 0xEE, 0x42]);
    other.v86.cpu.write_blob_physical(marker, RAM);
    await assert.rejects(other.restore_state(state), /4096-byte sectors, this one 512/, "a 512-byte disk refuses the snapshot");
    assert.deepEqual(other.v86.cpu.read_blob_physical(RAM, 4), marker, "nothing was restored");
    await other.destroy();
}
console.log("ok - snapshots: restored onto the same disks, refused before anything is restored onto a 512-byte one");
console.log("virtio_blk_sector_size: passed");
                                                                                                                                                                                                                                                                                            source/v64/tests/a64/virtio_input_touch.mjs                                                         0000644 0000000 0000000 00000013457 00000000000 016102  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The virt machine's multi-touch screen and the mouse (src/virtio_input.js):
// with no tablet beside it (Android's preset: a keyboard and a touch screen)
// the mouse is one finger, the left button down a touch where the mouse is,
// moves while down a drag, up the finger lifted; with a tablet the tablet
// takes the mouse and the touch screen only touches. The events stay in the
// device's pending list (no driver takes them here).
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const EV_SYN = 0, EV_KEY = 1, EV_ABS = 3, BTN_TOUCH = 0x14A;
const ABS_MT_SLOT = 0x2F, ABS_MT_POSITION_X = 0x35, ABS_MT_POSITION_Y = 0x36, ABS_MT_TRACKING_ID = 0x39;

async function machine(inputs)
{
    const emulator = new V86({
        cpu_type: "arm64", graphics_adapter: "none", memory_size: 16 << 20, autostart: false, log_level: 0,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", virtio_input: inputs,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    const device = kind => emulator.v86.cpu.virtio_devices.find(d => d.name === "virtio-" + kind).device;
    return { emulator, device };
}
// (the events since the last call, without the SYN_REPORTs)
const take = device => device.pending.splice(0).filter(([type]) => type !== EV_SYN);

// a keyboard and a touch screen: the mouse is a finger
{
    const { emulator, device } = await machine(["keyboard", "multitouch"]);
    const touch = device("multitouch");
    // (the screen 720x1280 on the page: x, y, width, height; 0x7FFF is the axes' maximum)
    emulator.bus.send("mouse-absolute", [360, 640, 720, 1280]);
    assert.deepEqual(take(touch), [], "a move with no button: nothing");
    emulator.bus.send("mouse-click", [true, false, false]);
    assert.deepEqual(take(touch), [[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_TRACKING_ID, 0], [EV_ABS, ABS_MT_POSITION_X, 16384],
        [EV_ABS, ABS_MT_POSITION_Y, 16384], [EV_KEY, BTN_TOUCH, 1]], "the left button down: a touch where the mouse is");
    emulator.bus.send("mouse-absolute", [360, 320, 720, 1280]);
    assert.deepEqual(take(touch), [[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_POSITION_Y, 8192]], "a move while down: a drag");
    emulator.bus.send("mouse-click", [true, false, true]);
    assert.deepEqual(take(touch), [], "another button: the finger stays");
    emulator.bus.send("mouse-click", [false, false, false]);
    assert.deepEqual(take(touch), [[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_TRACKING_ID, -1], [EV_KEY, BTN_TOUCH, 0]], "up: the finger lifted");
    emulator.bus.send("mouse-absolute", [100, 100, 720, 1280]);
    assert.deepEqual(take(touch), [], "a move after: nothing");
    // (a touch screen's own touches as before)
    emulator.bus.send("touch", { "touches": [[7, 72, 128]], "width": 720, "height": 1280 });
    assert.deepEqual(take(touch), [[EV_ABS, ABS_MT_SLOT, 0], [EV_ABS, ABS_MT_TRACKING_ID, 0], [EV_ABS, ABS_MT_POSITION_X, 3277],
        [EV_ABS, ABS_MT_POSITION_Y, 3277], [EV_KEY, BTN_TOUCH, 1]], "a touch of the page's touch screen");
    await emulator.destroy();
    console.log("PASS: a touch screen with no tablet takes the mouse as a finger (a tap, a drag, lifted)");
}

// with a tablet beside it: the tablet takes the mouse, the touch screen does not
{
    const { emulator, device } = await machine(["keyboard", "tablet", "multitouch"]);
    emulator.bus.send("mouse-absolute", [360, 640, 720, 1280]);
    emulator.bus.send("mouse-click", [true, false, false]);
    assert.deepEqual(take(device("multitouch")), [], "the touch screen leaves the mouse to the tablet");
    assert.ok(take(device("tablet")).length > 0, "the tablet takes it");
    // (the page's cursor is the tablet's to hide, whichever driver runs last)
    const absolute = [];
    emulator.add_listener("absolute-pointer", state => absolute.push(state));
    for(const kind of ["multitouch", "tablet"]) device(kind).virtio.device_status = 4;
    await emulator.restore_state(await emulator.save_state());
    assert.deepEqual(absolute, [[true, true]], "only the tablet says how the pointer is (the guest draws its cursor)");
    await emulator.destroy();
    console.log("PASS: with a tablet, the tablet takes the mouse");
}

// the page's mouse adapter (src/browser/mouse.js) takes the mouse and touches
// over the screen only after "mouse-enable": a pointing device says so while
// its driver runs (DRIVER_OK; here a state with it restored), and stops on a
// reset; the keyboard does not (the virt machine has no PS/2 mouse to say it,
// and a MacBook's trackpad reached no device)
{
    const { emulator, device } = await machine(["keyboard", "multitouch"]);
    const said = [];
    emulator.add_listener("mouse-enable", enabled => said.push(enabled));
    const absolute = [];
    emulator.add_listener("absolute-pointer", state => absolute.push(state));
    const DRIVER_OK = 4;
    for(const kind of ["keyboard", "multitouch"]) device(kind).virtio.device_status = DRIVER_OK;
    await emulator.restore_state(await emulator.save_state());
    assert.deepEqual(said, [true], "the touch screen's driver runs: the page takes the pointer (not for the keyboard)");
    assert.deepEqual(absolute, [[true, false]], "absolute positions, no cursor of the guest's: no pointer lock, the host's cursor stays");
    device("multitouch").virtio.reset();
    assert.deepEqual(said, [true, false], "a reset: the page leaves the pointer");
    assert.deepEqual(absolute, [[true, false], [false, false]]);
    await emulator.destroy();
    console.log("PASS: a pointing device tells the page when its driver runs (mouse-enable)");
}
                                                                                                                                                                                                                 source/v64/tests/android/fixtures.mjs                                                               0000644 0000000 0000000 00000036346 00000000000 015046  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Small synthetic Android images for src/android/'s tests
// (docs/android-images-plan.md I1, I3): sparse images, vbmeta structs, super
// with liblp metadata, erofs, zips, boot images, and a Cuttlefish-like images
// zip (tests/android/library.mjs; tests/android/make_package.mjs writes one
// for the wizard's browser test).

import { crc32 as zlib_crc32, deflateRawSync as deflate_raw_sync, gzipSync as gzip_sync } from "node:zlib";
import { put16, put32, put64, put32be, put64be, bytes_of, concat, crc32c } from "../../src/android/bytes.js";
import { lp_checksum } from "../../src/android/lp.js";
import { lz4_legacy_store } from "../../src/android/lz4.js";
import { cpio_newc } from "../../src/android/cpio.js";

const SECTOR = 512;
let seed = 12345;
/** random bytes, the same each run */
export const random = n => Uint8Array.from({ length: n }, () => (seed = seed * 1103515245 + 12345 >>> 0) >>> 24);
/** read(offset, length) over bytes */
export const reader = image => (offset, length) => image.subarray(offset, offset + length);

/** a sparse image of chunks [type, blocks, data] and the raw image it stands for */
export function make_sparse(chunks, block = 4096)
{
    const parts = [], raw = [];
    let total = 0;
    for(const [type, blocks, data] of chunks)
    {
        const header = new Uint8Array(12);
        put16(header, 0, type);
        put32(header, 4, blocks);
        put32(header, 8, 12 + data.length);
        parts.push(header, data);
        if(type === 0xCAC1) raw.push(data);
        else if(type === 0xCAC2) raw.push(Uint8Array.from({ length: blocks * block }, (_, i) => data[i % 4]));
        else if(type === 0xCAC3) raw.push(new Uint8Array(blocks * block));
        if(type !== 0xCAC4) total += blocks;
    }
    const header = new Uint8Array(28);
    put32(header, 0, 0xED26FF3A); put16(header, 4, 1); put16(header, 8, 28); put16(header, 10, 12);
    put32(header, 12, block); put32(header, 16, total); put32(header, 20, chunks.length);
    return { sparse: concat([header, ...parts]), raw: concat(raw) };
}

/** a vbmeta struct with descriptors (hashtree: { partition, size, salt },
 * chain: { partition }) and flags */
export function make_vbmeta(descriptors, flags = 0)
{
    const parts = [];
    for(const d of descriptors)
    {
        let body;
        if(d.chain)
        {
            body = new Uint8Array(92 + Math.ceil(d.chain.length / 8) * 8);
            put64be(body, 0, 4);
            put32be(body, 20, d.chain.length);
            body.set(bytes_of(d.chain), 92);
        }
        else
        {
            const name = d.partition, salt = d.salt, length = 180 + name.length + salt.length + 32;
            body = new Uint8Array(Math.ceil(length / 8) * 8);
            put64be(body, 0, 1);
            put64be(body, 20, d.size);
            put32be(body, 44, 4096);
            put32be(body, 48, 4096);
            body.set(bytes_of("sha256"), 72);
            put32be(body, 104, name.length);
            put32be(body, 108, salt.length);
            put32be(body, 112, 32);
            body.set(bytes_of(name), 180);
            body.set(salt, 180 + name.length);
        }
        put64be(body, 8, body.length - 16);
        parts.push(body);
    }
    const aux = concat(parts);
    const header = new Uint8Array(256);
    header.set(bytes_of("AVB0"), 0);
    put64be(header, 20, aux.length);
    put64be(header, 96, 0);
    put64be(header, 104, aux.length);
    put32be(header, 120, flags);
    return concat([header, aux]);
}

/** an image with an AVB footer pointing at struct after its data */
export function with_footer(data, struct)
{
    const out = new Uint8Array(data.length + struct.length + 64);
    out.set(data);
    out.set(struct, data.length);
    const f = out.length - 64;
    out.set(bytes_of("AVBf"), f);
    put64be(out, f + 12, data.length);
    put64be(out, f + 20, data.length);
    put64be(out, f + 28, struct.length);
    return out;
}

/** super with liblp metadata (2 slots) for partitions [name, sectors at
 * sector] in group "g", alignment 1 MiB */
export function make_super(partitions, size)
{
    const max = 65536, slots = 2;
    const header_size = 256;
    const table = (entries, entry_size) => ({ entries, entry_size });
    const p_table = table(partitions.map(([name], i) =>
    {
        const e = new Uint8Array(52);
        e.set(bytes_of(name));
        put32(e, 40, i); put32(e, 44, 1); put32(e, 48, 1);
        return e;
    }), 52);
    const x_table = table(partitions.map(([, sectors, sector]) =>
    {
        const e = new Uint8Array(24);
        put64(e, 0, sectors); put32(e, 8, 0); put64(e, 12, sector);
        return e;
    }), 24);
    const groups = table(["default", "g"].map(name => { const e = new Uint8Array(48); e.set(bytes_of(name)); return e; }), 48);
    const device = new Uint8Array(64);
    put64(device, 0, 2048); put32(device, 8, 1 << 20); put64(device, 16, size); device.set(bytes_of("super"), 24);
    const devices = table([device], 64);
    const tables = [p_table, x_table, groups, devices];
    const header = new Uint8Array(header_size);
    put32(header, 0, 0x414C5030); put16(header, 4, 10); put16(header, 6, 2); put32(header, 8, header_size);
    let offset = 0;
    tables.forEach((t, i) =>
    {
        put32(header, 80 + 12 * i, offset);
        put32(header, 84 + 12 * i, t.entries.length);
        put32(header, 88 + 12 * i, t.entry_size);
        offset += t.entries.length * t.entry_size;
    });
    put32(header, 44, offset);
    const metadata = concat([header, ...tables.flatMap(t => t.entries)]);
    lp_checksum(metadata);
    const image = new Uint8Array(size);
    const geometry = new Uint8Array(52);
    put32(geometry, 0, 0x616C4467); put32(geometry, 4, 52); put32(geometry, 40, max); put32(geometry, 44, slots); put32(geometry, 48, 4096);
    image.set(geometry, 4096);
    image.set(geometry, 8192);
    for(let i = 0; i < 2 * slots; i++) image.set(metadata, 4096 + 2 * 4096 + max * i);
    return image;
}

/** a 4 KiB erofs image: the root (with xattrs) holding "hello" (flat
 * plain) and "tail" (flat inline) */
export function make_erofs()
{
    const B = 4096, image = new Uint8Array(4 * B);
    const sb = 1024;
    put32(image, sb, 0xE0F5E1E2); image[sb + 12] = 12; put16(image, sb + 14, 0);
    put64(image, sb + 16, 3); put32(image, sb + 36, 4); put32(image, sb + 40, 1);
    put32(image, sb + 8, 1);
    const inode = (nid, layout, mode, size, block, xattr_count) =>
    {
        const at = B + nid * 32;
        put16(image, at, layout << 1); put16(image, at + 2, xattr_count); put16(image, at + 4, mode);
        put16(image, at + 6, 1); put32(image, at + 8, size); put32(image, at + 16, block); put32(image, at + 20, nid + 1);
        return at;
    };
    const dir = new Uint8Array(B);
    const entries = [[0, 2, "."], [0, 2, ".."], [2, 1, "hello"], [4, 1, "tail"]];
    let name_at = entries.length * 12;
    entries.forEach(([nid, type, name], i) =>
    {
        put64(dir, i * 12, nid); put16(dir, i * 12 + 8, name_at); dir[i * 12 + 10] = type;
        dir.set(bytes_of(name), name_at);
        name_at += name.length;
    });
    image.set(dir, 2 * B);
    const root = inode(0, 0, 0o40755, name_at, 2, 1);
    put32(image, root + 32, 0x12345678);
    inode(2, 0, 0o100644, 5, 3, 0);
    image.set(bytes_of("world"), 3 * B);
    const tail = inode(4, 2, 0o100644, 3, 0, 0);
    image.set(bytes_of("end"), tail + 32);
    put32(image, sb + 4, crc32c(0xFFFFFFFF, image.subarray(sb, B)));
    return image;
}

/** a zip of members [{ name, data, store }], with zip64's fields when zip64 */
export function make_zip(members, zip64 = false, comment = "")
{
    const parts = [], central = [];
    let offset = 0;
    for(const { name, data, store } of members)
    {
        const compressed = store ? data : new Uint8Array(deflate_raw_sync(data));
        const crc = zlib_crc32(data), n = bytes_of(name), big = zip64 ? 0xFFFFFFFF : 0;
        const local = new Uint8Array(30 + n.length);
        put32(local, 0, 0x04034B50); put16(local, 4, 20); put16(local, 8, store ? 0 : 8); put32(local, 14, crc);
        put32(local, 18, big || compressed.length); put32(local, 22, big || data.length); put16(local, 26, n.length);
        local.set(n, 30);
        parts.push(local, compressed);
        const extra = new Uint8Array(zip64 ? 28 : 0);
        if(zip64) { put16(extra, 0, 1); put16(extra, 2, 24); put64(extra, 4, data.length); put64(extra, 12, compressed.length); put64(extra, 20, offset); }
        const c = new Uint8Array(46 + n.length + extra.length);
        put32(c, 0, 0x02014B50); put16(c, 4, 45); put16(c, 6, 45); put16(c, 10, store ? 0 : 8); put32(c, 16, crc);
        put32(c, 20, big || compressed.length); put32(c, 24, big || data.length);
        put16(c, 28, n.length); put16(c, 30, extra.length); put32(c, 42, big || offset);
        c.set(n, 46); c.set(extra, 46 + n.length);
        central.push(c);
        offset += local.length + compressed.length;
    }
    const cd = concat(central), tail = [];
    if(zip64)
    {
        const z = new Uint8Array(56);
        put32(z, 0, 0x06064B50); put64(z, 4, 44); put16(z, 12, 45); put16(z, 14, 45);
        put64(z, 24, members.length); put64(z, 32, members.length); put64(z, 40, cd.length); put64(z, 48, offset);
        const locator = new Uint8Array(20);
        put32(locator, 0, 0x07064B50); put64(locator, 8, offset + cd.length); put32(locator, 16, 1);
        tail.push(z, locator);
    }
    const e = new Uint8Array(22);
    put32(e, 0, 0x06054B50);
    put16(e, 8, zip64 ? 0xFFFF : members.length); put16(e, 10, zip64 ? 0xFFFF : members.length);
    put32(e, 12, zip64 ? 0xFFFFFFFF : cd.length); put32(e, 16, zip64 ? 0xFFFFFFFF : offset); put16(e, 20, comment.length);
    return concat([...parts, cd, ...tail, e, bytes_of(comment)]);
}

/** boot.img / init_boot.img (header version 4) */
export function make_boot(kernel, ramdisk, cmdline)
{
    const page = 4096, align = n => Math.ceil(n / page) * page;
    const out = new Uint8Array(page + align(kernel.length) + align(ramdisk.length));
    out.set(bytes_of("ANDROID!"));
    put32(out, 8, kernel.length); put32(out, 12, ramdisk.length); put32(out, 16, 0x1234); put32(out, 20, 1584); put32(out, 40, 4);
    out.set(bytes_of(cmdline), 44);
    out.set(kernel, page);
    out.set(ramdisk, page + align(kernel.length));
    return out;
}

/** vendor_boot.img, header version 4, ramdisks [name, bytes] */
export function make_vendor_boot(ramdisks, cmdline, bootconfig)
{
    const page = 2048, align = n => Math.ceil(n / page) * page;
    const ramdisk = concat(ramdisks.map(r => r[1]));
    const table = new Uint8Array(ramdisks.length * 108);
    let offset = 0;
    ramdisks.forEach(([name, data], i) =>
    {
        put32(table, i * 108, data.length); put32(table, i * 108 + 4, offset); put32(table, i * 108 + 8, i + 1);
        table.set(bytes_of(name), i * 108 + 12);
        offset += data.length;
    });
    const header = new Uint8Array(align(2128));
    header.set(bytes_of("VNDRBOOT")); put32(header, 8, 4); put32(header, 12, page); put32(header, 24, ramdisk.length);
    header.set(bytes_of(cmdline), 28);
    put32(header, 2096, 2128); put32(header, 2100, 0); put32(header, 2112, table.length); put32(header, 2116, ramdisks.length);
    put32(header, 2120, 108); put32(header, 2124, bootconfig.length);
    const pad = b => concat([b, new Uint8Array(align(b.length) - b.length)]);
    return concat([header, pad(ramdisk), pad(table), bytes_of(bootconfig)]);
}

/** A Cuttlefish-like images zip: fastboot-info.txt, boot images (an arm64
 * Image), four vbmeta, a sparse super of 16 MiB with system_a and vendor_a,
 * userdata; and its parts */
export function make_cuttlefish_package()
{
    const MiB = 2048;
    const super_raw = make_super([["system_a", MiB, MiB], ["vendor_a", MiB, 2 * MiB]], 16 << 20);
    super_raw.set(random(4096), MiB * SECTOR);
    super_raw.set(random(4096), 2 * MiB * SECTOR);
    const raw_blocks = 3 * MiB * SECTOR / 4096;
    const { sparse } = make_sparse([[0xCAC1, raw_blocks, super_raw.subarray(0, raw_blocks * 4096)], [0xCAC3, (16 << 20) / 4096 - raw_blocks, new Uint8Array(0)]]);
    const kernel = random(8192);
    kernel.set(bytes_of("ARMd"), 56);
    const images = {
        "boot.img": make_boot(kernel, new Uint8Array(0), ""), "init_boot.img": make_boot(new Uint8Array(0), random(50), ""),
        "vendor_boot.img": make_vendor_boot([["r", lz4_legacy_store(cpio_newc([["prop.default", bytes_of("ro.vendor.build.version.sdk_full=36.1\n")]]))]], "", ""),
        "vbmeta.img": make_vbmeta([]),
        "vbmeta_system.img": make_vbmeta([]), "vbmeta_vendor_dlkm.img": make_vbmeta([]), "vbmeta_system_dlkm.img": make_vbmeta([]),
    };
    const members = [{ name: "fastboot-info.txt", data: bytes_of("# cuttlefish\nversion 1\n") }, { name: "android-info.txt", data: bytes_of("config=phone\n") },
        ...Object.entries(images).map(([name, data]) => ({ name, data })), { name: "super.img", data: sparse },
        { name: "userdata.img", data: make_sparse([[0xCAC3, 4, new Uint8Array(0)]]).sparse }];
    return { zip: make_zip(members), images, super_raw, MiB };
}

/** A GSI zip: system.img (an ext4 magic, 1 MiB; or as a sparse image),
 * vbmeta.img (verification disabled), build.prop at sdk_full */
export function make_gsi_package(sdk_full = "36.1", sparse = false)
{
    const system = random(1 << 20);
    system[1080] = 0x53; system[1081] = 0xEF;
    const image = sparse ? make_sparse([[0xCAC1, 128, system.subarray(0, 128 * 4096)], [0xCAC3, 64, new Uint8Array(0)], [0xCAC1, 64, system.subarray(192 * 4096)]]) : null;
    if(sparse) system.fill(0, 128 * 4096, 192 * 4096);
    return { system, zip: make_zip([{ name: "system.img", data: sparse ? image.sparse : system }, { name: "vbmeta.img", data: make_vbmeta([], 2) },
        { name: "build.prop", data: bytes_of(`ro.system.build.version.release=16\nro.system.build.version.sdk_full=${sdk_full}\nro.system.product.cpu.abilist32=armeabi-v7a\n`) }]) };
}

/** An Android Emulator system image zip (the SDK's layout: everything in
 * the ABI's directory): source.properties of `api` and `abi`, build.prop,
 * kernel-ranchu, ramdisk.img (a gzip-compressed cpio with init.ranchu.rc
 * and an init), system.img (an ext4 magic, 1 MiB; or as a sparse image)
 * and userdata.img (an ext4 magic, 512 KiB) */
export function make_emulator_package(api = 25, abi = "armeabi-v7a", sparse = false)
{
    const kernel = random(5000);
    const ramdisk = new Uint8Array(gzip_sync(cpio_newc([["init.ranchu.rc", bytes_of("on boot\n    setprop ro.fixture 1\n")], ["init", random(2000)]])));
    const system = random(1 << 20), userdata = random(1 << 19);
    for(const fs of [system, userdata]) { fs[1080] = 0x53; fs[1081] = 0xEF; }
    const image = sparse ? make_sparse([[0xCAC1, 128, system.subarray(0, 128 * 4096)], [0xCAC3, 64, new Uint8Array(0)], [0xCAC1, 64, system.subarray(192 * 4096)]]) : null;
    if(sparse) system.fill(0, 128 * 4096, 192 * 4096);
    const dir = abi + "/";
    return { kernel, ramdisk, system, userdata, zip: make_zip([
        { name: dir + "source.properties", data: bytes_of(`Pkg.Revision=18\nAndroidVersion.ApiLevel=${api}\nSystemImage.Abi=${abi}\nSystemImage.TagId=google_apis\n`) },
        { name: dir + "build.prop", data: bytes_of("ro.build.version.release=7.1.1\nro.build.version.sdk=25\n") },
        { name: dir + "kernel-ranchu", data: kernel }, { name: dir + "ramdisk.img", data: ramdisk },
        { name: dir + "system.img", data: sparse ? image.sparse : system }, { name: dir + "userdata.img", data: userdata },
    ]) };
}
                                                                                                                                                                                                                                                                                          source/v64/tests/android/library.mjs                                                                0000644 0000000 0000000 00000107651 00000000000 014637  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// src/android/'s image library (docs/android-images-plan.md I1) on small
// synthetic images: each format read back as written, against node's own
// CRC-32 and SHA-256. tools/a64_android.mjs's byte-identical outputs check
// the library on Cuttlefish's real images.

import assert from "node:assert/strict";
import { crc32 as zlib_crc32 } from "node:zlib";
import { createHash as create_hash } from "node:crypto";
import * as bytes from "../../src/android/bytes.js";
import { parse_boot_image, parse_vendor_boot_image } from "../../src/android/bootimg.js";
import { lz4_legacy_decompress, lz4_legacy_store } from "../../src/android/lz4.js";
import { cpio_files, cpio_newc } from "../../src/android/cpio.js";
import { parse_bootconfig, append_bootconfig } from "../../src/android/bootconfig.js";
import { is_sparse, sparse_size, unsparse, sparse_read, sparse_decoder } from "../../src/android/sparse.js";
import { vbmeta_struct, partition_vbmeta, vbmeta_digest, hashtree_descriptor, avb_hashtree, AVB_FLAG_VERIFICATION_DISABLED } from "../../src/android/avb.js";
import { lp_metadata, lp_checksum, lp_end, lp_parse, lp_serialize, lp_resize, lp_remove, lp_place, super_replace, super_footer_struct, super_partition } from "../../src/android/lp.js";
import { zip_entries, zip_stream, zip_read } from "../../src/android/zip.js";
import { erofs_root, erofs_data, erofs_entries, erofs_list, erofs_lookup, erofs_add_file, erofs_replace_files } from "../../src/android/erofs.js";
import { SECTOR, guid_bytes, guid_text, name_guid, gpt_layout, gpt_writes, gpt_partitions } from "../../src/android/gpt.js";
import { CF_ARM64_ONLY_PHONE, device_partitions, device_bootconfig } from "../../src/android/devices.js";
import { android_boot } from "../../src/android/boot.js";

const { u16, u32, u64, u32be, u64be, put16, put32, put64, put32be, put64be, latin1, bytes_of, concat, equals } = bytes;
const sha = (...parts) => { const h = create_hash("sha256"); for(const p of parts) h.update(p); return new Uint8Array(h.digest()); };
import { random, reader, make_sparse, make_vbmeta, with_footer, make_super, make_erofs, make_zip, make_boot, make_vendor_boot,
    make_cuttlefish_package, make_gsi_package, make_emulator_package } from "./fixtures.mjs";
const run = async (name, f) => { await f(); console.log("ok " + name); };

await run("bytes", () =>
{
    const b = new Uint8Array(16);
    put64(b, 0, 2 ** 40 + 5); put64be(b, 8, 2 ** 45 + 7);
    assert.equal(u64(b, 0), 2 ** 40 + 5);
    assert.equal(u64be(b, 8), 2 ** 45 + 7);
    put32(b, 0, 0xFEDCBA98); put32be(b, 4, 0xFEDCBA98); put16(b, 8, 0xBEEF);
    assert.equal(u32(b, 0), 0xFEDCBA98);
    assert.equal(u32be(b, 4), 0xFEDCBA98);
    assert.equal(u16(b, 8), 0xBEEF);
    for(const n of [0, 1, 1000, 70000])
    {
        const data = random(n);
        assert.equal(bytes.crc32(data), zlib_crc32(data));
        assert.equal(bytes.crc32(data.subarray(n >> 1), bytes.crc32(data.subarray(0, n >> 1))), zlib_crc32(data));
        assert.deepEqual(bytes.sha256(data), sha(data));
        assert.equal(bytes.sha256_hex(data.subarray(0, n >> 1), data.subarray(n >> 1)), bytes.hex(sha(data)));
    }
    // CRC-32C's check value, with the inversion erofs leaves out
    assert.equal((bytes.crc32c(0xFFFFFFFF, bytes_of("123456789")) ^ 0xFFFFFFFF) >>> 0, 0xE3069283);
    const text = latin1(Uint8Array.from({ length: 100000 }, (_, i) => i & 0xFF));
    assert.equal(text.length, 100000);
    assert.equal(text.charCodeAt(99999), 99999 & 0xFF);
    assert.equal(bytes.c_string(bytes_of("abc\0def"), 0, 7), "abc");
    assert.equal(bytes.index_of(bytes_of("xxabcabd"), bytes_of("abd")), 5);
    assert.equal(bytes.index_of(bytes_of("xxabcab"), bytes_of("abd")), -1);
    assert.equal(bytes.compare(bytes_of("ab"), bytes_of("abc")), -1);
    assert.equal(bytes.compare(bytes_of("b"), bytes_of("abc")), 1);
    assert.deepEqual(bytes.utf16le("Az"), new Uint8Array([0x41, 0, 0x7A, 0]));
});

await run("lz4", () =>
{
    // a block with a match: "abc", then 9 bytes 3 back, then "x"
    const block = new Uint8Array([0x35, 0x61, 0x62, 0x63, 3, 0, 0x10, 0x78]);
    const frame = new Uint8Array(4 + 4 + block.length);
    put32(frame, 0, 0x184C2102);
    put32(frame, 4, block.length);
    frame.set(block, 8);
    assert.equal(latin1(lz4_legacy_decompress(frame)), "abcabcabcabcx");
    // (two frames one after another: the kernel's concatenated ramdisks)
    assert.equal(latin1(lz4_legacy_decompress(concat([frame, frame]))), "abcabcabcabcxabcabcabcabcx");
    for(const n of [0, 1, 14, 15, 16, 269, 270, 271, (8 << 20) + 3])
    {
        const data = random(n);
        assert.ok(equals(lz4_legacy_decompress(lz4_legacy_store(data)), data), "lz4 store " + n);
    }
});

await run("cpio", () =>
{
    const files = [["lib/modules/a.ko", random(5)], ["init", random(4096)], ["x", new Uint8Array(0)]];
    const back = cpio_files(cpio_newc(files));
    assert.deepEqual([...back.keys()], files.map(f => f[0]));
    for(const [name, data] of files) assert.ok(equals(back.get(name), data), name);
});

await run("bootconfig", () =>
{
    const map = parse_bootconfig("# comment\nandroidboot.a = 1\n androidboot.b=\"two words\"\n\nbad line\n");
    assert.deepEqual([...map], [["androidboot.a", "1"], ["androidboot.b", "two words"]]);
    for(const n of [0, 1, 2, 3])
    {
        const initrd = random(n);
        const out = append_bootconfig(initrd, map);
        assert.equal(out.length % 4, 0);
        assert.equal(latin1(out, out.length - 12), "#BOOTCONFIG\n");
        const size = u32(out, out.length - 20), checksum = u32(out, out.length - 16);
        const data = out.subarray(out.length - 20 - size, out.length - 20);
        assert.equal(data.reduce((s, x) => s + x, 0), checksum);
        assert.ok(equals(out.subarray(0, n), initrd));
        assert.equal(latin1(data).replace(/\0+$/, ""), "androidboot.a = \"1\"\nandroidboot.b = \"two words\"\n");
    }
});

await run("sparse", () =>
{
    const { sparse, raw } = make_sparse([[0xCAC1, 2, random(8192)], [0xCAC2, 3, new Uint8Array([0x11, 0x22, 0x33, 0x44])],
        [0xCAC3, 2, new Uint8Array(0)], [0xCAC2, 1, new Uint8Array(4)], [0xCAC4, 0, random(4)], [0xCAC1, 1, random(4096)]]);
    const read = reader(sparse);
    assert.ok(is_sparse(read));
    assert.ok(!is_sparse(reader(raw)));
    assert.equal(sparse_size(read), raw.length);
    const out = new Uint8Array(raw.length).fill(0);
    const writes = [];
    assert.equal(unsparse(read, (at, data) => { writes.push([at, data.length]); out.set(data, at); }, 5000), raw.length);
    assert.ok(equals(out, raw));
    // (zero fills and "don't care" are not written; pieces of at most 5000 bytes)
    assert.ok(writes.every(([, n]) => n <= 5000));
    assert.equal(writes.reduce((s, [, n]) => s + n, 0), 3 * 4096 + 3 * 4096);
    for(const [offset, length] of [[0, 1], [4095, 2], [8000, 9000], [7 * 4096 - 3, 4096 + 6], [0, raw.length], [raw.length - 1, 1]])
    {
        assert.ok(equals(sparse_read(read, offset, length), raw.subarray(offset, offset + length)), `sparse_read ${offset} ${length}`);
    }
    // as a stream, in pieces of any size
    for(const piece of [1, 3, 7, 12, 4096, sparse.length])
    {
        const streamed = new Uint8Array(raw.length);
        const decoder = sparse_decoder((at, data) => streamed.set(data, at), 5000);
        for(let i = 0; i < sparse.length; i += piece)
        {
            decoder.push(sparse.subarray(i, i + piece));
            if(i >= 28) assert.equal(decoder.size(), raw.length);
        }
        assert.equal(decoder.end(), raw.length);
        assert.ok(equals(streamed, raw), "sparse_decoder " + piece);
    }
    const cut = sparse_decoder(() => {});
    cut.push(sparse.subarray(0, sparse.length - 1));
    assert.throws(() => cut.end(), /cut short/);
    assert.throws(() => sparse_decoder(() => {}).push(random(28)), /not a sparse image/);
    const after = sparse_decoder(() => {});
    assert.throws(() => after.push(concat([sparse, new Uint8Array(1)])), /after its last chunk/);
});

await run("avb", () =>
{
    const salt = random(32);
    const top = make_vbmeta([{ chain: "boot" }, { partition: "odm", size: 3 * 4096, salt }]);
    const parsed = vbmeta_struct(top);
    assert.deepEqual(parsed.descriptors, [{ tag: 4, partition: "boot" }, { tag: 1, partition: "odm" }]);
    const boot_struct = make_vbmeta([{ partition: "boot", size: 4096, salt }]);
    const boot = with_footer(random(5000), boot_struct);
    assert.ok(equals(partition_vbmeta(boot).struct, boot_struct));
    const partitions = { vbmeta: top, boot };
    const digest = vbmeta_digest(name => partitions[name]);
    assert.equal(digest.digest, bytes.hex(sha(top, boot_struct)));
    assert.equal(digest.size, top.length + boot_struct.length);
    assert.deepEqual(digest.chained, ["boot"]);
    // verification disabled: libavb loads vbmeta alone
    const off = make_vbmeta([{ chain: "boot" }], AVB_FLAG_VERIFICATION_DISABLED);
    assert.deepEqual(vbmeta_digest(name => ({ vbmeta: off })[name]), { digest: bytes.hex(sha(off)), size: off.length, chained: [] });
    const d = hashtree_descriptor(top, "odm");
    assert.equal(d.image_size, 3 * 4096);
    assert.equal(d.algorithm, "sha256");
    assert.ok(equals(d.salt, salt));
    assert.throws(() => hashtree_descriptor(top, "system"));
    // the tree: one block's image has none; three blocks' one level
    const one = random(4096);
    assert.deepEqual(avb_hashtree(one, salt), { root: sha(salt, one), tree: new Uint8Array(0) });
    const three = random(3 * 4096);
    const level = new Uint8Array(4096);
    for(let i = 0; i < 3; i++) level.set(sha(salt, three.subarray(i * 4096, (i + 1) * 4096)), 32 * i);
    const t = avb_hashtree(three, salt);
    assert.ok(equals(t.tree, level));
    assert.ok(equals(t.root, sha(salt, level)));
    // (a partial last block is hashed padded with zeros; 129 blocks need two levels)
    const big = random(129 * 4096 - 100);
    const t2 = avb_hashtree(big, salt);
    assert.equal(t2.tree.length, 3 * 4096);
});

await run("lp", () =>
{
    const MiB = 2048;
    const image = make_super([["odm_a", 2 * MiB, 2 * MiB], ["system_a", 4 * MiB, 4 * MiB]], 16 << 20);
    const lp = lp_metadata(reader(image));
    assert.equal(lp.copies.length, 4);
    assert.equal(lp.alignment, 1 << 20);
    assert.equal(lp.size, 16 << 20);
    assert.deepEqual(lp.copies[0].partitions.map(p => [p.name, p.extents[0].sectors, p.extents[0].sector]), [["odm_a", 2 * MiB, 2 * MiB], ["system_a", 4 * MiB, 4 * MiB]]);
    assert.equal(lp_end(lp), 8 * MiB);
    // checksums as liblp's: sha256 of the tables, then of the header with its checksum zero
    const m = lp.copies[0].bytes;
    assert.ok(equals(m.subarray(48, 80), sha(m.subarray(256))));
    const h = new Uint8Array(m.subarray(0, 256));
    h.fill(0, 12, 44);
    assert.ok(equals(m.subarray(12, 44), sha(h)));
    // odm_a replaced: moved after system_a, its descriptor and checksums new
    const salt = random(8);
    const odm = random(3 * 4096);
    image.set(odm, 2 * MiB * SECTOR);
    const vbmeta = make_vbmeta([{ partition: "odm", size: odm.length, salt }]);
    assert.ok(equals(super_partition(reader(image), lp, vbmeta, "odm"), odm));
    const space = { sector: lp_end(lp) };
    const bigger = random(5 * 4096);
    const r = super_replace(lp, vbmeta, "odm", bigger, space);
    assert.deepEqual(r.record, { sector: 8 * MiB, sectors: MiB, image_blocks: 5, root_digest: bytes.hex(avb_hashtree(bigger, salt).root), footer: false });
    assert.equal(space.sector, 9 * MiB);
    assert.equal(r.data.offset, 8 * MiB * SECTOR);
    assert.ok(equals(r.data.bytes, concat([bigger, avb_hashtree(bigger, salt).tree])));
    const nd = hashtree_descriptor(r.vbmeta, "odm");
    assert.equal(nd.image_size, bigger.length);
    assert.ok(equals(r.vbmeta.subarray(nd.digest, nd.digest + 32), avb_hashtree(bigger, salt).root));
    assert.equal(hashtree_descriptor(vbmeta, "odm").image_size, odm.length, "the old vbmeta stays as it was");
    for(const copy of lp.copies) image.set(copy.bytes, copy.offset);
    const again = lp_metadata(reader(image));
    assert.deepEqual(again.copies.map(c => c.partitions[0].extents[0].sector), [8 * MiB, 8 * MiB, 8 * MiB, 8 * MiB]);
    assert.ok(equals(again.copies[3].bytes.subarray(48, 80), sha(again.copies[3].bytes.subarray(256))));
    // with an AVB footer: the struct after the tree, the footer at the extent's end
    const struct = make_vbmeta([{ partition: "odm", size: odm.length, salt }]);
    const f = super_replace(lp, r.vbmeta, "odm", bigger, space, struct);
    image.set(f.data.bytes, f.data.offset);
    for(const copy of lp.copies) image.set(copy.bytes, copy.offset);
    const own = super_footer_struct(reader(image), lp_metadata(reader(image)), "odm");
    assert.equal(hashtree_descriptor(own, "odm").image_size, bigger.length);
    assert.throws(() => super_replace(lp, r.vbmeta, "odm", random(9 << 20), space), /no room/);

    // the writer: tables as they were, then changed
    const fresh = make_super([["product_a", MiB, 2 * MiB], ["system_a", 2 * MiB, 3 * MiB], ["system_b", 0, 0]], 16 << 20);
    const lp2 = lp_metadata(reader(fresh));
    for(const copy of lp2.copies) assert.ok(equals(lp_serialize(lp_parse(copy.bytes)), copy.bytes));
    const model = lp_parse(lp2.copies[0].bytes);
    assert.deepEqual(model.partitions.map(p => [p.name, p.group, p.extents.length]), [["product_a", 1, 1], ["system_a", 1, 1], ["system_b", 1, 1]]);
    assert.deepEqual(model.groups.map(g => g.name), ["default", "g"]);
    assert.equal(model.block_devices[0].name, "super");
    const apply = writes => { for(const w of writes) fresh.set(w.bytes, w.offset); };
    apply(lp_remove(lp2, "product_a"));
    apply(lp_place(lp2, "system_a", 6 * MiB, 4 * MiB + 1));
    assert.throws(() => lp_place(lp2, "system_a", 6 * MiB + 1, 1), /unaligned/);
    assert.throws(() => lp_place(lp2, "vendor_a", 6 * MiB, 1), /no vendor_a/);
    assert.throws(() => lp_resize(lp2, 5 << 20), /leave out/);
    apply(lp_resize(lp2, (10 << 20) + 1));
    const lp3 = lp_metadata(reader(fresh));
    assert.equal(lp3.size, 11 << 20);
    assert.equal(lp_end(lp3), 10 * MiB + 1);
    for(const copy of lp3.copies)
    {
        assert.deepEqual(copy.partitions.map(p => [p.name, p.extents.map(e => [e.sectors, e.sector])]), [["system_a", [[4 * MiB + 1, 6 * MiB]]], ["system_b", [[0, 0]]]]);
        assert.ok(equals(copy.bytes.subarray(48, 80), sha(copy.bytes.subarray(256))));
    }
});

await run("erofs", () =>
{
    const image = make_erofs();
    assert.deepEqual(erofs_list(image).map(e => [e.path, e.type]), [["hello", 1], ["tail", 1]]);
    assert.equal(latin1(erofs_data(image, erofs_lookup(image, "hello"))), "world");
    assert.equal(latin1(erofs_data(image, erofs_lookup(image, "tail"))), "end");
    assert.equal(erofs_lookup(image, "nothing"), null);
    const labels = { dir: "u:object_r:vendor_file:s0", file: "u:object_r:same_process_hal_file:s0" };
    const data = random(10000);
    const added = erofs_add_file(image, "lib64/hw/x.so", data, labels);
    assert.ok(equals(erofs_data(added, erofs_lookup(added, "lib64/hw/x.so")), data));
    assert.equal(latin1(erofs_data(added, erofs_lookup(added, "hello"))), "world");
    assert.deepEqual(erofs_list(added).map(e => e.path), ["hello", "lib64", "lib64/hw", "lib64/hw/x.so", "tail"]);
    const file = erofs_lookup(added, "lib64/hw/x.so");
    assert.ok(latin1(added, file.xattrs, file.xattrs + file.xattr_size).includes("selinux" + labels.file));
    assert.equal(u32(added, 1024 + 36) * 4096, added.length);
    assert.equal(u64(added, 1024 + 16), 6);
    const sum = new Uint8Array(added.subarray(1024, 4096));
    put32(sum, 4, 0);
    assert.equal(u32(added, 1024 + 4), bytes.crc32c(0xFFFFFFFF, sum));
    assert.ok(erofs_entries(added, erofs_root(added)).some(e => e.name === "lib64"));
    assert.throws(() => erofs_add_file(added, "lib64/y", data, labels), /exists/);
    const replaced = erofs_replace_files(added, [["hello", random(5000)], ["tail", bytes_of("new tail")], ["lib64/hw/x.so", bytes_of("so")]]);
    assert.equal(erofs_data(replaced, erofs_lookup(replaced, "hello")).length, 5000);
    assert.equal(latin1(erofs_data(replaced, erofs_lookup(replaced, "tail"))), "new tail");
    assert.equal(latin1(erofs_data(replaced, erofs_lookup(replaced, "lib64/hw/x.so"))), "so");
    assert.throws(() => erofs_replace_files(added, [["lib64", data]]), /not a regular file/);
});

await run("gpt", () =>
{
    const guid = "0FC63DAF-8483-4772-8E79-3D69D8477DE4";
    assert.deepEqual([...guid_bytes(guid).subarray(0, 4)], [0xAF, 0x3D, 0xC6, 0x0F]);
    assert.equal(guid_text(guid_bytes(guid)), guid);
    assert.match(name_guid("super"), /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-8[0-9A-F]{3}-[0-9A-F]{12}$/);
    const { partitions, disk_size } = gpt_layout([{ name: "misc", size: 4096 }, { name: "boot_a", size: (1 << 20) + 1 }, { name: "userdata", size: 3 << 20 }]);
    assert.deepEqual(partitions.map(p => [p.name, p.start, p.size]), [["misc", 1 << 20, 4096], ["boot_a", 2 << 20, (1 << 20) + 1], ["userdata", 4 << 20, 3 << 20]]);
    assert.equal(disk_size, 8 << 20);
    // (sizes as whole sectors on the disk)
    partitions[1].size = 2 << 20;
    const disk = new Uint8Array(disk_size);
    for(const w of gpt_writes(disk_size, partitions)) disk.set(w.bytes, w.offset);
    assert.equal(u16(disk, 510), 0xAA55);
    const back = gpt_partitions(reader(disk));
    assert.deepEqual(back.map(p => [p.name, p.start, p.size, p.type]), partitions.map(p => [p.name, p.start, p.size, guid]));
    assert.equal(back[0].guid, name_guid("misc"));
    // the primary header broken: the backup's
    disk[SECTOR + 20] ^= 1;
    assert.throws(() => gpt_partitions(reader(disk)), /no valid header/);
    assert.deepEqual(gpt_partitions(reader(disk), disk_size).map(p => p.name), ["misc", "boot_a", "userdata"]);
});

await run("boot images", () =>
{
    const kernel = random(5000), ramdisk = random(300);
    const boot = parse_boot_image(make_boot(kernel, ramdisk, "a=b"));
    assert.equal(boot.version, 4);
    assert.ok(equals(boot.kernel, kernel));
    assert.ok(equals(boot.ramdisk, ramdisk));
    assert.equal(boot.cmdline, "a=b");
    assert.equal(boot.os_version, 0x1234);
    const r1 = random(3000), r2 = random(10);
    const vendor = parse_vendor_boot_image(make_vendor_boot([["first", r1], ["dlkm", r2]], "v=1", "androidboot.x=1\n"));
    assert.equal(vendor.cmdline, "v=1");
    assert.deepEqual(vendor.ramdisks.map(r => [r.type, r.name, r.bytes.length]), [[1, "first", 3000], [2, "dlkm", 10]]);
    assert.ok(equals(vendor.ramdisk, concat([r1, r2])));
    assert.equal(vendor.bootconfig, "androidboot.x=1\n");
    assert.throws(() => parse_boot_image(random(100)), /not a boot image/);
});

await run("device and bootloader", () =>
{
    const device = CF_ARM64_ONLY_PHONE;
    const names = device_partitions(device).map(p => p.name);
    assert.equal(names.length, 19);
    assert.deepEqual(names.slice(0, 3), ["misc", "boot_a", "boot_b"]);
    assert.deepEqual(names.slice(-4), ["super", "userdata", "metadata", "frp"]);
    const vbmeta = { size: 1, digest: "00" };
    const swiftshader = device_bootconfig(device, { vbmeta, memory_mb: 2048 });
    const venus = device_bootconfig(device, { vbmeta, memory_mb: 2048, gpu_mode: "venus", selinux: "permissive", page_size: 16384 });
    assert.equal(swiftshader.get("androidboot.hardware.vulkan"), "pastel");
    assert.equal(swiftshader.get("androidboot.ddr_size"), "2048MB");
    assert.equal(swiftshader.has("androidboot.selinux"), false);
    assert.equal(venus.get("androidboot.hardware.vulkan"), "virtio");
    assert.equal(venus.get("androidboot.selinux"), "permissive");
    assert.equal(venus.get("androidboot.fstab_suffix"), "cf.ext4.hctr2");
    // (Venus's new key last, the ones it changes where they were)
    assert.deepEqual([...venus.keys()].slice(-2), ["androidboot.opengles.version", "androidboot.hardware.hwcomposer.mode"]);
    assert.throws(() => device_bootconfig(device, { vbmeta, memory_mb: 1, gpu_mode: "virgl" }), /no GPU mode/);
    // gfxstream_guest_angle's keys, as Cuttlefish's launcher writes them, but
    // composed on the client (as Venus's) and OpenGL ES 3.0
    const gfxstream = device_bootconfig(device, { vbmeta, memory_mb: 2048, gpu_mode: "gfxstream" });
    assert.deepEqual(["cpuvulkan.version", "hardware.vulkan", "hardware.gltransport", "hardware.egl", "opengles.version", "hardware.hwcomposer",
        "hardware.hwcomposer.mode"].map(k => gfxstream.get("androidboot." + k)), ["0", "ranchu", "virtio-gpu-asg", "angle", "196608", "ranchu", "client"]);

    const kernel = random(8192), generic = random(100), vendor_ramdisk = random(200);
    const top = make_vbmeta([{ chain: "boot" }], AVB_FLAG_VERIFICATION_DISABLED);
    const partitions = { boot: make_boot(kernel, new Uint8Array(0), "b=2"), init_boot: make_boot(new Uint8Array(0), generic, ""),
        vendor_boot: make_vendor_boot([["r", vendor_ramdisk]], "v=1", "androidboot.vendor=yes\nandroidboot.hardware.vulkan=x\n"), vbmeta: top };
    const read = name => partitions[name];
    const m = android_boot(read, device, { memory_mb: 1536 });
    assert.ok(equals(m.kernel, kernel));
    assert.equal(m.cmdline, "v=1 b=2 " + device.cmdline_tail);
    assert.equal(m.vbmeta.digest, bytes.hex(sha(top)));
    assert.deepEqual([...m.bootconfig.keys()].slice(0, 3), ["androidboot.vendor", "androidboot.hardware.vulkan", "androidboot.slot_suffix"]);
    assert.equal(m.bootconfig.get("androidboot.hardware.vulkan"), "pastel");
    assert.ok(equals(m.initrd, append_bootconfig(concat([vendor_ramdisk, generic]), m.bootconfig)));
    const extra = random(7), debug = random(9);
    const m2 = android_boot(read, device, { memory_mb: 1536, vendor_ramdisk: debug, extra_ramdisk: extra, gpu_mode: "venus" });
    assert.ok(equals(m2.initrd.subarray(0, 9 + 7 + 100), concat([debug, extra, generic])));
    assert.equal(m2.bootconfig.get("androidboot.hardware.vulkan"), "virtio");
});

await run("zip", async () =>
{
    const pattern = Uint8Array.from({ length: 3 << 20 }, (_, i) => (i * 7) % 251);
    const members = [{ name: "boot.img", data: random(300000) }, { name: "stored.txt", data: bytes_of("hello"), store: true },
        { name: "pattern.img", data: pattern }, { name: "empty", data: new Uint8Array(0) }];
    for(const zip64 of [false, true])
    {
        const archive = make_zip(members, zip64, "a comment");
        const sync_read = reader(archive);
        // (reads as promises: a File's slices)
        const async_read = async (offset, length) => sync_read(offset, length);
        const entries = await zip_entries(async_read, archive.length);
        assert.deepEqual(entries.map(e => [e.name, e.method, e.size]), members.map(m => [m.name, m.store ? 0 : 8, m.data.length]));
        for(const [i, m] of members.entries())
        {
            assert.ok(equals(await zip_read(sync_read, entries[i]), m.data), m.name);
            const pieces = [];
            const n = await zip_stream(async_read, entries[i], async bytes => { pieces.push(bytes.slice()); }, { chunk: 1000 });
            assert.equal(n, m.data.length);
            assert.ok(equals(concat(pieces), m.data), m.name + " in pieces");
        }
        assert.ok(equals(await zip_read(sync_read, entries[2], 10), pattern.subarray(0, 10)));
    }
    const archive = make_zip(members);
    const entries = await zip_entries(reader(archive), archive.length);
    // a stored member's byte changed: its CRC-32
    const broken = new Uint8Array(archive);
    broken[entries[1].offset + 30 + "stored.txt".length] ^= 1;
    await assert.rejects(zip_read(reader(broken), entries[1]), /CRC-32 differs/);
    // a deflated member broken, a read failing, the sink failing: errors, not hangs
    const garbage = new Uint8Array(archive);
    garbage.fill(0xFF, entries[0].offset + 40, entries[0].offset + 40 + 64);
    await assert.rejects(zip_read(reader(garbage), entries[0]));
    let reads = 0;
    const failing = async (offset, length) => { if(++reads > 3) throw new Error("read failed"); return archive.subarray(offset, offset + length); };
    await assert.rejects(zip_stream(failing, entries[2], () => {}, { chunk: 4096 }), /read failed/);
    await assert.rejects(zip_stream(reader(archive), entries[2], () => { throw new Error("sink failed"); }, { chunk: 4096 }), /sink failed/);
    await assert.rejects(zip_entries(reader(random(1000)), 1000), /no end of central directory/);
    // a sparse member straight into the decoder
    const { sparse, raw } = make_sparse([[0xCAC1, 3, random(3 * 4096)], [0xCAC3, 5, new Uint8Array(0)], [0xCAC2, 2, new Uint8Array([1, 2, 3, 4])]]);
    const z = make_zip([{ name: "super.img", data: sparse }]);
    const [member] = await zip_entries(reader(z), z.length);
    const out = new Uint8Array(raw.length);
    const decoder = sparse_decoder((at, data) => out.set(data, at));
    await zip_stream(reader(z), member, bytes => decoder.push(bytes), { chunk: 777 });
    assert.equal(decoder.end(), raw.length);
    assert.ok(equals(out, raw));
});

await run("assemble a Cuttlefish package", async () =>
{
    const { identify_package, cuttlefish_disk, write_disk, package_entries, SUPER_SLACK } = await import("../../src/android/assemble.js");
    const { zip, images, super_raw, MiB } = make_cuttlefish_package();
    const read = reader(zip);
    const entries = await package_entries(read, zip.length);
    assert.deepEqual(await identify_package(entries, read), { kind: "cuttlefish", device: "cf_arm64_only_phone", text: "a Cuttlefish arm64 device (its images zip)" });
    assert.equal((await identify_package([{ name: "system.img" }, { name: "vbmeta.img" }, { name: "build.prop" }], read)).kind, "gsi");
    assert.equal(await identify_package([{ name: "readme.txt" }], read), null);
    const disk = await cuttlefish_disk(read, entries, { userdata_bytes: 3 << 20 });
    assert.equal(disk.super_size, Math.ceil((3 * MiB * SECTOR + SUPER_SLACK) / (1 << 20)) * (1 << 20));
    const out = new Uint8Array(disk.disk_size);
    const progress = [];
    await write_disk(read, disk, async (offset, bytes) => { out.set(bytes, offset); }, (done, total) => progress.push([done, total]));
    assert.deepEqual(progress.at(-1), [disk.data_bytes, disk.data_bytes]);
    const parts = new Map(gpt_partitions(reader(out), out.length).map(p => [p.name, p]));
    assert.deepEqual([...parts.keys()], device_partitions(CF_ARM64_ONLY_PHONE).map(p => p.name));
    for(const [name, data] of Object.entries(images))
    {
        // (the partition: the image, in whole sectors)
        const p = parts.get(name.replace(".img", "") + "_a");
        assert.equal(p.size, Math.ceil(data.length / SECTOR) * SECTOR, name);
        assert.ok(equals(out.subarray(p.start, p.start + data.length), data), name);
    }
    const sp = parts.get("super");
    assert.equal(sp.size, disk.super_size);
    const lp = lp_metadata(reader(out.subarray(sp.start, sp.start + sp.size)));
    assert.equal(lp.size, disk.super_size);
    assert.deepEqual(lp.copies[0].partitions.map(p => [p.name, p.extents[0].sector]), [["system_a", MiB], ["vendor_a", 2 * MiB]]);
    assert.ok(equals(out.subarray(sp.start + MiB * SECTOR, sp.start + 2 * MiB * SECTOR), super_raw.subarray(MiB * SECTOR, 2 * MiB * SECTOR)));
    assert.equal(parts.get("userdata").size, 3 << 20);
    assert.ok(out.subarray(parts.get("userdata").start, parts.get("userdata").start + (3 << 20)).every(b => b === 0));
});

await run("assemble a Cuttlefish package with a GSI", async () =>
{
    const { cuttlefish_disk, write_disk, package_entries, gsi_package, identify_package } = await import("../../src/android/assemble.js");
    const { zip, images, super_raw, MiB } = make_cuttlefish_package();
    const read = reader(zip);
    const entries = await package_entries(read, zip.length);
    for(const sparse of [false, true])
    {
        const g = make_gsi_package("36.1", sparse);
        const gread = reader(g.zip);
        const gentries = await package_entries(gread, g.zip.length);
        assert.equal((await identify_package(gentries, gread)).kind, "gsi");
        const gsi = await gsi_package(gread, gentries);
        assert.deepEqual([gsi.sdk_full, gsi.release, gsi.abilist32, gsi.size, gsi.sparse], ["36.1", "16", "armeabi-v7a", 1 << 20, sparse]);
        const disk = await cuttlefish_disk(read, entries, { userdata_bytes: 1 << 20, gsi, gsi_read: gread });
        assert.equal(disk.vendor_sdk_full, "36.1");
        const out = new Uint8Array(disk.disk_size);
        await write_disk(read, disk, (offset, bytes) => { out.set(bytes, offset); });
        const parts = new Map(gpt_partitions(reader(out), out.length).map(p => [p.name, p]));
        // (vbmeta: the GSI's; the other images the device's)
        const vb = parts.get("vbmeta_a");
        assert.ok(equals(out.subarray(vb.start, vb.start + 256), make_vbmeta([], 2)));
        assert.ok(equals(out.subarray(parts.get("boot_a").start, parts.get("boot_a").start + images["boot.img"].length), images["boot.img"]));
        const sp = parts.get("super");
        const lp = lp_metadata(reader(out.subarray(sp.start, sp.start + sp.size)));
        const system = lp.copies[0].partitions.find(p => p.name === "system_a").extents[0];
        assert.equal(system.sector, 3 * MiB);
        assert.equal(system.sectors, (1 << 20) / SECTOR);
        assert.ok(lp.copies.every(c => c.partitions.find(p => p.name === "system_a").extents[0].sector === 3 * MiB));
        assert.ok(equals(out.subarray(sp.start + system.sector * SECTOR, sp.start + system.sector * SECTOR + (1 << 20)), g.system), "the GSI's system");
        // (the old system_a's data not written; vendor_a's as it was)
        assert.ok(out.subarray(sp.start + MiB * SECTOR, sp.start + 2 * MiB * SECTOR).every(b => b === 0));
        assert.ok(equals(out.subarray(sp.start + 2 * MiB * SECTOR, sp.start + 3 * MiB * SECTOR), super_raw.subarray(2 * MiB * SECTOR, 3 * MiB * SECTOR)));
        assert.equal(lp.size, Math.ceil(((3 * MiB + 2048) * SECTOR + (64 << 20)) / (1 << 20)) * (1 << 20));
    }
    // a GSI older than the vendor: refused
    const old = make_gsi_package("36.0");
    const oread = reader(old.zip);
    const oentries = await package_entries(oread, old.zip.length);
    await assert.rejects(cuttlefish_disk(read, entries, { userdata_bytes: 1 << 20, gsi: await gsi_package(oread, oentries), gsi_read: oread }), /older than the device's vendor/);
});

await run("assemble an emulator image, its partitions as disks", async () =>
{
    const { emulator_disk, write_disk, package_entries, identify_package } = await import("../../src/android/assemble.js");
    const { android_bootloader } = await import("../../src/android/bootloader.js");
    const { PartitionBuffer } = await import("../../src/android/partition_buffer.js");
    for(const sparse of [false, true])
    {
        const e = make_emulator_package(25, "armeabi-v7a", sparse);
        const read = reader(e.zip);
        const entries = await package_entries(read, e.zip.length);
        const kind = await identify_package(entries, read);
        assert.equal(kind.kind, "emulator");
        const disk = await emulator_disk(read, entries);
        assert.equal(disk.device.id, "ranchu_25_armeabi_v7a");
        assert.deepEqual([disk.api, disk.abi, disk.tag, disk.release], [25, "armeabi-v7a", "google_apis", "7.1.1"]);
        assert.deepEqual(disk.partitions.map(p => p.name), ["kernel", "ramdisk", "system", "cache", "userdata"]);
        const out = new Uint8Array(disk.disk_size);
        await write_disk(read, disk, (offset, bytes) => { out.set(bytes, offset); });
        const parts = new Map(gpt_partitions(reader(out), out.length).map(p => [p.name, p]));
        const at = (name, length) => out.subarray(parts.get(name).start, parts.get(name).start + length);
        assert.ok(equals(at("system", 1 << 20), e.system), "system.img" + (sparse ? " (sparse)" : ""));
        assert.ok(equals(at("userdata", 1 << 19), e.userdata));
        // (an empty ext4 for cache: its superblock)
        assert.equal(u16(at("cache", 2048), 1080), 0xEF53);
        assert.equal(parts.get("cache").size, 64 << 20);
        // the bootloader: the kernel and ramdisk, the emulator's command line, the disks in fstab's order
        const boot = await android_bootloader(async (offset, length) => out.slice(offset, offset + length), out.length,
            { device: "ranchu_25_armeabi_v7a", memory_mb: 1024 });
        assert.ok(equals(boot.kernel.subarray(0, 5000), e.kernel) && boot.kernel.subarray(5000).every(b => b === 0));
        // (the image's ramdisk, then the device model's init additions: src/android/ramdisk_overlay.js)
        assert.ok(equals(boot.initrd.subarray(0, e.ramdisk.length), e.ramdisk));
        const added = cpio_files(boot.initrd.subarray(Math.ceil(e.ramdisk.length / 4) * 4));
        assert.deepEqual([...added.keys()], ["init.ranchu.rc"]);
        assert.match(latin1(added.get("init.ranchu.rc")),
            /^on boot\n {4}setprop ro.fixture 1\n\n# v64 .*\nservice v64_anr \/system\/bin\/sh \/system\/bin\/settings put secure anr_show_background 1\n[^]*on property:sys.boot_completed=1\n {4}start v64_anr\n/);
        assert.equal(boot.clock_rate, 0.1);
        assert.deepEqual(boot.properties, { "ro.config.low_ram": "true", "dalvik.vm.stack-trace-file": "" });
        assert.match(boot.cmdline, /^qemu=1 androidboot.hardware=ranchu console=ttyAMA0 .* qemu\.gles=0 .* android.bootanim=0$/);
        assert.equal(boot.ranchu_gpu, "guest", "no gpu_mode: the guest renders");
        assert.equal(boot.bootconfig, null);
        // the GPU mode "host" (docs/gles-proxy-plan.md): the GLES host, qemu.gles=1, the default GLES version's property
        // (3.1, docs/gles3-plan.md), or the one given
        const host = await android_bootloader(async (offset, length) => out.slice(offset, offset + length), out.length,
            { device: "ranchu_25_armeabi_v7a", gpu_mode: "host", memory_mb: 1024 });
        assert.equal(host.ranchu_gpu, "host");
        assert.match(host.cmdline, / qemu\.gles=1 /);
        assert.deepEqual(host.properties, { "ro.config.low_ram": "true", "dalvik.vm.stack-trace-file": "", "ro.opengles.version": "196609" });
        assert.equal(host.gles_version, "3.1");
        const host32 = await android_bootloader(async (offset, length) => out.slice(offset, offset + length), out.length,
            { device: "ranchu_25_armeabi_v7a", gpu_mode: "host", memory_mb: 1024, gles_version: "3.2" });
        assert.equal(host32.properties["ro.opengles.version"], "196610");
        // (the VM config's default, "swiftshader", is the guest's own rendering here too; Cuttlefish's modes are not ranchu's)
        assert.equal((await android_bootloader(async (offset, length) => out.slice(offset, offset + length), out.length,
            { device: "ranchu_25_armeabi_v7a", gpu_mode: "swiftshader", memory_mb: 1024 })).ranchu_gpu, "guest");
        await assert.rejects(android_bootloader(async (offset, length) => out.slice(offset, offset + length), out.length,
            { device: "ranchu_25_armeabi_v7a", gpu_mode: "venus", memory_mb: 1024 }), /no GPU mode venus \(guest, host\)/);
        assert.deepEqual(boot.disks.map(d => [d.name, d.start, d.size, d.readonly]),
            ["system", "cache", "userdata"].map(name => [name, parts.get(name).start, parts.get(name).size, name === "system"]));
        // a partition as a disk: reads and writes moved by its start; the disk's state once
        const backing = { get: (start, length, done) => done(out.slice(start, start + length)), set: (start, data, done) => { out.set(data, start); done(); },
            get_state: () => ["state"], set_state: () => {}, disk_name: "virtio_disk0" };
        const userdata = new PartitionBuffer(backing, boot.disks[2], true), cache = new PartitionBuffer(backing, boot.disks[1], false);
        assert.equal(userdata.byteLength, parts.get("userdata").size);
        assert.equal(userdata.disk_name, "virtio_disk0:userdata");
        const got = await new Promise(resolve => userdata.get(1080, 2, resolve));
        assert.deepEqual([...got], [0x53, 0xEF]);
        await new Promise(resolve => cache.set(0, new Uint8Array([1, 2, 3]), resolve));
        assert.deepEqual([...at("cache", 3)], [1, 2, 3]);
        assert.deepEqual(userdata.get_state(), [backing]);
        assert.deepEqual(cache.get_state(), []);
    }
    // an image v64 has no device model for: refused, saying which it boots
    const other = make_emulator_package(30, "x86_64");
    const oread = reader(other.zip);
    await assert.rejects(emulator_disk(oread, await package_entries(oread, other.zip.length)), /API 30 for x86_64: v64 boots API 25 armeabi-v7a/);
});
                                                                                       source/v64/tests/android/make_package.mjs                                                           0000644 0000000 0000000 00000002340 00000000000 015550  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// A small Cuttlefish-like images zip (tests/android/fixtures.mjs) for the
// wizard's browser test (tests/app/wizard_test.html part=android and
// android_gsi): build/android-test-package.zip, and GSIs of the vendor's
// version and older, build/android-test-gsi.zip and android-test-gsi-old.zip;
// an Android Emulator image (part=android_emulator), build/android-test-emulator.zip
//
//   node tests/android/make_package.mjs [out directory]

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { make_cuttlefish_package, make_gsi_package, make_emulator_package } from "./fixtures.mjs";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const dir = (process.argv[2] ? path.resolve(process.argv[2]) : ROOT + "build") + "/";
fs.mkdirSync(dir, { recursive: true });
for(const [name, zip] of [["android-test-package.zip", make_cuttlefish_package().zip], ["android-test-gsi.zip", make_gsi_package("36.1").zip],
    ["android-test-gsi-old.zip", make_gsi_package("36.0").zip], ["android-test-emulator.zip", make_emulator_package().zip]])
{
    fs.writeFileSync(dir + name, zip);
    console.log(dir + name + ": " + zip.length + " bytes");
}
                                                                                                                                                                                                                                                                                                source/v64/tests/android/real_images.mjs                                                            0000644 0000000 0000000 00000021635 00000000000 015440  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// src/android/ on the real images, when they are here (each part skipped
// otherwise; docs/android-images-plan.md I1, I2): Cuttlefish's image zip
// and the GSI's zip read as zips, super's metadata written again as it was,
// and the bootloader's work from tools/a64_android.mjs's disk.img giving
// that tool's initrd.img, initrd-venus.img and command line.
//
//   node tests/android/real_images.mjs [--out build/a64-android/out]

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createHash as create_hash } from "node:crypto";
import { equals } from "../../src/android/bytes.js";
import { zip_entries, zip_stream, zip_read } from "../../src/android/zip.js";
import { sparse_read } from "../../src/android/sparse.js";
import { lp_metadata, lp_parse, lp_serialize } from "../../src/android/lp.js";
import { gpt_partitions } from "../../src/android/gpt.js";
import { vbmeta_struct } from "../../src/android/avb.js";
import { CF_ARM64_ONLY_PHONE } from "../../src/android/devices.js";
import { android_boot } from "../../src/android/boot.js";

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const A = ROOT + "build/a64-android/";
const out_arg = process.argv.indexOf("--out");
const OUT = out_arg > 0 ? path.resolve(process.argv[out_arg + 1]) + "/" : A + "out/";

function file_reader(file)
{
    const fd = fs.openSync(file, "r");
    return (offset, length) =>
    {
        const b = Buffer.allocUnsafe(length);
        return b.subarray(0, fs.readSync(fd, b, 0, length, offset));
    };
}
const sha256 = bytes => create_hash("sha256").update(bytes).digest("hex");
let ran = 0;
async function part(name, files, f)
{
    const missing = files.filter(file => !fs.existsSync(file));
    if(missing.length) { console.log(`skip ${name} (no ${missing.map(m => path.relative(ROOT, m)).join(", ")})`); return; }
    const start = Date.now();
    await f();
    ran++;
    console.log(`ok ${name} (${((Date.now() - start) / 1000).toFixed(1)} s)`);
}

const CF_ZIP = A + "dl/aosp_cf_arm64_only_phone-img-15581820.zip";
await part("Cuttlefish image zip", [CF_ZIP, A + "img/boot.img", A + "img/vbmeta.img"], async () =>
{
    const read = file_reader(CF_ZIP);
    const entries = await zip_entries(read, fs.statSync(CF_ZIP).size);
    const names = entries.map(e => e.name).sort();
    for(const name of ["boot.img", "init_boot.img", "vendor_boot.img", "super.img", "userdata.img", "vbmeta.img", "vbmeta_system.img"])
    {
        assert.ok(names.includes(name), name);
    }
    for(const name of ["vbmeta.img", "boot.img"])
    {
        const data = await zip_read(read, entries.find(e => e.name === name));
        assert.ok(equals(data, fs.readFileSync(A + "img/" + name)), name);
    }
    // (super's sparse header, without inflating the rest)
    const head = await zip_read(read, entries.find(e => e.name === "super.img"), 28);
    assert.equal(head.length, 28);
    assert.equal(head[0] | head[1] << 8 | head[2] << 16 | head[3] << 24, 0xED26FF3A | 0);
});

const GSI_ZIP = A + "dl/gsi/aosp_arm64-exp-BP2A.250605.031.A3-13578795-82277143.zip";
await part("GSI zip", [GSI_ZIP], async () =>
{
    const read = file_reader(GSI_ZIP);
    const entries = await zip_entries(read, fs.statSync(GSI_ZIP).size);
    const system = entries.find(e => e.name === "system.img");
    assert.ok(system, "system.img");
    const vbmeta = vbmeta_struct(await zip_read(read, entries.find(e => e.name === "vbmeta.img")));
    assert.equal(vbmeta.flags & 2, 2, "the GSI's vbmeta disables verification");
    // (system.img whole: its CRC-32 and size checked as it inflates)
    const hash = create_hash("sha256");
    assert.equal(await zip_stream(read, system, bytes => { hash.update(bytes); }), system.size);
    if(fs.existsSync(A + "dl/gsi/unpacked/system.img")) assert.equal(hash.digest("hex"), sha256(fs.readFileSync(A + "dl/gsi/unpacked/system.img")));
});

await part("super's metadata written again", [A + "img/super.img"], async () =>
{
    const read = file_reader(A + "img/super.img");
    const lp = lp_metadata((offset, length) => sparse_read(read, offset, length));
    for(const copy of lp.copies) assert.ok(equals(lp_serialize(lp_parse(copy.bytes)), copy.bytes));
});

await part("the bootloader's work from disk.img", [OUT + "disk.img", OUT + "manifest.json", OUT + "initrd.img", A + "dl/vendor_ramdisk-debug.img"], async () =>
{
    const manifest = JSON.parse(fs.readFileSync(OUT + "manifest.json", "utf8"));
    const read = file_reader(OUT + "disk.img");
    const partitions = gpt_partitions(read, fs.statSync(OUT + "disk.img").size);
    assert.deepEqual(partitions.map(p => [p.name, p.start]), manifest.disk.partitions.map(p => [p.name, p.start]));
    const by_name = new Map(partitions.map(p => [p.name, p]));
    // (each partition as the bootloader reads it: whole, the slot's)
    const read_partition = name =>
    {
        const p = by_name.get(name + CF_ARM64_ONLY_PHONE.slot) || by_name.get(name);
        if(!p) throw new Error("no partition " + name);
        return read(p.start, p.size);
    };
    const options = { memory_mb: 1536, page_size: manifest.kernel.page_size, vendor_ramdisk: fs.readFileSync(A + "dl/vendor_ramdisk-debug.img") };
    assert.equal(manifest.vendor_ramdisk, "vendor_ramdisk-debug.img");
    if(manifest.kernel.page_size !== 4096) { console.log("  (16K: its ramdisk and kernel are not on the disk; the 4K bootloader only)"); return; }
    const m = android_boot(read_partition, CF_ARM64_ONLY_PHONE, options);
    assert.equal(m.cmdline, manifest.cmdline);
    assert.deepEqual(m.vbmeta, manifest.vbmeta);
    assert.deepEqual(Object.fromEntries(m.bootconfig), manifest.bootconfig);
    assert.equal(sha256(m.kernel), manifest.results.Image);
    assert.equal(sha256(m.initrd), manifest.results["initrd.img"]);
    if(manifest.results["initrd-venus.img"])
    {
        assert.equal(sha256(android_boot(read_partition, CF_ARM64_ONLY_PHONE, { ...options, gpu_mode: "venus" }).initrd), manifest.results["initrd-venus.img"]);
    }
});

// v64's bootloader (I2.2): a V86 with android in place of kernel, initrd
// and cmdline loads what the tool made (TEST_RELEASE_BUILD=1: build/libv86.mjs)
await part("v64's bootloader (V86 android option)", [OUT + "disk.img", OUT + "manifest.json", A + "dl/vendor_ramdisk-debug.img", ROOT + "build/v86-arm64.wasm"], async () =>
{
    const manifest = JSON.parse(fs.readFileSync(OUT + "manifest.json", "utf8"));
    if(manifest.kernel.page_size !== 4096) { console.log("  (16K: not on the disk)"); return; }
    const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    for(const gpu_mode of manifest.results["initrd-venus.img"] ? ["swiftshader", "venus"] : ["swiftshader"])
    {
        const emulator = new V86({
            cpu_type: "arm64", cpu_cores: 1, memory_size: 1536 * 1048576, log_level: 0, autostart: false,
            wasm_path: ROOT + "build/v86-arm64.wasm", virtio_transport: "pci", graphics_adapter: "none",
            virtio_disks: [{ url: OUT + "disk.img", async: true, size: fs.statSync(OUT + "disk.img").size }],
            android: { gpu_mode, vendor_ramdisk: { url: A + "dl/vendor_ramdisk-debug.img" } },
        });
        await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
        const files = emulator.v86.cpu.boot_files;
        assert.equal(files.cmdline, manifest.cmdline);
        assert.equal(sha256(new Uint8Array(files.kernel)), manifest.results.Image);
        assert.equal(sha256(new Uint8Array(files.initrd)), manifest.results[gpu_mode === "venus" ? "initrd-venus.img" : "initrd.img"], gpu_mode);
        await emulator.destroy();
    }
});

// the importer (I3.1): the Cuttlefish zip as a disk, the same as the tool's
// --release --no-venus --shrink-super --userdata-mb 4096 disk.img
const SMALL = A + "out-official-small/";
await part("the importer's disk (tools/a64_android.mjs's out-official-small)", [CF_ZIP, SMALL + "disk.img"], async () =>
{
    const { cuttlefish_disk, write_disk, package_entries } = await import("../../src/android/assemble.js");
    const read = file_reader(CF_ZIP);
    const disk = await cuttlefish_disk(read, await package_entries(read, fs.statSync(CF_ZIP).size), { userdata_bytes: 4096 * 1048576 });
    const file = A + "i1-imported.img";
    fs.rmSync(file, { force: true });
    const fd = fs.openSync(file, "w");
    fs.ftruncateSync(fd, disk.disk_size);
    await write_disk(read, disk, (offset, bytes) => { fs.writeSync(fd, bytes, 0, bytes.length, offset); });
    fs.closeSync(fd);
    assert.equal(fs.statSync(file).size, fs.statSync(SMALL + "disk.img").size);
    const a = file_reader(file), b = file_reader(SMALL + "disk.img");
    for(let at = 0; at < disk.disk_size; at += 16 << 20) assert.ok(equals(a(at, 16 << 20), b(at, 16 << 20)), "the disks differ in [" + at + ", +16 MiB)");
    fs.rmSync(file);
});

console.log(`${ran} parts ran`);
                                                                                                   source/v64/tests/api/2g-mem.js                                                                      0000755 0000000 0000000 00000004173 00000000000 013231  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import fs from "node:fs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 2 * 1024 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");

    emulator.create_file("test.lua", Buffer.from(`
local t = {}
local m = 1
while collectgarbage("count") < 1.8 * 1024 * 1024 do
    t[m] = string.rep("A", 4096)
    m = m + 1
    if m % 10000 == 0 then
        print(m, " ", collectgarbage("count"))
    end
end
print("memory usage (kB) ", collectgarbage("count"))
print("page count ", m)
local ref = string.rep("A", 4096)
for i = 1, m - 1 do
    assert(t[i] == ref)
end
print("ok")
`));
});

let ran_command = false;
let line = "";

emulator.add_listener("serial0-output-byte", async function(byte)
{
    const chr = String.fromCharCode(byte);

    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        var new_line = line;
        console.error("Serial: %s", line);
        line = "";
    }
    else if(chr >= " " && chr <= "~")
    {
        line += chr;
    }

    if(!ran_command && line.endsWith("~% "))
    {
        ran_command = true;

        emulator.serial0_send("free -m\n");
        emulator.serial0_send("time -v lua /mnt/test.lua\n");
        emulator.serial0_send("echo test fini''shed\n");
    }

    if(chr === "\n" && new_line.startsWith("test finished"))
    {
        emulator.destroy();
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/api/arm64-options.js                                                               0000755 0000000 0000000 00000024650 00000000000 014571  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The guest CPU and machine combinations of new V86()
// (docs/arm64-virt-android16-plan.md P1.1, src/machine_options.js):
// - cpu_type x86 and x86_64 run on machine_type i440fx (their default) and
//   q35, cpu_type arm64 and arm32 on virt (their default) and ranchu (the
//   Android emulator's board); every other combination fails
//   in the constructor, and the x86 CPU's init refuses virt again;
// - an option of the other family is an error, never ignored: the PC
//   machines' firmware, disks and chipset options on virt, kernel, dtb,
//   virtio_disks, virtio_rng, virtio_transport and virtio_input on the PC machines;
// - virt has no VGA (graphics_adapter "none" or "virtio_gpu"), virtio-net
//   only, and no ACPI; ranchu has the emulator's framebuffer (graphics_adapter
//   "none") and no PCIe (virtio_transport "mmio").

import assert from "node:assert/strict";
import { CPU_TYPES, DEFAULT_CPU_PROFILES, MACHINE_TYPES, check_machine_options } from "../../src/machine_options.js";

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

assert.deepEqual(CPU_TYPES, ["x86", "x86_64", "arm64", "arm32"]);
assert.deepEqual(MACHINE_TYPES, ["i440fx", "q35", "virt", "ranchu"]);

// the matrix
const runs = { x86: ["i440fx", "q35"], x86_64: ["i440fx", "q35"], arm64: ["virt", "ranchu"], arm32: ["virt", "ranchu"] };
for(const cpu_type of CPU_TYPES)
{
    for(const machine_type of MACHINE_TYPES)
    {
        const options = { cpu_type, machine_type };
        if(runs[cpu_type].includes(machine_type))
        {
            assert.deepEqual(check_machine_options(options), { ...options, cpu_profile: DEFAULT_CPU_PROFILES[cpu_type] });
        }
        else
        {
            assert.throws(() => check_machine_options(options), /does not run on machine_type/, JSON.stringify(options));
            assert.throws(() => new V86({ graphics_adapter: "none", cpu_type, machine_type, autostart: false }),
                /does not run on machine_type/, "constructor: " + JSON.stringify(options));
        }
    }
}
console.log("PASS the cpu_type and machine_type matrix");

// defaults
assert.deepEqual(check_machine_options({}), { cpu_type: "x86", machine_type: "i440fx", cpu_profile: "generic-x86" });
assert.deepEqual(check_machine_options({ cpu_type: "x86_64" }), { cpu_type: "x86_64", machine_type: "i440fx", cpu_profile: "generic-x86-64" });
assert.deepEqual(check_machine_options({ cpu_type: "arm64" }), { cpu_type: "arm64", machine_type: "virt", cpu_profile: "generic-arm64" });
assert.deepEqual(check_machine_options({ cpu_type: "arm32" }), { cpu_type: "arm32", machine_type: "virt", cpu_profile: "cortex-a15" });
console.log("PASS defaults: i440fx with x86, virt with arm64 and arm32");

// unknown names
for(const cpu_type of ["aarch64", "arm", "x86-64", ""])
{
    assert.throws(() => check_machine_options({ cpu_type }), /Unknown cpu_type .*supported: "x86", "x86_64", "arm64", "arm32"/);
}
assert.throws(() => check_machine_options({ machine_type: "pc" }), /machine_type must be one of "i440fx", "q35", "virt", "ranchu"/);
assert.throws(() => check_machine_options({ experimental_x64: true }), /experimental_x64 was replaced/);
console.log("PASS unknown cpu_type and machine_type");

// the CPU model (cpu_profile, docs/iphone4-plan.md "CPU 型号"; the arm64 profiles of docs/aarch32-plan.md Q7.2)
for(const cpu_profile of ["generic-arm64-v1", "generic-arm64-v1.1", "generic-arm64", "generic-arm64-compat32"])
{
    assert.equal(check_machine_options({ cpu_type: "arm64", cpu_profile }).cpu_profile, cpu_profile);
}
assert.equal(check_machine_options({ cpu_type: "arm64" }).cpu_profile, "generic-arm64", "arm64's default");
assert.equal(check_machine_options({ cpu_type: "arm32" }).cpu_profile, "cortex-a15", "arm32's default");
assert.equal(check_machine_options({}).cpu_profile, "generic-x86", "the PC's default");
assert.equal(check_machine_options({ cpu_type: "x86_64" }).cpu_profile, "generic-x86-64");
// (a model alone picks its CPU type)
assert.deepEqual(check_machine_options({ cpu_profile: "cortex-a15" }), { cpu_type: "arm32", machine_type: "virt", cpu_profile: "cortex-a15" });
assert.deepEqual(check_machine_options({ cpu_profile: "generic-x86-64" }), { cpu_type: "x86_64", machine_type: "i440fx", cpu_profile: "generic-x86-64" });
assert.throws(() => check_machine_options({ cpu_type: "arm32", cpu_profile: "generic-arm64-compat32" }),
    /cpu_profile "generic-arm64-compat32" is a CPU of cpu_type "arm64", not "arm32"; cpu_type "arm32" has "cortex-a15"/);
assert.throws(() => check_machine_options({ cpu_type: "x86_64", cpu_profile: "generic-arm64" }), /is a CPU of cpu_type "arm64", not "x86_64"/);
assert.throws(() => check_machine_options({ cpu_profile: "v3" }), /Unknown cpu_profile "v3"; supported: "generic-x86"/);
assert.throws(() => check_machine_options({ cpu_type: "arm64", a64_profile: "v3" }), /a64_profile was replaced by cpu_profile/);
assert.equal(check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", cpu_profile: "cortex-a15" }).cpu_profile, "cortex-a15");
console.log("PASS cpu_profile");

// PC options on virt
const pc_options = {
    bzimage: { url: "bzImage" }, multiboot: { url: "x" }, bios: { url: "seabios.bin" }, vga_bios: { url: "vgabios.bin" },
    fda: { url: "a" }, fdb: { url: "b" }, cdrom: { url: "c" }, hpet: true, smbus: true, pcie_root_ports: 2, qemu_compatible: true,
    uart1: true, uart2: true, uart3: true, parallel1: true, modem: { uart: 1 }, cpuid_level: 0xD, x87_fast_math: true,
    x87_jit_cache: true, high_memory_size: 1 << 30, cpu_features: ["XSAVE"],
};
for(const [name, value] of Object.entries(pc_options))
{
    assert.throws(() => check_machine_options({ cpu_type: "arm64", [name]: value }),
        new RegExp("^Error: " + name + " is an option of the PC machines"), name);
    assert.doesNotThrow(() => check_machine_options({ cpu_type: "x86", [name]: value }), name);
}
// (false and undefined are no options)
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", hpet: false, uart1: false, acpi: false, bios: undefined }));
assert.throws(() => check_machine_options({ cpu_type: "arm64", acpi: true }), /acpi: true is an option of the PC machines/);
// (extended RAM is the 64-bit CPUs': at 4 GiB on virt, P8.5)
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", extended_memory_size: 1 << 30 }));
console.log(`PASS ${Object.keys(pc_options).length + 1} PC options refused on virt`);

// virt options on the PC machines
for(const [name, value] of Object.entries({ kernel: { url: "Image" }, dtb: { url: "virt.dtb" }, virtio_disks: [{ url: "disk.img" }],
    virtio_rng: true, virtio_transport: "pci", virtio_input: true }))
{
    for(const cpu_type of ["x86", "x86_64"])
    {
        assert.throws(() => check_machine_options({ cpu_type, [name]: value }), new RegExp(name + " is an option of machine_type \"virt\""));
    }
    assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", [name]: value }));
}
console.log("PASS kernel, dtb, virtio_disks, virtio_rng, virtio_transport and virtio_input refused on the PC machines");

// virt's devices
for(const adapter of ["none", "virtio_gpu"])
{
    assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", graphics_adapter: adapter }));
}
for(const adapter of ["bochs_vga", "vmware_svga"])
{
    assert.throws(() => check_machine_options({ cpu_type: "arm64", graphics_adapter: adapter }), /is not on machine_type "virt" \(no VGA\)/);
}
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", net_device: { type: "virtio" } }));
assert.throws(() => check_machine_options({ cpu_type: "arm64", net_device: { type: "ne2k" } }), /it has virtio-net/);
assert.throws(() => check_machine_options({ cpu_type: "arm64", hda: { url: "a" }, virtio_disks: [{ url: "b" }] }), /give one of them/);
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", hda: { url: "a" }, hdb: { url: "b" } }));
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", cpu_cores: 4 }));
// (the virtio devices' transport, P5.7; the input devices, P5.8, P7.4)
for(const transport of ["mmio", "pci"]) assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", virtio_transport: transport }));
assert.throws(() => check_machine_options({ cpu_type: "arm64", virtio_transport: "isa" }), /virtio_transport is "mmio" \(the default\) or "pci"/);
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm64", virtio_input: ["keyboard", "tablet", "multitouch"] }));
assert.throws(() => check_machine_options({ cpu_type: "arm64", virtio_input: ["joystick"] }), /virtio_input is true or a list/);
// (ranchu: the emulator's framebuffer, virtio-mmio only)
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", graphics_adapter: "none", virtio_transport: "mmio" }));
assert.throws(() => check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", graphics_adapter: "virtio_gpu" }),
    /"virtio_gpu" is not on machine_type "ranchu"/);
assert.throws(() => check_machine_options({ cpu_type: "arm64", machine_type: "ranchu", virtio_transport: "pci" }), /no PCIe host/);
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", ranchu_display: { width: 320, height: 480, dpi: 160 } }));
assert.throws(() => check_machine_options({ cpu_type: "arm32", ranchu_properties: { a: "b" } }), /ranchu_properties is an option of machine_type "ranchu"/);
assert.doesNotThrow(() => check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", ranchu_gpu: "host" }));
assert.throws(() => check_machine_options({ cpu_type: "arm32", machine_type: "ranchu", ranchu_gpu: "angle" }), /ranchu_gpu must be "guest" or "host"/);
assert.throws(() => check_machine_options({ cpu_type: "arm64", ranchu_gpu: "host" }), /ranchu_gpu is an option of machine_type "ranchu"/);
console.log("PASS virt's display, network, disks, cores, virtio transport and input devices; ranchu's");

// the constructor checks, before it loads anything
assert.throws(() => new V86({ graphics_adapter: "bochs_vga", cpu_type: "arm64", autostart: false }), /"bochs_vga" is not on machine_type "virt"/);
assert.throws(() => new V86({ graphics_adapter: "none", cpu_type: "arm64", bios: { url: "seabios.bin" }, autostart: false }),
    /bios is an option of the PC machines/);
assert.throws(() => new V86({ graphics_adapter: "bochs_vga", kernel: { url: "Image" }, autostart: false }), /kernel is an option of machine_type "virt"/);
console.log("PASS the constructor refuses them");
                                                                                        source/v64/tests/api/cdrom-insert-eject.js                                                          0000755 0000000 0000000 00000004644 00000000000 015646  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import { setTimeout as pause } from "timers/promises";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: { url: __dirname + "/../../images/msdos622.img" },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
});

//const interval = setInterval(() => {
//    console.warn(emulator.screen_adapter.get_text_screen());
//}, 1000);

const timeout = setTimeout(() => {
    console.warn(emulator.screen_adapter.get_text_screen());
    throw new Error("Timeout");
}, 60 * 1000);

setTimeout(async () =>
{
    await emulator.wait_until_vga_screen_contains("C:\\> ");
    console.log("Got C:\\>");
    // (get_cdrom_state, docs/vm-manager-plan.md G1: the drive, empty)
    const empty = await emulator.get_cdrom_state();
    if(!empty.present || empty.inserted) throw new Error("get_cdrom_state of the empty drive: " + JSON.stringify(empty));
    await pause(1000);
    emulator.keyboard_send_text("dir D:\n");
    await emulator.wait_until_vga_screen_contains("Abort, Retry, Fail?");
    console.log("Got Abort, Retry, Fail?");
    await pause(1000);
    emulator.keyboard_send_text("a");
    emulator.set_cdrom({ url: __dirname + "/../../images/linux4.iso" });
    await pause(1000);
    emulator.keyboard_send_text("dir D:\n");
    await emulator.wait_until_vga_screen_contains("BOOT         <DIR>");
    console.log("Got BOOT");
    const inserted = await emulator.get_cdrom_state();
    if(!inserted.present || !inserted.inserted) throw new Error("get_cdrom_state with a disc: " + JSON.stringify(inserted));
    await emulator.eject_cdrom();
    const ejected = await emulator.get_cdrom_state();
    if(!ejected.present || ejected.inserted) throw new Error("get_cdrom_state after eject_cdrom: " + JSON.stringify(ejected));
    console.log("get_cdrom_state: empty, a disc, ejected");
    emulator.destroy();
    clearTimeout(timeout);
    //clearInterval(interval);
}, 1000);
                                                                                            source/v64/tests/api/clean-shutdown.js                                                              0000755 0000000 0000000 00000002104 00000000000 015070  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

// This test checks that calling emulator.destroy() will remove all event
// listeners, so that the nodejs process cleanly and automatically exits.

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

setTimeout(function()
    {
        console.error("Calling stop()");
        emulator.destroy();
        console.error("Called stop()");
    }, 3000);
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/api/destroy-during-init.js                                                         0000755 0000000 0000000 00000003060 00000000000 016057  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

// This test checks that emulator.destroy() works before the emulator has
// loaded: it resolves, the emulator never starts, and the nodejs process
// exits by itself.

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

async function destroy_early(name, wait)
{
    const emulator = new V86(config);
    emulator.add_listener("emulator-loaded", () => {
        console.error("Failed: the emulator loaded after destroy() (%s)", name);
        process.exit(1);
    });
    await wait(emulator);
    await emulator.destroy();
    console.log("Destroyed: %s", name);
}

await destroy_early("while the wasm module loads", async () => {});
await destroy_early("while the images load", async emulator => {
    while(!emulator.v86) await new Promise(resolve => setTimeout(resolve, 1));
});

// Loading goes on in the background: give it the time to (not) finish
await new Promise(resolve => setTimeout(resolve, 2000));
console.log("Done");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/api/disk-image.js                                                                  0000755 0000000 0000000 00000013751 00000000000 014161  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// A guest on a QCOW2 disk (docs/disk-image-formats-plan.md P1): MS-DOS 6.22
// (images/msdos622.img, put in a QCOW2 image of its non-zero clusters,
// tests/image/tiny_qcow2.mjs) boots from it, read in ranges from a file,
// on the IDE disk of i440FX and the AHCI disk of Q35. A file written by the
// guest is there after a restart and after a snapshot restored; the image
// file is never written.

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import { createHash as create_hash } from "node:crypto";
import { build_qcow2 } from "../image/tiny_qcow2.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const raw = fs.readFileSync(__dirname + "/../../images/msdos622.img");
const CLUSTER = 65536;
const data = [];
for(let offset = 0; offset < raw.length; offset += CLUSTER)
{
    const cluster = raw.subarray(offset, offset + CLUSTER);
    if(cluster.some(b => b)) data.push([offset, new Uint8Array(cluster)]);
}
const image = build_qcow2({ size: raw.length, data });
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-image-"));
const image_file = path.join(temp, "msdos622.qcow2");
fs.writeFileSync(image_file, image);
const image_sha256 = create_hash("sha256").update(image).digest("hex");
console.log("msdos622.img (" + raw.length + " bytes) in a QCOW2 image of " + image.length + " bytes");

const lines = emulator => emulator.screen_adapter ? emulator.screen_adapter.get_text_screen().map(line => line.replace(/\x00/g, " ")) : [""];
const screen = emulator => lines(emulator).join("\n");

async function wait_until(emulator, condition, what, timeout = 120000)
{
    const start = Date.now();
    while(!condition())
    {
        if(Date.now() - start > timeout)
        {
            console.error(screen(emulator));
            throw new Error("Timeout waiting for " + what);
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}

const wait_for = (emulator, pattern, what) => wait_until(emulator, () => pattern.test(screen(emulator)), what);

/** the prompt, alone on its line, for a second: AUTOEXEC.BAT is done */
async function prompt(emulator, what)
{
    let stable = 0;
    await wait_until(emulator, () =>
    {
        const l = lines(emulator).filter(x => x.trim());
        stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0;
        return stable >= 10;
    }, what);
}

/** a command at the DOS prompt on a clear screen: its output, once the prompt is back */
async function dos(emulator, command)
{
    // (slowly: the BIOS keyboard buffer has 15 keys)
    await emulator.keyboard_send_text("cls\n", 20);
    // (the prompt has a blank line before it)
    await wait_until(emulator, () => { const l = lines(emulator).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await emulator.keyboard_send_text(command + "\n", 20);
    await wait_until(emulator, () => lines(emulator).filter(x => x.startsWith("C:\\>")).length >= 2, command);
    return screen(emulator);
}

async function run(machine_type)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        machine_type,
        hda: { url: image_file, async: true, format: "qcow2" },
        network_relay_url: "<UNUSED>",
        autostart: true,
        memory_size: 32 * 1024 * 1024,
        log_level: 0,
        disable_jit: +process.env.DISABLE_JIT,
    });
    emulator.add_listener("emulator-error", error => { throw error; });
    await prompt(emulator, "C:\\> (" + machine_type + ")");
    console.log(machine_type + ": C:\\> from the QCOW2 disk");

    const word = "QCOW" + machine_type.toUpperCase();
    await dos(emulator, "echo " + word + " > C:\\V86TEST.TXT");
    assert.match(await dos(emulator, "type C:\\V86TEST.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    console.log(machine_type + ": the guest wrote a file");

    // export (P2): the disk as RAW, with the file
    const chunks = [];
    assert.equal(await emulator.export_disk_image("hda", { write: chunk => { chunks.push(chunk); } }), raw.length);
    const exported = Buffer.concat(chunks);
    // (echo writes the space before the redirection)
    assert.ok(exported.includes(word + " \r\n"), "the export has the file's data");
    let changed = 0;
    for(let i = 0; i < raw.length; i += 512) if(Buffer.compare(exported.subarray(i, i + 512), raw.subarray(i, i + 512))) changed++;
    console.log(machine_type + ": exported RAW (" + exported.length + " bytes, " + changed + " sectors differ from msdos622.img)");

    await emulator.restart();
    await new Promise(resolve => setTimeout(resolve, 2000));
    await prompt(emulator, "C:\\> after the restart");
    assert.match(await dos(emulator, "type C:\\V86TEST.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    console.log(machine_type + ": the file is there after a restart");

    const state = await emulator.save_state();
    await dos(emulator, "echo LATER > C:\\LATER.TXT");
    assert.match(await dos(emulator, "type C:\\LATER.TXT"), /^LATER\s*$/m);
    await emulator.restore_state(state);
    assert.match(await dos(emulator, "dir C:\\LATER.TXT"), /File not found/);
    assert.match(await dos(emulator, "type C:\\V86TEST.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    console.log(machine_type + ": the snapshot restored: the file written after it is gone, the one before is there");

    await emulator.destroy();
    assert.equal(create_hash("sha256").update(fs.readFileSync(image_file)).digest("hex"), image_sha256, "the image file is unchanged");
}

await run("i440fx");
await run("q35");
fs.rmSync(temp, { recursive: true });
console.log("disk image guest tests passed");
                       source/v64/tests/api/disk-options.js                                                                0000755 0000000 0000000 00000017105 00000000000 014567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The disks' disk_option, disk_error and token (docs/disk-persistence-plan.md
// "启动校验"): each rule refuses the machine when it is created, with the
// disk and the reason; the CPU Worker gets the options with the descriptor.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { check_disk_bindings, check_disk_policy } = await import("../../src/disk_options.js");
const { encode_worker_file } = await import("../../src/browser/cpu_worker.js");

const bios = { url: __dirname + "/../../bios/seabios.bin" };
const vga_bios = { url: __dirname + "/../../bios/vgabios.bin" };
const image = () => new ArrayBuffer(1 << 20);
const refused = (options, pattern, what) =>
    assert.throws(() => new V86({ bios, vga_bios, graphics_adapter: "none", autostart: false, ...options }), pattern, what);

// not in the V86 options themselves
refused({ hda: { buffer: image() }, disk_option: "read_write" }, /disk_option is an option of each disk/, "disk_option at the top");
refused({ hda: { buffer: image() }, disk_error: "report" }, /disk_error is an option of each disk/, "disk_error at the top");
refused({ hda: { buffer: image() }, token: "x" }, /token is an option of each disk/, "token at the top");
console.log("ok - disk_option, disk_error and token are refused in the V86 options");

// values
refused({ hda: { buffer: image(), disk_option: "rw" } }, /hda: disk_option "rw" is not one of read_only, read_write/);
refused({ hda: { buffer: image(), disk_error: "ignore" } }, /hda: disk_error "ignore" is not one of stop, report/);
refused({ hda: { buffer: image(), token: 42 } }, /hda: token must be a string/);
console.log("ok - unknown values are refused");

// where they apply
refused({ cdrom: { buffer: image(), disk_option: "read_only" } }, /cdrom: disk_option is for disks/);
refused({ hda: { buffer: image() }, bios: { ...bios, disk_option: "read_only" } }, /bios: disk_option is for disks/);
refused({ hda: { buffer: image() }, initial_state: { url: "x", disk_error: "stop" } }, /initial_state: disk_error is for disks and CD drives/);
refused({ hda: { buffer: image() }, bzimage: { url: "x", token: "t" } }, /bzimage: token is for disks/);
refused({ fda: { buffer: image(), disk_option: "read_write" } }, /fda: an ArrayBuffer is an image in memory/, "read_write on a floppy: as for disks");
assert.deepEqual(check_disk_policy("fda", { buffer: image(), disk_option: "read_only" }), { disk_option: "read_only", disk_error: "stop" },
    "read_only on a floppy: as without it; a floppy's errors stop the machine, as a disk's");
assert.deepEqual(check_disk_policy("fdb", { buffer: image(), disk_error: "stop" }), { disk_option: "read_only", disk_error: "stop" },
    "disk_error on a floppy");
assert.deepEqual(check_disk_policy("fdb", { url: "/images/a.img", disk_option: "read_write", disk_error: "report" }), { disk_option: "read_write", disk_error: "report" },
    "a floppy written back (D3)");
assert.deepEqual(check_disk_policy("cdrom", { buffer: image(), disk_error: "report" }), { disk_option: "read_only", disk_error: "report" },
    "disk_error on a CD drive");
console.log("ok - disk_option is for hard disks and floppies, disk_error for hard disks, floppies and CD drives, neither for the other files");

// read_write: the sources that cannot be written back
refused({ hda: { buffer: image(), disk_option: "read_write" } }, /hda: an ArrayBuffer is an image in memory, with no persistent source/);
refused({ hda: { buffer: new File([new Uint8Array(512)], "disk.img"), disk_option: "read_write" } }, /hda: a File cannot be written back/);
refused({ hda: { url: "disk.img", use_parts: true, fixed_chunk_size: 512, size: 1 << 20, disk_option: "read_write" } },
    /hda: an image in parts \(use_parts, \.zst\) can only be read/);
refused({ hda: { url: "/nonexistent/disk.img", async: true, size: 1 << 20, disk_option: "read_write", format: "qcow2" } },
    /hda: disk_option "read_write" is for RAW images/);
assert.throws(() => new V86({ cpu_type: "arm64", graphics_adapter: "none", autostart: false, wasm_path: "x",
    virtio_disks: [{ buffer: image(), readonly: true, disk_option: "read_write" }] }),
    /virtio_disk0: disk_option "read_write" and readonly: the guest cannot write the disk/);
class OwnBuffer
{
    constructor() { this.byteLength = 1 << 20; this.disk_option = "read_write"; }
    load() {}
    get() {}
    set() {}
}
refused({ hda: new OwnBuffer() }, /hda: a buffer object of one's own is written back only when it implements the backend contract .*; it has no flush, close, mark, generation, get_state, set_state, check_state/);
console.log("ok - read_write: an ArrayBuffer, a File, an image in parts, a container format, a write-protected disk, a buffer object without the backend contract are refused");

// an image bound twice, one of them read_write
const rw = { disk_option: "read_write", disk_error: "stop" }, ro = { disk_option: "read_only", disk_error: "stop" };
assert.throws(() => check_disk_bindings([["hda", { url: "/images/a.img" }, rw], ["hdb", { url: "/images/a.img" }, ro]]),
    /hda and hdb are the same image, and one of them has disk_option "read_write"/);
assert.throws(() => check_disk_bindings([["sata3", { url: "/images/a.img" }, rw]], [["hda", { url: "/images/a.img" }]]),
    /hda and sata3 are the same image/, "with a disk attached before");
const shared = image();
assert.doesNotThrow(() => check_disk_bindings([["hda", { buffer: shared }, ro], ["hdb", { buffer: shared }, ro]]), "read_only twice");
assert.doesNotThrow(() => check_disk_bindings([["hda", { url: "/images/a.img" }, rw], ["hdb", { url: "/images/b.img" }, ro]]));
console.log("ok - an image bound to two disks with one of them read_write is refused");

// a browser disk (docs/vm-manager-plan.md U6) is in a browser's private storage: not in Node, read only or read write
refused({ hda: { url: "opfs:v86/disks/x.img", disk_option: "read_write" } }, /hda: a browser disk \(opfs:v86\/disks\/x\.img\) is in a browser's private storage \(OPFS\), not in Node/);
refused({ cdrom: { url: "opfs:v86/disks/x.img" } }, /cdrom: a browser disk .* not in Node/);
assert.throws(() => check_disk_policy("fda", { url: "opfs:v86/disks/f.img" }), /fda: a browser disk .* not in Node/);
console.log("ok - a browser disk (opfs:) is refused in Node");

// the CPU Worker gets them
assert.deepEqual((({ disk_option, disk_error, token }) => ({ disk_option, disk_error, token }))(
    encode_worker_file({ buffer: image(), disk_option: "read_only", disk_error: "report", token: "secret" })),
    { disk_option: "read_only", disk_error: "report", token: "secret" });
console.log("ok - the CPU Worker's descriptor has disk_option, disk_error and token");

// and a disk whose options are fine starts, its policy on its buffer
const emulator = new V86({ bios, vga_bios, graphics_adapter: "bochs_vga", autostart: false, log_level: 0, hda: { buffer: image(), disk_error: "report" }, cdrom: { buffer: image() } });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const ide = emulator.v86.cpu.devices.ide;
assert.equal(ide.primary.master.buffer.disk_name, "hda");
assert.equal(ide.primary.master.buffer.disk_error, "report");
assert.equal(ide.secondary.master.buffer.disk_name, "cdrom");
assert.equal(ide.secondary.master.buffer.disk_error, "stop", "the default");
await emulator.destroy();
console.log("ok - the policy reaches the disk");
console.log("disk option tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/api/floppy.js                                                                      0000755 0000000 0000000 00000017313 00000000000 013456  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import { setTimeout as pause } from "timers/promises";
import url from "node:url";
import fs from "node:fs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

async function exec_test(test_name, v86_config, timeout_sec, test_function)
{
    console.log("Starting: " + test_name);
    const tm_start = performance.now();
    const emulator = new V86(v86_config);
    const timeout = setTimeout(async () => {
        console.warn(emulator.screen_adapter.get_text_screen());
        await emulator.destroy();
        throw new Error("Timeout error in test " + test_name);
    }, timeout_sec * 1000);
    await new Promise(resolve => emulator.bus.register("emulator-started", () => resolve()));
    try
    {
        await test_function(emulator);
    }
    catch(err)
    {
        console.warn(emulator.screen_adapter.get_text_screen());
        throw new Error("Error in test " + test_name, { cause: err });
    }
    clearTimeout(timeout);
    await emulator.destroy();
    console.log("Done: " + test_name + " (" + ((performance.now() - tm_start) / 1000).toFixed(2) + " sec)");
}

/**
 * Execute given CLI command and wait for its completion.
 *
 * Injects command into the guest's keyboard buffer, then waits for both the
 * command and the expected response lines to show at the bottom of the VGA
 * screen.
 *
 * If command is empty then no command is executed and only the expected
 * response lines are waited for. If command contains only whitespace and/or
 * newline characters then it is send to the guest, but it does not become
 * part of the expected response.
 *
 * Allowed character set for command and expected is the printable subset
 * of 7-bit ASCII, use newline character "\n" to encode ENTER key.
 *
 * Throws an Error if the given timeout elapsed before the expected response
 * could be detected.
 *
 * @param {V86} emulator
 * @param {string} command
 * @param {Array<string|RegExp>} expected
 * @param {number} timeout_msec
 */
async function expect(emulator, command, expected, timeout_msec)
{
    if(command)
    {
        for(const ch of command)
        {
            emulator.keyboard_send_text(ch);
            await pause(10);
        }
        expected = [new RegExp(RegExp.escape(command.trimRight()) + "$"), ...expected];
        await pause(100);
    }
    if(!await emulator.wait_until_vga_screen_contains(expected, {timeout_msec: timeout_msec}))
    {
        throw new Error("Timeout of " + timeout_msec + " msec expired");
    }
}

const CONFIG_MSDOS622_HD = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: { url: __dirname + "/../../images/msdos622.img" },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT
};

const CONFIG_TINYCORE_CD = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/TinyCore-11.0.iso" },
    autostart: true,
    memory_size: 128 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT
};

await exec_test("floppy-insert-eject", CONFIG_MSDOS622_HD, 60, async emulator =>
{
    console.log("Waiting for C:\\>");
    await expect(emulator, "", ["C:\\>"], 10000);

    console.log("Reading A:");
    await expect(emulator, "dir A:\n", ["", "", "General failure reading drive A", "Abort, Retry, Fail?"], 5000);
    await expect(emulator, "A", ["", "C:\\>"], 1000);

    console.log("Inserting disk freedos722.img into drive fda");
    await emulator.set_fda({ url: __dirname + "/../../images/freedos722.img" });

    console.log("Reading A:X86TEST.ASM");
    await expect(emulator, "dir /B A:X86TEST.ASM\n", ["X86TEST.ASM", "", "C:\\>"], 3000);

    console.log("Ejecting disk from drive A:");
    emulator.eject_fda();

    console.log("Reading A:");
    await expect(emulator, "dir A:\n", ["", " Volume in drive A is FREEDOS", "", "General failure reading drive A", "Abort, Retry, Fail?"], 5000);
});

await exec_test("floppy-insert-fdb", CONFIG_MSDOS622_HD, 60, async emulator =>
{
    console.log("Waiting for C:\\>");
    await expect(emulator, "", ["C:\\>"], 10000);

    console.log("Inserting disk freedos722.img into drive fdb");
    await emulator.set_fdb({ url: __dirname + "/../../images/freedos722.img" });

    console.log("Reading B:X86TEST.ASM");
    await expect(emulator, "dir /B B:X86TEST.ASM\n", ["X86TEST.ASM", "", "C:\\>"], 3000);

    console.log("Formatting B:");
    await expect(emulator, "format /V:V86 /U B:\n", ["Insert new diskette for drive B:", "and press ENTER when ready..."], 3000);
    await expect(emulator, "\n", [/Volume Serial Number is [0-9A-F-]+/, "", "Format another (Y/N)?"], 3000);
    await expect(emulator, "N\n", ["", "", "C:\\>"], 3000);
});

await exec_test("floppy-tinycore-linux", CONFIG_TINYCORE_CD, 60, async emulator =>
{
    console.log("Waiting for boot menu");
    await expect(emulator, "", [/BIOS default device boot in \d+ seconds\.\.\./], 10000);

    // press arrow down key 3 times
    for(let i = 0; i < 3; i++)
    {
        emulator.keyboard_send_scancodes([
            0xe0, 0x50,        // press
            0xe0, 0x50 | 0x80, // release
        ]);
        await pause(600);
    }

    console.log("Waiting for tc@box:~$");
    await expect(emulator, "\n", ["tc@box:~$"], 30000);

    console.log("Inserting disk windows101.img into drive fda");
    await emulator.set_fda({ url: __dirname + "/../../images/windows101.img" });

    console.log("Mounting /dev/fd0 into /mnt/fd0");
    await expect(emulator, "mkdir /mnt/fd0\n", ["tc@box:~$"], 3000);
    await expect(emulator, "sudo mount /dev/fd0 /mnt/fd0\n", ["tc@box:~$"], 3000);

    console.log("Reading /mnt/fd0/COMMAND.COM");
    await expect(emulator, "ls /mnt/fd0/COMMAND.COM\n", ["/mnt/fd0/COMMAND.COM", "tc@box:~$"], 3000);

    console.log("Unmounting fda");
    await expect(emulator, "sudo umount /dev/fd0\n", ["tc@box:~$"], 3000);

    console.log("Formatting /dev/fd0");
    await expect(emulator, "sudo mke2fs -q /dev/fd0\n", ["/dev/fd0 contains a vfat file system labelled 'WIN101'", "Proceed anyway? (y,N)"], 3000);
    await expect(emulator, "y\n", ["tc@box:~$"], 5000);

    console.log("Reading /mnt/fd0");
    await expect(emulator, "sudo mount /dev/fd0 /mnt/fd0\n", ["tc@box:~$"], 3000);
    await expect(emulator, "ls /mnt/fd0\n", ["lost+found/", "tc@box:~$"], 3000);
});

await exec_test("floppy-state-snapshot", CONFIG_MSDOS622_HD, 60, async emulator =>
{
    console.log("Waiting for C:\\>");
    await expect(emulator, "", ["C:\\>"], 10000);

    console.log("Inserting disk freedos722.img into drive fda");
    await emulator.set_fda({ url: __dirname + "/../../images/freedos722.img" });

    console.log("Saving initial state");
    const initial_state = await emulator.save_state();

    console.log("Creating file A:V86TEST.TXT");
    await expect(emulator, "echo v86test > A:V86TEST.TXT\n", ["", "C:\\>"], 3000);

    console.log("Saving modified state");
    const modified_state = await emulator.save_state();

    console.log("Restoring initial state");
    await emulator.restore_state(initial_state);

    console.log("Reading A:V86TEST.TXT");
    await expect(emulator, "dir /B A:V86TEST.TXT\n", ["", "C:\\>"], 3000);

    console.log("Restoring modified state");
    await emulator.restore_state(modified_state);

    console.log("Reading A:V86TEST.TXT");
    await expect(emulator, "dir /B A:V86TEST.TXT\n", ["V86TEST.TXT", "", "C:\\>"], 3000);
});
                                                                                                                                                                                                                                                                                                                     source/v64/tests/api/iso9660.js                                                                     0000755 0000000 0000000 00000005747 00000000000 013274  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import crypto from "node:crypto";
import { setTimeout as pause } from "timers/promises";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { generate } = await import("../../src/iso9660.js");

process.on("unhandledRejection", exn => { throw exn; });

const TEXT_FILE_NAME = "Hello World, this is a Long FileName.txt";
const TEXT_FILE_CONTENTS = "iso9660 joliet content marker 133769\n";

const binary_file_contents = new Uint8Array(2 * 2048 + 1337);
for(let i = 0; i < binary_file_contents.length; i++) binary_file_contents[i] = (i * 7 + 13) & 0xFF;
const binary_file_md5 = crypto.createHash("md5").update(binary_file_contents).digest("hex");

const iso = generate([
    { name: TEXT_FILE_NAME, contents: new TextEncoder().encode(TEXT_FILE_CONTENTS) },
    { name: "data.bin", contents: binary_file_contents },
]);

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 128 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
});

let serial_text = "";
let search_offset = 0;
let pending = null;

const timeout = setTimeout(() => {
    console.warn(serial_text);
    throw new Error("Timeout");
}, 5 * 60 * 1000);

emulator.add_listener("serial0-output-byte", byte => {
    const chr = String.fromCharCode(byte);
    process.stdout.write(chr);
    serial_text += chr;
    if(pending)
    {
        const index = serial_text.indexOf(pending.str, search_offset);
        if(index !== -1)
        {
            search_offset = index + pending.str.length;
            const resolve = pending.resolve;
            pending = null;
            resolve();
        }
    }
});

function wait_for(str)
{
    return new Promise(resolve => {
        const index = serial_text.indexOf(str, search_offset);
        if(index !== -1)
        {
            search_offset = index + str.length;
            resolve();
            return;
        }
        pending = { str, resolve };
    });
}

await wait_for("~%");
console.log("\nBooted, inserting generated iso");
await emulator.set_cdrom({ buffer: iso.buffer });
await pause(1000);

emulator.serial0_send("mkdir -p /tmp/cd && mount -t iso9660 /dev/sr0 /tmp/cd && ls /tmp/cd\n");
await wait_for(TEXT_FILE_NAME);
await wait_for("~%");
console.log("\nJoliet filename found");

emulator.serial0_send("cat /tmp/cd/*.txt\n");
await wait_for(TEXT_FILE_CONTENTS.trim());
await wait_for("~%");
console.log("\nFile contents found");

emulator.serial0_send("md5sum /tmp/cd/data.bin\n");
await wait_for(binary_file_md5);
console.log("\nBinary file checksum matches");

console.log("Test passed");
emulator.destroy();
clearTimeout(timeout);
                         source/v64/tests/api/jit-switches.js                                                                0000755 0000000 0000000 00000014153 00000000000 014561  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The JIT switch registry (docs/jit-unification-plan.md, cross-phase rule 1;
// src/rust/jit_switches.rs, src/jit_switches.js):
// - a module on its own reads each switch's default, refuses unknown ids,
//   unknown names and values out of range, and reads back what it set;
// - JIT_SWITCHES and the V86 option jit_switches set switches by name over
//   the settings configure_jit_backend applied; an unknown name fails the
//   construction.

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import { WASM_TABLE_OFFSET, WASM_TABLE_SIZE } from "../../src/const.js";
import { get_jit_switches, jit_switch_table, parse_jit_switches, set_jit_switches } from "../../src/jit_switches.js";
import { jit_switches_from_env, jit_switches_of, set_emulator_jit_switches, with_jit_switches } from "../lib/jit_switches.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const WASM = __dirname + "/../../build/" + (TEST_RELEASE_BUILD ? "v86.wasm" : "v86-debug.wasm");

process.on("unhandledRejection", exn => { throw exn; });

// A module on its own
{
    const module = await WebAssembly.compile(fs.readFileSync(WASM));
    const env = {};
    for(const { name, kind } of WebAssembly.Module.imports(module))
    {
        env[name] = kind === "table" ? new WebAssembly.Table({ element: "anyfunc", initial: WASM_TABLE_SIZE + WASM_TABLE_OFFSET }) : () => 0;
    }
    const { exports } = await WebAssembly.instantiate(module, { env });
    exports["rust_init"]();
    const memory = exports.memory;

    const table = jit_switch_table(exports, memory);
    assert.equal(table.length, exports["jit_switch_count"]());
    assert.ok(table.length >= 28, "switches: " + table.map(s => s.name).join(" "));
    table.forEach(({ name, default: value }, id) => assert.equal(exports["jit_switch"](id) >>> 0, value, name + ": the default"));
    assert.equal(exports["jit_switch"](table.length) >>> 0, 0xFFFFFFFF);
    assert.equal(exports["jit_set_switch"](table.length, 0), 0);
    assert.deepEqual(get_jit_switches(exports, memory, true), {});

    set_jit_switches(exports, memory, { x64_outline: 0, x64_block_count: false, x64_legacy_heat: 1000, x64_span_entries: 40 });
    const now = get_jit_switches(exports, memory);
    assert.equal(now.x64_outline, 0);
    assert.equal(now.x64_block_count, 0);
    assert.equal(now.x64_legacy_heat, 1000);
    assert.equal(now.x64_span_entries, 40);
    assert.equal(now.x64_span_crossings, 4096, "x64_span_entries keeps x64_span_crossings");
    assert.deepEqual(get_jit_switches(exports, memory, true), { x64_outline: 0, x64_block_count: 0, x64_legacy_heat: 1000, x64_span_entries: 40 });
    // (an old setter is an alias: jit_switch reads what it set)
    exports["x64_page_set_outline"](1);
    assert.equal(get_jit_switches(exports, memory).x64_outline, 1);

    assert.throws(() => set_jit_switches(exports, memory, { x64_outline: 2 }), /x64_outline cannot be 2/);
    assert.throws(() => set_jit_switches(exports, memory, { x64_legacy_heat: 0 }), /x64_legacy_heat cannot be 0/);
    assert.throws(() => set_jit_switches(exports, memory, { no_such_switch: 1 }), /no JIT switch no_such_switch/);
    // (chained page functions need tail calls, which src/cpu.js reports)
    assert.throws(() => set_jit_switches(exports, memory, { x64_chaining: 1 }), /x64_chaining cannot be 1/);
    exports["jit_set_tail_calls"](1);
    set_jit_switches(exports, memory, { x64_chaining: 1 });
    set_jit_switches(exports, memory, { x64_chaining: 0 });
    assert.equal(get_jit_switches(exports, memory).x64_chaining, 0);
    console.log(`${table.length} switches: defaults, round trips and refusals`);
}

// Parsing, and JIT_SWITCHES
assert.deepEqual(parse_jit_switches("a=1, b = 0,c_2=7"), { a: 1, b: 0, c_2: 7 });
assert.deepEqual(parse_jit_switches({ a: true, b: false, c: 3 }), { a: 1, b: 0, c: 3 });
assert.deepEqual(parse_jit_switches(undefined), {});
assert.throws(() => parse_jit_switches("a"), /expected name=value/);
assert.throws(() => parse_jit_switches("a=-1"), /expected name=value/);
assert.deepEqual(jit_switches_from_env({ JIT_SWITCHES: "x64_outline=0" }), { x64_outline: 0 });
assert.deepEqual(with_jit_switches({ jit_switches: { x64_loops: 1 } }, { JIT_SWITCHES: "x64_outline=0,x64_loops=0" }).jit_switches,
    { x64_outline: 0, x64_loops: 1 }, "a test's own value wins over JIT_SWITCHES");
assert.deepEqual(with_jit_switches({ memory_size: 1 }, {}), { memory_size: 1 });

// The V86 option
const config = {
    graphics_adapter: "none",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    autostart: false,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
};

function load(options)
{
    const emulator = new V86(options);
    return new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", () => resolve(emulator));
        emulator.add_listener("emulator-error", error => { emulator.destroy(); reject(error); });
    });
}

{
    const emulator = await load({ ...config, jit_switches: "x64_outline=0, x64_legacy_heat=1000" });
    const values = jit_switches_of(emulator);
    assert.equal(values.x64_outline, 0);
    assert.equal(values.x64_legacy_heat, 1000);
    // (not named: as configure_jit_backend left them; the region tiers'
    // switches went with them in M11)
    assert.equal(values.ir_tier0, 1);
    assert.equal(values.x64_page_legacy32, 1);
    assert.equal(values.x64_page_prot16, 1);
    assert.equal(values.x64_page_v86, 1);
    set_emulator_jit_switches(emulator, { x64_outline: 1 });
    assert.equal(jit_switches_of(emulator).x64_outline, 1);
    await emulator.destroy();
    console.log("the option jit_switches");
}

await assert.rejects(load({ ...config, jit_switches: { no_such_switch: 1 } }), /no JIT switch no_such_switch/);
await assert.rejects(load({ ...config, jit_switches: { x64_legacy_heat: 0 } }), /x64_legacy_heat cannot be 0/);
console.log("unknown names and refused values fail the construction");
console.log("Done");
                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/api/parallel.js                                                                    0000755 0000000 0000000 00000011413 00000000000 013734  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "node:assert/strict";
import { setTimeout as pause } from "timers/promises";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const STATUS_ERROR = 0x08;
const STATUS_SELECT = 0x10;
const STATUS_ACK = 0x40;
const STATUS_NOT_BUSY = 0x80;
const STATUS_IDLE = STATUS_NOT_BUSY | STATUS_ACK | STATUS_SELECT | STATUS_ERROR;
const STATUS_ACK_LOW = STATUS_NOT_BUSY | STATUS_SELECT | STATUS_ERROR;

function escape_regexp(text)
{
    return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

async function expect(emulator, command, expected, timeout_msec)
{
    if(command)
    {
        for(const ch of command)
        {
            emulator.keyboard_send_text(ch);
            await pause(10);
        }
        expected = [new RegExp(escape_regexp(command.trimRight()) + "$"), ...expected];
        await pause(100);
    }
    if(!await emulator.wait_until_vga_screen_contains(expected, {timeout_msec: timeout_msec}))
    {
        throw new Error("Timeout of " + timeout_msec + " msec expired");
    }
}

const base_config = {
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: { url: __dirname + "/../../images/msdos622.img" },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

async function destroy_emulator(emulator)
{
    if(emulator.v86)
    {
        await emulator.destroy();
    }
}

function dump_screen(emulator)
{
    if(emulator.screen_adapter)
    {
        console.warn(emulator.screen_adapter.get_text_screen());
    }
}

async function test_parallel_port(lpt, enable_lpt2)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        ...base_config,
        parallel1: enable_lpt2,
    });
    const parallel_data = [];
    const parallel_control = [];
    const dos_device = "LPT" + (lpt + 1);
    const event_prefix = "parallel" + lpt;
    const expected_text = "V86-PARALLEL-" + dos_device + "-OK";

    emulator.add_listener(event_prefix + "-data-output", byte =>
    {
        parallel_data.push(byte);
    });

    emulator.add_listener(event_prefix + "-control-output", value =>
    {
        parallel_control.push(value);

        // Acknowledge the guest's strobe so BIOS/DOS see an online printer.
        emulator.bus.send(event_prefix + "-status-input", STATUS_ACK_LOW);
        emulator.bus.send(event_prefix + "-status-input", STATUS_IDLE);
    });

    const timeout = setTimeout(async () =>
    {
        dump_screen(emulator);
        console.warn(dos_device + " data:", Buffer.from(parallel_data).toString("ascii"));
        await destroy_emulator(emulator);
        throw new Error("Timeout");
    }, 60 * 1000);

    try
    {
        await new Promise(resolve => emulator.bus.register("emulator-started", () => resolve()));
        assert(!!emulator.v86.cpu.devices.parallel0, "expected LPT1 to be enabled");
        assert.equal(
            !!emulator.v86.cpu.devices.parallel1,
            enable_lpt2,
            "expected LPT2 to " + (enable_lpt2 ? "be enabled when requested" : "stay disabled by default")
        );

        emulator.bus.send(event_prefix + "-status-input", STATUS_IDLE);

        console.log("Waiting for C:\\>");
        await expect(emulator, "", ["C:\\>"], 10000);

        console.log("Printing to " + dos_device);
        await expect(emulator, "echo " + expected_text + ">" + dos_device + "\n", ["", "C:\\>"], 5000);

        const printed = Buffer.from(parallel_data).toString("ascii");
        assert(
            printed.includes(expected_text),
            "expected " + dos_device + " output to include " + JSON.stringify(expected_text) + ", got " + JSON.stringify(printed)
        );
        assert(
            parallel_control.length > 0,
            "expected DOS " + dos_device + " write to drive the parallel control lines"
        );

        // after a snapshot, the status register still reads as a byte
        // (nothing latched is undefined, which a snapshot stores as null)
        const state = await emulator.save_state();
        await emulator.restore_state(state);
        const status = emulator.v86.cpu.io.port_read8((lpt === 0 ? 0x378 : 0x278) + 1);
        assert.equal(typeof status, "number", "the status register after a restore");
    }
    catch(err)
    {
        dump_screen(emulator);
        throw err;
    }
    finally
    {
        clearTimeout(timeout);
        await destroy_emulator(emulator);
    }
}

await test_parallel_port(0, false);
await test_parallel_port(1, true);

console.log("ok");
                                                                                                                                                                                                                                                     source/v64/tests/api/pic.js                                                                         0000755 0000000 0000000 00000004636 00000000000 012724  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import fs from "node:fs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const root_path = __dirname + "/../..";

process.on("unhandledRejection", exn => { throw exn; });

if(!fs.existsSync(root_path + "/images/fs.json"))
{
    console.log("Missing images/fs.json, test skipped");
    process.exit(0);
}

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage_initrd_from_filesystem: true,
    cmdline: [
        "rw apm=off vga=0x344 video=vesafb:ypan,vremap:8",
        "root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose mitigations=off",
        "audit=0 init=/usr/bin/init-openrc net.ifnames=0 biosdevname=0",
    ].join(" "),
    filesystem: {
        basefs: root_path + "/images/fs.json",
        baseurl: root_path + "/images/arch/",
    },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");

    // Trigger a lot of interrupts
    // There have been bugs in the pic in the past, e.g. #1203
    const interval = setInterval(() =>
    {
        emulator.bus.send("mouse-delta", [1, 0]);
    }, 0);

    const timeout = setTimeout(() => {
        console.warn(emulator.screen_adapter.get_text_screen());
        throw new Error("Timeout");
    }, 600 * 1000);

    let line = "";
    emulator.add_listener("serial0-output-byte", async function(byte)
    {
        const chr = String.fromCharCode(byte);

        if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
        {
            return;
        }

        if(chr === "\n")
        {
            console.error("Serial: %s", line);

            if(line.startsWith("localhost login:"))
            {
                console.log("Test passed");
                clearTimeout(timeout);
                clearInterval(interval);
                emulator.destroy();
            }

            line = "";
        }
        else
        {
            line += chr;
        }
    });
});
                                                                                                  source/v64/tests/api/reboot-buildroot.js                                                            0000755 0000000 0000000 00000004174 00000000000 015441  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage.bin" },
    net_device: {
        relay_url: "fetch",
        type: "ne2k",
    },
    cmdline: "tsc=reliable mitigations=off random.trust_cpu=on",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    virtio_console: true,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

let did_reboot = false;
let reboot_finished = false;
let did_send_echo = false;
let serial_text = "";

const timeout = setTimeout(() => {
    console.log(serial_text);
    throw new Error("Timeout");
}, 60 * 1000);

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    process.stdout.write(chr);
    serial_text += chr;

    if(did_reboot)
    {
        if(serial_text.endsWith("Files send via emulator appear in /mnt/"))
        {
            reboot_finished = true;
        }

        if(did_send_echo)
        {
            if(serial_text.endsWith("finished"))
            {
                console.log("Ok");
                emulator.destroy();
                clearTimeout(timeout);
            }
        }
        else if(reboot_finished && serial_text.endsWith("~% "))
        {
            console.log("running echo");
            emulator.serial0_send("echo fini''shed\n");
            serial_text = "";
            did_send_echo = true;
        }
    }
    else
    {
        if(serial_text.endsWith("~% "))
        {
            console.log("rebooting");
            emulator.serial0_send("reboot\n");
            serial_text = "";
            did_reboot = true;
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/api/reboot.js                                                                      0000755 0000000 0000000 00000004077 00000000000 013442  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    net_device: {
        relay_url: "fetch",
        type: "virtio",
    },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    virtio_console: true,
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

let did_reboot = false;
let reboot_finished = false;
let did_send_echo = false;
let serial_text = "";

const timeout = setTimeout(() => {
    console.log(serial_text);
    throw new Error("Timeout");
}, 60 * 1000);

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    //process.stdout.write(chr);
    serial_text += chr;

    if(did_reboot)
    {
        if(serial_text.endsWith("Files send via emulator appear in /mnt/"))
        {
            reboot_finished = true;
        }

        if(did_send_echo)
        {
            if(serial_text.endsWith("finished"))
            {
                console.log("Ok");
                emulator.destroy();
                clearTimeout(timeout);
            }
        }
        else if(reboot_finished && serial_text.endsWith("~% "))
        {
            console.log("running echo");
            emulator.serial0_send("echo fini''shed\n");
            serial_text = "";
            did_send_echo = true;
        }
    }
    else
    {
        if(serial_text.endsWith("~% "))
        {
            console.log("rebooting");
            emulator.serial0_send("reboot\n");
            serial_text = "";
            did_reboot = true;
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/api/reset.js                                                                       0000755 0000000 0000000 00000003543 00000000000 013267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

// This test checks that reset works

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

let did_restart = false;
let serial_text = "";

const timeout = setTimeout(() => {
    console.log(serial_text);
    throw new Error("Timeout");
}, 60 * 1000);

emulator.add_listener("serial0-output-byte", async function(byte)
{
    var chr = String.fromCharCode(byte);
    process.stdout.write(chr);
    serial_text += chr;

    if(did_restart)
    {
        if(serial_text.endsWith("Files send via emulator appear in /mnt/"))
        {
            console.log("running echo");
            emulator.keyboard_send_text("echo fini''shed\n");

            await emulator.wait_until_vga_screen_contains("finished");
            console.log("Ok");
            emulator.destroy();
            clearTimeout(timeout);
        }
    }
    else
    {
        if(serial_text.endsWith("~% "))
        {
            emulator.keyboard_send_text("abc");
            setTimeout(() => {
                console.log("Calling restart()");
                emulator.restart();
            }, 500);
            serial_text = "";
            did_restart = true;
        }
    }
});
                                                                                                                                                             source/v64/tests/api/sb16-dma.js                                                                    0000755 0000000 0000000 00000010405 00000000000 013452  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// This test checks the SB16's 16-bit DMA playback: the address of a buffer in
// an odd 64 KiB page (the 16-bit channels count words, and the page register's
// bit 0 is unused), and a stop by masking the channel, as Windows XP's driver
// does (D9, exit auto-init, and the mask at once: reading on played the
// buffer's end again, the folder-click sound up to 8 times).

import assert from "assert/strict";

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

// (the BIOS at the reset vector: the PICs masked, then HLT with interrupts
// on, so that the machine's timers run)
const bios = new Uint8Array(0x10000).fill(0xF4);
bios.set([0xB0, 0xFF, 0xE6, 0x21, 0xE6, 0xA1, 0xFB, 0xF4, 0xEB, 0xFD], 0xFFF0);

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { buffer: bios.buffer },
    hda: { buffer: new ArrayBuffer(1024 * 1024) },
    memory_size: 16 * 1024 * 1024,
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const io = emulator.v86.cpu.io;
const dma = emulator.v86.cpu.devices.dma;

let samples = [];
emulator.add_listener("dac-send-data", ([left, right]) => { samples.push(...left, ...right); });

function dsp(...bytes)
{
    for(const byte of bytes) io.port_write8(0x22C, byte);
}

// the second controller's channel 5: mode, word address, page, words - 1
function program_channel5(mode, word_address, page, words)
{
    io.port_write8(0xD4, 0x05);
    io.port_write8(0xD8, 0);
    io.port_write8(0xD6, mode);
    io.port_write8(0xC4, word_address & 0xFF);
    io.port_write8(0xC4, word_address >> 8);
    io.port_write8(0x8B, page);
    io.port_write8(0xC6, words - 1 & 0xFF);
    io.port_write8(0xC6, words - 1 >> 8);
}

function fill16(address, words, value)
{
    emulator.write_memory(new Uint8Array(new Int16Array(words).fill(value).buffer), address);
}

// a buffer at 0x30000: page 2, word address 0x8000 (byte address bit 16 from the word address)
fill16(0x30000, 1024, 0x4000);
program_channel5(0x49, 0x8000, 0x02, 1024);
dsp(0xB0, 0x10, 1023 & 0xFF, 1023 >> 8);
io.port_write8(0xD4, 0x01);
for(let i = 0; i < 8; i++) emulator.bus.send("dac-request-data");
assert.equal(samples.length, 2 * 1024, "the whole buffer played, mono on both channels");
assert.ok(samples.every(s => Math.abs(s - 0.5) < 0.001), "the samples of 0x30000, not 0x20000's zeros");
console.log("PASS: a 16-bit buffer in an odd 64 KiB page");

// Windows XP's sounds: 16 KiB auto-init buffer, 128 KiB DSP block, stopped by D9 and the mask
samples = [];
fill16(0x8000, 8192, 0x2000);
program_channel5(0x59, 0x4000, 0, 8192);
dsp(0xB6, 0x30, 0xFF, 0xFF);
io.port_write8(0xD4, 0x01);
for(let i = 0; i < 3; i++) emulator.bus.send("dac-request-data");
assert.equal(samples.length, 3 * 1024, "three blocks of 2 KiB played");
dsp(0xD9);
io.port_write8(0xD4, 0x05);
const count = dma.channel_count[5];
samples = [];
for(let i = 0; i < 16; i++) emulator.bus.send("dac-request-data");
assert.equal(samples.length, 0, "a masked channel delivers no more samples");
assert.equal(dma.channel_count[5], count, "and its count stays");
console.log("PASS: masking the channel stops the sound");

// a host that stops asking (an AudioContext waiting for a gesture): the
// transfer keeps the machine's time on its own, and its samples are dropped
// (the plugin's card: src/audio_devices/sb16/plugin.js)
const sb16 = emulator.v86.cpu.devices.audio.device["card"];
io.port_write8(0x226, 1);
io.port_write8(0x226, 0);
program_channel5(0x59, 0x4000, 0, 8192);
dsp(0xB6, 0x30, 0xFF, 0xFF);
io.port_write8(0xD4, 0x01);
samples = [];
await emulator.run();
await new Promise(resolve => setTimeout(resolve, 1000));
await emulator.stop();
const moved = 0x20000 - sb16.dma_bytes_left;
assert.ok(moved >= 0x4000 && moved < 0x20000, "the transfer moved on its own: " + moved + " bytes");
assert.equal(samples.length, 0, "nobody listens: its samples are dropped");
emulator.bus.send("dac-request-data");
assert.equal(samples.length, 1024, "a host that asks again gets the samples");
console.log("PASS: a transfer the host stops asking for keeps the machine's time");

emulator.destroy();
console.log("Done");
                                                                                                                                                                                                                                                           source/v64/tests/api/sb16-state.js                                                                  0000755 0000000 0000000 00000003320 00000000000 014027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// This test checks that restoring a state restores the SB16's sampling rate
// for the speaker too, and drops the samples of the discarded timeline.

import assert from "assert/strict";

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { buffer: new Uint8Array(0x10000).fill(0xF4).buffer },
    // (without a primary drive, restoring before PCI enumeration hits a
    // separate bug in PCI.set_state)
    hda: { buffer: new ArrayBuffer(1024 * 1024) },
    memory_size: 16 * 1024 * 1024,
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

// DSP command 0x41: set the output sampling rate
function set_sampling_rate(rate)
{
    for(const byte of [0x41, rate >> 8, rate & 0xFF])
    {
        emulator.v86.cpu.io.port_write8(0x22C, byte);
    }
}

let rate;
emulator.add_listener("dac-tell-sampling-rate", value => { rate = value; });

set_sampling_rate(44100);
assert.equal(rate, 44100);
const state = await emulator.save_state();

set_sampling_rate(11025);
// (the plugin's card: src/audio_devices/sb16/plugin.js)
const sb16 = emulator.v86.cpu.devices.audio.device["card"];
sb16.dac_buffers[0].push(0.5);
sb16.dac_buffers[1].push(0.5);

await emulator.restore_state(state);
assert.equal(rate, 44100, "the speaker hears the restored sampling rate");
assert.equal(sb16.dac_buffers[0].length + sb16.dac_buffers[1].length, 0, "no samples of the discarded timeline");

emulator.destroy();
console.log("Done");
                                                                                                                                                                                                                                                                                                                source/v64/tests/api/serial.js                                                                      0000755 0000000 0000000 00000003154 00000000000 013422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import assert from "node:assert/strict";
import crypto from "node:crypto";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const config = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux.iso" },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
    disable_jit: +process.env.DISABLE_JIT,
};

const emulator = new V86(config);

let serial_data = [];

setTimeout(async () =>
{
    await emulator.wait_until_vga_screen_contains("/root% ");
    console.log("Booted, sending file to ttyS0");
    emulator.keyboard_send_text("cat /bin/busybox > /dev/ttyS0\n");
}, 1000);

const timeout = setTimeout(() => {
    console.log(serial_data);
    throw new Error("Timeout");
}, 60 * 1000);

emulator.add_listener("serial0-output-byte", function(byte)
{
    serial_data.push(byte);

    if(serial_data.length === 510277)
    {
        const hash = crypto.createHash("sha256");
        hash.update(new Uint8Array(serial_data));
        assert("da1fb5b421123c58080a59832675632505b8c139a8d7ecd1c31591ca5c65cea6" === hash.digest("hex"));
        console.log("ok");
        clearTimeout(timeout);
        emulator.destroy();
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/api/site_states.mjs                                                                0000755 0000000 0000000 00000037025 00000000000 014653  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The retro-gaming-site's saved states across the move of the NE2000 and the
// SB16 into plugins (docs/modern-pc-devices-plan.md M1). Each state of the
// site's game table (app.js GAMES: Windows 98 and XP machines with an NE2000
// and an SB16, saved before M1 with untagged state[59] and state[61]) is
// restored as the site's page does (the same options, the site's BIOS):
// - with this build: the plugins read the old slots; the cards' states equal
//   what the build before M1 (OLD_LIB) restores, field for field (the
//   NE2000's own address is random each time: its address in the state,
//   which the guest uses through mac_address_translation, is compared)
// - both builds run it for SECONDS: the guest goes on (instructions, no
//   reset), the SB16 plays (samples to a speaker that takes them at the
//   sampling rate, how many are not silent), the NE2000 sends what it sends;
//   the two builds' figures side by side
// - this build saves it again (format 8, tagged slots): the save restores in
//   this build and goes on; the build before M1 refuses it ("Version
//   mismatch") instead of reading tagged slots as registers
//
// A local test: the site's checkout beside the v86 checkout (SITE=<dir>),
// its states and game disks there (the XP system disk, which the site keeps
// only in parts on its R2 bucket, read from there as the page reads it, the
// parts kept in build/site-parts). The
// GL bridge's device is there for the states that have it, without a renderer.
// OLD_LIB=<libv86.mjs of the build before M1>, STATES=<game ids, comma
// separated>, SECONDS=20, REPORT=<file.json>.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import { execFileSync } from "node:child_process";
import { createRequire as create_require } from "node:module";
import zlib from "node:zlib";
import { ReadOnlyOverlayDisk } from "../smp/disk_fixture.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = path.resolve(__dirname, "../..");
process.on("unhandledRejection", exn => { throw exn; });

const SITE = path.resolve(process.env.SITE || ["../retro-gaming-site", "../../../retro-gaming-site"].map(up => path.join(ROOT, up))
    .find(candidate => fs.existsSync(candidate)) || "retro-gaming-site");
if(!fs.existsSync(path.join(SITE, "app.js")))
{
    console.log("Skipped: no retro-gaming-site checkout at " + SITE + " (SITE)");
    process.exit(0);
}
const SECONDS = +process.env.SECONDS || 20;
const { V86 } = await import(path.join(ROOT, "build/libv86.mjs"));
const OLD = process.env.OLD_LIB ? (await import(path.resolve(process.env.OLD_LIB))).V86 : null;

// the GL bridge's virtio device (the site's graphics_proxy: true; some of its
// states have it), on a channel that does not answer: no renderer here
const { createV86GLDevice: create_v86gl_device } = create_require(import.meta.url)("../../src/browser/glbridge/v86gl_device.js");

// the site's game table: its data, evaluated with its bucket URLs
const app = fs.readFileSync(path.join(SITE, "app.js"), "utf8");
const constant = name => app.match(new RegExp("const " + name + " = \"([^\"]+)\""))[1];
const table = app.match(/^const GAMES = (\{[^]*?^\});/m)[1];
const GAMES = new Function("R2_URL_1", "R2_URL_2", "return " + table)(constant("R2_URL_1"), constant("R2_URL_2"));
const wanted = process.env.STATES ? process.env.STATES.split(",") : Object.keys(GAMES);

const PART = 1024 * 1024, BLOCK = 256;
const PART_CACHE = path.join(ROOT, "build/site-parts");
const parts_in_memory = new Map();
let fetching = 0;
const waiting = [];

/** A part of the bucket, unpacked: from PART_CACHE or fetched (a few at a time), the last 256 kept in memory */
function bucket_part(url)
{
    let part = parts_in_memory.get(url);
    if(part)
    {
        parts_in_memory.delete(url);
        parts_in_memory.set(url, part);
        return part;
    }
    part = (async () => {
        const file = path.join(PART_CACHE, new URL(url).pathname.replace(/\//g, "_"));
        let packed;
        if(fs.existsSync(file)) packed = fs.readFileSync(file);
        else
        {
            if(fetching >= 8) await new Promise(resolve => waiting.push(resolve));
            fetching++;
            try
            {
                for(let attempt = 1; ; attempt++)
                {
                    try
                    {
                        const response = await fetch(url);
                        if(!response.ok) throw new Error("HTTP " + response.status);
                        packed = Buffer.from(await response.arrayBuffer());
                        break;
                    }
                    catch(error)
                    {
                        if(attempt === 3) throw new Error(url + ": " + error.message);
                        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
                    }
                }
            }
            finally
            {
                fetching--;
                waiting.shift()?.();
            }
            fs.mkdirSync(PART_CACHE, { recursive: true });
            fs.writeFileSync(file, packed);
        }
        const bytes = new Uint8Array(url.endsWith(".zst") ? zlib.zstdDecompressSync(packed) : packed);
        assert.equal(bytes.length, PART, url);
        return bytes;
    })();
    part.catch(() => parts_in_memory.delete(url));
    parts_in_memory.set(url, part);
    if(parts_in_memory.size > 256) parts_in_memory.delete(parts_in_memory.keys().next().value);
    return part;
}

/**
 * A disk the site keeps only on its bucket, in 1 MiB parts (fixed_chunk_size,
 * use_parts), read-only: the library in node reads files only, so the parts
 * are fetched and unpacked here. The guest's writes stay in an overlay of
 * 256-byte blocks, in the state the page's disk has (src/buffer.js), so the
 * site's states restore into it.
 */
class BucketDisk
{
    constructor(url, size)
    {
        const extension = url.match(/\.[^.]+(\.zst)?$/)[0];
        this.part_url = index => url.slice(0, -extension.length) + "-" + index * PART + "-" + (index + 1) * PART + extension;
        this.byteLength = size;
        this.overlay = new Map();
    }
    load() { this.onload?.({}); }
    get(start, length, done)
    {
        const first = Math.floor(start / PART), last = Math.floor((start + length - 1) / PART);
        const parts = [];
        for(let index = first; index <= last; index++) parts.push(bucket_part(this.part_url(index)));
        Promise.all(parts).then(parts => {
            const data = new Uint8Array(length);
            parts.forEach((part, i) => {
                const at = (first + i) * PART, from = Math.max(start, at), to = Math.min(start + length, at + PART);
                data.set(part.subarray(from - at, to - at), from - start);
            });
            for(let block = Math.floor(start / BLOCK); block * BLOCK < start + length; block++)
            {
                const written = this.overlay.get(block);
                if(!written) continue;
                const from = Math.max(start, block * BLOCK), to = Math.min(start + length, (block + 1) * BLOCK);
                data.set(written.subarray(from - block * BLOCK, to - block * BLOCK), from - start);
            }
            done(data);
        }, error => done(undefined, error));
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done)
    {
        assert.ok(start % BLOCK === 0 && data.length % BLOCK === 0 && start + data.length <= this.byteLength);
        for(let at = 0; at < data.length; at += BLOCK) this.overlay.set((start + at) / BLOCK, data.slice(at, at + BLOCK));
        done?.();
    }
    get_buffer(done) { done(undefined); }
    get_state()
    {
        const blocks = [...this.overlay.keys()];
        const bytes = new Uint8Array(blocks.length * BLOCK);
        blocks.forEach((block, i) => bytes.set(this.overlay.get(block), i * BLOCK));
        return [null, Float64Array.from(blocks), [bytes]];
    }
    set_state(state)
    {
        this.overlay.clear();
        if(state[0])
        {
            for(const [block, bytes] of state[0]) this.overlay.set(block, bytes.slice());
            return;
        }
        let i = 0;
        for(const chunk of state[2])
            for(let at = 0; at < chunk.length; at += BLOCK) this.overlay.set(state[1][i++], chunk.slice(at, at + BLOCK));
        assert.equal(i, state[1].length, "the disk's written blocks");
    }
}

/** A disk of the site: the local file of the same name if there is one, else the bucket's parts, as the page reads them */
function disk(location, size)
{
    const name = path.basename(location).replace(/\.zst$/, "");
    for(const candidate of [path.join(SITE, "game", name), path.join(SITE, "windows98/windows98multidisk", name)])
    {
        if(fs.existsSync(candidate) && fs.statSync(candidate).size === size) return new ReadOnlyOverlayDisk(candidate);
    }
    return new BucketDisk(location.startsWith("http") ? location : constant("R2_URL_1") + location, size);
}

/** A machine as the site's page makes it (startEmulator9xMultiDisk), not running yet */
async function machine(Lib, game, gl)
{
    const emulator = new Lib({
        memory_size: game.memorySize,
        vram_size: 16 * 1024 * 1024,
        graphics_adapter: "bochs_vga",
        bios: { url: path.join(SITE, "bios/seabios.bin") },
        vga_bios: { url: path.join(SITE, "bios/vgabios.bin") },
        hda: disk(game.systemDisk, game.systemDiskSize),
        hdb: disk(game.disk, game.size),
        acpi: false,
        net_device: { type: "ne2k" },
        preserve_mac_from_state_image: false,
        mac_address_translation: true,
        boot_order: 0x213,
        virtio_devices: gl ? [create_v86gl_device({ remote: false, post() {}, listen() {} })] : undefined,
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        autostart: false,
        log_level: 0,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}

/** The cards of a machine: before M1 the core's devices, since then the plugins' */
function cards(emulator)
{
    const devices = emulator.v86.cpu.devices;
    return {
        ne2k: devices.net && (devices.net.device ? devices.net.device["card"] : devices.net),
        sb16: devices.sb16 || devices.audio && devices.audio.device["card"],
    };
}

/** A state as plain values (typed arrays as arrays), for comparing */
const plain = state => JSON.parse(JSON.stringify(state, (key, value) => ArrayBuffer.isView(value) ? Array.from(value) : value));

/** The cards' states, the NE2000's own random address left out (its address in the state is) */
function card_states(emulator)
{
    const { ne2k, sb16 } = cards(emulator);
    const net = plain(ne2k.get_state());
    net[15] = "own address";
    return { ne2k: net, mac_in_state: plain(ne2k.mac_address_in_state), sb16: plain(sb16.get_state()) };
}

/** Run for SECONDS with a speaker that takes the SB16's samples at its rate: what happened */
async function run(emulator, seconds)
{
    const cpu = emulator.v86.cpu;
    const resets_before = cpu.last_reset ? cpu.last_reset["count"] : 0;
    let rate = 22050, queued = 0, last = performance.now(), samples = 0, loud = 0, frames = 0;
    emulator.bus.register("dac-tell-sampling-rate", r => { rate = r; });
    emulator.bus.register("dac-send-data", data => {
        queued += data[0].length;
        samples += data[0].length;
        for(const channel of data) for(const sample of channel) if(Math.abs(sample) > 1e-3) loud++;
    });
    emulator.bus.register("net0-send", () => { frames++; });
    const speaker = setInterval(() => {
        const now = performance.now();
        queued = Math.max(0, queued - rate * (now - last) / 1000);
        last = now;
        if(queued < rate * 0.2) emulator.bus.send("dac-request-data");
    }, 5);
    const before = emulator.get_instruction_counter() >>> 0;
    let instructions = 0, previous = before;
    await emulator.run();
    const end = Date.now() + seconds * 1000;
    while(Date.now() < end)
    {
        await new Promise(resolve => setTimeout(resolve, 250));
        const now = emulator.get_instruction_counter() >>> 0;
        instructions += (now - previous) >>> 0;
        previous = now;
    }
    await emulator.stop();
    clearInterval(speaker);
    return {
        instructions,
        reset: (cpu.last_reset ? cpu.last_reset["count"] : 0) !== resets_before,
        samples, loud, frames,
    };
}

const report = {};
let failed = 0;
for(const id of wanted)
{
    const game = GAMES[id];
    const file = path.join(SITE, game.stateurl.replace(/^https?:\/\/[^/]+\//, ""));
    if(!fs.existsSync(file))
    {
        console.log("skip " + id + ": no local " + file);
        continue;
    }
    const raw = execFileSync("zstd", ["-dc", file], { maxBuffer: 2 ** 31 });
    const version = raw.readInt32LE(4);
    const state = raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.length);
    const gl = raw.subarray(16, 16 + raw.readInt32LE(12)).includes("\"v86gl\"");
    const entry = report[id] = { version };
    try
    {
        // this build: the old slots through the plugins
        let emulator = await machine(V86, game, gl);
        await emulator.restore_state(state);
        assert.equal(emulator.v86.cpu.devices.net.name, "ne2k");
        assert.equal(emulator.v86.cpu.devices.audio.name, "sb16");
        const restored = card_states(emulator);
        entry.new = await run(emulator, SECONDS);
        const resaved = await emulator.save_state();
        await emulator.destroy();
        assert.equal(new Int32Array(resaved, 0, 2)[1], 8, "saved again: format 8");

        // its own save (the slots tagged), back in this build
        const header = new Int32Array(resaved, 0, 4);
        const tagged = JSON.parse(Buffer.from(resaved, 16, header[3]).toString("utf8")).state;
        assert.deepEqual([tagged[59][0], tagged[59][2], tagged[61][0], tagged[61][2]], ["net_adapter", "ne2k", "audio_device", "sb16"]);
        emulator = await machine(V86, game, gl);
        await emulator.restore_state(resaved);
        entry.resaved = await run(emulator, Math.min(SECONDS, 5));
        await emulator.destroy();
        assert.ok(entry.resaved.instructions > 0 && !entry.resaved.reset, "the new save goes on");

        if(OLD)
        {
            // the build before M1: the same cards' states, its own run
            emulator = await machine(OLD, game, gl);
            await emulator.restore_state(state);
            assert.deepEqual(restored, card_states(emulator), "the cards' states as the build before M1 restores them");
            entry.old = await run(emulator, SECONDS);
            // and this build's new save: refused
            await assert.rejects(emulator.restore_state(resaved), /Version mismatch/);
            await emulator.destroy();
        }
        assert.ok(entry.new.instructions > 0 && !entry.new.reset, "the guest goes on");
        if(entry.old) assert.equal(entry.new.reset, entry.old.reset);
        console.log("ok - " + id + " (format " + version + "): " + JSON.stringify(entry));
    }
    catch(error)
    {
        failed++;
        entry.error = String(error && error.stack || error);
        console.log("FAIL - " + id + ": " + entry.error.split("\n").slice(0, 4).join(" | ") + " " + JSON.stringify(entry));
    }
}
if(process.env.REPORT) fs.writeFileSync(process.env.REPORT, JSON.stringify(report, null, 1));
console.log((failed ? "FAIL" : "PASS") + ": " + (Object.keys(report).length - failed) + " of " + Object.keys(report).length + " states");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/api/state.js                                                                       0000755 0000000 0000000 00000013256 00000000000 013267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const config_async_cdrom = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    autostart: true,
    memory_size: 64 * 1024 * 1024,
    filesystem: {},
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
};

const config_sync_cdrom = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: false },
    autostart: true,
    memory_size: 64 * 1024 * 1024,
    filesystem: {},
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
};

const config_filesystem = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    autostart: true,
    memory_size: 64 * 1024 * 1024,
    filesystem: {},
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
    cmdline: "tsc=reliable mitigations=off random.trust_cpu=on",
    network_relay_url: "<UNUSED>",
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
};

const config_large_memory = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso", async: true },
    autostart: true,
    memory_size: 2048 * 1024 * 1024,
    // (the most vram_size allows, MAX_VRAM_SIZE in src/graphics_adapter.js)
    vram_size: 256 * 1024 * 1024,
    network_relay_url: "<UNUSED>",
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
};

async function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }

async function run_test(name, config, done)
{
    const emulator = new V86(config);

    await sleep(2000);

    console.log("Saving: %s", name);
    const before_save = await emulator.get_diagnostics();
    const state = await emulator.save_state();

    await sleep(1000);

    console.log("Restoring: %s", name);
    await emulator.restore_state(state);

    const booted = await emulator.wait_until_vga_screen_contains("~% ", { timeout_msec: 120000 });
    if(!booted)
    {
        console.error("Timed out after restoring: " + name);
        console.error(JSON.stringify({ before_save, after_restore: await emulator.get_diagnostics() }));
        console.error(emulator.screen_adapter.get_text_screen());
        emulator.destroy();
        throw new Error("Guest did not boot after restoring " + name);
    }
    await sleep(1000);

    emulator.keyboard_send_text("echo -n test; echo passed\n");
    const responded = await emulator.wait_until_vga_screen_contains("testpassed", { timeout_msec: 10000 });
    if(!responded)
    {
        console.warn("Failed: " + name);
        const lines = emulator.screen_adapter.get_text_screen();
        console.warn(lines.map(line => line.replace(/\x00/g, " ")));
        process.exit(1);
    }

    console.log("Done: %s", name);
    emulator.destroy();
}

// Before the BIOS has enumerated PCI (there is none here), the IDE controller
// of a machine without a primary drive reports I/O BARs for the holes in its
// pci_bars
async function run_test_before_pci_enumeration()
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { buffer: new Uint8Array(0x10000).fill(0xF4).buffer },
        memory_size: 16 * 1024 * 1024,
        autostart: false,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

    console.log("Saving and restoring: before PCI enumeration");
    await emulator.restore_state(await emulator.save_state());

    console.log("Done: before PCI enumeration");
    emulator.destroy();
}

// The UART's receive queue belongs to the snapshot: Linux's 8250 driver
// sizes the FIFO by looping 256 bytes back, and a restore that kept the
// queue of the timeline it discards handed them to the console (^\ killed
// init, the sync cdrom case failing now and then)
async function run_test_uart_queue()
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { buffer: new Uint8Array(0x10000).fill(0xF4).buffer },
        memory_size: 16 * 1024 * 1024,
        autostart: false,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const uart = emulator.v86.cpu.devices.uart0;

    console.log("Saving and restoring: the UART's receive queue");
    uart.data_received(0x41);
    uart.data_received(0x42);
    const state = await emulator.save_state();
    uart.input.length = 0;
    for(let byte = 0; byte < 256; byte++) uart.data_received(byte);
    await emulator.restore_state(state);
    assert.deepEqual(uart.input, [0x41, 0x42], "the queue at the save");

    console.log("Done: the UART's receive queue");
    emulator.destroy();
}

(async function() {
    await run_test_before_pci_enumeration();
    await run_test_uart_queue();
    await run_test("async cdrom", config_async_cdrom);
    await run_test("sync cdrom", config_sync_cdrom);
    await run_test("filesystem", config_filesystem);
    await run_test("large memory size", config_large_memory);
})();
                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/api/test.js                                                                        0000755 0000000 0000000 00000001537 00000000000 013125  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { url: __dirname + "/../../images/freedos722.img", async: true },
    network_relay_url: "<UNUSED>",
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    log_level: -641,
    disable_jit: +process.env.DISABLE_JIT,
});

setInterval(() => {
    console.log(emulator.screen_adapter.get_text_screen());
}, 500);
                                                                                                                                                                 source/v64/tests/app/android_gles_test.html                                                         0000644 0000000 0000000 00000016740 00000000000 016175  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: Android 7.1 on the host's GPU</title>
<!-- The VM manager starting the "Android (ARM 32-bit)" preset with its default GPU, the host's (docs/gles-proxy-plan.md E5):
     the imported emulator image (tools/android_import.mjs's build/a32-android/disk.img, by URL), the CPU in its Worker,
     the GLES host's plugin there and the renderer on this page's WebGPU. Passes when Android's boot completes (asked
     over the serial console), the page's GLES executor drew and posted frames into a layer of the screen's compositor
     (not read back), and the screen shows them.
     TIMEOUT_MS=1800000 node tests/app/browser_runner.mjs tests/app/android_gles_test.html webgpu=1 [worker=0] -->
<style>iframe { width: 600px; height: 1000px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { VMStore } from "../../src/app/vm_store.js";
import { preset, preset_config } from "../../src/app/guest_presets.js";

const args = new URLSearchParams(location.search);
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(1000);
    }
}
function check(condition, what) { if(!condition) throw new Error(what); }

(async () =>
{
    const started = Date.now();
    const seconds = () => Math.round((Date.now() - started) / 1000) + " s";
    try
    {
        const config = preset_config(preset("android7_arm32"));
        config.name = "Android 7.1 (GLES test)";
        // (read_only: the guest's writes stay in memory; read_write would need a disk service)
        config.disks = [{ slot: "hda", image: { kind: "url", url: "/build/a32-android/disk.img", async: true },
            disk_option: "read_only", disk_error: "stop" }];
        if(args.get("worker") === "0") config.advanced.cpu_worker = false;
        check(config.android.gpu_mode === "host", "the preset's GPU is the host's: " + config.android.gpu_mode);
        const store = await VMStore.open();
        const stored = await store.put(config);
        store.close();
        const frame = document.createElement("iframe");
        frame.src = "/index.html?vm=" + stored.id;
        document.body.append(frame);
        await new Promise(resolve => frame.onload = resolve);
        const w = frame.contentWindow;
        const emulator = await until(() => w.v86_console?.emulator, "the console's emulator", 120000);
        log("emulator up (" + (config.advanced.cpu_worker ? "CPU Worker" : "CPU in the page") + "), " + seconds());
        let serial = "", serial_bytes = 0;
        emulator.add_listener("serial0-output-byte", byte => { serial_bytes++; serial = (serial + String.fromCharCode(byte)).slice(-20000); });
        // (progress every minute: the console's last line, the guest's instructions, the page's GLES executor)
        const progress = setInterval(() =>
        {
            const g = emulator.adapter_renderer && emulator.adapter_renderer.gles;
            const last = serial.split("\n").map(l => l.trim()).filter(Boolean).slice(-1)[0] || "";
            const doc = frame.contentDocument;
            const status = [".console-status", ".console-notice"].map(q => doc.querySelector(q)).filter(Boolean)
                .map(e => e.textContent.trim()).filter(Boolean).join(" | ");
            log(seconds() + ": console \"" + status.slice(0, 200) + "\"; serial " + serial_bytes + " bytes, last \"" + last.slice(0, 100) + "\"; instructions " +
                emulator.get_instruction_counter() + "; gles " + (g ? JSON.stringify({ batches: g.stats.batches, draws: g.stats.draws, posts: g.stats.posts }) : "none"));
        }, 60000);
        // (the console's shell, then sys.boot_completed, asked now and then: a computed answer)
        let tick = 0;
        await until(() =>
        {
            if(/A32_BOOT_1_X/.test(serial)) return true;
            if(tick++ % 30 === 0) emulator.serial0_send("\necho A32_BOOT_$(getprop sys.boot_completed)_X\n");
            return false;
        }, "sys.boot_completed", 1500000);
        log("boot completed, " + seconds());
        clearInterval(progress);
        // (the screen woken, the keyguard dismissed, home: as tests/a32/android_boot.mjs; until then the display is dark)
        emulator.serial0_send("input keyevent 224; sleep 2; wm dismiss-keyguard; sleep 2; input keyevent 3\n");
        const renderer = emulator.adapter_renderer;
        check(renderer && renderer.gles, "the page has the GLES executor");
        const stats = renderer.gles.stats;
        log("executor: " + JSON.stringify({ batches: stats.batches, draws: stats.draws, posts: stats.posts, errors: stats.errors.length }));
        check(stats.draws > 100 && stats.posts > 10, "the executor drew and posted frames");
        check(stats.errors.length === 0, "no executor errors: " + stats.errors.join("; "));
        // (frames as a layer of the screen's compositor, not read back: the executor has the layer)
        check(renderer.gles.layer, "the posted frames go to a layer of the screen's compositor");
        // (the screen through the console's screenshot: the compositor's picture, the layer in it; until it has Android's colors)
        let shot, pixels, colors;
        await until(async () =>
        {
            const image = emulator.screen_make_screenshot();
            await new Promise(resolve => { if(image.complete) resolve(); else image.onload = resolve; });
            shot = document.createElement("canvas");
            shot.width = image.width;
            shot.height = image.height;
            const context = shot.getContext("2d");
            context.drawImage(image, 0, 0);
            pixels = context.getImageData(0, 0, shot.width, shot.height).data;
            colors = new Set();
            for(let i = 0; i < pixels.length; i += 4 * 97) colors.add(pixels[i] << 16 | pixels[i + 1] << 8 | pixels[i + 2]);
            return colors.size > 20;
        }, "the home screen on the screen", 600000).catch(() => {});
        log("screen " + shot.width + "x" + shot.height + ", " + colors.size + " colors; first pixel " + Array.from(pixels.subarray(0, 4)));
        // (the compositor's view: device, scanout, layers)
        const compositor = emulator.gles_compositor;
        log("compositor: " + (compositor ? JSON.stringify({ same_device: compositor.device === renderer.gles.device,
            scanout: !!compositor.scanout, size: [compositor.canvas.width, compositor.canvas.height], stats: compositor.stats,
            layers: compositor.layers.map(l => ({ name: l.name, visible: l.visible, texture: !!l.texture, same: l.textureDevice === compositor.device,
                place: [l.x, l.y, l.width, l.height] })) }) : "none"));
        // (the picture itself, for the report: a data URL in the log)
        log("screenshot " + shot.toDataURL("image/png"));
        check(shot.width === 480 && shot.height === 800, "the screen is the device's 480 by 800");
        check(colors.size > 20, "the screen shows Android's picture");
        document.getElementById("result").textContent = "PASS " + lines.join("; ");
    }
    catch(error)
    {
        document.getElementById("result").textContent = "FAIL " + (error && error.stack || error) + "\n" + lines.join("\n");
    }
})();
</script>
                                source/v64/tests/app/app_test.html                                                                  0000644 0000000 0000000 00000022141 00000000000 014313  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: the page</title>
<!-- The VM manager's page in a frame (docs/vm-manager-plan.md U2): the
     library starts empty; New, Rename and Export; Import of a FreeDOS machine
     (a .v86vm.json naming images/freedos722.img); Power on opens its console,
     which boots FreeDOS to "Welcome to FreeDOS"; get_cdrom_state; Delete.
     The frame's file picker, window.open and downloads are taken over.
     node tests/app/browser_runner.mjs tests/app/app_test.html [page=app_debug.html] [worker=0] -->
<style>iframe { width: 1000px; height: 700px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { new_config } from "../../src/app/vm_config.js";
import { export_config } from "../../src/app/vm_store.js";

const args = new URLSearchParams(location.search);
const page = args.get("page") || "index.html";
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout = 30000)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(100);
    }
}
function check(condition, what)
{
    if(!condition) throw new Error(what);
}

/** The page in a frame; resolves when its document is there */
async function open_frame(url)
{
    const frame = document.createElement("iframe");
    frame.src = url;
    document.body.append(frame);
    await new Promise(resolve => frame.onload = resolve);
    return frame;
}

async function main()
{
    const frame = await open_frame("/" + page);
    const w = frame.contentWindow, d = frame.contentDocument;
    const $ = selector => d.querySelector(selector);
    const names = () => Array.from(d.querySelectorAll(".vm-list .vm-name"), e => e.textContent);
    await until(() => $(".library"), "the library");
    check(names().length === 0 && /No virtual machines yet/.test($(".library-list").textContent), "an empty library");
    log("the library: empty");

    // New: the wizard, "install later", the "Other" preset's machine, its name by default, no disk
    const create = async () =>
    {
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        const next = () => Array.from(wizard.querySelectorAll("button")).find(b => b.textContent === "Next").click();
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.value === "later").click();
        next();
        await until(() => wizard.querySelector("li[data-preset=other].selected"), "the preset");
        next();
        await until(() => wizard.querySelector("input[aria-label=Name]"), "the name");
        next();
        (await until(() => wizard.querySelector("input[name=disk][value=none]"), "the disk")).click();
        next();
        (await until(() => Array.from(wizard.querySelectorAll("button")).find(b => b.textContent === "Finish"), "the summary")).click();
    };
    await create();
    await until(() => names().length === 1, "a new machine in the list");
    check(names()[0] === "Other", "its name: " + names()[0]);
    check(/Memory128MB/.test($(".hardware").textContent.replace(/\s+/g, "")), "its hardware: " + $(".hardware").textContent);
    await create();
    await until(() => names().length === 2, "a second new machine");
    check(names().includes("Other 2"), "the second's name");
    log("New (the wizard): " + names().join(", "));

    // rename the selected one in the dialog
    const selected = $(".vm-list li.selected .vm-name").textContent;
    $("#rename_vm").click();
    const input = await until(() => $("dialog[open] input"), "the rename dialog");
    input.value = "Renamed machine";
    Array.from(d.querySelectorAll("dialog[open] button")).find(b => b.textContent === "OK").click();
    await until(() => names().includes("Renamed machine"), "the new name");
    check(!names().includes(selected), "the old name is gone");
    log("Rename: " + selected + " -> Renamed machine");

    // export: the download's file
    let exported;
    const create_url = w.URL.createObjectURL;
    w.URL.createObjectURL = blob => { exported = blob; return create_url.call(w.URL, blob); };
    w.HTMLAnchorElement.prototype.click = function() { exported_name = this.download; };
    let exported_name;
    $("#export_vm").click();
    await until(() => exported && exported_name, "the export");
    const exported_config = JSON.parse(await exported.text());
    check(exported_config.format === "v86-vm" && exported_config.name === $(".summary h1").textContent, "the exported configuration");
    check(exported_name === exported_config.name + ".v86vm.json", "the export's name " + exported_name);
    log("Export: " + exported_name);

    // import a FreeDOS machine: the frame's file picker answers with the file
    const freedos = new_config({ name: "FreeDOS", notes: "from images/freedos722.img" });
    freedos.floppies = [{ slot: "fda", image: { kind: "url", url: "images/freedos722.img", size: 737280 }, disk_option: "read_only" }];
    if(args.get("worker") === "0") freedos.advanced.cpu_worker = false;
    w.HTMLInputElement.prototype.click = function()
    {
        const transfer = new w.DataTransfer();
        transfer.items.add(new w.File([export_config(freedos)], "FreeDOS.v86vm.json", { type: "application/json" }));
        this.files = transfer.files;
        this.dispatchEvent(new w.Event("change"));
    };
    $("#import_vm").click();
    await until(() => names().includes("FreeDOS"), "the imported machine");
    check($(".summary h1").textContent === "FreeDOS", "the imported machine is selected");
    check(/Floppy\(fda\)images\/freedos722\.img/.test($(".hardware").textContent.replace(/\s+/g, "")), "its floppy: " + $(".hardware").textContent);
    log("Import: FreeDOS, " + names().length + " machines");

    // power on: a new tab (here another frame) with its console
    let opened;
    w.open = url => { opened = url; return null; };
    $("#power_on").click();
    await until(() => opened, "window.open");
    check(/\?vm=[0-9a-f-]{36}$/.test(opened), "the console's address " + opened);
    const console_frame = await open_frame(new URL(opened, w.location.href).href);
    const c = console_frame.contentDocument;
    await until(() => c.getElementById("screen_container"), "the console's screen");
    await until(() => c.title.startsWith("FreeDOS - v86"), "the console's title, its machine's name (" + c.title + ")");
    const emulator = await until(() => console_frame.contentWindow.v86_console?.emulator, "the console's emulator");
    // (text mode is drawn on the canvas: the emulator reads its screen)
    await emulator.wait_until_vga_screen_contains("Welcome to FreeDOS", { timeout_msec: 120000 }).then(found =>
    {
        if(!found) throw new Error("no \"Welcome to FreeDOS\" on the screen; the console's status: " + c.querySelector(".console-status").textContent);
    });
    log("Power on: the console at " + opened.replace(/^.*\?/, "?") + " boots FreeDOS: \"Welcome to FreeDOS\"");
    const cdrom = await emulator.get_cdrom_state();
    check(cdrom.present === true && cdrom.inserted === false, "get_cdrom_state: the i440FX machine's empty CD drive: " + JSON.stringify(cdrom));
    log("get_cdrom_state: " + JSON.stringify(cdrom));
    // power off from the Power menu (its confirmation)
    c.querySelector("#menu_power").click();
    (await until(() => c.querySelector("#menu_power_off"), "the Power menu")).click();
    const yes = await until(() => Array.from(c.querySelectorAll("dialog[open] button")).find(b => b.textContent === "Power off"), "the power off dialog");
    yes.click();
    await until(() => /Powered off/.test(c.querySelector(".console-status").textContent), "powered off");
    log("Power off: confirmed, the console says so");

    // delete the FreeDOS machine
    $("#delete_vm").click();
    const confirm_delete = await until(() => Array.from(d.querySelectorAll("dialog[open] button")).find(b => b.textContent === "Delete"), "the delete dialog");
    confirm_delete.click();
    await until(() => !names().includes("FreeDOS"), "deleted");
    log("Delete: " + names().length + " machines left");

    // the library after a reload
    w.location.reload();
    await new Promise(resolve => frame.onload = resolve);
    await until(() => frame.contentDocument.querySelector(".library"), "the library again");
    const after = Array.from(frame.contentDocument.querySelectorAll(".vm-list .vm-name"), e => e.textContent).sort();
    check(JSON.stringify(after) === JSON.stringify(["Other 2", "Renamed machine"].sort()) ||
        JSON.stringify(after) === JSON.stringify(["Other", "Renamed machine"].sort()), "after the reload: " + after);
    log("after a reload: " + after.join(", "));
}

main().then(() =>
{
    document.getElementById("result").textContent = "PASS (" + page + ")\n" + lines.join("\n");
}, e =>
{
    document.getElementById("result").textContent = "FAIL (" + page + "): " + (e.stack || e.message) + "\n" + lines.join("\n");
});
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/app/browser_disk_test.html                                                         0000644 0000000 0000000 00000032330 00000000000 016231  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: browser disks</title>
<!-- Browser disks (docs/vm-manager-plan.md U6), machines in frames ("tabs"):
     part=linux    Linux 4.16 (images/linux4.iso) formats a new browser disk, writes a file, syncs, powers off; the tab
                   closed and opened again: the file is there; a file synced, the tab closed without powering off after
                   the timed flush: there too
     part=import   images/msdos622.img imported (its SHA-256 the source's), exported (the same bytes), MS-DOS on it
                   writes a file, which is in the disk after power off
     part=share    two machines with one browser disk: the second is refused while the first runs; one suspended, the
                   other writes to the disk: the resume is refused; the library's Browser disks dialog; deleting a
                   machine deletes its own disk, not the shared one
     part=page     the CPU in the page: a browser disk written back is refused at the start
     node tests/app/browser_runner.mjs tests/app/browser_disk_test.html part=linux -->
<style>iframe { width: 1000px; height: 650px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { VMStore } from "../../src/app/vm_store.js";
import { new_config } from "../../src/app/vm_config.js";
import { create_disk, import_disk, export_disk, disk_file, list_disks, disk_id } from "../../src/app/browser_disks.js";
import { SHA256 } from "../../src/image/sha256.js";

const args = new URLSearchParams(location.search);
const part = args.get("part") || "linux";
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout = 30000)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(100);
    }
}
function check(condition, what) { if(!condition) throw new Error(what); }
const sha256 = bytes => { const h = new SHA256(); h.update(bytes); return h.hex(); };
const contains = (bytes, text) => { const needle = new TextEncoder().encode(text); outer: for(let i = 0; i + needle.length <= bytes.length; i++) { for(let j = 0; j < needle.length; j++) if(bytes[i + j] !== needle[j]) continue outer; return true; } return false; };

let store;
async function machine(name, fields)
{
    return store.put(Object.assign(new_config({ name }), fields));
}
/** a console tab; its emulator (or, with expect_error, its notice's text) */
async function open_console(id, { expect_error = false } = {})
{
    const frame = document.createElement("iframe");
    frame.src = "/index.html?vm=" + id;
    document.body.append(frame);
    await new Promise(resolve => frame.onload = resolve);
    const w = frame.contentWindow, d = frame.contentDocument;
    const $ = s => d.querySelector(s);
    const menu = async (m, item) => { $("#" + m).click(); (await until(() => $("#" + item), item)).click(); };
    const power_off = async () =>
    {
        await menu("menu_power", "menu_power_off");
        Array.from((await until(() => $("dialog[open]"), "the power off dialog")).querySelectorAll("button")).find(b => b.textContent === "Power off").click();
        await until(() => /Powered off/.test($(".console-status").textContent), "powered off", 60000);
    };
    if(expect_error)
    {
        const text = await until(() => $(".console-notice p.error")?.textContent, "the console's error", 60000);
        return { frame, w, d, $, text };
    }
    const emulator = await until(() => w.v86_console?.emulator, "the console's emulator", 60000);
    return { frame, w, d, $, menu, power_off, emulator };
}
const type = (emulator, text) => emulator.keyboard_send_text(text + "\n", 20);
const screen = (emulator, pattern, timeout = 120000) => emulator.wait_until_vga_screen_contains(pattern, { timeout_msec: timeout });
// MS-DOS's prompt once AUTOEXEC.BAT is done (its last program's line, then the
// prompt at the bottom): the batch file's commands show "C:\>" before, and keys
// typed while its programs load overflow the BIOS's buffer of 15
const DOS_PROMPT = [/MSCD001 unit 0$/, "", /^C:\\>$/];
/** Linux's shell, once it reads the keys: the kernel registers the keyboard
 * after the first prompt (keys typed before are lost), so an echo until its line comes */
async function linux_shell(emulator, what)
{
    check(await screen(emulator, /^~%/, 240000), what);
    for(let i = 1; ; i++)
    {
        await type(emulator, "echo READY-" + i);
        // (a line of the screen ends in spaces)
        if(await screen(emulator, new RegExp("^READY-" + i + " *$"), 5000)) return;
        check(i < 5, what + " reads the keys");
    }
}
/** a page's error, as the console shows it when the machine does not start */
async function start_error(c)
{
    return until(() => c.$(".console-notice p.error")?.textContent, "the start's error", 60000);
}

const linux_vm = path => ({
    cdrom: { image: { kind: "url", url: "images/linux4.iso", async: true }, disk_error: "stop" },
    disks: [{ slot: "hda", image: { kind: "browser", path, size: 32 << 20 }, disk_option: "read_write", disk_error: "stop" }],
});
const dos_vm = path => ({
    disks: [{ slot: "hda", image: { kind: "browser", path, size: 64 << 20 }, disk_option: "read_write", disk_error: "stop" }],
});

const parts = {
    async linux()
    {
        const disk = await create_disk(32 << 20, "linux disk", store);
        const config = await machine("Linux on a browser disk", linux_vm(disk.path));
        let c = await open_console(config.id);
        await linux_shell(c.emulator, "Linux's shell");
        await type(c.emulator, "mke2fs -q /dev/sda && mkdir -p /mnt && mount /dev/sda /mnt && echo PERSISTENT > /mnt/note && sync && umount /mnt && echo FORMATTED-OK");
        check(await screen(c.emulator, /^FORMATTED-OK/), "formatted, written, synced");
        await c.power_off();
        c.frame.remove();
        log("Linux formatted the browser disk, wrote /note, synced, powered off; the tab closed");

        c = await open_console(config.id);
        await linux_shell(c.emulator, "Linux's shell again");
        await type(c.emulator, "mkdir -p /mnt && mount /dev/sda /mnt && cat /mnt/note && echo TIMED > /mnt/timed && sync");
        check(await screen(c.emulator, /^PERSISTENT/), "the file after the tab was closed and opened again");
        log("opened again: /note says PERSISTENT");
        // (the guest's sync done: the backend's timer flushes within 5 s; then the tab goes without powering off)
        await sleep(7000);
        c.frame.remove();
        c = await open_console(config.id);
        await linux_shell(c.emulator, "Linux's shell a third time");
        await type(c.emulator, "mkdir -p /mnt && mount /dev/sda /mnt && cat /mnt/timed");
        check(await screen(c.emulator, /^TIMED/), "the file of the timed flush");
        await c.power_off();
        log("a file synced, the tab closed after 7 s without powering off: there after opening again (the timed flush)");
    },
    async import()
    {
        const source = new Uint8Array(await (await fetch("/images/msdos622.img")).arrayBuffer());
        let progress = 0;
        const disk = await import_disk("/images/msdos622.img", "msdos622.img", { prefs: store, progress: done => { progress = done; } });
        check(disk.size === source.length && disk.sha256 === sha256(source) && progress === source.length, "the import: " + disk.sha256);
        log("imported images/msdos622.img: " + disk.size + " bytes, SHA-256 " + disk.sha256.slice(0, 16) + "… the source's");
        // (exported: as a download, no save picker here)
        let exported;
        const save_picker = window.showSaveFilePicker;
        window.showSaveFilePicker = undefined;
        await export_disk(disk.id, "copy.img", parts => { exported = parts[0]; });
        window.showSaveFilePicker = save_picker;
        check(exported && sha256(new Uint8Array(await exported.arrayBuffer())) === disk.sha256, "the export");
        log("exported: the same SHA-256");
        const config = await machine("DOS on an imported disk", dos_vm(disk.path));
        const c = await open_console(config.id);
        check(await screen(c.emulator, DOS_PROMPT, 120000), "MS-DOS's prompt");
        await type(c.emulator, "echo IMPORTED-WRITE > C:\\IW.TXT");
        await sleep(1500);
        await c.power_off();
        const bytes = new Uint8Array(await (await disk_file(disk.id)).arrayBuffer());
        check(contains(bytes, "IMPORTED-WRITE"), "the write in the browser disk");
        check(sha256(source) === disk.sha256, "the source unchanged");
        log("MS-DOS wrote C:\\IW.TXT on it; powered off: the text is in the browser disk, the source as it was");
    },
    async share()
    {
        const disk = await import_disk("/images/msdos622.img", "shared.img", { prefs: store });
        const own = await create_disk(4 << 20, "own disk", store);
        const first = await machine("First", Object.assign(dos_vm(disk.path)));
        first.disks.push({ slot: "hdb", image: { kind: "browser", path: own.path, size: 4 << 20 }, disk_option: "read_write", disk_error: "stop" });
        await store.put(first);
        const second = await machine("Second", dos_vm(disk.path));
        const a = await open_console(first.id);
        check(await screen(a.emulator, DOS_PROMPT, 120000), "the first's prompt");
        const b = await open_console(second.id, { expect_error: true });
        check(/used by another tab/.test(b.text), "the second refused: " + b.text);
        b.frame.remove();
        log("one disk, two machines: the second refused while the first runs (\"" + b.text.slice(0, 70) + "…\")");

        await a.menu("menu_power", "menu_suspend");
        await until(() => /Suspended/.test(a.$(".console-status").textContent), "the first suspended", 120000);
        a.frame.remove();
        const c = await open_console(second.id);
        check(await screen(c.emulator, DOS_PROMPT, 120000), "the second's prompt");
        await type(c.emulator, "echo SECOND-WROTE > C:\\SW.TXT");
        await sleep(1500);
        await c.power_off();
        c.frame.remove();
        const r = await open_console(first.id, { expect_error: true });
        check(/could not be resumed/.test(r.text) && /cannot go back/.test(r.text), "the resume refused: " + r.text);
        r.frame.remove();
        log("the first suspended, the second wrote to the disk: the first's resume refused (\"" + r.text.slice(r.text.indexOf("(a disk"), r.text.indexOf("(a disk") + 60) + "…\")");

        // the library: its Browser disks dialog; deleting the first deletes its own disk, not the shared one
        const library = document.createElement("iframe");
        library.src = "/index.html";
        document.body.append(library);
        await new Promise(resolve => library.onload = resolve);
        const ld = library.contentDocument;
        (await until(() => ld.querySelector("#browser_disks"), "the library")).click();
        const rows = await until(() => ld.querySelectorAll("dialog[open] table.browser-disks tr").length >= 2 &&
            Array.from(ld.querySelectorAll("dialog[open] table.browser-disks tr"), tr => tr.textContent), "the browser disks dialog");
        check(rows.some(r => /shared\.img/.test(r) && /First, Second/.test(r)) && rows.some(r => /own disk/.test(r) && /First/.test(r)), "the dialog: " + rows.join(" | "));
        Array.from(ld.querySelectorAll("dialog[open] button")).find(x => x.textContent === "Close").click();
        log("Browser disks: " + rows.map(r => r.replace(/Export.*$/, "")).join("; "));
        Array.from(ld.querySelectorAll(".vm-list li")).find(li => li.textContent.startsWith("First")).click();
        (await until(() => ld.querySelector("#delete_vm"), "the delete button")).click();
        Array.from((await until(() => ld.querySelector("dialog[open]"), "the delete dialog")).querySelectorAll("button")).find(x => x.textContent === "Delete").click();
        await until(async () => !(await store.get(first.id)), "the first deleted");
        const left = (await list_disks()).map(d => d.id);
        check(left.includes(disk.id) && !left.includes(own.id), "the disks after deleting the first: " + left);
        log("deleting the first: its own disk deleted, the shared one kept");
    },
    async page()
    {
        const disk = await create_disk(1 << 20, "page disk", store);
        const config = await machine("CPU in the page", Object.assign(dos_vm(disk.path)));
        config.disks[0].image.size = 1 << 20;
        config.advanced.cpu_worker = false;
        await store.put(config);
        const c = await open_console(config.id, { expect_error: true });
        check(/needs the CPU Worker/.test(c.text), "the CPU in the page: " + c.text);
        log("the CPU in the page: \"" + c.text.slice(0, 100) + "…\"");
        check(disk_id(disk.path) === disk.id, "disk_id");
    },
};

(async () =>
{
    store = await VMStore.open();
    await parts[part]();
})().then(() =>
{
    document.getElementById("result").textContent = "PASS (" + part + ")\n" + lines.join("\n");
}, e =>
{
    document.getElementById("result").textContent = "FAIL (" + part + "): " + (e.stack || e.message) + "\n" + lines.join("\n");
});
</script>
                                                                                                                                                                                                                                                                                                        source/v64/tests/app/browser_runner.mjs                                                             0000644 0000000 0000000 00000024261 00000000000 015402  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The VM manager's pages in headless Chrome (docs/vm-manager-plan.md): a
// static server for the repository (no caching), a page that reports its
// result in an element #result starting with PASS or FAIL (the server adds
// the script that sends it here), and Chrome with a profile of its own.
// With service=1, a disk service (tools/disk-service.mjs, --allow-create)
// on a directory of its own (with dos.img, a copy of images/msdos622.img),
// for this page's origin: its URL is the page's query argument
// service=<url>; GET /__service_files lists its files, GET
// /__service_file?name=&contains= says whether one has a text and a writer,
// POST /__service_down and /__service_up take the service away and back.
// With isolated=1, the pages cross-origin isolated (COOP/COEP, as the site's
// _headers): the cores in host threads (vCPU workers). With autoplay=1, audio
// plays without a user's gesture (pages that measure their output).
//   node tests/app/browser_runner.mjs <page> [query arguments...]
//   node tests/app/browser_runner.mjs tests/app/store_test.html
// Needs Chrome (CHROME); TIMEOUT_MS (default 300000); BROWSER_DEBUG_PORT (DevTools).

import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { create_disk_service } from "../../tools/disk-service.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const page = process.argv[2];
if(!page)
{
    console.error("usage: node tests/app/browser_runner.mjs <page> [query arguments...]");
    process.exit(2);
}
const args = process.argv.slice(3);
const with_service = args.includes("service=1");
const ISOLATION = args.includes("isolated=1") ? { "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp" } : {};
const AUTOPLAY = args.includes("autoplay=1");
// (webgpu=1: WebGPU on in headless Chrome, as tests/gles/chrome_renderer.mjs has it, and no throttling of a long run's timers)
const WEBGPU = args.includes("webgpu=1");
let query = args.filter(a => a !== "service=1" && a !== "isolated=1" && a !== "autoplay=1" && a !== "webgpu=1").join("&");
let service, service_dir, service_listeners = null;

const REPORTER = `<script>
    let logged = 0;
    const reporter = new MutationObserver(() => {
        // (the page's #log as it grows: an hour-long part says where it is)
        const log = document.getElementById("log")?.textContent || "";
        if(log.length < logged) logged = 0;
        const added = log.slice(logged).replace(/^\\n/, "");
        logged = log.length;
        if(added) fetch("/__log", { method: "POST", body: "log: " + added });
        const text = document.getElementById("result")?.textContent || "";
        if(!/^(PASS|FAIL)\\b/.test(text)) return;
        reporter.disconnect();
        fetch("/__test_result", { method: "POST", body: JSON.stringify({ status: text.startsWith("PASS") ? "PASS" : "FAIL", details: text }) });
    });
    reporter.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
    addEventListener("error", e => fetch("/__log", { method: "POST", body: "error: " + e.message + " " + e.filename + ":" + e.lineno }));
    addEventListener("unhandledrejection", e => fetch("/__log", { method: "POST", body: "unhandled rejection: " + (e.reason && e.reason.stack || e.reason) }));
</script>`;

const TYPES = { ".html": "text/html", ".js": "text/javascript", ".mjs": "text/javascript", ".wasm": "application/wasm",
    ".css": "text/css", ".json": "application/json", ".svg": "image/svg+xml", ".png": "image/png" };

const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-app-browser-"));
let browser, timeout;

const server = http.createServer((req, res) =>
{
    const address = new URL(req.url, "http://localhost");
    if(address.pathname === "/__service_file")
    {
        const name = path.basename(address.searchParams.get("name") || "");
        const text = address.searchParams.get("contains") || "";
        const image = service && service.images.get(name);
        res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });
        res.end(JSON.stringify({ contains: !!text && fs.readFileSync(path.join(service_dir, name)).includes(text),
            writer: !!(image && image.writer && image.writer.expires > Date.now()), session_open: !!(image && image.writer) }));
        return;
    }
    if(req.method === "POST" && (address.pathname === "/__service_down" || address.pathname === "/__service_up"))
    {
        if(address.pathname === "/__service_down")
        {
            service_listeners = service.server.listeners("request");
            service.server.removeAllListeners("request");
            service.server.on("request", request => request.socket.destroy());
        }
        else if(service_listeners)
        {
            service.server.removeAllListeners("request");
            for(const listener of service_listeners) service.server.on("request", listener);
            service_listeners = null;
        }
        res.end("OK");
        return;
    }
    if(address.pathname === "/__service_files")
    {
        const files = service_dir ? fs.readdirSync(service_dir).filter(name => !name.startsWith(".")).map(name => ({ name, size: fs.statSync(path.join(service_dir, name)).size })) : [];
        res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }).end(JSON.stringify(files));
        return;
    }
    if(req.method === "POST" && (address.pathname === "/__test_result" || address.pathname === "/__log"))
    {
        let body = "";
        req.on("data", d => { body += d; });
        req.on("end", () =>
        {
            res.end("OK");
            if(address.pathname === "/__log")
            {
                console.log("[page] " + body);
                return;
            }
            const result = JSON.parse(body);
            console.log(result.details);
            finish(result.status === "PASS" ? 0 : 1);
        });
        return;
    }
    const file = path.resolve(root, "." + decodeURIComponent(address.pathname));
    if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
    let size;
    try { size = fs.statSync(file).isFile() ? fs.statSync(file).size : -1; }
    catch(e) { size = -1; }
    if(size < 0) { res.writeHead(404).end(); return; }
    const type = TYPES[path.extname(file)] || "application/octet-stream";
    // (Range requests, as web servers answer them: v86 reads images given by URL in parts)
    const range = /^bytes=(\d+)-(\d*)$/.exec(req.headers["range"] || "");
    if(range && !file.endsWith(".html"))
    {
        const first = +range[1], last = Math.min(range[2] ? +range[2] : size - 1, size - 1);
        if(first >= size || last < first)
        {
            res.writeHead(416, { "Content-Range": "bytes */" + size }).end();
            return;
        }
        const part = Buffer.alloc(last - first + 1);
        const fd = fs.openSync(file, "r");
        try { fs.readSync(fd, part, 0, part.length, first); } finally { fs.closeSync(fd); }
        res.writeHead(206, { "Content-Type": type, "Content-Range": "bytes " + first + "-" + last + "/" + size, "Accept-Ranges": "bytes",
            "Content-Length": part.length, "Cache-Control": "no-store", ...ISOLATION });
        res.end(part);
        return;
    }
    if(!file.endsWith(".html"))
    {
        // (streamed: a package of a GB)
        res.writeHead(200, { "Content-Type": type, "Accept-Ranges": "bytes", "Content-Length": size, "Cache-Control": "no-store", ...ISOLATION });
        fs.createReadStream(file).pipe(res);
        return;
    }
    const body = Buffer.concat([fs.readFileSync(file), Buffer.from(REPORTER)]);
    res.writeHead(200, { "Content-Type": type, "Accept-Ranges": "bytes", "Cache-Control": "no-store", ...ISOLATION });
    res.end(body);
});

function finish(code)
{
    clearTimeout(timeout);
    server.close();
    if(service) service.close();
    process.exitCode = code;
    const remove = () => { try { fs.rmSync(profile, { recursive: true, force: true }); } catch(e) {} };
    if(browser && browser.exitCode === null && browser.signalCode === null)
    {
        browser.on("exit", remove);
        browser.kill();
    }
    else remove();
}

// (the runner stopped from outside: its Chrome stopped too, not left running the page's machine)
for(const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(signal, () => { finish(1); process.exit(1); });

server.listen(0, "127.0.0.1", async () =>
{
    const origin = "http://127.0.0.1:" + server.address().port;
    if(with_service)
    {
        service_dir = fs.mkdtempSync(path.join(profile, "service-"));
        fs.copyFileSync(path.join(root, "images/msdos622.img"), path.join(service_dir, "dos.img"));
        service = create_disk_service({ dir: service_dir, origins: [origin], allow_create: true, lease_ms: 5000 });
        await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
        query = [query, "service=" + encodeURIComponent("http://127.0.0.1:" + service.server.address().port + "/")].filter(Boolean).join("&");
    }
    const url = origin + "/" + page + (query ? "?" + query : "");
    console.log(url);
    browser = spawn(process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
        ...(AUTOPLAY ? ["--autoplay-policy=no-user-gesture-required"] : []),
        ...(WEBGPU ? ["--enable-unsafe-webgpu", "--disable-background-timer-throttling", "--disable-renderer-backgrounding"] : []),
        // (BROWSER_DEBUG_PORT: DevTools on that port, to look at a long part while it runs)
        ...(process.env.BROWSER_DEBUG_PORT ? ["--remote-debugging-port=" + process.env.BROWSER_DEBUG_PORT] : []),
        "--user-data-dir=" + profile, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", d => { stderr = (stderr + d).slice(-4000); });
    browser.on("error", error => { console.error(error); finish(1); });
    timeout = setTimeout(() =>
    {
        console.error("FAIL: timed out\n" + stderr);
        finish(1);
    }, +process.env.TIMEOUT_MS || 300000);
});
                                                                                                                                                                                                                                                                                                                                               source/v64/tests/app/console_test.html                                                              0000644 0000000 0000000 00000044264 00000000000 015207  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: the console</title>
<!-- The VM manager's console (docs/vm-manager-plan.md U4, "功能对照"), MS-DOS 6.22 in a frame, every runtime function of the old page:
     part=main  power (pause, run), keys (Alt+Tab's press and release, other keys, Ctrl+Alt+Del reboots), devices (a CD of files that
                DOS reads, ejected; a floppy that DOS reads, ejected; the hda image downloaded), view (scale, zoom to fit, theatre mode,
                screenshot, full screen), input (mouse off, lock), sound (mute), tools (a memory dump, a network capture), drawers
                (the serial terminal, the shared folder's files sent and got, the details), the application icon,
                the status bar, a state saved to a file and loaded, power off
     part=disk  (with the runner's service=1) a hard disk written back to the disk service: the warning before leaving, a write in
                the service's file, the service gone: the disk error dialog, Retry once it is back, Save and power off (the session closed)
     node tests/app/browser_runner.mjs tests/app/console_test.html part=main [worker=0] -->
<style>iframe { width: 1200px; height: 800px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { VMStore } from "../../src/app/vm_store.js";
import { new_config } from "../../src/app/vm_config.js";

const args = new URLSearchParams(location.search);
const part = args.get("part") || "main";
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout = 30000)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(100);
    }
}
function check(condition, what) { if(!condition) throw new Error(what); }
// MS-DOS's prompt once AUTOEXEC.BAT is done (its last program's line, then the
// prompt at the bottom): the batch file's commands show "C:\>" before, and keys
// typed while its programs load overflow the BIOS's buffer of 15
const DOS_PROMPT = [/MSCD001 unit 0$/, "", /^C:\\>$/];

let frame, w, d, emulator;
const $ = selector => d.querySelector(selector);
/** what the frame downloaded: [name, Blob] */
const downloads = [];
/** a click on a menu's item */
async function menu(menu_id, item_id)
{
    $("#" + menu_id).click();
    const item = await until(() => $("#" + item_id), "the menu item " + item_id);
    check(!item.disabled, item_id + " enabled");
    item.click();
}
/** the frame's next file picker answers with these files */
function answer_picker(files)
{
    w.HTMLInputElement.prototype.click = function()
    {
        const transfer = new w.DataTransfer();
        for(const file of files) transfer.items.add(file);
        this.files = transfer.files;
        this.dispatchEvent(new w.Event("change"));
    };
}
/** a command typed at DOS's prompt, then the prompt again */
async function dos(command, expect, timeout = 30000)
{
    // (20 ms a key: DOS's 16-key buffer drops what comes faster)
    await emulator.keyboard_send_text(command + "\n", 20);
    if(expect && !await emulator.wait_until_vga_screen_contains(expect, { timeout_msec: timeout }))
    {
        // (the screen's last lines, for the report: the page's screen adapter)
        const screen = emulator.screen_adapter?.get_text_screen?.() || [];
        throw new Error("DOS shows " + expect + " after " + command + "; the screen ends: " + JSON.stringify(screen.map(l => l.trimEnd()).filter(Boolean).slice(-5)));
    }
}
/** wrap an emulator method to record its calls */
function spy(name)
{
    const calls = [];
    const original = emulator[name].bind(emulator);
    emulator[name] = (...a) => { calls.push(a); return original(...a); };
    return calls;
}

async function start(config)
{
    const store = await VMStore.open();
    const stored = await store.put(config);
    store.close();
    frame = document.createElement("iframe");
    frame.src = "/index.html?vm=" + stored.id;
    document.body.append(frame);
    await new Promise(resolve => frame.onload = resolve);
    w = frame.contentWindow;
    d = frame.contentDocument;
    // (downloads: the anchor's click with its object URL or data URL)
    const create_url = w.URL.createObjectURL.bind(w.URL);
    const blobs = new Map();
    w.URL.createObjectURL = blob => { const url = create_url(blob); blobs.set(url, blob); return url; };
    w.HTMLAnchorElement.prototype.click = function()
    {
        if(!this.download) return;
        downloads.push([this.download, blobs.get(this.href) || this.href]);
    };
    emulator = await until(() => w.v86_console?.emulator, "the console's emulator", 60000);
    check(await emulator.wait_until_vga_screen_contains(DOS_PROMPT, { timeout_msec: 120000 }), "MS-DOS's prompt");
}
async function next_download(what)
{
    const count = downloads.length;
    return { wait: () => until(() => downloads.length > count && downloads[downloads.length - 1], what) };
}

const parts = {
    async main()
    {
        const config = new_config({ name: "DOS console" });
        config.disks = [{ slot: "hda", image: { kind: "url", url: "images/msdos622.img", async: true }, disk_option: "read_only", disk_error: "stop" }];
        config.filesystem = {};
        config.network[0].backend = "inbrowser";
        config.network[0].relay_url = "";
        // (USB, which DOS leaves alone: EHCI, the tablet on a companion)
        config.usb = { controller: "ehci", tablet: true, disks: [] };
        if(args.get("worker") === "0") config.advanced.cpu_worker = false;
        await start(config);
        log("MS-DOS 6.22 at its prompt in the console");

        // the status bar
        const status = await until(() => /MIPS/.test($(".console-status").textContent) && $(".console-status").textContent, "the status bar's speed", 10000);
        check(/Running/.test(status) && /\d+s/.test(status) && /Text 80×25/.test(status), "the status bar: " + status);
        log("status bar: " + status.replace(/\s+/g, " "));

        // power: pause, run
        await menu("menu_power", "menu_run");
        await until(() => !emulator.is_running() && /Paused/.test($(".console-status").textContent), "paused");
        await menu("menu_power", "menu_run");
        await until(() => emulator.is_running() && /Running/.test($(".console-status").textContent), "running again");
        log("Power: Pause and Run");

        // keys
        const scancodes = spy("keyboard_send_scancodes");
        await menu("menu_keys", "keys_Alt_Tab");
        await until(() => scancodes.length === 2, "Alt+Tab's press and release");
        check(JSON.stringify(scancodes) === JSON.stringify([[[56, 15]], [[143, 184]]]), "Alt+Tab: " + JSON.stringify(scancodes));
        await menu("menu_keys", "keys_other");
        const input = await until(() => $("dialog[open] input"), "the keys dialog");
        input.value = "Ctrl+Alt+F1";
        Array.from(d.querySelectorAll("dialog[open] button")).find(b => b.textContent === "OK").click();
        await until(() => scancodes.length === 4, "Ctrl+Alt+F1");
        check(JSON.stringify(scancodes[2]) === JSON.stringify([[29, 56, 59]]), "Ctrl+Alt+F1: " + JSON.stringify(scancodes[2]));
        await dos("cls");
        await sleep(500);
        await menu("menu_keys", "keys_Ctrl_Alt_Del");
        check(await emulator.wait_until_vga_screen_contains("Starting MS-DOS", { timeout_msec: 60000 }), "Ctrl+Alt+Del rebooted DOS");
        check(await emulator.wait_until_vga_screen_contains(DOS_PROMPT, { timeout_msec: 60000 }), "the prompt after the reboot");
        log("Keys: Alt+Tab pressed and released, Ctrl+Alt+F1, Ctrl+Alt+Del reboots DOS");

        // devices: a CD of files, a floppy, the hda image
        answer_picker([new w.File(["Hello from the console's CD\r\n"], "readme.txt")]);
        await menu("menu_devices", "devices_insert_cdrom");
        await until(async () => (await emulator.get_cdrom_state()).inserted, "the CD inserted");
        await dos("cls");
        await dos("dir D:", "README");
        await menu("menu_devices", "devices_eject_cdrom");
        await until(async () => !(await emulator.get_cdrom_state()).inserted, "the CD ejected");
        const floppy = await (await fetch("/images/freedos722.img")).blob();
        answer_picker([new w.File([floppy], "freedos722.img")]);
        await menu("menu_devices", "devices_insert_fda");
        await until(async () => !!(await emulator.get_disk_fda()), "the floppy inserted");
        await dos("cls");
        await dos("dir A:", "COMMAND");
        await menu("menu_devices", "devices_eject_fda");
        await until(async () => !(await emulator.get_disk_fda()), "the floppy ejected");
        const hda = await next_download("the hda image");
        await menu("menu_devices", "devices_get_hda");
        const [hda_name, hda_blob] = await hda.wait();
        const original = await (await fetch("/images/msdos622.img")).blob();
        check(hda_name === "DOS_console-hda.img" && hda_blob.size === original.size, "the hda image: " + hda_name + " " + hda_blob.size);
        log("Devices: a CD of files (DOS lists README.TXT), ejected; a floppy (DOS lists COMMAND.COM), ejected; " + hda_name + " (" + hda_blob.size + " bytes)");

        // view
        const scale = spy("screen_set_scale");
        await menu("menu_view", "view_scale_200");
        check(JSON.stringify(scale.at(-1)) === "[2,2]", "scale 200%: " + JSON.stringify(scale));
        await menu("menu_view", "view_zoom_to_fit");
        check(scale.length >= 3 && scale.at(-1)[0] > 0, "zoom to fit");
        await menu("menu_view", "view_zoom_to_fit");
        await menu("menu_view", "view_theatre");
        check($(".console").classList.contains("theatre") && !$(".theatre-show-ui").hidden, "theatre mode");
        $(".theatre-show-ui").click();
        check(!$(".console").classList.contains("theatre"), "theatre mode left");
        const shot = await next_download("the screenshot");
        await menu("menu_view", "view_screenshot");
        const [shot_name, shot_url] = await shot.wait();
        check(shot_name === "DOS_console-screenshot.png" && String(shot_url).startsWith("data:image/png"), "the screenshot: " + shot_name);
        const fullscreen = spy("screen_go_fullscreen");
        await menu("menu_view", "view_fullscreen");
        check(fullscreen.length === 1, "full screen asked");
        log("View: scale 200%, zoom to fit, theatre mode and back, a screenshot (" + shot_name + "), full screen");

        // input, sound
        const mouse = spy("mouse_set_enabled");
        await menu("menu_input", "input_mouse");
        check(JSON.stringify(mouse) === "[[false]]" && /Mouse off/.test($(".console-status").textContent), "the mouse off");
        await menu("menu_input", "input_mouse");
        const lock = spy("lock_mouse");
        await menu("menu_input", "input_lock_mouse");
        check(lock.length === 1, "lock the mouse");
        const volume = spy("set_speaker_volume");
        $("#mute").click();
        check(JSON.stringify(volume) === "[[0]]" && $("#mute").textContent === "Unmute", "muted");
        $("#mute").click();
        check(JSON.stringify(volume.at(-1)) === "[1]", "unmuted");
        log("Input: the mouse off and on, locked; Sound: muted and unmuted");

        // tools
        const dump = await next_download("the memory dump");
        await menu("menu_tools", "tools_memory_dump");
        const [dump_name, dump_blob] = await dump.wait();
        check(dump_blob.size === config.memory.mb << 20, "the memory dump: " + dump_blob.size);
        await menu("menu_tools", "tools_capture");
        await until(() => /Capturing network traffic: 0 packets/.test($(".console-status").textContent), "capturing");
        const traffic = await next_download("the capture");
        await menu("menu_tools", "tools_capture");
        const [traffic_name] = await traffic.wait();
        await menu("menu_tools", "tools_stop_capture");
        log("Tools: " + dump_name + " (" + dump_blob.size + " bytes), " + traffic_name);

        // drawers
        $("#drawer_terminal").click();
        await until(() => $(".console-drawer .terminal .xterm"), "the serial terminal (xterm)", 20000);
        const icon = new w.Image();
        await new Promise((resolve, reject) =>
        {
            icon.onload = resolve;
            icon.onerror = () => reject(new Error("the application icon failed to load"));
            icon.src = d.querySelector('link[rel="apple-touch-icon"]').href;
        });
        check(icon.naturalWidth === 192 && icon.naturalHeight === 192, "the application icon: " + icon.naturalWidth + "x" + icon.naturalHeight);
        $("#drawer_files").click();
        answer_picker([new w.File(["hello 9p"], "hello.txt")]);
        const send = await until(() => $(".console-drawer input[type=file]"), "the shared folder's send");
        send.click();
        await until(() => /Sent to the shared folder/.test($(".console-status").textContent), "sent");
        const got = await next_download("the file got");
        const path = $(".console-drawer input[aria-label='File to get']");
        path.value = "/hello.txt";
        Array.from(d.querySelectorAll(".console-drawer button")).find(b => b.textContent === "Get").click();
        const [got_name, got_blob] = await got.wait();
        check(got_name === "hello.txt" && await got_blob.text() === "hello 9p", "the file got: " + got_name);
        $("#drawer_details").click();
        const details = await until(() => /Instructions/.test($(".console-drawer").textContent) && $(".console-drawer").textContent, "the details");
        check(/Storage \(IDE\)/.test(details) && /Text, 80×25/.test(details), "the details: " + details);
        await until(() => /Execution: 1 core/.test($(".console-drawer").textContent), "the execution note");
        await until(() => /USB devices: tablet \(port 1, UHCI companion, 12 Mbit\/s\)/.test($(".console-drawer").textContent), "the USB devices");
        $("#drawer_details").click();
        check($(".console-drawer").hidden, "the drawer closed");
        log("Drawers: the serial terminal, the shared folder (hello.txt sent and got), the details");

        // a state saved to a file and loaded
        const saved = await next_download("the state");
        await menu("menu_power", "menu_save_state");
        const [state_name, state_blob] = await saved.wait();
        check(state_name === "DOS_console-state.bin" && state_blob.size > 1 << 20, "the state: " + state_blob.size);
        await dos("cls");
        await dos("echo AFTER-THE-SAVE", "AFTER-THE-SAVE");
        answer_picker([new w.File([state_blob], state_name)]);
        await menu("menu_power", "menu_load_state");
        await until(async () => !/AFTER-THE-SAVE/.test(await screen_text()), "the state loaded (the text after the save gone)", 30000);
        check(emulator.is_running(), "running after the load");
        log("State: saved (" + state_blob.size + " bytes) and loaded back");

        // power off
        await menu("menu_power", "menu_power_off");
        Array.from((await until(() => $("dialog[open]"), "the power off dialog")).querySelectorAll("button")).find(b => b.textContent === "Power off").click();
        await until(() => /Powered off/.test($(".console-status").textContent), "powered off");
        log("Power off: confirmed");
    },
    async disk()
    {
        const service = args.get("service");
        check(service, "the runner's disk service (service=1)");
        const config = new_config({ name: "DOS written back" });
        config.disks = [{ slot: "hda", image: { kind: "url", url: service + "dos.img", async: true }, disk_option: "read_write", disk_error: "stop" }];
        await start(config);
        log("MS-DOS on the disk service's dos.img (read write)");
        const leave = new w.Event("beforeunload", { cancelable: true });
        w.dispatchEvent(leave);
        check(leave.defaultPrevented, "leaving the page asks first");
        log("leaving the page: the browser asks first");

        const service_file = async text => (await fetch("/__service_file?name=dos.img&contains=" + encodeURIComponent(text))).json();
        await dos("echo FIRST-WRITE > C:\\FIRST.TXT");
        await until(async () => (await service_file("FIRST-WRITE")).contains, "the write in the service's file", 30000);
        log("a write is in the service's file");

        await fetch("/__service_down", { method: "POST" });
        emulator.keyboard_send_text("echo SECOND-WRITE > C:\\SECOND.TXT\n", 20);
        const text = await until(() => $("#disk_error_text") && $("#disk_error_text").textContent, "the disk error dialog", 120000);
        check(/Disk hda: the write .* failed/.test(text) && /retry once the disk can be reached again/.test(text), "the dialog: " + text);
        check(!emulator.is_running(), "the machine stopped");
        log("the service gone: \"" + text.slice(0, 90) + "…\"");
        await fetch("/__service_up", { method: "POST" });
        Array.from(d.querySelectorAll("dialog[open] button")).find(b => b.textContent === "Retry").click();
        await until(async () => (await service_file("SECOND-WRITE")).contains, "the second write after Retry", 30000);
        log("Retry: the write landed");

        const saved = await next_download("the state");
        await menu("menu_power", "menu_save_and_power_off");
        const [state_name, state_blob] = await saved.wait();
        await until(() => /Powered off/.test($(".console-status").textContent), "powered off");
        await until(async () => !(await service_file("x")).session_open, "the session closed");
        log("Save and power off: " + state_name + " (" + state_blob.size + " bytes), the disk's session closed");
    },
};

async function screen_text()
{
    // (the guest's text screen through a screenshot would need OCR: the emulator's own check, with no wait)
    return await emulator.wait_until_vga_screen_contains("AFTER-THE-SAVE", { timeout_msec: 1 }) ? "AFTER-THE-SAVE" : "";
}

parts[part]().then(() =>
{
    document.getElementById("result").textContent = "PASS (" + part + ")\n" + lines.join("\n");
}, e =>
{
    document.getElementById("result").textContent = "FAIL (" + part + "): " + (e.stack || e.message) + "\n" + lines.join("\n");
});
</script>
                                                                                                                                                                                                                                                                                                                                            source/v64/tests/app/disk_service_create.mjs                                                        0000755 0000000 0000000 00000031105 00000000000 016321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The disk service's list and create (docs/vm-manager-plan.md "磁盘服务的创建
// 与列出", U3; tools/disk-service.mjs) and the VM manager's client
// (src/app/disk_service_client.js): every rule of create (--allow-create,
// the name, an existing file, the size, the free space, the token, the
// origin), list, the probe; then a Linux guest (images/linux4.iso) formats a
// new image as its hda with disk_option "read_write", writes a file and
// syncs, and the service's file has it.
//   node tests/app/disk_service_create.mjs [guest=0]

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import http from "node:http";
import url from "node:url";
import { create_disk_service, DEFAULT_MAX_SIZE } from "../../tools/disk-service.mjs";
import { list_images, create_image, probe, image_url, new_image_name, ServiceError } from "../../src/app/disk_service_client.js";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = path.resolve(__dirname, "../..") + "/";
const GUEST = !process.argv.includes("guest=0");
process.on("unhandledRejection", exn => { throw exn; });

let passed = 0;
async function test(name, fn)
{
    await fn();
    passed++;
    console.log("ok - " + name);
}

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-service-create-"));
const PAGE = "http://page.invalid:8000";

/** A service on a directory of its own; free: the volume's free bytes it sees */
async function start(options = {})
{
    const dir = fs.mkdtempSync(path.join(temp, "dir-"));
    const service = create_disk_service(Object.assign({ dir, origins: [PAGE], lease_ms: 2000 }, options));
    await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
    const base = "http://127.0.0.1:" + service.server.address().port + "/";
    return { service, dir, base };
}

/** A POST of the protocol, its status and JSON */
async function post(base, name, headers)
{
    const response = await fetch(base + name, { method: "POST", headers });
    return { status: response.status, body: await response.json().catch(() => null), headers: response.headers };
}

await test("without --allow-create: list answers (create: false), create is refused", async () =>
{
    const { service, base } = await start();
    const list = await post(base, "", { "X-V86-Disk-Op": "list" });
    assert.equal(list.status, 200);
    assert.deepEqual(list.body, { images: [], create: false, max_size: DEFAULT_MAX_SIZE });
    assert.equal(list.headers.get("X-V86-Disk-Protocol"), "1");
    const created = await post(base, "a.img", { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": "1048576" });
    assert.equal(created.status, 403);
    assert.equal(created.body.code, "create");
    await service.close();
});

await test("create: the names it refuses", async () =>
{
    const { service, base } = await start({ allow_create: true });
    for(const name of ["x.iso", ".hidden.img", "-dash.img", "_under.img", "space name.img", "%2E%2E%2Fup.img", "sub%2Fx.img",
        "a".repeat(125) + ".img", "x.img.tmp", "UPPER.IMG"])
    {
        const r = await post(base, name, { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": "512" });
        assert.equal(r.status, 400, name);
        assert.equal(r.body.code, "name", name);
    }
    const longest = "b".repeat(124) + ".img";
    assert.equal((await post(base, longest, { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": "512" })).status, 201, "128 characters");
    await service.close();
});

await test("create: the sizes it refuses (not whole sectors, none, above --max-size, above the free space)", async () =>
{
    const { service, dir, base } = await start({ allow_create: true, max_size: 1 << 20, free_space: () => 64 << 10 });
    for(const size of [undefined, "0", "-512", "511", "513", "abc", "1.5", String((1 << 20) + 512)])
    {
        const headers = { "X-V86-Disk-Op": "create" };
        if(size !== undefined) headers["X-V86-Disk-Size"] = size;
        const r = await post(base, "s.img", headers);
        assert.equal(r.status, 400, "size " + size);
        assert.equal(r.body.code, "size", "size " + size);
    }
    const full = await post(base, "s.img", { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": String(128 << 10) });
    assert.equal(full.status, 507);
    assert.equal(full.body.code, "no_space");
    assert(!fs.existsSync(path.join(dir, "s.img")), "nothing made");
    await service.close();
});

await test("create: a new image of zeros, its identity, never over an existing file", async () =>
{
    const { service, dir, base } = await start({ allow_create: true });
    fs.writeFileSync(path.join(dir, "existing.img"), "data");
    const r = await post(base, "new.img", { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": String(64 << 20) });
    assert.equal(r.status, 201);
    assert.deepEqual(r.body, { name: "new.img", size: 64 << 20, url: base + "new.img" });
    const file = path.join(dir, "new.img");
    const stat = fs.statSync(file);
    assert.equal(stat.size, 64 << 20);
    const fd = fs.openSync(file, "r");
    const sample = Buffer.alloc(4096);
    for(const at of [0, 32 << 20, (64 << 20) - 4096])
    {
        fs.readSync(fd, sample, 0, 4096, at);
        assert(sample.every(b => b === 0), "zeros at " + at);
    }
    fs.closeSync(fd);
    const state = JSON.parse(fs.readFileSync(path.join(dir, ".v86-disk-service.json"), "utf8"));
    assert.match(state["new.img"].uuid, /^[0-9a-f-]{36}$/);
    assert.equal(state["new.img"].generation, 1);
    console.log("    (64 MiB new.img takes " + stat.blocks * 512 + " bytes on this volume)");
    for(const name of ["new.img", "existing.img"])
    {
        const again = await post(base, name, { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": "512" });
        assert.equal(again.status, 409, name);
        assert.equal(again.body.code, "exists", name);
    }
    assert.equal(fs.readFileSync(path.join(dir, "existing.img"), "utf8"), "data");
    // (a Range read of the new image, as v86 reads it)
    const read = await fetch(base + "new.img", { headers: { Range: "bytes=512-1023" } });
    assert.equal(read.status, 206);
    assert.equal((await read.arrayBuffer()).byteLength, 512);
    await service.close();
});

await test("list: name, size, time of change, writer; at the root only", async () =>
{
    const { service, dir, base } = await start({ allow_create: true });
    fs.writeFileSync(path.join(dir, "b.img"), Buffer.alloc(1024));
    fs.writeFileSync(path.join(dir, ".hidden"), "x");
    fs.mkdirSync(path.join(dir, "subdir"));
    await post(base, "a.img", { "X-V86-Disk-Op": "create", "X-V86-Disk-Size": "2048" });
    let list = (await post(base, "", { "X-V86-Disk-Op": "list" })).body;
    assert.equal(list.create, true);
    assert.deepEqual(list.images.map(i => [i.name, i.size, i.writer]), [["a.img", 2048, false], ["b.img", 1024, false]]);
    assert(!isNaN(Date.parse(list.images[0].modified)));
    const open = await post(base, "a.img", { "X-V86-Disk-Op": "open" });
    assert.equal(open.status, 200);
    list = (await post(base, "", { "X-V86-Disk-Op": "list" })).body;
    assert.equal(list.images.find(i => i.name === "a.img").writer, true, "a writer's session");
    const wrong = await post(base, "a.img", { "X-V86-Disk-Op": "list" });
    assert.equal(wrong.status, 400);
    await service.close();
});

await test("the token and the origin", async () =>
{
    const { service, base } = await start({ allow_create: true, token: "secret" });
    for(const op of ["list", "create"])
    {
        const headers = { "X-V86-Disk-Op": op, "X-V86-Disk-Size": "512" };
        const r = await post(base, op === "list" ? "" : "t.img", headers);
        assert.equal(r.status, 401, op);
        assert.equal(r.body.code, "token");
        const ok = await post(base, op === "list" ? "" : "t.img", Object.assign({ Authorization: "Bearer secret" }, headers));
        assert.equal(ok.status, op === "list" ? 200 : 201, op);
    }
    const foreign = await post(base, "", { "X-V86-Disk-Op": "list", Authorization: "Bearer secret", Origin: "http://other.invalid" });
    assert.equal(foreign.status, 403);
    assert.equal(foreign.body.code, "origin");
    const page = await post(base, "", { "X-V86-Disk-Op": "list", Authorization: "Bearer secret", Origin: PAGE });
    assert.equal(page.status, 200);
    assert.equal(page.headers.get("Access-Control-Allow-Origin"), PAGE);
    const preflight = await fetch(base + "u.img", { method: "OPTIONS", headers: { Origin: PAGE, "Access-Control-Request-Method": "POST",
        "Access-Control-Request-Headers": "x-v86-disk-op, x-v86-disk-size, authorization" } });
    assert.equal(preflight.status, 204);
    assert.match(preflight.headers.get("Access-Control-Allow-Headers"), /X-V86-Disk-Size/);
    assert.match(preflight.headers.get("Access-Control-Expose-Headers"), /X-V86-Disk-Protocol/);
    await service.close();
});

await test("the client: list, create, its errors, the probe of a service, a static server, nothing", async () =>
{
    const { service, base } = await start({ allow_create: true, token: "t" });
    const s = { url: base.slice(0, -1), token: "t" };
    assert.deepEqual((await list_images(s)).images, []);
    const made = await create_image(s, "client.img", 4096);
    assert.deepEqual(made, { name: "client.img", size: 4096, url: base + "client.img" });
    assert.equal(image_url(s, "client.img"), base + "client.img");
    await assert.rejects(create_image(s, "client.img", 4096), e => e instanceof ServiceError && e.code === "exists" && e.status === 409);
    await assert.rejects(list_images({ url: base }), e => e.code === "token");
    const probed = await probe(s);
    assert(probed.ok && probed.list.create && probed.list.images.length === 1);
    assert.equal(new_image_name("Windows 98 (SE)", probed.list.images), "windows-98-se.img");
    assert.equal(new_image_name("client", probed.list.images), "client-2.img");
    // (a static server: no protocol; nothing listening)
    const plain = http.createServer((req, res) => res.writeHead(404).end());
    await new Promise(resolve => plain.listen(0, "127.0.0.1", resolve));
    const static_probe = await probe({ url: "http://127.0.0.1:" + plain.address().port + "/" });
    assert(!static_probe.ok && static_probe.code === "not_a_service", JSON.stringify(static_probe));
    const port = plain.address().port;
    await new Promise(resolve => plain.close(resolve));
    const nothing = await probe({ url: "http://127.0.0.1:" + port + "/" });
    assert(!nothing.ok && nothing.code === "unreachable", JSON.stringify(nothing));
    await service.close();
});

if(GUEST)
{
    await test("a Linux guest formats a new image (read_write), writes a file and syncs: the service's file has it", async () =>
    {
        const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
        const { service, dir, base } = await start({ allow_create: true, lease_ms: 30000 });
        await create_image({ url: base }, "guest.img", 32 << 20);
        const emulator = new V86({
            graphics_adapter: "bochs_vga", bios: { url: ROOT + "bios/seabios.bin" }, vga_bios: { url: ROOT + "bios/vgabios.bin" }, memory_size: 128 << 20,
            autostart: true, screen_dummy: true, log_level: 0,
            cdrom: { url: ROOT + "images/linux4.iso" }, hda: { url: base + "guest.img", disk_option: "read_write" },
        });
        let serial = "";
        emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
        const until = async (what, predicate, timeout) =>
        {
            const end = Date.now() + timeout;
            while(!predicate()) { if(Date.now() > end) throw new Error("timed out: " + what + "\n" + serial.slice(-500)); await new Promise(r => setTimeout(r, 50)); }
        };
        const PROMPT = /~% $/;
        await until("the shell", () => PROMPT.test(serial), 240000);
        const run = async command =>
        {
            serial = "";
            emulator.serial0_send(command + "\n");
            await until(command, () => PROMPT.test(serial), 120000);
            return serial;
        };
        const out = await run("mke2fs -q /dev/sda && mkdir -p /mnt && mount /dev/sda /mnt && echo NEW-IMAGE-FROM-THE-MANAGER > /mnt/note && sync && umount /mnt && echo synced");
        assert.match(out, /synced/, out);
        await emulator.destroy();
        const image = fs.readFileSync(path.join(dir, "guest.img"));
        assert(image.includes("NEW-IMAGE-FROM-THE-MANAGER"), "the text in the service's file");
        assert.equal(image.readUInt16LE(1024 + 56), 0xEF53, "an ext2 superblock");
        await service.close();
    });
}

fs.rmSync(temp, { recursive: true, force: true });
console.log(passed + " tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/app/legacy_cases.mjs                                                               0000755 0000000 0000000 00000013665 00000000000 014761  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The old page's starts that tests/app/legacy_options.mjs records
// (docs/vm-manager-plan.md U0): query arguments and form inputs.

/** Query arguments: custom images and every argument start_emulation reads */
export const QUERY_CASES = [
    "profile=custom&hda.url=images/msdos622.img",
    "profile=custom&cdrom.url=images/linux4.iso&cdrom.size=7731200&m=512",
    "profile=custom&fda.url=images/freedos722.img&fda.size=737280",
    "profile=custom&hda.url=a.img&hda.size=1048576&hdb.url=b.img&hdb.size=2097152&chunk_size=1000",
    "profile=custom&hda.url=a.img&chunk_size=9999999",
    "profile=custom&hda.url=http://127.0.0.1:8471/a.img&hda.disk_option=read_write&hda.disk_error=report&hdb.url=b.img&hdb.disk_option=read_only",
    "profile=custom&hda.empty=1048576&hdb.empty=0&cdrom.url=c.iso",
    "profile=custom&cdrom.url=c.iso&m=4096",
    "profile=custom&cdrom.url=c.iso&m=3001&cpu_type=x86_64&cores=4&parallel=0",
    "profile=custom&cdrom.url=c.iso&m=99999999",
    "profile=custom&cdrom.url=c.iso&m=8",
    "profile=custom&cdrom.url=c.iso&cpu_type=arm64&m=2048&graphics_adapter=virtio_gpu&displays=2&cmdline=console%3DttyAMA0",
    "profile=custom&cdrom.url=c.iso&cpu_type=arm64&m=512",
    "profile=custom&cdrom.url=c.iso&cpu_type=arm64&machine_type=i440fx&graphics_adapter=bochs_vga",
    "profile=custom&cdrom.url=c.iso&cpu_type=arm64&disable_jit=1&hda.url=d.img",
    "profile=custom&cdrom.url=c.iso&cpu_type=x86&machine_type=virt",
    "profile=custom&hda.url=h.img&machine_type=q35&hpet=0&smbus=0&root_ports=3",
    "profile=custom&hda.url=h.img&machine_type=q35&root_ports=99",
    "profile=custom&hda.url=h.img&machine_type=q35&cores=2&acpi=0",
    "profile=custom&cdrom.url=c.iso&vram=300&graphics_adapter=vmware_svga",
    "profile=custom&cdrom.url=c.iso&vram=5&displays=9",
    "profile=custom&cdrom.url=c.iso&acpi=1&bios=bochs&boot_order=213",
    "profile=custom&cdrom.url=c.iso&net_device_type=virtio&mtu=9000&relay_url=fetch:https://proxy.invalid/&mute=1&disable_jit=1&modem=2",
    "profile=custom&cdrom.url=c.iso&relay_url=wisps://wisp.invalid/&modem=7&mtu=abc",
    "profile=custom&cdrom.url=c.iso&kernel.url=k.bin&initrd.url=i.bin&cmdline=console%3DttyS0",
    "profile=custom&cdrom.url=c.iso&cpu_worker=0&ir_tier0=0&x87_fast_math=0&x87_jit_cache=0",
    "profile=custom&cdrom.url=c.iso&cores=2&acpi=0&parallel=1",
    "profile=custom&cdrom.url=c.iso&cpu_type=bogus&machine_type=bogus",
    "profile=custom&hda.url=h.img&fda.url=f.img&fda.disk_option=read_write&fda.disk_error=report&hdb.disk_option=read_write",
    "profile=custom&cdrom.url=c.iso&c=dir&s=ls&theatre=1&graphics_proxy=0",
    "profile=custom&cdrom.url=c.iso&graphics_adapter=none&net_device_type=none&modem=0",
    "profile=custom&cdrom.url=c.iso&acpi=1&mute=1&relay_url=inbrowser&disable_jit=1",
];

/** Starts from the form: [name, [["value" | "check" | "click", element id, value]...]] */
export const FORM_CASES = [
    ["defaults", []],
    ["memory 4096", [["value", "memory_size", "4096"], ["value", "vga_memory_size", "32"], ["value", "graphics_adapter", "vmware_svga"]]],
    ["memory 3001", [["value", "memory_size", "3001"]]],
    ["4 cores, not parallel", [["value", "cpu_cores", "4"], ["check", "parallel", false], ["check", "acpi", false]]],
    ["arm64", [["value", "cpu_type", "arm64"], ["value", "memory_size", "2048"]]],
    ["arm64 virtio_gpu", [["value", "cpu_type", "arm64"], ["value", "graphics_adapter", "virtio_gpu"], ["value", "machine_type", "q35"]]],
    ["x86 on virt", [["value", "machine_type", "virt"]]],
    ["q35 and the rest", [["value", "machine_type", "q35"], ["value", "boot_order", "213"], ["value", "net_device_type", "virtio"],
        ["value", "mtu", "9000"], ["value", "modem", "1"], ["check", "disable_audio", true], ["value", "relay_url", "wss://relay.invalid/"]]],
    ["x86_64 q35 2 cores", [["value", "cpu_type", "x86_64"], ["value", "machine_type", "q35"], ["value", "cpu_cores", "2"]]],
    ["acpi", [["check", "acpi", true], ["value", "vga_memory_size", "3"]]],
    ["fetch relay", [["value", "relay_url", "fetch:https://cors.invalid/"]]],
    ["no relay", [["value", "relay_url", ""], ["value", "net_device_type", "none"]]],
    ["empty disks", [["click", "hda_toggle_empty_disk"], ["value", "hda_empty_size", "50"], ["click", "fda_toggle_empty_disk"],
        ["value", "fda_empty_size", "368640"]]],
    ["empty hdb", [["click", "hdb_toggle_empty_disk"], ["value", "hdb_empty_size", "99999"], ["click", "fdb_toggle_empty_disk"]]],
    ["disk urls", [["value", "hda_url", " http://127.0.0.1:8471/a.img "], ["value", "hda_disk_option", "read_write"],
        ["value", "hdb_url", "b.img"]]],
    ["read write without a url", [["value", "hda_disk_option", "read_write"]]],
    ["second read write without a url", [["value", "hda_url", "a.img"], ["value", "hdb_disk_option", "read_write"]]],
];

/**
 * The differences between two records, one line each
 * @param {!Object} expected
 * @param {!Object} actual
 * @return {!Array<string>}
 */
export function compare_records(expected, actual)
{
    const lines = [];
    const walk = (a, b, at) =>
    {
        if(a && b && typeof a === "object" && typeof b === "object" && Array.isArray(a) === Array.isArray(b))
        {
            for(const k of new Set([...Object.keys(a), ...Object.keys(b)]))
            {
                if(!(k in a)) lines.push(at + "." + k + ": only now, " + JSON.stringify(b[k]));
                else if(!(k in b)) lines.push(at + "." + k + ": missing now, was " + JSON.stringify(a[k]));
                else walk(a[k], b[k], at + "." + k);
            }
        }
        else if(JSON.stringify(a) !== JSON.stringify(b))
        {
            lines.push(at + ": " + JSON.stringify(a) + " -> " + JSON.stringify(b));
        }
    };
    for(const key of new Set([...Object.keys(expected), ...Object.keys(actual)]))
    {
        if(!(key in actual)) lines.push(key + ": not recorded now");
        else if(!(key in expected)) lines.push(key + ": new case");
        else walk(expected[key], actual[key], key);
    }
    return lines;
}
                                                                           source/v64/tests/app/legacy_options.mjs                                                             0000755 0000000 0000000 00000021206 00000000000 015344  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The options the pages give new V86(), recorded in headless Chrome
// (docs/vm-manager-plan.md U0): the VM manager (index.html, build/v86_app.js)
// for a set of query arguments, the debug page (debug.html,
// src/browser/main.js) for those and for starts from its form. A test hook (window.v86_record_options, defined by the script this
// server puts at the top of the pages) receives the options instead of
// starting the emulator. The old page (legacy.html, ADVANCED-compiled
// build/v86_all.js) was recorded too until U7 deleted it.
//   node tests/app/legacy_options.mjs record=<file>   record into a JSON file
//   node tests/app/legacy_options.mjs check=<file>    record and compare with a recorded file
// tests/app/shared_options.mjs makes the same starts from the modules.
// Needs build/v86_app.js and build/libv86.mjs (make app), and Chrome (CHROME).

import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { QUERY_CASES, FORM_CASES, compare_records } from "./legacy_cases.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const arg = name => (process.argv.find(a => a.startsWith(name + "=")) || "").slice(name.length + 1) || undefined;
const record_file = arg("record"), check_file = arg("check");
if(!record_file && !check_file)
{
    console.error("usage: node tests/app/legacy_options.mjs record=<file> | check=<file>");
    process.exit(2);
}
/** The pages (the form only on the debug page) */
const PAGES = ["index.html", "debug.html"];
const HAS_FORM = page => page !== "index.html";

// (the page's hook and the frame's report to the driver)
const RECORDER = `<script>
(function() {
    const ser = v =>
        v === undefined ? { $: "undefined" } :
        typeof v === "number" && !Number.isFinite(v) ? { $: String(v) } :
        v === null || typeof v !== "object" && typeof v !== "function" ? v :
        typeof v === "function" ? { $: "function" } :
        v instanceof Element ? { $: "element", id: v.id } :
        v instanceof File ? { $: "File", name: v.name, size: v.size } :
        v instanceof ArrayBuffer ? { $: "ArrayBuffer", byteLength: v.byteLength } :
        Array.isArray(v) ? v.map(ser) :
        Object.fromEntries(Object.keys(v).map(k => [k, ser(v[k])]));
    const fields = () => Object.fromEntries(["memory_size", "vga_memory_size", "cpu_type", "machine_type", "acpi"]
        .map(id => document.getElementById(id)).filter(Boolean).map(e => [e.id, e.type === "checkbox" ? e.checked : e.value]));
    window.v86_record_options = options => parent.postMessage({ kind: "options", options: ser(options), search: location.search,
        title: document.title, fields: fields(), reset: document.getElementById("reset")?.style.display || "" }, "*");
    window.alert = text => parent.postMessage({ kind: "alert", text: String(text), fields: fields() }, "*");
})();
</script>`;

const DRIVER = `<!doctype html><body><script>
(async () => {
    const cases = await (await fetch("/__cases")).json();
    const results = {};
    for(const c of cases)
    {
        results[c.key] = await new Promise(resolve => {
            const frame = document.createElement("iframe");
            let done = false;
            const finish = r => {
                if(done) return;
                done = true;
                removeEventListener("message", on_message);
                clearTimeout(timer);
                frame.remove();
                resolve(r);
            };
            const on_message = e => { if(e.source === frame.contentWindow) finish(e.data); };
            addEventListener("message", on_message);
            const timer = setTimeout(() => finish({ kind: "timeout" }), 20000);
            if(c.form)
            {
                frame.onload = () => {
                    const d = frame.contentDocument;
                    for(const [what, id, value] of c.form)
                    {
                        const e = d.getElementById(id);
                        if(!e) { finish({ kind: "missing", id }); return; }
                        if(what === "click") e.click();
                        else if(what === "check") e.checked = value;
                        else e.value = value;
                    }
                    d.getElementById("start_emulation").click();
                };
            }
            frame.src = c.url;
            document.body.appendChild(frame);
        });
    }
    await fetch("/__done", { method: "POST", body: JSON.stringify(results) });
})();
</script>`;

/** The keys in order, for a stable file */
function sorted(value)
{
    if(Array.isArray(value)) return value.map(sorted);
    if(value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map(k => [k, sorted(value[k])]));
    return value;
}

const cases = [];
for(const page of PAGES)
{
    for(const query of QUERY_CASES) cases.push({ key: page + " ?" + query, url: "/" + page + "?" + query });
    if(HAS_FORM(page)) for(const [name, form] of FORM_CASES) cases.push({ key: page + " form " + name, url: "/" + page, form });
}

const profile_dir = fs.mkdtempSync(path.join(os.tmpdir(), "v86-legacy-options-"));
let browser, timeout, port;

const server = http.createServer((req, res) =>
{
    const address = new URL(req.url, "http://localhost");
    if(address.pathname === "/__driver.html") { res.writeHead(200, { "Content-Type": "text/html" }).end(DRIVER); return; }
    if(address.pathname === "/__cases") { res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(cases)); return; }
    if(address.pathname === "/__done")
    {
        let body = "";
        req.on("data", d => { body += d; });
        req.on("end", () => { res.end("OK"); done(JSON.parse(body)); });
        return;
    }
    const file = path.resolve(root, "." + decodeURIComponent(address.pathname));
    if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
    let body;
    try { body = fs.readFileSync(file); }
    catch(e) { res.writeHead(404).end(); return; }
    const type = file.endsWith(".wasm") ? "application/wasm" : /\.(js|mjs)$/.test(file) ? "text/javascript" :
        file.endsWith(".html") ? "text/html" : file.endsWith(".css") ? "text/css" : "application/octet-stream";
    if(file.endsWith(".html")) body = Buffer.from(RECORDER + body.toString());
    res.writeHead(200, { "Content-Type": type, "Cache-Control": "no-store" });
    res.end(body);
});

function done(results)
{
    clearTimeout(timeout);
    server.close();
    if(browser) browser.kill();
    setTimeout(() => fs.rmSync(profile_dir, { recursive: true, force: true }), 500);

    // (this server's origin, a new port each run, as one name)
    const origin = new RegExp("http://127\\.0\\.0\\.1:" + port, "g");
    const record = {};
    for(const [key, result] of Object.entries(results))
    {
        const value = sorted(result);
        record[key] = JSON.parse(JSON.stringify(value).replace(origin, "http://ORIGIN"));
    }
    // (a form case of a field the page does not have is recorded as such)
    const failed = Object.entries(record).filter(([, r]) => !["options", "alert", "missing"].includes(r.kind));
    for(const [key, r] of failed) console.log("NO OPTIONS " + key + ": " + JSON.stringify(r));
    console.log(Object.keys(record).length + " cases, " + failed.length + " without options");
    if(record_file)
    {
        fs.writeFileSync(record_file, JSON.stringify(record, null, 1) + "\n");
        console.log("recorded " + record_file);
        process.exitCode = failed.length ? 1 : 0;
        return;
    }
    const differences = compare_records(JSON.parse(fs.readFileSync(check_file, "utf8")), record);
    for(const line of differences) console.log(line);
    console.log(differences.length ? "FAIL: " + differences.length + " differences from " + check_file : "PASS: the same as " + check_file);
    process.exitCode = differences.length || failed.length ? 1 : 0;
}

server.listen(0, "127.0.0.1", () =>
{
    port = server.address().port;
    const url = "http://127.0.0.1:" + port + "/__driver.html";
    browser = spawn(process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
        "--user-data-dir=" + profile_dir, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", d => { stderr = (stderr + d).slice(-4000); });
    timeout = setTimeout(() =>
    {
        console.error("FAIL: timed out\n" + stderr);
        server.close();
        browser.kill();
        process.exitCode = 1;
    }, +process.env.TIMEOUT_MS || 600000);
});
                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/app/machine_rules.mjs                                                              0000755 0000000 0000000 00000011565 00000000000 015152  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// allowed_options (src/machine_options.js, docs/vm-manager-plan.md U0): what
// it allows is what the library accepts, for every CPU, machine, display
// adapter and network card, and the options it marks unavailable are
// rejected (check_machine_options, and the PC platform's own checks).
//   node tests/app/machine_rules.mjs

import assert from "node:assert/strict";
import { ARM_MACHINE_TYPES, CPU_TYPES, MACHINE_TYPES, GRAPHICS_ADAPTERS, NET_DEVICE_TYPES, MAX_CORES, PC_ONLY, VIRT_ONLY, Q35_ONLY,
    allowed_options, check_machine_options } from "../../src/machine_options.js";
import { create_platform } from "../../src/platform.js";
import { VIRT_MAX_CORES } from "../../src/virt/platform.js";

const accepts = options => { try { check_machine_options(options); return true; } catch(e) { return false; } };
let checks = 0;
// (a valid value of the options that are not booleans)
const VALUES = { virtio_input: ["keyboard"], virtio_transport: "pci", audio_device: "hd_audio",
    audio_device_path: "build/v86-hd-audio.js", usb: { controller: "uhci", tablet: true }, firmware: { type: "seabios" }, tpm: { version: "2.0" } };

assert.equal(VIRT_MAX_CORES, MAX_CORES, "the virt machine's cores");
for(const cpu_type of CPU_TYPES)
{
    for(const machine_type of MACHINE_TYPES)
    {
        const allowed = allowed_options(cpu_type, machine_type);
        const valid = allowed.machine_types.includes(machine_type);
        assert.equal(accepts({ cpu_type, machine_type }), valid, cpu_type + " on " + machine_type);
        checks++;
        if(!valid) continue;
        for(const adapter of GRAPHICS_ADAPTERS)
        {
            assert.equal(accepts({ cpu_type, machine_type, graphics_adapter: adapter }), allowed.graphics_adapters.includes(adapter),
                cpu_type + " on " + machine_type + " with " + adapter);
            checks++;
        }
        for(const type of NET_DEVICE_TYPES)
        {
            assert.equal(accepts({ cpu_type, machine_type, net_device: { type } }), allowed.net_device_types.includes(type),
                cpu_type + " on " + machine_type + " with " + type);
            checks++;
        }
        for(const name of [...PC_ONLY, ...VIRT_ONLY, "acpi"])
        {
            const rejected = !accepts({ cpu_type, machine_type, [name]: VALUES[name] === undefined ? true : VALUES[name] });
            if(name in allowed.unavailable)
            {
                assert(rejected || Q35_ONLY.includes(name), name + " on " + machine_type + " is unavailable but accepted");
            }
            else
            {
                assert(!rejected, name + " on " + machine_type + " is available but rejected");
            }
            checks++;
        }
        if(!ARM_MACHINE_TYPES.includes(machine_type))
        {
            // (the PC platform's checks: Q35's devices, ACPI)
            const platform = settings => { try { create_platform(Object.assign({ machine_type, acpi: true }, settings), 128 << 20); return true; } catch(e) { return false; } };
            for(const name of Q35_ONLY)
            {
                assert.equal(platform({ [name]: name === "pcie_root_ports" ? 1 : true }), !(name in allowed.unavailable), name + " on " + machine_type);
                checks++;
            }
            assert.equal(platform({ acpi: false }), allowed.acpi === "with_cores", "acpi: false on " + machine_type);
            assert.equal(platform({ acpi: false, cpu_cores: 2 }), false, "two cores without ACPI on " + machine_type);
            assert.equal(platform({ cpu_cores: allowed.max_cores }), true, allowed.max_cores + " cores on " + machine_type);
            assert.equal(platform({ cpu_cores: allowed.max_cores + 1 }), false, allowed.max_cores + 1 + " cores on " + machine_type);
            checks += 4;
        }
        else
        {
            assert.equal(allowed.acpi, "none");
        }
    }
}
// UEFI (docs/uefi.md): the x86_64 CPU with ACPI, its code image, no BIOS
// images; on i440FX QEMU's layout
const uefi = { type: "uefi", code: { url: "c.fd" } };
for(const [options, accepted] of [
    [{ cpu_type: "x86_64", machine_type: "q35", acpi: true, firmware: uefi }, true],
    [{ cpu_type: "x86_64", machine_type: "i440fx", acpi: true, qemu_compatible: true, firmware: uefi }, true],
    [{ cpu_type: "x86_64", machine_type: "i440fx", acpi: true, firmware: uefi }, false],
    [{ cpu_type: "x86", machine_type: "q35", acpi: true, firmware: uefi }, false],
    [{ cpu_type: "x86_64", machine_type: "q35", firmware: uefi }, false],
    [{ cpu_type: "x86_64", machine_type: "q35", acpi: true, firmware: { type: "uefi" } }, false],
    [{ cpu_type: "x86_64", machine_type: "q35", acpi: true, firmware: uefi, bios: { url: "b.bin" } }, false],
    [{ cpu_type: "arm64", machine_type: "virt", firmware: uefi }, false],
])
{
    assert.equal(accepts(options), accepted, JSON.stringify(options));
    checks++;
}
console.log("PASS: " + checks + " checks of allowed_options");
                                                                                                                                           source/v64/tests/app/missing_image_test.html                                                        0000644 0000000 0000000 00000006606 00000000000 016356  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>A missing image</title>
<!-- An image that is not there (HTTP 404) fails with the reason, on the page (worker=0) and with the CPU in its Worker:
     the start (emulator-error, no hang, no disk of an error page), and set_fda, set_cdrom and attach_sata_drive
     (rejected). node tests/app/browser_runner.mjs tests/app/missing_image_test.html [worker=0] -->
<div id="screen"><canvas></canvas></div>
<pre id="result"></pre>
<script type="module">
import { V86 } from "../../build/libv86.mjs";
const worker = new URLSearchParams(location.search).get("worker") !== "0";
const lines = [];
const check = (condition, what) => { if(!condition) throw new Error(what); };
const config = options => Object.assign({
    wasm_path: "../../build/v86.wasm", cpu_worker: worker, cpu_worker_url: "../../build/cpu-worker.js",
    bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
    graphics_adapter: "bochs_vga", graphics_adapter_path: "../../build/v86-bochs-vga.js",
    memory_size: 32 << 20, autostart: false, disable_speaker: true,
    screen: { container: document.getElementById("screen") },
}, options);
/** loaded, or the start's error */
function started(vm)
{
    return Promise.race([
        new Promise(resolve => vm.add_listener("emulator-loaded", () => resolve({ loaded: true }))),
        new Promise(resolve => vm.add_listener("emulator-error", error => resolve({ error: String(error && error.message || error) }))),
        new Promise(resolve => setTimeout(() => resolve({ timeout: true }), 30000)),
    ]);
}
async function rejection(promise)
{
    try { await promise; } catch(error) { return error.message; }
    return null;
}

try
{
    let vm = new V86(config({ fda: { url: "missing-floppy.img" } }));
    const start = await started(vm);
    check(start.error && /fda: (\S*\/)?missing-floppy\.img could not be loaded \(HTTP 404\)/.test(start.error), "the start: " + JSON.stringify(start));
    lines.push("the start with a missing fda: emulator-error \"" + start.error + "\"");
    await vm.destroy().catch(() => {});

    vm = new V86(config({}));
    check((await started(vm)).loaded, "a machine without disks starts");
    const fda = await rejection(vm.set_fda({ url: "missing-floppy.img" }));
    check(fda && /fda: (\S*\/)?missing-floppy\.img could not be loaded \(HTTP 404\)/.test(fda), "set_fda: " + fda);
    const cdrom = await rejection(vm.set_cdrom({ url: "missing-cd.iso" }));
    check(cdrom && /cdrom: (\S*\/)?missing-cd\.iso could not be loaded \(HTTP 404\)/.test(cdrom), "set_cdrom: " + cdrom);
    lines.push("set_fda and set_cdrom of a missing image: rejected (\"" + fda + "\", \"" + cdrom + "\")");
    await vm.destroy();

    vm = new V86(config({ machine_type: "q35", acpi: true }));
    check((await started(vm)).loaded, "a Q35 machine starts");
    const sata = await rejection(vm.attach_sata_drive(3, { url: "missing-disk.img" }));
    check(sata && /sata3: (\S*\/)?missing-disk\.img could not be loaded \(HTTP 404\)/.test(sata), "attach_sata_drive: " + sata);
    lines.push("attach_sata_drive of a missing image: rejected (\"" + sata + "\")");
    await vm.destroy();
    document.getElementById("result").textContent = "PASS (" + (worker ? "CPU Worker" : "page") + ")\n" + lines.join("\n");
}
catch(error)
{
    document.getElementById("result").textContent = "FAIL " + (error.stack || error.message) + "\n" + lines.join("\n");
}
</script>
                                                                                                                          source/v64/tests/app/opfs_disk_test.html                                                            0000644 0000000 0000000 00000002517 00000000000 015521  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: the browser disk backend</title>
<!-- src/opfs_disk.js (docs/vm-manager-plan.md U6): tests/app/opfs_disk_worker.js in a dedicated worker;
     and on the page, where there are no synchronous access handles: written back, it needs the CPU Worker.
     node tests/app/browser_runner.mjs tests/app/opfs_disk_test.html -->
<pre id="result"></pre>
<script type="module">
import { OpfsDisk } from "../../src/opfs_disk.js";

const worker = new Worker("opfs_disk_worker.js", { type: "module" });
const result = await new Promise(resolve => { worker.onmessage = e => resolve(e.data); worker.onerror = e => resolve({ status: "FAIL", error: e.message, log: [] }); });
let page = "";
if(result.status === "PASS")
{
    // (the worker made v86/disks/t1.img)
    try
    {
        await new OpfsDisk("opfs:v86/disks/t1.img", { name: "hda" }).load();
        page = "FAIL: the page opened a disk to write back";
    }
    catch(e)
    {
        page = /needs the CPU Worker/.test(e.message) ? "on the page: \"" + e.message.slice(0, 90) + "…\"" : "FAIL: " + e.message;
    }
}
const failed = result.status !== "PASS" || page.startsWith("FAIL");
document.getElementById("result").textContent = (failed ? "FAIL " + (result.error || page) : "PASS") + "\n" + result.log.concat(page ? [page] : []).join("\n");
</script>
                                                                                                                                                                                 source/v64/tests/app/opfs_disk_worker.js                                                            0000644 0000000 0000000 00000016512 00000000000 015523  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The browser disk backend (src/opfs_disk.js, docs/vm-manager-plan.md U6) in
// a dedicated worker, where FileSystemSyncAccessHandles exist: reads and
// writes, the record (identity, generation; the VM manager's fields kept),
// the generation's moves (a session's first write, the first after a
// snapshot), snapshots' references, the timed flush, one writer per disk,
// the checks at the start, the browser's quota as a write error that is not
// retried. tests/app/opfs_disk_test.html runs it.

import { OpfsDisk } from "../../src/opfs_disk.js";

const log = [];
const check = (condition, what) => { if(!condition) throw new Error(what); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const call = (fn, ...args) => new Promise(resolve => fn(...args, (...result) => resolve(result)));

async function file(name, size, record)
{
    let dir = await navigator.storage.getDirectory();
    for(const part of ["v86", "disks"]) dir = await dir.getDirectoryHandle(part, { create: true });
    await dir.removeEntry(name).catch(() => {});
    await dir.removeEntry(name.replace(/\.img$/, ".json")).catch(() => {});
    const access = await (await dir.getFileHandle(name, { create: true })).createSyncAccessHandle();
    access.truncate(size);
    access.close();
    if(record)
    {
        const writable = await (await dir.getFileHandle(name.replace(/\.img$/, ".json"), { create: true })).createWritable();
        await writable.write(JSON.stringify(record));
        await writable.close();
    }
    return dir;
}
async function record_of(dir, name)
{
    return JSON.parse(await (await (await dir.getFileHandle(name.replace(/\.img$/, ".json"))).getFile()).text());
}
async function load_error(disk)
{
    try { await disk.load(); }
    catch(e) { return e; }
    return null;
}

async function main()
{
    // a disk with the manager's record: its identity and generation, read and written
    const dir = await file("t1.img", 1 << 20, { uuid: "11111111-2222-3333-4444-555555555555", generation: 7, size: 1 << 20, label: "kept" });
    const disk = new OpfsDisk("opfs:v86/disks/t1.img", { name: "hda" });
    await disk.load();
    check(disk.byteLength === 1 << 20 && disk.writeback, "loaded");
    check(JSON.stringify(disk.identity) === JSON.stringify({ opfs: "opfs:v86/disks/t1.img", uuid: "11111111-2222-3333-4444-555555555555" }), "identity " + JSON.stringify(disk.identity));
    check(disk.generation() === "7", "the record's generation " + disk.generation());
    const [zeros] = await call(disk.get.bind(disk), 4096, 512);
    check(zeros.length === 512 && zeros.every(b => b === 0), "zeros");
    const data = new Uint8Array(1024).map((_, i) => i * 7 & 0xFF);
    const [write_error] = await call(disk.set.bind(disk), 512, data);
    check(!write_error, "a write");
    check(disk.generation() === "8", "the session's first write moved the generation: " + disk.generation());
    await call(disk.set.bind(disk), 4096, data.subarray(0, 512));
    check(disk.generation() === "8", "the second write did not");
    const [read] = await call(disk.get.bind(disk), 512, 1024);
    check(read.every((b, i) => b === data[i]), "read back");
    log.push("read and write; the record's identity and generation 7; the session's first write moved it to 8, the second did not");

    // the timed flush: 1 s after the last write
    check(disk.flushes === 0, "no flush yet");
    await sleep(1300);
    check(disk.flushes === 1, "the timed flush: " + disk.flushes);
    log.push("the timed flush 1 s after the last write");

    // a snapshot: the reference; the next write moves the generation; then the reference no longer fits
    const state = disk.get_state();
    check(state[0] === "v86-writeback" && state[3] === "8" && state[4] === 1 << 20, "the reference " + JSON.stringify(state));
    disk.check_state(state);
    await call(disk.set.bind(disk), 0, data.subarray(0, 512));
    check(disk.generation() === "9", "the first write after the snapshot moved the generation");
    let refused = null;
    try { disk.check_state(state); } catch(e) { refused = e; }
    check(refused && /cannot go back/.test(refused.message), "a reference of before the write is refused");
    log.push("a snapshot's reference (generation 8, no data); the write after it moved the generation to 9; the reference refused then");

    // one writer: another disk on the same image cannot open it
    const second = new OpfsDisk("opfs:v86/disks/t1.img", { name: "hdb" });
    const busy = await load_error(second);
    check(busy && busy.kind === "in_use" && /used by another tab/.test(busy.message), "the second writer: " + (busy && busy.message));
    log.push("a second writer refused: " + busy.message.slice(0, 70) + "…");

    // the browser's quota: a write error not retried
    const write = disk.access.write.bind(disk.access);
    disk.access.write = () => { throw new globalThis.DOMException("The quota has been exceeded.", "QuotaExceededError"); };
    const [quota] = await call(disk.set.bind(disk), 0, data.subarray(0, 512));
    check(quota && quota.kind === "no_space" && quota.retryable === false && /storage for this site is full/.test(quota.message), "the quota's error " + (quota && quota.message));
    disk.access.write = write;
    log.push("QuotaExceededError: a write error of kind no_space, not retried");

    // closed: flushed, the record kept (with the manager's fields); another session opens it
    await call(disk.close.bind(disk));
    const record = await record_of(dir, "t1.img");
    check(record.generation === 9 && record.label === "kept" && record.size === 1 << 20, "the record " + JSON.stringify(record));
    const again = new OpfsDisk("opfs:v86/disks/t1.img", { name: "hda" });
    await again.load();
    again.check_state(again.get_state());
    const [after] = await call(again.get.bind(again), 512, 1024);
    check(after.every((b, i) => b === data[i]), "the data after closing");
    await call(again.close.bind(again));
    log.push("closed and opened again: the data and the record (generation 9, the manager's label) kept");

    // the checks at the start
    await file("odd.img", 1000);
    const odd = await load_error(new OpfsDisk("opfs:v86/disks/odd.img", { name: "hda" }));
    check(odd && /whole number of 512-byte sectors/.test(odd.message), "a size that is not whole sectors: " + (odd && odd.message));
    const sized = await load_error(new OpfsDisk("opfs:v86/disks/t1.img", { name: "hda", size: 2048 }));
    check(sized && /the descriptor's size says 2048/.test(sized.message), "the descriptor's size");
    const missing = await load_error(new OpfsDisk("opfs:v86/disks/none.img", { name: "hda" }));
    check(missing && /does not exist/.test(missing.message), "a disk that does not exist: " + (missing && missing.message));
    // (a disk without a record: one made, its generation moved as its size differs from none)
    await file("plain.img", 4096);
    const plain = new OpfsDisk("opfs:v86/disks/plain.img", { name: "hda" });
    await plain.load();
    check(/^[0-9a-f-]{36}$/.test(plain.identity.uuid) && plain.generation() === "2", "a disk without a record: " + plain.generation());
    await call(plain.close.bind(plain));
    log.push("refused at the start: not whole sectors, another size than the descriptor's, a disk that does not exist; a disk without a record gets one");
}

main().then(() => postMessage({ status: "PASS", log }), e => postMessage({ status: "FAIL", error: e.stack || e.message, log }));
                                                                                                                                                                                      source/v64/tests/app/presets.mjs                                                                    0000755 0000000 0000000 00000054142 00000000000 014017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The wizard's guest presets (src/app/guest_presets.js) and the settings
// dialog's rules (src/app/vm_model.js), docs/vm-manager-plan.md U3: every
// preset's configuration passes validate_config and the library's checks
// (check_machine_options, check_disk_options), the verified ones name their
// basis; Android's gives the options the Android test starts with; and no
// sequence of the dialog's choices (the CPU, machine, display, network,
// sound, cores, memory, ACPI, Q35's devices) makes a configuration the
// library refuses.
//   node tests/app/presets.mjs

import assert from "node:assert/strict";
import { PRESETS, preset, preset_config } from "../../src/app/guest_presets.js";
import { choices, change, fitted } from "../../src/app/vm_model.js";
import { new_config, validate_config, check_config, config_to_options } from "../../src/app/vm_config.js";
import { hardware_rows } from "../../src/app/ui/describe.js";

let passed = 0;
function test(name, fn)
{
    fn();
    passed++;
    console.log("ok - " + name);
}
const ENV = { debug: false, query_append: "", graphics_proxy: false, screen_container: undefined, file: () => new Blob([]) };
const problems = c => check_config(c).map(p => p.path + ": " + p.message);

test("every preset: a valid configuration the library accepts, with its new disk", () =>
{
    assert.equal(new Set(PRESETS.map(p => p.id)).size, PRESETS.length);
    for(const p of PRESETS)
    {
        const config = preset_config(p, { name: "x" });
        assert.equal(config.template, p.id);
        assert.equal(config.guest, p.guest);
        assert.deepEqual(problems(config), [], p.id);
        // (its new empty disk where the wizard puts it by default: in memory up to 2000 MB, else a URL stands in)
        config.disks = [{ slot: "hda", image: p.disk_mb <= 2000 && p.disk_location === "memory" ?
            { kind: "empty", size: p.disk_mb << 20 } : { kind: "url", url: "http://127.0.0.1:8471/x.img", size: p.disk_mb * 1048576 },
        disk_option: p.disk_location === "memory" ? "read_only" : "read_write", disk_error: "stop" }];
        assert.deepEqual(problems(config), [], p.id + " with its disk");
        assert(p.install.length && p.install_text && p.basis, p.id);
        assert(p.verified || p.id === "other" || /never|only starts|not verified/i.test(p.basis), p.id + ": an unverified preset says so");
    }
    const unverified = PRESETS.filter(p => !p.verified).map(p => p.id);
    assert.deepEqual(unverified, ["windows11", "windows7", "android_x86_64", "android_x86", "other"]);
    console.log("    " + PRESETS.length + " presets, not verified: " + unverified.join(", "));
});

test("the presets' hardware (the plan's table)", () =>
{
    const row = id =>
    {
        const c = preset_config(preset(id));
        return [c.cpu.type, c.machine.type, c.memory.mb, c.cpu.cores, c.display.adapter, c.display.vram_mb, c.network.map(n => n.device).join("+"),
            c.sound.device, c.machine.acpi];
    };
    assert.deepEqual(row("dos"), ["x86", "i440fx", 64, 1, "bochs_vga", 8, "ne2k", "sb16", false]);
    assert.deepEqual(row("windows98"), ["x86", "i440fx", 256, 1, "bochs_vga", 16, "ne2k", "sb16", false]);
    assert.deepEqual(row("windows95"), ["x86", "i440fx", 64, 1, "bochs_vga", 16, "ne2k", "sb16", false]);
    assert.deepEqual(row("windowsxp"), ["x86", "i440fx", 2048, 1, "bochs_vga", 16, "ne2k", "sb16", false]);
    assert.deepEqual(row("windows81"), ["x86_64", "i440fx", 2048, 2, "vmware_svga", 16, "e1000", "hd_audio", true]);
    assert.deepEqual(row("windows7"), row("windows81"), "Vista, 7 and 10: Windows 8.1's hardware");
    // (Windows 11: Q35 with UEFI, Secure Boot with Microsoft's keys, a TPM 2.0, 4 GiB)
    assert.deepEqual(row("windows11"), ["x86_64", "q35", 4096, 2, "vmware_svga", 16, "e1000", "hd_audio", true]);
    const w11 = preset_config(preset("windows11"));
    assert.deepEqual([w11.machine.firmware, w11.machine.secure_boot, w11.machine.secure_boot_keys, w11.tpm, w11.usb.controller],
        ["uefi", true, "microsoft", { state: null }, "xhci"]);
    assert.equal(preset("windows11").disk_mb, 64 * 1024, "Windows 11's 64 GB");
    assert.deepEqual(row("linux"), ["x86", "i440fx", 512, 1, "bochs_vga", 8, "ne2k", "sb16", true]);
    assert.deepEqual(row("linux64"), ["x86_64", "i440fx", 1024, 2, "virtio_gpu", 8, "virtio", "sb16", true]);
    assert.deepEqual(row("linux_arm64"), ["arm64", "virt", 1024, 4, "virtio_gpu", 8, "virtio", "none", false]);
    assert.deepEqual(row("android16"), ["arm64", "virt", 1536, 4, "virtio_gpu", 8, "virtio+virtio+virtio", "virtio", false]);
    assert.deepEqual(row("linux_arm32"), ["arm32", "virt", 512, 2, "none", 8, "virtio", "none", false]);
    assert.deepEqual(row("android7_arm32"), ["arm32", "ranchu", 1024, 2, "none", 8, "virtio", "none", false]);
    assert.deepEqual(row("android_x86_64"), ["x86_64", "i440fx", 2048, 2, "virtio_gpu", 8, "virtio", "hd_audio", true]);
    assert.deepEqual(row("android_x86"), ["x86", "i440fx", 2048, 2, "virtio_gpu", 8, "virtio", "hd_audio", true]);
    assert.equal(preset_config(preset("windowsnt4")).advanced.cpuid_level, 2);
    // the USB tablet: XP, Vista to 8.1, Linux, Android-x86; not DOS, Windows 3.x, 9x, NT 4, 2000 or the ARM machines
    const tablet = PRESETS.filter(p => preset_config(p).usb).map(p => p.id);
    assert.deepEqual(tablet, ["windowsxp", "windows81", "windows11", "windows7", "linux", "linux64", "android_x86_64", "android_x86"]);
    assert.deepEqual(preset_config(preset("windows81")).usb, { controller: "xhci", tablet: true, disks: [] });
    // (xHCI for the systems with its driver; EHCI for XP to 7, whose drivers have none)
    assert.deepEqual(["windowsxp", "windows7", "windows81", "linux", "linux64"].map(id => preset_config(preset(id)).usb.controller),
        ["ehci", "ehci", "xhci", "xhci", "xhci"]);
});

test("Android's options: those of tests/a64/android_boot.mjs (A64_ANDROID_BOOTLOADER=1)", () =>
{
    const c = preset_config(preset("android16"));
    c.disks = [{ slot: "hda", image: { kind: "url", url: "disk.img", async: true }, disk_option: "read_only", disk_error: "stop" }];
    let o = config_to_options(c, ENV);
    assert.equal(o.cpu_type, "arm64");
    assert.equal(o.cpu_cores, 4);
    assert.equal(o.memory_size, 1536 << 20);
    // (the bootloader: no kernel, initrd or command line of the page's)
    assert.deepEqual(o.android, { device: "cf_arm64_only_phone", gpu_mode: "gfxstream", selinux: "enforcing", vendor_ramdisk: undefined, gles_version: undefined });
    assert.equal("kernel" in o || "initrd" in o, false);
    assert.equal(o.cmdline, undefined);
    assert.equal(o.virtio_transport, "pci");
    assert.deepEqual(o.virtio_disks, [{ url: "disk.img", async: true }]);
    assert.equal(o.graphics_adapter, "virtio_gpu");
    assert.deepEqual(o.graphics_adapter_test, { level: "gfxstream" });
    assert.equal(o.virtio_gpu_pci_slot, 2);
    assert.deepEqual(o.net_device, { type: "virtio", relay_url: "fetch", cors_proxy: undefined, mtu: 1500, count: 3, id: 2 });
    assert.equal(o.virtio_console, true);
    assert.equal(o.virtio_console_ports, 18);
    assert.equal(o.virtio_rng, true);
    assert.deepEqual(o.virtio_input, ["keyboard", "multitouch"]);
    assert.equal(o.virtio_vsock, true);
    assert.equal(o.virtio_sound, true);
    assert.deepEqual(o.jit_switches, { a64_page: 1 });
    assert.deepEqual(check_config(c), []);
    // (the debug vendor ramdisk, and a command line after the device's)
    c.android = Object.assign({}, c.android, { vendor_ramdisk: "debug", debug_ramdisk: { kind: "url", url: "vendor_ramdisk-debug.img" } });
    c.kernel = { bzimage: null, initrd: null, cmdline: "androidboot.x=1", multiboot: null, from_filesystem: false };
    o = config_to_options(c, ENV);
    assert.deepEqual(o.android.vendor_ramdisk, { url: "vendor_ramdisk-debug.img" });
    assert.equal(o.cmdline, "androidboot.x=1");
    assert.deepEqual(check_config(c), []);
});

test("Android 7.1's emulator image: the options of tests/a32/android_boot.mjs (A32_ANDROID_DISK=1)", () =>
{
    const c = preset_config(preset("android7_arm32"));
    c.disks = [{ slot: "hda", image: { kind: "url", url: "disk.img", async: true }, disk_option: "read_write", disk_error: "stop" }];
    const o = config_to_options(c, ENV);
    assert.equal(o.cpu_type, "arm32");
    assert.equal(o.machine_type, "ranchu");
    assert.equal(o.cpu_cores, 2);
    assert.equal(o.memory_size, 1024 << 20);
    assert.deepEqual(o.android, { device: "ranchu_25_armeabi_v7a", gpu_mode: "host", selinux: "enforcing", vendor_ramdisk: undefined, gles_version: "3.1" });
    assert.equal("kernel" in o || "initrd" in o, false);
    assert.equal(o.graphics_adapter, "none");
    assert.deepEqual(o.virtio_disks, [{ url: "disk.img", async: true, disk_option: "read_write" }]);
    assert.equal(o.net_device.type, "virtio");
    assert.equal(o.net_device.relay_url, "fetch");
    assert.equal(o.virtio_transport, undefined);
    assert.equal(o.virtio_input, undefined);
    assert.equal(o.cpu_profile, undefined);
    assert.deepEqual(o.jit_switches, { a64_page: 1 });
    assert.deepEqual(check_config(c), []);
    // (its device model is ranchu's: Cuttlefish's on ranchu is refused, ranchu's on virt too)
    assert.ok(problems(Object.assign({}, c, { android: Object.assign({}, c.android, { device: "cf_arm64_only_phone" }) }))
        .some(p => /boots on the virt machine with the arm64 CPU/.test(p)));
    let { config, notes } = change(c, "machine.type", "virt");
    assert.equal(config.android, null);
    assert.ok(notes.some(n => /ranchu_25_armeabi_v7a boots on the ranchu machine/.test(n)), JSON.stringify(notes));
    ({ config, notes } = change(c, "cpu.type", "arm64"));
    assert.equal(config.machine.type, "ranchu");
    assert.equal(config.android, null);
    assert.deepEqual(problems(config), []);
    // (its GPU modes, docs/gles-proxy-plan.md E5: the host's GPU or the
    // guest's CPU, "swiftshader" the guest's as before; not Cuttlefish's)
    for(const gpu_mode of ["host", "guest", "swiftshader"])
    {
        const d = Object.assign({}, c, { android: Object.assign({}, c.android, { gpu_mode }) });
        assert.deepEqual(problems(d), [], gpu_mode);
        assert.equal(config_to_options(d, ENV).android.gpu_mode, gpu_mode);
        assert.equal(fitted(d).config.android.gpu_mode, gpu_mode);
    }
    const gfxstream = Object.assign({}, c, { android: Object.assign({}, c.android, { gpu_mode: "gfxstream" }) });
    assert.ok(problems(gfxstream).some(p => /android.gpu_mode/.test(p)), JSON.stringify(problems(gfxstream)));
    ({ config, notes } = fitted(gfxstream));
    assert.equal(config.android.gpu_mode, "guest");
    assert.ok(notes.some(n => /Android's GPU: the guest's CPU \(ranchu_25_armeabi_v7a has no gfxstream\)/.test(n)), JSON.stringify(notes));
    // (and Cuttlefish has neither)
    const host = Object.assign(preset_config(preset("android16")), {});
    host.android = Object.assign({}, host.android, { gpu_mode: "host" });
    assert.ok(problems(host).some(p => /android.gpu_mode/.test(p)), JSON.stringify(problems(host)));
    assert.equal(fitted(host).config.android.gpu_mode, "swiftshader");
});

test("arm32 and ranchu: what a choice implies", () =>
{
    let { config, notes } = change(new_config(), "cpu.type", "arm32");
    assert.equal(config.machine.type, "virt");
    assert.ok(notes.some(n => /Machine: virt \(the arm32 CPU's\)/.test(n)), JSON.stringify(notes));
    ({ config, notes } = change(config, "machine.type", "ranchu"));
    assert.equal(config.cpu.type, "arm32");
    assert.equal(config.display.adapter, "none");
    assert.equal(config.sound.device, "none");
    assert.ok(notes.some(n => /the emulator's framebuffer/.test(n)), JSON.stringify(notes));
    assert.deepEqual(problems(config), []);
    assert.deepEqual(choices(config).graphics_adapters, ["none"]);
    assert.deepEqual(choices(config).sound_devices, ["none"]);
    ({ config, notes } = change(config, "memory.mb", 4096));
    assert.equal(config.memory.mb, 2048);
    ({ config, notes } = change(config, "cpu.type", "x86"));
    assert.equal(config.machine.type, "i440fx");
    ({ config, notes } = change(new_config(), "machine.type", "ranchu"));
    assert.equal(config.cpu.type, "arm64");
    assert.deepEqual(problems(config), []);
});

test("change: Android's bootloader follows the machine and Vulkan", () =>
{
    let { config, notes } = change(preset_config(preset("android16")), "display.proxy", false);
    assert.equal(config.display.vulkan, "none");
    assert.equal(config.android.gpu_mode, "swiftshader");
    assert.ok(notes.some(n => /SwiftShader/.test(n)), JSON.stringify(notes));
    assert.equal(fitted(config).config.android.gpu_mode, "swiftshader");
    ({ config, notes } = change(preset_config(preset("android16")), "cpu.type", "x86"));
    assert.equal(config.android, null);
    assert.ok(notes.some(n => /Android's bootloader off/.test(n)), JSON.stringify(notes));
    // (Venus for the display: Android's GPU follows)
    ({ config, notes } = change(preset_config(preset("android16")), "display.vulkan", "venus"));
    assert.equal(config.android.gpu_mode, "venus");
    assert.ok(notes.some(n => /Android's GPU: Venus/.test(n)), JSON.stringify(notes));
    assert.deepEqual(problems(config), []);
    assert.deepEqual(config_to_options(config, ENV).graphics_adapter_test, { level: "venus" });
    assert.equal(config_to_options(config, ENV).android.gpu_mode, "venus");
});

test("the summary's rows: Android's display and sound", () =>
{
    const rows = Object.fromEntries(hardware_rows(preset_config(preset("android16"))));
    assert.equal(rows["Display"], "virtio-gpu, 8 MB, Vulkan (gfxstream)");
    assert.equal(rows["Sound"], "virtio-snd");
    assert.equal(rows["Android boot"], "from the first disk (cf_arm64_only_phone), gfxstream");
    assert.equal(Object.fromEntries(hardware_rows(preset_config(preset("dos"))))["Sound"], "Sound Blaster 16");
});

test("change: what a choice implies, and says", () =>
{
    let { config, notes } = change(new_config(), "cpu.type", "arm64");
    assert.equal(config.machine.type, "virt");
    assert.equal(config.display.adapter, "virtio_gpu");
    assert.equal(config.network[0].device, "virtio");
    assert.equal(config.sound.device, "none");
    assert(notes.some(n => /Machine: virt/.test(n)) && notes.some(n => /Display: virtio_gpu/.test(n)), notes.join("; "));
    ({ config, notes } = change(config, "machine.type", "q35"));
    assert.equal(config.cpu.type, "x86");
    assert.equal(config.machine.acpi, true);
    assert.equal(config.machine.hpet, true);
    assert.equal(config.machine.smbus, true);
    ({ config } = change(config, "machine.type", "i440fx"));
    assert.equal(config.machine.hpet, false);
    assert.equal(config.machine.acpi, true, "ACPI stays on when it may");
    ({ config } = change(config, "machine.acpi", false));
    ({ config, notes } = change(config, "cpu.cores", 2));
    assert.equal(config.machine.acpi, true);
    assert(notes.some(n => /more than one core/.test(n)), notes.join("; "));
    ({ config, notes } = change(config, "memory.mb", 4096));
    assert.equal(config.cpu.type, "x86_64");
    ({ config, notes } = change(config, "cpu.type", "x86"));
    assert.equal(config.memory.mb, 2048);
    const floppy = new_config();
    floppy.floppies = [{ slot: "fda", image: { kind: "url", url: "f.img" }, disk_option: "read_only" }];
    floppy.serial = [{ port: 1, attach: "modem" }];
    ({ config, notes } = change(floppy, "cpu.type", "arm64"));
    assert.deepEqual(config.floppies, []);
    assert.equal(config.serial[0].attach, "terminal");
    assert(notes.some(n => /Floppy drives removed/.test(n)) && notes.some(n => /Modem removed/.test(n)), notes.join("; "));
    const choice = choices(config);
    assert.deepEqual(choice.graphics_adapters, ["none", "virtio_gpu"]);
    assert.deepEqual(choice.acpi_fixed && choice.acpi_fixed.value, false);
});

test("change: UEFI keeps the x86_64 CPU and ACPI, or goes", () =>
{
    const uefi = new_config();
    uefi.cpu.type = "x86_64";
    uefi.machine.acpi = true;
    uefi.machine.firmware = "uefi";
    let { config, notes } = change(uefi, "machine.acpi", false);
    assert.equal(config.machine.acpi, true);
    assert.equal(config.machine.firmware, "uefi");
    assert(notes.some(n => /ACPI on: UEFI needs it/.test(n)), notes.join("; "));
    ({ config, notes } = change(config, "cpu.type", "x86"));
    assert.equal(config.machine.firmware, "seabios");
    assert(notes.some(n => /Firmware: SeaBIOS/.test(n)), notes.join("; "));
    ({ config } = change(uefi, "cpu.type", "arm64"));
    assert.equal(config.machine.firmware, "seabios");
});

test("change: Secure Boot keeps UEFI on Q35, or goes", () =>
{
    const c = new_config();
    c.cpu.type = "x86_64";
    Object.assign(c.machine, { type: "q35", acpi: true, firmware: "uefi", secure_boot: true });
    let { config, notes } = change(c, "machine.type", "i440fx");
    assert.equal(config.machine.secure_boot, false);
    assert(notes.some(n => /Secure Boot off/.test(n)), notes.join("; "));
    ({ config, notes } = change(c, "cpu.type", "x86"));
    assert.equal(config.machine.firmware, "seabios");
    assert.equal(config.machine.secure_boot, false);
    ({ config } = change(c, "machine.secure_boot_keys", "none"));
    assert.equal(config.machine.secure_boot, true);
    assert.equal(config.machine.secure_boot_keys, "none");
});

test("change: the TPM keeps ACPI, or goes with an ARM CPU", () =>
{
    const c = new_config();
    c.machine.acpi = true;
    c.tpm = { state: null };
    let { config, notes } = change(c, "machine.acpi", false);
    assert.equal(config.machine.acpi, true);
    assert(notes.some(n => /ACPI on: the TPM needs it/.test(n)), notes.join("; "));
    ({ config, notes } = change(config, "cpu.type", "arm64"));
    assert.equal(config.tpm, null);
    assert(notes.some(n => /TPM removed/.test(n)), notes.join("; "));
});

test("change: Vulkan and the graphics proxy", () =>
{
    let { config, notes } = change(change(new_config(), "cpu.type", "arm64").config, "display.vulkan", "venus");
    assert.equal(config.display.proxy, true);
    assert(notes.some(n => /Graphics proxy: on/.test(n)), notes.join("; "));
    assert.deepEqual(problems(config), []);
    assert.deepEqual(config_to_options(config, ENV).graphics_adapter_test, { level: "venus" });
    ({ config, notes } = change(config, "display.proxy", false));
    assert.equal(config.display.vulkan, "none");
    assert(notes.some(n => /Vulkan: off/.test(n)), notes.join("; "));
    // (a PC keeps virtio-gpu and its Vulkan; another adapter drops it)
    ({ config } = change(change(config, "display.vulkan", "gfxstream").config, "cpu.type", "x86"));
    assert.equal(config.display.vulkan, "gfxstream");
    assert.deepEqual(config_to_options(config, ENV).graphics_adapter_test, { level: "gfxstream" });
    ({ config } = change(config, "display.adapter", "bochs_vga"));
    assert.equal(config.display.vulkan, "none");
    assert.deepEqual(problems(config), []);
});

test("every combination of the dialog's choices: CPU, machine, display, network, sound, cores", () =>
{
    let count = 0;
    for(const cpu of choices(new_config()).cpu_types)
    {
        let a = change(new_config(), "cpu.type", cpu).config;
        for(const machine of choices(a).machine_types)
        {
            const b = change(a, "machine.type", machine).config;
            for(const adapter of choices(b).graphics_adapters)
            {
                const c = change(b, "display.adapter", adapter).config;
                for(const nic of choices(c).net_devices)
                {
                    const d = change(c, "network.0.device", nic).config;
                    for(const sound of choices(d).sound_devices)
                    {
                        for(const cores of [1, 2, choices(d).max_cores])
                        {
                            const e = change(change(d, "sound.device", sound).config, "cpu.cores", cores).config;
                            assert.deepEqual(problems(e), [], [cpu, machine, adapter, nic, sound, cores].join(" "));
                            count++;
                        }
                    }
                }
            }
        }
    }
    console.log("    " + count + " combinations");
});

test("random sequences of the dialog's choices (5000 changes): every configuration accepted", () =>
{
    let seed = 1;
    const random = n => { seed = seed * 1103515245 + 12345 & 0x7FFFFFFF; return seed % n; };
    const pick = list => list[random(list.length)];
    let config = new_config();
    for(let i = 0; i < 5000; i++)
    {
        const ch = choices(config);
        const moves = [
            () => ["cpu.type", pick(ch.cpu_types)],
            () => ["machine.type", pick(ch.machine_types)],
            () => ["display.adapter", pick(ch.graphics_adapters)],
            () => ["display.vram_mb", pick([1, 8, 16, 64, ch.max_vram])],
            () => ["display.displays", config.display.adapter === "virtio_gpu" ? pick([1, 2, 4]) : 1],
            () => ["display.proxy", pick([true, false])],
            () => ["display.vulkan", config.display.adapter === "virtio_gpu" ? pick(["none", "venus", "gfxstream"]) : "none"],
            () => ["network.0.device", pick(ch.net_devices)],
            () => ["network.0.backend", pick(["none", "inbrowser", "fetch"])],
            () => ["sound.device", pick(ch.sound_devices)],
            () => ["cpu.cores", 1 + random(ch.max_cores)],
            () => ["memory.mb", pick([16, 64, 512, 2048, 2050, 4096, ch.max_memory])],
            () => ["machine.boot_order", pick(ch.boot_orders)],
            () => ch.acpi_fixed ? ["machine.acpi", ch.acpi_fixed.value] : ["machine.acpi", pick([true, false])],
            () => config.machine.type === "q35" ? [pick(["machine.hpet", "machine.smbus"]), pick([true, false])] : ["cpu.jit", pick([true, false])],
            () => config.machine.type === "q35" ? ["machine.pcie_root_ports", random(7)] : ["cpu.parallel", pick([true, false])],
            () => ["machine.firmware", pick(["seabios", "uefi"])],
            () => config.machine.firmware === "uefi" ? ["machine.secure_boot", pick([true, false])] : ["machine.secure_boot_keys", pick(["microsoft", "none"])],
        ];
        const [path, value] = pick(moves)();
        config = change(config, path, value).config;
        const p = problems(config);
        assert.deepEqual(p, [], "after " + path + " = " + JSON.stringify(value) + " (change " + i + ")");
    }
});

console.log(passed + " tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/app/shared_options.mjs                                                             0000755 0000000 0000000 00000015406 00000000000 015353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The shared modules as ES modules (docs/vm-manager-plan.md U0): Node
// imports src/browser/vm_options.js and query_compat.js, as the
// pages do, and makes each start that tests/app/legacy_options.mjs recorded
// in the VM manager (index.html: the addresses) and the debug page
// (debug.html: the addresses and its form): the same options, alerts,
// addresses and form fields.
//   node tests/app/legacy_options.mjs record=build/app/legacy-options.json
//   node tests/app/shared_options.mjs build/app/legacy-options.json

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { DEFAULT_FORM, settings_to_options } from "../../src/browser/vm_options.js";
import { start_settings, format_query_args } from "../../src/browser/query_compat.js";
import { FORM_CASES, compare_records } from "./legacy_cases.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const record_file = process.argv[2];
if(!record_file)
{
    console.error("usage: node tests/app/shared_options.mjs <file recorded by tests/app/legacy_options.mjs>");
    process.exit(2);
}
const recorded = JSON.parse(fs.readFileSync(record_file, "utf8"));

const SCREEN = { id: "screen_container" };
/** A copy of the form (plain values) */
const clone = v => JSON.parse(JSON.stringify(v));
const ser = v =>
    v === undefined ? { $: "undefined" } :
    typeof v === "number" && !Number.isFinite(v) ? { $: String(v) } :
    v === null || typeof v !== "object" && typeof v !== "function" ? v :
    typeof v === "function" ? { $: "function" } :
    v === SCREEN ? { $: "element", id: v.id } :
    v instanceof ArrayBuffer ? { $: "ArrayBuffer", byteLength: v.byteLength } :
    Array.isArray(v) ? v.map(ser) :
    Object.fromEntries(Object.keys(v).sort().map(k => [k, ser(v[k])]));

/** The pages: their builds, form, version, title and elements */
const PAGES = {};
for(const [name, debug] of [["index.html", false], ["debug.html", true]])
{
    const html = fs.readFileSync(path.join(root, name), "utf8");
    const version = /id="version"[^>]*>([^<]*)</.exec(html);
    PAGES[name] = {
        debug,
        query_append: version ? "?" + version[1] : "",
        title: /<title>([^<]*)<\/title>/.exec(html)[1],
        ids: new Set(Array.from(html.matchAll(/id="([^"]+)"/g), m => m[1])),
        // (a select's options: a value it lacks makes its value "")
        selects: new Map(Array.from(html.matchAll(/<select id="([^"]+)">([\s\S]*?)<\/select>/g),
            m => [m[1], new Set(Array.from(m[2].matchAll(/<option value="([^"]*)"/g), o => o[1]))])),
        // (debug.html on localhost: the local relay, main.js's onload)
        form: Object.assign(clone(DEFAULT_FORM), debug ? { relay_url: "ws://localhost:8080/" } : {}),
    };
}

/** The form's fields that the recorder reads */
const FIELDS = ["memory_size", "vga_memory_size", "cpu_type", "machine_type", "acpi"];

/** A form case's steps on DEFAULT_FORM, as the page's fields hold them; undefined when the page lacks a field */
function fill_form(page, steps)
{
    const form = clone(page.form);
    for(const [what, id, value] of steps)
    {
        // (the empty disks' fields appear when their links are clicked)
        const toggled = id.endsWith("_empty_size") && steps.some(([w, i]) => w === "click" && i === id.replace("_empty_size", "_toggle_empty_disk"));
        if(!page.ids.has(id) && !toggled) return { missing: id };
        const disk = /^(hda|hdb|fda|fdb)_(url|disk_option|toggle_empty_disk|empty_size)$/.exec(id);
        if(what === "click")
        {
            // (an empty disk's default size: 100 MB, a 1.44 MB floppy)
            form.empty_sizes[disk[1]] = disk[1].startsWith("hd") ? 100 : 2880 * 512;
        }
        else if(disk && disk[2] === "url") form.urls[disk[1]] = value;
        else if(disk && disk[2] === "disk_option") form.disk_options[disk[1]] = value;
        else if(disk && disk[2] === "empty_size") form.empty_sizes[disk[1]] = +value;
        else form[id] = page.selects.has(id) && !page.selects.get(id).has(value) ? "" : value;
    }
    return { form };
}

/** A start as main.js makes it: the record the page would have */
function start(page, profile, query_args, form, location_search)
{
    const location_args = new URLSearchParams(location_search);
    const result = start_settings(profile, query_args, form, { location_args, origin: "http://ORIGIN", debug: page.debug, graphics_proxy: false });
    const fields = Object.fromEntries(FIELDS.filter(id => page.ids.has(id)).map(id => [id, form[id]]));
    if(result.error)
    {
        return { fields, kind: "alert", text: result.error };
    }
    for(const id of FIELDS)
    {
        const value = result.updates[id];
        if(value === undefined || !(id in fields)) continue;
        fields[id] = page.selects.has(id) && !page.selects.get(id).has(value) ? "" : value;
    }
    const options = settings_to_options(result.settings, {
        cpu_worker: result.cpu_worker, debug: page.debug, query_append: page.query_append, graphics_proxy: false, screen_container: SCREEN,
    });
    const title = result.title || profile?.name;
    return {
        fields,
        kind: "options",
        options: ser(options),
        reset: profile?.state && page.ids.has("reset") ? "none" : "",
        search: query_args ? location_search : format_query_args(result.new_query_args),
        title: title ? title + " - v86" + (page.debug ? " - debug" : "") : page.title,
    };
}

const made = {};
// (the modules' notes, as "More than 2048 MB of memory: selecting the x86_64 CPU")
const log = console.log;
console.log = () => {};
for(const key of Object.keys(recorded))
{
    const [page_name, kind, ...rest] = key.split(" ");
    const page = PAGES[page_name];
    if(kind === "form")
    {
        const name = rest.join(" ");
        const steps = FORM_CASES.find(([n]) => n === name)[1];
        const filled = fill_form(page, steps);
        made[key] = filled.missing ? { id: filled.missing, kind: "missing" } : start(page, null, null, filled.form, "");
        continue;
    }
    // (main.js's onload: custom with an image)
    const search = kind;
    const query_args = new URLSearchParams(search);
    const id = query_args.get("profile");
    if(id === "custom" && ["hda.url", "cdrom.url", "fda.url"].some(name => query_args.has(name)))
    {
        made[key] = start(page, null, query_args, clone(page.form), search);
    }
    else
    {
        made[key] = { kind: "no start" };
    }
}

console.log = log;

const differences = compare_records(recorded, made);
for(const line of differences.slice(0, 50)) console.log(line);
console.log(Object.keys(made).length + " starts made by the modules: " +
    (differences.length ? "FAIL, " + differences.length + " differences from " + record_file : "PASS, the same as the pages recorded"));
process.exitCode = differences.length ? 1 : 0;
                                                                                                                                                                                                                                                          source/v64/tests/app/store_test.html                                                                0000644 0000000 0000000 00000026620 00000000000 014675  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: the library</title>
<!-- The VM manager's library (docs/vm-manager-plan.md U1, src/app/vm_store.js):
     configurations stored, read back after the page is reloaded, exported,
     imported (a new id on a collision, into another library with their own),
     a file's handle kept, a configuration deleted with its handles.
     node tests/app/browser_runner.mjs tests/app/store_test.html -->
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { VMStore, export_config, import_config, export_file_name, files_to_choose } from "../../src/app/vm_store.js";
import { new_config, VERSION } from "../../src/app/vm_config.js";
import { machine_digest } from "../../src/app/vm_state.js";
import { PRESETS, preset_config } from "../../src/app/guest_presets.js";

const DB = "v86-vm-manager-test", DB2 = "v86-vm-manager-test-imported";
const phase = new URLSearchParams(location.search).get("phase") || "1";
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };

/** The same value: plain data, any order of keys */
function canonical(value)
{
    if(Array.isArray(value)) return value.map(canonical);
    if(value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])]));
    return value;
}
function check(condition, what)
{
    if(!condition) throw new Error(what);
}
function same(a, b, what)
{
    const x = JSON.stringify(canonical(a)), y = JSON.stringify(canonical(b));
    if(x !== y) throw new Error(what + ": differs\n" + x.slice(0, 600) + "\n" + y.slice(0, 600));
}
/** The next phase, after a reload: this phase's lines kept */
function next(phase)
{
    sessionStorage.setItem("lines", JSON.stringify(JSON.parse(sessionStorage.getItem("lines") || "[]").concat(lines)));
    location.search = "?phase=" + phase;
}
const by_name = list => list.slice().sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
const remove_database = name => new Promise(resolve =>
{
    const request = globalThis.indexedDB.deleteDatabase(name);
    request.onsuccess = request.onerror = request.onblocked = () => resolve();
});

async function phase1()
{
    sessionStorage.removeItem("lines");
    await remove_database(DB);
    await remove_database(DB2);
    const store = await VMStore.open(DB);
    // (a file's handle: a file in this origin's private file system, a FileSystemFileHandle as a picked file's)
    const opfs = await navigator.storage.getDirectory();
    const handle = await opfs.getFileHandle("vm-store-test.img", { create: true });
    const writable = await handle.createWritable();
    await writable.write(new Uint8Array([1, 2, 3, 4]));
    await writable.close();
    const handle_id = await store.put_handle(handle);

    const stored = [];
    for(const p of PRESETS)
    {
        stored.push(await store.put(preset_config(p)));
    }
    const custom = new_config({ name: "With a file", notes: "notes ✓ 中文" });
    custom.disks = [{ slot: "hda", image: { kind: "file", name: "vm-store-test.img", size: 4, last_modified: (await handle.getFile()).lastModified,
        handle: handle_id }, disk_option: "read_only", disk_error: "stop" }];
    custom.cpu.cores = 2;
    custom.machine.acpi = true;
    stored.push(await store.put(custom));
    log("stored " + stored.length + " configurations and a file's handle");

    let refused;
    try
    {
        await store.put(Object.assign(new_config(), { name: "" }));
    }
    catch(e)
    {
        refused = e;
    }
    check(refused && refused.problems && refused.problems[0].path === "name", "a configuration without a name is refused");
    log("refused a configuration without a name: " + refused.message.split("\n")[1]);

    // preferences (U3: the disk service)
    check(await store.get_pref("disk_service") === undefined, "no preference yet");
    await store.put_pref("disk_service", { url: "http://127.0.0.1:8471/", token: "t" });

    // a library of version 1 (vms, handles; no prefs) opens as version 2, its configurations kept
    const OLD = "v86-vm-manager-test-v1";
    await remove_database(OLD);
    await new Promise((resolve, reject) =>
    {
        const request = globalThis.indexedDB.open(OLD, 1);
        request.onupgradeneeded = () =>
        {
            request.result.createObjectStore("vms", { keyPath: "id" }).put(stored[0]);
            request.result.createObjectStore("handles");
        };
        request.onsuccess = () => { request.result.close(); resolve(); };
        request.onerror = () => reject(request.error);
    });
    const upgraded = await VMStore.open(OLD);
    same(await upgraded.list(), [stored[0]], "the version 1 library's configuration");
    await upgraded.put_pref("x", 1);
    check(await upgraded.get_pref("x") === 1, "the upgraded library's preferences");
    upgraded.close();
    await remove_database(OLD);
    log("a version 1 library opens as version 2, its configuration kept, with preferences");

    // a suspended machine of configuration version 2 (its sound "none": a
    // muted Sound Blaster): migrated, it resumes without "the settings
    // changed" (its digest is the new form's), stored in the new form
    {
        const raw = Object.assign(JSON.parse(JSON.stringify(stored[0])), { id: "suspended-v2", version: 2, sound: { device: "none" } });
        delete raw.sound.mute;
        raw.suspended = { size: 1, time: "2026-10-26T00:00:00.000Z", digest: await machine_digest(raw) };
        const changed = Object.assign(JSON.parse(JSON.stringify(raw)), { id: "changed-v2" });
        changed.memory = { mb: raw.memory.mb + 64 };
        const transaction = store.db.transaction("vms", "readwrite");
        transaction.objectStore("vms").put(raw);
        transaction.objectStore("vms").put(changed);
        await new Promise(resolve => transaction.oncomplete = resolve);
        const migrated = await store.get("suspended-v2");
        check(migrated.version === VERSION && migrated.sound.device === "sb16" && migrated.sound.mute === true, "the muted Sound Blaster");
        check(migrated.suspended.digest === await machine_digest(migrated), "the digest of the migrated configuration");
        const kept = await new Promise(resolve => { const r = store.db.transaction("vms").objectStore("vms").get("suspended-v2"); r.onsuccess = () => resolve(r.result); });
        check(kept.version === VERSION, "stored in the new form");
        const other = await store.get("changed-v2");
        check(other.suspended.digest !== await machine_digest(other), "a digest that was already wrong stays wrong (the settings did change)");
        await store.delete("suspended-v2");
        await store.delete("changed-v2");
        log("a suspended machine of version 2 migrates with its digest; a changed one still says so");
    }

    sessionStorage.setItem("stored", JSON.stringify(stored));
    sessionStorage.setItem("handle_id", handle_id);
    store.close();
    next(2);
}

async function phase2()
{
    const store = await VMStore.open(DB);
    const stored = JSON.parse(sessionStorage.getItem("stored"));
    const listed = await store.list();
    same(listed, by_name(stored), "the library after the reload");
    for(const config of stored)
    {
        same(await store.get(config.id), config, "get " + config.name);
    }
    log("after the reload: " + listed.length + " configurations, each field the same");

    const handle = await store.get_handle(sessionStorage.getItem("handle_id"));
    check(handle && handle.kind === "file", "the handle after the reload");
    const bytes = new Uint8Array(await (await handle.getFile()).arrayBuffer());
    same(Array.from(bytes), [1, 2, 3, 4], "the handle's file");
    log("the file's handle after the reload: " + handle.name + ", its 4 bytes");
    same(await store.get_pref("disk_service"), { url: "http://127.0.0.1:8471/", token: "t" }, "the preference after the reload");
    await store.put_pref("disk_service", undefined);
    check(await store.get_pref("disk_service") === undefined, "a preference removed");
    log("a preference after the reload, and removed");

    // export, and import into the same library: a new id; the file's handle stays behind
    const ids = new Set(listed.map(c => c.id));
    const texts = [];
    for(const config of listed)
    {
        const text = export_config(config);
        texts.push(text);
        const imported = import_config(text, ids);
        check(imported.id !== config.id, "an import into the same library gets a new id");
        const expected = JSON.parse(JSON.stringify(config));
        for(const disk of expected.disks) if(disk.image.kind === "file") delete disk.image.handle;
        expected.id = imported.id;
        same(imported, expected, "export and import of " + config.name);
    }
    const custom = listed.find(c => c.name === "With a file");
    check(export_file_name(custom) === "With a file.v86vm.json", "the export's file name");
    check(files_to_choose(import_config(export_config(custom))).length === 1, "an imported file needs to be chosen again");
    check(files_to_choose(custom).length === 0, "a stored file with a handle does not");
    log("exported and imported " + texts.length + ": the same fields, a new id, the file to be chosen again");

    let bad;
    try { import_config("{ not json"); } catch(e) { bad = e; }
    check(bad && /not JSON/.test(bad.message), "a file that is not JSON");
    bad = undefined;
    try { import_config(JSON.stringify({ format: "v86-vm", version: 1, name: "x", cpu: { cores: 99 } })); } catch(e) { bad = e; }
    check(bad && bad.problems.some(p => p.path === "cpu.cores"), "an imported configuration is checked");
    log("refused an import that is not JSON, and one with 99 cores");

    // into another library: the ids kept
    const other = await VMStore.open(DB2);
    const imported = [];
    for(const text of texts) imported.push(await other.put(import_config(text, new Set((await other.list()).map(c => c.id)))));
    for(const [i, config] of imported.entries()) check(config.id === listed[i].id, "an import into another library keeps its id");
    other.close();
    sessionStorage.setItem("imported", JSON.stringify(imported));

    // delete: the configuration and its file's handle
    await store.delete(custom.id);
    check(await store.get(custom.id) === undefined, "deleted");
    check(await store.get_handle(sessionStorage.getItem("handle_id")) === undefined, "the deleted configuration's handle");
    check((await store.list()).length === listed.length - 1, "the others stay");
    log("deleted the configuration with the file, and its handle");
    store.close();
    next(3);
}

async function phase3()
{
    const other = await VMStore.open(DB2);
    same(await other.list(), by_name(JSON.parse(sessionStorage.getItem("imported"))), "the other library after the reload");
    other.close();
    const store = await VMStore.open(DB);
    check((await store.list()).length === JSON.parse(sessionStorage.getItem("stored")).length - 1, "the deletion after the reload");
    store.close();
    log("after another reload: the imported library the same, the deletion kept");
    await remove_database(DB);
    await remove_database(DB2);
    document.getElementById("result").textContent = "PASS\n" + JSON.parse(sessionStorage.getItem("lines")).concat(lines).join("\n");
}

const run = { "1": phase1, "2": phase2, "3": phase3 }[phase];
run().catch(e =>
{
    document.getElementById("result").textContent = "FAIL (phase " + phase + "): " + (e.stack || e.message);
});
</script>
                                                                                                                source/v64/tests/app/suspend_test.html                                                              0000644 0000000 0000000 00000020633 00000000000 015220  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: suspend and resume</title>
<!-- The VM manager's suspended machines and one tab per machine (docs/vm-manager-plan.md U5), MS-DOS in frames ("tabs"):
     a second tab of a running machine refused, the library shows it running; Suspend (the browser asked once to keep
     the storage), the tab closed, the library shows it suspended; opened again it resumes, the guest's screen as it was,
     and goes on, the state file used up; settings changed after suspending: asked, "Discard" starts afresh; only the
     notes changed: resumed without asking; not enough space: refused, said why.
     node tests/app/browser_runner.mjs tests/app/suspend_test.html -->
<style>iframe { width: 1000px; height: 650px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
import { VMStore } from "../../src/app/vm_store.js";
import { new_config } from "../../src/app/vm_config.js";
import { read_state } from "../../src/app/vm_state.js";

const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout = 30000)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(100);
    }
}
function check(condition, what) { if(!condition) throw new Error(what); }

async function open_tab(url)
{
    const frame = document.createElement("iframe");
    frame.src = url;
    document.body.append(frame);
    await new Promise(resolve => frame.onload = resolve);
    return frame;
}
/** a console tab of the machine, its emulator once its prompt is there (or its notice when it does not start) */
async function console_tab(id, { prompt = true } = {})
{
    const frame = await open_tab("/index.html?vm=" + id);
    const w = frame.contentWindow, d = frame.contentDocument;
    const $ = s => d.querySelector(s);
    const menu = async (menu_id, item_id) => { $("#" + menu_id).click(); (await until(() => $("#" + item_id), item_id)).click(); };
    const emulator = prompt ? await until(() => w.v86_console?.emulator, "the console's emulator", 60000) : null;
    return { frame, w, d, $, menu, emulator };
}
const type = async (emulator, text) => { await emulator.keyboard_send_text(text + "\n", 20); };
const screen_has = (emulator, text, timeout = 60000) => emulator.wait_until_vga_screen_contains(text, { timeout_msec: timeout });
// MS-DOS's prompt once AUTOEXEC.BAT is done (its last program's line, then the
// prompt at the bottom): the batch file's commands show "C:\>" before, and keys
// typed while its programs load overflow the BIOS's buffer of 15
const DOS_PROMPT = [/MSCD001 unit 0$/, "", /^C:\\>$/];

async function main()
{
    const store = await VMStore.open();
    const config = await store.put(Object.assign(new_config({ name: "DOS to suspend" }), {
        disks: [{ slot: "hda", image: { kind: "url", url: "images/msdos622.img", async: true }, disk_option: "read_only", disk_error: "stop" }],
    }));
    const id = config.id;

    // a running machine: a second tab is refused, the library shows it running
    const a = await console_tab(id);
    check(await screen_has(a.emulator, DOS_PROMPT, 120000), "MS-DOS's prompt");
    await type(a.emulator, "echo BEFORE-SUSPEND");
    check(await screen_has(a.emulator, "BEFORE-SUSPEND"), "the text before suspending");
    const b = await console_tab(id, { prompt: false });
    const refused = await until(() => b.$(".console-notice p.error")?.textContent, "the second tab's refusal");
    check(/runs in another tab/.test(refused) && !b.w.v86_console, "the second tab: " + refused);
    b.frame.remove();
    const library = await open_tab("/index.html");
    const state_of = () => library.contentDocument.querySelector(".vm-list li[data-id='" + id + "'] .vm-state")?.textContent;
    await until(() => state_of() === "Running in another tab", "the library: running");
    log("a second tab refused (\"" + refused.slice(0, 60) + "…\"); the library: Running in another tab");

    // suspend: persistent storage asked once; the tab closed; the library: suspended
    let persist_calls = 0;
    a.w.navigator.storage.persist = async () => { persist_calls++; return true; };
    await a.menu("menu_power", "menu_suspend");
    await until(() => /Suspended/.test(a.$(".console-status").textContent), "suspended", 120000);
    const file = await read_state(id);
    const suspended = (await store.get(id)).suspended;
    check(file && file.size > 1 << 20 && suspended && suspended.size === file.size && /^[0-9a-f]{64}$/.test(suspended.digest), "the state: " + JSON.stringify(suspended));
    check(persist_calls === 1 && await store.get_pref("persist_asked") === true, "persist() asked once: " + persist_calls);
    a.frame.remove();
    library.contentWindow.dispatchEvent(new Event("focus"));
    await until(() => state_of() === "Suspended", "the library: suspended");
    check(library.contentDocument.querySelector("#power_on").textContent === "Resume" && library.contentDocument.querySelector("#discard_state"),
        "the library's Resume and Discard");
    log("Suspend: " + file.size + " bytes in v86/states/, persist() asked once, the tab closed; the library: Suspended, Resume");

    // opened again: resumed, the screen as it was, the guest goes on; the state file used up
    const c = await console_tab(id);
    check(await screen_has(c.emulator, "BEFORE-SUSPEND", 60000), "the resumed screen");
    await type(c.emulator, "echo AFTER-RESUME");
    check(await screen_has(c.emulator, "AFTER-RESUME"), "the guest goes on after resuming");
    await until(async () => !(await read_state(id)) && !(await store.get(id)).suspended, "the state used up");
    log("Resume: the screen as it was (BEFORE-SUSPEND), the guest goes on (AFTER-RESUME), the state file used up");

    // not enough space: refused, said why
    c.w.navigator.storage.estimate = async () => ({ quota: 64 << 20, usage: 60 << 20 });
    await c.menu("menu_power", "menu_suspend");
    const too_small = await until(() => c.$("dialog[open]"), "the space dialog");
    check(/Not enough space/.test(too_small.textContent), "the space dialog: " + too_small.textContent);
    Array.from(too_small.querySelectorAll("button")).find(x => x.textContent === "OK").click();
    check(c.emulator.is_running() && !(await read_state(id)), "still running, no state");
    delete c.w.navigator.storage.estimate;
    log("not enough space: \"" + too_small.querySelector("p, .dialog-body").textContent.slice(0, 70) + "…\", still running");

    // settings changed after suspending: asked; Discard starts afresh
    await c.menu("menu_power", "menu_suspend");
    await until(() => /Suspended/.test(c.$(".console-status").textContent), "suspended again", 120000);
    c.frame.remove();
    const changed = await store.get(id);
    changed.memory.mb = 64;
    await store.put(changed);
    const d = await console_tab(id, { prompt: false });
    (await until(() => d.$("#resume_discard"), "the question about the changed settings")).click();
    const fresh = await until(() => d.w.v86_console?.emulator, "the fresh machine", 60000);
    check(await screen_has(fresh, "Starting MS-DOS", 120000), "a fresh boot");
    check(!(await read_state(id)) && !(await store.get(id)).suspended, "the state discarded");
    log("settings changed after suspending: asked; Discard: a fresh boot, the state gone");

    // only the notes changed: resumed without asking
    check(await screen_has(fresh, DOS_PROMPT, 120000), "the prompt");
    await d.menu("menu_power", "menu_suspend");
    await until(() => /Suspended/.test(d.$(".console-status").textContent), "suspended a third time", 120000);
    d.frame.remove();
    await store.put(Object.assign(await store.get(id), { notes: "notes changed", name: "DOS renamed" }));
    const e = await console_tab(id);
    check(!e.$("#resume_anyway"), "no question for the notes and the name");
    await until(async () => !(await read_state(id)), "resumed (the state used up)", 60000);
    log("only the name and notes changed: resumed without asking");
    store.close();
}

main().then(() =>
{
    document.getElementById("result").textContent = "PASS\n" + lines.join("\n");
}, e =>
{
    document.getElementById("result").textContent = "FAIL: " + (e.stack || e.message) + "\n" + lines.join("\n");
});
</script>
                                                                                                     source/v64/tests/app/vm_config.mjs                                                                  0000644 0000000 0000000 00000107555 00000000000 014305  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The VM manager's configuration (src/app/vm_config.js, docs/vm-manager-plan.md
// U1): the defaults, the migration, every check of validate_config, and
// config_to_options: each of the old page's
// profiles as a configuration gives the options the old page gives it
// (?profile=<id>), and the configuration's own fields reach the options.
//   node tests/app/vm_config.mjs

import assert from "node:assert/strict";
import { DEFAULT_FORM, settings_to_options } from "../../src/browser/vm_options.js";
import { start_settings } from "../../src/browser/query_compat.js";
import { FORMAT, VERSION, new_config, with_defaults, migrate, validate_config, check_config, config_to_options, uefi_vars_template } from "../../src/app/vm_config.js";
import { PRESETS, preset_config } from "../../src/app/guest_presets.js";

let passed = 0;
function test(name, fn)
{
    fn();
    passed++;
    console.log("ok - " + name);
}

const ENV = { debug: false, query_append: "?v", graphics_proxy: false, screen_container: "screen", file: image => new Blob([image.name]) };
const log = console.log;

/**
 * The options as they behave: undefined and false the same (absent) except
 * for the options whose default is true; ArrayBuffers by their size
 */
function behaviour(value)
{
    const TRUE_BY_DEFAULT = ["cpu_worker", "ir_tier0", "x87_fast_math", "x87_jit_cache", "autostart"];
    if(value instanceof ArrayBuffer) return { ArrayBuffer: value.byteLength };
    if(Array.isArray(value)) return value.map(behaviour);
    if(value && typeof value === "object")
    {
        return Object.fromEntries(Object.keys(value).sort()
            .filter(k => value[k] !== undefined && (value[k] !== false || TRUE_BY_DEFAULT.includes(k)))
            .map(k => [k, behaviour(value[k])]));
    }
    return value;
}

test("the defaults: a valid configuration, the old page's machine before its form is changed", () =>
{
    const config = new_config();
    assert.equal(config.format, FORMAT);
    assert.equal(config.version, VERSION);
    assert.match(config.id, /^[0-9a-f-]{36}$/);
    assert.deepEqual(validate_config(config), []);
    assert.deepEqual(check_config(config), []);
    // (the old page's start from the form without changes: start_settings with DEFAULT_FORM)
    console.log = () => {};
    const start = start_settings(null, null, DEFAULT_FORM, { location_args: new URLSearchParams(), origin: "", debug: false, graphics_proxy: false });
    console.log = log;
    assert.deepEqual(behaviour(config_to_options(config, ENV)), behaviour(settings_to_options(start.settings, Object.assign({ cpu_worker: start.cpu_worker }, ENV))));
});

test("JSON and back: the same configuration", () =>
{
    for(const p of PRESETS)
    {
        const config = preset_config(p, { name: p.name, notes: "notes ✓ 中文" });
        assert.deepEqual(migrate(JSON.parse(JSON.stringify(config))), config, p.id);
    }
});

test("migrate: not a configuration, a bad or newer version", () =>
{
    assert.throws(() => migrate(null), /not a v86 virtual machine/);
    assert.throws(() => migrate({ format: "other", version: 1 }), /not a v86 virtual machine/);
    assert.throws(() => migrate({ format: FORMAT, version: 0 }), /format version 0 is not valid/);
    assert.throws(() => migrate({ format: FORMAT, version: "1" }), /format version "1" is not valid/);
    assert.throws(() => migrate({ format: FORMAT, version: VERSION + 1 }), /newer v86/);
});

test("migrate: missing fields get their defaults, the given ones stay", () =>
{
    const config = migrate({ format: FORMAT, version: 1, id: "x", name: "Mine", memory: { mb: 512 }, cpu: { cores: 2 }, machine: { acpi: true } });
    assert.equal(config.name, "Mine");
    assert.equal(config.memory.mb, 512);
    assert.equal(config.cpu.cores, 2);
    assert.equal(config.cpu.type, "x86");
    assert.equal(config.machine.type, "i440fx");
    assert.deepEqual(config.network, [{ device: "ne2k", backend: "relay", relay_url: "wss://relay.widgetry.org/", mtu: 1500, mac_address_translation: false }]);
    assert.deepEqual(validate_config(config), []);
    assert.deepEqual(with_defaults(config), config, "with_defaults keeps a whole configuration");
});

test("migrate: version 1's display.vulkan (a boolean) names Venus", () =>
{
    const venus = migrate({ format: FORMAT, version: 1, id: "x", display: { adapter: "virtio_gpu", proxy: true, vulkan: true } });
    assert.equal(venus.version, VERSION);
    assert.equal(venus.display.vulkan, "venus");
    assert.equal(migrate({ format: FORMAT, version: 1, id: "y", display: { vulkan: false } }).display.vulkan, "none");
    assert.equal(migrate({ format: FORMAT, version: 1, id: "z" }).display.vulkan, "none");
});

test("migrate: version 2's PC sound \"none\" (a muted Sound Blaster) stays a muted Sound Blaster", () =>
{
    const pc = migrate({ format: FORMAT, version: 2, id: "x", sound: { device: "none" } });
    assert.equal(pc.version, VERSION);
    assert.deepEqual(pc.sound, { device: "sb16", mute: true });
    assert.deepEqual(migrate({ format: FORMAT, version: 2, id: "y", sound: { device: "sb16" } }).sound, { device: "sb16", mute: false });
    const virt = migrate({ format: FORMAT, version: 2, id: "z", cpu: { type: "arm64" }, machine: { type: "virt" }, display: { adapter: "virtio_gpu" },
        network: [{ device: "virtio" }], sound: { device: "none" } });
    assert.deepEqual(virt.sound, { device: "none", mute: false }, "the virt machine's none was no device");
    assert.deepEqual(validate_config(pc), []);
});

test("migrate: version 3 has no USB (usb null); USB on a PC goes to the usb option", () =>
{
    const old = migrate({ format: FORMAT, version: 3, id: "x" });
    assert.equal(old.version, VERSION);
    assert.equal(old.usb, null);
    assert.equal(config_to_options(old, ENV).usb, undefined);
    const c = new_config();
    c.usb = { controller: "uhci", tablet: true };
    assert.deepEqual(validate_config(c), []);
    assert.deepEqual(check_config(c), []);
    assert.deepEqual(config_to_options(c, ENV).usb, { controller: "uhci", tablet: true });
});

test("USB disks: a port each (with the tablet's; UHCI two, EHCI six), defaults filled in; usb.mass_storage with their images, policies and write protection", () =>
{
    const c = new_config();
    c.usb = { controller: "uhci", tablet: true, disks: [{ id: "stick", image: { kind: "url", url: "images/stick.img", size: 1 << 20, async: true } }] };
    const normal = migrate(JSON.parse(JSON.stringify(c)));
    assert.deepEqual(normal.usb.disks[0], { id: "stick", image: c.usb.disks[0].image, disk_option: "read_only", disk_error: "stop", write_protected: false });
    assert.deepEqual(validate_config(normal), []);
    assert.deepEqual(check_config(normal), []);
    assert.deepEqual(config_to_options(normal, ENV).usb, { controller: "uhci", tablet: true,
        mass_storage: [{ id: "stick", image: { url: "images/stick.img", size: 1 << 20, async: true }, read_only: false }] });
    normal.usb.disks[0].write_protected = true;
    normal.usb.disks[0].disk_error = "report";
    const o = config_to_options(normal, ENV).usb.mass_storage[0];
    assert.equal(o.read_only, true);
    assert.equal(o.image.disk_error, "report");
    // EHCI: six ports, the tablet's and five disks'
    normal.usb.controller = "ehci";
    normal.usb.disks = ["a", "b", "c", "d", "e"].map(usb_disk);
    assert.deepEqual(validate_config(normal), []);
    assert.equal(config_to_options(normal, ENV).usb.controller, "ehci");
    normal.usb.disks.push(usb_disk("f"));
    assert.deepEqual(validate_config(normal).map(p => p.path), ["usb.disks"]);
    // (an old configuration's usb without disks has none)
    assert.deepEqual(migrate({ format: FORMAT, version: VERSION, id: "x", usb: { controller: "uhci", tablet: true } }).usb.disks, []);
});

test("the sound card: audio_device for the PC machines; none keeps the speaker, mute silences the page", () =>
{
    const c = new_config();
    assert.equal(config_to_options(c, ENV).audio_device, undefined, "the library's default, the Sound Blaster");
    c.sound = { device: "none", mute: false };
    let o = config_to_options(c, ENV);
    assert.equal(o.audio_device, "none");
    assert.ok(!o.disable_speaker, "no sound card, the PC speaker still plays");
    c.sound = { device: "hd_audio", mute: false };
    o = config_to_options(c, ENV);
    assert.equal(o.audio_device, "hd_audio");
    assert.deepEqual(check_config(c), []);
    c.sound.mute = true;
    assert.equal(config_to_options(c, ENV).disable_speaker, true);
});

/** Every check: a change of a valid configuration and the field it is reported on */
const RULES = [
    ["format", c => { c.format = "x"; }, "format"],
    ["version", c => { c.version = 1; }, "version"],
    ["no id", c => { c.id = ""; }, "id"],
    ["no name", c => { c.name = "  "; }, "name"],
    ["a long name", c => { c.name = "x".repeat(201); }, "name"],
    ["notes", c => { c.notes = 1; }, "notes"],
    ["cpu type", c => { c.cpu.type = "z80"; }, "cpu.type"],
    ["machine type", c => { c.machine.type = "isa"; }, "machine.type"],
    ["arm64 on a PC", c => { c.cpu.type = "arm64"; }, "machine.type"],
    ["x86 on virt", c => { c.machine.type = "virt"; }, "machine.type"],
    ["no cores", c => { c.cpu.cores = 0; }, "cpu.cores"],
    ["9 cores", c => { c.cpu.cores = 9; c.machine.acpi = true; }, "cpu.cores"],
    ["parallel", c => { c.cpu.parallel = "yes"; }, "cpu.parallel"],
    ["jit", c => { c.cpu.jit = 1; }, "cpu.jit"],
    ["too little memory", c => { c.memory.mb = 8; }, "memory.mb"],
    ["too much memory", c => { c.memory.mb = 70000; c.cpu.type = "x86_64"; }, "memory.mb"],
    ["4 GB on x86", c => { c.memory.mb = 4096; }, "memory.mb"],
    ["acpi", c => { c.machine.acpi = "on"; }, "machine.acpi"],
    ["ACPI on virt", c => { c.cpu.type = "arm64"; c.machine.type = "virt"; c.machine.acpi = true; c.display.adapter = "none";
        c.network[0].device = "virtio"; c.sound.device = "none"; }, "machine.acpi"],
    ["Q35 without ACPI", c => { c.machine.type = "q35"; }, "machine.acpi"],
    ["two cores without ACPI", c => { c.cpu.cores = 2; }, "machine.acpi"],
    ["an HPET on i440FX", c => { c.machine.hpet = true; }, "machine.hpet"],
    ["an SMBus on i440FX", c => { c.machine.smbus = true; }, "machine.smbus"],
    ["root ports on i440FX", c => { c.machine.pcie_root_ports = 1; }, "machine.pcie_root_ports"],
    ["7 root ports", c => { c.machine.type = "q35"; c.machine.acpi = true; c.machine.pcie_root_ports = 7; }, "machine.pcie_root_ports"],
    ["a boot order", c => { c.machine.boot_order = 0x111; }, "machine.boot_order"],
    ["fastboot", c => { c.machine.fastboot = null; }, "machine.fastboot"],
    ["bootmenu", c => { c.machine.bootmenu = "x"; }, "machine.bootmenu"],
    ["a BIOS image", c => { c.machine.bios = { kind: "url", url: "" }; }, "machine.bios"],
    ["a BIOS on virt", c => { Object.assign(c, arm64()); c.machine.bios = { kind: "url", url: "b.bin" }; }, "machine.bios"],
    ["a firmware", c => { c.machine.firmware = "efi"; }, "machine.firmware"],
    ["UEFI on the x86 CPU", c => { c.machine.firmware = "uefi"; c.machine.acpi = true; }, "machine.firmware"],
    ["UEFI without ACPI", c => { c.cpu.type = "x86_64"; c.machine.firmware = "uefi"; }, "machine.firmware"],
    ["UEFI with a BIOS image", c => { c.cpu.type = "x86_64"; c.machine.acpi = true; c.machine.firmware = "uefi"; c.machine.bios = { kind: "url", url: "b.bin" }; },
        "machine.bios"],
    ["UEFI on virt", c => { Object.assign(c, arm64()); c.machine.firmware = "uefi"; }, "machine.firmware"],
    ["a UEFI variable store of a URL", c => { c.machine.uefi_vars = { kind: "url", url: "v.fd" }; }, "machine.uefi_vars"],
    ["Secure Boot with SeaBIOS", c => { c.machine.type = "q35"; c.machine.secure_boot = true; }, "machine.secure_boot"],
    ["Secure Boot on i440FX", c => { c.cpu.type = "x86_64"; c.machine.acpi = true; c.machine.firmware = "uefi"; c.machine.secure_boot = true; },
        "machine.secure_boot"],
    ["Secure Boot keys of no kind", c => { c.machine.secure_boot_keys = "mine"; }, "machine.secure_boot_keys"],
    ["a TPM without ACPI", c => { c.tpm = { state: null }; }, "tpm"],
    ["a TPM's state of a URL", c => { c.machine.acpi = true; c.tpm = { state: { kind: "url", url: "t.img" } }; }, "tpm.state"],
    ["a TPM on virt", c => { Object.assign(c, arm64()); c.tpm = { state: null }; }, "tpm"],
    ["a disk's slot", c => { c.disks = [disk({ slot: "hdc" })]; }, "disks.0.slot"],
    ["a slot twice", c => { c.disks = [disk(), disk()]; }, "disks.1.slot"],
    ["an image's kind", c => { c.disks = [disk({ image: { kind: "ftp" } })]; }, "disks.0.image"],
    ["a URL without a URL", c => { c.disks = [disk({ image: { kind: "url", url: "" } })]; }, "disks.0.image"],
    ["a directory's URL", c => { c.disks = [disk({ image: { kind: "url", url: "http://127.0.0.1:8471/" } })]; }, "disks.0.image"],
    ["a URL's size", c => { c.disks = [disk({ image: { kind: "url", url: "a.img", size: -1 } })]; }, "disks.0.image"],
    ["a file without a name", c => { c.disks = [disk({ image: { kind: "file", name: "", size: 1, last_modified: 0 } })]; }, "disks.0.image"],
    ["an empty disk's size", c => { c.disks = [disk({ image: { kind: "empty", size: 0 } })]; }, "disks.0.image"],
    ["an empty disk too large", c => { c.disks = [disk({ image: { kind: "empty", size: 2001 * 1024 * 1024 } })]; }, "disks.0.image"],
    ["a browser disk's path", c => { c.disks = [disk({ image: { kind: "browser", path: "../x.img", size: 512 } })]; }, "disks.0.image"],
    ["disk_option", c => { c.disks = [disk({ disk_option: "rw" })]; }, "disks.0.disk_option"],
    ["disk_error", c => { c.disks = [disk({ disk_error: "ignore" })]; }, "disks.0.disk_error"],
    ["read write of a file", c => { c.disks = [disk({ image: { kind: "file", name: "a.img", size: 512, last_modified: 0 }, disk_option: "read_write" })]; },
        "disks.0.disk_option"],
    ["read write of an empty disk", c => { c.disks = [disk({ image: { kind: "empty", size: 512 }, disk_option: "read_write" })]; }, "disks.0.disk_option"],
    ["an empty CD", c => { c.cdrom.image = { kind: "empty", size: 2048 }; }, "cdrom.image"],
    ["the CD's disk_error", c => { c.cdrom.disk_error = "x"; }, "cdrom.disk_error"],
    ["a floppy on virt", c => { Object.assign(c, arm64()); c.floppies = [{ slot: "fda", image: null, disk_option: "read_only" }]; }, "floppies.0"],
    ["a floppy's slot", c => { c.floppies = [{ slot: "fdc", image: null, disk_option: "read_only" }]; }, "floppies.0.slot"],
    ["a floppy slot twice", c => { c.floppies = [floppy(), floppy()]; }, "floppies.1.slot"],
    ["an empty floppy's size", c => { c.floppies = [floppy({ image: { kind: "empty", size: 1000 * 512 } })]; }, "floppies.0.image"],
    ["a floppy's disk_option", c => { c.floppies = [floppy({ disk_option: "x" })]; }, "floppies.0.disk_option"],
    ["a kernel's image", c => { c.kernel = kernel({ bzimage: { kind: "url" } }); }, "kernel.bzimage"],
    ["multiboot on virt", c => { Object.assign(c, arm64()); c.kernel = kernel({ multiboot: { kind: "url", url: "m.bin" } }); }, "kernel.multiboot"],
    ["a command line", c => { c.kernel = kernel({ cmdline: 1 }); }, "kernel.cmdline"],
    ["from_filesystem", c => { c.kernel = kernel({ from_filesystem: "yes" }); }, "kernel.from_filesystem"],
    ["a display adapter", c => { c.display.adapter = "cga"; }, "display.adapter"],
    ["VGA on virt", c => { Object.assign(c, arm64()); c.display.adapter = "bochs_vga"; }, "display.adapter"],
    ["video memory", c => { c.display.vram_mb = 12; }, "display.vram_mb"],
    ["512 MB of video memory", c => { c.display.vram_mb = 512; }, "display.vram_mb"],
    ["the state's video memory without a state", c => { c.display.vram_mb = null; }, "display.vram_mb"],
    ["the proxy", c => { c.display.proxy = 1; }, "display.proxy"],
    ["Vulkan", c => { c.display.vulkan = 1; }, "display.vulkan"],
    ["Vulkan of another kind", c => { c.display.adapter = "virtio_gpu"; c.display.proxy = true; c.display.vulkan = "virgl"; }, "display.vulkan"],
    ["Vulkan on Bochs VGA", c => { c.display.proxy = true; c.display.vulkan = "venus"; }, "display.vulkan"],
    ["Vulkan without the proxy", c => { c.display.adapter = "virtio_gpu"; c.display.vulkan = "gfxstream"; }, "display.vulkan"],
    ["5 displays", c => { c.display.adapter = "virtio_gpu"; c.display.displays = 5; }, "display.displays"],
    ["2 displays on Bochs VGA", c => { c.display.displays = 2; }, "display.displays"],
    ["two network cards", c => { c.network.push(c.network[0]); }, "network"],
    ["a network card", c => { c.network[0].device = "rtl8139"; }, "network.0.device"],
    ["ne2k on virt", c => { Object.assign(c, arm64()); c.network[0].device = "ne2k"; }, "network.0.device"],
    ["e1000 on virt", c => { Object.assign(c, arm64()); c.network[0].device = "e1000"; }, "network.0.device"],
    ["a backend", c => { c.network[0].backend = "slirp"; }, "network.0.backend"],
    ["a relay's URL", c => { c.network[0].relay_url = "http://relay"; }, "network.0.relay_url"],
    ["a wisp server's URL", c => { c.network[0].backend = "wisp"; c.network[0].relay_url = "wss://x/"; }, "network.0.relay_url"],
    ["a CORS proxy's URL", c => { c.network[0].backend = "fetch"; c.network[0].relay_url = "proxy"; }, "network.0.relay_url"],
    ["the MTU", c => { c.network[0].mtu = 67; }, "network.0.mtu"],
    ["MAC address translation", c => { c.network[0].mac_address_translation = "x"; }, "network.0.mac_address_translation"],
    ["a sound card", c => { c.sound.device = "gus"; }, "sound.device"],
    ["mute", c => { c.sound.mute = "yes"; }, "sound.mute"],
    ["HD Audio on virt", c => { Object.assign(c, arm64()); c.sound.device = "hd_audio"; }, "sound.device"],
    ["a USB controller", c => { c.usb = { controller: "ohci", tablet: true }; }, "usb.controller"],
    ["the tablet", c => { c.usb = { controller: "uhci", tablet: "yes" }; }, "usb.tablet"],
    ["USB on virt", c => { Object.assign(c, arm64()); c.usb = { controller: "uhci", tablet: true }; }, "usb.controller"],
    ["a USB disk's id", c => { c.usb = { controller: "uhci", tablet: false, disks: [usb_disk("a b")] }; }, "usb.disks.0.id"],
    ["a USB disk's id twice", c => { c.usb = { controller: "uhci", tablet: false, disks: [usb_disk("a"), usb_disk("a")] }; }, "usb.disks.1.id"],
    ["a USB disk named tablet", c => { c.usb = { controller: "uhci", tablet: false, disks: [usb_disk("tablet")] }; }, "usb.disks.0.id"],
    ["more USB disks than ports", c => { c.usb = { controller: "uhci", tablet: true, disks: [usb_disk("a"), usb_disk("b")] }; }, "usb.disks"],
    ["a chosen file written back as a USB disk", c => { c.usb = { controller: "uhci", tablet: false,
        disks: [Object.assign(usb_disk("a"), { image: { kind: "file", name: "x.img", size: 512 }, disk_option: "read_write" })] }; }, "usb.disks.0.disk_option"],
    ["a USB disk's write protection", c => { c.usb = { controller: "uhci", tablet: false, disks: [Object.assign(usb_disk("a"), { write_protected: 1 })] }; },
        "usb.disks.0.write_protected"],
    ["a Sound Blaster on virt", c => { Object.assign(c, arm64()); c.sound.device = "sb16"; }, "sound.device"],
    ["a UART", c => { c.serial = [{ port: 4, attach: "none" }]; }, "serial.0.port"],
    ["a UART twice", c => { c.serial = [{ port: 1, attach: "none" }, { port: 1, attach: "none" }]; }, "serial.1.port"],
    ["what a UART has", c => { c.serial = [{ port: 1, attach: "printer" }]; }, "serial.0.attach"],
    ["two modems", c => { c.serial = [{ port: 1, attach: "modem" }, { port: 2, attach: "modem" }]; }, "serial"],
    ["a modem on virt", c => { Object.assign(c, arm64()); c.serial = [{ port: 1, attach: "modem" }]; }, "serial.0.attach"],
    ["the file system's URL", c => { c.filesystem = { baseurl: 1 }; }, "filesystem.baseurl"],
    ["the file system's description", c => { c.filesystem = { basefs: "fs.json" }; }, "filesystem.basefs"],
    ["an empty state", c => { c.initial_state = { kind: "empty", size: 1 }; }, "initial_state"],
    ["virtio sound on a PC", c => { c.sound.device = "virtio"; }, "sound.device"],
    ["the virt section on a PC", c => { c.virt.vsock = true; }, "virt"],
    ["a transport", c => { Object.assign(c, arm64()); c.virt.transport = "isa"; }, "virt.transport"],
    ["input devices", c => { Object.assign(c, arm64()); c.virt.input = ["mouse"]; }, "virt.input"],
    ["console ports", c => { Object.assign(c, arm64()); c.virt.console_ports = 31; }, "virt.console_ports"],
    ["vsock", c => { Object.assign(c, arm64()); c.virt.vsock = 1; }, "virt.vsock"],
    ["an arm64 model on a PC", c => { c.cpu.profile = "generic-arm64-compat32"; }, "cpu.profile"],
    ["an unknown model", c => { Object.assign(c, arm64()); c.cpu.profile = "v3"; }, "cpu.profile"],
    ["a GPU slot without pci", c => { Object.assign(c, arm64()); c.virt.gpu_pci_slot = 2; }, "virt.gpu_pci_slot"],
    ["five virtio cards", c => { Object.assign(c, arm64()); c.network = Array(5).fill(c.network[0]); }, "network"],
    ["two cards served", c => { Object.assign(c, arm64()); c.network = [c.network[0], c.network[0]]; }, "network"],
    ["the CPU worker", c => { c.advanced.cpu_worker = "1"; }, "advanced.cpu_worker"],
    ["the mouse", c => { c.advanced.mouse_disabled = 0; }, "advanced.mouse_disabled"],
    ["cpuid_level", c => { c.advanced.cpuid_level = 0; }, "advanced.cpuid_level"],
    ["cpuid_level on virt", c => { Object.assign(c, arm64()); c.advanced.cpuid_level = 2; }, "advanced.cpuid_level"],
    ["Android on a PC", c => { c.android = android(); c.disks = [disk()]; }, "android"],
    ["Android's device", c => { Object.assign(c, arm64(), { android: android({ device: "pixel" }), disks: [disk()] }); }, "android.device"],
    ["Android's GPU mode", c => { Object.assign(c, arm64(), { android: android({ gpu_mode: "virgl" }), disks: [disk()] }); }, "android.gpu_mode"],
    ["Android's gfxstream with Venus", c => { Object.assign(c, arm64(), { android: android({ gpu_mode: "gfxstream" }), disks: [disk()] });
        Object.assign(c.display, { proxy: true, vulkan: "venus" }); }, "android.gpu_mode"],
    ["Android's Venus without Vulkan", c => { Object.assign(c, arm64(), { android: android({ gpu_mode: "venus" }), disks: [disk()] }); }, "android.gpu_mode"],
    ["Android's vendor ramdisk", c => { Object.assign(c, arm64(), { android: android({ vendor_ramdisk: "eng" }), disks: [disk()] }); }, "android.vendor_ramdisk"],
    ["Android's debug ramdisk not chosen", c => { Object.assign(c, arm64(), { android: android({ vendor_ramdisk: "debug" }), disks: [disk()] }); }, "android.debug_ramdisk"],
    ["Android's debug ramdisk's image", c => { Object.assign(c, arm64(), { android: android({ debug_ramdisk: { kind: "url", url: "" } }), disks: [disk()] }); },
        "android.debug_ramdisk"],
    ["Android's SELinux", c => { Object.assign(c, arm64(), { android: android({ selinux: "off" }), disks: [disk()] }); }, "android.selinux"],
    ["Android's GLES version", c => { Object.assign(c, arm64(), { android: android({ gles_version: "3.3" }), disks: [disk()] }); }, "android.gles_version"],
    ["Android with a kernel", c => { Object.assign(c, arm64(), { android: android(), disks: [disk()], kernel: kernel({ bzimage: { kind: "url", url: "Image" } }) }); },
        "kernel"],
    ["Android with a CD", c => { Object.assign(c, arm64(), { android: android(), disks: [disk()] }); c.cdrom.image = { kind: "url", url: "a.iso" }; }, "cdrom.image"],
];

function disk(fields) { return Object.assign({ slot: "hda", image: { kind: "url", url: "a.img" }, disk_option: "read_only", disk_error: "stop" }, fields); }
function floppy(fields) { return Object.assign({ slot: "fda", image: null, disk_option: "read_only" }, fields); }
function kernel(fields) { return Object.assign({ bzimage: null, initrd: null, cmdline: null, multiboot: null, from_filesystem: false }, fields); }
function android(fields) { return Object.assign({ device: "cf_arm64_only_phone", gpu_mode: "swiftshader", vendor_ramdisk: "release", debug_ramdisk: null, selinux: "enforcing", display: "device",
    gles_version: "3.1" }, fields); }
/** A USB disk of the configuration */
function usb_disk(id) { return { id, image: { kind: "empty", size: 1 << 20 }, disk_option: "read_only", disk_error: "stop", write_protected: false }; }
/** The sections of a valid arm64 machine */
function arm64()
{
    const c = new_config();
    c.cpu.type = "arm64";
    c.machine.type = "virt";
    c.display.adapter = "virtio_gpu";
    c.network[0].device = "virtio";
    c.sound.device = "none";
    return { cpu: c.cpu, machine: c.machine, display: c.display, network: c.network, sound: c.sound };
}

test("arm64's sections are valid", () => assert.deepEqual(validate_config(new_config(arm64())), []));

test("the PC cards: e1000 (a plugin) is valid on i440FX and Q35 and goes to net_device.type", () =>
{
    for(const machine of ["i440fx", "q35"])
    {
        const c = new_config();
        c.machine.type = machine;
        c.machine.acpi = machine === "q35";
        c.network[0].device = "e1000";
        assert.deepEqual(validate_config(c), [], machine);
        assert.deepEqual(check_config(c), [], machine);
        assert.equal(config_to_options(c, ENV).net_device.type, "e1000", machine);
    }
});

test("android: its defaults, a valid Android machine", () =>
{
    assert.equal(new_config().android, null);
    assert.deepEqual(new_config({ android: { gpu_mode: "swiftshader" } }).android,
        { device: "cf_arm64_only_phone", gpu_mode: "swiftshader", vendor_ramdisk: "release", debug_ramdisk: null, selinux: "enforcing", display: "device",
            gles_version: "3.1" });
    assert.deepEqual(validate_config(new_config(Object.assign(arm64(), { android: android(), disks: [disk()] }))), []);
});

test("android: the GLES version an emulator image's host announces, given only on the host's GPU", () =>
{
    const options = gpu_mode => config_to_options(new_config({ android: { device: "ranchu_25_armeabi_v7a", gpu_mode, gles_version: "3.2" } }), ENV).android;
    assert.equal(options("host").gles_version, "3.2");
    assert.equal(options("guest").gles_version, undefined);
});

test("a problem does not hide the others (only a bad CPU or machine type does)", () =>
{
    const config = new_config({ id: "", name: "" });
    config.cpu.cores = 99;
    config.display.vram_mb = 3;
    assert.deepEqual(validate_config(config).map(p => p.path), ["id", "name", "cpu.cores", "machine.acpi", "display.vram_mb"]);
});

test("every check reports its field (" + RULES.length + " rules)", () =>
{
    for(const [name, change, path] of RULES)
    {
        const config = new_config();
        change(config);
        const problems = validate_config(config);
        assert(problems.some(p => p.path === path), name + ": expected a problem at " + path + ", got " + JSON.stringify(problems));
    }
});

test("config_to_options: the configuration's fields", () =>
{
    const c = new_config({ name: "x" });
    c.machine.type = "q35";
    c.machine.acpi = true;
    c.machine.hpet = false;
    c.machine.pcie_root_ports = 2;
    c.machine.boot_order = 0x213;
    c.machine.fastboot = true;
    c.machine.bootmenu = true;
    c.machine.bios = { kind: "url", url: "bios/bochs-bios.bin" };
    c.cpu = { type: "x86_64", cores: 4, parallel: false, jit: false };
    c.memory.mb = 3000;
    c.disks = [disk({ image: { kind: "url", url: "http://127.0.0.1:8471/a.img", async: true }, disk_option: "read_write", disk_error: "report" }),
        disk({ slot: "hdb", image: { kind: "file", name: "b.img", size: 512, last_modified: 1 } })];
    c.cdrom.image = { kind: "browser", path: "v86/disks/cd.img", size: 2048 };
    c.floppies = [floppy({ image: { kind: "empty", size: 1474560 } })];
    c.kernel = kernel({ bzimage: { kind: "url", url: "k.bin", async: false }, cmdline: "quiet" });
    c.display = { adapter: "virtio_gpu", vram_mb: 32, proxy: true, vulkan: "venus", displays: 2 };
    c.network = [{ device: "virtio", backend: "fetch", relay_url: "https://cors.invalid/", mtu: 9000, mac_address_translation: true }];
    c.sound = { device: "hd_audio", mute: true };
    c.serial = [{ port: 0, attach: "terminal" }, { port: 2, attach: "modem" }];
    c.filesystem = { baseurl: "fs/" };
    c.advanced = { cpu_worker: false, ir_tier0: false, x87_fast_math: true, x87_jit_cache: false, cpuid_level: 7, mouse_disabled: false };
    assert.deepEqual(validate_config(c), []);
    const o = config_to_options(c, ENV);
    assert.equal(o.machine_type, "q35");
    assert.equal(o.acpi, true);
    assert.equal(o.hpet, false);
    assert.equal(o.smbus, false);
    assert.equal(o.pcie_root_ports, 2);
    assert.equal(o.boot_order, 0x213);
    assert.equal(o.fastboot, true);
    assert.equal(o.bootmenu, true);
    assert.deepEqual(o.bios, { url: "bios/bochs-bios.bin" });
    assert.deepEqual(o.vga_bios, { url: "bios/vgabios.bin" });
    assert.equal(o.cpu_type, "x86_64");
    assert.equal(o.cpu_cores, 4);
    assert.equal(o.parallel, false);
    assert.equal(o.disable_jit, true);
    assert.equal(o.experimental_smp_jit, false);
    assert.equal(o.memory_size, 2048 * 1024 * 1024);
    assert.equal(o.extended_memory_size, 952 * 1024 * 1024);
    assert.deepEqual(o.hda, { url: "http://127.0.0.1:8471/a.img", async: true, disk_option: "read_write", disk_error: "report" });
    assert(o.hdb.buffer instanceof Blob && o.hdb.buffer.size === 5, "a file's image is the picked File");
    assert.deepEqual(o.cdrom, { url: "opfs:v86/disks/cd.img", size: 2048 });
    assert.equal(o.fda.buffer.byteLength, 1474560);
    assert.deepEqual(o.bzimage, { url: "k.bin", async: false });
    assert.equal(o.cmdline, "quiet");
    assert.equal(o.graphics_adapter, "virtio_gpu");
    assert.equal(o.vram_size, 32 * 1024 * 1024);
    assert.deepEqual(o.graphics_adapter_test, { scanouts: 2, level: "venus" });
    assert.deepEqual(o.net_device, { type: "virtio", relay_url: "fetch", cors_proxy: "https://cors.invalid/", mtu: 9000 });
    assert.equal(o.mac_address_translation, true);
    assert.equal(o.disable_speaker, true);
    assert.equal(o.audio_device, "hd_audio");
    assert.deepEqual(o.modem, { uart: 2 });
    assert.deepEqual(o.filesystem, { baseurl: "fs/" });
    assert.equal(o.cpu_worker, false);
    assert.equal(o.ir_tier0, false);
    assert.equal(o.x87_fast_math, true);
    assert.equal(o.x87_jit_cache, false);
    assert.equal(o.cpuid_level, 7);
    // (the library refuses a browser disk in Node, U6: here, not on the page)
    const node = check_config(c);
    assert(node.length === 1 && node[0].path === "disks" && /not in Node/.test(node[0].message), JSON.stringify(node));
    c.cdrom.image = { kind: "url", url: "cd.iso", async: true };
    assert.deepEqual(check_config(c), []);
});

test("config_to_options: the backends, arm64, a file not chosen yet", () =>
{
    const relay = backend => { const c = new_config(); c.network[0].backend = backend[0]; c.network[0].relay_url = backend[1]; return config_to_options(c, ENV).net_device.relay_url; };
    assert.equal(relay(["none", ""]), "");
    assert.equal(relay(["inbrowser", ""]), "inbrowser");
    assert.equal(relay(["fetch", ""]), "fetch");
    assert.equal(relay(["wisp", "wisps://w.invalid/"]), "wisps://w.invalid/");
    const a = new_config(arm64());
    a.memory.mb = 2048;
    a.cdrom.image = { kind: "url", url: "alpine.iso" };
    a.disks = [disk()];
    const o = config_to_options(a, ENV);
    assert.equal(o.machine_type, "virt");
    assert.deepEqual(o.virtio_disks, [{ url: "alpine.iso", readonly: true }, { url: "a.img" }]);
    assert.deepEqual(o.virtio_input, ["keyboard", "tablet", "multitouch"]);
    assert.deepEqual(o.jit_switches, { a64_page: 1 });
    assert.equal(o.memory_size, 1792 * 1024 * 1024);
    assert.equal(o.extended_memory_size, 256 * 1024 * 1024);
    assert.equal(o.acpi, false);
    assert.equal(o.cpu_profile, undefined, "the CPU type's default model");
    assert.deepEqual(check_config(a), []);
    // (the model with 32-bit programs: docs/aarch32-plan.md Q7.1)
    a.cpu.profile = "generic-arm64-compat32";
    assert.equal(config_to_options(a, ENV).cpu_profile, "generic-arm64-compat32");
    assert.deepEqual(check_config(a), []);
    const f = new_config();
    f.disks = [disk({ image: { kind: "file", name: "c.img", size: 512, last_modified: 0 } })];
    assert.throws(() => config_to_options(f, Object.assign({}, ENV, { file: () => undefined })), /c\.img needs to be chosen again/);
});

test("UEFI: OVMF's images in place of the BIOS images; on i440FX with QEMU's layout; the library accepts both machines", () =>
{
    for(const type of ["i440fx", "q35"])
    {
        const c = new_config();
        c.cpu.type = "x86_64";
        c.machine.type = type;
        c.machine.acpi = true;
        c.machine.firmware = "uefi";
        assert.deepEqual(validate_config(c), []);
        assert.deepEqual(check_config(c), [], type);
        const o = config_to_options(c, ENV);
        assert.deepEqual(o.firmware, { type: "uefi", code: { url: "bios/ovmf-code.fd" }, vars: { url: "bios/ovmf-vars.fd" } });
        assert.equal(o.bios, undefined);
        assert.equal(o.vga_bios, undefined);
        assert.equal(o.qemu_compatible, type === "i440fx" ? true : undefined);
    }
    // (migrated: SeaBIOS, no variable store)
    const migrated = with_defaults({ format: FORMAT, version: VERSION, machine: { type: "i440fx" } }).machine;
    assert.equal(migrated.firmware, "seabios");
    assert.equal(migrated.uefi_vars, null);
    // the machine's variable store: its browser disk written back, with the CPU Worker; else the template
    const c = new_config();
    Object.assign(c.cpu, { type: "x86_64" });
    Object.assign(c.machine, { type: "q35", acpi: true, firmware: "uefi", uefi_vars: { kind: "browser", path: "v86/disks/vars.img", size: 540672 } });
    assert.deepEqual(validate_config(c), []);
    assert.deepEqual(config_to_options(c, ENV).firmware.vars, { url: "opfs:v86/disks/vars.img", size: 540672, disk_option: "read_write" });
    c.advanced.cpu_worker = false;
    assert.deepEqual(config_to_options(c, ENV).firmware.vars, { url: "bios/ovmf-vars.fd" });
});

test("Secure Boot: the Secure Boot firmware on Q35; a new store's keys Microsoft's or none; the library accepts it", () =>
{
    const c = new_config();
    c.cpu.type = "x86_64";
    Object.assign(c.machine, { type: "q35", acpi: true, firmware: "uefi", secure_boot: true });
    assert.deepEqual(validate_config(c), []);
    assert.deepEqual(check_config(c), []);
    assert.deepEqual(config_to_options(c, ENV).firmware,
        { type: "uefi", secure_boot: true, code: { url: "bios/ovmf-secure-code.fd" }, vars: { url: "bios/ovmf-vars-ms.fd" } });
    assert.equal(uefi_vars_template(c.machine), "bios/ovmf-vars-ms.fd");
    c.machine.secure_boot_keys = "none";
    assert.deepEqual(config_to_options(c, ENV).firmware.vars, { url: "bios/ovmf-vars.fd" });
    // (the machine's store: its own keys, whatever the template)
    c.machine.uefi_vars = { kind: "browser", path: "v86/disks/vars.img", size: 540672 };
    assert.deepEqual(config_to_options(c, ENV).firmware.vars, { url: "opfs:v86/disks/vars.img", size: 540672, disk_option: "read_write" });
    const migrated = with_defaults({ format: FORMAT, version: VERSION, machine: { type: "q35" } }).machine;
    assert.equal(migrated.secure_boot, false);
    assert.equal(migrated.secure_boot_keys, "microsoft");
});

test("the TPM: tpm 2.0; its state the machine's browser disk written back, with the CPU Worker; else in memory", () =>
{
    const c = new_config();
    c.machine.acpi = true;
    c.tpm = { state: null };
    assert.deepEqual(validate_config(c), []);
    assert.deepEqual(check_config(c), []);
    assert.deepEqual(config_to_options(c, ENV).tpm, { version: "2.0" });
    c.tpm.state = { kind: "browser", path: "v86/disks/tpm.img", size: 524288 };
    assert.deepEqual(config_to_options(c, ENV).tpm, { version: "2.0", state: { url: "opfs:v86/disks/tpm.img", size: 524288, disk_option: "read_write" } });
    c.advanced.cpu_worker = false;
    assert.deepEqual(config_to_options(c, ENV).tpm, { version: "2.0" });
    assert.equal(with_defaults({ format: FORMAT, version: VERSION }).tpm, null);
});

test("check_config: the library's own checks after validate_config's", () =>
{
    const c = new_config();
    c.disks = [disk({ image: { kind: "url", url: "parts/.img.zst", use_parts: true }, disk_option: "read_write" })];
    assert.deepEqual(validate_config(c), []);
    const problems = check_config(c);
    assert.equal(problems.length, 1);
    assert.equal(problems[0].path, "disks");
    assert.match(problems[0].message, /in parts .* can only be read/);
});

console.log(passed + " tests passed");
                                                                                                                                                   source/v64/tests/app/wizard_test.html                                                               0000644 0000000 0000000 00000175753 00000000000 015055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VM manager: the wizard and the settings dialog</title>
<!-- The VM manager's wizard and settings dialog (docs/vm-manager-plan.md U3), in a frame:
     part=freedos  the DOS preset from a floppy URL (images/freedos722.img), no hard disk: "Welcome to FreeDOS"
     part=linux    the 32-bit Linux preset from a CD URL (images/linux4.iso), a new disk in memory: the shell's "~%"
     part=arm64    the arm64 Linux preset, direct boot: Alpine's kernel, initrd and ISO (build/a64-linux/): "login:" on the serial console
     part=uefi     a machine of no preset edited to UEFI (OVMF, Q35) in the settings dialog, powered on: the UEFI Shell's
                   prompt on the serial console (bios/ovmf-code.fd through the CPU worker); a variable set in the Shell is
                   there at the next power-on (the machine's variable store, a browser disk written back), and gone after
                   the settings dialog's "Reset UEFI variables…"; with a TPM added there, OVMF's TCG2 protocol at each
                   power-on (the TPM plugin in the CPU worker, its state a browser disk), after "Clear TPM…" too
     part=secure_boot  a machine of no preset edited to UEFI on Q35 with Secure Boot (Microsoft's keys): the library's summary; powered
                   on through the CPU worker, the Secure Boot firmware's boot manager on the serial console (no bootable device)
     part=dialog   the settings dialog: arm64 makes the machine virt and says so, the choices it offers, ACPI fixed with its
                   reason, a problem shown on its panel and fixed, Add and Remove, Cancel keeps the configuration
     part=service  (with the runner's service=1) the disk service in Preferences, the wizard's new disk created there
     part=android  an Android image package (build/android-test-package.zip: tests/android/make_package.mjs) dropped on the
                   wizard: Cuttlefish's arm64 device, the Android 16 preset with gfxstream (I8.1), a browser disk made in the
                   importer's worker, the bootloader (src/android/bootloader.js) reading the disk's GPT and boot partitions
     part=android_gsi  the same package with a GSI (build/android-test-gsi.zip) dropped together; an older GSI refused; the disk's
                   vbmeta the GSI's (nothing chained)
     part=android_emulator  an Android Emulator image zip (build/android-test-emulator.zip) dropped on the wizard: the Android
                   7.1 (32-bit) preset, its disk made in the importer's worker, the bootloader giving its kernel, ramdisk and the
                   emulator's disks as partitions; the settings dialog's Android panel (no wipe)
     part=android_console  (local, a few minutes) the official package imported as android_boot does, powered on; once init's
                   second stage is on hvc0, the machine stopped and the console's Kernel console drawer opened: the log kept from before;
                   its keys to hvc0; the shell on the serial terminal (androidboot.console ttyAMA0) answering a command typed there;
                   the display at the device model's 720x1280
     part=android_service  (with the runner's service=1) the package imported into a new image of the disk service (I3.2):
                   its size, and the bootloader reading it from the service
     part=android_cancel  (local) the official zip's import cancelled: the wizard says so, the browser disk made so far is gone
     part=android_boot  (local, an hour or more) docs/android-images-plan.md I3's acceptance: the official Cuttlefish images zip
                   (package=<path>, build/a64-android/dl/aosp_cf_arm64_only_phone-img-15581820.zip) through the wizard, nothing
                   else filled in, powered on: init's sys.boot_completed=1 in the kernel's log (hvc0), then Android's screen in the
                   graphics proxy's compositor (the preset's gfxstream from the CPU worker, the renderer in the page);
                   timeout=<minutes> (180);
                   gsi=<path> also drops a GSI (I5.3), entry=<catalog id> the catalog's entry chosen (android16-cuttlefish; with
                   gsi= "", another package: the catalog lists one entry per Android version, android17-gsi-cp3a for the GSI it has)
     node tests/app/browser_runner.mjs tests/app/wizard_test.html part=freedos -->
<style>iframe { width: 1100px; height: 760px; border: 1px solid #888; }</style>
<pre id="log"></pre>
<pre id="result"></pre>
<script type="module">
const args = new URLSearchParams(location.search);
const part = args.get("part") || "freedos";
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(condition, what, timeout = 30000)
{
    const end = Date.now() + timeout;
    for(;;)
    {
        const value = await condition();
        if(value) return value;
        if(Date.now() > end) throw new Error("timed out: " + what);
        await sleep(100);
    }
}
function check(condition, what) { if(!condition) throw new Error(what); }

async function open_frame(url)
{
    const frame = document.createElement("iframe");
    frame.src = url;
    document.body.append(frame);
    await new Promise(resolve => frame.onload = resolve);
    return frame;
}

let library, w, d;
const $ = selector => d.querySelector(selector);
const $$ = selector => Array.from(d.querySelectorAll(selector));
const button = (text, scope = d) => Array.from(scope.querySelectorAll("button")).find(b => b.textContent.trim() === text && !b.disabled);
const names = () => $$(".vm-list .vm-name").map(e => e.textContent);
/** set a field the way a person does: its value, then change */
function set(element, value)
{
    element.value = value;
    element.dispatchEvent(new w.Event("input", { bubbles: true }));
    element.dispatchEvent(new w.Event("change", { bubbles: true }));
}
/** A table's rows as "name value; name value" */
const table_text = table => Array.from(table.querySelectorAll("tr"), tr => Array.from(tr.children, c => c.textContent.trim()).join(" ")).join("; ");
const select_text = (element, text) => set(element, Array.from(element.options).find(o => o.textContent.startsWith(text)).value);

async function open_library()
{
    library = await open_frame("/index.html");
    w = library.contentWindow;
    d = library.contentDocument;
    await until(() => $(".library"), "the library");
    // (power on opens a tab: here, the address)
    w.open = url => { w.__opened = url; return null; };
}

/**
 * The wizard: the source (its radio's text and URLs), the preset, the name, the disk
 * @param {{source: string, urls: Object<string, string>, preset: string, name: string, disk: "none" | "memory" | "service", disk_mb?: number}} o
 */
async function wizard(o)
{
    $("#new_vm").click();
    const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
    Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith(o.source)).click();
    for(const [label, url] of Object.entries(o.urls))
    {
        // (an optional image starts as "None": its URL choice first)
        const source = await until(() => wizard.querySelector("select[aria-label=\"" + label + ": source\"]"), "the source of " + label);
        if(source.value !== "url") set(source, "url");
        const input = await until(() => wizard.querySelector("input[aria-label=\"" + label + ": URL\"]"), "the URL of " + label);
        set(input, url);
    }
    button("Next", wizard).click();
    (await until(() => wizard.querySelector("li[data-preset=" + o.preset + "]"), "the preset " + o.preset)).click();
    log("wizard: " + o.source + " " + JSON.stringify(o.urls) + ", preset " + wizard.querySelector(".preset-detail h3").textContent +
        " (" + wizard.querySelector(".preset-detail p").textContent.slice(0, 60) + "…)");
    button("Next", wizard).click();
    set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), o.name);
    button("Next", wizard).click();
    await until(() => wizard.querySelector("input[name=disk]"), "the disk step");
    if(o.disk === "none")
    {
        wizard.querySelector("input[name=disk][value=none]").click();
    }
    else
    {
        if(o.disk_mb) set(wizard.querySelector("input[aria-label='Disk size in MB']"), String(o.disk_mb));
        const location = await until(() => wizard.querySelector("input[name=location][value=" + o.disk + "]"), "the location");
        check(!location.disabled, "the location " + o.disk + " can be chosen");
        location.click();
    }
    button("Next", wizard).click();
    const summary = table_text(await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary"));
    button("Finish", wizard).click();
    await until(() => names().includes(o.name), "the new machine in the library");
    return summary;
}

/** Power on the selected machine: its console in another frame; its emulator */
/** The colours of the emulator's screenshot (every 97th pixel, up to 1000) */
async function screen_colours(emulator)
{
    const image = emulator.screen_make_screenshot();
    if(!image) return { colours: 0 };
    await image.decode().catch(() => {});
    const canvas = document.createElement("canvas");
    canvas.width = image.naturalWidth;
    canvas.height = image.naturalHeight;
    if(!canvas.width || !canvas.height) return { colours: 0 };
    const context = canvas.getContext("2d");
    context.drawImage(image, 0, 0);
    const data = context.getImageData(0, 0, canvas.width, canvas.height).data;
    const colours = new Set();
    for(let i = 0; i < data.length && colours.size < 1000; i += 4 * 97) colours.add(data[i] << 16 | data[i + 1] << 8 | data[i + 2]);
    return { width: canvas.width, height: canvas.height, colours: colours.size };
}

/**
 * Where the display stands on the page: the adapter's renderer (GX's
 * surfaces, VX), the graphics proxy's compositor and its layers, the
 * console's canvases (the bundle's own names are compiled: the glbridge
 * objects are found by their shape)
 */
function display_state(frame, emulator)
{
    const values = Object.values(emulator).filter(v => v && typeof v === "object");
    const renderer = values.find(v => "executor" in v && "idle" in v);
    const plugins = values.find(v => Array.isArray(v) && v.some(p => p && p.bridge));
    const compositor = plugins && plugins.map(p => p.bridge && p.bridge.compositor).find(Boolean);
    const canvases = Array.from(frame.contentDocument.querySelectorAll("canvas"), c => c.width + "x" + c.height +
        (c.offsetParent === null ? " hidden" : ""));
    return "renderer " + (renderer ? "gx " + (renderer.gx ? renderer.gx.surfaces.size + " surfaces" : "none") + ", vx " + (renderer.vx ? "yes" : "no") : "none") +
        "; compositor " + (compositor ? (compositor.attached ? "attached" : "detached") + ", layers " +
            (compositor.layers.map(l => (l.visible ? "shown " : "hidden ") + l.canvas.width + "x" + l.canvas.height).join(" ") || "none") : "none") +
        "; canvases " + (canvases.join(", ") || "none");
}

async function power_on()
{
    w.__opened = undefined;
    $("#power_on").click();
    const url = await until(() => w.__opened, "power on");
    const frame = await open_frame(new URL(url, w.location.href).href);
    const emulator = await until(() => frame.contentWindow.v86_console?.emulator, "the console's emulator", 60000);
    return { frame, emulator };
}

/**
 * The official package (package=, gsi=, entry= as android_boot's) through the
 * wizard, nothing else filled in, imported: the machine in the library
 * @return {Promise<number>} when the files were dropped
 */
async function import_android()
{
    const urls = ["/" + (args.get("package") || "build/a64-android/dl/aosp_cf_arm64_only_phone-img-15581820.zip"),
        ...(args.get("gsi") ? ["/" + args.get("gsi")] : [])];
    const entry = args.has("entry") ? args.get("entry") : args.get("gsi") ? "" : "android16-cuttlefish";
    await open_library();
    $("#new_vm").click();
    const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
    Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
    (await until(() => wizard.querySelector("input[name=catalog][value='" + entry + "']"), "the catalog's entry " + entry)).click();
    const started = Date.now();
    const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
    const files = new w.DataTransfer();
    for(const url of urls) files.items.add(new w.File([await (await fetch(url)).blob()], url.split("/").pop(), { type: "application/zip" }));
    input.files = files.files;
    input.dispatchEvent(new w.Event("change", { bubbles: true }));
    log("package: " + await until(() => /Cuttlefish arm64 device/.test(wizard.querySelector(".drop-zone [role=status]")?.textContent) &&
        wizard.querySelector(".drop-zone [role=status]").textContent, "the package read", 120000));
    // (the catalog's SHA-256 checks)
    await until(() => button("Next", wizard), "the files checked: " + wizard.querySelector(".wizard-status").textContent, 600000);
    if(entry) log("checked against the catalog's " + entry + " in " + ((Date.now() - started) / 1000).toFixed(0) + " s");
    button("Next", wizard).click();
    await until(() => wizard.querySelector("li[data-preset=android16][aria-selected=true]"), "the Android 16 preset chosen");
    button("Next", wizard).click();
    const machine = args.get("gsi") ? "Android GSI (official)" : "Android 16 (official)";
    set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), machine);
    button("Next", wizard).click();
    await until(() => wizard.querySelector("input[name=userdata][value='4']:checked"), "the usual userdata");
    button("Next", wizard).click();
    log("summary: " + table_text(await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary")));
    const import_started = Date.now();
    button("Finish", wizard).click();
    await until(() => names().includes(machine), "the imported machine in the library", 1800000);
    log("imported in " + ((Date.now() - import_started) / 1000).toFixed(0) + " s");
    return started;
}

const parts = {
    async freedos()
    {
        await open_library();
        const summary = await wizard({ source: "A floppy image", urls: { "Floppy image": "images/freedos722.img" }, preset: "dos", name: "FreeDOS (wizard)", disk: "none" });
        check(/Memory 64 MB/.test(summary) && /Floppy \(fda\) images\/freedos722\.img/.test(summary) && !/Hard disk/.test(summary), "the summary: " + summary);
        check(/Memory 64 MB/.test(table_text($(".hardware"))), "the library's summary");
        log("library: " + names().join(", "));
        const { emulator } = await power_on();
        check(await emulator.wait_until_vga_screen_contains("Welcome to FreeDOS", { timeout_msec: 120000 }), "FreeDOS's welcome");
        log("power on: \"Welcome to FreeDOS\"");
        await emulator.destroy();
    },
    async linux()
    {
        await open_library();
        const summary = await wizard({ source: "A CD or DVD image", urls: { "CD image": "images/linux4.iso" }, preset: "linux", name: "Linux 4 (wizard)",
            disk: "memory", disk_mb: 64 });
        check(/Memory 512 MB/.test(summary) && /CD\/DVD images\/linux4\.iso/.test(summary) && /Hard disk \(hda\) empty disk in memory, 64 MB/.test(summary) &&
            /ACPI/.test(summary), "the summary: " + summary);
        const { emulator } = await power_on();
        check(await emulator.wait_until_vga_screen_contains("~%", { timeout_msec: 240000 }), "Linux's shell");
        log("power on: Linux 4 boots to its shell (\"~%\")");
        await emulator.destroy();
    },
    async arm64()
    {
        await open_library();
        const base = "build/a64-linux/";
        const summary = await wizard({ source: "A kernel and initrd", urls: { "Kernel": base + "boot/vmlinuz-virt", "Initrd": base + "boot/initramfs-virt",
            "The system's CD (optional)": base + "alpine-virt-3.24.0-aarch64.iso" }, preset: "linux_arm64", name: "Alpine arm64 (wizard)", disk: "none" });
        check(/Processor arm64, 4 cores/.test(summary) && /Machine virt/.test(summary) && /Direct boot kernel/.test(summary) && /Display virtio-gpu/.test(summary),
            "the summary: " + summary);
        const { emulator } = await power_on();
        let serial = "";
        emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
        await until(() => /login:/.test(serial), "Alpine's login on the serial console", 300000);
        log("power on: Alpine arm64 boots to \"" + serial.trim().split("\n").pop().trim() + "\"");
        await emulator.destroy();
    },
    async uefi()
    {
        await open_library();
        await wizard({ source: "Install the system later", urls: {}, preset: "other", name: "UEFI", disk: "none" });
        $("#edit_vm").click();
        const dialog = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        const item = id => dialog.querySelector("li[data-item=" + id + "]");
        const panel = () => dialog.querySelector(".settings-panel");
        item("machine").click();
        select_text(panel().querySelector("select[aria-label=Machine]"), "Q35");
        select_text(panel().querySelector("select[aria-label=Firmware]"), "UEFI (OVMF)");
        await until(() => /UEFI is OVMF/.test(panel().textContent), "the UEFI note");
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "TPM");
        await until(() => item("tpm") && item("tpm").classList.contains("selected"), "the TPM added");
        button("Save", dialog).click();
        await until(() => !$("dialog.settings-dialog[open]"), "saved");
        const VARIABLE = "V86Test -guid 2c94c1ab-37b4-4d11-9a3f-5fd77b0d5e8a";
        // powered on to the Shell: { frame, emulator, command }
        const shell = async () =>
        {
            const { frame, emulator } = await power_on();
            let serial = "";
            emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
            const plain = () => serial.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");
            await until(() => /Shell> $/.test(plain()), "the UEFI Shell on the serial console", 180000);
            check(/UEFI Interactive Shell v2\.2/.test(serial), "the Shell's banner");
            const command = async text =>
            {
                serial = "";
                for(const chr of text + "\r")
                {
                    emulator.serial0_send(chr);
                    await new Promise(resolve => setTimeout(resolve, 20));
                }
                await until(() => /Shell> $/.test(plain()), JSON.stringify(text), 60000);
                return plain();
            };
            return { frame, emulator, command };
        };
        // (powered off: the variable store flushed, the machine's lock and the store's handle let go)
        const power_off = async ({ frame, emulator }) => { await emulator.destroy(); frame.remove(); };

        // (OVMF's TCG2 protocol: it found the TPM, through the plugin the CPU worker loaded)
        const tcg2 = async machine => /^\s*[0-9A-F]+: Tcg2\s*$/m.test(await machine.command("dh -p Tcg2"));
        let machine = await shell();
        log("power on: OVMF on Q35 to \"Shell>\" on the serial console");
        check(await tcg2(machine), "OVMF's TCG2 protocol: the TPM found");
        log("the TPM: OVMF's TCG2 protocol installed");
        await machine.command("setvar " + VARIABLE + " -nv -bs -rt =L\"v86\"");
        check(/76 00 38 00 36 00/.test(await machine.command("setvar " + VARIABLE)), "the variable set");
        await power_off(machine);
        machine = await shell();
        check(/76 00 38 00 36 00/.test(await machine.command("setvar " + VARIABLE)), "the variable at the next power-on");
        log("a variable set in the Shell: there at the next power-on");
        // (a TPM state the plugin refused would leave OVMF without a TPM)
        check(await tcg2(machine), "the TPM at the next power-on, from its kept state");
        log("the TPM at the next power-on, from the state the first one kept");
        await power_off(machine);

        // (back in the library's tab: it reads the machines again, the variable store the console made)
        w.dispatchEvent(new Event("focus"));
        await new Promise(resolve => setTimeout(resolve, 500));
        $("#edit_vm").click();
        const again = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        again.querySelector("li[data-item=machine]").click();
        const reset = await until(() => button("Reset UEFI variables…", again), "the reset button");
        reset.click();
        const ask = await until(() => $$("dialog[open]").find(e => /Reset UEFI variables\?/.test(e.textContent)), "the question");
        button("Reset", ask).click();
        const status = await until(() => /^Reset|^Not reset/.test(again.querySelector(".settings-panel [role=status]").textContent) &&
            again.querySelector(".settings-panel [role=status]").textContent, "the reset");
        check(/^Reset/.test(status), status);
        again.querySelector("li[data-item=tpm]").click();
        const clear = await until(() => button("Clear TPM…", again), "Clear TPM… (the state made)");
        clear.click();
        const sure = await until(() => $$("dialog[open]").find(e => /Clear the TPM\?/.test(e.textContent)), "the question");
        button("Clear", sure).click();
        const cleared = await until(() => /^Cleared|^Not cleared/.test(again.querySelector(".settings-panel [role=status]").textContent) &&
            again.querySelector(".settings-panel [role=status]").textContent, "the clear");
        check(/^Cleared/.test(cleared), cleared);
        button("Cancel", again).click();
        machine = await shell();
        check(!/76 00 38 00 36 00/.test(await machine.command("setvar " + VARIABLE)), "the variable gone after the reset");
        log("Reset UEFI variables: the variable gone at the next power-on");
        check(await tcg2(machine), "a new TPM after Clear TPM…");
        log("Clear TPM…: a new TPM at the next power-on");
        await power_off(machine);
    },
    async secure_boot()
    {
        await open_library();
        await wizard({ source: "Install the system later", urls: {}, preset: "other", name: "Secure Boot", disk: "none" });
        $("#edit_vm").click();
        const dialog = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        const panel = () => dialog.querySelector(".settings-panel");
        dialog.querySelector("li[data-item=machine]").click();
        select_text(panel().querySelector("select[aria-label=Machine]"), "Q35");
        select_text(panel().querySelector("select[aria-label=Firmware]"), "UEFI (OVMF)");
        const box = await until(() => Array.from(panel().querySelectorAll("label.check")).find(l => /^Secure Boot/.test(l.textContent.trim())),
            "the Secure Boot switch");
        check(!box.querySelector("input").disabled, "Secure Boot available on Q35");
        box.querySelector("input").click();
        const keys = await until(() => panel().querySelector("select[aria-label='Secure Boot keys']"), "the keys");
        check(/^Microsoft/.test(keys.selectedOptions[0].textContent), "Microsoft's keys by default: " + keys.selectedOptions[0].textContent);
        button("Save", dialog).click();
        await until(() => !$("dialog.settings-dialog[open]"), "saved");
        await until(() => /Secure Boot/.test(table_text($(".hardware"))), "the library showing Secure Boot");
        log("Secure Boot: on Q35 with UEFI, Microsoft's keys");

        // powered on (the Secure Boot firmware, its store's flash SMM's, through the CPU worker): no disk, the boot manager says so
        const { frame, emulator } = await power_on();
        let serial = "";
        emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
        const plain = () => serial.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");
        await until(() => /BdsDxe: No bootable option or device was found/.test(plain()), "the boot manager on the serial console", 180000);
        log("power on: the Secure Boot firmware's boot manager (no bootable device)");
        await emulator.destroy();
        frame.remove();
    },
    async dialog()
    {
        await open_library();
        await wizard({ source: "Install the system later", urls: {}, preset: "other", name: "To edit", disk: "memory", disk_mb: 32 });
        const before = JSON.stringify(names());
        $("#edit_vm").click();
        let dialog = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        const item = id => dialog.querySelector("li[data-item=" + id + "]");
        const panel = () => dialog.querySelector(".settings-panel");
        const items = () => Array.from(dialog.querySelectorAll(".hardware-list li"), li => li.dataset.item);
        check(JSON.stringify(items()) === JSON.stringify(["general", "memory", "processor", "machine", "disk-0", "cdrom", "network-0", "sound", "display", "serial", "advanced"]),
            "the hardware list: " + items());

        // the CPU: arm64 makes the machine virt, said in the notes
        item("processor").click();
        select_text(panel().querySelector("select[aria-label=CPU]"), "arm64");
        await until(() => /Machine: virt/.test(dialog.querySelector(".settings-notes").textContent), "the note");
        log("arm64: " + dialog.querySelector(".settings-notes").textContent);
        // the CPU model: automatic and arm64's own (the regression-only ones left out), with what the chosen one is for
        const models = () => Array.from(panel().querySelector("select[aria-label='CPU model']").options, o => o.textContent);
        check(JSON.stringify(models()) === JSON.stringify(["Automatic (the system decides)", "Generic 64-bit ARM (recommended)",
            "Generic 64-bit ARM that runs 32-bit programs"]), "arm64's CPU models: " + models());
        check(/64-bit Linux, Android 16/.test(panel().textContent), "automatic: the default model's purpose");
        select_text(panel().querySelector("select[aria-label='CPU model']"), "Generic 64-bit ARM that runs 32-bit");
        await until(() => /32-bit programs too/.test(panel().textContent), "the model's purpose");
        log("arm64's CPU models: " + models().join(", "));
        item("display").click();
        const adapters = Array.from(panel().querySelector("select[aria-label='Display adapter']").options, o => o.textContent);
        check(JSON.stringify(adapters) === JSON.stringify(["None (serial console only)", "virtio-gpu"]), "virt's display adapters: " + adapters);
        item("machine").click();
        const acpi = Array.from(panel().querySelectorAll("label.check")).find(l => /^ACPI/.test(l.textContent.trim()));
        check(acpi.querySelector("input").disabled && /device tree/.test(acpi.textContent), "ACPI fixed, with its reason: " + acpi.textContent);
        check(items().includes("virt") && !items().includes("floppy-0"), "virt's items: " + items());
        log("virt: display adapters " + adapters.join(", ") + "; ACPI " + acpi.textContent.trim());

        // back to x86, then two cores: ACPI on, fixed
        item("processor").click();
        select_text(panel().querySelector("select[aria-label=CPU]"), "x86 (32-bit");
        await until(() => /CPU model: automatic/.test(dialog.querySelector(".settings-notes").textContent), "the CPU model's note");
        check(JSON.stringify(models()) === JSON.stringify(["Automatic (the system decides)", "Generic 32-bit x86 (recommended)"]) &&
            panel().querySelector("select[aria-label='CPU model']").selectedOptions[0].textContent.startsWith("Automatic"),
            "x86: its CPU models, the arm64 one dropped: " + models());
        select_text(panel().querySelector("select[aria-label=Cores]"), "2");
        item("machine").click();
        const acpi2 = Array.from(panel().querySelectorAll("label.check")).find(l => /^ACPI/.test(l.textContent.trim())).querySelector("input");
        check(acpi2.checked && acpi2.disabled, "two cores: ACPI on and fixed");

        // the firmware: UEFI brings the x86_64 CPU and says what it is; SeaBIOS again
        const firmwares = Array.from(panel().querySelector("select[aria-label=Firmware]").options, o => o.textContent);
        check(firmwares.includes("UEFI (OVMF)"), "the firmware: " + firmwares);
        select_text(panel().querySelector("select[aria-label=Firmware]"), "UEFI (OVMF)");
        await until(() => /UEFI is OVMF/.test(panel().textContent), "the UEFI note");
        // (Secure Boot only on Q35: its firmware runs in SMM)
        const secure_boot = Array.from(panel().querySelectorAll("label.check")).find(l => /^Secure Boot/.test(l.textContent.trim()));
        check(secure_boot && secure_boot.querySelector("input").disabled && /Q35/.test(secure_boot.textContent), "Secure Boot: on Q35 only");
        item("processor").click();
        check(panel().querySelector("select[aria-label=CPU]").selectedOptions[0].textContent.startsWith("x86_64"), "UEFI: the x86_64 CPU");
        select_text(panel().querySelector("select[aria-label=CPU]"), "x86 (32-bit");
        item("machine").click();
        check(panel().querySelector("select[aria-label=Firmware]").selectedOptions[0].textContent.startsWith("SeaBIOS"),
            "the x86 CPU: SeaBIOS again");
        log("Firmware: " + firmwares.join(", ") + "; UEFI chose x86_64, the x86 CPU SeaBIOS again");

        // a problem: the disk's URL left empty; Save shows it on the disk's panel
        item("disk-0").click();
        select_text(panel().querySelector("select[aria-label='Source: source']"), "An image on the web");
        button("Save", dialog).click();
        await until(() => dialog.querySelector(".settings-panel ul.problems"), "the problem on its panel");
        check(dialog.querySelector("li[data-item=disk-0]").classList.contains("has-problem") && dialog.querySelector("li[data-item=disk-0]").classList.contains("selected"),
            "the disk's item marked and chosen");
        log("Save with an empty URL: " + dialog.querySelector(".settings-panel ul.problems").textContent + " (on the disk's panel)");
        set(panel().querySelector("input[aria-label='Source: URL']"), "images/msdos622.img");
        check(!dialog.querySelector("ul.problems"), "the problem gone after the fix");

        // Add a floppy drive, remove it again; add a second disk
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "Floppy drive");
        await until(() => item("floppy-0") && item("floppy-0").classList.contains("selected"), "the floppy drive added and chosen");
        button("Remove", dialog).click();
        await until(() => !item("floppy-0"), "the floppy drive removed");
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "Hard disk");
        await until(() => item("disk-1"), "a second hard disk");
        log("Add and Remove: a floppy drive added and removed, a second hard disk added");

        // Add USB: UHCI with the tablet; EHCI chosen, the tablet off
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "USB");
        await until(() => item("usb") && item("usb").classList.contains("selected"), "USB added and chosen");
        const controllers = Array.from(panel().querySelector("select[aria-label=Controller]").options, o => o.textContent);
        check(JSON.stringify(controllers) === JSON.stringify(["UHCI (USB 1.1)", "EHCI (USB 2.0, with UHCI companions)", "xHCI (USB 3)"]),
            "the USB controllers: " + controllers);
        select_text(panel().querySelector("select[aria-label=Controller]"), "EHCI");
        await until(() => /EHCI/.test(item("usb").textContent), "EHCI in the item's summary");
        const tablet = Array.from(panel().querySelectorAll("label.check")).find(l => /^Tablet/.test(l.textContent.trim())).querySelector("input");
        check(tablet.checked && /EHCI, tablet/.test(item("usb").textContent), "the tablet on: " + item("usb").textContent);
        tablet.click();
        await until(() => !/tablet/.test(item("usb").textContent), "the tablet off in the item's summary");
        check(!Array.from(dialog.querySelector("select[aria-label='Add hardware']").options, o => o.textContent).includes("USB"), "USB no longer to add");
        log("USB: added (" + controllers.join(", ") + "), EHCI chosen, the tablet turned off");

        // Add a USB disk: an empty disk in memory, write protected
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "USB disk");
        await until(() => item("usb-disk-0") && item("usb-disk-0").classList.contains("selected"), "a USB disk added and chosen");
        check(/USB disk \(usb0\)/.test(item("usb-disk-0").textContent), "its item: " + item("usb-disk-0").textContent);
        const protect = Array.from(panel().querySelectorAll("label.check")).find(l => /^Write protected/.test(l.textContent.trim())).querySelector("input");
        check(!protect.checked, "not write protected at first");
        protect.click();
        await until(() => protect.isConnected ? protect.checked : panel().querySelector("label.check input").checked, "write protected");
        log("USB disk: added (usb0), write protected");

        // Add a TPM: its item, its panel (Clear TPM… waits for the state, made at the first power-on)
        select_text(dialog.querySelector("select[aria-label='Add hardware']"), "TPM");
        await until(() => item("tpm") && item("tpm").classList.contains("selected"), "the TPM added and chosen");
        check(/TPM 2\.0 \(CRB\)/.test(item("tpm").textContent), "its item: " + item("tpm").textContent);
        const clear = Array.from(panel().querySelectorAll("button")).find(b => b.textContent === "Clear TPM…");
        check(clear && clear.disabled, "Clear TPM… disabled before the first power-on");
        check(!Array.from(dialog.querySelector("select[aria-label='Add hardware']").options, o => o.textContent).includes("TPM"), "TPM no longer to add");
        log("TPM: added (TPM 2.0, CRB), nothing to clear yet");
        button("Save", dialog).click();
        await until(() => !$("dialog.settings-dialog[open]"), "saved");
        const table = await until(() => /2 cores/.test(table_text($(".hardware"))) && table_text($(".hardware")), "the library showing the saved machine");
        check(/x86, 2 cores/.test(table) && /ACPI/.test(table) && /Hard disk \(hda\) images\/msdos622\.img/.test(table) && /Hard disk \(hdb\)/.test(table) &&
            /USB EHCI(;|$)/.test(table) && /USB disk \(usb0\) [^;]*write protected/.test(table), "the saved machine: " + table);
        log("saved: " + table.slice(0, 160));

        // Cancel: nothing changes
        $("#edit_vm").click();
        dialog = await until(() => $("dialog.settings-dialog[open]"), "the dialog again");
        item("memory").click();
        set(dialog.querySelector(".settings-panel input[aria-label='Memory in MB']"), "1024");
        button("Cancel", dialog).click();
        await until(() => !$("dialog.settings-dialog[open]"), "cancelled");
        await sleep(500);
        check(!/1024 MB/.test(table_text($(".hardware"))) && JSON.stringify(names()) === before, "Cancel keeps the configuration");
        log("Cancel: the configuration unchanged");
    },
    async android()
    {
        await open_library();
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
        // (the package as a person drops or chooses it: a File in the input)
        const blob = await (await fetch("/build/android-test-package.zip")).blob();
        const file = new w.File([blob], "aosp_cf_test-img-1.zip", { type: "application/zip" });
        const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
        const files = new w.DataTransfer();
        files.items.add(file);
        input.files = files.files;
        input.dispatchEvent(new w.Event("change", { bubbles: true }));
        const status = await until(() => /Cuttlefish arm64 device/.test(wizard.querySelector(".drop-zone [role=status]")?.textContent) &&
            wizard.querySelector(".drop-zone [role=status]").textContent, "the package read");
        log("package: " + status);
        // (the catalog's first entry is chosen: this package is not its file)
        const differs = await until(() => /^differs/.test(wizard.querySelector(".drop-zone td[data-role=device]")?.textContent) &&
            wizard.querySelector(".drop-zone td[data-role=device]").textContent, "the catalog's check");
        check(!button("Next", wizard) && /not the catalog's/.test(wizard.querySelector(".wizard-status").textContent), "Next held back: " + wizard.querySelector(".wizard-status").textContent);
        log("the catalog's entry: " + differs);
        wizard.querySelector("input[name=catalog][value='']").click();
        await until(() => button("Next", wizard), "Next, with another package");
        button("Next", wizard).click();
        const chosen = await until(() => wizard.querySelector("li[data-preset=android16][aria-selected=true]"), "the Android 16 preset chosen");
        check(!wizard.querySelector(".preset-detail p.error"), "the preset installs from a package");
        button("Next", wizard).click();
        set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), "Android (wizard)");
        button("Next", wizard).click();
        (await until(() => wizard.querySelector("input[name=userdata][value='2']"), "the userdata sizes")).click();
        check(/userdata blank/.test(wizard.querySelector(".wizard-body").textContent), "the disk step says what the disk is");
        button("Next", wizard).click();
        const summary = table_text(await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary"));
        check(/Android boot from the first disk \(cf_arm64_only_phone\), gfxstream/.test(summary) && /Hard disk \(hda\) .*read write/.test(summary) &&
            /Vulkan \(gfxstream\)/.test(summary), "the summary: " + summary);
        button("Finish", wizard).click();
        await until(() => names().includes("Android (wizard)"), "the new machine in the library", 120000);
        const table = table_text($(".hardware"));
        log("library: " + table.slice(0, 200));
        // the browser disk: v64's bootloader reads it as the machine will
        let dir = await w.navigator.storage.getDirectory();
        for(const name of ["v86", "disks"]) dir = await dir.getDirectoryHandle(name);
        const disks = [];
        for await (const [name, handle] of dir.entries()) if(name.endsWith(".img")) disks.push(await handle.getFile());
        const disk = disks.sort((a, b) => b.lastModified - a.lastModified)[0];
        const { android_bootloader } = await import("/src/android/bootloader.js");
        const boot = await android_bootloader(async (offset, length) => new Uint8Array(await disk.slice(offset, offset + length).arrayBuffer()), disk.size, { memory_mb: 1536 });
        check(boot.kernel.length === 8192 && /console=hvc0 earlycon/.test(boot.cmdline) && boot.bootconfig.get("androidboot.hardware.vulkan") === "pastel",
            "the bootloader on the disk: " + boot.kernel.length + " " + boot.cmdline);
        log("the browser disk (" + disk.size + " bytes): the bootloader gives " + boot.kernel.length + " bytes of kernel, " + boot.initrd.length + " of initrd, vbmeta " +
            boot.vbmeta.digest.slice(0, 16) + "…, cmdline " + boot.cmdline);
        // the settings dialog's Android item: its choices, and Wipe user data
        $("#edit_vm").click();
        const dialog = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        dialog.querySelector("li[data-item=android]").click();
        const panel = await until(() => dialog.querySelector(".settings-panel[aria-label=Android]"), "the Android panel");
        const gpu = panel.querySelector("select[aria-label=GPU]");
        check(/gfxstream/.test(gpu.selectedOptions[0].textContent) && !gpu.disabled && gpu.options.length === 2, "the GPU: gfxstream, or SwiftShader");
        button("Wipe user data…", panel).click();
        const ask = await until(() => $$("dialog[open]").find(e => /Wipe user data\?/.test(e.textContent)), "the question");
        button("Wipe", ask).click();
        const wiped = await until(() => /^Wiped|^Not wiped/.test(panel.querySelector("[role=status]").textContent) && panel.querySelector("[role=status]").textContent, "the wipe");
        check(/^Wiped: userdata, metadata/.test(wiped), "the wipe: " + wiped);
        log("settings: Android panel, " + wiped);
        button("Cancel", dialog).click();
    },
    async android_emulator()
    {
        await open_library();
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
        (await until(() => wizard.querySelector("input[name=catalog][value='']"), "the catalog")).click();
        const blob = await (await fetch("/build/android-test-emulator.zip")).blob();
        const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
        const files = new w.DataTransfer();
        files.items.add(new w.File([blob], "armeabi-v7a-25_r18.zip", { type: "application/zip" }));
        input.files = files.files;
        input.dispatchEvent(new w.Event("change", { bubbles: true }));
        const status = await until(() => /Android Emulator system image/.test(wizard.querySelector(".drop-zone [role=status]")?.textContent) &&
            wizard.querySelector(".drop-zone [role=status]").textContent, "the package read");
        log("package: " + status);
        await until(() => button("Next", wizard), "Next");
        button("Next", wizard).click();
        await until(() => wizard.querySelector("li[data-preset=android7_arm32][aria-selected=true]"), "the Android 7.1 (32-bit) preset chosen");
        check(!wizard.querySelector(".preset-detail p.error"), "the preset installs from a package");
        button("Next", wizard).click();
        set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), "Android 7 (wizard)");
        button("Next", wizard).click();
        const body = await until(() => /Android Emulator's image \(Android 7\.1\.1, API 25, armeabi-v7a/.test(wizard.querySelector(".wizard-body")?.textContent) &&
            wizard.querySelector(".wizard-body").textContent, "the disk step");
        check(!wizard.querySelector("input[name=userdata]"), "no userdata sizes: the image's own");
        log("disk step: " + body.slice(0, 200));
        button("Next", wizard).click();
        const summary = table_text(await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary"));
        check(/Android boot from the first disk \(ranchu_25_armeabi_v7a\), the emulator's disks/.test(summary) && /Hard disk \(hda\) .*read write/.test(summary),
            "the summary: " + summary);
        button("Finish", wizard).click();
        await until(() => names().includes("Android 7 (wizard)"), "the new machine in the library", 120000);
        const table = table_text($(".hardware"));
        check(/arm32/.test(table) && /ranchu/.test(table), "the library: " + table.slice(0, 300));
        let dir = await w.navigator.storage.getDirectory();
        for(const name of ["v86", "disks"]) dir = await dir.getDirectoryHandle(name);
        const disks = [];
        for await (const [name, handle] of dir.entries()) if(name.endsWith(".img")) disks.push(await handle.getFile());
        const disk = disks.sort((a, b) => b.lastModified - a.lastModified)[0];
        const { android_bootloader } = await import("/src/android/bootloader.js");
        const boot = await android_bootloader(async (offset, length) => new Uint8Array(await disk.slice(offset, offset + length).arrayBuffer()), disk.size,
            { device: "ranchu_25_armeabi_v7a", memory_mb: 1024 });
        check(boot.kernel.length >= 5000 && /androidboot.hardware=ranchu/.test(boot.cmdline) &&
            boot.disks.map(d => d.name + (d.readonly ? " ro" : "")).join(",") === "system ro,cache,userdata",
            "the bootloader on the disk: " + boot.kernel.length + " " + boot.cmdline + " " + JSON.stringify(boot.disks));
        log("the browser disk (" + disk.size + " bytes): " + boot.disks.map(d => d.name + "@" + d.start).join(", "));
        $("#edit_vm").click();
        const dialog = await until(() => $("dialog.settings-dialog[open]"), "the settings dialog");
        dialog.querySelector("li[data-item=android]").click();
        const panel = await until(() => dialog.querySelector(".settings-panel[aria-label=Android]"), "the Android panel");
        const wipe = Array.from(panel.querySelectorAll("button")).find(b => b.textContent === "Wipe user data…");
        // (no wipe; the GPU: the host's or the guest's CPU; the GLES version the host's GPU announces, 3.1 by default)
        const gpu = panel.querySelector("select[aria-label=GPU]"), gles = panel.querySelector("select[aria-label='GLES version']");
        const chosen = select => select && select.options[select.selectedIndex].textContent;
        check(wipe && wipe.disabled && gpu && gpu.options.length === 2 && /host's GPU/.test(chosen(gpu)) && /^GLES 3\.1/.test(chosen(gles)),
            "the emulator image's panel: no wipe; the GPU, the GLES version: " + chosen(gpu) + " / " + chosen(gles));
        const machine = dialog.querySelector("li[data-item=processor]");
        machine.click();
        const cpu = await until(() => dialog.querySelector(".settings-panel select[aria-label=CPU]"), "the CPU");
        check(/ARM \(32-bit/.test(cpu.selectedOptions[0].textContent), "the CPU: " + cpu.selectedOptions[0].textContent);
        button("Cancel", dialog).click();
    },
    async android_gsi()
    {
        await open_library();
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
        (await until(() => wizard.querySelector("input[name=catalog][value='']"), "the catalog")).click();
        const file = async (url, name) => new w.File([await (await fetch(url)).blob()], name, { type: "application/zip" });
        const drop = async files =>
        {
            const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
            const list = new w.DataTransfer();
            for(const f of files) list.items.add(f);
            input.files = list.files;
            input.dispatchEvent(new w.Event("change", { bubbles: true }));
        };
        const device = await file("/build/android-test-package.zip", "aosp_cf_test-img-1.zip");
        // (an older GSI: refused, said why)
        await drop([device, await file("/build/android-test-gsi-old.zip", "aosp_arm64-exp-old.zip")]);
        const refused = await until(() => wizard.querySelector(".drop-zone p.error")?.textContent, "the older GSI refused");
        check(/older than the device's vendor/.test(refused), "the refusal: " + refused);
        log("an older GSI: " + refused.slice(0, 120) + "…");
        // (the GSI of the vendor's version, in a second drop: the device kept)
        await drop([await file("/build/android-test-gsi.zip", "aosp_arm64-exp-test.zip")]);
        const status = await until(() => /running the GSI's Android 16/.test(wizard.querySelector(".drop-zone [role=status]")?.textContent) &&
            wizard.querySelector(".drop-zone [role=status]").textContent, "the device and the GSI read");
        check(/32-bit ABIs/.test(wizard.querySelector(".drop-zone").textContent), "the note on 32-bit apps");
        log("package: " + status);
        button("Next", wizard).click();
        await until(() => wizard.querySelector("li[data-preset=android16][aria-selected=true]"), "the Android 16 preset chosen");
        button("Next", wizard).click();
        set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), "Android GSI (wizard)");
        button("Next", wizard).click();
        (await until(() => wizard.querySelector("input[name=userdata][value='2']"), "the userdata sizes")).click();
        button("Next", wizard).click();
        await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary");
        button("Finish", wizard).click();
        await until(() => names().includes("Android GSI (wizard)"), "the new machine in the library", 120000);
        let dir = await w.navigator.storage.getDirectory();
        for(const name of ["v86", "disks"]) dir = await dir.getDirectoryHandle(name);
        const disks = [];
        for await (const [name, handle] of dir.entries()) if(name.endsWith(".img")) disks.push(await handle.getFile());
        const disk = disks.sort((a, b) => b.lastModified - a.lastModified)[0];
        const { android_bootloader } = await import("/src/android/bootloader.js");
        const boot = await android_bootloader(async (offset, length) => new Uint8Array(await disk.slice(offset, offset + length).arrayBuffer()), disk.size, { memory_mb: 1536 });
        check(boot.vbmeta.chained.length === 0 && boot.vbmeta.size === 256, "the GSI's vbmeta: " + JSON.stringify(boot.vbmeta));
        log("the browser disk (" + disk.size + " bytes): vbmeta the GSI's alone (" + boot.vbmeta.size + " bytes, nothing chained)");
    },
    async android_service()
    {
        const service = args.get("service");
        check(service, "the runner's disk service (service=1)");
        await open_library();
        $("#preferences").click();
        const prefs = await until(() => $("dialog[open]"), "the preferences");
        set(prefs.querySelector("input[aria-label='Disk service URL']"), service);
        button("Save", prefs).click();
        await until(() => $("#service_status").textContent === "Disk service: " + service, "the library using the disk service");
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
        (await until(() => wizard.querySelector("input[name=catalog][value='']"), "the catalog")).click();
        const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
        const files = new w.DataTransfer();
        files.items.add(new w.File([await (await fetch("/build/android-test-package.zip")).blob()], "aosp_cf_test-img-1.zip", { type: "application/zip" }));
        input.files = files.files;
        input.dispatchEvent(new w.Event("change", { bubbles: true }));
        await until(() => /Cuttlefish arm64 device/.test(wizard.querySelector(".drop-zone [role=status]")?.textContent), "the package read");
        await until(() => button("Next", wizard), "Next");
        button("Next", wizard).click();
        await until(() => wizard.querySelector("li[data-preset=android16][aria-selected=true]"), "the Android 16 preset chosen");
        button("Next", wizard).click();
        set(await until(() => wizard.querySelector("input[aria-label=Name]"), "the name"), "Android on the service");
        button("Next", wizard).click();
        (await until(() => wizard.querySelector("input[name=userdata][value='2']"), "the userdata sizes")).click();
        (await until(() => wizard.querySelector("input[name=location][value=service]:not([disabled])"), "the service as the location")).click();
        button("Next", wizard).click();
        await until(() => wizard.querySelector(".wizard-body table.hardware"), "the summary");
        button("Finish", wizard).click();
        await until(() => names().includes("Android on the service"), "the new machine in the library", 120000);
        const listed = await (await fetch("/__service_files")).json();
        const image = listed.find(f => f.name === "android-on-the-service.img");
        check(image && image.size > 2 << 30, "the service's image: " + JSON.stringify(listed));
        const url = service.replace(/\/?$/, "/") + image.name;
        const { android_bootloader } = await import("/src/android/bootloader.js");
        const read = async (offset, length) => new Uint8Array(await (await fetch(url, { headers: { Range: "bytes=" + offset + "-" + (offset + length - 1) } })).arrayBuffer());
        const boot = await android_bootloader(read, image.size, { memory_mb: 1536 });
        check(boot.kernel.length === 8192 && /console=hvc0/.test(boot.cmdline), "the bootloader on the service's image");
        check(/read write/.test(table_text($(".hardware"))) && table_text($(".hardware")).includes(image.name), "the machine's disk: " + table_text($(".hardware")));
        log("the disk service's image " + image.name + " (" + image.size + " bytes): the bootloader gives " + boot.kernel.length + " bytes of kernel, cmdline " + boot.cmdline);
    },
    async android_cancel()
    {
        await open_library();
        const disks = async () =>
        {
            let dir = await w.navigator.storage.getDirectory();
            for(const name of ["v86", "disks"]) dir = await dir.getDirectoryHandle(name, { create: true });
            const list = [];
            for await (const [name] of dir.entries()) if(name.endsWith(".img")) list.push(name);
            return list;
        };
        const before = await disks();
        $("#new_vm").click();
        const wizard = await until(() => $("dialog.wizard-dialog[open]"), "the wizard");
        Array.from(wizard.querySelectorAll("input[name=source]")).find(r => r.parentElement.textContent.trim().startsWith("An Android image package")).click();
        (await until(() => wizard.querySelector("input[name=catalog][value='']"), "the catalog")).click();
        const input = await until(() => wizard.querySelector("input[aria-label='Android image package']"), "the package's input");
        const files = new w.DataTransfer();
        files.items.add(new w.File([await (await fetch("/build/a64-android/dl/aosp_cf_arm64_only_phone-img-15581820.zip")).blob()], "aosp_cf_arm64_only_phone-img-15581820.zip"));
        input.files = files.files;
        input.dispatchEvent(new w.Event("change", { bubbles: true }));
        await until(() => button("Next", wizard), "the package read", 120000);
        for(let i = 0; i < 3; i++) { button("Next", wizard).click(); await sleep(200); }
        button("Next", wizard).click();
        await until(() => button("Finish", wizard), "the summary");
        button("Finish", wizard).click();
        await until(() => /Importing .*: \d+%/.test(wizard.querySelector(".wizard-status").textContent), "the import going on", 60000);
        button("Cancel import", wizard).click();
        await until(() => /cancelled/.test(wizard.querySelector(".wizard-status").textContent), "the import cancelled");
        check(button("Finish", wizard), "the wizard back to its buttons");
        await until(async () => JSON.stringify(await disks()) === JSON.stringify(before), "the browser disk made so far deleted", 10000);
        log("cancelled: " + wizard.querySelector(".wizard-status").textContent + "; the browser disks as before (" + before.length + ")");
    },
    async android_boot()
    {
        const started = await import_android();
        const { frame, emulator } = await power_on();
        const booted = Date.now();
        let kernel = "";
        const milestones = [["second stage", /init: init second stage started/], ["zygote", /starting service 'zygote'/], ["system_server", /starting service 'system_server'|SystemServer/],
            ["boot_completed", /init: processing action \(sys\.boot_completed=1\)/]];
        const seen = new Set();
        emulator.add_listener("virtio-console0-output-bytes", bytes =>
        {
            kernel = (kernel + String.fromCharCode.apply(null, Array.from(bytes))).slice(-8192);
            for(const [what, pattern] of milestones) if(!seen.has(what) && pattern.test(kernel)) { seen.add(what); log(((Date.now() - booted) / 1000).toFixed(0) + " s: " + what); }
            if(/reboot: Restarting system with command 'bootloader'/.test(kernel)) seen.add("failed");
        });
        await until(() => seen.has("boot_completed") || seen.has("failed"), "sys.boot_completed=1 in the kernel's log", (+args.get("timeout") || 180) * 60000);
        check(!seen.has("failed"), "init rebooted into the bootloader: " + kernel.slice(-1500));
        log("boot_completed " + ((Date.now() - booted) / 1000).toFixed(0) + " s after power on (" + ((Date.now() - started) / 60000).toFixed(1) + " min in all)");
        // (the preset's GPU, gfxstream: the machine in the CPU worker, the renderer in this page draws what the
        // guest's GPU drew into the graphics proxy's compositor, the lock screen at least: a screen of the
        // display's size (the page's, which the guest takes), not the text screen it starts as (720x400)
        let last = "", noted = 0;
        const shown = await until(async () =>
        {
            const s = await screen_colours(emulator);
            const what = s.width + "x" + s.height + ", " + s.colours + " colours";
            if(what !== last && Date.now() - noted > 60000)
            {
                log(((Date.now() - booted) / 1000).toFixed(0) + " s: the screen " + what + "; " + display_state(frame, emulator));
                noted = Date.now();
            }
            last = what;
            return !(s.width === 720 && s.height === 400) && s.colours >= 64 && s;
        }, "the screen drawn by the guest's GPU (the log has what it showed)", 30 * 60000);
        log("the screen " + ((Date.now() - booted) / 1000).toFixed(0) + " s after power on: " + shown.width + "x" + shown.height + ", " +
            shown.colours + " colours (sampled)");
        await emulator.destroy();
    },
    async android_console()
    {
        await import_android();
        const { frame, emulator } = await power_on();
        const booted = Date.now();
        let kernel = "";
        emulator.add_listener("virtio-console0-output-bytes", bytes => { kernel = (kernel + String.fromCharCode.apply(null, Array.from(bytes))).slice(-65536); });
        await until(() => /init: init second stage started/.test(kernel), "init's second stage on hvc0", 600000);
        // (the machine stopped, the drawer opened: what it shows was printed before, kept from power on)
        await emulator.stop();
        log(((Date.now() - booted) / 1000).toFixed(0) + " s: init's second stage; stopped, the kernel console opened");
        const c = frame.contentDocument, cw = frame.contentWindow;
        c.querySelector("#drawer_kernel").click();
        const rows = await until(() => c.querySelector(".console-drawer .terminal .xterm-rows"), "the kernel console (xterm)", 30000);
        const shown = await until(() => /\[\s*\d+\.\d+\]/.test(rows.textContent) && rows.textContent.replace(/\s+/g, " ").trim(),
            "the kernel's log kept from before the drawer opened", 10000);
        log("kernel console, kept from before: " + shown.slice(0, 160));
        await emulator.run();
        // (keys typed in it go to hvc0, which Android only writes: its shell is on the serial port, androidboot.console ttyAMA0)
        const typed = [];
        const send = emulator.virtio_console_send;
        emulator.virtio_console_send = data => { typed.push(data); send.call(emulator, data); };
        const type_in = (selector, text) => c.querySelector(selector).dispatchEvent(new cw.InputEvent("input", { data: text, inputType: "insertText", bubbles: true }));
        type_in(".console-drawer .xterm-helper-textarea", "x");
        check(typed.join("") === "x", "the kernel console's keys to hvc0: " + JSON.stringify(typed));
        // (the serial terminal: the shell a userdebug build runs there, a command typed and answered)
        c.querySelector("#drawer_terminal").click();
        const serial_rows = await until(() => c.querySelector(".console-drawer .terminal .xterm-rows"), "the serial terminal (xterm)", 30000);
        const asked = Date.now();
        let answered = false;
        while(!answered && Date.now() - asked < 900000)
        {
            type_in(".console-drawer .xterm-helper-textarea", "echo v86-$((6*7))");
            type_in(".console-drawer .xterm-helper-textarea", "\r");
            answered = await until(() => /v86-42/.test(serial_rows.textContent), "", 20000).catch(() => false);
        }
        check(answered, "the shell's answer in the serial terminal: " + serial_rows.textContent.replace(/\s+/g, " ").slice(-300));
        log("serial terminal: typed echo v86-$((6*7)), the shell answered v86-42 (" + ((Date.now() - booted) / 1000).toFixed(0) + " s)");
        // (the display: the device model's 720x1280, the screen zoomed to the window; not a display of the window's size)
        await until(() => /Graphics 720×1280/.test(c.body.textContent), "the display at the device's 720×1280", 900000);
        log("display: 720×1280, the device's (" + ((Date.now() - booted) / 1000).toFixed(0) + " s)");
        await emulator.destroy();
    },
    async service()
    {
        const service = args.get("service");
        check(service, "the runner's disk service (service=1)");
        await open_library();
        $("#preferences").click();
        const prefs = await until(() => $("dialog[open]"), "the preferences");
        set(prefs.querySelector("input[aria-label='Disk service URL']"), service);
        button("Test", prefs).click();
        await until(() => /A disk service: 1 images, creates new ones/.test(prefs.textContent), "the test of the service");
        button("Save", prefs).click();
        await until(() => $("#service_status").textContent === "Disk service: " + service, "the library using the disk service");
        log("Preferences: " + service + ", tested; the library shows it");
        const summary = await wizard({ source: "A CD or DVD image", urls: { "CD image": "images/linux4.iso" }, preset: "linux", name: "Kept disk", disk: "service", disk_mb: 16 });
        check(/read write/.test(summary) || /created when finished/.test(summary), "the summary: " + summary);
        const files = await (await fetch("/__service_files")).json();
        const kept = files.find(f => f.name === "kept-disk.img");
        check(files.length === 2 && kept && kept.size === 16 << 20, "the service's files: " + JSON.stringify(files));
        const table = await until(() => table_text($(".hardware")).includes(service + "kept-disk.img") && table_text($(".hardware")), "the machine's disk");
        check(/read write/.test(table), "the machine's disk: " + table);
        log("the wizard's new disk: " + kept.name + " (" + kept.size + " bytes) in the service's directory, read write");
    },
};

parts[part]().then(() =>
{
    document.getElementById("result").textContent = "PASS (" + part + ")\n" + lines.join("\n");
}, e =>
{
    document.getElementById("result").textContent = "FAIL (" + part + "): " + (e.stack || e.message) + "\n" + lines.join("\n");
});
</script>
                     source/v64/tests/bench/compare.mjs                                                                  0000755 0000000 0000000 00000004774 00000000000 014265  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Compares two configurations of one core (docs/jit-unification-plan.md P0.8):
// N sessions of tests/bench/run.mjs, each with the arm under test (the JIT
// switches of --switches-a) and the baseline arm (--switches-b) on the same
// core, the runner alternating the arms' order within each benchmark; then
// tests/bench/gate.mjs judges the sessions. With --aa both arms run
// --switches-a, which measures the noise a gate has to stay clear of.
//
// Usage: tests/bench/compare.mjs --switches-a "name=value,..." [--switches-b "..."]
//        [--wasm build/v86.wasm] [--sessions 3] [--level R|F|S|D]
//        [--target name,...] [--quick] [--filter re] [--runs n] [--aa]
// The session files go to build/bench/compare-<time>-<n>.json.

import { spawnSync } from "node:child_process";
import path from "node:path";
import url from "node:url";

const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "../..");
const args = process.argv.slice(2);
const value = name => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };
const flag = name => args.includes(name);

const switches_a = value("--switches-a") || "";
const aa = flag("--aa");
const switches_b = aa ? switches_a : value("--switches-b") || "";
if(!aa && switches_a === switches_b)
{
    console.error("compare.mjs: --switches-a and --switches-b are the same; use --aa to measure the noise");
    process.exit(2);
}
const sessions = Number(value("--sessions") || 3);
const level = value("--level") || "R";
const stamp = new Date().toISOString().replace(/[:.]/g, "-");

const run_args = ["--wasm", value("--wasm") || "build/v86.wasm", "--switches-a", switches_a, "--switches-b", switches_b];
if(flag("--quick")) run_args.push("--quick");
for(const name of ["--filter", "--runs"]) if(value(name) !== undefined) run_args.push(name, value(name));

const files = [];
for(let n = 1; n <= sessions; n++)
{
    const out = `build/bench/compare-${stamp}-${n}.json`;
    console.log(`[compare] session ${n}/${sessions}: ${switches_a || "(defaults)"} against ${switches_b || "(defaults)"}`);
    const r = spawnSync("node", ["tests/bench/run.mjs", ...run_args, "--out", out], { cwd: ROOT, stdio: "inherit" });
    if(r.status !== 0) process.exit(r.status ?? 1);
    files.push(out);
}

const gate_args = aa ? ["--aa"] : ["--level", level, ...value("--target") ? ["--target", value("--target")] : []];
const r = spawnSync("node", ["tests/bench/gate.mjs", ...gate_args, ...files], { cwd: ROOT, stdio: "inherit" });
process.exit(r.status ?? 1);
    source/v64/tests/bench/gate.mjs                                                                     0000755 0000000 0000000 00000020122 00000000000 013540  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Gate decisions over benchmark sessions (docs/jit-unification-plan.md,
// cross-phase rule 2 and P0.8). Each session is a result file of
// tests/bench/run.mjs with the arm under test (--arm, default "ir") and a
// baseline arm. Per benchmark, the median over the sessions of the warm ratio
// (baseline time / arm time; above 1 is faster) is judged:
//
//   --level R  the suite's geometric mean >= 0.99 and each benchmark >= 0.97.
//              A benchmark below 0.97 is retested with --runs 7, and at 4
//              times the work when its runs last under 40 ms (the command is
//              printed); --retest file.json replaces its ratio by the
//              retest's (repeated: the last file with the benchmark).
//   --level F  each --target benchmark >= 1.05 and the suite >= 1.00.
//   --level S  the same-source members: int, memory and control benchmarks
//              whose instruction and data ratios (x86-64 / i686, fields of
//              make bench-same-source) are within 0.8-1.25, 563.memops
//              excluded: geometric mean >= 1.00, each >= 0.85.
//   --level D  the suite's geometric mean >= 1.00, each benchmark >= 0.95.
//   --aa       the sessions ran one core against itself: print the noise
//              (each benchmark's ratio range), no decision.
//
// The thresholds hold for medians of 3 alternating sessions or more; fewer
// sessions are judged with a warning. Exit status 0 when the gate passes.
//
// Usage: tests/bench/gate.mjs --level R|F|S|D [--target name,...] [--arm ir]
//        [--retest retest.json]... [--json out.json] [--aa] session.json...

import fs from "node:fs";

const LEVELS = {
    R: { suite: 0.99, each: 0.97, retest: true },
    F: { suite: 1.00, each: 0, target: 1.05 },
    S: { suite: 1.00, each: 0.85 },
    D: { suite: 1.00, each: 0.95 },
};
const SAME_SOURCE_CATEGORIES = new Set(["int", "memory", "control"]);
const SAME_SOURCE_EXCLUDED = new Set(["563.memops"]);

const args = process.argv.slice(2);
const value = name => { const i = args.indexOf(name); return i >= 0 ? args.splice(i, 2)[1] : undefined; };
const flag = name => { const i = args.indexOf(name); if(i >= 0) args.splice(i, 1); return i >= 0; };
const level = value("--level"), arm = value("--arm") || "ir", json_file = value("--json");
// (--retest may repeat: a later file's ratio replaces an earlier one's)
const retest_files = [];
for(let file; (file = value("--retest")) !== undefined;) retest_files.push(file);
const targets = (value("--target") || "").split(",").filter(Boolean);
const aa = flag("--aa");
const files = args;
if(!files.length || !aa && !LEVELS[level])
{
    console.error("usage: tests/bench/gate.mjs --level R|F|S|D [--target name,...] [--arm ir] [--retest f.json] [--json out.json] [--aa] session.json...");
    process.exit(2);
}

const median = values => {
    const s = [...values].sort((a, b) => a - b);
    return s.length % 2 ? s[s.length >> 1] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2;
};
const geomean = values => Math.exp(values.reduce((sum, v) => sum + Math.log(v), 0) / values.length);

/** {name: {category, ratios: [warm ratio per session], ...fields}} */
function collect(paths)
{
    const benchmarks = new Map();
    for(const p of paths)
    {
        const session = JSON.parse(fs.readFileSync(p, "utf8"));
        for(const r of session.results)
        {
            const a = r.arms?.[arm];
            if(r.error || !a || !(a.warm_ratio > 0)) continue;
            if(!benchmarks.has(r.name)) benchmarks.set(r.name, { category: r.category, ratios: [], ms: [], instruction_ratio: r.instruction_ratio, data_ratio: r.data_ratio });
            benchmarks.get(r.name).ratios.push(a.warm_ratio);
            if(a.warm > 0) benchmarks.get(r.name).ms.push(a.warm);
        }
    }
    return benchmarks;
}

const sessions = collect(files);
if(!sessions.size)
{
    console.error(`no results of the arm "${arm}" with a baseline in ${files.join(", ")}`);
    process.exit(2);
}

if(aa)
{
    console.log(`A/A noise over ${files.length} sessions (warm ratio, ideally 1):`);
    const spreads = [];
    for(const [name, b] of sessions)
    {
        const low = Math.min(...b.ratios), high = Math.max(...b.ratios);
        spreads.push(Math.max(high - 1, 1 - low));
        console.log(`  ${name.padEnd(18)} median ${median(b.ratios).toFixed(3)}  range ${low.toFixed(3)}-${high.toFixed(3)}`);
    }
    console.log(`suite geometric mean ${geomean([...sessions.values()].map(b => median(b.ratios))).toFixed(3)}; ` +
        `largest deviation ${Math.max(...spreads).toFixed(3)}, median deviation ${median(spreads).toFixed(3)}`);
    process.exit(0);
}

const rules = LEVELS[level];
const retest = new Map();
for(const file of retest_files) for(const [name, b] of collect([file])) retest.set(name, b);
let members = [...sessions.entries()];
if(level === "S")
{
    members = members.filter(([name, b]) => SAME_SOURCE_CATEGORIES.has(b.category) && !SAME_SOURCE_EXCLUDED.has(name) &&
        b.instruction_ratio >= 0.8 && b.instruction_ratio <= 1.25 && b.data_ratio >= 0.8 && b.data_ratio <= 1.25);
    if(!members.length)
    {
        console.error("level S: no benchmark has instruction_ratio and data_ratio within 0.8-1.25 (make bench-same-source results)");
        process.exit(2);
    }
}

const rows = members.map(([name, b]) => {
    const retested = retest.get(name);
    const ratio = retested ? median(retested.ratios) : median(b.ratios);
    return { name, category: b.category, sessions: b.ratios.length, ratio, retested: !!retested };
});
const suite = geomean(rows.map(r => r.ratio));
const problems = [];
if(suite < rules.suite) problems.push(`geometric mean ${suite.toFixed(3)} < ${rules.suite}`);
const below = rows.filter(r => r.ratio < rules.each);
for(const r of below) problems.push(`${r.name} ${r.ratio.toFixed(3)} < ${rules.each}` + (rules.retest && !r.retested ? " (retest with --runs 7)" : ""));
for(const name of targets)
{
    const r = rows.find(r => r.name === name);
    if(!r) problems.push(`target ${name}: no result`);
    else if(r.ratio < rules.target) problems.push(`target ${name} ${r.ratio.toFixed(3)} < ${rules.target}`);
}
if(level === "F" && !targets.length) problems.push("level F needs --target");

const fewest = Math.min(...rows.map(r => r.sessions));
console.log(`gate ${level} over ${files.length} session(s), arm "${arm}"${retest_files.length ? ", retest " + retest_files.join(", ") : ""}`);
if(fewest < 3) console.log(`warning: ${fewest} session(s) for some benchmarks; the thresholds hold for medians of 3 or more`);
for(const r of rows)
{
    const mark = r.ratio < rules.each ? "  <" : "";
    console.log(`  ${r.name.padEnd(18)} ${r.category.padEnd(8)} ${r.ratio.toFixed(3)}${r.retested ? " (retest)" : ""}${mark}`);
}
console.log(`geometric mean ${suite.toFixed(3)} (${rows.length} benchmarks)`);
const retests = rules.retest ? below.filter(r => !r.retested) : [];
if(retests.length)
{
    const session = JSON.parse(fs.readFileSync(files[0], "utf8"));
    const wasm = label => session.arms?.find(a => a.label === label)?.wasm;
    // (two configurations of one core, tests/bench/compare.mjs: their switches)
    const switches = label => Object.entries(session.arms?.find(a => a.label === label)?.switches || {}).map(([k, v]) => `${k}=${v}`).join(",");
    const configured = [["--switches-a", switches(arm)], ["--switches-b", switches("baseline")]].filter(([, v]) => v).map(([f, v]) => ` ${f} ${v}`).join("");
    // Runs of a few milliseconds are decided by a millisecond: a benchmark
    // shorter than 40 ms per run is retested at 4 times the work (a 718.avx.ymm
    // at 0.89 over 9 ms runs was 1.00 over 35 ms runs).
    const short = retests.some(r => median(sessions.get(r.name).ms) < 40);
    console.log(`retest: node tests/bench/run.mjs --filter '^(${retests.map(r => r.name.split(".")[0]).join("|")})' --runs 7` +
        `${short ? " --scale 4" : ""} --wasm ${wasm(arm)} --baseline ${wasm("baseline")}${configured} --out retest.json`);
}
if(json_file) fs.writeFileSync(json_file, JSON.stringify({ level, arm, sessions: files, suite, rows, problems }, null, 1));
console.log(problems.length ? "FAILED: " + problems.join("; ") : `gate ${level}: passed`);
process.exit(problems.length ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/bench/lib/bench.h                                                                  0000644 0000000 0000000 00000001753 00000000000 014111  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Freestanding helpers shared by the benchmark kernels.
#ifndef BENCH_H
#define BENCH_H
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef int i32;
typedef unsigned long long u64;
typedef long long i64;
#define NOINLINE __attribute__((noinline))
#define UNUSED __attribute__((unused))

// (size_t: unsigned int for i686, a 64-bit count for x86-64)
typedef __SIZE_TYPE__ size_t;
void *memcpy(void *dst, const void *src, size_t n);
void *memset(void *dst, int value, size_t n);
void *memmove(void *dst, const void *src, size_t n);
int memcmp(const void *a, const void *b, size_t n);

// FNV-1a style accumulation of results into the checksum.
static inline u32 mix(u32 h, u32 v) { return (h ^ v) * 0x01000193u; }
static inline u32 lcg(u32 *state) { return *state = *state * 1664525u + 1013904223u; }
// Keep a value observable without a memory round trip the optimizer can drop.
#define KEEP(x) __asm__ volatile("" : : "r"(x))

u32 bench_main(u32 iterations);
#endif
                     source/v64/tests/bench/lib/boot.asm                                                                 0000644 0000000 0000000 00000005130 00000000000 014317  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; v86 CPU benchmark BIOS. Enters flat 32-bit protected mode with 4 KiB paging
; identity-mapping the first 64 MiB, enables x87/SSE, installs exception
; handlers that report the vector, then signals readiness and halts.
;
; Memory map: 0x500 ready marker (0xCAFE), 0x600 parameter block (see
; lib/crt0.asm), 0x7000 IDT, 0x10000 page directory, 0x11000-0x20FFF page
; tables, stack below 0x3F0000, benchmark images from 0x400000.
bits 16
org 0
    cli
    lgdt [cs:gdtr]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:0xF0000 + protected
bits 32
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov fs, ax
    mov gs, ax
    mov esp, 0x3F0000
    cld
    ; Page directory: 16 tables for 64 MiB.
    xor eax, eax
    mov edi, 0x10000
    mov ecx, 1024
    rep stosd
    mov edi, 0x10000
    mov eax, 0x11003
    mov ecx, 16
.pde:
    stosd
    add eax, 4096
    loop .pde
    mov edi, 0x11000
    mov eax, 3
    mov ecx, 16 * 1024
.pte:
    stosd
    add eax, 4096
    loop .pte
    ; IDT: vectors 0-31 report the exception; the rest are absent.
    xor eax, eax
    mov edi, 0x7000
    mov ecx, 512
    rep stosd
    mov edi, 0x7000
    mov ebx, 0xF0000 + fault0
    xor ecx, ecx
.idt:
    mov eax, ebx
    mov [edi], ax
    mov word [edi + 2], 8
    mov word [edi + 4], 0x8E00
    shr eax, 16
    mov [edi + 6], ax
    add edi, 8
    add ebx, fault1 - fault0
    inc ecx
    cmp ecx, 32
    jb .idt
    lidt [0xF0000 + idtr]
    mov eax, 0x10000
    mov cr3, eax
    ; CR0: PG, NE, MP; clear EM and TS. CR4: OSFXSR, OSXMMEXCPT.
    mov eax, cr0
    or eax, 0x80000022
    and eax, ~0xC
    mov cr0, eax
    mov eax, cr4
    or eax, 0x600
    mov cr4, eax
    ; With XSAVE (CPUID.1:ECX bit 26): CR4.OSXSAVE and XCR0 with x87 and SSE
    ; state, and AVX state with AVX (bit 28)
    mov eax, 1
    cpuid
    bt ecx, 26
    jnc .no_xsave
    mov eax, cr4
    or eax, 1 << 18
    mov cr4, eax
    mov eax, 3
    bt ecx, 28
    jnc .no_avx
    mov eax, 7
.no_avx:
    xor ecx, ecx
    xor edx, edx
    xsetbv
.no_xsave:
    fninit
    mov dword [0x500], 0xCAFE
    hlt
    jmp $
    ; One 32-byte stub per vector: record 0x80000000 | vector, then halt.
align 32
fault0:
%assign vector 0
%rep 32
    mov dword [0x608], 0x80000000 | vector
    mov eax, [esp]
    mov [0x60C], eax
    hlt
    jmp $
    align 32
%assign vector vector + 1
%endrep
fault1 equ fault0 + 32
align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr:
    dw 23
    dd 0xF0000 + gdt
idtr:
    dw 32 * 8 - 1
    dd 0x7000
times 0xFFF0 - ($ - $$) db 0xF4
bits 16
    jmp 0xF000:start
start equ 0
times 0x10000 - ($ - $$) db 0xF4
                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/bench/lib/crt0.asm                                                                 0000644 0000000 0000000 00000001025 00000000000 014223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Benchmark entry. Parameter block: [0x600] iterations (in), [0x604] checksum
; (out), [0x608] status (0 running, 1 done, 0x80000000|vector on exception),
; [0x60C] faulting EIP. Interrupts stay disabled.
bits 32
global _start
global ___chkstk_ms
extern _bench_main
section .text
_start:
    mov esp, 0x3F0000
    push dword [0x600]
    call _bench_main
    add esp, 4
    mov [0x604], eax
    mov dword [0x608], 1
    hlt
    jmp $
; MinGW probes stack frames above 4 KiB; the benchmark stack is fully mapped.
___chkstk_ms:
    ret
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/bench/lib/crt0_64.asm                                                              0000644 0000000 0000000 00000001513 00000000000 014536  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Benchmark entry for x86-64 PE32+ images (lib/long_mode.asm boots them).
; Parameter block as in lib/crt0.asm: [0x600] iterations (in), [0x604]
; checksum (out), [0x608] status (0 running, 1 done, 0x80000000|vector on
; exception), [0x60C] faulting RIP (a qword). Interrupts stay disabled.
; bench_main(iterations) follows the Microsoft x64 convention: the argument
; in ECX, 32 bytes of shadow space above the return address.
bits 64
default rel
global _start
global ___chkstk_ms
extern bench_main
section .text
_start:
    ; (16-byte aligned at the call, which the shadow space keeps)
    mov rsp, 0x3F0000
    sub rsp, 32
    mov ecx, [abs 0x600]
    call bench_main
    mov [abs 0x604], eax
    mov dword [abs 0x608], 1
    hlt
    jmp $
; MinGW probes stack frames above 4 KiB; the benchmark stack is fully mapped.
___chkstk_ms:
    ret
                                                                                                                                                                                     source/v64/tests/bench/lib/long_mode.asm                                                            0000644 0000000 0000000 00000011216 00000000000 015321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; v86 CPU benchmark boot for x86-64 images (docs/jit-unification-plan.md
; P0.2): a multiboot kernel that enters 64-bit mode with the first 1 GiB
; identity mapped, enables x87/SSE (and XSAVE/AVX when CPUID reports them),
; installs 64-bit exception stubs that report the vector, then signals
; readiness and halts in 64-bit mode. tests/bench/run.mjs --isa x86_64 then
; loads a PE32+ image (lib/crt0_64.asm) and starts it at its entry.
;
; Memory map as with lib/boot.asm: 0x500 ready marker (0xCAFE), 0x600
; parameter block (lib/crt0_64.asm; the faulting RIP is the qword at 0x60C),
; 0x7000 IDT, 0x10000 PML4, 0x11000 PDPT, 0x12000 page directory, stack
; below 0x3F0000, benchmark images from 0x400000, this boot at 1 MiB.
;
; LARGE_PAGES (nasm -D, default 1): 2 MiB pages throughout, as the review's
; prototype and Windows' kernel mappings; 0 maps the first 64 MiB with 4 KiB
; pages (page tables at 0x13000-0x32FFF).
;
; COMPAT (nasm -D, default 0; P0.2b): 1 halts in compatibility mode instead,
; in the 32-bit code segment 8, so that run.mjs --isa compat32 starts the
; i686 images (lib/crt0.asm) there: 32-bit code under a 64-bit OS, as WOW64.
; Exceptions still go through the 64-bit IDT.
%ifndef LARGE_PAGES
%define LARGE_PAGES 1
%endif
%ifndef COMPAT
%define COMPAT 0
%endif
bits 32
org 0x100000
header:
    dd 0x1BADB002, 0x10000, -(0x1BADB002 + 0x10000)
    dd header, header, image_end, image_end, start
start:
    cli
    cld
    lgdt [gdtr]
    jmp 8:protected
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov fs, ax
    mov gs, ax
    mov esp, 0x3F0000
    ; PML4, PDPT and page directory: zeroed, then one entry each.
    xor eax, eax
    mov edi, 0x10000
    mov ecx, 3 * 1024
    rep stosd
    mov dword [0x10000], 0x11003
    mov dword [0x11000], 0x12003
    ; Page directory: 512 large pages of 2 MiB (1 GiB).
    mov edi, 0x12000
    mov eax, 0x83
    mov ecx, 512
.pde:
    mov [edi], eax
    add eax, 0x200000
    add edi, 8
    loop .pde
%if LARGE_PAGES == 0
    ; The first 64 MiB in 4 KiB pages instead: 32 page tables.
    mov edi, 0x13000
    mov eax, 3
    mov ecx, 32 * 512
.pte:
    mov [edi], eax
    mov dword [edi + 4], 0
    add eax, 4096
    add edi, 8
    loop .pte
    mov edi, 0x12000
    mov eax, 0x13003
    mov ecx, 32
.pt:
    mov [edi], eax
    add eax, 4096
    add edi, 8
    loop .pt
%endif
    ; CR4.PAE, CR3, EFER.LME, then CR0.PG: compatibility mode until the far jump.
    mov eax, cr4
    or eax, 0x20
    mov cr4, eax
    mov eax, 0x10000
    mov cr3, eax
    mov ecx, 0xC0000080
    rdmsr
    or eax, 0x100
    wrmsr
    mov eax, cr0
    or eax, 0x80000001
    mov cr0, eax
    jmp 24:long_mode
bits 64
; (the parameter block and IDT addresses are absolute)
default abs
long_mode:
    mov rsp, 0x3F0000
    ; IDT: vectors 0-31 report the exception; the rest are absent.
    xor eax, eax
    mov edi, 0x7000
    mov ecx, 512
    rep stosq
    mov edi, 0x7000
    mov rbx, fault0
    xor ecx, ecx
.idt:
    mov rax, rbx
    mov [rdi], ax
    mov word [rdi + 2], 24
    mov word [rdi + 4], 0x8E00
    shr rax, 16
    mov [rdi + 6], ax
    shr rax, 16
    mov [rdi + 8], eax
    add rdi, 16
    add rbx, fault1 - fault0
    inc ecx
    cmp ecx, 32
    jb .idt
    lidt [idtr]
    ; CR0: NE, MP; clear EM and TS. CR4: OSFXSR, OSXMMEXCPT.
    mov rax, cr0
    or eax, 0x22
    and eax, ~0xC
    mov cr0, rax
    mov rax, cr4
    or eax, 0x600
    mov cr4, rax
    ; With XSAVE (CPUID.1:ECX bit 26): CR4.OSXSAVE and XCR0 with x87 and SSE
    ; state, and AVX state with AVX (bit 28)
    mov eax, 1
    cpuid
    bt ecx, 26
    jnc .no_xsave
    mov rax, cr4
    or eax, 1 << 18
    mov cr4, rax
    mov eax, 3
    bt ecx, 28
    jnc .no_avx
    mov eax, 7
.no_avx:
    xor ecx, ecx
    xor edx, edx
    xsetbv
.no_xsave:
    fninit
%if COMPAT
    ; (RETF with 64-bit operands: to the 32-bit code segment)
    push 8
    mov rax, compat_mode
    push rax
    o64 retf
bits 32
compat_mode:
    mov dword [0x500], 0xCAFE
    hlt
    jmp $
bits 64
%else
    mov dword [0x500], 0xCAFE
    hlt
    jmp $
%endif
    ; One 32-byte stub per vector: record 0x80000000 | vector and the
    ; faulting RIP (above the error code where the vector pushes one).
align 32
fault0:
%assign vector 0
%rep 32
    mov dword [0x608], 0x80000000 | vector
%if vector == 8 || (vector >= 10 && vector <= 14) || vector == 17 || vector == 21 || vector == 29 || vector == 30
    mov rax, [rsp + 8]
%else
    mov rax, [rsp]
%endif
    mov [0x60C], rax
    hlt
    jmp $
    align 32
%assign vector vector + 1
%endrep
fault1 equ fault0 + 32
align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF, 0x00AF9A000000FFFF
gdtr:
    dw 31
    dd gdt
idtr:
    dw 32 * 16 - 1
    dq 0x7000
image_end:
                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/bench/lib/rt.c                                                                     0000644 0000000 0000000 00000002376 00000000000 013454  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Freestanding C runtime: string primitives in the REP form used by the
// MSVC runtime of the era, so they exercise v86's string instruction paths.
#include "bench.h"

void *memcpy(void *dst, const void *src, size_t n)
{
    void *d = dst;
    size_t words = n >> 2;
    __asm__ volatile("rep movsl" : "+D"(d), "+S"(src), "+c"(words) : : "memory");
    n &= 3;
    __asm__ volatile("rep movsb" : "+D"(d), "+S"(src), "+c"(n) : : "memory");
    return dst;
}
void *memset(void *dst, int value, size_t n)
{
    void *d = dst;
    u32 fill = (u8)value * 0x01010101u;
    size_t words = n >> 2;
    __asm__ volatile("rep stosl" : "+D"(d), "+c"(words) : "a"(fill) : "memory");
    n &= 3;
    __asm__ volatile("rep stosb" : "+D"(d), "+c"(n) : "a"(fill) : "memory");
    return dst;
}
void *memmove(void *dst, const void *src, size_t n)
{
    if(dst <= src || (const u8 *)dst >= (const u8 *)src + n) return memcpy(dst, src, n);
    const u8 *s = (const u8 *)src + n - 1;
    u8 *d = (u8 *)dst + n - 1;
    __asm__ volatile("std; rep movsb; cld" : "+D"(d), "+S"(s), "+c"(n) : : "memory");
    return dst;
}
int memcmp(const void *a, const void *b, size_t n)
{
    const u8 *x = a, *y = b;
    for(size_t i = 0; i < n; i++)
        if(x[i] != y[i]) return x[i] - y[i];
    return 0;
}
                                                                                                                                                                                                                                                                  source/v64/tests/bench/machine.mjs                                                                  0000644 0000000 0000000 00000014372 00000000000 014233  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The benchmark machines (tests/bench/run.mjs, tools/replay_record.mjs): PE
// images, a machine booted for an arm's ISA, and one timed run.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../build/libv86.mjs";
import { STATE_OFFSETS as OWN_STATE_OFFSETS } from "../../src/state_layout.js";

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// Minimal PE loader: sections at ImageBase + VirtualAddress, zero-filled to
// VirtualSize. Writable sections are restored before every run. PE32 and
// PE32+ (linked below 4 GiB).
export function load_pe(file) {
    const b = fs.readFileSync(file), pe = b.readUInt32LE(0x3C);
    assert.equal(b.readUInt32LE(pe), 0x4550, `${file}: not a PE image`);
    const sections = b.readUInt16LE(pe + 6), optional = pe + 24, table = optional + b.readUInt16LE(pe + 20);
    const pe32plus = b.readUInt16LE(optional) === 0x20B;
    const base = pe32plus ? Number(b.readBigUInt64LE(optional + 24)) : b.readUInt32LE(optional + 28);
    assert(base < 2 ** 32 - 0x1000000, `${file}: image base above 4 GiB`);
    const entry = base + b.readUInt32LE(optional + 16);
    const parts = [];
    for(let i = 0; i < sections; i++) {
        const s = table + 40 * i;
        const virtual_size = b.readUInt32LE(s + 8), address = base + b.readUInt32LE(s + 12);
        const raw_size = b.readUInt32LE(s + 16), raw = b.readUInt32LE(s + 20), flags = b.readUInt32LE(s + 36);
        const bytes = new Uint8Array(Math.max(virtual_size, raw_size));
        bytes.set(b.subarray(raw, raw + Math.min(raw_size, bytes.length)));
        parts.push({ name: b.toString("latin1", s, s + 8).replace(/\0+$/, ""), address, bytes, writable: !!(flags & 0x80000000) });
    }
    return { entry, parts };
}

/**
 * The boot images of the manifest (build/bench/manifest.json) by ISA: the
 * benchmark BIOS for i686, the long-mode boot for x86_64 (with 4 KiB pages
 * if `small_pages`) and its compatibility-mode variant for compat32
 */
export function boot_images(manifest, small_pages = false) {
    const read = file => file && fs.readFileSync(file);
    return {
        i686: read(manifest.boot),
        x86_64: read(small_pages ? manifest.boot64_small_pages : manifest.boot64),
        compat32: read(manifest.boot_compat),
    };
}

// (a benchmark's cpu_features: the optional CPU features its guest uses;
// cpu_type: the x86-64 profile for its own ones, such as LZCNT. An x86_64
// arm boots the long-mode boot with the x86-64 profile. `extra`: JIT
// switches over the arm's; `ir_setup`: [export, value] calls after boot.)
export async function create(arm, bench, boots, { extra = {}, ir_setup = [] } = {}) {
    const jit_switches = { ...arm.switches, ...extra };
    const boot = boots[arm.isa];
    assert(boot, `no boot image for ${arm.isa}`);
    // (an arm of another tree brings its own V86 and state layout: run.mjs
    // --baseline-root)
    const vm = new (arm.V86 || V86)({
        graphics_adapter: "bochs_vga",
        wasm_path: arm.wasm, memory_size: 128 << 20,
        ...bench.cpu_features ? { cpu_features: bench.cpu_features, cpu_features_unreleased: !!bench.cpu_features_unreleased } : {},
        ...arm.isa === "i686" ? { ...bench.cpu_type ? { cpu_type: bench.cpu_type } : {}, bios: { buffer: Uint8Array.from(boot).buffer } } :
            { cpu_type: "x86_64", multiboot: { buffer: Uint8Array.from(boot).buffer } },
        ...arm.interpreted ? { disable_jit: true } : {},
        disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
        ...Object.keys(jit_switches).length ? { jit_switches } : {},
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu;
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    vm.run();
    const end = performance.now() + 15000;
    while(view().getUint32(0x500, true) !== 0xCAFE) { assert(performance.now() < end, "benchmark BIOS did not start"); await sleep(1); }
    await vm.stop();
    for(const [name, value] of ir_setup) {
        assert.equal(typeof cpu.wm.exports[name], "function", `--ir-setup: no export ${name}`);
        assert(cpu.wm.exports[name](Number(value)), `--ir-setup: ${name}(${value}) refused`);
    }
    return { vm, cpu, e: cpu.wm.exports, view, arm };
}

/** One run of `image` with `iterations`: { ms, instructions (the budget counter), checksum } */
export async function execute(machine, image, iterations) {
    const { vm, cpu, e, view } = machine;
    const STATE_OFFSETS = machine.arm.state_offsets || OWN_STATE_OFFSETS;
    for(const part of image.parts) if(part.writable || !machine.loaded) cpu.mem8.set(part.bytes, part.address);
    machine.loaded = true;
    const v = view();
    v.setUint32(0x600, iterations, true); v.setUint32(0x604, 0, true); v.setUint32(0x608, 0, true);
    cpu.reg32.fill(0);
    if(machine.arm.isa !== "i686") {
        // (the upper halves, R8-R15 and RIP's upper half: the 64-bit register file)
        const words = (offset, n) => new Uint32Array(cpu.wasm_memory.buffer, cpu.state_base + offset, n);
        words(STATE_OFFSETS.x64_gpr_hi, 16).fill(0);
        words(STATE_OFFSETS.x64_gpr_ext_lo, 8).fill(0);
        words(STATE_OFFSETS.x64_rip_hi, 1)[0] = 0;
    }
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0; cpu.instruction_pointer[0] = image.entry;
    e.fpu_discard_cache(); cpu.fpu_st.fill(0); cpu.fpu_stack_empty[0] = 255; cpu.fpu_stack_ptr[0] = 0;
    e.set_control_word(0x37F); cpu.fpu_status_word[0] = 0; cpu.mxcsr[0] = 0x1F80;
    e.update_state_flags();
    const counter = new Uint32Array(e.memory.buffer);
    counter[664 >> 2] = 0;
    const started = performance.now();
    vm.run();
    const limit = started + 120000;
    while(!cpu.in_hlt[0]) { assert(performance.now() < limit, "benchmark timeout"); await sleep(0); }
    const ms = performance.now() - started;
    await vm.stop();
    const status = view().getUint32(0x608, true);
    if(status !== 1) throw new Error(status >>> 31 ? `guest exception ${status & 31} at ${view().getUint32(0x60C, true).toString(16)}` : `guest did not finish (${status})`);
    return { ms, instructions: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0, checksum: view().getUint32(0x604, true) };
}
                                                                                                                                                                                                                                                                      source/v64/tests/bench/report.mjs                                                                   0000644 0000000 0000000 00000005537 00000000000 014145  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Summarize a benchmark result file, or compare two (before -> after).
//   node tests/bench/report.mjs results.json [previous.json] [--arm ir] [--markdown]
// Ratios are against the file's reference arm: the --baseline core ("baseline"),
// or "legacy" in results recorded before IR became the only backend. Without
// one, only MIPS are shown. The comparison reports the arm's own speedup
// between the two files, which is independent of that reference.
import fs from "node:fs";

const args = process.argv.slice(2);
const files = args.filter(a => !a.startsWith("--") && !args[args.indexOf(a) - 1]?.startsWith("--arm"));
const arm = args.includes("--arm") ? args[args.indexOf("--arm") + 1] : "ir";
const markdown = args.includes("--markdown");
const [current, previous] = files.map(f => JSON.parse(fs.readFileSync(f, "utf8")));
if(!current) { console.error("usage: report.mjs results.json [previous.json] [--arm ir] [--markdown]"); process.exit(2); }

const fmt = (v, digits = 2) => v === null || v === undefined || Number.isNaN(v) ? "-" : v.toFixed(digits);
const reference = ["baseline", "legacy"].find(name => name !== arm && current.results.some(r => r.arms?.[name]));
const rows = [];
const header = ["benchmark", "category", `${reference ?? "reference"} MIPS`, `${arm} MIPS`, "warm x", "cold x"];
if(previous) header.push(`${arm} vs prev`);
for(const r of current.results) {
    const a = r.arms?.[arm], l = reference && r.arms?.[reference];
    if(!a || r.error) { rows.push([r.name, r.category, "error", r.error || "-", "", ""]); continue; }
    const row = [r.name, r.category, fmt(l?.warm_mips, 0), fmt(a.warm_mips, 0), fmt(a.warm_ratio), fmt(a.cold_ratio)];
    if(previous) {
        const p = previous.results.find(x => x.name === r.name)?.arms?.[arm];
        row.push(p?.warm ? fmt(p.warm / a.warm) : "-");
    }
    rows.push(row);
}
const s = current.scores?.[arm];
if(markdown) {
    console.log(`| ${header.join(" | ")} |\n|${header.map(() => "---").join("|")}|`);
    for(const row of rows) console.log(`| ${row.join(" | ")} |`);
}
else {
    const widths = header.map((h, i) => Math.max(h.length, ...rows.map(r => String(r[i] ?? "").length)));
    const line = cells => cells.map((c, i) => String(c ?? "").padEnd(widths[i])).join("  ");
    console.log(line(header));
    for(const row of rows) console.log(line(row));
}
if(s) {
    console.log(`\n${arm} vs ${reference} (${current.revision ?? "?"}, ${current.date}): warm ${fmt(s.warm, 3)}, cold ${fmt(s.cold, 3)}`);
    for(const [c, v] of Object.entries(s.categories)) console.log(`  ${c.padEnd(9)} warm ${fmt(v.warm, 3)}  cold ${fmt(v.cold, 3)}`);
}
if(previous?.scores?.[arm]) {
    const p = previous.scores[arm];
    console.log(`previous (${previous.revision ?? "?"}): warm ${fmt(p.warm, 3)}, cold ${fmt(p.cold, 3)}`);
}
if(current.errors?.length) console.log(`\nerrors:\n  ${current.errors.join("\n  ")}`);
                                                                                                                                                                 source/v64/tests/bench/run.mjs                                                                      0000644 0000000 0000000 00000042124 00000000000 013427  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// v86 CPU benchmark runner: identical guest work on each arm (the core under
// test and an optional baseline core), checked results, SPEC-style ratio scores.
//
//   node tests/bench/run.mjs [--filter re] [--runs 5] [--cold 3] [--scale 1]
//        [--wasm build/v86.wasm] [--baseline other.wasm]
//        [--baseline-root dir]   (the baseline is another tree at another
//            revision, built: its build/v86.wasm (unless --baseline) with its
//            build/libv86.mjs and state layout, as a core and the JavaScript
//            of another revision do not always agree)
//        [--xp image.img] [--xp-runs 3] [--out file.json] [--quick]
//        [--ir-setup "export=value,..."]   (calls on every arm after boot)
//        [--switches-a "name=value,..."] [--switches-b "name=value,..."]
//            (the JIT switches of the arm and of the baseline, over
//            JIT_SWITCHES; --switches-b without --baseline compares two
//            configurations of one core, see tests/bench/compare.mjs)
//        [--fallbacks]   (print the instructions the JITs most often leave to
//            the interpreter: the step profile of an extra round that is not
//            timed, tools/step_profile.mjs)
//        [--isa i686|x86_64|compat32]   (x86_64: the PE32+ builds of the C
//            benchmarks, started in 64-bit mode by build/bench/long_mode.bin,
//            where the x64 page tier runs them; --small-pages boots with 4 KiB
//            pages. compat32: the i686 images in compatibility mode under the
//            same paging, build/bench/long_mode_compat.bin)
//        [--same-source]   (the arm is the x86_64 build, the baseline the
//            i686 build of the same source, on one core unless --baseline;
//            each row gets instruction_ratio and data_ratio, x86-64 over
//            i686: tests/bench/gate.mjs --level S, make bench-same-source)
//        [--interpreter]   (one more arm without JIT, with the arm's ISA:
//            the reference its checksums must match)
//
// Build the suite first: node tools/bench/build.mjs (make bench-build).
//
// Measurements per benchmark and arm:
//   cold  first run in a fresh VM: JIT discovery, compilation and execution
//   warm  median of timed runs after the timings have stabilized
// Ratios are baseline time / arm time (above 1 means faster than the baseline);
// without --baseline only MIPS are reported. Scores are geometric means of the
// ratios per category and over the whole suite.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import assert from "node:assert/strict";
import { spawnSync, execSync } from "node:child_process";
import { parse_jit_switches, set_jit_switches } from "../../src/jit_switches.js";
import { jit_switches_from_env, jit_switches_of } from "../lib/jit_switches.mjs";
import { jit_stats, jit_stats_enabled } from "../../tools/bench/jit_stats.mjs";
import { step_profile } from "../../tools/step_profile.mjs";
import { load_pe, boot_images, create as create_machine, execute } from "./machine.mjs";

const root = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../..");
process.chdir(root);
const args = process.argv.slice(2);
const option = (name, fallback) => {
    const i = args.indexOf("--" + name);
    return i < 0 ? fallback : args[i + 1];
};
const flag = name => args.includes("--" + name);
const quick = flag("quick");
const runs = Number(option("runs", quick ? 3 : 5));
const cold_runs = Number(option("cold", quick ? 1 : 3));
const scale = Number(option("scale", quick ? 0.5 : 1));
const filter = option("filter") ? new RegExp(option("filter")) : null;
const wasm = option("wasm", "build/v86.wasm");
const baseline_root = option("baseline-root") && path.resolve(option("baseline-root"));
const baseline = option("baseline") || (baseline_root && path.join(baseline_root, "build/v86.wasm"));
const baseline_tree = baseline_root ? {
    V86: (await import(path.join(baseline_root, "build/libv86.mjs"))).V86,
    state_offsets: (await import(path.join(baseline_root, "src/state_layout.js"))).STATE_OFFSETS,
} : {};
const xp_image = option("xp");
const xp_runs = Number(option("xp-runs", 3));
const fallbacks = flag("fallbacks");
const same_source = flag("same-source");
const isa = same_source ? "x86_64" : option("isa", "i686");
assert(["i686", "x86_64", "compat32"].includes(isa), `--isa ${isa}: i686, x86_64 or compat32`);
const ir_setup = (option("ir-setup") || "").split(",").filter(Boolean).map(s => s.split("="));
const out = option("out", `build/bench/results-${new Date().toISOString().replace(/[:.]/g, "-")}.json`);
assert(Number.isInteger(runs) && runs >= 1 && Number.isInteger(cold_runs) && cold_runs >= 0 && scale > 0);

const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const wide = isa !== "i686" || same_source;
assert(!wide || manifest.boot64, "no x86-64 builds: install x86_64-w64-mingw32-gcc and make bench-build");
const boots = boot_images(manifest, flag("small-pages"));
const create = (arm, bench, extra = {}) => create_machine(arm, bench, boots, { extra, ir_setup });
const switches = name => ({ ...jit_switches_from_env(), ...parse_jit_switches(option(name)) });
const arms = [
    { label: "ir", isa, wasm, switches: switches("switches-a") },
    ...same_source ? [{ label: "baseline", isa: "i686", wasm: baseline || wasm, switches: switches("switches-b"), ...baseline_tree }] :
        baseline || option("switches-b") ? [{ label: "baseline", isa, wasm: baseline || wasm, switches: switches("switches-b"), ...baseline_tree }] : [],
    ...flag("interpreter") ? [{ label: "interpreter", isa, wasm, switches: {}, interpreted: true }] : [],
];
// The arm whose results another arm's must equal: the first one before it with its ISA
const reference_of = arm => arms.find(a => a !== arm && a.isa === arm.isa && arms.indexOf(a) < arms.indexOf(arm)) ??
    arms.find(a => a !== arm && a.isa === arm.isa);
const median = values => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
const geomean = values => values.length ? Math.exp(values.reduce((s, v) => s + Math.log(v), 0) / values.length) : null;

const results = [];
const errors = [];
const writable = image => image.parts.filter(p => p.writable).reduce((sum, p) => sum + p.bytes.length, 0);
for(const bench of manifest.benchmarks) {
    if(filter && !filter.test(bench.name)) continue;
    if(arms.some(a => a.isa === "x86_64") && !bench.image64) continue;
    const images = { i686: load_pe(bench.image), ...bench.image64 ? { x86_64: load_pe(bench.image64) } : {} };
    images.compat32 = images.i686;
    const iterations = Math.max(1, Math.round(bench.iterations * scale));
    const row = { name: bench.name, category: bench.category, about: bench.about, iterations, arms: {} };
    for(const arm of arms) row.arms[arm.label] = { cold_ms: [], warm_ms: [], warmup_ms: [], checksum: null, instructions: null };
    // (the x64 page tier counts instructions per block, an upper bound that
    // depends on where blocks were left: only its checksums must repeat; it
    // runs compat32's code too with x64_page_compat32, and i686 code with
    // x64_page_legacy32, a switch or the build's default: arm.legacy32)
    const page_tier = arm => !arm.interpreted && (arm.isa !== "i686" || arm.legacy32);
    const note = (arm, sample) => {
        const r = row.arms[arm.label], exact = !page_tier(arm);
        r.checksum ??= sample.checksum; r.instructions ??= sample.instructions;
        if(r.checksum !== sample.checksum || exact && r.instructions !== sample.instructions)
            errors.push(`${bench.name}/${arm.label}: nondeterministic result ${sample.checksum}/${sample.instructions}`);
    };
    try {
        for(let c = 0; c < cold_runs; c++) for(const arm of c % 2 ? [...arms].reverse() : arms) {
            const machine = await create(arm, bench);
            arm.legacy32 ??= jit_switches_of(machine.vm).x64_page_legacy32 === 1;
            try { const s = await execute(machine, images[arm.isa], iterations); note(arm, s); row.arms[arm.label].cold_ms.push(s.ms); }
            finally { await machine.vm.destroy(); }
        }
        const machines = [];
        try {
            for(const arm of arms) machines.push(await create(arm, bench));
            for(const m of machines) m.arm.legacy32 ??= jit_switches_of(m.vm).x64_page_legacy32 === 1;
            // Warm up until two consecutive runs of every arm agree within 5%.
            for(let w = 0; w < 30; w++) {
                for(const m of machines) { const s = await execute(m, images[m.arm.isa], iterations); note(m.arm, s); row.arms[m.arm.label].warmup_ms.push(s.ms); }
                if(w >= 3 && machines.every(m => { const t = row.arms[m.arm.label].warmup_ms.slice(-2); return Math.abs(t[0] - t[1]) <= 0.05 * Math.min(...t); })) break;
            }
            for(let r = 0; r < runs; r++) for(const m of r % 2 ? [...machines].reverse() : machines) {
                const s = await execute(m, images[m.arm.isa], iterations);
                note(m.arm, s);
                row.arms[m.arm.label].warm_ms.push(s.ms);
            }
            // (tools/bench/jit_stats.mjs, docs/jit-unification-plan.md P0.7)
            if(jit_stats_enabled())
            {
                for(const m of machines) row.arms[m.arm.label].jit_stats = jit_stats(m.vm, { script: "bench", benchmark: bench.name, arm: m.arm.label, wasm: m.arm.wasm });
            }
            // (docs/jit-unification-plan.md P0.8: the step profile slows
            // every step, so it runs in one more round, not timed)
            if(fallbacks) {
                const m = machines[0], memory = m.cpu.wasm_memory;
                set_jit_switches(m.e, memory, { step_profile: 1 }, "--fallbacks");
                m.e.step_profile_reset();
                const s = await execute(m, images[m.arm.isa], iterations);
                note(m.arm, s);
                const steps = step_profile(m.e);
                set_jit_switches(m.e, memory, { step_profile: 0 }, "--fallbacks");
                row.arms[m.arm.label].steps = steps.slice(0, 40);
                const share = steps.reduce((sum, r) => sum + r.count, 0) / s.instructions;
                console.log(`  stepped ${(100 * share).toFixed(1)}%: ` + steps.slice(0, 8).map(r =>
                    `${r.name} ${(100 * r.count / s.instructions).toFixed(1)}%`).join(", "));
            }
            // Same source: the exact instruction counts (cross-phase rule 3) of
            // one more round, x86-64 in a fresh machine without the page
            // tier's block counts (compiled in; an upper bound when a block is
            // left early), and the writable data of each build
            if(same_source) {
                for(const m of machines.filter(m => !m.arm.interpreted)) {
                    const counted = m.arm.isa === "x86_64" ? await create(m.arm, bench, { x64_block_count: 0 }) : m;
                    try {
                        const before = counted.e.core_statistics_get(0, 0), steps = counted.e.x64_page_stat(4);
                        await execute(counted, images[m.arm.isa], iterations);
                        const r = row.arms[m.arm.label];
                        r.retired = counted.e.core_statistics_get(0, 0) - before;
                        if(m.arm.isa === "x86_64") r.step_share = (counted.e.x64_page_stat(4) - steps) / r.retired;
                    }
                    finally { if(counted !== m) await counted.vm.destroy(); }
                }
                row.instruction_ratio = row.arms.ir.retired / row.arms.baseline.retired;
                // (neither build writes static data: as much in both)
                const data = [writable(images.x86_64), writable(images.i686)];
                row.data_ratio = data[1] ? data[0] / data[1] : data[0] ? Infinity : 1;
            }
        }
        finally {
            for(const m of machines) await m.vm.destroy();
        }
        const reference = row.arms.baseline;
        for(const arm of arms) {
            const r = row.arms[arm.label];
            // (results only compare within an ISA; instruction counts only
            // between JIT arms of 32-bit code: the x64 page tier counts blocks)
            const same = reference_of(arm), expected = same && row.arms[same.label];
            const counts = !page_tier(arm) && !(same && page_tier(same)) && !arm.interpreted && !same?.interpreted;
            if(expected && (r.checksum !== expected.checksum || counts && r.instructions !== expected.instructions))
                errors.push(`${bench.name}: ${arm.label} result ${r.checksum}/${r.instructions} differs from ${same.label} ${expected.checksum}/${expected.instructions}`);
            r.warm = median(r.warm_ms); r.cold = cold_runs ? median(r.cold_ms) : null;
            r.warm_mips = r.instructions / r.warm / 1000;
            r.cold_mips = r.cold ? r.instructions / r.cold / 1000 : null;
            r.warm_ratio = reference ? median(reference.warm_ms) / r.warm : null;
            r.cold_ratio = reference && cold_runs ? median(reference.cold_ms) / r.cold : null;
        }
    }
    catch(error) {
        errors.push(`${bench.name}: ${error.message}`);
        row.error = error.message;
    }
    results.push(row);
    const line = arms.map(arm => {
        const r = row.arms[arm.label];
        return row.error ? `${arm.label} -` : `${arm.label} ${r.warm_mips.toFixed(0)} MIPS${arm.label === "baseline" || r.warm_ratio === null ? "" : ` x${r.warm_ratio.toFixed(2)} cold x${(r.cold_ratio ?? NaN).toFixed(2)}`}`;
    }).join(" | ");
    const ratios = row.instruction_ratio ? ` | instructions x${row.instruction_ratio.toFixed(2)} data x${row.data_ratio.toFixed(2)}` +
        ` steps ${(100 * row.arms.ir.step_share).toFixed(1)}%` : "";
    console.log(`${bench.name.padEnd(16)} ${row.error ? "ERROR " + row.error : line + ratios}`);
}

if(xp_image) {
    const row = { name: "900.xpboot", category: "system", about: "Windows XP boot to the first 800x600x32 desktop mode, synchronous disk", arms: {} };
    for(const arm of arms) row.arms[arm.label] = { boot_ms: [], avg_mips: [] };
    for(let r = 0; r < xp_runs; r++) for(const arm of r % 2 ? [...arms].reverse() : arms) {
        const child = spawnSync(process.execPath, ["tests/ir/performance/xp_boot.mjs", xp_image, arm.wasm], {
            env: { ...process.env, IR_SYNC_DISK: "1", IR_BOOT_TARGET: "desktop", IR_BOOT_MS: "180000", IR_DIAGNOSTICS: "0" },
            encoding: "utf8", timeout: 400000, maxBuffer: 1 << 28,
        });
        const result = child.stdout.split("\n").filter(l => l.includes('"event":"result"')).map(l => JSON.parse(l))[0];
        if(!result?.milestone) { errors.push(`900.xpboot/${arm.label}: no desktop milestone`); continue; }
        row.arms[arm.label].boot_ms.push(result.milestone.ms);
        row.arms[arm.label].avg_mips.push(result.milestone.instructions / result.milestone.ms / 1000);
    }
    for(const arm of arms) {
        const r = row.arms[arm.label];
        r.warm = median(r.boot_ms); r.warm_mips = median(r.avg_mips);
        r.warm_ratio = row.arms.baseline ? median(row.arms.baseline.boot_ms) / r.warm : null;
    }
    results.push(row);
    console.log(`900.xpboot       ${arms.map(a => `${a.label} ${(row.arms[a.label].warm / 1000).toFixed(2)} s ${row.arms[a.label].warm_mips.toFixed(0)} MIPS`).join(" | ")}`);
}

const scores = {};
for(const arm of arms) {
    if(arm.label === "baseline" || !baseline) continue;
    const ok = results.filter(r => !r.error && r.arms[arm.label]?.warm_ratio);
    const categories = [...new Set(ok.map(r => r.category))];
    scores[arm.label] = {
        warm: geomean(ok.map(r => r.arms[arm.label].warm_ratio)),
        cold: geomean(ok.filter(r => r.arms[arm.label].cold_ratio).map(r => r.arms[arm.label].cold_ratio)),
        categories: Object.fromEntries(categories.map(c => [c, {
            warm: geomean(ok.filter(r => r.category === c).map(r => r.arms[arm.label].warm_ratio)),
            cold: geomean(ok.filter(r => r.category === c && r.arms[arm.label].cold_ratio).map(r => r.arms[arm.label].cold_ratio)),
        }])),
        slower_than_baseline: ok.filter(r => r.arms[arm.label].warm_ratio < 1).map(r => r.name),
    };
}
let revision = null;
try { revision = execSync("git rev-parse --short HEAD", { encoding: "utf8" }).trim() + (execSync("git status --porcelain", { encoding: "utf8" }).trim() ? "+dirty" : ""); } catch{}
const report = {
    suite: "v86-cpu", version: 1, date: new Date().toISOString(), revision, arms,
    settings: { runs, cold_runs, scale, ir_setup, isa, same_source },
    host: { platform: process.platform, cpus: os.cpus().length, model: os.cpus()[0]?.model, load: os.loadavg(), node: process.version },
    scores, errors, results,
};
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, JSON.stringify(report, null, 1));
for(const [label, s] of Object.entries(scores)) {
    console.log(`\n${label} vs baseline: warm score ${s.warm?.toFixed(3)}  cold score ${s.cold?.toFixed(3) ?? "-"}`);
    for(const [c, v] of Object.entries(s.categories)) console.log(`  ${c.padEnd(9)} warm ${v.warm.toFixed(3)}  cold ${v.cold?.toFixed(3) ?? "-"}`);
    if(s.slower_than_baseline.length) console.log(`  slower than baseline: ${s.slower_than_baseline.join(" ")}`);
}
if(errors.length) { console.log("\nERRORS:\n  " + errors.join("\n  ")); process.exitCode = 1; }
console.log(`\nresults: ${out}`);
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/bench/src/bitboard.c                                                               0000644 0000000 0000000 00000004136 00000000000 014632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // deepsjeng-like: 64-bit bitboard move generation on a 32-bit CPU (paired
// shifts/masks, bit scans, population counts) with a bounded recursive search.
#include "../lib/bench.h"
static inline u32 popcount64(u64 b) { u32 c = 0; while(b) { b &= b - 1; c++; } return c; }
static inline u32 lsb64(u64 b) { return (u32)b ? __builtin_ctz((u32)b) : 32 + __builtin_ctz((u32)(b >> 32)); }
static u64 knight_attacks(u64 b)
{
    const u64 a = 0xFEFEFEFEFEFEFEFEull, ab = 0xFCFCFCFCFCFCFCFCull, h = 0x7F7F7F7F7F7F7F7Full, gh = 0x3F3F3F3F3F3F3F3Full;
    return (b << 17 & a) | (b << 15 & h) | (b << 10 & ab) | (b << 6 & gh)
        | (b >> 17 & h) | (b >> 15 & a) | (b >> 10 & gh) | (b >> 6 & ab);
}
static u64 slide(u64 from, u64 occupied, int shift, u64 mask)
{
    u64 r = 0, b = from;
    for(;;) {
        b = shift > 0 ? b << shift & mask : b >> -shift & mask;
        if(!b) return r;
        r |= b;
        if(b & occupied) return r;
    }
}
static u64 rook_attacks(u64 b, u64 occupied)
{
    return slide(b, occupied, 8, ~0ull) | slide(b, occupied, -8, ~0ull)
        | slide(b, occupied, 1, 0xFEFEFEFEFEFEFEFEull) | slide(b, occupied, -1, 0x7F7F7F7F7F7F7F7Full);
}
NOINLINE static u32 search(u64 mine, u64 theirs, u32 depth)
{
    if(!depth) return popcount64(mine) * 3 - popcount64(theirs);
    u32 best = 0, tried = 0;
    u64 pieces = mine;
    while(pieces && tried < 4) {
        u32 square = lsb64(pieces);
        pieces &= pieces - 1;
        u64 from = 1ull << square;
        u64 moves = (square & 1 ? knight_attacks(from) : rook_attacks(from, mine | theirs)) & ~mine;
        while(moves && tried < 4) {
            u64 to = moves & -moves;
            moves ^= to;
            tried++;
            u32 score = search(theirs & ~to, (mine ^ from) | to, depth - 1);
            if(score > best) best = score;
        }
    }
    return best;
}
u32 bench_main(u32 n)
{
    u32 h = 0;
    u64 mine = 0x000000000000FF42ull, theirs = 0x42FF000000000000ull;
    for(u32 i = 0; i < n; i++) {
        h = mix(h, search(mine, theirs, 5));
        mine = mine << 1 | mine >> 63;
        theirs ^= (u64)i << (i & 31);
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/bench/src/bytecode.c                                                               0000644 0000000 0000000 00000004546 00000000000 014647  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // perlbench-like: a switch-dispatched stack-machine interpreter (indirect
// jump tables, unpredictable branches, small memory stack).
#include "../lib/bench.h"
enum { PUSH, LOAD, STORE, ADD, SUB, MUL, AND, XOR, SHL, SHR, LT, JZ, JMP, DUP, SWAP, DROP, INC, MOD, CALL, RET, HALT };
static const int program[] = {
    // for(i = 0; i < 2000; i++) { acc = (acc * 31 + i) ^ (i << 3); if(i % 7 < 3) acc += helper(i); }
    PUSH, 0, STORE, 0, PUSH, 7, STORE, 1,
    /* 8 loop */ LOAD, 0, PUSH, 2000, LT, JZ, 57,
    LOAD, 1, PUSH, 31, MUL, LOAD, 0, ADD, LOAD, 0, PUSH, 3, SHL, XOR, STORE, 1,
    LOAD, 0, PUSH, 7, MOD, PUSH, 3, LT, JZ, 50,
    LOAD, 1, LOAD, 0, CALL, 60, ADD, STORE, 1,
    /* 50 next */ LOAD, 0, INC, STORE, 0, JMP, 8,
    /* 57 end */ LOAD, 1, HALT,
    /* 60 helper(x) = (x ^ 0x5a5a) & 0xfff */ PUSH, 0x5a5a, XOR, PUSH, 0xfff, AND, RET,
};
NOINLINE static u32 run(const int *code)
{
    int stack[64], vars[4] = { 0 }, calls[16];
    int sp = 0, cp = 0, pc = 0;
    for(;;) {
        int op = code[pc++];
        switch(op) {
        case PUSH: stack[sp++] = code[pc++]; break;
        case LOAD: stack[sp++] = vars[code[pc++]]; break;
        case STORE: vars[code[pc++]] = stack[--sp]; break;
        case ADD: sp--; stack[sp - 1] += stack[sp]; break;
        case SUB: sp--; stack[sp - 1] -= stack[sp]; break;
        case MUL: sp--; stack[sp - 1] *= stack[sp]; break;
        case AND: sp--; stack[sp - 1] &= stack[sp]; break;
        case XOR: sp--; stack[sp - 1] ^= stack[sp]; break;
        case SHL: sp--; stack[sp - 1] <<= stack[sp]; break;
        case SHR: sp--; stack[sp - 1] = (u32)stack[sp - 1] >> stack[sp]; break;
        case LT: sp--; stack[sp - 1] = stack[sp - 1] < stack[sp]; break;
        case JZ: if(!stack[--sp]) pc = code[pc]; else pc++; break;
        case JMP: pc = code[pc]; break;
        case DUP: stack[sp] = stack[sp - 1]; sp++; break;
        case SWAP: { int t = stack[sp - 1]; stack[sp - 1] = stack[sp - 2]; stack[sp - 2] = t; break; }
        case DROP: sp--; break;
        case INC: stack[sp - 1]++; break;
        case MOD: sp--; stack[sp - 1] %= stack[sp]; break;
        case CALL: calls[cp++] = pc + 1; pc = code[pc]; break;
        case RET: pc = calls[--cp]; break;
        case HALT: return stack[sp - 1];
        }
    }
}
u32 bench_main(u32 n)
{
    u32 h = 0x811C9DC5u;
    for(u32 i = 0; i < n; i++) h = mix(h, run(program));
    return h;
}
                                                                                                                                                          source/v64/tests/bench/src/chase.c                                                                  0000644 0000000 0000000 00000003233 00000000000 014124  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // mcf-like: pointer chasing through a randomly permuted 2 MiB list and a
// binary search tree (dependent loads, poor locality, TLB pressure).
#include "../lib/bench.h"
#define NODES (1 << 18)
struct node { struct node *next; u32 value; };
static struct node list[NODES];
struct tree { struct tree *left, *right; u32 key; };
static struct tree trees[1 << 14];
static u32 order[NODES];
NOINLINE static void build(void)
{
    u32 seed = 12345;
    for(u32 i = 0; i < NODES; i++) order[i] = i;
    for(u32 i = NODES - 1; i > 0; i--) {
        u32 j = lcg(&seed) % (i + 1), t = order[i];
        order[i] = order[j]; order[j] = t;
    }
    for(u32 i = 0; i < NODES; i++) {
        list[order[i]].next = &list[order[(i + 1) % NODES]];
        list[order[i]].value = i * 2654435761u;
    }
    struct tree *root = &trees[0];
    root->key = 0x80000000u; root->left = root->right = 0;
    for(u32 i = 1; i < (1 << 14); i++) {
        struct tree *t = &trees[i];
        t->key = lcg(&seed); t->left = t->right = 0;
        struct tree *p = root;
        for(;;) {
            struct tree **link = t->key < p->key ? &p->left : &p->right;
            if(!*link) { *link = t; break; }
            p = *link;
        }
    }
}
u32 bench_main(u32 n)
{
    build();
    u32 h = 0, seed = 99;
    struct node *p = &list[0];
    for(u32 i = 0; i < n; i++) {
        for(u32 k = 0; k < 4096; k++) { h += p->value; p = p->next; }
        for(u32 k = 0; k < 256; k++) {
            u32 key = lcg(&seed);
            struct tree *t = &trees[0];
            u32 depth = 0;
            while(t) { depth++; t = key < t->key ? t->left : t->right; }
            h = mix(h, depth);
        }
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/bench/src/fcompare.c                                                               0000644 0000000 0000000 00000002627 00000000000 014643  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Branchy float code built for i586 (FCOM/FCOMP + FNSTSW AX + SAHF/TEST, no
// FCOMI/FCMOV): clamping, min/max and bounding-box tests like 2004-era games.
#include "../lib/bench.h"
typedef struct { float x, y, z; } vec3;
static vec3 points[2048];
NOINLINE static u32 cull(const vec3 *lo, const vec3 *hi, u32 count)
{
    u32 inside = 0;
    for(u32 i = 0; i < count; i++) {
        const vec3 *p = &points[i];
        if(p->x < lo->x || p->x > hi->x) continue;
        if(p->y < lo->y || p->y > hi->y) continue;
        if(p->z >= lo->z && p->z <= hi->z) inside++;
    }
    return inside;
}
NOINLINE static float clamp_sum(u32 count)
{
    float sum = 0, best = -1e30f;
    for(u32 i = 0; i < count; i++) {
        float v = points[i].x - points[i].y;
        if(v < -100.0f) v = -100.0f;
        else if(v > 100.0f) v = 100.0f;
        if(v > best) best = v;
        sum += v;
    }
    return sum + best;
}
u32 bench_main(u32 n)
{
    u32 seed = 11;
    for(u32 i = 0; i < 2048; i++) {
        points[i].x = (i32)(lcg(&seed) >> 16) - 32768.0f;
        points[i].y = (i32)(lcg(&seed) >> 16) - 32768.0f;
        points[i].z = (i32)(lcg(&seed) >> 16) - 32768.0f;
    }
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        vec3 lo = { -20000.0f + i, -15000.0f, -30000.0f }, hi = { 20000.0f, 15000.0f + i, 10000.0f };
        h = mix(h, cull(&lo, &hi, 2048));
        h = mix(h, (u32)(i32)clamp_sum(2048));
    }
    return h;
}
                                                                                                         source/v64/tests/bench/src/ftol.c                                                                   0000644 0000000 0000000 00000001734 00000000000 014011  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Float/integer conversion as game code does it: truncating casts (FNSTCW/
// FLDCW/FISTP sequences), rounding conversions (FISTP), integer loads (FILD).
#include "../lib/bench.h"
static float samples[4096];
static i32 ints[4096];
NOINLINE static u32 quantize(u32 count)
{
    u32 h = 0;
    for(u32 i = 0; i < count; i++) {
        i32 t = (i32)samples[i];
        i32 r = __builtin_lrintf(samples[i] * 0.5f);
        ints[i] = t + r;
        h += t ^ r;
    }
    return h;
}
NOINLINE static float accumulate(u32 count)
{
    float sum = 0;
    for(u32 i = 0; i < count; i++) sum += (float)ints[i] * 0.125f + (float)(short)i;
    return sum;
}
u32 bench_main(u32 n)
{
    for(u32 i = 0; i < 4096; i++) samples[i] = (i32)(i * 2654435761u >> 16) * 0.37f - 30000.0f;
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        h = mix(h, quantize(4096));
        float s = accumulate(4096);
        h = mix(h, (u32)(i32)(s * 0.001f));
        samples[i & 4095] += 1.5f;
    }
    return h;
}
                                    source/v64/tests/bench/src/hash.c                                                                   0000644 0000000 0000000 00000005726 00000000000 013775  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Table-driven CRC-32, SHA-256 compression (rotates, adds, big message
// schedule) and Adler-32 over a buffer.
#include "../lib/bench.h"
static u8 buffer[16384];
static u32 crc_table[256];
static const u32 k[64] = {
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};
static inline u32 ror(u32 x, u32 n) { return x >> n | x << (32 - n); }
NOINLINE static void sha256_block(u32 state[8], const u8 *p)
{
    u32 w[64];
    for(u32 i = 0; i < 16; i++) w[i] = p[4 * i] << 24 | p[4 * i + 1] << 16 | p[4 * i + 2] << 8 | p[4 * i + 3];
    for(u32 i = 16; i < 64; i++)
        w[i] = w[i - 16] + (ror(w[i - 15], 7) ^ ror(w[i - 15], 18) ^ w[i - 15] >> 3) + w[i - 7]
            + (ror(w[i - 2], 17) ^ ror(w[i - 2], 19) ^ w[i - 2] >> 10);
    u32 a = state[0], b = state[1], c = state[2], d = state[3], e = state[4], f = state[5], g = state[6], h = state[7];
    for(u32 i = 0; i < 64; i++) {
        u32 t1 = h + (ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i];
        u32 t2 = (ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
        h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
    }
    state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; state[5] += f; state[6] += g; state[7] += h;
}
NOINLINE static u32 crc32(const u8 *p, u32 n)
{
    u32 c = ~0u;
    while(n--) c = crc_table[(c ^ *p++) & 255] ^ c >> 8;
    return ~c;
}
NOINLINE static u32 adler32(const u8 *p, u32 n)
{
    u32 a = 1, b = 0;
    while(n--) { a = (a + *p++) % 65521; b = (b + a) % 65521; }
    return b << 16 | a;
}
u32 bench_main(u32 n)
{
    for(u32 i = 0; i < 256; i++) {
        u32 c = i;
        for(u32 j = 0; j < 8; j++) c = c & 1 ? 0xEDB88320u ^ c >> 1 : c >> 1;
        crc_table[i] = c;
    }
    u32 seed = 1;
    for(u32 i = 0; i < sizeof(buffer); i++) buffer[i] = lcg(&seed) >> 24;
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        u32 state[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
        for(u32 b = 0; b < sizeof(buffer); b += 64) sha256_block(state, buffer + b);
        h = mix(mix(mix(h, state[0] ^ state[7]), crc32(buffer, sizeof(buffer))), adler32(buffer, 4096));
        buffer[i % sizeof(buffer)]++;
    }
    return h;
}
                                          source/v64/tests/bench/src/lz.c                                                                     0000644 0000000 0000000 00000004746 00000000000 013500  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // xz-like: LZ77 compression with hash chains, then decompression and
// round-trip verification (byte loops, table lookups, data-dependent branches).
#include "../lib/bench.h"
#define SIZE 65536
static u8 input[SIZE], packed[SIZE * 2], output[SIZE];
static u16 head[4096], chain[SIZE];
NOINLINE static void make_input(u32 seed)
{
    for(u32 i = 0; i < SIZE; i++) {
        u32 r = lcg(&seed);
        input[i] = (r >> 30) ? input[i >= 64 ? i - 1 - ((r >> 8) & 63) : i] + (r >> 29 & 1) : r >> 24;
    }
}
NOINLINE static u32 compress(void)
{
    u32 out = 0;
    for(u32 i = 0; i < 4096; i++) head[i] = 0xFFFF;
    for(u32 i = 0; i < SIZE;) {
        u32 best = 0, distance = 0;
        if(i + 3 < SIZE) {
            u32 h = (input[i] << 4 ^ input[i + 1] << 2 ^ input[i + 2]) & 4095;
            u32 candidate = head[h], tries = 16;
            while(candidate != 0xFFFF && tries-- && i - candidate < 32768) {
                u32 len = 0;
                while(len < 255 && i + len < SIZE && input[candidate + len] == input[i + len]) len++;
                if(len > best) { best = len; distance = i - candidate; }
                candidate = chain[candidate];
            }
            chain[i] = head[h]; head[h] = i;
        }
        if(best >= 4) {
            packed[out++] = 0xFF; packed[out++] = best; packed[out++] = distance; packed[out++] = distance >> 8;
            for(u32 k = 1; k < best && i + k + 3 < SIZE; k++) {
                u32 h = (input[i + k] << 4 ^ input[i + k + 1] << 2 ^ input[i + k + 2]) & 4095;
                chain[i + k] = head[h]; head[h] = i + k;
            }
            i += best;
        }
        else {
            if(input[i] == 0xFF) packed[out++] = 0xFF, packed[out++] = 0;
            else packed[out++] = input[i];
            i++;
        }
    }
    return out;
}
NOINLINE static u32 decompress(u32 length)
{
    u32 out = 0;
    for(u32 i = 0; i < length;) {
        u8 b = packed[i++];
        if(b != 0xFF) { output[out++] = b; continue; }
        u32 len = packed[i++];
        if(!len) { output[out++] = 0xFF; continue; }
        u32 distance = packed[i] | packed[i + 1] << 8;
        i += 2;
        for(u32 k = 0; k < len; k++, out++) output[out] = output[out - distance];
    }
    return out;
}
u32 bench_main(u32 n)
{
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        make_input(i + 1);
        u32 length = compress();
        u32 restored = decompress(length);
        h = mix(mix(h, length), restored == SIZE && !memcmp(input, output, SIZE));
    }
    return h;
}
                          source/v64/tests/bench/src/m_alu.asm                                                                0000644 0000000 0000000 00000001213 00000000000 014470  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Register-only integer ALU and FLAGS work (no memory, no helpers).
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    push edi
    mov ecx, [esp + 16]
    shl ecx, 12
    mov eax, 0x12345678
    mov ebx, 0x9E3779B9
    xor edx, edx
    mov esi, 7
    mov edi, 3
.loop:
    add eax, ebx
    xor edx, eax
    rol eax, 5
    sub ebx, edx
    imul esi, eax
    lea edi, [edi + esi * 2 + 1]
    adc edx, edi
    shr ebx, 1
    sbb eax, esi
    and edi, 0x7FFFFFFF
    or ebx, edi
    not esi
    neg edx
    dec ecx
    jnz .loop
    xor eax, ebx
    xor eax, edx
    xor eax, esi
    xor eax, edi
    pop edi
    pop esi
    pop ebx
    ret
                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/bench/src/m_avx2.asm                                                               0000644 0000000 0000000 00000002261 00000000000 014573  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; AVX2 (the templates of docs/simd-xsave-plan.md P7 part 3): a strlen-like
; scan of a 4 KiB table, 32 bytes a step: VPCMPEQB with a broadcast byte,
; VPMINUB, VPCMPGTB, VPOR, VPANDN, VPADDB, VPXOR, VPMINUD, VPCMPEQD, VPAND
; and VPMOVMSKB r32, ymm; VPBROADCASTB/D each round.
%include "micro.inc"
_bench_main:
    push esi
    push ebx
    mov edx, [esp + 12]
    shl edx, 4
    xor ebx, ebx
.loop:
    mov esi, table
    mov ecx, 128
    vpbroadcastb ymm7, [needle]
    vpbroadcastd ymm6, [bias]
.inner:
    vmovdqu ymm0, [esi]
    vpcmpeqb ymm1, ymm0, ymm7
    vpminub ymm2, ymm0, ymm6
    vpcmpgtb ymm3, ymm0, ymm6
    vpor ymm1, ymm1, ymm3
    vpandn ymm4, ymm2, ymm1
    vpaddb ymm5, ymm4, ymm0
    vpxor ymm5, ymm5, ymm2
    vpminud ymm5, ymm5, ymm0
    vpcmpeqd ymm4, ymm5, ymm0
    vpand ymm4, ymm4, ymm1
    vpmovmskb eax, ymm4
    add ebx, eax
    vpmovmskb eax, ymm5
    xor ebx, eax
    add esi, 32
    dec ecx
    jnz .inner
    vzeroupper
    dec edx
    jnz .loop
    mov eax, ebx
    pop ebx
    pop esi
    ret
section .data
align 32
needle: db 0x5A
align 4
bias: dd 0x40404040
align 32
table:
%assign i 0
%rep 1024
    dd (i * 2654435761 + 12345) & 0xFFFFFFFF
%assign i i+1
%endrep
                                                                                                                                                                                                                                                                                                                                               source/v64/tests/bench/src/m_avx256.asm                                                             0000644 0000000 0000000 00000002110 00000000000 014737  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; AVX VEX.256 moves (the templates of docs/simd-xsave-plan.md P6 part 3):
; VMOVDQA/VMOVDQU ymm loads, VMOVNTDQ and VMOVDQU ymm stores (aligned and
; not), VMOVUPS between YMM registers over a 4 KiB table; VPXOR (VEX.128)
; sums the low halves, VZEROUPPER each round.
%include "micro.inc"
_bench_main:
    push esi
    push edi
    mov edx, [esp + 12]
    shl edx, 4
    vpxor xmm6, xmm6, xmm6
.loop:
    mov esi, table
    mov edi, copy
    mov ecx, 128
.inner:
    vmovdqa ymm0, [esi]
    vmovdqu ymm1, [esi + 8]
    vmovntdq [edi], ymm0
    vmovdqu [edi + 4100], ymm1
    vmovups ymm2, ymm1
    vpxor xmm6, xmm6, xmm2
    add esi, 32
    add edi, 32
    dec ecx
    jnz .inner
    vmovdqu ymm3, [copy + 4116]
    vpxor xmm6, xmm6, xmm3
    vzeroupper
    dec edx
    jnz .loop
    vpshufd xmm0, xmm6, 0x4E
    vpaddd xmm6, xmm6, xmm0
    vpshufd xmm0, xmm6, 0xB1
    vpaddd xmm6, xmm6, xmm0
    vmovd eax, xmm6
    pop edi
    pop esi
    ret
section .data
align 32
table:
%assign i 0
%rep 1032
    dd (i * 2654435761 + 12345) & 0xFFFFFFFF
%assign i i+1
%endrep
align 32
copy: times 8256 db 0
                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/bench/src/m_bmi.asm                                                                0000644 0000000 0000000 00000002164 00000000000 014464  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; BMI1, BMI2, LZCNT and MOVBE (the templates of docs/simd-xsave-plan.md P10
; part 2): the words of a 4 KiB table, loaded big-endian (MOVBE), each set
; bit in turn (TZCNT, BLSR), then LZCNT and a left-aligned copy (SHLX), the
; low bits below a count (BZHI), BLSMSK, ANDN and shifts by register (SARX,
; SHRX).
%include "micro.inc"
_bench_main:
    push esi
    push edi
    push ebx
    push ebp
    mov ebp, [esp + 20]
    xor ebx, ebx
.loop:
    mov esi, table
    mov ecx, 1024
.inner:
    movbe eax, [esi]
    mov edx, eax
.bits:
    test edx, edx
    jz .done
    tzcnt edi, edx
    add ebx, edi
    blsr edx, edx
    jmp .bits
.done:
    lzcnt edi, eax
    shlx edx, eax, edi
    add ebx, edx
    bzhi edx, eax, ecx
    xor ebx, edx
    blsmsk edx, eax
    andn edx, edx, ebx
    add ebx, edx
    sarx edx, eax, ecx
    shrx edi, ebx, ecx
    xor ebx, edx
    add ebx, edi
    add esi, 4
    dec ecx
    jnz .inner
    dec ebp
    jnz .loop
    mov eax, ebx
    pop ebp
    pop ebx
    pop edi
    pop esi
    ret
section .data
align 4
table:
%assign i 0
%rep 1024
    dd (i * 2654435761 + 12345) & 0xFFFFFFFF
%assign i i+1
%endrep
                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/bench/src/m_branch.asm                                                             0000644 0000000 0000000 00000001114 00000000000 015144  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Data-dependent, poorly predictable branches driven by a 32-bit LFSR.
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    mov ecx, [esp + 12]
    shl ecx, 12
    mov eax, 0xACE1ACE1
    xor ebx, ebx
    xor esi, esi
.loop:
    shr eax, 1
    jnc .no_tap
    xor eax, 0xD0000001
.no_tap:
    test al, 2
    jz .a
    add ebx, 3
    test al, 4
    jnz .b
    sub esi, ebx
    jmp .c
.a:
    inc esi
    test al, 8
    jz .c
.b:
    xor ebx, esi
.c:
    cmp bl, al
    jae .d
    add esi, 5
.d:
    dec ecx
    jnz .loop
    lea eax, [ebx + esi]
    pop esi
    pop ebx
    ret
                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/bench/src/m_call.asm                                                               0000644 0000000 0000000 00000000601 00000000000 014622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Near CALL/RET to small leaf and two-level functions (return-site dispatch).
%include "micro.inc"
_bench_main:
    push ebx
    mov ecx, [esp + 8]
    shl ecx, 11
    xor eax, eax
    mov ebx, 1
.loop:
    call leaf
    call outer
    dec ecx
    jnz .loop
    pop ebx
    ret
leaf:
    add eax, ebx
    rol ebx, 1
    ret
outer:
    call leaf
    xor eax, 0x55
    call leaf
    ret
                                                                                                                               source/v64/tests/bench/src/m_fma.asm                                                                0000644 0000000 0000000 00000002444 00000000000 014461  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; FMA (the templates of docs/simd-xsave-plan.md P11 part 2): a polynomial of
; degree 8 in Horner form, the forms libm's _fma variants use most
; (VFMADD213SD, VFMADD132SD, VFMADD231SD; register and memory operands), at
; 512 points a round.
%include "micro.inc"
_bench_main:
    push esi
    push ebx
    mov edx, [esp + 12]
    vxorpd xmm7, xmm7, xmm7
.loop:
    mov ecx, 512
.inner:
    vcvtsi2sd xmm0, xmm0, ecx
    vmulsd xmm0, xmm0, [scale]
    vmovsd xmm1, [coefficients]
    vfmadd213sd xmm1, xmm0, [coefficients + 8]
    vfmadd213sd xmm1, xmm0, [coefficients + 16]
    vfmadd213sd xmm1, xmm0, [coefficients + 24]
    vmovsd xmm2, [coefficients + 32]
    vfmadd132sd xmm1, xmm2, xmm0
    vmovsd xmm2, [coefficients + 40]
    vfmadd132sd xmm1, xmm2, xmm0
    vmovsd xmm3, [coefficients + 48]
    vfmadd231sd xmm3, xmm1, xmm0
    vfmadd213sd xmm3, xmm0, [coefficients + 56]
    vfmadd213sd xmm3, xmm0, [coefficients + 64]
    vaddsd xmm7, xmm7, xmm3
    dec ecx
    jnz .inner
    dec edx
    jnz .loop
    vmovd eax, xmm7
    vpextrd ebx, xmm7, 1
    xor eax, ebx
    pop ebx
    pop esi
    ret
section .data
align 8
scale: dq 0.001953125
coefficients: dq 2.48015873015873e-05, 0.0001984126984126984, 0.001388888888888889, 0.008333333333333333
    dq 0.041666666666666664, 0.16666666666666666, 0.5, 1.0, 1.0
                                                                                                                                                                                                                            source/v64/tests/bench/src/m_icall.asm                                                              0000644 0000000 0000000 00000001015 00000000000 014773  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Indirect calls through a function-pointer table (virtual-call shape).
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    mov ecx, [esp + 12]
    shl ecx, 11
    xor eax, eax
    mov esi, 0x9E3779B9
.loop:
    mov ebx, esi
    shr ebx, 30
    call [table + ebx * 4]
    imul esi, esi, 1103515245
    add esi, 12345
    dec ecx
    jnz .loop
    pop esi
    pop ebx
    ret
f0: add eax, 1
    ret
f1: xor eax, 0x1234
    ret
f2: rol eax, 3
    ret
f3: sub eax, esi
    ret
section .data
table: dd f0, f1, f2, f3
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/bench/src/m_jtable.asm                                                             0000644 0000000 0000000 00000001325 00000000000 015154  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Switch statements compiled to jump tables (indirect JMP to 8 targets).
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    mov ecx, [esp + 12]
    shl ecx, 11
    xor eax, eax
    mov esi, 0x2545F491
switch_loop:
    mov ebx, esi
    shr ebx, 29
    jmp [cases + ebx * 4]
c0: inc eax
    jmp switch_next
c1: add eax, 7
    jmp switch_next
c2: xor eax, esi
    jmp switch_next
c3: shl eax, 1
    jmp switch_next
c4: sub eax, 3
    jmp switch_next
c5: ror eax, 2
    jmp switch_next
c6: not eax
    jmp switch_next
c7: add eax, ebx
switch_next:
    imul esi, esi, 1103515245
    add esi, 12345
    dec ecx
    jnz switch_loop
    pop esi
    pop ebx
    ret
section .data
cases: dd c0, c1, c2, c3, c4, c5, c6, c7
                                                                                                                                                                                                                                                                                                           source/v64/tests/bench/src/m_memory.asm                                                             0000644 0000000 0000000 00000001166 00000000000 015226  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Loads and stores to an L1-sized array: indexed, unaligned and byte/word
; accesses mixed with ALU work.
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    push edi
    mov ecx, [esp + 16]
    shl ecx, 11
    xor eax, eax
    xor ebx, ebx
.loop:
    mov esi, ebx
    and esi, 1023
    mov edx, [array + esi * 4]
    add edx, eax
    mov [array + esi * 4 + 4], edx
    movzx edi, byte [array + esi + 1]
    add eax, edi
    mov di, [array + esi * 2 + 3]
    add eax, edi
    mov [array + esi + 2], ax
    add ebx, 97
    dec ecx
    jnz .loop
    pop edi
    pop esi
    pop ebx
    ret
section .bss
array: resd 1100
                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/bench/src/m_pages.asm                                                              0000644 0000000 0000000 00000001401 00000000000 015005  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Control flow that crosses 4 KiB code pages on every step: 16 blocks on 16
; pages, visited in a data-dependent order through direct and indirect jumps.
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    mov ecx, [esp + 12]
    shl ecx, 9
    xor eax, eax
    mov esi, 0x12345
    jmp page0
done:
    pop esi
    pop ebx
    ret
%assign p 0
%rep 16
    align 4096
page %+ p:
    add eax, p * 3 + 1
    rol eax, 3
    imul esi, esi, 69069
    inc esi
%if p == 15
    dec ecx
    jz done
    mov ebx, esi
    shr ebx, 28
    jmp [pages + ebx * 4]
%else
%assign q p + 1
    test esi, 0x100000
    jz page %+ q
    xor eax, esi
    jmp page %+ q
%endif
%assign p p + 1
%endrep
section .data
pages:
%assign p 0
%rep 16
    dd page %+ p
%assign p p + 1
%endrep
                                                                                                                                                                                                                                                               source/v64/tests/bench/src/m_rmw.asm                                                                0000644 0000000 0000000 00000001167 00000000000 014524  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Read-modify-write memory operands (ADD/INC/XOR/SHL on [mem]) and LOCK XADD.
%include "micro.inc"
_bench_main:
    push ebx
    mov ecx, [esp + 8]
    shl ecx, 11
    xor eax, eax
    xor ebx, ebx
.loop:
    mov edx, ebx
    and edx, 255
    add [counters + edx * 4], ecx
    inc dword [counters + edx * 4 + 1024]
    xor [counters + edx * 4 + 2048], eax
    shl dword [counters + edx * 4 + 3072], 1
    mov eax, 1
    lock xadd [counters], eax
    add ebx, 13
    dec ecx
    jnz .loop
    mov eax, [counters + 4]
    add eax, [counters + 1028]
    add eax, [counters + 2052]
    pop ebx
    ret
section .bss
counters: resd 1024
                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/bench/src/m_smc.asm                                                                0000644 0000000 0000000 00000000755 00000000000 014503  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Self-modifying code: every 64th iteration rewrites an immediate in a
; function on its own page, then keeps calling it (invalidation/recompile).
%include "micro.inc"
_bench_main:
    push ebx
    mov ecx, [esp + 8]
    shl ecx, 10
    xor eax, eax
    xor ebx, ebx
.loop:
    test ecx, 63
    jnz .call
    inc ebx
    mov [patched + 1], ebx
.call:
    call patched
    dec ecx
    jnz .loop
    pop ebx
    ret
    align 4096
patched:
    mov edx, 0
    add eax, edx
    rol eax, 1
    ret
                   source/v64/tests/bench/src/m_sse4int.asm                                                            0000644 0000000 0000000 00000001674 00000000000 015313  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; SSE4.1 packed integers: PMINUD, PMAXSD from aligned memory, PMULLD,
; PCMPGTQ, PBLENDW, BLENDPS and PACKUSDW over a 4 KiB table.
%include "micro.inc"
_bench_main:
    push esi
    mov edx, [esp + 8]
    shl edx, 4
    movdqa xmm7, [limit]
    pxor xmm6, xmm6
.loop:
    mov esi, table
    mov ecx, 256
.inner:
    movdqa xmm0, [esi]
    movdqa xmm1, xmm0
    pminud xmm0, xmm7
    pmaxsd xmm1, [esi + 16]
    pmulld xmm0, xmm1
    movdqa xmm2, xmm0
    pcmpgtq xmm2, xmm1
    pblendw xmm0, xmm2, 0x5A
    blendps xmm1, xmm0, 5
    packusdw xmm1, xmm0
    paddd xmm6, xmm1
    add esi, 16
    dec ecx
    jnz .inner
    dec edx
    jnz .loop
    pshufd xmm0, xmm6, 0x4E
    paddd xmm6, xmm0
    pshufd xmm0, xmm6, 0xB1
    paddd xmm6, xmm0
    movd eax, xmm6
    pop esi
    ret
section .data
align 16
limit: dd 0x7FFF0000, 0x00FFFFFF, 0x12345678, 0xFFFFFFF0
table:
%assign i 0
%rep 1028
    dd (i * 2654435761 + 12345) & 0xFFFFFFFF
%assign i i+1
%endrep
                                                                    source/v64/tests/bench/src/m_sse4round.asm                                                          0000644 0000000 0000000 00000002471 00000000000 015644  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; SSE4.1 ROUND over finite values: ROUNDSD floor and ceil (PE suppressed),
; ROUNDSS truncation from memory, ROUNDPD in MXCSR's mode (PE reported).
%include "micro.inc"
_bench_main:
    push esi
    push edi
    ; values[i] = (i - 256) * 0.37, singles[i] = (i - 128) * 0.61
    xor ecx, ecx
.fill_values:
    lea eax, [ecx - 256]
    cvtsi2sd xmm0, eax
    mulsd xmm0, [scale_double]
    movsd [values + ecx * 8], xmm0
    inc ecx
    cmp ecx, 512
    jb .fill_values
    xor ecx, ecx
.fill_singles:
    lea eax, [ecx - 128]
    cvtsi2ss xmm0, eax
    mulss xmm0, [scale_single]
    movss [singles + ecx * 4], xmm0
    inc ecx
    cmp ecx, 256
    jb .fill_singles
    mov edx, [esp + 12]
    shl edx, 4
    xorpd xmm6, xmm6
    xorps xmm7, xmm7
.loop:
    mov esi, values
    mov edi, singles
    mov ecx, 256
.inner:
    movsd xmm0, [esi]
    roundsd xmm1, xmm0, 9
    roundsd xmm2, xmm0, 10
    addsd xmm1, xmm2
    roundss xmm3, [edi], 11
    addss xmm7, xmm3
    roundpd xmm4, [esi], 4
    addpd xmm6, xmm4
    addsd xmm6, xmm1
    add esi, 16
    add edi, 4
    dec ecx
    jnz .inner
    dec edx
    jnz .loop
    cvttsd2si eax, xmm6
    cvttss2si ecx, xmm7
    add eax, ecx
    pop edi
    pop esi
    ret
section .data
align 8
scale_double: dq 0.37
scale_single: dd 0.61
section .bss
align 16
values: resq 512
singles: resd 256
                                                                                                                                                                                                       source/v64/tests/bench/src/m_sse4strings.asm                                                        0000644 0000000 0000000 00000002330 00000000000 016200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; SSE4.2 PCMPISTRI over NUL-terminated strings: strlen in 16-byte chunks
; (equal each against the empty string: the index of the NUL) and the first
; vowel (equal any), with unaligned operands.
%include "micro.inc"
_bench_main:
    push esi
    push edi
    push ebx
    mov ebx, [esp + 16]
    shl ebx, 4
    xor edi, edi
    pxor xmm0, xmm0
    movdqa xmm1, [vowels]
.loop:
    mov esi, strings
.next:
    mov eax, esi
.length:
    pcmpistri xmm0, [eax], 0x08
    lea eax, [eax + 16]
    jnz .length
    lea eax, [eax + ecx - 16]
    sub eax, esi
    add edi, eax
    pcmpistri xmm1, [esi], 0x00
    add edi, ecx
    lea esi, [esi + eax + 1]
    cmp byte [esi], 0
    jnz .next
    dec ebx
    jnz .loop
    mov eax, edi
    pop ebx
    pop edi
    pop esi
    ret
section .data
align 16
vowels: db "aeiou", 0
    times 10 db 0
strings:
    db "the quick brown fox jumps over the lazy dog", 0
    db "pack my box with five dozen liquor jugs", 0
    db "sphinx of black quartz, judge my vow", 0
    db "x", 0
    db "how vexingly quick daft zebras jump", 0
    db "rhythm", 0
    db "a much longer string that spans several sixteen byte chunks before its end", 0
    db "bright vixens jump; dozy fowl quack", 0
    db 0
    times 32 db 0
                                                                                                                                                                                                                                                                                                        source/v64/tests/bench/src/m_stack.asm                                                              0000644 0000000 0000000 00000001235 00000000000 015020  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Stack traffic: PUSH/POP of registers and frames (EBP chains, locals).
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    push edi
    mov ecx, [esp + 16]
    shl ecx, 11
    xor eax, eax
.loop:
    push eax
    push ecx
    push 7
    call frame
    add esp, 12
    dec ecx
    jnz .loop
    pop edi
    pop esi
    pop ebx
    ret
frame:
    push ebp
    mov ebp, esp
    sub esp, 16
    mov edx, [ebp + 8]
    mov [ebp - 4], edx
    mov edx, [ebp + 12]
    add edx, [ebp - 4]
    mov [ebp - 8], edx
    push ebx
    push esi
    mov ebx, [ebp + 16]
    lea esi, [edx + ebx]
    xor eax, esi
    pop esi
    pop ebx
    mov esp, ebp
    pop ebp
    ret
                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/bench/src/m_string.asm                                                             0000644 0000000 0000000 00000001464 00000000000 015225  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; REP string instructions: MOVSD/STOSD blocks, MOVSB tails, SCASB searches
; and CMPSD compares over small and page-sized buffers.
%include "micro.inc"
_bench_main:
    push ebx
    push esi
    push edi
    mov ebx, [esp + 16]
    shl ebx, 4
    cld
.loop:
    mov esi, source
    mov edi, target
    mov ecx, 1024
    rep movsd
    mov edi, target + 4096
    mov eax, ebx
    mov ecx, 64
    rep stosd
    mov esi, source + 1
    mov edi, target + 8192 + 3
    mov ecx, 37
    rep movsb
    mov edi, source
    mov al, 0x5A
    mov ecx, 512
    repne scasb
    mov esi, source
    mov edi, target
    mov ecx, 256
    repe cmpsd
    dec ebx
    jnz .loop
    mov eax, [target + 4096]
    add eax, ecx
    pop edi
    pop esi
    pop ebx
    ret
section .data
source: times 4096 db 0x11
section .bss
target: resb 12288
                                                                                                                                                                                                            source/v64/tests/bench/src/m_x87.asm                                                                0000644 0000000 0000000 00000001556 00000000000 014347  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; x87 register-stack arithmetic without memory operands (FLD ST(i), FMUL,
; FADD, FXCH, FSUB, FABS, FCHS, FADDP): a bounded fixed-point iteration.
%include "micro.inc"
_bench_main:
    mov ecx, [esp + 4]
    shl ecx, 12
    fld1
    fld1
    fadd st0, st0
    fdivp st1, st0          ; a = 0.5
    fld st0
    fmul st0, st0           ; b = 0.25
    fldz                    ; [x, b, a]
.loop:
    fld st0                 ; [x, x, b, a]
    fmul st0, st3           ; [x*a, x, b, a]
    fadd st0, st2           ; [y = x*a + b, x, b, a]
    fxch st1                ; [x, y, b, a]
    fsub st0, st1
    fabs
    fchs                    ; [-|x - y|, y, b, a]
    faddp st1, st0          ; [y - |x - y|, b, a]
    dec ecx
    jnz .loop
    fmul st0, st0
    fadd st0, st1
    fstp st1
    fstp st1
    push dword 1000000
    fimul dword [esp]
    fistp dword [esp]
    pop eax
    ret
                                                                                                                                                  source/v64/tests/bench/src/mandel.c                                                                 0000644 0000000 0000000 00000001270 00000000000 014300  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Mandelbrot set escape iterations in double precision (tight dependent
// multiply/add chains and a compare per iteration).
#include "../lib/bench.h"
u32 bench_main(u32 n)
{
    u32 h = 0;
    for(u32 frame = 0; frame < n; frame++) {
        double zoom = 1.0 / (1 + frame % 8);
        for(int y = 0; y < 48; y++)
            for(int x = 0; x < 64; x++) {
                double cr = -0.75 + (x - 32) * 0.05 * zoom, ci = 0.1 + (y - 24) * 0.05 * zoom, zr = 0, zi = 0;
                int k = 0;
                while(k < 64 && zr * zr + zi * zi < 4.0) { double t = zr * zr - zi * zi + cr; zi = 2 * zr * zi + ci; zr = t; k++; }
                h = mix(h, k);
            }
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                        source/v64/tests/bench/src/matmul.c                                                                 0000644 0000000 0000000 00000003326 00000000000 014343  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Game-style single-precision math: 4x4 matrix products and transforming
// vertex arrays (built for both x87 and SSE scalar code generation).
#include "../lib/bench.h"
typedef struct { float m[4][4]; } mat4;
typedef struct { float x, y, z, w; } vec4;
static vec4 vertices[4096], out[4096];
NOINLINE static void multiply(mat4 *r, const mat4 *a, const mat4 *b)
{
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 4; j++)
            r->m[i][j] = a->m[i][0] * b->m[0][j] + a->m[i][1] * b->m[1][j] + a->m[i][2] * b->m[2][j] + a->m[i][3] * b->m[3][j];
}
NOINLINE static void transform(const mat4 *m, const vec4 *in, vec4 *o, u32 count)
{
    for(u32 i = 0; i < count; i++) {
        vec4 v = in[i];
        o[i].x = m->m[0][0] * v.x + m->m[0][1] * v.y + m->m[0][2] * v.z + m->m[0][3] * v.w;
        o[i].y = m->m[1][0] * v.x + m->m[1][1] * v.y + m->m[1][2] * v.z + m->m[1][3] * v.w;
        o[i].z = m->m[2][0] * v.x + m->m[2][1] * v.y + m->m[2][2] * v.z + m->m[2][3] * v.w;
        o[i].w = m->m[3][0] * v.x + m->m[3][1] * v.y + m->m[3][2] * v.z + m->m[3][3] * v.w;
    }
}
u32 bench_main(u32 n)
{
    mat4 a, b, r;
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 4; j++) { a.m[i][j] = (i == j) + 0.01f * (i + j); b.m[i][j] = (i == j) - 0.02f * (i - j); }
    for(u32 i = 0; i < 4096; i++) { vertices[i].x = i * 0.5f; vertices[i].y = 1.0f - i * 0.25f; vertices[i].z = i & 7; vertices[i].w = 1.0f; }
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        multiply(&r, &a, &b);
        a = r;
        transform(&r, vertices, out, 4096);
        h = mix(h, (u32)(i32)(out[i & 4095].x * 16.0f));
        if(i % 16 == 15) for(int p = 0; p < 4; p++) for(int q = 0; q < 4; q++) a.m[p][q] = (p == q) + 0.01f * (p - q);
    }
    return h;
}
                                                                                                                                                                                                                                                                                                          source/v64/tests/bench/src/memops.c                                                                 0000644 0000000 0000000 00000001612 00000000000 014340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Bulk memory: REP MOVS/STOS copies and fills of several sizes, overlapping
// memmove, byte-wise compares and a strided copy (TLB and string paths).
#include "../lib/bench.h"
static u8 a[1 << 20], b[1 << 20];
u32 bench_main(u32 n)
{
    u32 h = 0;
    static const u32 sizes[] = { 16, 64, 256, 4096, 65536, 1 << 20 };
    for(u32 i = 0; i < n; i++) {
        for(u32 s = 0; s < 6; s++) {
            u32 size = sizes[s], reps = (1 << 20) / size;
            for(u32 r = 0; r < reps; r++) memcpy(b + (r * size & ((1 << 20) - size)), a + ((r * 7 * size) & ((1 << 20) - size)), size);
            memset(a, i + s, size);
        }
        memmove(a + 3, a, 65536);
        memmove(b, b + 5, 65536);
        for(u32 k = 0; k < (1 << 20); k += 4096) memcpy(a + k, b + ((k * 3) & ((1 << 20) - 1)), 64);
        h = mix(mix(h, memcmp(a, b, 4096)), a[i & 0xFFFFF] + b[(i * 17) & 0xFFFFF]);
    }
    return h;
}
                                                                                                                      source/v64/tests/bench/src/micro.inc                                                                0000644 0000000 0000000 00000000167 00000000000 014504  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Shared prologue for the nasm micro-benchmarks: cdecl u32 bench_main(u32 n).
bits 32
global _bench_main
section .text
                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/bench/src/mmx.c                                                                    0000644 0000000 0000000 00000002524 00000000000 013644  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // MMX pixel blending (PUNPCKLBW/PMULLW/PADDW/PSRLW/PACKUSWB) and packed
// arithmetic with EMMS between passes, like DirectDraw-era software paths.
#include "../lib/bench.h"
#include <mmintrin.h>
static __m64 source[8192], destination[8192];
NOINLINE static u32 blend(u32 count, int alpha)
{
    const __m64 zero = _mm_setzero_si64(), a = _mm_set1_pi16(alpha), ia = _mm_set1_pi16(256 - alpha);
    __m64 total = _mm_setzero_si64();
    for(u32 i = 0; i < count; i++) {
        __m64 s = source[i], d = destination[i];
        __m64 lo = _mm_srli_pi16(_mm_add_pi16(_mm_mullo_pi16(_mm_unpacklo_pi8(s, zero), a), _mm_mullo_pi16(_mm_unpacklo_pi8(d, zero), ia)), 8);
        __m64 hi = _mm_srli_pi16(_mm_add_pi16(_mm_mullo_pi16(_mm_unpackhi_pi8(s, zero), a), _mm_mullo_pi16(_mm_unpackhi_pi8(d, zero), ia)), 8);
        __m64 r = _mm_packs_pu16(lo, hi);
        destination[i] = r;
        total = _mm_add_pi32(total, _mm_madd_pi16(lo, hi));
    }
    u32 h = _mm_cvtsi64_si32(total) ^ _mm_cvtsi64_si32(_mm_srli_si64(total, 32));
    _mm_empty();
    return h;
}
u32 bench_main(u32 n)
{
    u32 seed = 77;
    for(u32 i = 0; i < 8192; i++) { source[i] = _mm_set_pi32(lcg(&seed), lcg(&seed)); destination[i] = _mm_set_pi32(lcg(&seed), lcg(&seed)); }
    _mm_empty();
    u32 h = 0;
    for(u32 i = 0; i < n; i++) h = mix(h, blend(8192, 32 + (i & 127)));
    return h;
}
                                                                                                                                                                            source/v64/tests/bench/src/muldiv.c                                                                 0000644 0000000 0000000 00000001522 00000000000 014340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Integer multiply/divide heavy code: 32-bit MUL/DIV/IDIV, 64-bit products
// and libgcc 64-bit division (__udivdi3/__umoddi3), modular exponentiation.
#include "../lib/bench.h"
NOINLINE static u32 powmod(u32 base, u32 exponent, u32 modulus)
{
    u64 result = 1, b = base % modulus;
    while(exponent) {
        if(exponent & 1) result = result * b % modulus;
        b = b * b % modulus;
        exponent >>= 1;
    }
    return (u32)result;
}
NOINLINE static u32 gcd(u32 a, u32 b) { while(b) { u32 t = a % b; a = b; b = t; } return a; }
u32 bench_main(u32 n)
{
    u32 h = 0, seed = 3;
    for(u32 i = 0; i < n * 256; i++) {
        u32 a = lcg(&seed) | 1, b = lcg(&seed) >> 8 | 1;
        i32 s = (i32)a / (i32)(b | 3);
        h = mix(h, powmod(a, b, 1000000007u) + gcd(a, b) + (u32)s + a / b + (u32)((u64)a * b >> 32));
    }
    return h;
}
                                                                                                                                                                              source/v64/tests/bench/src/nbody.c                                                                  0000644 0000000 0000000 00000002332 00000000000 014153  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // n-body simulation in double precision: square roots and divisions in the
// inner loop (x87 and SSE2 scalar builds).
#include "../lib/bench.h"
#define BODIES 64
static double px[BODIES], py[BODIES], pz[BODIES], vx[BODIES], vy[BODIES], vz[BODIES], mass[BODIES];
NOINLINE static void step(double dt)
{
    for(int i = 0; i < BODIES; i++)
        for(int j = i + 1; j < BODIES; j++) {
            double dx = px[i] - px[j], dy = py[i] - py[j], dz = pz[i] - pz[j];
            double d2 = dx * dx + dy * dy + dz * dz + 0.01;
            double d = __builtin_sqrt(d2), f = dt / (d2 * d);
            vx[i] -= dx * mass[j] * f; vy[i] -= dy * mass[j] * f; vz[i] -= dz * mass[j] * f;
            vx[j] += dx * mass[i] * f; vy[j] += dy * mass[i] * f; vz[j] += dz * mass[i] * f;
        }
    for(int i = 0; i < BODIES; i++) { px[i] += dt * vx[i]; py[i] += dt * vy[i]; pz[i] += dt * vz[i]; }
}
u32 bench_main(u32 n)
{
    for(int i = 0; i < BODIES; i++) {
        px[i] = i * 1.5; py[i] = (i % 7) * 0.75; pz[i] = (i % 3) - 1.0;
        vx[i] = vy[i] = vz[i] = 0; mass[i] = 1.0 + (i & 3) * 0.25;
    }
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        step(0.001);
        h = mix(h, (u32)(i32)(px[i % BODIES] * 1000.0));
    }
    return h;
}
                                                                                                                                                                                                                                                                                                      source/v64/tests/bench/src/recursion.c                                                              0000644 0000000 0000000 00000001672 00000000000 015057  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // leela-like: recursive tree search (n-queens backtracking) and deep call
// chains (near CALL/RET, stack frames, returns to many call sites).
#include "../lib/bench.h"
NOINLINE static u32 queens(u32 row, u32 n, u32 columns, u32 left, u32 right)
{
    if(row == n) return 1;
    u32 count = 0, free = ~(columns | left | right) & ((1u << n) - 1);
    while(free) {
        u32 bit = free & -free;
        free ^= bit;
        count += queens(row + 1, n, columns | bit, (left | bit) << 1, (right | bit) >> 1);
    }
    return count;
}
NOINLINE static u32 fib(u32 n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
NOINLINE static u32 ackermann(u32 m, u32 n)
{
    if(!m) return n + 1;
    if(!n) return ackermann(m - 1, 1);
    return ackermann(m - 1, ackermann(m, n - 1));
}
u32 bench_main(u32 n)
{
    u32 h = 0;
    for(u32 i = 0; i < n; i++) h = mix(mix(mix(h, queens(0, 8, 0, 0, 0)), fib(16 + (i & 1))), ackermann(2, 20 + (i & 3)));
    return h;
}
                                                                      source/v64/tests/bench/src/simd_int.c                                                               0000644 0000000 0000000 00000002657 00000000000 014660  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SSE2 packed integer image processing: saturating adds, averages, byte
// shuffles via unpack, multiply-add and sum of absolute differences.
#include "../lib/bench.h"
#include <emmintrin.h>
static __m128i image[8192], reference[8192];
NOINLINE static u32 process(u32 count)
{
    __m128i sad = _mm_setzero_si128(), acc = _mm_setzero_si128();
    const __m128i zero = _mm_setzero_si128(), weights = _mm_set1_epi16(3);
    for(u32 i = 0; i < count; i++) {
        __m128i a = image[i], b = reference[i];
        __m128i blended = _mm_avg_epu8(_mm_adds_epu8(a, b), a);
        __m128i lo = _mm_unpacklo_epi8(blended, zero), hi = _mm_unpackhi_epi8(blended, zero);
        acc = _mm_add_epi32(acc, _mm_madd_epi16(_mm_add_epi16(lo, hi), weights));
        sad = _mm_add_epi64(sad, _mm_sad_epu8(a, b));
        image[i] = _mm_packus_epi16(_mm_srli_epi16(lo, 1), _mm_srli_epi16(hi, 1));
    }
    acc = _mm_add_epi32(acc, _mm_shuffle_epi32(acc, 0x4E));
    acc = _mm_add_epi32(acc, _mm_shuffle_epi32(acc, 0xB1));
    return _mm_cvtsi128_si32(acc) ^ _mm_cvtsi128_si32(sad) ^ _mm_cvtsi128_si32(_mm_srli_si128(sad, 8));
}
u32 bench_main(u32 n)
{
    u32 seed = 21;
    for(u32 i = 0; i < 8192; i++) {
        image[i] = _mm_set_epi32(lcg(&seed), lcg(&seed), lcg(&seed), lcg(&seed));
        reference[i] = _mm_set_epi32(lcg(&seed), lcg(&seed), lcg(&seed), lcg(&seed));
    }
    u32 h = 0;
    for(u32 i = 0; i < n; i++) h = mix(h, process(8192));
    return h;
}
                                                                                 source/v64/tests/bench/src/simd_sse.c                                                               0000644 0000000 0000000 00000003115 00000000000 014646  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Packed single-precision SSE: batched vertex transforms, dot products and
// reciprocal square roots (MOVAPS/MULPS/ADDPS/SHUFPS/RSQRTPS).
#include "../lib/bench.h"
#include <xmmintrin.h>
static __m128 positions[4096], normals[4096], results[4096];
NOINLINE static void transform(const __m128 rows[4], u32 count)
{
    for(u32 i = 0; i < count; i++) {
        __m128 v = positions[i];
        __m128 x = _mm_shuffle_ps(v, v, 0x00), y = _mm_shuffle_ps(v, v, 0x55), z = _mm_shuffle_ps(v, v, 0xAA), w = _mm_shuffle_ps(v, v, 0xFF);
        __m128 r = _mm_add_ps(_mm_add_ps(_mm_mul_ps(rows[0], x), _mm_mul_ps(rows[1], y)), _mm_add_ps(_mm_mul_ps(rows[2], z), _mm_mul_ps(rows[3], w)));
        __m128 n = normals[i];
        __m128 d = _mm_mul_ps(n, n);
        d = _mm_add_ps(d, _mm_shuffle_ps(d, d, 0x4E));
        d = _mm_add_ps(d, _mm_shuffle_ps(d, d, 0xB1));
        results[i] = _mm_add_ps(r, _mm_mul_ps(n, _mm_rsqrt_ps(_mm_max_ps(d, _mm_set1_ps(1e-6f)))));
    }
}
u32 bench_main(u32 n)
{
    for(u32 i = 0; i < 4096; i++) {
        positions[i] = _mm_set_ps(1.0f, (float)(i & 63), (float)(i >> 6), (float)i * 0.5f);
        normals[i] = _mm_set_ps(0.0f, 1.0f, (float)(i & 3), 0.5f);
    }
    __m128 rows[4] = { _mm_set_ps(0, 0, 0.1f, 1), _mm_set_ps(0, 0.1f, 1, 0), _mm_set_ps(0, 1, 0, 0.1f), _mm_set_ps(1, 0, 0, 0) };
    u32 h = 0;
    for(u32 i = 0; i < n; i++) {
        transform(rows, 4096);
        float lane[4];
        _mm_storeu_ps(lane, results[i & 4095]);
        h = mix(h, (u32)(i32)(lane[0] * 256.0f + lane[1]));
        rows[0] = _mm_add_ps(rows[0], _mm_set1_ps(0.001f));
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/bench/src/sort.c                                                                   0000644 0000000 0000000 00000003251 00000000000 014030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Quicksort through a comparator function pointer with insertion-sort
// leaves, plus a merge of sorted runs (indirect calls, swaps, recursion).
#include "../lib/bench.h"
#define N 32768
static i32 data[N], scratch[N];
typedef int (*compare_fn)(const void *, const void *);
static int ascending(const void *a, const void *b) { i32 x = *(const i32 *)a, y = *(const i32 *)b; return (x > y) - (x < y); }
NOINLINE static void quicksort(i32 *a, i32 lo, i32 hi, compare_fn cmp)
{
    while(hi - lo > 16) {
        i32 pivot = a[lo + (hi - lo) / 2], i = lo, j = hi;
        while(i <= j) {
            while(cmp(&a[i], &pivot) < 0) i++;
            while(cmp(&a[j], &pivot) > 0) j--;
            if(i <= j) { i32 t = a[i]; a[i] = a[j]; a[j] = t; i++; j--; }
        }
        if(j - lo < hi - i) { quicksort(a, lo, j, cmp); lo = i; }
        else { quicksort(a, i, hi, cmp); hi = j; }
    }
    for(i32 i = lo + 1; i <= hi; i++) {
        i32 v = a[i], j = i - 1;
        while(j >= lo && cmp(&a[j], &v) > 0) { a[j + 1] = a[j]; j--; }
        a[j + 1] = v;
    }
}
NOINLINE static void merge(i32 *out, const i32 *a, u32 na, const i32 *b, u32 nb)
{
    u32 i = 0, j = 0, k = 0;
    while(i < na && j < nb) out[k++] = a[i] <= b[j] ? a[i++] : b[j++];
    while(i < na) out[k++] = a[i++];
    while(j < nb) out[k++] = b[j++];
}
u32 bench_main(u32 n)
{
    u32 h = 0, seed = 5;
    for(u32 r = 0; r < n; r++) {
        for(u32 i = 0; i < N; i++) data[i] = (i32)lcg(&seed);
        quicksort(data, 0, N / 2 - 1, ascending);
        quicksort(data, N / 2, N - 1, ascending);
        merge(scratch, data, N / 2, data + N / 2, N / 2);
        for(u32 i = 0; i < N; i += 97) h = mix(h, scratch[i]);
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/bench/src/strings.c                                                                0000644 0000000 0000000 00000003475 00000000000 014542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // xalancbmk-like: tokenizing text, hashing words into a chained table, string
// comparisons and byte loops.
#include "../lib/bench.h"
static char text[65536];
struct entry { const char *word; u32 length, count; struct entry *next; };
static struct entry entries[8192];
static struct entry *buckets[1024];
static const char *const words[] = { "the", "quick", "brown", "fox", "jumps", "over", "lazy", "dog",
    "element", "attribute", "namespace", "document", "stylesheet", "template", "select", "value" };
NOINLINE static void make_text(void)
{
    u32 seed = 7, at = 0;
    while(at < sizeof(text) - 16) {
        const char *w = words[lcg(&seed) >> 28];
        while(*w) text[at++] = *w++;
        text[at++] = (lcg(&seed) >> 29) ? ' ' : '\n';
    }
    text[at] = 0;
}
static int compare(const char *a, const char *b, u32 n)
{
    for(u32 i = 0; i < n; i++) if(a[i] != b[i]) return a[i] - b[i];
    return 0;
}
NOINLINE static u32 index_text(void)
{
    u32 used = 0;
    memset(buckets, 0, sizeof(buckets));
    for(const char *p = text; *p;) {
        while(*p == ' ' || *p == '\n') p++;
        const char *start = p;
        u32 h = 2166136261u;
        while(*p && *p != ' ' && *p != '\n') h = (h ^ (u8)*p++) * 16777619u;
        u32 len = p - start;
        if(!len) break;
        struct entry **b = &buckets[h & 1023], *e = *b;
        while(e && (e->length != len || compare(e->word, start, len))) e = e->next;
        if(e) e->count++;
        else if(used < 8192) { e = &entries[used++]; e->word = start; e->length = len; e->count = 1; e->next = *b; *b = e; }
    }
    u32 h = 0;
    for(u32 i = 0; i < used; i++) h = mix(h, entries[i].count * entries[i].length);
    return h;
}
u32 bench_main(u32 n)
{
    make_text();
    u32 h = 0;
    for(u32 i = 0; i < n; i++) { h = mix(h, index_text()); text[i % 60000] ^= 1; }
    return h;
}
                                                                                                                                                                                                   source/v64/tests/bench/src/trig.c                                                                   0000644 0000000 0000000 00000002031 00000000000 014001  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // x87 transcendental and root instructions (FSIN/FCOS/FSINCOS/FPATAN/FSQRT/
// FSCALE/FRNDINT) as used by rotation and animation code.
#include "../lib/bench.h"
static inline double fsin(double x) { double r; __asm__("fsin" : "=t"(r) : "0"(x)); return r; }
static inline double fcos(double x) { double r; __asm__("fcos" : "=t"(r) : "0"(x)); return r; }
static inline double fatan2(double y, double x) { double r; __asm__("fpatan" : "=t"(r) : "0"(x), "u"(y) : "st(1)"); return r; }
static inline double fsqrt(double x) { double r; __asm__("fsqrt" : "=t"(r) : "0"(x)); return r; }
static inline double frnd(double x) { double r; __asm__("frndint" : "=t"(r) : "0"(x)); return r; }
u32 bench_main(u32 n)
{
    u32 h = 0;
    double angle = 0.001;
    for(u32 i = 0; i < n * 1024; i++) {
        double s = fsin(angle), c = fcos(angle), a = fatan2(s, c + 1.5), r = fsqrt(s * s + c * c + a * a);
        angle += 0.0137 * frnd(r * 3.0);
        if(angle > 6.2831853) angle -= 6.2831853;
        h = mix(h, (u32)(i32)(r * 65536.0));
    }
    return h;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/bench/src/vcall.c                                                                  0000644 0000000 0000000 00000004345 00000000000 014147  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // omnetpp-like: discrete event simulation with a binary-heap event queue and
// virtual dispatch through vtables (indirect calls, pointer-heavy structs).
#include "../lib/bench.h"
struct module;
struct vtable { u32 (*handle)(struct module *, u32 time); u32 (*delay)(struct module *); };
struct module { const struct vtable *vt; u32 state, count, id; };
struct event { u32 time; struct module *target; };
static struct event heap[4096];
static u32 heap_size;
static struct module modules[64];
static void push(u32 time, struct module *m)
{
    u32 i = heap_size++;
    while(i && heap[(i - 1) / 2].time > time) { heap[i] = heap[(i - 1) / 2]; i = (i - 1) / 2; }
    heap[i].time = time; heap[i].target = m;
}
static struct event pop(void)
{
    struct event top = heap[0], last = heap[--heap_size];
    u32 i = 0;
    for(;;) {
        u32 c = 2 * i + 1;
        if(c >= heap_size) break;
        if(c + 1 < heap_size && heap[c + 1].time < heap[c].time) c++;
        if(heap[c].time >= last.time) break;
        heap[i] = heap[c]; i = c;
    }
    heap[i] = last;
    return top;
}
static u32 queue_handle(struct module *m, u32 t) { m->state = m->state * 3 + t; return ++m->count; }
static u32 queue_delay(struct module *m) { return 5 + (m->state & 15); }
static u32 router_handle(struct module *m, u32 t) { m->state ^= t << (m->id & 7); return m->count += 2; }
static u32 router_delay(struct module *m) { return 3 + (m->state >> 28); }
static u32 sink_handle(struct module *m, u32 t) { m->state += t; return m->count; }
static u32 sink_delay(struct module *m) { return 11 + (m->id & 3); }
static const struct vtable vtables[3] = {
    { queue_handle, queue_delay }, { router_handle, router_delay }, { sink_handle, sink_delay },
};
u32 bench_main(u32 n)
{
    for(u32 i = 0; i < 64; i++) { modules[i].vt = &vtables[i % 3]; modules[i].state = i; modules[i].count = 0; modules[i].id = i; }
    heap_size = 0;
    for(u32 i = 0; i < 1024; i++) push(i * 7 % 1000, &modules[i & 63]);
    u32 h = 0;
    for(u32 i = 0; i < n * 1024; i++) {
        struct event e = pop();
        struct module *m = e.target;
        h = mix(h, m->vt->handle(m, e.time));
        struct module *next = &modules[(m->state + i) & 63];
        push(e.time + m->vt->delay(m), next);
    }
    return h;
}
                                                                                                                                                                                                                                                                                           source/v64/tests/bench/suite.json                                                                   0000644 0000000 0000000 00000022254 00000000000 014136  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
  "comment": "v86 CPU benchmark suite. Each benchmark is one guest program; iterations sets the work of one timed run.",
  "profiles": {
    "int": "-O2 -march=i686 -mtune=pentium4 -mno-sse -mno-mmx -mfpmath=387",
    "x87": "-O2 -march=i686 -mtune=pentium4 -mno-sse -mno-mmx -mfpmath=387 -fno-math-errno",
    "x87_i586": "-O2 -march=pentium -mfpmath=387 -fno-math-errno",
    "sse": "-O2 -march=pentium4 -msse2 -mfpmath=sse -fno-math-errno",
    "avx": "-O2 -march=pentium4 -mavx -mprefer-vector-width=128 -mfpmath=sse -fno-math-errno",
    "mmx": "-O2 -march=pentium-mmx -mmmx -mfpmath=387"
  },
  "comment64": "x86-64 builds of the C benchmarks with these profiles (tools/bench/build.mjs, docs/jit-unification-plan.md P0.3): nocona as pentium4's counterpart; int without SSE registers or vectorization, as the i686 int profile",
  "profiles64": {
    "int": "-O2 -mtune=nocona -mgeneral-regs-only -fno-tree-vectorize",
    "x87": "-O2 -mtune=nocona -mfpmath=387 -fno-math-errno",
    "sse": "-O2 -mtune=nocona -mfpmath=sse -fno-math-errno",
    "avx": "-O2 -mtune=nocona -mavx -mprefer-vector-width=128 -mfpmath=sse -fno-math-errno"
  },
  "benchmarks": [
    {"name": "500.bytecode", "category": "int", "source": "bytecode.c", "profile": "int", "iterations": 310, "about": "perlbench-like switch-dispatched bytecode interpreter" },
    {"name": "502.codebloat", "category": "int", "source": "@codebloat", "profile": "int", "iterations": 250, "about": "gcc-like: 600 distinct functions, large code footprint, calls in data-dependent order" },
    {"name": "505.chase", "category": "memory", "source": "chase.c", "profile": "int", "iterations": 330, "about": "mcf-like pointer chasing over a permuted 2 MiB list and a search tree" },
    {"name": "520.vcall", "category": "control", "source": "vcall.c", "profile": "int", "iterations": 490, "about": "omnetpp-like event queue with virtual dispatch through vtables" },
    {"name": "523.strings", "category": "int", "source": "strings.c", "profile": "int", "iterations": 85, "about": "xalancbmk-like tokenizing, hashing and string compares" },
    {"name": "531.bitboard", "category": "int", "source": "bitboard.c", "profile": "int", "iterations": 370, "about": "deepsjeng-like 64-bit bitboard search on a 32-bit CPU" },
    {"name": "541.recursion", "category": "control", "source": "recursion.c", "profile": "int", "iterations": 390, "about": "leela-like recursive search: n-queens, fib, ackermann" },
    {"name": "557.lz", "category": "int", "source": "lz.c", "profile": "int", "iterations": 13, "about": "xz-like LZ77 compression, decompression and verification" },
    {"name": "560.hash", "category": "int", "source": "hash.c", "profile": "int", "iterations": 66, "about": "SHA-256, table CRC-32 and Adler-32 over 16 KiB" },
    {"name": "561.sort", "category": "int", "source": "sort.c", "profile": "int", "iterations": 24, "about": "quicksort through a comparator pointer, merge of runs" },
    {"name": "562.muldiv", "category": "int", "source": "muldiv.c", "profile": "int", "iterations": 620, "about": "32/64-bit multiply, divide, modular exponentiation" },
    {"name": "563.memops", "category": "memory", "source": "memops.c", "profile": "int", "iterations": 22, "about": "REP MOVS/STOS copies and fills, memmove, strided copies" },
    {"name": "600.matmul.x87", "category": "x87", "source": "matmul.c", "profile": "x87", "iterations": 85, "about": "float 4x4 matrix products and vertex transforms, x87 code" },
    {"name": "601.matmul.sse", "category": "sse", "source": "matmul.c", "profile": "sse", "iterations": 740, "about": "same source, SSE scalar/packed code" },
    {"name": "605.nbody.x87", "category": "x87", "source": "nbody.c", "profile": "x87", "iterations": 170, "about": "double-precision n-body with sqrt/div, x87 code" },
    {"name": "606.nbody.sse", "category": "sse", "source": "nbody.c", "profile": "sse", "iterations": 870, "about": "same source, SSE2 scalar double code" },
    {"name": "610.mandel.x87", "category": "x87", "source": "mandel.c", "profile": "x87", "iterations": 15, "about": "Mandelbrot escape loop, x87 code" },
    {"name": "611.mandel.sse", "category": "sse", "source": "mandel.c", "profile": "sse", "iterations": 69, "about": "same source, SSE2 code" },
    {"name": "615.ftol", "category": "x87", "source": "ftol.c", "profile": "x87", "iterations": 250, "about": "float/int conversions: FNSTCW/FLDCW/FISTP, FILD" },
    {"name": "616.fcompare", "category": "x87", "source": "fcompare.c", "profile": "x87_i586", "iterations": 290, "about": "i586 float branches: FCOMP + FNSTSW AX + SAHF" },
    {"name": "617.trig", "category": "x87", "source": "trig.c", "profile": "x87", "iterations": 320, "about": "FSIN/FCOS/FPATAN/FSQRT/FRNDINT" },
    {"name": "620.simd.sse", "category": "sse", "source": "simd_sse.c", "profile": "sse", "iterations": 400, "about": "packed float vertex transforms, RSQRTPS" },
    {"name": "621.simd.int", "category": "sse", "source": "simd_int.c", "profile": "sse", "iterations": 310, "about": "SSE2 packed integer image processing, PSADBW" },
    {"name": "625.mmx", "category": "mmx", "source": "mmx.c", "profile": "mmx", "iterations": 290, "about": "MMX pixel blending with EMMS" },
    {"name": "700.alu", "category": "micro", "source": "m_alu.asm", "iterations": 1200, "about": "register ALU and FLAGS" },
    {"name": "701.branch", "category": "micro", "source": "m_branch.asm", "iterations": 2000, "about": "unpredictable data-dependent branches" },
    {"name": "702.call", "category": "micro", "source": "m_call.asm", "iterations": 3100, "about": "near CALL/RET" },
    {"name": "703.icall", "category": "micro", "source": "m_icall.asm", "iterations": 2500, "about": "indirect calls through a table" },
    {"name": "704.jtable", "category": "micro", "source": "m_jtable.asm", "iterations": 2200, "about": "jump-table switch" },
    {"name": "705.stack", "category": "micro", "source": "m_stack.asm", "iterations": 3000, "about": "PUSH/POP and EBP frames" },
    {"name": "706.memory", "category": "micro", "source": "m_memory.asm", "iterations": 3500, "about": "indexed, unaligned, byte/word loads and stores" },
    {"name": "707.rmw", "category": "micro", "source": "m_rmw.asm", "iterations": 3000, "about": "read-modify-write memory operands, LOCK XADD" },
    {"name": "708.pages", "category": "micro", "source": "m_pages.asm", "iterations": 1400, "about": "control flow crossing a 4 KiB code page every step" },
    {"name": "709.smc", "category": "micro", "source": "m_smc.asm", "iterations": 520, "about": "self-modifying code every 64 calls" },
    {"name": "710.string", "category": "micro", "source": "m_string.asm", "iterations": 5900, "about": "REP MOVSD/STOSD/MOVSB/SCASB/CMPSD" },
    {"name": "711.x87", "category": "micro", "source": "m_x87.asm", "iterations": 1100, "about": "x87 register-stack arithmetic" },
    {"name": "712.sse4.int", "category": "sse4", "source": "m_sse4int.asm", "iterations": 100, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2"], "about": "SSE4.1 PMINUD/PMAXSD/PMULLD/PCMPGTQ/PBLENDW/BLENDPS/PACKUSDW" },
    {"name": "713.sse4.round", "category": "sse4", "source": "m_sse4round.asm", "iterations": 100, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2"], "about": "SSE4.1 ROUNDSD/ROUNDSS/ROUNDPD over finite values" },
    {"name": "714.sse4.strings", "category": "sse4", "source": "m_sse4strings.asm", "iterations": 100, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2"], "about": "SSE4.2 PCMPISTRI strlen and first-vowel search" },
    {"name": "715.avx.matmul", "category": "avx", "source": "matmul.c", "profile": "avx", "iterations": 740, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], "cpu_features_unreleased": true, "about": "601's source, AVX (VEX.128) code" },
    {"name": "716.avx.nbody", "category": "avx", "source": "nbody.c", "profile": "avx", "iterations": 870, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], "cpu_features_unreleased": true, "about": "606's source, AVX scalar double code" },
    {"name": "717.avx.mandel", "category": "avx", "source": "mandel.c", "profile": "avx", "iterations": 69, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], "cpu_features_unreleased": true, "about": "611's source, AVX code" },
    {"name": "718.avx.ymm", "category": "avx", "source": "m_avx256.asm", "iterations": 600, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], "cpu_features_unreleased": true, "about": "VEX.256 moves: VMOVDQA/VMOVDQU/VMOVNTDQ/VMOVUPS ymm" },
    {"name": "719.avx2.scan", "category": "avx", "source": "m_avx2.asm", "iterations": 300, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "AVX2"], "cpu_features_unreleased": true, "about": "AVX2 hot forms: a strlen-like scan with VPCMPEQB/VPMINUB/VPMOVMSKB ymm" },
    {"name": "720.bmi.bits", "category": "bmi", "source": "m_bmi.asm", "iterations": 60, "cpu_type": "x86_64", "cpu_features": ["BMI1", "BMI2", "LZCNT", "MOVBE"], "cpu_features_unreleased": true, "about": "BMI hot forms: each set bit with TZCNT/BLSR, LZCNT/SHLX/BZHI/BLSMSK/ANDN/SARX/SHRX, MOVBE loads" },
    {"name": "721.fma.poly", "category": "fma", "source": "m_fma.asm", "iterations": 2000, "cpu_features": ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "FMA"], "cpu_features_unreleased": true, "about": "FMA hot forms: Horner polynomials with VFMADD213SD/VFMADD132SD/VFMADD231SD" }
  ]
}
                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/benchmark/arch-bytemark.js                                                         0000755 0000000 0000000 00000004252 00000000000 016055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import path from "node:path";
import url from "node:url";
const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const BENCH_COLLECT_STATS = +process.env.BENCH_COLLECT_STATS;
const { V86 } = await import(BENCH_COLLECT_STATS ? "../../src/main.js" : "../../build/libv86.mjs");

const V86_ROOT = path.join(__dirname, "../..");

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: path.join(V86_ROOT, "/bios/seabios.bin") },
    vga_bios: { url: path.join(V86_ROOT, "/bios/vgabios.bin") },
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    vram_size: 8 * 1024 * 1024,
    net_device: {
        type: "virtio",
        relay_url: "<UNUSED>",
    },
    initial_state: { url: path.join(V86_ROOT, "/images/arch_state-v2.bin.zst") },
    filesystem: { baseurl: path.join(V86_ROOT, "/images/arch/") },
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
});

emulator.bus.register("emulator-started", function()
{
    let exclude_tests = [];

    if(process.argv.length > 2)
    {
        exclude_tests = [
            "DONUMSORT",
            "DOSTRINGSORT",
            "DOBITFIELD",
            "DOEMF",
            "DOFOUR",
            "DOASSIGN",
            "DOIDEA",
            "DOHUFF",
            "DONNET",
            "DOLU",
        ].filter(name => !process.argv.includes(name));
    }

    setTimeout(() => {
        const set = exclude_tests.map(name => `echo ${name}=0 >> CMD`).join(" && ");
        emulator.serial0_send(`echo 0 > /sys/class/graphics/fbcon/cursor_blink && cd nbench && touch CMD && ${set || "echo"} && ./nbench -cCMD\n`);
    }, 1000);
});

var line = "";

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        console.log("%s", line);
        line = "";
    }
    else
    {
        line += chr;
    }

    if(line === "* Trademarks are property of their respective holder.")
    {
        emulator.destroy();

        if(BENCH_COLLECT_STATS)
        {
            console.log(emulator.get_instruction_stats());
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/benchmark/arch-python.js                                                           0000755 0000000 0000000 00000003534 00000000000 015562  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const BENCH_COLLECT_STATS = +process.env.BENCH_COLLECT_STATS;
const { V86 } = await import(BENCH_COLLECT_STATS ? "../../src/main.js" : "../../build/libv86.mjs");

const V86_ROOT = path.join(__dirname, "../..");

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: path.join(V86_ROOT, "/bios/seabios.bin") },
    vga_bios: { url: path.join(V86_ROOT, "/bios/vgabios.bin") },
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    vram_size: 8 * 1024 * 1024,
    net_device: {
        type: "virtio",
        relay_url: "<UNUSED>",
    },
    initial_state: { url: path.join(V86_ROOT, "/images/arch_state-v2.bin.zst") },
    filesystem: { baseurl: path.join(V86_ROOT, "/images/arch/") },
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
});

emulator.bus.register("emulator-started", function()
{
    emulator.create_file("/bench.py", Buffer.from(`
def fib(n):
    if n < 2:
        return n
    return fib(n-2) + fib(n-1)

n = 30
print("fib(", n, ")= ", fib(n))
`));

    setTimeout(() => {
        emulator.serial0_send(`python3 /bench.py > /dev/null && python /bench.py > /dev/null && time python /bench.py\n`);
    }, 1000);
});

var line = "";

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        console.log("%s", line);

        if(line.startsWith("sys"))
        {
            emulator.destroy();

            if(BENCH_COLLECT_STATS)
            {
                console.log(emulator.get_instruction_stats());
            }
        }

        line = "";
    }
    else
    {
        line += chr;
    }
});
                                                                                                                                                                    source/v64/tests/benchmark/fetch-download.js                                                        0000755 0000000 0000000 00000006125 00000000000 016223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import { createServer } from "node:http";
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const __filename = url.fileURLToPath(import.meta.url);

const USE_VIRTIO = !!process.env.USE_VIRTIO;
const BENCHFILE_SIZE = (parseInt(process.env.BENCHFILE_SIZE_MB, 10) || 32) * 1024 * 1024;

const { V86 } = await import("../../build/libv86.mjs");

const LOG_SERIAL = true;

if(isMainThread)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
        autostart: false,
        memory_size: 64 * 1024 * 1024,
        net_device: {
            relay_url: "fetch",
            type: USE_VIRTIO ? "virtio" : "ne2k",
        }
    });

    const server = new Worker(__filename, { workerData: BENCHFILE_SIZE });
    server.on("error", (e) => { throw new Error("server: " + e); });
    server.on("message", function(msg) {
        SERVER_PORT = msg;
        console.log("Server started on port " + SERVER_PORT);
        emulator.run();
    });

    let SERVER_PORT = 0;
    let serial_text = "";
    let booted = false;

    emulator.bus.register("emulator-started", function()
    {
        console.log("Booting now, please stand by");
    });

    emulator.add_listener("serial0-output-byte", function(byte)
    {
        var chr = String.fromCharCode(byte);

        if(LOG_SERIAL) process.stdout.write(chr);

        serial_text += chr;

        if(!booted && serial_text.endsWith("~% "))
        {
            booted = true;
            emulator.serial0_send(`udhcpc;curl --fail --connect-timeout 10 -s -o /dev/null -w '<%{exitcode}><%{speed_download}>\\t<DONE>' http://${SERVER_PORT}.external\n`);
        }

        if(serial_text.endsWith("\t<DONE>"))
        {
            console.log("\n---\n");
            emulator.destroy();
            server.terminate();
            parse_console(serial_text);
        }
    });
}
else
{
    const benchsize = workerData;
    const benchfile = Buffer.alloc(benchsize);

    const server = createServer(function(_, response) {
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("content-length", benchsize.toString(10));
        response.write(benchfile);
        response.end();
    });

    server.listen(0, () => parentPort.postMessage(server.address().port));
}

function parse_console(output) {
    const regex = /<(\d+)><(\d+)>\t<DONE>/.exec(output);

    if(!regex)
    {
        console.error("Can't parse console log");
        process.exit(1);
    }

    const exitcode = parseInt(regex[1], 10);
    const speed = parseInt(regex[2], 10); // in bytes

    if(exitcode !== 0)
    {
        console.error("Bench failed, curl returned non-zero exit code %s", exitcode);
        process.exit(exitcode);
    }

    console.log("Average download speed: %s kB/s", (speed / 1024).toFixed(2));
}
                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/benchmark/linux-boot.js                                                            0000755 0000000 0000000 00000004664 00000000000 015433  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const BENCH_COLLECT_STATS = +process.env.BENCH_COLLECT_STATS;
const { V86 } = await import(BENCH_COLLECT_STATS ? "../../src/main.js" : "../../build/libv86.mjs");

const V86_ROOT = path.join(__dirname, "../..");

const LOG_SERIAL = true;

if(true)
{
    var emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        cdrom: { url: __dirname + "/../../images/linux3.iso" },
        autostart: true,
        memory_size: 32 * 1024 * 1024,
        disable_jit: +process.env.DISABLE_JIT,
        log_level: 0,
    });
}
else
{
    var emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: path.join(V86_ROOT, "/bios/seabios.bin") },
        vga_bios: { url: path.join(V86_ROOT, "/bios/vgabios.bin") },
        autostart: true,
        memory_size: 512 * 1024 * 1024,
        vram_size: 8 * 1024 * 1024,
        network_relay_url: "<UNUSED>",
        bzimage_initrd_from_filesystem: true,
        cmdline: "rw console=ttyS0 apm=off root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose mitigations=off audit=0 tsc=reliable nowatchdog init=/usr/bin/init-openrc",
        filesystem: {
            basefs: {
                url: path.join(V86_ROOT, "/images/fs.json"),
            },
            baseurl: path.join(V86_ROOT, "/images/arch/"),
        },
        disable_jit: +process.env.DISABLE_JIT,
        log_level: 0,
    });
}

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
    start_time = Date.now();
});

var serial_text = "";
var start_time;

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(LOG_SERIAL) process.stdout.write(chr);

    serial_text += chr;

    if(serial_text.endsWith("~% ") || serial_text.endsWith("root@localhost:~# "))
    {
        const end_time = Date.now();
        const elapsed = end_time - start_time;
        console.log("Done in %dms", elapsed);
        emulator.destroy();

        if(BENCH_COLLECT_STATS)
        {
            console.log(emulator.get_instruction_stats());
        }
    }
});
                                                                            source/v64/tests/benchmark/snapshot.js                                                              0000755 0000000 0000000 00000003251 00000000000 015161  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import path from "node:path";
import url from "node:url";

const BENCH_COLLECT_STATS = +process.env.BENCH_COLLECT_STATS;
const { V86 } = await import(BENCH_COLLECT_STATS ? "../../src/main.js" : "../../build/libv86.mjs");

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const V86_ROOT = path.join(__dirname, "../..");

const LOG_SERIAL = true;


var emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux3.iso" },
    autostart: true,
    memory_size: 1024 * 1024 * 1024,
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
});


emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
    start_time = Date.now();
});

var serial_text = "";
var start_time;

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(LOG_SERIAL) process.stdout.write(chr);

    serial_text += chr;

    if(serial_text.endsWith("~% ") || serial_text.endsWith("root@localhost:~# "))
    {
        console.log("Creating snapshots");
        const start_time = Date.now();
        for(var i = 0; i < 10; ++i) emulator.save_state();
        const end_time = Date.now();
        const elapsed = end_time - start_time;
        console.log("Done in %dms", elapsed);
        emulator.destroy();

        if(BENCH_COLLECT_STATS)
        {
            console.log(emulator.get_instruction_stats());
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/decode/decode.rs                                                                   0000644 0000000 0000000 00000115537 00000000000 014056  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use super::*;

fn d(bytes: &[u8], mode32: bool) -> DecodedInstruction {
    decode(bytes, GuestEip(0xFFFE), LinearAddress(0x1FFFE), mode32).unwrap()
}

#[test]
fn prefixes_boundaries_and_missing_page() {
    let i = d(&[0x66, 0x66, 0x67, 0x64, 0x65, 0xB8, 0x34, 0x12], true);
    assert_eq!(i.length, 8);
    assert_eq!(i.operand_size, 16);
    assert_eq!(i.address_size, 16);
    assert_eq!(i.prefixes.segment, Some(5));
    assert_eq!(i.immediate, Some(0x1234));
    assert_eq!(i.next_pc, GuestEip(0x10006));
    assert_eq!(
        decode(&[0xB8, 1], GuestEip(4095), LinearAddress(4095), true).unwrap_err(),
        DecodeStop::Incomplete { available: 2 }
    );
    assert_eq!(d(&[0xB8, 1, 2, 3, 4], true).length, 5);
    let mut bytes = vec![0x66; 14];
    bytes.push(0x90);
    assert_eq!(d(&bytes, true).length, 15);
    bytes.insert(0, 0x66);
    assert_eq!(
        decode(&bytes, GuestEip(0), LinearAddress(0), true).unwrap_err(),
        DecodeStop::TooLong
    );
    assert_eq!(
        d(&[0xF3, 0xF2, 0x0F, 0x10, 0xC0], true).encoding.opcode,
        0xF20F10
    );
    // F2/F3 take precedence over 66 (decode_rules::mandatory_variant)
    assert_eq!(
        d(&[0xF2, 0x66, 0x0F, 0x10, 0xC0], true).encoding.opcode,
        0xF20F10
    );
    assert!(d(&[0xF0, 0x01, 0x00], true).prefixes.lock);
    assert!(d(&[0x8D, 0xC0], true).baseline_ud);
    assert_eq!(d(&[0x0F, 0x20, 0x04], true).length, 3); // ignore_mod, no SIB
    assert_eq!(
        d(&[0x9A, 1, 2, 3, 4, 5, 6], true).extra_immediate,
        Some(0x605)
    );
    assert_eq!(d(&[0xC8, 1, 2, 3], true).extra_immediate, Some(3));
}

#[test]
fn prefix_product_and_missing_groups_are_explicit() {
    use crate::decode_rules::{
        apply_prefix, mandatory_variant, Variant, REFINING_ALL, REFINING_REP,
    };
    use crate::prefix::*;
    // The mandatory-prefix rule, against an independent statement of it: the
    // last F2/F3 before 66; a refining prefix (all three in the SSE maps,
    // F2/F3 at MOVBE/CRC32) without a row is #UD, other prefixes are ignored
    // or set the operand size.
    for flags in 0..256u16 {
        let flags = flags as u8;
        if flags & PREFIX_F2 != 0 && flags & PREFIX_F3 != 0 {
            continue; // apply_prefix keeps only the last of the two
        }
        for available in 0..8 {
            let mask = (if available & 1 != 0 { PREFIX_66 } else { 0 })
                | (if available & 2 != 0 { PREFIX_F2 } else { 0 })
                | (if available & 4 != 0 { PREFIX_F3 } else { 0 });
            for refining in [0, REFINING_REP, REFINING_ALL] {
                let rep = flags & (PREFIX_F2 | PREFIX_F3);
                let expected = if rep != 0 && mask & rep != 0 {
                    Variant::Prefixed(rep)
                }
                else if refining & rep != 0 {
                    Variant::Undefined
                }
                else if refining & PREFIX_66 != 0 && flags & PREFIX_66 != 0 {
                    if mask & PREFIX_66 != 0 {
                        Variant::Prefixed(PREFIX_66)
                    }
                    else {
                        Variant::Undefined
                    }
                }
                else {
                    Variant::Plain
                };
                assert_eq!(mandatory_variant(flags, mask, refining), expected);
            }
        }
    }
    // of F2 and F3 the last one counts, in either order
    assert_eq!(
        apply_prefix(apply_prefix(0, 0xF2).unwrap(), 0xF3),
        Some(PREFIX_F3)
    );
    assert_eq!(
        apply_prefix(apply_prefix(0, 0xF3).unwrap(), 0xF2),
        Some(PREFIX_F2)
    );
    for a in [
        0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
    ] {
        for b in [
            0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
        ] {
            for mode in [false, true] {
                let mut bytes = vec![a, b, a, 0x0F, 0x10, 0xC0];
                let decoded = d(&bytes, mode);
                let flags = [a, b, a]
                    .into_iter()
                    .fold(0, |f, p| apply_prefix(f, p).unwrap());
                // 0F 10 has rows for all of 66, F2 and F3
                let expected =
                    match mandatory_variant(flags, PREFIX_66 | PREFIX_F2 | PREFIX_F3, REFINING_ALL)
                    {
                        Variant::Prefixed(PREFIX_66) => 0x660F10,
                        Variant::Prefixed(PREFIX_F2) => 0xF20F10,
                        Variant::Prefixed(PREFIX_F3) => 0xF30F10,
                        variant => {
                            assert_eq!(variant, Variant::Plain);
                            0x0F10
                        },
                    };
                assert_eq!(decoded.encoding.opcode, expected);
                assert!(!decoded.early_ud);
                // No read past the supplied snapshot, including prefix and ModRM boundaries.
                for n in 0..bytes.len() {
                    assert!(matches!(
                        decode(&bytes[..n], GuestEip(4094), LinearAddress(4094), mode),
                        Err(DecodeStop::Incomplete { .. })
                    ));
                }
                bytes[4] = 0x71;
                bytes[5] = 0x00;
                if matches!(decode(&bytes, GuestEip(0),LinearAddress(0),mode),Ok(ref i) if i.encoding.group_ud)
                {
                    let i = d(&bytes, mode);
                    assert!(i.baseline_ud);
                    assert!(i.ea.is_none());
                    assert!(i.immediate.is_none());
                }
            }
        }
    }
    // 66 with F3 is an operand-size prefix: MOVSS, as iced-x86 and XED decode
    assert_eq!(
        d(&[0x66, 0xF3, 0x0F, 0x10, 0xC1], true).encoding.opcode,
        0xF30F10
    );
    assert_eq!(
        d(&[0xF3, 0x66, 0x0F, 0x10, 0xC1], true).encoding.opcode,
        0xF30F10
    );
    // A mandatory prefix without a row: #UD after ModRM, without SIB,
    // displacement or immediate (F3 0F 2B is AMD's MOVNTSS, 66 0F C3 not MOVNTI)
    for bytes in [
        &[0xF3, 0x0F, 0x2B, 0x04, 0x24][..],
        &[0x66, 0x0F, 0xC3, 0x04, 0x24],
        &[0xF2, 0x0F, 0x77],
    ] {
        let i = d(bytes, true);
        assert!(
            i.baseline_ud && i.early_ud && i.ea.is_none(),
            "{bytes:02X?}"
        );
        assert_eq!(
            i.length as usize,
            bytes.len() - if bytes.len() > 3 { 1 } else { 0 },
            "{bytes:02X?}"
        );
    }
    // Outside the SSE maps F2/F3 are plain repeat prefixes
    let i = d(&[0xF3, 0x0F, 0xAF, 0xC1], true);
    assert!(i.encoding.opcode == 0x0FAF && !i.baseline_ud);
    for e in encodings().iter().filter(|e| e.group_ud) {
        let mut bytes = Vec::new();
        if e.opcode > 0xFFFF {
            bytes.push((e.opcode >> 16) as u8);
        }
        if e.opcode > 0xFF {
            bytes.push((e.opcode >> 8) as u8);
        }
        bytes.extend([e.opcode as u8, (e.group as u8) << 3 | 4]);
        let i = d(&bytes, true);
        assert!(i.baseline_ud && i.ea.is_none());
        assert_eq!(
            i.length as usize,
            bytes.len(),
            "missing /g must not fetch SIB/displacement/immediate"
        );
    }
}

#[test]
fn ea_and_wrapping() {
    let gpr = [0xFFFFFFFF, 0x1111, 0x2222, 0xFFFF, 0x100, 0xFFFE, 3, 5];
    let i = d(&[0x8B, 0x44, 0x88, 0xFC], true); // [eax + ecx*4 - 4]
    let ea = i.ea.unwrap();
    assert_eq!(ea.offset(&gpr), 0x443F);
    assert_eq!(ea.segment, 3);
    let i = d(&[0x8B, 0x46, 0x04], false); // [bp+4], 16-bit wrap
    assert_eq!(i.ea.unwrap().offset(&gpr), 2);
    assert_eq!(i.ea.unwrap().segment, 2);
    let i = d(&[0x8B, 0x04, 0xED, 1, 0, 0, 0], true); // [ebp*8 + 1], no base => DS
    assert_eq!(i.ea.unwrap().segment, 3);
    assert_eq!(i.ea.unwrap().offset(&gpr), 0x7FFF1);
    let i = d(&[0x8B, 0x06, 0xFF, 0xFF], false);
    assert_eq!(i.ea.unwrap().offset(&gpr), 65535);
    assert_eq!(i.ea.unwrap().segment, 3);
}

/// The opcode bytes of a catalogue key: mandatory prefix, escapes, opcode
fn catalogue_bytes(opcode: u32) -> Vec<u8> {
    if matches!(opcode >> 8 & 0xFFFF, 0x0F38 | 0x0F3A) {
        let mut bytes = if opcode >> 24 != 0 { vec![(opcode >> 24) as u8] } else { vec![] };
        bytes.extend([0x0F, (opcode >> 8) as u8, opcode as u8]);
        return bytes;
    }
    let mut bytes = Vec::new();
    if opcode > 0xFFFF {
        bytes.push((opcode >> 16) as u8);
    }
    if opcode > 0xFF {
        bytes.push((opcode >> 8) as u8);
    }
    bytes.push(opcode as u8);
    bytes
}

#[test]
fn catalogue_lengths_and_all_modrm_sib_forms() {
    let mut count = 0;
    // (VEX rows: vex_rows_decode_from_their_own_encodings)
    for encoding in encodings().iter().filter(|e| e.vex == 0) {
        for mode32 in [false, true] {
            for m in 0..if encoding.fetch_modrm { 256 } else { 1 } {
                if encoding.group >= 0 && (m >> 3 & 7) != encoding.group as u32 {
                    continue;
                }
                // (LES/LDS with a register ModRM byte: a VEX prefix; TZCNT
                // and LZCNT without their features: BSF and BSR, see
                // tzcnt_and_lzcnt_are_bsf_and_bsr_without_their_features)
                if matches!(encoding.opcode, 0xC4 | 0xC5) && m >= 0xC0
                    || matches!(encoding.opcode, 0xF30FBC | 0xF30FBD) && !encoding.exists()
                {
                    continue;
                }
                let mut bytes = catalogue_bytes(encoding.opcode);
                let op_size32 = mode32 != bytes.contains(&0x66);
                if encoding.fetch_modrm {
                    bytes.push(m as u8);
                }
                // A row whose semantics come later (or whose feature is
                // absent) is #UD right after its ModRM byte
                if encoding.unimplemented || !encoding.exists() {
                    let decoded = d(&bytes, mode32);
                    assert!(
                        decoded.early_ud && decoded.baseline_ud && decoded.ea.is_none(),
                        "{:x} {m:x}",
                        encoding.opcode
                    );
                    assert_eq!(
                        (decoded.encoding.id, decoded.length as usize),
                        (encoding.id, bytes.len()),
                        "{:x} {m:x}",
                        encoding.opcode
                    );
                    count += 1;
                    continue;
                }
                let sib_count =
                    if mode32 && encoding.e && !encoding.ignore_mod && m < 0xC0 && m & 7 == 4 {
                        256
                    }
                    else {
                        1
                    };
                for sib in 0..sib_count {
                    let mut sample = bytes.clone();
                    let mut displacement = 0;
                    if encoding.e && !encoding.ignore_mod && m < 0xC0 {
                        if mode32 && m & 7 == 4 {
                            sample.push(sib as u8);
                        }
                        displacement = match m >> 6 {
                            1 => 1,
                            2 => {
                                if mode32 {
                                    4
                                }
                                else {
                                    2
                                }
                            },
                            _ if mode32 && (m & 7 == 5 || m & 7 == 4 && sib & 7 == 5) => 4,
                            _ if !mode32 && m & 7 == 6 => 2,
                            _ => 0,
                        };
                    }
                    let imm = match encoding.immediate {
                        ImmediateKind::None => 0,
                        ImmediateKind::Byte | ImmediateKind::SignedByte => 1,
                        ImmediateKind::Word => 2,
                        ImmediateKind::Operand => {
                            if op_size32 {
                                4
                            }
                            else {
                                2
                            }
                        },
                        ImmediateKind::Address => {
                            if mode32 {
                                4
                            }
                            else {
                                2
                            }
                        },
                    };
                    sample.resize(
                        sample.len() + displacement + imm + encoding.extra_bytes as usize,
                        0x25,
                    );
                    let decoded = d(&sample, mode32);
                    assert_eq!(
                        decoded.encoding.id, encoding.id,
                        "{:x} {m:x}",
                        encoding.opcode
                    );
                    assert_eq!(
                        decoded.length as usize,
                        sample.len(),
                        "{:x} {m:x}",
                        encoding.opcode
                    );
                    for cut in 0..sample.len() {
                        assert!(
                            decode(&sample[..cut], GuestEip(0), LinearAddress(0), mode32).is_err()
                        );
                    }
                    count += 1;
                }
            }
        }
    }
    // Repeat, conflicting and address/segment prefixes against every catalogue
    // opcode in both modes. Padding allows prefix selection to change its form.
    let prefix_sets: &[&[u8]] = &[
        &[0x66],
        &[0x67],
        &[0x66, 0x67],
        &[0xF0],
        &[0xF2],
        &[0xF3],
        &[0xF2, 0xF3],
        &[0xF3, 0xF2],
        &[0x66, 0xF2, 0xF3],
        &[0xF3, 0x66, 0xF2],
        &[0x26, 0x36, 0x64, 0x65],
        &[0x66, 0x66, 0x67, 0x67],
        &[0xF3, 0xF3],
    ];
    for encoding in encodings() {
        for mode32 in [false, true] {
            for prefixes in prefix_sets {
                for memory in [false, true] {
                    let mut sample = prefixes.to_vec();
                    if encoding.opcode > 0xFFFF {
                        sample.push((encoding.opcode >> 16) as u8);
                    }
                    if encoding.opcode > 0xFF {
                        sample.push((encoding.opcode >> 8) as u8);
                    }
                    sample.push(encoding.opcode as u8);
                    if encoding.fetch_modrm {
                        sample.push(
                            (if memory { 4 } else { 0xC0 }) | (encoding.group.max(0) as u8) << 3,
                        );
                        if memory {
                            sample.push(0x9D);
                        }
                    }
                    sample.resize(15, 0x25);
                    if decode(&sample, GuestEip(0), LinearAddress(0), mode32).is_ok() {
                        count += 1;
                    }
                }
            }
        }
    }
    assert!(count > 1_000_000);
    println!("Checked {count} encoding/ModRM/SIB forms and all truncated prefixes");
}

#[test]
fn independent_disassembler_corpus() {
    use std::fs;
    fs::create_dir_all("build/ir-decode").unwrap();
    for mode32 in [false, true] {
        let mut bytes = Vec::new();
        let mut starts = Vec::new();
        let mut seed = 0x12345678u32;
        for i in 0..8192 {
            let mut instruction = Vec::new();
            // Restrict oracle corpus to instructions NDISASM and the baseline both implement.
            if i % 5 == 0 {
                instruction.push(0x66);
            }
            if i % 7 == 0 {
                instruction.push(0x67);
            }
            if i % 11 == 0 {
                instruction.push(0x64);
            }
            instruction.push([0x8B, 0x89, 0x01, 0x29, 0x31, 0x39][i % 6]);
            seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
            let m = (seed >> 16) as u8;
            instruction.push(m);
            let size32 = mode32 != instruction.contains(&0x67);
            let sib = seed as u8;
            let mut displacement = 0;
            if m < 0xC0 {
                if size32 && m & 7 == 4 {
                    instruction.push(sib);
                }
                displacement = match m >> 6 {
                    1 => 1,
                    2 => {
                        if size32 {
                            4
                        }
                        else {
                            2
                        }
                    },
                    _ if size32 && (m & 7 == 5 || m & 7 == 4 && sib & 7 == 5) => 4,
                    _ if !size32 && m & 7 == 6 => 2,
                    _ => 0,
                };
            }
            instruction.extend_from_slice(&seed.to_le_bytes()[..displacement]);
            assert_eq!(d(&instruction, mode32).length as usize, instruction.len());
            starts.push(bytes.len().to_string());
            bytes.extend(instruction);
        }
        let size = if mode32 { 32 } else { 16 };
        fs::write(format!("build/ir-decode/oracle-{size}.bin"), bytes).unwrap();
        fs::write(
            format!("build/ir-decode/oracle-{size}.json"),
            format!("[{}]", starts.join(",")),
        )
        .unwrap();
    }
}

#[test]
fn legacy_dispatch_boundary_and_invalid_form_fetch() {
    // A non-custom ModRM helper is an observer/block boundary even without
    // block_boundary set in the catalogue (e.g. BOUND).
    let bound = d(&[0x62, 0x00], true);
    assert_eq!(bound.flow, Flow::Boundary);
    // The baseline dispatch reads ModRM before selecting the invalid unprefixed
    // SSE3 form, then delivers UD without consuming an EA displacement.
    let bare = d(&[0x0F, 0x7C, 0x05], true);
    assert_eq!(bare.length, 3);
    assert!(bare.ea.is_none());
    assert!(matches!(
        decode(&[0x0F, 0x7C], GuestEip(0), LinearAddress(0), true),
        Err(DecodeStop::Incomplete { .. })
    ));
    let prefixed = d(&[0x66, 0x0F, 0x7C, 0x05, 1, 2, 3, 4], true);
    assert_eq!(prefixed.length, 8);
    assert!(prefixed.ea.is_some());
}

#[test]
fn lock_requires_a_supported_memory_destination() {
    use crate::decode_rules::lock_allowed;
    use crate::prefix::PREFIX_LOCK;
    assert_eq!(
        crate::decode_rules::apply_prefix(0, 0xF0),
        Some(PREFIX_LOCK)
    );
    for opcode in [
        0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19, 0x20, 0x21, 0x28, 0x29, 0x30, 0x31, 0x86,
        0x87, 0x0FAB, 0x0FB0, 0x0FB1, 0x0FB3, 0x0FBB, 0x0FC0, 0x0FC1,
    ] {
        for modrm in 0..=255 {
            assert_eq!(lock_allowed(opcode, Some(modrm)), modrm < 0xC0);
        }
    }
    for (opcode, groups) in [
        (0x80, 0x7F),
        (0x81, 0x7F),
        (0x82, 0x7F),
        (0x83, 0x7F),
        (0xF6, 0x0C),
        (0xF7, 0x0C),
        (0xFE, 3),
        (0xFF, 3),
        (0x0FBA, 0xE0),
        (0x0FC7, 2),
    ] {
        for modrm in 0..=255 {
            assert_eq!(
                lock_allowed(opcode, Some(modrm)),
                modrm < 0xC0 && groups >> (modrm >> 3 & 7) & 1 != 0
            );
        }
    }
    for bytes in [
        &[0xF0, 0x90][..],
        &[0xF0, 0x01, 0xD8],
        &[0xF0, 0x89, 0x07],
        &[0xF0, 0x0F, 0xC7, 0xC8],
        &[0xF0, 0x83, 0x3F, 1],
        &[0xF0, 0x0F, 0xBA, 0x27, 1],
        &[0xF0, 0x03, 0x07],
    ] {
        assert!(d(bytes, true).baseline_ud, "{bytes:02x?}");
    }
    for bytes in [
        &[0xF0, 0x01, 0x07][..],
        &[0xF0, 0x66, 0xFF, 0x07],
        &[0x66, 0xF0, 0xFF, 0x07],
        &[0xF0, 0x0F, 0xC7, 0x0F],
    ] {
        assert!(!d(bytes, true).baseline_ud, "{bytes:02x?}");
    }
}

#[test]
fn three_byte_maps_decode_and_stay_undefined_without_their_features() {
    use crate::cpu::features::{ALL, TEST_FEATURES};
    for features in [0, ALL] {
        TEST_FEATURES.with(|f| f.set(features));
        for (bytes, key) in [
            (&[0x0F, 0x38, 0xF1, 0x04, 0x24][..], 0x0F38F1), // movbe [esp]
            (&[0x0F, 0x38, 0xF0, 0x00], 0x0F38F0),           // movbe
            (&[0x66, 0x0F, 0x38, 0xF1, 0x00], 0x0F38F1),     // movbe m16 (66: operand size)
        ] {
            // without MOVBE #UD after the ModRM byte (no SIB read); with it
            // (P10) the whole memory operand
            let i = d(bytes, true);
            let length =
                if features == 0 && bytes[3] == 0x04 { bytes.len() - 1 } else { bytes.len() };
            assert_eq!(
                (i.early_ud, i.baseline_ud, i.ea.is_none()),
                (features == 0, features == 0, features == 0),
                "{bytes:02X?}"
            );
            assert!(i.immediate.is_none(), "{bytes:02X?}");
            assert_eq!(
                (i.encoding.opcode, i.length as usize),
                (key, length),
                "{bytes:02X?}"
            );
        }
        // F3 at MOVBE/CRC32 and 66 at the MOVBE rows' CRC32 are refused; an
        // unprefixed 0F 38 10 has no row
        for bytes in [
            &[0xF3, 0x0F, 0x38, 0xF0, 0x00][..],
            &[0x0F, 0x38, 0x10, 0xC1],
        ] {
            let i = d(bytes, true);
            assert!(
                i.early_ud && i.length as usize == bytes.len(),
                "{bytes:02X?}"
            );
        }
        // an opcode byte without rows is unknown (#UD at that byte when run)
        assert_eq!(
            decode(
                &[0x0F, 0x38, 0xFF, 0xC1],
                GuestEip(0),
                LinearAddress(0),
                true
            )
            .unwrap_err(),
            DecodeStop::UnknownEncoding { opcode: 0x0F38FF }
        );
        // the escape and third byte belong to the instruction
        assert!(matches!(
            decode(&[0x66, 0x0F, 0x38], GuestEip(0), LinearAddress(0), true),
            Err(DecodeStop::Incomplete { .. })
        ));
    }
    TEST_FEATURES.with(|f| f.set(0));
}

#[test]
fn sse42_rows_decode_with_their_feature() {
    use crate::cpu::features::{SSE4_1, SSE4_2, SSSE3, TEST_FEATURES};
    for features in [SSSE3 | SSE4_1, SSSE3 | SSE4_1 | SSE4_2] {
        TEST_FEATURES.with(|f| f.set(features));
        for mode32 in [false, true] {
            let w32 = if mode32 { 32 } else { 16 };
            // (the operand size: CRC32's source; none for PCMPxSTRx, whose 66 is mandatory)
            for (bytes, key, memory, imm8, operand_size) in [
                (
                    &[0x66, 0x0F, 0x3A, 0x63, 0xC1, 0x0C][..],
                    0x660F3A63,
                    false,
                    Some(0x0C),
                    None,
                ), // pcmpistri
                (
                    &[0x66, 0x0F, 0x3A, 0x60, 0x07, 0x40],
                    0x660F3A60,
                    true,
                    Some(0x40),
                    None,
                ), // pcmpestrm [..]
                (
                    &[0xF2, 0x0F, 0x38, 0xF0, 0xC1],
                    0xF20F38F0,
                    false,
                    None,
                    Some(w32),
                ), // crc32 r32, r/m8
                (
                    &[0xF2, 0x0F, 0x38, 0xF1, 0x07],
                    0xF20F38F1,
                    true,
                    None,
                    Some(w32),
                ), // crc32 r32, [..]
                // (66 is the operand size)
                (
                    &[0x66, 0xF2, 0x0F, 0x38, 0xF1, 0xC1],
                    0xF20F38F1,
                    false,
                    None,
                    Some(48 - w32),
                ),
            ] {
                let i = d(bytes, mode32);
                assert_eq!(i.encoding.opcode, key, "{bytes:02X?}");
                if features & SSE4_2 == 0 {
                    // #UD right after the ModRM byte: no EA, no immediate
                    assert!(i.early_ud && i.baseline_ud && i.ea.is_none() && i.immediate.is_none());
                    assert_eq!(i.length as usize, bytes.len() - imm8.map_or(0, |_| 1));
                    continue;
                }
                assert!(!i.early_ud && !i.baseline_ud, "{bytes:02X?}");
                assert_eq!(
                    (i.length as usize, i.ea.is_some(), i.immediate),
                    (bytes.len(), memory, imm8),
                    "{bytes:02X?}"
                );
                assert!(operand_size.is_none_or(|size| i.operand_size == size));
            }
            // F3 selects no CRC32
            assert!(d(&[0xF3, 0x0F, 0x38, 0xF1, 0xC1], mode32).early_ud);
        }
    }
    TEST_FEATURES.with(|f| f.set(0));
}

#[test]
fn ssse3_rows_decode_with_their_feature() {
    use crate::cpu::features::{SSSE3, TEST_FEATURES};
    for features in [0, SSSE3] {
        TEST_FEATURES.with(|f| f.set(features));
        for mode32 in [false, true] {
            for (bytes, key, memory, imm8) in [
                (&[0x66, 0x0F, 0x38, 0x00, 0xC1][..], 0x660F3800, false, None), // pshufb xmm
                (&[0x0F, 0x38, 0x04, 0xC1], 0x0F3804, false, None),             // pmaddubsw mm
                (&[0x0F, 0x38, 0x1C, 0x07], 0x0F381C, true, None),              // pabsb mm, [..]
                (
                    &[0x66, 0x0F, 0x3A, 0x0F, 0xC1, 0x11],
                    0x660F3A0F,
                    false,
                    Some(0x11),
                ), // palignr
                (&[0x0F, 0x3A, 0x0F, 0x07, 0x80], 0x0F3A0F, true, Some(0x80)),
            ] {
                let i = d(bytes, mode32);
                assert_eq!(i.encoding.opcode, key, "{bytes:02X?}");
                if features == 0 {
                    // #UD right after the ModRM byte: no EA, no immediate
                    assert!(i.early_ud && i.baseline_ud && i.ea.is_none() && i.immediate.is_none());
                    assert_eq!(i.length as usize, bytes.len() - imm8.map_or(0, |_| 1));
                    continue;
                }
                assert!(!i.early_ud && !i.baseline_ud, "{bytes:02X?}");
                assert_eq!(i.length as usize, bytes.len());
                assert_eq!(i.ea.is_some(), memory);
                assert_eq!(i.immediate, imm8);
            }
            // F2/F3 select no SSSE3 form
            for bytes in [
                &[0xF3, 0x0F, 0x38, 0x00, 0xC1][..],
                &[0xF2, 0x0F, 0x3A, 0x0F, 0xC1],
            ] {
                assert!(d(bytes, mode32).early_ud, "{bytes:02X?}");
            }
        }
    }
    TEST_FEATURES.with(|f| f.set(0));
}

/// The bytes of a C4 VEX prefix and opcode for `row` (a VEX row): its map
/// and pp, VEX.L and VEX.W as given, VEX.vvvv (not inverted) and R/X/B 0
fn vex3_bytes(row: &Encoding, vvvv: u8, l: bool, w: bool) -> Vec<u8> {
    let (map, pp) = ((row.opcode >> 16) as u8, (row.opcode >> 8 & 3) as u8);
    vec![
        0xC4,
        0xE0 | map,
        (w as u8) << 7 | (!vvvv & 15) << 3 | (l as u8) << 2 | pp,
        row.opcode as u8,
    ]
}

#[test]
fn vex_or_les_lds_prefixes_and_fields() {
    use crate::cpu::features::{ALL, TEST_FEATURES};
    use crate::decode_rules::Vex;
    TEST_FEATURES.with(|f| f.set(ALL));
    for mode32 in [false, true] {
        // a memory ModRM byte: LES/LDS
        let les = d(
            &[
                0xC4,
                if mode32 { 0x05 } else { 0x06 },
                0x34,
                0x12,
                0x56,
                0x78,
            ],
            mode32,
        );
        assert_eq!((les.encoding.opcode, les.vex), (0xC4, None));
        assert_eq!(les.length, if mode32 { 6 } else { 4 });
        assert_eq!(d(&[0xC5, 0x00], mode32).encoding.opcode, 0xC5);
        // a register one: VEX (VZEROUPPER; VZEROALL, without semantics yet)
        for (bytes, name) in [
            (&[0xC5, 0xF8, 0x77][..], "VEX_Vzeroupper"),
            (&[0xC5, 0xFC, 0x77], "VEX_Vzeroall"),
            (&[0xC4, 0xE1, 0x7C, 0x77], "VEX_Vzeroall"),
            // W and the ignored B are free in 32-bit mode
            (&[0xC4, 0xC1, 0xFC, 0x77], "VEX_Vzeroall"),
            (&[0x2E, 0x67, 0xC5, 0xF8, 0x77], "VEX_Vzeroupper"),
        ] {
            let i = d(bytes, mode32);
            assert_eq!(form(i.encoding), name, "{bytes:02X?}");
            assert!(i.vex.is_some(), "{bytes:02X?}");
            assert_eq!(
                (i.early_ud, i.baseline_ud),
                (i.encoding.unimplemented, i.encoding.unimplemented),
                "{bytes:02X?}"
            );
            assert_eq!(i.length as usize, bytes.len(), "{bytes:02X?}");
        }
        // 66, F2, F3 and LOCK: #UD at the first VEX byte
        for prefix in [0x66, 0xF2, 0xF3, 0xF0] {
            let i = d(&[prefix, 0xC5, 0xF8, 0x77], mode32);
            assert!(i.early_ud && i.baseline_ud && i.vex.is_none() && i.length == 3);
            let i = d(&[prefix, 0xC4, 0xE1, 0x7C, 0x77], mode32);
            assert!(i.early_ud && i.length == 3 && i.encoding.opcode == 0xC4);
        }
        // reserved maps and opcodes without rows: unknown, after the opcode byte
        for (bytes, key) in [
            (&[0xC4, 0xE0, 0x78, 0x77][..], 0xC4000077),
            (&[0xC4, 0xE4, 0x78, 0x77], 0xC4040077),
            (&[0xC4, 0xFF, 0x78, 0x77], 0xC41F0077),
            (&[0xC5, 0xF8, 0x00], 0xC4010000),
            (&[0xC4, 0xE2, 0x78, 0x00], 0xC4020000),
        ] {
            assert_eq!(
                decode(bytes, GuestEip(0), LinearAddress(0), mode32).unwrap_err(),
                DecodeStop::UnknownEncoding { opcode: key }
            );
        }
        // every byte up to the ModRM belongs to the instruction
        let bytes = [0xC4, 0xE2, 0x79, 0x18, 0xC1];
        for n in 1..bytes.len() {
            assert!(matches!(
                decode(&bytes[..n], GuestEip(0), LinearAddress(0), mode32),
                Err(DecodeStop::Incomplete { .. })
            ));
        }
        let mut long = vec![0x2E; 12];
        long.extend([0xC4, 0xE1, 0x7C, 0x77]);
        assert_eq!(
            decode(&long, GuestEip(0), LinearAddress(0), mode32).unwrap_err(),
            DecodeStop::TooLong
        );
    }
    // the fields, inverted where the encoding inverts them; R, X and B are
    // ignored outside 64-bit mode, where VEX.vvvv names 8 registers
    let v = Vex::three(0x42, 0x85 ^ 0x78 ^ 0x48, true);
    assert_eq!(
        v,
        Vex {
            map: 2,
            pp: 1,
            l: true,
            w: true,
            vvvv: 9,
            r: true,
            x: false,
            b: true
        }
    );
    // (outside 64-bit mode the three-byte prefix's top VEX.vvvv bit is ignored)
    assert_eq!(Vex::three(0x42, 0x85 ^ 0x78 ^ 0x48, false).vvvv, 1);
    assert_eq!(Vex::three(0x62, 0x85, false).r, false);
    assert_eq!(
        Vex::two(0x7D, true),
        Vex {
            map: 1,
            pp: 1,
            l: true,
            w: false,
            vvvv: 0,
            r: true,
            x: false,
            b: false
        }
    );
    assert_eq!(Vex::two(0xC5, false).vvvv, 7);
    assert_eq!(Vex::three(0xE3, 0x79, false).key(0x4A), 0xC403014A);
    TEST_FEATURES.with(|f| f.set(0));
}

#[test]
fn vex_rows_decode_from_their_own_encodings() {
    use crate::cpu::features::{ALL, TEST_FEATURES};
    use crate::decode_rules::vex;
    let mut count = 0;
    for row in encodings()
        .iter()
        .filter(|e| e.vex != 0 && e.vex & vex::LONG == 0)
    {
        let (l, w) = (row.vex & vex::L1 != 0, row.vex & vex::W1 != 0);
        let vvvv = if row.vex & vex::VVVV != 0 { 3 } else { 0 };
        let group = if row.group >= 0 { row.group as u8 } else { 2 };
        let vsib = row.vex & vex::VSIB != 0;
        let mut forms = Vec::new();
        if row.fetch_modrm && !row.reg_ud {
            forms.push(vec![0xC0 | group << 3 | 1]);
        }
        if row.fetch_modrm && !row.mem_ud {
            // [eax+disp8] or [bx+si+disp8], [eax+ecx*1+disp8] for VSIB
            forms.push(if vsib {
                vec![0x44 | group << 3, 0x08, 0x10]
            }
            else {
                vec![0x40 | group << 3, 0x10]
            });
        }
        if !row.fetch_modrm {
            forms.push(vec![]);
        }
        for operand in forms {
            for mode32 in [false, true] {
                if vsib && !mode32 {
                    continue; // (16-bit addressing: below)
                }
                let mut bytes = vex3_bytes(row, vvvv, l, w);
                bytes.extend(&operand);
                // (the VEX prefix, opcode and ModRM byte)
                let head = 4 + operand.len().min(1);
                if row.immediate == ImmediateKind::Byte {
                    bytes.push(0x5A);
                }
                // as if implemented, with the features: this row, whole
                TEST_FEATURES.with(|f| f.set(ALL));
                TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(true));
                let i = d(&bytes, mode32);
                assert_eq!(form(i.encoding), form(row), "{bytes:02X?}");
                assert!(!i.early_ud && !i.baseline_ud, "{} {bytes:02X?}", form(row));
                assert_eq!(i.length as usize, bytes.len(), "{} {bytes:02X?}", form(row));
                assert_eq!(i.ea.is_some(), operand.first().is_some_and(|&m| m < 0xC0));
                assert_eq!(
                    i.immediate,
                    (row.immediate == ImmediateKind::Byte).then_some(0x5A)
                );
                if vsib {
                    assert_eq!(i.ea.unwrap().index, Some(1));
                }
                // the two-byte prefix where it can say the same
                if row.opcode >> 16 & 0xFF == 1 && !w {
                    let mut short = vec![
                        0xC5,
                        0x80 | (!vvvv & 15) << 3 | (l as u8) << 2 | (row.opcode >> 8 & 3) as u8,
                    ];
                    short.extend(&bytes[3..]);
                    assert_eq!(d(&short, mode32).encoding.id, row.id, "{short:02X?}");
                }
                // VEX.vvvv must be 1111b unless an operand; the three-byte
                // prefix's top bit is ignored outside 64-bit mode (SDM 2.3.5.6)
                for (bit, accepted) in [(0x40, true), (0x08, row.vex & vex::VVVV != 0)] {
                    let mut b = bytes.clone();
                    b[2] ^= bit;
                    let other = d(&b, mode32);
                    if accepted {
                        assert!(
                            other.encoding.id == row.id && !other.early_ud,
                            "{} {b:02X?}",
                            form(row)
                        );
                    }
                    else {
                        assert!(
                            other.early_ud && other.length as usize == head,
                            "{} {b:02X?}",
                            form(row)
                        );
                    }
                }
                // the other VEX.L and VEX.W select another row or none
                for (bit, rule, ignored) in [
                    (0x04, vex::L0 | vex::L1, false),
                    (0x80, vex::W0 | vex::W1, row.vex & vex::WIG32 != 0),
                ] {
                    let mut b = bytes.clone();
                    b[2] ^= bit;
                    match decode(&b, GuestEip(0), LinearAddress(0), mode32) {
                        Ok(other) if row.vex & rule != 0 && !ignored => {
                            assert!(
                                other.encoding.id != row.id || other.early_ud,
                                "{} {b:02X?}",
                                form(row)
                            )
                        },
                        Ok(other) => {
                            assert_eq!(other.encoding.id, row.id, "{} {b:02X?}", form(row))
                        },
                        Err(e) => panic!("{} {b:02X?} {e:?}", form(row)),
                    }
                }
                // without the features or the semantics: #UD after the ModRM
                // byte (a row with its semantics decodes in full)
                for (features, all) in [(0, true), (ALL, false)] {
                    TEST_FEATURES.with(|f| f.set(features));
                    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(all));
                    let i = d(&bytes, mode32);
                    assert_eq!(i.encoding.id, row.id);
                    if features == ALL && !row.unimplemented {
                        assert!(!i.early_ud && i.length as usize == bytes.len());
                        continue;
                    }
                    assert!(i.early_ud && i.baseline_ud && i.ea.is_none() && i.immediate.is_none());
                    assert_eq!(i.length as usize, head);
                }
                count += 1;
            }
        }
    }
    TEST_FEATURES.with(|f| f.set(0));
    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(false));
    assert!(count > 1000, "{count}");
}

#[test]
fn vex_vsib_and_gather_registers() {
    use crate::cpu::features::{ALL, TEST_FEATURES};
    TEST_FEATURES.with(|f| f.set(ALL));
    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(true));
    // VPGATHERDD xmm2, [eax+xmm1*4], xmm3
    let gather = [0xC4, 0xE2, 0x61, 0x90, 0x14, 0x88];
    let i = d(&gather, true);
    assert_eq!(form(i.encoding), "VEX_Vpgatherdd_xmm_vm32x_xmm");
    assert!(!i.baseline_ud && i.ea.unwrap().index == Some(1) && i.ea.unwrap().scale == 2);
    // xmm4 is an index register like the others
    let i = d(&[0xC4, 0xE2, 0x61, 0x90, 0x14, 0xA0], true);
    assert!(!i.baseline_ud && i.ea.unwrap().index == Some(4));
    // no SIB byte, a register form or 16-bit addressing: #UD after ModRM
    for (bytes, mode32) in [
        (&[0xC4, 0xE2, 0x61, 0x90, 0x10][..], true),
        (&[0xC4, 0xE2, 0x61, 0x90, 0xD1], true),
        (&[0x67, 0xC4, 0xE2, 0x61, 0x90, 0x14], true),
        (&[0xC4, 0xE2, 0x61, 0x90, 0x14], false),
    ] {
        let i = d(bytes, mode32);
        assert!(
            i.early_ud && i.length as usize == bytes.len(),
            "{bytes:02X?}"
        );
    }
    // destination, index and mask registers must differ: #UD after the SIB
    for (vvvv, sib) in [(1, 0x88), (2, 0x88), (3, 0x98)] {
        let mut bytes = gather;
        bytes[2] = (!vvvv & 15) << 3 | 1;
        bytes[5] = sib;
        let i = d(&bytes, true);
        assert!(
            i.baseline_ud && !i.early_ud && i.length == 6,
            "{bytes:02X?}"
        );
    }
    TEST_FEATURES.with(|f| f.set(0));
    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(false));
}

#[test]
fn tzcnt_and_lzcnt_are_bsf_and_bsr_without_their_features() {
    use crate::cpu::features::{BMI1, LZCNT, TEST_FEATURES};
    for features in [0, BMI1, LZCNT, BMI1 | LZCNT] {
        TEST_FEATURES.with(|f| f.set(features));
        for (byte, feature) in [(0xBC, BMI1), (0xBD, LZCNT)] {
            for prefix in [&[0xF3][..], &[0x66, 0xF3], &[0xF3, 0x66], &[0xF2, 0xF3]] {
                let mut bytes = prefix.to_vec();
                bytes.extend([0x0F, byte, 0x04, 0x24]);
                let i = d(&bytes, true);
                if features & feature != 0 {
                    // (TZCNT and LZCNT, P10)
                    assert_eq!(i.encoding.opcode, 0xF30F00 | byte as u32);
                    assert!(!i.early_ud && i.length as usize == bytes.len());
                }
                else {
                    assert_eq!(i.encoding.opcode, 0x0F00 | byte as u32);
                    assert!(!i.baseline_ud && i.length as usize == bytes.len());
                }
            }
        }
    }
    TEST_FEATURES.with(|f| f.set(0));
}
                                                                                                                                                                 source/v64/tests/decode/legacy_modrm.rs                                                             0000644 0000000 0000000 00000012701 00000000000 015262  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Pinned staged EA interpreter from e87c1f43270a0d3185ed48e40dbf9069a60360a6.
use crate::cpu::cpu::*;
use crate::paging::OrPageFault;

pub unsafe fn resolve_modrm16(modrm_byte: i32) -> OrPageFault<i32> {
    match modrm_byte & !0o070 {
        0o000 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) & 0xFFFF),
        0o100 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) + read_imm8s()? & 0xFFFF),
        0o200 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(SI) + read_imm16()? & 0xFFFF),
        0o001 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) & 0xFFFF),
        0o101 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) + read_imm8s()? & 0xFFFF),
        0o201 => get_seg_prefix_ds(read_reg16(BX) + read_reg16(DI) + read_imm16()? & 0xFFFF),
        0o002 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) & 0xFFFF),
        0o102 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) + read_imm8s()? & 0xFFFF),
        0o202 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(SI) + read_imm16()? & 0xFFFF),
        0o003 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) & 0xFFFF),
        0o103 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) + read_imm8s()? & 0xFFFF),
        0o203 => get_seg_prefix_ss(read_reg16(BP) + read_reg16(DI) + read_imm16()? & 0xFFFF),
        0o004 => get_seg_prefix_ds(read_reg16(SI) & 0xFFFF),
        0o104 => get_seg_prefix_ds(read_reg16(SI) + read_imm8s()? & 0xFFFF),
        0o204 => get_seg_prefix_ds(read_reg16(SI) + read_imm16()? & 0xFFFF),
        0o005 => get_seg_prefix_ds(read_reg16(DI) & 0xFFFF),
        0o105 => get_seg_prefix_ds(read_reg16(DI) + read_imm8s()? & 0xFFFF),
        0o205 => get_seg_prefix_ds(read_reg16(DI) + read_imm16()? & 0xFFFF),
        0o006 => get_seg_prefix_ds(read_imm16()?),
        0o106 => get_seg_prefix_ss(read_reg16(BP) + read_imm8s()? & 0xFFFF),
        0o206 => get_seg_prefix_ss(read_reg16(BP) + read_imm16()? & 0xFFFF),
        0o007 => get_seg_prefix_ds(read_reg16(BX) & 0xFFFF),
        0o107 => get_seg_prefix_ds(read_reg16(BX) + read_imm8s()? & 0xFFFF),
        0o207 => get_seg_prefix_ds(read_reg16(BX) + read_imm16()? & 0xFFFF),
        _ => {
            dbg_assert!(false);
            std::hint::unreachable_unchecked()
        },
    }
}

pub unsafe fn resolve_modrm32_(modrm_byte: i32) -> OrPageFault<i32> {
    let r = (modrm_byte & 7) as u8;
    dbg_assert!(modrm_byte < 192);
    Ok(if r as i32 == 4 {
        if modrm_byte < 64 {
            resolve_sib(false)?
        }
        else {
            resolve_sib(true)? + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? }
        }
    }
    else if r as i32 == 5 {
        if modrm_byte < 64 {
            get_seg_prefix_ds(read_imm32s()?)?
        }
        else {
            get_seg_prefix_ss(
                read_reg32(EBP) + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? },
            )?
        }
    }
    else if modrm_byte < 64 {
        get_seg_prefix_ds(read_reg32(r as i32))?
    }
    else {
        get_seg_prefix_ds(
            read_reg32(r as i32) + if modrm_byte < 128 { read_imm8s()? } else { read_imm32s()? },
        )?
    })
}
unsafe fn resolve_sib(with_imm: bool) -> OrPageFault<i32> {
    let sib_byte = read_imm8()?;
    let r = sib_byte & 7;
    let m = sib_byte >> 3 & 7;
    let base;
    let seg;
    if r == 4 {
        base = read_reg32(ESP);
        seg = SS
    }
    else if r == 5 {
        if with_imm {
            base = read_reg32(EBP);
            seg = SS
        }
        else {
            base = read_imm32s()?;
            seg = DS
        }
    }
    else {
        base = read_reg32(r);
        seg = DS
    }
    let offset;
    if m == 4 {
        offset = 0
    }
    else {
        let s = sib_byte >> 6 & 3;
        offset = read_reg32(m) << s
    }
    Ok(get_seg_prefix(seg)? + base + offset)
}

pub unsafe fn resolve_modrm32(modrm_byte: i32) -> OrPageFault<i32> {
    match modrm_byte & !0o070 {
        0o000 => get_seg_prefix_ds(read_reg32(EAX)),
        0o100 => get_seg_prefix_ds(read_reg32(EAX) + read_imm8s()?),
        0o200 => get_seg_prefix_ds(read_reg32(EAX) + read_imm32s()?),
        0o001 => get_seg_prefix_ds(read_reg32(ECX)),
        0o101 => get_seg_prefix_ds(read_reg32(ECX) + read_imm8s()?),
        0o201 => get_seg_prefix_ds(read_reg32(ECX) + read_imm32s()?),
        0o002 => get_seg_prefix_ds(read_reg32(EDX)),
        0o102 => get_seg_prefix_ds(read_reg32(EDX) + read_imm8s()?),
        0o202 => get_seg_prefix_ds(read_reg32(EDX) + read_imm32s()?),
        0o003 => get_seg_prefix_ds(read_reg32(EBX)),
        0o103 => get_seg_prefix_ds(read_reg32(EBX) + read_imm8s()?),
        0o203 => get_seg_prefix_ds(read_reg32(EBX) + read_imm32s()?),
        0o004 => resolve_sib(false),
        0o104 => Ok(resolve_sib(true)? + read_imm8s()?),
        0o204 => Ok(resolve_sib(true)? + read_imm32s()?),
        0o005 => get_seg_prefix_ds(read_imm32s()?),
        0o105 => get_seg_prefix_ss(read_reg32(EBP) + read_imm8s()?),
        0o205 => get_seg_prefix_ss(read_reg32(EBP) + read_imm32s()?),
        0o006 => get_seg_prefix_ds(read_reg32(ESI)),
        0o106 => get_seg_prefix_ds(read_reg32(ESI) + read_imm8s()?),
        0o206 => get_seg_prefix_ds(read_reg32(ESI) + read_imm32s()?),
        0o007 => get_seg_prefix_ds(read_reg32(EDI)),
        0o107 => get_seg_prefix_ds(read_reg32(EDI) + read_imm8s()?),
        0o207 => get_seg_prefix_ds(read_reg32(EDI) + read_imm32s()?),
        _ => {
            dbg_assert!(false);
            std::hint::unreachable_unchecked()
        },
    }
}
                                                               source/v64/tests/decode/oracle.mjs                                                                  0000644 0000000 0000000 00000001356 00000000000 014236  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import {spawnSync} from "node:child_process";
for(const size of [16, 32]) {
    const result = spawnSync("ndisasm", ["-b", String(size), `build/ir-decode/oracle-${size}.bin`], {encoding: "utf8", maxBuffer: 8 * 1024 * 1024});
    if(result.error) throw result.error;
    assert.equal(result.status, 0, result.stderr);
    const offsets = result.stdout.split("\n").filter(line => /^[0-9A-F]+\s+[0-9A-F]/.test(line)).map(line => parseInt(line.split(/\s/)[0], 16));
    assert.deepEqual(offsets, JSON.parse(fs.readFileSync(`build/ir-decode/oracle-${size}.json`)));
}
console.log("PASS: 16,384 instruction boundaries agree with independent NDISASM (16/32-bit, prefixes and addressing)");
                                                                                                                                                                                                                                                                                  source/v64/tests/decode/simd_corpus.rs                                                              0000644 0000000 0000000 00000024236 00000000000 015155  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! The SIMD decode corpus (docs/simd-xsave-plan.md P1d): VEX and the legacy
//! SIMD encodings in 16-, 32- and 64-bit mode. The x64 decoder and, outside
//! 64-bit mode, the IR decoder decode each with every feature and as if every
//! row had its semantics (TEST_FEATURES, TEST_DECODE_UNIMPLEMENTED). This test
//! checks that the two agree, and that without the features each encoding is
//! #UD (TZCNT and LZCNT: BSF and BSR); tests/x64/oracle compares the x64
//! decoder's results (build/x64-decode/simd.bin) with iced-x86.
use crate::cpu::features::{ALL, TEST_FEATURES};
use crate::decode::{self, form, DecodeStop, GuestEip, LinearAddress, TEST_DECODE_UNIMPLEMENTED};
use crate::x64::decode::{decode_with, DecodeError};
use crate::x64::state::{ExecutionMode, GuestIp};

/// The bytes after each corpus entry, also for tests/x64/oracle: SIB,
/// displacement and immediate bytes come from here
pub const FILLER: [u8; 8] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x08];

/// A register and a memory ModRM byte for each ModRM.reg: [rcx], and
/// [rax+rcx*4] (VSIB index 1) or [si] in 16-bit addressing
fn modrms() -> Vec<Vec<u8>> {
    (0..8u8)
        .flat_map(|g| [vec![0xC1 | g << 3], vec![0x04 | g << 3, 0x88]])
        .collect()
}

/// (bits, bytes) of every corpus entry, without FILLER
pub fn corpus() -> Vec<(u8, Vec<u8>)> {
    let mut rows = Vec::new();
    for bits in [16u8, 32, 64] {
        let long = bits == 64;
        let mut push = |prefix: &[u8], body: &[u8], modrm: &[u8]| {
            let mut bytes = prefix.to_vec();
            bytes.extend(body);
            bytes.extend(modrm);
            rows.push((bits, bytes));
        };
        // C4: every opcode of maps 1-3 with each pp; VEX.L, W, vvvv (its low
        // and top bits) and R/X/B (B alone outside 64-bit mode) varied
        for map in 1..=3u8 {
            for pp in 0..4u8 {
                for opcode in 0..=255u8 {
                    for (l, w, vvvv, rxb) in [
                        (0, 0, 0, 7),
                        (1, 0, 0, 7),
                        (0, 1, 0, 7),
                        (1, 1, 0, 7),
                        (0, 0, 1, 7),
                        (1, 1, 1, 7),
                        (0, 0, 8, 7),
                        (0, 0, 0, if long { 0 } else { 6 }),
                    ] {
                        let byte2 = w << 7 | (!vvvv & 15) << 3 | l << 2 | pp;
                        for modrm in modrms() {
                            push(&[], &[0xC4, rxb << 5 | map, byte2, opcode], &modrm);
                        }
                    }
                }
            }
        }
        // C5
        for pp in 0..4u8 {
            for opcode in 0..=255u8 {
                for (l, vvvv) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
                    for modrm in modrms() {
                        push(
                            &[],
                            &[0xC5, 0x80 | (!vvvv & 15) << 3 | l << 2 | pp, opcode],
                            &modrm,
                        );
                    }
                }
            }
        }
        // reserved maps
        for map in [0u8, 4, 5, 31] {
            for opcode in [0x00, 0x10, 0x77, 0xF2, 0xF7] {
                push(&[], &[0xC4, 0xE0 | map, 0x78, opcode], &[0xC1]);
            }
        }
        // prefixes before VEX: vzeroupper, vpaddd ymm, andn, vpgatherdd
        let rex: &[u8] = if long { &[0x40, 0x48, 0x41] } else { &[] };
        for &prefix in [0x66, 0xF2, 0xF3, 0xF0, 0x2E, 0x67].iter().chain(rex) {
            for body in [
                &[0xC5, 0xF8, 0x77][..],
                &[0xC4, 0xE1, 0x7D, 0xFE, 0xC1],
                &[0xC4, 0xE2, 0x78, 0xF2, 0xC1],
                &[0xC4, 0xE2, 0x61, 0x90, 0x14, 0x88],
            ] {
                push(&[prefix], body, &[]);
                push(&[prefix, 0x2E], body, &[]);
            }
        }
        // the legacy maps 0F 38 and 0F 3A, and 0F BC, BD (TZCNT, LZCNT), with
        // mandatory-prefix orders, REX.W in 64-bit mode
        let mut prefix_sets: Vec<Vec<u8>> = [
            &[][..],
            &[0x66],
            &[0xF2],
            &[0xF3],
            &[0x66, 0xF2],
            &[0xF2, 0x66],
            &[0x66, 0xF3],
            &[0xF3, 0x66],
            &[0xF2, 0xF3],
            &[0xF3, 0xF2],
        ]
        .iter()
        .map(|p| p.to_vec())
        .collect();
        if long {
            for i in 0..prefix_sets.len() {
                let mut w = prefix_sets[i].clone();
                w.push(0x48);
                prefix_sets.push(w);
            }
        }
        for prefixes in &prefix_sets {
            for escape in [0x38u8, 0x3A] {
                for opcode in 0..=255u8 {
                    for modrm in modrms() {
                        push(prefixes, &[0x0F, escape, opcode], &modrm);
                    }
                }
            }
            for opcode in [0xBCu8, 0xBD] {
                for modrm in modrms() {
                    push(prefixes, &[0x0F, opcode], &modrm);
                }
            }
        }
    }
    rows
}

fn mode(bits: u8) -> ExecutionMode {
    match bits {
        16 => ExecutionMode::Protected16,
        32 => ExecutionMode::Compatibility32,
        _ => ExecutionMode::Long64,
    }
}

/// The x64 decoder's result and the bytes it fetched
fn x64(bits: u8, bytes: &[u8]) -> (Result<crate::x64::decode::Decoded, DecodeError>, usize) {
    let mut fetched = 0;
    let result = decode_with(GuestIp(0x1000), mode(bits), |offset| {
        fetched = fetched.max(offset as usize + 1);
        bytes.get(offset as usize).copied().ok_or(())
    });
    (result, fetched)
}

#[test]
fn simd_decode_corpus() {
    let rows = corpus();
    let mut out = Vec::new();
    let mut names: Vec<&str> = Vec::new();
    let (mut valid, mut compared) = (0, 0);
    TEST_FEATURES.with(|f| f.set(ALL));
    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(true));
    for (bits, bytes) in &rows {
        let mut full = bytes.clone();
        full.extend(FILLER);
        let (x, fetched) = x64(*bits, &full);
        // the IR decoder agrees outside 64-bit mode: the same row and length,
        // and #UD where the x64 decoder refuses, after the bytes it fetched
        if *bits != 64 {
            let i = decode::decode(&full, GuestEip(0x1000), LinearAddress(0x1000), *bits == 32);
            match (&x, &i) {
                (Ok(x), Ok(i)) => assert!(
                    !i.baseline_ud && i.length == x.length && i.encoding.id == x.encoding.id,
                    "{bits} {bytes:02X?}"
                ),
                (Err(DecodeError::InvalidOpcode), Ok(i)) => {
                    assert!(i.baseline_ud, "{bits} {bytes:02X?}");
                    assert!(
                        !i.early_ud || i.length as usize == fetched,
                        "{bits} {bytes:02X?}"
                    );
                },
                (
                    Err(DecodeError::UnknownOpcode(key)),
                    Err(DecodeStop::UnknownEncoding { opcode }),
                ) => {
                    assert_eq!(key, opcode, "{bits} {bytes:02X?}")
                },
                _ => panic!("{bits} {bytes:02X?}: x64 {x:?}, IR {i:?}"),
            }
            compared += 1;
        }
        // build/x64-decode/simd.bin: bits, length and bytes; valid, the
        // decoded length and the form (an index into simd-forms.json, or
        // 0xFFFF for legacy rows)
        out.extend([*bits, bytes.len() as u8]);
        out.extend(bytes);
        let form_index = match &x {
            Ok(d) if d.vex.is_some() => {
                let name = form(d.encoding);
                names.iter().position(|n| *n == name).unwrap_or_else(|| {
                    names.push(name);
                    names.len() - 1
                }) as u16
            },
            _ => 0xFFFF,
        };
        out.extend([x.is_ok() as u8, x.as_ref().map_or(0, |d| d.length)]);
        out.extend(form_index.to_le_bytes());
        valid += x.is_ok() as usize;
    }
    // Without the features every VEX and three-byte map encoding is #UD;
    // with them, so is every one whose row has no semantics yet (the release
    // contract until each phase); F3 0F BC/BD are BSF/BSR without BMI1/LZCNT
    for (features, all) in [(0, true), (ALL, false)] {
        TEST_FEATURES.with(|f| f.set(features));
        TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(all));
        for (bits, bytes) in &rows {
            let mut full = bytes.clone();
            full.extend(FILLER);
            let (x, _) = x64(*bits, &full);
            let at = bytes.iter().position(|&b| !matches!(b, 0x26 | 0x2E | 0x36 | 0x3E | 0x64..=0x67 | 0xF0 | 0xF2 | 0xF3 | 0x40..=0x4F)).unwrap();
            let opcode = &bytes[at..];
            let simd = matches!(opcode[0], 0xC4 | 0xC5) && (*bits == 64 || opcode[1] >= 0xC0)
                || opcode.starts_with(&[0x0F, 0x38])
                || opcode.starts_with(&[0x0F, 0x3A]);
            if simd {
                assert!(
                    matches!(
                        x,
                        Err(DecodeError::InvalidOpcode | DecodeError::UnknownOpcode(_))
                    ) || features != 0 && x.as_ref().is_ok_and(|d| d.encoding.implemented()),
                    "{features:x} {bits} {bytes:02X?}: {x:?}"
                );
            }
            else if features == 0 && matches!(opcode, [0x0F, 0xBC | 0xBD, ..]) {
                assert_eq!(
                    x.unwrap().opcode,
                    0x0F00 | opcode[1] as u32,
                    "{bits} {bytes:02X?}"
                );
            }
        }
    }
    TEST_FEATURES.with(|f| f.set(0));
    TEST_DECODE_UNIMPLEMENTED.with(|t| t.set(false));
    std::fs::create_dir_all("build/x64-decode").unwrap();
    std::fs::write("build/x64-decode/simd.bin", out).unwrap();
    std::fs::write(
        "build/x64-decode/simd-forms.json",
        format!(
            "[{}]",
            names
                .iter()
                .map(|n| format!("{n:?}"))
                .collect::<Vec<_>>()
                .join(",")
        ),
    )
    .unwrap();
    println!("SIMD decode corpus: {} encodings, {valid} valid with every feature, {compared} also decoded by the IR decoder", rows.len());
    assert!(
        rows.len() > 1_000_000 && names.len() == 688,
        "{} {}",
        rows.len(),
        names.len()
    );
}
                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/decode/staged.mjs                                                                  0000644 0000000 0000000 00000007713 00000000000 014243  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import {V86} from "../../build/libv86.mjs";
const vm = new V86({graphics_adapter: "bochs_vga", wasm_path:process.argv[2]||"build/v86-ir-test.wasm",memory_size:32<<20,
    bios:{buffer:Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer},
    disable_keyboard:true,disable_mouse:true,disable_speaker:true,net_device:{type:"none"},autostart:false});
try {
    await new Promise(r=>vm.add_listener("emulator-loaded",r));
    const cpu=vm.v86.cpu,e=cpu.wm.exports,mem=cpu.mem8,w=new Uint32Array(e.memory.buffer);
    const v=new DataView(mem.buffer,mem.byteOffset), put=(a,x)=>v.setUint32(a,x,true);
    vm.run();const deadline=performance.now()+10000;
    while(v.getUint16(0x500,true)!==0xCAFE){assert(performance.now()<deadline);await new Promise(r=>setTimeout(r,1));}
    await vm.stop();
    const cr0=cpu.cr[0],PC=0x8000,SP=0x90000,GP=0x180000,PF=0x180100;
    function reset(size,prefix,bytes,ip=PC,absent=false,nulls=false){
        e.ir_test_set_cr0(cr0|0x10000);cpu.cr[2]=0xBADF000;cpu.flags[0]=2;cpu.flags_changed[0]=0;
        cpu.sreg.set([16,8,16,16,16,16]);cpu.segment_offsets.set([0x100,0,0,0x300,0x400,0x500]);
        cpu.segment_limits.fill(0xFFFFFFFF,0,6);cpu.segment_is_null.fill(+nulls,0,6);
        cpu.segment_is_null[1]=cpu.segment_is_null[2]=0;
        cpu.segment_access_bytes.set([0x93,0x9B,0x93,0x93,0x93,0x93]);
        cpu.is_32[0]=+(size===32);cpu.stack_size_32[0]=1;w[612>>2]=0;
        cpu.reg32.set([0xFFFF1234,0xABCDEF01,0x12345678,0x87654321,SP,0xFFFFFFFC,0xFFFF,5]);
        cpu.instruction_pointer[0]=ip;w[560>>2]=PC-2;cpu.in_hlt[0]=0;
        cpu.gdtr_offset[0]=0x3000;cpu.gdtr_size[0]=23;
        put(0x3008,65535);put(0x300C,0xCF9B00);put(0x3010,65535);put(0x3014,0xCF9300);
        cpu.idtr_offset[0]=0x2000;cpu.idtr_size[0]=0x7FF;
        for(const [n,handler] of [[13,GP],[14,PF]]){put(0x2000+n*8,8<<16|handler&65535);put(0x2004+n*8,handler&0xFFFF0000|0x8E00);}
        put(0x12000,0x13023);
        for(const page of [2,3,8,9,0x8F,0x90,0x180])put(0x13000+page*4,page*4096|0x23);
        if(absent)put(0x13000+9*4,0);
        mem.fill(0xCC,SP-64,SP);mem.set(bytes,ip);
        e.full_clear_tlb();e.update_state_flags();
        new Uint8Array(e.memory.buffer)[648]=prefix;
    }
    function state(result){return {result,ip:cpu.instruction_pointer[0],previous:w[560>>2],cr2:cpu.cr[2],
        regs:Array.from(cpu.reg32),flags:e.get_eflags(),segments:Array.from(cpu.segment_offsets),
        frame:Buffer.from(mem.slice(SP-64,SP))};}
    let comparisons=0;
    for(const size of [16,32]) for(let m=0;m<192;m++) {
        const sibs=size===32&&(m&7)===4?256:1;
        for(let sib=0;sib<sibs;sib++) for(const prefix of [0,1,2,3,4,5,6,7]) {
            const bytes=size===32&&(m&7)===4?[sib,0x80,0xFE,0xFF,0x12]:[0x80,0xFE,0xFF,0x12];
            reset(size,prefix,bytes);const old=state(e.ir_test_resolve_modrm(m,size,1));
            reset(size,prefix,bytes);assert.deepEqual(state(e.ir_test_resolve_modrm(m,size,0)),old,`EA ${size}/${m}/${sib}/${prefix}`);
            comparisons++;
        }
    }
    // With SIB, a null segment precedes a trailing displacement fetch; without
    // SIB, that fetch precedes the null-segment check. Keep the baseline priority.
    for(const size of [16,32]) for(const m of [0x05,0x06,0x40,0x44,0x45,0x84,0x85]) {
        for(const prefix of [0,1,4,5,7]) for(const nulls of [false,true]) for(const cut of [0,1,2,3]){
            const bytes=[0,0x80,0xFF,0xFF,0xFF];const ip=0x9000-cut;
            reset(size,prefix,bytes,ip,true,nulls);const old=state(e.ir_test_resolve_modrm(m,size,1));
            reset(size,prefix,bytes,ip,true,nulls);assert.deepEqual(state(e.ir_test_resolve_modrm(m,size,0)),old,`fetch ordering ${size}/${m}/${prefix}/${nulls}/${cut}`);
            comparisons++;
        }
    }
    console.log(`PASS: ${comparisons} staged interpreter EA comparisons against pinned resolver, including cross-page fetch/segment fault priority`);
} finally {await vm.destroy();}
                                                     source/v64/tests/decode/vex_modes.mjs                                                               0000644 0000000 0000000 00000017453 00000000000 014767  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // C4 and C5 in the 32-bit interpreter by mode (docs/simd-xsave-plan.md P1c):
// a VEX prefix in protected mode when the next byte would be a register
// ModRM byte, otherwise LES/LDS; real and virtual-8086 mode have no VEX, and
// there the register form of LES/LDS is #UD. Prefixes before VEX are #UD at
// the first VEX byte, and fetch faults on the bytes the decoder needs come
// before #UD (decode::tests and x64::decode::tests check the other decoders).
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";

const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: process.argv[2] || "build/v86-ir-test.wasm", memory_size: 32 << 20,
    bios: { buffer: Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer },
    disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
try
{
    await new Promise(r => vm.add_listener("emulator-loaded", r));
    const cpu = vm.v86.cpu, e = cpu.wm.exports, mem = cpu.mem8, words = new Uint32Array(e.memory.buffer);
    const view = new DataView(mem.buffer, mem.byteOffset), set32 = (a, x) => view.setUint32(a, x, true), get32 = a => view.getUint32(a, true);
    vm.run();
    const deadline = performance.now() + 10000;
    while(view.getUint16(0x500, true) !== 0xCAFE) { assert(performance.now() < deadline); await new Promise(r => setTimeout(r, 1)); }
    await vm.stop();
    const cr0 = cpu.cr[0], STACK = 0x90000, DATA = 0x7000, ABSENT = 0x9000;
    // a handler per vector: #UD, #GP, #PF
    const HANDLERS = { 6: 0x18000, 13: 0x18100, 14: 0x18200 };
    const descriptor = (index, base, limit, access, flags) => {
        set32(0x3000 + index * 8, limit & 65535 | base << 16);
        set32(0x3004 + index * 8, base & 0xFF000000 | base >>> 16 & 255 | access << 8 | limit & 0xF0000 | flags << 20);
    };
    /** `bytes` at `pc` in `mode`: "real", "vm86", "protected16" or "protected32" */
    function reset(mode, bytes, pc)
    {
        e.ir_test_set_cr0(mode === "real" ? cr0 & ~0x80000001 : cr0 | 0x10000);
        cpu.cr[2] = 0xBADF000; cpu.cr[3] = 0x12000;
        descriptor(0, 0, 0, 0, 0); descriptor(1, 0, 0xFFFFF, 0x9B, 12); descriptor(2, 0, 0xFFFFF, 0x93, 12);
        descriptor(3, 0, 0xFFFF, 0x9B, 0); descriptor(7, 0x4000, 0x67, 0x89, 0);
        cpu.gdtr_offset[0] = 0x3000; cpu.gdtr_size[0] = 63;
        const real = mode === "real" || mode === "vm86";
        cpu.sreg.set(real ? [0, 0, 0, 0, 0, 0] : [16, mode === "protected16" ? 0x18 : 8, 16, 16, 16, 16]);
        cpu.segment_offsets.fill(0, 0, 6); cpu.segment_is_null.fill(0, 0, 6);
        cpu.segment_limits.fill(real ? 0xFFFF : 0xFFFFFFFF, 0, 6);
        cpu.segment_access_bytes.set(real && mode === "vm86" ? [0xF3, 0xFB, 0xF3, 0xF3, 0xF3, 0xF3] : [0x93, 0x9B, 0x93, 0x93, 0x93, 0x93]);
        cpu.is_32[0] = +(mode === "protected32"); cpu.stack_size_32[0] = +!real;
        words[612 >> 2] = mode === "vm86" ? 3 : 0;
        cpu.reg32.set([0x11111111, 0x22222222, 0x33333333, 0x44444444, STACK, 0x55555555, 0x66666666, 0x77777777]);
        cpu.flags[0] = mode === "vm86" ? 0x20002 | 3 << 12 : 2; cpu.flags_changed[0] = 0;
        // the IDT, or the real-mode vector table, and the TSS's ring-0 stack
        if(real && mode === "real")
        {
            cpu.idtr_offset[0] = 0; cpu.idtr_size[0] = 0x3FF;
            for(const [vector, handler] of Object.entries(HANDLERS)) set32(vector * 4, handler >>> 4 << 16);
        }
        else
        {
            cpu.idtr_offset[0] = 0x2000; cpu.idtr_size[0] = 0x7FF;
            for(const [vector, handler] of Object.entries(HANDLERS))
            {
                set32(0x2000 + vector * 8, 8 << 16 | handler & 65535); set32(0x2004 + vector * 8, handler & 0xFFFF0000 | 0x8E00);
            }
            // (TR)
            cpu.segment_offsets[6] = 0x4000; cpu.segment_limits[6] = 0x67; cpu.sreg[6] = 0x38; cpu.tss_size_32[0] = 1;
            set32(0x4004, STACK); set32(0x4008, 16);
        }
        // the first 4 MiB mapped for user and supervisor, but ABSENT
        set32(0x12000, 0x13007);
        for(let page = 0; page < 1024; page++) set32(0x13000 + page * 4, page === ABSENT >>> 12 ? 0 : page * 4096 | 7);
        mem.fill(0xCC, STACK - 64, STACK + 16);
        // far pointers: 32-bit at DATA, 16-bit at DATA + 16
        set32(DATA, 0x12345678); set32(DATA + 4, 0x10); set32(DATA + 16, 0x105678);
        mem.fill(0x90, pc - 16, pc + 32);
        mem.set(bytes, pc);
        cpu.instruction_pointer[0] = pc; cpu.in_hlt[0] = 0;
        e.full_clear_tlb(); e.update_state_flags();
    }
    /** Step once: the vector delivered and the address it reports, or "done" and the next address */
    function step(mode, bytes, pc = 0x8000)
    {
        reset(mode, bytes, pc);
        e.ir_test_step();
        const ip = cpu.instruction_pointer[0] >>> 0;
        const vector = Object.keys(HANDLERS).find(v => HANDLERS[v] === ip);
        if(vector === undefined) return { done: ip };
        // (#GP and #PF push an error code; the real-mode frame is 16-bit)
        const frame = mode === "real" ? (cpu.reg32[4] & 0xFFFF) : cpu.reg32[4] >>> 0;
        const eip = mode === "real" ? view.getUint16(frame, true) : get32(frame + (vector === "6" ? 0 : 4));
        return { vector: +vector, eip, cr2: cpu.cr[2] >>> 0 };
    }
    const ud = pc => ({ vector: 6, eip: pc });
    let count = 0;
    const expect = (mode, bytes, expected, pc = 0x8000) => {
        const result = step(mode, bytes, pc);
        if(expected.vector !== 14) delete result.cr2;
        assert.deepEqual(result, expected, `${mode} ${bytes.map(b => b.toString(16)).join(" ")} at ${pc.toString(16)}`);
        count++;
    };

    for(const mode of ["protected32", "protected16"])
    {
        // VEX forms without their features (this machine's default: no AVX,
        // AVX2 or BMI1), a reserved map, an opcode without rows
        for(const bytes of [[0xC5, 0xF8, 0x77], [0xC4, 0xE2, 0x79, 0x18, 0xC1], [0xC4, 0xE2, 0x78, 0xF2, 0xC1],
            [0xC4, 0xC0, 0x78, 0x77], [0xC5, 0xF8, 0x00]])
        {
            expect(mode, bytes, ud(0x8000));
        }
        // 66, F2, F3 and LOCK before VEX
        for(const prefix of [0x66, 0xF2, 0xF3, 0xF0]) expect(mode, [prefix, 0xC5, 0xF8, 0x77], ud(0x8000));
        // a memory ModRM byte: LES/LDS
        const les = mode === "protected32" ? [0xC4, 0x05, 0, 0x70, 0, 0] : [0xC4, 0x06, 0x10, 0x70];
        expect(mode, les, { done: 0x8000 + les.length });
        assert.equal(cpu.sreg[0], 0x10);
        assert.equal(cpu.reg32[0] >>> 0, mode === "protected32" ? 0x12345678 : 0x11115678);
        // fetch faults on the bytes the decoder reads come first: VEX's
        // second byte and opcode, and its ModRM byte, but not where a
        // prefix makes it #UD at the first VEX byte
        expect(mode, [0xC4, 0xE2, 0x79, 0x18, 0xC1], { vector: 14, eip: ABSENT - 2, cr2: ABSENT }, ABSENT - 2);
        expect(mode, [0xC4, 0xE2, 0x79, 0x18, 0xC1], { vector: 14, eip: ABSENT - 4, cr2: ABSENT }, ABSENT - 4);
        expect(mode, [0x66, 0xC4, 0xE2, 0x79, 0x18], ud(ABSENT - 3), ABSENT - 3);
        expect(mode, [0xC5, 0xF8, 0x77], ud(ABSENT - 3), ABSENT - 3);
    }
    for(const mode of ["real", "vm86"])
    {
        // the register forms of LES and LDS, after the ModRM byte
        expect(mode, [0xC4, 0xC0, 0x78, 0x77], ud(0x8000));
        expect(mode, [0xC5, 0xF8, 0x77], ud(0x8000));
        expect(mode, [0xC4, 0xE2, 0x79, 0x18, 0xC1], ud(0x8000));
        expect(mode, [0xC4, 0x06, 0x10, 0x70], { done: 0x8004 });
        assert.equal(cpu.sreg[0], 0x10);
        assert.equal(cpu.segment_offsets[0], 0x100);
    }
    // ... and only two bytes are read in virtual-8086 mode, which pages
    expect("vm86", [0xC5, 0xF8, 0x77], ud(ABSENT - 2), ABSENT - 2);
    console.log(`PASS: ${count} C4/C5 decodes by mode: VEX or LES/LDS, prefixes before VEX, fetch faults before #UD`);
}
finally
{
    await vm.destroy();
}
                                                                                                                                                                                                                     source/v64/tests/devices/acpi_device.js                                                             0000755 0000000 0000000 00000061301 00000000000 015245  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Device-level tests of the ACPI fixed hardware (src/acpi.js) and of shared
// level-triggered IRQ lines (CPU.set_shared_irq_level). Ports are accessed
// directly with an injected clock; no guest code runs.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// PM base as SeaBIOS programs it with v86's tables; the device decodes PMBA
const PM_BASE = 0x600;
const PM1_STS = PM_BASE + 0;
const PM1_EN = PM_BASE + 2;
const PM1_CNT = PM_BASE + 4;
const PM_TMR = PM_BASE + 8;
const GLBCTL = PM_BASE + 0x28;
const GPE0_STS = 0xAFE0;
const GPE0_EN = 0xAFE2;
const SMI_CMD = 0xB2;
const FW_CFG_SELECT = 0x510;
const FW_CFG_DATA = 0x511;
const FW_CFG_FILE_DIR = 0x19;
const PCI_CONFIG_ADDRESS = 0xCF8;
const PCI_CONFIG_DATA = 0xCFC;
const RESET_CONTROL = 0xCF9;
const ACPI_PCI_DEVICE = 7;
const PCI_PMBA = 0x40;
const PCI_PMREGMISC = 0x80;

const TMR = 1 << 0;
const PWRBTN = 1 << 8;
const WAK = 1 << 15;
const PM1_EN_DEFINED = 0x0721;
const SCI_EN = 1 << 0;
const BM_RLS = 1 << 1;
const SLP_TYP = 7 << 10;
const SLP_EN = 1 << 13;

const SCI_IRQ = 9;
const OTHER_SOURCE = 0x40; // stands in for a PCI function sharing IRQ 9

const TICKS_PER_MS = 3579545 / 1000;

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    acpi: true,
    autostart: false,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
});

await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const acpi = cpu.devices.acpi;
const io = cpu.io;

// Line levels as driven through device_raise_irq/device_lower_irq
const line = new Array(24).fill(false);
{
    const raise = cpu.device_raise_irq;
    const lower = cpu.device_lower_irq;
    cpu.device_raise_irq = irq => { line[irq] = true; raise(irq); };
    cpu.device_lower_irq = irq => { line[irq] = false; lower(irq); };
}

// The slave 8259 as laid out in pic.rs (see CPU.set_state_pic)
const pic_slave = () => new Uint8Array(cpu.wasm_memory.buffer, cpu.get_pic_addr_slave(), 13);
const PIC_IRR = 3;
const PIC_ELCR = 10;
const slave_irr_has_irq9 = () => (pic_slave()[PIC_IRR] & 1 << (SCI_IRQ - 8)) !== 0;

let now = 0;
acpi.clock = () => now;

const power_off_events = [];
emulator.add_listener("acpi-power-off", state => power_off_events.push(state));
const sleep_events = [];
emulator.add_listener("acpi-sleep", state => sleep_events.push("sleep " + state));
emulator.add_listener("acpi-wake", cause => sleep_events.push("wake " + cause));

const pci_address = (device, reg) => (0x80000000 | device << 11 | reg & 0xFC) | 0;
function pci_write32(device, reg, value)
{
    io.port_write32(PCI_CONFIG_ADDRESS, pci_address(device, reg));
    io.port_write32(PCI_CONFIG_DATA, value);
}
function pci_write8(device, reg, value)
{
    io.port_write32(PCI_CONFIG_ADDRESS, pci_address(device, reg));
    io.port_write8(PCI_CONFIG_DATA + (reg & 3), value);
}
function pci_read32(device, reg)
{
    io.port_write32(PCI_CONFIG_ADDRESS, pci_address(device, reg));
    return io.port_read32(PCI_CONFIG_DATA);
}

/** What SeaBIOS does in piix4_pm_config_setup */
function program_pm_base(base)
{
    pci_write32(ACPI_PCI_DEVICE, PCI_PMBA, base | 1);
    pci_write8(ACPI_PCI_DEVICE, PCI_PMREGMISC, 1);
}

function power_on()
{
    acpi.reset();
    program_pm_base(PM_BASE);
    for(const sources of cpu.shared_irq_sources)
    {
        sources.clear();
    }
    line.fill(false);
    cpu.device_lower_irq(SCI_IRQ);
    now = 0;
    acpi.timer_offset = 0;
    acpi.timer_last = 0;
    acpi.timer_period = 0;
}

function enable_acpi_mode()
{
    io.port_write8(SMI_CMD, 0xF1);
}

const ms_for_ticks = ticks => ticks / TICKS_PER_MS;

const tests = [];
const test = (name, fn) => tests.push({ name, fn });

// Run before any PCI configuration access: the reset register must already
// exist when a new VM is created (including a VM that will restore a state).
test("reset control is independent of PCI configuration address accesses", () => {
    const reboot = cpu.reboot_internal;
    let resets = 0;
    cpu.reboot_internal = () => { resets++; };
    try
    {
        assert.equal(io.port_read8(RESET_CONTROL), 0);
        io.port_write8(RESET_CONTROL, 0x06);
        assert.equal(resets, 1, "FADT reset works before any access to 0xCF8");

        cpu.devices.pci.reset();
        io.port_write8(RESET_CONTROL, 0x02);
        for(const value of [0x0200, 0x0600])
        {
            io.port_write16(PCI_CONFIG_ADDRESS, value);
            assert.equal(cpu.devices.pci.pci_addr32[0] & 0xFFFF, value);
            io.port_write32(PCI_CONFIG_ADDRESS, pci_address(0, 0) | value);
            assert.equal(cpu.devices.pci.pci_addr32[0], pci_address(0, 0) | value);
            assert.equal(resets, 1, "word/dword config writes never reset the CPU");
            assert.equal(io.port_read8(RESET_CONTROL), 0x02, "config writes preserve RCR");
        }

        io.port_write8(RESET_CONTROL, 0x06); // Linux reboot=pci
        assert.equal(resets, 2);
        io.port_write32(PCI_CONFIG_ADDRESS, pci_address(0, 0));
        io.port_write8(RESET_CONTROL, 0x06);
        assert.equal(resets, 2, "PCI config accesses do not clear the RST_CPU latch");
    }
    finally
    {
        cpu.devices.pci.reset();
        cpu.reboot_internal = reboot;
    }
});

test("an event is latched while disabled and raises the SCI once enabled", () => {
    power_on();
    enable_acpi_mode();
    assert.equal(io.port_read16(PM1_CNT) & SCI_EN, SCI_EN);

    acpi.press_power_button();
    assert.equal(io.port_read16(PM1_STS) & PWRBTN, PWRBTN);
    assert.equal(line[SCI_IRQ], false);

    io.port_write16(PM1_EN, PWRBTN);
    assert.equal(line[SCI_IRQ], true);

    io.port_write16(PM1_STS, PWRBTN);
    assert.equal(io.port_read16(PM1_STS) & PWRBTN, 0);
    assert.equal(line[SCI_IRQ], false);
});

test("SCI_EN gates the SCI, is switched through SMI_CMD and preserved on PM1_CNT writes", () => {
    power_on();
    io.port_write16(PM1_EN, PWRBTN);
    acpi.press_power_button();
    assert.equal(line[SCI_IRQ], false, "no SCI in legacy mode");

    io.port_write16(PM1_CNT, SCI_EN);
    assert.equal(io.port_read16(PM1_CNT) & SCI_EN, 0, "OSPM cannot set SCI_EN");

    io.port_write8(SMI_CMD, 0xF1);
    assert.equal(line[SCI_IRQ], true);
    assert.equal(io.port_read8(SMI_CMD), 0xF1);

    io.port_write16(PM1_CNT, 0);
    assert.equal(io.port_read16(PM1_CNT) & SCI_EN, SCI_EN, "OSPM cannot clear SCI_EN");
    assert.equal(line[SCI_IRQ], true);

    io.port_write8(SMI_CMD, 0xF0);
    assert.equal(line[SCI_IRQ], false);
    assert.equal(io.port_read16(PM1_STS) & PWRBTN, PWRBTN, "status survives ACPI disable");
});

test("with two pending events, clearing one keeps the SCI asserted", () => {
    power_on();
    enable_acpi_mode();
    io.port_write16(PM1_EN, PWRBTN | TMR);
    acpi.press_power_button();
    now = ms_for_ticks((1 << 23) + 10);
    acpi.timer(now);
    assert.equal(io.port_read16(PM1_STS) & (PWRBTN | TMR), PWRBTN | TMR);
    assert.equal(line[SCI_IRQ], true);

    io.port_write16(PM1_STS, PWRBTN);
    assert.equal(line[SCI_IRQ], true);

    io.port_write16(PM1_STS, TMR);
    assert.equal(line[SCI_IRQ], false);
});

for(const first of ["sci", "other"])
{
    test(`SCI and another source share IRQ 9 (cleared ${first} first)`, () => {
        power_on();
        pic_slave()[PIC_ELCR] |= 1 << (SCI_IRQ - 8); // level-triggered, as the guest programs it
        enable_acpi_mode();
        io.port_write16(PM1_EN, PWRBTN);

        acpi.press_power_button();
        cpu.set_shared_irq_level(SCI_IRQ, OTHER_SOURCE, true);
        assert.equal(line[SCI_IRQ], true);
        assert.ok(slave_irr_has_irq9());

        const clear_sci = () => io.port_write16(PM1_STS, PWRBTN);
        const clear_other = () => cpu.set_shared_irq_level(SCI_IRQ, OTHER_SOURCE, false);
        const [a, b] = first === "sci" ? [clear_sci, clear_other] : [clear_other, clear_sci];

        a();
        assert.equal(line[SCI_IRQ], true, "remaining source keeps the line");
        assert.ok(slave_irr_has_irq9(), "remaining source keeps the PIC request");

        b();
        assert.equal(line[SCI_IRQ], false);
        assert.ok(!slave_irr_has_irq9());

        pic_slave()[PIC_ELCR] &= ~(1 << (SCI_IRQ - 8));
    });
}

test("a PCI function lowers the line it asserted even if the guest rerouted the pin", () => {
    power_on();
    const pci = cpu.devices.pci;
    const pci_id = pci.device_spaces.findIndex(space => space && (space[0x3C >> 2] >> 8 & 0xFF) !== 0);
    assert.ok(pci_id >= 0, "a PCI function with an interrupt pin");

    const routing = pci.isa_bridge_space8.slice(0x60, 0x64);
    try
    {
        pci.isa_bridge_space8.fill(10, 0x60, 0x64);
        pci.raise_irq(pci_id);
        assert.equal(line[10], true);

        pci.isa_bridge_space8.fill(11, 0x60, 0x64);
        pci.lower_irq(pci_id);
        assert.equal(line[10], false);
        assert.equal(cpu.shared_irq_sources[10].size, 0);
        assert.equal(cpu.shared_irq_sources[11].size, 0);

        // PIRQ routing disabled (bit 7): the pin reaches no ISA IRQ
        pci.isa_bridge_space8.fill(0x8A, 0x60, 0x64);
        pci.raise_irq(pci_id);
        assert.ok(cpu.shared_irq_sources.every(sources => sources.size === 0));
        pci.lower_irq(pci_id);
        assert.equal(line[10], false);

        // disabling the route while asserted deasserts the old line
        pci.isa_bridge_space8.fill(11, 0x60, 0x64);
        pci.raise_irq(pci_id);
        assert.equal(line[11], true);
        pci.isa_bridge_space8.fill(0x8B, 0x60, 0x64);
        pci.raise_irq(pci_id);
        assert.equal(line[11], false);
        pci.lower_irq(pci_id);
    }
    finally
    {
        pci.isa_bridge_space8.set(routing, 0x60);
    }
});

test("PM1 registers: write-one-to-clear, defined bits only, every access width", () => {
    power_on();
    enable_acpi_mode();
    acpi.press_power_button();
    now = ms_for_ticks((1 << 23) + 1);
    acpi.timer(now);

    io.port_write16(PM1_STS, 0);
    assert.equal(io.port_read16(PM1_STS), PWRBTN | TMR, "writing zero changes nothing");

    io.port_write8(PM1_STS + 1, PWRBTN >> 8);
    assert.equal(io.port_read16(PM1_STS), TMR, "byte write to the upper half");

    io.port_write16(PM1_EN, 0xFFFF);
    assert.equal(io.port_read16(PM1_EN), PM1_EN_DEFINED);
    assert.equal(io.port_read32(PM1_STS) >>> 0, (PM1_EN_DEFINED << 16 | TMR) >>> 0, "dword read of PM1_EVT");
    assert.equal(io.port_read8(PM1_EN + 1), PM1_EN_DEFINED >> 8);

    io.port_write16(PM1_CNT, 0xFFFF & ~SLP_EN);
    assert.equal(io.port_read16(PM1_CNT), SLP_TYP | BM_RLS | SCI_EN, "GBL_RLS/SLP_EN read as zero, reserved bits ignored");
    io.port_write16(PM1_CNT, SCI_EN);

    assert.equal(io.port_read8(PM_BASE + 6), 0);
    assert.equal(io.port_read16(PM_BASE + 0xC), 0);
    assert.equal(io.port_read32(PM_BASE + 0x3C), 0);

    io.port_write32(GLBCTL, 0x12345678);
    assert.equal(io.port_read32(GLBCTL), 0x12345678);
    assert.equal(io.port_read8(GLBCTL + 1), 0x56);
});

test("PM timer: 3.579545 MHz, 24 bits, monotonic, does not advance on reads", () => {
    power_on();
    assert.equal(io.port_read32(PM_TMR), 0);

    now = 1.5;
    const a = io.port_read32(PM_TMR);
    assert.equal(io.port_read32(PM_TMR), a, "repeated reads at the same time");
    assert.equal(io.port_read32(PM_TMR), a);

    now = 1000;
    assert.equal(io.port_read32(PM_TMR), 3579545);
    const bytes = [0, 1, 2, 3].map(i => io.port_read8(PM_TMR + i));
    assert.deepEqual(bytes, [3579545 & 0xFF, 3579545 >> 8 & 0xFF, 3579545 >> 16 & 0xFF, 0]);
    assert.equal(io.port_read16(PM_TMR + 2), 3579545 >> 16);

    now = ms_for_ticks((1 << 24) + 1000);
    const wrapped = io.port_read32(PM_TMR);
    assert.equal(wrapped, Math.floor(now * TICKS_PER_MS) & 0xFFFFFF);
    assert.ok(wrapped < 2000, "wrapped at 24 bits");

    now = 0;
    assert.equal(io.port_read32(PM_TMR), wrapped, "never goes back");

    io.port_write32(PM_TMR, 0);
    assert.equal(io.port_read32(PM_TMR), wrapped, "read-only");
});

test("TMR_STS latches at bit 23 toggles regardless of TMR_EN; timer() reports the deadline", () => {
    power_on();
    enable_acpi_mode();
    assert.equal(acpi.timer(0), 100);

    now = ms_for_ticks((1 << 23) - 100);
    acpi.timer(now);
    assert.equal(io.port_read16(PM1_STS) & TMR, 0);

    now = ms_for_ticks((1 << 23) + 1);
    acpi.timer(now);
    assert.equal(io.port_read16(PM1_STS) & TMR, TMR);
    assert.equal(line[SCI_IRQ], false);

    io.port_write16(PM1_EN, TMR);
    assert.equal(line[SCI_IRQ], true);
    io.port_write16(PM1_STS, TMR);
    assert.equal(line[SCI_IRQ], false);

    // the status is also latched when only PM1_STS is read
    now = ms_for_ticks((1 << 24) + 1);
    assert.equal(io.port_read16(PM1_STS) & TMR, TMR);
    io.port_write16(PM1_STS, TMR);

    now = ms_for_ticks((1 << 24) + 10);
    assert.equal(acpi.timer(now), 100);
    now = ms_for_ticks(3 * (1 << 23) - 5 * TICKS_PER_MS);
    const deadline = acpi.timer(now);
    assert.ok(Math.abs(deadline - 5) < 0.01, "5 ms until the next toggle, got " + deadline);
});

test("GPE0: status is write-one-to-clear, enable is read/write, both feed the SCI", () => {
    power_on();
    enable_acpi_mode();
    io.port_write16(GPE0_EN, 0x0003);
    assert.equal(io.port_read16(GPE0_EN), 0x0003);

    // No GPE source is implemented yet; inject the status bits
    acpi.gpe_sts = 0x0101;
    acpi.update_sci();
    assert.equal(line[SCI_IRQ], true);
    assert.equal(io.port_read32(GPE0_STS) >>> 0, (0x0003 << 16 | 0x0101) >>> 0);

    io.port_write8(GPE0_STS, 0xFF);
    assert.equal(io.port_read16(GPE0_STS), 0x0100);
    assert.equal(line[SCI_IRQ], false, "GPE 8 is not enabled");

    io.port_write8(GPE0_STS + 1, 0x01);
    assert.equal(io.port_read16(GPE0_STS), 0);
    assert.equal(io.port_read8(GPE0_EN + 1), 0);
});

test("SLP_EN: S5 and S4 turn the machine off, unsupported types wake up at once", () => {
    power_on();
    power_off_events.length = 0;

    io.port_write16(PM1_CNT, 5 << 10 | SLP_EN); // a type no sleep state uses
    assert.equal(acpi.soft_off, 0);
    assert.equal(acpi.sleeping, 0);
    assert.equal(io.port_read16(PM1_STS) & WAK, WAK);
    assert.equal(io.port_read16(PM1_CNT) & SLP_EN, 0, "SLP_EN reads as zero");
    io.port_write16(PM1_STS, WAK);
    assert.equal(io.port_read16(PM1_STS) & WAK, 0);

    io.port_write16(PM1_CNT, 0 << 10); // writing SLP_TYP alone does nothing
    assert.equal(acpi.soft_off, 0);

    io.port_write16(PM1_CNT, 2 << 10 | SLP_EN);
    assert.equal(acpi.soft_off, 4);

    power_on();
    io.port_write8(PM1_CNT + 1, SLP_EN >> 8); // byte access, SLP_TYP = 0
    assert.equal(acpi.soft_off, 5);
    io.port_write8(PM1_CNT + 1, SLP_EN >> 8);
    assert.deepEqual(power_off_events, ["S4", "S5"], "one event per power-off");

    power_on();
    assert.equal(acpi.soft_off, 0);
});

const RTC_EVENT = 1 << 10;
const CMOS_SHUTDOWN_STATUS = 0x0F;

test("S3: cores stop, RAM and the BIOS shadow stay, the power button wakes through the resume path", () => {
    power_on();
    sleep_events.length = 0;
    const ram = 0x300000, shadow = 0xFFF00;
    cpu.mem8[ram] = 0x5A;
    const bios_byte = cpu.mem8[shadow];
    cpu.mem8[shadow] = bios_byte ^ 0xFF; // like SeaBIOS's "POST ran" flag in its RAM copy

    io.port_write16(PM1_CNT, SCI_EN | 1 << 10 | SLP_EN); // S3 (SLP_TYP 1)
    assert.equal(acpi.sleeping, 3);
    assert.equal(acpi.soft_off, 0, "not a power-off");
    assert.equal(cpu.devices.rtc.cmos_read(CMOS_SHUTDOWN_STATUS), 0xFE, "SeaBIOS will resume through the FACS waking vector");
    assert.deepEqual(sleep_events, ["sleep S3"]);
    assert.equal(cpu.run_cores() > 0, true, "while asleep only device timers run");

    // a second SLP_EN is ignored while asleep
    io.port_write16(PM1_CNT, 1 << 10 | SLP_EN);
    assert.deepEqual(sleep_events, ["sleep S3"]);

    acpi.press_power_button();
    assert.equal(acpi.sleeping, 0);
    assert.deepEqual(sleep_events, ["sleep S3", "wake power-button"]);
    assert.equal(acpi.pm1_sts & (WAK | PWRBTN), WAK | PWRBTN, "WAK_STS and the cause");
    assert.equal(acpi.pm1_cnt & SCI_EN, 0, "the hardware reset clears SCI_EN (the OS sets it again)");
    assert.equal(cpu.mem8[ram], 0x5A, "RAM kept");
    assert.equal(cpu.mem8[shadow], bios_byte ^ 0xFF, "the BIOS is not reloaded on wake");
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xFFFF0, "the CPU starts at the reset vector");
    cpu.mem8[shadow] = bios_byte;
});

test("S3: the RTC alarm wakes only with RTC_EN; RTC_STS names the cause", () => {
    power_on();
    enable_acpi_mode();
    sleep_events.length = 0;
    io.port_write16(PM1_CNT, SCI_EN | 1 << 10 | SLP_EN);
    assert.equal(acpi.sleeping, 3);
    acpi.rtc_alarm(); // RTC_EN clear
    assert.equal(acpi.sleeping, 3, "no wake without RTC_EN");
    acpi.press_power_button();
    assert.equal(acpi.sleeping, 0);

    power_on();
    enable_acpi_mode();
    sleep_events.length = 0;
    io.port_write16(PM1_EN, RTC_EVENT);
    io.port_write16(PM1_CNT, SCI_EN | 1 << 10 | SLP_EN);
    assert.equal(acpi.sleeping, 3);
    acpi.rtc_alarm();
    assert.equal(acpi.sleeping, 0);
    assert.deepEqual(sleep_events, ["sleep S3", "wake rtc"]);
    assert.equal(acpi.pm1_sts & (WAK | RTC_EVENT | PWRBTN), WAK | RTC_EVENT);

    // while running, the alarm latches RTC_STS (an SCI when enabled)
    power_on();
    enable_acpi_mode();
    io.port_write16(PM1_EN, RTC_EVENT);
    acpi.rtc_alarm();
    assert.equal(io.port_read16(PM1_STS) & RTC_EVENT, RTC_EVENT);
    assert.equal(line[SCI_IRQ], true);
});

test("S3 survives a snapshot: the restored machine is asleep and wakes", () => {
    power_on();
    io.port_write16(PM1_CNT, SCI_EN | 1 << 10 | SLP_EN);
    const state = acpi.get_state();
    acpi.press_power_button();
    assert.equal(acpi.sleeping, 0);
    acpi.set_state(state);
    assert.equal(acpi.sleeping, 3, "format 3 keeps the sleeping state");
    acpi.press_power_button();
    assert.equal(acpi.sleeping, 0);

    // a format 2 image (before S3) is awake
    const old = state.slice(0, 10);
    old[4] = 2;
    acpi.set_state(old);
    assert.equal(acpi.sleeping, 0);
});

test("fw_cfg etc/system-states advertises S3, S4 and S5", () => {
    const file = cpu.option_roms.find(f => f.name === "etc/system-states");
    assert.ok(file);
    assert.deepEqual(Array.from(file.data), [0x80, 0, 0, 0x81, 0x82, 0x80]);

    // Read it through the fw_cfg ports, as SeaBIOS does
    const read_bytes = n => Array.from({ length: n }, () => io.port_read8(FW_CFG_DATA));
    const be = bytes => bytes.reduce((v, b) => v * 256 + b, 0);

    io.port_write16(FW_CFG_SELECT, FW_CFG_FILE_DIR);
    const count = be(read_bytes(4));
    let select = -1;
    for(let i = 0; i < count; i++)
    {
        const size = be(read_bytes(4));
        const sel = be(read_bytes(2));
        read_bytes(2);
        const name = String.fromCharCode(...read_bytes(56)).replace(/\0.*$/s, "");
        if(name === "etc/system-states")
        {
            assert.equal(size, 6);
            select = sel;
        }
    }
    assert.ok(select >= 0, "listed in the file directory");

    io.port_write16(FW_CFG_SELECT, select);
    assert.deepEqual(read_bytes(6), [0x80, 0, 0, 0x81, 0x82, 0x80]);
});

test("snapshot: registers, timer phase and SCI survive save_state/restore_state", async () => {
    power_on();
    pic_slave()[PIC_ELCR] |= 1 << (SCI_IRQ - 8);
    enable_acpi_mode();
    io.port_write16(PM1_EN, PWRBTN);
    io.port_write16(GPE0_EN, 0x0004);
    io.port_write32(GLBCTL, 1);
    acpi.press_power_button();
    cpu.set_shared_irq_level(SCI_IRQ, OTHER_SOURCE, true);
    now = 500;
    const timer = io.port_read32(PM_TMR);
    const registers = () => [PM1_STS, PM1_EN, PM1_CNT, GPE0_STS, GPE0_EN].map(port => io.port_read16(port));
    const before = registers();

    io.port_write8(RESET_CONTROL, 0x02);
    const state = await emulator.save_state();

    power_on();
    program_pm_base(0xB000);
    cpu.devices.pci.reset();
    io.port_write16(PM1_EN, 0);
    now = 10000; // host time moved on while the image was stored

    await emulator.restore_state(state);
    assert.equal(acpi.pm_base, PM_BASE, "PM decode follows the restored PCI configuration");
    assert.equal(io.port_read32(0xB008), -1, "the pre-restore mapping is released");
    assert.equal(io.port_read8(RESET_CONTROL), 0x02, "RCR survives restore");
    assert.deepEqual(registers(), before);
    assert.equal(io.port_read32(GLBCTL), 1);
    assert.equal(io.port_read32(PM_TMR), timer, "the timer continues from the saved value");
    now = 10100;
    assert.equal(io.port_read32(PM_TMR), timer + Math.floor(100 * TICKS_PER_MS));

    assert.deepEqual([...cpu.shared_irq_sources[SCI_IRQ]].sort(), [OTHER_SOURCE, 0x100].sort());
    assert.ok(slave_irr_has_irq9());

    // The other source leaving must not drop the SCI
    cpu.set_shared_irq_level(SCI_IRQ, OTHER_SOURCE, false);
    assert.ok(slave_irr_has_irq9());
    io.port_write16(PM1_STS, PWRBTN);
    assert.ok(!slave_irr_has_irq9());
    pic_slave()[PIC_ELCR] &= ~(1 << (SCI_IRQ - 8));
});

test("snapshot restores both enabled and disabled PM I/O decode", async () => {
    power_on();
    io.port_write16(PM1_EN, PWRBTN);
    const enabled_state = await emulator.save_state();
    acpi.reset();
    const disabled_state = await emulator.save_state();

    await emulator.restore_state(enabled_state);
    assert.equal(acpi.pm_base, PM_BASE);
    assert.equal(io.port_read16(PM1_EN), PWRBTN, "restore enables a previously disabled PM block");

    await emulator.restore_state(disabled_state);
    assert.equal(acpi.pm_base, -1);
    assert.equal(io.port_read16(PM1_EN), 0xFFFF, "restore disables a previously enabled PM block");
});

test("state images from before the rewrite are imported", () => {
    power_on();
    enable_acpi_mode();
    now = 0;
    // format 1: [PM1_CNT as written, PM1_STS, PM1_EN, raw GPE bytes]
    acpi.set_state([0x2001, PWRBTN, PWRBTN, new Uint8Array([0xFF, 0xFF, 0x01, 0x00])]);
    acpi.sync_sci();
    assert.equal(io.port_read16(PM1_CNT), SCI_EN, "SLP_EN dropped, SCI_EN kept");
    assert.equal(io.port_read16(GPE0_STS), 0, "stale GPE status bytes dropped");
    assert.equal(io.port_read16(GPE0_EN), 1);
    assert.equal(line[SCI_IRQ], true, "pending enabled event raises the SCI");
    assert.equal(acpi.soft_off, 0);
});

test("reset returns to power-on values, releases the SCI and keeps the timer running", () => {
    power_on();
    enable_acpi_mode();
    io.port_write16(PM1_EN, PWRBTN);
    acpi.press_power_button();
    assert.equal(line[SCI_IRQ], true);
    now = 20;
    const timer = io.port_read32(PM_TMR);

    acpi.reset();
    assert.equal(line[SCI_IRQ], false);
    assert.equal(io.port_read16(PM1_STS), 0xFFFF, "PCIRST# disables the PM I/O space");
    program_pm_base(PM_BASE);
    assert.deepEqual([PM1_STS, PM1_EN, PM1_CNT, GPE0_STS, GPE0_EN].map(port => io.port_read16(port)), [0, 0, 0, 0, 0]);
    assert.equal(io.port_read32(PM_TMR), timer);
});

test("a machine reset deasserts every shared source (like PCIRST#)", () => {
    power_on();
    cpu.set_shared_irq_level(11, OTHER_SOURCE, true);
    enable_acpi_mode();
    io.port_write16(PM1_EN, PWRBTN);
    acpi.press_power_button();
    assert.equal(line[11], true);
    assert.equal(line[SCI_IRQ], true);

    cpu.reboot_internal();
    assert.equal(line[11], false);
    assert.equal(line[SCI_IRQ], false);
    assert.ok(cpu.shared_irq_sources.every(sources => sources.size === 0));
    assert.equal(acpi.pm1_cnt & SCI_EN, 0, "legacy mode after reset");
    assert.equal(io.port_read16(PM1_CNT), 0xFFFF, "PM I/O space disabled until the firmware programs PMBA");
});

test("the PM block is decoded at PMBA once PMREGMISC enables it", () => {
    power_on();
    now = 1000;
    const timer = io.port_read32(PM_TMR);
    assert.equal(timer, 3579545);

    program_pm_base(0xB000);
    assert.equal(io.port_read32(0xB008), timer, "moved");
    assert.equal(io.port_read32(PM_TMR), -1, "old base released");

    pci_write8(ACPI_PCI_DEVICE, PCI_PMREGMISC, 0);
    assert.equal(io.port_read32(0xB008), -1, "disabled");

    pci_write32(ACPI_PCI_DEVICE, PCI_PMBA, 0xB0FF);
    assert.equal(pci_read32(ACPI_PCI_DEVICE, PCI_PMBA), 0xB0C1, "reserved bits read as 0, bit 0 as 1");
    pci_write8(ACPI_PCI_DEVICE, PCI_PMREGMISC, 1);
    assert.equal(io.port_read32(0xB0C8), timer, "64-byte aligned base");

    program_pm_base(PM_BASE);
    assert.equal(io.port_read32(0xB0C8), -1);
    assert.equal(io.port_read32(PM_TMR), timer);
});

let failed = 0;
for(const { name, fn } of tests)
{
    try
    {
        await fn();
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("not ok - " + name);
        console.log(e);
    }
}

console.log(`${tests.length - failed}/${tests.length} ACPI device tests passed`);
await emulator.destroy();
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                               source/v64/tests/devices/acpi_guest.js                                                              0000755 0000000 0000000 00000051374 00000000000 015146  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// ACPI with a real guest (acpi: true). GUEST selects the image:
//   buildroot (default): buildroot-bzimage68.bin, Linux 6.8, PIC interrupt routing
//   linux4: linux4.iso, Linux 4.16, IOAPIC interrupt routing (uses the MADT)
// - the tables SeaBIOS installed from v86's table loader match the emulated
//   hardware and advertise S3, S4 and S5; the guest reports no ACPI errors
// - S3, if the kernel supports it (linux4): suspend to RAM, woken
//   alternately by an RTC alarm and by the power button (S3_CYCLES); RAM
//   contents and the shell survive, the kernel reports the wake from S3
// - S4, if supported: hibernate to a swap disk, ACPI S4 soft off, power
//   on with RAM cleared, the booted kernel restores the image from the disk
//   (as an initramfs does, through /sys/power/resume) (S4_CYCLES)
// - the fixed power button reaches the guest as one event, without an SCI storm
// - the PM timer keeps time as the guest's clocksource
// - "reboot" (reboot=acpi) goes through the FADT reset register and the guest
//   comes back with ACPI enabled (the direct-boot kernel is placed again)
// - "poweroff" enters S5: the emulator emits acpi-power-off and stops
// - power_button() powers the machine on again (repeated POWER_CYCLES times)

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const POWER_CYCLES = +process.env.POWER_CYCLES || 2;
const S3_CYCLES = process.env.S3_CYCLES === undefined ? 4 : +process.env.S3_CYCLES;
const S4_CYCLES = process.env.S4_CYCLES === undefined ? 2 : +process.env.S4_CYCLES;
const CPU_CORES = +process.env.CPU_CORES || 1;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

/**
 * A file from an ISO9660 image (plain names, without version or Rock Ridge)
 * @param {string} path
 * @param {!Array<string>} names
 * @return {!ArrayBuffer}
 */
function iso_file(path, names)
{
    const iso = fs.readFileSync(path);
    let extent = iso.readUInt32LE(16 * 2048 + 156 + 2), size = iso.readUInt32LE(16 * 2048 + 156 + 10);
    for(const name of names)
    {
        let found = false;
        for(let at = extent * 2048; at < extent * 2048 + size;)
        {
            const length = iso[at];
            if(!length) { at = (Math.floor(at / 2048) + 1) * 2048; continue; }
            const entry = iso.toString("latin1", at + 33, at + 33 + iso[at + 32]).replace(/;\d+$/, "").replace(/\.$/, "");
            if(entry === name)
            {
                extent = iso.readUInt32LE(at + 2);
                size = iso.readUInt32LE(at + 10);
                found = true;
                break;
            }
            at += length;
        }
        assert.ok(found, name + " in " + path);
    }
    return iso.buffer.slice(iso.byteOffset + extent * 2048, iso.byteOffset + extent * 2048 + size);
}

const GUEST = process.env.GUEST || "buildroot";
const GUESTS = {
    // reboot=acpi: use the FADT reset register (also the default of newer kernels)
    "buildroot": {
        bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
        cmdline: "console=ttyS0 audit=0 reboot=acpi",
    },
    // The CD's own kernel, booted directly: its isolinux line is
    // "root=/dev/sr0". nokaslr: 32-bit hibernation restores into a kernel at
    // the same address (with KASLR the resuming kernel may lie elsewhere).
    // resume=: the kernel restores a hibernation image from the swap disk.
    // (Kernel messages stay on the VGA console: the image starts a shell on
    // the console and one on ttyS0.)
    "linux4": {
        cdrom: { url: __dirname + "/../../images/linux4.iso" },
        bzimage: { buffer: iso_file(__dirname + "/../../images/linux4.iso", ["BOOT", "BZIMAGE"]) },
        cmdline: "root=/dev/sr0 nokaslr resume=/dev/sda",
        // blank disk: swap space for hibernation
        hda: { buffer: new ArrayBuffer(96 * 1024 * 1024) },
    },
};
assert.ok(GUESTS[GUEST], "unknown GUEST " + GUEST);

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    autostart: true,
    memory_size: 256 * 1024 * 1024,
    acpi: true,
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1 && !+process.env.DISABLE_JIT,
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
    ...GUESTS[GUEST],
    // PARALLEL=1: application processors in vCPU workers
    ...(+process.env.PARALLEL ? { parallel: true, wasm_path: __dirname + "/../../build/v86-parallel.wasm" } : {}),
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, (120 + POWER_CYCLES * 60 + S3_CYCLES * 60 + S4_CYCLES * 180) * 1000);

let serial = "";
let waiter = null;

emulator.add_listener("serial0-output-byte", function(byte)
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});

const PROMPT = /~% $/;

function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what)), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}

async function command(cmd, timeout_ms = 60000)
{
    serial = "";
    emulator.serial0_send(cmd + "\n");
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(cmd.length);
}

function value_of(output, key)
{
    const match = output.match(new RegExp(key + "=(\\d+)"));
    assert.ok(match, "no " + key + "= in " + JSON.stringify(output));
    return +match[1];
}

function next_event(name, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + name)), timeout_ms);
        const listener = value => {
            clearTimeout(timer);
            emulator.remove_listener(name, listener);
            resolve(value);
        };
        emulator.add_listener(name, listener);
    });
}

/**
 * The tables SeaBIOS installed from v86's etc/table-loader, read from guest memory
 */
function check_tables()
{
    const mem = emulator.v86.cpu.mem8;
    const u16 = a => mem[a] | mem[a + 1] << 8;
    const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
    const u64 = a => u32(a) + u32(a + 4) * 2 ** 32;
    const signature = (a, n = 4) => String.fromCharCode(...mem.subarray(a, a + n));
    const checksum = (a, n) => mem.subarray(a, a + n).reduce((x, y) => x + y, 0) & 0xFF;
    const contains = (table, text) => Buffer.from(mem.subarray(table.addr, table.addr + table.len)).includes(text);

    let rsdp = -1;
    for(let a = 0xE0000; a < 0x100000; a += 16)
    {
        if(signature(a, 8) === "RSD PTR " && checksum(a, 20) === 0)
        {
            rsdp = a;
            break;
        }
    }
    assert.ok(rsdp >= 0, "RSDP in the BIOS area");
    assert.equal(mem[rsdp + 15], 2, "RSDP revision 2");
    assert.equal(checksum(rsdp, 36), 0, "RSDP extended checksum");
    assert.equal(signature(rsdp + 9, 6), "V86   ", "v86's tables, not SeaBIOS's fallback");

    const table_at = addr => {
        const len = u32(addr + 4);
        assert.equal(checksum(addr, len), 0, signature(addr) + " checksum");
        return { addr, len };
    };

    const xsdt = table_at(u64(rsdp + 24));
    assert.equal(signature(xsdt.addr), "XSDT");
    const rsdt = table_at(u32(rsdp + 16));
    assert.equal(signature(rsdt.addr), "RSDT");

    const tables = {};
    for(let p = xsdt.addr + 36; p < xsdt.addr + xsdt.len; p += 8)
    {
        const addr = u64(p);
        tables[signature(addr)] = table_at(addr);
        assert.equal(u32(rsdt.addr + 36 + (p - xsdt.addr - 36) / 2), addr, "RSDT lists the same table");
    }

    const facp = tables["FACP"].addr;
    assert.equal(mem[facp + 8], 3, "FADT revision 3");
    tables["DSDT"] = table_at(u32(facp + 40));
    assert.equal(signature(tables["DSDT"].addr), "DSDT");
    assert.equal(u64(facp + 140), tables["DSDT"].addr, "X_DSDT");

    // FACS has no checksum; it must be 64-byte aligned and at least 64 bytes
    const facs = u32(facp + 36);
    assert.equal(signature(facs), "FACS");
    assert.equal(facs % 64, 0);
    assert.ok(u32(facs + 4) >= 64);
    assert.equal(u64(facp + 132), facs, "X_FIRMWARE_CTRL");

    // FADT fields against the emulated PIIX4 PM function, at the base SeaBIOS programmed
    const pm_base = emulator.v86.cpu.devices.acpi.pm_base;
    assert.equal(pm_base, 0x600, "SeaBIOS moves the PM base when it loads v86's tables");
    assert.equal(u16(facp + 46), 9, "SCI_INT");
    assert.equal(u32(facp + 48), 0xB2, "SMI_CMD");
    assert.equal(mem[facp + 52], 0xF1, "ACPI_ENABLE");
    assert.equal(mem[facp + 53], 0xF0, "ACPI_DISABLE");
    assert.equal(u32(facp + 56), pm_base, "PM1a_EVT_BLK");
    assert.equal(u32(facp + 64), pm_base + 4, "PM1a_CNT_BLK");
    assert.equal(u32(facp + 76), pm_base + 8, "PM_TMR_BLK");
    assert.equal(u32(facp + 80), 0xAFE0, "GPE0_BLK");
    assert.deepEqual([mem[facp + 88], mem[facp + 89], mem[facp + 91], mem[facp + 92]], [4, 2, 4, 4], "block lengths");
    const flags = u32(facp + 112);
    assert.equal(flags & 1 << 4, 0, "PWR_BUTTON clear: fixed power button");
    assert.equal(flags & 1 << 8, 0, "TMR_VAL_EXT clear: 24-bit timer");
    assert.ok(flags & 1 << 10, "RESET_REG_SUP");
    assert.deepEqual([mem[facp + 116], u64(facp + 120), mem[facp + 128]], [1, 0xCF9, 0x06], "RESET_REG");

    // Sleep states: S3 (SLP_TYP 1), S4 (2), S5 (0)
    for(const state of ["_S3_", "_S4_", "_S5_"]) assert.ok(contains(tables["DSDT"], state), state + " advertised");
    // no S4BIOS: the OS hibernates itself
    assert.equal(u32(facs + 16) & 1, 0, "FACS S4BIOS_F clear");

    assert.ok(tables["APIC"], "MADT");

    return Object.keys(tables).sort();
}

async function boot()
{
    // printed by the image's init scripts on every boot, then the shell
    await wait_serial(/Files send via emulator appear in \/mnt\/[\s\S]*~% $/, "boot to the shell prompt", 120000);
}

async function power_off()
{
    const event = next_event("acpi-power-off", 60000);
    const stopped = next_event("emulator-stopped", 60000);
    serial = "";
    emulator.serial0_send("poweroff\n");
    assert.equal(await event, "S5");
    await stopped;
    assert.equal(emulator.is_running(), false);
}

const t0 = Date.now();
const log = text => console.log(`[${((Date.now() - t0) / 1000).toFixed(1)}s] ${text}`);

await boot();
log("booted");

log("tables: " + check_tables().join(" "));

// The diagnostics snapshot sees the same machine
{
    const d = await emulator.get_diagnostics();
    assert.equal(d.cpu.mode, "protected32");
    assert.ok(d.cpu.paging);
    assert.equal(d.acpi.pm_base, "0x600");
    assert.ok(d.acpi.sci_enabled, "the OS switched to ACPI mode");
    assert.equal(d.acpi_tables.oem_id, "V86   ");
    assert.deepEqual(d.acpi_tables.tables.map(t => t.signature).sort(), ["APIC", "DSDT", "FACP", "FACS", "XSDT"]);
    assert.ok(d.acpi_tables.tables.every(t => t.checksum_ok));
    // (the local APIC of the core that ran last)
    assert.equal(d.apic.id, d.active_core ?? 0);
}

// Older kernels report that the PCI root bridge has no _OSC; it is optional
// for conventional PCI (the tables don't claim PCIe features)
const PROBLEMS = "dmesg | grep -i -E 'ACPI (BIOS )?(Error|Warning)|AE_[A-Z_]+|Firmware Bug' | grep -v '_OSC failed (AE_NOT_FOUND)'";
const acpi_problems = await command(PROBLEMS + "; echo PROBLEMS=$(" + PROBLEMS + " | wc -l)");
assert.equal(value_of(acpi_problems, "PROBLEMS"), 0, "ACPI errors in dmesg: " + acpi_problems);

const dmesg = await command("dmesg | grep -E 'ACPI: (Interpreter enabled|(PM: )?\\(supports)|Power Button|Using (PIC|IOAPIC) for interrupt routing'");
assert.match(dmesg, /ACPI: Interpreter enabled/);
const sleep_states = await command("cat /sys/power/state 2>/dev/null; echo STATES_END");
const can_suspend = /\bmem\b/.test(sleep_states), can_hibernate = /\bdisk\b/.test(sleep_states);
// a kernel without CONFIG_SUSPEND/HIBERNATION lists only what it can use
assert.match(dmesg, can_suspend ? /ACPI: (PM: )?\(supports S0 S3 S4 S5\)/ : /ACPI: (PM: )?\(supports S0 (S3 )?(S4 )?S5\)/);
assert.match(dmesg, /Power Button \[PWRF\]/);
log("guest ACPI: " + dmesg.trim().split("\n").filter(line => line.includes("ACPI")).join(" | "));

const COUNTERS = "set -- $(cat /sys/firmware/acpi/interrupts/ff_pwr_btn); echo BTN=$1; " +
    "set -- $(cat /sys/firmware/acpi/interrupts/sci); echo SCI=$1";
const before = await command(COUNTERS);
assert.equal(await emulator.power_button(), true);
await new Promise(resolve => setTimeout(resolve, 1000));
const after = await command(COUNTERS);
const buttons = value_of(after, "BTN") - value_of(before, "BTN");
const scis = value_of(after, "SCI") - value_of(before, "SCI");
log(`power button: ${buttons} event(s), ${scis} SCI(s)`);
assert.equal(buttons, 1);
assert.ok(scis >= 1 && scis <= 3, "no SCI storm");

const clocksource = await command(
    "echo acpi_pm > /sys/devices/system/clocksource/clocksource0/current_clocksource; " +
    "cat /sys/devices/system/clocksource/clocksource0/current_clocksource");
if(!/\nacpi_pm/.test(clocksource))
{
    // Keep the failure strict, but distinguish an unavailable/rejected clock
    // from a serial command failure when tests run under heavy host load.
    console.error("Clocksource selection returned: " + JSON.stringify(clocksource));
    console.error(await command(
        "cat /sys/devices/system/clocksource/clocksource0/available_clocksource; " +
        "dmesg | grep -i -E 'clocksource|pm.timer|pmtmr|unstable'"));
}
assert.match(clocksource, /\nacpi_pm/);
const host_start = Date.now();
const uptime = await command("set -- $(cat /proc/uptime); echo U0=${1%.*}${1#*.}; sleep 3; set -- $(cat /proc/uptime); echo U1=${1%.*}${1#*.}");
const guest_seconds = (value_of(uptime, "U1") - value_of(uptime, "U0")) / 100;
const host_seconds = (Date.now() - host_start) / 1000;
log(`acpi_pm clocksource: guest ${guest_seconds.toFixed(2)}s over host ${host_seconds.toFixed(2)}s`);
assert.ok(guest_seconds >= 2.9 && guest_seconds <= host_seconds + 0.1, "guest time follows the PM timer");

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

// S3: suspend to RAM. A tmpfs file (RAM only) must survive; the wake cause
// alternates between the RTC alarm (RTC_EN wake) and the power button.
if(can_suspend && S3_CYCLES)
{
    await command("dd if=/dev/urandom of=/tmp/s3.bin bs=1024 count=2048 2>/dev/null; md5sum /tmp/s3.bin > /tmp/s3.md5");
    for(let cycle = 1; cycle <= S3_CYCLES; cycle++)
    {
        const by_rtc = cycle % 2 === 1;
        const before = await command("set -- $(cat /proc/uptime); echo UP=${1%.*}; echo RTC=$(date +%s)");
        const slept = next_event("acpi-sleep", 60000);
        const woke = next_event("acpi-wake", 120000);
        // (the kernel log is cleared each cycle: over many cycles its ring buffer wraps)
        const alarm = "dmesg -c >/dev/null; " + (by_rtc ? "echo 0 > /sys/class/rtc/rtc0/wakealarm; echo +3 > /sys/class/rtc/rtc0/wakealarm; " : "");
        serial = "";
        // (the marker is computed, so the echoed command line cannot match it)
        emulator.serial0_send(alarm + "echo mem > /sys/power/state; echo RESUMED_$((" + cycle + "*7))\n");
        assert.equal(await slept, "S3");
        assert.equal(emulator.v86.cpu.devices.acpi.sleeping, 3, "cores stopped in S3");
        if(!by_rtc)
        {
            await delay(1000);
            if(cycle === 2)
            {
                // a snapshot of the sleeping machine wakes after restore
                const state = await emulator.save_state();
                await emulator.restore_state(state);
                assert.equal(emulator.v86.cpu.devices.acpi.sleeping, 3, "restored asleep");
            }
            assert.equal(await emulator.power_button(), true);
        }
        assert.equal(await woke, by_rtc ? "rtc" : "power-button");
        await wait_serial(new RegExp("RESUMED_" + cycle * 7 + "\r?\n[\\s\\S]*~% $"), "resume " + cycle, 60000).catch(error => {
            const d = emulator.v86.cpu.get_diagnostics();
            console.log(JSON.stringify({ cpu: d.cpu, cores: d.cores, parallel: d.parallel, acpi: d.acpi }, null, 1));
            console.log("serial: " + JSON.stringify(serial.slice(-1500)));
            throw error;
        });
        const check = await command("md5sum -c /tmp/s3.md5 >/dev/null && echo RAM_INTACT=1; " +
            "echo WAKES=$(dmesg | grep -c -E '(ACPI: )?(PM: )?Waking up from system sleep state S3')");
        assert.equal(value_of(check, "RAM_INTACT"), 1, "tmpfs contents survive S3");
        assert.equal(value_of(check, "WAKES"), 1, "the kernel woke from S3");
        const after = await command("set -- $(cat /proc/uptime); echo UP=${1%.*}; echo RTC=$(date +%s)");
        assert.ok(value_of(after, "UP") >= value_of(before, "UP"), "uptime does not go backwards across S3");
        assert.ok(value_of(after, "RTC") >= value_of(before, "RTC"), "wall clock does not go backwards across S3");
        log(`S3 cycle ${cycle}: woken by ${by_rtc ? "the RTC alarm" : "the power button"}, RAM intact`);
    }
}

// S4: the guest hibernates to the swap disk and enters ACPI S4 (soft off).
// Power-on clears RAM and boots from the CD again; handing the image to the
// new kernel (/sys/power/resume, as an initramfs does) restores the old one.
if(can_hibernate && S4_CYCLES)
{
    const swap = await command("mkswap /dev/sda >/dev/null && swapon /dev/sda && echo SWAP=1");
    assert.equal(value_of(swap, "SWAP"), 1, "swap on the blank disk");
    for(let cycle = 1; cycle <= S4_CYCLES; cycle++)
    {
        const marker = 1000 + cycle;
        await command(`echo ${marker} > /tmp/s4-marker; echo platform > /sys/power/disk; echo 1 > /sys/power/pm_debug_messages; dmesg -c >/dev/null`);
        const off = next_event("acpi-power-off", 180000);
        const stopped = next_event("emulator-stopped", 180000);
        serial = "";
        emulator.serial0_send(`echo disk > /sys/power/state; echo THAWED_${cycle}=$(cat /tmp/s4-marker)\n`);
        assert.equal(await off, "S4");
        await stopped;
        log(`S4 cycle ${cycle}: hibernated, soft off (S4)`);
        // power-on clears RAM (a sentinel far above what firmware touches)
        const SENTINEL = 200 * 1024 * 1024;
        emulator.v86.cpu.mem8.set([0x5A, 0xA5, 0x5A, 0xA5], SENTINEL);
        serial = "";
        assert.equal(await emulator.power_button(), true);
        assert.deepEqual([...emulator.v86.cpu.mem8.subarray(SENTINEL, SENTINEL + 4)], [0, 0, 0, 0], "RAM cleared at power-on");
        // the new kernel finds the image through resume= and restores it
        const thawed = await wait_serial(new RegExp(`THAWED_${cycle}=\\d+\\r?\\n[\\s\\S]*~% $`), "restore " + cycle, 180000);
        assert.equal(value_of(thawed, `THAWED_${cycle}`), marker, "the shell continues in the restored kernel");
        const restored = await command("echo RESTORED=$(dmesg | grep -c 'Image restored successfully')");
        assert.equal(value_of(restored, "RESTORED"), 1, "the kernel restored the image from swap");
        log(`S4 cycle ${cycle}: powered on, image restored from disk, marker ${marker} back`);
    }
}

// Watch the PIIX reset control register: reboot=acpi writes the FADT reset value there
const reset_writes = [];
{
    const port = emulator.v86.cpu.io.ports[0xCF9];
    const write8 = port.write8;
    port.write8 = function(value) { reset_writes.push(value); return write8.call(this, value); };
}
serial = "";
emulator.serial0_send("reboot\n");
await boot();
assert.deepEqual(reset_writes, [0x06], "reset through the FADT reset register");
const after_reboot = await command("dmesg | grep -E 'ACPI: Interpreter enabled'; set -- $(cat /sys/firmware/acpi/interrupts/sci); echo SCI=$1");
assert.match(after_reboot, /ACPI: Interpreter enabled/);
assert.equal(value_of(after_reboot, "SCI"), 0, "counters start again after the reboot");
log("rebooted through the ACPI reset register, ACPI enabled again");

for(let cycle = 1; cycle <= POWER_CYCLES; cycle++)
{
    await power_off();
    log(`power cycle ${cycle}: S5, emulator stopped`);

    if(cycle === POWER_CYCLES) break;

    serial = "";
    assert.equal(await emulator.power_button(), true);
    assert.equal(emulator.is_running(), true);
    await boot();
    log(`power cycle ${cycle}: powered on and booted again`);
}

clearTimeout(overall_timeout);
console.log("ACPI guest test passed");
await emulator.destroy();
process.exit(0);
                                                                                                                                                                                                                                                                    source/v64/tests/devices/acpi_tables.js                                                             0000755 0000000 0000000 00000062262 00000000000 015267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Tests of the ACPI tables v86 generates (src/acpi_tables.js), without a guest:
// - the table-loader script is executed the way SeaBIOS does
//   (src/fw/romfile_loader.c) and the installed tables are validated
// - with ACPICA's iasl and acpiexec (env IASL/ACPIEXEC, or on PATH), the
//   tables are disassembled and recompiled and the DSDT's methods are run

import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

process.on("unhandledRejection", exn => { throw exn; });

const { create_platform } = await import("../../src/platform.js");
const { build_acpi_tables, ACPI_TABLES_FILE, ACPI_RSDP_FILE, ZONE_HIGH, ZONE_FSEG } = await import("../../src/acpi_tables.js");

const PM_BASE = 0x600;

// ---------------------------------------------------------------------------
// SeaBIOS's loader, on a sparse "physical memory"

function run_loader({ tables, rsdp, loader })
{
    const files = { [ACPI_TABLES_FILE]: tables, [ACPI_RSDP_FILE]: rsdp };
    const allocated = {};
    const zones = { [ZONE_HIGH]: 0x0FFF0000, [ZONE_FSEG]: 0x000F6C00 };
    const u32 = (bytes, o) => (bytes[o] | bytes[o + 1] << 8 | bytes[o + 2] << 16 | bytes[o + 3] << 24) >>> 0;
    const name_at = (bytes, o) => String.fromCharCode(...bytes.subarray(o, o + 56)).replace(/\0.*$/s, "");

    assert.equal(loader.length % 128, 0, "loader entries are 128 bytes");
    for(let o = 0; o < loader.length; o += 128)
    {
        const command = u32(loader, o);
        const entry = o + 4;
        if(command === 1)
        {
            const file = name_at(loader, entry);
            const align = u32(loader, entry + 56);
            const zone = loader[entry + 60];
            assert.ok(files[file], "allocate of a file that exists: " + file);
            assert.ok(!allocated[file], "allocated once: " + file);
            assert.equal(align & align - 1, 0, "power of two alignment");
            assert.ok(zones[zone] !== undefined, "known zone");
            const address = Math.ceil(zones[zone] / align) * align;
            zones[zone] = address + files[file].length;
            allocated[file] = { address, data: files[file].slice() };
        }
        else if(command === 2)
        {
            const dest = allocated[name_at(loader, entry)];
            const src = allocated[name_at(loader, entry + 56)];
            const offset = u32(loader, entry + 112);
            const size = loader[entry + 116];
            assert.ok(dest && src, "pointer between allocated files");
            assert.ok([1, 2, 4, 8].includes(size) && offset + size <= dest.data.length);
            let value = 0n;
            for(let i = 0; i < size; i++) value |= BigInt(dest.data[offset + i]) << BigInt(8 * i);
            value += BigInt(src.address);
            for(let i = 0; i < size; i++) dest.data[offset + i] = Number(value >> BigInt(8 * i) & 0xFFn);
        }
        else if(command === 3)
        {
            const file = allocated[name_at(loader, entry)];
            const offset = u32(loader, entry + 56);
            const start = u32(loader, entry + 60);
            const length = u32(loader, entry + 64);
            assert.ok(file && offset < file.data.length && start + length <= file.data.length);
            const sum = file.data.subarray(start, start + length).reduce((a, b) => a + b, 0);
            file.data[offset] = file.data[offset] - sum & 0xFF;
        }
        else
        {
            assert.fail("unexpected loader command " + command);
        }
    }

    // Guest physical memory as a lookup over the allocations
    const regions = Object.values(allocated);
    const mem = address => {
        for(const { address: base, data } of regions)
        {
            if(address >= base && address < base + data.length) return { data, offset: address - base };
        }
        assert.fail("address " + address.toString(16) + " is not in an installed table");
    };
    const read = (address, length) => { const { data, offset } = mem(address); return data.subarray(offset, offset + length); };
    return { allocated, read };
}

const le = bytes => bytes.reduceRight((v, b) => v * 256 + b, 0);
const checksum = bytes => bytes.reduce((a, b) => a + b, 0) & 0xFF;
const text = bytes => String.fromCharCode(...bytes);

/** Walk the installed tables from the RSDP, checking checksums and pointers */
function install(platform, pm_base = PM_BASE,
    listed = ["APIC", "FACP"].concat(platform.hpet ? ["HPET"] : [], platform.ecam ? ["MCFG"] : []))
{
    const built = build_acpi_tables(platform, pm_base);
    const { allocated, read } = run_loader(built);

    const rsdp = allocated[ACPI_RSDP_FILE];
    assert.equal(rsdp.address % 16, 0);
    const r = rsdp.data;
    assert.equal(text(r.subarray(0, 8)), "RSD PTR ");
    assert.equal(checksum(r.subarray(0, 20)), 0, "RSDP checksum");
    assert.equal(checksum(r.subarray(0, 36)), 0, "RSDP extended checksum");
    assert.equal(r[15], 2, "RSDP revision 2 (has an XSDT)");
    assert.equal(le(r.subarray(20, 24)), 36);

    const table_at = address => {
        const header = read(address, 36);
        const length = le(header.subarray(4, 8));
        const data = read(address, length);
        assert.equal(checksum(data), 0, text(header.subarray(0, 4)) + " checksum");
        return { signature: text(header.subarray(0, 4)), revision: header[8], data, address };
    };

    const rsdt = table_at(le(r.subarray(16, 20)));
    const xsdt = table_at(le(r.subarray(24, 32)));
    assert.equal(rsdt.signature, "RSDT");
    assert.equal(xsdt.signature, "XSDT");
    const rsdt_entries = [];
    for(let o = 36; o < rsdt.data.length; o += 4) rsdt_entries.push(le(rsdt.data.subarray(o, o + 4)));
    const xsdt_entries = [];
    for(let o = 36; o < xsdt.data.length; o += 8) xsdt_entries.push(le(xsdt.data.subarray(o, o + 8)));
    assert.deepEqual(rsdt_entries, xsdt_entries, "RSDT and XSDT list the same tables");
    assert.ok(rsdt_entries.every(a => a < 2 ** 32), "tables below 4 GiB for 32-bit OSes");

    const tables = {};
    for(const address of rsdt_entries)
    {
        const t = table_at(address);
        assert.ok(!tables[t.signature], "listed once: " + t.signature);
        tables[t.signature] = t;
    }
    assert.deepEqual(Object.keys(tables).sort(), listed);

    const fadt = tables["FACP"].data;
    const facs_address = le(fadt.subarray(36, 40));
    const dsdt_address = le(fadt.subarray(40, 44));
    assert.equal(le(fadt.subarray(132, 140)), facs_address, "X_FIRMWARE_CTRL = FIRMWARE_CTRL");
    assert.equal(le(fadt.subarray(140, 148)), dsdt_address, "X_DSDT = DSDT");
    assert.equal(facs_address % 64, 0, "FACS 64-byte aligned");
    const facs = read(facs_address, 64);
    assert.equal(text(facs.subarray(0, 4)), "FACS");
    assert.ok(le(facs.subarray(4, 8)) >= 64);
    tables["DSDT"] = table_at(dsdt_address);
    assert.equal(tables["DSDT"].signature, "DSDT");
    tables["FACS"] = { data: facs, address: facs_address };

    return { tables, built, rsdp: r };
}

const tests = [];
const test = (name, fn) => tests.push({ name, fn });

const PLATFORMS = [
    ["256 MiB, defaults", {}, 256 << 20],
    ["32 MiB, all serial and parallel ports", { uart1: true, uart2: true, uart3: true, parallel1: true }, 32 << 20],
    ["2 GiB", {}, 2 ** 31 - (1 << 17)],
    ["QEMU compatible", { qemu_compatible: true }, 256 << 20],
];

for(const [label, settings, memory] of PLATFORMS)
{
    test("loader installs consistent tables: " + label, () => {
        const platform = create_platform(settings, memory);
        const { tables } = install(platform);
        const fadt = tables["FACP"];
        const f = fadt.data;
        const u = (o, n) => le(f.subarray(o, o + n));

        assert.equal(fadt.revision, 3);
        assert.equal(f.length, 244);
        assert.equal(u(46, 2), 9, "SCI_INT");
        assert.equal(u(48, 4), 0xB2, "SMI_CMD");
        assert.deepEqual([f[52], f[53]], [0xF1, 0xF0]);
        assert.deepEqual([u(56, 4), u(64, 4), u(76, 4), u(80, 4)], [PM_BASE, PM_BASE + 4, PM_BASE + 8, 0xAFE0]);
        assert.deepEqual([f[88], f[89], f[91], f[92]], [4, 2, 4, 4], "block lengths");
        assert.equal(f[108], 0x32, "CENTURY");
        const flags = u(112, 4);
        assert.equal(flags & 1 << 4, 0, "fixed power button");
        assert.equal(flags & 1 << 8, 0, "24-bit PM timer");
        assert.ok(flags & 1 << 10, "RESET_REG_SUP");
        // RESET_REG: system I/O, 8 bits at 0xCF9, value 6
        assert.deepEqual([f[116], f[117], u(120, 8), f[128]], [1, 8, 0xCF9, 6]);
        // extended blocks agree with the legacy ones
        const gas = o => [f[o], f[o + 1], u(o + 4, 8)];
        assert.deepEqual(gas(148), [1, 32, PM_BASE]);
        assert.deepEqual(gas(172), [1, 16, PM_BASE + 4]);
        assert.deepEqual(gas(208), [1, 32, PM_BASE + 8]);
        assert.deepEqual(gas(220), [1, 32, 0xAFE0]);

        const madt = tables["APIC"].data;
        assert.equal(le(madt.subarray(36, 40)), 0xFEE00000);
        const entries = [];
        for(let o = 44; o < madt.length; o += madt[o + 1]) entries.push(madt.subarray(o, o + madt[o + 1]));
        assert.equal(entries.filter(e => e[0] === 0).length, platform.cores, "one local APIC per core");
        const ioapic = entries.find(e => e[0] === 1);
        assert.deepEqual([ioapic[2], le(ioapic.subarray(4, 8)), le(ioapic.subarray(8, 12))], [0, 0xFEC00000, 0]);
        const overrides = entries.filter(e => e[0] === 2).map(e => [e[3], le(e.subarray(4, 8)), le(e.subarray(8, 10))]);
        assert.deepEqual(overrides, [[9, 9, 0x0D], [10, 10, 0x0D], [11, 11, 0x0D]], "SCI and PCI links level/high; IRQ 5 (SB16) stays edge");

        const dsdt = Buffer.from(tables["DSDT"].data);
        assert.equal(tables["DSDT"].revision, 1, "32-bit AML integers");
        // Name (_Sx_, Package (4) {SLP_TYP, SLP_TYP, 0, 0}): S3 = 1, S4 = 2, S5 = 0
        for(const [state, slp_typ] of [["_S3_", 1], ["_S4_", 2], ["_S5_", 0]])
        {
            const at = dsdt.indexOf(state);
            // NameOp, RootChar ("\\_Sx_")
            assert.ok(at > 1 && dsdt[at - 2] === 0x08 && dsdt[at - 1] === 0x5C, state + " advertised");
            assert.equal(dsdt[at + 4], 0x12, state + " is a package");
            const element = dsdt.subarray(at + 7, at + 9);
            const value = element[0] === 0x0A ? element[1] : element[0] === 0x01 ? 1 : element[0] === 0x00 ? 0 : -1;
            assert.equal(value, slp_typ, state + " SLP_TYP");
        }
        assert.ok(dsdt.includes(Buffer.from([0x0C, 0x41, 0xD0, 0x03, 0x03])), "PNP0303 (SeaBIOS checks for it)");
        const com_ports = (dsdt.toString("latin1").match(/COM\d/g) || []).length;
        assert.equal(com_ports, platform.uarts.length, "one COM device per emulated UART");
        // Device (PCI0) {Name (_HID, PNP0A03) Name (_UID, n)}: QEMU's PC has 0
        const pci0 = dsdt.indexOf("PCI0");
        const uid = dsdt.indexOf("_UID", pci0);
        assert.ok(uid > pci0 && uid - pci0 < 32, "PCI0 _UID");
        assert.equal(dsdt[uid + 4] === 0x00 ? 0 : dsdt[uid + 4] === 0x01 ? 1 : -1, settings.qemu_compatible ? 0 : 1, "PCI0 _UID");
        // (QEMU's PC does not describe the PIC, timer, DMA, speaker and FPU)
        assert.equal(dsdt.includes("SPKR"), !settings.qemu_compatible, "legacy ISA devices");
    });
}

test("Q35: MCFG, the ICH9 PM layout in the FADT, the PCI Express root bridge, S5 only", () => {
    const platform = create_platform({ machine_type: "q35", cpu_cores: 2 }, 512 << 20);
    const { tables } = install(platform);
    const f = tables["FACP"].data;
    const u = (o, n) => le(f.subarray(o, o + n));
    assert.deepEqual([f[52], f[53]], [0x02, 0x03], "ICH9 ACPI_ENABLE/ACPI_DISABLE");
    assert.deepEqual([u(56, 4), u(64, 4), u(76, 4), u(80, 4)], [PM_BASE, PM_BASE + 4, PM_BASE + 8, PM_BASE + 0x20], "GPE0 inside the PM block");
    assert.deepEqual([f[88], f[89], f[91], f[92]], [4, 2, 4, 16], "block lengths");
    assert.deepEqual([f[220], f[221], le(f.subarray(224, 232))], [1, 128, PM_BASE + 0x20], "X_GPE0_BLK");

    const m = tables["MCFG"].data;
    assert.equal(m.length, 60);
    assert.deepEqual([le(m.subarray(44, 52)), le(m.subarray(52, 54)), m[54], m[55]], [0xB0000000, 0, 0, 255], "ECAM, segment 0, buses 0-255");

    const dsdt = Buffer.from(tables["DSDT"].data);
    const latin = dsdt.toString("latin1");
    assert.ok(dsdt.includes(Buffer.from([0x0C, 0x41, 0xD0, 0x0A, 0x08])), "PNP0A08");
    assert.ok(dsdt.includes(Buffer.from([0x0C, 0x41, 0xD0, 0x0A, 0x03])), "PNP0A03 (_CID)");
    assert.ok(dsdt.includes(Buffer.from([0x0C, 0x41, 0xD0, 0x03, 0x03])), "PNP0303 (SeaBIOS checks for it)");
    assert.ok(latin.includes("_S5_") && !latin.includes("_S3_") && !latin.includes("_S4_"), "S5 only");
    for(const name of ["PICF", "_PIC", "PRTP", "PRTA", "GSIA", "GSIH", "LNKE", "LNKH", "DRAC"]) assert.ok(latin.includes(name), name);
    // Memory32Fixed descriptors: the ECAM window (DRAC) and the RCBA block (MBRS)
    const memory32 = (base, length) => Buffer.from([0x86, 9, 0, 1, ...[base, length].flatMap(v => [v & 0xFF, v >> 8 & 0xFF, v >> 16 & 0xFF, v >>> 24])]);
    assert.ok(dsdt.includes(memory32(0xB0000000, 0x10000000)), "ECAM reserved");
    assert.ok(dsdt.includes(memory32(0xFED1C000, 0x4000)), "RCBA reserved");
    // the root bridge's memory window starts above the ECAM window
    // (DWord memory: flags, granularity, minimum, maximum)
    const window = Buffer.from([0x0C, 0x03, 0, 0, 0, 0, 0, 0, 0, 0xC0, 0xFF, 0xFF, 0xBF, 0xFE]);
    assert.ok(dsdt.includes(window), "PCI memory window 0xC0000000-0xFEBFFFFF");
});

test("Q35 with hpet: the HPET table, a PNP0103 device with the timer block's memory", () => {
    const platform = create_platform({ machine_type: "q35", hpet: true }, 256 << 20);
    const { tables } = install(platform);
    const h = tables["HPET"].data;
    assert.equal(h.length, 56);
    assert.equal(le(h.subarray(36, 40)), 0x8086A201, "event timer block ID");
    assert.deepEqual([h[40], le(h.subarray(44, 52))], [0, 0xFED00000], "system memory at 0xFED00000");
    const dsdt = Buffer.from(tables["DSDT"].data);
    assert.ok(dsdt.includes(Buffer.from([0x0C, 0x41, 0xD0, 0x01, 0x03])), "PNP0103");
    assert.ok(dsdt.includes(Buffer.from([0x86, 9, 0, 1, 0x00, 0x00, 0xD0, 0xFE, 0x00, 0x04, 0x00, 0x00])), "Memory32Fixed(0xFED00000, 0x400)");
    assert.ok(!install(create_platform({ machine_type: "q35" }, 256 << 20)).tables["HPET"], "no table without hpet");
});

test("Q35: invalid machine types and acpi: false are rejected", () => {
    assert.throws(() => create_platform({ machine_type: "pc" }, 256 << 20), /machine_type/);
    assert.throws(() => create_platform({ machine_type: "q35", acpi: false }, 256 << 20), /requires ACPI/);
    assert.equal(create_platform({ machine_type: "q35" }, 256 << 20).acpi, true, "on by default");
    assert.equal(create_platform({}, 256 << 20).machine, "i440fx");
    assert.throws(() => create_platform({ hpet: true }, 256 << 20), /hpet requires machine_type "q35"/);
    assert.throws(() => create_platform({ pcie_root_ports: 1 }, 256 << 20), /pcie_root_ports requires machine_type "q35"/);
    assert.throws(() => create_platform({ machine_type: "q35", pcie_root_ports: 7 }, 256 << 20), /from 0 to 6/);
    assert.deepEqual(create_platform({ machine_type: "q35", pcie_root_ports: 2 }, 256 << 20).reserved_pci_slots, [0x00, 0x1F, 0x1C],
        "root ports reserve device 28");
});

test("the table sizes do not depend on the PM base (tables are regenerated when read)", () => {
    const platform = create_platform({}, 256 << 20);
    const a = build_acpi_tables(platform, 0x600);
    const b = build_acpi_tables(platform, 0xB000);
    assert.equal(a.tables.length, b.tables.length);
    assert.deepEqual(a.loader, b.loader);
    assert.deepEqual(a.rsdp, b.rsdp);
    const { tables } = install(platform, 0xB000);
    assert.equal(le(tables["FACP"].data.subarray(56, 60)), 0xB000);
});

test("platform description rejects overlapping I/O ranges", async () => {
    const { check_platform } = await import("../../src/platform.js");
    const platform = create_platform({}, 256 << 20);
    assert.throws(() => check_platform(platform, 0x3C0), /conflict.*acpi-pm|conflict.*fdc/i);
    check_platform(platform, 0x600);
});

// ---------------------------------------------------------------------------
// ACPICA

function find_tool(name, env)
{
    if(process.env[env]) return process.env[env];
    try
    {
        return execFileSync("sh", ["-c", "command -v " + name], { encoding: "utf8" }).trim() || null;
    }
    catch(e)
    {
        return null;
    }
}

const IASL = find_tool("iasl", "IASL");
const ACPIEXEC = find_tool("acpiexec", "ACPIEXEC");
const skipped = [];

function write_installed_tables(dir, settings = { uart1: true })
{
    const platform = create_platform(settings, 256 << 20);
    const { tables } = install(platform);
    for(const [name, { data }] of Object.entries(tables))
    {
        fs.writeFileSync(path.join(dir, name.toLowerCase() + ".dat"), data);
    }
}

for(const [label, settings, names] of IASL ? [["", undefined, ["dsdt", "facp", "apic", "facs"]],
    [" (Q35)", { machine_type: "q35" }, ["dsdt", "facp", "apic", "facs", "mcfg"]],
    [" (Q35 with the HPET)", { machine_type: "q35", hpet: true }, ["dsdt", "facp", "apic", "facs", "mcfg", "hpet"]]] : [])
{
    test("iasl disassembles every table and recompiles the DSDT without errors" + label, () => {
        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "v86-acpi-"));
        write_installed_tables(dir, settings);
        const iasl = args => {
            const { status, stdout, stderr } = spawnSync(IASL, args, { cwd: dir, encoding: "utf8" });
            return { status, out: stdout + stderr };
        };
        for(const name of names)
        {
            const { status, out } = iasl(["-d", name + ".dat"]);
            assert.equal(status, 0, out);
            assert.doesNotMatch(out, /Error|Warning/, name + ": " + out);
        }
        // -oa: no optimizations, so the AML can be compared byte for byte
        const { status, out } = iasl(["-oa", "-p", "recompiled", "dsdt.dsl"]);
        assert.equal(status, 0, out);
        assert.match(out, /Compilation successful\. 0 Errors/, out);
        // The only accepted warning: Processor() instead of Device(ACPI0007), for Windows 2000/XP
        const warnings = out.match(/^Warning +\d+/gm) || [];
        assert.deepEqual(warnings.map(w => w.split(/ +/)[1]), ["3168"], out);
        // the recompiled AML is the same code (only the header's compiler id differs)
        const original = fs.readFileSync(path.join(dir, "dsdt.dat")).subarray(36);
        const recompiled = fs.readFileSync(path.join(dir, "recompiled.aml")).subarray(36);
        assert.ok(original.equals(recompiled), "iasl compiles the disassembly back to the same AML");
        fs.rmSync(dir, { recursive: true });
    });
}
if(!IASL)
{
    skipped.push("iasl (set IASL=/path/to/iasl)");
}

if(ACPIEXEC)
{
    test("acpiexec runs the interrupt link methods and the sleeping state packages", () => {
        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "v86-acpi-"));
        write_installed_tables(dir);
        const commands = [
            "evaluate \\_SB.LNKA._STA",
            "evaluate \\_SB.LNKA._CRS",
            "evaluate \\_SB.LNKA._SRS (89 06 00 09 01 0B 00 00 00 79 00)",
            "evaluate \\_SB.LNKA._CRS",
            "evaluate \\_SB.LNKA._DIS",
            "evaluate \\_SB.LNKA._STA",
            "evaluate \\_SB.LNKA._PRS",
            "evaluate \\_S3",
            "evaluate \\_S4",
            "evaluate \\_S5",
            "evaluate \\_SB.PCI0.ISA.KBD._HID",
        ].join("; ");
        let out;
        try
        {
            out = execFileSync(ACPIEXEC, ["-b", commands, "dsdt.dat"], { cwd: dir, encoding: "utf8", stdio: "pipe" });
        }
        catch(e)
        {
            out = e.stdout; // acpiexec reports its own leak tracking as an error
        }
        const results = out.split(/Evaluating /).slice(1).map(block => {
            const value = block.match(/\[(Integer|Buffer)\][^\n]*/g) || [];
            return value.join(" | ");
        });
        assert.deepEqual(results, [
            "[Integer] = 000000000000000B",
            "[Buffer] Length 0B =     0000: 89 06 00 09 01 00 00 00 00 79 00                 // .........y.",
            "",
            "[Buffer] Length 0B =     0000: 89 06 00 09 01 0B 00 00 00 79 00                 // .........y.",
            "",
            "[Integer] = 0000000000000009",
            "[Buffer] Length 0F =     0000: 89 0A 00 09 02 0A 00 00 00 0B 00 00 00 79 00     // .............y.",
            "[Integer] = 0000000000000001 | [Integer] = 0000000000000001 | [Integer] = 0000000000000000 | [Integer] = 0000000000000000",
            "[Integer] = 0000000000000002 | [Integer] = 0000000000000002 | [Integer] = 0000000000000000 | [Integer] = 0000000000000000",
            "[Integer] = 0000000000000000 | [Integer] = 0000000000000000 | [Integer] = 0000000000000000 | [Integer] = 0000000000000000",
            "[Integer] = 000000000303D041",
        ]);
        assert.doesNotMatch(out, /ACPI Error: (?!\d+ \(0x[0-9a-f]+\) Outstanding cache allocations)/, out);
        fs.rmSync(dir, { recursive: true });
    });
}
else
{
    skipped.push("acpiexec (set ACPIEXEC=/path/to/acpiexec)");
}

if(ACPIEXEC)
{
    // (the 128-entry _PRT packages don't fit the debugger's output buffer:
    // the routing itself is checked by the guests of tests/devices/q35_guest.js)
    test("acpiexec (Q35): _PIC records the mode, GSI links report 16-23, PIRQ links work", () => {
        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "v86-acpi-"));
        write_installed_tables(dir, { machine_type: "q35" });
        const commands = [
            "evaluate \\PICF",
            "evaluate \\_PIC 1",
            "evaluate \\PICF",
            "evaluate \\_SB.GSIA._CRS",
            "evaluate \\_SB.GSIH._CRS",
            "evaluate \\_SB.GSIE._STA",
            "evaluate \\_SB.LNKE._STA",
            "evaluate \\_SB.LNKE._SRS (89 06 00 09 01 0A 00 00 00 79 00)",
            "evaluate \\_SB.LNKE._CRS",
            "evaluate \\_S5",
        ].join("; ");
        let out;
        try
        {
            out = execFileSync(ACPIEXEC, ["-b", commands, "dsdt.dat"], { cwd: dir, encoding: "utf8", stdio: "pipe" });
        }
        catch(e)
        {
            out = e.stdout;
        }
        const blocks = out.split(/Evaluating /).slice(1);
        assert.equal(blocks.length, 10, out);
        assert.match(blocks[0], /\[Integer\] = 0000000000000000/, "PIC mode until _PIC");
        assert.match(blocks[2], /\[Integer\] = 0000000000000001/, "APIC mode after _PIC(1)");
        assert.match(blocks[3], /89 06 00 09 01 10 00 00 00 79 00/, "GSIA: IRQ 16, level, active high, shared");
        assert.match(blocks[4], /89 06 00 09 01 17 00 00 00 79 00/, "GSIH: IRQ 23");
        assert.match(blocks[5], /000000000000000B/);
        assert.match(blocks[8], /89 06 00 09 01 0A 00 00 00 79 00/, "LNKE routed to IRQ 10");
        assert.match(blocks[9], /\[Integer\] = 0000000000000000/);
        assert.doesNotMatch(out, /ACPI Error: (?!\d+ \(0x[0-9a-f]+\) Outstanding cache allocations)/, out);
        fs.rmSync(dir, { recursive: true });
    });
}

if(ACPIEXEC)
{
    test("acpiexec (Q35): _OSC grants native PCI Express hot plug, SHPC, PME, AER and the PCI Express capability", () => {
        const dir = fs.mkdtempSync(path.join(os.tmpdir(), "v86-acpi-"));
        write_installed_tables(dir, { machine_type: "q35", pcie_root_ports: 2 });
        const uuid = "(5B 4D DB 33 F7 1F 1C 40 96 57 74 41 C0 3D D7 66)";
        const commands = [
            // (support: everything; control asked: hot plug, SHPC, PME, AER, capability, LTR)
            "evaluate \\_SB.PCI0._OSC " + uuid + " 1 3 (00 00 00 00 1F 01 00 00 3F 00 00 00)",
            "evaluate \\_SB.PCI0._OSC " + uuid + " 1 3 (01 00 00 00 1F 01 00 00 1D 00 00 00)",
            "evaluate \\_SB.PCI0._OSC (00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF) 1 3 (00 00 00 00 00 00 00 00 1F 00 00 00)",
            "evaluate \\_SB.PCI0._OSC " + uuid + " 2 3 (00 00 00 00 00 00 00 00 1F 00 00 00)",
        ].join("; ");
        let out;
        try
        {
            out = execFileSync(ACPIEXEC, ["-b", commands, "dsdt.dat"], { cwd: dir, encoding: "utf8", stdio: "pipe" });
        }
        catch(e)
        {
            out = e.stdout;
        }
        const blocks = out.split(/Evaluating /).slice(1);
        assert.equal(blocks.length, 4, out);
        assert.match(blocks[0], /10 00 00 00 1F 01 00 00 1F 00 00 00/, "granted 0x1F, LTR masked (and so reported)");
        assert.match(blocks[1], /01 00 00 00 1F 01 00 00 1D 00 00 00/, "a query of a subset: granted as asked");
        assert.match(blocks[2], /04 00 00 00 00 00 00 00 1F 00 00 00/, "another UUID: unrecognized");
        assert.match(blocks[3], /08 00 00 00 00 00 00 00 1F 00 00 00/, "revision 2: unrecognized revision");
        assert.doesNotMatch(out, /ACPI Error: (?!\d+ \(0x[0-9a-f]+\) Outstanding cache allocations)/, out);
        fs.rmSync(dir, { recursive: true });
    });
}

let failed = 0;
for(const { name, fn } of tests)
{
    try
    {
        await fn();
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("not ok - " + name);
        console.log(e);
    }
}
for(const tool of skipped)
{
    console.log("SKIP - not verified with " + tool);
}

console.log(`${tests.length - failed}/${tests.length} ACPI table tests passed` + (skipped.length ? `, ${skipped.length} ACPICA check(s) skipped` : ""));
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                              source/v64/tests/devices/ahci.js                                                                    0000755 0000000 0000000 00000123046 00000000000 013723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The AHCI controller of the Q35 machine, driven through its registers and
// command structures in guest memory; no guest code runs. Covers the
// behaviour SeaBIOS and Linux depend on (docs/ahci.md):
// presence and signatures, the initial D2H FIS, PIO, DMA and ATAPI commands,
// PRDTs, error completion and recovery, native command queuing and its error
// log, link power management, interrupts, resets, hot plug and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// hda: 8 MiB with a pattern; hdb: 3 TiB, never allocated (reads return
// their byte offset); the CD: 2 MiB, each sector filled with its number
const HDA_SIZE = 8 << 20;
const hda = new Uint8Array(HDA_SIZE);
for(let i = 0; i < HDA_SIZE; i++) hda[i] = i * 7 + (i >> 9) & 0xFF;
const hda_original = hda.slice();

const HDB_SECTORS = 6 * 2 ** 30;
const hdb_reads = [];
// (a class: state images take no plain objects)
class SparseDisk
{
    constructor(byte_length) { this.byteLength = byte_length; }
    load() { this.onload?.({}); }
    get(start, length, done)
    {
        hdb_reads.push(start);
        const data = new Uint8Array(length);
        for(let s = 0; s < length; s += 512) new DataView(data.buffer).setFloat64(s, start + s, true);
        done(data);
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done) { done(); }
    get_buffer(done) { done(undefined); }
    get_state() { return []; }
    set_state() {}
}
const hdb = new SparseDisk(HDB_SECTORS * 512);

const CD_SIZE = 2 << 20;
const cd = new Uint8Array(CD_SIZE);
for(let s = 0; s < CD_SIZE / 2048; s++) cd.fill(s & 0xFF, s * 2048, s * 2048 + 2048);

class CDImage
{
    constructor() { this.byteLength = CD_SIZE; }
    get(start, length, done) { done(cd.slice(start, start + length)); }
    set(start, data, done) { done(); }
    get_buffer(done) { done(undefined); }
    get_state() { return []; }
    set_state() {}
}

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    memory_size: 64 * 1024 * 1024,
    // the top 16 MiB of RAM at 4 GiB: DMA above 4 GiB
    high_memory_size: 16 * 1024 * 1024,
    hda: { buffer: hda.buffer },
    hdb,
    cdrom: { buffer: cd.buffer },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const AHCI = 0x1F << 3 | 2;
const ABAR = 0xC0000000;

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

// --- helpers ---------------------------------------------------------------

const r32 = offset => cpu.mmap_read32(ABAR + offset) >>> 0;
const w32 = (offset, value) => cpu.mmap_write32(ABAR + offset, value | 0);
const pr = (port, reg) => r32(0x100 + port * 0x80 + reg);
const pw = (port, reg, value) => w32(0x100 + port * 0x80 + reg, value);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };

const PX = { CLB: 0x00, FB: 0x08, IS: 0x10, IE: 0x14, CMD: 0x18, TFD: 0x20, SIG: 0x24, SSTS: 0x28, SCTL: 0x2C, SERR: 0x30, SACT: 0x34, CI: 0x38 };
const ST = 1, FRE = 1 << 4, CR = 1 << 15, FR = 1 << 14;
const DHRS = 1, PSS = 2, OFS = 1 << 24, TFES = 1 << 30;
const PCS = 1 << 6, PRCS = 1 << 22, DIAG_N = 1 << 16, DIAG_X = 1 << 26, HPCP = 1 << 18;

/** Per port: command list, received FISes, command tables, data */
const clb = port => 0x200000 + port * 0x10000;
const fb = port => clb(port) + 0x400;
const ctba = (port, slot) => clb(port) + 0x1000 + slot * 0x100;
const DATA = 0x400000;

function program_pci(command = 0x0006)
{
    pci.config_write(AHCI, 0x24, 4, ABAR);
    pci.config_write(AHCI, 0x04, 2, command);
}

function start_port(port)
{
    pw(port, PX.CMD, 0);
    pw(port, PX.CLB, clb(port));
    pw(port, PX.FB, fb(port));
    mem.fill(0, clb(port), clb(port) + 0x10000);
    pw(port, PX.CMD, FRE);
    pw(port, PX.IS, -1);
    pw(port, PX.SERR, -1);
    pw(port, PX.CMD, FRE | ST);
}

/**
 * Build a command in a slot and issue it
 * @param {number} port
 * @param {number} slot
 * @param {{command: number, features?: number, lba?: number, count?: number, device?: number,
 *          prdt?: Array<[number, number]>, write?: boolean, atapi?: Array<number>, control?: number,
 *          queued?: boolean}} c
 */
function issue(port, slot, c)
{
    const table = ctba(port, slot);
    mem.fill(0, table, table + 0x100);
    const lba = c.lba || 0, count = c.count || 0, features = c.features || 0;
    const fis = c.control !== undefined ?
        [0x27, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, c.control] :
        [0x27, 0x80, c.command, features & 0xFF,
            lba & 0xFF, lba >> 8 & 0xFF, lba >> 16 & 0xFF, c.device === undefined ? 0x40 : c.device,
            Math.floor(lba / 2 ** 24) & 0xFF, Math.floor(lba / 2 ** 32) & 0xFF, Math.floor(lba / 2 ** 40) & 0xFF, features >> 8,
            count & 0xFF, count >> 8, 0, 0];
    mem.set(fis, table);
    if(c.atapi) mem.set(c.atapi, table + 0x40);
    const prdt = c.prdt || [];
    prdt.forEach(([address, length], i) => {
        put32(table + 0x80 + i * 16, address);
        put32(table + 0x80 + i * 16 + 12, length - 1 | (c.prd_interrupt ? 1 << 31 : 0));
    });
    const header = clb(port) + slot * 32;
    put32(header, 5 | (c.atapi ? 1 << 5 : 0) | (c.write ? 1 << 6 : 0) | prdt.length << 16);
    put32(header + 4, 0xDEADBEEF); // PRDBC: must be rewritten
    put32(header + 8, table);
    pw(port, PX.IS, -1);
    if(c.queued) pw(port, PX.SACT, 1 << slot);
    pw(port, PX.CI, 1 << slot);
}

/**
 * READ/WRITE FPDMA QUEUED: the sector count in the features fields, the tag
 * (the slot, as AHCI wants it) in bits 7:3 of the sector count
 */
const ncq = (port, slot, write, lba, count, prdt) =>
    issue(port, slot, { command: write ? 0x61 : 0x60, features: count, lba, count: slot << 3, prdt, write, queued: true });

const prdbc = (port, slot) => u32(clb(port) + slot * 32 + 4);
const sdb = port => mem.subarray(fb(port) + 0x58, fb(port) + 0x60);
const SDBS = 1 << 3;
const d2h = port => mem.subarray(fb(port) + 0x40, fb(port) + 0x54);
const pio_setup = port => mem.subarray(fb(port) + 0x20, fb(port) + 0x34);
const words = (address, n) => Array.from({ length: n }, (_, i) => mem[address + 2 * i] | mem[address + 2 * i + 1] << 8);

// --- tests -----------------------------------------------------------------

program_pci();

test("generic host control: CAP, PI, VS, GHC", () => {
    const cap = r32(0x00);
    assert.equal(cap & 0x1F, 5, "six ports");
    assert.equal(cap >> 8 & 0x1F, 31, "32 command slots");
    assert.ok(cap & 1 << 18, "AHCI only (SAM)");
    assert.equal(cap >> 20 & 0xF, 1, "Gen 1");
    assert.ok(cap & 1 << 31, "64-bit addressing");
    assert.equal(r32(0x0C), 0x3F, "ports implemented");
    assert.equal(r32(0x10), 0x00010000, "AHCI 1.0");
    assert.equal(r32(0x04) >>> 31, 1, "AE reads as one");
    w32(0x04, 0);
    assert.equal(r32(0x04) >>> 31, 1, "AE stays set");
});

test("ports: link up with a device, nothing without; signature after FIS reception starts", () => {
    assert.equal(pr(0, PX.SSTS), 0x113, "hda: present, Gen 1, active");
    assert.equal(pr(1, PX.SSTS), 0x113, "hdb");
    assert.equal(pr(2, PX.SSTS), 0x113, "the CD drive");
    for(const port of [3, 4, 5]) assert.equal(pr(port, PX.SSTS), 0, "port " + port + " empty");
    assert.equal(pr(0, PX.TFD), 0x7F, "no D2H FIS before FRE");
    assert.equal(pr(0, PX.SIG), 0xFFFFFFFF);
    assert.equal(pr(0, PX.CMD) & 6, 6, "SUD and POD read as one");

    pw(0, PX.CLB, clb(0));
    pw(0, PX.FB, fb(0));
    pw(0, PX.CMD, FRE);
    assert.equal(pr(0, PX.CMD) & FR, FR, "FR follows FRE");
    assert.equal(pr(0, PX.SIG), 0x00000101, "ATA signature");
    assert.equal(pr(0, PX.TFD) & 0xFF, 0x50, "ready, no BSY/DRQ (SeaBIOS waits for this)");
    assert.equal(d2h(0)[0], 0x34, "the D2H FIS was posted");
    assert.ok(pr(0, PX.IS) & DHRS);

    pw(2, PX.CLB, clb(2));
    pw(2, PX.FB, fb(2));
    pw(2, PX.CMD, FRE);
    assert.equal(pr(2, PX.SIG), 0xEB140101, "ATAPI signature");
    assert.equal(pr(2, PX.TFD) & 0x88, 0);
});

test("IDENTIFY DEVICE: PIO data in, PIO setup FIS with E_Status, SATA words, PRDBC", () => {
    start_port(0);
    mem.fill(0xEE, DATA, DATA + 1024);
    issue(0, 3, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.CI), 0, "completed");
    const is = pr(0, PX.IS);
    assert.ok(is & PSS, "PSS (the PIO setup FIS has the interrupt bit)");
    assert.ok(is & DHRS);
    assert.equal(is & TFES, 0);
    const ps = pio_setup(0);
    assert.equal(ps[0], 0x5F);
    assert.equal(ps[1] & 0x60, 0x60, "interrupt bit, device to host");
    assert.equal(ps[2] & 0xC9, 0x48, "status during the block: DRDY|DRQ, no BSY/ERR (SeaBIOS reads it)");
    assert.equal(ps[15] & 0xC9, 0x40, "E_Status: DRDY, no DRQ (Linux reads it)");
    assert.equal(ps[16] | ps[17] << 8, 512, "transfer count");
    assert.equal(prdbc(0, 3), 512);
    const id = words(DATA, 256);
    assert.equal(id[76] & 2, 2, "word 76: Gen 1");
    assert.equal(id[80], 0x0070, "word 80: ATA-4 to -6 (Linux: SATA)");
    assert.equal(id[93], 0, "word 93: no PATA cable detection");
    assert.equal(id[60] | id[61] << 16, HDA_SIZE / 512);
    assert.equal(mem[DATA + 512], 0xEE, "nothing beyond the PRDT");
    assert.equal(pr(0, PX.TFD) & 0xFF, 0x50);
});

test("IDENTIFY PACKET DEVICE on a disk: error with DHRS and TFES, slot kept, list halted until ST is cleared", () => {
    start_port(0);
    issue(0, 0, { command: 0xA1, prdt: [[DATA, 512]] });
    const is = pr(0, PX.IS);
    assert.ok(is & DHRS, "DHRS: SeaBIOS 1.16.2 only sees DHRS and PSS");
    assert.ok(is & TFES);
    assert.equal(d2h(0)[2] & 0x01, 1, "ERR in the D2H FIS");
    assert.equal(d2h(0)[3], 0x04, "ABRT");
    assert.equal(pr(0, PX.TFD), 0x0441, "PxTFD: error 04, status 41");
    assert.equal(pr(0, PX.CI), 1, "the failed slot stays issued");

    // further commands wait
    issue(0, 1, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.CI), 3);

    // SeaBIOS's recovery: clear ST, wait for CR, clear SERR and IS, set ST
    pw(0, PX.CMD, FRE);
    assert.equal(pr(0, PX.CMD) & CR, 0, "CR clears");
    assert.equal(pr(0, PX.CI), 0, "clearing ST clears PxCI");
    pw(0, PX.SERR, pr(0, PX.SERR));
    pw(0, PX.IS, pr(0, PX.IS));
    assert.equal(pr(0, PX.TFD) & 0x88, 0, "no BSY/DRQ: no COMRESET needed");
    pw(0, PX.CMD, FRE | ST);
    issue(0, 1, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.CI), 0, "works again");
    assert.equal(pr(0, PX.IS) & TFES, 0);
});

test("SET FEATURES with W=1 and a bogus PRDT (bsize 0) moves no data", () => {
    start_port(0);
    const ivt = mem.slice(0, 0x400);
    mem.fill(0x5A, 0, 0x400);
    issue(0, 0, { command: 0xEF, features: 0x03, count: 0x46, write: true, prdt: [[0, 0x400000]], prd_interrupt: true });
    assert.equal(pr(0, PX.CI), 0);
    assert.ok(mem.subarray(0, 0x400).every(b => b === 0x5A), "the memory at the PRDT's address 0 is untouched");
    assert.equal(prdbc(0, 0), 0);
    mem.set(ivt, 0);
});

test("READ DMA EXT over several PRDT entries, LBA48 beyond 2^32 sectors (hdb)", () => {
    start_port(0);
    issue(0, 5, { command: 0x25, lba: 100, count: 3, prdt: [[DATA, 1000], [DATA + 0x2000, 24], [DATA + 0x3000, 512]] });
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(pr(0, PX.IS) & (TFES | DHRS), DHRS);
    const expect = hda.subarray(100 * 512, 103 * 512);
    assert.deepEqual(mem.subarray(DATA, DATA + 1000), expect.subarray(0, 1000));
    assert.deepEqual(mem.subarray(DATA + 0x2000, DATA + 0x2000 + 24), expect.subarray(1000, 1024));
    assert.deepEqual(mem.subarray(DATA + 0x3000, DATA + 0x3200), expect.subarray(1024, 1536));
    assert.equal(prdbc(0, 5), 1536);

    start_port(1);
    for(const lba of [0x1_2345_6789, HDB_SECTORS - 1])
    {
        hdb_reads.length = 0;
        issue(1, 0, { command: 0x25, lba, count: 1, prdt: [[DATA, 512]] });
        assert.equal(pr(1, PX.CI), 0);
        assert.equal(new DataView(mem.buffer, mem.byteOffset + DATA, 8).getFloat64(0, true), lba * 512);
        assert.deepEqual(hdb_reads, [lba * 512]);
    }
});

test("WRITE DMA, read back; FLUSH CACHE EXT; PIO WRITE SECTORS", () => {
    start_port(0);
    for(let i = 0; i < 1024; i++) mem[DATA + i] = 255 - (i & 0xFF);
    issue(0, 0, { command: 0x35, lba: 2000, count: 2, write: true, prdt: [[DATA, 1024]] });
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(prdbc(0, 0), 1024);
    assert.ok(hda.subarray(2000 * 512, 2002 * 512).every((b, i) => b === 255 - (i & 0xFF)), "on the disk");

    issue(0, 1, { command: 0xEA });
    assert.equal(pr(0, PX.CI), 0, "flush completes");

    mem.fill(0x77, DATA + 0x8000, DATA + 0x8200);
    issue(0, 2, { command: 0x30, lba: 10, count: 1, write: true, prdt: [[DATA + 0x8000, 512]] });
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(pr(0, PX.IS) & PSS, 0, "the first PIO-out block has no interrupt bit");
    assert.ok(hda.subarray(5120, 5632).every(b => b === 0x77));

    hda.set(hda_original);
});

test("reads beyond the end: IDNF error", () => {
    start_port(0);
    issue(0, 0, { command: 0x25, lba: HDA_SIZE / 512 - 1, count: 2, prdt: [[DATA, 1024]] });
    assert.equal(pr(0, PX.TFD), 0x1041, "IDNF, DRDY|ERR (not 0xFF, which reads as BSY)");
    assert.ok(pr(0, PX.IS) & TFES);
});

test("a PRDT shorter than the transfer: error and overflow, no memory beyond it", () => {
    start_port(0);
    mem.fill(0x33, DATA, DATA + 1024);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 256]] });
    assert.ok(pr(0, PX.IS) & TFES);
    assert.ok(pr(0, PX.IS) & OFS);
    assert.equal(mem[DATA + 300], 0x33);
    issue(0, 0, { command: 0x25, lba: 0, count: 2, prdt: [[DATA, 512]] });
});

test("64-bit addressing: command list, received FISes, command table and data above 4 GiB", () => {
    const HIGH = 0x1_0000_0000;
    pw(0, PX.CMD, 0);
    pw(0, PX.CLB, 0x10000);
    pw(0, 0x04, 1);              // CLBU: 4 GiB + 64 KiB
    pw(0, PX.FB, 0x11000);
    pw(0, 0x0C, 1);              // FBU
    pw(0, PX.CMD, FRE);
    pw(0, PX.IS, -1);
    pw(0, PX.CMD, FRE | ST);
    const list = HIGH + 0x10000, received = HIGH + 0x11000, table = HIGH + 0x12000, data = HIGH + 0x20000;
    const put = (address, bytes) => cpu.write_blob_physical(Uint8Array.from(bytes), address);
    const dword = v => [v & 0xFF, v >> 8 & 0xFF, v >> 16 & 0xFF, v >>> 24];
    put(table, [0x27, 0x80, 0x25, 0, 33, 0, 0, 0x40, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]);
    // PRD: DBA/DBAU above 4 GiB, 1024 bytes
    put(table + 0x80, [...dword(data & 0xFFFFFFFF), ...dword(1), 0, 0, 0, 0, ...dword(1023)]);
    // header: CFL 5, PRDTL 1, CTBA/CTBAU
    put(list, [...dword(5 | 1 << 16), 0, 0, 0, 0, ...dword(table & 0xFFFFFFFF), ...dword(1)]);
    pw(0, PX.CI, 1);
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(pr(0, PX.IS) & TFES, 0);
    assert.deepEqual(cpu.read_blob_physical(data, 1024), hda.subarray(33 * 512, 35 * 512), "data above 4 GiB");
    assert.equal(cpu.read_blob_physical(received + 0x40, 1)[0], 0x34, "D2H FIS above 4 GiB");
    assert.deepEqual(Array.from(cpu.read_blob_physical(list + 4, 4)), dword(1024), "PRDBC");

    // beyond the 36-bit bus: the transfer fails, nothing is written
    put(table + 0x80, [...dword(0), ...dword(0x10), 0, 0, 0, 0, ...dword(1023)]);
    pw(0, PX.IS, -1);
    pw(0, PX.CI, 1);
    assert.ok(pr(0, PX.IS) & TFES, "error");
    pw(0, PX.CMD, FRE);
    pw(0, 0x04, 0);
    pw(0, 0x0C, 0);
});

test("ATAPI: IDENTIFY PACKET, TEST UNIT READY with a bogus PRDT, INQUIRY and READ(10) by DMA", () => {
    start_port(2);
    issue(2, 0, { command: 0xA1, prdt: [[DATA, 512]] });
    assert.equal(pr(2, PX.CI), 0);
    assert.ok(pr(2, PX.IS) & PSS);
    const ps = pio_setup(2);
    assert.equal(ps[2] & 0x41, 0x40, "DRDY (SeaBIOS's success condition holds for ATAPI too)");
    assert.equal(words(DATA, 1)[0] >> 8 & 0x1F, 5, "CD-ROM");

    // SeaBIOS: features = DMA for every packet, buffer NULL and bsize 0 for TUR
    issue(2, 0, { command: 0xA0, features: 1, lba: 0, prdt: [[0, 0x400000]], atapi: [0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] });
    assert.equal(pr(2, PX.CI), 0, "TEST UNIT READY succeeds");
    assert.equal(pr(2, PX.IS) & (TFES | PSS), 0, "no PIO setup interrupt for the command packet");

    issue(2, 1, { command: 0xA0, features: 1, prdt: [[DATA, 36]], atapi: [0x12, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0] });
    assert.equal(pr(2, PX.CI), 0);
    assert.equal(mem[DATA], 0x05, "INQUIRY: CD-ROM");
    assert.equal(prdbc(2, 1), 36);

    issue(2, 2, { command: 0xA0, features: 1, prdt: [[DATA, 4096]], atapi: [0x28, 0, 0, 0, 0, 7, 0, 0, 2, 0, 0, 0] });
    assert.equal(pr(2, PX.CI), 0);
    assert.ok(mem.subarray(DATA, DATA + 2048).every(b => b === 7) && mem.subarray(DATA + 2048, DATA + 4096).every(b => b === 8), "sectors 7 and 8");
    assert.equal(prdbc(2, 2), 4096);
});

test("ATAPI PIO READ(10) in byte-count-limited blocks", () => {
    start_port(2);
    // byte count limit 2048 in LBA mid/high: two DRQ blocks of one sector
    issue(2, 0, { command: 0xA0, features: 0, lba: 2048 << 8, prdt: [[DATA, 4096]], atapi: [0x28, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 0] });
    assert.equal(pr(2, PX.CI), 0);
    assert.ok(mem.subarray(DATA, DATA + 2048).every(b => b === 3) && mem.subarray(DATA + 2048, DATA + 4096).every(b => b === 4));
    assert.equal(prdbc(2, 0), 4096);
    assert.ok(pr(2, PX.IS) & PSS);
});

test("ATAPI media change: eject -> NOT READY; insert -> NOT READY, UNIT ATTENTION, ready", () => {
    start_port(2);
    const tur = () => {
        pw(2, PX.CMD, FRE);
        pw(2, PX.CMD, FRE | ST);
        issue(2, 0, { command: 0xA0, features: 1, prdt: [[0, 0x400000]], atapi: [0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] });
        return pr(2, PX.IS) & TFES ? pr(2, PX.TFD) >> 12 & 0xF : 0; // sense key
    };
    const drive = cpu.devices.cdrom;
    drive.eject();
    assert.equal(tur(), 2, "NOT READY");
    drive.set_cdrom(new CDImage());
    assert.equal(tur(), 2, "NOT READY (medium changed)");
    assert.equal(tur(), 6, "UNIT ATTENTION");
    assert.equal(tur(), 0, "ready");
});

test("NCQ: CAP.SNCQ, IDENTIFY queue depth 32, general purpose logging", () => {
    assert.ok(r32(0x00) & 1 << 30, "SNCQ");
    start_port(0);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    const id = words(DATA, 256);
    assert.equal(id[75], 31, "word 75: queue depth - 1");
    assert.ok(id[76] & 1 << 8, "word 76: NCQ");
    assert.ok(id[84] & 1 << 5 && id[87] & 1 << 5, "words 84/87: GPL (READ LOG EXT)");
    start_port(2);
    issue(2, 0, { command: 0xA1, prdt: [[DATA, 512]] });
    assert.equal(words(DATA, 256)[76] & 1 << 8, 0, "not on the CD drive");
});

test("NCQ: queued reads and writes complete with set device bits FISes", () => {
    start_port(0);
    ncq(0, 3, false, 40, 2, [[DATA, 1024]]);
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(pr(0, PX.SACT), 0, "the tag completed");
    const is = pr(0, PX.IS);
    assert.ok(is & SDBS, "SDBS");
    assert.equal(is & (DHRS | TFES), 0, "the register FIS accepting the command has no interrupt bit");
    assert.deepEqual(Array.from(sdb(0)), [0xA1, 0x40, 0x50, 0, 1 << 3, 0, 0, 0], "SDB FIS: I, status, SActive = tag 3");
    assert.deepEqual(mem.subarray(DATA, DATA + 1024), hda.subarray(40 * 512, 42 * 512));
    assert.equal(pr(0, PX.TFD) & 0xFF, 0x50);

    // a write over two PRDT entries, tag 31, and read back with tag 0
    for(let i = 0; i < 1536; i++) mem[DATA + 0x10000 + i] = i * 13 & 0xFF;
    ncq(0, 31, true, 3000, 3, [[DATA + 0x10000, 1000], [DATA + 0x10000 + 1000, 536]]);
    assert.equal(pr(0, PX.SACT), 0);
    assert.deepEqual(Array.from(sdb(0).subarray(4, 8)), [0, 0, 0, 0x80], "SActive = tag 31");
    assert.deepEqual(hda.subarray(3000 * 512, 3003 * 512), mem.subarray(DATA + 0x10000, DATA + 0x10000 + 1536));
    mem.fill(0, DATA, DATA + 1536);
    ncq(0, 0, false, 3000, 3, [[DATA, 1536]]);
    assert.deepEqual(mem.subarray(DATA, DATA + 1536), mem.subarray(DATA + 0x10000, DATA + 0x10000 + 1536));
    hda.set(hda_original);
});

test("NCQ errors: SDB FIS with ERR, TFES, the tag stays active; READ LOG EXT 10h; recovery", () => {
    start_port(0);
    const read_log = (slot, log) => issue(0, slot, { command: 0x2F, lba: log, count: 1, prdt: [[DATA + 0x8000, 512]] });

    ncq(0, 6, false, HDA_SIZE / 512 - 1, 2, [[DATA, 1024]]);
    assert.equal(pr(0, PX.CI), 0, "accepted");
    assert.equal(pr(0, PX.SACT), 1 << 6, "never completed");
    assert.ok(pr(0, PX.IS) & TFES, "TFES");
    assert.equal(pr(0, PX.TFD), 0x1041, "IDNF, DRDY|ERR");
    assert.deepEqual(Array.from(sdb(0)), [0xA1, 0x40, 0x41, 0x10, 0, 0, 0, 0]);
    ncq(0, 7, false, 0, 1, [[DATA, 512]]);
    assert.equal(pr(0, PX.CI), 1 << 7, "the list is halted");

    // Linux: stop and restart the engine, then read the NCQ error log
    pw(0, PX.CMD, FRE);
    assert.equal(pr(0, PX.SACT) | pr(0, PX.CI), 0, "clearing ST clears PxSACT and PxCI");
    pw(0, PX.CMD, FRE | ST);
    ncq(0, 1, false, 0, 1, [[DATA, 512]]);
    assert.ok(pr(0, PX.IS) & TFES, "queued commands are aborted until the log was read");
    assert.equal(pr(0, PX.TFD) >> 8, 0x04);
    pw(0, PX.CMD, FRE);
    pw(0, PX.CMD, FRE | ST);

    read_log(0, 0x00);
    assert.equal(pr(0, PX.CI), 0);
    assert.equal(pr(0, PX.IS) & TFES, 0);
    assert.deepEqual(words(DATA + 0x8000, 0x11).filter((w, i) => w), [1, 1], "the log directory: version 1, log 10h");
    assert.equal(words(DATA + 0x8000, 0x11)[0x10], 1);
    read_log(0, 0x10);
    assert.ok(pr(0, PX.IS) & PSS, "PIO data in");
    const log = mem.subarray(DATA + 0x8000, DATA + 0x8200);
    const lba = HDA_SIZE / 512 - 1;
    assert.deepEqual(Array.from(log.subarray(0, 14)),
        [6, 0, 0x41, 0x10, lba & 0xFF, lba >> 8 & 0xFF, lba >> 16 & 0xFF, 0x40, lba >>> 24, 0, 0, 0, 2, 0],
        "tag 6, status, error, LBA, count");
    assert.equal(log.reduce((a, b) => a + b, 0) & 0xFF, 0, "checksum");
    read_log(0, 0x10);
    assert.equal(log[0], 0x80, "read again: no queued command failed (NQ)");
    assert.equal(log.reduce((a, b) => a + b, 0) & 0xFF, 0);
    read_log(0, 0x30);
    assert.equal(pr(0, PX.TFD), 0x0441, "other logs: aborted");
    pw(0, PX.CMD, FRE);
    pw(0, PX.CMD, FRE | ST);

    ncq(0, 2, false, 9, 1, [[DATA, 512]]);
    assert.equal(pr(0, PX.SACT) | pr(0, PX.IS) & TFES, 0, "queued commands work again");
    assert.deepEqual(mem.subarray(DATA, DATA + 512), hda.subarray(9 * 512, 10 * 512));

    // a PRDT shorter than the transfer: overflow
    ncq(0, 3, false, 0, 2, [[DATA, 512]]);
    assert.ok(pr(0, PX.IS) & OFS);
    assert.ok(pr(0, PX.IS) & TFES);
    pw(0, PX.CMD, FRE);
    pw(0, PX.CMD, FRE | ST);
    read_log(0, 0x10);
    assert.equal(mem[DATA + 0x8000], 3, "tag 3 in the log");

    // a COMRESET also clears the error
    ncq(0, 4, false, HDA_SIZE / 512, 1, [[DATA, 512]]);
    pw(0, PX.SCTL, 1);
    pw(0, PX.SCTL, 0);
    start_port(0);
    ncq(0, 5, false, 0, 1, [[DATA, 512]]);
    assert.equal(pr(0, PX.SACT) | pr(0, PX.IS) & TFES, 0);

    // ATAPI devices have no queued commands
    start_port(2);
    issue(2, 0, { command: 0x60, features: 1, count: 0, prdt: [[DATA, 2048]], queued: true });
    assert.ok(pr(2, PX.IS) & TFES);
    assert.equal(pr(2, PX.TFD) >> 8, 0x04);
});

// a disk to hot plug: 1 MiB, each sector filled with its number + 0x40
const extra = new Uint8Array(1 << 20);
for(let s = 0; s < extra.length / 512; s++) extra.fill(s + 0x40 & 0xFF, s * 512, s * 512 + 512);

test("hot plug: HPCP on the ports without a drive at power-on", () => {
    for(const port of [0, 1, 2]) assert.equal(pr(port, PX.CMD) & HPCP, 0, "port " + port);
    for(const port of [3, 4, 5]) assert.equal(pr(port, PX.CMD) & HPCP, HPCP, "port " + port);
});

await emulator.attach_sata_drive(3, { buffer: extra.buffer });
test("hot plug: attaching a disk: DIAG.X and DIAG.N (PCS, PRCS), the link comes up, the signature; INTA", () => {
    // (attached above, before FIS reception was on: no D2H FIS yet)
    assert.equal(pr(3, PX.SERR), DIAG_X | DIAG_N);
    assert.equal(pr(3, PX.IS) & (PCS | PRCS), PCS | PRCS);
    assert.equal(pr(3, PX.SSTS), 0x113);
    assert.equal(pr(3, PX.TFD), 0x7F);

    pw(3, PX.CLB, clb(3));
    pw(3, PX.FB, fb(3));
    pw(3, PX.IE, PCS | PRCS);
    w32(0x04, 2);
    assert.ok(cpu.shared_irq_sources[16].has(AHCI), "PCS/PRCS interrupt");
    pw(3, PX.IS, -1);
    assert.equal(pr(3, PX.IS) & (PCS | PRCS), PCS | PRCS, "writing PxIS does not clear PCS and PRCS");
    pw(3, PX.SERR, DIAG_X | DIAG_N);
    assert.equal(pr(3, PX.IS), 0, "clearing PxSERR does");
    assert.ok(!cpu.shared_irq_sources[16].has(AHCI));
    w32(0x04, 0);

    start_port(3);
    assert.equal(pr(3, PX.SIG), 0x101, "the signature once FIS reception is on");
    issue(3, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    const id = words(DATA, 256);
    assert.equal(id[60] | id[61] << 16, 2048, "IDENTIFY: 1 MiB");
    issue(3, 1, { command: 0x25, lba: 5, count: 2, prdt: [[DATA, 1024]] });
    assert.deepEqual(mem.subarray(DATA, DATA + 1024), extra.subarray(5 * 512, 7 * 512));
    ncq(3, 2, false, 9, 1, [[DATA, 512]]);
    assert.ok(mem.subarray(DATA, DATA + 512).every(b => b === 0x49), "NCQ too");
    assert.deepEqual(cpu.disk_devices().map(([name]) => name), ["hda", "hdb", "cdrom", "sata3"]);
});

test("hot plug: detaching: DIAG.N (PRCS), no link, PxTFD 7Fh; commands stay issued until ST is cleared", () => {
    start_port(3);
    pw(3, PX.IE, PRCS);
    w32(0x04, 2);
    emulator.detach_sata_drive(3);
    assert.equal(pr(3, PX.SERR), DIAG_N);
    assert.equal(pr(3, PX.IS), PRCS);
    assert.ok(cpu.shared_irq_sources[16].has(AHCI));
    assert.equal(pr(3, PX.SSTS), 0);
    assert.equal(pr(3, PX.TFD), 0x7F);
    assert.equal(pr(3, PX.SIG), 0xFFFFFFFF);
    issue(3, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(3, PX.CI), 1, "nothing executes it");
    pw(3, PX.CMD, FRE);
    assert.equal(pr(3, PX.CI), 0);
    pw(3, PX.SERR, -1);
    pw(3, PX.IE, 0);
    w32(0x04, 0);
    assert.ok(!cpu.shared_irq_sources[16].has(AHCI));
    assert.throws(() => emulator.detach_sata_drive(3), /no drive/);
    assert.throws(() => cpu.devices.ahci.attach(0, { buffer: undefined, is_cdrom: true }), /already has a drive/);
});

test("hot plug: the CD drive on port 2 out and an empty one in: cdrom follows", () => {
    const drive = cpu.devices.cdrom;
    emulator.detach_sata_drive(2);
    assert.equal(cpu.devices.cdrom, undefined);
    assert.equal(pr(2, PX.SSTS), 0);
    cpu.devices.ahci.attach(2, { buffer: undefined, is_cdrom: true });
    assert.notEqual(cpu.devices.cdrom, drive);
    assert.ok(cpu.devices.cdrom.is_atapi && !cpu.devices.cdrom.has_disk());
    start_port(2);
    assert.equal(pr(2, PX.SIG), 0xEB140101);
    cpu.devices.cdrom.set_cdrom(new CDImage());
    assert.ok(cpu.devices.cdrom.has_disk());
});

await emulator.attach_sata_drive(4, { buffer: extra.buffer });
const hot_state = await emulator.save_state();
emulator.detach_sata_drive(4);
await emulator.attach_sata_drive(5, { buffer: extra.buffer });
pw(5, PX.SERR, -1);
await emulator.restore_state(hot_state);
test("hot plug and snapshots: a drive on one side only is a hot plug event for the restored guest", () => {
    assert.equal(pr(4, PX.SSTS), 0, "port 4: in the snapshot, not in the machine: removed");
    assert.equal(pr(4, PX.SERR) & DIAG_N, DIAG_N);
    assert.equal(pr(5, PX.SSTS), 0x113, "port 5: in the machine only: plugged in");
    assert.equal(pr(5, PX.SERR) & (DIAG_X | DIAG_N), DIAG_X | DIAG_N);
    start_port(5);
    issue(5, 0, { command: 0x25, lba: 1, count: 1, prdt: [[DATA, 512]] });
    assert.ok(mem.subarray(DATA, DATA + 512).every(b => b === 0x41));
    emulator.detach_sata_drive(5);
    for(const port of [3, 4, 5]) pw(port, PX.SERR, -1);
});

// a disk image (docs/disk-image-formats-plan.md P0): a QCOW2 disk of 1 MiB,
// its second cluster damaged
const { build_qcow2 } = await import("../image/tiny_qcow2.mjs");
await emulator.attach_sata_drive(3, { buffer: build_qcow2({ size: 1 << 20, data: [[0, extra.subarray(0, 65536)]], damaged: [65536] }).buffer, format: "qcow2", disk_error: "report" });
pw(3, PX.SERR, -1);
test("a QCOW2 disk: reads; a failed read or write ends a queued or DMA command with ABRT (TFES), the port goes on", () => {
    start_port(3);
    const read_log = slot => issue(3, slot, { command: 0x2F, lba: 0x10, count: 1, prdt: [[DATA + 0x8000, 512]] });
    const restart = () => { pw(3, PX.CMD, FRE); pw(3, PX.CMD, FRE | ST); };
    issue(3, 0, { command: 0x25, lba: 5, count: 2, prdt: [[DATA, 1024]] });
    assert.deepEqual(mem.subarray(DATA, DATA + 1024), extra.subarray(5 * 512, 7 * 512), "DMA read");
    ncq(3, 1, false, 128, 1, [[DATA, 512]]);
    assert.ok(pr(3, PX.IS) & TFES, "queued read of the damaged cluster: TFES");
    assert.equal(pr(3, PX.TFD), 0x0441, "ABRT, DRDY|ERR");
    restart();
    read_log(2);
    assert.equal(mem[DATA + 0x8000], 1, "tag 1 in the NCQ error log");
    issue(3, 3, { command: 0x25, lba: 129, count: 1, prdt: [[DATA, 512]] });
    assert.ok(pr(3, PX.IS) & TFES, "DMA read of the damaged cluster: TFES");
    assert.equal(pr(3, PX.TFD) >> 8, 0x04, "ABRT");
    restart();
    const disk = cpu.devices.ahci.ports[3].device.buffer;
    disk.overlay.limit = disk.overlay.size();
    ncq(3, 4, true, 7, 1, [[DATA, 512]]);
    assert.ok(pr(3, PX.IS) & TFES, "queued write past the memory budget: TFES");
    assert.equal(pr(3, PX.TFD), 0x0441);
    disk.overlay.limit = Infinity;
    restart();
    read_log(5);
    ncq(3, 6, false, 1, 1, [[DATA, 512]]);
    assert.equal(pr(3, PX.SACT) | pr(3, PX.IS) & TFES, 0, "queued commands work again");
    assert.deepEqual(mem.subarray(DATA, DATA + 512), extra.subarray(512, 1024));
});
emulator.detach_sata_drive(3);
pw(3, PX.SERR, -1);

// the drive's disk_error policy (docs/disk-persistence-plan.md D0): sata3
// with the default ("stop"), sata4 with "report"; their reads and writes
// fail on request
class FlakyDrive
{
    constructor(policy)
    {
        this.byteLength = 1 << 20;
        this.data = new Uint8Array(this.byteLength).map((_, i) => i * 3 + (i >> 9) & 0xFF);
        this.fail_reads = 0;
        this.fail_writes = 0;
        if(policy) this.disk_error = policy;
    }
    load() { this.onload?.({}); }
    get(start, length, done)
    {
        if(this.fail_reads) { this.fail_reads--; done(undefined, new Error("the test's drive failed the read")); return; }
        done(this.data.slice(start, start + length));
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done)
    {
        if(this.fail_writes) { this.fail_writes--; done(new Error("the test's drive failed the write")); return; }
        this.data.set(data, start);
        done();
    }
    get_buffer(done) { done(undefined); }
    get_state() { return []; }
    set_state() {}
}
const stopping = new FlakyDrive(), reporting = new FlakyDrive("report");
await emulator.attach_sata_drive(3, stopping);
await emulator.attach_sata_drive(4, reporting);
const disk_errors = [];
emulator.add_listener("disk-error", event => disk_errors.push(event));
pw(3, PX.SERR, -1);
pw(4, PX.SERR, -1);
test("disk_error: stop holds a failed queued read until run() retries it; report ends a queued write with ABRT (TFES)", () => {
    start_port(3);
    stopping.fail_reads = 1;
    ncq(3, 1, false, 10, 2, [[DATA, 1024]]);
    assert.equal(pr(3, PX.SACT), 1 << 1, "tag 1 is still in flight");
    assert.equal(cpu.disk_holds.length, 1, "held");
    assert.deepEqual(disk_errors[0], { disk: "sata3", operation: "read", offset: 10 * 512, length: 1024,
        reason: "the test's drive failed the read", retryable: true, policy: "stop" });
    // (run() retries it; the machine is stopped again before it runs)
    emulator.v86.run();
    emulator.v86.stop();
    assert.equal(cpu.disk_holds.length, 0);
    assert.equal(pr(3, PX.SACT) | pr(3, PX.IS) & TFES, 0, "the read completed");
    assert.deepEqual(mem.subarray(DATA, DATA + 1024), stopping.data.subarray(10 * 512, 12 * 512));
    start_port(4);
    reporting.fail_writes = 1;
    ncq(4, 2, true, 7, 1, [[DATA, 512]]);
    assert.ok(pr(4, PX.IS) & TFES, "TFES at once");
    assert.equal(pr(4, PX.TFD), 0x0441, "ABRT, DRDY|ERR");
    assert.equal(disk_errors[1].policy, "report");
    assert.equal(disk_errors[1].operation, "write");
    assert.equal(cpu.disk_holds.length, 0, "nothing held");
});
emulator.detach_sata_drive(3);
emulator.detach_sata_drive(4);
pw(3, PX.SERR, -1);
pw(4, PX.SERR, -1);

// a drive written back (docs/disk-persistence-plan.md D1): a buffer object
// of one's own with the backend contract, recording what the controller
// asks of it
class RecordingDrive extends FlakyDrive
{
    constructor()
    {
        super();
        this.disk_option = "read_write";
        this.log = [];
    }
    set(start, data, done) { this.log.push("write " + start / 512); super.set(start, data, done); }
    flush(done) { this.log.push("flush"); done(); }
    close(done) { this.log.push("close"); done(); }
    mark() { return "1"; }
    generation() { return "1"; }
    check_state() {}
}
const recording = new RecordingDrive();
await emulator.attach_sata_drive(3, recording);
pw(3, PX.SERR, -1);
test("a drive written back: IDENTIFY reports its write cache; an NCQ write with FUA is flushed before it completes", () => {
    start_port(3);
    issue(3, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    const id = words(DATA, 256);
    assert.equal(id[82] & 1 << 5, 1 << 5, "word 82: write cache");
    assert.equal(id[85] & 1 << 5, 1 << 5, "word 85: enabled");
    ncq(3, 1, true, 8, 1, [[DATA, 512]]);
    assert.equal(pr(3, PX.SACT), 0);
    assert.deepEqual(recording.log, ["write 8"], "no FUA: no flush");
    issue(3, 2, { command: 0x61, features: 1, lba: 9, count: 2 << 3, device: 0xC0, prdt: [[DATA, 512]], write: true, queued: true });
    assert.equal(pr(3, PX.SACT) | pr(3, PX.IS) & TFES, 0, "completed");
    assert.deepEqual(recording.log, ["write 8", "write 9", "flush"], "FUA: the write, then the flush, then the completion");
    issue(3, 3, { command: 0xEF, features: 0x82 });
    issue(3, 4, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(words(DATA, 256)[85] & 1 << 5, 0, "SET FEATURES 82h: off");
    ncq(3, 5, true, 10, 1, [[DATA, 512]]);
    assert.deepEqual(recording.log.slice(3), ["write 10", "flush"], "write cache off: each write flushed");
    issue(3, 6, { command: 0xEF, features: 0x02 });
});
emulator.detach_sata_drive(3);
pw(3, PX.SERR, -1);

test("link power management: CAP, ICC requests, PxSCTL.IPM, commands wake the link, ALPE/ASP when idle", () => {
    const cap = r32(0x00);
    assert.ok(cap & 1 << 26 && cap & 1 << 14 && cap & 1 << 13, "SALP, SSC, PSC");
    start_port(0);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.ok(words(DATA, 256)[76] & 1 << 9, "IDENTIFY word 76: host-initiated power management");
    const ipm = () => pr(0, PX.SSTS) >> 8 & 0xF;
    assert.equal(ipm(), 1, "active");
    pw(0, PX.CMD, FRE | ST | 2 << 28);
    assert.equal(ipm(), 2, "ICC: partial");
    assert.equal(pr(0, PX.CMD) >>> 28, 0, "ICC reads as idle");
    pw(0, PX.CMD, FRE | ST | 6 << 28);
    assert.equal(ipm(), 6, "ICC: slumber");
    issue(0, 1, { command: 0x25, lba: 1, count: 1, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.CI), 0, "the command ran");
    assert.equal(ipm(), 1, "and woke the link");
    pw(0, PX.SCTL, 3 << 8);
    pw(0, PX.CMD, FRE | ST | 2 << 28);
    pw(0, PX.CMD, FRE | ST | 6 << 28);
    assert.equal(ipm(), 1, "PxSCTL.IPM: neither partial nor slumber allowed");
    pw(0, PX.SCTL, 0);
    pw(0, PX.CMD, FRE | ST | 1 << 26);
    assert.equal(ipm(), 2, "ALPE without ASP: an idle port goes to partial");
    pw(0, PX.CMD, FRE | ST | 3 << 26);
    issue(0, 2, { command: 0x25, lba: 2, count: 1, prdt: [[DATA, 512]] });
    assert.equal(ipm(), 6, "ALPE with ASP: slumber again after the command");
    assert.deepEqual(mem.subarray(DATA, DATA + 512), hda.subarray(2 * 512, 3 * 512));
    pw(0, PX.SCTL, 2 << 8);
    pw(0, PX.CMD, FRE | ST | 1 << 28);
    issue(0, 3, { command: 0x25, lba: 3, count: 1, prdt: [[DATA, 512]] });
    assert.equal(ipm(), 1, "slumber not allowed: stays active");
    pw(0, PX.SCTL, 0);
    pw(0, PX.CMD, FRE | ST | 1 << 28);
    assert.equal(ipm(), 1);
    pw(3, PX.CMD, 6 << 28);
    assert.equal(pr(3, PX.SSTS), 0, "no link, no state");
});

test("interrupts: GHC.IE and PxIE gate INTA (Q35: PIRQA, GSI 16); clearing PxIS lowers it", () => {
    start_port(0);
    const gsi = cpu.shared_irq_sources[16];
    w32(0x04, 0);
    pw(0, PX.IE, DHRS);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.ok(!gsi.has(AHCI), "GHC.IE clear");
    assert.equal(r32(0x08), 1, "IS shows port 0");
    w32(0x04, 2);
    assert.ok(gsi.has(AHCI), "asserted");
    pw(0, PX.IS, DHRS | PSS);
    assert.ok(!gsi.has(AHCI), "deasserted");
    pw(0, PX.IE, 0);
    w32(0x04, 0);
});

test("MSI: the capability, INTA released, a message to the local APIC per event", () => {
    const LAPIC = 0xFEE00000;
    const irr = vector => !!((cpu.read32s(LAPIC + 0x200 + (vector >> 5) * 16) >>> 0) & 1 << (vector & 31));
    cpu.write32(LAPIC + 0xF0, 0x1FF); // software enabled
    assert.equal(pci.config_read(AHCI, 0x34, 1), 0x80, "capability list");
    assert.equal(pci.config_read(AHCI, 0x80, 2), 0x0005, "MSI, last capability");
    assert.equal(pci.config_read(AHCI, 0x82, 2), 0x0080, "64-bit address, one message, disabled");
    pci.config_write(AHCI, 0x84, 4, 0xFEE00000 | 3); // destination 0, physical (the low bits are reserved)
    pci.config_write(AHCI, 0x88, 4, 0);
    pci.config_write(AHCI, 0x8C, 2, 0x0045);         // vector 0x45, fixed
    pci.config_write(AHCI, 0x80, 4, 0xFFFF0105);     // enable; read-only bits stay
    assert.equal(pci.config_read(AHCI, 0x80, 4) >>> 0, 0x00810005);
    assert.equal(pci.config_read(AHCI, 0x84, 4) >>> 0, 0xFEE00000);

    start_port(0);
    w32(0x04, 2);
    pw(0, PX.IE, DHRS);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.ok(irr(0x45), "the message reached the local APIC");
    assert.ok(!cpu.shared_irq_sources[16].has(AHCI), "INTA is not used with MSI");
    // disabling MSI with an interrupt pending: INTA again
    pci.config_write(AHCI, 0x82, 2, 0);
    assert.ok(cpu.shared_irq_sources[16].has(AHCI));
    pw(0, PX.IS, -1);
    assert.ok(!cpu.shared_irq_sources[16].has(AHCI));
    pw(0, PX.IE, 0);
    w32(0x04, 0);
});

test("COMRESET and HBA reset: the device sends its signature again", () => {
    start_port(0);
    pw(0, PX.SCTL, 1);
    assert.equal(pr(0, PX.SSTS) & 0xF, 0, "no link while COMRESET is asserted");
    pw(0, PX.IS, -1);
    pw(0, PX.SCTL, 0);
    assert.equal(pr(0, PX.SSTS), 0x113);
    assert.equal(pr(0, PX.SIG), 0x101);
    assert.ok(pr(0, PX.IS) & DHRS, "D2H FIS (FIS reception is on)");

    w32(0x04, 1);
    assert.equal(r32(0x04) & 1, 0, "HR self-clears");
    assert.equal(pr(0, PX.CMD) & (ST | FRE), 0);
    assert.equal(pr(0, PX.TFD), 0x7F);
    assert.equal(pr(0, PX.CLB), clb(0), "CLB survives an HBA reset");
    pw(0, PX.CMD, FRE);
    assert.equal(pr(0, PX.SIG), 0x101);
});

test("software reset: a control FIS with SRST, then without", () => {
    start_port(2);
    issue(2, 0, { control: 0x04 });
    assert.equal(pr(2, PX.CI), 0, "completes without a D2H FIS");
    assert.ok(pr(2, PX.TFD) & 0x80, "BSY while SRST is set");
    issue(2, 0, { control: 0x00 });
    assert.equal(pr(2, PX.SIG), 0xEB140101);
    assert.equal(pr(2, PX.TFD) & 0x88, 0);
    assert.ok(pr(2, PX.IS) & DHRS);
});

test("memory space and bus mastering: no decode without MSE, no commands without BME", () => {
    program_pci(0x0000);
    assert.equal(r32(0x0C), 0xFFFFFFFF, "ABAR not decoded");
    program_pci(0x0002);
    assert.equal(r32(0x0C), 0x3F);
    start_port(0);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.CI), 1, "waits for bus mastering");
    program_pci(0x0006);
    assert.equal(pr(0, PX.CI), 0, "runs once BME is set");
});

test("byte accesses to the port registers", () => {
    start_port(0);
    issue(0, 0, { command: 0xEC, prdt: [[DATA, 512]] });
    assert.equal(pr(0, PX.IS) & 3, 3);
    cpu.mmap_write8(ABAR + 0x100 + PX.IS, DHRS);
    assert.equal(pr(0, PX.IS) & 3, PSS, "a byte write clears only its bits");
    assert.equal(cpu.mmap_read8(ABAR + 0x100 + PX.SSTS), 0x13);
});

const state = await emulator.save_state();
await emulator.restore_state(state);
test("snapshot: registers and the drives survive, commands work after the restore", () => {
    assert.equal(pr(0, PX.CLB), clb(0));
    assert.equal(pr(0, PX.SIG), 0x101);
    assert.equal(pr(2, PX.SIG), 0xEB140101);
    start_port(0);
    issue(0, 0, { command: 0x25, lba: 7, count: 1, prdt: [[DATA, 512]] });
    assert.deepEqual(mem.subarray(DATA, DATA + 512), hda_original.subarray(7 * 512, 8 * 512));
});

// the streamed snapshot format too (its slots must not collide with the machine's)
const chunks = [];
await emulator.save_state_stream(chunk => { chunks.push(chunk.slice()); });
const stream = Buffer.concat(chunks);
await emulator.restore_state_stream({ size: stream.length, read: async (offset, length) => stream.subarray(offset, offset + length) });
test("streamed snapshot: a Q35 machine restores, the disks work", () => {
    assert.equal(cpu.platform.machine, "q35");
    assert.equal(pr(0, PX.SIG), 0x101);
    start_port(0);
    issue(0, 0, { command: 0x25, lba: 11, count: 1, prdt: [[DATA, 512]] });
    assert.deepEqual(mem.subarray(DATA, DATA + 512), hda_original.subarray(11 * 512, 12 * 512));
});

emulator.destroy();
console.log((failed ? "FAIL" : "PASS") + ": " + passed + " AHCI tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/devices/ahci_lifecycle.mjs                                                         0000755 0000000 0000000 00000031000 00000000000 016103  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AHCI commands with disk I/O in flight (docs/ahci.md): the
// hard disk is an embedder's asynchronous buffer whose reads and writes
// complete 100 ms later.
// - a machine reset while a READ DMA is in flight: no data reaches RAM, no
//   status and no interrupt for the machine that starts after it;
// - clearing PxCMD.ST while a READ DMA is in flight: PxCI clears at once,
//   the late data reaches no memory, no status bits appear;
// - a write completes for the guest only once the backend has it (DMA and
//   PIO), and FLUSH CACHE after it;
// - a snapshot taken while a write is in flight holds the completed command;
// - a reset while a write is in flight: the write lands (the guest issued
//   it), its completion reaches nothing;
// - S5 while a write is in flight: "acpi-power-off" only after it landed;
// - native command queuing: several queued commands in flight at once, each
//   completing on its own; a non-queued command waits for them; clearing ST
//   drops them; a snapshot waits for them;
// - hot plug: pulling the drive out with I/O in flight drops the read, the
//   write lands; the drive works again once plugged in.
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { SyncBuffer } = await import("../../src/buffer.js");

const SIZE = 16 << 20, LATENCY = 100;
const disk = new Uint8Array(SIZE).map((_, i) => i * 7 & 0xFF);
let writes_landed = 0;
const base = new SyncBuffer(disk.buffer);
const hda = Object.create(base);
hda.get = (start, length, callback) => setTimeout(() => base.get(start, length, callback), LATENCY);
hda.set = (start, data, callback) => setTimeout(() => base.set(start, data, () => { writes_landed++; callback(); }), LATENCY);

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
    machine_type: "q35", hda, memory_size: 32 << 20, autostart: false, log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const AHCI = 0x1F << 3 | 2, ABAR = 0xC0000000;
const ST = 1, FRE = 1 << 4, DHRS = 1;
const IS = 0x110, CMD = 0x118, CI = 0x138;
const CLB = 0x200000, FB = 0x200400, TABLE = 0x201000, DATA = 0x300000;

const r32 = offset => cpu.mmap_read32(ABAR + offset) >>> 0;
const w32 = (offset, value) => cpu.mmap_write32(ABAR + offset, value | 0);
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const pending = () => cpu["snapshot_io_pending"] || 0;
const SACT = 0x134, SDBS = 1 << 3;
const irq_asserted = () => cpu.shared_irq_sources.some(sources => sources.has(AHCI));

function setup()
{
    pci.config_write(AHCI, 0x24, 4, ABAR);
    pci.config_write(AHCI, 0x04, 2, 0x0006);
    w32(CMD, 0);
    w32(0x100, CLB);
    w32(0x108, FB);
    w32(CMD, FRE);
    w32(CMD, FRE | ST);
    w32(IS, -1);
    w32(0x114, -1 & 0xFDC000FF); // PxIE: everything
    w32(0x04, 2);               // GHC.IE
}

function issue(command, lba, count, write)
{
    mem.fill(0, TABLE, TABLE + 0x100);
    mem.set([0x27, 0x80, command, 0, lba & 0xFF, lba >> 8 & 0xFF, lba >> 16 & 0xFF, 0x40, 0, 0, 0, 0, count, 0], TABLE);
    put32(TABLE + 0x80, DATA);
    put32(TABLE + 0x8C, count * 512 - 1);
    put32(CLB, 5 | (write ? 1 << 6 : 0) | 1 << 16);
    put32(CLB + 8, TABLE);
    w32(CI, 1);
}

// a READ DMA in flight, then a machine reset
setup();
mem.fill(0xAA, DATA, DATA + 1024);
issue(0x25, 4, 2, false);
assert.equal(r32(CI), 1, "in flight");
assert.equal(pending(), 1);
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.ok(mem.subarray(DATA, DATA + 1024).every(b => b === 0xAA), "the late data did not reach RAM");
assert.equal(pending(), 0, "and is no longer counted as pending");
assert.equal(r32(CI), 0);
assert.equal(r32(IS), 0, "no status for the reset port");
assert.ok(!irq_asserted(), "no interrupt");
console.log("ok - READ DMA in flight across a reset is dropped");

// a READ DMA in flight, then software stops the command list
setup();
mem.fill(0xAA, DATA, DATA + 1024);
issue(0x25, 4, 2, false);
w32(CMD, FRE);
assert.equal(r32(CI), 0, "clearing ST clears PxCI at once");
w32(IS, -1);
await delay(LATENCY * 3);
assert.ok(mem.subarray(DATA, DATA + 1024).every(b => b === 0xAA), "no data after ST was cleared");
assert.equal(r32(IS), 0, "no status for the stopped command");
console.log("ok - a command in flight is dropped when ST is cleared");

// writes complete for the guest when the backend has them
setup();
mem.fill(0x5A, DATA, DATA + 512);
let landed = writes_landed;
issue(0xCA, 8, 1, true);
assert.equal(r32(CI), 1, "a DMA write is not complete before the backend has it");
await delay(LATENCY * 2);
assert.equal(writes_landed, landed + 1);
assert.equal(r32(CI), 0, "then it is");
assert.ok(r32(IS) & DHRS);
assert.ok(disk.subarray(8 * 512, 9 * 512).every(b => b === 0x5A));

w32(IS, -1);
mem.fill(0x6B, DATA, DATA + 512);
landed = writes_landed;
issue(0x30, 9, 1, true);
assert.equal(r32(CI), 1, "a PIO write neither (BSY until the backend has it)");
assert.equal(r32(0x120) & 0x80, 0x80, "PxTFD shows BSY");
await delay(LATENCY * 2);
assert.equal(writes_landed, landed + 1);
assert.equal(r32(CI), 0);
assert.ok(disk.subarray(9 * 512, 10 * 512).every(b => b === 0x6B));

issue(0xE7, 0, 0, false);
assert.equal(r32(CI), 0, "FLUSH CACHE with no write in flight completes at once");
console.log("ok - writes and FLUSH CACHE complete after the backend has the data");

// a snapshot while a write is in flight: it waits, the command is complete in it
setup();
mem.fill(0x3C, DATA, DATA + 512);
issue(0xCA, 12, 1, true);
assert.equal(r32(CI), 1);
const state = await emulator.save_state();
assert.equal(pending(), 0, "the snapshot waited for the write");
assert.equal(r32(CI), 0, "and the command completed before the state was taken");
w32(IS, -1);
await emulator.restore_state(state);
assert.equal(r32(CI), 0, "complete in the snapshot");
assert.ok(r32(IS) & DHRS, "with its status");
assert.ok(disk.subarray(12 * 512, 13 * 512).every(b => b === 0x3C));
console.log("ok - a snapshot taken during a write holds the completed command");

// a write in flight, then a reset: it lands, nothing completes
setup();
mem.fill(0x4D, DATA, DATA + 512);
issue(0xCA, 16, 1, true);
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.ok(disk.subarray(16 * 512, 17 * 512).every(b => b === 0x4D), "the write itself landed (the guest issued it)");
assert.equal(r32(IS), 0, "no status for the reset port");
assert.ok(!irq_asserted());
console.log("ok - a write completing after a reset does not touch the port");

/**
 * READ/WRITE FPDMA QUEUED in slot (= tag) n: its own command table and data
 * buffer (DATA + n * 64 KiB)
 */
function queue(slot, lba, count, write)
{
    const table = TABLE + slot * 0x100, data = DATA + slot * 0x10000, header = CLB + slot * 32;
    mem.fill(0, table, table + 0x100);
    mem.set([0x27, 0x80, write ? 0x61 : 0x60, count, lba & 0xFF, lba >> 8 & 0xFF, lba >> 16 & 0xFF, 0x40, 0, 0, 0, 0, slot << 3, 0], table);
    put32(table + 0x80, data);
    put32(table + 0x8C, count * 512 - 1);
    put32(header, 5 | (write ? 1 << 6 : 0) | 1 << 16);
    put32(header + 8, table);
}
const sector = lba => disk.subarray(lba * 512, lba * 512 + 512);
const buffer = slot => mem.subarray(DATA + slot * 0x10000, DATA + slot * 0x10000 + 512);

// four queued reads at once
setup();
for(let slot = 0; slot < 4; slot++)
{
    mem.fill(0xAA, DATA + slot * 0x10000, DATA + slot * 0x10000 + 512);
    queue(slot, 100 + slot * 3, 1, false);
}
w32(SACT, 0xF);
w32(CI, 0xF);
assert.equal(r32(CI), 0, "the device took all four at once");
assert.equal(r32(SACT), 0xF);
assert.equal(pending(), 4, "four reads in flight");
assert.equal(r32(0x120) & 0x88, 0, "PxTFD: not busy");
w32(IS, -1);
await delay(LATENCY * 2);
assert.equal(r32(SACT), 0, "all completed");
assert.ok(r32(IS) & SDBS);
for(let slot = 0; slot < 4; slot++) assert.deepEqual(buffer(slot), sector(100 + slot * 3), "tag " + slot);
console.log("ok - four queued reads are in flight at once");

// a queued write completes when the backend has it; a non-queued command
// waits for the queued ones
setup();
mem.fill(0x19, DATA + 5 * 0x10000, DATA + 5 * 0x10000 + 512);
landed = writes_landed;
queue(5, 30, 1, true);
w32(SACT, 1 << 5);
w32(CI, 1 << 5);
issue(0x25, 31, 1, false); // READ DMA EXT in slot 0
assert.equal(r32(CI), 1, "the non-queued command waits");
await delay(LATENCY * 1.5);
assert.equal(writes_landed, landed + 1);
assert.equal(r32(SACT), 0, "the write completed after it landed");
assert.ok(sector(30).every(b => b === 0x19));
assert.equal(r32(CI), 1, "then the non-queued command runs");
await delay(LATENCY * 1.5);
assert.equal(r32(CI), 0);
assert.ok(r32(IS) & DHRS);

// FLUSH CACHE after queued writes: it completes after they landed
mem.fill(0x2A, DATA + 6 * 0x10000, DATA + 6 * 0x10000 + 512);
landed = writes_landed;
queue(6, 32, 1, true);
w32(SACT, 1 << 6);
w32(CI, 1 << 6);
issue(0xE7, 0, 0, false);
assert.equal(r32(CI), 1, "FLUSH CACHE waits");
await delay(LATENCY * 1.5);
assert.equal(writes_landed, landed + 1);
assert.equal(r32(CI), 0, "and completes once the queued write landed");
assert.ok(sector(32).every(b => b === 0x2A));
console.log("ok - a non-queued command (and FLUSH CACHE) waits for the queued commands in flight");

// clearing ST drops the queued commands in flight
setup();
mem.fill(0xAA, DATA, DATA + 512);
queue(0, 40, 1, false);
w32(SACT, 1);
w32(CI, 1);
w32(CMD, FRE);
assert.equal(r32(SACT), 0, "PxSACT clears with ST");
w32(IS, -1);
await delay(LATENCY * 2);
assert.ok(buffer(0).every(b => b === 0xAA), "no data after ST was cleared");
assert.equal(r32(IS), 0, "no set device bits FIS");
console.log("ok - queued commands in flight are dropped when ST is cleared");

// a snapshot waits for the queued commands in flight
setup();
queue(2, 50, 1, false);
queue(3, 51, 1, false);
w32(SACT, 0xC);
w32(CI, 0xC);
assert.equal(pending(), 2);
const queued_state = await emulator.save_state();
assert.equal(pending(), 0);
assert.equal(r32(SACT), 0, "completed before the state was taken");
w32(IS, -1);
await emulator.restore_state(queued_state);
assert.equal(r32(SACT), 0);
assert.ok(r32(IS) & SDBS);
assert.deepEqual(buffer(2), sector(50));
console.log("ok - a snapshot waits for the queued commands in flight");

// the drive pulled out with a queued read and a queued write in flight
setup();
mem.fill(0xAA, DATA, DATA + 1024);
mem.fill(0x5C, DATA + 7 * 0x10000, DATA + 7 * 0x10000 + 512);
landed = writes_landed;
queue(7, 60, 1, true);
queue(0, 4, 2, false);
w32(SACT, 1 << 7 | 1);
w32(CI, 1 << 7 | 1);
assert.equal(pending(), 2);
emulator.detach_sata_drive(0);
assert.equal(pending(), 1, "the read is dropped (the write is in the backend's hands)");
assert.equal(r32(0x128), 0, "no link");
w32(IS, -1);
await delay(LATENCY * 2);
assert.equal(pending(), 0);
assert.equal(writes_landed, landed + 1, "the write landed");
assert.ok(sector(60).every(b => b === 0x5C));
assert.ok(mem.subarray(DATA, DATA + 1024).every(b => b === 0xAA), "no data from the read");
assert.equal(r32(IS), 1 << 22, "no completion, only PRCS (the link went down)");
assert.equal(r32(SACT), 1 << 7 | 1, "both stay active (until software stops the port)");
// plugged in again: after the guest restarts the port, it works
await emulator.attach_sata_drive(0, hda);
w32(0x130, -1); // PxSERR
setup();
issue(0x25, 4, 2, false);
await delay(LATENCY * 2);
assert.equal(r32(CI), 0);
assert.deepEqual(mem.subarray(DATA, DATA + 1024), disk.subarray(4 * 512, 6 * 512));
console.log("ok - a drive pulled out with I/O in flight: the read is dropped, the write lands; plugged in again");

// S5 with a write in flight: the power-off is announced after it landed
setup();
pci.config_write(0x1F << 3, 0x40, 4, 0x601); // PMBASE
pci.config_write(0x1F << 3, 0x44, 1, 0x80);  // ACPI_EN
assert.equal(cpu.devices.acpi.pm_base, 0x600);
mem.fill(0x2E, DATA, DATA + 512);
landed = writes_landed;
issue(0xCA, 20, 1, true);
let announced_after = -1;
const off = new Promise(resolve => emulator.add_listener("acpi-power-off", () => { announced_after = writes_landed - landed; resolve(); }));
cpu.io.port_write16(0x604, 0 << 10 | 1 << 13); // SLP_TYP 0 (S5), SLP_EN
await off;
assert.equal(announced_after, 1, "acpi-power-off after the write landed");
console.log("ok - S5 is announced after the AHCI write in flight landed");

emulator.destroy();
console.log("AHCI lifecycle tests passed");
source/v64/tests/devices/default_cards.js                                                           0000755 0000000 0000000 00000015743 00000000000 015623  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The NE2000 and the SB16 as plugins (docs/modern-pc-devices-plan.md M1): a
// PC machine that names no cards gets them (src/net_adapters/ne2k/,
// src/audio_devices/sb16/; with TEST_RELEASE_BUILD=1 the built
// build/v86-ne2k.js and build/v86-sb16.js beside build/libv86.mjs), a plugin
// file that cannot be loaded fails the start naming it, a snapshot has format
// 8 and the cards' tagged slots, and a snapshot of the form before M1 (format
// 6, the cards' own states untagged in state[59] and state[61]) restores into
// the plugins as they are; slots of other cards are refused. The site's real
// saves: tests/api/site_states.mjs.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const ROOT = __dirname + "/../../";
const BASE = {
    wasm_path: ROOT + "build/" + (TEST_RELEASE_BUILD ? "v86.wasm" : "v86-debug.wasm"),
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    graphics_adapter: "bochs_vga",
    memory_size: 32 << 20,
    disable_keyboard: true,
    disable_mouse: true,
    disable_speaker: true,
    log_level: 0,
};

/** @return {!Promise<V86>} a machine up to SeaBIOS's "No bootable device", stopped */
async function boot(options = {})
{
    const emulator = new V86({ ...BASE, autostart: true, ...options });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    await emulator.wait_until_vga_screen_contains("No bootable device.", { timeout_msec: 60000 });
    await emulator.stop();
    return emulator;
}

/** The snapshot's header and info (its state array, buffers by reference) */
function parse(snapshot)
{
    const header = new Int32Array(snapshot, 0, 4);
    const info_end = 16 + header[3];
    return { header, info: JSON.parse(new TextDecoder().decode(new Uint8Array(snapshot, 16, header[3]))), info_end };
}

/** The snapshot rewritten as before M1: format 6, the cards' slots untagged */
function as_before_m1(snapshot)
{
    const { info, info_end } = parse(snapshot);
    for(const slot of [59, 61]) info.state[slot] = info.state[slot][3];
    const json = new TextEncoder().encode(JSON.stringify(info));
    // (the buffers keep their place: the info block is padded to 4 bytes, as state.js writes it)
    const padded = json.length + 3 & ~3, old_padded = info_end - 16 + 3 & ~3;
    const rest = new Uint8Array(snapshot, 16 + old_padded);
    const out = new Uint8Array(16 + padded + rest.length);
    out.set(json, 16);
    out.fill(0x20, 16 + json.length, 16 + padded);
    out.set(rest, 16 + padded);
    const header = new Int32Array(out.buffer, 0, 4);
    header.set(new Int32Array(snapshot, 0, 4));
    header[1] = 6;
    header[2] = out.length;
    header[3] = padded;
    return out.buffer;
}

const plain = state => JSON.stringify(state, (key, value) => ArrayBuffer.isView(value) ? Array.from(value) : value);
const cards = emulator => [emulator.v86.cpu.devices.net.device["card"], emulator.v86.cpu.devices.audio.device["card"]];

// a plugin file that cannot be loaded: the start fails naming it (first, and
// without the other card: a plugin already registered in the process is not
// loaded again)
for(const [options, file] of [
    [{ net_device: { type: "ne2k", plugin_path: ROOT + "build/no-such-ne2k.js" }, audio_device: "none" }, /net_device "ne2k": cannot load .*no-such-ne2k\.js/],
    [{ net_device: { type: "none" }, audio_device: "sb16", audio_device_path: ROOT + "build/no-such-sb16.js" }, /audio_device "sb16": cannot load .*no-such-sb16\.js/],
])
{
    const emulator = new V86({ ...BASE, autostart: false, ...options });
    const error = await new Promise(resolve => emulator.add_listener("emulator-error", resolve));
    assert.match(String(error && error.message), file);
    await emulator.destroy();
}
console.log("PASS: a plugin file that cannot be loaded fails the start, named");

// the defaults: an NE2000 and an SB16, plugins
const first = await boot();
const [ne2k, sb16] = cards(first);
assert.ok(ne2k && sb16);
assert.equal(first.v86.cpu.devices.net.name, "ne2k");
assert.equal(first.v86.cpu.devices.audio.name, "sb16");
assert.equal(first.v86.cpu.devices.sb16, undefined, "no core SB16");
// (the NE2000 at its I/O BAR: a read of its reset port sets ISR.RST; the SB16's DSP version)
const io = first.v86.cpu.io;
const port = first.v86.cpu.devices.pci.config_read(first.v86.cpu.devices.net.pci_id, 0x10, 4) & 0xFFFC;
io.port_write8(port, 0x21);
io.port_read8(port + 0x1F);
assert.equal(io.port_read8(port + 0x07) & 0x80, 0x80, "the NE2000's reset in ISR");
io.port_write8(0x226, 1);
io.port_write8(0x226, 0);
assert.equal(io.port_read8(0x22A), 0xAA, "the DSP's reset answer");
io.port_write8(0x22C, 0xE1);
assert.deepEqual([io.port_read8(0x22A), io.port_read8(0x22A)], [4, 5], "DSP version 4.05");
console.log("PASS: a PC machine without net_device and audio_device has the NE2000 and the SB16 plugins");

// a snapshot: format 8, the cards' slots tagged
const snapshot = await first.save_state();
const { header, info } = parse(snapshot);
assert.equal(header[1], 8, "format 8");
assert.deepEqual([info.state[59][0], info.state[59][2], info.state[61][0], info.state[61][2]], ["net_adapter", "ne2k", "audio_device", "sb16"]);
const saved = [plain(ne2k.get_state()), plain(sb16.get_state())];
await first.destroy();
console.log("PASS: a snapshot has format 8 and the cards' tagged slots");

// as before M1 (format 6, untagged): the plugins read the cards' own states
// (the saved address too: a new NE2000 has a random one, and keeps it unless told otherwise)
for(const [label, state] of [["format 8", snapshot], ["before M1", as_before_m1(snapshot)]])
{
    const machine = await boot({ preserve_mac_from_state_image: true });
    await machine.restore_state(state);
    assert.deepEqual(cards(machine).map(card => plain(card.get_state())), saved, label + ": the cards as saved");
    await machine.destroy();
}
console.log("PASS: a snapshot of the form before M1 (format 6, untagged slots) restores into the plugins as it is");

// other cards: refused before anything changes
for(const [options, message] of [
    [{ net_device: { type: "e1000" } }, /with net_device: "ne2k", this one has "e1000"/],
    [{ net_device: { type: "none" } }, /with net_device: "ne2k", this one has "none"/],
    [{ audio_device: "hd_audio" }, /with audio_device: "sb16", this one has "hd_audio"/],
    [{ audio_device: "none" }, /with audio_device: "sb16", this one has "none"/],
])
{
    for(const state of [snapshot, as_before_m1(snapshot)])
    {
        const machine = await boot(options);
        await assert.rejects(machine.restore_state(state), message);
        await machine.destroy();
    }
}
console.log("PASS: the slots of other cards are refused, tagged or not");
                             source/v64/tests/devices/device_io_reset.mjs                                                        0000755 0000000 0000000 00000011166 00000000000 016323  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// ACPI reset and S5 (docs/acpi.md): disk I/O in flight across a
// machine reset or S5. The hard disk is an embedder's asynchronous buffer whose
// reads and writes complete 100 ms later.
// - a reset while an IDE read is in flight: the read is dropped, the reset
//   IDE controller raises no interrupt for it;
// - a reset while an IDE DMA write is in flight: its completion does not
//   touch the reset channel (no interrupt, bus master status left alone);
// - a reset while an ISA DMA transfer (the floppy's path) is in flight: the
//   late data does not reach the RAM of the machine that starts after it;
// - S5 while a write is in flight: "acpi-power-off" comes only after it landed.
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SIZE = 16 << 20, LATENCY = 100;
const disk = new Uint8Array(SIZE).map((_, i) => i * 7 & 0xFF);
let writes_landed = 0;
// v86's own in-memory disk, with every read and write completing later
const { SyncBuffer } = await import("../../src/buffer.js");
const base = new SyncBuffer(disk.buffer);
const hda = Object.create(base);
hda.get = (start, length, callback) => setTimeout(() => base.get(start, length, callback), LATENCY);
hda.set = (start, data, callback) => setTimeout(() => base.set(start, data, () => { writes_landed++; callback(); }), LATENCY);

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
    hda, memory_size: 32 << 20, acpi: true, autostart: false, log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu;
const channel = cpu.devices.ide.primary, drive = channel.master;
let irqs = 0;
const raise = cpu.device_raise_irq.bind(cpu);
cpu.device_raise_irq = irq => { if(irq === channel.irq) irqs++; raise(irq); };

// an IDE read in flight, then a machine reset
let read_completed = false;
drive.read_buffer(0, 512, () => { read_completed = true; });
assert.equal(cpu["snapshot_io_pending"], 1, "the read is in flight");
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.equal(read_completed, false, "a read in flight is dropped by the reset");
assert.equal(cpu["snapshot_io_pending"], 0, "and no longer counted as pending");
console.log("ok - IDE read in flight across a reset is dropped");

// an IDE DMA write in flight (as ata_write_sectors_dma leaves it), then a reset
drive.current_command = 0xCA;
channel.dma_status = 1;
irqs = 0;
const { track_state_io } = await import("../../src/state_io.js");
const epoch = drive.reset_epoch;
track_state_io(cpu, done => drive.buffer.set(0, new Uint8Array(512).fill(0x55), done), () => {
    if(epoch !== drive.reset_epoch) return;
    drive.push_irq();
});
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.equal(disk[0], 0x55, "the write itself landed (the guest issued it)");
assert.equal(irqs, 0, "its completion raised no interrupt on the reset channel");
assert.equal(channel.dma_status, 0, "bus master status as after reset");
console.log("ok - IDE write completing after a reset does not touch the channel");

// an ISA DMA transfer in flight, then a reset: the late data stays out of RAM
const dma = cpu.devices.dma;
const target = 0x10000;
cpu.mem8.fill(0, target, target + 512);
dma.channel_page[2] = target >> 16;
dma.channel_addr[2] = target & 0xFFFF;
dma.channel_count[2] = 511;
let dma_done = false;
dma.do_read(hda, 1024, 512, 2, () => { dma_done = true; });
cpu.reboot_internal("test");
await delay(LATENCY * 3);
assert.equal(dma_done, false, "the transfer does not complete for the new machine");
assert.ok(cpu.mem8.subarray(target, target + 512).every(b => b === 0), "its data did not reach RAM");
console.log("ok - ISA DMA transfer across a reset leaves RAM alone");

// S5 while a write is in flight: the host hears of it after the write landed
const landed_before = writes_landed;
track_state_io(cpu, done => hda.set(4096, new Uint8Array(512).fill(0xAA), done), () => {});
const announced = new Promise(resolve => emulator.add_listener("acpi-power-off", resolve));
cpu.devices.acpi.power_off(5);
assert.equal(await announced, "S5");
assert.equal(writes_landed, landed_before + 1, "acpi-power-off comes after the write landed");
assert.equal(disk[4096], 0xAA);
console.log("ok - S5 is announced after disk writes in flight landed");

await emulator.destroy();
console.log("device I/O reset tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/devices/disk_error.mjs                                                             0000755 0000000 0000000 00000025314 00000000000 015336  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// What a failed disk request does (docs/disk-persistence-plan.md D0, "错误处理"):
// an IDE disk whose backend fails reads and writes on request, driven
// through the ports while the guest (a boot sector spinning in `jmp $`)
// runs.
// - disk_error "stop" (the default): the request stays unfinished, the
//   machine stops, "disk-error" tells the host (disk, operation, offset,
//   length, reason, retryable); a snapshot is refused meanwhile; run()
//   retries it and the command completes; one that cannot be retried is
//   reported to the guest (ERR/ABRT) by run(); a write held is retried;
//   a reset drops a held read; destroy() and a restored snapshot drop what
//   is held;
// - disk_error "report": the guest sees ERR/ABRT at once, the machine goes on.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SIZE = 1 << 20;

// (a class: state images take no plain objects)
class FlakyDisk
{
    constructor()
    {
        this.byteLength = SIZE;
        this.data = new Uint8Array(SIZE).map((_, i) => i * 13 + (i >> 9) & 0xFF);
        // a boot sector: jmp $
        this.data.fill(0, 0, 512);
        this.data.set([0xEB, 0xFE], 0);
        this.data.set([0x55, 0xAA], 510);
        /** the next reads and writes that fail, and whether they can be retried */
        this.fail_reads = 0;
        this.fail_writes = 0;
        this.retryable = true;
        this.reads = 0;
        this.writes = 0;
    }
    load() { this.onload?.({}); }
    error(what)
    {
        const error = new Error("the test's disk failed the " + what);
        if(!this.retryable) error.retryable = false;
        return error;
    }
    get(start, length, done)
    {
        this.reads++;
        if(this.fail_reads) { this.fail_reads--; done(undefined, this.error("read")); return; }
        done(this.data.slice(start, start + length));
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done)
    {
        this.writes++;
        if(this.fail_writes) { this.fail_writes--; done(this.error("write")); return; }
        this.data.set(data, start);
        done();
    }
    get_buffer(done) { done(undefined); }
    get_state() { return [this.data]; }
    set_state(state) { this.data.set(state[0]); }
}

async function machine(hda)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        hda,
        autostart: true,
        memory_size: 32 * 1024 * 1024,
        log_level: 0,
    });
    const events = [];
    emulator.add_listener("disk-error", event => events.push(event));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    // (SeaBIOS boots the disk: then the guest spins)
    const disk = hda.buffer || hda;
    for(let i = 0; i < 2000 && disk.reads === 0; i++) await new Promise(resolve => setTimeout(resolve, 5));
    await new Promise(resolve => setTimeout(resolve, 500));
    return { emulator, events, io: emulator.v86.cpu.io, cpu: emulator.v86.cpu };
}

const DATA = 0x1F0, ERROR = 0x1F1, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const NIEN = 0x02, SRST = 0x04, DRQ = 0x08, ERR = 0x01, BSY = 0x80, ABRT = 0x04;
const READ = 0x20, WRITE = 0x30;

function command(io, lba, count, cmd)
{
    io.port_write8(CONTROL, NIEN);
    io.port_write8(DEVICE, 0xE0 | lba >> 24 & 0x0F);
    io.port_write8(COUNT, count);
    io.port_write8(LBA_LOW, lba & 0xFF);
    io.port_write8(LBA_MID, lba >> 8 & 0xFF);
    io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
    io.port_write8(COMMAND, cmd);
}
function read_data(io, count)
{
    const bytes = new Uint8Array(count * 512);
    for(let i = 0; i < bytes.length; i += 2)
    {
        const w = io.port_read16(DATA);
        bytes[i] = w; bytes[i + 1] = w >> 8;
    }
    return bytes;
}
function write_data(io, bytes)
{
    for(let i = 0; i < bytes.length; i += 2) io.port_write16(DATA, bytes[i] | bytes[i + 1] << 8);
}
const status = io => io.port_read8(COMMAND);
const until = async (condition, what) =>
{
    for(let i = 0; i < 2000 && !condition(); i++) await new Promise(resolve => setTimeout(resolve, 2));
    assert.ok(condition(), what);
};

// --- disk_error "stop" (the default) ---------------------------------------
{
    const disk = new FlakyDisk();
    const { emulator, events, io, cpu } = await machine(disk);
    assert.ok(emulator.is_running(), "the guest runs");

    // a read fails: held, the machine stops
    disk.fail_reads = 1;
    const stopped = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 8, 2, READ);
    await stopped;
    assert.equal(emulator.is_running(), false, "the machine stopped");
    assert.equal(events.length, 1, "one disk-error event");
    assert.deepEqual(events[0], { disk: "hda", operation: "read", offset: 8 * 512, length: 1024,
        reason: "the test's disk failed the read", retryable: true, policy: "stop" });
    assert.equal(status(io) & BSY, BSY, "the command is not finished");
    assert.equal(cpu.disk_holds.length, 1);
    await assert.rejects(emulator.save_state(), /held after an I\/O error/, "no snapshot while a request is held");
    // run(): the read is retried and completes
    await emulator.run();
    assert.ok(emulator.is_running());
    await until(() => (status(io) & (BSY | DRQ)) === DRQ, "the retried read completes");
    assert.deepEqual(read_data(io, 2), disk.data.subarray(8 * 512, 10 * 512), "with the disk's data");
    assert.equal(cpu.disk_holds.length, 0);
    console.log("ok - stop: a failed read stops the machine (disk-error), run() retries it, the guest gets the data");

    // a write fails: held, retried by run(), lands
    disk.fail_writes = 1;
    const pattern = new Uint8Array(512).fill(0xA5);
    const stopped2 = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 20, 1, WRITE);
    write_data(io, pattern);
    await stopped2;
    assert.equal(events.length, 2);
    assert.equal(events[1].operation, "write");
    assert.equal(events[1].offset, 20 * 512);
    assert.notDeepEqual(disk.data.subarray(20 * 512, 21 * 512), pattern, "the write has not landed");
    assert.equal(status(io) & BSY, BSY);
    await emulator.run();
    await until(() => (status(io) & (BSY | ERR)) === 0, "the retried write completes");
    assert.deepEqual(disk.data.subarray(20 * 512, 21 * 512), pattern, "the write landed");
    console.log("ok - stop: a failed write is held, run() retries it, it lands");

    // an error that cannot be retried: held; run() reports it to the guest
    disk.fail_reads = 1;
    disk.retryable = false;
    const stopped3 = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 4, 1, READ);
    await stopped3;
    assert.equal(events[2].retryable, false);
    const reads = disk.reads;
    await emulator.run();
    await until(() => !(status(io) & BSY), "the command ends");
    assert.equal(status(io) & (ERR | DRQ), ERR, "ERR");
    assert.equal(io.port_read8(ERROR), ABRT, "ABRT");
    assert.equal(disk.reads, reads, "not retried");
    disk.retryable = true;
    command(io, 4, 1, READ);
    await until(() => (status(io) & (BSY | DRQ)) === DRQ, "the next read works");
    assert.deepEqual(read_data(io, 1), disk.data.subarray(4 * 512, 5 * 512));
    console.log("ok - stop: an error that cannot be retried is reported to the guest (ERR/ABRT) by run()");

    // a reset drops a held read
    disk.fail_reads = 1;
    const stopped4 = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 4, 1, READ);
    await stopped4;
    assert.equal(cpu.disk_holds.length, 1);
    io.port_write8(CONTROL, SRST | NIEN);
    io.port_write8(CONTROL, NIEN);
    assert.equal(cpu.disk_holds.length, 0, "the reset dropped it");
    const reads2 = disk.reads;
    await emulator.run();
    await new Promise(resolve => setTimeout(resolve, 50));
    assert.equal(disk.reads, reads2, "nothing retried");
    console.log("ok - stop: a device reset drops a held read");

    // a restored snapshot drops what is held
    await until(() => !(status(io) & BSY), "ready after the reset");
    const state = await emulator.save_state();
    disk.fail_writes = 1;
    const stopped5 = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 30, 1, WRITE);
    write_data(io, pattern);
    await stopped5;
    assert.equal(cpu.disk_holds.length, 1);
    await emulator.restore_state(state);
    assert.equal(cpu.disk_holds.length, 0, "the restore dropped it");
    const writes = disk.writes;
    await emulator.run();
    await new Promise(resolve => setTimeout(resolve, 50));
    assert.equal(disk.writes, writes, "not retried");
    console.log("ok - stop: a restored snapshot drops a held write");

    // destroy() with a request held
    disk.fail_reads = 1;
    const stopped6 = new Promise(resolve => emulator.add_listener("emulator-stopped", resolve));
    command(io, 4, 1, READ);
    await stopped6;
    await emulator.destroy();
    assert.equal(cpu.disk_holds.length, 0, "destroy() dropped it");
    console.log("ok - stop: destroy() drops a held request");
}

// --- disk_error "report" ---------------------------------------------------
{
    const disk = new FlakyDisk();
    disk.disk_error = "report";
    const { emulator, events, io } = await machine(disk);
    disk.fail_reads = 1;
    command(io, 8, 1, READ);
    await until(() => !(status(io) & BSY), "the command ends");
    assert.equal(status(io) & (ERR | DRQ), ERR, "ERR at once");
    assert.equal(io.port_read8(ERROR), ABRT, "ABRT");
    assert.equal(events.length, 1);
    assert.equal(events[0].policy, "report");
    assert.ok(emulator.is_running(), "the machine goes on");
    disk.fail_writes = 1;
    command(io, 9, 1, WRITE);
    write_data(io, new Uint8Array(512).fill(1));
    await until(() => !(status(io) & BSY), "the write ends");
    assert.equal(status(io) & ERR, ERR, "the failed write: ERR");
    assert.equal(events[1].operation, "write");
    command(io, 8, 1, READ);
    await until(() => (status(io) & (BSY | DRQ)) === DRQ, "the next read works");
    assert.deepEqual(read_data(io, 1), disk.data.subarray(8 * 512, 9 * 512));
    await emulator.destroy();
    console.log("ok - report: the guest sees ERR/ABRT at once, disk-error tells the host, the machine goes on");
}

console.log("disk error tests passed");
                                                                                                                                                                                                                                                                                                                    source/v64/tests/devices/disk_sector_size.js                                                        0000755 0000000 0000000 00000043520 00000000000 016360  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Hard disks with logical sectors of 4096 bytes (docs/disk-image-formats-plan.md,
// the appendix's "4K 逻辑扇区"), driven through the ports and AHCI's
// command structures; no guest code runs.
// - IDE (i440FX), a RAW disk with logical_sector_size 4096 next to a
//   512-byte one: IDENTIFY words 106 and 117-118 (none for the 512-byte
//   disk) and the capacity in 4096-byte sectors; READ/WRITE SECTORS with a
//   DRQ block (and an interrupt) per 4096-byte sector, READ/WRITE MULTIPLE
//   with blocks of the multiple count, READ/WRITE DMA through the bus
//   master, IDNF past the end;
// - AHCI (Q35), a VHDX image with 4096-byte sectors: IDENTIFY, DMA, PIO
//   (the PIO setup FIS's count: a sector) and NCQ reads and writes;
// - snapshots: restored onto the same disks; refused before anything is
//   restored where a disk's sector size is another;
// - options: a size that is not a multiple of the sector size, a value
//   other than 512 or 4096: emulator-error;
// - SeaBIOS does not boot from such a disk (images/msdos622.img's data):
//   it reports that it cannot read it and goes on.

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import { build_vhdx } from "../image/tiny_vhdx.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const S = 4096;
const SIZE = 8 << 20;
const pattern = new Uint8Array(SIZE).map((_, i) => i * 7 + (i >> 12) & 0xFF);

function config(extra)
{
    return {
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        autostart: false,
        memory_size: 32 * 1024 * 1024,
        log_level: 0,
        ...extra,
    };
}

async function start(extra)
{
    const emulator = new V86(config(extra));
    await new Promise((resolve, reject) =>
    {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}

// ---- IDE ------------------------------------------------------------------

const hda_bytes = pattern.slice();
const hdb_bytes = new Uint8Array(1 << 20).map((_, i) => i & 0xFF);
const ide_config = () => ({ hda: { buffer: hda_bytes.buffer, logical_sector_size: 4096 }, hdb: { buffer: hdb_bytes.buffer } });
let emulator = await start(ide_config());
let cpu = emulator.v86.cpu, io = cpu.io;
const channel = cpu.devices.ide.primary;

const DATA = 0x1F0, ERROR = 0x1F1, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const BM_COMMAND = 0xB400, BM_STATUS = 0xB402, BM_PRDT = 0xB404;
const DRQ = 0x08, ERR = 0x01, BSY = 0x80, IDNF = 0x10;
// (interrupts on: the test counts the channel's)
io.port_write8(CONTROL, 0);
let pushes = 0;
{
    const raise = cpu.device_raise_irq.bind(cpu);
    cpu.device_raise_irq = irq => { if(irq === channel.irq) pushes++; raise(irq); };
}

const status = () => io.port_read8(COMMAND);
async function until_ready()
{
    for(let i = 0; i < 1000 && status() & BSY; i++) await new Promise(resolve => setTimeout(resolve, 1));
}

function read_words(count)
{
    assert.equal(status() & (DRQ | ERR), DRQ, "data ready");
    return Array.from({ length: count }, () => io.port_read16(DATA));
}

function identify(device)
{
    io.port_write8(DEVICE, device);
    io.port_write8(COMMAND, 0xEC);
    return read_words(256);
}

/** a command of 28-bit LBA (device: 0xE0 master, 0xF0 slave) */
function command28(lba, count, command, device = 0xE0)
{
    io.port_write8(DEVICE, device | lba >> 24 & 0xF);
    io.port_write8(COUNT, count & 0xFF);
    io.port_write8(LBA_LOW, lba & 0xFF);
    io.port_write8(LBA_MID, lba >> 8 & 0xFF);
    io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
    io.port_write8(COMMAND, command);
}

function command48(lba, count, command)
{
    io.port_write8(DEVICE, 0x40);
    io.port_write8(COUNT, count >> 8);
    io.port_write8(LBA_LOW, Math.floor(lba / 2 ** 24) & 0xFF);
    io.port_write8(LBA_MID, Math.floor(lba / 2 ** 32) & 0xFF);
    io.port_write8(LBA_HIGH, Math.floor(lba / 2 ** 40) & 0xFF);
    io.port_write8(COUNT, count & 0xFF);
    io.port_write8(LBA_LOW, lba & 0xFF);
    io.port_write8(LBA_MID, lba >> 8 & 0xFF);
    io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
    io.port_write8(COMMAND, command);
}

/**
 * The data of a PIO read in DRQ blocks of `block` bytes: the device asks
 * for each block with an interrupt and DRQ, and keeps DRQ within it
 */
async function pio_in(total, block)
{
    await until_ready();
    const bytes = new Uint8Array(total);
    for(let at = 0; at < total; at += block)
    {
        const before = pushes;
        const n = Math.min(block, total - at);
        for(let i = 0; i < n; i += 2)
        {
            assert.equal(status() & (DRQ | ERR), DRQ, "DRQ within the block at " + (at + i));
            const word = io.port_read16(DATA);
            bytes[at + i] = word;
            bytes[at + i + 1] = word >> 8;
            if(i + 2 < n) assert.equal(pushes, before, "no interrupt within a block");
        }
        assert.equal(pushes, before + (at + n < total ? 1 : 0), "an interrupt for the next block");
    }
    assert.equal(status() & (DRQ | ERR | BSY), 0, "done");
    return bytes;
}

async function pio_out(bytes, block)
{
    for(let at = 0; at < bytes.length; at += block)
    {
        assert.equal(status() & (DRQ | ERR), DRQ, "ready for the block at " + at);
        const before = pushes;
        const n = Math.min(block, bytes.length - at);
        for(let i = 0; i < n; i += 2)
        {
            io.port_write16(DATA, bytes[at + i] | bytes[at + i + 1] << 8);
            if(i + 2 < n) assert.equal(pushes, before, "no interrupt within a block");
        }
        assert.equal(pushes, before + 1, "an interrupt after the block");
    }
    await until_ready();
    assert.equal(status() & (DRQ | ERR | BSY), 0, "done");
}

const PRDT = 0x10000, DMA_BUFFER = 0x100000;
async function dma(command, lba, count, out)
{
    const length = count * S;
    // two PRD entries, 8 KiB and the rest
    const prd = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset + PRDT, 16);
    prd.setUint32(0, DMA_BUFFER, true); prd.setUint16(4, 8192, true); prd.setUint16(6, 0, true);
    prd.setUint32(8, DMA_BUFFER + 8192, true); prd.setUint16(12, length - 8192, true); prd.setUint16(14, 0x8000, true);
    if(out) cpu.mem8.set(out, DMA_BUFFER);
    else cpu.mem8.fill(0xEE, DMA_BUFFER, DMA_BUFFER + length + 512);
    io.port_write8(BM_STATUS, 6);
    io.port_write32(BM_PRDT, PRDT);
    command28(lba, count, command);
    io.port_write8(BM_COMMAND, out ? 0x01 : 0x09);
    await until_ready();
    assert.equal(io.port_read8(BM_STATUS) & 3, 0, "the bus master is done, no error");
    io.port_write8(BM_COMMAND, 0);
    assert.equal(status() & (ERR | DRQ | BSY), 0, "the command is done");
    return cpu.mem8.slice(DMA_BUFFER, DMA_BUFFER + length + 512);
}

{
    const words = identify(0xE0);
    assert.equal(words[106], 0x5000, "word 106: valid, logical sectors longer than 256 words, one per physical sector");
    assert.deepEqual(words.slice(117, 119), [2048, 0], "words 117-118: 2048 words per logical sector");
    assert.equal(words[60] | words[61] << 16, SIZE / S, "words 60-61: the capacity in 4096-byte sectors");
    assert.equal(words[100] | words[101] << 16, SIZE / S, "words 100-103: likewise");
    const words_512 = identify(0xF0);
    assert.equal(words_512[106], 0, "the 512-byte disk: no word 106");
    assert.deepEqual(words_512.slice(117, 119), [0, 0]);
    assert.equal(words_512[60] | words_512[61] << 16, hdb_bytes.length / 512);
    assert.equal((await emulator.disk_image_info("hda")).logical_sector_size, 4096, "disk_image_info");
    assert.equal((await emulator.disk_image_info("hdb")).logical_sector_size, 512);
    console.log("ok - IDENTIFY: words 106 and 117-118, the capacity in 4096-byte sectors; the 512-byte disk unchanged; disk_image_info");
}

{
    command28(1, 2, 0x20);
    assert.deepEqual(await pio_in(2 * S, S), pattern.subarray(S, 3 * S), "READ SECTORS: LBA 1, two sectors");
    command48(SIZE / S - 3, 3, 0x24);
    assert.deepEqual(await pio_in(3 * S, S), pattern.subarray(SIZE - 3 * S), "READ SECTORS EXT: the last three");
    // the 512-byte disk on the same channel
    command28(3, 2, 0x20, 0xF0);
    assert.deepEqual(await pio_in(1024, 512), hdb_bytes.subarray(1536, 2560), "the 512-byte disk: blocks of 512 bytes");
    // READ MULTIPLE with 4 sectors a block
    command28(0, 4, 0xC6);
    await until_ready();
    command28(8, 6, 0xC4);
    assert.deepEqual(await pio_in(6 * S, 4 * S), pattern.subarray(8 * S, 14 * S), "READ MULTIPLE: blocks of 4 sectors");
    console.log("ok - PIO reads: a DRQ block per 4096-byte sector, READ MULTIPLE in blocks of 4 sectors");
}

{
    const data = new Uint8Array(3 * S).map((_, i) => 255 - (i * 3 & 0xFF));
    command28(20, 2, 0x30);
    await pio_out(data.subarray(0, 2 * S), S);
    assert.deepEqual(hda_bytes.subarray(20 * S, 22 * S), data.subarray(0, 2 * S), "WRITE SECTORS: in the image at LBA 20 * 4096");
    command28(0, 2, 0xC6);
    await until_ready();
    command28(30, 3, 0xC5);
    await pio_out(data, 2 * S);
    assert.deepEqual(hda_bytes.subarray(30 * S, 33 * S), data, "WRITE MULTIPLE: blocks of 2 sectors");
    command28(30, 3, 0x20);
    assert.deepEqual(await pio_in(3 * S, S), data, "read back");
    assert.deepEqual(hda_bytes.subarray(33 * S, 34 * S), pattern.subarray(33 * S, 34 * S), "the next sector unchanged");
    console.log("ok - PIO writes: WRITE SECTORS, WRITE MULTIPLE, read back");
}

{
    const read = await dma(0xC8, 40, 3);
    assert.deepEqual(read.subarray(0, 3 * S), hda_bytes.subarray(40 * S, 43 * S), "READ DMA: 3 sectors through two PRD entries");
    assert.ok(read.subarray(3 * S).every(b => b === 0xEE), "nothing beyond");
    const data = new Uint8Array(2 * S).map((_, i) => i * 13 & 0xFF);
    await dma(0xCA, 50, 2, data);
    assert.deepEqual(hda_bytes.subarray(50 * S, 52 * S), data, "WRITE DMA: in the image");
    console.log("ok - DMA: READ DMA and WRITE DMA of 4096-byte sectors through the bus master");
}

{
    command28(SIZE / S - 1, 2, 0x20);
    await until_ready();
    assert.equal(status() & (ERR | DRQ), ERR, "past the end");
    assert.equal(io.port_read8(ERROR), IDNF, "IDNF");
    command28(SIZE / S - 1, 1, 0x20);
    assert.deepEqual(await pio_in(S, S), hda_bytes.subarray(SIZE - S), "the last sector");
    console.log("ok - past the end of the disk (in 4096-byte sectors): IDNF");
}

// snapshots: the same disks, then one whose sector size is another
const state = await emulator.save_state();
const words_before = identify(0xE0);
await emulator.destroy();
{
    const same = await start(ide_config());
    await same.restore_state(state);
    cpu = same.v86.cpu; io = cpu.io;
    assert.deepEqual(identify(0xE0), words_before, "restored: the same IDENTIFY");
    await same.destroy();
    const other = await start({ hda: { buffer: hda_bytes.slice().buffer }, hdb: { buffer: hdb_bytes.slice().buffer } });
    const memory_before = other.v86.cpu.mem8.slice(0, 1 << 20);
    await assert.rejects(other.restore_state(state), /sector/, "a 512-byte disk refuses the 4096-byte disk's state");
    assert.deepEqual(other.v86.cpu.mem8.slice(0, 1 << 20), memory_before, "nothing was restored");
    assert.equal(other.v86.cpu.devices.ide.primary.master.sector_size, 512);
    await other.destroy();
    console.log("ok - snapshots: restored onto the same disks, refused where a disk's sector size differs");
}

// ---- AHCI -----------------------------------------------------------------

const vhdx_data = [[0, pattern.slice(0, 1 << 20)]];
const vhdx = build_vhdx({ size: 16 << 20, logical_sector_size: 4096, data: vhdx_data });
emulator = await start({ machine_type: "q35", memory_size: 64 << 20, hda: { buffer: vhdx.image.buffer, format: "vhdx" } });
cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const AHCI = 0x1F << 3 | 2;
const ABAR = 0xC0000000;
const r32 = offset => cpu.mmap_read32(ABAR + offset) >>> 0;
const w32 = (offset, value) => cpu.mmap_write32(ABAR + offset, value | 0);
const pr = (port, reg) => r32(0x100 + port * 0x80 + reg);
const pw = (port, reg, value) => w32(0x100 + port * 0x80 + reg, value);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const PX = { CLB: 0x00, FB: 0x08, IS: 0x10, CMD: 0x18, TFD: 0x20, SERR: 0x30, SACT: 0x34, CI: 0x38 };
const clb = 0x200000, fb = clb + 0x400, table = clb + 0x1000, BUFFER = 0x400000;
pci.config_write(AHCI, 0x24, 4, ABAR);
pci.config_write(AHCI, 0x04, 2, 0x0006);
w32(0x04, 1 << 31);
pw(0, PX.CMD, 0);
pw(0, PX.CLB, clb);
pw(0, PX.FB, fb);
mem.fill(0, clb, clb + 0x10000);
pw(0, PX.CMD, 1 << 4);
pw(0, PX.SERR, -1);
pw(0, PX.IS, -1);
pw(0, PX.CMD, 1 << 4 | 1);

/** a command in slot `slot` (its table at table + slot * 0x100) */
async function ahci(c)
{
    const slot = c.slot || 0, at = table + slot * 0x100;
    mem.fill(0, at, at + 0x100);
    const lba = c.lba || 0, count = c.count || 0, features = c.features || 0;
    mem.set([0x27, 0x80, c.command, features & 0xFF, lba & 0xFF, lba >> 8 & 0xFF, lba >> 16 & 0xFF, 0x40,
        Math.floor(lba / 2 ** 24) & 0xFF, 0, 0, features >> 8, count & 0xFF, count >> 8, 0, 0], at);
    const length = c.length;
    put32(at + 0x80, BUFFER);
    put32(at + 0x80 + 12, length - 1);
    const header = clb + slot * 32;
    put32(header, 5 | (c.write ? 1 << 6 : 0) | 1 << 16);
    put32(header + 4, 0xDEADBEEF);
    put32(header + 8, at);
    if(c.write) mem.set(c.data, BUFFER);
    else mem.fill(0xEE, BUFFER, BUFFER + length);
    pw(0, PX.IS, -1);
    if(c.queued) pw(0, PX.SACT, 1 << slot);
    pw(0, PX.CI, 1 << slot);
    for(let i = 0; i < 1000 && (pr(0, PX.CI) | pr(0, PX.SACT)) & 1 << slot; i++) await new Promise(resolve => setTimeout(resolve, 1));
    assert.equal((pr(0, PX.CI) | pr(0, PX.SACT)) & 1 << slot, 0, "the command completed");
    assert.equal(pr(0, PX.TFD) & 1, 0, "no error");
    return { data: mem.slice(BUFFER, BUFFER + length), prdbc: u32(header + 4) };
}

const disk = cpu.devices.ahci.ports[0].device;
assert.equal(disk.sector_size, 4096, "the VHDX disk's sectors");
assert.equal((await emulator.disk_image_info("hda")).logical_sector_size, 4096, "disk_image_info");
{
    const words = Array.from({ length: 256 }, (_, i) => 0);
    const { data } = await ahci({ command: 0xEC, length: 512 });
    for(let i = 0; i < 256; i++) words[i] = data[2 * i] | data[2 * i + 1] << 8;
    assert.equal(words[106], 0x5000);
    assert.deepEqual(words.slice(117, 119), [2048, 0]);
    assert.equal(words[100] | words[101] << 16, (16 << 20) / S);
    console.log("ok - AHCI: IDENTIFY of the VHDX disk with 4096-byte sectors");
}
{
    let r = await ahci({ command: 0x25, lba: 2, count: 3, length: 3 * S });
    assert.equal(r.prdbc, 3 * S);
    assert.deepEqual(r.data, pattern.subarray(2 * S, 5 * S), "READ DMA EXT");
    r = await ahci({ command: 0x20, lba: 1, count: 2, length: 2 * S });
    assert.equal(r.prdbc, 2 * S);
    assert.deepEqual(r.data, pattern.subarray(S, 3 * S), "READ SECTORS (PIO)");
    const pio_setup = mem.subarray(fb + 0x20, fb + 0x34);
    assert.equal(pio_setup[16] | pio_setup[17] << 8, S, "the PIO setup FIS: a block of one sector");
    const data = new Uint8Array(2 * S).map((_, i) => i * 5 + 1 & 0xFF);
    await ahci({ command: 0x35, lba: 300, count: 2, length: 2 * S, write: true, data });
    r = await ahci({ command: 0x25, lba: 300, count: 2, length: 2 * S });
    assert.deepEqual(r.data, data, "WRITE DMA EXT, read back (past the VHDX's data: a block not present)");
    // native command queuing: the count in the features
    const queued = new Uint8Array(S).map((_, i) => i * 11 & 0xFF);
    await ahci({ command: 0x61, features: 1, lba: 7, count: 3 << 3, slot: 3, length: S, write: true, data: queued, queued: true });
    r = await ahci({ command: 0x60, features: 3, lba: 6, count: 4 << 3, slot: 4, length: 3 * S, queued: true });
    assert.deepEqual(r.data, Uint8Array.from([...pattern.subarray(6 * S, 7 * S), ...queued, ...pattern.subarray(8 * S, 9 * S)]),
        "WRITE FPDMA QUEUED, READ FPDMA QUEUED");
    console.log("ok - AHCI: DMA, PIO (a block per sector) and NCQ reads and writes of 4096-byte sectors");
}
await emulator.destroy();

// ---- options ----------------------------------------------------------------

for(const [hda, pattern_message] of [
    [{ buffer: new ArrayBuffer(SIZE + 512), logical_sector_size: 4096 }, /not a multiple/],
    [{ buffer: new ArrayBuffer(SIZE), logical_sector_size: 2048 }, /logical_sector_size/],
])
{
    await assert.rejects(start({ hda }), error => pattern_message.test(String(error && error.message || error)));
}
console.log("ok - a size that is not a multiple of 4096, a sector size other than 512 or 4096: emulator-error");

// SeaBIOS reads disks in 512-byte sectors: it does not boot MS-DOS's disk
// as one of 4096-byte sectors, says so and goes on with the next device
{
    const image = fs.readFileSync(__dirname + "/../../images/msdos622.img");
    const machine = new V86({ ...config({ hda: { buffer: new Uint8Array(image).buffer, logical_sector_size: 4096 } }), autostart: true });
    const text = () => machine.screen_adapter ? machine.screen_adapter.get_text_screen().join("\n") : "";
    const start = Date.now();
    while(!/No bootable device/.test(text()))
    {
        assert.ok(Date.now() - start < 60000, "SeaBIOS goes on: " + text());
        await new Promise(resolve => setTimeout(resolve, 100));
    }
    assert.match(text(), /Booting from Hard Disk\.\.\.\s+Boot failed: could not read the boot disk/);
    await machine.destroy();
    console.log("ok - SeaBIOS does not boot a disk of 4096-byte sectors: it says so and tries the next device");
}
console.log("disk sector size tests passed");
                                                                                                                                                                                source/v64/tests/devices/disk_write_cache.js                                                        0000755 0000000 0000000 00000033335 00000000000 016307  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The blocks written to the lazily loaded disks (AsyncFileBuffer and
// AsyncXHRBuffer in src/buffer.js; docs/sata.md): reads see them over the
// source, they are kept in chunks of 65536 blocks (16 MiB), and a snapshot
// holds their numbers and those chunks, so the manifest of a V7 snapshot stays
// small however much was written (with 1.5 GB written, it listed millions of
// 256-byte buffers: "Invalid V7 snapshot: manifest too large"). Snapshots of
// the format before still restore. DISK_WRITE_MB=1536 writes as much as
// Windows 8.1 did installing VMware Tools (the default writes 40 MB).

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { AsyncFileBuffer } = await import("../../src/buffer.js");

const BLOCK = 256, CHUNK_BLOCKS = 0x10000;
const WRITE_MB = +(process.env.DISK_WRITE_MB || 40);

let failed = 0, passed = 0;
async function test(name, f)
{
    try
    {
        await f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

// AsyncFileBuffer over a "file" of 32 MiB whose every 32-bit word holds its own
// offset. It reads with FileReaderSync, as in the CPU worker; the slices are
// real Blobs (for get_as_file), read here from the bytes they were made of.
const SOURCE_SIZE = 32 << 20;
const source = new Uint8Array(SOURCE_SIZE);
new Uint32Array(source.buffer).forEach((_, i, words) => { words[i] = i * 4; });
const slice_bytes = new WeakMap();
const file = {
    size: SOURCE_SIZE,
    slice(start = 0, end = SOURCE_SIZE)
    {
        const bytes = source.subarray(start, end), blob = new Blob([bytes]);
        slice_bytes.set(blob, bytes);
        return blob;
    },
};
globalThis.FileReaderSync = class { readAsArrayBuffer(blob) { return slice_bytes.get(blob).slice().buffer; } };

// the data written to a block: its number, then a byte of its own
function written(index, round = 0)
{
    const data = new Uint8Array(BLOCK).fill(index * 7 + round & 255);
    new DataView(data.buffer).setFloat64(0, index * 2 + round, true);
    return data;
}
function expected(offset, length, writes)
{
    const result = source.slice(offset, offset + length);
    for(let at = 0; at < length; at += BLOCK)
    {
        const round = writes.get((offset + at) / BLOCK);
        if(round !== undefined) result.set(written((offset + at) / BLOCK, round), at);
    }
    return result;
}
function read(disk, offset, length)
{
    let result;
    disk.get(offset, length, data => { result = data.slice(); });
    assert.ok(result, "synchronous read");
    return result;
}
function write(disk, writes, index, count = 1, round = 0)
{
    const data = new Uint8Array(count * BLOCK);
    for(let i = 0; i < count; i++)
    {
        data.set(written(index + i, round), i * BLOCK);
        writes.set(index + i, round);
    }
    disk.set(index * BLOCK, data, () => {});
}

const disk = new AsyncFileBuffer(file);
const writes = new Map();

await test("reads see the blocks written over the file; a block written again keeps its slot", () => {
    assert.deepEqual(read(disk, 0x10000, 0x1000), source.subarray(0x10000, 0x11000), "nothing written: the file");
    write(disk, writes, 0x103, 3);
    write(disk, writes, 0x200);
    assert.equal(disk.written_blocks.size, 4);
    assert.equal(disk.write_chunks.length, 1);
    assert.deepEqual(read(disk, 0x10000, 0x1000), expected(0x10000, 0x1000, writes), "partly written");
    assert.deepEqual(read(disk, 0x20000, BLOCK), written(0x200), "one block, all written");
    write(disk, writes, 0x104, 1, 1);
    assert.equal(disk.written_blocks.size, 4, "the same slot");
    assert.deepEqual(read(disk, 0x10000, 0x1000), expected(0x10000, 0x1000, writes));
});

await test("get_from_cache and get_and_cache: blocks kept from reads give way to writes", () => {
    assert.equal(disk.get_from_cache(0x10300, 0x400), undefined, "not all there");
    assert.deepEqual(disk.get_from_cache(0x10300, 0x300), expected(0x10300, 0x300, writes), "all written");
    let cached;
    disk.get_and_cache(0x30000, 0x400, data => { cached = data.slice(); });
    assert.deepEqual(cached, source.subarray(0x30000, 0x30400));
    assert.equal(disk.block_cache.size, 4, "kept from the read");
    assert.deepEqual(disk.get_from_cache(0x30000, 0x400), source.subarray(0x30000, 0x30400));
    write(disk, writes, 0x301);
    assert.equal(disk.block_cache.size, 3, "the written block is not kept twice");
    assert.deepEqual(disk.get_from_cache(0x30000, 0x400), expected(0x30000, 0x400, writes));
    assert.deepEqual(read(disk, 0x2FF00, 0x600), expected(0x2FF00, 0x600, writes));
});

await test("chunks: the 65537th block written starts a second chunk", () => {
    // 65536 more blocks from block 0x10000 (offset 16 MiB), in 64 KiB writes
    for(let i = 0; i < CHUNK_BLOCKS; i += 256) write(disk, writes, 0x10000 + i, 256);
    assert.equal(disk.written_blocks.size, 5 + CHUNK_BLOCKS);
    assert.equal(disk.write_chunks.length, 2);
    assert.equal(disk.write_chunks[0].length, CHUNK_BLOCKS * BLOCK);
    assert.deepEqual(read(disk, 0x1000000, 0x1000000), expected(0x1000000, 0x1000000, writes), "16 MiB across both chunks");
});

let state;
await test("get_state: the block numbers in the order of the chunks, the last only as far as written", () => {
    state = disk.get_state();
    assert.equal(state[0], null);
    assert.ok(state[1] instanceof Float64Array);
    assert.equal(state[1].length, disk.written_blocks.size);
    assert.equal(state[2].length, 2);
    assert.equal(state[2][0].buffer, disk.write_chunks[0].buffer, "referenced, not copied");
    assert.equal(state[2][1].length, 5 * BLOCK);
    state[1].forEach((index, slot) => {
        const chunk = state[2][Math.floor(slot / CHUNK_BLOCKS)], at = slot % CHUNK_BLOCKS * BLOCK;
        if(Buffer.compare(chunk.subarray(at, at + BLOCK), written(index, writes.get(index))))
            assert.fail("slot " + slot + ": not the data of block " + index);
    });
});

await test("set_state: a full chunk is taken as it is, the last is copied; writes after the restore", () => {
    // as a restore makes them: new buffers
    const restored = [null, state[1].slice(), state[2].map(chunk => chunk.slice())];
    const other = new AsyncFileBuffer(file);
    other.get_and_cache(0, 0x400, () => {});
    other.set_state(restored);
    assert.equal(other.block_cache.size, 0, "blocks kept from reads are dropped");
    assert.equal(other.write_chunks[0], restored[2][0], "the full chunk");
    assert.equal(other.write_chunks[1].length, CHUNK_BLOCKS * BLOCK, "the last one, copied to a chunk of full size");
    assert.deepEqual(read(other, 0, 0x2000000), expected(0, 0x2000000, writes), "all 32 MiB");
    const after = new Map(writes);
    write(other, after, 0x10010, 1, 2);
    write(other, after, 0x400, 2, 2);
    assert.equal(other.written_blocks.size, disk.written_blocks.size + 2);
    assert.deepEqual(read(other, 0, 0x2000000), expected(0, 0x2000000, after));
    assert.deepEqual(read(disk, 0, 0x2000000), expected(0, 0x2000000, writes), "the original disk is unchanged");
});

await test("set_state: snapshots from before ([[block number, 256 bytes], ...])", () => {
    const other = new AsyncFileBuffer(file);
    const before = new Map([[5, 0], [0x1FFFF, 0], [6, 0]]);
    other.set_state([Array.from(before.keys(), index => [index, written(index)])]);
    assert.equal(other.written_blocks.size, 3);
    assert.deepEqual(read(other, 0, 0x1000), expected(0, 0x1000, before));
    assert.deepEqual(read(other, 0x1FFFF00, BLOCK), written(0x1FFFF));
    other.set_state([[]]);
    assert.equal(other.written_blocks.size, 0, "nothing written");
    assert.deepEqual(read(other, 0, 0x1000), source.subarray(0, 0x1000));
});

await test("set_state: invalid states", () => {
    const other = new AsyncFileBuffer(file);
    const chunk = new Uint8Array(2 * BLOCK);
    assert.throws(() => other.set_state([null, Float64Array.of(1), [chunk]]), /block numbers/, "one number for two blocks");
    assert.throws(() => other.set_state([null, Float64Array.of(1, SOURCE_SIZE / BLOCK), [chunk]]), /block numbers/, "beyond the disk");
    assert.throws(() => other.set_state([null, Float64Array.of(1, 2.5), [chunk]]), /block numbers/);
    assert.throws(() => other.set_state([null, Float64Array.of(1), [new Uint8Array(100)]]), /chunk/);
    const full = new Uint8Array(CHUNK_BLOCKS * BLOCK), twice = new Float64Array(CHUNK_BLOCKS).map((_, i) => i);
    twice[7] = 3;
    assert.throws(() => other.set_state([null, twice, [full]]), /twice/);
});

await test("get_as_file: the file with the blocks written, a part for each run of them", async () => {
    const RealFile = globalThis.File;
    let parts;
    globalThis.File = class extends RealFile { constructor(list, name) { super(list, name); parts = list.length; } };
    const file = disk.get_as_file("disk.img");
    globalThis.File = RealFile;
    assert.equal(file.name, "disk.img");
    const result = new Uint8Array(await file.arrayBuffer());
    assert.equal(result.length, SOURCE_SIZE);
    assert.ok(Buffer.from(result).equals(Buffer.from(expected(0, SOURCE_SIZE, writes))));
    // the file before 0x103, blocks 0x103-0x105, file, 0x200, file, 0x301, file,
    // 0x10000 up to the end of the first chunk, the 5 blocks in the second
    assert.equal(parts, 9);
});

// A machine whose disk (an AsyncXHRBuffer reading a file here) had WRITE_MB
// written, in 64 KiB runs, every other one
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-write-cache-"));
const image = path.join(directory, "disk.img");
const IMAGE_SIZE = Math.max(64, WRITE_MB * 2) * 1024 * 1024;
fs.writeFileSync(image, "");
fs.truncateSync(image, IMAGE_SIZE);
const RUN_BLOCKS = 256, RUNS = WRITE_MB * 16;
function run_data(run)
{
    const data = new Uint8Array(RUN_BLOCKS * BLOCK).fill(run * 13 & 255);
    const view = new DataView(data.buffer);
    for(let i = 0; i < RUN_BLOCKS; i++) view.setUint32(i * BLOCK, run * 2 * RUN_BLOCKS + i, true);
    return data;
}

async function machine()
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        hda: { url: image, async: true },
        memory_size: 32 * 1024 * 1024,
        autostart: false,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    return { emulator, disk: emulator.v86.cpu.devices.ide.primary.master.buffer };
}
function read_async(disk, offset, length)
{
    return new Promise(resolve => disk.get(offset, length, data => resolve(data.slice())));
}
async function check_disk(disk, label)
{
    for(let run = 0; run < RUNS; run++)
    {
        const offset = run * 2 * RUN_BLOCKS * BLOCK;
        const data = await read_async(disk, offset, 2 * RUN_BLOCKS * BLOCK);
        if(!Buffer.from(data.subarray(0, RUN_BLOCKS * BLOCK)).equals(Buffer.from(run_data(run))) ||
            data.subarray(RUN_BLOCKS * BLOCK).some(byte => byte !== 0))
        {
            assert.fail(label + ": run " + run + " differs");
        }
    }
}

const first = await machine();
let t = performance.now();
for(let run = 0; run < RUNS; run++) first.disk.set(run * 2 * RUN_BLOCKS * BLOCK, run_data(run), () => {});
console.log(`  ${WRITE_MB} MB written in ${Math.round(performance.now() - t)} ms: ` +
    `${first.disk.written_blocks.size} blocks, ${first.disk.write_chunks.length} chunks`);

await test("V7: the manifest stays small, and the disk is as written after a restore", async () => {
    const snapshot = path.join(directory, "state.v7");
    const out = fs.openSync(snapshot, "w");
    let size = 0;
    t = performance.now();
    await first.emulator.save_state_stream(bytes => { fs.writeSync(out, bytes); size += bytes.length; });
    fs.closeSync(out);
    const save_ms = Math.round(performance.now() - t);
    const header = new DataView(new ArrayBuffer(32));
    const fd = fs.openSync(snapshot, "r");
    fs.readSync(fd, new Uint8Array(header.buffer), 0, 32, 0);
    const manifest = header.getUint32(12, true), buffers = header.getUint32(16, true);
    console.log(`  saved ${Math.round(size / 1048576)} MB in ${save_ms} ms: manifest ${manifest} bytes, ${buffers} buffers`);
    assert.ok(size > WRITE_MB * 1024 * 1024);
    assert.ok(manifest < 256 * 1024, "manifest: " + manifest + " bytes");
    assert.ok(buffers < 1000, buffers + " buffers");

    const second = await machine();
    t = performance.now();
    await second.emulator.restore_state_stream({ size, read: async (offset, length) => {
        const bytes = new Uint8Array(length);
        assert.equal(fs.readSync(fd, bytes, 0, length, offset), length);
        return bytes;
    } });
    fs.closeSync(fd);
    console.log(`  restored in ${Math.round(performance.now() - t)} ms`);
    assert.equal(second.disk.written_blocks.size, RUNS * RUN_BLOCKS);
    await check_disk(second.disk, "restored");
    second.emulator.destroy();
    fs.rmSync(snapshot);
});

await test("V6 (save_state): the same disk after a restore", async () => {
    if(WRITE_MB > 1024) return;
    const snapshot = await first.emulator.save_state();
    const second = await machine();
    await second.emulator.restore_state(snapshot);
    await check_disk(second.disk, "restored");
    second.emulator.destroy();
});

first.emulator.destroy();
fs.rmSync(directory, { recursive: true });
console.log((failed ? "FAIL" : "PASS") + ": " + passed + " disk write cache tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                   source/v64/tests/devices/disk_writeback.mjs                                                         0000755 0000000 0000000 00000037710 00000000000 016163  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Disks written back to local files (docs/disk-persistence-plan.md D1),
// driven through the IDE ports (no guest code runs) and, for virtio-blk,
// through a queue in guest RAM of the virt machine:
// - hda read_write (a file), hdb read_only (a file read in ranges): a write
//   to hda is in the file when the command completes, FLUSH CACHE makes it
//   durable (fdatasync); hdb's file never changes;
// - IDENTIFY: hda reports a write cache, enabled (words 82, 85 bit 5); hdb
//   as before; SET FEATURES 82h turns it off (each write then durable
//   before it completes), 02h on again; the setting is in snapshots;
// - the snapshot table: read_write onto read_write, same file and
//   generation: restored; onto a read_only disk of the same file (read in
//   ranges): restored, its changes in memory dropped; a write after the
//   snapshot, a copy of the file, a read_only disk read whole: refused; a
//   read_only snapshot (changes in memory) onto read_write: refused; all
//   before anything is restored;
// - destroy() flushes and closes the file; detach_sata_drive too;
// - virtio-blk: a write is in the file, FLUSH is fdatasync, a snapshot is a
//   reference.

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const root = path.resolve(__dirname, "../..") + "/";

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-writeback-"));
const SIZE = 4 << 20;
const make = (name, fill) =>
{
    const file = path.join(temp, name);
    const data = new Uint8Array(SIZE).map((_, i) => i * fill + (i >> 9) & 0xFF);
    data.fill(0, 0, 512);
    data.set([0xEB, 0xFE], 0);
    data.set([0x55, 0xAA], 510);
    fs.writeFileSync(file, data);
    return file;
};
const hda_file = make("hda.img", 3), hdb_file = make("hdb.img", 5);
const hdb_original = fs.readFileSync(hdb_file);
const read_file = (file, offset, length) => { const b = Buffer.alloc(length); const fd = fs.openSync(file, "r"); fs.readSync(fd, b, 0, length, offset); fs.closeSync(fd); return new Uint8Array(b); };

const bios = { url: root + "bios/seabios.bin" }, vga_bios = { url: root + "bios/vgabios.bin" };
async function machine(options)
{
    const emulator = new V86({ bios, vga_bios, graphics_adapter: "none", autostart: false, memory_size: 32 << 20, log_level: 0, ...options });
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    return emulator;
}

const DATA = 0x1F0, ERROR = 0x1F1, FEATURES = 0x1F1, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const NIEN = 0x02, DRQ = 0x08, ERR = 0x01, BSY = 0x80;
function ide(emulator)
{
    const io = emulator.v86.cpu.io;
    io.port_write8(CONTROL, NIEN);
    const status = () => io.port_read8(COMMAND);
    const command = (slave, lba, count, cmd, features = 0) =>
    {
        io.port_write8(DEVICE, 0xE0 | (slave ? 0x10 : 0) | lba >> 24 & 0x0F);
        io.port_write8(FEATURES, features);
        io.port_write8(COUNT, count);
        io.port_write8(LBA_LOW, lba & 0xFF);
        io.port_write8(LBA_MID, lba >> 8 & 0xFF);
        io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
        io.port_write8(COMMAND, cmd);
    };
    const words = n => Array.from({ length: n }, () => io.port_read16(DATA));
    const write = (slave, lba, bytes) =>
    {
        command(slave, lba, bytes.length / 512, 0x30);
        for(let i = 0; i < bytes.length; i += 2) io.port_write16(DATA, bytes[i] | bytes[i + 1] << 8);
        assert.equal(status() & (BSY | ERR | DRQ), 0, "the write completed");
    };
    // (hda's reads complete at once, those of a file read in ranges later)
    const read = async (slave, lba, count) =>
    {
        command(slave, lba, count, 0x20);
        const bytes = new Uint8Array(count * 512);
        for(let s = 0; s < count; s++)
        {
            for(let i = 0; i < 1000 && status() & BSY; i++) await new Promise(resolve => setTimeout(resolve, 1));
            assert.equal(status() & (DRQ | ERR | BSY), DRQ);
            words(256).forEach((w, i) => { bytes[s * 512 + 2 * i] = w; bytes[s * 512 + 2 * i + 1] = w >> 8; });
        }
        return bytes;
    };
    const identify = slave => { command(slave, 0, 0, 0xEC); assert.equal(status() & DRQ, DRQ); return words(256); };
    const flush_cache = slave => { command(slave, 0, 0, 0xE7); assert.equal(status() & (BSY | ERR), 0); };
    const set_features = (slave, subcommand) => { command(slave, 0, 0, 0xEF, subcommand); assert.equal(status() & (BSY | ERR), 0); };
    return { status, command, write, read, identify, flush_cache, set_features, io };
}

try
{
    const options = { hda: { url: hda_file, disk_option: "read_write" }, hdb: { url: hdb_file, async: true } };
    const emulator = await machine(options);
    const cpu = emulator.v86.cpu;
    const hda = cpu.devices.ide.primary.master.buffer, hdb = cpu.devices.ide.primary.slave.buffer;
    assert.ok(hda.writeback && !hdb.writeback);
    const d = ide(emulator);

    // stop() on a stopped machine still flushes
    await call_set(hda, 0, hda.get_from_cache(0, 512));
    assert.ok(hda.dirty_since);
    await emulator.stop();
    assert.equal(hda.dirty_since, 0, "stop(): flushed");

    // writes are in the file when they complete; FLUSH CACHE: fdatasync
    const pattern = new Uint8Array(1024).fill(0x6C);
    d.write(false, 100, pattern);
    assert.deepEqual(read_file(hda_file, 100 * 512, 1024), pattern, "hda's file has the write");
    assert.deepEqual(await d.read(false, 100, 2), pattern, "and reads it back");
    const flushes = hda.flushes;
    d.flush_cache(false);
    assert.equal(hda.flushes, flushes + 1, "FLUSH CACHE: fdatasync");
    d.write(true, 100, pattern);
    assert.deepEqual(read_file(hdb_file, 0, SIZE), new Uint8Array(hdb_original), "hdb's file does not change");
    assert.deepEqual(await d.read(true, 100, 2), pattern, "hdb's write is in memory");
    console.log("ok - read_write: a completed write is in the file, FLUSH CACHE is fdatasync; read_only: the file never changes");

    // the write cache
    let id = d.identify(false);
    assert.equal(id[82] & 1 << 5, 1 << 5, "hda: write cache supported");
    assert.equal(id[85] & 1 << 5, 1 << 5, "hda: enabled");
    id = d.identify(true);
    assert.equal(id[82] & 1 << 5, 0, "hdb: as before");
    assert.equal(id[85] & 1 << 5, 0);
    d.set_features(false, 0x82);
    assert.equal(d.identify(false)[85] & 1 << 5, 0, "SET FEATURES 82h: off");
    let before = hda.flushes;
    d.write(false, 200, pattern);
    d.write(false, 202, pattern);
    assert.equal(hda.flushes, before + 2, "write cache off: each write durable before it completes");
    const saved_off = await emulator.save_state();
    d.set_features(false, 0x02);
    assert.equal(d.identify(false)[85] & 1 << 5, 1 << 5, "02h: on again");
    before = hda.flushes;
    d.write(false, 204, pattern);
    assert.equal(hda.flushes, before, "write cache on: no flush per write");
    d.set_features(true, 0x82);
    assert.equal(d.identify(true)[85] & 1 << 5, 0, "hdb: SET FEATURES taken as before, nothing reported");
    console.log("ok - IDENTIFY reports hda's write cache (words 82, 85), SET FEATURES 82h/02h turn it off/on; hdb as before");

    // snapshots
    const state = await emulator.save_state();
    await emulator.destroy();
    assert.ok(hda.closed, "destroy() closed the file");
    {
        const same = await machine(options);
        const memory = same.v86.cpu.mem8.slice(0, 1 << 16);
        await same.restore_state(state);
        const s = ide(same);
        assert.equal(s.identify(false)[85] & 1 << 5, 1 << 5, "the write cache as saved (on)");
        assert.deepEqual(await s.read(false, 204, 2), pattern);
        await assert.rejects(same.restore_state(saved_off), /in generation .* cannot go back to it/,
            "a snapshot from before later writes");
        s.write(false, 300, pattern);
        await assert.rejects(same.restore_state(state), /in generation/, "a write after the restore: the snapshot is gone");
        same.v86.cpu.mem8.set(memory);
        await same.destroy();
        console.log("ok - snapshot onto read_write, the same file in the same generation: restored; after a write: refused");
    }
    {
        const fresh = await machine(options);
        const s = ide(fresh);
        const state2 = await fresh.save_state();
        s.write(false, 400, pattern);
        const marker = new Uint8Array([1, 2, 3, 4]);
        fresh.v86.cpu.write_blob_physical(marker, 0x1000);
        await assert.rejects(fresh.restore_state(state2), /in generation/, "a write after the save");
        assert.deepEqual(fresh.v86.cpu.read_blob_physical(0x1000, 4), marker, "nothing restored");
        const now = await fresh.save_state();
        await fresh.destroy();
        // onto a read_only disk of the same file, read in ranges
        const reader = await machine({ hda: { url: hda_file, async: true }, hdb: options.hdb });
        const r = ide(reader);
        r.write(false, 400, new Uint8Array(1024).fill(0x11));
        await reader.restore_state(now);
        assert.deepEqual(await r.read(false, 400, 2), pattern, "read_only, the same file in the same generation: its changes in memory dropped");
        assert.equal(r.identify(false)[82] & 1 << 5, 0, "and no write cache");
        await reader.destroy();
        // read whole: refused
        const whole = await machine({ hda: { url: hda_file }, hdb: options.hdb });
        await assert.rejects(whole.restore_state(now), /cannot tell whether its image is that one/);
        await whole.destroy();
        // a copy of the file
        const copy = path.join(temp, "copy.img");
        fs.copyFileSync(hda_file, copy);
        const other = await machine({ hda: { url: copy, disk_option: "read_write" }, hdb: options.hdb });
        await assert.rejects(other.restore_state(now), /is \{"path":.*hda\.img.*\} in generation .*copy\.img/);
        // and a read_only snapshot (changes in memory) onto read_write
        const memory_machine = await machine({ hda: { url: copy, async: true }, hdb: options.hdb });
        ide(memory_machine).write(false, 10, pattern);
        const in_memory = await memory_machine.save_state();
        await memory_machine.destroy();
        await assert.rejects(other.restore_state(in_memory), /has its changes in memory .* not written into/);
        await other.destroy();
        console.log("ok - snapshot onto a read_only disk of the file in ranges: restored without its changes; read whole, a copy, " +
            "changes in memory onto read_write: refused");
    }

    // the same file twice
    fs.symlinkSync(hda_file, path.join(temp, "link.img"));
    await assert.rejects(machine({ hda: { url: hda_file, disk_option: "read_write" }, hdb: { url: path.join(temp, "link.img"), async: true } }),
        /hda and hdb are the same file .* an image written back has one disk/, "by another name");
    assert.throws(() => new V86({ bios, vga_bios, graphics_adapter: "none", autostart: false,
        hda: { url: hda_file, disk_option: "read_write" }, hdb: { url: hda_file, async: true } }), /hda and hdb are the same image/);
    console.log("ok - the same file as two disks, one of them read_write: refused (by the same or another name)");

    // Q35: attach and detach a write-back drive
    {
        const q35 = await machine({ machine_type: "q35", hda: { url: hdb_file, async: true } });
        await q35.attach_sata_drive(3, { url: hda_file, disk_option: "read_write" });
        const drive = q35.v86.cpu.devices.ahci.ports[3].device.buffer;
        assert.ok(drive.writeback && !drive.closed);
        await assert.rejects(q35.attach_sata_drive(4, { url: hda_file, async: true }), /sata3 and sata4 are the same image|same file/);
        await call_set(drive, 0, new Uint8Array(512).fill(9));
        q35.detach_sata_drive(3);
        assert.ok(drive.closed, "detached: flushed and closed");
        assert.equal(drive.dirty_since, 0);
        await q35.attach_sata_drive(3, { url: hda_file, disk_option: "read_write" });
        await q35.destroy();
        console.log("ok - attach_sata_drive: a write-back drive; detach_sata_drive flushes and closes it");
    }

    // virtio-blk
    {
        const virt = await machine({ cpu_type: "arm64", bios: undefined, vga_bios: undefined, wasm_path: root + "build/v86-arm64.wasm",
            virtio_disks: [{ url: hda_file, disk_option: "read_write" }] });
        const vcpu = virt.v86.cpu;
        const disk = vcpu.virtio_devices[0].device.backend.buffer;
        const transport = vcpu.virtio_mmio[31];
        const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
        const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUF = RAM + 0x20000;
        const u16 = (a, v) => vcpu.write_blob_physical(new Uint8Array([v & 0xFF, v >> 8]), a);
        const u32 = (a, v) => vcpu.write_blob_physical(new Uint8Array(new Uint32Array([v]).buffer), a);
        reg(0x070, 0); reg(0x070, 3); reg(0x024, 1); reg(0x020, 1); reg(0x024, 0); reg(0x020, 0); reg(0x070, 11);
        reg(0x030, 0); reg(0x038, 8); reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
        vcpu.write_blob_physical(new Uint8Array(0x3000), DESC);
        reg(0x044, 1); reg(0x070, 15);
        let avail = 0;
        const request = (type, sector, data) =>
        {
            const head = new Uint8Array(16);
            new DataView(head.buffer).setUint32(0, type, true);
            new DataView(head.buffer).setUint32(8, sector, true);
            vcpu.write_blob_physical(head, BUF);
            if(data) vcpu.write_blob_physical(data, BUF + 0x100);
            const desc = (i, address, length, flags, next) => { u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length); u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next); };
            desc(0, BUF, 16, 1, data ? 1 : 2);
            if(data) desc(1, BUF + 0x100, data.length, 1, 2);
            desc(2, BUF + 0x1000, 1, 2, 0);
            u16(AVAIL + 4 + 2 * (avail % 8), 0);
            u16(AVAIL + 2, ++avail);
            reg(0x050, 0);
            assert.equal(vcpu.read16_physical(USED + 2), avail, "completed");
            return vcpu.read8_physical(BUF + 0x1000);
        };
        const data = new Uint8Array(512).fill(0x3C);
        assert.equal(request(1, 50, data), 0);
        assert.deepEqual(read_file(hda_file, 50 * 512, 512), data, "virtio-blk: the write is in the file");
        const f = disk.flushes;
        assert.equal(request(4, 0), 0);
        assert.equal(disk.flushes, f + 1, "FLUSH: fdatasync");
        const virt_state = await virt.save_state();
        assert.ok(virt_state.byteLength < SIZE, "the snapshot has no disk data (" + virt_state.byteLength + " bytes)");
        await virt.destroy();
        assert.ok(disk.closed);
        const again = await machine({ cpu_type: "arm64", bios: undefined, vga_bios: undefined, wasm_path: root + "build/v86-arm64.wasm",
            virtio_disks: [{ url: hda_file, disk_option: "read_write" }] });
        await again.restore_state(virt_state);
        const reopened = again.v86.cpu.virtio_devices[0].device.backend.buffer;
        await call_set(reopened, 0, new Uint8Array(512));
        await assert.rejects(again.restore_state(virt_state), /virtio_disk0 .* in generation/, "after a write: refused");
        await again.destroy();
        console.log("ok - virtio-blk: a write is in the file, FLUSH is fdatasync, the snapshot is a reference: restored, refused after a write");
    }
}
finally
{
    fs.rmSync(temp, { recursive: true, force: true });
}

function call_set(buffer, start, data)
{
    return new Promise(resolve => buffer.set(start, data, resolve));
}
console.log("disk write-back tests passed");
                                                        source/v64/tests/devices/display.js                                                                 0000755 0000000 0000000 00000014517 00000000000 014466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The display boundary (src/display.js): the CPU Worker transport covers every
// device-facing call, and every presenter survives a text-mode save/restore.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

if(!TEST_RELEASE_BUILD)
{
    const { DisplaySinkRecorder, DISPLAY_SINK_REPLAY } = await import("../../src/display.js");

    const recorded = [];
    const recorder = new DisplaySinkRecorder((name, args) => recorded.push([name, args]), () => {});
    const font = new Uint8Array(65536).fill(7);
    const calls = [
        ["set_mode", [true]],
        ["set_size_text", [80, 25]],
        ["set_size_graphical", [640, 480, 1024, 768]],
        ["put_char", [1, 2, 65, 3, 0x112233, 0x445566]],
        ["update_cursor", [4, 5]],
        ["update_cursor_scanline", [13, 14, true]],
        ["set_font_bitmap", [16, true, false, true, font, true]],
        ["set_font_page", [1, 2]],
        ["clear_screen", []],
        ["clear_text_state", []],
    ];
    for(const [name, args] of calls) recorder[name](...args);

    assert.deepEqual(recorded.map(([name]) => name).sort(), Object.keys(DISPLAY_SINK_REPLAY).sort(),
        "every recorded call has a replay entry and vice versa");
    assert.notEqual(recorded.find(([name]) => name === "set_font_bitmap")[1][4], font,
        "the font bitmap is snapshotted, not aliased");

    const replayed = [];
    const sink = new Proxy({}, { get: (_, name) => (...args) => replayed.push([name, args]) });
    for(const [name, args] of recorded) DISPLAY_SINK_REPLAY[name](sink, args);
    assert.deepEqual(replayed, calls, "replay applies each call with its arguments");

    console.log("PASS: display sink recorder and replay table agree");
}

for(const [name, screen] of [["dummy", undefined], ["ansi", { ansi: true }]])
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        fda: { url: __dirname + "/../../images/freedos722.img" },
        screen,
        autostart: true,
        memory_size: 32 * 1024 * 1024,
        net_device: { type: "none" },
        disable_speaker: true,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));

    const booted = await emulator.wait_until_vga_screen_contains(/FreeDOS|SeaBIOS/, { timeout_msec: 60000 });
    assert.ok(booted, name + ": text appears on screen");
    const before = emulator.screen_adapter.get_text_screen().join("\n");

    const state = await emulator.save_state();
    await emulator.restore_state(state);
    const after = emulator.screen_adapter.get_text_screen().join("\n");
    assert.equal(after, before, name + ": the text screen survives a text-mode save/restore");
    if(name === "ansi") assert.match(after, /\x1B\[48;2;/, "ansi: rows carry truecolor escapes");

    await emulator.destroy();
    console.log("PASS: " + name + " presenter restores a text-mode state");
}

// Vertical retrace comes from the CRTC timing on the machine clock, not from
// the host drawing frames: in node nothing draws, and a program waiting for
// retrace must still see 70 of them per second (60 in 640x480 modes).
//
//     xor ax, ax / mov ds, ax / mov ax, MODE / int 0x10 / sti
//     mov bx, [0x46c] / mov cx, 70
//   frame: mov dx, 0x3da
//   .end:   in al, dx / test al, 8 / jnz .end     ; current retrace ends
//   .start: in al, dx / test al, 8 / jz .start    ; next one starts
//     loop frame
//     mov ax, [0x46c] / sub ax, bx                ; BIOS ticks (18.2 Hz) elapsed
//     serial: 'R', ticks, 'D' / hlt
const RETRACE_PROGRAM = [
    0x31, 0xc0, 0x8e, 0xd8, 0xb8, 0x13, 0x00, 0xcd, 0x10, 0xfb, 0x8b, 0x1e,
    0x6c, 0x04, 0xb9, 0x46, 0x00, 0xba, 0xda, 0x03, 0xec, 0xa8, 0x08, 0x75,
    0xfb, 0xec, 0xa8, 0x08, 0x74, 0xfb, 0xe2, 0xf1, 0xa1, 0x6c, 0x04, 0x29,
    0xd8, 0x88, 0xc3, 0xba, 0xf8, 0x03, 0xb0, 0x52, 0xee, 0x88, 0xd8, 0xee,
    0xb0, 0x44, 0xee, 0xf4, 0xeb, 0xfd,
];
const RETRACE_PROGRAM_MODE_OFFSET = 5;

async function count_retrace_ticks(mode, cpu_clock)
{
    const floppy = new Uint8Array(1474560);
    floppy.set(RETRACE_PROGRAM);
    floppy[RETRACE_PROGRAM_MODE_OFFSET] = mode;
    floppy[510] = 0x55;
    floppy[511] = 0xAA;

    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        fda: { buffer: floppy.buffer },
        boot_order: 0x321,
        autostart: true,
        memory_size: 32 * 1024 * 1024,
        net_device: { type: "none" },
        disable_speaker: true,
        cpu_clock,
        log_level: 0,
    });
    const output = [];
    const done = new Promise(resolve => emulator.add_listener("serial0-output-byte", byte => {
        output.push(byte);
        if(byte === 0x44 && output.length >= 3 && output[output.length - 3] === 0x52) resolve();
    }));
    const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error(
        "mode " + mode.toString(16) + ": the program never saw 70 retraces")), 120000));
    await Promise.race([done, timeout]);
    await emulator.destroy();
    return output[output.length - 2];
}

for(const [mode, hz] of [[0x03, 70], [0x13, 70], [0x12, 60]])
{
    const ticks = await count_retrace_ticks(mode);
    const expected = 70 / hz * 18.2065;
    assert.ok(Math.abs(ticks - expected) <= 4,
        `mode ${mode.toString(16)}: 70 retraces took ${ticks} ticks, expected about ${expected.toFixed(1)}`);
    console.log(`PASS: mode ${mode.toString(16)} retraces at about ${hz} Hz (${ticks} ticks for 70)`);
}

{
    const deterministic = { mode: "deterministic" };
    const first = await count_retrace_ticks(0x13, deterministic);
    const second = await count_retrace_ticks(0x13, deterministic);
    assert.equal(first, second, "deterministic clock: retrace timing is reproducible");
    assert.ok(Math.abs(first - 18.2) <= 4, `deterministic clock: ${first} ticks for 70 retraces`);
    console.log(`PASS: deterministic clock reproduces retrace timing (${first} ticks twice)`);
}
                                                                                                                                                                                 source/v64/tests/devices/e1000.js                                                                   0000755 0000000 0000000 00000103346 00000000000 013545  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The e1000 network card (net_device.type "e1000", an Intel 82540EM, the
// plugin of src/net_adapters/e1000/), driven through its registers and
// descriptor rings in guest memory; no guest code runs, the test moves the
// machine clock (docs/modern-pc-devices-plan.md, N1): PCI identity, the
// EEPROM (EERD and Microwire), the PHY over MDIC and auto-negotiation,
// transmit (legacy, context and data descriptors, checksum offload, TSO,
// VLAN, ring wrap), receive (filters, buffers across descriptors, FCS, the
// FIFO without descriptors, checksums, VLAN), interrupts and their
// moderation, statistics, resets and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

let host = 1000;
const options = {
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 32 * 1024 * 1024,
    net_device: { type: "e1000" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
};
const emulator = new V86(options);
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
// (the v86 layout: the NE2000's slot)
const E1000 = 0x05 << 3;
const BAR = 0xC0000000;
cpu.clock.resume();

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

// --- helpers ---------------------------------------------------------------

const R = {
    CTRL: 0x0000, STATUS: 0x0008, EECD: 0x0010, EERD: 0x0014, MDIC: 0x0020, VET: 0x0038,
    ICR: 0x00C0, ITR: 0x00C4, ICS: 0x00C8, IMS: 0x00D0, IMC: 0x00D8, RCTL: 0x0100, TCTL: 0x0400, PBA: 0x1000,
    RDBAL: 0x2800, RDBAH: 0x2804, RDLEN: 0x2808, RDH: 0x2810, RDT: 0x2818, RDTR: 0x2820, RADV: 0x282C,
    TDBAL: 0x3800, TDBAH: 0x3804, TDLEN: 0x3808, TDH: 0x3810, TDT: 0x3818, TIDV: 0x3820, TADV: 0x382C,
    MPC: 0x4010, GPRC: 0x4074, GPTC: 0x4080, GORCL: 0x4088, GORCH: 0x408C, RNBC: 0x40A0, ROC: 0x40AC, TPR: 0x40D0,
    TPT: 0x40D4, TSCTC: 0x40F8,
    RXCSUM: 0x5000, MTA: 0x5200, RA: 0x5400, VFTA: 0x5600,
};
const ICR_TXDW = 1, ICR_TXQE = 2, ICR_LSC = 4, ICR_RXDMT0 = 1 << 4, ICR_RXO = 1 << 6, ICR_RXT0 = 1 << 7, ICR_MDAC = 1 << 9;
const RCTL_EN = 2, RCTL_UPE = 8, RCTL_MPE = 16, RCTL_LPE = 32, RCTL_BAM = 1 << 15, RCTL_VFE = 1 << 18, RCTL_SECRC = 1 << 26;
const BSIZE_256 = 3 << 16;
const TCTL_EN = 2;
const CTRL_RST = 1 << 26, CTRL_VME = 1 << 30;
const STATUS_LU = 2;
// transmit descriptor commands (second dword)
const EOP = 1 << 24, IFCS = 1 << 25, IC = 1 << 26, TSE = 1 << 26, RS = 1 << 27, DEXT = 1 << 29, VLE = 1 << 30, IDE = 1 << 31,
    DTYP_D = 1 << 20, CMD_TCP = 1 << 24, CMD_IP = 1 << 25;
const IXSM = 1, TXSM = 2;
// receive status and errors
const DD = 1, RX_EOP = 2, RX_IXSM = 4, VP = 8, TCPCS = 1 << 5, IPCS = 1 << 6;
const TCPE = 1 << 5;

const r32 = offset => cpu.mmap_read32(BAR + offset) >>> 0;
const w32 = (offset, value) => cpu.mmap_write32(BAR + offset, value | 0);
const u16 = a => mem[a] | mem[a + 1] << 8;
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const be16 = (b, o) => b[o] << 8 | b[o + 1];
const be32 = (b, o) => (b[o] << 24 | b[o + 1] << 16 | b[o + 2] << 8 | b[o + 3]) >>> 0;
const irq = () => !!pci.intx_levels[E1000];

/** The card (the plugin's device object) */
const card = () => cpu.devices.net.device["card"];

/** Move the machine clock on and run the machine's timers */
function advance(ms)
{
    host += ms;
    cpu.run_hardware_timers(false, cpu.clock.now());
}

/** Frames the card sent */
let sent = [];
emulator.add_listener("net0-send", frame => sent.push(new Uint8Array(frame)));
const receive = frame => emulator.bus.send("net0-receive", frame);

// An independent RFC 1071 checksum
function csum(bytes, start = 0, end = bytes.length, sum = 0)
{
    for(let i = start; i < end; i += 2) sum += bytes[i] << 8 | (i + 1 < end ? bytes[i + 1] : 0);
    while(sum > 0xFFFF) sum = (sum & 0xFFFF) + Math.floor(sum / 0x10000);
    return sum;
}
const valid = (bytes, start, end, sum = 0) => csum(bytes, start, end, sum) === 0xFFFF;

const MAC = () => Array.from(card().mac);
const OTHER = [0x52, 0x54, 0x00, 0x12, 0x34, 0x56];

function eth(dst, src, type, payload)
{
    const f = new Uint8Array(14 + payload.length);
    f.set(dst); f.set(src, 6); f[12] = type >> 8; f[13] = type; f.set(payload, 14);
    return f;
}
/** An IPv4 header (no options) and payload; checksum filled unless zero_sum */
function ipv4(protocol, payload, { id = 0x1234, zero_sum = false, length } = {})
{
    const p = new Uint8Array(20 + payload.length);
    p[0] = 0x45; p[8] = 64; p[9] = protocol;
    const total = length === undefined ? p.length : length;
    p[2] = total >> 8; p[3] = total; p[4] = id >> 8; p[5] = id;
    p.set([10, 0, 2, 15], 12); p.set([10, 0, 2, 2], 16);
    if(!zero_sum) { const s = ~csum(p, 0, 20) & 0xFFFF; p[10] = s >> 8; p[11] = s; }
    p.set(payload, 20);
    return p;
}
/** TCP or UDP over IPv4 with a valid checksum (pseudo-header from ipv4's addresses) */
function l4(protocol, data, { seq = 1000, flags = 0x18 } = {})
{
    const header = protocol === 6 ? 20 : 8;
    const s = new Uint8Array(header + data.length);
    s[0] = 0x30; s[1] = 0x39; s[2] = 0x00; s[3] = 0x50;
    if(protocol === 6)
    {
        s[4] = seq >>> 24; s[5] = seq >> 16; s[6] = seq >> 8; s[7] = seq;
        s[12] = 0x50; s[13] = flags; s[14] = 0xFF; s[15] = 0xFF;
    }
    else
    {
        s[4] = s.length >> 8; s[5] = s.length;
    }
    s.set(data, header);
    const at = protocol === 6 ? 16 : 6;
    const sum = ~csum(s, 0, s.length, pseudo(protocol, s.length)) & 0xFFFF || 0xFFFF;
    s[at] = sum >> 8; s[at + 1] = sum;
    return s;
}
const pseudo = (protocol, length) => csum(Uint8Array.of(10, 0, 2, 15, 10, 0, 2, 2)) + protocol + length;
const bytes = (n, seed = 1) => Uint8Array.from({ length: n }, (_, i) => i * seed + 7 & 0xFF);

/** Check an IPv4 TCP/UDP frame's checksums */
function check_frame(f, what)
{
    assert.ok(valid(f, 14, 34), what + ": IP header checksum");
    const total = be16(f, 16), protocol = f[23];
    assert.ok(valid(f, 34, 14 + total, pseudo(protocol, total - 20)), what + ": " + (protocol === 6 ? "TCP" : "UDP") + " checksum");
}

// rings in guest memory
const TX_RING = 0x100000, TX_BUF = 0x110000, RX_RING = 0x200000, RX_BUF = 0x210000;
const TX_COUNT = 8, RX_COUNT = 8;
let tx_buf_next = TX_BUF;

function tx_buffer(data)
{
    const at = tx_buf_next;
    mem.set(data, at);
    tx_buf_next += data.length + 15 & ~15;
    if(tx_buf_next > TX_BUF + 0x80000) tx_buf_next = TX_BUF;
    return at;
}
function tx_desc(i, lower_low, lower_high, upper_low, upper_high)
{
    const a = TX_RING + 16 * i;
    put32(a, lower_low); put32(a + 4, lower_high); put32(a + 8, upper_low); put32(a + 12, upper_high);
}
/** legacy: buffer, length | CSO << 16 | CMD; STA | CSS << 8 | special << 16 */
const legacy = (i, data, cmd, { cso = 0, css = 0, special = 0 } = {}) =>
    tx_desc(i, tx_buffer(data), 0, data.length | cso << 16 | cmd, css << 8 | special << 16);
const context = (i, { ipcss = 14, ipcso = 24, ipcse = 33, tucss = 34, tucso, tucse = 0, paylen = 0, tucmd, hdrlen = 0, mss = 0 }) =>
    tx_desc(i, ipcss | ipcso << 8 | ipcse << 16, tucss | tucso << 8 | tucse << 16, paylen | DEXT | tucmd, hdrlen << 8 | mss << 16);
const data_desc = (i, data, dcmd, popts = 0, special = 0) =>
    tx_desc(i, tx_buffer(data), 0, data.length | DEXT | DTYP_D | dcmd, popts << 8 | special << 16);
const tx_status = i => mem[TX_RING + 16 * i + 12] & 0xF;

function setup_tx()
{
    w32(R.TDBAL, TX_RING); w32(R.TDBAH, 0); w32(R.TDLEN, TX_COUNT * 16);
    w32(R.TDH, 0); w32(R.TDT, 0);
    mem.fill(0, TX_RING, TX_RING + TX_COUNT * 16);
    w32(R.TCTL, TCTL_EN);
    sent = [];
}

const rx_buffer = i => RX_BUF + i * 0x4000;
/** (a ring is a multiple of eight descriptors, RDLEN of 128 bytes) */
function setup_rx(rctl, count = RX_COUNT)
{
    w32(R.RCTL, 0);
    for(let i = 0; i < RX_COUNT; i++)
    {
        const a = RX_RING + 16 * i;
        mem.fill(0, a, a + 16);
        put32(a, rx_buffer(i));
        mem.fill(0xCC, rx_buffer(i), rx_buffer(i) + 0x4000);
    }
    w32(R.RDBAL, RX_RING); w32(R.RDBAH, 0); w32(R.RDLEN, count * 16);
    w32(R.RDH, 0); w32(R.RDT, count - 1);
    w32(R.RCTL, rctl);
}
const rx = i => {
    const a = RX_RING + 16 * i;
    return { length: u16(a + 8), csum: u16(a + 10), status: mem[a + 12], errors: mem[a + 13], special: u16(a + 14),
        data: mem.slice(rx_buffer(i), rx_buffer(i) + u16(a + 8)) };
};

/** A reference FCS (bitwise CRC-32) */
function fcs(f)
{
    let c = ~0;
    for(const b of f) { c ^= b; for(let k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; }
    return ~c >>> 0;
}

// --- PCI ---------------------------------------------------------------------

test("PCI: 8086:100E, subsystem 8086:001E, Ethernet, INTA, power management, no MSI", () => {
    const space = pci.space_bytes(E1000);
    const word = o => space[o] | space[o + 1] << 8;
    assert.equal(word(0), 0x8086);
    assert.equal(word(2), 0x100E);
    assert.equal(word(0x2C), 0x8086);
    assert.equal(word(0x2E), 0x001E);
    assert.deepEqual([space[0x0B], space[0x0A], space[0x09]], [2, 0, 0], "class 02/00/00");
    assert.equal(space[0x3D], 1, "INTA");
    assert.ok(word(6) & 0x10, "capabilities list");
    assert.equal(space[0x34], 0xDC);
    assert.equal(space[0xDC], 0x01, "power management");
    assert.equal(space[0xDD], 0, "the only capability (no MSI)");
    assert.equal(word(0xDE), 0xC822);
});

test("PCI: BAR0 is 128 KiB of memory, BAR1 64 I/O ports", () => {
    pci.config_write(E1000, 0x10, 4, -1);
    const space = pci.space_bytes(E1000);
    const dword = o => (space[o] | space[o + 1] << 8 | space[o + 2] << 16 | space[o + 3] << 24) >>> 0;
    assert.equal(dword(0x10), 0xFFFE0000, "BAR0 size");
    const io = dword(0x14);
    assert.equal(io & 1, 1, "BAR1: I/O");
    pci.config_write(E1000, 0x14, 4, -1);
    assert.equal(dword(0x14), 0xFFFFFFC1, "BAR1 size");
    pci.config_write(E1000, 0x14, 4, io);
    pci.config_write(E1000, 0x10, 4, BAR);
    assert.equal(r32(R.STATUS), 0xFFFFFFFF, "not decoded while memory space is off");
    pci.config_write(E1000, 0x04, 2, 0x0007);
    assert.ok(r32(R.STATUS) & STATUS_LU, "decoded: link up");
});

test("PCI: the power management capability keeps its read-only bytes; PMCSR takes D3 and back", () => {
    pci.config_write(E1000, 0xDC, 4, 0);
    pci.config_write(E1000, 0xE0, 2, 0x8103);
    const space = pci.space_bytes(E1000);
    assert.deepEqual(Array.from(space.subarray(0xDC, 0xE2)), [0x01, 0x00, 0x22, 0xC8, 0x03, 0x01]);
    pci.config_write(E1000, 0xE0, 2, 0);
    assert.equal(space[0xE0], 0);
});

test("I/O BAR: IOADDR selects a register, IODATA reaches it", () => {
    const space = pci.space_bytes(E1000);
    const io = (space[0x14] | space[0x15] << 8) & ~3;
    cpu.io.port_write32(io, R.STATUS);
    assert.equal(cpu.io.port_read32(io + 4) >>> 0, r32(R.STATUS));
    cpu.io.port_write32(io, R.VET);
    cpu.io.port_write32(io + 4, 0x8100);
    assert.equal(r32(R.VET), 0x8100);
});

// --- EEPROM and PHY ------------------------------------------------------------

function eerd(word)
{
    w32(R.EERD, word << 8 | 1);
    const value = r32(R.EERD);
    assert.ok(value & 0x10, "EERD: done");
    return value >>> 16;
}
function microwire(word)
{
    const CS = 2, SK = 1, DI = 4, DO = 8;
    let eecd = r32(R.EECD) & ~0xF;
    const write = v => { eecd = v; w32(R.EECD, v); };
    write(eecd | CS);
    const shift_out = (value, bits) => {
        for(let i = bits - 1; i >= 0; i--)
        {
            const di = value >> i & 1 ? DI : 0;
            write(eecd & ~DI | di);
            write(eecd | SK);
            write(eecd & ~SK);
        }
    };
    shift_out(6, 3);
    shift_out(word, 6);
    let value = 0;
    for(let i = 0; i < 16; i++)
    {
        write(eecd | SK);
        value = value << 1 | (r32(R.EECD) & DO ? 1 : 0);
        write(eecd & ~SK);
    }
    write(eecd & ~CS);
    return value;
}

test("EEPROM: 64 words summing to 0xBABA, the address and IDs (EERD)", () => {
    let sum = 0;
    const words = [];
    for(let i = 0; i < 64; i++) { words.push(eerd(i)); sum += words[i]; }
    assert.equal(sum & 0xFFFF, 0xBABA, "checksum");
    const mac = MAC();
    assert.deepEqual(words.slice(0, 3), [mac[0] | mac[1] << 8, mac[2] | mac[3] << 8, mac[4] | mac[5] << 8]);
    assert.deepEqual(words.slice(0x0B, 0x0F), [0x001E, 0x8086, 0x100E, 0x8086], "subsystem and device");
    assert.equal(r32(R.RA), (mac[0] | mac[1] << 8 | mac[2] << 16 | mac[3] << 24) >>> 0, "RAL0");
    assert.equal(r32(R.RA + 4), (mac[4] | mac[5] << 8 | 1 << 31) >>> 0, "RAH0: address valid");
    assert.deepEqual([0, 1, 2, 0x0B, 0x3F].map(microwire), [0, 1, 2, 0x0B, 0x3F].map(eerd), "Microwire reads the same words");
    assert.equal(r32(R.EECD) & 0x380, 0x180, "present, granted, 64 words");
});

function mdic(op, reg, data = 0, phy = 1)
{
    w32(R.MDIC, op << 26 | phy << 21 | reg << 16 | data);
    const value = r32(R.MDIC);
    assert.ok(value & 1 << 28, "MDIC: ready");
    return value;
}

test("PHY: an 88E1011 at address 1 (the ID Intel's driver checks), 1000 Mb/s full duplex", () => {
    assert.equal(mdic(2, 2) & 0xFFFF, 0x0141);
    assert.equal(mdic(2, 3) & 0xFFFF, 0x0C20);
    assert.ok(mdic(2, 1) & 0x24, "BMSR: link, auto-negotiation complete");
    assert.ok(mdic(2, 3, 0, 2) & 1 << 30, "no PHY at address 2");
    const status = r32(R.STATUS);
    assert.equal(status & 0xC3, 0x83, "STATUS: full duplex, link up, 1000 Mb/s");
    mdic(1, 4, 0x01E1);
    assert.equal(mdic(2, 4) & 0xFFFF, 0x01E1, "ANAR is writable");
    mdic(1, 2, 0x1234);
    assert.equal(mdic(2, 2) & 0xFFFF, 0x0141, "the ID is read-only");
});

test("PHY: restarting auto-negotiation takes the link down, LSC when it is back; MDAC", () => {
    w32(R.IMS, ICR_LSC | ICR_MDAC);
    r32(R.ICR);
    mdic(1, 0, 0x1340);
    assert.equal(r32(R.STATUS) & STATUS_LU, 0, "link down");
    assert.equal(mdic(2, 1) & 4, 0);
    advance(50);
    assert.equal(r32(R.STATUS) & STATUS_LU, 0, "still negotiating");
    advance(60);
    assert.ok(r32(R.STATUS) & STATUS_LU, "link up again");
    assert.ok(irq());
    assert.equal(r32(R.ICR) & ICR_LSC, ICR_LSC);
    assert.ok(!irq(), "ICR read: INTA released");
    w32(R.MDIC, 2 << 26 | 1 << 21 | 1 << 16 | 1 << 29);
    assert.equal(r32(R.ICR) & ICR_MDAC, ICR_MDAC, "MDIC with interrupt enable: MDAC");
    w32(R.IMC, -1);
});

// --- interrupts ---------------------------------------------------------------

test("interrupts: ICS sets causes, IMS/IMC mask, ICR reads to clear and writes one to clear", () => {
    w32(R.IMC, -1);
    r32(R.ICR);
    w32(R.ICS, ICR_RXT0 | ICR_TXDW);
    assert.ok(!irq(), "masked");
    assert.equal(r32(R.IMS), 0);
    w32(R.IMS, ICR_RXT0);
    assert.ok(irq(), "unmasked: INTA");
    assert.equal(r32(R.IMS), ICR_RXT0);
    w32(R.IMC, ICR_RXT0);
    assert.ok(!irq());
    w32(R.IMS, ICR_RXT0);
    w32(R.ICR, ICR_RXT0);
    assert.ok(!irq(), "write one to clear");
    assert.equal(r32(R.ICR), ICR_TXDW, "the rest stays until read");
    assert.equal(r32(R.ICR), 0, "read to clear");
    w32(R.IMC, -1);
});

test("interrupts: ITR spaces rising edges by its interval (256 ns units)", () => {
    w32(R.ITR, 1000);
    w32(R.IMS, ICR_RXT0);
    w32(R.ICS, ICR_RXT0);
    assert.ok(irq(), "the first at once");
    r32(R.ICR);
    w32(R.ICS, ICR_RXT0);
    assert.ok(!irq(), "the next waits (256 us)");
    advance(0.1);
    assert.ok(!irq());
    advance(0.2);
    assert.ok(irq(), "after the interval");
    r32(R.ICR);
    w32(R.ITR, 0);
    w32(R.IMC, -1);
});

// --- transmit -----------------------------------------------------------------

test("transmit: legacy descriptors, a frame in two buffers, RS writes DD, TXDW and TXQE", () => {
    setup_tx();
    w32(R.IMS, ICR_TXDW);
    r32(R.ICR);
    const frame = eth(OTHER, MAC(), 0x0800, bytes(100));
    legacy(0, frame.subarray(0, 20), 0);
    legacy(1, frame.subarray(20), EOP | IFCS | RS);
    w32(R.TDT, 2);
    assert.equal(sent.length, 1);
    assert.deepEqual(sent[0], frame);
    assert.equal(r32(R.TDH), 2);
    assert.equal(tx_status(0), 0, "no RS: not written back");
    assert.equal(tx_status(1), DD);
    assert.ok(irq(), "TXDW");
    assert.equal(r32(R.ICR), ICR_TXDW | ICR_TXQE);
    assert.equal(r32(R.TPT), 1);
    assert.equal(r32(R.GPTC), 1);
    w32(R.IMC, -1);
});

test("transmit: the ring wraps; TCTL.EN off holds the queue", () => {
    sent = [];
    for(let n = 0; n < 7; n++) legacy((2 + n) % TX_COUNT, eth(OTHER, MAC(), 0x88B5, bytes(50, n + 1)), EOP | RS);
    w32(R.TCTL, 0);
    w32(R.TDT, 1);
    assert.equal(sent.length, 0, "transmitter off");
    w32(R.TCTL, TCTL_EN);
    assert.equal(sent.length, 7);
    assert.equal(r32(R.TDH), 1);
    sent.forEach((f, n) => assert.equal(f[14 + 1], 7 + n + 1 & 0xFF, "in ring order"));
    r32(R.ICR);
});

test("transmit: bus mastering off holds the queue until it is on", () => {
    sent = [];
    legacy(1, eth(OTHER, MAC(), 0x88B5, bytes(50)), EOP | RS);
    pci.config_write(E1000, 0x04, 2, 0x0003);
    w32(R.TDT, 2);
    assert.equal(sent.length, 0);
    pci.config_write(E1000, 0x04, 2, 0x0007);
    assert.equal(sent.length, 1);
    r32(R.ICR);
});

test("transmit: IP and UDP checksums inserted (context + data descriptors)", () => {
    setup_tx();
    const udp = l4(17, bytes(301, 3));
    // the driver leaves the pseudo header's sum in the UDP checksum
    const ps = csum(new Uint8Array(0), 0, 0, pseudo(17, udp.length));
    udp[6] = ps >> 8; udp[7] = ps;
    const frame = eth(OTHER, MAC(), 0x0800, ipv4(17, udp, { zero_sum: true }));
    context(0, { tucso: 34 + 6, tucmd: CMD_IP });
    data_desc(1, frame.subarray(0, 34), 0, IXSM | TXSM);
    data_desc(2, frame.subarray(34), EOP | RS);
    w32(R.TDT, 3);
    assert.equal(sent.length, 1);
    check_frame(sent[0], "UDP");
    assert.equal(tx_status(2), DD);
    r32(R.ICR);
});

test("transmit: a legacy descriptor's checksum (IC, CSO, CSS)", () => {
    sent = [];
    const payload = bytes(77);
    const frame = eth(OTHER, MAC(), 0x88B5, new Uint8Array(2 + payload.length));
    frame.set(payload, 16);
    legacy(3, frame, EOP | IC | RS, { cso: 14, css: 16 });
    w32(R.TDT, 4);
    assert.equal(be16(sent[0], 14), ~csum(payload) & 0xFFFF);
    r32(R.ICR);
});

test("transmit: TSO cuts a TCP stream into MSS segments (lengths, IDs, sequence, PSH, checksums)", () => {
    setup_tx();
    const payload = bytes(2500, 5);
    const tcp = l4(6, new Uint8Array(0), { seq: 0x10000000, flags: 0x18 });
    // what drivers leave for TSO: no IP length and checksum, the pseudo header's sum without length
    const ps = csum(new Uint8Array(0), 0, 0, pseudo(6, 0));
    tcp[16] = ps >> 8; tcp[17] = ps;
    const header = eth(OTHER, MAC(), 0x0800, ipv4(6, tcp, { zero_sum: true, length: 0, id: 0x4000 }));
    assert.equal(header.length, 54);
    context(0, { tucso: 34 + 16, tucmd: CMD_IP | CMD_TCP | TSE, paylen: 2500, hdrlen: 54, mss: 1000 });
    data_desc(1, header, TSE, IXSM | TXSM);
    data_desc(2, payload.subarray(0, 1200), TSE);
    data_desc(3, payload.subarray(1200), TSE | EOP | RS);
    r32(R.TSCTC);
    w32(R.TDT, 4);
    assert.equal(sent.length, 3);
    sent.forEach((f, n) => {
        const size = n < 2 ? 1000 : 500;
        assert.equal(f.length, 54 + size, "segment " + n);
        assert.equal(be16(f, 16), 40 + size, "IP total length");
        assert.equal(be16(f, 18), 0x4000 + n, "IP identification");
        assert.equal(be32(f, 38), 0x10000000 + 1000 * n, "sequence number");
        assert.equal(f[47] & 8, n < 2 ? 0 : 8, "PSH on the last segment only");
        assert.deepEqual(f.subarray(54), payload.subarray(1000 * n, 1000 * n + size));
        check_frame(f, "segment " + n);
    });
    assert.equal(r32(R.TSCTC), 1);
    r32(R.ICR);
});

test("transmit: VLAN tag inserted (CTRL.VME, VLE)", () => {
    setup_tx();
    w32(R.CTRL, r32(R.CTRL) | CTRL_VME);
    w32(R.VET, 0x8100);
    const frame = eth(OTHER, MAC(), 0x0800, bytes(60));
    legacy(0, frame, EOP | RS | VLE, { special: 0x2123 });
    w32(R.TDT, 1);
    assert.deepEqual(Array.from(sent[0].subarray(12, 16)), [0x81, 0x00, 0x21, 0x23]);
    assert.deepEqual(sent[0].subarray(16), frame.subarray(12));
    w32(R.CTRL, r32(R.CTRL) & ~CTRL_VME);
    r32(R.ICR);
});

test("transmit: IDE delays TXDW by TIDV, at most TADV after the first", () => {
    setup_tx();
    w32(R.TIDV, 100);
    w32(R.TADV, 150);
    w32(R.IMS, ICR_TXDW);
    r32(R.ICR);
    legacy(0, eth(OTHER, MAC(), 0x88B5, bytes(50)), EOP | RS | IDE);
    w32(R.TDT, 1);
    assert.ok(!irq(), "delayed");
    advance(0.07);
    legacy(1, eth(OTHER, MAC(), 0x88B5, bytes(50)), EOP | RS | IDE);
    w32(R.TDT, 2);
    advance(0.07);
    assert.ok(!irq(), "TIDV restarted by the second");
    advance(0.02);
    assert.ok(irq(), "TADV (153.6 us) after the first");
    r32(R.ICR);
    w32(R.TIDV, 0); w32(R.TADV, 0);
    w32(R.IMC, -1);
});

// --- receive ------------------------------------------------------------------

test("receive: unicast to RA[0] into a descriptor, FCS kept (SECRC off), RXT0", () => {
    setup_rx(RCTL_EN | RCTL_BAM);
    w32(R.IMS, ICR_RXT0);
    r32(R.ICR);
    const frame = eth(MAC(), OTHER, 0x88B5, bytes(100));
    receive(frame);
    const d = rx(0);
    assert.equal(d.length, frame.length + 4);
    assert.equal(d.status & (DD | RX_EOP), DD | RX_EOP);
    assert.deepEqual(d.data.subarray(0, frame.length), frame);
    const crc = fcs(frame);
    assert.deepEqual(Array.from(d.data.subarray(frame.length)), [crc & 0xFF, crc >>> 8 & 0xFF, crc >>> 16 & 0xFF, crc >>> 24]);
    assert.equal(r32(R.RDH), 1);
    assert.ok(irq());
    assert.equal(r32(R.ICR) & ICR_RXT0, ICR_RXT0);
    assert.equal(r32(R.GPRC), 1);
    assert.equal(r32(R.GORCL), frame.length + 4);
});

test("receive: short frames padded to 60 bytes", () => {
    receive(eth(MAC(), OTHER, 0x88B5, bytes(10)));
    assert.equal(rx(1).length, 64);
    assert.equal(r32(R.RDH), 2);
});

test("receive filter: other unicast, broadcast (BAM), multicast (MTA, MPE), promiscuous (UPE)", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    const head = () => r32(R.RDH);
    receive(eth(OTHER, [2, 0, 0, 0, 0, 1], 0x88B5, bytes(50)));
    assert.equal(head(), 0, "another card's address");
    receive(eth([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], OTHER, 0x0806, bytes(46)));
    assert.equal(head(), 0, "broadcast without BAM");
    w32(R.RCTL, RCTL_EN | RCTL_SECRC | RCTL_BAM);
    receive(eth([0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], OTHER, 0x0806, bytes(46)));
    assert.equal(head(), 1, "broadcast with BAM");
    const group = [0x01, 0x00, 0x5E, 0x00, 0x00, 0xFB];
    receive(eth(group, OTHER, 0x0800, bytes(46)));
    assert.equal(head(), 1, "multicast not in the table");
    const hash = (group[5] << 8 | group[4]) >> 4 & 0xFFF;
    w32(R.MTA + (hash >> 5) * 4, 1 << (hash & 31));
    receive(eth(group, OTHER, 0x0800, bytes(46)));
    assert.equal(head(), 2, "multicast in the table (MO 0)");
    receive(eth([0x01, 0x00, 0x5E, 0x00, 0x00, 0x01], OTHER, 0x0800, bytes(46)));
    assert.equal(head(), 2);
    w32(R.RCTL, RCTL_EN | RCTL_SECRC | RCTL_BAM | RCTL_MPE);
    receive(eth([0x01, 0x00, 0x5E, 0x00, 0x00, 0x01], OTHER, 0x0800, bytes(46)));
    assert.equal(head(), 3, "multicast promiscuous");
    w32(R.RCTL, RCTL_EN | RCTL_SECRC | RCTL_UPE);
    receive(eth(OTHER, [2, 0, 0, 0, 0, 1], 0x88B5, bytes(50)));
    assert.equal(head(), 4, "unicast promiscuous");
    w32(R.RA + 8, 0x00544152); w32(R.RA + 12, 1 << 31 | 0x5634);
    w32(R.RCTL, RCTL_EN | RCTL_SECRC);
    receive(eth([0x52, 0x41, 0x54, 0x00, 0x34, 0x56], OTHER, 0x88B5, bytes(50)));
    assert.equal(head(), 5, "a second receive address");
    w32(R.RA + 12, 0);
    w32(R.MTA + (hash >> 5) * 4, 0);
    r32(R.ICR);
});

test("receive: a frame across 256-byte buffers, EOP on the last; RXDMT0", () => {
    setup_rx(RCTL_EN | RCTL_SECRC | BSIZE_256);
    w32(R.IMS, ICR_RXDMT0 | ICR_RXT0);
    r32(R.ICR);
    const frame = eth(MAC(), OTHER, 0x88B5, bytes(586));
    receive(frame);
    assert.deepEqual([0, 1, 2].map(i => rx(i).length), [256, 256, 88]);
    assert.deepEqual([0, 1, 2].map(i => rx(i).status & (DD | RX_EOP)), [DD, DD, DD | RX_EOP]);
    const data = new Uint8Array([...rx(0).data, ...rx(1).data, ...rx(2).data]);
    assert.deepEqual(data, frame);
    assert.equal(r32(R.RDH), 3);
    receive(frame);
    assert.equal(r32(R.RDH), 6);
    assert.equal(r32(R.ICR) & ICR_RXDMT0, ICR_RXDMT0, "one free descriptor of eight: below half");
    w32(R.IMC, -1);
});

test("receive: without free descriptors frames wait in the FIFO (RNBC); a full FIFO drops (MPC, RXO)", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    r32(R.RNBC); r32(R.MPC);
    w32(R.RDT, 0);
    w32(R.IMS, ICR_RXO);
    r32(R.ICR);
    const frame = n => eth(MAC(), OTHER, 0x88B5, bytes(1000, n));
    for(let n = 0; n < 3; n++) receive(frame(n));
    assert.equal(r32(R.RDH), 0);
    assert.equal(r32(R.RNBC), 3);
    w32(R.RDT, 2);
    assert.equal(r32(R.RDH), 2, "two delivered when the guest gives two");
    assert.deepEqual(rx(1).data, frame(1));
    w32(R.RDT, 3);
    assert.deepEqual(rx(2).data, frame(2), "in order");
    assert.ok(!irq());
    // PBA's 48 KiB
    for(let n = 0; n < 60; n++) receive(frame(n));
    assert.ok(r32(R.MPC) > 0, "missed packets");
    assert.ok(irq(), "RXO");
    assert.equal(r32(R.ICR) & ICR_RXO, ICR_RXO);
    // (the FIFO's frames go with a reset)
    w32(R.CTRL, r32(R.CTRL) | CTRL_RST);
    assert.equal(card().rx_fifo.length, 0);
});

test("receive: IPv4 and TCP/UDP checksums checked (RXCSUM), IXSM without", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    w32(R.RXCSUM, 0x300);
    const good = eth(MAC(), OTHER, 0x0800, ipv4(6, l4(6, bytes(200))));
    receive(good);
    assert.equal(rx(0).status & (IPCS | TCPCS | RX_IXSM), IPCS | TCPCS);
    assert.equal(rx(0).errors, 0);
    const bad = good.slice();
    bad[60] ^= 1;
    receive(bad);
    assert.equal(rx(1).errors & TCPE, TCPE, "TCP checksum error");
    receive(eth(MAC(), OTHER, 0x0800, ipv4(17, l4(17, bytes(31)))));
    assert.equal(rx(2).status & (IPCS | TCPCS), IPCS | TCPCS, "UDP");
    assert.equal(rx(2).errors, 0);
    receive(eth(MAC(), OTHER, 0x86DD, bytes(60)));
    assert.equal(rx(3).status & (IPCS | TCPCS | RX_IXSM), RX_IXSM, "not IPv4: nothing checked");
    w32(R.RXCSUM, 0);
    receive(good);
    assert.equal(rx(4).status & (IPCS | TCPCS | RX_IXSM), RX_IXSM, "offload off");
});

test("receive: VLAN tag stripped into the descriptor (CTRL.VME), VFTA filter (VFE)", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    w32(R.CTRL, r32(R.CTRL) | CTRL_VME);
    w32(R.VET, 0x8100);
    const inner = eth(MAC(), OTHER, 0x0800, bytes(60));
    const tagged = new Uint8Array(inner.length + 4);
    tagged.set(inner.subarray(0, 12));
    tagged.set([0x81, 0x00, 0x20, 0x05], 12);
    tagged.set(inner.subarray(12), 16);
    receive(tagged);
    assert.equal(rx(0).status & VP, VP);
    assert.equal(rx(0).special, 0x2005);
    assert.deepEqual(rx(0).data, inner);
    w32(R.RCTL, RCTL_EN | RCTL_SECRC | RCTL_VFE);
    receive(tagged);
    assert.equal(r32(R.RDH), 1, "VLAN 5 not in VFTA");
    w32(R.VFTA, 1 << 5);
    receive(tagged);
    assert.equal(r32(R.RDH), 2);
    w32(R.VFTA, 0);
    w32(R.CTRL, r32(R.CTRL) & ~CTRL_VME);
});

test("receive: frames over 1518 bytes need LPE (ROC)", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    r32(R.ROC);
    const long = eth(MAC(), OTHER, 0x88B5, bytes(1600));
    receive(long);
    assert.equal(r32(R.RDH), 0);
    assert.equal(r32(R.ROC), 1);
    w32(R.RCTL, RCTL_EN | RCTL_SECRC | RCTL_LPE);
    receive(long);
    assert.equal(r32(R.RDH), 1);
    assert.equal(rx(0).length, long.length);
});

test("receive: RDTR delays RXT0, RADV bounds the delay", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    w32(R.RDTR, 100);
    w32(R.RADV, 200);
    w32(R.IMS, ICR_RXT0);
    r32(R.ICR);
    const frame = eth(MAC(), OTHER, 0x88B5, bytes(50));
    receive(frame);
    assert.ok(!irq(), "delayed");
    advance(0.11);
    assert.ok(irq(), "RDTR (102.4 us) without another frame");
    r32(R.ICR);
    for(let n = 0; n < 3; n++) { receive(frame); advance(0.06); }
    assert.ok(!irq(), "each frame restarts RDTR");
    advance(0.04);
    assert.ok(irq(), "RADV (204.8 us) after the first");
    r32(R.ICR);
    w32(R.RDTR, 0x80000000 | 100);
    receive(frame);
    w32(R.RDTR, 1 << 31 | 100);
    assert.ok(irq(), "FPD ends the delay");
    r32(R.ICR);
    w32(R.RDTR, 0); w32(R.RADV, 0);
    w32(R.IMC, -1);
});

test("statistics read to clear; a 64-bit counter clears with its high half", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    r32(R.GPRC); r32(R.GORCH);
    receive(eth(MAC(), OTHER, 0x88B5, bytes(100)));
    assert.equal(r32(R.GPRC), 1);
    assert.equal(r32(R.GPRC), 0);
    assert.equal(r32(R.TPR) > 0, true);
    assert.equal(r32(R.GORCL), 118);
    assert.equal(r32(R.GORCL), 118, "the low half alone does not clear");
    assert.equal(r32(R.GORCH), 0);
    assert.equal(r32(R.GORCL), 0);
});

test("loopback: a frame sent in PHY loopback comes back", () => {
    setup_rx(RCTL_EN | RCTL_SECRC);
    setup_tx();
    mdic(1, 0, 0x4140);
    const frame = eth(MAC(), MAC(), 0x88B5, bytes(64));
    legacy(0, frame, EOP | RS);
    w32(R.TDT, 1);
    assert.equal(sent.length, 0, "not to the network");
    assert.deepEqual(rx(0).data, frame);
    mdic(1, 0, 0x1140);
    r32(R.ICR);
});

// --- resets and snapshots -------------------------------------------------------

test("CTRL.RST: registers to their defaults, RA[0] from the EEPROM, the PHY kept", () => {
    w32(R.RA, 0x11223344);
    w32(R.IMS, ICR_RXT0);
    w32(R.ICS, ICR_RXT0);
    w32(R.RCTL, RCTL_EN);
    assert.ok(irq());
    mdic(1, 4, 0x01E1);
    w32(R.CTRL, r32(R.CTRL) | CTRL_RST);
    assert.equal(r32(R.CTRL) & CTRL_RST, 0, "self-clearing");
    assert.equal(r32(R.RCTL), 0);
    assert.equal(r32(R.IMS), 0);
    assert.ok(!irq());
    assert.equal(r32(R.RA), (eerd(0) | eerd(1) << 16) >>> 0);
    assert.equal(r32(R.PBA), 0x00100030);
    assert.equal(mdic(2, 4) & 0xFFFF, 0x01E1);
    assert.ok(r32(R.STATUS) & STATUS_LU);
});

const saved = { rdh: 0, tdh: 0, mac: [] };
let state;
{
    setup_rx(RCTL_EN | RCTL_SECRC);
    setup_tx();
    w32(R.RDT, 0);
    w32(R.ITR, 777);
    w32(R.IMS, ICR_RXT0 | ICR_TXDW);
    const waiting = eth(MAC(), OTHER, 0x88B5, bytes(333));
    receive(waiting);
    legacy(0, eth(OTHER, MAC(), 0x88B5, bytes(50)), EOP | RS);
    w32(R.TDT, 1);
    saved.mac = MAC();
    saved.tdh = r32(R.TDH);
    state = await emulator.save_state();
    w32(R.CTRL, CTRL_RST);
    w32(R.MTA, 0x55);
    await emulator.restore_state(state);
    test("snapshot: registers, rings, the FIFO and the address survive", () => {
        assert.equal(r32(R.ITR), 777);
        assert.equal(r32(R.IMS), ICR_RXT0 | ICR_TXDW);
        assert.equal(r32(R.MTA), 0);
        assert.equal(r32(R.TDH), saved.tdh);
        assert.equal(r32(R.RCTL), RCTL_EN | RCTL_SECRC);
        assert.deepEqual(MAC(), saved.mac);
        w32(R.RDT, 2);
        assert.deepEqual(rx(0).data, waiting, "the frame from the FIFO");
        assert.ok(r32(R.STATUS) & STATUS_LU);
    });
}

// Another machine restores the snapshot: its card keeps its own address
// (preserve_mac_from_state_image off), unless asked to translate
for(const mode of ["own", "translation", "preserve", "ne2k"])
{
    const other = new V86({ ...options,
        net_device: { type: mode === "ne2k" ? "ne2k" : "e1000" },
        mac_address_translation: mode === "translation",
        preserve_mac_from_state_image: mode === "preserve" });
    await new Promise(resolve => other.add_listener("emulator-loaded", resolve));
    if(mode === "ne2k")
    {
        let error;
        await other.restore_state(state).catch(e => { error = e; });
        test("snapshot: a machine with another network card refuses it", () => {
            assert.match(String(error && error.message), /net_device: "e1000", this one has "ne2k"/);
        });
        await other.destroy();
        continue;
    }
    await other.restore_state(state);
    const c = other.v86.cpu.devices.net.device["card"];
    const frames = [];
    other.add_listener("net0-send", f => frames.push(new Uint8Array(f)));
    const ra = c.guest_mac();
    test("snapshot restored with the address " + mode, () => {
        if(mode === "preserve")
        {
            assert.deepEqual(Array.from(c.mac), saved.mac);
            assert.deepEqual(Array.from(ra), saved.mac);
        }
        else if(mode === "own")
        {
            assert.notDeepEqual(Array.from(c.mac), saved.mac);
            assert.deepEqual(Array.from(ra), Array.from(c.mac), "RA[0] has the card's own address");
            assert.deepEqual(Array.from(c.eeprom_mac()), Array.from(c.mac));
        }
        else
        {
            assert.deepEqual(Array.from(ra), saved.mac, "the guest keeps its address");
            assert.notDeepEqual(Array.from(c.mac), saved.mac);
            // a frame the guest sends goes out with the card's address
            const cpu2 = other.v86.cpu;
            const f = eth(OTHER, saved.mac, 0x88B5, bytes(50));
            cpu2.mem8.set(f, 0x180000);
            const a = 0x100000 + 16;
            cpu2.mem8.fill(0, a, a + 16);
            new DataView(cpu2.mem8.buffer, cpu2.mem8.byteOffset).setUint32(a, 0x180000, true);
            new DataView(cpu2.mem8.buffer, cpu2.mem8.byteOffset).setUint32(a + 8, f.length | EOP | RS, true);
            cpu2.mmap_write32(BAR + R.TDT, 2);
            assert.equal(frames.length, 1);
            assert.deepEqual(Array.from(frames[0].subarray(6, 12)), Array.from(c.mac), "translated source");
        }
    });
    await other.destroy();
}

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                          source/v64/tests/devices/e1000_guest.mjs                                                            0000755 0000000 0000000 00000025471 00000000000 015133  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The e1000 network card with a real driver: Linux 4.16's e1000 (built into
// images/linux4.iso) on net_device.type "e1000", the fetch backend's network
// (docs/modern-pc-devices-plan.md, N1, "验收"). The driver probes the card
// (EEPROM, PHY), the link comes up, DHCP, ARP, ICMP and DNS go through it;
// TCP both ways against an endpoint in this test, checked by MD5 (the
// guest's md5sum); the link down and up, a reboot and a snapshot. Prints the
// throughput and the card's interrupt rate.
//
// CPU_CORES=2 (with ACPI: the I/O APIC routes INTA), TRANSFER_MB (8; the
// plan's long run is 1024), DISABLE_JIT=1, SHOW_LOGS=1.

import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import url from "node:url";
import { tcp_endpoint } from "./tcp_endpoint.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const TRANSFER_MB = +process.env.TRANSFER_MB || 8;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

/**
 * A file from an ISO9660 image (plain names)
 * @param {string} path
 * @param {!Array<string>} names
 * @return {!ArrayBuffer}
 */
function iso_file(path, names)
{
    const iso = fs.readFileSync(path);
    let extent = iso.readUInt32LE(16 * 2048 + 156 + 2), size = iso.readUInt32LE(16 * 2048 + 156 + 10);
    for(const name of names)
    {
        let found = false;
        for(let at = extent * 2048; at < extent * 2048 + size;)
        {
            const length = iso[at];
            if(!length) { at = (Math.floor(at / 2048) + 1) * 2048; continue; }
            const entry = iso.toString("latin1", at + 33, at + 33 + iso[at + 32]).replace(/;\d+$/, "").replace(/\.$/, "");
            if(entry === name)
            {
                extent = iso.readUInt32LE(at + 2);
                size = iso.readUInt32LE(at + 10);
                found = true;
                break;
            }
            at += length;
        }
        assert.ok(found, name + " in " + path);
    }
    return iso.buffer.slice(iso.byteOffset + extent * 2048, iso.byteOffset + extent * 2048 + size);
}

const ISO = __dirname + "/../../images/linux4.iso";
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: ISO },
    bzimage: { buffer: iso_file(ISO, ["BOOT", "BZIMAGE"]) },
    cmdline: "root=/dev/sr0",
    memory_size: 256 * 1024 * 1024,
    acpi: CPU_CORES > 1,
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1 && !+process.env.DISABLE_JIT,
    disable_jit: +process.env.DISABLE_JIT,
    net_device: { type: "e1000", relay_url: "fetch" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, (300 + TRANSFER_MB * 4) * 1000);

let serial = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});

const PROMPT = /~% $/;

function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}

async function command(cmd, timeout_ms = 60000)
{
    serial = "";
    emulator.serial0_send(cmd + "\n");
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(cmd.length).replace(PROMPT, "");
}

/**
 * After a boot: the init script may still write after the shell's first
 * prompt (on two cores it does); wait until an empty line gets a prompt
 * and nothing else for a while
 */
async function settle()
{
    await wait_serial(PROMPT, "the shell", 240000);
    for(let attempt = 0; attempt < 30; attempt++)
    {
        await new Promise(resolve => setTimeout(resolve, 1500));
        serial = "";
        emulator.serial0_send("\n");
        await wait_serial(PROMPT, "the shell", 30000);
        await new Promise(resolve => setTimeout(resolve, 1000));
        if(/^\s*~% $/.test(serial)) return;
    }
    throw new Error("the shell does not settle:\n" + serial);
}

let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

/** The card's interrupts so far (/proc/interrupts, all CPUs) */
async function card_interrupts()
{
    const line = (await command("grep eth0 /proc/interrupts")).trim();
    return line.split(/\s+/).slice(1, 1 + CPU_CORES).reduce((sum, n) => sum + +n, 0);
}

// The endpoints (tests/devices/tcp_endpoint.mjs, at the router's address):
// port 5000 answers any request with TRANSFER_MB of a pattern (HTTP, for
// wget); port 5001 takes what comes (telnet: a newline arrives as CR LF)
const pattern = new Uint8Array(TRANSFER_MB << 20);
for(let i = 0; i < pattern.length; i++) pattern[i] = (i * 2654435761 >>> 24) ^ i >>> 12;
let upload = null;
// (the network adapter exists once the emulator is ready)
emulator.add_listener("emulator-ready", () => tcp_endpoint(emulator, {
    5000: { serve: () => Buffer.concat([Buffer.from("HTTP/1.0 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: " +
        pattern.length + "\r\n\r\n"), pattern]) },
    5001: { sink: data => { upload && upload(data); upload = null; } },
}));

const md5 = bytes => crypto.createHash("md5").update(bytes).digest("hex");

async function bring_up()
{
    // (the kernel's messages go to the VGA console: dmesg, and the carrier)
    const link = await command("ifconfig eth0 up; for i in $(seq 50); do [ \"$(cat /sys/class/net/eth0/carrier)\" = 1 ] && break; " +
        "sleep 0.2; done; cat /sys/class/net/eth0/carrier; dmesg | grep 'Link is Up' | tail -1", 30000);
    assert.match(link, /(^|\n)1\r?\n/, "carrier");
    assert.match(link, /NIC Link is Up 1000 Mbps Full Duplex/);
    const lease = await command("udhcpc -i eth0 -n -q 2>&1", 60000);
    assert.match(lease, /lease of 192\.168\.86\.100 obtained/);
}

console.log("Booting linux4.iso with an e1000 (" + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");
await settle();

await step("the driver: e1000 at the NE2000's slot, the EEPROM's address, PRO/1000", async () => {
    const dmesg = await command("dmesg | grep -i e1000");
    const mac = Array.from(emulator.v86.cpu.devices.net.device["card"].mac, b => b.toString(16).padStart(2, "0")).join(":");
    assert.match(dmesg, /e1000 0000:00:05\.0 eth0: \(PCI:33MHz:32-bit\) /);
    assert.ok(dmesg.includes("eth0: " + "(PCI:33MHz:32-bit) " + mac), "the address " + mac + " in " + dmesg);
    assert.match(dmesg, /Intel\(R\) PRO\/1000 Network Connection/);
    assert.doesNotMatch(dmesg, /EEPROM Checksum Is Not Valid|Invalid MAC Address|PHY/);
    const lspci = await command("lspci -k | grep -A1 8086:100e");
    assert.match(lspci, /e1000/);
});

await step("link up, DHCP", bring_up);

await step("ICMP to the router and beyond, ARP, DNS", async () => {
    assert.match(await command("ping -c 3 192.168.86.1"), /3 packets transmitted, 3 packets received, 0% packet loss/);
    assert.match(await command("ping -c 2 1.2.3.4"), /2 packets transmitted, 2 packets received/);
    assert.match(await command("arp -a"), /\(192\.168\.86\.1\) at 52:54:00:01:02:03 \[ether\] {2}on eth0/);
    assert.match(await command("nslookup example.org 2>&1"), /Address/);
});

await step("TCP to the guest: " + TRANSFER_MB + " MiB (HTTP), by MD5", async () => {
    const before = await card_interrupts();
    const start = Date.now();
    const output = await command("wget -q -O - http://192.168.86.1:5000/ | md5sum", TRANSFER_MB * 4000 + 30000);
    const seconds = (Date.now() - start) / 1000;
    assert.ok(output.includes(md5(pattern)), "MD5 " + md5(pattern) + " in " + output);
    const interrupts = await card_interrupts() - before;
    console.log("    " + (TRANSFER_MB / seconds).toFixed(2) + " MiB/s, " + interrupts + " interrupts (" +
        (interrupts / seconds).toFixed(0) + "/s, " + (pattern.length / 1448 / interrupts).toFixed(1) + " segments each)");
});

await step("TCP from the guest: " + TRANSFER_MB + " MiB (telnet), by MD5", async () => {
    // a pattern of lines without the bytes telnet treats specially (IAC, ^])
    const lines = Math.ceil((TRANSFER_MB << 20) / 64);
    const received = new Promise(resolve => { upload = resolve; });
    const start = Date.now();
    const sum = await command("seq -w 1 " + lines + " | sed 's/$/ abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTU/' | tee /tmp/up | md5sum; " +
        "telnet 192.168.86.1 5001 < /tmp/up > /dev/null; rm /tmp/up", TRANSFER_MB * 8000 + 30000);
    const data = await received;
    const seconds = (Date.now() - start) / 1000;
    // (telnet sends a newline as CR LF)
    const text = data.toString("latin1").replace(/\r\n/g, "\n");
    assert.ok(sum.includes(md5(Buffer.from(text, "latin1"))), "MD5 of " + text.length + " bytes in " + sum);
    console.log("    " + (text.length / 1048576 / seconds).toFixed(2) + " MiB/s (with making the data)");
});

await step("the link down and up", async () => {
    await command("ifconfig eth0 down");
    assert.match(await command("ifconfig eth0"), /^((?!UP).)*$/s);
    await bring_up();
    assert.match(await command("ping -c 2 192.168.86.1"), /2 packets received/);
});

await step("a snapshot: the guest's network goes on after restoring it", async () => {
    const state = await emulator.save_state();
    await command("ifconfig eth0 down");
    await emulator.restore_state(state);
    serial = "";
    emulator.serial0_send("\n");
    await wait_serial(PROMPT, "the shell after restoring", 30000);
    assert.match(await command("ping -c 2 192.168.86.1"), /2 packets transmitted, 2 packets received/);
});

await step("a reboot: the driver finds the card again", async () => {
    // (the old shell prints no prompt after "reboot": the next is the new one's)
    serial = "";
    emulator.serial0_send("reboot\n");
    await settle();
    await bring_up();
    assert.match(await command("ping -c 2 192.168.86.1"), /2 packets received/);
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                                       source/v64/tests/devices/fetch_network.js                                                           0000755 0000000 0000000 00000035731 00000000000 015664  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "assert/strict";
import url from "node:url";
import { Worker, isMainThread, parentPort } from "node:worker_threads";
import { createServer } from "node:http";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const __filename = url.fileURLToPath(import.meta.url);
process.on("unhandledRejection", exn => { throw exn; });

const USE_VIRTIO = !!process.env.USE_VIRTIO;
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;

const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const SHOW_LOGS = false;

function wait(time) {
    return new Promise((res) => setTimeout(res, time));
}

if(isMainThread)
{
    let SERVER_PORT = 0;

    const tests =
    [
        {
            name: "DHCP",
            start: () =>
            {
                emulator.serial0_send("udhcpc\n");
                emulator.serial0_send("echo -e done\\\\tudhcpc\n");
            },
            end_trigger: "done\tudhcpc",
            end: (capture) =>
            {
                assert(/lease of 192.168.86.100 obtained/.test(capture), "lease of 192.168.86.100 obtained");
            },
        },
        {
            name: "lspci",
            timeout: 60,
            start: () =>
            {
                emulator.serial0_send("lspci -k\n");
                emulator.serial0_send("echo -e done\\\\tlspci\n");
            },
            end_trigger: "done\tlspci",
            end: (capture) =>
            {
                if(!USE_VIRTIO) {
                    assert(/ne2k/.test(capture), "ne2k missing from lspci");
                } else {
                    assert(!/ne2k/.test(capture), "ne2k in lspci");
                }
            },
        },
        {
            name: "ifconfig",
            start: () =>
            {
                emulator.serial0_send("ifconfig\n");
                emulator.serial0_send("echo -e done\\\\tifconfig\n");
            },
            end_trigger: "done\tifconfig",
            end: (capture) =>
            {
                assert(/192.168.86.100/.test(capture), "192.168.86.100");
            },
        },
        {
            name: "route",
            start: () =>
            {
                emulator.serial0_send("ip route\n");
                emulator.serial0_send("echo -e done\\\\troute\n");
            },
            end_trigger: "done\troute",
            end: (capture) =>
            {
                assert(/192.168.86.1/.test(capture), "192.168.86.100");
            },
        },
        {
            name: "ping 1.2.3.4",
            start: () =>
            {
                emulator.serial0_send("ping -c 2 1.2.3.4\n");
                emulator.serial0_send("echo -e done\\\\tping\n");
            },
            end_trigger: "done\tping",
            end: (capture) =>
            {
                assert(/2 packets transmitted, 2 (packets )?received, 0% packet loss/.test(capture), "2 packets transmitted, 2 packets received, 0% packet loss");
                assert(/from 1\.2\.3\.4:/.test(capture), "got correct source ip");
            },
        },
        {
            name: "arp -a",
            start: () =>
            {
                emulator.serial0_send("arp -a\n");
                emulator.serial0_send("echo -e done\\\\tarp\n");
            },
            end_trigger: "done\tarp",
            end: (capture) =>
            {
                assert(/.192.168.86.1. at 52:54:00:01:02:03 \[ether\] {2}on eth0/.test(capture), "(192.168.86.1) at 52:54:00:01:02:03 [ether]  on eth0");
            },
        },
        {
            name: "Accept incoming connection",
            timeout: 60,
            allow_failure: true,
            start: async () =>
            {
                let open = await emulator.network_adapter.tcp_probe(80);
                assert(!open, "Probe shows port not open");
                emulator.serial0_send("echo -n hello | socat TCP4-LISTEN:80 - && echo -e done\\\\tlisten\n");
                await wait(1000);
                open = await emulator.network_adapter.tcp_probe(80);
                assert(open, "Probe shows port open, but does not show as a connection");
                await wait(1000);
                let h = emulator.network_adapter.connect(80);
                h.on("connect", () => {
                    h.write(new TextEncoder().encode("From VM: "));
                    h.on("data", (d) => {
                        d.reverse();
                        h.write(d);
                        h.write(new TextEncoder().encode("\n"));
                        h.close();
                    });
                });
            },
            end_trigger: "done\tlisten",
            end: (capture) =>
            {
                assert(/From VM: olleh/.test(capture), "got From VM");
            },
        },
        {
            name: "GET mocked.example.org",
            allow_failure: true,
            start: () =>
            {
                emulator.serial0_send("wget -T 10 -O - mocked.example.org\n");
                emulator.serial0_send("echo -e done\\\\tmocked.example.org\n");
            },
            end_trigger: "done\tmocked.example.org",
            end: (capture) =>
            {
                assert(/This text is from the mock/.test(capture), "got mocked.example.org text");
            },
        },
        {
            name: "GET example.org",
            allow_failure: true,
            start: () =>
            {
                emulator.serial0_send("wget -T 10 -O - example.org\n");
                emulator.serial0_send("echo -e done\\\\texample.org\n");
            },
            end_trigger: "done\texample.org",
            end: (capture) =>
            {
                assert(/This domain is for use in documentation examples without needing permission/.test(capture), "got example.org text");
            },
        },
        {
            name: "GET local server",
            allow_failure: true,
            start: () =>
            {
                emulator.serial0_send(`wget -T 10 -O - ${SERVER_PORT}.external\n`);
                emulator.serial0_send("echo -e done\\\\tlocal server\n");
            },
            end_trigger: "done\tlocal server",
            end: (capture) =>
            {
                assert(/This text is from the local server/.test(capture), "got local server text");
            },
        },
        {
            name: "GET local server with custom header",
            allow_failure: true,
            start: () =>
            {
                emulator.serial0_send(`wget -S -T 10 --header='x-client-test: hello' -O - ${SERVER_PORT}.external/header\n`);
                emulator.serial0_send("echo -e done\\\\tlocal server custom header\n");
            },
            end_trigger: "done\tlocal server custom header",
            end: (capture) =>
            {
                assert(/x-server-test: {1,}h_e_l_l_o/.test(capture), "got local server custom header");
            },
        },
        {
            name: "GET local server with redirect",
            allow_failure: true,
            start: () =>
            {
                emulator.serial0_send(`curl -m 10 -L -v ${SERVER_PORT}.external/redirect\n`);
                emulator.serial0_send("echo -e done\\\\tlocal server redirect\n");
            },
            end_trigger: "done\tlocal server redirect",
            end: (capture) =>
            {
                assert(/x-was-fetch-redirected: {1,}true/.test(capture), "got local server redirect header");
                assert(/This text is from the local server/.test(capture), "got actual redirect");
            },
        },
        {
            name: "Forbidden character in header name",
            start: () =>
            {
                emulator.serial0_send("wget --header='test.v86: 123' -T 10 -O - test.domain\n");
                emulator.serial0_send("echo -e done\\\\tincorrect header name\n");
            },
            end_trigger: "done\tincorrect header name",
            end: (capture) =>
            {
                assert(/400 Bad Request/.test(capture), "got error 400");
            },
        },
        {
            name: "Empty header value",
            start: () =>
            {
                emulator.serial0_send("wget --header='test:' -T 10 -O - test.domain\n");
                emulator.serial0_send("echo -e done\\\\tempty header value\n");
            },
            end_trigger: "done\tempty header value",
            end: (capture) =>
            {
                assert(/400 Bad Request/.test(capture), "got error 400");
            },
        },
        {
            name: "Header without separator",
            start: () =>
            {
                emulator.serial0_send("wget --header='testheader' -T 10 -O - test.domain\n");
                emulator.serial0_send("echo -e done\\\\theader without colon\n");
            },
            end_trigger: "done\theader without colon",
            end: (capture) =>
            {
                assert(/400 Bad Request/.test(capture), "got error 400");
            },
        },
        {
            name: "POST large body to local server",
            allow_failure: true,
            timeout: 30,
            start: () =>
            {
                // POST a 3000-byte body — larger than one TCP segment (~1460 bytes).
                // This exercises the multi-segment body buffering fix.
                emulator.serial0_send(`dd if=/dev/zero bs=3000 count=1 2>/dev/null | curl -m 10 -s -X POST --data-binary @- ${SERVER_PORT}.external/post\n`);
                emulator.serial0_send("echo -e done\\\\tpost large body\n");
            },
            end_trigger: "done\tpost large body",
            end: (capture) =>
            {
                assert(/Received 3000 bytes/.test(capture), "server received full 3000 byte body");
            },
        },
    ];


    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
        autostart: true,
        memory_size: 64 * 1024 * 1024,
        disable_jit: +process.env.DISABLE_JIT,
        net_device: {
            relay_url: "fetch",
            type: USE_VIRTIO ? "virtio" : "ne2k",
        },
        log_level: SHOW_LOGS ? 0x400000 : 0,
    });

    const server = new Worker(__filename);
    server.on("error", (e) => { throw new Error("server: " + e); });
    server.on("message", function(msg) {
        SERVER_PORT = msg;
        console.log("Server started on port " + SERVER_PORT);
    });

    emulator.add_listener("emulator-ready", function () {
        let network_adapter = emulator.network_adapter;
        let original_fetch = network_adapter.fetch;
        network_adapter.fetch = (url, opts) => {
            if(/^http:\/\/mocked.example.org\/?/.test(url)) {
                let contents = new TextEncoder().encode("This text is from the mock");
                let headers = new Headers();
                headers.append("Content-Type", "text/plain");
                headers.append("Content-Length", contents.length);
                return new Promise(res => setTimeout(() => res(new Response(contents, {
                    headers
                })), 50));
            }
            return original_fetch(url, opts);
        };
    });

    let test_num = 0;
    let booted = false;
    let line = "";
    let capture = "";
    let end_trigger;

    emulator.bus.register("emulator-started", function()
    {
        console.log("Booting now, please stand by");
    });

    emulator.add_listener("serial0-output-byte", function(byte)
    {
        const chr = String.fromCharCode(byte);
        if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
        {
            return;
        }

        let new_line = "";
        if(chr === "\n")
        {
            console.log("    Captured: %s", line);
            new_line = line;
            capture += line + "\n";
            line = "";
        }
        else
        {
            line += chr;
        }

        if(new_line === end_trigger)
        {
            let test_has_failed = false;

            try {
                tests[test_num].end(capture);
            } catch(e) {
                console.log(e);
                test_has_failed = true;
            }

            if(!test_has_failed)
            {
                console.log("[+] Test #%d passed: %s", test_num, tests[test_num].name);
            }
            else
            {
                if(tests[test_num].allow_failure)
                {
                    console.warn("[!] Test #%d failed: %s (failure allowed)", test_num, tests[test_num].name);
                }
                else
                {
                    console.error("[-] Test #%d failed: %s", test_num, tests[test_num].name);
                    server.terminate();
                    process.exit(1);
                }
            }

            test_num++;

        }

        if(!booted && line.endsWith("~% ") || new_line === end_trigger)
        {
            booted = true;

            if(test_num >= tests.length)
            {
                emulator.destroy();
                server.terminate();
                console.log("Tests finished.");
            }
            else
            {
                console.log("Starting test #%d: %s", test_num, tests[test_num].name);

                capture = "";
                end_trigger = tests[test_num].end_trigger;

                tests[test_num].start();
            }
        }
    });
}
else
{
    const server = createServer(function(request, response) {
        switch(request.method) {
            case "GET":
                if(request.url === "/") {
                    response.end("This text is from the local server");
                } else if(request.url === "/header") {
                     response.writeHead(200, { "x-server-test": request.headers["x-client-test"].split("").join("_") || "none" });
                     response.end();
                } else if(request.url === "/redirect") {
                     response.writeHead(307, { "location": "/" });
                     response.end();
                } else {
                     response.writeHead(404);
                     response.end("Unknown endpoint");
                }
                break;
            case "POST":
                if(request.url === "/post") {
                    let chunks = [];
                    request.on("data", chunk => chunks.push(chunk));
                    request.on("end", () => {
                        const full = Buffer.concat(chunks);
                        response.end(`Received ${full.length} bytes`);
                    });
                } else {
                    response.writeHead(404);
                    response.end("Unknown POST endpoint");
                }
                break;
            default:
                response.writeHead(405);
                response.end("Unknown method");
                break;
        }
    });

    server.listen(0, () => parentPort.postMessage(server.address().port));
}
                                       source/v64/tests/devices/fetch_network_post.js                                                      0000755 0000000 0000000 00000014706 00000000000 016730  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
/**
 * Test: multi-segment HTTP POST/PUT body buffering in fetch_network adapter.
 *
 * Verifies that a POST body split across multiple TCP segments is fully
 * buffered and dispatched, rather than truncated at the first segment.
 *
 * Run:  node tests/devices/fetch_network_post.js
 */

import assert from "node:assert/strict";
import { FetchNetworkAdapter } from "../../src/browser/fetch_network.js";

const text_encoder = new TextEncoder();

let tests_passed = 0;
let tests_failed = 0;

function test(name, fn) {
    process.stdout.write(name + " ... ");
    try {
        fn();
        console.log("PASS");
        tests_passed++;
    } catch(e) {
        console.log("FAIL");
        console.log("  " + e.message);
        tests_failed++;
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** Build a minimal mock BusConnector and FetchNetworkAdapter, returning
 *  the captured `on_data_http` handler and the adapter itself. */
function setup() {
    // Capture fetch() calls so we can inspect them.
    let fetch_calls = [];
    let bus_handler = null;

    const bus = {
        register(event, handler, ctx) {
            if(event === "tcp-connection") bus_handler = handler.bind(ctx);
        },
        send(event, data) { /* noop */ },
    };

    const adapter = new FetchNetworkAdapter(bus, {});
    // Override adapter.fetch to capture rather than actually fetching.
    adapter.fetch = (url, opts) => {
        fetch_calls.push({ url, opts });
        // Return a promise that resolves with a mock response.
        return Promise.resolve([
            { status: 200, statusText: "OK", headers: new Headers() },
            new ArrayBuffer(0),
        ]);
    };

    // The connection's write/close methods need to exist; make them no-ops.
    const connection = {
        sport: 80,
        handlers: {},
        on(event, handler) {
            this.handlers[event] = handler;
        },
        accept() {},
        write() {},
        writev() {},
        close() {},
        net: adapter,
    };

    // Trigger the bus handler to register on_data_http.
    bus_handler(connection);

    const on_data = connection.handlers["data"];
    if(!on_data) throw new Error("on_data_http not registered");

    // Wrap so `this` inside on_data_http is bound to the mock connection.
    const dispatch = (buf) => on_data.call(connection, buf);

    return { dispatch, adapter, fetch_calls };
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

test("Small POST body fits in one segment", () => {
    const { dispatch, fetch_calls } = setup();

    const body = "hello world";
    const request = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 11\r\n\r\n" + body;
    dispatch(text_encoder.encode(request).buffer);

    assert.equal(fetch_calls.length, 1, "fetch should be called once");
    const { opts } = fetch_calls[0];
    assert.ok(opts.body instanceof Uint8Array, "body should be Uint8Array");
    assert.equal(opts.body.length, 11, "body length should be 11");
});

test("Large POST body split across three segments", () => {
    const { dispatch, fetch_calls } = setup();

    const big_body = new Uint8Array(4000);
    big_body.fill(0x42); // 'B'

    const headers = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 4000\r\n\r\n";
    const hdr_bytes = text_encoder.encode(headers);

    // Segment 1: headers + first 1000 bytes of body
    const seg1 = new Uint8Array(hdr_bytes.length + 1000);
    seg1.set(hdr_bytes);
    seg1.set(big_body.slice(0, 1000), hdr_bytes.length);
    dispatch(seg1.buffer);
    assert.equal(fetch_calls.length, 0, "no fetch yet — body incomplete");

    // Segment 2: next 1500 bytes
    dispatch(big_body.slice(1000, 2500).buffer);
    assert.equal(fetch_calls.length, 0, "still no fetch");

    // Segment 3: final 1500 bytes
    dispatch(big_body.slice(2500, 4000).buffer);
    assert.equal(fetch_calls.length, 1, "fetch called now");

    const body = fetch_calls[0].opts.body;
    assert.ok(body instanceof Uint8Array, "body should be Uint8Array");
    assert.equal(body.length, 4000, "all 4000 bytes present");
    assert.equal(body[0], 0x42, "first byte preserved");
    assert.equal(body[3999], 0x42, "last byte preserved");
});

test("Binary body with embedded CRLFCRLF is not corrupted", () => {
    const { dispatch, fetch_calls } = setup();

    // Body contains the byte sequence 0x0D 0x0A 0x0D 0x0A (\r\n\r\n) inside it
    const bin_body = new Uint8Array([0xAA, 0x0D, 0x0A, 0x0D, 0x0A, 0xBB]);
    const headers = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 6\r\n\r\n";
    const hdr_bytes = text_encoder.encode(headers);

    const full = new Uint8Array(hdr_bytes.length + bin_body.length);
    full.set(hdr_bytes);
    full.set(bin_body, hdr_bytes.length);
    dispatch(full.buffer);

    assert.equal(fetch_calls.length, 1);
    const body = fetch_calls[0].opts.body;
    assert.equal(body.length, 6, "body length should be 6");
    assert.equal(body[0], 0xAA);
    assert.equal(body[1], 0x0D);
    assert.equal(body[5], 0xBB);
});

test("GET request (no body) is dispatched immediately", () => {
    const { dispatch, fetch_calls } = setup();

    const request = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n";
    dispatch(text_encoder.encode(request).buffer);

    assert.equal(fetch_calls.length, 1, "fetch called once");
    assert.equal(fetch_calls[0].opts.method, "GET");
});

test("Headers split across two segments", () => {
    const { dispatch, fetch_calls } = setup();

    const body = "hi";
    const request = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 2\r\n\r\n" + body;

    // Split in the middle of a header line
    const bytes = text_encoder.encode(request);
    const mid = Math.floor(bytes.length * 0.4);

    dispatch(bytes.slice(0, mid).buffer);
    assert.equal(fetch_calls.length, 0, "no fetch — headers incomplete");

    dispatch(bytes.slice(mid).buffer);
    assert.equal(fetch_calls.length, 1, "fetch called after second segment");
    assert.equal(fetch_calls[0].opts.body.length, 2);
});

// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------

console.log(`\n${tests_passed} passed, ${tests_failed} failed`);
process.exit(tests_failed > 0 ? 1 : 0);
                                                          source/v64/tests/devices/gfxstream_create_graphics_pipelines.hex                                    0000644 0000000 0000000 00000003340 00000000000 022431  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       08020000a448000000000000cd480000000000000100000000000001000000001c00000000000000000000000200000012000000000000000000000001000000414c000000000000000000046d61696eb40000795ae399d001000000000000000400000000000000000000040000000000000008000000000000000012000000000000000000000010000000424c000000000000000000046d61696eb40000795ae39a10010000000000000004000000000000000000000400000000000000080000000000000000b40000795ae39a48130000000000002031b09d3b31b09d3b00000000030000000100000001000000020000000100000003000000010000000000000004000000000000000800000000000000010000002800000001000000020000002800000001000000030000002800000001000000040000000000000000000000670000000000000001000000010000006d0000000000000002000000020000006d0000000000000003000000030000006700000000000000b40000795ae39b201400000000000000000000000300000000000000b40000795ae39b40b40000795ae39b58160000000000000000000000010000000000000000000000010000000000000000000000b40000795ae39b88170000000000001831aa9e3b31aa9e3b00000000010000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000b40000795ae39be018000000000000000000000004000000000000000000803fb40000795ae39c10ffff00000000000000000000b40000795ae39c18190000000000000000000000000000000000000001000000000000000100000000000000060000000000000007000000000000000000000000000000000000000700000000000000070000000000000000000000000000000000000000000000b40000795ae39c801a0000000000000000000000000000000300000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b40000795ae39cd81b0000000000000000000000090000000000000001000000020000000300000005000000060000000700000008000000040000003e4c000000000000444c0000000000000000000000000000000000000000000000000000000000000000000000000000                                                                                                                                                                                                                                                                                                source/v64/tests/devices/gfxstream_guest_driver.js                                                  0000644 0000000 0000000 00000023005 00000000000 017570  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A machine with a virtio-gpu at level gfxstream and a guest's driver that a
// test plays by hand (tests/devices/virtio_gpu_gfxstream_vk.js, and
// virtio_gpu_gfxstream_render.js on a real renderer): the control queue,
// the context, ASG rings, and commands as gfxstream's guest encodes them
// (tests/devices/gfxstream_guest_protocol.js).

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { GUEST_COMMANDS, GfxReader, GfxWriter } = await import("./gfxstream_guest_protocol.js");

export { GUEST_COMMANDS, GfxReader, GfxWriter };

export const OK = 0x1100, OK_MAP_INFO = 0x1106;
export const HOST3D = 2, MAPPABLE = 1;
const RING_SIZE = 12288, BUFFER_SIZE = 1 << 20;
/** the context the driver's commands are of */
export const CTX = 1;

/**
 * @param {!Object} renderer the device's renderer
 * @return {!Promise<!Object>} the driver
 */
export async function gfxstream_machine(renderer)
{
    const floppy = new Uint8Array(1474560);
    floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
    floppy[510] = 0x55;
    floppy[511] = 0xAA;

    const emulator = new V86({
        graphics_adapter: "virtio_gpu",
        graphics_adapter_test: { level: "gfxstream", renderer },
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        fda: { buffer: floppy.buffer },
        boot_order: 0x321,
        autostart: true,
        memory_size: 64 << 20,
        vram_size: 16 << 20,
        net_device: { type: "none" },
        disable_speaker: true,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
    await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
    await emulator.stop();

    const cpu = emulator.v86.cpu, io = cpu.io;
    const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
    const BDF = 0x12 << 3;
    const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
    const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;
    const hostmem = (pci_read(0x20) & ~0xF) >>> 0;
    let common = 0, notify = 0;
    const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
    for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
    {
        if(pci_read8(at) !== 0x09) continue;
        const type = pci_read8(at + 3);
        if(type === 1) common = bar2 + pci_read(at + 8);
        if(type === 2) notify = bar2 + pci_read(at + 8);
    }
    const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
    const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
    const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
    const read_bytes = (address, length) => Uint8Array.from({ length }, (_, i) => cpu.read8(address + i));
    const w8 = (offset, value) => cpu.write8(common + offset, value);
    const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
    const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
        { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];
    w8(20, 0);
    w8(20, 3);
    write32(common, 0);
    const features0 = read32(common + 4);
    write32(common + 8, 0); write32(common + 12, features0);
    write32(common + 8, 1); write32(common + 12, 1);
    w8(20, 11);
    QUEUES.forEach((q, i) => {
        w16(22, i);
        q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
        write32(common + 32, q.desc); write32(common + 36, 0);
        write32(common + 40, q.avail); write32(common + 44, 0);
        write32(common + 48, q.used); write32(common + 52, 0);
        for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
        w16(28, 1);
    });
    w8(20, 15);

    const REQUEST = 0x200000, REPLY = 0x280000, SLOT = 0x1000;
    let next_slot = 0;
    const used_idx = () => read32(QUEUES[0].used) >>> 16;
    function send(bytes, wait = true)
    {
        const q = QUEUES[0];
        const slot = next_slot++ % 16;
        const head = slot * 2;
        write_bytes(REQUEST + slot * SLOT, bytes);
        write32(q.desc + head * 16, REQUEST + slot * SLOT); write32(q.desc + head * 16 + 4, 0);
        write32(q.desc + head * 16 + 8, bytes.length);
        cpu.write8(q.desc + head * 16 + 12, 1); cpu.write8(q.desc + head * 16 + 14, head + 1);
        write32(q.desc + (head + 1) * 16, REPLY + slot * SLOT); write32(q.desc + (head + 1) * 16 + 4, 0);
        write32(q.desc + (head + 1) * 16 + 8, 256);
        cpu.write8(q.desc + (head + 1) * 16 + 12, 2);
        write32(q.avail + 4 + (q.avail_idx % q.size) * 2, head);
        q.avail_idx = q.avail_idx + 1 & 0xFFFF;
        cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
        cpu.write8(q.avail + 3, q.avail_idx >> 8);
        const before = used_idx();
        cpu.write8(notify, 0);
        cpu.write8(notify + 1, 0);
        if(wait) assert.equal(used_idx(), before + 1 & 0xFFFF, "answered at once");
        return slot;
    }
    const answer = slot => read32(REPLY + slot * SLOT);
    const control = (type, values, wait, fence = null) => {
        const out = new Uint32Array(6 + values.length);
        out[0] = type;
        if(fence)
        {
            out[1] = 1 | (fence.ring !== undefined ? 2 : 0);
            out[2] = fence.id;
            out[5] = fence.ring || 0;
        }
        out[4] = CTX;
        out.set(values, 6);
        return send(new Uint8Array(out.buffer), wait);
    };
    const command = (type, ...values) => answer(control(type, values));
    const submit_3d = (words, wait, fence) => control(0x0207, [words.length * 4, 0, ...words], wait, fence);
    /** until the device has answered every request sent (the GPU's work), a while at most */
    const settle = async (what, before) => {
        for(let i = 0; i < 1000 && used_idx() !== QUEUES[0].avail_idx; i++) await new Promise(resolve => setTimeout(resolve, 10));
        assert.equal(used_idx(), QUEUES[0].avail_idx, what + ": answered");
    };

    /** a ring of the context: its blob, CONTEXT_CREATE, mapped; the stream and the replies on it */
    function make_ring(res, at)
    {
        assert.equal(command(0x010C, res, HOST3D, MAPPABLE, 0, 0, 0, RING_SIZE + BUFFER_SIZE, 0), OK);
        assert.equal(answer(submit_3d([0x1001, res])), OK, "CONTEXT_CREATE");
        assert.equal(command(0x0208, res, 0, at, 0), OK_MAP_INFO);
        return { res, base: hostmem + at, buffer: hostmem + at + RING_SIZE, write_offset: 0, write_pos: 0, reply_pos: 0, flags: false };
    }
    function push(ring, bytes)
    {
        if(!ring.flags) { bytes = Uint8Array.of(0, 0, 0, 0, ...bytes); ring.flags = true; }
        write_bytes(ring.buffer + ring.write_offset, bytes);
        write32(ring.base + 128 + (ring.write_pos & 2047), ring.write_offset);
        write32(ring.base + 128 + (ring.write_pos & 2047) + 4, bytes.length);
        ring.write_pos = ring.write_pos + 8 >>> 0;
        write32(ring.base + 8, ring.write_pos);
        ring.write_offset = (ring.write_offset + Math.ceil(bytes.length / 4096) * 4096) % BUFFER_SIZE;
    }
    const ping = ring => assert.equal(answer(submit_3d([0x1002, ring.res])), OK, "PING");
    /** what the device wrote back since the last read */
    function replies(ring)
    {
        const pos = read32(ring.base + 8192 + 8);
        const bytes = read_bytes(ring.buffer + (ring.reply_pos & BUFFER_SIZE - 1), pos - ring.reply_pos >>> 0);
        ring.reply_pos = pos;
        return bytes;
    }
    const driver = {
        emulator, cpu, gpu, hostmem, write32, read32, write_bytes, read_bytes, send, answer, control, command, submit_3d, used_idx, settle,
        make_ring, push, ping, replies,
        /** the last sequence number */
        seqno: 0,
        /** the ring `call` uses unless told */
        ring: null,
        /** a command as the guest encodes it: opcode, size, sequence number, parameters */
        encode(name, a, number = ++driver.seqno)
        {
            const [opcode, write] = GUEST_COMMANDS[name];
            const w = new GfxWriter(64);
            w.u32(opcode); w.u32(0); w.u32(number);
            write(w, a);
            const out = w.result().slice();
            new DataView(out.buffer).setUint32(4, out.length, true);
            return out;
        },
        /** a command buffer's command: opcode, size, parameters (no handle) */
        encode_cb(name, a)
        {
            const [opcode, write] = GUEST_COMMANDS[name];
            const w = new GfxWriter(64);
            w.u32(opcode); w.u32(0);
            write(w, a);
            const out = w.result().slice();
            new DataView(out.buffer).setUint32(4, out.length, true);
            return out;
        },
        /** a command and its reply (decoded as the guest decodes it, into a) */
        call(name, a, ring = driver.ring)
        {
            push(ring, driver.encode(name, a));
            ping(ring);
            const read = GUEST_COMMANDS[name][2];
            if(!read) return a;
            const bytes = replies(ring);
            const r = new GfxReader(bytes);
            read(r, a);
            assert.equal(r.p, bytes.length, name + ": the reply read whole");
            return a;
        },
    };
    return driver;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/devices/gfxstream_guest_protocol.js                                                0000644 0000000 0000000 00001616635 00000000000 020160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/gfxstream_protocol_gen.mjs from gfxstream's guest
// encoder (mesa src/gfxstream/guest/vulkan_enc, the build pinned in
// docs/gfxstream-protocol.md); do not edit.
//
// gfxstream's Vulkan wire format: (the guest's side, for tests) ge_* write a request as the guest's driver
// encoded, into objects with the C names (structs) or an object of the
// parameters (commands); gd_* read a reply as the driver does, from such
// objects (what is missing is written as zeros, an empty array or a null
// pointer).

/* eslint-disable */

// (tools/gfxstream_protocol_runtime.js, copied into gfxstream_protocol.js)
//
// gfxstream's Vulkan encoding (its cereal marshaling, "reserved" for
// requests): little endian, each value in its C size, no padding; 64-bit
// values (sizes, handles, VkDeviceSize, 64-bit flags) are numbers here, exact
// below 2**53; a pointer's presence and a size_t are 8 bytes big endian, a
// string's length and a string array's count 4 bytes big endian.

const MAX_COUNT = 1 << 24;

/**
 * Reads a command's parameters
 * @constructor
 * @param {!Uint8Array} bytes
 * @param {number=} start
 * @param {number=} end
 */
export function GfxReader(bytes, start, end)
{
    this.bytes = bytes;
    this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    this.p = start || 0;
    this.end = end === undefined ? bytes.length : end;
}

/** @param {number} n */
GfxReader.prototype.take = function(n)
{
    const at = this.p;
    if(at + n > this.end) throw new Error("gfxstream: read past the end of the command");
    this.p = at + n;
    return at;
};

GfxReader.prototype.u8 = function() { return this.view.getUint8(this.take(1)); };
GfxReader.prototype.i8 = function() { return this.view.getInt8(this.take(1)); };
GfxReader.prototype.u16 = function() { return this.view.getUint16(this.take(2), true); };
GfxReader.prototype.i16 = function() { return this.view.getInt16(this.take(2), true); };
GfxReader.prototype.u32 = function() { return this.view.getUint32(this.take(4), true); };
GfxReader.prototype.i32 = function() { return this.view.getInt32(this.take(4), true); };
GfxReader.prototype.f32 = function() { return this.view.getFloat32(this.take(4), true); };
GfxReader.prototype.f64 = function() { return this.view.getFloat64(this.take(8), true); };
GfxReader.prototype.u64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getUint32(at + 4, true) * 0x100000000;
};
GfxReader.prototype.i64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, true) + this.view.getInt32(at + 4, true) * 0x100000000;
};
/** a handle (the host's: the device allocates them) */
GfxReader.prototype.h = GfxReader.prototype.u64;
GfxReader.prototype.be32 = function() { return this.view.getUint32(this.take(4), false); };
GfxReader.prototype.be64 = function()
{
    const at = this.take(8);
    return this.view.getUint32(at, false) * 0x100000000 + this.view.getUint32(at + 4, false);
};
/** a pointer's presence (the guest's pointer, big endian): whether it is not null */
GfxReader.prototype.ptr = function()
{
    const at = this.take(8);
    // (tests: where the guest's pointers are)
    if(this.presences) this.presences.push(at);
    return (this.view.getUint32(at, false) | this.view.getUint32(at + 4, false)) !== 0;
};
/** a 32-bit value the guest wrote without moving on (what comes next overwrites it) */
GfxReader.prototype.peek_u32 = function()
{
    return this.p + 4 <= this.end ? this.view.getUint32(this.p, true) : 0;
};
/** @param {number} n */
GfxReader.prototype.count = function(n)
{
    if(!(n >= 0 && n <= MAX_COUNT)) throw new Error("gfxstream: a count of " + n);
    return n;
};
/** n bytes as a string (latin1), up to the first NUL */
GfxReader.prototype.str = function(n)
{
    const at = this.take(this.count(n));
    let s = "";
    for(let i = 0; i < n; i++)
    {
        const c = this.bytes[at + i];
        if(!c) break;
        s += String.fromCharCode(c);
    }
    return s;
};
/** a string: its length (big endian), then its bytes */
GfxReader.prototype.string = function() { return this.str(this.be32()); };
/** strings: their count (big endian), then each */
GfxReader.prototype.strings = function()
{
    const out = new Array(this.count(this.be32()));
    for(let i = 0; i < out.length; i++) out[i] = this.string();
    return out;
};
/**
 * @param {Function} type
 * @param {number} size
 * @param {number} n
 */
GfxReader.prototype.typed = function(type, size, n)
{
    const at = this.take(this.count(n) * size);
    const out = new type(n);
    for(let i = 0; i < n; i++)
    {
        const p = at + i * size;
        out[i] = size === 1 ? this.bytes[p] : size === 2 ? this.view.getUint16(p, true) :
            type === Float32Array ? this.view.getFloat32(p, true) : type === Int32Array ? this.view.getInt32(p, true) : this.view.getUint32(p, true);
    }
    return out;
};
GfxReader.prototype.u8s = function(n) { return this.typed(Uint8Array, 1, n); };
GfxReader.prototype.u16s = function(n) { return this.typed(Uint16Array, 2, n); };
GfxReader.prototype.u32s = function(n) { return this.typed(Uint32Array, 4, n); };
GfxReader.prototype.i32s = function(n) { return this.typed(Int32Array, 4, n); };
GfxReader.prototype.f32s = function(n) { return this.typed(Float32Array, 4, n); };
GfxReader.prototype.u64s = function(n)
{
    const out = new Array(this.count(n));
    for(let i = 0; i < n; i++) out[i] = this.u64();
    return out;
};
GfxReader.prototype.i64s = GfxReader.prototype.u64s;
/** n bytes (a copy) */
GfxReader.prototype.bytes_of = function(n)
{
    const at = this.take(this.count(n));
    return this.bytes.slice(at, at + n);
};

/**
 * Writes a reply
 * @constructor
 * @param {number=} size to start with
 */
export function GfxWriter(size)
{
    this.bytes = new Uint8Array(size || 256);
    this.view = new DataView(this.bytes.buffer);
    this.p = 0;
}

/** @param {number} n */
GfxWriter.prototype.room = function(n)
{
    const at = this.p;
    if(at + n > this.bytes.length)
    {
        const bigger = new Uint8Array(Math.max(this.bytes.length * 2, at + n));
        bigger.set(this.bytes);
        this.bytes = bigger;
        this.view = new DataView(bigger.buffer);
    }
    this.p = at + n;
    return at;
};

/** @return {!Uint8Array} what was written */
GfxWriter.prototype.result = function() { return this.bytes.subarray(0, this.p); };

GfxWriter.prototype.u8 = function(v) { const at = this.room(1); this.view.setUint8(at, v & 0xFF); };
GfxWriter.prototype.i8 = GfxWriter.prototype.u8;
GfxWriter.prototype.u16 = function(v) { const at = this.room(2); this.view.setUint16(at, v & 0xFFFF, true); };
GfxWriter.prototype.i16 = GfxWriter.prototype.u16;
GfxWriter.prototype.u32 = function(v) { const at = this.room(4); this.view.setUint32(at, v >>> 0, true); };
GfxWriter.prototype.i32 = function(v) { const at = this.room(4); this.view.setInt32(at, v | 0, true); };
GfxWriter.prototype.f32 = function(v) { const at = this.room(4); this.view.setFloat32(at, v || 0, true); };
GfxWriter.prototype.f64 = function(v) { const at = this.room(8); this.view.setFloat64(at, v || 0, true); };
GfxWriter.prototype.u64 = function(v)
{
    const at = this.room(8);
    v = v || 0;
    // (~0ULL, VK_WHOLE_SIZE: 2**64 as a number)
    if(v >= 2 ** 64)
    {
        this.view.setUint32(at, 0xFFFFFFFF, true);
        this.view.setUint32(at + 4, 0xFFFFFFFF, true);
        return;
    }
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setUint32(at + 4, high, true);
};
GfxWriter.prototype.i64 = function(v)
{
    v = v || 0;
    if(v >= 0) return this.u64(v);
    const at = this.room(8);
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, v - high * 0x100000000, true);
    this.view.setInt32(at + 4, high, true);
};
GfxWriter.prototype.h = GfxWriter.prototype.u64;
GfxWriter.prototype.be32 = function(v) { const at = this.room(4); this.view.setUint32(at, v >>> 0, false); };
GfxWriter.prototype.be64 = function(v)
{
    const at = this.room(8);
    v = v || 0;
    const high = Math.floor(v / 0x100000000);
    this.view.setUint32(at, high, false);
    this.view.setUint32(at + 4, v - high * 0x100000000, false);
};
/** a pointer's presence: what the guest compares with null */
GfxWriter.prototype.ptr = function(present) { this.be64(present ? 1 : 0); };
/** a string (latin1) in n bytes, NUL padded */
GfxWriter.prototype.str = function(s, n)
{
    const at = this.room(n);
    s = s || "";
    for(let i = 0; i < n; i++) this.bytes[at + i] = i < s.length && i < n - 1 ? s.charCodeAt(i) & 0xFF : 0;
};
/** a string's bytes, without its length */
GfxWriter.prototype.chars = function(s, n)
{
    s = s || "";
    const at = this.room(n);
    for(let i = 0; i < n; i++) this.bytes[at + i] = s.charCodeAt(i) & 0xFF;
};
/** a string: its length (big endian), then its bytes */
GfxWriter.prototype.string = function(s)
{
    s = s || "";
    this.be32(s.length);
    this.chars(s, s.length);
};
/** strings: their count (big endian), then each */
GfxWriter.prototype.strings = function(a)
{
    a = a || [];
    this.be32(a.length);
    for(const s of a) this.string(s);
};
GfxWriter.prototype.u8s = function(a, n) { for(let i = 0; i < n; i++) this.u8(a ? a[i] : 0); };
GfxWriter.prototype.u16s = function(a, n) { for(let i = 0; i < n; i++) this.u16(a ? a[i] : 0); };
GfxWriter.prototype.u32s = function(a, n) { for(let i = 0; i < n; i++) this.u32(a ? a[i] : 0); };
GfxWriter.prototype.i32s = function(a, n) { for(let i = 0; i < n; i++) this.i32(a ? a[i] : 0); };
GfxWriter.prototype.f32s = function(a, n) { for(let i = 0; i < n; i++) this.f32(a ? a[i] : 0); };
GfxWriter.prototype.u64s = function(a, n) { for(let i = 0; i < n; i++) this.u64(a ? a[i] : 0); };
GfxWriter.prototype.i64s = GfxWriter.prototype.u64s;
GfxWriter.prototype.bytes_of = function(a, n)
{
    const at = this.room(n);
    if(a) this.bytes.set(a.length > n ? a.subarray(0, n) : a, at);
};

/** VK_STRUCTURE_TYPE_MAX_ENUM: a chain's root not set yet */
const ROOT_NONE = 2147483647;

function pnext_struct(table, stype, root)
{
    const v = table[stype];
    if(!v || Array.isArray(v)) return v || null;
    return v[root] || v["default"] || null;
}
/** whether one of a[start, end) holds */
function arrayany(a, start, end, f)
{
    for(let i = start; i < end; i++) if(a && f(a[i])) return true;
    return false;
}

function ge_VkInstanceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.ptr(o.pApplicationInfo != null);
    if(o.pApplicationInfo != null)
    {
        ge_VkApplicationInfo(w, o.pApplicationInfo, root);
    }
    w.u32(o.enabledLayerCount);
    let c0 = 0;
    c0 = o.enabledLayerCount;
    w.be32(c0);
    for(let i = 0; i < c0; i++)
    {
        const l1 = o.ppEnabledLayerNames?.[i] ? o.ppEnabledLayerNames?.[i].length : 0; w.be32(l1);
        if(l1)
        {
            w.chars(o.ppEnabledLayerNames?.[i], l1);
        }
    }
    w.u32(o.enabledExtensionCount);
    let c2 = 0;
    c2 = o.enabledExtensionCount;
    w.be32(c2);
    for(let i = 0; i < c2; i++)
    {
        const l3 = o.ppEnabledExtensionNames?.[i] ? o.ppEnabledExtensionNames?.[i].length : 0; w.be32(l3);
        if(l3)
        {
            w.chars(o.ppEnabledExtensionNames?.[i], l3);
        }
    }
}

function ge_VkAllocationCallbacks(w, o, root)
{
    o = o || {};
    w.ptr(o.pUserData != null);
    if(o.pUserData != null)
    {
        w.void(o.pUserData);
    }
    w.be64(o.pfnAllocation);
    w.be64(o.pfnReallocation);
    w.be64(o.pfnFree);
    w.be64(o.pfnInternalAllocation);
    w.be64(o.pfnInternalFree);
}

function ge_VkPhysicalDeviceFeatures(w, o, root)
{
    o = o || {};
    w.u32(o.robustBufferAccess);
    w.u32(o.fullDrawIndexUint32);
    w.u32(o.imageCubeArray);
    w.u32(o.independentBlend);
    w.u32(o.geometryShader);
    w.u32(o.tessellationShader);
    w.u32(o.sampleRateShading);
    w.u32(o.dualSrcBlend);
    w.u32(o.logicOp);
    w.u32(o.multiDrawIndirect);
    w.u32(o.drawIndirectFirstInstance);
    w.u32(o.depthClamp);
    w.u32(o.depthBiasClamp);
    w.u32(o.fillModeNonSolid);
    w.u32(o.depthBounds);
    w.u32(o.wideLines);
    w.u32(o.largePoints);
    w.u32(o.alphaToOne);
    w.u32(o.multiViewport);
    w.u32(o.samplerAnisotropy);
    w.u32(o.textureCompressionETC2);
    w.u32(o.textureCompressionASTC_LDR);
    w.u32(o.textureCompressionBC);
    w.u32(o.occlusionQueryPrecise);
    w.u32(o.pipelineStatisticsQuery);
    w.u32(o.vertexPipelineStoresAndAtomics);
    w.u32(o.fragmentStoresAndAtomics);
    w.u32(o.shaderTessellationAndGeometryPointSize);
    w.u32(o.shaderImageGatherExtended);
    w.u32(o.shaderStorageImageExtendedFormats);
    w.u32(o.shaderStorageImageMultisample);
    w.u32(o.shaderStorageImageReadWithoutFormat);
    w.u32(o.shaderStorageImageWriteWithoutFormat);
    w.u32(o.shaderUniformBufferArrayDynamicIndexing);
    w.u32(o.shaderSampledImageArrayDynamicIndexing);
    w.u32(o.shaderStorageBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageImageArrayDynamicIndexing);
    w.u32(o.shaderClipDistance);
    w.u32(o.shaderCullDistance);
    w.u32(o.shaderFloat64);
    w.u32(o.shaderInt64);
    w.u32(o.shaderInt16);
    w.u32(o.shaderResourceResidency);
    w.u32(o.shaderResourceMinLod);
    w.u32(o.sparseBinding);
    w.u32(o.sparseResidencyBuffer);
    w.u32(o.sparseResidencyImage2D);
    w.u32(o.sparseResidencyImage3D);
    w.u32(o.sparseResidency2Samples);
    w.u32(o.sparseResidency4Samples);
    w.u32(o.sparseResidency8Samples);
    w.u32(o.sparseResidency16Samples);
    w.u32(o.sparseResidencyAliased);
    w.u32(o.variableMultisampleRate);
    w.u32(o.inheritedQueries);
}

function gd_VkPhysicalDeviceFeatures(r, o, root)
{
    o = o || {};
    o.robustBufferAccess = r.u32();
    o.fullDrawIndexUint32 = r.u32();
    o.imageCubeArray = r.u32();
    o.independentBlend = r.u32();
    o.geometryShader = r.u32();
    o.tessellationShader = r.u32();
    o.sampleRateShading = r.u32();
    o.dualSrcBlend = r.u32();
    o.logicOp = r.u32();
    o.multiDrawIndirect = r.u32();
    o.drawIndirectFirstInstance = r.u32();
    o.depthClamp = r.u32();
    o.depthBiasClamp = r.u32();
    o.fillModeNonSolid = r.u32();
    o.depthBounds = r.u32();
    o.wideLines = r.u32();
    o.largePoints = r.u32();
    o.alphaToOne = r.u32();
    o.multiViewport = r.u32();
    o.samplerAnisotropy = r.u32();
    o.textureCompressionETC2 = r.u32();
    o.textureCompressionASTC_LDR = r.u32();
    o.textureCompressionBC = r.u32();
    o.occlusionQueryPrecise = r.u32();
    o.pipelineStatisticsQuery = r.u32();
    o.vertexPipelineStoresAndAtomics = r.u32();
    o.fragmentStoresAndAtomics = r.u32();
    o.shaderTessellationAndGeometryPointSize = r.u32();
    o.shaderImageGatherExtended = r.u32();
    o.shaderStorageImageExtendedFormats = r.u32();
    o.shaderStorageImageMultisample = r.u32();
    o.shaderStorageImageReadWithoutFormat = r.u32();
    o.shaderStorageImageWriteWithoutFormat = r.u32();
    o.shaderUniformBufferArrayDynamicIndexing = r.u32();
    o.shaderSampledImageArrayDynamicIndexing = r.u32();
    o.shaderStorageBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageImageArrayDynamicIndexing = r.u32();
    o.shaderClipDistance = r.u32();
    o.shaderCullDistance = r.u32();
    o.shaderFloat64 = r.u32();
    o.shaderInt64 = r.u32();
    o.shaderInt16 = r.u32();
    o.shaderResourceResidency = r.u32();
    o.shaderResourceMinLod = r.u32();
    o.sparseBinding = r.u32();
    o.sparseResidencyBuffer = r.u32();
    o.sparseResidencyImage2D = r.u32();
    o.sparseResidencyImage3D = r.u32();
    o.sparseResidency2Samples = r.u32();
    o.sparseResidency4Samples = r.u32();
    o.sparseResidency8Samples = r.u32();
    o.sparseResidency16Samples = r.u32();
    o.sparseResidencyAliased = r.u32();
    o.variableMultisampleRate = r.u32();
    o.inheritedQueries = r.u32();
    return o;
}

function ge_VkFormatProperties(w, o, root)
{
    o = o || {};
    w.u32(o.linearTilingFeatures);
    w.u32(o.optimalTilingFeatures);
    w.u32(o.bufferFeatures);
}

function gd_VkFormatProperties(r, o, root)
{
    o = o || {};
    o.linearTilingFeatures = r.u32();
    o.optimalTilingFeatures = r.u32();
    o.bufferFeatures = r.u32();
    return o;
}

function ge_VkImageFormatProperties(w, o, root)
{
    o = o || {};
    ge_VkExtent3D(w, o.maxExtent, root);
    w.u32(o.maxMipLevels);
    w.u32(o.maxArrayLayers);
    w.u32(o.sampleCounts);
    w.u64(o.maxResourceSize);
}

function gd_VkImageFormatProperties(r, o, root)
{
    o = o || {};
    o.maxExtent = gd_VkExtent3D(r, o.maxExtent, root);
    o.maxMipLevels = r.u32();
    o.maxArrayLayers = r.u32();
    o.sampleCounts = r.u32();
    o.maxResourceSize = r.u64();
    return o;
}

function ge_VkPhysicalDeviceProperties(w, o, root)
{
    o = o || {};
    w.u32(o.apiVersion);
    w.u32(o.driverVersion);
    w.u32(o.vendorID);
    w.u32(o.deviceID);
    w.i32(o.deviceType);
    w.str(o.deviceName, 256);
    w.u8s(o.pipelineCacheUUID, 16);
    ge_VkPhysicalDeviceLimits(w, o.limits, root);
    ge_VkPhysicalDeviceSparseProperties(w, o.sparseProperties, root);
}

function gd_VkPhysicalDeviceProperties(r, o, root)
{
    o = o || {};
    o.apiVersion = r.u32();
    o.driverVersion = r.u32();
    o.vendorID = r.u32();
    o.deviceID = r.u32();
    o.deviceType = r.i32();
    o.deviceName = r.str(256);
    o.pipelineCacheUUID = r.u8s(16);
    o.limits = gd_VkPhysicalDeviceLimits(r, o.limits, root);
    o.sparseProperties = gd_VkPhysicalDeviceSparseProperties(r, o.sparseProperties, root);
    return o;
}

function ge_VkQueueFamilyProperties(w, o, root)
{
    o = o || {};
    w.u32(o.queueFlags);
    w.u32(o.queueCount);
    w.u32(o.timestampValidBits);
    ge_VkExtent3D(w, o.minImageTransferGranularity, root);
}

function gd_VkQueueFamilyProperties(r, o, root)
{
    o = o || {};
    o.queueFlags = r.u32();
    o.queueCount = r.u32();
    o.timestampValidBits = r.u32();
    o.minImageTransferGranularity = gd_VkExtent3D(r, o.minImageTransferGranularity, root);
    return o;
}

function ge_VkPhysicalDeviceMemoryProperties(w, o, root)
{
    o = o || {};
    w.u32(o.memoryTypeCount);
    for(let i = 0; i < 32; i++)
    {
        ge_VkMemoryType(w, o.memoryTypes?.[i], root);
    }
    w.u32(o.memoryHeapCount);
    for(let i = 0; i < 16; i++)
    {
        ge_VkMemoryHeap(w, o.memoryHeaps?.[i], root);
    }
}

function gd_VkPhysicalDeviceMemoryProperties(r, o, root)
{
    o = o || {};
    o.memoryTypeCount = r.u32();
    o.memoryTypes = new Array(r.count(32));
    for(let i = 0; i < 32; i++)
    {
        o.memoryTypes[i] = gd_VkMemoryType(r, o.memoryTypes[i], root);
    }
    o.memoryHeapCount = r.u32();
    o.memoryHeaps = new Array(r.count(16));
    for(let i = 0; i < 16; i++)
    {
        o.memoryHeaps[i] = gd_VkMemoryHeap(r, o.memoryHeaps[i], root);
    }
    return o;
}

function ge_VkDeviceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.queueCreateInfoCount);
    for(let i = 0; i < o.queueCreateInfoCount; i++)
    {
        ge_VkDeviceQueueCreateInfo(w, o.pQueueCreateInfos?.[i], root);
    }
    w.u32(o.enabledLayerCount);
    let c0 = 0;
    c0 = o.enabledLayerCount;
    w.be32(c0);
    for(let i = 0; i < c0; i++)
    {
        const l1 = o.ppEnabledLayerNames?.[i] ? o.ppEnabledLayerNames?.[i].length : 0; w.be32(l1);
        if(l1)
        {
            w.chars(o.ppEnabledLayerNames?.[i], l1);
        }
    }
    w.u32(o.enabledExtensionCount);
    let c2 = 0;
    c2 = o.enabledExtensionCount;
    w.be32(c2);
    for(let i = 0; i < c2; i++)
    {
        const l3 = o.ppEnabledExtensionNames?.[i] ? o.ppEnabledExtensionNames?.[i].length : 0; w.be32(l3);
        if(l3)
        {
            w.chars(o.ppEnabledExtensionNames?.[i], l3);
        }
    }
    w.ptr(o.pEnabledFeatures != null);
    if(o.pEnabledFeatures != null)
    {
        ge_VkPhysicalDeviceFeatures(w, o.pEnabledFeatures, root);
    }
}

function ge_VkExtensionProperties(w, o, root)
{
    o = o || {};
    w.str(o.extensionName, 256);
    w.u32(o.specVersion);
}

function gd_VkExtensionProperties(r, o, root)
{
    o = o || {};
    o.extensionName = r.str(256);
    o.specVersion = r.u32();
    return o;
}

function ge_VkLayerProperties(w, o, root)
{
    o = o || {};
    w.str(o.layerName, 256);
    w.u32(o.specVersion);
    w.u32(o.implementationVersion);
    w.str(o.description, 256);
}

function gd_VkLayerProperties(r, o, root)
{
    o = o || {};
    o.layerName = r.str(256);
    o.specVersion = r.u32();
    o.implementationVersion = r.u32();
    o.description = r.str(256);
    return o;
}

function ge_VkSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreCount);
    if(o.waitSemaphoreCount)
    {
        for(let k = 0; k < o.waitSemaphoreCount; k++)
        {
            w.h(o.pWaitSemaphores?.[k]);
        }
    }
    if((o.waitSemaphoreCount > 0))
    {
        w.u32s(o.pWaitDstStageMask, o.waitSemaphoreCount);
    }
    w.u32(o.commandBufferCount);
    if(o.commandBufferCount)
    {
        for(let k = 0; k < o.commandBufferCount; k++)
        {
            w.h(o.pCommandBuffers?.[k]);
        }
    }
    w.u32(o.signalSemaphoreCount);
    if(o.signalSemaphoreCount)
    {
        for(let k = 0; k < o.signalSemaphoreCount; k++)
        {
            w.h(o.pSignalSemaphores?.[k]);
        }
    }
}

function ge_VkMemoryAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.allocationSize);
    w.u32(o.memoryTypeIndex);
}

function ge_VkMappedMemoryRange(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.memory);
    w.u64(o.offset);
    w.u64(o.size);
}

function ge_VkMemoryRequirements(w, o, root)
{
    o = o || {};
    w.u64(o.size);
    w.u64(o.alignment);
    w.u32(o.memoryTypeBits);
}

function gd_VkMemoryRequirements(r, o, root)
{
    o = o || {};
    o.size = r.u64();
    o.alignment = r.u64();
    o.memoryTypeBits = r.u32();
    return o;
}

function ge_VkSparseImageMemoryRequirements(w, o, root)
{
    o = o || {};
    ge_VkSparseImageFormatProperties(w, o.formatProperties, root);
    w.u32(o.imageMipTailFirstLod);
    w.u64(o.imageMipTailSize);
    w.u64(o.imageMipTailOffset);
    w.u64(o.imageMipTailStride);
}

function gd_VkSparseImageMemoryRequirements(r, o, root)
{
    o = o || {};
    o.formatProperties = gd_VkSparseImageFormatProperties(r, o.formatProperties, root);
    o.imageMipTailFirstLod = r.u32();
    o.imageMipTailSize = r.u64();
    o.imageMipTailOffset = r.u64();
    o.imageMipTailStride = r.u64();
    return o;
}

function ge_VkSparseImageFormatProperties(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    ge_VkExtent3D(w, o.imageGranularity, root);
    w.u32(o.flags);
}

function gd_VkSparseImageFormatProperties(r, o, root)
{
    o = o || {};
    o.aspectMask = r.u32();
    o.imageGranularity = gd_VkExtent3D(r, o.imageGranularity, root);
    o.flags = r.u32();
    return o;
}

function ge_VkBindSparseInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreCount);
    if(o.waitSemaphoreCount)
    {
        for(let k = 0; k < o.waitSemaphoreCount; k++)
        {
            w.h(o.pWaitSemaphores?.[k]);
        }
    }
    w.u32(o.bufferBindCount);
    for(let i = 0; i < o.bufferBindCount; i++)
    {
        ge_VkSparseBufferMemoryBindInfo(w, o.pBufferBinds?.[i], root);
    }
    w.u32(o.imageOpaqueBindCount);
    for(let i = 0; i < o.imageOpaqueBindCount; i++)
    {
        ge_VkSparseImageOpaqueMemoryBindInfo(w, o.pImageOpaqueBinds?.[i], root);
    }
    w.u32(o.imageBindCount);
    for(let i = 0; i < o.imageBindCount; i++)
    {
        ge_VkSparseImageMemoryBindInfo(w, o.pImageBinds?.[i], root);
    }
    w.u32(o.signalSemaphoreCount);
    if(o.signalSemaphoreCount)
    {
        for(let k = 0; k < o.signalSemaphoreCount; k++)
        {
            w.h(o.pSignalSemaphores?.[k]);
        }
    }
}

function ge_VkFenceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function ge_VkSemaphoreCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function ge_VkEventCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function ge_VkQueryPoolCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.queryType);
    w.u32(o.queryCount);
    w.u32(o.pipelineStatistics);
}

function ge_VkBufferCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u64(o.size);
    w.u32(o.usage);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    w.ptr(o.pQueueFamilyIndices != null);
    if(o.pQueueFamilyIndices != null)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
        }
    }
}

function ge_VkBufferViewCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.buffer);
    w.i32(o.format);
    w.u64(o.offset);
    w.u64(o.range);
}

function ge_VkImageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.imageType);
    w.i32(o.format);
    ge_VkExtent3D(w, o.extent, root);
    w.u32(o.mipLevels);
    w.u32(o.arrayLayers);
    w.i32(o.samples);
    w.i32(o.tiling);
    w.u32(o.usage);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    w.ptr(o.pQueueFamilyIndices != null);
    if(o.pQueueFamilyIndices != null)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
        }
    }
    w.i32(o.initialLayout);
}

function ge_VkImageSubresource(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    w.u32(o.mipLevel);
    w.u32(o.arrayLayer);
}

function ge_VkSubresourceLayout(w, o, root)
{
    o = o || {};
    w.u64(o.offset);
    w.u64(o.size);
    w.u64(o.rowPitch);
    w.u64(o.arrayPitch);
    w.u64(o.depthPitch);
}

function gd_VkSubresourceLayout(r, o, root)
{
    o = o || {};
    o.offset = r.u64();
    o.size = r.u64();
    o.rowPitch = r.u64();
    o.arrayPitch = r.u64();
    o.depthPitch = r.u64();
    return o;
}

function ge_VkImageViewCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.image);
    w.i32(o.viewType);
    w.i32(o.format);
    ge_VkComponentMapping(w, o.components, root);
    ge_VkImageSubresourceRange(w, o.subresourceRange, root);
}

function ge_VkShaderModuleCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.be64(o.codeSize);
    if((Math.trunc(o.codeSize / 4) > 0))
    {
        w.u32s(o.pCode, Math.trunc(o.codeSize / 4));
    }
}

function ge_VkPipelineCacheCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.be64(o.initialDataSize);
    if((o.initialDataSize > 0))
    {
        w.bytes_of(o.pInitialData, o.initialDataSize);
    }
}

function ge_VkGraphicsPipelineCreateInfo(w, o, root)
{
    o = o || {};
    let hasRasterization = 1;
    hasRasterization = (((o.pRasterizationState == null) ? 0 : !o.pRasterizationState.rasterizerDiscardEnable) || ((o.pDynamicState == null) ? 0 : arrayany(o.pDynamicState.pDynamicStates, 0, o.pDynamicState.dynamicStateCount, s => (s === 1000377001)))) ? 1 : 0;
    w.be32(hasRasterization);
    let hasTessellation = 1;
    hasTessellation = arrayany(o.pStages, 0, o.stageCount, s => ((s.stage === 2) || (s.stage === 4))) ? 1 : 0;
    w.be32(hasTessellation);
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.stageCount);
    for(let i = 0; i < o.stageCount; i++)
    {
        ge_VkPipelineShaderStageCreateInfo(w, o.pStages?.[i], root);
    }
    w.ptr(o.pVertexInputState != null);
    if(o.pVertexInputState != null)
    {
        ge_VkPipelineVertexInputStateCreateInfo(w, o.pVertexInputState, root);
    }
    w.ptr(o.pInputAssemblyState != null);
    if(o.pInputAssemblyState != null)
    {
        ge_VkPipelineInputAssemblyStateCreateInfo(w, o.pInputAssemblyState, root);
    }
    w.ptr(o.pTessellationState != null);
    if(o.pTessellationState != null)
    {
        if(hasTessellation)
        {
            ge_VkPipelineTessellationStateCreateInfo(w, o.pTessellationState, root);
        }
    }
    w.ptr(o.pViewportState != null);
    if(o.pViewportState != null)
    {
        if(hasRasterization)
        {
            ge_VkPipelineViewportStateCreateInfo(w, o.pViewportState, root);
        }
    }
    w.ptr(o.pRasterizationState != null);
    if(o.pRasterizationState != null)
    {
        ge_VkPipelineRasterizationStateCreateInfo(w, o.pRasterizationState, root);
    }
    w.ptr(o.pMultisampleState != null);
    if(o.pMultisampleState != null)
    {
        if(hasRasterization)
        {
            ge_VkPipelineMultisampleStateCreateInfo(w, o.pMultisampleState, root);
        }
    }
    w.ptr(o.pDepthStencilState != null);
    if(o.pDepthStencilState != null)
    {
        if(hasRasterization)
        {
            ge_VkPipelineDepthStencilStateCreateInfo(w, o.pDepthStencilState, root);
        }
    }
    w.ptr(o.pColorBlendState != null);
    if(o.pColorBlendState != null)
    {
        if(hasRasterization)
        {
            ge_VkPipelineColorBlendStateCreateInfo(w, o.pColorBlendState, root);
        }
    }
    w.ptr(o.pDynamicState != null);
    if(o.pDynamicState != null)
    {
        ge_VkPipelineDynamicStateCreateInfo(w, o.pDynamicState, root);
    }
    w.h(o.layout);
    w.h(o.renderPass);
    w.u32(o.subpass);
    w.h(o.basePipelineHandle);
    w.i32(o.basePipelineIndex);
}

function ge_VkComputePipelineCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    ge_VkPipelineShaderStageCreateInfo(w, o.stage, root);
    w.h(o.layout);
    w.h(o.basePipelineHandle);
    w.i32(o.basePipelineIndex);
}

function ge_VkPipelineLayoutCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.setLayoutCount);
    if(o.setLayoutCount)
    {
        for(let k = 0; k < o.setLayoutCount; k++)
        {
            w.h(o.pSetLayouts?.[k]);
        }
    }
    w.u32(o.pushConstantRangeCount);
    for(let i = 0; i < o.pushConstantRangeCount; i++)
    {
        ge_VkPushConstantRange(w, o.pPushConstantRanges?.[i], root);
    }
}

function ge_VkSamplerCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.magFilter);
    w.i32(o.minFilter);
    w.i32(o.mipmapMode);
    w.i32(o.addressModeU);
    w.i32(o.addressModeV);
    w.i32(o.addressModeW);
    w.f32(o.mipLodBias);
    w.u32(o.anisotropyEnable);
    w.f32(o.maxAnisotropy);
    w.u32(o.compareEnable);
    w.i32(o.compareOp);
    w.f32(o.minLod);
    w.f32(o.maxLod);
    w.i32(o.borderColor);
    w.u32(o.unnormalizedCoordinates);
}

function ge_VkDescriptorSetLayoutCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.bindingCount);
    for(let i = 0; i < o.bindingCount; i++)
    {
        ge_VkDescriptorSetLayoutBinding(w, o.pBindings?.[i], root);
    }
}

function ge_VkDescriptorPoolCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.maxSets);
    w.u32(o.poolSizeCount);
    for(let i = 0; i < o.poolSizeCount; i++)
    {
        ge_VkDescriptorPoolSize(w, o.pPoolSizes?.[i], root);
    }
}

function ge_VkDescriptorSetAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.descriptorPool);
    w.u32(o.descriptorSetCount);
    if(o.descriptorSetCount)
    {
        for(let k = 0; k < o.descriptorSetCount; k++)
        {
            w.h(o.pSetLayouts?.[k]);
        }
    }
}

function ge_VkWriteDescriptorSet(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.dstSet);
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
    w.i32(o.descriptorType);
    w.ptr(o.pImageInfo != null);
    if(o.pImageInfo != null)
    {
        if((((((0 === o.descriptorType) || (1 === o.descriptorType)) || (2 === o.descriptorType)) || (3 === o.descriptorType)) || (10 === o.descriptorType)))
        {
            for(let i = 0; i < o.descriptorCount; i++)
            {
                ge_VkDescriptorImageInfo(w, o.pImageInfo?.[i], root);
            }
        }
    }
    w.ptr(o.pBufferInfo != null);
    if(o.pBufferInfo != null)
    {
        if(((((6 === o.descriptorType) || (8 === o.descriptorType)) || (7 === o.descriptorType)) || (9 === o.descriptorType)))
        {
            for(let i = 0; i < o.descriptorCount; i++)
            {
                ge_VkDescriptorBufferInfo(w, o.pBufferInfo?.[i], root);
            }
        }
    }
    w.ptr(o.pTexelBufferView != null);
    if(o.pTexelBufferView != null)
    {
        if(((4 === o.descriptorType) || (5 === o.descriptorType)))
        {
            if(o.descriptorCount)
            {
                for(let k = 0; k < o.descriptorCount; k++)
                {
                    w.h(o.pTexelBufferView?.[k]);
                }
            }
        }
    }
}

function ge_VkCopyDescriptorSet(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcSet);
    w.u32(o.srcBinding);
    w.u32(o.srcArrayElement);
    w.h(o.dstSet);
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
}

function ge_VkFramebufferCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.renderPass);
    w.u32(o.attachmentCount);
    if(((o.flags & 1) === 0))
    {
        if(o.attachmentCount)
        {
            for(let k = 0; k < o.attachmentCount; k++)
            {
                w.h(o.pAttachments?.[k]);
            }
        }
    }
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.layers);
}

function ge_VkRenderPassCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.attachmentCount);
    for(let i = 0; i < o.attachmentCount; i++)
    {
        ge_VkAttachmentDescription(w, o.pAttachments?.[i], root);
    }
    w.u32(o.subpassCount);
    for(let i = 0; i < o.subpassCount; i++)
    {
        ge_VkSubpassDescription(w, o.pSubpasses?.[i], root);
    }
    w.u32(o.dependencyCount);
    for(let i = 0; i < o.dependencyCount; i++)
    {
        ge_VkSubpassDependency(w, o.pDependencies?.[i], root);
    }
}

function ge_VkExtent2D(w, o, root)
{
    o = o || {};
    w.u32(o.width);
    w.u32(o.height);
}

function gd_VkExtent2D(r, o, root)
{
    o = o || {};
    o.width = r.u32();
    o.height = r.u32();
    return o;
}

function ge_VkCommandPoolCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
}

function ge_VkCommandBufferAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.commandPool);
    w.i32(o.level);
    w.u32(o.commandBufferCount);
}

function ge_VkCommandBufferBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.ptr(o.pInheritanceInfo != null);
    if(o.pInheritanceInfo != null)
    {
        ge_VkCommandBufferInheritanceInfo(w, o.pInheritanceInfo, root);
    }
}

function ge_VkViewport(w, o, root)
{
    o = o || {};
    w.f32(o.x);
    w.f32(o.y);
    w.f32(o.width);
    w.f32(o.height);
    w.f32(o.minDepth);
    w.f32(o.maxDepth);
}

function ge_VkRect2D(w, o, root)
{
    o = o || {};
    ge_VkOffset2D(w, o.offset, root);
    ge_VkExtent2D(w, o.extent, root);
}

function ge_VkBufferCopy(w, o, root)
{
    o = o || {};
    w.u64(o.srcOffset);
    w.u64(o.dstOffset);
    w.u64(o.size);
}

function ge_VkImageCopy(w, o, root)
{
    o = o || {};
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    ge_VkOffset3D(w, o.srcOffset, root);
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    ge_VkOffset3D(w, o.dstOffset, root);
    ge_VkExtent3D(w, o.extent, root);
}

function ge_VkImageBlit(w, o, root)
{
    o = o || {};
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    for(let i = 0; i < 2; i++)
    {
        ge_VkOffset3D(w, o.srcOffsets?.[i], root);
    }
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    for(let i = 0; i < 2; i++)
    {
        ge_VkOffset3D(w, o.dstOffsets?.[i], root);
    }
}

function ge_VkBufferImageCopy(w, o, root)
{
    o = o || {};
    w.u64(o.bufferOffset);
    w.u32(o.bufferRowLength);
    w.u32(o.bufferImageHeight);
    ge_VkImageSubresourceLayers(w, o.imageSubresource, root);
    ge_VkOffset3D(w, o.imageOffset, root);
    ge_VkExtent3D(w, o.imageExtent, root);
}

function ge_VkClearColorValue(w, o, root)
{
    o = o || {};
    w.f32s(o.float32, 4);
}

function ge_VkImageSubresourceRange(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    w.u32(o.baseMipLevel);
    w.u32(o.levelCount);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}

function ge_VkClearDepthStencilValue(w, o, root)
{
    o = o || {};
    w.f32(o.depth);
    w.u32(o.stencil);
}

function ge_VkClearAttachment(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    w.u32(o.colorAttachment);
    ge_VkClearValue(w, o.clearValue, root);
}

function ge_VkClearRect(w, o, root)
{
    o = o || {};
    ge_VkRect2D(w, o.rect, root);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}

function ge_VkImageResolve(w, o, root)
{
    o = o || {};
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    ge_VkOffset3D(w, o.srcOffset, root);
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    ge_VkOffset3D(w, o.dstOffset, root);
    ge_VkExtent3D(w, o.extent, root);
}

function ge_VkMemoryBarrier(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
}

function ge_VkBufferMemoryBarrier(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.size);
}

function ge_VkImageMemoryBarrier(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.image);
    ge_VkImageSubresourceRange(w, o.subresourceRange, root);
}

function ge_VkRenderPassBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.renderPass);
    w.h(o.framebuffer);
    ge_VkRect2D(w, o.renderArea, root);
    w.u32(o.clearValueCount);
    w.ptr(o.pClearValues != null);
    if(o.pClearValues != null)
    {
        for(let i = 0; i < o.clearValueCount; i++)
        {
            ge_VkClearValue(w, o.pClearValues?.[i], root);
        }
    }
}

function ge_VkBindBufferMemoryInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.buffer);
    w.h(o.memory);
    w.u64(o.memoryOffset);
}

function ge_VkBindImageMemoryInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.image);
    w.h(o.memory);
    w.u64(o.memoryOffset);
}

function ge_VkPhysicalDeviceGroupProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.physicalDeviceCount);
    w.u64s(o.physicalDevices, 32);
    w.u32(o.subsetAllocation);
}

function gd_VkPhysicalDeviceGroupProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.physicalDeviceCount = r.u32();
    o.physicalDevices = r.u64s(32);
    o.subsetAllocation = r.u32();
    return o;
}

function ge_VkImageMemoryRequirementsInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.image);
}

function ge_VkMemoryRequirements2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkMemoryRequirements(w, o.memoryRequirements, root);
}

function gd_VkMemoryRequirements2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.memoryRequirements = gd_VkMemoryRequirements(r, o.memoryRequirements, root);
    return o;
}

function ge_VkBufferMemoryRequirementsInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.buffer);
}

function ge_VkImageSparseMemoryRequirementsInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.image);
}

function ge_VkSparseImageMemoryRequirements2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkSparseImageMemoryRequirements(w, o.memoryRequirements, root);
}

function gd_VkSparseImageMemoryRequirements2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.memoryRequirements = gd_VkSparseImageMemoryRequirements(r, o.memoryRequirements, root);
    return o;
}

function ge_VkPhysicalDeviceFeatures2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkPhysicalDeviceFeatures(w, o.features, root);
}

function gd_VkPhysicalDeviceFeatures2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.features = gd_VkPhysicalDeviceFeatures(r, o.features, root);
    return o;
}

function ge_VkPhysicalDeviceProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkPhysicalDeviceProperties(w, o.properties, root);
}

function gd_VkPhysicalDeviceProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.properties = gd_VkPhysicalDeviceProperties(r, o.properties, root);
    return o;
}

function ge_VkFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkFormatProperties(w, o.formatProperties, root);
}

function gd_VkFormatProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.formatProperties = gd_VkFormatProperties(r, o.formatProperties, root);
    return o;
}

function ge_VkPhysicalDeviceImageFormatInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.format);
    w.i32(o.type);
    w.i32(o.tiling);
    w.u32(o.usage);
    w.u32(o.flags);
}

function ge_VkImageFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageFormatProperties(w, o.imageFormatProperties, root);
}

function gd_VkImageFormatProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imageFormatProperties = gd_VkImageFormatProperties(r, o.imageFormatProperties, root);
    return o;
}

function ge_VkQueueFamilyProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkQueueFamilyProperties(w, o.queueFamilyProperties, root);
}

function gd_VkQueueFamilyProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.queueFamilyProperties = gd_VkQueueFamilyProperties(r, o.queueFamilyProperties, root);
    return o;
}

function ge_VkPhysicalDeviceMemoryProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkPhysicalDeviceMemoryProperties(w, o.memoryProperties, root);
}

function gd_VkPhysicalDeviceMemoryProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.memoryProperties = gd_VkPhysicalDeviceMemoryProperties(r, o.memoryProperties, root);
    return o;
}

function ge_VkPhysicalDeviceSparseImageFormatInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.format);
    w.i32(o.type);
    w.i32(o.samples);
    w.u32(o.usage);
    w.i32(o.tiling);
}

function ge_VkSparseImageFormatProperties2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkSparseImageFormatProperties(w, o.properties, root);
}

function gd_VkSparseImageFormatProperties2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.properties = gd_VkSparseImageFormatProperties(r, o.properties, root);
    return o;
}

function ge_VkDeviceQueueInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
    w.u32(o.queueIndex);
}

function ge_VkSamplerYcbcrConversionCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.format);
    w.i32(o.ycbcrModel);
    w.i32(o.ycbcrRange);
    ge_VkComponentMapping(w, o.components, root);
    w.i32(o.xChromaOffset);
    w.i32(o.yChromaOffset);
    w.i32(o.chromaFilter);
    w.u32(o.forceExplicitReconstruction);
}

function ge_VkDescriptorUpdateTemplateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.descriptorUpdateEntryCount);
    for(let i = 0; i < o.descriptorUpdateEntryCount; i++)
    {
        ge_VkDescriptorUpdateTemplateEntry(w, o.pDescriptorUpdateEntries?.[i], root);
    }
    w.i32(o.templateType);
    w.h(o.descriptorSetLayout);
    w.i32(o.pipelineBindPoint);
    w.h(o.pipelineLayout);
    w.u32(o.set);
}

function ge_VkPhysicalDeviceExternalBufferInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.usage);
    w.i32(o.handleType);
}

function ge_VkExternalBufferProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkExternalMemoryProperties(w, o.externalMemoryProperties, root);
}

function gd_VkExternalBufferProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.externalMemoryProperties = gd_VkExternalMemoryProperties(r, o.externalMemoryProperties, root);
    return o;
}

function ge_VkPhysicalDeviceExternalFenceInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.handleType);
}

function ge_VkExternalFenceProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalFenceFeatures);
}

function gd_VkExternalFenceProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalFenceFeatures = r.u32();
    return o;
}

function ge_VkPhysicalDeviceExternalSemaphoreInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.handleType);
}

function ge_VkExternalSemaphoreProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
    w.u32(o.externalSemaphoreFeatures);
}

function gd_VkExternalSemaphoreProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalSemaphoreFeatures = r.u32();
    return o;
}

function ge_VkDescriptorSetLayoutSupport(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.supported);
}

function gd_VkDescriptorSetLayoutSupport(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.supported = r.u32();
    return o;
}

function ge_VkRenderPassCreateInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.attachmentCount);
    for(let i = 0; i < o.attachmentCount; i++)
    {
        ge_VkAttachmentDescription2(w, o.pAttachments?.[i], root);
    }
    w.u32(o.subpassCount);
    for(let i = 0; i < o.subpassCount; i++)
    {
        ge_VkSubpassDescription2(w, o.pSubpasses?.[i], root);
    }
    w.u32(o.dependencyCount);
    for(let i = 0; i < o.dependencyCount; i++)
    {
        ge_VkSubpassDependency2(w, o.pDependencies?.[i], root);
    }
    w.u32(o.correlatedViewMaskCount);
    if((o.correlatedViewMaskCount > 0))
    {
        w.u32s(o.pCorrelatedViewMasks, o.correlatedViewMaskCount);
    }
}

function ge_VkSubpassBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.contents);
}

function ge_VkSubpassEndInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
}

function ge_VkSemaphoreWaitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.semaphoreCount);
    if(o.semaphoreCount)
    {
        for(let k = 0; k < o.semaphoreCount; k++)
        {
            w.h(o.pSemaphores?.[k]);
        }
    }
    if((o.semaphoreCount > 0))
    {
        w.u64s(o.pValues, o.semaphoreCount);
    }
}

function ge_VkSemaphoreSignalInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.semaphore);
    w.u64(o.value);
}

function ge_VkBufferDeviceAddressInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.buffer);
}

function ge_VkDeviceMemoryOpaqueCaptureAddressInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.memory);
}

function ge_VkPhysicalDeviceToolProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.version, 256);
    w.u32(o.purposes);
    w.str(o.description, 256);
    w.str(o.layer, 256);
}

function gd_VkPhysicalDeviceToolProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.name = r.str(256);
    o.version = r.str(256);
    o.purposes = r.u32();
    o.description = r.str(256);
    o.layer = r.str(256);
    return o;
}

function ge_VkPrivateDataSlotCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function ge_VkDependencyInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.dependencyFlags);
    w.u32(o.memoryBarrierCount);
    for(let i = 0; i < o.memoryBarrierCount; i++)
    {
        ge_VkMemoryBarrier2(w, o.pMemoryBarriers?.[i], root);
    }
    w.u32(o.bufferMemoryBarrierCount);
    for(let i = 0; i < o.bufferMemoryBarrierCount; i++)
    {
        ge_VkBufferMemoryBarrier2(w, o.pBufferMemoryBarriers?.[i], root);
    }
    w.u32(o.imageMemoryBarrierCount);
    for(let i = 0; i < o.imageMemoryBarrierCount; i++)
    {
        ge_VkImageMemoryBarrier2(w, o.pImageMemoryBarriers?.[i], root);
    }
}

function ge_VkSubmitInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.waitSemaphoreInfoCount);
    for(let i = 0; i < o.waitSemaphoreInfoCount; i++)
    {
        ge_VkSemaphoreSubmitInfo(w, o.pWaitSemaphoreInfos?.[i], root);
    }
    w.u32(o.commandBufferInfoCount);
    for(let i = 0; i < o.commandBufferInfoCount; i++)
    {
        ge_VkCommandBufferSubmitInfo(w, o.pCommandBufferInfos?.[i], root);
    }
    w.u32(o.signalSemaphoreInfoCount);
    for(let i = 0; i < o.signalSemaphoreInfoCount; i++)
    {
        ge_VkSemaphoreSubmitInfo(w, o.pSignalSemaphoreInfos?.[i], root);
    }
}

function ge_VkCopyBufferInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcBuffer);
    w.h(o.dstBuffer);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkBufferCopy2(w, o.pRegions?.[i], root);
    }
}

function ge_VkCopyImageInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkImageCopy2(w, o.pRegions?.[i], root);
    }
}

function ge_VkCopyBufferToImageInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcBuffer);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkBufferImageCopy2(w, o.pRegions?.[i], root);
    }
}

function ge_VkCopyImageToBufferInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstBuffer);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkBufferImageCopy2(w, o.pRegions?.[i], root);
    }
}

function ge_VkBlitImageInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkImageBlit2(w, o.pRegions?.[i], root);
    }
    w.i32(o.filter);
}

function ge_VkResolveImageInfo2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkImageResolve2(w, o.pRegions?.[i], root);
    }
}

function ge_VkRenderingInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    ge_VkRect2D(w, o.renderArea, root);
    w.u32(o.layerCount);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        ge_VkRenderingAttachmentInfo(w, o.pColorAttachments?.[i], root);
    }
    w.ptr(o.pDepthAttachment != null);
    if(o.pDepthAttachment != null)
    {
        ge_VkRenderingAttachmentInfo(w, o.pDepthAttachment, root);
    }
    w.ptr(o.pStencilAttachment != null);
    if(o.pStencilAttachment != null)
    {
        ge_VkRenderingAttachmentInfo(w, o.pStencilAttachment, root);
    }
}

function ge_VkDeviceBufferMemoryRequirements(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkBufferCreateInfo(w, o.pCreateInfo, root);
}

function ge_VkDeviceImageMemoryRequirements(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageCreateInfo(w, o.pCreateInfo, root);
    w.i32(o.planeAspect);
}

function ge_VkMemoryMapInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.memory);
    w.u64(o.offset);
    w.u64(o.size);
}

function ge_VkMemoryUnmapInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.memory);
}

function ge_VkRenderingAreaInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentFormats != null);
    if(o.pColorAttachmentFormats != null)
    {
        if((o.colorAttachmentCount > 0))
        {
            w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
        }
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
}

function ge_VkDeviceImageSubresourceInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageCreateInfo(w, o.pCreateInfo, root);
    ge_VkImageSubresource2(w, o.pSubresource, root);
}

function ge_VkSubresourceLayout2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkSubresourceLayout(w, o.subresourceLayout, root);
}

function gd_VkSubresourceLayout2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.subresourceLayout = gd_VkSubresourceLayout(r, o.subresourceLayout, root);
    return o;
}

function ge_VkImageSubresource2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageSubresource(w, o.imageSubresource, root);
}

function ge_VkRenderingAttachmentLocationInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentLocations != null);
    if(o.pColorAttachmentLocations != null)
    {
        if((o.colorAttachmentCount > 0))
        {
            w.u32s(o.pColorAttachmentLocations, o.colorAttachmentCount);
        }
    }
}

function ge_VkRenderingInputAttachmentIndexInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentInputIndices != null);
    if(o.pColorAttachmentInputIndices != null)
    {
        if((o.colorAttachmentCount > 0))
        {
            w.u32s(o.pColorAttachmentInputIndices, o.colorAttachmentCount);
        }
    }
    w.ptr(o.pDepthInputAttachmentIndex != null);
    if(o.pDepthInputAttachmentIndex != null)
    {
        w.u32(o.pDepthInputAttachmentIndex);
    }
    w.ptr(o.pStencilInputAttachmentIndex != null);
    if(o.pStencilInputAttachmentIndex != null)
    {
        w.u32(o.pStencilInputAttachmentIndex);
    }
}

function ge_VkBindDescriptorSetsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.stageFlags);
    w.h(o.layout);
    w.u32(o.firstSet);
    w.u32(o.descriptorSetCount);
    if(o.descriptorSetCount)
    {
        for(let k = 0; k < o.descriptorSetCount; k++)
        {
            w.h(o.pDescriptorSets?.[k]);
        }
    }
    w.u32(o.dynamicOffsetCount);
    w.ptr(o.pDynamicOffsets != null);
    if(o.pDynamicOffsets != null)
    {
        if((o.dynamicOffsetCount > 0))
        {
            w.u32s(o.pDynamicOffsets, o.dynamicOffsetCount);
        }
    }
}

function ge_VkPushConstantsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.layout);
    w.u32(o.stageFlags);
    w.u32(o.offset);
    w.u32(o.size);
    if((o.size > 0))
    {
        w.bytes_of(o.pValues, o.size);
    }
}

function ge_VkPushDescriptorSetInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.stageFlags);
    w.h(o.layout);
    w.u32(o.set);
    w.u32(o.descriptorWriteCount);
    for(let i = 0; i < o.descriptorWriteCount; i++)
    {
        ge_VkWriteDescriptorSet(w, o.pDescriptorWrites?.[i], root);
    }
}

function ge_VkPushDescriptorSetWithTemplateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.descriptorUpdateTemplate);
    w.h(o.layout);
    w.u32(o.set);
    w.void(o.pData);
}

function ge_VkCopyMemoryToImageInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkMemoryToImageCopy(w, o.pRegions?.[i], root);
    }
}

function ge_VkCopyImageToMemoryInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkImageToMemoryCopy(w, o.pRegions?.[i], root);
    }
}

function ge_VkCopyImageToImageInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    for(let i = 0; i < o.regionCount; i++)
    {
        ge_VkImageCopy2(w, o.pRegions?.[i], root);
    }
}

function ge_VkHostImageLayoutTransitionInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.image);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    ge_VkImageSubresourceRange(w, o.subresourceRange, root);
}

function ge_VkImportSemaphoreFdInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.semaphore);
    w.u32(o.flags);
    w.i32(o.handleType);
    w.i32(o.fd);
}

function ge_VkSemaphoreGetFdInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.semaphore);
    w.i32(o.handleType);
}

function ge_VkImportFenceFdInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.fence);
    w.u32(o.flags);
    w.i32(o.handleType);
    w.i32(o.fd);
}

function ge_VkFenceGetFdInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.fence);
    w.i32(o.handleType);
}

function ge_VkPipelineInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.pipeline);
}

function ge_VkPipelineExecutablePropertiesKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.stages);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.u32(o.subgroupSize);
}

function gd_VkPipelineExecutablePropertiesKHR(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.stages = r.u32();
    o.name = r.str(256);
    o.description = r.str(256);
    o.subgroupSize = r.u32();
    return o;
}

function ge_VkPipelineExecutableInfoKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.pipeline);
    w.u32(o.executableIndex);
}

function ge_VkPipelineExecutableStatisticKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.i32(o.format);
    ge_VkPipelineExecutableStatisticValueKHR(w, o.value, root);
}

function gd_VkPipelineExecutableStatisticKHR(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.name = r.str(256);
    o.description = r.str(256);
    o.format = r.i32();
    o.value = gd_VkPipelineExecutableStatisticValueKHR(r, o.value, root);
    return o;
}

function ge_VkPipelineExecutableInternalRepresentationKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.str(o.name, 256);
    w.str(o.description, 256);
    w.u32(o.isText);
    w.be64(o.dataSize);
    w.ptr(o.pData != null);
    if(o.pData != null)
    {
        if((o.dataSize > 0))
        {
            w.bytes_of(o.pData, o.dataSize);
        }
    }
}

function gd_VkPipelineExecutableInternalRepresentationKHR(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.name = r.str(256);
    o.description = r.str(256);
    o.isText = r.u32();
    o.dataSize = r.be64();
    r.ptr();
    if(o.pData != null)
    {
        o.pData = r.bytes_of(o.dataSize);
    }
    return o;
}

function ge_VkImageDrmFormatModifierPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
}

function gd_VkImageDrmFormatModifierPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifier = r.u64();
    return o;
}

function ge_VkDescriptorImageInfo(w, o, root)
{
    o = o || {};
    w.h(o.sampler);
    w.h(o.imageView);
    w.i32(o.imageLayout);
}

function ge_VkDescriptorBufferInfo(w, o, root)
{
    o = o || {};
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.range);
}

function ge_VkPhysicalDeviceSubgroupProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.subgroupSize);
    w.u32(o.supportedStages);
    w.u32(o.supportedOperations);
    w.u32(o.quadOperationsInAllStages);
}

function ge_VkPhysicalDevice16BitStorageFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
}

function ge_VkMemoryDedicatedRequirements(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.prefersDedicatedAllocation);
    w.u32(o.requiresDedicatedAllocation);
}

function ge_VkMemoryDedicatedAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.image);
    w.h(o.buffer);
}

function ge_VkMemoryAllocateFlagsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.deviceMask);
}

function ge_VkDeviceGroupRenderPassBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.deviceMask);
    w.u32(o.deviceRenderAreaCount);
    for(let i = 0; i < o.deviceRenderAreaCount; i++)
    {
        ge_VkRect2D(w, o.pDeviceRenderAreas?.[i], root);
    }
}

function ge_VkDeviceGroupCommandBufferBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.deviceMask);
}

function ge_VkDeviceGroupSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreCount);
    if((o.waitSemaphoreCount > 0))
    {
        w.u32s(o.pWaitSemaphoreDeviceIndices, o.waitSemaphoreCount);
    }
    w.u32(o.commandBufferCount);
    if((o.commandBufferCount > 0))
    {
        w.u32s(o.pCommandBufferDeviceMasks, o.commandBufferCount);
    }
    w.u32(o.signalSemaphoreCount);
    if((o.signalSemaphoreCount > 0))
    {
        w.u32s(o.pSignalSemaphoreDeviceIndices, o.signalSemaphoreCount);
    }
}

function ge_VkDeviceGroupBindSparseInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.resourceDeviceIndex);
    w.u32(o.memoryDeviceIndex);
}

function ge_VkBindBufferMemoryDeviceGroupInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.deviceIndexCount);
    if((o.deviceIndexCount > 0))
    {
        w.u32s(o.pDeviceIndices, o.deviceIndexCount);
    }
}

function ge_VkBindImageMemoryDeviceGroupInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.deviceIndexCount);
    if((o.deviceIndexCount > 0))
    {
        w.u32s(o.pDeviceIndices, o.deviceIndexCount);
    }
    w.u32(o.splitInstanceBindRegionCount);
    for(let i = 0; i < o.splitInstanceBindRegionCount; i++)
    {
        ge_VkRect2D(w, o.pSplitInstanceBindRegions?.[i], root);
    }
}

function ge_VkDeviceGroupDeviceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.physicalDeviceCount);
    if(o.physicalDeviceCount)
    {
        for(let k = 0; k < o.physicalDeviceCount; k++)
        {
            w.h(o.pPhysicalDevices?.[k]);
        }
    }
}

function ge_VkPhysicalDevicePointClippingProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.pointClippingBehavior);
}

function ge_VkRenderPassInputAttachmentAspectCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.aspectReferenceCount);
    for(let i = 0; i < o.aspectReferenceCount; i++)
    {
        ge_VkInputAttachmentAspectReference(w, o.pAspectReferences?.[i], root);
    }
}

function ge_VkImageViewUsageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.usage);
}

function ge_VkPipelineTessellationDomainOriginStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.domainOrigin);
}

function ge_VkRenderPassMultiviewCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.subpassCount);
    if((o.subpassCount > 0))
    {
        w.u32s(o.pViewMasks, o.subpassCount);
    }
    w.u32(o.dependencyCount);
    if((o.dependencyCount > 0))
    {
        w.i32s(o.pViewOffsets, o.dependencyCount);
    }
    w.u32(o.correlationMaskCount);
    if((o.correlationMaskCount > 0))
    {
        w.u32s(o.pCorrelationMasks, o.correlationMaskCount);
    }
}

function ge_VkPhysicalDeviceMultiviewFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
}

function ge_VkPhysicalDeviceMultiviewProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
}

function ge_VkPhysicalDeviceVariablePointersFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
}

function ge_VkPhysicalDeviceProtectedMemoryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.protectedMemory);
}

function ge_VkPhysicalDeviceProtectedMemoryProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.protectedNoFault);
}

function ge_VkProtectedSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.protectedSubmit);
}

function ge_VkSamplerYcbcrConversionInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.conversion);
}

function ge_VkBindImagePlaneMemoryInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.planeAspect);
}

function ge_VkImagePlaneMemoryRequirementsInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.planeAspect);
}

function ge_VkPhysicalDeviceSamplerYcbcrConversionFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.samplerYcbcrConversion);
}

function ge_VkSamplerYcbcrConversionImageFormatProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.combinedImageSamplerDescriptorCount);
}

function ge_VkPhysicalDeviceExternalImageFormatInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.handleType);
}

function ge_VkExternalImageFormatProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkExternalMemoryProperties(w, o.externalMemoryProperties, root);
}

function ge_VkPhysicalDeviceIDProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u8s(o.deviceUUID, 16);
    w.u8s(o.driverUUID, 16);
    w.u8s(o.deviceLUID, 8);
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
}

function ge_VkExternalMemoryImageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function ge_VkExternalMemoryBufferCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function ge_VkExportMemoryAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function ge_VkExportFenceCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function ge_VkExportSemaphoreCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.handleTypes);
}

function ge_VkPhysicalDeviceMaintenance3Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}

function ge_VkPhysicalDeviceShaderDrawParametersFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderDrawParameters);
}

function ge_VkPhysicalDeviceVulkan11Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
    w.u32(o.protectedMemory);
    w.u32(o.samplerYcbcrConversion);
    w.u32(o.shaderDrawParameters);
}

function ge_VkPhysicalDeviceVulkan11Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u8s(o.deviceUUID, 16);
    w.u8s(o.driverUUID, 16);
    w.u8s(o.deviceLUID, 8);
    w.u32(o.deviceNodeMask);
    w.u32(o.deviceLUIDValid);
    w.u32(o.subgroupSize);
    w.u32(o.subgroupSupportedStages);
    w.u32(o.subgroupSupportedOperations);
    w.u32(o.subgroupQuadOperationsInAllStages);
    w.i32(o.pointClippingBehavior);
    w.u32(o.maxMultiviewViewCount);
    w.u32(o.maxMultiviewInstanceIndex);
    w.u32(o.protectedNoFault);
    w.u32(o.maxPerSetDescriptors);
    w.u64(o.maxMemoryAllocationSize);
}

function ge_VkPhysicalDeviceVulkan12Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.samplerMirrorClampToEdge);
    w.u32(o.drawIndirectCount);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
    w.u32(o.descriptorIndexing);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
    w.u32(o.samplerFilterMinmax);
    w.u32(o.scalarBlockLayout);
    w.u32(o.imagelessFramebuffer);
    w.u32(o.uniformBufferStandardLayout);
    w.u32(o.shaderSubgroupExtendedTypes);
    w.u32(o.separateDepthStencilLayouts);
    w.u32(o.hostQueryReset);
    w.u32(o.timelineSemaphore);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
    w.u32(o.shaderOutputViewportIndex);
    w.u32(o.shaderOutputLayer);
    w.u32(o.subgroupBroadcastDynamicId);
}

function ge_VkPhysicalDeviceVulkan12Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.driverID);
    w.str(o.driverName, 256);
    w.str(o.driverInfo, 256);
    ge_VkConformanceVersion(w, o.conformanceVersion, root);
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
    w.u64(o.maxTimelineSemaphoreValueDifference);
    w.u32(o.framebufferIntegerColorSampleCounts);
}

function ge_VkImageFormatListCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.viewFormatCount);
    if((o.viewFormatCount > 0))
    {
        w.i32s(o.pViewFormats, o.viewFormatCount);
    }
}

function ge_VkPhysicalDevice8BitStorageFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
}

function ge_VkPhysicalDeviceDriverProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.driverID);
    w.str(o.driverName, 256);
    w.str(o.driverInfo, 256);
    ge_VkConformanceVersion(w, o.conformanceVersion, root);
}

function ge_VkPhysicalDeviceShaderAtomicInt64Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
}

function ge_VkPhysicalDeviceShaderFloat16Int8Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
}

function ge_VkPhysicalDeviceFloatControlsProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.denormBehaviorIndependence);
    w.i32(o.roundingModeIndependence);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat16);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat32);
    w.u32(o.shaderSignedZeroInfNanPreserveFloat64);
    w.u32(o.shaderDenormPreserveFloat16);
    w.u32(o.shaderDenormPreserveFloat32);
    w.u32(o.shaderDenormPreserveFloat64);
    w.u32(o.shaderDenormFlushToZeroFloat16);
    w.u32(o.shaderDenormFlushToZeroFloat32);
    w.u32(o.shaderDenormFlushToZeroFloat64);
    w.u32(o.shaderRoundingModeRTEFloat16);
    w.u32(o.shaderRoundingModeRTEFloat32);
    w.u32(o.shaderRoundingModeRTEFloat64);
    w.u32(o.shaderRoundingModeRTZFloat16);
    w.u32(o.shaderRoundingModeRTZFloat32);
    w.u32(o.shaderRoundingModeRTZFloat64);
}

function ge_VkDescriptorSetLayoutBindingFlagsCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.bindingCount);
    w.ptr(o.pBindingFlags != null);
    if(o.pBindingFlags != null)
    {
        if((o.bindingCount > 0))
        {
            w.u32s(o.pBindingFlags, o.bindingCount);
        }
    }
}

function ge_VkPhysicalDeviceDescriptorIndexingFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
}

function ge_VkPhysicalDeviceDescriptorIndexingProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxUpdateAfterBindDescriptorsInAllPools);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderSampledImageArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexingNative);
    w.u32(o.shaderStorageImageArrayNonUniformIndexingNative);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexingNative);
    w.u32(o.robustBufferAccessUpdateAfterBind);
    w.u32(o.quadDivergentImplicitLod);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSamplers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindUniformBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageBuffers);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindSampledImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindStorageImages);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInputAttachments);
    w.u32(o.maxPerStageUpdateAfterBindResources);
    w.u32(o.maxDescriptorSetUpdateAfterBindSamplers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffers);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetUpdateAfterBindSampledImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindStorageImages);
    w.u32(o.maxDescriptorSetUpdateAfterBindInputAttachments);
}

function ge_VkDescriptorSetVariableDescriptorCountAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.descriptorSetCount);
    if((o.descriptorSetCount > 0))
    {
        w.u32s(o.pDescriptorCounts, o.descriptorSetCount);
    }
}

function ge_VkDescriptorSetVariableDescriptorCountLayoutSupport(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxVariableDescriptorCount);
}

function ge_VkSubpassDescriptionDepthStencilResolve(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.depthResolveMode);
    w.i32(o.stencilResolveMode);
    w.ptr(o.pDepthStencilResolveAttachment != null);
    if(o.pDepthStencilResolveAttachment != null)
    {
        ge_VkAttachmentReference2(w, o.pDepthStencilResolveAttachment, root);
    }
}

function ge_VkPhysicalDeviceDepthStencilResolveProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.supportedDepthResolveModes);
    w.u32(o.supportedStencilResolveModes);
    w.u32(o.independentResolveNone);
    w.u32(o.independentResolve);
}

function ge_VkPhysicalDeviceScalarBlockLayoutFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.scalarBlockLayout);
}

function ge_VkImageStencilUsageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.stencilUsage);
}

function ge_VkSamplerReductionModeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.reductionMode);
}

function ge_VkPhysicalDeviceSamplerFilterMinmaxProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.filterMinmaxSingleComponentFormats);
    w.u32(o.filterMinmaxImageComponentMapping);
}

function ge_VkPhysicalDeviceVulkanMemoryModelFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
}

function ge_VkPhysicalDeviceImagelessFramebufferFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.imagelessFramebuffer);
}

function ge_VkFramebufferAttachmentsCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.attachmentImageInfoCount);
    for(let i = 0; i < o.attachmentImageInfoCount; i++)
    {
        ge_VkFramebufferAttachmentImageInfo(w, o.pAttachmentImageInfos?.[i], root);
    }
}

function ge_VkRenderPassAttachmentBeginInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.attachmentCount);
    if(o.attachmentCount)
    {
        for(let k = 0; k < o.attachmentCount; k++)
        {
            w.h(o.pAttachments?.[k]);
        }
    }
}

function ge_VkPhysicalDeviceUniformBufferStandardLayoutFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.uniformBufferStandardLayout);
}

function ge_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderSubgroupExtendedTypes);
}

function ge_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.separateDepthStencilLayouts);
}

function ge_VkAttachmentReferenceStencilLayout(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.stencilLayout);
}

function ge_VkAttachmentDescriptionStencilLayout(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.stencilInitialLayout);
    w.i32(o.stencilFinalLayout);
}

function ge_VkPhysicalDeviceHostQueryResetFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.hostQueryReset);
}

function ge_VkPhysicalDeviceTimelineSemaphoreFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.timelineSemaphore);
}

function ge_VkPhysicalDeviceTimelineSemaphoreProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.maxTimelineSemaphoreValueDifference);
}

function ge_VkSemaphoreTypeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.semaphoreType);
    w.u64(o.initialValue);
}

function ge_VkTimelineSemaphoreSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.waitSemaphoreValueCount);
    w.ptr(o.pWaitSemaphoreValues != null);
    if(o.pWaitSemaphoreValues != null)
    {
        if((o.waitSemaphoreValueCount > 0))
        {
            w.u64s(o.pWaitSemaphoreValues, o.waitSemaphoreValueCount);
        }
    }
    w.u32(o.signalSemaphoreValueCount);
    w.ptr(o.pSignalSemaphoreValues != null);
    if(o.pSignalSemaphoreValues != null)
    {
        if((o.signalSemaphoreValueCount > 0))
        {
            w.u64s(o.pSignalSemaphoreValues, o.signalSemaphoreValueCount);
        }
    }
}

function ge_VkPhysicalDeviceBufferDeviceAddressFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}

function ge_VkBufferOpaqueCaptureAddressCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.opaqueCaptureAddress);
}

function ge_VkMemoryOpaqueCaptureAddressAllocateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.opaqueCaptureAddress);
}

function ge_VkPhysicalDeviceVulkan13Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.robustImageAccess);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
    w.u32(o.pipelineCreationCacheControl);
    w.u32(o.privateData);
    w.u32(o.shaderDemoteToHelperInvocation);
    w.u32(o.shaderTerminateInvocation);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
    w.u32(o.synchronization2);
    w.u32(o.textureCompressionASTC_HDR);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
    w.u32(o.dynamicRendering);
    w.u32(o.shaderIntegerDotProduct);
    w.u32(o.maintenance4);
}

function ge_VkPhysicalDeviceVulkan13Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxInlineUniformTotalSize);
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.maxBufferSize);
}

function ge_VkPipelineCreationFeedbackCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkPipelineCreationFeedback(w, o.pPipelineCreationFeedback, root);
    w.u32(o.pipelineStageCreationFeedbackCount);
    for(let i = 0; i < o.pipelineStageCreationFeedbackCount; i++)
    {
        ge_VkPipelineCreationFeedback(w, o.pPipelineStageCreationFeedbacks?.[i], root);
    }
}

function ge_VkPhysicalDeviceShaderTerminateInvocationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderTerminateInvocation);
}

function ge_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderDemoteToHelperInvocation);
}

function ge_VkPhysicalDevicePrivateDataFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.privateData);
}

function ge_VkDevicePrivateDataCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.privateDataSlotRequestCount);
}

function ge_VkPhysicalDevicePipelineCreationCacheControlFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.pipelineCreationCacheControl);
}

function ge_VkMemoryBarrier2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
}

function ge_VkPhysicalDeviceSynchronization2Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.synchronization2);
}

function ge_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
}

function ge_VkPhysicalDeviceImageRobustnessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.robustImageAccess);
}

function ge_VkPhysicalDeviceSubgroupSizeControlFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
}

function ge_VkPhysicalDeviceSubgroupSizeControlProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.minSubgroupSize);
    w.u32(o.maxSubgroupSize);
    w.u32(o.maxComputeWorkgroupSubgroups);
    w.u32(o.requiredSubgroupSizeStages);
}

function ge_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.requiredSubgroupSize);
}

function ge_VkPhysicalDeviceInlineUniformBlockFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
}

function ge_VkPhysicalDeviceInlineUniformBlockProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxInlineUniformBlockSize);
    w.u32(o.maxPerStageDescriptorInlineUniformBlocks);
    w.u32(o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks);
    w.u32(o.maxDescriptorSetInlineUniformBlocks);
    w.u32(o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks);
}

function ge_VkWriteDescriptorSetInlineUniformBlock(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.dataSize);
    if((o.dataSize > 0))
    {
        w.bytes_of(o.pData, o.dataSize);
    }
}

function ge_VkDescriptorPoolInlineUniformBlockCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxInlineUniformBlockBindings);
}

function ge_VkPhysicalDeviceTextureCompressionASTCHDRFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.textureCompressionASTC_HDR);
}

function ge_VkPipelineRenderingCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    w.ptr(o.pColorAttachmentFormats != null);
    if(o.pColorAttachmentFormats != null)
    {
        if((o.colorAttachmentCount > 0))
        {
            w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
        }
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
}

function ge_VkPhysicalDeviceDynamicRenderingFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.dynamicRendering);
}

function ge_VkCommandBufferInheritanceRenderingInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    if((o.colorAttachmentCount > 0))
    {
        w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
    w.i32(o.rasterizationSamples);
}

function ge_VkPhysicalDeviceShaderIntegerDotProductFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderIntegerDotProduct);
}

function ge_VkPhysicalDeviceShaderIntegerDotProductProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.integerDotProduct8BitUnsignedAccelerated);
    w.u32(o.integerDotProduct8BitSignedAccelerated);
    w.u32(o.integerDotProduct8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProduct4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProduct16BitUnsignedAccelerated);
    w.u32(o.integerDotProduct16BitSignedAccelerated);
    w.u32(o.integerDotProduct16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct32BitUnsignedAccelerated);
    w.u32(o.integerDotProduct32BitSignedAccelerated);
    w.u32(o.integerDotProduct32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProduct64BitUnsignedAccelerated);
    w.u32(o.integerDotProduct64BitSignedAccelerated);
    w.u32(o.integerDotProduct64BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitSignedAccelerated);
    w.u32(o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated);
}

function ge_VkPhysicalDeviceTexelBufferAlignmentProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.storageTexelBufferOffsetAlignmentBytes);
    w.u32(o.storageTexelBufferOffsetSingleTexelAlignment);
    w.u64(o.uniformTexelBufferOffsetAlignmentBytes);
    w.u32(o.uniformTexelBufferOffsetSingleTexelAlignment);
}

function ge_VkFormatProperties3(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.linearTilingFeatures);
    w.u64(o.optimalTilingFeatures);
    w.u64(o.bufferFeatures);
}

function ge_VkPhysicalDeviceMaintenance4Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maintenance4);
}

function ge_VkPhysicalDeviceMaintenance4Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.maxBufferSize);
}

function ge_VkPhysicalDeviceVulkan14Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.globalPriorityQuery);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
    w.u32(o.shaderFloatControls2);
    w.u32(o.shaderExpectAssume);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
    w.u32(o.indexTypeUint8);
    w.u32(o.dynamicRenderingLocalRead);
    w.u32(o.maintenance5);
    w.u32(o.maintenance6);
    w.u32(o.pipelineProtectedAccess);
    w.u32(o.pipelineRobustness);
    w.u32(o.hostImageCopy);
    w.u32(o.pushDescriptor);
}

function ge_VkPhysicalDeviceVulkan14Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.lineSubPixelPrecisionBits);
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
    w.u32(o.maxPushDescriptors);
    w.u32(o.dynamicRenderingLocalReadDepthStencilAttachments);
    w.u32(o.dynamicRenderingLocalReadMultisampledAttachments);
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
    w.u32(o.copySrcLayoutCount);
    w.ptr(o.pCopySrcLayouts != null);
    if(o.pCopySrcLayouts != null)
    {
        if((o.copySrcLayoutCount > 0))
        {
            w.i32s(o.pCopySrcLayouts, o.copySrcLayoutCount);
        }
    }
    w.u32(o.copyDstLayoutCount);
    w.ptr(o.pCopyDstLayouts != null);
    if(o.pCopyDstLayouts != null)
    {
        if((o.copyDstLayoutCount > 0))
        {
            w.i32s(o.pCopyDstLayouts, o.copyDstLayoutCount);
        }
    }
    w.u8s(o.optimalTilingLayoutUUID, 16);
    w.u32(o.identicalMemoryTypeRequirements);
}

function ge_VkDeviceQueueGlobalPriorityCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.globalPriority);
}

function ge_VkPhysicalDeviceGlobalPriorityQueryFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.globalPriorityQuery);
}

function ge_VkQueueFamilyGlobalPriorityProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.priorityCount);
    w.i32s(o.priorities, 16);
}

function ge_VkPhysicalDeviceShaderSubgroupRotateFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
}

function ge_VkPhysicalDeviceShaderFloatControls2Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderFloatControls2);
}

function ge_VkPhysicalDeviceShaderExpectAssumeFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.shaderExpectAssume);
}

function ge_VkPhysicalDeviceLineRasterizationFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
}

function ge_VkPhysicalDeviceLineRasterizationProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.lineSubPixelPrecisionBits);
}

function ge_VkPipelineRasterizationLineStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.lineRasterizationMode);
    w.u32(o.stippledLineEnable);
    w.u32(o.lineStippleFactor);
    w.u16(o.lineStipplePattern);
}

function ge_VkPhysicalDeviceVertexAttributeDivisorProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxVertexAttribDivisor);
    w.u32(o.supportsNonZeroFirstInstance);
}

function ge_VkPipelineVertexInputDivisorStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.vertexBindingDivisorCount);
    for(let i = 0; i < o.vertexBindingDivisorCount; i++)
    {
        ge_VkVertexInputBindingDivisorDescription(w, o.pVertexBindingDivisors?.[i], root);
    }
}

function ge_VkPhysicalDeviceVertexAttributeDivisorFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
}

function ge_VkPhysicalDeviceIndexTypeUint8Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.indexTypeUint8);
}

function ge_VkPhysicalDeviceMaintenance5Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maintenance5);
}

function ge_VkPhysicalDeviceMaintenance5Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.earlyFragmentMultisampleCoverageAfterSampleCounting);
    w.u32(o.earlyFragmentSampleMaskTestBeforeSampleCounting);
    w.u32(o.depthStencilSwizzleOneSupport);
    w.u32(o.polygonModePointSize);
    w.u32(o.nonStrictSinglePixelWideLinesUseParallelogram);
    w.u32(o.nonStrictWideLinesUseParallelogram);
}

function ge_VkPipelineCreateFlags2CreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.flags);
}

function ge_VkBufferUsageFlags2CreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.usage);
}

function ge_VkPhysicalDevicePushDescriptorProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxPushDescriptors);
}

function ge_VkPhysicalDeviceDynamicRenderingLocalReadFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.dynamicRenderingLocalRead);
}

function ge_VkPhysicalDeviceMaintenance6Features(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maintenance6);
}

function ge_VkPhysicalDeviceMaintenance6Properties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.blockTexelViewCompatibleMultipleLayers);
    w.u32(o.maxCombinedImageSamplerDescriptorCount);
    w.u32(o.fragmentShadingRateClampCombinerInputs);
}

function ge_VkBindMemoryStatus(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.pResult);
}

function ge_VkPhysicalDevicePipelineProtectedAccessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.pipelineProtectedAccess);
}

function ge_VkPhysicalDevicePipelineRobustnessFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.pipelineRobustness);
}

function ge_VkPhysicalDevicePipelineRobustnessProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.defaultRobustnessStorageBuffers);
    w.i32(o.defaultRobustnessUniformBuffers);
    w.i32(o.defaultRobustnessVertexInputs);
    w.i32(o.defaultRobustnessImages);
}

function ge_VkPipelineRobustnessCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.storageBuffers);
    w.i32(o.uniformBuffers);
    w.i32(o.vertexInputs);
    w.i32(o.images);
}

function ge_VkPhysicalDeviceHostImageCopyFeatures(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.hostImageCopy);
}

function ge_VkPhysicalDeviceHostImageCopyProperties(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.copySrcLayoutCount);
    w.ptr(o.pCopySrcLayouts != null);
    if(o.pCopySrcLayouts != null)
    {
        if((o.copySrcLayoutCount > 0))
        {
            w.i32s(o.pCopySrcLayouts, o.copySrcLayoutCount);
        }
    }
    w.u32(o.copyDstLayoutCount);
    w.ptr(o.pCopyDstLayouts != null);
    if(o.pCopyDstLayouts != null)
    {
        if((o.copyDstLayoutCount > 0))
        {
            w.i32s(o.pCopyDstLayouts, o.copyDstLayoutCount);
        }
    }
    w.u8s(o.optimalTilingLayoutUUID, 16);
    w.u32(o.identicalMemoryTypeRequirements);
}

function ge_VkSubresourceHostMemcpySize(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.size);
}

function ge_VkHostImageCopyDevicePerformanceQuery(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.optimalDeviceAccess);
    w.u32(o.identicalMemoryLayout);
}

function ge_VkPresentRegionsKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.swapchainCount);
    w.ptr(o.pRegions != null);
    if(o.pRegions != null)
    {
        for(let i = 0; i < o.swapchainCount; i++)
        {
            ge_VkPresentRegionKHR(w, o.pRegions?.[i], root);
        }
    }
}

function ge_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.pipelineExecutableInfo);
}

function ge_VkNativeBufferANDROID(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.ptr(o.handle != null);
    if(o.handle != null)
    {
        w.u32(o.handle);
    }
    w.i32(o.stride);
    w.i32(o.format);
    w.i32(o.usage);
    ge_VkNativeBufferUsage2ANDROID(w, o.usage2, root);
}

function ge_VkPhysicalDeviceTransformFeedbackFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.transformFeedback);
    w.u32(o.geometryStreams);
}

function ge_VkPhysicalDeviceTransformFeedbackPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxTransformFeedbackStreams);
    w.u32(o.maxTransformFeedbackBuffers);
    w.u64(o.maxTransformFeedbackBufferSize);
    w.u32(o.maxTransformFeedbackStreamDataSize);
    w.u32(o.maxTransformFeedbackBufferDataSize);
    w.u32(o.maxTransformFeedbackBufferDataStride);
    w.u32(o.transformFeedbackQueries);
    w.u32(o.transformFeedbackStreamsLinesTriangles);
    w.u32(o.transformFeedbackRasterizationStreamSelect);
    w.u32(o.transformFeedbackDraw);
}

function ge_VkPipelineRasterizationStateStreamCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.rasterizationStream);
}

function ge_VkPhysicalDeviceDepthClipEnableFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.depthClipEnable);
}

function ge_VkPipelineRasterizationDepthClipStateCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.depthClipEnable);
}

function ge_VkDrmFormatModifierPropertiesListEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    w.ptr(o.pDrmFormatModifierProperties != null);
    if(o.pDrmFormatModifierProperties != null)
    {
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            ge_VkDrmFormatModifierPropertiesEXT(w, o.pDrmFormatModifierProperties?.[i], root);
        }
    }
}

function ge_VkPhysicalDeviceImageDrmFormatModifierInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    w.ptr(o.pQueueFamilyIndices != null);
    if(o.pQueueFamilyIndices != null)
    {
        if((o.queueFamilyIndexCount > 0))
        {
            w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
        }
    }
}

function ge_VkImageDrmFormatModifierListCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    if((o.drmFormatModifierCount > 0))
    {
        w.u64s(o.pDrmFormatModifiers, o.drmFormatModifierCount);
    }
}

function ge_VkImageDrmFormatModifierExplicitCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    for(let i = 0; i < o.drmFormatModifierPlaneCount; i++)
    {
        ge_VkSubresourceLayout(w, o.pPlaneLayouts?.[i], root);
    }
}

function ge_VkDrmFormatModifierPropertiesList2EXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.drmFormatModifierCount);
    w.ptr(o.pDrmFormatModifierProperties != null);
    if(o.pDrmFormatModifierProperties != null)
    {
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            ge_VkDrmFormatModifierProperties2EXT(w, o.pDrmFormatModifierProperties?.[i], root);
        }
    }
}

function ge_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxVertexAttribDivisor);
}

function ge_VkPhysicalDeviceFragmentDensityMapFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.fragmentDensityMap);
    w.u32(o.fragmentDensityMapDynamic);
    w.u32(o.fragmentDensityMapNonSubsampledImages);
}

function ge_VkImportColorBufferGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.colorBuffer);
}

function ge_VkPhysicalDeviceFragmentDensityMapPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkExtent2D(w, o.minFragmentDensityTexelSize, root);
    ge_VkExtent2D(w, o.maxFragmentDensityTexelSize, root);
    w.u32(o.fragmentDensityInvocations);
}

function ge_VkCreateBlobGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.blobMem);
    w.u32(o.blobFlags);
    w.u64(o.blobId);
}

function ge_VkRenderPassFragmentDensityMapCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkAttachmentReference(w, o.fragmentDensityMapAttachment, root);
}

function ge_VkImportBufferGOOGLE(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.buffer);
}

function ge_VkRenderingFragmentDensityMapAttachmentInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.imageView);
    w.i32(o.imageLayout);
}

function ge_VkPhysicalDeviceMemoryBudgetPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64s(o.heapBudget, 16);
    w.u64s(o.heapUsage, 16);
}

function ge_VkPhysicalDeviceProvokingVertexFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.provokingVertexLast);
    w.u32(o.transformFeedbackPreservesProvokingVertex);
}

function ge_VkPhysicalDeviceProvokingVertexPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.provokingVertexModePerPipeline);
    w.u32(o.transformFeedbackPreservesTriangleFanProvokingVertex);
}

function ge_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.i32(o.provokingVertexMode);
}

function ge_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.extendedDynamicState);
}

function ge_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.texelBufferAlignment);
}

function ge_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.deviceMemoryReport);
}

function ge_VkDeviceDeviceMemoryReportCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.be64(o.pfnUserCallback);
    w.void(o.pUserData);
}

function ge_VkSamplerCustomBorderColorCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkClearColorValue(w, o.customBorderColor, root);
    w.i32(o.format);
}

function ge_VkPhysicalDeviceCustomBorderColorPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.maxCustomBorderColorSamplers);
}

function ge_VkPhysicalDeviceCustomBorderColorFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.customBorderColors);
    w.u32(o.customBorderColorWithoutFormat);
}

function ge_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.graphicsPipelineLibrary);
}

function ge_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.graphicsPipelineLibraryFastLinking);
    w.u32(o.graphicsPipelineLibraryIndependentInterpolationDecoration);
}

function ge_VkGraphicsPipelineLibraryCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
}

function ge_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.ycbcr2plane444Formats);
}

function ge_VkPhysicalDeviceImageCompressionControlFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionControl);
}

function ge_VkImageCompressionControlEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.compressionControlPlaneCount);
    w.ptr(o.pFixedRateFlags != null);
    if(o.pFixedRateFlags != null)
    {
        if((o.compressionControlPlaneCount > 0))
        {
            w.u32s(o.pFixedRateFlags, o.compressionControlPlaneCount);
        }
    }
}

function ge_VkImageCompressionPropertiesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionFlags);
    w.u32(o.imageCompressionFixedRateFlags);
}

function ge_VkPhysicalDevice4444FormatsFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.formatA4R4G4B4);
    w.u32(o.formatA4B4G4R4);
}

function ge_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.primitiveTopologyListRestart);
    w.u32(o.primitiveTopologyPatchListRestart);
}

function ge_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.extendedDynamicState2);
    w.u32(o.extendedDynamicState2LogicOp);
    w.u32(o.extendedDynamicState2PatchControlPoints);
}

function ge_VkPhysicalDeviceColorWriteEnableFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.colorWriteEnable);
}

function ge_VkPipelineColorWriteCreateInfoEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.attachmentCount);
    if((o.attachmentCount > 0))
    {
        w.u32s(o.pColorWriteEnables, o.attachmentCount);
    }
}

function ge_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.imageCompressionControlSwapchain);
}

function gd_VkShaderModuleCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.codeSize = r.be64();
    o.pCode = r.u32s(Math.trunc(o.codeSize / 4));
    return o;
}

function gd_VkPipelineLayoutCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.setLayoutCount = r.u32();
    if(o.setLayoutCount)
    {
        o.pSetLayouts = r.u64s(o.setLayoutCount);
    }
    o.pushConstantRangeCount = r.u32();
    o.pPushConstantRanges = new Array(r.count(o.pushConstantRangeCount));
    for(let i = 0; i < o.pushConstantRangeCount; i++)
    {
        o.pPushConstantRanges[i] = gd_VkPushConstantRange(r, o.pPushConstantRanges[i], root);
    }
    return o;
}

function gd_VkPhysicalDeviceSubgroupProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.subgroupSize = r.u32();
    o.supportedStages = r.u32();
    o.supportedOperations = r.u32();
    o.quadOperationsInAllStages = r.u32();
    return o;
}

function gd_VkPhysicalDevice16BitStorageFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    return o;
}

function gd_VkMemoryDedicatedRequirements(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.prefersDedicatedAllocation = r.u32();
    o.requiresDedicatedAllocation = r.u32();
    return o;
}

function gd_VkMemoryDedicatedAllocateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.image = r.h();
    o.buffer = r.h();
    return o;
}

function gd_VkMemoryAllocateFlagsInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.deviceMask = r.u32();
    return o;
}

function gd_VkDeviceGroupRenderPassBeginInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceMask = r.u32();
    o.deviceRenderAreaCount = r.u32();
    o.pDeviceRenderAreas = new Array(r.count(o.deviceRenderAreaCount));
    for(let i = 0; i < o.deviceRenderAreaCount; i++)
    {
        o.pDeviceRenderAreas[i] = gd_VkRect2D(r, o.pDeviceRenderAreas[i], root);
    }
    return o;
}

function gd_VkDeviceGroupCommandBufferBeginInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceMask = r.u32();
    return o;
}

function gd_VkDeviceGroupSubmitInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.waitSemaphoreCount = r.u32();
    o.pWaitSemaphoreDeviceIndices = r.u32s(o.waitSemaphoreCount);
    o.commandBufferCount = r.u32();
    o.pCommandBufferDeviceMasks = r.u32s(o.commandBufferCount);
    o.signalSemaphoreCount = r.u32();
    o.pSignalSemaphoreDeviceIndices = r.u32s(o.signalSemaphoreCount);
    return o;
}

function gd_VkDeviceGroupBindSparseInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.resourceDeviceIndex = r.u32();
    o.memoryDeviceIndex = r.u32();
    return o;
}

function gd_VkBindBufferMemoryDeviceGroupInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceIndexCount = r.u32();
    o.pDeviceIndices = r.u32s(o.deviceIndexCount);
    return o;
}

function gd_VkBindImageMemoryDeviceGroupInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceIndexCount = r.u32();
    o.pDeviceIndices = r.u32s(o.deviceIndexCount);
    o.splitInstanceBindRegionCount = r.u32();
    o.pSplitInstanceBindRegions = new Array(r.count(o.splitInstanceBindRegionCount));
    for(let i = 0; i < o.splitInstanceBindRegionCount; i++)
    {
        o.pSplitInstanceBindRegions[i] = gd_VkRect2D(r, o.pSplitInstanceBindRegions[i], root);
    }
    return o;
}

function gd_VkDeviceGroupDeviceCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.physicalDeviceCount = r.u32();
    if(o.physicalDeviceCount)
    {
        o.pPhysicalDevices = r.u64s(o.physicalDeviceCount);
    }
    return o;
}

function gd_VkPhysicalDevicePointClippingProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pointClippingBehavior = r.i32();
    return o;
}

function gd_VkRenderPassInputAttachmentAspectCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.aspectReferenceCount = r.u32();
    o.pAspectReferences = new Array(r.count(o.aspectReferenceCount));
    for(let i = 0; i < o.aspectReferenceCount; i++)
    {
        o.pAspectReferences[i] = gd_VkInputAttachmentAspectReference(r, o.pAspectReferences[i], root);
    }
    return o;
}

function gd_VkImageViewUsageCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.usage = r.u32();
    return o;
}

function gd_VkPipelineTessellationDomainOriginStateCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.domainOrigin = r.i32();
    return o;
}

function gd_VkRenderPassMultiviewCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.subpassCount = r.u32();
    o.pViewMasks = r.u32s(o.subpassCount);
    o.dependencyCount = r.u32();
    o.pViewOffsets = r.i32s(o.dependencyCount);
    o.correlationMaskCount = r.u32();
    o.pCorrelationMasks = r.u32s(o.correlationMaskCount);
    return o;
}

function gd_VkPhysicalDeviceMultiviewFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMultiviewProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVariablePointersFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    return o;
}

function gd_VkPhysicalDeviceProtectedMemoryFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.protectedMemory = r.u32();
    return o;
}

function gd_VkPhysicalDeviceProtectedMemoryProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.protectedNoFault = r.u32();
    return o;
}

function gd_VkProtectedSubmitInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.protectedSubmit = r.u32();
    return o;
}

function gd_VkSamplerYcbcrConversionInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.conversion = r.h();
    return o;
}

function gd_VkBindImagePlaneMemoryInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.planeAspect = r.i32();
    return o;
}

function gd_VkImagePlaneMemoryRequirementsInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.planeAspect = r.i32();
    return o;
}

function gd_VkPhysicalDeviceSamplerYcbcrConversionFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.samplerYcbcrConversion = r.u32();
    return o;
}

function gd_VkSamplerYcbcrConversionImageFormatProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.combinedImageSamplerDescriptorCount = r.u32();
    return o;
}

function gd_VkPhysicalDeviceExternalImageFormatInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleType = r.i32();
    return o;
}

function gd_VkExternalImageFormatProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.externalMemoryProperties = gd_VkExternalMemoryProperties(r, o.externalMemoryProperties, root);
    return o;
}

function gd_VkPhysicalDeviceIDProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceUUID = r.u8s(16);
    o.driverUUID = r.u8s(16);
    o.deviceLUID = r.u8s(8);
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
    return o;
}

function gd_VkExternalMemoryImageCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleTypes = r.u32();
    return o;
}

function gd_VkExternalMemoryBufferCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleTypes = r.u32();
    return o;
}

function gd_VkExportMemoryAllocateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleTypes = r.u32();
    return o;
}

function gd_VkExportFenceCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleTypes = r.u32();
    return o;
}

function gd_VkExportSemaphoreCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.handleTypes = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMaintenance3Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
    return o;
}

function gd_VkPhysicalDeviceShaderDrawParametersFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderDrawParameters = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkan11Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    o.protectedMemory = r.u32();
    o.samplerYcbcrConversion = r.u32();
    o.shaderDrawParameters = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkan11Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceUUID = r.u8s(16);
    o.driverUUID = r.u8s(16);
    o.deviceLUID = r.u8s(8);
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
    o.subgroupSize = r.u32();
    o.subgroupSupportedStages = r.u32();
    o.subgroupSupportedOperations = r.u32();
    o.subgroupQuadOperationsInAllStages = r.u32();
    o.pointClippingBehavior = r.i32();
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
    o.protectedNoFault = r.u32();
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
    return o;
}

function gd_VkPhysicalDeviceVulkan12Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.samplerMirrorClampToEdge = r.u32();
    o.drawIndirectCount = r.u32();
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    o.descriptorIndexing = r.u32();
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    o.samplerFilterMinmax = r.u32();
    o.scalarBlockLayout = r.u32();
    o.imagelessFramebuffer = r.u32();
    o.uniformBufferStandardLayout = r.u32();
    o.shaderSubgroupExtendedTypes = r.u32();
    o.separateDepthStencilLayouts = r.u32();
    o.hostQueryReset = r.u32();
    o.timelineSemaphore = r.u32();
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    o.shaderOutputViewportIndex = r.u32();
    o.shaderOutputLayer = r.u32();
    o.subgroupBroadcastDynamicId = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkan12Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.driverID = r.i32();
    o.driverName = r.str(256);
    o.driverInfo = r.str(256);
    o.conformanceVersion = gd_VkConformanceVersion(r, o.conformanceVersion, root);
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
    o.maxTimelineSemaphoreValueDifference = r.u64();
    o.framebufferIntegerColorSampleCounts = r.u32();
    return o;
}

function gd_VkImageFormatListCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.viewFormatCount = r.u32();
    o.pViewFormats = r.i32s(o.viewFormatCount);
    return o;
}

function gd_VkPhysicalDevice8BitStorageFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceDriverProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.driverID = r.i32();
    o.driverName = r.str(256);
    o.driverInfo = r.str(256);
    o.conformanceVersion = gd_VkConformanceVersion(r, o.conformanceVersion, root);
    return o;
}

function gd_VkPhysicalDeviceShaderAtomicInt64Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderFloat16Int8Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceFloatControlsProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
    return o;
}

function gd_VkDescriptorSetLayoutBindingFlagsCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.bindingCount = r.u32();
    r.ptr();
    if(o.pBindingFlags != null)
    {
        o.pBindingFlags = r.u32s(o.bindingCount);
    }
    return o;
}

function gd_VkPhysicalDeviceDescriptorIndexingFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    return o;
}

function gd_VkPhysicalDeviceDescriptorIndexingProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
    return o;
}

function gd_VkDescriptorSetVariableDescriptorCountAllocateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.descriptorSetCount = r.u32();
    o.pDescriptorCounts = r.u32s(o.descriptorSetCount);
    return o;
}

function gd_VkDescriptorSetVariableDescriptorCountLayoutSupport(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxVariableDescriptorCount = r.u32();
    return o;
}

function gd_VkSubpassDescriptionDepthStencilResolve(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.depthResolveMode = r.i32();
    o.stencilResolveMode = r.i32();
    r.ptr();
    if(o.pDepthStencilResolveAttachment != null)
    {
        o.pDepthStencilResolveAttachment = gd_VkAttachmentReference2(r, o.pDepthStencilResolveAttachment, root);
    }
    return o;
}

function gd_VkPhysicalDeviceDepthStencilResolveProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
    return o;
}

function gd_VkPhysicalDeviceScalarBlockLayoutFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.scalarBlockLayout = r.u32();
    return o;
}

function gd_VkImageStencilUsageCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.stencilUsage = r.u32();
    return o;
}

function gd_VkSamplerReductionModeCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.reductionMode = r.i32();
    return o;
}

function gd_VkPhysicalDeviceSamplerFilterMinmaxProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkanMemoryModelFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    return o;
}

function gd_VkPhysicalDeviceImagelessFramebufferFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imagelessFramebuffer = r.u32();
    return o;
}

function gd_VkFramebufferAttachmentsCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.attachmentImageInfoCount = r.u32();
    o.pAttachmentImageInfos = new Array(r.count(o.attachmentImageInfoCount));
    for(let i = 0; i < o.attachmentImageInfoCount; i++)
    {
        o.pAttachmentImageInfos[i] = gd_VkFramebufferAttachmentImageInfo(r, o.pAttachmentImageInfos[i], root);
    }
    return o;
}

function gd_VkRenderPassAttachmentBeginInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.attachmentCount = r.u32();
    if(o.attachmentCount)
    {
        o.pAttachments = r.u64s(o.attachmentCount);
    }
    return o;
}

function gd_VkPhysicalDeviceUniformBufferStandardLayoutFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.uniformBufferStandardLayout = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderSubgroupExtendedTypes = r.u32();
    return o;
}

function gd_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.separateDepthStencilLayouts = r.u32();
    return o;
}

function gd_VkAttachmentReferenceStencilLayout(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.stencilLayout = r.i32();
    return o;
}

function gd_VkAttachmentDescriptionStencilLayout(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.stencilInitialLayout = r.i32();
    o.stencilFinalLayout = r.i32();
    return o;
}

function gd_VkPhysicalDeviceHostQueryResetFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.hostQueryReset = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTimelineSemaphoreFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.timelineSemaphore = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTimelineSemaphoreProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxTimelineSemaphoreValueDifference = r.u64();
    return o;
}

function gd_VkSemaphoreTypeCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.semaphoreType = r.i32();
    o.initialValue = r.u64();
    return o;
}

function gd_VkTimelineSemaphoreSubmitInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.waitSemaphoreValueCount = r.u32();
    r.ptr();
    if(o.pWaitSemaphoreValues != null)
    {
        o.pWaitSemaphoreValues = r.u64s(o.waitSemaphoreValueCount);
    }
    o.signalSemaphoreValueCount = r.u32();
    r.ptr();
    if(o.pSignalSemaphoreValues != null)
    {
        o.pSignalSemaphoreValues = r.u64s(o.signalSemaphoreValueCount);
    }
    return o;
}

function gd_VkPhysicalDeviceBufferDeviceAddressFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    return o;
}

function gd_VkBufferOpaqueCaptureAddressCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.opaqueCaptureAddress = r.u64();
    return o;
}

function gd_VkMemoryOpaqueCaptureAddressAllocateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.opaqueCaptureAddress = r.u64();
    return o;
}

function gd_VkPhysicalDeviceVulkan13Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.robustImageAccess = r.u32();
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    o.pipelineCreationCacheControl = r.u32();
    o.privateData = r.u32();
    o.shaderDemoteToHelperInvocation = r.u32();
    o.shaderTerminateInvocation = r.u32();
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    o.synchronization2 = r.u32();
    o.textureCompressionASTC_HDR = r.u32();
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    o.dynamicRendering = r.u32();
    o.shaderIntegerDotProduct = r.u32();
    o.maintenance4 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkan13Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxInlineUniformTotalSize = r.u32();
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.maxBufferSize = r.u64();
    return o;
}

function gd_VkPipelineCreationFeedbackCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pPipelineCreationFeedback = gd_VkPipelineCreationFeedback(r, o.pPipelineCreationFeedback, root);
    o.pipelineStageCreationFeedbackCount = r.u32();
    o.pPipelineStageCreationFeedbacks = new Array(r.count(o.pipelineStageCreationFeedbackCount));
    for(let i = 0; i < o.pipelineStageCreationFeedbackCount; i++)
    {
        o.pPipelineStageCreationFeedbacks[i] = gd_VkPipelineCreationFeedback(r, o.pPipelineStageCreationFeedbacks[i], root);
    }
    return o;
}

function gd_VkPhysicalDeviceShaderTerminateInvocationFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderTerminateInvocation = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderDemoteToHelperInvocation = r.u32();
    return o;
}

function gd_VkPhysicalDevicePrivateDataFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.privateData = r.u32();
    return o;
}

function gd_VkDevicePrivateDataCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.privateDataSlotRequestCount = r.u32();
    return o;
}

function gd_VkPhysicalDevicePipelineCreationCacheControlFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pipelineCreationCacheControl = r.u32();
    return o;
}

function gd_VkMemoryBarrier2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.srcStageMask = r.u64();
    o.srcAccessMask = r.u64();
    o.dstStageMask = r.u64();
    o.dstAccessMask = r.u64();
    return o;
}

function gd_VkPhysicalDeviceSynchronization2Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.synchronization2 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    return o;
}

function gd_VkPhysicalDeviceImageRobustnessFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.robustImageAccess = r.u32();
    return o;
}

function gd_VkPhysicalDeviceSubgroupSizeControlFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    return o;
}

function gd_VkPhysicalDeviceSubgroupSizeControlProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
    return o;
}

function gd_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.requiredSubgroupSize = r.u32();
    return o;
}

function gd_VkPhysicalDeviceInlineUniformBlockFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    return o;
}

function gd_VkPhysicalDeviceInlineUniformBlockProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
    return o;
}

function gd_VkWriteDescriptorSetInlineUniformBlock(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.dataSize = r.u32();
    o.pData = r.bytes_of(o.dataSize);
    return o;
}

function gd_VkDescriptorPoolInlineUniformBlockCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxInlineUniformBlockBindings = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTextureCompressionASTCHDRFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.textureCompressionASTC_HDR = r.u32();
    return o;
}

function gd_VkPipelineRenderingCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    r.ptr();
    if(o.pColorAttachmentFormats != null)
    {
        o.pColorAttachmentFormats = r.i32s(o.colorAttachmentCount);
    }
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    return o;
}

function gd_VkPhysicalDeviceDynamicRenderingFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.dynamicRendering = r.u32();
    return o;
}

function gd_VkCommandBufferInheritanceRenderingInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.viewMask = r.u32();
    o.colorAttachmentCount = r.u32();
    o.pColorAttachmentFormats = r.i32s(o.colorAttachmentCount);
    o.depthAttachmentFormat = r.i32();
    o.stencilAttachmentFormat = r.i32();
    o.rasterizationSamples = r.i32();
    return o;
}

function gd_VkPhysicalDeviceShaderIntegerDotProductFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderIntegerDotProduct = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderIntegerDotProductProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTexelBufferAlignmentProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
    return o;
}

function gd_VkFormatProperties3(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.linearTilingFeatures = r.u64();
    o.optimalTilingFeatures = r.u64();
    o.bufferFeatures = r.u64();
    return o;
}

function gd_VkPhysicalDeviceMaintenance4Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maintenance4 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMaintenance4Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxBufferSize = r.u64();
    return o;
}

function gd_VkPhysicalDeviceVulkan14Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.globalPriorityQuery = r.u32();
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    o.shaderFloatControls2 = r.u32();
    o.shaderExpectAssume = r.u32();
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    o.indexTypeUint8 = r.u32();
    o.dynamicRenderingLocalRead = r.u32();
    o.maintenance5 = r.u32();
    o.maintenance6 = r.u32();
    o.pipelineProtectedAccess = r.u32();
    o.pipelineRobustness = r.u32();
    o.hostImageCopy = r.u32();
    o.pushDescriptor = r.u32();
    return o;
}

function gd_VkPhysicalDeviceVulkan14Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.lineSubPixelPrecisionBits = r.u32();
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
    o.maxPushDescriptors = r.u32();
    o.dynamicRenderingLocalReadDepthStencilAttachments = r.u32();
    o.dynamicRenderingLocalReadMultisampledAttachments = r.u32();
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
    o.copySrcLayoutCount = r.u32();
    r.ptr();
    if(o.pCopySrcLayouts != null)
    {
        o.pCopySrcLayouts = r.i32s(o.copySrcLayoutCount);
    }
    o.copyDstLayoutCount = r.u32();
    r.ptr();
    if(o.pCopyDstLayouts != null)
    {
        o.pCopyDstLayouts = r.i32s(o.copyDstLayoutCount);
    }
    o.optimalTilingLayoutUUID = r.u8s(16);
    o.identicalMemoryTypeRequirements = r.u32();
    return o;
}

function gd_VkDeviceQueueGlobalPriorityCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.globalPriority = r.i32();
    return o;
}

function gd_VkPhysicalDeviceGlobalPriorityQueryFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.globalPriorityQuery = r.u32();
    return o;
}

function gd_VkQueueFamilyGlobalPriorityProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.priorityCount = r.u32();
    o.priorities = r.i32s(16);
    return o;
}

function gd_VkPhysicalDeviceShaderSubgroupRotateFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderFloatControls2Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderFloatControls2 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceShaderExpectAssumeFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.shaderExpectAssume = r.u32();
    return o;
}

function gd_VkPhysicalDeviceLineRasterizationFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    return o;
}

function gd_VkPhysicalDeviceLineRasterizationProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.lineSubPixelPrecisionBits = r.u32();
    return o;
}

function gd_VkPipelineRasterizationLineStateCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.lineRasterizationMode = r.i32();
    o.stippledLineEnable = r.u32();
    o.lineStippleFactor = r.u32();
    o.lineStipplePattern = r.u16();
    return o;
}

function gd_VkPhysicalDeviceVertexAttributeDivisorProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
    return o;
}

function gd_VkPipelineVertexInputDivisorStateCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.vertexBindingDivisorCount = r.u32();
    o.pVertexBindingDivisors = new Array(r.count(o.vertexBindingDivisorCount));
    for(let i = 0; i < o.vertexBindingDivisorCount; i++)
    {
        o.pVertexBindingDivisors[i] = gd_VkVertexInputBindingDivisorDescription(r, o.pVertexBindingDivisors[i], root);
    }
    return o;
}

function gd_VkPhysicalDeviceVertexAttributeDivisorFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    return o;
}

function gd_VkPhysicalDeviceIndexTypeUint8Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.indexTypeUint8 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMaintenance5Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maintenance5 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMaintenance5Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
    return o;
}

function gd_VkPipelineCreateFlags2CreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u64();
    return o;
}

function gd_VkBufferUsageFlags2CreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.usage = r.u64();
    return o;
}

function gd_VkPhysicalDevicePushDescriptorProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxPushDescriptors = r.u32();
    return o;
}

function gd_VkPhysicalDeviceDynamicRenderingLocalReadFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.dynamicRenderingLocalRead = r.u32();
    return o;
}

function gd_VkRenderingAttachmentLocationInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.colorAttachmentCount = r.u32();
    r.ptr();
    if(o.pColorAttachmentLocations != null)
    {
        o.pColorAttachmentLocations = r.u32s(o.colorAttachmentCount);
    }
    return o;
}

function gd_VkRenderingInputAttachmentIndexInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.colorAttachmentCount = r.u32();
    r.ptr();
    if(o.pColorAttachmentInputIndices != null)
    {
        o.pColorAttachmentInputIndices = r.u32s(o.colorAttachmentCount);
    }
    r.ptr();
    if(o.pDepthInputAttachmentIndex != null)
    {
        o.pDepthInputAttachmentIndex = r.u32();
    }
    r.ptr();
    if(o.pStencilInputAttachmentIndex != null)
    {
        o.pStencilInputAttachmentIndex = r.u32();
    }
    return o;
}

function gd_VkPhysicalDeviceMaintenance6Features(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maintenance6 = r.u32();
    return o;
}

function gd_VkPhysicalDeviceMaintenance6Properties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
    return o;
}

function gd_VkBindMemoryStatus(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pResult = r.i32();
    return o;
}

function gd_VkPhysicalDevicePipelineProtectedAccessFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pipelineProtectedAccess = r.u32();
    return o;
}

function gd_VkPhysicalDevicePipelineRobustnessFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pipelineRobustness = r.u32();
    return o;
}

function gd_VkPhysicalDevicePipelineRobustnessProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
    return o;
}

function gd_VkPipelineRobustnessCreateInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.storageBuffers = r.i32();
    o.uniformBuffers = r.i32();
    o.vertexInputs = r.i32();
    o.images = r.i32();
    return o;
}

function gd_VkPhysicalDeviceHostImageCopyFeatures(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.hostImageCopy = r.u32();
    return o;
}

function gd_VkPhysicalDeviceHostImageCopyProperties(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.copySrcLayoutCount = r.u32();
    r.ptr();
    if(o.pCopySrcLayouts != null)
    {
        o.pCopySrcLayouts = r.i32s(o.copySrcLayoutCount);
    }
    o.copyDstLayoutCount = r.u32();
    r.ptr();
    if(o.pCopyDstLayouts != null)
    {
        o.pCopyDstLayouts = r.i32s(o.copyDstLayoutCount);
    }
    o.optimalTilingLayoutUUID = r.u8s(16);
    o.identicalMemoryTypeRequirements = r.u32();
    return o;
}

function gd_VkSubresourceHostMemcpySize(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.size = r.u64();
    return o;
}

function gd_VkHostImageCopyDevicePerformanceQuery(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.optimalDeviceAccess = r.u32();
    o.identicalMemoryLayout = r.u32();
    return o;
}

function gd_VkPresentRegionsKHR(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.swapchainCount = r.u32();
    r.ptr();
    if(o.pRegions != null)
    {
        o.pRegions = new Array(r.count(o.swapchainCount));
        for(let i = 0; i < o.swapchainCount; i++)
        {
            o.pRegions[i] = gd_VkPresentRegionKHR(r, o.pRegions[i], root);
        }
    }
    return o;
}

function gd_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.pipelineExecutableInfo = r.u32();
    return o;
}

function gd_VkNativeBufferANDROID(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    r.ptr();
    if(o.handle != null)
    {
        o.handle = r.u32();
    }
    o.stride = r.i32();
    o.format = r.i32();
    o.usage = r.i32();
    o.usage2 = gd_VkNativeBufferUsage2ANDROID(r, o.usage2, root);
    return o;
}

function gd_VkPhysicalDeviceTransformFeedbackFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.transformFeedback = r.u32();
    o.geometryStreams = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTransformFeedbackPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxTransformFeedbackStreams = r.u32();
    o.maxTransformFeedbackBuffers = r.u32();
    o.maxTransformFeedbackBufferSize = r.u64();
    o.maxTransformFeedbackStreamDataSize = r.u32();
    o.maxTransformFeedbackBufferDataSize = r.u32();
    o.maxTransformFeedbackBufferDataStride = r.u32();
    o.transformFeedbackQueries = r.u32();
    o.transformFeedbackStreamsLinesTriangles = r.u32();
    o.transformFeedbackRasterizationStreamSelect = r.u32();
    o.transformFeedbackDraw = r.u32();
    return o;
}

function gd_VkPipelineRasterizationStateStreamCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.rasterizationStream = r.u32();
    return o;
}

function gd_VkPhysicalDeviceDepthClipEnableFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.depthClipEnable = r.u32();
    return o;
}

function gd_VkPipelineRasterizationDepthClipStateCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.depthClipEnable = r.u32();
    return o;
}

function gd_VkDrmFormatModifierPropertiesListEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifierCount = r.u32();
    r.ptr();
    if(o.pDrmFormatModifierProperties != null)
    {
        o.pDrmFormatModifierProperties = new Array(r.count(o.drmFormatModifierCount));
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            o.pDrmFormatModifierProperties[i] = gd_VkDrmFormatModifierPropertiesEXT(r, o.pDrmFormatModifierProperties[i], root);
        }
    }
    return o;
}

function gd_VkPhysicalDeviceImageDrmFormatModifierInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifier = r.u64();
    o.sharingMode = r.i32();
    o.queueFamilyIndexCount = r.u32();
    r.ptr();
    if(o.pQueueFamilyIndices != null)
    {
        o.pQueueFamilyIndices = r.u32s(o.queueFamilyIndexCount);
    }
    return o;
}

function gd_VkImageDrmFormatModifierListCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifierCount = r.u32();
    o.pDrmFormatModifiers = r.u64s(o.drmFormatModifierCount);
    return o;
}

function gd_VkImageDrmFormatModifierExplicitCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.pPlaneLayouts = new Array(r.count(o.drmFormatModifierPlaneCount));
    for(let i = 0; i < o.drmFormatModifierPlaneCount; i++)
    {
        o.pPlaneLayouts[i] = gd_VkSubresourceLayout(r, o.pPlaneLayouts[i], root);
    }
    return o;
}

function gd_VkDrmFormatModifierPropertiesList2EXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.drmFormatModifierCount = r.u32();
    r.ptr();
    if(o.pDrmFormatModifierProperties != null)
    {
        o.pDrmFormatModifierProperties = new Array(r.count(o.drmFormatModifierCount));
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            o.pDrmFormatModifierProperties[i] = gd_VkDrmFormatModifierProperties2EXT(r, o.pDrmFormatModifierProperties[i], root);
        }
    }
    return o;
}

function gd_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxVertexAttribDivisor = r.u32();
    return o;
}

function gd_VkPhysicalDeviceFragmentDensityMapFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000218000;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.fragmentDensityMap = r.u32();
    o.fragmentDensityMapDynamic = r.u32();
    o.fragmentDensityMapNonSubsampledImages = r.u32();
    return o;
}

function gd_VkImportColorBufferGOOGLE(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000385000;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.colorBuffer = r.u32();
    return o;
}

function gd_VkPhysicalDeviceFragmentDensityMapPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000218001;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.minFragmentDensityTexelSize = gd_VkExtent2D(r, o.minFragmentDensityTexelSize, root);
    o.maxFragmentDensityTexelSize = gd_VkExtent2D(r, o.maxFragmentDensityTexelSize, root);
    o.fragmentDensityInvocations = r.u32();
    return o;
}

function gd_VkCreateBlobGOOGLE(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000385002;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.blobMem = r.u32();
    o.blobFlags = r.u32();
    o.blobId = r.u64();
    return o;
}

function gd_VkRenderPassFragmentDensityMapCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000218002;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.fragmentDensityMapAttachment = gd_VkAttachmentReference(r, o.fragmentDensityMapAttachment, root);
    return o;
}

function gd_VkImportBufferGOOGLE(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    o.sType = 1000385001;
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.buffer = r.u32();
    return o;
}

function gd_VkRenderingFragmentDensityMapAttachmentInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imageView = r.h();
    o.imageLayout = r.i32();
    return o;
}

function gd_VkPhysicalDeviceMemoryBudgetPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.heapBudget = r.u64s(16);
    o.heapUsage = r.u64s(16);
    return o;
}

function gd_VkPhysicalDeviceProvokingVertexFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.provokingVertexLast = r.u32();
    o.transformFeedbackPreservesProvokingVertex = r.u32();
    return o;
}

function gd_VkPhysicalDeviceProvokingVertexPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.provokingVertexModePerPipeline = r.u32();
    o.transformFeedbackPreservesTriangleFanProvokingVertex = r.u32();
    return o;
}

function gd_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.provokingVertexMode = r.i32();
    return o;
}

function gd_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.extendedDynamicState = r.u32();
    return o;
}

function gd_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.texelBufferAlignment = r.u32();
    return o;
}

function gd_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.deviceMemoryReport = r.u32();
    return o;
}

function gd_VkDeviceDeviceMemoryReportCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.pfnUserCallback = r.be64();
    o.pUserData = r.void();
    return o;
}

function gd_VkSamplerCustomBorderColorCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.customBorderColor = gd_VkClearColorValue(r, o.customBorderColor, root);
    o.format = r.i32();
    return o;
}

function gd_VkPhysicalDeviceCustomBorderColorPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.maxCustomBorderColorSamplers = r.u32();
    return o;
}

function gd_VkPhysicalDeviceCustomBorderColorFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.customBorderColors = r.u32();
    o.customBorderColorWithoutFormat = r.u32();
    return o;
}

function gd_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.graphicsPipelineLibrary = r.u32();
    return o;
}

function gd_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.graphicsPipelineLibraryFastLinking = r.u32();
    o.graphicsPipelineLibraryIndependentInterpolationDecoration = r.u32();
    return o;
}

function gd_VkGraphicsPipelineLibraryCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    return o;
}

function gd_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.ycbcr2plane444Formats = r.u32();
    return o;
}

function gd_VkPhysicalDeviceImageCompressionControlFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imageCompressionControl = r.u32();
    return o;
}

function gd_VkImageCompressionControlEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.compressionControlPlaneCount = r.u32();
    r.ptr();
    if(o.pFixedRateFlags != null)
    {
        o.pFixedRateFlags = r.u32s(o.compressionControlPlaneCount);
    }
    return o;
}

function gd_VkImageCompressionPropertiesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imageCompressionFlags = r.u32();
    o.imageCompressionFixedRateFlags = r.u32();
    return o;
}

function gd_VkPhysicalDevice4444FormatsFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.formatA4R4G4B4 = r.u32();
    o.formatA4B4G4R4 = r.u32();
    return o;
}

function gd_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.primitiveTopologyListRestart = r.u32();
    o.primitiveTopologyPatchListRestart = r.u32();
    return o;
}

function gd_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.extendedDynamicState2 = r.u32();
    o.extendedDynamicState2LogicOp = r.u32();
    o.extendedDynamicState2PatchControlPoints = r.u32();
    return o;
}

function gd_VkPhysicalDeviceColorWriteEnableFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.colorWriteEnable = r.u32();
    return o;
}

function gd_VkPipelineColorWriteCreateInfoEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.attachmentCount = r.u32();
    o.pColorWriteEnables = r.u32s(o.attachmentCount);
    return o;
}

function gd_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.imageCompressionControlSwapchain = r.u32();
    return o;
}

function ge_VkApplicationInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.ptr(o.pApplicationName != null);
    if(o.pApplicationName != null)
    {
        const l0 = o.pApplicationName ? o.pApplicationName.length : 0; w.be32(l0);
        w.chars(o.pApplicationName, l0);
    }
    w.u32(o.applicationVersion);
    w.ptr(o.pEngineName != null);
    if(o.pEngineName != null)
    {
        const l1 = o.pEngineName ? o.pEngineName.length : 0; w.be32(l1);
        w.chars(o.pEngineName, l1);
    }
    w.u32(o.engineVersion);
    w.u32(o.apiVersion);
}

function ge_VkExtent3D(w, o, root)
{
    o = o || {};
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.depth);
}

function gd_VkExtent3D(r, o, root)
{
    o = o || {};
    o.width = r.u32();
    o.height = r.u32();
    o.depth = r.u32();
    return o;
}

function ge_VkPhysicalDeviceLimits(w, o, root)
{
    o = o || {};
    w.u32(o.maxImageDimension1D);
    w.u32(o.maxImageDimension2D);
    w.u32(o.maxImageDimension3D);
    w.u32(o.maxImageDimensionCube);
    w.u32(o.maxImageArrayLayers);
    w.u32(o.maxTexelBufferElements);
    w.u32(o.maxUniformBufferRange);
    w.u32(o.maxStorageBufferRange);
    w.u32(o.maxPushConstantsSize);
    w.u32(o.maxMemoryAllocationCount);
    w.u32(o.maxSamplerAllocationCount);
    w.u64(o.bufferImageGranularity);
    w.u64(o.sparseAddressSpaceSize);
    w.u32(o.maxBoundDescriptorSets);
    w.u32(o.maxPerStageDescriptorSamplers);
    w.u32(o.maxPerStageDescriptorUniformBuffers);
    w.u32(o.maxPerStageDescriptorStorageBuffers);
    w.u32(o.maxPerStageDescriptorSampledImages);
    w.u32(o.maxPerStageDescriptorStorageImages);
    w.u32(o.maxPerStageDescriptorInputAttachments);
    w.u32(o.maxPerStageResources);
    w.u32(o.maxDescriptorSetSamplers);
    w.u32(o.maxDescriptorSetUniformBuffers);
    w.u32(o.maxDescriptorSetUniformBuffersDynamic);
    w.u32(o.maxDescriptorSetStorageBuffers);
    w.u32(o.maxDescriptorSetStorageBuffersDynamic);
    w.u32(o.maxDescriptorSetSampledImages);
    w.u32(o.maxDescriptorSetStorageImages);
    w.u32(o.maxDescriptorSetInputAttachments);
    w.u32(o.maxVertexInputAttributes);
    w.u32(o.maxVertexInputBindings);
    w.u32(o.maxVertexInputAttributeOffset);
    w.u32(o.maxVertexInputBindingStride);
    w.u32(o.maxVertexOutputComponents);
    w.u32(o.maxTessellationGenerationLevel);
    w.u32(o.maxTessellationPatchSize);
    w.u32(o.maxTessellationControlPerVertexInputComponents);
    w.u32(o.maxTessellationControlPerVertexOutputComponents);
    w.u32(o.maxTessellationControlPerPatchOutputComponents);
    w.u32(o.maxTessellationControlTotalOutputComponents);
    w.u32(o.maxTessellationEvaluationInputComponents);
    w.u32(o.maxTessellationEvaluationOutputComponents);
    w.u32(o.maxGeometryShaderInvocations);
    w.u32(o.maxGeometryInputComponents);
    w.u32(o.maxGeometryOutputComponents);
    w.u32(o.maxGeometryOutputVertices);
    w.u32(o.maxGeometryTotalOutputComponents);
    w.u32(o.maxFragmentInputComponents);
    w.u32(o.maxFragmentOutputAttachments);
    w.u32(o.maxFragmentDualSrcAttachments);
    w.u32(o.maxFragmentCombinedOutputResources);
    w.u32(o.maxComputeSharedMemorySize);
    w.u32s(o.maxComputeWorkGroupCount, 3);
    w.u32(o.maxComputeWorkGroupInvocations);
    w.u32s(o.maxComputeWorkGroupSize, 3);
    w.u32(o.subPixelPrecisionBits);
    w.u32(o.subTexelPrecisionBits);
    w.u32(o.mipmapPrecisionBits);
    w.u32(o.maxDrawIndexedIndexValue);
    w.u32(o.maxDrawIndirectCount);
    w.f32(o.maxSamplerLodBias);
    w.f32(o.maxSamplerAnisotropy);
    w.u32(o.maxViewports);
    w.u32s(o.maxViewportDimensions, 2);
    w.f32s(o.viewportBoundsRange, 2);
    w.u32(o.viewportSubPixelBits);
    w.be64(o.minMemoryMapAlignment);
    w.u64(o.minTexelBufferOffsetAlignment);
    w.u64(o.minUniformBufferOffsetAlignment);
    w.u64(o.minStorageBufferOffsetAlignment);
    w.i32(o.minTexelOffset);
    w.u32(o.maxTexelOffset);
    w.i32(o.minTexelGatherOffset);
    w.u32(o.maxTexelGatherOffset);
    w.f32(o.minInterpolationOffset);
    w.f32(o.maxInterpolationOffset);
    w.u32(o.subPixelInterpolationOffsetBits);
    w.u32(o.maxFramebufferWidth);
    w.u32(o.maxFramebufferHeight);
    w.u32(o.maxFramebufferLayers);
    w.u32(o.framebufferColorSampleCounts);
    w.u32(o.framebufferDepthSampleCounts);
    w.u32(o.framebufferStencilSampleCounts);
    w.u32(o.framebufferNoAttachmentsSampleCounts);
    w.u32(o.maxColorAttachments);
    w.u32(o.sampledImageColorSampleCounts);
    w.u32(o.sampledImageIntegerSampleCounts);
    w.u32(o.sampledImageDepthSampleCounts);
    w.u32(o.sampledImageStencilSampleCounts);
    w.u32(o.storageImageSampleCounts);
    w.u32(o.maxSampleMaskWords);
    w.u32(o.timestampComputeAndGraphics);
    w.f32(o.timestampPeriod);
    w.u32(o.maxClipDistances);
    w.u32(o.maxCullDistances);
    w.u32(o.maxCombinedClipAndCullDistances);
    w.u32(o.discreteQueuePriorities);
    w.f32s(o.pointSizeRange, 2);
    w.f32s(o.lineWidthRange, 2);
    w.f32(o.pointSizeGranularity);
    w.f32(o.lineWidthGranularity);
    w.u32(o.strictLines);
    w.u32(o.standardSampleLocations);
    w.u64(o.optimalBufferCopyOffsetAlignment);
    w.u64(o.optimalBufferCopyRowPitchAlignment);
    w.u64(o.nonCoherentAtomSize);
}

function ge_VkPhysicalDeviceSparseProperties(w, o, root)
{
    o = o || {};
    w.u32(o.residencyStandard2DBlockShape);
    w.u32(o.residencyStandard2DMultisampleBlockShape);
    w.u32(o.residencyStandard3DBlockShape);
    w.u32(o.residencyAlignedMipSize);
    w.u32(o.residencyNonResidentStrict);
}

function gd_VkPhysicalDeviceLimits(r, o, root)
{
    o = o || {};
    o.maxImageDimension1D = r.u32();
    o.maxImageDimension2D = r.u32();
    o.maxImageDimension3D = r.u32();
    o.maxImageDimensionCube = r.u32();
    o.maxImageArrayLayers = r.u32();
    o.maxTexelBufferElements = r.u32();
    o.maxUniformBufferRange = r.u32();
    o.maxStorageBufferRange = r.u32();
    o.maxPushConstantsSize = r.u32();
    o.maxMemoryAllocationCount = r.u32();
    o.maxSamplerAllocationCount = r.u32();
    o.bufferImageGranularity = r.u64();
    o.sparseAddressSpaceSize = r.u64();
    o.maxBoundDescriptorSets = r.u32();
    o.maxPerStageDescriptorSamplers = r.u32();
    o.maxPerStageDescriptorUniformBuffers = r.u32();
    o.maxPerStageDescriptorStorageBuffers = r.u32();
    o.maxPerStageDescriptorSampledImages = r.u32();
    o.maxPerStageDescriptorStorageImages = r.u32();
    o.maxPerStageDescriptorInputAttachments = r.u32();
    o.maxPerStageResources = r.u32();
    o.maxDescriptorSetSamplers = r.u32();
    o.maxDescriptorSetUniformBuffers = r.u32();
    o.maxDescriptorSetUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetStorageBuffers = r.u32();
    o.maxDescriptorSetStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetSampledImages = r.u32();
    o.maxDescriptorSetStorageImages = r.u32();
    o.maxDescriptorSetInputAttachments = r.u32();
    o.maxVertexInputAttributes = r.u32();
    o.maxVertexInputBindings = r.u32();
    o.maxVertexInputAttributeOffset = r.u32();
    o.maxVertexInputBindingStride = r.u32();
    o.maxVertexOutputComponents = r.u32();
    o.maxTessellationGenerationLevel = r.u32();
    o.maxTessellationPatchSize = r.u32();
    o.maxTessellationControlPerVertexInputComponents = r.u32();
    o.maxTessellationControlPerVertexOutputComponents = r.u32();
    o.maxTessellationControlPerPatchOutputComponents = r.u32();
    o.maxTessellationControlTotalOutputComponents = r.u32();
    o.maxTessellationEvaluationInputComponents = r.u32();
    o.maxTessellationEvaluationOutputComponents = r.u32();
    o.maxGeometryShaderInvocations = r.u32();
    o.maxGeometryInputComponents = r.u32();
    o.maxGeometryOutputComponents = r.u32();
    o.maxGeometryOutputVertices = r.u32();
    o.maxGeometryTotalOutputComponents = r.u32();
    o.maxFragmentInputComponents = r.u32();
    o.maxFragmentOutputAttachments = r.u32();
    o.maxFragmentDualSrcAttachments = r.u32();
    o.maxFragmentCombinedOutputResources = r.u32();
    o.maxComputeSharedMemorySize = r.u32();
    o.maxComputeWorkGroupCount = r.u32s(3);
    o.maxComputeWorkGroupInvocations = r.u32();
    o.maxComputeWorkGroupSize = r.u32s(3);
    o.subPixelPrecisionBits = r.u32();
    o.subTexelPrecisionBits = r.u32();
    o.mipmapPrecisionBits = r.u32();
    o.maxDrawIndexedIndexValue = r.u32();
    o.maxDrawIndirectCount = r.u32();
    o.maxSamplerLodBias = r.f32();
    o.maxSamplerAnisotropy = r.f32();
    o.maxViewports = r.u32();
    o.maxViewportDimensions = r.u32s(2);
    o.viewportBoundsRange = r.f32s(2);
    o.viewportSubPixelBits = r.u32();
    o.minMemoryMapAlignment = r.be64();
    o.minTexelBufferOffsetAlignment = r.u64();
    o.minUniformBufferOffsetAlignment = r.u64();
    o.minStorageBufferOffsetAlignment = r.u64();
    o.minTexelOffset = r.i32();
    o.maxTexelOffset = r.u32();
    o.minTexelGatherOffset = r.i32();
    o.maxTexelGatherOffset = r.u32();
    o.minInterpolationOffset = r.f32();
    o.maxInterpolationOffset = r.f32();
    o.subPixelInterpolationOffsetBits = r.u32();
    o.maxFramebufferWidth = r.u32();
    o.maxFramebufferHeight = r.u32();
    o.maxFramebufferLayers = r.u32();
    o.framebufferColorSampleCounts = r.u32();
    o.framebufferDepthSampleCounts = r.u32();
    o.framebufferStencilSampleCounts = r.u32();
    o.framebufferNoAttachmentsSampleCounts = r.u32();
    o.maxColorAttachments = r.u32();
    o.sampledImageColorSampleCounts = r.u32();
    o.sampledImageIntegerSampleCounts = r.u32();
    o.sampledImageDepthSampleCounts = r.u32();
    o.sampledImageStencilSampleCounts = r.u32();
    o.storageImageSampleCounts = r.u32();
    o.maxSampleMaskWords = r.u32();
    o.timestampComputeAndGraphics = r.u32();
    o.timestampPeriod = r.f32();
    o.maxClipDistances = r.u32();
    o.maxCullDistances = r.u32();
    o.maxCombinedClipAndCullDistances = r.u32();
    o.discreteQueuePriorities = r.u32();
    o.pointSizeRange = r.f32s(2);
    o.lineWidthRange = r.f32s(2);
    o.pointSizeGranularity = r.f32();
    o.lineWidthGranularity = r.f32();
    o.strictLines = r.u32();
    o.standardSampleLocations = r.u32();
    o.optimalBufferCopyOffsetAlignment = r.u64();
    o.optimalBufferCopyRowPitchAlignment = r.u64();
    o.nonCoherentAtomSize = r.u64();
    return o;
}

function gd_VkPhysicalDeviceSparseProperties(r, o, root)
{
    o = o || {};
    o.residencyStandard2DBlockShape = r.u32();
    o.residencyStandard2DMultisampleBlockShape = r.u32();
    o.residencyStandard3DBlockShape = r.u32();
    o.residencyAlignedMipSize = r.u32();
    o.residencyNonResidentStrict = r.u32();
    return o;
}

function ge_VkMemoryType(w, o, root)
{
    o = o || {};
    w.u32(o.propertyFlags);
    w.u32(o.heapIndex);
}

function ge_VkMemoryHeap(w, o, root)
{
    o = o || {};
    w.u64(o.size);
    w.u32(o.flags);
}

function gd_VkMemoryType(r, o, root)
{
    o = o || {};
    o.propertyFlags = r.u32();
    o.heapIndex = r.u32();
    return o;
}

function gd_VkMemoryHeap(r, o, root)
{
    o = o || {};
    o.size = r.u64();
    o.flags = r.u32();
    return o;
}

function ge_VkDeviceQueueCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
    w.u32(o.queueCount);
    if((o.queueCount > 0))
    {
        w.f32s(o.pQueuePriorities, o.queueCount);
    }
}

function ge_VkSparseBufferMemoryBindInfo(w, o, root)
{
    o = o || {};
    w.h(o.buffer);
    w.u32(o.bindCount);
    for(let i = 0; i < o.bindCount; i++)
    {
        ge_VkSparseMemoryBind(w, o.pBinds?.[i], root);
    }
}

function ge_VkSparseImageOpaqueMemoryBindInfo(w, o, root)
{
    o = o || {};
    w.h(o.image);
    w.u32(o.bindCount);
    for(let i = 0; i < o.bindCount; i++)
    {
        ge_VkSparseMemoryBind(w, o.pBinds?.[i], root);
    }
}

function ge_VkSparseImageMemoryBindInfo(w, o, root)
{
    o = o || {};
    w.h(o.image);
    w.u32(o.bindCount);
    for(let i = 0; i < o.bindCount; i++)
    {
        ge_VkSparseImageMemoryBind(w, o.pBinds?.[i], root);
    }
}

function ge_VkComponentMapping(w, o, root)
{
    o = o || {};
    w.i32(o.r);
    w.i32(o.g);
    w.i32(o.b);
    w.i32(o.a);
}

function ge_VkPipelineShaderStageCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.stage);
    w.h(o.module);
    const l0 = o.pName ? o.pName.length : 0; w.be32(l0);
    w.chars(o.pName, l0);
    w.ptr(o.pSpecializationInfo != null);
    if(o.pSpecializationInfo != null)
    {
        ge_VkSpecializationInfo(w, o.pSpecializationInfo, root);
    }
}

function ge_VkPipelineVertexInputStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.vertexBindingDescriptionCount);
    for(let i = 0; i < o.vertexBindingDescriptionCount; i++)
    {
        ge_VkVertexInputBindingDescription(w, o.pVertexBindingDescriptions?.[i], root);
    }
    w.u32(o.vertexAttributeDescriptionCount);
    for(let i = 0; i < o.vertexAttributeDescriptionCount; i++)
    {
        ge_VkVertexInputAttributeDescription(w, o.pVertexAttributeDescriptions?.[i], root);
    }
}

function ge_VkPipelineInputAssemblyStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.topology);
    w.u32(o.primitiveRestartEnable);
}

function ge_VkPipelineTessellationStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.patchControlPoints);
}

function ge_VkPipelineViewportStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.viewportCount);
    w.ptr(o.pViewports != null);
    if(o.pViewports != null)
    {
        for(let i = 0; i < o.viewportCount; i++)
        {
            ge_VkViewport(w, o.pViewports?.[i], root);
        }
    }
    w.u32(o.scissorCount);
    w.ptr(o.pScissors != null);
    if(o.pScissors != null)
    {
        for(let i = 0; i < o.scissorCount; i++)
        {
            ge_VkRect2D(w, o.pScissors?.[i], root);
        }
    }
}

function ge_VkPipelineRasterizationStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.depthClampEnable);
    w.u32(o.rasterizerDiscardEnable);
    w.i32(o.polygonMode);
    w.u32(o.cullMode);
    w.i32(o.frontFace);
    w.u32(o.depthBiasEnable);
    w.f32(o.depthBiasConstantFactor);
    w.f32(o.depthBiasClamp);
    w.f32(o.depthBiasSlopeFactor);
    w.f32(o.lineWidth);
}

function ge_VkPipelineMultisampleStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.rasterizationSamples);
    w.u32(o.sampleShadingEnable);
    w.f32(o.minSampleShading);
    w.ptr(o.pSampleMask != null);
    if(o.pSampleMask != null)
    {
        if((Math.trunc((o.rasterizationSamples + 31) / 32) > 0))
        {
            w.u32s(o.pSampleMask, Math.trunc((o.rasterizationSamples + 31) / 32));
        }
    }
    w.u32(o.alphaToCoverageEnable);
    w.u32(o.alphaToOneEnable);
}

function ge_VkPipelineDepthStencilStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.depthTestEnable);
    w.u32(o.depthWriteEnable);
    w.i32(o.depthCompareOp);
    w.u32(o.depthBoundsTestEnable);
    w.u32(o.stencilTestEnable);
    ge_VkStencilOpState(w, o.front, root);
    ge_VkStencilOpState(w, o.back, root);
    w.f32(o.minDepthBounds);
    w.f32(o.maxDepthBounds);
}

function ge_VkPipelineColorBlendStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.logicOpEnable);
    w.i32(o.logicOp);
    w.u32(o.attachmentCount);
    for(let i = 0; i < o.attachmentCount; i++)
    {
        ge_VkPipelineColorBlendAttachmentState(w, o.pAttachments?.[i], root);
    }
    w.f32s(o.blendConstants, 4);
}

function ge_VkPipelineDynamicStateCreateInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.dynamicStateCount);
    if((o.dynamicStateCount > 0))
    {
        w.i32s(o.pDynamicStates, o.dynamicStateCount);
    }
}

function ge_VkPushConstantRange(w, o, root)
{
    o = o || {};
    w.u32(o.stageFlags);
    w.u32(o.offset);
    w.u32(o.size);
}

function ge_VkDescriptorSetLayoutBinding(w, o, root)
{
    o = o || {};
    w.u32(o.binding);
    w.i32(o.descriptorType);
    w.u32(o.descriptorCount);
    w.u32(o.stageFlags);
    w.ptr(o.pImmutableSamplers != null);
    if(o.pImmutableSamplers != null)
    {
        if(o.descriptorCount)
        {
            for(let k = 0; k < o.descriptorCount; k++)
            {
                w.h(o.pImmutableSamplers?.[k]);
            }
        }
    }
}

function ge_VkDescriptorPoolSize(w, o, root)
{
    o = o || {};
    w.i32(o.type);
    w.u32(o.descriptorCount);
}

function ge_VkAttachmentDescription(w, o, root)
{
    o = o || {};
    w.u32(o.flags);
    w.i32(o.format);
    w.i32(o.samples);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    w.i32(o.stencilLoadOp);
    w.i32(o.stencilStoreOp);
    w.i32(o.initialLayout);
    w.i32(o.finalLayout);
}

function ge_VkSubpassDescription(w, o, root)
{
    o = o || {};
    w.u32(o.flags);
    w.i32(o.pipelineBindPoint);
    w.u32(o.inputAttachmentCount);
    for(let i = 0; i < o.inputAttachmentCount; i++)
    {
        ge_VkAttachmentReference(w, o.pInputAttachments?.[i], root);
    }
    w.u32(o.colorAttachmentCount);
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        ge_VkAttachmentReference(w, o.pColorAttachments?.[i], root);
    }
    w.ptr(o.pResolveAttachments != null);
    if(o.pResolveAttachments != null)
    {
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            ge_VkAttachmentReference(w, o.pResolveAttachments?.[i], root);
        }
    }
    w.ptr(o.pDepthStencilAttachment != null);
    if(o.pDepthStencilAttachment != null)
    {
        ge_VkAttachmentReference(w, o.pDepthStencilAttachment, root);
    }
    w.u32(o.preserveAttachmentCount);
    if((o.preserveAttachmentCount > 0))
    {
        w.u32s(o.pPreserveAttachments, o.preserveAttachmentCount);
    }
}

function ge_VkSubpassDependency(w, o, root)
{
    o = o || {};
    w.u32(o.srcSubpass);
    w.u32(o.dstSubpass);
    w.u32(o.srcStageMask);
    w.u32(o.dstStageMask);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.dependencyFlags);
}

function ge_VkCommandBufferInheritanceInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.renderPass);
    w.u32(o.subpass);
    w.h(o.framebuffer);
    w.u32(o.occlusionQueryEnable);
    w.u32(o.queryFlags);
    w.u32(o.pipelineStatistics);
}

function ge_VkOffset2D(w, o, root)
{
    o = o || {};
    w.i32(o.x);
    w.i32(o.y);
}

function ge_VkImageSubresourceLayers(w, o, root)
{
    o = o || {};
    w.u32(o.aspectMask);
    w.u32(o.mipLevel);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}

function ge_VkOffset3D(w, o, root)
{
    o = o || {};
    w.i32(o.x);
    w.i32(o.y);
    w.i32(o.z);
}

function ge_VkClearValue(w, o, root)
{
    o = o || {};
    ge_VkClearColorValue(w, o.color, root);
}

function ge_VkDescriptorUpdateTemplateEntry(w, o, root)
{
    o = o || {};
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
    w.i32(o.descriptorType);
    w.be64(o.offset);
    w.be64(o.stride);
}

function ge_VkExternalMemoryProperties(w, o, root)
{
    o = o || {};
    w.u32(o.externalMemoryFeatures);
    w.u32(o.exportFromImportedHandleTypes);
    w.u32(o.compatibleHandleTypes);
}

function gd_VkExternalMemoryProperties(r, o, root)
{
    o = o || {};
    o.externalMemoryFeatures = r.u32();
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    return o;
}

function ge_VkAttachmentDescription2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.format);
    w.i32(o.samples);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    w.i32(o.stencilLoadOp);
    w.i32(o.stencilStoreOp);
    w.i32(o.initialLayout);
    w.i32(o.finalLayout);
}

function ge_VkSubpassDescription2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.i32(o.pipelineBindPoint);
    w.u32(o.viewMask);
    w.u32(o.inputAttachmentCount);
    for(let i = 0; i < o.inputAttachmentCount; i++)
    {
        ge_VkAttachmentReference2(w, o.pInputAttachments?.[i], root);
    }
    w.u32(o.colorAttachmentCount);
    for(let i = 0; i < o.colorAttachmentCount; i++)
    {
        ge_VkAttachmentReference2(w, o.pColorAttachments?.[i], root);
    }
    w.ptr(o.pResolveAttachments != null);
    if(o.pResolveAttachments != null)
    {
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            ge_VkAttachmentReference2(w, o.pResolveAttachments?.[i], root);
        }
    }
    w.ptr(o.pDepthStencilAttachment != null);
    if(o.pDepthStencilAttachment != null)
    {
        ge_VkAttachmentReference2(w, o.pDepthStencilAttachment, root);
    }
    w.u32(o.preserveAttachmentCount);
    if((o.preserveAttachmentCount > 0))
    {
        w.u32s(o.pPreserveAttachments, o.preserveAttachmentCount);
    }
}

function ge_VkSubpassDependency2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.srcSubpass);
    w.u32(o.dstSubpass);
    w.u32(o.srcStageMask);
    w.u32(o.dstStageMask);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.dependencyFlags);
    w.i32(o.viewOffset);
}

function ge_VkBufferMemoryBarrier2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.size);
}

function ge_VkImageMemoryBarrier2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.image);
    ge_VkImageSubresourceRange(w, o.subresourceRange, root);
}

function ge_VkSemaphoreSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.semaphore);
    w.u64(o.value);
    w.u64(o.stageMask);
    w.u32(o.deviceIndex);
}

function ge_VkCommandBufferSubmitInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.commandBuffer);
    w.u32(o.deviceMask);
}

function ge_VkBufferCopy2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.srcOffset);
    w.u64(o.dstOffset);
    w.u64(o.size);
}

function ge_VkImageCopy2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    ge_VkOffset3D(w, o.srcOffset, root);
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    ge_VkOffset3D(w, o.dstOffset, root);
    ge_VkExtent3D(w, o.extent, root);
}

function ge_VkBufferImageCopy2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u64(o.bufferOffset);
    w.u32(o.bufferRowLength);
    w.u32(o.bufferImageHeight);
    ge_VkImageSubresourceLayers(w, o.imageSubresource, root);
    ge_VkOffset3D(w, o.imageOffset, root);
    ge_VkExtent3D(w, o.imageExtent, root);
}

function ge_VkImageBlit2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    for(let i = 0; i < 2; i++)
    {
        ge_VkOffset3D(w, o.srcOffsets?.[i], root);
    }
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    for(let i = 0; i < 2; i++)
    {
        ge_VkOffset3D(w, o.dstOffsets?.[i], root);
    }
}

function ge_VkImageResolve2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    ge_VkImageSubresourceLayers(w, o.srcSubresource, root);
    ge_VkOffset3D(w, o.srcOffset, root);
    ge_VkImageSubresourceLayers(w, o.dstSubresource, root);
    ge_VkOffset3D(w, o.dstOffset, root);
    ge_VkExtent3D(w, o.extent, root);
}

function ge_VkRenderingAttachmentInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.h(o.imageView);
    w.i32(o.imageLayout);
    w.i32(o.resolveMode);
    w.h(o.resolveImageView);
    w.i32(o.resolveImageLayout);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    ge_VkClearValue(w, o.clearValue, root);
}

function ge_VkMemoryToImageCopy(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.void(o.pHostPointer);
    w.u32(o.memoryRowLength);
    w.u32(o.memoryImageHeight);
    ge_VkImageSubresourceLayers(w, o.imageSubresource, root);
    ge_VkOffset3D(w, o.imageOffset, root);
    ge_VkExtent3D(w, o.imageExtent, root);
}

function ge_VkImageToMemoryCopy(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.void(o.pHostPointer);
    w.u32(o.memoryRowLength);
    w.u32(o.memoryImageHeight);
    ge_VkImageSubresourceLayers(w, o.imageSubresource, root);
    ge_VkOffset3D(w, o.imageOffset, root);
    ge_VkExtent3D(w, o.imageExtent, root);
}

function ge_VkPipelineExecutableStatisticValueKHR(w, o, root)
{
    o = o || {};
    w.u32(o.b32);
}

function gd_VkPipelineExecutableStatisticValueKHR(r, o, root)
{
    o = o || {};
    o.b32 = r.u32();
    return o;
}

function ge_VkInputAttachmentAspectReference(w, o, root)
{
    o = o || {};
    w.u32(o.subpass);
    w.u32(o.inputAttachmentIndex);
    w.u32(o.aspectMask);
}

function ge_VkConformanceVersion(w, o, root)
{
    o = o || {};
    w.u8(o.major);
    w.u8(o.minor);
    w.u8(o.subminor);
    w.u8(o.patch);
}

function ge_VkAttachmentReference2(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.attachment);
    w.i32(o.layout);
    w.u32(o.aspectMask);
}

function ge_VkFramebufferAttachmentImageInfo(w, o, root)
{
    o = o || {};
    w.i32(o.sType);
    if((root === 2147483647))
    {
        root = o.sType;
    }
    ge_pnext(w, o.pNext, root);
    w.u32(o.flags);
    w.u32(o.usage);
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.layerCount);
    w.u32(o.viewFormatCount);
    if((o.viewFormatCount > 0))
    {
        w.i32s(o.pViewFormats, o.viewFormatCount);
    }
}

function ge_VkPipelineCreationFeedback(w, o, root)
{
    o = o || {};
    w.u32(o.flags);
    w.u64(o.duration);
}

function ge_VkVertexInputBindingDivisorDescription(w, o, root)
{
    o = o || {};
    w.u32(o.binding);
    w.u32(o.divisor);
}

function ge_VkPresentRegionKHR(w, o, root)
{
    o = o || {};
    w.u32(o.rectangleCount);
    w.ptr(o.pRectangles != null);
    if(o.pRectangles != null)
    {
        for(let i = 0; i < o.rectangleCount; i++)
        {
            ge_VkRectLayerKHR(w, o.pRectangles?.[i], root);
        }
    }
}

function ge_VkNativeBufferUsage2ANDROID(w, o, root)
{
    o = o || {};
    w.u64(o.consumer);
    w.u64(o.producer);
}

function ge_VkDrmFormatModifierPropertiesEXT(w, o, root)
{
    o = o || {};
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u32(o.drmFormatModifierTilingFeatures);
}

function ge_VkDrmFormatModifierProperties2EXT(w, o, root)
{
    o = o || {};
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    w.u64(o.drmFormatModifierTilingFeatures);
}

function ge_VkAttachmentReference(w, o, root)
{
    o = o || {};
    w.u32(o.attachment);
    w.i32(o.layout);
}

function gd_VkPushConstantRange(r, o, root)
{
    o = o || {};
    o.stageFlags = r.u32();
    o.offset = r.u32();
    o.size = r.u32();
    return o;
}

function gd_VkRect2D(r, o, root)
{
    o = o || {};
    o.offset = gd_VkOffset2D(r, o.offset, root);
    o.extent = gd_VkExtent2D(r, o.extent, root);
    return o;
}

function gd_VkInputAttachmentAspectReference(r, o, root)
{
    o = o || {};
    o.subpass = r.u32();
    o.inputAttachmentIndex = r.u32();
    o.aspectMask = r.u32();
    return o;
}

function gd_VkConformanceVersion(r, o, root)
{
    o = o || {};
    o.major = r.u8();
    o.minor = r.u8();
    o.subminor = r.u8();
    o.patch = r.u8();
    return o;
}

function gd_VkAttachmentReference2(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.attachment = r.u32();
    o.layout = r.i32();
    o.aspectMask = r.u32();
    return o;
}

function gd_VkFramebufferAttachmentImageInfo(r, o, root)
{
    o = o || {};
    o.sType = r.i32();
    if((root === 2147483647))
    {
        root = o.sType;
    }
    o.pNext = gd_pnext(r, o.pNext, root);
    o.flags = r.u32();
    o.usage = r.u32();
    o.width = r.u32();
    o.height = r.u32();
    o.layerCount = r.u32();
    o.viewFormatCount = r.u32();
    o.pViewFormats = r.i32s(o.viewFormatCount);
    return o;
}

function gd_VkPipelineCreationFeedback(r, o, root)
{
    o = o || {};
    o.flags = r.u32();
    o.duration = r.u64();
    return o;
}

function gd_VkVertexInputBindingDivisorDescription(r, o, root)
{
    o = o || {};
    o.binding = r.u32();
    o.divisor = r.u32();
    return o;
}

function gd_VkPresentRegionKHR(r, o, root)
{
    o = o || {};
    o.rectangleCount = r.u32();
    r.ptr();
    if(o.pRectangles != null)
    {
        o.pRectangles = new Array(r.count(o.rectangleCount));
        for(let i = 0; i < o.rectangleCount; i++)
        {
            o.pRectangles[i] = gd_VkRectLayerKHR(r, o.pRectangles[i], root);
        }
    }
    return o;
}

function gd_VkNativeBufferUsage2ANDROID(r, o, root)
{
    o = o || {};
    o.consumer = r.u64();
    o.producer = r.u64();
    return o;
}

function gd_VkDrmFormatModifierPropertiesEXT(r, o, root)
{
    o = o || {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u32();
    return o;
}

function gd_VkDrmFormatModifierProperties2EXT(r, o, root)
{
    o = o || {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u64();
    return o;
}

function gd_VkAttachmentReference(r, o, root)
{
    o = o || {};
    o.attachment = r.u32();
    o.layout = r.i32();
    return o;
}

function gd_VkClearColorValue(r, o, root)
{
    o = o || {};
    o.float32 = r.f32s(4);
    return o;
}

function ge_VkSparseMemoryBind(w, o, root)
{
    o = o || {};
    w.u64(o.resourceOffset);
    w.u64(o.size);
    w.h(o.memory);
    w.u64(o.memoryOffset);
    w.u32(o.flags);
}

function ge_VkSparseImageMemoryBind(w, o, root)
{
    o = o || {};
    ge_VkImageSubresource(w, o.subresource, root);
    ge_VkOffset3D(w, o.offset, root);
    ge_VkExtent3D(w, o.extent, root);
    w.h(o.memory);
    w.u64(o.memoryOffset);
    w.u32(o.flags);
}

function ge_VkSpecializationInfo(w, o, root)
{
    o = o || {};
    w.u32(o.mapEntryCount);
    for(let i = 0; i < o.mapEntryCount; i++)
    {
        ge_VkSpecializationMapEntry(w, o.pMapEntries?.[i], root);
    }
    w.be64(o.dataSize);
    if((o.dataSize > 0))
    {
        w.bytes_of(o.pData, o.dataSize);
    }
}

function ge_VkVertexInputBindingDescription(w, o, root)
{
    o = o || {};
    w.u32(o.binding);
    w.u32(o.stride);
    w.i32(o.inputRate);
}

function ge_VkVertexInputAttributeDescription(w, o, root)
{
    o = o || {};
    w.u32(o.location);
    w.u32(o.binding);
    w.i32(o.format);
    w.u32(o.offset);
}

function ge_VkStencilOpState(w, o, root)
{
    o = o || {};
    w.i32(o.failOp);
    w.i32(o.passOp);
    w.i32(o.depthFailOp);
    w.i32(o.compareOp);
    w.u32(o.compareMask);
    w.u32(o.writeMask);
    w.u32(o.reference);
}

function ge_VkPipelineColorBlendAttachmentState(w, o, root)
{
    o = o || {};
    w.u32(o.blendEnable);
    w.i32(o.srcColorBlendFactor);
    w.i32(o.dstColorBlendFactor);
    w.i32(o.colorBlendOp);
    w.i32(o.srcAlphaBlendFactor);
    w.i32(o.dstAlphaBlendFactor);
    w.i32(o.alphaBlendOp);
    w.u32(o.colorWriteMask);
}

function ge_VkRectLayerKHR(w, o, root)
{
    o = o || {};
    ge_VkOffset2D(w, o.offset, root);
    ge_VkExtent2D(w, o.extent, root);
    w.u32(o.layer);
}

function gd_VkOffset2D(r, o, root)
{
    o = o || {};
    o.x = r.i32();
    o.y = r.i32();
    return o;
}

function gd_VkRectLayerKHR(r, o, root)
{
    o = o || {};
    o.offset = gd_VkOffset2D(r, o.offset, root);
    o.extent = gd_VkExtent2D(r, o.extent, root);
    o.layer = r.u32();
    return o;
}

function ge_VkSpecializationMapEntry(w, o, root)
{
    o = o || {};
    w.u32(o.constantID);
    w.u32(o.offset);
    w.be64(o.size);
}

/** pNext's structs (requests), by sType (some by the chain's root too): [its function, its C size] */
const PNEXT_REQUEST = {
    16: [ge_VkShaderModuleCreateInfo, 40],
    30: [ge_VkPipelineLayoutCreateInfo, 48],
    1000094000: [ge_VkPhysicalDeviceSubgroupProperties, 32],
    1000083000: [ge_VkPhysicalDevice16BitStorageFeatures, 32],
    1000127000: [ge_VkMemoryDedicatedRequirements, 24],
    1000127001: [ge_VkMemoryDedicatedAllocateInfo, 32],
    1000060000: [ge_VkMemoryAllocateFlagsInfo, 24],
    1000060003: [ge_VkDeviceGroupRenderPassBeginInfo, 32],
    1000060004: [ge_VkDeviceGroupCommandBufferBeginInfo, 24],
    1000060005: [ge_VkDeviceGroupSubmitInfo, 64],
    1000060006: [ge_VkDeviceGroupBindSparseInfo, 24],
    1000060013: [ge_VkBindBufferMemoryDeviceGroupInfo, 32],
    1000060014: [ge_VkBindImageMemoryDeviceGroupInfo, 48],
    1000070001: [ge_VkDeviceGroupDeviceCreateInfo, 32],
    1000059000: [ge_VkPhysicalDeviceFeatures2, 240],
    1000117000: [ge_VkPhysicalDevicePointClippingProperties, 24],
    1000117001: [ge_VkRenderPassInputAttachmentAspectCreateInfo, 32],
    1000117002: [ge_VkImageViewUsageCreateInfo, 24],
    1000117003: [ge_VkPipelineTessellationDomainOriginStateCreateInfo, 24],
    1000053000: [ge_VkRenderPassMultiviewCreateInfo, 64],
    1000053001: [ge_VkPhysicalDeviceMultiviewFeatures, 32],
    1000053002: [ge_VkPhysicalDeviceMultiviewProperties, 24],
    1000120000: [ge_VkPhysicalDeviceVariablePointersFeatures, 24],
    1000145001: [ge_VkPhysicalDeviceProtectedMemoryFeatures, 24],
    1000145002: [ge_VkPhysicalDeviceProtectedMemoryProperties, 24],
    1000145000: [ge_VkProtectedSubmitInfo, 24],
    1000156001: [ge_VkSamplerYcbcrConversionInfo, 24],
    1000156002: [ge_VkBindImagePlaneMemoryInfo, 24],
    1000156003: [ge_VkImagePlaneMemoryRequirementsInfo, 24],
    1000156004: [ge_VkPhysicalDeviceSamplerYcbcrConversionFeatures, 24],
    1000156005: [ge_VkSamplerYcbcrConversionImageFormatProperties, 24],
    1000071000: [ge_VkPhysicalDeviceExternalImageFormatInfo, 24],
    1000071001: [ge_VkExternalImageFormatProperties, 32],
    1000071004: [ge_VkPhysicalDeviceIDProperties, 64],
    1000072001: [ge_VkExternalMemoryImageCreateInfo, 24],
    1000072000: [ge_VkExternalMemoryBufferCreateInfo, 24],
    1000072002: [ge_VkExportMemoryAllocateInfo, 24],
    1000113000: [ge_VkExportFenceCreateInfo, 24],
    1000077000: [ge_VkExportSemaphoreCreateInfo, 24],
    1000168000: [ge_VkPhysicalDeviceMaintenance3Properties, 32],
    1000063000: [ge_VkPhysicalDeviceShaderDrawParametersFeatures, 24],
    49: [ge_VkPhysicalDeviceVulkan11Features, 64],
    50: [ge_VkPhysicalDeviceVulkan11Properties, 112],
    51: [ge_VkPhysicalDeviceVulkan12Features, 208],
    52: [ge_VkPhysicalDeviceVulkan12Properties, 736],
    1000147000: [ge_VkImageFormatListCreateInfo, 32],
    1000177000: [ge_VkPhysicalDevice8BitStorageFeatures, 32],
    1000196000: [ge_VkPhysicalDeviceDriverProperties, 536],
    1000180000: [ge_VkPhysicalDeviceShaderAtomicInt64Features, 24],
    1000082000: [ge_VkPhysicalDeviceShaderFloat16Int8Features, 24],
    1000197000: [ge_VkPhysicalDeviceFloatControlsProperties, 88],
    1000161000: [ge_VkDescriptorSetLayoutBindingFlagsCreateInfo, 32],
    1000161001: [ge_VkPhysicalDeviceDescriptorIndexingFeatures, 96],
    1000161002: [ge_VkPhysicalDeviceDescriptorIndexingProperties, 112],
    1000161003: [ge_VkDescriptorSetVariableDescriptorCountAllocateInfo, 32],
    1000161004: [ge_VkDescriptorSetVariableDescriptorCountLayoutSupport, 24],
    1000199001: [ge_VkSubpassDescriptionDepthStencilResolve, 32],
    1000199000: [ge_VkPhysicalDeviceDepthStencilResolveProperties, 32],
    1000221000: [ge_VkPhysicalDeviceScalarBlockLayoutFeatures, 24],
    1000246000: [ge_VkImageStencilUsageCreateInfo, 24],
    1000130001: [ge_VkSamplerReductionModeCreateInfo, 24],
    1000130000: [ge_VkPhysicalDeviceSamplerFilterMinmaxProperties, 24],
    1000211000: [ge_VkPhysicalDeviceVulkanMemoryModelFeatures, 32],
    1000108000: [ge_VkPhysicalDeviceImagelessFramebufferFeatures, 24],
    1000108001: [ge_VkFramebufferAttachmentsCreateInfo, 32],
    1000108003: [ge_VkRenderPassAttachmentBeginInfo, 32],
    1000253000: [ge_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, 24],
    1000175000: [ge_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, 24],
    1000241000: [ge_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, 24],
    1000241001: [ge_VkAttachmentReferenceStencilLayout, 24],
    1000241002: [ge_VkAttachmentDescriptionStencilLayout, 24],
    1000261000: [ge_VkPhysicalDeviceHostQueryResetFeatures, 24],
    1000207000: [ge_VkPhysicalDeviceTimelineSemaphoreFeatures, 24],
    1000207001: [ge_VkPhysicalDeviceTimelineSemaphoreProperties, 24],
    1000207002: [ge_VkSemaphoreTypeCreateInfo, 32],
    1000207003: [ge_VkTimelineSemaphoreSubmitInfo, 48],
    1000257000: [ge_VkPhysicalDeviceBufferDeviceAddressFeatures, 32],
    1000257002: [ge_VkBufferOpaqueCaptureAddressCreateInfo, 24],
    1000257003: [ge_VkMemoryOpaqueCaptureAddressAllocateInfo, 24],
    53: [ge_VkPhysicalDeviceVulkan13Features, 80],
    54: [ge_VkPhysicalDeviceVulkan13Properties, 216],
    1000192000: [ge_VkPipelineCreationFeedbackCreateInfo, 40],
    1000215000: [ge_VkPhysicalDeviceShaderTerminateInvocationFeatures, 24],
    1000276000: [ge_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, 24],
    1000295000: [ge_VkPhysicalDevicePrivateDataFeatures, 24],
    1000295001: [ge_VkDevicePrivateDataCreateInfo, 24],
    1000297000: [ge_VkPhysicalDevicePipelineCreationCacheControlFeatures, 24],
    1000314000: [ge_VkMemoryBarrier2, 48],
    1000314007: [ge_VkPhysicalDeviceSynchronization2Features, 24],
    1000325000: [ge_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, 24],
    1000335000: [ge_VkPhysicalDeviceImageRobustnessFeatures, 24],
    1000225002: [ge_VkPhysicalDeviceSubgroupSizeControlFeatures, 24],
    1000225000: [ge_VkPhysicalDeviceSubgroupSizeControlProperties, 32],
    1000225001: [ge_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, 24],
    1000138000: [ge_VkPhysicalDeviceInlineUniformBlockFeatures, 24],
    1000138001: [ge_VkPhysicalDeviceInlineUniformBlockProperties, 40],
    1000138002: [ge_VkWriteDescriptorSetInlineUniformBlock, 32],
    1000138003: [ge_VkDescriptorPoolInlineUniformBlockCreateInfo, 24],
    1000066000: [ge_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, 24],
    1000044002: [ge_VkPipelineRenderingCreateInfo, 40],
    1000044003: [ge_VkPhysicalDeviceDynamicRenderingFeatures, 24],
    1000044004: [ge_VkCommandBufferInheritanceRenderingInfo, 56],
    1000280000: [ge_VkPhysicalDeviceShaderIntegerDotProductFeatures, 24],
    1000280001: [ge_VkPhysicalDeviceShaderIntegerDotProductProperties, 136],
    1000281001: [ge_VkPhysicalDeviceTexelBufferAlignmentProperties, 48],
    1000360000: [ge_VkFormatProperties3, 40],
    1000413000: [ge_VkPhysicalDeviceMaintenance4Features, 24],
    1000413001: [ge_VkPhysicalDeviceMaintenance4Properties, 24],
    55: [ge_VkPhysicalDeviceVulkan14Features, 104],
    56: [ge_VkPhysicalDeviceVulkan14Properties, 144],
    1000174000: [ge_VkDeviceQueueGlobalPriorityCreateInfo, 24],
    1000388000: [ge_VkPhysicalDeviceGlobalPriorityQueryFeatures, 24],
    1000388001: [ge_VkQueueFamilyGlobalPriorityProperties, 88],
    1000416000: [ge_VkPhysicalDeviceShaderSubgroupRotateFeatures, 24],
    1000528000: [ge_VkPhysicalDeviceShaderFloatControls2Features, 24],
    1000544000: [ge_VkPhysicalDeviceShaderExpectAssumeFeatures, 24],
    1000259000: [ge_VkPhysicalDeviceLineRasterizationFeatures, 40],
    1000259002: [ge_VkPhysicalDeviceLineRasterizationProperties, 24],
    1000259001: [ge_VkPipelineRasterizationLineStateCreateInfo, 32],
    1000525000: [ge_VkPhysicalDeviceVertexAttributeDivisorProperties, 24],
    1000190001: [ge_VkPipelineVertexInputDivisorStateCreateInfo, 32],
    1000190002: [ge_VkPhysicalDeviceVertexAttributeDivisorFeatures, 24],
    1000265000: [ge_VkPhysicalDeviceIndexTypeUint8Features, 24],
    1000470000: [ge_VkPhysicalDeviceMaintenance5Features, 24],
    1000470001: [ge_VkPhysicalDeviceMaintenance5Properties, 40],
    1000470005: [ge_VkPipelineCreateFlags2CreateInfo, 24],
    1000470006: [ge_VkBufferUsageFlags2CreateInfo, 24],
    1000080000: [ge_VkPhysicalDevicePushDescriptorProperties, 24],
    1000232000: [ge_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, 24],
    1000232001: [ge_VkRenderingAttachmentLocationInfo, 32],
    1000232002: [ge_VkRenderingInputAttachmentIndexInfo, 48],
    1000545000: [ge_VkPhysicalDeviceMaintenance6Features, 24],
    1000545001: [ge_VkPhysicalDeviceMaintenance6Properties, 32],
    1000545002: [ge_VkBindMemoryStatus, 24],
    1000466000: [ge_VkPhysicalDevicePipelineProtectedAccessFeatures, 24],
    1000068001: [ge_VkPhysicalDevicePipelineRobustnessFeatures, 24],
    1000068002: [ge_VkPhysicalDevicePipelineRobustnessProperties, 32],
    1000068000: [ge_VkPipelineRobustnessCreateInfo, 32],
    1000270000: [ge_VkPhysicalDeviceHostImageCopyFeatures, 24],
    1000270001: [ge_VkPhysicalDeviceHostImageCopyProperties, 72],
    1000270008: [ge_VkSubresourceHostMemcpySize, 24],
    1000270009: [ge_VkHostImageCopyDevicePerformanceQuery, 24],
    1000084000: [ge_VkPresentRegionsKHR, 32],
    1000269000: [ge_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, 24],
    1000010000: [ge_VkNativeBufferANDROID, 64],
    1000028000: [ge_VkPhysicalDeviceTransformFeedbackFeaturesEXT, 24],
    1000028001: [ge_VkPhysicalDeviceTransformFeedbackPropertiesEXT, 64],
    1000028002: [ge_VkPipelineRasterizationStateStreamCreateInfoEXT, 24],
    1000102000: [ge_VkPhysicalDeviceDepthClipEnableFeaturesEXT, 24],
    1000102001: [ge_VkPipelineRasterizationDepthClipStateCreateInfoEXT, 24],
    1000158000: [ge_VkDrmFormatModifierPropertiesListEXT, 32],
    1000158002: [ge_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, 40],
    1000158003: [ge_VkImageDrmFormatModifierListCreateInfoEXT, 32],
    1000158004: [ge_VkImageDrmFormatModifierExplicitCreateInfoEXT, 40],
    1000158006: [ge_VkDrmFormatModifierPropertiesList2EXT, 32],
    1000190000: [ge_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, 24],
    1000218000: { 1000059000: [ge_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 3: [ge_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 5: [ge_VkImportColorBufferGOOGLE, 24], default: [ge_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32] },
    1000218001: { 1000059001: [ge_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40], 5: [ge_VkCreateBlobGOOGLE, 32], default: [ge_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40] },
    1000218002: { 38: [ge_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 1000109004: [ge_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 5: [ge_VkImportBufferGOOGLE, 24], default: [ge_VkRenderPassFragmentDensityMapCreateInfoEXT, 24] },
    1000044007: [ge_VkRenderingFragmentDensityMapAttachmentInfoEXT, 32],
    1000237000: [ge_VkPhysicalDeviceMemoryBudgetPropertiesEXT, 272],
    1000254000: [ge_VkPhysicalDeviceProvokingVertexFeaturesEXT, 24],
    1000254002: [ge_VkPhysicalDeviceProvokingVertexPropertiesEXT, 24],
    1000254001: [ge_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, 24],
    1000267000: [ge_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, 24],
    1000281000: [ge_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, 24],
    1000284000: [ge_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, 24],
    1000284001: [ge_VkDeviceDeviceMemoryReportCreateInfoEXT, 40],
    1000287000: [ge_VkSamplerCustomBorderColorCreateInfoEXT, 40],
    1000287001: [ge_VkPhysicalDeviceCustomBorderColorPropertiesEXT, 24],
    1000287002: [ge_VkPhysicalDeviceCustomBorderColorFeaturesEXT, 24],
    1000320000: [ge_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, 24],
    1000320001: [ge_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, 24],
    1000320002: [ge_VkGraphicsPipelineLibraryCreateInfoEXT, 24],
    1000330000: [ge_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, 24],
    1000338000: [ge_VkPhysicalDeviceImageCompressionControlFeaturesEXT, 24],
    1000338001: [ge_VkImageCompressionControlEXT, 32],
    1000338004: [ge_VkImageCompressionPropertiesEXT, 24],
    1000340000: [ge_VkPhysicalDevice4444FormatsFeaturesEXT, 24],
    1000356000: [ge_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, 24],
    1000377000: [ge_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, 32],
    1000381000: [ge_VkPhysicalDeviceColorWriteEnableFeaturesEXT, 24],
    1000381001: [ge_VkPipelineColorWriteCreateInfoEXT, 32],
    1000385000: [ge_VkImportColorBufferGOOGLE, 24],
    1000385001: [ge_VkImportBufferGOOGLE, 24],
    1000385002: [ge_VkCreateBlobGOOGLE, 32],
    1000437000: [ge_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, 24],
};
/** pNext's structs (replies) */
const PNEXT_REPLY = {
    16: [gd_VkShaderModuleCreateInfo, 40],
    30: [gd_VkPipelineLayoutCreateInfo, 48],
    1000094000: [gd_VkPhysicalDeviceSubgroupProperties, 32],
    1000083000: [gd_VkPhysicalDevice16BitStorageFeatures, 32],
    1000127000: [gd_VkMemoryDedicatedRequirements, 24],
    1000127001: [gd_VkMemoryDedicatedAllocateInfo, 32],
    1000060000: [gd_VkMemoryAllocateFlagsInfo, 24],
    1000060003: [gd_VkDeviceGroupRenderPassBeginInfo, 32],
    1000060004: [gd_VkDeviceGroupCommandBufferBeginInfo, 24],
    1000060005: [gd_VkDeviceGroupSubmitInfo, 64],
    1000060006: [gd_VkDeviceGroupBindSparseInfo, 24],
    1000060013: [gd_VkBindBufferMemoryDeviceGroupInfo, 32],
    1000060014: [gd_VkBindImageMemoryDeviceGroupInfo, 48],
    1000070001: [gd_VkDeviceGroupDeviceCreateInfo, 32],
    1000059000: [gd_VkPhysicalDeviceFeatures2, 240],
    1000117000: [gd_VkPhysicalDevicePointClippingProperties, 24],
    1000117001: [gd_VkRenderPassInputAttachmentAspectCreateInfo, 32],
    1000117002: [gd_VkImageViewUsageCreateInfo, 24],
    1000117003: [gd_VkPipelineTessellationDomainOriginStateCreateInfo, 24],
    1000053000: [gd_VkRenderPassMultiviewCreateInfo, 64],
    1000053001: [gd_VkPhysicalDeviceMultiviewFeatures, 32],
    1000053002: [gd_VkPhysicalDeviceMultiviewProperties, 24],
    1000120000: [gd_VkPhysicalDeviceVariablePointersFeatures, 24],
    1000145001: [gd_VkPhysicalDeviceProtectedMemoryFeatures, 24],
    1000145002: [gd_VkPhysicalDeviceProtectedMemoryProperties, 24],
    1000145000: [gd_VkProtectedSubmitInfo, 24],
    1000156001: [gd_VkSamplerYcbcrConversionInfo, 24],
    1000156002: [gd_VkBindImagePlaneMemoryInfo, 24],
    1000156003: [gd_VkImagePlaneMemoryRequirementsInfo, 24],
    1000156004: [gd_VkPhysicalDeviceSamplerYcbcrConversionFeatures, 24],
    1000156005: [gd_VkSamplerYcbcrConversionImageFormatProperties, 24],
    1000071000: [gd_VkPhysicalDeviceExternalImageFormatInfo, 24],
    1000071001: [gd_VkExternalImageFormatProperties, 32],
    1000071004: [gd_VkPhysicalDeviceIDProperties, 64],
    1000072001: [gd_VkExternalMemoryImageCreateInfo, 24],
    1000072000: [gd_VkExternalMemoryBufferCreateInfo, 24],
    1000072002: [gd_VkExportMemoryAllocateInfo, 24],
    1000113000: [gd_VkExportFenceCreateInfo, 24],
    1000077000: [gd_VkExportSemaphoreCreateInfo, 24],
    1000168000: [gd_VkPhysicalDeviceMaintenance3Properties, 32],
    1000063000: [gd_VkPhysicalDeviceShaderDrawParametersFeatures, 24],
    49: [gd_VkPhysicalDeviceVulkan11Features, 64],
    50: [gd_VkPhysicalDeviceVulkan11Properties, 112],
    51: [gd_VkPhysicalDeviceVulkan12Features, 208],
    52: [gd_VkPhysicalDeviceVulkan12Properties, 736],
    1000147000: [gd_VkImageFormatListCreateInfo, 32],
    1000177000: [gd_VkPhysicalDevice8BitStorageFeatures, 32],
    1000196000: [gd_VkPhysicalDeviceDriverProperties, 536],
    1000180000: [gd_VkPhysicalDeviceShaderAtomicInt64Features, 24],
    1000082000: [gd_VkPhysicalDeviceShaderFloat16Int8Features, 24],
    1000197000: [gd_VkPhysicalDeviceFloatControlsProperties, 88],
    1000161000: [gd_VkDescriptorSetLayoutBindingFlagsCreateInfo, 32],
    1000161001: [gd_VkPhysicalDeviceDescriptorIndexingFeatures, 96],
    1000161002: [gd_VkPhysicalDeviceDescriptorIndexingProperties, 112],
    1000161003: [gd_VkDescriptorSetVariableDescriptorCountAllocateInfo, 32],
    1000161004: [gd_VkDescriptorSetVariableDescriptorCountLayoutSupport, 24],
    1000199001: [gd_VkSubpassDescriptionDepthStencilResolve, 32],
    1000199000: [gd_VkPhysicalDeviceDepthStencilResolveProperties, 32],
    1000221000: [gd_VkPhysicalDeviceScalarBlockLayoutFeatures, 24],
    1000246000: [gd_VkImageStencilUsageCreateInfo, 24],
    1000130001: [gd_VkSamplerReductionModeCreateInfo, 24],
    1000130000: [gd_VkPhysicalDeviceSamplerFilterMinmaxProperties, 24],
    1000211000: [gd_VkPhysicalDeviceVulkanMemoryModelFeatures, 32],
    1000108000: [gd_VkPhysicalDeviceImagelessFramebufferFeatures, 24],
    1000108001: [gd_VkFramebufferAttachmentsCreateInfo, 32],
    1000108003: [gd_VkRenderPassAttachmentBeginInfo, 32],
    1000253000: [gd_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, 24],
    1000175000: [gd_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, 24],
    1000241000: [gd_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, 24],
    1000241001: [gd_VkAttachmentReferenceStencilLayout, 24],
    1000241002: [gd_VkAttachmentDescriptionStencilLayout, 24],
    1000261000: [gd_VkPhysicalDeviceHostQueryResetFeatures, 24],
    1000207000: [gd_VkPhysicalDeviceTimelineSemaphoreFeatures, 24],
    1000207001: [gd_VkPhysicalDeviceTimelineSemaphoreProperties, 24],
    1000207002: [gd_VkSemaphoreTypeCreateInfo, 32],
    1000207003: [gd_VkTimelineSemaphoreSubmitInfo, 48],
    1000257000: [gd_VkPhysicalDeviceBufferDeviceAddressFeatures, 32],
    1000257002: [gd_VkBufferOpaqueCaptureAddressCreateInfo, 24],
    1000257003: [gd_VkMemoryOpaqueCaptureAddressAllocateInfo, 24],
    53: [gd_VkPhysicalDeviceVulkan13Features, 80],
    54: [gd_VkPhysicalDeviceVulkan13Properties, 216],
    1000192000: [gd_VkPipelineCreationFeedbackCreateInfo, 40],
    1000215000: [gd_VkPhysicalDeviceShaderTerminateInvocationFeatures, 24],
    1000276000: [gd_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, 24],
    1000295000: [gd_VkPhysicalDevicePrivateDataFeatures, 24],
    1000295001: [gd_VkDevicePrivateDataCreateInfo, 24],
    1000297000: [gd_VkPhysicalDevicePipelineCreationCacheControlFeatures, 24],
    1000314000: [gd_VkMemoryBarrier2, 48],
    1000314007: [gd_VkPhysicalDeviceSynchronization2Features, 24],
    1000325000: [gd_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, 24],
    1000335000: [gd_VkPhysicalDeviceImageRobustnessFeatures, 24],
    1000225002: [gd_VkPhysicalDeviceSubgroupSizeControlFeatures, 24],
    1000225000: [gd_VkPhysicalDeviceSubgroupSizeControlProperties, 32],
    1000225001: [gd_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, 24],
    1000138000: [gd_VkPhysicalDeviceInlineUniformBlockFeatures, 24],
    1000138001: [gd_VkPhysicalDeviceInlineUniformBlockProperties, 40],
    1000138002: [gd_VkWriteDescriptorSetInlineUniformBlock, 32],
    1000138003: [gd_VkDescriptorPoolInlineUniformBlockCreateInfo, 24],
    1000066000: [gd_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, 24],
    1000044002: [gd_VkPipelineRenderingCreateInfo, 40],
    1000044003: [gd_VkPhysicalDeviceDynamicRenderingFeatures, 24],
    1000044004: [gd_VkCommandBufferInheritanceRenderingInfo, 56],
    1000280000: [gd_VkPhysicalDeviceShaderIntegerDotProductFeatures, 24],
    1000280001: [gd_VkPhysicalDeviceShaderIntegerDotProductProperties, 136],
    1000281001: [gd_VkPhysicalDeviceTexelBufferAlignmentProperties, 48],
    1000360000: [gd_VkFormatProperties3, 40],
    1000413000: [gd_VkPhysicalDeviceMaintenance4Features, 24],
    1000413001: [gd_VkPhysicalDeviceMaintenance4Properties, 24],
    55: [gd_VkPhysicalDeviceVulkan14Features, 104],
    56: [gd_VkPhysicalDeviceVulkan14Properties, 144],
    1000174000: [gd_VkDeviceQueueGlobalPriorityCreateInfo, 24],
    1000388000: [gd_VkPhysicalDeviceGlobalPriorityQueryFeatures, 24],
    1000388001: [gd_VkQueueFamilyGlobalPriorityProperties, 88],
    1000416000: [gd_VkPhysicalDeviceShaderSubgroupRotateFeatures, 24],
    1000528000: [gd_VkPhysicalDeviceShaderFloatControls2Features, 24],
    1000544000: [gd_VkPhysicalDeviceShaderExpectAssumeFeatures, 24],
    1000259000: [gd_VkPhysicalDeviceLineRasterizationFeatures, 40],
    1000259002: [gd_VkPhysicalDeviceLineRasterizationProperties, 24],
    1000259001: [gd_VkPipelineRasterizationLineStateCreateInfo, 32],
    1000525000: [gd_VkPhysicalDeviceVertexAttributeDivisorProperties, 24],
    1000190001: [gd_VkPipelineVertexInputDivisorStateCreateInfo, 32],
    1000190002: [gd_VkPhysicalDeviceVertexAttributeDivisorFeatures, 24],
    1000265000: [gd_VkPhysicalDeviceIndexTypeUint8Features, 24],
    1000470000: [gd_VkPhysicalDeviceMaintenance5Features, 24],
    1000470001: [gd_VkPhysicalDeviceMaintenance5Properties, 40],
    1000470005: [gd_VkPipelineCreateFlags2CreateInfo, 24],
    1000470006: [gd_VkBufferUsageFlags2CreateInfo, 24],
    1000080000: [gd_VkPhysicalDevicePushDescriptorProperties, 24],
    1000232000: [gd_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, 24],
    1000232001: [gd_VkRenderingAttachmentLocationInfo, 32],
    1000232002: [gd_VkRenderingInputAttachmentIndexInfo, 48],
    1000545000: [gd_VkPhysicalDeviceMaintenance6Features, 24],
    1000545001: [gd_VkPhysicalDeviceMaintenance6Properties, 32],
    1000545002: [gd_VkBindMemoryStatus, 24],
    1000466000: [gd_VkPhysicalDevicePipelineProtectedAccessFeatures, 24],
    1000068001: [gd_VkPhysicalDevicePipelineRobustnessFeatures, 24],
    1000068002: [gd_VkPhysicalDevicePipelineRobustnessProperties, 32],
    1000068000: [gd_VkPipelineRobustnessCreateInfo, 32],
    1000270000: [gd_VkPhysicalDeviceHostImageCopyFeatures, 24],
    1000270001: [gd_VkPhysicalDeviceHostImageCopyProperties, 72],
    1000270008: [gd_VkSubresourceHostMemcpySize, 24],
    1000270009: [gd_VkHostImageCopyDevicePerformanceQuery, 24],
    1000084000: [gd_VkPresentRegionsKHR, 32],
    1000269000: [gd_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, 24],
    1000010000: [gd_VkNativeBufferANDROID, 64],
    1000028000: [gd_VkPhysicalDeviceTransformFeedbackFeaturesEXT, 24],
    1000028001: [gd_VkPhysicalDeviceTransformFeedbackPropertiesEXT, 64],
    1000028002: [gd_VkPipelineRasterizationStateStreamCreateInfoEXT, 24],
    1000102000: [gd_VkPhysicalDeviceDepthClipEnableFeaturesEXT, 24],
    1000102001: [gd_VkPipelineRasterizationDepthClipStateCreateInfoEXT, 24],
    1000158000: [gd_VkDrmFormatModifierPropertiesListEXT, 32],
    1000158002: [gd_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, 40],
    1000158003: [gd_VkImageDrmFormatModifierListCreateInfoEXT, 32],
    1000158004: [gd_VkImageDrmFormatModifierExplicitCreateInfoEXT, 40],
    1000158006: [gd_VkDrmFormatModifierPropertiesList2EXT, 32],
    1000190000: [gd_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, 24],
    1000218000: { 1000059000: [gd_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 3: [gd_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32], 5: [gd_VkImportColorBufferGOOGLE, 24], default: [gd_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, 32] },
    1000218001: { 1000059001: [gd_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40], 5: [gd_VkCreateBlobGOOGLE, 32], default: [gd_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, 40] },
    1000218002: { 38: [gd_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 1000109004: [gd_VkRenderPassFragmentDensityMapCreateInfoEXT, 24], 5: [gd_VkImportBufferGOOGLE, 24], default: [gd_VkRenderPassFragmentDensityMapCreateInfoEXT, 24] },
    1000044007: [gd_VkRenderingFragmentDensityMapAttachmentInfoEXT, 32],
    1000237000: [gd_VkPhysicalDeviceMemoryBudgetPropertiesEXT, 272],
    1000254000: [gd_VkPhysicalDeviceProvokingVertexFeaturesEXT, 24],
    1000254002: [gd_VkPhysicalDeviceProvokingVertexPropertiesEXT, 24],
    1000254001: [gd_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, 24],
    1000267000: [gd_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, 24],
    1000281000: [gd_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, 24],
    1000284000: [gd_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, 24],
    1000284001: [gd_VkDeviceDeviceMemoryReportCreateInfoEXT, 40],
    1000287000: [gd_VkSamplerCustomBorderColorCreateInfoEXT, 40],
    1000287001: [gd_VkPhysicalDeviceCustomBorderColorPropertiesEXT, 24],
    1000287002: [gd_VkPhysicalDeviceCustomBorderColorFeaturesEXT, 24],
    1000320000: [gd_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, 24],
    1000320001: [gd_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, 24],
    1000320002: [gd_VkGraphicsPipelineLibraryCreateInfoEXT, 24],
    1000330000: [gd_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, 24],
    1000338000: [gd_VkPhysicalDeviceImageCompressionControlFeaturesEXT, 24],
    1000338001: [gd_VkImageCompressionControlEXT, 32],
    1000338004: [gd_VkImageCompressionPropertiesEXT, 24],
    1000340000: [gd_VkPhysicalDevice4444FormatsFeaturesEXT, 24],
    1000356000: [gd_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, 24],
    1000377000: [gd_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, 32],
    1000381000: [gd_VkPhysicalDeviceColorWriteEnableFeaturesEXT, 24],
    1000381001: [gd_VkPipelineColorWriteCreateInfoEXT, 32],
    1000385000: [gd_VkImportColorBufferGOOGLE, 24],
    1000385001: [gd_VkImportBufferGOOGLE, 24],
    1000385002: [gd_VkCreateBlobGOOGLE, 32],
    1000437000: [gd_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, 24],
};
function ge_pnext(w, o, root)
{
    // (structs the guest does not know are skipped)
    while(o && !pnext_struct(PNEXT_REQUEST, o.sType, root)) o = o.pNext;
    if(!o) { w.be32(0); return; }
    const e = pnext_struct(PNEXT_REQUEST, o.sType, root);
    w.be32(e[1]);
    w.u32(o.sType);
    e[0](w, o, root);
}
function gd_pnext(r, o, root)
{
    while(o && !pnext_struct(PNEXT_REPLY, o.sType, root)) o = o.pNext;
    r.be32();
    if(!o) return o;
    r.u32();
    return pnext_struct(PNEXT_REPLY, o.sType, root)[0](r, o, root);
}
function ge_vkCreateInstance(w, a)
{
    ge_VkInstanceCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pInstance);
}
function gd_vkCreateInstance(r, a)
{
    a.pInstance = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyInstance(w, a)
{
    w.h(a.instance);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkEnumeratePhysicalDevices(w, a)
{
    w.h(a.instance);
    w.ptr(a.pPhysicalDeviceCount != null);
    if(a.pPhysicalDeviceCount != null)
    {
        w.u32(a.pPhysicalDeviceCount);
    }
    w.ptr(a.pPhysicalDevices != null);
    if(a.pPhysicalDevices != null)
    {
        if(a.pPhysicalDeviceCount)
        {
            if(a.pPhysicalDeviceCount != null)
            {
                for(let k = 0; k < a.pPhysicalDeviceCount; k++)
                {
                    w.h(a.pPhysicalDevices?.[k]);
                }
            }
        }
    }
}
function gd_vkEnumeratePhysicalDevices(r, a)
{
    r.ptr();
    if(a.pPhysicalDeviceCount != null)
    {
        a.pPhysicalDeviceCount = r.u32();
    }
    r.ptr();
    if(a.pPhysicalDevices != null)
    {
        if(a.pPhysicalDeviceCount)
        {
            a.pPhysicalDevices = r.u64s(a.pPhysicalDeviceCount);
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkGetPhysicalDeviceFeatures(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceFeatures(w, a.pFeatures, 2147483647);
}
function gd_vkGetPhysicalDeviceFeatures(r, a)
{
    a.pFeatures = gd_VkPhysicalDeviceFeatures(r, a.pFeatures, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceFormatProperties(w, a)
{
    w.h(a.physicalDevice);
    w.i32(a.format);
    ge_VkFormatProperties(w, a.pFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceFormatProperties(r, a)
{
    a.pFormatProperties = gd_VkFormatProperties(r, a.pFormatProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceImageFormatProperties(w, a)
{
    w.h(a.physicalDevice);
    w.i32(a.format);
    w.i32(a.type);
    w.i32(a.tiling);
    w.u32(a.usage);
    w.u32(a.flags);
    ge_VkImageFormatProperties(w, a.pImageFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceImageFormatProperties(r, a)
{
    a.pImageFormatProperties = gd_VkImageFormatProperties(r, a.pImageFormatProperties, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkGetPhysicalDeviceProperties(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceProperties(w, a.pProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceProperties(r, a)
{
    a.pProperties = gd_VkPhysicalDeviceProperties(r, a.pProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceQueueFamilyProperties(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            ge_VkQueueFamilyProperties(w, a.pQueueFamilyProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceQueueFamilyProperties(r, a)
{
    r.ptr();
    if(a.pQueueFamilyPropertyCount != null)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                a.pQueueFamilyProperties[i] = gd_VkQueueFamilyProperties(r, a.pQueueFamilyProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkGetPhysicalDeviceMemoryProperties(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceMemoryProperties(w, a.pMemoryProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceMemoryProperties(r, a)
{
    a.pMemoryProperties = gd_VkPhysicalDeviceMemoryProperties(r, a.pMemoryProperties, 2147483647);
    return a;
}
function ge_vkGetInstanceProcAddr(w, a)
{
    w.h(a.instance);
    const l0 = a.pName ? a.pName.length : 0; w.be32(l0);
    w.chars(a.pName, l0);
}
function gd_vkGetInstanceProcAddr(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetDeviceProcAddr(w, a)
{
    w.h(a.device);
    const l0 = a.pName ? a.pName.length : 0; w.be32(l0);
    w.chars(a.pName, l0);
}
function gd_vkGetDeviceProcAddr(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkCreateDevice(w, a)
{
    w.h(a.physicalDevice);
    ge_VkDeviceCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pDevice);
}
function gd_vkCreateDevice(r, a)
{
    a.pDevice = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyDevice(w, a)
{
    w.h(a.device);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkEnumerateInstanceExtensionProperties(w, a)
{
    w.ptr(a.pLayerName != null);
    if(a.pLayerName != null)
    {
        const l0 = a.pLayerName ? a.pLayerName.length : 0; w.be32(l0);
        w.chars(a.pLayerName, l0);
    }
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkExtensionProperties(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkEnumerateInstanceExtensionProperties(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkExtensionProperties(r, a.pProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkEnumerateDeviceExtensionProperties(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pLayerName != null);
    if(a.pLayerName != null)
    {
        const l0 = a.pLayerName ? a.pLayerName.length : 0; w.be32(l0);
        w.chars(a.pLayerName, l0);
    }
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkExtensionProperties(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkEnumerateDeviceExtensionProperties(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkExtensionProperties(r, a.pProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkEnumerateInstanceLayerProperties(w, a)
{
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkLayerProperties(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkEnumerateInstanceLayerProperties(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkLayerProperties(r, a.pProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkEnumerateDeviceLayerProperties(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkLayerProperties(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkEnumerateDeviceLayerProperties(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkLayerProperties(r, a.pProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkGetDeviceQueue(w, a)
{
    w.h(a.device);
    w.u32(a.queueFamilyIndex);
    w.u32(a.queueIndex);
    w.h(a.pQueue);
}
function gd_vkGetDeviceQueue(r, a)
{
    a.pQueue = r.h();
    return a;
}
function ge_vkQueueSubmit(w, a)
{
    w.h(a.queue);
    w.u32(a.submitCount);
    for(let i = 0; i < a.submitCount; i++)
    {
        ge_VkSubmitInfo(w, a.pSubmits?.[i], 2147483647);
    }
    w.h(a.fence);
}
function gd_vkQueueSubmit(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkQueueWaitIdle(w, a)
{
    w.h(a.queue);
}
function gd_vkQueueWaitIdle(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkDeviceWaitIdle(w, a)
{
    w.h(a.device);
}
function gd_vkDeviceWaitIdle(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkAllocateMemory(w, a)
{
    w.h(a.device);
    ge_VkMemoryAllocateInfo(w, a.pAllocateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pMemory);
}
function gd_vkAllocateMemory(r, a)
{
    a.pMemory = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkFreeMemory(w, a)
{
    w.h(a.device);
    w.h(a.memory);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkFlushMappedMemoryRanges(w, a)
{
    w.h(a.device);
    w.u32(a.memoryRangeCount);
    for(let i = 0; i < a.memoryRangeCount; i++)
    {
        ge_VkMappedMemoryRange(w, a.pMemoryRanges?.[i], 2147483647);
    }
}
function gd_vkFlushMappedMemoryRanges(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkInvalidateMappedMemoryRanges(w, a)
{
    w.h(a.device);
    w.u32(a.memoryRangeCount);
    for(let i = 0; i < a.memoryRangeCount; i++)
    {
        ge_VkMappedMemoryRange(w, a.pMemoryRanges?.[i], 2147483647);
    }
}
function gd_vkInvalidateMappedMemoryRanges(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetDeviceMemoryCommitment(w, a)
{
    w.h(a.device);
    w.h(a.memory);
    w.u64(a.pCommittedMemoryInBytes);
}
function gd_vkGetDeviceMemoryCommitment(r, a)
{
    a.pCommittedMemoryInBytes = r.u64();
    return a;
}
function ge_vkBindBufferMemory(w, a)
{
    w.h(a.device);
    w.h(a.buffer);
    w.h(a.memory);
    w.u64(a.memoryOffset);
}
function gd_vkBindBufferMemory(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkBindImageMemory(w, a)
{
    w.h(a.device);
    w.h(a.image);
    w.h(a.memory);
    w.u64(a.memoryOffset);
}
function gd_vkBindImageMemory(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetBufferMemoryRequirements(w, a)
{
    w.h(a.device);
    w.h(a.buffer);
    ge_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetBufferMemoryRequirements(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetImageMemoryRequirements(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetImageMemoryRequirements(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetImageSparseMemoryRequirements(w, a)
{
    w.h(a.device);
    w.h(a.image);
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            ge_VkSparseImageMemoryRequirements(w, a.pSparseMemoryRequirements?.[i], 2147483647);
        }
    }
}
function gd_vkGetImageSparseMemoryRequirements(r, a)
{
    r.ptr();
    if(a.pSparseMemoryRequirementCount != null)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    r.ptr();
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                a.pSparseMemoryRequirements[i] = gd_VkSparseImageMemoryRequirements(r, a.pSparseMemoryRequirements[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkGetPhysicalDeviceSparseImageFormatProperties(w, a)
{
    w.h(a.physicalDevice);
    w.i32(a.format);
    w.i32(a.type);
    w.i32(a.samples);
    w.u32(a.usage);
    w.i32(a.tiling);
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkSparseImageFormatProperties(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceSparseImageFormatProperties(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkSparseImageFormatProperties(r, a.pProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkQueueBindSparse(w, a)
{
    w.h(a.queue);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindSparseInfo(w, a.pBindInfo?.[i], 2147483647);
    }
    w.h(a.fence);
}
function gd_vkQueueBindSparse(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCreateFence(w, a)
{
    w.h(a.device);
    ge_VkFenceCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pFence);
}
function gd_vkCreateFence(r, a)
{
    a.pFence = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyFence(w, a)
{
    w.h(a.device);
    w.h(a.fence);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkResetFences(w, a)
{
    w.h(a.device);
    w.u32(a.fenceCount);
    if(a.fenceCount)
    {
        for(let k = 0; k < a.fenceCount; k++)
        {
            w.h(a.pFences?.[k]);
        }
    }
}
function gd_vkResetFences(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetFenceStatus(w, a)
{
    w.h(a.device);
    w.h(a.fence);
}
function gd_vkGetFenceStatus(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkWaitForFences(w, a)
{
    w.h(a.device);
    w.u32(a.fenceCount);
    if(a.fenceCount)
    {
        for(let k = 0; k < a.fenceCount; k++)
        {
            w.h(a.pFences?.[k]);
        }
    }
    w.u32(a.waitAll);
    w.u64(a.timeout);
}
function gd_vkWaitForFences(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCreateSemaphore(w, a)
{
    w.h(a.device);
    ge_VkSemaphoreCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pSemaphore);
}
function gd_vkCreateSemaphore(r, a)
{
    a.pSemaphore = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroySemaphore(w, a)
{
    w.h(a.device);
    w.h(a.semaphore);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateEvent(w, a)
{
    w.h(a.device);
    ge_VkEventCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pEvent);
}
function gd_vkCreateEvent(r, a)
{
    a.pEvent = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyEvent(w, a)
{
    w.h(a.device);
    w.h(a.event);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkGetEventStatus(w, a)
{
    w.h(a.device);
    w.h(a.event);
}
function gd_vkGetEventStatus(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkSetEvent(w, a)
{
    w.h(a.device);
    w.h(a.event);
}
function gd_vkSetEvent(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkResetEvent(w, a)
{
    w.h(a.device);
    w.h(a.event);
}
function gd_vkResetEvent(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCreateQueryPool(w, a)
{
    w.h(a.device);
    ge_VkQueryPoolCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pQueryPool);
}
function gd_vkCreateQueryPool(r, a)
{
    a.pQueryPool = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyQueryPool(w, a)
{
    w.h(a.device);
    w.h(a.queryPool);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkGetQueryPoolResults(w, a)
{
    w.h(a.device);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
    w.be64(a.dataSize);
    if((a.dataSize > 0))
    {
        w.bytes_of(a.pData, a.dataSize);
    }
    w.u64(a.stride);
    w.u32(a.flags);
}
function gd_vkGetQueryPoolResults(r, a)
{
    a.pData = r.bytes_of(a.dataSize);
    a.ret = r.i32();
    return a;
}
function ge_vkCreateBuffer(w, a)
{
    w.h(a.device);
    ge_VkBufferCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pBuffer);
}
function gd_vkCreateBuffer(r, a)
{
    a.pBuffer = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyBuffer(w, a)
{
    w.h(a.device);
    w.h(a.buffer);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateBufferView(w, a)
{
    w.h(a.device);
    ge_VkBufferViewCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pView);
}
function gd_vkCreateBufferView(r, a)
{
    a.pView = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyBufferView(w, a)
{
    w.h(a.device);
    w.h(a.bufferView);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateImage(w, a)
{
    w.h(a.device);
    ge_VkImageCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pImage);
}
function gd_vkCreateImage(r, a)
{
    a.pImage = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyImage(w, a)
{
    w.h(a.device);
    w.h(a.image);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkGetImageSubresourceLayout(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkImageSubresource(w, a.pSubresource, 2147483647);
    ge_VkSubresourceLayout(w, a.pLayout, 2147483647);
}
function gd_vkGetImageSubresourceLayout(r, a)
{
    a.pLayout = gd_VkSubresourceLayout(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkCreateImageView(w, a)
{
    w.h(a.device);
    ge_VkImageViewCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pView);
}
function gd_vkCreateImageView(r, a)
{
    a.pView = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyImageView(w, a)
{
    w.h(a.device);
    w.h(a.imageView);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateShaderModule(w, a)
{
    w.h(a.device);
    ge_VkShaderModuleCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pShaderModule);
}
function gd_vkCreateShaderModule(r, a)
{
    a.pShaderModule = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyShaderModule(w, a)
{
    w.h(a.device);
    w.h(a.shaderModule);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreatePipelineCache(w, a)
{
    w.h(a.device);
    ge_VkPipelineCacheCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pPipelineCache);
}
function gd_vkCreatePipelineCache(r, a)
{
    a.pPipelineCache = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyPipelineCache(w, a)
{
    w.h(a.device);
    w.h(a.pipelineCache);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkGetPipelineCacheData(w, a)
{
    w.h(a.device);
    w.h(a.pipelineCache);
    w.ptr(a.pDataSize != null);
    if(a.pDataSize != null)
    {
        w.be64(a.pDataSize);
    }
    w.ptr(a.pData != null);
    if(a.pData != null)
    {
        if((a.pDataSize > 0))
        {
            w.bytes_of(a.pData, a.pDataSize);
        }
    }
}
function gd_vkGetPipelineCacheData(r, a)
{
    r.ptr();
    if(a.pDataSize != null)
    {
        a.pDataSize = r.be64();
    }
    r.ptr();
    if(a.pData != null)
    {
        a.pData = r.bytes_of(a.pDataSize);
    }
    a.ret = r.i32();
    return a;
}
function ge_vkMergePipelineCaches(w, a)
{
    w.h(a.device);
    w.h(a.dstCache);
    w.u32(a.srcCacheCount);
    if(a.srcCacheCount)
    {
        for(let k = 0; k < a.srcCacheCount; k++)
        {
            w.h(a.pSrcCaches?.[k]);
        }
    }
}
function gd_vkMergePipelineCaches(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCreateGraphicsPipelines(w, a)
{
    w.h(a.device);
    w.h(a.pipelineCache);
    w.u32(a.createInfoCount);
    for(let i = 0; i < a.createInfoCount; i++)
    {
        ge_VkGraphicsPipelineCreateInfo(w, a.pCreateInfos?.[i], 2147483647);
    }
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    if(a.createInfoCount)
    {
        for(let k = 0; k < a.createInfoCount; k++)
        {
            w.h(a.pPipelines?.[k]);
        }
    }
}
function gd_vkCreateGraphicsPipelines(r, a)
{
    if(a.createInfoCount)
    {
        a.pPipelines = r.u64s(a.createInfoCount);
    }
    a.ret = r.i32();
    return a;
}
function ge_vkCreateComputePipelines(w, a)
{
    w.h(a.device);
    w.h(a.pipelineCache);
    w.u32(a.createInfoCount);
    for(let i = 0; i < a.createInfoCount; i++)
    {
        ge_VkComputePipelineCreateInfo(w, a.pCreateInfos?.[i], 2147483647);
    }
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    if(a.createInfoCount)
    {
        for(let k = 0; k < a.createInfoCount; k++)
        {
            w.h(a.pPipelines?.[k]);
        }
    }
}
function gd_vkCreateComputePipelines(r, a)
{
    if(a.createInfoCount)
    {
        a.pPipelines = r.u64s(a.createInfoCount);
    }
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyPipeline(w, a)
{
    w.h(a.device);
    w.h(a.pipeline);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreatePipelineLayout(w, a)
{
    w.h(a.device);
    ge_VkPipelineLayoutCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pPipelineLayout);
}
function gd_vkCreatePipelineLayout(r, a)
{
    a.pPipelineLayout = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyPipelineLayout(w, a)
{
    w.h(a.device);
    w.h(a.pipelineLayout);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateSampler(w, a)
{
    w.h(a.device);
    ge_VkSamplerCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pSampler);
}
function gd_vkCreateSampler(r, a)
{
    a.pSampler = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroySampler(w, a)
{
    w.h(a.device);
    w.h(a.sampler);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateDescriptorSetLayout(w, a)
{
    w.h(a.device);
    ge_VkDescriptorSetLayoutCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pSetLayout);
}
function gd_vkCreateDescriptorSetLayout(r, a)
{
    a.pSetLayout = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyDescriptorSetLayout(w, a)
{
    w.h(a.device);
    w.h(a.descriptorSetLayout);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateDescriptorPool(w, a)
{
    w.h(a.device);
    ge_VkDescriptorPoolCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pDescriptorPool);
}
function gd_vkCreateDescriptorPool(r, a)
{
    a.pDescriptorPool = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyDescriptorPool(w, a)
{
    w.h(a.device);
    w.h(a.descriptorPool);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkResetDescriptorPool(w, a)
{
    w.h(a.device);
    w.h(a.descriptorPool);
    w.u32(a.flags);
}
function gd_vkResetDescriptorPool(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkAllocateDescriptorSets(w, a)
{
    w.h(a.device);
    ge_VkDescriptorSetAllocateInfo(w, a.pAllocateInfo, 2147483647);
    if(a.pAllocateInfo.descriptorSetCount)
    {
        for(let k = 0; k < a.pAllocateInfo.descriptorSetCount; k++)
        {
            w.h(a.pDescriptorSets?.[k]);
        }
    }
}
function gd_vkAllocateDescriptorSets(r, a)
{
    if(a.pAllocateInfo.descriptorSetCount)
    {
        a.pDescriptorSets = r.u64s(a.pAllocateInfo.descriptorSetCount);
    }
    a.ret = r.i32();
    return a;
}
function ge_vkFreeDescriptorSets(w, a)
{
    w.h(a.device);
    w.h(a.descriptorPool);
    w.u32(a.descriptorSetCount);
    w.ptr(a.pDescriptorSets != null);
    if(a.pDescriptorSets != null)
    {
        if(a.descriptorSetCount)
        {
            for(let k = 0; k < a.descriptorSetCount; k++)
            {
                w.h(a.pDescriptorSets?.[k]);
            }
        }
    }
}
function gd_vkFreeDescriptorSets(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkUpdateDescriptorSets(w, a)
{
    w.h(a.device);
    w.u32(a.descriptorWriteCount);
    for(let i = 0; i < a.descriptorWriteCount; i++)
    {
        ge_VkWriteDescriptorSet(w, a.pDescriptorWrites?.[i], 2147483647);
    }
    w.u32(a.descriptorCopyCount);
    for(let i = 0; i < a.descriptorCopyCount; i++)
    {
        ge_VkCopyDescriptorSet(w, a.pDescriptorCopies?.[i], 2147483647);
    }
}
function ge_vkCreateFramebuffer(w, a)
{
    w.h(a.device);
    ge_VkFramebufferCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pFramebuffer);
}
function gd_vkCreateFramebuffer(r, a)
{
    a.pFramebuffer = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyFramebuffer(w, a)
{
    w.h(a.device);
    w.h(a.framebuffer);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateRenderPass(w, a)
{
    w.h(a.device);
    ge_VkRenderPassCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pRenderPass);
}
function gd_vkCreateRenderPass(r, a)
{
    a.pRenderPass = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyRenderPass(w, a)
{
    w.h(a.device);
    w.h(a.renderPass);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkGetRenderAreaGranularity(w, a)
{
    w.h(a.device);
    w.h(a.renderPass);
    ge_VkExtent2D(w, a.pGranularity, 2147483647);
}
function gd_vkGetRenderAreaGranularity(r, a)
{
    a.pGranularity = gd_VkExtent2D(r, a.pGranularity, 2147483647);
    return a;
}
function ge_vkCreateCommandPool(w, a)
{
    w.h(a.device);
    ge_VkCommandPoolCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pCommandPool);
}
function gd_vkCreateCommandPool(r, a)
{
    a.pCommandPool = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyCommandPool(w, a)
{
    w.h(a.device);
    w.h(a.commandPool);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkResetCommandPool(w, a)
{
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.flags);
}
function gd_vkResetCommandPool(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkAllocateCommandBuffers(w, a)
{
    w.h(a.device);
    ge_VkCommandBufferAllocateInfo(w, a.pAllocateInfo, 2147483647);
    if(a.pAllocateInfo.commandBufferCount)
    {
        for(let k = 0; k < a.pAllocateInfo.commandBufferCount; k++)
        {
            w.h(a.pCommandBuffers?.[k]);
        }
    }
}
function gd_vkAllocateCommandBuffers(r, a)
{
    if(a.pAllocateInfo.commandBufferCount)
    {
        a.pCommandBuffers = r.u64s(a.pAllocateInfo.commandBufferCount);
    }
    a.ret = r.i32();
    return a;
}
function ge_vkFreeCommandBuffers(w, a)
{
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.commandBufferCount);
    w.ptr(a.pCommandBuffers != null);
    if(a.pCommandBuffers != null)
    {
        if(a.commandBufferCount)
        {
            for(let k = 0; k < a.commandBufferCount; k++)
            {
                w.h(a.pCommandBuffers?.[k]);
            }
        }
    }
}
function ge_vkBeginCommandBuffer(w, a)
{
    ge_VkCommandBufferBeginInfo(w, a.pBeginInfo, 2147483647);
}
function gd_vkBeginCommandBuffer(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkEndCommandBuffer(w, a)
{
}
function gd_vkEndCommandBuffer(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkResetCommandBuffer(w, a)
{
    w.u32(a.flags);
}
function gd_vkResetCommandBuffer(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBindPipeline(w, a)
{
    w.i32(a.pipelineBindPoint);
    w.h(a.pipeline);
}
function ge_vkCmdSetViewport(w, a)
{
    w.u32(a.firstViewport);
    w.u32(a.viewportCount);
    for(let i = 0; i < a.viewportCount; i++)
    {
        ge_VkViewport(w, a.pViewports?.[i], 2147483647);
    }
}
function ge_vkCmdSetScissor(w, a)
{
    w.u32(a.firstScissor);
    w.u32(a.scissorCount);
    for(let i = 0; i < a.scissorCount; i++)
    {
        ge_VkRect2D(w, a.pScissors?.[i], 2147483647);
    }
}
function ge_vkCmdSetLineWidth(w, a)
{
    w.f32(a.lineWidth);
}
function ge_vkCmdSetDepthBias(w, a)
{
    w.f32(a.depthBiasConstantFactor);
    w.f32(a.depthBiasClamp);
    w.f32(a.depthBiasSlopeFactor);
}
function ge_vkCmdSetBlendConstants(w, a)
{
    w.f32s(a.blendConstants, 4);
}
function ge_vkCmdSetDepthBounds(w, a)
{
    w.f32(a.minDepthBounds);
    w.f32(a.maxDepthBounds);
}
function ge_vkCmdSetStencilCompareMask(w, a)
{
    w.u32(a.faceMask);
    w.u32(a.compareMask);
}
function ge_vkCmdSetStencilWriteMask(w, a)
{
    w.u32(a.faceMask);
    w.u32(a.writeMask);
}
function ge_vkCmdSetStencilReference(w, a)
{
    w.u32(a.faceMask);
    w.u32(a.reference);
}
function ge_vkCmdBindDescriptorSets(w, a)
{
    w.i32(a.pipelineBindPoint);
    w.h(a.layout);
    w.u32(a.firstSet);
    w.u32(a.descriptorSetCount);
    if(a.descriptorSetCount)
    {
        for(let k = 0; k < a.descriptorSetCount; k++)
        {
            w.h(a.pDescriptorSets?.[k]);
        }
    }
    w.u32(a.dynamicOffsetCount);
    if((a.dynamicOffsetCount > 0))
    {
        w.u32s(a.pDynamicOffsets, a.dynamicOffsetCount);
    }
}
function ge_vkCmdBindIndexBuffer(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.i32(a.indexType);
}
function ge_vkCmdBindVertexBuffers(w, a)
{
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    if(a.bindingCount)
    {
        for(let k = 0; k < a.bindingCount; k++)
        {
            w.h(a.pBuffers?.[k]);
        }
    }
    if((a.bindingCount > 0))
    {
        w.u64s(a.pOffsets, a.bindingCount);
    }
}
function ge_vkCmdDraw(w, a)
{
    w.u32(a.vertexCount);
    w.u32(a.instanceCount);
    w.u32(a.firstVertex);
    w.u32(a.firstInstance);
}
function ge_vkCmdDrawIndexed(w, a)
{
    w.u32(a.indexCount);
    w.u32(a.instanceCount);
    w.u32(a.firstIndex);
    w.i32(a.vertexOffset);
    w.u32(a.firstInstance);
}
function ge_vkCmdDrawIndirect(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.u32(a.drawCount);
    w.u32(a.stride);
}
function ge_vkCmdDrawIndexedIndirect(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.u32(a.drawCount);
    w.u32(a.stride);
}
function ge_vkCmdDispatch(w, a)
{
    w.u32(a.groupCountX);
    w.u32(a.groupCountY);
    w.u32(a.groupCountZ);
}
function ge_vkCmdDispatchIndirect(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
}
function ge_vkCmdCopyBuffer(w, a)
{
    w.h(a.srcBuffer);
    w.h(a.dstBuffer);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkBufferCopy(w, a.pRegions?.[i], 2147483647);
    }
}
function ge_vkCmdCopyImage(w, a)
{
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkImageCopy(w, a.pRegions?.[i], 2147483647);
    }
}
function ge_vkCmdBlitImage(w, a)
{
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkImageBlit(w, a.pRegions?.[i], 2147483647);
    }
    w.i32(a.filter);
}
function ge_vkCmdCopyBufferToImage(w, a)
{
    w.h(a.srcBuffer);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkBufferImageCopy(w, a.pRegions?.[i], 2147483647);
    }
}
function ge_vkCmdCopyImageToBuffer(w, a)
{
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstBuffer);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkBufferImageCopy(w, a.pRegions?.[i], 2147483647);
    }
}
function ge_vkCmdUpdateBuffer(w, a)
{
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.dataSize);
    if((a.dataSize > 0))
    {
        w.bytes_of(a.pData, a.dataSize);
    }
}
function ge_vkCmdFillBuffer(w, a)
{
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.size);
    w.u32(a.data);
}
function ge_vkCmdClearColorImage(w, a)
{
    w.h(a.image);
    w.i32(a.imageLayout);
    ge_VkClearColorValue(w, a.pColor, 2147483647);
    w.u32(a.rangeCount);
    for(let i = 0; i < a.rangeCount; i++)
    {
        ge_VkImageSubresourceRange(w, a.pRanges?.[i], 2147483647);
    }
}
function ge_vkCmdClearDepthStencilImage(w, a)
{
    w.h(a.image);
    w.i32(a.imageLayout);
    ge_VkClearDepthStencilValue(w, a.pDepthStencil, 2147483647);
    w.u32(a.rangeCount);
    for(let i = 0; i < a.rangeCount; i++)
    {
        ge_VkImageSubresourceRange(w, a.pRanges?.[i], 2147483647);
    }
}
function ge_vkCmdClearAttachments(w, a)
{
    w.u32(a.attachmentCount);
    for(let i = 0; i < a.attachmentCount; i++)
    {
        ge_VkClearAttachment(w, a.pAttachments?.[i], 2147483647);
    }
    w.u32(a.rectCount);
    for(let i = 0; i < a.rectCount; i++)
    {
        ge_VkClearRect(w, a.pRects?.[i], 2147483647);
    }
}
function ge_vkCmdResolveImage(w, a)
{
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    for(let i = 0; i < a.regionCount; i++)
    {
        ge_VkImageResolve(w, a.pRegions?.[i], 2147483647);
    }
}
function ge_vkCmdSetEvent(w, a)
{
    w.h(a.event);
    w.u32(a.stageMask);
}
function ge_vkCmdResetEvent(w, a)
{
    w.h(a.event);
    w.u32(a.stageMask);
}
function ge_vkCmdWaitEvents(w, a)
{
    w.u32(a.eventCount);
    if(a.eventCount)
    {
        for(let k = 0; k < a.eventCount; k++)
        {
            w.h(a.pEvents?.[k]);
        }
    }
    w.u32(a.srcStageMask);
    w.u32(a.dstStageMask);
    w.u32(a.memoryBarrierCount);
    for(let i = 0; i < a.memoryBarrierCount; i++)
    {
        ge_VkMemoryBarrier(w, a.pMemoryBarriers?.[i], 2147483647);
    }
    w.u32(a.bufferMemoryBarrierCount);
    for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
    {
        ge_VkBufferMemoryBarrier(w, a.pBufferMemoryBarriers?.[i], 2147483647);
    }
    w.u32(a.imageMemoryBarrierCount);
    for(let i = 0; i < a.imageMemoryBarrierCount; i++)
    {
        ge_VkImageMemoryBarrier(w, a.pImageMemoryBarriers?.[i], 2147483647);
    }
}
function ge_vkCmdPipelineBarrier(w, a)
{
    w.u32(a.srcStageMask);
    w.u32(a.dstStageMask);
    w.u32(a.dependencyFlags);
    w.u32(a.memoryBarrierCount);
    for(let i = 0; i < a.memoryBarrierCount; i++)
    {
        ge_VkMemoryBarrier(w, a.pMemoryBarriers?.[i], 2147483647);
    }
    w.u32(a.bufferMemoryBarrierCount);
    for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
    {
        ge_VkBufferMemoryBarrier(w, a.pBufferMemoryBarriers?.[i], 2147483647);
    }
    w.u32(a.imageMemoryBarrierCount);
    for(let i = 0; i < a.imageMemoryBarrierCount; i++)
    {
        ge_VkImageMemoryBarrier(w, a.pImageMemoryBarriers?.[i], 2147483647);
    }
}
function ge_vkCmdBeginQuery(w, a)
{
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.flags);
}
function ge_vkCmdEndQuery(w, a)
{
    w.h(a.queryPool);
    w.u32(a.query);
}
function ge_vkCmdResetQueryPool(w, a)
{
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
}
function ge_vkCmdWriteTimestamp(w, a)
{
    w.i32(a.pipelineStage);
    w.h(a.queryPool);
    w.u32(a.query);
}
function ge_vkCmdCopyQueryPoolResults(w, a)
{
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.stride);
    w.u32(a.flags);
}
function ge_vkCmdPushConstants(w, a)
{
    w.h(a.layout);
    w.u32(a.stageFlags);
    w.u32(a.offset);
    w.u32(a.size);
    if((a.size > 0))
    {
        w.bytes_of(a.pValues, a.size);
    }
}
function ge_vkCmdBeginRenderPass(w, a)
{
    ge_VkRenderPassBeginInfo(w, a.pRenderPassBegin, 2147483647);
    w.i32(a.contents);
}
function ge_vkCmdNextSubpass(w, a)
{
    w.i32(a.contents);
}
function ge_vkCmdEndRenderPass(w, a)
{
}
function ge_vkCmdExecuteCommands(w, a)
{
    w.u32(a.commandBufferCount);
    if(a.commandBufferCount)
    {
        for(let k = 0; k < a.commandBufferCount; k++)
        {
            w.h(a.pCommandBuffers?.[k]);
        }
    }
}
function ge_vkEnumerateInstanceVersion(w, a)
{
    w.u32(a.pApiVersion);
}
function gd_vkEnumerateInstanceVersion(r, a)
{
    a.pApiVersion = r.u32();
    a.ret = r.i32();
    return a;
}
function ge_vkBindBufferMemory2(w, a)
{
    w.h(a.device);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindBufferMemoryInfo(w, a.pBindInfos?.[i], 2147483647);
    }
}
function gd_vkBindBufferMemory2(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkBindImageMemory2(w, a)
{
    w.h(a.device);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindImageMemoryInfo(w, a.pBindInfos?.[i], 2147483647);
    }
}
function gd_vkBindImageMemory2(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetDeviceGroupPeerMemoryFeatures(w, a)
{
    w.h(a.device);
    w.u32(a.heapIndex);
    w.u32(a.localDeviceIndex);
    w.u32(a.remoteDeviceIndex);
    w.u32(a.pPeerMemoryFeatures);
}
function gd_vkGetDeviceGroupPeerMemoryFeatures(r, a)
{
    a.pPeerMemoryFeatures = r.u32();
    return a;
}
function ge_vkCmdSetDeviceMask(w, a)
{
    w.u32(a.deviceMask);
}
function ge_vkCmdDispatchBase(w, a)
{
    w.u32(a.baseGroupX);
    w.u32(a.baseGroupY);
    w.u32(a.baseGroupZ);
    w.u32(a.groupCountX);
    w.u32(a.groupCountY);
    w.u32(a.groupCountZ);
}
function ge_vkEnumeratePhysicalDeviceGroups(w, a)
{
    w.h(a.instance);
    w.ptr(a.pPhysicalDeviceGroupCount != null);
    if(a.pPhysicalDeviceGroupCount != null)
    {
        w.u32(a.pPhysicalDeviceGroupCount);
    }
    w.ptr(a.pPhysicalDeviceGroupProperties != null);
    if(a.pPhysicalDeviceGroupProperties != null)
    {
        for(let i = 0; i < a.pPhysicalDeviceGroupCount; i++)
        {
            ge_VkPhysicalDeviceGroupProperties(w, a.pPhysicalDeviceGroupProperties?.[i], 2147483647);
        }
    }
}
function gd_vkEnumeratePhysicalDeviceGroups(r, a)
{
    r.ptr();
    if(a.pPhysicalDeviceGroupCount != null)
    {
        a.pPhysicalDeviceGroupCount = r.u32();
    }
    r.ptr();
    if(a.pPhysicalDeviceGroupProperties != null)
    {
        if(a.pPhysicalDeviceGroupCount != null)
        {
            a.pPhysicalDeviceGroupProperties = new Array(r.count(a.pPhysicalDeviceGroupCount));
            for(let i = 0; i < a.pPhysicalDeviceGroupCount; i++)
            {
                a.pPhysicalDeviceGroupProperties[i] = gd_VkPhysicalDeviceGroupProperties(r, a.pPhysicalDeviceGroupProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkGetImageMemoryRequirements2(w, a)
{
    w.h(a.device);
    ge_VkImageMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetImageMemoryRequirements2(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetBufferMemoryRequirements2(w, a)
{
    w.h(a.device);
    ge_VkBufferMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetBufferMemoryRequirements2(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetImageSparseMemoryRequirements2(w, a)
{
    w.h(a.device);
    ge_VkImageSparseMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            ge_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
        }
    }
}
function gd_vkGetImageSparseMemoryRequirements2(r, a)
{
    r.ptr();
    if(a.pSparseMemoryRequirementCount != null)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    r.ptr();
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                a.pSparseMemoryRequirements[i] = gd_VkSparseImageMemoryRequirements2(r, a.pSparseMemoryRequirements[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkGetPhysicalDeviceFeatures2(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceFeatures2(w, a.pFeatures, 2147483647);
}
function gd_vkGetPhysicalDeviceFeatures2(r, a)
{
    a.pFeatures = gd_VkPhysicalDeviceFeatures2(r, a.pFeatures, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceProperties2(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceProperties2(w, a.pProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceProperties2(r, a)
{
    a.pProperties = gd_VkPhysicalDeviceProperties2(r, a.pProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceFormatProperties2(w, a)
{
    w.h(a.physicalDevice);
    w.i32(a.format);
    ge_VkFormatProperties2(w, a.pFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceFormatProperties2(r, a)
{
    a.pFormatProperties = gd_VkFormatProperties2(r, a.pFormatProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceImageFormatProperties2(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceImageFormatInfo2(w, a.pImageFormatInfo, 2147483647);
    ge_VkImageFormatProperties2(w, a.pImageFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceImageFormatProperties2(r, a)
{
    a.pImageFormatProperties = gd_VkImageFormatProperties2(r, a.pImageFormatProperties, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkGetPhysicalDeviceQueueFamilyProperties2(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            ge_VkQueueFamilyProperties2(w, a.pQueueFamilyProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceQueueFamilyProperties2(r, a)
{
    r.ptr();
    if(a.pQueueFamilyPropertyCount != null)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                a.pQueueFamilyProperties[i] = gd_VkQueueFamilyProperties2(r, a.pQueueFamilyProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkGetPhysicalDeviceMemoryProperties2(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceMemoryProperties2(w, a.pMemoryProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceMemoryProperties2(r, a)
{
    a.pMemoryProperties = gd_VkPhysicalDeviceMemoryProperties2(r, a.pMemoryProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceSparseImageFormatProperties2(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceSparseImageFormatInfo2(w, a.pFormatInfo, 2147483647);
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkSparseImageFormatProperties2(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceSparseImageFormatProperties2(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkSparseImageFormatProperties2(r, a.pProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkTrimCommandPool(w, a)
{
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.flags);
}
function ge_vkGetDeviceQueue2(w, a)
{
    w.h(a.device);
    ge_VkDeviceQueueInfo2(w, a.pQueueInfo, 2147483647);
    w.h(a.pQueue);
}
function gd_vkGetDeviceQueue2(r, a)
{
    a.pQueue = r.h();
    return a;
}
function ge_vkCreateSamplerYcbcrConversion(w, a)
{
    w.h(a.device);
    ge_VkSamplerYcbcrConversionCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pYcbcrConversion);
}
function gd_vkCreateSamplerYcbcrConversion(r, a)
{
    a.pYcbcrConversion = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroySamplerYcbcrConversion(w, a)
{
    w.h(a.device);
    w.h(a.ycbcrConversion);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkCreateDescriptorUpdateTemplate(w, a)
{
    w.h(a.device);
    ge_VkDescriptorUpdateTemplateCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pDescriptorUpdateTemplate);
}
function gd_vkCreateDescriptorUpdateTemplate(r, a)
{
    a.pDescriptorUpdateTemplate = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyDescriptorUpdateTemplate(w, a)
{
    w.h(a.device);
    w.h(a.descriptorUpdateTemplate);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkUpdateDescriptorSetWithTemplate(w, a)
{
    w.h(a.device);
    w.h(a.descriptorSet);
    w.h(a.descriptorUpdateTemplate);
    w.ptr(a.pData != null);
    if(a.pData != null)
    {
        w.void(a.pData);
    }
}
function ge_vkGetPhysicalDeviceExternalBufferProperties(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalBufferInfo(w, a.pExternalBufferInfo, 2147483647);
    ge_VkExternalBufferProperties(w, a.pExternalBufferProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalBufferProperties(r, a)
{
    a.pExternalBufferProperties = gd_VkExternalBufferProperties(r, a.pExternalBufferProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceExternalFenceProperties(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalFenceInfo(w, a.pExternalFenceInfo, 2147483647);
    ge_VkExternalFenceProperties(w, a.pExternalFenceProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalFenceProperties(r, a)
{
    a.pExternalFenceProperties = gd_VkExternalFenceProperties(r, a.pExternalFenceProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceExternalSemaphoreProperties(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalSemaphoreInfo(w, a.pExternalSemaphoreInfo, 2147483647);
    ge_VkExternalSemaphoreProperties(w, a.pExternalSemaphoreProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalSemaphoreProperties(r, a)
{
    a.pExternalSemaphoreProperties = gd_VkExternalSemaphoreProperties(r, a.pExternalSemaphoreProperties, 2147483647);
    return a;
}
function ge_vkGetDescriptorSetLayoutSupport(w, a)
{
    w.h(a.device);
    ge_VkDescriptorSetLayoutCreateInfo(w, a.pCreateInfo, 2147483647);
    ge_VkDescriptorSetLayoutSupport(w, a.pSupport, 2147483647);
}
function gd_vkGetDescriptorSetLayoutSupport(r, a)
{
    a.pSupport = gd_VkDescriptorSetLayoutSupport(r, a.pSupport, 2147483647);
    return a;
}
function ge_vkCmdDrawIndirectCount(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.h(a.countBuffer);
    w.u64(a.countBufferOffset);
    w.u32(a.maxDrawCount);
    w.u32(a.stride);
}
function ge_vkCmdDrawIndexedIndirectCount(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.h(a.countBuffer);
    w.u64(a.countBufferOffset);
    w.u32(a.maxDrawCount);
    w.u32(a.stride);
}
function ge_vkCreateRenderPass2(w, a)
{
    w.h(a.device);
    ge_VkRenderPassCreateInfo2(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pRenderPass);
}
function gd_vkCreateRenderPass2(r, a)
{
    a.pRenderPass = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBeginRenderPass2(w, a)
{
    ge_VkRenderPassBeginInfo(w, a.pRenderPassBegin, 2147483647);
    ge_VkSubpassBeginInfo(w, a.pSubpassBeginInfo, 2147483647);
}
function ge_vkCmdNextSubpass2(w, a)
{
    ge_VkSubpassBeginInfo(w, a.pSubpassBeginInfo, 2147483647);
    ge_VkSubpassEndInfo(w, a.pSubpassEndInfo, 2147483647);
}
function ge_vkCmdEndRenderPass2(w, a)
{
    ge_VkSubpassEndInfo(w, a.pSubpassEndInfo, 2147483647);
}
function ge_vkResetQueryPool(w, a)
{
    w.h(a.device);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
}
function ge_vkGetSemaphoreCounterValue(w, a)
{
    w.h(a.device);
    w.h(a.semaphore);
    w.u64(a.pValue);
}
function gd_vkGetSemaphoreCounterValue(r, a)
{
    a.pValue = r.u64();
    a.ret = r.i32();
    return a;
}
function ge_vkWaitSemaphores(w, a)
{
    w.h(a.device);
    ge_VkSemaphoreWaitInfo(w, a.pWaitInfo, 2147483647);
    w.u64(a.timeout);
}
function gd_vkWaitSemaphores(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkSignalSemaphore(w, a)
{
    w.h(a.device);
    ge_VkSemaphoreSignalInfo(w, a.pSignalInfo, 2147483647);
}
function gd_vkSignalSemaphore(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetBufferDeviceAddress(w, a)
{
    w.h(a.device);
    ge_VkBufferDeviceAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetBufferDeviceAddress(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetBufferOpaqueCaptureAddress(w, a)
{
    w.h(a.device);
    ge_VkBufferDeviceAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetBufferOpaqueCaptureAddress(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetDeviceMemoryOpaqueCaptureAddress(w, a)
{
    w.h(a.device);
    ge_VkDeviceMemoryOpaqueCaptureAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetDeviceMemoryOpaqueCaptureAddress(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetPhysicalDeviceToolProperties(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pToolCount != null);
    if(a.pToolCount != null)
    {
        w.u32(a.pToolCount);
    }
    w.ptr(a.pToolProperties != null);
    if(a.pToolProperties != null)
    {
        for(let i = 0; i < a.pToolCount; i++)
        {
            ge_VkPhysicalDeviceToolProperties(w, a.pToolProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceToolProperties(r, a)
{
    r.ptr();
    if(a.pToolCount != null)
    {
        a.pToolCount = r.u32();
    }
    r.ptr();
    if(a.pToolProperties != null)
    {
        if(a.pToolCount != null)
        {
            a.pToolProperties = new Array(r.count(a.pToolCount));
            for(let i = 0; i < a.pToolCount; i++)
            {
                a.pToolProperties[i] = gd_VkPhysicalDeviceToolProperties(r, a.pToolProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkCreatePrivateDataSlot(w, a)
{
    w.h(a.device);
    ge_VkPrivateDataSlotCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pPrivateDataSlot);
}
function gd_vkCreatePrivateDataSlot(r, a)
{
    a.pPrivateDataSlot = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyPrivateDataSlot(w, a)
{
    w.h(a.device);
    w.h(a.privateDataSlot);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkSetPrivateData(w, a)
{
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.data);
}
function gd_vkSetPrivateData(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetPrivateData(w, a)
{
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.pData);
}
function gd_vkGetPrivateData(r, a)
{
    a.pData = r.u64();
    return a;
}
function ge_vkCmdSetEvent2(w, a)
{
    w.h(a.event);
    ge_VkDependencyInfo(w, a.pDependencyInfo, 2147483647);
}
function ge_vkCmdResetEvent2(w, a)
{
    w.h(a.event);
    w.u64(a.stageMask);
}
function ge_vkCmdWaitEvents2(w, a)
{
    w.u32(a.eventCount);
    if(a.eventCount)
    {
        for(let k = 0; k < a.eventCount; k++)
        {
            w.h(a.pEvents?.[k]);
        }
    }
    for(let i = 0; i < a.eventCount; i++)
    {
        ge_VkDependencyInfo(w, a.pDependencyInfos?.[i], 2147483647);
    }
}
function ge_vkCmdPipelineBarrier2(w, a)
{
    ge_VkDependencyInfo(w, a.pDependencyInfo, 2147483647);
}
function ge_vkCmdWriteTimestamp2(w, a)
{
    w.u64(a.stage);
    w.h(a.queryPool);
    w.u32(a.query);
}
function ge_vkQueueSubmit2(w, a)
{
    w.h(a.queue);
    w.u32(a.submitCount);
    for(let i = 0; i < a.submitCount; i++)
    {
        ge_VkSubmitInfo2(w, a.pSubmits?.[i], 2147483647);
    }
    w.h(a.fence);
}
function gd_vkQueueSubmit2(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCmdCopyBuffer2(w, a)
{
    ge_VkCopyBufferInfo2(w, a.pCopyBufferInfo, 2147483647);
}
function ge_vkCmdCopyImage2(w, a)
{
    ge_VkCopyImageInfo2(w, a.pCopyImageInfo, 2147483647);
}
function ge_vkCmdCopyBufferToImage2(w, a)
{
    ge_VkCopyBufferToImageInfo2(w, a.pCopyBufferToImageInfo, 2147483647);
}
function ge_vkCmdCopyImageToBuffer2(w, a)
{
    ge_VkCopyImageToBufferInfo2(w, a.pCopyImageToBufferInfo, 2147483647);
}
function ge_vkCmdBlitImage2(w, a)
{
    ge_VkBlitImageInfo2(w, a.pBlitImageInfo, 2147483647);
}
function ge_vkCmdResolveImage2(w, a)
{
    ge_VkResolveImageInfo2(w, a.pResolveImageInfo, 2147483647);
}
function ge_vkCmdBeginRendering(w, a)
{
    ge_VkRenderingInfo(w, a.pRenderingInfo, 2147483647);
}
function ge_vkCmdEndRendering(w, a)
{
}
function ge_vkCmdSetCullMode(w, a)
{
    w.u32(a.cullMode);
}
function ge_vkCmdSetFrontFace(w, a)
{
    w.i32(a.frontFace);
}
function ge_vkCmdSetPrimitiveTopology(w, a)
{
    w.i32(a.primitiveTopology);
}
function ge_vkCmdSetViewportWithCount(w, a)
{
    w.u32(a.viewportCount);
    for(let i = 0; i < a.viewportCount; i++)
    {
        ge_VkViewport(w, a.pViewports?.[i], 2147483647);
    }
}
function ge_vkCmdSetScissorWithCount(w, a)
{
    w.u32(a.scissorCount);
    for(let i = 0; i < a.scissorCount; i++)
    {
        ge_VkRect2D(w, a.pScissors?.[i], 2147483647);
    }
}
function ge_vkCmdBindVertexBuffers2(w, a)
{
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    w.ptr(a.pBuffers != null);
    if(a.pBuffers != null)
    {
        if(a.bindingCount)
        {
            for(let k = 0; k < a.bindingCount; k++)
            {
                w.h(a.pBuffers?.[k]);
            }
        }
    }
    if((a.bindingCount > 0))
    {
        w.u64s(a.pOffsets, a.bindingCount);
    }
    w.ptr(a.pSizes != null);
    if(a.pSizes != null)
    {
        if((a.bindingCount > 0))
        {
            w.u64s(a.pSizes, a.bindingCount);
        }
    }
    w.ptr(a.pStrides != null);
    if(a.pStrides != null)
    {
        if((a.bindingCount > 0))
        {
            w.u64s(a.pStrides, a.bindingCount);
        }
    }
}
function ge_vkCmdSetDepthTestEnable(w, a)
{
    w.u32(a.depthTestEnable);
}
function ge_vkCmdSetDepthWriteEnable(w, a)
{
    w.u32(a.depthWriteEnable);
}
function ge_vkCmdSetDepthCompareOp(w, a)
{
    w.i32(a.depthCompareOp);
}
function ge_vkCmdSetDepthBoundsTestEnable(w, a)
{
    w.u32(a.depthBoundsTestEnable);
}
function ge_vkCmdSetStencilTestEnable(w, a)
{
    w.u32(a.stencilTestEnable);
}
function ge_vkCmdSetStencilOp(w, a)
{
    w.u32(a.faceMask);
    w.i32(a.failOp);
    w.i32(a.passOp);
    w.i32(a.depthFailOp);
    w.i32(a.compareOp);
}
function ge_vkCmdSetRasterizerDiscardEnable(w, a)
{
    w.u32(a.rasterizerDiscardEnable);
}
function ge_vkCmdSetDepthBiasEnable(w, a)
{
    w.u32(a.depthBiasEnable);
}
function ge_vkCmdSetPrimitiveRestartEnable(w, a)
{
    w.u32(a.primitiveRestartEnable);
}
function ge_vkGetDeviceBufferMemoryRequirements(w, a)
{
    w.h(a.device);
    ge_VkDeviceBufferMemoryRequirements(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetDeviceBufferMemoryRequirements(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetDeviceImageMemoryRequirements(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageMemoryRequirements(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetDeviceImageMemoryRequirements(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetDeviceImageSparseMemoryRequirements(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageMemoryRequirements(w, a.pInfo, 2147483647);
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            ge_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
        }
    }
}
function gd_vkGetDeviceImageSparseMemoryRequirements(r, a)
{
    r.ptr();
    if(a.pSparseMemoryRequirementCount != null)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    r.ptr();
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                a.pSparseMemoryRequirements[i] = gd_VkSparseImageMemoryRequirements2(r, a.pSparseMemoryRequirements[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkCmdSetLineStipple(w, a)
{
    w.u32(a.lineStippleFactor);
    w.u16(a.lineStipplePattern);
}
function ge_vkMapMemory2(w, a)
{
    w.h(a.device);
    ge_VkMemoryMapInfo(w, a.pMemoryMapInfo, 2147483647);
    w.ptr(a.ppData != null);
    if(a.ppData != null)
    {
        w.void(a.ppData);
    }
}
function gd_vkMapMemory2(r, a)
{
    r.ptr();
    if(a.ppData != null)
    {
        a.ppData = r.void();
    }
    a.ret = r.i32();
    return a;
}
function ge_vkUnmapMemory2(w, a)
{
    w.h(a.device);
    ge_VkMemoryUnmapInfo(w, a.pMemoryUnmapInfo, 2147483647);
}
function gd_vkUnmapMemory2(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBindIndexBuffer2(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.u64(a.size);
    w.i32(a.indexType);
}
function ge_vkGetRenderingAreaGranularity(w, a)
{
    w.h(a.device);
    ge_VkRenderingAreaInfo(w, a.pRenderingAreaInfo, 2147483647);
    ge_VkExtent2D(w, a.pGranularity, 2147483647);
}
function gd_vkGetRenderingAreaGranularity(r, a)
{
    a.pGranularity = gd_VkExtent2D(r, a.pGranularity, 2147483647);
    return a;
}
function ge_vkGetDeviceImageSubresourceLayout(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageSubresourceInfo(w, a.pInfo, 2147483647);
    ge_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function gd_vkGetDeviceImageSubresourceLayout(r, a)
{
    a.pLayout = gd_VkSubresourceLayout2(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkGetImageSubresourceLayout2(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkImageSubresource2(w, a.pSubresource, 2147483647);
    ge_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function gd_vkGetImageSubresourceLayout2(r, a)
{
    a.pLayout = gd_VkSubresourceLayout2(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkCmdPushDescriptorSet(w, a)
{
    w.i32(a.pipelineBindPoint);
    w.h(a.layout);
    w.u32(a.set);
    w.u32(a.descriptorWriteCount);
    for(let i = 0; i < a.descriptorWriteCount; i++)
    {
        ge_VkWriteDescriptorSet(w, a.pDescriptorWrites?.[i], 2147483647);
    }
}
function ge_vkCmdPushDescriptorSetWithTemplate(w, a)
{
    w.h(a.descriptorUpdateTemplate);
    w.h(a.layout);
    w.u32(a.set);
    w.ptr(a.pData != null);
    if(a.pData != null)
    {
        w.void(a.pData);
    }
}
function ge_vkCmdSetRenderingAttachmentLocations(w, a)
{
    ge_VkRenderingAttachmentLocationInfo(w, a.pLocationInfo, 2147483647);
}
function ge_vkCmdSetRenderingInputAttachmentIndices(w, a)
{
    ge_VkRenderingInputAttachmentIndexInfo(w, a.pInputAttachmentIndexInfo, 2147483647);
}
function ge_vkCmdBindDescriptorSets2(w, a)
{
    ge_VkBindDescriptorSetsInfo(w, a.pBindDescriptorSetsInfo, 2147483647);
}
function ge_vkCmdPushConstants2(w, a)
{
    ge_VkPushConstantsInfo(w, a.pPushConstantsInfo, 2147483647);
}
function ge_vkCmdPushDescriptorSet2(w, a)
{
    ge_VkPushDescriptorSetInfo(w, a.pPushDescriptorSetInfo, 2147483647);
}
function ge_vkCmdPushDescriptorSetWithTemplate2(w, a)
{
    ge_VkPushDescriptorSetWithTemplateInfo(w, a.pPushDescriptorSetWithTemplateInfo, 2147483647);
}
function ge_vkCopyMemoryToImage(w, a)
{
    w.h(a.device);
    ge_VkCopyMemoryToImageInfo(w, a.pCopyMemoryToImageInfo, 2147483647);
}
function gd_vkCopyMemoryToImage(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCopyImageToMemory(w, a)
{
    w.h(a.device);
    ge_VkCopyImageToMemoryInfo(w, a.pCopyImageToMemoryInfo, 2147483647);
}
function gd_vkCopyImageToMemory(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCopyImageToImage(w, a)
{
    w.h(a.device);
    ge_VkCopyImageToImageInfo(w, a.pCopyImageToImageInfo, 2147483647);
}
function gd_vkCopyImageToImage(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkTransitionImageLayout(w, a)
{
    w.h(a.device);
    w.u32(a.transitionCount);
    for(let i = 0; i < a.transitionCount; i++)
    {
        ge_VkHostImageLayoutTransitionInfo(w, a.pTransitions?.[i], 2147483647);
    }
}
function gd_vkTransitionImageLayout(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBeginRenderingKHR(w, a)
{
    ge_VkRenderingInfo(w, a.pRenderingInfo, 2147483647);
}
function ge_vkCmdEndRenderingKHR(w, a)
{
}
function ge_vkGetPhysicalDeviceFeatures2KHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceFeatures2(w, a.pFeatures, 2147483647);
}
function gd_vkGetPhysicalDeviceFeatures2KHR(r, a)
{
    a.pFeatures = gd_VkPhysicalDeviceFeatures2(r, a.pFeatures, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceProperties2(w, a.pProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceProperties2KHR(r, a)
{
    a.pProperties = gd_VkPhysicalDeviceProperties2(r, a.pProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceFormatProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    w.i32(a.format);
    ge_VkFormatProperties2(w, a.pFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceFormatProperties2KHR(r, a)
{
    a.pFormatProperties = gd_VkFormatProperties2(r, a.pFormatProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceImageFormatProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceImageFormatInfo2(w, a.pImageFormatInfo, 2147483647);
    ge_VkImageFormatProperties2(w, a.pImageFormatProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceImageFormatProperties2KHR(r, a)
{
    a.pImageFormatProperties = gd_VkImageFormatProperties2(r, a.pImageFormatProperties, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkGetPhysicalDeviceQueueFamilyProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pQueueFamilyPropertyCount != null);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u32(a.pQueueFamilyPropertyCount);
    }
    w.ptr(a.pQueueFamilyProperties != null);
    if(a.pQueueFamilyProperties != null)
    {
        for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
        {
            ge_VkQueueFamilyProperties2(w, a.pQueueFamilyProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceQueueFamilyProperties2KHR(r, a)
{
    r.ptr();
    if(a.pQueueFamilyPropertyCount != null)
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pQueueFamilyProperties != null)
    {
        if(a.pQueueFamilyPropertyCount != null)
        {
            a.pQueueFamilyProperties = new Array(r.count(a.pQueueFamilyPropertyCount));
            for(let i = 0; i < a.pQueueFamilyPropertyCount; i++)
            {
                a.pQueueFamilyProperties[i] = gd_VkQueueFamilyProperties2(r, a.pQueueFamilyProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkGetPhysicalDeviceMemoryProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceMemoryProperties2(w, a.pMemoryProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceMemoryProperties2KHR(r, a)
{
    a.pMemoryProperties = gd_VkPhysicalDeviceMemoryProperties2(r, a.pMemoryProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceSparseImageFormatInfo2(w, a.pFormatInfo, 2147483647);
    w.ptr(a.pPropertyCount != null);
    if(a.pPropertyCount != null)
    {
        w.u32(a.pPropertyCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pPropertyCount; i++)
        {
            ge_VkSparseImageFormatProperties2(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceSparseImageFormatProperties2KHR(r, a)
{
    r.ptr();
    if(a.pPropertyCount != null)
    {
        a.pPropertyCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pPropertyCount != null)
        {
            a.pProperties = new Array(r.count(a.pPropertyCount));
            for(let i = 0; i < a.pPropertyCount; i++)
            {
                a.pProperties[i] = gd_VkSparseImageFormatProperties2(r, a.pProperties[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkTrimCommandPoolKHR(w, a)
{
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.flags);
}
function ge_vkGetPhysicalDeviceExternalBufferPropertiesKHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalBufferInfo(w, a.pExternalBufferInfo, 2147483647);
    ge_VkExternalBufferProperties(w, a.pExternalBufferProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalBufferPropertiesKHR(r, a)
{
    a.pExternalBufferProperties = gd_VkExternalBufferProperties(r, a.pExternalBufferProperties, 2147483647);
    return a;
}
function ge_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalSemaphoreInfo(w, a.pExternalSemaphoreInfo, 2147483647);
    ge_VkExternalSemaphoreProperties(w, a.pExternalSemaphoreProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR(r, a)
{
    a.pExternalSemaphoreProperties = gd_VkExternalSemaphoreProperties(r, a.pExternalSemaphoreProperties, 2147483647);
    return a;
}
function ge_vkImportSemaphoreFdKHR(w, a)
{
    w.h(a.device);
    ge_VkImportSemaphoreFdInfoKHR(w, a.pImportSemaphoreFdInfo, 2147483647);
}
function gd_vkImportSemaphoreFdKHR(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetSemaphoreFdKHR(w, a)
{
    w.h(a.device);
    ge_VkSemaphoreGetFdInfoKHR(w, a.pGetFdInfo, 2147483647);
    w.i32(a.pFd);
}
function gd_vkGetSemaphoreFdKHR(r, a)
{
    a.pFd = r.i32();
    a.ret = r.i32();
    return a;
}
function ge_vkCreateDescriptorUpdateTemplateKHR(w, a)
{
    w.h(a.device);
    ge_VkDescriptorUpdateTemplateCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pDescriptorUpdateTemplate);
}
function gd_vkCreateDescriptorUpdateTemplateKHR(r, a)
{
    a.pDescriptorUpdateTemplate = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyDescriptorUpdateTemplateKHR(w, a)
{
    w.h(a.device);
    w.h(a.descriptorUpdateTemplate);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkUpdateDescriptorSetWithTemplateKHR(w, a)
{
    w.h(a.device);
    w.h(a.descriptorSet);
    w.h(a.descriptorUpdateTemplate);
    w.ptr(a.pData != null);
    if(a.pData != null)
    {
        w.void(a.pData);
    }
}
function ge_vkCreateRenderPass2KHR(w, a)
{
    w.h(a.device);
    ge_VkRenderPassCreateInfo2(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pRenderPass);
}
function gd_vkCreateRenderPass2KHR(r, a)
{
    a.pRenderPass = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBeginRenderPass2KHR(w, a)
{
    ge_VkRenderPassBeginInfo(w, a.pRenderPassBegin, 2147483647);
    ge_VkSubpassBeginInfo(w, a.pSubpassBeginInfo, 2147483647);
}
function ge_vkCmdNextSubpass2KHR(w, a)
{
    ge_VkSubpassBeginInfo(w, a.pSubpassBeginInfo, 2147483647);
    ge_VkSubpassEndInfo(w, a.pSubpassEndInfo, 2147483647);
}
function ge_vkCmdEndRenderPass2KHR(w, a)
{
    ge_VkSubpassEndInfo(w, a.pSubpassEndInfo, 2147483647);
}
function ge_vkGetPhysicalDeviceExternalFencePropertiesKHR(w, a)
{
    w.h(a.physicalDevice);
    ge_VkPhysicalDeviceExternalFenceInfo(w, a.pExternalFenceInfo, 2147483647);
    ge_VkExternalFenceProperties(w, a.pExternalFenceProperties, 2147483647);
}
function gd_vkGetPhysicalDeviceExternalFencePropertiesKHR(r, a)
{
    a.pExternalFenceProperties = gd_VkExternalFenceProperties(r, a.pExternalFenceProperties, 2147483647);
    return a;
}
function ge_vkImportFenceFdKHR(w, a)
{
    w.h(a.device);
    ge_VkImportFenceFdInfoKHR(w, a.pImportFenceFdInfo, 2147483647);
}
function gd_vkImportFenceFdKHR(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetFenceFdKHR(w, a)
{
    w.h(a.device);
    ge_VkFenceGetFdInfoKHR(w, a.pGetFdInfo, 2147483647);
    w.i32(a.pFd);
}
function gd_vkGetFenceFdKHR(r, a)
{
    a.pFd = r.i32();
    a.ret = r.i32();
    return a;
}
function ge_vkGetImageMemoryRequirements2KHR(w, a)
{
    w.h(a.device);
    ge_VkImageMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetImageMemoryRequirements2KHR(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetBufferMemoryRequirements2KHR(w, a)
{
    w.h(a.device);
    ge_VkBufferMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetBufferMemoryRequirements2KHR(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetImageSparseMemoryRequirements2KHR(w, a)
{
    w.h(a.device);
    ge_VkImageSparseMemoryRequirementsInfo2(w, a.pInfo, 2147483647);
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            ge_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
        }
    }
}
function gd_vkGetImageSparseMemoryRequirements2KHR(r, a)
{
    r.ptr();
    if(a.pSparseMemoryRequirementCount != null)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    r.ptr();
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                a.pSparseMemoryRequirements[i] = gd_VkSparseImageMemoryRequirements2(r, a.pSparseMemoryRequirements[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkCreateSamplerYcbcrConversionKHR(w, a)
{
    w.h(a.device);
    ge_VkSamplerYcbcrConversionCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pYcbcrConversion);
}
function gd_vkCreateSamplerYcbcrConversionKHR(r, a)
{
    a.pYcbcrConversion = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroySamplerYcbcrConversionKHR(w, a)
{
    w.h(a.device);
    w.h(a.ycbcrConversion);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkBindBufferMemory2KHR(w, a)
{
    w.h(a.device);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindBufferMemoryInfo(w, a.pBindInfos?.[i], 2147483647);
    }
}
function gd_vkBindBufferMemory2KHR(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkBindImageMemory2KHR(w, a)
{
    w.h(a.device);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindImageMemoryInfo(w, a.pBindInfos?.[i], 2147483647);
    }
}
function gd_vkBindImageMemory2KHR(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetDescriptorSetLayoutSupportKHR(w, a)
{
    w.h(a.device);
    ge_VkDescriptorSetLayoutCreateInfo(w, a.pCreateInfo, 2147483647);
    ge_VkDescriptorSetLayoutSupport(w, a.pSupport, 2147483647);
}
function gd_vkGetDescriptorSetLayoutSupportKHR(r, a)
{
    a.pSupport = gd_VkDescriptorSetLayoutSupport(r, a.pSupport, 2147483647);
    return a;
}
function ge_vkGetBufferDeviceAddressKHR(w, a)
{
    w.h(a.device);
    ge_VkBufferDeviceAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetBufferDeviceAddressKHR(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetBufferOpaqueCaptureAddressKHR(w, a)
{
    w.h(a.device);
    ge_VkBufferDeviceAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetBufferOpaqueCaptureAddressKHR(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetDeviceMemoryOpaqueCaptureAddressKHR(w, a)
{
    w.h(a.device);
    ge_VkDeviceMemoryOpaqueCaptureAddressInfo(w, a.pInfo, 2147483647);
}
function gd_vkGetDeviceMemoryOpaqueCaptureAddressKHR(r, a)
{
    a.ret = r.u64();
    return a;
}
function ge_vkGetPipelineExecutablePropertiesKHR(w, a)
{
    w.h(a.device);
    ge_VkPipelineInfoKHR(w, a.pPipelineInfo, 2147483647);
    w.ptr(a.pExecutableCount != null);
    if(a.pExecutableCount != null)
    {
        w.u32(a.pExecutableCount);
    }
    w.ptr(a.pProperties != null);
    if(a.pProperties != null)
    {
        for(let i = 0; i < a.pExecutableCount; i++)
        {
            ge_VkPipelineExecutablePropertiesKHR(w, a.pProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPipelineExecutablePropertiesKHR(r, a)
{
    r.ptr();
    if(a.pExecutableCount != null)
    {
        a.pExecutableCount = r.u32();
    }
    r.ptr();
    if(a.pProperties != null)
    {
        if(a.pExecutableCount != null)
        {
            a.pProperties = new Array(r.count(a.pExecutableCount));
            for(let i = 0; i < a.pExecutableCount; i++)
            {
                a.pProperties[i] = gd_VkPipelineExecutablePropertiesKHR(r, a.pProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkGetPipelineExecutableStatisticsKHR(w, a)
{
    w.h(a.device);
    ge_VkPipelineExecutableInfoKHR(w, a.pExecutableInfo, 2147483647);
    w.ptr(a.pStatisticCount != null);
    if(a.pStatisticCount != null)
    {
        w.u32(a.pStatisticCount);
    }
    w.ptr(a.pStatistics != null);
    if(a.pStatistics != null)
    {
        for(let i = 0; i < a.pStatisticCount; i++)
        {
            ge_VkPipelineExecutableStatisticKHR(w, a.pStatistics?.[i], 2147483647);
        }
    }
}
function gd_vkGetPipelineExecutableStatisticsKHR(r, a)
{
    r.ptr();
    if(a.pStatisticCount != null)
    {
        a.pStatisticCount = r.u32();
    }
    r.ptr();
    if(a.pStatistics != null)
    {
        if(a.pStatisticCount != null)
        {
            a.pStatistics = new Array(r.count(a.pStatisticCount));
            for(let i = 0; i < a.pStatisticCount; i++)
            {
                a.pStatistics[i] = gd_VkPipelineExecutableStatisticKHR(r, a.pStatistics[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkGetPipelineExecutableInternalRepresentationsKHR(w, a)
{
    w.h(a.device);
    ge_VkPipelineExecutableInfoKHR(w, a.pExecutableInfo, 2147483647);
    w.ptr(a.pInternalRepresentationCount != null);
    if(a.pInternalRepresentationCount != null)
    {
        w.u32(a.pInternalRepresentationCount);
    }
    w.ptr(a.pInternalRepresentations != null);
    if(a.pInternalRepresentations != null)
    {
        for(let i = 0; i < a.pInternalRepresentationCount; i++)
        {
            ge_VkPipelineExecutableInternalRepresentationKHR(w, a.pInternalRepresentations?.[i], 2147483647);
        }
    }
}
function gd_vkGetPipelineExecutableInternalRepresentationsKHR(r, a)
{
    r.ptr();
    if(a.pInternalRepresentationCount != null)
    {
        a.pInternalRepresentationCount = r.u32();
    }
    r.ptr();
    if(a.pInternalRepresentations != null)
    {
        if(a.pInternalRepresentationCount != null)
        {
            a.pInternalRepresentations = new Array(r.count(a.pInternalRepresentationCount));
            for(let i = 0; i < a.pInternalRepresentationCount; i++)
            {
                a.pInternalRepresentations[i] = gd_VkPipelineExecutableInternalRepresentationKHR(r, a.pInternalRepresentations[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkCmdSetEvent2KHR(w, a)
{
    w.h(a.event);
    ge_VkDependencyInfo(w, a.pDependencyInfo, 2147483647);
}
function ge_vkCmdResetEvent2KHR(w, a)
{
    w.h(a.event);
    w.u64(a.stageMask);
}
function ge_vkCmdWaitEvents2KHR(w, a)
{
    w.u32(a.eventCount);
    if(a.eventCount)
    {
        for(let k = 0; k < a.eventCount; k++)
        {
            w.h(a.pEvents?.[k]);
        }
    }
    for(let i = 0; i < a.eventCount; i++)
    {
        ge_VkDependencyInfo(w, a.pDependencyInfos?.[i], 2147483647);
    }
}
function ge_vkCmdPipelineBarrier2KHR(w, a)
{
    ge_VkDependencyInfo(w, a.pDependencyInfo, 2147483647);
}
function ge_vkCmdWriteTimestamp2KHR(w, a)
{
    w.u64(a.stage);
    w.h(a.queryPool);
    w.u32(a.query);
}
function ge_vkQueueSubmit2KHR(w, a)
{
    w.h(a.queue);
    w.u32(a.submitCount);
    for(let i = 0; i < a.submitCount; i++)
    {
        ge_VkSubmitInfo2(w, a.pSubmits?.[i], 2147483647);
    }
    w.h(a.fence);
}
function gd_vkQueueSubmit2KHR(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCmdCopyBuffer2KHR(w, a)
{
    ge_VkCopyBufferInfo2(w, a.pCopyBufferInfo, 2147483647);
}
function ge_vkCmdCopyImage2KHR(w, a)
{
    ge_VkCopyImageInfo2(w, a.pCopyImageInfo, 2147483647);
}
function ge_vkCmdCopyBufferToImage2KHR(w, a)
{
    ge_VkCopyBufferToImageInfo2(w, a.pCopyBufferToImageInfo, 2147483647);
}
function ge_vkCmdCopyImageToBuffer2KHR(w, a)
{
    ge_VkCopyImageToBufferInfo2(w, a.pCopyImageToBufferInfo, 2147483647);
}
function ge_vkCmdBlitImage2KHR(w, a)
{
    ge_VkBlitImageInfo2(w, a.pBlitImageInfo, 2147483647);
}
function ge_vkCmdResolveImage2KHR(w, a)
{
    ge_VkResolveImageInfo2(w, a.pResolveImageInfo, 2147483647);
}
function ge_vkGetDeviceBufferMemoryRequirementsKHR(w, a)
{
    w.h(a.device);
    ge_VkDeviceBufferMemoryRequirements(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetDeviceBufferMemoryRequirementsKHR(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetDeviceImageMemoryRequirementsKHR(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageMemoryRequirements(w, a.pInfo, 2147483647);
    ge_VkMemoryRequirements2(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkGetDeviceImageMemoryRequirementsKHR(r, a)
{
    a.pMemoryRequirements = gd_VkMemoryRequirements2(r, a.pMemoryRequirements, 2147483647);
    return a;
}
function ge_vkGetDeviceImageSparseMemoryRequirementsKHR(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageMemoryRequirements(w, a.pInfo, 2147483647);
    w.ptr(a.pSparseMemoryRequirementCount != null);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u32(a.pSparseMemoryRequirementCount);
    }
    w.ptr(a.pSparseMemoryRequirements != null);
    if(a.pSparseMemoryRequirements != null)
    {
        for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
        {
            ge_VkSparseImageMemoryRequirements2(w, a.pSparseMemoryRequirements?.[i], 2147483647);
        }
    }
}
function gd_vkGetDeviceImageSparseMemoryRequirementsKHR(r, a)
{
    r.ptr();
    if(a.pSparseMemoryRequirementCount != null)
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    r.ptr();
    if(a.pSparseMemoryRequirements != null)
    {
        if(a.pSparseMemoryRequirementCount != null)
        {
            a.pSparseMemoryRequirements = new Array(r.count(a.pSparseMemoryRequirementCount));
            for(let i = 0; i < a.pSparseMemoryRequirementCount; i++)
            {
                a.pSparseMemoryRequirements[i] = gd_VkSparseImageMemoryRequirements2(r, a.pSparseMemoryRequirements[i], 2147483647);
            }
        }
    }
    return a;
}
function ge_vkCmdBindIndexBuffer2KHR(w, a)
{
    w.h(a.buffer);
    w.u64(a.offset);
    w.u64(a.size);
    w.i32(a.indexType);
}
function ge_vkGetRenderingAreaGranularityKHR(w, a)
{
    w.h(a.device);
    ge_VkRenderingAreaInfo(w, a.pRenderingAreaInfo, 2147483647);
    ge_VkExtent2D(w, a.pGranularity, 2147483647);
}
function gd_vkGetRenderingAreaGranularityKHR(r, a)
{
    a.pGranularity = gd_VkExtent2D(r, a.pGranularity, 2147483647);
    return a;
}
function ge_vkGetDeviceImageSubresourceLayoutKHR(w, a)
{
    w.h(a.device);
    ge_VkDeviceImageSubresourceInfo(w, a.pInfo, 2147483647);
    ge_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function gd_vkGetDeviceImageSubresourceLayoutKHR(r, a)
{
    a.pLayout = gd_VkSubresourceLayout2(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkGetImageSubresourceLayout2KHR(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkImageSubresource2(w, a.pSubresource, 2147483647);
    ge_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function gd_vkGetImageSubresourceLayout2KHR(r, a)
{
    a.pLayout = gd_VkSubresourceLayout2(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkCmdSetLineStippleKHR(w, a)
{
    w.u32(a.lineStippleFactor);
    w.u16(a.lineStipplePattern);
}
function ge_vkGetSwapchainGrallocUsageANDROID(w, a)
{
    w.h(a.device);
    w.i32(a.format);
    w.u32(a.imageUsage);
    w.i32(a.grallocUsage);
}
function gd_vkGetSwapchainGrallocUsageANDROID(r, a)
{
    a.grallocUsage = r.i32();
    a.ret = r.i32();
    return a;
}
function ge_vkAcquireImageANDROID(w, a)
{
    w.h(a.device);
    w.h(a.image);
    w.i32(a.nativeFenceFd);
    w.h(a.semaphore);
    w.h(a.fence);
}
function gd_vkAcquireImageANDROID(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkQueueSignalReleaseImageANDROID(w, a)
{
    w.h(a.queue);
    w.u32(a.waitSemaphoreCount);
    w.ptr(a.pWaitSemaphores != null);
    if(a.pWaitSemaphores != null)
    {
        if(a.waitSemaphoreCount)
        {
            for(let k = 0; k < a.waitSemaphoreCount; k++)
            {
                w.h(a.pWaitSemaphores?.[k]);
            }
        }
    }
    w.h(a.image);
    w.i32(a.pNativeFenceFd);
}
function gd_vkQueueSignalReleaseImageANDROID(r, a)
{
    a.pNativeFenceFd = r.i32();
    a.ret = r.i32();
    return a;
}
function ge_vkGetSwapchainGrallocUsage2ANDROID(w, a)
{
    w.h(a.device);
    w.i32(a.format);
    w.u32(a.imageUsage);
    w.u32(a.swapchainImageUsage);
    w.u64(a.grallocConsumerUsage);
    w.u64(a.grallocProducerUsage);
}
function gd_vkGetSwapchainGrallocUsage2ANDROID(r, a)
{
    a.grallocConsumerUsage = r.u64();
    a.grallocProducerUsage = r.u64();
    a.ret = r.i32();
    return a;
}
function ge_vkCmdBindTransformFeedbackBuffersEXT(w, a)
{
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    if(a.bindingCount)
    {
        for(let k = 0; k < a.bindingCount; k++)
        {
            w.h(a.pBuffers?.[k]);
        }
    }
    if((a.bindingCount > 0))
    {
        w.u64s(a.pOffsets, a.bindingCount);
    }
    w.ptr(a.pSizes != null);
    if(a.pSizes != null)
    {
        if((a.bindingCount > 0))
        {
            w.u64s(a.pSizes, a.bindingCount);
        }
    }
}
function ge_vkCmdBeginTransformFeedbackEXT(w, a)
{
    w.u32(a.firstCounterBuffer);
    w.u32(a.counterBufferCount);
    w.ptr(a.pCounterBuffers != null);
    if(a.pCounterBuffers != null)
    {
        if(a.counterBufferCount)
        {
            for(let k = 0; k < a.counterBufferCount; k++)
            {
                w.h(a.pCounterBuffers?.[k]);
            }
        }
    }
    w.ptr(a.pCounterBufferOffsets != null);
    if(a.pCounterBufferOffsets != null)
    {
        if((a.counterBufferCount > 0))
        {
            w.u64s(a.pCounterBufferOffsets, a.counterBufferCount);
        }
    }
}
function ge_vkCmdEndTransformFeedbackEXT(w, a)
{
    w.u32(a.firstCounterBuffer);
    w.u32(a.counterBufferCount);
    w.ptr(a.pCounterBuffers != null);
    if(a.pCounterBuffers != null)
    {
        if(a.counterBufferCount)
        {
            for(let k = 0; k < a.counterBufferCount; k++)
            {
                w.h(a.pCounterBuffers?.[k]);
            }
        }
    }
    w.ptr(a.pCounterBufferOffsets != null);
    if(a.pCounterBufferOffsets != null)
    {
        if((a.counterBufferCount > 0))
        {
            w.u64s(a.pCounterBufferOffsets, a.counterBufferCount);
        }
    }
}
function ge_vkCmdBeginQueryIndexedEXT(w, a)
{
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.flags);
    w.u32(a.index);
}
function ge_vkCmdEndQueryIndexedEXT(w, a)
{
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.index);
}
function ge_vkCmdDrawIndirectByteCountEXT(w, a)
{
    w.u32(a.instanceCount);
    w.u32(a.firstInstance);
    w.h(a.counterBuffer);
    w.u64(a.counterBufferOffset);
    w.u32(a.counterOffset);
    w.u32(a.vertexStride);
}
function ge_vkGetImageDrmFormatModifierPropertiesEXT(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkImageDrmFormatModifierPropertiesEXT(w, a.pProperties, 2147483647);
}
function gd_vkGetImageDrmFormatModifierPropertiesEXT(r, a)
{
    a.pProperties = gd_VkImageDrmFormatModifierPropertiesEXT(r, a.pProperties, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkGetPhysicalDeviceToolPropertiesEXT(w, a)
{
    w.h(a.physicalDevice);
    w.ptr(a.pToolCount != null);
    if(a.pToolCount != null)
    {
        w.u32(a.pToolCount);
    }
    w.ptr(a.pToolProperties != null);
    if(a.pToolProperties != null)
    {
        for(let i = 0; i < a.pToolCount; i++)
        {
            ge_VkPhysicalDeviceToolProperties(w, a.pToolProperties?.[i], 2147483647);
        }
    }
}
function gd_vkGetPhysicalDeviceToolPropertiesEXT(r, a)
{
    r.ptr();
    if(a.pToolCount != null)
    {
        a.pToolCount = r.u32();
    }
    r.ptr();
    if(a.pToolProperties != null)
    {
        if(a.pToolCount != null)
        {
            a.pToolProperties = new Array(r.count(a.pToolCount));
            for(let i = 0; i < a.pToolCount; i++)
            {
                a.pToolProperties[i] = gd_VkPhysicalDeviceToolProperties(r, a.pToolProperties[i], 2147483647);
            }
        }
    }
    a.ret = r.i32();
    return a;
}
function ge_vkCmdSetLineStippleEXT(w, a)
{
    w.u32(a.lineStippleFactor);
    w.u16(a.lineStipplePattern);
}
function ge_vkCmdSetCullModeEXT(w, a)
{
    w.u32(a.cullMode);
}
function ge_vkCmdSetFrontFaceEXT(w, a)
{
    w.i32(a.frontFace);
}
function ge_vkCmdSetPrimitiveTopologyEXT(w, a)
{
    w.i32(a.primitiveTopology);
}
function ge_vkCmdSetViewportWithCountEXT(w, a)
{
    w.u32(a.viewportCount);
    for(let i = 0; i < a.viewportCount; i++)
    {
        ge_VkViewport(w, a.pViewports?.[i], 2147483647);
    }
}
function ge_vkCmdSetScissorWithCountEXT(w, a)
{
    w.u32(a.scissorCount);
    for(let i = 0; i < a.scissorCount; i++)
    {
        ge_VkRect2D(w, a.pScissors?.[i], 2147483647);
    }
}
function ge_vkCmdBindVertexBuffers2EXT(w, a)
{
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    w.ptr(a.pBuffers != null);
    if(a.pBuffers != null)
    {
        if(a.bindingCount)
        {
            for(let k = 0; k < a.bindingCount; k++)
            {
                w.h(a.pBuffers?.[k]);
            }
        }
    }
    if((a.bindingCount > 0))
    {
        w.u64s(a.pOffsets, a.bindingCount);
    }
    w.ptr(a.pSizes != null);
    if(a.pSizes != null)
    {
        if((a.bindingCount > 0))
        {
            w.u64s(a.pSizes, a.bindingCount);
        }
    }
    w.ptr(a.pStrides != null);
    if(a.pStrides != null)
    {
        if((a.bindingCount > 0))
        {
            w.u64s(a.pStrides, a.bindingCount);
        }
    }
}
function ge_vkCmdSetDepthTestEnableEXT(w, a)
{
    w.u32(a.depthTestEnable);
}
function ge_vkCmdSetDepthWriteEnableEXT(w, a)
{
    w.u32(a.depthWriteEnable);
}
function ge_vkCmdSetDepthCompareOpEXT(w, a)
{
    w.i32(a.depthCompareOp);
}
function ge_vkCmdSetDepthBoundsTestEnableEXT(w, a)
{
    w.u32(a.depthBoundsTestEnable);
}
function ge_vkCmdSetStencilTestEnableEXT(w, a)
{
    w.u32(a.stencilTestEnable);
}
function ge_vkCmdSetStencilOpEXT(w, a)
{
    w.u32(a.faceMask);
    w.i32(a.failOp);
    w.i32(a.passOp);
    w.i32(a.depthFailOp);
    w.i32(a.compareOp);
}
function ge_vkCopyMemoryToImageEXT(w, a)
{
    w.h(a.device);
    ge_VkCopyMemoryToImageInfo(w, a.pCopyMemoryToImageInfo, 2147483647);
}
function gd_vkCopyMemoryToImageEXT(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCopyImageToMemoryEXT(w, a)
{
    w.h(a.device);
    ge_VkCopyImageToMemoryInfo(w, a.pCopyImageToMemoryInfo, 2147483647);
}
function gd_vkCopyImageToMemoryEXT(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkCopyImageToImageEXT(w, a)
{
    w.h(a.device);
    ge_VkCopyImageToImageInfo(w, a.pCopyImageToImageInfo, 2147483647);
}
function gd_vkCopyImageToImageEXT(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkTransitionImageLayoutEXT(w, a)
{
    w.h(a.device);
    w.u32(a.transitionCount);
    for(let i = 0; i < a.transitionCount; i++)
    {
        ge_VkHostImageLayoutTransitionInfo(w, a.pTransitions?.[i], 2147483647);
    }
}
function gd_vkTransitionImageLayoutEXT(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetImageSubresourceLayout2EXT(w, a)
{
    w.h(a.device);
    w.h(a.image);
    ge_VkImageSubresource2(w, a.pSubresource, 2147483647);
    ge_VkSubresourceLayout2(w, a.pLayout, 2147483647);
}
function gd_vkGetImageSubresourceLayout2EXT(r, a)
{
    a.pLayout = gd_VkSubresourceLayout2(r, a.pLayout, 2147483647);
    return a;
}
function ge_vkCreatePrivateDataSlotEXT(w, a)
{
    w.h(a.device);
    ge_VkPrivateDataSlotCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pPrivateDataSlot);
}
function gd_vkCreatePrivateDataSlotEXT(r, a)
{
    a.pPrivateDataSlot = r.h();
    a.ret = r.i32();
    return a;
}
function ge_vkDestroyPrivateDataSlotEXT(w, a)
{
    w.h(a.device);
    w.h(a.privateDataSlot);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function ge_vkSetPrivateDataEXT(w, a)
{
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.data);
}
function gd_vkSetPrivateDataEXT(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkGetPrivateDataEXT(w, a)
{
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.pData);
}
function gd_vkGetPrivateDataEXT(r, a)
{
    a.pData = r.u64();
    return a;
}
function ge_vkCmdSetPatchControlPointsEXT(w, a)
{
    w.u32(a.patchControlPoints);
}
function ge_vkCmdSetRasterizerDiscardEnableEXT(w, a)
{
    w.u32(a.rasterizerDiscardEnable);
}
function ge_vkCmdSetDepthBiasEnableEXT(w, a)
{
    w.u32(a.depthBiasEnable);
}
function ge_vkCmdSetLogicOpEXT(w, a)
{
    w.i32(a.logicOp);
}
function ge_vkCmdSetPrimitiveRestartEnableEXT(w, a)
{
    w.u32(a.primitiveRestartEnable);
}
function ge_vkCmdSetColorWriteEnableEXT(w, a)
{
    w.u32(a.attachmentCount);
    if((a.attachmentCount > 0))
    {
        w.u32s(a.pColorWriteEnables, a.attachmentCount);
    }
}
function ge_vkMapMemoryIntoAddressSpaceGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.memory);
    w.ptr(a.pAddress != null);
    if(a.pAddress != null)
    {
        w.u64(a.pAddress);
    }
}
function gd_vkMapMemoryIntoAddressSpaceGOOGLE(r, a)
{
    r.ptr();
    if(a.pAddress != null)
    {
        a.pAddress = r.u64();
    }
    a.ret = r.i32();
    return a;
}
function ge_vkUpdateDescriptorSetWithTemplateSizedGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.descriptorSet);
    w.h(a.descriptorUpdateTemplate);
    w.u32(a.imageInfoCount);
    w.u32(a.bufferInfoCount);
    w.u32(a.bufferViewCount);
    w.ptr(a.pImageInfoEntryIndices != null);
    if(a.pImageInfoEntryIndices != null)
    {
        if((a.imageInfoCount > 0))
        {
            w.u32s(a.pImageInfoEntryIndices, a.imageInfoCount);
        }
    }
    w.ptr(a.pBufferInfoEntryIndices != null);
    if(a.pBufferInfoEntryIndices != null)
    {
        if((a.bufferInfoCount > 0))
        {
            w.u32s(a.pBufferInfoEntryIndices, a.bufferInfoCount);
        }
    }
    w.ptr(a.pBufferViewEntryIndices != null);
    if(a.pBufferViewEntryIndices != null)
    {
        if((a.bufferViewCount > 0))
        {
            w.u32s(a.pBufferViewEntryIndices, a.bufferViewCount);
        }
    }
    w.ptr(a.pImageInfos != null);
    if(a.pImageInfos != null)
    {
        for(let i = 0; i < a.imageInfoCount; i++)
        {
            ge_VkDescriptorImageInfo(w, a.pImageInfos?.[i], 2147483647);
        }
    }
    w.ptr(a.pBufferInfos != null);
    if(a.pBufferInfos != null)
    {
        for(let i = 0; i < a.bufferInfoCount; i++)
        {
            ge_VkDescriptorBufferInfo(w, a.pBufferInfos?.[i], 2147483647);
        }
    }
    w.ptr(a.pBufferViews != null);
    if(a.pBufferViews != null)
    {
        if(a.bufferViewCount)
        {
            for(let k = 0; k < a.bufferViewCount; k++)
            {
                w.h(a.pBufferViews?.[k]);
            }
        }
    }
}
function ge_vkBeginCommandBufferAsyncGOOGLE(w, a)
{
    ge_VkCommandBufferBeginInfo(w, a.pBeginInfo, 2147483647);
}
function ge_vkEndCommandBufferAsyncGOOGLE(w, a)
{
}
function ge_vkResetCommandBufferAsyncGOOGLE(w, a)
{
    w.u32(a.flags);
}
function ge_vkCommandBufferHostSyncGOOGLE(w, a)
{
    w.u32(a.needHostSync);
    w.u32(a.sequenceNumber);
}
function ge_vkCreateImageWithRequirementsGOOGLE(w, a)
{
    w.h(a.device);
    ge_VkImageCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pImage);
    ge_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkCreateImageWithRequirementsGOOGLE(r, a)
{
    a.pImage = r.h();
    a.pMemoryRequirements = gd_VkMemoryRequirements(r, a.pMemoryRequirements, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkCreateBufferWithRequirementsGOOGLE(w, a)
{
    w.h(a.device);
    ge_VkBufferCreateInfo(w, a.pCreateInfo, 2147483647);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
    w.h(a.pBuffer);
    ge_VkMemoryRequirements(w, a.pMemoryRequirements, 2147483647);
}
function gd_vkCreateBufferWithRequirementsGOOGLE(r, a)
{
    a.pBuffer = r.h();
    a.pMemoryRequirements = gd_VkMemoryRequirements(r, a.pMemoryRequirements, 2147483647);
    a.ret = r.i32();
    return a;
}
function ge_vkGetMemoryHostAddressInfoGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.memory);
    w.ptr(a.pAddress != null);
    if(a.pAddress != null)
    {
        w.u64(a.pAddress);
    }
    w.ptr(a.pSize != null);
    if(a.pSize != null)
    {
        w.u64(a.pSize);
    }
    w.ptr(a.pHostmemId != null);
    if(a.pHostmemId != null)
    {
        w.u64(a.pHostmemId);
    }
}
function gd_vkGetMemoryHostAddressInfoGOOGLE(r, a)
{
    r.ptr();
    if(a.pAddress != null)
    {
        a.pAddress = r.u64();
    }
    r.ptr();
    if(a.pSize != null)
    {
        a.pSize = r.u64();
    }
    r.ptr();
    if(a.pHostmemId != null)
    {
        a.pHostmemId = r.u64();
    }
    a.ret = r.i32();
    return a;
}
function ge_vkFreeMemorySyncGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.memory);
    w.ptr(a.pAllocator != null);
    if(a.pAllocator != null)
    {
        ge_VkAllocationCallbacks(w, a.pAllocator, 2147483647);
    }
}
function gd_vkFreeMemorySyncGOOGLE(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkQueueHostSyncGOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.needHostSync);
    w.u32(a.sequenceNumber);
}
function ge_vkQueueSubmitAsyncGOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.submitCount);
    for(let i = 0; i < a.submitCount; i++)
    {
        ge_VkSubmitInfo(w, a.pSubmits?.[i], 2147483647);
    }
    w.h(a.fence);
}
function ge_vkQueueWaitIdleAsyncGOOGLE(w, a)
{
    w.h(a.queue);
}
function ge_vkQueueBindSparseAsyncGOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.bindInfoCount);
    for(let i = 0; i < a.bindInfoCount; i++)
    {
        ge_VkBindSparseInfo(w, a.pBindInfo?.[i], 2147483647);
    }
    w.h(a.fence);
}
function ge_vkGetLinearImageLayoutGOOGLE(w, a)
{
    w.h(a.device);
    w.i32(a.format);
    w.u64(a.pOffset);
    w.u64(a.pRowPitchAlignment);
}
function gd_vkGetLinearImageLayoutGOOGLE(r, a)
{
    a.pOffset = r.u64();
    a.pRowPitchAlignment = r.u64();
    return a;
}
function ge_vkGetLinearImageLayout2GOOGLE(w, a)
{
    w.h(a.device);
    ge_VkImageCreateInfo(w, a.pCreateInfo, 2147483647);
    w.u64(a.pOffset);
    w.u64(a.pRowPitchAlignment);
}
function gd_vkGetLinearImageLayout2GOOGLE(r, a)
{
    a.pOffset = r.u64();
    a.pRowPitchAlignment = r.u64();
    return a;
}
function ge_vkQueueFlushCommandsGOOGLE(w, a)
{
    w.h(a.queue);
    w.h(a.commandBuffer);
    w.u64(a.dataSize);
    w.bytes_of(a.pData, a.dataSize);
}
function ge_vkQueueCommitDescriptorSetUpdatesGOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.descriptorPoolCount);
    if(a.descriptorPoolCount)
    {
        for(let k = 0; k < a.descriptorPoolCount; k++)
        {
            w.h(a.pDescriptorPools?.[k]);
        }
    }
    w.u32(a.descriptorSetCount);
    if(a.descriptorSetCount)
    {
        for(let k = 0; k < a.descriptorSetCount; k++)
        {
            w.h(a.pSetLayouts?.[k]);
        }
    }
    if((a.descriptorSetCount > 0))
    {
        w.u64s(a.pDescriptorSetPoolIds, a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        w.u32s(a.pDescriptorSetWhichPool, a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        w.u32s(a.pDescriptorSetPendingAllocation, a.descriptorSetCount);
    }
    if((a.descriptorSetCount > 0))
    {
        w.u32s(a.pDescriptorWriteStartingIndices, a.descriptorSetCount);
    }
    w.u32(a.pendingDescriptorWriteCount);
    for(let i = 0; i < a.pendingDescriptorWriteCount; i++)
    {
        ge_VkWriteDescriptorSet(w, a.pPendingDescriptorWrites?.[i], 2147483647);
    }
}
function ge_vkCollectDescriptorPoolIdsGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.descriptorPool);
    w.u32(a.pPoolIdCount);
    w.ptr(a.pPoolIds != null);
    if(a.pPoolIds != null)
    {
        if((a.pPoolIdCount > 0))
        {
            w.u64s(a.pPoolIds, a.pPoolIdCount);
        }
    }
}
function gd_vkCollectDescriptorPoolIdsGOOGLE(r, a)
{
    a.pPoolIdCount = r.u32();
    r.ptr();
    if(a.pPoolIds != null)
    {
        a.pPoolIds = r.u64s(a.pPoolIdCount);
    }
    return a;
}
function ge_vkQueueSignalReleaseImageANDROIDAsyncGOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.waitSemaphoreCount);
    w.ptr(a.pWaitSemaphores != null);
    if(a.pWaitSemaphores != null)
    {
        if(a.waitSemaphoreCount)
        {
            for(let k = 0; k < a.waitSemaphoreCount; k++)
            {
                w.h(a.pWaitSemaphores?.[k]);
            }
        }
    }
    w.h(a.image);
}
function ge_vkQueueFlushCommandsFromAuxMemoryGOOGLE(w, a)
{
    w.h(a.queue);
    w.h(a.commandBuffer);
    w.h(a.deviceMemory);
    w.u64(a.dataOffset);
    w.u64(a.dataSize);
}
function ge_vkGetBlobGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.memory);
}
function gd_vkGetBlobGOOGLE(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkUpdateDescriptorSetWithTemplateSized2GOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.descriptorSet);
    w.h(a.descriptorUpdateTemplate);
    w.u32(a.imageInfoCount);
    w.u32(a.bufferInfoCount);
    w.u32(a.bufferViewCount);
    w.u32(a.inlineUniformBlockCount);
    w.ptr(a.pImageInfoEntryIndices != null);
    if(a.pImageInfoEntryIndices != null)
    {
        if((a.imageInfoCount > 0))
        {
            w.u32s(a.pImageInfoEntryIndices, a.imageInfoCount);
        }
    }
    w.ptr(a.pBufferInfoEntryIndices != null);
    if(a.pBufferInfoEntryIndices != null)
    {
        if((a.bufferInfoCount > 0))
        {
            w.u32s(a.pBufferInfoEntryIndices, a.bufferInfoCount);
        }
    }
    w.ptr(a.pBufferViewEntryIndices != null);
    if(a.pBufferViewEntryIndices != null)
    {
        if((a.bufferViewCount > 0))
        {
            w.u32s(a.pBufferViewEntryIndices, a.bufferViewCount);
        }
    }
    w.ptr(a.pImageInfos != null);
    if(a.pImageInfos != null)
    {
        for(let i = 0; i < a.imageInfoCount; i++)
        {
            ge_VkDescriptorImageInfo(w, a.pImageInfos?.[i], 2147483647);
        }
    }
    w.ptr(a.pBufferInfos != null);
    if(a.pBufferInfos != null)
    {
        for(let i = 0; i < a.bufferInfoCount; i++)
        {
            ge_VkDescriptorBufferInfo(w, a.pBufferInfos?.[i], 2147483647);
        }
    }
    w.ptr(a.pBufferViews != null);
    if(a.pBufferViews != null)
    {
        if(a.bufferViewCount)
        {
            for(let k = 0; k < a.bufferViewCount; k++)
            {
                w.h(a.pBufferViews?.[k]);
            }
        }
    }
    w.ptr(a.pInlineUniformBlockData != null);
    if(a.pInlineUniformBlockData != null)
    {
        if((a.inlineUniformBlockCount > 0))
        {
            w.u8s(a.pInlineUniformBlockData, a.inlineUniformBlockCount);
        }
    }
}
function ge_vkQueueSubmitAsync2GOOGLE(w, a)
{
    w.h(a.queue);
    w.u32(a.submitCount);
    for(let i = 0; i < a.submitCount; i++)
    {
        ge_VkSubmitInfo2(w, a.pSubmits?.[i], 2147483647);
    }
    w.h(a.fence);
}
function ge_vkGetSemaphoreGOOGLE(w, a)
{
    w.h(a.device);
    w.h(a.semaphore);
    w.u64(a.syncId);
}
function gd_vkGetSemaphoreGOOGLE(r, a)
{
    a.ret = r.i32();
    return a;
}
function ge_vkTraceAsyncGOOGLE(w, a)
{
    w.u64(a.id);
}

/** the commands by name: [opcode, encode the request, decode the reply (or null), in a command buffer's stream] */
export const GUEST_COMMANDS = {
    vkCreateInstance: [20000, ge_vkCreateInstance, gd_vkCreateInstance, 0],
    vkDestroyInstance: [20001, ge_vkDestroyInstance, null, 0],
    vkEnumeratePhysicalDevices: [20002, ge_vkEnumeratePhysicalDevices, gd_vkEnumeratePhysicalDevices, 0],
    vkGetPhysicalDeviceFeatures: [20003, ge_vkGetPhysicalDeviceFeatures, gd_vkGetPhysicalDeviceFeatures, 0],
    vkGetPhysicalDeviceFormatProperties: [20004, ge_vkGetPhysicalDeviceFormatProperties, gd_vkGetPhysicalDeviceFormatProperties, 0],
    vkGetPhysicalDeviceImageFormatProperties: [20005, ge_vkGetPhysicalDeviceImageFormatProperties, gd_vkGetPhysicalDeviceImageFormatProperties, 0],
    vkGetPhysicalDeviceProperties: [20006, ge_vkGetPhysicalDeviceProperties, gd_vkGetPhysicalDeviceProperties, 0],
    vkGetPhysicalDeviceQueueFamilyProperties: [20007, ge_vkGetPhysicalDeviceQueueFamilyProperties, gd_vkGetPhysicalDeviceQueueFamilyProperties, 0],
    vkGetPhysicalDeviceMemoryProperties: [20008, ge_vkGetPhysicalDeviceMemoryProperties, gd_vkGetPhysicalDeviceMemoryProperties, 0],
    vkGetInstanceProcAddr: [20009, ge_vkGetInstanceProcAddr, gd_vkGetInstanceProcAddr, 0],
    vkGetDeviceProcAddr: [20010, ge_vkGetDeviceProcAddr, gd_vkGetDeviceProcAddr, 0],
    vkCreateDevice: [20011, ge_vkCreateDevice, gd_vkCreateDevice, 0],
    vkDestroyDevice: [20012, ge_vkDestroyDevice, null, 0],
    vkEnumerateInstanceExtensionProperties: [20013, ge_vkEnumerateInstanceExtensionProperties, gd_vkEnumerateInstanceExtensionProperties, 0],
    vkEnumerateDeviceExtensionProperties: [20014, ge_vkEnumerateDeviceExtensionProperties, gd_vkEnumerateDeviceExtensionProperties, 0],
    vkEnumerateInstanceLayerProperties: [20015, ge_vkEnumerateInstanceLayerProperties, gd_vkEnumerateInstanceLayerProperties, 0],
    vkEnumerateDeviceLayerProperties: [20016, ge_vkEnumerateDeviceLayerProperties, gd_vkEnumerateDeviceLayerProperties, 0],
    vkGetDeviceQueue: [20017, ge_vkGetDeviceQueue, gd_vkGetDeviceQueue, 0],
    vkQueueSubmit: [20018, ge_vkQueueSubmit, gd_vkQueueSubmit, 0],
    vkQueueWaitIdle: [20019, ge_vkQueueWaitIdle, gd_vkQueueWaitIdle, 0],
    vkDeviceWaitIdle: [20020, ge_vkDeviceWaitIdle, gd_vkDeviceWaitIdle, 0],
    vkAllocateMemory: [20021, ge_vkAllocateMemory, gd_vkAllocateMemory, 0],
    vkFreeMemory: [20022, ge_vkFreeMemory, null, 0],
    vkFlushMappedMemoryRanges: [20025, ge_vkFlushMappedMemoryRanges, gd_vkFlushMappedMemoryRanges, 0],
    vkInvalidateMappedMemoryRanges: [20026, ge_vkInvalidateMappedMemoryRanges, gd_vkInvalidateMappedMemoryRanges, 0],
    vkGetDeviceMemoryCommitment: [20027, ge_vkGetDeviceMemoryCommitment, gd_vkGetDeviceMemoryCommitment, 0],
    vkBindBufferMemory: [20028, ge_vkBindBufferMemory, gd_vkBindBufferMemory, 0],
    vkBindImageMemory: [20029, ge_vkBindImageMemory, gd_vkBindImageMemory, 0],
    vkGetBufferMemoryRequirements: [20030, ge_vkGetBufferMemoryRequirements, gd_vkGetBufferMemoryRequirements, 0],
    vkGetImageMemoryRequirements: [20031, ge_vkGetImageMemoryRequirements, gd_vkGetImageMemoryRequirements, 0],
    vkGetImageSparseMemoryRequirements: [20032, ge_vkGetImageSparseMemoryRequirements, gd_vkGetImageSparseMemoryRequirements, 0],
    vkGetPhysicalDeviceSparseImageFormatProperties: [20033, ge_vkGetPhysicalDeviceSparseImageFormatProperties, gd_vkGetPhysicalDeviceSparseImageFormatProperties, 0],
    vkQueueBindSparse: [20034, ge_vkQueueBindSparse, gd_vkQueueBindSparse, 0],
    vkCreateFence: [20035, ge_vkCreateFence, gd_vkCreateFence, 0],
    vkDestroyFence: [20036, ge_vkDestroyFence, null, 0],
    vkResetFences: [20037, ge_vkResetFences, gd_vkResetFences, 0],
    vkGetFenceStatus: [20038, ge_vkGetFenceStatus, gd_vkGetFenceStatus, 0],
    vkWaitForFences: [20039, ge_vkWaitForFences, gd_vkWaitForFences, 0],
    vkCreateSemaphore: [20040, ge_vkCreateSemaphore, gd_vkCreateSemaphore, 0],
    vkDestroySemaphore: [20041, ge_vkDestroySemaphore, null, 0],
    vkCreateEvent: [20042, ge_vkCreateEvent, gd_vkCreateEvent, 0],
    vkDestroyEvent: [20043, ge_vkDestroyEvent, null, 0],
    vkGetEventStatus: [20044, ge_vkGetEventStatus, gd_vkGetEventStatus, 0],
    vkSetEvent: [20045, ge_vkSetEvent, gd_vkSetEvent, 0],
    vkResetEvent: [20046, ge_vkResetEvent, gd_vkResetEvent, 0],
    vkCreateQueryPool: [20047, ge_vkCreateQueryPool, gd_vkCreateQueryPool, 0],
    vkDestroyQueryPool: [20048, ge_vkDestroyQueryPool, null, 0],
    vkGetQueryPoolResults: [20049, ge_vkGetQueryPoolResults, gd_vkGetQueryPoolResults, 0],
    vkCreateBuffer: [20050, ge_vkCreateBuffer, gd_vkCreateBuffer, 0],
    vkDestroyBuffer: [20051, ge_vkDestroyBuffer, null, 0],
    vkCreateBufferView: [20052, ge_vkCreateBufferView, gd_vkCreateBufferView, 0],
    vkDestroyBufferView: [20053, ge_vkDestroyBufferView, null, 0],
    vkCreateImage: [20054, ge_vkCreateImage, gd_vkCreateImage, 0],
    vkDestroyImage: [20055, ge_vkDestroyImage, null, 0],
    vkGetImageSubresourceLayout: [20056, ge_vkGetImageSubresourceLayout, gd_vkGetImageSubresourceLayout, 0],
    vkCreateImageView: [20057, ge_vkCreateImageView, gd_vkCreateImageView, 0],
    vkDestroyImageView: [20058, ge_vkDestroyImageView, null, 0],
    vkCreateShaderModule: [20059, ge_vkCreateShaderModule, gd_vkCreateShaderModule, 0],
    vkDestroyShaderModule: [20060, ge_vkDestroyShaderModule, null, 0],
    vkCreatePipelineCache: [20061, ge_vkCreatePipelineCache, gd_vkCreatePipelineCache, 0],
    vkDestroyPipelineCache: [20062, ge_vkDestroyPipelineCache, null, 0],
    vkGetPipelineCacheData: [20063, ge_vkGetPipelineCacheData, gd_vkGetPipelineCacheData, 0],
    vkMergePipelineCaches: [20064, ge_vkMergePipelineCaches, gd_vkMergePipelineCaches, 0],
    vkCreateGraphicsPipelines: [20065, ge_vkCreateGraphicsPipelines, gd_vkCreateGraphicsPipelines, 0],
    vkCreateComputePipelines: [20066, ge_vkCreateComputePipelines, gd_vkCreateComputePipelines, 0],
    vkDestroyPipeline: [20067, ge_vkDestroyPipeline, null, 0],
    vkCreatePipelineLayout: [20068, ge_vkCreatePipelineLayout, gd_vkCreatePipelineLayout, 0],
    vkDestroyPipelineLayout: [20069, ge_vkDestroyPipelineLayout, null, 0],
    vkCreateSampler: [20070, ge_vkCreateSampler, gd_vkCreateSampler, 0],
    vkDestroySampler: [20071, ge_vkDestroySampler, null, 0],
    vkCreateDescriptorSetLayout: [20072, ge_vkCreateDescriptorSetLayout, gd_vkCreateDescriptorSetLayout, 0],
    vkDestroyDescriptorSetLayout: [20073, ge_vkDestroyDescriptorSetLayout, null, 0],
    vkCreateDescriptorPool: [20074, ge_vkCreateDescriptorPool, gd_vkCreateDescriptorPool, 0],
    vkDestroyDescriptorPool: [20075, ge_vkDestroyDescriptorPool, null, 0],
    vkResetDescriptorPool: [20076, ge_vkResetDescriptorPool, gd_vkResetDescriptorPool, 0],
    vkAllocateDescriptorSets: [20077, ge_vkAllocateDescriptorSets, gd_vkAllocateDescriptorSets, 0],
    vkFreeDescriptorSets: [20078, ge_vkFreeDescriptorSets, gd_vkFreeDescriptorSets, 0],
    vkUpdateDescriptorSets: [20079, ge_vkUpdateDescriptorSets, null, 0],
    vkCreateFramebuffer: [20080, ge_vkCreateFramebuffer, gd_vkCreateFramebuffer, 0],
    vkDestroyFramebuffer: [20081, ge_vkDestroyFramebuffer, null, 0],
    vkCreateRenderPass: [20082, ge_vkCreateRenderPass, gd_vkCreateRenderPass, 0],
    vkDestroyRenderPass: [20083, ge_vkDestroyRenderPass, null, 0],
    vkGetRenderAreaGranularity: [20084, ge_vkGetRenderAreaGranularity, gd_vkGetRenderAreaGranularity, 0],
    vkCreateCommandPool: [20085, ge_vkCreateCommandPool, gd_vkCreateCommandPool, 0],
    vkDestroyCommandPool: [20086, ge_vkDestroyCommandPool, null, 0],
    vkResetCommandPool: [20087, ge_vkResetCommandPool, gd_vkResetCommandPool, 0],
    vkAllocateCommandBuffers: [20088, ge_vkAllocateCommandBuffers, gd_vkAllocateCommandBuffers, 0],
    vkFreeCommandBuffers: [20089, ge_vkFreeCommandBuffers, null, 0],
    vkBeginCommandBuffer: [20090, ge_vkBeginCommandBuffer, gd_vkBeginCommandBuffer, 1],
    vkEndCommandBuffer: [20091, ge_vkEndCommandBuffer, gd_vkEndCommandBuffer, 1],
    vkResetCommandBuffer: [20092, ge_vkResetCommandBuffer, gd_vkResetCommandBuffer, 1],
    vkCmdBindPipeline: [20093, ge_vkCmdBindPipeline, null, 1],
    vkCmdSetViewport: [20094, ge_vkCmdSetViewport, null, 1],
    vkCmdSetScissor: [20095, ge_vkCmdSetScissor, null, 1],
    vkCmdSetLineWidth: [20096, ge_vkCmdSetLineWidth, null, 1],
    vkCmdSetDepthBias: [20097, ge_vkCmdSetDepthBias, null, 1],
    vkCmdSetBlendConstants: [20098, ge_vkCmdSetBlendConstants, null, 1],
    vkCmdSetDepthBounds: [20099, ge_vkCmdSetDepthBounds, null, 1],
    vkCmdSetStencilCompareMask: [20100, ge_vkCmdSetStencilCompareMask, null, 1],
    vkCmdSetStencilWriteMask: [20101, ge_vkCmdSetStencilWriteMask, null, 1],
    vkCmdSetStencilReference: [20102, ge_vkCmdSetStencilReference, null, 1],
    vkCmdBindDescriptorSets: [20103, ge_vkCmdBindDescriptorSets, null, 1],
    vkCmdBindIndexBuffer: [20104, ge_vkCmdBindIndexBuffer, null, 1],
    vkCmdBindVertexBuffers: [20105, ge_vkCmdBindVertexBuffers, null, 1],
    vkCmdDraw: [20106, ge_vkCmdDraw, null, 1],
    vkCmdDrawIndexed: [20107, ge_vkCmdDrawIndexed, null, 1],
    vkCmdDrawIndirect: [20108, ge_vkCmdDrawIndirect, null, 1],
    vkCmdDrawIndexedIndirect: [20109, ge_vkCmdDrawIndexedIndirect, null, 1],
    vkCmdDispatch: [20110, ge_vkCmdDispatch, null, 1],
    vkCmdDispatchIndirect: [20111, ge_vkCmdDispatchIndirect, null, 1],
    vkCmdCopyBuffer: [20112, ge_vkCmdCopyBuffer, null, 1],
    vkCmdCopyImage: [20113, ge_vkCmdCopyImage, null, 1],
    vkCmdBlitImage: [20114, ge_vkCmdBlitImage, null, 1],
    vkCmdCopyBufferToImage: [20115, ge_vkCmdCopyBufferToImage, null, 1],
    vkCmdCopyImageToBuffer: [20116, ge_vkCmdCopyImageToBuffer, null, 1],
    vkCmdUpdateBuffer: [20117, ge_vkCmdUpdateBuffer, null, 1],
    vkCmdFillBuffer: [20118, ge_vkCmdFillBuffer, null, 1],
    vkCmdClearColorImage: [20119, ge_vkCmdClearColorImage, null, 1],
    vkCmdClearDepthStencilImage: [20120, ge_vkCmdClearDepthStencilImage, null, 1],
    vkCmdClearAttachments: [20121, ge_vkCmdClearAttachments, null, 1],
    vkCmdResolveImage: [20122, ge_vkCmdResolveImage, null, 1],
    vkCmdSetEvent: [20123, ge_vkCmdSetEvent, null, 1],
    vkCmdResetEvent: [20124, ge_vkCmdResetEvent, null, 1],
    vkCmdWaitEvents: [20125, ge_vkCmdWaitEvents, null, 1],
    vkCmdPipelineBarrier: [20126, ge_vkCmdPipelineBarrier, null, 1],
    vkCmdBeginQuery: [20127, ge_vkCmdBeginQuery, null, 1],
    vkCmdEndQuery: [20128, ge_vkCmdEndQuery, null, 1],
    vkCmdResetQueryPool: [20129, ge_vkCmdResetQueryPool, null, 1],
    vkCmdWriteTimestamp: [20130, ge_vkCmdWriteTimestamp, null, 1],
    vkCmdCopyQueryPoolResults: [20131, ge_vkCmdCopyQueryPoolResults, null, 1],
    vkCmdPushConstants: [20132, ge_vkCmdPushConstants, null, 1],
    vkCmdBeginRenderPass: [20133, ge_vkCmdBeginRenderPass, null, 1],
    vkCmdNextSubpass: [20134, ge_vkCmdNextSubpass, null, 1],
    vkCmdEndRenderPass: [20135, ge_vkCmdEndRenderPass, null, 1],
    vkCmdExecuteCommands: [20136, ge_vkCmdExecuteCommands, null, 1],
    vkEnumerateInstanceVersion: [20137, ge_vkEnumerateInstanceVersion, gd_vkEnumerateInstanceVersion, 0],
    vkBindBufferMemory2: [20138, ge_vkBindBufferMemory2, gd_vkBindBufferMemory2, 0],
    vkBindImageMemory2: [20139, ge_vkBindImageMemory2, gd_vkBindImageMemory2, 0],
    vkGetDeviceGroupPeerMemoryFeatures: [20140, ge_vkGetDeviceGroupPeerMemoryFeatures, gd_vkGetDeviceGroupPeerMemoryFeatures, 0],
    vkCmdSetDeviceMask: [20141, ge_vkCmdSetDeviceMask, null, 1],
    vkCmdDispatchBase: [20142, ge_vkCmdDispatchBase, null, 1],
    vkEnumeratePhysicalDeviceGroups: [20143, ge_vkEnumeratePhysicalDeviceGroups, gd_vkEnumeratePhysicalDeviceGroups, 0],
    vkGetImageMemoryRequirements2: [20144, ge_vkGetImageMemoryRequirements2, gd_vkGetImageMemoryRequirements2, 0],
    vkGetBufferMemoryRequirements2: [20145, ge_vkGetBufferMemoryRequirements2, gd_vkGetBufferMemoryRequirements2, 0],
    vkGetImageSparseMemoryRequirements2: [20146, ge_vkGetImageSparseMemoryRequirements2, gd_vkGetImageSparseMemoryRequirements2, 0],
    vkGetPhysicalDeviceFeatures2: [20147, ge_vkGetPhysicalDeviceFeatures2, gd_vkGetPhysicalDeviceFeatures2, 0],
    vkGetPhysicalDeviceProperties2: [20148, ge_vkGetPhysicalDeviceProperties2, gd_vkGetPhysicalDeviceProperties2, 0],
    vkGetPhysicalDeviceFormatProperties2: [20149, ge_vkGetPhysicalDeviceFormatProperties2, gd_vkGetPhysicalDeviceFormatProperties2, 0],
    vkGetPhysicalDeviceImageFormatProperties2: [20150, ge_vkGetPhysicalDeviceImageFormatProperties2, gd_vkGetPhysicalDeviceImageFormatProperties2, 0],
    vkGetPhysicalDeviceQueueFamilyProperties2: [20151, ge_vkGetPhysicalDeviceQueueFamilyProperties2, gd_vkGetPhysicalDeviceQueueFamilyProperties2, 0],
    vkGetPhysicalDeviceMemoryProperties2: [20152, ge_vkGetPhysicalDeviceMemoryProperties2, gd_vkGetPhysicalDeviceMemoryProperties2, 0],
    vkGetPhysicalDeviceSparseImageFormatProperties2: [20153, ge_vkGetPhysicalDeviceSparseImageFormatProperties2, gd_vkGetPhysicalDeviceSparseImageFormatProperties2, 0],
    vkTrimCommandPool: [20154, ge_vkTrimCommandPool, null, 0],
    vkGetDeviceQueue2: [20155, ge_vkGetDeviceQueue2, gd_vkGetDeviceQueue2, 0],
    vkCreateSamplerYcbcrConversion: [20156, ge_vkCreateSamplerYcbcrConversion, gd_vkCreateSamplerYcbcrConversion, 0],
    vkDestroySamplerYcbcrConversion: [20157, ge_vkDestroySamplerYcbcrConversion, null, 0],
    vkCreateDescriptorUpdateTemplate: [20158, ge_vkCreateDescriptorUpdateTemplate, gd_vkCreateDescriptorUpdateTemplate, 0],
    vkDestroyDescriptorUpdateTemplate: [20159, ge_vkDestroyDescriptorUpdateTemplate, null, 0],
    vkUpdateDescriptorSetWithTemplate: [20160, ge_vkUpdateDescriptorSetWithTemplate, null, 0],
    vkGetPhysicalDeviceExternalBufferProperties: [20161, ge_vkGetPhysicalDeviceExternalBufferProperties, gd_vkGetPhysicalDeviceExternalBufferProperties, 0],
    vkGetPhysicalDeviceExternalFenceProperties: [20162, ge_vkGetPhysicalDeviceExternalFenceProperties, gd_vkGetPhysicalDeviceExternalFenceProperties, 0],
    vkGetPhysicalDeviceExternalSemaphoreProperties: [20163, ge_vkGetPhysicalDeviceExternalSemaphoreProperties, gd_vkGetPhysicalDeviceExternalSemaphoreProperties, 0],
    vkGetDescriptorSetLayoutSupport: [20164, ge_vkGetDescriptorSetLayoutSupport, gd_vkGetDescriptorSetLayoutSupport, 0],
    vkCmdDrawIndirectCount: [282774587, ge_vkCmdDrawIndirectCount, null, 1],
    vkCmdDrawIndexedIndirectCount: [245204359, ge_vkCmdDrawIndexedIndirectCount, null, 1],
    vkCreateRenderPass2: [279590827, ge_vkCreateRenderPass2, gd_vkCreateRenderPass2, 0],
    vkCmdBeginRenderPass2: [235222847, ge_vkCmdBeginRenderPass2, null, 1],
    vkCmdNextSubpass2: [244873750, ge_vkCmdNextSubpass2, null, 1],
    vkCmdEndRenderPass2: [221297834, ge_vkCmdEndRenderPass2, null, 1],
    vkResetQueryPool: [252097672, ge_vkResetQueryPool, null, 0],
    vkGetSemaphoreCounterValue: [267066974, ge_vkGetSemaphoreCounterValue, gd_vkGetSemaphoreCounterValue, 0],
    vkWaitSemaphores: [224777382, ge_vkWaitSemaphores, gd_vkWaitSemaphores, 0],
    vkSignalSemaphore: [271024127, ge_vkSignalSemaphore, gd_vkSignalSemaphore, 0],
    vkGetBufferDeviceAddress: [222632266, ge_vkGetBufferDeviceAddress, gd_vkGetBufferDeviceAddress, 0],
    vkGetBufferOpaqueCaptureAddress: [230188231, ge_vkGetBufferOpaqueCaptureAddress, gd_vkGetBufferOpaqueCaptureAddress, 0],
    vkGetDeviceMemoryOpaqueCaptureAddress: [260620079, ge_vkGetDeviceMemoryOpaqueCaptureAddress, gd_vkGetDeviceMemoryOpaqueCaptureAddress, 0],
    vkGetPhysicalDeviceToolProperties: [286895278, ge_vkGetPhysicalDeviceToolProperties, gd_vkGetPhysicalDeviceToolProperties, 0],
    vkCreatePrivateDataSlot: [262776916, ge_vkCreatePrivateDataSlot, gd_vkCreatePrivateDataSlot, 0],
    vkDestroyPrivateDataSlot: [224520231, ge_vkDestroyPrivateDataSlot, null, 0],
    vkSetPrivateData: [242146991, ge_vkSetPrivateData, gd_vkSetPrivateData, 0],
    vkGetPrivateData: [237052348, ge_vkGetPrivateData, gd_vkGetPrivateData, 0],
    vkCmdSetEvent2: [232259114, ge_vkCmdSetEvent2, null, 1],
    vkCmdResetEvent2: [271973131, ge_vkCmdResetEvent2, null, 1],
    vkCmdWaitEvents2: [244672720, ge_vkCmdWaitEvents2, null, 1],
    vkCmdPipelineBarrier2: [296709912, ge_vkCmdPipelineBarrier2, null, 1],
    vkCmdWriteTimestamp2: [246322283, ge_vkCmdWriteTimestamp2, null, 1],
    vkQueueSubmit2: [275454371, ge_vkQueueSubmit2, gd_vkQueueSubmit2, 0],
    vkCmdCopyBuffer2: [236505336, ge_vkCmdCopyBuffer2, null, 1],
    vkCmdCopyImage2: [247540368, ge_vkCmdCopyImage2, null, 1],
    vkCmdCopyBufferToImage2: [267966219, ge_vkCmdCopyBufferToImage2, null, 1],
    vkCmdCopyImageToBuffer2: [215156661, ge_vkCmdCopyImageToBuffer2, null, 1],
    vkCmdBlitImage2: [275239053, ge_vkCmdBlitImage2, null, 1],
    vkCmdResolveImage2: [282440329, ge_vkCmdResolveImage2, null, 1],
    vkCmdBeginRendering: [294618673, ge_vkCmdBeginRendering, null, 1],
    vkCmdEndRendering: [220725158, ge_vkCmdEndRendering, null, 1],
    vkCmdSetCullMode: [224605861, ge_vkCmdSetCullMode, null, 1],
    vkCmdSetFrontFace: [223122493, ge_vkCmdSetFrontFace, null, 1],
    vkCmdSetPrimitiveTopology: [263054804, ge_vkCmdSetPrimitiveTopology, null, 1],
    vkCmdSetViewportWithCount: [267390210, ge_vkCmdSetViewportWithCount, null, 1],
    vkCmdSetScissorWithCount: [219934891, ge_vkCmdSetScissorWithCount, null, 1],
    vkCmdBindVertexBuffers2: [258656493, ge_vkCmdBindVertexBuffers2, null, 1],
    vkCmdSetDepthTestEnable: [209714588, ge_vkCmdSetDepthTestEnable, null, 1],
    vkCmdSetDepthWriteEnable: [240260392, ge_vkCmdSetDepthWriteEnable, null, 1],
    vkCmdSetDepthCompareOp: [245341736, ge_vkCmdSetDepthCompareOp, null, 1],
    vkCmdSetDepthBoundsTestEnable: [219709826, ge_vkCmdSetDepthBoundsTestEnable, null, 1],
    vkCmdSetStencilTestEnable: [286845216, ge_vkCmdSetStencilTestEnable, null, 1],
    vkCmdSetStencilOp: [235751186, ge_vkCmdSetStencilOp, null, 1],
    vkCmdSetRasterizerDiscardEnable: [276298238, ge_vkCmdSetRasterizerDiscardEnable, null, 1],
    vkCmdSetDepthBiasEnable: [267154733, ge_vkCmdSetDepthBiasEnable, null, 1],
    vkCmdSetPrimitiveRestartEnable: [230252008, ge_vkCmdSetPrimitiveRestartEnable, null, 1],
    vkGetDeviceBufferMemoryRequirements: [294177590, ge_vkGetDeviceBufferMemoryRequirements, gd_vkGetDeviceBufferMemoryRequirements, 0],
    vkGetDeviceImageMemoryRequirements: [282480635, ge_vkGetDeviceImageMemoryRequirements, gd_vkGetDeviceImageMemoryRequirements, 0],
    vkGetDeviceImageSparseMemoryRequirements: [233707261, ge_vkGetDeviceImageSparseMemoryRequirements, gd_vkGetDeviceImageSparseMemoryRequirements, 0],
    vkCmdSetLineStipple: [235403148, ge_vkCmdSetLineStipple, null, 1],
    vkMapMemory2: [269932043, ge_vkMapMemory2, gd_vkMapMemory2, 0],
    vkUnmapMemory2: [229872812, ge_vkUnmapMemory2, gd_vkUnmapMemory2, 0],
    vkCmdBindIndexBuffer2: [206158434, ge_vkCmdBindIndexBuffer2, null, 1],
    vkGetRenderingAreaGranularity: [214660941, ge_vkGetRenderingAreaGranularity, gd_vkGetRenderingAreaGranularity, 0],
    vkGetDeviceImageSubresourceLayout: [216549053, ge_vkGetDeviceImageSubresourceLayout, gd_vkGetDeviceImageSubresourceLayout, 0],
    vkGetImageSubresourceLayout2: [269545412, ge_vkGetImageSubresourceLayout2, gd_vkGetImageSubresourceLayout2, 0],
    vkCmdPushDescriptorSet: [246922559, ge_vkCmdPushDescriptorSet, null, 1],
    vkCmdPushDescriptorSetWithTemplate: [229886695, ge_vkCmdPushDescriptorSetWithTemplate, null, 1],
    vkCmdSetRenderingAttachmentLocations: [204730753, ge_vkCmdSetRenderingAttachmentLocations, null, 1],
    vkCmdSetRenderingInputAttachmentIndices: [285610580, ge_vkCmdSetRenderingInputAttachmentIndices, null, 1],
    vkCmdBindDescriptorSets2: [281461882, ge_vkCmdBindDescriptorSets2, null, 1],
    vkCmdPushConstants2: [275905655, ge_vkCmdPushConstants2, null, 1],
    vkCmdPushDescriptorSet2: [269912858, ge_vkCmdPushDescriptorSet2, null, 1],
    vkCmdPushDescriptorSetWithTemplate2: [285015421, ge_vkCmdPushDescriptorSetWithTemplate2, null, 1],
    vkCopyMemoryToImage: [263029492, ge_vkCopyMemoryToImage, gd_vkCopyMemoryToImage, 0],
    vkCopyImageToMemory: [204990977, ge_vkCopyImageToMemory, gd_vkCopyImageToMemory, 0],
    vkCopyImageToImage: [223491795, ge_vkCopyImageToImage, gd_vkCopyImageToImage, 0],
    vkTransitionImageLayout: [252133608, ge_vkTransitionImageLayout, gd_vkTransitionImageLayout, 0],
    vkCmdBeginRenderingKHR: [298092805, ge_vkCmdBeginRenderingKHR, null, 1],
    vkCmdEndRenderingKHR: [200651584, ge_vkCmdEndRenderingKHR, null, 1],
    vkGetPhysicalDeviceFeatures2KHR: [20198, ge_vkGetPhysicalDeviceFeatures2KHR, gd_vkGetPhysicalDeviceFeatures2KHR, 0],
    vkGetPhysicalDeviceProperties2KHR: [20199, ge_vkGetPhysicalDeviceProperties2KHR, gd_vkGetPhysicalDeviceProperties2KHR, 0],
    vkGetPhysicalDeviceFormatProperties2KHR: [20200, ge_vkGetPhysicalDeviceFormatProperties2KHR, gd_vkGetPhysicalDeviceFormatProperties2KHR, 0],
    vkGetPhysicalDeviceImageFormatProperties2KHR: [20201, ge_vkGetPhysicalDeviceImageFormatProperties2KHR, gd_vkGetPhysicalDeviceImageFormatProperties2KHR, 0],
    vkGetPhysicalDeviceQueueFamilyProperties2KHR: [20202, ge_vkGetPhysicalDeviceQueueFamilyProperties2KHR, gd_vkGetPhysicalDeviceQueueFamilyProperties2KHR, 0],
    vkGetPhysicalDeviceMemoryProperties2KHR: [20203, ge_vkGetPhysicalDeviceMemoryProperties2KHR, gd_vkGetPhysicalDeviceMemoryProperties2KHR, 0],
    vkGetPhysicalDeviceSparseImageFormatProperties2KHR: [20204, ge_vkGetPhysicalDeviceSparseImageFormatProperties2KHR, gd_vkGetPhysicalDeviceSparseImageFormatProperties2KHR, 0],
    vkTrimCommandPoolKHR: [20208, ge_vkTrimCommandPoolKHR, null, 0],
    vkGetPhysicalDeviceExternalBufferPropertiesKHR: [20210, ge_vkGetPhysicalDeviceExternalBufferPropertiesKHR, gd_vkGetPhysicalDeviceExternalBufferPropertiesKHR, 0],
    vkGetPhysicalDeviceExternalSemaphorePropertiesKHR: [20215, ge_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR, gd_vkGetPhysicalDeviceExternalSemaphorePropertiesKHR, 0],
    vkImportSemaphoreFdKHR: [20218, ge_vkImportSemaphoreFdKHR, gd_vkImportSemaphoreFdKHR, 0],
    vkGetSemaphoreFdKHR: [20219, ge_vkGetSemaphoreFdKHR, gd_vkGetSemaphoreFdKHR, 0],
    vkCreateDescriptorUpdateTemplateKHR: [20222, ge_vkCreateDescriptorUpdateTemplateKHR, gd_vkCreateDescriptorUpdateTemplateKHR, 0],
    vkDestroyDescriptorUpdateTemplateKHR: [20223, ge_vkDestroyDescriptorUpdateTemplateKHR, null, 0],
    vkUpdateDescriptorSetWithTemplateKHR: [20224, ge_vkUpdateDescriptorSetWithTemplateKHR, null, 0],
    vkCreateRenderPass2KHR: [20225, ge_vkCreateRenderPass2KHR, gd_vkCreateRenderPass2KHR, 0],
    vkCmdBeginRenderPass2KHR: [20226, ge_vkCmdBeginRenderPass2KHR, null, 1],
    vkCmdNextSubpass2KHR: [20227, ge_vkCmdNextSubpass2KHR, null, 1],
    vkCmdEndRenderPass2KHR: [20228, ge_vkCmdEndRenderPass2KHR, null, 1],
    vkGetPhysicalDeviceExternalFencePropertiesKHR: [20230, ge_vkGetPhysicalDeviceExternalFencePropertiesKHR, gd_vkGetPhysicalDeviceExternalFencePropertiesKHR, 0],
    vkImportFenceFdKHR: [20233, ge_vkImportFenceFdKHR, gd_vkImportFenceFdKHR, 0],
    vkGetFenceFdKHR: [20234, ge_vkGetFenceFdKHR, gd_vkGetFenceFdKHR, 0],
    vkGetImageMemoryRequirements2KHR: [20241, ge_vkGetImageMemoryRequirements2KHR, gd_vkGetImageMemoryRequirements2KHR, 0],
    vkGetBufferMemoryRequirements2KHR: [20242, ge_vkGetBufferMemoryRequirements2KHR, gd_vkGetBufferMemoryRequirements2KHR, 0],
    vkGetImageSparseMemoryRequirements2KHR: [20243, ge_vkGetImageSparseMemoryRequirements2KHR, gd_vkGetImageSparseMemoryRequirements2KHR, 0],
    vkCreateSamplerYcbcrConversionKHR: [20244, ge_vkCreateSamplerYcbcrConversionKHR, gd_vkCreateSamplerYcbcrConversionKHR, 0],
    vkDestroySamplerYcbcrConversionKHR: [20245, ge_vkDestroySamplerYcbcrConversionKHR, null, 0],
    vkBindBufferMemory2KHR: [20246, ge_vkBindBufferMemory2KHR, gd_vkBindBufferMemory2KHR, 0],
    vkBindImageMemory2KHR: [20247, ge_vkBindImageMemory2KHR, gd_vkBindImageMemory2KHR, 0],
    vkGetDescriptorSetLayoutSupportKHR: [20248, ge_vkGetDescriptorSetLayoutSupportKHR, gd_vkGetDescriptorSetLayoutSupportKHR, 0],
    vkGetBufferDeviceAddressKHR: [219261480, ge_vkGetBufferDeviceAddressKHR, gd_vkGetBufferDeviceAddressKHR, 0],
    vkGetBufferOpaqueCaptureAddressKHR: [285631711, ge_vkGetBufferOpaqueCaptureAddressKHR, gd_vkGetBufferOpaqueCaptureAddressKHR, 0],
    vkGetDeviceMemoryOpaqueCaptureAddressKHR: [294671624, ge_vkGetDeviceMemoryOpaqueCaptureAddressKHR, gd_vkGetDeviceMemoryOpaqueCaptureAddressKHR, 0],
    vkGetPipelineExecutablePropertiesKHR: [269458798, ge_vkGetPipelineExecutablePropertiesKHR, gd_vkGetPipelineExecutablePropertiesKHR, 0],
    vkGetPipelineExecutableStatisticsKHR: [271191699, ge_vkGetPipelineExecutableStatisticsKHR, gd_vkGetPipelineExecutableStatisticsKHR, 0],
    vkGetPipelineExecutableInternalRepresentationsKHR: [274148497, ge_vkGetPipelineExecutableInternalRepresentationsKHR, gd_vkGetPipelineExecutableInternalRepresentationsKHR, 0],
    vkCmdSetEvent2KHR: [270411360, ge_vkCmdSetEvent2KHR, null, 1],
    vkCmdResetEvent2KHR: [283215906, ge_vkCmdResetEvent2KHR, null, 1],
    vkCmdWaitEvents2KHR: [244967758, ge_vkCmdWaitEvents2KHR, null, 1],
    vkCmdPipelineBarrier2KHR: [201310066, ge_vkCmdPipelineBarrier2KHR, null, 1],
    vkCmdWriteTimestamp2KHR: [252552241, ge_vkCmdWriteTimestamp2KHR, null, 1],
    vkQueueSubmit2KHR: [293024240, ge_vkQueueSubmit2KHR, gd_vkQueueSubmit2KHR, 0],
    vkCmdCopyBuffer2KHR: [247893766, ge_vkCmdCopyBuffer2KHR, null, 1],
    vkCmdCopyImage2KHR: [227008250, ge_vkCmdCopyImage2KHR, null, 1],
    vkCmdCopyBufferToImage2KHR: [248841963, ge_vkCmdCopyBufferToImage2KHR, null, 1],
    vkCmdCopyImageToBuffer2KHR: [252249060, ge_vkCmdCopyImageToBuffer2KHR, null, 1],
    vkCmdBlitImage2KHR: [259838288, ge_vkCmdBlitImage2KHR, null, 1],
    vkCmdResolveImage2KHR: [254857232, ge_vkCmdResolveImage2KHR, null, 1],
    vkGetDeviceBufferMemoryRequirementsKHR: [201613635, ge_vkGetDeviceBufferMemoryRequirementsKHR, gd_vkGetDeviceBufferMemoryRequirementsKHR, 0],
    vkGetDeviceImageMemoryRequirementsKHR: [243155021, ge_vkGetDeviceImageMemoryRequirementsKHR, gd_vkGetDeviceImageMemoryRequirementsKHR, 0],
    vkGetDeviceImageSparseMemoryRequirementsKHR: [275585477, ge_vkGetDeviceImageSparseMemoryRequirementsKHR, gd_vkGetDeviceImageSparseMemoryRequirementsKHR, 0],
    vkCmdBindIndexBuffer2KHR: [202856085, ge_vkCmdBindIndexBuffer2KHR, null, 1],
    vkGetRenderingAreaGranularityKHR: [238658496, ge_vkGetRenderingAreaGranularityKHR, gd_vkGetRenderingAreaGranularityKHR, 0],
    vkGetDeviceImageSubresourceLayoutKHR: [252830318, ge_vkGetDeviceImageSubresourceLayoutKHR, gd_vkGetDeviceImageSubresourceLayoutKHR, 0],
    vkGetImageSubresourceLayout2KHR: [243334937, ge_vkGetImageSubresourceLayout2KHR, gd_vkGetImageSubresourceLayout2KHR, 0],
    vkCmdSetLineStippleKHR: [219923286, ge_vkCmdSetLineStippleKHR, null, 1],
    vkGetSwapchainGrallocUsageANDROID: [20251, ge_vkGetSwapchainGrallocUsageANDROID, gd_vkGetSwapchainGrallocUsageANDROID, 0],
    vkAcquireImageANDROID: [20252, ge_vkAcquireImageANDROID, gd_vkAcquireImageANDROID, 0],
    vkQueueSignalReleaseImageANDROID: [20253, ge_vkQueueSignalReleaseImageANDROID, gd_vkQueueSignalReleaseImageANDROID, 0],
    vkGetSwapchainGrallocUsage2ANDROID: [287960452, ge_vkGetSwapchainGrallocUsage2ANDROID, gd_vkGetSwapchainGrallocUsage2ANDROID, 0],
    vkCmdBindTransformFeedbackBuffersEXT: [267779978, ge_vkCmdBindTransformFeedbackBuffersEXT, null, 1],
    vkCmdBeginTransformFeedbackEXT: [294396901, ge_vkCmdBeginTransformFeedbackEXT, null, 1],
    vkCmdEndTransformFeedbackEXT: [272333731, ge_vkCmdEndTransformFeedbackEXT, null, 1],
    vkCmdBeginQueryIndexedEXT: [275810601, ge_vkCmdBeginQueryIndexedEXT, null, 1],
    vkCmdEndQueryIndexedEXT: [279821337, ge_vkCmdEndQueryIndexedEXT, null, 1],
    vkCmdDrawIndirectByteCountEXT: [285235943, ge_vkCmdDrawIndirectByteCountEXT, null, 1],
    vkGetImageDrmFormatModifierPropertiesEXT: [251301237, ge_vkGetImageDrmFormatModifierPropertiesEXT, gd_vkGetImageDrmFormatModifierPropertiesEXT, 0],
    vkGetPhysicalDeviceToolPropertiesEXT: [282247593, ge_vkGetPhysicalDeviceToolPropertiesEXT, gd_vkGetPhysicalDeviceToolPropertiesEXT, 0],
    vkCmdSetLineStippleEXT: [263855692, ge_vkCmdSetLineStippleEXT, null, 1],
    vkCmdSetCullModeEXT: [266285895, ge_vkCmdSetCullModeEXT, null, 1],
    vkCmdSetFrontFaceEXT: [212644406, ge_vkCmdSetFrontFaceEXT, null, 1],
    vkCmdSetPrimitiveTopologyEXT: [260783979, ge_vkCmdSetPrimitiveTopologyEXT, null, 1],
    vkCmdSetViewportWithCountEXT: [257105245, ge_vkCmdSetViewportWithCountEXT, null, 1],
    vkCmdSetScissorWithCountEXT: [204588120, ge_vkCmdSetScissorWithCountEXT, null, 1],
    vkCmdBindVertexBuffers2EXT: [243419921, ge_vkCmdBindVertexBuffers2EXT, null, 1],
    vkCmdSetDepthTestEnableEXT: [233771166, ge_vkCmdSetDepthTestEnableEXT, null, 1],
    vkCmdSetDepthWriteEnableEXT: [218663304, ge_vkCmdSetDepthWriteEnableEXT, null, 1],
    vkCmdSetDepthCompareOpEXT: [247761589, ge_vkCmdSetDepthCompareOpEXT, null, 1],
    vkCmdSetDepthBoundsTestEnableEXT: [223213519, ge_vkCmdSetDepthBoundsTestEnableEXT, null, 1],
    vkCmdSetStencilTestEnableEXT: [286438749, ge_vkCmdSetStencilTestEnableEXT, null, 1],
    vkCmdSetStencilOpEXT: [277159578, ge_vkCmdSetStencilOpEXT, null, 1],
    vkCopyMemoryToImageEXT: [218832495, ge_vkCopyMemoryToImageEXT, gd_vkCopyMemoryToImageEXT, 0],
    vkCopyImageToMemoryEXT: [204695490, ge_vkCopyImageToMemoryEXT, gd_vkCopyImageToMemoryEXT, 0],
    vkCopyImageToImageEXT: [223534798, ge_vkCopyImageToImageEXT, gd_vkCopyImageToImageEXT, 0],
    vkTransitionImageLayoutEXT: [242817558, ge_vkTransitionImageLayoutEXT, gd_vkTransitionImageLayoutEXT, 0],
    vkGetImageSubresourceLayout2EXT: [296152177, ge_vkGetImageSubresourceLayout2EXT, gd_vkGetImageSubresourceLayout2EXT, 0],
    vkCreatePrivateDataSlotEXT: [236374049, ge_vkCreatePrivateDataSlotEXT, gd_vkCreatePrivateDataSlotEXT, 0],
    vkDestroyPrivateDataSlotEXT: [208891309, ge_vkDestroyPrivateDataSlotEXT, null, 0],
    vkSetPrivateDataEXT: [225259406, ge_vkSetPrivateDataEXT, gd_vkSetPrivateDataEXT, 0],
    vkGetPrivateDataEXT: [291399427, ge_vkGetPrivateDataEXT, gd_vkGetPrivateDataEXT, 0],
    vkCmdSetPatchControlPointsEXT: [208680354, ge_vkCmdSetPatchControlPointsEXT, null, 1],
    vkCmdSetRasterizerDiscardEnableEXT: [245221405, ge_vkCmdSetRasterizerDiscardEnableEXT, null, 1],
    vkCmdSetDepthBiasEnableEXT: [259472348, ge_vkCmdSetDepthBiasEnableEXT, null, 1],
    vkCmdSetLogicOpEXT: [267481927, ge_vkCmdSetLogicOpEXT, null, 1],
    vkCmdSetPrimitiveRestartEnableEXT: [299567883, ge_vkCmdSetPrimitiveRestartEnableEXT, null, 1],
    vkCmdSetColorWriteEnableEXT: [202223297, ge_vkCmdSetColorWriteEnableEXT, null, 1],
    vkMapMemoryIntoAddressSpaceGOOGLE: [20317, ge_vkMapMemoryIntoAddressSpaceGOOGLE, gd_vkMapMemoryIntoAddressSpaceGOOGLE, 0],
    vkUpdateDescriptorSetWithTemplateSizedGOOGLE: [20320, ge_vkUpdateDescriptorSetWithTemplateSizedGOOGLE, null, 0],
    vkBeginCommandBufferAsyncGOOGLE: [20321, ge_vkBeginCommandBufferAsyncGOOGLE, null, 1],
    vkEndCommandBufferAsyncGOOGLE: [20322, ge_vkEndCommandBufferAsyncGOOGLE, null, 1],
    vkResetCommandBufferAsyncGOOGLE: [20323, ge_vkResetCommandBufferAsyncGOOGLE, null, 1],
    vkCommandBufferHostSyncGOOGLE: [20324, ge_vkCommandBufferHostSyncGOOGLE, null, 1],
    vkCreateImageWithRequirementsGOOGLE: [20325, ge_vkCreateImageWithRequirementsGOOGLE, gd_vkCreateImageWithRequirementsGOOGLE, 0],
    vkCreateBufferWithRequirementsGOOGLE: [20326, ge_vkCreateBufferWithRequirementsGOOGLE, gd_vkCreateBufferWithRequirementsGOOGLE, 0],
    vkGetMemoryHostAddressInfoGOOGLE: [20327, ge_vkGetMemoryHostAddressInfoGOOGLE, gd_vkGetMemoryHostAddressInfoGOOGLE, 0],
    vkFreeMemorySyncGOOGLE: [20328, ge_vkFreeMemorySyncGOOGLE, gd_vkFreeMemorySyncGOOGLE, 0],
    vkQueueHostSyncGOOGLE: [20329, ge_vkQueueHostSyncGOOGLE, null, 0],
    vkQueueSubmitAsyncGOOGLE: [20330, ge_vkQueueSubmitAsyncGOOGLE, null, 0],
    vkQueueWaitIdleAsyncGOOGLE: [20331, ge_vkQueueWaitIdleAsyncGOOGLE, null, 0],
    vkQueueBindSparseAsyncGOOGLE: [20332, ge_vkQueueBindSparseAsyncGOOGLE, null, 0],
    vkGetLinearImageLayoutGOOGLE: [20333, ge_vkGetLinearImageLayoutGOOGLE, gd_vkGetLinearImageLayoutGOOGLE, 0],
    vkGetLinearImageLayout2GOOGLE: [282325414, ge_vkGetLinearImageLayout2GOOGLE, gd_vkGetLinearImageLayout2GOOGLE, 0],
    vkQueueFlushCommandsGOOGLE: [20340, ge_vkQueueFlushCommandsGOOGLE, null, 0],
    vkQueueCommitDescriptorSetUpdatesGOOGLE: [267932433, ge_vkQueueCommitDescriptorSetUpdatesGOOGLE, null, 0],
    vkCollectDescriptorPoolIdsGOOGLE: [213659202, ge_vkCollectDescriptorPoolIdsGOOGLE, gd_vkCollectDescriptorPoolIdsGOOGLE, 0],
    vkQueueSignalReleaseImageANDROIDAsyncGOOGLE: [243985229, ge_vkQueueSignalReleaseImageANDROIDAsyncGOOGLE, null, 0],
    vkQueueFlushCommandsFromAuxMemoryGOOGLE: [290633483, ge_vkQueueFlushCommandsFromAuxMemoryGOOGLE, null, 0],
    vkGetBlobGOOGLE: [20341, ge_vkGetBlobGOOGLE, gd_vkGetBlobGOOGLE, 0],
    vkUpdateDescriptorSetWithTemplateSized2GOOGLE: [244782974, ge_vkUpdateDescriptorSetWithTemplateSized2GOOGLE, null, 0],
    vkQueueSubmitAsync2GOOGLE: [292092830, ge_vkQueueSubmitAsync2GOOGLE, null, 0],
    vkGetSemaphoreGOOGLE: [20342, ge_vkGetSemaphoreGOOGLE, gd_vkGetSemaphoreGOOGLE, 0],
    vkTraceAsyncGOOGLE: [286553566, ge_vkTraceAsyncGOOGLE, null, 0],
};

/** the structs by name: [encode in a request, decode in a reply] */
export const GUEST_STRUCTS = {
    VkAllocationCallbacks: [ge_VkAllocationCallbacks, null],
    VkApplicationInfo: [ge_VkApplicationInfo, null],
    VkAttachmentDescription: [ge_VkAttachmentDescription, null],
    VkAttachmentDescription2: [ge_VkAttachmentDescription2, null],
    VkAttachmentDescriptionStencilLayout: [ge_VkAttachmentDescriptionStencilLayout, gd_VkAttachmentDescriptionStencilLayout],
    VkAttachmentReference: [ge_VkAttachmentReference, gd_VkAttachmentReference],
    VkAttachmentReference2: [ge_VkAttachmentReference2, gd_VkAttachmentReference2],
    VkAttachmentReferenceStencilLayout: [ge_VkAttachmentReferenceStencilLayout, gd_VkAttachmentReferenceStencilLayout],
    VkBindBufferMemoryDeviceGroupInfo: [ge_VkBindBufferMemoryDeviceGroupInfo, gd_VkBindBufferMemoryDeviceGroupInfo],
    VkBindBufferMemoryInfo: [ge_VkBindBufferMemoryInfo, null],
    VkBindDescriptorSetsInfo: [ge_VkBindDescriptorSetsInfo, null],
    VkBindImageMemoryDeviceGroupInfo: [ge_VkBindImageMemoryDeviceGroupInfo, gd_VkBindImageMemoryDeviceGroupInfo],
    VkBindImageMemoryInfo: [ge_VkBindImageMemoryInfo, null],
    VkBindImagePlaneMemoryInfo: [ge_VkBindImagePlaneMemoryInfo, gd_VkBindImagePlaneMemoryInfo],
    VkBindMemoryStatus: [ge_VkBindMemoryStatus, gd_VkBindMemoryStatus],
    VkBindSparseInfo: [ge_VkBindSparseInfo, null],
    VkBlitImageInfo2: [ge_VkBlitImageInfo2, null],
    VkBufferCopy: [ge_VkBufferCopy, null],
    VkBufferCopy2: [ge_VkBufferCopy2, null],
    VkBufferCreateInfo: [ge_VkBufferCreateInfo, null],
    VkBufferDeviceAddressInfo: [ge_VkBufferDeviceAddressInfo, null],
    VkBufferImageCopy: [ge_VkBufferImageCopy, null],
    VkBufferImageCopy2: [ge_VkBufferImageCopy2, null],
    VkBufferMemoryBarrier: [ge_VkBufferMemoryBarrier, null],
    VkBufferMemoryBarrier2: [ge_VkBufferMemoryBarrier2, null],
    VkBufferMemoryRequirementsInfo2: [ge_VkBufferMemoryRequirementsInfo2, null],
    VkBufferOpaqueCaptureAddressCreateInfo: [ge_VkBufferOpaqueCaptureAddressCreateInfo, gd_VkBufferOpaqueCaptureAddressCreateInfo],
    VkBufferUsageFlags2CreateInfo: [ge_VkBufferUsageFlags2CreateInfo, gd_VkBufferUsageFlags2CreateInfo],
    VkBufferViewCreateInfo: [ge_VkBufferViewCreateInfo, null],
    VkClearAttachment: [ge_VkClearAttachment, null],
    VkClearColorValue: [ge_VkClearColorValue, gd_VkClearColorValue],
    VkClearDepthStencilValue: [ge_VkClearDepthStencilValue, null],
    VkClearRect: [ge_VkClearRect, null],
    VkClearValue: [ge_VkClearValue, null],
    VkCommandBufferAllocateInfo: [ge_VkCommandBufferAllocateInfo, null],
    VkCommandBufferBeginInfo: [ge_VkCommandBufferBeginInfo, null],
    VkCommandBufferInheritanceInfo: [ge_VkCommandBufferInheritanceInfo, null],
    VkCommandBufferInheritanceRenderingInfo: [ge_VkCommandBufferInheritanceRenderingInfo, gd_VkCommandBufferInheritanceRenderingInfo],
    VkCommandBufferSubmitInfo: [ge_VkCommandBufferSubmitInfo, null],
    VkCommandPoolCreateInfo: [ge_VkCommandPoolCreateInfo, null],
    VkComponentMapping: [ge_VkComponentMapping, null],
    VkComputePipelineCreateInfo: [ge_VkComputePipelineCreateInfo, null],
    VkConformanceVersion: [ge_VkConformanceVersion, gd_VkConformanceVersion],
    VkCopyBufferInfo2: [ge_VkCopyBufferInfo2, null],
    VkCopyBufferToImageInfo2: [ge_VkCopyBufferToImageInfo2, null],
    VkCopyDescriptorSet: [ge_VkCopyDescriptorSet, null],
    VkCopyImageInfo2: [ge_VkCopyImageInfo2, null],
    VkCopyImageToBufferInfo2: [ge_VkCopyImageToBufferInfo2, null],
    VkCopyImageToImageInfo: [ge_VkCopyImageToImageInfo, null],
    VkCopyImageToMemoryInfo: [ge_VkCopyImageToMemoryInfo, null],
    VkCopyMemoryToImageInfo: [ge_VkCopyMemoryToImageInfo, null],
    VkCreateBlobGOOGLE: [ge_VkCreateBlobGOOGLE, gd_VkCreateBlobGOOGLE],
    VkDependencyInfo: [ge_VkDependencyInfo, null],
    VkDescriptorBufferInfo: [ge_VkDescriptorBufferInfo, null],
    VkDescriptorImageInfo: [ge_VkDescriptorImageInfo, null],
    VkDescriptorPoolCreateInfo: [ge_VkDescriptorPoolCreateInfo, null],
    VkDescriptorPoolInlineUniformBlockCreateInfo: [ge_VkDescriptorPoolInlineUniformBlockCreateInfo, gd_VkDescriptorPoolInlineUniformBlockCreateInfo],
    VkDescriptorPoolSize: [ge_VkDescriptorPoolSize, null],
    VkDescriptorSetAllocateInfo: [ge_VkDescriptorSetAllocateInfo, null],
    VkDescriptorSetLayoutBinding: [ge_VkDescriptorSetLayoutBinding, null],
    VkDescriptorSetLayoutBindingFlagsCreateInfo: [ge_VkDescriptorSetLayoutBindingFlagsCreateInfo, gd_VkDescriptorSetLayoutBindingFlagsCreateInfo],
    VkDescriptorSetLayoutCreateInfo: [ge_VkDescriptorSetLayoutCreateInfo, null],
    VkDescriptorSetLayoutSupport: [ge_VkDescriptorSetLayoutSupport, gd_VkDescriptorSetLayoutSupport],
    VkDescriptorSetVariableDescriptorCountAllocateInfo: [ge_VkDescriptorSetVariableDescriptorCountAllocateInfo, gd_VkDescriptorSetVariableDescriptorCountAllocateInfo],
    VkDescriptorSetVariableDescriptorCountLayoutSupport: [ge_VkDescriptorSetVariableDescriptorCountLayoutSupport, gd_VkDescriptorSetVariableDescriptorCountLayoutSupport],
    VkDescriptorUpdateTemplateCreateInfo: [ge_VkDescriptorUpdateTemplateCreateInfo, null],
    VkDescriptorUpdateTemplateEntry: [ge_VkDescriptorUpdateTemplateEntry, null],
    VkDeviceBufferMemoryRequirements: [ge_VkDeviceBufferMemoryRequirements, null],
    VkDeviceCreateInfo: [ge_VkDeviceCreateInfo, null],
    VkDeviceDeviceMemoryReportCreateInfoEXT: [ge_VkDeviceDeviceMemoryReportCreateInfoEXT, gd_VkDeviceDeviceMemoryReportCreateInfoEXT],
    VkDeviceGroupBindSparseInfo: [ge_VkDeviceGroupBindSparseInfo, gd_VkDeviceGroupBindSparseInfo],
    VkDeviceGroupCommandBufferBeginInfo: [ge_VkDeviceGroupCommandBufferBeginInfo, gd_VkDeviceGroupCommandBufferBeginInfo],
    VkDeviceGroupDeviceCreateInfo: [ge_VkDeviceGroupDeviceCreateInfo, gd_VkDeviceGroupDeviceCreateInfo],
    VkDeviceGroupRenderPassBeginInfo: [ge_VkDeviceGroupRenderPassBeginInfo, gd_VkDeviceGroupRenderPassBeginInfo],
    VkDeviceGroupSubmitInfo: [ge_VkDeviceGroupSubmitInfo, gd_VkDeviceGroupSubmitInfo],
    VkDeviceImageMemoryRequirements: [ge_VkDeviceImageMemoryRequirements, null],
    VkDeviceImageSubresourceInfo: [ge_VkDeviceImageSubresourceInfo, null],
    VkDeviceMemoryOpaqueCaptureAddressInfo: [ge_VkDeviceMemoryOpaqueCaptureAddressInfo, null],
    VkDevicePrivateDataCreateInfo: [ge_VkDevicePrivateDataCreateInfo, gd_VkDevicePrivateDataCreateInfo],
    VkDeviceQueueCreateInfo: [ge_VkDeviceQueueCreateInfo, null],
    VkDeviceQueueGlobalPriorityCreateInfo: [ge_VkDeviceQueueGlobalPriorityCreateInfo, gd_VkDeviceQueueGlobalPriorityCreateInfo],
    VkDeviceQueueInfo2: [ge_VkDeviceQueueInfo2, null],
    VkDrmFormatModifierProperties2EXT: [ge_VkDrmFormatModifierProperties2EXT, gd_VkDrmFormatModifierProperties2EXT],
    VkDrmFormatModifierPropertiesEXT: [ge_VkDrmFormatModifierPropertiesEXT, gd_VkDrmFormatModifierPropertiesEXT],
    VkDrmFormatModifierPropertiesList2EXT: [ge_VkDrmFormatModifierPropertiesList2EXT, gd_VkDrmFormatModifierPropertiesList2EXT],
    VkDrmFormatModifierPropertiesListEXT: [ge_VkDrmFormatModifierPropertiesListEXT, gd_VkDrmFormatModifierPropertiesListEXT],
    VkEventCreateInfo: [ge_VkEventCreateInfo, null],
    VkExportFenceCreateInfo: [ge_VkExportFenceCreateInfo, gd_VkExportFenceCreateInfo],
    VkExportMemoryAllocateInfo: [ge_VkExportMemoryAllocateInfo, gd_VkExportMemoryAllocateInfo],
    VkExportSemaphoreCreateInfo: [ge_VkExportSemaphoreCreateInfo, gd_VkExportSemaphoreCreateInfo],
    VkExtensionProperties: [ge_VkExtensionProperties, gd_VkExtensionProperties],
    VkExtent2D: [ge_VkExtent2D, gd_VkExtent2D],
    VkExtent3D: [ge_VkExtent3D, gd_VkExtent3D],
    VkExternalBufferProperties: [ge_VkExternalBufferProperties, gd_VkExternalBufferProperties],
    VkExternalFenceProperties: [ge_VkExternalFenceProperties, gd_VkExternalFenceProperties],
    VkExternalImageFormatProperties: [ge_VkExternalImageFormatProperties, gd_VkExternalImageFormatProperties],
    VkExternalMemoryBufferCreateInfo: [ge_VkExternalMemoryBufferCreateInfo, gd_VkExternalMemoryBufferCreateInfo],
    VkExternalMemoryImageCreateInfo: [ge_VkExternalMemoryImageCreateInfo, gd_VkExternalMemoryImageCreateInfo],
    VkExternalMemoryProperties: [ge_VkExternalMemoryProperties, gd_VkExternalMemoryProperties],
    VkExternalSemaphoreProperties: [ge_VkExternalSemaphoreProperties, gd_VkExternalSemaphoreProperties],
    VkFenceCreateInfo: [ge_VkFenceCreateInfo, null],
    VkFenceGetFdInfoKHR: [ge_VkFenceGetFdInfoKHR, null],
    VkFormatProperties: [ge_VkFormatProperties, gd_VkFormatProperties],
    VkFormatProperties2: [ge_VkFormatProperties2, gd_VkFormatProperties2],
    VkFormatProperties3: [ge_VkFormatProperties3, gd_VkFormatProperties3],
    VkFramebufferAttachmentImageInfo: [ge_VkFramebufferAttachmentImageInfo, gd_VkFramebufferAttachmentImageInfo],
    VkFramebufferAttachmentsCreateInfo: [ge_VkFramebufferAttachmentsCreateInfo, gd_VkFramebufferAttachmentsCreateInfo],
    VkFramebufferCreateInfo: [ge_VkFramebufferCreateInfo, null],
    VkGraphicsPipelineCreateInfo: [ge_VkGraphicsPipelineCreateInfo, null],
    VkGraphicsPipelineLibraryCreateInfoEXT: [ge_VkGraphicsPipelineLibraryCreateInfoEXT, gd_VkGraphicsPipelineLibraryCreateInfoEXT],
    VkHostImageCopyDevicePerformanceQuery: [ge_VkHostImageCopyDevicePerformanceQuery, gd_VkHostImageCopyDevicePerformanceQuery],
    VkHostImageLayoutTransitionInfo: [ge_VkHostImageLayoutTransitionInfo, null],
    VkImageBlit: [ge_VkImageBlit, null],
    VkImageBlit2: [ge_VkImageBlit2, null],
    VkImageCompressionControlEXT: [ge_VkImageCompressionControlEXT, gd_VkImageCompressionControlEXT],
    VkImageCompressionPropertiesEXT: [ge_VkImageCompressionPropertiesEXT, gd_VkImageCompressionPropertiesEXT],
    VkImageCopy: [ge_VkImageCopy, null],
    VkImageCopy2: [ge_VkImageCopy2, null],
    VkImageCreateInfo: [ge_VkImageCreateInfo, null],
    VkImageDrmFormatModifierExplicitCreateInfoEXT: [ge_VkImageDrmFormatModifierExplicitCreateInfoEXT, gd_VkImageDrmFormatModifierExplicitCreateInfoEXT],
    VkImageDrmFormatModifierListCreateInfoEXT: [ge_VkImageDrmFormatModifierListCreateInfoEXT, gd_VkImageDrmFormatModifierListCreateInfoEXT],
    VkImageDrmFormatModifierPropertiesEXT: [ge_VkImageDrmFormatModifierPropertiesEXT, gd_VkImageDrmFormatModifierPropertiesEXT],
    VkImageFormatListCreateInfo: [ge_VkImageFormatListCreateInfo, gd_VkImageFormatListCreateInfo],
    VkImageFormatProperties: [ge_VkImageFormatProperties, gd_VkImageFormatProperties],
    VkImageFormatProperties2: [ge_VkImageFormatProperties2, gd_VkImageFormatProperties2],
    VkImageMemoryBarrier: [ge_VkImageMemoryBarrier, null],
    VkImageMemoryBarrier2: [ge_VkImageMemoryBarrier2, null],
    VkImageMemoryRequirementsInfo2: [ge_VkImageMemoryRequirementsInfo2, null],
    VkImagePlaneMemoryRequirementsInfo: [ge_VkImagePlaneMemoryRequirementsInfo, gd_VkImagePlaneMemoryRequirementsInfo],
    VkImageResolve: [ge_VkImageResolve, null],
    VkImageResolve2: [ge_VkImageResolve2, null],
    VkImageSparseMemoryRequirementsInfo2: [ge_VkImageSparseMemoryRequirementsInfo2, null],
    VkImageStencilUsageCreateInfo: [ge_VkImageStencilUsageCreateInfo, gd_VkImageStencilUsageCreateInfo],
    VkImageSubresource: [ge_VkImageSubresource, null],
    VkImageSubresource2: [ge_VkImageSubresource2, null],
    VkImageSubresourceLayers: [ge_VkImageSubresourceLayers, null],
    VkImageSubresourceRange: [ge_VkImageSubresourceRange, null],
    VkImageToMemoryCopy: [ge_VkImageToMemoryCopy, null],
    VkImageViewCreateInfo: [ge_VkImageViewCreateInfo, null],
    VkImageViewUsageCreateInfo: [ge_VkImageViewUsageCreateInfo, gd_VkImageViewUsageCreateInfo],
    VkImportBufferGOOGLE: [ge_VkImportBufferGOOGLE, gd_VkImportBufferGOOGLE],
    VkImportColorBufferGOOGLE: [ge_VkImportColorBufferGOOGLE, gd_VkImportColorBufferGOOGLE],
    VkImportFenceFdInfoKHR: [ge_VkImportFenceFdInfoKHR, null],
    VkImportSemaphoreFdInfoKHR: [ge_VkImportSemaphoreFdInfoKHR, null],
    VkInputAttachmentAspectReference: [ge_VkInputAttachmentAspectReference, gd_VkInputAttachmentAspectReference],
    VkInstanceCreateInfo: [ge_VkInstanceCreateInfo, null],
    VkLayerProperties: [ge_VkLayerProperties, gd_VkLayerProperties],
    VkMappedMemoryRange: [ge_VkMappedMemoryRange, null],
    VkMemoryAllocateFlagsInfo: [ge_VkMemoryAllocateFlagsInfo, gd_VkMemoryAllocateFlagsInfo],
    VkMemoryAllocateInfo: [ge_VkMemoryAllocateInfo, null],
    VkMemoryBarrier: [ge_VkMemoryBarrier, null],
    VkMemoryBarrier2: [ge_VkMemoryBarrier2, gd_VkMemoryBarrier2],
    VkMemoryDedicatedAllocateInfo: [ge_VkMemoryDedicatedAllocateInfo, gd_VkMemoryDedicatedAllocateInfo],
    VkMemoryDedicatedRequirements: [ge_VkMemoryDedicatedRequirements, gd_VkMemoryDedicatedRequirements],
    VkMemoryHeap: [ge_VkMemoryHeap, gd_VkMemoryHeap],
    VkMemoryMapInfo: [ge_VkMemoryMapInfo, null],
    VkMemoryOpaqueCaptureAddressAllocateInfo: [ge_VkMemoryOpaqueCaptureAddressAllocateInfo, gd_VkMemoryOpaqueCaptureAddressAllocateInfo],
    VkMemoryRequirements: [ge_VkMemoryRequirements, gd_VkMemoryRequirements],
    VkMemoryRequirements2: [ge_VkMemoryRequirements2, gd_VkMemoryRequirements2],
    VkMemoryToImageCopy: [ge_VkMemoryToImageCopy, null],
    VkMemoryType: [ge_VkMemoryType, gd_VkMemoryType],
    VkMemoryUnmapInfo: [ge_VkMemoryUnmapInfo, null],
    VkNativeBufferANDROID: [ge_VkNativeBufferANDROID, gd_VkNativeBufferANDROID],
    VkNativeBufferUsage2ANDROID: [ge_VkNativeBufferUsage2ANDROID, gd_VkNativeBufferUsage2ANDROID],
    VkOffset2D: [ge_VkOffset2D, gd_VkOffset2D],
    VkOffset3D: [ge_VkOffset3D, null],
    VkPhysicalDevice16BitStorageFeatures: [ge_VkPhysicalDevice16BitStorageFeatures, gd_VkPhysicalDevice16BitStorageFeatures],
    VkPhysicalDevice4444FormatsFeaturesEXT: [ge_VkPhysicalDevice4444FormatsFeaturesEXT, gd_VkPhysicalDevice4444FormatsFeaturesEXT],
    VkPhysicalDevice8BitStorageFeatures: [ge_VkPhysicalDevice8BitStorageFeatures, gd_VkPhysicalDevice8BitStorageFeatures],
    VkPhysicalDeviceBufferDeviceAddressFeatures: [ge_VkPhysicalDeviceBufferDeviceAddressFeatures, gd_VkPhysicalDeviceBufferDeviceAddressFeatures],
    VkPhysicalDeviceColorWriteEnableFeaturesEXT: [ge_VkPhysicalDeviceColorWriteEnableFeaturesEXT, gd_VkPhysicalDeviceColorWriteEnableFeaturesEXT],
    VkPhysicalDeviceCustomBorderColorFeaturesEXT: [ge_VkPhysicalDeviceCustomBorderColorFeaturesEXT, gd_VkPhysicalDeviceCustomBorderColorFeaturesEXT],
    VkPhysicalDeviceCustomBorderColorPropertiesEXT: [ge_VkPhysicalDeviceCustomBorderColorPropertiesEXT, gd_VkPhysicalDeviceCustomBorderColorPropertiesEXT],
    VkPhysicalDeviceDepthClipEnableFeaturesEXT: [ge_VkPhysicalDeviceDepthClipEnableFeaturesEXT, gd_VkPhysicalDeviceDepthClipEnableFeaturesEXT],
    VkPhysicalDeviceDepthStencilResolveProperties: [ge_VkPhysicalDeviceDepthStencilResolveProperties, gd_VkPhysicalDeviceDepthStencilResolveProperties],
    VkPhysicalDeviceDescriptorIndexingFeatures: [ge_VkPhysicalDeviceDescriptorIndexingFeatures, gd_VkPhysicalDeviceDescriptorIndexingFeatures],
    VkPhysicalDeviceDescriptorIndexingProperties: [ge_VkPhysicalDeviceDescriptorIndexingProperties, gd_VkPhysicalDeviceDescriptorIndexingProperties],
    VkPhysicalDeviceDeviceMemoryReportFeaturesEXT: [ge_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT, gd_VkPhysicalDeviceDeviceMemoryReportFeaturesEXT],
    VkPhysicalDeviceDriverProperties: [ge_VkPhysicalDeviceDriverProperties, gd_VkPhysicalDeviceDriverProperties],
    VkPhysicalDeviceDynamicRenderingFeatures: [ge_VkPhysicalDeviceDynamicRenderingFeatures, gd_VkPhysicalDeviceDynamicRenderingFeatures],
    VkPhysicalDeviceDynamicRenderingLocalReadFeatures: [ge_VkPhysicalDeviceDynamicRenderingLocalReadFeatures, gd_VkPhysicalDeviceDynamicRenderingLocalReadFeatures],
    VkPhysicalDeviceExtendedDynamicState2FeaturesEXT: [ge_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT, gd_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT],
    VkPhysicalDeviceExtendedDynamicStateFeaturesEXT: [ge_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT, gd_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT],
    VkPhysicalDeviceExternalBufferInfo: [ge_VkPhysicalDeviceExternalBufferInfo, null],
    VkPhysicalDeviceExternalFenceInfo: [ge_VkPhysicalDeviceExternalFenceInfo, null],
    VkPhysicalDeviceExternalImageFormatInfo: [ge_VkPhysicalDeviceExternalImageFormatInfo, gd_VkPhysicalDeviceExternalImageFormatInfo],
    VkPhysicalDeviceExternalSemaphoreInfo: [ge_VkPhysicalDeviceExternalSemaphoreInfo, null],
    VkPhysicalDeviceFeatures: [ge_VkPhysicalDeviceFeatures, gd_VkPhysicalDeviceFeatures],
    VkPhysicalDeviceFeatures2: [ge_VkPhysicalDeviceFeatures2, gd_VkPhysicalDeviceFeatures2],
    VkPhysicalDeviceFloatControlsProperties: [ge_VkPhysicalDeviceFloatControlsProperties, gd_VkPhysicalDeviceFloatControlsProperties],
    VkPhysicalDeviceFragmentDensityMapFeaturesEXT: [ge_VkPhysicalDeviceFragmentDensityMapFeaturesEXT, gd_VkPhysicalDeviceFragmentDensityMapFeaturesEXT],
    VkPhysicalDeviceFragmentDensityMapPropertiesEXT: [ge_VkPhysicalDeviceFragmentDensityMapPropertiesEXT, gd_VkPhysicalDeviceFragmentDensityMapPropertiesEXT],
    VkPhysicalDeviceGlobalPriorityQueryFeatures: [ge_VkPhysicalDeviceGlobalPriorityQueryFeatures, gd_VkPhysicalDeviceGlobalPriorityQueryFeatures],
    VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT: [ge_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT, gd_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT],
    VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT: [ge_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT, gd_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT],
    VkPhysicalDeviceGroupProperties: [ge_VkPhysicalDeviceGroupProperties, gd_VkPhysicalDeviceGroupProperties],
    VkPhysicalDeviceHostImageCopyFeatures: [ge_VkPhysicalDeviceHostImageCopyFeatures, gd_VkPhysicalDeviceHostImageCopyFeatures],
    VkPhysicalDeviceHostImageCopyProperties: [ge_VkPhysicalDeviceHostImageCopyProperties, gd_VkPhysicalDeviceHostImageCopyProperties],
    VkPhysicalDeviceHostQueryResetFeatures: [ge_VkPhysicalDeviceHostQueryResetFeatures, gd_VkPhysicalDeviceHostQueryResetFeatures],
    VkPhysicalDeviceIDProperties: [ge_VkPhysicalDeviceIDProperties, gd_VkPhysicalDeviceIDProperties],
    VkPhysicalDeviceImageCompressionControlFeaturesEXT: [ge_VkPhysicalDeviceImageCompressionControlFeaturesEXT, gd_VkPhysicalDeviceImageCompressionControlFeaturesEXT],
    VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT: [ge_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT, gd_VkPhysicalDeviceImageCompressionControlSwapchainFeaturesEXT],
    VkPhysicalDeviceImageDrmFormatModifierInfoEXT: [ge_VkPhysicalDeviceImageDrmFormatModifierInfoEXT, gd_VkPhysicalDeviceImageDrmFormatModifierInfoEXT],
    VkPhysicalDeviceImageFormatInfo2: [ge_VkPhysicalDeviceImageFormatInfo2, null],
    VkPhysicalDeviceImageRobustnessFeatures: [ge_VkPhysicalDeviceImageRobustnessFeatures, gd_VkPhysicalDeviceImageRobustnessFeatures],
    VkPhysicalDeviceImagelessFramebufferFeatures: [ge_VkPhysicalDeviceImagelessFramebufferFeatures, gd_VkPhysicalDeviceImagelessFramebufferFeatures],
    VkPhysicalDeviceIndexTypeUint8Features: [ge_VkPhysicalDeviceIndexTypeUint8Features, gd_VkPhysicalDeviceIndexTypeUint8Features],
    VkPhysicalDeviceInlineUniformBlockFeatures: [ge_VkPhysicalDeviceInlineUniformBlockFeatures, gd_VkPhysicalDeviceInlineUniformBlockFeatures],
    VkPhysicalDeviceInlineUniformBlockProperties: [ge_VkPhysicalDeviceInlineUniformBlockProperties, gd_VkPhysicalDeviceInlineUniformBlockProperties],
    VkPhysicalDeviceLimits: [ge_VkPhysicalDeviceLimits, gd_VkPhysicalDeviceLimits],
    VkPhysicalDeviceLineRasterizationFeatures: [ge_VkPhysicalDeviceLineRasterizationFeatures, gd_VkPhysicalDeviceLineRasterizationFeatures],
    VkPhysicalDeviceLineRasterizationProperties: [ge_VkPhysicalDeviceLineRasterizationProperties, gd_VkPhysicalDeviceLineRasterizationProperties],
    VkPhysicalDeviceMaintenance3Properties: [ge_VkPhysicalDeviceMaintenance3Properties, gd_VkPhysicalDeviceMaintenance3Properties],
    VkPhysicalDeviceMaintenance4Features: [ge_VkPhysicalDeviceMaintenance4Features, gd_VkPhysicalDeviceMaintenance4Features],
    VkPhysicalDeviceMaintenance4Properties: [ge_VkPhysicalDeviceMaintenance4Properties, gd_VkPhysicalDeviceMaintenance4Properties],
    VkPhysicalDeviceMaintenance5Features: [ge_VkPhysicalDeviceMaintenance5Features, gd_VkPhysicalDeviceMaintenance5Features],
    VkPhysicalDeviceMaintenance5Properties: [ge_VkPhysicalDeviceMaintenance5Properties, gd_VkPhysicalDeviceMaintenance5Properties],
    VkPhysicalDeviceMaintenance6Features: [ge_VkPhysicalDeviceMaintenance6Features, gd_VkPhysicalDeviceMaintenance6Features],
    VkPhysicalDeviceMaintenance6Properties: [ge_VkPhysicalDeviceMaintenance6Properties, gd_VkPhysicalDeviceMaintenance6Properties],
    VkPhysicalDeviceMemoryBudgetPropertiesEXT: [ge_VkPhysicalDeviceMemoryBudgetPropertiesEXT, gd_VkPhysicalDeviceMemoryBudgetPropertiesEXT],
    VkPhysicalDeviceMemoryProperties: [ge_VkPhysicalDeviceMemoryProperties, gd_VkPhysicalDeviceMemoryProperties],
    VkPhysicalDeviceMemoryProperties2: [ge_VkPhysicalDeviceMemoryProperties2, gd_VkPhysicalDeviceMemoryProperties2],
    VkPhysicalDeviceMultiviewFeatures: [ge_VkPhysicalDeviceMultiviewFeatures, gd_VkPhysicalDeviceMultiviewFeatures],
    VkPhysicalDeviceMultiviewProperties: [ge_VkPhysicalDeviceMultiviewProperties, gd_VkPhysicalDeviceMultiviewProperties],
    VkPhysicalDevicePipelineCreationCacheControlFeatures: [ge_VkPhysicalDevicePipelineCreationCacheControlFeatures, gd_VkPhysicalDevicePipelineCreationCacheControlFeatures],
    VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR: [ge_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR, gd_VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR],
    VkPhysicalDevicePipelineProtectedAccessFeatures: [ge_VkPhysicalDevicePipelineProtectedAccessFeatures, gd_VkPhysicalDevicePipelineProtectedAccessFeatures],
    VkPhysicalDevicePipelineRobustnessFeatures: [ge_VkPhysicalDevicePipelineRobustnessFeatures, gd_VkPhysicalDevicePipelineRobustnessFeatures],
    VkPhysicalDevicePipelineRobustnessProperties: [ge_VkPhysicalDevicePipelineRobustnessProperties, gd_VkPhysicalDevicePipelineRobustnessProperties],
    VkPhysicalDevicePointClippingProperties: [ge_VkPhysicalDevicePointClippingProperties, gd_VkPhysicalDevicePointClippingProperties],
    VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT: [ge_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT, gd_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT],
    VkPhysicalDevicePrivateDataFeatures: [ge_VkPhysicalDevicePrivateDataFeatures, gd_VkPhysicalDevicePrivateDataFeatures],
    VkPhysicalDeviceProperties: [ge_VkPhysicalDeviceProperties, gd_VkPhysicalDeviceProperties],
    VkPhysicalDeviceProperties2: [ge_VkPhysicalDeviceProperties2, gd_VkPhysicalDeviceProperties2],
    VkPhysicalDeviceProtectedMemoryFeatures: [ge_VkPhysicalDeviceProtectedMemoryFeatures, gd_VkPhysicalDeviceProtectedMemoryFeatures],
    VkPhysicalDeviceProtectedMemoryProperties: [ge_VkPhysicalDeviceProtectedMemoryProperties, gd_VkPhysicalDeviceProtectedMemoryProperties],
    VkPhysicalDeviceProvokingVertexFeaturesEXT: [ge_VkPhysicalDeviceProvokingVertexFeaturesEXT, gd_VkPhysicalDeviceProvokingVertexFeaturesEXT],
    VkPhysicalDeviceProvokingVertexPropertiesEXT: [ge_VkPhysicalDeviceProvokingVertexPropertiesEXT, gd_VkPhysicalDeviceProvokingVertexPropertiesEXT],
    VkPhysicalDevicePushDescriptorProperties: [ge_VkPhysicalDevicePushDescriptorProperties, gd_VkPhysicalDevicePushDescriptorProperties],
    VkPhysicalDeviceSamplerFilterMinmaxProperties: [ge_VkPhysicalDeviceSamplerFilterMinmaxProperties, gd_VkPhysicalDeviceSamplerFilterMinmaxProperties],
    VkPhysicalDeviceSamplerYcbcrConversionFeatures: [ge_VkPhysicalDeviceSamplerYcbcrConversionFeatures, gd_VkPhysicalDeviceSamplerYcbcrConversionFeatures],
    VkPhysicalDeviceScalarBlockLayoutFeatures: [ge_VkPhysicalDeviceScalarBlockLayoutFeatures, gd_VkPhysicalDeviceScalarBlockLayoutFeatures],
    VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures: [ge_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures, gd_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures],
    VkPhysicalDeviceShaderAtomicInt64Features: [ge_VkPhysicalDeviceShaderAtomicInt64Features, gd_VkPhysicalDeviceShaderAtomicInt64Features],
    VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures: [ge_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures, gd_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures],
    VkPhysicalDeviceShaderDrawParametersFeatures: [ge_VkPhysicalDeviceShaderDrawParametersFeatures, gd_VkPhysicalDeviceShaderDrawParametersFeatures],
    VkPhysicalDeviceShaderExpectAssumeFeatures: [ge_VkPhysicalDeviceShaderExpectAssumeFeatures, gd_VkPhysicalDeviceShaderExpectAssumeFeatures],
    VkPhysicalDeviceShaderFloat16Int8Features: [ge_VkPhysicalDeviceShaderFloat16Int8Features, gd_VkPhysicalDeviceShaderFloat16Int8Features],
    VkPhysicalDeviceShaderFloatControls2Features: [ge_VkPhysicalDeviceShaderFloatControls2Features, gd_VkPhysicalDeviceShaderFloatControls2Features],
    VkPhysicalDeviceShaderIntegerDotProductFeatures: [ge_VkPhysicalDeviceShaderIntegerDotProductFeatures, gd_VkPhysicalDeviceShaderIntegerDotProductFeatures],
    VkPhysicalDeviceShaderIntegerDotProductProperties: [ge_VkPhysicalDeviceShaderIntegerDotProductProperties, gd_VkPhysicalDeviceShaderIntegerDotProductProperties],
    VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures: [ge_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures, gd_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures],
    VkPhysicalDeviceShaderSubgroupRotateFeatures: [ge_VkPhysicalDeviceShaderSubgroupRotateFeatures, gd_VkPhysicalDeviceShaderSubgroupRotateFeatures],
    VkPhysicalDeviceShaderTerminateInvocationFeatures: [ge_VkPhysicalDeviceShaderTerminateInvocationFeatures, gd_VkPhysicalDeviceShaderTerminateInvocationFeatures],
    VkPhysicalDeviceSparseImageFormatInfo2: [ge_VkPhysicalDeviceSparseImageFormatInfo2, null],
    VkPhysicalDeviceSparseProperties: [ge_VkPhysicalDeviceSparseProperties, gd_VkPhysicalDeviceSparseProperties],
    VkPhysicalDeviceSubgroupProperties: [ge_VkPhysicalDeviceSubgroupProperties, gd_VkPhysicalDeviceSubgroupProperties],
    VkPhysicalDeviceSubgroupSizeControlFeatures: [ge_VkPhysicalDeviceSubgroupSizeControlFeatures, gd_VkPhysicalDeviceSubgroupSizeControlFeatures],
    VkPhysicalDeviceSubgroupSizeControlProperties: [ge_VkPhysicalDeviceSubgroupSizeControlProperties, gd_VkPhysicalDeviceSubgroupSizeControlProperties],
    VkPhysicalDeviceSynchronization2Features: [ge_VkPhysicalDeviceSynchronization2Features, gd_VkPhysicalDeviceSynchronization2Features],
    VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT: [ge_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT, gd_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT],
    VkPhysicalDeviceTexelBufferAlignmentProperties: [ge_VkPhysicalDeviceTexelBufferAlignmentProperties, gd_VkPhysicalDeviceTexelBufferAlignmentProperties],
    VkPhysicalDeviceTextureCompressionASTCHDRFeatures: [ge_VkPhysicalDeviceTextureCompressionASTCHDRFeatures, gd_VkPhysicalDeviceTextureCompressionASTCHDRFeatures],
    VkPhysicalDeviceTimelineSemaphoreFeatures: [ge_VkPhysicalDeviceTimelineSemaphoreFeatures, gd_VkPhysicalDeviceTimelineSemaphoreFeatures],
    VkPhysicalDeviceTimelineSemaphoreProperties: [ge_VkPhysicalDeviceTimelineSemaphoreProperties, gd_VkPhysicalDeviceTimelineSemaphoreProperties],
    VkPhysicalDeviceToolProperties: [ge_VkPhysicalDeviceToolProperties, gd_VkPhysicalDeviceToolProperties],
    VkPhysicalDeviceTransformFeedbackFeaturesEXT: [ge_VkPhysicalDeviceTransformFeedbackFeaturesEXT, gd_VkPhysicalDeviceTransformFeedbackFeaturesEXT],
    VkPhysicalDeviceTransformFeedbackPropertiesEXT: [ge_VkPhysicalDeviceTransformFeedbackPropertiesEXT, gd_VkPhysicalDeviceTransformFeedbackPropertiesEXT],
    VkPhysicalDeviceUniformBufferStandardLayoutFeatures: [ge_VkPhysicalDeviceUniformBufferStandardLayoutFeatures, gd_VkPhysicalDeviceUniformBufferStandardLayoutFeatures],
    VkPhysicalDeviceVariablePointersFeatures: [ge_VkPhysicalDeviceVariablePointersFeatures, gd_VkPhysicalDeviceVariablePointersFeatures],
    VkPhysicalDeviceVertexAttributeDivisorFeatures: [ge_VkPhysicalDeviceVertexAttributeDivisorFeatures, gd_VkPhysicalDeviceVertexAttributeDivisorFeatures],
    VkPhysicalDeviceVertexAttributeDivisorProperties: [ge_VkPhysicalDeviceVertexAttributeDivisorProperties, gd_VkPhysicalDeviceVertexAttributeDivisorProperties],
    VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT: [ge_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT, gd_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT],
    VkPhysicalDeviceVulkan11Features: [ge_VkPhysicalDeviceVulkan11Features, gd_VkPhysicalDeviceVulkan11Features],
    VkPhysicalDeviceVulkan11Properties: [ge_VkPhysicalDeviceVulkan11Properties, gd_VkPhysicalDeviceVulkan11Properties],
    VkPhysicalDeviceVulkan12Features: [ge_VkPhysicalDeviceVulkan12Features, gd_VkPhysicalDeviceVulkan12Features],
    VkPhysicalDeviceVulkan12Properties: [ge_VkPhysicalDeviceVulkan12Properties, gd_VkPhysicalDeviceVulkan12Properties],
    VkPhysicalDeviceVulkan13Features: [ge_VkPhysicalDeviceVulkan13Features, gd_VkPhysicalDeviceVulkan13Features],
    VkPhysicalDeviceVulkan13Properties: [ge_VkPhysicalDeviceVulkan13Properties, gd_VkPhysicalDeviceVulkan13Properties],
    VkPhysicalDeviceVulkan14Features: [ge_VkPhysicalDeviceVulkan14Features, gd_VkPhysicalDeviceVulkan14Features],
    VkPhysicalDeviceVulkan14Properties: [ge_VkPhysicalDeviceVulkan14Properties, gd_VkPhysicalDeviceVulkan14Properties],
    VkPhysicalDeviceVulkanMemoryModelFeatures: [ge_VkPhysicalDeviceVulkanMemoryModelFeatures, gd_VkPhysicalDeviceVulkanMemoryModelFeatures],
    VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT: [ge_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT, gd_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT],
    VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures: [ge_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures, gd_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures],
    VkPipelineCacheCreateInfo: [ge_VkPipelineCacheCreateInfo, null],
    VkPipelineColorBlendAttachmentState: [ge_VkPipelineColorBlendAttachmentState, null],
    VkPipelineColorBlendStateCreateInfo: [ge_VkPipelineColorBlendStateCreateInfo, null],
    VkPipelineColorWriteCreateInfoEXT: [ge_VkPipelineColorWriteCreateInfoEXT, gd_VkPipelineColorWriteCreateInfoEXT],
    VkPipelineCreateFlags2CreateInfo: [ge_VkPipelineCreateFlags2CreateInfo, gd_VkPipelineCreateFlags2CreateInfo],
    VkPipelineCreationFeedback: [ge_VkPipelineCreationFeedback, gd_VkPipelineCreationFeedback],
    VkPipelineCreationFeedbackCreateInfo: [ge_VkPipelineCreationFeedbackCreateInfo, gd_VkPipelineCreationFeedbackCreateInfo],
    VkPipelineDepthStencilStateCreateInfo: [ge_VkPipelineDepthStencilStateCreateInfo, null],
    VkPipelineDynamicStateCreateInfo: [ge_VkPipelineDynamicStateCreateInfo, null],
    VkPipelineExecutableInfoKHR: [ge_VkPipelineExecutableInfoKHR, null],
    VkPipelineExecutableInternalRepresentationKHR: [ge_VkPipelineExecutableInternalRepresentationKHR, gd_VkPipelineExecutableInternalRepresentationKHR],
    VkPipelineExecutablePropertiesKHR: [ge_VkPipelineExecutablePropertiesKHR, gd_VkPipelineExecutablePropertiesKHR],
    VkPipelineExecutableStatisticKHR: [ge_VkPipelineExecutableStatisticKHR, gd_VkPipelineExecutableStatisticKHR],
    VkPipelineExecutableStatisticValueKHR: [ge_VkPipelineExecutableStatisticValueKHR, gd_VkPipelineExecutableStatisticValueKHR],
    VkPipelineInfoKHR: [ge_VkPipelineInfoKHR, null],
    VkPipelineInputAssemblyStateCreateInfo: [ge_VkPipelineInputAssemblyStateCreateInfo, null],
    VkPipelineLayoutCreateInfo: [ge_VkPipelineLayoutCreateInfo, gd_VkPipelineLayoutCreateInfo],
    VkPipelineMultisampleStateCreateInfo: [ge_VkPipelineMultisampleStateCreateInfo, null],
    VkPipelineRasterizationDepthClipStateCreateInfoEXT: [ge_VkPipelineRasterizationDepthClipStateCreateInfoEXT, gd_VkPipelineRasterizationDepthClipStateCreateInfoEXT],
    VkPipelineRasterizationLineStateCreateInfo: [ge_VkPipelineRasterizationLineStateCreateInfo, gd_VkPipelineRasterizationLineStateCreateInfo],
    VkPipelineRasterizationProvokingVertexStateCreateInfoEXT: [ge_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT, gd_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT],
    VkPipelineRasterizationStateCreateInfo: [ge_VkPipelineRasterizationStateCreateInfo, null],
    VkPipelineRasterizationStateStreamCreateInfoEXT: [ge_VkPipelineRasterizationStateStreamCreateInfoEXT, gd_VkPipelineRasterizationStateStreamCreateInfoEXT],
    VkPipelineRenderingCreateInfo: [ge_VkPipelineRenderingCreateInfo, gd_VkPipelineRenderingCreateInfo],
    VkPipelineRobustnessCreateInfo: [ge_VkPipelineRobustnessCreateInfo, gd_VkPipelineRobustnessCreateInfo],
    VkPipelineShaderStageCreateInfo: [ge_VkPipelineShaderStageCreateInfo, null],
    VkPipelineShaderStageRequiredSubgroupSizeCreateInfo: [ge_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo, gd_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo],
    VkPipelineTessellationDomainOriginStateCreateInfo: [ge_VkPipelineTessellationDomainOriginStateCreateInfo, gd_VkPipelineTessellationDomainOriginStateCreateInfo],
    VkPipelineTessellationStateCreateInfo: [ge_VkPipelineTessellationStateCreateInfo, null],
    VkPipelineVertexInputDivisorStateCreateInfo: [ge_VkPipelineVertexInputDivisorStateCreateInfo, gd_VkPipelineVertexInputDivisorStateCreateInfo],
    VkPipelineVertexInputStateCreateInfo: [ge_VkPipelineVertexInputStateCreateInfo, null],
    VkPipelineViewportStateCreateInfo: [ge_VkPipelineViewportStateCreateInfo, null],
    VkPresentRegionKHR: [ge_VkPresentRegionKHR, gd_VkPresentRegionKHR],
    VkPresentRegionsKHR: [ge_VkPresentRegionsKHR, gd_VkPresentRegionsKHR],
    VkPrivateDataSlotCreateInfo: [ge_VkPrivateDataSlotCreateInfo, null],
    VkProtectedSubmitInfo: [ge_VkProtectedSubmitInfo, gd_VkProtectedSubmitInfo],
    VkPushConstantRange: [ge_VkPushConstantRange, gd_VkPushConstantRange],
    VkPushConstantsInfo: [ge_VkPushConstantsInfo, null],
    VkPushDescriptorSetInfo: [ge_VkPushDescriptorSetInfo, null],
    VkPushDescriptorSetWithTemplateInfo: [ge_VkPushDescriptorSetWithTemplateInfo, null],
    VkQueryPoolCreateInfo: [ge_VkQueryPoolCreateInfo, null],
    VkQueueFamilyGlobalPriorityProperties: [ge_VkQueueFamilyGlobalPriorityProperties, gd_VkQueueFamilyGlobalPriorityProperties],
    VkQueueFamilyProperties: [ge_VkQueueFamilyProperties, gd_VkQueueFamilyProperties],
    VkQueueFamilyProperties2: [ge_VkQueueFamilyProperties2, gd_VkQueueFamilyProperties2],
    VkRect2D: [ge_VkRect2D, gd_VkRect2D],
    VkRectLayerKHR: [ge_VkRectLayerKHR, gd_VkRectLayerKHR],
    VkRenderPassAttachmentBeginInfo: [ge_VkRenderPassAttachmentBeginInfo, gd_VkRenderPassAttachmentBeginInfo],
    VkRenderPassBeginInfo: [ge_VkRenderPassBeginInfo, null],
    VkRenderPassCreateInfo: [ge_VkRenderPassCreateInfo, null],
    VkRenderPassCreateInfo2: [ge_VkRenderPassCreateInfo2, null],
    VkRenderPassFragmentDensityMapCreateInfoEXT: [ge_VkRenderPassFragmentDensityMapCreateInfoEXT, gd_VkRenderPassFragmentDensityMapCreateInfoEXT],
    VkRenderPassInputAttachmentAspectCreateInfo: [ge_VkRenderPassInputAttachmentAspectCreateInfo, gd_VkRenderPassInputAttachmentAspectCreateInfo],
    VkRenderPassMultiviewCreateInfo: [ge_VkRenderPassMultiviewCreateInfo, gd_VkRenderPassMultiviewCreateInfo],
    VkRenderingAreaInfo: [ge_VkRenderingAreaInfo, null],
    VkRenderingAttachmentInfo: [ge_VkRenderingAttachmentInfo, null],
    VkRenderingAttachmentLocationInfo: [ge_VkRenderingAttachmentLocationInfo, gd_VkRenderingAttachmentLocationInfo],
    VkRenderingFragmentDensityMapAttachmentInfoEXT: [ge_VkRenderingFragmentDensityMapAttachmentInfoEXT, gd_VkRenderingFragmentDensityMapAttachmentInfoEXT],
    VkRenderingInfo: [ge_VkRenderingInfo, null],
    VkRenderingInputAttachmentIndexInfo: [ge_VkRenderingInputAttachmentIndexInfo, gd_VkRenderingInputAttachmentIndexInfo],
    VkResolveImageInfo2: [ge_VkResolveImageInfo2, null],
    VkSamplerCreateInfo: [ge_VkSamplerCreateInfo, null],
    VkSamplerCustomBorderColorCreateInfoEXT: [ge_VkSamplerCustomBorderColorCreateInfoEXT, gd_VkSamplerCustomBorderColorCreateInfoEXT],
    VkSamplerReductionModeCreateInfo: [ge_VkSamplerReductionModeCreateInfo, gd_VkSamplerReductionModeCreateInfo],
    VkSamplerYcbcrConversionCreateInfo: [ge_VkSamplerYcbcrConversionCreateInfo, null],
    VkSamplerYcbcrConversionImageFormatProperties: [ge_VkSamplerYcbcrConversionImageFormatProperties, gd_VkSamplerYcbcrConversionImageFormatProperties],
    VkSamplerYcbcrConversionInfo: [ge_VkSamplerYcbcrConversionInfo, gd_VkSamplerYcbcrConversionInfo],
    VkSemaphoreCreateInfo: [ge_VkSemaphoreCreateInfo, null],
    VkSemaphoreGetFdInfoKHR: [ge_VkSemaphoreGetFdInfoKHR, null],
    VkSemaphoreSignalInfo: [ge_VkSemaphoreSignalInfo, null],
    VkSemaphoreSubmitInfo: [ge_VkSemaphoreSubmitInfo, null],
    VkSemaphoreTypeCreateInfo: [ge_VkSemaphoreTypeCreateInfo, gd_VkSemaphoreTypeCreateInfo],
    VkSemaphoreWaitInfo: [ge_VkSemaphoreWaitInfo, null],
    VkShaderModuleCreateInfo: [ge_VkShaderModuleCreateInfo, gd_VkShaderModuleCreateInfo],
    VkSparseBufferMemoryBindInfo: [ge_VkSparseBufferMemoryBindInfo, null],
    VkSparseImageFormatProperties: [ge_VkSparseImageFormatProperties, gd_VkSparseImageFormatProperties],
    VkSparseImageFormatProperties2: [ge_VkSparseImageFormatProperties2, gd_VkSparseImageFormatProperties2],
    VkSparseImageMemoryBind: [ge_VkSparseImageMemoryBind, null],
    VkSparseImageMemoryBindInfo: [ge_VkSparseImageMemoryBindInfo, null],
    VkSparseImageMemoryRequirements: [ge_VkSparseImageMemoryRequirements, gd_VkSparseImageMemoryRequirements],
    VkSparseImageMemoryRequirements2: [ge_VkSparseImageMemoryRequirements2, gd_VkSparseImageMemoryRequirements2],
    VkSparseImageOpaqueMemoryBindInfo: [ge_VkSparseImageOpaqueMemoryBindInfo, null],
    VkSparseMemoryBind: [ge_VkSparseMemoryBind, null],
    VkSpecializationInfo: [ge_VkSpecializationInfo, null],
    VkSpecializationMapEntry: [ge_VkSpecializationMapEntry, null],
    VkStencilOpState: [ge_VkStencilOpState, null],
    VkSubmitInfo: [ge_VkSubmitInfo, null],
    VkSubmitInfo2: [ge_VkSubmitInfo2, null],
    VkSubpassBeginInfo: [ge_VkSubpassBeginInfo, null],
    VkSubpassDependency: [ge_VkSubpassDependency, null],
    VkSubpassDependency2: [ge_VkSubpassDependency2, null],
    VkSubpassDescription: [ge_VkSubpassDescription, null],
    VkSubpassDescription2: [ge_VkSubpassDescription2, null],
    VkSubpassDescriptionDepthStencilResolve: [ge_VkSubpassDescriptionDepthStencilResolve, gd_VkSubpassDescriptionDepthStencilResolve],
    VkSubpassEndInfo: [ge_VkSubpassEndInfo, null],
    VkSubresourceHostMemcpySize: [ge_VkSubresourceHostMemcpySize, gd_VkSubresourceHostMemcpySize],
    VkSubresourceLayout: [ge_VkSubresourceLayout, gd_VkSubresourceLayout],
    VkSubresourceLayout2: [ge_VkSubresourceLayout2, gd_VkSubresourceLayout2],
    VkTimelineSemaphoreSubmitInfo: [ge_VkTimelineSemaphoreSubmitInfo, gd_VkTimelineSemaphoreSubmitInfo],
    VkVertexInputAttributeDescription: [ge_VkVertexInputAttributeDescription, null],
    VkVertexInputBindingDescription: [ge_VkVertexInputBindingDescription, null],
    VkVertexInputBindingDivisorDescription: [ge_VkVertexInputBindingDivisorDescription, gd_VkVertexInputBindingDivisorDescription],
    VkViewport: [ge_VkViewport, null],
    VkWriteDescriptorSet: [ge_VkWriteDescriptorSet, null],
    VkWriteDescriptorSetInlineUniformBlock: [ge_VkWriteDescriptorSetInlineUniformBlock, gd_VkWriteDescriptorSetInlineUniformBlock],
};
                                                                                                   source/v64/tests/devices/gfxstream_protocol.js                                                      0000644 0000000 0000000 00000034470 00000000000 016737  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// gfxstream's Vulkan wire format of src/graphics_adapters/virtio_gpu/
// gfxstream_protocol.js (generated by tools/gfxstream_protocol_gen.mjs from
// the guest's C) against the guest's own code: gfxstream_protocol_vectors.txt
// holds structs the guest's request writers wrote (tools/gfxstream_oracle),
// which must decode to what they were made of and encode again
// (tests/devices/gfxstream_guest_protocol.js) to the same bytes; and replies
// this encoder wrote, with what the guest's reply readers read of them
// (written again by the guest), which must still come out the same.
//
// With --oracle <tools/gfxstream_oracle's build>, it writes the vectors again.

import assert from "assert/strict";
import fs from "node:fs";
import url from "node:url";
import { execFileSync } from "node:child_process";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const P = await import("../../src/graphics_adapters/virtio_gpu/gfxstream_protocol.js");
const { GUEST_STRUCTS, GUEST_COMMANDS } = await import("./gfxstream_guest_protocol.js");
const VECTORS = __dirname + "/gfxstream_protocol_vectors.txt";

const unhex = hex => Uint8Array.from(hex.match(/../g) || [], h => parseInt(h, 16));
const hex = bytes => Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
const ROOT_NONE = 0x7FFFFFFF;
// VkStructureType
const S = {
    PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES: 50, PHYSICAL_DEVICE_VULKAN_1_2_FEATURES: 51, PHYSICAL_DEVICE_FEATURES_2: 1000059000,
    PHYSICAL_DEVICE_PROPERTIES_2: 1000059001, IMAGE_FORMAT_PROPERTIES_2: 1000059003, EXTERNAL_IMAGE_FORMAT_PROPERTIES: 1000071001,
    MEMORY_DEDICATED_REQUIREMENTS: 1000127000, MEMORY_REQUIREMENTS_2: 1000146003, PHYSICAL_DEVICE_DRIVER_PROPERTIES: 1000196000,
};

// The replies: objects as the device's Vulkan model fills them
const REPLIES = {
    VkPhysicalDeviceProperties2: { sType: S.PHYSICAL_DEVICE_PROPERTIES_2,
        pNext: { sType: S.PHYSICAL_DEVICE_DRIVER_PROPERTIES, driverID: 10, driverName: "v64", driverInfo: "gfxstream on WebGPU",
            conformanceVersion: { major: 1, minor: 3, subminor: 0, patch: 0 },
            pNext: { sType: S.PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES, pNext: null, deviceUUID: Uint8Array.from({ length: 16 }, (_, i) => i + 1),
                driverUUID: new Uint8Array(16).fill(7), deviceLUID: new Uint8Array(8), deviceNodeMask: 1, deviceLUIDValid: 0, subgroupSize: 4,
                subgroupSupportedStages: 0x1F, subgroupSupportedOperations: 0xFF, subgroupQuadOperationsInAllStages: 1, pointClippingBehavior: 0,
                maxMultiviewViewCount: 6, maxMultiviewInstanceIndex: 1 << 27, protectedNoFault: 0, maxPerSetDescriptors: 1024,
                maxMemoryAllocationSize: 2 ** 31 } },
        properties: { apiVersion: 1 << 22 | 3 << 12, driverVersion: 1, vendorID: 0x1AE0, deviceID: 2, deviceType: 4, deviceName: "v64 WebGPU",
            pipelineCacheUUID: new Uint8Array(16).fill(0xAB),
            limits: { maxImageDimension2D: 8192, maxComputeWorkGroupCount: [65535, 65535, 65535], pointSizeRange: [1, 64],
                timestampPeriod: 1.5, nonCoherentAtomSize: 64, bufferImageGranularity: 1 },
            sparseProperties: {} } },
    VkPhysicalDeviceFeatures2: { sType: S.PHYSICAL_DEVICE_FEATURES_2, features: { robustBufferAccess: 1, samplerAnisotropy: 1 },
        pNext: { sType: S.PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, pNext: null, timelineSemaphore: 1, bufferDeviceAddress: 0, vulkanMemoryModel: 1 } },
    VkPhysicalDeviceMemoryProperties: { memoryTypeCount: 2, memoryTypes: [{ propertyFlags: 1, heapIndex: 0 }, { propertyFlags: 7, heapIndex: 0 }],
        memoryHeapCount: 1, memoryHeaps: [{ size: 2 ** 32, flags: 1 }] },
    VkMemoryRequirements2: { sType: S.MEMORY_REQUIREMENTS_2, memoryRequirements: { size: 0x123000, alignment: 4096, memoryTypeBits: 3 },
        pNext: { sType: S.MEMORY_DEDICATED_REQUIREMENTS, pNext: null, prefersDedicatedAllocation: 1, requiresDedicatedAllocation: 0 } },
    VkQueueFamilyProperties: { queueFlags: 7, queueCount: 1, timestampValidBits: 64, minImageTransferGranularity: { width: 1, height: 1, depth: 1 } },
    VkExtensionProperties: { extensionName: "VK_KHR_swapchain", specVersion: 70 },
    VkFormatProperties: { linearTilingFeatures: 0x1, optimalTilingFeatures: 0x1D401, bufferFeatures: 0x58 },
    VkSubresourceLayout: { offset: 0, size: 640 * 480 * 4, rowPitch: 2560, arrayPitch: 0, depthPitch: 0 },
    VkImageFormatProperties2: { sType: S.IMAGE_FORMAT_PROPERTIES_2,
        imageFormatProperties: { maxExtent: { width: 8192, height: 8192, depth: 1 }, maxMipLevels: 14, maxArrayLayers: 256, sampleCounts: 5, maxResourceSize: 2 ** 31 },
        pNext: { sType: S.EXTERNAL_IMAGE_FORMAT_PROPERTIES, pNext: null,
            externalMemoryProperties: { externalMemoryFeatures: 3, exportFromImportedHandleTypes: 0x400, compatibleHandleTypes: 0x400 } } },
};
const reply_hex = name => {
    const w = new P.GfxWriter(16);
    P.STRUCTS[name][1](w, REPLIES[name], ROOT_NONE);
    return hex(w.result());
};

if(process.argv[2] === "--oracle")
{
    const oracle = process.argv[3];
    const lines = ["# tests/devices/gfxstream_protocol.js --oracle <tools/gfxstream_oracle's build> writes these",
        "# request: what the guest's reservedmarshal_* wrote; reply: this encoder's; guest: the reply as the guest read it, written again"];
    for(const line of execFileSync(oracle, ["requests"], { encoding: "utf8" }).trim().split("\n")) lines.push("request " + line);
    const replies = Object.keys(REPLIES).map(name => name + " " + reply_hex(name)).join("\n") + "\n";
    for(const line of replies.trim().split("\n")) lines.push("reply " + line);
    for(const line of execFileSync(oracle, ["replies"], { input: replies, encoding: "utf8" }).trim().split("\n")) lines.push("guest " + line);
    fs.writeFileSync(VECTORS, lines.join("\n") + "\n");
    console.log("wrote " + VECTORS);
    process.exit(0);
}

const vectors = { request: [], reply: {}, guest: {} };
for(const line of fs.readFileSync(VECTORS, "utf8").split("\n"))
{
    if(!line || line.startsWith("#")) continue;
    const [kind, name, data] = line.split(" ");
    if(kind === "request") vectors.request.push([name, data || ""]);
    else vectors[kind][name] = data || "";
}

/** a request's struct, decoded; the guest's pointers (addresses) as 1 */
const decode = (name, data) => {
    const bytes = unhex(data);
    const r = new P.GfxReader(bytes);
    r.presences = [];
    const o = P.STRUCTS[name][0](r, ROOT_NONE);
    assert.equal(r.p, bytes.length, name + ": all of it read");
    const normal = bytes.slice();
    for(const at of r.presences)
    {
        const set = normal.subarray(at, at + 8).some(b => b);
        normal.fill(0, at, at + 8);
        if(set) normal[at + 7] = 1;
    }
    return { o, normal };
};

// Every request decodes and encodes again to the guest's bytes
const decoded = {};
for(const [name, data] of vectors.request)
{
    const { o, normal } = decode(name, data);
    const w = new P.GfxWriter(16);
    GUEST_STRUCTS[name][0](w, o, ROOT_NONE);
    assert.equal(hex(w.result()), hex(normal), name + ": encoded again");
    (decoded[name] = decoded[name] || []).push(o);
}
console.log("PASS: " + vectors.request.length + " structs of the guest's request writers, decoded and encoded again");

// What they decode to
let o = decoded.VkInstanceCreateInfo[0];
assert.deepEqual(o.ppEnabledExtensionNames, ["VK_KHR_surface", "VK_EXT_debug_utils"]);
assert.equal(o.pApplicationInfo.pApplicationName, "vktest");
assert.equal(o.pApplicationInfo.pEngineName, null);
assert.equal(o.pApplicationInfo.apiVersion, 1 << 22 | 3 << 12);
o = decoded.VkDeviceCreateInfo[0];
assert.equal(o.pNext.sType, S.PHYSICAL_DEVICE_FEATURES_2);
assert.equal(o.pNext.features.samplerAnisotropy, 1);
assert.equal(o.pNext.pNext.shaderDrawParameters, 1, "Vulkan11Features in the chain");
assert.equal(o.pQueueCreateInfos[0].pQueuePriorities[0], 1);
assert.deepEqual(o.ppEnabledExtensionNames, ["VK_KHR_swapchain"]);
assert.equal(o.pEnabledFeatures, null);
o = decoded.VkImageCreateInfo[0];
assert.equal(o.pNext.handle, 77, "VkNativeBufferANDROID's handle: what it points to");
assert.deepEqual([o.pNext.stride, o.pNext.format, o.pNext.usage, o.pNext.usage2.consumer, o.pNext.usage2.producer], [640, 1, 0x300, 5, 6]);
assert.deepEqual([o.extent.width, o.extent.height, o.format, o.usage], [640, 480, 37, 0x17]);
assert.deepEqual(Array.from(o.pQueueFamilyIndices), [0, 1]);
o = decoded.VkMemoryAllocateInfo[0];
assert.equal(o.pNext.colorBuffer, 42, "VkImportColorBufferGOOGLE (the chain's root decides the sType)");
assert.equal(o.pNext.pNext.image, 0x55);
assert.deepEqual([o.allocationSize, o.memoryTypeIndex], [1 << 20, 3]);
o = decoded.VkGraphicsPipelineCreateInfo[0];
assert.equal(o.pStages[1].pName, "main");
assert.equal(o.pStages[1].pSpecializationInfo.dataSize, 4);
assert.deepEqual(Array.from(o.pStages[1].pSpecializationInfo.pData), [4, 3, 2, 1]);
assert.equal(o.pVertexInputState.pVertexAttributeDescriptions[1].offset, 8);
assert.equal(o.pTessellationState, null);
assert.equal(o.pViewportState.pViewports[0].width, 640);
assert.equal(o.pMultisampleState.pSampleMask[0], 0xFFFFFFFF);
assert.deepEqual(Array.from(o.pColorBlendState.blendConstants), [0.25, 0.5, 0.75, 1]);
assert.deepEqual(Array.from(o.pDynamicState.pDynamicStates), [0, 1]);
assert.deepEqual([o.layout, o.renderPass, o.basePipelineIndex], [0x60, 0x61, -1]);
const [sampler, uniform, texel] = decoded.VkWriteDescriptorSet;
assert.equal(sampler.pImageInfo[0].imageView, 0x72);
assert.deepEqual(sampler.pBufferInfo, [], "a buffer pointer of an image descriptor: there, its contents not");
assert.deepEqual(uniform.pBufferInfo.map(b => b.buffer), [0x73, 0x74]);
assert.equal(uniform.pBufferInfo[1].range, 2 ** 64, "VK_WHOLE_SIZE");
assert.deepEqual(texel.pTexelBufferView, [0x75]);
o = decoded.VkDescriptorSetLayoutCreateInfo[0];
assert.deepEqual(o.pBindings[0].pImmutableSamplers, [0x70]);
assert.equal(o.pBindings[1].pImmutableSamplers, null);
o = decoded.VkShaderModuleCreateInfo[0];
assert.equal(o.codeSize, 12);
assert.deepEqual(Array.from(o.pCode), [0x07230203, 0x00010000, 0x0008000a]);
o = decoded.VkSubmitInfo[0];
assert.deepEqual([o.pWaitSemaphores, Array.from(o.pWaitDstStageMask), o.pCommandBuffers, o.pSignalSemaphores], [[1], [0x400], [2, 3], [4]]);
assert.deepEqual([o.pNext.pWaitSemaphoreValues, o.pNext.pSignalSemaphoreValues], [[5], [6]]);
o = decoded.VkRenderPassBeginInfo[0];
assert.deepEqual(Array.from(o.pClearValues[0].color.float32).map(v => Math.round(v * 10) / 10), [0.1, 0.2, 0.3, 1]);
assert.deepEqual([o.renderArea.offset.x, o.renderArea.extent.width], [1, 300]);
o = decoded.VkCommandBufferBeginInfo[0];
assert.equal(o.pInheritanceInfo, null);
console.log("PASS: what they decode to");

// Replies: what the guest reads of this encoder's (and writes again) is what was written
for(const name of Object.keys(REPLIES))
{
    assert.equal(reply_hex(name), vectors.reply[name], name + ": the reply as recorded");
    assert.equal(vectors.guest[name], vectors.reply[name], name + ": the guest read the reply as written");
}
console.log("PASS: " + Object.keys(REPLIES).length + " replies, read by the guest's reply readers as written");

// The commands: each decodes and encodes its parameters (the guest's side
// writes them, the device's reads them)
const by_name = {};
for(const [op, entry] of Object.entries(P.COMMANDS)) by_name[entry[0]] = [+op, ...entry.slice(1)];
assert.equal(Object.keys(by_name).length, Object.keys(GUEST_COMMANDS).length);
const roundtrip = (name, a) => {
    const w = new P.GfxWriter(16);
    GUEST_COMMANDS[name][1](w, a);
    const bytes = w.result();
    const r = new P.GfxReader(bytes);
    const back = by_name[name][1](r);
    assert.equal(r.p, bytes.length, name + ": all of it read");
    return back;
};
let a = roundtrip("vkCreateImage", { device: 5, pCreateInfo: decoded.VkImageCreateInfo[0], pAllocator: null, pImage: 0 });
assert.equal(a.device, 5);
assert.equal(a.pCreateInfo.pNext.handle, 77);
a = roundtrip("vkEnumeratePhysicalDevices", { instance: 3, pPhysicalDeviceCount: 1, pPhysicalDevices: [0] });
assert.deepEqual([a.pPhysicalDeviceCount, a.pPhysicalDevices], [1, [0]]);
a = roundtrip("vkEnumerateDeviceExtensionProperties", { physicalDevice: 3, pLayerName: null, pPropertyCount: 2, pProperties: [{}, {}] });
assert.deepEqual([a.pPropertyCount, a.pProperties.length], [2, 2], "an output array of structs: as long as its count");
a = roundtrip("vkCmdDraw", { commandBuffer: 9, vertexCount: 3, instanceCount: 1, firstVertex: 0, firstInstance: 0 });
assert.deepEqual([a.commandBuffer, a.vertexCount], [undefined, 3], "a command buffer's command: no handle (it is the buffer's)");
assert.ok(by_name.vkCmdDraw[3], "vkCmdDraw is in a command buffer's stream");
a = roundtrip("vkQueueFlushCommandsGOOGLE", { queue: 1, commandBuffer: 2, dataSize: 4, pData: Uint8Array.of(1, 2, 3, 4) });
assert.deepEqual(Array.from(a.pData), [1, 2, 3, 4]);
// a reply: the guest reads what the device wrote
const reply = (name, a, request) => {
    const w = new P.GfxWriter(16);
    by_name[name][2](w, a);
    const r = new P.GfxReader(w.result());
    const back = GUEST_COMMANDS[name][2](r, request);
    assert.equal(r.p, w.result().length, name + ": its reply read");
    return back;
};
a = reply("vkEnumeratePhysicalDevices", { pPhysicalDeviceCount: 1, pPhysicalDevices: [0x1000], ret: 0 }, { pPhysicalDeviceCount: 1, pPhysicalDevices: [0] });
assert.deepEqual([a.pPhysicalDeviceCount, a.pPhysicalDevices, a.ret], [1, [0x1000], 0]);
a = reply("vkCreateImageWithRequirementsGOOGLE", { pImage: 0x2000, pMemoryRequirements: { size: 4096, alignment: 256, memoryTypeBits: 1 }, ret: 0 }, {});
assert.deepEqual([a.pImage, a.pMemoryRequirements.size, a.ret], [0x2000, 4096, 0]);
console.log("PASS: commands of both sides");

// A command as Android's ANGLE wrote it (the A9 scenario: SystemUI's
// pipelines, 4 samples): pSampleMask's (rasterizationSamples + 31) / 32
// words, C's division of integers; the rest after it read right
{
    const payload = unhex(fs.readFileSync(__dirname + "/gfxstream_create_graphics_pipelines.hex", "utf8").trim());
    const r = new P.GfxReader(payload, 4);
    const pipelines = by_name.vkCreateGraphicsPipelines[1](r);
    assert.equal(r.p, payload.length, "vkCreateGraphicsPipelines: all of it read");
    const multisample = pipelines.pCreateInfos[0].pMultisampleState;
    assert.equal(multisample.rasterizationSamples, 4);
    assert.equal(multisample.pSampleMask.length, 1, "one word of sample mask");
    console.log("PASS: ANGLE's vkCreateGraphicsPipelines (a sample mask of 4 samples)");
}
                                                                                                                                                                                                        source/v64/tests/devices/gfxstream_protocol_vectors.txt                                             0000644 0000000 0000000 00000040651 00000000000 020705  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # tests/devices/gfxstream_protocol.js --oracle <tools/gfxstream_oracle's build> writes these
# request: what the guest's reservedmarshal_* wrote; reply: this encoder's; guest: the reply as the guest read it, written again
request VkInstanceCreateInfo 010000000000000000000000000000016bc6dbb0000000000000000000000001041dfddf00000006766b746573740700000000000000000000000000000000304000000000000000000002000000000000020000000e564b5f4b48525f7375726661636500000012564b5f4558545f64656275675f7574696c73
request VkDeviceCreateInfo 03000000000000f078b09b3b78b09b3b0000004031000000310000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000002000000000000000000000000000000010000000000803f0000000000000000010000000000000100000010564b5f4b48525f73776170636861696e0000000000000000
request VkImageCreateInfo 0e0000000000004010f19a3b10f19a3b00000000000000016bc6deb04d0000008002000001000000000300000500000000000000060000000000000000000000010000002500000080020000e00100000100000001000000010000000100000000000000170000000100000002000000000000016bc6da70000000000100000000000000
request VkMemoryAllocateInfo 0500000000000018e8a9a03be8a9a03b0000002019ba9c3b19ba9c3b00000000550000000000000000000000000000002a000000000010000000000003000000
request VkGraphicsPipelineCreateInfo 00000001000000001c000000000000000000000002000000120000000000000000000000010000005100000000000000000000046d61696e0000000000000000120000000000000000000000100000005200000000000000000000046d61696e000000016bc6d9300100000003000000000000000000000000000004000000000000000404030201000000016bc6e4f013000000000000000000000001000000000000001400000000000000020000000000000000000000670000000000000001000000000000006a00000008000000000000016bc6d98014000000000000000000000004000000000000000000000000000000000000016bc6da2816000000000000000000000001000000000000016bc6da100000000000000000000020440000f043000000000000803f01000000000000016bc6d910000000000000000080020000e0010000000000016bc6da701700000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000803f000000016bc6d9b0180000000000000000000000010000000000000000000000000000016bc6d90cffffffff0000000000000000000000016bc6e2d019000000000000000000000001000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000803f000000016bc6deb01a0000000000000000000000000000000300000001000000010000000600000007000000000000000100000000000000000000000f0000000000803e0000003f0000403f0000803f000000016bc6d8e81b000000000000000000000002000000000000000100000060000000000000006100000000000000000000000000000000000000ffffffff
request VkWriteDescriptorSet 2300000000000000760000000000000000000000000000000100000001000000000000016bc6deb07100000000000000720000000000000005000000000000016bc6ddc00000000000000000
request VkWriteDescriptorSet 2300000000000000760000000000000001000000000000000200000006000000000000016bc6deb0000000016bc6ddc073000000000000000000000000000000000100000000000074000000000000000001000000000000ffffffffffffffff0000000000000000
request VkWriteDescriptorSet 230000000000000076000000000000000200000003000000010000000400000000000000000000000000000000000000000000016bc6e4f07500000000000000
request VkDescriptorSetLayoutCreateInfo 2000000000000000000000000200000000000000010000000100000010000000000000016bc6da707000000000000000010000000600000001000000010000000000000000000000
request VkShaderModuleCreateInfo 100000000000000000000000000000000000000c03022307000001000a000800
request VkSubmitInfo 04000000000000309bf29d3b9bf29d3b0000000001000000000000016bc6ddc0050000000000000001000000000000016bc6deb00600000000000000010000000100000000000000000400000200000002000000000000000300000000000000010000000400000000000000
request VkRenderPassCreateInfo 260000000000000000000000010000000000000025000000010000000100000000000000020000000100000000000000eacd9a3b01000000000000000000000000000000010000000000000002000000000000000000000000000000000000000000000000000000
request VkBufferCreateInfo 0c0000000000001840e39b3b40e39b3b00000000000400000000000000000100000000008200000000000000000000000000000000000000
request VkRenderPassBeginInfo 2b000000000000006100000000000000620000000000000001000000020000002c010000c800000001000000000000016bc6dbb0cdcccc3dcdcc4c3e9a99993e0000803f
request VkPipelineLayoutCreateInfo 1e000000000000000000000001000000900000000000000001000000010000000000000010000000
request VkCommandBufferBeginInfo 2a00000000000000010000000000000000000000
request VkImageMemoryBarrier 2d0000000000000000000000000100000000000002000000ffffffffffffffff55000000000000000100000000000000010000000000000001000000
reply VkPhysicalDeviceProperties2 79b09b3b00000218a0c79d3ba0c79d3b000000703200000032000000000000000102030405060708090a0b0c0d0e0f100707070707070707070707070707070700000000000000000100000000000000040000001f000000ff00000001000000000000000600000000000008000000000004000000000080000000000a0000007636340000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000067667873747265616d206f6e20576562475055000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010300000030400001000000e01a0000020000000400000076363420576562475055000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000abababababababababababababababab000000000020000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffff0000ffff0000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c03f000000000000000000000000000000000000803f000080420000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000
reply VkPhysicalDeviceFeatures2 78b09b3b000000d0330000003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
reply VkPhysicalDeviceMemoryProperties 020000000100000000000000070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
reply VkMemoryRequirements2 53049d3b0000001818ba9c3b18ba9c3b0000000001000000000000000030120000000000001000000000000003000000
reply VkQueueFamilyProperties 070000000100000040000000010000000100000001000000
reply VkExtensionProperties 564b5f4b48525f73776170636861696e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000046000000
reply VkFormatProperties 0100000001d4010058000000
reply VkSubresourceLayout 000000000000000000c0120000000000000a00000000000000000000000000000000000000000000
reply VkImageFormatProperties2 7bb09b3b0000002059df9b3b59df9b3b000000000300000000040000000400000020000000200000010000000e00000000010000050000000000008000000000
guest VkPhysicalDeviceProperties2 79b09b3b00000218a0c79d3ba0c79d3b000000703200000032000000000000000102030405060708090a0b0c0d0e0f100707070707070707070707070707070700000000000000000100000000000000040000001f000000ff00000001000000000000000600000000000008000000000004000000000080000000000a0000007636340000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000067667873747265616d206f6e20576562475055000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010300000030400001000000e01a0000020000000400000076363420576562475055000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000abababababababababababababababab000000000020000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffff0000ffff0000ffff000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c03f000000000000000000000000000000000000803f000080420000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000
guest VkPhysicalDeviceFeatures2 78b09b3b000000d0330000003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000001000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
guest VkPhysicalDeviceMemoryProperties 020000000100000000000000070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000100000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
guest VkMemoryRequirements2 53049d3b0000001818ba9c3b18ba9c3b0000000001000000000000000030120000000000001000000000000003000000
guest VkQueueFamilyProperties 070000000100000040000000010000000100000001000000
guest VkExtensionProperties 564b5f4b48525f73776170636861696e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000046000000
guest VkFormatProperties 0100000001d4010058000000
guest VkSubresourceLayout 000000000000000000c0120000000000000a00000000000000000000000000000000000000000000
guest VkImageFormatProperties2 7bb09b3b0000002059df9b3b59df9b3b000000000300000000040000000400000020000000200000010000000e00000000010000050000000000008000000000
                                                                                       source/v64/tests/devices/graphics_adapter.js                                                        0000755 0000000 0000000 00000014140 00000000000 016311  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Display adapters as plugins (src/graphics_adapter.js): graphics_adapter is
// required and checked, the plugin loads only when named, "none" boots
// without a display, snapshots name their adapter and reject another one,
// snapshots from before the plugins still restore, and the VGA BIOS's PCI ROM
// header is made to name the adapter's device.

import assert from "assert/strict";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const ROOT = __dirname + "/../../";
const BASE = {
    wasm_path: ROOT + "build/" + (TEST_RELEASE_BUILD ? "v86.wasm" : "v86-debug.wasm"),
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    memory_size: 32 << 20,
    disable_keyboard: true,
    disable_mouse: true,
    disable_speaker: true,
    net_device: { type: "none" },
    log_level: 0,
};

/**
 * @param {Object} options
 * @return {!Promise<V86>}
 */
async function start(options)
{
    const emulator = new V86({ ...BASE, ...options });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return emulator;
}

// Option checks happen in the constructor, before anything loads
for(const [options, message] of [
    [{}, /graphics_adapter is required/],
    [{ graphics_adapter: "cirrus" }, /Unknown graphics_adapter "cirrus"/],
    [{ graphics_adapter: () => {} }, /use graphics_proxy: true/],
    [{ graphics_adapter: "bochs_vga", vga_memory_size: 8 << 20 }, /vga_memory_size was renamed to vram_size/],
    [{ graphics_adapter: "bochs_vga", vram_size: 3 << 20 }, /vram_size must be a power of two/],
    // (the VGA core backs 256 MiB; a 512 MiB BAR1 made vmware_svga's VRAM view throw once a driver used it)
    [{ graphics_adapter: "vmware_svga", vram_size: 512 << 20 }, /vram_size must be at most 256 MiB/],
])
{
    assert.throws(() => new V86({ ...BASE, autostart: false, ...options }), message);
}
console.log("PASS: graphics_adapter is required and checked");

// A plugin file that is not there says which file it looked for
{
    const emulator = new V86({ ...BASE, autostart: false, graphics_adapter: "bochs_vga",
        graphics_adapter_path: ROOT + "build/no-such-adapter.js" });
    const error = await new Promise(resolve => emulator.add_listener("emulator-error", resolve));
    assert.match(String(error && error.message), /cannot load .*no-such-adapter\.js/);
    await emulator.destroy();
    console.log("PASS: a missing plugin file is reported with its path");
}

// The Bochs VGA: boots to text, its snapshot names the adapter
let bochs_state;
{
    const emulator = await start({ graphics_adapter: "bochs_vga", vram_size: 4 << 20, autostart: true });
    const cpu = emulator.v86.cpu;
    assert.equal(cpu.devices.graphics_adapter.name, "bochs_vga");
    assert.equal(cpu.devices.vga.vga_memory_size, 4 << 20, "vram_size reaches the VGA");
    await emulator.wait_until_vga_screen_contains("No bootable device.", { timeout_msec: 60000 });
    emulator.stop();
    bochs_state = await emulator.save_state();
    await emulator.destroy();

    const restored = await start({ graphics_adapter: "bochs_vga", vram_size: 4 << 20, autostart: false });
    await restored.restore_state(bochs_state);
    assert.ok(restored.screen_adapter.get_text_screen().some(line => line.includes("No bootable device.")),
        "the text screen comes back");
    await restored.destroy();
    console.log("PASS: bochs_vga boots, saves and restores");
}

// No display adapter: no VGA ports, no VGA text, snapshots do not mix
{
    const emulator = await start({ graphics_adapter: "none", autostart: true });
    const cpu = emulator.v86.cpu;
    assert.equal(cpu.devices.graphics_adapter, undefined);
    assert.equal(cpu.devices.vga, undefined);
    assert.equal(cpu.io.port_read8(0x3DA), 0xFF, "nothing decodes the VGA ports");
    await assert.rejects(emulator.wait_until_vga_screen_contains("x"), /graphics_adapter is "none"/);

    // SeaBIOS runs without a VGA BIOS: let it reach the boot attempt
    await new Promise(resolve => setTimeout(resolve, 3000));
    emulator.stop();
    const none_state = await emulator.save_state();

    await assert.rejects(emulator.restore_state(bochs_state),
        /graphics_adapter: "bochs_vga", this one has "none"/);
    await emulator.destroy();

    const bochs = await start({ graphics_adapter: "bochs_vga", autostart: false });
    await assert.rejects(bochs.restore_state(none_state),
        /graphics_adapter: "none", this one has "bochs_vga"/);
    await bochs.destroy();
    console.log("PASS: graphics_adapter \"none\" boots without a display, snapshots do not mix");
}

// The PCI ROM header of the VGA BIOS (SeaBIOS only runs a matching ROM)
if(!TEST_RELEASE_BUILD)
{
    const { patch_vga_bios_ids } = await import("../../src/graphics_adapter.js");
    const original = new Uint8Array(fs.readFileSync(ROOT + "bios/vgabios.bin"));
    const ids = rom => {
        const pcir = rom[0x18] | rom[0x19] << 8;
        return [rom[pcir + 4] | rom[pcir + 5] << 8, rom[pcir + 6] | rom[pcir + 7] << 8];
    };
    const checksum = rom => rom.subarray(0, rom[2] * 512).reduce((sum, byte) => sum + byte, 0) & 0xFF;

    const same = original.slice();
    patch_vga_bios_ids(same, 0x1234, 0x1111);
    assert.deepEqual(same, original, "a ROM that names the device stays as it is");

    for(const [vendor, device] of [[0x15AD, 0x0405], [0x1AF4, 0x1050]])
    {
        const rom = original.slice();
        patch_vga_bios_ids(rom, vendor, device);
        assert.deepEqual(ids(rom), [vendor, device]);
        assert.equal(checksum(rom), 0, "the checksum stays valid");
        assert.equal(rom.reduce((n, byte, i) => n + (byte !== original[i]), 0) <= 5, true,
            "only the IDs and the checksum byte change");
    }
    console.log("PASS: the VGA BIOS's PCI ROM header names the adapter's device");
}
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/devices/hd_audio.js                                                                0000755 0000000 0000000 00000040231 00000000000 014565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The HD Audio controller (audio_device "hd_audio", the plugin of
// src/audio_devices/hd_audio/), driven through its registers, rings and
// buffer descriptor lists in guest memory; no guest code runs, the test moves
// the machine clock (docs/modern-pc-devices-plan.md, H1): PCI identity on
// i440FX and Q35, the controller reset and the codec's presence, CORB/RIRB
// and immediate commands, the codec's nodes and verbs, an output stream
// (rate, LPIB, the DMA position buffer, completion interrupts, wrap, SSYNC,
// the amplifier), descriptor errors, the wall clock and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

let host = 1000;
const options = machine_type => ({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 32 * 1024 * 1024,
    machine_type,
    acpi: machine_type === "q35",
    audio_device: "hd_audio",
    net_device: { type: "none" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});

async function machine(machine_type)
{
    const emulator = new V86(options(machine_type));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume();
    return emulator;
}

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const emulator = await machine("i440fx");
const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const HDA = 0x1B << 3;
const BAR = 0xC0000000;

const r8 = offset => cpu.mmap_read8(BAR + offset);
// (v86 splits 16-bit MMIO accesses into bytes, as the guest's would be)
const r16 = offset => r8(offset) | r8(offset + 1) << 8;
const r32 = offset => cpu.mmap_read32(BAR + offset) >>> 0;
const w8 = (offset, value) => cpu.mmap_write8(BAR + offset, value);
const w16 = (offset, value) => cpu.mmap_write16(BAR + offset, value);
const w32 = (offset, value) => cpu.mmap_write32(BAR + offset, value | 0);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const irq = () => !!pci.intx_levels[HDA];
const controller = () => cpu.devices.audio.device["controller"];

function advance(ms)
{
    host += ms;
    cpu.run_hardware_timers(false, cpu.clock.now());
}

const R = {
    GCAP: 0x00, VMIN: 0x02, VMAJ: 0x03, GCTL: 0x08, WAKEEN: 0x0C, STATESTS: 0x0E, INTCTL: 0x20, INTSTS: 0x24, WALCLK: 0x30,
    SSYNC: 0x38, CORBLBASE: 0x40, CORBUBASE: 0x44, CORBWP: 0x48, CORBRP: 0x4A, CORBCTL: 0x4C, CORBSIZE: 0x4E,
    RIRBLBASE: 0x50, RIRBUBASE: 0x54, RIRBWP: 0x58, RINTCNT: 0x5A, RIRBCTL: 0x5C, RIRBSTS: 0x5D, ICOI: 0x60, ICII: 0x64,
    ICIS: 0x68, DPLBASE: 0x70, DPUBASE: 0x74,
};
const SD = 0x80;
const SD_CTL = SD, SD_STS = SD + 3, SD_LPIB = SD + 4, SD_CBL = SD + 8, SD_LVI = SD + 0xC, SD_FIFOS = SD + 0x10, SD_FMT = SD + 0x12,
    SD_BDPL = SD + 0x18, SD_BDPU = SD + 0x1C;
const CORB = 0x100000, RIRB = 0x101000, BDL = 0x102000, POSITIONS = 0x103000, PCM = 0x200000;

/** The PCM (raw bytes) and the speaker's samples the controller sent */
let pcm = [], speaker = [], rates = [];
emulator.add_listener("hd-audio-pcm", info => pcm.push(...info["chunks"].map(chunk => new Uint8Array(chunk))));
emulator.add_listener("dac-send-data", data => speaker.push(data));
emulator.add_listener("dac-tell-sampling-rate", rate => rates.push(rate));
const pcm_bytes = () => { const all = new Uint8Array(pcm.reduce((n, c) => n + c.length, 0)); let at = 0; for(const c of pcm) { all.set(c, at); at += c.length; } return all; };

// --- PCI ---------------------------------------------------------------------

test("PCI: ICH6 HD Audio (8086:2668) at 00:1b.0 on i440FX, class 04/03/00, INTA, 16 KiB BAR0", () => {
    const space = pci.space_bytes(HDA);
    const word = o => space[o] | space[o + 1] << 8;
    assert.equal(word(0), 0x8086);
    assert.equal(word(2), 0x2668);
    assert.deepEqual([space[0x0B], space[0x0A], space[0x09]], [4, 3, 0]);
    assert.equal(space[0x3D], 1);
    pci.config_write(HDA, 0x10, 4, -1);
    assert.equal((space[0x10] | space[0x11] << 8 | space[0x12] << 16 | space[0x13] << 24) >>> 0, 0xFFFFC000);
    pci.config_write(HDA, 0x10, 4, BAR);
    pci.config_write(HDA, 0x04, 2, 0x0006);
    assert.equal(r16(R.GCAP), 0x1001, "one output stream, no input, 64-bit");
    assert.deepEqual([r8(R.VMAJ), r8(R.VMIN)], [1, 0]);
});

// --- reset and commands --------------------------------------------------------

test("GCTL.CRST: in reset nothing else is written; leaving it, the codec at address 0 (STATESTS)", () => {
    w32(R.GCTL, 0);
    assert.equal(r32(R.GCTL) & 1, 0);
    w32(R.INTCTL, -1);
    assert.equal(r32(R.INTCTL), 0, "in reset");
    w32(R.GCTL, 1);
    assert.equal(r32(R.GCTL) & 1, 1);
    assert.equal(r16(R.STATESTS), 1);
    w16(R.STATESTS, 1);
    assert.equal(r16(R.STATESTS), 0, "write one to clear");
});

let corb_wp = 0, rirb_rp = 0;
function setup_rings()
{
    w8(R.CORBCTL, 0);
    w8(R.RIRBCTL, 0);
    w32(R.CORBLBASE, CORB); w32(R.CORBUBASE, 0);
    w32(R.RIRBLBASE, RIRB); w32(R.RIRBUBASE, 0);
    assert.equal(r8(R.CORBSIZE), 0x42, "256 entries");
    // (the read pointer's reset handshake, as Linux does it)
    w16(R.CORBRP, 0x8000);
    assert.equal(r16(R.CORBRP), 0x8000);
    w16(R.CORBRP, 0);
    assert.equal(r16(R.CORBRP), 0);
    w16(R.CORBWP, 0);
    w16(R.RIRBWP, 0x8000);
    assert.equal(r16(R.RIRBWP), 0);
    w16(R.RINTCNT, 1);
    w8(R.RIRBCTL, 3);
    w8(R.CORBCTL, 2);
    corb_wp = 0; rirb_rp = 0;
}
/** Commands through the CORB; their responses from the RIRB */
function commands(...verbs)
{
    for(const verb of verbs)
    {
        corb_wp = corb_wp + 1 & 0xFF;
        put32(CORB + 4 * corb_wp, verb);
    }
    w16(R.CORBWP, corb_wp);
    const responses = [];
    while(rirb_rp !== r16(R.RIRBWP))
    {
        rirb_rp = rirb_rp + 1 & 0xFF;
        responses.push(u32(RIRB + 8 * rirb_rp));
        assert.equal(u32(RIRB + 8 * rirb_rp + 4), 0, "solicited, codec 0");
    }
    w8(R.RIRBSTS, 1);
    return responses;
}
const verb = (nid, verb12, payload = 0) => nid << 20 | verb12 << 8 | payload;
const verb4 = (nid, verb, payload) => nid << 20 | verb << 16 | payload;
const param = (nid, id) => verb(nid, 0xF00, id);

test("CORB and RIRB: responses in order, RINTFL and the controller interrupt (CIE, GIE)", () => {
    setup_rings();
    w32(R.INTCTL, 1 << 31 | 1 << 30);
    corb_wp = corb_wp + 1 & 0xFF;
    put32(CORB + 4 * corb_wp, param(0, 0));
    w16(R.CORBWP, corb_wp);
    assert.equal(r16(R.CORBRP), corb_wp, "read up to the write pointer");
    assert.equal(r16(R.RIRBWP), 1);
    assert.equal(u32(RIRB + 8), 0x1AF40012, "vendor ID");
    assert.equal(r8(R.RIRBSTS) & 1, 1, "RINTFL");
    assert.ok(irq());
    assert.equal(r32(R.INTSTS), (1 << 31 | 1 << 30) >>> 0);
    w8(R.RIRBSTS, 1);
    assert.ok(!irq());
    rirb_rp = 1;
    w16(R.RINTCNT, 2);
    assert.deepEqual(commands(param(0, 2), param(0, 4), param(1, 5)), [0x00100101, 0x00010001, 0x01]);
});

test("the codec: the function group, a DAC and a line out pin connected to it", () => {
    const [nodes, fg_nodes, dac, pin, pcm_formats, streams, conn_len, conn, config, pin_cap, amp] = commands(
        param(0, 4), param(1, 4), param(2, 9), param(3, 9), param(1, 0xA), param(2, 0xB), param(3, 0xE), verb(3, 0xF02),
        verb(3, 0xF1C), param(3, 0xC), param(2, 0x12));
    assert.equal(nodes, 0x00010001);
    assert.equal(fg_nodes, 0x00020002);
    assert.equal(dac >>> 20 & 0xF, 0, "an audio output");
    assert.equal(dac & 0x15, 0x15, "stereo, output amp, format override");
    assert.equal(pin >>> 20 & 0xF, 4, "a pin");
    assert.ok(pin & 1 << 8, "with a connection list");
    assert.equal(pcm_formats, 1 << 17 | 1 << 5 | 1 << 6, "16 bits, 44.1 and 48 kHz");
    assert.equal(streams, 1, "PCM");
    assert.deepEqual([conn_len, conn], [1, 2]);
    assert.equal(config, 0x00004010, "line out, green");
    assert.equal(pin_cap, 1 << 4, "output");
    assert.equal(amp >>> 31, 1, "a mute");
    assert.equal(amp >> 8 & 0x7F, 0x4A);
});

test("the codec's verbs: format, stream and channel, amplifier, pin control, power, config bytes, reset", () => {
    commands(verb4(2, 0x2, 0x0011), verb(2, 0x706, 0x10), verb4(2, 0x3, 0xB000 | 0x40), verb(3, 0x707, 0x40),
        verb(1, 0x705, 3), verb(3, 0x71F, 0x90));
    const [format, conv, left, right, pinctl, power, config] = commands(verb4(2, 0xA, 0), verb(2, 0xF06), verb4(2, 0xB, 0xA000),
        verb4(2, 0xB, 0x8000), verb(3, 0xF07), verb(1, 0xF05), verb(3, 0xF1C));
    assert.deepEqual([format, conv, left, right, pinctl, power, config], [0x0011, 0x10, 0x40, 0x40, 0x40, 0x33, 0x90004010]);
    commands(verb(1, 0x7FF));
    assert.deepEqual(commands(verb(2, 0xF06), verb4(2, 0xB, 0xA000), verb(3, 0xF1C)), [0, 0x4A, 0x00004010]);
});

test("the immediate command: ICOI, ICIS.ICB, the response in ICII with IRV", () => {
    w32(R.ICOI, param(0, 0));
    w16(R.ICIS, 1);
    assert.equal(r16(R.ICIS) & 3, 2, "not busy, valid");
    assert.equal(r32(R.ICII), 0x1AF40012);
    w16(R.ICIS, 2);
    assert.equal(r16(R.ICIS) & 3, 0);
    w32(R.ICOI, 1 << 28 | param(0, 0));
    w16(R.ICIS, 1);
    assert.equal(r16(R.ICIS) & 1, 1, "no codec at address 1: busy (the driver times out)");
    w32(R.GCTL, 0);
    w32(R.GCTL, 1);
    setup_rings();
});

test("the wall clock: 24 MHz", () => {
    const before = r32(R.WALCLK);
    advance(1);
    assert.equal(r32(R.WALCLK) - before, 24000);
});

// --- an output stream ---------------------------------------------------------

const FMT_48K_16_STEREO = 0x0011, FMT_44K_16_STEREO = 0x4011;
const PERIOD = 1920;
/** Four descriptors of 1920 bytes (10 ms at 48 kHz), IOC on each second */
function setup_stream(fmt = FMT_48K_16_STEREO, ioc = [false, true, false, true])
{
    w32(SD_CTL, 1);
    assert.equal(r32(SD_CTL) & 1, 1, "in reset");
    w32(SD_CTL, 0);
    for(let i = 0; i < 4; i++)
    {
        put32(BDL + 16 * i, PCM + i * PERIOD); put32(BDL + 16 * i + 4, 0);
        put32(BDL + 16 * i + 8, PERIOD); put32(BDL + 16 * i + 12, ioc[i] ? 1 : 0);
    }
    for(let i = 0; i < 4 * PERIOD; i++) mem[PCM + i] = i * 7 + (i >> 8) & 0xFF;
    w32(SD_BDPL, BDL); w32(SD_BDPU, 0);
    w32(SD_CBL, 4 * PERIOD);
    w16(SD_LVI, 3);
    w16(SD_FMT, fmt);
    commands(verb4(2, 0x2, fmt), verb(2, 0x706, 0x10), verb(3, 0x707, 0x40), verb4(2, 0x3, 0xB000 | 0x4A));
    pcm = []; speaker = []; rates = [];
}

test("a stream plays at its rate: LPIB, the PCM in order, the speaker told 48000 Hz", () => {
    setup_stream();
    assert.equal(r16(SD_FIFOS), 0xFF);
    w32(R.INTCTL, 1 << 31 | 1);
    w32(SD_CTL, 1 << 20 | 1 << 2 | 2);
    assert.deepEqual(rates, [48000]);
    advance(5);
    assert.equal(r32(SD_LPIB), 960, "5 ms: 240 frames of 4 bytes");
    assert.ok(!irq());
    advance(6);
    assert.equal(r32(SD_LPIB), 2112);
    assert.equal(r8(SD_STS) & 4, 0, "the first descriptor has no IOC");
    advance(10);
    assert.equal(r32(SD_LPIB), 4032);
    assert.equal(r8(SD_STS) & 4, 4, "BCIS: the second descriptor done");
    assert.ok(irq(), "the stream's interrupt");
    assert.equal(r32(R.INTSTS) & 1, 1);
    w8(SD_STS, 4);
    assert.ok(!irq());
    assert.deepEqual(pcm_bytes(), mem.slice(PCM, PCM + 4032));
    const samples = speaker.reduce((n, [left]) => n + left.length, 0);
    assert.equal(samples, 1008);
    const view = new DataView(mem.buffer, mem.byteOffset);
    assert.equal(speaker[0][0][0], view.getInt16(PCM, true) / 32768, "0 dB: the samples as they are");
    assert.equal(speaker[0][1][0], view.getInt16(PCM + 2, true) / 32768);
});

test("the cyclic buffer wraps at CBL, the DMA position buffer follows LPIB", () => {
    w32(R.DPLBASE, POSITIONS | 1); w32(R.DPUBASE, 0);
    advance(25);
    assert.equal(r32(SD_LPIB), (4032 + 4800) % (4 * PERIOD));
    assert.equal(u32(POSITIONS), r32(SD_LPIB));
    assert.equal(pcm_bytes().length, 4032 + 4800);
    assert.deepEqual(pcm_bytes().slice(4 * PERIOD), mem.slice(PCM, PCM + 4032 + 4800 - 4 * PERIOD), "from the start again");
});

test("RUN cleared: the position stays; set again: it goes on from there", () => {
    w32(SD_CTL, 1 << 20 | 1 << 2);
    const lpib = r32(SD_LPIB);
    advance(20);
    assert.equal(r32(SD_LPIB), lpib);
    w32(SD_CTL, 1 << 20 | 1 << 2 | 2);
    advance(1);
    assert.equal(r32(SD_LPIB), (lpib + 192) % (4 * PERIOD));
    w32(SD_CTL, 1 << 20 | 1 << 2);
});

test("SSYNC holds a running stream until it is cleared", () => {
    setup_stream();
    w32(R.SSYNC, 1);
    w32(SD_CTL, 1 << 20 | 2);
    advance(10);
    assert.equal(r32(SD_LPIB), 0);
    w32(R.SSYNC, 0);
    advance(10);
    assert.equal(r32(SD_LPIB), 1920);
    w32(SD_CTL, 1 << 20);
});

test("44.1 kHz; the amplifier's gain and mute; a stream the DAC does not take is silent", () => {
    setup_stream(FMT_44K_16_STEREO);
    commands(verb4(2, 0x3, 0xA000 | 0x4A - 6), verb4(2, 0x3, 0x9000 | 0x80));
    w32(SD_CTL, 1 << 20 | 2);
    assert.deepEqual(rates, [44100]);
    advance(10);
    assert.equal(r32(SD_LPIB), 441 * 4);
    const view = new DataView(mem.buffer, mem.byteOffset);
    assert.ok(Math.abs(speaker[0][0][1] - view.getInt16(PCM + 4, true) / 32768 * Math.pow(10, -6 / 20)) < 1e-6, "left: -6 dB");
    assert.equal(speaker[0][1][1], 0, "right: muted");
    w32(SD_CTL, 1 << 20);
    setup_stream();
    commands(verb(2, 0x706, 0x20));
    w32(SD_CTL, 1 << 20 | 2);
    advance(5);
    assert.ok(speaker.every(([left, right]) => left.every(v => v === 0) && right.every(v => v === 0)), "tag 1, DAC on 2");
    assert.equal(r32(SD_LPIB), 960, "the stream runs nevertheless");
    w32(SD_CTL, 1 << 20);
});

test("a bad descriptor list: DESE, the stream stops (DEIE: an interrupt)", () => {
    setup_stream();
    put32(BDL + 8, 0);
    w32(R.INTCTL, 1 << 31 | 1);
    w32(SD_CTL, 1 << 20 | 1 << 4 | 2);
    advance(5);
    assert.equal(r8(SD_STS) & 0x10, 0x10);
    assert.equal(r32(SD_CTL) & 2, 0, "stopped");
    assert.ok(irq());
    w8(SD_STS, 0x10);
    assert.ok(!irq());
});

test("SRST: the descriptor to its defaults", () => {
    w32(SD_CTL, 1);
    assert.deepEqual([r32(SD_CTL) & 0xFFFFFF, r32(SD_LPIB), r32(SD_CBL), r16(SD_LVI), r16(SD_FMT), r32(SD_BDPL)], [1, 0, 0, 0, 0, 0]);
    w32(SD_CTL, 0);
});

// --- snapshots ------------------------------------------------------------------

{
    setup_stream();
    w32(R.INTCTL, 1 << 31 | 1);
    w32(SD_CTL, 1 << 20 | 1 << 2 | 2);
    advance(15);
    const lpib = r32(SD_LPIB);
    const state = await emulator.save_state();
    advance(100);
    w32(R.GCTL, 0);
    await emulator.restore_state(state);
    test("snapshot: the stream goes on from where it was, the rings and the codec as they were", () => {
        assert.equal(r32(R.GCTL) & 1, 1);
        assert.equal(r32(SD_LPIB), lpib);
        assert.equal(r32(SD_CTL) & 2, 2);
        advance(5);
        assert.equal(r32(SD_LPIB), lpib + 960);
        assert.deepEqual(commands(verb(2, 0xF06)), [0x10]);
    });
    w32(SD_CTL, 1 << 20);

    const other = new V86({ ...options("i440fx"), audio_device: "sb16" });
    await new Promise(resolve => other.add_listener("emulator-loaded", resolve));
    let error;
    await other.restore_state(state).catch(e => { error = e; });
    test("snapshot: a machine with another sound card refuses it", () => {
        assert.match(String(error && error.message), /audio_device: "hd_audio", this one has "sb16"/);
    });
    await other.destroy();
}

// --- Q35 -------------------------------------------------------------------------

{
    const q35 = await machine("q35");
    const space = q35.v86.cpu.devices.pci.space_bytes(HDA);
    test("Q35: ICH9 HD Audio (8086:293E) at 00:1b.0", () => {
        assert.equal(space[2] | space[3] << 8, 0x293E);
        assert.equal(space[8], 3, "revision 3");
    });
    await q35.destroy();
}

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/devices/hd_audio_browser.html                                                      0000644 0000000 0000000 00000023466 00000000000 016670  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>HD Audio in the browser</title>
<!-- What the page plays of the HD Audio controller (docs/sound.md, docs/modern-pc-devices-plan.md H1), in
     headless Chrome with the CPU worker: Alpine x86_64 plays 20 s of a 1 kHz tone (tests/devices/hd_audio_play.c
     "tone", which switches the Master controls on); an analyser on the page's output measures it every 50 ms.
     The machine is paused for 2 s in the middle: the tone stops and goes on, its 20 s of machine time all
     heard, without gaps. Needs build/hd-audio/player.tar (tests/devices/hd_audio_guest.mjs makes it) and the
     Alpine ISO in build/x64-linux/.
     node tests/app/browser_runner.mjs tests/devices/hd_audio_browser.html autoplay=1 -->
<pre id="log"></pre>
<pre id="result"></pre>
<div id="screen_container" style="display: none"><div></div><canvas></canvas></div>
<script type="module">
import { V86 } from "../../build/libv86.mjs";

const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function check(condition, what) { if(!condition) throw new Error(what); }

// the page's output: an analyser beside each connection to a destination
const analysers = [];
const connect = AudioNode.prototype.connect;
AudioNode.prototype.connect = function(target, ...rest)
{
    if(target instanceof AudioDestinationNode)
    {
        const analyser = this.context.createAnalyser();
        analyser.fftSize = 2048;
        connect.call(this, analyser);
        analysers.push(analyser);
    }
    return connect.call(this, target, ...rest);
};
const buffer = new Float32Array(2048);
const spectrum = new Float32Array(1024);
/** The output's strongest frequency (Hz) */
function frequency()
{
    const analyser = analysers[0];
    analyser.getFloatFrequencyData(spectrum);
    let best = 1;
    for(let i = 2; i < spectrum.length; i++) if(spectrum[i] > spectrum[best]) best = i;
    return best * analyser.context.sampleRate / analyser.fftSize;
}
function level()
{
    let peak = 0;
    for(const analyser of analysers)
    {
        analyser.getFloatTimeDomainData(buffer);
        let sum = 0;
        for(const v of buffer) sum += v * v;
        peak = Math.max(peak, Math.sqrt(sum / buffer.length));
    }
    return peak;
}

async function main()
{
    const ALPINE = "/build/x64-linux/";
    const emulator = new V86({
        wasm_path: "/build/v86.wasm",
        cpu_worker: true,
        cpu_worker_url: "/build/cpu-worker.js",
        graphics_adapter: "bochs_vga",
        screen_container: document.getElementById("screen_container"),
        bios: { url: "/bios/seabios.bin" },
        vga_bios: { url: "/bios/vgabios.bin" },
        bzimage: { url: ALPINE + "boot/vmlinuz-virt" },
        initrd: { url: ALPINE + "boot/initramfs-virt" },
        cdrom: { url: ALPINE + "alpine-virt-3.24.0-x86_64.iso", async: true },
        hda: { url: "/build/hd-audio/player.tar" },
        cmdline: "console=ttyS0,115200 loglevel=4 nokaslr modules=loop,squashfs,sd-mod,usb-storage",
        memory_size: 512 * 1024 * 1024,
        cpu_type: "x86_64",
        acpi: true,
        audio_device: "hd_audio",
        net_device: { type: "none" },
        disable_keyboard: true,
        disable_mouse: true,
        autostart: true,
    });
    let serial = "";
    emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
    // (what the controller played, and when it arrived here)
    const produced = [];
    emulator.add_listener("hd-audio-pcm", pcm => produced.push({ at: Date.now(), bytes: pcm["chunks"].reduce((n, c) => n + c.byteLength, 0) }));
    const until = async (pattern, what, timeout) =>
    {
        const end = Date.now() + timeout;
        while(!pattern.test(serial))
        {
            if(Date.now() > end) throw new Error("timed out: " + what + "\n" + serial.slice(-1500));
            await sleep(100);
        }
    };
    const PROMPT = /:~# (\x1b\[6n)?$/;
    const command = async (line, timeout = 120000) => { serial = ""; emulator.serial0_send(line + "\n"); await until(PROMPT, line, timeout); return serial; };

    await until(/login: $/, "the login prompt", 900000);
    serial = "";
    emulator.serial0_send("root\n");
    await until(PROMPT, "the shell", 120000);
    await command("for i in $(seq 30); do [ -e /dev/snd/pcmC0D0p ] && break; sleep 1; done; tar -xf /dev/sda -C /tmp");
    const context = analysers[0] && analysers[0].context;
    log("Alpine's shell; the audio context: " + (context ? context.state + ", " + context.sampleRate + " Hz" : "none") +
        ", " + analysers.length + " output(s)");
    check(analysers.length, "the speaker's output");

    serial = "";
    emulator.serial0_send("/tmp/hd_audio_play 48000 20 tone\n");
    // the level every 50 ms, until the player is done; a pause of 2 s once the tone is on for 8 s
    const levels = [];
    let loud_since = 0, paused = null;
    const start = Date.now();
    while(!/PCM_DONE|PCM_FAIL/.test(serial) && Date.now() - start < 300000)
    {
        await sleep(50);
        const value = level();
        levels.push({ at: Date.now() - start, value, running: emulator.is_running(), frequency: value > 0.05 ? frequency() : 0 });
        if(value > 0.05 && !loud_since) loud_since = Date.now();
        if(loud_since && !paused && Date.now() - loud_since > 8000)
        {
            paused = { at: Date.now() - start };
            await emulator.stop();
            // (the level while paused too)
            for(const end = Date.now() + 2000; Date.now() < end;)
            {
                await sleep(50);
                levels.push({ at: Date.now() - start, value: level(), running: false, state: analysers[0].context.state });
            }
            paused.end = Date.now() - start;
            emulator.run();
        }
    }
    await until(PROMPT, "the player's end", 60000);
    // (what the page still plays after the controller is done)
    const done_at = Date.now() - start;
    for(const end = Date.now() + 5000; Date.now() < end;)
    {
        await sleep(50);
        levels.push({ at: Date.now() - start, value: level(), running: true, frequency: 0, tail: true });
    }
    const timeline = [];
    for(let t = 0; t < levels[levels.length - 1].at; t += 500)
    {
        const bucket = levels.filter(l => l.at >= t && l.at < t + 500);
        timeline.push(bucket.length ? (bucket.filter(l => l.value > 0.05).length * 9 / bucket.length).toFixed(0) : "-");
    }
    log("loudness per 0.5 s (0-9): " + timeline.join("") + "; paused " + (paused.at / 1000).toFixed(1) + "-" +
        (paused.end / 1000).toFixed(1) + " s, the player done at " + (done_at / 1000).toFixed(1) + " s");
    const done = serial.match(/PCM_DONE rate=\d+ frames=(\d+)/);
    check(done && +done[1] === 960000, "the player: " + serial.slice(-300));

    // (the tone's windows: from the first loud one to the last)
    const loud = levels.filter(l => l.value > 0.05 && !l.tail);
    const first = loud[0].at, last = loud[loud.length - 1].at;
    const during = levels.filter(l => l.at >= first && l.at <= last);
    // (the speaker suspends the audio context while the machine is stopped:
    // nothing plays, the analyser keeps its last data)
    const in_pause = during.filter(l => l.at > paused.at + 300 && l.at < paused.end);
    const playing = during.filter(l => !(l.at > paused.at && l.at < paused.end + 300));
    const gaps = playing.filter(l => l.value <= 0.05).length;
    const heard = loud.filter(l => l.running).length * 50 / 1000;
    const tail = levels.filter(l => l.tail && l.value > 0.05).length * 50 / 1000;
    log("the tone from " + (first / 1000).toFixed(1) + " s to " + (last / 1000).toFixed(1) + " s: " + heard.toFixed(1) +
        " s heard, level " + (loud.reduce((s, l) => s + l.value, 0) / loud.length).toFixed(3) + ", " + gaps + " quiet windows of " +
        playing.length + " while playing; paused " + ((paused.end - paused.at) / 1000).toFixed(1) + " s: " +
        in_pause.filter(l => l.state !== "suspended" && l.value > 0.05).length + " loud windows of " + in_pause.length +
        " (the context " + [...new Set(in_pause.map(l => l.state))].join(", ") + "); " + tail.toFixed(2) + " s after the player's end");
    const pause_start = start + paused.at, pause_end = start + paused.end;
    const during_pause = produced.filter(p => p.at > pause_start + 300 && p.at < pause_end).reduce((n, p) => n + p.bytes, 0);
    const first_pcm = produced.find(p => p.at >= start), total = produced.filter(p => p.at >= start).reduce((n, p) => n + p.bytes, 0);
    log("the controller: " + total + " bytes from " + ((first_pcm.at - start) / 1000).toFixed(1) + " s to " +
        ((produced[produced.length - 1].at - start) / 1000).toFixed(1) + " s, " + during_pause + " bytes while paused");
    const per_second = [];
    for(let t = 0; t < 23; t++)
    {
        per_second.push(Math.round(produced.filter(p => p.at >= start + t * 1000 && p.at < start + t * 1000 + 1000).reduce((n, p) => n + p.bytes, 0) / 4 / 100) / 10);
    }
    log("the controller's frames per second (k): " + per_second.join(" "));

    const frequencies = loud.map(l => l.frequency).filter(Boolean).sort((a, b) => a - b);
    log("the tone's frequency: " + frequencies[frequencies.length >> 1].toFixed(0) + " Hz (median)");
    check(in_pause.length >= 20 && in_pause.every(l => l.state === "suspended" || l.value <= 0.05), "silence while the machine is paused");
    check(tail < 1, "what the page has queued: " + tail.toFixed(2) + " s");
    check(gaps <= playing.length * 0.02, "no gaps while playing: " + gaps);
    check(heard > 18.5 && heard < 21.5, "20 s of tone heard: " + heard.toFixed(1));
    await emulator.destroy();
}

main().then(() => { document.getElementById("result").textContent = "PASS"; },
    error => { document.getElementById("result").textContent = "FAIL: " + (error && error.stack || error); });
</script>
                                                                                                                                                                                                          source/v64/tests/devices/hd_audio_guest.mjs                                                         0000755 0000000 0000000 00000025200 00000000000 016150  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The HD Audio controller with real drivers: Alpine 3.24 x86_64's
// snd-hda-intel and snd-hda-codec-generic (the pinned virt ISO,
// tests/lib/alpine_image.mjs) on audio_device "hd_audio"
// (docs/modern-pc-devices-plan.md, H1, "验收"). The drivers bind the
// controller and the codec (card "HDA Intel", codec "QEMU Generic", a PCM
// device and the Master controls); tests/devices/hd_audio_play.c, a
// freestanding ALSA player built here with clang and rust-lld, plays a
// pattern at 48 and 44.1 kHz: the stream's bytes as the controller read them
// ("hd-audio-pcm") are the pattern, in the format asked for, and take their
// time on the machine clock; the controller's interrupts drive the player.
//
// MACHINE=q35 (ICH9's controller), CPU_CORES=2, SHOW_LOGS=1.

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import { spawnSync } from "node:child_process";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "i440fx";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const out = ROOT + "build/hd-audio/";
fs.mkdirSync(out, { recursive: true });
function run(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, program + ": " + (result.stderr || result.error));
    return result.stdout.trim();
}
// the player: x86-64 Linux, static, no libc
const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
run(process.env.CLANG || "clang", ["--target=x86_64-unknown-linux-gnu", "-O2", "-ffreestanding", "-fno-stack-protector", "-fno-pic",
    "-fno-builtin", "-mno-red-zone", "-c", __dirname + "hd_audio_play.c", "-o", out + "hd_audio_play.o"]);
run(lld, ["-flavor", "gnu", "-m", "elf_x86_64", "-static", "-e", "_start", "-o", out + "hd_audio_play", out + "hd_audio_play.o"]);
run("bsdtar", ["--format", "ustar", "--no-xattrs", "--no-mac-metadata", "--uid", "0", "--gid", "0", "-cf", out + "player.tar", "-C", out, "hd_audio_play"]);
const tar = fs.readFileSync(out + "player.tar");
const disk = new Uint8Array(1 << 20);
disk.set(tar);

const prepared = await prepare_alpine("x86_64-virt");
const directory = ROOT + "build/x64-linux/";
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    bzimage: { url: directory + "boot/vmlinuz-virt" },
    initrd: { url: directory + "boot/initramfs-virt" },
    cdrom: { url: directory + prepared.image.name },
    hda: { buffer: disk.buffer },
    cmdline: "console=ttyS0,115200 loglevel=4 nokaslr modules=loop,squashfs,sd-mod,usb-storage",
    memory_size: 512 * 1024 * 1024,
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    acpi: true,
    net_device: { type: "none" },
    audio_device: "hd_audio",
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, 900 * 1000);

let serial = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});
/** The speaker's samples (after the codec's amplifier) */
let speaker = [];
emulator.add_listener("dac-send-data", data => speaker.push(data[0].slice()));
/** The stream's bytes by format, and when they came (machine time) */
let pcm = [];
emulator.add_listener("hd-audio-pcm", info => pcm.push({ format: info["format"], chunks: info["chunks"].map(c => new Uint8Array(c)),
    at: emulator.v86.cpu.clock.now() }));

// (Alpine's shell asks the terminal for the cursor position after its prompt)
const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send(cmd + "\n");
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(cmd.length).replace(PROMPT, "");
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

console.log("Booting Alpine x86_64 with HD Audio (" + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");
await wait_serial(/login: $/, "the login prompt", 600000);
serial = "";
emulator.serial0_send("root\n");
await wait_serial(PROMPT, "the shell", 120000);

await step("the drivers: snd-hda-intel binds the controller, the generic parser the codec", async () => {
    // (mdev loads the modules by their modaliases)
    const cards = await command("for i in $(seq 30); do [ -e /dev/snd/pcmC0D0p ] && break; sleep 1; done; cat /proc/asound/cards");
    assert.match(cards, /0 \[Intel\s*\]: HDA-Intel - HDA Intel/);
    const codec = await command("cat '/proc/asound/card0/codec#0'");
    assert.match(codec, /Codec: QEMU Generic/);
    assert.match(codec, /Vendor Id: 0x1af40012/);
    assert.match(codec, /Node 0x02 \[Audio Output\][^\n]*Stereo Amp-Out/);
    assert.match(codec, /Control: name="Master Playback Volume"/);
    assert.match(codec, /Node 0x03 \[Pin Complex\][\s\S]*Line Out[\s\S]*Connection: 1\s+0x02/);
    const lspci = await command("cat /sys/bus/pci/devices/0000:00:1b.0/vendor /sys/bus/pci/devices/0000:00:1b.0/device; " +
        "basename $(readlink /sys/bus/pci/devices/0000:00:1b.0/driver)");
    assert.match(lspci, new RegExp("0x8086\\s+" + (MACHINE === "q35" ? "0x293e" : "0x2668") + "\\s+snd_hda_intel"));
});

await step("the player arrives", async () => {
    const output = await command("tar -xf /dev/sda -C /tmp && ls -l /tmp/hd_audio_play");
    assert.match(output, /hd_audio_play/);
});

for(const [rate, fmt, seconds] of [[48000, 0x0011, 2], [44100, 0x4011, 1]])
{
    await step(`${seconds} s at ${rate} Hz: the pattern, in its format and time`, async () => {
        pcm = [];
        const before = await command("grep snd_hda_intel /proc/interrupts");
        const output = await command(`/tmp/hd_audio_play ${rate} ${seconds}`, 120000);
        const done = output.match(/PCM_DONE rate=(\d+) frames=(\d+) ms=(\d+)/);
        assert.ok(done, "the player: " + output);
        assert.equal(+done[2], rate * seconds);
        const after = await command("grep snd_hda_intel /proc/interrupts");
        // (the line "<irq>: <count per CPU> ... snd_hda_intel:card0")
        const count = text =>
        {
            const line = text.split("\n").find(l => /^\s*\d+:.*snd_hda_intel/.test(l));
            assert.ok(line, "the controller's interrupt line: " + JSON.stringify(text));
            return line.trim().split(/\s+/).slice(1, 1 + CPU_CORES).reduce((sum, n) => sum + +n, 0);
        };
        const interrupts = count(after) - count(before);
        assert.ok(pcm.length, "the stream played");
        assert.ok(pcm.every(p => p.format === fmt), "the format: " + pcm.map(p => p.format.toString(16)).join());
        const bytes = new Uint8Array(pcm.reduce((n, p) => n + p.chunks.reduce((m, c) => m + c.length, 0), 0));
        let at = 0;
        for(const p of pcm) for(const c of p.chunks) { bytes.set(c, at); at += c.length; }
        // the pattern from its first frame: left = frame * 7, right = ~left
        const view = new DataView(bytes.buffer);
        const first = Array.from({ length: bytes.length / 4 }, (_, i) => i).find(i => view.getInt16(4 * i, true) === 7 && view.getInt16(4 * i - 4, true) === 0);
        assert.ok(first !== undefined, "the pattern's start");
        let frames = 0;
        for(let i = first - 1; i < bytes.length / 4 && frames < rate * seconds; i++, frames++)
        {
            const left = view.getInt16(4 * i, true), expected = frames * 7 << 16 >> 16;
            if(left !== expected || view.getInt16(4 * i + 2, true) !== ~expected)
            {
                assert.fail("frame " + frames + ": " + left + ", " + view.getInt16(4 * i + 2, true) + " instead of " + expected);
            }
        }
        assert.equal(frames, rate * seconds, "every frame of the pattern");
        // (the stream's time: a second of samples takes a second of the machine's clock)
        const span = pcm[pcm.length - 1].at - pcm[0].at;
        assert.ok(span > seconds * 1000 * 0.9 && span < seconds * 1000 + 500, "played in " + span.toFixed(0) + " ms of machine time");
        console.log(`    ${frames} frames in ${span.toFixed(0)} ms (machine), the player ${done[3]} ms (guest), ${interrupts} interrupts`);
        assert.ok(interrupts >= seconds * rate / 960 / 2, "period interrupts");
    });
}

await step("the driver's Master controls: muted at first, on at their top the 1 kHz tone reaches the speaker", async () => {
    speaker = [];
    const output = await command("/tmp/hd_audio_play 48000 1 tone", 120000);
    assert.match(output, /PCM_DONE rate=48000 frames=48000/, output);
    const samples = new Float32Array(speaker.reduce((n, s) => n + s.length, 0));
    let at = 0;
    for(const s of speaker) { samples.set(s, at); at += s.length; }
    const loud = samples.filter(v => Math.abs(Math.abs(v) - 8000 / 32768) < 1e-6).length;
    assert.ok(loud >= 47000, "the square wave at 0 dB: " + loud + " of " + samples.length);
    let changes = 0;
    for(let i = 1; i < samples.length; i++) if(samples[i] !== samples[i - 1]) changes++;
    assert.ok(changes > 1900 && changes < 2100, "1 kHz: " + changes + " edges");
    const codec = await command("grep -A1 'Amp-Out vals' '/proc/asound/card0/codec#0'");
    assert.match(codec, /\[0x4a 0x4a\]/);
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/devices/hd_audio_play.c                                                            0000644 0000000 0000000 00000014633 00000000000 015424  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A freestanding ALSA player for tests/devices/hd_audio_guest.mjs and
// hd_audio_browser.html (x86-64 Linux, no libc): opens /dev/snd/pcmC0D0p,
// asks for interleaved S16_LE stereo at the rate given (argv[1], 48000 by
// default) through the PCM ioctls, plays seconds (argv[2], 1 by default) of a
// pattern the host recognises and drains. With argv[3] "tone" it plays a
// 1 kHz square wave instead, after switching the Master controls on and to
// their top (the driver starts them muted). Prints
// "PCM_DONE rate=<r> frames=<n> ms=<t>" or "PCM_FAIL <step> <errno>".
//   clang --target=x86_64-unknown-linux-gnu -O2 -ffreestanding -fno-stack-protector
//       -fno-pic -fno-builtin -nostdlib -static -fuse-ld=lld hd_audio_play.c

typedef unsigned long word;
typedef unsigned int u32;
typedef short s16;

static long sys(long n, word a, word b, word c)
{
    long r;
    __asm__ volatile("syscall" : "=a"(r) : "a"(n), "D"(a), "S"(b), "d"(c) : "rcx", "r11", "memory", "cc");
    return r;
}
enum { SYS_WRITE = 1, SYS_OPEN = 2, SYS_CLOSE = 3, SYS_IOCTL = 16, SYS_EXIT = 60, SYS_CLOCK_GETTIME = 228 };

static void out(const char *s) { word n = 0; while(s[n]) n++; sys(SYS_WRITE, 1, (word)s, n); }
static void out_num(long v)
{
    char b[24]; int i = 23; b[i] = 0;
    if(v < 0) { out("-"); v = -v; }
    do { b[--i] = '0' + v % 10; v /= 10; } while(v);
    out(b + i);
}
static long now_ms(void)
{
    long ts[2];
    sys(SYS_CLOCK_GETTIME, 1, (word)ts, 0);
    return ts[0] * 1000 + ts[1] / 1000000;
}
static void fail(const char *step, long e)
{
    out("PCM_FAIL "); out(step); out(" "); out_num(-e); out("\n");
    sys(SYS_EXIT, 1, 0, 0);
}

// <sound/asound.h>
struct mask { u32 bits[8]; };
struct interval { u32 min, max; u32 flags; };
#define INTERVAL_INTEGER 4
struct hw_params {
    u32 flags;
    struct mask masks[3];
    struct mask mres[5];
    struct interval intervals[12];
    struct interval ires[9];
    u32 rmask, cmask, info, msbits, rate_num, rate_den;
    word fifo_size;
    unsigned char reserved[64];
};
struct xferi { long result; void *buf; word frames; };
_Static_assert(sizeof(struct hw_params) == 608, "snd_pcm_hw_params");
struct elem_value {
    // (struct snd_ctl_elem_id)
    u32 numid, iface, device, subdevice;
    char name[44];
    u32 index;
    u32 indirect;
    long values[128];
    long tstamp[2];
    unsigned char reserved[112];
};
_Static_assert(sizeof(struct elem_value) == 1224, "snd_ctl_elem_value");
#define ELEM_WRITE ((word)3 << 30 | (word)sizeof(struct elem_value) << 16 | 'U' << 8 | 0x13)
enum { IFACE_MIXER = 2 };

#define IOC(dir, nr, size) ((word)(dir) << 30 | (word)(size) << 16 | 'A' << 8 | (nr))
#define HW_PARAMS IOC(3, 0x11, sizeof(struct hw_params))
#define PREPARE IOC(0, 0x40, 0)
#define DRAIN IOC(0, 0x44, 0)
#define WRITEI_FRAMES IOC(1, 0x50, sizeof(struct xferi))

enum { MASK_ACCESS = 0, MASK_FORMAT = 1, MASK_SUBFORMAT = 2 };
enum { CHANNELS = 10, RATE = 11, PERIOD_SIZE = 13, PERIODS = 15 };
enum { ACCESS_RW_INTERLEAVED = 3, FORMAT_S16_LE = 2 };

static struct hw_params params;
static s16 buffer[2 * 960];

static long number(const char *s, long otherwise)
{
    if(!s) return otherwise;
    long v = 0;
    while(*s >= '0' && *s <= '9') v = v * 10 + *s++ - '0';
    return v;
}

static struct elem_value elem;

/** A mixer control of card 0 to the values given (both channels) */
static void control(const char *name, long value)
{
    long fd = sys(SYS_OPEN, (word)"/dev/snd/controlC0", 2, 0);
    if(fd < 0) fail("control open", fd);
    for(word i = 0; i < sizeof elem; i++) ((char *)&elem)[i] = 0;
    elem.iface = IFACE_MIXER;
    for(int i = 0; name[i]; i++) elem.name[i] = name[i];
    elem.values[0] = elem.values[1] = value;
    long r = sys(SYS_IOCTL, fd, ELEM_WRITE, (word)&elem);
    if(r < 0) fail(name, r);
    sys(SYS_CLOSE, fd, 0, 0);
}

static void set_interval(int param, u32 value)
{
    struct interval *i = &params.intervals[param - 8];
    i->min = i->max = value;
    i->flags = INTERVAL_INTEGER;
}

void entry(word *stack)
{
    long argc = (long)stack[0];
    char **argv = (char **)(stack + 1);
    long rate = number(argc > 1 ? argv[1] : 0, 48000);
    long seconds = number(argc > 2 ? argv[2] : 0, 1);
    int tone = argc > 3 && argv[3][0] == 't';
    if(tone)
    {
        control("Master Playback Switch", 1);
        control("Master Playback Volume", 0x4A);
    }

    long fd = sys(SYS_OPEN, (word)"/dev/snd/pcmC0D0p", 2 /* O_RDWR */, 0);
    if(fd < 0) fail("open", fd);

    // everything allowed, then the format asked for; the kernel chooses the rest
    for(int m = 0; m < 3; m++) for(int w = 0; w < 8; w++) params.masks[m].bits[w] = 0xFFFFFFFF;
    for(int i = 0; i < 12; i++) { params.intervals[i].min = 0; params.intervals[i].max = 0xFFFFFFFF; params.intervals[i].flags = 0; }
    for(int w = 0; w < 8; w++) params.masks[MASK_ACCESS].bits[w] = params.masks[MASK_FORMAT].bits[w] = params.masks[MASK_SUBFORMAT].bits[w] = 0;
    params.masks[MASK_ACCESS].bits[0] = 1 << ACCESS_RW_INTERLEAVED;
    params.masks[MASK_FORMAT].bits[0] = 1 << FORMAT_S16_LE;
    params.masks[MASK_SUBFORMAT].bits[0] = 1;
    set_interval(CHANNELS, 2);
    set_interval(RATE, (u32)rate);
    set_interval(PERIOD_SIZE, 960);
    set_interval(PERIODS, 4);
    params.rmask = 0xFFFFFFFF;
    params.info = 0xFFFFFFFF;
    long r = sys(SYS_IOCTL, fd, HW_PARAMS, (word)&params);
    if(r < 0) fail("hw_params", r);
    r = sys(SYS_IOCTL, fd, PREPARE, 0);
    if(r < 0) fail("prepare", r);

    // the pattern: left = frame * 7 (16 bits), right = its complement
    long total = rate * seconds, frame = 0;
    long start = now_ms();
    while(frame < total)
    {
        long n = total - frame < 960 ? total - frame : 960;
        for(long i = 0; i < n; i++)
        {
            s16 v = (s16)((frame + i) * 7);
            // (the tone: half a period of 1 kHz up, half down)
            if(tone) v = (frame + i) * 2000 / rate % 2 ? -8000 : 8000;
            buffer[2 * i] = v;
            buffer[2 * i + 1] = tone ? v : (s16)~v;
        }
        struct xferi x = { 0, buffer, (word)n };
        r = sys(SYS_IOCTL, fd, WRITEI_FRAMES, (word)&x);
        if(r < 0) fail("writei", r);
        frame += x.result;
    }
    r = sys(SYS_IOCTL, fd, DRAIN, 0);
    if(r < 0) fail("drain", r);
    sys(SYS_CLOSE, fd, 0, 0);
    out("PCM_DONE rate="); out_num(rate); out(" frames="); out_num(frame); out(" ms="); out_num(now_ms() - start); out("\n");
    sys(SYS_EXIT, 0, 0, 0);
}

__asm__(".text\n.global _start\n_start:\nmov %rsp,%rdi\nand $-16,%rsp\ncall entry\nud2\n");
                                                                                                     source/v64/tests/devices/hpet.js                                                                    0000755 0000000 0000000 00000026621 00000000000 013760  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The HPET of the Q35 machine (hpet: true), driven through its registers
// with a machine clock the test moves (docs/q35.md): the
// capabilities, the main counter, one-shot and periodic timers in 32- and
// 64-bit mode, the legacy replacement route (and the PIT and RTC losing IRQ
// 0 and 8), I/O APIC routes edge and level triggered, FSB messages (also of
// timer 0 with the legacy replacement route, as Windows has it), the ACPI
// description and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

let host = 1000;
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    hpet: true,
    memory_size: 32 * 1024 * 1024,
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const hpet = cpu.devices.hpet;
// (not running: the machine clock is paused; this test moves it itself)
cpu.clock.resume();

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const BASE = 0xFED00000;
const r32 = offset => cpu.mmap_read32(BASE + offset) >>> 0;
const w32 = (offset, value) => cpu.mmap_write32(BASE + offset, value | 0);
const T = (n, reg) => 0x100 + 0x20 * n + reg;
const CONF = 0x00, CMP = 0x08, FSB = 0x10;
const ENABLE = 1, LEG_RT = 2;
const LEVEL = 1 << 1, INT_ENB = 1 << 2, PERIODIC = 1 << 3, VAL_SET = 1 << 6, MODE32 = 1 << 8, FSB_EN = 1 << 14;
const route = gsi => gsi << 9;
const TICKS_PER_MS = 1e12 / 69841279;

/** Interrupt activity: [kind, line, level] */
let events = [];
const raise = cpu.device_raise_irq, lower = cpu.device_lower_irq, gsi_level = cpu.set_shared_gsi_level;
cpu.device_raise_irq = irq => { events.push(["irq", irq, true]); raise.call(cpu, irq); };
cpu.device_lower_irq = irq => { events.push(["irq", irq, false]); lower.call(cpu, irq); };
cpu.set_shared_gsi_level = function(gsi, source, level) { events.push(["gsi", gsi, level]); gsi_level.call(cpu, gsi, source, level); };
const msis = [];
cpu.apic_msi = (address, data) => { msis.push([address >>> 0, data]); return true; };

/** Move the machine clock on by ms and run the HPET's timers */
function advance(ms)
{
    while(ms > 0)
    {
        const step = Math.min(ms, 500);
        host += step;
        ms -= step;
    }
    return hpet.timer(cpu.clock.now());
}
const counter = () => r32(0xF0) + r32(0xF4) * 2 ** 32;
const hpet_events = () => events.filter(([kind, line]) => kind === "gsi" || line === 0 || line === 8);

test("capabilities: revision 1, three 64-bit timers, legacy route capable, Intel, 14.31818 MHz", () => {
    assert.equal(r32(0x000), 0x8086A201);
    assert.equal(r32(0x004), 69841279, "period: 69841279 fs");
    for(let n = 0; n < 3; n++)
    {
        assert.equal(r32(T(n, CONF)) & 0x8030, 0x8030, "timer " + n + ": periodic and 64-bit capable, FSB delivery");
        assert.equal(r32(T(n, CONF) + 4), 0x00F00000, "routes: I/O APIC 20-23");
        assert.equal(r32(T(n, CMP)), 0xFFFFFFFF, "comparator: all ones");
        assert.equal(r32(T(n, CMP) + 4), 0xFFFFFFFF);
    }
    assert.equal(r32(0x010), 0, "stopped, no legacy route");
});

test("main counter: stopped until enabled, 14.31818 MHz, writable only while stopped", () => {
    advance(50);
    assert.equal(counter(), 0, "stopped");
    w32(0x010, ENABLE);
    advance(10);
    assert.ok(Math.abs(counter() - 10 * TICKS_PER_MS) <= 1, "10 ms: " + counter());
    w32(0x010, 0);
    const frozen = counter();
    advance(10);
    assert.equal(counter(), frozen, "stopped again");
    w32(0xF0, 0xFFFFFFF0);
    w32(0xF4, 1);
    assert.equal(counter(), 2 ** 32 + 0xFFFFFFF0, "written while stopped");
    w32(0x010, ENABLE);
    advance(1);
    assert.ok(Math.abs(counter() - (2 ** 32 + 0xFFFFFFF0 + TICKS_PER_MS)) <= 1, "counts on from there, past 2^32");
    w32(0xF0, 0);
    assert.ok(counter() > 2 ** 32, "not writable while running");
    w32(0x010, 0);
    w32(0xF0, 0);
    w32(0xF4, 0);
    w32(0x010, ENABLE);
});

test("one-shot, 32-bit mode (as Linux programs it), I/O APIC input 20, edge", () => {
    events = [];
    w32(T(0, CONF), INT_ENB | MODE32 | route(20));
    assert.equal(r32(T(0, CMP) + 4), 0, "32-bit mode: the comparator's upper half is 0");
    const at = (counter() + 14318) >>> 0;   // about 1 ms
    w32(T(0, CMP), at);
    const wait = advance(0.5);
    assert.deepEqual(hpet_events(), [], "not yet");
    assert.ok(wait > 0.4 && wait < 0.6, "the next match in about 0.5 ms: " + wait);
    advance(0.6);
    assert.deepEqual(hpet_events(), [["gsi", 20, true], ["gsi", 20, false]], "an edge on input 20");
    events = [];
    advance(10);
    assert.deepEqual(hpet_events(), [], "once");
    w32(T(0, CONF), 0);
});

test("periodic, 32-bit: Tn_VAL_SET sets the comparator, then the period; missed periods coalesce", () => {
    events = [];
    const now = counter();
    w32(T(0, CONF), INT_ENB | PERIODIC | VAL_SET | MODE32 | route(21));
    w32(T(0, CMP), now + 1000);             // the comparator
    w32(T(0, CMP), 2000);                   // then the period
    assert.equal(r32(T(0, CONF)) & VAL_SET, 0, "VAL_SET clears itself");
    assert.equal(r32(T(0, CMP)), now + 1000);
    advance(1000 / TICKS_PER_MS + 0.01);
    assert.equal(hpet_events().length, 2, "the first match");
    assert.equal(r32(T(0, CMP)), now + 3000, "the comparator moves on by the period");
    events = [];
    advance(2000 / TICKS_PER_MS);
    assert.equal(hpet_events().length, 2, "the second, a period later");
    events = [];
    advance(20000 / TICKS_PER_MS);
    assert.equal(hpet_events().length, 2, "ten periods late: one interrupt");
    assert.ok(r32(T(0, CMP)) > counter() % 2 ** 32, "the comparator ahead of the counter again");
    w32(T(0, CONF), 0);
});

test("periodic, 64-bit (timer 1): comparator and period in two halves", () => {
    events = [];
    const now = counter();
    w32(T(1, CONF), INT_ENB | PERIODIC | VAL_SET | route(22));
    w32(T(1, CMP), now + 500);
    assert.equal(r32(T(1, CONF)) & VAL_SET, VAL_SET, "64-bit: VAL_SET stays for the upper half");
    w32(T(1, CMP) + 4, 0);
    assert.equal(r32(T(1, CONF)) & VAL_SET, 0);
    w32(T(1, CMP), 1500);
    w32(T(1, CMP) + 4, 0);
    assert.equal(r32(T(1, CMP)), now + 500, "then only the period changes");
    assert.equal(r32(T(1, CMP) + 4), 0);
    advance(600 / TICKS_PER_MS);
    advance(1500 / TICKS_PER_MS);
    assert.equal(hpet_events().length, 4, "two matches");
    w32(T(1, CONF), 0);
});

test("legacy replacement route: timers 0 and 1 on IRQ 0 and 8; the PIT and the RTC lose them", () => {
    const pit = cpu.devices.pit, rtc = cpu.devices.rtc;
    assert.ok(pit.drives_irq0() && rtc.drives_irq8());
    w32(0x010, ENABLE | LEG_RT);
    assert.ok(!pit.drives_irq0() && !rtc.drives_irq8(), "taken");
    events = [];
    w32(T(0, CONF), INT_ENB | MODE32 | route(20));
    w32(T(0, CMP), counter() + 100 >>> 0);
    w32(T(1, CONF), INT_ENB | MODE32);
    w32(T(1, CMP), counter() + 200 >>> 0);
    advance(300 / TICKS_PER_MS);
    assert.deepEqual(hpet_events(), [["irq", 0, true], ["irq", 0, false], ["irq", 8, true], ["irq", 8, false]],
        "timer 0 on IRQ 0 (not input 20), timer 1 on IRQ 8");
    w32(0x010, ENABLE);
    assert.ok(pit.drives_irq0() && rtc.drives_irq8(), "given back");
    w32(T(0, CONF), 0);
    w32(T(1, CONF), 0);
});

test("level triggered (timer 2, input 23): GINTR_STA, the line held until the status is cleared", () => {
    events = [];
    w32(T(2, CONF), INT_ENB | LEVEL | MODE32 | route(23));
    w32(T(2, CMP), counter() + 100 >>> 0);
    advance(200 / TICKS_PER_MS);
    assert.deepEqual(hpet_events(), [["gsi", 23, true]]);
    assert.equal(r32(0x020), 4, "status of timer 2");
    assert.ok(cpu.shared_irq_sources[23].size > 0);
    cpu.mmap_write8(BASE + 0x020, 0);
    assert.equal(r32(0x020), 4, "a byte write of 0 clears nothing");
    w32(0x020, 4);
    assert.equal(r32(0x020), 0);
    assert.deepEqual(hpet_events(), [["gsi", 23, true], ["gsi", 23, false]], "cleared: the line drops");
    w32(T(2, CONF), 0);
});

test("FSB delivery: the timer's message to the local APIC", () => {
    msis.length = 0;
    events = [];
    w32(T(1, FSB) + 4, 0xFEE00000);
    w32(T(1, FSB), 0x0041);
    w32(T(1, CONF), INT_ENB | MODE32 | FSB_EN | route(20));
    w32(T(1, CMP), counter() + 100 >>> 0);
    advance(200 / TICKS_PER_MS);
    assert.deepEqual(msis, [[0xFEE00000, 0x41]]);
    assert.deepEqual(hpet_events(), [], "no line");
    w32(T(1, CONF), 0);
});

test("FSB delivery before the legacy replacement route (as Windows uses timer 0, and QEMU has it)", () => {
    w32(0x010, ENABLE | LEG_RT);
    msis.length = 0;
    events = [];
    w32(T(0, FSB) + 4, 0xFEE0100C);
    w32(T(0, FSB), 0x49D1);
    w32(T(0, CONF), INT_ENB | MODE32 | FSB_EN);
    w32(T(0, CMP), counter() + 100 >>> 0);
    advance(200 / TICKS_PER_MS);
    assert.deepEqual(msis, [[0xFEE0100C, 0x49D1]], "timer 0's message");
    assert.deepEqual(hpet_events(), [], "not IRQ 0");
    assert.ok(!cpu.devices.pit.drives_irq0(), "the PIT still loses IRQ 0");
    w32(T(0, CONF), 0);
    w32(0x010, ENABLE);
});

test("ACPI: the HPET table (in the tables SeaBIOS loads), a PNP0103 device in the DSDT", () => {
    const file = cpu.option_roms.find(rom => rom.name === "etc/acpi/tables");
    const data = file.get_data ? file.get_data() : file.data;
    const text = Buffer.from(data);
    const at = text.indexOf(Buffer.from([0x48, 0x50, 0x45, 0x54, 56, 0, 0, 0]));     // "HPET", length 56
    assert.ok(at >= 0, "the HPET table");
    const u32 = a => text.readUInt32LE(a);
    assert.equal(u32(at + 4), 56, "its length");
    assert.equal(u32(at + 36), 0x8086A201, "event timer block ID: GCAP_ID");
    assert.equal(text[at + 40], 0, "system memory");
    assert.equal(u32(at + 44), BASE, "base address");
    assert.equal(text.subarray(at, at + 56).reduce((a, b) => a + b, 0) & 0xFF, 0, "checksum");
    // the DSDT: Device (HPET) with _HID EISAID("PNP0103") (41 D0 01 03)
    assert.ok(text.indexOf(Buffer.from([0x5B, 0x82])) >= 0 && text.indexOf(Buffer.from([0x0C, 0x41, 0xD0, 0x01, 0x03])) >= 0, "PNP0103");
});

// a periodic timer across a snapshot
events = [];
const start = counter();
w32(T(0, CONF), INT_ENB | PERIODIC | VAL_SET | MODE32 | route(20));
w32(T(0, CMP), start + 1000);
w32(T(0, CMP), 4000);
const state = await emulator.save_state();
w32(T(0, CONF), 0);
w32(0x010, 0);
await emulator.restore_state(state);
cpu.clock.resume();
test("snapshot: the counter runs on, the periodic timer keeps comparator and period", () => {
    events = [];
    assert.equal(r32(0x010), ENABLE);
    assert.equal(r32(T(0, CMP)), start + 1000);
    advance(1100 / TICKS_PER_MS);
    assert.equal(hpet_events().length, 2, "the first match");
    advance(4000 / TICKS_PER_MS);
    assert.equal(hpet_events().length, 4, "a period later");
    w32(T(0, CONF), 0);
});

emulator.destroy();
console.log((failed ? "FAIL" : "PASS") + ": " + passed + " HPET tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                               source/v64/tests/devices/ich9_tco.js                                                                0000755 0000000 0000000 00000012253 00000000000 014515  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The TCO watchdog of the Q35 machine's ICH9 (PMBASE + 0x60), with a
// machine clock the test moves (docs/q35.md): stopped
// until software reloads it, 0.6 s ticks from TCO_TMR, TIMEOUT on the first
// timeout and SMI_STS.TCO_STS, SECOND_TO_STS and BOOT_STS on the second, a
// reset only with NO_REBOOT (RCBA GCS) cleared, reloads keeping it from
// firing, TCO_TMR_HLT, TCO_LOCK and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

let host = 1000;
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    memory_size: 32 * 1024 * 1024,
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
cpu.clock.resume();

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

// the PM block at 0x600 and the root complex registers, as SeaBIOS sets them up
const LPC = 0x1F << 3;
pci.config_write(LPC, 0x40, 4, 0x601);
pci.config_write(LPC, 0x44, 1, 0x80);
pci.config_write(LPC, 0xF0, 4, 0xFED1C001);
const TCO = 0x660, RLD = 0, STS1 = 4, STS2 = 6, CNT1 = 8, TMR = 0x12;
const inw = offset => cpu.io.port_read16(TCO + offset);
const outw = (offset, value) => cpu.io.port_write16(TCO + offset, value);
const SMI_STS = 0x634;
const GCS = 0xFED1C000 + 0x3410;
const TIMEOUT = 1 << 3, SECOND_TO = 1 << 1, BOOT = 1 << 2, HLT = 1 << 11, LOCK = 1 << 12;

const resets = [];
cpu.reboot_internal = reason => { resets.push(reason); };
function advance(ms)
{
    for(; ms > 0; ms -= 100)
    {
        host += Math.min(ms, 100);
        cpu.devices.acpi.timer(cpu.clock.now());
    }
}

test("registers: defaults, stopped until reloaded", () => {
    assert.equal(inw(TMR), 4, "TCO_TMR: 4 ticks (2.4 s)");
    assert.equal(inw(CNT1), 0);
    advance(10000);
    assert.equal(inw(STS1), 0, "not running");
    assert.equal(cpu.read32s(GCS) & 0x20, 0x20, "NO_REBOOT set at reset");
});

test("first timeout: TIMEOUT, an SMI with SMI_EN.TCO_EN; second: SECOND_TO_STS, BOOT_STS; no reset with NO_REBOOT", () => {
    cpu.io.port_write32(0x630, 1 << 13);   // SMI_EN.TCO_EN
    outw(TMR, 4);
    outw(RLD, 1);
    advance(1300);
    assert.equal(inw(RLD), 1, "about 1 tick left after 1.3 s");
    advance(1200);
    assert.equal(inw(STS1) & TIMEOUT, TIMEOUT, "first timeout at 2.4 s");
    assert.equal(cpu.io.port_read16(SMI_STS) & 0x2000, 0x2000, "SMI_STS.TCO_STS");
    assert.ok(cpu.smm_active(), "the SMI: the CPU is in SMM");
    assert.equal(inw(STS2) & (SECOND_TO | BOOT), 0);
    advance(2400);
    assert.equal(inw(STS2) & (SECOND_TO | BOOT), SECOND_TO | BOOT, "second timeout");
    assert.deepEqual(resets, [], "NO_REBOOT: no reset");
    advance(5000);
    assert.equal(inw(RLD), 0, "BOOT_STS keeps it stopped");
    outw(STS1, TIMEOUT);
    outw(STS2, SECOND_TO | BOOT);
    assert.equal(inw(STS1) & TIMEOUT, 0, "write one to clear");
    assert.equal(inw(STS2), 0);
    cpu.io.port_write16(SMI_STS, 0x2000);
    cpu.io.port_write32(0x630, 0);
});

test("reloads (iTCO_wdt's pings) keep it from timing out", () => {
    outw(RLD, 1);
    for(let i = 0; i < 10; i++)
    {
        advance(2000);
        outw(RLD, 1);
    }
    assert.equal(inw(STS1) & TIMEOUT, 0);
});

test("with NO_REBOOT cleared, the second timeout resets the machine", () => {
    cpu.write32(GCS, cpu.read32s(GCS) & ~0x20);
    assert.equal(cpu.read32s(GCS) & 0x20, 0);
    outw(RLD, 1);
    advance(2500);
    assert.deepEqual(resets, [], "first timeout");
    outw(STS1, TIMEOUT);
    advance(2500);
    assert.deepEqual(resets, ["tco"], "second timeout: reset");
});

test("TCO_TMR_HLT stops it; TCO_LOCK stays set", () => {
    cpu.devices.acpi.tco.reset();
    outw(CNT1, HLT);
    outw(RLD, 1);
    advance(5000);
    assert.equal(inw(STS1) & TIMEOUT, 0, "halted");
    outw(CNT1, 0);
    advance(2500);
    assert.equal(inw(STS1) & TIMEOUT, TIMEOUT, "running once HLT is cleared");
    outw(CNT1, LOCK | HLT);
    outw(CNT1, HLT);
    assert.equal(inw(CNT1) & LOCK, LOCK, "TCO_LOCK cannot be cleared");
});

cpu.devices.acpi.tco.reset();
outw(TMR, 10);
outw(RLD, 1);
advance(3000);
const state = await emulator.save_state();
outw(CNT1, HLT);
await emulator.restore_state(state);
cpu.clock.resume();
test("snapshot: the running timer goes on from where it was", () => {
    assert.equal(inw(RLD), 5, "5 of 10 ticks left");
    advance(3100);
    assert.equal(inw(STS1) & TIMEOUT, TIMEOUT);
});

emulator.destroy();
console.log((failed ? "FAIL" : "PASS") + ": " + passed + " TCO tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/devices/ide_disk_image.js                                                          0000755 0000000 0000000 00000026037 00000000000 015736  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// An IDE hard disk from a QCOW2 image (docs/disk-image-formats-plan.md P0,
// P1), driven through the ports; no guest code runs. The image is built in
// memory (tests/image/tiny_qcow2.mjs): 3 TiB, data around 2^32 sectors.
// - IDENTIFY reports the virtual size, not the file's; READ SECTORS EXT
//   across 2^32 sectors; writes stay in memory, the image is not changed;
// - a damaged L2 entry: the read ends with ERR/ABRT, the next one works; a
//   write past the memory budget too;
// - snapshots: restored onto the same image, refused before anything is
//   restored for another image;
// - from a file read in ranges: a snapshot waits for the read in flight, a
//   reset drops it.

import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import { createHash as create_hash } from "node:crypto";
import { build_qcow2 } from "../image/tiny_qcow2.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SECTORS = 6 * 2 ** 30; // 3 TiB
const BOUNDARY = 2 ** 32 * 512;
const pattern = new Uint8Array(4 * 65536).map((_, i) => i * 31 + (i >> 9) & 0xFF);
const first = new Uint8Array(65536).map((_, i) => i & 0xFF ^ 0x5A);
const image = build_qcow2({
    size: SECTORS * 512,
    data: [[0, first], [BOUNDARY - 2 * 65536, pattern]],
    zero: [65536],
    damaged: [BOUNDARY + 4 * 65536],
});
const image_sha256 = create_hash("sha256").update(image).digest("hex");
const expected = (offset, length) =>
{
    const result = new Uint8Array(length);
    for(const [start, bytes] of [[0, first], [BOUNDARY - 2 * 65536, pattern]])
    {
        const from = Math.max(start, offset), to = Math.min(start + bytes.length, offset + length);
        if(from < to) result.set(bytes.subarray(from - start, to - start), from - offset);
    }
    return result;
};

function config(hda)
{
    return {
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        hda,
        autostart: false,
        memory_size: 32 * 1024 * 1024,
        log_level: 0,
    };
}

const emulator = new V86(config({ buffer: image.buffer, format: "qcow2", overlay_limit: 64 * 1024 * 1024, disk_error: "report" }));
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const io = emulator.v86.cpu.io;

const DATA = 0x1F0, ERROR = 0x1F1, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const NIEN = 0x02, DRQ = 0x08, ERR = 0x01, BSY = 0x80, ABRT = 0x04;
io.port_write8(CONTROL, NIEN);

function read_words(count)
{
    assert.equal(io.port_read8(COMMAND) & (DRQ | ERR), DRQ, "data ready");
    return Array.from({ length: count }, () => io.port_read16(DATA));
}

function command_ext(lba, count, command)
{
    io.port_write8(DEVICE, 0x40);
    io.port_write8(COUNT, count >> 8);
    io.port_write8(LBA_LOW, Math.floor(lba / 2 ** 24) & 0xFF);
    io.port_write8(LBA_MID, Math.floor(lba / 2 ** 32) & 0xFF);
    io.port_write8(LBA_HIGH, Math.floor(lba / 2 ** 40) & 0xFF);
    io.port_write8(COUNT, count & 0xFF);
    io.port_write8(LBA_LOW, lba & 0xFF);
    io.port_write8(LBA_MID, lba >> 8 & 0xFF);
    io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
    io.port_write8(COMMAND, command);
}

async function until_ready()
{
    for(let i = 0; i < 1000 && io.port_read8(COMMAND) & BSY; i++) await new Promise(resolve => setTimeout(resolve, 1));
}

async function read_sectors(lba, count)
{
    command_ext(lba, count, 0x24);
    await until_ready();
    const bytes = new Uint8Array(count * 512);
    for(let s = 0; s < count; s++)
    {
        const words = read_words(256);
        words.forEach((w, i) => { bytes[s * 512 + i * 2] = w; bytes[s * 512 + i * 2 + 1] = w >> 8; });
    }
    return bytes;
}

async function write_sectors(lba, bytes)
{
    command_ext(lba, bytes.length / 512, 0x34);
    for(let i = 0; i < bytes.length; i += 2)
    {
        if(i % 512 === 0) assert.equal(io.port_read8(COMMAND) & (DRQ | ERR), DRQ, "ready for data");
        io.port_write16(DATA, bytes[i] | bytes[i + 1] << 8);
    }
    await until_ready();
}

// IDENTIFY: the virtual size
io.port_write8(DEVICE, 0xE0);
io.port_write8(COMMAND, 0xEC);
const identify = read_words(256);
assert.deepEqual(identify.slice(100, 104), [0x0000, 0x8000, 0x0001, 0x0000], "words 100-103: 3 TiB, the image's virtual size");
assert.ok(image.length < 1 << 20, "the file is small");
console.log("ok - IDENTIFY: the virtual size (3 TiB) of a file of " + image.length + " bytes");

// reads: the first sectors, a zero cluster, across 2^32 sectors
assert.deepEqual(await read_sectors(0, 2), expected(0, 1024), "the first sectors");
assert.deepEqual(await read_sectors(128, 1), new Uint8Array(512), "a zero cluster");
const lba = BOUNDARY / 512;
assert.deepEqual(await read_sectors(lba - 2, 4), expected(BOUNDARY - 1024, 2048), "across 2^32 sectors");
console.log("ok - READ SECTORS EXT: the image's data, across 2^32 sectors");

// writes stay in memory
const written = new Uint8Array(1024).map((_, i) => 255 - (i & 0xFF));
await write_sectors(lba + 1, written);
assert.equal(io.port_read8(COMMAND) & ERR, 0);
assert.deepEqual(await read_sectors(lba, 3), Uint8Array.from([...expected(BOUNDARY, 512), ...written]), "read back");
assert.equal(create_hash("sha256").update(image).digest("hex"), image_sha256, "the image is not changed");
console.log("ok - WRITE SECTORS EXT: read back, the image unchanged");

// a damaged L2 entry: ERR with ABRT; the next command works
command_ext(lba + 4 * 128, 1, 0x24);
await until_ready();
assert.equal(io.port_read8(COMMAND) & (ERR | DRQ | BSY), ERR, "the read failed");
assert.equal(io.port_read8(ERROR), ABRT, "ABRT");
assert.deepEqual(await read_sectors(0, 1), expected(0, 512), "the next read works");
console.log("ok - a damaged cluster: the read ends with ERR/ABRT, the disk goes on");

// past the memory budget: the write fails
const budget = emulator.v86.cpu.devices.ide.primary.master.buffer;
budget.overlay.limit = budget.overlay.size() + 512;
command_ext(1000, 2, 0x34);
for(let i = 0; i < 512; i++) io.port_write16(DATA, 0x1111);
await until_ready();
assert.equal(io.port_read8(COMMAND) & (ERR | DRQ), ERR, "the write (two sectors, more than the budget) failed");
assert.equal(io.port_read8(ERROR), ABRT);
budget.overlay.limit = Infinity;
console.log("ok - a write past the memory budget ends with ERR/ABRT");

// snapshots
const state = await emulator.save_state();
await write_sectors(lba + 1, new Uint8Array(1024));
await emulator.restore_state(state);
assert.deepEqual(await read_sectors(lba + 1, 2), written, "the snapshot's writes");
const other = new V86(config({ buffer: build_qcow2({ size: SECTORS * 512, data: [[0, first]] }).buffer, format: "qcow2" }));
await new Promise(resolve => other.add_listener("emulator-loaded", resolve));
const memory_before = other.v86.cpu.mem8.slice(0, 1 << 20);
await assert.rejects(other.restore_state(state), /another image/);
assert.deepEqual(other.v86.cpu.mem8.slice(0, 1 << 20), memory_before, "nothing was restored");
const raw = new V86(config({ buffer: new ArrayBuffer(16 << 20) }));
await new Promise(resolve => raw.add_listener("emulator-loaded", resolve));
await assert.rejects(raw.restore_state(state), /container format, this machine's is RAW/);
other.destroy();
raw.destroy();
console.log("ok - snapshots: restored onto the same image; another image or RAW refused before restoring");
emulator.destroy();

// a file read in ranges: in-flight reads, snapshots and resets
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-image-"));
const image_file = path.join(temp, "disk.qcow2");
fs.writeFileSync(image_file, image);
const lazy = new V86(config({ url: image_file, async: true, format: "auto" }));
let error;
lazy.add_listener("emulator-error", e => { error = e; });
await new Promise(resolve => lazy.add_listener("emulator-loaded", resolve));
assert.equal(error, undefined);
const cpu = lazy.v86.cpu;
const lazy_io = cpu.io;
lazy_io.port_write8(CONTROL, NIEN);
const drive = cpu.devices.ide.primary.master;
let completed = false;
drive.read_buffer(BOUNDARY - 65536, 4096, data => { completed = data; });
assert.equal(cpu["snapshot_io_pending"], 1, "a read in flight");
const saved = await lazy.save_state();
assert.ok(completed, "the snapshot waited for it");
assert.deepEqual(completed, expected(BOUNDARY - 65536, 4096));
assert.ok(saved.byteLength > 0);
completed = false;
drive.read_buffer(4 * 65536 + BOUNDARY, 512, () => { completed = true; }, () => { completed = true; });
cpu.reboot_internal("test");
await new Promise(resolve => setTimeout(resolve, 200));
assert.equal(completed, false, "a reset drops the read in flight");
assert.equal(cpu["snapshot_io_pending"], 0);
lazy.destroy();
fs.rmSync(temp, { recursive: true });
console.log("ok - from a file: a snapshot waits for the read in flight, a reset drops it");

// export (P2): the disk as the guest sees it, after the disk I/O in flight
{
    const small = build_qcow2({ size: 1 << 20, data: [[0, first]] });
    const small_file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-image-")), "small.qcow2");
    fs.writeFileSync(small_file, small);
    const machine = new V86(config({ url: small_file, async: true, format: "qcow2" }));
    await new Promise(resolve => machine.add_listener("emulator-loaded", resolve));
    const disk = machine.v86.cpu.devices.ide.primary.master;
    const written = new Uint8Array(1024).fill(0xEE);
    await new Promise(resolve => disk.write_to_backend(131072, written, resolve));
    let read_done = false;
    disk.read_buffer(65536 * 8, 4096, () => { read_done = true; });
    const chunks = [];
    const info = await machine.disk_image_info("hda");
    assert.deepEqual([info.format, info.size, info.file_size, info.written], ["qcow2", 1 << 20, small.length, 1024]);
    const size = await machine.export_disk_image("hda", { write: chunk => { assert.ok(read_done, "after the read in flight"); chunks.push(chunk); } });
    assert.equal(size, 1 << 20);
    const expected_disk = new Uint8Array(1 << 20);
    expected_disk.set(first);
    expected_disk.set(written, 131072);
    assert.deepEqual(new Uint8Array(Buffer.concat(chunks)), expected_disk);
    await assert.rejects(machine.export_disk_image("hdb", { write() {} }), /No disk hdb/);
    machine.destroy();
    fs.rmSync(path.dirname(small_file), { recursive: true });
    console.log("ok - export_disk_image: RAW with the guest's writes, after the read in flight; disk_image_info");
}

// a disk that cannot be opened: emulator-error
const broken = new V86(config({ buffer: new Uint8Array(65536).buffer, format: "qcow2" }));
const failure = await new Promise(resolve => broken.add_listener("emulator-error", resolve));
assert.match(failure.message, /hda: not a qcow2 image/);
console.log("ok - a disk that is not of its format fails the start (emulator-error)");

console.log("IDE disk image tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/devices/ide_large_disk.js                                                          0000755 0000000 0000000 00000010276 00000000000 015744  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// 48-bit ATA addressing on a disk larger than 2^32 sectors (3 TiB, never
// allocated: reads return their own byte offset). Ports are accessed
// directly; no guest code runs. [ATA-6] 6.2 (HOB), 8.16 (IDENTIFY words
// 60-61 and 100-103), 8.33 (READ NATIVE MAX ADDRESS EXT), 8.36 (READ SECTORS EXT).

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SECTORS = 6 * 2 ** 30; // 3 TiB: 0x1_8000_0000 sectors
const reads = [];
const disk = {
    byteLength: SECTORS * 512,
    load() { this.onload?.({}); },
    get(start, length, done)
    {
        assert.ok(Number.isSafeInteger(start) && start >= 0 && start + length <= this.byteLength, "read in range");
        reads.push(start);
        const data = new Uint8Array(length);
        new DataView(data.buffer).setBigUint64(0, BigInt(start), true);
        done(data);
    },
    get_and_cache(start, length, done) { this.get(start, length, done); },
    get_from_cache() { return undefined; },
    set(start, data, done) { done(); },
    get_buffer(done) { done(undefined); },
};

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: disk,
    autostart: false,
    memory_size: 32 * 1024 * 1024,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const io = emulator.v86.cpu.io;

const DATA = 0x1F0, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const NIEN = 0x02, HOB = 0x80, DRQ = 0x08, ERR = 0x01;
io.port_write8(CONTROL, NIEN);

function read_words(count)
{
    assert.equal(io.port_read8(COMMAND) & (DRQ | ERR), DRQ, "data ready");
    return Array.from({ length: count }, () => io.port_read16(DATA));
}

// IDENTIFY: the 28-bit capacity saturates, the 48-bit one is complete
io.port_write8(DEVICE, 0xE0);
io.port_write8(COMMAND, 0xEC);
const identify = read_words(256);
assert.equal(identify[60] | identify[61] << 16, 0x0FFFFFFF, "words 60-61 capped for 28-bit commands");
assert.deepEqual(identify.slice(100, 104), [0x0000, 0x8000, 0x0001, 0x0000], "words 100-103: 0x1_8000_0000 sectors");
assert.ok(identify[83] & 1 << 10, "48-bit address feature set supported");

// READ NATIVE MAX ADDRESS EXT: bits 24-47 are read back with HOB set
io.port_write8(DEVICE, 0x40);
io.port_write8(COMMAND, 0x27);
assert.equal(io.port_read8(COMMAND) & ERR, 0);
const low = [LBA_LOW, LBA_MID, LBA_HIGH].map(port => io.port_read8(port));
io.port_write8(CONTROL, NIEN | HOB);
const high = [LBA_LOW, LBA_MID, LBA_HIGH].map(port => io.port_read8(port));
io.port_write8(CONTROL, NIEN);
const max = low[0] + low[1] * 2 ** 8 + low[2] * 2 ** 16 + high[0] * 2 ** 24 + high[1] * 2 ** 32 + high[2] * 2 ** 40;
assert.equal(max, SECTORS - 1, "native max address");

// READ SECTORS EXT above 2^32 sectors: the high order byte of each register
// is written first
function read_sector(lba)
{
    const bytes = [0, 1, 2, 3, 4, 5].map(i => Math.floor(lba / 2 ** (8 * i)) & 0xFF);
    io.port_write8(COUNT, 0); io.port_write8(COUNT, 1);
    io.port_write8(LBA_LOW, bytes[3]); io.port_write8(LBA_LOW, bytes[0]);
    io.port_write8(LBA_MID, bytes[4]); io.port_write8(LBA_MID, bytes[1]);
    io.port_write8(LBA_HIGH, bytes[5]); io.port_write8(LBA_HIGH, bytes[2]);
    io.port_write8(DEVICE, 0x40);
    io.port_write8(COMMAND, 0x24);
    const words = read_words(256);
    return words[0] + words[1] * 2 ** 16 + words[2] * 2 ** 32 + words[3] * 2 ** 48;
}
for(const lba of [0x1_2345_6789, 0xFFFF_FFFF, 0x1_0000_0000, SECTORS - 1])
{
    reads.length = 0;
    assert.equal(read_sector(lba), lba * 512, `LBA ${lba.toString(16)}: the data came from its byte offset`);
    assert.deepEqual(reads, [lba * 512]);
}

emulator.destroy();
console.log("PASS ide_large_disk: IDENTIFY capacity words, HOB reads of READ NATIVE MAX ADDRESS EXT, READ SECTORS EXT beyond 2^32 sectors");
                                                                                                                                                                                                                                                                                                                                  source/v64/tests/devices/mmio_ram.js                                                                0000755 0000000 0000000 00000013021 00000000000 014606  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Device memory behind a movable PCI memory BAR (src/rust/cpu/mmio_ram.rs,
// docs/display-design.md), exercised through the VGA's
// linear frame buffer: it is decoded where SeaBIOS assigns BAR0, pixels
// written there reach the screen, it moves when the guest moves the BAR (and
// stops being decoded at the old place), the banked window does not care
// where it is, and a snapshot brings the BAR back where the guest had it.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const { V86 } = await import("../../src/main.js");

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    vram_size: 8 * 1024 * 1024,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await new Promise(resolve => setTimeout(resolve, 3000));
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io, vga = cpu.devices.vga;
const VGA_BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | VGA_BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_write = (reg, value) => { io.port_write32(0xcf8, 0x80000000 | VGA_BDF << 8 | reg); io.port_write32(0xcfc, value); };
const dispi = (index, value) => { io.port_write16(0x1ce, index); io.port_write16(0x1cf, value); };
const WIDTH = 64, HEIGHT = 48;
const pixel = (x, y) => {
    cpu.devices.display.request_frame();
    const p = (y * vga.pixels.width + x) * 4;
    return [...vga.pixels.data.subarray(p, p + 3)];
};
const put = (base, x, y, xrgb) => {
    const address = base + (y * WIDTH + x) * 4;
    for(let i = 0; i < 4; i++) cpu.write8(address + i, xrgb >>> 8 * i & 0xFF);
};

const bar = pci_read(0x10);
const base = (bar & ~0xF) >>> 0;
console.log("SeaBIOS put BAR0 at " + base.toString(16) + " (flags " + (bar & 0xF) + ")");
assert.equal(bar & 0xF, 0x8, "BAR0 stays a prefetchable 32-bit memory BAR");
assert.equal(base % (8 << 20), 0, "aligned to its size");
assert.equal(vga.lfb_address, base, "the frame buffer is decoded where the BAR is");

// 64x48, 32 bpp, LFB
dispi(4, 0); dispi(1, WIDTH); dispi(2, HEIGHT); dispi(3, 32); dispi(4, 0x41);
put(base, 10, 5, 0x00112233);
assert.deepEqual(pixel(10, 5), [0x11, 0x22, 0x33], "written through the LFB, shown on the screen");

const moved = (base + (16 << 20)) >>> 0;
pci_write(0x10, 0xFFFFFFFF);
assert.equal(pci_read(0x10), (~((8 << 20) - 1) | 0x8) >>> 0, "sizing reports 8 MiB");
assert.equal(vga.lfb_address, base, "sizing does not move it");
pci_write(0x10, moved);
assert.equal(pci_read(0x10), (moved | 0x8) >>> 0, "the guest moves BAR0");
assert.equal(vga.lfb_address, moved);
assert.equal(cpu.read8(moved + (5 * WIDTH + 10) * 4), 0x33, "the same memory at the new place");
put(moved, 11, 5, 0x00445566);
assert.deepEqual(pixel(11, 5), [0x44, 0x55, 0x66], "written at the new place, shown on the screen");
put(base, 12, 5, 0x00778899);
assert.deepEqual(pixel(12, 5), [0, 0, 0], "the old place no longer reaches the frame buffer");
console.log("PASS: the frame buffer follows BAR0, " + base.toString(16) + " -> " + moved.toString(16));

// The banked window at 0xA0000 reaches the frame buffer wherever the BAR is
dispi(5, 0);
cpu.write8(0xA0000 + (6 * WIDTH + 2) * 4 + 2, 0x7f);
assert.equal(cpu.read8(moved + (6 * WIDTH + 2) * 4 + 2), 0x7f);
assert.deepEqual(pixel(2, 6), [0x7f, 0, 0], "banked writes are shown too");
console.log("PASS: the banked window is independent of BAR0");

// Page flipping: with the second page shown (Y offset), writes to the pages
// above and below it are dirty but not on the screen, and render passes no
// rows for them (it passed a negative height, and the CPU Worker's copy threw
// "Invalid typed array length": Yuri's Revenge drawing its DirectDraw back buffer)
{
    const heights = [];
    const update_buffer = vga.display.update_buffer;
    vga.display.update_buffer = function(layers)
    {
        for(const l of layers) heights.push(l.buffer_height);
        return update_buffer.call(this, layers);
    };
    dispi(9, HEIGHT);
    pixel(0, 0);
    heights.length = 0;
    for(const y of [4, HEIGHT - 10, 2 * HEIGHT + 3])
    {
        put(moved, 3, y, 0x00ABCDEF);
        pixel(0, 0);
    }
    assert.deepEqual(heights, [], "no rows for the pages that are not shown");
    put(moved, 4, HEIGHT + 7, 0x00123456);
    assert.deepEqual(pixel(4, 7), [0x12, 0x34, 0x56], "the shown page still reaches the screen");
    assert.ok(heights.length === 1 && heights[0] > 0, "the rows of the written page: " + heights);
    vga.display.update_buffer = update_buffer;
    dispi(9, 0);
    console.log("PASS: dirty rows off the shown page are not passed on");
}

const state = await emulator.save_state();
pci_write(0x10, base);
assert.equal(vga.lfb_address, base);
await emulator.restore_state(state);
assert.equal(pci_read(0x10), (moved | 0x8) >>> 0, "the snapshot's BAR");
assert.equal(vga.lfb_address, moved, "the frame buffer is back where the snapshot's guest had it");
assert.equal(cpu.read8(moved + (5 * WIDTH + 11) * 4), 0x66);
console.log("PASS: a snapshot restores the moved BAR");

await emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/devices/pcie_hotplug.mjs                                                           0000755 0000000 0000000 00000024353 00000000000 015657  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// PCI Express native hot plug on the Q35 machine's root ports
// (src/pcie_root_port.js) with an unmodified Linux: Alpine's x86_64 virt
// kernel (6.18, pciehp built in) booted directly, the pinned Alpine ISO as
// the CD (downloaded on first use, as tests/x64/linux_boot.mjs does). Three
// root ports:
//   port 0 (slot 1): the virtio NIC (net_device), plugged in at boot
//   port 1 (slot 2): a virtio function Linux has no driver for (device type
//     21, signal distribution), plugged in at boot
//   port 2 (slot 3): a virtio entropy device, not plugged in (pcie_plugged: false)
// Linux takes the slots over (_OSC); the empty one is off. The entropy
// device is hot added (/dev/hwrng reads it) and taken out by the attention
// button (Linux releases it and switches the slot off); the NIC goes the
// same way and comes back (eth0 sends again); the driverless function is
// pulled out without notice (a surprise removal) and plugged in again. (A
// surprise removal of a virtio device that has a driver hangs Linux's
// pciehp thread: vp_reset waits for device_status to read 0, and a card
// that is gone reads as all ones.)
// SHOW_LOGS=1 shows the serial console, TEST_RELEASE_BUILD=1 tests the
// release build, DISABLE_JIT=1 the interpreter (several minutes to boot).

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const DISABLE_JIT = +process.env.DISABLE_JIT;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const ROOT = __dirname + "/../../";
// (the pinned ISO, downloaded, checked and unpacked: tests/lib/alpine_image.mjs)
const { directory: DIRECTORY, image: { name: ISO } } = await prepare_alpine("x86_64-virt");
const KERNEL = "boot/vmlinuz-virt";
const INITRD = "boot/initramfs-virt";

/** What the entropy device hands out, from the start of each buffer */
const rng_byte = i => i * 37 + 11 & 0xFF;
let rng;

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    machine_type: "q35",
    cpu_type: "x86_64",
    memory_size: 512 * 1024 * 1024,
    bzimage: { url: DIRECTORY + KERNEL },
    initrd: { url: DIRECTORY + INITRD },
    cdrom: { url: DIRECTORY + ISO },
    cmdline: "console=ttyS0,115200 loglevel=7 nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage",
    pcie_root_ports: 3,
    net_device: { type: "virtio", pcie_root_port: 0 },
    virtio_devices: [
        {
            "name": "signal-distribution",
            "device_id": 0x1040 + 21,
            "subsystem_device_id": 21,
            "queues": [{ "size": 8 }],
            "pcie_root_port": 1,
            "notify": () => {},
        },
        {
            "name": "rng",
            "device_id": 0x1040 + 4,
            "subsystem_device_id": 4,
            "queues": [{ "size": 8 }],
            "pcie_root_port": 2,
            "pcie_plugged": false,
            "init": handle => { rng = handle; },
            "notify": queue => {
                for(let request; (request = rng["pop_request"](queue)); )
                {
                    const bytes = new Uint8Array(request["writable"]);
                    for(let i = 0; i < bytes.length; i++) bytes[i] = rng_byte(i);
                    request["write"](bytes);
                    request["complete"]();
                }
                rng["flush"](queue);
            },
        },
    ],
    autostart: true,
    screen_dummy: true,
    log_level: 0,
    disable_jit: !!DISABLE_JIT,
    experimental_smp_jit: !DISABLE_JIT,
    ir_sync_publication: true,
});

let serial = "";
emulator.add_listener("serial0-output-byte", byte => {
    const c = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(c);
    serial += c;
});
let frames_sent = 0;
emulator.bus.register("net0-send", () => { frames_sent++; });

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

async function wait_for(what, predicate, timeout_ms)
{
    const start = Date.now();
    while(!predicate())
    {
        if(Date.now() - start > timeout_ms) throw new Error("timed out waiting for " + what + "\n" + serial.slice(-2000));
        await sleep(100);
    }
}

let commands = 0;

/**
 * Run a shell command, return its output: what comes between two markers,
 * each echoed as two quoted halves, so that the command line the shell
 * echoes (wrapped at 80 columns) has neither
 */
async function command(cmd, timeout_ms = 60000)
{
    const n = ++commands;
    serial = "";
    emulator.serial0_send("echo \"BEGIN\"\"_" + n + "\"; " + cmd + "; echo \"END\"\"_" + n + "\"\n");
    const output = new RegExp("BEGIN_" + n + "\\r?\\n([^]*?)END_" + n + "\\r?\\n");
    await wait_for(JSON.stringify(cmd), () => output.test(serial), timeout_ms);
    return output.exec(serial)[1];
}

/** Run a command until its output satisfies predicate */
async function wait_for_command(cmd, predicate, what, timeout_ms = 30000)
{
    const start = Date.now();
    for(;;)
    {
        const output = await command(cmd);
        if(predicate(output)) return output;
        if(Date.now() - start > timeout_ms) throw new Error("timed out waiting for " + what + ": " + output);
        await sleep(500);
    }
}

const slot_power = async slot => (await command("cat /sys/bus/pci/slots/" + slot + "/power")).trim();
const pci_function = async bus => (await command("cat /sys/bus/pci/devices/0000:0" + bus + ":00.0/device 2>/dev/null || echo none")).trim();

const start = Date.now();
await wait_for("the login prompt", () => /localhost login:/.test(serial), DISABLE_JIT ? 1800000 : 600000);
emulator.serial0_send("root\n");
await wait_for("the shell", () => /localhost:~# /.test(serial), 60000);
console.log("Booted in " + Math.round((Date.now() - start) / 1000) + " s");

// The slots: Linux has them through _OSC
const dmesg = await command("dmesg | grep -e _OSC -e pciehp");
assert.match(dmesg, /_OSC: OS now controls \[PCIeHotplug PME PCIeCapability\]/, "_OSC grants native hot plug");
for(const slot of [1, 2, 3])
{
    assert.match(dmesg, new RegExp("pciehp: Slot #" + slot + " AttnBtn\\+ PwrCtrl\\+ MRL- AttnInd\\+ PwrInd\\+ HotPlug\\+ Surprise\\+ .*LLActRep\\+"),
        "pciehp drives slot " + slot);
}
assert.equal(await slot_power(1), "1", "slot 1 (the NIC) is on");
assert.equal(await slot_power(2), "1", "slot 2 (the driverless function) is on");
assert.equal(await slot_power(3), "0", "the empty slot 3 is off");
assert.equal(await pci_function(1), "0x1041", "the NIC behind port 0");
assert.equal(await pci_function(3), "none", "slot 3 empty");
console.log("_OSC, three hot plug slots, the empty one off: ok");

// The entropy device: hot added, read, taken out by the attention button
assert.equal(await emulator.attach_pcie_device(2), undefined);
await wait_for_command("cat /sys/class/misc/hw_random/rng_available", output => /virtio_rng/.test(output), "virtio_rng");
const random = (await command("head -c 16 /dev/hwrng | od -An -tx1")).trim().split(/\s+/).map(x => parseInt(x, 16));
assert.equal(random.length, 16);
// (each buffer starts the sequence afresh)
assert.ok(random.every((x, i) => i === 0 || x === (random[i - 1] + 37 & 0xFF) || x === rng_byte(0)),
    "/dev/hwrng reads the device: " + random.map(x => x.toString(16)).join(" "));
assert.equal(await slot_power(3), "1", "Linux switched slot 3 on");
console.log("Entropy device hot added, /dev/hwrng: ok");

let removal_start = Date.now();
await emulator.detach_pcie_device(2);
const rng_removal = Date.now() - removal_start;
assert.equal(await pci_function(3), "none", "the entropy device is gone");
assert.equal(await slot_power(3), "0", "Linux switched slot 3 off");
assert.match(await command("dmesg | grep 'Slot(3)'"), /Slot\(3\): Button press: will power off in 5 sec/);
console.log("Entropy device taken out by the attention button after " + (rng_removal / 1000).toFixed(1) + " s: ok");

// The NIC: out by the attention button, in again
await command("ip link set eth0 up");
await wait_for("eth0 sending", () => frames_sent > 0, 30000);
removal_start = Date.now();
await emulator.detach_pcie_device(0);
const nic_removal = Date.now() - removal_start;
assert.match(await command("ip link show eth0 2>&1"), /can't find device|does not exist/, "eth0 is gone");
assert.equal(await slot_power(1), "0", "Linux switched slot 1 off");
assert.equal(await pci_function(1), "none", "the NIC is gone");

await emulator.attach_pcie_device(0);
await wait_for_command("ls /sys/class/net", output => /eth0/.test(output), "eth0 back");
assert.equal(await pci_function(1), "0x1041", "the NIC is back");
assert.equal(await slot_power(1), "1", "Linux switched slot 1 on");
const sent_before = frames_sent;
await command("ip link set eth0 up");
await wait_for("eth0 sending again", () => frames_sent > sent_before, 30000);
console.log("NIC taken out by the attention button after " + (nic_removal / 1000).toFixed(1) + " s, plugged in again, eth0 sends: ok");

// The driverless function: pulled out without notice, plugged in again
await emulator.detach_pcie_device(1, { surprise: true });
await wait_for_command("dmesg | grep 'Slot(2)'", output => /Slot\(2\): Card not present/.test(output), "Linux noticing");
assert.match(await command("dmesg | grep 'Slot(2)'"), /Slot\(2\): Link Down/);
await wait_for_command("cat /sys/bus/pci/slots/2/power", output => output.trim() === "0", "Linux switching slot 2 off");
assert.equal(await pci_function(2), "none", "the driverless function is gone");

await emulator.attach_pcie_device(1);
await wait_for_command("cat /sys/bus/pci/devices/0000:02:00.0/device 2>/dev/null", output => output.trim() === "0x1055", "the function back");
assert.equal(await slot_power(2), "1", "Linux switched slot 2 on");
console.log("Driverless function pulled out without notice, plugged in again: ok");

// Nothing of Linux's waits on a card that is gone
assert.equal((await command("for p in /proc/[0-9]*; do [ \"$(cut -d' ' -f3 $p/stat)\" = D ] && cat $p/comm; done")).trim(), "",
    "no task in uninterruptible sleep");

emulator.destroy();
console.log("PCI Express hot plug with Linux: ok");
                                                                                                                                                                                                                                                                                     source/v64/tests/devices/pcie_root_port.js                                                          0000755 0000000 0000000 00000066300 00000000000 016045  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The PCI Express root ports of the Q35 machine (pcie_root_ports) and the
// devices behind them, driven through configuration space and the devices'
// registers; no guest code runs (docs/q35.md): the type 1
// header and the capabilities, configuration routing by the bus numbers the
// guest programs, memory and I/O forwarding through the windows, bus
// mastering (DMA, MSI) through the bridge, INTx through the swizzle and
// snapshots; PCI Express native hot plug: the slot registers, the hot plug
// interrupt (INTx, MSI), surprise removal, insertion (into a powered slot
// and into one the guest switched off), removal through the attention
// button, the guest switching the slot off and on, snapshots; built-in
// devices behind root ports. With a guest: tests/devices/pcie_hotplug.mjs.
// Behind root port 0: a second AHCI controller (ahci_test_drives) with a
// disk; behind root port 2: a virtio device (virtio_devices, pcie_root_port).

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { SyncBuffer } = await import("../../src/buffer.js");

const disk = new Uint8Array(1 << 20).map((_, i) => i * 13 + (i >> 9) & 0xFF);

const rng = {
    "name": "rng",
    "device_id": 0x1044,
    "subsystem_device_id": 4,
    "queues": [{ "size": 8 }],
    "pcie_root_port": 2,
    "notify": () => {},
};

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    pcie_root_ports: 3,
    memory_size: 64 * 1024 * 1024,
    ahci_test_drives: [{ buffer: new SyncBuffer(disk.buffer) }],
    ahci_test_pci_id: 1 << 8,
    virtio_devices: [rng],
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const RP = n => 0x1C << 3 | n;         // root port n on bus 0
const read = (bdf, offset, size = 4) => pci.config_read(bdf, offset, size) >>> 0;
const write = (bdf, offset, value, size = 4) => pci.config_write(bdf, offset, size, value);
const ECAM = 0xB0000000;
const ecam_read = (bdf, offset) => cpu.mmap_read32(ECAM + bdf * 4096 + offset) >>> 0;
// the MCH's PCIEXBAR, as SeaBIOS programs it: 256 MiB at ECAM, enabled
write(0, 0x64, 0);
write(0, 0x60, ECAM | 1);
/** secondary and subordinate bus numbers of a root port */
const buses = (n, secondary, subordinate = secondary) => write(RP(n), 0x18, secondary << 8 | subordinate << 16);
const capability = (bdf, id) => {
    for(let at = read(bdf, 0x34, 1); at; at = read(bdf, at + 1, 1))
    {
        if(read(bdf, at, 1) === id) return at;
    }
    return 0;
};

test("root ports: identity, type 1 header, capability chain", () => {
    for(let n = 0; n < 3; n++)
    {
        assert.equal(read(RP(n), 0x00), 0x8086 | 0x2940 + 2 * n << 16, "ICH9 PCI Express Port " + (n + 1));
        assert.equal(read(RP(n), 0x08) >>> 8, 0x060400, "PCI-to-PCI bridge");
        assert.equal(read(RP(n), 0x0E, 1), n === 0 ? 0x81 : 0x01, "type 1 header; function 0 multi-function");
        assert.equal(read(RP(n), 0x3D, 1), n + 1, "INTA, INTB, INTC");
    }
    assert.equal(read(RP(3), 0x00), 0xFFFFFFFF, "three ports only");
    const chain = [];
    for(let at = read(RP(0), 0x34, 1); at; at = read(RP(0), at + 1, 1)) chain.push([at, read(RP(0), at, 1)]);
    assert.deepEqual(chain, [[0x40, 0x10], [0x80, 0x05], [0x90, 0x0D], [0xA0, 0x01]], "PCI Express, MSI, SSVID, PM");
    assert.equal(read(RP(0), 0x42, 2), 0x0141, "PCI Express 1, root port, slot implemented");
    assert.equal(read(RP(1), 0x4C) >>> 24, 2, "link capabilities: port number");
    assert.equal(read(RP(0), 0x4C) & 0x3FF, 0x11, "2.5 GT/s, x1");
    assert.equal(read(RP(0), 0x5A, 2) & 0x40, 0x40, "port 0: presence detected (the AHCI controller)");
    assert.equal(read(RP(0), 0x52, 2) & 0x2000, 0x2000, "port 0: link active");
    assert.equal(read(RP(1), 0x5A, 2) & 0x40, 0, "port 1: empty");
    assert.equal(read(RP(1), 0x52, 2) & 0x2000, 0);
    assert.equal(read(RP(2), 0x5A, 2) & 0x40, 0x40, "port 2: the virtio device");
    assert.equal(ecam_read(RP(0), 0x100), 0, "extended space: no extended capabilities");
    assert.equal(ecam_read(RP(0), 0x00), read(RP(0), 0x00), "the same through ECAM");
});

test("type 1 header writes: bus numbers, windows (read-only bits), secondary status, bridge control", () => {
    write(RP(1), 0x18, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x18), 0xFFFFFFFF, "primary, secondary, subordinate, latency timer");
    write(RP(1), 0x18, 0);
    write(RP(1), 0x1C, 0xFFFF);
    assert.equal(read(RP(1), 0x1C, 2), 0xF0F0, "I/O base/limit: 16-bit decode");
    write(RP(1), 0x20, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x20), 0xFFF0FFF0);
    write(RP(1), 0x24, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x24), 0xFFF1FFF1, "prefetchable: 64-bit");
    write(RP(1), 0x28, 0x12345678);
    assert.equal(read(RP(1), 0x28), 0x12345678, "prefetchable base, upper 32 bits");
    write(RP(1), 0x30, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x30), 0, "I/O upper 16 bits: read-only (16-bit)");
    write(RP(1), 0x38, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x38), 0, "no expansion ROM");
    write(RP(1), 0x10, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x10), 0, "no BARs");
    write(RP(1), 0x3C, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x3C), 0x005F02FF, "interrupt line, pin (read-only), bridge control");
    write(RP(1), 0x3C, 0);
    for(const offset of [0x1C, 0x20, 0x24, 0x28, 0x2C]) write(RP(1), offset, 0);
    // capabilities: read-only parts stay
    write(RP(1), 0x40, 0xFFFFFFFF);
    assert.equal(read(RP(1), 0x40), 0x01418010);
    write(RP(1), 0x4C, 0);
    assert.equal(read(RP(1), 0x4C) >>> 24, 2);
    write(RP(1), 0xA4, 0xFFFF);
    assert.equal(read(RP(1), 0xA4, 2), 0x0103, "PMCSR: power state, PME enable");
    write(RP(1), 0xA4, 0);
    write(RP(1), 0x200, 0xFFFFFFFF);
    assert.equal(ecam_read(RP(1), 0x200), 0, "the extended space stays zero");
});

test("configuration routing by the bus numbers the guest programs", () => {
    assert.equal(read(1 << 8, 0), 0xFFFFFFFF, "nothing on bus 1 before the bridge has the number");
    buses(0, 1);
    assert.equal(read(1 << 8, 0), 0x29228086, "bus 1, device 0: the AHCI controller behind root port 0");
    assert.equal(read(1 << 8 | 1 << 3, 0), 0xFFFFFFFF, "device 1: nothing behind a PCI Express downstream port");
    assert.equal(ecam_read(1 << 8, 0), 0x29228086, "the same through ECAM");
    buses(0, 5);
    assert.equal(read(1 << 8, 0), 0xFFFFFFFF, "renumbered: bus 1 is gone");
    assert.equal(read(5 << 8, 0), 0x29228086, "bus 5");
    buses(0, 1, 4);
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "buses 2-4: behind the port, but no bridge there");
    buses(2, 2);
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "overlapping ranges: bus 2 goes to port 0 (the first), where nothing has it");
    buses(0, 1);
    assert.equal(read(2 << 8, 0), 0x10441AF4, "bus 2, device 0: the virtio device behind root port 2");
    write(1 << 8, 0x3C, 0x0B, 1);
    assert.equal(read(1 << 8, 0x3C, 1), 0x0B, "writes reach the function behind the bridge");
});

/** AHCI behind root port 0 at bus 1: ABAR, command */
const ABAR = 0xC0100000;
function program_ahci(command = 0x0006)
{
    write(1 << 8, 0x24, ABAR);
    write(1 << 8, 0x04, command, 2);
}
const abar_read = offset => cpu.mmap_read32(ABAR + offset) >>> 0;

test("memory forwarding: ABAR behind the root port only through its windows while it decodes memory", () => {
    buses(0, 1);
    program_ahci();
    assert.equal(abar_read(0x0C), 0xFFFFFFFF, "the root port forwards nothing yet");
    write(RP(0), 0x20, 0xC010 | 0xC010 << 16);      // memory window C0100000-C01FFFFF
    assert.equal(abar_read(0x0C), 0xFFFFFFFF, "the window, but memory decode is off in the root port");
    write(RP(0), 0x04, 0x0002, 2);
    assert.equal(abar_read(0x0C), 0x3F, "decoded: ports implemented");
    write(RP(0), 0x20, 0xC020 | 0xC020 << 16);
    assert.equal(abar_read(0x0C), 0xFFFFFFFF, "outside the memory window");
    write(RP(0), 0x24, 0xC001 | 0xC011 << 16);      // prefetchable C0000000-C01FFFFF
    assert.equal(abar_read(0x0C), 0x3F, "inside the prefetchable window");
    write(RP(0), 0x24, 0xFFF1 | 0x0001 << 16);      // prefetchable window closed
    assert.equal(abar_read(0x0C), 0xFFFFFFFF);
    write(RP(0), 0x20, 0xC010 | 0xC010 << 16);
    assert.equal(abar_read(0x0C), 0x3F);
    write(1 << 8, 0x04, 0x0004, 2);
    assert.equal(abar_read(0x0C), 0xFFFFFFFF, "the function's own memory decode still counts");
    program_ahci();
});

test("bus mastering through the root port: commands wait for the bridge's too; MSI as well", () => {
    const P = 0x100, CLB = 0x200000, FB = 0x200400, TABLE = 0x201000, DATA = 0x300000;
    const w = (offset, value) => cpu.mmap_write32(ABAR + offset, value | 0);
    const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
    w(P + 0x18, 0);
    w(P + 0x00, CLB);
    w(P + 0x08, FB);
    w(P + 0x18, 0x10);
    w(P + 0x18, 0x11);
    mem.fill(0, TABLE, TABLE + 0x100);
    mem.set([0x27, 0x80, 0x25, 0, 3, 0, 0, 0x40, 0, 0, 0, 0, 1, 0], TABLE);   // READ DMA EXT, LBA 3
    put32(TABLE + 0x80, DATA);
    put32(TABLE + 0x8C, 511);
    put32(CLB, 5 | 1 << 16);
    put32(CLB + 8, TABLE);
    w(P + 0x38, 1);
    assert.equal(abar_read(P + 0x38), 1, "the root port's bus mastering is off: the command waits");
    write(RP(0), 0x04, 0x0006, 2);
    assert.equal(abar_read(P + 0x38), 0, "on: it runs");
    assert.deepEqual(mem.subarray(DATA, DATA + 512), disk.subarray(3 * 512, 4 * 512));
    assert.ok(pci.is_bus_master(1 << 8));
    write(RP(0), 0x04, 0x0002, 2);
    assert.ok(!pci.is_bus_master(1 << 8), "no MSI (a memory write) without the bridge's bus mastering");
    write(RP(0), 0x04, 0x0006, 2);
});

test("MSI behind a root port: the message reaches the local APIC only with the bridge's bus mastering", () => {
    const LAPIC = 0xFEE00000;
    const irr = vector => !!((cpu.read32s(LAPIC + 0x200 + (vector >> 5) * 16) >>> 0) & 1 << (vector & 31));
    const eoi = () => cpu.write32(LAPIC + 0xB0, 0);
    cpu.write32(LAPIC + 0xF0, 0x1FF);
    const AHCI = 1 << 8;
    write(AHCI, 0x84, 0xFEE00000);
    write(AHCI, 0x88, 0);
    write(AHCI, 0x8C, 0x0046, 2);
    write(AHCI, 0x82, 0x0001, 2);           // MSI enable
    write(RP(0), 0x04, 0x0002, 2);          // the root port: memory decode, no bus mastering
    cpu.mmap_write32(ABAR + 0x100 + 0x10, -1);
    cpu.mmap_write32(ABAR + 0x04, 2);
    cpu.mmap_write32(ABAR + 0x100 + 0x14, 1);
    const comreset = () => {
        cpu.mmap_write32(ABAR + 0x100 + 0x10, -1);
        cpu.mmap_write32(ABAR + 0x100 + 0x2C, 1);
        cpu.mmap_write32(ABAR + 0x100 + 0x2C, 0);
    };
    comreset();
    assert.ok(!irr(0x46), "no message while the root port does not master the bus");
    write(RP(0), 0x04, 0x0006, 2);
    comreset();
    assert.ok(irr(0x46), "delivered through the root port");
    eoi();
    cpu.mmap_write32(ABAR + 0x100 + 0x10, -1);
    write(AHCI, 0x82, 0, 2);
    cpu.mmap_write32(ABAR + 0x04, 0);
    cpu.mmap_write32(ABAR + 0x100 + 0x14, 0);
});

test("INTx behind a root port: the swizzle, then the root port's pin at device 28 (D28IR: PIRQA-D)", () => {
    const AHCI = 1 << 8;
    assert.deepEqual(pci.root_pin(AHCI), { pci_id: RP(0), pin: 0 }, "INTA of device 0 -> INTA of the bridge");
    const sources = gsi => cpu.shared_irq_sources[gsi];
    cpu.mmap_write32(ABAR + 0x04, 2);           // GHC.IE
    cpu.mmap_write32(ABAR + 0x100 + 0x14, 1);   // PxIE: DHRS
    cpu.mmap_write32(ABAR + 0x100 + 0x38, 0);
    // a D2H FIS interrupt: COMRESET
    cpu.mmap_write32(ABAR + 0x100 + 0x2C, 1);
    cpu.mmap_write32(ABAR + 0x100 + 0x2C, 0);
    assert.ok(sources(16).has(AHCI), "PIRQA: GSI 16");
    cpu.mmap_write32(ABAR + 0x100 + 0x10, -1);
    assert.ok(!sources(16).has(AHCI));
    // as if it had INTB: the bridge's INTB, PIRQB, GSI 17
    pci.space_bytes(AHCI)[0x3D] = 2;
    cpu.mmap_write32(ABAR + 0x100 + 0x2C, 1);
    cpu.mmap_write32(ABAR + 0x100 + 0x2C, 0);
    assert.ok(sources(17).has(AHCI), "INTB: GSI 17");
    cpu.mmap_write32(ABAR + 0x100 + 0x10, -1);
    pci.space_bytes(AHCI)[0x3D] = 1;
    cpu.mmap_write32(ABAR + 0x04, 0);
    cpu.mmap_write32(ABAR + 0x100 + 0x14, 0);
});

/** The virtio device behind root port 2 at bus 2: its I/O BARs */
function io_bars()
{
    const bars = [];
    for(let bar = 0; bar < 6; bar++)
    {
        const offset = 0x10 + 4 * bar;
        const old = read(2 << 8, offset);
        write(2 << 8, offset, 0xFFFFFFFF);
        const probe = read(2 << 8, offset);
        write(2 << 8, offset, old);
        if(probe && probe & 1) bars.push({ offset, size: (~(probe & ~3) >>> 0 & 0xFFFF) + 1 });
    }
    return bars;
}

test("I/O forwarding: the I/O BARs of a function behind a root port appear only through the I/O window", () => {
    buses(0, 1);
    buses(2, 2);
    const bars = io_bars();
    assert.ok(bars.length > 0, "virtio has I/O BARs");
    const virtio = cpu.devices.virtio_devices[0].virtio;
    let port = 0xC000;
    for(const bar of bars)
    {
        write(2 << 8, bar.offset, port | 1);
        bar.port = port;
        port += Math.max(bar.size, 0x100);
    }
    const mapped = () => bars.map(bar => cpu.io.ports[bar.port].device === virtio);
    assert.deepEqual(mapped(), bars.map(() => false), "the root port forwards no I/O yet");
    write(RP(2), 0x1C, 0xC0 | 0xC0 << 8, 2);       // I/O window C000-CFFF
    assert.deepEqual(mapped(), bars.map(() => false), "the window, but I/O decode is off in the root port");
    write(RP(2), 0x04, 0x0001, 2);
    assert.deepEqual(mapped(), bars.map(() => true), "forwarded");
    write(RP(2), 0x1C, 0xD0 | 0xD0 << 8, 2);
    assert.deepEqual(mapped(), bars.map(() => false), "outside the I/O window");
    write(RP(2), 0x1C, 0xC0 | 0xC0 << 8, 2);
    assert.deepEqual(mapped(), bars.map(() => true));
    write(2 << 8, bars[0].offset, 0xD000 | 1);
    assert.equal(cpu.io.ports[bars[0].port].device, undefined, "moved away: the old ports are free");
    assert.equal(cpu.io.ports[0xD000].device, undefined, "and the new ones outside the window are not decoded");
    write(2 << 8, bars[0].offset, bars[0].port | 1);
    assert.deepEqual(mapped(), bars.map(() => true));
});

const state = await emulator.save_state();
write(RP(0), 0x18, 0);
write(RP(2), 0x04, 0, 2);
await emulator.restore_state(state);
test("snapshot: bus numbers, windows, decode and the I/O BARs behind the root ports survive", () => {
    assert.equal(read(1 << 8, 0), 0x29228086);
    assert.equal(abar_read(0x0C), 0x3F);
    const virtio = cpu.devices.virtio_devices[0].virtio;
    assert.equal(cpu.io.ports[0xC000].device, virtio);
});

// PCI Express native hot plug; root port 2's card is the virtio device
const LNKSTA = 0x52, SLTCAP = 0x54, SLTCTL = 0x58, SLTSTA = 0x5A;
const ABP = 1, PDC = 8, CC = 0x10, PDS = 0x40, DLLSC = 0x100;
const ABPE = 1, PDCE = 8, CCIE = 0x10, HPIE = 0x20, INDICATORS_OFF = 0x3C0, PCC = 0x400, DLLSCE = 0x1000;
const POWER_INDICATOR_ON = 0x1C0;               // (the attention indicator off)
const slot_status = n => read(RP(n), SLTSTA, 2);
const link_up = n => (read(RP(n), LNKSTA, 2) & 0x2000) !== 0;
const clear_events = n => write(RP(n), SLTSTA, 0x11F, 2);
// the root port's own pin: INTA-INTC, through D28IR to PIRQA-C, GSI 16-18
const intx = n => !!cpu.shared_irq_sources[16 + n] && cpu.shared_irq_sources[16 + n].has(RP(n));

test("hot plug slots: attention button, power controller, indicators, surprise, hot plug capable, slot numbers", () => {
    for(let n = 0; n < 3; n++)
    {
        assert.equal(read(RP(n), SLTCAP), (0x7B | n + 1 << 19) >>> 0, "port " + n);
    }
    assert.equal(read(RP(0), SLTCTL, 2), POWER_INDICATOR_ON, "a slot with a card: on, its power indicator on (as QEMU)");
    assert.equal(read(RP(2), SLTCTL, 2), POWER_INDICATOR_ON);
    assert.equal(read(RP(1), SLTCTL, 2), INDICATORS_OFF | PCC, "the empty slot: off, indicators off");
    write(RP(1), SLTCTL, 0xFFFF, 2);
    assert.equal(read(RP(1), SLTCTL, 2), 0x17FF, "no electromechanical interlock");
    assert.equal(slot_status(1), CC, "a write of slot control is a command, completed at once");
    write(RP(1), SLTSTA, 0x0100, 2);
    assert.equal(slot_status(1), CC, "write one to clear: only those");
    clear_events(1);
    assert.equal(slot_status(1), 0);
    write(RP(1), SLTCTL, INDICATORS_OFF, 2);
    clear_events(1);
});

test("the hot plug interrupt: INTx while an enabled event is pending, an MSI when one starts", () => {
    write(RP(1), SLTCTL, INDICATORS_OFF | CCIE, 2);
    assert.ok(!intx(1), "not without HPIE");
    clear_events(1);
    write(RP(1), SLTCTL, INDICATORS_OFF | HPIE | CCIE, 2);
    assert.ok(intx(1), "command completed, enabled: INTB, PIRQB");
    clear_events(1);
    assert.ok(!intx(1), "cleared");
    const msis = [];
    const apic_msi = cpu.apic_msi;
    cpu.apic_msi = (address, data) => { msis.push([address >>> 0, data]); return true; };
    write(RP(1), 0x84, 0xFEE00000);
    write(RP(1), 0x88, 0);
    write(RP(1), 0x8C, 0x0055, 2);
    write(RP(1), 0x82, 0x0001, 2);
    write(RP(1), 0x04, 0x0004, 2);              // (a message is a memory write: bus mastering)
    write(RP(1), SLTCTL, INDICATORS_OFF | HPIE | CCIE, 2);
    assert.deepEqual(msis, [[0xFEE00000, 0x55]], "a message");
    assert.ok(!intx(1), "no INTx with MSI");
    write(RP(1), SLTCTL, INDICATORS_OFF | HPIE | CCIE, 2);
    assert.equal(msis.length, 1, "the event still pending: no new message");
    clear_events(1);
    write(RP(1), SLTCTL, INDICATORS_OFF | HPIE | CCIE, 2);
    assert.equal(msis.length, 2, "cleared, then a new event: a new message");
    cpu.apic_msi = apic_msi;
    write(RP(1), 0x82, 0, 2);
    write(RP(1), 0x04, 0, 2);
    write(RP(1), SLTCTL, INDICATORS_OFF, 2);
    clear_events(1);
});

const virtio_port = () => cpu.io.ports[0xC000].device === cpu.devices.virtio_devices[0].virtio;
write(RP(2), SLTCTL, INDICATORS_OFF | HPIE | PDCE | ABPE | DLLSCE, 2);
clear_events(2);
const power_on_command = read(2 << 8, 0x04, 2);
test("a card in the slot: present, link up", () => {
    assert.equal(slot_status(2), PDS);
    assert.ok(link_up(2));
    assert.ok(virtio_port(), "its I/O BAR where the guest put it");
    write(2 << 8, 0x04, 0x0001, 2);
    assert.equal(read(2 << 8, 0x04, 2), 0x0001);
});
await emulator.detach_pcie_device(2, { surprise: true });
test("surprise removal: the card leaves the bus at once", () => {
    assert.equal(slot_status(2), PDC | DLLSC, "presence detect and link changed, nothing present");
    assert.ok(!link_up(2));
    assert.ok(intx(2), "enabled events: the hot plug interrupt (INTC, PIRQC)");
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "nothing answers configuration cycles");
    assert.ok(!virtio_port(), "its I/O BARs are gone");
});
clear_events(2);
await emulator.attach_pcie_device(2);
test("plugged in: presence and link up, the device starts afresh", () => {
    assert.equal(slot_status(2), PDS | PDC | DLLSC);
    assert.ok(link_up(2));
    assert.equal(read(2 << 8, 0), 0x10441AF4, "the virtio device again");
    assert.equal(read(2 << 8, 0x04, 2), power_on_command, "command as at power-on");
    assert.ok(!virtio_port(), "its BARs as at power-on (outside the root port's window)");
});
clear_events(2);
let removed = false;
const removal = emulator.detach_pcie_device(2).then(() => { removed = true; });
await new Promise(resolve => setTimeout(resolve, 0));
const POWER_INDICATOR_BLINK = 0x2C0;            // (the attention indicator off)
test("removal through the attention button: the guest is asked, the card stays meanwhile", () => {
    assert.equal(slot_status(2), PDS | ABP, "attention button pressed");
    assert.ok(!removed);
    assert.equal(read(2 << 8, 0), 0x10441AF4, "still on the bus");
    clear_events(2);
    write(RP(2), SLTCTL, POWER_INDICATOR_BLINK | HPIE | PDCE | ABPE | DLLSCE | PCC, 2);
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "the guest switched the slot off: off the bus");
    assert.equal(slot_status(2) & (PDS | PDC | DLLSC), PDS | DLLSC, "the link down; the power indicator blinks: the card stays");
    assert.ok(!link_up(2));
    write(RP(2), SLTCTL, INDICATORS_OFF | HPIE | PDCE | ABPE | DLLSCE | PCC, 2);
    assert.equal(slot_status(2) & (PDS | PDC), PDC, "the power indicator off too: out of the slot");
});
await removal;
test("removal through the attention button: done once the guest switched the slot and its power indicator off", () => {
    assert.ok(removed);
});
clear_events(2);
await emulator.attach_pcie_device(2);
test("plugged into a slot the guest switched off: presence and the attention button, off the bus until switched on", () => {
    assert.equal(slot_status(2), PDS | PDC | ABP, "presence detect changed, attention button pressed (Linux enables only ABPE then)");
    assert.ok(!link_up(2));
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "nothing answers yet");
    clear_events(2);
    write(RP(2), SLTCTL, INDICATORS_OFF | HPIE | PDCE | ABPE | DLLSCE, 2);
    assert.equal(slot_status(2), PDS | CC | DLLSC, "switched on: the link comes up");
    assert.ok(link_up(2));
    assert.equal(read(2 << 8, 0), 0x10441AF4, "the virtio device");
    assert.equal(read(2 << 8, 0x04, 2), power_on_command, "afresh");
});
write(RP(2), SLTCTL, INDICATORS_OFF | HPIE | PDCE | ABPE | DLLSCE, 2);
clear_events(2);
await emulator.attach_pcie_device(2);
clear_events(2);
test("the guest switches the slot off and on: the card stays in, off the bus meanwhile", () => {
    write(RP(2), SLTCTL, INDICATORS_OFF | PCC, 2);
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF, "off");
    assert.equal(slot_status(2) & (PDS | PDC | DLLSC), PDS | DLLSC, "present, the link down");
    assert.ok(!link_up(2));
    write(RP(2), SLTCTL, INDICATORS_OFF, 2);
    assert.equal(read(2 << 8, 0), 0x10441AF4, "on again");
    assert.ok(link_up(2));
    clear_events(2);
});
await emulator.detach_pcie_device(2, { surprise: true });
const hot_plug_state = await emulator.save_state();
await emulator.attach_pcie_device(2);
await emulator.restore_state(hot_plug_state);
test("snapshot: the slot empty as saved, the card off the bus", () => {
    assert.equal(slot_status(2) & PDS, 0);
    assert.ok(!link_up(2));
    assert.equal(read(2 << 8, 0), 0xFFFFFFFF);
});
await emulator.attach_pcie_device(2);
test("snapshot: and plugged in again", () => {
    assert.equal(read(2 << 8, 0), 0x10441AF4);
});
const attach_error = await emulator.attach_pcie_device(1).then(() => null, e => e);
await emulator.detach_pcie_device(1);
test("attach_pcie_device needs a device for the port; detaching from an empty slot does nothing", () => {
    assert.match(String(attach_error), /no device for root port 1/);
    assert.equal(slot_status(1) & (PDS | PDC), 0);
});
write(RP(2), SLTCTL, INDICATORS_OFF | PCC, 2);
write(RP(1), SLTCTL, INDICATORS_OFF, 2);
await emulator.restart();
test("reset: a slot with a card on (the card afresh), an empty one off", () => {
    assert.equal(read(RP(2), SLTCTL, 2), POWER_INDICATOR_ON);
    assert.equal(slot_status(2), PDS, "no events");
    buses(2, 2);
    assert.equal(read(2 << 8, 0), 0x10441AF4, "the card the guest had switched off is back on the bus");
    assert.equal(read(RP(1), SLTCTL, 2), INDICATORS_OFF | PCC, "the empty slot the guest had switched on is off");
});
emulator.destroy();

// Built-in devices behind root ports: virtio-net, 9p, the console (starting
// unplugged) and the balloon; then the NE2000
const builtin = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    pcie_root_ports: 4,
    memory_size: 64 * 1024 * 1024,
    net_device: { type: "virtio", pcie_root_port: 0 },
    filesystem: { pcie_root_port: 1 },
    virtio_console: { pcie_root_port: 2, pcie_plugged: false },
    virtio_balloon: { pcie_root_port: 3 },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => builtin.add_listener("emulator-loaded", resolve));
const bpci = builtin.v86.cpu.devices.pci;
const bread = (bdf, offset, size = 4) => bpci.config_read(bdf, offset, size) >>> 0;
for(let n = 0; n < 4; n++) bpci.config_write(RP(n), 0x18, 4, n + 1 << 8 | n + 1 << 16);
test("built-in devices behind root ports: virtio-net, 9p, the console not plugged in, the balloon", () => {
    assert.equal(bread(1 << 8, 0), 0x10411AF4, "virtio-net behind port 0");
    assert.equal(bread(2 << 8, 0), 0x10491AF4, "9p behind port 1");
    assert.equal(bread(3 << 8, 0), 0xFFFFFFFF, "port 2: the console is not plugged in");
    assert.equal(bread(RP(2), SLTSTA, 2) & PDS, 0);
    assert.equal(bread(4 << 8, 0), 0x10451AF4, "the balloon behind port 3");
    for(const slot of [0x0A, 0x06, 0x0C, 0x0B]) assert.equal(bread(slot << 3, 0), 0xFFFFFFFF, "not in its usual slot on bus 0");
});
await builtin.attach_pcie_device(2);
test("built-in devices behind root ports: the console plugged in, on the bus once its slot is switched on", () => {
    assert.equal(bread(RP(2), SLTSTA, 2) & (PDS | PDC | ABP), PDS | PDC | ABP, "its empty slot was off");
    assert.equal(bread(3 << 8, 0), 0xFFFFFFFF);
    bpci.config_write(RP(2), SLTCTL, 2, INDICATORS_OFF);
    assert.equal(bread(3 << 8, 0), 0x10431AF4);
});
builtin.destroy();

const ne2k = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    pcie_root_ports: 2,
    memory_size: 64 * 1024 * 1024,
    net_device: { type: "ne2k", pcie_root_port: 1 },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => ne2k.add_listener("emulator-loaded", resolve));
const npci = ne2k.v86.cpu.devices.pci;
npci.config_write(RP(1), 0x18, 4, 2 << 8 | 2 << 16);
test("the NE2000 behind a root port: its I/O BAR starts above the legacy ports", () => {
    assert.equal(npci.config_read(2 << 8, 0, 4) >>> 0, 0x802910EC);
    assert.equal(npci.config_read(2 << 8, 0x10, 4) >>> 0, 0x1301);
    assert.equal(npci.config_read(0x02 << 3, 0, 4) >>> 0, 0xFFFFFFFF, "not at 00:02.0");
});
ne2k.destroy();

const { create_platform } = await import("../../src/platform.js");
test("placements behind root ports: on Q35, an existing port, one device per port", () => {
    const q35 = { machine_type: "q35", pcie_root_ports: 2 };
    assert.throws(() => create_platform({ root_port_devices: { net: { port: 0, plugged: true } } }, 32 << 20), /root ports need machine_type "q35"/);
    assert.throws(() => create_platform({ ...q35, root_port_devices: { net: { port: 2, plugged: true } } }, 32 << 20), /pcie_root_port must be/);
    assert.throws(() => create_platform({ ...q35, root_port_devices: { net: { port: 0, plugged: true }, virtio_9p: { port: 0, plugged: true } } }, 32 << 20), /taken/);
    assert.deepEqual(create_platform({ ...q35, root_port_devices: { net: { port: 1, plugged: false } } }, 32 << 20).root_port_devices, { net: 1 });
});

console.log((failed ? "FAIL" : "PASS") + ": " + passed + " PCI Express root port tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                source/v64/tests/devices/q35_guest.js                                                               0000755 0000000 0000000 00000103472 00000000000 014637  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The Q35 machine (machine_type: "q35") with real guests and the real
// firmware (docs/q35.md, docs/ahci.md, docs/sata.md). PARTS selects (comma separated):
//   linux: SeaBIOS boots linux4.iso (Linux 4.16, IOAPIC routing) from the
//     SATA CD drive through AHCI; the tables have MCFG and the ICH9 layout;
//     the guest uses ECAM, ahci/libata with MSI and 64-bit DMA, reads its root from sr0,
//     writes and verifies hda (an asynchronous disk whose requests complete
//     out of order: native command queuing with several commands in flight),
//     finds a disk hot plugged into port 3 and loses it when it is pulled
//     out, keeps the data across a reset through the FADT reset register and
//     across a snapshot, and powers off (S5)
//   dos: MS-DOS 6.22 from the SATA disk through SeaBIOS's int13h in real
//     mode (clean boot), and with EMM386 in virtual-8086 mode, where
//     SeaBIOS reaches its 32-bit AHCI driver through SMM (call32_smm)
//   intx: the same kernel booted directly with pci=nomsi: AHCI's INTA
//     reaches the IOAPIC through PIRQA as GSI 16; a second AHCI controller
//     behind PCI Express root port 1 too (the swizzle, then device 28's
//     route), and ahci reads the disk behind the bridge; with the HPET
//   pic: a direct kernel boot (Linux 6.8, PIC routing): ECAM, the PCI
//     Express root bridge and the PIRQ links; the root complex registers
//     and the SMBus controller from the guest (devmem, /dev/port)
//   pcie: the same kernel with three PCI Express root ports; behind port 0
//     a second AHCI controller (no driver in this kernel), behind port 2 a
//     virtio entropy device: the buses and windows the firmware set up,
//     /dev/hwrng reading the virtio device through the I/O window
//   hpet: the same kernel with hpet: true: Linux finds the HPET by the ACPI
//     table, takes IRQ 0 with the legacy replacement route, keeps time with
//     it as clock source
// Images: images/linux4.iso, images/msdos622.img, images/buildroot-bzimage68.bin

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import crypto from "node:crypto";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const PARTS = (process.env.PARTS || "linux,intx,dos,pic,pcie,hpet").split(",");
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { SyncBuffer } = await import("../../src/buffer.js");

const IMAGES = __dirname + "/../../images/";
const BIOS = { url: __dirname + "/../../bios/seabios.bin" };
const VGA_BIOS = { url: __dirname + "/../../bios/vgabios.bin" };

const log = message => console.log(message);

/**
 * A booted emulator with serial and screen helpers
 * @param {Object} options
 */
async function start(options)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: BIOS,
        vga_bios: VGA_BIOS,
        machine_type: "q35",
        memory_size: 256 * 1024 * 1024,
        autostart: true,
        screen_dummy: true,
        log_level: 0,
        ...options,
    });
    const machine = { emulator, serial: "" };
    emulator.add_listener("serial0-output-byte", byte => {
        const c = String.fromCharCode(byte);
        if(SHOW_LOGS) process.stdout.write(c);
        machine.serial += c;
    });
    return machine;
}

function screen(machine)
{
    // (the screen exists once the emulator has loaded)
    const adapter = machine.emulator.screen_adapter;
    return adapter ? adapter.get_text_screen().join("\n") : "";
}

function wait_for(what, predicate, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const start = Date.now();
        const check = () => {
            if(predicate()) return resolve();
            if(Date.now() - start > timeout_ms) return reject(new Error("timed out waiting for " + what));
            setTimeout(check, 50);
        };
        check();
    });
}

const PROMPT = /~% $/;

async function command(machine, cmd, timeout_ms = 120000)
{
    machine.serial = "";
    machine.emulator.serial0_send(cmd + "\n");
    await wait_for(JSON.stringify(cmd), () => PROMPT.test(machine.serial), timeout_ms);
    return machine.serial.slice(cmd.length).replace(PROMPT, "");
}

/** Run a command until its output satisfies predicate */
async function wait_for_command(machine, cmd, predicate, what, timeout_ms = 60000)
{
    const start = Date.now();
    for(;;)
    {
        const out = await command(machine, cmd);
        if(predicate(out)) return out;
        if(Date.now() - start > timeout_ms) throw new Error("timed out waiting for " + what + ": " + out);
        await new Promise(resolve => setTimeout(resolve, 500));
    }
}

function next_event(emulator, name, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + name)), timeout_ms);
        const listener = value => {
            clearTimeout(timer);
            emulator.remove_listener(name, listener);
            resolve(value);
        };
        emulator.add_listener(name, listener);
    });
}

/**
 * v86's tables as the guest sees them
 * @param {!Uint8Array} mem
 */
function check_tables(mem)
{
    const u16 = a => mem[a] | mem[a + 1] << 8;
    const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
    const u64 = a => u32(a) + u32(a + 4) * 2 ** 32;
    const signature = (a, n = 4) => String.fromCharCode(...mem.subarray(a, a + n));
    const checksum = (a, n) => mem.subarray(a, a + n).reduce((x, y) => x + y, 0) & 0xFF;

    let rsdp = -1;
    for(let a = 0xE0000; a < 0x100000; a += 16)
    {
        if(signature(a, 8) === "RSD PTR " && checksum(a, 20) === 0) { rsdp = a; break; }
    }
    assert.ok(rsdp >= 0, "RSDP");
    assert.equal(signature(rsdp + 9, 6), "V86   ", "v86's tables");
    const xsdt = u64(rsdp + 24);
    const tables = {};
    for(let p = xsdt + 36; p < xsdt + u32(xsdt + 4); p += 8)
    {
        const address = u64(p);
        assert.equal(checksum(address, u32(address + 4)), 0, signature(address) + " checksum");
        tables[signature(address)] = address;
    }
    assert.deepEqual(Object.keys(tables).sort(), ["APIC", "FACP", "MCFG"]);

    const mcfg = tables["MCFG"];
    assert.equal(u64(mcfg + 44), 0xB0000000, "MCFG: ECAM base");
    assert.deepEqual([u16(mcfg + 52), mem[mcfg + 54], mem[mcfg + 55]], [0, 0, 255], "segment 0, buses 0-255");

    const facp = tables["FACP"];
    const pm_base = u32(facp + 56);
    assert.equal(pm_base, 0x600, "the PM base SeaBIOS programs in PMBASE");
    assert.deepEqual([mem[facp + 52], mem[facp + 53]], [0x02, 0x03], "ICH9 ACPI_ENABLE/ACPI_DISABLE");
    assert.equal(u32(facp + 80), pm_base + 0x20, "GPE0_BLK inside the ICH9 PM block");
    assert.equal(mem[facp + 92], 16, "GPE0_BLK_LEN");

    const dsdt = u32(facp + 40);
    const text = Buffer.from(mem.subarray(dsdt, dsdt + u32(dsdt + 4)));
    assert.ok(text.includes("_S5_"), "S5 advertised");
    assert.ok(!text.includes("_S3_") && !text.includes("_S4_"), "S3 and S4 not advertised on Q35 yet");
    assert.ok(text.includes("PRTA") && text.includes("PRTP") && text.includes("PICF"), "APIC and PIC routing tables, _PIC");
    assert.ok(text.includes("DRAC"), "ECAM reserved by a motherboard resource");
}

/**
 * A disk image whose requests complete after a random 0-4 ms, so that
 * requests in flight together complete out of order. Writes reach the image
 * at once (only their completion is late), reads take the data when issued.
 * (a class: state images take no plain objects)
 */
class LatencyDisk
{
    /** @param {!Uint8Array} data */
    constructor(data)
    {
        this.data = data;
        this.byteLength = data.length;
        this.in_flight = 0;
        this.max_in_flight = 0;
    }
    load() { this.onload?.({}); }
    later(f)
    {
        this.max_in_flight = Math.max(this.max_in_flight, ++this.in_flight);
        setTimeout(() => { this.in_flight--; f(); }, Math.random() * 4);
    }
    get(start, length, done)
    {
        const data = this.data.slice(start, start + length);
        this.later(() => done(data));
    }
    set(start, data, done)
    {
        this.data.set(data, start);
        this.later(done);
    }
    // (the starter reads the MBR for the CHS geometry)
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache(start, length) { return this.data.slice(start, start + length); }
    get_buffer(done) { done(undefined); }
    get_state() { return []; }
    set_state() {}
}

async function part_linux()
{
    log("linux: booting linux4.iso from the SATA CD drive");
    const disk = new Uint8Array(64 * 1024 * 1024);
    const hda = new LatencyDisk(disk);
    const machine = await start({
        cdrom: { url: IMAGES + "linux4.iso" },
        hda,
    });
    const { emulator } = machine;
    try
    {
        await wait_for("the shell", () => PROMPT.test(machine.serial), 240000);
        const cpu = emulator.v86.cpu;
        check_tables(cpu.mem8);
        log("linux: tables: MCFG, FADT with the ICH9 PM layout, S5 only");

        const dmesg = await command(machine, "dmesg");
        for(const [pattern, what] of [
            [/PCI: Using MMCONFIG|PCI: MMCONFIG for domain 0000 \[bus 00-ff\] at \[mem 0xb0000000-0xbfffffff\]|ECAM \[mem 0xb0000000-0xbfffffff\]/, "ECAM"],
            [/ACPI: Using IOAPIC for interrupt routing/, "IOAPIC routing"],
            [/PNP0A08/, "PCI Express root bridge"],
            [/ahci 0000:00:1f\.2: AHCI 0001\.0000 32 slots 6 ports 1\.5 Gbps 0x3f impl SATA mode/, "AHCI controller"],
            [/ata1: SATA link up 1\.5 Gbps/, "hda's link"],
            [/ata1\.00: .*LBA48 NCQ \(depth (31\/)?32\)/, "hda with NCQ"],
            [/ata3\.00: ATAPI: /, "the CD drive"],
            [/Attached scsi CD-ROM sr0/, "sr0"],
            [/ata2: SATA link down/, "empty port"],
        ])
        {
            assert.ok(pattern.test(dmesg), what + " in dmesg");
        }
        assert.ok(!/exception Emask|hard resetting link|timeout|failed command/i.test(dmesg), "no libata errors");
        assert.ok(/ahci 0000:00:1f\.2: flags: 64bit/.test(dmesg), "64-bit addressing");
        const interrupts = await command(machine, "cat /proc/interrupts");
        assert.ok(/\d+:\s+\d+\s+PCI-MSI \d+-edge\s+ahci/.test(interrupts), "ahci uses MSI");
        log("linux: ECAM, IOAPIC routing, ahci with MSI and 64-bit DMA, hda and sr0 attached");

        // Write a pattern with the guest, compare it on both sides
        const md5 = await command(machine,
            "dd if=/dev/urandom of=/tmp/x bs=1k count=4096 2>/dev/null && dd if=/tmp/x of=/dev/sda bs=64k conv=fsync 2>/dev/null; " +
            "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda bs=64k count=64 2>/dev/null | md5sum; md5sum /tmp/x");
        const sums = md5.match(/[0-9a-f]{32}/g);
        assert.ok(sums && sums.length === 2 && sums[0] === sums[1], "read back what was written: " + md5);
        const host_sum = crypto.createHash("md5").update(disk.subarray(0, 4 << 20)).digest("hex");
        assert.equal(host_sum, sums[0], "the disk image holds the guest's data");
        // reads of four regions at once
        const parallel = await command(machine,
            "echo 3 > /proc/sys/vm/drop_caches; for i in 0 1 2 3; do dd if=/dev/sda bs=4k skip=$((i * 256)) count=256 2>/dev/null | md5sum & done; wait");
        const parallel_sums = parallel.match(/[0-9a-f]{32}/g);
        assert.deepEqual(parallel_sums && parallel_sums.sort(),
            [0, 1, 2, 3].map(i => crypto.createHash("md5").update(disk.subarray(i << 20, i + 1 << 20)).digest("hex")).sort(),
            "parallel reads: " + parallel);
        const ahci_port = emulator.v86.cpu.devices.ahci.ports[0];
        assert.ok(hda.max_in_flight > 1, "queued commands overlapped (" + hda.max_in_flight + " in flight at most)");
        assert.equal(ahci_port.ncq_error, null);
        log("linux: NCQ: up to " + hda.max_in_flight + " commands in flight, completing out of order");

        // An NCQ error: the disk image claims to end at 32 MiB for a moment,
        // a read at 48 MiB fails with IDNF. Linux's error handler restarts
        // the port, finds the failed tag in the NCQ error log (READ LOG EXT
        // 10h), fails that command and goes on with NCQ.
        await command(machine, "dmesg -c >/dev/null");
        hda.byteLength = 32 << 20;
        const failed = await command(machine, "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda of=/dev/null bs=4k skip=12288 count=16; echo status=$?");
        hda.byteLength = disk.length;
        assert.ok(/status=1/.test(failed), "the read failed: " + failed);
        const eh = await command(machine, "dmesg");
        for(const [pattern, what] of [
            [/ata1\.00: failed command: READ FPDMA QUEUED/, "the failed queued command"],
            [/ata1\.00: error: \{ IDNF \}/, "its error, from the NCQ error log"],
            [/ata1: EH complete/, "recovery"],
        ])
        {
            assert.ok(pattern.test(eh), what + " in dmesg: " + eh);
        }
        assert.ok(!/log page 10h|hard resetting link|limiting SATA|NCQ disabled|timeout/i.test(eh), "no reset, NCQ kept: " + eh);
        const recovered = await command(machine, "dd if=/dev/sda bs=4k skip=12288 count=16 2>/dev/null | md5sum");
        assert.ok(recovered.includes(crypto.createHash("md5").update(disk.subarray(48 << 20, (48 << 20) + 65536)).digest("hex")), "reads work again: " + recovered);
        log("linux: NCQ error: IDNF reported through the NCQ error log, no link reset, reads work again");

        // link power management: with the min_power policy Linux sets ALPE
        // and ASP, the idle link sleeps (slumber), commands wake it
        const port0 = emulator.v86.cpu.devices.ahci.ports[0];
        const policy = "/sys/class/scsi_host/host0/link_power_management_policy";
        await command(machine, "dmesg -c >/dev/null");
        assert.ok((await command(machine, "echo min_power > " + policy + "; cat " + policy)).includes("min_power"));
        const lpm_read = await command(machine, "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda bs=64k count=64 2>/dev/null | md5sum");
        assert.ok(lpm_read.includes(crypto.createHash("md5").update(disk.subarray(0, 4 << 20)).digest("hex")), "reads with LPM: " + lpm_read);
        assert.equal(port0.cmd >> 26 & 3, 3, "ALPE and ASP");
        assert.equal(port0.ssts >> 8 & 0xF, 6, "idle: slumber");
        await command(machine, "echo max_performance > " + policy);
        assert.equal(port0.ssts >> 8 & 0xF, 1, "max_performance: active");
        const lpm_dmesg = await command(machine, "dmesg");
        assert.ok(!/exception Emask|hard resetting link|failed command/.test(lpm_dmesg), "no libata errors: " + lpm_dmesg);
        log("linux: link power management (min_power): the idle link slumbers, reads wake it");

        const cd_sum = await command(machine, "dd if=/dev/sr0 bs=64k count=32 2>/dev/null | md5sum");
        const iso = fs.readFileSync(IMAGES + "linux4.iso");
        assert.ok(cd_sum.includes(crypto.createHash("md5").update(iso.subarray(0, 2 << 20)).digest("hex")), "sr0 reads the ISO");
        log("linux: 4 MiB written to hda and read back, sr0 matches the ISO");

        // hot plug: a disk into port 3 (ata4)
        const extra = new Uint8Array(8 << 20).map((_, i) => i * 31 + (i >> 9) & 0xFF);
        const extra_sum = crypto.createHash("md5").update(extra).digest("hex");
        await emulator.attach_sata_drive(3, { buffer: extra.buffer });
        await wait_for_command(machine, "ls /sys/block | cat", out => /^sdb\s*$/m.test(out), "sdb");
        const extra_read = await command(machine, "dd if=/dev/sdb bs=64k 2>/dev/null | md5sum");
        assert.ok(extra_read.includes(extra_sum), "sdb reads the image: " + extra_read);
        const plugged = await command(machine, "dmesg | grep ata4");
        assert.ok(/ata4: SATA link up 1\.5 Gbps/.test(plugged) && /ata4\.00: .*NCQ/.test(plugged), plugged);
        log("linux: a disk hot plugged into port 3 appears as sdb (ata4) and reads the image");

        // a snapshot, restored into the same machine (with the hot plugged disk)
        const state = await emulator.save_state();
        await emulator.restore_state(state);
        const after = await command(machine, "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda bs=64k count=64 2>/dev/null | md5sum; dd if=/dev/sdb bs=64k 2>/dev/null | md5sum");
        assert.ok(after.includes(sums[0]) && after.includes(extra_sum), "after a snapshot restore: " + after);
        log("linux: snapshot restored, the disks read the same");

        // and pulled out again
        emulator.detach_sata_drive(3);
        await wait_for_command(machine, "ls /sys/block | cat", out => !/^sdb\s*$/m.test(out), "sdb to go away");
        const unplugged = await command(machine, "dmesg | grep ata4");
        assert.ok(/ata4: SATA link down/.test(unplugged), unplugged);
        log("linux: pulled out, sdb is gone (ata4: link down)");

        // reset through the FADT reset register, boot again from the CD
        machine.serial = "";
        emulator.serial0_send("reboot -f\n");
        await wait_for("the shell after the reset", () => PROMPT.test(machine.serial), 240000);
        const again = await command(machine, "dd if=/dev/sda bs=64k count=64 2>/dev/null | md5sum");
        assert.ok(again.includes(sums[0]), "the data is still on hda after the reset");
        log("linux: reset (reboot), booted again from the CD, hda kept the data");

        const off = next_event(emulator, "acpi-power-off", 60000);
        emulator.serial0_send("poweroff -f\n");
        assert.equal(await off, "S5");
        log("linux: poweroff -> S5");
    }
    finally
    {
        emulator.destroy();
    }
}

/**
 * A file from an ISO9660 image (plain names, without version or Rock Ridge)
 * @param {string} path
 * @param {!Array<string>} names
 * @return {!ArrayBuffer}
 */
function iso_file(path, names)
{
    const iso = fs.readFileSync(path);
    let extent = iso.readUInt32LE(16 * 2048 + 156 + 2), size = iso.readUInt32LE(16 * 2048 + 156 + 10);
    for(const name of names)
    {
        let found = false;
        for(let at = extent * 2048; at < extent * 2048 + size;)
        {
            const length = iso[at];
            if(!length) { at = (Math.floor(at / 2048) + 1) * 2048; continue; }
            const entry = iso.toString("latin1", at + 33, at + 33 + iso[at + 32]).replace(/;\d+$/, "").replace(/\.$/, "");
            if(entry === name)
            {
                extent = iso.readUInt32LE(at + 2);
                size = iso.readUInt32LE(at + 10);
                found = true;
                break;
            }
            at += length;
        }
        assert.ok(found, name + " in " + path);
    }
    return iso.buffer.slice(iso.byteOffset + extent * 2048, iso.byteOffset + extent * 2048 + size);
}

async function part_intx()
{
    log("intx: linux4's kernel booted directly with pci=nomsi: AHCI's INTA through PIRQA, GSI 16");
    const disk = new Uint8Array(4 << 20).map((_, i) => i * 29 + (i >> 9) & 0xFF);
    const machine = await start({
        cdrom: { url: IMAGES + "linux4.iso" },
        bzimage: { buffer: iso_file(IMAGES + "linux4.iso", ["BOOT", "BZIMAGE"]) },
        cmdline: "root=/dev/sr0 pci=nomsi",
        // a second AHCI controller behind root port 1
        pcie_root_ports: 2,
        ahci_test_drives: [{ buffer: new SyncBuffer(disk.buffer) }],
        ahci_test_pci_id: 2 << 8,
        // (and the HPET, for this kernel too)
        hpet: true,
    });
    try
    {
        await wait_for("the shell", () => PROMPT.test(machine.serial), 240000);
        await command(machine, "dd if=/dev/sr0 bs=64k count=16 2>/dev/null | md5sum");
        const interrupts = await command(machine, "cat /proc/interrupts");
        const match = interrupts.match(/16:\s+(\d+)\s+IO-APIC\s+16-fasteoi\s+ahci/);
        assert.ok(match && +match[1] > 0, "ahci on GSI 16 (PIRQA): " + interrupts);
        log("intx: " + match[1] + " interrupts on GSI 16");

        const dmesg = await command(machine, "dmesg");
        const bus = dmesg.match(/pci 0000:00:1c\.1: PCI bridge to \[bus (\w\w)\]/);
        assert.ok(bus, "root port 1's bus: " + dmesg);
        assert.ok(new RegExp("ahci 0000:" + bus[1] + ":00\\.0: AHCI 0001\\.0000 32 slots 6 ports").test(dmesg), "ahci behind the bridge");
        const block = await command(machine, "for b in /sys/block/sd*; do echo $(readlink -f $b); done");
        const sd = block.match(new RegExp("0000:00:1c\\.1/0000:" + bus[1] + ":00\\.0/\\S*/block/(sd\\w)"));
        assert.ok(sd, "a disk behind the bridge: " + block);
        const sum = await command(machine, "dd if=/dev/" + sd[1] + " bs=64k 2>/dev/null | md5sum");
        assert.ok(sum.includes(crypto.createHash("md5").update(disk).digest("hex")), "reads the disk: " + sum);
        const shared = await command(machine, "cat /proc/interrupts");
        assert.ok(new RegExp("16:\\s+\\d+\\s+IO-APIC\\s+16-fasteoi\\s+ahci\\[0000:00:1f\\.2\\], ahci\\[0000:" + bus[1] + ":00\\.0\\]").test(shared),
            "both controllers on GSI 16: INTA behind root port 1 -> device 28's INTA -> PIRQA: " + shared);
        log("intx: the AHCI controller behind root port 1 (" + bus[1] + ":00.0): /dev/" + sd[1] + " reads the image, INTA on GSI 16");
        assert.ok(/ACPI: HPET id: 0x8086a201 base: 0xfed00000/.test(dmesg) && /clocksource: hpet: mask/.test(dmesg), "the HPET");
        assert.ok(machine.emulator.v86.cpu.devices.hpet.legacy_replacement(), "IRQ 0 from the HPET");
        log("intx: Linux 4.16 uses the HPET too (legacy replacement route)");
    }
    finally
    {
        machine.emulator.destroy();
    }
}

async function part_dos()
{
    for(const clean of [true, false])
    {
        log("dos: MS-DOS 6.22 from the SATA disk, " + (clean ? "clean boot (real mode)" : "CONFIG.SYS with EMM386 (virtual-8086 mode)"));
        const machine = await start({
            hda: { buffer: fs.readFileSync(IMAGES + "msdos622.img").buffer },
            memory_size: 64 * 1024 * 1024,
        });
        try
        {
            let pressed = false;
            const press = setInterval(() => {
                if(clean && !pressed && /Starting MS-DOS/.test(screen(machine)))
                {
                    machine.emulator.keyboard_send_scancodes([0x3F, 0xBF]); // F5: bypass CONFIG.SYS and AUTOEXEC.BAT
                    pressed = /bypassing/.test(screen(machine));
                }
            }, 50);
            try
            {
                if(clean)
                {
                    await wait_for("C:\\>", () => /C:\\>/.test(screen(machine)), 120000);
                    assert.ok(/MS-DOS is bypassing/.test(screen(machine)));
                    log("dos: C:\\> through SeaBIOS's AHCI disk services");
                }
                else
                {
                    // EMM386 runs DOS in virtual-8086 mode: SeaBIOS reaches its
                    // 32-bit AHCI driver from there through SMM (call32_smm)
                    await wait_for("the emulator", () => machine.emulator.v86, 60000);
                    const cpu = machine.emulator.v86.cpu;
                    // (counted where the APM control port raises them, in
                    // the mode of the guest's OUT)
                    let smis = 0, from_vm86 = 0;
                    const smi = cpu.smi.bind(cpu);
                    cpu.smi = core => {
                        smis++;
                        if(cpu.get_eflags() & 1 << 17) from_vm86++;
                        smi(core);
                    };
                    await wait_for("C:\\>", () => /C:\\>|Bad or missing/.test(screen(machine)), 120000);
                    assert.ok(!/Bad or missing/.test(screen(machine)), "disk services in virtual-8086 mode: " + screen(machine));
                    const before = from_vm86;
                    machine.emulator.keyboard_send_text("dir\n");
                    await wait_for("DIR", () => /bytes free/.test(screen(machine)), 60000);
                    assert.ok(cpu.cr[0] & 1, "EMM386: protected mode");
                    assert.ok(from_vm86 > before, "DIR's disk reads: SMIs from virtual-8086 mode (" + (from_vm86 - before) + ")");
                    log("dos: with EMM386 the disk services work from virtual-8086 mode through SMM: " +
                        from_vm86 + " of " + smis + " SMIs from virtual-8086 mode");
                }
            }
            finally
            {
                clearInterval(press);
            }
        }
        finally
        {
            machine.emulator.destroy();
        }
    }
}

async function part_pic()
{
    log("pic: direct kernel boot, PIC routing");
    const machine = await start({
        bzimage: { url: IMAGES + "buildroot-bzimage68.bin" },
        cmdline: "console=ttyS0 audit=0",
        smbus: true,
    });
    try
    {
        await wait_for("the shell", () => PROMPT.test(machine.serial), 180000);
        const dmesg = await command(machine, "dmesg");
        assert.ok(/ECAM \[mem 0xb0000000-0xbfffffff\].*for domain 0000 \[bus 00-ff\]/.test(dmesg), "ECAM");
        assert.ok(/Using ECAM for extended config space/.test(dmesg));
        assert.ok(/ACPI: Using PIC for interrupt routing/.test(dmesg));
        assert.ok(/ACPI: PCI Root Bridge \[PCI0\]/.test(dmesg));
        for(const link of "ABCDEFGH") assert.ok(new RegExp("Interrupt link LNK" + link + " configured for IRQ 1[01]").test(dmesg), "LNK" + link);
        const devices = await command(machine, "for d in /sys/bus/pci/devices/*; do echo $d $(cat $d/vendor $d/device $d/class); done");
        for(const [bdf, id] of [["00:00.0", "0x8086 0x29c0 0x060000"], ["00:1f.0", "0x8086 0x2918 0x060100"], ["00:1f.2", "0x8086 0x2922 0x010601"]])
        {
            assert.ok(devices.includes(bdf + " " + id), bdf + " " + id);
        }
        const iomem = await command(machine, "cat /proc/iomem");
        assert.ok(/b0000000-bfffffff : PCI ECAM/.test(iomem) || /b0000000-bfffffff : PCI MMCONFIG/.test(iomem));
        assert.ok(/fed1c000-fed1ffff/.test(iomem), "RCBA reserved");
        // the root complex registers reach the guest (GCS: no reboot; D28IR:
        // INTA-D -> PIRQA-D)
        const rcba = await command(machine, "devmem 0xfed1f410 32; devmem 0xfed1f146 16");
        assert.ok(/0x00000020\s+0x3210/.test(rcba), "RCBA through the guest's own reads: " + rcba);
        log("pic: ECAM in use, PNP0A08 root bridge, eight PIRQ links, chipset functions, RCBA readable");

        // the SMBus controller where SeaBIOS put it (the PM base + 0x100),
        // a byte written to the EEPROM at 0x50 and read back through /dev/port
        const smbus = await command(machine, "cat /sys/bus/pci/devices/0000:00:1f.3/class /sys/bus/pci/devices/0000:00:1f.3/resource | head -6");
        assert.ok(/0x0c0500/.test(smbus) && /0x0000000000000700 0x000000000000071f 0x0000000000040101/.test(smbus), "00:1f.3 at 0x700: " + smbus);
        // (shell functions, so that the commands stay short)
        await command(machine, "outb() { printf \"\\\\$(printf %o $2)\" | dd of=/dev/port bs=1 seek=$1 conv=notrunc 2>/dev/null; }");
        await command(machine, "inb() { dd if=/dev/port bs=1 skip=$1 count=1 2>/dev/null | od -An -tx1 | tr -d ' '; }");
        // write byte data 0x77 at offset 5 of the EEPROM at 0x50, then read it
        await command(machine, "outb 1792 255; outb 1796 160; outb 1795 5; outb 1797 119; outb 1794 72");
        const read_back = await command(machine, "outb 1792 255; outb 1796 161; outb 1795 5; outb 1794 72; echo SMB $(inb 1792) $(inb 1797)");
        const result = read_back.match(/SMB ([0-9a-f]{2}) ([0-9a-f]{2})/);
        assert.ok(result && (parseInt(result[1], 16) & 0xBF) === 0x02 && result[2] === "77", "INTR, and the byte: " + read_back);
        log("pic: SMBus at 0x700 (SeaBIOS), the EEPROM at 0x50 written and read by the guest");
    }
    finally
    {
        machine.emulator.destroy();
    }
}

async function part_pcie()
{
    log("pcie: direct kernel boot, three PCI Express root ports");
    const disk = new Uint8Array(4 << 20).map((_, i) => i * 29 + (i >> 9) & 0xFF);
    const pattern = i => i * 37 + 11 & 0xFF;
    let rng;
    const machine = await start({
        bzimage: { url: IMAGES + "buildroot-bzimage68.bin" },
        cmdline: "console=ttyS0 audit=0",
        pcie_root_ports: 3,
        ahci_test_drives: [{ buffer: new SyncBuffer(disk.buffer) }],
        ahci_test_pci_id: 1 << 8,
        virtio_devices: [{
            "name": "rng",
            "device_id": 0x1044,
            "subsystem_device_id": 4,
            "queues": [{ "size": 8 }],
            "pcie_root_port": 2,
            "init": handle => { rng = handle; },
            "notify": queue => {
                let request;
                while((request = rng["pop_request"](queue)))
                {
                    const bytes = new Uint8Array(request["writable"]);
                    for(let i = 0; i < bytes.length; i++) bytes[i] = pattern(i);
                    request["write"](bytes);
                    request["complete"]();
                }
                rng["flush"](queue);
            },
        }],
    });
    try
    {
        await wait_for("the shell", () => PROMPT.test(machine.serial), 180000);
        const devices = await command(machine, "for d in /sys/bus/pci/devices/*; do echo $(readlink -f $d) $(cat $d/vendor $d/device $d/class); done");
        for(let n = 0; n < 3; n++)
        {
            const id = "0x8086 0x" + (0x2940 + 2 * n).toString(16) + " 0x060400";
            assert.ok(devices.includes("/sys/devices/pci0000:00/0000:00:1c." + n + " " + id), "root port " + n + ": " + devices);
        }
        const ahci = devices.match(/\/0000:00:1c\.0\/0000:(\w\w):00\.0 0x8086 0x2922 0x010601/);
        const virtio = devices.match(/\/0000:00:1c\.2\/0000:(\w\w):00\.0 0x1af4 0x1044 0x/);
        assert.ok(ahci && virtio, "the AHCI controller behind port 0, the virtio device behind port 2: " + devices);
        log("pcie: root ports 00:1c.0-2, AHCI at " + ahci[1] + ":00.0 behind port 0, virtio at " + virtio[1] + ":00.0 behind port 2");

        const dmesg = await command(machine, "dmesg");
        assert.ok(/pci 0000:00:1c\.0: \[8086:2940\] type 01 class 0x060400 PCIe Root Port/.test(dmesg), "a PCI Express root port");
        assert.ok(new RegExp("pci 0000:00:1c\\.0: PCI bridge to \\[bus " + ahci[1] + "\\]").test(dmesg), "the bridge's bus");
        assert.ok(new RegExp("pci 0000:00:1c\\.2:\\s+bridge window \\[io\\s+0x[0-9a-f]+-0x[0-9a-f]+\\]").test(dmesg), "port 2: an I/O window for the virtio device");
        assert.ok(!/BAR \d+: (no space|failed)|can't claim/.test(dmesg), "every BAR assigned within the windows");

        const expected = Array.from({ length: 8 }, (_, i) => pattern(i).toString(16).padStart(2, "0")).join(" ");
        const random = await command(machine, "cat /sys/class/misc/hw_random/rng_current; head -c 8 /dev/hwrng | od -An -tx1");
        assert.ok(random.includes("virtio_rng") && random.includes(expected), "/dev/hwrng: " + random);
        const interrupts = await command(machine, "cat /proc/interrupts");
        assert.ok(/virtio\d/.test(interrupts), "the virtio device's interrupt: " + interrupts);
        log("pcie: /dev/hwrng reads the virtio device behind root port 2 (INTx through the swizzle)");
    }
    finally
    {
        machine.emulator.destroy();
    }
}

async function part_hpet()
{
    log("hpet: direct kernel boot with the HPET");
    const machine = await start({
        bzimage: { url: IMAGES + "buildroot-bzimage68.bin" },
        cmdline: "console=ttyS0 audit=0",
        hpet: true,
    });
    try
    {
        await wait_for("the shell", () => PROMPT.test(machine.serial), 180000);
        const hpet = machine.emulator.v86.cpu.devices.hpet;
        const dmesg = await command(machine, "dmesg");
        assert.ok(/ACPI: HPET 0x[0-9A-F]+ 000038 \(v01 /.test(dmesg), "the ACPI table: " + dmesg);
        assert.ok(/ACPI: HPET id: 0x8086a201 base: 0xfed00000/.test(dmesg), "the event timer block");
        assert.ok(/clocksource: hpet: mask: 0xffffffff/.test(dmesg), "an HPET clock source");
        assert.ok(!/hpet: Config register invalid|HPET.*(not|dis)abl/i.test(dmesg), "not refused");
        assert.ok(hpet.legacy_replacement(), "Linux took IRQ 0 and 8 (legacy replacement route)");
        const interrupts = await command(machine, "cat /proc/interrupts");
        const timer = interrupts.match(/^\s*0:\s+(\d+)\s+.*timer/m);
        assert.ok(timer && +timer[1] > 0, "interrupts on IRQ 0, from the HPET: " + interrupts);
        log("hpet: Linux found it (ACPI HPET table), IRQ 0 by legacy replacement: " + timer[1] + " interrupts");

        const sources = await command(machine, "cat /sys/devices/system/clocksource/clocksource0/available_clocksource");
        assert.ok(/\bhpet\b/.test(sources), sources);
        await command(machine, "echo hpet > /sys/devices/system/clocksource/clocksource0/current_clocksource");
        assert.ok((await command(machine, "cat /sys/devices/system/clocksource/clocksource0/current_clocksource")).includes("hpet"));
        const start = Date.now();
        const elapsed = await command(machine, "a=$(cut -d' ' -f1 /proc/uptime); sleep 2; b=$(cut -d' ' -f1 /proc/uptime); echo \"$a $b\"");
        const host_seconds = (Date.now() - start) / 1000;
        const [a, b] = elapsed.trim().split(/\s+/).slice(-2).map(Number);
        assert.ok(b - a >= 1.9 && b - a <= host_seconds + 0.2, "the guest's 2 s by the HPET: " + (b - a) + " (host " + host_seconds + ")");
        const timer_list = await command(machine, "grep -i -m 3 hpet /proc/timer_list");
        assert.ok(/hpet/i.test(timer_list), "an HPET clock event device: " + timer_list);
        log("hpet: clocksource hpet, sleep 2 took " + (b - a).toFixed(2) + " s of guest uptime");
    }
    finally
    {
        machine.emulator.destroy();
    }
}

const timeout = setTimeout(() => {
    console.log("Timeout");
    process.exit(1);
}, 20 * 60 * 1000);

for(const part of PARTS)
{
    await { "linux": part_linux, "intx": part_intx, "dos": part_dos, "pic": part_pic, "pcie": part_pcie, "hpet": part_hpet }[part]();
}
clearTimeout(timeout);
console.log("Q35 guest test passed (" + PARTS.join(", ") + ")");
                                                                                                                                                                                                      source/v64/tests/devices/smbus.js                                                                   0000755 0000000 0000000 00000021230 00000000000 014140  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The ICH9 SMBus controller of the Q35 machine (smbus: true), driven through
// its I/O registers as SeaBIOS sets it up (BAR4 at the PM base + 0x100,
// HOSTC.HST_EN) and as Linux's i2c-i801 drives it (docs/q35.md):
// decode, quick/byte/byte data/word data commands to the EEPROMs at
// 0x50-0x57, NACK for absent devices, block commands through the 32-byte
// buffer and byte by byte, I2C block reads, interrupts and snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    machine_type: "q35",
    smbus: true,
    memory_size: 32 * 1024 * 1024,
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const SMB = 0x1F << 3 | 3;

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const BASE = 0x700;
const inb = offset => cpu.io.port_read8(BASE + offset);
const outb = (offset, value) => cpu.io.port_write8(BASE + offset, value);
const STS = 0, CNT = 2, CMD = 3, SLVA = 4, D0 = 5, D1 = 6, BLK = 7, AUX_CTL = 0xD;
const INTR = 2, DEV_ERR = 4, FAILED = 0x10, INUSE = 0x40, BYTE_DONE = 0x80, BUSY = 1;
const START = 0x40, LAST_BYTE = 0x20, INTREN = 1, KILL = 2;
const QUICK = 0 << 2, BYTE = 1 << 2, BYTE_DATA = 2 << 2, WORD_DATA = 3 << 2, BLOCK = 5 << 2, I2C_READ = 6 << 2;
const E32B = 2;

/** A command as i801 runs it: clear the status, set up, start; the status after */
function run(protocol, address, read, setup = {})
{
    outb(STS, 0xFF);
    outb(SLVA, address << 1 | (read ? 1 : 0));
    if(setup.command !== undefined) outb(CMD, setup.command);
    if(setup.d0 !== undefined) outb(D0, setup.d0);
    if(setup.d1 !== undefined) outb(D1, setup.d1);
    outb(CNT, protocol | START | (setup.intren ? INTREN : 0));
    return inb(STS) & ~INUSE;
}

test("PCI function 00:1f.3: ICH9 SMBus, BAR4 I/O, HOSTC; decoded only with HST_EN and I/O space", () => {
    assert.equal(pci.config_read(SMB, 0, 4) >>> 0, 0x29308086);
    assert.equal(pci.config_read(SMB, 0x08, 4) >>> 8, 0x0C0500, "SMBus");
    assert.equal(pci.config_read(0x1F << 3, 0x0E, 1) & 0x80, 0x80, "device 31 is multi-function");
    pci.config_write(SMB, 0x20, 4, 0xFFFFFFFF);
    assert.equal(pci.config_read(SMB, 0x20, 4) >>> 0, 0xFFFFFFE1, "32 bytes of I/O");
    // SeaBIOS (ich9_smbus_setup): PM base + 0x100, HST_EN
    pci.config_write(SMB, 0x20, 4, BASE | 1);
    assert.equal(inb(STS), 0xFF, "not decoded yet");
    pci.config_write(SMB, 0x40, 1, 1);
    assert.equal(inb(STS), 0xFF, "HST_EN, but I/O space disabled");
    pci.config_write(SMB, 0x04, 2, 1);
    assert.equal(inb(STS), 0, "decoded");
    assert.equal(inb(STS), INUSE, "INUSE_STS: set by the read that found it clear");
    outb(STS, INUSE);
    assert.equal(inb(STS) & INUSE, 0, "cleared by writing one");
    pci.config_write(SMB, 0x40, 1, 0xFF);
    assert.equal(pci.config_read(SMB, 0x40, 1), 0x1F, "HOSTC: five bits");
    assert.equal(inb(STS), 0xFF, "I2C_EN: the SMBus host interface is off");
    pci.config_write(SMB, 0x40, 1, 1);
});

test("byte data and word data to the EEPROM at 0x50; a quick command; no device at 0x30: DEV_ERR", () => {
    assert.equal(run(BYTE_DATA, 0x50, false, { command: 0x10, d0: 0xAB }), INTR, "write byte data");
    assert.equal(run(BYTE_DATA, 0x50, true, { command: 0x10 }), INTR);
    assert.equal(inb(D0), 0xAB, "read back");
    assert.equal(run(WORD_DATA, 0x50, false, { command: 0x20, d0: 0x34, d1: 0x12 }), INTR, "write word");
    assert.equal(run(WORD_DATA, 0x50, true, { command: 0x20 }), INTR);
    assert.deepEqual([inb(D0), inb(D1)], [0x34, 0x12]);
    assert.equal(run(BYTE, 0x50, false, { command: 0x20 }), INTR, "send byte: the offset");
    assert.equal(run(BYTE, 0x50, true), INTR);
    assert.equal(inb(D0), 0x34, "receive byte at it");
    assert.equal(run(BYTE, 0x50, true), INTR);
    assert.equal(inb(D0), 0x12, "and on");
    assert.equal(run(QUICK, 0x57, false), INTR, "the eighth EEPROM answers");
    assert.equal(run(QUICK, 0x30, false), DEV_ERR, "nothing at 0x30: no acknowledge");
    assert.equal(run(QUICK, 0x58, false), DEV_ERR);
    assert.equal(run(BYTE_DATA, 0x51, true, { command: 0x10 }), INTR, "another EEPROM, zeroed");
    assert.equal(inb(D0), 0);
});

test("block write and read through the 32-byte buffer (E32B)", () => {
    outb(AUX_CTL, E32B);
    inb(CNT); // (resets the buffer index)
    for(let i = 0; i < 5; i++) outb(BLK, 0x60 + i);
    assert.equal(run(BLOCK, 0x52, false, { command: 0x40, d0: 5 }), INTR, "block write");
    assert.equal(run(BLOCK, 0x52, true, { command: 0x40 }), INTR, "block read");
    assert.equal(inb(D0), 5, "the byte count");
    inb(CNT);
    assert.deepEqual(Array.from({ length: 5 }, () => inb(BLK)), [0x60, 0x61, 0x62, 0x63, 0x64]);
    outb(AUX_CTL, 0);
});

test("byte-by-byte block transfers (as i801 without E32B): BYTE_DONE, LAST_BYTE", () => {
    // write: count in D0, the first byte in HOST_BLOCK_DB before START
    const bytes = [0x11, 0x22, 0x33];
    outb(STS, 0xFF);
    outb(SLVA, 0x53 << 1);
    outb(CMD, 0x80);
    outb(D0, bytes.length);
    outb(BLK, bytes[0]);
    outb(CNT, BLOCK | START);
    for(let i = 1; i <= bytes.length; i++)
    {
        assert.equal(inb(STS) & BYTE_DONE, BYTE_DONE, "byte " + i + " taken");
        assert.equal(inb(STS) & BUSY, BUSY);
        if(i < bytes.length) outb(BLK, bytes[i]);
        outb(STS, BYTE_DONE);
    }
    assert.equal(inb(STS) & (INTR | BUSY), INTR, "done");

    // read: the count comes with the first byte; LAST_BYTE before the last
    outb(STS, 0xFF);
    outb(SLVA, 0x53 << 1 | 1);
    outb(CMD, 0x80);
    const got = [];
    let length = 1;
    for(let i = 1; i <= length; i++)
    {
        const cnt = BLOCK | (i === length && i > 1 ? LAST_BYTE : 0);
        outb(CNT, i === 1 ? cnt | START : cnt);
        assert.equal(inb(STS) & BYTE_DONE, BYTE_DONE, "byte " + i);
        if(i === 1) length = inb(D0);
        if(i === length) outb(CNT, BLOCK | LAST_BYTE);
        got.push(inb(BLK));
        outb(STS, BYTE_DONE);
    }
    assert.deepEqual(got, bytes, "read back");
    assert.equal(inb(STS) & (INTR | BUSY | BYTE_DONE), INTR, "INTR after the last byte");
});

test("I2C block read: the offset in HST_D1, bytes until LAST_BYTE", () => {
    outb(STS, 0xFF);
    outb(SLVA, 0x50 << 1 | 1);
    outb(D1, 0x20);
    const got = [];
    for(let i = 1; i <= 2; i++)
    {
        outb(CNT, I2C_READ | (i === 2 ? LAST_BYTE : 0) | (i === 1 ? START : 0));
        assert.equal(inb(STS) & BYTE_DONE, BYTE_DONE);
        got.push(inb(BLK));
        outb(STS, BYTE_DONE);
    }
    assert.deepEqual(got, [0x34, 0x12], "the word written above");
    assert.equal(inb(STS) & (INTR | BUSY), INTR);
});

test("KILL ends a byte-by-byte transfer: FAILED; an uncleared error stops the next command", () => {
    outb(STS, 0xFF);
    outb(SLVA, 0x50 << 1 | 1);
    outb(D1, 0);
    outb(CNT, I2C_READ | START);
    assert.equal(inb(STS) & BUSY, BUSY);
    outb(CNT, KILL);
    assert.equal(inb(STS) & (FAILED | BUSY | BYTE_DONE), FAILED);
    outb(CNT, 0);
    outb(SLVA, 0x50 << 1 | 1);
    outb(CNT, BYTE | START);
    assert.equal(inb(STS) & (DEV_ERR | INTR), DEV_ERR, "FAILED still set: not run");
    assert.equal(run(BYTE, 0x50, true), INTR, "cleared: runs");
});

test("INTREN: INTA (00:1f.3 behind D31IR: PIRQA, GSI 16) until the status is cleared", () => {
    run(QUICK, 0x50, false, { intren: true });
    assert.ok(cpu.shared_irq_sources[16].has(SMB), "asserted");
    outb(STS, INTR);
    assert.ok(!cpu.shared_irq_sources[16].has(SMB), "cleared");
    outb(CNT, 0);
});

run(WORD_DATA, 0x55, false, { command: 0x00, d0: 0x5A, d1: 0xA5 });
const state = await emulator.save_state();
run(WORD_DATA, 0x55, false, { command: 0x00, d0: 0, d1: 0 });
pci.config_write(SMB, 0x40, 1, 0);
await emulator.restore_state(state);
test("snapshot: decode and the EEPROMs' contents", () => {
    assert.equal(run(WORD_DATA, 0x55, true, { command: 0x00 }), INTR);
    assert.deepEqual([inb(D0), inb(D1)], [0x5A, 0xA5]);
});

emulator.destroy();
console.log((failed ? "FAIL" : "PASS") + ": " + passed + " SMBus tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/devices/smm.js                                                                     0000755 0000000 0000000 00000053244 00000000000 013615  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// System management mode on the Q35 machine (docs/q35.md), with
// SeaBIOS: its SMM setup (SMBASE relocated to 0xA0000, SMRAM
// closed with G_SMRAME), the state save area in QEMU's 32-bit layout, SMRAM
// visibility (the VGA window outside SMM, RAM in SMM and with D_OPEN), an SMI
// with a handler of the test's own that only executes RSM (the state comes
// back), an SMI in SMM (latched until RSM), SMIs from the local APIC (an IPI,
// an MSI), snapshots (also in SMM), TSEG (all ones outside SMM, RAM in it;
// QEMU's extended TSEG), high SMRAM (H_SMRAME, also with SMBASE there),
// D_CLS, the auto HALT restart field, D_LCK and the LPC's SMI_LOCK. Then the x86-64 CPU profile:
// SeaBIOS with QEMU's 64-bit save area. (An SMI in long mode:
// tests/x64/smm_long_mode.mjs.)

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { STATE_OFFSETS } = await import("../../src/state_layout.js");

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

/** A Q35 machine with SeaBIOS, stopped once SeaBIOS found nothing to boot */
async function boot(options = {})
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        machine_type: "q35",
        memory_size: 32 * 1024 * 1024,
        autostart: true,
        screen_dummy: true,
        log_level: 0,
        ...options,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const deadline = Date.now() + 60000;
    while(!/No bootable device/.test(emulator.screen_adapter.get_text_screen().join("\n")))
    {
        assert.ok(Date.now() < deadline, "SeaBIOS boots");
        await new Promise(resolve => setTimeout(resolve, 100));
    }
    await emulator.stop();
    return emulator;
}

let emulator = await boot();
let cpu = emulator.v86.cpu;
const pci = () => cpu.devices.pci;

const state32 = offset => new Uint32Array(cpu.wasm_memory.buffer, cpu.state_base + offset, 1);
const smbase = () => state32(STATE_OFFSETS.smbase)[0] >>> 0;
const in_smm = () => !!cpu.smm_active();
const smi_pending = () => !!cpu.apic_core_smi_pending(0);
const ram32 = address => (cpu.mem8[address] | cpu.mem8[address + 1] << 8 | cpu.mem8[address + 2] << 16 | cpu.mem8[address + 3] << 24) >>> 0;
const ram64 = address => BigInt(ram32(address)) | BigInt(ram32(address + 4)) << 32n;
const MCH_SMRAM = 0x9D, MCH_ESMRAMC = 0x9E, MCH_EXT_TSEG_MBYTES = 0x50;

// One instruction (the handler's RSM, after an SMI the slice takes first). A
// slice ends before its first instruction when the IR scheduler submits a
// compile at its start (src/rust/cpu/cpu.rs run_cpu_slice), so that the host
// can install the code: then the next slice runs it. (After a boot a code page
// may just have reached its threshold.)
function step()
{
    if(cpu.run_cpu_slice(1)) return;
    assert.equal(cpu.get_jit_info().ir?.pending, 1, "the slice yielded to a compile");
    assert.equal(cpu.run_cpu_slice(1), 1, "the next slice runs the instruction");
}

test("SeaBIOS's SMM setup: SMBASE relocated to 0xA0000, SMI_EN.APMC_EN, SMRAM closed with G_SMRAME", () => {
    assert.equal(smbase(), 0xA0000);
    assert.ok(!in_smm());
    assert.equal(pci().config_read(0, MCH_SMRAM, 1), 0x0A, "G_SMRAME, C_BASE_SEG; D_OPEN clear");
    assert.ok(cpu.devices.acpi.smi_en & 1 << 5, "APMC_EN");
    assert.deepEqual(Array.from(cpu.mem8.subarray(0xA8000, 0xA8003)), [0x8C, 0xC8, 0xEA], "SeaBIOS's entry_smi in SMRAM");
});

test("the state save area of the last SMI (call32_smm's return): QEMU's 32-bit layout", () => {
    // (SeaBIOS's handler put the 16-bit state there that RSM went back to)
    const area = 0xA8000;
    assert.equal(ram32(area + 0x7EFC), 0x00020000, "revision: SMBASE relocation, 32-bit layout");
    assert.equal(ram32(area + 0x7EF8), 0xA0000, "SMBASE");
    assert.equal(ram32(area + 0x7FFC) & 1, 0, "CR0: back to real mode");
    assert.equal(ram32(area + 0x7FAC), 0xF000, "CS selector: SeaBIOS's 16-bit code");
    assert.equal(ram32(area + 0x7F84 + 12 + 8), 0xF0000, "CS base");
});

test("SMRAM visibility: outside SMM the VGA window, with D_OPEN RAM", () => {
    assert.notEqual(cpu.read32s(0xAFEFC) >>> 0, 0x00020000, "closed: the guest sees the VGA window");
    pci().config_write(0, MCH_SMRAM, 1, 0x4A);
    assert.equal(cpu.read32s(0xAFEFC) >>> 0, 0x00020000, "D_OPEN: RAM");
    pci().config_write(0, MCH_SMRAM, 1, 0x0A);
    assert.notEqual(cpu.read32s(0xAFEFC) >>> 0, 0x00020000);
});

// an SMI with a handler that only executes RSM
const saved_handler = cpu.mem8.slice(0xA8000, 0xA8002);
cpu.mem8.set([0x0F, 0xAA], 0xA8000);
cpu.reg32[3] = 0x12345678; // EBX
const before = { eip: cpu.instruction_pointer[0], eflags: cpu.get_eflags(), cr0: cpu.cr[0], cs: cpu.sreg[1], cs_base: cpu.segment_offsets[1] };
test("an SMI: the core enters SMM at SMBASE + 0x8000, in real mode with 4 GiB segments; SMRAM is RAM there", () => {
    cpu.smi();
    assert.ok(in_smm(), "taken at once (between instructions)");
    assert.ok(!smi_pending());
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xA8000);
    assert.equal(cpu.segment_offsets[1] >>> 0, 0xA0000, "CS base: SMBASE");
    assert.equal(cpu.sreg[1], 0xA000, "CS selector");
    assert.equal(cpu.segment_limits[3] >>> 0, 0xFFFFFFFF, "DS: 4 GiB");
    assert.equal(cpu.cr[0] & 0x80000001, 0, "no protected mode, no paging");
    assert.equal(cpu.get_eflags() & 0x200, 0, "interrupts off");
    assert.equal(cpu.read32s(0xA8000) & 0xFFFF, 0xAA0F, "in SMM the CPU sees SMRAM");
    assert.equal(ram32(0xAFFF0), before.eip - before.cs_base >>> 0, "EIP saved");
    assert.equal(ram32(0xAFFDC), 0x12345678, "EBX saved");
});
test("an SMI in SMM is latched, not nested", () => {
    cpu.smi();
    assert.ok(in_smm());
    assert.ok(smi_pending(), "pending until RSM");
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xA8000, "the handler did not restart");
});
// (one instruction: the RSM)
step();
test("RSM: out of SMM, the state back (registers, EFLAGS, CR0), SMBASE kept", () => {
    assert.ok(!in_smm());
    assert.equal(cpu.reg32[3] >>> 0, 0x12345678, "EBX");
    assert.equal(cpu.instruction_pointer[0], before.eip, "EIP: where the SMI came");
    assert.equal(cpu.get_eflags(), before.eflags, "EFLAGS");
    assert.equal(cpu.cr[0] >>> 0, before.cr0 >>> 0, "CR0");
    assert.equal(cpu.sreg[1], before.cs, "CS");
    assert.equal(smbase(), 0xA0000);
    assert.notEqual(cpu.read32s(0xA8000) & 0xFFFF, 0xAA0F, "the VGA window again");
    assert.ok(smi_pending(), "the latched SMI waits for the next instruction boundary");
});
cpu.reg32[3] = 0x87654321;
// the latched SMI at the start of the slice, then its handler's RSM
step();
test("the latched SMI is taken after RSM", () => {
    assert.ok(!smi_pending());
    assert.ok(!in_smm(), "(and its handler returned)");
    assert.equal(ram32(0xAFFDC), 0x87654321, "EBX saved by the second SMI");
    assert.equal(cpu.instruction_pointer[0], before.eip);
});

test("SMIs from the local APIC: an IPI to self, an MSI (delivery mode SMI)", () => {
    // ICR: delivery mode SMI, shorthand self
    cpu.write32(0xFEE00310, 0);
    cpu.write32(0xFEE00300, 2 << 8 | 1 << 18);
    assert.ok(in_smm(), "IPI");
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xA8000);
    step();
    assert.ok(!in_smm());
    assert.ok(cpu.apic_msi(0xFEE00000, 2 << 8), "MSI accepted");
    assert.ok(in_smm(), "MSI");
    step();
    assert.ok(!in_smm());
    assert.equal(cpu.instruction_pointer[0], before.eip);
});

// a snapshot in SMM, with an SMI latched
cpu.smi();
cpu.smi();
const in_smm_state = await emulator.save_state();
step();
step();
assert.ok(!in_smm() && !smi_pending());
await emulator.restore_state(in_smm_state);
test("snapshot in SMM: SMM and the latched SMI come back", () => {
    assert.ok(in_smm());
    assert.ok(smi_pending());
    step();
    assert.ok(!in_smm(), "RSM");
    assert.ok(smi_pending());
    step();
    assert.ok(!in_smm() && !smi_pending(), "the latched SMI, and its RSM");
    assert.equal(cpu.instruction_pointer[0], before.eip);
});

// TSEG: the top of the 32 MiB of RAM
const TOP = 32 << 20;
test("ESMRAMC: H_SMRAME, TSEG_SZ, T_EN writable, the cache bits read as one; extended TSEG: 16 MiB", () => {
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0x38);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x00);
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0x38);
    pci().config_write(0, MCH_ESMRAMC, 1, 0xFF);
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0xBF);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x38);
    assert.equal(pci().config_read(0, MCH_EXT_TSEG_MBYTES, 2), 0xFFFF, "before the query");
    pci().config_write(0, MCH_EXT_TSEG_MBYTES, 2, 0xFFFF);
    assert.equal(pci().config_read(0, MCH_EXT_TSEG_MBYTES, 2), 16, "the size in MiB");
});
test("TSEG (T_EN, 1 MiB): outside SMM all ones and writes dropped, in SMM RAM", () => {
    const base = TOP - (1 << 20);
    cpu.mem8.set([0x11, 0x22, 0x33, 0x44], base);
    cpu.mem8.set([0x55, 0x66, 0x77, 0x88], TOP - 4);
    cpu.mem8.set([0x99, 0xAA], base - 2);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x39);
    assert.equal(cpu.read32s(base) >>> 0, 0xFFFFFFFF, "all ones");
    assert.equal(cpu.read8(TOP - 1), 0xFF, "to the top");
    assert.equal(cpu.read32s(base - 2) >>> 0, 0xFFFFAA99, "across its start: RAM below");
    cpu.write32(base, 0xDEADBEEF);
    cpu.write16(base - 1, 0x5A5A);
    assert.equal(ram32(base), 0x44332211, "a write is dropped");
    assert.equal(cpu.mem8[base - 1], 0x5A, "(the byte below it is written)");
    // (the handler of the test: RSM)
    cpu.smi();
    assert.ok(in_smm());
    assert.equal(cpu.read32s(base) >>> 0, 0x44332211, "RAM in SMM");
    assert.equal(cpu.read32s(TOP - 4) >>> 0, 0x88776655);
    assert.equal(cpu.read32s(base - 2) >>> 0, 0x22115A99, "across its start");
    cpu.write32(base, 0xCAFEF00D);
    cpu.write16(base - 1, 0xA5A5);
    assert.equal(ram32(base), 0xCAFEF0A5, "written in SMM");
    step();
    assert.ok(!in_smm());
    assert.equal(cpu.read32s(base) >>> 0, 0xFFFFFFFF, "hidden again");
});
test("TSEG: G_SMRAME clear: no TSEG; TSEG_SZ 11: the extended size", () => {
    pci().config_write(0, MCH_SMRAM, 1, 0x02);
    assert.equal(cpu.read32s(TOP - (1 << 20)) >>> 0, 0xCAFEF0A5, "without G_SMRAME: RAM");
    pci().config_write(0, MCH_SMRAM, 1, 0x0A);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x3F);
    assert.equal(cpu.read32s(TOP - (16 << 20)) >>> 0, 0xFFFFFFFF, "16 MiB");
    assert.notEqual(cpu.read32s(TOP - (16 << 20) - 4) >>> 0, 0xFFFFFFFF);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x38);
    assert.equal(cpu.read32s(TOP - (1 << 20)) >>> 0, 0xCAFEF0A5, "T_EN clear: RAM");
});

const HIGH_SMRAM = 0xFEDA0000;
test("H_SMRAME: the RAM at 0xFEDA0000 instead (with D_OPEN for everyone, in SMM), the VGA window at 0xA0000", () => {
    pci().config_write(0, MCH_ESMRAMC, 1, 0xB8);
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0xB8);
    assert.notEqual(cpu.read32s(HIGH_SMRAM + 0x8000) & 0xFFFF, 0xAA0F, "outside SMM: not SMRAM");
    pci().config_write(0, MCH_SMRAM, 1, 0x4A);
    assert.equal(cpu.read32s(HIGH_SMRAM + 0x8000) & 0xFFFF, 0xAA0F, "D_OPEN: high SMRAM is the RAM of 0xA0000");
    assert.notEqual(cpu.read32s(0xA8000) & 0xFFFF, 0xAA0F, "and 0xA0000 the VGA window");
    cpu.write8(HIGH_SMRAM + 0x10, 0x5C);
    assert.equal(cpu.mem8[0xA0010], 0x5C, "a write reaches that RAM");
    pci().config_write(0, MCH_SMRAM, 1, 0x0A);
    assert.notEqual(cpu.read32s(HIGH_SMRAM + 0x8000) & 0xFFFF, 0xAA0F, "closed");
});
test("H_SMRAME: SMBASE in high SMRAM, the save area and the handler through it", () => {
    state32(STATE_OFFSETS.smbase)[0] = HIGH_SMRAM;
    cpu.reg32[3] = 0x13579BDF;
    cpu.smi();
    assert.ok(in_smm());
    assert.equal(cpu.segment_offsets[1] >>> 0, HIGH_SMRAM, "CS base: SMBASE");
    assert.equal(cpu.instruction_pointer[0] >>> 0, HIGH_SMRAM + 0x8000);
    assert.equal(cpu.read32s(HIGH_SMRAM + 0x8000) & 0xFFFF, 0xAA0F, "in SMM: high SMRAM");
    assert.notEqual(cpu.read32s(0xA8000) & 0xFFFF, 0xAA0F, "in SMM with H_SMRAME: 0xA0000 is the VGA window");
    assert.equal(ram32(0xAFFDC), 0x13579BDF, "EBX in the save area, in the RAM of 0xA0000");
    assert.equal(ram32(0xAFEF8), HIGH_SMRAM, "SMBASE in the save area");
    // (the RSM, fetched from high SMRAM)
    step();
    assert.ok(!in_smm());
    assert.equal(cpu.instruction_pointer[0], before.eip);
    assert.equal(cpu.reg32[3] >>> 0, 0x13579BDF);
    assert.equal(smbase(), HIGH_SMRAM);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x38);
    cpu.smi();
    assert.ok(!in_smm(), "high SMRAM off: the save area is nowhere, the SMI is dropped");
    state32(STATE_OFFSETS.smbase)[0] = 0xA0000;
});
test("D_CLS: in SMM, data accesses to the VGA window, instruction fetches to compatible SMRAM", () => {
    pci().config_write(0, MCH_SMRAM, 1, 0x2A);
    assert.equal(pci().config_read(0, MCH_SMRAM, 1), 0x2A);
    cpu.smi();
    assert.ok(in_smm());
    assert.notEqual(cpu.read32s(0xA8000) & 0xFFFF, 0xAA0F, "data: the VGA window");
    step();
    assert.ok(!in_smm(), "the handler's RSM came from SMRAM");
    assert.equal(cpu.instruction_pointer[0], before.eip);
    pci().config_write(0, MCH_SMRAM, 1, 0x0A);
});
test("auto HALT restart (0x7F02): RSM halts again after an SMI in HLT, unless the handler clears it", () => {
    cpu.in_hlt[0] = 1;
    cpu.smi();
    assert.ok(in_smm());
    assert.ok(!cpu.in_hlt[0], "the handler runs");
    assert.equal(ram32(0xAFF00), 0x00010000, "auto HALT restart set, I/O instruction restart (0x7F00) clear");
    step();
    assert.ok(!in_smm());
    assert.ok(cpu.in_hlt[0], "halted again");
    assert.equal(cpu.instruction_pointer[0], before.eip);
    cpu.smi();
    assert.equal(ram32(0xAFF00), 0x00010000);
    cpu.mem8[0xAFF02] = 0;
    step();
    assert.ok(!in_smm() && !cpu.in_hlt[0], "cleared by the handler: on after the HLT");
    cpu.smi();
    assert.equal(ram32(0xAFF00), 0, "an SMI outside HLT: clear");
    cpu.mem8[0xAFF02] = 1;
    step();
    assert.ok(!in_smm() && !cpu.in_hlt[0], "set by the handler without HLT: ignored");
    assert.equal(cpu.instruction_pointer[0], before.eip);
});
cpu.mem8.set(saved_handler, 0xA8000);

pci().config_write(0, MCH_ESMRAMC, 1, 0x39);
const state = await emulator.save_state();
pci().config_write(0, MCH_SMRAM, 1, 0x4A);
pci().config_write(0, MCH_ESMRAMC, 1, 0x38);
state32(STATE_OFFSETS.smbase)[0] = 0x30000;
await emulator.restore_state(state);
test("snapshot: SMBASE, SMRAM closed and TSEG (the MCH's SMRAM controls)", () => {
    assert.equal(smbase(), 0xA0000);
    assert.equal(pci().config_read(0, MCH_SMRAM, 1), 0x0A);
    assert.notEqual(cpu.read32s(0xAFEFC) >>> 0, 0x00020000, "closed again");
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0x39);
    assert.equal(cpu.read32s(TOP - (1 << 20)) >>> 0, 0xFFFFFFFF, "TSEG");
});

test("D_LCK: D_OPEN, G_SMRAME, D_LCK and ESMRAMC locked until a reset", () => {
    pci().config_write(0, MCH_SMRAM, 1, 0x1A);
    pci().config_write(0, MCH_SMRAM, 1, 0x42);
    assert.equal(pci().config_read(0, MCH_SMRAM, 1), 0x1A, "locked: G_SMRAME stays, D_OPEN stays clear");
    assert.notEqual(cpu.read32s(0xAFEFC) >>> 0, 0x00020000);
    pci().config_write(0, MCH_ESMRAMC, 1, 0x38);
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0x39, "ESMRAMC");
    assert.equal(cpu.read32s(TOP - (1 << 20)) >>> 0, 0xFFFFFFFF, "TSEG stays");
    cpu.devices.q35.reset();
    assert.equal(pci().config_read(0, MCH_SMRAM, 1), 0x02, "a reset unlocks it");
    assert.equal(pci().config_read(0, MCH_ESMRAMC, 1), 0x38);
    assert.equal(cpu.read32s(TOP - (1 << 20)) >>> 0, 0xCAFEF0A5, "no TSEG");
});

test("GEN_PMCON_1.SMI_LOCK: set until a reset; under it SMI_EN.GBL_SMI_EN does not clear", () => {
    // (the LPC bridge 00:1f.0; SMI_EN at PMBASE + 0x30: OVMF's SmmControl2Dxe checks this)
    const LPC = 0x1F << 3, GEN_PMCON_1 = 0xA0, SMI_LOCK = 0x10;
    // (the PM block decoded at SeaBIOS's PMBASE: a reset turns it off)
    const decode = () => { pci().config_write(LPC, 0x40, 4, 0x601); pci().config_write(LPC, 0x44, 1, 0x80); };
    decode();
    const smi_en_port = 0x600 + 0x30;
    const smi_en = () => cpu.io.port_read32(smi_en_port) >>> 0;
    const before = smi_en();
    cpu.io.port_write32(smi_en_port, before & ~1);
    assert.equal(smi_en() & 1, 0, "without the lock GBL_SMI_EN clears");
    cpu.io.port_write32(smi_en_port, before | 1);
    pci().config_write(LPC, GEN_PMCON_1, 2, SMI_LOCK);
    cpu.io.port_write32(smi_en_port, (before | 1) & ~(1 | 1 << 5));
    assert.equal(smi_en() & 1, 1, "GBL_SMI_EN stays");
    assert.equal(smi_en() & 1 << 5, 0, "the other bits are written (APMC_EN)");
    pci().config_write(LPC, GEN_PMCON_1, 2, 0);
    assert.equal(pci().config_read(LPC, GEN_PMCON_1, 2) & SMI_LOCK, SMI_LOCK, "SMI_LOCK stays");
    cpu.devices.q35.reset();
    assert.equal(pci().config_read(LPC, GEN_PMCON_1, 2) & SMI_LOCK, 0, "a reset clears it");
    decode();
    cpu.io.port_write32(smi_en_port, before & ~1);
    assert.equal(smi_en() & 1, 0, "and GBL_SMI_EN clears again");
    cpu.io.port_write32(smi_en_port, before);
});

emulator.destroy();

// The x86-64 profile: QEMU's 64-bit save area (revision 0x20064), which
// SeaBIOS's handler reads and edits as well
emulator = await boot({ cpu_type: "x86_64" });
cpu = emulator.v86.cpu;
test("x86-64: SeaBIOS's SMM setup and call32_smm with the 64-bit save area", () => {
    const area = 0xA8000;
    assert.equal(smbase(), 0xA0000, "relocated");
    assert.equal(ram32(area + 0x7EFC), 0x00020064, "revision: SMBASE relocation, 64-bit layout");
    assert.equal(ram32(area + 0x7F00), 0xA0000, "SMBASE");
    assert.equal(ram32(area + 0x7F58) & 1, 0, "CR0: back to real mode");
    assert.equal(ram32(area + 0x7E10) & 0xFFFF, 0xF000, "CS selector");
    assert.equal(ram64(area + 0x7E18), 0xF0000n, "CS base");
    assert.equal(ram64(area + 0x7ED0), 0n, "EFER");
});
cpu.mem8.set([0x0F, 0xAA], 0xA8000);
const wide = { rbx: 0x0123456789ABCDEFn, r9: 0xFEDCBA9876543210n, eip: cpu.instruction_pointer[0], cs_base: cpu.segment_offsets[1],
    eflags: cpu.get_eflags(), ds: cpu.sreg[3] };
const gpr_high = new Uint32Array(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.x64_gpr_hi, 16);
const gpr_ext = new Uint32Array(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.x64_gpr_ext_lo, 8);
cpu.reg32[3] = Number(wide.rbx & 0xFFFFFFFFn);
gpr_high[3] = Number(wide.rbx >> 32n);
gpr_ext[1] = Number(wide.r9 & 0xFFFFFFFFn);
gpr_high[9] = Number(wide.r9 >> 32n);
test("x86-64: an SMI saves the full registers in the 64-bit layout", () => {
    cpu.smi();
    assert.ok(in_smm());
    const area = 0xA8000;
    assert.equal(ram32(area + 0x7EFC), 0x00020064);
    assert.equal(ram64(area + 0x7FE0), wide.rbx, "RBX");
    assert.equal(ram64(area + 0x7FF8 - 9 * 8), wide.r9, "R9");
    assert.equal(ram64(area + 0x7F78), BigInt(wide.eip - wide.cs_base >>> 0), "RIP");
    assert.equal(ram32(area + 0x7F70), wide.eflags >>> 0, "RFLAGS");
    assert.equal(ram32(area + 0x7E30) & 0xFFFF, wide.ds, "DS selector");
    // the handler changes the low byte of RBX's high half
    cpu.mem8[area + 0x7FE4] = 0x5A;
});
step();
test("x86-64: RSM restores the 64-bit registers (and what the handler changed)", () => {
    assert.ok(!in_smm());
    assert.equal(cpu.instruction_pointer[0], wide.eip);
    assert.equal(cpu.get_eflags(), wide.eflags);
    assert.equal(cpu.reg32[3] >>> 0, Number(wide.rbx & 0xFFFFFFFFn));
    assert.equal(gpr_high[3] >>> 0, Number(wide.rbx >> 32n) & ~0xFF | 0x5A, "RBX's high half, as the handler left it");
    assert.equal(gpr_ext[1] >>> 0, Number(wide.r9 & 0xFFFFFFFFn));
    assert.equal(gpr_high[9] >>> 0, Number(wide.r9 >> 32n), "R9's high half");
    assert.equal(cpu.sreg[3], wide.ds);
});
test("x86-64: the auto HALT restart byte (0x7EC9)", () => {
    cpu.in_hlt[0] = 1;
    cpu.smi();
    assert.ok(in_smm());
    assert.equal(cpu.mem8[0xA8000 + 0x7EC9], 1, "auto HALT restart");
    assert.equal(cpu.mem8[0xA8000 + 0x7EC8], 0, "I/O instruction restart");
    step();
    assert.ok(!in_smm() && cpu.in_hlt[0], "halted again");
    cpu.in_hlt[0] = 0;
});
emulator.destroy();

// XSAVE (docs/simd-xsave-plan.md 6.1): an SMI clears CR4, so the handler runs
// with CR4.OSXSAVE 0; XCR0 is not in the save area and stays; RSM restores a
// valid CR4 and shuts down for a reserved bit
emulator = await boot({ cpu_features: ["XSAVE"] });
cpu = emulator.v86.cpu;
{
    const xcr0 = new Uint32Array(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.xcr0, 2);
    cpu.cr[4] |= 1 << 18;
    xcr0.set([3, 0]);
    cpu.mem8.set([0x0F, 0xAA], 0xA8000);
    test("XSAVE: in SMM CR4.OSXSAVE is 0, XCR0 stays", () => {
        cpu.smi();
        assert.ok(in_smm());
        assert.equal(cpu.cr[4], 0);
        assert.deepEqual(Array.from(xcr0), [3, 0]);
    });
    step();
    test("XSAVE: RSM restores CR4.OSXSAVE; XCR0 stays", () => {
        assert.ok(!in_smm());
        assert.equal(cpu.cr[4] & 1 << 18, 1 << 18);
        assert.deepEqual(Array.from(xcr0), [3, 0]);
    });
    test("RSM to a reserved CR4 bit: shutdown (here a board reset)", () => {
        const resets = cpu.last_reset ? cpu.last_reset.count : 0;
        cpu.smi();
        assert.ok(in_smm());
        cpu.mem8[0xAFF14 + 2] |= 1 << 6; // CR4 in the 32-bit save area: bit 22
        step();
        assert.equal(cpu.last_reset && cpu.last_reset.count, resets + 1);
        assert.equal(cpu.last_reset.reason, "triple-fault");
    });
}
emulator.destroy();

console.log((failed ? "FAIL" : "PASS") + ": " + passed + " SMM tests passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/devices/tcp_endpoint.mjs                                                           0000644 0000000 0000000 00000017714 00000000000 015663  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A TCP endpoint for network card tests, at the fake network's router
// (192.168.86.1, 52:54:00:01:02:03): it takes the guest's connections to its
// ports from the frames the card sends and answers through the card's
// receive path. Unlike the fake network's own TCP (one segment in flight) it
// keeps a window of segments in flight, so that a transfer measures the card
// and the guest rather than the round trips. In-order delivery only:
// segments after a gap are dropped and acknowledged as duplicates, the
// sender goes back to the first unacknowledged byte on three duplicates or
// a timeout.

import crypto from "node:crypto";

const ROUTER_MAC = [0x52, 0x54, 0x00, 0x01, 0x02, 0x03];
const ROUTER_IP = [192, 168, 86, 1];
const MSS = 1460;
const WINDOW = 65535;
const IN_FLIGHT = 48 * 1024;

const FIN = 1, SYN = 2, RST = 4, PSH = 8, ACK = 16;

function sum16(bytes, start, end, sum = 0)
{
    for(let i = start; i < end; i += 2) sum += bytes[i] << 8 | (i + 1 < end ? bytes[i + 1] : 0);
    while(sum > 0xFFFF) sum = (sum & 0xFFFF) + Math.floor(sum / 0x10000);
    return sum;
}

/**
 * Call it when the emulator is ready ("emulator-ready"): the network
 * adapter (the fake network's frames) exists from then on
 * @param {Object} emulator a V86
 * @param {Object<number, {serve?: function(Uint8Array): Uint8Array, sink?: function(Buffer)}>} ports
 *     serve: the response to the first data (the endpoint sends it and closes);
 *     sink: all data until the guest's FIN
 * @return {{stop: function()}}
 */
export function tcp_endpoint(emulator, ports)
{
    const connections = new Map();
    const adapter = emulator.network_adapter;
    const fake_send = adapter && adapter.send.bind(adapter);

    function deliver(frame)
    {
        emulator.bus.send("net0-receive", frame);
    }

    function segment(c, flags, payload = new Uint8Array(0), seq = c.snd_nxt, options = [])
    {
        const tcp_length = 20 + options.length + payload.length;
        const f = new Uint8Array(14 + 20 + tcp_length);
        f.set(c.guest_mac, 0); f.set(ROUTER_MAC, 6); f[12] = 0x08;
        const ip = 14;
        f[ip] = 0x45; f[ip + 2] = 20 + tcp_length >> 8; f[ip + 3] = 20 + tcp_length; f[ip + 6] = 0x40;
        f[ip + 8] = 64; f[ip + 9] = 6; f.set(ROUTER_IP, ip + 12); f.set(c.guest_ip, ip + 16);
        const ip_sum = ~sum16(f, ip, ip + 20) & 0xFFFF;
        f[ip + 10] = ip_sum >> 8; f[ip + 11] = ip_sum;
        const t = ip + 20;
        f[t] = c.port >> 8; f[t + 1] = c.port; f[t + 2] = c.guest_port >> 8; f[t + 3] = c.guest_port;
        new DataView(f.buffer).setUint32(t + 4, seq >>> 0);
        new DataView(f.buffer).setUint32(t + 8, c.rcv_nxt >>> 0);
        f[t + 12] = (20 + options.length) / 4 << 4; f[t + 13] = flags;
        f[t + 14] = WINDOW >> 8; f[t + 15] = WINDOW & 0xFF;
        f.set(options, t + 20);
        f.set(payload, t + 20 + options.length);
        const pseudo = sum16(f, ip + 12, ip + 20) + 6 + tcp_length;
        const tcp_sum = ~sum16(f, t, t + tcp_length, pseudo) & 0xFFFF;
        f[t + 16] = tcp_sum >> 8; f[t + 17] = tcp_sum;
        deliver(f);
    }

    /** Send what the window allows */
    function pump(c)
    {
        if(!c.out) return;
        const window = Math.min(c.guest_window, IN_FLIGHT);
        while(c.snd_nxt - c.snd_una < window && c.snd_nxt - c.data_seq < c.out.length)
        {
            const offset = c.snd_nxt - c.data_seq;
            const length = Math.min(MSS, c.out.length - offset, window - (c.snd_nxt - c.snd_una));
            if(length <= 0) break;
            segment(c, ACK | (offset + length === c.out.length ? PSH : 0), c.out.subarray(offset, offset + length));
            c.snd_nxt += length;
        }
        if(c.snd_una - c.data_seq === c.out.length && !c.fin_sent)
        {
            c.fin_sent = true;
            segment(c, FIN | ACK);
            c.snd_nxt += 1;
        }
    }

    function on_frame(f)
    {
        if(f.length < 54 || f[12] !== 0x08 || f[13] !== 0 || f[23] !== 6) return false;
        if(f[30] !== ROUTER_IP[0] || f[31] !== ROUTER_IP[1] || f[32] !== ROUTER_IP[2] || f[33] !== ROUTER_IP[3]) return false;
        const ip = 14, t = ip + ((f[ip] & 0xF) << 2);
        const port = f[t + 2] << 8 | f[t + 3];
        if(!ports[port]) return false;
        const view = new DataView(f.buffer, f.byteOffset, f.byteLength);
        const guest_port = f[t] << 8 | f[t + 1];
        const seq = view.getUint32(t + 4), ack = view.getUint32(t + 8);
        const flags = f[t + 13];
        const total = f[ip + 2] << 8 | f[ip + 3];
        const payload = f.subarray(t + (f[t + 12] >> 4 << 2), ip + total);
        const key = port + ":" + guest_port;
        let c = connections.get(key);

        if(flags & SYN)
        {
            c = {
                port, guest_port, guest_mac: f.slice(6, 12), guest_ip: f.slice(26, 30),
                rcv_nxt: seq + 1 >>> 0, snd_una: 0, snd_nxt: 0, data_seq: 0, guest_window: 0,
                out: null, received: [], fin_sent: false, guest_fin: false, dup: 0, last_progress: Date.now(), handler: ports[port],
            };
            const isn = crypto.randomBytes(4).readUInt32BE(0) >>> 1;
            c.snd_una = c.snd_nxt = isn;
            c.data_seq = isn + 1;
            connections.set(key, c);
            // (no window scaling: the guest's window is what its segments say)
            segment(c, SYN | ACK, undefined, isn, [2, 4, MSS >> 8, MSS & 0xFF]);
            c.snd_nxt = isn + 1;
            c.snd_una = isn;
            return true;
        }
        if(!c) return true;
        if(flags & RST) { connections.delete(key); return true; }

        c.guest_window = view.getUint16(t + 14);
        if(flags & ACK)
        {
            // relative to our first sequence number: no wrap within a test
            const acked = ack - c.snd_una | 0;
            if(acked > 0 && (ack - c.snd_nxt | 0) <= 0)
            {
                c.snd_una = ack >>> 0;
                c.dup = 0;
                c.last_progress = Date.now();
            }
            else if(acked === 0 && c.snd_nxt !== c.snd_una && !payload.length && ++c.dup === 3)
            {
                // three duplicates: from the first unacknowledged byte again
                c.snd_nxt = c.snd_una;
                c.dup = 0;
            }
        }
        if(payload.length)
        {
            if(seq === c.rcv_nxt)
            {
                c.rcv_nxt = c.rcv_nxt + payload.length >>> 0;
                if(c.handler.sink) c.received.push(Buffer.from(payload));
                else if(c.handler.serve && !c.out)
                {
                    c.out = c.handler.serve(payload);
                }
            }
            segment(c, ACK);
        }
        if(flags & FIN && !c.guest_fin && seq + payload.length >>> 0 === c.rcv_nxt)
        {
            c.guest_fin = true;
            c.rcv_nxt = c.rcv_nxt + 1 >>> 0;
            if(c.handler.sink)
            {
                c.out = new Uint8Array(0);
                c.handler.sink(Buffer.concat(c.received));
            }
            segment(c, ACK);
        }
        pump(c);
        if(c.fin_sent && c.snd_una === c.snd_nxt && c.guest_fin) connections.delete(key);
        return true;
    }

    // the card's frames: ours, or the fake network's
    if(adapter) adapter.send = frame => { if(!on_frame(frame)) fake_send(frame); };
    else emulator.add_listener("net0-send", on_frame);

    // a lost segment without three duplicates (the end of a transfer)
    const timer = setInterval(() => {
        for(const c of connections.values())
        {
            if(c.out && c.snd_nxt !== c.snd_una && Date.now() - c.last_progress > 300)
            {
                c.snd_nxt = c.snd_una;
                if(c.fin_sent && c.snd_una - c.data_seq === c.out.length) c.fin_sent = false;
                c.last_progress = Date.now();
                pump(c);
            }
        }
    }, 100);
    // (it does not keep the process alive)
    timer.unref();

    return {
        stop()
        {
            clearInterval(timer);
            if(adapter) adapter.send = fake_send;
        },
    };
}
                                                    source/v64/tests/devices/testfs.json                                                                0000644 0000000 0000000 00000000437 00000000000 014657  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {"fsroot":[["foo",4,1531432001,33188,1000,1000,"7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"],["dir",4096,1532940393,16877,1000,1000,[["bar",7,1532940393,33188,1000,1000,"5d70f436aa013f4f1d5af4a5e8149b479c813ab4ceea0bcf8b01f78eac84fd25"]]]],"version":3,"size":4107}
                                                                                                                                                                                                                                 source/v64/tests/devices/testfs/5d70f436aa013f4f1d5af4a5e8149b479c813ab4ceea0bcf8b01f78eac84fd25    0000644 0000000 0000000 00000000007 00000000000 025131  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       foobaz
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/devices/testfs/7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730    0000644 0000000 0000000 00000000004 00000000000 024563  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       bar
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/devices/usb.js                                                                     0000755 0000000 0000000 00000036505 00000000000 013613  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// USB (usb: { controller: "uhci", tablet: true }, the plugin of src/usb/):
// the UHCI controller driven through its I/O registers and a schedule in
// guest memory (frame list, queue heads, transfer descriptors), no guest
// code; the test moves the machine clock (docs/modern-pc-devices-plan.md U1).
// PCI identity on i440FX and Q35, registers, port reset and enable, frames
// at 1 ms, control transfers (descriptors, SET_ADDRESS, SET_CONFIGURATION,
// HID requests), STALL, timeouts, short packets, the interrupt endpoint's
// reports from the page's pointer, NAK, the routing of the pointer away from
// PS/2, snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

let host = 1000;
const options = machine_type => ({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 32 * 1024 * 1024,
    machine_type,
    acpi: machine_type === "q35",
    usb: { controller: "uhci", tablet: true },
    net_device: { type: "none" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
async function machine(machine_type)
{
    const emulator = new V86(options(machine_type));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume();
    return emulator;
}

let failed = 0, passed = 0;
function test(name, f)
{
    try
    {
        f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const emulator = await machine("i440fx");
const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
// (PIIX3's function 2 on i440FX, ICH9's 00:1d.0 on Q35)
const UHCI = 0x01 << 3 | 2, ICH9_UHCI = 0x1D << 3;
const IO = 0xC000;

const r16 = offset => cpu.io.port_read16(IO + offset);
const r32 = offset => cpu.io.port_read32(IO + offset) >>> 0;
const w16 = (offset, value) => cpu.io.port_write16(IO + offset, value);
const w32 = (offset, value) => cpu.io.port_write32(IO + offset, value | 0);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const irq = () => !!pci.intx_levels[UHCI];

const USBCMD = 0x00, USBSTS = 0x02, USBINTR = 0x04, FRNUM = 0x06, FLBASEADD = 0x08, PORTSC1 = 0x10, PORTSC2 = 0x12;
const RS = 1, HCRESET = 2, HALTED = 1 << 5, USBINT = 1, ERROR = 2;
const CCS = 1, CSC = 2, PE = 4, PR = 1 << 9;
const T = 1, Q = 2, VF = 4;
const ACTIVE = 1 << 23, IOC = 1 << 24, SPD = 1 << 29, STALLED = 1 << 22, CRC_TIMEOUT = 1 << 18, ERRORS3 = 3 << 27;
const PID_SETUP = 0x2D, PID_IN = 0x69, PID_OUT = 0xE1;

/** Move the machine clock on and run the machine's timers */
function advance(ms)
{
    for(let i = 0; i < ms; i++)
    {
        host += 1;
        cpu.run_hardware_timers(false, cpu.clock.now());
    }
}

// the schedule: every frame list entry to one queue head
const FRAME_LIST = 0x100000, QH = 0x101000, TDS = 0x102000, BUFFERS = 0x103000;
let tablet_active = null;
emulator.add_listener("usb-tablet-active", value => { tablet_active = value; });

const token = (pid, address, endpoint, toggle, length) => pid | address << 8 | endpoint << 15 | toggle << 19 | (length - 1 & 0x7FF) << 21;
/** Write TDs (each [control, token, buffer]) linked depth first; the queue head's element the first */
function queue(tds)
{
    tds.forEach(([control, tok, buffer], i) =>
    {
        const at = TDS + 32 * i;
        put32(at, i + 1 < tds.length ? TDS + 32 * (i + 1) | VF : T);
        put32(at + 4, control);
        put32(at + 8, tok);
        put32(at + 12, buffer);
    });
    put32(QH + 4, TDS);
}
const td_control = i => u32(TDS + 32 * i + 4);

/**
 * A control transfer: SETUP, the data stage (IN packets of 8 bytes), the status stage
 * @return {{data: Uint8Array, status: number}} the data read, the last TD's control
 */
function control(address, setup, length = setup[6] | setup[7] << 8, out = null)
{
    mem.set(setup, BUFFERS);
    const tds = [[ACTIVE | ERRORS3, token(PID_SETUP, address, 0, 0, 8), BUFFERS]];
    const into = !(setup[0] & 0x80);
    let toggle = 1;
    for(let done = 0; done < length; done += 8)
    {
        const n = Math.min(8, length - done);
        if(out) mem.set(out.subarray(done, done + n), BUFFERS + 0x100 + done);
        tds.push([ACTIVE | ERRORS3, token(into ? PID_OUT : PID_IN, address, 0, toggle, n), BUFFERS + 0x100 + done]);
        toggle ^= 1;
    }
    tds.push([ACTIVE | ERRORS3 | IOC, token(into ? PID_IN : PID_OUT, address, 0, 1, 0), 0]);
    queue(tds);
    advance(3);
    let read = 0;
    for(let i = 1; i < tds.length - 1; i++)
    {
        const c = td_control(i);
        if(c & ACTIVE || c & STALLED) break;
        read += (c + 1) & 0x7FF;
    }
    return { data: mem.slice(BUFFERS + 0x100, BUFFERS + 0x100 + read), status: td_control(tds.length - 1), first: td_control(0), tds: tds.length };
}
const setup = (type, request, value, index, length) => Uint8Array.of(type, request, value & 0xFF, value >> 8, index & 0xFF, index >> 8, length & 0xFF, length >> 8);

// --- PCI and registers --------------------------------------------------------

test("PCI: PIIX3 UHCI (8086:7020) at 00:01.2, class 0C/03/00, BAR4 32 I/O ports, SBRN 1.0, INTD", () => {
    const space = pci.space_bytes(UHCI);
    const word = o => space[o] | space[o + 1] << 8;
    assert.equal(word(0), 0x8086);
    assert.equal(word(2), 0x7020);
    assert.deepEqual([space[0x0B], space[0x0A], space[0x09]], [0x0C, 0x03, 0x00]);
    assert.equal(space[0x60], 0x10);
    assert.equal(space[0x3D], 4);
    pci.config_write(UHCI, 0x20, 4, -1);
    assert.equal((space[0x20] | space[0x21] << 8 | space[0x22] << 16 | space[0x23] << 24) >>> 0, 0xFFFFFFE1);
    pci.config_write(UHCI, 0x20, 4, IO | 1);
    pci.config_write(UHCI, 0x04, 2, 0x0005);
});

test("registers after reset: halted, the tablet on port 1 (connected, changed), bit 7 of PORTSC reads 1", () => {
    w16(USBCMD, HCRESET);
    assert.equal(r16(USBCMD) & HCRESET, 0, "self-clearing");
    assert.equal(r16(USBSTS) & HALTED, HALTED);
    assert.equal(r16(PORTSC1) & 0x8B, 0x80 | CCS | CSC, "port 1: the tablet");
    assert.equal(r16(PORTSC2) & 0x8F, 0x80, "port 2: empty");
    assert.equal(cpu.io.port_read8(IO + 0x0C), 64, "SOFMOD");
});

test("frames: FRNUM counts milliseconds while running, not while halted; HCHalted follows RS", () => {
    for(let i = 0; i < 1024; i++) put32(FRAME_LIST + 4 * i, QH | Q);
    put32(QH, T);
    put32(QH + 4, T);
    w32(FLBASEADD, FRAME_LIST);
    w16(FRNUM, 0x3FE);
    w16(USBCMD, RS);
    assert.equal(r16(USBSTS) & HALTED, 0);
    advance(5);
    assert.equal(r16(FRNUM), 0x403, "five frames, past the frame list's end");
    w16(USBCMD, 0);
    assert.equal(r16(USBSTS) & HALTED, HALTED);
    advance(5);
    assert.equal(r16(FRNUM), 0x403);
    w16(USBCMD, RS);
});

test("port reset and enable: CSC cleared by writing it, PR resets the device, PE enables the port", () => {
    w16(PORTSC1, CSC);
    assert.equal(r16(PORTSC1) & CSC, 0);
    w16(PORTSC1, PR);
    assert.equal(r16(PORTSC1) & (PR | PE), PR);
    w16(PORTSC1, 0);
    w16(PORTSC1, PE);
    assert.equal(r16(PORTSC1) & (CCS | PE), CCS | PE);
});

let device_descriptor;
test("GET_DESCRIPTOR(device) at address 0: QEMU's tablet IDs, 8-byte packets; IOC: USBINT and INTD", () => {
    w16(USBINTR, 0xF);
    const r = control(0, setup(0x80, 6, 0x0100, 0, 18));
    device_descriptor = r.data;
    assert.equal(r.data.length, 18);
    assert.equal(r.data[1], 1);
    assert.equal(r.data[7], 8, "bMaxPacketSize0");
    assert.equal(r.data[8] | r.data[9] << 8, 0x0627);
    assert.equal(r.data[10] | r.data[11] << 8, 0x0001);
    assert.equal(r.status & ACTIVE, 0, "the status stage done");
    assert.equal(r16(USBSTS) & USBINT, USBINT);
    assert.ok(irq());
    w16(USBSTS, USBINT);
    assert.ok(!irq());
});

test("SET_ADDRESS: the device answers at its new address after the status stage, not at 0", () => {
    const r = control(0, setup(0x00, 5, 7, 0, 0));
    assert.equal(r.status & (ACTIVE | STALLED), 0);
    assert.deepEqual(control(7, setup(0x80, 6, 0x0100, 0, 18)).data, device_descriptor);
    mem.set(setup(0x80, 6, 0x0100, 0, 18), BUFFERS);
    queue([[ACTIVE | ERRORS3, token(PID_SETUP, 0, 0, 0, 8), BUFFERS]]);
    advance(1);
    assert.equal(td_control(0) & (ACTIVE | CRC_TIMEOUT | 3 << 27), ACTIVE | CRC_TIMEOUT | 2 << 27, "no answer at 0: a timeout, retried");
    advance(2);
    assert.equal(td_control(0) & (ACTIVE | CRC_TIMEOUT | 3 << 27), CRC_TIMEOUT, "three errors: retired");
    assert.equal(r16(USBSTS) & ERROR, ERROR);
    w16(USBSTS, 0xFF);
});

test("GET_DESCRIPTOR: the configuration (HID interface, interrupt IN endpoint), strings", () => {
    const config = control(7, setup(0x80, 6, 0x0200, 0, 34)).data;
    assert.equal(config.length, 34);
    assert.equal(config[2] | config[3] << 8, 34, "wTotalLength");
    assert.deepEqual(Array.from(config.subarray(9, 18)), [9, 4, 0, 0, 1, 3, 0, 0, 0], "interface: HID, not a boot device");
    assert.deepEqual(Array.from(config.subarray(18, 21)), [9, 0x21, 0x11]);
    assert.deepEqual(Array.from(config.subarray(27, 34)), [7, 5, 0x81, 3, 8, 0, 10], "endpoint 0x81, interrupt, 8 bytes, 10 ms");
    const name = control(7, setup(0x80, 6, 0x0302, 0x0409, 255), 255).data;
    assert.equal(new TextDecoder("utf-16le").decode(name.subarray(2)), "v86 USB Tablet");
});

test("a short packet: SPD stops the queue at it, USBINT for the short packet", () => {
    mem.set(setup(0x80, 6, 0x0100, 0, 18), BUFFERS);
    queue([[ACTIVE | ERRORS3, token(PID_SETUP, 7, 0, 0, 8), BUFFERS],
        [ACTIVE | ERRORS3 | SPD, token(PID_IN, 7, 0, 1, 64), BUFFERS + 0x100],
        [ACTIVE | ERRORS3, token(PID_OUT, 7, 0, 1, 0), 0]]);
    w16(USBSTS, 0xFF);
    advance(2);
    assert.equal(td_control(1) & 0x7FF, 7, "8 bytes (the first packet)");
    assert.equal(r16(USBSTS) & USBINT, USBINT);
    assert.equal(u32(QH + 4), TDS + 32 | VF, "the queue head still at the short TD");
    assert.equal(td_control(2) & ACTIVE, ACTIVE, "the status stage not done");
    w16(USBSTS, 0xFF);
});

test("STALL: an unknown descriptor (device qualifier: a full-speed device has none)", () => {
    const r = control(7, setup(0x80, 6, 0x0600, 0, 10));
    assert.equal(td_control(1) & (STALLED | ACTIVE), STALLED);
    assert.equal(r16(USBSTS) & ERROR, ERROR);
    w16(USBSTS, 0xFF);
    assert.equal(control(7, setup(0x80, 6, 0x0100, 0, 18)).data.length, 18, "the next SETUP goes on");
});

test("SET_CONFIGURATION: the tablet configured, announced as the pointer's device", () => {
    tablet_active = null;
    control(7, setup(0x00, 9, 1, 0, 0));
    assert.deepEqual(Array.from(control(7, setup(0x80, 8, 0, 0, 1)).data), [1]);
    assert.equal(tablet_active, true);
    const report = control(7, setup(0x81, 6, 0x2200, 0, 74), 74).data;
    assert.equal(report.length, 74, "the report descriptor");
    assert.deepEqual(Array.from(report.subarray(0, 4)), [0x05, 0x01, 0x09, 0x02]);
    control(7, setup(0x21, 0x0A, 0, 0, 0));
    assert.deepEqual(Array.from(control(7, setup(0xA1, 0x02, 0, 0, 1)).data), [0], "GET_IDLE");
});

/** The interrupt endpoint's TD: active again, polled for a frame */
function poll()
{
    queue([[ACTIVE | ERRORS3 | IOC, token(PID_IN, 7, 1, 0, 8), BUFFERS + 0x200]]);
    advance(1);
    const c = td_control(0);
    return c & ACTIVE ? null : mem.slice(BUFFERS + 0x200, BUFFERS + 0x200 + ((c + 1) & 0x7FF));
}
const view = bytes => ({ buttons: bytes[0], x: bytes[1] | bytes[2] << 8, y: bytes[3] | bytes[4] << 8, wheel: bytes[5] << 24 >> 24 });

test("the interrupt endpoint: a report after configuring, then NAK until the pointer moves", () => {
    const first = poll();
    assert.equal(first.length, 6);
    assert.deepEqual(view(first), { buttons: 0, x: 0x3FFF, y: 0x3FFF, wheel: 0 });
    assert.equal(poll(), null, "nothing new: NAK, the TD still active");
    emulator.bus.send("mouse-absolute", [100, 50, 400, 200]);
    // (the middle of the page's pixel)
    assert.deepEqual(view(poll()), { buttons: 0, x: Math.round(100.5 / 400 * 32767), y: Math.round(50.5 / 200 * 32767), wheel: 0 });
    emulator.bus.send("mouse-click", [true, false, true]);
    assert.equal(view(poll()).buttons, 3, "left and right");
    emulator.bus.send("mouse-wheel", [1, 0]);
    const r = view(poll());
    assert.deepEqual([r.buttons, r.wheel], [3, 1]);
    emulator.bus.send("mouse-click", [false, false, false]);
    emulator.bus.send("mouse-absolute", [400, 200, 400, 200]);
    assert.deepEqual(view(poll()), { buttons: 0, x: 32767, y: 32767, wheel: 0 });
});

test("the pointer: PS/2 leaves it to the tablet; with the pointer locked, PS/2 has it", () => {
    const ps2 = cpu.devices.ps2;
    assert.equal(ps2.pointer_elsewhere, true);
    emulator.bus.send("mouse-pointer-lock", true);
    assert.equal(ps2.pointer_elsewhere, false);
    poll();
    emulator.bus.send("mouse-absolute", [0, 0, 400, 200]);
    assert.equal(poll(), null, "locked: the tablet does not move");
    emulator.bus.send("mouse-pointer-lock", false);
    assert.equal(ps2.pointer_elsewhere, true);
});

{
    const state = await emulator.save_state();
    control(7, setup(0x00, 9, 0, 0, 0));
    tablet_active = null;
    await emulator.restore_state(state);
    test("snapshot: the controller, the port, the configured tablet at its address (announced again)", () => {
        assert.equal(r16(PORTSC1) & (CCS | PE), CCS | PE);
        assert.equal(r16(USBCMD) & RS, RS);
        assert.equal(tablet_active, true);
        assert.deepEqual(Array.from(control(7, setup(0x80, 8, 0, 0, 1)).data), [1]);
        emulator.bus.send("mouse-absolute", [200, 100, 400, 200]);
        assert.deepEqual(view(poll()).x, Math.round(200.5 / 400 * 32767));
    });
}

{
    tablet_active = null;
    await emulator.usb_plug("tablet", false);
    test("usb_plug: out of its port, the port says so (CCS, CSC, disabled), the pointer back to PS/2", () => {
        assert.equal(r16(PORTSC1) & (CCS | CSC | PE), CSC);
        assert.equal(tablet_active, false);
        assert.equal(cpu.devices.ps2.pointer_elsewhere, false);
        assert.equal(control(7, setup(0x80, 6, 0x0100, 0, 18)).data.length, 0, "no answer");
    });
    await emulator.usb_plug("tablet", true);
    test("usb_plug: back in, enumerated again from address 0", () => {
        assert.equal(r16(PORTSC1) & (CCS | CSC), CCS | CSC);
        w16(PORTSC1, CSC | PR);
        w16(PORTSC1, 0);
        w16(PORTSC1, PE);
        assert.equal(control(0, setup(0x80, 6, 0x0100, 0, 18)).data.length, 18);
    });
    let error;
    await emulator.usb_plug("disk", true).catch(e => { error = e; });
    test("usb_plug: a device the machine does not have", () => assert.match(String(error), /no USB device "disk"/));
}

{
    const q35 = await machine("q35");
    const space = q35.v86.cpu.devices.pci.space_bytes(ICH9_UHCI);
    test("Q35: ICH9's UHCI (8086:2934) at 00:1d.0, INTA", () => {
        assert.equal(space[2] | space[3] << 8, 0x2934);
        assert.equal(space[0x3D], 1);
    });
    await q35.destroy();
}

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                           source/v64/tests/devices/usb_ehci.js                                                                0000755 0000000 0000000 00000050763 00000000000 014605  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// EHCI (usb.controller "ehci", src/usb/ehci.js, docs/usb.md): ICH9's EHCI1
// with its three UHCI companions, driven through the registers and the
// schedules in guest memory, no guest code; the test moves the machine
// clock (docs/modern-pc-devices-plan.md U3). The PCI functions and the
// legacy support handoff, the capability registers, the ports' owners
// (CONFIGFLAG, Port Owner: the high-speed USB disk stays, the full-speed
// tablet goes to its companion), the asynchronous schedule (control
// transfers, BOT on bulk endpoints of 512 bytes, qTDs over pages, short
// packets and the alternate next qTD, STALL, no device, NAK), Interrupt on
// Async Advance, FRINDEX and the periodic schedule, hot plug, snapshots,
// HCRESET, the i440FX place.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SECTORS = 8192;
const pattern = i => (i * 11 + (i >> 9)) & 0xFF;
const image = new Uint8Array(SECTORS * 512).map((_, i) => pattern(i));

let host = 1000;
const options = machine_type => ({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 64 * 1024 * 1024,
    machine_type,
    acpi: machine_type === "q35",
    usb: { controller: "ehci", tablet: true, mass_storage: [{ id: "stick", image: { buffer: image.buffer } }] },
    net_device: { type: "none" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
async function machine(machine_type)
{
    const emulator = new V86(options(machine_type));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume();
    return emulator;
}

let failed = 0, passed = 0;
async function test(name, f)
{
    try
    {
        await f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const emulator = await machine("q35");
const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const EHCI = 0x1D << 3 | 7, UHCI = [0x1D << 3, 0x1D << 3 | 1, 0x1D << 3 | 2];
const BAR = 0xC0000000, IO = 0xC000;

const r32 = offset => cpu.mmap_read32(BAR + offset) >>> 0;
const r8 = offset => cpu.mmap_read8(BAR + offset);
const w32 = (offset, value) => cpu.mmap_write32(BAR + offset, value | 0);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const uhci_r16 = offset => cpu.io.port_read16(IO + offset);
const uhci_w16 = (offset, value) => cpu.io.port_write16(IO + offset, value);

// operational registers (after CAPLENGTH 0x20)
const USBCMD = 0x20, USBSTS = 0x24, USBINTR = 0x28, FRINDEX = 0x2C, PERIODICLISTBASE = 0x34, ASYNCLISTADDR = 0x38,
    CONFIGFLAG = 0x60, PORTSC = port => 0x64 + 4 * port;
const RS = 1, HCRESET = 2, PSE = 1 << 4, ASE = 1 << 5, IAAD = 1 << 6;
const USBINT = 1, USBERRINT = 2, PCD = 4, IAA = 1 << 5, HALTED = 1 << 12, PSS = 1 << 14, ASS = 1 << 15;
const CCS = 1, CSC = 2, PED = 4, PEDC = 8, PR = 1 << 8, PP = 1 << 12, PO = 1 << 13, LS = 3 << 10;
const UHCI_PORTSC1 = 0x10, UHCI_CCS = 1, UHCI_CSC = 2;
const TOKEN_ACTIVE = 1 << 7, TOKEN_HALTED = 1 << 6, TOKEN_XACTERR = 1 << 3, TOKEN_IOC = 1 << 15;
const OUT = 0, IN = 1, SETUP = 2;

/** Move the machine clock on and run the machine's timers */
function advance(ms)
{
    for(let i = 0; i < ms; i++)
    {
        host += 1;
        cpu.run_hardware_timers(false, cpu.clock.now());
    }
}

// --- PCI and the capability registers ----------------------------------------------

await test("PCI: UHCI companions 2934/2935/2936 at 00:1d.0-2 (INTA-C, function 0 multifunction), EHCI 293A at 00:1d.7 (0C/03/20, INTD, BAR0 4 KiB of memory, SBRN 2.0)", () => {
    [0x2934, 0x2935, 0x2936].forEach((device, i) => {
        const space = pci.space_bytes(UHCI[i]);
        assert.equal(space[2] | space[3] << 8, device);
        assert.equal(space[0x3D], i + 1);
    });
    assert.equal(pci.space_bytes(UHCI[0])[0x0E] & 0x80, 0x80);
    const space = pci.space_bytes(EHCI);
    assert.equal(space[2] | space[3] << 8, 0x293A);
    assert.deepEqual([space[0x0B], space[0x0A], space[0x09]], [0x0C, 0x03, 0x20]);
    assert.equal(space[0x3D], 4);
    assert.equal(space[0x60], 0x20);
    pci.config_write(EHCI, 0x10, 4, -1);
    assert.equal((space[0x10] | space[0x11] << 8 | space[0x12] << 16 | space[0x13] << 24) >>> 0, 0xFFFFF000);
    pci.config_write(EHCI, 0x10, 4, BAR);
    pci.config_write(EHCI, 0x04, 2, 0x0006);
    pci.config_write(UHCI[0], 0x20, 4, IO | 1);
    pci.config_write(UHCI[0], 0x04, 2, 0x0005);
});

await test("legacy support: USBLEGSUP at 0x68 (EECP); the OS taking ownership gets it at once", () => {
    const space = pci.space_bytes(EHCI);
    assert.equal(space[0x68], 0x01);
    pci.config_write(EHCI, 0x68, 4, 1 << 16);
    assert.equal(space[0x6A] & 1, 1, "the BIOS owns it");
    pci.config_write(EHCI, 0x68, 4, 1 << 16 | 1 << 24);
    assert.deepEqual([space[0x6A] & 1, space[0x6B] & 1], [0, 1]);
});

await test("capability registers: CAPLENGTH 0x20, HCIVERSION 1.0, 6 ports, 2 per companion, 3 companions; 64-bit, EECP 0x68", () => {
    assert.equal(r8(0), 0x20);
    assert.equal(r32(0) >>> 16, 0x0100);
    assert.equal(r32(4) & 0xFFFF, 6 | 2 << 8 | 3 << 12);
    assert.equal(r32(8) & 1, 1);
    assert.equal(r32(8) >> 8 & 0xFF, 0x68);
    assert.equal(r32(USBSTS) & HALTED, HALTED);
});

await test("before CONFIGFLAG every port is a companion's: the tablet and the disk on 00:1d.0's two ports", () => {
    assert.equal(uhci_r16(UHCI_PORTSC1) & UHCI_CCS, UHCI_CCS);
    assert.equal(uhci_r16(UHCI_PORTSC1 + 2) & UHCI_CCS, UHCI_CCS);
    assert.equal(r32(PORTSC(0)) & (CCS | PO | PP), PO | PP);
});

await test("CONFIGFLAG: the ports to the EHCI (the companion sees its devices leave), connected with J, a port change", () => {
    w32(USBINTR, USBINT | USBERRINT | PCD | IAA);
    w32(CONFIGFLAG, 1);
    assert.equal(uhci_r16(UHCI_PORTSC1) & (UHCI_CCS | UHCI_CSC), UHCI_CSC);
    for(const port of [0, 1]) assert.equal(r32(PORTSC(port)) & (CCS | CSC | PED | PO | LS), CCS | CSC | 2 << 10);
    assert.equal(r32(PORTSC(2)) & CCS, 0);
    assert.equal(r32(USBSTS) & PCD, PCD);
    assert.ok(pci.intx_levels[EHCI]);
    w32(USBSTS, PCD);
    assert.ok(!pci.intx_levels[EHCI]);
});

await test("port reset: the high-speed disk's port enabled; the full-speed tablet's not, then Port Owner gives it to its companion", () => {
    w32(PORTSC(1), CSC | PR);
    w32(PORTSC(1), 0);
    assert.equal(r32(PORTSC(1)) & (CCS | PED | PR), CCS | PED);
    w32(PORTSC(0), CSC | PR);
    w32(PORTSC(0), 0);
    assert.equal(r32(PORTSC(0)) & (CCS | PED), CCS);
    w32(PORTSC(0), PO);
    assert.equal(r32(PORTSC(0)) & (CCS | PO), PO);
    assert.equal(uhci_r16(UHCI_PORTSC1) & UHCI_CCS, UHCI_CCS, "the tablet on the companion");
    assert.equal(uhci_r16(UHCI_PORTSC1 + 2) & UHCI_CCS, 0, "the disk not");
});

await test("usb_devices: the tablet on a companion at 12 Mbit/s, the disk on the EHCI at 480", async () => {
    assert.deepEqual(await emulator.usb_devices(), [
        { id: "tablet", port: 0, plugged: true, controller: "uhci", speed: 12 },
        { id: "stick", port: 1, plugged: true, controller: "ehci", speed: 480 },
    ]);
});

// --- the asynchronous schedule ------------------------------------------------------

// queue heads, qTDs, buffers
const QH = 0x100000, QTDS = 0x101000, DATA = 0x200000;
/** A queue head of the ring of one: the endpoint, its speed (high), max packet */
function queue_head(address, endpoint, max_packet, control)
{
    put32(QH, QH | 2);
    put32(QH + 4, address | endpoint << 8 | 2 << 12 | (control ? 1 << 14 : 0) | 1 << 15 | max_packet << 16);
    put32(QH + 8, 1 << 30);
    for(let i = 3; i < 17; i++) put32(QH + 4 * i, 0);
    put32(QH + 16, 1);
}
/** qTDs (each [pid, length, buffer, toggle, ioc]) linked; the queue head's next the first */
function qtds(list, alternate = 1)
{
    list.forEach(([pid, length, buffer, toggle, ioc], i) =>
    {
        const at = QTDS + 64 * i;
        put32(at, i + 1 < list.length ? QTDS + 64 * (i + 1) : 1);
        put32(at + 4, alternate);
        put32(at + 8, (toggle ? 1 << 31 : 0) | length << 16 | (ioc ? TOKEN_IOC : 0) | 3 << 10 | pid << 8 | TOKEN_ACTIVE);
        for(let page = 0; page < 5; page++) put32(at + 12 + 4 * page, page ? (buffer & ~0xFFF) + 0x1000 * page : buffer);
        for(let page = 0; page < 5; page++) put32(at + 32 + 4 * page, 0);
    });
    put32(QH + 16, QTDS);
    put32(QH + 24, 0);
}
const token = i => u32(QTDS + 64 * i + 8);
const left = i => token(i) >>> 16 & 0x7FFF;
/** Run until the last qTD is done (or `ms`) */
function run(count, ms = 20)
{
    for(let i = 0; i < ms && token(count - 1) & TOKEN_ACTIVE && !(token(count - 1) & TOKEN_HALTED); i++)
    {
        advance(1);
        if(Array.from({ length: count }, (_, j) => token(j)).some(t => t & TOKEN_HALTED)) break;
    }
}
const setup = (type, request, value, index, length) => Uint8Array.of(type, request, value & 0xFF, value >> 8, index & 0xFF, index >> 8, length & 0xFF, length >> 8);
/** A control transfer: SETUP, the data stage in one qTD, the status stage */
function control(address, bytes)
{
    const length = bytes[6] | bytes[7] << 8, into = bytes[0] & 0x80;
    mem.set(bytes, DATA);
    queue_head(address, 0, 64, true);
    const list = [[SETUP, 8, DATA, 0, false]];
    if(length) list.push([into ? IN : OUT, length, DATA + 0x1000, 1, false]);
    list.push([into ? OUT : IN, 0, 0, 1, true]);
    qtds(list);
    run(list.length);
    const data_qtd = length ? 1 : -1;
    const moved = data_qtd > 0 ? length - left(1) : 0;
    return { data: mem.slice(DATA + 0x1000, DATA + 0x1000 + moved), tokens: list.map((_, i) => token(i)) };
}

await test("a control transfer on the asynchronous schedule: GET_DESCRIPTOR at address 0 (SETUP, IN, OUT); IOC: USBINT", () => {
    w32(ASYNCLISTADDR, QH);
    w32(USBCMD, RS | ASE | 8 << 16);
    assert.equal(r32(USBSTS) & (HALTED | ASS), ASS);
    const r = control(0, setup(0x80, 6, 0x0100, 0, 18));
    assert.equal(r.data.length, 18);
    assert.deepEqual([r.data[1], r.data[7], r.data[8] | r.data[9] << 8], [1, 64, 0x46F4]);
    assert.ok(r.tokens.every(t => !(t & (TOKEN_ACTIVE | TOKEN_HALTED))), r.tokens.map(t => t.toString(16)).join(" "));
    assert.equal(r32(USBSTS) & USBINT, USBINT);
    w32(USBSTS, USBINT);
});

await test("SET_ADDRESS, SET_CONFIGURATION; at high speed: bulk packets of 512 bytes, the qualifier the full speed's", () => {
    control(0, setup(0x00, 5, 5, 0, 0));
    const config = control(5, setup(0x80, 6, 0x0200, 0, 32)).data;
    assert.deepEqual([config[22] | config[23] << 8, config[29] | config[30] << 8], [512, 512]);
    assert.deepEqual(Array.from(control(5, setup(0x80, 6, 0x0600, 0, 10)).data), [10, 6, 0x00, 0x02, 0, 0, 0, 64, 1, 0]);
    const other = control(5, setup(0x80, 6, 0x0700, 0, 32)).data;
    assert.deepEqual([other[1], other[22] | other[23] << 8], [7, 64]);
    control(5, setup(0x00, 9, 1, 0, 0));
    assert.deepEqual(Array.from(control(5, setup(0x80, 8, 0, 0, 1)).data), [1]);
});

/** A bulk transfer in qTDs of up to 16 KiB */
function bulk(endpoint, pid, length, out = null)
{
    if(out) mem.set(out, DATA);
    queue_head(5, endpoint, 512, false);
    const list = [];
    for(let at = 0; at < length || !list.length; at += 16384) list.push([pid, Math.min(16384, length - at), DATA + at, 0, at + 16384 >= length]);
    qtds(list);
    run(list.length, 50);
    let moved = 0;
    list.forEach(([, n], i) => { moved += n - left(i); });
    return { data: mem.slice(DATA, DATA + moved), tokens: list.map((_, i) => token(i)) };
}
let tags = 0;
function scsi(cb, length = 0, direction_in = true, out = null)
{
    const cbw = new Uint8Array(31);
    const view = new DataView(cbw.buffer);
    view.setUint32(0, 0x43425355, true);
    view.setUint32(4, ++tags, true);
    view.setUint32(8, length, true);
    cbw[12] = direction_in ? 0x80 : 0;
    cbw[14] = cb.length;
    cbw.set(cb, 15);
    bulk(2, OUT, 31, cbw);
    const data = length ? bulk(direction_in ? 1 : 2, direction_in ? IN : OUT, length, out).data : null;
    const csw = bulk(1, IN, 13).data;
    const csw_view = new DataView(csw.buffer);
    assert.equal(csw_view.getUint32(4, true), tags);
    return { data, status: csw[12], residue: csw_view.getUint32(8, true) };
}
const read10 = (lba, count) => [0x28, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];
const write10 = (lba, count) => [0x2A, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];

await test("the USB disk on bulk endpoints: INQUIRY, READ(10) of 64 sectors (qTDs over pages), WRITE(10) of 100 sectors", () => {
    const inquiry = scsi([0x12, 0, 0, 0, 36, 0], 36);
    assert.equal(new TextDecoder().decode(inquiry.data.subarray(8, 16)), "v86     ");
    const read = scsi(read10(5, 64), 64 * 512);
    assert.equal(read.status, 0);
    assert.deepEqual(read.data, image.slice(5 * 512, 69 * 512));
    const data = new Uint8Array(100 * 512).map((_, i) => i * 7 + 3 & 0xFF);
    assert.equal(scsi(write10(200, 100), data.length, false, data).status, 0);
    assert.deepEqual(image.slice(200 * 512, 300 * 512), data);
});

await test("a short packet: the qTD ends with its bytes left, USBINT; the alternate next qTD goes on from it", () => {
    const cbw = new Uint8Array(31);
    new DataView(cbw.buffer).setUint32(0, 0x43425355, true);
    new DataView(cbw.buffer).setUint32(4, 99, true);
    cbw[12] = 0x80;
    cbw[14] = 6;
    cbw.set([0x00, 0, 0, 0, 0, 0], 15);
    bulk(2, OUT, 31, cbw);
    // the CSW into a qTD of 512: 13 bytes; its alternate next (index 2) taken, not its next (index 1)
    queue_head(5, 1, 512, false);
    w32(USBSTS, 0x3F);
    qtds([[IN, 512, DATA, 0, false], [IN, 512, DATA + 0x1000, 0, false], [IN, 0, DATA + 0x2000, 0, true]], QTDS + 128);
    advance(3);
    assert.equal(left(0), 512 - 13);
    assert.equal(token(0) & TOKEN_ACTIVE, 0);
    assert.equal(r32(USBSTS) & USBINT, USBINT);
    assert.equal(token(1) & TOKEN_ACTIVE, TOKEN_ACTIVE, "the next qTD not taken");
    assert.equal(u32(QH + 12), QTDS + 128, "the queue head's current qTD: the alternate one");
});

await test("STALL: an unknown descriptor halts the qTD (USBERRINT); a new SETUP goes on", () => {
    w32(USBSTS, 0x3F);
    const r = control(5, setup(0x80, 6, 0x5500, 0, 8));
    assert.ok(r.tokens.some(t => t & TOKEN_HALTED));
    assert.equal(r32(USBSTS) & USBERRINT, USBERRINT);
    assert.equal(control(5, setup(0x80, 8, 0, 0, 1)).data[0], 1);
});

await test("no device at the address: a transaction error, CERR down to 0, then halted", () => {
    const r = control(9, setup(0x80, 6, 0x0100, 0, 18));
    assert.equal(r.tokens[0] & (TOKEN_HALTED | TOKEN_XACTERR), TOKEN_HALTED | TOKEN_XACTERR);
});

await test("Interrupt on Async Advance: the doorbell answered at once (IAA, IAAD cleared)", () => {
    w32(USBSTS, 0x3F);
    w32(USBCMD, r32(USBCMD) | IAAD);
    assert.equal(r32(USBCMD) & IAAD, 0);
    assert.equal(r32(USBSTS) & IAA, IAA);
    w32(USBSTS, IAA);
});

await test("FRINDEX: 8 micro-frames a millisecond; the periodic schedule: an iTD skipped, a queue head by its S-mask", () => {
    const before = r32(FRINDEX);
    advance(4);
    assert.equal(r32(FRINDEX) - before & 0x3FFF, 32);
    // every frame: an iTD, then a queue head for address 9 (none there) in micro-frame 0
    const LIST = 0x300000, ITD = 0x301000, PQH = 0x302000;
    for(let i = 0; i < 1024; i++) put32(LIST + 4 * i, ITD);
    put32(ITD, PQH | 2);
    put32(PQH, 1);
    put32(PQH + 4, 9 | 1 << 8 | 2 << 12 | 8 << 16);
    put32(PQH + 8, 1 << 30 | 1);
    for(let i = 3; i < 17; i++) put32(PQH + 4 * i, 0);
    put32(PQH + 16, QTDS + 0x800);
    put32(QTDS + 0x800, 1);
    put32(QTDS + 0x804, 1);
    put32(QTDS + 0x808, 8 << 16 | 3 << 10 | IN << 8 | TOKEN_ACTIVE);
    w32(PERIODICLISTBASE, LIST);
    w32(USBCMD, r32(USBCMD) | PSE);
    assert.equal(r32(USBSTS) & PSS, PSS);
    advance(4);
    assert.equal(u32(QTDS + 0x808) & (TOKEN_ACTIVE | TOKEN_HALTED | TOKEN_XACTERR), TOKEN_HALTED | TOKEN_XACTERR, "three micro-frames' errors");
    w32(USBCMD, r32(USBCMD) & ~PSE);
});

// a disk whose reads come back later
const pending = [];
class SlowBuffer
{
    constructor() { this.bytes = new Uint8Array(512 * 256).map((_, i) => i * 5 & 0xFF); this.byteLength = this.bytes.length; this.onload = undefined; }
    load() { this.onload && this.onload({}); }
    get(start, length, fn) { pending.push(() => fn(this.bytes.slice(start, start + length))); }
    set(start, data, fn) { this.bytes.set(data, start); fn(); }
    get_state() { return []; }
    set_state() {}
}
await test("usb_attach_disk: the next free port (2), the EHCI's; a READ whose data comes later NAKs (the qTD stays active)", async () => {
    const slow = new SlowBuffer();
    await emulator.usb_attach_disk("slow", slow);
    assert.equal(r32(PORTSC(2)) & (CCS | CSC), CCS | CSC);
    w32(PORTSC(2), CSC | PR);
    w32(PORTSC(2), 0);
    assert.equal(r32(PORTSC(2)) & PED, PED);
    control(0, setup(0x00, 5, 6, 0, 0));
    control(6, setup(0x00, 9, 1, 0, 0));
    const cbw = new Uint8Array(31);
    const view = new DataView(cbw.buffer);
    view.setUint32(0, 0x43425355, true);
    view.setUint32(4, 7, true);
    view.setUint32(8, 4096, true);
    cbw[12] = 0x80;
    cbw[14] = 10;
    cbw.set(read10(3, 8), 15);
    mem.set(cbw, DATA);
    queue_head(6, 2, 512, false);
    qtds([[OUT, 31, DATA, 0, true]]);
    run(1);
    queue_head(6, 1, 512, false);
    qtds([[IN, 4096, DATA, 0, true]]);
    advance(5);
    assert.equal(token(0) & TOKEN_ACTIVE, TOKEN_ACTIVE, "waiting");
    assert.equal(left(0), 4096);
    pending.shift()();
    run(1);
    assert.equal(left(0), 0);
    assert.deepEqual(mem.slice(DATA, DATA + 4096), slow.bytes.slice(3 * 512, 11 * 512));
    queue_head(6, 1, 512, false);
    qtds([[IN, 13, DATA, 0, true]]);
    run(1);
    assert.equal(mem[DATA + 12], 0, "CSW: passed");
});

await test("usb_plug: the EHCI's disk out (CSC, PEDC) and back; the companion's tablet out gives the port back to the EHCI", async () => {
    await emulator.usb_plug("stick", false);
    assert.equal(r32(PORTSC(1)) & (CCS | CSC | PED | PEDC), CSC | PEDC);
    await emulator.usb_plug("stick", true);
    assert.equal(r32(PORTSC(1)) & (CCS | CSC), CCS | CSC);
    await emulator.usb_plug("tablet", false);
    assert.equal(uhci_r16(UHCI_PORTSC1) & UHCI_CCS, 0);
    assert.equal(r32(PORTSC(0)) & PO, 0, "the EHCI's again");
    await emulator.usb_plug("tablet", true);
    assert.equal(r32(PORTSC(0)) & (CCS | CSC), CCS | CSC, "seen by the EHCI first");
});

await test("a snapshot: the registers, the ports and their owners, the companions; the disk goes on reading", async () => {
    // the tablet to its companion again; the disk enabled again at address 5
    w32(PORTSC(0), CSC | PR);
    w32(PORTSC(0), 0);
    w32(PORTSC(0), PO);
    w32(PORTSC(1), CSC | PR);
    w32(PORTSC(1), 0);
    control(0, setup(0x00, 5, 5, 0, 0));
    control(5, setup(0x00, 9, 1, 0, 0));
    const state = await emulator.save_state();
    w32(CONFIGFLAG, 0);
    await emulator.restore_state(state);
    assert.equal(r32(CONFIGFLAG), 1);
    assert.equal(r32(PORTSC(0)) & PO, PO);
    assert.equal(r32(PORTSC(1)) & (CCS | PED), CCS | PED);
    assert.equal(uhci_r16(UHCI_PORTSC1) & UHCI_CCS, UHCI_CCS, "the tablet on its companion");
    assert.deepEqual(scsi(read10(5, 1), 512).data, image.slice(5 * 512, 6 * 512));
});

await test("CONFIGFLAG cleared: every device to the companions; HCRESET: halted, the ports the companions'", () => {
    w32(CONFIGFLAG, 0);
    assert.equal(r32(PORTSC(1)) & (CCS | PO), PO);
    assert.equal(uhci_r16(UHCI_PORTSC1 + 2) & UHCI_CCS, UHCI_CCS, "the disk on the companion");
    w32(USBCMD, HCRESET);
    assert.equal(r32(USBSTS) & HALTED, HALTED);
    assert.equal(r32(USBCMD) & RS, 0);
    assert.equal(r32(PORTSC(1)) & PO, PO);
});

{
    const pc = await machine("i440fx");
    const space = n => pc.v86.cpu.devices.pci.space_bytes(0x06 << 3 | n);
    await test("i440FX: the EHCI at 00:06.7, its companions at 00:06.0-2", () => {
        assert.equal(space(7)[2] | space(7)[3] << 8, 0x293A);
        assert.equal(space(0)[2] | space(0)[3] << 8, 0x2934);
        assert.equal(space(2)[2] | space(2)[3] << 8, 0x2936);
    });
    await pc.destroy();
}

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
             source/v64/tests/devices/usb_guest.mjs                                                              0000755 0000000 0000000 00000024174 00000000000 015176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// USB with real drivers: Alpine 3.24 x86_64's uhci-hcd and usbhid on usb:
// { controller: "uhci", tablet: true } (docs/modern-pc-devices-plan.md U1,
// "验收"; the pinned virt ISO, tests/lib/alpine_image.mjs). The tablet is
// enumerated (sysfs: its IDs, its product, a HID input device); the page's
// pointer arrives as absolute events (/dev/input/event*: ABS_X, ABS_Y over
// 0 to 32767, the buttons, the wheel) at the corners, the centre and a 5x5
// grid; out of its port and back in, it is enumerated again; a snapshot.
//
// MACHINE=q35 (ICH9's UHCI), CPU_CORES=2, SHOW_LOGS=1, USB_CONTROLLER=ehci
// (EHCI, ehci-pci: the full-speed tablet on its UHCI companion, at 12M) or
// xhci (xhci-pci: the tablet on a USB 2 root port, at 12M).

import assert from "node:assert/strict";
import url from "node:url";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "i440fx";
const CONTROLLER = process.env.USB_CONTROLLER || "uhci";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const prepared = await prepare_alpine("x86_64-virt");
const directory = ROOT + "build/x64-linux/";
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    bzimage: { url: directory + "boot/vmlinuz-virt" },
    initrd: { url: directory + "boot/initramfs-virt" },
    cdrom: { url: directory + prepared.image.name },
    cmdline: "console=ttyS0,115200 loglevel=4 nokaslr modules=loop,squashfs,sd-mod,usb-storage",
    memory_size: 512 * 1024 * 1024,
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    acpi: true,
    net_device: { type: "none" },
    usb: { controller: CONTROLLER, tablet: true },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, 900 * 1000);

let serial = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});
let tablet_active = false;
emulator.add_listener("usb-tablet-active", value => { tablet_active = value; });

const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send(cmd + "\n");
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(cmd.length).replace(PROMPT, "");
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

console.log("Booting Alpine x86_64 with a USB tablet (" + CONTROLLER + ", " + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");
await wait_serial(/login: $/, "the login prompt", 600000);
serial = "";
emulator.serial0_send("root\n");
await wait_serial(PROMPT, "the shell", 120000);

/** The tablet's event device (/proc/bus/input/devices), once it is there */
async function event_device()
{
    const output = await command("for i in $(seq 30); do grep -q 'v86 USB Tablet' /proc/bus/input/devices && break; sleep 1; done; " +
        "grep -A6 'v86 USB Tablet' /proc/bus/input/devices | grep Handlers");
    const match = output.match(/event(\d+)/);
    assert.ok(match, "the tablet's input device: " + output);
    return "/dev/input/event" + match[1];
}

let device;
await step("the controller's driver and usbhid: the tablet enumerated (its IDs and product), an input device, the pointer the tablet's", async () => {
    device = await event_device();
    const ids = await command("cat /sys/bus/usb/devices/*/idVendor /sys/bus/usb/devices/*/idProduct /sys/bus/usb/devices/*/product 2>/dev/null | tr '\\n' ' '");
    assert.match(ids, /0627/);
    assert.match(ids, /v86 USB Tablet/);
    // (PIIX3's function 2 on i440FX, ICH9's 00:1d.0 on Q35; EHCI's first
    // companion at 00:1d.0 or v86's 00:06.0, the EHCI at function 7; xHCI at 00:14.0)
    const slot = CONTROLLER === "ehci" ? (MACHINE === "q35" ? "1d" : "06") : MACHINE === "q35" ? "1d.0" : "01.2";
    const driver = await command("basename $(readlink /sys/bus/pci/devices/0000:00:" + (CONTROLLER === "xhci" ? "14.0" :
        CONTROLLER === "ehci" ? slot + ".0" : slot) + "/driver)");
    assert.match(driver, CONTROLLER === "xhci" ? /xhci_hcd/ : /uhci_hcd/);
    if(CONTROLLER === "xhci")
    {
        assert.match(await command("for d in /sys/bus/usb/devices/*; do [ \"$(cat $d/idVendor 2>/dev/null)\" = 0627 ] && echo SPE''ED $(cat $d/speed); done"),
            /^SPEED 12$/m);
    }
    if(CONTROLLER === "ehci")
    {
        assert.match(await command("basename $(readlink /sys/bus/pci/devices/0000:00:" + slot + ".7/driver)"), /ehci-pci/);
        // (the tablet's speed: full, on the companion)
        assert.match(await command("for d in /sys/bus/usb/devices/*; do [ \"$(cat $d/idVendor 2>/dev/null)\" = 0627 ] && echo SPE''ED $(cat $d/speed); done"),
            /^SPEED 12$/m);
    }
    assert.ok(tablet_active, "announced: the PS/2 mouse leaves the pointer to it");
});

/**
 * The tablet's value for a position of the page's pointer: the middle of its pixel
 * @param {number} position
 * @param {number} size
 */
const tablet_value = (position, size) => Math.min(32767, Math.round((position + 0.5) / size * 32767));

/**
 * The events the guest reads while the page's pointer goes through `points`
 * (each [x, y] over a screen of 1024x768), with a click at the end
 * @return {Promise<!Array<{type: number, code: number, value: number}>>}
 */
async function events_for(points)
{
    // (cat writes what it reads at once; hexdump would buffer it)
    await command("rm -f /tmp/ev; (cat " + device + " > /tmp/ev &) ; sleep 1");
    for(const [x, y] of points)
    {
        emulator.bus.send("mouse-absolute", [x, y, 1024, 768]);
        await sleep(60);
    }
    emulator.bus.send("mouse-click", [true, false, false]);
    await sleep(60);
    emulator.bus.send("mouse-click", [false, false, false]);
    emulator.bus.send("mouse-wheel", [1, 0]);
    await sleep(300);
    const output = await command("sleep 1; killall cat; hexdump -v -e '6/4 \"%d \" \"\\n\"' /tmp/ev");
    return output.split("\n").map(line => line.trim().split(/\s+/).map(Number)).filter(w => w.length === 6 && !w.some(isNaN))
        .map(w => ({ type: w[4] & 0xFFFF, code: w[4] >>> 16, value: w[5] }));
}

await step("the pointer: corners, centre and a 5x5 grid as absolute positions, the buttons, the wheel", async () => {
    const points = [[0, 0], [1023, 0], [0, 767], [1023, 767], [512, 384]];
    for(let i = 0; i < 5; i++) for(let j = 0; j < 5; j++) points.push([Math.round(i * 1023 / 4), Math.round(j * 767 / 4)]);
    const events = await events_for(points);
    // (each report's X and Y; a value the same as the last is not sent again)
    let x = -1, y = -1;
    const seen = [];
    for(const e of events)
    {
        if(e.type === 3 && e.code === 0) x = e.value;
        if(e.type === 3 && e.code === 1) y = e.value;
        if(e.type === 0 && e.code === 0 && x >= 0 && y >= 0) seen.push([x, y]);
    }
    const expected = points.map(([px, py]) => [tablet_value(px, 1024), tablet_value(py, 768)]);
    for(const [ex, ey] of expected)
    {
        assert.ok(seen.some(([sx, sy]) => sx === ex && sy === ey), "the position " + ex + "," + ey + " among " + JSON.stringify(seen.slice(0, 40)));
    }
    // (and no position the page's pointer never had)
    const stray = seen.filter(([sx, sy]) => !expected.some(([ex, ey]) => sx === ex && sy === ey));
    assert.deepEqual(stray, [], "positions not the pointer's");
    assert.ok(events.some(e => e.type === 1 && e.code === 0x110 && e.value === 1), "BTN_LEFT down");
    assert.ok(events.some(e => e.type === 1 && e.code === 0x110 && e.value === 0), "BTN_LEFT up");
    assert.ok(events.some(e => e.type === 2 && e.code === 8 && e.value === 1), "REL_WHEEL up");
});

await step("out of its port and back in: gone from the guest, enumerated again", async () => {
    await emulator.usb_plug("tablet", false);
    const gone = await command("sleep 3; grep -c 'v86 USB Tablet' /proc/bus/input/devices");
    assert.match(gone, /^\s*0\s*$/m, "gone: " + gone);
    assert.ok(!tablet_active);
    await emulator.usb_plug("tablet", true);
    device = await event_device();
    assert.ok(tablet_active);
    const events = await events_for([[100, 100], [900, 700]]);
    assert.ok(events.some(e => e.type === 3 && e.code === 0 && e.value === tablet_value(900, 1024)), "the pointer again");
});

await step("a snapshot: the tablet goes on after restoring it", async () => {
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    serial = "";
    emulator.serial0_send("\n");
    await wait_serial(PROMPT, "the shell after restoring", 30000);
    const events = await events_for([[300, 200]]);
    assert.ok(events.some(e => e.type === 3 && e.code === 0 && e.value === tablet_value(300, 1024)));
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/devices/usb_storage.js                                                             0000755 0000000 0000000 00000063515 00000000000 015340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// USB disks (usb.mass_storage, src/usb/mass_storage.js, docs/usb.md): a
// disk image as a USB stick behind the UHCI controller, driven through the
// controller's registers and a schedule in guest memory, no guest code; the
// test moves the machine clock (docs/modern-pc-devices-plan.md U2).
// Enumeration, GET_MAX_LUN, Bulk-Only Transport (CBW, data, CSW, tags,
// residues, the cases where host and device disagree, an invalid CBW and the
// reset recovery), the SCSI commands (INQUIRY, TEST UNIT READY, READ
// CAPACITY, READ and WRITE across pieces of the image, MODE SENSE, REQUEST
// SENSE, SYNCHRONIZE CACHE, eject and PREVENT), a read-only disk, a disk
// whose reads complete later (NAK meanwhile), usb_attach_disk and
// usb_detach_disk, usb_plug, snapshots.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SECTORS = 8192;
const pattern = i => (i * 7 + (i >> 9)) & 0xFF;
const image = new Uint8Array(SECTORS * 512).map((_, i) => pattern(i));

let host = 1000;
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 32 * 1024 * 1024,
    usb: { controller: "uhci", tablet: false, mass_storage: [{ id: "stick", image: { buffer: image.buffer } }] },
    net_device: { type: "none" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu;
cpu.clock.resume();
const pci = cpu.devices.pci;
const mem = cpu.mem8;

let failed = 0, passed = 0;
async function test(name, f)
{
    try
    {
        await f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const UHCI = 0x01 << 3 | 2, IO = 0xC000;
const r16 = offset => cpu.io.port_read16(IO + offset);
const w16 = (offset, value) => cpu.io.port_write16(IO + offset, value);
const w32 = (offset, value) => cpu.io.port_write32(IO + offset, value | 0);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };

const USBCMD = 0x00, USBSTS = 0x02, FLBASEADD = 0x08, PORTSC1 = 0x10, PORTSC2 = 0x12;
const RS = 1;
const CCS = 1, CSC = 2, PE = 4, PR = 1 << 9;
const T = 1, Q = 2, VF = 4;
const ACTIVE = 1 << 23, SPD = 1 << 29, STALLED = 1 << 22, ERRORS3 = 3 << 27;
const PID_SETUP = 0x2D, PID_IN = 0x69, PID_OUT = 0xE1;

/** Move the machine clock on and run the machine's timers */
function advance(ms)
{
    for(let i = 0; i < ms; i++)
    {
        host += 1;
        cpu.run_hardware_timers(false, cpu.clock.now());
    }
}

// the schedule: every frame list entry to one queue head; room for 64 KiB
// transfers (1024 TDs of 64 bytes)
const FRAME_LIST = 0x100000, QH = 0x101000, TDS = 0x200000, DATA = 0x400000;
const token = (pid, address, endpoint, toggle, length) => pid | address << 8 | endpoint << 15 | toggle << 19 | (length - 1 & 0x7FF) << 21;
/** Write TDs (each [control, token, buffer]) linked depth first; the queue head's element the first */
function queue(tds)
{
    tds.forEach(([control, tok, buffer], i) =>
    {
        const at = TDS + 32 * i;
        put32(at, i + 1 < tds.length ? TDS + 32 * (i + 1) | VF : T);
        put32(at + 4, control);
        put32(at + 8, tok);
        put32(at + 12, buffer);
    });
    put32(QH + 4, TDS);
}
const td_control = i => u32(TDS + 32 * i + 4);

/** A control transfer (8-byte packets): the data read, whether it stalled */
function control(address, setup, length = setup[6] | setup[7] << 8)
{
    mem.set(setup, DATA);
    const tds = [[ACTIVE | ERRORS3, token(PID_SETUP, address, 0, 0, 8), DATA]];
    const into = !(setup[0] & 0x80);
    let toggle = 1;
    for(let done = 0; done < length; done += 8)
    {
        tds.push([ACTIVE | ERRORS3, token(into ? PID_OUT : PID_IN, address, 0, toggle, Math.min(8, length - done)), DATA + 0x100 + done]);
        toggle ^= 1;
    }
    tds.push([ACTIVE | ERRORS3, token(into ? PID_IN : PID_OUT, address, 0, 1, 0), 0]);
    queue(tds);
    advance(3);
    let read = 0;
    for(let i = 1; i < tds.length - 1; i++)
    {
        const c = td_control(i);
        if(c & ACTIVE || c & STALLED) break;
        read += (c + 1) & 0x7FF;
    }
    const stalled = tds.some((_, i) => td_control(i) & STALLED);
    return { data: mem.slice(DATA + 0x100, DATA + 0x100 + read), stalled, done: !(td_control(tds.length - 1) & ACTIVE) };
}
const setup = (type, request, value, index, length) => Uint8Array.of(type, request, value & 0xFF, value >> 8, index & 0xFF, index >> 8, length & 0xFF, length >> 8);

// bulk transfers: the endpoints' data toggles
const toggles = new Map();
/**
 * A bulk transfer of 64-byte packets: run frames until its TDs are done (a
 * NAKed TD stays active), at most `frames`
 * @return {{data: Uint8Array, stalled: boolean, done: boolean, length: number}}
 */
function bulk(address, endpoint, pid, length, out = null, frames = 50)
{
    if(out) mem.set(out, DATA);
    const key = address << 8 | endpoint | (pid === PID_IN ? 0x80 : 0);
    let toggle = toggles.get(key) || 0;
    const tds = [];
    for(let done = 0; done < length || done === 0 && length === 0; done += 64)
    {
        tds.push([ACTIVE | ERRORS3 | (pid === PID_IN ? SPD : 0), token(pid, address, endpoint, toggle, Math.min(64, length - done)), DATA + done]);
        toggle ^= 1;
    }
    queue(tds);
    let moved = 0, stalled = false, finished = false;
    for(let frame = 0; frame < frames && !finished; frame++)
    {
        advance(1);
        moved = 0;
        finished = true;
        for(let i = 0; i < tds.length; i++)
        {
            const c = td_control(i);
            if(c & STALLED) { stalled = true; break; }
            if(c & ACTIVE) { finished = false; break; }
            const n = (c + 1) & 0x7FF;
            moved += n;
            // (a short packet ends the transfer)
            if(n < 64) break;
        }
        if(stalled) break;
    }
    toggles.set(key, toggle);
    return { data: mem.slice(DATA, DATA + moved), stalled, done: finished && !stalled, length: moved };
}

let tags = 0;
/** A command block wrapper */
function cbw(length, direction_in, cb, tag = ++tags)
{
    const bytes = new Uint8Array(31);
    const view = new DataView(bytes.buffer);
    view.setUint32(0, 0x43425355, true);
    view.setUint32(4, tag, true);
    view.setUint32(8, length, true);
    bytes[12] = direction_in ? 0x80 : 0;
    bytes[14] = cb.length;
    bytes.set(cb, 15);
    return bytes;
}
/** The command status wrapper */
function csw(address)
{
    const r = bulk(address, 1, PID_IN, 13);
    assert.ok(r.done && r.length === 13, "a CSW: " + JSON.stringify({ stalled: r.stalled, length: r.length }));
    const view = new DataView(r.data.buffer);
    assert.equal(view.getUint32(0, true), 0x53425355, "dCSWSignature");
    return { tag: view.getUint32(4, true), residue: view.getUint32(8, true), status: r.data[12] };
}
/**
 * A SCSI command: CBW, data (IN: `length` bytes; OUT: `out`), CSW
 * @return {{data: ?Uint8Array, status: number, residue: number}}
 */
function scsi(address, cb, length = 0, direction_in = true, out = null)
{
    const tag = tags + 1;
    assert.ok(bulk(address, 2, PID_OUT, 31, cbw(length, direction_in, Uint8Array.from(cb))).done, "the CBW taken");
    let data = null;
    if(length)
    {
        const r = bulk(address, direction_in ? 1 : 2, direction_in ? PID_IN : PID_OUT, length, out, 200);
        assert.ok(r.done, "the data stage done");
        data = r.data;
    }
    const status = csw(address);
    assert.equal(status.tag, tag, "the CSW's tag is the CBW's");
    return { data, status: status.status, residue: status.residue };
}
/** REQUEST SENSE: [key, ASC, ASCQ] */
function request_sense(address)
{
    const data = scsi(address, [0x03, 0, 0, 0, 18, 0], 18).data;
    assert.equal(data[0], 0x70, "fixed format, current");
    return [data[2] & 0xF, data[12], data[13]];
}
const be32 = (bytes, at) => (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
const read10 = (lba, count) => [0x28, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];
const write10 = (lba, count) => [0x2A, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];

/** Reset and enable a port, give the device an address and its configuration */
function enumerate(portsc, address)
{
    w16(portsc, CSC);
    w16(portsc, PR);
    w16(portsc, 0);
    w16(portsc, PE);
    assert.equal(control(0, setup(0x00, 5, address, 0, 0)).done, true, "SET_ADDRESS");
    assert.equal(control(address, setup(0x00, 9, 1, 0, 0)).done, true, "SET_CONFIGURATION");
    for(const key of Array.from(toggles.keys())) if(key >> 8 === address) toggles.delete(key);
}

// --- the controller, the port, enumeration ----------------------------------------

await test("the USB disk on port 1 (no tablet), port 2 empty", () => {
    pci.config_write(UHCI, 0x20, 4, IO | 1);
    pci.config_write(UHCI, 0x04, 2, 0x0005);
    assert.equal(r16(PORTSC1) & (CCS | CSC), CCS | CSC);
    assert.equal(r16(PORTSC2) & CCS, 0);
    for(let i = 0; i < 1024; i++) put32(FRAME_LIST + 4 * i, QH | Q);
    put32(QH, T);
    put32(QH + 4, T);
    w32(FLBASEADD, FRAME_LIST);
    w16(USBCMD, RS);
    w16(PORTSC1, CSC);
    w16(PORTSC1, PR);
    w16(PORTSC1, 0);
    w16(PORTSC1, PE);
    assert.equal(r16(PORTSC1) & (CCS | PE), CCS | PE);
});

await test("descriptors: QEMU's USB disk IDs, USB 2.0, 64-byte packets; mass storage, SCSI, Bulk-Only; bulk IN 0x81, OUT 0x02; a serial number; its high speed", () => {
    const device = control(0, setup(0x80, 6, 0x0100, 0, 18)).data;
    assert.equal(device.length, 18);
    assert.equal(device[2] | device[3] << 8, 0x0200);
    assert.equal(device[7], 64);
    assert.equal(device[8] | device[9] << 8, 0x46F4);
    assert.equal(device[10] | device[11] << 8, 0x0001);
    assert.equal(control(0, setup(0x00, 5, 3, 0, 0)).done, true);
    const config = control(3, setup(0x80, 6, 0x0200, 0, 32)).data;
    assert.equal(config.length, 32);
    assert.deepEqual(Array.from(config.subarray(9, 18)), [9, 4, 0, 0, 2, 8, 6, 0x50, 0]);
    assert.deepEqual(Array.from(config.subarray(18, 25)), [7, 5, 0x81, 2, 64, 0, 0]);
    assert.deepEqual(Array.from(config.subarray(25, 32)), [7, 5, 0x02, 2, 64, 0, 0]);
    const serial = new TextDecoder("utf-16le").decode(control(3, setup(0x80, 6, 0x0303, 0x0409, 255), 255).data.subarray(2));
    assert.match(serial, /^[0-9A-F]{16}$/);
    const product = new TextDecoder("utf-16le").decode(control(3, setup(0x80, 6, 0x0302, 0x0409, 255), 255).data.subarray(2));
    assert.equal(product, "v86 USB Disk");
    // (a high-speed device at full speed: the qualifier and the other speed's configuration are its high speed's)
    assert.deepEqual(Array.from(control(3, setup(0x80, 6, 0x0600, 0, 10)).data), [10, 6, 0x00, 0x02, 0, 0, 0, 64, 1, 0]);
    const other = control(3, setup(0x80, 6, 0x0700, 0, 32)).data;
    assert.deepEqual([other[1], other[22] | other[23] << 8, other[29] | other[30] << 8], [7, 512, 512], "bulk packets of 512 bytes at high speed");
    assert.equal(control(3, setup(0x00, 9, 1, 0, 0)).done, true);
});

await test("GET_MAX_LUN: 0 (one LUN)", () => {
    assert.deepEqual(Array.from(control(3, setup(0xA1, 0xFE, 0, 0, 1)).data), [0]);
});

// --- SCSI ---------------------------------------------------------------------------

await test("INQUIRY: a removable direct access device, SPC-3, \"v86\" \"USB Disk\"; VPD pages 0x00 and 0x80 (the serial number)", () => {
    const r = scsi(3, [0x12, 0, 0, 0, 36, 0], 36);
    assert.equal(r.status, 0);
    assert.deepEqual(Array.from(r.data.subarray(0, 5)), [0, 0x80, 5, 2, 31]);
    assert.equal(new TextDecoder().decode(r.data.subarray(8, 32)), "v86     USB Disk        ");
    assert.deepEqual(Array.from(scsi(3, [0x12, 1, 0x00, 0, 255, 0], 255).data.subarray(0, 6)), [0, 0, 0, 2, 0, 0x80]);
    const serial = scsi(3, [0x12, 1, 0x80, 0, 255, 0], 255);
    assert.match(new TextDecoder().decode(serial.data.subarray(4, 4 + serial.data[3])), /^[0-9A-F]{16}$/);
    assert.equal(serial.residue, 255 - 20);
});

await test("TEST UNIT READY: ready; READ CAPACITY(10) and (16): 8192 sectors of 512 bytes; READ FORMAT CAPACITIES", () => {
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 0);
    const capacity = scsi(3, [0x25, 0, 0, 0, 0, 0, 0, 0, 0, 0], 8).data;
    assert.deepEqual([be32(capacity, 0), be32(capacity, 4)], [SECTORS - 1, 512]);
    const capacity16 = scsi(3, [0x9E, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0], 32).data;
    assert.deepEqual([be32(capacity16, 0), be32(capacity16, 4), be32(capacity16, 8)], [0, SECTORS - 1, 512]);
    // (the list, then zeros up to the host's length: the residue says how many)
    const formats = scsi(3, [0x23, 0, 0, 0, 0, 0, 0, 0, 252, 0], 252);
    assert.equal(formats.data[3], 8);
    assert.deepEqual([be32(formats.data, 4), formats.data[8]], [SECTORS, 2]);
    assert.equal(formats.residue, 240);
});

await test("READ(10): 70 sectors over several frames, the image's bytes", () => {
    const r = scsi(3, read10(3, 70), 70 * 512);
    assert.equal(r.status, 0);
    assert.equal(r.residue, 0);
    assert.deepEqual(r.data, image.slice(3 * 512, 73 * 512));
});

const written = new Uint8Array(130 * 512).map((_, i) => (i * 13 + 5) & 0xFF);
await test("WRITE(10): 130 sectors (more than one piece of the image), into the image; read back", () => {
    const r = scsi(3, write10(100, 130), written.length, false, written);
    assert.equal(r.status, 0);
    assert.deepEqual(image.slice(100 * 512, 230 * 512), written, "the image has the guest's data");
    assert.deepEqual(image.slice(99 * 512, 100 * 512), new Uint8Array(512).map((_, i) => pattern(99 * 512 + i)), "nothing before it");
    assert.deepEqual(image.slice(230 * 512, 231 * 512), new Uint8Array(512).map((_, i) => pattern(230 * 512 + i)), "nothing after it");
    assert.deepEqual(scsi(3, read10(100, 130), written.length).data, written);
});

await test("READ(6), READ(16), WRITE(6): the same sectors", () => {
    assert.deepEqual(scsi(3, [0x08, 0, 0, 100, 2, 0], 1024).data, written.slice(0, 1024));
    assert.deepEqual(scsi(3, [0x88, 0, 0, 0, 0, 0, 0, 0, 0, 101, 0, 0, 0, 1, 0, 0], 512).data, written.slice(512, 1024));
    const sector = new Uint8Array(512).fill(0xA5);
    assert.equal(scsi(3, [0x0A, 0, 0, 7, 1, 0], 512, false, sector).status, 0);
    assert.deepEqual(image.slice(7 * 512, 8 * 512), sector);
});

await test("errors: past the end (ILLEGAL REQUEST, LBA out of range), an unknown command; the sense once", () => {
    const r = scsi(3, read10(SECTORS - 2, 4), 2048);
    assert.equal(r.status, 1);
    assert.equal(r.residue, 2048, "no data: all of it residue");
    assert.deepEqual(request_sense(3), [5, 0x21, 0]);
    assert.deepEqual(request_sense(3), [0, 0, 0], "reported, then gone");
    assert.equal(scsi(3, [0xC5, 0, 0, 0, 0, 0]).status, 1);
    assert.deepEqual(request_sense(3), [5, 0x20, 0]);
    assert.equal(scsi(3, [0x12, 0, 0x80, 0, 36, 0], 36).status, 1, "INQUIRY: a page without EVPD");
    assert.deepEqual(request_sense(3), [5, 0x24, 0]);
});

await test("BOT: more expected than the device has (padded, the residue), less (phase error), the other direction (phase error)", () => {
    const more = scsi(3, [0x12, 0, 0, 0, 36, 0], 64);
    assert.equal(more.status, 0);
    assert.equal(more.data.length, 64);
    assert.deepEqual(Array.from(more.data.subarray(36)), new Array(28).fill(0));
    assert.equal(more.residue, 28);
    assert.equal(scsi(3, read10(0, 2), 512).status, 2);
    assert.equal(scsi(3, read10(0, 2), 1024, false, new Uint8Array(1024)).status, 2);
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0], 512).status, 0, "no data for a command without: padded");
    assert.deepEqual(scsi(3, read10(0, 1), 512).data, image.slice(0, 512), "and on");
});

await test("MODE SENSE(6) and (10): all pages (caching with the write cache, informational exceptions), not write protected", () => {
    const six = scsi(3, [0x1A, 0, 0x3F, 0, 192, 0], 192).data;
    assert.equal(six[0], 4 + 20 + 12 - 1, "the header and two pages");
    assert.equal(six[2] & 0x80, 0);
    assert.deepEqual([six[4], six[5], six[6] & 4], [0x08, 0x12, 4]);
    assert.deepEqual([six[24], six[25]], [0x1C, 0x0A]);
    const ten = scsi(3, [0x5A, 0, 0x08, 0, 0, 0, 0, 0, 255, 0], 255).data;
    assert.equal(ten[0] << 8 | ten[1], 8 + 20 - 2);
    assert.equal(ten[8], 0x08);
    assert.equal(scsi(3, [0x1A, 0, 0x05, 0, 192, 0], 192).status, 1, "a page it has not");
    assert.deepEqual(request_sense(3), [5, 0x24, 0]);
});

await test("SYNCHRONIZE CACHE, VERIFY: good", () => {
    assert.equal(scsi(3, [0x35, 0, 0, 0, 0, 0, 0, 0, 0, 0]).status, 0);
    assert.equal(scsi(3, [0x2F, 0, 0, 0, 0, 10, 0, 0, 8, 0]).status, 0);
});

let ejected = [];
emulator.add_listener("usb-disk-ejected", id => ejected.push(id));
await test("eject: refused while PREVENT, then the medium gone (NOT READY, MEDIUM NOT PRESENT, \"usb-disk-ejected\"); loaded again: UNIT ATTENTION once", () => {
    assert.equal(scsi(3, [0x1E, 0, 0, 0, 1, 0]).status, 0);
    assert.equal(scsi(3, [0x1B, 0, 0, 0, 2, 0]).status, 1);
    assert.deepEqual(request_sense(3), [5, 0x53, 2]);
    assert.equal(scsi(3, [0x1E, 0, 0, 0, 0, 0]).status, 0);
    assert.equal(scsi(3, [0x1B, 0, 0, 0, 2, 0]).status, 0);
    assert.deepEqual(ejected, ["stick"]);
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 1);
    assert.deepEqual(request_sense(3), [2, 0x3A, 0]);
    assert.equal(scsi(3, read10(0, 1), 512).status, 1);
    assert.equal(scsi(3, [0x1B, 0, 0, 0, 3, 0]).status, 0);
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 1);
    assert.deepEqual(request_sense(3), [6, 0x28, 0]);
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 0);
});

await test("an invalid CBW: both bulk endpoints STALL until the reset recovery (BOT reset, CLEAR_FEATURE of both)", () => {
    const bad = cbw(0, false, [0]);
    bad[0] = 0;
    assert.ok(bulk(3, 2, PID_OUT, 31, bad).done, "taken");
    assert.ok(bulk(3, 1, PID_IN, 13).stalled);
    assert.ok(bulk(3, 2, PID_OUT, 31, cbw(0, false, [0, 0, 0, 0, 0, 0])).stalled);
    assert.equal(control(3, setup(0x21, 0xFF, 0, 0, 0)).done, true, "BOT reset");
    assert.ok(bulk(3, 1, PID_IN, 13).stalled, "halted until cleared");
    assert.equal(control(3, setup(0x02, 1, 0, 0x81, 0)).done, true);
    assert.equal(control(3, setup(0x02, 1, 0, 0x02, 0)).done, true);
    toggles.clear();
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 0);
});

await test("a snapshot in the middle of a READ: the data goes on where it was", async () => {
    assert.ok(bulk(3, 2, PID_OUT, 31, cbw(8 * 512, true, read10(40, 8))).done);
    const first = bulk(3, 1, PID_IN, 1024).data;
    const toggles_saved = new Map(toggles);
    const state = await emulator.save_state();
    const rest = bulk(3, 1, PID_IN, 3072).data;
    await emulator.restore_state(state);
    toggles.clear();
    for(const [key, value] of toggles_saved) toggles.set(key, value);
    const again = bulk(3, 1, PID_IN, 3072).data;
    assert.deepEqual(again, rest);
    const all = new Uint8Array(4096);
    all.set(first);
    all.set(again, 1024);
    assert.deepEqual(all, image.slice(40 * 512, 48 * 512));
    assert.equal(csw(3).status, 0);
});

// --- a second disk: read only; then one whose reads come later ---------------------

const read_only = new Uint8Array(512 * 64).fill(0x5A);
await test("usb_attach_disk(read_only): in port 2; writes refused (DATA PROTECT), MODE SENSE's write protect bit; the image unchanged", async () => {
    await emulator.usb_attach_disk("ro", { buffer: read_only.buffer }, { read_only: true });
    assert.equal(r16(PORTSC2) & (CCS | CSC), CCS | CSC);
    enumerate(PORTSC2, 4);
    const r = scsi(4, write10(0, 1), 512, false, new Uint8Array(512));
    assert.equal(r.status, 1);
    assert.deepEqual(request_sense(4), [7, 0x27, 0]);
    assert.equal(scsi(4, [0x1A, 0, 0x3F, 0, 192, 0], 192).data[2] & 0x80, 0x80);
    assert.deepEqual(read_only, new Uint8Array(512 * 64).fill(0x5A));
    assert.deepEqual(scsi(4, read10(0, 1), 512).data, read_only.slice(0, 512));
});

await test("usb_detach_disk: out of its port (the guest sees it leave); an unknown id refused", async () => {
    await emulator.usb_detach_disk("ro");
    assert.equal(r16(PORTSC2) & (CCS | CSC | PE), CSC);
    await assert.rejects(emulator.usb_detach_disk("ro"));
    await assert.rejects(emulator.usb_attach_disk("stick", { buffer: new ArrayBuffer(512) }), /already/);
});

// a buffer object of one's own whose reads come back later
const slow_bytes = new Uint8Array(512 * 256).map((_, i) => i * 3 & 0xFF);
const pending = [];
class SlowBuffer
{
    constructor() { this.byteLength = slow_bytes.length; this.onload = undefined; }
    load() { this.onload && this.onload({}); }
    get(start, length, fn) { pending.push(() => fn(slow_bytes.slice(start, start + length))); }
    set(start, data, fn) { slow_bytes.set(data, start); fn(); }
    get_state() { return []; }
    set_state() {}
}
const slow = new SlowBuffer();
await test("a disk whose reads complete later: IN NAKs (the TD stays active) until the data is there", async () => {
    await emulator.usb_attach_disk("slow", slow);
    enumerate(PORTSC2, 5);
    assert.ok(bulk(5, 2, PID_OUT, 31, cbw(4096, true, read10(10, 8))).done);
    const waiting = bulk(5, 1, PID_IN, 4096, null, 5);
    assert.equal(waiting.done, false);
    assert.equal(waiting.length, 0, "nothing yet: NAK");
    assert.equal(pending.length, 1, "one read");
    pending.shift()();
    const r = bulk(5, 1, PID_IN, 4096);
    assert.ok(r.done);
    assert.deepEqual(r.data, slow_bytes.slice(10 * 512, 18 * 512));
    assert.equal(csw(5).status, 0);
});

await test("a bus reset in the middle of a READ: the read is dropped; the device starts afresh", async () => {
    assert.ok(bulk(5, 2, PID_OUT, 31, cbw(512, true, read10(0, 1))).done);
    enumerate(PORTSC2, 5);
    pending.shift()();
    assert.equal(pending.length, 0);
    const r = scsi(5, [0x00, 0, 0, 0, 0, 0]);
    assert.equal(r.status, 0);
});

await test("usb_plug: the disk out and back in (enumerated again), its image kept", async () => {
    await emulator.usb_plug("stick", false);
    assert.equal(r16(PORTSC1) & (CCS | CSC), CSC);
    await emulator.usb_plug("stick", true);
    assert.equal(r16(PORTSC1) & (CCS | CSC), CCS | CSC);
    enumerate(PORTSC1, 3);
    assert.deepEqual(scsi(3, read10(100, 1), 512).data, written.slice(0, 512));
});

await test("a snapshot with a disk this machine has no more: restored, it leaves (its port disconnected)", async () => {
    const state = await emulator.save_state();
    await emulator.usb_detach_disk("slow");
    await emulator.restore_state(state);
    assert.equal(r16(PORTSC2) & (CCS | CSC), CSC);
    assert.equal(r16(PORTSC1) & CCS, CCS, "the other disk still there");
    assert.equal(scsi(3, [0x00, 0, 0, 0, 0, 0]).status, 0);
});

// an image that fails its reads and writes (sectors 16 to 31), whose disk reports them
class FailingBuffer
{
    constructor() { this.bytes = new Uint8Array(512 * 64); this.byteLength = this.bytes.length; this.onload = undefined; this.disk_error = "report"; }
    load() { this.onload && this.onload({}); }
    bad(start, length) { return start < 32 * 512 && start + length > 16 * 512; }
    get(start, length, fn) { this.bad(start, length) ? fn(undefined, new Error("bad sector")) : fn(this.bytes.slice(start, start + length)); }
    set(start, data, fn) { if(this.bad(start, data.length)) fn(new Error("bad sector")); else { this.bytes.set(data, start); fn(); } }
    get_state() { return []; }
    set_state() {}
}
await test("an image's read and write errors (disk_error \"report\"): MEDIUM ERROR, the host's disk-error event; the disk goes on", async () => {
    const errors = [];
    const listener = e => errors.push(e.operation + " " + e.disk);
    emulator.add_listener("disk-error", listener);
    await emulator.usb_attach_disk("bad", new FailingBuffer());
    enumerate(PORTSC2, 6);
    const read = scsi(6, read10(14, 4), 2048);
    assert.equal(read.status, 1);
    assert.deepEqual(request_sense(6), [3, 0x11, 0]);
    const write = scsi(6, write10(20, 1), 512, false, new Uint8Array(512).fill(1));
    assert.equal(write.status, 1);
    assert.deepEqual(request_sense(6), [3, 0x0C, 0]);
    assert.deepEqual(scsi(6, read10(40, 1), 512).data, new Uint8Array(512), "elsewhere it reads");
    assert.deepEqual(errors, ["read usb:bad", "write usb:bad"]);
    emulator.remove_listener("disk-error", listener);
    await emulator.usb_detach_disk("bad");
});

await test("USB disks are disks: disk_buffer(\"usb:stick\"), disk_image_info", async () => {
    assert.equal(emulator.disk_buffer("usb:stick").byteLength, image.length);
    const info = await emulator.disk_image_info("usb:stick");
    assert.equal(info.size, image.length);
    assert.equal(info.logical_sector_size, 512);
});

await test("options: an id taken twice, too many disks for the ports", () => {
    const base = { graphics_adapter: "none", usb: { controller: "uhci", tablet: true, mass_storage: [] }, autostart: false };
    assert.throws(() => new V86({ ...base, usb: { ...base.usb, mass_storage: [{ id: "a", image: { buffer: new ArrayBuffer(512) } },
        { id: "a", image: { buffer: new ArrayBuffer(512) } }] } }), /taken/);
    assert.throws(() => new V86({ ...base, usb: { ...base.usb, mass_storage: [{ id: "a", image: { buffer: new ArrayBuffer(512) } },
        { id: "b", image: { buffer: new ArrayBuffer(512) } }] } }), /2 ports/);
    assert.throws(() => new V86({ ...base, usb: { ...base.usb, mass_storage: [{ id: "tablet", image: { buffer: new ArrayBuffer(512) } }] } }), /taken/);
});

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                   source/v64/tests/devices/usb_storage_guest.mjs                                                      0000755 0000000 0000000 00000030760 00000000000 016720  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// USB disks in a guest (usb.mass_storage, docs/usb.md,
// docs/modern-pc-devices-plan.md U2): Alpine 3.24 x86_64 (uhci-hcd,
// usb-storage, sd-mod) with a disk image on the UHCI controller. The disk
// seen (vendor, model, removable, size), data written through it and read
// back by SHA-256 on both sides of the image (the guest's page cache
// dropped), the time it took, a FAT file system made, mounted, written,
// unmounted and found in the image; a read-only disk attached at run time
// (writes refused), detached; the disk out of its port and back; an eject
// ("usb-disk-ejected"); a snapshot.
// Env: MACHINE (i440fx, q35), CPU_CORES (1), TEST_RELEASE_BUILD, SHOW_LOGS,
// USB_CONTROLLER (uhci; ehci: the disk at high speed, 480M, on the EHCI;
// xhci: at SuperSpeed, 5000M, on a USB 3 root port),
// USB_DISK_MB (64: the image; the data written is a quarter of it, at most 32 MiB),
// USB_WRITE_MB (none: a step that writes that many MiB, 16 MiB of random
// data again and again, reads them back and checks each copy, with the
// times: the plan's 1 GiB measure, USB_DISK_MB=1040 USB_WRITE_MB=1024).

import assert from "node:assert/strict";
import { createHash as create_hash } from "node:crypto";
import url from "node:url";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "i440fx";
const CONTROLLER = process.env.USB_CONTROLLER || "uhci";
const DISK_MB = +process.env.USB_DISK_MB || 64;
const WRITE_MB = +process.env.USB_WRITE_MB || 0;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const prepared = await prepare_alpine("x86_64-virt");
const directory = ROOT + "build/x64-linux/";
const image = new Uint8Array(DISK_MB << 20);
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    bzimage: { url: directory + "boot/vmlinuz-virt" },
    initrd: { url: directory + "boot/initramfs-virt" },
    cdrom: { url: directory + prepared.image.name },
    cmdline: "console=ttyS0,115200 loglevel=4 nokaslr modules=loop,squashfs,sd-mod,usb-storage",
    memory_size: 512 * 1024 * 1024,
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    acpi: true,
    net_device: { type: "none" },
    usb: { controller: CONTROLLER, tablet: false, mass_storage: [{ id: "stick", image: { buffer: image.buffer } }] },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, 1800 * 1000);

let serial = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});
const ejected = [];
emulator.add_listener("usb-disk-ejected", id => ejected.push(id));

const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send(cmd + "\n");
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(cmd.length).replace(PROMPT, "");
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}
const sha256 = bytes => create_hash("sha256").update(bytes).digest("hex");
/**
 * The SCSI disks in /sys/block, once `until` (a shell test) holds or after 30 s
 * @param {string} until
 * @return {!Promise<!Array<string>>}
 */
async function scsi_disks(until)
{
    const output = await command("for i in $(seq 30); do " + until + " && break; sleep 1; done; echo BLO''CKS $(ls /sys/block | grep sd)");
    return output.match(/^BLOCKS(.*)$/m)[1].trim().split(/\s+/).filter(Boolean);
}
/** The block device of a USB disk by its SCSI model, once it is there */
async function block_device(gone = false)
{
    const output = await command("for i in $(seq 30); do " + (gone ? "! " : "") + "grep -l 'USB Disk' /sys/block/sd*/device/model >/dev/null 2>&1 && break; " +
        "sleep 1; done; for d in /sys/block/sd*; do [ -e $d/device/model ] && echo $(basename $d) $(cat $d/device/vendor) $(cat $d/device/model) " +
        "$(cat $d/removable) $(cat $d/size) $(cat $d/ro); done");
    return output.split("\n").map(line => line.trim().split(/\s+/)).filter(f => /^sd[a-z]$/.test(f[0]))
        .map(f => ({ name: f[0], vendor: f[1], model: f[2] + " " + f[3], removable: +f[4], sectors: +f[5], ro: +f[6] }));
}

console.log("Booting Alpine x86_64 with a USB disk of " + DISK_MB + " MiB (" + CONTROLLER + ", " + MACHINE + ", " + CPU_CORES + " core" +
    (CPU_CORES > 1 ? "s" : "") + ")");
await wait_serial(/login: $/, "the login prompt", 600000);
serial = "";
emulator.serial0_send("root\n");
await wait_serial(PROMPT, "the shell", 120000);

let disk;
await step("usb-storage: the disk is sda, \"v86\" \"USB Disk\", removable, its size", async () => {
    const disks = await block_device();
    assert.equal(disks.length, 1, JSON.stringify(disks));
    disk = disks[0];
    assert.deepEqual([disk.vendor, disk.model, disk.removable, disk.sectors, disk.ro], ["v86", "USB Disk", 1, DISK_MB * 2048, 0]);
    // (the SCSI device's host's parent: the USB interface; its device's speed)
    const driver = await command("basename $(readlink /sys/block/" + disk.name + "/device/../../../driver)");
    assert.match(driver, /usb-storage/);
    const speed = await command("echo SPE''ED $(cat /sys/block/" + disk.name + "/device/../../../../speed)");
    assert.match(speed, CONTROLLER === "xhci" ? /^SPEED 5000$/m : CONTROLLER === "ehci" ? /^SPEED 480$/m : /^SPEED 12$/m);
});

await step("data written through the disk is in the image, and read back the same (SHA-256 on both sides)", async () => {
    // (from /tmp, a tmpfs of half the guest's memory)
    const mb = Math.min(DISK_MB / 4, 32);
    const output = await command("dd if=/dev/urandom of=/tmp/data bs=1M count=" + mb + " 2>/dev/null; sha256sum /tmp/data; " +
        "t=$(date +%s); dd if=/tmp/data of=/dev/" + disk.name + " bs=64k seek=16 conv=fsync 2>/dev/null; echo WROTE $(( $(date +%s) - t )); " +
        "echo 3 > /proc/sys/vm/drop_caches; t=$(date +%s); dd if=/dev/" + disk.name + " bs=64k skip=16 count=" + mb * 16 + " 2>/dev/null | sha256sum; " +
        "echo READ $(( $(date +%s) - t ))", 1200000);
    const sums = Array.from(output.matchAll(/^([0-9a-f]{64})/gm), m => m[1]);
    assert.equal(sums.length, 2, output);
    assert.equal(sums[1], sums[0], "read back");
    assert.equal(sha256(image.subarray(1 << 20, (1 + mb) << 20)), sums[0], "the image");
    const wrote = +output.match(/WROTE (\d+)/)[1], read = +output.match(/READ (\d+)/)[1];
    console.log("  " + mb + " MiB written in " + wrote + " s, read in " + read + " s (guest clock)");
});

if(WRITE_MB)
{
    await step(WRITE_MB + " MiB written (16 MiB of random data again and again), read back, each copy checked in the image", async () => {
        const copies = Math.ceil(WRITE_MB / 16);
        const output = await command("dd if=/dev/urandom of=/tmp/block bs=1M count=16 2>/dev/null; sha256sum /tmp/block; t=$(date +%s); i=0; " +
            "while [ $i -lt " + copies + " ]; do dd if=/tmp/block of=/dev/" + disk.name + " bs=1M seek=$((1 + i * 16)) 2>/dev/null; i=$((i + 1)); done; " +
            "sync; echo WROTE $(( $(date +%s) - t )); echo 3 > /proc/sys/vm/drop_caches; t=$(date +%s); i=0; " +
            "while [ $i -lt " + copies + " ]; do dd if=/dev/" + disk.name + " bs=1M skip=$((1 + i * 16)) count=16 2>/dev/null | sha256sum; i=$((i + 1)); done " +
            "| sort | uniq -c; echo READ $(( $(date +%s) - t ))", 3600000);
        const block = output.match(/^([0-9a-f]{64})/m)[1];
        assert.match(output, new RegExp("^\\s*" + copies + " " + block, "m"), "every copy read back: " + output);
        for(let i = 0; i < copies; i++)
        {
            assert.equal(sha256(image.subarray((1 + i * 16) << 20, (17 + i * 16) << 20)), block, "copy " + i + " in the image");
        }
        const wrote = +output.match(/WROTE (\d+)/)[1], read = +output.match(/READ (\d+)/)[1];
        console.log("  " + copies * 16 + " MiB written in " + wrote + " s (" + (copies * 16 / wrote).toFixed(1) + " MiB/s), read in " + read + " s (" +
            (copies * 16 / read).toFixed(1) + " MiB/s, guest clock)");
    });
}

await step("a FAT file system: made, mounted, a file written, unmounted (sync); the file in the image", async () => {
    // (markers split in the command, so that its echo does not match them)
    const output = await command("modprobe vfat; mkfs.vfat /dev/" + disk.name + " >/dev/null && mkdir -p /mnt/usb && " +
        "mount -t vfat /dev/" + disk.name + " /mnt/usb && echo v86-usb-disk-check > /mnt/usb/HELLO.TXT && umount /mnt/usb && echo DO''NE", 300000);
    assert.match(output, /^DONE/m);
    assert.ok(Buffer.from(image).includes("v86-usb-disk-check"), "the file's text in the image");
    assert.ok(Buffer.from(image).includes("HELLO   TXT"), "its directory entry");
});

let ro_disk;
const ro_image = new Uint8Array(4 << 20).fill(0x5A);
await step("usb_attach_disk(read_only): sdb, read only; a write refused; the image unchanged; usb_detach_disk: gone", async () => {
    await emulator.usb_attach_disk("ro", { buffer: ro_image.buffer }, { read_only: true });
    assert.equal((await scsi_disks("[ $(ls /sys/block | grep -c sd) = 2 ]")).length, 2);
    ro_disk = (await block_device()).find(d => d.name !== disk.name);
    assert.equal(ro_disk.ro, 1);
    const write = await command("dd if=/dev/zero of=/dev/" + ro_disk.name + " bs=512 count=1 oflag=direct 2>&1; echo STA''TUS $?");
    assert.match(write, /^STATUS [1-9]/m);
    assert.ok(ro_image.every(b => b === 0x5A));
    const read = await command("dd if=/dev/" + ro_disk.name + " bs=1M count=1 2>/dev/null | sha256sum");
    assert.equal(read.trim().slice(0, 64), sha256(ro_image.subarray(0, 1 << 20)));
    await emulator.usb_detach_disk("ro");
    assert.deepEqual(await scsi_disks("[ ! -e /sys/block/" + ro_disk.name + " ]"), [disk.name]);
});

await step("out of its port and back (usb_plug): gone, then the same disk again", async () => {
    await emulator.usb_plug("stick", false);
    assert.deepEqual(await scsi_disks("! ls /sys/block | grep -q sd"), []);
    await emulator.usb_plug("stick", true);
    disk = (await block_device())[0];
    assert.equal(disk.sectors, DISK_MB * 2048);
    const output = await command("mount -t vfat /dev/" + disk.name + " /mnt/usb && cat /mnt/usb/HELLO.TXT && umount /mnt/usb");
    assert.match(output, /^v86-usb-disk-check/m);
});

await step("a snapshot: restored, the disk reads as before", async () => {
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    serial = "";
    emulator.serial0_send("\n");
    await wait_serial(PROMPT, "the shell after restoring", 30000);
    const output = await command("mount -t vfat /dev/" + disk.name + " /mnt/usb && cat /mnt/usb/HELLO.TXT && umount /mnt/usb");
    assert.match(output, /^v86-usb-disk-check/m);
});

await step("eject: the guest ejects the medium (\"usb-disk-ejected\"), the disk has none then", async () => {
    // (-s: SCSI's ALLOW MEDIUM REMOVAL and START STOP UNIT, not the CD drive's ioctl)
    const output = await command("eject -s /dev/" + disk.name + "; echo STA''TUS $?; sleep 1; cat /sys/block/" + disk.name + "/size");
    assert.match(output, /^STATUS 0/m, output);
    assert.deepEqual(ejected, ["stick"]);
    assert.match(output, /^\s*0\s*$/m, "no medium: size 0");
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
                source/v64/tests/devices/usb_windows_xp.mjs                                                         0000755 0000000 0000000 00000033033 00000000000 016242  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// USB on Windows XP (docs/usb.md): the owner's XP image (i440FX, IDE, no
// ACPI: the standard PC HAL with the PIC) with the UHCI controller and the
// tablet. A tools disk has USBCHECK.EXE (tests/x64/windows_usb.c): it writes
// the controller's, the tablet's and its HID mouse's devices (Device
// Manager's problem code) and then the cursor's position every 300 ms, while
// the page's pointer goes to the corners, the centre and a 5x5 grid of the
// screen. Every device started without a problem (the controller, its root
// hub, the tablet and its mouse), and every position where the page's
// pointer was. A USB disk (U2, a FAT16 image in memory) in the second port:
// its devices started (usbstor), its file read, a file written to it (in
// the image afterwards). Takes about 10 minutes.
//
// Env: XP_IMAGE (retro-gaming-site/windowsxp/windowsxp_multidisk_C_4G.img,
// opened read only: writes stay in memory), XP_OUT (build/xp-usb: the
// screenshots), TEST_RELEASE_BUILD, XP_MEMORY_MB (512), XP_USB_CONTROLLER (uhci;
// ehci: EHCI with its companions, the USB disk at high speed).
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { deflateSync as deflate_sync, crc32 } from "node:zlib";
import { fileURLToPath } from "node:url";
import { MemoryDisk, ReadOnlyOverlayDisk, make_fat16, read_fat16 } from "../smp/disk_fixture.mjs";
import { site_directory } from "../lib/site.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const image_path = path.resolve(process.env.XP_IMAGE || path.join(site_directory(root), "windowsxp/windowsxp_multidisk_C_4G.img"));
const out = path.resolve(process.env.XP_OUT || path.join(root, "build/xp-usb"));
fs.mkdirSync(out, { recursive: true });
const image_mtime = fs.statSync(image_path).mtimeMs;
const CONTROLLER = process.env.XP_USB_CONTROLLER || "uhci";
const started = performance.now();
const elapsed = () => Math.round((performance.now() - started) / 1000);

// USBCHECK.EXE, 32-bit and without the CRT, as tests/x64/windows_boot.mjs builds it
const check = path.join(out, "USBCHECK.EXE");
const built = spawnSync("i686-w64-mingw32-gcc", ["-Os", "-nostdlib", "-fno-builtin", "-fno-stack-protector", "-mno-stack-arg-probe",
    "-Wl,--entry,_entry@0", "-Wl,--subsystem,console", "-o", check, path.join(root, "tests/x64/windows_usb.c"),
    "-lkernel32", "-luser32", "-lsetupapi", "-lcfgmgr32"], { encoding: "utf8" });
assert.equal(built.status, 0, built.stderr);
const tools = new MemoryDisk(make_fat16({ "USB.CMD": Buffer.from("@echo off\r\nstart %~d0\\USBCHECK.EXE\r\n"), "USBCHECK.EXE": fs.readFileSync(check) }));
const result_text = () => { const bytes = read_fat16(tools.bytes, "USB.TXT"); return bytes ? Buffer.from(bytes).toString("ascii") : ""; };
// the USB disk (another disk signature and volume serial than the tools disk's)
const usb_disk = make_fat16({ "USBDISK.TXT": Buffer.from("v86 USB disk check\r\n") });
new DataView(usb_disk.buffer).setUint32(440, 0x5B2026C3, true);
new DataView(usb_disk.buffer).setUint32(63 * 512 + 39, 0x5B2026C3, true);

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const vm = new V86({
    bios: { url: root + "bios/seabios.bin" },
    vga_bios: { url: root + "bios/vgabios.bin" },
    hda: new ReadOnlyOverlayDisk(image_path),
    hdb: tools,
    memory_size: (+process.env.XP_MEMORY_MB || 512) * 1048576,
    vram_size: 16 << 20,
    graphics_adapter: "bochs_vga",
    acpi: false,
    net_device: { type: "none" },
    usb: { controller: CONTROLLER, tablet: true, mass_storage: [{ id: "stick", image: { buffer: usb_disk.buffer } }] },
    autostart: true,
    log_level: 0,
});
const timeout = setTimeout(() => { console.log("Timeout"); process.exit(1); }, 1800 * 1000);
let tablet_active = false;
vm.add_listener("usb-tablet-active", value => { tablet_active = value; });
await new Promise(resolve => vm.add_listener("emulator-ready", resolve));
const cpu = vm.v86.cpu;

// The screen (bochs_vga's VBE mode), as a PNG in XP_OUT
function frame()
{
    const vga = cpu.devices.vga;
    if(!vga.svga_enabled || ![16, 24, 32].includes(vga.svga_bpp)) return null;
    const width = vga.svga_width, height = vga.svga_height, bytes_per = vga.svga_bpp / 8;
    const memory = new Uint8Array(cpu.wasm_memory.buffer, vga.svga_memory.byteOffset, vga.vga_memory_size);
    const stride = width * 3 + 1, raw = Buffer.alloc(stride * height), offset = vga.svga_offset * bytes_per;
    for(let y = 0; y < height; y++) for(let x = 0; x < width; x++)
    {
        const from = offset + (y * width + x) * bytes_per, to = y * stride + 1 + x * 3;
        if(bytes_per === 2)
        {
            const v = memory[from] | memory[from + 1] << 8;
            raw[to] = (v >> 11 & 31) << 3; raw[to + 1] = (v >> 5 & 63) << 2; raw[to + 2] = (v & 31) << 3;
        }
        else { raw[to] = memory[from + 2]; raw[to + 1] = memory[from + 1]; raw[to + 2] = memory[from]; }
    }
    return { width, height, raw };
}
function save(name, f)
{
    const chunk = (tag, data) =>
    {
        const body = Buffer.concat([Buffer.from(tag), data]), b = Buffer.alloc(data.length + 12);
        b.writeUInt32BE(data.length);
        body.copy(b, 4);
        b.writeUInt32BE(crc32(body), b.length - 4);
        return b;
    };
    const header = Buffer.alloc(13);
    header.writeUInt32BE(f.width);
    header.writeUInt32BE(f.height, 4);
    header[8] = 8;
    header[9] = 2;
    fs.writeFileSync(path.join(out, name), Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header),
        chunk("IDAT", deflate_sync(f.raw)), chunk("IEND", Buffer.alloc(0))]));
}

// The desktop: a graphics mode whose picture stays the same for 20 s
let last = null, same_since = 0;
for(;;)
{
    await delay(2000);
    const f = frame();
    const key = f && f.width + "x" + f.height + ":" + crc32(f.raw);
    if(key !== last) { last = key; same_since = performance.now(); if(f) save("screen.png", f); continue; }
    if(f && elapsed() > 60 && performance.now() - same_since > 20000) break;
}
let screen = frame();
save("desktop.png", screen);
console.log("desktop " + screen.width + "x" + screen.height + " at " + elapsed() + " s; the tablet " + (tablet_active ? "in use" : "not in use"));

const scans = {};
for(const [letters, codes] of [["1234567890", [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], ["qwertyuiop", [16, 17, 18, 19, 20, 21, 22, 23, 24, 25]],
    ["asdfghjkl", [30, 31, 32, 33, 34, 35, 36, 37, 38]], ["zxcvbnm", [44, 45, 46, 47, 48, 49, 50]]])
{
    [...letters].forEach((letter, i) => { scans[letter] = codes[i]; });
}
Object.assign(scans, { " ": 57, ".": 52, "/": 53, "\\": 43 });
const shifted = { ":": 39, "%": 6, "(": 10, ")": 11, "@": 3 };
async function type(text)
{
    for(const ch of text)
    {
        const code = shifted[ch] || scans[ch];
        assert.ok(code, "scan code for " + JSON.stringify(ch));
        await vm.keyboard_send_scancodes(shifted[ch] ? [42, code, code | 128, 170] : [code, code | 128], 30);
        await delay(60);
    }
}
const keys = { enter: [28, 156], down: [0xE0, 0x50, 0xE0, 0xD0], up: [0xE0, 0x48, 0xE0, 0xC8], tab: [15, 143], space: [57, 185],
    esc: [1, 129], "alt+n": [56, 49, 177, 184], "alt+f4": [56, 62, 190, 184] };

// XP_CONTROL=<file>: commands from that file, one per line, until "go" (to
// drive dialogs by hand): a key name of `keys`, "type <text>", "wait <s>";
// each batch ends with a screenshot (control.png)
if(process.env.XP_CONTROL)
{
    console.log("waiting for commands in " + process.env.XP_CONTROL);
    for(let go = false; !go;)
    {
        await delay(1000);
        if(!fs.existsSync(process.env.XP_CONTROL)) continue;
        const lines = fs.readFileSync(process.env.XP_CONTROL, "utf8").split("\n").map(line => line.trim()).filter(Boolean);
        fs.unlinkSync(process.env.XP_CONTROL);
        for(const line of lines)
        {
            if(line === "go") go = true;
            else if(line.startsWith("type ")) await type(line.slice(5));
            else if(line.startsWith("wait ")) await delay(1000 * +line.slice(5));
            else if(keys[line]) await vm.keyboard_send_scancodes(keys[line], 30);
            else console.log("unknown command " + line);
            await delay(300);
        }
        await delay(1000);
        save("control.png", frame());
        console.log("done: " + lines.join("; ") + " (tablet " + (tablet_active ? "in use" : "not in use") + ")");
    }
}

// The image has no driver for bochs_vga's display: XP's Found New Hardware
// wizard asks for one, and installs the USB devices' drivers only after it
// (it takes one new device at a time). Cancelled, until the tablet is in use.
for(let i = 0; !tablet_active; i++)
{
    assert.ok(i < 6, "the guest did not configure the tablet");
    await vm.keyboard_send_scancodes(keys.esc, 30);
    for(const limit = performance.now() + 30000; !tablet_active && performance.now() < limit;) await delay(1000);
}
console.log("the tablet in use at " + elapsed() + " s");

async function wait_file(text, seconds)
{
    for(const limit = performance.now() + seconds * 1000; performance.now() < limit;)
    {
        if(result_text().includes(text)) return true;
        await delay(2000);
        const f = frame();
        if(f) save("screen.png", f);
    }
    return false;
}

// Win+R, USB.CMD from the tools disk. Having installed the drivers, XP may
// ask to restart (Yes/No) and take the keys meant for the Run dialog: No
// first (Alt+N does nothing on the desktop); an error box after keys went
// astray takes Enter; then again.
for(let attempt = 0; ; attempt++)
{
    assert.ok(attempt < 3, "USB.TXT without READY: " + JSON.stringify(result_text()));
    await delay(attempt ? 2000 : 20000);
    await vm.keyboard_send_scancodes(keys["alt+n"], 30);
    await delay(2000);
    await vm.keyboard_send_scancodes([0xE0, 0x5B, 0x13, 0x93, 0xE0, 0xDB], 30);
    await delay(3000);
    await type("cmd /c for %d in (d e f g h) do @if exist %d:\\usb.cmd %d:\\usb.cmd");
    await vm.keyboard_send_scancodes(keys.enter, 30);
    if(await wait_file("READY", 240)) break;
    save("attempt-" + attempt + ".png", frame());
    await vm.keyboard_send_scancodes(keys.enter, 30);
}
screen = frame();
const points = [[0, 0], [screen.width - 1, 0], [0, screen.height - 1], [screen.width - 1, screen.height - 1],
    [screen.width >> 1, screen.height >> 1]];
for(let i = 0; i < 5; i++) for(let j = 0; j < 5; j++) points.push([Math.round(i * (screen.width - 1) / 4), Math.round(j * (screen.height - 1) / 4)]);
for(const [x, y] of points)
{
    vm.bus.send("mouse-absolute", [x, y, screen.width, screen.height]);
    await delay(2500);
}
// (USBCHECK.EXE stops logging there)
vm.bus.send("mouse-absolute", [3, 5, screen.width, screen.height]);
assert.ok(await wait_file("END", 300), "USB.TXT without END");
save("end.png", frame());

const text = result_text();
console.log(text.split("\r\n").filter(line => !line.startsWith("POS")).join("\n"));
const devices = text.split("\r\n").filter(line => line.startsWith("DEVICE"));
const controllers = CONTROLLER === "ehci" ? ["PCI\\VEN_8086&DEV_293A", "PCI\\VEN_8086&DEV_2934", "PCI\\VEN_8086&DEV_2935", "PCI\\VEN_8086&DEV_2936",
    "USB\\ROOT_HUB20"] : ["PCI\\VEN_8086&DEV_7020"];
for(const id of [...controllers, "USB\\ROOT_HUB", "USB\\VID_0627&PID_0001", "HID\\VID_0627&PID_0001", "USB\\VID_46F4&PID_0001", "USBSTOR\\DISK"])
{
    // (every one of them: the root hubs of the EHCI and the companions)
    const lines = devices.filter(d => d.startsWith("DEVICE " + id));
    assert.ok(lines.length, id + " present");
    for(const line of lines) assert.match(line, /error=0 .*\| started/, line);
}
// the USB disk: its file read, FROMWIN.TXT written into the image
assert.match(text, /^DISK [D-Z]:\\ v86 USB disk check\r?$/m);
assert.match(text, /^DISK WRITTEN\r?$/m);
const written = read_fat16(usb_disk, "FROMWIN.TXT");
assert.ok(written && Buffer.from(written).toString("ascii").startsWith("written by Windows"), "FROMWIN.TXT in the USB disk's image");
console.log("USB disk: USBDISK.TXT read, FROMWIN.TXT in the image");
const usb_devices = await vm.usb_devices();
console.log("USB devices: " + usb_devices.map(d => d.id + " " + d.controller + " " + d.speed + " Mbit/s").join(", "));
if(CONTROLLER === "ehci")
{
    assert.deepEqual(usb_devices.map(d => [d.id, d.controller, d.speed]), [["tablet", "uhci", 12], ["stick", "ehci", 480]]);
}

// The positions in order: each point seen (within a pixel), held for at
// least two samples
const runs = [];
for(const [, x, y] of text.matchAll(/^POS (-?\d+) (-?\d+)/gm))
{
    const run = runs[runs.length - 1];
    if(run && run.x === +x && run.y === +y) run.n++;
    else runs.push({ x: +x, y: +y, n: 1 });
}
let at = 0, worst = 0;
const missing = [];
for(const [x, y] of points)
{
    const found = runs.findIndex((r, i) => i >= at && Math.abs(r.x - x) <= 1 && Math.abs(r.y - y) <= 1 && r.n >= 2);
    if(found < 0) { missing.push(x + "," + y); continue; }
    worst = Math.max(worst, Math.abs(runs[found].x - x), Math.abs(runs[found].y - y));
    at = found + 1;
}
console.log("positions: " + (points.length - missing.length) + " of " + points.length + " seen, worst error " + worst + " px" +
    (missing.length ? ", missing " + missing.join(" ") : ""));
console.log("runs: " + runs.map(r => r.x + "," + r.y + "x" + r.n).join(" "));
assert.equal(fs.statSync(image_path).mtimeMs, image_mtime, "the image is unchanged");
// (a point the guest did not run during is no error of the tablet's: allow one)
assert.ok(missing.length <= 1, "missing positions: " + missing.join(" "));
clearTimeout(timeout);
await vm.destroy();
console.log("PASS");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/devices/usb_xhci.js                                                                0000755 0000000 0000000 00000071353 00000000000 014626  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// xHCI (usb.controller "xhci", src/usb/xhci.js, docs/usb.md): QEMU's
// qemu-xhci, driven through its registers and its rings and contexts in
// guest memory, no guest code; the test moves the machine clock
// (docs/modern-pc-devices-plan.md U4). The PCI function and its
// capabilities, the capability registers and the extended capabilities
// (legacy support, the two supported protocols), the ports (the SuperSpeed
// USB disk on a USB 3 root port, enabled at once; the full-speed tablet on
// a USB 2 one, enabled by a reset), the command ring (slots, Address Device
// with and without BSR, Configure Endpoint, Evaluate Context, Stop and Reset
// Endpoint, Set TR Dequeue Pointer, Reset Device, no-op, errors), the
// transfer rings (control transfers at SuperSpeed: the device and BOS
// descriptors; BOT on bulk endpoints of 1024 bytes over TDs of several
// TRBs, a short packet with ISP, Event Data, STALL; the tablet's interrupt
// endpoint), the event ring (cycle bits, its wrap, EHB, INTx and MSI),
// Port Status Change Events, hot plug, snapshots, HCRST.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SECTORS = 8192;
const pattern = i => (i * 13 + (i >> 9)) & 0xFF;
const image = new Uint8Array(SECTORS * 512).map((_, i) => pattern(i));

let host = 1000;
const options = machine_type => ({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    memory_size: 64 * 1024 * 1024,
    machine_type,
    acpi: machine_type === "q35",
    usb: { controller: "xhci", tablet: true, mass_storage: [{ id: "stick", image: { buffer: image.buffer } }] },
    net_device: { type: "none" },
    cpu_clock: { mode: "normal", now: () => host },
    autostart: false,
    log_level: 0,
});
async function machine(machine_type)
{
    const emulator = new V86(options(machine_type));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume();
    return emulator;
}

let failed = 0, passed = 0;
async function test(name, f)
{
    try
    {
        await f();
        passed++;
        console.log("ok - " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL - " + name);
        console.log(e);
    }
}

const emulator = await machine("q35");
const cpu = emulator.v86.cpu;
const pci = cpu.devices.pci;
const mem = cpu.mem8;
const XHCI = 0x14 << 3;
const BAR = 0xC0000000;

const r32 = offset => cpu.mmap_read32(BAR + offset) >>> 0;
const r8 = offset => cpu.mmap_read8(BAR + offset);
const w32 = (offset, value) => cpu.mmap_write32(BAR + offset, value | 0);
const u32 = a => (mem[a] | mem[a + 1] << 8 | mem[a + 2] << 16 | mem[a + 3] << 24) >>> 0;
const put32 = (a, v) => { mem[a] = v; mem[a + 1] = v >> 8; mem[a + 2] = v >> 16; mem[a + 3] = v >>> 24; };
const irq = () => !!pci.intx_levels[XHCI];

const OP = 0x40, USBCMD = OP, USBSTS = OP + 4, CRCR = OP + 0x18, DCBAAP = OP + 0x30, CONFIG = OP + 0x38;
const PORTSC = port => OP + 0x400 + 0x10 * (port - 1);
const RT = 0x1000, IMAN = RT + 0x20, ERSTSZ = RT + 0x28, ERSTBA = RT + 0x30, ERDP = RT + 0x38;
const DB = target => 0x2000 + 4 * target;
const RS = 1, HCRST = 2, INTE = 4;
const HCH = 1, EINT = 8, PCD = 16;
const CCS = 1, PED = 2, PR = 1 << 4, PLS = 0xF << 5, SPEED = 0xF << 10, CSC = 1 << 17, PRC = 1 << 21;
const NORMAL = 1, SETUP = 2, DATA = 3, STATUS = 4, LINK = 6, EVENT_DATA = 7, ENABLE_SLOT = 9, DISABLE_SLOT = 10, ADDRESS_DEVICE = 11,
    CONFIGURE_ENDPOINT = 12, EVALUATE_CONTEXT = 13, RESET_ENDPOINT = 14, STOP_ENDPOINT = 15, SET_TR_DEQUEUE = 16, RESET_DEVICE = 17,
    NOOP_COMMAND = 23, TRANSFER_EVENT = 32, COMMAND_EVENT = 33, PORT_EVENT = 34;
const CYCLE = 1, TC = 2, ISP = 4, CH = 16, IOC = 32, IDT = 64, DIR_IN = 1 << 16;
const SUCCESS = 1, STALL_ERROR = 6, SHORT_PACKET = 13, CONTEXT_STATE = 19, TRB_ERROR = 5, STOPPED = 26;

/** Move the machine clock on and run the machine's timers */
function advance(ms)
{
    for(let i = 0; i < ms; i++)
    {
        host += 1;
        cpu.run_hardware_timers(false, cpu.clock.now());
    }
}

// guest memory: the DCBAA, the command ring, the event ring and its ERST,
// input contexts, output contexts, transfer rings, data
const DCBAA = 0x100000, COMMANDS = 0x101000, EVENTS = 0x102000, ERST = 0x103000, INPUT = 0x104000, OUTPUT = 0x110000,
    RINGS = 0x200000, BUFFER = 0x800000;
const EVENT_TRBS = 32;

/** A ring the test writes: TRBs, a Link TRB (toggle cycle) at its end */
class Ring
{
    constructor(base, size) { this.base = base; this.size = size; this.index = 0; this.cycle = 1; }
    push(low, high, status, control)
    {
        if(this.index === this.size - 1)
        {
            // (a Link TRB back to the start, toggling the cycle)
            this.write(this.base + 16 * this.index, this.base, 0, 0, LINK << 10 | TC);
            this.index = 0;
            this.cycle ^= 1;
        }
        const at = this.base + 16 * this.index;
        this.write(at, low, high, status, control);
        this.index++;
        return at;
    }
    write(target, low, high, status, control)
    {
        put32(target, low);
        put32(target + 4, high);
        put32(target + 8, status || 0);
        put32(target + 12, (control & ~CYCLE | this.cycle) >>> 0);
    }
}

let commands, events_index = 0, events_cycle = 1;
/** The events the controller wrote since, the dequeue pointer moved past them (EHB cleared) */
function events()
{
    const list = [];
    for(;;)
    {
        const at = EVENTS + 16 * events_index;
        const control = u32(at + 12);
        if((control & 1) !== events_cycle) break;
        list.push({ at, low: u32(at), high: u32(at + 4), status: u32(at + 8), control, type: control >> 10 & 0x3F, code: u32(at + 8) >>> 24,
            slot: control >>> 24, dci: control >> 16 & 0x1F, length: u32(at + 8) & 0xFFFFFF });
        events_index++;
        if(events_index === EVENT_TRBS) { events_index = 0; events_cycle ^= 1; }
    }
    w32(ERDP, EVENTS + 16 * events_index | 8);
    w32(ERDP + 4, 0);
    return list;
}
/** A command: its completion event */
function command(type, low = 0, high = 0, control = 0)
{
    const at = commands.push(low, high, 0, type << 10 | control);
    w32(DB(0), 0);
    const list = events().filter(e => e.type === COMMAND_EVENT);
    assert.equal(list.length, 1, "one completion");
    assert.equal(list[0].low, at, "for the command");
    return list[0];
}

// --- PCI, the registers -------------------------------------------------------------

await test("PCI: QEMU's qemu-xhci (1B36:000D, 0C/03/30) at 00:14.0, INTA; BAR0 16 KiB of memory; PM and MSI; SBRN 3.0", () => {
    const space = pci.space_bytes(XHCI);
    assert.equal(space[0] | space[1] << 8, 0x1B36);
    assert.equal(space[2] | space[3] << 8, 0x000D);
    assert.deepEqual([space[0x0B], space[0x0A], space[0x09]], [0x0C, 0x03, 0x30]);
    assert.equal(space[0x3D], 1);
    assert.equal(space[0x60], 0x30);
    assert.deepEqual([space[0x34], space[0x50], space[0x51], space[0x70]], [0x50, 0x01, 0x70, 0x05]);
    pci.config_write(XHCI, 0x10, 4, -1);
    assert.equal((space[0x10] | space[0x11] << 8 | space[0x12] << 16 | space[0x13] << 24) >>> 0, 0xFFFFC000);
    pci.config_write(XHCI, 0x10, 4, BAR);
    pci.config_write(XHCI, 0x04, 2, 0x0006);
});

await test("capability registers: CAPLENGTH 0x40, 1.0, 32 slots, 1 interrupter, 8 ports; 64-bit; doorbells, runtime; extended capabilities", () => {
    assert.equal(r8(0), 0x40);
    assert.equal(r32(0) >>> 16, 0x0100);
    assert.equal(r32(4), 32 | 1 << 8 | 8 << 24);
    assert.equal(r32(0x10) & 1, 1);
    assert.equal(r32(0x14), 0x2000);
    assert.equal(r32(0x18), 0x1000);
    const xecp = (r32(0x10) >>> 16) * 4;
    // legacy support, then the supported protocols: USB 3 ports 1-4, USB 2 ports 5-8
    assert.equal(r32(xecp) & 0xFF, 1);
    const usb3 = xecp + 4 * (r32(xecp) >> 8 & 0xFF);
    assert.deepEqual([r32(usb3) & 0xFF, r32(usb3) >>> 24, r32(usb3 + 4), r32(usb3 + 8) & 0xFFFF], [2, 3, 0x20425355, 1 | 4 << 8]);
    const usb2 = usb3 + 4 * (r32(usb3) >> 8 & 0xFF);
    assert.deepEqual([r32(usb2) & 0xFF, r32(usb2) >>> 24, r32(usb2 + 8) & 0xFFFF], [2, 2, 5 | 4 << 8]);
    assert.equal(r32(usb2) >> 8 & 0xFF, 0, "the last");
    // the OS taking the controller: the BIOS lets go at once
    w32(xecp, 1 << 24);
    assert.equal(r32(xecp) & (1 << 16 | 1 << 24), 1 << 24);
});

await test("ports: the SuperSpeed disk on USB 3 port 2, enabled (U0, speed 4); the full-speed tablet on USB 2 port 5, polling", () => {
    assert.equal(r32(USBSTS) & HCH, HCH);
    assert.equal(r32(PORTSC(2)) & (CCS | PED | PLS | SPEED), CCS | PED | 0 << 5 | 4 << 10);
    assert.equal(r32(PORTSC(5)) & (CCS | PED | PLS | SPEED), CCS | 7 << 5 | 1 << 10);
    assert.equal(r32(PORTSC(1)) & CCS, 0);
    assert.equal(r32(PORTSC(6)) & CCS, 0, "the disk not on its USB 2 port");
    assert.equal(r32(PORTSC(2)) & CSC, CSC);
});

await test("running: the command ring, the event ring (one segment), interrupts on; a no-op command completes (an event, IP, EINT, INTA)", () => {
    for(let i = 0; i < 33; i++) { put32(DCBAA + 8 * i, 0); put32(DCBAA + 8 * i + 4, 0); }
    w32(DCBAAP, DCBAA);
    w32(DCBAAP + 4, 0);
    w32(CONFIG, 32);
    commands = new Ring(COMMANDS, 16);
    w32(CRCR, COMMANDS | 1);
    w32(CRCR + 4, 0);
    put32(ERST, EVENTS);
    put32(ERST + 4, 0);
    put32(ERST + 8, EVENT_TRBS);
    mem.fill(0, EVENTS, EVENTS + 16 * EVENT_TRBS);
    w32(ERSTSZ, 1);
    w32(ERDP, EVENTS);
    w32(ERDP + 4, 0);
    w32(ERSTBA, ERST);
    w32(ERSTBA + 4, 0);
    w32(IMAN, 2);
    w32(USBCMD, RS | INTE);
    assert.equal(r32(USBSTS) & HCH, 0);
    const done = command(NOOP_COMMAND);
    assert.equal(done.code, SUCCESS);
    assert.ok(irq());
    assert.equal(r32(USBSTS) & EINT, EINT);
    w32(IMAN, 3);
    w32(USBSTS, EINT);
    assert.ok(!irq());
});

await test("a port change while running: its Port Status Change Event (port, PCD); a USB 2 reset enables the tablet's port (PRC)", () => {
    w32(PORTSC(5), PR);
    const list = events();
    assert.deepEqual(list.map(e => [e.type, e.low >>> 24]), [[PORT_EVENT, 5]]);
    assert.equal(r32(PORTSC(5)) & (PED | PLS | PRC), PED | PRC);
    assert.equal(r32(USBSTS) & PCD, PCD);
    w32(PORTSC(5), PRC | CSC);
    w32(PORTSC(2), CSC);
    assert.equal(r32(PORTSC(5)) & (PRC | CSC), 0);
    w32(USBSTS, PCD);
});

// slots, contexts, transfer rings
const ring_of = new Map();
/** The transfer ring of a slot's endpoint */
function ring(slot, dci)
{
    const key = slot + ":" + dci;
    if(!ring_of.has(key)) ring_of.set(key, new Ring(RINGS + (slot * 32 + dci) * 0x400, 64));
    return ring_of.get(key);
}
/** An input context: the add flags, the slot context, endpoint contexts by DCI ([type, max packet, interval]) */
function input(add, slot_words, endpoints = {})
{
    mem.fill(0, INPUT, INPUT + 32 * 33);
    put32(INPUT + 4, add);
    slot_words.forEach((w, i) => put32(INPUT + 32 + 4 * i, w));
    for(const [dci, [type, max_packet, interval]] of Object.entries(endpoints))
    {
        const at = INPUT + 32 * (+dci + 1);
        const r = ring(current_slot, +dci);
        put32(at, interval << 16);
        put32(at + 4, 3 << 1 | type << 3 | max_packet << 16);
        put32(at + 8, r.base + 16 * r.index | r.cycle);
        put32(at + 12, 0);
        put32(at + 16, 8);
    }
    return INPUT;
}
let current_slot = 0;
const output = slot => OUTPUT + 0x1000 * slot;
const slot_state = slot => u32(output(slot) + 12) >>> 27;
const endpoint_state = (slot, dci) => u32(output(slot) + 32 * dci) & 7;
/** Enable a slot for a root port and address its device */
function new_device(port, speed, bsr = false)
{
    const enabled = command(ENABLE_SLOT);
    assert.equal(enabled.code, SUCCESS);
    const slot = current_slot = enabled.slot;
    mem.fill(0, output(slot), output(slot) + 0x400);
    put32(DCBAA + 8 * slot, output(slot));
    const address = command(ADDRESS_DEVICE, input(3, [speed << 20 | 1 << 27, port << 16, 0, 0], { 1: [4, speed === 4 ? 512 : 64, 0] }), 0,
        slot << 24 | (bsr ? 1 << 9 : 0));
    return { slot, code: address.code };
}
/** A control transfer on endpoint 0: Setup, Data (IN), Status; the data and the events */
function control(slot, setup_bytes, length, extra = 0)
{
    const r = ring(slot, 1);
    const low = setup_bytes[0] | setup_bytes[1] << 8 | setup_bytes[2] << 16 | setup_bytes[3] << 24;
    const high = setup_bytes[4] | setup_bytes[5] << 8 | setup_bytes[6] << 16 | setup_bytes[7] << 24;
    const into = setup_bytes[0] & 0x80;
    r.push(low, high, 8, SETUP << 10 | IDT | (length ? (into ? 3 : 2) << 16 : 0));
    if(length) r.push(BUFFER, 0, length, DATA << 10 | ISP | (into ? DIR_IN : 0) | extra);
    r.push(0, 0, 0, STATUS << 10 | IOC | (into && length ? 0 : DIR_IN));
    w32(DB(slot), 1);
    advance(2);
    const list = events().filter(e => e.type === TRANSFER_EVENT);
    const short = list.find(e => e.code === SHORT_PACKET);
    return { data: mem.slice(BUFFER, BUFFER + length - (short ? short.length : 0)), events: list };
}
const setup = (type, request, value, index, length) => [type, request, value & 0xFF, value >> 8, index & 0xFF, index >> 8, length & 0xFF, length >> 8];

let disk;
await test("Enable Slot, Address Device (the USB 3 port): the slot Addressed at its ID, endpoint 0 running; GET_DESCRIPTOR: USB 3, 2^9", () => {
    disk = new_device(2, 4);
    assert.equal(disk.code, SUCCESS);
    assert.equal(slot_state(disk.slot), 2);
    assert.equal(u32(output(disk.slot) + 12) & 0xFF, disk.slot, "the device's address");
    assert.equal(endpoint_state(disk.slot, 1), 1);
    const device = control(disk.slot, setup(0x80, 6, 0x0100, 0, 18), 18);
    assert.deepEqual([device.data[2] | device.data[3] << 8, device.data[7], device.data[8] | device.data[9] << 8], [0x0300, 9, 0x46F4]);
    assert.deepEqual(device.events.map(e => [e.code, e.slot, e.dci]), [[SUCCESS, disk.slot, 1]]);
});

await test("SuperSpeed descriptors: the BOS (USB 2.0 extension, SuperSpeed capability), the configuration (bulk 1024, companions); no device qualifier", () => {
    const bos = control(disk.slot, setup(0x80, 6, 0x0F00, 0, 22), 22).data;
    assert.deepEqual([bos[1], bos[2], bos[4], bos[7], bos[14]], [0x0F, 22, 2, 2, 3]);
    const config = control(disk.slot, setup(0x80, 6, 0x0200, 0, 44), 44).data;
    assert.equal(config.length, 44);
    assert.deepEqual([config[18 + 4] | config[18 + 5] << 8, config[25 + 1], config[31 + 4] | config[31 + 5] << 8, config[38 + 1]], [1024, 0x30, 1024, 0x30]);
    const qualifier = control(disk.slot, setup(0x80, 6, 0x0600, 0, 10), 10);
    assert.deepEqual(qualifier.events.map(e => e.code), [STALL_ERROR], "STALL");
    assert.equal(endpoint_state(disk.slot, 1), 2, "endpoint 0 halted");
    assert.equal(command(RESET_ENDPOINT, 0, 0, disk.slot << 24 | 1 << 16).code, SUCCESS);
    assert.equal(endpoint_state(disk.slot, 1), 3, "stopped");
    // (the ring on past the failed TD: Set TR Dequeue Pointer)
    const r = ring(disk.slot, 1);
    assert.equal(command(SET_TR_DEQUEUE, r.base + 16 * r.index | r.cycle, 0, disk.slot << 24 | 1 << 16).code, SUCCESS);
    // SET_ISOCH_DELAY and SET_CONFIGURATION
    assert.deepEqual(control(disk.slot, setup(0x00, 0x31, 40, 0, 0), 0).events.map(e => e.code), [SUCCESS]);
    assert.deepEqual(control(disk.slot, setup(0x00, 9, 1, 0, 0), 0).events.map(e => e.code), [SUCCESS]);
});

await test("Configure Endpoint: bulk IN (DCI 3) and OUT (DCI 4) running, the slot Configured; Evaluate Context: endpoint 0's max packet", () => {
    const done = command(CONFIGURE_ENDPOINT, input(1 | 1 << 3 | 1 << 4, [4 << 20 | 4 << 27, 2 << 16, 0, 0], { 3: [6, 1024, 0], 4: [2, 1024, 0] }), 0,
        disk.slot << 24);
    assert.equal(done.code, SUCCESS);
    assert.equal(slot_state(disk.slot), 3);
    assert.deepEqual([endpoint_state(disk.slot, 3), endpoint_state(disk.slot, 4)], [1, 1]);
    assert.equal(u32(output(disk.slot)) >>> 27, 4, "context entries");
    mem.fill(0, INPUT, INPUT + 96);
    put32(INPUT + 4, 2);
    put32(INPUT + 64 + 4, 512 << 16);
    assert.equal(command(EVALUATE_CONTEXT, INPUT, 0, disk.slot << 24).code, SUCCESS);
    assert.equal(u32(output(disk.slot) + 32 + 4) >>> 16, 512);
});

let tags = 0;
/** A bulk transfer in Normal TRBs of up to 16 KiB (ISP; IOC on the last): its events */
function bulk(dci, length, out = null, event_data = false)
{
    if(out) mem.set(out, BUFFER);
    const r = ring(disk.slot, dci);
    for(let at = 0; at < length || at === 0 && length === 0; at += 16384)
    {
        const n = Math.min(16384, length - at), last = at + 16384 >= length;
        r.push(BUFFER + at, 0, n, NORMAL << 10 | ISP | (last && !event_data ? IOC : CH));
        if(length === 0) break;
    }
    if(event_data) r.push(0x12345678, 0x9ABC, 0, EVENT_DATA << 10 | IOC);
    w32(DB(disk.slot), dci);
    for(let i = 0; i < 100 && !events_pending(); i++) advance(1);
    return events().filter(e => e.type === TRANSFER_EVENT);
}
function events_pending()
{
    return (u32(EVENTS + 16 * events_index + 12) & 1) === events_cycle;
}
function scsi(cb, length = 0, direction_in = true, out = null)
{
    const cbw = new Uint8Array(31);
    const view = new DataView(cbw.buffer);
    view.setUint32(0, 0x43425355, true);
    view.setUint32(4, ++tags, true);
    view.setUint32(8, length, true);
    cbw[12] = direction_in ? 0x80 : 0;
    cbw[14] = cb.length;
    cbw.set(cb, 15);
    assert.deepEqual(bulk(4, 31, cbw).map(e => e.code), [SUCCESS], "the CBW");
    let data = null;
    if(length)
    {
        const list = bulk(direction_in ? 3 : 4, length, out);
        assert.ok(list.length && list.every(e => e.code === SUCCESS || e.code === SHORT_PACKET), JSON.stringify(list));
        data = mem.slice(BUFFER, BUFFER + length);
    }
    const csw = bulk(3, 13);
    assert.deepEqual(csw.map(e => e.code), [SUCCESS]);
    return { data, status: mem[BUFFER + 12], tag: u32(BUFFER + 4) };
}
const read10 = (lba, count) => [0x28, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];
const write10 = (lba, count) => [0x2A, 0, lba >>> 24, lba >> 16 & 0xFF, lba >> 8 & 0xFF, lba & 0xFF, 0, count >> 8, count & 0xFF, 0];

await test("the USB disk at SuperSpeed: INQUIRY, READ(10) of 96 sectors (TDs of several TRBs), WRITE(10) of 100 sectors", () => {
    const inquiry = scsi([0x12, 0, 0, 0, 36, 0], 36);
    assert.equal(inquiry.tag, tags);
    assert.equal(new TextDecoder().decode(inquiry.data.subarray(8, 16)), "v86     ");
    const read = scsi(read10(9, 96), 96 * 512);
    assert.equal(read.status, 0);
    assert.deepEqual(read.data, image.slice(9 * 512, 105 * 512));
    const data = new Uint8Array(100 * 512).map((_, i) => i * 3 + 1 & 0xFF);
    assert.equal(scsi(write10(300, 100), data.length, false, data).status, 0);
    assert.deepEqual(image.slice(300 * 512, 400 * 512), data);
});

await test("a short packet: the CSW into a TRB of 512 (ISP): Short Packet, the bytes left; Event Data: its parameter and the bytes so far (ED)", () => {
    const cbw = new Uint8Array(31);
    new DataView(cbw.buffer).setUint32(0, 0x43425355, true);
    new DataView(cbw.buffer).setUint32(4, 77, true);
    cbw[14] = 6;
    assert.deepEqual(bulk(4, 31, cbw).map(e => e.code), [SUCCESS]);
    const short = bulk(3, 512);
    assert.deepEqual(short.map(e => [e.code, e.length]), [[SHORT_PACKET, 512 - 13]]);
    // INQUIRY's data with an Event Data TRB after its Normal TRB
    const inquiry = new Uint8Array(31);
    new DataView(inquiry.buffer).setUint32(0, 0x43425355, true);
    new DataView(inquiry.buffer).setUint32(4, 78, true);
    new DataView(inquiry.buffer).setUint32(8, 36, true);
    inquiry[12] = 0x80;
    inquiry[14] = 6;
    inquiry.set([0x12, 0, 0, 0, 36, 0], 15);
    bulk(4, 31, inquiry);
    const list = bulk(3, 36, null, true);
    assert.deepEqual(list.map(e => [e.code, e.low, e.high, e.length, e.control >> 2 & 1]), [[SUCCESS, 0x12345678, 0x9ABC, 36, 1]]);
    assert.deepEqual(bulk(3, 13).map(e => e.code), [SUCCESS]);
});

await test("STALL on bulk (a command past the end... with a CBW that is not one): the endpoint halts; Reset Endpoint, Set TR Dequeue; on", () => {
    // an invalid CBW: both bulk endpoints STALL until the reset recovery
    const bad = new Uint8Array(31);
    bulk(4, 31, bad);
    const stalled = bulk(3, 13);
    assert.deepEqual(stalled.map(e => e.code), [STALL_ERROR]);
    assert.equal(endpoint_state(disk.slot, 3), 2);
    assert.equal(command(RESET_ENDPOINT, 0, 0, disk.slot << 24 | 3 << 16).code, SUCCESS);
    assert.equal(command(RESET_ENDPOINT, 0, 0, disk.slot << 24 | 3 << 16).code, CONTEXT_STATE, "only a halted one");
    const r = ring(disk.slot, 3);
    assert.equal(command(SET_TR_DEQUEUE, r.base + 16 * r.index | r.cycle, 0, disk.slot << 24 | 3 << 16).code, SUCCESS);
    // the reset recovery: BOT reset, CLEAR_FEATURE(ENDPOINT_HALT) of both
    control(disk.slot, setup(0x21, 0xFF, 0, 0, 0), 0);
    control(disk.slot, setup(0x02, 1, 0, 0x81, 0), 0);
    control(disk.slot, setup(0x02, 1, 0, 0x02, 0), 0);
    assert.equal(endpoint_state(disk.slot, 4), 1, "OUT running");
    assert.equal(scsi([0x00, 0, 0, 0, 0, 0]).status, 0);
});

// a disk whose reads come back later
const pending = [];
class SlowBuffer
{
    constructor() { this.bytes = new Uint8Array(512 * 256).map((_, i) => i * 5 & 0xFF); this.byteLength = this.bytes.length; this.onload = undefined; }
    load() { this.onload && this.onload({}); }
    get(start, length, fn) { pending.push(() => fn(this.bytes.slice(start, start + length))); }
    set(start, data, fn) { this.bytes.set(data, start); fn(); }
    get_state() { return []; }
    set_state() {}
}
let slow;
await test("Stop Endpoint with a TD the device NAKs: a Transfer Event (Stopped) at its TRB, the endpoint stopped; the ring from there again", async () => {
    await emulator.usb_attach_disk("slow", new SlowBuffer());
    // (the next free port: physical port 2, USB 3 root port 3)
    assert.equal(r32(PORTSC(3)) & (CCS | PED), CCS | PED);
    events();
    slow = new_device(3, 4);
    assert.equal(slow.code, SUCCESS);
    control(slow.slot, setup(0x00, 9, 1, 0, 0), 0);
    command(CONFIGURE_ENDPOINT, input(1 | 1 << 3 | 1 << 4, [4 << 20 | 4 << 27, 3 << 16, 0, 0], { 3: [6, 1024, 0], 4: [2, 1024, 0] }), 0, slow.slot << 24);
    const cbw = new Uint8Array(31);
    const view = new DataView(cbw.buffer);
    view.setUint32(0, 0x43425355, true);
    view.setUint32(4, 5, true);
    view.setUint32(8, 4096, true);
    cbw[12] = 0x80;
    cbw[14] = 10;
    cbw.set(read10(2, 8), 15);
    mem.set(cbw, BUFFER);
    ring(slow.slot, 4).push(BUFFER, 0, 31, NORMAL << 10 | IOC);
    w32(DB(slow.slot), 4);
    advance(2);
    assert.deepEqual(events().map(e => e.code), [SUCCESS]);
    const trb = ring(slow.slot, 3).push(BUFFER, 0, 4096, NORMAL << 10 | ISP | IOC);
    w32(DB(slow.slot), 3);
    advance(5);
    assert.deepEqual(events(), [], "waiting: NAK");
    const stopped = command(STOP_ENDPOINT, 0, 0, slow.slot << 24 | 3 << 16);
    assert.equal(stopped.code, SUCCESS);
    // (the Transfer Event came before the command's completion)
    assert.equal(endpoint_state(slow.slot, 3), 3);
    assert.equal(u32(output(slow.slot) + 32 * 3 + 8) & ~0xF, trb, "the dequeue pointer at its TRB");
    // started again: the data, once it is there
    w32(DB(slow.slot), 3);
    pending.shift()();
    advance(3);
    const list = events();
    assert.deepEqual(list.map(e => e.code), [SUCCESS]);
});

await test("a command for a slot not enabled, an unknown command: their completion codes", () => {
    assert.equal(command(RESET_DEVICE, 0, 0, 31 << 24).code, 11);
    assert.equal(command(50).code, TRB_ERROR);
});

let tablet;
await test("the tablet on its USB 2 port: Address Device with BSR, then without; its interrupt endpoint's reports from the page's pointer", () => {
    tablet = new_device(5, 1, true);
    assert.equal(tablet.code, SUCCESS);
    assert.equal(slot_state(tablet.slot), 1, "Default (BSR)");
    const again = command(ADDRESS_DEVICE, input(3, [1 << 20 | 1 << 27, 5 << 16, 0, 0], { 1: [4, 8, 0] }), 0, tablet.slot << 24);
    assert.equal(again.code, SUCCESS);
    assert.equal(slot_state(tablet.slot), 2);
    const device = control(tablet.slot, setup(0x80, 6, 0x0100, 0, 18), 18);
    assert.equal(device.data[8] | device.data[9] << 8, 0x0627);
    control(tablet.slot, setup(0x00, 9, 1, 0, 0), 0);
    command(CONFIGURE_ENDPOINT, input(1 | 1 << 3, [1 << 20 | 3 << 27, 5 << 16, 0, 0], { 3: [7, 8, 3] }), 0, tablet.slot << 24);
    events();
    // a report: the pointer moved
    ring(tablet.slot, 3).push(BUFFER, 0, 8, NORMAL << 10 | ISP | IOC);
    w32(DB(tablet.slot), 3);
    advance(2);
    events();
    emulator.bus.send("mouse-absolute", [100, 50, 400, 200]);
    ring(tablet.slot, 3).push(BUFFER, 0, 8, NORMAL << 10 | ISP | IOC);
    w32(DB(tablet.slot), 3);
    advance(3);
    const list = events();
    assert.deepEqual(list.map(e => [e.code, e.length]), [[SHORT_PACKET, 2]], "six bytes into eight");
    assert.equal(mem[BUFFER + 1] | mem[BUFFER + 2] << 8, Math.round(100.5 / 400 * 32767));
});

await test("usb_devices: the tablet at 12 Mbit/s, the disks at 5000, all on the xHCI", async () => {
    assert.deepEqual((await emulator.usb_devices()).map(d => [d.id, d.controller, d.speed]), [["tablet", "xhci", 12], ["stick", "xhci", 5000],
        ["slow", "xhci", 5000]]);
});

await test("hot plug: the disk out (CSC, a Port Status Change Event; its transfers fail), back in", async () => {
    await emulator.usb_plug("stick", false);
    const list = events();
    assert.deepEqual(list.map(e => [e.type, e.low >>> 24]), [[PORT_EVENT, 2]]);
    assert.equal(r32(PORTSC(2)) & (CCS | CSC), CSC);
    await emulator.usb_plug("stick", true);
    assert.equal(r32(PORTSC(2)) & (CCS | PED), CCS | PED);
    assert.deepEqual(events().map(e => e.type), [PORT_EVENT]);
    w32(PORTSC(2), CSC);
    // a new slot for it
    assert.equal(command(DISABLE_SLOT, 0, 0, disk.slot << 24).code, SUCCESS);
    disk = new_device(2, 4);
    assert.equal(disk.code, SUCCESS);
    control(disk.slot, setup(0x00, 9, 1, 0, 0), 0);
    command(CONFIGURE_ENDPOINT, input(1 | 1 << 3 | 1 << 4, [4 << 20 | 4 << 27, 2 << 16, 0, 0], { 3: [6, 1024, 0], 4: [2, 1024, 0] }), 0, disk.slot << 24);
    assert.deepEqual(scsi(read10(1, 1), 512).data, image.slice(512, 1024));
});

await test("a snapshot: the registers, rings, slots and endpoints; the disk goes on reading after it", async () => {
    const state = await emulator.save_state();
    const saved = [events_index, events_cycle, new Map(Array.from(ring_of, ([k, r]) => [k, [r.index, r.cycle]])), commands.index, commands.cycle, tags];
    assert.deepEqual(scsi(read10(20, 2), 1024).data, image.slice(20 * 512, 22 * 512));
    await emulator.restore_state(state);
    [events_index, events_cycle] = saved;
    for(const [k, [index, cycle]] of saved[2]) Object.assign(ring_of.get(k), { index, cycle });
    commands.index = saved[3];
    commands.cycle = saved[4];
    tags = saved[5];
    assert.equal(r32(USBSTS) & HCH, 0);
    assert.deepEqual(scsi(read10(30, 2), 1024).data, image.slice(30 * 512, 32 * 512));
});

await test("the event ring wraps (its cycle bit); a full ring drops events", () => {
    // more completions than the ring has entries, read as they come
    for(let i = 0; i < EVENT_TRBS + 5; i++) assert.equal(command(NOOP_COMMAND).code, SUCCESS);
    // the driver not reading: the ring fills, the last entry an Event Ring Full Error, then nothing
    for(let i = 0; i < EVENT_TRBS + 4; i++)
    {
        commands.push(0, 0, 0, NOOP_COMMAND << 10);
        w32(DB(0), 0);
    }
    const list = events();
    assert.equal(list.length, EVENT_TRBS - 1);
    assert.equal(list[list.length - 1].code, 21);
});

await test("MSI: a message for an event (no INTA), IP cleared once it is sent", () => {
    const space = pci.space_bytes(XHCI);
    pci.config_write(XHCI, 0x70 + 4, 4, 0xFEE00000);
    pci.config_write(XHCI, 0x70 + 12, 2, 0x45);
    pci.config_write(XHCI, 0x70 + 2, 2, 1);
    assert.equal(space[0x72] & 1, 1);
    let sent = 0;
    const apic_msi = cpu.apic_msi;
    cpu.apic_msi = () => { sent++; return true; };
    command(NOOP_COMMAND);
    cpu.apic_msi = apic_msi;
    assert.equal(sent, 1);
    assert.ok(!irq());
    assert.equal(r32(IMAN) & 1, 0);
    pci.config_write(XHCI, 0x70 + 2, 2, 0);
});

await test("HCRST: halted, the slots gone, the ports as their devices are", () => {
    w32(USBCMD, 0);
    assert.equal(r32(USBSTS) & HCH, HCH);
    w32(USBCMD, HCRST);
    assert.equal(r32(USBCMD), 0);
    assert.equal(r32(PORTSC(2)) & (CCS | PED), CCS | PED);
    assert.equal(r32(PORTSC(5)) & (CCS | PED), CCS, "the USB 2 port to be reset again");
});

{
    const pc = await machine("i440fx");
    await test("i440FX: at 00:14.0 too", () => {
        const space = pc.v86.cpu.devices.pci.space_bytes(0x14 << 3);
        assert.equal(space[2] | space[3] << 8, 0x000D);
    });
    await pc.destroy();
}

await emulator.destroy();
console.log(passed + " passed, " + failed + " failed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                     source/v64/tests/devices/venus_guest_protocol.js                                                    0000644 0000000 0000000 00001523647 00000000000 017320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Generated by tools/venus_protocol_gen.mjs from Mesa's venus-protocol
// (src/virtio/venus-protocol, Mesa 26.1.6); do not edit.
//
// The driver's side of the Venus wire format, for tests: g_* encode a request,
// h_* decode a reply (the device's side is venus_protocol.js, where d_* read a request the guest's driver encoded, into
// objects with the C names (structs) or an object of the parameters
// (commands); e_* write a reply the driver decodes, from such objects (what
// is missing is written as zeros, an empty array or a null pointer).

/* eslint-disable */

import { VenusReader, VenusWriter } from "../../src/graphics_adapters/virtio_gpu/venus_protocol.js";
export { VenusReader, VenusWriter };
const EMPTY = {};
const GUEST_PNEXT = {1000470006: g_VkBufferUsageFlags2CreateInfo_self, 1000072000: g_VkExternalMemoryBufferCreateInfo_self, 1000257002: g_VkBufferOpaqueCaptureAddressCreateInfo_self, 1000244002: g_VkBufferDeviceAddressCreateInfoEXT_self, 1000060013: g_VkBindBufferMemoryDeviceGroupInfo_self, 1000545002: g_VkBindMemoryStatus_self, 1000081000: g_VkCommandBufferInheritanceConditionalRenderingInfoEXT_self, 1000044004: g_VkCommandBufferInheritanceRenderingInfo_self, 1000232001: g_VkRenderingAttachmentLocationInfo_self, 1000232002: g_VkRenderingInputAttachmentIndexInfo_self, 1000135010: g_VkCommandBufferInheritanceDescriptorHeapInfoEXT_self, 1000060004: g_VkDeviceGroupCommandBufferBeginInfo_self, 1000453000: g_VkExternalMemoryAcquireUnmodifiedEXT_self, 1000143000: g_VkSampleLocationsInfoEXT_self, 1000060003: g_VkDeviceGroupRenderPassBeginInfo_self, 1000143001: g_VkRenderPassSampleLocationsBeginInfoEXT_self, 1000108003: g_VkRenderPassAttachmentBeginInfo_self, 1000376002: g_VkMultisampledRenderToSingleSampledInfoEXT_self, 1000044006: g_VkRenderingFragmentShadingRateAttachmentInfoKHR_self, 1000283002: g_VkDepthBiasRepresentationInfoEXT_self, 30: g_VkPipelineLayoutCreateInfo_self, 1000138003: g_VkDescriptorPoolInlineUniformBlockCreateInfo_self, 1000351002: g_VkMutableDescriptorTypeCreateInfoEXT_self, 1000161003: g_VkDescriptorSetVariableDescriptorCountAllocateInfo_self, 1000161000: g_VkDescriptorSetLayoutBindingFlagsCreateInfo_self, 1000174000: g_VkDeviceQueueGlobalPriorityCreateInfo_self, 1000295000: g_VkPhysicalDevicePrivateDataFeatures_self, 1000120000: g_VkPhysicalDeviceVariablePointersFeatures_self, 1000053001: g_VkPhysicalDeviceMultiviewFeatures_self, 1000083000: g_VkPhysicalDevice16BitStorageFeatures_self, 1000175000: g_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self, 1000156004: g_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self, 1000145001: g_VkPhysicalDeviceProtectedMemoryFeatures_self, 1000148000: g_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self, 1000392000: g_VkPhysicalDeviceMultiDrawFeaturesEXT_self, 1000138000: g_VkPhysicalDeviceInlineUniformBlockFeatures_self, 1000413000: g_VkPhysicalDeviceMaintenance4Features_self, 1000470000: g_VkPhysicalDeviceMaintenance5Features_self, 1000545000: g_VkPhysicalDeviceMaintenance6Features_self, 1000562000: g_VkPhysicalDeviceMaintenance7FeaturesKHR_self, 1000063000: g_VkPhysicalDeviceShaderDrawParametersFeatures_self, 1000082000: g_VkPhysicalDeviceShaderFloat16Int8Features_self, 1000261000: g_VkPhysicalDeviceHostQueryResetFeatures_self, 1000388000: g_VkPhysicalDeviceGlobalPriorityQueryFeatures_self, 1000161001: g_VkPhysicalDeviceDescriptorIndexingFeatures_self, 1000207000: g_VkPhysicalDeviceTimelineSemaphoreFeatures_self, 1000177000: g_VkPhysicalDevice8BitStorageFeatures_self, 1000081001: g_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self, 1000211000: g_VkPhysicalDeviceVulkanMemoryModelFeatures_self, 1000180000: g_VkPhysicalDeviceShaderAtomicInt64Features_self, 1000260000: g_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self, 1000273000: g_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self, 1000190002: g_VkPhysicalDeviceVertexAttributeDivisorFeatures_self, 1000028000: g_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self, 1000201000: g_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self, 1000203000: g_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self, 1000328000: g_VkPhysicalDeviceMeshShaderFeaturesEXT_self, 1000150013: g_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self, 1000347000: g_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self, 1000348013: g_VkPhysicalDeviceRayQueryFeaturesKHR_self, 1000386000: g_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self, 1000221000: g_VkPhysicalDeviceScalarBlockLayoutFeatures_self, 1000253000: g_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self, 1000102000: g_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self, 1000257000: g_VkPhysicalDeviceBufferDeviceAddressFeatures_self, 1000244000: g_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self, 1000108000: g_VkPhysicalDeviceImagelessFramebufferFeatures_self, 1000066000: g_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self, 1000252000: g_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self, 1000181000: g_VkPhysicalDeviceShaderClockFeaturesKHR_self, 1000265000: g_VkPhysicalDeviceIndexTypeUint8Features_self, 1000251000: g_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self, 1000241000: g_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self, 1000356000: g_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self, 1000276000: g_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self, 1000281000: g_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self, 1000225002: g_VkPhysicalDeviceSubgroupSizeControlFeatures_self, 1000259000: g_VkPhysicalDeviceLineRasterizationFeatures_self, 1000297000: g_VkPhysicalDevicePipelineCreationCacheControlFeatures_self, 49: g_VkPhysicalDeviceVulkan11Features_self, 51: g_VkPhysicalDeviceVulkan12Features_self, 53: g_VkPhysicalDeviceVulkan13Features_self, 55: g_VkPhysicalDeviceVulkan14Features_self, 1000287002: g_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self, 1000411000: g_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self, 1000267000: g_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self, 1000377000: g_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self, 1000455000: g_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self, 1000325000: g_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self, 1000323000: g_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self, 1000286000: g_VkPhysicalDeviceRobustness2FeaturesKHR_self, 1000335000: g_VkPhysicalDeviceImageRobustnessFeatures_self, 1000336000: g_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self, 1000340000: g_VkPhysicalDevice4444FormatsFeaturesEXT_self, 1000234000: g_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self, 1000226003: g_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self, 1000215000: g_VkPhysicalDeviceShaderTerminateInvocationFeatures_self, 1000393000: g_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self, 1000418000: g_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self, 1000524000: g_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self, 1000495000: g_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self, 1000351000: g_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self, 1000355000: g_VkPhysicalDeviceDepthClipControlFeaturesEXT_self, 1000582000: g_VkPhysicalDeviceDepthClampControlFeaturesEXT_self, 1000352000: g_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self, 1000558000: g_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self, 1000381000: g_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self, 1000314007: g_VkPhysicalDeviceSynchronization2Features_self, 1000270000: g_VkPhysicalDeviceHostImageCopyFeatures_self, 1000382000: g_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self, 1000465000: g_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self, 1000376000: g_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self, 1000466000: g_VkPhysicalDevicePipelineProtectedAccessFeatures_self, 1000330000: g_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self, 1000254000: g_VkPhysicalDeviceProvokingVertexFeaturesEXT_self, 1000280000: g_VkPhysicalDeviceShaderIntegerDotProductFeatures_self, 1000579000: g_VkPhysicalDeviceShaderFmaFeaturesKHR_self, 1000044003: g_VkPhysicalDeviceDynamicRenderingFeatures_self, 1000391000: g_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self, 1000342000: g_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self, 1000320000: g_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self, 1000451000: g_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self, 1000422000: g_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self, 1000068001: g_VkPhysicalDevicePipelineRobustnessFeatures_self, 1000339000: g_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self, 1000421000: g_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self, 1000498000: g_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self, 1000499000: g_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self, 1000283000: g_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self, 1000481000: g_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self, 1000506000: g_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self, 1000434000: g_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self, 1000416000: g_VkPhysicalDeviceShaderSubgroupRotateFeatures_self, 1000544000: g_VkPhysicalDeviceShaderExpectAssumeFeatures_self, 1000528000: g_VkPhysicalDeviceShaderFloatControls2Features_self, 1000232000: g_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self, 1000235000: g_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self, 1000141000: g_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self, 1000564000: g_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self, 1000642000: g_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self, 1000567000: g_VkPhysicalDeviceShaderFloat8FeaturesEXT_self, 1000387000: g_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self, 1000135009: g_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self, 1000295001: g_VkDevicePrivateDataCreateInfo_self, 1000059000: g_VkPhysicalDeviceFeatures2_self, 1000070001: g_VkDeviceGroupDeviceCreateInfo_self, 1000071000: g_VkPhysicalDeviceExternalImageFormatInfo_self, 1000147000: g_VkImageFormatListCreateInfo_self, 1000158002: g_VkPhysicalDeviceImageDrmFormatModifierInfoEXT_self, 1000246000: g_VkImageStencilUsageCreateInfo_self, 1000170000: g_VkPhysicalDeviceImageViewImageFormatInfoEXT_self, 1000207002: g_VkSemaphoreTypeCreateInfo_self, 1000384005: g_VkDeviceQueueTimelineInfoMESA_self, 1000072002: g_VkExportMemoryAllocateInfo_self, 1000060000: g_VkMemoryAllocateFlagsInfo_self, 1000127001: g_VkMemoryDedicatedAllocateInfo_self, 1000257003: g_VkMemoryOpaqueCaptureAddressAllocateInfo_self, 1000384002: g_VkImportMemoryResourceInfoMESA_self, 1000113000: g_VkExportFenceCreateInfo_self, 1000108001: g_VkFramebufferAttachmentsCreateInfo_self, 1000072001: g_VkExternalMemoryImageCreateInfo_self, 1000158003: g_VkImageDrmFormatModifierListCreateInfoEXT_self, 1000158004: g_VkImageDrmFormatModifierExplicitCreateInfoEXT_self, 1000135007: g_VkOpaqueCaptureDataCreateInfoEXT_self, 1000060014: g_VkBindImageMemoryDeviceGroupInfo_self, 1000156002: g_VkBindImagePlaneMemoryInfo_self, 1000156003: g_VkImagePlaneMemoryRequirementsInfo_self, 16: g_VkShaderModuleCreateInfo_self, 1000225001: g_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo_self, 1000068000: g_VkPipelineRobustnessCreateInfo_self, 1000135006: g_VkShaderDescriptorSetAndBindingMappingInfoEXT_self, 1000190001: g_VkPipelineVertexInputDivisorStateCreateInfo_self, 1000117003: g_VkPipelineTessellationDomainOriginStateCreateInfo_self, 1000355001: g_VkPipelineViewportDepthClipControlCreateInfoEXT_self, 1000582001: g_VkPipelineViewportDepthClampControlCreateInfoEXT_self, 1000101001: g_VkPipelineRasterizationConservativeStateCreateInfoEXT_self, 1000028002: g_VkPipelineRasterizationStateStreamCreateInfoEXT_self, 1000102001: g_VkPipelineRasterizationDepthClipStateCreateInfoEXT_self, 1000259001: g_VkPipelineRasterizationLineStateCreateInfo_self, 1000254001: g_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT_self, 1000143002: g_VkPipelineSampleLocationsStateCreateInfoEXT_self, 1000148002: g_VkPipelineColorBlendAdvancedStateCreateInfoEXT_self, 1000381001: g_VkPipelineColorWriteCreateInfoEXT_self, 1000470005: g_VkPipelineCreateFlags2CreateInfo_self, 1000290000: g_VkPipelineLibraryCreateInfoKHR_self, 1000192000: g_VkPipelineCreationFeedbackCreateInfo_self, 1000226001: g_VkPipelineFragmentShadingRateStateCreateInfoKHR_self, 1000044002: g_VkPipelineRenderingCreateInfo_self, 1000320002: g_VkGraphicsPipelineLibraryCreateInfoEXT_self, 1000060005: g_VkDeviceGroupSubmitInfo_self, 1000145000: g_VkProtectedSubmitInfo_self, 1000207003: g_VkTimelineSemaphoreSubmitInfo_self, 1000060006: g_VkDeviceGroupBindSparseInfo_self, 1000053000: g_VkRenderPassMultiviewCreateInfo_self, 1000117001: g_VkRenderPassInputAttachmentAspectCreateInfo_self, 1000241002: g_VkAttachmentDescriptionStencilLayout_self, 1000241001: g_VkAttachmentReferenceStencilLayout_self, 1000199001: g_VkSubpassDescriptionDepthStencilResolve_self, 1000226000: g_VkFragmentShadingRateAttachmentInfoKHR_self, 1000314000: g_VkMemoryBarrier2_self, 1000077000: g_VkExportSemaphoreCreateInfo_self, 1000117002: g_VkImageViewUsageCreateInfo_self, 1000418001: g_VkImageViewSlicedCreateInfoEXT_self, 1000156001: g_VkSamplerYcbcrConversionInfo_self, 1000391001: g_VkImageViewMinLodCreateInfoEXT_self, 1000130001: g_VkSamplerReductionModeCreateInfo_self, 1000287000: g_VkSamplerCustomBorderColorCreateInfoEXT_self, 1000411001: g_VkSamplerBorderColorComponentMappingCreateInfoEXT_self, 1000135011: g_VkSamplerCustomBorderColorIndexCreateInfoEXT_self, 1000138002: g_VkWriteDescriptorSetInlineUniformBlock_self, 1000150007: g_VkWriteDescriptorSetAccelerationStructureKHR_self, 1000384006: g_VkRingMonitorInfoMESA_self, 1000384007: g_VkRingPriorityInfoMESA_self};
const GUEST_PNEXT_PARTIAL = {1000161004: g_VkDescriptorSetVariableDescriptorCountLayoutSupport_self_partial, 1000295000: g_VkPhysicalDevicePrivateDataFeatures_self_partial, 1000120000: g_VkPhysicalDeviceVariablePointersFeatures_self_partial, 1000053001: g_VkPhysicalDeviceMultiviewFeatures_self_partial, 1000083000: g_VkPhysicalDevice16BitStorageFeatures_self_partial, 1000175000: g_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self_partial, 1000156004: g_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self_partial, 1000145001: g_VkPhysicalDeviceProtectedMemoryFeatures_self_partial, 1000148000: g_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self_partial, 1000392000: g_VkPhysicalDeviceMultiDrawFeaturesEXT_self_partial, 1000138000: g_VkPhysicalDeviceInlineUniformBlockFeatures_self_partial, 1000413000: g_VkPhysicalDeviceMaintenance4Features_self_partial, 1000470000: g_VkPhysicalDeviceMaintenance5Features_self_partial, 1000545000: g_VkPhysicalDeviceMaintenance6Features_self_partial, 1000562000: g_VkPhysicalDeviceMaintenance7FeaturesKHR_self_partial, 1000063000: g_VkPhysicalDeviceShaderDrawParametersFeatures_self_partial, 1000082000: g_VkPhysicalDeviceShaderFloat16Int8Features_self_partial, 1000261000: g_VkPhysicalDeviceHostQueryResetFeatures_self_partial, 1000388000: g_VkPhysicalDeviceGlobalPriorityQueryFeatures_self_partial, 1000161001: g_VkPhysicalDeviceDescriptorIndexingFeatures_self_partial, 1000207000: g_VkPhysicalDeviceTimelineSemaphoreFeatures_self_partial, 1000177000: g_VkPhysicalDevice8BitStorageFeatures_self_partial, 1000081001: g_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self_partial, 1000211000: g_VkPhysicalDeviceVulkanMemoryModelFeatures_self_partial, 1000180000: g_VkPhysicalDeviceShaderAtomicInt64Features_self_partial, 1000260000: g_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self_partial, 1000273000: g_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self_partial, 1000190002: g_VkPhysicalDeviceVertexAttributeDivisorFeatures_self_partial, 1000028000: g_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self_partial, 1000201000: g_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self_partial, 1000203000: g_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self_partial, 1000328000: g_VkPhysicalDeviceMeshShaderFeaturesEXT_self_partial, 1000150013: g_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self_partial, 1000347000: g_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self_partial, 1000348013: g_VkPhysicalDeviceRayQueryFeaturesKHR_self_partial, 1000386000: g_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self_partial, 1000221000: g_VkPhysicalDeviceScalarBlockLayoutFeatures_self_partial, 1000253000: g_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self_partial, 1000102000: g_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self_partial, 1000257000: g_VkPhysicalDeviceBufferDeviceAddressFeatures_self_partial, 1000244000: g_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self_partial, 1000108000: g_VkPhysicalDeviceImagelessFramebufferFeatures_self_partial, 1000066000: g_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self_partial, 1000252000: g_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self_partial, 1000181000: g_VkPhysicalDeviceShaderClockFeaturesKHR_self_partial, 1000265000: g_VkPhysicalDeviceIndexTypeUint8Features_self_partial, 1000251000: g_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self_partial, 1000241000: g_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self_partial, 1000356000: g_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self_partial, 1000276000: g_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self_partial, 1000281000: g_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self_partial, 1000225002: g_VkPhysicalDeviceSubgroupSizeControlFeatures_self_partial, 1000259000: g_VkPhysicalDeviceLineRasterizationFeatures_self_partial, 1000297000: g_VkPhysicalDevicePipelineCreationCacheControlFeatures_self_partial, 49: g_VkPhysicalDeviceVulkan11Features_self_partial, 51: g_VkPhysicalDeviceVulkan12Features_self_partial, 53: g_VkPhysicalDeviceVulkan13Features_self_partial, 55: g_VkPhysicalDeviceVulkan14Features_self_partial, 1000287002: g_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self_partial, 1000411000: g_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self_partial, 1000267000: g_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self_partial, 1000377000: g_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self_partial, 1000455000: g_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self_partial, 1000325000: g_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self_partial, 1000323000: g_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self_partial, 1000286000: g_VkPhysicalDeviceRobustness2FeaturesKHR_self_partial, 1000335000: g_VkPhysicalDeviceImageRobustnessFeatures_self_partial, 1000336000: g_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self_partial, 1000340000: g_VkPhysicalDevice4444FormatsFeaturesEXT_self_partial, 1000234000: g_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self_partial, 1000226003: g_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self_partial, 1000215000: g_VkPhysicalDeviceShaderTerminateInvocationFeatures_self_partial, 1000393000: g_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self_partial, 1000418000: g_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self_partial, 1000524000: g_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self_partial, 1000495000: g_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self_partial, 1000351000: g_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self_partial, 1000355000: g_VkPhysicalDeviceDepthClipControlFeaturesEXT_self_partial, 1000582000: g_VkPhysicalDeviceDepthClampControlFeaturesEXT_self_partial, 1000352000: g_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self_partial, 1000558000: g_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self_partial, 1000381000: g_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self_partial, 1000314007: g_VkPhysicalDeviceSynchronization2Features_self_partial, 1000270000: g_VkPhysicalDeviceHostImageCopyFeatures_self_partial, 1000382000: g_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self_partial, 1000465000: g_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self_partial, 1000376000: g_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self_partial, 1000466000: g_VkPhysicalDevicePipelineProtectedAccessFeatures_self_partial, 1000330000: g_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self_partial, 1000254000: g_VkPhysicalDeviceProvokingVertexFeaturesEXT_self_partial, 1000280000: g_VkPhysicalDeviceShaderIntegerDotProductFeatures_self_partial, 1000579000: g_VkPhysicalDeviceShaderFmaFeaturesKHR_self_partial, 1000044003: g_VkPhysicalDeviceDynamicRenderingFeatures_self_partial, 1000391000: g_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self_partial, 1000342000: g_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self_partial, 1000320000: g_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self_partial, 1000451000: g_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self_partial, 1000422000: g_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self_partial, 1000068001: g_VkPhysicalDevicePipelineRobustnessFeatures_self_partial, 1000339000: g_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self_partial, 1000421000: g_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self_partial, 1000498000: g_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self_partial, 1000499000: g_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self_partial, 1000283000: g_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self_partial, 1000481000: g_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self_partial, 1000506000: g_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self_partial, 1000434000: g_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self_partial, 1000416000: g_VkPhysicalDeviceShaderSubgroupRotateFeatures_self_partial, 1000544000: g_VkPhysicalDeviceShaderExpectAssumeFeatures_self_partial, 1000528000: g_VkPhysicalDeviceShaderFloatControls2Features_self_partial, 1000232000: g_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self_partial, 1000235000: g_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self_partial, 1000141000: g_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self_partial, 1000564000: g_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self_partial, 1000642000: g_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self_partial, 1000567000: g_VkPhysicalDeviceShaderFloat8FeaturesEXT_self_partial, 1000387000: g_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self_partial, 1000135009: g_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self_partial, 1000392001: g_VkPhysicalDeviceMultiDrawPropertiesEXT_self_partial, 1000080000: g_VkPhysicalDevicePushDescriptorProperties_self_partial, 1000196000: g_VkPhysicalDeviceDriverProperties_self_partial, 1000071004: g_VkPhysicalDeviceIDProperties_self_partial, 1000053002: g_VkPhysicalDeviceMultiviewProperties_self_partial, 1000094000: g_VkPhysicalDeviceSubgroupProperties_self_partial, 1000117000: g_VkPhysicalDevicePointClippingProperties_self_partial, 1000145002: g_VkPhysicalDeviceProtectedMemoryProperties_self_partial, 1000130000: g_VkPhysicalDeviceSamplerFilterMinmaxProperties_self_partial, 1000143003: g_VkPhysicalDeviceSampleLocationsPropertiesEXT_self_partial, 1000148001: g_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self_partial, 1000138001: g_VkPhysicalDeviceInlineUniformBlockProperties_self_partial, 1000168000: g_VkPhysicalDeviceMaintenance3Properties_self_partial, 1000413001: g_VkPhysicalDeviceMaintenance4Properties_self_partial, 1000470001: g_VkPhysicalDeviceMaintenance5Properties_self_partial, 1000545001: g_VkPhysicalDeviceMaintenance6Properties_self_partial, 1000562001: g_VkPhysicalDeviceMaintenance7PropertiesKHR_self_partial, 1000197000: g_VkPhysicalDeviceFloatControlsProperties_self_partial, 1000101000: g_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self_partial, 1000161002: g_VkPhysicalDeviceDescriptorIndexingProperties_self_partial, 1000207001: g_VkPhysicalDeviceTimelineSemaphoreProperties_self_partial, 1000190000: g_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self_partial, 1000525000: g_VkPhysicalDeviceVertexAttributeDivisorProperties_self_partial, 1000212000: g_VkPhysicalDevicePCIBusInfoPropertiesEXT_self_partial, 1000199000: g_VkPhysicalDeviceDepthStencilResolveProperties_self_partial, 1000028001: g_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self_partial, 1000511000: g_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self_partial, 1000328001: g_VkPhysicalDeviceMeshShaderPropertiesEXT_self_partial, 1000150014: g_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self_partial, 1000347001: g_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self_partial, 1000281001: g_VkPhysicalDeviceTexelBufferAlignmentProperties_self_partial, 1000225000: g_VkPhysicalDeviceSubgroupSizeControlProperties_self_partial, 1000259002: g_VkPhysicalDeviceLineRasterizationProperties_self_partial, 50: g_VkPhysicalDeviceVulkan11Properties_self_partial, 52: g_VkPhysicalDeviceVulkan12Properties_self_partial, 54: g_VkPhysicalDeviceVulkan13Properties_self_partial, 56: g_VkPhysicalDeviceVulkan14Properties_self_partial, 1000287001: g_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self_partial, 1000455001: g_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self_partial, 1000286001: g_VkPhysicalDeviceRobustness2PropertiesKHR_self_partial, 1000226002: g_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self_partial, 1000495001: g_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self_partial, 1000270001: g_VkPhysicalDeviceHostImageCopyProperties_self_partial, 1000254002: g_VkPhysicalDeviceProvokingVertexPropertiesEXT_self_partial, 1000280001: g_VkPhysicalDeviceShaderIntegerDotProductProperties_self_partial, 1000322000: g_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self_partial, 1000320001: g_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self_partial, 1000451001: g_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self_partial, 1000068002: g_VkPhysicalDevicePipelineRobustnessProperties_self_partial, 1000506002: g_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self_partial, 1000135008: g_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self_partial, 1000158000: g_VkDrmFormatModifierPropertiesListEXT_self_partial, 1000376001: g_VkSubpassResolvePerformanceQueryEXT_self_partial, 1000360000: g_VkFormatProperties3_self_partial, 1000158006: g_VkDrmFormatModifierPropertiesList2EXT_self_partial, 1000071001: g_VkExternalImageFormatProperties_self_partial, 1000156005: g_VkSamplerYcbcrConversionImageFormatProperties_self_partial, 1000170001: g_VkFilterCubicImageViewImageFormatPropertiesEXT_self_partial, 1000270009: g_VkHostImageCopyDevicePerformanceQuery_self_partial, 1000388001: g_VkQueueFamilyGlobalPriorityProperties_self_partial, 1000237000: g_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self_partial, 1000384003: g_VkMemoryResourceAllocationSizePropertiesMESA_self_partial, 1000270008: g_VkSubresourceHostMemcpySize_self_partial, 1000127000: g_VkMemoryDedicatedRequirements_self_partial};
const GUEST_PNEXT_REPLY = {1000161004: h_VkDescriptorSetVariableDescriptorCountLayoutSupport_self, 1000295000: h_VkPhysicalDevicePrivateDataFeatures_self, 1000120000: h_VkPhysicalDeviceVariablePointersFeatures_self, 1000053001: h_VkPhysicalDeviceMultiviewFeatures_self, 1000083000: h_VkPhysicalDevice16BitStorageFeatures_self, 1000175000: h_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self, 1000156004: h_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self, 1000145001: h_VkPhysicalDeviceProtectedMemoryFeatures_self, 1000148000: h_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self, 1000392000: h_VkPhysicalDeviceMultiDrawFeaturesEXT_self, 1000138000: h_VkPhysicalDeviceInlineUniformBlockFeatures_self, 1000413000: h_VkPhysicalDeviceMaintenance4Features_self, 1000470000: h_VkPhysicalDeviceMaintenance5Features_self, 1000545000: h_VkPhysicalDeviceMaintenance6Features_self, 1000562000: h_VkPhysicalDeviceMaintenance7FeaturesKHR_self, 1000063000: h_VkPhysicalDeviceShaderDrawParametersFeatures_self, 1000082000: h_VkPhysicalDeviceShaderFloat16Int8Features_self, 1000261000: h_VkPhysicalDeviceHostQueryResetFeatures_self, 1000388000: h_VkPhysicalDeviceGlobalPriorityQueryFeatures_self, 1000161001: h_VkPhysicalDeviceDescriptorIndexingFeatures_self, 1000207000: h_VkPhysicalDeviceTimelineSemaphoreFeatures_self, 1000177000: h_VkPhysicalDevice8BitStorageFeatures_self, 1000081001: h_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self, 1000211000: h_VkPhysicalDeviceVulkanMemoryModelFeatures_self, 1000180000: h_VkPhysicalDeviceShaderAtomicInt64Features_self, 1000260000: h_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self, 1000273000: h_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self, 1000190002: h_VkPhysicalDeviceVertexAttributeDivisorFeatures_self, 1000028000: h_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self, 1000201000: h_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self, 1000203000: h_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self, 1000328000: h_VkPhysicalDeviceMeshShaderFeaturesEXT_self, 1000150013: h_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self, 1000347000: h_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self, 1000348013: h_VkPhysicalDeviceRayQueryFeaturesKHR_self, 1000386000: h_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self, 1000221000: h_VkPhysicalDeviceScalarBlockLayoutFeatures_self, 1000253000: h_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self, 1000102000: h_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self, 1000257000: h_VkPhysicalDeviceBufferDeviceAddressFeatures_self, 1000244000: h_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self, 1000108000: h_VkPhysicalDeviceImagelessFramebufferFeatures_self, 1000066000: h_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self, 1000252000: h_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self, 1000181000: h_VkPhysicalDeviceShaderClockFeaturesKHR_self, 1000265000: h_VkPhysicalDeviceIndexTypeUint8Features_self, 1000251000: h_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self, 1000241000: h_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self, 1000356000: h_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self, 1000276000: h_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self, 1000281000: h_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self, 1000225002: h_VkPhysicalDeviceSubgroupSizeControlFeatures_self, 1000259000: h_VkPhysicalDeviceLineRasterizationFeatures_self, 1000297000: h_VkPhysicalDevicePipelineCreationCacheControlFeatures_self, 49: h_VkPhysicalDeviceVulkan11Features_self, 51: h_VkPhysicalDeviceVulkan12Features_self, 53: h_VkPhysicalDeviceVulkan13Features_self, 55: h_VkPhysicalDeviceVulkan14Features_self, 1000287002: h_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self, 1000411000: h_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self, 1000267000: h_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self, 1000377000: h_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self, 1000455000: h_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self, 1000325000: h_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self, 1000323000: h_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self, 1000286000: h_VkPhysicalDeviceRobustness2FeaturesKHR_self, 1000335000: h_VkPhysicalDeviceImageRobustnessFeatures_self, 1000336000: h_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self, 1000340000: h_VkPhysicalDevice4444FormatsFeaturesEXT_self, 1000234000: h_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self, 1000226003: h_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self, 1000215000: h_VkPhysicalDeviceShaderTerminateInvocationFeatures_self, 1000393000: h_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self, 1000418000: h_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self, 1000524000: h_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self, 1000495000: h_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self, 1000351000: h_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self, 1000355000: h_VkPhysicalDeviceDepthClipControlFeaturesEXT_self, 1000582000: h_VkPhysicalDeviceDepthClampControlFeaturesEXT_self, 1000352000: h_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self, 1000558000: h_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self, 1000381000: h_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self, 1000314007: h_VkPhysicalDeviceSynchronization2Features_self, 1000270000: h_VkPhysicalDeviceHostImageCopyFeatures_self, 1000382000: h_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self, 1000465000: h_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self, 1000376000: h_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self, 1000466000: h_VkPhysicalDevicePipelineProtectedAccessFeatures_self, 1000330000: h_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self, 1000254000: h_VkPhysicalDeviceProvokingVertexFeaturesEXT_self, 1000280000: h_VkPhysicalDeviceShaderIntegerDotProductFeatures_self, 1000579000: h_VkPhysicalDeviceShaderFmaFeaturesKHR_self, 1000044003: h_VkPhysicalDeviceDynamicRenderingFeatures_self, 1000391000: h_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self, 1000342000: h_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self, 1000320000: h_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self, 1000451000: h_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self, 1000422000: h_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self, 1000068001: h_VkPhysicalDevicePipelineRobustnessFeatures_self, 1000339000: h_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self, 1000421000: h_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self, 1000498000: h_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self, 1000499000: h_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self, 1000283000: h_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self, 1000481000: h_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self, 1000506000: h_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self, 1000434000: h_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self, 1000416000: h_VkPhysicalDeviceShaderSubgroupRotateFeatures_self, 1000544000: h_VkPhysicalDeviceShaderExpectAssumeFeatures_self, 1000528000: h_VkPhysicalDeviceShaderFloatControls2Features_self, 1000232000: h_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self, 1000235000: h_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self, 1000141000: h_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self, 1000564000: h_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self, 1000642000: h_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self, 1000567000: h_VkPhysicalDeviceShaderFloat8FeaturesEXT_self, 1000387000: h_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self, 1000135009: h_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self, 1000392001: h_VkPhysicalDeviceMultiDrawPropertiesEXT_self, 1000080000: h_VkPhysicalDevicePushDescriptorProperties_self, 1000196000: h_VkPhysicalDeviceDriverProperties_self, 1000071004: h_VkPhysicalDeviceIDProperties_self, 1000053002: h_VkPhysicalDeviceMultiviewProperties_self, 1000094000: h_VkPhysicalDeviceSubgroupProperties_self, 1000117000: h_VkPhysicalDevicePointClippingProperties_self, 1000145002: h_VkPhysicalDeviceProtectedMemoryProperties_self, 1000130000: h_VkPhysicalDeviceSamplerFilterMinmaxProperties_self, 1000143003: h_VkPhysicalDeviceSampleLocationsPropertiesEXT_self, 1000148001: h_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self, 1000138001: h_VkPhysicalDeviceInlineUniformBlockProperties_self, 1000168000: h_VkPhysicalDeviceMaintenance3Properties_self, 1000413001: h_VkPhysicalDeviceMaintenance4Properties_self, 1000470001: h_VkPhysicalDeviceMaintenance5Properties_self, 1000545001: h_VkPhysicalDeviceMaintenance6Properties_self, 1000562001: h_VkPhysicalDeviceMaintenance7PropertiesKHR_self, 1000197000: h_VkPhysicalDeviceFloatControlsProperties_self, 1000101000: h_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self, 1000161002: h_VkPhysicalDeviceDescriptorIndexingProperties_self, 1000207001: h_VkPhysicalDeviceTimelineSemaphoreProperties_self, 1000190000: h_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self, 1000525000: h_VkPhysicalDeviceVertexAttributeDivisorProperties_self, 1000212000: h_VkPhysicalDevicePCIBusInfoPropertiesEXT_self, 1000199000: h_VkPhysicalDeviceDepthStencilResolveProperties_self, 1000028001: h_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self, 1000511000: h_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self, 1000328001: h_VkPhysicalDeviceMeshShaderPropertiesEXT_self, 1000150014: h_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self, 1000347001: h_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self, 1000281001: h_VkPhysicalDeviceTexelBufferAlignmentProperties_self, 1000225000: h_VkPhysicalDeviceSubgroupSizeControlProperties_self, 1000259002: h_VkPhysicalDeviceLineRasterizationProperties_self, 50: h_VkPhysicalDeviceVulkan11Properties_self, 52: h_VkPhysicalDeviceVulkan12Properties_self, 54: h_VkPhysicalDeviceVulkan13Properties_self, 56: h_VkPhysicalDeviceVulkan14Properties_self, 1000287001: h_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self, 1000455001: h_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self, 1000286001: h_VkPhysicalDeviceRobustness2PropertiesKHR_self, 1000226002: h_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self, 1000495001: h_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self, 1000270001: h_VkPhysicalDeviceHostImageCopyProperties_self, 1000254002: h_VkPhysicalDeviceProvokingVertexPropertiesEXT_self, 1000280001: h_VkPhysicalDeviceShaderIntegerDotProductProperties_self, 1000322000: h_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self, 1000320001: h_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self, 1000451001: h_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self, 1000068002: h_VkPhysicalDevicePipelineRobustnessProperties_self, 1000506002: h_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self, 1000135008: h_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self, 1000158000: h_VkDrmFormatModifierPropertiesListEXT_self, 1000376001: h_VkSubpassResolvePerformanceQueryEXT_self, 1000360000: h_VkFormatProperties3_self, 1000158006: h_VkDrmFormatModifierPropertiesList2EXT_self, 1000071001: h_VkExternalImageFormatProperties_self, 1000156005: h_VkSamplerYcbcrConversionImageFormatProperties_self, 1000170001: h_VkFilterCubicImageViewImageFormatPropertiesEXT_self, 1000270009: h_VkHostImageCopyDevicePerformanceQuery_self, 1000388001: h_VkQueueFamilyGlobalPriorityProperties_self, 1000237000: h_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self, 1000384003: h_VkMemoryResourceAllocationSizePropertiesMESA_self, 1000270008: h_VkSubresourceHostMemcpySize_self, 1000127000: h_VkMemoryDedicatedRequirements_self};
/** name: [request encoder, reply decoder or null] */
export const GUEST = {
    vkCreateInstance: [g_vkCreateInstance, h_vkCreateInstance_reply],
    vkDestroyInstance: [g_vkDestroyInstance, h_vkDestroyInstance_reply],
    vkEnumeratePhysicalDevices: [g_vkEnumeratePhysicalDevices, h_vkEnumeratePhysicalDevices_reply],
    vkGetPhysicalDeviceFeatures: [g_vkGetPhysicalDeviceFeatures, h_vkGetPhysicalDeviceFeatures_reply],
    vkGetPhysicalDeviceFormatProperties: [g_vkGetPhysicalDeviceFormatProperties, h_vkGetPhysicalDeviceFormatProperties_reply],
    vkGetPhysicalDeviceImageFormatProperties: [g_vkGetPhysicalDeviceImageFormatProperties, h_vkGetPhysicalDeviceImageFormatProperties_reply],
    vkGetPhysicalDeviceProperties: [g_vkGetPhysicalDeviceProperties, h_vkGetPhysicalDeviceProperties_reply],
    vkGetPhysicalDeviceQueueFamilyProperties: [g_vkGetPhysicalDeviceQueueFamilyProperties, h_vkGetPhysicalDeviceQueueFamilyProperties_reply],
    vkGetPhysicalDeviceMemoryProperties: [g_vkGetPhysicalDeviceMemoryProperties, h_vkGetPhysicalDeviceMemoryProperties_reply],
    vkCreateDevice: [g_vkCreateDevice, h_vkCreateDevice_reply],
    vkDestroyDevice: [g_vkDestroyDevice, h_vkDestroyDevice_reply],
    vkEnumerateInstanceExtensionProperties: [g_vkEnumerateInstanceExtensionProperties, h_vkEnumerateInstanceExtensionProperties_reply],
    vkEnumerateDeviceExtensionProperties: [g_vkEnumerateDeviceExtensionProperties, h_vkEnumerateDeviceExtensionProperties_reply],
    vkEnumerateInstanceLayerProperties: [g_vkEnumerateInstanceLayerProperties, h_vkEnumerateInstanceLayerProperties_reply],
    vkEnumerateDeviceLayerProperties: [g_vkEnumerateDeviceLayerProperties, h_vkEnumerateDeviceLayerProperties_reply],
    vkGetDeviceQueue: [g_vkGetDeviceQueue, h_vkGetDeviceQueue_reply],
    vkQueueSubmit: [g_vkQueueSubmit, h_vkQueueSubmit_reply],
    vkQueueWaitIdle: [g_vkQueueWaitIdle, h_vkQueueWaitIdle_reply],
    vkDeviceWaitIdle: [g_vkDeviceWaitIdle, h_vkDeviceWaitIdle_reply],
    vkAllocateMemory: [g_vkAllocateMemory, h_vkAllocateMemory_reply],
    vkFreeMemory: [g_vkFreeMemory, h_vkFreeMemory_reply],
    vkUnmapMemory: [g_vkUnmapMemory, h_vkUnmapMemory_reply],
    vkFlushMappedMemoryRanges: [g_vkFlushMappedMemoryRanges, h_vkFlushMappedMemoryRanges_reply],
    vkInvalidateMappedMemoryRanges: [g_vkInvalidateMappedMemoryRanges, h_vkInvalidateMappedMemoryRanges_reply],
    vkGetDeviceMemoryCommitment: [g_vkGetDeviceMemoryCommitment, h_vkGetDeviceMemoryCommitment_reply],
    vkBindBufferMemory: [g_vkBindBufferMemory, h_vkBindBufferMemory_reply],
    vkBindImageMemory: [g_vkBindImageMemory, h_vkBindImageMemory_reply],
    vkGetBufferMemoryRequirements: [g_vkGetBufferMemoryRequirements, h_vkGetBufferMemoryRequirements_reply],
    vkGetImageMemoryRequirements: [g_vkGetImageMemoryRequirements, h_vkGetImageMemoryRequirements_reply],
    vkGetImageSparseMemoryRequirements: [g_vkGetImageSparseMemoryRequirements, h_vkGetImageSparseMemoryRequirements_reply],
    vkGetPhysicalDeviceSparseImageFormatProperties: [g_vkGetPhysicalDeviceSparseImageFormatProperties, h_vkGetPhysicalDeviceSparseImageFormatProperties_reply],
    vkQueueBindSparse: [g_vkQueueBindSparse, h_vkQueueBindSparse_reply],
    vkCreateFence: [g_vkCreateFence, h_vkCreateFence_reply],
    vkDestroyFence: [g_vkDestroyFence, h_vkDestroyFence_reply],
    vkResetFences: [g_vkResetFences, h_vkResetFences_reply],
    vkGetFenceStatus: [g_vkGetFenceStatus, h_vkGetFenceStatus_reply],
    vkWaitForFences: [g_vkWaitForFences, h_vkWaitForFences_reply],
    vkCreateSemaphore: [g_vkCreateSemaphore, h_vkCreateSemaphore_reply],
    vkDestroySemaphore: [g_vkDestroySemaphore, h_vkDestroySemaphore_reply],
    vkCreateEvent: [g_vkCreateEvent, h_vkCreateEvent_reply],
    vkDestroyEvent: [g_vkDestroyEvent, h_vkDestroyEvent_reply],
    vkGetEventStatus: [g_vkGetEventStatus, h_vkGetEventStatus_reply],
    vkSetEvent: [g_vkSetEvent, h_vkSetEvent_reply],
    vkResetEvent: [g_vkResetEvent, h_vkResetEvent_reply],
    vkCreateQueryPool: [g_vkCreateQueryPool, h_vkCreateQueryPool_reply],
    vkDestroyQueryPool: [g_vkDestroyQueryPool, h_vkDestroyQueryPool_reply],
    vkGetQueryPoolResults: [g_vkGetQueryPoolResults, h_vkGetQueryPoolResults_reply],
    vkCreateBuffer: [g_vkCreateBuffer, h_vkCreateBuffer_reply],
    vkDestroyBuffer: [g_vkDestroyBuffer, h_vkDestroyBuffer_reply],
    vkCreateBufferView: [g_vkCreateBufferView, h_vkCreateBufferView_reply],
    vkDestroyBufferView: [g_vkDestroyBufferView, h_vkDestroyBufferView_reply],
    vkCreateImage: [g_vkCreateImage, h_vkCreateImage_reply],
    vkDestroyImage: [g_vkDestroyImage, h_vkDestroyImage_reply],
    vkGetImageSubresourceLayout: [g_vkGetImageSubresourceLayout, h_vkGetImageSubresourceLayout_reply],
    vkCreateImageView: [g_vkCreateImageView, h_vkCreateImageView_reply],
    vkDestroyImageView: [g_vkDestroyImageView, h_vkDestroyImageView_reply],
    vkCreateShaderModule: [g_vkCreateShaderModule, h_vkCreateShaderModule_reply],
    vkDestroyShaderModule: [g_vkDestroyShaderModule, h_vkDestroyShaderModule_reply],
    vkCreatePipelineCache: [g_vkCreatePipelineCache, h_vkCreatePipelineCache_reply],
    vkDestroyPipelineCache: [g_vkDestroyPipelineCache, h_vkDestroyPipelineCache_reply],
    vkGetPipelineCacheData: [g_vkGetPipelineCacheData, h_vkGetPipelineCacheData_reply],
    vkMergePipelineCaches: [g_vkMergePipelineCaches, h_vkMergePipelineCaches_reply],
    vkCreateGraphicsPipelines: [g_vkCreateGraphicsPipelines, h_vkCreateGraphicsPipelines_reply],
    vkCreateComputePipelines: [g_vkCreateComputePipelines, h_vkCreateComputePipelines_reply],
    vkDestroyPipeline: [g_vkDestroyPipeline, h_vkDestroyPipeline_reply],
    vkCreatePipelineLayout: [g_vkCreatePipelineLayout, h_vkCreatePipelineLayout_reply],
    vkDestroyPipelineLayout: [g_vkDestroyPipelineLayout, h_vkDestroyPipelineLayout_reply],
    vkCreateSampler: [g_vkCreateSampler, h_vkCreateSampler_reply],
    vkDestroySampler: [g_vkDestroySampler, h_vkDestroySampler_reply],
    vkCreateDescriptorSetLayout: [g_vkCreateDescriptorSetLayout, h_vkCreateDescriptorSetLayout_reply],
    vkDestroyDescriptorSetLayout: [g_vkDestroyDescriptorSetLayout, h_vkDestroyDescriptorSetLayout_reply],
    vkCreateDescriptorPool: [g_vkCreateDescriptorPool, h_vkCreateDescriptorPool_reply],
    vkDestroyDescriptorPool: [g_vkDestroyDescriptorPool, h_vkDestroyDescriptorPool_reply],
    vkResetDescriptorPool: [g_vkResetDescriptorPool, h_vkResetDescriptorPool_reply],
    vkAllocateDescriptorSets: [g_vkAllocateDescriptorSets, h_vkAllocateDescriptorSets_reply],
    vkFreeDescriptorSets: [g_vkFreeDescriptorSets, h_vkFreeDescriptorSets_reply],
    vkUpdateDescriptorSets: [g_vkUpdateDescriptorSets, h_vkUpdateDescriptorSets_reply],
    vkCreateFramebuffer: [g_vkCreateFramebuffer, h_vkCreateFramebuffer_reply],
    vkDestroyFramebuffer: [g_vkDestroyFramebuffer, h_vkDestroyFramebuffer_reply],
    vkCreateRenderPass: [g_vkCreateRenderPass, h_vkCreateRenderPass_reply],
    vkDestroyRenderPass: [g_vkDestroyRenderPass, h_vkDestroyRenderPass_reply],
    vkGetRenderAreaGranularity: [g_vkGetRenderAreaGranularity, h_vkGetRenderAreaGranularity_reply],
    vkCreateCommandPool: [g_vkCreateCommandPool, h_vkCreateCommandPool_reply],
    vkDestroyCommandPool: [g_vkDestroyCommandPool, h_vkDestroyCommandPool_reply],
    vkResetCommandPool: [g_vkResetCommandPool, h_vkResetCommandPool_reply],
    vkAllocateCommandBuffers: [g_vkAllocateCommandBuffers, h_vkAllocateCommandBuffers_reply],
    vkFreeCommandBuffers: [g_vkFreeCommandBuffers, h_vkFreeCommandBuffers_reply],
    vkBeginCommandBuffer: [g_vkBeginCommandBuffer, h_vkBeginCommandBuffer_reply],
    vkEndCommandBuffer: [g_vkEndCommandBuffer, h_vkEndCommandBuffer_reply],
    vkResetCommandBuffer: [g_vkResetCommandBuffer, h_vkResetCommandBuffer_reply],
    vkCmdBindPipeline: [g_vkCmdBindPipeline, h_vkCmdBindPipeline_reply],
    vkCmdSetViewport: [g_vkCmdSetViewport, h_vkCmdSetViewport_reply],
    vkCmdSetScissor: [g_vkCmdSetScissor, h_vkCmdSetScissor_reply],
    vkCmdSetLineWidth: [g_vkCmdSetLineWidth, h_vkCmdSetLineWidth_reply],
    vkCmdSetDepthBias: [g_vkCmdSetDepthBias, h_vkCmdSetDepthBias_reply],
    vkCmdSetBlendConstants: [g_vkCmdSetBlendConstants, h_vkCmdSetBlendConstants_reply],
    vkCmdSetDepthBounds: [g_vkCmdSetDepthBounds, h_vkCmdSetDepthBounds_reply],
    vkCmdSetStencilCompareMask: [g_vkCmdSetStencilCompareMask, h_vkCmdSetStencilCompareMask_reply],
    vkCmdSetStencilWriteMask: [g_vkCmdSetStencilWriteMask, h_vkCmdSetStencilWriteMask_reply],
    vkCmdSetStencilReference: [g_vkCmdSetStencilReference, h_vkCmdSetStencilReference_reply],
    vkCmdBindDescriptorSets: [g_vkCmdBindDescriptorSets, h_vkCmdBindDescriptorSets_reply],
    vkCmdBindIndexBuffer: [g_vkCmdBindIndexBuffer, h_vkCmdBindIndexBuffer_reply],
    vkCmdBindVertexBuffers: [g_vkCmdBindVertexBuffers, h_vkCmdBindVertexBuffers_reply],
    vkCmdDraw: [g_vkCmdDraw, h_vkCmdDraw_reply],
    vkCmdDrawIndexed: [g_vkCmdDrawIndexed, h_vkCmdDrawIndexed_reply],
    vkCmdDrawIndirect: [g_vkCmdDrawIndirect, h_vkCmdDrawIndirect_reply],
    vkCmdDrawIndexedIndirect: [g_vkCmdDrawIndexedIndirect, h_vkCmdDrawIndexedIndirect_reply],
    vkCmdDispatch: [g_vkCmdDispatch, h_vkCmdDispatch_reply],
    vkCmdDispatchIndirect: [g_vkCmdDispatchIndirect, h_vkCmdDispatchIndirect_reply],
    vkCmdCopyBuffer: [g_vkCmdCopyBuffer, h_vkCmdCopyBuffer_reply],
    vkCmdCopyImage: [g_vkCmdCopyImage, h_vkCmdCopyImage_reply],
    vkCmdBlitImage: [g_vkCmdBlitImage, h_vkCmdBlitImage_reply],
    vkCmdCopyBufferToImage: [g_vkCmdCopyBufferToImage, h_vkCmdCopyBufferToImage_reply],
    vkCmdCopyImageToBuffer: [g_vkCmdCopyImageToBuffer, h_vkCmdCopyImageToBuffer_reply],
    vkCmdUpdateBuffer: [g_vkCmdUpdateBuffer, h_vkCmdUpdateBuffer_reply],
    vkCmdFillBuffer: [g_vkCmdFillBuffer, h_vkCmdFillBuffer_reply],
    vkCmdClearColorImage: [g_vkCmdClearColorImage, h_vkCmdClearColorImage_reply],
    vkCmdClearDepthStencilImage: [g_vkCmdClearDepthStencilImage, h_vkCmdClearDepthStencilImage_reply],
    vkCmdClearAttachments: [g_vkCmdClearAttachments, h_vkCmdClearAttachments_reply],
    vkCmdResolveImage: [g_vkCmdResolveImage, h_vkCmdResolveImage_reply],
    vkCmdSetEvent: [g_vkCmdSetEvent, h_vkCmdSetEvent_reply],
    vkCmdResetEvent: [g_vkCmdResetEvent, h_vkCmdResetEvent_reply],
    vkCmdWaitEvents: [g_vkCmdWaitEvents, h_vkCmdWaitEvents_reply],
    vkCmdPipelineBarrier: [g_vkCmdPipelineBarrier, h_vkCmdPipelineBarrier_reply],
    vkCmdBeginQuery: [g_vkCmdBeginQuery, h_vkCmdBeginQuery_reply],
    vkCmdEndQuery: [g_vkCmdEndQuery, h_vkCmdEndQuery_reply],
    vkCmdResetQueryPool: [g_vkCmdResetQueryPool, h_vkCmdResetQueryPool_reply],
    vkCmdWriteTimestamp: [g_vkCmdWriteTimestamp, h_vkCmdWriteTimestamp_reply],
    vkCmdCopyQueryPoolResults: [g_vkCmdCopyQueryPoolResults, h_vkCmdCopyQueryPoolResults_reply],
    vkCmdPushConstants: [g_vkCmdPushConstants, h_vkCmdPushConstants_reply],
    vkCmdBeginRenderPass: [g_vkCmdBeginRenderPass, h_vkCmdBeginRenderPass_reply],
    vkCmdNextSubpass: [g_vkCmdNextSubpass, h_vkCmdNextSubpass_reply],
    vkCmdEndRenderPass: [g_vkCmdEndRenderPass, h_vkCmdEndRenderPass_reply],
    vkCmdExecuteCommands: [g_vkCmdExecuteCommands, h_vkCmdExecuteCommands_reply],
    vkEnumerateInstanceVersion: [g_vkEnumerateInstanceVersion, h_vkEnumerateInstanceVersion_reply],
    vkBindBufferMemory2: [g_vkBindBufferMemory2, h_vkBindBufferMemory2_reply],
    vkBindImageMemory2: [g_vkBindImageMemory2, h_vkBindImageMemory2_reply],
    vkGetDeviceGroupPeerMemoryFeatures: [g_vkGetDeviceGroupPeerMemoryFeatures, h_vkGetDeviceGroupPeerMemoryFeatures_reply],
    vkCmdSetDeviceMask: [g_vkCmdSetDeviceMask, h_vkCmdSetDeviceMask_reply],
    vkCmdDispatchBase: [g_vkCmdDispatchBase, h_vkCmdDispatchBase_reply],
    vkEnumeratePhysicalDeviceGroups: [g_vkEnumeratePhysicalDeviceGroups, h_vkEnumeratePhysicalDeviceGroups_reply],
    vkGetImageMemoryRequirements2: [g_vkGetImageMemoryRequirements2, h_vkGetImageMemoryRequirements2_reply],
    vkGetBufferMemoryRequirements2: [g_vkGetBufferMemoryRequirements2, h_vkGetBufferMemoryRequirements2_reply],
    vkGetImageSparseMemoryRequirements2: [g_vkGetImageSparseMemoryRequirements2, h_vkGetImageSparseMemoryRequirements2_reply],
    vkGetPhysicalDeviceFeatures2: [g_vkGetPhysicalDeviceFeatures2, h_vkGetPhysicalDeviceFeatures2_reply],
    vkGetPhysicalDeviceProperties2: [g_vkGetPhysicalDeviceProperties2, h_vkGetPhysicalDeviceProperties2_reply],
    vkGetPhysicalDeviceFormatProperties2: [g_vkGetPhysicalDeviceFormatProperties2, h_vkGetPhysicalDeviceFormatProperties2_reply],
    vkGetPhysicalDeviceImageFormatProperties2: [g_vkGetPhysicalDeviceImageFormatProperties2, h_vkGetPhysicalDeviceImageFormatProperties2_reply],
    vkGetPhysicalDeviceQueueFamilyProperties2: [g_vkGetPhysicalDeviceQueueFamilyProperties2, h_vkGetPhysicalDeviceQueueFamilyProperties2_reply],
    vkGetPhysicalDeviceMemoryProperties2: [g_vkGetPhysicalDeviceMemoryProperties2, h_vkGetPhysicalDeviceMemoryProperties2_reply],
    vkGetPhysicalDeviceSparseImageFormatProperties2: [g_vkGetPhysicalDeviceSparseImageFormatProperties2, h_vkGetPhysicalDeviceSparseImageFormatProperties2_reply],
    vkTrimCommandPool: [g_vkTrimCommandPool, h_vkTrimCommandPool_reply],
    vkGetDeviceQueue2: [g_vkGetDeviceQueue2, h_vkGetDeviceQueue2_reply],
    vkCreateSamplerYcbcrConversion: [g_vkCreateSamplerYcbcrConversion, h_vkCreateSamplerYcbcrConversion_reply],
    vkDestroySamplerYcbcrConversion: [g_vkDestroySamplerYcbcrConversion, h_vkDestroySamplerYcbcrConversion_reply],
    vkCreateDescriptorUpdateTemplate: [g_vkCreateDescriptorUpdateTemplate, h_vkCreateDescriptorUpdateTemplate_reply],
    vkDestroyDescriptorUpdateTemplate: [g_vkDestroyDescriptorUpdateTemplate, h_vkDestroyDescriptorUpdateTemplate_reply],
    vkGetPhysicalDeviceExternalBufferProperties: [g_vkGetPhysicalDeviceExternalBufferProperties, h_vkGetPhysicalDeviceExternalBufferProperties_reply],
    vkGetPhysicalDeviceExternalFenceProperties: [g_vkGetPhysicalDeviceExternalFenceProperties, h_vkGetPhysicalDeviceExternalFenceProperties_reply],
    vkGetPhysicalDeviceExternalSemaphoreProperties: [g_vkGetPhysicalDeviceExternalSemaphoreProperties, h_vkGetPhysicalDeviceExternalSemaphoreProperties_reply],
    vkGetDescriptorSetLayoutSupport: [g_vkGetDescriptorSetLayoutSupport, h_vkGetDescriptorSetLayoutSupport_reply],
    vkCmdDrawIndirectCount: [g_vkCmdDrawIndirectCount, h_vkCmdDrawIndirectCount_reply],
    vkCmdDrawIndexedIndirectCount: [g_vkCmdDrawIndexedIndirectCount, h_vkCmdDrawIndexedIndirectCount_reply],
    vkCreateRenderPass2: [g_vkCreateRenderPass2, h_vkCreateRenderPass2_reply],
    vkCmdBeginRenderPass2: [g_vkCmdBeginRenderPass2, h_vkCmdBeginRenderPass2_reply],
    vkCmdNextSubpass2: [g_vkCmdNextSubpass2, h_vkCmdNextSubpass2_reply],
    vkCmdEndRenderPass2: [g_vkCmdEndRenderPass2, h_vkCmdEndRenderPass2_reply],
    vkResetQueryPool: [g_vkResetQueryPool, h_vkResetQueryPool_reply],
    vkGetSemaphoreCounterValue: [g_vkGetSemaphoreCounterValue, h_vkGetSemaphoreCounterValue_reply],
    vkWaitSemaphores: [g_vkWaitSemaphores, h_vkWaitSemaphores_reply],
    vkSignalSemaphore: [g_vkSignalSemaphore, h_vkSignalSemaphore_reply],
    vkGetBufferDeviceAddress: [g_vkGetBufferDeviceAddress, h_vkGetBufferDeviceAddress_reply],
    vkGetBufferOpaqueCaptureAddress: [g_vkGetBufferOpaqueCaptureAddress, h_vkGetBufferOpaqueCaptureAddress_reply],
    vkGetDeviceMemoryOpaqueCaptureAddress: [g_vkGetDeviceMemoryOpaqueCaptureAddress, h_vkGetDeviceMemoryOpaqueCaptureAddress_reply],
    vkSetReplyCommandStreamMESA: [g_vkSetReplyCommandStreamMESA, h_vkSetReplyCommandStreamMESA_reply],
    vkSeekReplyCommandStreamMESA: [g_vkSeekReplyCommandStreamMESA, h_vkSeekReplyCommandStreamMESA_reply],
    vkExecuteCommandStreamsMESA: [g_vkExecuteCommandStreamsMESA, h_vkExecuteCommandStreamsMESA_reply],
    vkCmdBindTransformFeedbackBuffersEXT: [g_vkCmdBindTransformFeedbackBuffersEXT, h_vkCmdBindTransformFeedbackBuffersEXT_reply],
    vkCmdBeginTransformFeedbackEXT: [g_vkCmdBeginTransformFeedbackEXT, h_vkCmdBeginTransformFeedbackEXT_reply],
    vkCmdEndTransformFeedbackEXT: [g_vkCmdEndTransformFeedbackEXT, h_vkCmdEndTransformFeedbackEXT_reply],
    vkCmdBeginQueryIndexedEXT: [g_vkCmdBeginQueryIndexedEXT, h_vkCmdBeginQueryIndexedEXT_reply],
    vkCmdEndQueryIndexedEXT: [g_vkCmdEndQueryIndexedEXT, h_vkCmdEndQueryIndexedEXT_reply],
    vkCmdDrawIndirectByteCountEXT: [g_vkCmdDrawIndirectByteCountEXT, h_vkCmdDrawIndirectByteCountEXT_reply],
    vkGetImageDrmFormatModifierPropertiesEXT: [g_vkGetImageDrmFormatModifierPropertiesEXT, h_vkGetImageDrmFormatModifierPropertiesEXT_reply],
    vkCreateRingMESA: [g_vkCreateRingMESA, h_vkCreateRingMESA_reply],
    vkDestroyRingMESA: [g_vkDestroyRingMESA, h_vkDestroyRingMESA_reply],
    vkNotifyRingMESA: [g_vkNotifyRingMESA, h_vkNotifyRingMESA_reply],
    vkWriteRingExtraMESA: [g_vkWriteRingExtraMESA, h_vkWriteRingExtraMESA_reply],
    vkGetMemoryResourcePropertiesMESA: [g_vkGetMemoryResourcePropertiesMESA, h_vkGetMemoryResourcePropertiesMESA_reply],
    vkGetPhysicalDeviceToolProperties: [g_vkGetPhysicalDeviceToolProperties, h_vkGetPhysicalDeviceToolProperties_reply],
    vkCreatePrivateDataSlot: [g_vkCreatePrivateDataSlot, h_vkCreatePrivateDataSlot_reply],
    vkDestroyPrivateDataSlot: [g_vkDestroyPrivateDataSlot, h_vkDestroyPrivateDataSlot_reply],
    vkSetPrivateData: [g_vkSetPrivateData, h_vkSetPrivateData_reply],
    vkGetPrivateData: [g_vkGetPrivateData, h_vkGetPrivateData_reply],
    vkCmdSetEvent2: [g_vkCmdSetEvent2, h_vkCmdSetEvent2_reply],
    vkCmdResetEvent2: [g_vkCmdResetEvent2, h_vkCmdResetEvent2_reply],
    vkCmdWaitEvents2: [g_vkCmdWaitEvents2, h_vkCmdWaitEvents2_reply],
    vkCmdPipelineBarrier2: [g_vkCmdPipelineBarrier2, h_vkCmdPipelineBarrier2_reply],
    vkCmdWriteTimestamp2: [g_vkCmdWriteTimestamp2, h_vkCmdWriteTimestamp2_reply],
    vkQueueSubmit2: [g_vkQueueSubmit2, h_vkQueueSubmit2_reply],
    vkCmdCopyBuffer2: [g_vkCmdCopyBuffer2, h_vkCmdCopyBuffer2_reply],
    vkCmdCopyImage2: [g_vkCmdCopyImage2, h_vkCmdCopyImage2_reply],
    vkCmdCopyBufferToImage2: [g_vkCmdCopyBufferToImage2, h_vkCmdCopyBufferToImage2_reply],
    vkCmdCopyImageToBuffer2: [g_vkCmdCopyImageToBuffer2, h_vkCmdCopyImageToBuffer2_reply],
    vkCmdBlitImage2: [g_vkCmdBlitImage2, h_vkCmdBlitImage2_reply],
    vkCmdResolveImage2: [g_vkCmdResolveImage2, h_vkCmdResolveImage2_reply],
    vkCmdBeginRendering: [g_vkCmdBeginRendering, h_vkCmdBeginRendering_reply],
    vkCmdEndRendering: [g_vkCmdEndRendering, h_vkCmdEndRendering_reply],
    vkCmdSetCullMode: [g_vkCmdSetCullMode, h_vkCmdSetCullMode_reply],
    vkCmdSetFrontFace: [g_vkCmdSetFrontFace, h_vkCmdSetFrontFace_reply],
    vkCmdSetPrimitiveTopology: [g_vkCmdSetPrimitiveTopology, h_vkCmdSetPrimitiveTopology_reply],
    vkCmdSetViewportWithCount: [g_vkCmdSetViewportWithCount, h_vkCmdSetViewportWithCount_reply],
    vkCmdSetScissorWithCount: [g_vkCmdSetScissorWithCount, h_vkCmdSetScissorWithCount_reply],
    vkCmdBindVertexBuffers2: [g_vkCmdBindVertexBuffers2, h_vkCmdBindVertexBuffers2_reply],
    vkCmdSetDepthTestEnable: [g_vkCmdSetDepthTestEnable, h_vkCmdSetDepthTestEnable_reply],
    vkCmdSetDepthWriteEnable: [g_vkCmdSetDepthWriteEnable, h_vkCmdSetDepthWriteEnable_reply],
    vkCmdSetDepthCompareOp: [g_vkCmdSetDepthCompareOp, h_vkCmdSetDepthCompareOp_reply],
    vkCmdSetDepthBoundsTestEnable: [g_vkCmdSetDepthBoundsTestEnable, h_vkCmdSetDepthBoundsTestEnable_reply],
    vkCmdSetStencilTestEnable: [g_vkCmdSetStencilTestEnable, h_vkCmdSetStencilTestEnable_reply],
    vkCmdSetStencilOp: [g_vkCmdSetStencilOp, h_vkCmdSetStencilOp_reply],
    vkCmdSetRasterizerDiscardEnable: [g_vkCmdSetRasterizerDiscardEnable, h_vkCmdSetRasterizerDiscardEnable_reply],
    vkCmdSetDepthBiasEnable: [g_vkCmdSetDepthBiasEnable, h_vkCmdSetDepthBiasEnable_reply],
    vkCmdSetPrimitiveRestartEnable: [g_vkCmdSetPrimitiveRestartEnable, h_vkCmdSetPrimitiveRestartEnable_reply],
    vkGetDeviceBufferMemoryRequirements: [g_vkGetDeviceBufferMemoryRequirements, h_vkGetDeviceBufferMemoryRequirements_reply],
    vkGetDeviceImageMemoryRequirements: [g_vkGetDeviceImageMemoryRequirements, h_vkGetDeviceImageMemoryRequirements_reply],
    vkGetDeviceImageSparseMemoryRequirements: [g_vkGetDeviceImageSparseMemoryRequirements, h_vkGetDeviceImageSparseMemoryRequirements_reply],
    vkCmdSetPatchControlPointsEXT: [g_vkCmdSetPatchControlPointsEXT, h_vkCmdSetPatchControlPointsEXT_reply],
    vkCmdSetLogicOpEXT: [g_vkCmdSetLogicOpEXT, h_vkCmdSetLogicOpEXT_reply],
    vkGetPhysicalDeviceCalibrateableTimeDomainsKHR: [g_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR, h_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR_reply],
    vkGetCalibratedTimestampsKHR: [g_vkGetCalibratedTimestampsKHR, h_vkGetCalibratedTimestampsKHR_reply],
    vkCmdSetLineStipple: [g_vkCmdSetLineStipple, h_vkCmdSetLineStipple_reply],
    vkCmdBeginConditionalRenderingEXT: [g_vkCmdBeginConditionalRenderingEXT, h_vkCmdBeginConditionalRenderingEXT_reply],
    vkCmdEndConditionalRenderingEXT: [g_vkCmdEndConditionalRenderingEXT, h_vkCmdEndConditionalRenderingEXT_reply],
    vkResetFenceResourceMESA: [g_vkResetFenceResourceMESA, h_vkResetFenceResourceMESA_reply],
    vkWaitSemaphoreResourceMESA: [g_vkWaitSemaphoreResourceMESA, h_vkWaitSemaphoreResourceMESA_reply],
    vkImportSemaphoreResourceMESA: [g_vkImportSemaphoreResourceMESA, h_vkImportSemaphoreResourceMESA_reply],
    vkCmdDrawMultiEXT: [g_vkCmdDrawMultiEXT, h_vkCmdDrawMultiEXT_reply],
    vkCmdDrawMultiIndexedEXT: [g_vkCmdDrawMultiIndexedEXT, h_vkCmdDrawMultiIndexedEXT_reply],
    vkCmdPushDescriptorSet: [g_vkCmdPushDescriptorSet, h_vkCmdPushDescriptorSet_reply],
    vkSubmitVirtqueueSeqnoMESA: [g_vkSubmitVirtqueueSeqnoMESA, h_vkSubmitVirtqueueSeqnoMESA_reply],
    vkWaitVirtqueueSeqnoMESA: [g_vkWaitVirtqueueSeqnoMESA, h_vkWaitVirtqueueSeqnoMESA_reply],
    vkWaitRingSeqnoMESA: [g_vkWaitRingSeqnoMESA, h_vkWaitRingSeqnoMESA_reply],
    vkCmdSetColorWriteEnableEXT: [g_vkCmdSetColorWriteEnableEXT, h_vkCmdSetColorWriteEnableEXT_reply],
    vkCmdSetVertexInputEXT: [g_vkCmdSetVertexInputEXT, h_vkCmdSetVertexInputEXT_reply],
    vkCmdSetTessellationDomainOriginEXT: [g_vkCmdSetTessellationDomainOriginEXT, h_vkCmdSetTessellationDomainOriginEXT_reply],
    vkCmdSetDepthClampEnableEXT: [g_vkCmdSetDepthClampEnableEXT, h_vkCmdSetDepthClampEnableEXT_reply],
    vkCmdSetPolygonModeEXT: [g_vkCmdSetPolygonModeEXT, h_vkCmdSetPolygonModeEXT_reply],
    vkCmdSetRasterizationSamplesEXT: [g_vkCmdSetRasterizationSamplesEXT, h_vkCmdSetRasterizationSamplesEXT_reply],
    vkCmdSetSampleMaskEXT: [g_vkCmdSetSampleMaskEXT, h_vkCmdSetSampleMaskEXT_reply],
    vkCmdSetAlphaToCoverageEnableEXT: [g_vkCmdSetAlphaToCoverageEnableEXT, h_vkCmdSetAlphaToCoverageEnableEXT_reply],
    vkCmdSetAlphaToOneEnableEXT: [g_vkCmdSetAlphaToOneEnableEXT, h_vkCmdSetAlphaToOneEnableEXT_reply],
    vkCmdSetLogicOpEnableEXT: [g_vkCmdSetLogicOpEnableEXT, h_vkCmdSetLogicOpEnableEXT_reply],
    vkCmdSetColorBlendEnableEXT: [g_vkCmdSetColorBlendEnableEXT, h_vkCmdSetColorBlendEnableEXT_reply],
    vkCmdSetColorBlendEquationEXT: [g_vkCmdSetColorBlendEquationEXT, h_vkCmdSetColorBlendEquationEXT_reply],
    vkCmdSetColorWriteMaskEXT: [g_vkCmdSetColorWriteMaskEXT, h_vkCmdSetColorWriteMaskEXT_reply],
    vkCmdSetRasterizationStreamEXT: [g_vkCmdSetRasterizationStreamEXT, h_vkCmdSetRasterizationStreamEXT_reply],
    vkCmdSetConservativeRasterizationModeEXT: [g_vkCmdSetConservativeRasterizationModeEXT, h_vkCmdSetConservativeRasterizationModeEXT_reply],
    vkCmdSetExtraPrimitiveOverestimationSizeEXT: [g_vkCmdSetExtraPrimitiveOverestimationSizeEXT, h_vkCmdSetExtraPrimitiveOverestimationSizeEXT_reply],
    vkCmdSetDepthClipEnableEXT: [g_vkCmdSetDepthClipEnableEXT, h_vkCmdSetDepthClipEnableEXT_reply],
    vkCmdSetSampleLocationsEnableEXT: [g_vkCmdSetSampleLocationsEnableEXT, h_vkCmdSetSampleLocationsEnableEXT_reply],
    vkCmdSetColorBlendAdvancedEXT: [g_vkCmdSetColorBlendAdvancedEXT, h_vkCmdSetColorBlendAdvancedEXT_reply],
    vkCmdSetProvokingVertexModeEXT: [g_vkCmdSetProvokingVertexModeEXT, h_vkCmdSetProvokingVertexModeEXT_reply],
    vkCmdSetLineRasterizationModeEXT: [g_vkCmdSetLineRasterizationModeEXT, h_vkCmdSetLineRasterizationModeEXT_reply],
    vkCmdSetLineStippleEnableEXT: [g_vkCmdSetLineStippleEnableEXT, h_vkCmdSetLineStippleEnableEXT_reply],
    vkCmdSetDepthClipNegativeOneToOneEXT: [g_vkCmdSetDepthClipNegativeOneToOneEXT, h_vkCmdSetDepthClipNegativeOneToOneEXT_reply],
    vkGetPhysicalDeviceFragmentShadingRatesKHR: [g_vkGetPhysicalDeviceFragmentShadingRatesKHR, h_vkGetPhysicalDeviceFragmentShadingRatesKHR_reply],
    vkCmdSetFragmentShadingRateKHR: [g_vkCmdSetFragmentShadingRateKHR, h_vkCmdSetFragmentShadingRateKHR_reply],
    vkCmdBindIndexBuffer2: [g_vkCmdBindIndexBuffer2, h_vkCmdBindIndexBuffer2_reply],
    vkGetRenderingAreaGranularity: [g_vkGetRenderingAreaGranularity, h_vkGetRenderingAreaGranularity_reply],
    vkGetDeviceImageSubresourceLayout: [g_vkGetDeviceImageSubresourceLayout, h_vkGetDeviceImageSubresourceLayout_reply],
    vkGetImageSubresourceLayout2: [g_vkGetImageSubresourceLayout2, h_vkGetImageSubresourceLayout2_reply],
    vkCmdSetSampleLocationsEXT: [g_vkCmdSetSampleLocationsEXT, h_vkCmdSetSampleLocationsEXT_reply],
    vkGetPhysicalDeviceMultisamplePropertiesEXT: [g_vkGetPhysicalDeviceMultisamplePropertiesEXT, h_vkGetPhysicalDeviceMultisamplePropertiesEXT_reply],
    vkUnmapMemory2: [g_vkUnmapMemory2, h_vkUnmapMemory2_reply],
    vkCmdSetRenderingAttachmentLocations: [g_vkCmdSetRenderingAttachmentLocations, h_vkCmdSetRenderingAttachmentLocations_reply],
    vkCmdSetRenderingInputAttachmentIndices: [g_vkCmdSetRenderingInputAttachmentIndices, h_vkCmdSetRenderingInputAttachmentIndices_reply],
    vkCmdBindDescriptorSets2: [g_vkCmdBindDescriptorSets2, h_vkCmdBindDescriptorSets2_reply],
    vkCmdPushConstants2: [g_vkCmdPushConstants2, h_vkCmdPushConstants2_reply],
    vkCmdPushDescriptorSet2: [g_vkCmdPushDescriptorSet2, h_vkCmdPushDescriptorSet2_reply],
    vkCopyImageToImage: [g_vkCopyImageToImage, h_vkCopyImageToImage_reply],
    vkTransitionImageLayout: [g_vkTransitionImageLayout, h_vkTransitionImageLayout_reply],
    vkCopyImageToMemoryMESA: [g_vkCopyImageToMemoryMESA, h_vkCopyImageToMemoryMESA_reply],
    vkCopyMemoryToImageMESA: [g_vkCopyMemoryToImageMESA, h_vkCopyMemoryToImageMESA_reply],
    vkCreateDeferredOperationKHR: [g_vkCreateDeferredOperationKHR, h_vkCreateDeferredOperationKHR_reply],
    vkDestroyDeferredOperationKHR: [g_vkDestroyDeferredOperationKHR, h_vkDestroyDeferredOperationKHR_reply],
    vkGetDeferredOperationMaxConcurrencyKHR: [g_vkGetDeferredOperationMaxConcurrencyKHR, h_vkGetDeferredOperationMaxConcurrencyKHR_reply],
    vkGetDeferredOperationResultKHR: [g_vkGetDeferredOperationResultKHR, h_vkGetDeferredOperationResultKHR_reply],
    vkDeferredOperationJoinKHR: [g_vkDeferredOperationJoinKHR, h_vkDeferredOperationJoinKHR_reply],
    vkCmdSetDepthBias2EXT: [g_vkCmdSetDepthBias2EXT, h_vkCmdSetDepthBias2EXT_reply],
    vkCmdSetAttachmentFeedbackLoopEnableEXT: [g_vkCmdSetAttachmentFeedbackLoopEnableEXT, h_vkCmdSetAttachmentFeedbackLoopEnableEXT_reply],
    vkCmdSetDepthClampRangeEXT: [g_vkCmdSetDepthClampRangeEXT, h_vkCmdSetDepthClampRangeEXT_reply],
    vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR: [g_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR, h_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR_reply],
    vkCmdDrawMeshTasksEXT: [g_vkCmdDrawMeshTasksEXT, h_vkCmdDrawMeshTasksEXT_reply],
    vkCmdDrawMeshTasksIndirectEXT: [g_vkCmdDrawMeshTasksIndirectEXT, h_vkCmdDrawMeshTasksIndirectEXT_reply],
    vkCmdDrawMeshTasksIndirectCountEXT: [g_vkCmdDrawMeshTasksIndirectCountEXT, h_vkCmdDrawMeshTasksIndirectCountEXT_reply],
    vkWriteSamplerDescriptorMESA: [g_vkWriteSamplerDescriptorMESA, h_vkWriteSamplerDescriptorMESA_reply],
    vkWriteResourceDescriptorMESA: [g_vkWriteResourceDescriptorMESA, h_vkWriteResourceDescriptorMESA_reply],
    vkCmdBindSamplerHeapEXT: [g_vkCmdBindSamplerHeapEXT, h_vkCmdBindSamplerHeapEXT_reply],
    vkCmdBindResourceHeapEXT: [g_vkCmdBindResourceHeapEXT, h_vkCmdBindResourceHeapEXT_reply],
    vkCmdPushDataEXT: [g_vkCmdPushDataEXT, h_vkCmdPushDataEXT_reply],
    vkGetImageOpaqueCaptureDataEXT: [g_vkGetImageOpaqueCaptureDataEXT, h_vkGetImageOpaqueCaptureDataEXT_reply],
    vkGetPhysicalDeviceDescriptorSizeEXT: [g_vkGetPhysicalDeviceDescriptorSizeEXT, h_vkGetPhysicalDeviceDescriptorSizeEXT_reply],
    vkRegisterCustomBorderColorEXT: [g_vkRegisterCustomBorderColorEXT, h_vkRegisterCustomBorderColorEXT_reply],
    vkUnregisterCustomBorderColorEXT: [g_vkUnregisterCustomBorderColorEXT, h_vkUnregisterCustomBorderColorEXT_reply],
};

function g_vkCreateInstance(w, a)
{
    w.u32(0);
    w.u32(a.cmd_flags || 0);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkInstanceCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pInstance != null)
    {
        w.u64(1);
        w.h(a.pInstance);
    }
    else w.u64(0);
}
function h_vkCreateInstance_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pInstance = r.h();
    }
    else
    {
        a.pInstance = null;
    }
    return a;
}
function g_vkDestroyInstance(w, a)
{
    w.u32(1);
    w.u32(a.cmd_flags || 0);
    w.h(a.instance);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyInstance_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkEnumeratePhysicalDevices(w, a)
{
    w.u32(2);
    w.u32(a.cmd_flags || 0);
    w.h(a.instance);
    if(a.pPhysicalDeviceCount != null)
    {
        w.u64(1);
        w.u32(a.pPhysicalDeviceCount);
    }
    else w.u64(0);
    if(a.pPhysicalDevices)
    {
        w.size((a.pPhysicalDeviceCount || 0));
        for(let i = 0; i < (a.pPhysicalDeviceCount || 0); i++)
        {
            w.h((a.pPhysicalDevices || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumeratePhysicalDevices_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPhysicalDeviceCount = r.u32();
    }
    else
    {
        a.pPhysicalDeviceCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pPhysicalDevices = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pPhysicalDevices[i] = r.h();
        }
    }
    else
    {
        r.size();
        a.pPhysicalDevices = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceFeatures(w, a)
{
    w.u32(3);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pFeatures != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceFeatures_partial(w, a.pFeatures || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceFeatures_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pFeatures = h_VkPhysicalDeviceFeatures(r);
    }
    else
    {
        a.pFeatures = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceFormatProperties(w, a)
{
    w.u32(4);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.format);
    if(a.pFormatProperties != null)
    {
        w.u64(1);
        g_VkFormatProperties_partial(w, a.pFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceFormatProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pFormatProperties = h_VkFormatProperties(r);
    }
    else
    {
        a.pFormatProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceImageFormatProperties(w, a)
{
    w.u32(5);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.format);
    w.i32(a.type);
    w.i32(a.tiling);
    w.u32(a.usage);
    w.u32(a.flags);
    if(a.pImageFormatProperties != null)
    {
        w.u64(1);
        g_VkImageFormatProperties_partial(w, a.pImageFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceImageFormatProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pImageFormatProperties = h_VkImageFormatProperties(r);
    }
    else
    {
        a.pImageFormatProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceProperties(w, a)
{
    w.u32(6);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pProperties != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceProperties_partial(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pProperties = h_VkPhysicalDeviceProperties(r);
    }
    else
    {
        a.pProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceQueueFamilyProperties(w, a)
{
    w.u32(7);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pQueueFamilyPropertyCount);
    }
    else w.u64(0);
    if(a.pQueueFamilyProperties)
    {
        w.size((a.pQueueFamilyPropertyCount || 0));
        for(let i = 0; i < (a.pQueueFamilyPropertyCount || 0); i++)
        {
            g_VkQueueFamilyProperties_partial(w, (a.pQueueFamilyProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceQueueFamilyProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    else
    {
        a.pQueueFamilyPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pQueueFamilyProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pQueueFamilyProperties[i] = h_VkQueueFamilyProperties(r);
        }
    }
    else
    {
        r.size();
        a.pQueueFamilyProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceMemoryProperties(w, a)
{
    w.u32(8);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pMemoryProperties != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceMemoryProperties_partial(w, a.pMemoryProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceMemoryProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryProperties = h_VkPhysicalDeviceMemoryProperties(r);
    }
    else
    {
        a.pMemoryProperties = null;
    }
    return a;
}
function g_vkCreateDevice(w, a)
{
    w.u32(11);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkDeviceCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pDevice != null)
    {
        w.u64(1);
        w.h(a.pDevice);
    }
    else w.u64(0);
}
function h_vkCreateDevice_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pDevice = r.h();
    }
    else
    {
        a.pDevice = null;
    }
    return a;
}
function g_vkDestroyDevice(w, a)
{
    w.u32(12);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyDevice_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkEnumerateInstanceExtensionProperties(w, a)
{
    w.u32(13);
    w.u32(a.cmd_flags || 0);
    if(a.pLayerName)
    {
        const string_size = a.pLayerName.length + 1;
        w.size(string_size);
        w.str(a.pLayerName, string_size);
    }
    else
    {
        w.size(0);
    }
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkExtensionProperties_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumerateInstanceExtensionProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkExtensionProperties(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkEnumerateDeviceExtensionProperties(w, a)
{
    w.u32(14);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pLayerName)
    {
        const string_size = a.pLayerName.length + 1;
        w.size(string_size);
        w.str(a.pLayerName, string_size);
    }
    else
    {
        w.size(0);
    }
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkExtensionProperties_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumerateDeviceExtensionProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkExtensionProperties(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkEnumerateInstanceLayerProperties(w, a)
{
    w.u32(15);
    w.u32(a.cmd_flags || 0);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkLayerProperties_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumerateInstanceLayerProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkLayerProperties(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkEnumerateDeviceLayerProperties(w, a)
{
    w.u32(16);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkLayerProperties_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumerateDeviceLayerProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkLayerProperties(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkGetDeviceQueue(w, a)
{
    w.u32(17);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.queueFamilyIndex);
    w.u32(a.queueIndex);
    if(a.pQueue != null)
    {
        w.u64(1);
        w.h(a.pQueue);
    }
    else w.u64(0);
}
function h_vkGetDeviceQueue_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pQueue = r.h();
    }
    else
    {
        a.pQueue = null;
    }
    return a;
}
function g_vkQueueSubmit(w, a)
{
    w.u32(18);
    w.u32(a.cmd_flags || 0);
    w.h(a.queue);
    w.u32(a.submitCount);
    if(a.pSubmits)
    {
        w.size(a.submitCount);
        for(let i = 0; i < a.submitCount; i++)
        {
            g_VkSubmitInfo(w, (a.pSubmits || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.h(a.fence);
}
function h_vkQueueSubmit_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkQueueWaitIdle(w, a)
{
    w.u32(19);
    w.u32(a.cmd_flags || 0);
    w.h(a.queue);
}
function h_vkQueueWaitIdle_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkDeviceWaitIdle(w, a)
{
    w.u32(20);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
}
function h_vkDeviceWaitIdle_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkAllocateMemory(w, a)
{
    w.u32(21);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pAllocateInfo != null)
    {
        w.u64(1);
        g_VkMemoryAllocateInfo(w, a.pAllocateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pMemory != null)
    {
        w.u64(1);
        w.h(a.pMemory);
    }
    else w.u64(0);
}
function h_vkAllocateMemory_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pMemory = r.h();
    }
    else
    {
        a.pMemory = null;
    }
    return a;
}
function g_vkFreeMemory(w, a)
{
    w.u32(22);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.memory);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkFreeMemory_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkUnmapMemory(w, a)
{
    w.u32(24);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.memory);
}
function h_vkUnmapMemory_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkFlushMappedMemoryRanges(w, a)
{
    w.u32(25);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.memoryRangeCount);
    if(a.pMemoryRanges)
    {
        w.size(a.memoryRangeCount);
        for(let i = 0; i < a.memoryRangeCount; i++)
        {
            g_VkMappedMemoryRange(w, (a.pMemoryRanges || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkFlushMappedMemoryRanges_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkInvalidateMappedMemoryRanges(w, a)
{
    w.u32(26);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.memoryRangeCount);
    if(a.pMemoryRanges)
    {
        w.size(a.memoryRangeCount);
        for(let i = 0; i < a.memoryRangeCount; i++)
        {
            g_VkMappedMemoryRange(w, (a.pMemoryRanges || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkInvalidateMappedMemoryRanges_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetDeviceMemoryCommitment(w, a)
{
    w.u32(27);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.memory);
    w.u64(a.pCommittedMemoryInBytes != null ? 1 : 0);
}
function h_vkGetDeviceMemoryCommitment_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pCommittedMemoryInBytes = r.u64();
    }
    else
    {
        a.pCommittedMemoryInBytes = null;
    }
    return a;
}
function g_vkBindBufferMemory(w, a)
{
    w.u32(28);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.buffer);
    w.h(a.memory);
    w.u64(a.memoryOffset);
}
function h_vkBindBufferMemory_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkBindImageMemory(w, a)
{
    w.u32(29);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    w.h(a.memory);
    w.u64(a.memoryOffset);
}
function h_vkBindImageMemory_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetBufferMemoryRequirements(w, a)
{
    w.u32(30);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.buffer);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetBufferMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetImageMemoryRequirements(w, a)
{
    w.u32(31);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetImageMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetImageSparseMemoryRequirements(w, a)
{
    w.u32(32);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        w.size((a.pSparseMemoryRequirementCount || 0));
        for(let i = 0; i < (a.pSparseMemoryRequirementCount || 0); i++)
        {
            g_VkSparseImageMemoryRequirements_partial(w, (a.pSparseMemoryRequirements || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetImageSparseMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else
    {
        a.pSparseMemoryRequirementCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pSparseMemoryRequirements = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pSparseMemoryRequirements[i] = h_VkSparseImageMemoryRequirements(r);
        }
    }
    else
    {
        r.size();
        a.pSparseMemoryRequirements = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceSparseImageFormatProperties(w, a)
{
    w.u32(33);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.format);
    w.i32(a.type);
    w.i32(a.samples);
    w.u32(a.usage);
    w.i32(a.tiling);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkSparseImageFormatProperties_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceSparseImageFormatProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkSparseImageFormatProperties(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkQueueBindSparse(w, a)
{
    w.u32(34);
    w.u32(a.cmd_flags || 0);
    w.h(a.queue);
    w.u32(a.bindInfoCount);
    if(a.pBindInfo)
    {
        w.size(a.bindInfoCount);
        for(let i = 0; i < a.bindInfoCount; i++)
        {
            g_VkBindSparseInfo(w, (a.pBindInfo || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.h(a.fence);
}
function h_vkQueueBindSparse_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCreateFence(w, a)
{
    w.u32(35);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkFenceCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pFence != null)
    {
        w.u64(1);
        w.h(a.pFence);
    }
    else w.u64(0);
}
function h_vkCreateFence_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pFence = r.h();
    }
    else
    {
        a.pFence = null;
    }
    return a;
}
function g_vkDestroyFence(w, a)
{
    w.u32(36);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.fence);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyFence_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkResetFences(w, a)
{
    w.u32(37);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.fenceCount);
    if(a.pFences)
    {
        w.size(a.fenceCount);
        for(let i = 0; i < a.fenceCount; i++)
        {
            w.h((a.pFences || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkResetFences_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetFenceStatus(w, a)
{
    w.u32(38);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.fence);
}
function h_vkGetFenceStatus_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkWaitForFences(w, a)
{
    w.u32(39);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.fenceCount);
    if(a.pFences)
    {
        w.size(a.fenceCount);
        for(let i = 0; i < a.fenceCount; i++)
        {
            w.h((a.pFences || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.waitAll);
    w.u64(a.timeout);
}
function h_vkWaitForFences_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCreateSemaphore(w, a)
{
    w.u32(40);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkSemaphoreCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pSemaphore != null)
    {
        w.u64(1);
        w.h(a.pSemaphore);
    }
    else w.u64(0);
}
function h_vkCreateSemaphore_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pSemaphore = r.h();
    }
    else
    {
        a.pSemaphore = null;
    }
    return a;
}
function g_vkDestroySemaphore(w, a)
{
    w.u32(41);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.semaphore);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroySemaphore_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateEvent(w, a)
{
    w.u32(42);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkEventCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pEvent != null)
    {
        w.u64(1);
        w.h(a.pEvent);
    }
    else w.u64(0);
}
function h_vkCreateEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pEvent = r.h();
    }
    else
    {
        a.pEvent = null;
    }
    return a;
}
function g_vkDestroyEvent(w, a)
{
    w.u32(43);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.event);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetEventStatus(w, a)
{
    w.u32(44);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.event);
}
function h_vkGetEventStatus_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkSetEvent(w, a)
{
    w.u32(45);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.event);
}
function h_vkSetEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkResetEvent(w, a)
{
    w.u32(46);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.event);
}
function h_vkResetEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCreateQueryPool(w, a)
{
    w.u32(47);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkQueryPoolCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pQueryPool != null)
    {
        w.u64(1);
        w.h(a.pQueryPool);
    }
    else w.u64(0);
}
function h_vkCreateQueryPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pQueryPool = r.h();
    }
    else
    {
        a.pQueryPool = null;
    }
    return a;
}
function g_vkDestroyQueryPool(w, a)
{
    w.u32(48);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.queryPool);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyQueryPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetQueryPoolResults(w, a)
{
    w.u32(49);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
    w.u64(a.dataSize);
    w.size(a.pData ? a.dataSize : 0);
    w.u64(a.stride);
    w.u32(a.flags);
}
function h_vkGetQueryPoolResults_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pData = r.blob(array_size);
    }
    else
    {
        r.size();
        a.pData = null;
    }
    return a;
}
function g_vkCreateBuffer(w, a)
{
    w.u32(50);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkBufferCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pBuffer != null)
    {
        w.u64(1);
        w.h(a.pBuffer);
    }
    else w.u64(0);
}
function h_vkCreateBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pBuffer = r.h();
    }
    else
    {
        a.pBuffer = null;
    }
    return a;
}
function g_vkDestroyBuffer(w, a)
{
    w.u32(51);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.buffer);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateBufferView(w, a)
{
    w.u32(52);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkBufferViewCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pView != null)
    {
        w.u64(1);
        w.h(a.pView);
    }
    else w.u64(0);
}
function h_vkCreateBufferView_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pView = r.h();
    }
    else
    {
        a.pView = null;
    }
    return a;
}
function g_vkDestroyBufferView(w, a)
{
    w.u32(53);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.bufferView);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyBufferView_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateImage(w, a)
{
    w.u32(54);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkImageCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pImage != null)
    {
        w.u64(1);
        w.h(a.pImage);
    }
    else w.u64(0);
}
function h_vkCreateImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pImage = r.h();
    }
    else
    {
        a.pImage = null;
    }
    return a;
}
function g_vkDestroyImage(w, a)
{
    w.u32(55);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetImageSubresourceLayout(w, a)
{
    w.u32(56);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pSubresource != null)
    {
        w.u64(1);
        g_VkImageSubresource(w, a.pSubresource || EMPTY);
    }
    else w.u64(0);
    if(a.pLayout != null)
    {
        w.u64(1);
        g_VkSubresourceLayout_partial(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetImageSubresourceLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pLayout = h_VkSubresourceLayout(r);
    }
    else
    {
        a.pLayout = null;
    }
    return a;
}
function g_vkCreateImageView(w, a)
{
    w.u32(57);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkImageViewCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pView != null)
    {
        w.u64(1);
        w.h(a.pView);
    }
    else w.u64(0);
}
function h_vkCreateImageView_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pView = r.h();
    }
    else
    {
        a.pView = null;
    }
    return a;
}
function g_vkDestroyImageView(w, a)
{
    w.u32(58);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.imageView);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyImageView_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateShaderModule(w, a)
{
    w.u32(59);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkShaderModuleCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pShaderModule != null)
    {
        w.u64(1);
        w.h(a.pShaderModule);
    }
    else w.u64(0);
}
function h_vkCreateShaderModule_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pShaderModule = r.h();
    }
    else
    {
        a.pShaderModule = null;
    }
    return a;
}
function g_vkDestroyShaderModule(w, a)
{
    w.u32(60);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.shaderModule);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyShaderModule_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreatePipelineCache(w, a)
{
    w.u32(61);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkPipelineCacheCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pPipelineCache != null)
    {
        w.u64(1);
        w.h(a.pPipelineCache);
    }
    else w.u64(0);
}
function h_vkCreatePipelineCache_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPipelineCache = r.h();
    }
    else
    {
        a.pPipelineCache = null;
    }
    return a;
}
function g_vkDestroyPipelineCache(w, a)
{
    w.u32(62);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipelineCache);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyPipelineCache_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPipelineCacheData(w, a)
{
    w.u32(63);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipelineCache);
    if(a.pDataSize != null)
    {
        w.u64(1);
        w.u64(a.pDataSize);
    }
    else w.u64(0);
    w.size(a.pData ? (a.pDataSize ? a.pDataSize : 0) : 0);
}
function h_vkGetPipelineCacheData_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pDataSize = r.u64();
    }
    else
    {
        a.pDataSize = null;
    }
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pData = r.blob(array_size);
    }
    else
    {
        r.size();
        a.pData = null;
    }
    return a;
}
function g_vkMergePipelineCaches(w, a)
{
    w.u32(64);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.dstCache);
    w.u32(a.srcCacheCount);
    if(a.pSrcCaches)
    {
        w.size(a.srcCacheCount);
        for(let i = 0; i < a.srcCacheCount; i++)
        {
            w.h((a.pSrcCaches || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkMergePipelineCaches_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCreateGraphicsPipelines(w, a)
{
    w.u32(65);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipelineCache);
    w.u32(a.createInfoCount);
    if(a.pCreateInfos)
    {
        w.size(a.createInfoCount);
        for(let i = 0; i < a.createInfoCount; i++)
        {
            g_VkGraphicsPipelineCreateInfo(w, (a.pCreateInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pPipelines)
    {
        w.size(a.createInfoCount);
        for(let i = 0; i < a.createInfoCount; i++)
        {
            w.h((a.pPipelines || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCreateGraphicsPipelines_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pPipelines = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pPipelines[i] = r.h();
        }
    }
    else
    {
        r.size();
        a.pPipelines = null;
    }
    return a;
}
function g_vkCreateComputePipelines(w, a)
{
    w.u32(66);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipelineCache);
    w.u32(a.createInfoCount);
    if(a.pCreateInfos)
    {
        w.size(a.createInfoCount);
        for(let i = 0; i < a.createInfoCount; i++)
        {
            g_VkComputePipelineCreateInfo(w, (a.pCreateInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pPipelines)
    {
        w.size(a.createInfoCount);
        for(let i = 0; i < a.createInfoCount; i++)
        {
            w.h((a.pPipelines || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCreateComputePipelines_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pPipelines = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pPipelines[i] = r.h();
        }
    }
    else
    {
        r.size();
        a.pPipelines = null;
    }
    return a;
}
function g_vkDestroyPipeline(w, a)
{
    w.u32(67);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipeline);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyPipeline_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreatePipelineLayout(w, a)
{
    w.u32(68);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkPipelineLayoutCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pPipelineLayout != null)
    {
        w.u64(1);
        w.h(a.pPipelineLayout);
    }
    else w.u64(0);
}
function h_vkCreatePipelineLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPipelineLayout = r.h();
    }
    else
    {
        a.pPipelineLayout = null;
    }
    return a;
}
function g_vkDestroyPipelineLayout(w, a)
{
    w.u32(69);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.pipelineLayout);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyPipelineLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateSampler(w, a)
{
    w.u32(70);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pSampler != null)
    {
        w.u64(1);
        w.h(a.pSampler);
    }
    else w.u64(0);
}
function h_vkCreateSampler_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pSampler = r.h();
    }
    else
    {
        a.pSampler = null;
    }
    return a;
}
function g_vkDestroySampler(w, a)
{
    w.u32(71);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.sampler);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroySampler_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateDescriptorSetLayout(w, a)
{
    w.u32(72);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkDescriptorSetLayoutCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pSetLayout != null)
    {
        w.u64(1);
        w.h(a.pSetLayout);
    }
    else w.u64(0);
}
function h_vkCreateDescriptorSetLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pSetLayout = r.h();
    }
    else
    {
        a.pSetLayout = null;
    }
    return a;
}
function g_vkDestroyDescriptorSetLayout(w, a)
{
    w.u32(73);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.descriptorSetLayout);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyDescriptorSetLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateDescriptorPool(w, a)
{
    w.u32(74);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkDescriptorPoolCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pDescriptorPool != null)
    {
        w.u64(1);
        w.h(a.pDescriptorPool);
    }
    else w.u64(0);
}
function h_vkCreateDescriptorPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pDescriptorPool = r.h();
    }
    else
    {
        a.pDescriptorPool = null;
    }
    return a;
}
function g_vkDestroyDescriptorPool(w, a)
{
    w.u32(75);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.descriptorPool);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyDescriptorPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkResetDescriptorPool(w, a)
{
    w.u32(76);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.descriptorPool);
    w.u32(a.flags);
}
function h_vkResetDescriptorPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkAllocateDescriptorSets(w, a)
{
    w.u32(77);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pAllocateInfo != null)
    {
        w.u64(1);
        g_VkDescriptorSetAllocateInfo(w, a.pAllocateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pDescriptorSets)
    {
        w.size((a.pAllocateInfo ? a.pAllocateInfo.descriptorSetCount : 0));
        for(let i = 0; i < (a.pAllocateInfo ? a.pAllocateInfo.descriptorSetCount : 0); i++)
        {
            w.h((a.pDescriptorSets || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkAllocateDescriptorSets_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pDescriptorSets = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pDescriptorSets[i] = r.h();
        }
    }
    else
    {
        r.size();
        a.pDescriptorSets = null;
    }
    return a;
}
function g_vkFreeDescriptorSets(w, a)
{
    w.u32(78);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.descriptorPool);
    w.u32(a.descriptorSetCount);
    if(a.pDescriptorSets)
    {
        w.size(a.descriptorSetCount);
        for(let i = 0; i < a.descriptorSetCount; i++)
        {
            w.h((a.pDescriptorSets || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkFreeDescriptorSets_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkUpdateDescriptorSets(w, a)
{
    w.u32(79);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.descriptorWriteCount);
    if(a.pDescriptorWrites)
    {
        w.size(a.descriptorWriteCount);
        for(let i = 0; i < a.descriptorWriteCount; i++)
        {
            g_VkWriteDescriptorSet(w, (a.pDescriptorWrites || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.descriptorCopyCount);
    if(a.pDescriptorCopies)
    {
        w.size(a.descriptorCopyCount);
        for(let i = 0; i < a.descriptorCopyCount; i++)
        {
            g_VkCopyDescriptorSet(w, (a.pDescriptorCopies || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkUpdateDescriptorSets_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateFramebuffer(w, a)
{
    w.u32(80);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkFramebufferCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pFramebuffer != null)
    {
        w.u64(1);
        w.h(a.pFramebuffer);
    }
    else w.u64(0);
}
function h_vkCreateFramebuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pFramebuffer = r.h();
    }
    else
    {
        a.pFramebuffer = null;
    }
    return a;
}
function g_vkDestroyFramebuffer(w, a)
{
    w.u32(81);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.framebuffer);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyFramebuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateRenderPass(w, a)
{
    w.u32(82);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkRenderPassCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pRenderPass != null)
    {
        w.u64(1);
        w.h(a.pRenderPass);
    }
    else w.u64(0);
}
function h_vkCreateRenderPass_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pRenderPass = r.h();
    }
    else
    {
        a.pRenderPass = null;
    }
    return a;
}
function g_vkDestroyRenderPass(w, a)
{
    w.u32(83);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.renderPass);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyRenderPass_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetRenderAreaGranularity(w, a)
{
    w.u32(84);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.renderPass);
    if(a.pGranularity != null)
    {
        w.u64(1);
        g_VkExtent2D_partial(w, a.pGranularity || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetRenderAreaGranularity_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pGranularity = h_VkExtent2D(r);
    }
    else
    {
        a.pGranularity = null;
    }
    return a;
}
function g_vkCreateCommandPool(w, a)
{
    w.u32(85);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkCommandPoolCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pCommandPool != null)
    {
        w.u64(1);
        w.h(a.pCommandPool);
    }
    else w.u64(0);
}
function h_vkCreateCommandPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pCommandPool = r.h();
    }
    else
    {
        a.pCommandPool = null;
    }
    return a;
}
function g_vkDestroyCommandPool(w, a)
{
    w.u32(86);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.commandPool);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyCommandPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkResetCommandPool(w, a)
{
    w.u32(87);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.flags);
}
function h_vkResetCommandPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkAllocateCommandBuffers(w, a)
{
    w.u32(88);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pAllocateInfo != null)
    {
        w.u64(1);
        g_VkCommandBufferAllocateInfo(w, a.pAllocateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pCommandBuffers)
    {
        w.size((a.pAllocateInfo ? a.pAllocateInfo.commandBufferCount : 0));
        for(let i = 0; i < (a.pAllocateInfo ? a.pAllocateInfo.commandBufferCount : 0); i++)
        {
            w.h((a.pCommandBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkAllocateCommandBuffers_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pCommandBuffers = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pCommandBuffers[i] = r.h();
        }
    }
    else
    {
        r.size();
        a.pCommandBuffers = null;
    }
    return a;
}
function g_vkFreeCommandBuffers(w, a)
{
    w.u32(89);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.commandBufferCount);
    if(a.pCommandBuffers)
    {
        w.size(a.commandBufferCount);
        for(let i = 0; i < a.commandBufferCount; i++)
        {
            w.h((a.pCommandBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkFreeCommandBuffers_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkBeginCommandBuffer(w, a)
{
    w.u32(90);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pBeginInfo != null)
    {
        w.u64(1);
        g_VkCommandBufferBeginInfo(w, a.pBeginInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkBeginCommandBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkEndCommandBuffer(w, a)
{
    w.u32(91);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
}
function h_vkEndCommandBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkResetCommandBuffer(w, a)
{
    w.u32(92);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.flags);
}
function h_vkResetCommandBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCmdBindPipeline(w, a)
{
    w.u32(93);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.pipelineBindPoint);
    w.h(a.pipeline);
}
function h_vkCmdBindPipeline_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetViewport(w, a)
{
    w.u32(94);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstViewport);
    w.u32(a.viewportCount);
    if(a.pViewports)
    {
        w.size(a.viewportCount);
        for(let i = 0; i < a.viewportCount; i++)
        {
            g_VkViewport(w, (a.pViewports || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetViewport_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetScissor(w, a)
{
    w.u32(95);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstScissor);
    w.u32(a.scissorCount);
    if(a.pScissors)
    {
        w.size(a.scissorCount);
        for(let i = 0; i < a.scissorCount; i++)
        {
            g_VkRect2D(w, (a.pScissors || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetScissor_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetLineWidth(w, a)
{
    w.u32(96);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.f32(a.lineWidth);
}
function h_vkCmdSetLineWidth_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthBias(w, a)
{
    w.u32(97);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.f32(a.depthBiasConstantFactor);
    w.f32(a.depthBiasClamp);
    w.f32(a.depthBiasSlopeFactor);
}
function h_vkCmdSetDepthBias_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetBlendConstants(w, a)
{
    w.u32(98);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.size(4);
    w.f32s(a.blendConstants, 4);
}
function h_vkCmdSetBlendConstants_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthBounds(w, a)
{
    w.u32(99);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.f32(a.minDepthBounds);
    w.f32(a.maxDepthBounds);
}
function h_vkCmdSetDepthBounds_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetStencilCompareMask(w, a)
{
    w.u32(100);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.faceMask);
    w.u32(a.compareMask);
}
function h_vkCmdSetStencilCompareMask_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetStencilWriteMask(w, a)
{
    w.u32(101);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.faceMask);
    w.u32(a.writeMask);
}
function h_vkCmdSetStencilWriteMask_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetStencilReference(w, a)
{
    w.u32(102);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.faceMask);
    w.u32(a.reference);
}
function h_vkCmdSetStencilReference_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindDescriptorSets(w, a)
{
    w.u32(103);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.pipelineBindPoint);
    w.h(a.layout);
    w.u32(a.firstSet);
    w.u32(a.descriptorSetCount);
    if(a.pDescriptorSets)
    {
        w.size(a.descriptorSetCount);
        for(let i = 0; i < a.descriptorSetCount; i++)
        {
            w.h((a.pDescriptorSets || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.dynamicOffsetCount);
    if(a.pDynamicOffsets)
    {
        w.size(a.dynamicOffsetCount);
        w.u32s(a.pDynamicOffsets, a.dynamicOffsetCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdBindDescriptorSets_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindIndexBuffer(w, a)
{
    w.u32(104);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.i32(a.indexType);
}
function h_vkCmdBindIndexBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindVertexBuffers(w, a)
{
    w.u32(105);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    if(a.pBuffers)
    {
        w.size(a.bindingCount);
        for(let i = 0; i < a.bindingCount; i++)
        {
            w.h((a.pBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pOffsets)
    {
        w.size(a.bindingCount);
        w.u64s(a.pOffsets, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdBindVertexBuffers_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDraw(w, a)
{
    w.u32(106);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.vertexCount);
    w.u32(a.instanceCount);
    w.u32(a.firstVertex);
    w.u32(a.firstInstance);
}
function h_vkCmdDraw_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawIndexed(w, a)
{
    w.u32(107);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.indexCount);
    w.u32(a.instanceCount);
    w.u32(a.firstIndex);
    w.i32(a.vertexOffset);
    w.u32(a.firstInstance);
}
function h_vkCmdDrawIndexed_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawIndirect(w, a)
{
    w.u32(108);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.u32(a.drawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawIndirect_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawIndexedIndirect(w, a)
{
    w.u32(109);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.u32(a.drawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawIndexedIndirect_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDispatch(w, a)
{
    w.u32(110);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.groupCountX);
    w.u32(a.groupCountY);
    w.u32(a.groupCountZ);
}
function h_vkCmdDispatch_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDispatchIndirect(w, a)
{
    w.u32(111);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
}
function h_vkCmdDispatchIndirect_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyBuffer(w, a)
{
    w.u32(112);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcBuffer);
    w.h(a.dstBuffer);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkBufferCopy(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdCopyBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyImage(w, a)
{
    w.u32(113);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkImageCopy(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdCopyImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBlitImage(w, a)
{
    w.u32(114);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkImageBlit(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.i32(a.filter);
}
function h_vkCmdBlitImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyBufferToImage(w, a)
{
    w.u32(115);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcBuffer);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkBufferImageCopy(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdCopyBufferToImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyImageToBuffer(w, a)
{
    w.u32(116);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstBuffer);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkBufferImageCopy(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdCopyImageToBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdUpdateBuffer(w, a)
{
    w.u32(117);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.dataSize);
    if(a.pData)
    {
        w.size(a.dataSize);
        w.blob(a.pData, a.dataSize);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdUpdateBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdFillBuffer(w, a)
{
    w.u32(118);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.size);
    w.u32(a.data);
}
function h_vkCmdFillBuffer_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdClearColorImage(w, a)
{
    w.u32(119);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.image);
    w.i32(a.imageLayout);
    if(a.pColor != null)
    {
        w.u64(1);
        g_VkClearColorValue(w, a.pColor || EMPTY);
    }
    else w.u64(0);
    w.u32(a.rangeCount);
    if(a.pRanges)
    {
        w.size(a.rangeCount);
        for(let i = 0; i < a.rangeCount; i++)
        {
            g_VkImageSubresourceRange(w, (a.pRanges || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdClearColorImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdClearDepthStencilImage(w, a)
{
    w.u32(120);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.image);
    w.i32(a.imageLayout);
    if(a.pDepthStencil != null)
    {
        w.u64(1);
        g_VkClearDepthStencilValue(w, a.pDepthStencil || EMPTY);
    }
    else w.u64(0);
    w.u32(a.rangeCount);
    if(a.pRanges)
    {
        w.size(a.rangeCount);
        for(let i = 0; i < a.rangeCount; i++)
        {
            g_VkImageSubresourceRange(w, (a.pRanges || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdClearDepthStencilImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdClearAttachments(w, a)
{
    w.u32(121);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.attachmentCount);
    if(a.pAttachments)
    {
        w.size(a.attachmentCount);
        for(let i = 0; i < a.attachmentCount; i++)
        {
            g_VkClearAttachment(w, (a.pAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.rectCount);
    if(a.pRects)
    {
        w.size(a.rectCount);
        for(let i = 0; i < a.rectCount; i++)
        {
            g_VkClearRect(w, (a.pRects || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdClearAttachments_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdResolveImage(w, a)
{
    w.u32(122);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.srcImage);
    w.i32(a.srcImageLayout);
    w.h(a.dstImage);
    w.i32(a.dstImageLayout);
    w.u32(a.regionCount);
    if(a.pRegions)
    {
        w.size(a.regionCount);
        for(let i = 0; i < a.regionCount; i++)
        {
            g_VkImageResolve(w, (a.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdResolveImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetEvent(w, a)
{
    w.u32(123);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.event);
    w.u32(a.stageMask);
}
function h_vkCmdSetEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdResetEvent(w, a)
{
    w.u32(124);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.event);
    w.u32(a.stageMask);
}
function h_vkCmdResetEvent_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdWaitEvents(w, a)
{
    w.u32(125);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.eventCount);
    if(a.pEvents)
    {
        w.size(a.eventCount);
        for(let i = 0; i < a.eventCount; i++)
        {
            w.h((a.pEvents || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.srcStageMask);
    w.u32(a.dstStageMask);
    w.u32(a.memoryBarrierCount);
    if(a.pMemoryBarriers)
    {
        w.size(a.memoryBarrierCount);
        for(let i = 0; i < a.memoryBarrierCount; i++)
        {
            g_VkMemoryBarrier(w, (a.pMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.bufferMemoryBarrierCount);
    if(a.pBufferMemoryBarriers)
    {
        w.size(a.bufferMemoryBarrierCount);
        for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
        {
            g_VkBufferMemoryBarrier(w, (a.pBufferMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.imageMemoryBarrierCount);
    if(a.pImageMemoryBarriers)
    {
        w.size(a.imageMemoryBarrierCount);
        for(let i = 0; i < a.imageMemoryBarrierCount; i++)
        {
            g_VkImageMemoryBarrier(w, (a.pImageMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdWaitEvents_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPipelineBarrier(w, a)
{
    w.u32(126);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.srcStageMask);
    w.u32(a.dstStageMask);
    w.u32(a.dependencyFlags);
    w.u32(a.memoryBarrierCount);
    if(a.pMemoryBarriers)
    {
        w.size(a.memoryBarrierCount);
        for(let i = 0; i < a.memoryBarrierCount; i++)
        {
            g_VkMemoryBarrier(w, (a.pMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.bufferMemoryBarrierCount);
    if(a.pBufferMemoryBarriers)
    {
        w.size(a.bufferMemoryBarrierCount);
        for(let i = 0; i < a.bufferMemoryBarrierCount; i++)
        {
            g_VkBufferMemoryBarrier(w, (a.pBufferMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.imageMemoryBarrierCount);
    if(a.pImageMemoryBarriers)
    {
        w.size(a.imageMemoryBarrierCount);
        for(let i = 0; i < a.imageMemoryBarrierCount; i++)
        {
            g_VkImageMemoryBarrier(w, (a.pImageMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdPipelineBarrier_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginQuery(w, a)
{
    w.u32(127);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.flags);
}
function h_vkCmdBeginQuery_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndQuery(w, a)
{
    w.u32(128);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.query);
}
function h_vkCmdEndQuery_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdResetQueryPool(w, a)
{
    w.u32(129);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
}
function h_vkCmdResetQueryPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdWriteTimestamp(w, a)
{
    w.u32(130);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.pipelineStage);
    w.h(a.queryPool);
    w.u32(a.query);
}
function h_vkCmdWriteTimestamp_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyQueryPoolResults(w, a)
{
    w.u32(131);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
    w.h(a.dstBuffer);
    w.u64(a.dstOffset);
    w.u64(a.stride);
    w.u32(a.flags);
}
function h_vkCmdCopyQueryPoolResults_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPushConstants(w, a)
{
    w.u32(132);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.layout);
    w.u32(a.stageFlags);
    w.u32(a.offset);
    w.u32(a.size);
    if(a.pValues)
    {
        w.size(a.size);
        w.blob(a.pValues, a.size);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdPushConstants_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginRenderPass(w, a)
{
    w.u32(133);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pRenderPassBegin != null)
    {
        w.u64(1);
        g_VkRenderPassBeginInfo(w, a.pRenderPassBegin || EMPTY);
    }
    else w.u64(0);
    w.i32(a.contents);
}
function h_vkCmdBeginRenderPass_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdNextSubpass(w, a)
{
    w.u32(134);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.contents);
}
function h_vkCmdNextSubpass_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndRenderPass(w, a)
{
    w.u32(135);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
}
function h_vkCmdEndRenderPass_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdExecuteCommands(w, a)
{
    w.u32(136);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.commandBufferCount);
    if(a.pCommandBuffers)
    {
        w.size(a.commandBufferCount);
        for(let i = 0; i < a.commandBufferCount; i++)
        {
            w.h((a.pCommandBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdExecuteCommands_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkEnumerateInstanceVersion(w, a)
{
    w.u32(137);
    w.u32(a.cmd_flags || 0);
    w.u64(a.pApiVersion != null ? 1 : 0);
}
function h_vkEnumerateInstanceVersion_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pApiVersion = r.u32();
    }
    else
    {
        a.pApiVersion = null;
    }
    return a;
}
function g_vkBindBufferMemory2(w, a)
{
    w.u32(138);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.bindInfoCount);
    if(a.pBindInfos)
    {
        w.size(a.bindInfoCount);
        for(let i = 0; i < a.bindInfoCount; i++)
        {
            g_VkBindBufferMemoryInfo(w, (a.pBindInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkBindBufferMemory2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkBindImageMemory2(w, a)
{
    w.u32(139);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.bindInfoCount);
    if(a.pBindInfos)
    {
        w.size(a.bindInfoCount);
        for(let i = 0; i < a.bindInfoCount; i++)
        {
            g_VkBindImageMemoryInfo(w, (a.pBindInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkBindImageMemory2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetDeviceGroupPeerMemoryFeatures(w, a)
{
    w.u32(140);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.heapIndex);
    w.u32(a.localDeviceIndex);
    w.u32(a.remoteDeviceIndex);
    w.u64(a.pPeerMemoryFeatures != null ? 1 : 0);
}
function h_vkGetDeviceGroupPeerMemoryFeatures_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pPeerMemoryFeatures = r.u32();
    }
    else
    {
        a.pPeerMemoryFeatures = null;
    }
    return a;
}
function g_vkCmdSetDeviceMask(w, a)
{
    w.u32(141);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.deviceMask);
}
function h_vkCmdSetDeviceMask_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDispatchBase(w, a)
{
    w.u32(142);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.baseGroupX);
    w.u32(a.baseGroupY);
    w.u32(a.baseGroupZ);
    w.u32(a.groupCountX);
    w.u32(a.groupCountY);
    w.u32(a.groupCountZ);
}
function h_vkCmdDispatchBase_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkEnumeratePhysicalDeviceGroups(w, a)
{
    w.u32(143);
    w.u32(a.cmd_flags || 0);
    w.h(a.instance);
    if(a.pPhysicalDeviceGroupCount != null)
    {
        w.u64(1);
        w.u32(a.pPhysicalDeviceGroupCount);
    }
    else w.u64(0);
    if(a.pPhysicalDeviceGroupProperties)
    {
        w.size((a.pPhysicalDeviceGroupCount || 0));
        for(let i = 0; i < (a.pPhysicalDeviceGroupCount || 0); i++)
        {
            g_VkPhysicalDeviceGroupProperties_partial(w, (a.pPhysicalDeviceGroupProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkEnumeratePhysicalDeviceGroups_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPhysicalDeviceGroupCount = r.u32();
    }
    else
    {
        a.pPhysicalDeviceGroupCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pPhysicalDeviceGroupProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pPhysicalDeviceGroupProperties[i] = h_VkPhysicalDeviceGroupProperties(r);
        }
    }
    else
    {
        r.size();
        a.pPhysicalDeviceGroupProperties = null;
    }
    return a;
}
function g_vkGetImageMemoryRequirements2(w, a)
{
    w.u32(144);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkImageMemoryRequirementsInfo2(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements2_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetImageMemoryRequirements2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements2(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetBufferMemoryRequirements2(w, a)
{
    w.u32(145);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkBufferMemoryRequirementsInfo2(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements2_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetBufferMemoryRequirements2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements2(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetImageSparseMemoryRequirements2(w, a)
{
    w.u32(146);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkImageSparseMemoryRequirementsInfo2(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        w.size((a.pSparseMemoryRequirementCount || 0));
        for(let i = 0; i < (a.pSparseMemoryRequirementCount || 0); i++)
        {
            g_VkSparseImageMemoryRequirements2_partial(w, (a.pSparseMemoryRequirements || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetImageSparseMemoryRequirements2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else
    {
        a.pSparseMemoryRequirementCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pSparseMemoryRequirements = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pSparseMemoryRequirements[i] = h_VkSparseImageMemoryRequirements2(r);
        }
    }
    else
    {
        r.size();
        a.pSparseMemoryRequirements = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceFeatures2(w, a)
{
    w.u32(147);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pFeatures != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceFeatures2_partial(w, a.pFeatures || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceFeatures2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pFeatures = h_VkPhysicalDeviceFeatures2(r);
    }
    else
    {
        a.pFeatures = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceProperties2(w, a)
{
    w.u32(148);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pProperties != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceProperties2_partial(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pProperties = h_VkPhysicalDeviceProperties2(r);
    }
    else
    {
        a.pProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceFormatProperties2(w, a)
{
    w.u32(149);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.format);
    if(a.pFormatProperties != null)
    {
        w.u64(1);
        g_VkFormatProperties2_partial(w, a.pFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceFormatProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pFormatProperties = h_VkFormatProperties2(r);
    }
    else
    {
        a.pFormatProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceImageFormatProperties2(w, a)
{
    w.u32(150);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pImageFormatInfo != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceImageFormatInfo2(w, a.pImageFormatInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pImageFormatProperties != null)
    {
        w.u64(1);
        g_VkImageFormatProperties2_partial(w, a.pImageFormatProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceImageFormatProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pImageFormatProperties = h_VkImageFormatProperties2(r);
    }
    else
    {
        a.pImageFormatProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceQueueFamilyProperties2(w, a)
{
    w.u32(151);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pQueueFamilyPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pQueueFamilyPropertyCount);
    }
    else w.u64(0);
    if(a.pQueueFamilyProperties)
    {
        w.size((a.pQueueFamilyPropertyCount || 0));
        for(let i = 0; i < (a.pQueueFamilyPropertyCount || 0); i++)
        {
            g_VkQueueFamilyProperties2_partial(w, (a.pQueueFamilyProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceQueueFamilyProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pQueueFamilyPropertyCount = r.u32();
    }
    else
    {
        a.pQueueFamilyPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pQueueFamilyProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pQueueFamilyProperties[i] = h_VkQueueFamilyProperties2(r);
        }
    }
    else
    {
        r.size();
        a.pQueueFamilyProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceMemoryProperties2(w, a)
{
    w.u32(152);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pMemoryProperties != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceMemoryProperties2_partial(w, a.pMemoryProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceMemoryProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryProperties = h_VkPhysicalDeviceMemoryProperties2(r);
    }
    else
    {
        a.pMemoryProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceSparseImageFormatProperties2(w, a)
{
    w.u32(153);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pFormatInfo != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceSparseImageFormatInfo2(w, a.pFormatInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkSparseImageFormatProperties2_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceSparseImageFormatProperties2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkSparseImageFormatProperties2(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkTrimCommandPool(w, a)
{
    w.u32(154);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.commandPool);
    w.u32(a.flags);
}
function h_vkTrimCommandPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetDeviceQueue2(w, a)
{
    w.u32(155);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pQueueInfo != null)
    {
        w.u64(1);
        g_VkDeviceQueueInfo2(w, a.pQueueInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pQueue != null)
    {
        w.u64(1);
        w.h(a.pQueue);
    }
    else w.u64(0);
}
function h_vkGetDeviceQueue2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pQueue = r.h();
    }
    else
    {
        a.pQueue = null;
    }
    return a;
}
function g_vkCreateSamplerYcbcrConversion(w, a)
{
    w.u32(156);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkSamplerYcbcrConversionCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pYcbcrConversion != null)
    {
        w.u64(1);
        w.h(a.pYcbcrConversion);
    }
    else w.u64(0);
}
function h_vkCreateSamplerYcbcrConversion_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pYcbcrConversion = r.h();
    }
    else
    {
        a.pYcbcrConversion = null;
    }
    return a;
}
function g_vkDestroySamplerYcbcrConversion(w, a)
{
    w.u32(157);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.ycbcrConversion);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroySamplerYcbcrConversion_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateDescriptorUpdateTemplate(w, a)
{
    w.u32(158);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkDescriptorUpdateTemplateCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pDescriptorUpdateTemplate != null)
    {
        w.u64(1);
        w.h(a.pDescriptorUpdateTemplate);
    }
    else w.u64(0);
}
function h_vkCreateDescriptorUpdateTemplate_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pDescriptorUpdateTemplate = r.h();
    }
    else
    {
        a.pDescriptorUpdateTemplate = null;
    }
    return a;
}
function g_vkDestroyDescriptorUpdateTemplate(w, a)
{
    w.u32(159);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.descriptorUpdateTemplate);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyDescriptorUpdateTemplate_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPhysicalDeviceExternalBufferProperties(w, a)
{
    w.u32(161);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pExternalBufferInfo != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceExternalBufferInfo(w, a.pExternalBufferInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pExternalBufferProperties != null)
    {
        w.u64(1);
        g_VkExternalBufferProperties_partial(w, a.pExternalBufferProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceExternalBufferProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pExternalBufferProperties = h_VkExternalBufferProperties(r);
    }
    else
    {
        a.pExternalBufferProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceExternalFenceProperties(w, a)
{
    w.u32(162);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pExternalFenceInfo != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceExternalFenceInfo(w, a.pExternalFenceInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pExternalFenceProperties != null)
    {
        w.u64(1);
        g_VkExternalFenceProperties_partial(w, a.pExternalFenceProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceExternalFenceProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pExternalFenceProperties = h_VkExternalFenceProperties(r);
    }
    else
    {
        a.pExternalFenceProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceExternalSemaphoreProperties(w, a)
{
    w.u32(163);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pExternalSemaphoreInfo != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceExternalSemaphoreInfo(w, a.pExternalSemaphoreInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pExternalSemaphoreProperties != null)
    {
        w.u64(1);
        g_VkExternalSemaphoreProperties_partial(w, a.pExternalSemaphoreProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceExternalSemaphoreProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pExternalSemaphoreProperties = h_VkExternalSemaphoreProperties(r);
    }
    else
    {
        a.pExternalSemaphoreProperties = null;
    }
    return a;
}
function g_vkGetDescriptorSetLayoutSupport(w, a)
{
    w.u32(164);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkDescriptorSetLayoutCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pSupport != null)
    {
        w.u64(1);
        g_VkDescriptorSetLayoutSupport_partial(w, a.pSupport || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetDescriptorSetLayoutSupport_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pSupport = h_VkDescriptorSetLayoutSupport(r);
    }
    else
    {
        a.pSupport = null;
    }
    return a;
}
function g_vkCmdDrawIndirectCount(w, a)
{
    w.u32(165);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.h(a.countBuffer);
    w.u64(a.countBufferOffset);
    w.u32(a.maxDrawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawIndirectCount_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawIndexedIndirectCount(w, a)
{
    w.u32(166);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.h(a.countBuffer);
    w.u64(a.countBufferOffset);
    w.u32(a.maxDrawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawIndexedIndirectCount_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCreateRenderPass2(w, a)
{
    w.u32(167);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkRenderPassCreateInfo2(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pRenderPass != null)
    {
        w.u64(1);
        w.h(a.pRenderPass);
    }
    else w.u64(0);
}
function h_vkCreateRenderPass2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pRenderPass = r.h();
    }
    else
    {
        a.pRenderPass = null;
    }
    return a;
}
function g_vkCmdBeginRenderPass2(w, a)
{
    w.u32(168);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pRenderPassBegin != null)
    {
        w.u64(1);
        g_VkRenderPassBeginInfo(w, a.pRenderPassBegin || EMPTY);
    }
    else w.u64(0);
    if(a.pSubpassBeginInfo != null)
    {
        w.u64(1);
        g_VkSubpassBeginInfo(w, a.pSubpassBeginInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBeginRenderPass2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdNextSubpass2(w, a)
{
    w.u32(169);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pSubpassBeginInfo != null)
    {
        w.u64(1);
        g_VkSubpassBeginInfo(w, a.pSubpassBeginInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pSubpassEndInfo != null)
    {
        w.u64(1);
        g_VkSubpassEndInfo(w, a.pSubpassEndInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdNextSubpass2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndRenderPass2(w, a)
{
    w.u32(170);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pSubpassEndInfo != null)
    {
        w.u64(1);
        g_VkSubpassEndInfo(w, a.pSubpassEndInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdEndRenderPass2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkResetQueryPool(w, a)
{
    w.u32(171);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.queryPool);
    w.u32(a.firstQuery);
    w.u32(a.queryCount);
}
function h_vkResetQueryPool_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetSemaphoreCounterValue(w, a)
{
    w.u32(172);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.semaphore);
    w.u64(a.pValue != null ? 1 : 0);
}
function h_vkGetSemaphoreCounterValue_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pValue = r.u64();
    }
    else
    {
        a.pValue = null;
    }
    return a;
}
function g_vkWaitSemaphores(w, a)
{
    w.u32(173);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pWaitInfo != null)
    {
        w.u64(1);
        g_VkSemaphoreWaitInfo(w, a.pWaitInfo || EMPTY);
    }
    else w.u64(0);
    w.u64(a.timeout);
}
function h_vkWaitSemaphores_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkSignalSemaphore(w, a)
{
    w.u32(174);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pSignalInfo != null)
    {
        w.u64(1);
        g_VkSemaphoreSignalInfo(w, a.pSignalInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkSignalSemaphore_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetBufferDeviceAddress(w, a)
{
    w.u32(175);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkBufferDeviceAddressInfo(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetBufferDeviceAddress_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.u64();
    return a;
}
function g_vkGetBufferOpaqueCaptureAddress(w, a)
{
    w.u32(176);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkBufferDeviceAddressInfo(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetBufferOpaqueCaptureAddress_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.u64();
    return a;
}
function g_vkGetDeviceMemoryOpaqueCaptureAddress(w, a)
{
    w.u32(177);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkDeviceMemoryOpaqueCaptureAddressInfo(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetDeviceMemoryOpaqueCaptureAddress_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.u64();
    return a;
}
function g_vkSetReplyCommandStreamMESA(w, a)
{
    w.u32(178);
    w.u32(a.cmd_flags || 0);
    if(a.pStream != null)
    {
        w.u64(1);
        g_VkCommandStreamDescriptionMESA(w, a.pStream || EMPTY);
    }
    else w.u64(0);
}
function h_vkSetReplyCommandStreamMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkSeekReplyCommandStreamMESA(w, a)
{
    w.u32(179);
    w.u32(a.cmd_flags || 0);
    w.u64(a.position);
}
function h_vkSeekReplyCommandStreamMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkExecuteCommandStreamsMESA(w, a)
{
    w.u32(180);
    w.u32(a.cmd_flags || 0);
    w.u32(a.streamCount);
    if(a.pStreams)
    {
        w.size(a.streamCount);
        for(let i = 0; i < a.streamCount; i++)
        {
            g_VkCommandStreamDescriptionMESA(w, (a.pStreams || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pReplyPositions)
    {
        w.size(a.streamCount);
        w.u64s(a.pReplyPositions, a.streamCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(a.dependencyCount);
    if(a.pDependencies)
    {
        w.size(a.dependencyCount);
        for(let i = 0; i < a.dependencyCount; i++)
        {
            g_VkCommandStreamDependencyMESA(w, (a.pDependencies || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.flags);
}
function h_vkExecuteCommandStreamsMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindTransformFeedbackBuffersEXT(w, a)
{
    w.u32(181);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    if(a.pBuffers)
    {
        w.size(a.bindingCount);
        for(let i = 0; i < a.bindingCount; i++)
        {
            w.h((a.pBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pOffsets)
    {
        w.size(a.bindingCount);
        w.u64s(a.pOffsets, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
    if(a.pSizes)
    {
        w.size(a.bindingCount);
        w.u64s(a.pSizes, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdBindTransformFeedbackBuffersEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginTransformFeedbackEXT(w, a)
{
    w.u32(182);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstCounterBuffer);
    w.u32(a.counterBufferCount);
    if(a.pCounterBuffers)
    {
        w.size(a.counterBufferCount);
        for(let i = 0; i < a.counterBufferCount; i++)
        {
            w.h((a.pCounterBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pCounterBufferOffsets)
    {
        w.size(a.counterBufferCount);
        w.u64s(a.pCounterBufferOffsets, a.counterBufferCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdBeginTransformFeedbackEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndTransformFeedbackEXT(w, a)
{
    w.u32(183);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstCounterBuffer);
    w.u32(a.counterBufferCount);
    if(a.pCounterBuffers)
    {
        w.size(a.counterBufferCount);
        for(let i = 0; i < a.counterBufferCount; i++)
        {
            w.h((a.pCounterBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pCounterBufferOffsets)
    {
        w.size(a.counterBufferCount);
        w.u64s(a.pCounterBufferOffsets, a.counterBufferCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdEndTransformFeedbackEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginQueryIndexedEXT(w, a)
{
    w.u32(184);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.flags);
    w.u32(a.index);
}
function h_vkCmdBeginQueryIndexedEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndQueryIndexedEXT(w, a)
{
    w.u32(185);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.queryPool);
    w.u32(a.query);
    w.u32(a.index);
}
function h_vkCmdEndQueryIndexedEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawIndirectByteCountEXT(w, a)
{
    w.u32(186);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.instanceCount);
    w.u32(a.firstInstance);
    w.h(a.counterBuffer);
    w.u64(a.counterBufferOffset);
    w.u32(a.counterOffset);
    w.u32(a.vertexStride);
}
function h_vkCmdDrawIndirectByteCountEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetImageDrmFormatModifierPropertiesEXT(w, a)
{
    w.u32(187);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pProperties != null)
    {
        w.u64(1);
        g_VkImageDrmFormatModifierPropertiesEXT_partial(w, a.pProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetImageDrmFormatModifierPropertiesEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pProperties = h_VkImageDrmFormatModifierPropertiesEXT(r);
    }
    else
    {
        a.pProperties = null;
    }
    return a;
}
function g_vkCreateRingMESA(w, a)
{
    w.u32(188);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkRingCreateInfoMESA(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCreateRingMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkDestroyRingMESA(w, a)
{
    w.u32(189);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
}
function h_vkDestroyRingMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkNotifyRingMESA(w, a)
{
    w.u32(190);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
    w.u32(a.seqno);
    w.u32(a.flags);
}
function h_vkNotifyRingMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkWriteRingExtraMESA(w, a)
{
    w.u32(191);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
    w.u64(a.offset);
    w.u32(a.value);
}
function h_vkWriteRingExtraMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetMemoryResourcePropertiesMESA(w, a)
{
    w.u32(192);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.resourceId);
    if(a.pMemoryResourceProperties != null)
    {
        w.u64(1);
        g_VkMemoryResourcePropertiesMESA_partial(w, a.pMemoryResourceProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetMemoryResourcePropertiesMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pMemoryResourceProperties = h_VkMemoryResourcePropertiesMESA(r);
    }
    else
    {
        a.pMemoryResourceProperties = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceToolProperties(w, a)
{
    w.u32(196);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pToolCount != null)
    {
        w.u64(1);
        w.u32(a.pToolCount);
    }
    else w.u64(0);
    if(a.pToolProperties)
    {
        w.size((a.pToolCount || 0));
        for(let i = 0; i < (a.pToolCount || 0); i++)
        {
            g_VkPhysicalDeviceToolProperties_partial(w, (a.pToolProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceToolProperties_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pToolCount = r.u32();
    }
    else
    {
        a.pToolCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pToolProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pToolProperties[i] = h_VkPhysicalDeviceToolProperties(r);
        }
    }
    else
    {
        r.size();
        a.pToolProperties = null;
    }
    return a;
}
function g_vkCreatePrivateDataSlot(w, a)
{
    w.u32(197);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCreateInfo != null)
    {
        w.u64(1);
        g_VkPrivateDataSlotCreateInfo(w, a.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pPrivateDataSlot != null)
    {
        w.u64(1);
        w.h(a.pPrivateDataSlot);
    }
    else w.u64(0);
}
function h_vkCreatePrivateDataSlot_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPrivateDataSlot = r.h();
    }
    else
    {
        a.pPrivateDataSlot = null;
    }
    return a;
}
function g_vkDestroyPrivateDataSlot(w, a)
{
    w.u32(198);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.privateDataSlot);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyPrivateDataSlot_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkSetPrivateData(w, a)
{
    w.u32(199);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.data);
}
function h_vkSetPrivateData_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkGetPrivateData(w, a)
{
    w.u32(200);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.i32(a.objectType);
    w.u64(a.objectHandle);
    w.h(a.privateDataSlot);
    w.u64(a.pData != null ? 1 : 0);
}
function h_vkGetPrivateData_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pData = r.u64();
    }
    else
    {
        a.pData = null;
    }
    return a;
}
function g_vkCmdSetEvent2(w, a)
{
    w.u32(201);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.event);
    if(a.pDependencyInfo != null)
    {
        w.u64(1);
        g_VkDependencyInfo(w, a.pDependencyInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetEvent2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdResetEvent2(w, a)
{
    w.u32(202);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.event);
    w.u64(a.stageMask);
}
function h_vkCmdResetEvent2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdWaitEvents2(w, a)
{
    w.u32(203);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.eventCount);
    if(a.pEvents)
    {
        w.size(a.eventCount);
        for(let i = 0; i < a.eventCount; i++)
        {
            w.h((a.pEvents || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pDependencyInfos)
    {
        w.size(a.eventCount);
        for(let i = 0; i < a.eventCount; i++)
        {
            g_VkDependencyInfo(w, (a.pDependencyInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdWaitEvents2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPipelineBarrier2(w, a)
{
    w.u32(204);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pDependencyInfo != null)
    {
        w.u64(1);
        g_VkDependencyInfo(w, a.pDependencyInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdPipelineBarrier2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdWriteTimestamp2(w, a)
{
    w.u32(205);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u64(a.stage);
    w.h(a.queryPool);
    w.u32(a.query);
}
function h_vkCmdWriteTimestamp2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkQueueSubmit2(w, a)
{
    w.u32(206);
    w.u32(a.cmd_flags || 0);
    w.h(a.queue);
    w.u32(a.submitCount);
    if(a.pSubmits)
    {
        w.size(a.submitCount);
        for(let i = 0; i < a.submitCount; i++)
        {
            g_VkSubmitInfo2(w, (a.pSubmits || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.h(a.fence);
}
function h_vkQueueSubmit2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCmdCopyBuffer2(w, a)
{
    w.u32(207);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pCopyBufferInfo != null)
    {
        w.u64(1);
        g_VkCopyBufferInfo2(w, a.pCopyBufferInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdCopyBuffer2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyImage2(w, a)
{
    w.u32(208);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pCopyImageInfo != null)
    {
        w.u64(1);
        g_VkCopyImageInfo2(w, a.pCopyImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdCopyImage2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyBufferToImage2(w, a)
{
    w.u32(209);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pCopyBufferToImageInfo != null)
    {
        w.u64(1);
        g_VkCopyBufferToImageInfo2(w, a.pCopyBufferToImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdCopyBufferToImage2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdCopyImageToBuffer2(w, a)
{
    w.u32(210);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pCopyImageToBufferInfo != null)
    {
        w.u64(1);
        g_VkCopyImageToBufferInfo2(w, a.pCopyImageToBufferInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdCopyImageToBuffer2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBlitImage2(w, a)
{
    w.u32(211);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pBlitImageInfo != null)
    {
        w.u64(1);
        g_VkBlitImageInfo2(w, a.pBlitImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBlitImage2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdResolveImage2(w, a)
{
    w.u32(212);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pResolveImageInfo != null)
    {
        w.u64(1);
        g_VkResolveImageInfo2(w, a.pResolveImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdResolveImage2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginRendering(w, a)
{
    w.u32(213);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pRenderingInfo != null)
    {
        w.u64(1);
        g_VkRenderingInfo(w, a.pRenderingInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBeginRendering_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndRendering(w, a)
{
    w.u32(214);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
}
function h_vkCmdEndRendering_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetCullMode(w, a)
{
    w.u32(215);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.cullMode);
}
function h_vkCmdSetCullMode_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetFrontFace(w, a)
{
    w.u32(216);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.frontFace);
}
function h_vkCmdSetFrontFace_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetPrimitiveTopology(w, a)
{
    w.u32(217);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.primitiveTopology);
}
function h_vkCmdSetPrimitiveTopology_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetViewportWithCount(w, a)
{
    w.u32(218);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.viewportCount);
    if(a.pViewports)
    {
        w.size(a.viewportCount);
        for(let i = 0; i < a.viewportCount; i++)
        {
            g_VkViewport(w, (a.pViewports || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetViewportWithCount_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetScissorWithCount(w, a)
{
    w.u32(219);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.scissorCount);
    if(a.pScissors)
    {
        w.size(a.scissorCount);
        for(let i = 0; i < a.scissorCount; i++)
        {
            g_VkRect2D(w, (a.pScissors || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetScissorWithCount_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindVertexBuffers2(w, a)
{
    w.u32(220);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstBinding);
    w.u32(a.bindingCount);
    if(a.pBuffers)
    {
        w.size(a.bindingCount);
        for(let i = 0; i < a.bindingCount; i++)
        {
            w.h((a.pBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pOffsets)
    {
        w.size(a.bindingCount);
        w.u64s(a.pOffsets, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
    if(a.pSizes)
    {
        w.size(a.bindingCount);
        w.u64s(a.pSizes, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
    if(a.pStrides)
    {
        w.size(a.bindingCount);
        w.u64s(a.pStrides, a.bindingCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdBindVertexBuffers2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthTestEnable(w, a)
{
    w.u32(221);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthTestEnable);
}
function h_vkCmdSetDepthTestEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthWriteEnable(w, a)
{
    w.u32(222);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthWriteEnable);
}
function h_vkCmdSetDepthWriteEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthCompareOp(w, a)
{
    w.u32(223);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.depthCompareOp);
}
function h_vkCmdSetDepthCompareOp_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthBoundsTestEnable(w, a)
{
    w.u32(224);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthBoundsTestEnable);
}
function h_vkCmdSetDepthBoundsTestEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetStencilTestEnable(w, a)
{
    w.u32(225);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.stencilTestEnable);
}
function h_vkCmdSetStencilTestEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetStencilOp(w, a)
{
    w.u32(226);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.faceMask);
    w.i32(a.failOp);
    w.i32(a.passOp);
    w.i32(a.depthFailOp);
    w.i32(a.compareOp);
}
function h_vkCmdSetStencilOp_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetRasterizerDiscardEnable(w, a)
{
    w.u32(227);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.rasterizerDiscardEnable);
}
function h_vkCmdSetRasterizerDiscardEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthBiasEnable(w, a)
{
    w.u32(228);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthBiasEnable);
}
function h_vkCmdSetDepthBiasEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetPrimitiveRestartEnable(w, a)
{
    w.u32(229);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.primitiveRestartEnable);
}
function h_vkCmdSetPrimitiveRestartEnable_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetDeviceBufferMemoryRequirements(w, a)
{
    w.u32(230);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkDeviceBufferMemoryRequirements(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements2_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetDeviceBufferMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements2(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetDeviceImageMemoryRequirements(w, a)
{
    w.u32(231);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkDeviceImageMemoryRequirements(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pMemoryRequirements != null)
    {
        w.u64(1);
        g_VkMemoryRequirements2_partial(w, a.pMemoryRequirements || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetDeviceImageMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMemoryRequirements = h_VkMemoryRequirements2(r);
    }
    else
    {
        a.pMemoryRequirements = null;
    }
    return a;
}
function g_vkGetDeviceImageSparseMemoryRequirements(w, a)
{
    w.u32(232);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkDeviceImageMemoryRequirements(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirementCount != null)
    {
        w.u64(1);
        w.u32(a.pSparseMemoryRequirementCount);
    }
    else w.u64(0);
    if(a.pSparseMemoryRequirements)
    {
        w.size((a.pSparseMemoryRequirementCount || 0));
        for(let i = 0; i < (a.pSparseMemoryRequirementCount || 0); i++)
        {
            g_VkSparseImageMemoryRequirements2_partial(w, (a.pSparseMemoryRequirements || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetDeviceImageSparseMemoryRequirements_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pSparseMemoryRequirementCount = r.u32();
    }
    else
    {
        a.pSparseMemoryRequirementCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pSparseMemoryRequirements = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pSparseMemoryRequirements[i] = h_VkSparseImageMemoryRequirements2(r);
        }
    }
    else
    {
        r.size();
        a.pSparseMemoryRequirements = null;
    }
    return a;
}
function g_vkCmdSetPatchControlPointsEXT(w, a)
{
    w.u32(233);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.patchControlPoints);
}
function h_vkCmdSetPatchControlPointsEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetLogicOpEXT(w, a)
{
    w.u32(234);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.logicOp);
}
function h_vkCmdSetLogicOpEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR(w, a)
{
    w.u32(235);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pTimeDomainCount != null)
    {
        w.u64(1);
        w.u32(a.pTimeDomainCount);
    }
    else w.u64(0);
    w.size(a.pTimeDomains ? (a.pTimeDomainCount ? a.pTimeDomainCount : 0) : 0);
}
function h_vkGetPhysicalDeviceCalibrateableTimeDomainsKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pTimeDomainCount = r.u32();
    }
    else
    {
        a.pTimeDomainCount = null;
    }
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pTimeDomains = r.i32s(array_size);
    }
    else
    {
        r.size();
        a.pTimeDomains = null;
    }
    return a;
}
function g_vkGetCalibratedTimestampsKHR(w, a)
{
    w.u32(236);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.timestampCount);
    if(a.pTimestampInfos)
    {
        w.size(a.timestampCount);
        for(let i = 0; i < a.timestampCount; i++)
        {
            g_VkCalibratedTimestampInfoKHR(w, (a.pTimestampInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.size(a.pTimestamps ? a.timestampCount : 0);
    w.u64(a.pMaxDeviation != null ? 1 : 0);
}
function h_vkGetCalibratedTimestampsKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pTimestamps = r.u64s(array_size);
    }
    else
    {
        r.size();
        a.pTimestamps = null;
    }
    if(r.u64())
    {
        a.pMaxDeviation = r.u64();
    }
    else
    {
        a.pMaxDeviation = null;
    }
    return a;
}
function g_vkCmdSetLineStipple(w, a)
{
    w.u32(237);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.lineStippleFactor);
    w.u16(a.lineStipplePattern);
}
function h_vkCmdSetLineStipple_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBeginConditionalRenderingEXT(w, a)
{
    w.u32(240);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pConditionalRenderingBegin != null)
    {
        w.u64(1);
        g_VkConditionalRenderingBeginInfoEXT(w, a.pConditionalRenderingBegin || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBeginConditionalRenderingEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdEndConditionalRenderingEXT(w, a)
{
    w.u32(241);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
}
function h_vkCmdEndConditionalRenderingEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkResetFenceResourceMESA(w, a)
{
    w.u32(244);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.fence);
}
function h_vkResetFenceResourceMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkWaitSemaphoreResourceMESA(w, a)
{
    w.u32(245);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.semaphore);
}
function h_vkWaitSemaphoreResourceMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkImportSemaphoreResourceMESA(w, a)
{
    w.u32(246);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pImportSemaphoreResourceInfo != null)
    {
        w.u64(1);
        g_VkImportSemaphoreResourceInfoMESA(w, a.pImportSemaphoreResourceInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkImportSemaphoreResourceMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawMultiEXT(w, a)
{
    w.u32(247);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.drawCount);
    if(a.pVertexInfo)
    {
        w.size(a.drawCount);
        for(let i = 0; i < a.drawCount; i++)
        {
            g_VkMultiDrawInfoEXT(w, (a.pVertexInfo || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.instanceCount);
    w.u32(a.firstInstance);
    w.u32(a.stride);
}
function h_vkCmdDrawMultiEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawMultiIndexedEXT(w, a)
{
    w.u32(248);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.drawCount);
    if(a.pIndexInfo)
    {
        w.size(a.drawCount);
        for(let i = 0; i < a.drawCount; i++)
        {
            g_VkMultiDrawIndexedInfoEXT(w, (a.pIndexInfo || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.instanceCount);
    w.u32(a.firstInstance);
    w.u32(a.stride);
    if(a.pVertexOffset != null)
    {
        w.u64(1);
        w.i32(a.pVertexOffset);
    }
    else w.u64(0);
}
function h_vkCmdDrawMultiIndexedEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPushDescriptorSet(w, a)
{
    w.u32(249);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.pipelineBindPoint);
    w.h(a.layout);
    w.u32(a.set);
    w.u32(a.descriptorWriteCount);
    if(a.pDescriptorWrites)
    {
        w.size(a.descriptorWriteCount);
        for(let i = 0; i < a.descriptorWriteCount; i++)
        {
            g_VkWriteDescriptorSet(w, (a.pDescriptorWrites || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdPushDescriptorSet_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkSubmitVirtqueueSeqnoMESA(w, a)
{
    w.u32(251);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
    w.u64(a.seqno);
}
function h_vkSubmitVirtqueueSeqnoMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkWaitVirtqueueSeqnoMESA(w, a)
{
    w.u32(252);
    w.u32(a.cmd_flags || 0);
    w.u64(a.seqno);
}
function h_vkWaitVirtqueueSeqnoMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkWaitRingSeqnoMESA(w, a)
{
    w.u32(253);
    w.u32(a.cmd_flags || 0);
    w.ring_id(a.ring);
    w.u64(a.seqno);
}
function h_vkWaitRingSeqnoMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetColorWriteEnableEXT(w, a)
{
    w.u32(254);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.attachmentCount);
    if(a.pColorWriteEnables)
    {
        w.size(a.attachmentCount);
        w.u32s(a.pColorWriteEnables, a.attachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetColorWriteEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetVertexInputEXT(w, a)
{
    w.u32(255);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.vertexBindingDescriptionCount);
    if(a.pVertexBindingDescriptions)
    {
        w.size(a.vertexBindingDescriptionCount);
        for(let i = 0; i < a.vertexBindingDescriptionCount; i++)
        {
            g_VkVertexInputBindingDescription2EXT(w, (a.pVertexBindingDescriptions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(a.vertexAttributeDescriptionCount);
    if(a.pVertexAttributeDescriptions)
    {
        w.size(a.vertexAttributeDescriptionCount);
        for(let i = 0; i < a.vertexAttributeDescriptionCount; i++)
        {
            g_VkVertexInputAttributeDescription2EXT(w, (a.pVertexAttributeDescriptions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetVertexInputEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetTessellationDomainOriginEXT(w, a)
{
    w.u32(256);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.domainOrigin);
}
function h_vkCmdSetTessellationDomainOriginEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthClampEnableEXT(w, a)
{
    w.u32(257);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthClampEnable);
}
function h_vkCmdSetDepthClampEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetPolygonModeEXT(w, a)
{
    w.u32(258);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.polygonMode);
}
function h_vkCmdSetPolygonModeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetRasterizationSamplesEXT(w, a)
{
    w.u32(259);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.rasterizationSamples);
}
function h_vkCmdSetRasterizationSamplesEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetSampleMaskEXT(w, a)
{
    w.u32(260);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.samples);
    if(a.pSampleMask)
    {
        w.size(Math.floor((a.samples + 31) / 32));
        w.u32s(a.pSampleMask, Math.floor((a.samples + 31) / 32));
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetSampleMaskEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetAlphaToCoverageEnableEXT(w, a)
{
    w.u32(261);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.alphaToCoverageEnable);
}
function h_vkCmdSetAlphaToCoverageEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetAlphaToOneEnableEXT(w, a)
{
    w.u32(262);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.alphaToOneEnable);
}
function h_vkCmdSetAlphaToOneEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetLogicOpEnableEXT(w, a)
{
    w.u32(263);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.logicOpEnable);
}
function h_vkCmdSetLogicOpEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetColorBlendEnableEXT(w, a)
{
    w.u32(264);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstAttachment);
    w.u32(a.attachmentCount);
    if(a.pColorBlendEnables)
    {
        w.size(a.attachmentCount);
        w.u32s(a.pColorBlendEnables, a.attachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetColorBlendEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetColorBlendEquationEXT(w, a)
{
    w.u32(265);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstAttachment);
    w.u32(a.attachmentCount);
    if(a.pColorBlendEquations)
    {
        w.size(a.attachmentCount);
        for(let i = 0; i < a.attachmentCount; i++)
        {
            g_VkColorBlendEquationEXT(w, (a.pColorBlendEquations || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetColorBlendEquationEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetColorWriteMaskEXT(w, a)
{
    w.u32(266);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstAttachment);
    w.u32(a.attachmentCount);
    if(a.pColorWriteMasks)
    {
        w.size(a.attachmentCount);
        for(let i = 0; i < a.attachmentCount; i++)
        {
            w.u32((a.pColorWriteMasks || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetColorWriteMaskEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetRasterizationStreamEXT(w, a)
{
    w.u32(267);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.rasterizationStream);
}
function h_vkCmdSetRasterizationStreamEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetConservativeRasterizationModeEXT(w, a)
{
    w.u32(268);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.conservativeRasterizationMode);
}
function h_vkCmdSetConservativeRasterizationModeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetExtraPrimitiveOverestimationSizeEXT(w, a)
{
    w.u32(269);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.f32(a.extraPrimitiveOverestimationSize);
}
function h_vkCmdSetExtraPrimitiveOverestimationSizeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthClipEnableEXT(w, a)
{
    w.u32(270);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.depthClipEnable);
}
function h_vkCmdSetDepthClipEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetSampleLocationsEnableEXT(w, a)
{
    w.u32(271);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.sampleLocationsEnable);
}
function h_vkCmdSetSampleLocationsEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetColorBlendAdvancedEXT(w, a)
{
    w.u32(272);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.firstAttachment);
    w.u32(a.attachmentCount);
    if(a.pColorBlendAdvanced)
    {
        w.size(a.attachmentCount);
        for(let i = 0; i < a.attachmentCount; i++)
        {
            g_VkColorBlendAdvancedEXT(w, (a.pColorBlendAdvanced || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkCmdSetColorBlendAdvancedEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetProvokingVertexModeEXT(w, a)
{
    w.u32(273);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.provokingVertexMode);
}
function h_vkCmdSetProvokingVertexModeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetLineRasterizationModeEXT(w, a)
{
    w.u32(274);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.lineRasterizationMode);
}
function h_vkCmdSetLineRasterizationModeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetLineStippleEnableEXT(w, a)
{
    w.u32(275);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.stippledLineEnable);
}
function h_vkCmdSetLineStippleEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthClipNegativeOneToOneEXT(w, a)
{
    w.u32(276);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.negativeOneToOne);
}
function h_vkCmdSetDepthClipNegativeOneToOneEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPhysicalDeviceFragmentShadingRatesKHR(w, a)
{
    w.u32(277);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pFragmentShadingRateCount != null)
    {
        w.u64(1);
        w.u32(a.pFragmentShadingRateCount);
    }
    else w.u64(0);
    if(a.pFragmentShadingRates)
    {
        w.size((a.pFragmentShadingRateCount || 0));
        for(let i = 0; i < (a.pFragmentShadingRateCount || 0); i++)
        {
            g_VkPhysicalDeviceFragmentShadingRateKHR_partial(w, (a.pFragmentShadingRates || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceFragmentShadingRatesKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pFragmentShadingRateCount = r.u32();
    }
    else
    {
        a.pFragmentShadingRateCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pFragmentShadingRates = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pFragmentShadingRates[i] = h_VkPhysicalDeviceFragmentShadingRateKHR(r);
        }
    }
    else
    {
        r.size();
        a.pFragmentShadingRates = null;
    }
    return a;
}
function g_vkCmdSetFragmentShadingRateKHR(w, a)
{
    w.u32(278);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pFragmentSize != null)
    {
        w.u64(1);
        g_VkExtent2D(w, a.pFragmentSize || EMPTY);
    }
    else w.u64(0);
    w.size(2);
    w.i32s(a.combinerOps, 2);
}
function h_vkCmdSetFragmentShadingRateKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindIndexBuffer2(w, a)
{
    w.u32(279);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.u64(a.size);
    w.i32(a.indexType);
}
function h_vkCmdBindIndexBuffer2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetRenderingAreaGranularity(w, a)
{
    w.u32(280);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pRenderingAreaInfo != null)
    {
        w.u64(1);
        g_VkRenderingAreaInfo(w, a.pRenderingAreaInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pGranularity != null)
    {
        w.u64(1);
        g_VkExtent2D_partial(w, a.pGranularity || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetRenderingAreaGranularity_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pGranularity = h_VkExtent2D(r);
    }
    else
    {
        a.pGranularity = null;
    }
    return a;
}
function g_vkGetDeviceImageSubresourceLayout(w, a)
{
    w.u32(281);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pInfo != null)
    {
        w.u64(1);
        g_VkDeviceImageSubresourceInfo(w, a.pInfo || EMPTY);
    }
    else w.u64(0);
    if(a.pLayout != null)
    {
        w.u64(1);
        g_VkSubresourceLayout2_partial(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetDeviceImageSubresourceLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pLayout = h_VkSubresourceLayout2(r);
    }
    else
    {
        a.pLayout = null;
    }
    return a;
}
function g_vkGetImageSubresourceLayout2(w, a)
{
    w.u32(282);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.image);
    if(a.pSubresource != null)
    {
        w.u64(1);
        g_VkImageSubresource2(w, a.pSubresource || EMPTY);
    }
    else w.u64(0);
    if(a.pLayout != null)
    {
        w.u64(1);
        g_VkSubresourceLayout2_partial(w, a.pLayout || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetImageSubresourceLayout2_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pLayout = h_VkSubresourceLayout2(r);
    }
    else
    {
        a.pLayout = null;
    }
    return a;
}
function g_vkCmdSetSampleLocationsEXT(w, a)
{
    w.u32(283);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pSampleLocationsInfo != null)
    {
        w.u64(1);
        g_VkSampleLocationsInfoEXT(w, a.pSampleLocationsInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetSampleLocationsEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPhysicalDeviceMultisamplePropertiesEXT(w, a)
{
    w.u32(284);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.samples);
    if(a.pMultisampleProperties != null)
    {
        w.u64(1);
        g_VkMultisamplePropertiesEXT_partial(w, a.pMultisampleProperties || EMPTY);
    }
    else w.u64(0);
}
function h_vkGetPhysicalDeviceMultisamplePropertiesEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    if(r.u64())
    {
        a.pMultisampleProperties = h_VkMultisamplePropertiesEXT(r);
    }
    else
    {
        a.pMultisampleProperties = null;
    }
    return a;
}
function g_vkUnmapMemory2(w, a)
{
    w.u32(286);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pMemoryUnmapInfo != null)
    {
        w.u64(1);
        g_VkMemoryUnmapInfo(w, a.pMemoryUnmapInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkUnmapMemory2_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCmdSetRenderingAttachmentLocations(w, a)
{
    w.u32(287);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pLocationInfo != null)
    {
        w.u64(1);
        g_VkRenderingAttachmentLocationInfo(w, a.pLocationInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetRenderingAttachmentLocations_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetRenderingInputAttachmentIndices(w, a)
{
    w.u32(288);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pInputAttachmentIndexInfo != null)
    {
        w.u64(1);
        g_VkRenderingInputAttachmentIndexInfo(w, a.pInputAttachmentIndexInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetRenderingInputAttachmentIndices_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindDescriptorSets2(w, a)
{
    w.u32(289);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pBindDescriptorSetsInfo != null)
    {
        w.u64(1);
        g_VkBindDescriptorSetsInfo(w, a.pBindDescriptorSetsInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBindDescriptorSets2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPushConstants2(w, a)
{
    w.u32(290);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pPushConstantsInfo != null)
    {
        w.u64(1);
        g_VkPushConstantsInfo(w, a.pPushConstantsInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdPushConstants2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPushDescriptorSet2(w, a)
{
    w.u32(291);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pPushDescriptorSetInfo != null)
    {
        w.u64(1);
        g_VkPushDescriptorSetInfo(w, a.pPushDescriptorSetInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdPushDescriptorSet2_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCopyImageToImage(w, a)
{
    w.u32(295);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCopyImageToImageInfo != null)
    {
        w.u64(1);
        g_VkCopyImageToImageInfo(w, a.pCopyImageToImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCopyImageToImage_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkTransitionImageLayout(w, a)
{
    w.u32(296);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.transitionCount);
    if(a.pTransitions)
    {
        w.size(a.transitionCount);
        for(let i = 0; i < a.transitionCount; i++)
        {
            g_VkHostImageLayoutTransitionInfo(w, (a.pTransitions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkTransitionImageLayout_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCopyImageToMemoryMESA(w, a)
{
    w.u32(297);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCopyImageToMemoryInfo != null)
    {
        w.u64(1);
        g_VkCopyImageToMemoryInfoMESA(w, a.pCopyImageToMemoryInfo || EMPTY);
    }
    else w.u64(0);
    w.u64(a.dataSize);
    w.size(a.pData ? a.dataSize : 0);
}
function h_vkCopyImageToMemoryMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pData = r.blob(array_size);
    }
    else
    {
        r.size();
        a.pData = null;
    }
    return a;
}
function g_vkCopyMemoryToImageMESA(w, a)
{
    w.u32(298);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pCopyMemoryToImageInfo != null)
    {
        w.u64(1);
        g_VkCopyMemoryToImageInfoMESA(w, a.pCopyMemoryToImageInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCopyMemoryToImageMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCreateDeferredOperationKHR(w, a)
{
    w.u32(299);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
    if(a.pDeferredOperation != null)
    {
        w.u64(1);
        w.h(a.pDeferredOperation);
    }
    else w.u64(0);
}
function h_vkCreateDeferredOperationKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pDeferredOperation = r.h();
    }
    else
    {
        a.pDeferredOperation = null;
    }
    return a;
}
function g_vkDestroyDeferredOperationKHR(w, a)
{
    w.u32(300);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.operation);
    if(a.pAllocator != null)
    {
        w.u64(1);
    }
    else w.u64(0);
}
function h_vkDestroyDeferredOperationKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetDeferredOperationMaxConcurrencyKHR(w, a)
{
    w.u32(301);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.operation);
}
function h_vkGetDeferredOperationMaxConcurrencyKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.u32();
    return a;
}
function g_vkGetDeferredOperationResultKHR(w, a)
{
    w.u32(302);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.operation);
}
function h_vkGetDeferredOperationResultKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkDeferredOperationJoinKHR(w, a)
{
    w.u32(303);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.h(a.operation);
}
function h_vkDeferredOperationJoinKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    return a;
}
function g_vkCmdSetDepthBias2EXT(w, a)
{
    w.u32(328);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pDepthBiasInfo != null)
    {
        w.u64(1);
        g_VkDepthBiasInfoEXT(w, a.pDepthBiasInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetDepthBias2EXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetAttachmentFeedbackLoopEnableEXT(w, a)
{
    w.u32(329);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.aspectMask);
}
function h_vkCmdSetAttachmentFeedbackLoopEnableEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdSetDepthClampRangeEXT(w, a)
{
    w.u32(330);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.i32(a.depthClampMode);
    if(a.pDepthClampRange != null)
    {
        w.u64(1);
        g_VkDepthClampRangeEXT(w, a.pDepthClampRange || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdSetDepthClampRangeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR(w, a)
{
    w.u32(331);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    if(a.pPropertyCount != null)
    {
        w.u64(1);
        w.u32(a.pPropertyCount);
    }
    else w.u64(0);
    if(a.pProperties)
    {
        w.size((a.pPropertyCount || 0));
        for(let i = 0; i < (a.pPropertyCount || 0); i++)
        {
            g_VkCooperativeMatrixPropertiesKHR_partial(w, (a.pProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetPhysicalDeviceCooperativeMatrixPropertiesKHR_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pPropertyCount = r.u32();
    }
    else
    {
        a.pPropertyCount = null;
    }
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pProperties[i] = h_VkCooperativeMatrixPropertiesKHR(r);
        }
    }
    else
    {
        r.size();
        a.pProperties = null;
    }
    return a;
}
function g_vkCmdDrawMeshTasksEXT(w, a)
{
    w.u32(332);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.u32(a.groupCountX);
    w.u32(a.groupCountY);
    w.u32(a.groupCountZ);
}
function h_vkCmdDrawMeshTasksEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawMeshTasksIndirectEXT(w, a)
{
    w.u32(333);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.u32(a.drawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawMeshTasksIndirectEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdDrawMeshTasksIndirectCountEXT(w, a)
{
    w.u32(334);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    w.h(a.buffer);
    w.u64(a.offset);
    w.h(a.countBuffer);
    w.u64(a.countBufferOffset);
    w.u32(a.maxDrawCount);
    w.u32(a.stride);
}
function h_vkCmdDrawMeshTasksIndirectCountEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkWriteSamplerDescriptorMESA(w, a)
{
    w.u32(335);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, a.pSampler || EMPTY);
    }
    else w.u64(0);
    w.u64(a.dataSize);
    w.size(a.pData ? a.dataSize : 0);
}
function h_vkWriteSamplerDescriptorMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pData = r.blob(array_size);
    }
    else
    {
        r.size();
        a.pData = null;
    }
    return a;
}
function g_vkWriteResourceDescriptorMESA(w, a)
{
    w.u32(336);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pResource != null)
    {
        w.u64(1);
        g_VkResourceDescriptorInfoEXT(w, a.pResource || EMPTY);
    }
    else w.u64(0);
    w.u64(a.dataSize);
    w.size(a.pData ? a.dataSize : 0);
}
function h_vkWriteResourceDescriptorMESA_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const array_size = r.size();
        a.pData = r.blob(array_size);
    }
    else
    {
        r.size();
        a.pData = null;
    }
    return a;
}
function g_vkCmdBindSamplerHeapEXT(w, a)
{
    w.u32(339);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pBindInfo != null)
    {
        w.u64(1);
        g_VkBindHeapInfoEXT(w, a.pBindInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBindSamplerHeapEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdBindResourceHeapEXT(w, a)
{
    w.u32(340);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pBindInfo != null)
    {
        w.u64(1);
        g_VkBindHeapInfoEXT(w, a.pBindInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdBindResourceHeapEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkCmdPushDataEXT(w, a)
{
    w.u32(341);
    w.u32(a.cmd_flags || 0);
    w.h(a.commandBuffer);
    if(a.pPushDataInfo != null)
    {
        w.u64(1);
        g_VkPushDataInfoEXT(w, a.pPushDataInfo || EMPTY);
    }
    else w.u64(0);
}
function h_vkCmdPushDataEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_vkGetImageOpaqueCaptureDataEXT(w, a)
{
    w.u32(342);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.imageCount);
    if(a.pImages)
    {
        w.size(a.imageCount);
        for(let i = 0; i < a.imageCount; i++)
        {
            w.h((a.pImages || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(a.pDatas)
    {
        w.size(a.imageCount);
        for(let i = 0; i < a.imageCount; i++)
        {
            g_VkHostAddressRangeEXT_partial(w, (a.pDatas || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function h_vkGetImageOpaqueCaptureDataEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        a.pDatas = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            a.pDatas[i] = h_VkHostAddressRangeEXT(r);
        }
    }
    else
    {
        r.size();
        a.pDatas = null;
    }
    return a;
}
function g_vkGetPhysicalDeviceDescriptorSizeEXT(w, a)
{
    w.u32(343);
    w.u32(a.cmd_flags || 0);
    w.h(a.physicalDevice);
    w.i32(a.descriptorType);
}
function h_vkGetPhysicalDeviceDescriptorSizeEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.u64();
    return a;
}
function g_vkRegisterCustomBorderColorEXT(w, a)
{
    w.u32(344);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    if(a.pBorderColor != null)
    {
        w.u64(1);
        g_VkSamplerCustomBorderColorCreateInfoEXT(w, a.pBorderColor || EMPTY);
    }
    else w.u64(0);
    w.u32(a.requestIndex);
    if(a.pIndex != null)
    {
        w.u64(1);
        w.u32(a.pIndex);
    }
    else w.u64(0);
}
function h_vkRegisterCustomBorderColorEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    a.ret = r.i32();
    if(r.u64())
    {
        a.pIndex = r.u32();
    }
    else
    {
        a.pIndex = null;
    }
    return a;
}
function g_vkUnregisterCustomBorderColorEXT(w, a)
{
    w.u32(345);
    w.u32(a.cmd_flags || 0);
    w.h(a.device);
    w.u32(a.index);
}
function h_vkUnregisterCustomBorderColorEXT_reply(r)
{
    const a = {};
    a.command = r.u32();
    return a;
}
function g_VkBufferUsageFlags2CreateInfo_self(w, o)
{
    w.u64(o.usage);
}
function g_VkExternalMemoryBufferCreateInfo_self(w, o)
{
    w.u32(o.handleTypes);
}
function g_VkBufferOpaqueCaptureAddressCreateInfo_self(w, o)
{
    w.u64(o.opaqueCaptureAddress);
}
function g_VkBufferDeviceAddressCreateInfoEXT_self(w, o)
{
    w.u64(o.deviceAddress);
}
function g_VkBindBufferMemoryDeviceGroupInfo_self(w, o)
{
    w.u32(o.deviceIndexCount);
    if(o.pDeviceIndices)
    {
        w.size(o.deviceIndexCount);
        w.u32s(o.pDeviceIndices, o.deviceIndexCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkBindMemoryStatus_self(w, o)
{
    if(o.pResult != null)
    {
        w.u64(1);
        w.i32(o.pResult);
    }
    else w.u64(0);
}
function g_VkCommandBufferInheritanceConditionalRenderingInfoEXT_self(w, o)
{
    w.u32(o.conditionalRenderingEnable);
}
function g_VkCommandBufferInheritanceRenderingInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachmentFormats)
    {
        w.size(o.colorAttachmentCount);
        w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    }
    else
    {
        w.size(0);
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
    w.i32(o.rasterizationSamples);
}
function g_VkRenderingAttachmentLocationInfo_self(w, o)
{
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachmentLocations)
    {
        w.size(o.colorAttachmentCount);
        w.u32s(o.pColorAttachmentLocations, o.colorAttachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkRenderingInputAttachmentIndexInfo_self(w, o)
{
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachmentInputIndices)
    {
        w.size(o.colorAttachmentCount);
        w.u32s(o.pColorAttachmentInputIndices, o.colorAttachmentCount);
    }
    else
    {
        w.size(0);
    }
    if(o.pDepthInputAttachmentIndex != null)
    {
        w.u64(1);
        w.u32(o.pDepthInputAttachmentIndex);
    }
    else w.u64(0);
    if(o.pStencilInputAttachmentIndex != null)
    {
        w.u64(1);
        w.u32(o.pStencilInputAttachmentIndex);
    }
    else w.u64(0);
}
function g_VkCommandBufferInheritanceDescriptorHeapInfoEXT_self(w, o)
{
    if(o.pSamplerHeapBindInfo != null)
    {
        w.u64(1);
        g_VkBindHeapInfoEXT(w, o.pSamplerHeapBindInfo || EMPTY);
    }
    else w.u64(0);
    if(o.pResourceHeapBindInfo != null)
    {
        w.u64(1);
        g_VkBindHeapInfoEXT(w, o.pResourceHeapBindInfo || EMPTY);
    }
    else w.u64(0);
}
function g_VkDeviceGroupCommandBufferBeginInfo_self(w, o)
{
    w.u32(o.deviceMask);
}
function g_VkExternalMemoryAcquireUnmodifiedEXT_self(w, o)
{
    w.u32(o.acquireUnmodifiedMemory);
}
function g_VkSampleLocationsInfoEXT_self(w, o)
{
    w.i32(o.sampleLocationsPerPixel);
    g_VkExtent2D(w, o.sampleLocationGridSize || EMPTY);
    w.u32(o.sampleLocationsCount);
    if(o.pSampleLocations)
    {
        w.size(o.sampleLocationsCount);
        for(let i = 0; i < o.sampleLocationsCount; i++)
        {
            g_VkSampleLocationEXT(w, (o.pSampleLocations || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDeviceGroupRenderPassBeginInfo_self(w, o)
{
    w.u32(o.deviceMask);
    w.u32(o.deviceRenderAreaCount);
    if(o.pDeviceRenderAreas)
    {
        w.size(o.deviceRenderAreaCount);
        for(let i = 0; i < o.deviceRenderAreaCount; i++)
        {
            g_VkRect2D(w, (o.pDeviceRenderAreas || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkRenderPassSampleLocationsBeginInfoEXT_self(w, o)
{
    w.u32(o.attachmentInitialSampleLocationsCount);
    if(o.pAttachmentInitialSampleLocations)
    {
        w.size(o.attachmentInitialSampleLocationsCount);
        for(let i = 0; i < o.attachmentInitialSampleLocationsCount; i++)
        {
            g_VkAttachmentSampleLocationsEXT(w, (o.pAttachmentInitialSampleLocations || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.postSubpassSampleLocationsCount);
    if(o.pPostSubpassSampleLocations)
    {
        w.size(o.postSubpassSampleLocationsCount);
        for(let i = 0; i < o.postSubpassSampleLocationsCount; i++)
        {
            g_VkSubpassSampleLocationsEXT(w, (o.pPostSubpassSampleLocations || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkRenderPassAttachmentBeginInfo_self(w, o)
{
    w.u32(o.attachmentCount);
    if(o.pAttachments)
    {
        w.size(o.attachmentCount);
        for(let i = 0; i < o.attachmentCount; i++)
        {
            w.h((o.pAttachments || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkMultisampledRenderToSingleSampledInfoEXT_self(w, o)
{
    w.u32(o.multisampledRenderToSingleSampledEnable);
    w.i32(o.rasterizationSamples);
}
function g_VkRenderingFragmentShadingRateAttachmentInfoKHR_self(w, o)
{
    w.h(o.imageView);
    w.i32(o.imageLayout);
    g_VkExtent2D(w, o.shadingRateAttachmentTexelSize || EMPTY);
}
function g_VkDepthBiasRepresentationInfoEXT_self(w, o)
{
    w.i32(o.depthBiasRepresentation);
    w.u32(o.depthBiasExact);
}
function g_VkPipelineLayoutCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.setLayoutCount);
    if(o.pSetLayouts)
    {
        w.size(o.setLayoutCount);
        for(let i = 0; i < o.setLayoutCount; i++)
        {
            w.h((o.pSetLayouts || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.pushConstantRangeCount);
    if(o.pPushConstantRanges)
    {
        w.size(o.pushConstantRangeCount);
        for(let i = 0; i < o.pushConstantRangeCount; i++)
        {
            g_VkPushConstantRange(w, (o.pPushConstantRanges || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorPoolInlineUniformBlockCreateInfo_self(w, o)
{
    w.u32(o.maxInlineUniformBlockBindings);
}
function g_VkMutableDescriptorTypeCreateInfoEXT_self(w, o)
{
    w.u32(o.mutableDescriptorTypeListCount);
    if(o.pMutableDescriptorTypeLists)
    {
        w.size(o.mutableDescriptorTypeListCount);
        for(let i = 0; i < o.mutableDescriptorTypeListCount; i++)
        {
            g_VkMutableDescriptorTypeListEXT(w, (o.pMutableDescriptorTypeLists || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorSetVariableDescriptorCountAllocateInfo_self(w, o)
{
    w.u32(o.descriptorSetCount);
    if(o.pDescriptorCounts)
    {
        w.size(o.descriptorSetCount);
        w.u32s(o.pDescriptorCounts, o.descriptorSetCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorSetLayoutBindingFlagsCreateInfo_self(w, o)
{
    w.u32(o.bindingCount);
    if(o.pBindingFlags)
    {
        w.size(o.bindingCount);
        for(let i = 0; i < o.bindingCount; i++)
        {
            w.u32((o.pBindingFlags || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDeviceQueueGlobalPriorityCreateInfo_self(w, o)
{
    w.i32(o.globalPriority);
}
function g_VkPhysicalDevicePrivateDataFeatures_self(w, o)
{
    w.u32(o.privateData);
}
function g_VkPhysicalDeviceVariablePointersFeatures_self(w, o)
{
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
}
function g_VkPhysicalDeviceMultiviewFeatures_self(w, o)
{
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
}
function g_VkPhysicalDevice16BitStorageFeatures_self(w, o)
{
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
}
function g_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self(w, o)
{
    w.u32(o.shaderSubgroupExtendedTypes);
}
function g_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self(w, o)
{
    w.u32(o.samplerYcbcrConversion);
}
function g_VkPhysicalDeviceProtectedMemoryFeatures_self(w, o)
{
    w.u32(o.protectedMemory);
}
function g_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self(w, o)
{
    w.u32(o.advancedBlendCoherentOperations);
}
function g_VkPhysicalDeviceMultiDrawFeaturesEXT_self(w, o)
{
    w.u32(o.multiDraw);
}
function g_VkPhysicalDeviceInlineUniformBlockFeatures_self(w, o)
{
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
}
function g_VkPhysicalDeviceMaintenance4Features_self(w, o)
{
    w.u32(o.maintenance4);
}
function g_VkPhysicalDeviceMaintenance5Features_self(w, o)
{
    w.u32(o.maintenance5);
}
function g_VkPhysicalDeviceMaintenance6Features_self(w, o)
{
    w.u32(o.maintenance6);
}
function g_VkPhysicalDeviceMaintenance7FeaturesKHR_self(w, o)
{
    w.u32(o.maintenance7);
}
function g_VkPhysicalDeviceShaderDrawParametersFeatures_self(w, o)
{
    w.u32(o.shaderDrawParameters);
}
function g_VkPhysicalDeviceShaderFloat16Int8Features_self(w, o)
{
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
}
function g_VkPhysicalDeviceHostQueryResetFeatures_self(w, o)
{
    w.u32(o.hostQueryReset);
}
function g_VkPhysicalDeviceGlobalPriorityQueryFeatures_self(w, o)
{
    w.u32(o.globalPriorityQuery);
}
function g_VkPhysicalDeviceDescriptorIndexingFeatures_self(w, o)
{
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
}
function g_VkPhysicalDeviceTimelineSemaphoreFeatures_self(w, o)
{
    w.u32(o.timelineSemaphore);
}
function g_VkPhysicalDevice8BitStorageFeatures_self(w, o)
{
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
}
function g_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self(w, o)
{
    w.u32(o.conditionalRendering);
    w.u32(o.inheritedConditionalRendering);
}
function g_VkPhysicalDeviceVulkanMemoryModelFeatures_self(w, o)
{
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
}
function g_VkPhysicalDeviceShaderAtomicInt64Features_self(w, o)
{
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
}
function g_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self(w, o)
{
    w.u32(o.shaderBufferFloat32Atomics);
    w.u32(o.shaderBufferFloat32AtomicAdd);
    w.u32(o.shaderBufferFloat64Atomics);
    w.u32(o.shaderBufferFloat64AtomicAdd);
    w.u32(o.shaderSharedFloat32Atomics);
    w.u32(o.shaderSharedFloat32AtomicAdd);
    w.u32(o.shaderSharedFloat64Atomics);
    w.u32(o.shaderSharedFloat64AtomicAdd);
    w.u32(o.shaderImageFloat32Atomics);
    w.u32(o.shaderImageFloat32AtomicAdd);
    w.u32(o.sparseImageFloat32Atomics);
    w.u32(o.sparseImageFloat32AtomicAdd);
}
function g_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self(w, o)
{
    w.u32(o.shaderBufferFloat16Atomics);
    w.u32(o.shaderBufferFloat16AtomicAdd);
    w.u32(o.shaderBufferFloat16AtomicMinMax);
    w.u32(o.shaderBufferFloat32AtomicMinMax);
    w.u32(o.shaderBufferFloat64AtomicMinMax);
    w.u32(o.shaderSharedFloat16Atomics);
    w.u32(o.shaderSharedFloat16AtomicAdd);
    w.u32(o.shaderSharedFloat16AtomicMinMax);
    w.u32(o.shaderSharedFloat32AtomicMinMax);
    w.u32(o.shaderSharedFloat64AtomicMinMax);
    w.u32(o.shaderImageFloat32AtomicMinMax);
    w.u32(o.sparseImageFloat32AtomicMinMax);
}
function g_VkPhysicalDeviceVertexAttributeDivisorFeatures_self(w, o)
{
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
}
function g_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self(w, o)
{
    w.u32(o.transformFeedback);
    w.u32(o.geometryStreams);
}
function g_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self(w, o)
{
    w.u32(o.computeDerivativeGroupQuads);
    w.u32(o.computeDerivativeGroupLinear);
}
function g_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self(w, o)
{
    w.u32(o.fragmentShaderBarycentric);
}
function g_VkPhysicalDeviceMeshShaderFeaturesEXT_self(w, o)
{
    w.u32(o.taskShader);
    w.u32(o.meshShader);
    w.u32(o.multiviewMeshShader);
    w.u32(o.primitiveFragmentShadingRateMeshShader);
    w.u32(o.meshShaderQueries);
}
function g_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self(w, o)
{
    w.u32(o.accelerationStructure);
    w.u32(o.accelerationStructureCaptureReplay);
    w.u32(o.accelerationStructureIndirectBuild);
    w.u32(o.accelerationStructureHostCommands);
    w.u32(o.descriptorBindingAccelerationStructureUpdateAfterBind);
}
function g_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingPipeline);
    w.u32(o.rayTracingPipelineShaderGroupHandleCaptureReplay);
    w.u32(o.rayTracingPipelineShaderGroupHandleCaptureReplayMixed);
    w.u32(o.rayTracingPipelineTraceRaysIndirect);
    w.u32(o.rayTraversalPrimitiveCulling);
}
function g_VkPhysicalDeviceRayQueryFeaturesKHR_self(w, o)
{
    w.u32(o.rayQuery);
}
function g_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingMaintenance1);
    w.u32(o.rayTracingPipelineTraceRaysIndirect2);
}
function g_VkPhysicalDeviceScalarBlockLayoutFeatures_self(w, o)
{
    w.u32(o.scalarBlockLayout);
}
function g_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self(w, o)
{
    w.u32(o.uniformBufferStandardLayout);
}
function g_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self(w, o)
{
    w.u32(o.depthClipEnable);
}
function g_VkPhysicalDeviceBufferDeviceAddressFeatures_self(w, o)
{
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}
function g_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self(w, o)
{
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
}
function g_VkPhysicalDeviceImagelessFramebufferFeatures_self(w, o)
{
    w.u32(o.imagelessFramebuffer);
}
function g_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self(w, o)
{
    w.u32(o.textureCompressionASTC_HDR);
}
function g_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self(w, o)
{
    w.u32(o.ycbcrImageArrays);
}
function g_VkPhysicalDeviceShaderClockFeaturesKHR_self(w, o)
{
    w.u32(o.shaderSubgroupClock);
    w.u32(o.shaderDeviceClock);
}
function g_VkPhysicalDeviceIndexTypeUint8Features_self(w, o)
{
    w.u32(o.indexTypeUint8);
}
function g_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self(w, o)
{
    w.u32(o.fragmentShaderSampleInterlock);
    w.u32(o.fragmentShaderPixelInterlock);
    w.u32(o.fragmentShaderShadingRateInterlock);
}
function g_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self(w, o)
{
    w.u32(o.separateDepthStencilLayouts);
}
function g_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self(w, o)
{
    w.u32(o.primitiveTopologyListRestart);
    w.u32(o.primitiveTopologyPatchListRestart);
}
function g_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self(w, o)
{
    w.u32(o.shaderDemoteToHelperInvocation);
}
function g_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self(w, o)
{
    w.u32(o.texelBufferAlignment);
}
function g_VkPhysicalDeviceSubgroupSizeControlFeatures_self(w, o)
{
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
}
function g_VkPhysicalDeviceLineRasterizationFeatures_self(w, o)
{
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
}
function g_VkPhysicalDevicePipelineCreationCacheControlFeatures_self(w, o)
{
    w.u32(o.pipelineCreationCacheControl);
}
function g_VkPhysicalDeviceVulkan11Features_self(w, o)
{
    w.u32(o.storageBuffer16BitAccess);
    w.u32(o.uniformAndStorageBuffer16BitAccess);
    w.u32(o.storagePushConstant16);
    w.u32(o.storageInputOutput16);
    w.u32(o.multiview);
    w.u32(o.multiviewGeometryShader);
    w.u32(o.multiviewTessellationShader);
    w.u32(o.variablePointersStorageBuffer);
    w.u32(o.variablePointers);
    w.u32(o.protectedMemory);
    w.u32(o.samplerYcbcrConversion);
    w.u32(o.shaderDrawParameters);
}
function g_VkPhysicalDeviceVulkan12Features_self(w, o)
{
    w.u32(o.samplerMirrorClampToEdge);
    w.u32(o.drawIndirectCount);
    w.u32(o.storageBuffer8BitAccess);
    w.u32(o.uniformAndStorageBuffer8BitAccess);
    w.u32(o.storagePushConstant8);
    w.u32(o.shaderBufferInt64Atomics);
    w.u32(o.shaderSharedInt64Atomics);
    w.u32(o.shaderFloat16);
    w.u32(o.shaderInt8);
    w.u32(o.descriptorIndexing);
    w.u32(o.shaderInputAttachmentArrayDynamicIndexing);
    w.u32(o.shaderUniformTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageTexelBufferArrayDynamicIndexing);
    w.u32(o.shaderUniformBufferArrayNonUniformIndexing);
    w.u32(o.shaderSampledImageArrayNonUniformIndexing);
    w.u32(o.shaderStorageBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageImageArrayNonUniformIndexing);
    w.u32(o.shaderInputAttachmentArrayNonUniformIndexing);
    w.u32(o.shaderUniformTexelBufferArrayNonUniformIndexing);
    w.u32(o.shaderStorageTexelBufferArrayNonUniformIndexing);
    w.u32(o.descriptorBindingUniformBufferUpdateAfterBind);
    w.u32(o.descriptorBindingSampledImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageImageUpdateAfterBind);
    w.u32(o.descriptorBindingStorageBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUniformTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingStorageTexelBufferUpdateAfterBind);
    w.u32(o.descriptorBindingUpdateUnusedWhilePending);
    w.u32(o.descriptorBindingPartiallyBound);
    w.u32(o.descriptorBindingVariableDescriptorCount);
    w.u32(o.runtimeDescriptorArray);
    w.u32(o.samplerFilterMinmax);
    w.u32(o.scalarBlockLayout);
    w.u32(o.imagelessFramebuffer);
    w.u32(o.uniformBufferStandardLayout);
    w.u32(o.shaderSubgroupExtendedTypes);
    w.u32(o.separateDepthStencilLayouts);
    w.u32(o.hostQueryReset);
    w.u32(o.timelineSemaphore);
    w.u32(o.bufferDeviceAddress);
    w.u32(o.bufferDeviceAddressCaptureReplay);
    w.u32(o.bufferDeviceAddressMultiDevice);
    w.u32(o.vulkanMemoryModel);
    w.u32(o.vulkanMemoryModelDeviceScope);
    w.u32(o.vulkanMemoryModelAvailabilityVisibilityChains);
    w.u32(o.shaderOutputViewportIndex);
    w.u32(o.shaderOutputLayer);
    w.u32(o.subgroupBroadcastDynamicId);
}
function g_VkPhysicalDeviceVulkan13Features_self(w, o)
{
    w.u32(o.robustImageAccess);
    w.u32(o.inlineUniformBlock);
    w.u32(o.descriptorBindingInlineUniformBlockUpdateAfterBind);
    w.u32(o.pipelineCreationCacheControl);
    w.u32(o.privateData);
    w.u32(o.shaderDemoteToHelperInvocation);
    w.u32(o.shaderTerminateInvocation);
    w.u32(o.subgroupSizeControl);
    w.u32(o.computeFullSubgroups);
    w.u32(o.synchronization2);
    w.u32(o.textureCompressionASTC_HDR);
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
    w.u32(o.dynamicRendering);
    w.u32(o.shaderIntegerDotProduct);
    w.u32(o.maintenance4);
}
function g_VkPhysicalDeviceVulkan14Features_self(w, o)
{
    w.u32(o.globalPriorityQuery);
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
    w.u32(o.shaderFloatControls2);
    w.u32(o.shaderExpectAssume);
    w.u32(o.rectangularLines);
    w.u32(o.bresenhamLines);
    w.u32(o.smoothLines);
    w.u32(o.stippledRectangularLines);
    w.u32(o.stippledBresenhamLines);
    w.u32(o.stippledSmoothLines);
    w.u32(o.vertexAttributeInstanceRateDivisor);
    w.u32(o.vertexAttributeInstanceRateZeroDivisor);
    w.u32(o.indexTypeUint8);
    w.u32(o.dynamicRenderingLocalRead);
    w.u32(o.maintenance5);
    w.u32(o.maintenance6);
    w.u32(o.pipelineProtectedAccess);
    w.u32(o.pipelineRobustness);
    w.u32(o.hostImageCopy);
    w.u32(o.pushDescriptor);
}
function g_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self(w, o)
{
    w.u32(o.customBorderColors);
    w.u32(o.customBorderColorWithoutFormat);
}
function g_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self(w, o)
{
    w.u32(o.borderColorSwizzle);
    w.u32(o.borderColorSwizzleFromImage);
}
function g_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState);
}
function g_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState2);
    w.u32(o.extendedDynamicState2LogicOp);
    w.u32(o.extendedDynamicState2PatchControlPoints);
}
function g_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self(w, o)
{
    w.u32(o.extendedDynamicState3TessellationDomainOrigin);
    w.u32(o.extendedDynamicState3DepthClampEnable);
    w.u32(o.extendedDynamicState3PolygonMode);
    w.u32(o.extendedDynamicState3RasterizationSamples);
    w.u32(o.extendedDynamicState3SampleMask);
    w.u32(o.extendedDynamicState3AlphaToCoverageEnable);
    w.u32(o.extendedDynamicState3AlphaToOneEnable);
    w.u32(o.extendedDynamicState3LogicOpEnable);
    w.u32(o.extendedDynamicState3ColorBlendEnable);
    w.u32(o.extendedDynamicState3ColorBlendEquation);
    w.u32(o.extendedDynamicState3ColorWriteMask);
    w.u32(o.extendedDynamicState3RasterizationStream);
    w.u32(o.extendedDynamicState3ConservativeRasterizationMode);
    w.u32(o.extendedDynamicState3ExtraPrimitiveOverestimationSize);
    w.u32(o.extendedDynamicState3DepthClipEnable);
    w.u32(o.extendedDynamicState3SampleLocationsEnable);
    w.u32(o.extendedDynamicState3ColorBlendAdvanced);
    w.u32(o.extendedDynamicState3ProvokingVertexMode);
    w.u32(o.extendedDynamicState3LineRasterizationMode);
    w.u32(o.extendedDynamicState3LineStippleEnable);
    w.u32(o.extendedDynamicState3DepthClipNegativeOneToOne);
    w.u32(o.extendedDynamicState3ViewportWScalingEnable);
    w.u32(o.extendedDynamicState3ViewportSwizzle);
    w.u32(o.extendedDynamicState3CoverageToColorEnable);
    w.u32(o.extendedDynamicState3CoverageToColorLocation);
    w.u32(o.extendedDynamicState3CoverageModulationMode);
    w.u32(o.extendedDynamicState3CoverageModulationTableEnable);
    w.u32(o.extendedDynamicState3CoverageModulationTable);
    w.u32(o.extendedDynamicState3CoverageReductionMode);
    w.u32(o.extendedDynamicState3RepresentativeFragmentTestEnable);
    w.u32(o.extendedDynamicState3ShadingRateImageEnable);
}
function g_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self(w, o)
{
    w.u32(o.shaderZeroInitializeWorkgroupMemory);
}
function g_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self(w, o)
{
    w.u32(o.shaderSubgroupUniformControlFlow);
}
function g_VkPhysicalDeviceRobustness2FeaturesKHR_self(w, o)
{
    w.u32(o.robustBufferAccess2);
    w.u32(o.robustImageAccess2);
    w.u32(o.nullDescriptor);
}
function g_VkPhysicalDeviceImageRobustnessFeatures_self(w, o)
{
    w.u32(o.robustImageAccess);
}
function g_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self(w, o)
{
    w.u32(o.workgroupMemoryExplicitLayout);
    w.u32(o.workgroupMemoryExplicitLayoutScalarBlockLayout);
    w.u32(o.workgroupMemoryExplicitLayout8BitAccess);
    w.u32(o.workgroupMemoryExplicitLayout16BitAccess);
}
function g_VkPhysicalDevice4444FormatsFeaturesEXT_self(w, o)
{
    w.u32(o.formatA4R4G4B4);
    w.u32(o.formatA4B4G4R4);
}
function g_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self(w, o)
{
    w.u32(o.shaderImageInt64Atomics);
    w.u32(o.sparseImageInt64Atomics);
}
function g_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self(w, o)
{
    w.u32(o.pipelineFragmentShadingRate);
    w.u32(o.primitiveFragmentShadingRate);
    w.u32(o.attachmentFragmentShadingRate);
}
function g_VkPhysicalDeviceShaderTerminateInvocationFeatures_self(w, o)
{
    w.u32(o.shaderTerminateInvocation);
}
function g_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self(w, o)
{
    w.u32(o.image2DViewOf3D);
    w.u32(o.sampler2DViewOf3D);
}
function g_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self(w, o)
{
    w.u32(o.imageSlicedViewOf3D);
}
function g_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.attachmentFeedbackLoopDynamicState);
}
function g_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self(w, o)
{
    w.u32(o.legacyVertexAttributes);
}
function g_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self(w, o)
{
    w.u32(o.mutableDescriptorType);
}
function g_VkPhysicalDeviceDepthClipControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthClipControl);
}
function g_VkPhysicalDeviceDepthClampControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthClampControl);
}
function g_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self(w, o)
{
    w.u32(o.vertexInputDynamicState);
}
function g_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self(w, o)
{
    w.u32(o.shaderRelaxedExtendedInstruction);
}
function g_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self(w, o)
{
    w.u32(o.colorWriteEnable);
}
function g_VkPhysicalDeviceSynchronization2Features_self(w, o)
{
    w.u32(o.synchronization2);
}
function g_VkPhysicalDeviceHostImageCopyFeatures_self(w, o)
{
    w.u32(o.hostImageCopy);
}
function g_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self(w, o)
{
    w.u32(o.primitivesGeneratedQuery);
    w.u32(o.primitivesGeneratedQueryWithRasterizerDiscard);
    w.u32(o.primitivesGeneratedQueryWithNonZeroStreams);
}
function g_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self(w, o)
{
    w.u32(o.legacyDithering);
}
function g_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self(w, o)
{
    w.u32(o.multisampledRenderToSingleSampled);
}
function g_VkPhysicalDevicePipelineProtectedAccessFeatures_self(w, o)
{
    w.u32(o.pipelineProtectedAccess);
}
function g_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self(w, o)
{
    w.u32(o.ycbcr2plane444Formats);
}
function g_VkPhysicalDeviceProvokingVertexFeaturesEXT_self(w, o)
{
    w.u32(o.provokingVertexLast);
    w.u32(o.transformFeedbackPreservesProvokingVertex);
}
function g_VkPhysicalDeviceShaderIntegerDotProductFeatures_self(w, o)
{
    w.u32(o.shaderIntegerDotProduct);
}
function g_VkPhysicalDeviceShaderFmaFeaturesKHR_self(w, o)
{
    w.u32(o.shaderFmaFloat16);
    w.u32(o.shaderFmaFloat32);
    w.u32(o.shaderFmaFloat64);
}
function g_VkPhysicalDeviceDynamicRenderingFeatures_self(w, o)
{
    w.u32(o.dynamicRendering);
}
function g_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self(w, o)
{
    w.u32(o.minLod);
}
function g_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self(w, o)
{
    w.u32(o.rasterizationOrderColorAttachmentAccess);
    w.u32(o.rasterizationOrderDepthAttachmentAccess);
    w.u32(o.rasterizationOrderStencilAttachmentAccess);
}
function g_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self(w, o)
{
    w.u32(o.graphicsPipelineLibrary);
}
function g_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self(w, o)
{
    w.u32(o.nestedCommandBuffer);
    w.u32(o.nestedCommandBufferRendering);
    w.u32(o.nestedCommandBufferSimultaneousUse);
}
function g_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self(w, o)
{
    w.u32(o.nonSeamlessCubeMap);
}
function g_VkPhysicalDevicePipelineRobustnessFeatures_self(w, o)
{
    w.u32(o.pipelineRobustness);
}
function g_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self(w, o)
{
    w.u32(o.attachmentFeedbackLoopLayout);
}
function g_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self(w, o)
{
    w.u32(o.depthClampZeroOne);
}
function g_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self(w, o)
{
    w.u32(o.pipelineLibraryGroupHandles);
}
function g_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self(w, o)
{
    w.u32(o.dynamicRenderingUnusedAttachments);
}
function g_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self(w, o)
{
    w.u32(o.depthBiasControl);
    w.u32(o.leastRepresentableValueForceUnormRepresentation);
    w.u32(o.floatRepresentation);
    w.u32(o.depthBiasExact);
}
function g_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self(w, o)
{
    w.u32(o.rayTracingPositionFetch);
}
function g_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self(w, o)
{
    w.u32(o.cooperativeMatrix);
    w.u32(o.cooperativeMatrixRobustBufferAccess);
}
function g_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self(w, o)
{
    w.u32(o.shaderMaximalReconvergence);
}
function g_VkPhysicalDeviceShaderSubgroupRotateFeatures_self(w, o)
{
    w.u32(o.shaderSubgroupRotate);
    w.u32(o.shaderSubgroupRotateClustered);
}
function g_VkPhysicalDeviceShaderExpectAssumeFeatures_self(w, o)
{
    w.u32(o.shaderExpectAssume);
}
function g_VkPhysicalDeviceShaderFloatControls2Features_self(w, o)
{
    w.u32(o.shaderFloatControls2);
}
function g_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self(w, o)
{
    w.u32(o.dynamicRenderingLocalRead);
}
function g_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self(w, o)
{
    w.u32(o.shaderQuadControl);
}
function g_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self(w, o)
{
    w.u32(o.shaderBFloat16Type);
    w.u32(o.shaderBFloat16DotProduct);
    w.u32(o.shaderBFloat16CooperativeMatrix);
}
function g_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self(w, o)
{
    w.u32(o.shaderReplicatedComposites);
}
function g_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self(w, o)
{
    w.u32(o.shaderUniformBufferUnsizedArray);
}
function g_VkPhysicalDeviceShaderFloat8FeaturesEXT_self(w, o)
{
    w.u32(o.shaderFloat8);
    w.u32(o.shaderFloat8CooperativeMatrix);
}
function g_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self(w, o)
{
    w.u32(o.shaderUntypedPointers);
}
function g_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self(w, o)
{
    w.u32(o.descriptorHeap);
    w.u32(o.descriptorHeapCaptureReplay);
}
function g_VkDevicePrivateDataCreateInfo_self(w, o)
{
    w.u32(o.privateDataSlotRequestCount);
}
function g_VkPhysicalDeviceFeatures2_self(w, o)
{
    g_VkPhysicalDeviceFeatures(w, o.features || EMPTY);
}
function g_VkDeviceGroupDeviceCreateInfo_self(w, o)
{
    w.u32(o.physicalDeviceCount);
    if(o.pPhysicalDevices)
    {
        w.size(o.physicalDeviceCount);
        for(let i = 0; i < o.physicalDeviceCount; i++)
        {
            w.h((o.pPhysicalDevices || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPhysicalDeviceExternalImageFormatInfo_self(w, o)
{
    w.i32(o.handleType);
}
function g_VkImageFormatListCreateInfo_self(w, o)
{
    w.u32(o.viewFormatCount);
    if(o.pViewFormats)
    {
        w.size(o.viewFormatCount);
        w.i32s(o.pViewFormats, o.viewFormatCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkPhysicalDeviceImageDrmFormatModifierInfoEXT_self(w, o)
{
    w.u64(o.drmFormatModifier);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    if(o.sharingMode === 1)
    {
        w.size(o.queueFamilyIndexCount);
        w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkImageStencilUsageCreateInfo_self(w, o)
{
    w.u32(o.stencilUsage);
}
function g_VkPhysicalDeviceImageViewImageFormatInfoEXT_self(w, o)
{
    w.i32(o.imageViewType);
}
function g_VkSemaphoreTypeCreateInfo_self(w, o)
{
    w.i32(o.semaphoreType);
    w.u64(o.initialValue);
}
function g_VkDeviceQueueTimelineInfoMESA_self(w, o)
{
    w.u32(o.ringIdx);
}
function g_VkExportMemoryAllocateInfo_self(w, o)
{
    w.u32(o.handleTypes);
}
function g_VkMemoryAllocateFlagsInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.deviceMask);
}
function g_VkMemoryDedicatedAllocateInfo_self(w, o)
{
    w.h(o.image);
    w.h(o.buffer);
}
function g_VkMemoryOpaqueCaptureAddressAllocateInfo_self(w, o)
{
    w.u64(o.opaqueCaptureAddress);
}
function g_VkImportMemoryResourceInfoMESA_self(w, o)
{
    w.u32(o.resourceId);
}
function g_VkExportFenceCreateInfo_self(w, o)
{
    w.u32(o.handleTypes);
}
function g_VkFramebufferAttachmentsCreateInfo_self(w, o)
{
    w.u32(o.attachmentImageInfoCount);
    if(o.pAttachmentImageInfos)
    {
        w.size(o.attachmentImageInfoCount);
        for(let i = 0; i < o.attachmentImageInfoCount; i++)
        {
            g_VkFramebufferAttachmentImageInfo(w, (o.pAttachmentImageInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkExternalMemoryImageCreateInfo_self(w, o)
{
    w.u32(o.handleTypes);
}
function g_VkImageDrmFormatModifierListCreateInfoEXT_self(w, o)
{
    w.u32(o.drmFormatModifierCount);
    if(o.pDrmFormatModifiers)
    {
        w.size(o.drmFormatModifierCount);
        w.u64s(o.pDrmFormatModifiers, o.drmFormatModifierCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkImageDrmFormatModifierExplicitCreateInfoEXT_self(w, o)
{
    w.u64(o.drmFormatModifier);
    w.u32(o.drmFormatModifierPlaneCount);
    if(o.pPlaneLayouts)
    {
        w.size(o.drmFormatModifierPlaneCount);
        for(let i = 0; i < o.drmFormatModifierPlaneCount; i++)
        {
            g_VkSubresourceLayout(w, (o.pPlaneLayouts || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkOpaqueCaptureDataCreateInfoEXT_self(w, o)
{
    if(o.pData != null)
    {
        w.u64(1);
        g_VkHostAddressRangeConstEXT(w, o.pData || EMPTY);
    }
    else w.u64(0);
}
function g_VkBindImageMemoryDeviceGroupInfo_self(w, o)
{
    w.u32(o.deviceIndexCount);
    if(o.pDeviceIndices)
    {
        w.size(o.deviceIndexCount);
        w.u32s(o.pDeviceIndices, o.deviceIndexCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.splitInstanceBindRegionCount);
    if(o.pSplitInstanceBindRegions)
    {
        w.size(o.splitInstanceBindRegionCount);
        for(let i = 0; i < o.splitInstanceBindRegionCount; i++)
        {
            g_VkRect2D(w, (o.pSplitInstanceBindRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkBindImagePlaneMemoryInfo_self(w, o)
{
    w.i32(o.planeAspect);
}
function g_VkImagePlaneMemoryRequirementsInfo_self(w, o)
{
    w.i32(o.planeAspect);
}
function g_VkShaderModuleCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u64(o.codeSize);
    if(o.pCode)
    {
        w.size(Math.floor(o.codeSize / 4));
        w.u32s(o.pCode, Math.floor(o.codeSize / 4));
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineShaderStageRequiredSubgroupSizeCreateInfo_self(w, o)
{
    w.u32(o.requiredSubgroupSize);
}
function g_VkPipelineRobustnessCreateInfo_self(w, o)
{
    w.i32(o.storageBuffers);
    w.i32(o.uniformBuffers);
    w.i32(o.vertexInputs);
    w.i32(o.images);
}
function g_VkShaderDescriptorSetAndBindingMappingInfoEXT_self(w, o)
{
    w.u32(o.mappingCount);
    if(o.pMappings)
    {
        w.size(o.mappingCount);
        for(let i = 0; i < o.mappingCount; i++)
        {
            g_VkDescriptorSetAndBindingMappingEXT(w, (o.pMappings || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineVertexInputDivisorStateCreateInfo_self(w, o)
{
    w.u32(o.vertexBindingDivisorCount);
    if(o.pVertexBindingDivisors)
    {
        w.size(o.vertexBindingDivisorCount);
        for(let i = 0; i < o.vertexBindingDivisorCount; i++)
        {
            g_VkVertexInputBindingDivisorDescription(w, (o.pVertexBindingDivisors || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineTessellationDomainOriginStateCreateInfo_self(w, o)
{
    w.i32(o.domainOrigin);
}
function g_VkPipelineViewportDepthClipControlCreateInfoEXT_self(w, o)
{
    w.u32(o.negativeOneToOne);
}
function g_VkPipelineViewportDepthClampControlCreateInfoEXT_self(w, o)
{
    w.i32(o.depthClampMode);
    if(o.pDepthClampRange != null)
    {
        w.u64(1);
        g_VkDepthClampRangeEXT(w, o.pDepthClampRange || EMPTY);
    }
    else w.u64(0);
}
function g_VkPipelineRasterizationConservativeStateCreateInfoEXT_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.conservativeRasterizationMode);
    w.f32(o.extraPrimitiveOverestimationSize);
}
function g_VkPipelineRasterizationStateStreamCreateInfoEXT_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.rasterizationStream);
}
function g_VkPipelineRasterizationDepthClipStateCreateInfoEXT_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.depthClipEnable);
}
function g_VkPipelineRasterizationLineStateCreateInfo_self(w, o)
{
    w.i32(o.lineRasterizationMode);
    w.u32(o.stippledLineEnable);
    w.u32(o.lineStippleFactor);
    w.u16(o.lineStipplePattern);
}
function g_VkPipelineRasterizationProvokingVertexStateCreateInfoEXT_self(w, o)
{
    w.i32(o.provokingVertexMode);
}
function g_VkPipelineSampleLocationsStateCreateInfoEXT_self(w, o)
{
    w.u32(o.sampleLocationsEnable);
    g_VkSampleLocationsInfoEXT(w, o.sampleLocationsInfo || EMPTY);
}
function g_VkPipelineColorBlendAdvancedStateCreateInfoEXT_self(w, o)
{
    w.u32(o.srcPremultiplied);
    w.u32(o.dstPremultiplied);
    w.i32(o.blendOverlap);
}
function g_VkPipelineColorWriteCreateInfoEXT_self(w, o)
{
    w.u32(o.attachmentCount);
    if(o.pColorWriteEnables)
    {
        w.size(o.attachmentCount);
        w.u32s(o.pColorWriteEnables, o.attachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineCreateFlags2CreateInfo_self(w, o)
{
    w.u64(o.flags);
}
function g_VkPipelineLibraryCreateInfoKHR_self(w, o)
{
    w.u32(o.libraryCount);
    if(o.pLibraries)
    {
        w.size(o.libraryCount);
        for(let i = 0; i < o.libraryCount; i++)
        {
            w.h((o.pLibraries || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineCreationFeedbackCreateInfo_self(w, o)
{
    if(o.pPipelineCreationFeedback != null)
    {
        w.u64(1);
        g_VkPipelineCreationFeedback(w, o.pPipelineCreationFeedback || EMPTY);
    }
    else w.u64(0);
    w.u32(o.pipelineStageCreationFeedbackCount);
    if(o.pPipelineStageCreationFeedbacks)
    {
        w.size(o.pipelineStageCreationFeedbackCount);
        for(let i = 0; i < o.pipelineStageCreationFeedbackCount; i++)
        {
            g_VkPipelineCreationFeedback(w, (o.pPipelineStageCreationFeedbacks || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineFragmentShadingRateStateCreateInfoKHR_self(w, o)
{
    g_VkExtent2D(w, o.fragmentSize || EMPTY);
    w.size(2);
    w.i32s(o.combinerOps, 2);
}
function g_VkPipelineRenderingCreateInfo_self(w, o)
{
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachmentFormats)
    {
        w.size(o.colorAttachmentCount);
        w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    }
    else
    {
        w.size(0);
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
}
function g_VkGraphicsPipelineLibraryCreateInfoEXT_self(w, o)
{
    w.u32(o.flags);
}
function g_VkDeviceGroupSubmitInfo_self(w, o)
{
    w.u32(o.waitSemaphoreCount);
    if(o.pWaitSemaphoreDeviceIndices)
    {
        w.size(o.waitSemaphoreCount);
        w.u32s(o.pWaitSemaphoreDeviceIndices, o.waitSemaphoreCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.commandBufferCount);
    if(o.pCommandBufferDeviceMasks)
    {
        w.size(o.commandBufferCount);
        w.u32s(o.pCommandBufferDeviceMasks, o.commandBufferCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.signalSemaphoreCount);
    if(o.pSignalSemaphoreDeviceIndices)
    {
        w.size(o.signalSemaphoreCount);
        w.u32s(o.pSignalSemaphoreDeviceIndices, o.signalSemaphoreCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkProtectedSubmitInfo_self(w, o)
{
    w.u32(o.protectedSubmit);
}
function g_VkTimelineSemaphoreSubmitInfo_self(w, o)
{
    w.u32(o.waitSemaphoreValueCount);
    if(o.pWaitSemaphoreValues)
    {
        w.size(o.waitSemaphoreValueCount);
        w.u64s(o.pWaitSemaphoreValues, o.waitSemaphoreValueCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.signalSemaphoreValueCount);
    if(o.pSignalSemaphoreValues)
    {
        w.size(o.signalSemaphoreValueCount);
        w.u64s(o.pSignalSemaphoreValues, o.signalSemaphoreValueCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkDeviceGroupBindSparseInfo_self(w, o)
{
    w.u32(o.resourceDeviceIndex);
    w.u32(o.memoryDeviceIndex);
}
function g_VkRenderPassMultiviewCreateInfo_self(w, o)
{
    w.u32(o.subpassCount);
    if(o.pViewMasks)
    {
        w.size(o.subpassCount);
        w.u32s(o.pViewMasks, o.subpassCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.dependencyCount);
    if(o.pViewOffsets)
    {
        w.size(o.dependencyCount);
        w.i32s(o.pViewOffsets, o.dependencyCount);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.correlationMaskCount);
    if(o.pCorrelationMasks)
    {
        w.size(o.correlationMaskCount);
        w.u32s(o.pCorrelationMasks, o.correlationMaskCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkRenderPassInputAttachmentAspectCreateInfo_self(w, o)
{
    w.u32(o.aspectReferenceCount);
    if(o.pAspectReferences)
    {
        w.size(o.aspectReferenceCount);
        for(let i = 0; i < o.aspectReferenceCount; i++)
        {
            g_VkInputAttachmentAspectReference(w, (o.pAspectReferences || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkAttachmentDescriptionStencilLayout_self(w, o)
{
    w.i32(o.stencilInitialLayout);
    w.i32(o.stencilFinalLayout);
}
function g_VkAttachmentReferenceStencilLayout_self(w, o)
{
    w.i32(o.stencilLayout);
}
function g_VkSubpassDescriptionDepthStencilResolve_self(w, o)
{
    w.i32(o.depthResolveMode);
    w.i32(o.stencilResolveMode);
    if(o.pDepthStencilResolveAttachment != null)
    {
        w.u64(1);
        g_VkAttachmentReference2(w, o.pDepthStencilResolveAttachment || EMPTY);
    }
    else w.u64(0);
}
function g_VkFragmentShadingRateAttachmentInfoKHR_self(w, o)
{
    if(o.pFragmentShadingRateAttachment != null)
    {
        w.u64(1);
        g_VkAttachmentReference2(w, o.pFragmentShadingRateAttachment || EMPTY);
    }
    else w.u64(0);
    g_VkExtent2D(w, o.shadingRateAttachmentTexelSize || EMPTY);
}
function g_VkMemoryBarrier2_self(w, o)
{
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
}
function g_VkExportSemaphoreCreateInfo_self(w, o)
{
    w.u32(o.handleTypes);
}
function g_VkImageViewUsageCreateInfo_self(w, o)
{
    w.u32(o.usage);
}
function g_VkImageViewSlicedCreateInfoEXT_self(w, o)
{
    w.u32(o.sliceOffset);
    w.u32(o.sliceCount);
}
function g_VkSamplerYcbcrConversionInfo_self(w, o)
{
    w.h(o.conversion);
}
function g_VkImageViewMinLodCreateInfoEXT_self(w, o)
{
    w.f32(o.minLod);
}
function g_VkSamplerReductionModeCreateInfo_self(w, o)
{
    w.i32(o.reductionMode);
}
function g_VkSamplerCustomBorderColorCreateInfoEXT_self(w, o)
{
    g_VkClearColorValue(w, o.customBorderColor || EMPTY);
    w.i32(o.format);
}
function g_VkSamplerBorderColorComponentMappingCreateInfoEXT_self(w, o)
{
    g_VkComponentMapping(w, o.components || EMPTY);
    w.u32(o.srgb);
}
function g_VkSamplerCustomBorderColorIndexCreateInfoEXT_self(w, o)
{
    w.u32(o.index);
}
function g_VkWriteDescriptorSetInlineUniformBlock_self(w, o)
{
    w.u32(o.dataSize);
    if(o.pData)
    {
        w.size(o.dataSize);
        w.blob(o.pData, o.dataSize);
    }
    else
    {
        w.size(0);
    }
}
function g_VkWriteDescriptorSetAccelerationStructureKHR_self(w, o)
{
    w.u32(o.accelerationStructureCount);
    if(o.pAccelerationStructures)
    {
        w.size(o.accelerationStructureCount);
        for(let i = 0; i < o.accelerationStructureCount; i++)
        {
            w.h((o.pAccelerationStructures || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkRingMonitorInfoMESA_self(w, o)
{
    w.u32(o.maxReportingPeriodMicroseconds);
}
function g_VkRingPriorityInfoMESA_self(w, o)
{
    w.i32(o.priority);
}
function g_VkDescriptorSetVariableDescriptorCountLayoutSupport_self_partial(w, o)
{
}
function g_VkPhysicalDevicePrivateDataFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVariablePointersFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMultiviewFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDevice16BitStorageFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceProtectedMemoryFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMultiDrawFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceInlineUniformBlockFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance4Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance5Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance6Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance7FeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderDrawParametersFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderFloat16Int8Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceHostQueryResetFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceGlobalPriorityQueryFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDescriptorIndexingFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTimelineSemaphoreFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDevice8BitStorageFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkanMemoryModelFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderAtomicInt64Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVertexAttributeDivisorFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMeshShaderFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRayQueryFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceScalarBlockLayoutFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceBufferDeviceAddressFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceImagelessFramebufferFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderClockFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceIndexTypeUint8Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSubgroupSizeControlFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceLineRasterizationFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDevicePipelineCreationCacheControlFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan11Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan12Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan13Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan14Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRobustness2FeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceImageRobustnessFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDevice4444FormatsFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderTerminateInvocationFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthClipControlFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthClampControlFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSynchronization2Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceHostImageCopyFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDevicePipelineProtectedAccessFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceProvokingVertexFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderIntegerDotProductFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderFmaFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDynamicRenderingFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDevicePipelineRobustnessFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderSubgroupRotateFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderExpectAssumeFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderFloatControls2Features_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderFloat8FeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMultiDrawPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDevicePushDescriptorProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDriverProperties_self_partial(w, o)
{
    g_VkConformanceVersion_partial(w, o.conformanceVersion || EMPTY);
}
function g_VkPhysicalDeviceIDProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMultiviewProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSubgroupProperties_self_partial(w, o)
{
}
function g_VkPhysicalDevicePointClippingProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceProtectedMemoryProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSamplerFilterMinmaxProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSampleLocationsPropertiesEXT_self_partial(w, o)
{
    g_VkExtent2D_partial(w, o.maxSampleLocationGridSize || EMPTY);
}
function g_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceInlineUniformBlockProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance3Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance4Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance5Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance6Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMaintenance7PropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFloatControlsProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDescriptorIndexingProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTimelineSemaphoreProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVertexAttributeDivisorProperties_self_partial(w, o)
{
}
function g_VkPhysicalDevicePCIBusInfoPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDepthStencilResolveProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMeshShaderPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceTexelBufferAlignmentProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceSubgroupSizeControlProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceLineRasterizationProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan11Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan12Properties_self_partial(w, o)
{
    g_VkConformanceVersion_partial(w, o.conformanceVersion || EMPTY);
}
function g_VkPhysicalDeviceVulkan13Properties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceVulkan14Properties_self_partial(w, o)
{
    w.u32(o.copySrcLayoutCount);
    w.size(o.pCopySrcLayouts ? o.copySrcLayoutCount : 0);
    w.u32(o.copyDstLayoutCount);
    w.size(o.pCopyDstLayouts ? o.copyDstLayoutCount : 0);
}
function g_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceRobustness2PropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self_partial(w, o)
{
    g_VkExtent2D_partial(w, o.minFragmentShadingRateAttachmentTexelSize || EMPTY);
    g_VkExtent2D_partial(w, o.maxFragmentShadingRateAttachmentTexelSize || EMPTY);
    g_VkExtent2D_partial(w, o.maxFragmentSize || EMPTY);
}
function g_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceHostImageCopyProperties_self_partial(w, o)
{
    w.u32(o.copySrcLayoutCount);
    w.size(o.pCopySrcLayouts ? o.copySrcLayoutCount : 0);
    w.u32(o.copyDstLayoutCount);
    w.size(o.pCopyDstLayouts ? o.copyDstLayoutCount : 0);
}
function g_VkPhysicalDeviceProvokingVertexPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceShaderIntegerDotProductProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self_partial(w, o)
{
}
function g_VkPhysicalDevicePipelineRobustnessProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self_partial(w, o)
{
}
function g_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self_partial(w, o)
{
}
function g_VkDrmFormatModifierPropertiesListEXT_self_partial(w, o)
{
    w.u32(o.drmFormatModifierCount);
    if(o.pDrmFormatModifierProperties)
    {
        w.size(o.drmFormatModifierCount);
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            g_VkDrmFormatModifierPropertiesEXT_partial(w, (o.pDrmFormatModifierProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkSubpassResolvePerformanceQueryEXT_self_partial(w, o)
{
}
function g_VkFormatProperties3_self_partial(w, o)
{
}
function g_VkDrmFormatModifierPropertiesList2EXT_self_partial(w, o)
{
    w.u32(o.drmFormatModifierCount);
    if(o.pDrmFormatModifierProperties)
    {
        w.size(o.drmFormatModifierCount);
        for(let i = 0; i < o.drmFormatModifierCount; i++)
        {
            g_VkDrmFormatModifierProperties2EXT_partial(w, (o.pDrmFormatModifierProperties || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkExternalImageFormatProperties_self_partial(w, o)
{
    g_VkExternalMemoryProperties_partial(w, o.externalMemoryProperties || EMPTY);
}
function g_VkSamplerYcbcrConversionImageFormatProperties_self_partial(w, o)
{
}
function g_VkFilterCubicImageViewImageFormatPropertiesEXT_self_partial(w, o)
{
}
function g_VkHostImageCopyDevicePerformanceQuery_self_partial(w, o)
{
}
function g_VkQueueFamilyGlobalPriorityProperties_self_partial(w, o)
{
}
function g_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self_partial(w, o)
{
}
function g_VkMemoryResourceAllocationSizePropertiesMESA_self_partial(w, o)
{
}
function g_VkSubresourceHostMemcpySize_self_partial(w, o)
{
}
function g_VkMemoryDedicatedRequirements_self_partial(w, o)
{
}
function h_VkDescriptorSetVariableDescriptorCountLayoutSupport_self(r, o)
{
    o.maxVariableDescriptorCount = r.u32();
}
function h_VkPhysicalDevicePrivateDataFeatures_self(r, o)
{
    o.privateData = r.u32();
}
function h_VkPhysicalDeviceVariablePointersFeatures_self(r, o)
{
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
}
function h_VkPhysicalDeviceMultiviewFeatures_self(r, o)
{
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
}
function h_VkPhysicalDevice16BitStorageFeatures_self(r, o)
{
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
}
function h_VkPhysicalDeviceShaderSubgroupExtendedTypesFeatures_self(r, o)
{
    o.shaderSubgroupExtendedTypes = r.u32();
}
function h_VkPhysicalDeviceSamplerYcbcrConversionFeatures_self(r, o)
{
    o.samplerYcbcrConversion = r.u32();
}
function h_VkPhysicalDeviceProtectedMemoryFeatures_self(r, o)
{
    o.protectedMemory = r.u32();
}
function h_VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT_self(r, o)
{
    o.advancedBlendCoherentOperations = r.u32();
}
function h_VkPhysicalDeviceMultiDrawFeaturesEXT_self(r, o)
{
    o.multiDraw = r.u32();
}
function h_VkPhysicalDeviceInlineUniformBlockFeatures_self(r, o)
{
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
}
function h_VkPhysicalDeviceMaintenance4Features_self(r, o)
{
    o.maintenance4 = r.u32();
}
function h_VkPhysicalDeviceMaintenance5Features_self(r, o)
{
    o.maintenance5 = r.u32();
}
function h_VkPhysicalDeviceMaintenance6Features_self(r, o)
{
    o.maintenance6 = r.u32();
}
function h_VkPhysicalDeviceMaintenance7FeaturesKHR_self(r, o)
{
    o.maintenance7 = r.u32();
}
function h_VkPhysicalDeviceShaderDrawParametersFeatures_self(r, o)
{
    o.shaderDrawParameters = r.u32();
}
function h_VkPhysicalDeviceShaderFloat16Int8Features_self(r, o)
{
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
}
function h_VkPhysicalDeviceHostQueryResetFeatures_self(r, o)
{
    o.hostQueryReset = r.u32();
}
function h_VkPhysicalDeviceGlobalPriorityQueryFeatures_self(r, o)
{
    o.globalPriorityQuery = r.u32();
}
function h_VkPhysicalDeviceDescriptorIndexingFeatures_self(r, o)
{
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
}
function h_VkPhysicalDeviceTimelineSemaphoreFeatures_self(r, o)
{
    o.timelineSemaphore = r.u32();
}
function h_VkPhysicalDevice8BitStorageFeatures_self(r, o)
{
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
}
function h_VkPhysicalDeviceConditionalRenderingFeaturesEXT_self(r, o)
{
    o.conditionalRendering = r.u32();
    o.inheritedConditionalRendering = r.u32();
}
function h_VkPhysicalDeviceVulkanMemoryModelFeatures_self(r, o)
{
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
}
function h_VkPhysicalDeviceShaderAtomicInt64Features_self(r, o)
{
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
}
function h_VkPhysicalDeviceShaderAtomicFloatFeaturesEXT_self(r, o)
{
    o.shaderBufferFloat32Atomics = r.u32();
    o.shaderBufferFloat32AtomicAdd = r.u32();
    o.shaderBufferFloat64Atomics = r.u32();
    o.shaderBufferFloat64AtomicAdd = r.u32();
    o.shaderSharedFloat32Atomics = r.u32();
    o.shaderSharedFloat32AtomicAdd = r.u32();
    o.shaderSharedFloat64Atomics = r.u32();
    o.shaderSharedFloat64AtomicAdd = r.u32();
    o.shaderImageFloat32Atomics = r.u32();
    o.shaderImageFloat32AtomicAdd = r.u32();
    o.sparseImageFloat32Atomics = r.u32();
    o.sparseImageFloat32AtomicAdd = r.u32();
}
function h_VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT_self(r, o)
{
    o.shaderBufferFloat16Atomics = r.u32();
    o.shaderBufferFloat16AtomicAdd = r.u32();
    o.shaderBufferFloat16AtomicMinMax = r.u32();
    o.shaderBufferFloat32AtomicMinMax = r.u32();
    o.shaderBufferFloat64AtomicMinMax = r.u32();
    o.shaderSharedFloat16Atomics = r.u32();
    o.shaderSharedFloat16AtomicAdd = r.u32();
    o.shaderSharedFloat16AtomicMinMax = r.u32();
    o.shaderSharedFloat32AtomicMinMax = r.u32();
    o.shaderSharedFloat64AtomicMinMax = r.u32();
    o.shaderImageFloat32AtomicMinMax = r.u32();
    o.sparseImageFloat32AtomicMinMax = r.u32();
}
function h_VkPhysicalDeviceVertexAttributeDivisorFeatures_self(r, o)
{
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
}
function h_VkPhysicalDeviceTransformFeedbackFeaturesEXT_self(r, o)
{
    o.transformFeedback = r.u32();
    o.geometryStreams = r.u32();
}
function h_VkPhysicalDeviceComputeShaderDerivativesFeaturesKHR_self(r, o)
{
    o.computeDerivativeGroupQuads = r.u32();
    o.computeDerivativeGroupLinear = r.u32();
}
function h_VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR_self(r, o)
{
    o.fragmentShaderBarycentric = r.u32();
}
function h_VkPhysicalDeviceMeshShaderFeaturesEXT_self(r, o)
{
    o.taskShader = r.u32();
    o.meshShader = r.u32();
    o.multiviewMeshShader = r.u32();
    o.primitiveFragmentShadingRateMeshShader = r.u32();
    o.meshShaderQueries = r.u32();
}
function h_VkPhysicalDeviceAccelerationStructureFeaturesKHR_self(r, o)
{
    o.accelerationStructure = r.u32();
    o.accelerationStructureCaptureReplay = r.u32();
    o.accelerationStructureIndirectBuild = r.u32();
    o.accelerationStructureHostCommands = r.u32();
    o.descriptorBindingAccelerationStructureUpdateAfterBind = r.u32();
}
function h_VkPhysicalDeviceRayTracingPipelineFeaturesKHR_self(r, o)
{
    o.rayTracingPipeline = r.u32();
    o.rayTracingPipelineShaderGroupHandleCaptureReplay = r.u32();
    o.rayTracingPipelineShaderGroupHandleCaptureReplayMixed = r.u32();
    o.rayTracingPipelineTraceRaysIndirect = r.u32();
    o.rayTraversalPrimitiveCulling = r.u32();
}
function h_VkPhysicalDeviceRayQueryFeaturesKHR_self(r, o)
{
    o.rayQuery = r.u32();
}
function h_VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR_self(r, o)
{
    o.rayTracingMaintenance1 = r.u32();
    o.rayTracingPipelineTraceRaysIndirect2 = r.u32();
}
function h_VkPhysicalDeviceScalarBlockLayoutFeatures_self(r, o)
{
    o.scalarBlockLayout = r.u32();
}
function h_VkPhysicalDeviceUniformBufferStandardLayoutFeatures_self(r, o)
{
    o.uniformBufferStandardLayout = r.u32();
}
function h_VkPhysicalDeviceDepthClipEnableFeaturesEXT_self(r, o)
{
    o.depthClipEnable = r.u32();
}
function h_VkPhysicalDeviceBufferDeviceAddressFeatures_self(r, o)
{
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
}
function h_VkPhysicalDeviceBufferDeviceAddressFeaturesEXT_self(r, o)
{
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
}
function h_VkPhysicalDeviceImagelessFramebufferFeatures_self(r, o)
{
    o.imagelessFramebuffer = r.u32();
}
function h_VkPhysicalDeviceTextureCompressionASTCHDRFeatures_self(r, o)
{
    o.textureCompressionASTC_HDR = r.u32();
}
function h_VkPhysicalDeviceYcbcrImageArraysFeaturesEXT_self(r, o)
{
    o.ycbcrImageArrays = r.u32();
}
function h_VkPhysicalDeviceShaderClockFeaturesKHR_self(r, o)
{
    o.shaderSubgroupClock = r.u32();
    o.shaderDeviceClock = r.u32();
}
function h_VkPhysicalDeviceIndexTypeUint8Features_self(r, o)
{
    o.indexTypeUint8 = r.u32();
}
function h_VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT_self(r, o)
{
    o.fragmentShaderSampleInterlock = r.u32();
    o.fragmentShaderPixelInterlock = r.u32();
    o.fragmentShaderShadingRateInterlock = r.u32();
}
function h_VkPhysicalDeviceSeparateDepthStencilLayoutsFeatures_self(r, o)
{
    o.separateDepthStencilLayouts = r.u32();
}
function h_VkPhysicalDevicePrimitiveTopologyListRestartFeaturesEXT_self(r, o)
{
    o.primitiveTopologyListRestart = r.u32();
    o.primitiveTopologyPatchListRestart = r.u32();
}
function h_VkPhysicalDeviceShaderDemoteToHelperInvocationFeatures_self(r, o)
{
    o.shaderDemoteToHelperInvocation = r.u32();
}
function h_VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT_self(r, o)
{
    o.texelBufferAlignment = r.u32();
}
function h_VkPhysicalDeviceSubgroupSizeControlFeatures_self(r, o)
{
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
}
function h_VkPhysicalDeviceLineRasterizationFeatures_self(r, o)
{
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
}
function h_VkPhysicalDevicePipelineCreationCacheControlFeatures_self(r, o)
{
    o.pipelineCreationCacheControl = r.u32();
}
function h_VkPhysicalDeviceVulkan11Features_self(r, o)
{
    o.storageBuffer16BitAccess = r.u32();
    o.uniformAndStorageBuffer16BitAccess = r.u32();
    o.storagePushConstant16 = r.u32();
    o.storageInputOutput16 = r.u32();
    o.multiview = r.u32();
    o.multiviewGeometryShader = r.u32();
    o.multiviewTessellationShader = r.u32();
    o.variablePointersStorageBuffer = r.u32();
    o.variablePointers = r.u32();
    o.protectedMemory = r.u32();
    o.samplerYcbcrConversion = r.u32();
    o.shaderDrawParameters = r.u32();
}
function h_VkPhysicalDeviceVulkan12Features_self(r, o)
{
    o.samplerMirrorClampToEdge = r.u32();
    o.drawIndirectCount = r.u32();
    o.storageBuffer8BitAccess = r.u32();
    o.uniformAndStorageBuffer8BitAccess = r.u32();
    o.storagePushConstant8 = r.u32();
    o.shaderBufferInt64Atomics = r.u32();
    o.shaderSharedInt64Atomics = r.u32();
    o.shaderFloat16 = r.u32();
    o.shaderInt8 = r.u32();
    o.descriptorIndexing = r.u32();
    o.shaderInputAttachmentArrayDynamicIndexing = r.u32();
    o.shaderUniformTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageTexelBufferArrayDynamicIndexing = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexing = r.u32();
    o.shaderSampledImageArrayNonUniformIndexing = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageImageArrayNonUniformIndexing = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexing = r.u32();
    o.shaderUniformTexelBufferArrayNonUniformIndexing = r.u32();
    o.shaderStorageTexelBufferArrayNonUniformIndexing = r.u32();
    o.descriptorBindingUniformBufferUpdateAfterBind = r.u32();
    o.descriptorBindingSampledImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageImageUpdateAfterBind = r.u32();
    o.descriptorBindingStorageBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUniformTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingStorageTexelBufferUpdateAfterBind = r.u32();
    o.descriptorBindingUpdateUnusedWhilePending = r.u32();
    o.descriptorBindingPartiallyBound = r.u32();
    o.descriptorBindingVariableDescriptorCount = r.u32();
    o.runtimeDescriptorArray = r.u32();
    o.samplerFilterMinmax = r.u32();
    o.scalarBlockLayout = r.u32();
    o.imagelessFramebuffer = r.u32();
    o.uniformBufferStandardLayout = r.u32();
    o.shaderSubgroupExtendedTypes = r.u32();
    o.separateDepthStencilLayouts = r.u32();
    o.hostQueryReset = r.u32();
    o.timelineSemaphore = r.u32();
    o.bufferDeviceAddress = r.u32();
    o.bufferDeviceAddressCaptureReplay = r.u32();
    o.bufferDeviceAddressMultiDevice = r.u32();
    o.vulkanMemoryModel = r.u32();
    o.vulkanMemoryModelDeviceScope = r.u32();
    o.vulkanMemoryModelAvailabilityVisibilityChains = r.u32();
    o.shaderOutputViewportIndex = r.u32();
    o.shaderOutputLayer = r.u32();
    o.subgroupBroadcastDynamicId = r.u32();
}
function h_VkPhysicalDeviceVulkan13Features_self(r, o)
{
    o.robustImageAccess = r.u32();
    o.inlineUniformBlock = r.u32();
    o.descriptorBindingInlineUniformBlockUpdateAfterBind = r.u32();
    o.pipelineCreationCacheControl = r.u32();
    o.privateData = r.u32();
    o.shaderDemoteToHelperInvocation = r.u32();
    o.shaderTerminateInvocation = r.u32();
    o.subgroupSizeControl = r.u32();
    o.computeFullSubgroups = r.u32();
    o.synchronization2 = r.u32();
    o.textureCompressionASTC_HDR = r.u32();
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
    o.dynamicRendering = r.u32();
    o.shaderIntegerDotProduct = r.u32();
    o.maintenance4 = r.u32();
}
function h_VkPhysicalDeviceVulkan14Features_self(r, o)
{
    o.globalPriorityQuery = r.u32();
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
    o.shaderFloatControls2 = r.u32();
    o.shaderExpectAssume = r.u32();
    o.rectangularLines = r.u32();
    o.bresenhamLines = r.u32();
    o.smoothLines = r.u32();
    o.stippledRectangularLines = r.u32();
    o.stippledBresenhamLines = r.u32();
    o.stippledSmoothLines = r.u32();
    o.vertexAttributeInstanceRateDivisor = r.u32();
    o.vertexAttributeInstanceRateZeroDivisor = r.u32();
    o.indexTypeUint8 = r.u32();
    o.dynamicRenderingLocalRead = r.u32();
    o.maintenance5 = r.u32();
    o.maintenance6 = r.u32();
    o.pipelineProtectedAccess = r.u32();
    o.pipelineRobustness = r.u32();
    o.hostImageCopy = r.u32();
    o.pushDescriptor = r.u32();
}
function h_VkPhysicalDeviceCustomBorderColorFeaturesEXT_self(r, o)
{
    o.customBorderColors = r.u32();
    o.customBorderColorWithoutFormat = r.u32();
}
function h_VkPhysicalDeviceBorderColorSwizzleFeaturesEXT_self(r, o)
{
    o.borderColorSwizzle = r.u32();
    o.borderColorSwizzleFromImage = r.u32();
}
function h_VkPhysicalDeviceExtendedDynamicStateFeaturesEXT_self(r, o)
{
    o.extendedDynamicState = r.u32();
}
function h_VkPhysicalDeviceExtendedDynamicState2FeaturesEXT_self(r, o)
{
    o.extendedDynamicState2 = r.u32();
    o.extendedDynamicState2LogicOp = r.u32();
    o.extendedDynamicState2PatchControlPoints = r.u32();
}
function h_VkPhysicalDeviceExtendedDynamicState3FeaturesEXT_self(r, o)
{
    o.extendedDynamicState3TessellationDomainOrigin = r.u32();
    o.extendedDynamicState3DepthClampEnable = r.u32();
    o.extendedDynamicState3PolygonMode = r.u32();
    o.extendedDynamicState3RasterizationSamples = r.u32();
    o.extendedDynamicState3SampleMask = r.u32();
    o.extendedDynamicState3AlphaToCoverageEnable = r.u32();
    o.extendedDynamicState3AlphaToOneEnable = r.u32();
    o.extendedDynamicState3LogicOpEnable = r.u32();
    o.extendedDynamicState3ColorBlendEnable = r.u32();
    o.extendedDynamicState3ColorBlendEquation = r.u32();
    o.extendedDynamicState3ColorWriteMask = r.u32();
    o.extendedDynamicState3RasterizationStream = r.u32();
    o.extendedDynamicState3ConservativeRasterizationMode = r.u32();
    o.extendedDynamicState3ExtraPrimitiveOverestimationSize = r.u32();
    o.extendedDynamicState3DepthClipEnable = r.u32();
    o.extendedDynamicState3SampleLocationsEnable = r.u32();
    o.extendedDynamicState3ColorBlendAdvanced = r.u32();
    o.extendedDynamicState3ProvokingVertexMode = r.u32();
    o.extendedDynamicState3LineRasterizationMode = r.u32();
    o.extendedDynamicState3LineStippleEnable = r.u32();
    o.extendedDynamicState3DepthClipNegativeOneToOne = r.u32();
    o.extendedDynamicState3ViewportWScalingEnable = r.u32();
    o.extendedDynamicState3ViewportSwizzle = r.u32();
    o.extendedDynamicState3CoverageToColorEnable = r.u32();
    o.extendedDynamicState3CoverageToColorLocation = r.u32();
    o.extendedDynamicState3CoverageModulationMode = r.u32();
    o.extendedDynamicState3CoverageModulationTableEnable = r.u32();
    o.extendedDynamicState3CoverageModulationTable = r.u32();
    o.extendedDynamicState3CoverageReductionMode = r.u32();
    o.extendedDynamicState3RepresentativeFragmentTestEnable = r.u32();
    o.extendedDynamicState3ShadingRateImageEnable = r.u32();
}
function h_VkPhysicalDeviceZeroInitializeWorkgroupMemoryFeatures_self(r, o)
{
    o.shaderZeroInitializeWorkgroupMemory = r.u32();
}
function h_VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR_self(r, o)
{
    o.shaderSubgroupUniformControlFlow = r.u32();
}
function h_VkPhysicalDeviceRobustness2FeaturesKHR_self(r, o)
{
    o.robustBufferAccess2 = r.u32();
    o.robustImageAccess2 = r.u32();
    o.nullDescriptor = r.u32();
}
function h_VkPhysicalDeviceImageRobustnessFeatures_self(r, o)
{
    o.robustImageAccess = r.u32();
}
function h_VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR_self(r, o)
{
    o.workgroupMemoryExplicitLayout = r.u32();
    o.workgroupMemoryExplicitLayoutScalarBlockLayout = r.u32();
    o.workgroupMemoryExplicitLayout8BitAccess = r.u32();
    o.workgroupMemoryExplicitLayout16BitAccess = r.u32();
}
function h_VkPhysicalDevice4444FormatsFeaturesEXT_self(r, o)
{
    o.formatA4R4G4B4 = r.u32();
    o.formatA4B4G4R4 = r.u32();
}
function h_VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT_self(r, o)
{
    o.shaderImageInt64Atomics = r.u32();
    o.sparseImageInt64Atomics = r.u32();
}
function h_VkPhysicalDeviceFragmentShadingRateFeaturesKHR_self(r, o)
{
    o.pipelineFragmentShadingRate = r.u32();
    o.primitiveFragmentShadingRate = r.u32();
    o.attachmentFragmentShadingRate = r.u32();
}
function h_VkPhysicalDeviceShaderTerminateInvocationFeatures_self(r, o)
{
    o.shaderTerminateInvocation = r.u32();
}
function h_VkPhysicalDeviceImage2DViewOf3DFeaturesEXT_self(r, o)
{
    o.image2DViewOf3D = r.u32();
    o.sampler2DViewOf3D = r.u32();
}
function h_VkPhysicalDeviceImageSlicedViewOf3DFeaturesEXT_self(r, o)
{
    o.imageSlicedViewOf3D = r.u32();
}
function h_VkPhysicalDeviceAttachmentFeedbackLoopDynamicStateFeaturesEXT_self(r, o)
{
    o.attachmentFeedbackLoopDynamicState = r.u32();
}
function h_VkPhysicalDeviceLegacyVertexAttributesFeaturesEXT_self(r, o)
{
    o.legacyVertexAttributes = r.u32();
}
function h_VkPhysicalDeviceMutableDescriptorTypeFeaturesEXT_self(r, o)
{
    o.mutableDescriptorType = r.u32();
}
function h_VkPhysicalDeviceDepthClipControlFeaturesEXT_self(r, o)
{
    o.depthClipControl = r.u32();
}
function h_VkPhysicalDeviceDepthClampControlFeaturesEXT_self(r, o)
{
    o.depthClampControl = r.u32();
}
function h_VkPhysicalDeviceVertexInputDynamicStateFeaturesEXT_self(r, o)
{
    o.vertexInputDynamicState = r.u32();
}
function h_VkPhysicalDeviceShaderRelaxedExtendedInstructionFeaturesKHR_self(r, o)
{
    o.shaderRelaxedExtendedInstruction = r.u32();
}
function h_VkPhysicalDeviceColorWriteEnableFeaturesEXT_self(r, o)
{
    o.colorWriteEnable = r.u32();
}
function h_VkPhysicalDeviceSynchronization2Features_self(r, o)
{
    o.synchronization2 = r.u32();
}
function h_VkPhysicalDeviceHostImageCopyFeatures_self(r, o)
{
    o.hostImageCopy = r.u32();
}
function h_VkPhysicalDevicePrimitivesGeneratedQueryFeaturesEXT_self(r, o)
{
    o.primitivesGeneratedQuery = r.u32();
    o.primitivesGeneratedQueryWithRasterizerDiscard = r.u32();
    o.primitivesGeneratedQueryWithNonZeroStreams = r.u32();
}
function h_VkPhysicalDeviceLegacyDitheringFeaturesEXT_self(r, o)
{
    o.legacyDithering = r.u32();
}
function h_VkPhysicalDeviceMultisampledRenderToSingleSampledFeaturesEXT_self(r, o)
{
    o.multisampledRenderToSingleSampled = r.u32();
}
function h_VkPhysicalDevicePipelineProtectedAccessFeatures_self(r, o)
{
    o.pipelineProtectedAccess = r.u32();
}
function h_VkPhysicalDeviceYcbcr2Plane444FormatsFeaturesEXT_self(r, o)
{
    o.ycbcr2plane444Formats = r.u32();
}
function h_VkPhysicalDeviceProvokingVertexFeaturesEXT_self(r, o)
{
    o.provokingVertexLast = r.u32();
    o.transformFeedbackPreservesProvokingVertex = r.u32();
}
function h_VkPhysicalDeviceShaderIntegerDotProductFeatures_self(r, o)
{
    o.shaderIntegerDotProduct = r.u32();
}
function h_VkPhysicalDeviceShaderFmaFeaturesKHR_self(r, o)
{
    o.shaderFmaFloat16 = r.u32();
    o.shaderFmaFloat32 = r.u32();
    o.shaderFmaFloat64 = r.u32();
}
function h_VkPhysicalDeviceDynamicRenderingFeatures_self(r, o)
{
    o.dynamicRendering = r.u32();
}
function h_VkPhysicalDeviceImageViewMinLodFeaturesEXT_self(r, o)
{
    o.minLod = r.u32();
}
function h_VkPhysicalDeviceRasterizationOrderAttachmentAccessFeaturesEXT_self(r, o)
{
    o.rasterizationOrderColorAttachmentAccess = r.u32();
    o.rasterizationOrderDepthAttachmentAccess = r.u32();
    o.rasterizationOrderStencilAttachmentAccess = r.u32();
}
function h_VkPhysicalDeviceGraphicsPipelineLibraryFeaturesEXT_self(r, o)
{
    o.graphicsPipelineLibrary = r.u32();
}
function h_VkPhysicalDeviceNestedCommandBufferFeaturesEXT_self(r, o)
{
    o.nestedCommandBuffer = r.u32();
    o.nestedCommandBufferRendering = r.u32();
    o.nestedCommandBufferSimultaneousUse = r.u32();
}
function h_VkPhysicalDeviceNonSeamlessCubeMapFeaturesEXT_self(r, o)
{
    o.nonSeamlessCubeMap = r.u32();
}
function h_VkPhysicalDevicePipelineRobustnessFeatures_self(r, o)
{
    o.pipelineRobustness = r.u32();
}
function h_VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT_self(r, o)
{
    o.attachmentFeedbackLoopLayout = r.u32();
}
function h_VkPhysicalDeviceDepthClampZeroOneFeaturesKHR_self(r, o)
{
    o.depthClampZeroOne = r.u32();
}
function h_VkPhysicalDevicePipelineLibraryGroupHandlesFeaturesEXT_self(r, o)
{
    o.pipelineLibraryGroupHandles = r.u32();
}
function h_VkPhysicalDeviceDynamicRenderingUnusedAttachmentsFeaturesEXT_self(r, o)
{
    o.dynamicRenderingUnusedAttachments = r.u32();
}
function h_VkPhysicalDeviceDepthBiasControlFeaturesEXT_self(r, o)
{
    o.depthBiasControl = r.u32();
    o.leastRepresentableValueForceUnormRepresentation = r.u32();
    o.floatRepresentation = r.u32();
    o.depthBiasExact = r.u32();
}
function h_VkPhysicalDeviceRayTracingPositionFetchFeaturesKHR_self(r, o)
{
    o.rayTracingPositionFetch = r.u32();
}
function h_VkPhysicalDeviceCooperativeMatrixFeaturesKHR_self(r, o)
{
    o.cooperativeMatrix = r.u32();
    o.cooperativeMatrixRobustBufferAccess = r.u32();
}
function h_VkPhysicalDeviceShaderMaximalReconvergenceFeaturesKHR_self(r, o)
{
    o.shaderMaximalReconvergence = r.u32();
}
function h_VkPhysicalDeviceShaderSubgroupRotateFeatures_self(r, o)
{
    o.shaderSubgroupRotate = r.u32();
    o.shaderSubgroupRotateClustered = r.u32();
}
function h_VkPhysicalDeviceShaderExpectAssumeFeatures_self(r, o)
{
    o.shaderExpectAssume = r.u32();
}
function h_VkPhysicalDeviceShaderFloatControls2Features_self(r, o)
{
    o.shaderFloatControls2 = r.u32();
}
function h_VkPhysicalDeviceDynamicRenderingLocalReadFeatures_self(r, o)
{
    o.dynamicRenderingLocalRead = r.u32();
}
function h_VkPhysicalDeviceShaderQuadControlFeaturesKHR_self(r, o)
{
    o.shaderQuadControl = r.u32();
}
function h_VkPhysicalDeviceShaderBfloat16FeaturesKHR_self(r, o)
{
    o.shaderBFloat16Type = r.u32();
    o.shaderBFloat16DotProduct = r.u32();
    o.shaderBFloat16CooperativeMatrix = r.u32();
}
function h_VkPhysicalDeviceShaderReplicatedCompositesFeaturesEXT_self(r, o)
{
    o.shaderReplicatedComposites = r.u32();
}
function h_VkPhysicalDeviceShaderUniformBufferUnsizedArrayFeaturesEXT_self(r, o)
{
    o.shaderUniformBufferUnsizedArray = r.u32();
}
function h_VkPhysicalDeviceShaderFloat8FeaturesEXT_self(r, o)
{
    o.shaderFloat8 = r.u32();
    o.shaderFloat8CooperativeMatrix = r.u32();
}
function h_VkPhysicalDeviceShaderUntypedPointersFeaturesKHR_self(r, o)
{
    o.shaderUntypedPointers = r.u32();
}
function h_VkPhysicalDeviceDescriptorHeapFeaturesEXT_self(r, o)
{
    o.descriptorHeap = r.u32();
    o.descriptorHeapCaptureReplay = r.u32();
}
function h_VkPhysicalDeviceMultiDrawPropertiesEXT_self(r, o)
{
    o.maxMultiDrawCount = r.u32();
}
function h_VkPhysicalDevicePushDescriptorProperties_self(r, o)
{
    o.maxPushDescriptors = r.u32();
}
function h_VkPhysicalDeviceDriverProperties_self(r, o)
{
    o.driverID = r.i32();
    {
        const array_size = r.size();
        o.driverName = r.str(array_size);
    }
    {
        const array_size = r.size();
        o.driverInfo = r.str(array_size);
    }
    o.conformanceVersion = h_VkConformanceVersion(r);
}
function h_VkPhysicalDeviceIDProperties_self(r, o)
{
    {
        const array_size = r.size();
        o.deviceUUID = r.u8s(array_size);
    }
    {
        const array_size = r.size();
        o.driverUUID = r.u8s(array_size);
    }
    {
        const array_size = r.size();
        o.deviceLUID = r.u8s(array_size);
    }
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
}
function h_VkPhysicalDeviceMultiviewProperties_self(r, o)
{
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
}
function h_VkPhysicalDeviceSubgroupProperties_self(r, o)
{
    o.subgroupSize = r.u32();
    o.supportedStages = r.u32();
    o.supportedOperations = r.u32();
    o.quadOperationsInAllStages = r.u32();
}
function h_VkPhysicalDevicePointClippingProperties_self(r, o)
{
    o.pointClippingBehavior = r.i32();
}
function h_VkPhysicalDeviceProtectedMemoryProperties_self(r, o)
{
    o.protectedNoFault = r.u32();
}
function h_VkPhysicalDeviceSamplerFilterMinmaxProperties_self(r, o)
{
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
}
function h_VkPhysicalDeviceSampleLocationsPropertiesEXT_self(r, o)
{
    o.sampleLocationSampleCounts = r.u32();
    o.maxSampleLocationGridSize = h_VkExtent2D(r);
    {
        const array_size = r.size();
        o.sampleLocationCoordinateRange = r.f32s(array_size);
    }
    o.sampleLocationSubPixelBits = r.u32();
    o.variableSampleLocations = r.u32();
}
function h_VkPhysicalDeviceBlendOperationAdvancedPropertiesEXT_self(r, o)
{
    o.advancedBlendMaxColorAttachments = r.u32();
    o.advancedBlendIndependentBlend = r.u32();
    o.advancedBlendNonPremultipliedSrcColor = r.u32();
    o.advancedBlendNonPremultipliedDstColor = r.u32();
    o.advancedBlendCorrelatedOverlap = r.u32();
    o.advancedBlendAllOperations = r.u32();
}
function h_VkPhysicalDeviceInlineUniformBlockProperties_self(r, o)
{
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
}
function h_VkPhysicalDeviceMaintenance3Properties_self(r, o)
{
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
}
function h_VkPhysicalDeviceMaintenance4Properties_self(r, o)
{
    o.maxBufferSize = r.u64();
}
function h_VkPhysicalDeviceMaintenance5Properties_self(r, o)
{
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
}
function h_VkPhysicalDeviceMaintenance6Properties_self(r, o)
{
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
}
function h_VkPhysicalDeviceMaintenance7PropertiesKHR_self(r, o)
{
    o.robustFragmentShadingRateAttachmentAccess = r.u32();
    o.separateDepthStencilAttachmentAccess = r.u32();
    o.maxDescriptorSetTotalUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetTotalStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetTotalBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindTotalUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindTotalStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindTotalBuffersDynamic = r.u32();
}
function h_VkPhysicalDeviceFloatControlsProperties_self(r, o)
{
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
}
function h_VkPhysicalDeviceConservativeRasterizationPropertiesEXT_self(r, o)
{
    o.primitiveOverestimationSize = r.f32();
    o.maxExtraPrimitiveOverestimationSize = r.f32();
    o.extraPrimitiveOverestimationSizeGranularity = r.f32();
    o.primitiveUnderestimation = r.u32();
    o.conservativePointAndLineRasterization = r.u32();
    o.degenerateTrianglesRasterized = r.u32();
    o.degenerateLinesRasterized = r.u32();
    o.fullyCoveredFragmentShaderInputVariable = r.u32();
    o.conservativeRasterizationPostDepthCoverage = r.u32();
}
function h_VkPhysicalDeviceDescriptorIndexingProperties_self(r, o)
{
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
}
function h_VkPhysicalDeviceTimelineSemaphoreProperties_self(r, o)
{
    o.maxTimelineSemaphoreValueDifference = r.u64();
}
function h_VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT_self(r, o)
{
    o.maxVertexAttribDivisor = r.u32();
}
function h_VkPhysicalDeviceVertexAttributeDivisorProperties_self(r, o)
{
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
}
function h_VkPhysicalDevicePCIBusInfoPropertiesEXT_self(r, o)
{
    o.pciDomain = r.u32();
    o.pciBus = r.u32();
    o.pciDevice = r.u32();
    o.pciFunction = r.u32();
}
function h_VkPhysicalDeviceDepthStencilResolveProperties_self(r, o)
{
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
}
function h_VkPhysicalDeviceTransformFeedbackPropertiesEXT_self(r, o)
{
    o.maxTransformFeedbackStreams = r.u32();
    o.maxTransformFeedbackBuffers = r.u32();
    o.maxTransformFeedbackBufferSize = r.u64();
    o.maxTransformFeedbackStreamDataSize = r.u32();
    o.maxTransformFeedbackBufferDataSize = r.u32();
    o.maxTransformFeedbackBufferDataStride = r.u32();
    o.transformFeedbackQueries = r.u32();
    o.transformFeedbackStreamsLinesTriangles = r.u32();
    o.transformFeedbackRasterizationStreamSelect = r.u32();
    o.transformFeedbackDraw = r.u32();
}
function h_VkPhysicalDeviceComputeShaderDerivativesPropertiesKHR_self(r, o)
{
    o.meshAndTaskShaderDerivatives = r.u32();
}
function h_VkPhysicalDeviceMeshShaderPropertiesEXT_self(r, o)
{
    o.maxTaskWorkGroupTotalCount = r.u32();
    {
        const array_size = r.size();
        o.maxTaskWorkGroupCount = r.u32s(array_size);
    }
    o.maxTaskWorkGroupInvocations = r.u32();
    {
        const array_size = r.size();
        o.maxTaskWorkGroupSize = r.u32s(array_size);
    }
    o.maxTaskPayloadSize = r.u32();
    o.maxTaskSharedMemorySize = r.u32();
    o.maxTaskPayloadAndSharedMemorySize = r.u32();
    o.maxMeshWorkGroupTotalCount = r.u32();
    {
        const array_size = r.size();
        o.maxMeshWorkGroupCount = r.u32s(array_size);
    }
    o.maxMeshWorkGroupInvocations = r.u32();
    {
        const array_size = r.size();
        o.maxMeshWorkGroupSize = r.u32s(array_size);
    }
    o.maxMeshSharedMemorySize = r.u32();
    o.maxMeshPayloadAndSharedMemorySize = r.u32();
    o.maxMeshOutputMemorySize = r.u32();
    o.maxMeshPayloadAndOutputMemorySize = r.u32();
    o.maxMeshOutputComponents = r.u32();
    o.maxMeshOutputVertices = r.u32();
    o.maxMeshOutputPrimitives = r.u32();
    o.maxMeshOutputLayers = r.u32();
    o.maxMeshMultiviewViewCount = r.u32();
    o.meshOutputPerVertexGranularity = r.u32();
    o.meshOutputPerPrimitiveGranularity = r.u32();
    o.maxPreferredTaskWorkGroupInvocations = r.u32();
    o.maxPreferredMeshWorkGroupInvocations = r.u32();
    o.prefersLocalInvocationVertexOutput = r.u32();
    o.prefersLocalInvocationPrimitiveOutput = r.u32();
    o.prefersCompactVertexOutput = r.u32();
    o.prefersCompactPrimitiveOutput = r.u32();
}
function h_VkPhysicalDeviceAccelerationStructurePropertiesKHR_self(r, o)
{
    o.maxGeometryCount = r.u64();
    o.maxInstanceCount = r.u64();
    o.maxPrimitiveCount = r.u64();
    o.maxPerStageDescriptorAccelerationStructures = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindAccelerationStructures = r.u32();
    o.maxDescriptorSetAccelerationStructures = r.u32();
    o.maxDescriptorSetUpdateAfterBindAccelerationStructures = r.u32();
    o.minAccelerationStructureScratchOffsetAlignment = r.u32();
}
function h_VkPhysicalDeviceRayTracingPipelinePropertiesKHR_self(r, o)
{
    o.shaderGroupHandleSize = r.u32();
    o.maxRayRecursionDepth = r.u32();
    o.maxShaderGroupStride = r.u32();
    o.shaderGroupBaseAlignment = r.u32();
    o.shaderGroupHandleCaptureReplaySize = r.u32();
    o.maxRayDispatchInvocationCount = r.u32();
    o.shaderGroupHandleAlignment = r.u32();
    o.maxRayHitAttributeSize = r.u32();
}
function h_VkPhysicalDeviceTexelBufferAlignmentProperties_self(r, o)
{
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
}
function h_VkPhysicalDeviceSubgroupSizeControlProperties_self(r, o)
{
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
}
function h_VkPhysicalDeviceLineRasterizationProperties_self(r, o)
{
    o.lineSubPixelPrecisionBits = r.u32();
}
function h_VkPhysicalDeviceVulkan11Properties_self(r, o)
{
    {
        const array_size = r.size();
        o.deviceUUID = r.u8s(array_size);
    }
    {
        const array_size = r.size();
        o.driverUUID = r.u8s(array_size);
    }
    {
        const array_size = r.size();
        o.deviceLUID = r.u8s(array_size);
    }
    o.deviceNodeMask = r.u32();
    o.deviceLUIDValid = r.u32();
    o.subgroupSize = r.u32();
    o.subgroupSupportedStages = r.u32();
    o.subgroupSupportedOperations = r.u32();
    o.subgroupQuadOperationsInAllStages = r.u32();
    o.pointClippingBehavior = r.i32();
    o.maxMultiviewViewCount = r.u32();
    o.maxMultiviewInstanceIndex = r.u32();
    o.protectedNoFault = r.u32();
    o.maxPerSetDescriptors = r.u32();
    o.maxMemoryAllocationSize = r.u64();
}
function h_VkPhysicalDeviceVulkan12Properties_self(r, o)
{
    o.driverID = r.i32();
    {
        const array_size = r.size();
        o.driverName = r.str(array_size);
    }
    {
        const array_size = r.size();
        o.driverInfo = r.str(array_size);
    }
    o.conformanceVersion = h_VkConformanceVersion(r);
    o.denormBehaviorIndependence = r.i32();
    o.roundingModeIndependence = r.i32();
    o.shaderSignedZeroInfNanPreserveFloat16 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat32 = r.u32();
    o.shaderSignedZeroInfNanPreserveFloat64 = r.u32();
    o.shaderDenormPreserveFloat16 = r.u32();
    o.shaderDenormPreserveFloat32 = r.u32();
    o.shaderDenormPreserveFloat64 = r.u32();
    o.shaderDenormFlushToZeroFloat16 = r.u32();
    o.shaderDenormFlushToZeroFloat32 = r.u32();
    o.shaderDenormFlushToZeroFloat64 = r.u32();
    o.shaderRoundingModeRTEFloat16 = r.u32();
    o.shaderRoundingModeRTEFloat32 = r.u32();
    o.shaderRoundingModeRTEFloat64 = r.u32();
    o.shaderRoundingModeRTZFloat16 = r.u32();
    o.shaderRoundingModeRTZFloat32 = r.u32();
    o.shaderRoundingModeRTZFloat64 = r.u32();
    o.maxUpdateAfterBindDescriptorsInAllPools = r.u32();
    o.shaderUniformBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderSampledImageArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageBufferArrayNonUniformIndexingNative = r.u32();
    o.shaderStorageImageArrayNonUniformIndexingNative = r.u32();
    o.shaderInputAttachmentArrayNonUniformIndexingNative = r.u32();
    o.robustBufferAccessUpdateAfterBind = r.u32();
    o.quadDivergentImplicitLod = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSamplers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindUniformBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageBuffers = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindSampledImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindStorageImages = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInputAttachments = r.u32();
    o.maxPerStageUpdateAfterBindResources = r.u32();
    o.maxDescriptorSetUpdateAfterBindSamplers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffers = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetUpdateAfterBindSampledImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindStorageImages = r.u32();
    o.maxDescriptorSetUpdateAfterBindInputAttachments = r.u32();
    o.supportedDepthResolveModes = r.u32();
    o.supportedStencilResolveModes = r.u32();
    o.independentResolveNone = r.u32();
    o.independentResolve = r.u32();
    o.filterMinmaxSingleComponentFormats = r.u32();
    o.filterMinmaxImageComponentMapping = r.u32();
    o.maxTimelineSemaphoreValueDifference = r.u64();
    o.framebufferIntegerColorSampleCounts = r.u32();
}
function h_VkPhysicalDeviceVulkan13Properties_self(r, o)
{
    o.minSubgroupSize = r.u32();
    o.maxSubgroupSize = r.u32();
    o.maxComputeWorkgroupSubgroups = r.u32();
    o.requiredSubgroupSizeStages = r.u32();
    o.maxInlineUniformBlockSize = r.u32();
    o.maxPerStageDescriptorInlineUniformBlocks = r.u32();
    o.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxDescriptorSetInlineUniformBlocks = r.u32();
    o.maxDescriptorSetUpdateAfterBindInlineUniformBlocks = r.u32();
    o.maxInlineUniformTotalSize = r.u32();
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
    o.storageTexelBufferOffsetAlignmentBytes = r.u64();
    o.storageTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.uniformTexelBufferOffsetAlignmentBytes = r.u64();
    o.uniformTexelBufferOffsetSingleTexelAlignment = r.u32();
    o.maxBufferSize = r.u64();
}
function h_VkPhysicalDeviceVulkan14Properties_self(r, o)
{
    o.lineSubPixelPrecisionBits = r.u32();
    o.maxVertexAttribDivisor = r.u32();
    o.supportsNonZeroFirstInstance = r.u32();
    o.maxPushDescriptors = r.u32();
    o.dynamicRenderingLocalReadDepthStencilAttachments = r.u32();
    o.dynamicRenderingLocalReadMultisampledAttachments = r.u32();
    o.earlyFragmentMultisampleCoverageAfterSampleCounting = r.u32();
    o.earlyFragmentSampleMaskTestBeforeSampleCounting = r.u32();
    o.depthStencilSwizzleOneSupport = r.u32();
    o.polygonModePointSize = r.u32();
    o.nonStrictSinglePixelWideLinesUseParallelogram = r.u32();
    o.nonStrictWideLinesUseParallelogram = r.u32();
    o.blockTexelViewCompatibleMultipleLayers = r.u32();
    o.maxCombinedImageSamplerDescriptorCount = r.u32();
    o.fragmentShadingRateClampCombinerInputs = r.u32();
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
    o.copySrcLayoutCount = r.u32();
    if(r.peek_size())
    {
        const array_size = r.size();
        o.pCopySrcLayouts = r.i32s(array_size);
    }
    else
    {
        r.size();
        o.pCopySrcLayouts = null;
    }
    o.copyDstLayoutCount = r.u32();
    if(r.peek_size())
    {
        const array_size = r.size();
        o.pCopyDstLayouts = r.i32s(array_size);
    }
    else
    {
        r.size();
        o.pCopyDstLayouts = null;
    }
    {
        const array_size = r.size();
        o.optimalTilingLayoutUUID = r.u8s(array_size);
    }
    o.identicalMemoryTypeRequirements = r.u32();
}
function h_VkPhysicalDeviceCustomBorderColorPropertiesEXT_self(r, o)
{
    o.maxCustomBorderColorSamplers = r.u32();
}
function h_VkPhysicalDeviceExtendedDynamicState3PropertiesEXT_self(r, o)
{
    o.dynamicPrimitiveTopologyUnrestricted = r.u32();
}
function h_VkPhysicalDeviceRobustness2PropertiesKHR_self(r, o)
{
    o.robustStorageBufferAccessSizeAlignment = r.u64();
    o.robustUniformBufferAccessSizeAlignment = r.u64();
}
function h_VkPhysicalDeviceFragmentShadingRatePropertiesKHR_self(r, o)
{
    o.minFragmentShadingRateAttachmentTexelSize = h_VkExtent2D(r);
    o.maxFragmentShadingRateAttachmentTexelSize = h_VkExtent2D(r);
    o.maxFragmentShadingRateAttachmentTexelSizeAspectRatio = r.u32();
    o.primitiveFragmentShadingRateWithMultipleViewports = r.u32();
    o.layeredShadingRateAttachments = r.u32();
    o.fragmentShadingRateNonTrivialCombinerOps = r.u32();
    o.maxFragmentSize = h_VkExtent2D(r);
    o.maxFragmentSizeAspectRatio = r.u32();
    o.maxFragmentShadingRateCoverageSamples = r.u32();
    o.maxFragmentShadingRateRasterizationSamples = r.i32();
    o.fragmentShadingRateWithShaderDepthStencilWrites = r.u32();
    o.fragmentShadingRateWithSampleMask = r.u32();
    o.fragmentShadingRateWithShaderSampleMask = r.u32();
    o.fragmentShadingRateWithConservativeRasterization = r.u32();
    o.fragmentShadingRateWithFragmentShaderInterlock = r.u32();
    o.fragmentShadingRateWithCustomSampleLocations = r.u32();
    o.fragmentShadingRateStrictMultiplyCombiner = r.u32();
}
function h_VkPhysicalDeviceLegacyVertexAttributesPropertiesEXT_self(r, o)
{
    o.nativeUnalignedPerformance = r.u32();
}
function h_VkPhysicalDeviceHostImageCopyProperties_self(r, o)
{
    o.copySrcLayoutCount = r.u32();
    if(r.peek_size())
    {
        const array_size = r.size();
        o.pCopySrcLayouts = r.i32s(array_size);
    }
    else
    {
        r.size();
        o.pCopySrcLayouts = null;
    }
    o.copyDstLayoutCount = r.u32();
    if(r.peek_size())
    {
        const array_size = r.size();
        o.pCopyDstLayouts = r.i32s(array_size);
    }
    else
    {
        r.size();
        o.pCopyDstLayouts = null;
    }
    {
        const array_size = r.size();
        o.optimalTilingLayoutUUID = r.u8s(array_size);
    }
    o.identicalMemoryTypeRequirements = r.u32();
}
function h_VkPhysicalDeviceProvokingVertexPropertiesEXT_self(r, o)
{
    o.provokingVertexModePerPipeline = r.u32();
    o.transformFeedbackPreservesTriangleFanProvokingVertex = r.u32();
}
function h_VkPhysicalDeviceShaderIntegerDotProductProperties_self(r, o)
{
    o.integerDotProduct8BitUnsignedAccelerated = r.u32();
    o.integerDotProduct8BitSignedAccelerated = r.u32();
    o.integerDotProduct8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProduct4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProduct16BitUnsignedAccelerated = r.u32();
    o.integerDotProduct16BitSignedAccelerated = r.u32();
    o.integerDotProduct16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct32BitUnsignedAccelerated = r.u32();
    o.integerDotProduct32BitSignedAccelerated = r.u32();
    o.integerDotProduct32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProduct64BitUnsignedAccelerated = r.u32();
    o.integerDotProduct64BitSignedAccelerated = r.u32();
    o.integerDotProduct64BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating8BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating4x8BitPackedMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating16BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating32BitMixedSignednessAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitUnsignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitSignedAccelerated = r.u32();
    o.integerDotProductAccumulatingSaturating64BitMixedSignednessAccelerated = r.u32();
}
function h_VkPhysicalDeviceFragmentShaderBarycentricPropertiesKHR_self(r, o)
{
    o.triStripVertexOrderIndependentOfProvokingVertex = r.u32();
}
function h_VkPhysicalDeviceGraphicsPipelineLibraryPropertiesEXT_self(r, o)
{
    o.graphicsPipelineLibraryFastLinking = r.u32();
    o.graphicsPipelineLibraryIndependentInterpolationDecoration = r.u32();
}
function h_VkPhysicalDeviceNestedCommandBufferPropertiesEXT_self(r, o)
{
    o.maxCommandBufferNestingLevel = r.u32();
}
function h_VkPhysicalDevicePipelineRobustnessProperties_self(r, o)
{
    o.defaultRobustnessStorageBuffers = r.i32();
    o.defaultRobustnessUniformBuffers = r.i32();
    o.defaultRobustnessVertexInputs = r.i32();
    o.defaultRobustnessImages = r.i32();
}
function h_VkPhysicalDeviceCooperativeMatrixPropertiesKHR_self(r, o)
{
    o.cooperativeMatrixSupportedStages = r.u32();
}
function h_VkPhysicalDeviceDescriptorHeapPropertiesEXT_self(r, o)
{
    o.samplerHeapAlignment = r.u64();
    o.resourceHeapAlignment = r.u64();
    o.maxSamplerHeapSize = r.u64();
    o.maxResourceHeapSize = r.u64();
    o.minSamplerHeapReservedRange = r.u64();
    o.minSamplerHeapReservedRangeWithEmbedded = r.u64();
    o.minResourceHeapReservedRange = r.u64();
    o.samplerDescriptorSize = r.u64();
    o.imageDescriptorSize = r.u64();
    o.bufferDescriptorSize = r.u64();
    o.samplerDescriptorAlignment = r.u64();
    o.imageDescriptorAlignment = r.u64();
    o.bufferDescriptorAlignment = r.u64();
    o.maxPushDataSize = r.u64();
    o.imageCaptureReplayOpaqueDataSize = r.u64();
    o.maxDescriptorHeapEmbeddedSamplers = r.u32();
    o.samplerYcbcrConversionCount = r.u32();
    o.sparseDescriptorHeaps = r.u32();
    o.protectedDescriptorHeaps = r.u32();
}
function h_VkDrmFormatModifierPropertiesListEXT_self(r, o)
{
    o.drmFormatModifierCount = r.u32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        o.pDrmFormatModifierProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            o.pDrmFormatModifierProperties[i] = h_VkDrmFormatModifierPropertiesEXT(r);
        }
    }
    else
    {
        r.size();
        o.pDrmFormatModifierProperties = null;
    }
}
function h_VkSubpassResolvePerformanceQueryEXT_self(r, o)
{
    o.optimal = r.u32();
}
function h_VkFormatProperties3_self(r, o)
{
    o.linearTilingFeatures = r.u64();
    o.optimalTilingFeatures = r.u64();
    o.bufferFeatures = r.u64();
}
function h_VkDrmFormatModifierPropertiesList2EXT_self(r, o)
{
    o.drmFormatModifierCount = r.u32();
    if(r.peek_size())
    {
        const iter_count = r.size();
        o.pDrmFormatModifierProperties = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            o.pDrmFormatModifierProperties[i] = h_VkDrmFormatModifierProperties2EXT(r);
        }
    }
    else
    {
        r.size();
        o.pDrmFormatModifierProperties = null;
    }
}
function h_VkExternalImageFormatProperties_self(r, o)
{
    o.externalMemoryProperties = h_VkExternalMemoryProperties(r);
}
function h_VkSamplerYcbcrConversionImageFormatProperties_self(r, o)
{
    o.combinedImageSamplerDescriptorCount = r.u32();
}
function h_VkFilterCubicImageViewImageFormatPropertiesEXT_self(r, o)
{
    o.filterCubic = r.u32();
    o.filterCubicMinmax = r.u32();
}
function h_VkHostImageCopyDevicePerformanceQuery_self(r, o)
{
    o.optimalDeviceAccess = r.u32();
    o.identicalMemoryLayout = r.u32();
}
function h_VkQueueFamilyGlobalPriorityProperties_self(r, o)
{
    o.priorityCount = r.u32();
    {
        const array_size = r.size();
        o.priorities = r.i32s(array_size);
    }
}
function h_VkPhysicalDeviceMemoryBudgetPropertiesEXT_self(r, o)
{
    {
        const array_size = r.size();
        o.heapBudget = r.u64s(array_size);
    }
    {
        const array_size = r.size();
        o.heapUsage = r.u64s(array_size);
    }
}
function h_VkMemoryResourceAllocationSizePropertiesMESA_self(r, o)
{
    o.allocationSize = r.u64();
}
function h_VkSubresourceHostMemcpySize_self(r, o)
{
    o.size = r.u64();
}
function h_VkMemoryDedicatedRequirements_self(r, o)
{
    o.prefersDedicatedAllocation = r.u32();
    o.requiresDedicatedAllocation = r.u32();
}
function g_VkInstanceCreateInfo(w, o)
{
    w.u32(1);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkInstanceCreateInfo_self(w, o);
}
function g_VkPhysicalDeviceFeatures_partial(w, o)
{
}
function h_VkPhysicalDeviceFeatures(r)
{
    const o = {};
    o.robustBufferAccess = r.u32();
    o.fullDrawIndexUint32 = r.u32();
    o.imageCubeArray = r.u32();
    o.independentBlend = r.u32();
    o.geometryShader = r.u32();
    o.tessellationShader = r.u32();
    o.sampleRateShading = r.u32();
    o.dualSrcBlend = r.u32();
    o.logicOp = r.u32();
    o.multiDrawIndirect = r.u32();
    o.drawIndirectFirstInstance = r.u32();
    o.depthClamp = r.u32();
    o.depthBiasClamp = r.u32();
    o.fillModeNonSolid = r.u32();
    o.depthBounds = r.u32();
    o.wideLines = r.u32();
    o.largePoints = r.u32();
    o.alphaToOne = r.u32();
    o.multiViewport = r.u32();
    o.samplerAnisotropy = r.u32();
    o.textureCompressionETC2 = r.u32();
    o.textureCompressionASTC_LDR = r.u32();
    o.textureCompressionBC = r.u32();
    o.occlusionQueryPrecise = r.u32();
    o.pipelineStatisticsQuery = r.u32();
    o.vertexPipelineStoresAndAtomics = r.u32();
    o.fragmentStoresAndAtomics = r.u32();
    o.shaderTessellationAndGeometryPointSize = r.u32();
    o.shaderImageGatherExtended = r.u32();
    o.shaderStorageImageExtendedFormats = r.u32();
    o.shaderStorageImageMultisample = r.u32();
    o.shaderStorageImageReadWithoutFormat = r.u32();
    o.shaderStorageImageWriteWithoutFormat = r.u32();
    o.shaderUniformBufferArrayDynamicIndexing = r.u32();
    o.shaderSampledImageArrayDynamicIndexing = r.u32();
    o.shaderStorageBufferArrayDynamicIndexing = r.u32();
    o.shaderStorageImageArrayDynamicIndexing = r.u32();
    o.shaderClipDistance = r.u32();
    o.shaderCullDistance = r.u32();
    o.shaderFloat64 = r.u32();
    o.shaderInt64 = r.u32();
    o.shaderInt16 = r.u32();
    o.shaderResourceResidency = r.u32();
    o.shaderResourceMinLod = r.u32();
    o.sparseBinding = r.u32();
    o.sparseResidencyBuffer = r.u32();
    o.sparseResidencyImage2D = r.u32();
    o.sparseResidencyImage3D = r.u32();
    o.sparseResidency2Samples = r.u32();
    o.sparseResidency4Samples = r.u32();
    o.sparseResidency8Samples = r.u32();
    o.sparseResidency16Samples = r.u32();
    o.sparseResidencyAliased = r.u32();
    o.variableMultisampleRate = r.u32();
    o.inheritedQueries = r.u32();
    return o;
}
function g_VkFormatProperties_partial(w, o)
{
}
function h_VkFormatProperties(r)
{
    const o = {};
    o.linearTilingFeatures = r.u32();
    o.optimalTilingFeatures = r.u32();
    o.bufferFeatures = r.u32();
    return o;
}
function g_VkImageFormatProperties_partial(w, o)
{
    g_VkExtent3D_partial(w, o.maxExtent || EMPTY);
}
function h_VkImageFormatProperties(r)
{
    const o = {};
    o.maxExtent = h_VkExtent3D(r);
    o.maxMipLevels = r.u32();
    o.maxArrayLayers = r.u32();
    o.sampleCounts = r.u32();
    o.maxResourceSize = r.u64();
    return o;
}
function g_VkPhysicalDeviceProperties_partial(w, o)
{
    g_VkPhysicalDeviceLimits_partial(w, o.limits || EMPTY);
    g_VkPhysicalDeviceSparseProperties_partial(w, o.sparseProperties || EMPTY);
}
function h_VkPhysicalDeviceProperties(r)
{
    const o = {};
    o.apiVersion = r.u32();
    o.driverVersion = r.u32();
    o.vendorID = r.u32();
    o.deviceID = r.u32();
    o.deviceType = r.i32();
    {
        const array_size = r.size();
        o.deviceName = r.str(array_size);
    }
    {
        const array_size = r.size();
        o.pipelineCacheUUID = r.u8s(array_size);
    }
    o.limits = h_VkPhysicalDeviceLimits(r);
    o.sparseProperties = h_VkPhysicalDeviceSparseProperties(r);
    return o;
}
function g_VkQueueFamilyProperties_partial(w, o)
{
    g_VkExtent3D_partial(w, o.minImageTransferGranularity || EMPTY);
}
function h_VkQueueFamilyProperties(r)
{
    const o = {};
    o.queueFlags = r.u32();
    o.queueCount = r.u32();
    o.timestampValidBits = r.u32();
    o.minImageTransferGranularity = h_VkExtent3D(r);
    return o;
}
function g_VkPhysicalDeviceMemoryProperties_partial(w, o)
{
    w.size(32);
    for(let i = 0; i < 32; i++)
    {
        g_VkMemoryType_partial(w, (o.memoryTypes || EMPTY)[i] || EMPTY);
    }
    w.size(16);
    for(let i = 0; i < 16; i++)
    {
        g_VkMemoryHeap_partial(w, (o.memoryHeaps || EMPTY)[i] || EMPTY);
    }
}
function h_VkPhysicalDeviceMemoryProperties(r)
{
    const o = {};
    o.memoryTypeCount = r.u32();
    {
        const iter_count = r.size();
        o.memoryTypes = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            o.memoryTypes[i] = h_VkMemoryType(r);
        }
    }
    o.memoryHeapCount = r.u32();
    {
        const iter_count = r.size();
        o.memoryHeaps = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            o.memoryHeaps[i] = h_VkMemoryHeap(r);
        }
    }
    return o;
}
function g_VkDeviceCreateInfo(w, o)
{
    w.u32(3);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceCreateInfo_self(w, o);
}
function g_VkExtensionProperties_partial(w, o)
{
}
function h_VkExtensionProperties(r)
{
    const o = {};
    {
        const array_size = r.size();
        o.extensionName = r.str(array_size);
    }
    o.specVersion = r.u32();
    return o;
}
function g_VkLayerProperties_partial(w, o)
{
}
function h_VkLayerProperties(r)
{
    const o = {};
    {
        const array_size = r.size();
        o.layerName = r.str(array_size);
    }
    o.specVersion = r.u32();
    o.implementationVersion = r.u32();
    {
        const array_size = r.size();
        o.description = r.str(array_size);
    }
    return o;
}
function g_VkSubmitInfo(w, o)
{
    w.u32(4);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubmitInfo_self(w, o);
}
function g_VkMemoryAllocateInfo(w, o)
{
    w.u32(5);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMemoryAllocateInfo_self(w, o);
}
function g_VkMappedMemoryRange(w, o)
{
    w.u32(6);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMappedMemoryRange_self(w, o);
}
function g_VkMemoryRequirements_partial(w, o)
{
}
function h_VkMemoryRequirements(r)
{
    const o = {};
    o.size = r.u64();
    o.alignment = r.u64();
    o.memoryTypeBits = r.u32();
    return o;
}
function g_VkSparseImageMemoryRequirements_partial(w, o)
{
    g_VkSparseImageFormatProperties_partial(w, o.formatProperties || EMPTY);
}
function h_VkSparseImageMemoryRequirements(r)
{
    const o = {};
    o.formatProperties = h_VkSparseImageFormatProperties(r);
    o.imageMipTailFirstLod = r.u32();
    o.imageMipTailSize = r.u64();
    o.imageMipTailOffset = r.u64();
    o.imageMipTailStride = r.u64();
    return o;
}
function g_VkSparseImageFormatProperties_partial(w, o)
{
    g_VkExtent3D_partial(w, o.imageGranularity || EMPTY);
}
function h_VkSparseImageFormatProperties(r)
{
    const o = {};
    o.aspectMask = r.u32();
    o.imageGranularity = h_VkExtent3D(r);
    o.flags = r.u32();
    return o;
}
function g_VkBindSparseInfo(w, o)
{
    w.u32(7);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBindSparseInfo_self(w, o);
}
function g_VkFenceCreateInfo(w, o)
{
    w.u32(8);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkFenceCreateInfo_self(w, o);
}
function g_VkSemaphoreCreateInfo(w, o)
{
    w.u32(9);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSemaphoreCreateInfo_self(w, o);
}
function g_VkEventCreateInfo(w, o)
{
    w.u32(10);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkEventCreateInfo_self(w, o);
}
function g_VkQueryPoolCreateInfo(w, o)
{
    w.u32(11);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkQueryPoolCreateInfo_self(w, o);
}
function g_VkBufferCreateInfo(w, o)
{
    w.u32(12);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferCreateInfo_self(w, o);
}
function g_VkBufferViewCreateInfo(w, o)
{
    w.u32(13);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferViewCreateInfo_self(w, o);
}
function g_VkImageCreateInfo(w, o)
{
    w.u32(14);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageCreateInfo_self(w, o);
}
function g_VkImageSubresource(w, o)
{
    w.u32(o.aspectMask);
    w.u32(o.mipLevel);
    w.u32(o.arrayLayer);
}
function g_VkSubresourceLayout_partial(w, o)
{
}
function h_VkSubresourceLayout(r)
{
    const o = {};
    o.offset = r.u64();
    o.size = r.u64();
    o.rowPitch = r.u64();
    o.arrayPitch = r.u64();
    o.depthPitch = r.u64();
    return o;
}
function g_VkImageViewCreateInfo(w, o)
{
    w.u32(15);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageViewCreateInfo_self(w, o);
}
function g_VkShaderModuleCreateInfo(w, o)
{
    w.u32(16);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkShaderModuleCreateInfo_self(w, o);
}
function g_VkPipelineCacheCreateInfo(w, o)
{
    w.u32(17);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineCacheCreateInfo_self(w, o);
}
function g_VkGraphicsPipelineCreateInfo(w, o)
{
    w.u32(28);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkGraphicsPipelineCreateInfo_self(w, o);
}
function g_VkComputePipelineCreateInfo(w, o)
{
    w.u32(29);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkComputePipelineCreateInfo_self(w, o);
}
function g_VkPipelineLayoutCreateInfo(w, o)
{
    w.u32(30);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineLayoutCreateInfo_self(w, o);
}
function g_VkSamplerCreateInfo(w, o)
{
    w.u32(31);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSamplerCreateInfo_self(w, o);
}
function g_VkDescriptorSetLayoutCreateInfo(w, o)
{
    w.u32(32);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDescriptorSetLayoutCreateInfo_self(w, o);
}
function g_VkDescriptorPoolCreateInfo(w, o)
{
    w.u32(33);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDescriptorPoolCreateInfo_self(w, o);
}
function g_VkDescriptorSetAllocateInfo(w, o)
{
    w.u32(34);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDescriptorSetAllocateInfo_self(w, o);
}
function g_VkWriteDescriptorSet(w, o)
{
    w.u32(35);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkWriteDescriptorSet_self(w, o);
}
function g_VkCopyDescriptorSet(w, o)
{
    w.u32(36);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyDescriptorSet_self(w, o);
}
function g_VkFramebufferCreateInfo(w, o)
{
    w.u32(37);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkFramebufferCreateInfo_self(w, o);
}
function g_VkRenderPassCreateInfo(w, o)
{
    w.u32(38);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderPassCreateInfo_self(w, o);
}
function g_VkExtent2D_partial(w, o)
{
}
function h_VkExtent2D(r)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    return o;
}
function g_VkCommandPoolCreateInfo(w, o)
{
    w.u32(39);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCommandPoolCreateInfo_self(w, o);
}
function g_VkCommandBufferAllocateInfo(w, o)
{
    w.u32(40);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCommandBufferAllocateInfo_self(w, o);
}
function g_VkCommandBufferBeginInfo(w, o)
{
    w.u32(42);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCommandBufferBeginInfo_self(w, o);
}
function g_VkViewport(w, o)
{
    w.f32(o.x);
    w.f32(o.y);
    w.f32(o.width);
    w.f32(o.height);
    w.f32(o.minDepth);
    w.f32(o.maxDepth);
}
function g_VkRect2D(w, o)
{
    g_VkOffset2D(w, o.offset || EMPTY);
    g_VkExtent2D(w, o.extent || EMPTY);
}
function g_VkBufferCopy(w, o)
{
    w.u64(o.srcOffset);
    w.u64(o.dstOffset);
    w.u64(o.size);
}
function g_VkImageCopy(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    g_VkOffset3D(w, o.srcOffset || EMPTY);
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    g_VkOffset3D(w, o.dstOffset || EMPTY);
    g_VkExtent3D(w, o.extent || EMPTY);
}
function g_VkImageBlit(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    w.size(2);
    for(let i = 0; i < 2; i++)
    {
        g_VkOffset3D(w, (o.srcOffsets || EMPTY)[i] || EMPTY);
    }
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    w.size(2);
    for(let i = 0; i < 2; i++)
    {
        g_VkOffset3D(w, (o.dstOffsets || EMPTY)[i] || EMPTY);
    }
}
function g_VkBufferImageCopy(w, o)
{
    w.u64(o.bufferOffset);
    w.u32(o.bufferRowLength);
    w.u32(o.bufferImageHeight);
    g_VkImageSubresourceLayers(w, o.imageSubresource || EMPTY);
    g_VkOffset3D(w, o.imageOffset || EMPTY);
    g_VkExtent3D(w, o.imageExtent || EMPTY);
}
function g_VkClearColorValue(w, o)
{
    const tag = o._tag !== undefined ? o._tag : 2;
    w.u32(tag);
    switch(tag)
    {
    case 0:
        w.size(4);
        w.f32s(o.float32, 4);
        break;
    case 1:
        w.size(4);
        w.i32s(o.int32, 4);
        break;
    case 2:
        w.size(4);
        w.u32s(o.uint32, 4);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
}
function g_VkImageSubresourceRange(w, o)
{
    w.u32(o.aspectMask);
    w.u32(o.baseMipLevel);
    w.u32(o.levelCount);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}
function g_VkClearDepthStencilValue(w, o)
{
    w.f32(o.depth);
    w.u32(o.stencil);
}
function g_VkClearAttachment(w, o)
{
    w.u32(o.aspectMask);
    w.u32(o.colorAttachment);
    g_VkClearValue(w, o.clearValue || EMPTY);
}
function g_VkClearRect(w, o)
{
    g_VkRect2D(w, o.rect || EMPTY);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}
function g_VkImageResolve(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    g_VkOffset3D(w, o.srcOffset || EMPTY);
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    g_VkOffset3D(w, o.dstOffset || EMPTY);
    g_VkExtent3D(w, o.extent || EMPTY);
}
function g_VkMemoryBarrier(w, o)
{
    w.u32(46);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMemoryBarrier_self(w, o);
}
function g_VkBufferMemoryBarrier(w, o)
{
    w.u32(44);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferMemoryBarrier_self(w, o);
}
function g_VkImageMemoryBarrier(w, o)
{
    w.u32(45);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageMemoryBarrier_self(w, o);
}
function g_VkRenderPassBeginInfo(w, o)
{
    w.u32(43);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderPassBeginInfo_self(w, o);
}
function g_VkBindBufferMemoryInfo(w, o)
{
    w.u32(1000157000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBindBufferMemoryInfo_self(w, o);
}
function g_VkBindImageMemoryInfo(w, o)
{
    w.u32(1000157001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBindImageMemoryInfo_self(w, o);
}
function g_VkPhysicalDeviceGroupProperties_partial(w, o)
{
    w.u32(1000070000);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceGroupProperties_self_partial(w, o);
}
function h_VkPhysicalDeviceGroupProperties(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceGroupProperties_self(r, o);
    return o;
}
function g_VkImageMemoryRequirementsInfo2(w, o)
{
    w.u32(1000146001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageMemoryRequirementsInfo2_self(w, o);
}
function g_VkMemoryRequirements2_partial(w, o)
{
    w.u32(1000146003);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkMemoryRequirements2_self_partial(w, o);
}
function h_VkMemoryRequirements2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkMemoryRequirements2_self(r, o);
    return o;
}
function g_VkBufferMemoryRequirementsInfo2(w, o)
{
    w.u32(1000146000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferMemoryRequirementsInfo2_self(w, o);
}
function g_VkImageSparseMemoryRequirementsInfo2(w, o)
{
    w.u32(1000146002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageSparseMemoryRequirementsInfo2_self(w, o);
}
function g_VkSparseImageMemoryRequirements2_partial(w, o)
{
    w.u32(1000146004);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkSparseImageMemoryRequirements2_self_partial(w, o);
}
function h_VkSparseImageMemoryRequirements2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkSparseImageMemoryRequirements2_self(r, o);
    return o;
}
function g_VkPhysicalDeviceFeatures2_partial(w, o)
{
    w.u32(1000059000);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceFeatures2_self_partial(w, o);
}
function h_VkPhysicalDeviceFeatures2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceFeatures2_self(r, o);
    return o;
}
function g_VkPhysicalDeviceProperties2_partial(w, o)
{
    w.u32(1000059001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceProperties2_self_partial(w, o);
}
function h_VkPhysicalDeviceProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceProperties2_self(r, o);
    return o;
}
function g_VkFormatProperties2_partial(w, o)
{
    w.u32(1000059002);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkFormatProperties2_self_partial(w, o);
}
function h_VkFormatProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkFormatProperties2_self(r, o);
    return o;
}
function g_VkPhysicalDeviceImageFormatInfo2(w, o)
{
    w.u32(1000059004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPhysicalDeviceImageFormatInfo2_self(w, o);
}
function g_VkImageFormatProperties2_partial(w, o)
{
    w.u32(1000059003);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkImageFormatProperties2_self_partial(w, o);
}
function h_VkImageFormatProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkImageFormatProperties2_self(r, o);
    return o;
}
function g_VkQueueFamilyProperties2_partial(w, o)
{
    w.u32(1000059005);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkQueueFamilyProperties2_self_partial(w, o);
}
function h_VkQueueFamilyProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkQueueFamilyProperties2_self(r, o);
    return o;
}
function g_VkPhysicalDeviceMemoryProperties2_partial(w, o)
{
    w.u32(1000059006);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceMemoryProperties2_self_partial(w, o);
}
function h_VkPhysicalDeviceMemoryProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceMemoryProperties2_self(r, o);
    return o;
}
function g_VkPhysicalDeviceSparseImageFormatInfo2(w, o)
{
    w.u32(1000059008);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPhysicalDeviceSparseImageFormatInfo2_self(w, o);
}
function g_VkSparseImageFormatProperties2_partial(w, o)
{
    w.u32(1000059007);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkSparseImageFormatProperties2_self_partial(w, o);
}
function h_VkSparseImageFormatProperties2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkSparseImageFormatProperties2_self(r, o);
    return o;
}
function g_VkDeviceQueueInfo2(w, o)
{
    w.u32(1000145003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceQueueInfo2_self(w, o);
}
function g_VkSamplerYcbcrConversionCreateInfo(w, o)
{
    w.u32(1000156000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSamplerYcbcrConversionCreateInfo_self(w, o);
}
function g_VkDescriptorUpdateTemplateCreateInfo(w, o)
{
    w.u32(1000085000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDescriptorUpdateTemplateCreateInfo_self(w, o);
}
function g_VkPhysicalDeviceExternalBufferInfo(w, o)
{
    w.u32(1000071002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPhysicalDeviceExternalBufferInfo_self(w, o);
}
function g_VkExternalBufferProperties_partial(w, o)
{
    w.u32(1000071003);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkExternalBufferProperties_self_partial(w, o);
}
function h_VkExternalBufferProperties(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkExternalBufferProperties_self(r, o);
    return o;
}
function g_VkPhysicalDeviceExternalFenceInfo(w, o)
{
    w.u32(1000112000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPhysicalDeviceExternalFenceInfo_self(w, o);
}
function g_VkExternalFenceProperties_partial(w, o)
{
    w.u32(1000112001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkExternalFenceProperties_self_partial(w, o);
}
function h_VkExternalFenceProperties(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkExternalFenceProperties_self(r, o);
    return o;
}
function g_VkPhysicalDeviceExternalSemaphoreInfo(w, o)
{
    w.u32(1000076000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPhysicalDeviceExternalSemaphoreInfo_self(w, o);
}
function g_VkExternalSemaphoreProperties_partial(w, o)
{
    w.u32(1000076001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkExternalSemaphoreProperties_self_partial(w, o);
}
function h_VkExternalSemaphoreProperties(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkExternalSemaphoreProperties_self(r, o);
    return o;
}
function g_VkDescriptorSetLayoutSupport_partial(w, o)
{
    w.u32(1000168001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkDescriptorSetLayoutSupport_self_partial(w, o);
}
function h_VkDescriptorSetLayoutSupport(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkDescriptorSetLayoutSupport_self(r, o);
    return o;
}
function g_VkRenderPassCreateInfo2(w, o)
{
    w.u32(1000109004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderPassCreateInfo2_self(w, o);
}
function g_VkSubpassBeginInfo(w, o)
{
    w.u32(1000109005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubpassBeginInfo_self(w, o);
}
function g_VkSubpassEndInfo(w, o)
{
    w.u32(1000109006);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubpassEndInfo_self(w, o);
}
function g_VkSemaphoreWaitInfo(w, o)
{
    w.u32(1000207004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSemaphoreWaitInfo_self(w, o);
}
function g_VkSemaphoreSignalInfo(w, o)
{
    w.u32(1000207005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSemaphoreSignalInfo_self(w, o);
}
function g_VkBufferDeviceAddressInfo(w, o)
{
    w.u32(1000244001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferDeviceAddressInfo_self(w, o);
}
function g_VkDeviceMemoryOpaqueCaptureAddressInfo(w, o)
{
    w.u32(1000257004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceMemoryOpaqueCaptureAddressInfo_self(w, o);
}
function g_VkCommandStreamDescriptionMESA(w, o)
{
    w.u32(o.resourceId);
    w.u64(o.offset);
    w.u64(o.size);
}
function g_VkCommandStreamDependencyMESA(w, o)
{
    w.u32(o.srcCommandStream);
    w.u32(o.dstCommandStream);
}
function g_VkImageDrmFormatModifierPropertiesEXT_partial(w, o)
{
    w.u32(1000158005);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkImageDrmFormatModifierPropertiesEXT_self_partial(w, o);
}
function h_VkImageDrmFormatModifierPropertiesEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkImageDrmFormatModifierPropertiesEXT_self(r, o);
    return o;
}
function g_VkRingCreateInfoMESA(w, o)
{
    w.u32(1000384000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRingCreateInfoMESA_self(w, o);
}
function g_VkMemoryResourcePropertiesMESA_partial(w, o)
{
    w.u32(1000384001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkMemoryResourcePropertiesMESA_self_partial(w, o);
}
function h_VkMemoryResourcePropertiesMESA(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkMemoryResourcePropertiesMESA_self(r, o);
    return o;
}
function g_VkPhysicalDeviceToolProperties_partial(w, o)
{
    w.u32(1000245000);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceToolProperties_self_partial(w, o);
}
function h_VkPhysicalDeviceToolProperties(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceToolProperties_self(r, o);
    return o;
}
function g_VkPrivateDataSlotCreateInfo(w, o)
{
    w.u32(1000295002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPrivateDataSlotCreateInfo_self(w, o);
}
function g_VkDependencyInfo(w, o)
{
    w.u32(1000314003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDependencyInfo_self(w, o);
}
function g_VkSubmitInfo2(w, o)
{
    w.u32(1000314004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubmitInfo2_self(w, o);
}
function g_VkCopyBufferInfo2(w, o)
{
    w.u32(1000337000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyBufferInfo2_self(w, o);
}
function g_VkCopyImageInfo2(w, o)
{
    w.u32(1000337001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyImageInfo2_self(w, o);
}
function g_VkCopyBufferToImageInfo2(w, o)
{
    w.u32(1000337002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyBufferToImageInfo2_self(w, o);
}
function g_VkCopyImageToBufferInfo2(w, o)
{
    w.u32(1000337003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyImageToBufferInfo2_self(w, o);
}
function g_VkBlitImageInfo2(w, o)
{
    w.u32(1000337004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBlitImageInfo2_self(w, o);
}
function g_VkResolveImageInfo2(w, o)
{
    w.u32(1000337005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkResolveImageInfo2_self(w, o);
}
function g_VkRenderingInfo(w, o)
{
    w.u32(1000044000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderingInfo_self(w, o);
}
function g_VkDeviceBufferMemoryRequirements(w, o)
{
    w.u32(1000413002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceBufferMemoryRequirements_self(w, o);
}
function g_VkDeviceImageMemoryRequirements(w, o)
{
    w.u32(1000413003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceImageMemoryRequirements_self(w, o);
}
function g_VkCalibratedTimestampInfoKHR(w, o)
{
    w.u32(1000184000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCalibratedTimestampInfoKHR_self(w, o);
}
function g_VkConditionalRenderingBeginInfoEXT(w, o)
{
    w.u32(1000081002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkConditionalRenderingBeginInfoEXT_self(w, o);
}
function g_VkImportSemaphoreResourceInfoMESA(w, o)
{
    w.u32(1000384004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImportSemaphoreResourceInfoMESA_self(w, o);
}
function g_VkMultiDrawInfoEXT(w, o)
{
    w.u32(o.firstVertex);
    w.u32(o.vertexCount);
}
function g_VkMultiDrawIndexedInfoEXT(w, o)
{
    w.u32(o.firstIndex);
    w.u32(o.indexCount);
    w.i32(o.vertexOffset);
}
function g_VkVertexInputBindingDescription2EXT(w, o)
{
    w.u32(1000352001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkVertexInputBindingDescription2EXT_self(w, o);
}
function g_VkVertexInputAttributeDescription2EXT(w, o)
{
    w.u32(1000352002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkVertexInputAttributeDescription2EXT_self(w, o);
}
function g_VkColorBlendEquationEXT(w, o)
{
    w.i32(o.srcColorBlendFactor);
    w.i32(o.dstColorBlendFactor);
    w.i32(o.colorBlendOp);
    w.i32(o.srcAlphaBlendFactor);
    w.i32(o.dstAlphaBlendFactor);
    w.i32(o.alphaBlendOp);
}
function g_VkColorBlendAdvancedEXT(w, o)
{
    w.i32(o.advancedBlendOp);
    w.u32(o.srcPremultiplied);
    w.u32(o.dstPremultiplied);
    w.i32(o.blendOverlap);
    w.u32(o.clampResults);
}
function g_VkPhysicalDeviceFragmentShadingRateKHR_partial(w, o)
{
    w.u32(1000226004);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkPhysicalDeviceFragmentShadingRateKHR_self_partial(w, o);
}
function h_VkPhysicalDeviceFragmentShadingRateKHR(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkPhysicalDeviceFragmentShadingRateKHR_self(r, o);
    return o;
}
function g_VkExtent2D(w, o)
{
    w.u32(o.width);
    w.u32(o.height);
}
function g_VkRenderingAreaInfo(w, o)
{
    w.u32(1000470003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderingAreaInfo_self(w, o);
}
function g_VkDeviceImageSubresourceInfo(w, o)
{
    w.u32(1000470004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceImageSubresourceInfo_self(w, o);
}
function g_VkSubresourceLayout2_partial(w, o)
{
    w.u32(1000338002);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkSubresourceLayout2_self_partial(w, o);
}
function h_VkSubresourceLayout2(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkSubresourceLayout2_self(r, o);
    return o;
}
function g_VkImageSubresource2(w, o)
{
    w.u32(1000338003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageSubresource2_self(w, o);
}
function g_VkSampleLocationsInfoEXT(w, o)
{
    w.u32(1000143000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSampleLocationsInfoEXT_self(w, o);
}
function g_VkMultisamplePropertiesEXT_partial(w, o)
{
    w.u32(1000143004);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkMultisamplePropertiesEXT_self_partial(w, o);
}
function h_VkMultisamplePropertiesEXT(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkMultisamplePropertiesEXT_self(r, o);
    return o;
}
function g_VkMemoryUnmapInfo(w, o)
{
    w.u32(1000271001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMemoryUnmapInfo_self(w, o);
}
function g_VkRenderingAttachmentLocationInfo(w, o)
{
    w.u32(1000232001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderingAttachmentLocationInfo_self(w, o);
}
function g_VkRenderingInputAttachmentIndexInfo(w, o)
{
    w.u32(1000232002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderingInputAttachmentIndexInfo_self(w, o);
}
function g_VkBindDescriptorSetsInfo(w, o)
{
    w.u32(1000545003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBindDescriptorSetsInfo_self(w, o);
}
function g_VkPushConstantsInfo(w, o)
{
    w.u32(1000545004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPushConstantsInfo_self(w, o);
}
function g_VkPushDescriptorSetInfo(w, o)
{
    w.u32(1000545005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPushDescriptorSetInfo_self(w, o);
}
function g_VkCopyImageToImageInfo(w, o)
{
    w.u32(1000270007);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyImageToImageInfo_self(w, o);
}
function g_VkHostImageLayoutTransitionInfo(w, o)
{
    w.u32(1000270006);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkHostImageLayoutTransitionInfo_self(w, o);
}
function g_VkCopyImageToMemoryInfoMESA(w, o)
{
    w.u32(1000384008);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyImageToMemoryInfoMESA_self(w, o);
}
function g_VkCopyMemoryToImageInfoMESA(w, o)
{
    w.u32(1000384010);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCopyMemoryToImageInfoMESA_self(w, o);
}
function g_VkDepthBiasInfoEXT(w, o)
{
    w.u32(1000283001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDepthBiasInfoEXT_self(w, o);
}
function g_VkDepthClampRangeEXT(w, o)
{
    w.f32(o.minDepthClamp);
    w.f32(o.maxDepthClamp);
}
function g_VkCooperativeMatrixPropertiesKHR_partial(w, o)
{
    w.u32(1000506001);
    w.pnext(o.pNext, GUEST_PNEXT_PARTIAL);
    g_VkCooperativeMatrixPropertiesKHR_self_partial(w, o);
}
function h_VkCooperativeMatrixPropertiesKHR(r)
{
    const o = {};
    o.sType = r.u32();
    o.pNext = r.pnext(GUEST_PNEXT_REPLY);
    h_VkCooperativeMatrixPropertiesKHR_self(r, o);
    return o;
}
function g_VkResourceDescriptorInfoEXT(w, o)
{
    w.u32(1000135002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkResourceDescriptorInfoEXT_self(w, o);
}
function g_VkBindHeapInfoEXT(w, o)
{
    w.u32(1000135003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBindHeapInfoEXT_self(w, o);
}
function g_VkPushDataInfoEXT(w, o)
{
    w.u32(1000135004);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPushDataInfoEXT_self(w, o);
}
function g_VkHostAddressRangeEXT_partial(w, o)
{
    w.u64(o.size);
    w.size(o.address ? o.size : 0);
}
function h_VkHostAddressRangeEXT(r)
{
    const o = {};
    o.size = r.u64();
    if(r.peek_size())
    {
        const array_size = r.size();
        o.address = r.blob(array_size);
    }
    else
    {
        r.size();
        o.address = null;
    }
    return o;
}
function g_VkSamplerCustomBorderColorCreateInfoEXT(w, o)
{
    w.u32(1000287000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSamplerCustomBorderColorCreateInfoEXT_self(w, o);
}
function g_VkSampleLocationEXT(w, o)
{
    w.f32(o.x);
    w.f32(o.y);
}
function g_VkAttachmentSampleLocationsEXT(w, o)
{
    w.u32(o.attachmentIndex);
    g_VkSampleLocationsInfoEXT(w, o.sampleLocationsInfo || EMPTY);
}
function g_VkSubpassSampleLocationsEXT(w, o)
{
    w.u32(o.subpassIndex);
    g_VkSampleLocationsInfoEXT(w, o.sampleLocationsInfo || EMPTY);
}
function g_VkPushConstantRange(w, o)
{
    w.u32(o.stageFlags);
    w.u32(o.offset);
    w.u32(o.size);
}
function g_VkMutableDescriptorTypeListEXT(w, o)
{
    w.u32(o.descriptorTypeCount);
    if(o.pDescriptorTypes)
    {
        w.size(o.descriptorTypeCount);
        w.i32s(o.pDescriptorTypes, o.descriptorTypeCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkPhysicalDeviceFeatures(w, o)
{
    w.u32(o.robustBufferAccess);
    w.u32(o.fullDrawIndexUint32);
    w.u32(o.imageCubeArray);
    w.u32(o.independentBlend);
    w.u32(o.geometryShader);
    w.u32(o.tessellationShader);
    w.u32(o.sampleRateShading);
    w.u32(o.dualSrcBlend);
    w.u32(o.logicOp);
    w.u32(o.multiDrawIndirect);
    w.u32(o.drawIndirectFirstInstance);
    w.u32(o.depthClamp);
    w.u32(o.depthBiasClamp);
    w.u32(o.fillModeNonSolid);
    w.u32(o.depthBounds);
    w.u32(o.wideLines);
    w.u32(o.largePoints);
    w.u32(o.alphaToOne);
    w.u32(o.multiViewport);
    w.u32(o.samplerAnisotropy);
    w.u32(o.textureCompressionETC2);
    w.u32(o.textureCompressionASTC_LDR);
    w.u32(o.textureCompressionBC);
    w.u32(o.occlusionQueryPrecise);
    w.u32(o.pipelineStatisticsQuery);
    w.u32(o.vertexPipelineStoresAndAtomics);
    w.u32(o.fragmentStoresAndAtomics);
    w.u32(o.shaderTessellationAndGeometryPointSize);
    w.u32(o.shaderImageGatherExtended);
    w.u32(o.shaderStorageImageExtendedFormats);
    w.u32(o.shaderStorageImageMultisample);
    w.u32(o.shaderStorageImageReadWithoutFormat);
    w.u32(o.shaderStorageImageWriteWithoutFormat);
    w.u32(o.shaderUniformBufferArrayDynamicIndexing);
    w.u32(o.shaderSampledImageArrayDynamicIndexing);
    w.u32(o.shaderStorageBufferArrayDynamicIndexing);
    w.u32(o.shaderStorageImageArrayDynamicIndexing);
    w.u32(o.shaderClipDistance);
    w.u32(o.shaderCullDistance);
    w.u32(o.shaderFloat64);
    w.u32(o.shaderInt64);
    w.u32(o.shaderInt16);
    w.u32(o.shaderResourceResidency);
    w.u32(o.shaderResourceMinLod);
    w.u32(o.sparseBinding);
    w.u32(o.sparseResidencyBuffer);
    w.u32(o.sparseResidencyImage2D);
    w.u32(o.sparseResidencyImage3D);
    w.u32(o.sparseResidency2Samples);
    w.u32(o.sparseResidency4Samples);
    w.u32(o.sparseResidency8Samples);
    w.u32(o.sparseResidency16Samples);
    w.u32(o.sparseResidencyAliased);
    w.u32(o.variableMultisampleRate);
    w.u32(o.inheritedQueries);
}
function g_VkFramebufferAttachmentImageInfo(w, o)
{
    w.u32(1000108002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkFramebufferAttachmentImageInfo_self(w, o);
}
function g_VkSubresourceLayout(w, o)
{
    w.u64(o.offset);
    w.u64(o.size);
    w.u64(o.rowPitch);
    w.u64(o.arrayPitch);
    w.u64(o.depthPitch);
}
function g_VkHostAddressRangeConstEXT(w, o)
{
    w.u64(o.size);
    if(o.address)
    {
        w.size(o.size);
        w.blob(o.address, o.size);
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorSetAndBindingMappingEXT(w, o)
{
    w.u32(1000135005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDescriptorSetAndBindingMappingEXT_self(w, o);
}
function g_VkVertexInputBindingDivisorDescription(w, o)
{
    w.u32(o.binding);
    w.u32(o.divisor);
}
function g_VkPipelineCreationFeedback(w, o)
{
    w.u32(o.flags);
    w.u64(o.duration);
}
function g_VkInputAttachmentAspectReference(w, o)
{
    w.u32(o.subpass);
    w.u32(o.inputAttachmentIndex);
    w.u32(o.aspectMask);
}
function g_VkAttachmentReference2(w, o)
{
    w.u32(1000109001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkAttachmentReference2_self(w, o);
}
function g_VkComponentMapping(w, o)
{
    w.i32(o.r);
    w.i32(o.g);
    w.i32(o.b);
    w.i32(o.a);
}
function g_VkConformanceVersion_partial(w, o)
{
}
function g_VkDrmFormatModifierPropertiesEXT_partial(w, o)
{
}
function g_VkDrmFormatModifierProperties2EXT_partial(w, o)
{
}
function g_VkExternalMemoryProperties_partial(w, o)
{
}
function h_VkConformanceVersion(r)
{
    const o = {};
    o.major = r.u8();
    o.minor = r.u8();
    o.subminor = r.u8();
    o.patch = r.u8();
    return o;
}
function h_VkDrmFormatModifierPropertiesEXT(r)
{
    const o = {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u32();
    return o;
}
function h_VkDrmFormatModifierProperties2EXT(r)
{
    const o = {};
    o.drmFormatModifier = r.u64();
    o.drmFormatModifierPlaneCount = r.u32();
    o.drmFormatModifierTilingFeatures = r.u64();
    return o;
}
function h_VkExternalMemoryProperties(r)
{
    const o = {};
    o.externalMemoryFeatures = r.u32();
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    return o;
}
function g_VkInstanceCreateInfo_self(w, o)
{
    w.u32(o.flags);
    if(o.pApplicationInfo != null)
    {
        w.u64(1);
        g_VkApplicationInfo(w, o.pApplicationInfo || EMPTY);
    }
    else w.u64(0);
    w.u32(o.enabledLayerCount);
    if(o.ppEnabledLayerNames)
    {
        w.size(o.enabledLayerCount);
        for(let i = 0; i < o.enabledLayerCount; i++)
        {
            const string_size = (o.ppEnabledLayerNames || EMPTY)[i].length + 1;
            w.size(string_size);
            w.str((o.ppEnabledLayerNames || EMPTY)[i], string_size);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.enabledExtensionCount);
    if(o.ppEnabledExtensionNames)
    {
        w.size(o.enabledExtensionCount);
        for(let i = 0; i < o.enabledExtensionCount; i++)
        {
            const string_size = (o.ppEnabledExtensionNames || EMPTY)[i].length + 1;
            w.size(string_size);
            w.str((o.ppEnabledExtensionNames || EMPTY)[i], string_size);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkExtent3D_partial(w, o)
{
}
function h_VkExtent3D(r)
{
    const o = {};
    o.width = r.u32();
    o.height = r.u32();
    o.depth = r.u32();
    return o;
}
function g_VkPhysicalDeviceLimits_partial(w, o)
{
}
function g_VkPhysicalDeviceSparseProperties_partial(w, o)
{
}
function h_VkPhysicalDeviceLimits(r)
{
    const o = {};
    o.maxImageDimension1D = r.u32();
    o.maxImageDimension2D = r.u32();
    o.maxImageDimension3D = r.u32();
    o.maxImageDimensionCube = r.u32();
    o.maxImageArrayLayers = r.u32();
    o.maxTexelBufferElements = r.u32();
    o.maxUniformBufferRange = r.u32();
    o.maxStorageBufferRange = r.u32();
    o.maxPushConstantsSize = r.u32();
    o.maxMemoryAllocationCount = r.u32();
    o.maxSamplerAllocationCount = r.u32();
    o.bufferImageGranularity = r.u64();
    o.sparseAddressSpaceSize = r.u64();
    o.maxBoundDescriptorSets = r.u32();
    o.maxPerStageDescriptorSamplers = r.u32();
    o.maxPerStageDescriptorUniformBuffers = r.u32();
    o.maxPerStageDescriptorStorageBuffers = r.u32();
    o.maxPerStageDescriptorSampledImages = r.u32();
    o.maxPerStageDescriptorStorageImages = r.u32();
    o.maxPerStageDescriptorInputAttachments = r.u32();
    o.maxPerStageResources = r.u32();
    o.maxDescriptorSetSamplers = r.u32();
    o.maxDescriptorSetUniformBuffers = r.u32();
    o.maxDescriptorSetUniformBuffersDynamic = r.u32();
    o.maxDescriptorSetStorageBuffers = r.u32();
    o.maxDescriptorSetStorageBuffersDynamic = r.u32();
    o.maxDescriptorSetSampledImages = r.u32();
    o.maxDescriptorSetStorageImages = r.u32();
    o.maxDescriptorSetInputAttachments = r.u32();
    o.maxVertexInputAttributes = r.u32();
    o.maxVertexInputBindings = r.u32();
    o.maxVertexInputAttributeOffset = r.u32();
    o.maxVertexInputBindingStride = r.u32();
    o.maxVertexOutputComponents = r.u32();
    o.maxTessellationGenerationLevel = r.u32();
    o.maxTessellationPatchSize = r.u32();
    o.maxTessellationControlPerVertexInputComponents = r.u32();
    o.maxTessellationControlPerVertexOutputComponents = r.u32();
    o.maxTessellationControlPerPatchOutputComponents = r.u32();
    o.maxTessellationControlTotalOutputComponents = r.u32();
    o.maxTessellationEvaluationInputComponents = r.u32();
    o.maxTessellationEvaluationOutputComponents = r.u32();
    o.maxGeometryShaderInvocations = r.u32();
    o.maxGeometryInputComponents = r.u32();
    o.maxGeometryOutputComponents = r.u32();
    o.maxGeometryOutputVertices = r.u32();
    o.maxGeometryTotalOutputComponents = r.u32();
    o.maxFragmentInputComponents = r.u32();
    o.maxFragmentOutputAttachments = r.u32();
    o.maxFragmentDualSrcAttachments = r.u32();
    o.maxFragmentCombinedOutputResources = r.u32();
    o.maxComputeSharedMemorySize = r.u32();
    {
        const array_size = r.size();
        o.maxComputeWorkGroupCount = r.u32s(array_size);
    }
    o.maxComputeWorkGroupInvocations = r.u32();
    {
        const array_size = r.size();
        o.maxComputeWorkGroupSize = r.u32s(array_size);
    }
    o.subPixelPrecisionBits = r.u32();
    o.subTexelPrecisionBits = r.u32();
    o.mipmapPrecisionBits = r.u32();
    o.maxDrawIndexedIndexValue = r.u32();
    o.maxDrawIndirectCount = r.u32();
    o.maxSamplerLodBias = r.f32();
    o.maxSamplerAnisotropy = r.f32();
    o.maxViewports = r.u32();
    {
        const array_size = r.size();
        o.maxViewportDimensions = r.u32s(array_size);
    }
    {
        const array_size = r.size();
        o.viewportBoundsRange = r.f32s(array_size);
    }
    o.viewportSubPixelBits = r.u32();
    o.minMemoryMapAlignment = r.u64();
    o.minTexelBufferOffsetAlignment = r.u64();
    o.minUniformBufferOffsetAlignment = r.u64();
    o.minStorageBufferOffsetAlignment = r.u64();
    o.minTexelOffset = r.i32();
    o.maxTexelOffset = r.u32();
    o.minTexelGatherOffset = r.i32();
    o.maxTexelGatherOffset = r.u32();
    o.minInterpolationOffset = r.f32();
    o.maxInterpolationOffset = r.f32();
    o.subPixelInterpolationOffsetBits = r.u32();
    o.maxFramebufferWidth = r.u32();
    o.maxFramebufferHeight = r.u32();
    o.maxFramebufferLayers = r.u32();
    o.framebufferColorSampleCounts = r.u32();
    o.framebufferDepthSampleCounts = r.u32();
    o.framebufferStencilSampleCounts = r.u32();
    o.framebufferNoAttachmentsSampleCounts = r.u32();
    o.maxColorAttachments = r.u32();
    o.sampledImageColorSampleCounts = r.u32();
    o.sampledImageIntegerSampleCounts = r.u32();
    o.sampledImageDepthSampleCounts = r.u32();
    o.sampledImageStencilSampleCounts = r.u32();
    o.storageImageSampleCounts = r.u32();
    o.maxSampleMaskWords = r.u32();
    o.timestampComputeAndGraphics = r.u32();
    o.timestampPeriod = r.f32();
    o.maxClipDistances = r.u32();
    o.maxCullDistances = r.u32();
    o.maxCombinedClipAndCullDistances = r.u32();
    o.discreteQueuePriorities = r.u32();
    {
        const array_size = r.size();
        o.pointSizeRange = r.f32s(array_size);
    }
    {
        const array_size = r.size();
        o.lineWidthRange = r.f32s(array_size);
    }
    o.pointSizeGranularity = r.f32();
    o.lineWidthGranularity = r.f32();
    o.strictLines = r.u32();
    o.standardSampleLocations = r.u32();
    o.optimalBufferCopyOffsetAlignment = r.u64();
    o.optimalBufferCopyRowPitchAlignment = r.u64();
    o.nonCoherentAtomSize = r.u64();
    return o;
}
function h_VkPhysicalDeviceSparseProperties(r)
{
    const o = {};
    o.residencyStandard2DBlockShape = r.u32();
    o.residencyStandard2DMultisampleBlockShape = r.u32();
    o.residencyStandard3DBlockShape = r.u32();
    o.residencyAlignedMipSize = r.u32();
    o.residencyNonResidentStrict = r.u32();
    return o;
}
function g_VkMemoryType_partial(w, o)
{
}
function g_VkMemoryHeap_partial(w, o)
{
}
function h_VkMemoryType(r)
{
    const o = {};
    o.propertyFlags = r.u32();
    o.heapIndex = r.u32();
    return o;
}
function h_VkMemoryHeap(r)
{
    const o = {};
    o.size = r.u64();
    o.flags = r.u32();
    return o;
}
function g_VkDeviceCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.queueCreateInfoCount);
    if(o.pQueueCreateInfos)
    {
        w.size(o.queueCreateInfoCount);
        for(let i = 0; i < o.queueCreateInfoCount; i++)
        {
            g_VkDeviceQueueCreateInfo(w, (o.pQueueCreateInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.enabledLayerCount);
    if(o.ppEnabledLayerNames)
    {
        w.size(o.enabledLayerCount);
        for(let i = 0; i < o.enabledLayerCount; i++)
        {
            const string_size = (o.ppEnabledLayerNames || EMPTY)[i].length + 1;
            w.size(string_size);
            w.str((o.ppEnabledLayerNames || EMPTY)[i], string_size);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.enabledExtensionCount);
    if(o.ppEnabledExtensionNames)
    {
        w.size(o.enabledExtensionCount);
        for(let i = 0; i < o.enabledExtensionCount; i++)
        {
            const string_size = (o.ppEnabledExtensionNames || EMPTY)[i].length + 1;
            w.size(string_size);
            w.str((o.ppEnabledExtensionNames || EMPTY)[i], string_size);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pEnabledFeatures != null)
    {
        w.u64(1);
        g_VkPhysicalDeviceFeatures(w, o.pEnabledFeatures || EMPTY);
    }
    else w.u64(0);
}
function g_VkSubmitInfo_self(w, o)
{
    w.u32(o.waitSemaphoreCount);
    if(o.pWaitSemaphores)
    {
        w.size(o.waitSemaphoreCount);
        for(let i = 0; i < o.waitSemaphoreCount; i++)
        {
            w.h((o.pWaitSemaphores || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pWaitDstStageMask)
    {
        w.size(o.waitSemaphoreCount);
        for(let i = 0; i < o.waitSemaphoreCount; i++)
        {
            w.u32((o.pWaitDstStageMask || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.commandBufferCount);
    if(o.pCommandBuffers)
    {
        w.size(o.commandBufferCount);
        for(let i = 0; i < o.commandBufferCount; i++)
        {
            w.h((o.pCommandBuffers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.signalSemaphoreCount);
    if(o.pSignalSemaphores)
    {
        w.size(o.signalSemaphoreCount);
        for(let i = 0; i < o.signalSemaphoreCount; i++)
        {
            w.h((o.pSignalSemaphores || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkMemoryAllocateInfo_self(w, o)
{
    w.u64(o.allocationSize);
    w.u32(o.memoryTypeIndex);
}
function g_VkMappedMemoryRange_self(w, o)
{
    w.h(o.memory);
    w.u64(o.offset);
    w.u64(o.size);
}
function g_VkBindSparseInfo_self(w, o)
{
    w.u32(o.waitSemaphoreCount);
    if(o.pWaitSemaphores)
    {
        w.size(o.waitSemaphoreCount);
        for(let i = 0; i < o.waitSemaphoreCount; i++)
        {
            w.h((o.pWaitSemaphores || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.bufferBindCount);
    if(o.pBufferBinds)
    {
        w.size(o.bufferBindCount);
        for(let i = 0; i < o.bufferBindCount; i++)
        {
            g_VkSparseBufferMemoryBindInfo(w, (o.pBufferBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.imageOpaqueBindCount);
    if(o.pImageOpaqueBinds)
    {
        w.size(o.imageOpaqueBindCount);
        for(let i = 0; i < o.imageOpaqueBindCount; i++)
        {
            g_VkSparseImageOpaqueMemoryBindInfo(w, (o.pImageOpaqueBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.imageBindCount);
    if(o.pImageBinds)
    {
        w.size(o.imageBindCount);
        for(let i = 0; i < o.imageBindCount; i++)
        {
            g_VkSparseImageMemoryBindInfo(w, (o.pImageBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.signalSemaphoreCount);
    if(o.pSignalSemaphores)
    {
        w.size(o.signalSemaphoreCount);
        for(let i = 0; i < o.signalSemaphoreCount; i++)
        {
            w.h((o.pSignalSemaphores || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkFenceCreateInfo_self(w, o)
{
    w.u32(o.flags);
}
function g_VkSemaphoreCreateInfo_self(w, o)
{
    w.u32(o.flags);
}
function g_VkEventCreateInfo_self(w, o)
{
    w.u32(o.flags);
}
function g_VkQueryPoolCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.queryType);
    w.u32(o.queryCount);
    w.u32(o.pipelineStatistics);
}
function g_VkBufferCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u64(o.size);
    w.u32(o.usage);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    if(o.sharingMode === 1)
    {
        w.size(o.queueFamilyIndexCount);
        w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkBufferViewCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.h(o.buffer);
    w.i32(o.format);
    w.u64(o.offset);
    w.u64(o.range);
}
function g_VkImageCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.imageType);
    w.i32(o.format);
    g_VkExtent3D(w, o.extent || EMPTY);
    w.u32(o.mipLevels);
    w.u32(o.arrayLayers);
    w.i32(o.samples);
    w.i32(o.tiling);
    w.u32(o.usage);
    w.i32(o.sharingMode);
    w.u32(o.queueFamilyIndexCount);
    if(o.sharingMode === 1)
    {
        w.size(o.queueFamilyIndexCount);
        w.u32s(o.pQueueFamilyIndices, o.queueFamilyIndexCount);
    }
    else
    {
        w.size(0);
    }
    w.i32(o.initialLayout);
}
function g_VkImageViewCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.h(o.image);
    w.i32(o.viewType);
    w.i32(o.format);
    g_VkComponentMapping(w, o.components || EMPTY);
    g_VkImageSubresourceRange(w, o.subresourceRange || EMPTY);
}
function g_VkPipelineCacheCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u64(o.initialDataSize);
    if(o.pInitialData)
    {
        w.size(o.initialDataSize);
        w.blob(o.pInitialData, o.initialDataSize);
    }
    else
    {
        w.size(0);
    }
}
function g_VkGraphicsPipelineCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.stageCount);
    if(o.pStages)
    {
        w.size(o.stageCount);
        for(let i = 0; i < o.stageCount; i++)
        {
            g_VkPipelineShaderStageCreateInfo(w, (o.pStages || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pVertexInputState != null)
    {
        w.u64(1);
        g_VkPipelineVertexInputStateCreateInfo(w, o.pVertexInputState || EMPTY);
    }
    else w.u64(0);
    if(o.pInputAssemblyState != null)
    {
        w.u64(1);
        g_VkPipelineInputAssemblyStateCreateInfo(w, o.pInputAssemblyState || EMPTY);
    }
    else w.u64(0);
    if(o.pTessellationState != null)
    {
        w.u64(1);
        g_VkPipelineTessellationStateCreateInfo(w, o.pTessellationState || EMPTY);
    }
    else w.u64(0);
    if(o.pViewportState != null)
    {
        w.u64(1);
        g_VkPipelineViewportStateCreateInfo(w, o.pViewportState || EMPTY);
    }
    else w.u64(0);
    if(o.pRasterizationState != null)
    {
        w.u64(1);
        g_VkPipelineRasterizationStateCreateInfo(w, o.pRasterizationState || EMPTY);
    }
    else w.u64(0);
    if(o.pMultisampleState != null)
    {
        w.u64(1);
        g_VkPipelineMultisampleStateCreateInfo(w, o.pMultisampleState || EMPTY);
    }
    else w.u64(0);
    if(o.pDepthStencilState != null)
    {
        w.u64(1);
        g_VkPipelineDepthStencilStateCreateInfo(w, o.pDepthStencilState || EMPTY);
    }
    else w.u64(0);
    if(o.pColorBlendState != null)
    {
        w.u64(1);
        g_VkPipelineColorBlendStateCreateInfo(w, o.pColorBlendState || EMPTY);
    }
    else w.u64(0);
    if(o.pDynamicState != null)
    {
        w.u64(1);
        g_VkPipelineDynamicStateCreateInfo(w, o.pDynamicState || EMPTY);
    }
    else w.u64(0);
    w.h(o.layout);
    w.h(o.renderPass);
    w.u32(o.subpass);
    w.h(o.basePipelineHandle);
    w.i32(o.basePipelineIndex);
}
function g_VkComputePipelineCreateInfo_self(w, o)
{
    w.u32(o.flags);
    g_VkPipelineShaderStageCreateInfo(w, o.stage || EMPTY);
    w.h(o.layout);
    w.h(o.basePipelineHandle);
    w.i32(o.basePipelineIndex);
}
function g_VkSamplerCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.magFilter);
    w.i32(o.minFilter);
    w.i32(o.mipmapMode);
    w.i32(o.addressModeU);
    w.i32(o.addressModeV);
    w.i32(o.addressModeW);
    w.f32(o.mipLodBias);
    w.u32(o.anisotropyEnable);
    w.f32(o.maxAnisotropy);
    w.u32(o.compareEnable);
    w.i32(o.compareOp);
    w.f32(o.minLod);
    w.f32(o.maxLod);
    w.i32(o.borderColor);
    w.u32(o.unnormalizedCoordinates);
}
function g_VkDescriptorSetLayoutCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.bindingCount);
    if(o.pBindings)
    {
        w.size(o.bindingCount);
        for(let i = 0; i < o.bindingCount; i++)
        {
            g_VkDescriptorSetLayoutBinding(w, (o.pBindings || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorPoolCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.maxSets);
    w.u32(o.poolSizeCount);
    if(o.pPoolSizes)
    {
        w.size(o.poolSizeCount);
        for(let i = 0; i < o.poolSizeCount; i++)
        {
            g_VkDescriptorPoolSize(w, (o.pPoolSizes || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorSetAllocateInfo_self(w, o)
{
    w.h(o.descriptorPool);
    w.u32(o.descriptorSetCount);
    if(o.pSetLayouts)
    {
        w.size(o.descriptorSetCount);
        for(let i = 0; i < o.descriptorSetCount; i++)
        {
            w.h((o.pSetLayouts || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkWriteDescriptorSet_self(w, o)
{
    w.h(o.dstSet);
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
    w.i32(o.descriptorType);
    if(o.pImageInfo)
    {
        w.size(o.descriptorCount);
        for(let i = 0; i < o.descriptorCount; i++)
        {
            g_VkDescriptorImageInfo(w, (o.pImageInfo || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pBufferInfo)
    {
        w.size(o.descriptorCount);
        for(let i = 0; i < o.descriptorCount; i++)
        {
            g_VkDescriptorBufferInfo(w, (o.pBufferInfo || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pTexelBufferView)
    {
        w.size(o.descriptorCount);
        for(let i = 0; i < o.descriptorCount; i++)
        {
            w.h((o.pTexelBufferView || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyDescriptorSet_self(w, o)
{
    w.h(o.srcSet);
    w.u32(o.srcBinding);
    w.u32(o.srcArrayElement);
    w.h(o.dstSet);
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
}
function g_VkFramebufferCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.h(o.renderPass);
    w.u32(o.attachmentCount);
    if(!(o.flags & 1))
    {
        w.size(o.attachmentCount);
        for(let i = 0; i < o.attachmentCount; i++)
        {
            w.h((o.pAttachments || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.layers);
}
function g_VkRenderPassCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.attachmentCount);
    if(o.pAttachments)
    {
        w.size(o.attachmentCount);
        for(let i = 0; i < o.attachmentCount; i++)
        {
            g_VkAttachmentDescription(w, (o.pAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.subpassCount);
    if(o.pSubpasses)
    {
        w.size(o.subpassCount);
        for(let i = 0; i < o.subpassCount; i++)
        {
            g_VkSubpassDescription(w, (o.pSubpasses || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.dependencyCount);
    if(o.pDependencies)
    {
        w.size(o.dependencyCount);
        for(let i = 0; i < o.dependencyCount; i++)
        {
            g_VkSubpassDependency(w, (o.pDependencies || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCommandPoolCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
}
function g_VkCommandBufferAllocateInfo_self(w, o)
{
    w.h(o.commandPool);
    w.i32(o.level);
    w.u32(o.commandBufferCount);
}
function g_VkCommandBufferBeginInfo_self(w, o)
{
    w.u32(o.flags);
    if(o.pInheritanceInfo != null)
    {
        w.u64(1);
        g_VkCommandBufferInheritanceInfo(w, o.pInheritanceInfo || EMPTY);
    }
    else w.u64(0);
}
function g_VkOffset2D(w, o)
{
    w.i32(o.x);
    w.i32(o.y);
}
function g_VkImageSubresourceLayers(w, o)
{
    w.u32(o.aspectMask);
    w.u32(o.mipLevel);
    w.u32(o.baseArrayLayer);
    w.u32(o.layerCount);
}
function g_VkOffset3D(w, o)
{
    w.i32(o.x);
    w.i32(o.y);
    w.i32(o.z);
}
function g_VkExtent3D(w, o)
{
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.depth);
}
function g_VkClearValue(w, o)
{
    const tag = o._tag !== undefined ? o._tag : 0;
    w.u32(tag);
    switch(tag)
    {
    case 0:
        g_VkClearColorValue(w, o.color || EMPTY);
        break;
    case 1:
        g_VkClearDepthStencilValue(w, o.depthStencil || EMPTY);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
}
function g_VkMemoryBarrier_self(w, o)
{
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
}
function g_VkBufferMemoryBarrier_self(w, o)
{
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.size);
}
function g_VkImageMemoryBarrier_self(w, o)
{
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.image);
    g_VkImageSubresourceRange(w, o.subresourceRange || EMPTY);
}
function g_VkRenderPassBeginInfo_self(w, o)
{
    w.h(o.renderPass);
    w.h(o.framebuffer);
    g_VkRect2D(w, o.renderArea || EMPTY);
    w.u32(o.clearValueCount);
    if(o.pClearValues)
    {
        w.size(o.clearValueCount);
        for(let i = 0; i < o.clearValueCount; i++)
        {
            g_VkClearValue(w, (o.pClearValues || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkBindBufferMemoryInfo_self(w, o)
{
    w.h(o.buffer);
    w.h(o.memory);
    w.u64(o.memoryOffset);
}
function g_VkBindImageMemoryInfo_self(w, o)
{
    w.h(o.image);
    w.h(o.memory);
    w.u64(o.memoryOffset);
}
function g_VkPhysicalDeviceGroupProperties_self_partial(w, o)
{
    w.size(32);
    for(let i = 0; i < 32; i++)
    {
        w.h((o.physicalDevices || EMPTY)[i]);
    }
}
function h_VkPhysicalDeviceGroupProperties_self(r, o)
{
    o.physicalDeviceCount = r.u32();
    {
        const iter_count = r.size();
        o.physicalDevices = new Array(iter_count);
        for(let i = 0; i < iter_count; i++)
        {
            o.physicalDevices[i] = r.h();
        }
    }
    o.subsetAllocation = r.u32();
}
function g_VkImageMemoryRequirementsInfo2_self(w, o)
{
    w.h(o.image);
}
function g_VkMemoryRequirements2_self_partial(w, o)
{
    g_VkMemoryRequirements_partial(w, o.memoryRequirements || EMPTY);
}
function h_VkMemoryRequirements2_self(r, o)
{
    o.memoryRequirements = h_VkMemoryRequirements(r);
}
function g_VkBufferMemoryRequirementsInfo2_self(w, o)
{
    w.h(o.buffer);
}
function g_VkImageSparseMemoryRequirementsInfo2_self(w, o)
{
    w.h(o.image);
}
function g_VkSparseImageMemoryRequirements2_self_partial(w, o)
{
    g_VkSparseImageMemoryRequirements_partial(w, o.memoryRequirements || EMPTY);
}
function h_VkSparseImageMemoryRequirements2_self(r, o)
{
    o.memoryRequirements = h_VkSparseImageMemoryRequirements(r);
}
function g_VkPhysicalDeviceFeatures2_self_partial(w, o)
{
    g_VkPhysicalDeviceFeatures_partial(w, o.features || EMPTY);
}
function h_VkPhysicalDeviceFeatures2_self(r, o)
{
    o.features = h_VkPhysicalDeviceFeatures(r);
}
function g_VkPhysicalDeviceProperties2_self_partial(w, o)
{
    g_VkPhysicalDeviceProperties_partial(w, o.properties || EMPTY);
}
function h_VkPhysicalDeviceProperties2_self(r, o)
{
    o.properties = h_VkPhysicalDeviceProperties(r);
}
function g_VkFormatProperties2_self_partial(w, o)
{
    g_VkFormatProperties_partial(w, o.formatProperties || EMPTY);
}
function h_VkFormatProperties2_self(r, o)
{
    o.formatProperties = h_VkFormatProperties(r);
}
function g_VkPhysicalDeviceImageFormatInfo2_self(w, o)
{
    w.i32(o.format);
    w.i32(o.type);
    w.i32(o.tiling);
    w.u32(o.usage);
    w.u32(o.flags);
}
function g_VkImageFormatProperties2_self_partial(w, o)
{
    g_VkImageFormatProperties_partial(w, o.imageFormatProperties || EMPTY);
}
function h_VkImageFormatProperties2_self(r, o)
{
    o.imageFormatProperties = h_VkImageFormatProperties(r);
}
function g_VkQueueFamilyProperties2_self_partial(w, o)
{
    g_VkQueueFamilyProperties_partial(w, o.queueFamilyProperties || EMPTY);
}
function h_VkQueueFamilyProperties2_self(r, o)
{
    o.queueFamilyProperties = h_VkQueueFamilyProperties(r);
}
function g_VkPhysicalDeviceMemoryProperties2_self_partial(w, o)
{
    g_VkPhysicalDeviceMemoryProperties_partial(w, o.memoryProperties || EMPTY);
}
function h_VkPhysicalDeviceMemoryProperties2_self(r, o)
{
    o.memoryProperties = h_VkPhysicalDeviceMemoryProperties(r);
}
function g_VkPhysicalDeviceSparseImageFormatInfo2_self(w, o)
{
    w.i32(o.format);
    w.i32(o.type);
    w.i32(o.samples);
    w.u32(o.usage);
    w.i32(o.tiling);
}
function g_VkSparseImageFormatProperties2_self_partial(w, o)
{
    g_VkSparseImageFormatProperties_partial(w, o.properties || EMPTY);
}
function h_VkSparseImageFormatProperties2_self(r, o)
{
    o.properties = h_VkSparseImageFormatProperties(r);
}
function g_VkDeviceQueueInfo2_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
    w.u32(o.queueIndex);
}
function g_VkSamplerYcbcrConversionCreateInfo_self(w, o)
{
    w.i32(o.format);
    w.i32(o.ycbcrModel);
    w.i32(o.ycbcrRange);
    g_VkComponentMapping(w, o.components || EMPTY);
    w.i32(o.xChromaOffset);
    w.i32(o.yChromaOffset);
    w.i32(o.chromaFilter);
    w.u32(o.forceExplicitReconstruction);
}
function g_VkDescriptorUpdateTemplateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.descriptorUpdateEntryCount);
    if(o.pDescriptorUpdateEntries)
    {
        w.size(o.descriptorUpdateEntryCount);
        for(let i = 0; i < o.descriptorUpdateEntryCount; i++)
        {
            g_VkDescriptorUpdateTemplateEntry(w, (o.pDescriptorUpdateEntries || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.i32(o.templateType);
    w.h(o.descriptorSetLayout);
    w.i32(o.pipelineBindPoint);
    w.h(o.pipelineLayout);
    w.u32(o.set);
}
function g_VkPhysicalDeviceExternalBufferInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.usage);
    w.i32(o.handleType);
}
function g_VkExternalBufferProperties_self_partial(w, o)
{
    g_VkExternalMemoryProperties_partial(w, o.externalMemoryProperties || EMPTY);
}
function h_VkExternalBufferProperties_self(r, o)
{
    o.externalMemoryProperties = h_VkExternalMemoryProperties(r);
}
function g_VkPhysicalDeviceExternalFenceInfo_self(w, o)
{
    w.i32(o.handleType);
}
function g_VkExternalFenceProperties_self_partial(w, o)
{
}
function h_VkExternalFenceProperties_self(r, o)
{
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalFenceFeatures = r.u32();
}
function g_VkPhysicalDeviceExternalSemaphoreInfo_self(w, o)
{
    w.i32(o.handleType);
}
function g_VkExternalSemaphoreProperties_self_partial(w, o)
{
}
function h_VkExternalSemaphoreProperties_self(r, o)
{
    o.exportFromImportedHandleTypes = r.u32();
    o.compatibleHandleTypes = r.u32();
    o.externalSemaphoreFeatures = r.u32();
}
function g_VkDescriptorSetLayoutSupport_self_partial(w, o)
{
}
function h_VkDescriptorSetLayoutSupport_self(r, o)
{
    o.supported = r.u32();
}
function g_VkRenderPassCreateInfo2_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.attachmentCount);
    if(o.pAttachments)
    {
        w.size(o.attachmentCount);
        for(let i = 0; i < o.attachmentCount; i++)
        {
            g_VkAttachmentDescription2(w, (o.pAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.subpassCount);
    if(o.pSubpasses)
    {
        w.size(o.subpassCount);
        for(let i = 0; i < o.subpassCount; i++)
        {
            g_VkSubpassDescription2(w, (o.pSubpasses || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.dependencyCount);
    if(o.pDependencies)
    {
        w.size(o.dependencyCount);
        for(let i = 0; i < o.dependencyCount; i++)
        {
            g_VkSubpassDependency2(w, (o.pDependencies || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.correlatedViewMaskCount);
    if(o.pCorrelatedViewMasks)
    {
        w.size(o.correlatedViewMaskCount);
        w.u32s(o.pCorrelatedViewMasks, o.correlatedViewMaskCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkSubpassBeginInfo_self(w, o)
{
    w.i32(o.contents);
}
function g_VkSubpassEndInfo_self(w, o)
{
}
function g_VkSemaphoreWaitInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.semaphoreCount);
    if(o.pSemaphores)
    {
        w.size(o.semaphoreCount);
        for(let i = 0; i < o.semaphoreCount; i++)
        {
            w.h((o.pSemaphores || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pValues)
    {
        w.size(o.semaphoreCount);
        w.u64s(o.pValues, o.semaphoreCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkSemaphoreSignalInfo_self(w, o)
{
    w.h(o.semaphore);
    w.u64(o.value);
}
function g_VkBufferDeviceAddressInfo_self(w, o)
{
    w.h(o.buffer);
}
function g_VkDeviceMemoryOpaqueCaptureAddressInfo_self(w, o)
{
    w.h(o.memory);
}
function g_VkImageDrmFormatModifierPropertiesEXT_self_partial(w, o)
{
}
function h_VkImageDrmFormatModifierPropertiesEXT_self(r, o)
{
    o.drmFormatModifier = r.u64();
}
function g_VkRingCreateInfoMESA_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.resourceId);
    w.u64(o.offset);
    w.u64(o.size);
    w.u64(o.idleTimeout);
    w.u64(o.headOffset);
    w.u64(o.tailOffset);
    w.u64(o.statusOffset);
    w.u64(o.bufferOffset);
    w.u64(o.bufferSize);
    w.u64(o.extraOffset);
    w.u64(o.extraSize);
}
function g_VkMemoryResourcePropertiesMESA_self_partial(w, o)
{
}
function h_VkMemoryResourcePropertiesMESA_self(r, o)
{
    o.memoryTypeBits = r.u32();
}
function g_VkPhysicalDeviceToolProperties_self_partial(w, o)
{
}
function h_VkPhysicalDeviceToolProperties_self(r, o)
{
    {
        const array_size = r.size();
        o.name = r.str(array_size);
    }
    {
        const array_size = r.size();
        o.version = r.str(array_size);
    }
    o.purposes = r.u32();
    {
        const array_size = r.size();
        o.description = r.str(array_size);
    }
    {
        const array_size = r.size();
        o.layer = r.str(array_size);
    }
}
function g_VkPrivateDataSlotCreateInfo_self(w, o)
{
    w.u32(o.flags);
}
function g_VkDependencyInfo_self(w, o)
{
    w.u32(o.dependencyFlags);
    w.u32(o.memoryBarrierCount);
    if(o.pMemoryBarriers)
    {
        w.size(o.memoryBarrierCount);
        for(let i = 0; i < o.memoryBarrierCount; i++)
        {
            g_VkMemoryBarrier2(w, (o.pMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.bufferMemoryBarrierCount);
    if(o.pBufferMemoryBarriers)
    {
        w.size(o.bufferMemoryBarrierCount);
        for(let i = 0; i < o.bufferMemoryBarrierCount; i++)
        {
            g_VkBufferMemoryBarrier2(w, (o.pBufferMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.imageMemoryBarrierCount);
    if(o.pImageMemoryBarriers)
    {
        w.size(o.imageMemoryBarrierCount);
        for(let i = 0; i < o.imageMemoryBarrierCount; i++)
        {
            g_VkImageMemoryBarrier2(w, (o.pImageMemoryBarriers || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkSubmitInfo2_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.waitSemaphoreInfoCount);
    if(o.pWaitSemaphoreInfos)
    {
        w.size(o.waitSemaphoreInfoCount);
        for(let i = 0; i < o.waitSemaphoreInfoCount; i++)
        {
            g_VkSemaphoreSubmitInfo(w, (o.pWaitSemaphoreInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.commandBufferInfoCount);
    if(o.pCommandBufferInfos)
    {
        w.size(o.commandBufferInfoCount);
        for(let i = 0; i < o.commandBufferInfoCount; i++)
        {
            g_VkCommandBufferSubmitInfo(w, (o.pCommandBufferInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.signalSemaphoreInfoCount);
    if(o.pSignalSemaphoreInfos)
    {
        w.size(o.signalSemaphoreInfoCount);
        for(let i = 0; i < o.signalSemaphoreInfoCount; i++)
        {
            g_VkSemaphoreSubmitInfo(w, (o.pSignalSemaphoreInfos || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyBufferInfo2_self(w, o)
{
    w.h(o.srcBuffer);
    w.h(o.dstBuffer);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkBufferCopy2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyImageInfo2_self(w, o)
{
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkImageCopy2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyBufferToImageInfo2_self(w, o)
{
    w.h(o.srcBuffer);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkBufferImageCopy2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyImageToBufferInfo2_self(w, o)
{
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstBuffer);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkBufferImageCopy2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkBlitImageInfo2_self(w, o)
{
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkImageBlit2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.i32(o.filter);
}
function g_VkResolveImageInfo2_self(w, o)
{
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkImageResolve2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkRenderingInfo_self(w, o)
{
    w.u32(o.flags);
    g_VkRect2D(w, o.renderArea || EMPTY);
    w.u32(o.layerCount);
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachments)
    {
        w.size(o.colorAttachmentCount);
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            g_VkRenderingAttachmentInfo(w, (o.pColorAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pDepthAttachment != null)
    {
        w.u64(1);
        g_VkRenderingAttachmentInfo(w, o.pDepthAttachment || EMPTY);
    }
    else w.u64(0);
    if(o.pStencilAttachment != null)
    {
        w.u64(1);
        g_VkRenderingAttachmentInfo(w, o.pStencilAttachment || EMPTY);
    }
    else w.u64(0);
}
function g_VkDeviceBufferMemoryRequirements_self(w, o)
{
    if(o.pCreateInfo != null)
    {
        w.u64(1);
        g_VkBufferCreateInfo(w, o.pCreateInfo || EMPTY);
    }
    else w.u64(0);
}
function g_VkDeviceImageMemoryRequirements_self(w, o)
{
    if(o.pCreateInfo != null)
    {
        w.u64(1);
        g_VkImageCreateInfo(w, o.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    w.i32(o.planeAspect);
}
function g_VkCalibratedTimestampInfoKHR_self(w, o)
{
    w.i32(o.timeDomain);
}
function g_VkConditionalRenderingBeginInfoEXT_self(w, o)
{
    w.h(o.buffer);
    w.u64(o.offset);
    w.u32(o.flags);
}
function g_VkImportSemaphoreResourceInfoMESA_self(w, o)
{
    w.h(o.semaphore);
    w.u32(o.resourceId);
}
function g_VkVertexInputBindingDescription2EXT_self(w, o)
{
    w.u32(o.binding);
    w.u32(o.stride);
    w.i32(o.inputRate);
    w.u32(o.divisor);
}
function g_VkVertexInputAttributeDescription2EXT_self(w, o)
{
    w.u32(o.location);
    w.u32(o.binding);
    w.i32(o.format);
    w.u32(o.offset);
}
function g_VkPhysicalDeviceFragmentShadingRateKHR_self_partial(w, o)
{
    g_VkExtent2D_partial(w, o.fragmentSize || EMPTY);
}
function h_VkPhysicalDeviceFragmentShadingRateKHR_self(r, o)
{
    o.sampleCounts = r.u32();
    o.fragmentSize = h_VkExtent2D(r);
}
function g_VkRenderingAreaInfo_self(w, o)
{
    w.u32(o.viewMask);
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachmentFormats)
    {
        w.size(o.colorAttachmentCount);
        w.i32s(o.pColorAttachmentFormats, o.colorAttachmentCount);
    }
    else
    {
        w.size(0);
    }
    w.i32(o.depthAttachmentFormat);
    w.i32(o.stencilAttachmentFormat);
}
function g_VkDeviceImageSubresourceInfo_self(w, o)
{
    if(o.pCreateInfo != null)
    {
        w.u64(1);
        g_VkImageCreateInfo(w, o.pCreateInfo || EMPTY);
    }
    else w.u64(0);
    if(o.pSubresource != null)
    {
        w.u64(1);
        g_VkImageSubresource2(w, o.pSubresource || EMPTY);
    }
    else w.u64(0);
}
function g_VkSubresourceLayout2_self_partial(w, o)
{
    g_VkSubresourceLayout_partial(w, o.subresourceLayout || EMPTY);
}
function h_VkSubresourceLayout2_self(r, o)
{
    o.subresourceLayout = h_VkSubresourceLayout(r);
}
function g_VkImageSubresource2_self(w, o)
{
    g_VkImageSubresource(w, o.imageSubresource || EMPTY);
}
function g_VkMultisamplePropertiesEXT_self_partial(w, o)
{
    g_VkExtent2D_partial(w, o.maxSampleLocationGridSize || EMPTY);
}
function h_VkMultisamplePropertiesEXT_self(r, o)
{
    o.maxSampleLocationGridSize = h_VkExtent2D(r);
}
function g_VkMemoryUnmapInfo_self(w, o)
{
    w.u32(o.flags);
    w.h(o.memory);
}
function g_VkBindDescriptorSetsInfo_self(w, o)
{
    w.u32(o.stageFlags);
    w.h(o.layout);
    w.u32(o.firstSet);
    w.u32(o.descriptorSetCount);
    if(o.pDescriptorSets)
    {
        w.size(o.descriptorSetCount);
        for(let i = 0; i < o.descriptorSetCount; i++)
        {
            w.h((o.pDescriptorSets || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.dynamicOffsetCount);
    if(o.pDynamicOffsets)
    {
        w.size(o.dynamicOffsetCount);
        w.u32s(o.pDynamicOffsets, o.dynamicOffsetCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkPushConstantsInfo_self(w, o)
{
    w.h(o.layout);
    w.u32(o.stageFlags);
    w.u32(o.offset);
    w.u32(o.size);
    if(o.pValues)
    {
        w.size(o.size);
        w.blob(o.pValues, o.size);
    }
    else
    {
        w.size(0);
    }
}
function g_VkPushDescriptorSetInfo_self(w, o)
{
    w.u32(o.stageFlags);
    w.h(o.layout);
    w.u32(o.set);
    w.u32(o.descriptorWriteCount);
    if(o.pDescriptorWrites)
    {
        w.size(o.descriptorWriteCount);
        for(let i = 0; i < o.descriptorWriteCount; i++)
        {
            g_VkWriteDescriptorSet(w, (o.pDescriptorWrites || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkCopyImageToImageInfo_self(w, o)
{
    w.u32(o.flags);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkImageCopy2(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkHostImageLayoutTransitionInfo_self(w, o)
{
    w.h(o.image);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    g_VkImageSubresourceRange(w, o.subresourceRange || EMPTY);
}
function g_VkCopyImageToMemoryInfoMESA_self(w, o)
{
    w.u32(o.flags);
    w.h(o.srcImage);
    w.i32(o.srcImageLayout);
    w.u32(o.memoryRowLength);
    w.u32(o.memoryImageHeight);
    g_VkImageSubresourceLayers(w, o.imageSubresource || EMPTY);
    g_VkOffset3D(w, o.imageOffset || EMPTY);
    g_VkExtent3D(w, o.imageExtent || EMPTY);
}
function g_VkCopyMemoryToImageInfoMESA_self(w, o)
{
    w.u32(o.flags);
    w.h(o.dstImage);
    w.i32(o.dstImageLayout);
    w.u32(o.regionCount);
    if(o.pRegions)
    {
        w.size(o.regionCount);
        for(let i = 0; i < o.regionCount; i++)
        {
            g_VkMemoryToImageCopyMESA(w, (o.pRegions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDepthBiasInfoEXT_self(w, o)
{
    w.f32(o.depthBiasConstantFactor);
    w.f32(o.depthBiasClamp);
    w.f32(o.depthBiasSlopeFactor);
}
function g_VkCooperativeMatrixPropertiesKHR_self_partial(w, o)
{
}
function h_VkCooperativeMatrixPropertiesKHR_self(r, o)
{
    o.MSize = r.u32();
    o.NSize = r.u32();
    o.KSize = r.u32();
    o.AType = r.i32();
    o.BType = r.i32();
    o.CType = r.i32();
    o.ResultType = r.i32();
    o.saturatingAccumulation = r.u32();
    o.scope = r.i32();
}
function g_VkResourceDescriptorInfoEXT_self(w, o)
{
    w.i32(o.type);
    g_VkResourceDescriptorDataEXT(w, o.data || EMPTY, o.type);
}
function g_VkBindHeapInfoEXT_self(w, o)
{
    g_VkDeviceAddressRangeEXT(w, o.heapRange || EMPTY);
    w.u64(o.reservedRangeOffset);
    w.u64(o.reservedRangeSize);
}
function g_VkPushDataInfoEXT_self(w, o)
{
    w.u32(o.offset);
    g_VkHostAddressRangeConstEXT(w, o.data || EMPTY);
}
function g_VkFramebufferAttachmentImageInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.usage);
    w.u32(o.width);
    w.u32(o.height);
    w.u32(o.layerCount);
    w.u32(o.viewFormatCount);
    if(o.pViewFormats)
    {
        w.size(o.viewFormatCount);
        w.i32s(o.pViewFormats, o.viewFormatCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorSetAndBindingMappingEXT_self(w, o)
{
    w.u32(o.descriptorSet);
    w.u32(o.firstBinding);
    w.u32(o.bindingCount);
    w.u32(o.resourceMask);
    w.i32(o.source);
    g_VkDescriptorMappingSourceDataEXT(w, o.sourceData || EMPTY, o.source);
}
function g_VkAttachmentReference2_self(w, o)
{
    w.u32(o.attachment);
    w.i32(o.layout);
    w.u32(o.aspectMask);
}
function g_VkApplicationInfo(w, o)
{
    w.u32(0);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkApplicationInfo_self(w, o);
}
function g_VkDeviceQueueCreateInfo(w, o)
{
    w.u32(2);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkDeviceQueueCreateInfo_self(w, o);
}
function g_VkSparseBufferMemoryBindInfo(w, o)
{
    w.h(o.buffer);
    w.u32(o.bindCount);
    if(o.pBinds)
    {
        w.size(o.bindCount);
        for(let i = 0; i < o.bindCount; i++)
        {
            g_VkSparseMemoryBind(w, (o.pBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkSparseImageOpaqueMemoryBindInfo(w, o)
{
    w.h(o.image);
    w.u32(o.bindCount);
    if(o.pBinds)
    {
        w.size(o.bindCount);
        for(let i = 0; i < o.bindCount; i++)
        {
            g_VkSparseMemoryBind(w, (o.pBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkSparseImageMemoryBindInfo(w, o)
{
    w.h(o.image);
    w.u32(o.bindCount);
    if(o.pBinds)
    {
        w.size(o.bindCount);
        for(let i = 0; i < o.bindCount; i++)
        {
            g_VkSparseImageMemoryBind(w, (o.pBinds || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineShaderStageCreateInfo(w, o)
{
    w.u32(18);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineShaderStageCreateInfo_self(w, o);
}
function g_VkPipelineVertexInputStateCreateInfo(w, o)
{
    w.u32(19);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineVertexInputStateCreateInfo_self(w, o);
}
function g_VkPipelineInputAssemblyStateCreateInfo(w, o)
{
    w.u32(20);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineInputAssemblyStateCreateInfo_self(w, o);
}
function g_VkPipelineTessellationStateCreateInfo(w, o)
{
    w.u32(21);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineTessellationStateCreateInfo_self(w, o);
}
function g_VkPipelineViewportStateCreateInfo(w, o)
{
    w.u32(22);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineViewportStateCreateInfo_self(w, o);
}
function g_VkPipelineRasterizationStateCreateInfo(w, o)
{
    w.u32(23);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineRasterizationStateCreateInfo_self(w, o);
}
function g_VkPipelineMultisampleStateCreateInfo(w, o)
{
    w.u32(24);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineMultisampleStateCreateInfo_self(w, o);
}
function g_VkPipelineDepthStencilStateCreateInfo(w, o)
{
    w.u32(25);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineDepthStencilStateCreateInfo_self(w, o);
}
function g_VkPipelineColorBlendStateCreateInfo(w, o)
{
    w.u32(26);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineColorBlendStateCreateInfo_self(w, o);
}
function g_VkPipelineDynamicStateCreateInfo(w, o)
{
    w.u32(27);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkPipelineDynamicStateCreateInfo_self(w, o);
}
function g_VkDescriptorSetLayoutBinding(w, o)
{
    w.u32(o.binding);
    w.i32(o.descriptorType);
    w.u32(o.descriptorCount);
    w.u32(o.stageFlags);
    if(o.pImmutableSamplers)
    {
        w.size(o.descriptorCount);
        for(let i = 0; i < o.descriptorCount; i++)
        {
            w.h((o.pImmutableSamplers || EMPTY)[i]);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkDescriptorPoolSize(w, o)
{
    w.i32(o.type);
    w.u32(o.descriptorCount);
}
function g_VkDescriptorImageInfo(w, o)
{
    w.h(o.sampler);
    w.h(o.imageView);
    w.i32(o.imageLayout);
}
function g_VkDescriptorBufferInfo(w, o)
{
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.range);
}
function g_VkAttachmentDescription(w, o)
{
    w.u32(o.flags);
    w.i32(o.format);
    w.i32(o.samples);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    w.i32(o.stencilLoadOp);
    w.i32(o.stencilStoreOp);
    w.i32(o.initialLayout);
    w.i32(o.finalLayout);
}
function g_VkSubpassDescription(w, o)
{
    w.u32(o.flags);
    w.i32(o.pipelineBindPoint);
    w.u32(o.inputAttachmentCount);
    if(o.pInputAttachments)
    {
        w.size(o.inputAttachmentCount);
        for(let i = 0; i < o.inputAttachmentCount; i++)
        {
            g_VkAttachmentReference(w, (o.pInputAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachments)
    {
        w.size(o.colorAttachmentCount);
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            g_VkAttachmentReference(w, (o.pColorAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pResolveAttachments)
    {
        w.size(o.colorAttachmentCount);
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            g_VkAttachmentReference(w, (o.pResolveAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pDepthStencilAttachment != null)
    {
        w.u64(1);
        g_VkAttachmentReference(w, o.pDepthStencilAttachment || EMPTY);
    }
    else w.u64(0);
    w.u32(o.preserveAttachmentCount);
    if(o.pPreserveAttachments)
    {
        w.size(o.preserveAttachmentCount);
        w.u32s(o.pPreserveAttachments, o.preserveAttachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkSubpassDependency(w, o)
{
    w.u32(o.srcSubpass);
    w.u32(o.dstSubpass);
    w.u32(o.srcStageMask);
    w.u32(o.dstStageMask);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.dependencyFlags);
}
function g_VkCommandBufferInheritanceInfo(w, o)
{
    w.u32(41);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCommandBufferInheritanceInfo_self(w, o);
}
function g_VkDescriptorUpdateTemplateEntry(w, o)
{
    w.u32(o.dstBinding);
    w.u32(o.dstArrayElement);
    w.u32(o.descriptorCount);
    w.i32(o.descriptorType);
    w.u64(o.offset);
    w.u64(o.stride);
}
function g_VkAttachmentDescription2(w, o)
{
    w.u32(1000109000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkAttachmentDescription2_self(w, o);
}
function g_VkSubpassDescription2(w, o)
{
    w.u32(1000109002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubpassDescription2_self(w, o);
}
function g_VkSubpassDependency2(w, o)
{
    w.u32(1000109003);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSubpassDependency2_self(w, o);
}
function g_VkMemoryBarrier2(w, o)
{
    w.u32(1000314000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMemoryBarrier2_self(w, o);
}
function g_VkBufferMemoryBarrier2(w, o)
{
    w.u32(1000314001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferMemoryBarrier2_self(w, o);
}
function g_VkImageMemoryBarrier2(w, o)
{
    w.u32(1000314002);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageMemoryBarrier2_self(w, o);
}
function g_VkSemaphoreSubmitInfo(w, o)
{
    w.u32(1000314005);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkSemaphoreSubmitInfo_self(w, o);
}
function g_VkCommandBufferSubmitInfo(w, o)
{
    w.u32(1000314006);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkCommandBufferSubmitInfo_self(w, o);
}
function g_VkBufferCopy2(w, o)
{
    w.u32(1000337006);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferCopy2_self(w, o);
}
function g_VkImageCopy2(w, o)
{
    w.u32(1000337007);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageCopy2_self(w, o);
}
function g_VkBufferImageCopy2(w, o)
{
    w.u32(1000337009);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkBufferImageCopy2_self(w, o);
}
function g_VkImageBlit2(w, o)
{
    w.u32(1000337008);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageBlit2_self(w, o);
}
function g_VkImageResolve2(w, o)
{
    w.u32(1000337010);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageResolve2_self(w, o);
}
function g_VkRenderingAttachmentInfo(w, o)
{
    w.u32(1000044001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkRenderingAttachmentInfo_self(w, o);
}
function g_VkMemoryToImageCopyMESA(w, o)
{
    w.u32(1000384009);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkMemoryToImageCopyMESA_self(w, o);
}
function g_VkResourceDescriptorDataEXT(w, o, tag)
{
    w.i32(tag);
    switch(tag)
    {
    case 2:
        if(o.pImage != null)
        {
            w.u64(1);
            g_VkImageDescriptorInfoEXT(w, o.pImage || EMPTY);
        }
        else w.u64(0);
        break;
    case 3:
        if(o.pImage != null)
        {
            w.u64(1);
            g_VkImageDescriptorInfoEXT(w, o.pImage || EMPTY);
        }
        else w.u64(0);
        break;
    case 10:
        if(o.pImage != null)
        {
            w.u64(1);
            g_VkImageDescriptorInfoEXT(w, o.pImage || EMPTY);
        }
        else w.u64(0);
        break;
    case 1000440001:
        if(o.pImage != null)
        {
            w.u64(1);
            g_VkImageDescriptorInfoEXT(w, o.pImage || EMPTY);
        }
        else w.u64(0);
        break;
    case 1000440000:
        if(o.pImage != null)
        {
            w.u64(1);
            g_VkImageDescriptorInfoEXT(w, o.pImage || EMPTY);
        }
        else w.u64(0);
        break;
    case 4:
        if(o.pTexelBuffer != null)
        {
            w.u64(1);
            g_VkTexelBufferDescriptorInfoEXT(w, o.pTexelBuffer || EMPTY);
        }
        else w.u64(0);
        break;
    case 5:
        if(o.pTexelBuffer != null)
        {
            w.u64(1);
            g_VkTexelBufferDescriptorInfoEXT(w, o.pTexelBuffer || EMPTY);
        }
        else w.u64(0);
        break;
    case 1000150000:
        if(o.pAddressRange != null)
        {
            w.u64(1);
            g_VkDeviceAddressRangeEXT(w, o.pAddressRange || EMPTY);
        }
        else w.u64(0);
        break;
    case 6:
        if(o.pAddressRange != null)
        {
            w.u64(1);
            g_VkDeviceAddressRangeEXT(w, o.pAddressRange || EMPTY);
        }
        else w.u64(0);
        break;
    case 7:
        if(o.pAddressRange != null)
        {
            w.u64(1);
            g_VkDeviceAddressRangeEXT(w, o.pAddressRange || EMPTY);
        }
        else w.u64(0);
        break;
    case 1000460000:
        if(o.pTensorARM != null)
        {
            w.u64(1);
            g_VkTensorViewCreateInfoARM(w, o.pTensorARM || EMPTY);
        }
        else w.u64(0);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
}
function g_VkDeviceAddressRangeEXT(w, o)
{
    w.u64(o.address);
    w.u64(o.size);
}
function g_VkDescriptorMappingSourceDataEXT(w, o, tag)
{
    w.i32(tag);
    switch(tag)
    {
    case 0:
        g_VkDescriptorMappingSourceConstantOffsetEXT(w, o.constantOffset || EMPTY);
        break;
    case 1:
        g_VkDescriptorMappingSourcePushIndexEXT(w, o.pushIndex || EMPTY);
        break;
    case 2:
        g_VkDescriptorMappingSourceIndirectIndexEXT(w, o.indirectIndex || EMPTY);
        break;
    case 3:
        g_VkDescriptorMappingSourceIndirectIndexArrayEXT(w, o.indirectIndexArray || EMPTY);
        break;
    case 4:
        g_VkDescriptorMappingSourceHeapDataEXT(w, o.heapData || EMPTY);
        break;
    case 5:
        w.u32(o.pushDataOffset);
        break;
    case 6:
        w.u32(o.pushAddressOffset);
        break;
    case 7:
        g_VkDescriptorMappingSourceIndirectAddressEXT(w, o.indirectAddress || EMPTY);
        break;
    case 8:
        g_VkDescriptorMappingSourceShaderRecordIndexEXT(w, o.shaderRecordIndex || EMPTY);
        break;
    case 9:
        w.u32(o.shaderRecordDataOffset);
        break;
    case 10:
        w.u32(o.shaderRecordAddressOffset);
        break;
    default:
        throw new Error("venus: bad union tag " + tag);
    }
}
function g_VkApplicationInfo_self(w, o)
{
    if(o.pApplicationName)
    {
        const string_size = o.pApplicationName.length + 1;
        w.size(string_size);
        w.str(o.pApplicationName, string_size);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.applicationVersion);
    if(o.pEngineName)
    {
        const string_size = o.pEngineName.length + 1;
        w.size(string_size);
        w.str(o.pEngineName, string_size);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.engineVersion);
    w.u32(o.apiVersion);
}
function g_VkDeviceQueueCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.queueFamilyIndex);
    w.u32(o.queueCount);
    if(o.pQueuePriorities)
    {
        w.size(o.queueCount);
        w.f32s(o.pQueuePriorities, o.queueCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkSparseMemoryBind(w, o)
{
    w.u64(o.resourceOffset);
    w.u64(o.size);
    w.h(o.memory);
    w.u64(o.memoryOffset);
    w.u32(o.flags);
}
function g_VkSparseImageMemoryBind(w, o)
{
    g_VkImageSubresource(w, o.subresource || EMPTY);
    g_VkOffset3D(w, o.offset || EMPTY);
    g_VkExtent3D(w, o.extent || EMPTY);
    w.h(o.memory);
    w.u64(o.memoryOffset);
    w.u32(o.flags);
}
function g_VkPipelineShaderStageCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.stage);
    w.h(o.module);
    if(o.pName)
    {
        const string_size = o.pName.length + 1;
        w.size(string_size);
        w.str(o.pName, string_size);
    }
    else
    {
        w.size(0);
    }
    if(o.pSpecializationInfo != null)
    {
        w.u64(1);
        g_VkSpecializationInfo(w, o.pSpecializationInfo || EMPTY);
    }
    else w.u64(0);
}
function g_VkPipelineVertexInputStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.vertexBindingDescriptionCount);
    if(o.pVertexBindingDescriptions)
    {
        w.size(o.vertexBindingDescriptionCount);
        for(let i = 0; i < o.vertexBindingDescriptionCount; i++)
        {
            g_VkVertexInputBindingDescription(w, (o.pVertexBindingDescriptions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.vertexAttributeDescriptionCount);
    if(o.pVertexAttributeDescriptions)
    {
        w.size(o.vertexAttributeDescriptionCount);
        for(let i = 0; i < o.vertexAttributeDescriptionCount; i++)
        {
            g_VkVertexInputAttributeDescription(w, (o.pVertexAttributeDescriptions || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineInputAssemblyStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.topology);
    w.u32(o.primitiveRestartEnable);
}
function g_VkPipelineTessellationStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.patchControlPoints);
}
function g_VkPipelineViewportStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.viewportCount);
    if(o.pViewports)
    {
        w.size(o.viewportCount);
        for(let i = 0; i < o.viewportCount; i++)
        {
            g_VkViewport(w, (o.pViewports || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.scissorCount);
    if(o.pScissors)
    {
        w.size(o.scissorCount);
        for(let i = 0; i < o.scissorCount; i++)
        {
            g_VkRect2D(w, (o.pScissors || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
}
function g_VkPipelineRasterizationStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.depthClampEnable);
    w.u32(o.rasterizerDiscardEnable);
    w.i32(o.polygonMode);
    w.u32(o.cullMode);
    w.i32(o.frontFace);
    w.u32(o.depthBiasEnable);
    w.f32(o.depthBiasConstantFactor);
    w.f32(o.depthBiasClamp);
    w.f32(o.depthBiasSlopeFactor);
    w.f32(o.lineWidth);
}
function g_VkPipelineMultisampleStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.rasterizationSamples);
    w.u32(o.sampleShadingEnable);
    w.f32(o.minSampleShading);
    if(o.pSampleMask)
    {
        w.size(Math.floor((o.rasterizationSamples + 31) / 32));
        w.u32s(o.pSampleMask, Math.floor((o.rasterizationSamples + 31) / 32));
    }
    else
    {
        w.size(0);
    }
    w.u32(o.alphaToCoverageEnable);
    w.u32(o.alphaToOneEnable);
}
function g_VkPipelineDepthStencilStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.depthTestEnable);
    w.u32(o.depthWriteEnable);
    w.i32(o.depthCompareOp);
    w.u32(o.depthBoundsTestEnable);
    w.u32(o.stencilTestEnable);
    g_VkStencilOpState(w, o.front || EMPTY);
    g_VkStencilOpState(w, o.back || EMPTY);
    w.f32(o.minDepthBounds);
    w.f32(o.maxDepthBounds);
}
function g_VkPipelineColorBlendStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.logicOpEnable);
    w.i32(o.logicOp);
    w.u32(o.attachmentCount);
    if(o.pAttachments)
    {
        w.size(o.attachmentCount);
        for(let i = 0; i < o.attachmentCount; i++)
        {
            g_VkPipelineColorBlendAttachmentState(w, (o.pAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.size(4);
    w.f32s(o.blendConstants, 4);
}
function g_VkPipelineDynamicStateCreateInfo_self(w, o)
{
    w.u32(o.flags);
    w.u32(o.dynamicStateCount);
    if(o.pDynamicStates)
    {
        w.size(o.dynamicStateCount);
        w.i32s(o.pDynamicStates, o.dynamicStateCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkAttachmentReference(w, o)
{
    w.u32(o.attachment);
    w.i32(o.layout);
}
function g_VkCommandBufferInheritanceInfo_self(w, o)
{
    w.h(o.renderPass);
    w.u32(o.subpass);
    w.h(o.framebuffer);
    w.u32(o.occlusionQueryEnable);
    w.u32(o.queryFlags);
    w.u32(o.pipelineStatistics);
}
function g_VkAttachmentDescription2_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.format);
    w.i32(o.samples);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    w.i32(o.stencilLoadOp);
    w.i32(o.stencilStoreOp);
    w.i32(o.initialLayout);
    w.i32(o.finalLayout);
}
function g_VkSubpassDescription2_self(w, o)
{
    w.u32(o.flags);
    w.i32(o.pipelineBindPoint);
    w.u32(o.viewMask);
    w.u32(o.inputAttachmentCount);
    if(o.pInputAttachments)
    {
        w.size(o.inputAttachmentCount);
        for(let i = 0; i < o.inputAttachmentCount; i++)
        {
            g_VkAttachmentReference2(w, (o.pInputAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u32(o.colorAttachmentCount);
    if(o.pColorAttachments)
    {
        w.size(o.colorAttachmentCount);
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            g_VkAttachmentReference2(w, (o.pColorAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pResolveAttachments)
    {
        w.size(o.colorAttachmentCount);
        for(let i = 0; i < o.colorAttachmentCount; i++)
        {
            g_VkAttachmentReference2(w, (o.pResolveAttachments || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    if(o.pDepthStencilAttachment != null)
    {
        w.u64(1);
        g_VkAttachmentReference2(w, o.pDepthStencilAttachment || EMPTY);
    }
    else w.u64(0);
    w.u32(o.preserveAttachmentCount);
    if(o.pPreserveAttachments)
    {
        w.size(o.preserveAttachmentCount);
        w.u32s(o.pPreserveAttachments, o.preserveAttachmentCount);
    }
    else
    {
        w.size(0);
    }
}
function g_VkSubpassDependency2_self(w, o)
{
    w.u32(o.srcSubpass);
    w.u32(o.dstSubpass);
    w.u32(o.srcStageMask);
    w.u32(o.dstStageMask);
    w.u32(o.srcAccessMask);
    w.u32(o.dstAccessMask);
    w.u32(o.dependencyFlags);
    w.i32(o.viewOffset);
}
function g_VkBufferMemoryBarrier2_self(w, o)
{
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.buffer);
    w.u64(o.offset);
    w.u64(o.size);
}
function g_VkImageMemoryBarrier2_self(w, o)
{
    w.u64(o.srcStageMask);
    w.u64(o.srcAccessMask);
    w.u64(o.dstStageMask);
    w.u64(o.dstAccessMask);
    w.i32(o.oldLayout);
    w.i32(o.newLayout);
    w.u32(o.srcQueueFamilyIndex);
    w.u32(o.dstQueueFamilyIndex);
    w.h(o.image);
    g_VkImageSubresourceRange(w, o.subresourceRange || EMPTY);
}
function g_VkSemaphoreSubmitInfo_self(w, o)
{
    w.h(o.semaphore);
    w.u64(o.value);
    w.u64(o.stageMask);
    w.u32(o.deviceIndex);
}
function g_VkCommandBufferSubmitInfo_self(w, o)
{
    w.h(o.commandBuffer);
    w.u32(o.deviceMask);
}
function g_VkBufferCopy2_self(w, o)
{
    w.u64(o.srcOffset);
    w.u64(o.dstOffset);
    w.u64(o.size);
}
function g_VkImageCopy2_self(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    g_VkOffset3D(w, o.srcOffset || EMPTY);
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    g_VkOffset3D(w, o.dstOffset || EMPTY);
    g_VkExtent3D(w, o.extent || EMPTY);
}
function g_VkBufferImageCopy2_self(w, o)
{
    w.u64(o.bufferOffset);
    w.u32(o.bufferRowLength);
    w.u32(o.bufferImageHeight);
    g_VkImageSubresourceLayers(w, o.imageSubresource || EMPTY);
    g_VkOffset3D(w, o.imageOffset || EMPTY);
    g_VkExtent3D(w, o.imageExtent || EMPTY);
}
function g_VkImageBlit2_self(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    w.size(2);
    for(let i = 0; i < 2; i++)
    {
        g_VkOffset3D(w, (o.srcOffsets || EMPTY)[i] || EMPTY);
    }
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    w.size(2);
    for(let i = 0; i < 2; i++)
    {
        g_VkOffset3D(w, (o.dstOffsets || EMPTY)[i] || EMPTY);
    }
}
function g_VkImageResolve2_self(w, o)
{
    g_VkImageSubresourceLayers(w, o.srcSubresource || EMPTY);
    g_VkOffset3D(w, o.srcOffset || EMPTY);
    g_VkImageSubresourceLayers(w, o.dstSubresource || EMPTY);
    g_VkOffset3D(w, o.dstOffset || EMPTY);
    g_VkExtent3D(w, o.extent || EMPTY);
}
function g_VkRenderingAttachmentInfo_self(w, o)
{
    w.h(o.imageView);
    w.i32(o.imageLayout);
    w.i32(o.resolveMode);
    w.h(o.resolveImageView);
    w.i32(o.resolveImageLayout);
    w.i32(o.loadOp);
    w.i32(o.storeOp);
    g_VkClearValue(w, o.clearValue || EMPTY);
}
function g_VkMemoryToImageCopyMESA_self(w, o)
{
    w.u64(o.dataSize);
    if(o.pData)
    {
        w.size(o.dataSize);
        w.blob(o.pData, o.dataSize);
    }
    else
    {
        w.size(0);
    }
    w.u32(o.memoryRowLength);
    w.u32(o.memoryImageHeight);
    g_VkImageSubresourceLayers(w, o.imageSubresource || EMPTY);
    g_VkOffset3D(w, o.imageOffset || EMPTY);
    g_VkExtent3D(w, o.imageExtent || EMPTY);
}
function g_VkImageDescriptorInfoEXT(w, o)
{
    w.u32(1000135001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkImageDescriptorInfoEXT_self(w, o);
}
function g_VkTexelBufferDescriptorInfoEXT(w, o)
{
    w.u32(1000135000);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkTexelBufferDescriptorInfoEXT_self(w, o);
}
function g_VkTensorViewCreateInfoARM(w, o)
{
    w.u32(1000460001);
    w.pnext(o.pNext, GUEST_PNEXT);
    g_VkTensorViewCreateInfoARM_self(w, o);
}
function g_VkDescriptorMappingSourceConstantOffsetEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.heapArrayStride);
    if(o.pEmbeddedSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, o.pEmbeddedSampler || EMPTY);
    }
    else w.u64(0);
    w.u32(o.samplerHeapOffset);
    w.u32(o.samplerHeapArrayStride);
}
function g_VkDescriptorMappingSourcePushIndexEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.pushOffset);
    w.u32(o.heapIndexStride);
    w.u32(o.heapArrayStride);
    if(o.pEmbeddedSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, o.pEmbeddedSampler || EMPTY);
    }
    else w.u64(0);
    w.u32(o.useCombinedImageSamplerIndex);
    w.u32(o.samplerHeapOffset);
    w.u32(o.samplerPushOffset);
    w.u32(o.samplerHeapIndexStride);
    w.u32(o.samplerHeapArrayStride);
}
function g_VkDescriptorMappingSourceIndirectIndexEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.pushOffset);
    w.u32(o.addressOffset);
    w.u32(o.heapIndexStride);
    w.u32(o.heapArrayStride);
    if(o.pEmbeddedSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, o.pEmbeddedSampler || EMPTY);
    }
    else w.u64(0);
    w.u32(o.useCombinedImageSamplerIndex);
    w.u32(o.samplerHeapOffset);
    w.u32(o.samplerPushOffset);
    w.u32(o.samplerAddressOffset);
    w.u32(o.samplerHeapIndexStride);
    w.u32(o.samplerHeapArrayStride);
}
function g_VkDescriptorMappingSourceIndirectIndexArrayEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.pushOffset);
    w.u32(o.addressOffset);
    w.u32(o.heapIndexStride);
    if(o.pEmbeddedSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, o.pEmbeddedSampler || EMPTY);
    }
    else w.u64(0);
    w.u32(o.useCombinedImageSamplerIndex);
    w.u32(o.samplerHeapOffset);
    w.u32(o.samplerPushOffset);
    w.u32(o.samplerAddressOffset);
    w.u32(o.samplerHeapIndexStride);
}
function g_VkDescriptorMappingSourceHeapDataEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.pushOffset);
}
function g_VkDescriptorMappingSourceIndirectAddressEXT(w, o)
{
    w.u32(o.pushOffset);
    w.u32(o.addressOffset);
}
function g_VkDescriptorMappingSourceShaderRecordIndexEXT(w, o)
{
    w.u32(o.heapOffset);
    w.u32(o.shaderRecordOffset);
    w.u32(o.heapIndexStride);
    w.u32(o.heapArrayStride);
    if(o.pEmbeddedSampler != null)
    {
        w.u64(1);
        g_VkSamplerCreateInfo(w, o.pEmbeddedSampler || EMPTY);
    }
    else w.u64(0);
    w.u32(o.useCombinedImageSamplerIndex);
    w.u32(o.samplerHeapOffset);
    w.u32(o.samplerShaderRecordOffset);
    w.u32(o.samplerHeapIndexStride);
    w.u32(o.samplerHeapArrayStride);
}
function g_VkSpecializationInfo(w, o)
{
    w.u32(o.mapEntryCount);
    if(o.pMapEntries)
    {
        w.size(o.mapEntryCount);
        for(let i = 0; i < o.mapEntryCount; i++)
        {
            g_VkSpecializationMapEntry(w, (o.pMapEntries || EMPTY)[i] || EMPTY);
        }
    }
    else
    {
        w.size(0);
    }
    w.u64(o.dataSize);
    if(o.pData)
    {
        w.size(o.dataSize);
        w.blob(o.pData, o.dataSize);
    }
    else
    {
        w.size(0);
    }
}
function g_VkVertexInputBindingDescription(w, o)
{
    w.u32(o.binding);
    w.u32(o.stride);
    w.i32(o.inputRate);
}
function g_VkVertexInputAttributeDescription(w, o)
{
    w.u32(o.location);
    w.u32(o.binding);
    w.i32(o.format);
    w.u32(o.offset);
}
function g_VkStencilOpState(w, o)
{
    w.i32(o.failOp);
    w.i32(o.passOp);
    w.i32(o.depthFailOp);
    w.i32(o.compareOp);
    w.u32(o.compareMask);
    w.u32(o.writeMask);
    w.u32(o.reference);
}
function g_VkPipelineColorBlendAttachmentState(w, o)
{
    w.u32(o.blendEnable);
    w.i32(o.srcColorBlendFactor);
    w.i32(o.dstColorBlendFactor);
    w.i32(o.colorBlendOp);
    w.i32(o.srcAlphaBlendFactor);
    w.i32(o.dstAlphaBlendFactor);
    w.i32(o.alphaBlendOp);
    w.u32(o.colorWriteMask);
}
function g_VkImageDescriptorInfoEXT_self(w, o)
{
    if(o.pView != null)
    {
        w.u64(1);
        g_VkImageViewCreateInfo(w, o.pView || EMPTY);
    }
    else w.u64(0);
    w.i32(o.layout);
}
function g_VkTexelBufferDescriptorInfoEXT_self(w, o)
{
    w.i32(o.format);
    g_VkDeviceAddressRangeEXT(w, o.addressRange || EMPTY);
}
function g_VkTensorViewCreateInfoARM_self(w, o)
{
    w.u64(o.flags);
    w.h(o.tensor);
    w.i32(o.format);
}
function g_VkSpecializationMapEntry(w, o)
{
    w.u32(o.constantID);
    w.u32(o.offset);
    w.u64(o.size);
}
                                                                                         source/v64/tests/devices/venus_protocol.js                                                          0000755 0000000 0000000 00000020026 00000000000 016072  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The Venus wire format of src/graphics_adapters/virtio_gpu/venus_protocol.js
// (generated by tools/venus_protocol_gen.mjs from Mesa's C) against Mesa's
// own code: venus_protocol_vectors.txt holds requests Mesa's encoders wrote
// (tools/venus_oracle/oracle.c), which must decode to what they were made
// of and encode again (tests/devices/venus_guest_protocol.js) to the same
// bytes; and replies this encoder wrote, with what Mesa's decoders read
// from them, which must still come out the same.

import assert from "assert/strict";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const P = await import("../../src/graphics_adapters/virtio_gpu/venus_protocol.js");
const { GUEST } = await import("./venus_guest_protocol.js");

const vectors = { request: {}, reply: {}, mesa: {} };
for(const line of fs.readFileSync(__dirname + "/venus_protocol_vectors.txt", "utf8").split("\n"))
{
    if(!line || line.startsWith("#")) continue;
    const [kind, name, ...rest] = line.split(" ");
    vectors[kind][name] = rest.join(" ");
}
const unhex = hex => Uint8Array.from(hex.match(/../g), h => parseInt(h, 16));
const hex = bytes => Array.from(bytes, b => b.toString(16).padStart(2, "0")).join("");
const by_name = {};
for(const [type, entry] of Object.entries(P.COMMANDS)) by_name[entry[0]] = [+type, entry[1], entry[2]];

/** a request: its type, flags, decoded parameters */
const decode = name => {
    const bytes = unhex(vectors.request[name]);
    const r = new P.VenusReader(bytes);
    const type = r.u32(), flags = r.u32();
    const a = by_name[name][1](r);
    assert.equal(type, by_name[name][0], name + ": its command type");
    assert.equal(r.p, bytes.length, name + ": all of it read");
    a.cmd_flags = flags;
    return a;
};

// Every request decodes and encodes again to Mesa's bytes
for(const name of Object.keys(vectors.request))
{
    const a = decode(name);
    // (an output the request only sizes)
    if(name === "vkGetQueryPoolResults") a.pData = new Uint8Array(a.dataSize);
    const w = new P.VenusWriter(16);
    GUEST[name][0](w, a);
    assert.equal(hex(w.result()), vectors.request[name], name + ": encoded again");
}
console.log("PASS: " + Object.keys(vectors.request).length + " requests of Mesa's encoders, decoded and encoded again");

// What they decode to
let a = decode("vkCreateInstance");
assert.deepEqual(a.pCreateInfo.ppEnabledExtensionNames, ["VK_KHR_surface", "VK_EXT_debug_utils"]);
assert.equal(a.pCreateInfo.pApplicationInfo.pApplicationName, "vktest");
assert.equal(a.pCreateInfo.pApplicationInfo.pEngineName, null);
assert.equal(a.pInstance, 0x1234);
a = decode("vkCreateDevice");
assert.equal(a.pCreateInfo.pNext.sType, 1000059000, "VkPhysicalDeviceFeatures2 in the chain");
assert.equal(a.pCreateInfo.pNext.features.samplerAnisotropy, 1);
assert.equal(a.pCreateInfo.pNext.pNext.timelineSemaphore, 1, "VkPhysicalDeviceVulkan12Features after it");
assert.deepEqual(Array.from(a.pCreateInfo.pQueueCreateInfos[0].pQueuePriorities), [1, 0.5]);
a = decode("vkCreateBuffer");
assert.equal(a.pCreateInfo.size, 0x100000005, "64-bit sizes");
assert.deepEqual(Array.from(a.pCreateInfo.pQueueFamilyIndices), [0, 3], "concurrent sharing's families");
a = decode("vkUpdateDescriptorSets");
assert.equal(a.pDescriptorWrites[0].pImageInfo[1].imageView, 0x63);
assert.equal(a.pDescriptorWrites[1].pBufferInfo[0].range, 2 ** 64, "VK_WHOLE_SIZE");
a = decode("vkCmdBeginRenderPass");
assert.deepEqual(Array.from(new Float32Array(a.pRenderPassBegin.pClearValues[0].color.uint32.buffer)), [0.25, 0.5, 0.75, 1],
    "clear values: their bits");
a = decode("vkCreateGraphicsPipelines");
const pipeline = a.pCreateInfos[0];
assert.equal(pipeline.pStages[1].pName, "fs_main");
assert.deepEqual(Array.from(pipeline.pStages[1].pSpecializationInfo.pData), [7, 0, 0, 0, 9, 0, 0, 0]);
assert.deepEqual(Array.from(pipeline.pMultisampleState.pSampleMask), [15]);
assert.equal(pipeline.basePipelineIndex, -1);
a = decode("vkCmdDrawMultiEXT");
assert.deepEqual(a.pVertexInfo, [{ firstVertex: 3, vertexCount: 6 }, { firstVertex: 10, vertexCount: 4 }], "a strided array");
a = decode("vkCreateRingMESA");
assert.equal(a.ring, "00007f0012345678", "a ring's id: 16 hex digits");
{
    // (two threads' rings 0x1c0 apart on Android's tagged heap: a number
    // would round both to 0xb4000076e5a3c000, one ring for two)
    const ids = ["b4000076e5a3c180", "b4000076e5a3c340"].map(ring => {
        const w = new P.VenusWriter(64);
        GUEST["vkNotifyRingMESA"][0](w, { ring, seqno: 1, flags: 0 });
        const r = new P.VenusReader(w.result());
        r.u32(); r.u32();
        return by_name["vkNotifyRingMESA"][1](r).ring;
    });
    assert.deepEqual(ids, ["b4000076e5a3c180", "b4000076e5a3c340"], "ring ids are exact");
}
assert.equal(a.pCreateInfo.pNext.maxReportingPeriodMicroseconds, 3000000);
console.log("PASS: what they decode to");

// Replies: the same objects encode to the bytes Mesa's decoders read
const replies = {
    "vkEnumeratePhysicalDevices": () => ({ ...decode("vkEnumeratePhysicalDevices"), ret: 0 }),
    "vkGetPhysicalDeviceProperties2": () => {
        const a = decode("vkGetPhysicalDeviceProperties2");
        a.pProperties.properties = { apiVersion: 0x403000, vendorID: 0x1af4, deviceName: "v86 WebGPU (Venus)", deviceType: 4,
            pipelineCacheUUID: [9, 8, 7], limits: { maxImageDimension2D: 8192, pointSizeRange: [1, 64] } };
        const driver = a.pProperties.pNext, v11 = driver.pNext;
        Object.assign(driver, { driverID: 22, driverName: "v86", conformanceVersion: { major: 1, minor: 3 } });
        Object.assign(v11, { deviceUUID: Array.from({ length: 16 }, (_, i) => i + 100), subgroupSize: 32, maxMultiviewViewCount: 6 });
        return a;
    },
    "vkGetPhysicalDeviceMemoryProperties": () => ({ pMemoryProperties: { memoryTypeCount: 2,
        memoryTypes: [{ propertyFlags: 1, heapIndex: 0 }, { propertyFlags: 0xE, heapIndex: 0 }], memoryHeapCount: 1,
        memoryHeaps: [{ size: 0x100000000, flags: 1 }] } }),
    "vkCreateBuffer": () => ({ ...decode("vkCreateBuffer"), ret: 0 }),
    "vkEnumerateInstanceExtensionProperties": () => ({ ret: 0, pPropertyCount: 2,
        pProperties: [{ extensionName: "VK_KHR_surface", specVersion: 25 }, { extensionName: "VK_EXT_debug_utils", specVersion: 2 }] }),
    "vkGetQueryPoolResults": () => ({ ...decode("vkGetQueryPoolResults"), ret: 0,
        pData: new Uint8Array(new BigUint64Array([1n, 0x1122334455667788n, 3n, 4n]).buffer) }),
    "vkGetBufferDeviceAddress": () => ({ ret: 0x7f0000001000 }),
    "vkGetPhysicalDeviceQueueFamilyProperties2": () => {
        const a = decode("vkGetPhysicalDeviceQueueFamilyProperties2");
        a.pQueueFamilyPropertyCount = 1;
        a.pQueueFamilyProperties.length = 1;
        a.pQueueFamilyProperties[0].queueFamilyProperties = { queueFlags: 7, queueCount: 1, timestampValidBits: 64,
            minImageTransferGranularity: { width: 1, height: 1, depth: 1 } };
        return a;
    },
};
for(const [name, make] of Object.entries(replies))
{
    assert.ok(vectors.mesa[name].includes("fatal=0 left=0"), name + ": Mesa read it all, without errors");
    const w = new P.VenusWriter(16);
    by_name[name][2](w, make());
    assert.equal(hex(w.result()), vectors.reply[name], name + ": the reply Mesa read");
}
// and the driver's side reads them as Mesa did
let reply = GUEST["vkGetPhysicalDeviceProperties2"][1](new P.VenusReader(unhex(vectors.reply["vkGetPhysicalDeviceProperties2"])));
assert.equal(reply.pProperties.properties.deviceName, "v86 WebGPU (Venus)");
assert.equal(reply.pProperties.pNext.driverName, "v86");
assert.equal(reply.pProperties.pNext.pNext.maxMultiviewViewCount, 6);
assert.match(vectors.mesa["vkGetPhysicalDeviceProperties2"], /name=v86 WebGPU \(Venus\) .* driverName=v86 .* maxMultiviewViewCount=6/);
reply = GUEST["vkGetQueryPoolResults"][1](new P.VenusReader(unhex(vectors.reply["vkGetQueryPoolResults"])));
assert.deepEqual(Array.from(new BigUint64Array(reply.pData.buffer)), [1n, 0x1122334455667788n, 3n, 4n]);
console.log("PASS: " + Object.keys(replies).length + " replies, as Mesa's decoders read them");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/devices/venus_protocol_vectors.txt                                                 0000644 0000000 0000000 00000032467 00000000000 020053  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # tools/venus_oracle/oracle.c (Mesa 26.1.6's encoders and decoders): requests it encoded,
# replies venus_protocol.js encoded and what Mesa's decoders read from them
request vkCreateInstance 000000000100000001000000000000000100000000000000000000000000000001000000000000000000000000000000000000000700000000000000766b74657374000007000000000000000000000000000000003040000000000000000000000000000200000002000000000000000f00000000000000564b5f4b48525f7375726661636500001300000000000000564b5f4558545f64656275675f7574696c730000000000000000000001000000000000003412000000000000
request vkEnumeratePhysicalDevices 02000000010000003412000000000000010000000000000002000000020000000000000010000000000000001100000000000000
request vkGetPhysicalDeviceProperties2 94000000010000001000000000000000010000000000000079b09b3b0100000000000000a0c79d3b0100000000000000320000000000000000000000
request vkCreateDevice 0b000000010000001000000000000000010000000000000003000000010000000000000078b09b3b01000000000000003300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000010000000000000002000000000000000000000000000000000000000200000002000000000000000000803f0000003f0000000000000000000000000100000001000000000000001100000000000000564b5f4b48525f73776170636861696e000000000000000000000000000000000000000001000000000000002000000000000000
request vkCreateBuffer 3200000000000000200000000000000001000000000000000c000000000000000000000000000000050000000100000082000000010000000200000002000000000000000000000003000000000000000000000001000000000000003000000000000000
request vkCmdBeginRenderPass 8500000000000000500000000000000001000000000000002b000000000000000000000040000000000000004100000000000000010000000200000080020000e0010000020000000200000000000000000000000200000004000000000000000000803e0000003f0000403f0000803f000000000200000004000000000000000000803f80000000000000000000000000000000
request vkUpdateDescriptorSets 4f000000000000002000000000000000020000000200000000000000230000000000000000000000700000000000000001000000000000000200000001000000020000000000000060000000000000006100000000000000050000006200000000000000630000000000000001000000000000000000000000000000000000002300000000000000000000007000000000000000000000000000000001000000060000000000000000000000010000000000000030000000000000000001000000000000ffffffffffffffff0000000000000000010000000100000000000000240000000000000000000000700000000000000001000000000000007100000000000000020000000000000001000000
request vkCmdPushConstants 84000000000000005000000000000000800000000000000001000000040000000c0000000c000000000000000102030405060708090a0b0c
request vkCreateShaderModule 3b000000000000002000000000000000010000000000000010000000000000000000000000000000140000000000000005000000000000000302230700000100010008000d00000000000000000000000000000001000000000000009000000000000000
request vkQueueSubmit 1200000000000000b0000000000000000100000001000000000000000400000001000000000000009bf29d3b0000000000000000020000000200000000000000050000000000000089674523010000000100000001000000000000000600000000000000020000000200000000000000a000000000000000a100000000000000020000000000000000040000001000000100000001000000000000005000000000000000010000000100000000000000a200000000000000c000000000000000
request vkCreateGraphicsPipelines 4100000000000000200000000000000000000000000000000100000001000000000000001c0000000000000000000000000000000200000002000000000000001200000000000000000000000000000001000000900000000000000005000000000000006d61696e00000000000000000000000012000000000000000000000000000000100000009100000000000000080000000000000066735f6d61696e000100000000000000020000000200000000000000000000000000000004000000000000000100000004000000040000000000000008000000000000000800000000000000070000000900000001000000000000001300000000000000000000000000000001000000010000000000000000000000140000000000000002000000020000000000000000000000000000006a000000000000000100000000000000670000000c000000010000000000000014000000000000000000000000000000040000000100000000000000000000000100000000000000160000000000000000000000000000000100000000000000000000000100000000000000000000000100000000000000170000000000000000000000000000000000000000000000000000000200000001000000000000000000000000000000000000000000803f01000000000000001800000000000000000000000000000004000000000000000000000001000000000000000f000000000000000000000001000000000000001900000000000000000000000000000001000000010000000300000000000000000000000000000002000000000000000700000000000000000000000300000000000000000000000000000000000000000000000000000000000000000000000000803f01000000000000001a0000000000000000000000000000000000000000000000010000000100000000000000010000000600000007000000000000000000000000000000000000000f0000000400000000000000cdcccc3dcdcc4c3e9a99993ecdcccc3e01000000000000001b000000000000000000000000000000020000000200000000000000000000000100000080000000000000004000000000000000000000000000000000000000ffffffff00000000000000000100000000000000d000000000000000
request vkCreateRingMESA bc0000000000000078563412007f0000010000000000000000a6a03b010000000000000006a6a03b0000000000000000c0c62d0000000000090000000000000000000000400102000000000040420f0000000000000000000000000040000000000000008000000000000000c0000000000000000000020000000000c0000200000000008000000000000000
request vkCmdDrawMultiEXT f700000000000000500000000000000002000000020000000000000003000000060000000a00000004000000010000000000000008000000
request vkCmdSetBlendConstants 6200000000000000500000000000000004000000000000000000803f0000003f0000803e00000000
request vkGetQueryPoolResults 31000000010000002000000000000000e000000000000000010000000200000020000000000000002000000000000000100000000000000003000000
request vkAllocateDescriptorSets 4d0000000000000020000000000000000100000000000000220000000000000000000000f200000000000000020000000200000000000000f000000000000000f100000000000000020000000000000000010000000000000101000000000000
request vkGetPhysicalDeviceQueueFamilyProperties2 9700000001000000100000000000000001000000000000000300000003000000000000007db09b3b00000000000000007db09b3b00000000000000007db09b3b0000000000000000
reply vkEnumeratePhysicalDevices 0200000000000000010000000000000002000000020000000000000010000000000000001100000000000000
reply vkGetPhysicalDeviceProperties2 94000000010000000000000079b09b3b0100000000000000a0c79d3b010000000000000032000000000000000000000010000000000000006465666768696a6b6c6d6e6f70717273100000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000200000000000000000000000000000000000000006000000000000000000000000000000000000000000000016000000000100000000000076383600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000300000000000000000000000030400000000000f41a00000000000004000000000100000000000076383620576562475055202856656e7573290000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000908070000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000803f0000804202000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
reply vkGetPhysicalDeviceMemoryProperties 08000000010000000000000002000000200000000000000001000000000000000e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000001000000000000000000000000100000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
reply vkCreateBuffer 320000000000000001000000000000003000000000000000
reply vkEnumerateInstanceExtensionProperties 0d0000000000000001000000000000000200000002000000000000000001000000000000564b5f4b48525f737572666163650000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000190000000001000000000000564b5f4558545f64656275675f7574696c730000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000
reply vkGetQueryPoolResults 310000000000000020000000000000000100000000000000887766554433221103000000000000000400000000000000
reply vkGetBufferDeviceAddress af00000000100000007f0000
reply vkGetPhysicalDeviceQueueFamilyProperties2 9700000001000000000000000100000001000000000000007db09b3b0000000000000000070000000100000040000000010000000100000001000000
mesa vkEnumeratePhysicalDevices ret=0 count=2 devices=10,11 fatal=0 left=0
mesa vkGetPhysicalDeviceProperties2 api=403000 vendor=1af4 name=v86 WebGPU (Venus) type=4 maxImage2D=8192 pointSize=1,64 uuid0=9 driverID=22 driverName=v86 conformance=1.3 deviceUUID=100,115 subgroupSize=32 maxMultiviewViewCount=6 fatal=0 left=0
mesa vkGetPhysicalDeviceMemoryProperties types=2 [1/0 e/0] heaps=1 [100000000/1] fatal=0 left=0
mesa vkCreateBuffer ret=0 buffer=30 fatal=0 left=0
mesa vkEnumerateInstanceExtensionProperties ret=0 count=2 VK_KHR_surface/25 VK_EXT_debug_utils/2 fatal=0 left=0
mesa vkGetQueryPoolResults ret=0 data=1,1122334455667788,3,4 fatal=0 left=0
mesa vkGetBufferDeviceAddress address=7f0000001000 fatal=0 left=0
mesa vkGetPhysicalDeviceQueueFamilyProperties2 count=1 flags=7 queues=1 bits=64 granularity=1,1,1 fatal=0 left=0
                                                                                                                                                                                                         source/v64/tests/devices/virgl_tgsi.js                                                              0000755 0000000 0000000 00000012067 00000000000 015170  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu's virgl shaders: TGSI text (tests/gpu/shaders/tgsi/, as
// Mesa's virgl driver sent it) through tgsi.js and tgsi_vgpu10.js into
// VGPU10 tokens, which GX's decoder must take and its WGSL emitter turn into
// WGSL naga accepts (when naga is there: cargo install naga-cli).

import assert from "assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import { createRequire as create_require } from "node:module";
import { spawnSync } from "node:child_process";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const require = create_require(import.meta.url);
const IR = require("../../src/browser/glbridge/shader_ir/dxbc_frontend.js");
const W = require("../../src/browser/glbridge/shader_ir/wgsl_emitter.js");
const { parse_tgsi } = await import("../../src/graphics_adapters/virtio_gpu/tgsi.js");
const { tgsi_to_vgpu10 } = await import("../../src/graphics_adapters/virtio_gpu/tgsi_vgpu10.js");

const naga = process.env.D9_NAGA || (spawnSync("naga", ["--version"]).status === 0 ? "naga" : null);
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "virgl-tgsi-"));

function validate(name, code)
{
    if(!naga) return;
    const file = path.join(scratch, name + ".wgsl");
    fs.writeFileSync(file, code);
    const result = spawnSync(naga, [file], { encoding: "utf8" });
    if(result.status !== 0)
    {
        console.error(code.split("\n").map((l, i) => String(i + 1).padStart(4) + "  " + l).join("\n"));
        assert.fail(name + ": naga rejected the WGSL:\n" + result.stderr + result.stdout);
    }
}

const corpus = path.join(__dirname, "../gpu/shaders/tgsi");
const files = fs.readdirSync(corpus).filter(f => f.endsWith(".txt")).sort();
const programs = new Map(files.map(f => [f, parse_tgsi(fs.readFileSync(path.join(corpus, f), "utf8"))]));

// fragment shaders first: their inputs are what the vertex shaders write
const links = new Map();
let count = 0;
for(const [name, program] of programs)
{
    if(program.processor !== 1) continue;
    const key = { flatshade: false, color_buffers: 2, swizzles: [[0, 1, 2, 5], [0, 0, 0, 5], [0, 1, 2, 3]], alpha_func: 4, alpha_ref: 0.5 };
    const result = tgsi_to_vgpu10(program, key);
    assert.deepEqual(result.problems, [], name);
    const p = IR.decode(result.tokens);
    const targets = { 0: "f32", 1: "f32" };
    const wgsl = W.emit(p, { targets });
    assert.deepEqual(wgsl.warnings, [], name);
    validate(name, wgsl.code);
    links.set(name.replace(/-fs\.txt$/, ""), { inputs: result.inputs, varyings: W.pixelVaryings(p) });
    count++;
}
for(const [name, program] of programs)
{
    if(program.processor !== 0) continue;
    const link = links.get(name.replace(/-vs\.txt$/, "")) || { inputs: { GENERIC0: 0 }, varyings: { 0: { type: "f32" } } };
    for(const [flip_y, halfz] of [[false, false], [true, true]])
    {
        const result = tgsi_to_vgpu10(program, { outputs: link.inputs, flip_y, halfz });
        assert.deepEqual(result.problems, [], name);
        const p = IR.decode(result.tokens);
        const vertex_inputs = {};
        for(const input of p.inputs) if(!input.name) vertex_inputs[input.index] = "f32";
        const wgsl = W.emit(p, { vertexInputs: vertex_inputs, varyings: link.varyings });
        assert.deepEqual(wgsl.warnings, [], name);
        validate(name + (flip_y ? "-flip" : ""), wgsl.code);
        // the position: Y flipped, Z into [0, 1], or as it is
        if(flip_y) assert.match(wgsl.code, /-/, name);
    }
    count++;
}
// tessellation: the control shader as a hull shader (two phases), the
// evaluation shader as a domain shader
{
    const tcs = programs.get("gltest-tess-tcs.txt"), tes = programs.get("gltest-tess-tes.txt");
    const ds = tgsi_to_vgpu10(tes, { outputs: { GENERIC0: 0 }, cps: 4, flip_y: true, halfz: false });
    assert.deepEqual(ds.problems, []);
    const hs = tgsi_to_vgpu10(tcs, { outputs: ds.inputs, in_cps: 4, domain: "quad", partitioning: 1, output_primitive: 3 });
    assert.deepEqual(hs.problems, []);
    const hp = IR.decode(hs.tokens), dp = IR.decode(ds.tokens);
    assert.deepEqual(hp.tess.phases.map(phase => phase.kind), ["decls", "cp", "fork"]);
    assert.deepEqual([hp.tess.inputCPs, hp.tess.outputCPs, hp.tess.domain], [4, 4, 3]);
    for(const [name, p, mode] of [["tess-hull", hp, "hull"], ["tess-domain", dp, "domain"]])
    {
        const wgsl = W.emit(p, { group: 0, mode });
        assert.deepEqual(wgsl.warnings, [], name);
        validate(name, wgsl.code);
    }
    count += 2;
}

// compute shaders
for(const [name, program] of programs)
{
    if(program.processor !== 5) continue;
    const result = tgsi_to_vgpu10(program, {});
    assert.deepEqual(result.problems, [], name);
    const p = IR.decode(result.tokens);
    const wgsl = W.emit(p, { group: 0 });
    assert.deepEqual(wgsl.warnings, [], name);
    validate(name, wgsl.code);
    count++;
}
assert.ok(count >= 5);
console.log("PASS: " + count + " TGSI programs translated" + (naga ? ", their WGSL valid by naga" : " (naga not found: WGSL unchecked)"));
fs.rmSync(scratch, { recursive: true, force: true });
                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/devices/virtio_9p.js                                                               0000755 0000000 0000000 00000137363 00000000000 014752  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import url from "node:url";
import fs from "node:fs";

process.on("unhandledRejection", exn => { throw exn; });

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const testfsjson = JSON.parse(fs.readFileSync(__dirname + "/testfs.json", "utf-8"));
const SHOW_LOGS = false;
const STOP_ON_FIRST_FAILURE = false;

function assert_equal(actual, expected, message)
{
    if(actual !== expected)
    {
        console.warn("Failed assert equal (Test: %s). %s", tests[test_num].name, message || "");
        console.warn("Expected:\n" + expected);
        console.warn("Actual:\n" + actual);
        test_fail();
    }
}

function assert_not_equal(actual, expected, message)
{
    if(actual === expected)
    {
        console.warn("Failed assert not equal (Test: %s). %s", tests[test_num].name, message || "");
        console.warn("Expected something different than:\n" + expected);
        test_fail();
    }
}

// Random printable characters.
const test_file = new Uint8Array(512).map(v => 0x20 + Math.random() * 0x5e);
const test_file_string = Buffer.from(test_file).toString();
const test_file_small = new Uint8Array(16).map(v => 0x20 + Math.random() * 0x5e);
const test_file_small_string = Buffer.from(test_file_small).toString();

const tests =
[
    {
        name: "Read Existing",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("cp /etc/profile /mnt/read-existing\n");
            emulator.serial0_send("echo start-capture; cat /etc/profile; echo done-read-existing\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-read-existing",
        end: async (capture, done) =>
        {
            const data = await emulator.read_file("read-existing");
            assert_equal(capture, Buffer.from(data).toString());
            done();
        },
    },
    {
        name: "Read New",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("dd if=/dev/zero of=/mnt/read-new bs=1k count=512\n");
            emulator.serial0_send("echo done-read-new\n");
        },
        end_trigger: "done-read-new",
        end: async (capture, done) =>
        {
            const data = await emulator.read_file("read-new");
            assert_equal(data.length, 512 * 1024);
            if(data.find(v => v !== 0))
            {
                console.warn("Fail: Incorrect data. Expected all zeros.");
                test_fail();
            }
            done();
        },
    },
    {
        name: "Read Async",
        use_fsjson: true,
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("echo start-capture;");

            // "foo" is from ./testfs/foo
            emulator.serial0_send("cat /mnt/foo;");

            emulator.serial0_send("echo done-read-async\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-read-async",
        end: async (capture, done) =>
        {
            assert_equal(capture, "bar\n");
            const data = await emulator.read_file("foo");
            assert_equal(Buffer.from(data).toString(), "bar\n");
            done();
        },
    },
    {
        name: "Write New",
        timeout: 60,
        files:
        [
            {
                file: "write-new",
                data: test_file,
            },
        ],
        start: () =>
        {
            emulator.serial0_send("echo start-capture; cat /mnt/write-new; echo; echo done-write-new\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-write-new",
        end: (capture, done)  =>
        {
            // Handle word wrapping.
            const lines = capture.split("\n");
            let pos = 0;
            for(const line of lines)
            {
                assert_equal(line, test_file_string.slice(pos, line.length));
                pos += line.length;
            }
            done();
        },
    },
    {
        name: "New file time",
        timeout: 10,
        start: () =>
        {
            emulator.serial0_send("echo start-capture; echo foo > /mnt/bar; ls  -l --full-time --color=never /mnt/bar; echo; echo done-write-new\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-write-new",
        end: (capture, done)  =>
        {
            const outputs = capture.split("\n").map(output => output.split(/\s+/));

            // atime: Should be fresh
            const [year, month, day] = outputs[0][5].split("-");
            assert_not_equal(year, "1970");

            done();
        },
    },
    {
        name: "Move",
        timeout: 60,
        files:
        [
            {
                file: "test-file",
                data: test_file,
            },
        ],
        start: () =>
        {
            emulator.serial0_send("echo start-capture;");
            emulator.serial0_send("cat /mnt/test-file;");
            emulator.serial0_send("find /mnt;");

            // Rename. Verify updated directory.
            emulator.serial0_send("mv /mnt/test-file /mnt/renamed;");
            emulator.serial0_send("cat /mnt/renamed;");
            emulator.serial0_send("find /mnt;");

            // Move between folders. Verify directories.
            emulator.serial0_send("mkdir /mnt/somedir;");
            emulator.serial0_send("mv /mnt/renamed /mnt/somedir/file;");
            emulator.serial0_send("cat /mnt/somedir/file;");
            emulator.serial0_send("find /mnt;");

            // Rename folder.
            emulator.serial0_send("mv /mnt/somedir /mnt/otherdir;");
            emulator.serial0_send("cat /mnt/otherdir/file;");
            emulator.serial0_send("find /mnt;");

            // Move folder.
            emulator.serial0_send("mkdir /mnt/thirddir;");
            emulator.serial0_send("mv /mnt/otherdir /mnt/thirddir;");
            emulator.serial0_send("cat /mnt/thirddir/otherdir/file;");
            emulator.serial0_send("find /mnt;");

            // Move folder outside /mnt. Should be removed from 9p filesystem.
            emulator.serial0_send("mv /mnt/thirddir/otherdir /root/movedoutside;");
            emulator.serial0_send("cat /root/movedoutside/file;");
            emulator.serial0_send("find /mnt;");

            // Cleanup.
            emulator.serial0_send("rm -rf /root/movedoutside;");
            emulator.serial0_send("echo done-move\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-move",
        end: (capture, done)  =>
        {
            assert_equal(capture,
                test_file_string +
                "/mnt\n" +
                "/mnt/test-file\n" +
                test_file_string +
                "/mnt\n" +
                "/mnt/renamed\n" +
                test_file_string +
                "/mnt\n" +
                "/mnt/somedir\n" +
                "/mnt/somedir/file\n" +
                test_file_string +
                "/mnt\n" +
                "/mnt/otherdir\n" +
                "/mnt/otherdir/file\n" +
                test_file_string +
                "/mnt\n" +
                "/mnt/thirddir\n" +
                "/mnt/thirddir/otherdir\n" +
                "/mnt/thirddir/otherdir/file\n" +
                test_file_string +
                "/mnt\n" +
                "/mnt/thirddir\n");
            done();
        },
    },
    {
        name: "Unlink",
        timeout: 60,
        files:
        [
            {
                file: "existing-file",
                data: test_file,
            },
        ],
        start: () =>
        {
            emulator.serial0_send("touch /mnt/new-file\n");
            emulator.serial0_send("mkdir /mnt/new-dir\n");
            emulator.serial0_send("touch /mnt/new-dir/file\n");

            emulator.serial0_send("echo start-capture;");

            emulator.serial0_send("rm /mnt/new-file;");
            emulator.serial0_send("test ! -e /mnt/new-file && echo new-file-unlinked;");
            emulator.serial0_send("cat /mnt/new-file 2>/dev/null || echo read-failed;");

            emulator.serial0_send("rm /mnt/existing-file;");
            emulator.serial0_send("test ! -e /mnt/existing-file && echo existing-file-unlinked;");
            emulator.serial0_send("cat /mnt/existing-file 2>/dev/null || echo read-failed;");

            emulator.serial0_send("rmdir /mnt/new-dir 2>/dev/null || echo rmdir-failed;");
            emulator.serial0_send("test -e /mnt/new-dir && echo new-dir-exist;");

            emulator.serial0_send("rm /mnt/new-dir/file;");
            emulator.serial0_send("rmdir /mnt/new-dir;");
            emulator.serial0_send("test ! -e /mnt/new-dir/file && echo new-dir-file-unlinked;");
            emulator.serial0_send("test ! -e /mnt/new-dir && echo new-dir-unlinked;");
            emulator.serial0_send("ls /mnt/new-dir 2>/dev/null || echo read-failed;");

            emulator.serial0_send("echo done-unlink\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-unlink",
        end: (capture, done)  =>
        {
            assert_equal(capture,
                "new-file-unlinked\n" +
                "read-failed\n" +
                "existing-file-unlinked\n" +
                "read-failed\n" +
                "rmdir-failed\n" +
                "new-dir-exist\n" +
                "new-dir-file-unlinked\n" +
                "new-dir-unlinked\n" +
                "read-failed\n");
            done();
        },
    },
    {
        name: "Hard Links",
        timeout: 60,
        files:
        [
            {
                file: "target",
                data: test_file_small,
            },
        ],
        start: () =>
        {
            // Helper that prints filename followed by nlinks.
            emulator.serial0_send("nlinks() {\n");
            emulator.serial0_send(`  ls -dli $@ | awk '{ print "'$@' "$3 }'\n`);
            emulator.serial0_send("}\n");

            // Check nlinks before mkdir.
            emulator.serial0_send("nlinks /mnt | tee -a /mnt/target\n");

            emulator.serial0_send("mkdir /mnt/dir\n");
            emulator.serial0_send("echo other > /mnt/target2\n");

            // Check nlinks after mkdir.
            emulator.serial0_send("nlinks /mnt | tee -a /mnt/target\n");
            emulator.serial0_send("nlinks /mnt/dir | tee -a /mnt/target\n");
            emulator.serial0_send("nlinks /mnt/target | tee -a /mnt/target\n");

            // Create hard links.
            emulator.serial0_send("ln /mnt/target /mnt/link1\n");
            emulator.serial0_send("ln /mnt/link1 /mnt/dir/link2\n");
            emulator.serial0_send("ln /mnt/dir/link2 /mnt/dir/link3\n");
            emulator.serial0_send("ln /mnt/target2 /mnt/link-other\n");

            // Test inode numbers.
            emulator.serial0_send("{ test /mnt/target -ef /mnt/link1 && \n");
            emulator.serial0_send("  test /mnt/link1 -ef /mnt/dir/link2 && \n");
            emulator.serial0_send("  test /mnt/target -ef /mnt/dir/link3 && \n");
            emulator.serial0_send("  echo same inode | tee -a /mnt/target; }\n");
            emulator.serial0_send("{ test /mnt/link-other -ef /mnt/dir/link3 || \n");
            emulator.serial0_send("  echo different inode | tee -a /mnt/link1; }\n");

            // Check nlinks after hard links.
            emulator.serial0_send("nlinks /mnt | tee -a /mnt/dir/link2\n");
            emulator.serial0_send("nlinks /mnt/dir | tee -a /mnt/dir/link2\n");
            emulator.serial0_send("nlinks /mnt/target | tee -a /mnt/dir/link2\n");
            emulator.serial0_send("nlinks /mnt/dir/link2 | tee -a /mnt/dir/link2\n");
            emulator.serial0_send("nlinks /mnt/target2 | tee -a /mnt/dir/link2\n");
            emulator.serial0_send("nlinks /mnt/link-other | tee -a /mnt/dir/link2\n");

            // Movement and unlink.
            emulator.serial0_send("mv /mnt/link1 /mnt/link1-renamed\n");
            emulator.serial0_send("echo renamed | tee -a /mnt/link1-renamed\n");
            emulator.serial0_send("mv /mnt/dir/link2 /mnt/link2-moved\n");
            emulator.serial0_send("echo moved | tee -a /mnt/link2-moved\n");
            emulator.serial0_send("rm /mnt/target\n");
            emulator.serial0_send("echo unlinked original | tee -a /mnt/dir/link3\n");

            // Test inode numbers after movement and unlinking.
            emulator.serial0_send("{ test /mnt/link1-renamed -ef /mnt/link2-moved && \n");
            emulator.serial0_send("  test /mnt/link2-moved -ef /mnt/dir/link3 && \n");
            emulator.serial0_send("  echo same inode after mv | tee -a /mnt/link1-renamed; }\n");

            // Check nlinks after movement and unlinking.
            emulator.serial0_send("nlinks /mnt | tee -a /mnt/link2-moved\n");
            emulator.serial0_send("nlinks /mnt/dir | tee -a /mnt/link2-moved\n");
            emulator.serial0_send("nlinks /mnt/link1-renamed | tee -a /mnt/link2-moved\n");

            emulator.serial0_send("echo start-capture;\\\n");

            // Unlink the rest and output the above messages.
            emulator.serial0_send("rm /mnt/link1-renamed;\\\n");
            emulator.serial0_send("echo unlinked link1 >> /mnt/link2-moved;\\\n");
            emulator.serial0_send("nlinks /mnt/link2-moved >> /mnt/link2-moved;\\\n");
            emulator.serial0_send("rm /mnt/link2-moved;\\\n");
            emulator.serial0_send("echo unlinked link2 >> /mnt/dir/link3;\\\n");
            emulator.serial0_send("nlinks /mnt/dir/link3 >> /mnt/dir/link3;\\\n");
            emulator.serial0_send("cat /mnt/dir/link3;\\\n");
            emulator.serial0_send("rm /mnt/dir/link3;\\\n");

            // Verify nlinks of directories after unlinking hardlinks.
            emulator.serial0_send("nlinks /mnt;\\\n");
            emulator.serial0_send("nlinks /mnt/dir;\\\n");

            // Verify nlinks of root directory after subdirectory is unlinked.
            emulator.serial0_send("rmdir /mnt/dir;\\\n");
            emulator.serial0_send("nlinks /mnt;\\\n");

            emulator.serial0_send("echo done-hard-links\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-hard-links",
        end: (capture, done) =>
        {
            assert_equal(capture,
                test_file_small_string +
                "/mnt 2\n" +
                "/mnt 3\n" +
                "/mnt/dir 2\n" +
                "/mnt/target 1\n" +
                "same inode\n" +
                "different inode\n" +
                "/mnt 3\n" +
                "/mnt/dir 2\n" +
                "/mnt/target 4\n" +
                "/mnt/dir/link2 4\n" +
                "/mnt/target2 2\n" +
                "/mnt/link-other 2\n" +
                "renamed\n" +
                "moved\n" +
                "unlinked original\n" +
                "same inode after mv\n" +
                "/mnt 3\n" +
                "/mnt/dir 2\n" +
                "/mnt/link1-renamed 3\n" +
                "unlinked link1\n" +
                "/mnt/link2-moved 2\n" +
                "unlinked link2\n" +
                "/mnt/dir/link3 1\n" +
                "/mnt 3\n" +
                "/mnt/dir 2\n" +
                "/mnt 2\n");
            done();
        },
    },
    {
        name: "Symlinks",
        timeout: 60,
        files:
        [
            {
                file: "target",
                data: test_file_small,
            },
        ],
        start: () =>
        {
            emulator.serial0_send("echo otherdata > /mnt/target2\n");
            emulator.serial0_send("ln -s /mnt/target /mnt/symlink\n");
            emulator.serial0_send("echo appended >> /mnt/symlink\n");

            emulator.serial0_send("echo start-capture;");

            // Should output same file data.
            emulator.serial0_send("cat /mnt/target;");
            emulator.serial0_send("cat /mnt/symlink;");

            // Swap target with the other file.
            emulator.serial0_send("rm /mnt/target;");
            emulator.serial0_send("mv /mnt/target2 /mnt/target;");

            // Symlink should now read from that file.
            emulator.serial0_send("cat /mnt/symlink;");

            emulator.serial0_send("rm /mnt/target;");
            emulator.serial0_send("rm /mnt/symlink;");
            emulator.serial0_send("echo done-symlinks\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-symlinks",
        end: (capture, done) =>
        {
            assert_equal(capture,
                test_file_small_string + "appended\n" +
                test_file_small_string + "appended\n" +
                "otherdata\n");
            done();
        },
    },
    {
        name: "Mknod - fifo",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("mkfifo /mnt/testfifo\n");
            emulator.serial0_send('(cat /mnt/testfifo > /mnt/testfifo-output;echo "\ndone-fifo") &\n');
            emulator.serial0_send("echo fifomessage > /mnt/testfifo\n");
        },
        end_trigger: "done-fifo",
        end: async (capture, done) =>
        {
            const data = await emulator.read_file("testfifo-output");
            assert_equal(Buffer.from(data).toString(), "fifomessage\n");
            done();
        },
    },
    {
        name: "Readlink",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("touch /mnt/target\n");
            emulator.serial0_send("ln -s /mnt/target /mnt/link\n");
            emulator.serial0_send("echo start-capture;");
            emulator.serial0_send("readlink /mnt/link;");
            emulator.serial0_send("echo done-readlink\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-readlink",
        end: (capture, done) =>
        {
            assert_equal(capture, "/mnt/target\n");
            done();
        },
    },
    {
        name: "Mkdir",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("echo notfoobar > /mnt/e-file\n");
            emulator.serial0_send("mkdir /mnt/a-dir\n");
            emulator.serial0_send("mkdir /mnt/a-dir/b-dir\n");
            emulator.serial0_send("mkdir /mnt/a-dir/c-dir\n");
            emulator.serial0_send("touch /mnt/a-dir/d-file\n");
            emulator.serial0_send("echo mkdirfoobar > /mnt/a-dir/e-file\n");
            emulator.serial0_send("echo done-mkdir\n");
        },
        end_trigger: "done-mkdir",
        end: async (capture, done) =>
        {
            const data = await emulator.read_file("a-dir/e-file");
            assert_equal(Buffer.from(data).toString(), "mkdirfoobar\n");
            done();
        },
    },
    {
        name: "Walk",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("mkdir -p /mnt/walk/a/aa/aaa/aaaa\n");
            emulator.serial0_send("mkdir -p /mnt/walk/a/aa/aaa/aaaa\n");
            emulator.serial0_send("mkdir -p /mnt/walk/b/ba\n");
            emulator.serial0_send("mkdir -p /mnt/walk/a/aa/aab\n");
            emulator.serial0_send("mkdir -p /mnt/walk/a/aa/aac\n");
            emulator.serial0_send("touch /mnt/walk/a/aa/aab/aabfile\n");
            emulator.serial0_send("touch /mnt/walk/b/bfile\n");
            emulator.serial0_send("echo start-capture;");
            emulator.serial0_send("find /mnt/walk | sort;"); // order agnostic
            emulator.serial0_send("echo done-walk\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-walk",
        end: (capture, done) =>
        {
            const actual = capture;
            const expected =
                "/mnt/walk\n" +
                "/mnt/walk/a\n" +
                "/mnt/walk/a/aa\n" +
                "/mnt/walk/a/aa/aaa\n" +
                "/mnt/walk/a/aa/aaa/aaaa\n" +
                "/mnt/walk/a/aa/aab\n" +
                "/mnt/walk/a/aa/aab/aabfile\n" +
                "/mnt/walk/a/aa/aac\n" +
                "/mnt/walk/b\n" +
                "/mnt/walk/b/ba\n" +
                "/mnt/walk/b/bfile\n";
            assert_equal(actual, expected);
            done();
        },
    },
    {
        name: "Statfs",
        timeout: 60,
        allow_failure: true,
        start: () =>
        {
            emulator.serial0_send("echo start-capture;");
            emulator.serial0_send("touch /mnt/file;");
            emulator.serial0_send("df -PTk /mnt | tail -n 1;");

            // Grow file and verify space usage.
            emulator.serial0_send("dd if=/dev/zero of=/mnt/file bs=1k count=4 status=none;");
            emulator.serial0_send("df -PTk /mnt | tail -n 1;");

            // Shrink file and verify space usage.
            emulator.serial0_send("truncate -s 0 /mnt/file;");
            emulator.serial0_send("df -PTk /mnt | tail -n 1;");

            emulator.serial0_send("echo done-statfs\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-statfs",
        end: (capture, done) =>
        {
            const outputs = capture.split("\n").map(output => output.split(/\s+/));
            if(outputs.length < 3)
            {
                console.warn("Wrong format: %s", capture);
                test_fail();
                done();
                return;
            }

            const before = outputs[0];
            const after_add = outputs[1];
            const after_rm = outputs[2];

            // mount tag
            assert_equal(before[0], "host9p");

            // fs type
            assert_equal(before[1], "9p");

            // total size in 1024 blocks
            assert_equal(after_add[2], before[2]);
            assert_equal(after_rm[2], before[2]);

            // used size in 1024 blocks
            assert_equal(+after_add[3], (+before[3]) + 4);
            assert_equal(after_rm[3], before[3]);

            // free size in 1024 blocks
            assert_equal(+after_add[4], (+before[4]) - 4);
            assert_equal(after_rm[4], before[4]);

            // Entry [5] is percentage used.

            // mount path
            assert_equal(before[6], "/mnt");

            done();
        },
    },
    {
        name: "File Attributes",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("echo start-capture;");

            emulator.serial0_send("dd if=/dev/zero of=/mnt/file bs=1 count=137 status=none;");
            emulator.serial0_send("touch -t 200002022222 /mnt/file;");
            emulator.serial0_send("chmod =rw /mnt/file;");
            emulator.serial0_send("ls -l --full-time --color=never /mnt/file;");

            emulator.serial0_send("chmod +x /mnt/file;");
            emulator.serial0_send("chmod -w /mnt/file;");
            emulator.serial0_send("ln /mnt/file /mnt/file-link;");
            emulator.serial0_send("ls -l --full-time --color=never /mnt/file;");

            emulator.serial0_send("chmod -x /mnt/file;");
            emulator.serial0_send("truncate -s 100 /mnt/file;");
            emulator.serial0_send("touch -t 201011220344 /mnt/file;");
            emulator.serial0_send("rm /mnt/file-link;");
            emulator.serial0_send("ls -l --full-time --color=never /mnt/file;");

            emulator.serial0_send("echo done-file-attr\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-file-attr",
        end: (capture, done) =>
        {
            const outputs = capture.split("\n").map(output => output.split(/\s+/));

            if(outputs.length < 3)
            {
                console.warn("Wrong format (expected 3 rows): %s", capture);
                test_fail();
                done();
                return;
            }

            // mode
            assert_equal(outputs[0][0], "-rw-r--r--");
            // nlinks
            assert_equal(outputs[0][1], "1");
            // user
            assert_equal(outputs[0][2], "root");
            // group
            assert_equal(outputs[0][3], "root");
            // size
            assert_equal(outputs[0][4], "137");
            // atime
            assert_equal(outputs[0][5], "2000-02-02");
            assert_equal(outputs[0][6], "22:22:00");
            assert_equal(outputs[0][7], "+0000");
            // pathname
            assert_equal(outputs[0][8], "/mnt/file");

            // mode
            assert_equal(outputs[1][0], "-r-xr-xr-x");
            // nlinks
            assert_equal(outputs[1][1], "2");
            // user
            assert_equal(outputs[1][2], "root");
            // group
            assert_equal(outputs[1][3], "root");
            // size
            assert_equal(outputs[1][4], "137");
            // atime
            assert_equal(outputs[1][5], "2000-02-02");
            assert_equal(outputs[1][6], "22:22:00");
            assert_equal(outputs[1][7], "+0000");
            // pathname
            assert_equal(outputs[1][8], "/mnt/file");

            // mode
            assert_equal(outputs[2][0], "-r--r--r--");
            // nlinks
            assert_equal(outputs[2][1], "1");
            // user
            assert_equal(outputs[2][2], "root");
            // group
            assert_equal(outputs[2][3], "root");
            // size
            assert_equal(outputs[2][4], "100");
            // atime
            assert_equal(outputs[2][5], "2010-11-22");
            assert_equal(outputs[2][6], "03:44:00");
            assert_equal(outputs[2][7], "+0000");
            // pathname
            assert_equal(outputs[2][8], "/mnt/file");

            done();
        },
    },
    {
        name: "Xattrwalk and Listxattr",
        timeout: 60,
        allow_failure: true,
        start: () =>
        {
            emulator.serial0_send("echo originalvalue > /mnt/file\n");
            emulator.serial0_send("echo start-capture;");

            emulator.serial0_send('setfattr --name=user.attr1 --value="val1" /mnt/file;');
            emulator.serial0_send('setfattr --name=user.attr2 --value="val2" /mnt/file;');
            emulator.serial0_send('setfattr --name=user.mime_type --value="text/plain" /mnt/file;');
            emulator.serial0_send('setfattr --name=user.nested.attr --value="foobar" /mnt/file;');

            // Unrecognized attribute name under other namespaces should be allowed.
            emulator.serial0_send('setfattr --name=security.not_an_attr --value="val3" /mnt/file;');

            // Remove the caps attribute we've automatically put in. Tested later.
            emulator.serial0_send("setfattr --remove=security.capability /mnt/file;");

            emulator.serial0_send("getfattr --encoding=text --absolute-names --dump /mnt/file | sort;");
            emulator.serial0_send("getfattr --encoding=text --absolute-names --name=user.nested.attr /mnt/file;");
            emulator.serial0_send("getfattr --encoding=text --absolute-names --name=security.not_an_attr /mnt/file;");
            emulator.serial0_send("getfattr --encoding=text --absolute-names --name=user.attr2 /mnt/file;");
            emulator.serial0_send("echo done-listxattr\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-listxattr",
        end: (capture, done) =>
        {
            assert_equal(capture,
                "# file: /mnt/file\n" +
                'security.not_an_attr="val3"\n' +
                'user.attr1="val1"\n' +
                'user.attr2="val2"\n' +
                'user.mime_type="text/plain"\n' +
                'user.nested.attr="foobar"\n' +
                "\n" +
                "# file: /mnt/file\n" +
                'user.nested.attr="foobar"\n' +
                "\n" +
                "# file: /mnt/file\n" +
                'security.not_an_attr="val3"\n' +
                "\n" +
                "# file: /mnt/file\n" +
                'user.attr2="val2"\n');
            done();
        },
    },
    {
        name: "Xattrcreate",
        timeout: 60,
        allow_failure: true,
        start: () =>
        {
            emulator.serial0_send("echo originalvalue > /mnt/file\n");
            // Remove the caps attribute we've automatically put in. Tested later.
            emulator.serial0_send("setfattr --remove=security.capability /mnt/file\n");

            emulator.serial0_send("echo start-capture;");

            // Creation of new xattr using xattrcreate.
            emulator.serial0_send("setfattr --name=user.foo --value=bar /mnt/file;");
            // File contents should not be overriden.
            emulator.serial0_send("cat /mnt/file;");
            emulator.serial0_send("getfattr --encoding=hex --absolute-names --name=user.foo /mnt/file;");

            // Overwriting of xattr using xattrcreate.
            emulator.serial0_send("setfattr --name=user.foo --value=baz /mnt/file;");
            // File contents should not be overriden.
            emulator.serial0_send("cat /mnt/file;");
            emulator.serial0_send("getfattr --encoding=hex --absolute-names --name=user.foo /mnt/file;");

            emulator.serial0_send("echo done-xattrcreate\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-xattrcreate",
        end: (capture, done) =>
        {
            assert_equal(capture,
                "originalvalue\n" +
                "# file: /mnt/file\n" +
                'user.foo="bar"\n' +
                "\n" +
                "originalvalue\n" +
                "# file: /mnt/file\n" +
                'user.foo="baz"\n' +
                "\n");
            done();
        },
    },
    {
        name: "Report All Security Capabilities",
        timeout: 60,
        allow_failure: true,
        start: () =>
        {
            emulator.serial0_send("touch /mnt/file\n");
            emulator.serial0_send("echo start-capture;");
            emulator.serial0_send("getfattr --encoding=hex --absolute-names --name=security.capability /mnt/file;");
            emulator.serial0_send("echo done-xattr\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-xattr",
        end: (capture, done) =>
        {
            assert_equal(capture,
                "# file: /mnt/file\n" +
                "security.capability=0x" +
                // magic and revision number
                "00000002" +
                // lower permitted
                "ffffffff" +
                // lower inheritable
                "ffffffff" +
                // higher permitted
                "3f000000" +
                // higher inheritable
                "3f000000" +
                "\n\n");
            done();
        },
    },
    {
        name: "File Locks",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("touch /mnt/file\n");
            emulator.serial0_send("touch /mnt/logs\n");
            emulator.serial0_send("mkfifo /mnt/fifo1\n");
            emulator.serial0_send("mkfifo /mnt/fifo2\n");

            emulator.serial0_send("flock -s /mnt/file -c 'cat /mnt/fifo1 >> /mnt/file' &\n");
            emulator.serial0_send("flock -s /mnt/file -c 'echo lock-shared-2 >> /mnt/file' \n");
            emulator.serial0_send("flock -xn /mnt/file -c 'echo lock unblocked! >> /mnt/logs' \n");
            emulator.serial0_send("echo lock-shared-1 > /mnt/fifo1\n");

            emulator.serial0_send("flock -x /mnt/file -c 'cat /mnt/fifo1 >> /mnt/file' &\n");
            emulator.serial0_send("flock -x /mnt/file -c 'echo lock-exclusive-2 >> /mnt/file' &\n");
            emulator.serial0_send("flock -sn /mnt/file -c 'echo lock unblocked! >> /mnt/logs' \n");
            emulator.serial0_send("echo lock-exclusive-1 > /mnt/fifo1\n");

            emulator.serial0_send("flock -s /mnt/file -c 'cat /mnt/fifo1 >> /mnt/file' &\n");
            emulator.serial0_send("flock -s /mnt/file -c 'cat /mnt/fifo2 >> /mnt/file' &\n");
            emulator.serial0_send("flock -x /mnt/file -c 'echo lock-exclusive-3 >> /mnt/file' &\n");
            emulator.serial0_send("echo lock-shared-4 > /mnt/fifo2\n");
            emulator.serial0_send("sleep 0.1\n");
            emulator.serial0_send("echo lock-shared-3 > /mnt/fifo1\n");

            emulator.serial0_send("echo start-capture;\\\n");
            emulator.serial0_send("cat /mnt/file;\\\n");
            emulator.serial0_send("cat /mnt/logs;\\\n");
            emulator.serial0_send("echo done-locks\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-locks",
        end: (capture, done) =>
        {
            assert_equal(capture,
                "lock-shared-2\n" +
                "lock-shared-1\n" +
                "lock-exclusive-1\n" +
                "lock-exclusive-2\n" +
                "lock-shared-4\n" +
                "lock-shared-3\n" +
                "lock-exclusive-3\n");

            const idx = emulator.fs9p.Search(0, "file");

            const P9_LOCK_TYPE_RDLCK = 0;
            const P9_LOCK_TYPE_WRLCK = 1;
            const P9_LOCK_TYPE_UNLCK = 2;
            const P9_LOCK_SUCCESS = 0;
            const P9_LOCK_BLOCKED = 1;
            const CLIENT_ID = "under test";

            function test_getlock(num, type, pos, proc_id, locked)
            {
                const lock = emulator.fs9p.DescribeLock(type, pos, 1, proc_id, CLIENT_ID);
                const ret = emulator.fs9p.GetLock(idx, lock, 0);
                assert_equal(ret !== null, locked,
                    `getlock ${num}: type=${type}, pos=${pos}, proc_id=${proc_id}. Wrong state:`);
            }

            function test_lock(num, type, start, length, proc_id, status, lock_state)
            {
                console.log(`    Lock ${num}: type=${type}, start=${start}, length=${length} ` +
                    ` proc_id=${proc_id}, expected state=${lock_state}`);

                const lock = emulator.fs9p.DescribeLock(type, start, length, proc_id, CLIENT_ID);
                assert_equal(emulator.fs9p.Lock(idx, lock, 0), status, "Wrong status:");

                for(const [i, state] of [...lock_state].entries())
                {
                    switch(state)
                    {
                        case "1":
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 1, false);
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 2, false);
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 2, true);
                            break;
                        case "2":
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 2, false);
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 1, false);
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 1, true);
                            break;
                        case "3":
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 1, false);
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 1, true);
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 2, false);
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 2, true);
                            break;
                        case "e":
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 1, false);
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 2, true);
                            break;
                        case "E":
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 1, true);
                            test_getlock(num, P9_LOCK_TYPE_RDLCK, i, 2, false);
                            break;
                        case "-":
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 1, false);
                            test_getlock(num, P9_LOCK_TYPE_WRLCK, i, 2, false);
                            break;
                    }
                }
            }

            // Key:
            // 1/2/3 = shared lock by process 1/2/both
            // e/E   = exclusive lock by process 1/2
            // -     = no locks
            const I = Infinity;
            test_lock(0, P9_LOCK_TYPE_RDLCK, 0, 1, 1, P9_LOCK_SUCCESS, "1-------"); // First lock.
            test_lock(1, P9_LOCK_TYPE_RDLCK, 0, 2, 1, P9_LOCK_SUCCESS, "11------"); // Replace.
            test_lock(2, P9_LOCK_TYPE_RDLCK, 1, 1, 2, P9_LOCK_SUCCESS, "13------");
            test_lock(3, P9_LOCK_TYPE_RDLCK, 2, 2, 1, P9_LOCK_SUCCESS, "1311----"); // Skip. Merge before.
            test_lock(4, P9_LOCK_TYPE_WRLCK, 0, 1, 1, P9_LOCK_SUCCESS, "e311----"); // Shrink left.
            test_lock(5, P9_LOCK_TYPE_WRLCK, 1, 1, 1, P9_LOCK_BLOCKED, "e311----");
            test_lock(6, P9_LOCK_TYPE_UNLCK, 0, 4, 1, P9_LOCK_SUCCESS, "-2------"); // Delete.
            test_lock(7, P9_LOCK_TYPE_WRLCK, 1, 2, 1, P9_LOCK_BLOCKED, "-2------");
            test_lock(8, P9_LOCK_TYPE_UNLCK, 1, 3, 2, P9_LOCK_SUCCESS, "--------"); // Delete.
            test_lock(9, P9_LOCK_TYPE_WRLCK, 1, 1, 1, P9_LOCK_SUCCESS, "-e------");
            test_lock(10, P9_LOCK_TYPE_RDLCK, 3, 3, 1, P9_LOCK_SUCCESS, "-e-111--"); // Skip.
            test_lock(11, P9_LOCK_TYPE_RDLCK, 2, 1, 2, P9_LOCK_SUCCESS, "-e2111--"); // Skip past.
            test_lock(12, P9_LOCK_TYPE_UNLCK, 2, 1, 2, P9_LOCK_SUCCESS, "-e-111--"); // Delete.
            test_lock(13, P9_LOCK_TYPE_WRLCK, 0, 1, 1, P9_LOCK_SUCCESS, "ee-111--");
            test_lock(14, P9_LOCK_TYPE_WRLCK, 1, 4, 1, P9_LOCK_SUCCESS, "eeeee1--"); // Merge before. Shrink both ways.
            test_lock(15, P9_LOCK_TYPE_WRLCK, 1, 2, 2, P9_LOCK_BLOCKED, "eeeee1--");
            test_lock(16, P9_LOCK_TYPE_RDLCK, 4, 5, 2, P9_LOCK_BLOCKED, "eeeee1--");
            test_lock(17, P9_LOCK_TYPE_RDLCK, 5, I, 2, P9_LOCK_SUCCESS, "eeeee322");
            test_lock(18, P9_LOCK_TYPE_UNLCK, 0, I, 1, P9_LOCK_SUCCESS, "-----222"); // Replace.
            test_lock(19, P9_LOCK_TYPE_RDLCK, 4, I, 2, P9_LOCK_SUCCESS, "----2222"); // Replace.
            test_lock(20, P9_LOCK_TYPE_WRLCK, 2, I, 2, P9_LOCK_SUCCESS, "--EEEEEE"); // Replace.
            test_lock(21, P9_LOCK_TYPE_WRLCK, 0, 1, 2, P9_LOCK_SUCCESS, "E-EEEEEE");
            test_lock(22, P9_LOCK_TYPE_WRLCK, 1, 3, 2, P9_LOCK_SUCCESS, "EEEEEEEE"); // Merge both. Shrink left.
            test_lock(23, P9_LOCK_TYPE_RDLCK, 3, 4, 2, P9_LOCK_SUCCESS, "EEE2222E"); // Split.
            test_lock(24, P9_LOCK_TYPE_RDLCK, 1, 2, 2, P9_LOCK_SUCCESS, "E222222E"); // Merge after. Shrink right.
            test_lock(25, P9_LOCK_TYPE_RDLCK, 2, 3, 2, P9_LOCK_SUCCESS, "E222222E"); // No-op.

            done();
        },
    },
    {
        name: "Stress Files",
        timeout: 360,
        start: () =>
        {
            emulator.serial0_send("mkdir /mnt/stress-files\n");

            emulator.serial0_send('cat << "EOF" | sh\n');

            // Create files.
            // Ensure directory inode data exceeds maximum message size for 9p.
            emulator.serial0_send("for f in $(seq -w 0 999)\n");
            emulator.serial0_send("do\n");
            emulator.serial0_send('    echo "$f" > "/mnt/stress-files/file-$f"\n');
            emulator.serial0_send("done\n");

            emulator.serial0_send("echo start-capture\n");

            // Read some of them.
            emulator.serial0_send("for f in $(seq -w 0 31 999)\n");
            emulator.serial0_send("do\n");
            emulator.serial0_send('    cat "/mnt/stress-files/file-$f"\n');
            emulator.serial0_send("done\n");

            // Walk.
            emulator.serial0_send("find /mnt/stress-files | sort\n");

            // Delete and verify.
            // Using glob checks readdir.
            emulator.serial0_send("rm /mnt/stress-files/file-*\n");
            emulator.serial0_send('test -z "$(ls /mnt/stress-files)" && echo delete-success\n');

            emulator.serial0_send("echo done-stress-files\n");
            emulator.serial0_send("EOF\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-stress-files",
        end: (capture, done) =>
        {
            let expected = "";
            for(let i = 0; i < 1000; i += 31)
            {
                expected += i.toString().padStart(3, "0") + "\n";
            }
            expected += "/mnt/stress-files\n";
            for(let i = 0; i < 1000; i ++)
            {
                expected += "/mnt/stress-files/file-" + i.toString().padStart(3, "0") + "\n";
            }
            expected += "delete-success\n";
            assert_equal(capture, expected);
            done();
        },
    },
    {
        name: "Stress Directories",
        timeout: 360,
        start: () =>
        {
            emulator.serial0_send('cat << "EOF" | sh\n');

            emulator.serial0_send("p=/mnt/stress-dirs\n");
            emulator.serial0_send('mkdir "$p"\n');

            // Create deep folder structure
            emulator.serial0_send("for i in $(seq 0 99)\n");
            emulator.serial0_send("do\n");
            emulator.serial0_send('    p="$p/$i"\n');
            emulator.serial0_send('    mkdir "$p"\n');
            emulator.serial0_send('    echo "$i" > "$p/file"\n');
            emulator.serial0_send("done\n");

            // Try accessing deep files
            emulator.serial0_send("p=/mnt/stress-dirs\n");
            emulator.serial0_send("echo start-capture\n");
            // Skip first 80 - otherwise too slow
            emulator.serial0_send("for i in $(seq 0 79)\n");
            emulator.serial0_send("do\n");
            emulator.serial0_send('    p="$p/$i"\n');
            emulator.serial0_send("done\n");
            emulator.serial0_send("for i in $(seq 80 99)\n");
            emulator.serial0_send("do\n");
            emulator.serial0_send('    p="$p/$i"\n');
            emulator.serial0_send('    cat "$p/file"\n');
            emulator.serial0_send("done\n");

            // Delete and verify
            emulator.serial0_send("rm -rf /mnt/stress-dirs/0\n");
            emulator.serial0_send('test -z "$(ls /mnt/stress-dirs)" && echo delete-success\n');

            emulator.serial0_send("echo done-stress-dirs\n");
            emulator.serial0_send("EOF\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-stress-dirs",
        end: (capture, done) =>
        {
            const outputs = capture.split("\n");
            for(let i = 0; i < 20; i++)
            {
                assert_equal(outputs[i], `${i + 80}`);
            }
            assert_equal(outputs[20], "delete-success");
            done();
        },
    },
    {
        name: "Read Past Available",
        timeout: 60,
        start: () =>
        {
            emulator.serial0_send("echo a > /mnt/small-file\n");
            emulator.serial0_send("echo start-capture;");

            // Reading from offsets > size of file should not read anything.
            emulator.serial0_send("dd if=/mnt/small-file bs=1 count=1 skip=10;");
            emulator.serial0_send("dd if=/mnt/small-file bs=1 count=1 skip=100;");
            emulator.serial0_send("dd if=/mnt/small-file bs=1 count=1 skip=1000;");

            emulator.serial0_send("echo done-read-exceed\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-read-exceed",
        end: (capture, done) =>
        {
            const outputs = capture.split("\n");
            assert_equal(outputs[0], "0+0 records in");
            assert_equal(outputs[1], "0+0 records out");
            assert_equal(outputs[2], "0+0 records in");
            assert_equal(outputs[3], "0+0 records out");
            assert_equal(outputs[4], "0+0 records in");
            assert_equal(outputs[5], "0+0 records out");
            done();
        },
    },
];

let test_num = 0;
let test_timeout = 0;
let test_has_failed = false;
const failed_tests = [];

function test_fail()
{
    if(!test_has_failed)
    {
        test_has_failed = true;
        failed_tests.push(test_num);
    }
}

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 64 * 1024 * 1024,
    filesystem: {
        baseurl: __dirname + "/testfs/",
    },
    disable_jit: +process.env.DISABLE_JIT,
    log_level: SHOW_LOGS ? 0x400000 : 0,
});

let ran_command = false;
let line = "";
let capturing = false;
let capture = "";
let next_trigger;
let next_trigger_handler;

async function prepare_test()
{
    console.log("\nPreparing test #%d: %s", test_num, tests[test_num].name);

    if(tests[test_num].timeout)
    {
        test_timeout = setTimeout(() =>
        {
            console.error("[-] Test #%d (%s) took longer than %s sec. Timing out and terminating.", test_num, tests[test_num].name, tests[test_num].timeout);
            process.exit(1);
        }, tests[test_num].timeout * 1000);
    }

    console.log("    Nuking /mnt");
    emulator.fs9p.RecursiveDelete("");

    if(tests[test_num].use_fsjson)
    {
        console.log("    Reloading files from json");
        emulator.fs9p.load_from_json(testfsjson);
    }

    console.log("    Loading additional files");
    if(tests[test_num].files)
    {
        let remaining = tests[test_num].files.length;
        for(const f of tests[test_num].files)
        {
            await emulator.create_file(f.file, f.data);
        }
    }

    console.log("Starting test #%d: %s", test_num, tests[test_num].name);

    capture = "";

    tests[test_num].start();

    if(tests[test_num].capture_trigger)
    {
        next_trigger = tests[test_num].capture_trigger;
        next_trigger_handler = start_capture;
    }
    else
    {
        next_trigger = tests[test_num].end_trigger;
        next_trigger_handler = end_test;
    }
}

function start_capture()
{
    console.log("Capturing...");
    capture = "";
    capturing = true;

    next_trigger = tests[test_num].end_trigger;
    next_trigger_handler = end_test;
}

function end_test()
{
    capturing = false;

    if(tests[test_num].timeout)
    {
        clearTimeout(test_timeout);
    }

    tests[test_num].end(capture, report_test);
}

function report_test()
{
    if(!test_has_failed)
    {
        console.log("[+] Test #%d passed: %s", test_num, tests[test_num].name);
    }
    else
    {
        if(tests[test_num].allow_failure)
        {
            console.warn("Test #%d failed: %s (failure allowed)", test_num, tests[test_num].name);
        }
        else
        {
            console.error("[-] Test #%d failed: %s", test_num, tests[test_num].name);

            if(STOP_ON_FIRST_FAILURE)
            {
                finish_tests();
            }
        }
        test_has_failed = false;
    }

    test_num++;

    if(test_num < tests.length)
    {
        prepare_test();
    }
    else
    {
        finish_tests();
    }
}

function finish_tests()
{
    emulator.stop();

    console.log("\nTests finished.");
    if(failed_tests.length === 0)
    {
        console.log("All tests passed");
    }
    else
    {
        let unallowed_failure = false;

        console.error("[-] Failed %d out of %d tests:", failed_tests.length, tests.length);
        for(const num of failed_tests)
        {
            if(tests[num].allow_failure)
            {
                console.warn("#%d %s (failure allowed)", num, tests[num].name);
            }
            else
            {
                unallowed_failure = true;
                console.error("[-] #%d %s", num, tests[num].name);
            }
        }
        if(unallowed_failure)
        {
            process.exit(1);
        }
    }
}

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
});

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    let new_line = "";
    let is_new_line = false;
    if(chr === "\n")
    {
        is_new_line = true;
        new_line = line;
        line = "";
    }
    else
    {
        line += chr;
    }

    if(!ran_command && line.endsWith("~% "))
    {
        ran_command = true;
        prepare_test();
    }
    else if(new_line === next_trigger)
    {
        next_trigger_handler();
    }
    else if(is_new_line && capturing)
    {
        capture += new_line + "\n";
        console.log("    Captured: %s", new_line);
    }
    else if(is_new_line)
    {
        console.log("    Serial: %s", new_line);
    }
});
                                                                                                                                                                                                                                                                             source/v64/tests/devices/virtio_balloon.js                                                          0000755 0000000 0000000 00000012777 00000000000 016051  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SHOW_LOGS = false;

function wait(time) {
    return new Promise((res) => setTimeout(res, time));
}

let s1;
const tests =
[
    {
        name: "Use space",
        start: async () =>
        {
            emulator.serial0_send("udhcpc\n");
            emulator.serial0_send("free -h\n");
            emulator.serial0_send("lspci -k\n");
            emulator.serial0_send("dd if=/dev/urandom of=/tmp/file bs=1M count=64\n");
            emulator.serial0_send("du -h /tmp/file\n");
            emulator.serial0_send("free -h\n");
            emulator.serial0_send("rm /tmp/file\n");
            emulator.serial0_send("free -h\n");
            emulator.serial0_send("echo done\n");
        },
        end_trigger: "done",
        end: (capture) =>
        {
        },
    },
    {
        name: "Delete space",
        start: async () =>
        {
            emulator.serial0_send("echo 3 > /proc/sys/vm/drop_caches\n");
            emulator.serial0_send("df -h; echo done\n");
        },
        end_trigger: "done",
        end: (capture) =>
        {
        },
    },
    {
        name: "Reclaim space",
        start: async () =>
        {
            s1 = await emulator.save_state();
            emulator.v86.cpu.devices.virtio_balloon.GetStats(s => { console.log(s); });
            emulator.v86.cpu.devices.virtio_balloon.Cleanup(async (zeroed) => {
                console.log("Zeroed ", zeroed / 1024 / 1024, "MB of pages");
                await wait(2000);
                emulator.serial0_send("echo done\n");
            });
        },
        end_trigger: "done",
        end: async (capture) =>
        {
            let s2 = await emulator.save_state();
            let saved = s1.byteLength - s2.byteLength;
            console.log(`Saved ${saved>>20}MB of ${s1.byteLength>>20}MB (${saved/s1.byteLength*100}%)`);
            assert(saved > 1000000, "not enough space saved");
            emulator.serial0_send("echo done\n");
        },
    },
    {
        name: "Wait",
        start: async () =>
        {
        },
        end_trigger: "done",
        end: async (capture) =>
        {
        },
    },
    {
        name: "Get Memory",
        start: async () =>
        {
            emulator.serial0_send("free -m; echo done\n");
        },
        end_trigger: "done",
        end: async (capture) =>
        {
        },
    },
    {
        name: "Inflate Balloon",
        start: async () =>
        {
            emulator.v86.cpu.devices.virtio_balloon.Inflate(30000);
            await wait(1000);
            emulator.serial0_send("free -m; echo done\n");
        },
        end_trigger: "done",
        end: async (capture) =>
        {
            assert(emulator.v86.cpu.devices.virtio_balloon.actual === 30000, "Got 30000 pages from vm");
        },
    },
];


const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
    autostart: true,
    memory_size: 200 * 1024 * 1024,
    disable_jit: +process.env.DISABLE_JIT,
    virtio_console: true,
    virtio_balloon: true,
    uart0: true,
    net_device: {
        relay_url: "fetch",
        type: "virtio",
    },
    log_level: SHOW_LOGS ? 0x400000 : 0,
    cmdline: "console=/dev/ttyS0"
});

let test_num = 0;
let booted = false;
let line = "";
let capture = "";
let end_trigger;

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
});

emulator.add_listener("serial0-output-byte", function(byte)
{
    const chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    let new_line = "";
    if(chr === "\n")
    {
        console.log("    Captured: %s", line);
        new_line = line;
        capture += line + "\n";
        line = "";
    }
    else
    {
        line += chr;
    }

    if(new_line === end_trigger)
    {
        let test_has_failed = false;

        try {
            tests[test_num].end(capture);
        } catch(e) {
            console.log(e);
            test_has_failed = true;
        }

        if(!test_has_failed)
        {
            console.log("[+] Test #%d passed: %s", test_num, tests[test_num].name);
        }
        else
        {
            if(tests[test_num].allow_failure)
            {
                console.warn("[!] Test #%d failed: %s (failure allowed)", test_num, tests[test_num].name);
            }
            else
            {
                console.error("[-] Test #%d failed: %s", test_num, tests[test_num].name);
                process.exit(1);
            }
        }

        test_num++;

    }

    if(!booted && line.endsWith("~% ") || new_line === end_trigger)
    {
        booted = true;

        if(test_num >= tests.length)
        {
            emulator.destroy();

            console.log("Tests finished.");
        }
        else
        {
            console.log("Starting test #%d: %s", test_num, tests[test_num].name);

            capture = "";
            end_trigger = tests[test_num].end_trigger;

            tests[test_num].start();
        }
    }
});
 source/v64/tests/devices/virtio_console.js                                                          0000755 0000000 0000000 00000003736 00000000000 016060  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "assert/strict";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const SHOW_LOGS = false;

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    acpi: true,
    cmdline: [
        "console=ttyS0",
        "audit=0",
    ].join(" "),
    disable_jit: +process.env.DISABLE_JIT,
    log_level: SHOW_LOGS ? 0x400000 : 0,
    virtio_console: true,
});

let line = "";
let sent_command = false;

emulator.add_listener("serial0-output-byte", function(byte)
{
    var chr = String.fromCharCode(byte);

    process.stdout.write(chr);

    if(chr === "\n")
    {
        line = "";
    }
    else
    {
        line += chr;
    }

    // TODO: use better prompt detection once it's configured to not print colours
    if(!sent_command && line.endsWith("~%"))
    {
        sent_command = true;
        emulator.serial0_send("lspci -vv; echo ping > /dev/hvc0\n");
    }

    if(line.endsWith("pong"))
    {
        console.log("\nTest passed");
        emulator.destroy();
    }
});

let got_output = false;

emulator.add_listener("virtio-console0-output-bytes", function(bytes)
{
    if(!got_output)
    {
        got_output = true;
        console.log("From virtio console:", String.fromCharCode.apply(String, bytes));
        emulator.serial0_send("cat /dev/hvc0\n");
        setTimeout(() => {
            emulator.bus.send("virtio-console0-input-bytes", Uint8Array.from(Buffer.from("pong\n")));
        }, 5000);
    }
});
                                  source/v64/tests/devices/virtio_devices.js                                                          0000755 0000000 0000000 00000027200 00000000000 016030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Custom virtio devices (the virtio_devices option, src/virtio_devices.js),
// driven through the transport's I/O ports without a guest: PCI identity,
// slot and port allocation, the configuration space, feature negotiation, a
// request round trip, notifications before DRIVER_OK, requests that outlive a
// reset, guest RAM access, machine resets and snapshots (including state[92]
// from before custom devices).

import assert from "assert/strict";

process.on("unhandledRejection", exn => { throw exn; });

const { V86 } = await import("../../src/main.js");
const {
    create_virtio_devices, get_virtio_devices_state, resolve_virtio_devices_state,
} = await import("../../src/virtio_devices.js");

const MEMORY_SIZE = 32 * 1024 * 1024;
const QUEUE_SIZE = 8;

// Replies with the request's bytes reversed, or keeps the request when told to
function echo_device(log)
{
    let dev = null;
    let config_word = 0x1234;
    let echoed = 0;
    const held = [];
    return {
        held,
        get echoed() { return echoed; },
        descriptor: {
            "name": "echo",
            "device_id": 0x10F0,
            "subsystem_device_id": 0x0E40,
            "features": [0],
            "queues": [{ "size": QUEUE_SIZE }],
            "config": [
                { "bytes": 4, "read": () => 0xC0FFEE01 },
                { "bytes": 2, "read": () => config_word, "write": value => { config_word = value; } },
            ],
            "init": handle => { dev = handle; log.push("init"); },
            "notify": queue => {
                log.push("notify " + queue);
                let request;
                while((request = dev["pop_request"](queue)))
                {
                    const bytes = request["read"]();
                    if(bytes[0] === 0xFF)
                    {
                        held.push(request);
                        continue;
                    }
                    request["write"](bytes.reverse());
                    request["complete"]();
                    echoed++;
                }
                dev["flush"](queue);
            },
            "reset": () => { log.push("reset"); },
            "get_state": () => [echoed, config_word],
            "set_state": state => { echoed = state[0]; config_word = state[1]; },
        },
        handle: () => dev,
    };
}

function create_emulator(virtio_devices)
{
    return new V86({
        graphics_adapter: "bochs_vga",
        memory_size: MEMORY_SIZE,
        // hlt forever: nothing moves the BARs from where the device put them
        bios: { buffer: new Uint8Array(65536).fill(0xF4).buffer },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" },
        autostart: false,
        log_level: 0,
        virtio_devices,
    });
}

const loaded = emulator => new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));

const log = [];
const echo = echo_device(log);
const emulator = create_emulator([echo.descriptor]);
await loaded(emulator);

const cpu = emulator.v86.cpu;
const io = cpu.io;
const [device] = cpu.devices.virtio_devices;

assert.deepEqual(log, ["init"], "init runs once, and a reset while the transport is built is not forwarded");

// PCI identity, through configuration mechanism #1
const SLOT = 0x10;
const pci_read32 = offset => {
    io.port_write32(0xCF8, (0x80000000 | SLOT << 11 | offset) >>> 0);
    return io.port_read32(0xCFC) >>> 0;
};
assert.equal(pci_read32(0x00), 0x10F01AF4, "vendor 1AF4 and the descriptor's device ID, in the first free slot");
assert.equal(pci_read32(0x2C), 0x0E401AF4, "subsystem ID");

const bar = n => pci_read32(0x10 + 4 * n) & ~3;
const common = bar(0), notify = bar(1), isr = bar(2), config = bar(3);
assert.equal(common, 0xE000, "ports come from the pool");
assert.deepEqual([notify, isr, config], [0xE100, 0xE200, 0xE300]);

// Device configuration space
assert.equal(io.port_read32(config) >>> 0, 0xC0FFEE01);
assert.equal(io.port_read16(config + 4), 0x1234);
io.port_write16(config + 4, 0xBEEF);
assert.equal(io.port_read16(config + 4), 0xBEEF, "config write reaches the device");

// Guest RAM
const ram = cpu.read_blob(0, MEMORY_SIZE);
const mem = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
const handle = echo.handle();
assert.ok(handle["is_ram"](0x1000, 4096));
assert.ok(!handle["is_ram"](0xA0000, 16), "legacy VGA memory is not RAM");
assert.ok(!handle["is_ram"](0x9FFF0, 32), "nor is a range that reaches into it");
assert.ok(!handle["is_ram"](MEMORY_SIZE - 16, 32), "nor is a range past the end of RAM");
assert.ok(!handle["is_ram"](0x1000, 0));
const view = handle["read_memory"](0x200000, 16);
view[0] = 0x5A;
assert.equal(mem.getUint8(0x200000), 0x5A, "contiguous RAM is read as a view");
handle["write_memory"](new Uint8Array([1, 2, 3]), 0x200010);
assert.equal(mem.getUint8(0x200012), 3);
assert.throws(() => handle["read_memory"](0xA0000, 16), RangeError);
assert.throws(() => handle["write_memory"](new Uint8Array([1]), 0xB8000), RangeError);

// A split virtqueue in guest RAM
const table = 0x10000, avail = table + 128, used = table + 256;
const data = 0x11000, reply = 0x12000;
const w8 = (offset, value) => io.port_write8(common + offset, value);
const w16 = (offset, value) => io.port_write16(common + offset, value);
const w32 = (offset, value) => io.port_write32(common + offset, value);
let avail_idx = 0;

function setup_queue(status, desc_address = table)
{
    w8(20, 0);
    w8(20, 3);
    w32(0, 0);
    assert.equal(io.port_read32(common + 4) & 1, 1, "device offers feature bit 0");
    w32(0, 1);
    assert.equal(io.port_read32(common + 4) & 1, 1, "VIRTIO_F_VERSION_1 is added");
    w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1);
    w8(20, 11);
    assert.equal(io.port_read8(common + 20), 11, "FEATURES_OK accepted");
    w16(22, 0);
    assert.equal(io.port_read16(common + 24), QUEUE_SIZE);
    w32(32, desc_address); w32(36, 0);
    w32(40, avail); w32(44, 0);
    w32(48, used); w32(52, 0);
    for(let i = 0; i < 512; i++) mem.setUint8(table + i, 0);
    w16(28, 1);
    w8(20, status);
    avail_idx = 0;
}

function submit(bytes, reply_address = reply)
{
    // descriptor 0: the request (readable), descriptor 1: the reply (writable)
    ram.set(bytes, data);
    mem.setUint32(table, data, true); mem.setUint32(table + 8, bytes.length, true);
    mem.setUint16(table + 12, 1, true); mem.setUint16(table + 14, 1, true);
    mem.setUint32(table + 16, reply_address, true); mem.setUint32(table + 24, 64, true);
    mem.setUint16(table + 28, 2, true);
    mem.setUint16(avail + 4 + (avail_idx % QUEUE_SIZE) * 2, 0, true);
    avail_idx = avail_idx + 1 & 0xFFFF;
    mem.setUint16(avail + 2, avail_idx, true);
    io.port_write16(notify, 0);
}

const used_idx = () => mem.getUint16(used + 2, true);

setup_queue(3);
submit(new Uint8Array([1, 2, 3]));
assert.equal(used_idx(), 0, "no request is taken before DRIVER_OK");
assert.ok(!log.includes("notify 0"), "the device is not notified before DRIVER_OK");

setup_queue(15);
submit(new TextEncoder().encode("hello"));
assert.equal(used_idx(), 1, "used ring acknowledges the request");
assert.equal(mem.getUint32(used + 8, true), 5, "used length is what the device wrote");
assert.equal(new TextDecoder().decode(ram.subarray(reply, reply + 5)), "olleh");
assert.ok(io.port_read8(isr) & 1, "queue interrupt raised");
assert.equal(echo.echoed, 1);

// A request kept past a guest reset must not complete into the new rings
submit(new Uint8Array([0xFF, 1]));
assert.equal(echo.held.length, 1);
log.length = 0;
w8(20, 0);
assert.deepEqual(log, ["reset"], "a guest reset reaches the device");
setup_queue(15);
echo.held[0]["write"](new Uint8Array([9]));
echo.held[0]["complete"]();
handle["flush"](0);
assert.equal(used_idx(), 0, "a stale request neither writes nor completes");
assert.notEqual(mem.getUint8(reply), 9);

// Snapshot: transport, device state
submit(new TextEncoder().encode("ab"));
assert.equal(used_idx(), 1);
const saved = await emulator.save_state();
assert.equal(echo.echoed, 2);
submit(new TextEncoder().encode("cd"));
io.port_write16(config + 4, 0x1111);
assert.equal(echo.echoed, 3);
await emulator.restore_state(saved);
assert.equal(echo.echoed, 2, "device state restored");
assert.equal(io.port_read16(config + 4), 0xBEEF);
assert.equal(io.port_read8(common + 20), 15, "transport state restored");
assert.equal(used_idx(), 1, "guest RAM and the ring restored together");
avail_idx = mem.getUint16(avail + 2, true);
submit(new TextEncoder().encode("xy"));
assert.equal(used_idx(), 2, "the restored queue keeps working");

// Buffers and rings are DMA: guest RAM only
setup_queue(15);
submit(new Uint8Array([1]), 0xB8000);
assert.equal(used_idx(), 0, "a reply buffer in VGA memory is not written");
assert.ok(io.port_read8(common + 20) & 64, "and the driver is told to reset");
setup_queue(15, 0xA0000);
mem.setUint16(avail + 2, 1, true);
io.port_write16(notify, 0);
assert.ok(io.port_read8(common + 20) & 64, "a ring outside RAM asks for a reset");

// Machine reset
log.length = 0;
await emulator.restart();
assert.ok(log.includes("reset"), "a machine reset reaches the device");
assert.equal(io.port_read8(common + 20), 0);

// Descriptor checks and slot collisions, on the live machine
const valid = { "name": "x", "device_id": 0x10F1, "queues": [{ "size": 4 }], "notify": () => {} };
assert.throws(() => create_virtio_devices(cpu, {}), /array/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "name": "" }]), /name/);
assert.throws(() => create_virtio_devices(cpu, [valid, valid]), /more than one device/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "queues": [{ "size": 3 }] }]), /power of two/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "notify": undefined }]), /notify/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "pci_slot": 0x12 }]), /slot 0x12, which is taken/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "io_base": 0xE000 }]), /ports 0xe000, which are taken/);
assert.throws(() => create_virtio_devices(cpu, [{ ...valid, "io_base": 0xE080 }]), /aligned/);
assert.throws(() => create_virtio_devices(cpu,
    [{ ...valid, "config": Array(65).fill({ "bytes": 4, "read": () => 0 }) }]), /256 bytes/);

// state[92] layouts
const fake = (name, upgrade_state) => ({ name, descriptor: { "upgrade_state": upgrade_state } });
assert.equal(get_virtio_devices_state(undefined), undefined, "no devices: state[92] stays empty");
assert.equal(resolve_virtio_devices_state([fake("a")], undefined).size, 0);
assert.throws(() => resolve_virtio_devices_state([], ["virtio_devices", 1, ["gone", [], 0, undefined]]),
    /"gone", which is not configured/);
assert.throws(() => resolve_virtio_devices_state([], ["virtio_devices", 2]), /version 2/);
const legacy = [0x56514731, "transport", 1, 2];
const upgraded = resolve_virtio_devices_state(
    [fake("a", () => null), fake("b", slot => slot[0] === 0x56514731 ? [slot[1], slot.slice(2), "host"] : null)],
    legacy);
assert.deepEqual(upgraded.get("b"), ["b", "transport", [1, 2], "host"], "a legacy slot goes to the device that recognizes it");
assert.throws(() => resolve_virtio_devices_state([fake("a", () => null)], legacy), /no configured virtio device recognizes/);

// A snapshot with the device, restored without it
const plain = create_emulator(undefined);
await loaded(plain);
await assert.rejects(plain.restore_state(saved), /"echo", which is not configured/);
await plain.destroy();

// Descriptors run on the CPU's thread
const { encode_worker_options } = await import("../../src/browser/cpu_worker.js");
globalThis.location = { href: "http://localhost/" };
assert.throws(() => encode_worker_options({ "virtio_devices": [echo.descriptor] }), /CPU Worker cannot transfer virtio_devices/);

await emulator.destroy();
console.log("PASS: custom virtio devices");
                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/devices/virtio_gpu.js                                                              0000755 0000000 0000000 00000051205 00000000000 015203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu as virtio-vga (src/graphics_adapters/virtio_gpu), after SeaBIOS
// and the VGA BIOS have set it up, driven through its transport the way a
// driver does: PCI identity and layout (VRAM in BAR0, the capabilities in
// the memory BAR2, as QEMU's virtio-vga), the VGA core until the first control command, display
// information and EDID, 2D resources with scattered backing (guest RAM and
// the frame buffer), scanouts and flushes, fences, errors, the cursor queue,
// display events from V86.set_display_size, two displays, snapshots and
// resets. The guests' drivers are tested by tests/x64/linux_gpu.mjs.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const VRAM = 16 << 20;
const MEMORY = 64 << 20;
const emulator = new V86({
    graphics_adapter: "virtio_gpu",
    graphics_adapter_test: { scanouts: 2, level: "2d-blob" },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: MEMORY,
    vram_size: VRAM,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;

// PCI identity: what Linux's virtio_pci and viogpudo's INF match
assert.equal(pci_read(0x00), 0x10501AF4, "virtio-gpu, modern");
assert.equal(pci_read(0x2C), 0x11001AF4, "subsystem 1AF4:1100");
assert.equal(pci_read(0x08), 0x03000001, "revision 1, a VGA controller");
const bar0 = pci_read(0x10), bar2 = pci_read(0x18);
assert.equal(bar0 & 0xF, 0x8, "BAR0 is prefetchable memory");
assert.equal(bar2 & 0xF, 0x0, "BAR2 is memory");
assert.deepEqual([0x14, 0x1C, 0x20, 0x24].map(pci_read), [0, 0, 0, 0], "no other BARs");
const fb = (bar0 & ~0xF) >>> 0, mmio = (bar2 & ~0xF) >>> 0;
assert.equal(fb % VRAM, 0, "BAR0 aligned to its size");
assert.equal(mmio % 0x20000, 0, "BAR2 aligned to its size (at least a block of v86's memory map)");
assert.equal(gpu.vga.lfb_address, fb, "the VGA core's frame buffer follows BAR0");
console.log(`SeaBIOS put the frame buffer at ${fb.toString(16)}, the capabilities at ${mmio.toString(16)}`);

// The capabilities: all four in BAR1, at their windows
const caps = {};
for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
{
    if(pci_read8(at) !== 0x09) continue;
    caps[pci_read8(at + 3)] = { bar: pci_read8(at + 4), offset: pci_read(at + 8), length: pci_read(at + 12) };
}
assert.deepEqual([1, 2, 3, 4].map(type => caps[type].bar), [2, 2, 2, 2], "common, notify, ISR and device config share BAR2");
assert.deepEqual([1, 2, 3, 4].map(type => caps[type].offset), [0, 0x100, 0x200, 0x300]);
assert.ok(caps[5], "and the PCI configuration access capability");
const common = mmio, notify = mmio + 0x100, isr = mmio + 0x200, config = mmio + 0x300;
// The capabilities through the memory map, as the CPU reaches them (16-bit
// writes arrive a byte at a time)
const mmio_read8 = address => cpu.mmap_read8(address);
const mmio_read16 = address => cpu.mmap_read8(address) | cpu.mmap_read8(address + 1) << 8;
const mmio_read32 = address => cpu.mmap_read32(address) >>> 0;
const mmio_write8 = (address, value) => cpu.mmap_write8(address, value);
const mmio_write16 = (address, value) => cpu.mmap_write16(address, value);
const mmio_write32 = (address, value) => cpu.mmap_write32(address, value);
assert.equal(mmio_read32(config + 8), 2, "num_scanouts");
assert.equal(mmio_read32(config + 12), 0, "num_capsets: no 3D at the 2d level");
assert.ok(cpu.devices.vga === gpu.vga, "the VGA core is the machine's VGA");
// Status is read-only or write-1-to-clear: Windows clears it with a 16-bit
// write, which must leave the capability list (virtio drivers look for it)
io.port_write32(0xcf8, 0x80000000 | BDF << 8 | 0x04);
io.port_write16(0xcfe, 0xFFFF);
assert.equal(pci_read(0x04) >>> 16 & 0x10, 0x10, "the capability list survives a write to the status register");
io.port_write8(0xcfe, 0);
assert.equal(pci_read(0x04) >>> 16 & 0x10, 0x10, "and a byte write");

// An OS that moves BAR2: the capabilities follow, the old place is unmapped
const pci_write = (reg, value) => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); io.port_write32(0xcfc, value); };
const MOVED = 0xFEA00000;
pci_write(0x18, MOVED);
assert.equal(cpu.mmap_read32(MOVED + 0x300 + 8) >>> 0, 2, "num_scanouts at the new place");
assert.equal(cpu.mmap_read8(mmio + 0x300 + 8), 0xFF, "nothing at the old one");
pci_write(0x18, mmio);
assert.equal(mmio_read32(config + 8), 2, "and back");
console.log("PASS: PCI identity, BARs and capabilities");

// Guest memory
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
const read_bytes = (address, length) => Array.from({ length }, (_, i) => cpu.read8(address + i));

// The transport: features, two queues
const w8 = (offset, value) => mmio_write8(common + offset, value);
const w16 = (offset, value) => mmio_write16(common + offset, value);
const w32 = (offset, value) => mmio_write32(common + offset, value);
const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
    { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];

function start_driver()
{
    w8(20, 0);
    w8(20, 3);
    w32(0, 0);
    const features0 = mmio_read32(common + 4) >>> 0;
    assert.equal(features0 & 6, 6, "EDID and RESOURCE_UUID");
    assert.equal(features0 & 1, 0, "no VIRGL at the 2d level");
    w32(0, 1);
    assert.equal(mmio_read32(common + 4) & 1, 1, "VIRTIO_F_VERSION_1");
    w32(8, 0); w32(12, 6); w32(8, 1); w32(12, 1);
    w8(20, 11);
    assert.equal(mmio_read8(common + 20), 11, "FEATURES_OK accepted");
    // (viogpudo always asks for configuration vector 0 and gives up when it
    // does not read back; interrupts stay INTx)
    w16(16, 0);
    assert.equal(mmio_read16(common + 16), 0, "msix_config keeps what the driver writes");
    QUEUES.forEach((q, i) => {
        w16(22, i);
        q.size = mmio_read16(common + 24);
        w16(26, 0xFFFF);
        assert.equal(mmio_read16(common + 26), 0xFFFF, "queue_msix_vector");
        w32(32, q.desc); w32(36, 0);
        w32(40, q.avail); w32(44, 0);
        w32(48, q.used); w32(52, 0);
        for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
        q.avail_idx = 0;
        w16(28, 1);
    });
    w8(20, 15);
}

const REQUEST = 0x200000, REPLY = 0x280000;
/**
 * A request on a queue: its bytes, readable, then a writable reply buffer
 * (in two descriptors, as Linux sends ATTACH_BACKING's entries)
 */
function submit(queue_index, parts, reply_size = 2048)
{
    const q = QUEUES[queue_index];
    let address = REQUEST, d = 0;
    for(const part of parts)
    {
        write_bytes(address, part);
        write32(q.desc + d * 16, address); write32(q.desc + d * 16 + 4, 0);
        write32(q.desc + d * 16 + 8, part.length);
        cpu.write8(q.desc + d * 16 + 12, 1);
        cpu.write8(q.desc + d * 16 + 14, d + 1);
        address += part.length + 64 & ~63;
        d++;
    }
    if(reply_size)
    {
        for(let i = 0; i < reply_size; i += 4) write32(REPLY + i, 0xDEADBEEF);
        write32(q.desc + d * 16, REPLY); write32(q.desc + d * 16 + 4, 0);
        write32(q.desc + d * 16 + 8, reply_size);
        cpu.write8(q.desc + d * 16 + 12, 2);
    }
    else
    {
        cpu.write8(q.desc + (d - 1) * 16 + 12, 0);
    }
    cpu.write8(q.desc + d * 16 + 13, 0);
    write32(q.avail + 4 + (q.avail_idx % q.size) * 2, 0);
    q.avail_idx = q.avail_idx + 1 & 0xFFFF;
    cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
    cpu.write8(q.avail + 3, q.avail_idx >> 8);
    const used_before = read32(q.used) >>> 16;
    mmio_write16(notify, queue_index);
    const used_after = read32(q.used) >>> 16;
    assert.equal(used_after, used_before + 1 & 0xFFFF, "the request is completed at once");
    return read32(q.used + 4 + ((used_after - 1) % q.size) * 8 + 4);
}

const header = (type, flags = 0, fence = 0) => {
    const h = new Uint8Array(24), v = new DataView(h.buffer);
    v.setUint32(0, type, true); v.setUint32(4, flags, true); v.setUint32(8, fence, true);
    return h;
};
const words = (...values) => new Uint8Array(new Uint32Array(values).buffer);
const concat = (...parts) => { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let at = 0; for(const p of parts) { out.set(p, at); at += p.length; } return out; };
const command = (type, ...values) => submit(0, [concat(header(type), words(...values))]);
const reply_type = () => read32(REPLY);
const OK = 0x1100;

// The VGA core is on screen until the driver sends a control command
let layers = [];
cpu.devices.display.update_buffer = l => { layers = layers.concat(l); };
assert.ok(!gpu.active);
start_driver();
assert.ok(!gpu.active, "DRIVER_OK alone does not take the screen");

// GET_DISPLAY_INFO: the first display on, 1024x768, the second off
assert.equal(command(0x0100), 24 + 16 * 24, "the whole response is written");
assert.equal(reply_type(), 0x1101);
assert.deepEqual([0, 1, 2, 3, 4].map(i => read32(REPLY + 24 + i * 4)), [0, 0, 1024, 768, 1]);
assert.equal(read32(REPLY + 24 + 24 + 16), 0, "the second display is off");
assert.ok(gpu.active, "the driver has the screen");

// GET_EDID: a valid EDID 1.4 whose preferred mode is the display's size
command(0x010A, 0, 0);
assert.equal(reply_type(), 0x1104);
assert.equal(read32(REPLY + 24), 128);
const edid = read_bytes(REPLY + 32, 128);
assert.deepEqual(edid.slice(0, 8), [0, 255, 255, 255, 255, 255, 255, 0], "the EDID header");
assert.equal(edid.reduce((a, b) => a + b) & 0xFF, 0, "the checksum");
assert.deepEqual([edid[18], edid[19]], [1, 4], "EDID 1.4");
assert.equal(edid[56] | (edid[58] >> 4) << 8, 1024, "preferred width");
assert.equal(edid[59] | (edid[61] >> 4) << 8, 768, "preferred height");
console.log("PASS: display information and EDID");

// A 64x48 B8G8R8X8 resource, its backing in three pieces: a page of RAM, the
// frame buffer (as viogpudo backs its resources), RAM again
const W = 64, H = 48, STRIDE = W * 4;
const pieces = [[0x300000, 4096], [fb + 0x10000, 4096], [0x310000, STRIDE * H - 8192]];
const pixel_address = offset => {
    for(const [address, length] of pieces)
    {
        if(offset < length) return address + offset;
        offset -= length;
    }
    throw new Error("outside the backing");
};
const put = (x, y, bgrx) => write32(pixel_address(y * STRIDE + x * 4), bgrx);
for(let y = 0; y < H; y++) for(let x = 0; x < W; x++) put(x, y, x | y << 8 | 0x40 << 16);
assert.equal(command(0x0101, 1, 2, W, H), 24);
assert.equal(reply_type(), OK);
const entries = concat(...pieces.map(([address, length]) => words(address >>> 0, Math.floor(address / 2 ** 32), length, 0)));
submit(0, [concat(header(0x0106), words(1, pieces.length)), entries]);
assert.equal(reply_type(), OK, "ATTACH_BACKING with its entries in a second descriptor");
command(0x0105, 0, 0, W, H, 0, 0, 1, 0);
assert.equal(reply_type(), OK, "TRANSFER_TO_HOST_2D");
command(0x0103, 0, 0, W, H, 0, 1);
assert.equal(reply_type(), OK, "SET_SCANOUT");
const scanout = gpu.scanouts[0];
const shown = (x, y) => [...scanout.rgba.subarray((y * W + x) * 4, (y * W + x) * 4 + 4)];
assert.deepEqual(shown(5, 7), [0x40, 7, 5, 255], "B8G8R8X8, converted");
assert.deepEqual(shown(10, 16), [0x40, 16, 10, 255], "from the frame buffer page");
assert.deepEqual(shown(63, 47), [0x40, 47, 63, 255], "the last pixel");

// Changes show after a transfer of their rectangle and a flush
put(20, 30, 0x00FF00FF);
put(21, 30, 0x0000FF00);
command(0x0105, 20, 30, 2, 1, 30 * STRIDE + 20 * 4, 0, 1, 0);
assert.deepEqual(shown(20, 30), [0x40, 30, 20, 255], "a transfer alone does not reach the display");
command(0x0104, 16, 28, 8, 4, 1, 0);
assert.deepEqual(shown(20, 30), [0xFF, 0, 0xFF, 255], "RESOURCE_FLUSH");
assert.deepEqual(shown(21, 30), [0, 0xFF, 0, 255]);

// What the display gets: the mode, then the picture
cpu.devices.display.request_frame(true);
assert.ok(layers.some(l => l.pixels.data === scanout.rgba && l.buffer_width === W), "the scanout is on screen");
console.log("PASS: resources, backing in RAM and VRAM, transfers, scanouts and flushes");

// Fences: the response carries the request's
submit(0, [concat(header(0x0104, 1, 0x1234), words(0, 0, 1, 1, 1, 0))]);
assert.equal(reply_type(), OK);
assert.equal(read32(REPLY + 4), 1, "VIRTIO_GPU_FLAG_FENCE");
assert.equal(read32(REPLY + 8), 0x1234, "the fence id");

// Errors
command(0x0101, 1, 2, 8, 8);
assert.equal(reply_type(), 0x1203, "a resource ID in use");
command(0x0101, 2, 99, 8, 8);
assert.equal(reply_type(), 0x1205, "an unknown format");
command(0x0103, 0, 0, W + 1, H, 0, 1);
assert.equal(reply_type(), 0x1205, "a scanout rectangle outside the resource");
command(0x0103, 0, 0, W, H, 7, 1);
assert.equal(reply_type(), 0x1202, "an unknown scanout");
command(0x0105, 0, 0, W, H, 0, 0, 9, 0);
assert.equal(reply_type(), 0x1203, "a transfer to no resource");
command(0x0108, 0, 0);
assert.equal(reply_type(), 0x1205, "no capsets");
command(0x7777);
assert.equal(reply_type(), 0x1200, "an unknown command");

// RESOURCE_ASSIGN_UUID: the same one each time
command(0x010B, 1, 0);
assert.equal(reply_type(), 0x1105);
const uuid = read_bytes(REPLY + 24, 16);
command(0x010B, 1, 0);
assert.deepEqual(read_bytes(REPLY + 24, 16), uuid);
assert.equal(uuid[6] >> 4, 4, "a version 4 UUID");
console.log("PASS: fences, errors and UUIDs");

// The cursor queue: a 2x2 B8G8R8A8 cursor, then moved; no reply
command(0x0101, 5, 1, 2, 2);
for(let i = 0; i < 4; i++) write32(0x320000 + i * 4, 0xFF0000FF);
command(0x0106, 5, 1, 0x320000, 0, 16, 0);
command(0x0105, 0, 0, 2, 2, 0, 0, 5, 0);
assert.equal(submit(1, [concat(header(0x0300), words(0, 10, 12, 0, 5, 1, 1, 0))], 0), 0, "nothing written");
assert.ok(gpu.cursor.visible);
layers = [];
cpu.devices.display.request_frame(false);
let patch = layers[layers.length - 1];
assert.deepEqual([patch.screen_x, patch.screen_y], [9, 11], "the hotspot at (1, 1)");
assert.deepEqual([...patch.pixels.data.subarray(0, 4)], [0, 0, 255, 255], "an opaque blue cursor");
submit(1, [concat(header(0x0301), words(0, 30, 20, 0, 0, 0, 0, 0))], 0);
layers = [];
cpu.devices.display.request_frame(false);
assert.equal(layers[0].screen_x, 9, "the picture under its old place first");
patch = layers[layers.length - 1];
assert.deepEqual([patch.screen_x, patch.screen_y], [29, 19], "MOVE_CURSOR");
submit(1, [concat(header(0x0300), words(0, 30, 20, 0, 0, 0, 0, 0))], 0);
assert.ok(!gpu.cursor.visible, "resource 0 hides it");
console.log("PASS: the cursor queue");

// The page's size: a display event, then the new size and EDID
mmio_read8(isr);
emulator.set_display_size(1280, 720);
assert.equal(mmio_read32(config), 1, "events_read: VIRTIO_GPU_EVENT_DISPLAY");
assert.equal(mmio_read8(isr), 3, "a configuration change interrupt (both bits, as QEMU: viogpudo's INTx handler takes only 1 and 3)");
mmio_write32(config + 4, 1);
assert.equal(mmio_read32(config), 0, "events_clear");
command(0x0100);
assert.deepEqual([2, 3].map(i => read32(REPLY + 24 + i * 4)), [1280, 720]);
command(0x010A, 0, 0);
assert.equal(cpu.read8(REPLY + 32 + 56) | (cpu.read8(REPLY + 32 + 58) >> 4) << 8, 1280);
emulator.set_display_size(1280, 720);
assert.equal(mmio_read32(config), 0, "the same size again is no event");

// A second display, beside the first
emulator.set_display_size(800, 600, 1);
command(0x0100);
assert.deepEqual([0, 1, 2, 3, 4].map(i => read32(REPLY + 48 + i * 4)), [1280, 0, 800, 600, 1], "the second display, on");
command(0x0101, 2, 2, 32, 32);
command(0x0106, 2, 1, 0x330000, 0, 32 * 32 * 4, 0);
for(let i = 0; i < 32 * 32; i++) write32(0x330000 + i * 4, 0x00808080);
command(0x0105, 0, 0, 32, 32, 0, 0, 2, 0);
command(0x0103, 0, 0, 32, 32, 1, 2);
assert.equal(reply_type(), OK);
layers = [];
cpu.devices.display.request_frame(true);
const second = layers.find(l => l.pixels.data === gpu.scanouts[1].rgba);
assert.equal(second.screen_x, W, "the second display is drawn beside the first");
console.log("PASS: display events from the page's size, two displays");

// Snapshots
const state = await emulator.save_state();
command(0x0102, 1, 0);
assert.equal(scanout.resource_id, 0, "RESOURCE_UNREF switches its displays off");
await emulator.restore_state(state);
// (the rings are guest RAM: back to where they were)
for(const q of QUEUES) q.avail_idx = read32(q.avail) >>> 16;
assert.equal(gpu.resources.size, 3);
assert.deepEqual([...gpu.scanouts[0].rgba.subarray((30 * W + 20) * 4, (30 * W + 20) * 4 + 4)], [0xFF, 0, 0xFF, 255],
    "the scanout's picture is back");
assert.equal(mmio_read8(common + 20), 15, "the transport is back");
put(0, 0, 0x00123456);
command(0x0105, 0, 0, 1, 1, 0, 0, 1, 0);
command(0x0104, 0, 0, 1, 1, 1, 0);
assert.deepEqual([...gpu.scanouts[0].rgba.subarray(0, 4)], [0x12, 0x34, 0x56, 255], "and the restored queues and backing work");
console.log("PASS: snapshots");

// Blobs in guest memory (level 2d-blob): a scanout shows one straight from
// there, as SET_SCANOUT_BLOB describes it; a flush is enough
{
    const BW = 32, BH = 20, BSTRIDE = 160, BOFFSET = 64;
    const blob = [[0x380000, 2048], [0x390000, BOFFSET + BSTRIDE * BH - 2048]];
    const blob_address = offset => {
        for(const [address, length] of blob)
        {
            if(offset < length) return address + offset;
            offset -= length;
        }
        throw new Error("outside the blob");
    };
    const bput = (x, y, bgrx) => write32(blob_address(BOFFSET + y * BSTRIDE + x * 4), bgrx);
    for(let y = 0; y < BH; y++) for(let x = 0; x < BW; x++) bput(x, y, x | y << 8 | 0x22 << 16);
    const size = BOFFSET + BSTRIDE * BH;
    const blob_entries = concat(...blob.map(([address, length]) => words(address, 0, length, 0)));
    // resource 9, BLOB_MEM_GUEST, shareable, 2 entries, blob id 0, size
    submit(0, [concat(header(0x010C), words(9, 1, 2, blob.length, 0, 0, size, 0)), blob_entries]);
    assert.equal(reply_type(), OK, "RESOURCE_CREATE_BLOB");
    // rectangle (2, 3, 24 x 16), scanout 1, resource 9, 32 x 20, B8G8R8X8, padding, strides, offsets
    command(0x010D, 2, 3, 24, 16, 1, 9, BW, BH, 2, 0, BSTRIDE, 0, 0, 0, BOFFSET, 0, 0, 0);
    assert.equal(reply_type(), OK, "SET_SCANOUT_BLOB");
    const second = gpu.scanouts[1];
    const bshown = (x, y) => [...second.rgba.subarray((y * 24 + x) * 4, (y * 24 + x) * 4 + 4)];
    assert.deepEqual(bshown(0, 0), [0x22, 3, 2, 255], "the rectangle's first pixel, from guest memory");
    assert.deepEqual(bshown(23, 15), [0x22, 18, 25, 255], "its last (across the blob's two pieces)");
    bput(10, 10, 0x00ABCDEF);
    command(0x0104, 0, 0, BW, BH, 9, 0);
    assert.deepEqual(bshown(8, 7), [0xAB, 0xCD, 0xEF, 255], "RESOURCE_FLUSH reads it again");
    command(0x0105, 0, 0, 1, 1, 0, 0, 9, 0);
    assert.equal(reply_type(), OK, "a transfer to a blob has nothing to do");
    command(0x010D, 0, 0, 64, 64, 1, 9, BW, BH, 2, 0, BSTRIDE, 0, 0, 0, BOFFSET, 0, 0, 0);
    assert.notEqual(reply_type(), OK, "a rectangle outside the blob's picture");
    const blob_state = await emulator.save_state();
    await emulator.restore_state(blob_state);
    for(const q of QUEUES) q.avail_idx = read32(q.avail) >>> 16;
    bput(11, 10, 0x00102030);
    command(0x0104, 0, 0, BW, BH, 9, 0);
    assert.deepEqual(bshown(9, 7), [0x10, 0x20, 0x30, 255], "a restored blob scanout");
    command(0x0102, 9, 0);
    assert.equal(second.resource_id, 0);
}
console.log("PASS: blobs in guest memory and their scanouts");

// A device reset gives the screen back to the VGA core
w8(20, 0);
assert.ok(!gpu.active);
assert.equal(gpu.resources.size, 0);
start_driver();
command(0x0100);
assert.ok(gpu.active);
// and so does a machine reset
await emulator.restart();
assert.ok(!gpu.active);
assert.equal(mmio_read8(common + 20), 0);
assert.equal(mmio_read32(config + 8), 2, "the capabilities still answer at BAR2 (the BIOS's VGA ROM window does not cover them)");
console.log("PASS: resets");

await emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/devices/virtio_gpu_gfxstream.js                                                    0000755 0000000 0000000 00000035346 00000000000 017273  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu's gfxstream transport (level gfxstream, src/graphics_adapters/
// virtio_gpu/gfxstream.js; docs/gfxstream-protocol.md), driven as the
// guest's gfxstream transport (mesa's AddressSpaceStream, gfxstream's
// VirtioGpuPipeStream) drives it: the capsets, a context of capset 3, its
// ASG ring in a HOST3D blob (CONTEXT_CREATE, then mapped: the host's config),
// the stream's commands through type 1 and large transfers with PING, the
// replies through the from-host ring, a decoder that waits (the host's
// state), the sync commands' tasks and the fences of each ring answered on
// their own, and the process pipe (GLProcessPipe) of a pipe resource.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// a renderer that answers at once
const renderer = {
    "post": message => { if(message["type"] === "submit") to_device({ "type": "done", "seq": message["seq"] }); },
    "listen": handler => { to_device = handler; },
};
let to_device = null;

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const emulator = new V86({
    graphics_adapter: "virtio_gpu",
    graphics_adapter_test: { level: "gfxstream", renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 64 << 20,
    vram_size: 16 << 20,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;

const hostmem = (pci_read(0x20) & ~0xF) >>> 0;
assert.ok(hostmem, "BAR4 placed");

let common = 0, notify = 0, device_config = 0;
const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
{
    if(pci_read8(at) !== 0x09) continue;
    const type = pci_read8(at + 3);
    if(type === 1) common = bar2 + pci_read(at + 8);
    if(type === 2) notify = bar2 + pci_read(at + 8);
    if(type === 4) device_config = bar2 + pci_read(at + 8);
}

const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
const read_bytes = (address, length) => Uint8Array.from({ length }, (_, i) => cpu.read8(address + i));
const w8 = (offset, value) => cpu.write8(common + offset, value);
const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
    { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];

w8(20, 0);
w8(20, 3);
write32(common, 0);
const features0 = read32(common + 4);
assert.equal(features0 & 0x19, 0x19, "VIRGL, RESOURCE_BLOB, CONTEXT_INIT");
write32(common + 8, 0); write32(common + 12, features0);
write32(common + 8, 1); write32(common + 12, 1);
w8(20, 11);
QUEUES.forEach((q, i) => {
    w16(22, i);
    q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
    write32(common + 32, q.desc); write32(common + 36, 0);
    write32(common + 40, q.avail); write32(common + 44, 0);
    write32(common + 48, q.used); write32(common + 52, 0);
    for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
    w16(28, 1);
});
w8(20, 15);

// One request at a time, each in its own slot; answered(slot) whether it was
const REQUEST = 0x200000, REPLY = 0x280000, SLOT = 0x1000;
let next_slot = 0;
const used_idx = () => read32(QUEUES[0].used) >>> 16;
function send(bytes, wait = true)
{
    const q = QUEUES[0];
    const slot = next_slot++ % 16;
    const head = slot * 2;
    write_bytes(REQUEST + slot * SLOT, bytes);
    for(let i = 0; i < 256; i += 4) write32(REPLY + slot * SLOT + i, 0xDEADBEEF);
    write32(q.desc + head * 16, REQUEST + slot * SLOT); write32(q.desc + head * 16 + 4, 0);
    write32(q.desc + head * 16 + 8, bytes.length);
    cpu.write8(q.desc + head * 16 + 12, 1); cpu.write8(q.desc + head * 16 + 14, head + 1);
    write32(q.desc + (head + 1) * 16, REPLY + slot * SLOT); write32(q.desc + (head + 1) * 16 + 4, 0);
    write32(q.desc + (head + 1) * 16 + 8, 256);
    cpu.write8(q.desc + (head + 1) * 16 + 12, 2);
    write32(q.avail + 4 + (q.avail_idx % q.size) * 2, head);
    q.avail_idx = q.avail_idx + 1 & 0xFFFF;
    cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
    cpu.write8(q.avail + 3, q.avail_idx >> 8);
    const before = used_idx();
    cpu.write8(notify, 0);
    cpu.write8(notify + 1, 0);
    if(wait) assert.equal(used_idx(), before + 1 & 0xFFFF, "answered at once");
    return slot;
}
const answer = slot => read32(REPLY + slot * SLOT);
const CTX = 1;
/** a control request: its type, a fence (on a ring) if given, its fields */
const control = (type, values, wait, fence = null) => {
    const out = new Uint32Array(6 + values.length);
    out[0] = type;
    if(fence)
    {
        out[1] = 1 | (fence.ring !== undefined ? 2 : 0);
        out[2] = fence.id;
        out[5] = fence.ring || 0;
    }
    out[4] = CTX;
    out.set(values, 6);
    return send(new Uint8Array(out.buffer), wait);
};
const command = (type, ...values) => answer(control(type, values));
const OK = 0x1100, OK_CAPSET_INFO = 0x1102, OK_CAPSET = 0x1103, OK_MAP_INFO = 0x1106;

// ---------------------------------------------------------------------------
// The capsets: gfxstream's alone

assert.equal(read32(device_config + 12), 2, "num_capsets: 2");
let slot = control(0x0108, [0, 0]);
assert.equal(answer(slot), OK_CAPSET_INFO);
assert.deepEqual([24, 28, 32].map(o => read32(REPLY + slot * SLOT + o)), [3, 0, 108], "capset 3 (gfxstream Vulkan), 108 bytes");
slot = control(0x0108, [1, 0]);
assert.deepEqual([24, 28, 32].map(o => read32(REPLY + slot * SLOT + o)), [9, 0, 16], "capset 9 (gfxstream composer), 16 bytes");
slot = control(0x0109, [3, 0]);
assert.equal(answer(slot), OK_CAPSET);
const vulkan_capset = Array.from({ length: 27 }, (_, i) => read32(REPLY + slot * SLOT + 24 + i * 4));
assert.deepEqual(vulkan_capset.slice(0, 7), [1, 12288, 1 << 20, 0, 1, 4096, 1],
    "protocolVersion 1, ringSize 12288, bufferSize 1 MiB, deferredMapping, blobAlignment 4096, noRenderControlEnc");
assert.equal(vulkan_capset[26], 1, "hasTraceAsyncCommand");
console.log("PASS: the gfxstream capsets");

// A context of capset 3, its ring's blob (ring storage and buffer), CONTEXT_CREATE, mapped
assert.equal(command(0x0200, 0, 3), OK, "CTX_CREATE, capset 3");
assert.ok(gpu.gfxstream.contexts.has(CTX));
const RING_RES = 10, RING_AT = 0x100000, RING_SIZE = 12288, BUFFER_SIZE = 1 << 20;
const HOST3D = 2, MAPPABLE = 1;
assert.equal(command(0x010C, RING_RES, HOST3D, MAPPABLE, 0, 0, 0, RING_SIZE + BUFFER_SIZE, 0), OK, "RESOURCE_CREATE_BLOB, blob id 0");
const submit_3d = (words, wait, fence) => control(0x0207, [words.length * 4, 0, ...words], wait, fence);
assert.equal(answer(submit_3d([0x1001, RING_RES])), OK, "CONTEXT_CREATE");
assert.equal(command(0x0208, RING_RES, 0, RING_AT, 0), OK_MAP_INFO, "MAP_BLOB");
const ring = hostmem + RING_AT, buffer = ring + RING_SIZE, config = ring + 2180;
assert.deepEqual([0, 4, 8, 16, 24].map(o => read32(config + o)), [BUFFER_SIZE, 4096, 0, 1, 0],
    "the ring's config: buffer_size, flush_interval, host_consumed_pos, transfer_mode 1, in_error");
assert.equal(read32(ring + 2176), 0, "the host's state: NEED_NOTIFY");
console.log("PASS: a context's ASG ring");

// A decoder of 12340-12349 that answers what it got, and 12345's
const decoded = [];
let held = null;
let ready_12349 = false;
gpu.gfxstream.decoders.push({ name: "test", first: 12340, last: 12349, decode: (ctx, ring, opcode, payload, reply) => {
    if(opcode === 12349 && !ready_12349) return gpu.gfxstream.AGAIN;
    decoded.push([opcode, Array.from(payload)]);
    if(opcode === 12342) ready_12349 = true;
    if(opcode === 12345) reply(payload.slice());
    if(opcode === 12346) return done => { held = done; };
    return null;
} });
const packet = (opcode, ...bytes) => {
    const out = new Uint8Array(8 + bytes.length), v = new DataView(out.buffer);
    v.setUint32(0, opcode, true); v.setUint32(4, out.length, true);
    out.set(bytes, 8);
    return out;
};
let write_offset = 0, write_pos = 0;
/** bytes into the buffer, a type 1 transfer of them onto the to-host ring */
const type1 = bytes => {
    write_bytes(buffer + write_offset, bytes);
    write32(ring + 128 + (write_pos & 2047), write_offset);
    write32(ring + 128 + (write_pos & 2047) + 4, bytes.length);
    write_pos = write_pos + 8 >>> 0;
    write32(ring + 8, write_pos);
    write_offset = (write_offset + 4096) % BUFFER_SIZE;
};
const ping = () => assert.equal(answer(submit_3d([0x1002, RING_RES])), OK, "PING");

// the client's flags, then a command with its reply
type1(Uint8Array.of(0, 0, 0, 0, ...packet(12345, 7, 8, 9, 10)));
ping();
assert.deepEqual(decoded, [[12345, [7, 8, 9, 10]]], "the command decoded");
assert.equal(read32(ring + 64), 8, "to-host read_pos moved on");
assert.equal(read32(config + 8), 16, "host_consumed_pos");
assert.equal(read32(ring + 8192 + 8), 4, "from-host write_pos: the reply's 4 bytes");
assert.deepEqual(Array.from(read_bytes(buffer, 4)), [7, 8, 9, 10], "the reply in the buffer");
console.log("PASS: a command and its reply");

// an unknown command skipped; a command split across two transfers
type1(packet(55555, 1, 2, 3, 4));
const split = packet(12347, 5, 6, 7, 8, 9, 10, 11, 12);
type1(split.subarray(0, 6));
ping();
assert.equal(gpu.gfxstream.stats.unknown[55555], 1, "the unknown command counted");
assert.equal(decoded.length, 1, "half a command waits");
type1(split.subarray(6));
ping();
assert.deepEqual(decoded[1], [12347, [5, 6, 7, 8, 9, 10, 11, 12]], "the command, whole");
console.log("PASS: unknown and split commands");

// a large transfer (type 3): its ring's view of the buffer
const large = packet(12348, 42, 43, 44, 45);
const large_pos = read32(ring + 4096 + 8);
write_bytes(buffer + (large_pos & BUFFER_SIZE - 1), large);
write32(ring + 4096 + 8, large_pos + large.length);
ping();
assert.deepEqual(decoded[2], [12348, [42, 43, 44, 45]], "the large transfer's command");
assert.equal(read32(ring + 4096 + 64), large_pos + large.length, "its read_pos");
console.log("PASS: a large transfer");

// a command that waits: the ones after it wait too, the host is rendering
type1(Uint8Array.of(...packet(12346), ...packet(12341, 1)));
ping();
assert.equal(decoded.at(-1)[0], 12346, "the waiting command");
assert.equal(read32(ring + 2176), 4, "the host's state: RENDERING");
held();
assert.deepEqual(decoded.at(-1), [12341, [1]], "the next one once it is done");
assert.equal(read32(ring + 2176), 0, "NEED_NOTIFY again");
console.log("PASS: a command that waits");

// a second ring of the context (another thread's stream): its own stream
// and replies; a command that comes after another ring's (AGAIN) decoded
// once that ring has decoded one
const RING2_RES = 11, RING2_AT = 0x300000;
assert.equal(command(0x010C, RING2_RES, HOST3D, MAPPABLE, 0, 0, 0, RING_SIZE + BUFFER_SIZE, 0), OK, "the second ring's blob");
assert.equal(answer(submit_3d([0x1001, RING2_RES])), OK, "CONTEXT_CREATE of the second ring");
assert.equal(command(0x0208, RING2_RES, 0, RING2_AT, 0), OK_MAP_INFO);
assert.equal(gpu.gfxstream.contexts.get(CTX).rings.size, 2, "two rings");
const ring2 = hostmem + RING2_AT, buffer2 = ring2 + RING_SIZE;
assert.equal(read32(ring2 + 2180 + 16), 1, "its config");
type1(packet(12349, 9));
ping();
assert.notEqual(decoded.at(-1)[0], 12349, "12349 waits for ring 2's command");
write_bytes(buffer2, Uint8Array.of(0, 0, 0, 0, ...packet(12345, 3, 1, 4), ...packet(12342)));
write32(ring2 + 128, 0); write32(ring2 + 132, 23);
write32(ring2 + 8, 8);
assert.equal(answer(submit_3d([0x1002, RING2_RES])), OK, "PING of the second ring");
assert.deepEqual(decoded.slice(-3).map(d => d[0]), [12345, 12342, 12349], "ring 2's commands, then ring 1's");
assert.deepEqual(Array.from(read_bytes(buffer2, 3)), [3, 1, 4], "the reply in ring 2's buffer");
assert.equal(read32(ring2 + 8192 + 8), 3, "ring 2's from-host write_pos");
assert.equal(read32(ring + 64), write_pos, "ring 1's transfers consumed");
console.log("PASS: two rings of a context");

// fences on rings: a sync task of ring 1 holds its fence, not ring 2's
let task_done = null;
// (before Vulkan's, whose tasks these would be)
gpu.gfxstream.decoders.unshift({ name: "sync", first: 0, last: -1, sync_task: (ctx, op, words) => done => { task_done = done; } });
const before = used_idx();
submit_3d([0xa000, 1, 0, 2, 0], false, { id: 100, ring: 1 });
submit_3d([0xf002, 0, 0], false, { id: 101, ring: 2 });
assert.equal(used_idx(), before + 1 & 0xFFFF, "ring 2's fence answered, ring 1's waits");
task_done();
assert.equal(used_idx(), before + 2 & 0xFFFF, "ring 1's once its task is done");
console.log("PASS: the fences of each ring");

// the process pipe: a pipe resource's transfers
const PIPE_RES = 20, PIPE_AT = 0x400000;
assert.equal(command(0x0204, PIPE_RES, 0, 64, 1 << 17, 1 << 20, 1, 1, 1, 0, 0, 0, 0), OK, "RESOURCE_CREATE_3D, a pipe (PIPE_BUFFER, BIND_CUSTOM)");
assert.equal(command(0x0106, PIPE_RES, 1, PIPE_AT, 0, 1 << 20, 0), OK, "RESOURCE_ATTACH_BACKING");
const name = new TextEncoder().encode("pipe:GLProcessPipe\0");
write_bytes(PIPE_AT, name);
const transfer = (type, length) => command(type, 0, 0, 0, length, 1, 1, 0, 0, PIPE_RES, 0, 0, 0);
assert.equal(transfer(0x0205, name.length), OK, "TRANSFER_TO_HOST_3D: the service's name");
write32(PIPE_AT, 100);
assert.equal(transfer(0x0205, 4), OK, "TRANSFER_TO_HOST_3D: the confirmation");
write32(PIPE_AT, 0); write32(PIPE_AT + 4, 0);
assert.equal(transfer(0x0206, 8), OK, "TRANSFER_FROM_HOST_3D");
assert.ok(read32(PIPE_AT) > 0 && read32(PIPE_AT + 4) === 0, "the process's unique id: " + read32(PIPE_AT));
console.log("PASS: the process pipe");

assert.equal(command(0x0201), OK, "CTX_DESTROY");
assert.ok(!gpu.gfxstream.contexts.has(CTX));
assert.equal(gpu.gfxstream.stats.errors, 0, gpu.gfxstream.stats.last_error);
console.log("PASS: CTX_DESTROY");
emulator.destroy();
                                                                                                                                                                                                                                                                                          source/v64/tests/devices/virtio_gpu_gfxstream_render.js                                             0000755 0000000 0000000 00000024445 00000000000 020630  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// gfxstream on a real renderer (headless Chrome's WebGPU,
// tests/x64/gpu_remote_renderer.mjs): Android's gralloc buffers as Vulkan
// sees them (docs/gfxstream-plan.md G3), the steps of
// tests/a64/android/vkahb.c played by hand: a virtio-gpu resource
// (RESOURCE_CREATE_3D, as minigbm makes an AHB), an image of it
// (VkImportColorBufferGOOGLE in vkAllocateMemory), cleared on the GPU, then
// read back with TRANSFER_FROM_HOST_3D as gralloc's lock does.

import assert from "assert/strict";
process.on("unhandledRejection", exn => { throw exn; });

const { gfxstream_machine, OK } = await import("./gfxstream_guest_driver.js");
const { create_remote_renderer } = await import("../x64/gpu_remote_renderer.mjs");

const remote = await create_remote_renderer();
const driver = await gfxstream_machine(remote.renderer);
const { emulator, gpu, command, control, submit_3d, settle, make_ring, call, encode_cb, read_bytes } = driver;
const vulkan = gpu.gfxstream.vulkan;
const errors = () => assert.equal(vulkan.stats.errors, 0, vulkan.stats.last_error);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

assert.equal(command(0x0200, 0, 3), OK, "CTX_CREATE, capset 3 (gfxstream Vulkan)");
driver.ring = make_ring(10, 0x100000);

const STYPE = { INSTANCE_CREATE_INFO: 1, DEVICE_QUEUE_CREATE_INFO: 2, DEVICE_CREATE_INFO: 3, SUBMIT_INFO: 4, MEMORY_ALLOCATE_INFO: 5,
    FENCE_CREATE_INFO: 8, IMAGE_CREATE_INFO: 14, COMMAND_POOL_CREATE_INFO: 39, COMMAND_BUFFER_ALLOCATE_INFO: 40, COMMAND_BUFFER_BEGIN_INFO: 42,
    IMAGE_MEMORY_BARRIER: 45, EXTERNAL_MEMORY_IMAGE_CREATE_INFO: 1000072001, MEMORY_DEDICATED_ALLOCATE_INFO: 1000127001,
    IMPORT_COLOR_BUFFER_GOOGLE: 1000385000 };
const instance = call("vkCreateInstance", { pCreateInfo: { sType: STYPE.INSTANCE_CREATE_INFO, pNext: null, flags: 0, pApplicationInfo: null,
    enabledLayerCount: 0, ppEnabledLayerNames: [], enabledExtensionCount: 0, ppEnabledExtensionNames: [] }, pAllocator: null, pInstance: 0 }).pInstance;
const physical = call("vkEnumeratePhysicalDevices", { instance, pPhysicalDeviceCount: 1, pPhysicalDevices: [0] }).pPhysicalDevices[0];
const device = call("vkCreateDevice", { physicalDevice: physical, pAllocator: null, pDevice: 0,
    pCreateInfo: { sType: STYPE.DEVICE_CREATE_INFO, pNext: null, flags: 0, queueCreateInfoCount: 1,
        pQueueCreateInfos: [{ sType: STYPE.DEVICE_QUEUE_CREATE_INFO, pNext: null, flags: 0, queueFamilyIndex: 0, queueCount: 1, pQueuePriorities: Float32Array.of(1) }],
        enabledLayerCount: 0, ppEnabledLayerNames: [], enabledExtensionCount: 0, ppEnabledExtensionNames: [], pEnabledFeatures: null } }).pDevice;
const queue = call("vkGetDeviceQueue", { device, queueFamilyIndex: 0, queueIndex: 0, pQueue: 0 }).pQueue;
errors();

// The AHB: a resource as minigbm makes it (R8G8B8A8, render target and
// sampler view), its backing in guest memory
const RES = 40, W = 64, H = 64, BACKING = 0x800000;
assert.equal(command(0x0204, RES, 2, 67, 2 | 8, W, H, 1, 1, 0, 0, 0, 0), OK, "RESOURCE_CREATE_3D");
assert.equal(command(0x0106, RES, 1, BACKING, 0, W * H * 4, 0), OK, "RESOURCE_ATTACH_BACKING");

// An image of it, as vkahb makes it and the guest's driver imports it
let a = call("vkCreateImage", { device, pAllocator: null, pImage: 0, pCreateInfo: { sType: STYPE.IMAGE_CREATE_INFO,
    pNext: { sType: STYPE.EXTERNAL_MEMORY_IMAGE_CREATE_INFO, pNext: null, handleTypes: 0x400 },
    flags: 0, imageType: 1, format: 37, extent: { width: W, height: H, depth: 1 }, mipLevels: 1, arrayLayers: 1, samples: 1, tiling: 0,
    usage: 0x2 | 0x4 | 0x10, sharingMode: 0, queueFamilyIndexCount: 0, pQueueFamilyIndices: null, initialLayout: 0 } });
assert.equal(a.ret, 0, "vkCreateImage");
const image = a.pImage;
a = call("vkAllocateMemory", { device, pAllocator: null, pMemory: 0, pAllocateInfo: { sType: STYPE.MEMORY_ALLOCATE_INFO,
    pNext: { sType: STYPE.MEMORY_DEDICATED_ALLOCATE_INFO, image, buffer: 0,
        pNext: { sType: STYPE.IMPORT_COLOR_BUFFER_GOOGLE, pNext: null, colorBuffer: RES } },
    allocationSize: W * H * 4, memoryTypeIndex: 0 } });
assert.equal(a.ret, 0, "vkAllocateMemory importing the resource");
const memory = a.pMemory;
assert.equal(call("vkBindImageMemory", { device, image, memory, memoryOffset: 0 }).ret, 0, "vkBindImageMemory");
assert.ok([...vulkan.vk.imports.values()].some(([, resource]) => resource === RES), "the image is the resource's surface");
errors();

const pool = call("vkCreateCommandPool", { device, pAllocator: null, pCommandPool: 0,
    pCreateInfo: { sType: STYPE.COMMAND_POOL_CREATE_INFO, pNext: null, flags: 2, queueFamilyIndex: 0 } }).pCommandPool;
const cb = call("vkAllocateCommandBuffers", { device, pAllocateInfo: { sType: STYPE.COMMAND_BUFFER_ALLOCATE_INFO, pNext: null, commandPool: pool,
    level: 0, commandBufferCount: 1 }, pCommandBuffers: [0] }).pCommandBuffers[0];
const range = { aspectMask: 1, baseMipLevel: 0, levelCount: 1, baseArrayLayer: 0, layerCount: 1 };
let next_fence = 5;

/**
 * The image cleared on the GPU (as vkahb does: to the transfer layout, the
 * clear, released to gralloc's), then the resource read back as gralloc's
 * lock does (TRANSFER_FROM_HOST_3D into the backing)
 */
async function clear_and_read(image, res, colour, what)
{
    const barrier = (old_layout, new_layout, src, dst) => ({ srcStageMask: 1, dstStageMask: 0x1000, dependencyFlags: 0,
        memoryBarrierCount: 0, pMemoryBarriers: null, bufferMemoryBarrierCount: 0, pBufferMemoryBarriers: null, imageMemoryBarrierCount: 1,
        pImageMemoryBarriers: [{ sType: STYPE.IMAGE_MEMORY_BARRIER, pNext: null, srcAccessMask: src, dstAccessMask: dst, oldLayout: old_layout,
            newLayout: new_layout, srcQueueFamilyIndex: 0xFFFFFFFF, dstQueueFamilyIndex: 0xFFFFFFFF, image, subresourceRange: range }] });
    const recorded = [
        encode_cb("vkBeginCommandBufferAsyncGOOGLE", { pBeginInfo: { sType: STYPE.COMMAND_BUFFER_BEGIN_INFO, pNext: null, flags: 1, pInheritanceInfo: null } }),
        encode_cb("vkCmdPipelineBarrier", barrier(0, 7, 0, 0x1000)),
        encode_cb("vkCmdClearColorImage", { image, imageLayout: 7, pColor: { float32: Float32Array.from(colour) }, rangeCount: 1, pRanges: [range] }),
        encode_cb("vkCmdPipelineBarrier", barrier(7, 1, 0x1000, 0)),
        encode_cb("vkEndCommandBufferAsyncGOOGLE", {}),
    ];
    const data = new Uint8Array(recorded.reduce((n, c) => n + c.length, 0));
    recorded.reduce((at, c) => { data.set(c, at); return at + c.length; }, 0);
    call("vkQueueFlushCommandsGOOGLE", { queue, commandBuffer: cb, dataSize: data.length, pData: data });
    const fence = call("vkCreateFence", { device, pAllocator: null, pFence: 0, pCreateInfo: { sType: STYPE.FENCE_CREATE_INFO, pNext: null, flags: 0 } }).pFence;
    call("vkQueueSubmitAsyncGOOGLE", { queue, submitCount: 1, fence,
        pSubmits: [{ sType: STYPE.SUBMIT_INFO, pNext: null, waitSemaphoreCount: 0, pWaitSemaphores: null, pWaitDstStageMask: null,
            commandBufferCount: 1, pCommandBuffers: [cb], signalSemaphoreCount: 0, pSignalSemaphores: null }] });
    submit_3d([0xa000, device, 0, fence, 0], false, { id: next_fence++, ring: 1 });
    await settle(what + ": CREATE_EXPORT_SYNC_VK of the clear's fence");
    assert.equal(call("vkGetFenceStatus", { device, fence }).ret, 0, what + ": the fence signaled");
    call("vkDestroyFence", { device, fence, pAllocator: null });
    errors();
    control(0x0206, [0, 0, 0, W, H, 1, 0, 0, res, 0, W * 4, 0], false);
    await settle(what + ": TRANSFER_FROM_HOST_3D");
    const pixels = read_bytes(BACKING, W * H * 4);
    const expected = colour.map(c => Math.round(c * 255));
    let wrong = 0;
    for(let i = 0; i < W * H; i++) if(expected.some((v, k) => Math.abs(pixels[i * 4 + k] - v) > 1)) wrong++;
    assert.equal(wrong, 0, `${what}: pixels of the clear colour ${expected}: pixel 0 is ${[...pixels.subarray(0, 4)]}`);
}
await clear_and_read(image, RES, [0.25, 0.5, 0.75, 1], "the AHB");
console.log("PASS: an AHB's image cleared on the GPU, read back through its resource");

// A swapchain image: Android's libvulkan binds it to its gralloc buffer with
// VkNativeBufferANDROID in vkBindImageMemory2's chain and no memory
const SWAPCHAIN_RES = 41;
assert.equal(command(0x0204, SWAPCHAIN_RES, 2, 67, 2 | 8, W, H, 1, 1, 0, 0, 0, 0), OK, "RESOURCE_CREATE_3D, a window's buffer");
assert.equal(command(0x0106, SWAPCHAIN_RES, 1, BACKING, 0, W * H * 4, 0), OK, "RESOURCE_ATTACH_BACKING");
a = call("vkCreateImage", { device, pAllocator: null, pImage: 0, pCreateInfo: { sType: STYPE.IMAGE_CREATE_INFO, pNext: null,
    flags: 0, imageType: 1, format: 37, extent: { width: W, height: H, depth: 1 }, mipLevels: 1, arrayLayers: 1, samples: 1, tiling: 0,
    usage: 0x2 | 0x10, sharingMode: 0, queueFamilyIndexCount: 0, pQueueFamilyIndices: null, initialLayout: 0 } });
assert.equal(a.ret, 0, "vkCreateImage");
const swapchain_image = a.pImage;
a = call("vkBindImageMemory2", { device, bindInfoCount: 1, pBindInfos: [{ sType: 1000157001, image: swapchain_image, memory: 0, memoryOffset: 0,
    pNext: { sType: 1000010000, pNext: null, handle: SWAPCHAIN_RES, stride: W, format: 1, usage: 0, usage2: { consumer: 0, producer: 0 } } }] });
assert.equal(a.ret, 0, "vkBindImageMemory2 with VkNativeBufferANDROID");
await clear_and_read(swapchain_image, SWAPCHAIN_RES, [1, 0.5, 0, 1], "the swapchain image");
console.log("PASS: a swapchain image cleared on the GPU, read back through its gralloc buffer");

// A snapshot (G6), saved and restored: the gralloc buffers' contents (the
// renderer is reset and makes them again), then the context's objects go on
// (the handles, the import, the sequence numbers)
async function read_colour(res, what)
{
    control(0x0206, [0, 0, 0, W, H, 1, 0, 0, res, 0, W * 4, 0], false);
    await settle(what + ": TRANSFER_FROM_HOST_3D");
    return [...read_bytes(BACKING, 4)];
}
const state = await emulator.save_state();
await emulator.restore_state(state);
assert.deepEqual(await read_colour(RES, "the AHB, restored"), [64, 128, 191, 255], "the AHB's texels came back");
assert.deepEqual(await read_colour(SWAPCHAIN_RES, "the swapchain buffer, restored"), [255, 128, 0, 255], "the swapchain buffer's too");
await clear_and_read(image, RES, [0, 1, 0, 1], "the AHB after the restore");
await clear_and_read(swapchain_image, SWAPCHAIN_RES, [0, 0, 1, 1], "the swapchain image after the restore");
console.log("PASS: a snapshot: gralloc buffers' contents, the context's objects go on");

emulator.destroy();
remote.close();
await wait(10);
                                                                                                                                                                                                                           source/v64/tests/devices/virtio_gpu_gfxstream_vk.js                                                 0000755 0000000 0000000 00000036026 00000000000 017767  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// gfxstream's Vulkan streams on the virtio-gpu device (docs/gfxstream-plan.md
// G2): a test that plays the guest's driver with the guest's encoder
// (tests/devices/gfxstream_guest_protocol.js) on an ASG ring: an instance,
// its physical device, a device and its queue (the host's handles), memory
// whose blob the guest maps (VkCreateBlobGOOGLE, vkGetBlobGOOGLE, then
// RESOURCE_CREATE_BLOB of the blob id), buffers made with their memory
// requirements, a command buffer flushed as one command
// (vkQueueFlushCommandsGOOGLE) and submitted without a reply
// (vkQueueSubmitAsyncGOOGLE), a fence exported (CREATE_EXPORT_SYNC_VK on a
// ring's timeline), and a second ring's command held until the one before
// it in the process's sequence, across a snapshot.

import assert from "assert/strict";
process.on("unhandledRejection", exn => { throw exn; });

const { gfxstream_machine, GUEST_COMMANDS, GfxReader, OK, OK_MAP_INFO, HOST3D, MAPPABLE, CTX } = await import("./gfxstream_guest_driver.js");
const VX = (await import("../../src/graphics_adapters/renderer_protocol.js")).VX;

// a renderer whose memories are arrays (VX: the commands this test needs;
// a snapshot's readbacks: memories', the rest answered "not done")
let to_device = null;
const vx_memory = new Map(), vx_log = [];
const respond = (id, data) => {
    const answer = new Uint8Array(16 + (data ? data.length : 0));
    const v = new DataView(answer.buffer);
    v.setUint32(0, id, true); v.setUint32(4, data ? data.length : 0, true); v.setUint32(12, data ? 1 : 0, true);
    if(data) answer.set(data, 16);
    to_device({ "type": "write", "offset": 16 * 1024, "bytes": answer });
};
const GX_SURFACE_READBACK = 4;
const renderer = {
    "post": message => {
        if(message["type"] !== "submit") return;
        const words = new Uint32Array(message["bytes"].buffer, message["bytes"].byteOffset, message["bytes"].byteLength >> 2);
        for(let at = 4; at < words[2];)
        {
            const op = words[at], n = words[at + 1], b = words.subarray(at + 2, at + 2 + n);
            const bytes = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
            at += 2 + n;
            if(message["stream"] !== "vx")
            {
                if(message["stream"] === "gx" && op === GX_SURFACE_READBACK) respond(b[9], null);
                continue;
            }
            vx_log.push(op);
            if(op === VX.MEMORY_CREATE) vx_memory.set(b[0], new Uint8Array(b[1]));
            else if(op === VX.DESTROY) vx_memory.delete(b[0]);
            else if(op === VX.MEMORY_WRITE) vx_memory.get(b[0]).set(bytes.subarray(16, 16 + b[3]), b[1]);
            else if(op === VX.COPY_BUFFER) vx_memory.get(b[3]).set(vx_memory.get(b[0]).slice(b[1], b[1] + b[6]), b[4]);
            else if(op === VX.MEMORY_READ) respond(b[4], vx_memory.get(b[0]).slice(b[1], b[1] + b[3]));
            else if(op === VX.TEXTURE_READ) respond(b[4], null);
        }
        to_device({ "type": "done", "seq": message["seq"] });
    },
    "listen": handler => { to_device = handler; },
};

const driver = await gfxstream_machine(renderer);
const { emulator, gpu, hostmem, write_bytes, command, submit_3d, used_idx, make_ring, push, ping, replies, encode, encode_cb, call } = driver;

// The context, its rings
assert.equal(command(0x0200, 0, 3), OK, "CTX_CREATE, capset 3 (gfxstream Vulkan)");
const ring1 = driver.ring = make_ring(10, 0x100000);
const vulkan = gpu.gfxstream.vulkan;
const errors = () => assert.equal(vulkan.stats.errors, 0, vulkan.stats.last_error);

// An instance and its physical device: the host's handles
const STYPE = { INSTANCE_CREATE_INFO: 1, DEVICE_QUEUE_CREATE_INFO: 2, DEVICE_CREATE_INFO: 3, SUBMIT_INFO: 4, MEMORY_ALLOCATE_INFO: 5,
    FENCE_CREATE_INFO: 8, BUFFER_CREATE_INFO: 12, COMMAND_POOL_CREATE_INFO: 39, COMMAND_BUFFER_ALLOCATE_INFO: 40, COMMAND_BUFFER_BEGIN_INFO: 42,
    PHYSICAL_DEVICE_PROPERTIES_2: 1000059001, CREATE_BLOB_GOOGLE: 1000385002 };
let a = call("vkCreateInstance", { pCreateInfo: { sType: STYPE.INSTANCE_CREATE_INFO, pNext: null, flags: 0, pApplicationInfo: null,
    enabledLayerCount: 0, ppEnabledLayerNames: [], enabledExtensionCount: 0, ppEnabledExtensionNames: [] }, pAllocator: null, pInstance: 0 });
assert.equal(a.ret, 0, "vkCreateInstance");
const instance = a.pInstance;
assert.ok(instance > 0, "the instance: the host's handle " + instance);
a = call("vkEnumeratePhysicalDevices", { instance, pPhysicalDeviceCount: 0, pPhysicalDevices: null });
assert.deepEqual([a.ret, a.pPhysicalDeviceCount], [0, 1], "one physical device");
a = call("vkEnumeratePhysicalDevices", { instance, pPhysicalDeviceCount: 1, pPhysicalDevices: [0] });
const physical = a.pPhysicalDevices[0];
assert.equal(call("vkEnumeratePhysicalDevices", { instance, pPhysicalDeviceCount: 1, pPhysicalDevices: [0] }).pPhysicalDevices[0], physical,
    "the same each time");
// the device's extensions, as the guest asks: the count, then them all
a = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: physical, pLayerName: null, pPropertyCount: 0, pProperties: null });
assert.equal(a.ret, 0);
const extension_count = a.pPropertyCount;
a = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: physical, pLayerName: null, pPropertyCount: extension_count,
    pProperties: Array.from({ length: extension_count }, () => ({})) });
assert.deepEqual([a.ret, a.pPropertyCount], [0, extension_count], "all of them: VK_SUCCESS");
assert.ok(a.pProperties.some(p => p.extensionName === "VK_KHR_external_memory_fd"), "the host's external memory (the guest offers AHBs then)");
a = call("vkGetPhysicalDeviceProperties2", { physicalDevice: physical, pProperties: { sType: STYPE.PHYSICAL_DEVICE_PROPERTIES_2, pNext: null, properties: {} } });
assert.equal(a.pProperties.properties.deviceName, "v86 WebGPU");
a = call("vkGetPhysicalDeviceMemoryProperties", { physicalDevice: physical, pMemoryProperties: {} });
const types = a.pMemoryProperties.memoryTypes.slice(0, a.pMemoryProperties.memoryTypeCount);
const HOST_VISIBLE = 2;
const host_type = types.findIndex(t => t.propertyFlags & HOST_VISIBLE), local_type = types.findIndex(t => !(t.propertyFlags & HOST_VISIBLE));
assert.ok(host_type >= 0 && local_type >= 0, "host visible and device local memory");
errors();
console.log("PASS: an instance and its physical device");

// A device and its queue
a = call("vkCreateDevice", { physicalDevice: physical, pAllocator: null, pDevice: 0,
    pCreateInfo: { sType: STYPE.DEVICE_CREATE_INFO, pNext: null, flags: 0, queueCreateInfoCount: 1,
        pQueueCreateInfos: [{ sType: STYPE.DEVICE_QUEUE_CREATE_INFO, pNext: null, flags: 0, queueFamilyIndex: 0, queueCount: 1, pQueuePriorities: Float32Array.of(1) }],
        enabledLayerCount: 0, ppEnabledLayerNames: [], enabledExtensionCount: 0, ppEnabledExtensionNames: [], pEnabledFeatures: null } });
assert.equal(a.ret, 0, "vkCreateDevice");
const device = a.pDevice;
const queue = call("vkGetDeviceQueue", { device, queueFamilyIndex: 0, queueIndex: 0, pQueue: 0 }).pQueue;
assert.equal(call("vkGetDeviceQueue", { device, queueFamilyIndex: 0, queueIndex: 0, pQueue: 0 }).pQueue, queue, "the same queue each time");
errors();
console.log("PASS: a device and its queue");

// Buffers with their requirements, memory the guest maps as a blob
const buffer_info = { sType: STYPE.BUFFER_CREATE_INFO, pNext: null, flags: 0, size: 4096, usage: 3, sharingMode: 0, queueFamilyIndexCount: 0, pQueueFamilyIndices: null };
a = call("vkCreateBufferWithRequirementsGOOGLE", { device, pCreateInfo: buffer_info, pAllocator: null, pBuffer: 0, pMemoryRequirements: {} });
assert.equal(a.ret, 0);
const src = a.pBuffer;
assert.ok(a.pMemoryRequirements.size >= 4096 && a.pMemoryRequirements.memoryTypeBits & 1 << host_type, "its requirements");
const dst = call("vkCreateBufferWithRequirementsGOOGLE", { device, pCreateInfo: buffer_info, pAllocator: null, pBuffer: 0, pMemoryRequirements: {} }).pBuffer;
const BLOB_ID = 7;
a = call("vkAllocateMemory", { device, pAllocator: null, pMemory: 0, pAllocateInfo: { sType: STYPE.MEMORY_ALLOCATE_INFO,
    pNext: { sType: STYPE.CREATE_BLOB_GOOGLE, pNext: null, blobMem: HOST3D, blobFlags: 0, blobId: BLOB_ID }, allocationSize: 4096, memoryTypeIndex: host_type } });
assert.equal(a.ret, 0, "host visible memory with a blob id");
const host_memory = a.pMemory;
const local_memory = call("vkAllocateMemory", { device, pAllocator: null, pMemory: 0,
    pAllocateInfo: { sType: STYPE.MEMORY_ALLOCATE_INFO, pNext: null, allocationSize: 4096, memoryTypeIndex: local_type } }).pMemory;
assert.equal(call("vkBindBufferMemory", { device, buffer: src, memory: host_memory, memoryOffset: 0 }).ret, 0);
assert.equal(call("vkBindBufferMemory", { device, buffer: dst, memory: local_memory, memoryOffset: 0 }).ret, 0);
assert.equal(call("vkGetBlobGOOGLE", { device, memory: host_memory }).ret, 0, "vkGetBlobGOOGLE");
const MEMORY_RES = 30, MEMORY_AT = 0x400000;
assert.equal(command(0x010C, MEMORY_RES, HOST3D, MAPPABLE, 0, BLOB_ID, 0, 4096, 0), OK, "RESOURCE_CREATE_BLOB of the blob id");
assert.equal(command(0x0208, MEMORY_RES, 0, MEMORY_AT, 0), OK_MAP_INFO, "MAP_BLOB");
const pattern = Uint8Array.from({ length: 256 }, (_, i) => i * 7 & 0xFF);
write_bytes(hostmem + MEMORY_AT, pattern);
errors();
console.log("PASS: buffers with their requirements, memory mapped as its blob");

// A command buffer, flushed as one command and submitted without a reply
const pool = call("vkCreateCommandPool", { device, pAllocator: null, pCommandPool: 0,
    pCreateInfo: { sType: STYPE.COMMAND_POOL_CREATE_INFO, pNext: null, flags: 2, queueFamilyIndex: 0 } }).pCommandPool;
a = call("vkAllocateCommandBuffers", { device, pAllocateInfo: { sType: STYPE.COMMAND_BUFFER_ALLOCATE_INFO, pNext: null, commandPool: pool, level: 0, commandBufferCount: 1 },
    pCommandBuffers: [0] });
assert.equal(a.ret, 0);
const cb = a.pCommandBuffers[0];
const recorded = [
    encode_cb("vkBeginCommandBufferAsyncGOOGLE", { pBeginInfo: { sType: STYPE.COMMAND_BUFFER_BEGIN_INFO, pNext: null, flags: 1, pInheritanceInfo: null } }),
    encode_cb("vkCmdCopyBuffer", { srcBuffer: src, dstBuffer: dst, regionCount: 1, pRegions: [{ srcOffset: 0, dstOffset: 16, size: 256 }] }),
    encode_cb("vkEndCommandBufferAsyncGOOGLE", {}),
];
const data = new Uint8Array(recorded.reduce((n, c) => n + c.length, 0));
recorded.reduce((at, c) => { data.set(c, at); return at + c.length; }, 0);
call("vkQueueFlushCommandsGOOGLE", { queue, commandBuffer: cb, dataSize: data.length, pData: data });
assert.equal(vulkan.stats.flushed, 3, "the command buffer's three commands");
const fence = call("vkCreateFence", { device, pAllocator: null, pFence: 0, pCreateInfo: { sType: STYPE.FENCE_CREATE_INFO, pNext: null, flags: 0 } }).pFence;
const batches = vx_log.length;
call("vkQueueSubmitAsyncGOOGLE", { queue, submitCount: 1, fence,
    pSubmits: [{ sType: STYPE.SUBMIT_INFO, pNext: null, waitSemaphoreCount: 0, pWaitSemaphores: null, pWaitDstStageMask: null,
        commandBufferCount: 1, pCommandBuffers: [cb], signalSemaphoreCount: 0, pSignalSemaphores: null }] });
// the fence's sync file: answered once the GPU is done
const before = used_idx();
submit_3d([0xa000, device, 0, fence, 0], false, { id: 5, ring: 1 });
for(let i = 0; i < 100 && used_idx() === before; i++) await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(used_idx(), before + 1 & 0xFFFF, "CREATE_EXPORT_SYNC_VK's fence answered");
assert.ok(vx_log.slice(batches).includes(VX.COPY_BUFFER), "the copy went to the GPU");
const copied = [...vx_memory.values()].find(m => m.length >= 272 && m[16] === pattern[0] && m[17] === pattern[1] && m[271] === pattern[255]);
assert.ok(copied, "the guest's bytes, written through the blob, copied on the GPU");
a = call("vkWaitForFences", { device, fenceCount: 1, pFences: [fence], waitAll: 1, timeout: 0 });
assert.equal(a.ret, 0, "vkWaitForFences: signaled");
// a swapchain image of a gralloc buffer: Android's libvulkan binds it with
// VkNativeBufferANDROID in vkBindImageMemory2's chain and no memory; the
// image becomes the resource's surface (VX.TEXTURE_IMPORT)
const GRALLOC_RES = 40;
assert.equal(command(0x0204, GRALLOC_RES, 2, 67, 2 | 8, 64, 64, 1, 1, 0, 0, 0, 0), OK, "RESOURCE_CREATE_3D, a gralloc buffer");
a = call("vkCreateImage", { device, pAllocator: null, pImage: 0, pCreateInfo: { sType: 14, pNext: null, flags: 0, imageType: 1, format: 37,
    extent: { width: 64, height: 64, depth: 1 }, mipLevels: 1, arrayLayers: 1, samples: 1, tiling: 0, usage: 0x10, sharingMode: 0,
    queueFamilyIndexCount: 0, pQueueFamilyIndices: null, initialLayout: 0 } });
assert.equal(a.ret, 0, "vkCreateImage");
const swapchain_image = a.pImage;
a = call("vkBindImageMemory2", { device, bindInfoCount: 1, pBindInfos: [{ sType: 1000157001, image: swapchain_image, memory: 0, memoryOffset: 0,
    pNext: { sType: 1000010000, pNext: null, handle: GRALLOC_RES, stride: 64, format: 1, usage: 0, usage2: { consumer: 0, producer: 0 } } }] });
assert.equal(a.ret, 0, "vkBindImageMemory2 with VkNativeBufferANDROID");
assert.ok([...vulkan.vk.imports.values()].some(([, resource]) => resource === GRALLOC_RES), "the swapchain image is the gralloc buffer's surface (VX.TEXTURE_IMPORT)");
errors();
console.log("PASS: a swapchain image bound to its gralloc buffer");

// vkQueueSignalReleaseImageANDROID's sync file (CREATE_QSRI_EXPORT_VK on ring
// 0): answered once the queues are idle, here at once
const before_qsri = used_idx();
submit_3d([0xa002, 0x1234, 0], false, { id: 6, ring: 0 });
for(let i = 0; i < 100 && used_idx() === before_qsri; i++) await new Promise(resolve => setTimeout(resolve, 10));
assert.equal(used_idx(), before_qsri + 1 & 0xFFFF, "CREATE_QSRI_EXPORT_VK's fence answered");
errors();
console.log("PASS: a command buffer flushed, submitted without a reply, its fence exported");

// Two rings of the process: a command holds until the one before it in sequence
const ring2 = make_ring(11, 0x200000);
const first = ++driver.seqno, second = ++driver.seqno;
push(ring2, encode("vkGetFenceStatus", { device, fence }, second));
ping(ring2);
assert.equal(replies(ring2).length, 0, "ring 2's command (number " + second + ") waits for number " + first);
// (G6: a snapshot meanwhile, restored: the command still waits on its ring,
// the process's objects and sequence go on)
const objects = gpu.gfxstream.contexts.get(CTX).decoder_state.get("vulkan").objects.size;
const state = await emulator.save_state();
await emulator.restore_state(state);
const restored = gpu.gfxstream.contexts.get(CTX);
assert.ok(restored.rings.get(ring2.res).input_length > 0, "ring 2's command kept, not decoded");
assert.equal(restored.decoder_state.get("vulkan").objects.size, objects, "the process's objects");
push(ring1, encode("vkDestroyFence", { device, fence, pAllocator: null }, first));
ping(ring1);
const r = new GfxReader(replies(ring2));
assert.equal(GUEST_COMMANDS.vkGetFenceStatus[2](r, {}).ret, 0, "then it runs: vkGetFenceStatus of a destroyed fence");
assert.equal(call("vkGetDeviceQueue", { device, queueFamilyIndex: 0, queueIndex: 0, pQueue: 0 }).pQueue, queue, "the queue's handle, as before");
errors();
console.log("PASS: two rings in the process's sequence, across a snapshot");

assert.equal(command(0x0201), OK, "CTX_DESTROY");
assert.ok(!gpu.gfxstream.contexts.has(CTX));
console.log("PASS: CTX_DESTROY");
emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/devices/virtio_gpu_hostmem.js                                                      0000755 0000000 0000000 00000030321 00000000000 016733  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu's host visible memory (level virgl43-hostmem): the shared
// memory capability and BAR4, HOST3D blobs from PIPE_RESOURCE_CREATE's
// templates, MAP_BLOB and UNMAP_BLOB, and coherency -- what the guest writes
// through a mapping reaches the blob before the GPU runs the next SUBMIT_3D,
// and what the GPU writes into a mapped blob is in the mapping before the
// submit's fence completes -- and snapshots of mappings. GX is a fake here:
// it keeps the buffers' bytes and answers readbacks from them. Mesa's virgl
// on it is tested by tests/x64/linux_gpu.mjs (gltest's buffer-storage cases).

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// GX opcodes and the readback answer's layout (src/graphics_adapters/renderer_protocol.js)
const GX_SURFACE_DEFINE = 1, GX_SURFACE_UPLOAD = 3, GX_SURFACE_READBACK = 4;
const QUERY_REGION_BYTES = 16 * 1024, READBACK_HEADER_BYTES = 16, RESPONSE_OK = 1;

/** A GX that keeps each buffer's bytes, and answers at once */
function fake_gx()
{
    let to_device = null;
    const buffers = new Map();
    const log = [];
    const renderer = {
        "post": message => {
            if(message["type"] === "reset") { buffers.clear(); return; }
            if(message["type"] !== "submit") return;
            const words = new Uint32Array(message["bytes"].buffer, message["bytes"].byteOffset, message["bytes"].byteLength >> 2);
            const answers = [];
            for(let at = 4; at < words[2];)
            {
                const op = words[at], body = words[at + 1], p = words.subarray(at + 2, at + 2 + body);
                if(op === GX_SURFACE_DEFINE)
                {
                    buffers.set(p[0], new Uint8Array(p[4]));
                    log.push(["define", p[0], p[4]]);
                }
                else if(op === GX_SURFACE_UPLOAD)
                {
                    const [sid, , , x, , , w] = p;
                    const bytes = new Uint8Array(p.buffer, p.byteOffset + 11 * 4, w);
                    buffers.get(sid).set(bytes, x);
                    log.push(["upload", sid, x, w, Array.from(bytes)]);
                }
                else if(op === GX_SURFACE_READBACK)
                {
                    const [sid, , , x, , , w, , , id] = p;
                    const answer = new Uint8Array(READBACK_HEADER_BYTES + w);
                    const v = new DataView(answer.buffer);
                    v.setUint32(0, id, true);
                    v.setUint32(4, w, true);
                    v.setUint32(12, RESPONSE_OK, true);
                    answer.set(buffers.get(sid).subarray(x, x + w), READBACK_HEADER_BYTES);
                    answers.push({ "type": "write", "offset": QUERY_REGION_BYTES, "bytes": answer });
                    log.push(["readback", sid, x, w]);
                }
                at += 2 + body;
            }
            for(const answer of answers) to_device(answer);
            to_device({ "type": "done", "seq": message["seq"] });
        },
        "listen": handler => { to_device = handler; },
    };
    return { renderer, buffers, log };
}
const gx = fake_gx();

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const emulator = new V86({
    graphics_adapter: "virtio_gpu",
    graphics_adapter_test: { level: "virgl43-hostmem", renderer: gx.renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 64 << 20,
    vram_size: 16 << 20,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;

// BAR4: 64 MiB of prefetchable memory, which SeaBIOS placed
const HOSTMEM = 64 << 20;
const bar4 = pci_read(0x20);
assert.equal(bar4 & 0xF, 8, "BAR4: 32-bit prefetchable memory");
const hostmem = (bar4 & ~0xF) >>> 0;
assert.ok(hostmem >= 0xE0000000 && hostmem % HOSTMEM === 0, "placed in the PCI memory window: " + hostmem.toString(16));

// The shared memory capability: struct virtio_pci_cap64, region 1 (host visible), all of BAR4
let shm = null, common = 0, notify = 0;
const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
{
    if(pci_read8(at) !== 0x09) continue;
    const type = pci_read8(at + 3);
    if(type === 8) shm = { len: pci_read8(at + 2), bar: pci_read8(at + 4), id: pci_read8(at + 5), offset: pci_read(at + 8),
        length: pci_read(at + 12), offset_hi: pci_read(at + 16), length_hi: pci_read(at + 20) };
    if(type === 1) common = bar2 + pci_read(at + 8);
    if(type === 2) notify = bar2 + pci_read(at + 8);
}
assert.deepEqual(shm, { len: 24, bar: 4, id: 1, offset: 0, length: HOSTMEM, offset_hi: 0, length_hi: 0 });
console.log("PASS: BAR4 at " + hostmem.toString(16) + " and the shared memory capability");

// The transport
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
const read_bytes = (address, length) => Array.from({ length }, (_, i) => cpu.read8(address + i));
const w8 = (offset, value) => cpu.write8(common + offset, value);
const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
    { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];

w8(20, 0);
w8(20, 3);
write32(common, 0);
const features0 = read32(common + 4);
assert.equal(features0 & 0x19, 0x19, "VIRGL, RESOURCE_BLOB, CONTEXT_INIT");
write32(common + 8, 0); write32(common + 12, features0);
write32(common + 8, 1); write32(common + 12, 1);
w8(20, 11);
QUEUES.forEach((q, i) => {
    w16(22, i);
    q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
    write32(common + 32, q.desc); write32(common + 36, 0);
    write32(common + 40, q.avail); write32(common + 44, 0);
    write32(common + 48, q.used); write32(common + 52, 0);
    for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
    w16(28, 1);
});
w8(20, 15);

const REQUEST = 0x200000, REPLY = 0x280000;
function submit(bytes)
{
    const q = QUEUES[0];
    write_bytes(REQUEST, bytes);
    write32(q.desc, REQUEST); write32(q.desc + 4, 0); write32(q.desc + 8, bytes.length);
    cpu.write8(q.desc + 12, 1); cpu.write8(q.desc + 14, 1);
    for(let i = 0; i < 64; i += 4) write32(REPLY + i, 0xDEADBEEF);
    write32(q.desc + 16, REPLY); write32(q.desc + 20, 0); write32(q.desc + 24, 64);
    cpu.write8(q.desc + 28, 2);
    write32(q.avail + 4 + (q.avail_idx % q.size) * 2, 0);
    q.avail_idx = q.avail_idx + 1 & 0xFFFF;
    cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
    cpu.write8(q.avail + 3, q.avail_idx >> 8);
    const before = read32(q.used) >>> 16;
    cpu.write8(notify, 0);
    cpu.write8(notify + 1, 0);
    assert.equal(read32(q.used) >>> 16, before + 1 & 0xFFFF, "completed at once (the fake GX answers at once)");
    return read32(REPLY);
}
const CTX = 1;
const command = (type, ...values) => {
    const out = new Uint32Array(6 + values.length);
    out[0] = type;
    out[4] = CTX;
    out.set(values, 6);
    return submit(new Uint8Array(out.buffer));
};
const OK = 0x1100, OK_MAP_INFO = 0x1106, ERR_INVALID_PARAMETER = 0x1205, ERR_INVALID_RESOURCE_ID = 0x1203;
/** SUBMIT_3D of virgl commands */
const submit_3d = (...words) => command(0x0207, words.length * 4, 0, ...words);

assert.equal(command(0x0200, 0, 0), OK, "CTX_CREATE");
assert.equal(submit_3d(), OK, "an empty SUBMIT_3D");

// PIPE_RESOURCE_CREATE (48): a buffer of 3 pages, blob id 7; then the blob
const RES = 5, SIZE = 3 * 4096, BLOB_ID = 7, MAPPABLE = 1;
assert.equal(submit_3d(48 | 11 << 16, 0, 64, 1 << 4, SIZE, 1, 1, 1, 0, 0, 0, BLOB_ID), OK);
assert.equal(command(0x010C, RES, 2, MAPPABLE, 0, BLOB_ID, 0, SIZE, 0), OK, "RESOURCE_CREATE_BLOB, HOST3D");
assert.equal(submit_3d(), OK);
assert.ok(gx.log.some(e => e[0] === "define" && e[1] === RES && e[2] === SIZE), "a GX buffer of the template's size");
assert.equal(command(0x010C, RES + 1, 2, MAPPABLE, 0, BLOB_ID, 0, SIZE, 0), ERR_INVALID_PARAMETER,
    "a template makes one blob");

// MAP_BLOB: OK_MAP_INFO, cached
const OFFSET = 16 * 4096, base = hostmem + OFFSET;
assert.equal(command(0x0208, RES, 0, OFFSET, 0), OK_MAP_INFO, "MAP_BLOB");
assert.equal(read32(REPLY + 24), 1, "VIRTIO_GPU_MAP_CACHE_CACHED");
assert.equal(command(0x0208, RES, 0, OFFSET, 0), ERR_INVALID_PARAMETER, "mapped once");
assert.equal(command(0x0208, 99, 0, 0, 0), ERR_INVALID_RESOURCE_ID);
assert.deepEqual(read_bytes(base, 8), [0, 0, 0, 0, 0, 0, 0, 0], "a new mapping reads as zeros");
console.log("PASS: PIPE_RESOURCE_CREATE, HOST3D blob, MAP_BLOB");

// The guest writes pages 0 and 2 through the mapping: SUBMIT_3D uploads them first
gx.log.length = 0;
write_bytes(base + 100, [1, 2, 3, 4]);
write_bytes(base + 2 * 4096 + 5, [9, 8]);
assert.equal(submit_3d(), OK);
const uploads = gx.log.filter(e => e[0] === "upload");
assert.deepEqual(uploads.map(e => e.slice(1, 4)), [[RES, 0, 4096], [RES, 8192, 4096]], "the two written pages, nothing else");
assert.deepEqual(gx.buffers.get(RES).subarray(100, 104), Uint8Array.from([1, 2, 3, 4]));
assert.deepEqual(gx.buffers.get(RES).subarray(8197, 8199), Uint8Array.from([9, 8]));
gx.log.length = 0;
assert.equal(submit_3d(), OK);
assert.equal(gx.log.filter(e => e[0] === "upload").length, 0, "no page written since: no upload");
console.log("PASS: the guest's writes reach the blob before the GPU work");

// The GPU writes it (RESOURCE_INLINE_WRITE, 9: res, level, usage, stride,
// layer stride, x, y, z, w, h, d, data): it is read back into the mapping
// before the submit completes
gx.log.length = 0;
assert.equal(submit_3d(9 | 13 << 16, RES, 0, 0, 0, 0, 4096 + 16, 0, 0, 8, 1, 1, 0x44332211, 0x88776655), OK);
assert.ok(gx.log.some(e => e[0] === "readback" && e[1] === RES), "read back");
assert.deepEqual(read_bytes(base + 4096 + 16, 8), [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88], "the GPU's bytes, in the mapping");
assert.deepEqual(read_bytes(base + 100, 4), [1, 2, 3, 4], "and the guest's are still there");
console.log("PASS: the GPU's writes reach the mapping before the fence");

// A snapshot: the mapping and the blob come back
const state = await emulator.save_state();
write_bytes(base + 100, [0, 0, 0, 0]);
await emulator.restore_state(state);
assert.deepEqual(read_bytes(base + 100, 4), [1, 2, 3, 4], "the mapping's bytes");
assert.deepEqual(read_bytes(base + 4096 + 16, 4), [0x11, 0x22, 0x33, 0x44]);
assert.deepEqual(gx.buffers.get(RES).subarray(4096 + 16, 4096 + 20), Uint8Array.from([0x11, 0x22, 0x33, 0x44]), "the blob, in GX again");
gx.log.length = 0;
write_bytes(base + 2 * 4096, [7]);
assert.equal(submit_3d(), OK);
assert.deepEqual(gx.log.filter(e => e[0] === "upload").map(e => e.slice(1, 4)), [[RES, 8192, 4096]], "still mapped after the restore");
console.log("PASS: snapshots keep mappings");

// UNMAP_BLOB, then the pages are of no blob; UNREF
assert.equal(command(0x0209, RES, 0), OK, "UNMAP_BLOB");
assert.equal(command(0x0209, RES, 0), ERR_INVALID_RESOURCE_ID, "unmapped once");
gx.log.length = 0;
write_bytes(base, [5]);
assert.equal(submit_3d(), OK);
assert.equal(gx.log.filter(e => e[0] === "upload").length, 0, "nothing uploaded for an unmapped blob");
assert.equal(command(0x0102, RES, 0), OK, "RESOURCE_UNREF");
console.log("PASS: UNMAP_BLOB");

emulator.destroy();
                                                                                                                                                                                                                                                                                                               source/v64/tests/devices/virtio_gpu_present.js                                                      0000755 0000000 0000000 00000024125 00000000000 016744  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu's scanouts shown without readbacks (docs/gfxstream-plan.md G4):
// a renderer that says it can (its "caps" to the device's "hello": the page's
// compositor) gets GX's SURFACE_PRESENT for a 3D scanout's flushes, the
// rectangle flushed, and no readback; a cursor over the picture, a second
// scanout or a renderer that cannot bring the readbacks back (and the
// renderer's picture goes, SURFACE_PRESENT of sid 0); so does SET_SCANOUT 0.
// GX is a fake here: it logs the batches' commands and answers readbacks
// with zeros. The renderer's side (the copy into the compositor's layer) is
// tests/glbridge/virtio_gpu_present_browser_test.html.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { GX } = await import("../../src/graphics_adapters/renderer_protocol.js");
const QUERY_REGION_BYTES = 16 * 1024, READBACK_HEADER_BYTES = 16, RESPONSE_OK = 1;

let to_device = null, present = true;
const log = [];
const renderer = {
    "post": message => {
        if(message["type"] === "hello" || message["type"] === "reset")
        {
            // (as svga_renderer.js does: after the device's listener is up)
            globalThis.queueMicrotask(() => to_device({ "type": "caps", "present": present }));
            return;
        }
        if(message["type"] !== "submit") return;
        const words = new Uint32Array(message["bytes"].buffer, message["bytes"].byteOffset, message["bytes"].byteLength >> 2);
        for(let at = 4; at < words[2];)
        {
            const op = words[at], body = words[at + 1], p = words.subarray(at + 2, at + 2 + body);
            if(op === GX.SURFACE_PRESENT) log.push(["present", ...p]);
            if(op === GX.SURFACE_READBACK)
            {
                const [sid, , , , , , w, h, , id] = p;
                log.push(["readback", sid]);
                const answer = new Uint8Array(READBACK_HEADER_BYTES + w * h * 4);
                const v = new DataView(answer.buffer);
                v.setUint32(0, id, true);
                v.setUint32(4, w * h * 4, true);
                v.setUint32(12, RESPONSE_OK, true);
                to_device({ "type": "write", "offset": QUERY_REGION_BYTES, "bytes": answer });
            }
            at += 2 + body;
        }
        to_device({ "type": "done", "seq": message["seq"] });
    },
    "listen": handler => { to_device = handler; },
};

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const emulator = new V86({
    graphics_adapter: "virtio_gpu",
    graphics_adapter_test: { level: "virgl43", renderer, scanouts: 2 },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 64 << 20,
    vram_size: 16 << 20,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
assert.equal(gpu.virgl.direct_present, true, "the renderer's caps: it shows pictures");
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;
let common = 0, notify = 0;
const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
{
    if(pci_read8(at) !== 0x09) continue;
    const type = pci_read8(at + 3);
    if(type === 1) common = bar2 + pci_read(at + 8);
    if(type === 2) notify = bar2 + pci_read(at + 8);
}

// The transport
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
const w8 = (offset, value) => cpu.write8(common + offset, value);
const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
    { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];
w8(20, 0);
w8(20, 3);
write32(common, 0);
const features0 = read32(common + 4);
write32(common + 8, 0); write32(common + 12, features0);
write32(common + 8, 1); write32(common + 12, 1);
w8(20, 11);
QUEUES.forEach((q, i) => {
    w16(22, i);
    q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
    write32(common + 32, q.desc); write32(common + 36, 0);
    write32(common + 40, q.avail); write32(common + 44, 0);
    write32(common + 48, q.used); write32(common + 52, 0);
    for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
    w16(28, 1);
});
w8(20, 15);

const REQUEST = 0x200000, REPLY = 0x280000;
function submit(bytes)
{
    const q = QUEUES[0];
    write_bytes(REQUEST, bytes);
    write32(q.desc, REQUEST); write32(q.desc + 4, 0); write32(q.desc + 8, bytes.length);
    cpu.write8(q.desc + 12, 1); cpu.write8(q.desc + 14, 1);
    write32(q.desc + 16, REPLY); write32(q.desc + 20, 0); write32(q.desc + 24, 64);
    cpu.write8(q.desc + 28, 2);
    write32(q.avail + 4 + (q.avail_idx % q.size) * 2, 0);
    q.avail_idx = q.avail_idx + 1 & 0xFFFF;
    cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
    cpu.write8(q.avail + 3, q.avail_idx >> 8);
    cpu.write8(notify, 0);
    cpu.write8(notify + 1, 0);
    return read32(REPLY);
}
const command = (type, ...values) => {
    const out = new Uint32Array(6 + values.length);
    out[0] = type;
    out.set(values, 6);
    return submit(new Uint8Array(out.buffer));
};
const OK = 0x1100;
const RESOURCE_CREATE_3D = 0x0204, SET_SCANOUT = 0x0103, RESOURCE_FLUSH = 0x0104;
// (PIPE_TEXTURE_2D, VIRGL_FORMAT_B8G8R8A8_UNORM, PIPE_BIND_RENDER_TARGET | SCANOUT)
const create = (id, width, height) => command(RESOURCE_CREATE_3D, id, 2, 1, 0x2 | 0x40000, width, height, 1, 1, 0, 0, 0, 0);
const W = 64, H = 48;

assert.equal(create(1, W, H), OK, "RESOURCE_CREATE_3D");
log.length = 0;
assert.equal(command(SET_SCANOUT, 0, 0, W, H, 0, 1), OK, "SET_SCANOUT of the 3D resource");
assert.deepEqual(log, [["present", 1, 0, 0, W, H, 0, 0, W, H]], "shown by the renderer, all of it, no readback");
log.length = 0;
assert.equal(command(RESOURCE_FLUSH, 8, 4, 16, 8, 1, 0), OK);
assert.deepEqual(log, [["present", 1, 8, 4, 16, 8, 8, 4, W, H]], "a flush: its rectangle");
assert.equal(gpu.scanouts[0].direct, 1);
console.log("PASS: a 3D scanout's flushes shown by the renderer, without readbacks");

// The screen takes the scanout's size at the next retrace, with no frame
// asked for: a page in text mode asks for none (an ARM machine's, no VGA),
// and the renderer's picture goes over a screen of the scanout's size
const sizes = [];
emulator.add_listener("screen-set-size", size => sizes.push(size));
gpu.on_vblank();
assert.deepEqual(sizes.at(-1), [W, H, 32], "the screen at the scanout's size: " + JSON.stringify(sizes));
console.log("PASS: the screen at the scanout's size at the next retrace, no frame asked for");

// a cursor over the picture: the device's picture again (read back), the renderer's goes
log.length = 0;
gpu.cursor.visible = true;
gpu.cursor_shown();
assert.deepEqual(log[0], ["present", 0, 0, 0, 0, 0, 0, 0, 0, 0], "the renderer's picture goes");
assert.ok(log.slice(1).length && log.slice(1).every(e => e[0] === "readback" && e[1] === 1), "the scanout read back: " + JSON.stringify(log));
assert.equal(gpu.scanouts[0].direct, 0);
log.length = 0;
assert.equal(command(RESOURCE_FLUSH, 0, 0, W, H, 1, 0), OK);
assert.ok(log.length && log.every(e => e[0] === "readback"), "with the cursor shown: readbacks");
gpu.cursor.visible = false;
log.length = 0;
assert.equal(command(RESOURCE_FLUSH, 0, 0, 8, 8, 1, 0), OK);
assert.deepEqual(log, [["present", 1, 0, 0, 8, 8, 0, 0, W, H]], "the cursor hidden: shown by the renderer again");
console.log("PASS: a cursor over it: read back");

// a second scanout: the device composes the two
assert.equal(create(2, W, H), OK);
log.length = 0;
assert.equal(command(SET_SCANOUT, 0, 0, W, H, 1, 2), OK, "SET_SCANOUT of the second display");
assert.ok(log.every(e => e[0] === "readback"), "the second scanout read back: " + JSON.stringify(log));
log.length = 0;
assert.equal(command(RESOURCE_FLUSH, 0, 0, W, H, 1, 0), OK);
assert.deepEqual(log[0], ["present", 0, 0, 0, 0, 0, 0, 0, 0, 0], "two scanouts: the renderer's picture goes");
assert.ok(log.slice(1).every(e => e[0] === "readback"));
assert.equal(command(SET_SCANOUT, 0, 0, 0, 0, 1, 0), OK, "the second display off");
log.length = 0;
assert.equal(command(RESOURCE_FLUSH, 0, 0, W, H, 1, 0), OK);
assert.deepEqual(log, [["present", 1, 0, 0, W, H, 0, 0, W, H]], "one scanout again: shown by the renderer");
console.log("PASS: two scanouts: read back");

// SET_SCANOUT 0: the renderer's picture goes
log.length = 0;
assert.equal(command(SET_SCANOUT, 0, 0, 0, 0, 0, 0), OK);
assert.deepEqual(log, [["present", 0, 0, 0, 0, 0, 0, 0, 0, 0]], "the scanout off");
console.log("PASS: SET_SCANOUT 0");

// a renderer that cannot (no compositor: node's, a headless one): readbacks as before
present = false;
gpu.virgl.reset();
await new Promise(resolve => setTimeout(resolve, 0));
assert.equal(gpu.virgl.direct_present, false);
assert.equal(create(3, W, H), OK);
log.length = 0;
assert.equal(command(SET_SCANOUT, 0, 0, W, H, 0, 3), OK);
assert.ok(log.length && log.every(e => e[0] === "readback"), "read back: " + JSON.stringify(log));
console.log("PASS: a renderer without a compositor: readbacks");

emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/devices/virtio_gpu_venus.js                                                        0000755 0000000 0000000 00000133246 00000000000 016431  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// virtio-gpu's Venus transport (level venus, src/graphics_adapters/virtio_gpu/
// venus.js), driven as Mesa's venus driver drives it: the capset, a context
// of capset 4, shared memory (HOST3D blobs of blob id 0) mapped into BAR4, a
// ring in it (vkCreateRingMESA), commands through the ring with their
// replies in a reply stream, the ring's head, ALIVE and FATAL status bits,
// indirect streams (vkExecuteCommandStreamsMESA), the seqno waits of
// SUBMIT_3D and of rings, and the instance and physical device queries that
// vulkaninfo makes. tests/devices/venus_guest_protocol.js (generated with
// the device's protocol, from Mesa's) encodes requests and decodes replies.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { GUEST, VenusReader, VenusWriter } = await import("./venus_guest_protocol.js");

// A renderer that keeps VX memory as bytes and runs its copies, fills,
// updates and reads; it answers at once (images and draws are not its)
const VX = (await import("../../src/graphics_adapters/renderer_protocol.js")).VX;
let to_device = null;
const vx_memory = new Map(), vx_log = [];
/** while held, batches wait for flush_renderer() (the GPU is slow) */
let held = null;
const flush_renderer = () => { const messages = held; held = null; for(const m of messages) renderer.post(m); };
const renderer = {
    "post": message => {
        if(message["type"] !== "submit") return;
        if(held) { held.push(message); return; }
        if(message["stream"] === "vx")
        {
            const words = new Uint32Array(message["bytes"].buffer, message["bytes"].byteOffset, message["bytes"].byteLength >> 2);
            for(let at = 4; at < words[2];)
            {
                const op = words[at], n = words[at + 1], b = words.subarray(at + 2, at + 2 + n);
                const bytes = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
                at += 2 + n;
                vx_log.push(op);
                if(op === VX.MEMORY_CREATE) vx_memory.set(b[0], new Uint8Array(b[1]));
                else if(op === VX.DESTROY) vx_memory.delete(b[0]);
                else if(op === VX.MEMORY_WRITE) vx_memory.get(b[0]).set(bytes.subarray(16, 16 + b[3]), b[1]);
                else if(op === VX.COPY_BUFFER) vx_memory.get(b[3]).set(vx_memory.get(b[0]).slice(b[1], b[1] + b[6]), b[4]);
                else if(op === VX.FILL_BUFFER) new DataView(vx_memory.get(b[0]).buffer).setUint32(b[1], b[5], true);
                else if(op === VX.MEMORY_READ)
                {
                    const data = vx_memory.get(b[0]).slice(b[1], b[1] + b[3]);
                    const answer = new Uint8Array(16 + data.length);
                    const v = new DataView(answer.buffer);
                    v.setUint32(0, b[4], true); v.setUint32(4, data.length, true); v.setUint32(12, 1, true);
                    answer.set(data, 16);
                    to_device({ "type": "write", "offset": 16 * 1024, "bytes": answer });
                }
            }
        }
        to_device({ "type": "done", "seq": message["seq"] });
    },
    "listen": handler => { to_device = handler; },
};

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const emulator = new V86({
    graphics_adapter: "virtio_gpu",
    graphics_adapter_test: { level: "venus", renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 64 << 20,
    vram_size: 16 << 20,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;

// BAR4: 128 MiB at level venus
const HOSTMEM = 128 << 20;
const hostmem = (pci_read(0x20) & ~0xF) >>> 0;
assert.ok(hostmem && hostmem % HOSTMEM === 0, "BAR4 placed: " + hostmem.toString(16));

let common = 0, notify = 0;
const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
{
    if(pci_read8(at) !== 0x09) continue;
    const type = pci_read8(at + 3);
    if(type === 1) common = bar2 + pci_read(at + 8);
    if(type === 2) notify = bar2 + pci_read(at + 8);
}

// The transport
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const write_bytes = (address, bytes) => bytes.forEach((b, i) => cpu.write8(address + i, b));
const read_bytes = (address, length) => Uint8Array.from({ length }, (_, i) => cpu.read8(address + i));
const w8 = (offset, value) => cpu.write8(common + offset, value);
const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
    { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];

w8(20, 0);
w8(20, 3);
write32(common, 0);
const features0 = read32(common + 4);
assert.equal(features0 & 0x19, 0x19, "VIRGL, RESOURCE_BLOB, CONTEXT_INIT");
write32(common + 8, 0); write32(common + 12, features0);
write32(common + 8, 1); write32(common + 12, 1);
w8(20, 11);
QUEUES.forEach((q, i) => {
    w16(22, i);
    q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
    write32(common + 32, q.desc); write32(common + 36, 0);
    write32(common + 40, q.avail); write32(common + 44, 0);
    write32(common + 48, q.used); write32(common + 52, 0);
    for(let j = 0; j < 0x3000; j += 4) write32(q.desc + j, 0);
    w16(28, 1);
});
w8(20, 15);

// One request at a time, each in its own slot; `done(slot)` says whether it was answered
const REQUEST = 0x200000, REPLY = 0x280000, SLOT = 0x1000;
let next_slot = 0;
function send(bytes, wait = true)
{
    const q = QUEUES[0];
    const slot = next_slot++ % 16;
    const head = slot * 2;
    write_bytes(REQUEST + slot * SLOT, bytes);
    for(let i = 0; i < 256; i += 4) write32(REPLY + slot * SLOT + i, 0xDEADBEEF);
    write32(q.desc + head * 16, REQUEST + slot * SLOT); write32(q.desc + head * 16 + 4, 0);
    write32(q.desc + head * 16 + 8, bytes.length);
    cpu.write8(q.desc + head * 16 + 12, 1); cpu.write8(q.desc + head * 16 + 14, head + 1);
    write32(q.desc + (head + 1) * 16, REPLY + slot * SLOT); write32(q.desc + (head + 1) * 16 + 4, 0);
    write32(q.desc + (head + 1) * 16 + 8, 256);
    cpu.write8(q.desc + (head + 1) * 16 + 12, 2);
    write32(q.avail + 4 + (q.avail_idx % q.size) * 2, head);
    q.avail_idx = q.avail_idx + 1 & 0xFFFF;
    cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
    cpu.write8(q.avail + 3, q.avail_idx >> 8);
    const before = read32(q.used) >>> 16;
    cpu.write8(notify, 0);
    cpu.write8(notify + 1, 0);
    if(wait) assert.equal(read32(q.used) >>> 16, before + 1 & 0xFFFF, "answered at once");
    return slot;
}
const answer = slot => read32(REPLY + slot * SLOT);
const CTX = 1;
const control = (type, values, wait) => {
    const out = new Uint32Array(6 + values.length);
    out[0] = type;
    out[4] = CTX;
    out.set(values, 6);
    return send(new Uint8Array(out.buffer), wait);
};
const command = (type, ...values) => answer(control(type, values));
const OK = 0x1100, OK_CAPSET_INFO = 0x1102, OK_CAPSET = 0x1103, OK_MAP_INFO = 0x1106, ERR_INVALID_PARAMETER = 0x1205;

// ---------------------------------------------------------------------------
// The capset

let slot = control(0x0108, [2, 0]);
assert.equal(answer(slot), OK_CAPSET_INFO, "GET_CAPSET_INFO 2");
assert.deepEqual([read32(REPLY + slot * SLOT + 24), read32(REPLY + slot * SLOT + 28), read32(REPLY + slot * SLOT + 32)],
    [4, 0, 160], "capset 4 (Venus), version 0, 160 bytes");
slot = control(0x0109, [4, 0]);
assert.equal(answer(slot), OK_CAPSET, "GET_CAPSET 4");
const capset = Array.from({ length: 40 }, (_, i) => read32(REPLY + slot * SLOT + 24 + i * 4));
assert.equal(capset[0], 1, "wire format 1");
assert.equal(capset[1], (1 << 22 | 4 << 12 | 343) >>> 0, "vk.xml 1.4.343, Mesa 26.1.6's protocol");
assert.equal(capset[4], 1, "supports_blob_id_0");
assert.equal(capset[5] & 1, 0, "the extension mask's bit 0 clear: every extension of the protocol");
assert.deepEqual(capset.slice(37), [1, 1, 0], "allow_vk_wait_syncs, supports_multiple_timelines, not use_guest_vram");
console.log("PASS: the Venus capset");

// A context of capset 4 (CONTEXT_INIT)
assert.equal(command(0x0200, 0, 4), OK, "CTX_CREATE, capset 4");
assert.ok(gpu.venus.contexts.has(CTX));

// Shared memory: the ring's and the replies'
const RING_RES = 10, REPLY_RES = 11, STREAM_RES = 12;
const RING_SIZE = 0x21000, RING_AT = 0x100000, REPLY_AT = 0x200000, STREAM_AT = 0x300000;
const HOST3D = 2, MAPPABLE = 1;
const blob = (res, size, at) => {
    assert.equal(command(0x010C, res, HOST3D, MAPPABLE, 0, 0, 0, size, 0), OK, "RESOURCE_CREATE_BLOB, blob id 0");
    assert.equal(command(0x0208, res, 0, at, 0), OK_MAP_INFO, "MAP_BLOB");
};
blob(RING_RES, RING_SIZE, RING_AT);
blob(REPLY_RES, 0x10000, REPLY_AT);
blob(STREAM_RES, 0x10000, STREAM_AT);
assert.equal(command(0x010C, 13, HOST3D, MAPPABLE, 0, 0x1234, 0, 4096, 0), ERR_INVALID_PARAMETER, "blob id of no memory");

/** Encode commands */
const encode = (...commands) => {
    const w = new VenusWriter(64);
    for(const [name, a] of commands) GUEST[name][0](w, a);
    return w.result();
};
/** SUBMIT_3D of Venus commands */
const submit_3d = (bytes, wait) => {
    const words = new Uint32Array(Math.ceil(bytes.length / 4));
    new Uint8Array(words.buffer).set(bytes);
    return control(0x0207, [bytes.length, 0, ...words], wait);
};

// The ring (Mesa's layout: head, tail, status 64 bytes apart, then the buffer)
const RING_ID = 0x7f0012345678, HEAD = 0, TAIL = 64, STATUS = 128, BUFFER = 192, BUFFER_SIZE = 0x20000, EXTRA = BUFFER + BUFFER_SIZE;
const ring_base = hostmem + RING_AT;
assert.equal(answer(submit_3d(encode(["vkCreateRingMESA", { ring: RING_ID, pCreateInfo: {
    sType: 1000384000, pNext: { sType: 1000384006, maxReportingPeriodMicroseconds: 3000000 },
    resourceId: RING_RES, offset: 0, size: RING_SIZE, idleTimeout: 1000000,
    headOffset: HEAD, tailOffset: TAIL, statusOffset: STATUS, bufferOffset: BUFFER, bufferSize: BUFFER_SIZE,
    extraOffset: EXTRA, extraSize: 64 } }]))), OK, "vkCreateRingMESA");
assert.equal(read32(ring_base + STATUS) & 4, 4, "ALIVE");

let tail = 0;
/** Commands into the ring; the device reads them when the machine's timers run */
const ring_write = (bytes, run = true) => {
    for(let i = 0; i < bytes.length; i++) cpu.write8(ring_base + BUFFER + (tail + i & BUFFER_SIZE - 1), bytes[i]);
    tail = tail + bytes.length >>> 0;
    write32(ring_base + TAIL, tail);
    if(run) cpu.devices.display.timer(cpu.clock.now());
};
let reply_position = 0;
/** A command with a reply, as the driver sends it: the reply stream first */
const call = (name, a) => {
    const at = reply_position;
    ring_write(encode(["vkSetReplyCommandStreamMESA", { pStream: { resourceId: REPLY_RES, offset: at, size: 0x1000 } }],
        [name, { cmd_flags: 1, ...a }]));
    assert.equal(read32(ring_base + HEAD), tail, name + ": the head is at the tail");
    reply_position = (reply_position + 0x1000) % 0x10000;
    const bytes = read_bytes(hostmem + REPLY_AT + at, 0x1000);
    const reply = GUEST[name][1](new VenusReader(bytes));
    return reply;
};

let reply = call("vkEnumerateInstanceVersion", { pApiVersion: 0 });
assert.equal(reply.ret, 0);
assert.equal(reply.pApiVersion >>> 12, 1 << 10 | 1, "Vulkan 1.1");
console.log("PASS: a ring, a command and its reply");

// ---------------------------------------------------------------------------
// What vulkaninfo and the driver ask

const INSTANCE = 0x1000, PHYSICAL_DEVICE = 0x2000;
reply = call("vkCreateInstance", { pCreateInfo: { sType: 1, pApplicationInfo: { sType: 0, pApplicationName: "venus test",
    apiVersion: 1 << 22 | 1 << 12 }, enabledExtensionCount: 0 }, pInstance: INSTANCE });
assert.equal(reply.ret, 0, "vkCreateInstance");

reply = call("vkEnumeratePhysicalDevices", { instance: INSTANCE, pPhysicalDeviceCount: 0, pPhysicalDevices: null });
assert.deepEqual([reply.ret, reply.pPhysicalDeviceCount], [0, 1], "one physical device");
reply = call("vkEnumeratePhysicalDevices", { instance: INSTANCE, pPhysicalDeviceCount: 1, pPhysicalDevices: [PHYSICAL_DEVICE] });
assert.deepEqual([reply.ret, reply.pPhysicalDeviceCount, reply.pPhysicalDevices], [0, 1, [PHYSICAL_DEVICE]]);

reply = call("vkEnumeratePhysicalDeviceGroups", { instance: INSTANCE, pPhysicalDeviceGroupCount: 1,
    pPhysicalDeviceGroupProperties: [{ sType: 1000070000, physicalDevices: new Array(32).fill(0) }] });
assert.equal(reply.pPhysicalDeviceGroupProperties[0].physicalDeviceCount, 1);
assert.equal(reply.pPhysicalDeviceGroupProperties[0].physicalDevices[0], PHYSICAL_DEVICE, "the group names the driver's id");

reply = call("vkGetPhysicalDeviceProperties", { physicalDevice: PHYSICAL_DEVICE, pProperties: {} });
assert.equal(reply.pProperties.deviceName, "v86 WebGPU");
assert.equal(reply.pProperties.limits.maxImageDimension2D, 8192);
assert.equal(reply.pProperties.limits.maxBoundDescriptorSets, 4);

// (the driver's chains, for a renderer of Vulkan 1.1)
const props2 = { sType: 1000059001, pNext: { sType: 1000071004, pNext: { sType: 1000168000, pNext: { sType: 1000094000,
    pNext: { sType: 1000196000 } } } } };
reply = call("vkGetPhysicalDeviceProperties2", { physicalDevice: PHYSICAL_DEVICE, pProperties: props2 });
const chain = s => { const out = {}; for(; s; s = s.pNext) out[s.sType] = s; return out; };
const got = chain(reply.pProperties.pNext);
assert.equal(got[1000094000].subgroupSize, 1, "VkPhysicalDeviceSubgroupProperties");
assert.equal(got[1000168000].maxMemoryAllocationSize, 1 << 30, "VkPhysicalDeviceMaintenance3Properties");
assert.equal(got[1000196000].driverName, "v86 WebGPU", "VkPhysicalDeviceDriverProperties");
assert.equal(reply.pProperties.properties.apiVersion >>> 12, 1 << 10 | 1);

reply = call("vkGetPhysicalDeviceFeatures2", { physicalDevice: PHYSICAL_DEVICE, pFeatures: { sType: 1000059000,
    pNext: { sType: 1000083000, pNext: { sType: 1000053001 } } } });
assert.equal(reply.pFeatures.features.robustBufferAccess, 1);
assert.equal(reply.pFeatures.features.geometryShader, 0);
assert.equal(reply.pFeatures.pNext.sType, 1000083000, "the chain comes back in its order");

reply = call("vkGetPhysicalDeviceQueueFamilyProperties2", { physicalDevice: PHYSICAL_DEVICE, pQueueFamilyPropertyCount: 4,
    pQueueFamilyProperties: Array.from({ length: 4 }, () => ({ sType: 1000059005 })) });
assert.equal(reply.pQueueFamilyPropertyCount, 1);
assert.equal(reply.pQueueFamilyProperties[0].queueFamilyProperties.queueFlags, 7, "graphics, compute, transfer");

reply = call("vkGetPhysicalDeviceMemoryProperties2", { physicalDevice: PHYSICAL_DEVICE, pMemoryProperties: { sType: 1000059006 } });
const memory = reply.pMemoryProperties.memoryProperties;
assert.equal(memory.memoryTypeCount, 3);
assert.deepEqual(memory.memoryTypes.slice(0, 3).map(t => t.propertyFlags), [1, 6, 14]);

reply = call("vkGetPhysicalDeviceFormatProperties2", { physicalDevice: PHYSICAL_DEVICE, format: 37, pFormatProperties: { sType: 1000059002 } });
const rgba8 = reply.pFormatProperties.formatProperties;
assert.equal(rgba8.optimalTilingFeatures & 0x1181, 0x1181, "R8G8B8A8_UNORM: sampled, linear filter, color attachment, blend");
assert.equal(rgba8.bufferFeatures & 0x40, 0x40, "and a vertex format");

reply = call("vkGetPhysicalDeviceImageFormatProperties2", { physicalDevice: PHYSICAL_DEVICE,
    pImageFormatInfo: { sType: 1000059004, format: 37, type: 1, tiling: 0, usage: 0x14, flags: 0 },
    pImageFormatProperties: { sType: 1000059003 } });
assert.equal(reply.ret, 0);
assert.equal(reply.pImageFormatProperties.imageFormatProperties.maxExtent.width, 8192);
assert.equal(reply.pImageFormatProperties.imageFormatProperties.sampleCounts, 5, "1 and 4 samples");
reply = call("vkGetPhysicalDeviceImageFormatProperties2", { physicalDevice: PHYSICAL_DEVICE,
    pImageFormatInfo: { sType: 1000059004, format: 106, type: 1, tiling: 0, usage: 0x4, flags: 0 },
    pImageFormatProperties: { sType: 1000059003 } });
assert.equal(reply.ret, -11, "R32G32B32_SFLOAT images: VK_ERROR_FORMAT_NOT_SUPPORTED");

reply = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: PHYSICAL_DEVICE, pLayerName: null, pPropertyCount: 0, pProperties: null });
const count = reply.pPropertyCount;
reply = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: PHYSICAL_DEVICE, pLayerName: null, pPropertyCount: count,
    pProperties: new Array(count).fill(0).map(() => ({})) });
assert.ok(reply.pProperties.some(p => p.extensionName === "VK_KHR_driver_properties"));
// transform feedback (VX captures in a compute pass), and more uniform buffers a stage than WebGPU's 12 (VX makes the rest storage)
assert.ok(reply.pProperties.some(p => p.extensionName === "VK_EXT_transform_feedback"), "VK_EXT_transform_feedback");
reply = call("vkGetPhysicalDeviceFeatures2", { physicalDevice: PHYSICAL_DEVICE, pFeatures: { sType: 1000059000, pNext: { sType: 1000028000 } } });
assert.deepEqual([reply.pFeatures.pNext.transformFeedback, reply.pFeatures.pNext.geometryStreams], [1, 0], "VkPhysicalDeviceTransformFeedbackFeaturesEXT");
reply = call("vkGetPhysicalDeviceProperties2", { physicalDevice: PHYSICAL_DEVICE, pProperties: { sType: 1000059001, pNext: { sType: 1000028001 } } });
const xfb_properties = reply.pProperties.pNext;
assert.deepEqual([xfb_properties.maxTransformFeedbackStreams, xfb_properties.maxTransformFeedbackBuffers, xfb_properties.transformFeedbackQueries], [1, 4, 1],
    "VkPhysicalDeviceTransformFeedbackPropertiesEXT");
assert.equal(reply.pProperties.properties.limits.maxPerStageDescriptorUniformBuffers, 14, "14 uniform buffers a stage");
console.log("PASS: the instance and physical device queries");

// A command the model does not do yet: an error, the ring goes on
reply = call("vkGetPhysicalDeviceCalibrateableTimeDomainsKHR", { physicalDevice: PHYSICAL_DEVICE, pTimeDomainCount: 0, pTimeDomains: null });
assert.equal(reply.ret, -8, "VK_ERROR_FEATURE_NOT_PRESENT");

// ---------------------------------------------------------------------------
// The transport's other commands

// Indirect: the commands in another shared memory, run by vkExecuteCommandStreamsMESA
const indirect = encode(["vkEnumerateInstanceVersion", { cmd_flags: 1 }]);
write_bytes(hostmem + STREAM_AT + 64, indirect);
ring_write(encode(["vkSetReplyCommandStreamMESA", { pStream: { resourceId: REPLY_RES, offset: 0x8000, size: 0x100 } }],
    ["vkExecuteCommandStreamsMESA", { streamCount: 1, pStreams: [{ resourceId: STREAM_RES, offset: 64, size: indirect.length }],
        pReplyPositions: [16], dependencyCount: 0, pDependencies: null, flags: 0 }]));
reply = GUEST["vkEnumerateInstanceVersion"][1](new VenusReader(read_bytes(hostmem + REPLY_AT + 0x8000 + 16, 64)));
assert.equal(reply.pApiVersion >>> 12, 1 << 10 | 1, "the indirect command's reply, where its position said");
console.log("PASS: vkExecuteCommandStreamsMESA");

// vkWriteRingExtraMESA (SUBMIT_3D)
assert.equal(answer(submit_3d(encode(["vkWriteRingExtraMESA", { ring: RING_ID, offset: 8, value: 0xCAFE }]))), OK);
assert.equal(read32(ring_base + EXTRA + 8), 0xCAFE, "vkWriteRingExtraMESA");

// vkWaitRingSeqnoMESA (SUBMIT_3D): the ring is read before the answer, without the timer
ring_write(encode(["vkEnumerateInstanceVersion", {}]), false);
assert.notEqual(read32(ring_base + HEAD), tail, "not read yet");
assert.equal(answer(submit_3d(encode(["vkWaitRingSeqnoMESA", { ring: RING_ID, seqno: tail }]))), OK);
assert.equal(read32(ring_base + HEAD), tail, "read for vkWaitRingSeqnoMESA");

// vkWaitVirtqueueSeqnoMESA in the ring waits for vkSubmitVirtqueueSeqnoMESA through SUBMIT_3D
const before = tail;
ring_write(encode(["vkWaitVirtqueueSeqnoMESA", { seqno: 5 }], ["vkEnumerateInstanceVersion", {}]));
assert.equal(read32(ring_base + HEAD), before, "the ring stops at the wait");
assert.equal(answer(submit_3d(encode(["vkSubmitVirtqueueSeqnoMESA", { ring: RING_ID, seqno: 5 }]))), OK);
assert.equal(read32(ring_base + HEAD), tail, "the ring went on");

// A SUBMIT_3D waiting for a ring that waits is answered after it, and the
// submissions after it run after it (virglrenderer's order)
ring_write(encode(["vkWaitVirtqueueSeqnoMESA", { seqno: 6 }]));
const waiting = submit_3d(encode(["vkWaitRingSeqnoMESA", { ring: RING_ID, seqno: tail }]), false);
assert.equal(answer(waiting), 0xDEADBEEF, "not answered while the ring waits");
const after = submit_3d(encode(["vkWriteRingExtraMESA", { ring: RING_ID, offset: 12, value: 7 }]), false);
assert.equal(read32(ring_base + EXTRA + 12), 0, "the submission after it waits too");
// (here the seqno comes from nowhere: the driver's would be in a submission before)
const venus_ctx = gpu.venus.contexts.get(CTX);
venus_ctx.virtqueue_seqnos.set(RING_ID, 6);
gpu.venus.wake_seqno_waits(venus_ctx);
assert.equal(read32(ring_base + HEAD), tail, "the ring went on");
assert.equal(answer(waiting), OK, "the waiting SUBMIT_3D was answered");
assert.equal(answer(after), OK, "and the one after it");
assert.equal(read32(ring_base + EXTRA + 12), 7);
console.log("PASS: seqno waits of rings and submissions");

// The ALIVE bit comes back after the driver's watchdog clears it
write32(ring_base + STATUS, read32(ring_base + STATUS) & ~4);
cpu.devices.display.timer(cpu.clock.now() + 1000);
assert.equal(read32(ring_base + STATUS) & 4, 4, "ALIVE again");

// A command the protocol does not know: the ring is FATAL
ring_write(Uint8Array.from([0xFF, 0xFF, 0, 0, 0, 0, 0, 0]));
assert.equal(read32(ring_base + STATUS) & 2, 2, "FATAL");
console.log("PASS: ALIVE and FATAL");

// ---------------------------------------------------------------------------
// Memory and submissions: a timeline wait the host meets later; GPU writes
// into memory the guest maps, while the guest writes other bytes of the
// same page

// (a new ring: the old one is FATAL)
const RING2 = RING_ID + 1;
tail = 0;
for(let i = 0; i < 256; i += 4) write32(ring_base + i, 0);
assert.equal(answer(submit_3d(encode(["vkCreateRingMESA", { ring: RING2, pCreateInfo: {
    sType: 1000384000, resourceId: RING_RES, offset: 0, size: RING_SIZE, idleTimeout: 1000000,
    headOffset: HEAD, tailOffset: TAIL, statusOffset: STATUS, bufferOffset: BUFFER, bufferSize: BUFFER_SIZE,
    extraOffset: EXTRA, extraSize: 64 } }]))), OK);
const DEVICE = 0x3000, QUEUE = 0x3001, BUF = 0x3002, MEM = 0x3003, SEM = 0x3004, POOL = 0x3005, CB = 0x3006;
reply = call("vkCreateDevice", { physicalDevice: PHYSICAL_DEVICE, pCreateInfo: { sType: 3, queueCreateInfoCount: 1,
    pQueueCreateInfos: [{ sType: 2, queueFamilyIndex: 0, queueCount: 1, pQueuePriorities: [1] }] }, pDevice: DEVICE });
assert.equal(reply.ret, 0, "vkCreateDevice");
ring_write(encode(["vkGetDeviceQueue2", { device: DEVICE, pQueueInfo: { sType: 1000145003, pNext: { sType: 1000384005, ringIdx: 1 },
    queueFamilyIndex: 0, queueIndex: 0 }, pQueue: QUEUE }],
    ["vkCreateBuffer", { device: DEVICE, pCreateInfo: { sType: 12, size: 4096, usage: 3 }, pBuffer: BUF }],
    ["vkAllocateMemory", { device: DEVICE, pAllocateInfo: { sType: 5, allocationSize: 4096, memoryTypeIndex: 1 }, pMemory: MEM }],
    ["vkBindBufferMemory", { device: DEVICE, buffer: BUF, memory: MEM, memoryOffset: 0 }],
    ["vkCreateSemaphore", { device: DEVICE, pCreateInfo: { sType: 9, pNext: { sType: 1000207002, semaphoreType: 1, initialValue: 0 } }, pSemaphore: SEM }],
    ["vkCreateCommandPool", { device: DEVICE, pCreateInfo: { sType: 39, queueFamilyIndex: 0 }, pCommandPool: POOL }],
    ["vkAllocateCommandBuffers", { device: DEVICE, pAllocateInfo: { sType: 40, commandPool: POOL, level: 0, commandBufferCount: 1 }, pCommandBuffers: [CB] }],
    ["vkBeginCommandBuffer", { commandBuffer: CB, pBeginInfo: { sType: 42 } }],
    ["vkCmdCopyBuffer", { commandBuffer: CB, srcBuffer: BUF, dstBuffer: BUF, regionCount: 1, pRegions: [{ srcOffset: 0, dstOffset: 64, size: 8 }] }],
    ["vkEndCommandBuffer", { commandBuffer: CB }]));
// the memory's blob, mapped
const MEM_RES = 20, MEM_AT = 0x400000, mem_base = hostmem + MEM_AT;
assert.equal(command(0x010C, MEM_RES, HOST3D, MAPPABLE, 0, MEM, 0, 4096, 0), OK, "RESOURCE_CREATE_BLOB of the memory");
assert.equal(command(0x0208, MEM_RES, 0, MEM_AT, 0), OK_MAP_INFO, "MAP_BLOB of the memory");
assert.deepEqual(Array.from(read_bytes(mem_base, 8)), [0, 0, 0, 0, 0, 0, 0, 0], "new memory reads as zeros");
write32(mem_base, 2);
// the submission waits for 1, signals 2
ring_write(encode(["vkQueueSubmit", { queue: QUEUE, submitCount: 1, pSubmits: [{ sType: 4,
    pNext: { sType: 1000207003, waitSemaphoreValueCount: 1, pWaitSemaphoreValues: [1], signalSemaphoreValueCount: 1, pSignalSemaphoreValues: [2] },
    waitSemaphoreCount: 1, pWaitSemaphores: [SEM], pWaitDstStageMask: [1], commandBufferCount: 1, pCommandBuffers: [CB],
    signalSemaphoreCount: 1, pSignalSemaphores: [SEM] }], fence: 0 }]));
assert.ok(!vx_log.includes(VX.BEGIN), "the submission waits for the semaphore");
reply = call("vkGetSemaphoreCounterValue", { device: DEVICE, semaphore: SEM, pValue: 0 });
assert.equal(reply.pValue, 0);
// the guest writes another byte of the page; the host signals 1; while the
// GPU runs the submission, the guest writes yet another byte of the page
cpu.write8(mem_base + 512, 0xAB);
held = [];
ring_write(encode(["vkSignalSemaphore", { device: DEVICE, pSignalInfo: { sType: 1000207005, semaphore: SEM, value: 1 } }]));
cpu.write8(mem_base + 520, 0xCD);
flush_renderer();
assert.ok(vx_log.includes(VX.BEGIN), "the submission ran");
assert.equal(read32(mem_base + 64), 2, "the GPU's copy, in the mapping");
assert.equal(cpu.read8(mem_base + 512), 0xAB, "the guest's byte, still there");
assert.equal(cpu.read8(mem_base + 520), 0xCD, "and the one it wrote while the GPU ran");
reply = call("vkGetSemaphoreCounterValue", { device: DEVICE, semaphore: SEM, pValue: 0 });
assert.equal(reply.pValue, 2, "the submission signaled 2");
console.log("PASS: a timeline wait the host meets; the GPU's and the guest's writes to one page");

// A blob of whole guest pages: a 16 KiB-page kernel rounds a memory of 20000
// bytes to 32768 (accepted); a blob past the largest page's rounding is not
const MEM16 = 0x3009, MEM16_RES = 21, MEM_BIG = 0x300A, MEM_BIG_RES = 22;
ring_write(encode(["vkAllocateMemory", { device: DEVICE, pAllocateInfo: { sType: 5, allocationSize: 20000, memoryTypeIndex: 1 }, pMemory: MEM16 }],
    ["vkAllocateMemory", { device: DEVICE, pAllocateInfo: { sType: 5, allocationSize: 20000, memoryTypeIndex: 1 }, pMemory: MEM_BIG }]));
assert.equal(command(0x010C, MEM16_RES, HOST3D, MAPPABLE, 0, MEM16, 0, 32768, 0), OK, "RESOURCE_CREATE_BLOB rounded to 16 KiB pages");
assert.equal(command(0x010C, MEM_BIG_RES, HOST3D, MAPPABLE, 0, MEM_BIG, 0, 131072, 0), ERR_INVALID_PARAMETER, "a blob past 64 KiB pages' rounding");
console.log("PASS: blobs rounded to the guest's pages (4, 16, 64 KiB)");

// Sync files (Venus's WSI needs them): what the device says of them; a
// fence's or semaphore's pending signal that went into a sync file does not
// land on it any more; a sync file the driver waited for signals a semaphore
reply = call("vkGetPhysicalDeviceExternalSemaphoreProperties", { physicalDevice: PHYSICAL_DEVICE,
    pExternalSemaphoreInfo: { sType: 1000076000, handleType: 0x10 }, pExternalSemaphoreProperties: { sType: 1000076001 } });
assert.equal(reply.pExternalSemaphoreProperties.externalSemaphoreFeatures, 3, "binary semaphores: sync files export and import");
reply = call("vkGetPhysicalDeviceExternalSemaphoreProperties", { physicalDevice: PHYSICAL_DEVICE,
    pExternalSemaphoreInfo: { sType: 1000076000, pNext: { sType: 1000207002, semaphoreType: 1, initialValue: 0 }, handleType: 0x10 },
    pExternalSemaphoreProperties: { sType: 1000076001 } });
assert.equal(reply.pExternalSemaphoreProperties.externalSemaphoreFeatures, 0, "timeline semaphores: none");
reply = call("vkGetPhysicalDeviceExternalFenceProperties", { physicalDevice: PHYSICAL_DEVICE,
    pExternalFenceInfo: { sType: 1000112000, handleType: 8 }, pExternalFenceProperties: { sType: 1000112001 } });
assert.equal(reply.pExternalFenceProperties.externalFenceFeatures, 3, "fences: sync files export and import");
const FENCE = 0x3007, BSEM = 0x3008;
const submit_signaling = () => ["vkQueueSubmit", { queue: QUEUE, submitCount: 1, pSubmits: [{ sType: 4, waitSemaphoreCount: 0, pWaitSemaphores: null,
    pWaitDstStageMask: null, commandBufferCount: 1, pCommandBuffers: [CB], signalSemaphoreCount: 1, pSignalSemaphores: [BSEM] }], fence: FENCE }];
ring_write(encode(["vkCreateFence", { device: DEVICE, pCreateInfo: { sType: 8, flags: 0 }, pFence: FENCE }],
    ["vkCreateSemaphore", { device: DEVICE, pCreateInfo: { sType: 9 }, pSemaphore: BSEM }]));
const binary = () => gpu.venus.contexts.get(CTX).objects.get(BSEM).signaled;
held = [];
ring_write(encode(submit_signaling(), ["vkResetFenceResourceMESA", { device: DEVICE, fence: FENCE }],
    ["vkWaitSemaphoreResourceMESA", { device: DEVICE, semaphore: BSEM }]));
flush_renderer();
assert.equal(call("vkGetFenceStatus", { device: DEVICE, fence: FENCE }).ret, 1, "VK_NOT_READY: the fence's signal went to the sync file");
assert.equal(binary(), false, "and the semaphore's");
held = [];
ring_write(encode(submit_signaling()));
flush_renderer();
assert.equal(call("vkGetFenceStatus", { device: DEVICE, fence: FENCE }).ret, 0, "a submission's fence signals as before");
assert.equal(binary(), true);
ring_write(encode(["vkWaitSemaphoreResourceMESA", { device: DEVICE, semaphore: BSEM }]));
assert.equal(binary(), false, "a sync file took the signal");
ring_write(encode(["vkImportSemaphoreResourceMESA", { device: DEVICE, pImportSemaphoreResourceInfo: { sType: 1000384004, semaphore: BSEM, resourceId: 0 } }]));
assert.equal(binary(), true, "a sync file the driver waited for signals it");
console.log("PASS: sync files of fences and semaphores");

// A snapshot, saved and restored: the context, its ring, reply stream and
// objects, the renderer's memory with what the GPU wrote, the mapping
const mem_rid = gpu.venus.contexts.get(CTX).objects.get(MEM).rid;
assert.equal(read32(mem_base + 64), 2);
const state = await emulator.save_state();
vx_memory.clear();
vx_log.length = 0;
await emulator.restore_state(state);
assert.ok(vx_log.includes(VX.MEMORY_CREATE), "the renderer's memory made again");
assert.equal(new DataView(vx_memory.get(mem_rid).buffer).getUint32(64, true), 2, "with what the GPU had written");
assert.equal(read32(mem_base + 64), 2, "the mapping");
assert.equal(call("vkGetSemaphoreCounterValue", { device: DEVICE, semaphore: SEM, pValue: 0 }).pValue, 2, "the ring and the semaphore go on");
assert.equal(call("vkGetFenceStatus", { device: DEVICE, fence: FENCE }).ret, 0, "the fence");
write32(mem_base, 7);
ring_write(encode(["vkQueueSubmit", { queue: QUEUE, submitCount: 1, pSubmits: [{ sType: 4, waitSemaphoreCount: 0, pWaitSemaphores: null,
    pWaitDstStageMask: null, commandBufferCount: 1, pCommandBuffers: [CB], signalSemaphoreCount: 0, pSignalSemaphores: null }], fence: 0 }]));
assert.equal(call("vkGetSemaphoreCounterValue", { device: DEVICE, semaphore: SEM, pValue: 0 }).pValue, 2);
assert.equal(read32(mem_base + 64), 7, "the command buffer, recorded before the snapshot, runs after it");
console.log("PASS: snapshots");

// gralloc's buffers (Android: docs/arm64-virt-android16-plan.md P11.4): the
// modifier and foreign queue extensions without the dma-buf ones (Mesa's
// venus on Linux would take swapchain images for dma-bufs), one modifier
// (linear), dma-buf images importable all the same, a virgl resource imported as
// memory (VkImportMemoryResourceInfoMESA) and an image bound to it, which
// becomes the resource's GX surface (VX.TEXTURE_IMPORT); after a submission
// the GPU's copy of the resource is the newer one; the import is in the
// state a snapshot keeps
reply = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: PHYSICAL_DEVICE, pLayerName: null, pPropertyCount: 0, pProperties: null });
reply = call("vkEnumerateDeviceExtensionProperties", { physicalDevice: PHYSICAL_DEVICE, pLayerName: null, pPropertyCount: reply.pPropertyCount,
    pProperties: new Array(reply.pPropertyCount).fill(0).map(() => ({})) });
for(const name of ["VK_EXT_image_drm_format_modifier", "VK_EXT_queue_family_foreign"])
{
    assert.ok(reply.pProperties.some(p => p.extensionName === name), name);
}
for(const name of ["VK_EXT_external_memory_dma_buf", "VK_KHR_external_memory_fd"])
{
    assert.ok(!reply.pProperties.some(p => p.extensionName === name), "not " + name);
}
const modifier_list = (count, properties) => call("vkGetPhysicalDeviceFormatProperties2", { physicalDevice: PHYSICAL_DEVICE, format: 37,
    pFormatProperties: { sType: 1000059002, pNext: { sType: 1000158000, drmFormatModifierCount: count, pDrmFormatModifierProperties: properties } } })
    .pFormatProperties.pNext;
assert.equal(modifier_list(0, null).drmFormatModifierCount, 1, "R8G8B8A8_UNORM: one modifier");
const linear = modifier_list(1, [{}]).pDrmFormatModifierProperties[0];
assert.equal(Number(linear.drmFormatModifier), 0, "DRM_FORMAT_MOD_LINEAR");
assert.equal(linear.drmFormatModifierPlaneCount, 1);
assert.equal(linear.drmFormatModifierTilingFeatures & 0x1181, 0x1181, "with optimal tiling's features");
const external_image = (handle_type, modifier) => call("vkGetPhysicalDeviceImageFormatProperties2", { physicalDevice: PHYSICAL_DEVICE,
    pImageFormatInfo: { sType: 1000059004, pNext: { sType: 1000071000, handleType: handle_type, pNext: { sType: 1000158002, drmFormatModifier: modifier,
        sharingMode: 0, queueFamilyIndexCount: 0, pQueueFamilyIndices: null } }, format: 37, type: 1, tiling: 1000158000, usage: 0x16, flags: 0 },
    pImageFormatProperties: { sType: 1000059003, pNext: { sType: 1000071001 } } });
reply = external_image(0x200, 0);
assert.equal(reply.ret, 0, "a dma-buf image with the linear modifier");
assert.equal(reply.pImageFormatProperties.pNext.externalMemoryProperties.externalMemoryFeatures, 5, "dedicated, importable");
assert.equal(reply.pImageFormatProperties.pNext.externalMemoryProperties.compatibleHandleTypes, 0x200);
assert.equal(external_image(0x1, 0).ret, -11, "opaque fds: no");
assert.equal(external_image(0x200, 1).ret, -11, "another modifier: no");
// (a virgl resource, as minigbm makes one: RESOURCE_CREATE_3D, a 2D texture of R8G8B8A8_UNORM)
const AHB_RES = 30, AHB_IMAGE = 0x3010, AHB_MEM = 0x3011, CB2 = 0x3012;
assert.equal(command(0x0204, AHB_RES, 2, 67, 2, 64, 32, 1, 1, 0, 0, 0, 0), OK, "RESOURCE_CREATE_3D");
const resource_properties = id => call("vkGetMemoryResourcePropertiesMESA", { device: DEVICE, resourceId: id,
    pMemoryResourceProperties: { pNext: { sType: 1000384003 } } });
reply = resource_properties(AHB_RES);
assert.equal(reply.ret, 0);
assert.equal(reply.pMemoryResourceProperties.memoryTypeBits, 1, "device local");
assert.equal(Number(reply.pMemoryResourceProperties.pNext.allocationSize), 64 * 32 * 4);
assert.equal(resource_properties(99).ret, -1000072003, "an unknown resource: VK_ERROR_INVALID_EXTERNAL_HANDLE");
ring_write(encode(["vkCreateImage", { device: DEVICE, pCreateInfo: { sType: 14,
        pNext: { sType: 1000072001, handleTypes: 0x200, pNext: { sType: 1000158004, drmFormatModifier: 0, drmFormatModifierPlaneCount: 1,
            pPlaneLayouts: [{ offset: 0, size: 8192, rowPitch: 256, arrayPitch: 0, depthPitch: 0 }] } },
        flags: 0, imageType: 1, format: 37, extent: { width: 64, height: 32, depth: 1 }, mipLevels: 1, arrayLayers: 1, samples: 1,
        tiling: 1000158000, usage: 0x16, sharingMode: 0, queueFamilyIndexCount: 0, pQueueFamilyIndices: null, initialLayout: 0 }, pImage: AHB_IMAGE }],
    ["vkAllocateMemory", { device: DEVICE, pAllocateInfo: { sType: 5, pNext: { sType: 1000384002, resourceId: AHB_RES,
        pNext: { sType: 1000127001, image: AHB_IMAGE, buffer: 0 } }, allocationSize: 8192, memoryTypeIndex: 0 }, pMemory: AHB_MEM }],
    ["vkBindImageMemory", { device: DEVICE, image: AHB_IMAGE, memory: AHB_MEM, memoryOffset: 0 }],
    ["vkAllocateCommandBuffers", { device: DEVICE, pAllocateInfo: { sType: 40, commandPool: POOL, level: 0, commandBufferCount: 1 }, pCommandBuffers: [CB2] }],
    ["vkBeginCommandBuffer", { commandBuffer: CB2, pBeginInfo: { sType: 42 } }],
    ["vkEndCommandBuffer", { commandBuffer: CB2 }]));
const vk = gpu.venus.vk;
const import_entry = [...vk.imports.values()][0];
assert.equal(import_entry[1], AHB_RES);
assert.equal(Number(call("vkGetImageDrmFormatModifierPropertiesEXT", { device: DEVICE, image: AHB_IMAGE, pProperties: {} }).pProperties.drmFormatModifier), 0);
assert.equal(Number(call("vkGetImageSubresourceLayout", { device: DEVICE, image: AHB_IMAGE, pSubresource: { aspectMask: 1, mipLevel: 0, arrayLayer: 0 },
    pLayout: {} }).pLayout.rowPitch), 256, "the guest's layout");
const ahb = gpu.resources.get(AHB_RES);
ahb.host_newer = true;
ring_write(encode(["vkQueueSubmit", { queue: QUEUE, submitCount: 1, pSubmits: [{ sType: 4, waitSemaphoreCount: 0, pWaitSemaphores: null,
    pWaitDstStageMask: null, commandBufferCount: 1, pCommandBuffers: [CB2], signalSemaphoreCount: 0, pSignalSemaphores: null }], fence: 0 }]));
assert.equal(ahb.host_newer, false, "after a submission the GPU's copy is the newer one");
// (the VX commands go with the submission's batch: the image made, then made the resource's surface)
assert.ok(vx_log.lastIndexOf(VX.TEXTURE_IMPORT) > vx_log.lastIndexOf(VX.TEXTURE_CREATE), "the image is the resource's GX surface");
assert.deepEqual(vk.get_state()[5], [import_entry], "a snapshot keeps the import");
console.log("PASS: gralloc's buffers: dma-buf images, resources imported as memory");

// Ring ids are the driver's pointers to its rings, exact: two threads' rings
// 0x1c0 apart on Android's tagged heap are two rings (as numbers both were
// 0xb4000076e5a3c000: the second ring replaced the first, whose thread
// waited for its replies for good). A snapshot of then has its ids as those
// numbers, and the driver's exact ids still find its rings.
{
    const rings = gpu.venus.contexts.get(CTX).rings;
    const RINGS_RES = 40;
    blob(RINGS_RES, RING_SIZE, 0x400000);
    const create = ring => answer(submit_3d(encode(["vkCreateRingMESA", { ring, pCreateInfo: {
        sType: 1000384000, resourceId: RINGS_RES, offset: 0, size: RING_SIZE, idleTimeout: 1000000,
        headOffset: HEAD, tailOffset: TAIL, statusOffset: STATUS, bufferOffset: BUFFER, bufferSize: BUFFER_SIZE,
        extraOffset: EXTRA, extraSize: 64 } }])));
    const count = rings.size;
    const [A, B] = ["b4000076e5a3c180", "b4000076e5a3c340"];
    assert.equal(create(A), OK);
    assert.equal(create(B), OK);
    assert.equal(rings.size, count + 2, "two rings");
    assert.equal(answer(submit_3d(encode(["vkDestroyRingMESA", { ring: B }]))), OK);
    assert.ok(rings.has(A) && !rings.has(B), "one destroyed, the other there");

    // (the Venus state of a snapshot of before: the ids as numbers)
    const venus_state = gpu.venus.get_state();
    for(const context of venus_state[0]) for(const r of context[1]) r[0] = Number(BigInt("0x" + r[0]));
    gpu.venus.set_state(venus_state, id => { const r = gpu.resources.get(id); return r && r.venus ? r : null; });
    const restored = gpu.venus.contexts.get(CTX).rings;
    assert.equal(restored.size, count + 1);
    assert.equal(answer(submit_3d(encode(["vkWriteRingExtraMESA", { ring: A, offset: 16, value: 0x5A5A }]))), OK, "a ring of the old snapshot by its exact id");
    assert.equal(answer(submit_3d(encode(["vkWriteRingExtraMESA", { ring: RING2, offset: 20, value: 0xA5A5 }]))), OK);
    assert.equal(read32(ring_base + EXTRA + 20), 0xA5A5, "and the test's own ring");
    assert.equal(answer(submit_3d(encode(["vkDestroyRingMESA", { ring: A }]))), OK);
    assert.equal(restored.size, count, "destroyed by its exact id");
}
console.log("PASS: ring ids, exact; a snapshot's rounded ids");

// A snapshot while requests wait: the ring waits for a virtqueue seqno, a
// SUBMIT_3D waits for the ring and holds the queue, a request after it is not
// read. Restored in place over a machine whose ring and submission wait too:
// the other machine's waits, woken, write nothing into the ring and release
// nothing; the snapshot's submission is answered once its ring goes on, and
// the request after it after that
{
    const q = QUEUES[0];
    const ring_wait = seqno => ring_write(encode(["vkWaitVirtqueueSeqnoMESA", { seqno }], ["vkEnumerateInstanceVersion", {}]));
    const wake = (ctx, seqno) => { ctx.virtqueue_seqnos.set(RING2, seqno); gpu.venus.wake_seqno_waits(ctx); };
    const head = read32(ring_base + HEAD);
    ring_wait(20);
    assert.equal(read32(ring_base + HEAD), head, "the ring waits");
    const submission = submit_3d(encode(["vkWaitRingSeqnoMESA", { ring: RING2, seqno: tail }]), false);
    const behind = control(0x0108, [2, 0], false);
    assert.equal(answer(submission), 0xDEADBEEF, "the submission waits");
    assert.equal(answer(behind), 0xDEADBEEF, "the request after it is held back");
    const saved = { avail_idx: q.avail_idx, next_slot, tail, reply_position };
    // (prepare_save waits for the requests a while, then they go into the snapshot)
    const state = await emulator.save_state();

    // the other machine: these go on, then a ring and a submission wait again
    wake(gpu.venus.contexts.get(CTX), 20);
    assert.equal(answer(submission), OK);
    assert.equal(answer(behind), OK_CAPSET_INFO);
    ring_wait(21);
    const other_head = read32(ring_base + HEAD);
    assert.notEqual(other_head, head);
    const other_submission = submit_3d(encode(["vkWaitRingSeqnoMESA", { ring: RING2, seqno: tail }]), false);
    assert.equal(answer(other_submission), 0xDEADBEEF);
    const other_ctx = gpu.venus.contexts.get(CTX);

    await emulator.restore_state(state);
    ({ avail_idx: q.avail_idx, next_slot, tail, reply_position } = saved);
    assert.equal(answer(submission), 0xDEADBEEF, "the snapshot's submission not answered");
    assert.equal(answer(behind), 0xDEADBEEF);
    // (the timer: the snapshot's requests queued again, after its guest RAM)
    cpu.devices.display.timer(cpu.clock.now());
    assert.equal(answer(submission), 0xDEADBEEF, "it waits again, in the command it waited in");
    assert.ok(gpu.held, "and holds the queue again");

    wake(other_ctx, 21);
    assert.equal(read32(ring_base + HEAD), head, "the other machine's ring writes no head into the restored one");
    assert.ok(gpu.held, "its submission releases nothing");
    assert.equal(answer(behind), 0xDEADBEEF, "the request after the snapshot's submission is still held back");

    wake(gpu.venus.contexts.get(CTX), 20);
    assert.equal(read32(ring_base + HEAD), tail, "the restored ring goes on");
    assert.equal(answer(submission), OK, "the snapshot's submission answered");
    assert.equal(answer(behind), OK_CAPSET_INFO, "then the request after it");
    assert.ok(!gpu.held && gpu.pending.length === 0);
}
console.log("PASS: a snapshot while requests wait, restored over a machine whose requests wait");

// Transform feedback: a command buffer's binds, begin and end are VX's
// XFB ops; a stream query pool keeps two values a query, and its query is
// one VX counts (BEGIN_QUERY and END_QUERY of the pool)
{
    const CB2 = 0x3020, XQ = 0x3021, XBUF = 0x3022;
    ring_write(encode(["vkCreateBuffer", { device: DEVICE, pCreateInfo: { sType: 12, size: 1024, usage: 0x800 }, pBuffer: XBUF }],
        ["vkBindBufferMemory", { device: DEVICE, buffer: XBUF, memory: MEM, memoryOffset: 0 }],
        ["vkCreateQueryPool", { device: DEVICE, pCreateInfo: { sType: 11, queryType: 1000028004, queryCount: 1 }, pQueryPool: XQ }],
        ["vkAllocateCommandBuffers", { device: DEVICE, pAllocateInfo: { sType: 40, commandPool: POOL, level: 0, commandBufferCount: 1 }, pCommandBuffers: [CB2] }],
        ["vkBeginCommandBuffer", { commandBuffer: CB2, pBeginInfo: { sType: 42 } }],
        ["vkCmdBeginQueryIndexedEXT", { commandBuffer: CB2, queryPool: XQ, query: 0, flags: 0, index: 0 }],
        ["vkCmdBindTransformFeedbackBuffersEXT", { commandBuffer: CB2, firstBinding: 0, bindingCount: 1, pBuffers: [XBUF], pOffsets: [256], pSizes: [512] }],
        ["vkCmdBeginTransformFeedbackEXT", { commandBuffer: CB2, firstCounterBuffer: 0, counterBufferCount: 1, pCounterBuffers: [XBUF], pCounterBufferOffsets: [0] }],
        ["vkCmdEndTransformFeedbackEXT", { commandBuffer: CB2, firstCounterBuffer: 0, counterBufferCount: 1, pCounterBuffers: [XBUF], pCounterBufferOffsets: [0] }],
        ["vkCmdEndQueryIndexedEXT", { commandBuffer: CB2, queryPool: XQ, query: 0, index: 0 }],
        ["vkEndCommandBuffer", { commandBuffer: CB2 }]));
    const pool = gpu.venus.contexts.get(CTX).objects.get(XQ);
    assert.deepEqual([pool.values, pool.memory.size], [2, 16], "a stream query pool: two u64 a query");
    vx_log.length = 0;
    ring_write(encode(["vkQueueSubmit", { queue: QUEUE, submitCount: 1, pSubmits: [{ sType: 4, waitSemaphoreCount: 0, pWaitSemaphores: null,
        pWaitDstStageMask: null, commandBufferCount: 1, pCommandBuffers: [CB2], signalSemaphoreCount: 0, pSignalSemaphores: null }], fence: 0 }]));
    const ops = vx_log.filter(op => [VX.BEGIN_QUERY, VX.XFB_BIND, VX.XFB_BEGIN, VX.XFB_END, VX.END_QUERY].includes(op));
    assert.deepEqual(ops, [VX.BEGIN_QUERY, VX.XFB_BIND, VX.XFB_BEGIN, VX.XFB_END, VX.END_QUERY], "the XFB ops in order: " + ops);
}
console.log("PASS: transform feedback's commands and queries");

// Destroying the context
assert.equal(command(0x0201), OK, "CTX_DESTROY");
assert.ok(!gpu.venus.contexts.has(CTX));
assert.equal(command(0x0102, RING_RES, 0), OK, "RESOURCE_UNREF");
console.log("PASS: CTX_DESTROY");

emulator.destroy();
                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/devices/virtio_rng.js                                                              0000755 0000000 0000000 00000005024 00000000000 015174  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// A virtio entropy device supplied through virtio_devices
// (docs/custom-virtio-devices.md), driven by Linux's own virtio_rng driver:
// the guest reads the device's bytes from /dev/hwrng.

import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const SHOW_LOGS = false;

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// Not random at all, so that the guest's reads can be checked
const pattern = i => i * 37 + 11 & 0xFF;

let device;
const rng = {
    "name": "rng",
    "device_id": 0x1044,
    "subsystem_device_id": 4,
    "queues": [{ "size": 8 }],
    "init": handle => { device = handle; },
    "notify": queue => {
        let request;
        while((request = device["pop_request"](queue)))
        {
            const bytes = new Uint8Array(request["writable"]);
            for(let i = 0; i < bytes.length; i++) bytes[i] = pattern(i);
            request["write"](bytes);
            request["complete"]();
        }
        device["flush"](queue);
    },
};

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    bzimage: { url: __dirname + "/../../images/buildroot-bzimage68.bin" },
    autostart: true,
    memory_size: 256 * 1024 * 1024,
    acpi: true,
    cmdline: "console=ttyS0 audit=0",
    disable_jit: +process.env.DISABLE_JIT,
    log_level: SHOW_LOGS ? 0x400000 : 0,
    virtio_devices: [rng],
});

const expected = Array.from({ length: 8 }, (_, i) => pattern(i).toString(16).padStart(2, "0")).join(" ");
let line = "";
let sent_command = false;
let passed = false;

const timeout = setTimeout(() => {
    console.error("\nTest failed: timeout");
    process.exit(1);
}, 120 * 1000);

emulator.add_listener("serial0-output-byte", function(byte)
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    line = chr === "\n" ? "" : line + chr;

    if(!sent_command && line.endsWith("~%"))
    {
        sent_command = true;
        emulator.serial0_send("cat /sys/class/misc/hw_random/rng_current; head -c 8 /dev/hwrng | od -An -tx1\n");
    }

    if(!passed && line.trim() === expected)
    {
        passed = true;
        clearTimeout(timeout);
        console.log("Test passed: /dev/hwrng reads " + expected);
        emulator.destroy();
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/devices/vmware_backdoor.js                                                         0000755 0000000 0000000 00000010203 00000000000 016152  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The VMware backdoor's RPCI channel (src/vmware.js, CMD_MESSAGE): the way
// vmwgfx and VMware's Windows drivers send their logs and ask for guestinfo
// settings, four bytes per access of port 0x5658, as open-vm-tools'
// lib/message does it.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const vm = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321, autostart: true, memory_size: 16 << 20,
    net_device: { type: "none" }, disable_speaker: true, log_level: 0,
});
await new Promise(resolve => vm.add_listener("emulator-ready", resolve));
await vm.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await vm.stop();

const cpu = vm.v86.cpu, io = cpu.io, reg = cpu.reg32;
const EAX = 0, ECX = 1, EDX = 2, EBX = 3, ESI = 6, EDI = 7;
const PORT = 0x5658, MAGIC = 0x564D5868, MESSAGE = 30;
/** One backdoor call: [eax, ebx, ecx, edx, esi, edi] after it */
const call = (step, ebx, channel) => {
    reg[EAX] = MAGIC;
    reg[EBX] = ebx;
    reg[ECX] = step << 16 | MESSAGE;
    reg[EDX] = channel << 16 | PORT;
    const eax = io.port_read32(PORT);
    return [eax, reg[EBX] >>> 0, reg[ECX] >>> 0, reg[EDX] >>> 0, reg[ESI] >>> 0, reg[EDI] >>> 0];
};
const SUCCESS = 1, DORECV = 2;

/** A whole RPCI exchange: the reply as text */
function rpci(text)
{
    const [, , status, edx] = call(0, 0x49435052 | 0x80000000, 0);
    assert.ok(status >>> 16 & SUCCESS, "OPEN");
    const channel = edx >>> 16;
    const bytes = new TextEncoder().encode(text);
    assert.ok(call(1, bytes.length, channel)[2] >>> 16 & SUCCESS, "SENDSIZE");
    for(let i = 0; i < bytes.length; i += 4)
    {
        const v = bytes[i] | (bytes[i + 1] | 0) << 8 | (bytes[i + 2] | 0) << 16 | (bytes[i + 3] | 0) << 24;
        assert.ok(call(2, v, channel)[2] >>> 16 & SUCCESS, "SENDPAYLOAD");
    }
    const [, size, received, type] = call(3, 0, channel);
    assert.ok(received >>> 16 & DORECV, "a reply");
    assert.equal(type >>> 16, 1, "its size comes as MESSAGE_TYPE_SENDSIZE");
    const reply = [];
    for(let i = 0; i < size; i += 4)
    {
        const [, v, , kind] = call(4, SUCCESS, channel);
        assert.equal(kind >>> 16, 2, "payload as MESSAGE_TYPE_SENDPAYLOAD");
        for(let j = 0; j < 4 && i + j < size; j++) reply.push(v >>> 8 * j & 0xFF);
    }
    call(5, SUCCESS, channel);
    assert.ok(call(6, 0, channel)[2] >>> 16 & SUCCESS, "CLOSE");
    return String.fromCharCode(...reply);
}

// what VMware Tools' installer asks first: which product, which hardware
reg[EAX] = MAGIC; reg[EBX] = 0; reg[ECX] = 10; reg[EDX] = PORT;
assert.equal(io.port_read32(PORT), 6, "GETVERSION: the backdoor's version");
assert.deepEqual([reg[EBX] >>> 0, reg[ECX]], [MAGIC, 4], "the magic, and the product: VMware Workstation");
reg[EAX] = MAGIC; reg[ECX] = 17; reg[EDX] = PORT;
assert.ok(io.port_read32(PORT) >= 11, "GETHWVERSION: a virtual hardware version");
console.log("PASS: GETVERSION names the product, GETHWVERSION the hardware version");

const logs = [];
vm.add_listener("vmware-log", text => logs.push(text));
assert.equal(rpci("log vm3d: WDDM 3D is enabled."), "1 ");
assert.deepEqual(logs, ["vm3d: WDDM 3D is enabled."], "the log reaches the emulator's bus");
assert.equal(rpci("info-get guestinfo.svga.wddm.enableGBObjects"), "0 No value found");
cpu.devices.vmware.guestinfo.set("svga.wddm.enableGBObjects", "FALSE");
assert.equal(rpci("info-get guestinfo.svga.wddm.enableGBObjects"), "1 FALSE", "guestinfo values the host set");
assert.equal(rpci("frobnicate"), "0 Unknown command");
console.log("PASS: RPCI over the backdoor: logs, guestinfo, unknown commands");
await vm.destroy();
                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/devices/vmware_svga.js                                                             0000755 0000000 0000000 00000041227 00000000000 015340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The VMware SVGA II adapter (src/graphics_adapters/vmware_svga), driven the
// way a driver does: PCI identity and BARs (what vm3d.inf matches), the
// register interface, modes and pitch, the FIFO (fences, interrupts,
// commands that wrap around the ring, unknown commands, 3D commands skipped
// at the 2D level), RECT_COPY, snapshots and reset. The guests' drivers are
// tested by tests/x64/linux_gpu.mjs.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const C = await import("../../src/graphics_adapters/vmware_svga/svga_constants.js");

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const VRAM = 8 << 20;
const emulator = new V86({
    graphics_adapter: "vmware_svga",
    graphics_adapter_test: { level: "2d" },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    vram_size: VRAM,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const svga = cpu.devices.graphics_adapter.device["svga"];
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };

// PCI identity: exactly what the Windows 8.1 driver's INF matches
assert.equal(pci_read(0x00), 0x040515AD, "VMware SVGA II");
assert.equal(pci_read(0x2C), 0x040515AD, "subsystem 15AD:0405");
assert.equal(pci_read(0x08), 0x03000000, "revision 0, VGA controller");
const bar0 = pci_read(0x10), bar1 = pci_read(0x14), bar2 = pci_read(0x18);
assert.equal(bar0 & 1, 1, "BAR0 is I/O");
assert.equal(bar1 & 0xF, 0x8, "BAR1 is prefetchable memory");
assert.equal(bar2 & 0xF, 0x0, "BAR2 is memory");
const port = bar0 & ~3, fb = (bar1 & ~0xF) >>> 0, fifo = (bar2 & ~0xF) >>> 0;
assert.equal(fb % VRAM, 0, "BAR1 aligned to its size");
assert.equal(fifo % (2 << 20), 0, "BAR2 aligned to its size");
console.log(`SeaBIOS put the ports at ${port.toString(16)}, the frame buffer at ${fb.toString(16)}, the FIFO at ${fifo.toString(16)}`);

const write_reg = (index, value) => { io.port_write32(port + C.SVGA_INDEX_PORT, index); io.port_write32(port + C.SVGA_VALUE_PORT, value); };
const read_reg = index => { io.port_write32(port + C.SVGA_INDEX_PORT, index); return io.port_read32(port + C.SVGA_VALUE_PORT) >>> 0; };
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const fifo_write = (index, value) => write32(fifo + index * 4, value);
const fifo_read = index => read32(fifo + index * 4);

// Version negotiation: the device keeps the highest it supports
write_reg(C.SVGA_REG_ID, C.SVGA_ID_2);
assert.equal(read_reg(C.SVGA_REG_ID), C.SVGA_ID_2);
write_reg(C.SVGA_REG_ID, C.SVGA_ID_2 + 1);
assert.equal(read_reg(C.SVGA_REG_ID), C.SVGA_ID_2, "SVGA_ID_3 is not taken");

const caps = read_reg(C.SVGA_REG_CAPABILITIES);
for(const cap of ["SVGA_CAP_EXTENDED_FIFO", "SVGA_CAP_PITCHLOCK", "SVGA_CAP_IRQMASK", "SVGA_CAP_RECT_COPY"])
{
    assert.ok(caps & C[cap], cap);
}
assert.equal(caps & C.SVGA_CAP_3D, 0, "no 3D at the 2D level");
assert.equal(read_reg(C.SVGA_REG_FB_START), fb);
assert.equal(read_reg(C.SVGA_REG_MEM_START), fifo);
assert.equal(read_reg(C.SVGA_REG_MEM_SIZE), 2 << 20);
assert.equal(read_reg(C.SVGA_REG_VRAM_SIZE), VRAM);
assert.equal(read_reg(C.SVGA_REG_MEM_REGS), C.SVGA_FIFO_NUM_REGS);
console.log("PASS: PCI identity, BARs and the register interface");

// A mode: 64x48x32, then a locked pitch
const pixel = (x, y) => {
    cpu.devices.display.request_frame(true);
    const p = (y * svga.pixels.width + x) * 4;
    return [...svga.pixels.data.subarray(p, p + 3)];
};
write_reg(C.SVGA_REG_WIDTH, 64);
write_reg(C.SVGA_REG_HEIGHT, 48);
write_reg(C.SVGA_REG_BITS_PER_PIXEL, 32);
assert.equal(read_reg(C.SVGA_REG_DEPTH), 24, "32 bpp has depth 24 (vmwgfx checks it)");
assert.equal(read_reg(C.SVGA_REG_BYTES_PER_LINE), 256);
write_reg(C.SVGA_REG_ENABLE, C.SVGA_REG_ENABLE_ENABLE);
write32(fb + 5 * 256 + 10 * 4, 0x00112233);
assert.deepEqual(pixel(10, 5), [0x11, 0x22, 0x33], "the SVGA mode is on screen");
write_reg(C.SVGA_REG_PITCHLOCK, 512);
assert.equal(read_reg(C.SVGA_REG_BYTES_PER_LINE), 512);
write32(fb + 7 * 512 + 3 * 4, 0x00445566);
assert.deepEqual(pixel(3, 7), [0x44, 0x55, 0x66], "rows are PITCHLOCK bytes apart");
console.log("PASS: modes and pitch");

// The FIFO: a 60 KiB ring after a page of registers
const MIN = 0x1000, MAX = 0x10000;
fifo_write(C.SVGA_FIFO_MIN, MIN);
fifo_write(C.SVGA_FIFO_MAX, MAX);
fifo_write(C.SVGA_FIFO_NEXT_CMD, MIN);
fifo_write(C.SVGA_FIFO_STOP, MIN);
write_reg(C.SVGA_REG_CONFIG_DONE, 1);
assert.equal(fifo_read(C.SVGA_FIFO_CAPABILITIES),
    C.SVGA_FIFO_CAP_FENCE | C.SVGA_FIFO_CAP_PITCHLOCK | C.SVGA_FIFO_CAP_RESERVE, "the device's FIFO capabilities");

let next = MIN;
const submit = (...dwords) => {
    for(const dword of dwords)
    {
        write32(fifo + next, dword);
        next = next + 4 === MAX ? MIN : next + 4;
    }
    fifo_write(C.SVGA_FIFO_NEXT_CMD, next);
    write_reg(C.SVGA_REG_SYNC, 1);
};
const irq_status = () => io.port_read32(port + C.SVGA_IRQSTATUS_PORT) >>> 0;

write_reg(C.SVGA_REG_IRQMASK, C.SVGA_IRQFLAG_ANY_FENCE);
submit(C.SVGA_CMD_FENCE, 0x1234);
assert.equal(fifo_read(C.SVGA_FIFO_FENCE), 0x1234, "the fence passed");
assert.equal(fifo_read(C.SVGA_FIFO_STOP), next, "the device consumed the command");
assert.equal(fifo_read(C.SVGA_FIFO_BUSY), 0);
assert.ok(irq_status() & C.SVGA_IRQFLAG_ANY_FENCE, "fence interrupt");
io.port_write32(port + C.SVGA_IRQSTATUS_PORT, C.SVGA_IRQFLAG_ANY_FENCE);
assert.equal(irq_status() & C.SVGA_IRQFLAG_ANY_FENCE, 0, "written 1 clears it");

// A command that wraps around the end of the ring
next = MAX - 4;
fifo_write(C.SVGA_FIFO_STOP, next);
fifo_write(C.SVGA_FIFO_NEXT_CMD, next);
submit(C.SVGA_CMD_FENCE, 0x5678);
assert.equal(fifo_read(C.SVGA_FIFO_FENCE), 0x5678, "a command split by the end of the ring");
assert.equal(fifo_read(C.SVGA_FIFO_STOP), MIN + 4);

// RECT_COPY within the frame buffer (pitch 512)
write32(fb + 1 * 512 + 1 * 4, 0x00FF0000);
submit(C.SVGA_CMD_RECT_COPY, 1, 1, 20, 9, 1, 1);
assert.deepEqual(pixel(20, 9), [0xFF, 0, 0], "RECT_COPY");

// 3D commands are skipped by their header at this level; unknown commands
// cannot be skipped: an error interrupt, and the FIFO is drained
submit(C.SVGA_3D_CMD_SURFACE_DEFINE, 8, 0, 0, C.SVGA_CMD_FENCE, 0x9ABC);
assert.equal(fifo_read(C.SVGA_FIFO_FENCE), 0x9ABC, "a 3D command skipped by its size");
write_reg(C.SVGA_REG_IRQMASK, C.SVGA_IRQFLAG_ERROR);
submit(0x7777, C.SVGA_CMD_FENCE, 0xDEF0);
assert.ok(irq_status() & C.SVGA_IRQFLAG_ERROR, "unknown command: error interrupt");
assert.equal(fifo_read(C.SVGA_FIFO_STOP), next, "and nothing left to parse");
assert.equal(fifo_read(C.SVGA_FIFO_FENCE), 0x9ABC, "the fence behind it is not run");
io.port_write32(port + C.SVGA_IRQSTATUS_PORT, 0xFFFFFFFF);
console.log("PASS: the FIFO: fences, interrupts, wrapping, RECT_COPY, 3D and unknown commands");

// Snapshots: registers, the FIFO and the frame buffer
const state = await emulator.save_state();
write_reg(C.SVGA_REG_PITCHLOCK, 0);
write_reg(C.SVGA_REG_WIDTH, 32);
submit(C.SVGA_CMD_FENCE, 0x1111);
await emulator.restore_state(state);
assert.equal(read_reg(C.SVGA_REG_PITCHLOCK), 512);
assert.equal(read_reg(C.SVGA_REG_WIDTH), 64);
assert.equal(fifo_read(C.SVGA_FIFO_FENCE), 0x9ABC, "FIFO memory comes back");
assert.deepEqual(pixel(20, 9), [0xFF, 0, 0], "the frame buffer comes back");
console.log("PASS: snapshots");

// A machine reset hands the screen back to VGA
cpu.reboot_internal("test");
assert.equal(read_reg(C.SVGA_REG_ENABLE), 0);
assert.equal(read_reg(C.SVGA_REG_CONFIG_DONE), 0);
console.log("PASS: reset");

await emulator.destroy();

// ---------------------------------------------------------------------------
// The whole 2D device (level 2d-full): guest memory regions, screen objects,
// command buffers, the hardware cursor

{
    const vm = new V86({
        graphics_adapter: "vmware_svga",
        graphics_adapter_test: { level: "2d-full" },
        bios: { url: __dirname + "/../../bios/seabios.bin" },
        vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
        fda: { buffer: floppy.buffer },
        boot_order: 0x321, autostart: true, memory_size: 32 << 20, vram_size: VRAM,
        net_device: { type: "none" }, disable_speaker: true, log_level: 0,
    });
    await new Promise(resolve => vm.add_listener("emulator-ready", resolve));
    await vm.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
    await vm.stop();
    const cpu = vm.v86.cpu, io = cpu.io, svga = cpu.devices.graphics_adapter.device["svga"];
    const port = pci_read_on(io, 0x10) & ~3, fifo = (pci_read_on(io, 0x18) & ~0xF) >>> 0;
    const reg = (index, value) => { io.port_write32(port, index); if(value === undefined) return io.port_read32(port + 1) >>> 0; io.port_write32(port + 1, value); };
    const w32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
    const r32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;

    const caps = reg(C.SVGA_REG_CAPABILITIES);
    for(const cap of ["SVGA_CAP_GMR", "SVGA_CAP_GMR2", "SVGA_CAP_SCREEN_OBJECT_2", "SVGA_CAP_COMMAND_BUFFERS",
        "SVGA_CAP_CMD_BUFFERS_2", "SVGA_CAP_CURSOR", "SVGA_CAP_ALPHA_CURSOR", "SVGA_CAP_MULTIMON", "SVGA_CAP_DISPLAY_TOPOLOGY"])
    {
        assert.ok(caps & C[cap], cap);
    }
    assert.ok(reg(C.SVGA_REG_GMR_MAX_IDS) > 0 && reg(C.SVGA_REG_GMRS_MAX_PAGES) > 0 && reg(C.SVGA_REG_MEMORY_SIZE) >= 64 << 20);

    reg(C.SVGA_REG_ENABLE, C.SVGA_REG_ENABLE_ENABLE);
    const MIN = 0x1000, MAX = 0x10000;
    w32(fifo, MIN); w32(fifo + 4, MAX); w32(fifo + 8, MIN); w32(fifo + 12, MIN);
    reg(C.SVGA_REG_CONFIG_DONE, 1);
    let next = MIN;
    const submit = (...dwords) => {
        for(const d of dwords) { w32(fifo + next, d); next = next + 4 === MAX ? MIN : next + 4; }
        w32(fifo + 8, next);
        reg(C.SVGA_REG_SYNC, 1);
    };

    // GMR1: a descriptor page at 1 MiB naming two pages at 2 MiB
    w32(0x100000, 0x200); w32(0x100004, 2); w32(0x100008, 0); w32(0x10000C, 0);
    reg(C.SVGA_REG_GMR_ID, 1);
    reg(C.SVGA_REG_GMR_DESCRIPTOR, 0x100);
    assert.deepEqual([...svga.gmrs.regions.get(1)], [0x200, 0x201], "GMR1 from its descriptor chain");

    // a 16x16 screen object (no backing store), filled from a GMRFB in GMR 1
    for(let i = 0; i < 16 * 16; i++) w32(0x200000 + i * 4, 0x00102030 + i);   // BGRX
    submit(C.SVGA_CMD_DEFINE_SCREEN, 44, 0, C.SVGA_SCREEN_MUST_BE_SET | C.SVGA_SCREEN_IS_PRIMARY, 16, 16, 0, 0,
        C.SVGA_GMR_NULL, 0, 0, 0);
    submit(C.SVGA_CMD_DEFINE_GMRFB, 1, 0, 64, 32 | 24 << 8);
    submit(C.SVGA_CMD_BLIT_GMRFB_TO_SCREEN, 0, 0, 0, 0, 16, 16, 0);
    const screen = svga.screens.screens.get(0);
    assert.deepEqual([...screen.rgba.subarray(0, 4)], [0x10, 0x20, 0x30, 255], "BLIT_GMRFB_TO_SCREEN converts BGRX");
    assert.deepEqual([...screen.rgba.subarray(17 * 4, 17 * 4 + 3)], [0x10, 0x20, 0x30 + 17], "row and column");

    // GMR2 defined and remapped by commands, read back into by BLIT_SCREEN_TO_GMRFB
    submit(C.SVGA_CMD_DEFINE_GMR2, 2, 2);
    submit(C.SVGA_CMD_REMAP_GMR2, 2, C.SVGA_REMAP_GMR2_PPN32, 0, 2, 0x300, 0x301);
    assert.deepEqual([...svga.gmrs.regions.get(2)], [0x300, 0x301], "REMAP_GMR2");
    submit(C.SVGA_CMD_DEFINE_GMRFB, 2, 0, 64, 32 | 24 << 8);
    submit(C.SVGA_CMD_BLIT_SCREEN_TO_GMRFB, 0, 0, 0, 0, 16, 16, 0);
    assert.equal(r32(0x300000 + 17 * 4) & 0xFFFFFF, 0x102030 + 17, "BLIT_SCREEN_TO_GMRFB");

    // a screen backed by the frame buffer (vmwgfx's screen object unit), next
    // to the first: shows VRAM, refreshed where UPDATE says
    const fb = (pci_read_on(io, 0x14) & ~0xF) >>> 0;
    w32(fb + 0x1000 + 3 * 32 + 2 * 4, 0x00AABBCC);
    submit(C.SVGA_CMD_DEFINE_SCREEN, 44, 1, 0, 8, 8, 16, 0, C.SVGA_GMR_FRAMEBUFFER, 0x1000, 32, 0);
    const backed = svga.screens.screens.get(1);
    assert.deepEqual([...backed.rgba.subarray((3 * 8 + 2) * 4, (3 * 8 + 2) * 4 + 3)], [0xAA, 0xBB, 0xCC], "a screen in VRAM");
    w32(fb + 0x1000 + 4 * 32 + 5 * 4, 0x00010203);
    submit(C.SVGA_CMD_UPDATE, 16 + 5, 4, 1, 1);
    assert.deepEqual([...backed.rgba.subarray((4 * 8 + 5) * 4, (4 * 8 + 5) * 4 + 3)], [1, 2, 3], "UPDATE in desktop coordinates");
    submit(C.SVGA_CMD_DESTROY_SCREEN, 1);
    console.log("PASS: GMR1, GMR2, screen objects and their blits");

    // what the screen sends to the display: the screen, then the cursor over it
    let layers = [];
    cpu.devices.display.update_buffer = l => { layers = layers.concat(l); };
    cpu.devices.display.request_frame(true);
    assert.equal(layers.length, 1, "one screen, one layer");
    assert.equal(layers[0].pixels.data, screen.rgba);
    submit(C.SVGA_CMD_DEFINE_ALPHA_CURSOR, 0, 1, 1, 2, 2, 0xFFFF0000, 0xFFFF0000, 0xFFFF0000, 0xFFFF0000);
    w32(fifo + C.SVGA_FIFO_CURSOR_ON * 4, 1);
    w32(fifo + C.SVGA_FIFO_CURSOR_X * 4, 5);
    w32(fifo + C.SVGA_FIFO_CURSOR_Y * 4, 6);
    w32(fifo + C.SVGA_FIFO_CURSOR_SCREEN_ID * 4, C.SVGA_ID_INVALID);
    w32(fifo + C.SVGA_FIFO_CURSOR_COUNT * 4, 1);
    layers = [];
    cpu.devices.display.request_frame(false);
    const patch = layers[layers.length - 1];
    assert.equal(patch.screen_x, 4, "the hotspot at (1, 1)");
    assert.equal(patch.screen_y, 5);
    assert.deepEqual([...patch.pixels.data.subarray(0, 4)], [255, 0, 0, 255], "an opaque red alpha cursor");
    w32(fifo + C.SVGA_FIFO_CURSOR_X * 4, 9);
    w32(fifo + C.SVGA_FIFO_CURSOR_COUNT * 4, 2);
    layers = [];
    cpu.devices.display.request_frame(false);
    assert.equal(layers[0].screen_x, 4, "moving it first restores the picture under its old place");
    assert.equal(layers[0].pixels.data, screen.rgba);
    assert.equal(layers[layers.length - 1].screen_x, 8);
    console.log("PASS: the cursor is drawn over the screen and erased where it was");

    // command buffers: a header at 4 MiB, its commands at 4 MiB + 4 KiB
    const header = 0x400000, commands = 0x401000;
    const command_buffer = (context, flags, ...dwords) => {
        dwords.forEach((d, i) => w32(commands + i * 4, d));
        for(let i = 0; i < 64; i += 4) w32(header + i, 0);
        w32(header + 16, flags); w32(header + 20, dwords.length * 4); w32(header + 24, commands);
        reg(C.SVGA_REG_COMMAND_HIGH, 0);
        reg(C.SVGA_REG_COMMAND_LOW, header | context);
        return [r32(header), r32(header + 4)];
    };
    reg(C.SVGA_REG_IRQMASK, C.SVGA_IRQFLAG_COMMAND_BUFFER | C.SVGA_IRQFLAG_ANY_FENCE);
    io.port_write32(port + 8, 0xFFFFFFFF);
    assert.deepEqual(command_buffer(C.SVGA_CB_CONTEXT_DEVICE, 0, C.SVGA_DC_CMD_START_STOP_CONTEXT, 1, 0), [C.SVGA_CB_STATUS_COMPLETED, 0]);
    assert.deepEqual(command_buffer(0, 0, C.SVGA_CMD_FENCE, 0x4242), [C.SVGA_CB_STATUS_COMPLETED, 0], "a command buffer completes");
    assert.equal(r32(fifo + C.SVGA_FIFO_FENCE * 4), 0x4242, "its fence passed");
    assert.ok(io.port_read32(port + 8) & C.SVGA_IRQFLAG_COMMAND_BUFFER, "and interrupted");
    io.port_write32(port + 8, 0xFFFFFFFF);
    command_buffer(0, C.SVGA_CB_FLAG_NO_IRQ, C.SVGA_CMD_NOP);
    assert.equal(io.port_read32(port + 8) & C.SVGA_IRQFLAG_COMMAND_BUFFER, 0, "SVGA_CB_FLAG_NO_IRQ");
    assert.deepEqual(command_buffer(0, 0, C.SVGA_CMD_NOP, 0x7777, C.SVGA_CMD_NOP), [C.SVGA_CB_STATUS_COMMAND_ERROR, 4],
        "an unknown command: COMMAND_ERROR at its offset");
    console.log("PASS: command buffers");

    // snapshots keep the regions, the screens and the cursor
    const state = await vm.save_state();
    submit(C.SVGA_CMD_DESTROY_SCREEN, 0);
    submit(C.SVGA_CMD_DEFINE_GMR2, 2, 0);
    await vm.restore_state(state);
    assert.deepEqual([...svga.gmrs.regions.get(2)], [0x300, 0x301]);
    assert.deepEqual([...svga.screens.screens.get(0).rgba.subarray(17 * 4, 17 * 4 + 3)], [0x10, 0x20, 0x30 + 17]);
    assert.equal(svga.cursor.width, 2);
    console.log("PASS: snapshots of the 2d-full level");
    await vm.destroy();
}

function pci_read_on(io, reg)
{
    io.port_write32(0xcf8, 0x80000000 | 0x12 << 3 << 8 | reg);
    return io.port_read32(0xcfc) >>> 0;
}
                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/devices/vmware_svga_3d.js                                                          0000755 0000000 0000000 00000042330 00000000000 015722  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The VMware SVGA II adapter's legacy 3D (level vgpu9, svga3d.js), driven
// through the FIFO and command buffers the way vm3d and Mesa's svga driver
// do. The renderer here records the D9WG batches the device sends and
// answers readbacks and queries like src/browser/glbridge/svga_renderer.js:
// texel (x, y) of texture h reads back as BGRA (x, y, h, 0x80).

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const C = await import("../../src/graphics_adapters/vmware_svga/svga_constants.js");
const { d9wg_commands, OP } = await import("../../src/graphics_adapters/vmware_svga/svga3d_d9wg.js");
const { QUERY_REGION_BYTES } = await import("../../src/graphics_adapters/renderer_protocol.js");

const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

// The renderer
const submitted = [];
let queue = [], to_device = null;
const renderer = {
    "post": message => { if(message["type"] === "submit") { submitted.push(message); queue.push(message); } },
    "listen": handler => { to_device = handler; },
};
function run_renderer()
{
    for(const batch of queue.splice(0))
    {
        for(const { opcode, view, at } of d9wg_commands(batch["bytes"]))
        {
            if(opcode === OP.READBACK_SURFACE)
            {
                const texture = view.getUint32(at + 4, true), width = view.getUint32(at + 16, true);
                const first = view.getUint32(at + 24, true), rows = view.getUint32(at + 28, true), pitch = view.getUint32(at + 32, true);
                const id = view.getUint32(at + 44, true);
                const answer = new Uint8Array(16 + rows * pitch);
                new DataView(answer.buffer).setUint32(0, id, true);
                new DataView(answer.buffer).setUint32(4, rows * pitch, true);
                new DataView(answer.buffer).setUint32(12, 1, true);
                for(let r = 0; r < rows; r++) for(let x = 0; x < width; x++)
                {
                    answer.set([x, first + r, texture, 0x80], 16 + r * pitch + x * 4);
                }
                to_device({ "type": "write", "offset": view.getUint32(at + 40, true), "bytes": answer });
            }
            if(opcode === OP.END_QUERY)
            {
                const answer = new Uint32Array([view.getUint32(at + 12, true), 42, 0, 1]);
                to_device({ "type": "write", "offset": view.getUint32(at + 8, true), "bytes": new Uint8Array(answer.buffer) });
            }
        }
        to_device({ "type": "done", "seq": batch["seq"] });
    }
}
let seen = 0;
/** The D9WG commands sent since the last call */
function sent()
{
    const commands = submitted.slice(seen).flatMap(batch => d9wg_commands(batch["bytes"]));
    seen = submitted.length;
    return commands;
}
const u32 = (command, i) => command.view.getUint32(command.at + 4 * i, true);
const f32_bits = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const vm = new V86({
    graphics_adapter: "vmware_svga",
    graphics_adapter_test: { level: "vgpu9", renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321, autostart: true, memory_size: 32 << 20, vram_size: 8 << 20,
    net_device: { type: "none" }, disable_speaker: true, log_level: 0,
});
await new Promise(resolve => vm.add_listener("emulator-ready", resolve));
await vm.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await vm.stop();

const cpu = vm.v86.cpu, io = cpu.io, svga = cpu.devices.graphics_adapter.device["svga"];
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | 0x12 << 3 << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const port = pci_read(0x10) & ~3, fifo = (pci_read(0x18) & ~0xF) >>> 0;
const reg = (index, value) => { io.port_write32(port, index); if(value === undefined) return io.port_read32(port + 1) >>> 0; io.port_write32(port + 1, value); };
const w32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const r32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;

// The device declares 3D and writes its capabilities when the FIFO is set up
assert.ok(reg(C.SVGA_REG_CAPABILITIES) & C.SVGA_CAP_3D, "SVGA_CAP_3D");
reg(C.SVGA_REG_ENABLE, C.SVGA_REG_ENABLE_ENABLE);
const MIN = 0x1000, MAX = 0x10000;
w32(fifo, MIN); w32(fifo + 4, MAX); w32(fifo + 8, MIN); w32(fifo + 12, MIN);
reg(C.SVGA_REG_CONFIG_DONE, 1);
assert.ok(r32(fifo + C.SVGA_FIFO_CAPABILITIES * 4) & C.SVGA_FIFO_CAP_3D_HWVERSION_REVISED);
assert.equal(r32(fifo + C.SVGA_FIFO_3D_HWVERSION_REVISED * 4), C.SVGA3D_HWVERSION_WS8_B1, "what vm3d needs at least");
const caps = fifo + C.SVGA_FIFO_3D_CAPS * 4, record = r32(caps);
assert.equal(r32(caps + 4), C.SVGA3D_FIFO_CAPS_RECORD_DEVCAPS);
assert.ok(record <= C.SVGA_FIFO_3D_CAPS_SIZE - 1, "the record fits");
assert.equal(r32(caps + 4 * record), 0, "an empty record ends the list");
const devcaps = new Map();
for(let i = 2; i < record; i += 2) devcaps.set(r32(caps + 4 * i), r32(caps + 4 * i + 4));
assert.equal(devcaps.get(C.SVGA3D_DEVCAP_3D), 1);
assert.equal(devcaps.get(C.SVGA3D_DEVCAP_VERTEX_SHADER_VERSION), C.SVGA3DVSVERSION_30);
assert.equal(devcaps.get(C.SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION), C.SVGA3DPSVERSION_30);
assert.equal(devcaps.get(C.SVGA3D_DEVCAP_MAX_RENDER_TARGETS), 4);
assert.ok(devcaps.get(C.SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5) & C.SVGA3DFORMAT_OP_OFFSCREEN_RENDERTARGET);
// what VMware's Windows driver asks the backdoor before it has the device
// (it loads as a full WDDM driver only with 3D there)
const backdoor = subcommand => {
    cpu.reg32[0] = 0x564D5868; cpu.reg32[3] = 0; cpu.reg32[1] = subcommand << 16 | 75; cpu.reg32[2] = 0x5658;
    return [io.port_read32(0x5658) >>> 0, cpu.reg32[3] >>> 0];
};
assert.deepEqual(backdoor(0), [reg(C.SVGA_REG_CAPABILITIES), 0x564D5868], "GET_SVGA_CAPABILITIES: the capabilities");
assert.deepEqual(backdoor(2), [C.SVGA3D_HWVERSION_WS8_B1, 0x564D5868], "and the 3D hardware version");
console.log("PASS: level vgpu9 declares 3D: hardware version, devcaps record (" + devcaps.size + " caps)");

let next = MIN;
const submit = (...dwords) => {
    for(const d of dwords) { w32(fifo + next, d); next = next + 4 === MAX ? MIN : next + 4; }
    w32(fifo + 8, next);
    reg(C.SVGA_REG_SYNC, 1);
};
const cmd3d = (id, ...body) => submit(id, body.length * 4, ...body);
const fence = value => submit(C.SVGA_CMD_FENCE, value);
const fence_passed = () => r32(fifo + C.SVGA_FIFO_FENCE * 4);
const find = (commands, opcode) => commands.filter(c => c.opcode === opcode);

// GMR 1: two pages at 2 MiB; screen 0: 32x32
w32(0x100000, 0x200); w32(0x100004, 2); w32(0x100008, 0); w32(0x10000C, 0);
reg(C.SVGA_REG_GMR_ID, 1);
reg(C.SVGA_REG_GMR_DESCRIPTOR, 0x100);
submit(C.SVGA_CMD_DEFINE_SCREEN, 44, 0, C.SVGA_SCREEN_MUST_BE_SET | C.SVGA_SCREEN_IS_PRIMARY, 32, 32, 0, 0, C.SVGA_GMR_NULL, 0, 0, 0);

// Surfaces: a 16x16 render target, a vertex buffer, a depth buffer
const NO_MIPS = [0, 0, 0, 0, 0];
cmd3d(C.SVGA_3D_CMD_SURFACE_DEFINE, 1, C.SVGA3D_SURFACE_HINT_RENDERTARGET, C.SVGA3D_X8R8G8B8, 1, ...NO_MIPS, 16, 16, 1);
cmd3d(C.SVGA_3D_CMD_SURFACE_DEFINE, 2, C.SVGA3D_SURFACE_HINT_VERTEXBUFFER, C.SVGA3D_BUFFER, 1, ...NO_MIPS, 36, 1, 1);
cmd3d(C.SVGA_3D_CMD_SURFACE_DEFINE, 3, C.SVGA3D_SURFACE_HINT_DEPTHSTENCIL, C.SVGA3D_Z_D24S8, 1, ...NO_MIPS, 16, 16, 1);
// three vertices into the buffer, through GMR 1
const vertices = [0, 0, 0, 1, 0, 0, 0, 1, 0];
vertices.forEach((v, i) => w32(0x200000 + 4 * i, f32_bits(v)));
cmd3d(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0, 36, 2, 0, 0, C.SVGA3D_WRITE_HOST_VRAM, 0, 0, 0, 36, 1, 1, 0, 0, 0, 12, 36, 0);
fence(1);
assert.equal(fence_passed(), 0, "the fence waits for the renderer");
run_renderer();
assert.equal(fence_passed(), 1, "and passes when it has run the batch");
let commands = sent();
const textures = find(commands, OP.CREATE_TEXTURE_2D);
assert.equal(textures.length, 2);
const [target, depth] = [u32(textures[0], 1), u32(textures[1], 1)];
assert.deepEqual([u32(textures[0], 2), u32(textures[0], 3), u32(textures[0], 5), u32(textures[0], 6)], [16, 16, 22, 1],
    "16x16 D3DFMT_X8R8G8B8, D3DUSAGE_RENDERTARGET");
assert.deepEqual([u32(textures[1], 5), u32(textures[1], 6)], [75, 2], "D3DFMT_D24S8, D3DUSAGE_DEPTHSTENCIL");
assert.equal(find(commands, OP.CREATE_BUFFER).length, 0, "a buffer becomes a D9WG buffer when a draw uses it");
console.log("PASS: surfaces, and fences after GPU work");

// A context, its state and a draw
const CID = 7;
cmd3d(C.SVGA_3D_CMD_CONTEXT_DEFINE, CID);
cmd3d(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_COLOR0, 1, 0, 0);
cmd3d(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_DEPTH, 3, 0, 0);
cmd3d(C.SVGA_3D_CMD_SETVIEWPORT, CID, 0, 0, 16, 16);
cmd3d(C.SVGA_3D_CMD_SETRENDERSTATE, CID, C.SVGA3D_RS_CULLMODE, C.SVGA3D_FACE_FRONT, C.SVGA3D_RS_FRONTWINDING, C.SVGA3D_FRONTWINDING_CCW,
    C.SVGA3D_RS_SRCBLEND, C.SVGA3D_BLENDOP_BLENDFACTOR, C.SVGA3D_RS_ALPHAREF, f32_bits(0.5), C.SVGA3D_RS_ZENABLE, 1);
cmd3d(C.SVGA_3D_CMD_SETTEXTURESTATE, CID, 0, C.SVGA3D_TS_BIND_TEXTURE, 1, 0, C.SVGA3D_TS_ADDRESSU, C.SVGA3D_TEX_ADDRESS_EDGE,
    0, C.SVGA3D_TS_COLORARG1, C.SVGA3D_TA_TEXTURE | C.SVGA3D_TM_ONE_MINUS, 0, C.SVGA3D_TS_COLOROP, C.SVGA3D_TC_MODULATE2X);
const SHADER = [0xFFFE0300, 0x0000FFFF];
cmd3d(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 5, C.SVGA3D_SHADERTYPE_VS, ...SHADER);
cmd3d(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_VS, 5);
cmd3d(C.SVGA_3D_CMD_SET_SHADER_CONST, CID, 3, C.SVGA3D_SHADERTYPE_VS, C.SVGA3D_CONST_TYPE_FLOAT, ...[1, 2, 3, 4].map(f32_bits));
cmd3d(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 1, 1,
    C.SVGA3D_DECLTYPE_FLOAT3, C.SVGA3D_DECLMETHOD_DEFAULT, C.SVGA3D_DECLUSAGE_POSITION, 0, 2, 0, 12, 0, 2,
    C.SVGA3D_PRIMITIVE_TRIANGLELIST, 1, 0xFFFFFFFF, 0, 0, 0, 0);
fence(2);
run_renderer();
assert.equal(fence_passed(), 2);
commands = sent();
const rt = find(commands, OP.SET_RENDER_TARGET)[0];
const device = u32(rt, 0);
assert.deepEqual([u32(rt, 1), u32(rt, 2)], [0, target], "COLOR0 is the render target's texture");
assert.deepEqual([1, 2, 3, 4].map(i => u32(find(commands, OP.SET_DEPTH_STENCIL_SURFACE_LEVEL)[0], i)), [depth, 0, 16, 16]);
const states = new Map(find(commands, OP.SET_RENDER_STATE).map(c => [u32(c, 1), u32(c, 2)]));
assert.equal(states.get(22), 3, "culling the front with counterclockwise fronts is D3DCULL_CCW");
assert.equal(states.get(19), 14, "SVGA3D_BLENDOP_BLENDFACTOR is D3DBLEND_BLENDFACTOR");
assert.equal(states.get(24), 128, "the alpha reference is a float in SVGA3D");
assert.equal(states.get(7), 1);
assert.deepEqual(find(commands, OP.SET_TEXTURE).map(c => [u32(c, 1), u32(c, 2)]), [[0, target]]);
assert.deepEqual(find(commands, OP.SET_SAMPLER_STATE).map(c => [u32(c, 2), u32(c, 3)]), [[1, 3]], "ADDRESS_EDGE is D3D's clamp");
assert.deepEqual(find(commands, OP.SET_TEXTURE_STAGE_STATE).map(c => [u32(c, 2), u32(c, 3)]), [[2, 0x12], [1, 5]],
    "TEXTURE|ONE_MINUS is D3DTA_TEXTURE|D3DTA_COMPLEMENT, MODULATE2X is 5");
const shader = find(commands, OP.CREATE_VERTEX_SHADER)[0];
assert.deepEqual([u32(shader, 0), u32(shader, 1), u32(shader, 2)], [device, 0x40000001, 2]);
assert.deepEqual([...new Uint32Array(rt.view.buffer.slice(rt.view.byteOffset + u32(shader, 3), rt.view.byteOffset + u32(shader, 3) + 8))], SHADER);
assert.equal(u32(find(commands, OP.SET_VERTEX_SHADER)[0], 1), 0x40000001);
const constant = find(commands, OP.SET_VERTEX_SHADER_CONSTANT_F)[0];
assert.deepEqual([u32(constant, 1), u32(constant, 2)], [3, 1]);
assert.deepEqual([...new Float32Array(constant.view.buffer.slice(constant.view.byteOffset + u32(constant, 3), constant.view.byteOffset + u32(constant, 3) + 16))], [1, 2, 3, 4]);
const buffer = find(commands, OP.CREATE_BUFFER)[0];
assert.deepEqual([u32(buffer, 2), u32(buffer, 3)], [1, 36], "a 36-byte vertex buffer");
const upload = find(commands, OP.UPDATE_BUFFER)[0];
assert.deepEqual([...new Float32Array(upload.view.buffer.slice(upload.view.byteOffset + u32(upload, 3), upload.view.byteOffset + u32(upload, 3) + 36))], vertices,
    "filled with what SURFACE_DMA brought");
const declaration = find(commands, OP.CREATE_VERTEX_DECLARATION)[0];
assert.equal(u32(declaration, 2), 1);
assert.deepEqual([u32(declaration, 4), u32(declaration, 5)], [0, C.SVGA3D_DECLTYPE_FLOAT3 | 0 << 8 | C.SVGA3D_DECLUSAGE_POSITION << 16],
    "stream 0, offset 0, FLOAT3 POSITION");
assert.deepEqual([1, 2, 3, 4].map(i => u32(find(commands, OP.SET_STREAM_SOURCE)[0], i)), [0, u32(buffer, 1), 12, 0]);
assert.deepEqual([1, 2, 3].map(i => u32(find(commands, OP.DRAW_PRIMITIVE)[0], i)), [4, 0, 1], "D3DPT_TRIANGLELIST, from 0, one");
console.log("PASS: a context's state, shaders, constants, vertex streams and a draw");

// Readbacks: SURFACE_DMA into the guest, and presenting to the screen
cmd3d(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0x100, 64, 1, 0, 0, C.SVGA3D_READ_HOST_VRAM, 2, 3, 0, 4, 2, 1, 0, 0, 0);
cmd3d(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 16, 16, 0, 4, 4, 20, 20);
fence(3);
const screen = svga.screens.screens.get(0);
assert.deepEqual([...screen.rgba.subarray((10 * 32 + 9) * 4, (10 * 32 + 9) * 4 + 4)], [0, 0, 0, 0], "not before the renderer has run it");
run_renderer();
assert.equal(fence_passed(), 3);
assert.deepEqual([0, 1, 2, 3].map(i => cpu.read8(0x200100 + 64 + 4 + i)), [3, 4, target, 0x80],
    "texel (3, 4) of the box at (2, 3) is in the guest, one row and one texel in");
assert.deepEqual([...screen.rgba.subarray((10 * 32 + 9) * 4, (10 * 32 + 9) * 4 + 4)], [target, 6, 5, 255],
    "texel (5, 6) on the screen at (9, 10), BGRA to RGBA");
// scaled: the 16x16 surface into 8x8
cmd3d(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 16, 16, 0, 0, 0, 8, 8);
fence(4);
run_renderer();
assert.deepEqual([...screen.rgba.subarray((3 * 32 + 1) * 4, (3 * 32 + 1) * 4 + 3)], [target, 6, 2], "scaled down");
console.log("PASS: readbacks into guest memory and onto the screen");

// An occlusion query: pending, then the count
cmd3d(C.SVGA_3D_CMD_BEGIN_QUERY, CID, C.SVGA3D_QUERYTYPE_OCCLUSION);
cmd3d(C.SVGA_3D_CMD_END_QUERY, CID, C.SVGA3D_QUERYTYPE_OCCLUSION, 1, 0x400);
assert.deepEqual([r32(0x200400), r32(0x200404)], [12, C.SVGA3D_QUERYSTATE_PENDING]);
fence(5);
run_renderer();
assert.deepEqual([r32(0x200400), r32(0x200404), r32(0x200408)], [12, C.SVGA3D_QUERYSTATE_SUCCEEDED, 42]);
console.log("PASS: occlusion queries");

// A command buffer with 3D in it completes after the GPU work
const header = 0x400000, body = 0x401000;
const clear = [C.SVGA_3D_CMD_CLEAR, 20, CID, C.SVGA3D_CLEAR_COLOR, 0xFF00FF00, 0, 0];
clear.forEach((d, i) => w32(body + i * 4, d));
for(let i = 0; i < 64; i += 4) w32(header + i, 0);
w32(header + 20, clear.length * 4); w32(header + 24, body);
reg(C.SVGA_REG_COMMAND_HIGH, 0);
reg(C.SVGA_REG_COMMAND_LOW, header);
assert.equal(r32(header), C.SVGA_CB_STATUS_NONE, "not complete while the renderer has not run it");
run_renderer();
assert.equal(r32(header), C.SVGA_CB_STATUS_COMPLETED);
const clears = find(sent(), OP.CLEAR);
assert.deepEqual([0, 1, 2, 5].map(i => u32(clears[0], i)), [device, 1, 0xFF00FF00, 0]);
console.log("PASS: command buffers with 3D complete after it");

// Snapshots: the GPU's contents are read back first, and a restore makes the
// objects again in a fresh renderer, filled and with their state
sent();
const saving = vm.save_state();
// (the readbacks of the save need the renderer)
await new Promise(resolve => setTimeout(resolve, 0));
run_renderer();
const state = await saving;
commands = sent();
assert.ok(find(commands, OP.READBACK_SURFACE).length >= 1, "the save read the render target back");
await vm.restore_state(state);
run_renderer();
commands = sent();
const created = find(commands, OP.CREATE_TEXTURE_2D);
assert.equal(created.length, 2, "both textures again");
const restored_target = u32(created[0], 1);
const filled = find(commands, OP.UPDATE_TEXTURE).find(c => u32(c, 0) === restored_target);
assert.ok(filled, "the render target is filled again");
const texels = new Uint8Array(filled.view.buffer.slice(filled.view.byteOffset + u32(filled, 11), filled.view.byteOffset + u32(filled, 11) + 16 * 16 * 4));
assert.deepEqual([...texels.subarray((6 * 16 + 5) * 4, (6 * 16 + 5) * 4 + 3)], [5, 6, target & 0xFF], "with what was read back");
const restored_states = new Map(find(commands, OP.SET_RENDER_STATE).map(c => [u32(c, 1), u32(c, 2)]));
assert.equal(restored_states.get(22), 3, "the context's render states are set again");
assert.equal(find(commands, OP.CREATE_VERTEX_SHADER).length, 1, "and its shaders defined");
assert.equal(u32(find(commands, OP.SET_RENDER_TARGET)[0], 2), restored_target, "its target is the new texture");
// the buffer's bytes are in the snapshot itself
cmd3d(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 1, 1,
    C.SVGA3D_DECLTYPE_FLOAT3, C.SVGA3D_DECLMETHOD_DEFAULT, C.SVGA3D_DECLUSAGE_POSITION, 0, 2, 0, 12, 0, 2,
    C.SVGA3D_PRIMITIVE_TRIANGLELIST, 1, 0xFFFFFFFF, 0, 0, 0, 0);
fence(6);
run_renderer();
const again = find(sent(), OP.UPDATE_BUFFER)[0];
assert.deepEqual([...new Float32Array(again.view.buffer.slice(again.view.byteOffset + u32(again, 3), again.view.byteOffset + u32(again, 3) + 36))], vertices);
console.log("PASS: snapshots of the 3D level");

await vm.destroy();
                                                                                                                                                                                                                                                                                                        source/v64/tests/devices/vmware_svga_gb.js                                                          0000755 0000000 0000000 00000046424 00000000000 016014  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The VMware SVGA II adapter's guest-backed objects (level gb9, svga_gb.js
// and svga3d.js): registers, MOBs and their page tables, object tables, GB
// surfaces moved between MOBs and the GPU, GB shaders, queries and fences
// into MOBs, screen targets, the cursor in a MOB, command buffers in MOBs
// and snapshots. The renderer is the recording one of vmware_svga_3d.js:
// texel (x, y) of texture h reads back as BGRA (x, y, h, 0x80).

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const C = await import("../../src/graphics_adapters/vmware_svga/svga_constants.js");
const { d9wg_commands, OP } = await import("../../src/graphics_adapters/vmware_svga/svga3d_d9wg.js");

const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

const submitted = [];
let queue = [], to_device = null;
const renderer = {
    "post": message => { if(message["type"] === "submit") { submitted.push(message); queue.push(message); } },
    "listen": handler => { to_device = handler; },
};
function run_renderer()
{
    for(const batch of queue.splice(0))
    {
        for(const { opcode, view, at } of d9wg_commands(batch["bytes"]))
        {
            if(opcode === OP.READBACK_SURFACE)
            {
                const texture = view.getUint32(at + 4, true), width = view.getUint32(at + 16, true);
                const first = view.getUint32(at + 24, true), rows = view.getUint32(at + 28, true), pitch = view.getUint32(at + 32, true);
                const id = view.getUint32(at + 44, true);
                const answer = new Uint8Array(16 + rows * pitch);
                new DataView(answer.buffer).setUint32(0, id, true);
                new DataView(answer.buffer).setUint32(4, rows * pitch, true);
                new DataView(answer.buffer).setUint32(12, 1, true);
                for(let r = 0; r < rows; r++) for(let x = 0; x < width; x++)
                {
                    answer.set([x, first + r, texture, 0x80], 16 + r * pitch + x * 4);
                }
                to_device({ "type": "write", "offset": view.getUint32(at + 40, true), "bytes": answer });
            }
            if(opcode === OP.END_QUERY)
            {
                const answer = new Uint32Array([view.getUint32(at + 12, true), 42, 0, 1]);
                to_device({ "type": "write", "offset": view.getUint32(at + 8, true), "bytes": new Uint8Array(answer.buffer) });
            }
        }
        to_device({ "type": "done", "seq": batch["seq"] });
    }
}
let seen = 0;
function sent()
{
    const commands = submitted.slice(seen).flatMap(batch => d9wg_commands(batch["bytes"]));
    seen = submitted.length;
    return commands;
}
const u32 = (command, i) => command.view.getUint32(command.at + 4 * i, true);
const payload = (command, offset, length) => new Uint8Array(command.view.buffer.slice(command.view.byteOffset + offset, command.view.byteOffset + offset + length));
const find = (commands, opcode) => commands.filter(c => c.opcode === opcode);

const vm = new V86({
    graphics_adapter: "vmware_svga",
    graphics_adapter_test: { level: "gb9", renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321, autostart: true, memory_size: 32 << 20, vram_size: 8 << 20,
    net_device: { type: "none" }, disable_speaker: true, log_level: 0,
});
await new Promise(resolve => vm.add_listener("emulator-ready", resolve));
await vm.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await vm.stop();

const cpu = vm.v86.cpu, io = cpu.io, svga = cpu.devices.graphics_adapter.device["svga"];
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | 0x12 << 3 << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const port = pci_read(0x10) & ~3, fifo = (pci_read(0x18) & ~0xF) >>> 0;
const reg = (index, value) => { io.port_write32(port, index); if(value === undefined) return io.port_read32(port + 1) >>> 0; io.port_write32(port + 1, value); };
const w32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const r32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const PAGE = 4096;

// Registers: what vmwgfx and vm3d read before they use GB objects
const caps = reg(C.SVGA_REG_CAPABILITIES);
assert.ok(caps & C.SVGA_CAP_GBOBJECTS && caps & C.SVGA_CAP_3D && caps & C.SVGA_CAP_CAP2_REGISTER);
const cap2 = reg(C.SVGA_REG_CAP2);
assert.ok(cap2 & C.SVGA_CAP2_GROW_OTABLE && cap2 & C.SVGA_CAP2_OTABLE_PTDEPTH_2 && cap2 & C.SVGA_CAP2_CURSOR_MOB);
assert.ok(reg(C.SVGA_REG_MOB_MAX_SIZE) >= 128 << 20);
assert.ok(reg(C.SVGA_REG_GBOBJECT_MEM_SIZE_KB) > 0 && reg(C.SVGA_REG_SUGGESTED_GBOBJECT_MEM_SIZE_KB) > 0);
assert.ok(reg(C.SVGA_REG_SCREENTARGET_MAX_WIDTH) >= 1920 && reg(C.SVGA_REG_SCREENTARGET_MAX_HEIGHT) >= 1080);
assert.equal(reg(C.SVGA_REG_MAX_PRIMARY_MEM), 8 << 20);
const devcap = index => { reg(C.SVGA_REG_DEV_CAP, index); return reg(C.SVGA_REG_DEV_CAP); };
assert.equal(devcap(C.SVGA3D_DEVCAP_3D), 1, "devcaps through SVGA_REG_DEV_CAP");
assert.equal(devcap(C.SVGA3D_DEVCAP_VERTEX_SHADER_VERSION), C.SVGA3DVSVERSION_30);
assert.equal(devcap(C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH), 8192);
assert.equal(devcap(C.SVGA3D_DEVCAP_DXCONTEXT), 0, "no DX at gb9");
reg(C.SVGA_REG_GUEST_DRIVER_ID, C.SVGA_REG_GUEST_DRIVER_ID_LINUX);
reg(C.SVGA_REG_GUEST_DRIVER_ID, 0xFFFFFFFF);
assert.equal(reg(C.SVGA_REG_GUEST_DRIVER_ID), C.SVGA_REG_GUEST_DRIVER_ID_LINUX, "SUBMIT ends the list, it is not an id");
console.log("PASS: level gb9's registers: GBOBJECTS, CAP2, devcaps through DEV_CAP, MOB and screen target limits");

reg(C.SVGA_REG_ENABLE, C.SVGA_REG_ENABLE_ENABLE);
const MIN = 0x1000, MAX = 0x10000;
w32(fifo, MIN); w32(fifo + 4, MAX); w32(fifo + 8, MIN); w32(fifo + 12, MIN);
reg(C.SVGA_REG_CONFIG_DONE, 1);
let next = MIN;
const submit = (...dwords) => {
    for(const d of dwords) { w32(fifo + next, d); next = next + 4 === MAX ? MIN : next + 4; }
    w32(fifo + 8, next);
    reg(C.SVGA_REG_SYNC, 1);
};
const cmd3d = (id, ...body) => submit(id, body.length * 4, ...body);
const fence = value => submit(C.SVGA_CMD_FENCE, value);
const fence_passed = () => r32(fifo + C.SVGA_FIFO_FENCE * 4);
const errors = () => svga.stats.errors;

// Object tables: the MOB table is one page (PT_0); the surface table two
// pages through a one-level page table of 64-bit entries
const MOB_TABLE = 0x300000, SURFACE_TABLE_PT = 0x301000;
w32(SURFACE_TABLE_PT, 0x308); w32(SURFACE_TABLE_PT + 4, 0); w32(SURFACE_TABLE_PT + 8, 0x30A); w32(SURFACE_TABLE_PT + 12, 0);
cmd3d(C.SVGA_3D_CMD_SET_OTABLE_BASE64, C.SVGA_OTABLE_MOB, MOB_TABLE / PAGE, 0, PAGE, 0, C.SVGA3D_MOBFMT_PT_0);
cmd3d(C.SVGA_3D_CMD_SET_OTABLE_BASE64, C.SVGA_OTABLE_SURFACE, SURFACE_TABLE_PT / PAGE, 0, 2 * PAGE, 0, C.SVGA3D_MOBFMT_PT64_1);
for(const type of [C.SVGA_OTABLE_CONTEXT, C.SVGA_OTABLE_SHADER, C.SVGA_OTABLE_SCREENTARGET])
{
    cmd3d(C.SVGA_3D_CMD_SET_OTABLE_BASE64, type, (0x302000 + type * PAGE) / PAGE, 0, PAGE, 0, C.SVGA3D_MOBFMT_PT_0);
}

// MOB 1: two pages that are not next to each other, through a page table
// of 32-bit entries; MOB 2: a range of eight pages
const MOB1_PT = 0x310000;
w32(MOB1_PT, 0x320); w32(MOB1_PT + 4, 0x325);
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_MOB64, 1, C.SVGA3D_MOBFMT_PT_1, MOB1_PT / PAGE, 0, 2 * PAGE);
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_MOB64, 2, C.SVGA3D_MOBFMT_RANGE, 0x330, 0, 8 * PAGE);
assert.equal(errors(), 0);
w32(0x325000 + 8, 0xC0FFEE);
assert.equal(svga.mobs.read32(1, PAGE + 8), 0xC0FFEE, "MOB 1's second page is the table's second entry");
assert.deepEqual([0, 1, 2, 3].map(i => r32(MOB_TABLE + 16 + 4 * i)), [C.SVGA3D_MOBFMT_PT_1, 2 * PAGE, MOB1_PT / PAGE, 0],
    "the device writes the MOB's entry");
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_MOB64, 9, 77, 0, 0, PAGE);
assert.equal(errors(), 1, "an unknown page table format is an error");
console.log("PASS: object tables and MOBs: page tables of each depth, entries written by the device");

// A GB surface: 16x16 X8R8G8B8 in MOB 2, filled by the guest, then updated
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, 5, C.SVGA3D_SURFACE_HINT_RENDERTARGET, C.SVGA3D_X8R8G8B8, 1, 0, 0, 16, 16, 1, 1, 0);
cmd3d(C.SVGA_3D_CMD_BIND_GB_SURFACE, 5, 2);
assert.deepEqual([0, 5, 6, 8].map(i => r32(0x308000 + 5 * 64 + 4 * i)), [C.SVGA3D_X8R8G8B8, 16, 16, 2],
    "the surface's entry, in the table's first page: format, size, its MOB");
for(let y = 0; y < 16; y++) for(let x = 0; x < 16; x++) w32(0x330000 + y * 64 + x * 4, 0xFF000000 | y << 8 | x);
cmd3d(C.SVGA_3D_CMD_UPDATE_GB_SURFACE, 5);
fence(1);
run_renderer();
assert.equal(fence_passed(), 1);
let commands = sent();
const texture = u32(find(commands, OP.CREATE_TEXTURE_2D)[0], 1);
const upload = find(commands, OP.UPDATE_TEXTURE)[0];
assert.deepEqual([0, 5, 6, 8].map(i => u32(upload, i)), [texture, 16, 16, 64]);
const texels = payload(upload, u32(upload, 11), 16 * 64);
assert.deepEqual([...texels.subarray(3 * 64 + 5 * 4, 3 * 64 + 5 * 4 + 4)], [5, 3, 0, 0xFF], "texel (5, 3) from the MOB");

// part of it back into the MOB: what the GPU has
cmd3d(C.SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL, 5, 0, 0, 4, 2, 0, 8, 4, 1, 0);
fence(2);
assert.equal(r32(0x330000 + 2 * 64 + 4 * 4), 0xFF000204, "not before the renderer has it");
run_renderer();
assert.equal(fence_passed(), 2);
assert.equal(r32(0x330000 + 2 * 64 + 4 * 4), (0x80 << 24 | texture << 16 | 2 << 8 | 4) >>> 0, "readback into the MOB");
assert.equal(r32(0x330000 + 2 * 64 + 12 * 4), 0xFF00020C, "outside of the box, the MOB keeps its own");
console.log("PASS: GB surfaces: UPDATE from the MOB, READBACK into it");

// GB shaders: bytecode in a MOB, used by any context
const SHADER = [0xFFFE0300, 0x0000FFFF];
w32(0x331000 + 0x40, SHADER[0]); w32(0x331000 + 0x44, SHADER[1]);
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_SHADER, 3, C.SVGA3D_SHADERTYPE_VS, 8);
cmd3d(C.SVGA_3D_CMD_BIND_GB_SHADER, 3, 2, PAGE + 0x40);
const CID = 4;
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_CONTEXT, CID);
cmd3d(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_VS, 3);
cmd3d(C.SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE, CID, 2, C.SVGA3D_SHADERTYPE_PS, C.SVGA3D_CONST_TYPE_BOOL, 1, 0, 1);
fence(3);
run_renderer();
commands = sent();
const vs = find(commands, OP.CREATE_VERTEX_SHADER)[0];
assert.deepEqual([...new Uint32Array(payload(vs, u32(vs, 3), 8).buffer)], SHADER, "the bytecode from the MOB");
assert.equal(u32(find(commands, OP.SET_VERTEX_SHADER)[0], 1), u32(vs, 1));
const bools = find(commands, OP.SET_PIXEL_SHADER_CONSTANT_B)[0];
assert.deepEqual([u32(bools, 1), u32(bools, 2)], [2, 3]);
assert.deepEqual([...new Uint32Array(payload(bools, u32(bools, 3), 12).buffer)], [1, 0, 1], "one dword per bool inline");
assert.deepEqual([0, 1, 2, 3].map(i => r32(0x305000 + 3 * 16 + 4 * i)), [C.SVGA3D_SHADERTYPE_VS, 8, PAGE + 0x40, 2]);
console.log("PASS: GB shaders from MOBs, inline shader constants");

// Queries and fences into MOBs
cmd3d(C.SVGA_3D_CMD_BEGIN_GB_QUERY, CID, C.SVGA3D_QUERYTYPE_OCCLUSION);
cmd3d(C.SVGA_3D_CMD_END_GB_QUERY, CID, C.SVGA3D_QUERYTYPE_OCCLUSION, 2, 2 * PAGE + 0x10);
cmd3d(C.SVGA_3D_CMD_WAIT_FOR_GB_QUERY, CID, C.SVGA3D_QUERYTYPE_OCCLUSION, 2, 2 * PAGE + 0x10);
cmd3d(C.SVGA_3D_CMD_GB_MOB_FENCE, 77, 2, 2 * PAGE + 0x20);
assert.equal(r32(0x332000 + 0x14), C.SVGA3D_QUERYSTATE_PENDING);
assert.equal(r32(0x332000 + 0x20), 0, "the MOB fence waits for the work before it");
run_renderer();
assert.equal(r32(0x332000 + 0x20), 77);
assert.deepEqual([0, 1, 2].map(i => r32(0x332000 + 0x10 + 4 * i)), [12, C.SVGA3D_QUERYSTATE_SUCCEEDED, 42]);
assert.equal(r32(0x332000 + 0x20), 77);
console.log("PASS: GB queries and MOB fences");

// Screen targets: an image the GPU has nothing newer of comes from its MOB
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_SCREENTARGET, 0, 16, 16, 0, 0, C.SVGA_STFLAG_PRIMARY, 96);
cmd3d(C.SVGA_3D_CMD_BIND_GB_SCREENTARGET, 0, 5, 0, 0);
cmd3d(C.SVGA_3D_CMD_UPDATE_GB_SURFACE, 5);
cmd3d(C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET, 0, 0, 0, 16, 16);
const screen = svga.screens.screens.get(0);
assert.ok(screen && screen.width === 16);
const at = (x, y) => [...screen.rgba.subarray((y * 16 + x) * 4, (y * 16 + x) * 4 + 4)];
assert.deepEqual(at(9, 2), [texture, 2, 9, 255], "from the MOB at once (where the readback above left the GPU's texel (9, 2))");
assert.deepEqual(at(1, 7), [0, 7, 1, 255]);
assert.deepEqual([0, 1, 2, 3].map(i => r32(0x306000 + 4 * i)), [5, 0, 0, 16], "the screen target's entry");
// once drawn into, the GPU's copy is newer: the update reads it back
cmd3d(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_COLOR0, 5, 0, 0);
cmd3d(C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET, 0, 0, 0, 16, 16);
fence(4);
assert.deepEqual(at(1, 7), [0, 7, 1, 255], "not yet");
run_renderer();
assert.deepEqual(at(1, 7), [texture, 7, 1, 255], "from the GPU");
console.log("PASS: screen targets, from the MOB or from the GPU");

// The cursor in a MOB: SVGAGBCursorHeader, then the image
const CURSOR = 0x333000;
[C.SVGA_ALPHA_CURSOR, 1, 2, 4, 4, 0, 0, 64].forEach((v, i) => w32(CURSOR + 4 * i, v));
for(let i = 0; i < 16; i++) w32(CURSOR + 32 + 4 * i, 0xFF0000FF);
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_MOB64, 3, C.SVGA3D_MOBFMT_RANGE, CURSOR / PAGE, 0, PAGE);
reg(C.SVGA_REG_CURSOR_MOBID, 3);
assert.deepEqual([svga.cursor.width, svga.cursor.height, svga.cursor.hot_x, svga.cursor.hot_y, svga.cursor.alpha], [4, 4, 1, 2, true]);
console.log("PASS: the cursor in a MOB");

// A command buffer in a MOB
const header = 0x400000;
const body = [C.SVGA_CMD_FENCE, 9];
body.forEach((v, i) => w32(0x334000 + 0x80 + 4 * i, v));
cmd3d(C.SVGA_3D_CMD_DEFINE_GB_MOB64, 4, C.SVGA3D_MOBFMT_RANGE, 0x334, 0, PAGE);
for(let i = 0; i < 16; i++) w32(header + 4 * i, 0);
w32(header + 16, C.SVGA_CB_FLAG_MOB); w32(header + 20, 8); w32(header + 24, 4); w32(header + 28, 0x80);
reg(C.SVGA_REG_COMMAND_HIGH, 0);
reg(C.SVGA_REG_COMMAND_LOW, header | C.SVGA_CB_CONTEXT_0);
run_renderer();
assert.equal(r32(header), C.SVGA_CB_STATUS_COMPLETED);
assert.equal(fence_passed(), 9);
console.log("PASS: command buffers in MOBs");

// Snapshots: MOBs, tables, the surface's binding and contents, shaders, targets
const saving = vm.save_state();
await new Promise(resolve => setTimeout(resolve, 0));
run_renderer();
const state = await saving;
sent();
await vm.restore_state(state);
run_renderer();
commands = sent();
assert.equal(svga.mobs.read32(1, PAGE + 8), 0xC0FFEE, "MOB 1 is there again");
const restored = svga.svga3d.surfaces.get(5);
assert.ok(restored && restored.mob === 2, "the surface, bound to its MOB");
const recreated = find(commands, OP.CREATE_VERTEX_SHADER)[0];
assert.deepEqual([...new Uint32Array(payload(recreated, u32(recreated, 3), 8).buffer)], SHADER, "the GB shader");
assert.ok(svga.svga3d.targets.get(0).image, "the screen target, bound");
cmd3d(C.SVGA_3D_CMD_UPDATE_GB_SCREENTARGET, 0, 0, 0, 16, 16);
fence(10);
run_renderer();
assert.equal(fence_passed(), 10);
assert.equal(errors(), 1);
console.log("PASS: snapshots of the gb9 level");

// The device's ABI: a restore declares the level and the capabilities the
// snapshot's device declared (its driver read them at boot), not what this
// version would choose or what its tables say now
const { LEVELS } = await import("../../src/graphics_adapters/vmware_svga/svga_device.js");
const gb9_caps = reg(C.SVGA_REG_CAPABILITIES);
reg(C.SVGA_REG_DEV_CAP, C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH);
const declared_width = reg(C.SVGA_REG_DEV_CAP);
const saving2 = vm.save_state();
await new Promise(resolve => setTimeout(resolve, 0));
run_renderer();
const state2 = await saving2;
// as if this machine had chosen another level, and the table had changed since
svga.level = "vgpu9";
svga.caps = LEVELS["vgpu9"].caps;
svga.configure_objects();
svga.devcaps.set(C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH, 1);
assert.equal(svga.mobs, null, "no MOBs at vgpu9");
await vm.restore_state(state2);
run_renderer();
assert.equal(svga.level, "gb9", "the snapshot's level");
assert.equal(reg(C.SVGA_REG_CAPABILITIES), gb9_caps, "its capabilities");
reg(C.SVGA_REG_DEV_CAP, C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH);
assert.equal(reg(C.SVGA_REG_DEV_CAP), declared_width, "the devcap value it declared");
assert.equal(svga.mobs.read32(1, PAGE + 8), 0xC0FFEE, "and its MOBs");
console.log("PASS: a restore declares the snapshot's level and capabilities");

// dx10.1 is dx10 and what shader model 4.1 adds; dx10 itself is unchanged
const { DX10_DEVCAPS, DX10_1_DEVCAPS } = await import("../../src/graphics_adapters/vmware_svga/svga3d_tables.js");
assert.equal(LEVELS["dx10.1"].caps, LEVELS["dx10"].caps);
assert.equal(LEVELS["dx10.1"].fifo_caps, LEVELS["dx10"].fifo_caps);
assert.equal(LEVELS["dx10.1"].cap2, LEVELS["dx10"].cap2 | C.SVGA_CAP2_DX2, "Linux's vmwgfx wants DX2 for SM4.1");
assert.ok(!(LEVELS["dx10"].cap2 & C.SVGA_CAP2_DX2));
const dx10_devcaps = new Map(DX10_DEVCAPS), dx10_1_devcaps = new Map(DX10_1_DEVCAPS);
// (a devcap dx10 does not list reads as 0)
assert.ok([...dx10_devcaps.keys()].every(index => dx10_1_devcaps.has(index)));
for(const [index, value] of dx10_1_devcaps)
{
    const old = dx10_devcaps.get(index) || 0;
    assert.equal((value & old) >>> 0, old >>> 0, "dx10.1 only adds to devcap " + index);
}
assert.equal(dx10_devcaps.get(C.SVGA3D_DEVCAP_SM41), 0);
assert.equal(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_SM41), 1);
assert.equal(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_NV12), C.SVGA3D_DXFMT_SUPPORTED);
// 4x multisampling of every target format (GX supersamples), where dx10 had WebGPU's formats only
assert.ok(!(dx10_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_R32G32B32A32_FLOAT) & C.SVGA3D_DXFMT_MULTISAMPLE));
assert.ok(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_R32G32B32A32_FLOAT) & C.SVGA3D_DXFMT_MULTISAMPLE);
assert.ok(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_R16G16_UNORM) & C.SVGA3D_DXFMT_MULTISAMPLE);
assert.ok(!(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_BC1_UNORM) & C.SVGA3D_DXFMT_MULTISAMPLE));
// B8G8R8X8 vertices and XR_BIAS surfaces from dx10.1 on
assert.ok(!(dx10_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM) & C.SVGA3D_DXFMT_DX_VERTEX_BUFFER));
assert.ok(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM) & C.SVGA3D_DXFMT_DX_VERTEX_BUFFER);
assert.ok(!dx10_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_R10G10B10_XR_BIAS_A2_UNORM));
assert.ok(dx10_1_devcaps.get(C.SVGA3D_DEVCAP_DXFMT_R10G10B10_XR_BIAS_A2_UNORM) & C.SVGA3D_DXFMT_SUPPORTED);
console.log("PASS: level dx10.1: dx10 and SVGA_CAP2_DX2, SM41, 4x multisampling of every target format, NV12/YUY2");

// dx11 is dx10.1 and shader model 5
const { DX11_DEVCAPS } = await import("../../src/graphics_adapters/vmware_svga/svga3d_tables.js");
assert.equal(LEVELS["dx11"].caps, LEVELS["dx10.1"].caps);
assert.equal(LEVELS["dx11"].cap2, LEVELS["dx10.1"].cap2 | C.SVGA_CAP2_DX3, "SM5 wants DX3");
const dx11_devcaps = new Map(DX11_DEVCAPS);
for(const [index, value] of dx10_1_devcaps)
{
    const now = dx11_devcaps.get(index);
    assert.ok(now === value || now >= value, "dx11 keeps or raises devcap " + index);
}
for(const [index, value] of [[C.SVGA3D_DEVCAP_SM5, 1], [C.SVGA3D_DEVCAP_MULTISAMPLE_8X, 1], [C.SVGA3D_DEVCAP_GL43, 1],
    [C.SVGA3D_DEVCAP_MAX_FORCED_SAMPLE_COUNT, 8], [C.SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH, 16384]])
{
    assert.equal(dx11_devcaps.get(index), value, "dx11 devcap " + index);
}
console.log("PASS: level dx11: dx10.1 and SVGA_CAP2_DX3, SM5, 8x multisampling, GL43, 16384-texel textures");

await vm.destroy();
                                                                                                                                                                                                                                            source/v64/tests/devices/vmware_svga_video.js                                                       0000755 0000000 0000000 00000020775 00000000000 016533  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The VMware SVGA II adapter's video overlay (level dx11-full,
// svga_video.js): SVGA_FIFO_CAP_VIDEO, SVGA_ESCAPE_VMWARE_VIDEO_SET_REGS and
// _FLUSH through the FIFO, YUY2 and YV12 frames from VRAM scaled into the
// destination rectangle, the color key, switching a unit off, snapshots; the
// overlay is drawn over the picture, guest memory stays as it was. Also the
// level's DX_PROVOKING_VERTEX devcap.

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const C = await import("../../src/graphics_adapters/vmware_svga/svga_constants.js");

// hlt forever
const floppy = new Uint8Array(1474560);
floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
floppy[510] = 0x55;
floppy[511] = 0xAA;

// (a 3D level needs a renderer; nothing here draws in 3D)
let to_device = null;
const renderer = {
    "post": message => { if(message["type"] === "submit") to_device({ "type": "done", "seq": message["seq"] }); },
    "listen": handler => { to_device = handler; },
};
const VRAM = 8 << 20;
const emulator = new V86({
    graphics_adapter: "vmware_svga",
    graphics_adapter_test: { level: "dx11-full", renderer },
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    fda: { buffer: floppy.buffer },
    boot_order: 0x321,
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    vram_size: VRAM,
    net_device: { type: "none" },
    disable_speaker: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
await emulator.wait_until_vga_screen_contains("Booting from Floppy", { timeout_msec: 30000 });
await emulator.stop();

const cpu = emulator.v86.cpu, io = cpu.io;
const svga = cpu.devices.graphics_adapter.device["svga"];
const BDF = 0x12 << 3;
const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
const port = pci_read(0x10) & ~3, fb = (pci_read(0x14) & ~0xF) >>> 0, fifo = (pci_read(0x18) & ~0xF) >>> 0;
const write_reg = (index, value) => { io.port_write32(port + C.SVGA_INDEX_PORT, index); io.port_write32(port + C.SVGA_VALUE_PORT, value); };
const read_reg = index => { io.port_write32(port + C.SVGA_INDEX_PORT, index); return io.port_read32(port + C.SVGA_VALUE_PORT) >>> 0; };
const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
const fifo_write = (index, value) => write32(fifo + index * 4, value);
const fifo_read = index => read32(fifo + index * 4);

// The level: the video overlay's FIFO capability, GL's provoking vertex
write_reg(C.SVGA_REG_ID, C.SVGA_ID_2);
write_reg(C.SVGA_REG_DEV_CAP, C.SVGA3D_DEVCAP_DX_PROVOKING_VERTEX);
assert.equal(read_reg(C.SVGA_REG_DEV_CAP), 1, "DX_PROVOKING_VERTEX");

// A 64x48x32 mode: the left half has the color key (magenta), the right not
const W = 64, H = 48, KEY = 0x00FF00FF, OTHER = 0x00102030;
write_reg(C.SVGA_REG_WIDTH, W);
write_reg(C.SVGA_REG_HEIGHT, H);
write_reg(C.SVGA_REG_BITS_PER_PIXEL, 32);
write_reg(C.SVGA_REG_ENABLE, C.SVGA_REG_ENABLE_ENABLE);
const pitch = read_reg(C.SVGA_REG_BYTES_PER_LINE);
for(let y = 0; y < H; y++) for(let x = 0; x < W; x++) write32(fb + y * pitch + x * 4, x < W / 2 ? KEY : OTHER);

const MIN = 0x1000, MAX = 0x10000;
fifo_write(C.SVGA_FIFO_MIN, MIN);
fifo_write(C.SVGA_FIFO_MAX, MAX);
fifo_write(C.SVGA_FIFO_NEXT_CMD, MIN);
fifo_write(C.SVGA_FIFO_STOP, MIN);
write_reg(C.SVGA_REG_CONFIG_DONE, 1);
assert.ok(fifo_read(C.SVGA_FIFO_CAPABILITIES) & C.SVGA_FIFO_CAP_VIDEO, "SVGA_FIFO_CAP_VIDEO");
let next = MIN;
const submit = (...dwords) => {
    for(const dword of dwords)
    {
        write32(fifo + next, dword);
        next = next + 4 === MAX ? MIN : next + 4;
    }
    fifo_write(C.SVGA_FIFO_NEXT_CMD, next);
    write_reg(C.SVGA_REG_SYNC, 1);
    assert.equal(fifo_read(C.SVGA_FIFO_STOP), next, "consumed");
};
const SET_REGS = 0x00020001, FLUSH = 0x00020002;
const R = { ENABLED: 0, FLAGS: 1, DATA_OFFSET: 2, FORMAT: 3, COLORKEY: 4, SIZE: 5, WIDTH: 6, HEIGHT: 7, SRC_X: 8, SRC_Y: 9,
    SRC_WIDTH: 10, SRC_HEIGHT: 11, DST_X: 12, DST_Y: 13, DST_WIDTH: 14, DST_HEIGHT: 15, PITCH_1: 16, PITCH_2: 17, PITCH_3: 18,
    DATA_GMRID: 19, DST_SCREEN_ID: 20 };
const escape = (...payload) => submit(C.SVGA_CMD_ESCAPE, C.SVGA_ESCAPE_NSID_VMWARE, payload.length * 4, ...payload);
const set_regs = (unit, regs) => escape(SET_REGS, unit, ...Object.entries(regs).flatMap(([name, value]) => [R[name], value]));
const flush = unit => escape(FLUSH, unit);

// What the page shows: the layers composed
const screen = new Uint8ClampedArray(W * H * 4);
cpu.devices.display.update_buffer = layers => {
    for(const l of layers)
    {
        for(let y = 0; y < l.buffer_height; y++)
        {
            const from = ((l.buffer_y + y) * l.pixels.width + l.buffer_x) * 4;
            screen.set(l.pixels.data.subarray(from, from + l.buffer_width * 4), ((l.screen_y + y) * W + l.screen_x) * 4);
        }
    }
};
const shown = (x, y) => { cpu.devices.display.request_frame(true); return [...screen.subarray((y * W + x) * 4, (y * W + x) * 4 + 3)]; };
const near = (got, want, what) => assert.ok(got.every((v, i) => Math.abs(v - want[i]) <= 2), what + ": " + got + " vs " + want);
near(shown(5, 5), [0xFF, 0, 0xFF], "the picture");

// A YUY2 frame in VRAM, 8x4: white on the left half, black on the right
// (Y 235 and 16, no color), scaled 4x into (16, 8) 32x16
const DATA = 0x100000;
for(let y = 0; y < 4; y++) for(let x = 0; x < 8; x += 2)
{
    const luma = x < 4 ? 235 : 16;
    write32(fb + DATA + y * 16 + x * 2, luma | 128 << 8 | luma << 16 | 128 << 24);
}
set_regs(0, { ENABLED: 1, FLAGS: 1, COLORKEY: KEY, FORMAT: 0x32595559, SIZE: 64, WIDTH: 8, HEIGHT: 4, SRC_X: 0, SRC_Y: 0,
    SRC_WIDTH: 8, SRC_HEIGHT: 4, DST_X: 16, DST_Y: 8, DST_WIDTH: 32, DST_HEIGHT: 16, PITCH_1: 16, DATA_GMRID: C.SVGA_GMR_FRAMEBUFFER,
    DATA_OFFSET: DATA, DST_SCREEN_ID: C.SVGA_ID_INVALID });
flush(0);
near(shown(20, 10), [255, 255, 255], "the video where the picture has the key");
near(shown(40, 10), [0x10, 0x20, 0x30], "the picture where it has not");
near(shown(5, 5), [0xFF, 0, 0xFF], "the picture outside of the rectangle");
assert.equal(read32(fb + 10 * pitch + 20 * 4), KEY, "guest memory is as it was");
console.log("PASS: a YUY2 frame, scaled, with a color key");

// Without the key: the whole rectangle; its right half is the frame's black
set_regs(0, { FLAGS: 0 });
flush(0);
near(shown(20, 10), [255, 255, 255], "the left of the frame");
near(shown(40, 10), [0, 0, 0], "the right of the frame, over the picture");
near(shown(48, 10), [0x10, 0x20, 0x30], "past the rectangle");

// The picture changes under it: still over it
for(let x = 32; x < 48; x++) write32(fb + 10 * pitch + x * 4, 0x00405060);
near(shown(40, 10), [0, 0, 0], "over the picture's new pixels");
console.log("PASS: without a color key, over a changing picture");

// A YV12 frame, 2x2: Y 16, 235, 81, 145, with U 90, V 240 (red's chroma)
const yv12 = [16, 235, 81, 145, 240, 90];
// (elsewhere in VRAM: unit 0 still shows its frame, read again on a restore)
const DATA2 = DATA + 0x1000;
yv12.forEach((v, i) => cpu.write8(fb + DATA2 + i, v));
set_regs(1, { ENABLED: 1, FLAGS: 0, FORMAT: 0x32315659, SIZE: 6, WIDTH: 2, HEIGHT: 2, SRC_WIDTH: 2, SRC_HEIGHT: 2,
    DST_X: 0, DST_Y: 40, DST_WIDTH: 2, DST_HEIGHT: 2, PITCH_1: 2, PITCH_2: 1, PITCH_3: 1, DATA_GMRID: C.SVGA_GMR_FRAMEBUFFER,
    DATA_OFFSET: DATA2, DST_SCREEN_ID: C.SVGA_ID_INVALID });
flush(1);
// (Y 81 with that chroma is BT.601's red)
near(shown(0, 41), [255, 0, 0], "YV12: red");
console.log("PASS: a YV12 frame");

// A snapshot: the units, and their frames read again
const state = await emulator.save_state();
await emulator.restore_state(state);
screen.fill(0);
svga.mode_key = "";
near(shown(20, 10), [255, 255, 255], "unit 0 after a restore");
near(shown(0, 41), [255, 0, 0], "unit 1 after a restore");
console.log("PASS: snapshots");

// Switched off: the picture again
set_regs(0, { ENABLED: 0 });
set_regs(1, { ENABLED: 0 });
near(shown(20, 10), [0xFF, 0, 0xFF], "the picture again");
near(shown(40, 10), [0x40, 0x50, 0x60], "the picture's own pixels");
assert.equal(svga.video.stats.escapes > 0, true);
console.log("PASS: units switched off");

emulator.destroy();
   source/v64/tests/devices/wisp_network.js                                                            0000755 0000000 0000000 00000011223 00000000000 015543  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env -S node --experimental-websocket

import assert from "assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const SHOW_LOGS = false;

const tests =
[
    {
        name: "DHCP",
        start: () =>
        {
            emulator.serial0_send("udhcpc\n");
            emulator.serial0_send("echo -e done\\\\tudhcpc\n");
        },
        end_trigger: "done\tudhcpc",
        end: (capture) =>
        {
            assert(/lease of 192.168.86.100 obtained/.test(capture), "lease of 192.168.86.100 obtained");
        },
    },
    {
        name: "ifconfig",
        start: () =>
        {
            emulator.serial0_send("ifconfig\n");
            emulator.serial0_send("echo -e done\\\\tifconfig\n");
        },
        end_trigger: "done\tifconfig",
        end: (capture) =>
        {
            assert(/192.168.86.100/.test(capture), "192.168.86.100");
        },
    },
    {
        name: "route",
        start: () =>
        {
            emulator.serial0_send("ip route\n");
            emulator.serial0_send("echo -e done\\\\troute\n");
        },
        end_trigger: "done\troute",
        end: (capture) =>
        {
            assert(/192.168.86.1/.test(capture), "192.168.86.100");
        },
    },
    //{
    //    name: "arp -a",
    //    start: () =>
    //    {
    //        emulator.serial0_send("arp -a\n");
    //        emulator.serial0_send("echo -e done\\\\tarp\n");
    //    },
    //    end_trigger: "done\tarp",
    //    end: (capture) =>
    //    {
    //        assert(/.192.168.86.1. at 52:54:00:01:02:03 \[ether\] {2}on eth0/.test(capture), "(192.168.86.1) at 52:54:00:01:02:03 [ether]  on eth0");
    //    },
    //},
    {
        name: "Curl example.org",
        allow_failure: true,
        start: () =>
        {
            emulator.serial0_send("wget -T 10 -O - example.org\n");
            emulator.serial0_send("echo -e done\\\\texample.org\n");
        },
        end_trigger: "done\texample.org",
        end: (capture) =>
        {
            assert(/This domain is for use in documentation examples without needing permission/.test(capture), "got example.org text");
        },
    },

];

const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 64 * 1024 * 1024,
    disable_jit: +process.env.DISABLE_JIT,
    network_relay_url: "wisps://wisp.mercurywork.shop/",
    log_level: SHOW_LOGS ? 0x400000 : 0,
});

let test_num = 0;
let booted = false;
let line = "";
let capture = "";
let end_trigger;

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
});

emulator.add_listener("serial0-output-byte", function(byte)
{
    const chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    let new_line = "";
    if(chr === "\n")
    {
        console.log("    Captured: %s", line);
        new_line = line;
        capture += line + "\n";
        line = "";
    }
    else
    {
        line += chr;
    }

    if(new_line === end_trigger)
    {
        let test_has_failed = false;

        try {
            tests[test_num].end(capture);
        } catch(e) {
            console.log(e);
            test_has_failed = true;
        }

        if(!test_has_failed)
        {
            console.log("[+] Test #%d passed: %s", test_num, tests[test_num].name);
        }
        else
        {
            if(tests[test_num].allow_failure)
            {
                console.warn("[!] Test #%d failed: %s (failure allowed)", test_num, tests[test_num].name);
            }
            else
            {
                console.error("[-] Test #%d failed: %s", test_num, tests[test_num].name);
                process.exit(1);
            }
        }

        test_num++;

    }

    if(!booted && line.endsWith("~% ") || new_line === end_trigger)
    {
        booted = true;

        if(test_num >= tests.length)
        {
            emulator.destroy();

            console.log("Tests finished.");
        }
        else
        {
            console.log("Starting test #%d: %s", test_num, tests[test_num].name);

            capture = "";
            end_trigger = tests[test_num].end_trigger;

            tests[test_num].start();
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/full/run.js                                                                        0000755 0000000 0000000 00000154363 00000000000 013151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "node:assert/strict";
import cluster from "node:cluster";
import os from "node:os";
import fs from "node:fs";
import url from "node:url";

// config variables
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const TIMEOUT_EXTRA_FACTOR = +process.env.TIMEOUT_EXTRA_FACTOR || 1;
const MAX_PARALLEL_TESTS = +process.env.MAX_PARALLEL_TESTS || 4;
const TEST_NAME = process.env.TEST_NAME;
const RUN_SLOW_TESTS = +process.env.RUN_SLOW_TESTS;
const LOG_LEVEL = +process.env.LOG_LEVEL || 0;
const DISABLE_JIT = +process.env.DISABLE_JIT;
const TEST_ACPI = +process.env.TEST_ACPI;

const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

process.on("unhandledRejection", exn => { throw exn; });

const VERBOSE = false;
const LOG_SCREEN = false;


var root_path = __dirname + "/../..";

var SCREEN_WIDTH = 80;

function get_line(screen, y)
{
    return screen.subarray(y * SCREEN_WIDTH, (y + 1) * SCREEN_WIDTH);
}

function line_to_text(screen, y)
{
    return bytearray_to_string(get_line(screen, y));
}

function string_to_bytearray(str)
{
    return new Uint8Array(str.split("").map(chr => chr.charCodeAt(0)));
}

function bytearray_to_string(arr)
{
    return String.fromCharCode.apply(String, arr).replace(/[\x00-\x08\x0b-\x1f\x7f\x80-\xff]/g, " ");
}

function screen_to_text(s)
{
    var result = [];
    result.push("+==================================== SCREEN ====================================+");

    for(var i = 0; i < 25; i++)
    {
        var line = line_to_text(s, i);
        result.push("|" + line + "|");
    }

    result.push("+================================================================================+");

    return result.join("\n");
}

function send_work_to_worker(worker, message)
{
    if(current_test < tests.length)
    {
        worker.send(tests[current_test]);
        current_test++;
    }
    else
    {
        worker.disconnect();
    }
}

if(cluster.isPrimary)
{
    var tests = [
        {
            name: "FreeDOS boot",
            fda: root_path + "/images/freedos722.img",
            timeout: 20,
            expected_texts: [
                "Welcome to FreeDOS",
            ],
        },
        {
            name: "FreeDOS boot with Bochs BIOS",
            fda: root_path + "/images/freedos722.img",
            timeout: 20,
            alternative_bios: true,
            expected_texts: [
                "Welcome to FreeDOS",
            ],
        },
        {
            name: "Windows 1.01 boot",
            fda: root_path + "/images/windows101.img",
            timeout: 10,
            expect_graphical_mode: true,
            expect_mouse_registered: true,
        },
        {
            name: "Sol OS",
            fda: root_path + "/images/os8.img",
            timeout: 20,
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [
                {
                    on_text: " or press",
                    run: "\n"
                },
            ],
        },
        {
            name: "Snowdrop",
            skip_if_disk_image_missing: true,
            fda: root_path + "/images/snowdrop.img",
            timeout: 30,
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [
                {
                    on_text: "[Snowdrop OS snowshell]:",
                    run: "desktop\n"
                },
            ],
        },
        {
            name: "GentleOS/16",
            skip_if_disk_image_missing: true,
            fda: root_path + "/images/gentleos16-fd1440.img",
            timeout: 30,
            expect_graphical_mode: true,
            expect_graphical_size: [320, 200],
        },
        {
            name: "GentleOS/32",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/gentleos32-disk.img",
            timeout: 30,
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
        },
        {
            name: "Linux",
            cdrom: root_path + "/images/linux.iso",
            timeout: 90,
            expected_texts: [
                "/root%",
                "test passed",
            ],
            actions: [
                {
                    on_text: "/root%",
                    run: "cd tests; ./test-i386 > emu.test; diff emu.test reference.test && echo test pas''sed || echo failed\n",
                },
            ],
        },
        {
            name: "Linux 0.11",
            skip_if_disk_image_missing: true,
            fda: root_path + "/images/experimental/linux-0.11/bootfloppy.img",
            hda: root_path + "/images/experimental/linux-0.11/hdc-0.11.img",
            timeout: 60,
            expected_texts: [
                "[/usr/root]#",
                "test passed",
            ],
            actions: [
                {
                    on_text: "[/usr/root]#",
                    run: "echo test pas''sed\n",
                },
            ],
        },
        {
            name: "Windows Vista installer",
            skip_if_disk_image_missing: true,
            cdrom: root_path + "/images/experimental/en_windows_vista_sp2_x86_dvd_342266.iso",
            memory_size: 512 * 1024 * 1024,
            timeout: 300,
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
            acpi: true,
        },
        {
            name: "Windows XP CD",
            skip_if_disk_image_missing: true,
            cdrom: root_path + "/images/experimental/VirtualXP.iso",
            memory_size: 512 * 1024 * 1024,
            timeout: 600,
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
            acpi: false, // XXX: fails with acpi on
        },
        {
            name: "Windows XP HD",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/experimental/copy_winxp_lite-from-pixelsuft.img",
            memory_size: 512 * 1024 * 1024,
            timeout: 300,
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
        },
        {
            name: "Windows 2000",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/windows2k.img",
            memory_size: 512 * 1024 * 1024,
            timeout: 300,
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
        {
            name: "Windows NT 4.0",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/winnt4_noacpi.img",
            memory_size: 512 * 1024 * 1024,
            timeout: 60,
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
            cpuid_level: 2,
        },
        {
            name: "Windows NT 3.1",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/winnt31.img",
            memory_size: 256 * 1024 * 1024,
            timeout: 60,
            expect_graphical_mode: true,
            expect_graphical_size: [640, 480],
            expect_mouse_registered: true,
        },
        {
            name: "Windows 98",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/windows98.img",
            timeout: 60,
            expect_graphical_mode: true,
            expect_graphical_size: [640, 480],
            expect_mouse_registered: true,
            failure_allowed: true,
        },
        {
            name: "Windows 95",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/w95.img",
            timeout: 120,
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
        {
            name: "Oberon",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/oberon.img",
            timeout: 30,
            expect_graphical_mode: true,
            expect_mouse_registered: true,
        },
        {
            name: "Linux 3",
            skip_if_disk_image_missing: true,
            cdrom: root_path + "/images/linux3.iso",
            timeout: 200,
            expected_texts: [
                "test passed",
            ],
            actions: [
                {
                    on_text: "~%",
                    run: "head -c 10000 /dev/urandom > rand; echo test pas''sed\n",
                    after: 1000,
                },
            ],
        },
        {
            name: "Linux 3 reboot",
            cdrom: root_path + "/images/linux3.iso",
            timeout: 90,
            expected_texts: [
                "~%",
                "SeaBIOS ",
                "~%",
            ],
            actions: [
                {
                    on_text: "~%",
                    run: "reboot\n",
                },
            ],
        },
        {
            name: "KolibriOS",
            fda: root_path + "/images/kolibri.img",
            timeout: 120,
            expect_graphical_mode: true,
            expect_mouse_registered: true,
        },
        {
            name: "Linux with Bochs BIOS",
            cdrom: root_path + "/images/linux.iso",
            timeout: 90,
            expected_texts: [
                "/root%",
                "test passed",
            ],
            alternative_bios: true,
            actions: [
                {
                    on_text: "/root%",
                    run: "cd tests; ./test-i386 > emu.test; diff emu.test reference.test && echo test pas''sed || echo failed\n",
                },
            ],
        },
        {
            name: "MS-DOS",
            hda: root_path + "/images/msdos.img",
            timeout: 90,
            expected_texts: [
                "C:\\>",
            ],
        },
        {
            name: "MS-DOS (hard disk + floppy disk)",
            hda: root_path + "/images/msdos.img",
            fda: root_path + "/images/kolibri.img",
            boot_order: 0x132,
            timeout: 90,
            actions: [
                { on_text: "C:\\>", run: "a:\n" },
            ],
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "Linux 4",
            skip_if_disk_image_missing: true,
            cdrom: root_path + "/images/linux4.iso",
            timeout: 200,
            expected_texts: [
                "~%",
            ],
            expected_serial_text: [
                "Files send via emulator appear in",
            ],
            expect_mouse_registered: true,
        },
        {
            name: "Linux bzImage",
            bzimage: root_path + "/images/buildroot-bzimage68.bin",
            cmdline: "auto",
            timeout: 200,
            expected_texts: [
                "~%",
            ],
            expected_serial_text: [
                "Files send via emulator appear in",
            ],
            expect_mouse_registered: true,
        },
        {
            name: "Linux with bzImage from filesystem",
            bzimage_initrd_from_filesystem: true,
            filesystem: {
                basefs: root_path + "/build/integration-test-fs/fs.json",
                baseurl: root_path + "/build/integration-test-fs/flat/",
            },
            cmdline: "auto",
            timeout: 200,
            expected_texts: [
                "~%",
            ],
            expected_serial_text: [
                "Files send via emulator appear in",
            ],
            expect_mouse_registered: true,
        },
        {
            name: "QNX",
            skip_if_disk_image_missing: true,
            fda: root_path + "/images/qnx-demo-network-4.05.img",
            timeout: 300,
            expect_mouse_registered: true,
            expect_graphical_mode: true,
            expect_graphical_size: [640, 480],
            actions: [
                { run: " ", after: 30 * 1000 },
                { run: " ", after: 15 * 1000 },
                { run: " ", after: 15 * 1000 },
                { run: " ", after: 15 * 1000 },
                { run: " ", after: 15 * 1000 },
                { run: " ", after: 15 * 1000 },
                { run: " ", after: 15 * 1000 },
            ],
        },
        {
            name: "OpenBSD Floppy",
            fda: root_path + "/images/openbsd-floppy.img",
            timeout: 180,
            expected_texts: ["(I)nstall, (U)pgrade or (S)hell"],
        },
        {
            name: "OpenBSD",
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/openbsd.img",
            timeout: 300,
            actions: [
                {
                    on_text: "boot>",
                    run: "boot -c\n",
                },
                {
                    on_text: "UKC>",
                    run: "disable mpbios\nexit\n",
                },
                {
                    on_text: "login:",
                    run: "root\n",
                },
                {
                    on_text: "Password:",
                    run: "root\n",
                },
            ],
            expected_texts: ["nyu# "],
        },
        {
            name: "OpenBSD state image",
            timeout: 60,
            memory_size: 256 * 1024 * 1024,
            skip_if_disk_image_missing: true,
            hda: root_path + "/images/openbsd.img",
            state: root_path + "/images/openbsd_state-v2.bin.zst",
            actions: [
                {
                    after: 1 * 1000,
                    run: `echo 'main(){printf("it");puts(" works");}' > a.c; clang a.c; ./a.out\n`,
                }
            ],
            expected_texts: [
                "it works",
            ],
        },
        {
            name: "Windows 3.0",
            slow: 1,
            skip_if_disk_image_missing: true,
            timeout: 10 * 60,
            cdrom: root_path + "/images/Win30.iso",
            expected_texts: [
                "Press any key to continue",
                "              **************************************************",
            ],
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [
                {
                    on_text: "Press any key to continue . . .",
                    after: 1000,
                    run: "x",
                },
                {
                    on_text: "              **************************************************",
                    after: 1000,
                    run: "x",
                },
                {
                    on_text: "C> ",
                    after: 1000,
                    run: "win\n",
                },
            ],
        },
        {
            name: "Windows 3.1",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            hda: root_path + "/images/win31.img",
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
            expected_texts: [
                "MODE prepare code page function completed",
            ],
        },
        {
            name: "Windows 95 big",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            hda: root_path + "/images/experimental/windows95-felixrieseberg.img",
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
        {
            name: "386BSD",
            skip_if_disk_image_missing: true,
            timeout: 5 * 60,
            memory_size: 64 * 1024 * 1024,
            hda: root_path + "/images/386bsd.img", // https://archive.org/details/386bsd-1.0-qemu
            expected_texts: [
                "386BSD Release 1.0",
                "login:",
                "erase ^?, kill ^U, intr ^C",
            ],
            actions: [
                {
                    on_text: "login:",
                    after: 1000,
                    run: "root\n",
                },
                {
                    on_text: "Password:",
                    after: 1000,
                    run: "welcome\n",
                },
            ],
        },
        {
            name: "FreeBSD",
            skip_if_disk_image_missing: true,
            timeout: 15 * 60,
            hda: root_path + "/images/freebsd.img",
            expected_texts: [
                "FreeBSD/i386 (nyu) (ttyv0)",
                "root@nyu:~ #",
            ],
            actions: [
                {
                    on_text: "   Autoboot in",
                    run: "\n",
                },
                {
                    // workaround for freebsd not accepting key inputs just before the boot prompt
                    // (probably needs delay between keydown and keyup)
                    on_text: "FreeBSD/i386 (nyu) (ttyv0)",
                    run: "\x08", // backspace to avoid messing with login prompt
                },
                {
                    on_text: "login:",
                    after: 1000,
                    run: "root\n",
                },
                {
                    on_text: "Password:",
                    after: 1000,
                    run: "\n",
                },
            ],
        },
        {
            name: "FreeBSD cdrom",
            skip_if_disk_image_missing: true,
            slow: 1,
            timeout: 10 * 60,
            cdrom: root_path + "/images/experimental/os/FreeBSD-11.0-RELEASE-i386-bootonly.iso",
            expected_texts: ["Welcome to FreeBSD!"],
            actions: [
                {
                    on_text: "   Autoboot in ",
                    run: "\n",
                }
            ],
        },
        {
            name: "Arch Linux",
            skip_if_disk_image_missing: true,
            timeout: 20 * 60,
            bzimage_initrd_from_filesystem: true,
            memory_size: 512 * 1024 * 1024,
            cmdline: [
                "rw apm=off vga=0x344 video=vesafb:ypan,vremap:8",
                "root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose mitigations=off",
                "audit=0 init=/usr/bin/init-openrc net.ifnames=0 biosdevname=0",
            ].join(" "),
            filesystem: {
                basefs: "images/fs.json",
                baseurl: "images/arch/",
            },
            expected_texts: [
                "root@localhost",
                "aaaaaaaaaaaaaaaaaaaa",
                "Hello, world",
                "Hello from JS",
                "Hello from OCaml",
                "Compress okay",
                "v86-in-v86 okay",
            ],
            actions: [
                {
                    on_text: "root@localhost",
                    run: `python -c 'print(100 * "a")'\n`,
                },
                {
                    on_text: "aaaaaaaaaaaaaaaaaaaa",
                    run: `gcc hello.c && ./a.out\n`,
                },
                {
                    on_text: "Hello, world",
                    run: `echo 'console.log("Hello from JS")' | node\n`,
                },
                {
                    on_text: "Hello from JS",
                    run: `echo 'print_endline "Hello from OCaml"' > hello.ml && ocamlopt hello.ml && ./a.out\n`,
                },
                {
                    on_text: "Hello from OCaml",
                    run:
                        "zstd hello.c && gzip -k hello.c && bzip2 -k hello.c && xz -k hello.c && lzma -k hello.c && " +
                        "zstdcat hello.c.zst && zcat hello.c.gz && bzcat hello.c.bz2 && xzcat hello.c.xz && lzmadec hello.c.lzma && " +
                        "echo Compress okay\n",
                },
                {
                    on_text: "Compress okay",
                    run:
                        RUN_SLOW_TESTS ?
                            "./v86-in-v86.js | tee /dev/stderr | grep -m1 'Files send via emulator appear in' ; sleep 2; echo; echo v86-in-v86 okay\n"
                        :
                            "./v86-in-v86.js | tee /dev/stderr | grep -m1 'Kernel command line:' ; sleep 2; echo; echo v86-in-v86 okay\n",
                },
                {
                    on_text: "v86-in-v86 okay",
                    run: "./startx.sh\n",
                },
            ],
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
        {
            name: "Arch Linux state image",
            skip_if_disk_image_missing: true,
            timeout: 60,
            memory_size: 512 * 1024 * 1024,
            filesystem: {
                basefs: "images/fs.json",
                baseurl: "images/arch/",
            },
            state: "images/arch_state-v3.bin.zst",
            net_device: { type: "virtio" },
            actions: [
                { after: 1000, run: "ls --color=never /dev/ /usr/bin/ > /dev/ttyS0\n" },
                { after: 2000, run: `python -c 'print(100 * "a")' > /dev/ttyS0\n` },
            ],
            expected_serial_text: [
                "ttyS0",
                "syslinux-install_update",
                "aaaaaaaaaaaaaaaaaaaa",
            ],
        },
        {
            name: "Arch Linux (with fda, cdrom, hda and hdb)",
            skip_if_disk_image_missing: true,
            timeout: 5 * 60,
            bzimage_initrd_from_filesystem: true,
            memory_size: 512 * 1024 * 1024,
            cmdline: [
                "rw apm=off vga=0x344 video=vesafb:ypan,vremap:8",
                "root=host9p rootfstype=9p rootflags=trans=virtio,cache=loose mitigations=off",
                "audit=0 init=/usr/bin/init-openrc net.ifnames=0 biosdevname=0",
            ].join(" "),
            filesystem: {
                basefs: "images/fs.json",
                baseurl: "images/arch/",
            },
            hda: root_path + "/images/w95.img",
            hdb: root_path + "/images/FiwixOS-3.4-i386.img",
            cdrom: root_path + "/images/dsl-4.11.rc2.iso",
            fda: root_path + "/images/freedos722.img",
            actions: [
                {
                    on_text: "root@localhost",
                    run: "modprobe floppy && mkdir /mnt/{a,b,c,f} && mount /dev/sda1 /mnt/a && mount /dev/sdb2 /mnt/b && mount /dev/sr0 /mnt/c && mount /dev/fd0 /mnt/f && ls /mnt/*\n",
                },
            ],
            expected_texts: [
                "bin   dev  home",                          // fiwix
                " AUTOEXEC.BAT   CONFIG.WIN   MSDOS.SYS",   // w95
                "KNOPPIX  boot  index.html",                // DSL
                "FDOS          README      debug.com",      // freedos
            ],
        },
        {
            name: "FreeGEM",
            skip_if_disk_image_missing: true,
            timeout: 60,
            hda: root_path + "/images/freegem.bin",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [
                {
                    on_text: "   Select from Menu",
                    run: "3",
                }
            ],
        },
        {
            name: "Haiku",
            skip_if_disk_image_missing: true,
            timeout: 15 * 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/haiku-r1beta2-hrev54154_111-x86_gcc2h-anyboot.iso",
            expected_serial_text: [
                "init_hardware()",
                "Running post install script /boot/system/boot/post-install/sshd_keymaker.sh",
                // After pressing enter in the boot dialog:
                "Running first login script /boot/system/boot/first-login/default_deskbar_items.sh",
            ],
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
            actions: [
                { after: 1 * 60 * 1000, run: "\n" },
                { after: 2 * 60 * 1000, run: "\n" },
                { after: 3 * 60 * 1000, run: "\n" },
                { after: 4 * 60 * 1000, run: "\n" },
                { after: 5 * 60 * 1000, run: "\n" },
                { after: 6 * 60 * 1000, run: "\n" },
                { after: 7 * 60 * 1000, run: "\n" },
                { after: 8 * 60 * 1000, run: "\n" },
            ],
            acpi: true,
        },
        {
            name: "Haiku state image",
            skip_if_disk_image_missing: true,
            timeout: 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/haiku-v5.img",
            state: root_path + "/images/haiku_state-v5.bin.zst",
            actions: [
                {
                    after: 2 * 1000,
                    run: `echo 'let rec f=function 0|1->1|x->f(x-1)+f(x-2)in Printf.printf"%d\n"(f 25)' | ocaml -stdin > /dev/ports/pc_serial0\n`
                },
            ],
            expected_serial_text: [
                "121393",
            ],
            acpi: true,
        },
        {
            name: "9front",
            use_small_bios: true, // has issues with 256k bios
            skip_if_disk_image_missing: true,
            acpi: true,
            timeout: 5 * 60,
            hda: root_path + "/images/9front-7781.38dcaeaa222c.386.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
            actions: [
                { after: 60 * 1000, run: "\n" },
                { after: 70 * 1000, run: "\n" },
                { after: 80 * 1000, run: "\n" },
                { after: 90 * 1000, run: "\n" },
                { after: 100 * 1000, run: "\n" },
                { after: 110 * 1000, run: "\n" },
                { after: 120 * 1000, run: "\n" },
                { after: 130 * 1000, run: "\n" },
                { after: 140 * 1000, run: "\n" },
                { after: 150 * 1000, run: "\n" },
                { after: 160 * 1000, run: "\n" },
                { after: 170 * 1000, run: "\n" },
                { after: 180 * 1000, run: "\n" },
            ],
        },
        {
            name: "ReactOS",
            skip_if_disk_image_missing: true,
            timeout: 10 * 60,
            hda: root_path + "/images/reactos-livecd-0.4.15-dev-73-g03c09c9-x86-gcc-lin-dbg.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
            actions: [
                { after: 1 * 60 * 1000, run: "\n" },
                { after: 2 * 60 * 1000, run: "\n" },
                { after: 3 * 60 * 1000, run: "\n" },
                { after: 4 * 60 * 1000, run: "\n" },
                { after: 5 * 60 * 1000, run: "\n" },
                { after: 6 * 60 * 1000, run: "\n" },
                { after: 7 * 60 * 1000, run: "\n" },
                { after: 8 * 60 * 1000, run: "\n" },
            ],
            expected_serial_text: [
                "DnsIntCacheInitialize()",
                // when desktop is rendered:
                "err: Attempted to close thread desktop",
            ],
        },
        {
            name: "ReactOS state image",
            skip_if_disk_image_missing: true,
            memory_size: 512 * 1024 * 1024,
            acpi: true,
            net_device: { type: "virtio" },
            timeout: 60,
            hda: root_path + "/images/reactos-v3.img",
            state: root_path + "/images/reactos_state-v3.bin.zst",
            actions: [
                { after: 5 * 1000, run: [0xE0, 0x5B, 0x13, 0x93, 0xE0, 0xDB] }, // meta+r
                { after: 10 * 1000, run: "cmd\n" },
                { after: 15 * 1000, run: "echo it works > COM1\n" },
            ],
            expected_serial_text: [
                "it works",
            ],
        },
        {
            name: "ReactOS CD",
            skip_if_disk_image_missing: true,
            timeout: 10 * 60,
            cdrom: root_path + "/images/reactos-livecd-0.4.15-dev-73-g03c09c9-x86-gcc-lin-dbg.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
            expected_serial_text: ["DnsIntCacheInitialize()"],
        },
        {
            name: "HelenOS",
            skip_if_disk_image_missing: true,
            timeout: 3 * 60,
            cdrom: root_path + "/images/HelenOS-0.11.2-ia32.iso",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            expected_serial_text: ["init: Spawning"],
        },
        {
            name: "Minix",
            skip_if_disk_image_missing: true,
            timeout: 60,
            hda: root_path + "/images/experimental/os/minix2hd.img",
            actions: [
                {
                    on_text: "    =  Start Minix",
                    run: "=",
                },
                {
                    on_text: "noname login:",
                    run: "root\n",
                },
            ],
            expected_texts: ["noname login:", "# "],
        },
        {
            name: "Minix CD",
            skip_if_disk_image_missing: true,
            timeout: 3 * 60,
            cdrom: root_path + "/images/minix-3.3.0.iso",
            actions: [
                {
                    on_text: "login:",
                    run: "root\n",
                },
            ],
            expected_texts: ["login:", "We'd like your feedback", "# "],
        },
        {
            name: "Mojo OS",
            skip_if_disk_image_missing: true,
            timeout: 60,
            cdrom: root_path + "/images/mojo-0.2.2.iso",
            actions: [
                {
                    on_text: "/> ",
                    run: "help\n",
                },
            ],
            expected_texts: ["Mojo test shell", "See manual pages for more information"],
            expected_serial_text: [" ===> Shell loaded"],
            expect_mouse_registered: true,
        },
        {
            name: "Vanadium OS",
            skip_if_disk_image_missing: true,
            timeout: 180,
            cdrom: root_path + "/images/vanadiumos.iso",
            actions: [
                { after: 5000, run: " " },
                { after: 5100, run: " " },
                { after: 5200, run: " " },
                { after: 5300, run: " " },
                { after: 5400, run: " " },
                { after: 5500, run: " " },
                { after: 5600, run: " " },
                { after: 5700, run: " " },
                { after: 5800, run: "c" },
            ],
            expect_mouse_registered: true,
            expect_graphical_mode: true,
        },
        {
            name: "Asuro",
            skip_if_disk_image_missing: true,
            timeout: 60,
            cdrom: root_path + "/images/asuro.iso",
            expect_mouse_registered: true,
            expect_graphical_mode: true,
            expected_serial_text: ["Asuro Booted Correctly!"],
        },
        {
            name: "Mobius",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            fda: root_path + "/images/mobius-fd-release5.img",
            expect_graphical_mode: true,
            actions: [
                {
                    on_text: "   The highlighted entry will be booted automatically",
                    run: "\n",
                },
            ],
            acpi: false, // segfaults with acpi on (also in other emulators)
        },
        {
            name: "FreeNOS",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            cdrom: root_path + "/images/FreeNOS-1.0.3.iso",
            acpi: true,
            actions: [
                {
                    on_text: "login:",
                    run: "root\n",
                },
            ],
            expected_texts: ["login:", "(localhost)"],
            expected_serial_text: ["FreeNOS 1.0.3"],
        },
        {
            name: "SerenityOS",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            hda: root_path + "/images/serenity.img",
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
        {
            name: "Redox",
            skip_if_disk_image_missing: true,
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            acpi: true,
            hda: root_path + "/images/redox_demo_i686_2022-11-26_643_harddrive.img",
            actions: [
                { on_text: "Arrow keys and enter select mode", run: "\n" },
            ],
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            expected_serial_text: ["# Login with the following:"],
        },
        {
            name: "Android 1.6",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            cdrom: root_path + "/images/android-x86-1.6-r2.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
        },
        {
            name: "Android 4.4",
            skip_if_disk_image_missing: true,
            timeout: 5 * 60,
            hda: root_path + "/images/android_x86_nonsse3_4.4r1_20140904.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [800, 600],
            expect_mouse_registered: true,
        },
        {
            name: "Syllable",
            skip_if_disk_image_missing: true,
            timeout: 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/syllable-destop-0.6.7.img",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
        },
        {
            name: "Mu",
            skip_if_disk_image_missing: true,
            timeout: 60,
            memory_size: 256 * 1024 * 1024,
            hda: root_path + "/images/mu-shell.img",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
        },
        {
            name: "FreeDOS boot floppy 160K", // source: https://github.com/codercowboy/freedosbootdisks/tree/master/bootdisks
            skip_if_disk_image_missing: true,
            fda: root_path + "/images/experimental/freedos-fds/freedos.boot.disk.160K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "FreeDOS boot floppy 180K",
            skip_if_disk_image_missing: true,
            fda: root_path + "/image/experimentals/freedos-fds/freedos.boot.disk.180K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "FreeDOS boot floppy 320K",
            skip_if_disk_image_missing: true,
            fda: root_path + "/image/experimentals/freedos-fds/freedos.boot.disk.320K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "FreeDOS boot floppy 360K",
            skip_if_disk_image_missing: true,
            fda: root_path + "/image/experimentals/freedos-fds/freedos.boot.disk.360K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "FreeDOS boot floppy 640K",
            skip_if_disk_image_missing: true,
            fda: root_path + "/image/experimentals/freedos-fds/freedos.boot.disk.640K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "FreeDOS boot floppy 1200K",
            skip_if_disk_image_missing: true,
            fda: root_path + "/image/experimentals/freedos-fds/freedos.boot.disk.1200K.img",
            timeout: 10,
            expected_texts: [
                "A:\\>",
            ],
        },
        {
            name: "ASM Space Invaders",
            skip_if_disk_image_missing: true,
            timeout: 10,
            fda: root_path + "/images/space-invaders.img", // non-standard floppy disk size, reads past end of original image
            expected_texts: [
                "                             #   SPACE INVADERS   # ",
            ],
        },
        {
            name: "NetBSD multiboot",
            skip_if_disk_image_missing: true,
            timeout: 15,
            memory_size: 256 * 1024 * 1024,
            multiboot: root_path + "/images/netbsd9.3-kernel-multiboot.img",
            expected_texts: [
                // NOTE: doesn't success booting yet, just testing the multiboot boot
                "[   1.0000000] multiboot:",
            ],
        },
        {
            name: "Crazierl",
            skip_if_disk_image_missing: true,
            timeout: 60,
            memory_size: 256 * 1024 * 1024,
            multiboot: root_path + "/images/crazierl-elf.img",
            initrd: root_path + "/images/crazierl-initrd.img",
            cmdline: "kernel /libexec/ld-elf32.so.1",
            acpi: true,
            expected_serial_text: [
                "Welcome to Crazierl:",
            ],
        },
        {
            name: "Fiwix",
            skip_if_disk_image_missing: true,
            timeout: 2 * 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/FiwixOS-3.4-i386.img",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            expected_texts: [
                "(root):~#",
            ],
            actions: [
                { on_text: "(root):~#", run: "/usr/games/lsdoom\n" },
            ],
        },
        {
            name: "9legacy",
            use_small_bios: true, // has issues with 256k bios
            skip_if_disk_image_missing: true,
            net_device: { type: "none" }, // if netdevice is found, waits for dhcp before starting desktop
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/9legacy.img",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            expected_texts: [
                "Selection:",
            ],
            actions: [
                { on_text: "Selection:", run: "1\n" },
            ],
            expected_serial_text: [
                "init: starting",
            ],
        },
        {
            name: "BSD/OS 3",
            skip_if_disk_image_missing: true,
            net_device: { type: "none" }, // executes 16-bit io instructions
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            cdrom: root_path + "/images/experimental/bsdos-3.0-binary.iso",
            fda: root_path + "/images/experimental/bsdos3-install-floppy.img",
            expected_texts: ["\xc9\xcd BSD/OS Installation"],
            boot_order: 0x321,
        },
        {
            name: "BSD/OS 4",
            skip_if_disk_image_missing: true,
            net_device: { type: "none" }, // executes 16-bit io instructions
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            cdrom: root_path + "/images/experimental/bsdos-4.3-x86-binary.iso",
            expected_texts: ["\xc9\xcd BSD/OS Installation"],
        },
        {
            name: "Arch Hurd",
            skip_if_disk_image_missing: true,
            net_device: { type: "none" }, // executes 16-bit io instructions
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            hda: root_path + "/images/archhurd-2018.09.28.img",
            expected_texts: ["sh-4.4# "],
        },
        {
            name: "Linux with Postgres",
            skip_if_disk_image_missing: true,
            timeout: 5 * 60,
            memory_size: 512 * 1024 * 1024,
            cdrom: root_path + "/images/experimental/linux-postgres.iso",
            expected_texts: [
                "performing post-bootstrap initialization",
                "syncing data to disk",
                "Success. You can now start the database server using",
            ],
        },
        {
            name: "Tiny Core 11 CD",
            skip_if_disk_image_missing: 1,
            timeout: 10 * 60,
            cdrom: root_path + "/images/TinyCore-11.0.iso",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [{ on_text: "                   BIOS default device boot in", run: "\n", after: 5000 }],
        },
        {
            name: "Tiny Core 11 HD",
            skip_if_disk_image_missing: 1,
            timeout: 10 * 60,
            hda: root_path + "/images/TinyCore-11.0.iso",
            expect_graphical_mode: true,
            expect_mouse_registered: true,
            actions: [{ on_text: "                   BIOS default device boot in", run: "\n", after: 5000 }],
        },
        {
            name: "Core 9 (with hard disk)",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-9.0.iso",
            fda: root_path + "/images/freedos722.img",
            boot_order: 0x213,
            actions: [
                { on_text: "boot:", run: "\n" },
                { on_text: "tc@box", run: "sudo mount /dev/fd0 /mnt && ls /mnt\n" },
            ],
            expected_texts: ["AUTOEXEC.BAT"],
        },
        {
            name: "Core 9 (with hard disk)",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-9.0.iso",
            hda: root_path + "/images/TinyCore-11.0.iso",
            boot_order: 0x213,
            actions: [
                { on_text: "boot:", run: "\n" },
                { on_text: "tc@box", run: "sudo mount /dev/sda1 /mnt && ls /mnt\n" },
            ],
            expected_texts: ["boot/ cde/"],
        },
        {
            name: "Core 8",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-8.0.iso",
            expected_texts: ["tc@box"],
            actions: [{ on_text: "boot:", run: "\n" }],
        },
        {
            name: "Core 7",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-7.2.iso",
            expected_texts: ["tc@box"],
            actions: [{ on_text: "boot:", run: "\n" }],
        },
        {
            name: "Core 6",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-6.4.1.iso",
            expected_texts: ["tc@box"],
            actions: [{ on_text: "boot:", run: "\n" }],
        },
        {
            name: "Core 5",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-5.4.iso",
            expected_texts: ["tc@box"],
            actions: [{ on_text: "boot:", run: "\n" }],
        },
        {
            name: "Core 4",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/experimental/os/Core-4.7.7.iso",
            expected_texts: ["tc@box"],
            actions: [{ on_text: "boot:", run: "\n" }],
        },
        {
            name: "Damn Small Linux",
            skip_if_disk_image_missing: 1,
            timeout: 5 * 60,
            cdrom: root_path + "/images/dsl-4.11.rc2.iso",
            expect_graphical_mode: true,
            expect_graphical_size: [1024, 768],
            expect_mouse_registered: true,
        },
    ];

    if(TEST_NAME)
    {
        tests = tests.filter(test => test.name === TEST_NAME);
    }

    var nr_of_cpus = Math.min(Math.round(os.cpus().length / 2) || 1, tests.length, MAX_PARALLEL_TESTS);
    console.log("Using %d cpus", nr_of_cpus);

    var current_test = 0;

    for(var i = 0; i < nr_of_cpus; i++)
    {
        var worker = cluster.fork();

        worker.on("message", send_work_to_worker.bind(null, worker));

        worker.on("exit", function(code, signal)
        {
            if(signal)
            {
                console.warn("Worker killed by signal " + signal);
                process.exit(1);
            }
            else if(code !== 0)
            {
                process.exit(code);
            }
        });

        worker.on("error", function(error)
        {
            console.error("Worker error: ", error.toString(), error);
            process.exit(1);
        });
    }
}
else
{
    cluster.worker.on("message", function(test_case)
    {
        run_test(test_case, function()
        {
            process.send("I'm done");
        });
    });
    process.send("up");
}

function bytearray_starts_with(arr, search)
{
    for(var i = 0; i < search.length; i++)
    {
        if(arr[i] !== search[i])
        {
            return false;
        }
    }
    return true;
}

function run_test(test, done)
{
    console.log("Starting test: %s", test.name);

    const images = [test.fda, test.hda, test.cdrom, test.bzimage, test.multiboot, test.filesystem && test.filesystem.basefs].filter(x => x);
    assert(images.length, "Bootable drive expected");

    const missing_images = images.filter(i => !fs.existsSync(i));
    if(missing_images.length)
    {
        if(test.skip_if_disk_image_missing)
        {
            console.warn("Missing disk image: " + missing_images.join(", ") + ", test skipped");
            console.warn();

            done();
            return;
        }
        else
        {
            console.warn("Missing disk image: " + missing_images.join(", "));
            process.exit(1);
        }
    }

    if(test.slow && !RUN_SLOW_TESTS)
    {
        console.warn("Slow test: " + test.name + ", skipped");
        console.warn();
        done();
        return;
    }

    if(test.alternative_bios)
    {
        var bios = root_path + "/bios/bochs-bios.bin";
        var vga_bios = root_path + "/bios/bochs-vgabios.bin";
    }
    else if(test.use_small_bios || TEST_RELEASE_BUILD)
    {
        var bios = root_path + "/bios/seabios.bin";
        var vga_bios = root_path + "/bios/vgabios.bin";
    }
    else
    {
        var bios = root_path + "/bios/seabios-debug.bin";
        var vga_bios = root_path + "/bios/vgabios-debug.bin";
    }

    var settings = {
        graphics_adapter: "bochs_vga",
        bios: { url: bios },
        vga_bios: { url: vga_bios },
        autostart: true,
        memory_size: test.memory_size || 128 * 1024 * 1024,
        log_level: LOG_LEVEL,
    };

    if(test.cdrom)
    {
        settings.cdrom = { url: test.cdrom, async: true };
    }
    if(test.fda)
    {
        settings.fda = { url: test.fda };
    }
    if(test.hda)
    {
        settings.hda = { url: test.hda, async: true };
    }
    if(test.hdb)
    {
        settings.hdb = { url: test.hdb, async: true };
    }
    if(test.state)
    {
        settings.initial_state = { url: test.state };
    }
    if(test.bzimage)
    {
        settings.bzimage = { url: test.bzimage };
    }
    if(test.multiboot)
    {
        settings.multiboot = { url: test.multiboot };
    }
    if(test.initrd)
    {
        settings.initrd = { url: test.initrd };
    }
    if(test.filesystem)
    {
        settings.filesystem = test.filesystem;
    }
    settings.cmdline = test.cmdline;
    settings.bzimage_initrd_from_filesystem = test.bzimage_initrd_from_filesystem;
    settings.acpi = test.acpi === undefined && !test.state ? TEST_ACPI : test.acpi;
    settings.boot_order = test.boot_order;
    settings.cpuid_level = test.cpuid_level;
    settings.net_device = test.net_device;
    settings.disable_jit = DISABLE_JIT;

    if(test.expected_texts)
    {
        test.expected_texts = test.expected_texts.map(string_to_bytearray);
    }
    else
    {
        test.expected_texts = [];
    }

    if(!test.expected_serial_text)
    {
        test.expected_serial_text = [];
    }

    var emulator = new V86(settings);
    var screen = new Uint8Array(SCREEN_WIDTH * 25);

    function check_text_test_done()
    {
        return test.expected_texts.length === 0;
    }

    function check_serial_test_done()
    {
        return test.expected_serial_text.length === 0;
    }

    var mouse_test_done = false;
    function check_mouse_test_done()
    {
        return !test.expect_mouse_registered || mouse_test_done;
    }

    var graphical_test_done = false;
    var size_test_done = false;
    function check_graphical_test_done()
    {
        return !test.expect_graphical_mode || (graphical_test_done && (!test.expect_graphical_size || size_test_done));
    }

    var test_start = Date.now();

    var timeout_seconds = test.timeout * TIMEOUT_EXTRA_FACTOR;
    var timeout = setTimeout(check_test_done, (timeout_seconds + 1) * 1000);
    var timeouts = [timeout];

    var on_text = [];
    var stopped = false;

    var screen_interval = null;

    function check_test_done()
    {
        if(stopped)
        {
            return;
        }

        if(check_text_test_done() &&
            check_mouse_test_done() &&
            check_graphical_test_done() &&
            check_serial_test_done())
        {
            var end = Date.now();

            for(let timeout of timeouts) clearTimeout(timeout);
            stopped = true;

            emulator.stop();

            if(screen_interval !== null)
            {
                clearInterval(screen_interval);
            }

            console.warn("Passed test: %s (took %ds)", test.name, (end - test_start) / 1000);
            console.warn();

            done();
        }
        else if(Date.now() >= test_start + timeout_seconds * 1000)
        {
            for(let timeout of timeouts) clearTimeout(timeout);
            stopped = true;

            if(screen_interval !== null)
            {
                clearInterval(screen_interval);
            }

            emulator.destroy();

            if(test.failure_allowed)
            {
                console.warn("Test failed: %s (failure allowed)\n", test.name);
            }
            else
            {
                console.warn(screen_to_text(screen));
                console.warn("Test failed: %s\n", test.name);
            }

            if(!check_text_test_done())
            {
                console.warn('Expected text "%s" after %d seconds.', bytearray_to_string(test.expected_texts[0]), timeout_seconds);
            }

            if(!check_graphical_test_done())
            {
                console.warn("Expected graphical mode after %d seconds.", timeout_seconds);
            }

            if(!check_mouse_test_done())
            {
                console.warn("Expected mouse activation after %d seconds.", timeout_seconds);
            }

            if(!check_serial_test_done())
            {
                console.warn('Expected serial text "%s" after %d seconds.', test.expected_serial_text, timeout_seconds);
            }

            if(on_text.length)
            {
                console.warn(`Note: Expected text "${bytearray_to_string(on_text[0].text)}" to run "${on_text[0].run}"`);
            }

            if(!test.failure_allowed)
            {
                process.exit(1);
            }
            else
            {
                done();
            }
        }
    }

    emulator.add_listener("mouse-enable", function()
    {
        mouse_test_done = true;
        check_test_done();
    });

    emulator.add_listener("screen-set-size", function(args)
    {
        const [w, h, bpp] = args;
        graphical_test_done = bpp !== 0;

        if(test.expect_graphical_size)
        {
            size_test_done = w === test.expect_graphical_size[0] && h === test.expect_graphical_size[1];
        }

        check_test_done();
    });

    emulator.add_listener("screen-put-char", function(chr)
    {
        var y = chr[0];
        var x = chr[1];
        var code = chr[2];
        screen[x + SCREEN_WIDTH * y] = code;

        var line = get_line(screen, y);

        if(!check_text_test_done())
        {
            let expected = test.expected_texts[0];
            if(x < expected.length && bytearray_starts_with(line, expected))
            {
                test.expected_texts.shift();
                if(VERBOSE) console.log(`Passed: "${bytearray_to_string(expected)}" on screen (${test.name})`);
                check_test_done();
            }
        }

        if(on_text.length)
        {
            let expected = on_text[0].text;

            if(x < expected.length && bytearray_starts_with(line, expected))
            {
                var action = on_text.shift();

                timeouts.push(
                    setTimeout(() => {
                        if(VERBOSE) console.error("Sending '%s'", action.run);
                        if(typeof action.run[0] === "string") emulator.keyboard_send_text(action.run, 10);
                        else emulator.keyboard_send_scancodes(action.run, 10);
                    }, action.after || 0)
                );
            }
        }
    });

    if(LOG_SCREEN)
    {
        screen_interval = setInterval(() => {
            console.warn(screen_to_text(screen));
        }, 10000);
    }

    let serial_line = "";
    emulator.add_listener("serial0-output-byte", function(byte)
        {
            var c = String.fromCharCode(byte);
            if(c === "\n")
            {
                if(VERBOSE)
                {
                    console.log(`Serial (${test.name}):`, serial_line);
                }

                if(test.expected_serial_text.length)
                {
                    const expected = test.expected_serial_text[0];
                    if(serial_line.includes(expected))
                    {
                        test.expected_serial_text.shift();
                        if(VERBOSE) console.log(`Passed: "${expected}" on serial (${test.name})`);
                        check_test_done();
                    }
                }

                serial_line = "";
            }
            else if(c >= " " && c <= "~")
            {
                serial_line += c;
            }
        });

    test.actions && test.actions.forEach(function(action)
    {
        if(action.on_text)
        {
            on_text.push({ text: string_to_bytearray(action.on_text), run: action.run, after: action.after });
        }
        else
        {
            timeouts.push(
                setTimeout(() => {
                    if(VERBOSE) console.error("Sending '%s'", action.run);
                    if(typeof action.run[0] === "string") emulator.keyboard_send_text(action.run, 10);
                    else emulator.keyboard_send_scancodes(action.run, 10);
                }, action.after || 0)
            );
        }
    });
}
                                                                                                                                                                                                                                                                             source/v64/tests/glbridge/cpu_worker_audio_browser_test.html                                        0000644 0000000 0000000 00000003232 00000000000 021636  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>CPU Worker AudioWorklet</title><pre id="result">RUNNING</pre>
<script type="module">
import {V86} from "../../build/libv86.mjs";
const params=new URLSearchParams(location.search);
const irBackend=params.get("jit_backend")==="ir";
const corePath="../../build/v86.wasm";
const jitOptions=irBackend?{jit_backend:"ir"}:{};
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
let vm;
try {
    vm=new V86({graphics_adapter: "bochs_vga", cpu_worker:true,cpu_worker_url:"../../build/cpu-worker.js",wasm_path:corePath,...jitOptions,
        bios:{url:"../../build/cpu-worker-test.bin"},memory_size:32<<20,
        disable_keyboard:true,disable_mouse:true,net_device:{type:"none"},autostart:false});
    await Promise.race([new Promise((r,j)=>{vm.add_listener("emulator-loaded",r);vm.add_listener("emulator-error",j);}),sleep(10000).then(()=>{throw new Error("Audio initialization blocked on autoplay");})]);
    if(irBackend) {
        const info=await vm.get_jit_info();
        if(info.backend!=="ir"||!info.ir_available||!info.ir.enabled)
            throw new Error("IR backend policy did not reach AudioWorklet Worker");
    }
    if(!vm.speaker_adapter.dac.node_processor) throw new Error("AudioWorklet missing");
    await vm.run();await sleep(50);
    const state=await vm.save_state();
    await vm.restore_state(state);
    await vm.stop();await vm.destroy();vm=null;
    document.getElementById("result").textContent="PASS "+(irBackend?"IR ":"")+"AudioWorklet direct port initializes without autoplay, saves and restores";
} catch(e) {if(vm) vm.worker_controller.close();document.getElementById("result").textContent="FAIL "+e.stack;}
</script>
                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/glbridge/cpu_worker_browser_test.html                                              0000644 0000000 0000000 00000033624 00000000000 020465  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>CPU Worker integration</title>
<div id="screen"><div></div><canvas></canvas></div><pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
import { V86 } from "../../build/libv86.mjs";
const params = new URLSearchParams(location.search);
const irBackend = params.get("jit_backend") === "ir";
const corePath = "../../build/v86.wasm";
const jitOptions = irBackend ? { jit_backend: "ir" } : {};
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(r => setTimeout(r,ms));
const u32 = n => [n&255,n>>>8&255,n>>>16&255,n>>>24&255];
let vm;
try {
    let pending = Promise.resolve(), lastEvent, batches = 0, delay = 0, restored;
    // The real graphics proxy (device, channel, worker relay) with a slow fake
    // renderer: each batch answers with a delayed readback of its number
    const fakeBridge = (emulator, options) => {
        options.screenBackend.fallback(); // it does not draw the screen
        return { ready: Promise.resolve(), failed: null,
            pushPCIBatch(e) {
                lastEvent = e; ++batches;
                const n = batches;
                pending = pending.then(async () => { await sleep(delay); e.writeGuestMemory(4096, Uint8Array.of(n)); });
            },
            waitForSubmittedBatches: () => pending,
            waitForIdle: () => pending, prepareSaveState: () => pending,
            serializeCheckpoint: () => Uint8Array.of(1,2,3,4), releaseCheckpoint() {},
            beginStateRestore() {}, onPCIStateRestored: data => { restored = data; },
            finishStateRestore() {}, cancelStateRestore() {}, screenChanged() {}, destroy() {}, reset() {},
            makeScreenshot: () => null,
        };
    };
    const fakeGraphics = { createBridge: fakeBridge };
    vm = new V86({ graphics_adapter: "bochs_vga", cpu_worker: true, cpu_worker_url: "../../build/cpu-worker.js",
        wasm_path: corePath, ...jitOptions, bios: { url: "../../build/cpu-worker-test.bin" },
        memory_size: 32 << 20, screen: { container: document.getElementById("screen") },
        disable_keyboard: !irBackend, disable_mouse: !irBackend, disable_speaker: true,
        filesystem: {}, net_device: { type: "none" }, autostart: true, graphics_proxy: fakeGraphics });
    await Promise.race([new Promise((resolve,reject) => { vm.add_listener("emulator-loaded",resolve); vm.add_listener("emulator-error",reject); }), sleep(15000).then(()=>{throw new Error("startup timeout");})]);
    const assertIRBackend = async label => {
        if(!irBackend) return;
        const info = await vm.get_jit_info();
        check(info.backend === "ir" && info.ir_available && info.ir.enabled === 1,
            label + " selects the IR backend");
    };
    await assertIRBackend("initial Worker");
    const word = async a => new DataView((await vm.read_memory(a,4)).buffer).getUint32(0,true);
    const wait = async test => { const end=performance.now()+10000; while(!await test()) { if(performance.now()>end) throw new Error("guest timeout"); await sleep(5); } };
    await wait(async()=>await word(0x500)===0xCAFE);
    check(!vm.v86, "no CPU or guest RAM allocated on main thread");
    let first=await word(0x504);
    // Main-thread long task: worker must continue running during this interval.
    const end=performance.now()+150; while(performance.now()<end) {}
    check(await word(0x504)!==first,"CPU advances while main thread is blocked");
    await vm.stop(); first=await word(0x504); await sleep(30);
    check(await word(0x504)===first,"stop is acknowledged at a CPU boundary");
    await vm.run();
    async function launch(bytes) {
        await vm.write_memory(Uint8Array.from([...bytes,0xC3]),0x1200000);
        await vm.write_memory(Uint8Array.from(u32(0x1200000)),0x600);
    }
    async function program(bytes) {
        await launch(bytes);
        await wait(async()=>await word(0x600)===0);
    }
    if(irBackend) {
        const poll60=[0xE4,0x64,0xA8,0x01,0x74,0xFA];

        // Keyboard: guest enables scanning, consumes the 0xFA ACK, then waits
        // for KeyA make/break codes emitted by the real browser KeyboardAdapter.
        await vm.write_memory(new Uint8Array(8),0x710);
        await launch([
            0xBA,0x60,0,0,0, 0xB0,0xF4,0xEE,
            ...poll60,0xE4,0x60,0xA2,...u32(0x712),
            0xB0,1,0xA2,...u32(0x714),
            ...poll60,0xE4,0x60,0xA2,...u32(0x710),
            ...poll60,0xE4,0x60,0xA2,...u32(0x711),
        ]);
        await wait(async()=>(await vm.read_memory(0x714,1))[0]===1);
        const canvas=document.querySelector("#screen canvas");
        canvas.dispatchEvent(new KeyboardEvent("keydown",{code:"KeyA",key:"a",bubbles:true}));
        canvas.dispatchEvent(new KeyboardEvent("keyup",{code:"KeyA",key:"a",bubbles:true}));
        await wait(async()=>await word(0x600)===0);
        const keyboard=await vm.read_memory(0x710,3);
        check(keyboard[0]===0x1E && keyboard[1]===0x9E && keyboard[2]===0xFA,
            "DOM keyboard make/break crosses Worker into guest PS/2 while IR is selected");

        // Mouse: guest enables the second PS/2 port and streaming. Waiting for
        // mouse_adapter.enabled proves the Worker's mouse-enable device event
        // reached the main-thread adapter before the DOM movement is injected.
        await vm.write_memory(new Uint8Array(8),0x720);
        await launch([
            0xB0,0xA8,0xE6,0x64,
            0xB0,0xD4,0xE6,0x64,0xB0,0xF4,0xE6,0x60,
            ...poll60,0xE4,0x60,0xA2,...u32(0x723),
            0xB0,1,0xA2,...u32(0x724),
            ...poll60,0xE4,0x60,0xA2,...u32(0x720),
            ...poll60,0xE4,0x60,0xA2,...u32(0x721),
            ...poll60,0xE4,0x60,0xA2,...u32(0x722),
        ]);
        await wait(async()=>(await vm.read_memory(0x724,1))[0]===1);
        await wait(()=>vm.mouse_adapter?.enabled===true);
        const move=new MouseEvent("mousemove",{clientX:16,clientY:12,bubbles:true});
        Object.defineProperty(move,"movementX",{value:6});
        Object.defineProperty(move,"movementY",{value:-4});
        canvas.dispatchEvent(move);
        await wait(async()=>await word(0x600)===0);
        const mouse=await vm.read_memory(0x720,5);
        check(mouse[3]===0xFA && mouse[0]===0x08 && mouse[1]===6 && mouse[2]===4,
            "DOM mouse movement crosses Worker into streamed guest PS/2 packet while IR is selected");
    }
    const floppy=new Uint8Array(1440*1024);floppy[0]=95;
    await vm.set_fda({buffer:floppy.buffer});
    check((await vm.get_disk_fda())[0]===95 && (await vm.get_disk_fda())[0]===95,"floppy export never detaches the live disk");
    check(new Uint8Array(await vm.worker_controller.rpc("disk",["fda"]))[0]===95 && (await vm.get_disk_fda())[0]===95,"disk download preserves worker backing storage");
    await vm.eject_fda();
    check(await vm.get_disk_fda()===null,"empty floppy preserves the public null result");
    await vm.create_file("worker.txt",Uint8Array.of(4,5,6));
    check((await vm.read_file("worker.txt")).join()==="4,5,6" && (await vm.read_file("worker.txt")).join()==="4,5,6","9p reads return copies without detaching filesystem data");
    const out = (port,value,size) => [0xBA,...u32(port),0xB8,...u32(value),...(size===1?[0xEE]:size===2?[0x66,0xEF]:[0xEF])];
    let vbe=[];
    for(const [reg,value] of [[4,0],[1,64],[2,64],[3,32],[4,0x41]]) vbe.push(...out(0x1CE,reg,2),...out(0x1CF,value,2));
    vbe.push(0xC7,0x05,...u32(0xE0000000),...u32(0x0000FF00));
    await program(vbe);
    await wait(()=>vm.screen_adapter.is_graphical() && vm.screen_adapter.get_graphics_canvas().getContext("2d").getImageData(0,0,1,1).data[1]===255);
    check(true,"VGA dirty pixels cross worker boundary into the DOM canvas");
    // Actual guest OUT instructions configure the real virtio PCI device.
    let setup=[];
    for(const [off,v,size] of [[20,0,1],[20,3,1],[8,0,4],[12,1,4],[8,1,4],[12,1,4],[20,11,1],[22,0,2],[24,8,2],[32,0x10000,4],[36,0,4],[40,0x10080,4],[44,0,4],[48,0x100A0,4],[52,0,4],[28,1,2],[20,15,1]]) setup.push(...out(0xF100+off,v,size));
    const mem=new Uint8Array(320), view=new DataView(mem.buffer);
    view.setUint32(0,0x10100,true);view.setUint32(8,24,true);view.setUint16(12,1,true);view.setUint16(14,1,true);
    view.setUint32(16,0x10120,true);view.setUint32(24,16,true);view.setUint16(28,2,true);view.setUint16(128,1,true);
    await vm.write_memory(mem,0x10000);await program(setup);
    let idx=0;
    async function request(op,addr,len) {
        await vm.write_memory(Uint8Array.from([op,addr,0,len,0,0].flatMap(u32)),0x10100);
        await vm.write_memory(new Uint8Array(4).fill(255),0x10120);
        await vm.write_memory(Uint8Array.of(++idx&255,idx>>>8),0x10082);
        await program(out(0xF200,0,2));
        await wait(async()=>await word(0x10120)!==0xFFFFFFFF);
        check(await word(0x10120)===0,"virtqueue request accepted "+op);
    }
    await request(1,0x100000,16<<20);
    await vm.write_memory(Uint8Array.from([0x324c4756,1,0,42,1,4,0,0,0xFFF1].flatMap(u32)),0x100000);
    delay=100;
    await request(2,0,36);
    // Burst inside one guest execution callback: descriptors must remain
    // pending when the transport fills, then resume without lost commands.
    const burst=[];
    for(let n=0;n<12;n++) {
        idx++;
        burst.push(0x66,0xC7,0x05,...u32(0x10082),idx&255,idx>>>8,...out(0xF200,0,2));
        // Wait for the used ring before reusing the request descriptors.
        burst.push(0x66,0x81,0x3D,...u32(0x100A2),idx&255,idx>>>8,0x75,0xF5);
    }
    await program(burst);
    const saved = await vm.save_state(); // Must wait for delayed GPU write.
    check((await vm.read_memory(0x101000,1))[0]===13,"save drains GPU readback into worker-owned RAM");
    check(vm.graphics_proxy.stats.graphics_peak_pending<=8 && vm.graphics_proxy.stats.graphics_peak_pending>1,"graphics backpressure bounds outstanding batches without loss");
    const oldWrite=lastEvent.writeGuestMemory, oldEpoch=vm.worker_controller.epoch;
    await vm.write_memory(Uint8Array.of(99),0x101000);
    await vm.restore_state(saved);
    check(vm.worker_controller.epoch>oldEpoch,"restore changes memory generation");
    oldWrite(4096,Uint8Array.of(77));await sleep(30);
    check((await vm.read_memory(0x101000,1))[0]===13,"late old-generation GPU writes cannot corrupt restored RAM");
    check(restored.join(",")==="1,2,3,4","graphics checkpoint round-trips inside ordinary v86 state");
    check(saved.byteLength>0,"save input remains owned by caller after restore");
    let pcm, rate;
    vm.add_listener("dac-send-data", data => { pcm=data; });
    vm.add_listener("dac-tell-sampling-rate", value => { rate=value; });
    await program([...out(0x22C,0x41,1),...out(0x22C,0x56,1),...out(0x22C,0x22,1),
        ...out(0x22C,0x10,1),...out(0x22C,255,1)]);
    vm.bus.send("dac-request-data");
    await wait(()=>!!pcm);
    check(rate===22050 && pcm[0][0]===1 && pcm[1][0]===1,"SB16 sample rate and PCM survive worker transfer");
    let rejected=false;
    try { await vm.restore_state(new ArrayBuffer(8)); } catch(_) { rejected=true; }
    check(rejected && !vm.is_running(),"failed restore leaves CPU stopped and rejects caller");
    await vm.restore_state(saved);
    check((await vm.read_memory(0x101000,1))[0]===13,"good checkpoint recovers after a rejected restore");
    await vm.stop();
    await assertIRBackend("post-device workload Worker");
    const state2=await vm.save_state();
    await vm.destroy();vm=null;
    // Boot directly from a saved state, including the graphics checkpoint.
    vm=new V86({graphics_adapter: "bochs_vga", cpu_worker:true,cpu_worker_url:"../../build/cpu-worker.js",wasm_path: corePath, ...jitOptions,
        bios:{url:"../../build/cpu-worker-test.bin"},initial_state:{buffer:state2},memory_size:32<<20,
        screen:{container:document.getElementById("screen")},disable_keyboard:true,disable_mouse:true,disable_speaker:true,
        filesystem:{},net_device:{type:"none"},graphics_proxy:fakeGraphics,autostart:false});
    await new Promise((r,j)=>{vm.add_listener("emulator-loaded",r);vm.add_listener("emulator-error",j);});
    await assertIRBackend("restored Worker");
    check(!vm.is_running(),"initial-state load preserves requested stopped mode");
    check((await vm.read_memory(0x101000,1))[0]===13,"initial state restores worker RAM");
    await vm.destroy();await vm.destroy();vm=null;
    vm=new V86({graphics_adapter: "bochs_vga", wasm_path: corePath, ...jitOptions,bios:{url:"../../build/cpu-worker-test.bin"},
        memory_size:32<<20,screen:{container:document.getElementById("screen")},
        disable_keyboard:true,disable_mouse:true,disable_speaker:true,
        filesystem:{},net_device:{type:"none"},graphics_proxy:fakeGraphics,autostart:false});
    await new Promise(r=>vm.add_listener("emulator-loaded",r));
    await assertIRBackend("main-thread restore");
    await vm.restore_state(state2);
    check(vm.read_memory(0x101000,1)[0]===13,"main-thread mode loads a worker snapshot");
    const legacy=await vm.save_state();await vm.destroy();vm=null;
    vm=new V86({graphics_adapter: "bochs_vga", cpu_worker:true,cpu_worker_url:"../../build/cpu-worker.js",wasm_path: corePath, ...jitOptions,
        bios:{url:"../../build/cpu-worker-test.bin"},initial_state:{buffer:legacy},memory_size:32<<20,
        screen:{container:document.getElementById("screen")},disable_keyboard:true,disable_mouse:true,disable_speaker:true,
        filesystem:{},net_device:{type:"none"},graphics_proxy:fakeGraphics,autostart:false});
    await new Promise((r,j)=>{vm.add_listener("emulator-loaded",r);vm.add_listener("emulator-error",j);});
    await assertIRBackend("cross-mode Worker restore");
    check((await vm.read_memory(0x101000,1))[0]===13,"worker mode loads a main-thread snapshot");
    await vm.destroy();vm=null;
    document.getElementById("result").textContent="PASS\n"+checks.join("\n");
} catch(error) {
    if(vm) await vm.destroy().catch(()=>{});
    document.getElementById("result").textContent="FAIL\n"+error.stack+"\n"+checks.join("\n");
}
</script>
                                                                                                            source/v64/tests/glbridge/cpu_worker_gpu_browser_test.html                                          0000644 0000000 0000000 00000015077 00000000000 021342  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>CPU Worker integration</title>
<div id="screen"><div></div><canvas></canvas></div><pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
import { V86 } from "../../build/libv86.mjs";
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(r => setTimeout(r,ms));
const u32 = n => [n&255,n>>>8&255,n>>>16&255,n>>>24&255];
let vm;
try {
    vm = new V86({ graphics_adapter: "bochs_vga", cpu_worker: true, cpu_worker_url: "../../build/cpu-worker.js",
        wasm_path: "../../build/v86.wasm", bios: { url: "../../build/cpu-worker-test.bin" },
        memory_size: 32 << 20, screen: { container: document.getElementById("screen") },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" }, autostart: true, graphics_proxy: true });
    await Promise.race([new Promise((resolve,reject) => { vm.add_listener("emulator-loaded",resolve); vm.add_listener("emulator-error",reject); }), sleep(15000).then(()=>{throw new Error("startup timeout");})]);
    const word = async a => new DataView((await vm.read_memory(a,4)).buffer).getUint32(0,true);
    const wait = async test => { const end=performance.now()+10000; while(!await test()) { if(performance.now()>end) throw new Error("guest timeout"); await sleep(5); } };
    await wait(async()=>await word(0x500)===0xCAFE);
    check(!vm.v86, "no CPU or guest RAM allocated on main thread");
    let first=await word(0x504);
    // Main-thread long task: worker must continue running during this interval.
    const end=performance.now()+150; while(performance.now()<end) {}
    check(await word(0x504)!==first,"CPU advances while main thread is blocked");
    await vm.stop(); first=await word(0x504); await sleep(30);
    check(await word(0x504)===first,"stop is acknowledged at a CPU boundary");
    await vm.run();
    async function program(bytes) {
        await vm.write_memory(Uint8Array.from([...bytes,0xC3]),0x1200000);
        await vm.write_memory(Uint8Array.from(u32(0x1200000)),0x600);
        await wait(async()=>await word(0x600)===0);
    }
    const out = (port,value,size) => [0xBA,...u32(port),0xB8,...u32(value),...(size===1?[0xEE]:size===2?[0x66,0xEF]:[0xEF])];
    // Establish the display mode in the guest, so it is part of the snapshot.
    // Changing only the host adapter would save text-mode VGA and race its
    // restoration against the GPU overlay visibility callbacks.
    let vbe=[];
    for(const [reg,value] of [[4,0],[1,64],[2,64],[3,32],[4,0x41]]) vbe.push(...out(0x1CE,reg,2),...out(0x1CF,value,2));
    await program(vbe);
    await wait(()=>vm.screen_adapter.is_graphical());
    // Actual guest OUT instructions configure the real virtio PCI device.
    let setup=[];
    for(const [off,v,size] of [[20,0,1],[20,3,1],[8,0,4],[12,1,4],[8,1,4],[12,1,4],[20,11,1],[22,0,2],[24,8,2],[32,0x10000,4],[36,0,4],[40,0x10080,4],[44,0,4],[48,0x100A0,4],[52,0,4],[28,1,2],[20,15,1]]) setup.push(...out(0xF100+off,v,size));
    const mem=new Uint8Array(320), view=new DataView(mem.buffer);
    view.setUint32(0,0x10100,true);view.setUint32(8,24,true);view.setUint16(12,1,true);view.setUint16(14,1,true);
    view.setUint32(16,0x10120,true);view.setUint32(24,16,true);view.setUint16(28,2,true);view.setUint16(128,1,true);
    await vm.write_memory(mem,0x10000);await program(setup);
    let idx=0;
    async function request(op,addr,len) {
        await vm.write_memory(Uint8Array.from([op,addr,0,len,0,0].flatMap(u32)),0x10100);
        await vm.write_memory(new Uint8Array(4).fill(255),0x10120);
        await vm.write_memory(Uint8Array.of(++idx&255,idx>>>8),0x10082);
        await program(out(0xF200,0,2));
        await wait(async()=>await word(0x10120)!==0xFFFFFFFF);
        check(await word(0x10120)===0,"virtqueue request accepted "+op);
    }
    await request(1,0x100000,16<<20);
    await vm.write_memory(Uint8Array.from([0x324c4756,1,0,42,1,4,0,0,0xFFF1].flatMap(u32)),0x100000);
        const session = [0xd0090001,0x20260806];
        const commands = [
            [1,[32,0,...session]], // HELLO
            [2,[1,0x1234,0,0,64,64,22,1,0x20,1,75,0,0]], // CREATE_DEVICE
            [5,[1,1,0xffff0000,0x3f800000,0,0]], // CLEAR red
            [4,[1,0x1234,0,0,64,64]], // PRESENT
        ];
        const sizes = commands.map(([,values]) => (16+values.length*4+7)&~7);
        const batchBytes = 32 + sizes.reduce((a,b)=>a+b,0);
        const wrapped = new Uint8Array(8 + batchBytes);
        const d9 = new DataView(wrapped.buffer);
        d9.setUint16(0,0xffe1,true); d9.setUint16(2,0xffff,true);
        d9.setUint32(4,batchBytes,true);
        d9.setUint32(8,0x47573944,true);
        d9.setUint16(12,1,true); d9.setUint16(14,3,true);
        [1,1,commands.length,batchBytes-32,...session].forEach((v,i)=>d9.setUint32(16+i*4,v,true));
        let cursor = 40;
        commands.forEach(([op,values],i)=>{
            d9.setUint16(cursor,op,true); d9.setUint32(cursor+4,sizes[i],true);
            d9.setUint32(cursor+8,i+1,true);
            values.forEach((v,j)=>d9.setUint32(cursor+16+j*4,v,true));
            cursor += sizes[i];
        });

    const header=Uint8Array.from([0x324c4756,1,0,1,1,wrapped.length,0x47573944,0].flatMap(u32));
    await vm.write_memory(header,0x100000);
    await vm.write_memory(wrapped,0x100020);
    await request(2,0,32+wrapped.length);
    await vm.stop();
    const bridge=vm.graphics_proxy.bridge;
    check(!bridge.failed && !bridge.d3d9Executor.failed,"real WebGPU D3D9 worker batch executes");
    const color=async()=>{
        await bridge.waitForIdle(false);
        const shot=bridge.makeScreenshot();
        if(!shot) throw new Error("missing GPU screenshot");
        await shot.decode();
        const c=document.createElement("canvas");c.width=c.height=64;
        const ctx=c.getContext("2d");ctx.drawImage(shot,0,0);
        return [...ctx.getImageData(32,32,1,1).data].join();
    };
    const actual=await color();
    check(actual==="255,0,0,255","worker virtqueue produces real red GPU pixels: "+actual);
    const saved=await vm.save_state();
    await vm.restore_state(saved);
    const restoredColor=await color();
    check(restoredColor==="255,0,0,255","GPU checkpoint restores saved frame through worker barrier: "+restoredColor);
    await vm.destroy();vm=null;
    document.getElementById("result").textContent="PASS\n"+checks.join("\n");
} catch(error) {
    if(vm) await vm.destroy().catch(()=>{});
    document.getElementById("result").textContent="FAIL\n"+error.stack+"\n"+checks.join("\n");
}
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/glbridge/cpu_worker_hotplug_browser_test.html                                      0000644 0000000 0000000 00000007705 00000000000 022230  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>CPU Worker: PCI Express hot plug</title>
<pre id="result">RUNNING</pre>
<script type="module">
// V86.attach_pcie_device and detach_pcie_device with the CPU in a Worker: the
// built-in devices' placements behind the root ports reach the worker, its
// errors come back, and a removal through the attention button (which waits
// for the guest; SeaBIOS never answers) holds back none of the commands
// after it, until a reset gives it up
import { V86 } from "../../build/libv86.mjs";
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const within = (promise, ms, what) => Promise.race([promise, sleep(ms).then(() => { throw new Error(what + ": no answer in " + ms + " ms"); })]);
const outcome = promise => promise.then(() => "ok", error => "error: " + (error && error.message || error));
let vm;
try {
    vm = new V86({ graphics_adapter: "bochs_vga", cpu_worker: true, cpu_worker_url: "../../build/cpu-worker.js",
        wasm_path: "../../build/v86.wasm", bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
        machine_type: "q35", pcie_root_ports: 4, memory_size: 64 << 20,
        net_device: { type: "virtio", pcie_root_port: 0 },
        virtio_console: { pcie_root_port: 1, pcie_plugged: false },
        virtio_balloon: { pcie_root_port: 2 },
        filesystem: { pcie_root_port: 3 },
        screen_dummy: true, disable_keyboard: true, disable_mouse: true, disable_speaker: true, autostart: true });
    await within(new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); }),
        15000, "startup");
    check(!vm.v86, "the CPU runs in the Worker");
    check(await outcome(vm.attach_pcie_device(1)) === "ok", "the console, out of its slot at boot, plugs in (its placement reached the Worker)");
    for(const [port, name] of [[0, "virtio-net"], [1, "the console"], [2, "the balloon"], [3, "9p"]])
    {
        check(await outcome(vm.detach_pcie_device(port, { surprise: true })) === "ok" && await outcome(vm.attach_pcie_device(port)) === "ok",
            name + " behind root port " + port + ": pulled out and plugged in again");
    }
    check(/attach_pcie_device: no root port 5 \(machine_type "q35", pcie_root_ports: 4\)/.test(await outcome(vm.attach_pcie_device(5))),
        "attaching to a root port the machine lacks: the Worker's error");
    check(/detach_pcie_device: no root port 7/.test(await outcome(vm.detach_pcie_device(7))),
        "detaching from a root port the machine lacks: the Worker's error");

    check(await outcome(vm.detach_pcie_device(1)) === "ok" && await outcome(vm.attach_pcie_device(1)) === "ok",
        "the console's slot is off (empty at boot, and no OS switches it on): its card leaves at once");
    const button = outcome(vm.detach_pcie_device(0));
    check(await Promise.race([button.then(() => "settled"), sleep(1000).then(() => "pending")]) === "pending",
        "removal through the attention button from the NIC's powered slot: waiting for the guest");
    await within(vm.stop(), 5000, "stop");
    await within(vm.run(), 5000, "run");
    const state = await within(vm.save_state(), 10000, "save_state");
    check(state.byteLength > 0, "stop, run and save_state answer meanwhile");
    await within(vm.restart(), 10000, "restart");
    check(/the machine was reset before the guest released the device/.test(await within(button, 5000, "the removal after the reset")),
        "a reset gives the removal up");
    check(await outcome(vm.attach_pcie_device(0)) === "ok", "the card stayed in");
    await vm.destroy();
    vm = null;
    document.getElementById("result").textContent = "PASS\n" + checks.join("\n");
} catch(error) {
    if(vm) await vm.destroy().catch(() => {});
    document.getElementById("result").textContent = "FAIL\n" + error.stack + "\n" + checks.join("\n");
}
</script>
                                                           source/v64/tests/glbridge/cpu_worker_screen_test.mjs                                                0000644 0000000 0000000 00000003343 00000000000 020101  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import { CPUWorkerController } from "../../src/browser/cpu_worker.js";

// A text redraw burst can exceed the engine's function argument limit.
// Drive the actual receiver and dispatch, checking order and epoch filtering.
// The page sends each character's screen-put-char (the worker does not),
// once the screen adapter has the character.
const controller = Object.create(CPUWorkerController.prototype);
let expected = 0, events = 0;
controller.epoch = 7;
controller.screen_queue = [];
controller.emulator = {
    screen_adapter: { put_char(index, row, character) {
        assert.equal(index, expected++);
        assert.equal(row, 0);
        assert.equal(character, 65);
    } },
    emulator_bus: { send(name, value) {
        assert.equal(name, "screen-put-char");
        assert.deepEqual(value, [events, 0, 65]);
        assert.equal(expected, ++events, "the event after the character");
    } },
};
const commands = Array.from({ length: 300000 }, (_, i) => ["put_char", [i, 0, 65]]);
controller.receive({ type: "screen", epoch: 6, commands });
assert.equal(expected, 0, "discard stale screen updates");
controller.receive({ type: "screen", epoch: 7, commands });
assert.equal(expected, commands.length, "deliver every command in order");
assert.equal(controller.screen_queue.length, 0);
controller.receive({ type: "screen", epoch: 7, commands: [] });
controller.receive({ type: "screen", epoch: 7, commands: [["put_char", [expected, 0, 65]]] });
assert.equal(expected, 300001, "continue receiving after a large burst");
assert.equal(events, expected, "one screen-put-char a character");
console.log("PASS: 300000-command Worker screen burst, order, stale epoch and subsequent update, the characters' events");
                                                                                                                                                                                                                                                                                             source/v64/tests/glbridge/cpu_worker_svga_browser_test.html                                         0000644 0000000 0000000 00000016611 00000000000 021502  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>CPU Worker: VMware SVGA II 3D</title>
<div id="screen"><div></div><canvas></canvas></div><pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// With a CPU worker the VMware SVGA II device runs in the worker and its 3D
// renderer (V86SVGARenderer, WebGPU) on this page: their messages cross the
// worker boundary. The guest finds the card on PCI, defines a GMR in its RAM
// by registers, and submits a command buffer that defines a surface and a
// context, clears the surface, and DMAs it into the GMR; the renderer's
// readback has to land in guest RAM before the buffer completes.
import { V86 } from "../../build/libv86.mjs";
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];
let vm;
try {
    vm = new V86({ graphics_adapter: "vmware_svga", graphics_adapter_path: "../../build/v86-vmware-svga.js",
        cpu_worker: true, cpu_worker_url: "../../build/cpu-worker.js",
        wasm_path: "../../build/v86.wasm", bios: { url: "../../build/cpu-worker-test.bin" },
        memory_size: 32 << 20, screen: { container: document.getElementById("screen") },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" }, autostart: true });
    await Promise.race([new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); }),
        sleep(20000).then(() => { throw new Error("startup timeout"); })]);
    const word = async a => new DataView((await vm.read_memory(a, 4)).buffer).getUint32(0, true);
    const wait = async (test, what) => { const end = performance.now() + 15000; while(!await test()) { if(performance.now() > end) throw new Error("timeout: " + what); await sleep(5); } };
    await wait(async () => await word(0x500) === 0xCAFE, "the test BIOS");
    check(!vm.v86, "no CPU or guest RAM on this page");
    check(vm.adapter_renderer, "the SVGA renderer is on this page");

    async function program(bytes) {
        await vm.write_memory(Uint8Array.from([...bytes, 0xC3]), 0x1200000);
        await vm.write_memory(Uint8Array.from(u32(0x1200000)), 0x600);
        await wait(async () => await word(0x600) === 0, "a guest program");
    }
    // pciscan: finds 15AD:0405, enables it, its I/O base into [0x700]
    await program([0x31,0xc9,0x89,0xc8,0xc1,0xe0,0x0b,0x0d,0x00,0x00,0x00,0x80,0xba,0xf8,0x0c,0x00,0x00,0xef,0xba,0xfc,0x0c,
        0x00,0x00,0xed,0x3d,0xad,0x15,0x05,0x04,0x74,0x11,0x41,0x83,0xf9,0x20,0x72,0xdd,0xc7,0x05,0x00,0x07,0x00,0x00,0xff,0xff,
        0xff,0xff,0xc3,0x89,0xc8,0xc1,0xe0,0x0b,0x0d,0x04,0x00,0x00,0x80,0xba,0xf8,0x0c,0x00,0x00,0xef,0xba,0xfc,0x0c,0x00,0x00,
        0xed,0x83,0xc8,0x07,0xef,0x89,0xc8,0xc1,0xe0,0x0b,0x0d,0x10,0x00,0x00,0x80,0xba,0xf8,0x0c,0x00,0x00,0xef,0xba,0xfc,0x0c,
        0x00,0x00,0xed,0x83,0xe0,0xfc,0xa3,0x00,0x07,0x00,0x00]);
    const io = await word(0x700);
    check(io !== 0xFFFFFFFF && io > 0, "the SVGA card is on PCI, I/O at 0x" + io.toString(16));
    // SVGA registers: index port io+0, value port io+1
    const out32 = (port, value) => [0xBA, ...u32(port), 0xB8, ...u32(value), 0xEF];
    const in32 = port => [0xBA, ...u32(port), 0xED];
    const reg = (index, value) => [...out32(io, index), ...out32(io + 1, value)];
    // the device's capabilities into [0x704]: 3D needs the renderer
    await program([...out32(io, 0x11 /* SVGA_REG_CAPABILITIES */), ...in32(io + 1), 0xA3, ...u32(0x704)]);
    const caps = await word(0x704);
    check(caps & 0x4000 /* SVGA_CAP_3D */, "the device offers 3D, its renderer found (caps 0x" + caps.toString(16) + ")");

    // GMR 1: one page at 0x301000, by its descriptor at 0x300000
    await vm.write_memory(Uint8Array.from([0x301, 1, 0, 0].flatMap(u32)), 0x300000);
    await vm.write_memory(new Uint8Array(4096).fill(0xEE), 0x301000);
    // the commands: a 16x16 surface, a context, a clear, the surface into the GMR
    const command = (id, ...body) => [id, body.length * 4, ...body];
    const commands = [
        ...command(0x410 /* SURFACE_DEFINE */, 1, 0x40, 1 /* X8R8G8B8 */, 1, 0, 0, 0, 0, 0, 16, 16, 1),
        ...command(0x415 /* CONTEXT_DEFINE */, 1),
        ...command(0x41A /* SETRENDERTARGET */, 1, 2 /* COLOR0 */, 1, 0, 0),
        ...command(0x421 /* CLEAR */, 1, 1 /* COLOR */, 0xFF336699, f32(1), 0, 0, 0, 16, 16),
        ...command(0x414 /* SURFACE_DMA */, 1, 0, 64, 1, 0, 0, 2 /* READ_HOST_VRAM */, 0, 0, 0, 16, 16, 1, 0, 0, 0),
    ];
    // an SVGACBHeader at 0x200000, its commands at 0x200040
    const header = [0, 0, 0, 0, 0 /* flags */, commands.length * 4, 0x200040, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    await vm.write_memory(Uint8Array.from(header.flatMap(u32)), 0x200000);
    await vm.write_memory(Uint8Array.from(commands.flatMap(u32)), 0x200040);
    await program([...reg(0 /* ID */, 0x90000002), ...reg(0x29 /* GMR_ID */, 1), ...reg(0x2A /* GMR_DESCRIPTOR */, 0x300),
        ...reg(0x31 /* COMMAND_HIGH */, 0), ...reg(0x30 /* COMMAND_LOW */, 0x200000)]);
    await wait(async () => await word(0x200000) !== 0, "the command buffer's status");
    check(await word(0x200000) === 1, "the command buffer completed (status " + await word(0x200000) + ")");
    const pixels = await vm.read_memory(0x301000, 16 * 16 * 4);
    const pixel = i => Array.from(pixels.subarray(i * 4, i * 4 + 3)).join();
    check(pixel(0) === "153,102,51" && pixel(255) === "153,102,51",
        "the renderer's clear, read back into guest RAM through the worker: " + pixel(0) + " / " + pixel(255));
    const stats = vm.adapter_renderer.executor.stats;
    check(stats.batches >= 1 && !stats.commandsFailed, "the renderer on this page ran the batches (" + stats.batches + ")");

    // A snapshot carries the surface's contents (read back from the renderer
    // on this page) and the restored device puts them on the GPU again: the
    // same DMA after a restore reads the same pixels
    const saved = await vm.save_state();
    await vm.restore_state(saved);
    await wait(async () => await word(0x500) === 0xCAFE, "the test BIOS after the restore");
    await vm.write_memory(new Uint8Array(4096).fill(0xEE), 0x301000);
    const again = command(0x414 /* SURFACE_DMA */, 1, 0, 64, 1, 0, 0, 2, 0, 0, 0, 16, 16, 1, 0, 0, 0);
    await vm.write_memory(Uint8Array.from([0, 0, 0, 0, 0, again.length * 4, 0x200040, 0, 0, 0, 0, 0, 0, 0, 0, 0].flatMap(u32)), 0x200000);
    await vm.write_memory(Uint8Array.from(again.flatMap(u32)), 0x200040);
    await program([...reg(0x31, 0), ...reg(0x30, 0x200000)]);
    await wait(async () => await word(0x200000) !== 0, "the command buffer's status after the restore");
    const restored = await vm.read_memory(0x301000, 16 * 16 * 4);
    check(Array.from(restored.subarray(0, 3)).join() === "153,102,51" && Array.from(restored.subarray(1020, 1023)).join() === "153,102,51",
        "after a save and restore the surface still has the clear: " + Array.from(restored.subarray(0, 3)).join());

    await vm.destroy(); vm = null;
    document.getElementById("result").textContent = "PASS\n" + checks.join("\n");
} catch(error) {
    if(vm) await vm.destroy().catch(() => {});
    document.getElementById("result").textContent = "FAIL\n" + error.stack + "\n" + checks.join("\n");
}
</script>
                                                                                                                       source/v64/tests/glbridge/cube2_glsl_direct_corpus_r6889.js                                         0000644 0000000 0000000 00000050466 00000000000 021004  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

/*
 * Every literal `shader ... [vertex] [fragment]` and
 * `lazyshader ... [vertex] [fragment]` pair in the official Cube 2 r6889
 * data/glsl.cfg whose two blocks contain no CubeScript substitution.
 * Extracted from the 112302-byte source snapshot with SHA-256:
 * cd8963aedfcfb2285e0a2750d7cb7384c1c5ac3fdd7b125b462ede400bee47a4
 *
 * The two other top-level shader pairs, noglareblendworld and screenrect,
 * require macro substitution; their resolved forms are covered separately.
 */
globalThis.CUBE2_DIRECT_GLSL_CORPUS_R6889 = Object.freeze([
  {
    "name": "null",
    "vertex": "attribute vec4 vvertex;\n    void main(void)\n    {\n        gl_Position = vvertex;\n    }",
    "fragment": "void main(void)\n    {\n        gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);\n    }"
  },
  {
    "name": "hud",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 hudmatrix;\n    varying vec2 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = hudmatrix * vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec2 texcoord0;\n    varying vec4 color;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0);\n    }"
  },
  {
    "name": "hudnotexture",
    "vertex": "attribute vec4 vvertex, vcolor;\n    uniform mat4 hudmatrix;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = hudmatrix * vvertex;\n        color = vcolor;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "hudrgb",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 hudmatrix;\n    varying vec2 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = hudmatrix * vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec2 texcoord0;\n    varying vec4 color;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor.rgb = color.rgb * texture2D(tex0, texcoord0).rgb;\n        gl_FragColor.a   = color.a;\n    }"
  },
  {
    "name": "texture",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 camprojmatrix;\n    varying vec2 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec2 texcoord0;\n    varying vec4 color;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0);\n    }"
  },
  {
    "name": "notexture",
    "vertex": "attribute vec4 vvertex, vcolor;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "cubemap",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec3 vtexcoord0;\n    varying vec3 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec3 texcoord0;\n    varying vec4 color;\n    uniform samplerCube tex0;\n    void main(void)\n    {\n        gl_FragColor = color * textureCube(tex0, texcoord0);\n    }"
  },
  {
    "name": "fogged",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 camprojmatrix;\n    varying vec2 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec2 texcoord0;\n    varying vec4 color;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0);\n    }"
  },
  {
    "name": "foggednotexture",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "fogoverlay",
    "vertex": "attribute vec4 vvertex, vcolor;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = vvertex;\n        color = vcolor;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "nocolor",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    void main() { gl_Position = camprojmatrix * vvertex; }",
    "fragment": "void main() {}"
  },
  {
    "name": "bbquery",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    uniform vec3 bborigin, bbsize;\n    void main() { gl_Position = camprojmatrix * vec4(bborigin + vvertex.xyz*bbsize, vvertex.w); }",
    "fragment": "void main() {}"
  },
  {
    "name": "fogworld",
    "vertex": "//:water\n    attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n    }",
    "fragment": "uniform vec3 fogcolor;\n    void main(void)\n    {\n        gl_FragColor = vec4(fogcolor, 1.0);\n    }"
  },
  {
    "name": "noglareworld",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n    }",
    "fragment": "void main(void)\n    {\n        gl_FragColor = vec4(0.0);\n    }"
  },
  {
    "name": "noglarealphaworld",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n    }",
    "fragment": "uniform vec4 colorparams;\n    uniform sampler2D lightmap;\n    void main(void)\n    {\n        gl_FragColor.rgb = vec3(0.0);\n        gl_FragColor.a = colorparams.a;\n    }"
  },
  {
    "name": "depthfxworld",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    uniform vec4 depthscale, depthoffsets;\n    varying vec4 depthranges;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        depthranges = depthoffsets + gl_Position.w*depthscale;\n    }",
    "fragment": "varying vec4 depthranges;\n    void main(void)\n    {\n        gl_FragColor = depthranges;\n    }"
  },
  {
    "name": "depthfxsplitworld",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    uniform vec4 depthscale, depthoffsets;\n    varying vec4 depthranges;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        depthranges = depthoffsets + gl_Position.w*depthscale;\n    }",
    "fragment": "varying vec4 depthranges;\n    void main(void)\n    {\n        vec4 ranges = vec4(depthranges.x, fract(depthranges.yzw));\n        ranges.xy -= ranges.yz*vec2(0.00390625, 0.00390625);\n        gl_FragColor = ranges;\n    }"
  },
  {
    "name": "shadowmapreceiver",
    "vertex": "attribute vec4 vvertex;\n    uniform mat4 shadowmatrix;\n    uniform vec2 shadowmapbias;\n    varying vec4 shadowmapvals;\n    void main(void)\n    {\n        gl_Position = shadowmatrix * vvertex;\n        shadowmapvals = vec4(0.0, 0.0, shadowmapbias.y - gl_Position.z, 0.0);\n    }",
    "fragment": "varying vec4 shadowmapvals;\n    void main(void)\n    {\n        gl_FragColor = shadowmapvals;\n    }"
  },
  {
    "name": "particlenotexture",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    uniform mat4 camprojmatrix;\n    uniform vec4 colorscale;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor * colorscale;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "blendbrush",
    "vertex": "attribute vec4 vvertex, vcolor;\n    uniform mat4 camprojmatrix;\n    uniform vec4 texgenS, texgenT;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        texcoord0 = vec2(dot(texgenS, vvertex), dot(texgenT, vvertex));\n    }",
    "fragment": "varying vec4 color;\n    varying vec2 texcoord0;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor = texture2D(tex0, texcoord0).r * color;\n    }"
  },
  {
    "name": "overbrightdecal",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        texcoord0 = vtexcoord0;\n    }",
    "fragment": "//:fog vec3(0.5)\n    varying vec4 color;\n    varying vec2 texcoord0;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        vec4 diffuse = texture2D(tex0, texcoord0);\n        gl_FragColor = mix(color, diffuse, color.a);\n    }"
  },
  {
    "name": "saturatedecal",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        texcoord0 = vtexcoord0;\n    }",
    "fragment": "varying vec4 color;\n    varying vec2 texcoord0;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        vec4 diffuse = texture2D(tex0, texcoord0);\n        diffuse.rgb *= 2.0;\n        gl_FragColor = diffuse * color;\n    }"
  },
  {
    "name": "skybox",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 skymatrix;\n    varying vec2 texcoord0;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = skymatrix * vvertex;\n        texcoord0 = vtexcoord0;\n        color = vcolor;\n    }",
    "fragment": "varying vec2 texcoord0;\n    varying vec4 color;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0);\n    }"
  },
  {
    "name": "skyboxglare",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec2 vtexcoord0;\n    uniform mat4 skymatrix;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = skymatrix * vvertex;\n        color = vcolor;\n        texcoord0 = vtexcoord0;\n    }",
    "fragment": "varying vec4 color;\n    varying vec2 texcoord0;\n    uniform sampler2D tex0;\n    void main(void)\n    {\n        vec4 glare = texture2D(tex0, texcoord0) * color;\n        gl_FragColor.rgb = vec3(dot(glare.rgb, vec3(10.56, 10.88, 10.56)) - 30.4);\n        gl_FragColor.a = glare.a;\n    }"
  },
  {
    "name": "skyfog",
    "vertex": "attribute vec4 vvertex, vcolor;\n    uniform mat4 skymatrix;\n    varying vec4 color;\n    void main(void)\n    {\n        gl_Position = skymatrix * vvertex;\n        color = vcolor;\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor =\n            //:variantoverride vec4(color.rgb, color.a * color.a)\n            color\n            ;\n    }"
  },
  {
    "name": "prefab",
    "vertex": "attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 prefabmatrix;\n    uniform mat3 prefabworld;\n    varying vec4 color;\n\n    void main(void)\n    {\n        gl_Position = prefabmatrix * vvertex;\n        color = vcolor;\n        color.rgb *= dot(prefabworld * vnormal, vec3(0.0, -0.447213595, 0.894427191));\n    }",
    "fragment": "varying vec4 color;\n    void main(void)\n    {\n        gl_FragColor = color;\n    }"
  },
  {
    "name": "waterglarefast",
    "vertex": "//:fog\n    attribute vec4 vvertex;\n    uniform mat4 camprojmatrix;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n    }",
    "fragment": "void main(void)\n    {\n        gl_FragColor = vec4(0.0);\n    }"
  },
  {
    "name": "underwater",
    "vertex": "attribute vec4 vvertex;\n    attribute vec3 vcolor;\n    uniform mat4 camprojmatrix;\n    varying vec3 color;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n    }",
    "fragment": "//:fogrgba vec4(vec3(0.0), 1.0)\n    uniform vec2 depth;\n    varying vec3 color;\n    void main(void)\n    {\n        gl_FragColor.rgb = 0.8*depth.x*color;\n        gl_FragColor.a = 0.5*depth.y;\n    }"
  },
  {
    "name": "lava",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    uniform vec4 lavatexgen;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        vec2 tc = mix(vvertex.xz, vvertex.yy, abs(vnormal.xz));\n        texcoord0 = (tc + lavatexgen.zw) * lavatexgen.xy;\n    }",
    "fragment": "uniform sampler2D tex0;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0) * 2.0;\n    }"
  },
  {
    "name": "lavaglare",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    uniform vec4 lavatexgen;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vec4(vcolor.rgb*2.0 - 1.0, vcolor.a);\n        vec2 tc = mix(vvertex.xz, vvertex.yy, abs(vnormal.xz));\n        texcoord0 = (tc + lavatexgen.zw) * lavatexgen.xy;\n    }",
    "fragment": "uniform sampler2D tex0;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        vec4 glow = texture2D(tex0, texcoord0) * color;\n        float k = max(glow.r, max(glow.g, glow.b));\n        gl_FragColor = glow*k*k*32.0;\n    }"
  },
  {
    "name": "waterfall",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 camprojmatrix;\n    varying vec4 color;\n    uniform vec4 waterfalltexgen;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        vec2 tc = mix(vvertex.xz, vvertex.yy, abs(vnormal.xz));\n        texcoord0 = (tc + waterfalltexgen.zw) * waterfalltexgen.xy;\n    }",
    "fragment": "uniform sampler2D tex0;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    void main(void)\n    {\n        gl_FragColor = color * texture2D(tex0, texcoord0);\n    }"
  },
  {
    "name": "waterfallrefract",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 camprojmatrix;\n    uniform mat4 watermatrix;\n    varying vec4 color;\n    uniform vec4 waterfalltexgen;\n    varying vec2 texcoord0;\n    varying vec4 texcoord1;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        vec2 tc = mix(vvertex.xz, vvertex.yy, abs(vnormal.xz));\n        texcoord0 = (tc + waterfalltexgen.zw) * waterfalltexgen.xy;\n        texcoord1 = watermatrix * vvertex;\n    }",
    "fragment": "uniform vec2 dudvoffset;\n    uniform sampler2D tex0, tex2, tex4;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    varying vec4 texcoord1;\n    void main(void)\n    {\n        vec4 diffuse = texture2D(tex0, texcoord0);\n        vec2 dudv = texture2D(tex2, texcoord0 + 0.2*diffuse.xy + dudvoffset).xy;\n        vec4 refract = texture2DProj(tex4, texcoord1 + vec4(4.0*dudv, 0.0, 0.0));\n        gl_FragColor = mix(refract, color, diffuse);\n    }"
  },
  {
    "name": "waterfallenvrefract",
    "vertex": "//:fog\n    attribute vec4 vvertex, vcolor;\n    attribute vec3 vnormal;\n    uniform mat4 camprojmatrix;\n    uniform mat4 watermatrix;\n    uniform vec3 camera;\n    varying vec4 color;\n    uniform vec4 waterfalltexgen;\n    varying vec2 texcoord0;\n    varying vec4 texcoord1;\n    varying vec3 camdir;\n    varying mat3 world;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        camdir = camera - vvertex.xyz;\n        vec3 absnorm = abs(vnormal);\n        world = mat3(absnorm.yzx, -absnorm.zxy, vnormal);\n        vec2 tc = mix(vvertex.xz, vvertex.yy, absnorm.xz);\n        texcoord0 = (tc + waterfalltexgen.zw) * waterfalltexgen.xy;\n        texcoord1 = watermatrix * vvertex;\n    }",
    "fragment": "uniform vec2 dudvoffset;\n    uniform sampler2D tex0, tex1, tex2, tex4;\n    uniform samplerCube tex3;\n    varying vec4 color;\n    varying vec2 texcoord0;\n    varying vec4 texcoord1;\n    varying vec3 camdir;\n    varying mat3 world;\n    void main(void)\n    {\n        vec4 diffuse = texture2D(tex0, texcoord0);\n        vec2 dudv = texture2D(tex2, texcoord0 + 0.2*diffuse.xy + dudvoffset).xy;\n        vec3 normal = world * (texture2D(tex1, texcoord0 + 0.1*dudv).rgb*2.0 - 1.0);\n        vec4 refract = texture2DProj(tex4, texcoord1 + vec4(4.0*dudv, 0.0, 0.0));\n        vec3 camvec = normalize(camdir);\n        float invfresnel = dot(normal, camvec);\n        vec4 reflect = textureCube(tex3, 2.0*invfresnel*normal - camvec);\n        gl_FragColor = mix(mix(reflect, refract, 1.0 - 0.4*step(0.0, invfresnel)), color, diffuse);\n    }"
  },
  {
    "name": "waterfallenv",
    "vertex": "//:fog\n    attribute vec4 vvertex;\n    attribute vec3 vcolor, vnormal;\n    uniform mat4 camprojmatrix;\n    uniform vec3 camera;\n    uniform vec4 waterfalltexgen;\n    varying vec2 texcoord0;\n    varying vec3 color, camdir;\n    varying mat3 world;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        camdir = camera - vvertex.xyz;\n        vec3 absnorm = abs(vnormal);\n        world = mat3(absnorm.yzx, -absnorm.zxy, vnormal);\n        vec2 tc = mix(vvertex.xz, vvertex.yy, absnorm.xz);\n        texcoord0 = (tc + waterfalltexgen.zw) * waterfalltexgen.xy;\n    }",
    "fragment": "uniform vec2 dudvoffset;\n    uniform sampler2D tex0, tex1, tex2;\n    uniform samplerCube tex3;\n    varying vec2 texcoord0;\n    varying vec3 color, camdir;\n    varying mat3 world;\n    void main(void)\n    {\n        vec4 diffuse = texture2D(tex0, texcoord0);\n        vec2 dudv = texture2D(tex2, texcoord0 + 0.2*diffuse.xy + dudvoffset).xy;\n        vec3 normal = world * (texture2D(tex1, texcoord0 + 0.1*dudv).rgb*2.0 - 1.0);\n        vec3 camvec = normalize(camdir);\n        vec4 reflect = textureCube(tex3, 2.0*dot(normal, camvec)*normal - camvec);\n        gl_FragColor.rgb = mix(reflect.rgb, color, diffuse.rgb);\n        gl_FragColor.a = 0.25 + 0.75*diffuse.r;\n    }"
  },
  {
    "name": "glass",
    "vertex": "attribute vec4 vvertex;\n    attribute vec3 vcolor, vnormal;\n    uniform mat4 camprojmatrix;\n    uniform vec3 camera;\n    varying vec3 color, rvec, camdir, normal;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        normal = vnormal;\n        camdir = camera - vvertex.xyz;\n        rvec = 2.0*dot(camdir, vnormal) * vnormal - camdir;\n    }",
    "fragment": "//:fogrgba vec4(vec3(0.0), 1.0)\n    uniform samplerCube tex0;\n    varying vec3 color, rvec, camdir, normal;\n    void main(void)\n    {\n        vec3 camvec = normalize(camdir);\n        vec3 reflect = textureCube(tex0, rvec).rgb;\n\n        float invfresnel = max(dot(camvec, normal), 0.70);\n        gl_FragColor.rgb = mix(reflect, color*0.05, invfresnel);\n        gl_FragColor.a = invfresnel * 0.95;\n    }"
  },
  {
    "name": "glassfast",
    "vertex": "attribute vec4 vvertex;\n    attribute vec3 vcolor, vnormal;\n    uniform mat4 camprojmatrix;\n    uniform vec3 camera;\n    varying vec3 color, rvec;\n    void main(void)\n    {\n        gl_Position = camprojmatrix * vvertex;\n        color = vcolor;\n        vec3 camdir = camera - vvertex.xyz;\n        rvec = 2.0*dot(camdir, vnormal) * vnormal - camdir;\n    }",
    "fragment": "//:fogrgba vec4(vec3(0.0), 1.0)\n    uniform samplerCube tex0;\n    varying vec3 color, rvec;\n    void main(void)\n    {\n        vec3 reflect = textureCube(tex0, rvec).rgb;\n        const float invfresnel = 0.75;\n        gl_FragColor.rgb = mix(reflect, color*0.05, invfresnel);\n        gl_FragColor.a = invfresnel * 0.95;\n    }"
  }
]);
                                                                                                                                                                                                          source/v64/tests/glbridge/d3d8_webgpu_browser_test.html                                             0000644 0000000 0000000 00000022505 00000000000 020414  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>D3D8 WebGPU browser validation test</title>
<style>
body { margin: 0; background: #111; color: #eee; font: 14px monospace; }
canvas { width: 640px; height: 480px; }
#result { white-space: pre-wrap; padding: 12px; }
</style>
<canvas id="screen" width="640" height="480"></canvas>
<div id="result">RUNNING</div>
<script src="../../src/browser/glbridge/webgpu_host.js"></script>
<script src="../../src/browser/glbridge/d3d8-webgpu/d3d8_executor.js"></script>
<script>
(async () => {
    "use strict";
    const result = document.getElementById("result");
    const sessionLow = 0xB0010001;
    const sessionHigh = 0x20260802;
    const u32 = (...values) => {
        const payload = new Uint8Array(values.length * 4);
        const view = new DataView(payload.buffer);
        values.forEach((value, index) => view.setUint32(index * 4,
            value >>> 0, true));
        return payload;
    };
    const surface = (handle, width, height) =>
        u32(handle, 0x1234, 0, 0, width, height);
    const createDevice = (handle, width, height) =>
        u32(handle, 0x1234, 0, 0, width, height, 22, 1, 0x20, 1, 75);
    const transform = (handle, state, matrix) => {
        const payload = new Uint8Array(72);
        const view = new DataView(payload.buffer);
        view.setUint32(0, handle, true);
        view.setUint32(4, state, true);
        matrix.forEach((value, index) =>
            view.setFloat32(8 + index * 4, value, true));
        return payload;
    };
    const command = (opcode, payload, blobs = []) =>
        ({ opcode, payload, blobs });
    const batch = commands => {
        let commandBytes = 0;
        for (const item of commands) {
            item.offset = 32 + commandBytes;
            item.size = (16 + item.payload.byteLength + item.blobs.reduce(
                (total, blob) => total + blob.data.byteLength, 0) + 7) & ~7;
            commandBytes += item.size;
        }
        const bytes = new Uint8Array(32 + commandBytes);
        const view = new DataView(bytes.buffer);
        view.setUint32(0, 0x47573844, true);
        view.setUint16(4, 1, true);
        view.setUint16(6, 7, true);
        view.setUint32(8, 1, true);
        view.setUint32(12, 1, true);
        view.setUint32(16, commands.length, true);
        view.setUint32(20, commandBytes, true);
        view.setUint32(24, sessionLow, true);
        view.setUint32(28, sessionHigh, true);
        commands.forEach((item, index) => {
            view.setUint16(item.offset, item.opcode, true);
            view.setUint32(item.offset + 4, item.size, true);
            view.setUint32(item.offset + 8, index + 1, true);
            bytes.set(item.payload, item.offset + 16);
            let blobOffset = item.offset + 16 + item.payload.byteLength;
            for (const blob of item.blobs) {
                view.setUint32(item.offset + 16 + blob.offsetField,
                    blobOffset, true);
                bytes.set(blob.data, blobOffset);
                blobOffset += blob.data.byteLength;
            }
        });
        return bytes;
    };

    try {
        if (!navigator.gpu) throw new Error("WebGPU unavailable");
        const deviceHandle = 0x100002;
        const textureHandle = 0x100003;
        const texture = new Uint8Array(16 * 16 * 4);
        for (let y = 0; y < 16; y++) {
            for (let x = 0; x < 16; x++) {
                const offset = (y * 16 + x) * 4;
                texture[offset] = x * 16;
                texture[offset + 1] = y * 16;
                texture[offset + 2] = 255 - x * 8;
                texture[offset + 3] = x < 2 || y < 2 ? 0 : 220;
            }
        }
        const vertices = new Uint8Array(3 * 40);
        const vertexView = new DataView(vertices.buffer);
        [[80, 60, 0, 0], [560, 60, 1, 0], [320, 420, 0.5, 1]]
            .forEach((vertex, index) => {
                const offset = index * 40;
                vertexView.setFloat32(offset, vertex[0], true);
                vertexView.setFloat32(offset + 4, vertex[1], true);
                vertexView.setFloat32(offset + 8, 0.5, true);
                vertexView.setFloat32(offset + 12, 1, true);
                vertexView.setUint32(offset + 16, 0xFFFFFFFF, true);
                vertexView.setUint32(offset + 20, 0xFF101010, true);
                vertexView.setFloat32(offset + 24, vertex[2], true);
                vertexView.setFloat32(offset + 28, vertex[3], true);
                vertexView.setFloat32(offset + 32, vertex[2] * 2, true);
                vertexView.setFloat32(offset + 36, vertex[3] * 2, true);
            });
        const identity = [
            1, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 1, 0, 0, 0, 0, 1,
        ];
        const fixedVertices = new Uint8Array(3 * 36);
        const fixedView = new DataView(fixedVertices.buffer);
        [[-0.75, 0.7, 0.4, 0, 0], [0.75, 0.7, 0.4, 1, 0],
            [0, -0.7, 0.4, 0.5, 1]].forEach((vertex, index) => {
            const offset = index * 36;
            fixedView.setFloat32(offset, vertex[0], true);
            fixedView.setFloat32(offset + 4, vertex[1], true);
            fixedView.setFloat32(offset + 8, vertex[2], true);
            fixedView.setFloat32(offset + 12, 0, true);
            fixedView.setFloat32(offset + 16, 0, true);
            fixedView.setFloat32(offset + 20, -1, true);
            fixedView.setUint32(offset + 24, 0xFFFFFFFF, true);
            fixedView.setFloat32(offset + 28, vertex[3], true);
            fixedView.setFloat32(offset + 32, vertex[4], true);
        });
        const executor = new D3D8WebGPUExecutor(
            document.getElementById("screen"));
        await Promise.race([
            executor.initialize(),
            new Promise((unused, reject) => setTimeout(() =>
                reject(new Error("WebGPU initialization timed out")), 8000)),
        ]);
        executor.device.pushErrorScope("validation");
        await executor.submit(batch([
            command(1, u32(32, 0, sessionLow, sessionHigh)),
            command(2, createDevice(deviceHandle, 640, 480)),
            command(0x110, u32(deviceHandle, textureHandle,
                16, 16, 1, 21, 0, 1)),
            command(0x111, u32(textureHandle, 0, 0, 0, 16, 16,
                64, texture.byteLength, 0, 0),
                [{ offsetField: 32, data: texture }]),
            command(0x202, u32(deviceHandle, 0, textureHandle, 0)),
            command(0x202, u32(deviceHandle, 1, textureHandle, 0)),
            command(0x201, u32(deviceHandle, 0, 16, 2)),
            command(0x201, u32(deviceHandle, 0, 17, 2)),
            command(0x201, u32(deviceHandle, 0, 18, 2)),
            command(0x201, u32(deviceHandle, 1, 1, 7)),
            command(0x201, u32(deviceHandle, 1, 2, 1)),
            command(0x201, u32(deviceHandle, 1, 3, 2)),
            command(0x201, u32(deviceHandle, 1, 4, 2)),
            command(0x201, u32(deviceHandle, 1, 5, 1)),
            command(0x200, u32(deviceHandle, 15, 1, 0)),
            command(0x200, u32(deviceHandle, 24, 8, 0)),
            command(0x200, u32(deviceHandle, 25, 5, 0)),
            command(0x200, u32(deviceHandle, 27, 1, 0)),
            command(0x200, u32(deviceHandle, 19, 5, 0)),
            command(0x200, u32(deviceHandle, 20, 6, 0)),
            command(0x200, u32(deviceHandle, 29, 1, 0)),
            command(0x203, u32(deviceHandle, 32, 24, 576, 432,
                0, 0x3F800000, 0)),
            command(0x20A, u32(deviceHandle, 0x2C4)),
            command(5, u32(deviceHandle, 1, 0xFF101820,
                0x3F800000, 0, 0)),
            command(5, u32(deviceHandle, 7, 0xFF204080,
                0x3E800000, 0x5A, 1, 24, 32, 160, 144)),
            command(0x302, u32(deviceHandle, 4, 1, 40, 3,
                vertices.byteLength, 0, 0),
                [{ offsetField: 24, data: vertices }]),
            command(0x204, transform(deviceHandle, 256, identity)),
            command(0x204, transform(deviceHandle, 2, identity)),
            command(0x204, transform(deviceHandle, 3, identity)),
            command(0x204, transform(deviceHandle, 16, identity)),
            command(0x200, u32(deviceHandle, 139, 0xFFFFFFFF, 0)),
            command(0x200, u32(deviceHandle, 143, 1, 0)),
            command(0x201, u32(deviceHandle, 0, 11, 0x10000)),
            command(0x201, u32(deviceHandle, 0, 24, 2)),
            command(0x201, u32(deviceHandle, 1, 1, 1)),
            command(0x20A, u32(deviceHandle, 0x152)),
            command(0x302, u32(deviceHandle, 4, 1, 36, 3,
                fixedVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: fixedVertices }]),
            command(0x202, u32(deviceHandle, 0, 0, 0)),
            command(0x202, u32(deviceHandle, 1, 0, 0)),
            command(0x103, u32(textureHandle, 3)),
            command(4, surface(deviceHandle, 640, 480)),
        ]));
        const validation = await executor.device.popErrorScope();
        if (executor.failed) throw executor.failed;
        if (validation) throw validation;
        const stats = executor.getStats();
        if (stats.drawCalls !== 2 || stats.presents !== 1 ||
                stats.rectangularClears !== 1)
            throw new Error("unexpected stats " + JSON.stringify(stats));
        result.textContent = "PASS\n" + JSON.stringify(stats, null, 2);
        result.dataset.status = "pass";
    } catch (error) {
        result.textContent = "FAIL\n" + (error && error.stack || error);
        result.dataset.status = "fail";
    }
})();
</script>
                                                                                                                                                                                           source/v64/tests/glbridge/d3d8_webgpu_executor_test.js                                              0000644 0000000 0000000 00000231420 00000000000 020235  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

const assert = require("node:assert/strict");
const {
    D3D8WebGPUExecutor,
    D8WG_MAGIC,
    D8WG_VERSION_MAJOR,
    D8WG_VERSION_MINOR,
    parseVertexDeclaration,
    vertexShaderWgsl,
    pixelShaderWgsl,
    shaderPipelineWgsl,
} = require("../../src/browser/glbridge/d3d8-webgpu/d3d8_executor.js");

const OP_HELLO = 1;
const OP_CREATE_DEVICE = 2;
const OP_RESET = 3;
const OP_PRESENT = 4;
const OP_CLEAR = 5;
const OP_BEGIN_SCENE = 6;
const OP_END_SCENE = 7;
const OP_UPDATE_SURFACE = 8;
const OP_CREATE_BUFFER = 0x100;
const OP_UPDATE_BUFFER = 0x101;
const OP_DESTROY_RESOURCE = 0x103;
const OP_CREATE_TEXTURE = 0x110;
const OP_UPDATE_TEXTURE = 0x111;
const OP_CREATE_VERTEX_SHADER = 0x120;
const OP_CREATE_PIXEL_SHADER = 0x121;
const OP_SET_RENDER_STATE = 0x200;
const OP_SET_TEXTURE_STAGE_STATE = 0x201;
const OP_SET_TEXTURE = 0x202;
const OP_SET_VIEWPORT = 0x203;
const OP_SET_TRANSFORM = 0x204;
const OP_SET_MATERIAL = 0x205;
const OP_SET_LIGHT = 0x206;
const OP_LIGHT_ENABLE = 0x207;
const OP_SET_STREAM_SOURCE = 0x208;
const OP_SET_INDICES = 0x209;
const OP_SET_VERTEX_FORMAT = 0x20A;
const OP_SET_RENDER_TARGET = 0x20B;
const OP_SET_VERTEX_SHADER = 0x20C;
const OP_SET_PIXEL_SHADER = 0x20D;
const OP_SET_VERTEX_SHADER_CONSTANT = 0x20E;
const OP_SET_PIXEL_SHADER_CONSTANT = 0x20F;
const OP_DRAW_PRIMITIVE = 0x300;
const OP_DRAW_INDEXED_PRIMITIVE = 0x301;
const OP_DRAW_PRIMITIVE_UP = 0x302;
const OP_DRAW_INDEXED_PRIMITIVE_UP = 0x303;

function u32Payload(...values) {
    const payload = Buffer.alloc(values.length * 4);
    values.forEach((value, index) => payload.writeUInt32LE(value >>> 0, index * 4));
    return payload;
}

function createDevicePayload(deviceHandle, width, height) {
    const payload = Buffer.alloc(44);
    payload.writeUInt32LE(deviceHandle, 0);
    payload.writeUInt32LE(0x1234, 4);
    payload.writeInt32LE(11, 8);
    payload.writeInt32LE(22, 12);
    payload.writeUInt32LE(width, 16);
    payload.writeUInt32LE(height, 20);
    payload.writeUInt32LE(22, 24); // D3DFMT_X8R8G8B8
    payload.writeUInt32LE(1, 28);
    payload.writeUInt32LE(0x20, 32);
    payload.writeUInt32LE(1, 36); // EnableAutoDepthStencil
    payload.writeUInt32LE(75, 40); // D3DFMT_D24S8
    return payload;
}

function surfacePayload(deviceHandle, x, y, width, height) {
    const payload = Buffer.alloc(24);
    payload.writeUInt32LE(deviceHandle, 0);
    payload.writeUInt32LE(0x1234, 4);
    payload.writeInt32LE(x, 8);
    payload.writeInt32LE(y, 12);
    payload.writeUInt32LE(width, 16);
    payload.writeUInt32LE(height, 20);
    return payload;
}

function transformPayload(deviceHandle, state, values) {
    assert.equal(values.length, 16);
    const payload = Buffer.alloc(72);
    payload.writeUInt32LE(deviceHandle, 0);
    payload.writeUInt32LE(state, 4);
    values.forEach((value, index) =>
        payload.writeFloatLE(value, 8 + index * 4));
    return payload;
}

function materialPayload(deviceHandle, values) {
    assert.equal(values.length, 17);
    const payload = Buffer.alloc(72);
    payload.writeUInt32LE(deviceHandle, 0);
    values.forEach((value, index) =>
        payload.writeFloatLE(value, 4 + index * 4));
    return payload;
}

function lightPayload(deviceHandle, index, type, values) {
    assert.equal(values.length, 25);
    const payload = Buffer.alloc(112);
    payload.writeUInt32LE(deviceHandle, 0);
    payload.writeUInt32LE(index, 4);
    payload.writeUInt32LE(type, 8);
    values.forEach((value, item) =>
        payload.writeFloatLE(value, 12 + item * 4));
    return payload;
}

const DEFAULT_SESSION_LOW = 0xA0010001;
const DEFAULT_SESSION_HIGH = 0x20260802;

function batch(commandSpecs, frameId, sessionLow = DEFAULT_SESSION_LOW,
        sessionHigh = DEFAULT_SESSION_HIGH) {
    let commandBytes = 0;
    for (const spec of commandSpecs) {
        const blobBytes = (spec.blobs || []).reduce(
            (total, blob) => total + blob.data.length, 0);
        spec.size = (16 + spec.payload.length +
            (spec.blob ? spec.blob.length : 0) + blobBytes + 7) & ~7;
        spec.offset = 32 + commandBytes;
        commandBytes += spec.size;
    }
    const result = Buffer.alloc(32 + commandBytes);
    result.writeUInt32LE(D8WG_MAGIC, 0);
    result.writeUInt16LE(D8WG_VERSION_MAJOR, 4);
    result.writeUInt16LE(D8WG_VERSION_MINOR, 6);
    result.writeUInt32LE(frameId, 8);
    result.writeUInt32LE(1, 12);
    result.writeUInt32LE(commandSpecs.length, 16);
    result.writeUInt32LE(commandBytes, 20);
    result.writeUInt32LE(sessionLow >>> 0, 24);
    result.writeUInt32LE(sessionHigh >>> 0, 28);

    let sequence = 1;
    for (const spec of commandSpecs) {
        const offset = spec.offset;
        result.writeUInt16LE(spec.opcode, offset);
        result.writeUInt16LE(0, offset + 2);
        result.writeUInt32LE(spec.size, offset + 4);
        result.writeUInt32LE(sequence++, offset + 8);
        spec.payload.copy(result, offset + 16);
        if (spec.blob) {
            const blobOffset = offset + 16 + spec.payload.length;
            result.writeUInt32LE(blobOffset, offset + 16 + 12);
            spec.blob.copy(result, blobOffset);
        }
        let blobOffset = offset + 16 + spec.payload.length +
            (spec.blob ? spec.blob.length : 0);
        for (const blob of spec.blobs || []) {
            result.writeUInt32LE(blobOffset,
                offset + 16 + blob.offsetField);
            blob.data.copy(result, blobOffset);
            blobOffset += blob.data.length;
        }
    }
    return result;
}

function command(opcode, payload, blob) {
    return { opcode, payload, blob };
}

function commandWithBlobs(opcode, payload, blobs) {
    return { opcode, payload, blobs };
}

function makeFakeWebGPU(options = {}) {
    const calls = [];
    const submittedWorkResolvers = [];
    class FakeBuffer {
        constructor(descriptor) { this.descriptor = descriptor; this.destroyed = false; }
        destroy() { this.destroyed = true; calls.push(["destroyBuffer"]); }
    }
    class FakeTexture {
        constructor(descriptor) { this.descriptor = descriptor; this.destroyed = false; }
        createView(descriptor) {
            const view = { texture: this, descriptor: descriptor || {} };
            calls.push(["createTextureView", view]);
            return view;
        }
        destroy() { this.destroyed = true; calls.push(["destroyTexture"]); }
    }
    class FakePass {
        constructor(descriptor) { this.descriptor = descriptor; this.calls = []; }
        setPipeline(value) { this.calls.push(["setPipeline", value]); }
        setBindGroup(index, value) { this.calls.push(["setBindGroup", index, value]); }
        setVertexBuffer(...args) { this.calls.push(["setVertexBuffer", ...args]); }
        setIndexBuffer(...args) {
            this.calls.push(["setIndexBuffer", ...args]);
            calls.push(["setIndexBuffer", ...args]);
        }
        setViewport(...args) {
            this.calls.push(["setViewport", ...args]);
            calls.push(["setViewport", ...args]);
        }
        setStencilReference(value) {
            this.calls.push(["setStencilReference", value]);
            calls.push(["setStencilReference", value]);
        }
        setScissorRect(...args) { this.calls.push(["setScissorRect", ...args]); calls.push(["setScissorRect", ...args]); }
        draw(...args) { this.calls.push(["draw", ...args]); calls.push(["draw", ...args]); }
        drawIndexed(...args) {
            this.calls.push(["drawIndexed", ...args]);
            calls.push(["drawIndexed", ...args]);
        }
        end() { this.calls.push(["end"]); calls.push(["endPass"]); }
    }
    class FakeEncoder {
        constructor() { this.passes = []; }
        beginRenderPass(descriptor) {
            const pass = new FakePass(descriptor);
            this.passes.push(pass);
            calls.push(["beginRenderPass", descriptor]);
            return pass;
        }
        copyBufferToBuffer(...args) {
            calls.push(["copyBufferToBuffer", ...args]);
        }
        copyBufferToTexture(...args) {
            calls.push(["copyBufferToTexture", ...args]);
        }
        copyTextureToTexture(source, target, size) {
            calls.push(["copyTextureToTexture", source, target, size]);
        }
        finish() { calls.push(["finish"]); return { passes: this.passes }; }
    }
    const queue = {
        writeBuffer(buffer, offset, data) {
            calls.push(["writeBuffer", buffer, offset, Buffer.from(
                data.buffer, data.byteOffset, data.byteLength)]);
        },
        writeTexture(...args) { calls.push(["writeTexture", ...args]); },
        submit(commandBuffers) { calls.push(["submit", commandBuffers]); },
        onSubmittedWorkDone() {
            calls.push(["onSubmittedWorkDone"]);
            if (!options.deferSubmittedWork) return Promise.resolve();
            return new Promise(resolve => submittedWorkResolvers.push(resolve));
        },
    };
    // WebGPU derives an automatic bind group layout from the resources a
    // shader *statically uses*: a binding that is declared but never
    // referenced is stripped, and creating a bind group that supplies it then
    // fails validation ("binding index N not present in the bind group
    // layout"). Emulating that here is what makes the fake device able to
    // catch a layout:"auto" pipeline whose shader does not touch every
    // binding -- a real failure mode for translated SM1.x shaders, which may
    // legitimately reference no constants and sample no textures.
    function usedBindings(code) {
        const used = new Set();
        const declaration =
            /@group\(0\)\s*@binding\((\d+)\)\s*var(?:<[^>]*>)?\s+(\w+)\s*:/g;
        let match;
        while ((match = declaration.exec(code)) !== null) {
            const binding = Number(match[1]);
            const name = match[2];
            // Count references outside the declaration itself.
            const references = code.match(
                new RegExp("\\b" + name + "\\b", "g")) || [];
            if (references.length > 1) used.add(binding);
        }
        return used;
    }

    const device = {
        queue,
        lost: new Promise(() => {}),
        createShaderModule(descriptor) {
            calls.push(["shader", descriptor]);
            return { ...descriptor, _code: descriptor.code };
        },
        createBuffer(descriptor) { calls.push(["createBuffer", descriptor]); return new FakeBuffer(descriptor); },
        createTexture(descriptor) {
            const texture = new FakeTexture(descriptor);
            calls.push(["createTexture", descriptor, texture]);
            return texture;
        },
        createSampler(descriptor) {
            const sampler = { descriptor };
            calls.push(["createSampler", descriptor]);
            return sampler;
        },
        createCommandEncoder() { calls.push(["createEncoder"]); return new FakeEncoder(); },
        createBindGroupLayout(descriptor) {
            calls.push(["createBindGroupLayout", descriptor]);
            return {
                descriptor,
                bindings: new Set(descriptor.entries.map(e => e.binding)),
            };
        },
        createPipelineLayout(descriptor) {
            calls.push(["createPipelineLayout", descriptor]);
            return { descriptor, bindGroupLayouts: descriptor.bindGroupLayouts };
        },
        createRenderPipeline(descriptor) {
            calls.push(["createPipeline", descriptor]);
            let layout;
            if (descriptor.layout === "auto") {
                // Dedupe: the vertex and fragment entry points usually come
                // from one shared module, and counting that source twice
                // would make every declaration look referenced.
                const sources = new Set();
                sources.add(descriptor.vertex.module._code);
                if (descriptor.fragment)
                    sources.add(descriptor.fragment.module._code);
                const code = [...sources].filter(Boolean).join("\n");
                layout = { bindings: usedBindings(code), auto: true };
            } else {
                layout = descriptor.layout.bindGroupLayouts[0];
            }
            return { descriptor, getBindGroupLayout() { return layout; } };
        },
        createBindGroup(descriptor) {
            calls.push(["createBindGroup", descriptor]);
            const layout = descriptor.layout;
            if (layout && layout.bindings) {
                for (const entry of descriptor.entries) {
                    if (!layout.bindings.has(entry.binding)) {
                        throw new Error("In entries[" + entry.binding +
                            "], binding index " + entry.binding +
                            " not present in the bind group layout");
                    }
                }
            }
            return descriptor;
        },
    };
    const context = {
        configure(descriptor) { calls.push(["configure", descriptor]); },
        getCurrentTexture() {
            calls.push(["getCurrentTexture"]);
            return { createView() { return { textureView: true }; } };
        },
    };
    const gpu = {
        async requestAdapter() { return { async requestDevice() { return device; } }; },
        getPreferredCanvasFormat() { return "bgra8unorm"; },
    };
    return {
        calls, device, context, gpu,
        completeSubmittedWork() {
            for (const resolve of submittedWorkResolvers.splice(0)) resolve();
        },
    };
}

async function main() {
    const fake = makeFakeWebGPU();
    const surfaces = [];
    const presents = [];
    const destroys = [];
    const canvas = {
        width: 1,
        height: 1,
        getContext(name) { assert.equal(name, "webgpu"); return fake.context; },
    };
    const executor = new D3D8WebGPUExecutor(canvas, {
        gpu: fake.gpu,
        onSurface(surface, reason) { surfaces.push({ surface, reason }); },
        onPresent(surface, stats) { presents.push({ surface, stats }); },
        onDestroy(surface, reason) { destroys.push({ surface, reason }); },
    });

    const deviceHandle = 0x00100002;
    const bufferHandle = 0x00100003;
    const indexBufferHandle = 0x00100004;
    const vertices = Buffer.alloc(80);
    const vertexView = new DataView(vertices.buffer, vertices.byteOffset, vertices.byteLength);
    const values = [
        [320, 60, 0.5, 1, 0xFFFF0000],
        [560, 420, 0.5, 1, 0xFF00FF00],
        [80, 420, 0.5, 1, 0xFF0000FF],
        [80, 60, 0.5, 1, 0xFFFFFF00],
    ];
    values.forEach((vertex, index) => {
        const base = index * 20;
        vertexView.setFloat32(base, vertex[0], true);
        vertexView.setFloat32(base + 4, vertex[1], true);
        vertexView.setFloat32(base + 8, vertex[2], true);
        vertexView.setFloat32(base + 12, vertex[3], true);
        vertexView.setUint32(base + 16, vertex[4], true);
    });

    const createBuffer = Buffer.alloc(32);
    createBuffer.writeUInt32LE(deviceHandle, 0);
    createBuffer.writeUInt32LE(bufferHandle, 4);
    createBuffer.writeUInt32LE(1, 8);
    createBuffer.writeUInt32LE(vertices.length, 12);
    createBuffer.writeUInt32LE(0x200, 16); // D3DUSAGE_DYNAMIC
    createBuffer.writeUInt32LE(0x44, 20);
    createBuffer.writeUInt32LE(0, 24);

    const update = Buffer.alloc(24);
    update.writeUInt32LE(bufferHandle, 0);
    update.writeUInt32LE(0, 4);
    update.writeUInt32LE(vertices.length, 8);
    update.writeUInt32LE(0x2000, 16); // D3DLOCK_DISCARD

    const indices = Buffer.alloc(12);
    [0, 1, 2, 0, 2, 3].forEach((value, index) =>
        indices.writeUInt16LE(value, index * 2));
    const createIndexBuffer = Buffer.alloc(32);
    createIndexBuffer.writeUInt32LE(deviceHandle, 0);
    createIndexBuffer.writeUInt32LE(indexBufferHandle, 4);
    createIndexBuffer.writeUInt32LE(2, 8);
    createIndexBuffer.writeUInt32LE(indices.length, 12);
    createIndexBuffer.writeUInt32LE(0, 16);
    createIndexBuffer.writeUInt32LE(101, 20);
    createIndexBuffer.writeUInt32LE(0, 24);
    const updateIndices = Buffer.alloc(24);
    updateIndices.writeUInt32LE(indexBufferHandle, 0);
    updateIndices.writeUInt32LE(0, 4);
    updateIndices.writeUInt32LE(indices.length, 8);
    const updateColour = Buffer.alloc(24);
    updateColour.writeUInt32LE(bufferHandle, 0);
    updateColour.writeUInt32LE(16, 4);
    updateColour.writeUInt32LE(4, 8);
    updateColour.writeUInt32LE(0x1000, 16); // D3DLOCK_NOOVERWRITE
    const replacementColour = Buffer.alloc(4);
    replacementColour.writeUInt32LE(0xFFFFFFFF, 0);

    const firstBatch = batch([
        command(OP_HELLO, u32Payload(32, 0,
            DEFAULT_SESSION_LOW, DEFAULT_SESSION_HIGH)),
        command(OP_CREATE_DEVICE, createDevicePayload(deviceHandle, 640, 480)),
        command(OP_CREATE_BUFFER, createBuffer),
        command(OP_UPDATE_BUFFER, update, vertices),
        command(OP_CREATE_BUFFER, createIndexBuffer),
        command(OP_UPDATE_BUFFER, updateIndices, indices),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 22, 1, 0)),
        command(OP_SET_STREAM_SOURCE, u32Payload(deviceHandle, 0, bufferHandle, 20)),
        command(OP_SET_INDICES, u32Payload(deviceHandle, indexBufferHandle, 0, 0)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x44)),
        command(OP_CLEAR, u32Payload(deviceHandle, 1, 0xFF000000, 0x3F800000, 0, 0)),
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(deviceHandle, 4, 0, 1)),
        command(OP_UPDATE_BUFFER, updateColour, replacementColour),
        command(OP_DRAW_INDEXED_PRIMITIVE,
            u32Payload(deviceHandle, 4, 0, 4, 0, 2)),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 11, 22, 640, 480)),
    ], 1);

    await executor.submit(firstBatch, { submitCount: 1 });
    assert.equal(executor.failed, null);
    assert.equal(canvas.width, 640);
    assert.equal(canvas.height, 480);
    assert.equal(surfaces.length, 1);
    assert.equal(presents.length, 1);
    assert.equal(executor.getStats().drawCalls, 2);
    assert.equal(executor.getStats().indexedDrawCalls, 1);
    assert.equal(executor.getStats().pipelineCreations, 1);
    assert.equal(executor.getStats().uploadBytes,
        vertices.length + indices.length + replacementColour.length);
    assert.equal(executor.getStats().bufferOrphans, 1,
        "D3DLOCK_DISCARD must orphan the prior GPU buffer");
    assert.equal(fake.calls.filter(call => call[0] === "submit").length, 1);
    assert.deepEqual(fake.calls.find(call => call[0] === "draw").slice(1),
        [3, 1, 0, 0]);
    assert.deepEqual(fake.calls.find(call => call[0] === "drawIndexed").slice(1),
        [6, 1, 0, 0, 0]);
    assert.equal(fake.calls.filter(call =>
        call[0] === "copyBufferToBuffer").length, 1,
    "mid-frame updates must preserve draw/upload ordering in one encoder");

    const index32Handle = 0x00100005;
    const indices32 = Buffer.alloc(24);
    [0, 0, 0, 0, 1, 2].forEach((value, index) =>
        indices32.writeUInt32LE(value, index * 4));
    const createIndex32 = Buffer.alloc(32);
    createIndex32.writeUInt32LE(deviceHandle, 0);
    createIndex32.writeUInt32LE(index32Handle, 4);
    createIndex32.writeUInt32LE(2, 8);
    createIndex32.writeUInt32LE(indices32.length, 12);
    createIndex32.writeUInt32LE(0, 16);
    createIndex32.writeUInt32LE(102, 20);
    const updateIndex32 = Buffer.alloc(24);
    updateIndex32.writeUInt32LE(index32Handle, 0);
    updateIndex32.writeUInt32LE(indices32.length, 8);
    const secondBatch = batch([
        command(OP_CREATE_BUFFER, createIndex32),
        command(OP_UPDATE_BUFFER, updateIndex32, indices32),
        command(OP_UPDATE_SURFACE,
            surfacePayload(deviceHandle, 33, 44, 800, 600)),
        command(OP_CLEAR, u32Payload(deviceHandle, 1, 0xFF102030, 0x3F800000, 0, 0)),
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_SET_INDICES, u32Payload(deviceHandle, index32Handle, 1, 0)),
        command(OP_DRAW_INDEXED_PRIMITIVE,
            u32Payload(deviceHandle, 4, 0, 3, 3, 1)),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 2);
    await executor.submit(secondBatch, { submitCount: 2 });
    assert.equal(executor.getStats().pipelineCreations, 1,
        "stable draws must reuse the WebGPU pipeline");
    assert.equal(executor.getStats().presents, 2);
    assert.equal(fake.calls.filter(call => call[0] === "submit").length, 2);
    assert.deepEqual(fake.calls.filter(call => call[0] === "drawIndexed")[1]
        .slice(1), [3, 1, 3, 1, 0]);
    assert.ok(fake.calls.some(call => call[0] === "setIndexBuffer" &&
        call[2] === "uint32"), "INDEX32 must bind with WebGPU uint32 format");
    assert.equal(surfaces.length, 2,
        "an unchanged Present must not emit a duplicate surface callback");
    assert.equal(surfaces[1].reason, "move");
    assert.equal(surfaces[1].surface.x, 33);
    assert.equal(surfaces[1].surface.y, 44);
    assert.equal(surfaces[1].surface.displayWidth, 800);
    assert.equal(surfaces[1].surface.displayHeight, 600);
    assert.equal(executor.devices.get(deviceHandle).surface.width, 640,
        "window resizing must not change the D3D backbuffer dimensions");
    assert.equal(canvas.width, 640);
    assert.equal(canvas.height, 480);

    const upPayload = u32Payload(deviceHandle, 6, 2, 20, 4,
        vertices.length, 0, 0);
    const indexedFan = Buffer.alloc(8);
    [0, 1, 2, 3].forEach((value, index) =>
        indexedFan.writeUInt16LE(value, index * 2));
    const indexedUpPayload = u32Payload(deviceHandle, 6, 0, 4, 2,
        101, 20, 4, indexedFan.length, vertices.length, 0, 0);
    const upBatch = batch([
        command(OP_CLEAR, u32Payload(deviceHandle, 1, 0xFF000000,
            0x3F800000, 0, 0)),
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP, upPayload,
            [{ offsetField: 24, data: vertices }]),
        commandWithBlobs(OP_DRAW_INDEXED_PRIMITIVE_UP, indexedUpPayload, [
            { offsetField: 40, data: indexedFan },
            { offsetField: 44, data: vertices },
        ]),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 3);
    await executor.submit(upBatch, { submitCount: 3 });
    assert.equal(executor.failed, null);
    assert.equal(executor.getStats().drawCalls, 5);
    assert.equal(executor.getStats().indexedDrawCalls, 3);
    assert.equal(executor.getStats().upDrawCalls, 2);
    assert.equal(executor.getStats().fanConversions, 2);
    assert.equal(executor.getStats().transientBufferCreations, 0,
        "small ordered and DrawUP uploads must reuse the transient ring");
    assert.equal(executor.getStats().transientUploadBytes,
        vertices.length * 2 + 12 + 12 + replacementColour.length);
    assert.equal(executor.getStats().presents, 3);
    assert.equal(fake.calls.filter(call => call[0] === "submit").length, 3);
    assert.equal(executor.devices.get(deviceHandle).streams[0].handle, 0,
        "UP draws must clear stream zero state");
    assert.equal(executor.devices.get(deviceHandle).indices.handle, 0,
        "indexed UP draws must clear index-buffer state");

    const textureHandle = 0x00100006;
    const dxtTextureHandle = 0x00100007;
    const dxt3TextureHandle = 0x00100008;
    const dxt5TextureHandle = 0x00100009;
    const rgbaTexture = Buffer.alloc(4 * 4 * 4);
    for (let pixel = 0; pixel < 16; pixel++) {
        rgbaTexture[pixel * 4] = pixel * 8;
        rgbaTexture[pixel * 4 + 1] = 255 - pixel * 8;
        rgbaTexture[pixel * 4 + 2] = 64 + pixel * 4;
        rgbaTexture[pixel * 4 + 3] = pixel === 0 ? 0 : 255;
    }
    const dxtTexture = Buffer.from([
        0x00, 0xF8, 0xE0, 0x07, 0, 0, 0, 0,
    ]);
    const dxt3Texture = Buffer.from([
        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
        0x00, 0xF8, 0xE0, 0x07, 0, 0, 0, 0,
    ]);
    const dxt5Texture = Buffer.from([
        0xFF, 0x00, 0, 0, 0, 0, 0, 0,
        0x00, 0xF8, 0xE0, 0x07, 0, 0, 0, 0,
    ]);
    const createTexture = u32Payload(deviceHandle, textureHandle,
        4, 4, 1, 21, 0, 1);
    const updateTexture = u32Payload(textureHandle, 0, 0, 0,
        4, 4, 16, rgbaTexture.length, 0, 0);
    const createDXT = u32Payload(deviceHandle, dxtTextureHandle,
        4, 4, 1, 0x31545844, 0, 1);
    const updateDXT = u32Payload(dxtTextureHandle, 0, 0, 0,
        4, 4, 8, dxtTexture.length, 0, 0);
    const createDXT3 = u32Payload(deviceHandle, dxt3TextureHandle,
        4, 4, 1, 0x33545844, 0, 1);
    const updateDXT3 = u32Payload(dxt3TextureHandle, 0, 0, 0,
        4, 4, 16, dxt3Texture.length, 0, 0);
    const createDXT5 = u32Payload(deviceHandle, dxt5TextureHandle,
        4, 4, 1, 0x35545844, 0, 1);
    const updateDXT5 = u32Payload(dxt5TextureHandle, 0, 0, 0,
        4, 4, 16, dxt5Texture.length, 0, 0);
    const conversionCases = [
        { format: 22, source: Buffer.from([3, 2, 1, 0]),
          expected: [1, 2, 3, 255] },
        { format: 23, source: Buffer.from([0x00, 0xF8]),
          expected: [255, 0, 0, 255] },
        { format: 24, source: Buffer.from([0x00, 0x7C]),
          expected: [255, 0, 0, 255] },
        { format: 25, source: Buffer.from([0x00, 0xFC]),
          expected: [255, 0, 0, 255] },
        { format: 26, source: Buffer.from([0x23, 0xF1]),
          expected: [17, 34, 51, 255] },
        { format: 50, source: Buffer.from([128]),
          expected: [128, 128, 128, 255] },
        { format: 28, source: Buffer.from([64]),
          expected: [255, 255, 255, 64] },
    ];
    const conversionCommands = conversionCases.flatMap((item, index) => {
        const handle = 0x0010000A + index;
        return [
            command(OP_CREATE_TEXTURE, u32Payload(deviceHandle, handle,
                1, 1, 1, item.format, 0, 1)),
            commandWithBlobs(OP_UPDATE_TEXTURE, u32Payload(handle, 0, 0, 0,
                1, 1, item.source.length, item.source.length, 0, 0),
                [{ offsetField: 32, data: item.source }]),
        ];
    });

    const texturedVertices = Buffer.alloc(3 * 40);
    const texturedView = new DataView(texturedVertices.buffer,
        texturedVertices.byteOffset, texturedVertices.byteLength);
    [[10, 20, 0, 0], [310, 20, 1, 0], [10, 220, 0, 1]]
        .forEach((vertex, index) => {
            const offset = index * 40;
            texturedView.setFloat32(offset, vertex[0], true);
            texturedView.setFloat32(offset + 4, vertex[1], true);
            texturedView.setFloat32(offset + 8, 0.5, true);
            texturedView.setFloat32(offset + 12, 1, true);
            texturedView.setUint32(offset + 16, 0xFFFFFFFF, true);
            texturedView.setUint32(offset + 20, 0xFF101010, true);
            texturedView.setFloat32(offset + 24, vertex[2], true);
            texturedView.setFloat32(offset + 28, vertex[3], true);
            texturedView.setFloat32(offset + 32, vertex[2] * 2, true);
            texturedView.setFloat32(offset + 36, vertex[3] * 2, true);
        });
    const partialTexture = rgbaTexture.subarray(0, 16);
    const partialUpdate = u32Payload(textureHandle, 0, 0, 0,
        2, 2, 8, partialTexture.length, 0, 0);
    const stage3Batch = batch([
        command(OP_CREATE_TEXTURE, createTexture),
        commandWithBlobs(OP_UPDATE_TEXTURE, updateTexture,
            [{ offsetField: 32, data: rgbaTexture }]),
        command(OP_CREATE_TEXTURE, createDXT),
        commandWithBlobs(OP_UPDATE_TEXTURE, updateDXT,
            [{ offsetField: 32, data: dxtTexture }]),
        command(OP_CREATE_TEXTURE, createDXT3),
        commandWithBlobs(OP_UPDATE_TEXTURE, updateDXT3,
            [{ offsetField: 32, data: dxt3Texture }]),
        command(OP_CREATE_TEXTURE, createDXT5),
        commandWithBlobs(OP_UPDATE_TEXTURE, updateDXT5,
            [{ offsetField: 32, data: dxt5Texture }]),
        ...conversionCommands,
        command(OP_SET_TEXTURE, u32Payload(deviceHandle, 0, textureHandle, 0)),
        command(OP_SET_TEXTURE, u32Payload(deviceHandle, 1, dxtTextureHandle, 0)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 0, 13, 3)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 0, 14, 3)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 0, 16, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 0, 17, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 0, 18, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 1, 1, 4)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 1, 2, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 1, 3, 1)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 1, 4, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE, u32Payload(deviceHandle, 1, 5, 2)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 15, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 24, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 25, 5, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 27, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 19, 5, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 20, 6, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 29, 1, 0)),
        command(OP_SET_VIEWPORT, u32Payload(deviceHandle, 10, 20,
            300, 200, 0, 0x3F800000, 0)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x2C4)),
        command(OP_CLEAR, u32Payload(deviceHandle, 1, 0xFF000000,
            0x3F800000, 0, 0)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(deviceHandle, 4, 1, 40, 3,
                texturedVertices.length, 0, 0),
            [{ offsetField: 24, data: texturedVertices }]),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 24, 128, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 60,
            0x80402010, 0)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(deviceHandle, 4, 1, 40, 3,
                texturedVertices.length, 0, 0),
            [{ offsetField: 24, data: texturedVertices }]),
        commandWithBlobs(OP_UPDATE_TEXTURE, partialUpdate,
            [{ offsetField: 32, data: partialTexture }]),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 4);
    await executor.submit(stage3Batch, { submitCount: 4 });
    assert.equal(executor.failed, null);
    assert.equal(executor.getStats().pipelineCreations, 2);
    assert.equal(executor.getStats().drawCalls, 7);
    assert.equal(fake.calls.filter(call => call[0] === "createTexture").length, 14,
        "fallback, retained back buffer, automatic depth, uncompressed formats, and DXT1/3/5 must be GPU resources");
    const textureWrites = fake.calls.filter(call => call[0] === "writeTexture");
    for (const write of textureWrites.slice(2, 5)) {
        assert.equal(write[2].byteLength, 64,
            "a 4x4 DXT block must decode to 64 RGBA bytes");
        assert.deepEqual(Array.from(write[2].subarray(0, 4)),
            [255, 0, 0, 255]);
    }
    conversionCases.forEach((item, index) => assert.deepEqual(
        Array.from(textureWrites[5 + index][2].subarray(0, 4)), item.expected,
        "format " + item.format + " conversion drifted"));
    assert.equal(fake.calls.filter(call => call[0] === "copyBufferToTexture").length, 1,
        "mid-frame LockRect uploads must stay ordered in the frame encoder");
    assert.ok(fake.calls.some(call => call[0] === "setScissorRect" &&
        call.slice(1).join(",") === "10,20,300,200"));
    const stage3Pipeline = fake.calls.filter(call => call[0] === "createPipeline")
        .at(-1)[1];
    assert.equal(stage3Pipeline.vertex.buffers[0].attributes.length, 5,
        "XYZRHW/DIFFUSE/SPECULAR/TEX2 must expose five vertex attributes");
    assert.ok(stage3Pipeline.fragment.targets[0].blend,
        "alpha blending must be represented in the WebGPU pipeline");
    assert.match(fake.calls.filter(call => call[0] === "shader").at(-1)[1].code,
        /discard;/, "alpha test must be compiled into the fixed-function shader");

    const identity = [
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1,
    ];
    const mapleVertices = Buffer.alloc(3 * 24);
    const mapleView = new DataView(mapleVertices.buffer,
        mapleVertices.byteOffset, mapleVertices.byteLength);
    [[-1, 1, 0.5, 0, 0], [1, 1, 0.5, 1, 0], [-1, -1, 0.5, 0, 1]]
        .forEach((vertex, index) => {
            const offset = index * 24;
            mapleView.setFloat32(offset, vertex[0], true);
            mapleView.setFloat32(offset + 4, vertex[1], true);
            mapleView.setFloat32(offset + 8, vertex[2], true);
            mapleView.setUint32(offset + 12, 0xFFFFFFFF, true);
            mapleView.setFloat32(offset + 16, vertex[3], true);
            mapleView.setFloat32(offset + 20, vertex[4], true);
        });
    const mapleTransformBatch = batch([
        command(OP_SET_TRANSFORM,
            transformPayload(deviceHandle, 256, identity)),
        command(OP_SET_TRANSFORM,
            transformPayload(deviceHandle, 2, identity)),
        command(OP_SET_TRANSFORM,
            transformPayload(deviceHandle, 3, identity)),
        command(OP_SET_VIEWPORT, u32Payload(deviceHandle, 25, 30,
            320, 240, 0, 0x3F800000, 0)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x142)),
        command(OP_CLEAR, u32Payload(deviceHandle, 7, 0xFF000000,
            0x3F800000, 0, 0)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(deviceHandle, 4, 1, 24, 3,
                mapleVertices.length, 0, 0),
            [{ offsetField: 24, data: mapleVertices }]),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 5);
    await executor.submit(mapleTransformBatch, { submitCount: 5 });
    assert.equal(executor.failed, null);
    const maplePipeline = fake.calls.filter(call => call[0] === "createPipeline")
        .at(-1)[1];
    assert.equal(maplePipeline.vertex.buffers[0].arrayStride, 24);
    assert.deepEqual(maplePipeline.vertex.buffers[0].attributes.map(attribute =>
        [attribute.shaderLocation, attribute.offset, attribute.format]), [
        [0, 0, "float32x3"],
        [1, 12, "unorm8x4"],
        [3, 16, "float32x2"],
    ], "Maple FVF 0x142 must decode XYZ, diffuse, and TEX1 without padding");
    assert.ok(maplePipeline.depthStencil,
        "automatic D24S8 must be present in the fixed-function pipeline");
    const mapleShader = fake.calls.filter(call => call[0] === "shader")
        .at(-1)[1].code;
    assert.match(mapleShader,
        /surface\.projection \* eye_position/,
        "XYZ vertices must use the D3D world/view/projection transform");
    assert.ok(fake.calls.some(call => call[0] === "setViewport" &&
        call.slice(1).join(",") === "25,30,320,240,0,1"),
    "XYZ draws must apply the D3D viewport instead of only scissoring");
    assert.ok(fake.calls.some(call => call[0] === "setStencilReference"),
        "the dynamic D3D stencil reference must be set on depth passes");

    const normalVertices = Buffer.alloc(3 * 24);
    const normalView = new DataView(normalVertices.buffer,
        normalVertices.byteOffset, normalVertices.byteLength);
    [[-1, -1, 0, 0, 0, -1], [0, 1, 0, 0, 0, -1], [1, -1, 0, 0, 0, -1]]
        .forEach((vertex, index) => vertex.forEach((value, component) =>
            normalView.setFloat32(index * 24 + component * 4, value, true)));
    const material = [
        0.95, 0.55, 0.12, 1,
        0.15, 0.35, 0.8, 1,
        0, 0, 0, 0,
        0, 0, 0, 0,
        0,
    ];
    const directional = [
        1, 0.95, 0.8, 1,
        0, 0, 0, 0,
        0, 0, 0, 0,
        0, 0, 0,
        0.35, -0.55, 0.75,
        100, 1,
        1, 0, 0,
        0, 0,
    ];
    const lightingBatch = batch([
        command(OP_SET_MATERIAL, materialPayload(deviceHandle, material)),
        command(OP_SET_LIGHT,
            lightPayload(deviceHandle, 0, 3, directional)),
        command(OP_LIGHT_ENABLE, u32Payload(deviceHandle, 0, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 137, 1, 0)),
        command(OP_SET_RENDER_STATE,
            u32Payload(deviceHandle, 139, 0xFF606060, 0)),
        command(OP_SET_TEXTURE_STAGE_STATE,
            u32Payload(deviceHandle, 0, 1, 2)),
        command(OP_SET_TEXTURE_STAGE_STATE,
            u32Payload(deviceHandle, 0, 2, 0)),
        command(OP_SET_TEXTURE_STAGE_STATE,
            u32Payload(deviceHandle, 1, 1, 1)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x12)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(deviceHandle, 4, 1, 24, 3,
                normalVertices.length, 0, 0),
            [{ offsetField: 24, data: normalVertices }]),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 6);
    await executor.submit(lightingBatch, { submitCount: 6 });
    assert.equal(executor.failed, null);
    const lightingPipeline = fake.calls
        .filter(call => call[0] === "createPipeline").at(-1)[1];
    assert.deepEqual(lightingPipeline.vertex.buffers[0].attributes.map(attribute =>
        [attribute.shaderLocation, attribute.offset, attribute.format]), [
        [0, 0, "float32x3"],
        [5, 12, "float32x3"],
    ], "XYZ|NORMAL must preserve the D3D FVF normal offset");
    const lightingShader = fake.calls.filter(call => call[0] === "shader")
        .at(-1)[1].code;
    assert.match(lightingShader, /surface\.lights\[light_index\]/,
        "fixed-function lighting must consume the host light table");
    assert.match(lightingShader,
        /active_material_ambient \* surface\.global_ambient/,
        "fixed-function lighting must include material/global ambient");

    const textureTransformBatch = batch([
        command(OP_SET_TRANSFORM,
            transformPayload(deviceHandle, 16, identity)),
        command(OP_SET_TEXTURE_STAGE_STATE,
            u32Payload(deviceHandle, 0, 11, 0x10000)),
        command(OP_SET_TEXTURE_STAGE_STATE,
            u32Payload(deviceHandle, 0, 24, 2)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 9, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 29, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 143, 1, 0)),
        command(OP_SET_RENDER_STATE, u32Payload(deviceHandle, 171, 2, 0)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x12)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(deviceHandle, 4, 1, 24, 3,
                normalVertices.length, 0, 0),
            [{ offsetField: 24, data: normalVertices }]),
        command(OP_PRESENT, surfacePayload(deviceHandle, 33, 44, 800, 600)),
    ], 7);
    await executor.submit(textureTransformBatch, { submitCount: 7 });
    assert.equal(executor.failed, null);
    const completeFixedPipeline = fake.calls
        .filter(call => call[0] === "createPipeline").at(-1)[1];
    const completeFixedShader = fake.calls
        .filter(call => call[0] === "shader").at(-1)[1].code;
    assert.match(completeFixedShader, /surface\.texture_transforms\[0\]/,
        "stage 4 must apply D3DTS_TEXTURE0 when transform flags are enabled");
    assert.match(completeFixedShader, /@interpolate\(flat\)/,
        "D3DSHADE_FLAT must select flat colour interpolation");
    assert.match(completeFixedShader, /light\.specular \* specular_factor/,
        "fixed-function lighting must evaluate material/light specular");
    assert.match(completeFixedShader, /normalize\(eye_normal_value\)/,
        "D3DRS_NORMALIZENORMALS must normalize transformed normals");
    assert.equal(completeFixedPipeline.fragment.targets[0].blend.color.operation,
        "subtract", "D3DRS_BLENDOP must reach the WebGPU blend pipeline");

    const resourcesBeforeRestore = executor.resources.size;
    const stateCheckpoint = executor.serializeState();
    assert.ok(stateCheckpoint.byteLength > 32,
        "save-state checkpoint must contain canonical D3D8 commands");

    const coldFake = makeFakeWebGPU();
    let coldContextRequests = 0;
    const coldExecutor = new D3D8WebGPUExecutor({
        width: 1,
        height: 1,
        getContext(name) {
            assert.equal(name, "webgpu");
            coldContextRequests++;
            return coldFake.context;
        },
    }, { gpu: coldFake.gpu });
    assert.equal(coldExecutor.context, null,
        "the cold-restore regression must begin before WebGPU initialization");
    await coldExecutor.restoreState(stateCheckpoint);
    assert.equal(coldContextRequests, 1,
        "cold restore must acquire a WebGPU canvas context exactly once");
    assert.equal(coldExecutor.devices.has(deviceHandle), true,
        "cold restore must replay CREATE_DEVICE only after initialization");
    assert.equal(coldExecutor.resources.size, resourcesBeforeRestore,
        "cold restore must rebuild every saved GPU resource");

    const failedFake = makeFakeWebGPU();
    const failedExecutor = new D3D8WebGPUExecutor({
        width: 1,
        height: 1,
        getContext() { return null; },
    }, { gpu: failedFake.gpu });
    const preservedSession = { marker: "must survive initialization failure" };
    failedExecutor.sessions.set("preserved", preservedSession);
    const savedConsoleError = console.error;
    console.error = () => {};
    try {
        await assert.rejects(failedExecutor.restoreState(stateCheckpoint),
            /could not acquire a WebGPU canvas context/);
    } finally {
        console.error = savedConsoleError;
    }
    assert.strictEqual(failedExecutor.sessions.get("preserved"),
        preservedSession,
        "initialization failure must not clear the existing logical namespace");

    await executor.restoreState(stateCheckpoint);
    assert.equal(executor.devices.has(deviceHandle), true);
    assert.equal(executor.resources.size, resourcesBeforeRestore,
        "state restore must rebuild each live resource exactly once");

    const bad = Buffer.from(secondBatch);
    bad.writeUInt32LE(bad.length, 20);
    assert.throws(() => executor.executeBatch(bad, {}), /truncated/);

    const wrongMinor = Buffer.from(secondBatch);
    wrongMinor.writeUInt16LE(0, 6);
    assert.throws(() => executor.executeBatch(wrongMinor, {}),
        /unsupported D8WG minor version/);

    const badUpPayload = u32Payload(deviceHandle, 4, 1, 20, 3, 60,
        0xFFFFFFF0, 0);
    const badUpBatch = batch([
        command(OP_SET_VERTEX_FORMAT, u32Payload(deviceHandle, 0x44)),
        command(OP_DRAW_PRIMITIVE_UP, badUpPayload),
    ], 5);
    assert.throws(() => executor.executeBatch(badUpBatch, {}),
        /outside its D8WG batch/);

    const shortIndexed = batch([
        command(OP_DRAW_INDEXED_PRIMITIVE, u32Payload(deviceHandle, 4, 0)),
    ], 6);
    assert.throws(() => executor.executeBatch(shortIndexed, {}),
        /short DRAW_INDEXED_PRIMITIVE/);

    const staleHandleBatch = batch([
        command(OP_DESTROY_RESOURCE, u32Payload(index32Handle, 2)),
        command(OP_SET_STREAM_SOURCE,
            u32Payload(deviceHandle, 0, bufferHandle, 20)),
        command(OP_SET_INDICES,
            u32Payload(deviceHandle, index32Handle, 0, 0)),
        command(OP_DRAW_INDEXED_PRIMITIVE,
            u32Payload(deviceHandle, 4, 0, 3, 0, 1)),
    ], 8);
    assert.throws(() => executor.executeBatch(staleHandleBatch, {}),
        /unknown index buffer/);

    const destroyDeviceBatch = batch([
        command(OP_DESTROY_RESOURCE, u32Payload(deviceHandle, 0)),
    ], 9);
    executor.executeBatch(destroyDeviceBatch, {});
    assert.equal(executor.devices.has(deviceHandle), false);
    assert.equal(executor.resources.size, 0,
        "destroying a device must release all of its host GPU resources");
    assert.equal(destroys.length, 2);
    assert.equal(destroys.at(-1).reason, "device");
    assert.equal(destroys.at(-1).surface.x, 33);

    const epochFake = makeFakeWebGPU();
    const epochExecutor = new D3D8WebGPUExecutor(canvas, {
        gpu: epochFake.gpu,
        device: epochFake.device,
        context: epochFake.context,
    });
    await epochExecutor.submit(batch([
        command(OP_HELLO, u32Payload(32, 0,
            DEFAULT_SESSION_LOW, DEFAULT_SESSION_HIGH)),
        command(OP_CREATE_DEVICE, createDevicePayload(0x110001, 320, 240)),
    ], 10), {});
    const resetPayload = Buffer.concat([
        u32Payload(0x110001), createDevicePayload(0x120001, 800, 600),
    ]);
    await epochExecutor.submit(batch([
        command(OP_RESET, resetPayload),
    ], 11), {});
    assert.equal(epochExecutor.devices.has(0x110001), false,
        "Reset must retire the old device namespace");
    assert.equal(epochExecutor.devices.has(0x120001), true,
        "Reset must create a fresh device namespace");
    const renderTargetPayload = u32Payload(0x120001, 0x120101,
        32, 32, 1, 21, 1, 0);
    await epochExecutor.submit(batch([
        command(OP_CREATE_TEXTURE, renderTargetPayload),
        command(OP_SET_RENDER_TARGET,
            u32Payload(0x120001, 0x120101, 0, 0)),
        command(OP_CLEAR,
            u32Payload(0x120001, 1, 0xFF18C448, 0x3F800000, 0, 0)),
        command(OP_SET_RENDER_TARGET,
            u32Payload(0x120001, 0, 0, 0)),
    ], 12), {});
    assert.ok(epochExecutor.resources.has(0x120101));
    assert.ok(epochFake.calls.some(call => call[0] === "createTexture" &&
        call[1].size.width === 32 && (call[1].usage & 0x10)),
    "render-target textures must carry WebGPU RENDER_ATTACHMENT usage");
    assert.deepEqual(Array.from(epochExecutor.resources.get(0x120101)
        .shadowLevels[0].data.subarray(0, 4)), [0x48, 0xC4, 0x18, 0xFF],
    "render-target Clear must update the canonical save-state shadow");
    const recoveredFake = makeFakeWebGPU();
    epochExecutor.pipelineCache.set("old-device-pipeline", {});
    epochExecutor.samplerCache.set("old-device-sampler", {});
    await epochExecutor.injectDeviceLoss(recoveredFake.device);
    assert.equal(epochExecutor.failed, null);
    assert.equal(epochExecutor.devices.has(0x120001), true,
        "device-loss recovery must rebuild the current device epoch");
    assert.equal(epochExecutor.resources.has(0x120101), true,
        "device-loss recovery must rebuild render-target resources");
    assert.deepEqual(Array.from(epochExecutor.resources.get(0x120101)
        .shadowLevels[0].data.subarray(0, 4)), [0x48, 0xC4, 0x18, 0xFF],
    "device-loss recovery must preserve render-target clear contents");
    assert.equal(epochExecutor.pipelineCache.size, 0,
        "device-loss recovery must discard pipelines owned by the lost GPUDevice");
    assert.equal(epochExecutor.samplerCache.size, 0,
        "device-loss recovery must discard samplers owned by the lost GPUDevice");
    assert.equal(epochExecutor.getStats().deviceRecoveries, 1);

    const resourceBaseline = epochExecutor.resources.size;
    for (let iteration = 0; iteration < 192; iteration++) {
        const handle = 0x130000 + iteration;
        await epochExecutor.submit(batch([
            command(OP_CREATE_BUFFER, u32Payload(0x120001, handle,
                1, 256, 0, 0, 1, 0)),
            command(OP_DESTROY_RESOURCE, u32Payload(handle, 1)),
        ], 20 + iteration), {});
    }
    assert.equal(epochExecutor.resources.size, resourceBaseline,
        "192 create/destroy cycles must not grow the live GPU resource map");

    let currentEpoch = 0x120001;
    for (let iteration = 0; iteration < 24; iteration++) {
        const oldEpoch = currentEpoch;
        const nextEpoch = 0x140000 + iteration;
        const childHandle = 0x150000 + iteration;
        await epochExecutor.submit(batch([
            command(OP_CREATE_BUFFER, u32Payload(oldEpoch, childHandle,
                1, 128, 0, 0, 1, 0)),
            command(OP_RESET, Buffer.concat([
                u32Payload(oldEpoch),
                createDevicePayload(nextEpoch, 400 + iteration, 300),
            ])),
        ], 300 + iteration), {});
        await epochExecutor.submit(batch([
            command(OP_UPDATE_BUFFER, u32Payload(childHandle, 0, 4,
                0, 0, 0)),
            command(OP_SET_STREAM_SOURCE,
                u32Payload(oldEpoch, 0, childHandle, 20)),
            command(OP_DRAW_PRIMITIVE,
                u32Payload(oldEpoch, 4, 0, 1, 0, 0)),
        ], 400 + iteration), {});
        currentEpoch = nextEpoch;
    }
    assert.equal(epochExecutor.devices.size, 1,
        "repeated Reset must retain exactly one live device epoch");
    assert.equal(epochExecutor.resources.size, 0,
        "repeated Reset must destroy every child from the retired epoch");
    assert.ok(epochExecutor.getStats().staleCommandsDropped >= 24 * 3,
        "stale batches must be dropped before they can touch a new epoch");

    const clearFake = makeFakeWebGPU({ deferSubmittedWork: true });
    const clearExecutor = new D3D8WebGPUExecutor(canvas, {
        gpu: clearFake.gpu,
        device: clearFake.device,
        context: clearFake.context,
    });
    const clearDevice = 0x1C0001;
    const clearSession = [0xC1EA0001, 0x20260802];
    const rectangleClear = Buffer.alloc(40);
    rectangleClear.writeUInt32LE(clearDevice, 0);
    rectangleClear.writeUInt32LE(7, 4);
    rectangleClear.writeUInt32LE(0xFF23DC5A, 8);
    rectangleClear.writeFloatLE(0.25, 12);
    rectangleClear.writeUInt32LE(0x5A, 16);
    rectangleClear.writeUInt32LE(1, 20);
    rectangleClear.writeInt32LE(12, 24);
    rectangleClear.writeInt32LE(18, 28);
    rectangleClear.writeInt32LE(112, 32);
    rectangleClear.writeInt32LE(98, 36);
    await clearExecutor.submit(batch([
        command(OP_HELLO, u32Payload(32, 0,
            clearSession[0], clearSession[1])),
        command(OP_CREATE_DEVICE, createDevicePayload(clearDevice, 320, 240)),
        command(OP_CLEAR, u32Payload(clearDevice, 7, 0xFF000000,
            0x3F800000, 0, 0)),
        command(OP_CLEAR, rectangleClear),
        command(OP_PRESENT, surfacePayload(clearDevice, 11, 22, 320, 240)),
    ], 1, clearSession[0], clearSession[1]), {});
    assert.equal(clearExecutor.failed, null);
    assert.equal(clearExecutor.getStats().rectangularClears, 1,
        "a D3DRECT Clear must be executed as a scoped GPU clear draw");
    assert.ok(clearFake.calls.some(call => call[0] === "setScissorRect" &&
        call.slice(1).join(",") === "12,18,100,80"),
    "rectangular Clear must preserve the requested D3DRECT");
    const clearPipeline = clearFake.calls.find(call =>
        call[0] === "createPipeline" &&
        String(call[1].label).includes("rectangular Clear"));
    assert.equal(clearPipeline[1].depthStencil.depthWriteEnabled, true);
    assert.equal(clearPipeline[1].depthStencil.stencilFront.passOp, "replace");
    assert.match(clearPipeline[1].vertex.module.code,
        /depth:\s*vec4<f32>/,
        "ClearData must remain two vec4 values so its WGSL size is 32 bytes");
    const clearBindGroup = clearFake.calls.find(call =>
        call[0] === "createBindGroup" &&
        call[1].entries?.[0]?.resource?.buffer?.descriptor?.label ===
            "D3D8 rectangular Clear uniforms");
    assert.equal(clearBindGroup[1].entries[0].resource.size, 32,
        "the rectangular Clear bind group must bind the complete 32-byte uniform");

    const retiredTextureHandle = 0x1C0002;
    const retiredPixel = Buffer.from([0x20, 0x80, 0xF0, 0xFF]);
    const retiredVertices = vertices.subarray(0, 60);
    await clearExecutor.submit(batch([
        command(OP_CREATE_TEXTURE, u32Payload(clearDevice,
            retiredTextureHandle, 1, 1, 1, 21, 0, 1)),
        commandWithBlobs(OP_UPDATE_TEXTURE,
            u32Payload(retiredTextureHandle, 0, 0, 0,
                1, 1, 4, 4, 0, 0),
            [{ offsetField: 32, data: retiredPixel }]),
        command(OP_SET_VERTEX_FORMAT, u32Payload(clearDevice, 0x44)),
        command(OP_CLEAR, u32Payload(clearDevice, 1, 0xFF000000,
            0x3F800000, 0, 0)),
        command(OP_BEGIN_SCENE, u32Payload(clearDevice, 0)),
        command(OP_SET_TEXTURE, u32Payload(clearDevice, 0,
            retiredTextureHandle, 0)),
        commandWithBlobs(OP_DRAW_PRIMITIVE_UP,
            u32Payload(clearDevice, 4, 1, 20, 3,
                retiredVertices.length, 0, 0),
            [{ offsetField: 24, data: retiredVertices }]),
        command(OP_SET_TEXTURE, u32Payload(clearDevice, 0, 0, 0)),
        command(OP_DESTROY_RESOURCE, u32Payload(retiredTextureHandle, 3)),
        command(OP_END_SCENE, u32Payload(clearDevice, 0)),
        command(OP_PRESENT, surfacePayload(clearDevice, 11, 22, 320, 240)),
    ], 2, clearSession[0], clearSession[1]), {});
    const retiredTexture = clearFake.calls.find(call =>
        call[0] === "createTexture" &&
        call[1].label === "D3D8 texture " +
            retiredTextureHandle.toString(16))[2];
    assert.equal(retiredTexture.destroyed, false,
        "a texture referenced by an uncompleted submit must remain alive");
    clearFake.completeSubmittedWork();
    await Promise.resolve();
    await Promise.resolve();
    assert.equal(retiredTexture.destroyed, true,
        "retired textures must be destroyed after queue completion");

    const sessionFake = makeFakeWebGPU();
    const sessionExecutor = new D3D8WebGPUExecutor(canvas, {
        gpu: sessionFake.gpu,
        device: sessionFake.device,
        context: sessionFake.context,
    });
    const reusedDevice = 0x00100001;
    const reusedTexture = 0x00100002;
    const sessionA = [0x11111111, 0xAAAAAAAA];
    const sessionB = [0x22222222, 0xBBBBBBBB];
    const createReusedTexture = u32Payload(reusedDevice, reusedTexture,
        8, 8, 1, 21, 0, 1);
    for (const [low, high] of [sessionA, sessionB]) {
        await sessionExecutor.submit(batch([
            command(OP_HELLO, u32Payload(32, 0, low, high)),
            command(OP_CREATE_DEVICE,
                createDevicePayload(reusedDevice, 320, 240)),
            command(OP_CREATE_TEXTURE, createReusedTexture),
        ], low & 0xFFFF, low, high), {});
    }
    assert.equal(sessionExecutor.failed, null);
    assert.equal(sessionExecutor.getStats().sessionsLive, 2,
        "identical handles from two guest processes must occupy two sessions");
    assert.equal(sessionExecutor.getStats().devicesLive, 2);
    assert.equal(sessionExecutor.getStats().resourcesLive, 2);

    const multiSessionCheckpoint = sessionExecutor.serializeState();
    await sessionExecutor.restoreState(multiSessionCheckpoint);
    assert.equal(sessionExecutor.getStats().sessionsLive, 2,
        "save/load must restore every live D3D8 process session");
    assert.equal(sessionExecutor.getStats().devicesLive, 2);
    assert.equal(sessionExecutor.getStats().resourcesLive, 2);

    await sessionExecutor.submit(batch([
        command(OP_DESTROY_RESOURCE, u32Payload(reusedDevice, 0)),
    ], 30, sessionA[0], sessionA[1]), {});
    assert.equal(sessionExecutor.getStats().devicesLive, 1);
    assert.equal(sessionExecutor.getStats().resourcesLive, 1);
    const sessionBState = sessionExecutor.sessions.get(
        sessionExecutor.sessionKey(sessionB[0], sessionB[1]));
    assert.equal(sessionBState.devices.has(reusedDevice), true,
        "destroying an old process must not destroy a new process using the same handle");
    assert.equal(sessionBState.resources.has(reusedTexture), true);

    // A delayed duplicate teardown from session A is stale only in session A.
    await sessionExecutor.submit(batch([
        command(OP_DESTROY_RESOURCE, u32Payload(reusedDevice, 0)),
    ], 31, sessionA[0], sessionA[1]), {});
    assert.equal(sessionExecutor.failed, null);
    assert.equal(sessionBState.devices.has(reusedDevice), true);
    assert.equal(sessionBState.resources.has(reusedTexture), true);

    await testShaderModel1x();

    console.log("d3d8_webgpu_executor_test: ok");
}

// ---- Stage 6: D3D8 shader model 1.x ----

const VS_1_1 = 0xFFFE0101;
const PS_1_1 = 0xFFFF0101;
const PS_1_2 = 0xFFFF0102;
const PS_1_4 = 0xFFFF0104;
const SHADER_END = 0x0000FFFF;
// Every register-encoded parameter token sets bit 31 in real D3D8 bytecode.
const PARAM = 0x80000000;
const WRITEMASK_ALL = 0x000F0000;
const NOSWIZZLE = 0xE4 << 16;
const REG_TEMP = 0 << 28;
const REG_INPUT = 1 << 28;
const REG_CONST = 2 << 28;
const REG_TEXTURE = 3 << 28;
const REG_RASTOUT = 4 << 28;
const REG_ATTROUT = 5 << 28;
const REG_TEXCRDOUT = 6 << 28;
const SATURATE = 1 << 20;

const SIO = {
    NOP: 0, MOV: 1, ADD: 2, SUB: 3, MAD: 4, MUL: 5, RCP: 6, RSQ: 7,
    DP3: 8, DP4: 9, MIN: 10, MAX: 11, SLT: 12, SGE: 13, EXP: 14, LOG: 15,
    LIT: 16, DST: 17, LRP: 18, FRC: 19, M4x4: 20,
    TEXCOORD: 64, TEXKILL: 65, TEX: 66, EXPP: 78, LOGP: 79, CND: 80,
    DEF: 81, CMP: 88,
};

function dst(type, num, extra = 0) {
    return (PARAM | type | num | WRITEMASK_ALL | extra) >>> 0;
}

function src(type, num, extra = 0) {
    return (PARAM | type | num | NOSWIZZLE | extra) >>> 0;
}

// The declaration the guest's own reference shader test uses: a float4
// position plus a D3DCOLOR diffuse, which the executor numbers v0/v1 by
// stream order.
const REFERENCE_DECL = [
    0x20000000,          // D3DVSD_STREAM(0)
    0x40030000,          // D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT4)
    0x40040005,          // D3DVSD_REG(D3DVSDE_DIFFUSE,  D3DVSDT_D3DCOLOR)
    0xFFFFFFFF,          // D3DVSD_END()
];

function vsWgsl(bodyTokens, declTokens = REFERENCE_DECL) {
    return vertexShaderWgsl([VS_1_1, ...bodyTokens, SHADER_END],
        parseVertexDeclaration(declTokens));
}

function psWgsl(bodyTokens, version = PS_1_1) {
    return pixelShaderWgsl([version, ...bodyTokens, SHADER_END]);
}

function assertRejects(label, run) {
    assert.throws(run, Error, label + " must be rejected, not mistranslated");
}

async function testShaderModel1x() {
    // --- vertex declaration parsing ---
    const decl = parseVertexDeclaration(REFERENCE_DECL);
    assert.deepEqual(decl.attributes, [
        { shaderLocation: 0, offset: 0, format: "float32x4" },
        { shaderLocation: 1, offset: 16, format: "unorm8x4" },
    ], "declaration must map D3DVSD_REG entries to sequential v0/v1 inputs");
    assert.equal(decl.stride, 20);

    // Narrower input types must declare the matching WGSL type and be
    // widened to vec4 on read, or the generated module would not compile.
    const narrow = parseVertexDeclaration([
        0x20000000, 0x40020000 /* FLOAT3 */, 0x40000005 /* FLOAT1 */,
        0xFFFFFFFF,
    ]);
    assert.deepEqual(narrow.attributes.map(a => a.format),
        ["float32x3", "float32"]);
    const narrowWgsl = vertexShaderWgsl(
        [VS_1_1, SIO.MOV, dst(REG_RASTOUT, 0), src(REG_INPUT, 0),
            SIO.MOV, dst(REG_ATTROUT, 0), src(REG_INPUT, 1), SHADER_END],
        narrow);
    assert.match(narrowWgsl, /@location\(0\) v0: vec3<f32>/);
    assert.match(narrowWgsl, /@location\(1\) v1: f32/);
    assert.match(narrowWgsl, /vec4<f32>\(input\.v0, 1\.0\)/,
        "a FLOAT3 input must be widened to vec4 with w=1");
    assert.match(narrowWgsl, /vec4<f32>\(input\.v1, 0\.0, 0\.0, 1\.0\)/);

    assertRejects("D3DVSD_SKIP",
        () => parseVertexDeclaration([0x20000000, 0x50010000, 0xFFFFFFFF]));
    assertRejects("declaration with no D3DVSD_REG entries",
        () => parseVertexDeclaration([0x20000000, 0xFFFFFFFF]));

    // --- per-instruction VS1.1 numeric translation ---
    // Each supported opcode gets its own assertion on the emitted WGSL
    // expression, per the doc's "every supported instruction has its own
    // numeric test" exit criterion.
    const v0 = src(REG_INPUT, 0);
    const v1 = src(REG_INPUT, 1);
    const c0 = src(REG_CONST, 0);
    const r0d = dst(REG_TEMP, 0);
    const vsCases = [
        [[SIO.MOV, r0d, v0], /r0 = input\.v0\.xyzw;/],
        [[SIO.ADD, r0d, v0, v1], /input\.v0\.xyzw \+ input\.v1\.xyzw/],
        [[SIO.SUB, r0d, v0, v1], /input\.v0\.xyzw - input\.v1\.xyzw/],
        [[SIO.MUL, r0d, v0, v1], /input\.v0\.xyzw \* input\.v1\.xyzw/],
        [[SIO.MAD, r0d, v0, v1, c0],
            /input\.v0\.xyzw \* input\.v1\.xyzw \+ constants\.vs\[0\]\.xyzw/],
        [[SIO.RCP, r0d, v0], /1\.0 \/ \(input\.v0\.xyzw\)\.x/],
        [[SIO.RSQ, r0d, v0], /inverseSqrt\(max\(abs\(\(input\.v0\.xyzw\)\.x\), 1e-12\)\)/],
        [[SIO.DP3, r0d, v0, v1],
            /dot\(\(input\.v0\.xyzw\)\.xyz, \(input\.v1\.xyzw\)\.xyz\)/],
        [[SIO.DP4, r0d, v0, v1], /dot\(input\.v0\.xyzw, input\.v1\.xyzw\)/],
        [[SIO.MIN, r0d, v0, v1], /min\(input\.v0\.xyzw, input\.v1\.xyzw\)/],
        [[SIO.MAX, r0d, v0, v1], /max\(input\.v0\.xyzw, input\.v1\.xyzw\)/],
        [[SIO.SLT, r0d, v0, v1], /select\(vec4<f32>\(0\.0\), vec4<f32>\(1\.0\), input\.v0\.xyzw < input\.v1\.xyzw\)/],
        [[SIO.SGE, r0d, v0, v1], /select\(vec4<f32>\(0\.0\), vec4<f32>\(1\.0\), input\.v0\.xyzw >= input\.v1\.xyzw\)/],
        [[SIO.EXP, r0d, v0], /exp2\(\(input\.v0\.xyzw\)\.x\)/],
        [[SIO.LOG, r0d, v0], /log2\(max\(abs\(\(input\.v0\.xyzw\)\.x\), 1e-12\)\)/],
        [[SIO.EXPP, r0d, v0], /exp2\(/],
        [[SIO.LOGP, r0d, v0], /log2\(/],
        [[SIO.FRC, r0d, v0], /fract\(input\.v0\.xyzw\)/],
        [[SIO.DST, r0d, v0, v1], /vec4<f32>\(1\.0, \(input\.v0\.xyzw\)\.y \* \(input\.v1\.xyzw\)\.y/],
        [[SIO.LIT, r0d, v0], /pow\(max\(/],
    ];
    for (const [body, pattern] of vsCases) {
        const wgsl = vsWgsl(body);
        assert.match(wgsl, pattern,
            "VS opcode " + body[0] + " translated unexpectedly");
    }

    // Output register mapping: oPos/oD0/oD1/oT0..oT7.
    assert.match(vsWgsl([SIO.MOV, dst(REG_RASTOUT, 0), v0]),
        /output\.position = /);
    assert.match(vsWgsl([SIO.MOV, dst(REG_ATTROUT, 0), v0]),
        /output\.diffuse = /);
    assert.match(vsWgsl([SIO.MOV, dst(REG_ATTROUT, 1), v0]),
        /output\.specular = /);
    assert.match(vsWgsl([SIO.MOV, dst(REG_TEXCRDOUT, 3), v0]),
        /output\.texcoord3 = /);

    // Write masks, saturate, and destination shift.
    assert.match(
        vsWgsl([SIO.MOV, (PARAM | REG_TEMP | 0 | 0x00030000) >>> 0, v0]),
        /r0\.xy = \(input\.v0\.xyzw\)\.xy;/,
        "a partial write mask must only assign the masked components");
    assert.match(vsWgsl([SIO.MOV, dst(REG_TEMP, 0, SATURATE), v0]),
        /clamp\(input\.v0\.xyzw, vec4<f32>\(0\.0\), vec4<f32>\(1\.0\)\)/);
    assert.match(
        vsWgsl([SIO.MOV, dst(REG_TEMP, 0, 1 << 24 /* _x2 */), v0]),
        /\* 2\)/, "destination shift _x2 must scale the result");

    // Source modifiers.
    assert.match(vsWgsl([SIO.MOV, r0d, src(REG_INPUT, 0, 1 << 24 /* neg */)]),
        /\(-input\.v0\.xyzw\)/);
    assert.match(vsWgsl([SIO.MOV, r0d, src(REG_INPUT, 0, 2 << 24 /* bias */)]),
        /input\.v0\.xyzw - vec4<f32>\(0\.5\)/);
    assert.match(vsWgsl([SIO.MOV, r0d, src(REG_INPUT, 0, 6 << 24 /* comp */)]),
        /vec4<f32>\(1\.0\) - input\.v0\.xyzw/);

    // Arbitrary swizzles must survive verbatim. Each component is a 2-bit
    // selector, low pair first: 0x1B = 0b00_01_10_11 -> .wzyx (compare
    // D3DVS_NOSWIZZLE 0xE4 = 0b11_10_01_00 -> .xyzw).
    assert.match(
        vsWgsl([SIO.MOV, r0d, (PARAM | REG_INPUT | 0 | (0x1B << 16)) >>> 0]),
        /input\.v0\.wzyx/);
    assert.match(
        vsWgsl([SIO.MOV, r0d, (PARAM | REG_INPUT | 0 | (0x00 << 16)) >>> 0]),
        /input\.v0\.xxxx/, "an all-zero swizzle byte replicates .x");

    // DEF must fold into a literal and win over the uniform constant bank.
    const defBody = [
        SIO.DEF, dst(REG_CONST, 5),
        0x3F800000, 0x40000000, 0x40400000, 0x40800000, // 1,2,3,4
        SIO.MOV, r0d, src(REG_CONST, 5),
    ];
    const defWgsl = vsWgsl(defBody);
    assert.doesNotMatch(defWgsl, /constants\.vs\[5\]/,
        "a DEF-ed register must inline as a literal, not read the uniform bank");
    assert.match(defWgsl, /vec4<f32>\(1e\+0, 2e\+0, 3e\+0, 4e\+0\)/);

    // --- VS rejection cases ---
    assertRejects("vs_1_0", () => vertexShaderWgsl(
        [0xFFFE0100, SHADER_END], decl));
    assertRejects("a pixel-shader version token in CreateVertexShader",
        () => vertexShaderWgsl([PS_1_1, SHADER_END], decl));
    assertRejects("D3DSIO_M4x4 (legal D3D8, outside Stage 6)",
        () => vsWgsl([SIO.M4x4, r0d, v0]));
    assertRejects("a pixel-only opcode in a vertex shader",
        () => vsWgsl([SIO.TEX, dst(REG_TEXTURE, 0)]));
    // The D8WG wire format carries an exact instruction_token_count and the
    // guest strips the trailing END sentinel, so reaching the end of the
    // token array is a normal, complete body -- but an instruction whose
    // operands run past that end is truncation and must be rejected.
    assert.match(vertexShaderWgsl([VS_1_1, SIO.MOV, r0d, v0], decl),
        /r0 = input\.v0\.xyzw;/,
        "a body that ends without an explicit END token is still complete");
    assertRejects("a truncated final instruction",
        () => vertexShaderWgsl([VS_1_1, SIO.MOV, r0d], decl));
    assertRejects("a truncated DEF immediate block",
        () => vertexShaderWgsl(
            [VS_1_1, SIO.DEF, dst(REG_CONST, 0), 0x3F800000], decl));
    assertRejects("a read of an undeclared vertex input",
        () => vsWgsl([SIO.MOV, r0d, src(REG_INPUT, 7)]));
    assertRejects("an out-of-range vertex constant register",
        () => vsWgsl([SIO.MOV, r0d, src(REG_CONST, 96)]));
    assertRejects("an unsupported source modifier",
        () => vsWgsl([SIO.MOV, r0d, src(REG_INPUT, 0, 9 << 24 /* _dz */)]));

    // --- per-instruction PS1.1-1.4 translation ---
    const t0 = src(REG_TEXTURE, 0);
    assert.match(psWgsl([SIO.MOV, r0d, src(REG_INPUT, 0)]),
        /r0 = input\.diffuse\.xyzw;/);
    assert.match(psWgsl([SIO.MOV, r0d, src(REG_INPUT, 1)]),
        /r0 = input\.specular\.xyzw;/);
    assert.match(psWgsl([SIO.MOV, r0d, src(REG_CONST, 3)]),
        /constants\.ps\[3\]/);
    assert.match(psWgsl([SIO.TEXCOORD, dst(REG_TEXTURE, 0)]),
        /t0 = vec4<f32>\(input\.texcoord0\.xy, 0\.0, 1\.0\);/);
    assert.match(psWgsl([SIO.TEX, dst(REG_TEXTURE, 0)]),
        /t0 = textureSample\(stage0Texture, stage0Sampler, t0\.xy\);/,
        "ps_1_1 tex samples into the texture register itself");
    assert.match(psWgsl([SIO.TEX, dst(REG_TEMP, 0), t0], PS_1_4),
        /r0 = textureSample\(stage0Texture, stage0Sampler, t0\.xy\);/,
        "ps_1_4 texld takes an explicit coordinate source");
    assert.match(psWgsl([SIO.TEXKILL, dst(REG_TEXTURE, 0)]), /discard;/);
    assert.match(
        psWgsl([SIO.LRP, r0d, src(REG_CONST, 0), src(REG_INPUT, 0),
            src(REG_INPUT, 1)]),
        /mix\(input\.specular\.xyzw, input\.diffuse\.xyzw, constants\.ps\[0\]\.xyzw\)/,
        "D3D8 lrp is mix(src2, src1, src0), not mix(src0, src1, src2)");
    assert.match(
        psWgsl([SIO.CND, r0d, src(REG_CONST, 0), src(REG_INPUT, 0),
            src(REG_INPUT, 1)]),
        /> vec4<f32>\(0\.5\)/, "cnd compares against 0.5");
    assert.match(
        psWgsl([SIO.CMP, r0d, src(REG_CONST, 0), src(REG_INPUT, 0),
            src(REG_INPUT, 1)], PS_1_2),
        />= vec4<f32>\(0\.0\)/, "cmp compares against 0");

    // r0 is the implicit ps.1.x output register and must be declared exactly
    // once even when the body also names it.
    const psDecls = psWgsl([SIO.MOV, r0d, src(REG_INPUT, 0)])
        .match(/var r0: vec4<f32>/g);
    assert.equal(psDecls.length, 1, "r0 must be declared exactly once");
    assert.match(psWgsl([SIO.NOP]), /var r0: vec4<f32>/,
        "r0 must still be declared for a shader that never writes it");

    // --- PS rejection cases ---
    assertRejects("ps_1_5", () => psWgsl([SIO.NOP], 0xFFFF0105));
    assertRejects("ps_2_0", () => psWgsl([SIO.NOP], 0xFFFF0200));
    assertRejects("cmp on ps_1_1 (needs 1.2+)",
        () => psWgsl([SIO.CMP, r0d, src(REG_CONST, 0), src(REG_INPUT, 0),
            src(REG_INPUT, 1)], PS_1_1));
    assertRejects("cnd on ps_1_4 (removed after 1.3)",
        () => psWgsl([SIO.CND, r0d, src(REG_CONST, 0), src(REG_INPUT, 0),
            src(REG_INPUT, 1)], PS_1_4));
    assertRejects("a vertex-only opcode in a pixel shader",
        () => psWgsl([SIO.RCP, r0d, src(REG_INPUT, 0)]));
    assertRejects("a texture stage beyond this backend's 2-stage limit",
        () => psWgsl([SIO.TEXCOORD, dst(REG_TEXTURE, 4)]));
    assertRejects("an out-of-range pixel constant register",
        () => psWgsl([SIO.MOV, r0d, src(REG_CONST, 8)]));

    // Comments must be skipped by length, not by scanning for the next
    // recognizable opcode -- a comment payload can contain anything.
    const commentToken = ((2 << 16) | 0xFFFE) >>> 0; // 2-DWORD comment
    const withComment = vsWgsl([
        commentToken, SIO.M4x4 /* payload, not an instruction */, 0xDEADBEEF,
        SIO.MOV, r0d, v0,
    ]);
    assert.match(withComment, /r0 = input\.v0\.xyzw;/,
        "comment payloads must be skipped without being decoded");

    // --- end-to-end: create, bind, draw through the executor ---
    const fake = makeFakeWebGPU();
    const canvas = {
        width: 1, height: 1,
        getContext(name) { assert.equal(name, "webgpu"); return fake.context; },
    };
    const executor = new D3D8WebGPUExecutor(canvas, { gpu: fake.gpu });
    const deviceHandle = 0x00100010;
    const vsHandle = 0x40000001; // real shader handles always carry bit 0
    const psHandle = 0x40000003;
    const vertexBuffer = 0x00100011;

    const vsBody = Buffer.alloc(8 * 4);
    [VS_1_1,
        SIO.MOV, dst(REG_RASTOUT, 0), src(REG_INPUT, 0),
        SIO.MOV, dst(REG_ATTROUT, 0), src(REG_INPUT, 1),
    ].forEach((token, i) => vsBody.writeUInt32LE(token >>> 0, i * 4));
    const declBuffer = Buffer.alloc(3 * 4);
    [0x20000000, 0x40030000, 0x40040005].forEach((token, i) =>
        declBuffer.writeUInt32LE(token >>> 0, i * 4));
    const psBody = Buffer.alloc(4 * 4);
    [PS_1_1, SIO.MOV, dst(REG_TEMP, 0), src(REG_INPUT, 0)]
        .forEach((token, i) => psBody.writeUInt32LE(token >>> 0, i * 4));

    const createVs = Buffer.alloc(24);
    createVs.writeUInt32LE(deviceHandle, 0);
    createVs.writeUInt32LE(vsHandle, 4);
    createVs.writeUInt32LE(declBuffer.length / 4, 8);
    createVs.writeUInt32LE(vsBody.length / 4, 16);
    const createPs = Buffer.alloc(16);
    createPs.writeUInt32LE(deviceHandle, 0);
    createPs.writeUInt32LE(psHandle, 4);
    createPs.writeUInt32LE(psBody.length / 4, 8);

    const vertexData = Buffer.alloc(3 * 20);
    for (let i = 0; i < 3; i++) {
        vertexData.writeFloatLE(i * 10, i * 20);
        vertexData.writeFloatLE(i * 10, i * 20 + 4);
        vertexData.writeFloatLE(0.5, i * 20 + 8);
        vertexData.writeFloatLE(1, i * 20 + 12);
        vertexData.writeUInt32LE(0xFFFFFFFF, i * 20 + 16);
    }
    const createVb = Buffer.alloc(32);
    createVb.writeUInt32LE(deviceHandle, 0);
    createVb.writeUInt32LE(vertexBuffer, 4);
    createVb.writeUInt32LE(1, 8);
    createVb.writeUInt32LE(vertexData.length, 12);
    const updateVb = Buffer.alloc(24);
    updateVb.writeUInt32LE(vertexBuffer, 0);
    updateVb.writeUInt32LE(0, 4);
    updateVb.writeUInt32LE(vertexData.length, 8);

    const vsConstants = Buffer.alloc(2 * 16);
    vsConstants.writeFloatLE(0.25, 0);
    const setVsConstant = Buffer.alloc(16);
    setVsConstant.writeUInt32LE(deviceHandle, 0);
    setVsConstant.writeUInt32LE(0, 4);
    setVsConstant.writeUInt32LE(2, 8);

    await executor.submit(batch([
        command(OP_HELLO, u32Payload(32, 0,
            DEFAULT_SESSION_LOW, DEFAULT_SESSION_HIGH)),
        command(OP_CREATE_DEVICE, createDevicePayload(deviceHandle, 320, 240)),
        commandWithBlobs(OP_CREATE_VERTEX_SHADER, createVs, [
            { offsetField: 12, data: declBuffer },
            { offsetField: 20, data: vsBody },
        ]),
        commandWithBlobs(OP_CREATE_PIXEL_SHADER, createPs, [
            { offsetField: 12, data: psBody },
        ]),
        command(OP_CREATE_BUFFER, createVb),
        command(OP_UPDATE_BUFFER, updateVb, vertexData),
        commandWithBlobs(OP_SET_VERTEX_SHADER_CONSTANT, setVsConstant, [
            { offsetField: 12, data: vsConstants },
        ]),
        command(OP_SET_VERTEX_SHADER, u32Payload(deviceHandle, vsHandle)),
        command(OP_SET_PIXEL_SHADER, u32Payload(deviceHandle, psHandle)),
        command(OP_SET_STREAM_SOURCE,
            u32Payload(deviceHandle, 0, vertexBuffer, 20)),
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(deviceHandle, 4, 0, 1)),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 0, 0, 320, 240)),
    ], 1), { submitCount: 1 });

    assert.equal(executor.failed, null, "a real SM1.x draw must not fail");
    assert.equal(executor.getStats().drawCalls, 1);
    assert.equal(executor.getStats().pipelineCreations, 1);
    assert.equal(executor.getStats().unsupportedCommands, 0,
        "a real shader draw must not fall into the unsupported-FVF path");

    // The generated module must come from the shader path, and the vertex
    // layout must follow the declaration rather than any FVF.
    const shaderCalls = fake.calls.filter(call => call[0] === "shader");
    assert.equal(shaderCalls.length, 1);
    assert.match(shaderCalls[0][1].code, /@vertex fn vs_main/);
    assert.match(shaderCalls[0][1].code, /@fragment fn fs_main/);
    assert.equal(
        (shaderCalls[0][1].code.match(/struct D8WGShaderConstants/g) || []).length,
        1, "the combined module must declare its uniform block exactly once");
    const pipelineCalls = fake.calls.filter(call => call[0] === "createPipeline");
    assert.deepEqual(pipelineCalls[0][1].vertex.buffers[0].attributes, [
        { shaderLocation: 0, offset: 0, format: "float32x4" },
        { shaderLocation: 1, offset: 16, format: "unorm8x4" },
    ]);

    // A second identical draw must reuse the cached pipeline: the doc's
    // "steady-state pipeline creation = 0/frame" budget applies to the
    // shader path too.
    await executor.submit(batch([
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(deviceHandle, 4, 0, 1)),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 0, 0, 320, 240)),
    ], 2), { submitCount: 2 });
    assert.equal(executor.failed, null);
    assert.equal(executor.getStats().drawCalls, 2);
    assert.equal(executor.getStats().pipelineCreations, 1,
        "rebinding the same shader pair must not rebuild the pipeline");

    // A v86 save/load must carry shaders, their bindings, and their constant
    // banks across the checkpoint; otherwise the first draw after a restore
    // hits an unresolved shader handle.
    const checkpoint = executor.serializeState();
    await executor.restoreState(checkpoint);
    assert.equal(executor.failed, null, "restoring a shader session must work");
    const restored = executor.devices.get(deviceHandle);
    assert.equal(restored.vertexShader, vsHandle,
        "the bound vertex shader must survive save/load");
    assert.equal(restored.pixelShader, psHandle);
    assert.equal(restored.vsConstants[0], 0.25,
        "shader constants must survive save/load");
    assert.equal(executor.resources.get(vsHandle).kind, 4);
    assert.equal(executor.resources.get(psHandle).kind, 5);

    // ...and the restored session must still be able to draw.
    await executor.submit(batch([
        command(OP_BEGIN_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(deviceHandle, 4, 0, 1)),
        command(OP_END_SCENE, u32Payload(deviceHandle, 0)),
        command(OP_PRESENT, surfacePayload(deviceHandle, 0, 0, 320, 240)),
    ], 4), { submitCount: 4 });
    assert.equal(executor.failed, null,
        "a restored shader session must keep drawing");
    assert.equal(executor.getStats().unsupportedCommands, 0);

    // Reset keeps app-visible shader handles stable (unlike buffer/texture
    // handles, which are private to the guest and get renumbered), because
    // the application still holds the DWORD it got from CreateVertexShader.
    // The host must therefore accept the same handle being re-created under
    // the new device epoch even though Reset retired it.
    const resetDevice = 0x00100020;
    await executor.submit(batch([
        command(OP_RESET, Buffer.concat([
            u32Payload(deviceHandle),
            createDevicePayload(resetDevice, 320, 240),
        ])),
        commandWithBlobs(OP_CREATE_VERTEX_SHADER, (() => {
            const p = Buffer.alloc(24);
            p.writeUInt32LE(resetDevice, 0);
            p.writeUInt32LE(vsHandle, 4);
            p.writeUInt32LE(declBuffer.length / 4, 8);
            p.writeUInt32LE(vsBody.length / 4, 16);
            return p;
        })(), [
            { offsetField: 12, data: declBuffer },
            { offsetField: 20, data: vsBody },
        ]),
        commandWithBlobs(OP_CREATE_PIXEL_SHADER, (() => {
            const p = Buffer.alloc(16);
            p.writeUInt32LE(resetDevice, 0);
            p.writeUInt32LE(psHandle, 4);
            p.writeUInt32LE(psBody.length / 4, 8);
            return p;
        })(), [{ offsetField: 12, data: psBody }]),
        command(OP_SET_VERTEX_SHADER, u32Payload(resetDevice, vsHandle)),
        command(OP_SET_PIXEL_SHADER, u32Payload(resetDevice, psHandle)),
    ], 5), {});
    assert.equal(executor.failed, null,
        "re-creating a stable shader handle after Reset must be accepted");
    assert.equal(executor.devices.get(resetDevice).vertexShader, vsHandle);
    assert.equal(executor.devices.get(resetDevice).pixelShader, psHandle);

    // Binding a handle the host never created is a protocol error, not a
    // silently-skipped draw.
    await executor.submit(batch([
        command(OP_SET_PIXEL_SHADER, u32Payload(resetDevice, 0x40000099)),
    ], 6), {});
    assert.notEqual(executor.failed, null,
        "an unknown pixel shader handle must fail the batch");
}

if (require.main === module) main().catch(error => {
    console.error(error);
    process.exitCode = 1;
});

module.exports = { makeFakeWebGPU, batch, command, u32Payload, createDevicePayload, D3D8WebGPUExecutor };
                                                                                                                                                                                                                                                source/v64/tests/glbridge/d3d8_webgpu_perf_test.js                                                  0000644 0000000 0000000 00000041446 00000000000 017342  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

// Stage 7 performance-hardening regression test.
//
// The doc's stage 7 exit conditions are per-frame budgets (section 12.1), not
// wall-clock numbers, so they can be asserted deterministically against a
// counting fake WebGPU device:
//
//   - steady-state pipeline creation  = 0 / frame
//   - steady-state bind group creation = 0 / frame
//   - steady-state GPU buffer creation = 0 / frame
//   - no GPU readback on a normal frame
//   - one render pass and one queue submit per frame
//   - uniform upload traffic proportional to distinct uniform state, not to
//     draw count or to unrelated render-state churn
//
// These are the properties that regress silently, so they are pinned here
// rather than left to a manual browser session.

const assert = require("node:assert/strict");
const {
    D3D8WebGPUExecutor,
    D8WG_MAGIC,
    D8WG_VERSION_MAJOR,
    D8WG_VERSION_MINOR,
} = require("../../src/browser/glbridge/d3d8-webgpu/d3d8_executor.js");

const OP_HELLO = 1;
const OP_CREATE_DEVICE = 2;
const OP_PRESENT = 4;
const OP_CLEAR = 5;
const OP_BEGIN_SCENE = 6;
const OP_END_SCENE = 7;
const OP_CREATE_BUFFER = 0x100;
const OP_UPDATE_BUFFER = 0x101;
const OP_SET_RENDER_STATE = 0x200;
const OP_SET_STREAM_SOURCE = 0x208;
const OP_SET_VERTEX_FORMAT = 0x20A;
const OP_DRAW_PRIMITIVE = 0x300;

const D3DRS_SRCBLEND = 19;
const D3DRS_DESTBLEND = 20;
const D3DRS_TEXTUREFACTOR = 60;

function countingFake() {
    const n = {
        createBuffer: 0, createBindGroup: 0, createPipeline: 0,
        createTexture: 0, writeBuffer: 0, writeBufferBytes: 0,
        renderPass: 0, submit: 0, mapAsync: 0, copyTextureToBuffer: 0,
        setBindGroup: 0, dynamicOffsets: [],
    };
    const pass = {
        setPipeline() {},
        setBindGroup(index, group, data, start, length) {
            n.setBindGroup++;
            if (data && length) n.dynamicOffsets.push(data[start]);
        },
        setVertexBuffer() {}, setIndexBuffer() {}, setViewport() {},
        setStencilReference() {}, setScissorRect() {},
        draw() {}, drawIndexed() {}, end() {},
    };
    const encoder = {
        beginRenderPass() { n.renderPass++; return pass; },
        copyBufferToBuffer() {},
        copyBufferToTexture() {},
        copyTextureToBuffer() { n.copyTextureToBuffer++; },
        copyTextureToTexture() {},
        finish() { return {}; },
    };
    const device = {
        lost: new Promise(() => {}),
        queue: {
            writeBuffer(buffer, offset, data) {
                n.writeBuffer++;
                n.writeBufferBytes += data.byteLength;
            },
            writeTexture() {},
            submit() { n.submit++; },
            onSubmittedWorkDone() { return Promise.resolve(); },
        },
        createShaderModule(d) { return { ...d, _code: d.code }; },
        createBuffer(d) {
            n.createBuffer++;
            return { descriptor: d, destroy() {},
                mapAsync() { n.mapAsync++; return Promise.resolve(); },
                getMappedRange() { return new ArrayBuffer(d.size); },
                unmap() {} };
        },
        createTexture(d) {
            n.createTexture++;
            return { descriptor: d, createView: () => ({}), destroy() {} };
        },
        createSampler(d) { return { descriptor: d }; },
        createCommandEncoder() { return encoder; },
        createBindGroupLayout(d) {
            return { descriptor: d,
                bindings: new Set(d.entries.map(e => e.binding)) };
        },
        createPipelineLayout(d) {
            return { descriptor: d, bindGroupLayouts: d.bindGroupLayouts };
        },
        createRenderPipeline(d) {
            n.createPipeline++;
            return { descriptor: d, getBindGroupLayout() {
                return d.layout === "auto"
                    ? { bindings: new Set([0, 1, 2, 3, 4]) }
                    : d.layout.bindGroupLayouts[0];
            } };
        },
        createBindGroup(d) { n.createBindGroup++; return d; },
    };
    const context = {
        configure() {},
        getCurrentTexture() { return { createView: () => ({}) }; },
    };
    const gpu = {
        async requestAdapter() {
            return { async requestDevice() { return device; } };
        },
        getPreferredCanvasFormat() { return "bgra8unorm"; },
    };
    return { n, device, context, gpu };
}

function u32Payload(...values) {
    const payload = Buffer.alloc(values.length * 4);
    values.forEach((v, i) => payload.writeUInt32LE(v >>> 0, i * 4));
    return payload;
}

function createDevicePayload(handle, width, height) {
    const p = Buffer.alloc(44);
    p.writeUInt32LE(handle, 0);
    p.writeUInt32LE(0x1234, 4);
    p.writeInt32LE(0, 8);
    p.writeInt32LE(0, 12);
    p.writeUInt32LE(width, 16);
    p.writeUInt32LE(height, 20);
    p.writeUInt32LE(22, 24);
    p.writeUInt32LE(1, 28);
    p.writeUInt32LE(0x20, 32);
    p.writeUInt32LE(1, 36);
    p.writeUInt32LE(75, 40);
    return p;
}

function surfacePayload(handle, width, height) {
    const p = Buffer.alloc(24);
    p.writeUInt32LE(handle, 0);
    p.writeUInt32LE(0x1234, 4);
    p.writeInt32LE(0, 8);
    p.writeInt32LE(0, 12);
    p.writeUInt32LE(width, 16);
    p.writeUInt32LE(height, 20);
    return p;
}

function batch(commands, frameId) {
    let commandBytes = 0;
    for (const c of commands) {
        c.size = (16 + c.payload.length +
            (c.blob ? c.blob.length : 0) + 7) & ~7;
        c.offset = 32 + commandBytes;
        commandBytes += c.size;
    }
    const result = Buffer.alloc(32 + commandBytes);
    result.writeUInt32LE(D8WG_MAGIC, 0);
    result.writeUInt16LE(D8WG_VERSION_MAJOR, 4);
    result.writeUInt16LE(D8WG_VERSION_MINOR, 6);
    result.writeUInt32LE(frameId, 8);
    result.writeUInt32LE(1, 12);
    result.writeUInt32LE(commands.length, 16);
    result.writeUInt32LE(commandBytes, 20);
    result.writeUInt32LE(0xA0010001, 24);
    result.writeUInt32LE(0x20260802, 28);
    let sequence = 1;
    for (const c of commands) {
        result.writeUInt16LE(c.opcode, c.offset);
        result.writeUInt32LE(c.size, c.offset + 4);
        result.writeUInt32LE(sequence++, c.offset + 8);
        c.payload.copy(result, c.offset + 16);
        if (c.blob) {
            const blobOffset = c.offset + 16 + c.payload.length;
            result.writeUInt32LE(blobOffset, c.offset + 16 + 12);
            c.blob.copy(result, blobOffset);
        }
    }
    return result;
}

const command = (opcode, payload, blob) => ({ opcode, payload, blob });

const DEVICE = 0x00100002;
const VERTEX_BUFFER = 0x00100003;

async function makeReadyExecutor() {
    const fake = countingFake();
    const canvas = { width: 1, height: 1, getContext: () => fake.context };
    const executor = new D3D8WebGPUExecutor(canvas, { gpu: fake.gpu });

    const vertices = Buffer.alloc(4 * 20);
    for (let i = 0; i < 4; i++) {
        vertices.writeFloatLE(i * 10, i * 20);
        vertices.writeFloatLE(i * 10, i * 20 + 4);
        vertices.writeFloatLE(0.5, i * 20 + 8);
        vertices.writeFloatLE(1, i * 20 + 12);
        vertices.writeUInt32LE(0xFFFFFFFF, i * 20 + 16);
    }
    const createBuffer = Buffer.alloc(32);
    createBuffer.writeUInt32LE(DEVICE, 0);
    createBuffer.writeUInt32LE(VERTEX_BUFFER, 4);
    createBuffer.writeUInt32LE(1, 8);
    createBuffer.writeUInt32LE(vertices.length, 12);
    createBuffer.writeUInt32LE(0x200, 16);
    createBuffer.writeUInt32LE(0x44, 20);
    const update = Buffer.alloc(24);
    update.writeUInt32LE(VERTEX_BUFFER, 0);
    update.writeUInt32LE(0, 4);
    update.writeUInt32LE(vertices.length, 8);

    await executor.submit(batch([
        command(OP_HELLO, u32Payload(32, 0, 0xA0010001, 0x20260802)),
        command(OP_CREATE_DEVICE, createDevicePayload(DEVICE, 640, 480)),
        command(OP_CREATE_BUFFER, createBuffer),
        command(OP_UPDATE_BUFFER, update, vertices),
        command(OP_SET_STREAM_SOURCE, u32Payload(DEVICE, 0, VERTEX_BUFFER, 20)),
        command(OP_SET_VERTEX_FORMAT, u32Payload(DEVICE, 0x44)),
    ], 1), {});
    assert.equal(executor.failed, null);
    return { fake, executor };
}

// A Maple-shaped frame: many sprite draws, each preceded by pipeline-state
// churn (blend factors) that must NOT invalidate the uniform block.
function spriteFrame(draws) {
    const commands = [
        command(OP_CLEAR,
            u32Payload(DEVICE, 1, 0xFF000000, 0x3F800000, 0, 0)),
        command(OP_BEGIN_SCENE, u32Payload(DEVICE, 0)),
    ];
    for (let i = 0; i < draws; i++) {
        commands.push(command(OP_SET_RENDER_STATE,
            u32Payload(DEVICE, D3DRS_SRCBLEND, (i % 2) ? 2 : 5, 0)));
        commands.push(command(OP_SET_RENDER_STATE,
            u32Payload(DEVICE, D3DRS_DESTBLEND, (i % 2) ? 1 : 6, 0)));
        commands.push(command(OP_DRAW_PRIMITIVE, u32Payload(DEVICE, 4, 0, 1)));
    }
    commands.push(command(OP_END_SCENE, u32Payload(DEVICE, 0)));
    commands.push(command(OP_PRESENT, surfacePayload(DEVICE, 640, 480)));
    return commands;
}

async function main() {
    const { fake, executor } = await makeReadyExecutor();
    const DRAWS = 150;
    const FRAMES = 10;

    // Two warm-up frames populate the pipeline/bind-group/sampler caches.
    await executor.submit(batch(spriteFrame(DRAWS), 2), {});
    await executor.submit(batch(spriteFrame(DRAWS), 3), {});
    assert.equal(executor.failed, null);

    const before = { ...fake.n };
    for (let frame = 0; frame < FRAMES; frame++) {
        await executor.submit(batch(spriteFrame(DRAWS), 4 + frame), {});
        assert.equal(executor.failed, null);
    }
    // Snapshot immediately: later verification frames also move these
    // counters, and a summary computed against live counters would misreport
    // the steady-state numbers this test exists to pin.
    const after = { ...fake.n };
    const delta = key => after[key] - before[key];

    // --- Stage 7 steady-state budgets (doc 12.1) ---
    assert.equal(delta("createPipeline"), 0,
        "steady-state pipeline creation must be 0/frame");
    assert.equal(delta("createBindGroup"), 0,
        "steady-state bind group creation must be 0/frame: the uniform slot " +
        "is addressed by dynamic offset and must not be part of bind group " +
        "identity");
    assert.equal(delta("createBuffer"), 0,
        "steady-state GPU buffer creation must be 0/frame: uniforms come " +
        "from the persistent ring, not a fresh buffer per state change");
    assert.equal(delta("createTexture"), 0,
        "no texture should be created on a steady-state frame");
    assert.equal(delta("renderPass"), FRAMES,
        "a frame of compatible draws must merge into one render pass");
    assert.equal(delta("submit"), FRAMES,
        "a normal frame must cost exactly one queue submit");

    // --- no readback on a normal frame (doc 10.4 / 12.1) ---
    assert.equal(delta("copyTextureToBuffer"), 0,
        "a normal frame must not read back from the GPU");
    assert.equal(delta("mapAsync"), 0,
        "a normal frame must not map a GPU buffer");

    // --- uniform traffic tracks distinct uniform state, not draw count ---
    assert.equal(delta("writeBuffer"), FRAMES,
        "blend-factor churn must not repack the uniform block: only one " +
        "uniform upload per frame is expected");
    assert.ok(delta("writeBufferBytes") <= FRAMES * 2048,
        "uniform upload bytes should stay near one block per frame, saw " +
        delta("writeBufferBytes"));

    // Every draw still binds, and every bind carries a valid dynamic offset.
    assert.equal(delta("setBindGroup"), FRAMES * DRAWS,
        "every draw must still bind its resources");
    for (const offset of fake.n.dynamicOffsets) {
        assert.equal(offset % 256, 0,
            "a dynamic uniform offset must respect the 256-byte alignment " +
            "limit, saw " + offset);
    }

    const stats = executor.getStats();
    assert.equal(stats.uniformRingOverflows, 0,
        "the uniform ring should absorb a normal frame without overflowing");
    assert.ok(stats.bindGroupHits > 0, "bind group cache should be hitting");
    assert.ok(stats.redundantStateWrites >= 0);

    // --- correctness guard: a render state the uniform block DOES contain
    // must still force a repack, or dead-store elimination would render with
    // stale uniforms. This is the failure mode the optimisation could cause.
    const beforeFactor = fake.n.writeBuffer;
    const factorFrame = [
        command(OP_BEGIN_SCENE, u32Payload(DEVICE, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(DEVICE, 4, 0, 1)),
        command(OP_SET_RENDER_STATE,
            u32Payload(DEVICE, D3DRS_TEXTUREFACTOR, 0xFF00FF00, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(DEVICE, 4, 0, 1)),
        command(OP_END_SCENE, u32Payload(DEVICE, 0)),
        command(OP_PRESENT, surfacePayload(DEVICE, 640, 480)),
    ];
    await executor.submit(batch(factorFrame, 100), {});
    assert.equal(executor.failed, null);
    assert.equal(fake.n.writeBuffer - beforeFactor, 2,
        "changing D3DRS_TEXTUREFACTOR must repack the uniform block: it is " +
        "read by the fixed-function shader");

    // --- second scenario: uniform state that genuinely changes every draw.
    // This is what proves the dynamic-offset design: the uniform slot moves
    // per draw, so if the slot offset (or the uniform buffer identity) were
    // part of bind group identity, bind group creation would scale with the
    // draw count instead of staying at zero.
    const varyingFrame = (frameIndex) => {
        const commands = [command(OP_BEGIN_SCENE, u32Payload(DEVICE, 0))];
        for (let i = 0; i < DRAWS; i++) {
            commands.push(command(OP_SET_RENDER_STATE, u32Payload(DEVICE,
                D3DRS_TEXTUREFACTOR, (frameIndex * 977 + i * 131) >>> 0, 0)));
            commands.push(command(OP_DRAW_PRIMITIVE,
                u32Payload(DEVICE, 4, 0, 1)));
        }
        commands.push(command(OP_END_SCENE, u32Payload(DEVICE, 0)));
        commands.push(command(OP_PRESENT, surfacePayload(DEVICE, 640, 480)));
        return commands;
    };
    await executor.submit(batch(varyingFrame(1), 200), {});
    const beforeVarying = { ...fake.n };
    const VARYING_FRAMES = 5;
    for (let f = 0; f < VARYING_FRAMES; f++) {
        await executor.submit(batch(varyingFrame(2 + f), 201 + f), {});
        assert.equal(executor.failed, null);
    }
    const varyingDelta = key => fake.n[key] - beforeVarying[key];
    assert.equal(varyingDelta("createBindGroup"), 0,
        "bind group creation must stay at 0/frame even when the uniform " +
        "block changes on every draw: the slot is reached by dynamic offset " +
        "and must not appear in bind group identity");
    assert.equal(varyingDelta("createBuffer"), 0,
        "per-draw uniform changes must come out of the ring, not new buffers");
    assert.equal(varyingDelta("writeBuffer"), VARYING_FRAMES * DRAWS,
        "each genuinely distinct uniform state needs exactly one upload");
    const distinctOffsets = new Set(
        fake.n.dynamicOffsets.slice(-DRAWS));
    assert.ok(distinctOffsets.size > 1,
        "per-draw uniform changes must land at distinct ring offsets");
    // The strongest form of the invariant: the bind group cache must stay
    // proportional to the number of distinct (texture, sampler) combinations,
    // NOT to the number of distinct uniform states. Per-frame creation counts
    // alone cannot catch a uniform-in-key regression, because the ring cursor
    // restarts each frame and so the same offsets recur and simply refill a
    // large cache once. Cache occupancy does catch it.
    assert.ok(executor.getStats().bindGroupsCached <= 4,
        "bind group cache must not scale with uniform state; " +
        DRAWS + " distinct per-draw uniform states produced " +
        executor.getStats().bindGroupsCached + " cached bind groups");

    // And a genuinely redundant write must be dropped rather than repacked.
    const beforeRedundant = fake.n.writeBuffer;
    await executor.submit(batch([
        command(OP_BEGIN_SCENE, u32Payload(DEVICE, 0)),
        command(OP_SET_RENDER_STATE,
            u32Payload(DEVICE, D3DRS_TEXTUREFACTOR, 0xFF00FF00, 0)),
        command(OP_DRAW_PRIMITIVE, u32Payload(DEVICE, 4, 0, 1)),
        command(OP_END_SCENE, u32Payload(DEVICE, 0)),
        command(OP_PRESENT, surfacePayload(DEVICE, 640, 480)),
    ], 101), {});
    assert.equal(fake.n.writeBuffer - beforeRedundant, 1,
        "re-setting a render state to its current value must not repack");

    console.log("d3d8_webgpu_perf_test: ok");
    console.log("  steady state per frame: " +
        (delta("createBuffer") / FRAMES) + " buffers, " +
        (delta("createBindGroup") / FRAMES) + " bind groups, " +
        (delta("createPipeline") / FRAMES) + " pipelines, " +
        (delta("writeBuffer") / FRAMES) + " uniform uploads (" +
        (delta("writeBufferBytes") / FRAMES) + " bytes), " +
        (delta("renderPass") / FRAMES) + " pass, " +
        (delta("submit") / FRAMES) + " submit, for " + DRAWS + " draws");
}

main().catch(error => {
    console.error(error);
    process.exitCode = 1;
});
                                                                                                                                                                                                                          source/v64/tests/glbridge/d3d9_legacy_format_browser_test.html                                      0000644 0000000 0000000 00000003575 00000000000 021746  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>D3D9 legacy texture WebGPU validation</title>
<pre id="result">RUNNING</pre>
<script>
(async () => {
    "use strict";
    const result = document.getElementById("result");
    try {
        if (!navigator.gpu) throw new Error("WebGPU unavailable");
        const adapter = await navigator.gpu.requestAdapter();
        if (!adapter) throw new Error("No WebGPU adapter");
        const device = await adapter.requestDevice();
        device.pushErrorScope("validation");

        const signed = device.createTexture({
            size: [1, 1, 1],
            format: "rgba8snorm",
            usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC |
                GPUTextureUsage.TEXTURE_BINDING,
        });
        device.queue.writeTexture({ texture: signed },
            new Uint8Array([0x80, 0x7f, 0x7f, 0x7f]),
            { bytesPerRow: 4, rowsPerImage: 1 }, [1, 1, 1]);

        const mixed = device.createTexture({
            size: [1, 1, 1],
            format: "rgba16float",
            usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC |
                GPUTextureUsage.TEXTURE_BINDING |
                GPUTextureUsage.RENDER_ATTACHMENT,
        });
        device.queue.writeTexture({ texture: mixed },
            new Uint8Array([0x00, 0xbc, 0x00, 0x3c,
                0x00, 0x3c, 0x00, 0x3c]),
            { bytesPerRow: 8, rowsPerImage: 1 }, [1, 1, 1]);

        await device.queue.onSubmittedWorkDone();
        const validation = await device.popErrorScope();
        if (validation) throw validation;
        signed.destroy();
        mixed.destroy();
        result.textContent = "PASS rgba8snorm rgba16float";
        result.dataset.status = "pass";
    } catch (error) {
        result.textContent = "FAIL " +
            ((error && error.message) || String(error));
        result.dataset.status = "fail";
    }
})();
</script>
                                                                                                                                   source/v64/tests/glbridge/d3d9_shader_corpus_test.js                                                0000644 0000000 0000000 00000013520 00000000000 017667  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Replays a directory of real-game shader bytecode through the translator.
//
// This is the consumer of D9WG_DUMP_SHADERS=1 (see dump_shader_bytecode in
// glbridge/d3d9proxy/d3d9_proxy.c). The translator in d3d9_shader_pipeline.js
// is hand-written, so unlike a vkd3d-shader/Tint pipeline it has no years of
// real-game coverage behind it -- and this repository's own tests are written
// against bytecode we assembled by hand, which is exactly the wrong sample: it
// contains the encodings we already thought of, not the ones we did not.
//
// Any D3D9 game is a corpus contributor whether or not it is playable here. A
// client that wedges at its main menu has still created its whole shader set
// during startup, so a few minutes in v86 yields a permanent regression corpus
// that replays offline in a second.
//
// Usage:
//     D9_SHADER_CORPUS=path/to/d3d9_dump node d3d9_shader_corpus_test.js
//     D9_NAGA=~/.cargo/bin/naga  (optional, validates the generated WGSL too)
//
// With no corpus directory this exits 0 after saying so: the dump is opt-in, so
// a checkout without one is not a failure. Point it at a directory of .d9sh
// files (raw DWORD token streams, named by content hash) to get a real report.
//
// Failures are grouped by message rather than listed per shader, because one
// unimplemented opcode in a game's shared shader prologue shows up in dozens of
// shaders and a flat list buries the second distinct problem.

"use strict";

const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const pipeline = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js");

const directory = process.env.D9_SHADER_CORPUS;
if (!directory) {
    console.log("SKIP: set D9_SHADER_CORPUS to a directory of .d9sh files " +
        "(produced by running a game with D9WG_DUMP_SHADERS=1) -- no corpus, " +
        "nothing to replay");
    process.exit(0);
}
if (!fs.existsSync(directory)) {
    console.error("D9_SHADER_CORPUS points at " + directory +
        ", which does not exist");
    process.exit(1);
}

function findNaga() {
    if (process.env.D9_NAGA) return process.env.D9_NAGA;
    const probe = spawnSync("naga", ["--version"], { encoding: "utf8" });
    return probe.status === 0 ? "naga" : null;
}
const naga = findNaga();

const files = fs.readdirSync(directory)
    .filter(name => name.endsWith(".d9sh"))
    .sort();
if (!files.length) {
    console.log("SKIP: " + directory + " holds no .d9sh files");
    process.exit(0);
}

const scratch = naga
    ? fs.mkdtempSync(path.join(os.tmpdir(), "d9corpus-")) : null;
// message -> {count, examples}
const translationFailures = new Map();
const validationFailures = new Map();
const notes = new Map();
let translated = 0;
let validated = 0;
const versions = new Map();

function record(map, message, file) {
    let entry = map.get(message);
    if (!entry) map.set(message, entry = { count: 0, examples: [] });
    ++entry.count;
    if (entry.examples.length < 3) entry.examples.push(file);
}

for (const file of files) {
    const bytes = fs.readFileSync(path.join(directory, file));
    if (bytes.length < 8 || bytes.length % 4 !== 0) {
        record(translationFailures, "file is not a whole number of DWORD tokens",
            file);
        continue;
    }
    const tokens = new Uint32Array(bytes.buffer, bytes.byteOffset,
        bytes.length / 4);
    const version = tokens[0];
    const kind = (version >>> 16) === 0xFFFF ? "ps"
        : ((version >>> 16) === 0xFFFE ? "vs" : "??");
    const label = kind + "_" + ((version >>> 8) & 0xFF) + "_" + (version & 0xFF);
    versions.set(label, (versions.get(label) || 0) + 1);

    const result = pipeline.compileShader(tokens);
    if (!result.ok) {
        record(translationFailures, result.error, file);
        continue;
    }
    ++translated;
    for (const note of result.notes || []) record(notes, note, file);
    if (!naga) continue;
    const wgslPath = path.join(scratch, file.replace(/\.d9sh$/, "") + ".wgsl");
    fs.writeFileSync(wgslPath, result.wgsl);
    const run = spawnSync(naga, [wgslPath], { encoding: "utf8" });
    if (run.status !== 0) {
        record(validationFailures,
            (run.stderr || run.stdout || "").trim().split("\n")[0], file);
        continue;
    }
    ++validated;
}

console.log(files.length + " shaders in " + directory);
console.log("  versions: " + [...versions.entries()].sort()
    .map(([label, count]) => label + " x" + count).join(", "));
console.log("  translated: " + translated + "/" + files.length);
if (naga) console.log("  naga-validated: " + validated + "/" + translated);
else console.log("  naga not found; WGSL was generated but not validated");

const report = (title, map) => {
    if (!map.size) return;
    console.log("\n" + title + ":");
    for (const [message, entry] of [...map.entries()]
            .sort((a, b) => b[1].count - a[1].count))
        console.log("  x" + entry.count + "  " + message +
            "\n        e.g. " + entry.examples.join(", "));
};
report("translation failures", translationFailures);
report("WGSL validation failures", validationFailures);
report("notes (translated, but with a documented approximation)", notes);

if (scratch && !validationFailures.size)
    fs.rmSync(scratch, { recursive: true, force: true });
else if (scratch)
    console.log("\ngenerated WGSL kept in " + scratch);

// A corpus is a measurement, not a pass/fail gate: a newly dumped game is
// *expected* to contain instructions we have not implemented, and failing the
// build for that would make people stop dumping. Set D9_CORPUS_STRICT=1 once a
// corpus is checked in as a regression baseline.
if (process.env.D9_CORPUS_STRICT === "1" &&
        (translationFailures.size || validationFailures.size)) {
    console.error("\nD9_CORPUS_STRICT=1 and the corpus has failures");
    process.exit(1);
}
                                                                                                                                                                                source/v64/tests/glbridge/d3d9_shader_pipeline_test.js                                              0000644 0000000 0000000 00000143773 00000000000 020177  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unit tests for glbridge/d3d9-webgpu/d3d9_shader_pipeline.js -- the D3D9
// shader-model 1.x/2.0/3.0 bytecode -> WGSL translator (plan section 9, M2).
//
// Every fixture here is real D3D9 bytecode, assembled token by token by the
// helpers at the top rather than captured from a game, so a failing test
// points at an exact instruction encoding instead of an opaque blob. The
// assembler encodes tokens the same way fxc does (register type split across
// bits 28-30 and 11-12, swizzle in 16-23, source modifier in 24-27), which is
// itself part of what these tests cover: a bug in either the assembler or the
// parser shows up as a decode mismatch.
//
// The WGSL these produce is additionally checked for real by
// d3d9_shader_wgsl_validation_test.js when a `naga` binary is available;
// this file asserts on translation *structure* (which registers, uniforms,
// varyings and reflection a shader yields) and runs everywhere.

"use strict";

const assert = require("assert");
const pipeline = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js");

// ---- bytecode assembler ----

const VS = (major, minor) => (0xfffe0000 | (major << 8) | minor) >>> 0;
const PS = (major, minor) => (0xffff0000 | (major << 8) | minor) >>> 0;
const END = 0x0000ffff;

const REG = pipeline.REGISTER;
const OP = pipeline.OP;

// D3DSP_REGTYPE is stored in two pieces: the low three bits at 28-30 and the
// high two at 11-12.
const regTypeBits = type => (((type & 0x7) << 28) | ((type & 0x18) << 8)) >>> 0;

const NOSWIZZLE = 0xe4; // .xyzw
const swizzle = text => {
    let bits = 0;
    for (let i = 0; i < 4; ++i) {
        const component = "xyzw".indexOf(text[Math.min(i, text.length - 1)]);
        bits |= component << (i * 2);
    }
    return bits;
};

const instruction = (opcode, options = {}) => {
    const length = options.length || 0;
    const control = options.control || 0;
    return ((opcode & 0xffff) | ((control & 0xff) << 16) |
        ((length & 0xf) << 24) | (options.predicated ? 0x10000000 : 0)) >>> 0;
};

const dst = (type, index, options = {}) => {
    const mask = options.mask === undefined ? 0xf : options.mask;
    return (0x80000000 | (index & 0x7ff) | regTypeBits(type) |
        ((mask & 0xf) << 16) | (((options.modifier || 0) & 0xf) << 20) |
        (((options.shift || 0) & 0xf) << 24)) >>> 0;
};

const src = (type, index, options = {}) => {
    const sw = options.swizzle === undefined ? NOSWIZZLE : options.swizzle;
    return (0x80000000 | (index & 0x7ff) | regTypeBits(type) |
        ((sw & 0xff) << 16) | (((options.modifier || 0) & 0xf) << 24) |
        (options.relative ? (1 << 13) : 0)) >>> 0;
};

const dclToken = (usage, usageIndex = 0, textureType = 0) =>
    (0x80000000 | (usage & 0xf) | ((usageIndex & 0xf) << 16) |
        ((textureType & 0xf) << 27)) >>> 0;

const floatBits = value => {
    const buffer = new ArrayBuffer(4);
    new Float32Array(buffer)[0] = value;
    return new Uint32Array(buffer)[0];
};

const tokens = list => new Uint32Array(list);

const USAGE = { POSITION: 0, BLENDWEIGHT: 1, BLENDINDICES: 2, NORMAL: 3,
    PSIZE: 4, TEXCOORD: 5, TANGENT: 6, BINORMAL: 7, TESSFACTOR: 8,
    POSITIONT: 9, COLOR: 10, FOG: 11, DEPTH: 12, SAMPLE: 13 };

// ---- test harness ----

const failures = [];
let passed = 0;

function test(name, body) {
    try {
        body();
        ++passed;
    } catch (error) {
        failures.push({ name, error });
    }
}

function compileOk(list, label) {
    const result = pipeline.compileShader(tokens(list));
    if (!result.ok)
        throw new Error((label || "shader") + " failed to translate: " + result.error);
    return result;
}

// ---- fixtures ----

// vs_1_1
//   dcl_position v0
//   dcl_texcoord0 v1
//   m4x4 oPos, v0, c0
//   mov oT0, v1
const VS_1_1_TRANSFORM = [
    VS(1, 1),
    instruction(OP.DCL), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
    instruction(OP.DCL), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 1),
    instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
    instruction(OP.MOV), dst(REG.OUTPUT, 0), src(REG.INPUT, 1),
    END,
];

// ps_1_1
//   tex t0
//   mul r0, t0, v0
const PS_1_1_MODULATE = [
    PS(1, 1),
    instruction(OP.TEX), dst(REG.TEXTURE, 0),
    instruction(OP.MUL), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), src(REG.INPUT, 0),
    END,
];

// ps_2_0
//   dcl_2d s0
//   dcl t0.xy
//   def c0, 0.5, 0.25, 0, 1
//   texld r0, t0, s0
//   mul r0, r0, c0
//   mov oC0, r0
const PS_2_0_TEXTURED = [
    PS(2, 0),
    instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
    instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0),
        dst(REG.TEXTURE, 0, { mask: 0x3 }),
    instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
        floatBits(0.5), floatBits(0.25), floatBits(0), floatBits(1),
    instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0),
        src(REG.TEXTURE, 0), src(REG.SAMPLER, 0),
    instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0),
        src(REG.TEMP, 0), src(REG.CONST, 0),
    instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
    END,
];

// vs_2_0 with the whole flow-control vocabulary plus relative addressing:
//   dcl_position v0
//   defi i0, 4, 0, 1, 0
//   defb b0, true
//   mov r0, c0
//   mova a0.x, v0.w
//   mov r1, c[a0.x + 2]
//   rep i0
//     add r0, r0, r1
//   endrep
//   if b0
//     mul r0, r0, r0
//   endif
//   m4x4 oPos, r0, c4
const VS_2_0_FLOW = [
    VS(2, 0),
    instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
    instruction(OP.DEFI, { length: 5 }), dst(REG.CONSTINT, 0), 4, 0, 1, 0,
    instruction(OP.DEFB, { length: 2 }), dst(REG.CONSTBOOL, 0), 1,
    instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.CONST, 0),
    instruction(OP.MOVA, { length: 2 }), dst(REG.ADDR, 0, { mask: 0x1 }),
        src(REG.INPUT, 0, { swizzle: swizzle("wwww") }),
    instruction(OP.MOV, { length: 3 }), dst(REG.TEMP, 1),
        src(REG.CONST, 2, { relative: true }), src(REG.ADDR, 0, { swizzle: swizzle("xxxx") }),
    instruction(OP.REP, { length: 1 }), src(REG.CONSTINT, 0),
    instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 1),
    instruction(OP.ENDREP),
    instruction(OP.IF, { length: 1 }), src(REG.CONSTBOOL, 0),
    instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 0),
    instruction(OP.ENDIF),
    instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0), src(REG.CONST, 4),
    END,
];

// vs_2_0 with a subroutine:
//   dcl_position v0
//   mov r0, v0
//   call l0
//   m4x4 oPos, r0, c0
//   ret
//   label l0
//     add r0, r0, r0
//   ret
const VS_2_0_SUBROUTINE = [
    VS(2, 0),
    instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
    instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.INPUT, 0),
    instruction(OP.CALL, { length: 1 }), src(REG.LABEL, 0),
    instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0), src(REG.CONST, 0),
    instruction(OP.RET),
    instruction(OP.LABEL, { length: 1 }), src(REG.LABEL, 0),
    instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 0),
    instruction(OP.RET),
    END,
];

// ---- tests ----

test("vs_1_1 transform: parses, emits a vertex entry point and a WVP uniform", () => {
    const { wgsl, reflection } = compileOk(VS_1_1_TRANSFORM, "vs_1_1");
    assert.strictEqual(reflection.kind, "vertex");
    assert.deepStrictEqual(reflection.version, { major: 1, minor: 1 });
    assert.strictEqual(reflection.entryPoint, "d9_vs_main");
    assert.ok(wgsl.includes("@vertex"), "no @vertex stage");
    assert.ok(wgsl.includes("fn d9_vs_main("), "missing entry point");
    // m4x4 reads c0..c3, so the float constant region must be four vec4s.
    assert.strictEqual(reflection.floatConstCount, 4);
    // Both declared inputs must surface with their semantics and a location
    // equal to their v# register number.
    assert.deepStrictEqual(reflection.inputs, [
        { register: 0, usage: USAGE.POSITION, usageIndex: 0, location: 0 },
        { register: 1, usage: USAGE.TEXCOORD, usageIndex: 0, location: 1 },
    ]);
    assert.ok(wgsl.includes("@location(0) in0: vec4<f32>"), "v0 not bound to location 0");
    assert.ok(wgsl.includes("@location(1) in1: vec4<f32>"), "v1 not bound to location 1");
    // oPos reaches @builtin(position) through the D3D9 half-pixel offset: D3D9
    // samples a pixel at its integer corner, WebGPU at its centre, and a title
    // that pixel-aligns its output has already subtracted that half pixel.
    assert.ok(wgsl.includes("o_position.x + o_position.w / d9c.viewport.x"),
        "oPos not routed to @builtin(position) with the half-pixel offset");
    assert.ok(wgsl.includes("o_position.y - o_position.w / d9c.viewport.y"),
        "the half-pixel offset must negate y: screen y grows downward");
    // oT0 is TEXCOORD0, which the fixed varying table puts at location 2.
    assert.ok(wgsl.includes("o_varying2 = "), "oT0 did not land in the TEXCOORD0 varying");
    assert.strictEqual(reflection.samplers.length, 0);
});

test("an unwritten oFog defaults to an unfogged factor", () => {
    const { wgsl, reflection } = compileOk(VS_1_1_TRANSFORM, "vs_1_1");
    assert.ok(!reflection.writtenVaryings.includes(pipeline.VARYING_FOG),
        "the fixture must leave oFog unwritten");
    assert.ok(wgsl.includes("var<private> o_varying10: vec4<f32> = " +
        "vec4<f32>(1.0, 0.0, 0.0, 0.0);"),
    "an unwritten oFog must default to factor one, not full fog:\n" + wgsl);
});

test("vs_1_1 m4x4 expands to four dot products against consecutive registers", () => {
    const { wgsl } = compileOk(VS_1_1_TRANSFORM, "vs_1_1");
    for (const register of [0, 1, 2, 3])
        assert.ok(wgsl.includes("d9c.f[" + register + "]"),
            "m4x4 did not read c" + register);
});

test("ps_1_1: t# is both coordinate and sample destination, r0 is the output", () => {
    const { wgsl, reflection } = compileOk(PS_1_1_MODULATE, "ps_1_1");
    assert.strictEqual(reflection.kind, "pixel");
    assert.ok(wgsl.includes("@fragment"), "no @fragment stage");
    // `tex t0` implies sampler 0 even without a dcl.
    assert.deepStrictEqual(reflection.samplers, [
        { index: 0, type: "2d", depth: false, textureBinding: 2, samplerBinding: 3 },
    ]);
    assert.ok(wgsl.includes("textureSample(d9_tex0, d9_smp0"), "no sample of texture 0");
    // ps_1_x has no oC0: the result is r0.
    assert.ok(wgsl.includes("result.color0 = r0;"),
        "ps_1_x output should come from r0, got:\n" + wgsl);
    // v0 is COLOR0 (varying 0), t0 is TEXCOORD0 (varying 2).
    assert.ok(wgsl.includes("v0 = stage_in.varying0;"), "v0 not wired to COLOR0");
    assert.ok(wgsl.includes("t0 = stage_in.varying2;"), "t0 not wired to TEXCOORD0");
});

test("ps_1_x tex/texld take sampler dimensions from the bound texture", () => {
    for (const minor of [1, 4]) {
        const code = minor === 1 ? [
            PS(1, 1), instruction(OP.TEX), dst(REG.TEXTURE, 0),
            instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), END,
        ] : [
            PS(1, 4), instruction(OP.TEX), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), END,
        ];
        for (const type of ["2d", "cube", "3d"]) {
            const result = pipeline.compileShader(tokens(code), {
                legacySamplerTypes: { 0: type, 7: "cube" },
            });
            assert.ok(result.ok, result.error);
            assert.equal(result.reflection.samplers.length, 1,
                "an unused bound texture must not add a sampler");
            assert.equal(result.reflection.samplers[0].type, type);
            assert.ok(result.wgsl.includes("var d9_tex0: texture_" + type + "<f32>"));
            if (type !== "2d") assert.match(result.wgsl, /textureSample\(d9_tex0, d9_smp0, [^\n]*\.xyz\)/);
        }
    }
    const sm2 = pipeline.compileShader(tokens(PS_2_0_TEXTURED), {
        legacySamplerTypes: { 0: "cube" },
    });
    assert.ok(sm2.ok, sm2.error);
    assert.equal(sm2.reflection.samplers[0].type, "2d",
        "SM2 explicit declarations must not be overridden by bindings");
});

test("a vs_1_1 with no dcl gets the API's fixed v# semantics", () => {
    // Real vs_1_x bytecode contains no dcl_ at all -- the instruction did not
    // exist before vs_2_0 -- so what v0/v5/v7 mean comes from D3D's fixed
    // register table, not from the shader. (The VS_1_1_* fixtures above spell
    // their inputs with dcl, which is convenient but not a shape any
    // assembler produces for this model.)
    //
    // Reflecting nothing here is not a cosmetic gap: the executor pairs a
    // vertex declaration element to a shader input by (usage, usageIndex), so
    // an input-less reflection means no attribute is bound, every v# reads
    // zero, and d3d9_executor drops the draw entirely -- which is what
    // happened to every vertex-shader draw 3DMark 2001 issued.
    const shader = [
        VS(1, 1),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV), dst(REG.ATTROUT, 0), src(REG.INPUT, 5),
        instruction(OP.MOV), dst(REG.TEXCRDOUT, 0), src(REG.INPUT, 7),
        END,
    ];
    const { wgsl, reflection } = compileOk(shader, "vs_1_1 without dcl");
    assert.deepStrictEqual(reflection.inputs, [
        { register: 0, usage: 0, usageIndex: 0, location: 0 },   // POSITION0
        { register: 5, usage: 10, usageIndex: 0, location: 5 },  // COLOR0
        { register: 7, usage: 5, usageIndex: 0, location: 7 },   // TEXCOORD0
    ], "v0/v5/v7 must reflect as position, diffuse and texcoord0");
    // And they have to reach the shader as real attributes: the register
    // variable is still private storage, but the entry point now takes an
    // attribute per input and copies it in, instead of leaving vin0 at the
    // zero it is initialised to.
    assert.match(wgsl, /fn d9_vs_main\(@location\(0\) \w+: vec4<f32>/);
    assert.match(wgsl, /\n\s+vin0 = \w+;/,
        "a used v# must be loaded from its vertex attribute");
});

test("vs_1_1 MOV a0.x selects a matrix-palette constant", () => {
    // SM1.1 has no MOVA instruction. Matrix-palette skinning loads each
    // vertex's packed bone index with MOV and then addresses c[a0.x + n]. If
    // the integer a0 mirror is not updated, every vertex reads the same root
    // matrix and an animated character remains in its bind/T pose.
    const shader = [
        VS(1, 1),
        instruction(OP.MOV), dst(REG.ADDR, 0, { mask: 0x1 }),
            src(REG.INPUT, 2, { swizzle: swizzle("xxxx") }),
        instruction(OP.M4x3), dst(REG.TEMP, 0, { mask: 0x7 }),
            src(REG.INPUT, 0), src(REG.CONST, 4, { relative: true }),
        instruction(OP.MOV), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ];
    const { wgsl, reflection } = compileOk(shader,
        "vs_1_1 matrix-palette address");
    assert.match(wgsl, /let _v\d+ = round\(/,
        "MOV a0.x must apply SM1.1 round-to-nearest conversion");
    assert.ok(wgsl.includes("a0 = vec4<i32>(a0f);"),
        "MOV a0.x did not update the integer address register:\n" + wgsl);
    assert.ok(wgsl.includes("clamp(a0.x + 4, 0, 255)"),
        "the bone matrix read did not use the updated address register:\n" + wgsl);
    assert.strictEqual(reflection.usesRelativeConstants, true);
    assert.strictEqual(reflection.floatConstCount, 256);
});

test("vs_1_0/ps_1_0 translate exactly like their 1.1 counterparts", () => {
    // The 1.0 models are strict subsets: vs_1_1 only adds the address
    // register, ps_1_1 only adds instructions a 1.0 shader cannot contain.
    // A device advertising vs_1_1/ps_1_4 therefore has to run them, and the
    // same bytecode with the minor version dropped must translate the same
    // way. 3DMark 2001 assembles most of its shaders as `vs.1.0`.
    const withVersion = (list, version) =>
        list.map((token, index) => (index === 0 ? version : token));
    // Everything but the header comment, which names the model it came from.
    const body = wgsl => wgsl.slice(wgsl.indexOf("\n") + 1);

    const vs10 = compileOk(withVersion(VS_1_1_TRANSFORM, VS(1, 0)), "vs_1_0");
    assert.deepStrictEqual(vs10.reflection.version, { major: 1, minor: 0 });
    assert.strictEqual(body(vs10.wgsl),
        body(compileOk(VS_1_1_TRANSFORM, "vs_1_1").wgsl));

    const ps10 = compileOk(withVersion(PS_1_1_MODULATE, PS(1, 0)), "ps_1_0");
    assert.deepStrictEqual(ps10.reflection.version, { major: 1, minor: 0 });
    assert.strictEqual(body(ps10.wgsl),
        body(compileOk(PS_1_1_MODULATE, "ps_1_1").wgsl));
});

test("ps_2_0: dcl_2d, def and texld produce a sampler pair and a constant default", () => {
    const { wgsl, reflection } = compileOk(PS_2_0_TEXTURED, "ps_2_0");
    assert.deepStrictEqual(reflection.samplers, [
        { index: 0, type: "2d", depth: false, textureBinding: 2, samplerBinding: 3 },
    ]);
    assert.ok(wgsl.includes("@group(0) @binding(2) var d9_tex0: texture_2d<f32>;"));
    assert.ok(wgsl.includes("@group(0) @binding(3) var d9_smp0: sampler;"));
    // The pixel-stage constant buffer is binding 1 (vertex takes binding 0).
    assert.ok(wgsl.includes("@group(0) @binding(1) var<uniform> d9c: D9Constants;"));
    assert.strictEqual(reflection.floatDefaults.length, 1);
    assert.strictEqual(reflection.floatDefaults[0].register, 0);
    assert.deepStrictEqual(reflection.floatDefaults[0].values.map(v => Math.round(v * 100) / 100),
        [0.5, 0.25, 0, 1]);
    assert.ok(wgsl.includes("result.color0 = oC0;"), "ps_2_0 output should come from oC0");
    // The coordinate is a 2D sampler's, so only .xy is taken.
    assert.ok(/textureSample\(d9_tex0, d9_smp0, _uv\d+\.xy\)/.test(wgsl),
        "2D sample did not use a two-component coordinate:\n" + wgsl);
});

test("ps_2_0 def registers count towards the float constant region", () => {
    const { reflection } = compileOk(PS_2_0_TEXTURED, "ps_2_0");
    assert.strictEqual(reflection.floatConstCount, 1);
    assert.strictEqual(reflection.floatRegionBytes, 16);
});

test("vs_2_0 flow control: rep/if/mova/relative addressing all translate", () => {
    const { wgsl, reflection } = compileOk(VS_2_0_FLOW, "vs_2_0 flow");
    assert.ok(/for \(var _rep\d+ = 0; _rep\d+ < d9c\.i\[0\]\.x;/.test(wgsl),
        "rep i0 did not become a bounded loop:\n" + wgsl);
    assert.ok(wgsl.includes("if ((d9c.b[0][0] != 0u))"), "if b0 did not read the bool register");
    assert.ok(wgsl.includes("a0 = vec4<i32>(a0f);"), "mova did not update a0");
    assert.ok(wgsl.includes("clamp(a0.x + 2, 0, 255)"),
        "relative addressing was not clamped into the constant file:\n" + wgsl);
    // Relative addressing forces the full 256-register file to be uploaded.
    assert.strictEqual(reflection.usesRelativeConstants, true);
    assert.strictEqual(reflection.floatConstCount, 256);
    assert.strictEqual(reflection.intConstCount, 1);
    assert.strictEqual(reflection.boolVectorCount, 1);
    assert.deepStrictEqual(reflection.intDefaults, [{ register: 0, values: [4, 0, 1, 0] }]);
    assert.deepStrictEqual(reflection.boolDefaults, [{ register: 0, value: true }]);
});

test("vs_2_0 subroutine: label bodies become functions defined before the caller", () => {
    const { wgsl } = compileOk(VS_2_0_SUBROUTINE, "vs_2_0 subroutine");
    const subroutineAt = wgsl.indexOf("fn d9_sub0()");
    const bodyAt = wgsl.indexOf("fn d9_body()");
    assert.ok(subroutineAt >= 0, "subroutine was not emitted");
    assert.ok(bodyAt > subroutineAt, "subroutine must precede its caller in WGSL");
    assert.ok(wgsl.includes("d9_sub0();"), "the call site was not emitted");
    // The trailing top-level `ret` ends main; it must not leave a stray
    // `return;` that would skip the output assembly.
    const body = wgsl.slice(bodyAt, wgsl.indexOf("}", bodyAt));
    assert.ok(!body.includes("return;"), "top-level ret leaked into the body:\n" + body);
});

test("write masks become per-component assignments (WGSL has no swizzle lvalue)", () => {
    const { wgsl } = compileOk([
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0, { mask: 0x5 }), src(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ], "write mask");
    assert.ok(/r0\.x = _v\d+\.x;/.test(wgsl), "missing .x component store:\n" + wgsl);
    assert.ok(/r0\.z = _v\d+\.z;/.test(wgsl), "missing .z component store:\n" + wgsl);
    assert.ok(!/r0\.y = /.test(wgsl), "masked-out .y was written anyway");
    assert.ok(!/\.xz = /.test(wgsl), "emitted an illegal multi-component swizzle assignment");
});

test("_sat destination modifier clamps, source modifiers apply after swizzle", () => {
    const { wgsl } = compileOk([
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        // mov_sat r0, -v0.yxwz
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0, { modifier: 1 }),
            src(REG.INPUT, 0, { swizzle: swizzle("yxwz"), modifier: 1 }),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ], "modifiers");
    assert.ok(wgsl.includes("clamp("), "_sat did not clamp");
    assert.ok(wgsl.includes("-((vin0).yxwz)"),
        "negate should wrap the swizzled read, got:\n" + wgsl);
});

test("texkill emits a discard over the ps_1_x three-component rule", () => {
    const { wgsl } = compileOk([
        PS(1, 1),
        instruction(OP.TEXKILL), dst(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 0),
        END,
    ], "texkill");
    assert.ok(wgsl.includes("discard;"), "texkill did not discard");
    assert.ok(wgsl.includes("(t0).xyz < vec3<f32>(0.0)"),
        "ps_1_x texkill must test three components:\n" + wgsl);
});

test("ps_2_0 texkill tests four components", () => {
    const { wgsl } = compileOk([
        PS(2, 0),
        instruction(OP.TEXKILL, { length: 1 }), dst(REG.TEMP, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ], "texkill 2.0");
    assert.ok(wgsl.includes("(r0).xyzw < vec4<f32>(0.0)"),
        "ps_2_0 texkill must test four components:\n" + wgsl);
});

test("ps_3_0 vPos/vFace map onto WGSL builtins", () => {
    const { wgsl, reflection } = compileOk([
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.COLOR, 0), dst(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.MISCTYPE, 0),
        instruction(OP.MAD, { length: 4 }), dst(REG.TEMP, 0), src(REG.TEMP, 0),
            src(REG.MISCTYPE, 1), src(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ], "ps_3_0 misc");
    assert.strictEqual(reflection.readsFragmentPosition, true);
    assert.strictEqual(reflection.readsFrontFacing, true);
    assert.ok(wgsl.includes("@builtin(front_facing) d9_front: bool"));
    assert.ok(wgsl.includes("d9_frag_position = stage_in.position;"));
    assert.ok(wgsl.includes("floor(d9_frag_position.xy)"),
        "vPos should report integer pixel coordinates");
});

test("vs_3_0 output semantics come from dcl, not from the register number", () => {
    // dcl_position o3 / dcl_texcoord0 o0 -- deliberately swapped versus the
    // vs_1_1 fixed mapping, which is exactly what vs_3_0 allows.
    const { wgsl } = compileOk([
        VS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.OUTPUT, 3),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.OUTPUT, 0),
        instruction(OP.M4x4, { length: 3 }), dst(REG.OUTPUT, 3), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.OUTPUT, 0), src(REG.INPUT, 0),
        END,
    ], "vs_3_0 outputs");
    assert.ok(wgsl.includes("o_position = "), "o3 (dcl_position) did not become the position");
    assert.ok(wgsl.includes("o_varying2 = "), "o0 (dcl_texcoord0) did not become TEXCOORD0");
});

test("every vertex shader emits the full varying set so VS/PS always link", () => {
    const { wgsl } = compileOk(VS_1_1_TRANSFORM, "vs_1_1");
    for (let slot = 0; slot < pipeline.VARYING_COUNT; ++slot)
        assert.ok(wgsl.includes("@location(" + slot + ") varying" + slot + ": vec4<f32>,"),
            "varying slot " + slot + " missing from the vertex output struct");
});

test("ps_1_x texbem displaces the coordinate by the stage's bump matrix", () => {
    const result = compileOk([
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXBEM), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        END,
    ]);
    // The displacement must be the D3D formula -- u by (m00, m10) and v by
    // (m01, m11) -- against the bump register, not an axis-swapped variant.
    // Getting the transpose wrong still renders a plausible bumpy surface, so
    // the shape of the expression is the only thing that catches it.
    assert.match(result.wgsl, /bump\[1\]\.x \* \([^)]*\)\.x \+ d9c\.bump\[1\]\.z \* \([^)]*\)\.y/,
        "u displacement should be m00*du + m10*dv: " + result.wgsl);
    assert.match(result.wgsl, /bump\[1\]\.y \* \([^)]*\)\.x \+ d9c\.bump\[1\]\.w \* \([^)]*\)\.y/,
        "v displacement should be m01*du + m11*dv");
    assert.strictEqual(result.reflection.bumpStageCount, 2,
        "the bump matrix array must cover sampler 1");
    assert.ok(result.reflection.bumpOffset >= 0,
        "the reflection must tell the host where to write the bump matrices");
});

test("ps_1_x texbeml scales by luminance from the bump map's blue channel", () => {
    const result = compileOk([
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXBEML), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        END,
    ]);
    assert.match(result.wgsl, /clamp\(d9c\.bump_lum\[1\]\.x \* \([^)]*\)\.z \+ d9c\.bump_lum\[1\]\.y, 0\.0, 1\.0\)/,
        "luminance should be scale*b + offset, clamped: " + result.wgsl);
});

test("ps_1_4 bem displaces a coordinate by the stage's bump matrix", () => {
    // The ps_1_4 spelling of the same transform, as an arithmetic instruction
    // with no sample: texcrd brings the coordinate into r1, texld the (du, dv)
    // pair into r0, and bem writes the displaced coordinate back for the
    // second phase to sample with.
    const result = compileOk([
        PS(1, 4),
        instruction(OP.TEXCOORD), dst(REG.TEMP, 1), src(REG.TEXTURE, 1),
        instruction(OP.TEX), dst(REG.TEMP, 0), src(REG.TEXTURE, 0),
        instruction(OP.BEM), dst(REG.TEMP, 1, { mask: 0x3 }),
            src(REG.TEMP, 1), src(REG.TEMP, 0),
        END,
    ]);
    // Same matrix convention as texbem, and the stage is the *destination*
    // register's index -- getting that from a source instead reads an
    // unwritten matrix and displaces by zero.
    assert.match(result.wgsl,
        /\w+\.x \+ d9c\.bump\[1\]\.x \* \w+\.x \+ d9c\.bump\[1\]\.z \* \w+\.y/,
        "r should be src0.r + m00*du + m10*dv: " + result.wgsl);
    assert.match(result.wgsl,
        /\w+\.y \+ d9c\.bump\[1\]\.y \* \w+\.x \+ d9c\.bump\[1\]\.w \* \w+\.y/,
        "g should be src0.g + m01*du + m11*dv");
    // bem writes .rg only. b and a of the destination must survive it.
    assert.match(result.wgsl, /r1\.x = /, "bem must write r");
    assert.match(result.wgsl, /r1\.y = /, "bem must write g");
    assert.ok(!/r1\.z = |r1\.w = /.test(result.wgsl),
        "bem must not touch b or a: " + result.wgsl);
    assert.strictEqual(result.reflection.bumpStageCount, 2,
        "the bump matrix array must cover stage 1");
});

test("ps_1_x texm3x3 forms build their coordinate from the preceding pads", () => {
    const result = compileOk([
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 2), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3TEX), dst(REG.TEXTURE, 3), src(REG.TEXTURE, 0),
        END,
    ]);
    // Three dot products, assembled into one vec3 that samples a cube map --
    // the shape tangent-space environment mapping needs.
    assert.strictEqual((result.wgsl.match(/let _m3row\d+ = dot\(/g) || []).length, 3,
        "each pad plus the tex should contribute one row: " + result.wgsl);
    assert.match(result.wgsl, /let _m3x3\d+ = vec3<f32>\(_m3row\d+, _m3row\d+, _m3row\d+\)/,
        "the three rows should assemble into a vec3 coordinate");
    assert.strictEqual(result.reflection.samplers.find(s => s.index === 3).type,
        "cube", "a texm3x3tex addresses a cube map");
});

test("ps_1_x instructions with no honest translation are still refused", () => {
    // TEXDEPTH replaces the fragment's depth from a texture-addressing result,
    // which this pipeline has no frag_depth path for. Refusing keeps it out of
    // the "renders something plausible but wrong" category.
    const result = pipeline.compileShader(tokens([
        PS(1, 4),
        instruction(OP.TEXDEPTH), dst(REG.TEMP, 0),
        END,
    ]));
    assert.strictEqual(result.ok, false);
    assert.ok(/texdepth/.test(result.error),
        "error should name the instruction: " + result.error);
});

test("vs_3_0 vertex texture fetch uses an explicit LOD and isolated bindings", () => {
    const result = compileOk([
        VS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.INPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.OUTPUT, 0),
        instruction(OP.TEXLDL, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.OUTPUT, 0),
            src(REG.TEMP, 0),
        END,
    ], "vs_3_0 vertex texture fetch");
    assert.match(result.wgsl, /textureSampleLevel\(d9_tex0, d9_smp0/);
    assert.match(result.wgsl, /@binding\(34\) var d9_tex0/);
    assert.deepStrictEqual(result.reflection.samplers, [{ index: 0, type: "2d",
        depth: false, textureBinding: 34, samplerBinding: 35 }]);
});

test("a truncated token stream is reported, never silently half-translated", () => {
    const result = pipeline.compileShader(tokens([
        VS(2, 0), instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0),
    ]));
    assert.strictEqual(result.ok, false);
});

test("a non-shader blob is rejected by the version token", () => {
    const result = pipeline.compileShader(tokens([0x12345678, 0, END]));
    assert.strictEqual(result.ok, false);
    assert.ok(/not a D3D9 shader/.test(result.error), result.error);
});

test("comment tokens (the D3DX/fxc signature blocks) are skipped", () => {
    const withComment = [
        VS(1, 1),
        // D3DSIO_COMMENT with three payload DWORDs.
        (0xfffe | (3 << 16)) >>> 0, 0xdeadbeef, 0xcafebabe, 0x00c0ffee,
        instruction(OP.DCL), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        END,
    ];
    const { reflection } = compileOk(withComment, "comment");
    assert.strictEqual(reflection.floatConstCount, 4);
    assert.strictEqual(reflection.inputs.length, 1);
});

test("predicated instructions become guarded blocks", () => {
    const { wgsl, reflection } = compileOk([
        VS(2, 1),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.SETP, { length: 3, control: 1 /* gt */ }),
            dst(REG.PREDICATE, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        // dst + predicate token + one source == three tokens after the
        // instruction token, which is what the SM2.0 length field must say.
        instruction(OP.MOV, { length: 3, predicated: true }), dst(REG.TEMP, 0),
            src(REG.PREDICATE, 0, { swizzle: swizzle("xxxx") }), src(REG.CONST, 1),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ], "predicate");
    assert.ok(wgsl.includes("var<private> p0: vec4<bool>"), "p0 was not declared");
    assert.ok(wgsl.includes("if (p0.x) {"), "predicate did not guard the instruction:\n" + wgsl);
    assert.strictEqual(reflection.floatConstCount, 2);
});

test("hashTokens is stable and distinguishes single-bit differences", () => {
    const a = pipeline.hashTokens(tokens(VS_1_1_TRANSFORM));
    const b = pipeline.hashTokens(tokens(VS_1_1_TRANSFORM));
    const c = pipeline.hashTokens(tokens(PS_1_1_MODULATE));
    assert.deepStrictEqual(a, b);
    assert.notDeepStrictEqual(a, c);
    const mutated = VS_1_1_TRANSFORM.slice();
    mutated[mutated.length - 2] ^= 1;
    assert.notDeepStrictEqual(a, pipeline.hashTokens(tokens(mutated)));
});

test("the shader cache translates identical bytecode exactly once", () => {
    const cache = new pipeline.D3D9ShaderCache();
    const stream = tokens(VS_1_1_TRANSFORM);
    const hash = pipeline.hashTokens(stream);
    const first = cache.compile(stream, hash.low, hash.high);
    const second = cache.compile(stream, hash.low, hash.high);
    assert.strictEqual(first, second, "cache returned a different object");
    assert.strictEqual(cache.stats.compiles, 1);
    assert.strictEqual(cache.stats.hits, 1);
});

test("the shader cache remembers failures instead of retrying them every frame", () => {
    const cache = new pipeline.D3D9ShaderCache();
    const stream = tokens([PS(1, 4), instruction(OP.TEXDEPTH),
        dst(REG.TEMP, 0), END]);
    const hash = pipeline.hashTokens(stream);
    assert.strictEqual(cache.compile(stream, hash.low, hash.high).ok, false);
    assert.strictEqual(cache.compile(stream, hash.low, hash.high).ok, false);
    assert.strictEqual(cache.stats.compiles, 1);
    assert.strictEqual(cache.stats.failures, 1);
});

test("the shader cache evicts least-recently-used entries at its limit", () => {
    const cache = new pipeline.D3D9ShaderCache({ limit: 2 });
    const make = seed => {
        const list = VS_1_1_TRANSFORM.slice();
        list[list.length - 2] = src(REG.INPUT, seed);
        return tokens(list);
    };
    for (const seed of [1, 2, 3]) {
        const stream = make(seed);
        const hash = pipeline.hashTokens(stream);
        cache.compile(stream, hash.low, hash.high);
    }
    assert.strictEqual(cache.entries.size, 2);
    assert.strictEqual(cache.stats.evictions, 1);
});

test("shader cache reports compile latency/size and survives persistence", () => {
    const times = [10, 12.5];
    const cache = new pipeline.D3D9ShaderCache({ clock: () => times.shift() });
    const stream = tokens(VS_1_1_TRANSFORM);
    const hash = pipeline.hashTokens(stream);
    const translated = cache.compile(stream, hash.low, hash.high);
    const stats = cache.snapshot();
    assert.equal(stats.misses, 1);
    assert.equal(stats.compileLatencyMs.p50, 2.5);
    assert.equal(stats.compileLatencyMs.p95, 2.5);
    assert.equal(stats.cached, 1);
    assert.equal(stats.totalWGSLBytes, translated.wgsl.length * 2);

    const restored = new pipeline.D3D9ShaderCache();
    assert.equal(restored.importEntries(cache.exportEntries()), 1);
    const before = restored.stats.compiles;
    assert.equal(restored.compile(stream, hash.low, hash.high).ok, true);
    assert.equal(restored.stats.compiles, before,
        "a restored shader should be a cache hit, not a retranslation");
    assert.equal(restored.snapshot().restored, 1);

    // A payload carrying another build's translations must be refused rather
    // than restored. Accepting it means this session runs WGSL and reflection
    // this file no longer produces -- which is invisible, survives a reload,
    // and makes a translator fix appear to do nothing for exactly the shaders
    // that have been seen before. The storage `version` cannot catch it: that
    // describes the envelope, and the envelope did not change.
    const stale = cache.exportEntries();
    assert.equal(stale.revision, pipeline.TRANSLATOR_REVISION,
        "an exported payload has to record which translator wrote it");
    stale.revision = stale.revision + "-other-build";
    assert.equal(new pipeline.D3D9ShaderCache().importEntries(stale), 0,
        "entries from a different translator build must not be restored");
    const missing = cache.exportEntries();
    delete missing.revision;
    assert.equal(new pipeline.D3D9ShaderCache().importEntries(missing), 0,
        "a payload predating the revision field is from an older build too");
});

test("arithmetic opcodes translate to their WGSL equivalents", () => {
    const cases = [
        [OP.ADD, 2, "(vin0) + (vin0)"],
        [OP.MUL, 2, "(vin0) * (vin0)"],
        [OP.MIN, 2, "min(vin0, vin0)"],
        [OP.MAX, 2, "max(vin0, vin0)"],
        [OP.DP3, 2, "dot((vin0).xyz, (vin0).xyz)"],
        [OP.DP4, 2, "dot(vin0, vin0)"],
        [OP.MAD, 3, "(vin0) * (vin0) + (vin0)"],
        [OP.LRP, 3, "mix(vin0, vin0, vin0)"],
        [OP.FRC, 1, "fract(vin0)"],
        [OP.ABS, 1, "abs(vin0)"],
        [OP.RCP, 1, "d9_rcp((vin0).x)"],
        [OP.RSQ, 1, "d9_rsq((vin0).x)"],
        [OP.LIT, 1, "d9_lit(vin0)"],
        [OP.NRM, 1, "d9_normalize((vin0).xyz)"],
        [OP.CRS, 2, "cross((vin0).xyz, (vin0).xyz)"],
        [OP.POW, 2, "pow(abs((vin0).x), (vin0).x)"],
    ];
    for (const [opcode, sourceCount, expected] of cases) {
        const list = [
            VS(2, 0),
            instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
            instruction(opcode, { length: 1 + sourceCount }), dst(REG.TEMP, 0),
        ];
        for (let i = 0; i < sourceCount; ++i) list.push(src(REG.INPUT, 0));
        list.push(instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0));
        list.push(END);
        const { wgsl } = compileOk(list, "opcode " + opcode);
        assert.ok(wgsl.includes(expected),
            "opcode " + opcode + " did not emit `" + expected + "`");
    }
});

test("cmp/slt/sge use select() with the right operand order", () => {
    const build = opcode => {
        const list = [
            VS(2, 0),
            instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
            instruction(opcode, { length: 4 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0), src(REG.CONST, 0),
        ];
        if (opcode === OP.CMP) list.push(src(REG.CONST, 1));
        list.push(instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0));
        list.push(END);
        return compileOk(list, "opcode " + opcode).wgsl;
    };
    // cmp dst, a, b, c  ->  dst = a >= 0 ? b : c, i.e. select(c, b, a >= 0).
    assert.ok(build(OP.CMP).includes(
        "select(d9c.f[1], d9c.f[0], (vin0) >= vec4<f32>(0.0))"), "cmp operand order");
    assert.ok(build(OP.SLT).includes(
        "select(vec4<f32>(0.0), vec4<f32>(1.0), (vin0) < (d9c.f[0]))"), "slt");
    assert.ok(build(OP.SGE).includes(
        "select(vec4<f32>(0.0), vec4<f32>(1.0), (vin0) >= (d9c.f[0]))"), "sge");
});

test("loop/endloop drives aL from the integer register's y/z fields", () => {
    const { wgsl } = compileOk([
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DEFI, { length: 5 }), dst(REG.CONSTINT, 0), 4, 2, 1, 0,
        instruction(OP.LOOP, { length: 2 }), src(REG.LOOP, 0), src(REG.CONSTINT, 0),
        // The relative-addressing token counts towards the instruction
        // length: dst + r0 + c[..] + the aL index token == four.
        instruction(OP.ADD, { length: 4 }), dst(REG.TEMP, 0), src(REG.TEMP, 0),
            src(REG.CONST, 0, { relative: true }), src(REG.LOOP, 0),
        instruction(OP.ENDLOOP),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ], "loop");
    assert.ok(wgsl.includes("aL = d9c.i[0].y;"), "aL was not initialised from i0.y");
    assert.ok(wgsl.includes("aL = aL + d9c.i[0].z;"), "aL was not stepped by i0.z");
    assert.ok(wgsl.includes("clamp(aL + 0, 0, 255)"),
        "c[aL] relative addressing did not use the loop counter:\n" + wgsl);
});

test("uniform sizing: the reflection describes the exact packed layout", () => {
    const { reflection } = compileOk(VS_2_0_FLOW, "vs_2_0 flow");
    assert.strictEqual(reflection.floatRegionBytes, 256 * 16);
    assert.strictEqual(reflection.intRegionBytes, 16);
    assert.strictEqual(reflection.boolRegionBytes, 16);
    const registerBytes = reflection.floatRegionBytes +
        reflection.intRegionBytes + reflection.boolRegionBytes;
    // A vertex shader carries one extra vec4 past the register file: the
    // viewport the half-pixel offset is measured against.
    assert.strictEqual(reflection.viewportOffset, registerBytes);
    assert.strictEqual(reflection.uniformBytes, registerBytes + 16);
});

test("a pixel shader carries no viewport uniform", () => {
    const { reflection } = compileOk(PS_2_0_TEXTURED, "ps_2_0 textured");
    assert.strictEqual(reflection.viewportOffset, -1,
        "the half-pixel offset is a vertex-stage concern only");
    assert.strictEqual(reflection.uniformBytes,
        reflection.floatRegionBytes + reflection.intRegionBytes +
        reflection.boolRegionBytes);
});

// Point-sprite expansion appends its own fields, which have to start after the
// viewport rather than on top of it.
test("point-sprite uniforms sit past the viewport, not on it", () => {
    const result = pipeline.compileShader(tokens(VS_1_1_TRANSFORM),
        { pointExpansion: true });
    assert.ok(result.ok, result.error);
    const reflection = result.reflection;
    const registerBytes = reflection.floatRegionBytes +
        reflection.intRegionBytes + reflection.boolRegionBytes;
    assert.strictEqual(reflection.viewportOffset, registerBytes);
    assert.strictEqual(reflection.pointViewportOffset, registerBytes + 16);
    assert.strictEqual(reflection.pointParamsOffset, registerBytes + 32);
    assert.strictEqual(reflection.uniformBytes, registerBytes + 48);
});

test("M5 compact skinning inputs are converted to D3D9 float4 registers", () => {
    const result = pipeline.compileShader(tokens(VS_1_1_TRANSFORM), {
        inputConversions: { 0: "dec3n", 1: "ubyte4" },
    });
    assert.ok(result.ok, result.error);
    assert.ok(result.wgsl.includes("@location(0) in0: u32"),
        "DEC3N must arrive as its packed uint32 storage");
    assert.ok(result.wgsl.includes("d9_unpack_dec3n(in0)"),
        "DEC3N was not sign-extended and normalised");
    assert.ok(result.wgsl.includes("@location(1) in1: vec4<u32>"),
        "UBYTE4 must use an integer vertex input");
    assert.ok(result.wgsl.includes("vin1 = vec4<f32>(in1)"),
        "UBYTE4 was not converted to the float4 D3D9 exposes");
});

test("projection source modifiers preserve a negative divisor", () => {
    const result = compileOk([
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0, { modifier: 9 /* _dz */ }),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ], "signed projective divide");
    assert.ok(result.wgsl.includes("select(-max(abs("),
        "negative q must not be clamped to a positive epsilon");
});

test("point-sprite vertex variants expand oPts into a six-vertex quad", () => {
    const bytecode = [
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 0),
            src(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.RASTOUT, 2),
            src(REG.CONST, 0),
        END,
    ];
    const result = pipeline.compileShader(tokens(bytecode),
        { pointExpansion: true, pointSprite: true });
    assert.equal(result.ok, true, result.error);
    assert.equal(result.reflection.writesPointSize, true);
    assert.equal(result.reflection.pointExpansion, true);
    assert.equal(result.reflection.pointParamsOffset + 16,
        result.reflection.uniformBytes);
    assert.ok(result.wgsl.includes("@builtin(vertex_index) d9_vertex_index"));
    assert.ok(result.wgsl.includes("var d9_point_size = o_pointsize.x"));
    assert.ok(result.wgsl.includes("result.varying2 = vec4<f32>(d9_point_uv"),
        "POINTSPRITEENABLE must synthesize TEXCOORD0");
});

test("generated WGSL is brace-balanced and declares every register it reads", () => {
    for (const [name, list] of [
        ["vs_1_1", VS_1_1_TRANSFORM], ["ps_1_1", PS_1_1_MODULATE],
        ["ps_2_0", PS_2_0_TEXTURED], ["vs_2_0 flow", VS_2_0_FLOW],
        ["vs_2_0 subroutine", VS_2_0_SUBROUTINE],
    ]) {
        const { wgsl } = compileOk(list, name);
        let depth = 0;
        for (const character of wgsl) {
            if (character === "{") ++depth;
            else if (character === "}") --depth;
            assert.ok(depth >= 0, name + ": unbalanced closing brace");
        }
        assert.strictEqual(depth, 0, name + ": unbalanced braces");
        // Every rN/tN/vinN referenced must have a var<private> declaration.
        const referenced = new Set(wgsl.match(/\b(?:r|t|vin)\d+\b/g) || []);
        for (const register of referenced) {
            if (/^t\d+$/.test(register) && !wgsl.includes("var<private> " + register))
                continue; // `t` also appears inside generated temp names
            assert.ok(wgsl.includes("var<private> " + register + ":"),
                name + ": " + register + " is used but never declared");
        }
    }
});

test("a derivative inside a data-dependent branch is hoisted above it",
        () => {
    // r1 is computed before the branch, so dpdy(r1) above the branch is the
    // same value D3D9 would have produced inside it.
    const result = pipeline.compileShader(new Uint32Array([
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 1), src(REG.INPUT, 0),
        instruction(OP.IFC, { length: 2, control: 5 }),
            src(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.DSY, { length: 2 }), dst(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]));
    assert.ok(result.ok, "translation failed: " + result.error);
    const lines = result.wgsl.split("\n");
    const derivative = lines.findIndex(line => line.includes("dpdy("));
    const branch = lines.findIndex(line => /^\s*if \(/.test(line));
    assert.ok(derivative >= 0, "expected a dpdy call");
    assert.ok(branch >= 0, "expected a branch");
    // The whole point: WGSL rejects the call inside the branch, so it has to
    // come out above it rather than being dropped.
    assert.ok(derivative < branch,
        "the derivative must be hoisted above the branch, not left inside it");
    assert.ok(!/vec4<f32>\(0\.0\)/.test(lines[derivative]),
        "a hoistable derivative must not degrade to zero");
});

test("a derivative of a register the branch rewrites degrades to zero", () => {
    // r1 is assigned *inside* the branch, so there is no value above it to
    // differentiate and hoisting would read the wrong one.
    const result = pipeline.compileShader(new Uint32Array([
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.IFC, { length: 2, control: 5 }),
            src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.DSX, { length: 2 }), dst(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]));
    assert.ok(result.ok, "translation failed: " + result.error);
    assert.ok(!result.wgsl.includes("dpdx("),
        "an unhoistable derivative must not emit a call WGSL rejects");
    assert.ok(result.reflection.warnings.some(warning =>
        warning.includes("no value above the branch")),
        "the approximation has to be reported");
});

test("an in-branch texture sample keeps its mip level via hoisted gradients",
        () => {
    const result = pipeline.compileShader(new Uint32Array([
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.IFC, { length: 2, control: 5 }),
            src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]));
    assert.ok(result.ok, "translation failed: " + result.error);
    // textureSampleGrad is legal under non-uniform control flow because the
    // gradients are explicit, so the sample keeps the mip level the shader
    // asked for instead of dropping to level 0.
    assert.ok(result.wgsl.includes("textureSampleGrad("),
        "expected an explicit-gradient sample");
    assert.ok(!/textureSampleLevel\(d9_tex0[^)]*0\.0\)/.test(result.wgsl),
        "the level-0 fallback must not be used when gradients are available");
    const lines = result.wgsl.split("\n");
    const gradient = lines.findIndex(line => line.includes("dpdx("));
    const branch = lines.findIndex(line => /^\s*if \(/.test(line));
    assert.ok(gradient >= 0 && gradient < branch,
        "the derivatives have to be computed above the branch");
});

// ---- report ----

if (failures.length) {
    for (const failure of failures) {
        console.error("FAIL " + failure.name);
        console.error("  " + (failure.error && failure.error.message));
        if (process.env.D9_TEST_STACK) console.error(failure.error);
    }
    console.error("\n" + failures.length + " failed, " + passed + " passed");
    process.exit(1);
}
console.log(passed + " shader pipeline tests passed");
     source/v64/tests/glbridge/d3d9_shader_wgsl_validation_test.js                                       0000644 0000000 0000000 00000145100 00000000000 021542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Validates that d3d9_shader_pipeline.js emits WGSL a real compiler accepts.
//
// d3d9_shader_pipeline_test.js asserts on translation structure -- which
// registers, varyings and reflection a shader yields -- and would happily pass
// on WGSL that no driver can compile. This file closes that gap by running the
// generated source through `naga`, the WGSL front end wgpu/Firefox use, which
// performs the same shape of validation Chrome's Tint does when
// d3d9_executor.js calls createShaderModule()/getCompilationInfo() (plan 9.6).
// Running it here means a syntax or type error surfaces in Node in one second
// instead of as a black screen inside v86.
//
// naga is optional: install it with
//     cargo install naga-cli
// and either put it on PATH or point D9_NAGA at the binary. Without it this
// test skips (exit 0) rather than failing, so it never blocks a machine that
// only wants the pure-JS suite.

"use strict";

const assert = require("assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync } = require("child_process");
const pipeline = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js");

function findNaga() {
    if (process.env.D9_NAGA) return process.env.D9_NAGA;
    const probe = spawnSync("naga", ["--version"], { encoding: "utf8" });
    return probe.status === 0 ? "naga" : null;
}

const naga = findNaga();
if (!naga) {
    console.log("SKIP: no `naga` binary (install with `cargo install naga-cli` " +
        "or set D9_NAGA) -- WGSL validation not run");
    process.exit(0);
}

// ---- the same little assembler the structural test uses ----

const VS = (major, minor) => (0xfffe0000 | (major << 8) | minor) >>> 0;
const PS = (major, minor) => (0xffff0000 | (major << 8) | minor) >>> 0;
const END = 0x0000ffff;
const REG = pipeline.REGISTER;
const OP = pipeline.OP;
const NOSWIZZLE = 0xe4;

const regTypeBits = type => (((type & 0x7) << 28) | ((type & 0x18) << 8)) >>> 0;
const swizzle = text => {
    let bits = 0;
    for (let i = 0; i < 4; ++i)
        bits |= "xyzw".indexOf(text[Math.min(i, text.length - 1)]) << (i * 2);
    return bits;
};
const instruction = (opcode, options = {}) =>
    ((opcode & 0xffff) | (((options.control || 0) & 0xff) << 16) |
        (((options.length || 0) & 0xf) << 24) |
        (options.predicated ? 0x10000000 : 0)) >>> 0;
const dst = (type, index, options = {}) =>
    (0x80000000 | (index & 0x7ff) | regTypeBits(type) |
        ((options.mask === undefined ? 0xf : options.mask) << 16) |
        (((options.modifier || 0) & 0xf) << 20) |
        (((options.shift || 0) & 0xf) << 24)) >>> 0;
const src = (type, index, options = {}) =>
    (0x80000000 | (index & 0x7ff) | regTypeBits(type) |
        ((options.swizzle === undefined ? NOSWIZZLE : options.swizzle) << 16) |
        (((options.modifier || 0) & 0xf) << 24) |
        (options.relative ? (1 << 13) : 0)) >>> 0;
const dclToken = (usage, usageIndex = 0, textureType = 0) =>
    (0x80000000 | (usage & 0xf) | ((usageIndex & 0xf) << 16) |
        ((textureType & 0xf) << 27)) >>> 0;
const floatBits = value => {
    const buffer = new ArrayBuffer(4);
    new Float32Array(buffer)[0] = value;
    return new Uint32Array(buffer)[0];
};
const USAGE = { POSITION: 0, NORMAL: 3, PSIZE: 4, TEXCOORD: 5, POSITIONT: 9,
    COLOR: 10, FOG: 11 };

// ---- corpus ----
//
// Each entry is a shader shaped like something a real D3D9 game emits, chosen
// to cover a distinct WGSL construct the translator has to get right.

const CORPUS = [
    // What an assembler actually produces for this model: no dcl_ anywhere,
    // because the instruction post-dates it. v0/v5/v7 mean position, diffuse
    // and texcoord0 by API rule, and the entry point has to declare them as
    // real attributes on their register's location.
    ["vs_1_1 as assembled, with no dcl_ to declare its inputs", [
        VS(1, 1),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV), dst(REG.ATTROUT, 0), src(REG.INPUT, 5),
        instruction(OP.MOV), dst(REG.OUTPUT, 0), src(REG.INPUT, 7),
        END,
    ]],
    // The DirectX 8 matrix-palette skinning path. SM1.1 writes its scalar
    // integer address register with MOV (MOVA starts at SM2), then indexes the
    // bone-matrix constants relative to it.
    ["vs_1_1 MOV a0.x matrix-palette skinning", [
        VS(1, 1),
        instruction(OP.MOV), dst(REG.ADDR, 0, { mask: 0x1 }),
            src(REG.INPUT, 2, { swizzle: swizzle("xxxx") }),
        instruction(OP.M4x3), dst(REG.TEMP, 0, { mask: 0x7 }),
            src(REG.INPUT, 0), src(REG.CONST, 4, { relative: true }),
        instruction(OP.MOV), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["vs_1_1 world transform + texcoord passthrough", [
        VS(1, 1),
        instruction(OP.DCL), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DCL), dclToken(USAGE.COLOR, 0), dst(REG.INPUT, 1),
        instruction(OP.DCL), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 2),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV), dst(REG.ATTROUT, 0), src(REG.INPUT, 1),
        instruction(OP.MOV), dst(REG.OUTPUT, 0), src(REG.INPUT, 2),
        END,
    ]],
    ["vs_1_1 diffuse lighting with dp3/max/mul", [
        VS(1, 1),
        instruction(OP.DCL), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DCL), dclToken(USAGE.NORMAL), dst(REG.INPUT, 1),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.DP3), dst(REG.TEMP, 0), src(REG.INPUT, 1), src(REG.CONST, 4),
        instruction(OP.MAX), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.CONST, 5),
        instruction(OP.MUL), dst(REG.ATTROUT, 0), src(REG.TEMP, 0), src(REG.CONST, 6),
        END,
    ]],
    ["vs_1_1 point size and fog rasterizer outputs", [
        VS(1, 1),
        instruction(OP.DCL), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.M4x4), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV), dst(REG.RASTOUT, 1, { mask: 0x1 }),
            src(REG.CONST, 4, { swizzle: swizzle("xxxx") }),
        instruction(OP.MOV), dst(REG.RASTOUT, 2, { mask: 0x1 }),
            src(REG.CONST, 4, { swizzle: swizzle("yyyy") }),
        END,
    ]],
    ["vs_2_0 rep/if/mova/relative addressing", [
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DEFI, { length: 5 }), dst(REG.CONSTINT, 0), 4, 0, 1, 0,
        instruction(OP.DEFB, { length: 2 }), dst(REG.CONSTBOOL, 0), 1,
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.CONST, 0),
        instruction(OP.MOVA, { length: 2 }), dst(REG.ADDR, 0, { mask: 0x1 }),
            src(REG.INPUT, 0, { swizzle: swizzle("wwww") }),
        instruction(OP.MOV, { length: 3 }), dst(REG.TEMP, 1),
            src(REG.CONST, 2, { relative: true }),
            src(REG.ADDR, 0, { swizzle: swizzle("xxxx") }),
        instruction(OP.REP, { length: 1 }), src(REG.CONSTINT, 0),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.ENDREP),
        instruction(OP.IF, { length: 1 }), src(REG.CONSTBOOL, 0),
        instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 0),
        instruction(OP.ELSE),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.CONST, 1),
        instruction(OP.ENDIF),
        instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0), src(REG.CONST, 4),
        END,
    ]],
    ["vs_2_0 loop/endloop with c[aL] matrix palette", [
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DEFI, { length: 5 }), dst(REG.CONSTINT, 0), 4, 8, 1, 0,
        instruction(OP.LOOP, { length: 2 }), src(REG.LOOP, 0), src(REG.CONSTINT, 0),
        instruction(OP.ADD, { length: 4 }), dst(REG.TEMP, 0), src(REG.TEMP, 0),
            src(REG.CONST, 0, { relative: true }), src(REG.LOOP, 0),
        instruction(OP.BREAKC, { length: 2, control: 1 }),
            src(REG.TEMP, 0), src(REG.CONST, 1),
        instruction(OP.ENDLOOP),
        instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0), src(REG.CONST, 4),
        END,
    ]],
    ["vs_2_0 subroutine call graph", [
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.INPUT, 0),
        instruction(OP.CALL, { length: 1 }), src(REG.LABEL, 1),
        instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 0), src(REG.CONST, 0),
        instruction(OP.RET),
        // l1 calls l0, and is declared first -- the emitter has to reorder.
        instruction(OP.LABEL, { length: 1 }), src(REG.LABEL, 1),
        instruction(OP.CALL, { length: 1 }), src(REG.LABEL, 0),
        instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.CONST, 5),
        instruction(OP.RET),
        instruction(OP.LABEL, { length: 1 }), src(REG.LABEL, 0),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 0),
        instruction(OP.RET),
        END,
    ]],
    ["vs_2_0 lit/dst/sincos/nrm/pow transcendentals", [
        VS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.NRM, { length: 2 }), dst(REG.TEMP, 0), src(REG.INPUT, 0),
        instruction(OP.LIT, { length: 2 }), dst(REG.TEMP, 1), src(REG.TEMP, 0),
        instruction(OP.DST, { length: 3 }), dst(REG.TEMP, 2), src(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.SINCOS, { length: 4 }), dst(REG.TEMP, 3, { mask: 0x3 }),
            src(REG.TEMP, 2, { swizzle: swizzle("xxxx") }), src(REG.CONST, 1), src(REG.CONST, 2),
        instruction(OP.POW, { length: 3 }), dst(REG.TEMP, 3), src(REG.TEMP, 3), src(REG.CONST, 3),
        instruction(OP.M4x4, { length: 3 }), dst(REG.RASTOUT, 0), src(REG.TEMP, 3), src(REG.CONST, 4),
        END,
    ]],
    ["vs_3_0 dcl-declared outputs in non-default order", [
        VS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.INPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 3), dst(REG.INPUT, 1),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION), dst(REG.OUTPUT, 4),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.COLOR, 1), dst(REG.OUTPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 7), dst(REG.OUTPUT, 2),
        instruction(OP.M4x4, { length: 3 }), dst(REG.OUTPUT, 4), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.OUTPUT, 0), src(REG.INPUT, 1),
        instruction(OP.MOV, { length: 2 }), dst(REG.OUTPUT, 2), src(REG.INPUT, 1),
        END,
    ]],
    ["vs_3_0 vertex texture fetch", [
        VS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2),
            dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.INPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.POSITION),
            dst(REG.OUTPUT, 0),
        instruction(OP.TEXLDL, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.OUTPUT, 0),
            src(REG.TEMP, 0),
        END,
    ]],
    ["ps_1_1 modulate diffuse by texture", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.MUL), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), src(REG.INPUT, 0),
        END,
    ]],
    ["ps_1_1 texcoord + texkill + result shift", [
        PS(1, 1),
        instruction(OP.TEXCOORD), dst(REG.TEXTURE, 0),
        instruction(OP.TEXKILL), dst(REG.TEXTURE, 1),
        instruction(OP.MUL), dst(REG.TEMP, 0, { shift: 1 }),
            src(REG.TEXTURE, 0), src(REG.INPUT, 0),
        END,
    ]],
    // The ps_1_x texture-addressing family. These build their sample
    // coordinate out of a bump matrix or a chain of dot products rather than
    // reading a texcoord directly, so they are the entries most likely to
    // produce WGSL that parses but does not type-check.
    ["ps_1_1 texbem environment bump mapping", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXBEM), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 1),
        END,
    ]],
    ["ps_1_1 texbeml bump mapping with luminance", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXBEML), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 1),
        END,
    ]],
    ["ps_1_4 bem arithmetic bump displacement", [
        PS(1, 4),
        instruction(OP.TEXCOORD), dst(REG.TEMP, 1), src(REG.TEXTURE, 1),
        instruction(OP.TEX), dst(REG.TEMP, 0), src(REG.TEXTURE, 0),
        instruction(OP.BEM), dst(REG.TEMP, 1, { mask: 0x3 }),
            src(REG.TEMP, 1), src(REG.TEMP, 0),
        instruction(OP.PHASE),
        instruction(OP.TEX), dst(REG.TEMP, 1), src(REG.TEMP, 1),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEMP, 1),
        END,
    ]],
    ["ps_1_1 texm3x3tex tangent-space environment map", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 2), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3TEX), dst(REG.TEXTURE, 3), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 3),
        END,
    ]],
    ["ps_1_1 texm3x3vspec reflective environment map", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3PAD), dst(REG.TEXTURE, 2), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x3VSPEC), dst(REG.TEXTURE, 3), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 3),
        END,
    ]],
    ["ps_1_1 texm3x2tex two-row matrix lookup", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXM3x2PAD), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.TEXM3x2TEX), dst(REG.TEXTURE, 2), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 2),
        END,
    ]],
    ["ps_1_1 texdp3tex dot-product lookup", [
        PS(1, 1),
        instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.TEXDP3TEX), dst(REG.TEXTURE, 1), src(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 1),
        END,
    ]],
    ["ps_1_4 texld with an explicit coordinate register", [
        PS(1, 4),
        instruction(OP.TEXCOORD), dst(REG.TEMP, 0), src(REG.TEXTURE, 0),
        instruction(OP.TEX), dst(REG.TEMP, 1), src(REG.TEMP, 0),
        instruction(OP.PHASE),
        instruction(OP.MUL), dst(REG.TEMP, 0), src(REG.TEMP, 1), src(REG.INPUT, 0),
        END,
    ]],
    ["ps_2_0 two-sampler blend with def constants", [
        PS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 1),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0),
            dst(REG.TEXTURE, 0, { mask: 0x3 }),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 1),
            dst(REG.TEXTURE, 1, { mask: 0x3 }),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0.5), floatBits(0.5), floatBits(1),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), src(REG.SAMPLER, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 1), src(REG.TEXTURE, 1), src(REG.SAMPLER, 1),
        instruction(OP.LRP, { length: 4 }), dst(REG.TEMP, 0),
            src(REG.CONST, 0), src(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.INPUT, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_2_0 cube sampler with a projected coordinate", [
        PS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 3), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
        instruction(OP.TEX, { length: 3, control: 1 }), dst(REG.TEMP, 0),
            src(REG.TEXTURE, 0), src(REG.SAMPLER, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_2_0 volume sampler and dp2add", [
        PS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 4), dst(REG.SAMPLER, 2),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), src(REG.SAMPLER, 2),
        instruction(OP.DP2ADD, { length: 4 }), dst(REG.TEMP, 1),
            src(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 1),
        END,
    ]],
    ["ps_2_0 cmp/slt/sge/frc/abs saturating chain", [
        PS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.25), floatBits(0.5), floatBits(0.75), floatBits(1),
        instruction(OP.FRC, { length: 2 }), dst(REG.TEMP, 0), src(REG.TEXTURE, 0),
        instruction(OP.ABS, { length: 2 }), dst(REG.TEMP, 1), src(REG.TEMP, 0),
        instruction(OP.SLT, { length: 3 }), dst(REG.TEMP, 2), src(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.SGE, { length: 3 }), dst(REG.TEMP, 3), src(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.CMP, { length: 4 }), dst(REG.TEMP, 0, { modifier: 1 }),
            src(REG.TEMP, 2), src(REG.TEMP, 3), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_2_0 source modifiers (bias/sign/complement/x2/abs)", [
        PS(2, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 0), src(REG.TEXTURE, 0, { modifier: 2 }),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.TEMP, 0, { modifier: 4 }), src(REG.TEXTURE, 0, { modifier: 6 }),
        instruction(OP.MAD, { length: 4 }), dst(REG.TEMP, 0),
            src(REG.TEMP, 0, { modifier: 7 }), src(REG.TEMP, 0, { modifier: 11 }),
            src(REG.TEMP, 0, { modifier: 1 }),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_3_0 flow control with vFace/vPos and oDepth", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.COLOR, 0), dst(REG.INPUT, 1),
        instruction(OP.DEFB, { length: 2 }), dst(REG.CONSTBOOL, 0), 1,
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0), src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        // A uniform (bool-register) branch keeps textureSample legal inside.
        instruction(OP.IF, { length: 1 }), src(REG.CONSTBOOL, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 1), src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.ENDIF),
        instruction(OP.MUL, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.MISCTYPE, 1),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 2), src(REG.MISCTYPE, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.DEPTHOUT, 0, { mask: 0x1 }),
            src(REG.TEMP, 2, { swizzle: swizzle("zzzz") }),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_3_0 data-dependent branch degrades to level-0 sampling", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0), floatBits(0), floatBits(0), floatBits(0),
        // `ifc` on an interpolated value is genuinely non-uniform control flow.
        instruction(OP.IFC, { length: 2, control: 1 }), src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0), src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_2_0 texldl/texldd explicit LOD and gradients", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.TEXLDL, { length: 3 }), dst(REG.TEMP, 0), src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.TEXLDD, { length: 5 }), dst(REG.TEMP, 1), src(REG.INPUT, 0),
            src(REG.SAMPLER, 0), src(REG.INPUT, 0), src(REG.INPUT, 0),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    // Sampling inside a data-dependent branch, with the coordinate available
    // above it. This must come out as textureSampleGrad with hoisted
    // derivatives -- naga proves the explicit-gradient form really is legal
    // under non-uniform control flow, which is the whole basis for preferring
    // it over dropping to mip level 0.
    ["ps_3_0 in-branch sample keeps its mip level via hoisted gradients", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(0, 0, 2), dst(REG.SAMPLER, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.IFC, { length: 2, control: 5 /* ne */ }),
            src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.TEX, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.INPUT, 0), src(REG.SAMPLER, 0),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    // The exact shape that made 3DMark06's airship a black silhouette: a
    // derivative inside a data-dependent `if`. Legal in D3D9, which runs both
    // sides of the branch; a compile error in WGSL, which is why naga has to
    // see this one.
    ["ps_3_0 dsx/dsy inside a data-dependent branch", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        // r1 is computed before the branch, so its derivative can be hoisted.
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 1), src(REG.INPUT, 0),
        instruction(OP.IFC, { length: 2, control: 5 /* ne */ }),
            src(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.DSX, { length: 2 }), dst(REG.TEMP, 2), src(REG.TEMP, 1),
        instruction(OP.DSY, { length: 2 }), dst(REG.TEMP, 3), src(REG.TEMP, 1),
        instruction(OP.ADD, { length: 3 }), dst(REG.TEMP, 0),
            src(REG.TEMP, 2), src(REG.TEMP, 3),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    // The case that cannot be hoisted: the branch overwrites the operand, so
    // there is no value above it to differentiate.
    ["ps_3_0 dsx of a register the branch itself rewrites", [
        PS(3, 0),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.INPUT, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.IFC, { length: 2, control: 5 /* ne */ }),
            src(REG.INPUT, 0), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.TEMP, 1), src(REG.CONST, 0),
        instruction(OP.DSX, { length: 2 }), dst(REG.TEMP, 0), src(REG.TEMP, 1),
        instruction(OP.ENDIF),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
    ["ps_2_x predicated instruction with setp", [
        PS(2, 1),
        instruction(OP.DCL, { length: 2 }), dclToken(USAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
        instruction(OP.DEF, { length: 5 }), dst(REG.CONST, 0),
            floatBits(0.5), floatBits(0), floatBits(0), floatBits(0),
        instruction(OP.SETP, { length: 3, control: 4 /* lt */ }), dst(REG.PREDICATE, 0),
            src(REG.TEXTURE, 0), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 3, predicated: true }), dst(REG.TEMP, 0),
            src(REG.PREDICATE, 0, { swizzle: swizzle("xxxx") }), src(REG.CONST, 0),
        instruction(OP.MOV, { length: 2 }), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
        END,
    ]],
];

// ---- run ----

// SM1 has no dcl_2d/dcl_cube: specialize ordinary tex/texld from SetTexture.
for (const minor of [1, 4]) {
    const code = minor === 1 ? [
        PS(1, 1), instruction(OP.TEX), dst(REG.TEXTURE, 0),
        instruction(OP.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), END,
    ] : [
        PS(1, 4), instruction(OP.TEX), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), END,
    ];
    for (const type of ["cube", "3d"]) {
        CORPUS.push(["ps_1_" + minor + " bound " + type, code, {
            legacySamplerTypes: { 0: type },
        }]);
    }
}

const directory = fs.mkdtempSync(path.join(os.tmpdir(), "d9wgsl-"));
const failures = [];
let validated = 0;

for (const [name, list, options] of CORPUS) {
    const stream = new Uint32Array(list);
    const result = pipeline.compileShader(stream, options);
    if (!result.ok) {
        failures.push({ name, message: "translation failed: " + result.error });
        continue;
    }
    const file = path.join(directory,
        name.replace(/[^a-z0-9]+/gi, "_").toLowerCase() + ".wgsl");
    fs.writeFileSync(file, result.wgsl);
    const run = spawnSync(naga, [file], { encoding: "utf8" });
    if (run.status !== 0) {
        failures.push({ name, message: (run.stderr || run.stdout || "").trim(),
            source: result.wgsl });
        continue;
    }
    ++validated;
}

// M5's declaration-specific vertex variants change the WGSL input scalar
// types and inject unpack helpers, so validate each conversion with naga too.
for (const [name, kind] of [["ubyte4", "ubyte4"], ["short2", "short2"],
        ["short4", "short4"], ["udec3", "udec3"], ["dec3n", "dec3n"]]) {
    const result = pipeline.compileShader(new Uint32Array(CORPUS[0][1]), {
        inputConversions: { 0: kind },
    });
    if (!result.ok) {
        failures.push({ name: "M5 " + name,
            message: "translation failed: " + result.error });
        continue;
    }
    const file = path.join(directory, "m5_" + name + ".wgsl");
    fs.writeFileSync(file, result.wgsl);
    const run = spawnSync(naga, [file], { encoding: "utf8" });
    if (run.status !== 0)
        failures.push({ name: "M5 " + name,
            message: (run.stderr || run.stdout || "").trim(), source: result.wgsl });
    else ++validated;
}

// M6 point primitives use a translated vertex-shader variant with instance
// attributes and @builtin(vertex_index) quad expansion.
{
    const result = pipeline.compileShader(new Uint32Array(CORPUS[0][1]), {
        pointExpansion: true, pointSprite: true,
    });
    const file = path.join(directory, "m6_programmable_point_sprite.wgsl");
    if (!result.ok) {
        failures.push({ name: "M6 programmable point sprite",
            message: "translation failed: " + result.error });
    } else {
        fs.writeFileSync(file, result.wgsl);
        const run = spawnSync(naga, [file], { encoding: "utf8" });
        if (run.status !== 0)
            failures.push({ name: "M6 programmable point sprite",
                message: (run.stderr || run.stdout || "").trim(),
                source: result.wgsl });
        else ++validated;
    }
}

// Programmable clip-plane variants add two inter-stage vec4s and extend the
// vertex constant block. Validate both modules, not just their fixed-function
// counterparts below.
for (const [name, source] of [
        ["programmable clip-plane vertex", CORPUS.find(entry =>
            entry[0].startsWith("vs_3_0 dcl"))[1]],
        ["programmable clip-plane pixel", CORPUS.find(entry =>
            entry[0].startsWith("ps_2_0 two-sampler"))[1]],
    ]) {
    const result = pipeline.compileShader(new Uint32Array(source), {
        clipPlaneCount: 6,
    });
    const file = path.join(directory,
        name.replace(/[^a-z0-9]+/gi, "_") + ".wgsl");
    if (!result.ok) {
        failures.push({ name, message: "translation failed: " + result.error });
    } else {
        fs.writeFileSync(file, result.wgsl);
        const run = spawnSync(naga, [file], { encoding: "utf8" });
        if (run.status !== 0)
            failures.push({ name,
                message: (run.stderr || run.stdout || "").trim(),
                source: result.wgsl });
        else ++validated;
    }
}

// Hardware shadow maps: a stage bound to a depth texture is declared
// texture_depth_2d and sampled through a sampler_comparison, which is a
// different WGSL type system from every other case above -- textureSample does
// not accept a comparison sampler and textureSampleCompare does not accept an
// ordinary one, so a mistake here is a compile error rather than a wrong
// image. The projected form is included because that is what a shadow lookup
// actually uses: tex2Dproj supplies the comparison reference as z/w.
for (const [name, entry] of [
        ["depth compare", "ps_2_0 two-sampler blend with def constants"],
        ["depth compare projected", "ps_2_0 cube sampler with a projected " +
            "coordinate"],
        ["depth compare non-uniform", "ps_3_0 data-dependent branch degrades " +
            "to level-0 sampling"],
        ["depth compare explicit lod", "ps_2_0 texldl/texldd explicit LOD and " +
            "gradients"],
    ]) {
    const source = CORPUS.find(item => item[0] === entry);
    assert.ok(source, "validation corpus is missing " + entry);
    const result = pipeline.compileShader(new Uint32Array(source[1]), {
        depthSamplers: [0],
    });
    if (!result.ok) {
        failures.push({ name, message: "translation failed: " + result.error });
        continue;
    }
    // The cube case must *not* become a depth sampler: a cube depth texture
    // cannot be created at all, and silently emitting texture_depth_2d for one
    // would pair a cube view with a 2D layout entry.
    const sampler0 = result.reflection.samplers.find(item => item.index === 0);
    if (sampler0.type === "2d") {
        assert.equal(sampler0.depth, "compare",
            name + ": a 2D sampler asked to be depth must report it");
        assert.ok(result.wgsl.includes("texture_depth_2d"),
            name + ": expected a texture_depth_2d declaration");
        assert.ok(result.wgsl.includes("sampler_comparison"),
            name + ": expected a sampler_comparison declaration");
        assert.ok(/textureSampleCompare(Level)?\(/.test(result.wgsl),
            name + ": expected a comparison sample");
        // Only stage 0 is the shadow map; the two-sampler case keeps an
        // ordinary textureSample on stage 1, which is the point -- one module
        // has to carry both kinds at once.
        assert.ok(!/textureSample(Bias|Grad|Level)?\(d9_tex0\b/.test(result.wgsl),
            name + ": a comparison sampler cannot be used with textureSample");
    } else {
        assert.equal(sampler0.depth, false,
            name + ": only 2D samplers can be depth");
    }
    const file = path.join(directory,
        name.replace(/[^a-z0-9]+/gi, "_") + ".wgsl");
    fs.writeFileSync(file, result.wgsl);
    const run = spawnSync(naga, [file], { encoding: "utf8" });
    if (run.status !== 0)
        failures.push({ name, message: (run.stderr || run.stdout || "").trim(),
            source: result.wgsl });
    else ++validated;
}

// The other half of the depth story: the ATI FOURCC formats read the stored
// depth back instead of comparing against it. Same texture_depth_2d, an
// ordinary sampler, textureSampleLevel rather than textureSampleCompare -- and
// naga is the thing that proves those three agree, because pairing a
// sampler_comparison with textureSampleLevel is a type error, not a bad image.
for (const [name, entry] of [
        ["depth fetch", "ps_2_0 two-sampler blend with def constants"],
        ["depth fetch explicit lod", "ps_2_0 texldl/texldd explicit LOD and " +
            "gradients"],
    ]) {
    const source = CORPUS.find(item => item[0] === entry);
    assert.ok(source, "validation corpus is missing " + entry);
    const result = pipeline.compileShader(new Uint32Array(source[1]), {
        depthSamplers: [0], depthFetchSamplers: [0],
    });
    if (!result.ok) {
        failures.push({ name, message: "translation failed: " + result.error });
        continue;
    }
    const sampler0 = result.reflection.samplers.find(item => item.index === 0);
    assert.equal(sampler0.depth, "fetch",
        name + ": a raw-depth sampler must report the fetch mode");
    assert.ok(result.wgsl.includes("texture_depth_2d"),
        name + ": a depth fetch is still a depth texture");
    assert.ok(!result.wgsl.includes("sampler_comparison"),
        name + ": a fetch reads through an ordinary sampler");
    assert.ok(!/textureSampleCompare/.test(result.wgsl),
        name + ": a fetch does not compare");
    assert.ok(/textureSampleLevel\(d9_tex0\b/.test(result.wgsl),
        name + ": expected a level-explicit depth fetch");
    const file = path.join(directory,
        name.replace(/[^a-z0-9]+/gi, "_") + ".wgsl");
    fs.writeFileSync(file, result.wgsl);
    const run = spawnSync(naga, [file], { encoding: "utf8" });
    if (run.status !== 0)
        failures.push({ name, message: (run.stderr || run.stdout || "").trim(),
            source: result.wgsl });
    else ++validated;
}

// The synthesised fixed-function stages are part of the same contract and
// pair with translated shaders inside a pipeline, so they get validated here
// too rather than only being exercised through the fake-device executor test.
{
    const executor = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js");
    const fixedFunction = [];
    // A vertex signature with every optional field defaulted off. The builder
    // reads these unconditionally, so a partial object would fail for reasons
    // that have nothing to do with what a case is testing.
    const vsBase = overrides => Object.assign({
        positionType: "world", hasColor: false, colorIsBGRA: false,
        hasColor1: false, color1IsBGRA: false, hasNormal: false,
        hasPointSize: false,
        texCoordSets: [], hasTexCoord: false, coordStages: [],
        fogMode: 0, fogRange: false, normalizeNormals: false,
        needsViewSpace: false, lighting: null, clipPlaneCount: 0,
        pointExpansion: false, pointSprite: false, pointScale: false,
        blendWeightType: -1, blendIndicesType: -1, vertexBlend: null,
    }, overrides);
    for (const positionType of ["world", "screen"]) {
        for (const hasColor of [false, true]) {
            for (const hasTexCoord of [false, true]) {
                fixedFunction.push(["ff vs " + positionType +
                    (hasColor ? " colour" : "") + (hasTexCoord ? " texcoord" : ""),
                    executor.buildFixedFunctionVertexShader(vsBase({
                        positionType, hasColor, hasTexCoord,
                        texCoordSets: hasTexCoord ? [0] : [],
                        coordStages: hasTexCoord
                            ? [{ index: 0, texCoordIndex: 0, tciMode: 0,
                                transformCount: 0, projected: false }] : [],
                    }))]);
            }
        }
    }
    // M3's fixed-function lighting: every light type, every material source,
    // and the two branches (local viewer, specular) that change the maths.
    for (const type of [1, 2, 3]) { // D3DLIGHT_POINT / SPOT / DIRECTIONAL
        for (const specularEnable of [false, true]) {
            for (const localViewer of [false, true]) {
                fixedFunction.push(["ff vs light type" + type +
                    (specularEnable ? " specular" : "") +
                    (localViewer ? " localviewer" : ""),
                    executor.buildFixedFunctionVertexShader(vsBase({
                        hasColor: true, hasColor1: true, hasNormal: true,
                        needsViewSpace: true, normalizeNormals: true,
                        lighting: { lights: [{ index: 0, type }, { index: 3, type }],
                            colorVertex: true, specularEnable, localViewer,
                            diffuseSource: 1, ambientSource: 0,
                            specularSource: 2, emissiveSource: 0 },
                    }))]);
            }
        }
    }
    for (const source of [0, 1, 2]) { // D3DMCS_MATERIAL / COLOR1 / COLOR2
        fixedFunction.push(["ff vs material source " + source,
            executor.buildFixedFunctionVertexShader(vsBase({
                hasColor: true, hasColor1: true, hasNormal: true,
                needsViewSpace: true,
                lighting: { lights: [{ index: 0, type: 3 }], colorVertex: true,
                    specularEnable: true, localViewer: false,
                    diffuseSource: source, ambientSource: source,
                    specularSource: source, emissiveSource: source },
            }))]);
    }
    // Coordinate generation and the transform component counts, including the
    // camera-space modes that make the shader read view-space position/normal.
    for (const tciMode of [0, 0x10000, 0x20000, 0x30000]) {
        for (const transformCount of [0, 1, 2, 3, 4]) {
            fixedFunction.push(["ff vs tci " + tciMode.toString(16) +
                " count" + transformCount,
                executor.buildFixedFunctionVertexShader(vsBase({
                    hasNormal: true, texCoordSets: [0, 1], hasTexCoord: true,
                    needsViewSpace: tciMode !== 0,
                    coordStages: [
                        { index: 0, texCoordIndex: 1, tciMode, transformCount,
                          projected: false },
                        { index: 1, texCoordIndex: 0, tciMode: 0,
                          transformCount: 0, projected: false },
                    ],
                }))]);
        }
    }
    // 3DMark 2001 leaves camera-space reflection TCI selected while drawing
    // one XYZRHW pass with no normal or texture-coordinate declaration. The
    // value is undefined in D3D, but the generated WGSL must remain valid: a
    // reference to position_view/normal_view here invalidates the module and
    // every pipeline/command buffer that follows it.
    fixedFunction.push(["ff vs screen stale camera reflection tci",
        executor.buildFixedFunctionVertexShader(vsBase({
            positionType: "screen", hasColor: true,
            coordStages: [{ index: 0, texCoordIndex: 0, tciMode: 0x30000,
                transformCount: 3, projected: false }],
        }))]);
    for (const fogMode of [1, 2, 3]) {
        for (const fogRange of [false, true]) {
            fixedFunction.push(["ff vs fog " + fogMode + (fogRange ? " range" : ""),
                executor.buildFixedFunctionVertexShader(vsBase({
                    fogMode, fogRange, needsViewSpace: fogRange,
                }))]);
        }
    }
    // Fixed-function vertex blending: every matrix count, both the ordered and
    // the indexed matrix source, and both integer index formats -- BLENDINDICES
    // is the one fixed-function attribute whose WGSL type is not f32, so a
    // wrong base type here is a compile error the compiler has to be the one to
    // catch. Paired with lighting because the blended normal takes a different
    // path from the plain one.
    for (let matrixCount = 1; matrixCount <= 4; ++matrixCount) {
        for (const indexScalar of [null, "u32", "i32", "f32", "f32-plain"]) {
            for (const hasNormal of [false, true]) {
                const indexed = indexScalar !== null;
                const scalar = indexed
                    ? indexScalar.replace("-plain", "") : "u32";
                fixedFunction.push(["ff vs blend " + matrixCount +
                    (indexed ? " indexed " + indexScalar : " ordered") +
                    (hasNormal ? " normal" : ""),
                    executor.buildFixedFunctionVertexShader(vsBase({
                        hasNormal, needsViewSpace: hasNormal,
                        normalizeNormals: hasNormal,
                        lighting: hasNormal
                            ? { lights: [{ index: 0, type: 3 }],
                                colorVertex: false, specularEnable: false,
                                localViewer: false, diffuseSource: 0,
                                ambientSource: 0, specularSource: 0,
                                emissiveSource: 0 }
                            : null,
                        blendWeightType: matrixCount > 1 ? 2 : -1,
                        blendIndicesType: indexed ? 5 : -1,
                        vertexBlend: {
                            matrixCount, weightCount: matrixCount - 1, indexed,
                            indexScalar: scalar,
                            // The unorm8x4 spelling (D3DCOLOR/UBYTE4N) reaches
                            // the shader as bytes over 255 and needs its own
                            // conversion, so it is its own case here.
                            indexNormalized: indexScalar === "f32",
                            matrixSlots: indexed ? 16 : matrixCount,
                        },
                    }))]);
            }
        }
    }
    fixedFunction.push(["ff vs point sprite scaled",
        executor.buildFixedFunctionVertexShader(vsBase({
            hasColor: true, hasPointSize: true, needsViewSpace: true,
            pointExpansion: true, pointSprite: true, pointScale: true,
            texCoordSets: [0], hasTexCoord: true,
            coordStages: [{ index: 0, texCoordIndex: 0, tciMode: 0,
                transformCount: 0, projected: false }],
        }))]);
    fixedFunction.push(["ff vs six user clip planes",
        executor.buildFixedFunctionVertexShader(vsBase({
            hasColor: true, clipPlaneCount: 6,
        }))]);

    // A pixel signature with a single default stage.
    const stage = overrides => Object.assign({
        index: 0, colorOp: 4, colorArg0: 1, colorArg1: 2, colorArg2: 1,
        alphaOp: 2, alphaArg0: 1, alphaArg1: 2, alphaArg2: 1, resultArg: 1,
        usesConstant: false, samplesTexture: true, textureType: "2d",
        transformCount: 0, projected: false, coordVarying: 0,
    }, overrides);
    const psBase = overrides => Object.assign({
        stages: [stage()], usesTextureFactor: false, fogMode: 0,
        tableFog: false,
        alphaTest: { enabled: false, func: 8, reference: 0 },
        specularEnable: false, clipPlaneCount: 0,
    }, overrides);
    for (const hasTexture of [false, true]) {
        for (const debugMode of [null, "solid", "color", "uv", "texture"]) {
            fixedFunction.push(["ff ps" + (hasTexture ? " textured" : "") +
                (debugMode ? " " + debugMode : ""),
                executor.buildFixedFunctionPixelShader(psBase({
                    stages: hasTexture ? [stage()] : [],
                }), debugMode)]);
        }
    }
    // Every D3DTEXTUREOP fill_caps() advertises, on both channels, since the
    // colour and alpha forms are emitted from separate code paths.
    for (const op of [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 24, 25, 26]) {
        fixedFunction.push(["ff ps op " + op,
            executor.buildFixedFunctionPixelShader(psBase({
                usesTextureFactor: true,
                stages: [stage({ colorOp: op, alphaOp: op, colorArg0: 3,
                    alphaArg0: 3 })],
            }), null)]);
    }
    // The argument pool, its two modifier bits, the scratch register and a
    // multi-stage cascade that threads a result through it.
    fixedFunction.push(["ff ps argument pool",
        executor.buildFixedFunctionPixelShader(psBase({
            usesTextureFactor: true, specularEnable: true,
            stages: [
                stage({ index: 0, colorOp: 26, colorArg0: 0x10 | 0,
                    colorArg1: 0x20 | 2, colorArg2: 3, alphaOp: 4,
                    alphaArg1: 4, alphaArg2: 6, usesConstant: true,
                    resultArg: 5 }),
                stage({ index: 1, colorOp: 25, colorArg0: 5, colorArg1: 1,
                    colorArg2: 2, alphaOp: 1, coordVarying: 1 }),
            ],
        }), null)]);
    // Cube and volume textures reach the cascade too, and PROJECTED changes the
    // coordinate expression rather than the sample.
    for (const textureType of ["2d", "cube", "3d"]) {
        for (const projected of [false, true]) {
            fixedFunction.push(["ff ps " + textureType +
                (projected ? " projected" : ""),
                executor.buildFixedFunctionPixelShader(psBase({
                    stages: [stage({ textureType, projected,
                        transformCount: projected ? 3 : 0 })],
                }), null)]);
        }
    }
    fixedFunction.push(["ff ps projected border colour",
        executor.buildFixedFunctionPixelShader(psBase({
            stages: [stage({ projected: true, transformCount: 3,
                addressU: 4, addressV: 4, addressW: 1,
                borderColor: 0x80402010 })],
        }), null)]);
    fixedFunction.push(["ff ps d3d7 texture colour key",
        executor.buildFixedFunctionPixelShader(psBase({
            stages: [stage({ colorKey: {
                low: 0x00102030, high: 0x00112233, indexed: false,
            } })],
        }), null)]);
    fixedFunction.push(["ff ps d3d7 indexed texture colour key",
        executor.buildFixedFunctionPixelShader(psBase({
            stages: [stage({ colorKey: {
                low: 9, high: 12, indexed: true,
            } })],
        }), null)]);
    for (const fogMode of [1, 2, 3]) {
        fixedFunction.push(["ff ps vertex fog " + fogMode,
            executor.buildFixedFunctionPixelShader(psBase({
                fogMode, specularEnable: true,
                alphaTest: { enabled: true, func: 5, reference: 128 },
            }), null)]);
        fixedFunction.push(["ff ps table fog " + fogMode,
            executor.buildFixedFunctionPixelShader(psBase({
                fogMode, tableFog: true, specularEnable: true,
                alphaTest: { enabled: true, func: 5, reference: 128 },
            }), null)]);
    }
    fixedFunction.push(["ff ps six user clip planes",
        executor.buildFixedFunctionPixelShader(psBase({
            clipPlaneCount: 6,
        }), null)]);
    for (const [name, wgsl] of fixedFunction) {
        const file = path.join(directory,
            name.replace(/[^a-z0-9]+/gi, "_").toLowerCase() + ".wgsl");
        fs.writeFileSync(file, wgsl);
        const run = spawnSync(naga, [file], { encoding: "utf8" });
        if (run.status !== 0)
            failures.push({ name, message: (run.stderr || run.stdout || "").trim(),
                source: wgsl });
        else ++validated;
    }
}

// A vertex and a fragment module have to agree on their inter-stage interface
// or the pipeline will not link. naga validates modules one at a time, so
// check the contract this translator relies on -- every vertex shader emits
// the complete varying set -- across a VS/PS pair that share no semantics.
{
    const vs = pipeline.compileShader(new Uint32Array(CORPUS[0][1]));
    const ps = pipeline.compileShader(new Uint32Array(CORPUS[11][1]));
    assert.ok(vs.ok && ps.ok, "corpus pair failed to translate");
    for (let slot = 0; slot < pipeline.VARYING_COUNT; ++slot) {
        const declaration = "@location(" + slot + ") varying" + slot + ": vec4<f32>,";
        if (!vs.wgsl.includes(declaration))
            failures.push({ name: "VS/PS interface",
                message: "vertex output is missing varying slot " + slot });
        if (!ps.wgsl.includes(declaration))
            failures.push({ name: "VS/PS interface",
                message: "pixel input is missing varying slot " + slot });
    }
}

// D3DSHADE_FLAT: the same pair compiled flat-shaded. Valid on its own, and
// the colour slots (only those) flat in both stages, so the pair still links.
{
    const pair = [["vertex", CORPUS[0][1]], ["pixel", CORPUS[11][1]]]
        .map(([kind, tokens]) => [kind, pipeline.compileShader(new Uint32Array(tokens),
            { flatShading: true })]);
    for (const [kind, result] of pair) {
        const name = "flat-shaded " + kind + " shader";
        if (!result.ok) {
            failures.push({ name, message: "translation failed: " + result.error });
            continue;
        }
        const file = path.join(directory, "flat_" + kind + ".wgsl");
        fs.writeFileSync(file, result.wgsl);
        const run = spawnSync(naga, [file], { encoding: "utf8" });
        if (run.status !== 0)
            failures.push({ name, message: (run.stderr || run.stdout || "").trim(),
                source: result.wgsl });
        else ++validated;
        for (let slot = 0; slot < pipeline.VARYING_COUNT; ++slot) {
            const flat = slot === pipeline.VARYING_COLOR0 || slot === pipeline.VARYING_COLOR1;
            const declaration = "@location(" + slot + ")" + (flat ? " @interpolate(flat)" : "") +
                " varying" + slot + ": vec4<f32>,";
            if (!result.wgsl.includes(declaration))
                failures.push({ name, message: "expected `" + declaration + "`",
                    source: result.wgsl });
        }
    }
}

if (failures.length) {
    for (const failure of failures) {
        console.error("FAIL " + failure.name);
        console.error(failure.message.split("\n").map(l => "  " + l).join("\n"));
        if (process.env.D9_TEST_WGSL && failure.source)
            console.error(failure.source);
    }
    console.error("\n" + failures.length + " failed, " + validated +
        " validated (naga: " + naga + ")");
    console.error("generated sources kept in " + directory);
    process.exit(1);
}
fs.rmSync(directory, { recursive: true, force: true });
console.log(validated + " translated shaders validated by naga");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/glbridge/d3d9_virtio_browser_test.html                                             0000644 0000000 0000000 00000012735 00000000000 020444  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>D3D9 virtio transport regression</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script src="../../build/libv86.js"></script>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
(async () => {
    const checks = [];
    const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
    let emulator;
    try {
        emulator = new V86({
            graphics_adapter: "bochs_vga",
            wasm_path: "../../build/v86.wasm", memory_size: 32 * 1024 * 1024,
            bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
            screen: { container: document.getElementById("screen") },
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false,
            graphics_proxy: true,
        });
        await new Promise(resolve => emulator.add_listener("emulator-loaded",resolve));
        const bridge = emulator.graphics_proxy.bridge;
        check(!bridge.failed, "graphics initializes");
        emulator.screen_adapter.set_mode(true);
        emulator.screen_adapter.set_size_graphical(64,64,64,64);
        const cpu = emulator.v86.cpu, io = cpu.io;
        const ram = cpu.read_blob(0,32*1024*1024);
        const memory = new DataView(ram.buffer,ram.byteOffset,ram.byteLength);
    const table = 0x10000, avail = table + 128, used = table + 160;
    const request = table + 256, reply = table + 288, arena = 0x100000;
    const w8 = (off, value) => io.port_write8(0xf100 + off, value);
    const w16 = (off, value) => io.port_write16(0xf100 + off, value);
    const w32 = (off, value) => io.port_write32(0xf100 + off, value);
    w8(20, 0); w8(20, 3);
    w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1); w8(20, 11);
    check(io.port_read8(0xf114) === 11, "virtio features negotiated");
    w16(22, 0); w16(24, 8);
    w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0);
    w32(48, used); w32(52, 0);
    memory.setUint32(table, request, true); memory.setUint32(table + 8, 24, true);
    memory.setUint16(table + 12, 1, true); memory.setUint16(table + 14, 1, true);
    memory.setUint32(table + 16, reply, true); memory.setUint32(table + 24, 16, true);
    memory.setUint16(table + 28, 2, true); memory.setUint16(avail, 1, true);
    w16(28, 1); w8(20, 15);
    let idx = 0;
    const submit = (opcode, address, length, flags) => {
        [opcode, address, 0, length, flags, 0].forEach((v, i) => memory.setUint32(request + i * 4, v, true));
        memory.setUint32(reply, 0xffffffff, true);
        memory.setUint16(avail + 4 + (idx & 7) * 2, 0, true);
        memory.setUint16(avail + 2, ++idx, true);
        io.port_write16(0xf200, 0);
        if(memory.getUint16(used + 2, true) !== idx || memory.getUint32(reply, true) !== 0)
            throw new Error("virtio request failed: " + memory.getUint32(reply, true));
    };
    submit(1, arena, 16 * 1024 * 1024, 0);

        // Exactly the wrapper authored by d3d9_proxy.c (also D3D8/DDraw):
        // VGL2 reserved0 = D9WG_MAGIC, one extended 0xFFE1 record, D9WG v1.3.
        const session = [0xd0090001,0x20260806];
        const commands = [
            [1,[32,0,...session]], // HELLO
            [2,[1,0x1234,0,0,64,64,22,1,0x20,1,75,0,0]], // CREATE_DEVICE
            [5,[1,1,0xffff0000,0x3f800000,0,0]], // CLEAR red
            [4,[1,0x1234,0,0,64,64]], // PRESENT
        ];
        const sizes = commands.map(([,values]) => (16+values.length*4+7)&~7);
        const batchBytes = 32 + sizes.reduce((a,b)=>a+b,0);
        const wrapped = new Uint8Array(8 + batchBytes);
        const d9 = new DataView(wrapped.buffer);
        d9.setUint16(0,0xffe1,true); d9.setUint16(2,0xffff,true);
        d9.setUint32(4,batchBytes,true);
        d9.setUint32(8,0x47573944,true);
        d9.setUint16(12,1,true); d9.setUint16(14,3,true);
        [1,1,commands.length,batchBytes-32,...session].forEach((v,i)=>d9.setUint32(16+i*4,v,true));
        let cursor = 40;
        commands.forEach(([op,values],i)=>{
            d9.setUint16(cursor,op,true); d9.setUint32(cursor+4,sizes[i],true);
            d9.setUint32(cursor+8,i+1,true);
            values.forEach((v,j)=>d9.setUint32(cursor+16+j*4,v,true));
            cursor += sizes[i];
        });
        [0x324c4756,1,0,1,1,wrapped.length,0x47573944,0].forEach((v,i)=>memory.setUint32(arena+i*4,v,true));
        ram.set(wrapped,arena+32);
        submit(2,0,32+wrapped.length,0);
        check(cpu.devices.virtio_devices.find(device => device.name === "v86gl").descriptor.get_state()[5]===1,"virtqueue accepts shipping D9WG reserved0 marker");
        await bridge.d3d9Executor.idle();
        check(!bridge.d3d9Executor.failed,"D3D9 batch executes");
        check(bridge.activeOwner==="d3d9","D3D9 Present shows its window layer");
        const shot = emulator.screen_make_screenshot();
        await shot.decode();
        const capture = document.createElement("canvas");
        capture.width = capture.height = 64;
        const ctx = capture.getContext("2d");
        ctx.drawImage(shot,0,0);
        const pixel = [...ctx.getImageData(32,32,1,1).data];
        check(pixel.join()==="255,0,0,255","D3D9 virtqueue produces red pixels: "+pixel);
        await emulator.destroy();
        document.getElementById("result").textContent="PASS\n"+checks.join("\n");
    } catch(error) {
        if(emulator) await emulator.destroy();
        document.getElementById("result").textContent="FAIL\n"+(error.stack||error);
    }
})();
</script>
                                   source/v64/tests/glbridge/d3d9_webgpu_browser_test.html                                             0000644 0000000 0000000 00000110613 00000000000 020413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>D3D9 WebGPU browser validation test</title>
<style>
body { margin: 0; background: #111; color: #eee; font: 14px monospace; }
canvas { width: 640px; height: 480px; }
#result { white-space: pre-wrap; padding: 12px; }
</style>
<canvas id="screen" width="640" height="480"></canvas>
<div id="result">RUNNING</div>
<script src="../../src/browser/glbridge/webgpu_host.js"></script>
<script src="../../src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js"></script>
<script src="../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js"></script>
<script>
(async () => {
    "use strict";
    const result = document.getElementById("result");
    const sessionLow = 0xD0090001;
    const sessionHigh = 0x20260806;
    const u32 = (...values) => {
        const payload = new Uint8Array(values.length * 4);
        const view = new DataView(payload.buffer);
        values.forEach((value, index) => view.setUint32(index * 4,
            value >>> 0, true));
        return payload;
    };
    const surface = (handle, width, height) =>
        u32(handle, 0x1234, 0, 0, width, height);
    const createDevice = (handle, width, height) =>
        u32(handle, 0x1234, 0, 0, width, height, 22, 1, 0x20, 1,
            75 /* D3DFMT_D24S8 */, 0 /* no MSAA */, 0 /* quality */);
    const transform = (handle, state, matrix) => {
        const payload = new Uint8Array(72);
        const view = new DataView(payload.buffer);
        view.setUint32(0, handle, true);
        view.setUint32(4, state, true);
        matrix.forEach((value, index) =>
            view.setFloat32(8 + index * 4, value, true));
        return payload;
    };
    // D9WGVertexElement is 8 bytes: stream(u16), offset(u16), type(u8),
    // method(u8), usage(u8), usageIndex(u8) -- see d3d9_protocol.h.
    const element = (offset, type, usage, usageIndex = 0) => {
        const payload = new Uint8Array(8);
        const view = new DataView(payload.buffer);
        view.setUint16(0, 0, true); // stream
        view.setUint16(2, offset, true);
        view.setUint8(4, type);
        view.setUint8(5, 0); // D3DDECLMETHOD_DEFAULT
        view.setUint8(6, usage);
        view.setUint8(7, usageIndex);
        return payload;
    };
    const concatBytes = arrays => {
        const total = arrays.reduce((sum, a) => sum + a.byteLength, 0);
        const out = new Uint8Array(total);
        let offset = 0;
        for (const a of arrays) { out.set(a, offset); offset += a.byteLength; }
        return out;
    };
    // SET_FVF's payload is device_handle/fvf/element_count/reserved followed
    // by the decoded D9WGVertexElement array (see d3d9_protocol.h and plan
    // section 4.3 -- the host never decodes raw FVF bits itself).
    const setFVF = (handle, fvf, elements) =>
        concatBytes([u32(handle, fvf, elements.length, 0), ...elements]);

    const DECLTYPE_FLOAT1 = 0;
    const DECLTYPE_FLOAT2 = 1;
    const DECLTYPE_FLOAT3 = 2;
    const DECLTYPE_FLOAT4 = 3;
    const DECLTYPE_D3DCOLOR = 4;
    const DECLTYPE_UBYTE4 = 5;
    const DECLUSAGE_POSITION = 0;
    const DECLUSAGE_PSIZE = 4;
    const DECLUSAGE_TEXCOORD = 5;
    const DECLUSAGE_POSITIONT = 9;
    const DECLUSAGE_COLOR = 10;

    // ---- M2 helpers ----
    // CREATE_{VERTEX,PIXEL}_SHADER: device/handle/token_count/code_offset/
    // hash_low/hash_high, with the raw token stream as the trailing blob.
    const createShader = (deviceHandle, handle, tokens) => {
        const hash = D3D9ShaderPipeline.hashTokens(tokens);
        const blob = new Uint8Array(tokens.buffer.slice(0));
        return { payload: u32(deviceHandle, handle, tokens.length, 0,
                hash.low, hash.high),
            blobs: [{ offsetField: 12, data: blob }] };
    };
    // SET_*_SHADER_CONSTANT_F: device/start_register/vector_count/data_offset.
    const shaderConstants = (deviceHandle, startRegister, values) => {
        const data = new Uint8Array(new Float32Array(values).buffer);
        return { payload: u32(deviceHandle, startRegister, values.length / 4, 0),
            blobs: [{ offsetField: 12, data }] };
    };

    const command = (opcode, payload, blobs = []) =>
        ({ opcode, payload, blobs });
    const batch = commands => {
        let commandBytes = 0;
        for (const item of commands) {
            item.offset = 32 + commandBytes;
            item.size = (16 + item.payload.byteLength + item.blobs.reduce(
                (total, blob) => total + blob.data.byteLength, 0) + 7) & ~7;
            commandBytes += item.size;
        }
        const bytes = new Uint8Array(32 + commandBytes);
        const view = new DataView(bytes.buffer);
        view.setUint32(0, 0x47573944, true); // D9WG_MAGIC ("D9WG")
        view.setUint16(4, 1, true); // version_major
        view.setUint16(6, 3, true); // version_minor
        view.setUint32(8, 1, true); // frame_id
        view.setUint32(12, 1, true); // flags: D9WG_BATCH_FLAG_PRESENT
        view.setUint32(16, commands.length, true);
        view.setUint32(20, commandBytes, true);
        view.setUint32(24, sessionLow, true);
        view.setUint32(28, sessionHigh, true);
        commands.forEach((item, index) => {
            view.setUint16(item.offset, item.opcode, true);
            view.setUint32(item.offset + 4, item.size, true);
            view.setUint32(item.offset + 8, index + 1, true);
            bytes.set(item.payload, item.offset + 16);
            let blobOffset = item.offset + 16 + item.payload.byteLength;
            for (const blob of item.blobs) {
                view.setUint32(item.offset + 16 + blob.offsetField,
                    blobOffset, true);
                bytes.set(blob.data, blobOffset);
                blobOffset += blob.data.byteLength;
            }
        });
        return bytes;
    };

    try {
        if (!navigator.gpu) throw new Error("WebGPU unavailable");
        const deviceHandle = 0x100002;
        const textureHandle = 0x100003;

        const texture = new Uint8Array(16 * 16 * 4);
        for (let y = 0; y < 16; y++) {
            for (let x = 0; x < 16; x++) {
                const offset = (y * 16 + x) * 4;
                // A8R8G8B8, little-endian DWORD: bytes are B,G,R,A.
                texture[offset] = 255 - x * 8;      // B
                texture[offset + 1] = y * 16;       // G
                texture[offset + 2] = x * 16;       // R
                texture[offset + 3] = x < 2 || y < 2 ? 0 : 220; // A
            }
        }

        // Draw 1: screen-space textured triangle. POSITIONT(float4) +
        // COLOR(D3DCOLOR) + TEXCOORD0(float2), stride 28.
        const screenElements = [
            element(0, DECLTYPE_FLOAT4, DECLUSAGE_POSITIONT),
            element(16, DECLTYPE_D3DCOLOR, DECLUSAGE_COLOR),
            element(20, DECLTYPE_FLOAT2, DECLUSAGE_TEXCOORD),
        ];
        const screenVertices = new Uint8Array(3 * 28);
        const screenView = new DataView(screenVertices.buffer);
        [[80, 60, 0, 0], [560, 60, 1, 0], [320, 420, 0.5, 1]]
            .forEach((vertex, index) => {
                const offset = index * 28;
                screenView.setFloat32(offset, vertex[0], true);      // x
                screenView.setFloat32(offset + 4, vertex[1], true);  // y
                screenView.setFloat32(offset + 8, 0.5, true);        // z
                screenView.setFloat32(offset + 12, 1, true);         // rhw
                screenView.setUint32(offset + 16, 0xFFFFFFFF, true); // color
                screenView.setFloat32(offset + 20, vertex[2], true); // u
                screenView.setFloat32(offset + 24, vertex[3], true); // v
            });

        // Draw 2: world-space colored triangle, no texture. POSITION(float3)
        // + COLOR(D3DCOLOR), stride 16, transformed by identity WORLD/VIEW/
        // PROJECTION -- exercises the non-pretransformed path.
        const worldElements = [
            element(0, DECLTYPE_FLOAT3, DECLUSAGE_POSITION),
            element(12, DECLTYPE_D3DCOLOR, DECLUSAGE_COLOR),
        ];
        const worldVertices = new Uint8Array(3 * 16);
        const worldView = new DataView(worldVertices.buffer);
        [[-0.75, 0.7, 0.4], [0.75, 0.7, 0.4], [0, -0.7, 0.4]]
            .forEach((vertex, index) => {
                const offset = index * 16;
                worldView.setFloat32(offset, vertex[0], true);
                worldView.setFloat32(offset + 4, vertex[1], true);
                worldView.setFloat32(offset + 8, vertex[2], true);
                worldView.setUint32(offset + 12, 0xFF20C0FF, true);
            });
        // Draw 6 (M6): a POSITIONT point sprite carrying a per-vertex PSIZE.
        // The executor expands this one D3D point into a six-vertex instanced
        // quad because WebGPU has no programmable point-size primitive.
        const pointElements = [
            element(0, DECLTYPE_FLOAT4, DECLUSAGE_POSITIONT),
            element(16, DECLTYPE_FLOAT1, DECLUSAGE_PSIZE),
            element(20, DECLTYPE_D3DCOLOR, DECLUSAGE_COLOR),
            element(24, DECLTYPE_FLOAT2, DECLUSAGE_TEXCOORD),
        ];
        const pointVertex = new Uint8Array(32);
        const pointView = new DataView(pointVertex.buffer);
        pointView.setFloat32(0, 500, true);
        pointView.setFloat32(4, 350, true);
        pointView.setFloat32(8, 0.25, true);
        pointView.setFloat32(12, 1, true);
        pointView.setFloat32(16, 72, true);
        pointView.setUint32(20, 0xFFFFFFFF, true);
        pointView.setFloat32(24, 0, true);
        pointView.setFloat32(28, 0, true);
        const identity = [
            1, 0, 0, 0, 0, 1, 0, 0,
            0, 0, 1, 0, 0, 0, 0, 1,
        ];

        // Draw 3 (M2): the same geometry through a real vs_2_0/ps_2_0 pair.
        // The bytecode is the one glbridge/sample/d3d9_shader_test.c ships to
        // the XP guest, so this validates against real WebGPU exactly what
        // that test validates against the real guest DLL. Token encoding is
        // documented in that file.
        const vertexShaderTokens = new Uint32Array([
            0xFFFE0200,
            0x0200001F, 0x80000000, 0x900F0000,             // dcl_position v0
            0x0200001F, 0x8000000A, 0x900F0001,             // dcl_color0 v1
            0x0200001F, 0x80000005, 0x900F0002,             // dcl_texcoord0 v2
            0x03000014, 0xC00F0000, 0x90E40000, 0xA0E40000, // m4x4 oPos, v0, c0
            0x03000005, 0xD00F0000, 0x90E40001, 0xA0E40004, // mul oD0, v1, c4
            0x02000001, 0xE00F0000, 0x90E40002,             // mov oT0, v2
            0x0000FFFF,
        ]);
        const pixelShaderTokens = new Uint32Array([
            0xFFFF0200,
            0x0200001F, 0x90000000, 0xA00F0800,             // dcl_2d s0
            0x0200001F, 0x80000005, 0xB0030000,             // dcl t0.xy
            0x0200001F, 0x8000000A, 0x900F0000,             // dcl_color0 v0
            0x05000051, 0xA00F0001,                         // def c1, ...
                0x3DCCCCCD, 0x3DCCCCCD, 0x3DCCCCCD, 0x00000000,
            0x03000042, 0x800F0000, 0xB0E40000, 0xA0E40800, // texld r0, t0, s0
            0x03000005, 0x800F0000, 0x80E40000, 0x90E40000, // mul r0, r0, v0
            0x04000004, 0x800F0800, 0x80E40000, 0xA0E40000, 0xA0E40001,
            0x0000FFFF,
        ]);
        const vertexShaderHandle = 0x40000001;
        const pixelShaderHandle = 0x40000003;
        // POSITION(float3) + COLOR(UBYTE4) + TEXCOORD0(float2), stride 24 --
        // the three semantics the vertex shader dcl's, in a different element
        // order than the fixed-function stage would assume. UBYTE4 is an M5
        // compact declaration type: WebGPU delivers vec4<u32>, while D3D9
        // promises unnormalised float components to the shader.
        const shaderElements = [
            element(0, DECLTYPE_FLOAT3, DECLUSAGE_POSITION),
            element(12, DECLTYPE_UBYTE4, DECLUSAGE_COLOR),
            element(16, DECLTYPE_FLOAT2, DECLUSAGE_TEXCOORD),
        ];
        const shaderVertices = new Uint8Array(3 * 24);
        const shaderVertexView = new DataView(shaderVertices.buffer);
        [[-0.6, -0.2, 0, 1], [-0.1, -0.2, 1, 1], [-0.35, -0.9, 0.5, 0]]
            .forEach((vertex, index) => {
                const offset = index * 24;
                shaderVertexView.setFloat32(offset, vertex[0], true);
                shaderVertexView.setFloat32(offset + 4, vertex[1], true);
                shaderVertexView.setFloat32(offset + 8, 0.4, true);
                shaderVertexView.setUint32(offset + 12, 0xFFFFFFFF, true);
                shaderVertexView.setFloat32(offset + 16, vertex[2], true);
                shaderVertexView.setFloat32(offset + 20, vertex[3], true);
            });
        // c0-c3 transposed for m4x4's four dot products (scale 0.8, shift x).
        const shaderTransform = [
            0.8, 0, 0, 0.1,
            0, 0.8, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1,
        ];
        const vertexShaderCreate = createShader(deviceHandle,
            vertexShaderHandle, vertexShaderTokens);
        const pixelShaderCreate = createShader(deviceHandle,
            pixelShaderHandle, pixelShaderTokens);
        const vertexTransformConstants = shaderConstants(deviceHandle, 0,
            shaderTransform);
        const vertexTintConstants = shaderConstants(deviceHandle, 4,
            [1, 0.9, 0.8, 1]);
        const pixelScaleConstants = shaderConstants(deviceHandle, 0,
            [0.9, 0.9, 0.9, 1]);

        // --- M3 fixtures ---
        const renderTargetHandle = 0x00200011;
        const cubeHandle = 0x00200012;
        const cubeFace = new Uint8Array(8 * 8 * 4);
        for (let index = 0; index < 8 * 8; ++index) {
            cubeFace[index * 4] = 40;
            cubeFace[index * 4 + 1] = 90;
            cubeFace[index * 4 + 2] = 140;
            cubeFace[index * 4 + 3] = 255;
        }
        const material = handle => {
            const payload = new Uint8Array(72);
            const view = new DataView(payload.buffer);
            view.setUint32(0, handle, true);
            [0.9, 0.8, 0.7, 1,   // diffuse
             1, 1, 1, 1,         // ambient
             0.5, 0.5, 0.5, 1,   // specular
             0, 0, 0, 0,         // emissive
            ].forEach((value, index) =>
                view.setFloat32(4 + index * 4, value, true));
            view.setFloat32(68, 24, true); // power
            return payload;
        };
        const light = (handle, index, type) => {
            const payload = new Uint8Array(112);
            const view = new DataView(payload.buffer);
            view.setUint32(0, handle, true);
            view.setUint32(4, index, true);
            view.setUint32(8, type, true);
            [1, 1, 0.95, 1,  // diffuse
             1, 1, 1, 1,     // specular
             0.1, 0.1, 0.1, 1, // ambient
            ].forEach((value, i) => view.setFloat32(12 + i * 4, value, true));
            [0, 0, 0].forEach((value, i) =>
                view.setFloat32(60 + i * 4, value, true));   // position
            [0.3, -0.6, 0.7].forEach((value, i) =>
                view.setFloat32(72 + i * 4, value, true));   // direction
            view.setFloat32(84, 1000, true);  // range
            view.setFloat32(88, 1, true);     // falloff
            [1, 0, 0].forEach((value, i) =>
                view.setFloat32(92 + i * 4, value, true));   // attenuation
            view.setFloat32(104, 0.5, true);  // theta
            view.setFloat32(108, 1.0, true);  // phi
            return payload;
        };
        // POSITION(float3) NORMAL(float3) TEXCOORD0(float2), stride 32.
        const litElements = [
            element(0, DECLTYPE_FLOAT3, DECLUSAGE_POSITION),
            element(12, DECLTYPE_FLOAT3, 3 /* DECLUSAGE_NORMAL */),
            element(24, DECLTYPE_FLOAT2, DECLUSAGE_TEXCOORD),
        ];
        const litVertices = new Uint8Array(3 * 32);
        {
            const view = new DataView(litVertices.buffer);
            [[-0.8, -0.8, 0, 0], [0.8, -0.8, 1, 0], [0, 0.8, 0.5, 1]]
                .forEach((vertex, index) => {
                    const offset = index * 32;
                    view.setFloat32(offset, vertex[0], true);
                    view.setFloat32(offset + 4, vertex[1], true);
                    view.setFloat32(offset + 8, 0.5, true);
                    view.setFloat32(offset + 12, 0, true);
                    view.setFloat32(offset + 16, 0, true);
                    view.setFloat32(offset + 20, -1, true);
                    view.setFloat32(offset + 24, vertex[2], true);
                    view.setFloat32(offset + 28, vertex[3], true);
                });
        }
        // A screen-space quad (XYZRHW + colour + uv, stride 28) in the
        // bottom-right corner, textured with the render target.
        const rtQuadVertices = new Uint8Array(3 * 28);
        {
            const view = new DataView(rtQuadVertices.buffer);
            [[400, 300, 0, 0], [620, 300, 1, 0], [510, 460, 0.5, 1]]
                .forEach((vertex, index) => {
                    const offset = index * 28;
                    view.setFloat32(offset, vertex[0], true);
                    view.setFloat32(offset + 4, vertex[1], true);
                    view.setFloat32(offset + 8, 0.2, true);
                    view.setFloat32(offset + 12, 1, true);
                    view.setUint32(offset + 16, 0xFFFFFFFF, true);
                    view.setFloat32(offset + 20, vertex[2], true);
                    view.setFloat32(offset + 24, vertex[3], true);
                });
        }

        // One 4x4 DXT1 block (8 bytes): two RGB565 endpoints plus a 2-bit
        // index per texel. This is the format a D3D9 game of this era keeps
        // nearly all of its art in, and it only works if the device asked for
        // `texture-compression-bc` at creation -- a fake device cannot prove
        // that, only a real one can.
        const dxtHandle = 0x00200013;
        const dxtBlock = new Uint8Array([
            0x1F, 0x00,   // colour0 = RGB565 pure blue
            0xE0, 0x07,   // colour1 = RGB565 pure green
            0x55, 0x55, 0x55, 0x55, // every texel picks index 1
        ]);

        const stretchRect = (handle, sourceHandle, sourceLevel,
                sourceLeft, sourceTop, sourceRight, sourceBottom,
                destinationHandle, destinationLevel,
                destinationLeft, destinationTop, destinationRight,
                destinationBottom) => {
            const payload = new Uint8Array(56);
            const view = new DataView(payload.buffer);
            view.setUint32(0, handle, true);
            view.setUint32(4, sourceHandle, true);
            view.setUint32(8, sourceLevel, true);
            [sourceLeft, sourceTop, sourceRight, sourceBottom]
                .forEach((value, index) =>
                    view.setInt32(12 + index * 4, value, true));
            view.setUint32(28, destinationHandle, true);
            view.setUint32(32, destinationLevel, true);
            [destinationLeft, destinationTop, destinationRight,
             destinationBottom].forEach((value, index) =>
                view.setInt32(36 + index * 4, value, true));
            view.setUint32(52, 0, true); // linear
            return payload;
        };

        const executor = new D3D9WebGPUExecutor(
            document.getElementById("screen"));
        await Promise.race([
            executor.initialize(),
            new Promise((unused, reject) => setTimeout(() =>
                reject(new Error("WebGPU initialization timed out")), 20000)),
        ]);
        // Diagnostic previews must never gate the real texture upload. Zeroing
        // the budget exercises the War3 battle regression where menu atlases
        // consumed the budget and later fog/UI/cursor uploads were returned
        // from before queue.writeTexture.
        executor.previewBudget = 0;
        executor.device.pushErrorScope("validation");
        await executor.submit(batch([
            command(1, u32(32, 0, sessionLow, sessionHigh)),
            command(2, createDevice(deviceHandle, 640, 480)),
            command(0x110, u32(deviceHandle, textureHandle, 16, 16, 1, 21, 0, 1)),
            command(0x110, u32(deviceHandle, dxtHandle, 4, 4, 1,
                0x31545844 /* D3DFMT_DXT1 */, 0, 1)),
            command(0x113, u32(dxtHandle, 0, 0, 0, 0, 4, 4, 1, 8, 0,
                dxtBlock.byteLength, 0), [{ offsetField: 44, data: dxtBlock }]),
            command(0x113, u32(textureHandle, 0, 0, 0, 0, 16, 16, 1,
                64, 0, texture.byteLength, 0),
                [{ offsetField: 44, data: texture }]),
            command(0x204, u32(deviceHandle, 0, 0, 640, 480, 0, 0x3F800000, 0)),
            // M4 partial depth+stencil Clear validates frag_depth and stencil
            // replacement in the dynamically generated utility pipeline.
            command(5, concatBytes([
                u32(deviceHandle, 6, 0, 0x3F000000, 0x5A, 1),
                u32(0, 0, 32, 32),
            ])),
            command(5, u32(deviceHandle, 7, 0xFF101820, 0x3F800000, 0, 0)),
            command(6, u32(deviceHandle, 0)),
            command(0x20E, setFVF(deviceHandle, 0x144, screenElements)),
            command(0x203, u32(deviceHandle, 0, textureHandle, 0)),
            command(0x302, u32(deviceHandle, 4, 1, 28, 3,
                screenVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: screenVertices }]),
            // The first draw's bind group has captured the original texture
            // view. Updating it now must rename the texture so that draw keeps
            // the old pixels and later draws see these new ones.
            command(0x113, u32(textureHandle, 0, 0, 0, 0, 16, 16, 1,
                64, 0, texture.byteLength, 0),
                [{ offsetField: 44, data: texture }]),
            command(0x206, transform(deviceHandle, 2, identity)),
            command(0x206, transform(deviceHandle, 3, identity)),
            command(0x206, transform(deviceHandle, 256, identity)),
            command(0x20E, setFVF(deviceHandle, 0x42, worldElements)),
            command(0x203, u32(deviceHandle, 0, dxtHandle, 0)),
            command(0x302, u32(deviceHandle, 4, 1, 16, 3,
                worldVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: worldVertices }]),

            // Draw 3: programmable vs_2_0 + ps_2_0, sampling the same texture
            // through independent sampler state (CLAMP + LINEAR rather than
            // D3D9's WRAP/POINT defaults, so a dropped SetSamplerState is
            // visible in the sampler descriptor the cache builds).
            command(0x121, vertexShaderCreate.payload, vertexShaderCreate.blobs),
            command(0x122, pixelShaderCreate.payload, pixelShaderCreate.blobs),
            command(0x211, u32(deviceHandle, vertexShaderHandle)),
            command(0x212, u32(deviceHandle, pixelShaderHandle)),
            command(0x213, vertexTransformConstants.payload,
                vertexTransformConstants.blobs),
            command(0x213, vertexTintConstants.payload,
                vertexTintConstants.blobs),
            command(0x216, pixelScaleConstants.payload,
                pixelScaleConstants.blobs),
            command(0x201, u32(deviceHandle, 0, 5, 2)),  // MAGFILTER=LINEAR
            command(0x201, u32(deviceHandle, 0, 6, 2)),  // MINFILTER=LINEAR
            command(0x201, u32(deviceHandle, 0, 1, 3)),  // ADDRESSU=CLAMP
            command(0x201, u32(deviceHandle, 0, 2, 3)),  // ADDRESSV=CLAMP
            command(0x203, u32(deviceHandle, 0, textureHandle, 0)),
            command(0x20E, setFVF(deviceHandle, 0x142, shaderElements)),
            command(0x302, u32(deviceHandle, 4, 1, 24, 3,
                shaderVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: shaderVertices }]),
            // Unbinding both shaders must return to the fixed-function path
            // inside the same frame.
            command(0x211, u32(deviceHandle, 0)),
            command(0x212, u32(deviceHandle, 0)),

            // Draw 4 (M3): fixed-function lighting plus a two-stage texture
            // cascade, rendered into a texture rather than the back buffer, then
            // sampled back. This is the combination the M3 work added, and Tint
            // is the compiler that matters for it: naga accepts things Tint
            // rejects (the f32-max literal in M2 was exactly that), so the
            // generated lighting and cascade WGSL has to be seen by a real
            // browser and not only by naga.
            command(0x110, u32(deviceHandle, renderTargetHandle, 128, 128, 1, 21,
                1 /* D3DUSAGE_RENDERTARGET */, 0)),
            // M4: both utility pipelines are generated dynamically, so they
            // need real Tint/WebGPU validation in addition to fake-device
            // unit tests. First fill a sub-rectangle, then clear another one.
            command(9, u32(deviceHandle, renderTargetHandle, 0, 0xFF305070,
                8, 8, 120, 120)),
            command(0x111, u32(deviceHandle, cubeHandle, 8, 1, 21, 0, 1, 0)),
            // All six faces: an unwritten face has undefined contents, and the
            // executor counts that (drawsWithIncompleteMipChain) rather than
            // letting a reflection sample garbage unremarked.
            ...[0, 1, 2, 3, 4, 5].map(face =>
                command(0x113, u32(cubeHandle, 0, 0, 0, face, 8, 8, 1, 32, 0,
                    cubeFace.byteLength, 0),
                    [{ offsetField: 44, data: cubeFace }])),
            command(0x20F, u32(deviceHandle, 0, renderTargetHandle, 0)),
            command(0x21E, u32(deviceHandle, 0, 0, 0, 0)), // no depth
            command(0x204, u32(deviceHandle, 0, 0, 128, 128, 0, 0x3F800000, 0)),
            command(5, concatBytes([
                u32(deviceHandle, 1, 0xFF203040, 0x3F800000, 0, 1),
                u32(16, 16, 112, 112),
            ])),
            command(5, u32(deviceHandle, 1, 0xFF203040, 0x3F800000, 0, 0)),
            command(0x200, u32(deviceHandle, 137, 1, 0)),   // LIGHTING
            command(0x200, u32(deviceHandle, 139, 0x00303030, 0)), // AMBIENT
            command(0x200, u32(deviceHandle, 143, 1, 0)),   // NORMALIZENORMALS
            command(0x200, u32(deviceHandle, 29, 1, 0)),    // SPECULARENABLE
            command(0x207, material(deviceHandle)),
            command(0x208, light(deviceHandle, 0, 3 /* DIRECTIONAL */)),
            command(0x209, u32(deviceHandle, 0, 1, 0)),
            command(0x203, u32(deviceHandle, 0, textureHandle, 0)),
            command(0x203, u32(deviceHandle, 1, cubeHandle, 0)),
            command(0x202, u32(deviceHandle, 0, 1, 4)),     // stage0 COLOROP=MODULATE
            command(0x202, u32(deviceHandle, 0, 2, 2)),     // COLORARG1=TEXTURE
            command(0x202, u32(deviceHandle, 0, 3, 0)),     // COLORARG2=DIFFUSE
            command(0x202, u32(deviceHandle, 1, 1, 7)),     // stage1 COLOROP=ADD
            command(0x202, u32(deviceHandle, 1, 2, 2)),     // COLORARG1=TEXTURE
            command(0x202, u32(deviceHandle, 1, 3, 1)),     // COLORARG2=CURRENT
            command(0x202, u32(deviceHandle, 1, 11, 0x00030000)), // TCI reflection
            command(0x20E, setFVF(deviceHandle, 0x112, litElements)),
            command(0x302, u32(deviceHandle, 4, 1, 32, 3,
                litVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: litVertices }]),
            // Back to the back buffer, restoring the implicit depth surface, and
            // sample the render target through the fixed-function path.
            command(0x202, u32(deviceHandle, 1, 1, 1)),     // stage1 COLOROP=DISABLE
            command(0x202, u32(deviceHandle, 0, 3, 0)),
            command(0x200, u32(deviceHandle, 137, 0, 0)),   // LIGHTING off
            command(0x200, u32(deviceHandle, 29, 0, 0)),    // SPECULARENABLE off
            command(0x20F, u32(deviceHandle, 0, 0, 0)),
            command(0x21E, u32(deviceHandle, 0xFFFFFFFF, 0, 640, 480)),
            command(0x204, u32(deviceHandle, 0, 0, 640, 480, 0, 0x3F800000, 0)),
            command(0x203, u32(deviceHandle, 0, renderTargetHandle, 0)),
            command(0x203, u32(deviceHandle, 1, 0, 0)),
            command(0x20E, setFVF(deviceHandle, 0x144, screenElements)),
            // Warcraft III uses projected mask textures for shadows/fog. A
            // WebGPU sampler cannot express D3DTADDRESS_BORDER, so this forces
            // the fixed-function fragment variant which replaces out-of-range
            // coordinates with D3DSAMP_BORDERCOLOR; real Tint validates it.
            command(0x201, u32(deviceHandle, 0, 1, 4)),  // ADDRESSU=BORDER
            command(0x201, u32(deviceHandle, 0, 2, 4)),  // ADDRESSV=BORDER
            command(0x201, u32(deviceHandle, 0, 4, 0x00000000)),
            // M5: the final back-buffer draw uses an sRGB attachment view, so
            // Tint validates the -srgb pipeline/view pairing on a real canvas.
            command(0x200, u32(deviceHandle, 194, 1, 0)),
            command(0x302, u32(deviceHandle, 4, 1, 28, 3,
                rtQuadVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: rtQuadVertices }]),
            command(0x200, u32(deviceHandle, 194, 0, 0)),

            // M6 point-sprite validation on a real WebGPU pipeline. The
            // generated quad samples the complete texture via automatic
            // [0,1] point UVs rather than the source vertex's TEXCOORD0.
            command(0x200, u32(deviceHandle, 154, 0x42800000, 0)), // POINTSIZE=64
            command(0x200, u32(deviceHandle, 156, 1, 0)),          // POINTSPRITE
            command(0x200, u32(deviceHandle, 157, 0, 0)),          // no scaling
            command(0x203, u32(deviceHandle, 0, textureHandle, 0)),
            command(0x20E, setFVF(deviceHandle, 0x144, pointElements)),
            command(0x302, u32(deviceHandle, 1, 1, 32, 1,
                pointVertex.byteLength, 0, 0),
                [{ offsetField: 24, data: pointVertex }]),
            command(0x200, u32(deviceHandle, 156, 0, 0)),

            // StretchRect the back buffer into the render target and back out
            // again. Only a real browser exercises the interesting part: the
            // swap chain's format (getPreferredCanvasFormat, normally
            // bgra8unorm) differs from the rgba8unorm every D3D9 texture becomes,
            // so even a same-size back-buffer copy has to go through the blit
            // pipeline rather than copyTextureToTexture.
            command(0x8, stretchRect(deviceHandle, 0, 0, 0, 0, 640, 480,
                renderTargetHandle, 0, 0, 0, 128, 128)),
            command(0x8, stretchRect(deviceHandle, renderTargetHandle, 0,
                0, 0, 128, 128, 0, 0, 20, 20, 148, 148)),

            command(7, u32(deviceHandle, 0)),
            command(0x103, u32(textureHandle, 3)),
            command(0x103, u32(cubeHandle, 4)),
            command(0x103, u32(dxtHandle, 3)),
            command(4, surface(deviceHandle, 640, 480)),
        ]));
        // Make persistence deterministic for this page: production batches
        // debounce IndexedDB writes, while the headless screenshot runner may
        // freeze timers immediately after capturing the result.
        await executor.flushPersistentShaderCache();
        const validation = await executor.device.popErrorScope();
        if (executor.failed) throw executor.failed;
        if (validation) throw validation;
        const stats = executor.getStats();
        const expected = {
            drawCalls: 6, upDrawCalls: 6, presents: 1, pipelineCreations: 6,
            malformedBatches: 0, unsupportedCommands: 0, droppedDraws: 0,
            // Two shaders translated, plus one declaration-specific M5 variant
            // which widens the UBYTE4 COLOR0 input to D3D9's float vector.
            shadersTranslated: 2, shaderTranslationFailures: 0,
            pointSpriteDraws: 1, pointSpriteInstances: 1,
            shaderVariantsTranslated: 1, shaderCompileErrors: 0,
            programmableDraws: 1, drawsWithCompactVertexInputs: 1,
            // M3: the lit draw goes into a render target, then the target is
            // sampled back on the back buffer -- two targets, so at least two
            // passes, and the cube texture is sampled by the cascade.
            renderTargetsCreated: 1, renderTargetBinds: 2,
            cubeTexturesCreated: 1,
            // A refused texture would mean the device did not get the BC
            // feature; the DXT1 upload above is the only way to notice.
            texturesRejected: 0,
            textureUploads: 9, texturePreviewsSkipped: 3,
            textureUpdateHazards: 1, textureRenames: 1,
            textureFullCopyRenameBytes: 1024,
            // Both StretchRects touch the back buffer, so both must go through
            // the deferred blit rather than being skipped.
            blits: 2, blitsSkipped: 0, blitsThroughBackBuffer: 2,
            colorFills: 1, partialClears: 2, srgbWriteRequests: 1,
            srgbWriteUnavailable: 0,
            drawsWithUnsupportedTextureOp: 0,
            depthTargetSizeMismatches: 0,
            drawsWithIncompleteMipChain: 0,
            // Exactly one: D3DRS_LIGHTING defaults to TRUE, so draw 2 (XYZ plus
            // a diffuse colour, no NORMAL) is the one draw here that asks to be
            // lit without the data to light it. Draw 1 and draw 5 are XYZRHW and
            // so pre-lit by definition, draw 3 is programmable, and draw 4 has a
            // real normal. Current lighting handles a missing normal as zero.
            drawsWithZeroNormalLighting: 1,
            drawsWithUnappliedLighting: 0,
            // Draws 1 and 2 sample with D3D9's default sampler state; draw 3
            // with the CLAMP/LINEAR one set above.
            samplersCreated: 3,
        };
        const mismatches = Object.keys(expected)
            .filter(key => stats[key] !== expected[key])
            .map(key => key + "=" + stats[key] + " (expected " + expected[key] + ")");
        if (mismatches.length)
            throw new Error("unexpected stats: " + mismatches.join(", ") +
                "\n" + JSON.stringify(stats, null, 2));

        // D3DSHADE_FLAT with a translated shader on either side (GTA San
        // Andreas: its vertex shaders with the fixed-function pixel stage).
        // The two stages have to declare the colour varyings alike, or
        // createRenderPipeline fails and the frame's command buffer with it.
        executor.device.pushErrorScope("validation");
        const drawShaded = () => command(0x302, u32(deviceHandle, 4, 1, 24, 3,
            shaderVertices.byteLength, 0, 0),
            [{ offsetField: 24, data: shaderVertices }]);
        await executor.submit(batch([
            command(6, u32(deviceHandle, 0)),
            command(0x200, u32(deviceHandle, 9, 1, 0)),  // SHADEMODE=FLAT
            command(0x20E, setFVF(deviceHandle, 0x142, shaderElements)),
            // vs + fixed-function ps
            command(0x211, u32(deviceHandle, vertexShaderHandle)),
            drawShaded(),
            // vs + ps
            command(0x212, u32(deviceHandle, pixelShaderHandle)),
            drawShaded(),
            // fixed-function vs + ps
            command(0x211, u32(deviceHandle, 0)),
            command(0x20E, setFVF(deviceHandle, 0x42, worldElements)),
            command(0x302, u32(deviceHandle, 4, 1, 16, 3,
                worldVertices.byteLength, 0, 0),
                [{ offsetField: 24, data: worldVertices }]),
            command(0x212, u32(deviceHandle, 0)),
            command(0x200, u32(deviceHandle, 9, 2, 0)),  // SHADEMODE=GOURAUD
            command(7, u32(deviceHandle, 0)),
            command(4, surface(deviceHandle, 640, 480)),
        ]));
        const flatValidation = await executor.device.popErrorScope();
        if (executor.failed) throw executor.failed;
        if (flatValidation)
            throw new Error("flat shading with a translated shader: " +
                flatValidation.message);
        const flatStats = executor.getStats();
        if (flatStats.drawCalls !== stats.drawCalls + 3 ||
                flatStats.droppedDraws !== stats.droppedDraws ||
                flatStats.shaderCompileErrors !== 0)
            throw new Error("flat-shaded draws: drawCalls " + stats.drawCalls +
                " -> " + flatStats.drawCalls + ", droppedDraws " +
                stats.droppedDraws + " -> " + flatStats.droppedDraws +
                ", shaderCompileErrors " + flatStats.shaderCompileErrors);
        result.textContent = "PASS\n" + JSON.stringify(stats, null, 2);
        result.dataset.status = "pass";
    } catch (error) {
        // A GPUValidationError has no stack and stringifies to
        // "[object GPUValidationError]", which hides the only useful part of
        // it; always surface .message first.
        result.textContent = "FAIL\n" +
            ((error && error.message) || "") + "\n" +
            ((error && error.stack) || String(error));
        result.dataset.status = "fail";
    }
})();
</script>
                                                                                                                     source/v64/tests/glbridge/d3d9_webgpu_executor_test.js                                              0000644 0000000 0000000 00001237274 00000000000 020254  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Executor-level tests for glbridge/d3d9-webgpu/d3d9_executor.js against a
// fake WebGPU device.
//
// These drive real D9WG batches (built byte-for-byte the way d3d9_proxy.c
// emits them) through the executor and assert on the WebGPU calls that come
// out: which shader modules, which pipeline topology, which bind group
// entries, and what actually lands in the shader constant buffer. The fake
// device reproduces the two validation rules that bite hardest in practice --
// a bind group must supply exactly the bindings its layout declares, and
// writeBuffer offsets/sizes must be multiples of 4 -- so a wiring mistake
// fails here rather than as a silent black screen inside v86.

"use strict";

const assert = require("node:assert/strict");
const { D3D9WebGPUExecutor, buildFixedFunctionPixelShader } =
    require("../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js");
const shaderPipeline = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_shader_pipeline.js");

const OP = {
    HELLO: 1, CREATE_DEVICE: 2, RESET: 3, PRESENT: 4, CLEAR: 5, COLOR_FILL: 9,
    BEGIN_SCENE: 6, END_SCENE: 7, GUEST_LOG: 11, READBACK_SURFACE: 12,
    CREATE_BUFFER: 0x100, UPDATE_BUFFER: 0x101, DESTROY_RESOURCE: 0x103,
    CREATE_TEXTURE_2D: 0x110, CREATE_TEXTURE_CUBE: 0x111,
    CREATE_TEXTURE_VOLUME: 0x112,
    UPDATE_TEXTURE: 0x113,
    CREATE_VERTEX_DECLARATION: 0x120,
    CREATE_VERTEX_SHADER: 0x121, CREATE_PIXEL_SHADER: 0x122,
    CREATE_QUERY: 0x123,
    SET_RENDER_STATE: 0x200, SET_SAMPLER_STATE: 0x201,
    SET_TEXTURE: 0x203, SET_VIEWPORT: 0x204, SET_TRANSFORM: 0x206,
    SET_MATERIAL: 0x207, SET_LIGHT: 0x208, LIGHT_ENABLE: 0x209,
    SET_STREAM_SOURCE: 0x20A, SET_STREAM_SOURCE_FREQ: 0x20B,
    SET_INDICES: 0x20C,
    SET_VERTEX_DECLARATION: 0x20D, SET_FVF: 0x20E,
    SET_RENDER_TARGET: 0x20F, SET_DEPTH_STENCIL_SURFACE_LEVEL: 0x21E,
    SET_VERTEX_SHADER: 0x211, SET_PIXEL_SHADER: 0x212,
    SET_VS_CONST_F: 0x213, SET_VS_CONST_I: 0x214, SET_VS_CONST_B: 0x215,
    SET_PS_CONST_F: 0x216, SET_PS_CONST_I: 0x217, SET_PS_CONST_B: 0x218,
    SET_CLIP_PLANE: 0x219, SET_PALETTE: 0x21F, SET_CURRENT_PALETTE: 0x220,
    GENERATE_MIPS: 0x221,
    DRAW_PRIMITIVE: 0x300, DRAW_INDEXED_PRIMITIVE: 0x301,
    DRAW_PRIMITIVE_UP: 0x302, DRAW_INDEXED_PRIMITIVE_UP: 0x303,
    BEGIN_QUERY: 0x400, END_QUERY: 0x401,
};

const D9WG_MAGIC = 0x47573944;
const BATCH_FLAG_PRESENT = 1;
const DECLUSAGE = { POSITION: 0, BLENDWEIGHT: 1, BLENDINDICES: 2, NORMAL: 3,
    PSIZE: 4, TEXCOORD: 5, TANGENT: 6, BINORMAL: 7, POSITIONT: 9, COLOR: 10 };
const DECLTYPE = { FLOAT1: 0, FLOAT2: 1, FLOAT3: 2, FLOAT4: 3, D3DCOLOR: 4,
    UBYTE4: 5, SHORT2: 6, SHORT4: 7, UBYTE4N: 8, UDEC3: 13, DEC3N: 14 };
const DEVICE = 0x00100002;

// ---- D9WG batch builder ----
//
// `blob` is the trailing variable-length payload some commands carry (shader
// bytecode, vertex data, constant values); the builder patches the recorded
// offset once the command's position in the batch is known, exactly as
// reserve_command_locked() does on the guest.

function command(opcode, payload, blob, blobOffsetField) {
    return { opcode, payload, blob: blob || null, blobOffsetField };
}

function buildBatch(commands, options = {}) {
    let commandBytes = 0;
    for (const item of commands) {
        const raw = 16 + item.payload.length + (item.blob ? item.blob.length : 0);
        item.size = (raw + 7) & ~7;
        item.offset = 32 + commandBytes;
        commandBytes += item.size;
    }
    const batch = Buffer.alloc(32 + commandBytes);
    batch.writeUInt32LE(D9WG_MAGIC, 0);
    batch.writeUInt16LE(1, 4);
    batch.writeUInt16LE(options.versionMinor ?? 4, 6);
    batch.writeUInt32LE(options.frameId || 1, 8);
    batch.writeUInt32LE(options.present ? BATCH_FLAG_PRESENT : 0, 12);
    batch.writeUInt32LE(commands.length, 16);
    batch.writeUInt32LE(commandBytes, 20);
    batch.writeUInt32LE(options.sessionLow || 0, 24);
    batch.writeUInt32LE(options.sessionHigh || 0, 28);
    let sequence = 1;
    for (const item of commands) {
        batch.writeUInt16LE(item.opcode, item.offset);
        batch.writeUInt32LE(item.size, item.offset + 4);
        batch.writeUInt32LE(sequence++, item.offset + 8);
        if (item.blob) {
            const blobOffset = item.offset + 16 + item.payload.length;
            item.payload.writeUInt32LE(blobOffset, item.blobOffsetField);
            item.blob.copy(batch, blobOffset);
        }
        item.payload.copy(batch, item.offset + 16);
    }
    return batch;
}

function u32(...values) {
    const buffer = Buffer.alloc(values.length * 4);
    values.forEach((value, index) => buffer.writeUInt32LE(value >>> 0, index * 4));
    return buffer;
}

function createDevicePayload(width, height, autoDepth = 1) {
    const payload = Buffer.alloc(52);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(0x1234, 4);
    payload.writeUInt32LE(width, 16);
    payload.writeUInt32LE(height, 20);
    payload.writeUInt32LE(22, 24);
    payload.writeUInt32LE(1, 28);
    payload.writeUInt32LE(autoDepth, 36);
    payload.writeUInt32LE(0, 44); // D3DMULTISAMPLE_NONE
    payload.writeUInt32LE(0, 48); // multisample quality
    return payload;
}

function element(stream, offset, type, usage, usageIndex = 0) {
    const buffer = Buffer.alloc(8);
    buffer.writeUInt16LE(stream, 0);
    buffer.writeUInt16LE(offset, 2);
    buffer.writeUInt8(type, 4);
    buffer.writeUInt8(0, 5);
    buffer.writeUInt8(usage, 6);
    buffer.writeUInt8(usageIndex, 7);
    return buffer;
}

function declarationPayload(handle, elements) {
    return Buffer.concat([u32(DEVICE, handle, elements.length, 0), ...elements]);
}

function fvfPayload(fvf, elements) {
    return Buffer.concat([u32(DEVICE, fvf, elements.length, 0), ...elements]);
}

function createBufferPayload(handle, kind, byteCount, format = 0) {
    return u32(DEVICE, handle, kind, byteCount, 0, format, 0, 0);
}

function setStreamSourcePayload(stream, handle, stride, offsetInBytes = 0) {
    return u32(DEVICE, stream, handle, stride, offsetInBytes, 0);
}

function setStreamSourceFreqPayload(stream, divider) {
    return u32(DEVICE, stream, divider);
}

function drawPrimitivePayload(type, startVertex, primitiveCount) {
    return u32(DEVICE, type, startVertex, primitiveCount);
}

function drawIndexedPayload(type, baseVertex, startIndex, primitiveCount) {
    const payload = Buffer.alloc(28);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(type, 4);
    payload.writeInt32LE(baseVertex, 8);
    payload.writeUInt32LE(0, 12);
    payload.writeUInt32LE(0, 16);
    payload.writeUInt32LE(startIndex, 20);
    payload.writeUInt32LE(primitiveCount, 24);
    return payload;
}

function shaderCreatePayload(handle, tokens) {
    const payload = Buffer.alloc(24);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(handle, 4);
    payload.writeUInt32LE(tokens.length, 8);
    const hash = shaderPipeline.hashTokens(tokens);
    payload.writeUInt32LE(hash.low, 16);
    payload.writeUInt32LE(hash.high, 20);
    const blob = Buffer.alloc(tokens.length * 4);
    tokens.forEach((token, index) => blob.writeUInt32LE(token >>> 0, index * 4));
    return { payload, blob, blobOffsetField: 12 };
}

function constantPayload(startRegister, vectorCount, values, writer) {
    const payload = Buffer.alloc(16);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(startRegister, 4);
    payload.writeUInt32LE(vectorCount, 8);
    const stride = values.length / vectorCount;
    const blob = Buffer.alloc(values.length * 4);
    values.forEach((value, index) => writer(blob, value, index * 4));
    void stride;
    return { payload, blob, blobOffsetField: 12 };
}

const floatConstants = (start, values) => constantPayload(start, values.length / 4,
    values, (buffer, value, at) => buffer.writeFloatLE(value, at));
const intConstants = (start, values) => constantPayload(start, values.length / 4,
    values, (buffer, value, at) => buffer.writeInt32LE(value, at));
const boolConstants = (start, values) => constantPayload(start, values.length,
    values, (buffer, value, at) => buffer.writeUInt32LE(value, at));

// ---- shader bytecode fixtures ----

const VS = (major, minor) => (0xfffe0000 | (major << 8) | minor) >>> 0;
const PS = (major, minor) => (0xffff0000 | (major << 8) | minor) >>> 0;
const END = 0x0000ffff;
const REG = shaderPipeline.REGISTER;
const SIO = shaderPipeline.OP;
const regTypeBits = type => (((type & 0x7) << 28) | ((type & 0x18) << 8)) >>> 0;
const instr = (opcode, length = 0) =>
    ((opcode & 0xffff) | ((length & 0xf) << 24)) >>> 0;
const dst = (type, index, mask = 0xf) =>
    (0x80000000 | (index & 0x7ff) | regTypeBits(type) | (mask << 16)) >>> 0;
const src = (type, index) =>
    (0x80000000 | (index & 0x7ff) | regTypeBits(type) | (0xe4 << 16)) >>> 0;
const dcl = (usage, usageIndex = 0, textureType = 0) =>
    (0x80000000 | usage | (usageIndex << 16) | (textureType << 27)) >>> 0;

// vs_2_0: dcl_position v0 / dcl_color0 v1 / m4x4 oPos, v0, c0 / mov oD0, v1
const VS_BYTECODE = [
    VS(2, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.INPUT, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.COLOR, 0), dst(REG.INPUT, 1),
    instr(SIO.M4x4, 3), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
    instr(SIO.MOV, 2), dst(REG.ATTROUT, 0), src(REG.INPUT, 1),
    END,
];

// vs_2_0: dcl_position v0 / dcl_texcoord v5 / m4x4 oPos, v0, c0 /
// mov oT0, v5. This is the fixed-function-pixel-stage boundary GTA SA's
// character vertex shaders use: once a vertex shader is bound, stage 0 must
// consume oT0 even if stale fixed-function TEXCOORDINDEX state says otherwise.
const VS_TEXCOORD0_BYTECODE = [
    VS(2, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.INPUT, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.TEXCOORD), dst(REG.INPUT, 5),
    instr(SIO.M4x4, 3), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
    instr(SIO.MOV, 2), dst(REG.OUTPUT, 0), src(REG.INPUT, 5),
    END,
];

// M5 skeletal-layout fixture. The maths is intentionally small; the important
// contract here is that BLENDWEIGHT/BLENDINDICES and the compact auxiliary
// semantics all reach v# with D3D9 float4 values, ready for a real matrix
// palette shader to index the c# register file.
const VS_M5_SKINNING_INPUTS = [
    VS(2, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.INPUT, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.BLENDWEIGHT), dst(REG.INPUT, 1),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.BLENDINDICES), dst(REG.INPUT, 2),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.TEXCOORD), dst(REG.INPUT, 3),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.TANGENT), dst(REG.INPUT, 4),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.NORMAL), dst(REG.INPUT, 5),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.BINORMAL), dst(REG.INPUT, 6),
    instr(SIO.M4x4, 3), dst(REG.RASTOUT, 0), src(REG.INPUT, 0), src(REG.CONST, 0),
    instr(SIO.ADD, 3), dst(REG.ATTROUT, 0), src(REG.INPUT, 1), src(REG.INPUT, 2),
    END,
];

// ps_2_0: dcl_2d s0 / dcl t0 / texld r0, t0, s0 / mul oC0, r0, c1
const PS_BYTECODE = [
    PS(2, 0),
    instr(SIO.DCL, 2), dcl(0, 0, 2), dst(REG.SAMPLER, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
    instr(SIO.TEX, 3), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), src(REG.SAMPLER, 0),
    instr(SIO.MUL, 3), dst(REG.COLOROUT, 0), src(REG.TEMP, 0), src(REG.CONST, 1),
    END,
];

const PS_SAMPLER15_BYTECODE = [
    PS(2, 0),
    instr(SIO.DCL, 2), dcl(0, 0, 2), dst(REG.SAMPLER, 15),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.TEXCOORD, 0), dst(REG.TEXTURE, 0),
    instr(SIO.TEX, 3), dst(REG.TEMP, 0),
        src(REG.TEXTURE, 0), src(REG.SAMPLER, 15),
    instr(SIO.MOV, 2), dst(REG.COLOROUT, 0), src(REG.TEMP, 0),
    END,
];

// A shader the translator refuses. texbem and the texm3x* family used to sit
// here; they are translated now, so this reaches for one of the few ps_1_x
// instructions that still has no honest translation -- texdepth replaces the
// fragment's depth, which this pipeline has no frag_depth path for.
const PS_UNSUPPORTED = [
    PS(1, 4),
    instr(SIO.TEXDEPTH), dst(REG.TEMP, 0),
    END,
];

// vs_3_0: dcl_2d s0 / dcl_position v0 / dcl_position o0 /
// texldl r0, v0, s0 / mov o0, r0. Vertex texture samplers live in D3D9's
// 256..259 namespace and must not alias pixel sampler s0.
const VS3_VERTEX_TEXTURE_FETCH = [
    VS(3, 0),
    instr(SIO.DCL, 2), dcl(0, 0, 2), dst(REG.SAMPLER, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.INPUT, 0),
    instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.OUTPUT, 0),
    instr(SIO.TEXLDL, 3), dst(REG.TEMP, 0),
        src(REG.INPUT, 0), src(REG.SAMPLER, 0),
    instr(SIO.MOV, 2), dst(REG.OUTPUT, 0), src(REG.TEMP, 0),
    END,
];

// ---- fake WebGPU ----

function makeFakeWebGPU(options) {
    options = options || {};
    const calls = [];
    const submittedWorkResolvers = [];
    class FakeBuffer {
        constructor(descriptor) {
            this.descriptor = descriptor;
            this.size = descriptor.size;
            this.data = new Uint8Array(descriptor.size);
        }
        mapAsync() {
            // A lost or errored device accepts the submit and then never
            // signals; makeFakeWebGPU({ hangMapAsync: true }) reproduces it.
            if (options.hangMapAsync) return new Promise(() => {});
            return Promise.resolve();
        }
        getMappedRange() { return this.data.buffer; }
        unmap() { this.mapped = false; }
        destroy() { this.destroyed = true; }
    }
    class FakeTexture {
        constructor(descriptor) { this.descriptor = descriptor; }
        createView(descriptor) {
            const view = { texture: this, descriptor: descriptor || null };
            calls.push(["createView", this, descriptor || null, view]);
            return view;
        }
        destroy() { this.destroyed = true; }
    }
    class FakePass {
        constructor(descriptor) { this.descriptor = descriptor; this.ops = []; }
        setPipeline(p) { this.ops.push(["pipeline", p]); }
        setBindGroup(i, g, dynamicOffsets) {
            this.ops.push(["bindGroup", i, g, dynamicOffsets]);
            calls.push(["setBindGroup", i, g, dynamicOffsets]);
        }
        setViewport(...a) { this.ops.push(["viewport", ...a]); }
        setScissorRect(...a) {
            this.ops.push(["scissor", ...a]);
            calls.push(["setScissorRect", ...a]);
        }
        setBlendConstant(value) {
            this.ops.push(["blendConstant", value]);
            calls.push(["setBlendConstant", value]);
        }
        setStencilReference(value) {
            this.ops.push(["stencilReference", value]);
            calls.push(["setStencilReference", value]);
        }
        setVertexBuffer(slot, buffer, offset) {
            this.ops.push(["vertexBuffer", slot, buffer, offset]);
        }
        setIndexBuffer(buffer, format, offset) {
            this.ops.push(["indexBuffer", buffer, format, offset]);
        }
        draw(...a) { this.ops.push(["draw", ...a]); }
        drawIndexed(...a) { this.ops.push(["drawIndexed", ...a]); }
        beginOcclusionQuery(slot) {
            this.occlusionSlot = slot;
            this.ops.push(["beginOcclusionQuery", slot]);
        }
        endOcclusionQuery() {
            if (this.descriptor.occlusionQuerySet &&
                    this.occlusionSlot !== undefined)
                this.descriptor.occlusionQuerySet.values[this.occlusionSlot] = 37n;
            this.ops.push(["endOcclusionQuery"]);
            this.occlusionSlot = undefined;
        }
        end() { this.ended = true; }
    }
    class FakeEncoder {
        constructor() { this.passes = []; }
        beginRenderPass(descriptor) {
            const pass = new FakePass(descriptor);
            this.passes.push(pass);
            calls.push(["beginRenderPass", descriptor, pass]);
            return pass;
        }
        copyTextureToTexture(...args) {
            calls.push(["copyTextureToTexture", ...args]);
        }
        copyTextureToBuffer(source, destination, size) {
            const texture = source.texture;
            const input = texture.readbackData || new Uint8Array(0);
            const sourcePitch = texture.readbackPitch || size.width * 4;
            const originY = source.origin ? source.origin.y || 0 : 0;
            // For BC formats size.height is a texel extent rounded to four,
            // while rowsPerImage is the number of actual block rows in the
            // buffer. They are equal for ordinary textures.
            const copiedRows = destination.rowsPerImage || size.height;
            for (let row = 0; row < copiedRows; ++row) {
                const from = (originY + row) * sourcePitch;
                destination.buffer.data.set(input.subarray(from,
                    from + Math.min(sourcePitch, destination.bytesPerRow)),
                    row * destination.bytesPerRow);
            }
            calls.push(["copyTextureToBuffer", source, destination, size]);
        }
        writeTimestamp(querySet, slot) {
            querySet.values[slot] = 1000n + BigInt(slot);
        }
        resolveQuerySet(querySet, first, count, buffer, offset) {
            const out = new DataView(buffer.data.buffer);
            for (let i = 0; i < count; ++i)
                out.setBigUint64(offset + i * 8,
                    querySet.values[first + i] || 0n, true);
        }
        copyBufferToBuffer(source, sourceOffset, destination,
                destinationOffset, size) {
            destination.data.set(source.data.subarray(sourceOffset,
                sourceOffset + size), destinationOffset);
        }
        finish() { return { encoder: this }; }
    }
    const queue = {
        writeBuffer(buffer, offset, data, dataOffset, size) {
            const length = size !== undefined ? size
                : (data.byteLength !== undefined ? data.byteLength : data.length);
            assert.equal(offset % 4, 0, "writeBuffer destination offset must be 4-aligned");
            assert.equal(length % 4, 0, "writeBuffer size must be a multiple of 4");
            // WebGPU copies the source at call time. Snapshotting here rather
            // than holding the caller's view matters: the executor writes
            // straight out of a buffer's CPU shadow, which keeps mutating, so
            // a live reference would make every recorded write appear to
            // contain the frame's final contents.
            const view = ArrayBuffer.isView(data)
                ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
                : new Uint8Array(data);
            const start = ArrayBuffer.isView(data) ? (dataOffset || 0) * 1 : (dataOffset || 0);
            const snapshot = view.slice(start, start + length);
            calls.push(["writeBuffer", buffer, offset, data, dataOffset, size, snapshot]);
        },
        writeTexture(...a) { calls.push(["writeTexture", ...a]); },
        submit(buffers) { calls.push(["submit", buffers]); },
        onSubmittedWorkDone() {
            return new Promise(resolve => submittedWorkResolvers.push(resolve));
        },
    };
    const device = {
        queue,
        lost: new Promise(() => {}),
        // A real GPUDevice reports the features it was actually created with,
        // which is what the shared host reads to decide capability flags --
        // the adapter's list is only what *could* have been requested.
        features: new Set(["texture-compression-bc", "timestamp-query"]),
        createShaderModule(descriptor) {
            const module = { descriptor, code: descriptor.code,
                getCompilationInfo: async () => ({ messages: [] }) };
            calls.push(["createShaderModule", descriptor, module]);
            return module;
        },
        createBuffer(descriptor) {
            const buffer = new FakeBuffer(descriptor);
            calls.push(["createBuffer", descriptor, buffer]);
            return buffer;
        },
        createTexture(descriptor) {
            const texture = new FakeTexture(descriptor);
            calls.push(["createTexture", descriptor, texture]);
            return texture;
        },
        createSampler(descriptor) {
            const sampler = { descriptor };
            calls.push(["createSampler", descriptor, sampler]);
            return sampler;
        },
        createCommandEncoder() {
            const encoder = new FakeEncoder();
            calls.push(["createCommandEncoder", encoder]);
            return encoder;
        },
        createQuerySet(descriptor) {
            const querySet = { descriptor,
                values: new BigUint64Array(descriptor.count),
                destroy() { this.destroyed = true; } };
            calls.push(["createQuerySet", descriptor, querySet]);
            return querySet;
        },
        createBindGroupLayout(descriptor) {
            const layout = { descriptor,
                bindings: new Set(descriptor.entries.map(e => e.binding)) };
            calls.push(["createBindGroupLayout", descriptor, layout]);
            return layout;
        },
        createPipelineLayout(descriptor) {
            calls.push(["createPipelineLayout", descriptor]);
            return { descriptor };
        },
        createRenderPipeline(descriptor) {
            const pipeline = { descriptor };
            calls.push(["createRenderPipeline", descriptor, pipeline]);
            return pipeline;
        },
        createBindGroup(descriptor) {
            const declared = descriptor.layout.bindings;
            const supplied = new Set(descriptor.entries.map(e => e.binding));
            for (const binding of supplied)
                assert.ok(declared.has(binding),
                    "bind group supplies binding " + binding +
                    " which its layout does not declare");
            for (const binding of declared)
                assert.ok(supplied.has(binding),
                    "bind group layout declares binding " + binding +
                    " but the bind group does not supply it");
            calls.push(["createBindGroup", descriptor]);
            return descriptor;
        },
    };
    const context = {
        configure(descriptor) { calls.push(["configure", descriptor]); },
        getCurrentTexture() {
            const texture = { width: 640, height: 480,
                createView: () => ({ swapchain: true }) };
            calls.push(["getCurrentTexture", texture]);
            return texture;
        },
    };
    const gpu = {
        async requestAdapter() {
            return {
                // A real adapter advertises optional features here, and a device
                // gets none of them unless it names them in requiredFeatures.
                features: new Set(["texture-compression-bc", "timestamp-query"]),
                async requestDevice(descriptor) {
                    calls.push(["requestDevice", descriptor || null]);
                    return device;
                },
            };
        },
        getPreferredCanvasFormat() { return "bgra8unorm"; },
    };
    return { calls, device, context, gpu,
        completeSubmittedWork() {
            for (const resolve of submittedWorkResolvers.splice(0)) resolve();
        } };
}

function makeExecutor(options = {}) {
    const { fakeOptions, ...executorOptions } = options;
    const fake = makeFakeWebGPU(fakeOptions);
    const canvas = { width: 1, height: 1, getContext: () => fake.context };
    const executor = new D3D9WebGPUExecutor(canvas,
        { gpu: fake.gpu, ...executorOptions });
    return { fake, executor, calls: fake.calls,
        find: name => fake.calls.filter(call => call[0] === name),
        last: name => {
            const matches = fake.calls.filter(call => call[0] === name);
            return matches[matches.length - 1];
        } };
}

/*
 * Constants reach the GPU as one staged upload of the whole uniform ring per
 * submit -- the shape a real driver's pushbuffer uses -- rather than one
 * writeBuffer per draw. A block therefore lives inside that upload, at the
 * dynamic offset the draw actually bound it at, so a test reads it through
 * here instead of treating the write's payload as the block itself.
 */
function constantBlock(find, buffer) {
    const write = find("writeBuffer").filter(call => call[1] === buffer).pop();
    assert.ok(write, "the uniform ring was never uploaded");
    const bind = find("setBindGroup").pop();
    const offsets = bind && bind[3];
    const dynamic = offsets && offsets.length ? offsets[0] : 0;
    return { buffer: write[6].buffer,
        byteOffset: write[6].byteOffset + dynamic - write[2] };
}

// Absolute DMA offset of the liveness counter: the response region base
// plus D9WG_HEARTBEAT_OFFSET (its last 16 bytes).
const HEARTBEAT_WRITE_OFFSET = (16 * 1024 * 1024 - 4 * 1024 * 1024) +
    (4 * 1024 * 1024 - 16);

// ---- harness ----

const failures = [];
let passed = 0;

async function test(name, body) {
    try {
        await body();
        ++passed;
    } catch (error) {
        failures.push({ name, error });
    }
}

// ---- tests ----

async function main() {

await test("a frame past the flush threshold submits early and never touches the swap chain",
        async () => {
    // The batch-size test's shape: one PCI batch carrying far more draws than
    // a frame is supposed to hold. Before the flush existed they all stayed
    // live as JS ops and then went into a single command buffer.
    const THRESHOLD = 1024;                       // the option's floor
    const DRAWS = THRESHOLD + 200;
    const { executor, fake, find } = makeExecutor({ flushThreshold: THRESHOLD });
    const draws = [];
    for (let i = 0; i < DRAWS; ++i)
        draws.push(command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        ...draws,
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.frameFlushes, 1,
        "one flush for " + DRAWS + " draws at a threshold of " + THRESHOLD);
    assert.equal(executor.stats.queueSubmits, 2,
        "the flush submits, and Present submits the remainder");
    // The whole point of owning the back buffer: a partial frame reaches the
    // GPU without acquiring a canvas texture it would have to hold across
    // tasks. One acquisition, at Present.
    assert.equal(find("getCurrentTexture").length, 1);
    // The flush is invisible to the guest's image: the second segment loads
    // what the first one drew, because both target the same owned texture.
    const passes = find("beginRenderPass");
    assert.ok(passes.length >= 2);
    assert.ok(passes.slice(1).every(call =>
        call[1].colorAttachments.every(a => a.loadOp === "load")),
        "a flush must not clear what the previous segment drew");
    assert.equal(executor.stats.framesWithoutColorClear, 1,
        "a flush is a fragment, not a frame that failed to clear");
    assert.equal(executor.stats.framesWithNoOps, 0);
});

await test("a Present whose ops were all flushed away still reaches the canvas",
        async () => {
    // The flush makes this ordinary rather than exotic: the last flush can
    // land on the final draw, so Present arrives with an empty frame -- and a
    // canvas texture is new and undefined every frame, so "nothing to replay"
    // must not mean "nothing to show".
    const THRESHOLD = 1024;
    const { executor, fake, find } = makeExecutor({ flushThreshold: THRESHOLD });
    const draws = [];
    for (let i = 0; i < THRESHOLD; ++i)
        draws.push(command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        ...draws,
    ]));
    await executor.idle();
    assert.equal(executor.stats.frameFlushes, 1);
    assert.equal(executor.frame, null, "the flush consumed the whole frame");
    const backBuffer = executor.backBufferTexture;
    assert.ok(backBuffer);
    assert.equal(find("getCurrentTexture").length, 0,
        "a flush must never acquire the swap chain");

    // Present arrives in a later batch with nothing of its own to draw.
    await executor.submit(buildBatch([
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(find("getCurrentTexture").length, 1);
    const presented = find("copyTextureToTexture")
        .filter(call => call[1].texture === backBuffer);
    assert.equal(presented.length, 1,
        "the owned back buffer must still be copied to the canvas");
    assert.equal(executor.stats.backBufferPresents, 1);
});

await test("the host reports liveness once per batch so a backlog is not a timeout",
        async () => {
    /*
     * The fault this exists for: submission has no backpressure, so a host that
     * has fallen thousands of batches behind still answers a readback -- just
     * later than any wall-clock deadline the guest could pick. Without a
     * liveness signal the guest cannot tell that apart from a dead host, and it
     * reported "GetFrontBufferData failed" for a host that was working.
     */
    const beats = [];
    const { executor } = makeExecutor();
    const metadata = { writeGuestMemory(offset, data) {
        if (offset === HEARTBEAT_WRITE_OFFSET)
            beats.push(Buffer.from(data).readUInt32LE(0));
    } };
    for (let i = 0; i < 3; ++i) {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CLEAR, u32(DEVICE, 1, 0xff000000, 0x3f800000, 0, 0)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }), metadata);
        await executor.idle();
    }
    assert.equal(beats.length, 3, "one beat per finished batch");
    // Strictly increasing is what lets the guest reset its deadline on change
    // rather than on a value it has to interpret.
    assert.deepEqual(beats, [1, 2, 3]);

    // A batch with no writer must not throw or stall the counter.
    await executor.submit(buildBatch([
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(beats.length, 3, "no writer, no beat, no error");
});

await test("a readback whose map never completes fails instead of hanging the guest",
        async () => {
    // The guest spins on the response with interrupts of its own, so a map that
    // never resolves is not slow -- it freezes the VM until the guest's own cap
    // expires. Bounding it here turns a stall into a reported failure the guest
    // can raise as D3DERR_DRIVERINTERNALERROR straight away.
    const { executor } = makeExecutor(
        { readbackTimeoutMs: 30, fakeOptions: { hangMapAsync: true } });
    const writes = [];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff000000, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }));
    await executor.idle();

    await executor.submit(buildBatch([
        command(OP.READBACK_SURFACE,
            u32(DEVICE, 0, 0, 21, 640, 480, 0, 1, 640 * 4, 640 * 4,
                16 * 1024, 0x22334455)),
    ], { versionMinor: 3 }), { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } });
    await executor.idle();

    assert.equal(executor.stats.renderTargetReadbackFailures, 1,
        "the stalled map must be reported as a readback failure");
    assert.equal(writes.length, 1,
        "the guest must still get a response rather than spinning to its cap");
    // status is the 4th u32 of D9WGReadbackResponse; 2 is D9WG_RESPONSE_FAILED.
    assert.equal(writes[0].data.readUInt32LE(12), 2);
});

await test("constants go up as one staged upload per submit, not one per draw",
        async () => {
    // What a driver does with its pushbuffer: write constants into a mapped
    // ring with a plain CPU pointer and ring the doorbell once. A 3DMark06
    // batch-size run made 22 million per-draw writeBuffer calls carrying 6.8 GB;
    // the bytes are unavoidable, the 22 million API calls were not.
    const DRAWS = 40;
    const { executor, find } = makeExecutor();
    const body = [];
    for (let i = 0; i < DRAWS; ++i) {
        // A constant change between every pair, so no two draws can share a
        // slot and the ring genuinely holds DRAWS distinct blocks.
        const c = floatConstants(0, [i, i + 1, i + 2, i + 3]);
        body.push(command(OP.SET_VS_CONST_F, c.payload, c.blob, c.blobOffsetField));
        body.push(command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)));
    }
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        ...body,
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    const ring = find("createBuffer").find(call =>
        /^D3D9 uniform ring \d+$/.test(String(call[1].label || "")))[2];
    const ringWrites = find("writeBuffer").filter(call => call[1] === ring);
    assert.equal(ringWrites.length, 1,
        DRAWS + " draws must produce one ring upload, not one each");
    assert.equal(executor.stats.uniformStagingUploads, 1);
    assert.equal(ringWrites[0][2], 0, "the staged upload starts at the ring base");
    // Every distinct block is still in it: DRAWS slots at 256-byte alignment.
    assert.ok(ringWrites[0][5] >= DRAWS * 256,
        "the upload must cover every slot the frame allocated");
});

await test("a run of draws with no state change between them shares one slot",
        async () => {
    // The driver answer to "did the constants change": nothing called
    // SetConstant, so nothing did. O(1), and it replaces hashing the assembled
    // block on every draw.
    const drawBatch = extra => {
        const body = [];
        for (let i = 0; i < 8; ++i) {
            if (extra) {
                const c = floatConstants(0, [i, i, i, i]);
                body.push(command(OP.SET_VS_CONST_F, c.payload, c.blob,
                    c.blobOffsetField));
            }
            body.push(command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)));
        }
        return buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
            command(OP.SET_FVF, fvfPayload(0x2,
                [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
            ...body,
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true });
    };

    const quiet = makeExecutor();
    await quiet.executor.submit(drawBatch(false));
    await quiet.executor.idle();
    assert.equal(quiet.executor.stats.uniformSlotReuses, 7,
        "seven draws after the first found the state unchanged");

    const busy = makeExecutor();
    await busy.executor.submit(drawBatch(true));
    await busy.executor.idle();
    assert.equal(busy.executor.stats.uniformSlotReuses, 0,
        "a SetVertexShaderConstantF between draws must invalidate the slot");
});

await test("identical consecutive draws issue one pass-state call, not nine",
        async () => {
    // The batch-size test's shape: many draws that differ only in their index
    // range. Pass state persists in WebGPU until it changes, so re-issuing it
    // per draw is pure JS->Dawn overhead -- and at this draw count it is the
    // dominant cost.
    const DRAWS = 24;
    const { executor, fake, find } = makeExecutor();
    const draws = [];
    for (let i = 0; i < DRAWS; ++i)
        draws.push(command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        ...draws,
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    const pass = find("beginRenderPass").pop()[2];
    const counted = kind => pass.ops.filter(op => op[0] === kind).length;
    assert.equal(counted("draw"), DRAWS, "every draw must still be issued");
    // Each of these is set once for the pass and then left alone.
    for (const kind of ["pipeline", "bindGroup", "blendConstant",
            "stencilReference", "viewport", "scissor", "vertexBuffer"])
        assert.equal(counted(kind), 1,
            kind + " should be set once per pass, not once per draw");
    assert.equal(executor.stats.redundantStateSkipped, (DRAWS - 1) * 7,
        "seven state calls skipped for each draw after the first");
});

await test("a new pass re-issues state that WebGPU forgot", async () => {
    // The skip is only sound because beginRenderPass resets all of it. A
    // target switch opens a new pass, and everything must be set again there
    // or the second pass draws with no pipeline bound at all.
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        // A Clear always starts a new pass (WebGPU spells a clear only as a
        // pass loadOp), so this is the cheapest way to force the boundary.
        command(OP.CLEAR, u32(DEVICE, 1, 0xff000000, 0x3f800000, 0, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    const passes = find("beginRenderPass").map(call => call[2])
        .filter(pass => pass.ops.some(op => op[0] === "draw"));
    assert.equal(passes.length, 2, "the Clear must have split the passes");
    for (const pass of passes)
        for (const kind of ["pipeline", "bindGroup", "viewport", "scissor",
                "vertexBuffer"])
            assert.equal(pass.ops.filter(op => op[0] === kind).length, 1,
                kind + " must be re-set in every pass that draws");
});

await test("uniform storage grows by pooled chunks, not one buffer per draw", async () => {
    // 3DMark06's batch-size test issues draw calls by the hundred thousand --
    // that is what it measures -- and each draw with distinct constants needs
    // its own uniform slot. One 16 MiB ring holds 65536 of them; past that the
    // old allocator handed out a fresh GPUBuffer per draw, each of which also
    // forced an uncacheable bind group, and the pair was held until Present.
    // That is what took the browser's GPU process down.
    const CHUNK = 64 * 1024;                     // the allocator's floor
    const SLOTS_PER_CHUNK = CHUNK / 256;         // UNIFORM_OFFSET_ALIGNMENT
    const { executor, fake } = makeExecutor(
        { uniformRingBytes: CHUNK, uniformRingChunks: 3 });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(64, 64)),
    ]));

    // "D3D9 uniform ring overflow" also starts with "D3D9 uniform ring ", so
    // the chunk label is matched exactly rather than by prefix.
    const ringBuffers = () => fake.calls.filter(call =>
        call[0] === "createBuffer" &&
        /^D3D9 uniform ring \d+$/.test(String(call[1].label || "")));
    const overflowBuffers = () => fake.calls.filter(call =>
        call[0] === "createBuffer" &&
        call[1].label === "D3D9 uniform ring overflow");

    // Exactly the pool's worth of slots: every one comes out of a chunk, and
    // the chunks are the only buffers allocated.
    const distinct = new Set();
    for (let i = 0; i < SLOTS_PER_CHUNK * 3; ++i) {
        const slot = executor.allocateUniformSlot(256);
        assert.equal(slot.transient, false, "slot " + i + " should be pooled");
        distinct.add(slot.buffer);
    }
    assert.equal(distinct.size, 3, "three chunks should have been used");
    assert.equal(ringBuffers().length, 3);
    assert.equal(overflowBuffers().length, 0,
        "nothing should overflow while the pool has room");

    // Past the pool the old per-draw path is still the fallback, but it is now
    // the documented last resort rather than the first thing a big frame hits.
    const beyond = executor.allocateUniformSlot(256);
    assert.equal(beyond.transient, true);
    assert.equal(overflowBuffers().length, 1);
    assert.equal(executor.stats.uniformRingOverflows, 1);

    // A new frame rewinds to chunk 0 and reuses the same buffers rather than
    // allocating more -- stable identity is what keeps bind groups cacheable.
    executor.frame = null;
    executor.ensureFrame();
    const rewound = executor.allocateUniformSlot(256);
    assert.equal(rewound.transient, false);
    assert.equal(rewound.offset, 0);
    assert.equal(rewound.buffer, [...distinct][0],
        "the frame should restart in the first pooled chunk");
    assert.equal(ringBuffers().length, 3, "no new chunk on the second frame");
});

await test("fixed-function FVF triangle still renders (M1 regression guard)", async () => {
    const { executor, fake, find } = makeExecutor();
    const vertices = Buffer.alloc(3 * 16);
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    const create = shaderCreatePayload; void create;
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, vertices.length)),
        command(OP.SET_FVF, fvfPayload(0x142, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawCalls, 1, "the draw was not recorded");
    assert.equal(executor.stats.droppedDraws, 0);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "triangle-list");
    assert.equal(pipeline.vertex.entryPoint, "d9_vs_main");
    assert.equal(pipeline.fragment.entryPoint, "d9_ps_main");
    // Position at location 0, diffuse at location 1, both from stream 0.
    assert.equal(pipeline.vertex.buffers.length, 1);
    assert.equal(pipeline.vertex.buffers[0].arrayStride, 16);
    assert.deepEqual(pipeline.vertex.buffers[0].attributes, [
        { shaderLocation: 0, offset: 0, format: "float32x3" },
        { shaderLocation: 1, offset: 12, format: "unorm8x4" },
    ]);
    const passes = fake.calls.filter(c => c[0] === "beginRenderPass");
    assert.equal(passes.length, 1);
    assert.deepEqual(passes[0][2].ops.filter(op => op[0] === "draw"), [["draw", 3]]);
});

await test("point sprites expand one source point into an instanced textured quad", async () => {
    const D3DRS_POINTSIZE = 154, D3DRS_POINTSPRITEENABLE = 156;
    const D3DRS_POINTSCALEENABLE = 157;
    const { executor, fake, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT1, DECLUSAGE.PSIZE),
        element(0, 16, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 20 * 8)),
        command(OP.SET_FVF, fvfPayload(0x142, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_POINTSIZE,
            0x41000000, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_POINTSPRITEENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_POINTSCALEENABLE, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(1, 0, 8)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.pointSpriteDraws, 1);
    assert.equal(executor.stats.pointSpriteInstances, 8);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "triangle-list");
    assert.equal(pipeline.primitive.cullMode, "none",
        "expanded points must not inherit triangle culling");
    assert.equal(pipeline.vertex.buffers[0].stepMode, "instance");
    assert.ok(pipeline.vertex.buffers[0].attributes.some(attribute =>
        attribute.shaderLocation === 12 && attribute.format === "float32"),
        "D3DDECLUSAGE_PSIZE must feed the point-size input");
    assert.ok(pipeline.vertex.module.code.includes("d9_point_uvs"));
    assert.ok(pipeline.vertex.module.code.includes("inverseSqrt(d9_point_denom)"),
        "D3DRS_POINTSCALEENABLE must apply A/B/C distance attenuation");
    assert.ok(pipeline.vertex.module.code.includes("result.varying2 = vec4<f32>(d9_point_uv"),
        "point-sprite UVs must replace TEXCOORD0");
    const pass = fake.calls.filter(call => call[0] === "beginRenderPass").pop()[2];
    assert.deepEqual(pass.ops.filter(op => op[0] === "draw"), [["draw", 6, 8]],
        "eight points should be one six-vertex instanced draw");
});

await test("fixed-function attribute locations follow semantics, not element order", async () => {
    // TEXCOORD declared before COLOR. M1 assigned locations by iteration
    // order while the WGSL hardcoded colour at location 1, so this
    // declaration fed texcoord bytes into the colour attribute.
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
        element(0, 20, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipeline = find("createRenderPipeline").pop()[1];
    const byLocation = new Map(pipeline.vertex.buffers[0].attributes
        .map(a => [a.shaderLocation, a]));
    assert.equal(byLocation.get(1).offset, 20, "COLOR0 must stay at location 1");
    assert.equal(byLocation.get(1).format, "unorm8x4");
    // M3 widened the fixed-function location table to make room for NORMAL and
    // COLOR1 (lighting) plus all eight coordinate sets, so TEXCOORD0 moved from
    // 2 to 4. The property under test is unchanged: the location follows the
    // semantic, not the element's position in the declaration.
    assert.equal(byLocation.get(4).offset, 12, "TEXCOORD0 must stay at location 4");
    assert.equal(byLocation.get(4).format, "float32x2");
});

await test("programmable vs+ps: modules, bindings and constants all line up", async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    const vs = shaderCreatePayload(0x40000001, VS_BYTECODE);
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    const vsConst = floatConstants(0, [
        1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 5, 6, 7, 1,
    ]);
    const psConst = floatConstants(1, [0.25, 0.5, 0.75, 1]);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000001)),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_VS_CONST_F, vsConst.payload, vsConst.blob, vsConst.blobOffsetField),
        command(OP.SET_PS_CONST_F, psConst.payload, psConst.blob, psConst.blobOffsetField),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.shadersTranslated, 2);
    assert.equal(executor.stats.shaderTranslationFailures, 0);
    // One extra translation for the D3DCOLOR-corrected vertex variant.
    assert.equal(executor.stats.shaderVariantsTranslated, 1);
    assert.equal(executor.stats.droppedDraws, 0, "the programmable draw was dropped");
    assert.equal(executor.stats.programmableDraws, 1);

    // Vertex and fragment must come from two different modules.
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.notEqual(pipeline.vertex.module, pipeline.fragment.module);
    assert.ok(pipeline.vertex.module.code.includes("@vertex"));
    assert.ok(pipeline.fragment.module.code.includes("@fragment"));
    // The v1 COLOR0 input is D3DCOLOR, so the module must swizzle it.
    assert.ok(/vin1 = in1\.bgra;/.test(pipeline.vertex.module.code),
        "D3DCOLOR vertex input was not corrected to RGBA:\n" +
        pipeline.vertex.module.code);
    // Locations follow the shader's own v# register numbers.
    assert.deepEqual(pipeline.vertex.buffers[0].attributes, [
        { shaderLocation: 0, offset: 0, format: "float32x3" },
        { shaderLocation: 1, offset: 12, format: "unorm8x4" },
    ]);

    // Bind group layout: vertex constants at 0, pixel constants at 1,
    // sampler 0's texture/sampler pair at 2/3.
    const layout = find("createBindGroupLayout").pop()[1];
    assert.deepEqual(layout.entries.map(e => e.binding).sort((a, b) => a - b),
        [0, 1, 2, 3]);
    const bindGroup = find("createBindGroup").pop()[1];
    const entries = new Map(bindGroup.entries.map(e => [e.binding, e]));
    assert.ok(entries.get(0).resource.buffer, "vertex constants are not a buffer");
    assert.equal(entries.get(0).resource.offset, 0);
    assert.equal(entries.get(1).resource.offset % 256, 0,
        "the pixel constant region must start on a 256-byte boundary");

    // And the values themselves: c0..c3 for the vertex stage, c1 for the
    // pixel stage at its own offset.
    const block = constantBlock(find, entries.get(0).resource.buffer);
    const data = new DataView(block.buffer, block.byteOffset);
    assert.equal(data.getFloat32(12 * 4, true), 5, "vs c3.x");
    assert.equal(data.getFloat32(13 * 4, true), 6, "vs c3.y");
    const pixelBase = entries.get(1).resource.offset;
    assert.equal(data.getFloat32(pixelBase + 16, true), 0.25, "ps c1.x");
    assert.equal(data.getFloat32(pixelBase + 28, true), 1, "ps c1.w");
});

await test("SM1 sampler variants follow cube/2D/volume bindings without poisoning the base shader",
        async () => {
    const { executor, find } = makeExecutor();
    const psHandle = 0x40000189; // NFS9's reported dropped ps_1_1 draw.
    const code = [PS(1, 1), instr(SIO.TEX), dst(REG.TEXTURE, 0),
        instr(SIO.MOV), dst(REG.TEMP, 0), src(REG.TEXTURE, 0), END];
    const ps = shaderCreatePayload(psHandle, code);
    const vs = shaderCreatePayload(0x40000001, VS_TEXCOORD0_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(64, 64)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 72)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT3, DECLUSAGE.TEXCOORD),
        ])),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000001)),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, psHandle)),
        command(OP.CREATE_TEXTURE_CUBE, u32(DEVICE, 0x401, 4, 1, 21, 0, 1, 0)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x402, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_TEXTURE_VOLUME, u32(DEVICE, 0x403, 4, 4, 4, 1, 21, 0, 1)),
    ]));
    for (const [handle, type] of [[0x401, "cube"], [0x402, "2d"],
            [0x403, "3d"], [0x401, "cube"]]) {
        const before = executor.stats.programmableDraws;
        await executor.submit(buildBatch([
            command(OP.SET_TEXTURE, u32(DEVICE, 0, handle, 0)),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 64, 64)),
        ], { present: true }));
        assert.equal(executor.stats.programmableDraws, before + 1, type + " draw must execute");
        assert.equal(executor.stats.droppedDraws, 0);
        const group = find("setBindGroup").filter(call =>
            call[2].entries.some(entry => entry.binding === 3)).pop()[2];
        assert.equal(group.layout.descriptor.entries.find(entry => entry.binding === 2)
            .texture.viewDimension, type);
        const view = group.entries.find(entry => entry.binding === 2).resource;
        assert.equal((view.descriptor && view.descriptor.dimension) ||
            view.texture.descriptor.dimension || "2d", type);
    }
    const shader = executor.resources.get(psHandle);
    assert.equal(shader.translated.reflection.samplers[0].type, "2d");
    assert.equal(shader.variants.size, 2, "revisiting cube must reuse its variant");
    // SM2 really does declare 2D; the same binding is still invalid for it.
    const explicit = shaderCreatePayload(0x40000200, PS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_PIXEL_SHADER, explicit.payload, explicit.blob, explicit.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000200)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ]));
    assert.equal(executor.stats.droppedDraws, 1);
});

await test("all-draw solid probe overrides programmable shading and rejecting state",
        async () => {
    const { executor, find } = makeExecutor();
    executor.debug.forceSolidAllDraws = true;
    // The all-draw probe must win over the older diagnostic which drops
    // programmable draws; otherwise a user carrying both toggles forward sees
    // black and receives the same false geometry diagnosis as before.
    executor.debug.skipProgrammableDraws = true;
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, 15, 1, 0)),   // alpha test
        command(OP.SET_RENDER_STATE, u32(DEVICE, 25, 1, 0)),   // NEVER
        command(OP.SET_RENDER_STATE, u32(DEVICE, 27, 1, 0)),   // blending
        command(OP.SET_RENDER_STATE, u32(DEVICE, 168, 0, 0)),  // no colour writes
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.programmableDraws, 1);
    const descriptor = find("createRenderPipeline").pop()[1];
    assert.ok(descriptor.fragment.module.code.includes(
        "return vec4<f32>(0.0, 1.0, 0.0, 1.0)"));
    assert.ok(!descriptor.fragment.module.code.includes("discard;"));
    assert.equal(descriptor.fragment.targets[0].writeMask, 0xf);
    assert.equal(descriptor.fragment.targets[0].blend, undefined);
    assert.equal(descriptor.primitive.cullMode, "none");
    assert.equal(descriptor.depthStencil.depthCompare, "always");
    assert.equal(descriptor.depthStencil.depthWriteEnabled, false);

    const pipelines = executor.debug.dumpPipelineStates();
    assert.equal(pipelines.length, 1);
    assert.equal(pipelines[0].draws, 1);
    assert.equal(pipelines[0].state.writeMask, 0xf);
    assert.equal(pipelines[0].state.alphaTest.enabled, false);
    const report = executor.debug.blackScreenReport();
    assert.equal(report.debug.forceSolidAllDraws, true);
    assert.ok(report.draws.programmable);
    assert.equal(report.draws.programmable.effectiveClip.width, 640);
    assert.equal(report.draws.programmable.effectiveClip.height, 480);
});

await test("a programmable VS routes fixed-function stage n through oTn", async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const vs = shaderCreatePayload(0x40000004, VS_TEXCOORD0_BYTECODE);
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000004)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        // This may be stale vertex-state from a preceding fixed-function pass.
        // D3D9 still routes stage 0 to oT0 while a vertex shader is bound.
        tss(0, 11 /* D3DTSS_TEXCOORDINDEX */, 1),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithUnwrittenCoordVarying, 0,
        "stage 0 must not follow stale TEXCOORDINDEX while a VS is bound");
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.ok(executor.resources.get(0x40000004).translated.reflection
        .writtenVaryings.includes(2),
    "the translated vertex shader must write oT0 into varying2");
    assert.ok(pipeline.fragment.module.code.includes("stage_in.varying2.xy"),
        "fixed-function stage 0 must sample the translated oT0 varying:\n" +
        pipeline.fragment.module.code);
    assert.ok(!pipeline.fragment.module.code.includes("stage_in.varying3.xy"),
        "stale TEXCOORDINDEX must not redirect stage 0 to oT1");
});

await test("persistent WGSL cache is restored before CREATE_SHADER executes", async () => {
    const cache = new shaderPipeline.D3D9ShaderCache();
    const stream = new Uint32Array(VS_BYTECODE);
    const hash = shaderPipeline.hashTokens(stream);
    cache.compile(stream, hash.low, hash.high);
    const payload = cache.exportEntries();
    let loads = 0;
    const storage = {
        async load() { ++loads; return payload; },
        async save() { throw new Error("a restored hit must not schedule a save"); },
    };
    const { executor } = makeExecutor({ shaderCacheStorage: storage });
    const vs = shaderCreatePayload(0x40000100, VS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
    ]));
    await executor.idle();
    const stats = executor.getStats();
    assert.equal(loads, 1);
    assert.equal(stats.shaderCachePersistentLoads, 1);
    assert.equal(stats.shaderCachePersistentBackend, "injected");
    assert.equal(stats.shaderCacheMisses, 0);
    assert.equal(stats.shaderCacheHits, 1);
    assert.equal(stats.shadersCached, 1);
    assert.ok(stats.shaderWGSLBytesCached > 0);
    assert.deepEqual(stats.occlusionQueries, { mode: "webgpu-query-set",
        active: 0, perFrameCapacity: 8192, resolved: 0 });
});

await test("CREATE_SHADER verifies guest hashes before cache lookup", async () => {
    const { executor } = makeExecutor();
    const firstHandle = 0x40000110;
    const secondHandle = 0x40000111;
    const first = shaderCreatePayload(firstHandle, VS_BYTECODE);
    const second = shaderCreatePayload(secondHandle, VS_TEXCOORD0_BYTECODE);
    // Reproduce the legacy D3D8 proxy bug: every CREATE_SHADER command
    // advertised the same all-zero cache key despite carrying different code.
    for (const shader of [first, second]) {
        shader.payload.writeUInt32LE(0, 16);
        shader.payload.writeUInt32LE(0, 20);
    }
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, first.payload, first.blob,
            first.blobOffsetField),
        command(OP.CREATE_VERTEX_SHADER, second.payload, second.blob,
            second.blobOffsetField),
    ]));
    await executor.idle();

    const stats = executor.getStats();
    assert.equal(stats.shaderCacheMisses, 2,
        "different bytecode must compile as two cache entries");
    assert.equal(stats.shaderCacheHits, 0);
    assert.notEqual(executor.resources.get(firstHandle).translated.wgsl,
        executor.resources.get(secondHandle).translated.wgsl,
        "a bogus guest hash must not alias distinct translated shaders");
});

await test("CREATE_SHADER translation can run through the M6 Worker path", async () => {
    class CompileWorker {
        postMessage(message) {
            queueMicrotask(() => this.onmessage({ data: { id: message.id,
                result: shaderPipeline.compileShader(
                    new Uint32Array(message.tokens)) } }));
        }
        terminate() {}
    }
    const { executor } = makeExecutor({ Worker: CompileWorker,
        shaderWorkerUrl: "fake://d3d9_shader_worker.js" });
    const vs = shaderCreatePayload(0x40000101, VS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
    ]));
    await executor.idle();
    const stats = executor.getStats();
    assert.equal(stats.shaderWorkerCompiles, 1);
    assert.equal(stats.shaderWorkerFallbacks, 0);
    assert.equal(stats.shaderCacheMisses, 1);
    assert.equal(stats.shaderCompileLatencyMs.samples, 1);
});

await test("shader `def` literals override app-set constants for that register", async () => {
    const { executor, find } = makeExecutor();
    // ps_2_0 with `def c0, 0.5, 0.25, 0, 1` and mov oC0, c0.
    const bytecode = [
        PS(2, 0),
        instr(SIO.DEF, 5), dst(REG.CONST, 0),
        0x3f000000, 0x3e800000, 0x00000000, 0x3f800000,
        instr(SIO.MOV, 2), dst(REG.COLOROUT, 0), src(REG.CONST, 0),
        END,
    ];
    const ps = shaderCreatePayload(0x40000005, bytecode);
    const psConst = floatConstants(0, [9, 9, 9, 9]);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000005)),
        command(OP.SET_PS_CONST_F, psConst.payload, psConst.blob, psConst.blobOffsetField),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const bindGroup = find("createBindGroup").pop()[1];
    const pixelEntry = bindGroup.entries.find(e => e.binding === 1);
    const block = constantBlock(find, pixelEntry.resource.buffer);
    const data = new DataView(block.buffer, block.byteOffset);
    const base = pixelEntry.resource.offset;
    assert.equal(data.getFloat32(base, true), 0.5,
        "def c0 must win over SetPixelShaderConstantF");
    assert.equal(data.getFloat32(base + 4, true), 0.25);
});

await test("int and bool constant registers land after the float region", async () => {
    const { executor, find } = makeExecutor();
    // vs_2_0 with rep i0 { add r0, r0, c0 } and if b0.
    const bytecode = [
        VS(2, 0),
        instr(SIO.DCL, 2), dcl(DECLUSAGE.POSITION), dst(REG.INPUT, 0),
        instr(SIO.REP, 1), src(REG.CONSTINT, 0),
        instr(SIO.ADD, 3), dst(REG.TEMP, 0), src(REG.TEMP, 0), src(REG.CONST, 0),
        instr(SIO.ENDREP),
        instr(SIO.IF, 1), src(REG.CONSTBOOL, 0),
        instr(SIO.MOV, 2), dst(REG.TEMP, 0), src(REG.CONST, 1),
        instr(SIO.ENDIF),
        instr(SIO.MOV, 2), dst(REG.RASTOUT, 0), src(REG.TEMP, 0),
        END,
    ];
    const vs = shaderCreatePayload(0x40000007, bytecode);
    const ints = intConstants(0, [3, 0, 1, 0]);
    const bools = boolConstants(0, [1]);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000007)),
        command(OP.SET_VS_CONST_I, ints.payload, ints.blob, ints.blobOffsetField),
        command(OP.SET_VS_CONST_B, bools.payload, bools.blob, bools.blobOffsetField),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const bindGroup = find("createBindGroup").pop()[1];
    const block = constantBlock(find, bindGroup.entries[0].resource.buffer);
    const data = new DataView(block.buffer, block.byteOffset);
    // The shader reads c0 and c1, so the float region is two vec4s (32 bytes),
    // then i0 (16 bytes), then the bool vector.
    assert.equal(data.getInt32(32, true), 3, "i0.x");
    assert.equal(data.getInt32(40, true), 1, "i0.z");
    assert.equal(data.getUint32(48, true), 1, "b0");
});

await test("a shader the translator refuses skips its draws and keeps the batch alive", async () => {
    const { executor } = makeExecutor();
    const ps = shaderCreatePayload(0x40000009, PS_UNSUPPORTED);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000009)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.failed, null, "the batch must not fail as a whole");
    assert.equal(executor.stats.shaderTranslationFailures, 1);
    assert.equal(executor.stats.droppedDraws, 1, "only the shader-bound draw is skipped");
    assert.equal(executor.stats.drawsSkippedForBadShader, 1,
        "the skip must be attributed to the shader, not to missing geometry");
    assert.equal(executor.stats.drawCalls, 1, "the fixed-function draw still ran");
});

await test("independent sampler state drives the GPUSampler, not the texture", async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const D3DSAMP_ADDRESSU = 1, D3DSAMP_ADDRESSV = 2;
    const D3DSAMP_MAGFILTER = 5, D3DSAMP_MINFILTER = 6, D3DSAMP_MIPFILTER = 7;
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_ADDRESSU, 3)), // CLAMP
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_ADDRESSV, 2)), // MIRROR
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MAGFILTER, 2)), // LINEAR
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MINFILTER, 2)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPFILTER, 2)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const samplers = find("createSampler");
    assert.equal(samplers.length, 1, "expected exactly one sampler to be created");
    assert.deepEqual({
        u: samplers[0][1].addressModeU, v: samplers[0][1].addressModeV,
        mag: samplers[0][1].magFilter, min: samplers[0][1].minFilter,
        mip: samplers[0][1].mipmapFilter,
    }, { u: "clamp-to-edge", v: "mirror-repeat", mag: "linear",
        min: "linear", mip: "linear" });
    assert.equal(executor.stats.samplersCreated, 1);
});

// The vendor FOURCC formats. These are outside the D3D9 specification but not
// outside what 9.0c-era games actually ship against, and the three below are
// exact WebGPU mappings rather than approximations.
await test("ATI1N and ATI2N map to BC4 and BC5", async () => {
    // 3Dc is BC4/BC5 under its pre-DX10 name, so this is a rename. Getting the
    // block size wrong is the failure that matters: BC4 is 8 bytes per 4x4
    // block and BC5 is 16, and a mismatched stride corrupts every level.
    const ATI1N = 0x31495441, ATI2N = 0x32495441;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0xA01, 16, 16, 1, ATI1N, 0, 0)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0xA02, 16, 16, 1, ATI2N, 0, 0)),
    ]));
    await executor.idle();
    const formats = find("createTexture").map(call => call[1].format);
    assert.ok(formats.includes("bc4-r-unorm"),
        "ATI1N is BC4: " + formats.join(", "));
    assert.ok(formats.includes("bc5-rg-unorm"),
        "ATI2N is BC5: " + formats.join(", "));
});

await test("a NULL render target allocates the cheapest renderable format",
        async () => {
    // Nothing reads it -- it exists so a depth-only pass need not allocate a
    // colour buffer -- so the size must still match while the per-texel cost
    // need not.
    const D3DFMT_NULL = 0x4C4C554E;
    const D3DUSAGE_RENDERTARGET = 1;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xA03, 256, 256, 1, D3DFMT_NULL,
                D3DUSAGE_RENDERTARGET, 0)),
    ]));
    await executor.idle();
    const descriptor = find("createTexture")
        .map(call => call[1])
        .find(entry => entry.size && entry.size.width === 256);
    assert.ok(descriptor, "the NULL target still has to be allocated");
    assert.equal(descriptor.format, "r8unorm");
});

await test("ATOC in D3DRS_ADAPTIVETESS_Y enables alpha-to-coverage",
        async () => {
    // D3D9 never grew a state for alpha-to-coverage, so every vendor smuggled
    // a FOURCC through a state that meant something else. WebGPU has it
    // natively, which makes this one of the few exact mappings in the family.
    const D3DRS_ADAPTIVETESS_Y = 181, ATOC = 0x434F5441;
    const D3DMULTISAMPLE_4_SAMPLES = 4;
    const { executor, find } = makeExecutor();
    const createDevice = createDevicePayload(640, 480);
    createDevice.writeUInt32LE(D3DMULTISAMPLE_4_SAMPLES, 44);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevice),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ADAPTIVETESS_Y, ATOC)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(
        find("createRenderPipeline").pop()[1].multisample.alphaToCoverageEnabled,
        true);
});

await test("ATOC on a single-sampled target stays off", async () => {
    // WebGPU rejects alphaToCoverage without multisampling, and with one
    // sample there is no coverage to spread an alpha value over anyway.
    const D3DRS_ADAPTIVETESS_Y = 181, ATOC = 0x434F5441;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ADAPTIVETESS_Y, ATOC)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(find("createRenderPipeline").pop()[1].multisample, undefined,
        "no multisample block at all on a single-sampled target");
});

// CreateAdditionalSwapChain targets a second guest window, so the host needs a
// second drawing surface. The back buffer is an ordinary render-target texture
// -- that is what keeps draws, StretchRect and readback unchanged -- and the
// chain is special only in the step that moves the finished image onto its own
// canvas.
const OP_CREATE_SWAP_CHAIN = 0x224;
const OP_DESTROY_SWAP_CHAIN = 0x225;
const OP_PRESENT_SWAP_CHAIN = 0x226;
const D3DUSAGE_RENDERTARGET_BIT = 1;

function makeSwapChainCanvas(calls) {
    return {
        width: 1, height: 1, style: {},
        getContext(kind) {
            calls.push(["swapchain-getContext", kind]);
            return {
                configure(descriptor) {
                    calls.push(["swapchain-configure", descriptor]);
                },
                unconfigure() { calls.push(["swapchain-unconfigure"]); },
                getCurrentTexture() {
                    const texture = { width: 256, height: 128,
                        createView: () => ({ swapchainOverlay: true }) };
                    calls.push(["swapchain-getCurrentTexture", texture]);
                    return texture;
                },
            };
        },
    };
}

await test("an additional swap chain gets its own configured canvas",
        async () => {
    const created = [];
    const surfaces = [];
    const { executor, find, calls } = makeExecutor({
        createSwapChainCanvas: (surface) => {
            created.push(surface);
            return makeSwapChainCanvas(calls);
        },
        onSwapChainSurface: (surface, reason) => surfaces.push([reason, surface]),
    });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x901, 256, 128, 1, 21, D3DUSAGE_RENDERTARGET_BIT, 0)),
        command(OP_CREATE_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0x901, 0xBEEF, 12, 34, 256, 128)),
    ]));
    await executor.idle();
    assert.equal(executor.stats.swapChainsCreated, 1);
    assert.equal(executor.stats.swapChainsRefused, 0);
    assert.equal(created.length, 1, "the embedder must be asked for a canvas");
    assert.equal(created[0].swapChain, 0x77);
    assert.deepEqual(
        { x: created[0].x, y: created[0].y,
          width: created[0].width, height: created[0].height },
        { x: 12, y: 34, width: 256, height: 128 });
    assert.ok(find("swapchain-configure").length === 1,
        "the chain's context has to be configured before it can be presented to");
    assert.deepEqual(surfaces.map(entry => entry[0]), ["create"]);
});

await test("presenting an additional chain blits its back buffer to its canvas",
        async () => {
    const { executor, find, calls } = makeExecutor({
        createSwapChainCanvas: () => makeSwapChainCanvas(calls),
    });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x901, 256, 128, 1, 21, D3DUSAGE_RENDERTARGET_BIT, 0)),
        command(OP_CREATE_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0x901, 0xBEEF, 12, 34, 256, 128)),
        command(OP_PRESENT_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0xBEEF, 40, 50, 256, 128, 0)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.swapChainPresents, 1);
    assert.equal(executor.stats.swapChainPresentsDropped, 0);
    assert.equal(find("swapchain-getCurrentTexture").length, 1,
        "the chain's canvas is acquired inside the submitting task");
    // A blit, not a copy: the back buffer is an ordinary D3D texture whose
    // format need not match the canvas format, and a copy requires a match.
    const blitPipelines = find("createRenderPipeline")
        .map(call => call[1])
        .filter(descriptor => /blit/.test(descriptor.label || ""));
    assert.ok(blitPipelines.length >= 1,
        "the present has to go through the format-converting blit path");
});

await test("an additional swap chain with no canvas hook is counted, not silent",
        async () => {
    // Rendering nowhere in silence is the failure mode that costs the most to
    // diagnose; a refusal that says so costs nothing.
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x901, 256, 128, 1, 21, D3DUSAGE_RENDERTARGET_BIT, 0)),
        command(OP_CREATE_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0x901, 0xBEEF, 0, 0, 256, 128)),
        command(OP_PRESENT_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0xBEEF, 0, 0, 256, 128, 0)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.swapChainsRefused, 1);
    assert.equal(executor.stats.swapChainPresentsDropped, 1,
        "the frame is dropped and counted rather than rendered nowhere");
});

await test("destroying an additional swap chain unconfigures and reports it",
        async () => {
    const surfaces = [];
    const { executor, find, calls } = makeExecutor({
        createSwapChainCanvas: () => makeSwapChainCanvas(calls),
        onSwapChainSurface: (surface, reason) => surfaces.push([reason, surface]),
    });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x901, 256, 128, 1, 21, D3DUSAGE_RENDERTARGET_BIT, 0)),
        command(OP_CREATE_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0x901, 0xBEEF, 0, 0, 256, 128)),
        command(OP_DESTROY_SWAP_CHAIN, u32(DEVICE, 0x77)),
        // A present after destruction must not resurrect it.
        command(OP_PRESENT_SWAP_CHAIN,
            u32(DEVICE, 0x77, 0xBEEF, 0, 0, 256, 128, 0)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.swapChainsDestroyed, 1);
    assert.equal(find("swapchain-unconfigure").length, 1);
    assert.equal(executor.stats.swapChainPresentsDropped, 1);
    assert.deepEqual(surfaces.map(entry => entry[0]), ["create", "destroy"]);
    assert.equal(surfaces[1][1].visible, false,
        "the page needs to know the overlay is gone, not just that it existed");
});

await test("a multisampled target makes the pipeline declare its sample count",
        async () => {
    // WebGPU takes the count on the pipeline as well as on the attachments and
    // rejects a mismatch, so a multisampled device used to fail every draw.
    const D3DMULTISAMPLE_4_SAMPLES = 4;
    const { executor, find } = makeExecutor();
    const createDevice = createDevicePayload(640, 480);
    createDevice.writeUInt32LE(D3DMULTISAMPLE_4_SAMPLES, 44);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevice),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const descriptor = find("createRenderPipeline").pop()[1];
    assert.ok(descriptor.multisample,
        "a multisampled pass needs a multisample block on the pipeline");
    assert.equal(descriptor.multisample.count, 4);
    assert.equal(descriptor.multisample.mask, 0xffffffff,
        "the default D3DRS_MULTISAMPLEMASK writes every sample");
});

await test("D3DRS_MULTISAMPLEMASK reaches the pipeline's sample mask",
        async () => {
    const D3DRS_MULTISAMPLEMASK = 162, D3DMULTISAMPLE_4_SAMPLES = 4;
    const { executor, find } = makeExecutor();
    const createDevice = createDevicePayload(640, 480);
    createDevice.writeUInt32LE(D3DMULTISAMPLE_4_SAMPLES, 44);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevice),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_MULTISAMPLEMASK, 0x5)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(find("createRenderPipeline").pop()[1].multisample.mask, 0x5);
});

await test("a single-sampled target leaves the multisample block off",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(find("createRenderPipeline").pop()[1].multisample, undefined,
        "the ordinary path must be untouched");
});

await test("D3DFILL_WIREFRAME turns each triangle into its three edges",
        async () => {
    // WebGPU has no polygon mode, so wireframe is different geometry rather
    // than a pipeline flag: a line list carrying every triangle's edges.
    const D3DRS_FILLMODE = 8, D3DFILL_WIREFRAME = 2;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE,
            u32(DEVICE, D3DRS_FILLMODE, D3DFILL_WIREFRAME)),
        // Two triangles, non-indexed.
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 2)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.fillModeDraws, 1);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "line-list",
        "the pipeline has to rasterise lines, not triangles");
    // Two triangles -> six edges -> twelve indices.
    const write = find("writeBuffer")
        .map(call => call[3])
        .filter(data => data instanceof Uint32Array).pop();
    assert.ok(write, "an index buffer of edges must have been written");
    assert.equal(write.length, 12,
        "two triangles are six edges, and each edge is two indices");
    assert.deepEqual(Array.from(write.slice(0, 6)), [0, 1, 1, 2, 2, 0],
        "the first triangle's edges are (0,1) (1,2) (2,0)");
});

await test("D3DFILL_SOLID is the default and rewrites nothing", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 2)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.fillModeDraws, 0,
        "solid fill must cost nothing at all");
    assert.equal(find("createRenderPipeline").pop()[1].primitive.topology,
        "triangle-list");
});

await test("D3DFILL_WIREFRAME unrolls a triangle strip before building edges",
        async () => {
    // A strip of N+2 vertices is N triangles that share edges; unrolling is
    // what makes the edge set match the solid form's silhouette.
    const D3DRS_FILLMODE = 8, D3DFILL_WIREFRAME = 2;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE,
            u32(DEVICE, D3DRS_FILLMODE, D3DFILL_WIREFRAME)),
        // D3DPT_TRIANGLESTRIP, two triangles = four vertices.
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(5, 0, 2)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(find("createRenderPipeline").pop()[1].primitive.topology,
        "line-list");
    const write = find("writeBuffer")
        .map(call => call[3])
        .filter(data => data instanceof Uint32Array).pop();
    assert.equal(write.length, 12, "two strip triangles are still six edges");
});

await test("D3DSHADE_FLAT stops interpolating the two colour varyings",
        async () => {
    const D3DRS_SHADEMODE = 9, D3DSHADE_FLAT = 1;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x42, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
        command(OP.SET_RENDER_STATE,
            u32(DEVICE, D3DRS_SHADEMODE, D3DSHADE_FLAT)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const pipeline = find("createRenderPipeline").pop()[1];
    // Both sides of the interface have to agree or the pipeline is invalid.
    for (const [name, wgsl] of [["vertex", pipeline.vertex.module.code],
            ["fragment", pipeline.fragment.module.code]]) {
        assert.match(wgsl, /@location\(0\) @interpolate\(flat\) varying0/,
            "the diffuse varying must be flat in the " + name + " stage:\n" + wgsl);
        assert.match(wgsl, /@location\(1\) @interpolate\(flat\) varying1/,
            "the specular varying must be flat in the " + name + " stage");
        // Texture coordinates keep interpolating under flat shading in D3D9.
        assert.doesNotMatch(wgsl, /@location\(2\) @interpolate\(flat\)/,
            "only the colour varyings are flat in the " + name + " stage");
    }
});

await test("D3DSHADE_FLAT: both stages agree whichever of them is a translated shader",
        async () => {
    // A vertex output and the fragment input at the same location must have
    // the same interpolation, or createRenderPipeline fails and the frame's
    // command buffer with it (GTA San Andreas: its vertex shaders with the
    // fixed-function pixel stage drew nothing). D3D9 flat-shades COLOR0/1
    // with shaders too, as wined3d does.
    const D3DRS_SHADEMODE = 9, D3DSHADE_FLAT = 1, D3DSHADE_GOURAUD = 2;
    const interpolation = code => {
        const slots = new Map();
        for (const match of code.matchAll(
                /@location\((\d+)\)\s*(@interpolate\([^)]*\))?\s*varying\d+/g))
            slots.set(+match[1], match[2] || "perspective");
        return slots;
    };
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    for (const [label, vertexShader, pixelShader] of [
            ["vs + fixed-function ps", true, false],
            ["fixed-function vs + ps", false, true],
            ["vs + ps", true, true]]) {
        const { executor, find } = makeExecutor();
        const vs = shaderCreatePayload(0x40000001, VS_BYTECODE);
        const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
        const draw = shadeMode => [
            command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_SHADEMODE, shadeMode)),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        ];
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
            command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
            command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
            command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
            command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
            ...(vertexShader ? [command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000001))] : []),
            ...(pixelShader ? [command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003))] : []),
            ...draw(D3DSHADE_FLAT),
            // and back: the same shaders, interpolating again
            ...draw(D3DSHADE_GOURAUD),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
        assert.equal(executor.stats.droppedDraws, 0, label);
        const [flat, gouraud] = find("createRenderPipeline").slice(-2).map(call => call[1]);
        for (const [shading, pipeline] of [["flat", flat], ["gouraud", gouraud]]) {
            const out = interpolation(pipeline.vertex.module.code);
            const into = interpolation(pipeline.fragment.module.code);
            for (const [slot, mode] of into)
                assert.equal(out.get(slot), mode, label + ", " + shading +
                    ": location " + slot + " differs between the stages:\n" +
                    pipeline.vertex.module.code + "\n" + pipeline.fragment.module.code);
            const expected = shading === "flat" ? "@interpolate(flat)" : "perspective";
            assert.equal(out.get(0), expected, label + ", " + shading + ": COLOR0");
            assert.equal(out.get(1), expected, label + ", " + shading + ": COLOR1");
            assert.equal(out.get(2), "perspective",
                label + ": texture coordinates keep interpolating");
        }
    }
});

await test("gouraud shading is the default and adds no interpolate attribute",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x42, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const wgsl = find("createRenderPipeline").pop()[1].vertex.module.code;
    assert.doesNotMatch(wgsl, /@interpolate\(flat\)/,
        "the default must not change the shader at all:\n" + wgsl);
});

await test("D3DTADDRESS_MIRRORONCE mirrors the coordinate about zero",
        async () => {
    // The sampler is already clamp-to-edge for the mode, so abs() on that axis
    // is the whole of what is left -- not an approximation of it.
    const D3DSAMP_ADDRESSU = 1, D3DSAMP_ADDRESSV = 2;
    const D3DTADDRESS_MIRRORONCE = 5;
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE,
            u32(DEVICE, 0, D3DSAMP_ADDRESSU, D3DTADDRESS_MIRRORONCE)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(find("createSampler").pop()[1].addressModeU, "clamp-to-edge",
        "the physical sampler clamps; the mirror is the shader's half");
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.match(wgsl, /abs\(/,
        "the U axis has to be mirrored about zero:\n" + wgsl);
    // Only the axis that asked for it.
    assert.doesNotMatch(wgsl, /abs\([^)]*\)\.y/,
        "V is still WRAP and must be left alone:\n" + wgsl);
});

// D3D9 applies the gamma ramp at scanout, so the host applies it in the step
// that puts the finished frame on the canvas -- and only when it would change
// anything, because a lookup pass costs a full-screen draw the plain copy does
// not.
function gammaRampPayload(build) {
    const payload = Buffer.alloc(16 + 768 * 2);
    payload.writeUInt32LE(DEVICE, 0);
    for (let index = 0; index < 256; ++index) {
        const [r, g, b] = build(index);
        payload.writeUInt16LE(r & 0xffff, 16 + index * 2);
        payload.writeUInt16LE(g & 0xffff, 16 + (256 + index) * 2);
        payload.writeUInt16LE(b & 0xffff, 16 + (512 + index) * 2);
    }
    return payload;
}

await test("a non-identity gamma ramp turns the present copy into a lookup pass",
        async () => {
    const OP_SET_GAMMA_RAMP = 0x223;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        // A half-brightness ramp: entry = index * 257 / 2.
        command(OP_SET_GAMMA_RAMP,
            gammaRampPayload(index => {
                const value = Math.round(index * 257 / 2);
                return [value, value, value];
            })),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.gammaRampUpdates, 1);
    assert.equal(executor.stats.gammaPresents, 1,
        "the ramp has to be applied on the way to the canvas");
    assert.equal(find("copyTextureToTexture").length, 0,
        "the plain copy cannot also run, or the ramp would be overwritten");
    const wgsl = find("createRenderPipeline")
        .map(call => call[1].fragment && call[1].fragment.module.code)
        .find(code => code && /d9_gamma_ramp/.test(code));
    assert.ok(wgsl, "a gamma lookup pipeline must have been built");
    assert.match(wgsl, /textureLoad\(d9_gamma_ramp/,
        "the table is indexed, never interpolated:\n" + wgsl);
});

await test("the identity gamma ramp keeps the plain present copy", async () => {
    // Titles set the identity ramp on startup and on exit. Paying for a
    // full-screen pass on every frame for a no-op transform is exactly the
    // cost this has to avoid.
    const OP_SET_GAMMA_RAMP = 0x223;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP_SET_GAMMA_RAMP,
            gammaRampPayload(index => [index * 257, index * 257, index * 257])),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.gammaRampUpdates, 1);
    assert.equal(executor.stats.gammaPresents, 0,
        "an identity ramp changes nothing and must not add a pass");
    assert.equal(find("copyTextureToTexture").length, 1,
        "the ordinary present copy still runs");
});

await test("a gamma ramp reset back to identity releases the lookup pass",
        async () => {
    const OP_SET_GAMMA_RAMP = 0x223;
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP_SET_GAMMA_RAMP, gammaRampPayload(() => [0, 0, 0])),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.gammaPresents, 1);
    await executor.submit(buildBatch([
        command(OP_SET_GAMMA_RAMP,
            gammaRampPayload(index => [index * 257, index * 257, index * 257])),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.gammaPresents, 1,
        "the second present is back on the copy path");
});

await test("D3DSAMP_MAXMIPLEVEL becomes the sampler's LOD floor", async () => {
    const { executor, find } = makeExecutor();
    const D3DSAMP_MIPFILTER = 7, D3DSAMP_MAXMIPLEVEL = 9;
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        // Four levels, so a floor of 2 is inside the chain.
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 4, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPFILTER, 2)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MAXMIPLEVEL, 2)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const descriptor = find("createSampler").pop()[1];
    assert.equal(descriptor.lodMinClamp, 2,
        "MAXMIPLEVEL 2 forbids sampling levels 0 and 1");
    assert.ok(descriptor.lodMaxClamp === undefined ||
        descriptor.lodMaxClamp > 2,
        "the coarse end of the chain stays available");
});

await test("SetLOD reaches the host and combines with D3DSAMP_MAXMIPLEVEL",
        async () => {
    // Two independent floors; D3D9 applies the more restrictive of the pair.
    const OP_SET_TEXTURE_LOD = 0x222;
    const D3DSAMP_MIPFILTER = 7, D3DSAMP_MAXMIPLEVEL = 9;
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 4, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPFILTER, 2)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MAXMIPLEVEL, 1)),
        command(OP_SET_TEXTURE_LOD, u32(DEVICE, 0x401, 3, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(find("createSampler").pop()[1].lodMinClamp, 3,
        "SetLOD(3) is more restrictive than MAXMIPLEVEL(1) and wins");
});

await test("a SetLOD past the end of the chain is clamped, not passed through",
        async () => {
    // lodMinClamp above lodMaxClamp is a WebGPU validation error, so a stale
    // level index has to be clamped against the chain that actually exists.
    const OP_SET_TEXTURE_LOD = 0x222;
    const D3DSAMP_MIPFILTER = 7;
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 4, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPFILTER, 2)),
        command(OP_SET_TEXTURE_LOD, u32(DEVICE, 0x401, 99, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(find("createSampler").pop()[1].lodMinClamp, 3,
        "a four-level chain floors at level 3, not 99");
});

await test("D3DSAMP_MIPMAPLODBIAS becomes textureSampleBias in the cascade",
        async () => {
    // WebGPU samplers carry no bias field, so the only place it can land is
    // the sample call.
    const D3DSAMP_MIPFILTER = 7, D3DSAMP_MIPMAPLODBIAS = 8;
    const floatBits = value => {
        const buffer = Buffer.alloc(4);
        buffer.writeFloatLE(value, 0);
        return buffer.readUInt32LE(0);
    };
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 4, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPFILTER, 2)),
        command(OP.SET_SAMPLER_STATE,
            u32(DEVICE, 0, D3DSAMP_MIPMAPLODBIAS, floatBits(-1.5))),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.match(wgsl, /textureSampleBias\(d9_tex0, d9_smp0, .*-1\.5/,
        "the bias has to reach the sample call:\n" + wgsl);
});

await test("a zero D3DSAMP_MIPMAPLODBIAS leaves the plain sample form alone",
        async () => {
    // The bias is baked as a literal, so every distinct value is a pipeline
    // variant. The default must not mint one.
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.ok(!/textureSampleBias/.test(wgsl),
        "an unbiased stage keeps textureSample:\n" + wgsl);
});

await test("a second draw with the same sampler state reuses the cached sampler", async () => {
    const { executor } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.samplersCreated, 1);
    assert.equal(executor.stats.samplerHits, 1);
});

await test("fixed-function BORDER sampler state reaches the generated shader",
        async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 1, 4)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 2, 4)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 4, 0x80402010)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.ok(wgsl.includes("let tex0 = select(vec4<f32>("));
    assert.ok(wgsl.includes("0.25098039") && wgsl.includes("0.50196078"));
    assert.ok(!executor.stats.unreadStateIds ||
        !(executor.stats.unreadStateIds.samplerStates || []).includes(4),
    "BORDERCOLOR is consumed together with BORDER addressing");
});

await test("multi-stream declarations bind one vertex buffer per stream", async () => {
    const { executor, fake, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(1, 0, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
        element(1, 4, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x202, 1, 96)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(1, 0x202, 12, 32)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.vertex.buffers.length, 2, "expected two vertex buffer layouts");
    assert.deepEqual(pipeline.vertex.buffers[0].attributes,
        [{ shaderLocation: 0, offset: 0, format: "float32x3" }]);
    assert.equal(pipeline.vertex.buffers[1].arrayStride, 12);
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    const binds = pass.ops.filter(op => op[0] === "vertexBuffer");
    assert.equal(binds.length, 2);
    assert.equal(binds[1][3], 32, "stream 1's OffsetInBytes was lost");
});

await test("indexed instancing maps D3D9 stream frequencies to WebGPU instances",
        async () => {
    const { executor, fake, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(1, 0, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x202, 1, 12)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x203, 2, 6, 101)),
        command(OP.CREATE_VERTEX_DECLARATION,
            declarationPayload(0x301, elements)),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(1, 0x202, 4)),
        command(OP.SET_STREAM_SOURCE_FREQ,
            setStreamSourceFreqPayload(0, 0x40000003)),
        command(OP.SET_STREAM_SOURCE_FREQ,
            setStreamSourceFreqPayload(1, 0x80000001)),
        command(OP.SET_INDICES, u32(DEVICE, 0x203)),
        command(OP.DRAW_INDEXED_PRIMITIVE,
            drawIndexedPayload(4, 0, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.vertex.buffers[0].stepMode, "vertex");
    assert.equal(pipeline.vertex.buffers[1].stepMode, "instance");
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    assert.deepEqual(pass.ops.find(op => op[0] === "drawIndexed"),
        ["drawIndexed", 3, 3, 0, 0]);
    assert.equal(executor.stats.instancedDraws, 1);
    assert.equal(executor.stats.instancesDrawn, 3);
    assert.equal(executor.stats.expandedInstanceStreams, 0);
});

await test("D3D9 instance divisors greater than one are expanded exactly",
        async () => {
    const { executor, fake, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(1, 0, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
    ];
    const instanceData = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
    const update = Buffer.alloc(24);
    update.writeUInt32LE(0x202, 0);
    update.writeUInt32LE(0, 4);
    update.writeUInt32LE(instanceData.length, 8);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x202, 1, 8)),
        command(OP.UPDATE_BUFFER, update, instanceData, 12),
        command(OP.CREATE_BUFFER, createBufferPayload(0x203, 2, 6, 101)),
        command(OP.CREATE_VERTEX_DECLARATION,
            declarationPayload(0x301, elements)),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(1, 0x202, 4)),
        command(OP.SET_STREAM_SOURCE_FREQ,
            setStreamSourceFreqPayload(0, 0x40000004)),
        command(OP.SET_STREAM_SOURCE_FREQ,
            setStreamSourceFreqPayload(1, 0x80000002)),
        command(OP.SET_INDICES, u32(DEVICE, 0x203)),
        command(OP.DRAW_INDEXED_PRIMITIVE,
            drawIndexedPayload(4, 0, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    const expanded = find("createBuffer").find(call =>
        call[1].label === "D3D9 instance divisor expansion");
    assert.ok(expanded, "divisor > 1 did not create an expanded instance stream");
    const upload = find("writeBuffer").find(call => call[1] === expanded[2]);
    assert.ok(upload, "expanded instance stream was not uploaded");
    assert.deepEqual([...upload[6].subarray(0, 16)], [
        1, 2, 3, 4, 1, 2, 3, 4,
        5, 6, 7, 8, 5, 6, 7, 8,
    ]);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.vertex.buffers[1].stepMode, "instance");
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    assert.deepEqual(pass.ops.find(op => op[0] === "drawIndexed"),
        ["drawIndexed", 3, 4, 0, 0]);
    assert.equal(executor.stats.expandedInstanceStreams, 1);
});

await test("triangle strips use strip topology instead of being reinterpreted as a list", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(5, 0, 4)), // 4 tris
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "triangle-strip");
    assert.equal(pipeline.primitive.stripIndexFormat, undefined,
        "a non-indexed strip must not declare stripIndexFormat");
});

await test("indexed triangle strips declare the strip index format", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x202, 2, 64, 101)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_INDICES, u32(DEVICE, 0x202)),
        command(OP.DRAW_INDEXED_PRIMITIVE, drawIndexedPayload(5, 0, 0, 4)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "triangle-strip");
    assert.equal(pipeline.primitive.stripIndexFormat, "uint16");
});

await test("triangle fans become an indexed triangle list", async () => {
    const { executor, fake, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(6, 0, 3)), // fan, 3 tris
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.primitive.topology, "triangle-list");
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    const drawIndexed = pass.ops.filter(op => op[0] === "drawIndexed");
    assert.equal(drawIndexed.length, 1);
    assert.equal(drawIndexed[0][1], 9, "3 fan triangles == 9 list indices");
    // (0,1,2) (0,2,3) (0,3,4)
    const indexWrite = find("writeBuffer").find(
        call => call[3] instanceof Uint32Array && call[3].length === 9);
    assert.ok(indexWrite, "the generated fan index buffer was not uploaded");
    assert.deepEqual([...indexWrite[3]], [0, 1, 2, 0, 2, 3, 0, 3, 4]);
});

await test("DrawIndexedPrimitiveUP works (M1 threw a ReferenceError on every call)", async () => {
    const { executor, fake } = makeExecutor();
    const vertexBytes = 4 * 12;
    const indexBytes = 6 * 2;
    const blob = Buffer.alloc(indexBytes + vertexBytes);
    for (let i = 0; i < 6; ++i) blob.writeUInt16LE([0, 1, 2, 0, 2, 3][i], i * 2);
    const payload = Buffer.alloc(48);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(4, 4);       // D3DPT_TRIANGLELIST
    payload.writeUInt32LE(0, 8);       // min_vertex_index
    payload.writeUInt32LE(4, 12);      // vertex_count
    payload.writeUInt32LE(2, 16);      // primitive_count
    payload.writeUInt32LE(101, 20);    // D3DFMT_INDEX16
    payload.writeUInt32LE(12, 24);     // stride
    payload.writeUInt32LE(6, 28);      // index_count
    payload.writeUInt32LE(indexBytes, 32);
    payload.writeUInt32LE(vertexBytes, 36);
    // index_data_offset / vertex_data_offset are patched below.
    const built = buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.DRAW_INDEXED_PRIMITIVE_UP, payload, blob, 40),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true });
    // buildBatch patched index_data_offset (field 40); the vertex data sits
    // straight after the index data in the same blob, so field 44 is patched
    // here, in the assembled batch, to point past it.
    const blobOffset = payload.readUInt32LE(40);
    const commandOffset = built.indexOf(payload, 32);
    built.writeUInt32LE(blobOffset + indexBytes, commandOffset + 44);

    await executor.submit(built);
    await executor.idle();
    assert.equal(executor.failed, null,
        "DrawIndexedPrimitiveUP must not blow up the batch: " + executor.failed);
    assert.equal(executor.stats.upDrawCalls, 1);
    assert.equal(executor.stats.droppedDraws, 0);
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    assert.equal(pass.ops.filter(op => op[0] === "drawIndexed").length, 1);
});

await test("identical bytecode is translated once and shares one shader module", async () => {
    const { executor, find } = makeExecutor();
    const first = shaderCreatePayload(0x40000011, VS_BYTECODE);
    const second = shaderCreatePayload(0x40000013, VS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, first.payload, first.blob, first.blobOffsetField),
        command(OP.CREATE_VERTEX_SHADER, second.payload, second.blob, second.blobOffsetField),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.shaderCache.stats.compiles, 1);
    assert.equal(executor.shaderCache.stats.hits, 1);
    assert.equal(find("createShaderModule").length, 0,
        "modules are only created when a pipeline needs them");
});

await test("HELLO's feature bits report which guest DLL is loaded", async () => {
    const { executor } = makeExecutor();
    // guest_pointer_bits / feature_bits / session_id_low / session_id_high.
    await executor.submit(buildBatch([
        command(OP.HELLO, u32(32, 3 /* SM2 | SM3 */, 0, 0)),
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.guestShaderModel2, true);
    assert.equal(executor.stats.guestShaderModel3, true);

    const stale = makeExecutor();
    await stale.executor.submit(buildBatch([
        command(OP.HELLO, u32(32, 0, 0, 0)),
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await stale.executor.idle();
    assert.equal(stale.executor.stats.guestShaderModel2, false,
        "a pre-M2 guest must be distinguishable from one that simply drew " +
        "no shaders");
    assert.equal(stale.executor.stats.guestShaderModel3, false);
});

await test("an empty client rect on Present keeps the last known surface size", async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const surfaceChangesAfterFirst = executor.stats.surfaceChanges;
    // Fullscreen War3 reports 0x0 here; letting that through would resize the
    // overlay canvas every other frame.
    await executor.submit(buildBatch([
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 0, 0)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.emptySurfaceReports, 1);
    assert.equal(executor.stats.surfaceChanges, surfaceChangesAfterFirst,
        "an empty rect must not count as a surface change");
    const state = executor.devices.get(DEVICE);
    assert.equal(state.surface.width, 640);
    assert.equal(state.surface.height, 480);
});

await test("a frame without Clear restores the previous D3D9 back buffer",
        async () => {
    const { executor, fake, find } = makeExecutor();
    // Establish the persistent image that the next Present must inherit.
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const backBuffer = executor.backBufferTexture;
    assert.ok(backBuffer, "the back buffer is an executor-owned texture");
    assert.equal(executor.stats.backBufferAllocations, 1);
    const passCountAfterFirst =
        fake.calls.filter(call => call[0] === "beginRenderPass").length;

    await executor.submit(buildBatch([
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        // 3DMark06's loading loop follows this path: it changes a small part
        // of the already-presented image and deliberately does not Clear.
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.framesWithoutColorClear, 1);
    assert.equal(executor.stats.framesWithNoOps, 0);
    // The image is inherited because it is literally the same texture, not
    // because anything was copied back into a fresh canvas texture.
    assert.equal(executor.backBufferTexture, backBuffer,
        "the second frame must draw into the same owned texture");
    assert.equal(executor.stats.backBufferAllocations, 1,
        "no reallocation, so nothing to restore");
    const secondFramePasses = fake.calls
        .filter(call => call[0] === "beginRenderPass")
        .slice(passCountAfterFirst);
    assert.ok(secondFramePasses.length, "the draw must open a pass");
    assert.ok(secondFramePasses.every(call =>
        call[1].colorAttachments.every(attachment =>
            attachment.loadOp === "load")),
        "a frame that never Clears must load the existing image");
    // Present is the only place the swap chain is touched.
    const presented = find("copyTextureToTexture")
        .filter(call => call[1].texture === backBuffer);
    assert.equal(presented.length, 2, "one copy to the canvas per Present");
    assert.notEqual(presented[0][2].texture, backBuffer,
        "the copy target is the acquired swap-chain texture");
    assert.equal(executor.stats.backBufferPresents, 2);
});

await test("a dynamic buffer rewritten between draws does not corrupt the earlier draw", async () => {
    // The exact idiom that made War3's scene geometry explode: one shared
    // dynamic vertex buffer, refilled and drawn twice inside a single frame.
    // Draws are recorded and replayed at Present, while writeBuffer takes
    // effect in queue order -- so without renaming, both draws would read the
    // second batch of vertices.
    const { executor, fake, find } = makeExecutor();
    const batchA = Buffer.alloc(36, 0x11);
    const batchB = Buffer.alloc(36, 0x22);
    const updatePayload = (handle, byteCount) => {
        const payload = Buffer.alloc(24);
        payload.writeUInt32LE(handle, 0);
        payload.writeUInt32LE(0, 4);
        payload.writeUInt32LE(byteCount, 8);
        return payload;
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.UPDATE_BUFFER, updatePayload(0x201, 36), batchA, 12),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.UPDATE_BUFFER, updatePayload(0x201, 36), batchB, 12),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.drawCalls, 2);
    assert.equal(executor.stats.bufferRenames, 1,
        "the second write must rename, not overwrite what draw 1 reads");

    // The two draws must end up bound to two different GPUBuffers.
    const pass = fake.calls.filter(c => c[0] === "beginRenderPass").pop()[2];
    const bound = pass.ops.filter(op => op[0] === "vertexBuffer").map(op => op[2]);
    assert.equal(bound.length, 2);
    assert.notEqual(bound[0], bound[1],
        "both draws are reading the same buffer, so the first one renders " +
        "the second one's vertices");

    // And each buffer must hold the batch its draw was issued with.
    const contentsOf = buffer => {
        const write = find("writeBuffer").filter(call => call[1] === buffer).pop();
        assert.ok(write, "no upload for a bound vertex buffer");
        return write[6][0]; // the snapshot taken at writeBuffer time
    };
    assert.equal(contentsOf(bound[0]), 0x11, "draw 1 lost its vertex data");
    assert.equal(contentsOf(bound[1]), 0x22, "draw 2 got the wrong vertex data");
});

await test("a buffer rewritten with no draw in between is updated in place", async () => {
    // Renaming must stay off the ordinary path: upload once, draw many.
    const { executor } = makeExecutor();
    const payload = Buffer.alloc(24);
    payload.writeUInt32LE(0x201, 0);
    payload.writeUInt32LE(0, 4);
    payload.writeUInt32LE(36, 8);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.UPDATE_BUFFER, payload, Buffer.alloc(36, 0x11), 12),
        command(OP.UPDATE_BUFFER, payload, Buffer.alloc(36, 0x22), 12),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.bufferRenames, 0,
        "no draw observed the first contents, so nothing needed renaming");
});

await test("a buffer rewritten in a later frame is updated in place", async () => {
    const { executor } = makeExecutor();
    const payload = Buffer.alloc(24);
    payload.writeUInt32LE(0x201, 0);
    payload.writeUInt32LE(0, 4);
    payload.writeUInt32LE(36, 8);
    const frame = data => buildBatch([
        command(OP.UPDATE_BUFFER, payload, data, 12),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
    ]));
    await executor.submit(frame(Buffer.alloc(36, 0x11)));
    await executor.submit(frame(Buffer.alloc(36, 0x22)));
    await executor.idle();
    assert.equal(executor.stats.drawCalls, 2);
    assert.equal(executor.stats.bufferRenames, 0,
        "the previous frame was already submitted; its draws cannot be " +
        "affected by this frame's writes");
});

await test("alpha test becomes a discard in both fixed-function and translated shaders", async () => {
    const D3DRS_ALPHATESTENABLE = 15, D3DRS_ALPHAREF = 24, D3DRS_ALPHAFUNC = 25;
    const D3DCMP_GREATEREQUAL = 7;
    const { executor, find } = makeExecutor();
    const ps = shaderCreatePayload(0x40000021, PS_BYTECODE);
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ALPHATESTENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ALPHAREF, 128, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        // Same draw with a translated pixel shader bound.
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000021)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);

    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2);
    for (const pipeline of pipelines) {
        const code = pipeline.fragment.module.code;
        assert.ok(code.includes("discard;"),
            "alpha test did not emit a discard:\n" + code);
        // GREATEREQUAL passes when a >= ref, so the discard is its negation.
        assert.ok(code.includes("0.501961"),
            "alpha reference 128 should normalise to ~0.501961:\n" + code);
    }
});

await test("turning alpha test off again returns to the untested shader", async () => {
    const D3DRS_ALPHATESTENABLE = 15;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ALPHATESTENABLE, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ALPHATESTENABLE, 0, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2, "the two states must not share a pipeline");
    // D3DCMP_ALWAYS is the default, so enabling alpha test without setting a
    // function is still a no-op -- the first draw must not gain a discard.
    assert.ok(!pipelines[0].fragment.module.code.includes("discard;"),
        "ALPHAFUNC defaults to ALWAYS, which tests nothing");
    assert.ok(!pipelines[1].fragment.module.code.includes("discard;"));
});

await test("the D3D9 hardware cursor is uploaded and composited over the frame", async () => {
    const { executor, fake, find } = makeExecutor();
    const size = 8;
    const bitmap = Buffer.alloc(size * size * 4, 0x80);
    const cursorProps = Buffer.alloc(32);
    cursorProps.writeUInt32LE(DEVICE, 0);
    cursorProps.writeUInt32LE(2, 4);   // hotspot x
    cursorProps.writeUInt32LE(3, 8);   // hotspot y
    cursorProps.writeUInt32LE(size, 12);
    cursorProps.writeUInt32LE(size, 16);
    cursorProps.writeUInt32LE(bitmap.length, 20);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(0x21A, cursorProps, bitmap, 24),
        command(0x21B, u32(DEVICE, 100, 50, 0)),   // SET_CURSOR_POSITION
        command(0x21C, u32(DEVICE, 1)),            // SHOW_CURSOR
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.cursorUploads, 1);
    assert.equal(executor.stats.cursorDraws, 1);
    // The cursor gets its own final pass, loading the frame underneath.
    const passes = fake.calls.filter(c => c[0] === "beginRenderPass");
    const cursorPass = passes[passes.length - 1];
    assert.equal(cursorPass[1].colorAttachments[0].loadOp, "load",
        "the cursor pass must not clear the frame it sits on");
    assert.equal(cursorPass[1].depthStencilAttachment, undefined,
        "the cursor must not be depth-tested against the game's scene");
    assert.deepEqual(cursorPass[2].ops.filter(op => op[0] === "draw"),
        [["draw", 6]]);

    // Position is placed by the hotspot, in normalised back-buffer space.
    const rectWrite = find("writeBuffer")
        .filter(call => call[6] && call[6].byteLength === 16).pop();
    const rect = new Float32Array(rectWrite[6].buffer, rectWrite[6].byteOffset, 4);
    assert.ok(Math.abs(rect[0] - (100 - 2) / 640) < 1e-6, "cursor origin x");
    assert.ok(Math.abs(rect[1] - (50 - 3) / 480) < 1e-6, "cursor origin y");
    assert.ok(Math.abs(rect[2] - size / 640) < 1e-6, "cursor width");
});

await test("a hidden cursor is not composited", async () => {
    const { executor } = makeExecutor();
    const size = 4;
    const bitmap = Buffer.alloc(size * size * 4, 0xff);
    const cursorProps = Buffer.alloc(32);
    cursorProps.writeUInt32LE(DEVICE, 0);
    cursorProps.writeUInt32LE(size, 12);
    cursorProps.writeUInt32LE(size, 16);
    cursorProps.writeUInt32LE(bitmap.length, 20);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(0x21A, cursorProps, bitmap, 24),
        command(0x21C, u32(DEVICE, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.submit(buildBatch([
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(0x21C, u32(DEVICE, 0)),  // ShowCursor(FALSE)
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.cursorUploads, 1);
    assert.equal(executor.stats.cursorDraws, 1, "only the visible frame draws it");
});

await test("the lock flags decide whether a mid-frame write has to rename", async () => {
    const D3DLOCK_NOOVERWRITE = 0x1000, D3DLOCK_DISCARD = 0x2000;
    const run = async lockFlags => {
        const { executor } = makeExecutor();
        const payload = Buffer.alloc(24);
        payload.writeUInt32LE(0x201, 0);
        payload.writeUInt32LE(0, 4);
        payload.writeUInt32LE(36, 8);
        payload.writeUInt32LE(lockFlags, 16);
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 36)),
            command(OP.SET_FVF, fvfPayload(0x2,
                [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
            command(OP.UPDATE_BUFFER, payload, Buffer.alloc(36, 0x11), 12),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.UPDATE_BUFFER, payload, Buffer.alloc(36, 0x22), 12),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
        return executor.stats;
    };

    // NOOVERWRITE is the application promising it is not touching bytes an
    // issued draw reads -- exactly the guarantee the hazard needs. Renaming
    // there is pure waste, and it is the idiom that made War3 rename ~277
    // times a frame.
    const noOverwrite = await run(D3DLOCK_NOOVERWRITE);
    assert.equal(noOverwrite.bufferRenames, 0);
    assert.equal(noOverwrite.bufferNoOverwriteWrites, 1);

    // DISCARD renames, but the replacement only carries the bytes being
    // written now: the rest is contents the application has abandoned.
    const discard = await run(D3DLOCK_DISCARD);
    assert.equal(discard.bufferRenames, 1);
    assert.equal(discard.bufferFullCopyRenames, 0);

    // A plain lock keeps the old contents readable, so the whole shadow has
    // to be copied forward. Correct, and the only case that costs that.
    const plain = await run(0);
    assert.equal(plain.bufferRenames, 1);
    assert.equal(plain.bufferFullCopyRenames, 1);
});

// The D3D8 frontend sends WINDOW_STATE on move/size/show because a title that
// draws one frame and then only pumps messages has no further Present to carry
// its geometry. If the host only logged it, the overlay would stay where the
// window used to be.
await test("window state moves the overlay for a title that stops presenting",
        async () => {
    const surfaces = [];
    const { executor } = makeExecutor({
        onSurface: (surface, reason) => surfaces.push({ ...surface, reason }) });
    const windowState = (flags, x, y, width, height) => {
        const payload = Buffer.alloc(40);
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(0xa0180, 4);
        payload.writeUInt32LE(0xa0180, 8);   // foreground is the game itself
        payload.writeUInt32LE(flags, 12);
        payload.writeInt32LE(x, 16);
        payload.writeInt32LE(y, 20);
        payload.writeUInt32LE(width, 24);
        payload.writeUInt32LE(height, 28);
        payload.writeUInt32LE(width, 32);    // client width
        payload.writeUInt32LE(height, 36);   // client height
        return payload;
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.PRESENT, u32(DEVICE, 0xa0180, 10, 20, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const afterPresent = executor.stats.surfaceChanges;

    // IS_WINDOW | VISIBLE | FOREGROUND, moved to a new origin.
    await executor.submit(buildBatch([
        command(0x21D, windowState(1 | 2 | 8, 100, 200, 640, 480)),
    ]));
    await executor.idle();
    assert.equal(executor.stats.surfaceChanges, afterPresent + 1,
        "a move with no Present must still reposition the overlay");
    const moved = surfaces[surfaces.length - 1];
    assert.equal(moved.reason, "window-state");
    assert.equal(moved.x, 100);
    assert.equal(moved.y, 200);
    assert.equal(moved.visible, true);

    // Repeating the identical report must not churn the canvas.
    await executor.submit(buildBatch([
        command(0x21D, windowState(1 | 2 | 8, 100, 200, 640, 480)),
    ]));
    await executor.idle();
    assert.equal(executor.stats.surfaceChanges, afterPresent + 1,
        "an unchanged window report must not re-notify");

    // Minimised: hide rather than move.
    await executor.submit(buildBatch([
        command(0x21D, windowState(1 | 2 | 4 | 8, 100, 200, 640, 480)),
    ]));
    await executor.idle();
    assert.equal(surfaces[surfaces.length - 1].visible, false,
        "a minimised window hides the overlay");
});

// Other guest windows over the device window (Warcraft III's cinematic popup,
// a message box) are state the surface keeps until the guest reports again: a
// Present meanwhile does not uncover anything.
await test("window state reports covered windows and the parts that show", async () => {
    const surfaces = [];
    const { executor } = makeExecutor({
        onSurface: (surface, reason) => surfaces.push({ ...surface, reason }) });
    const windowState = (flags, rects) => {
        const payload = Buffer.alloc(40 + (rects ? 4 + rects.length * 16 : 0));
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(0xa0180, 4);
        payload.writeUInt32LE(0xa0180, 8);
        payload.writeUInt32LE(flags | (rects ? 1 << 7 : 0), 12);
        payload.writeInt32LE(10, 16);        // client origin
        payload.writeInt32LE(20, 20);
        payload.writeUInt32LE(648, 24);      // window, frame included
        payload.writeUInt32LE(507, 28);
        payload.writeUInt32LE(640, 32);      // client
        payload.writeUInt32LE(480, 36);
        if (rects) {
            payload.writeUInt32LE(rects.length, 40);
            rects.forEach((r, i) => r.forEach((v, j) => payload.writeInt32LE(v, 44 + i * 16 + j * 4)));
        }
        return payload;
    };
    const last = () => surfaces[surfaces.length - 1];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.PRESENT, u32(DEVICE, 0xa0180, 10, 20, 640, 480)),
    ], { present: true }));
    await executor.idle();

    // IS_WINDOW | VISIBLE | FOREGROUND | OCCLUDED
    await executor.submit(buildBatch([command(0x21D, windowState(1 | 2 | 8 | 64))]));
    await executor.idle();
    assert.equal(last().visible, true, "a covered window is still up");
    assert.equal(last().occluded, true);
    await executor.submit(buildBatch([
        command(OP.PRESENT, u32(DEVICE, 0xa0180, 10, 20, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.devices.get(DEVICE).surface.occluded, true,
        "presenting behind the popup does not uncover the window");

    // A message box over the middle: the bands around it show
    const bands = [[0, 0, 640, 200], [0, 200, 220, 280], [420, 200, 640, 280], [0, 280, 640, 480]];
    await executor.submit(buildBatch([command(0x21D, windowState(1 | 2 | 8, bands))]));
    await executor.idle();
    assert.equal(last().occluded, false);
    assert.deepEqual(last().visibleRegion, {
        rects: bands.map(([left, top, right, bottom]) => ({ left, top, right, bottom })),
        baseWidth: 640, baseHeight: 480, originX: 10, originY: 20 });
    assert.equal(executor.stats.windowRegionReports, 1);
    const changes = executor.stats.surfaceChanges;
    await executor.submit(buildBatch([command(0x21D, windowState(1 | 2 | 8, bands))]));
    await executor.idle();
    assert.equal(executor.stats.surfaceChanges, changes, "the same region again changes nothing");

    // The box closes
    await executor.submit(buildBatch([command(0x21D, windowState(1 | 2 | 8))]));
    await executor.idle();
    assert.equal(last().visibleRegion, null, "all of the window shows again");
    assert.equal(last().occluded, false);

    // A region that does not fit the record is ignored rather than misread
    const truncated = windowState(1 | 2 | 8, bands).subarray(0, 60);
    await executor.submit(buildBatch([command(0x21D, truncated)]));
    await executor.idle();
    assert.equal(executor.devices.get(DEVICE).surface.visibleRegion, null);
});

await test("window state reports a game whose window cannot receive input", async () => {
    const { executor } = makeExecutor();
    const windowState = (flags) => {
        const payload = Buffer.alloc(40);
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(0xa0180, 4);   // hwnd
        payload.writeUInt32LE(0xb1234, 8);   // foreground hwnd (someone else)
        payload.writeUInt32LE(flags, 12);
        payload.writeUInt32LE(800, 24);
        payload.writeUInt32LE(600, 28);
        return payload;
    };
    // IS_WINDOW | VISIBLE | FULLSCREEN, but not FOREGROUND.
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(0x21D, windowState(1 | 2 | 16)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const stats = executor.getStats();
    assert.equal(stats.windowStateChanges, 1);
    assert.equal(stats.window.isWindow, true);
    assert.equal(stats.window.fullscreen, true);
    assert.equal(stats.window.foreground, false,
        "a game that is not the foreground window is exactly the case this " +
        "report exists to make visible");
    assert.equal(stats.window.hwnd, 0xa0180);
    assert.notEqual(stats.window.foregroundHwnd, stats.window.hwnd);
});

await test("the stage-0 texture matrix transforms fixed-function texcoords", async () => {
    const D3DTSS_TEXTURETRANSFORMFLAGS = 24, D3DTTFF_COUNT2 = 2;
    const D3DTS_TEXTURE0 = 16;
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    // A scrolling matrix: D3D9 games put the offset in row 3 (_31/_32) for
    // COUNT2, because the coordinate enters as the row vector (u, v, 1, 1).
    const scroll = [1, 0, 0, 0, 0, 1, 0, 0, 0.25, 0.5, 1, 0, 0, 0, 0, 1];
    const transform = Buffer.alloc(72);
    transform.writeUInt32LE(DEVICE, 0);
    transform.writeUInt32LE(D3DTS_TEXTURE0, 4);
    scroll.forEach((value, index) => transform.writeFloatLE(value, 8 + index * 4));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_TRANSFORM, transform),
        // This test isolates texture transforms; keep the vertex uniform layout
        // independent of D3D9's default-enabled fixed-function lighting.
        command(OP.SET_RENDER_STATE, u32(DEVICE, 137 /* D3DRS_LIGHTING */, 0, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(0x202, u32(DEVICE, 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);

    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2,
        "enabling the transform must not reuse the untransformed pipeline");
    assert.ok(!pipelines[0].vertex.module.code.includes("texture_transform0 *"),
        "the first draw has D3DTTFF_DISABLE and must pass texcoords through");
    assert.ok(pipelines[1].vertex.module.code.includes("texture_transform0 *"),
        "the second draw must apply the matrix:\n" + pipelines[1].vertex.module.code);
    // Entering as (u, v, 1, 1) is what puts the game's offset in row 3.
    assert.ok(pipelines[1].vertex.module.code.includes(".xy, 1.0, 1.0)"),
        "the coordinate must enter the matrix as (u, v, 1, 1)");

    // And the matrix has to actually reach the uniform, after the WVP,
    // viewport and padding.
    const bindGroup = find("createBindGroup").pop()[1];
    const block = constantBlock(find, bindGroup.entries[0].resource.buffer);
    const data = new Float32Array(block.buffer, block.byteOffset, 36);
    assert.deepEqual([...data.slice(20, 36)], scroll);
});

await test("fixed-function fog tints the fragment towards D3DRS_FOGCOLOR", async () => {
    const D3DRS_FOGENABLE = 28, D3DRS_FOGCOLOR = 34, D3DRS_FOGTABLEMODE = 35;
    const D3DRS_FOGSTART = 36, D3DRS_FOGEND = 37;
    const D3DFOG_LINEAR = 3;
    const floatBitsOf = value => {
        const buffer = new ArrayBuffer(4);
        new Float32Array(buffer)[0] = value;
        return new Uint32Array(buffer)[0];
    };
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        // This test isolates fog and asserts exact uniform offsets.
        command(OP.SET_RENDER_STATE, u32(DEVICE, 137 /* D3DRS_LIGHTING */, 0, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGTABLEMODE, D3DFOG_LINEAR, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGCOLOR, 0x00405060, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGSTART, floatBitsOf(10), 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGEND, floatBitsOf(200), 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);

    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2, "fog must not reuse the unfogged pipeline");
    assert.ok(!pipelines[0].fragment.module.code.includes("mix(uniforms.fog_color"),
        "the pre-fog draw must not blend");
    assert.ok(!pipelines[1].vertex.module.code.includes("fog_distance"),
        "table fog must not be reduced to a per-vertex factor");
    assert.ok(pipelines[1].fragment.module.code.includes(
        "fog_distance = 1.0 / max(abs(stage_in.position.w), 1e-6)"),
        "W table fog must recover clip W and evaluate per fragment:\n" +
        pipelines[1].fragment.module.code);
    assert.ok(pipelines[1].fragment.module.code.includes("mix(uniforms.fog_color"),
        "the pixel stage must blend towards the fog colour");

    // The fixed-function pixel stage has no register file, so binding 1 carries
    // the fog colour and, for table fog, its distance parameters.
    const layout = find("createBindGroupLayout").pop()[1];
    assert.ok(layout.entries.some(entry => entry.binding === 1),
        "the fog colour needs its own pixel-stage uniform binding");

    const bindGroup = find("createBindGroup").pop()[1];
    const pixelEntry = bindGroup.entries.find(entry => entry.binding === 1);
    const block = constantBlock(find, pixelEntry.resource.buffer);
    const data = new Float32Array(block.buffer, block.byteOffset);
    const fog = data.subarray(pixelEntry.resource.offset / 4,
        pixelEntry.resource.offset / 4 + 3);
    assert.deepEqual([...fog].map(v => Math.round(v * 255)), [0x40, 0x50, 0x60],
        "D3DRS_FOGCOLOR is 0x00RRGGBB and must reach the shader as RGB");

    // FOGSTART/FOGEND are float bits inside a DWORD, not integers.
    // Table fog evaluates in the fragment stage, so the parameters immediately
    // follow fog_color in the fixed pixel block.
    const pixelBase = pixelEntry.resource.offset / 4;
    assert.equal(data[pixelBase + 4], 10, "FOGSTART decoded as float bits");
    assert.equal(data[pixelBase + 5], 200, "FOGEND decoded as float bits");
});

await test("table fog with a translated VS uses fragment W instead of oFog",
        async () => {
    const D3DRS_FOGENABLE = 28, D3DRS_FOGTABLEMODE = 35;
    const D3DFOG_LINEAR = 3;
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const vs = shaderCreatePayload(0x40000016, VS_TEXCOORD0_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000016)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGTABLEMODE,
            D3DFOG_LINEAR, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.ok(pipeline.fragment.module.code.includes("mix(uniforms.fog_color"),
        "fixed-function fog remains enabled for the mixed VS/FF pixel path");
    assert.ok(pipeline.fragment.module.code.includes(
        "fog_distance = 1.0 / max(abs(stage_in.position.w), 1e-6)"),
        "table fog must be evaluated from per-fragment W");
    assert.ok(!pipeline.fragment.module.code.includes(
        "clamp(stage_in.varying10.x"),
        "table fog must ignore a programmable VS oFog output");
});

await test("vertex fog with a translated VS still consumes oFog", async () => {
    const D3DRS_FOGENABLE = 28, D3DRS_FOGVERTEXMODE = 140;
    const D3DFOG_LINEAR = 3;
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    const vs = shaderCreatePayload(0x40000017, VS_TEXCOORD0_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_VERTEX_DECLARATION, declarationPayload(0x301, elements)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x301)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000017)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGVERTEXMODE,
            D3DFOG_LINEAR, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.ok(pipeline.fragment.module.code.includes(
        "clamp(stage_in.varying10.x"),
        "vertex fog must consume the VS oFog varying");
    assert.ok(!pipeline.fragment.module.code.includes("let fog_distance"),
        "vertex fog must not be replaced by table fog");
    assert.ok(pipeline.vertex.module.code.includes(
        "o_varying10: vec4<f32> = vec4<f32>(1.0, 0.0, 0.0, 0.0);"),
        "an unwritten oFog defaults to factor one for vertex fog");
});

await test("table and vertex fog do not collide in the shader cache", async () => {
    const D3DRS_FOGENABLE = 28, D3DRS_FOGTABLEMODE = 35;
    const D3DRS_FOGVERTEXMODE = 140, D3DRS_LIGHTING = 137;
    const D3DFOG_NONE = 0, D3DFOG_LINEAR = 3;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_LIGHTING, 0, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGTABLEMODE,
            D3DFOG_LINEAR, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGTABLEMODE,
            D3DFOG_NONE, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_FOGVERTEXMODE,
            D3DFOG_LINEAR, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2);
    assert.ok(pipelines[0].fragment.module.code.includes("let fog_distance"),
        "the table-fog fragment module must use fragment W");
    assert.ok(!pipelines[0].vertex.module.code.includes("let fog_distance"),
        "table fog must not run in the vertex shader");
    assert.ok(pipelines[1].fragment.module.code.includes(
        "clamp(stage_in.varying10.x"),
        "the vertex-fog fragment module must consume oFog");
    assert.ok(pipelines[1].vertex.module.code.includes("let fog_distance"),
        "fixed-function vertex fog must be computed in the vertex shader");
});

await test("a malformed batch is rejected rather than half-executed", async () => {
    const { executor } = makeExecutor();
    const batch = buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
    ]);
    batch.writeUInt32LE(0xffffffff, 20); // command_bytes past the record
    await executor.submit(batch);
    await executor.idle();
    assert.ok(executor.failed, "an overrunning command_bytes must fail the batch");
    assert.equal(executor.stats.malformedBatches, 1);
});

await test("shader bytecode that overruns the batch is rejected", async () => {
    const { executor } = makeExecutor();
    const vs = shaderCreatePayload(0x40000015, VS_BYTECODE);
    const batch = buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
    ]);
    // Claim far more tokens than the batch can hold.
    const commandOffset = batch.indexOf(vs.payload, 32);
    batch.writeUInt32LE(0x10000, commandOffset + 8);
    await executor.submit(batch);
    await executor.idle();
    assert.ok(executor.failed, "an overrunning token count must fail the batch");
});

// ---- M3: fixed-function lighting and the texture-blending cascade ----

const D3DRS = {
    LIGHTING: 137, AMBIENT: 139, SPECULARENABLE: 29, COLORVERTEX: 141,
    NORMALIZENORMALS: 143, TEXTUREFACTOR: 60, SCISSORTESTENABLE: 174,
    DIFFUSEMATERIALSOURCE: 145, VERTEXBLEND: 151,
    INDEXEDVERTEXBLENDENABLE: 167,
};
const D3DVBF = { DISABLE: 0, ONE: 1, TWO: 2, THREE: 3, TWEENING: 255,
    ZERO: 256 };
const D3DTSS = {
    COLOROP: 1, COLORARG1: 2, COLORARG2: 3, ALPHAOP: 4, ALPHAARG1: 5,
    ALPHAARG2: 6, TEXCOORDINDEX: 11, TEXTURETRANSFORMFLAGS: 24,
    COLORARG0: 26, RESULTARG: 28, CONSTANT: 32,
};
const D3DTOP = {
    DISABLE: 1, SELECTARG1: 2, SELECTARG2: 3, MODULATE: 4, ADD: 7,
    ADDSIGNED: 8, BLENDTEXTUREALPHA: 13, DOTPRODUCT3: 24, MULTIPLYADD: 25,
    LERP: 26, PREMODULATE: 17, MODULATEALPHA_ADDCOLOR: 18,
    MODULATECOLOR_ADDALPHA: 19, MODULATEINVALPHA_ADDCOLOR: 20,
    MODULATEINVCOLOR_ADDALPHA: 21,
};
const D3DTA = { DIFFUSE: 0, CURRENT: 1, TEXTURE: 2, TFACTOR: 3, SPECULAR: 4,
    TEMP: 5, CONSTANT: 6, COMPLEMENT: 0x10, ALPHAREPLICATE: 0x20 };

function materialPayload(diffuse, ambient, specular, emissive, power) {
    const payload = Buffer.alloc(72);
    payload.writeUInt32LE(DEVICE, 0);
    [...diffuse, ...ambient, ...specular, ...emissive].forEach((value, index) =>
        payload.writeFloatLE(value, 4 + index * 4));
    payload.writeFloatLE(power, 68);
    return payload;
}

function lightPayload(index, type, options = {}) {
    const payload = Buffer.alloc(112);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(index, 4);
    payload.writeUInt32LE(type, 8);
    const diffuse = options.diffuse || [1, 1, 1, 1];
    const specular = options.specular || [1, 1, 1, 1];
    const ambient = options.ambient || [0, 0, 0, 0];
    [...diffuse, ...specular, ...ambient].forEach((value, i) =>
        payload.writeFloatLE(value, 12 + i * 4));
    (options.position || [0, 0, 0]).forEach((value, i) =>
        payload.writeFloatLE(value, 60 + i * 4));
    (options.direction || [0, 0, 1]).forEach((value, i) =>
        payload.writeFloatLE(value, 72 + i * 4));
    payload.writeFloatLE(options.range === undefined ? 1000 : options.range, 84);
    payload.writeFloatLE(options.falloff === undefined ? 1 : options.falloff, 88);
    (options.attenuation || [1, 0, 0]).forEach((value, i) =>
        payload.writeFloatLE(value, 92 + i * 4));
    payload.writeFloatLE(options.theta === undefined ? 0.5 : options.theta, 104);
    payload.writeFloatLE(options.phi === undefined ? 1.0 : options.phi, 108);
    return payload;
}

function transformPayload(state, matrix) {
    const payload = Buffer.alloc(72);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(state, 4);
    matrix.forEach((value, index) => payload.writeFloatLE(value, 8 + index * 4));
    return payload;
}

// ---- fixed-function vertex blending (D3DRS_VERTEXBLEND) ----
//
// The bug these cover: a skinned mesh whose every vertex was posed by world
// matrix 0 renders in bind pose -- rigid, in the right place, fully lit. It
// looks like a working draw, which is why it survived so long, and why these
// assert on the *matrices reaching the block* and not merely on the draw
// succeeding.

// Two world matrices whose translations differ in every component, so a vertex
// posed by the wrong one, or by their unweighted average, lands somewhere no
// other mistake would put it.
const WORLD0 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 2, 3, 1];
const WORLD1 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 40, 50, 60, 1];
const WORLD2 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 700, 800, 900, 1];

function blendedVertexUniforms(find) {
    const bindGroup = find("createBindGroup").pop()[1];
    const block = constantBlock(find, bindGroup.entries[0].resource.buffer);
    return new Float32Array(block.buffer, block.byteOffset);
}

await test("D3DRS_VERTEXBLEND poses a vertex by several world matrices",
        async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT1, DECLUSAGE.BLENDWEIGHT),
    ];
    const projection = [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 160)),
        command(OP.SET_FVF, fvfPayload(0, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_TRANSFORM, transformPayload(257, WORLD1)),
        command(OP.SET_TRANSFORM, transformPayload(3, projection)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.VERTEXBLEND, D3DVBF.ONE, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.blendedDraws, 1, "the draw must be blended");
    assert.equal(executor.stats.drawsWithUnappliedVertexBlend, 0);

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("blend_worlds: array<mat4x4<f32>, 2>"),
        "D3DVBF_1WEIGHTS names one weight and therefore two matrices:\n" + wgsl);
    assert.ok(wgsl.includes("uniforms.blend_worlds[0u]") &&
        wgsl.includes("uniforms.blend_worlds[1u]"),
        "an unindexed blend takes its matrices in order");
    // The last weight is D3D9's leftover, not a second attribute component.
    assert.ok(wgsl.includes("let d9_blend_last = 1.0 - (in13.x);"),
        "the final matrix takes 1 - sum(the supplied weights)");
    assert.ok(wgsl.includes("uniforms.view_projection * d9_blend_position"),
        "a blended draw may not pre-multiply the world matrix");
    assert.ok(!wgsl.includes("world_view_projection"),
        "world_view_projection would silently re-apply world matrix 0");
    // BLENDWEIGHT has to actually be fetched, or the shader reads garbage.
    const byLocation = new Map(pipeline.vertex.buffers[0].attributes
        .map(a => [a.shaderLocation, a]));
    assert.equal(byLocation.get(13).offset, 12, "BLENDWEIGHT belongs at 13");
    assert.equal(byLocation.get(13).format, "float32");

    // view_projection(16) viewport(4) blend_worlds(2 * 16)
    const data = blendedVertexUniforms(find);
    assert.deepEqual([...data.slice(0, 16)], projection,
        "with an identity view, view_projection is the projection alone");
    assert.deepEqual([...data.slice(20, 36)], WORLD0);
    assert.deepEqual([...data.slice(36, 52)], WORLD1);
});

await test("indexed vertex blending reads BLENDINDICES as an integer attribute",
        async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT3, DECLUSAGE.NORMAL),
        element(0, 24, DECLTYPE.FLOAT2, DECLUSAGE.BLENDWEIGHT),
        element(0, 32, DECLTYPE.UBYTE4, DECLUSAGE.BLENDINDICES),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 216)),
        command(OP.SET_FVF, fvfPayload(0, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 36)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_TRANSFORM, transformPayload(257, WORLD1)),
        command(OP.SET_TRANSFORM, transformPayload(258, WORLD2)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.VERTEXBLEND, D3DVBF.TWO, 0)),
        command(OP.SET_RENDER_STATE,
            u32(DEVICE, D3DRS.INDEXEDVERTEXBLENDENABLE, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.LIGHTING, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.NORMALIZENORMALS, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.blendedDraws, 1);

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    // UBYTE4 is uint8x4, an integer format: WebGPU rejects a pipeline whose
    // WGSL declares that location as f32, so the base type has to follow the
    // declaration's D3DDECLTYPE rather than the vec4<f32> everything else uses.
    assert.ok(wgsl.includes("@location(14) in14: vec4<u32>"),
        "BLENDINDICES must be declared with its format's base type:\n" + wgsl);
    assert.ok(wgsl.includes("uniforms.blend_worlds[d9_blend_index.x]") &&
        wgsl.includes("uniforms.blend_worlds[d9_blend_index.z]"),
        "an indexed blend selects each slot's matrix per vertex");
    assert.ok(/min\(in14,\s*vec4<u32>\(\d+u\)\)/.test(wgsl),
        "an out-of-range index has no defined uniform read, so clamp it");
    // The palette is sized from the highest matrix the guest has set (2), then
    // rounded up to a bucket so adding a bone does not mint a new pipeline.
    assert.ok(wgsl.includes("blend_worlds: array<mat4x4<f32>, 4>"),
        "three world matrices set must round up to the 4-entry bucket");
    // The blended normal must go through the blend, and then through the view
    // half only -- normal_matrix no longer carries the world half.
    assert.ok(wgsl.includes("vec4<f32>(d9_blend_normal, 0.0)"),
        "the normal has to ride the same blend as the position");

    const byLocation = new Map(pipeline.vertex.buffers[0].attributes
        .map(a => [a.shaderLocation, a]));
    assert.equal(byLocation.get(14).format, "uint8x4");
    assert.equal(byLocation.get(14).offset, 32);

    // view_projection(16) viewport(4) blend_worlds(4 * 16) view_matrix(16)
    const data = blendedVertexUniforms(find);
    assert.deepEqual([...data.slice(20, 36)], WORLD0);
    assert.deepEqual([...data.slice(36, 52)], WORLD1);
    assert.deepEqual([...data.slice(52, 68)], WORLD2);
    // The unset fourth palette entry is identity, not leftover memory.
    assert.deepEqual([...data.slice(68, 84)],
        [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
});

await test("D3DCOLOR blend indices are scaled back from unorm", async () => {
    // D3DFVF_LASTBETA_D3DCOLOR is the FVF spelling of "the last beta DWORD
    // holds matrix indices", and D3DCOLOR maps to unorm8x4 -- so the shader
    // receives index 2 as 2/255, not as 2. Truncating that selects bone 0 for
    // every vertex, which is bind pose again, arrived at by a different route.
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 144)),
        command(OP.SET_FVF, fvfPayload(0, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT1, DECLUSAGE.BLENDWEIGHT),
            element(0, 16, DECLTYPE.D3DCOLOR, DECLUSAGE.BLENDINDICES)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_TRANSFORM, transformPayload(257, WORLD1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.VERTEXBLEND, D3DVBF.ONE, 0)),
        command(OP.SET_RENDER_STATE,
            u32(DEVICE, D3DRS.INDEXEDVERTEXBLENDENABLE, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.blendedDraws, 1);
    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("@location(14) in14: vec4<f32>"),
        "unorm8x4 is a float format:\n" + wgsl);
    assert.ok(wgsl.includes("round(in14 * 255.0)"),
        "the index bytes have to be scaled back, and rounded not truncated");
    // No .bgra here: the swizzle a D3DCOLOR *colour* needs would reverse the
    // index order, since these bytes are indices in memory order, not channels.
    assert.ok(!wgsl.includes("in14.bgra"),
        "blend indices are bytes in order, not colour channels");
    const byLocation = new Map(pipeline.vertex.buffers[0].attributes
        .map(a => [a.shaderLocation, a]));
    assert.equal(byLocation.get(14).format, "unorm8x4");
});

await test("blend data with D3DRS_VERTEXBLEND disabled is ignored, as D3D9 does",
        async () => {
    // Engines share one declaration between their skinned and unskinned passes,
    // so blend elements are present far more often than blending is on. D3D9
    // poses those draws by D3DTS_WORLD alone; so must this. The counter is what
    // keeps the case visible without a warning that would fire every frame.
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT1, DECLUSAGE.BLENDWEIGHT),
        element(0, 16, DECLTYPE.UBYTE4, DECLUSAGE.BLENDINDICES),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 120)),
        command(OP.SET_FVF, fvfPayload(0, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_TRANSFORM, transformPayload(257, WORLD1)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.blendedDraws, 0);
    assert.equal(executor.stats.drawsWithUnappliedVertexBlend, 1,
        "ignored-but-present skinning data stays countable");

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("uniforms.world_view_projection * in0"),
        "an unblended draw keeps the folded matrix chain:\n" + wgsl);
    assert.ok(!wgsl.includes("blend_worlds"), "no palette is uploaded");
    // A vertex attribute the shader never declares is a pipeline the driver
    // may reject, so the layout has to drop them too.
    const locations = pipeline.vertex.buffers[0].attributes
        .map(a => a.shaderLocation);
    assert.deepEqual(locations, [0],
        "unread skinning attributes must stay out of the vertex layout");
});

await test("vertex blending falls back when the declaration cannot supply it",
        async () => {
    // D3DRS_VERTEXBLEND on, but nothing to blend with: D3D9's result is
    // undefined, so posing by world matrix 0 and saying so beats inventing one.
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 72)),
        command(OP.SET_FVF, fvfPayload(0x2, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.VERTEXBLEND, D3DVBF.TWO, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0, "the draw still renders");
    assert.equal(executor.stats.blendedDraws, 0);
    const wgsl = find("createRenderPipeline").pop()[1].vertex.module.code;
    assert.ok(!wgsl.includes("blend_worlds"),
        "a blend with no weights must not be attempted:\n" + wgsl);
});

await test("pre-transformed vertices are never blended", async () => {
    // XYZRHW geometry has already been through the whole transform pipeline, so
    // there is nothing for a world matrix to pose -- D3D9 ignores VERTEXBLEND
    // for it, and a blend applied here would move UI off screen.
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 120)),
        command(OP.SET_FVF, fvfPayload(0x4, [
            element(0, 0, DECLTYPE.FLOAT4, DECLUSAGE.POSITIONT),
            element(0, 16, DECLTYPE.FLOAT1, DECLUSAGE.BLENDWEIGHT)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TRANSFORM, transformPayload(256, WORLD0)),
        command(OP.SET_TRANSFORM, transformPayload(257, WORLD1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.VERTEXBLEND, D3DVBF.ONE, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.blendedDraws, 0);
    const wgsl = find("createRenderPipeline").pop()[1].vertex.module.code;
    assert.ok(!wgsl.includes("blend_worlds"),
        "XYZRHW must keep its screen-space path:\n" + wgsl);
    assert.ok(wgsl.includes("let ndc_x"), "and still be mapped through NDC");
});

await test("pre-transformed vertices survive stale camera-space texgen",
        async () => {
    // Exact state shape from 3DMark 2001 test 16: an XYZRHW+DIFFUSE stream has
    // no normal or texcoord, while stage 0 still asks for the camera-space
    // reflection vector and a COUNT3 texture transform. The generated value
    // is undefined, but compiling an identifier that was never declared drops
    // the draw and invalidates the rest of the WebGPU command buffer.
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 120)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT4, DECLUSAGE.POSITIONT),
            element(0, 16, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE_STAGE_STATE,
            u32(DEVICE, 0, D3DTSS.TEXCOORDINDEX, 0x30000)),
        command(OP.SET_TEXTURE_STAGE_STATE,
            u32(DEVICE, 0, D3DTSS.TEXTURETRANSFORMFLAGS, 3)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0, "the draw remains encodable");
    const wgsl = find("createRenderPipeline").pop()[1].vertex.module.code;
    assert.ok(!wgsl.includes("position_view"),
        "XYZRHW must not read an unavailable view-space position:\n" + wgsl);
    assert.ok(!wgsl.includes("normal_view"),
        "XYZRHW must not read an unavailable view-space normal:\n" + wgsl);
    assert.ok(wgsl.includes("vec4<f32>(0.0, 0.0, 0.0, 1.0)"),
        "a missing source coordinate needs a finite fallback:\n" + wgsl);
});

await test("fixed-function lighting accepts a sparse light index",
        async () => {
    const { executor, find } = makeExecutor();
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT3, DECLUSAGE.NORMAL),
    ];
    // A view matrix with a translation, so "the light was transformed into view
    // space" is distinguishable from "the light was passed through untouched" --
    // an identity view would make the two indistinguishable, which is exactly
    // the mistake the M1 WVP-order bug was.
    const view = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 20, 30, 1];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
        command(OP.SET_TRANSFORM, transformPayload(2, view)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.LIGHTING, 1, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.AMBIENT, 0x00204060, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.NORMALIZENORMALS, 1, 0)),
        command(OP.SET_MATERIAL, materialPayload(
            [0.5, 0.25, 0.125, 0.75], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0], 16)),
        // MaxActiveLights limits the simultaneous count, not the DWORD index.
        // 3DMark2001 uses scene-object light indices well above seven.
        command(OP.SET_LIGHT, lightPayload(37, 1 /* POINT */,
            { position: [1, 2, 3], attenuation: [1, 0, 0] })),
        command(OP.LIGHT_ENABLE, u32(DEVICE, 37, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithUnappliedLighting, 0,
        "a declaration with a NORMAL must actually be lit");

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("struct D9Light"),
        "the light array has to be declared:\n" + wgsl);
    assert.ok(wgsl.includes("normal_matrix"),
        "normals need the inverse-transpose matrix");
    assert.ok(wgsl.includes("uniforms.lights[0]"), "light 0 must be read");
    assert.ok(wgsl.includes("light.range_falloff.x"),
        "a point light must honour its range");
    // The normal has to reach the pipeline as its own attribute.
    const byLocation = new Map(pipeline.vertex.buffers[0].attributes
        .map(a => [a.shaderLocation, a]));
    assert.equal(byLocation.get(3).offset, 12, "NORMAL belongs at location 3");

    // And the light's position must arrive already multiplied by the view
    // matrix. (1,2,3) * view = (11,22,33).
    const bindGroup = find("createBindGroup").pop()[1];
    const block = constantBlock(find, bindGroup.entries[0].resource.buffer);
    const data = new Float32Array(block.buffer, block.byteOffset);
    // world_view_projection(16) viewport(4) world_view(16) normal_matrix(16)
    // material diffuse/ambient/specular/emissive(16) ambient_power(4) lights...
    const materialDiffuse = 16 + 4 + 16 + 16;
    assert.deepEqual([...data.slice(materialDiffuse, materialDiffuse + 4)],
        [0.5, 0.25, 0.125, 0.75], "material diffuse must reach the block");
    const ambientPower = materialDiffuse + 16;
    assert.deepEqual([...data.slice(ambientPower, ambientPower + 4)]
        .map(v => Math.round(v * 255) / 255),
        [0x20 / 255, 0x40 / 255, 0x60 / 255, 16 / 255].map(v =>
            Math.round(v * 255) / 255).slice(0, 3).concat([
                Math.round(16 * 255) / 255]),
        "D3DRS_AMBIENT is 0x00RRGGBB and the material power shares the vec4");
    const lightBase = ambientPower + 4;
    const position = [...data.slice(lightBase + 12, lightBase + 15)];
    assert.deepEqual(position, [11, 22, 33],
        "the light position must be transformed into view space");
});

await test("D3DRS_LIGHTING with no NORMAL preserves ambient and emissive",
        async () => {
    // D3D9 supplies a zero normal when the declaration has no NORMAL. The
    // light-direction dot products disappear, but ambient and emissive still
    // have to be evaluated. GTA SA relies on that distinction for character
    // batches whose pre-lit vertex colour is black.
    const { executor, find } = makeExecutor();
    const defaultWarnings = [];
    const originalConsoleWarn = console.warn;
    console.warn = (...args) => defaultWarnings.push(args);
    try {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
            command(OP.SET_FVF, fvfPayload(0x42, [
                element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
                element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 16)),
            command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.LIGHTING, 1, 0)),
            command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.AMBIENT,
                0x00ffffff, 0)),
            command(OP.SET_MATERIAL, materialPayload(
                [1, 1, 1, 1], [0.25, 0.5, 0.75, 1], [0, 0, 0, 0],
                [0.05, 0, 0, 0], 0)),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
    } finally {
        console.warn = originalConsoleWarn;
    }
    assert.equal(defaultWarnings.filter(args =>
        /coordinate set|lit draw with no NORMAL/.test(String(args[0]))).length, 0,
    "valid but suspicious draw state must not warn unless diagnostics are enabled");
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithUnappliedLighting, 0,
        "normal-less lighting is implemented, not dropped");
    assert.equal(executor.stats.drawsWithZeroNormalLighting, 1,
        "normal-less lit draws remain visible in diagnostics");
    assert.equal(executor.stats.zeroNormalDrawsWithoutTexture, 0);
    assert.equal(executor.stats.zeroNormalDrawsWithMissingTexture, 1,
        "the default stage-0 texture read must expose its missing binding");
    assert.equal(executor.stats.zeroNormalDrawsWithLiveTexture, 0);

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("let normal_view = vec3<f32>(0.0);"),
        "a missing NORMAL must become the D3D9 zero normal:\n" + wgsl);
    assert.ok(wgsl.includes("total_ambient * material_ambient.xyz"),
        "global ambient and material ambient must still be evaluated");
    assert.ok(wgsl.includes("material_emissive.xyz"),
        "material emissive must survive a missing normal");
    assert.ok(!wgsl.includes("let out_diffuse = vertex_diffuse;"),
        "black pre-lit COLOR0 must not bypass ambient lighting");

    const bindGroup = find("createBindGroup").pop()[1];
    const block = constantBlock(find, bindGroup.entries[0].resource.buffer);
    const data = new Float32Array(block.buffer, block.byteOffset);
    // world_view_projection(16) viewport(4) world_view(16) normal_matrix(16)
    const materialDiffuse = 16 + 4 + 16 + 16;
    assert.deepEqual([...data.slice(materialDiffuse + 4, materialDiffuse + 8)],
        [0.25, 0.5, 0.75, 1], "material ambient must reach the uniform block");
    const ambientPower = materialDiffuse + 16;
    assert.deepEqual([...data.slice(ambientPower, ambientPower + 3)], [1, 1, 1],
        "white D3DRS_AMBIENT must reach the uniform block");

    // The same evidence remains available on demand without changing the
    // rendering path or disabling the always-on counters above.
    const diagnosticWarnings = [];
    executor.debug.warnOnSuspiciousDraws = true;
    console.warn = (...args) => diagnosticWarnings.push(args);
    try {
        await executor.submit(buildBatch([
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
    } finally {
        console.warn = originalConsoleWarn;
    }
    assert.ok(diagnosticWarnings.some(args =>
        String(args[0]).includes("coordinate set")),
    "the missing-coordinate diagnostic must remain available on demand");
    assert.ok(diagnosticWarnings.some(args =>
        String(args[0]).includes("lit draw with no NORMAL")),
    "the zero-normal diagnostic must remain available on demand");
});

await test("a multi-stage texture cascade generates one blend per stage",
        async () => {
    // Terrain splatting in miniature: stage 0 selects its texture, stage 1
    // blends a second texture over it by the first's alpha, stage 2 modulates
    // the result with the diffuse colour.
    const { executor, find } = makeExecutor();
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x402, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x144, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
            element(0, 16, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0),
            element(0, 24, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 1)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 32)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_TEXTURE, u32(DEVICE, 1, 0x402, 0)),
        tss(0, D3DTSS.COLOROP, D3DTOP.SELECTARG1),
        tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        tss(1, D3DTSS.COLOROP, D3DTOP.BLENDTEXTUREALPHA),
        tss(1, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        tss(1, D3DTSS.COLORARG2, D3DTA.CURRENT),
        tss(1, D3DTSS.TEXCOORDINDEX, 1),
        tss(2, D3DTSS.COLOROP, D3DTOP.MODULATE),
        tss(2, D3DTSS.COLORARG1, D3DTA.CURRENT),
        tss(2, D3DTSS.COLORARG2, D3DTA.DIFFUSE),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 0,
        "every operation used here is inside TextureOpCaps");

    const pipeline = find("createRenderPipeline").pop()[1];
    const wgsl = pipeline.fragment.module.code;
    assert.ok(wgsl.includes("d9_tex0") && wgsl.includes("d9_tex1"),
        "both sampled stages need their own texture binding:\n" + wgsl);
    assert.ok(!wgsl.includes("d9_tex2"),
        "stage 2 samples nothing and must not declare a texture");
    assert.ok(wgsl.includes("mix("),
        "BLENDTEXTUREALPHA is a mix by the stage's texture alpha");
    // Stage 2 reads the running result, so `current` has to thread through.
    assert.ok(/current = vec4<f32>\(stage_rgb, stage_a\);/.test(wgsl),
        "each stage must write the cascade register");

    // Two textures bound means two texture/sampler binding pairs.
    const layout = find("createBindGroupLayout").pop()[1];
    for (const binding of [2, 3, 4, 5])
        assert.ok(layout.entries.some(entry => entry.binding === binding),
            "binding " + binding + " must be declared for two sampled stages");
    assert.ok(!layout.entries.some(entry => entry.binding === 6),
        "stage 2 samples nothing, so no third pair");
});

await test("D3DTSS_RESULTARG threads a stage result through the temp register",
        async () => {
    const { executor, find } = makeExecutor();
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        tss(0, D3DTSS.COLOROP, D3DTOP.SELECTARG1),
        tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        tss(0, D3DTSS.RESULTARG, D3DTA.TEMP),
        tss(1, D3DTSS.COLOROP, D3DTOP.MULTIPLYADD),
        tss(1, D3DTSS.COLORARG0, D3DTA.TEMP),
        tss(1, D3DTSS.COLORARG1, D3DTA.DIFFUSE),
        tss(1, D3DTSS.COLORARG2, D3DTA.TFACTOR),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.TEXTUREFACTOR, 0x80402010, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.ok(/temp = vec4<f32>\(stage_rgb, stage_a\);/.test(wgsl),
        "stage 0 must write the temp register:\n" + wgsl);
    assert.ok(wgsl.includes("temp.rgb"), "stage 1 must read it back");
    assert.ok(wgsl.includes("uniforms.texture_factor"),
        "D3DTA_TFACTOR needs the texture factor uniform");

    // The texture factor has to actually be uploaded, as 0xAARRGGBB.
    const bindGroup = find("createBindGroup").pop()[1];
    const pixelEntry = bindGroup.entries.find(entry => entry.binding === 1);
    const block = constantBlock(find, pixelEntry.resource.buffer);
    const data = new Float32Array(block.buffer, block.byteOffset);
    const factor = [...data.slice(pixelEntry.resource.offset / 4,
        pixelEntry.resource.offset / 4 + 4)].map(v => Math.round(v * 255));
    assert.deepEqual(factor, [0x40, 0x20, 0x10, 0x80],
        "D3DRS_TEXTUREFACTOR is 0xAARRGGBB");
});

const D3DTOP_BUMPENVMAP = 22;
const D3DTOP_BUMPENVMAPLUMINANCE = 23;
const D3DTSS_BUMPENVMAT00 = 7, D3DTSS_BUMPENVMAT01 = 8;
const D3DTSS_BUMPENVMAT10 = 9, D3DTSS_BUMPENVMAT11 = 10;

// A bump stage displaces the *next* stage's coordinate, so a BUMPENVMAP with
// no stage after it displaces nothing at all. That renders a frame which looks
// almost right, which is exactly the case worth reporting rather than drawing
// silently.
await test("a trailing D3DTOP_BUMPENVMAP has nothing to displace and is reported",
        async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(0x202, u32(DEVICE, 0, D3DTSS.COLOROP, D3DTOP_BUMPENVMAP)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 1,
        "a bump stage with no consumer must be reported");
    assert.equal(executor.stats.droppedDraws, 0,
        "the draw still renders rather than disappearing");
});

await test("D3DTOP_BUMPENVMAP displaces the next stage through its matrix",
        async () => {
    const { executor, find } = makeExecutor();
    const floatBitsOf = value => {
        const buffer = new ArrayBuffer(4);
        new Float32Array(buffer)[0] = value;
        return new Uint32Array(buffer)[0];
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        // Stage 0 is the (du, dv) map, stage 1 the environment it displaces.
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 60, 0, 1)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x402, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.SET_TEXTURE, u32(DEVICE, 1, 0x402, 0)),
        command(0x202, u32(DEVICE, 0, D3DTSS.COLOROP, D3DTOP_BUMPENVMAP)),
        command(0x202, u32(DEVICE, 0, D3DTSS_BUMPENVMAT00, floatBitsOf(0.25))),
        command(0x202, u32(DEVICE, 0, D3DTSS_BUMPENVMAT01, floatBitsOf(0.5))),
        command(0x202, u32(DEVICE, 0, D3DTSS_BUMPENVMAT10, floatBitsOf(0.75))),
        command(0x202, u32(DEVICE, 0, D3DTSS_BUMPENVMAT11, floatBitsOf(1.5))),
        command(0x202, u32(DEVICE, 1, D3DTSS.COLOROP, 2 /* SELECTARG1 */)),
        command(0x202, u32(DEVICE, 1, D3DTSS.COLORARG1, 2 /* TEXTURE */)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 0,
        "a bump pair is supported and must not be reported as unsupported");
    assert.equal(executor.stats.drawCalls, 1);

    // The bump stage must sample even though no argument named its texture:
    // the displacement is its whole purpose.
    const module = find("createShaderModule")
        .map(call => call[1].code)
        .find(code => /stage_bump0/.test(code));
    assert.ok(module, "the cascade must declare a bump matrix uniform");
    const code = module;
    assert.match(code, /textureSample\(d9_tex0/,
        "the bump stage samples its own (du, dv) map");
    assert.match(code,
        /stage_bump0\.x \* tex0\.r \+ uniforms\.stage_bump0\.z \* tex0\.g/,
        "u is displaced by m00*du + m10*dv: " + code);
    assert.match(code,
        /stage_bump0\.y \* tex0\.r \+ uniforms\.stage_bump0\.w \* tex0\.g/,
        "v is displaced by m01*du + m11*dv");
});

// The MODULATE*_ADD* family is the one part of the cascade that mixes a
// argument's colour with the *same* argument's alpha, so each case is checked
// against the algebra D3D9 documents rather than against "it compiled".
for (const { name, op, pattern } of [
    { name: "MODULATEALPHA_ADDCOLOR", op: D3DTOP.MODULATEALPHA_ADDCOLOR,
      // Arg1.RGB + Arg1.A * Arg2.RGB
      pattern: /\(tex0\.rgb \+ tex0\.a \* [a-z_0-9.]+\.rgb\)/ },
    { name: "MODULATECOLOR_ADDALPHA", op: D3DTOP.MODULATECOLOR_ADDALPHA,
      // Arg1.RGB * Arg2.RGB + Arg1.A
      pattern: /\(tex0\.rgb \* [a-z_0-9.]+\.rgb \+ vec3<f32>\(tex0\.a\)\)/ },
    { name: "MODULATEINVALPHA_ADDCOLOR", op: D3DTOP.MODULATEINVALPHA_ADDCOLOR,
      // (1 - Arg1.A) * Arg2.RGB + Arg1.RGB
      pattern: /\(\(1\.0 - tex0\.a\) \* [a-z_0-9.]+\.rgb \+ tex0\.rgb\)/ },
    { name: "MODULATEINVCOLOR_ADDALPHA", op: D3DTOP.MODULATEINVCOLOR_ADDALPHA,
      // (1 - Arg1.RGB) * Arg2.RGB + Arg1.A
      pattern: /\(\(vec3<f32>\(1\.0\) - tex0\.rgb\) \* [a-z_0-9.]+\.rgb \+ vec3<f32>\(tex0\.a\)\)/ },
]) {
    await test("D3DTOP_" + name + " emits the algebra D3D9 documents",
            async () => {
        const { executor, find } = makeExecutor();
        const tss = (stage, state, value) =>
            command(0x202, u32(DEVICE, stage, state, value));
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
            command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
            command(OP.SET_FVF, fvfPayload(0x104, [
                element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
                element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
                element(0, 16, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
            command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
            tss(0, D3DTSS.COLOROP, op),
            tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
            tss(0, D3DTSS.COLORARG2, D3DTA.DIFFUSE),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
        assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 0,
            "D3DTOP_" + name + " is advertised in TextureOpCaps and must " +
            "not be counted as unsupported");
        assert.equal(executor.stats.droppedDraws, 0);
        const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
        assert.match(wgsl, pattern,
            "D3DTOP_" + name + " must emit its documented form:\n" + wgsl);
    });
}

await test("the MODULATE*_ADD* family is refused as an alpha operation",
        async () => {
    // D3D9 defines all four for D3DTSS_COLOROP only. Counting the refusal is
    // what keeps a caps claim from covering a channel it was never made for.
    const { executor } = makeExecutor();
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
            element(0, 16, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        tss(0, D3DTSS.COLOROP, D3DTOP.SELECTARG1),
        tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        tss(0, D3DTSS.ALPHAOP, D3DTOP.MODULATEALPHA_ADDCOLOR),
        tss(0, D3DTSS.ALPHAARG1, D3DTA.TEXTURE),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 1,
        "an alpha-channel MODULATEALPHA_ADDCOLOR must be counted, not emitted");
});

await test("D3DTOP_PREMODULATE stays refused and is counted", async () => {
    // It modulates against the *next* stage's texture; nothing in the cascade
    // carries a value backwards, and fill_caps() does not advertise it.
    const { executor } = makeExecutor();
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR),
            element(0, 16, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 24)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        tss(0, D3DTSS.COLOROP, D3DTOP.PREMODULATE),
        tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawsWithUnsupportedTextureOp, 1,
        "PREMODULATE is outside TextureOpCaps and must be counted");
});

await test("a render target redirects the pass and keys its own pipeline",
        async () => {
    const D3DUSAGE_RENDERTARGET = 1;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        // A render target arrives as a CREATE_TEXTURE_2D carrying the usage.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x501, 256, 256, 1, 21, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        // Into the texture...
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0x501, 0)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0, 0, 0, 0)),
        command(OP.SET_VIEWPORT, u32(DEVICE, 0, 0, 256, 256, 0, 0x3f800000, 0)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff112233, 0, 0, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        // ...and back to the back buffer, restoring the implicit depth surface
        // (D9WG_AUTO_DEPTH_STENCIL_HANDLE) the way an app that saved it does.
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0, 0)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0xffffffff, 0, 640, 480)),
        command(OP.SET_VIEWPORT, u32(DEVICE, 0, 0, 640, 480, 0, 0x3f800000, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.renderTargetsCreated, 1);
    assert.equal(executor.stats.renderTargetBinds, 2);
    // The texture pass has no depth attachment and the back-buffer pass does,
    // so they cannot share a pipeline -- that is the whole point of baking
    // hasDepth into the key.
    const pipelines = find("createRenderPipeline").map(call => call[1]);
    assert.equal(pipelines.length, 2,
        "a target with a different depth configuration needs its own pipeline");
    assert.ok(!pipelines[0].depthStencil,
        "the render-to-texture pass was given no depth surface");
    assert.ok(pipelines[1].depthStencil,
        "the back-buffer pass still has the auto depth-stencil");
    // Two distinct targets means at least two passes, and the first must not be
    // pointed at the swap chain.
    const passes = find("beginRenderPass").map(call => call[1]);
    assert.ok(passes.length >= 2, "each target needs its own pass");
    assert.notEqual(passes[0].colorAttachments[0].view,
        passes[passes.length - 1].colorAttachments[0].view,
        "the texture pass must not render into the back buffer");
    assert.equal(executor.stats.renderPasses, passes.length);
});

await test("a pre-1.3 batch is rejected before any command executes",
        async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
    ], { versionMinor: 2 }));
    await executor.idle();
    assert.match(executor.failed && executor.failed.message,
        /unsupported D9WG version 1\.2/);
    assert.equal(executor.stats.malformedBatches, 1);
    assert.equal(executor.devices.size, 0,
        "an obsolete DLL must not partially initialize host state");
});

await test("a short pre-1.3 device payload is not decoded as 1.3", async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, Buffer.alloc(44)),
    ]));
    await executor.idle();
    assert.match(executor.failed && executor.failed.message,
        /CREATE_DEVICE payload is not protocol 1\.3/);
    assert.equal(executor.stats.malformedBatches, 1);
    assert.equal(executor.devices.size, 0);
});

await test("a depth texture sampled by a pixel shader becomes a shadow map",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DFMT_D24S8 = 75;
    const { executor, find } = makeExecutor();
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x502, 1024, 1024, 1, D3DFMT_D24S8,
                D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x502, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    // The regression this guards: the depth resource carried a null view, the
    // null reached createBindGroup as a binding resource, and the TypeError it
    // threw took the whole batch down with it.
    assert.equal(executor.stats.commandsFailed, 0,
        "sampling a depth texture must not throw out of its command");
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.depthStageWithoutDepthTexture, 0);

    const layout = find("createBindGroupLayout").pop()[1];
    const textureEntry = layout.entries.find(entry => entry.binding === 2);
    const samplerEntry = layout.entries.find(entry => entry.binding === 3);
    assert.equal(textureEntry.texture.sampleType, "depth");
    assert.equal(samplerEntry.sampler.type, "comparison");
    assert.ok(find("createSampler").some(call =>
        call[1].compare === "less-equal"),
        "a shadow map is read through a comparison sampler");

    // The module and the layout have to agree: a texture_2d<f32> paired with a
    // depth layout entry fails pipeline creation outright.
    assert.ok(find("createShaderModule").some(call =>
        call[1].code.includes("texture_depth_2d") &&
        call[1].code.includes("sampler_comparison")),
        "the pixel stage must be translated to a comparison sample");
});

await test("a shadow map still bound as the depth attachment is not sampled",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DFMT_D24S8 = 75;
    const { executor } = makeExecutor();
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x502, 640, 480, 1, D3DFMT_D24S8,
                D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        // Attachment and sampler at once: legal enough in D3D9, a submit-level
        // validation error in WebGPU.
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0x502, 0, 640, 480)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x502, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.commandsFailed, 0);
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.depthAttachmentSampledInPlace, 1,
        "the read-write hazard must degrade the stage, not the submit");
});

await test("a depth texture on a fixed-function stage reads the white fallback",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DFMT_D24S8 = 75;
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x502, 256, 256, 1, D3DFMT_D24S8,
                D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.SET_FVF, fvfPayload(0x102,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
             element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x502, 0)),
        // COLOROP = MODULATE with ARG1 = TEXTURE, so the cascade samples.
        command(OP.SET_TEXTURE_STAGE_STATE, u32(DEVICE, 0, 1, 4)),
        command(OP.SET_TEXTURE_STAGE_STATE, u32(DEVICE, 0, 2, 2)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    // Fixed function has no comparison reference to offer, so the stage cannot
    // be a shadow map. It has to degrade to the white fallback rather than
    // reach a float layout entry with a depth view, which is invalid.
    assert.equal(executor.stats.commandsFailed, 0);
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.depthTextureOnNonDepthStage, 1);
});

await test("one failing command does not discard the rest of its batch",
        async () => {
    const { executor, fake } = makeExecutor();
    // Force a runtime failure that is not a framing error, the way a bad
    // binding resource used to be one.
    executor.handlers[OP.SET_RENDER_STATE] = () => {
        throw new Error("synthetic command failure");
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, 27, 1, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.commandsFailed, 1);
    assert.equal(executor.failed, null,
        "one bad command is not a bad batch");
    assert.equal(executor.stats.droppedDraws, 0);
    const pass = fake.calls.filter(call => call[0] === "beginRenderPass").pop()[2];
    assert.ok(pass.ops.some(op => op[0] === "draw"),
        "commands queued behind the failure must still execute");
});

await test("a framing error still fails the whole batch", async () => {
    const { executor } = makeExecutor();
    const vs = shaderCreatePayload(0x40000015, VS_BYTECODE);
    const batch = buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_VERTEX_SHADER, vs.payload, vs.blob, vs.blobOffsetField),
    ]);
    batch.writeUInt32LE(0x10000, batch.indexOf(vs.payload, 32) + 8);
    await executor.submit(batch);
    await executor.idle();

    // The per-command guard must not swallow this: a blob reaching past the
    // record means the byte layout itself is wrong, so nothing in the batch
    // can be trusted -- unlike a command that simply could not be carried out.
    assert.ok(executor.failed, "a malformed stream must still fail the batch");
    assert.equal(executor.stats.commandsFailed, 0);
});

await test("a D24S8 mip is used as the explicit depth attachment",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DFMT_D24S8 = 75;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        // Disable the automatic depth surface so the pass can only succeed by
        // resolving the texture bound below.
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x502, 2560, 1920, 4, D3DFMT_D24S8,
                D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0x502, 2, 640, 480)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.texturesRejected, 0);
    const creation = find("createTexture").find(call =>
        call[1].label === "D3D9 depth surface");
    assert.ok(creation, "CreateTexture(D24S8) must allocate a GPU depth target");
    assert.equal(creation[1].format, "depth24plus-stencil8");
    assert.equal(creation[1].mipLevelCount, 4);
    assert.equal(creation[1].usage, 0x14,
        "a depth texture is a render attachment AND sampleable: D3D9 shadow " +
        "mapping renders into it and then binds it to a sampler");

    const pass = find("beginRenderPass").find(call =>
        call[1].depthStencilAttachment);
    assert.ok(pass, "the draw must open a pass with the explicit depth surface");
    assert.equal(pass[1].depthStencilAttachment.view.texture, creation[2]);
    assert.deepEqual(pass[1].depthStencilAttachment.view.descriptor, {
        baseMipLevel: 2,
        mipLevelCount: 1,
        dimension: "2d",
        baseArrayLayer: 0,
        arrayLayerCount: 1,
    }, "the attachment view must address exactly the selected depth mip");
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.equal(pipeline.depthStencil.format, "depth24plus-stencil8");
});

await test("an out-of-range depth mip is rejected at binding without invalidating WebGPU",
        async () => {
    const warnings = [];
    const realWarn = console.warn;
    const { executor, find } = makeExecutor();
    console.warn = (...args) => warnings.push(args.join(" "));
    try {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
            command(OP.CREATE_TEXTURE_2D,
                u32(DEVICE, 0x503, 640, 480, 2, 75, 2, 0)),
            command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
            command(OP.SET_FVF, fvfPayload(0x2,
                [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
            command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
            command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
                u32(DEVICE, 0x503, 2, 160, 120)),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
    } finally {
        console.warn = realWarn;
    }
    assert.equal(executor.stats.texturesRejected, 0);
    assert.ok(find("createTexture").some(call =>
        call[1].label === "D3D9 depth surface"),
        "a valid multi-mip depth descriptor must reach WebGPU");
    assert.ok(warnings.some(line => line.includes("out-of-range texture level")),
        "the invalid binding should explain why depth was omitted");
    const pass = find("beginRenderPass").find(call =>
        call[1].colorAttachments);
    assert.ok(pass && !pass[1].depthStencilAttachment,
        "an invalid mip must be dropped before render-pass validation");
});

await test("an oversized depth surface still depth-tests a smaller target",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DUSAGE_RENDERTARGET = 1;
    const D3DFMT_D24S8 = 75;
    const D3DFMT_A16B16G16R16F = 113;
    const { executor, fake } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        // The render-to-texture idiom D3D9 allows and WebGPU does not: one
        // full-size depth surface reused by a half-resolution HDR pass.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xC01, 640, 480, 1, D3DFMT_D24S8,
                D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xC02, 320, 240, 1, D3DFMT_A16B16G16R16F,
                D3DUSAGE_RENDERTARGET, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0xC02, 0, 0)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0xC01, 0, 640, 480)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.commandsFailed, 0);
    assert.equal(executor.stats.depthTargetSubstitutions, 1);
    // The point of the substitution: the pass keeps depth testing. Running it
    // with no depth attachment lets every blended draw paint over geometry
    // that should have occluded it, which reads as a washed-out translucent
    // frame rather than as an error.
    const pass = fake.calls.filter(call => call[0] === "beginRenderPass")
        .map(call => call[1])
        .find(descriptor => descriptor.depthStencilAttachment);
    assert.ok(pass, "the half-resolution pass must still have depth");
    const substitute = fake.calls.filter(call => call[0] === "createTexture")
        .find(call => call[1].label &&
            call[1].label.startsWith("D3D9 substitute depth"));
    assert.ok(substitute, "a matching depth texture has to be allocated");
    assert.equal(substitute[1].size.width, 320);
    assert.equal(substitute[1].size.height, 240);
    // Nothing was lost -- the draw did not depth-test against contents an
    // earlier pass wrote -- so the substitution must not be reported as one.
    assert.equal(executor.stats.depthTargetSubstitutionsUncleared, 0);
});

await test("an uncleared oversized-depth pass is reported, a cleared one is not",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DUSAGE_RENDERTARGET = 1;
    const D3DFMT_D24S8 = 75;
    const D3DFMT_A8R8G8B8 = 21;
    const D3DRS_ZENABLE = 7;
    const D3DCLEAR_ZBUFFER = 2;
    const setup = () => [
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xF01, 640, 480, 1, D3DFMT_D24S8, D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xF02, 320, 240, 1, D3DFMT_A8R8G8B8, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_ZENABLE, 1, 0)),
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0xF02, 0, 0)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL, u32(DEVICE, 0xF01, 0, 640, 480)),
    ];

    // Clearing depth on entry is what render-to-texture does, and it makes the
    // stand-in exactly equivalent to the surface it replaced.
    {
        const { executor } = makeExecutor();
        await executor.submit(buildBatch([
            ...setup(),
            command(OP.CLEAR, u32(DEVICE, D3DCLEAR_ZBUFFER, 0, 0x3f800000, 0)),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
        // Counted per target resolution, and both the Clear and the draw
        // resolve, so the interesting number is the second one.
        assert.ok(executor.stats.depthTargetSubstitutions >= 1);
        assert.equal(executor.stats.depthTargetSubstitutionsUncleared, 0,
            "a cleared substitute loses nothing and must stay quiet");
    }

    // Depth-testing without clearing reads a stand-in that never received what
    // an earlier pass wrote, which is the case worth reporting.
    {
        const { executor } = makeExecutor();
        await executor.submit(buildBatch([
            ...setup(),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
            command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
        ], { present: true }));
        await executor.idle();
        assert.equal(executor.stats.depthTargetSubstitutionsUncleared, 1);
    }
});

await test("an autogen texture allocates the chain and fills it after a write",
        async () => {
    const D3DUSAGE_AUTOGENMIPMAP = 0x400;
    const D3DFMT_A8R8G8B8 = 21;
    const { executor, fake, find } = makeExecutor();
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    // The guest reports one level, which is what D3D9's GetLevelCount says for
    // an autogen texture; the chain lives entirely on this side.
    const update = Buffer.alloc(48);
    update.writeUInt32LE(0xE01, 0);
    update.writeUInt32LE(8, 20);   // width
    update.writeUInt32LE(8, 24);   // height
    update.writeUInt32LE(1, 28);
    update.writeUInt32LE(32, 32);  // row pitch
    update.writeUInt32LE(256, 40);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xE01, 8, 8, 1, D3DFMT_A8R8G8B8,
                D3DUSAGE_AUTOGENMIPMAP, 0)),
        command(OP.UPDATE_TEXTURE, update, Buffer.alloc(256, 0x80), 44),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0xE01, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.commandsFailed, 0);
    assert.equal(executor.stats.droppedDraws, 0);
    const created = find("createTexture").find(call =>
        call[1].size && call[1].size.width === 8)[1];
    assert.equal(created.mipLevelCount, 4, "8x8 is a four-level chain");
    assert.ok(created.usage & 0x10,
        "each level is rendered from the one above, so it is an attachment");

    // The chain has to be filled between the upload and the draw that samples
    // it -- not at some later point, and not never.
    assert.equal(executor.stats.mipChainsGenerated, 1);
    assert.equal(executor.stats.mipLevelsGenerated, 3, "levels 1..3");
    // And it must not be reported as an incomplete upload: the app only ever
    // supplies level 0 by design.
    assert.equal(executor.stats.drawsWithIncompleteMipChain, 0);
});

await test("an untouched scratch texture is not an incomplete mip chain",
        async () => {
    const D3DFMT_X8R8G8B8 = 22;
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 60)),
        // 3DMark 99 creates and binds its dynamic frame-capture texture before
        // the first DirectDraw Blt fills it. A wholly untouched single-level
        // allocation is not evidence that the proxy lost a subresource write.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xE10, 256, 256, 1, D3DFMT_X8R8G8B8, 0, 0)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0xE10, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithIncompleteMipChain, 0,
        "a texture with no writes must not masquerade as a partial chain");
});

await test("a partially uploaded mip chain still reports missing levels",
        async () => {
    const D3DFMT_A8R8G8B8 = 21;
    const { executor } = makeExecutor();
    const update = Buffer.alloc(48);
    update.writeUInt32LE(0xE11, 0);
    update.writeUInt32LE(0, 4);    // level
    update.writeUInt32LE(0, 8);    // x
    update.writeUInt32LE(0, 12);   // y
    update.writeUInt32LE(0, 16);   // z
    update.writeUInt32LE(4, 20);   // width
    update.writeUInt32LE(4, 24);   // height
    update.writeUInt32LE(1, 28);   // depth
    update.writeUInt32LE(16, 32);  // row pitch
    update.writeUInt32LE(0, 36);   // slice pitch
    update.writeUInt32LE(64, 40);  // data bytes
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 60)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xE11, 4, 4, 3, D3DFMT_A8R8G8B8, 0, 0)),
        command(OP.UPDATE_TEXTURE, update, Buffer.alloc(64, 0x80), 44),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0xE11, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.drawsWithIncompleteMipChain, 1,
        "writing only level 0 of a three-level chain remains diagnostic");
});

await test("an autogen chain is regenerated only when level 0 changes",
        async () => {
    const D3DUSAGE_AUTOGENMIPMAP = 0x400;
    const D3DFMT_A8R8G8B8 = 21;
    const { executor } = makeExecutor();
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    // A factory, not an array: buildBatch() stamps size/offset onto each
    // command object, so reusing one twice rewrites the first copy's framing.
    const draw = () => [
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0xE02, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ];
    const update = Buffer.alloc(48);
    update.writeUInt32LE(0xE02, 0);
    update.writeUInt32LE(8, 20);
    update.writeUInt32LE(8, 24);
    update.writeUInt32LE(1, 28);
    update.writeUInt32LE(32, 32);
    update.writeUInt32LE(256, 40);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xE02, 8, 8, 1, D3DFMT_A8R8G8B8,
                D3DUSAGE_AUTOGENMIPMAP, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.UPDATE_TEXTURE, update, Buffer.alloc(256, 0x80), 44),
        ...draw(),
        // Sampling again without touching level 0 must not rebuild anything.
        ...draw(),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.mipChainsGenerated, 1,
        "a clean chain is not rebuilt on every draw");

    // An explicit GenerateMipSubLevels rebuilds regardless.
    await executor.submit(buildBatch([
        command(OP.GENERATE_MIPS, u32(DEVICE, 0xE02)),
    ]));
    await executor.idle();
    assert.equal(executor.stats.explicitMipGenerations, 1);
    assert.equal(executor.stats.mipChainsGenerated, 2);
});

await test("two depth surfaces of one size get separate substitutes",
        async () => {
    const D3DUSAGE_DEPTHSTENCIL = 2;
    const D3DUSAGE_RENDERTARGET = 1;
    const D3DFMT_D24S8 = 75;
    const D3DFMT_A8R8G8B8 = 21;
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480, 0)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        // Two full-size depth surfaces, two half-size targets. Sharing one
        // substitute across both passes would let them depth-test against
        // each other's fragments.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xD01, 640, 480, 1, D3DFMT_D24S8, D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xD02, 640, 480, 1, D3DFMT_D24S8, D3DUSAGE_DEPTHSTENCIL, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xD03, 320, 240, 1, D3DFMT_A8R8G8B8, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0xD03, 0, 0)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL, u32(DEVICE, 0xD01, 0, 640, 480)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL, u32(DEVICE, 0xD02, 0, 640, 480)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.depthTargetSubstitutions, 2);
    const substitutes = find("createTexture").filter(call =>
        call[1].label && call[1].label.startsWith("D3D9 substitute depth"));
    assert.equal(substitutes.length, 2,
        "each depth surface needs its own stand-in, not one shared by size");
});

await test("packed 4:2:2 and RGBG formats expand two pixels per block",
        async () => {
    const { executor, find } = makeExecutor();
    const D3DFMT_YUY2 = 0x32595559;
    const D3DFMT_UYVY = 0x59565955;
    const D3DFMT_R8G8_B8G8 = 0x47424752;
    const D3DFMT_G8R8_G8B8 = 0x42475247;
    // BT.601 studio swing: Y=16 is black, Y=235 white, neutral chroma at 128.
    const cases = [
        // Y0 U Y1 V -- black then white, both neutral.
        { name: "YUY2", format: D3DFMT_YUY2, source: [16, 128, 235, 128] },
        // U Y0 V Y1 -- same two pixels, chroma first.
        { name: "UYVY", format: D3DFMT_UYVY, source: [128, 16, 128, 235] },
        // R G0 B G1 -- shared red and blue, per-pixel green.
        { name: "RGBG", format: D3DFMT_R8G8_B8G8, source: [10, 0, 30, 255],
          expected: [[10, 0, 30, 255], [10, 255, 30, 255]] },
        // G0 R G1 B -- the same pair, bytes reordered.
        { name: "GRGB", format: D3DFMT_G8R8_G8B8, source: [0, 10, 255, 30],
          expected: [[10, 0, 30, 255], [10, 255, 30, 255]] },
    ];
    const commands = [command(OP.CREATE_DEVICE, createDevicePayload(640, 480))];
    cases.forEach((item, index) => {
        const handle = 0x900 + index;
        const source = Buffer.from(item.source);
        const update = Buffer.alloc(48);
        update.writeUInt32LE(handle, 0);
        update.writeUInt32LE(2, 20); // width: one block is two pixels
        update.writeUInt32LE(1, 24); // height
        update.writeUInt32LE(1, 28); // depth
        update.writeUInt32LE(4, 32); // row pitch
        update.writeUInt32LE(4, 40); // data bytes
        commands.push(command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, handle, 2, 1, 1, item.format, 0, 1)));
        commands.push(command(OP.UPDATE_TEXTURE, update, source, 44));
    });
    await executor.submit(buildBatch(commands));
    await executor.idle();

    assert.equal(executor.stats.texturesRejected, 0,
        "every packed format must be accepted");
    const writes = find("writeTexture").slice(-cases.length);
    cases.forEach((item, index) => {
        const data = Array.from(writes[index][2]);
        assert.equal(data.length, 8, item.name + ": two RGBA8 pixels");
        if (item.expected) {
            assert.deepEqual(data, item.expected.flat(),
                item.name + ": the pair shares chroma and differs in green");
            return;
        }
        // YUV: neutral chroma means grey, and the two luma values must not
        // come out equal -- that is the failure a naive "use byte 0 twice"
        // expansion produces, and it looks like a plausible dark image.
        assert.ok(data[0] < 40 && data[1] < 40 && data[2] < 40,
            item.name + ": Y=16 is black, got " + data.slice(0, 3));
        assert.ok(data[4] > 215 && data[5] > 215 && data[6] > 215,
            item.name + ": Y=235 is white, got " + data.slice(4, 7));
    });
});

await test("INDEX16 and INDEX32 texture uploads preserve little-endian bytes",
        async () => {
    const { executor, find } = makeExecutor();
    const cases = [
        { name: "INDEX16", format: 101, source: [0x34, 0x12],
          expected: [0x34, 0x12, 0x00, 0xff] },
        { name: "INDEX32", format: 102, source: [0x78, 0x56, 0x34, 0x12],
          expected: [0x78, 0x56, 0x34, 0x12] },
    ];
    const commands = [command(OP.CREATE_DEVICE, createDevicePayload(640, 480))];
    cases.forEach((item, index) => {
        const handle = 0x920 + index;
        const source = Buffer.from(item.source);
        const update = Buffer.alloc(48);
        update.writeUInt32LE(handle, 0);
        update.writeUInt32LE(1, 20);
        update.writeUInt32LE(1, 24);
        update.writeUInt32LE(1, 28);
        update.writeUInt32LE(source.length, 32);
        update.writeUInt32LE(source.length, 40);
        commands.push(command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, handle, 1, 1, 1, item.format, 0, 1)));
        commands.push(command(OP.UPDATE_TEXTURE, update, source, 44));
    });
    await executor.submit(buildBatch(commands));
    await executor.idle();

    assert.equal(executor.stats.texturesRejected, 0,
        "both index formats must be accepted as textures");
    const writes = find("writeTexture").slice(-cases.length);
    cases.forEach((item, index) => {
        assert.deepEqual(Array.from(writes[index][2]), item.expected,
            item.name + ": exact index bytes survive RGBA8 expansion");
    });
});

await test("a palette change repaints P8 textures without a re-upload",
        async () => {
    const D3DFMT_P8 = 41;
    const { executor, find } = makeExecutor();
    const paletteCommand = (index, colorFor) => {
        const payload = Buffer.alloc(16);
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(index, 4);
        payload.writeUInt32LE(256, 8);
        const blob = Buffer.alloc(256 * 4);
        for (let entry = 0; entry < 256; ++entry)
            blob.writeUInt32LE(colorFor(entry) >>> 0, entry * 4);
        return command(OP.SET_PALETTE, payload, blob, 12);
    };
    // Index 1 is opaque red under palette 0, opaque blue under palette 1.
    const indices = Buffer.from([1, 1, 1, 1]);
    const update = Buffer.alloc(48);
    update.writeUInt32LE(0xA01, 0);
    update.writeUInt32LE(2, 20);
    update.writeUInt32LE(2, 24);
    update.writeUInt32LE(1, 28);
    update.writeUInt32LE(2, 32);  // row pitch: one byte per texel
    update.writeUInt32LE(4, 40);

    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        paletteCommand(0, entry => entry === 1 ? 0xffff0000 : 0xff000000),
        paletteCommand(1, entry => entry === 1 ? 0xff0000ff : 0xff000000),
        command(OP.SET_CURRENT_PALETTE, u32(DEVICE, 0)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0xA01, 2, 2, 1, D3DFMT_P8, 0, 1)),
        command(OP.UPDATE_TEXTURE, update, indices, 44),
    ]));
    await executor.idle();

    assert.equal(executor.stats.palettesSet, 2);
    assert.equal(executor.stats.texturesRejected, 0);
    const first = Array.from(find("writeTexture").pop()[2]).slice(0, 4);
    assert.deepEqual(first, [255, 0, 0, 255],
        "palette 0 makes index 1 red");

    // The whole point of a palettized format: switching tables repaints the
    // texture with no new upload from the guest.
    const uploadsBefore = executor.stats.textureUploads;
    await executor.submit(buildBatch([
        command(OP.SET_CURRENT_PALETTE, u32(DEVICE, 1)),
    ]));
    await executor.idle();

    assert.equal(executor.stats.textureUploads, uploadsBefore,
        "a palette swap is not a guest upload");
    assert.equal(executor.stats.palettizedRepaints, 1);
    const second = Array.from(find("writeTexture").pop()[2]).slice(0, 4);
    assert.deepEqual(second, [0, 0, 255, 255],
        "palette 1 makes the same indices blue");
});

await test("FOURCC depth textures read the stored value, not a comparison",
        async () => {
    const D3DFMT_INTZ = 0x5A544E49;
    const { executor, find } = makeExecutor();
    const ps = shaderCreatePayload(0x40000003, PS_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        // INTZ is routinely created with usage 0 and then used as depth.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0xB01, 256, 256, 1, D3DFMT_INTZ, 0, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.CREATE_PIXEL_SHADER, ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000003)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0xB01, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.commandsFailed, 0);
    assert.equal(executor.stats.droppedDraws, 0);
    const created = find("createTexture").find(call =>
        call[1].label === "D3D9 depth surface");
    assert.ok(created, "a FOURCC depth format allocates a depth target");

    // Depth sample type, but an ordinary sampler: a raw fetch does not compare.
    const layout = find("createBindGroupLayout").pop()[1];
    assert.equal(layout.entries.find(e => e.binding === 2).texture.sampleType,
        "depth");
    assert.equal(layout.entries.find(e => e.binding === 3).sampler.type,
        "non-filtering",
        "an INTZ fetch reads through a plain sampler, not a comparison one");
    assert.ok(find("createShaderModule").some(call =>
        call[1].code.includes("texture_depth_2d") &&
        !call[1].code.includes("sampler_comparison")),
        "the stage must be a depth fetch, not a shadow-map comparison");
});

await test("a cube render target attaches one face per pass", async () => {
    const D3DUSAGE_RENDERTARGET = 1;
    const { executor, fake, find } = makeExecutor();
    // SetRenderTarget with the protocol-1.4 face field.
    const setCubeTarget = face =>
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0x601, 0, face));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(0x111, u32(DEVICE, 0x601, 64, 1, 21, D3DUSAGE_RENDERTARGET, 0, 0)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        // The environment-map idiom: render the scene once per face.
        ...[0, 1, 2, 3, 4, 5].flatMap(face => [
            setCubeTarget(face),
            command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        ]),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.commandsFailed, 0);
    const created = find("createTexture").find(call =>
        call[1].label === "D3D9 cube 64")[1];
    assert.ok(created.usage & 0x10,
        "a cube render target needs the attachment usage");

    // Six distinct attachment views, one per layer. Before the face reached
    // the host every one of these was layer 0, so five faces of an environment
    // map were painted over the first.
    const attachmentLayers = find("createView")
        .filter(call => call[2] && call[2].arrayLayerCount === 1 &&
            call[2].mipLevelCount === 1)
        .map(call => call[2].baseArrayLayer);
    for (const face of [0, 1, 2, 3, 4, 5])
        assert.ok(attachmentLayers.includes(face),
            "face " + face + " must get its own attachment view");
    assert.equal(executor.stats.cubeFaceTargetBinds, 5,
        "faces 1..5 are non-zero binds");

    // And they must not be merged into one pass: same texture, different
    // subresource, so the pass key has to separate them.
    const passes = fake.calls.filter(call => call[0] === "beginRenderPass");
    assert.ok(passes.length >= 6,
        "each face is its own render pass, got " + passes.length);
});

await test("a cube texture binds as a cube view and uploads per face",
        async () => {
    const { executor, find } = makeExecutor();
    const face = (index, level) => {
        const payload = Buffer.alloc(48);
        payload.writeUInt32LE(0x601, 0);
        payload.writeUInt32LE(level, 4);
        payload.writeUInt32LE(0, 8);   // x
        payload.writeUInt32LE(0, 12);  // y
        payload.writeUInt32LE(index, 16); // z == cube face
        payload.writeUInt32LE(4, 20);  // width
        payload.writeUInt32LE(4, 24);  // height
        payload.writeUInt32LE(1, 28);  // depth
        payload.writeUInt32LE(16, 32); // row pitch
        payload.writeUInt32LE(0, 36);
        payload.writeUInt32LE(64, 40); // data bytes
        return { payload, blob: Buffer.alloc(64, index + 1), field: 44 };
    };
    const uploads = [0, 1, 2, 3, 4, 5].map(index => face(index, 0));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(0x111, u32(DEVICE, 0x601, 4, 1, 21, 0, 1, 0)),
        ...uploads.map(upload =>
            command(OP.UPDATE_TEXTURE, upload.payload, upload.blob, upload.field)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x601, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.cubeTexturesCreated, 1);
    assert.equal(executor.stats.textureUploads, 6, "one upload per face");
    assert.equal(executor.stats.drawsWithIncompleteMipChain, 0,
        "all six faces of the single level were uploaded");

    const created = find("createTexture").find(call =>
        call[1].label === "D3D9 cube 4")[1];
    assert.equal(created.size.depthOrArrayLayers, 6,
        "a cube is six array layers");
    assert.ok(find("createView").some(call =>
        call[2] && call[2].dimension === "cube"),
        "the sampled view has to be a cube view");
    // Each face has to land on its own layer, or five of them overwrite one.
    const layers = find("writeTexture")
        .filter(call => call[1] && call[1].origin)
        .map(call => call[1].origin.z);
    assert.deepEqual(layers, [0, 1, 2, 3, 4, 5]);
    // And the fixed-function cascade has to sample it as a cube.
    const wgsl = find("createRenderPipeline").pop()[1].fragment.module.code;
    assert.ok(wgsl.includes("texture_cube<f32>"),
        "the cascade must declare a cube sampler:\n" + wgsl);
});

await test("legacy D3D9 texture formats preserve colour and signed bump values",
        async () => {
    const { executor, find } = makeExecutor();
    const halfMinusOne = [0x00, 0xbc];
    const halfZero = [0x00, 0x00];
    const halfHalf = [0x00, 0x38];
    const halfOne = [0x00, 0x3c];
    const cases = [
        { format: 20, gpu: "rgba8unorm", source: [0x33, 0x22, 0x11],
          expected: [0x11, 0x22, 0x33, 0xff] }, // R8G8B8: B,G,R
        { format: 27, gpu: "rgba8unorm", source: [0xe3],
          expected: [0xff, 0x00, 0xff, 0xff] },
        { format: 29, gpu: "rgba8unorm", source: [0xe3, 0x80],
          expected: [0xff, 0x00, 0xff, 0x80] },
        { format: 30, gpu: "rgba8unorm", source: [0x23, 0xf1],
          expected: [0x11, 0x22, 0x33, 0xff] },
        { format: 32, gpu: "rgba8unorm", source: [0x11, 0x22, 0x33, 0x44],
          expected: [0x11, 0x22, 0x33, 0x44] },
        { format: 33, gpu: "rgba8unorm", source: [0x11, 0x22, 0x33, 0x44],
          expected: [0x11, 0x22, 0x33, 0xff] },
        { format: 28, gpu: "rgba8unorm", source: [0x40],
          expected: [0x00, 0x00, 0x00, 0x40] }, // A8 missing RGB is zero
        { format: 51, gpu: "rgba8unorm", source: [0x40, 0x80],
          expected: [0x40, 0x40, 0x40, 0x80] },
        { format: 52, gpu: "rgba8unorm", source: [0xa5],
          expected: [0x55, 0x55, 0x55, 0xaa] },
        { format: 81, gpu: "rgba16float", source: [0x00, 0x80],
          expected: [...halfHalf, ...halfHalf, ...halfHalf, ...halfOne] },
        // 10:10:10:2 and 16-bit integer formats are expanded to RGBA16F so
        // sampling and blending preserve their precision and component order.
        { format: 31, gpu: "rgba16float", source: [0xff, 0x03, 0x00, 0xc0],
          expected: [...halfOne, ...halfZero, ...halfZero, ...halfOne] },
        { format: 35, gpu: "rgba16float", source: [0x00, 0x00, 0xf0, 0xff],
          expected: [...halfOne, ...halfZero, ...halfZero, ...halfOne] },
        { format: 34, gpu: "rgba16float", source: [0x00, 0x80, 0xff, 0xff],
          expected: [...halfHalf, ...halfOne, ...halfZero, ...halfOne] },
        { format: 36, gpu: "rgba16float",
          source: [0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff],
          expected: [...halfZero, ...halfHalf, ...halfOne, ...halfOne] },
        // D3D half-float texels already have the exact representation WebGPU
        // needs; missing channels receive D3D's documented (0,0,1) defaults.
        { format: 111, gpu: "rgba16float", source: halfHalf,
          expected: [...halfHalf, ...halfZero, ...halfZero, ...halfOne] },
        { format: 112, gpu: "rgba16float",
          source: [...halfHalf, ...halfOne],
          expected: [...halfHalf, ...halfOne, ...halfZero, ...halfOne] },
        { format: 113, gpu: "rgba16float",
          source: [...halfHalf, ...halfZero, ...halfOne, ...halfOne],
          expected: [...halfHalf, ...halfZero, ...halfOne, ...halfOne] },
        // WebGPU has native 32-bit float texture formats.  Their texels must
        // remain bit-exact: CPU conversion would both waste time and destroy
        // NaN/Inf payloads an HDR post-process is entitled to preserve.
        { format: 114, gpu: "r32float",
          source: [0x00, 0x00, 0x00, 0x3f],
          expected: [0x00, 0x00, 0x00, 0x3f] },
        { format: 115, gpu: "rg32float",
          source: [0x00, 0x00, 0x00, 0x3f,
                   0x00, 0x00, 0x80, 0x3f],
          expected: [0x00, 0x00, 0x00, 0x3f,
                     0x00, 0x00, 0x80, 0x3f] },
        { format: 116, gpu: "rgba32float",
          source: [0x00, 0x00, 0x00, 0x3f,
                   0x00, 0x00, 0x80, 0x3f,
                   0x00, 0x00, 0x00, 0x40,
                   0x00, 0x00, 0x40, 0x40],
          expected: [0x00, 0x00, 0x00, 0x3f,
                     0x00, 0x00, 0x80, 0x3f,
                     0x00, 0x00, 0x00, 0x40,
                     0x00, 0x00, 0x40, 0x40] },
        { format: 60, gpu: "rgba8snorm", source: [0x80, 0x7f],
          expected: [0x80, 0x7f, 0x7f, 0x7f] },
        { format: 63, gpu: "rgba8snorm", source: [0x80, 0xc0, 0x40, 0x7f],
          expected: [0x80, 0xc0, 0x40, 0x7f] },
        { format: 61, gpu: "rgba16float", source: [0xf0, 0xfd],
          expected: [...halfMinusOne, ...halfOne, ...halfOne, ...halfOne] },
        { format: 62, gpu: "rgba16float", source: [0x80, 0x7f, 0xff, 0],
          expected: [...halfMinusOne, ...halfOne, ...halfOne, ...halfOne] },
        { format: 64, gpu: "rgba16float", source: [0x00, 0x80, 0xff, 0x7f],
          expected: [...halfMinusOne, ...halfOne, ...halfOne, ...halfOne] },
        // W11V11U10: U is 10 signed bits at 0-9, V and W are 11 each at
        // 10-20 and 21-31. 0x7FEFFE00 is (u,v,w) = (-1, +1, +1).
        { format: 65, gpu: "rgba16float", source: [0x00, 0xfe, 0xef, 0x7f],
          expected: [...halfMinusOne, ...halfOne, ...halfOne, ...halfOne] },
        { format: 67, gpu: "rgba16float", source: [0x00, 0xfe, 0x07, 0xc0],
          expected: [...halfMinusOne, ...halfOne, ...halfZero, ...halfOne] },
        { format: 117, gpu: "rgba16float", source: [0x80, 0x00],
          expected: [...halfMinusOne, ...halfZero, ...halfZero, ...halfOne] },
    ];
    const commands = [command(OP.CREATE_DEVICE, createDevicePayload(640, 480))];
    cases.forEach((item, index) => {
        const handle = 0x700 + index;
        const source = Buffer.from(item.source);
        const update = Buffer.alloc(48);
        update.writeUInt32LE(handle, 0);
        update.writeUInt32LE(1, 20); // width
        update.writeUInt32LE(1, 24); // height
        update.writeUInt32LE(1, 28); // depth
        update.writeUInt32LE(source.length, 32); // source row pitch
        update.writeUInt32LE(source.length, 40);
        commands.push(command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, handle, 1, 1, 1, item.format, 0, 1)));
        commands.push(command(OP.UPDATE_TEXTURE, update, source, 44));
    });
    await executor.submit(buildBatch(commands));
    await executor.idle();
    assert.equal(executor.stats.texturesRejected, 0);
    const descriptors = find("createTexture").slice(-cases.length)
        .map(call => call[1]);
    const writes = find("writeTexture").slice(-cases.length);
    cases.forEach((item, index) => {
        assert.equal(descriptors[index].format, item.gpu,
            "wrong GPU format for D3DFMT " + item.format);
        if (item.gpu === "rgba8snorm")
            assert.equal(descriptors[index].usage & 0x10, 0,
                "SNORM textures must not request RENDER_ATTACHMENT");
        assert.deepEqual(Array.from(writes[index][2]), item.expected,
            "wrong texel conversion for D3DFMT " + item.format);
        assert.equal(writes[index][3].bytesPerRow, item.expected.length);
    });
});

await test("HDR render targets use a blendable rgba16float attachment",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x76f, 320, 180, 1, 113, 1, 0)),
        command(OP.SET_RENDER_TARGET, u32(DEVICE, 0, 0x76f, 0)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff102030, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.texturesRejected, 0);
    const texture = find("createTexture").find(call =>
        call[1].label === "D3D9 render target");
    assert.ok(texture, "A16B16G16R16F must allocate a render target");
    assert.equal(texture[1].format, "rgba16float");
    assert.ok(texture[1].usage & 0x10,
        "the HDR texture must carry RENDER_ATTACHMENT usage");
    assert.ok(find("beginRenderPass").some(call =>
        call[1].colorAttachments?.[0]?.view?.texture === texture[2]));
});

await test("FP32 textures use unfilterable bindings on baseline WebGPU",
        async () => {
    const { executor, find } = makeExecutor();
    const tss = (stage, state, value) =>
        command(0x202, u32(DEVICE, stage, state, value));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x780, 1, 60)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x781, 4, 4, 1, 114 /* R32F */, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x780, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x781, 0)),
        // Ask for linear filtering.  A baseline device without the optional
        // float32-filterable feature must legally degrade this one sampler to
        // nearest instead of creating an invalid bind group.
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 5, 2)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 6, 2)),
        tss(0, D3DTSS.COLOROP, D3DTOP.SELECTARG1),
        tss(0, D3DTSS.COLORARG1, D3DTA.TEXTURE),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    const layout = find("createBindGroupLayout").find(call =>
        call[1].entries.some(entry => entry.binding === 2));
    assert.ok(layout, "sampled FP32 draw needs a texture binding layout");
    assert.equal(layout[1].entries.find(entry => entry.binding === 2)
        .texture.sampleType, "unfilterable-float");
    assert.equal(layout[1].entries.find(entry => entry.binding === 3)
        .sampler.type, "non-filtering");
    const sampler = find("createSampler").pop()[1];
    assert.equal(sampler.minFilter, "nearest");
    assert.equal(sampler.magFilter, "nearest");
});

await test("signed textures reject render-target use but keep direct copies",
        async () => {
    const { executor, find } = makeExecutor();
    const stretch = (destinationSize) => {
        const payload = Buffer.alloc(56);
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(0x771, 4);
        payload.writeUInt32LE(0, 8);
        [0, 0, 4, 4].forEach((value, index) =>
            payload.writeInt32LE(value, 12 + index * 4));
        payload.writeUInt32LE(0x772, 28);
        payload.writeUInt32LE(0, 32);
        [0, 0, destinationSize, destinationSize].forEach((value, index) =>
            payload.writeInt32LE(value, 36 + index * 4));
        return payload;
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        // A stale or malformed guest must not make the host create an illegal
        // rgba8snorm RENDER_ATTACHMENT descriptor.
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x770, 4, 4, 1, 60, 1, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x771, 4, 4, 1, 60, 0, 1)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x772, 4, 4, 1, 60, 0, 1)),
        command(0x8, stretch(4)),
        command(0x8, stretch(2)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.texturesRejected, 1);
    assert.equal(executor.stats.blits, 1,
        "same-size same-format signed textures can use a GPU copy");
    assert.equal(executor.stats.blitsSkipped, 1,
        "scaling cannot render into an rgba8snorm texture");
    // Present's own back-buffer-to-canvas copy is not one of the blits.
    assert.equal(find("copyTextureToTexture").filter(call =>
        call[1].texture !== executor.backBufferTexture).length, 1);
    assert.ok(!find("createTexture").some(call =>
        call[1].format === "rgba8snorm" && (call[1].usage & 0x10)),
        "rgba8snorm must never request RENDER_ATTACHMENT");
});

await test("R8G8B8 upload honours a padded source pitch", async () => {
    const { executor, find } = makeExecutor();
    const source = Buffer.from([
        0x30, 0x20, 0x10, 0xee,
        0x60, 0x50, 0x40, 0xee,
    ]);
    const update = Buffer.alloc(48);
    update.writeUInt32LE(0x750, 0);
    update.writeUInt32LE(1, 20);
    update.writeUInt32LE(2, 24);
    update.writeUInt32LE(1, 28);
    update.writeUInt32LE(4, 32);
    update.writeUInt32LE(source.length, 40);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x750, 1, 2, 1, 20, 0, 1)),
        command(OP.UPDATE_TEXTURE, update, source, 44),
    ]));
    await executor.idle();
    const write = find("writeTexture").pop();
    assert.deepEqual(Array.from(write[2]), [
        0x10, 0x20, 0x30, 0xff,
        0x40, 0x50, 0x60, 0xff,
    ]);
    assert.equal(write[3].bytesPerRow, 4);
    assert.equal(write[3].rowsPerImage, 2);
});

await test("DXT2 and DXT4 reuse BC2 and BC3 block storage", async () => {
    const { executor, find } = makeExecutor();
    const commands = [command(OP.CREATE_DEVICE, createDevicePayload(640, 480))];
    [
        { handle: 0x760, format: 0x32545844, gpu: "bc2-rgba-unorm" },
        { handle: 0x761, format: 0x34545844, gpu: "bc3-rgba-unorm" },
    ].forEach(item => {
        const update = Buffer.alloc(48);
        update.writeUInt32LE(item.handle, 0);
        update.writeUInt32LE(4, 20);
        update.writeUInt32LE(4, 24);
        update.writeUInt32LE(1, 28);
        update.writeUInt32LE(16, 32);
        update.writeUInt32LE(16, 40);
        commands.push(command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, item.handle, 4, 4, 1, item.format, 0, 1)));
        commands.push(command(OP.UPDATE_TEXTURE, update,
            Buffer.alloc(16, item.handle & 0xff), 44));
    });
    await executor.submit(buildBatch(commands));
    await executor.idle();
    assert.deepEqual(find("createTexture").slice(-2).map(call => call[1].format),
        ["bc2-rgba-unorm", "bc3-rgba-unorm"]);
    assert.deepEqual(find("writeTexture").slice(-2).map(call => call[3]), [
        { bytesPerRow: 16, rowsPerImage: 1 },
        { bytesPerRow: 16, rowsPerImage: 1 },
    ]);
});

await test("exhausting the debug preview budget never drops a game texture upload",
        async () => {
    const { executor, find } = makeExecutor();
    executor.previewBudget = 0;
    const payload = Buffer.alloc(48);
    payload.writeUInt32LE(0x611, 0);
    payload.writeUInt32LE(0, 4);
    payload.writeUInt32LE(0, 8);
    payload.writeUInt32LE(0, 12);
    payload.writeUInt32LE(0, 16);
    payload.writeUInt32LE(4, 20);
    payload.writeUInt32LE(4, 24);
    payload.writeUInt32LE(1, 28);
    payload.writeUInt32LE(16, 32);
    payload.writeUInt32LE(0, 36);
    payload.writeUInt32LE(64, 40);
    await executor.submit(buildBatch([
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x611, 4, 4, 1, 21, 0, 1)),
        command(OP.UPDATE_TEXTURE, payload, Buffer.alloc(64, 0x7f), 44),
    ]));
    await executor.idle();
    assert.equal(executor.stats.texturePreviewsSkipped, 1,
        "the bounded diagnostic copy should be skipped");
    assert.equal(executor.stats.textureUploads, 1,
        "the actual upload must still be counted");
    assert.ok(find("writeTexture").some(call =>
        call[1].texture && call[1].texture.descriptor.size.width === 4),
        "preview exhaustion must not bypass queue.writeTexture");
});

await test("a texture updated after a recorded draw is renamed", async () => {
    const { executor, find } = makeExecutor();
    const upload = fill => {
        const payload = Buffer.alloc(48);
        payload.writeUInt32LE(0x612, 0);
        payload.writeUInt32LE(0, 4);
        payload.writeUInt32LE(0, 8);
        payload.writeUInt32LE(0, 12);
        payload.writeUInt32LE(0, 16);
        payload.writeUInt32LE(4, 20);
        payload.writeUInt32LE(4, 24);
        payload.writeUInt32LE(1, 28);
        payload.writeUInt32LE(16, 32);
        payload.writeUInt32LE(0, 36);
        payload.writeUInt32LE(64, 40);
        return command(OP.UPDATE_TEXTURE, payload, Buffer.alloc(64, fill), 44);
    };
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 60)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x612, 4, 4, 1, 21, 0, 1)),
        upload(0x11),
        command(OP.SET_FVF, fvfPayload(0x102, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x612, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        upload(0x22),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.textureUpdateHazards, 1);
    assert.equal(executor.stats.textureRenames, 1);
    const groups = find("createBindGroup").filter(call =>
        call[1].entries.some(entry => entry.binding === 2));
    assert.equal(groups.length, 2);
    const firstView = groups[0][1].entries.find(entry => entry.binding === 2).resource;
    const secondView = groups[1][1].entries.find(entry => entry.binding === 2).resource;
    assert.notEqual(firstView.texture, secondView.texture,
        "the earlier bind group must retain the old GPU texture");
});

await test("D3DRS_SCISSORTESTENABLE gates the scissor rect", async () => {
    const { executor, find } = makeExecutor();
    const scissor = Buffer.alloc(20);
    scissor.writeUInt32LE(DEVICE, 0);
    scissor.writeInt32LE(10, 4);
    scissor.writeInt32LE(20, 8);
    scissor.writeInt32LE(110, 12);
    scissor.writeInt32LE(220, 16);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(0x205, scissor),
        // Rect set but the test disabled: D3D9 ignores it.
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS.SCISSORTESTENABLE, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithScissor, 1,
        "only the draw with the test enabled is scissored");
    // Every draw carries a clip rect, because a D3D9 viewport clips and a
    // WebGPU one does not. With the test off that rect is the full viewport;
    // with it on it is the viewport intersected with the app's rect, which D3D9
    // also applies on top of the viewport rather than instead of it.
    const calls = find("setScissorRect");
    assert.equal(calls.length, 2, "each draw sets its own clip rect");
    assert.deepEqual(calls[0].slice(1), [0, 0, 640, 480],
        "with the test disabled the clip rect is the whole viewport");
    assert.deepEqual(calls[1].slice(1), [10, 20, 100, 200]);
});

// A D3D9 viewport clips geometry; WebGPU's setViewport only maps NDC to pixels.
// Nothing else would cut a draw off at the viewport edge, so a game that
// restricts a small panel with SetViewport alone had its geometry drawn across
// the whole target instead.
await test("a viewport clips, and carries its D3D9 depth range", async () => {
    const { executor, find } = makeExecutor();
    const viewport = Buffer.alloc(32);
    viewport.writeUInt32LE(DEVICE, 0);
    viewport.writeUInt32LE(64, 4);    // x
    viewport.writeUInt32LE(48, 8);    // y
    viewport.writeUInt32LE(128, 12);  // width
    viewport.writeUInt32LE(96, 16);   // height
    viewport.writeFloatLE(0.25, 20);  // MinZ
    viewport.writeFloatLE(0.5, 24);   // MaxZ
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_VIEWPORT, viewport),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.deepEqual(find("setScissorRect").pop().slice(1), [64, 48, 128, 96],
        "the clip rect has to follow the viewport with no app scissor set");
    // MinZ/MaxZ have always been on the wire; they used to be dropped here.
    const pass = find("beginRenderPass").pop()[2];
    assert.deepEqual(pass.ops.find(op => op[0] === "viewport").slice(1),
        [64, 48, 128, 96, 0.25, 0.5]);
});

await test("concurrent guest sessions keep colliding handles isolated",
        async () => {
    const { executor } = makeExecutor();
    const hello = (low, high) => {
        const payload = Buffer.alloc(16);
        payload.writeUInt32LE(32, 0);
        payload.writeUInt32LE(3, 4); // SM2 | SM3
        payload.writeUInt32LE(low, 8);
        payload.writeUInt32LE(high, 12);
        return command(OP.HELLO, payload);
    };
    await executor.submit(buildBatch([
        hello(0x1001, 0xfedcba98),
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
    ], { sessionLow: 0x1001, sessionHigh: 0xfedcba98 }));
    await executor.idle();
    assert.equal(executor.resources.size, 1);
    assert.equal(executor.stats.sessionChanges, 0);
    assert.equal(executor.resources.get(0x201).byteCount, 96);

    // A Futuremark helper process is alive concurrently and reuses both the
    // device and buffer handles. Its objects must occupy another namespace,
    // without destroying the benchmark process's resources. The two 64-bit
    // IDs differ only in their low bit, so converting them to Number would
    // round them together above 2^53.
    await executor.submit(buildBatch([
        hello(0x1002, 0xfedcba98),
        command(OP.CREATE_DEVICE, createDevicePayload(320, 240)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 128)),
    ], { sessionLow: 0x1002, sessionHigh: 0xfedcba98 }));
    await executor.idle();
    assert.equal(executor.stats.sessionChanges, 1);
    assert.equal(executor.resources.get(0x201).byteCount, 128);

    // A later batch from the first process carries no HELLO. The batch header
    // alone must restore its exact resource table and in-flight state.
    await executor.submit(buildBatch([], {
        sessionLow: 0x1001, sessionHigh: 0xfedcba98,
    }));
    await executor.idle();
    assert.equal(executor.stats.sessionChanges, 2);
    assert.equal(executor.resources.get(0x201).byteCount, 96,
        "the benchmark process's buffer was replaced by its helper");
    assert.equal(executor.devices.get(DEVICE).backBufferWidth, 640);
    const stats = executor.getStats();
    assert.equal(stats.activeSession, "fedcba9800001001");
    assert.equal(stats.sessionsLive, 2);
    assert.equal(stats.devicesLive, 2);
    assert.equal(stats.resourcesLive, 2);
});

await test("a helper process cannot discard another session's in-flight frame",
        async () => {
    const { executor } = makeExecutor();
    const helloPayload = Buffer.alloc(16);
    helloPayload.writeUInt32LE(32, 0);
    helloPayload.writeUInt32LE(3, 4); // SM2 | SM3
    helloPayload.writeUInt32LE(0xa001, 8);
    await executor.submit(buildBatch([
        command(OP.HELLO, helloPayload),
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ], { sessionLow: 0xa001 }));
    await executor.idle();
    assert.ok(executor.frame, "the benchmark frame should remain pending");
    assert.equal(executor.stats.queueSubmits, 0,
        "the recorded frame must wait for Present before GPU submission");

    // 3DMark06 launches short-lived capability helpers while the benchmark
    // process is alive. Merely receiving their HELLO used to release every
    // resource and drop the benchmark's recorded draw operations.
    const helperHello = Buffer.from(helloPayload);
    helperHello.writeUInt32LE(0xb002, 8);
    await executor.submit(buildBatch([
        command(OP.HELLO, helperHello),
    ], { sessionLow: 0xb002 }));
    await executor.idle();
    assert.equal(executor.frame, null,
        "the helper must see its own empty frame context");

    await executor.submit(buildBatch([
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { sessionLow: 0xa001, present: true }));
    await executor.idle();
    assert.equal(executor.stats.drawCalls, 1,
        "the benchmark's draw command should be retained exactly once");
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.queueSubmits, 1);
});

await test("the device requests texture-compression-bc so DXT textures work",
        async () => {
    // Without this, every createTexture for a DXT format throws
    // ("requires the 'texture-compression-bc' feature") and takes the whole
    // batch -- and therefore the whole frame -- down with it. DXT1/3/5 is where
    // a D3D9 game of this era keeps nearly all of its art, so the symptom is a
    // blank screen, not a missing texture.
    const { executor, find, fake } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x401, 16, 16, 1, 0x33545844 /* DXT3 */, 0, 1)),
    ]));
    await executor.idle();
    const request = find("requestDevice").pop();
    assert.ok(request, "requestDevice must be observed");
    assert.deepEqual(request[1] && request[1].requiredFeatures,
        ["texture-compression-bc", "timestamp-query"],
        "the adapter's optional BC and timestamp features must be requested");
    const created = find("createTexture").map(call => call[1]);
    assert.ok(created.some(descriptor => descriptor.format === "bc2-rgba-unorm"),
        "DXT3 must reach WebGPU as bc2-rgba-unorm");
    assert.equal(executor.stats.texturesRejected, 0);
    assert.equal(executor.stats.malformedBatches, 0);
    assert.ok(!executor.failed, "a DXT texture must not fail the batch");
});

await test("a texture format the device refuses costs one texture, not the frame",
        async () => {
    const { executor, fake } = makeExecutor();
    const realCreateTexture = fake.device.createTexture.bind(fake.device);
    fake.device.createTexture = descriptor => {
        if (descriptor.format === "bc1-rgba-unorm")
            throw new Error("simulated: unsupported format");
        return realCreateTexture(descriptor);
    };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x401, 16, 16, 1, 0x31545844 /* DXT1 */, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.ok(!executor.failed, "the batch must survive one refused texture");
    assert.equal(executor.stats.texturesRejected, 1);
    assert.equal(executor.stats.droppedDraws, 0,
        "the draw still renders, with the white fallback bound");
    assert.equal(executor.stats.drawsWithFallbackTexture, 1);
    assert.equal(executor.stats.presents, 1);
});

await test("StretchRect from the back buffer becomes a deferred blit", async () => {
    // The back buffer has no view until Present (the swap chain texture is only
    // valid inside the task that acquired it), so this cannot be submitted where
    // the command arrives. Doing it eagerly is what produced "the host cannot
    // address this surface" -- and grabbing the frame into a texture is how a
    // D3D9 game does full-screen post-processing, so it is not a rare path.
    const D3DUSAGE_RENDERTARGET = 1;
    const stretch = (sourceHandle, destinationHandle) => {
        const payload = Buffer.alloc(56);
        payload.writeUInt32LE(DEVICE, 0);
        payload.writeUInt32LE(sourceHandle, 4);
        payload.writeUInt32LE(0, 8);
        [0, 0, 640, 480].forEach((v, i) => payload.writeInt32LE(v, 12 + i * 4));
        payload.writeUInt32LE(destinationHandle, 28);
        payload.writeUInt32LE(0, 32);
        [0, 0, 256, 256].forEach((v, i) => payload.writeInt32LE(v, 36 + i * 4));
        payload.writeUInt32LE(0, 52); // linear filter
        return payload;
    };
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x501, 256, 256, 1, 21, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff000000, 0, 0, 0)),
        // Source handle 0 == the back buffer.
        command(0x8, stretch(0, 0x501)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.ok(!executor.failed, executor.failed && executor.failed.message);
    assert.equal(executor.stats.blitsSkipped, 0,
        "a back-buffer StretchRect must no longer be skipped");
    assert.equal(executor.stats.blits, 1);
    assert.equal(executor.stats.blitsThroughBackBuffer, 1);

    // It has to run as its own pass, drawing the six-vertex quad, into the
    // texture -- not into the back buffer.
    const passes = find("beginRenderPass").map(call => call[2]);
    const blitPass = passes.find(pass =>
        pass.ops.some(op => op[0] === "draw" && op[1] === 6));
    assert.ok(blitPass, "the blit must draw its quad in a pass of its own");
    const viewport = blitPass.ops.find(op => op[0] === "viewport");
    assert.deepEqual(viewport.slice(1, 5), [0, 0, 256, 256],
        "the destination rect becomes the viewport");
    // The source rect reaches the shader normalised against the source size.
    const uniformWrite = find("writeBuffer").pop();
    assert.deepEqual([...new Float32Array(uniformWrite[6].buffer,
        uniformWrite[6].byteOffset, 4)], [0, 0, 1, 1]);
});

await test("D3DSAMP_SRGBTEXTURE samples through an -srgb view", async () => {
    // Ignoring it hands the shader values substantially brighter than the app
    // intends (sRGB 0.5 is linear 0.21), which on an additive environment
    // reflection reads as blown-out white rather than as a gamma difference.
    const D3DSAMP_SRGBTEXTURE = 11;
    const { executor, find } = makeExecutor();
    const draw = extra => [
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD, 0)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.SET_TEXTURE, u32(DEVICE, 0, 0x401, 0)),
        ...extra,
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 4, 4, 1, 21, 0, 1)),
        ...draw([]),
        ...draw([command(OP.SET_SAMPLER_STATE,
            u32(DEVICE, 0, D3DSAMP_SRGBTEXTURE, 1))]),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.srgbTextureSamples, 1,
        "only the second draw asked for sRGB decoding");
    assert.equal(executor.stats.srgbViewsCreated, 1);
    assert.equal(executor.stats.srgbTextureUnavailable, 0);

    // The texture has to declare the view format up front, or the view is
    // invalid however it is requested later.
    const created = find("createTexture")
        .map(call => call[1]).find(d => d.size.width === 4);
    assert.deepEqual(created.viewFormats, ["rgba8unorm-srgb"]);
    assert.ok(find("createView").some(call =>
        call[2] && call[2].format === "rgba8unorm-srgb"),
        "the second draw must sample through the -srgb view");
});

await test("D3DRS_SRGBWRITEENABLE renders through an -srgb target view", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, 194, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.srgbWriteRequests, 1);
    assert.equal(executor.stats.srgbWriteUnavailable, 0);
    assert.deepEqual(find("configure").pop()[1].viewFormats,
        ["bgra8unorm-srgb"]);
    assert.equal(find("createRenderPipeline").pop()[1]
        .fragment.targets[0].format, "bgra8unorm-srgb");
});

await test("a state nothing reads is listed rather than silently dropped",
        async () => {
    // The expensive failures on this path have all been silent: a state the app
    // clearly cares about that the renderer never looks at, producing a picture
    // that is wrong in a plausible way with nothing saying so.
    const D3DRS_WRAP0 = 128, D3DSAMP_MIPMAPLODBIAS = 8;
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_WRAP0, 3, 0)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, 22 /* CULLMODE, read */, 1, 0)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, D3DSAMP_MIPMAPLODBIAS, 1)),
        command(OP.SET_SAMPLER_STATE, u32(DEVICE, 0, 5 /* MAGFILTER, read */, 2)),
    ]));
    await executor.idle();
    assert.deepEqual(executor.stats.unreadStateIds, {
        renderStates: [D3DRS_WRAP0],
        samplerStates: [D3DSAMP_MIPMAPLODBIAS],
    }, "only the unread ones, and each listed once");
});

await test("M5 compact declarations feed skeletal shader inputs without CPU repacking",
        async () => {
    const { executor, find } = makeExecutor();
    const shader = shaderCreatePayload(0x40000021, VS_M5_SKINNING_INPUTS);
    const elements = [
        element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
        element(0, 12, DECLTYPE.UBYTE4N, DECLUSAGE.BLENDWEIGHT),
        element(0, 16, DECLTYPE.UBYTE4, DECLUSAGE.BLENDINDICES),
        element(0, 20, DECLTYPE.SHORT2, DECLUSAGE.TEXCOORD),
        element(0, 24, DECLTYPE.SHORT4, DECLUSAGE.TANGENT),
        element(0, 32, DECLTYPE.DEC3N, DECLUSAGE.NORMAL),
        element(0, 36, DECLTYPE.UDEC3, DECLUSAGE.BINORMAL),
    ];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 400)),
        command(OP.CREATE_VERTEX_DECLARATION,
            declarationPayload(0x30000021, elements)),
        command(OP.CREATE_VERTEX_SHADER, shader.payload, shader.blob,
            shader.blobOffsetField),
        command(OP.SET_VERTEX_DECLARATION, u32(DEVICE, 0x30000021)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000021)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 40)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.droppedDraws, 0);
    assert.equal(executor.stats.drawsWithCompactVertexInputs, 1);
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.deepEqual(pipeline.vertex.buffers[0].attributes.map(a => a.format),
        ["float32x3", "unorm8x4", "uint8x4", "sint16x2", "sint16x4",
            "uint32", "uint32"]);
    const wgsl = pipeline.vertex.module.code;
    assert.ok(wgsl.includes("@location(2) in2: vec4<u32>"));
    assert.ok(wgsl.includes("d9_unpack_dec3n(in5)"));
    assert.ok(wgsl.includes("d9_unpack_udec3(in6)"));
});

await test("shadow render states map to signed projection, exact blend and depth-stencil",
        async () => {
    const floatBitsOf = value => {
        const bits = new ArrayBuffer(4);
        new Float32Array(bits)[0] = value;
        return new Uint32Array(bits)[0];
    };
    const R = { SRCBLEND: 19, DESTBLEND: 20, ALPHABLENDENABLE: 27,
        STENCILENABLE: 52, STENCILFAIL: 53, STENCILZFAIL: 54,
        STENCILPASS: 55, STENCILFUNC: 56, STENCILREF: 57,
        STENCILMASK: 58, STENCILWRITEMASK: 59, BLENDFACTOR: 193,
        DEPTHBIAS: 195, SLOPE: 175, SEPARATEALPHA: 206,
        SRCBLENDALPHA: 207, DESTBLENDALPHA: 208, BLENDOPALPHA: 209 };
    const { executor, find } = makeExecutor();
    const states = [
        [R.ALPHABLENDENABLE, 1], [R.SRCBLEND, 14], [R.DESTBLEND, 15],
        [R.BLENDFACTOR, 0x80402010], [R.SEPARATEALPHA, 1],
        [R.SRCBLENDALPHA, 2], [R.DESTBLENDALPHA, 1],
        [R.BLENDOPALPHA, 1], [R.STENCILENABLE, 1], [R.STENCILFAIL, 3],
        [R.STENCILZFAIL, 4], [R.STENCILPASS, 5], [R.STENCILFUNC, 7],
        [R.STENCILREF, 0x55], [R.STENCILMASK, 0xff],
        [R.STENCILWRITEMASK, 0x0f], [R.DEPTHBIAS, floatBitsOf(1 / 0x1000000)],
        [R.SLOPE, floatBitsOf(1.5)],
    ].map(([id, value]) => command(OP.SET_RENDER_STATE,
        u32(DEVICE, id, value, 0)));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        ...states,
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipeline = find("createRenderPipeline").pop()[1];
    assert.deepEqual(pipeline.fragment.targets[0].blend, {
        color: { srcFactor: "constant", dstFactor: "one-minus-constant",
            operation: "add" },
        alpha: { srcFactor: "one", dstFactor: "zero", operation: "add" },
    });
    assert.equal(pipeline.depthStencil.depthBias, 1);
    assert.equal(pipeline.depthStencil.depthBiasSlopeScale, 1.5);
    assert.deepEqual(pipeline.depthStencil.stencilFront, {
        compare: "greater-equal", failOp: "replace",
        depthFailOp: "increment-clamp", passOp: "decrement-clamp",
    });
    assert.equal(pipeline.depthStencil.stencilReadMask, 0xff);
    assert.equal(pipeline.depthStencil.stencilWriteMask, 0x0f);
    assert.deepEqual(find("setBlendConstant").pop()[1], {
        r: 0x40 / 255, g: 0x20 / 255, b: 0x10 / 255, a: 0x80 / 255,
    });
    assert.equal(find("setStencilReference").pop()[1], 0x55);

    const projected = buildFixedFunctionPixelShader({
        usesTextureFactor: false, specularEnable: false, fogMode: 0,
        alphaTest: { enabled: false, func: 8, reference: 0 },
        stages: [{ index: 0, colorOp: 2, colorArg0: 1, colorArg1: 2,
            colorArg2: 1, alphaOp: 2, alphaArg0: 1, alphaArg1: 2,
            alphaArg2: 1, resultArg: 1, samplesTexture: true,
            textureType: "2d", coordVarying: 0, projected: true,
            transformCount: 3, usesConstant: false }],
    }, null);
    assert.ok(projected.includes("select(-max(abs("),
        "projected shadows must preserve a negative q divisor");

    const bordered = buildFixedFunctionPixelShader({
        usesTextureFactor: false, specularEnable: false, fogMode: 0,
        alphaTest: { enabled: false, func: 8, reference: 0 },
        stages: [{ index: 0, colorOp: 2, colorArg0: 1, colorArg1: 2,
            colorArg2: 1, alphaOp: 2, alphaArg0: 1, alphaArg1: 2,
            alphaArg2: 1, resultArg: 1, samplesTexture: true,
            textureType: "2d", coordVarying: 0, projected: true,
            transformCount: 3, usesConstant: false, addressU: 4,
            addressV: 4, addressW: 1, borderColor: 0x80402010 }],
    }, null);
    assert.ok(bordered.includes("let tex0 = select(vec4<f32>("),
        "BORDER addressing must select the D3D border colour in WGSL");
    assert.ok(bordered.includes(".x >= 0.0") &&
        bordered.includes(".y <= 1.0"),
        "both BORDER axes must reject projected coordinates outside [0,1]");
    assert.ok(bordered.includes("0.25098039") &&
        bordered.includes("0.50196078"),
        "D3DCOLOR border bytes must be converted from ARGB to RGBA");
});

await test("D3D9 default blending is ONE/ZERO when blending is first enabled",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 96)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.SET_RENDER_STATE, u32(DEVICE, 27, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.deepEqual(find("createRenderPipeline").pop()[1]
        .fragment.targets[0].blend, {
        color: { srcFactor: "one", dstFactor: "zero", operation: "add" },
        alpha: { srcFactor: "one", dstFactor: "zero", operation: "add" },
    });
});

await test("M4 ColorFill preserves pixels outside a partial rectangle", async () => {
    const D3DUSAGE_RENDERTARGET = 1;
    const payload = Buffer.alloc(32);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(0x501, 4);
    payload.writeUInt32LE(0, 8);
    payload.writeUInt32LE(0x80402010, 12);
    [4, 6, 20, 22].forEach((value, index) =>
        payload.writeInt32LE(value, 16 + index * 4));
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x501, 64, 64, 1, 21, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.COLOR_FILL, payload),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.blitsSkipped, 0);
    assert.equal(executor.stats.colorFills, 1);
    const pass = find("beginRenderPass").pop()[2];
    assert.equal(pass.descriptor.colorAttachments[0].loadOp, "load",
        "a sub-rect fill must retain the rest of the attachment");
    assert.deepEqual(pass.ops.find(op => op[0] === "viewport").slice(1, 5),
        [4, 6, 16, 16]);
    assert.deepEqual(pass.ops.find(op => op[0] === "draw"), ["draw", 3]);
});

await test("M4 target fills and copies retain D3D command order", async () => {
    const D3DUSAGE_RENDERTARGET = 1;
    const fill = Buffer.alloc(32);
    fill.writeUInt32LE(DEVICE, 0);
    fill.writeUInt32LE(0x501, 4);
    fill.writeUInt32LE(0, 8);
    fill.writeUInt32LE(0xff204060, 12);
    [0, 0, 64, 64].forEach((value, index) =>
        fill.writeInt32LE(value, 16 + index * 4));
    const stretch = Buffer.alloc(56);
    stretch.writeUInt32LE(DEVICE, 0);
    stretch.writeUInt32LE(0x501, 4);
    stretch.writeUInt32LE(0, 8);
    [0, 0, 64, 64].forEach((value, index) =>
        stretch.writeInt32LE(value, 12 + index * 4));
    stretch.writeUInt32LE(0x502, 28);
    stretch.writeUInt32LE(0, 32);
    [0, 0, 64, 64].forEach((value, index) =>
        stretch.writeInt32LE(value, 36 + index * 4));
    stretch.writeUInt32LE(1, 52);
    const { executor, fake } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x501, 64, 64, 1, 21, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x502, 64, 64, 1, 21, D3DUSAGE_RENDERTARGET, 0)),
        command(OP.COLOR_FILL, fill),
        command(0x8, stretch),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const fillIndex = fake.calls.findIndex(call => call[0] === "beginRenderPass");
    const copyIndex = fake.calls.findIndex(call => call[0] ===
        "copyTextureToTexture");
    assert.ok(fillIndex >= 0 && copyIndex > fillIndex,
        "ColorFill must be encoded before the following StretchRect copy");
    assert.equal(executor.stats.queueSubmits, 1,
        "ordered target operations share the Present submission");
});

await test("M4 Clear honours its rectangle list", async () => {
    const clear = Buffer.alloc(40);
    clear.writeUInt32LE(DEVICE, 0);
    clear.writeUInt32LE(1, 4); // D3DCLEAR_TARGET
    clear.writeUInt32LE(0xff336699, 8);
    clear.writeFloatLE(1, 12);
    clear.writeUInt32LE(0, 16);
    clear.writeUInt32LE(1, 20);
    [8, 10, 28, 34].forEach((value, index) =>
        clear.writeInt32LE(value, 24 + index * 4));
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, clear),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    assert.equal(executor.stats.partialClears, 1);
    const pass = find("beginRenderPass").pop()[2];
    assert.equal(pass.descriptor.colorAttachments[0].loadOp, "load");
    assert.deepEqual(pass.ops.find(op => op[0] === "viewport").slice(1, 5),
        [8, 10, 20, 24]);
    assert.deepEqual(pass.ops.find(op => op[0] === "draw"), ["draw", 3]);
});

// WebGPU requires a pipeline's attachment state -- colour formats, presence of
// a depth-stencil attachment, sample count -- to match the pass it draws into.
// The rectangle-clear pipeline cache keyed only on the clear flags, so the
// pipeline built for a depth-less pass was handed to a pass that had depth:
// setPipeline failed validation, the whole command buffer was rejected, and
// the frame drew nothing. 3DMark 2001 reached this the moment one pass dropped
// depth (an undersized depth surface does exactly that) and the next had it.
await test("a rectangle clear caches one pipeline per pass attachment state",
        async () => {
    const clear = Buffer.alloc(40);
    clear.writeUInt32LE(DEVICE, 0);
    clear.writeUInt32LE(1, 4); // D3DCLEAR_TARGET
    clear.writeUInt32LE(0xff336699, 8);
    clear.writeFloatLE(1, 12);
    clear.writeUInt32LE(0, 16);
    clear.writeUInt32LE(1, 20);
    [0, 0, 16, 16].forEach((value, index) =>
        clear.writeInt32LE(value, 24 + index * 4));
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, clear),
        // Unbind the depth surface, so the next clear's pass has no
        // depth-stencil attachment while the clear flags stay identical.
        command(OP.SET_DEPTH_STENCIL_SURFACE_LEVEL,
            u32(DEVICE, 0, 0, 640, 480)),
        command(OP.CLEAR, clear),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await executor.idle();
    const pipelines = find("createRenderPipeline").map(call => call[1])
        .filter(descriptor =>
            (descriptor.label || "").startsWith("D3D9 rectangle clear"));
    assert.equal(pipelines.length, 2,
        "the two passes disagree about depth, so they cannot share a pipeline");
    assert.ok(pipelines.some(descriptor => descriptor.depthStencil),
        "the pass that has a depth attachment needs a depth-stencil state");
    assert.ok(pipelines.some(descriptor => !descriptor.depthStencil),
        "the pass without one must not declare a depth-stencil state");
});

// WebGPU counts a block-compressed copy in whole 4x4 blocks, and a mip level's
// physical extent is its logical size rounded up to that grid. The tail of a
// DXT mip chain is logically 2x2 and 1x1, so passing the logical size makes
// writeTexture fail validation. That failure arrives as an uncaptured device
// error rather than an exception, so the only symptom is that the smallest mips
// keep whatever the texture was created with -- which is how Kart Rider's UI
// atlases sampled as garbage while the console filled with "copySize.width (1)
// is not a multiple of compressed texture format block width (4)".
await test("a DXT mip chain's sub-block levels upload as whole 4x4 blocks",
        async () => {
    const { executor, find } = makeExecutor();
    const DXT1 = 0x31545844;
    // 8x8 DXT1 with a full chain: 8x8, 4x4, 2x2, 1x1. Every level occupies at
    // least one 8-byte block, and the last two are smaller than one block.
    const level = (index, size) => {
        const blockRow = Math.ceil(size / 4) * 8;
        const bytes = blockRow * Math.ceil(size / 4);
        const payload = Buffer.alloc(48);
        payload.writeUInt32LE(0x401, 0);
        payload.writeUInt32LE(index, 4);
        payload.writeUInt32LE(0, 8);       // x
        payload.writeUInt32LE(0, 12);      // y
        payload.writeUInt32LE(0, 16);      // z
        payload.writeUInt32LE(size, 20);   // logical width
        payload.writeUInt32LE(size, 24);   // logical height
        payload.writeUInt32LE(1, 28);      // depth
        payload.writeUInt32LE(blockRow, 32); // row pitch, in bytes per block row
        payload.writeUInt32LE(0, 36);
        payload.writeUInt32LE(bytes, 40);
        return { payload, blob: Buffer.alloc(bytes, index + 1), field: 44 };
    };
    const uploads = [[0, 8], [1, 4], [2, 2], [3, 1]]
        .map(([index, size]) => level(index, size));
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D, u32(DEVICE, 0x401, 8, 8, 4, DXT1, 0, 1)),
        ...uploads.map(upload =>
            command(OP.UPDATE_TEXTURE, upload.payload, upload.blob, upload.field)),
    ]));
    await executor.idle();

    // The executor also writes its 1x1 fallback texture, which carries no
    // mipLevel; only the mip uploads are of interest here.
    const writes = find("writeTexture")
        .filter(call => call[1].mipLevel !== undefined);
    assert.equal(writes.length, 4, "every level has to be written");
    for (const write of writes) {
        const mipLevel = write[1].mipLevel;
        const size = write[4];
        assert.equal(size.width % 4, 0,
            "level " + mipLevel + " copy width " + size.width +
            " is not a whole number of 4x4 blocks");
        assert.equal(size.height % 4, 0,
            "level " + mipLevel + " copy height " + size.height +
            " is not a whole number of 4x4 blocks");
        // Rounding up must not overshoot the level's physical extent either.
        const physical = Math.max(4, Math.ceil((8 >> mipLevel) / 4) * 4);
        assert.equal(size.width, physical);
        assert.equal(size.height, physical);
    }
});

// PRESENT carries the window's *client rect* so the page can place the overlay
// canvas; emit_present_and_flush fills it from GetClientRect. It is not the back
// buffer's size, and a windowed game's client area is shorter than the back
// buffer it hosts. Treating it as the render size made the swap-chain colour
// attachment look like it disagreed with the auto depth target created beside
// it, and the mismatch path then dropped depth for every pass -- depth testing
// off for the whole game, from a window border.
await test("a client rect smaller than the back buffer keeps depth attached",
        async () => {
    const { executor, find } = makeExecutor();
    // 640x467 client rect for a 640x480 back buffer: the window has a title bar.
    const clientRect = u32(DEVICE, 0x1234, 0, 0, 640, 467);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.PRESENT, clientRect),
    ], { present: true }));
    await executor.idle();

    await executor.submit(buildBatch([
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 12)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, clientRect),
    ], { present: true }));
    await executor.idle();

    assert.equal(executor.stats.depthTargetSizeMismatches, 0,
        "the client rect must not be mistaken for the back buffer's size");
    const pass = find("beginRenderPass").pop()[1];
    assert.ok(pass.depthStencilAttachment,
        "the back-buffer pass keeps its auto depth-stencil");
});

// D3D9 rasterises with the sample point at a pixel's integer corner; WebGPU
// samples at the pixel centre. A title that blits UI 1:1 has already subtracted
// that half pixel itself, so replaying its geometry unchanged lands every
// sample on a texel boundary and bilinear filtering returns the mean of two
// texels -- invisible on 3D art, ruinous on small text. XYZRHW UI is the case
// that shows it, but the offset belongs on every fixed-function draw.
await test("fixed-function draws carry the D3D9 half-pixel offset", async () => {
    const { executor, find } = makeExecutor();
    const drawWith = position => buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT4, position),
            element(0, 16, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ]);

    // POSITIONT: pre-transformed UI, the path the shop text goes through.
    await executor.submit(drawWith(DECLUSAGE.POSITIONT));
    await executor.idle();
    // POSITION: ordinary world-space geometry, through world_view_projection.
    await executor.submit(drawWith(DECLUSAGE.POSITION));
    await executor.idle();

    const vertexShaders = find("createShaderModule")
        .map(call => call[1].code)
        .filter(code => code.includes("d9_vs_main"));
    assert.ok(vertexShaders.length >= 2,
        "both a screen-space and a world-space vertex shader were built");
    for (const code of vertexShaders) {
        assert.ok(code.includes(
            "result.position.x + result.position.w / uniforms.viewport.x"),
            "a fixed-function vertex shader is missing the half-pixel offset");
        // Screen y grows downward, NDC y grows upward: the y term is negated.
        assert.ok(code.includes(
            "result.position.y - result.position.w / uniforms.viewport.y"),
            "the half-pixel offset must negate y");
    }
});

// The same case as "blend data with D3DRS_VERTEXBLEND disabled", reached from
// the FVF side rather than a real declaration, and with the four-weight shape a
// skinned mesh actually ships. D3D9 poses this by D3DTS_WORLD alone because the
// render state never enabled blending, and so does this -- but a model stuck in
// bind pose looks like a working draw, so the count is what makes the case
// visible when it turns out to be the reason a character does not move.
await test("a fixed-function skinned declaration is counted when blending is off",
        async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
            element(0, 12, DECLTYPE.FLOAT4, DECLUSAGE.BLENDWEIGHT),
            element(0, 28, DECLTYPE.UBYTE4, DECLUSAGE.BLENDINDICES),
            element(0, 32, DECLTYPE.FLOAT3, DECLUSAGE.NORMAL)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 44)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
    ]));
    await executor.idle();
    assert.equal(executor.stats.drawsWithUnappliedVertexBlend, 1,
        "a declaration carrying blend weights has to be counted");
});

// XYZRHW coordinates are absolute render-target pixels. setViewport already
// puts the viewport's origin back when it maps NDC into the viewport rect, so
// the shader has to take that origin off first. Getting this wrong cancels out
// exactly when the viewport sits at 0,0 -- which is every full-screen UI pass,
// and is why it stayed invisible until a game drew pre-transformed geometry
// through a small offset viewport (Kart Rider's shop item panels) and the
// geometry landed several viewport-widths outside the box.
await test("pre-transformed geometry subtracts the viewport origin",
        async () => {
    const { executor, find } = makeExecutor();
    const viewport = Buffer.alloc(32);
    viewport.writeUInt32LE(DEVICE, 0);
    viewport.writeUInt32LE(368, 4);   // x
    viewport.writeUInt32LE(104, 8);   // y
    viewport.writeUInt32LE(110, 12);  // width
    viewport.writeUInt32LE(109, 16);  // height
    viewport.writeFloatLE(0, 20);
    viewport.writeFloatLE(1, 24);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(800, 600)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x201, 1, 240)),
        command(OP.SET_VIEWPORT, viewport),
        command(OP.SET_FVF, fvfPayload(0x104, [
            element(0, 0, DECLTYPE.FLOAT4, DECLUSAGE.POSITIONT),
            element(0, 16, DECLTYPE.D3DCOLOR, DECLUSAGE.COLOR)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x201, 20)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        // Constants are staged and go up with the frame's submit, so the
        // upload only exists once the frame is actually presented.
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 800, 600)),
    ], { present: true }));
    await executor.idle();

    const vertexShader = find("createShaderModule").map(call => call[1].code)
        .filter(code => code.includes("d9_vs_main")).pop();
    assert.ok(vertexShader, "a screen-space vertex shader was built");
    assert.ok(vertexShader.includes("- viewport.z") &&
        vertexShader.includes("- viewport.w"),
        "the XYZRHW path must subtract the viewport origin:\n" + vertexShader);

    // The origin has to actually reach the uniform, not just the WGSL.
    const writes = find("writeBuffer");
    assert.ok(writes.length > 0, "constants were uploaded");
    const carriesOrigin = writes.some(call => {
        // call[6] is the snapshot of exactly the bytes this write sent, which
        // for a staged ring upload is its used prefix rather than the whole
        // mirror.
        const data = call[6];
        if (!data || !data.byteLength) return false;
        const floats = new Float32Array(data.buffer, data.byteOffset,
            Math.floor(data.byteLength / 4));
        for (let i = 0; i + 3 < floats.length; ++i) {
            if (floats[i] === 110 && floats[i + 1] === 109 &&
                    floats[i + 2] === 368 && floats[i + 3] === 104)
                return true;
        }
        return false;
    });
    assert.ok(carriesOrigin,
        "the viewport uniform must carry size in xy and origin in zw");
});

await test("volume textures allocate 3D storage and upload every slice", async () => {
    const { executor, find } = makeExecutor();
    const pixels = Buffer.alloc(32);
    for (let i = 0; i < pixels.length; ++i) pixels[i] = i;
    // D9WGUpdateTexture: handle, level, xyz, whd, row/slice pitch,
    // byte count and batch-relative data offset.
    const update = u32(0x900, 0, 0, 0, 0, 2, 2, 2, 8, 16, 32, 0);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_VOLUME,
            u32(DEVICE, 0x900, 2, 2, 2, 1, 21, 0, 1, 0)),
        command(OP.UPDATE_TEXTURE, update, pixels, 44),
    ], { versionMinor: 3 }));
    await executor.idle();

    const resource = executor.resources.get(0x900);
    assert.equal(resource.textureType, "3d");
    const descriptor = find("createTexture").find(call =>
        call[1].label === "D3D9 volume texture")[1];
    assert.equal(descriptor.dimension, "3d");
    assert.deepEqual(descriptor.size,
        { width: 2, height: 2, depthOrArrayLayers: 2 });
    const upload = find("writeTexture").pop();
    assert.deepEqual(upload[4],
        { width: 2, height: 2, depthOrArrayLayers: 2 });
    assert.equal(upload[3].rowsPerImage, 2);
    assert.equal(executor.stats.volumeTexturesCreated, 1);
});

await test("GPU render-target readback writes a converted D3D surface response",
        async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x901, 2, 1, 1, 21, 1, 0)),
    ], { versionMinor: 3 }));
    await executor.idle();
    // The physical texture is rgba8unorm. GetRenderTargetData must return
    // D3DFMT_A8R8G8B8's in-memory BGRA byte order.
    executor.resources.get(0x901).gpuTexture.readbackData =
        Uint8Array.from([0x11, 0x22, 0x33, 0x44,
            0x55, 0x66, 0x77, 0x88]);
    executor.resources.get(0x901).gpuTexture.readbackPitch = 8;
    const writes = [];
    const responseOffset = 16 * 1024;
    await executor.submit(buildBatch([
        command(OP.READBACK_SURFACE,
            u32(DEVICE, 0x901, 0, 21, 2, 1, 0, 1, 8, 8,
                responseOffset, 0x12345678)),
    ], { versionMinor: 3 }), {
        writeGuestMemory(offset, data) {
            // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
        },
    });
    await executor.idle();

    assert.equal(writes.length, 1);
    assert.equal(writes[0].offset, 12 * 1024 * 1024 + responseOffset);
    assert.equal(writes[0].data.readUInt32LE(0), 0x12345678);
    assert.equal(writes[0].data.readUInt32LE(4), 8);
    assert.equal(writes[0].data.readUInt32LE(12), 1);
    assert.deepEqual([...writes[0].data.subarray(16)],
        [0x33, 0x22, 0x11, 0x44, 0x77, 0x66, 0x55, 0x88]);
    assert.equal(executor.stats.renderTargetReadbacks, 1);
});

await test("DirectDraw P8 readback preserves raw indices and destination pitch",
        async () => {
    const { executor } = makeExecutor();
    const P8 = 41;
    const DD_INDEXED = 0x80000000;
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x902, 4, 2, 1, P8, DD_INDEXED, 0, 0, 0)),
    ], { versionMinor: 7 }));
    await executor.idle();
    const texture = executor.resources.get(0x902).gpuTexture;
    texture.readbackData = Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]);
    texture.readbackPitch = 4;
    const writes = [];
    const responseOffset = 16 * 1024;
    await executor.submit(buildBatch([
        command(OP.READBACK_SURFACE,
            u32(DEVICE, 0x902, 0, P8, 4, 2, 0, 2, 8, 16,
                responseOffset, 0x31415926, 0)),
    ], { versionMinor: 7 }), { writeGuestMemory(offset, data) {
        if (offset !== HEARTBEAT_WRITE_OFFSET)
            writes.push(Buffer.from(data));
    } });
    await executor.idle();
    assert.equal(writes.length, 1);
    assert.equal(writes[0].readUInt32LE(4), 16);
    assert.deepEqual([...writes[0].subarray(16)],
        [1, 2, 3, 4, 0, 0, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0]);
});

await test("DXT cube readback returns one raw block from the selected mip face",
        async () => {
    const { executor, find } = makeExecutor();
    const DXT1 = 0x31545844;
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_CUBE,
            u32(DEVICE, 0x903, 8, 4, DXT1, 0, 0, 0)),
    ], { versionMinor: 7 }));
    await executor.idle();
    const texture = executor.resources.get(0x903).gpuTexture;
    texture.readbackData = Uint8Array.from(
        [0x10, 0x21, 0x32, 0x43, 0x54, 0x65, 0x76, 0x87]);
    texture.readbackPitch = 8;
    const writes = [];
    await executor.submit(buildBatch([
        command(OP.READBACK_SURFACE,
            u32(DEVICE, 0x903, 2, DXT1, 2, 2, 0, 2, 8, 8,
                16 * 1024, 0x27182818, 5)),
    ], { versionMinor: 7 }), { writeGuestMemory(offset, data) {
        if (offset !== HEARTBEAT_WRITE_OFFSET)
            writes.push(Buffer.from(data));
    } });
    await executor.idle();
    assert.equal(writes.length, 1);
    assert.deepEqual([...writes[0].subarray(16)],
        [0x10, 0x21, 0x32, 0x43, 0x54, 0x65, 0x76, 0x87]);
    const copy = find("copyTextureToBuffer").pop();
    assert.equal(copy[1].mipLevel, 2);
    assert.deepEqual(copy[1].origin, { x: 0, y: 0, z: 5 });
    assert.deepEqual(copy[3],
        { width: 4, height: 4, depthOrArrayLayers: 1 });
});

await test("back-buffer readback uses a persistent post-Present snapshot",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CLEAR, u32(DEVICE, 1, 0xff000000, 0x3f800000, 0, 0)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }));
    await executor.idle();
    // The readback request arrives in a later task, by which time a canvas
    // texture would have expired; the owned back buffer has not.
    const snapshot = executor.backBufferTexture;
    assert.ok(snapshot, "the back buffer must outlive the task that drew it");
    snapshot.readbackData = new Uint8Array(640 * 4);
    snapshot.readbackData.set([0x11, 0x22, 0x33, 0x44]);
    snapshot.readbackPitch = 640 * 4;

    const writes = [];
    await executor.submit(buildBatch([
        command(OP.READBACK_SURFACE,
            u32(DEVICE, 0, 0, 21, 640, 480, 0, 1, 640 * 4, 640 * 4,
                16 * 1024, 0x22334455)),
    ], { versionMinor: 3 }), { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } });
    await executor.idle();

    const copy = find("copyTextureToBuffer").pop();
    assert.equal(copy[1].texture, snapshot);
    assert.equal(writes.length, 1);
    // The canvas is physically BGRA, already the memory order D3D9 expects.
    assert.deepEqual([...writes[0].data.subarray(16, 20)],
        [0x11, 0x22, 0x33, 0x44]);
    assert.equal(executor.stats.backBufferPresents, 1);
});

await test("event queries complete only after the submitted GPU fence", async () => {
    const { executor, fake } = makeExecutor();
    const writes = [];
    const metadata = { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } };
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x902, 8, 0)),
        command(OP.END_QUERY, u32(DEVICE, 0x902, 0, 41)),
    ], { versionMinor: 3 }), metadata);
    await executor.idle();
    assert.equal(writes.length, 0, "an event query is not an immediate CPU answer");
    fake.completeSubmittedWork();
    await Promise.resolve();
    assert.equal(writes.length, 1);
    assert.equal(writes[0].offset, 12 * 1024 * 1024);
    assert.equal(writes[0].data.readUInt32LE(0), 41);
    assert.equal(writes[0].data.readUInt32LE(4), 1);
    assert.equal(writes[0].data.readUInt32LE(12), 1);
    assert.equal(executor.stats.eventQueriesResolved, 1);
});

await test("occlusion queries return the GPU query-set sample count", async () => {
    const { executor } = makeExecutor();
    const writes = [];
    const elements = [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x903, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x903, 12)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x904, 9, 16)),
        command(OP.BEGIN_QUERY, u32(DEVICE, 0x904, 16, 50)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.END_QUERY, u32(DEVICE, 0x904, 16, 51)),
    ], { versionMinor: 3 }), { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } });
    await executor.idle();
    await Promise.resolve();

    assert.equal(writes.length, 1);
    assert.equal(writes[0].data.readUInt32LE(0), 51);
    assert.equal(writes[0].data.readUInt32LE(4), 37);
    assert.equal(writes[0].data.readUInt32LE(12), 1);
    assert.equal(executor.stats.occlusionQueriesResolved, 1);
});

await test("occlusion queries accumulate GPU segments across Present", async () => {
    const { executor } = makeExecutor();
    const writes = [];
    const metadata = { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } };
    const elements = [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x914, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2, elements)),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x914, 12)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x915, 9, 80)),
        command(OP.BEGIN_QUERY, u32(DEVICE, 0x915, 80, 70)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }), metadata);
    await executor.idle();
    await Promise.resolve();
    assert.equal(writes.length, 0, "BEGIN remains pending across Present");

    await executor.submit(buildBatch([
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.END_QUERY, u32(DEVICE, 0x915, 80, 71)),
    ], { versionMinor: 3 }), metadata);
    await executor.idle();
    await Promise.resolve();
    await Promise.resolve();
    assert.equal(writes.length, 1);
    assert.equal(writes[0].data.readUInt32LE(0), 71);
    assert.equal(writes[0].data.readUInt32LE(4), 74);
    assert.equal(writes[0].data.readUInt32LE(12), 1);
    assert.equal(executor.stats.occlusionQueriesResolved, 1);
});

await test("timestamp, frequency and disjoint query classes return real results",
        async () => {
    const { executor, fake } = makeExecutor();
    const writes = [];
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x908, 10, 32)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x909, 12, 48)),
        command(OP.CREATE_QUERY, u32(DEVICE, 0x90a, 11, 64)),
        command(OP.END_QUERY, u32(DEVICE, 0x908, 32, 61)),
        command(OP.END_QUERY, u32(DEVICE, 0x909, 48, 62)),
        command(OP.END_QUERY, u32(DEVICE, 0x90a, 64, 63)),
    ], { versionMinor: 3 }), { writeGuestMemory(offset, data) {
        // The host bumps a liveness counter once per batch at the very top
        // of the response region; it is not a response to anything, so it
        // must not be counted as one.
        if (offset === HEARTBEAT_WRITE_OFFSET) return;
        writes.push({ offset, data: Buffer.from(data) });
    } });
    await executor.idle();
    await Promise.resolve();
    assert.equal(writes.length, 1, "the GPU timestamp maps independently");
    assert.equal(writes[0].data.readUInt32LE(0), 61);
    assert.equal(writes[0].data.readUInt32LE(4), 1000);
    fake.completeSubmittedWork();
    await Promise.resolve();
    assert.equal(writes.length, 3);
    const byRequest = new Map(writes.map(write =>
        [write.data.readUInt32LE(0), write.data]));
    assert.equal(byRequest.get(62).readBigUInt64LE(4), 1000000000n);
    assert.equal(byRequest.get(63).readBigUInt64LE(4), 0n);
    assert.equal(executor.stats.timestampQueriesResolved, 1);
});

await test("enabled user clip planes reach both fixed shader stages", async () => {
    const D3DRS_CLIPPLANEENABLE = 152;
    const { executor, find } = makeExecutor();
    const plane = Buffer.alloc(24);
    plane.writeUInt32LE(DEVICE, 0);
    plane.writeUInt32LE(0, 4);
    plane.writeFloatLE(1, 8);
    plane.writeFloatLE(0, 12);
    plane.writeFloatLE(0, 16);
    plane.writeFloatLE(-0.25, 20);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x905, 1, 36)),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x905, 12)),
        command(OP.SET_CLIP_PLANE, plane),
        command(OP.SET_RENDER_STATE, u32(DEVICE, D3DRS_CLIPPLANEENABLE, 1, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }));
    await executor.idle();

    const pipeline = find("createRenderPipeline").pop()[1];
    assert.match(pipeline.vertex.module.code,
        /dot\(d9_clip_position, uniforms\.clip_planes\[0\]\)/);
    assert.match(pipeline.vertex.module.code,
        /d9_clip_position = uniforms\.world_matrix \* in0/);
    assert.match(pipeline.fragment.module.code,
        /if \(stage_in\.clip0\.x < 0\.0\) \{ discard; \}/);
    assert.deepEqual(executor.devices.get(DEVICE).clipPlanes[0],
        [1, 0, 0, -0.25]);
});

await test("vs_3_0 vertex texture fetch binds D3D vertex sampler 0 at 34/35",
        async () => {
    const { executor, find } = makeExecutor();
    const vs = shaderCreatePayload(0x40000906, VS3_VERTEX_TEXTURE_FETCH);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x906, 1, 48)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x907, 4, 4, 1, 21, 0, 1)),
        command(OP.CREATE_VERTEX_SHADER,
            vs.payload, vs.blob, vs.blobOffsetField),
        command(OP.SET_FVF, fvfPayload(0x2,
            [element(0, 0, DECLTYPE.FLOAT4, DECLUSAGE.POSITION)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x906, 16)),
        command(OP.SET_VERTEX_SHADER, u32(DEVICE, 0x40000906)),
        command(OP.SET_TEXTURE, u32(DEVICE, 256, 0x907, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    const layout = find("createBindGroupLayout").pop()[1];
    assert.ok(layout.entries.some(entry => entry.binding === 34 &&
        entry.visibility === 1));
    assert.ok(layout.entries.some(entry => entry.binding === 35 &&
        entry.visibility === 1));
    const group = find("createBindGroup").pop()[1];
    assert.ok(group.entries.some(entry => entry.binding === 34));
    assert.ok(group.entries.some(entry => entry.binding === 35));
});

await test("programmable pixel samplers expose the complete s0 through s15 range",
        async () => {
    const { executor, find } = makeExecutor();
    const ps = shaderCreatePayload(0x40000908, PS_SAMPLER15_BYTECODE);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_BUFFER, createBufferPayload(0x90b, 1, 60)),
        command(OP.CREATE_TEXTURE_2D,
            u32(DEVICE, 0x90c, 4, 4, 1, 21, 0, 1)),
        command(OP.SET_FVF, fvfPayload(0x102,
            [element(0, 0, DECLTYPE.FLOAT3, DECLUSAGE.POSITION),
             element(0, 12, DECLTYPE.FLOAT2, DECLUSAGE.TEXCOORD)])),
        command(OP.SET_STREAM_SOURCE, setStreamSourcePayload(0, 0x90b, 20)),
        command(OP.CREATE_PIXEL_SHADER,
            ps.payload, ps.blob, ps.blobOffsetField),
        command(OP.SET_PIXEL_SHADER, u32(DEVICE, 0x40000908)),
        command(OP.SET_TEXTURE, u32(DEVICE, 15, 0x90c, 0)),
        command(OP.DRAW_PRIMITIVE, drawPrimitivePayload(4, 0, 1)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true, versionMinor: 3 }));
    await executor.idle();

    assert.equal(executor.stats.droppedDraws, 0);
    const layout = find("createBindGroupLayout").pop()[1];
    assert.ok(layout.entries.some(entry => entry.binding === 32));
    assert.ok(layout.entries.some(entry => entry.binding === 33));
});

// Guest-to-host diagnostics. Everything the guest DLL refuses used to be
// invisible from the page -- the console sees only valid commands, and the
// guest's trace file is inside a VM whose filesystem the developer cannot
// reach -- which repeatedly turned "the picture is wrong" into guesswork.
await test("a guest log command reaches the console with its text intact",
        async () => {
    const { executor } = makeExecutor();
    const text = "CreateVertexBuffer refused: length=0 usage=00000008";
    const payload = Buffer.alloc(8 + text.length);
    payload.writeUInt32LE(2, 0);            // severity: failed
    payload.writeUInt32LE(text.length, 4);
    payload.write(text, 8, "ascii");

    const errors = [];
    const realError = console.error;
    console.error = (...args) => errors.push(args.join(" "));
    try {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.GUEST_LOG, payload),
        ]));
        await executor.idle();
    } finally {
        console.error = realError;
    }
    assert.equal(executor.stats.guestReports, 1);
    assert.equal(executor.stats.unsupportedCommands, 0,
        "the opcode has to be handled, not counted as unknown");
    assert.ok(errors.some(line => line === "[d3d9-guest] " + text),
        "the guest's text has to arrive verbatim, got: " + errors.join(" | "));
});

// The guest identifies itself at startup so that a session with no other
// guest messages means "nothing was refused" rather than "the DLL inside the
// disk image predates this channel and cannot say anything". Info severity has
// to reach the console like the rest, just not as a warning.
await test("an info-severity guest log is reported without being a warning",
        async () => {
    const { executor } = makeExecutor();
    const text = "proxy build guest-log-20260816 loaded";
    const payload = Buffer.alloc(8 + text.length);
    payload.writeUInt32LE(0, 0);            // severity: info
    payload.writeUInt32LE(text.length, 4);
    payload.write(text, 8, "ascii");

    const logs = [];
    const warnings = [];
    const realLog = console.log;
    const realWarn = console.warn;
    console.log = (...args) => logs.push(args.join(" "));
    console.warn = (...args) => warnings.push(args.join(" "));
    try {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.GUEST_LOG, payload),
        ]));
        await executor.idle();
    } finally {
        console.log = realLog;
        console.warn = realWarn;
    }
    assert.equal(executor.stats.guestReports, 1);
    assert.ok(logs.some(line => line === "[d3d9-guest] " + text),
        "the identification line has to reach the console");
    assert.ok(!warnings.some(line => line.includes(text)),
        "identification is not a warning");
});

// Restoring a state replays the graphics journal, which holds every report
// since the guest started (3DMark06's: one identification line per process
// that loaded the DLL). Those were printed when they happened.
await test("a replayed guest log is kept but not printed again", async () => {
    const { executor } = makeExecutor();
    const text = "proxy build guest-log-20260816 loaded";
    const payload = Buffer.alloc(8 + text.length);
    payload.writeUInt32LE(0, 0);            // severity: info
    payload.writeUInt32LE(text.length, 4);
    payload.write(text, 8, "ascii");

    const printed = [];
    const real = { log: console.log, warn: console.warn, error: console.error };
    console.log = console.warn = console.error = (...args) => printed.push(args.join(" "));
    try {
        await executor.submit(buildBatch([
            command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
            command(OP.GUEST_LOG, payload),
        ]), { replay: true });
        await executor.idle();
    } finally {
        Object.assign(console, real);
    }
    assert.equal(executor.stats.guestReports, 1);
    assert.deepEqual(executor.guestReports, [text], "the black-screen report still has it");
    assert.ok(!printed.some(line => line.includes(text)),
        "a replay does not print it again: " + printed.join(" | "));
});

// A truncated length field must not read past the command into whatever
// follows it in the batch.
await test("a guest log claiming more text than it carries is rejected",
        async () => {
    const { executor } = makeExecutor();
    const payload = Buffer.alloc(12);
    payload.writeUInt32LE(1, 0);
    payload.writeUInt32LE(0xffff, 4); // far more than the 4 bytes present
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.GUEST_LOG, payload),
    ]));
    await executor.idle();
    assert.equal(executor.stats.malformedBatches, 1);
    assert.equal(executor.stats.guestReports, 0);
});

// ---- report ----

if (failures.length) {
    for (const failure of failures) {
        console.error("FAIL " + failure.name);
        console.error("  " + (failure.error && failure.error.message));
        if (process.env.D9_TEST_STACK) console.error(failure.error);
    }
    console.error("\n" + failures.length + " failed, " + passed + " passed");
    process.exit(1);
}
console.log(passed + " executor tests passed");
}

if (require.main === module) main().catch(error => { console.error(error); process.exit(1); });

module.exports = { makeExecutor, buildBatch, command, u32, createDevicePayload, createBufferPayload, shaderCreatePayload, fvfPayload, element, setStreamSourcePayload, drawPrimitivePayload, OP, DEVICE, DECLTYPE, DECLUSAGE };
                                                                                                                                                                                                                                                                                                                                    source/v64/tests/glbridge/d3d9_webgpu_perf_test.js                                                  0000644 0000000 0000000 00000022113 00000000000 017331  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// M6 steady-state budget guard for the D3D9 WebGPU executor. This is a
// counting WebGPU device rather than a timing benchmark: it pins the resource
// creation/submission invariants that make frame time predictable on real GPU
// drivers.

"use strict";

const assert = require("node:assert/strict");
const { D3D9WebGPUExecutor } = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js");

const DEVICE = 0x100002;
const OP = {
    CREATE_DEVICE: 2, PRESENT: 4, CREATE_BUFFER: 0x100,
    SET_RENDER_STATE: 0x200, SET_STREAM_SOURCE: 0x20a, SET_FVF: 0x20e,
    DRAW_PRIMITIVE: 0x300,
};

function u32(...values) {
    const out = Buffer.alloc(values.length * 4);
    values.forEach((value, index) => out.writeUInt32LE(value >>> 0, index * 4));
    return out;
}

function command(opcode, payload) { return { opcode, payload }; }

function batch(commands, present) {
    let commandBytes = 0;
    for (const item of commands) {
        item.size = (16 + item.payload.length + 7) & ~7;
        item.offset = 32 + commandBytes;
        commandBytes += item.size;
    }
    const out = Buffer.alloc(32 + commandBytes);
    out.writeUInt32LE(0x47573944, 0);
    out.writeUInt16LE(1, 4);
    out.writeUInt16LE(3, 6);
    out.writeUInt32LE(present ? 1 : 0, 12);
    out.writeUInt32LE(commands.length, 16);
    out.writeUInt32LE(commandBytes, 20);
    commands.forEach((item, index) => {
        out.writeUInt16LE(item.opcode, item.offset);
        out.writeUInt32LE(item.size, item.offset + 4);
        out.writeUInt32LE(index + 1, item.offset + 8);
        item.payload.copy(out, item.offset + 16);
    });
    return out;
}

function createDevice() {
    const out = Buffer.alloc(52);
    out.writeUInt32LE(DEVICE, 0);
    out.writeUInt32LE(0x1234, 4);
    out.writeUInt32LE(800, 16);
    out.writeUInt32LE(600, 20);
    out.writeUInt32LE(22, 24);
    out.writeUInt32LE(1, 28);
    return out;
}

function createBuffer(handle, bytes) {
    return u32(DEVICE, handle, 1, bytes, 0, 0);
}

function fvf() {
    const out = Buffer.alloc(24);
    out.writeUInt32LE(DEVICE, 0);
    out.writeUInt32LE(0x002, 4);
    out.writeUInt32LE(1, 8);
    // D9WGVertexElement: stream 0, offset 0, FLOAT3, POSITION0.
    out.writeUInt16LE(0, 16);
    out.writeUInt16LE(0, 18);
    out.writeUInt8(2, 20);
    out.writeUInt8(0, 21);
    out.writeUInt8(0, 22);
    out.writeUInt8(0, 23);
    return out;
}

function frameCommands(includeSetup) {
    const commands = [];
    if (includeSetup) {
        commands.push(command(OP.CREATE_DEVICE, createDevice()));
        commands.push(command(OP.CREATE_BUFFER, createBuffer(0x201, 4096)));
        commands.push(command(OP.SET_FVF, fvf()));
        commands.push(command(OP.SET_STREAM_SOURCE,
            u32(DEVICE, 0, 0x201, 12, 0)));
    }
    // 150 draws with 300 state writes. CULLMODE alternates between two real
    // pipeline states; TEXTUREFACTOR changes twice per draw but is not read by
    // this untextured cascade, so it must not force a GPU resource allocation.
    for (let draw = 0; draw < 150; ++draw) {
        commands.push(command(OP.SET_RENDER_STATE,
            u32(DEVICE, 22, draw & 1 ? 1 : 3, 0)));
        commands.push(command(OP.SET_RENDER_STATE,
            u32(DEVICE, 60, 0xff000000 | draw, 0)));
        commands.push(command(OP.DRAW_PRIMITIVE,
            u32(DEVICE, 4, 0, 1)));
    }
    commands.push(command(OP.PRESENT,
        u32(DEVICE, 0x1234, 0, 0, 800, 600, 0, 0)));
    return commands;
}

function countingWebGPU() {
    const counts = new Map();
    const hit = name => counts.set(name, (counts.get(name) || 0) + 1);
    class BufferObject {
        constructor(descriptor) { this.size = descriptor.size; }
        destroy() { hit("destroyBuffer"); }
    }
    class TextureObject {
        constructor(descriptor) { this.descriptor = descriptor; }
        createView() { return { texture: this }; }
        destroy() { hit("destroyTexture"); }
    }
    class Pass {
        setPipeline() {}
        setBindGroup() {}
        setBlendConstant() {}
        setStencilReference() {}
        setViewport() {}
        setScissorRect() {}
        setVertexBuffer() {}
        setIndexBuffer() {}
        draw() { hit("draw"); }
        drawIndexed() { hit("drawIndexed"); }
        end() {}
    }
    const queue = {
        writeBuffer() { hit("writeBuffer"); },
        writeTexture() { hit("writeTexture"); },
        submit() { hit("submit"); },
        onSubmittedWorkDone() { return Promise.resolve(); },
    };
    const device = {
        queue, lost: new Promise(() => {}),
        createBuffer(descriptor) { hit("createBuffer"); return new BufferObject(descriptor); },
        createTexture(descriptor) { hit("createTexture"); return new TextureObject(descriptor); },
        createShaderModule(descriptor) {
            hit("createShaderModule");
            return { code: descriptor.code,
                getCompilationInfo: async () => ({ messages: [] }) };
        },
        createSampler() { hit("createSampler"); return {}; },
        createBindGroupLayout(descriptor) {
            hit("createBindGroupLayout");
            return { bindings: new Set(descriptor.entries.map(entry => entry.binding)) };
        },
        createPipelineLayout(descriptor) {
            hit("createPipelineLayout"); return { bindGroupLayouts: descriptor.bindGroupLayouts };
        },
        createRenderPipeline(descriptor) {
            hit("createRenderPipeline"); return { descriptor };
        },
        createBindGroup(descriptor) { hit("createBindGroup"); return descriptor; },
        createCommandEncoder() {
            hit("createCommandEncoder");
            return { beginRenderPass() { hit("beginRenderPass"); return new Pass(); },
                copyTextureToTexture() { hit("copyTextureToTexture"); },
                finish() { return {}; } };
        },
    };
    const context = {
        configure() {},
        getCurrentTexture() {
            return { width: 800, height: 600, createView: () => ({ swapchain: true }) };
        },
    };
    return { device, context, counts,
        snapshot: () => Object.fromEntries(counts) };
}

function delta(after, before, key) {
    return (after[key] || 0) - (before[key] || 0);
}

async function main() {
    const fake = countingWebGPU();
    const executor = new D3D9WebGPUExecutor({ getContext: () => fake.context }, {
        device: fake.device, context: fake.context, format: "bgra8unorm",
        uniformRingBytes: 4 * 1024 * 1024,
    });

    // Two warm-up frames populate both alternating pipeline/bind-group keys.
    await executor.submit(batch(frameCommands(true), true));
    await executor.submit(batch(frameCommands(false), true));
    await executor.idle();
    const before = fake.snapshot();
    const statsBefore = executor.getStats();

    await executor.submit(batch(frameCommands(false), true));
    await executor.idle();
    const after = fake.snapshot();
    const stats = executor.getStats();

    assert.equal(delta(after, before, "createRenderPipeline"), 0,
        "steady frame created a pipeline");
    assert.equal(delta(after, before, "createBindGroup"), 0,
        "steady frame created a bind group");
    assert.equal(delta(after, before, "createBuffer"), 0,
        "steady frame created a GPU buffer");
    assert.equal(delta(after, before, "createTexture"), 0,
        "steady frame created a texture");
    assert.equal(delta(after, before, "submit"), 1,
        "one D3D frame should be one WebGPU queue submit");
    assert.equal(delta(after, before, "beginRenderPass"), 1,
        "compatible draws should merge into one render pass");
    assert.equal(delta(after, before, "copyTextureToBuffer"), 0,
        "normal rendering must not read the GPU back");
    assert.equal(delta(after, before, "mapAsync"), 0,
        "normal rendering must not map GPU results");
    assert.equal(stats.lastFrame.pipelineCreations, 0);
    assert.equal(stats.lastFrame.bindGroupCreations, 0);
    assert.ok(stats.bindGroupHits - statsBefore.bindGroupHits >= 150,
        "every steady draw should hit the bind-group cache");
    /*
     * This frame writes two render states before every draw, so the constant
     * slot is invalidated 150 times by design -- the dirty serial is answering
     * "did any command run", not "did the resulting bytes differ", which is how
     * a driver answers it and is O(1) instead of a hash over the block.
     *
     * What has to hold is the property that actually costs anything: however
     * many slots the frame burns, they reach the GPU in one upload. The old
     * assertion here counted slot reuses because each slot used to carry its
     * own writeBuffer; now they do not.
     */
    assert.equal(delta(after, before, "writeBuffer"), 1,
        "a frame's constants must reach the GPU in one staged upload");
    assert.equal(stats.uniformStagingUploads -
        statsBefore.uniformStagingUploads, 1);
    assert.equal(stats.uniformRingOverflows, 0);
    assert.ok(stats.lastFrame.queueSubmits <= 5, "M6 submit budget exceeded");

    console.log("PASS d3d9 M6 steady-state: 150 draws, 0 pipeline/bind-group/buffer " +
        "creations, 1 pass, 1 submit");
}

main().catch(error => {
    console.error(error);
    process.exit(1);
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/glbridge/ddraw_blit_wgsl_validation_test.js                                        0000644 0000000 0000000 00000010163 00000000000 021564  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Runs every DirectDraw blit shader variant ddraw_ops.js can generate through
// `naga`, the WGSL front end wgpu and Firefox use.
//
// The executor tests prove the right variant is chosen and the right bindings
// are supplied; they cannot prove the WGSL compiles, because the fake device
// accepts any string. A blit shader that fails to compile is a black screen
// with a console message, and the whole 2D path is these shaders.
//
// naga is optional: install it with `cargo install naga-cli`.

"use strict";

const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");
const { ddBlitShaderSource } = require("../../src/browser/glbridge/d3d9-webgpu/ddraw_ops.js");

function findNaga() {
    const probe = spawnSync("naga", ["--version"], { encoding: "utf8" });
    return probe.status === 0 ? "naga" : null;
}

const naga = findNaga();
if (!naga) {
    console.log("SKIP: no `naga` binary (install with `cargo install naga-cli`)");
    process.exit(0);
}

const directory = fs.mkdtempSync(path.join(os.tmpdir(), "ddraw-wgsl-"));
let checked = 0;
const failures = [];

function validate(name, source) {
    const file = path.join(directory, name.replace(/[^a-z0-9]+/gi, "_") + ".wgsl");
    fs.writeFileSync(file, source);
    const run = spawnSync(naga, [file], { encoding: "utf8" });
    ++checked;
    if (run.status !== 0)
        failures.push({ name, output: (run.stderr || run.stdout || "").trim(),
            source });
}

// Every combination the executor can ask for. The impossible ones are left
// out on purpose: a fill never resolves a source palette or tests a source
// key, and a true-colour destination is the only thing a palette resolve can
// write into. Fills can still test a destination key.
for (const sourceKind of ["float", "index", "none"]) {
    for (const destinationKind of ["float", "index"]) {
        for (const colorKey of [false, true]) {
            for (const destinationKey of [false, true]) {
                for (const paletteResolve of [false, true]) {
                    if (sourceKind === "none" && (colorKey || paletteResolve))
                        continue;
                    if (paletteResolve && (sourceKind !== "index" ||
                            destinationKind !== "float"))
                        continue;
                    const variant = { sourceKind, destinationKind, colorKey,
                        destinationKey, paletteResolve, filterPoint: true };
                    validate([sourceKind, destinationKind,
                        colorKey ? "source-key" : "no-source-key",
                        destinationKey ? "destination-key" : "no-destination-key",
                        paletteResolve ? "palette" : "nopalette"].join("-"),
                        ddBlitShaderSource(variant));
                }
            }
        }
    }
}

// The two variants the 2D path lives on, spelled out so a regression names
// itself rather than appearing as "variant 7 failed".
validate("sprite-blit-p8-into-p8-with-source-key", ddBlitShaderSource({
    sourceKind: "index", destinationKind: "index", colorKey: true,
    destinationKey: false, paletteResolve: false, filterPoint: true }));
validate("sprite-blit-rgb-with-destination-key", ddBlitShaderSource({
    sourceKind: "float", destinationKind: "float", colorKey: false,
    destinationKey: true, paletteResolve: false, filterPoint: true }));
validate("present-p8-primary-to-canvas", ddBlitShaderSource({
    sourceKind: "index", destinationKind: "float", colorKey: false,
    destinationKey: false, paletteResolve: true, filterPoint: true }));

if (failures.length) {
    for (const failure of failures) {
        console.error("FAIL " + failure.name);
        console.error(failure.output.split("\n").slice(0, 12).join("\n"));
    }
    console.error(failures.length + " of " + checked +
        " DirectDraw blit shaders failed to compile");
    process.exit(1);
}
assert.ok(checked >= 20, "the variant sweep should cover at least twenty shaders");
console.log(checked + " DirectDraw blit shaders validated with naga");
                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/glbridge/ddraw_webgpu_executor_test.js                                             0000644 0000000 0000000 00000143076 00000000000 020605  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Executor-level tests for the D9WG 1.7 DirectDraw group
// (glbridge/d3d9-webgpu/ddraw_ops.js) against a fake WebGPU device.
//
// These drive real D9WG batches -- built byte for byte the way ddraw_proxy.c
// emits them -- through the executor and assert on what comes out: which
// pipeline variant, which bindings, what lands in the blit uniform block, and
// which blits are refused rather than performed wrongly. The fake device
// reproduces the validation rule that bites hardest here (a bind group must
// supply exactly the bindings its layout declares), so a wiring mistake fails
// here rather than as a silent black screen inside v86.

"use strict";

const assert = require("node:assert/strict");
const { D3D9WebGPUExecutor } = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js");
const ddraw = require("../../src/browser/glbridge/d3d9-webgpu/ddraw_ops.js");
ddraw.installDDrawOps(D3D9WebGPUExecutor);

const OP = {
    HELLO: 1, CREATE_DEVICE: 2, PRESENT: 4, SESSION_END: 13,
    DESTROY_RESOURCE: 0x103,
    CREATE_TEXTURE_2D: 0x110, CREATE_TEXTURE_CUBE: 0x111,
    UPDATE_TEXTURE: 0x113,
    SET_PALETTE: 0x21F,
    DD_BLT: 0x500, DD_SET_COLOR_KEY: 0x501,
    DD_SET_SURFACE_PALETTE: 0x502, DD_SET_DISPLAY_MODE: 0x503,
    DD_UPDATE_OVERLAY: 0x504,
};

const D9WG_MAGIC = 0x47573944;
const BATCH_FLAG_PRESENT = 1;
const DEVICE = 0x00100002;
const FMT_X8R8G8B8 = 22;
const FMT_R5G6B5 = 23;
const FMT_P8 = 41;
const FMT_D16 = 80;
const USAGE_DEPTHSTENCIL = 0x2;
const USAGE_DDRAW_INDEXED = 0x80000000;

const DDBLT = {
    KEY_SOURCE: 1 << 0, KEY_DESTINATION: 1 << 1,
    MIRROR_X: 1 << 2, MIRROR_Y: 1 << 3,
    COLOR_FILL: 1 << 4, DEPTH_FILL: 1 << 5, FILTER_LINEAR: 1 << 6,
};

const DDOVER = {
    SHOW: 1 << 0, HIDE: 1 << 1,
    KEY_SOURCE: 1 << 2, KEY_DESTINATION: 1 << 3,
    MIRROR_X: 1 << 4, MIRROR_Y: 1 << 5,
    KEY_SOURCE_OVERRIDE: 1 << 6, KEY_DESTINATION_OVERRIDE: 1 << 7,
};

// ---- batch builder (same shape as d3d9_webgpu_executor_test.js) ----

function command(opcode, payload, blob, blobOffsetField) {
    return { opcode, payload, blob: blob || null, blobOffsetField };
}

function buildBatch(commands, options = {}) {
    let commandBytes = 0;
    for (const item of commands) {
        const raw = 16 + item.payload.length + (item.blob ? item.blob.length : 0);
        item.size = (raw + 7) & ~7;
        item.offset = 32 + commandBytes;
        commandBytes += item.size;
    }
    const batch = Buffer.alloc(32 + commandBytes);
    batch.writeUInt32LE(D9WG_MAGIC, 0);
    batch.writeUInt16LE(1, 4);
    batch.writeUInt16LE(options.versionMinor ?? 7, 6);
    batch.writeUInt32LE(options.frameId || 1, 8);
    batch.writeUInt32LE(options.present ? BATCH_FLAG_PRESENT : 0, 12);
    batch.writeUInt32LE(commands.length, 16);
    batch.writeUInt32LE(commandBytes, 20);
    batch.writeUInt32LE(options.sessionLow || 0, 24);
    batch.writeUInt32LE(options.sessionHigh || 0, 28);
    let sequence = 1;
    for (const item of commands) {
        batch.writeUInt16LE(item.opcode, item.offset);
        batch.writeUInt32LE(item.size, item.offset + 4);
        batch.writeUInt32LE(sequence++, item.offset + 8);
        if (item.blob) {
            const blobOffset = item.offset + 16 + item.payload.length;
            item.payload.writeUInt32LE(blobOffset, item.blobOffsetField);
            item.blob.copy(batch, blobOffset);
        }
        item.payload.copy(batch, item.offset + 16);
    }
    return batch;
}

function u32(...values) {
    const buffer = Buffer.alloc(values.length * 4);
    values.forEach((value, index) => buffer.writeUInt32LE(value >>> 0, index * 4));
    return buffer;
}

function createDevicePayload(width, height) {
    const payload = Buffer.alloc(52);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(0x1234, 4);
    payload.writeUInt32LE(width, 16);
    payload.writeUInt32LE(height, 20);
    payload.writeUInt32LE(FMT_X8R8G8B8, 24);
    payload.writeUInt32LE(1, 28);
    return payload;
}

function createSurfacePayload(handle, width, height, format, usage = 0,
        levelCount = 1) {
    const payload = Buffer.alloc(40);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(handle, 4);
    payload.writeUInt32LE(width, 8);
    payload.writeUInt32LE(height, 12);
    payload.writeUInt32LE(levelCount, 16);
    payload.writeUInt32LE(format, 20);
    payload.writeUInt32LE(usage >>> 0, 24);
    return payload;
}

function createCubePayload(handle, edge, levelCount, format, usage = 0) {
    return u32(DEVICE, handle, edge, levelCount, format, usage, 0, 0);
}

function updateTexturePayload(handle, width, height, rowPitch, data,
        options = {}) {
    const payload = Buffer.alloc(48);
    payload.writeUInt32LE(handle, 0);
    payload.writeUInt32LE(options.level || 0, 4);
    payload.writeUInt32LE(options.x || 0, 8);
    payload.writeUInt32LE(options.y || 0, 12);
    payload.writeUInt32LE(options.face || 0, 16);
    payload.writeUInt32LE(width, 20);
    payload.writeUInt32LE(height, 24);
    payload.writeUInt32LE(1, 28);      // depth
    payload.writeUInt32LE(rowPitch, 32);
    payload.writeUInt32LE(options.slicePitch || rowPitch * height, 36);
    payload.writeUInt32LE(data.length, 40);
    return { payload, blob: data, blobOffsetField: 44 };
}

function bltPayload(options) {
    const payload = Buffer.alloc(80);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(options.sourceHandle || 0, 4);
    payload.writeUInt32LE(options.sourceLevel || 0, 8);
    payload.writeUInt32LE(options.sourceFace || 0, 12);
    const source = options.sourceRect || [0, 0, 0, 0];
    source.forEach((value, index) => payload.writeInt32LE(value, 16 + index * 4));
    payload.writeUInt32LE(options.destinationHandle || 0, 32);
    payload.writeUInt32LE(options.destinationLevel || 0, 36);
    payload.writeUInt32LE(options.destinationFace || 0, 40);
    payload.writeUInt32LE(options.flags || 0, 44);
    const destination = options.destinationRect || [0, 0, 0, 0];
    destination.forEach((value, index) =>
        payload.writeInt32LE(value, 48 + index * 4));
    payload.writeUInt32LE(options.fillColor || 0, 64);
    payload.writeFloatLE(options.fillDepth || 0, 68);
    payload.writeUInt32LE(options.fillStencil || 0, 72);
    return payload;
}

function colorKeyPayload(handle, kind, low, high, present = 1) {
    return u32(handle, kind, low, high, present, 0);
}

function overlayPayload(options) {
    const payload = Buffer.alloc(52);
    payload.writeUInt32LE(options.surfaceHandle, 0);
    payload.writeUInt32LE(options.overlayId, 4);
    const source = options.sourceRect || [0, 0, 0, 0];
    source.forEach((value, index) =>
        payload.writeInt32LE(value, 8 + index * 4));
    const destination = options.destinationRect || [0, 0, 0, 0];
    destination.forEach((value, index) =>
        payload.writeInt32LE(value, 24 + index * 4));
    payload.writeUInt32LE(options.flags || 0, 40);
    payload.writeUInt32LE(options.zOrder || 0, 44);
    payload.writeUInt32LE(options.destinationHandle || 0, 48);
    return payload;
}

function surfacePalettePayload(handle, index) {
    return u32(handle, index, 1, 0);
}

function displayModePayload(width, height, bpp, flags, changed) {
    return u32(DEVICE, width, height, bpp, 60, flags, changed ? 1 : 0, 0);
}

function palettePayload(index, entries) {
    const payload = Buffer.alloc(16);
    payload.writeUInt32LE(DEVICE, 0);
    payload.writeUInt32LE(index, 4);
    payload.writeUInt32LE(256, 8);
    const blob = Buffer.alloc(256 * 4);
    for (let i = 0; i < 256; ++i) blob.writeUInt32LE(entries(i) >>> 0, i * 4);
    return { payload, blob, blobOffsetField: 12 };
}

// ---- fake WebGPU ----

function makeFakeWebGPU() {
    const calls = [];
    class FakeBuffer {
        constructor(descriptor) {
            this.descriptor = descriptor;
            this.data = new Uint8Array(descriptor.size);
        }
        destroy() { this.destroyed = true; }
    }
    class FakeTexture {
        constructor(descriptor) { this.descriptor = descriptor; }
        createView(descriptor) { return { texture: this, descriptor }; }
        destroy() { this.destroyed = true; }
    }
    class FakePass {
        constructor(descriptor) {
            this.descriptor = descriptor;
            calls.push(["beginRenderPass", descriptor, this]);
        }
        setPipeline(pipeline) { calls.push(["setPipeline", pipeline, this]); }
        setBindGroup(...a) { calls.push(["setBindGroup", ...a]); }
        setViewport(...a) { calls.push(["setViewport", ...a]); }
        setScissorRect(...a) { calls.push(["setScissorRect", ...a]); }
        setStencilReference(...a) { calls.push(["setStencilReference", ...a]); }
        setVertexBuffer(...a) { calls.push(["setVertexBuffer", ...a]); }
        setIndexBuffer(...a) { calls.push(["setIndexBuffer", ...a]); }
        draw(...a) { calls.push(["draw", ...a]); }
        drawIndexed(...a) { calls.push(["drawIndexed", ...a]); }
        end() { calls.push(["endPass", this]); }
    }
    class FakeEncoder {
        beginRenderPass(descriptor) { return new FakePass(descriptor); }
        copyTextureToTexture(...a) { calls.push(["copyTextureToTexture", ...a]); }
        copyTextureToBuffer(...a) { calls.push(["copyTextureToBuffer", ...a]); }
        copyBufferToBuffer(...a) { calls.push(["copyBufferToBuffer", ...a]); }
        finish() { return { encoder: this }; }
    }
    const queue = {
        writeBuffer(buffer, offset, data, dataOffset, size) {
            const view = ArrayBuffer.isView(data)
                ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
                : new Uint8Array(data);
            calls.push(["writeBuffer", buffer, offset, view.slice()]);
        },
        writeTexture(destination, data, layout, size) {
            const view = ArrayBuffer.isView(data)
                ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
                : new Uint8Array(data);
            calls.push(["writeTexture", destination, view.slice(), layout, size]);
        },
        submit(buffers) { calls.push(["submit", buffers]); },
        onSubmittedWorkDone() { return Promise.resolve(); },
    };
    const device = {
        queue,
        lost: new Promise(() => {}),
        features: new Set(),
        createShaderModule(descriptor) {
            const module = { descriptor, code: descriptor.code,
                getCompilationInfo: async () => ({ messages: [] }) };
            calls.push(["createShaderModule", descriptor, module]);
            return module;
        },
        createBuffer(descriptor) {
            const buffer = new FakeBuffer(descriptor);
            calls.push(["createBuffer", descriptor, buffer]);
            return buffer;
        },
        createTexture(descriptor) {
            const texture = new FakeTexture(descriptor);
            calls.push(["createTexture", descriptor, texture]);
            return texture;
        },
        createSampler(descriptor) {
            const sampler = { descriptor };
            calls.push(["createSampler", descriptor, sampler]);
            return sampler;
        },
        createCommandEncoder() { return new FakeEncoder(); },
        createQuerySet(descriptor) {
            return { descriptor, values: new BigUint64Array(descriptor.count),
                destroy() {} };
        },
        createBindGroupLayout(descriptor) {
            const layout = { descriptor,
                bindings: new Set(descriptor.entries.map(e => e.binding)) };
            calls.push(["createBindGroupLayout", descriptor, layout]);
            return layout;
        },
        createPipelineLayout(descriptor) { return { descriptor }; },
        createRenderPipeline(descriptor) {
            const pipeline = { descriptor };
            calls.push(["createRenderPipeline", descriptor, pipeline]);
            return pipeline;
        },
        createBindGroup(descriptor) {
            const declared = descriptor.layout.bindings;
            const supplied = new Set(descriptor.entries.map(e => e.binding));
            for (const binding of supplied)
                assert.ok(declared.has(binding),
                    "bind group supplies binding " + binding +
                    " which its layout does not declare");
            for (const binding of declared)
                assert.ok(supplied.has(binding),
                    "bind group layout declares binding " + binding +
                    " but the bind group does not supply it");
            calls.push(["createBindGroup", descriptor]);
            return descriptor;
        },
    };
    const context = {
        configure(descriptor) { calls.push(["configure", descriptor]); },
        getCurrentTexture() {
            return { width: 640, height: 480,
                createView: () => ({ swapchain: true }) };
        },
    };
    const gpu = {
        async requestAdapter() {
            return { features: new Set(),
                async requestDevice() { return device; } };
        },
        getPreferredCanvasFormat() { return "bgra8unorm"; },
    };
    return { calls, device, context, gpu };
}

function makeExecutor(options = {}) {
    const fake = makeFakeWebGPU();
    const canvas = { width: 1, height: 1, getContext: () => fake.context };
    const executor = new D3D9WebGPUExecutor(canvas, { gpu: fake.gpu, ...options });
    return { fake, executor, calls: fake.calls,
        find: name => fake.calls.filter(call => call[0] === name),
        last: name => {
            const matches = fake.calls.filter(call => call[0] === name);
            return matches[matches.length - 1];
        } };
}

// The blit uniform block, read back out of the writeBuffer the replay made.
function uniformBlock(find) {
    const write = find("writeBuffer").filter(call => call[3].length === 128).pop();
    assert.ok(write, "no 128-byte blit uniform upload was made");
    const bytes = write[3];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    return {
        sourceRect: [view.getFloat32(0, true), view.getFloat32(4, true),
            view.getFloat32(8, true), view.getFloat32(12, true)],
        sourceSize: [view.getFloat32(16, true), view.getFloat32(20, true)],
        keyLow: [view.getUint32(32, true), view.getUint32(36, true),
            view.getUint32(40, true)],
        keyHigh: [view.getUint32(48, true), view.getUint32(52, true),
            view.getUint32(56, true)],
        fill: [view.getFloat32(64, true), view.getFloat32(68, true),
            view.getFloat32(72, true), view.getFloat32(76, true)],
        fillIndex: view.getUint32(80, true),
        destinationKeyLow: [view.getUint32(96, true),
            view.getUint32(100, true), view.getUint32(104, true)],
        destinationKeyHigh: [view.getUint32(112, true),
            view.getUint32(116, true), view.getUint32(120, true)],
    };
}

// ---- harness ----

const failures = [];
let passed = 0;

async function test(name, body) {
    try {
        await body();
        ++passed;
    } catch (error) {
        failures.push({ name, error });
    }
}

const SURFACE_SETUP = (handle, width, height, format, usage) =>
    command(OP.CREATE_TEXTURE_2D,
        createSurfacePayload(handle, width, height, format, usage));

async function main() {

await test("a palettised surface is stored as r8uint indices, not expanded to RGBA",
        async () => {
    const { executor, find } = makeExecutor();
    const indices = Buffer.alloc(4 * 4);
    for (let i = 0; i < indices.length; ++i) indices[i] = i * 7;
    const update = updateTexturePayload(0x300, 4, 4, 4, indices);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 4, 4, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.UPDATE_TEXTURE, update.payload, update.blob,
            update.blobOffsetField),
    ]));
    const created = find("createTexture")
        .find(call => call[1].size.width === 4);
    assert.ok(created, "the surface was never created");
    assert.equal(created[1].format, "r8uint",
        "an indexed DirectDraw surface must keep its indices");
    const resource = executor.resources.get(0x300);
    assert.equal(resource.ddIndexed, true);
    assert.equal(resource.gpuBytesPerTexel, 1,
        "one byte per texel, not the four an expanded P8 would take");
    const shadow = [...resource.textureShadows.values()][0];
    assert.ok(shadow, "the surface kept no CPU shadow of its indices");
    assert.deepEqual([...shadow.data.subarray(0, 4)], [0, 7, 14, 21],
        "the stored bytes are the app's indices, unmodified");
    const upload = find("writeTexture").find(call =>
        call[1].texture === resource.gpuTexture);
    assert.ok(upload, "the r8uint texture itself was never uploaded");
    assert.deepEqual([...upload[2].subarray(0, 4)], [0, 7, 14, 21]);
});

await test("D3D sampling resolves a surface palette and keys the original index",
        async () => {
    const { executor, find } = makeExecutor();
    const indices = Buffer.from([7, 9]);
    const update = updateTexturePayload(0x300, 2, 1, 2, indices);
    const palette = palettePayload(3,
        index => (0xff000000 | (index << 16) | (index << 8)) >>> 0);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 2, 1, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.UPDATE_TEXTURE, update.payload, update.blob,
            update.blobOffsetField),
        command(OP.SET_PALETTE, palette.payload, palette.blob,
            palette.blobOffsetField),
        command(OP.DD_SET_SURFACE_PALETTE, surfacePalettePayload(0x300, 3)),
        command(OP.DD_SET_COLOR_KEY, colorKeyPayload(0x300, 0, 9, 9)),
    ]));
    const resource = executor.resources.get(0x300);
    const sampled = executor.ddIndexedSampleViewFor(resource,
        resource.ddColorKey[0]);
    assert.ok(sampled, "no filterable sampling companion was created");
    const resolvedTexture = find("createTexture").find(call =>
        call[1].label === "DirectDraw indexed D3D sample view")[2];
    const resolvedUpload = find("writeTexture").find(call =>
        call[1].texture === resolvedTexture);
    assert.ok(resolvedUpload, "the RGBA companion received no pixels");
    assert.deepEqual([...resolvedUpload[2]], [7, 7, 0, 255, 9, 9, 0, 0],
        "index 9 must become transparent without keying duplicate RGB values");
    assert.equal(executor.getStats().ddIndexedSampleResolves, 1);
});

await test("cube mip uploads and DirectDraw blits address the requested subresources",
        async () => {
    const { executor, find } = makeExecutor();
    const texels = Buffer.alloc(2 * 2 * 4, 0x5a);
    const update = updateTexturePayload(0x300, 2, 2, 8, texels,
        { level: 2, face: 5 });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.CREATE_TEXTURE_CUBE,
            createCubePayload(0x300, 8, 4, FMT_X8R8G8B8)),
        SURFACE_SETUP(0x301, 2, 2, FMT_X8R8G8B8),
        command(OP.UPDATE_TEXTURE, update.payload, update.blob,
            update.blobOffsetField),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceLevel: 2, sourceFace: 5,
            sourceRect: [0, 0, 2, 2],
            destinationHandle: 0x301, destinationRect: [0, 0, 2, 2],
        })),
    ], { present: true }));
    const cube = executor.resources.get(0x300);
    assert.equal(cube.textureType, "cube");
    assert.equal(cube.levelCount, 4);
    assert.equal(cube.layerCount, 6);
    const upload = find("writeTexture").find(call =>
        call[1].texture === cube.gpuTexture);
    assert.ok(upload, "the cube face/mip upload never reached WebGPU");
    assert.equal(upload[1].mipLevel, 2);
    assert.deepEqual(upload[1].origin, { x: 0, y: 0, z: 5 });
    const copy = find("copyTextureToTexture").find(call =>
        call[1].texture === cube.gpuTexture);
    assert.ok(copy, "the cube subresource blit was not copied");
    assert.equal(copy[1].mipLevel, 2);
    assert.deepEqual(copy[1].origin, { x: 0, y: 0, z: 5 });
    assert.equal(copy[2].mipLevel, 0);
    assert.deepEqual(copy[2].origin, { x: 0, y: 0, z: 0 });
});

await test("a plain same-format blit is a copy, not a render pass", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        SURFACE_SETUP(0x301, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 32, 32],
            destinationHandle: 0x301, destinationRect: [8, 8, 40, 40],
        })),
    ], { present: true }));
    // Filtered by extent: a present copies the back buffer too, and that
    // copy is not the one under test.
    const copies = find("copyTextureToTexture")
        .filter(call => call[3] && call[3].width === 32);
    assert.equal(copies.length, 1, "the blit should be one texture copy");
    assert.deepEqual(copies[0][1].origin, { x: 0, y: 0, z: 0 });
    assert.deepEqual(copies[0][2].origin, { x: 8, y: 8, z: 0 });
    assert.deepEqual(copies[0][3], { width: 32, height: 32, depthOrArrayLayers: 1 });
    assert.equal(executor.getStats().ddBlitsCopied, 1);
    assert.deepEqual([...executor.resources.get(0x301).uploadedLevels], [0],
        "a GPU copy must initialize the destination level");
});

await test("a scaled DirectDraw blit initializes its texture destination",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 320, 320, FMT_X8R8G8B8),
        SURFACE_SETUP(0x301, 256, 256, FMT_X8R8G8B8),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 320, 320],
            destinationHandle: 0x301, destinationRect: [0, 0, 256, 256],
        })),
    ], { present: true }));
    const destination = executor.resources.get(0x301);
    assert.deepEqual([...destination.uploadedLevels], [0],
        "the render-blit path must count as a level-0 GPU write");
    assert.ok(find("createRenderPipeline").some(call =>
        String(call[1].label).startsWith("DirectDraw blit")),
    "the test must exercise the scaled render-blit path");
});

await test("a colour-keyed indexed blit discards on the index and stays indexed",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        SURFACE_SETUP(0x301, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.DD_SET_COLOR_KEY, colorKeyPayload(0x300, 0, 253, 253)),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 16, 16],
            destinationHandle: 0x301, destinationRect: [0, 0, 16, 16],
            flags: DDBLT.KEY_SOURCE,
        })),
    ], { present: true }));
    const pipeline = find("createRenderPipeline")
        .find(call => String(call[1].label).startsWith("DirectDraw blit"));
    assert.ok(pipeline, "no DirectDraw blit pipeline was created");
    assert.equal(pipeline[1].fragment.targets[0].format, "r8uint",
        "an indexed destination must be written as indices");
    const module = find("createShaderModule")
        .find(call => String(call[1].label).startsWith("ddraw blit"));
    assert.match(module[1].code, /texture_2d<u32>/,
        "an indexed source is read with textureLoad, not sampled");
    assert.match(module[1].code,
        /index >= blit\.key_low\.x && index <= blit\.key_high\.x/,
        "the colour key must compare the index itself");
    assert.match(module[1].code, /-> @location\(0\) vec4<u32>/);
    const block = uniformBlock(find);
    assert.equal(block.keyLow[0], 253);
    assert.equal(block.keyHigh[0], 253);
    assert.equal(executor.getStats().ddBlitsColorKeyed, 1);
});

await test("an indexed surface presented to the canvas resolves through its palette",
        async () => {
    const { executor, find } = makeExecutor();
    const palette = palettePayload(0, i => (0xff000000 | (i << 16)) >>> 0);
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 640, 480, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.SET_PALETTE, palette.payload, palette.blob,
            palette.blobOffsetField),
        command(OP.DD_SET_SURFACE_PALETTE, surfacePalettePayload(0x300, 0)),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 640, 480],
            destinationHandle: 0, destinationRect: [0, 0, 640, 480],
        })),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    const module = find("createShaderModule")
        .find(call => String(call[1].label).includes("pal"));
    assert.ok(module, "no palette-resolving blit shader was built");
    assert.match(module[1].code, /d9dd_palette\.entries\[index\]/);
    const layout = find("createBindGroupLayout")
        .find(call => call[1].entries.some(entry => entry.binding === 3));
    assert.ok(layout, "the palette buffer has no binding");
    const paletteBuffer = find("createBuffer")
        .find(call => String(call[1].label || "").startsWith("DirectDraw palette"));
    assert.ok(paletteBuffer, "the palette was never uploaded to the GPU");
    assert.equal(paletteBuffer[1].size, 256 * 16);
    const write = find("writeBuffer").find(call => call[1] === paletteBuffer[2]);
    assert.ok(write, "the palette buffer was never written");
    const floats = new Float32Array(write[3].buffer, write[3].byteOffset,
        write[3].byteLength / 4);
    // Entry 3 was 0xff030000: red = 3/255, and the wire is BGRA-ordered
    // D3DCOLOR, so the red channel has to survive the swap.
    assert.ok(Math.abs(floats[3 * 4] - 3 / 255) < 1e-6,
        "palette entry red channel: got " + floats[3 * 4]);
    assert.equal(floats[3 * 4 + 3], 1, "palette alpha");
});

await test("mirroring is a negative source extent, not a second pipeline",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_X8R8G8B8),
        SURFACE_SETUP(0x301, 64, 64, FMT_X8R8G8B8),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 32, 32],
            destinationHandle: 0x301, destinationRect: [0, 0, 32, 32],
            flags: DDBLT.MIRROR_X,
        })),
    ], { present: true }));
    const block = uniformBlock(find);
    assert.equal(block.sourceRect[0], 0.5, "u starts at the right edge");
    assert.equal(block.sourceRect[2], -0.5, "and runs backwards");
    assert.equal(block.sourceRect[3], 0.5, "v is untouched");
    assert.equal(executor.getStats().ddBlitsMirrored, 1);
    const pipelines = find("createRenderPipeline")
        .filter(call => String(call[1].label).startsWith("DirectDraw blit"));
    assert.equal(pipelines.length, 1, "mirroring must not fork the pipeline");
});

await test("a destination rectangle clipped to the surface takes the source with it",
        async () => {
    const clipped = ddraw.clipRects(
        { left: 0, top: 0, right: 32, bottom: 32 },
        { left: -16, top: -16, right: 16, bottom: 16 }, 640, 480);
    assert.deepEqual(clipped.viewport, [0, 0, 16, 16]);
    assert.deepEqual(clipped.source,
        { left: 16, top: 16, right: 32, bottom: 32 },
        "the visible half of the sprite is the half that gets read");

    const scaled = ddraw.clipRects(
        { left: 0, top: 0, right: 32, bottom: 32 },
        { left: 0, top: 0, right: 64, bottom: 64 }, 32, 32);
    assert.deepEqual(scaled.viewport, [0, 0, 32, 32]);
    assert.deepEqual(scaled.source,
        { left: 0, top: 0, right: 16, bottom: 16 },
        "a 2x stretch clipped in half reads half the source");
});

await test("a true-colour blit into a palettised surface is refused", async () => {
    const warnings = [];
    const { executor } = makeExecutor({ onWarning: (...a) => warnings.push(a) });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_X8R8G8B8),
        SURFACE_SETUP(0x301, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 16, 16],
            destinationHandle: 0x301, destinationRect: [0, 0, 16, 16],
        })),
    ], { present: true }));
    assert.equal(executor.getStats().ddBlitsSkipped, 1);
    assert.equal(executor.getStats().ddBlitsCopied, undefined);
});

await test("DDBLT_KEYSRC with no key attached is refused, not blitted opaquely",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_X8R8G8B8),
        SURFACE_SETUP(0x301, 64, 64, FMT_X8R8G8B8),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 16, 16],
            destinationHandle: 0x301, destinationRect: [0, 0, 16, 16],
            flags: DDBLT.KEY_SOURCE,
        })),
    ], { present: true }));
    assert.equal(executor.getStats().ddBlitsSkipped, 1);
    assert.equal(find("copyTextureToTexture")
        .filter(call => call[3] && call[3].width === 16).length, 0,
        "nothing may be copied when the blit was refused");
});

await test("a destination colour key snapshots and tests the old target pixels",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_X8R8G8B8),
        SURFACE_SETUP(0x301, 64, 64, FMT_X8R8G8B8),
        command(OP.DD_SET_COLOR_KEY,
            colorKeyPayload(0x301, 1, 0x00112233, 0x00445566)),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 16, 16],
            destinationHandle: 0x301, destinationRect: [0, 0, 16, 16],
            flags: DDBLT.KEY_DESTINATION,
        })),
    ], { present: true }));
    const destination = executor.resources.get(0x301);
    const snapshot = find("createTexture").find(call =>
        call[1].label === "DirectDraw destination colour-key snapshot");
    assert.ok(snapshot, "the target was not snapshotted before drawing");
    const copy = find("copyTextureToTexture").find(call =>
        call[1].texture === destination.gpuTexture &&
        call[2].texture === snapshot[2]);
    assert.ok(copy, "the key shader must read the pre-blit target pixels");
    const layout = find("createBindGroupLayout").find(call =>
        call[1].entries.some(entry => entry.binding === 4));
    assert.ok(layout, "the destination snapshot has no shader binding");
    const shader = find("createShaderModule").find(call =>
        String(call[1].label).includes("dest-key"));
    assert.ok(shader, "the destination-key shader variant was not selected");
    assert.match(shader[1].code, /d9dd_destination_key/);
    assert.match(shader[1].code,
        /any\(destination_quantised < blit\.destination_key_low\.rgb\)/);
    const block = uniformBlock(find);
    assert.deepEqual(block.destinationKeyLow, [0x11, 0x22, 0x33]);
    assert.deepEqual(block.destinationKeyHigh, [0x44, 0x55, 0x66]);
    assert.equal(executor.getStats().ddBlitsDestinationKeyed, 1);
    assert.equal(executor.getStats().ddBlitsSkipped, undefined);
});

await test("a destination-keyed self blit samples only a detached snapshot",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_X8R8G8B8),
        command(OP.DD_SET_COLOR_KEY,
            colorKeyPayload(0x300, 1, 0, 0x00ffffff)),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 32, 32],
            destinationHandle: 0x300, destinationRect: [16, 16, 48, 48],
            flags: DDBLT.KEY_DESTINATION,
        })),
    ], { present: true }));
    const surface = executor.resources.get(0x300);
    const snapshot = find("createTexture").find(call =>
        call[1].label === "DirectDraw destination colour-key snapshot");
    assert.ok(snapshot);
    const bindGroup = find("createBindGroup").find(call =>
        call[1].entries.some(entry => entry.binding === 4));
    const sourceBinding = bindGroup[1].entries.find(entry => entry.binding === 1);
    const destinationBinding = bindGroup[1].entries.find(
        entry => entry.binding === 4);
    assert.equal(sourceBinding.resource.texture, snapshot[2]);
    assert.equal(destinationBinding.resource.texture, snapshot[2]);
    assert.notEqual(sourceBinding.resource.texture, surface.gpuTexture,
        "sampling a texture while rendering to it violates WebGPU validation");
});

await test("depth-fill on a colour target is still refused", async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x301, 64, 64, FMT_X8R8G8B8),
        command(OP.DD_BLT, bltPayload({
            destinationHandle: 0x301, destinationRect: [0, 0, 16, 16],
            flags: DDBLT.DEPTH_FILL,
        })),
    ], { present: true }));
    assert.equal(executor.getStats().ddBlitsSkipped, 1);
});

await test("overlays composite by identity, z order, keys and mirroring",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(320, 200)),
        SURFACE_SETUP(0x310, 64, 32, FMT_X8R8G8B8),
        SURFACE_SETUP(0x311, 320, 200, FMT_X8R8G8B8),
        command(OP.DD_SET_COLOR_KEY,
            colorKeyPayload(0x310, 2, 0x00010203, 0x00010203)),
        command(OP.DD_UPDATE_OVERLAY, overlayPayload({
            surfaceHandle: 0x310, overlayId: 0xabc001,
            sourceRect: [0, 0, 64, 32], destinationRect: [10, 20, 138, 84],
            flags: DDOVER.SHOW | DDOVER.KEY_SOURCE | DDOVER.MIRROR_X,
            zOrder: 7, destinationHandle: 0x311,
        })),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 320, 200)),
    ], { present: true }));

    const state = executor.devices.get(DEVICE);
    assert.equal(state.ddOverlays.size, 1);
    const entry = state.ddOverlays.get(0xabc001);
    assert.ok(entry, "the overlay must be keyed by COM-surface identity");
    assert.equal(entry.surfaceHandle, 0x310);
    assert.equal(entry.zOrder, 7);
    const composite = find("createTexture").find(call =>
        call[1].label === "DirectDraw overlay composite");
    assert.ok(composite, "present did not build an overlay scanout image");
    const viewport = find("setViewport").find(call =>
        call[1] === 10 && call[2] === 20 && call[3] === 128 && call[4] === 64);
    assert.ok(viewport, "overlay destination position/stretch was lost");
    const block = uniformBlock(find);
    assert.equal(block.sourceRect[0], 1, "mirrored overlay begins at right edge");
    assert.equal(block.sourceRect[2], -1, "mirrored overlay walks backwards");
    assert.deepEqual(block.keyLow, [1, 2, 3]);
    assert.equal(executor.getStats().ddOverlayUpdates, 1);
    assert.equal(executor.getStats().ddOverlayComposites, 1);

    await executor.submit(buildBatch([
        command(OP.DD_UPDATE_OVERLAY, overlayPayload({
            surfaceHandle: 0x310, overlayId: 0xabc001,
            sourceRect: [0, 0, 64, 32], destinationRect: [10, 20, 138, 84],
            flags: DDOVER.HIDE, zOrder: 7, destinationHandle: 0x311,
        })),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 320, 200)),
    ], { present: true, frameId: 2 }));
    assert.equal(state.ddOverlays.has(0xabc001), false,
        "hiding releases the host-side persistent overlay entry");
    assert.equal(executor.getStats().ddOverlayComposites, 1,
        "a hidden overlay must not be composited again");
});

await test("duplicate overlay aliases keep independent host state",
        async () => {
    const { executor } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(320, 200)),
        SURFACE_SETUP(0x310, 64, 32, FMT_X8R8G8B8),
        SURFACE_SETUP(0x311, 320, 200, FMT_X8R8G8B8),
        command(OP.DD_UPDATE_OVERLAY, overlayPayload({
            surfaceHandle: 0x310, overlayId: 0xabc001,
            sourceRect: [0, 0, 64, 32], destinationRect: [8, 8, 72, 40],
            flags: DDOVER.SHOW, zOrder: 0, destinationHandle: 0x311,
        })),
        command(OP.DD_UPDATE_OVERLAY, overlayPayload({
            surfaceHandle: 0x310, overlayId: 0xabc002,
            sourceRect: [0, 0, 64, 32], destinationRect: [80, 8, 144, 40],
            flags: DDOVER.SHOW | DDOVER.MIRROR_Y,
            zOrder: 1, destinationHandle: 0x311,
        })),
    ]));
    const overlays = executor.devices.get(DEVICE).ddOverlays;
    assert.equal(overlays.size, 2,
        "shared pixels must not collapse two COM overlay objects");
    assert.deepEqual(overlays.get(0xabc001).destinationRect, [8, 8, 72, 40]);
    assert.deepEqual(overlays.get(0xabc002).destinationRect,
        [80, 8, 144, 40]);
    assert.equal(overlays.get(0xabc001).visible, true);
    assert.equal(overlays.get(0xabc002).visible, true);
});

await test("DDBLT_DEPTHFILL clears the requested depth rectangle", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x302, 64, 64, FMT_D16, USAGE_DEPTHSTENCIL),
        command(OP.DD_BLT, bltPayload({
            destinationHandle: 0x302,
            destinationRect: [8, 12, 40, 44],
            flags: DDBLT.DEPTH_FILL, fillDepth: 0.5,
        })),
    ], { present: true }));
    const pass = find("beginRenderPass").find(call =>
        call[1].colorAttachments.length === 0 &&
        call[1].depthStencilAttachment);
    assert.ok(pass, "the depth fill did not open a depth-only render pass");
    const viewport = find("setViewport").find(call =>
        call[1] === 8 && call[2] === 12 && call[3] === 32 && call[4] === 32);
    assert.ok(viewport, "the depth fill did not preserve its destination rect");
    const uniformWrite = find("writeBuffer").find(call => call[3].length === 32);
    assert.ok(uniformWrite, "the depth fill value was not uploaded");
    const depth = new DataView(uniformWrite[3].buffer,
        uniformWrite[3].byteOffset, uniformWrite[3].byteLength)
        .getFloat32(16, true);
    assert.equal(depth, 0.5);
    assert.equal(executor.getStats().ddDepthFills, 1);
});

await test("a colour fill needs no source binding at all", async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        SURFACE_SETUP(0x300, 64, 64, FMT_P8, USAGE_DDRAW_INDEXED),
        command(OP.DD_BLT, bltPayload({
            destinationHandle: 0x300, destinationRect: [0, 0, 64, 64],
            flags: DDBLT.COLOR_FILL, fillColor: 42,
        })),
    ], { present: true }));
    const layout = find("createBindGroupLayout")
        .find(call => call[1].entries.length === 1 &&
            call[1].entries[0].buffer);
    assert.ok(layout, "the fill variant should declare only its uniform block");
    assert.equal(uniformBlock(find).fillIndex, 42,
        "an indexed fill carries the palette index, not a colour");
    assert.equal(executor.getStats().ddFills, 1);
});

await test("a normal primary presents only the 3DMark splash dirty rectangle",
        async () => {
    const presented = [];
    const { executor } = makeExecutor({
        onPresent: surface => presented.push({ ...surface,
            clipRect: surface.clipRect && { ...surface.clipRect } }),
    });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(800, 600)),
        command(OP.DD_SET_DISPLAY_MODE,
            displayModePayload(800, 600, 32, 1 << 0, false)),
        SURFACE_SETUP(0x300, 800, 600, FMT_X8R8G8B8),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [190, 215, 610, 385],
            destinationHandle: 0, destinationRect: [190, 215, 610, 385],
        })),
        // 3DMark reports the 800x600 desktop at Present even though it changed
        // only the centred 420x170 splash rectangle.
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 800, 600)),
    ], { present: true }));
    assert.equal(presented.length, 1);
    assert.equal(presented[0].ddDesktopPrimary, true);
    assert.equal(presented[0].displayWidth, 800);
    assert.equal(presented[0].displayHeight, 600);
    assert.deepEqual(presented[0].clipRect, {
        left: 190, top: 215, right: 610, bottom: 385,
        baseWidth: 800, baseHeight: 600,
    });
    assert.equal(presented[0].width, 800);
});

await test("an exclusive fullscreen display mode repositions the overlay",
        async () => {
    const surfaces = [];
    const { executor } = makeExecutor({
        onSurface: (surface, reason) => surfaces.push({ ...surface, reason }),
    });
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(1024, 768)),
        command(OP.DD_SET_DISPLAY_MODE,
            displayModePayload(640, 480, 8, (1 << 1) | (1 << 2), true)),
    ]));
    const mode = surfaces.filter(s => s.reason === "display-mode").pop();
    assert.ok(mode, "a display mode change must reach the page");
    assert.equal(mode.width, 640);
    assert.equal(mode.height, 480);
    assert.equal(mode.x, 0, "a real mode change puts the window at the origin");
    assert.equal(mode.fullscreen, true);

    // ChangeDisplaySettings failed in the guest: the window is still a window,
    // so the overlay must not jump to the origin.
    const windowed = makeExecutor({
        onSurface: (surface, reason) => surfaces.push({ ...surface, reason }),
    });
    await windowed.executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(1024, 768)),
        command(OP.DD_SET_DISPLAY_MODE,
            displayModePayload(640, 480, 16, (1 << 1) | (1 << 2), false)),
    ]));
    const state = windowed.executor.devices.get(DEVICE);
    assert.equal(state.ddDisplayMode.guestModeChanged, false);
    assert.equal(state.ddDisplayMode.bitsPerPixel, 16);
});

await test("a DirectDraw display mode resizes the implicit back buffer",
        async () => {
    const { executor, find } = makeExecutor();

    // dxdiag sets its cooperative level while its temporary client area is
    // only 106x2, then switches to a 640x480 DirectDraw display mode.
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(106, 2)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 106, 2)),
    ], { present: true }));
    const oldBackBuffer = executor.backBufferTexture;
    assert.ok(oldBackBuffer, "the transient-size back buffer was not created");
    assert.equal(executor.canvas.width, 106);
    assert.equal(executor.canvas.height, 2);

    await executor.submit(buildBatch([
        command(OP.DD_SET_DISPLAY_MODE,
            displayModePayload(640, 480, 16,
                (1 << 1) | (1 << 2), true)),
        SURFACE_SETUP(0x300, 640, 480, FMT_R5G6B5),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x300, sourceRect: [0, 0, 640, 480],
            destinationHandle: 0, destinationRect: [0, 0, 640, 480],
        })),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { present: true }));
    await Promise.resolve();

    const state = executor.devices.get(DEVICE);
    assert.equal(state.backBufferWidth, 640);
    assert.equal(state.backBufferHeight, 480);
    assert.equal(executor.canvas.width, 640);
    assert.equal(executor.canvas.height, 480);
    assert.notEqual(executor.backBufferTexture, oldBackBuffer);
    assert.equal(oldBackBuffer.destroyed, true,
        "the retained 106x2 back buffer survived the mode switch");
    assert.deepEqual(executor.backBufferTexture.descriptor.size,
        { width: 640, height: 480, depthOrArrayLayers: 1 });

    const blitViewport = find("setViewport")
        .find(call => call[1] === 0 && call[2] === 0 &&
            call[3] === 640 && call[4] === 480);
    assert.ok(blitViewport,
        "SCREEN_BLT was still clipped to the transient device size");
});

await test("an unknown surface handle is skipped rather than guessed at",
        async () => {
    const { executor, find } = makeExecutor();
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
        command(OP.DD_BLT, bltPayload({
            sourceHandle: 0x999, sourceRect: [0, 0, 16, 16],
            destinationHandle: 0, destinationRect: [0, 0, 16, 16],
        })),
    ], { present: true }));
    assert.equal(executor.getStats().ddBlitsSkipped, 1);
    assert.equal(find("beginRenderPass").length, 0);
});

await test("retained back buffers are isolated by process session", async () => {
    const { executor } = makeExecutor();
    const sessionA = { sessionLow: 0x11111111, sessionHigh: 0xaaaaaaaa };
    const sessionB = { sessionLow: 0x22222222, sessionHigh: 0xbbbbbbbb };
    const keyA = "aaaaaaaa11111111";
    const keyB = "bbbbbbbb22222222";
    const present = () => command(OP.PRESENT,
        u32(DEVICE, 0x1234, 0, 0, 320, 200));

    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(320, 200)), present(),
    ], { ...sessionA, present: true }));
    const backBufferA = executor.sessionStates.get(keyA).backBufferTexture;
    assert.ok(backBufferA, "session A retained no back buffer");
    assert.equal(executor.canvas.width, 320);
    assert.equal(executor.canvas.height, 200);

    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(640, 480)),
    ], sessionB));
    assert.equal(executor.canvas.width, 320,
        "a non-presenting helper must not resize the visible canvas");
    assert.equal(executor.canvas.height, 200);
    await executor.submit(buildBatch([
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 640, 480)),
    ], { ...sessionB, present: true }));
    const backBufferB = executor.sessionStates.get(keyB).backBufferTexture;
    assert.ok(backBufferB, "session B retained no back buffer");
    assert.equal(executor.canvas.width, 640);
    assert.equal(executor.canvas.height, 480);
    assert.notEqual(backBufferB, backBufferA,
        "two processes must not alias one retained texture");
    assert.notEqual(backBufferA.destroyed, true,
        "switching sessions must not destroy the inactive owner's frame");

    await executor.submit(buildBatch([present()],
        { ...sessionA, present: true }));
    assert.equal(executor.backBufferTexture, backBufferA,
        "switching back must restore session A's retained texture");
    assert.equal(executor.canvas.width, 320);
    assert.equal(executor.canvas.height, 200);
    assert.notEqual(backBufferB.destroyed, true);
});

await test("destroying the DirectDraw device retires its retained frame",
        async () => {
    const destroyed = [];
    const { executor } = makeExecutor({
        onDestroy: (surface, reason) => destroyed.push({ ...surface, reason }),
    });
    const session = { sessionLow: 0x33333333, sessionHigh: 0xcccccccc };
    const key = "cccccccc33333333";
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(320, 200)),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 320, 200)),
    ], { ...session, present: true }));
    const backBuffer = executor.sessionStates.get(key).backBufferTexture;

    await executor.submit(buildBatch([
        command(OP.DESTROY_RESOURCE, u32(DEVICE, 0)),
    ], session));
    await Promise.resolve();
    assert.equal(executor.devices.size, 0);
    assert.equal(executor.backBufferTexture, null);
    assert.equal(backBuffer.destroyed, true);
    assert.equal(destroyed.length, 1);
    assert.equal(destroyed[0].visible, false);
    assert.equal(destroyed[0].reason, "device");
});

await test("SESSION_END releases every live object owned by the process",
        async () => {
    const destroyed = [];
    const { executor } = makeExecutor({
        onDestroy: (surface, reason) => destroyed.push({ ...surface, reason }),
    });
    const session = { sessionLow: 0x44444444, sessionHigh: 0xdddddddd };
    const key = "dddddddd44444444";
    await executor.submit(buildBatch([
        command(OP.CREATE_DEVICE, createDevicePayload(320, 200)),
        SURFACE_SETUP(0x300, 16, 16, FMT_X8R8G8B8),
        command(OP.PRESENT, u32(DEVICE, 0x1234, 0, 0, 320, 200)),
    ], { ...session, present: true }));
    const state = executor.sessionStates.get(key);
    const backBuffer = state.backBufferTexture;
    const surfaceTexture = state.resources.get(0x300).gpuTexture;

    await executor.submit(buildBatch([
        command(OP.SESSION_END,
            u32(session.sessionLow, session.sessionHigh)),
    ], session));
    await Promise.resolve();
    assert.equal(executor.sessionKey, null);
    assert.equal(executor.sessionStates.has(key), false);
    assert.equal(executor.getStats().sessionsEnded, 1);
    assert.equal(backBuffer.destroyed, true);
    assert.equal(surfaceTexture.destroyed, true);
    assert.equal(destroyed.length, 1);
    assert.equal(destroyed[0].reason, "session-end");
    assert.equal(destroyed[0].visible, false);
});

// ---- report ----

if (failures.length) {
    for (const failure of failures) {
        console.error("FAIL " + failure.name);
        console.error("     " + (failure.error && failure.error.message));
    }
    console.error(failures.length + " failed, " + passed + " passed");
    process.exit(1);
}
console.log(passed + " ddraw executor tests passed");
}

if (require.main === module) main().catch(error => { console.error(error); process.exit(1); });

module.exports = { makeExecutor, buildBatch, command, u32, createDevicePayload, createSurfacePayload, updateTexturePayload, bltPayload, palettePayload, OP, DEVICE, FMT_P8, USAGE_DDRAW_INDEXED };
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/glbridge/display_canvas_browser_test.html                                          0000644 0000000 0000000 00000013135 00000000000 021300  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>One canvas for text and graphics</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script type="module">
// Text and graphics modes share one canvas (docs/display-design.md).
// A boot sector switches text -> 13h -> text -> 13h, signalling each
// phase on COM1 and waiting for a byte before the next one:
//
//   mode 3, print "PHASE ONE TEXT"     -> '1'
//   mode 13h, fill with colour 4 (red) -> '2'
//   mode 3, print "PHASE THREE TEXT"   -> '3'
//   mode 13h, fill with colour 2 (green) -> '4'
//
// Returning to a mode of the same size as before is the interesting part: the
// canvas has to be resized and repainted although the device's size did not change.
import { V86 } from "../../build/libv86.mjs";

const PROGRAM = [0x31,0xc0,0x8e,0xd8,0x8e,0xc0,0x8e,0xd0,0xbc,0x0,0x7c,0xfb,0xb8,0x3,0x0,0xcd,0x10,0xbe,0x7c,0x7c,0xe8,0x36,0x0,0xb0,0x31,0xe8,0x4f,0x0,0xb8,0x13,0x0,0xcd,0x10,0xb0,0x4,0xe8,0x36,0x0,0xb0,0x32,0xe8,0x40,0x0,0xb8,0x3,0x0,0xcd,0x10,0xbe,0x8b,0x7c,0xe8,0x17,0x0,0xb0,0x33,0xe8,0x30,0x0,0xb8,0x13,0x0,0xcd,0x10,0xb0,0x2,0xe8,0x17,0x0,0xb0,0x34,0xe8,0x21,0x0,0xf4,0xeb,0xfd,0xac,0x84,0xc0,0x74,0x9,0xb4,0xe,0xbb,0xf,0x0,0xcd,0x10,0xeb,0xf2,0xc3,0x6,0xbb,0x0,0xa0,0x8e,0xc3,0x31,0xff,0xb9,0x0,0xfa,0xf3,0xaa,0x7,0xc3,0xba,0xf8,0x3,0xee,0xba,0xfd,0x3,0xec,0xa8,0x1,0x74,0xf8,0xba,0xf8,0x3,0xec,0xc3,0x50,0x48,0x41,0x53,0x45,0x20,0x4f,0x4e,0x45,0x20,0x54,0x45,0x58,0x54,0x0,0x50,0x48,0x41,0x53,0x45,0x20,0x54,0x48,0x52,0x45,0x45,0x20,0x54,0x45,0x58,0x54];

const worker = new URLSearchParams(location.search).get("worker") === "1";
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let emulator;
let state = () => "";

async function until(predicate, message, timeout = 20000)
{
    const end = performance.now() + timeout;
    while(!(await predicate()))
    {
        if(performance.now() > end) throw new Error("timed out: " + message + " " + state());
        await sleep(50);
    }
}

try
{
    const floppy = new Uint8Array(1474560);
    floppy.set(PROGRAM);
    floppy[510] = 0x55;
    floppy[511] = 0xAA;
    const container = document.getElementById("screen");
    emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: "../../build/v86.wasm",
        bios: { url: "../../bios/seabios.bin" },
        vga_bios: { url: "../../bios/vgabios.bin" },
        fda: { buffer: floppy.buffer },
        boot_order: 0x321,
        memory_size: 32 * 1024 * 1024,
        screen_container: container,
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" },
        autostart: true,
        ...(worker ? { cpu_worker: true, cpu_worker_url: "../../build/cpu-worker.js" } : {}),
    });
    let phase = "";
    emulator.add_listener("serial0-output-byte", byte => { phase = String.fromCharCode(byte); });
    const next = async expected => {
        await until(() => phase === expected, "phase " + expected, 60000);
    };

    const canvas = container.querySelector("canvas");
    const ctx = canvas.getContext("2d");
    const pixel = (x, y) => Array.from(ctx.getImageData(x, y, 1, 1).data.slice(0, 3)).join();
    // VGA palette colours 4 and 2: 6-bit DAC values 0x2A, shown as 168
    const is = (x, y, r, g, b) => {
        const p = ctx.getImageData(x, y, 1, 1).data;
        return Math.abs(p[0] - r) < 8 && Math.abs(p[1] - g) < 8 && Math.abs(p[2] - b) < 8;
    };
    const lit = () => {
        const data = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
        let n = 0;
        for(let i = 0; i < data.length; i += 4) if(data[i] > 128 && data[i + 1] > 128 && data[i + 2] > 128) n++;
        return n;
    };
    state = () => `(canvas ${canvas.width}x${canvas.height} display=${canvas.style.display}, centre ${pixel(canvas.width >> 1, canvas.height >> 1)}, phase ${phase})`;
    const shot_size = async () => {
        const image = emulator.screen_make_screenshot();
        await image.decode();
        return image.width + "x" + image.height;
    };

    await next("1");
    check(container.querySelectorAll("canvas").length === 1, "one canvas in the container");
    await until(() => canvas.width === 720 && canvas.height === 400 && lit() > 200, "text on the canvas");
    check(canvas.style.display !== "none", "text mode is drawn on the visible canvas (720x400)");
    check(await shot_size() === "720x400", "text-mode screenshot comes from the canvas");
    emulator.serial0_send("x");

    await next("2");
    await until(() => canvas.width === 320 && canvas.height === 200 && is(160, 100, 168, 0, 0), "13h, red");
    check(true, "mode 13h: 320x200 and red");
    emulator.serial0_send("x");

    await next("3");
    await until(() => canvas.width === 720 && canvas.height === 400 && lit() > 200, "text again");
    check(is(360, 300, 0, 0, 0), "back to text: 720x400, no leftover graphics");
    emulator.serial0_send("x");

    await next("4");
    await until(() => canvas.width === 320 && canvas.height === 200 && is(160, 100, 0, 168, 0), "13h again, green");
    check(true, "back to 13h at the same size: resized and repainted (green)");
    check(await shot_size() === "320x200", "graphics screenshot comes from the canvas");

    document.getElementById("result").textContent = "PASS " + (worker ? "(worker)" : "(main thread)") + "\n" + checks.join("\n");
}
catch(error)
{
    document.getElementById("result").textContent = "FAIL\n" + (error && error.stack || error) + "\n" + checks.join("\n");
}
finally
{
    if(emulator) emulator.destroy();
}
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/glbridge/display_compositor_browser_test.html                                      0000644 0000000 0000000 00000031425 00000000000 022225  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>One canvas: the guest desktop and a D3D9 window composited</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script src="../../build/libv86.js"></script>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
// docs/display-design.md. The guest shows mode 13h
// filled with red (the scanout); a D3D9 device clears green and presents in a
// 64x48 window at (100, 60) of the guest desktop (a window layer). Both end up
// in the one canvas, the layer where the guest put its window, and clipping
// and hiding the window reveal the desktop again.
//
//   mov ax, 0x13 / int 0x10 / es = 0xa000 / rep stosb 64000 x colour 4
//   serial 'R' / hlt
const PROGRAM = [0xb8,0x13,0x0,0xcd,0x10,0x68,0x0,0xa0,0x7,0x31,0xff,0xb0,0x4,0xb9,0x0,0xfa,0xf3,0xaa,0xba,0xf8,0x3,0xb0,0x52,0xee,0xf4,0xeb,0xfd];

(async () => {
    const checks = [];
    const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
    let emulator;
    try {
        const floppy = new Uint8Array(1474560);
        floppy.set(PROGRAM);
        floppy[510] = 0x55;
        floppy[511] = 0xAA;
        const container = document.getElementById("screen");
        emulator = new V86({
            graphics_adapter: "bochs_vga",
            wasm_path: "../../build/v86.wasm", memory_size: 32 * 1024 * 1024,
            bios: { url: "../../bios/seabios.bin" },
            vga_bios: { url: "../../bios/vgabios.bin" },
            fda: { buffer: floppy.buffer }, boot_order: 0x321,
            screen: { container },
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: true,
            graphics_proxy: true,
        });
        const booted = new Promise(resolve => emulator.add_listener("serial0-output-byte", byte => byte === 0x52 && resolve()));
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const bridge = emulator.graphics_proxy.bridge;
        await bridge.ready;
        check(!bridge.failed, "graphics initializes");
        const compositor = bridge.compositor;
        const canvas = container.querySelector("canvas");
        check(container.querySelectorAll("canvas").length === 1, "one canvas in the container");
        check(compositor && compositor.attached && compositor.canvas === canvas, "the compositor owns the screen canvas");
        check(bridge.d3d9Executor.device === compositor.device && bridge.glExecutor.device === compositor.device,
            "executors and compositor share one GPUDevice");
        const gpu_errors = [];
        compositor.device.addEventListener("uncapturederror", event => gpu_errors.push(event.error.message));
        await booted;

        const shot = async () => {
            const image = emulator.screen_make_screenshot();
            await image.decode();
            const capture = document.createElement("canvas");
            capture.width = image.width;
            capture.height = image.height;
            const context = capture.getContext("2d");
            context.drawImage(image, 0, 0);
            return (x, y) => [...context.getImageData(x, y, 1, 1).data.slice(0, 3)];
        };
        const near = (pixel, rgb) => pixel.every((v, i) => Math.abs(v - rgb[i]) < 8);
        const RED = [168, 0, 0], GREEN = [0, 255, 0];
        let pixel;
        for(let i = 0; i < 100; i++)
        {
            await sleep(50);
            pixel = await shot();
            if(canvas.width === 320 && near(pixel(20, 20), RED)) break;
        }
        check(canvas.width === 320 && canvas.height === 200 && near(pixel(20, 20), RED), "the guest's mode 13h is the scanout: " + pixel(20, 20));

        // The v86gl virtio transport, as v86gl.sys programs it
        const cpu = emulator.v86.cpu, io = cpu.io;
        const ram = cpu.read_blob(0, 32 * 1024 * 1024);
        const memory = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
        const table = 0x10000, avail = table + 128, used = table + 160;
        const request = table + 256, reply = table + 288, arena = 0x100000;
        const write = (address, bytes) => { emulator.write_memory(bytes, address); };
        // SeaBIOS has assigned the device's I/O BARs: common config, then notification
        const pci = reg => { io.port_write32(0xcf8, 0x80000000 | 0x13 << 11 | reg); return io.port_read32(0xcfc); };
        const common = pci(0x10) & ~3, notification = pci(0x14) & ~3;
        const w8 = (off, value) => io.port_write8(common + off, value);
        const w16 = (off, value) => io.port_write16(common + off, value);
        const w32 = (off, value) => io.port_write32(common + off, value);
        w8(20, 0); w8(20, 3);
        w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1); w8(20, 11);
        w16(22, 0); w16(24, 8);
        w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0);
        w32(48, used); w32(52, 0);
        const words = values => { const b = new Uint8Array(values.length * 4), v = new DataView(b.buffer); values.forEach((x, i) => v.setUint32(i * 4, x >>> 0, true)); return b; };
        const descriptors = new Uint8Array(32), dv = new DataView(descriptors.buffer);
        dv.setUint32(0, request, true); dv.setUint32(8, 24, true); dv.setUint16(12, 1, true); dv.setUint16(14, 1, true);
        dv.setUint32(16, reply, true); dv.setUint32(24, 16, true); dv.setUint16(28, 2, true);
        write(table, descriptors);
        write(avail, Uint8Array.of(1, 0));
        w16(28, 1); w8(20, 15);
        let idx = 0;
        const submit = (opcode, address, length, flags) => {
            write(request, words([opcode, address, 0, length, flags, 0]));
            write(reply, words([0xffffffff]));
            write(avail + 4 + (idx & 7) * 2, Uint8Array.of(0, 0));
            ++idx;
            write(avail + 2, Uint8Array.of(idx & 255, idx >> 8));
            io.port_write16(notification, 0);
            const answer = cpu.read_blob(reply, 4);
            const result = new DataView(answer.buffer, answer.byteOffset, 4).getUint32(0, true);
            if(result !== 0) throw new Error("virtio request failed: " + result);
        };
        submit(1, arena, 16 * 1024 * 1024, 0);

        const session = [0xd0090001, 0x20260930];
        const d3d9 = async (commands, present) => {
            const sizes = commands.map(([, values]) => (16 + values.length * 4 + 7) & ~7);
            const batchBytes = 32 + sizes.reduce((a, b) => a + b, 0);
            const wrapped = new Uint8Array(8 + batchBytes);
            const view = new DataView(wrapped.buffer);
            view.setUint16(0, 0xffe1, true); view.setUint16(2, 0xffff, true);
            view.setUint32(4, batchBytes, true);
            view.setUint32(8, 0x47573944, true);
            view.setUint16(12, 1, true); view.setUint16(14, 3, true);
            [1, present ? 1 : 0, commands.length, batchBytes - 32, ...session].forEach((v, i) => view.setUint32(16 + i * 4, v, true));
            let cursor = 40;
            commands.forEach(([op, values], i) => {
                view.setUint16(cursor, op, true); view.setUint32(cursor + 4, sizes[i], true);
                view.setUint32(cursor + 8, i + 1, true);
                values.forEach((v, j) => view.setUint32(cursor + 16 + j * 4, v >>> 0, true));
                cursor += sizes[i];
            });
            write(arena, words([0x324c4756, 1, 0, 1, 1, wrapped.length, 0x47573944, 0]));
            write(arena + 32, wrapped);
            submit(2, 0, 32 + wrapped.length, 0);
            await bridge.d3d9Executor.idle();
            check(!bridge.d3d9Executor.failed, "D3D9 batch executes");
        };
        // HELLO, CREATE_DEVICE (64x48 back buffer), CLEAR green, PRESENT at (100, 60)
        await d3d9([
            [1, [32, 0, ...session]],
            [2, [1, 0x1234, 0, 0, 64, 48, 22, 1, 0x20, 1, 75, 0, 0]],
            [5, [1, 1, 0xff00ff00, 0x3f800000, 0, 0]],
            [4, [1, 0x1234, 100, 60, 64, 48]],
        ], true);
        const layer = bridge.d3d9Canvas.layer;
        check(bridge.activeOwner === "d3d9" && layer.visible, "the D3D9 window is a visible layer");
        check(layer.x === 100 && layer.y === 60 && layer.width === 64 && layer.height === 48,
            `placed where the guest put the window (${layer.x},${layer.y} ${layer.width}x${layer.height})`);

        pixel = await shot();
        check(near(pixel(132, 84), GREEN), "inside the window: the D3D9 frame " + pixel(132, 84));
        check(near(pixel(20, 20), RED) && near(pixel(99, 84), RED) && near(pixel(164, 84), RED) && near(pixel(132, 108), RED),
            "around the window: the guest desktop");

        layer.setClip({ left: 0, top: 0, right: 0.5, bottom: 1 });
        pixel = await shot();
        check(near(pixel(110, 84), GREEN) && near(pixel(150, 84), RED), "a clipped window shows only its visible part");
        layer.setClip(null);

        // Visible, but covered by another window (Warcraft III's cinematic popup):
        // IS_WINDOW | VISIBLE | OCCLUDED
        await d3d9([[0x21D, [1, 0x1234, 0, 1 | 2 | 64, 100, 60, 64, 48, 64, 48]]], false);
        pixel = await shot();
        check(!layer.visible && near(pixel(132, 84), RED), "a covered window reveals what covers it: " + pixel(132, 84));
        check(bridge.d3d9Executor.stats.windowOccludedReports === 1, "an occluded window is not reported as a window problem");
        await d3d9([[4, [1, 0x1234, 100, 60, 64, 48]]], true);
        pixel = await shot();
        check(!layer.visible && near(pixel(132, 84), RED), "presenting behind the popup does not uncover it: " + pixel(132, 84));
        await d3d9([[0x21D, [1, 0x1234, 0, 1 | 2, 100, 60, 64, 48, 64, 48]]], false);
        pixel = await shot();
        check(layer.visible && near(pixel(132, 84), GREEN), "the popup closes: the window shows again: " + pixel(132, 84));

        // A message box over the window's right half and bottom-left corner:
        // IS_WINDOW | VISIBLE | REGION, the parts that show in client pixels
        await d3d9([[0x21D, [1, 0x1234, 0, 1 | 2 | 128, 100, 60, 64, 48, 64, 48,
            2, 0, 0, 32, 24, 0, 24, 16, 48]]], false);
        pixel = await shot();
        check(near(pixel(110, 70), GREEN) && near(pixel(105, 100), GREEN),
            "the parts other windows leave showing are drawn: " + pixel(110, 70) + " " + pixel(105, 100));
        check(near(pixel(150, 70), RED) && near(pixel(125, 100), RED),
            "what covers the rest shows through: " + pixel(150, 70) + " " + pixel(125, 100));
        check(bridge.d3d9Executor.stats.windowRegionReports === 1, "one region report");
        await d3d9([[4, [1, 0x1234, 100, 60, 64, 48]]], true);
        pixel = await shot();
        check(near(pixel(110, 70), GREEN) && near(pixel(150, 70), RED), "the region holds across Presents");
        await d3d9([[0x21D, [1, 0x1234, 0, 1 | 2, 100, 60, 64, 48, 64, 48]]], false);
        pixel = await shot();
        check(near(pixel(150, 70), GREEN) && near(pixel(125, 100), GREEN), "the box closes: all of it shows");

        // The guest reports the window hidden
        await d3d9([[0x21D, [1, 0x1234, 0, 1, 100, 60, 64, 48, 64, 48]]], false);
        pixel = await shot();
        check(!layer.visible && near(pixel(132, 84), RED), "a hidden window reveals the desktop: " + pixel(132, 84));

        // The screen-off bit (sequencer clocking mode): the scanout is cleared,
        // as on every mode set, which blanks the screen through the attribute
        // controller while it reprograms the registers
        io.port_write8(0x3c4, 1);
        const clocking_mode = io.port_read8(0x3c5);
        compositor.device.pushErrorScope("validation");
        io.port_write8(0x3c5, clocking_mode | 0x20);
        const clear_error = await compositor.device.popErrorScope();
        check(!clear_error, "the scanout is cleared without a WebGPU error: " + (clear_error && clear_error.message));
        pixel = await shot();
        check(near(pixel(20, 20), [0, 0, 0]) && near(pixel(132, 84), [0, 0, 0]), "a blanked screen is black: " + pixel(20, 20));
        io.port_write8(0x3c5, clocking_mode);
        for(let i = 0; i < 100; i++)
        {
            pixel = await shot();
            if(near(pixel(20, 20), RED)) break;
            await sleep(50);
        }
        check(near(pixel(20, 20), RED), "turned back on, it shows the desktop again: " + pixel(20, 20));
        await compositor.device.queue.onSubmittedWorkDone();
        await sleep(100);
        check(!gpu_errors.length, "no uncaptured WebGPU errors: " + gpu_errors.join(" | "));

        await emulator.destroy();
        document.getElementById("result").textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        if(emulator) await emulator.destroy().catch(() => {});
        document.getElementById("result").textContent = "FAIL\n" + (error.stack || error) + "\n" + checks.join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                           source/v64/tests/glbridge/display_text_glyphs_browser_test.html                                     0000644 0000000 0000000 00000007771 00000000000 022410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>Text mode pixels match the guest's font</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script type="module">
// Text mode is drawn on the canvas with the guest's own VGA font. Boot FreeDOS
// (scrolling text from the BIOS and the kernel), then check every pixel of
// every cell against the glyph in plane 2 and the attribute's colours.
import { V86 } from "../../src/main.js";

const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let emulator;

try
{
    const container = document.getElementById("screen");
    emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: "../../build/v86-debug.wasm",
        bios: { url: "../../bios/seabios.bin" },
        vga_bios: { url: "../../bios/vgabios.bin" },
        fda: { url: "../../images/freedos722.img" },
        memory_size: 32 * 1024 * 1024,
        screen_container: container,
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" },
        autostart: true,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
    check(await emulator.wait_until_vga_screen_contains("A:\\>", { timeout_msec: 60000 }), "FreeDOS reaches its prompt");
    // FreeDOS idles at its prompt; let the presenter draw the final screen.
    // (Not emulator.stop(): a stopped emulator pauses its presenter.)
    await sleep(1000);
    await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));

    const vga = emulator.v86.cpu.devices.vga;
    const canvas = container.querySelector("canvas");
    const cols = vga.max_cols, rows = vga.max_rows;
    const height = (vga.max_scan_line & 0x1F) + 1;
    const width = 9;
    check(canvas.width === cols * width && canvas.height === rows * height,
        `canvas is ${cols}x${rows} cells of ${width}x${height} (${canvas.width}x${canvas.height})`);

    const pixels = canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height).data;
    const rgb = color => [color >> 16 & 0xFF, color >> 8 & 0xFF, color & 0xFF];
    const palette = i => rgb(vga.vga256_palette[vga.dac_mask & vga.dac_map[i]]);
    const cursor_row = vga.cursor_address / cols | 0, cursor_col = vga.cursor_address % cols;
    let wrong_cells = [];
    for(let row = 0; row < rows; row++)
    {
        for(let col = 0; col < cols; col++)
        {
            if(row === cursor_row && col === cursor_col) continue;
            const addr = (vga.start_address << 1) + (row * cols + col) * 2;
            const chr = vga.vga_memory[addr], attr = vga.vga_memory[addr | 1];
            const fg = palette(attr & 0xF), bg = palette(attr >> 4 & 0x7);
            let bad = 0;
            for(let y = 0; y < height; y++)
            {
                const bits = vga.plane2[chr * 32 + y];
                for(let x = 0; x < width; x++)
                {
                    const on = x < 8 ? bits & (0x80 >> x) : chr >= 0xC0 && chr <= 0xDF && (vga.attribute_mode & 4) && (bits & 1);
                    const want = on ? fg : bg;
                    const p = ((row * height + y) * canvas.width + col * width + x) * 4;
                    if(Math.abs(pixels[p] - want[0]) > 2 || Math.abs(pixels[p + 1] - want[1]) > 2 || Math.abs(pixels[p + 2] - want[2]) > 2) bad++;
                }
            }
            if(bad) wrong_cells.push(`${row},${col} '${String.fromCharCode(chr)}' ${bad}px`);
        }
    }
    check(wrong_cells.length === 0, `every cell matches its glyph and colours (${wrong_cells.length} wrong: ${wrong_cells.slice(0, 8).join("; ")})`);

    document.getElementById("result").textContent = "PASS\n" + checks.join("\n");
}
catch(error)
{
    document.getElementById("result").textContent = "FAIL\n" + (error && error.stack || error) + "\n" + checks.join("\n");
}
finally
{
    if(emulator) emulator.destroy();
}
</script>
       source/v64/tests/glbridge/dxbc_wgsl_test.js                                                         0000644 0000000 0000000 00000074767 00000000000 016203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The VGPU10 shader front end (dxbc_frontend.js) and its WGSL (wgsl_emitter.js):
// programs written with the little assembler below decode as expected, and
// what they become is WGSL that naga (the WGSL front end of wgpu and Firefox)
// accepts. Without naga (cargo install naga-cli, or D9_NAGA=path) the WGSL is
// only checked for shape.
"use strict";

const assert = require("assert/strict");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync } = require("child_process");
const F = require("../../src/browser/glbridge/shader_ir/dxbc_frontend.js");
const W = require("../../src/browser/glbridge/shader_ir/wgsl_emitter.js");
const { OP, OPERAND, NAME, INTERPOLATION, DIM, RETURN, PROGRAM } = F;

const naga = process.env.D9_NAGA || (spawnSync("naga", ["--version"]).status === 0 ? "naga" : null);
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "dxbc-wgsl-"));

function validate(name, code) {
    if (!naga) return;
    const file = path.join(scratch, name + ".wgsl");
    fs.writeFileSync(file, code);
    const result = spawnSync(naga, [file], { encoding: "utf8" });
    if (result.status !== 0) {
        console.error(code.split("\n").map((l, i) => String(i + 1).padStart(4) + "  " + l).join("\n"));
        assert.fail(name + ": naga rejected the WGSL:\n" + result.stderr + result.stdout);
    }
}

// ---- assembler ------------------------------------------------------------

const X = 1, Y = 2, Z = 4, W_ = 8, XY = 3, XYZW = 15;
const SW = (x, y, z, w) => ({ swizzle: [x, y, z, w] });
const XYZW_S = SW(0, 1, 2, 3);

/** An operand: register type, indices, and { mask } | { swizzle } | { select } */
function operand(type, indices, selection, modifier) {
    const sel = selection || {};
    let token = 2;      // four components
    if (sel.zero) token = 0;
    else if (sel.one) token = 1;
    else if (sel.swizzle) token |= 1 << 2 | sel.swizzle[0] << 4 | sel.swizzle[1] << 6 | sel.swizzle[2] << 8 | sel.swizzle[3] << 10;
    else if (sel.select !== undefined) token |= 2 << 2 | sel.select << 4;
    else token |= (sel.mask === undefined ? XYZW : sel.mask) << 4;
    token |= type << 12 | indices.length << 20;
    const words = [];
    if (modifier) {
        token |= 1 << 31;
        words.push(1 | modifier << 6);
    }
    return [token >>> 0, ...words, ...indices];
}
const r = (i, sel, mod) => operand(OPERAND.TEMP, [i], sel, mod);
const v = (i, sel, mod) => operand(OPERAND.INPUT, [i], sel, mod);
const o = (i, sel) => operand(OPERAND.OUTPUT, [i], sel);
const cb = (slot, i, sel) => operand(OPERAND.CONSTANT_BUFFER, [slot, i], sel);
const t = (i, sel) => operand(OPERAND.RESOURCE, [i], sel || XYZW_S);
const s = i => operand(OPERAND.SAMPLER, [i], { zero: true });
const label = i => operand(OPERAND.LABEL, [i], { zero: true });
function imm(...values) {
    const token = (values.length === 4 ? 2 : 1) | OPERAND.IMMEDIATE32 << 12;
    return [token, ...values.map(x => typeof x === "number" && !Number.isInteger(x) ? f32(x) : x >>> 0)];
}
const f32 = x => new Uint32Array(new Float32Array([x]).buffer)[0];

/** An instruction: opcode, controls, operands */
function ins(op, ...operands) {
    let controls = 0;
    if (typeof operands[0] === "object" && !Array.isArray(operands[0])) controls = operands.shift().controls;
    const body = operands.flat();
    return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body];
}
function program(type, ...instructions) {
    const body = instructions.flat();
    return new Uint32Array([type << 16 | 4 << 4 | 0, 2 + body.length, ...body]);
}
const SAT = { controls: 1 << 2 };
const NZ = { controls: 1 << 7 };

const dcl_temps = n => ins(OP.DCL_TEMPS, n);
const dcl_input = (reg, mask) => ins(OP.DCL_INPUT, v(reg, { mask }));
const dcl_input_ps = (reg, mask, mode) => ins(OP.DCL_INPUT_PS, { controls: mode }, v(reg, { mask }));
const dcl_input_ps_siv = (reg, mask, mode, name) => ins(OP.DCL_INPUT_PS_SIV, { controls: mode }, v(reg, { mask }), name);
const dcl_input_sgv = (reg, mask, name) => ins(OP.DCL_INPUT_SGV, v(reg, { mask }), name);
const dcl_output = (reg, mask) => ins(OP.DCL_OUTPUT, o(reg, { mask }));
const dcl_output_siv = (reg, mask, name) => ins(OP.DCL_OUTPUT_SIV, o(reg, { mask }), name);
const dcl_cb = (slot, size) => ins(OP.DCL_CONSTANT_BUFFER, operand(OPERAND.CONSTANT_BUFFER, [slot, size], XYZW_S));
const dcl_sampler = (slot, mode = 0) => ins(OP.DCL_SAMPLER, { controls: mode }, operand(OPERAND.SAMPLER, [slot], { zero: true }));
const dcl_resource = (slot, dim, ret = RETURN.FLOAT) => ins(OP.DCL_RESOURCE, { controls: dim }, operand(OPERAND.RESOURCE, [slot], { zero: true }),
    ret | ret << 4 | ret << 8 | ret << 12);
const RET = ins(OP.RET);

let checked = 0;
function translate(name, tokens, options) {
    const p = F.decode(tokens);
    const result = W.emit(p, options);
    validate(name, result.code);
    checked++;
    return { p, result };
}

// ---- a vertex shader: transform by a matrix in cb0, pass a texcoord ---------

const VS = program(PROGRAM.VS,
    dcl_cb(0, 4),
    dcl_input(0, XYZW), dcl_input(1, X | Y), dcl_input_sgv(2, X, NAME.VERTEX_ID),
    dcl_output_siv(0, XYZW, NAME.POSITION), dcl_output(1, X | Y | Z | W_),
    dcl_temps(1),
    ins(OP.DP4, o(0, { mask: X }), v(0, XYZW_S), cb(0, 0, XYZW_S)),
    ins(OP.DP4, o(0, { mask: Y }), v(0, XYZW_S), cb(0, 1, XYZW_S)),
    ins(OP.DP4, o(0, { mask: Z }), v(0, XYZW_S), cb(0, 2, XYZW_S)),
    ins(OP.DP4, o(0, { mask: W_ }), v(0, XYZW_S), cb(0, 3, XYZW_S)),
    ins(OP.MOV, o(1, { mask: X | Y }), v(1, SW(0, 1, 0, 0))),
    ins(OP.UTOF, o(1, { mask: Z }), v(2, { select: 0 })),
    ins(OP.MOV, o(1, { mask: W_ }), imm(1.0)),
    RET);
{
    const { p, result } = translate("vs", VS, { vertexInputs: { 0: "f32", 1: "f32" } });
    assert.equal(p.stage, "vs");
    assert.equal(p.code.length, 8);
    assert.deepEqual([...p.cbuffers.keys()], [0]);
    assert.equal(p.outputs[0].name, NAME.POSITION);
    assert.ok(result.usesDraw, "the vertex id needs the draw's base vertex");
    assert.match(result.code, /@vertex fn main/);
    assert.deepEqual(result.bindings.map(b => b.binding).sort((a, b) => a - b), [0, 15]);
    console.log("PASS: a vertex shader: constant buffer, matrix, vertex id");
}

// ---- a pixel shader: texture, interpolation modes, discard, depth --------------

const PS = program(PROGRAM.PS,
    dcl_sampler(0), dcl_resource(0, DIM.TEXTURE2D),
    dcl_input_ps_siv(0, XYZW, INTERPOLATION.LINEAR_NOPERSPECTIVE, NAME.POSITION),
    dcl_input_ps(1, X | Y | Z | W_, INTERPOLATION.LINEAR),
    dcl_input_ps(2, X, INTERPOLATION.CONSTANT),
    dcl_output(0, XYZW),
    ins(OP.DCL_OUTPUT, operand(OPERAND.OUTPUT_DEPTH, [], { one: true })),
    dcl_temps(2),
    ins(OP.SAMPLE, r(0, { mask: XYZW }), v(1, SW(0, 1, 0, 0)), t(0), s(0)),
    ins(OP.LT, r(1, { mask: X }), r(0, { select: 3 }), imm(0.5)),
    ins(OP.DISCARD, NZ, r(1, { select: 0 })),
    ins(OP.MUL, SAT, o(0, { mask: XYZW }), r(0, XYZW_S), v(1, { select: 3 }, 1)),
    ins(OP.MOV, operand(OPERAND.OUTPUT_DEPTH, [], { one: true }), v(0, { select: 2 })),
    RET);
{
    const { p, result } = translate("ps", PS, { targets: { 0: "f32" } });
    assert.equal(p.inputs.length, 3);
    assert.equal(p.inputs[2].interpolation, INTERPOLATION.CONSTANT);
    assert.match(result.code, /@interpolate\(flat\) @location\(2\) i2: vec4<u32>/);
    assert.match(result.code, /textureSample\(t0, s0/);
    assert.match(result.code, /frag_depth/);
    const varyings = W.pixelVaryings(p);
    assert.deepEqual(Object.keys(varyings), ["1", "2"]);
    // the vertex shader linked to it writes what it reads, as it reads it
    const linked = translate("vs_linked", VS, { vertexInputs: { 0: "f32", 1: "f32" }, varyings }).result;
    assert.match(linked.code, /@interpolate\(flat\) @location\(2\) o2: vec4<u32>/);
    console.log("PASS: a pixel shader: sampling, flat and noperspective inputs, discard, depth, and its link");
}

// ---- control flow: loops, conditions, switch, subroutines ------------------------

const FLOW = program(PROGRAM.PS,
    dcl_input_ps(1, X, INTERPOLATION.CONSTANT),
    dcl_output(0, XYZW),
    dcl_temps(3),
    ins(OP.MOV, r(0, { mask: XYZW }), imm(0, 0, 0, 0)),
    ins(OP.LOOP),
    ins(OP.IGE, r(1, { mask: X }), r(0, { select: 0 }), imm(10)),
    ins(OP.BREAKC, NZ, r(1, { select: 0 })),
    ins(OP.IADD, r(0, { mask: X }), r(0, { select: 0 }), imm(1)),
    ins(OP.IF, NZ, v(1, { select: 0 })),
    ins(OP.CONTINUE),
    ins(OP.ELSE),
    ins(OP.IADD, r(0, { mask: Y }), r(0, { select: 1 }), imm(2)),
    ins(OP.ENDIF),
    ins(OP.ENDLOOP),
    ins(OP.SWITCH, r(0, { select: 1 })),
    ins(OP.CASE, imm(0)),
    ins(OP.CASE, imm(2)),
    ins(OP.MOV, r(2, { mask: XYZW }), imm(1.0, 0.0, 0.0, 1.0)),
    ins(OP.BREAK),
    ins(OP.DEFAULT),
    ins(OP.CALL, label(0)),
    ins(OP.BREAK),
    ins(OP.ENDSWITCH),
    ins(OP.UDIV, r(1, { mask: X }), r(1, { mask: Y }), r(0, { select: 0 }), imm(3)),
    ins(OP.IMUL, operand(OPERAND.NULL, [], { zero: true }), r(1, { mask: Z }), r(0, { select: 0 }), r(0, { select: 1 })),
    ins(OP.UBFE, r(1, { mask: W_ }), imm(4), imm(8), r(0, { select: 0 })),
    ins(OP.FIRSTBIT_HI, r(2, { mask: Z }), r(1, { select: 3 })),
    ins(OP.UTOF, r(2, { mask: W_ }), r(1, { select: 0 })),
    ins(OP.MOV, o(0, { mask: XYZW }), r(2, XYZW_S)),
    RET,
    ins(OP.LABEL, label(0)),
    ins(OP.MOV, r(2, { mask: XYZW }), imm(0.0, 1.0, 0.0, 1.0)),
    RET);
{
    const { result } = translate("flow", FLOW, { targets: { 0: "f32" } });
    assert.match(result.code, /loop \{/);
    assert.match(result.code, /switch \(/);
    assert.match(result.code, /case 0i, 2i: \{/);
    assert.match(result.code, /fn label0\(\)/);
    console.log("PASS: control flow: loop, breakc, if/else, continue, switch with shared cases, call/label; integer ops");
}

// ---- texture forms: arrays, cubes, comparisons, loads, sizes, gathers ----------

const TEX = program(PROGRAM.PS,
    dcl_sampler(0), dcl_sampler(1, 1),
    dcl_resource(0, DIM.TEXTURE2DARRAY), dcl_resource(1, DIM.TEXTURECUBE), dcl_resource(2, DIM.TEXTURE2D),
    dcl_resource(3, DIM.TEXTURE2D, RETURN.UINT), dcl_resource(4, DIM.TEXTURE3D), dcl_resource(5, DIM.TEXTURE1D),
    dcl_input_ps(1, XYZW, INTERPOLATION.LINEAR),
    dcl_output(0, XYZW), dcl_output(1, XYZW),
    dcl_temps(4),
    ins(OP.SAMPLE_L, r(0, { mask: XYZW }), v(1, XYZW_S), t(0), s(0), imm(0.0)),
    ins(OP.SAMPLE_B, r(1, { mask: XYZW }), v(1, XYZW_S), t(1), s(0), imm(-1.0)),
    ins(OP.SAMPLE_C, r(2, { mask: X }), v(1, XYZW_S), t(2, SW(0, 0, 0, 0)), s(1), v(1, { select: 3 })),
    ins(OP.SAMPLE_C_LZ, r(2, { mask: Y }), v(1, XYZW_S), t(2, SW(0, 0, 0, 0)), s(1), v(1, { select: 3 })),
    ins(OP.FTOI, r(3, { mask: XYZW }), v(1, XYZW_S)),
    ins(OP.LD, r(3, { mask: XYZW }), r(3, XYZW_S), t(3)),
    ins(OP.RESINFO, { controls: 2 }, r(3, { mask: XY }), imm(0), t(4)),
    ins(OP.SAMPLE_D, r(0, { mask: XYZW }), v(1, XYZW_S), t(4), s(0), v(1, XYZW_S), v(1, XYZW_S)),
    ins(OP.GATHER4, r(1, { mask: XYZW }), v(1, XYZW_S), t(0), s(0)),
    ins(OP.SAMPLE, r(1, { mask: XYZW }), v(1, XYZW_S), t(5), s(0)),
    ins(OP.DERIV_RTX_FINE, r(2, { mask: Z | W_ }), v(1, XYZW_S)),
    ins(OP.ADD, o(0, { mask: XYZW }), r(0, XYZW_S), r(1, XYZW_S)),
    ins(OP.MOV, o(1, { mask: XYZW }), r(3, XYZW_S)),
    RET);
{
    const { result } = translate("textures", TEX, { targets: { 0: "f32", 1: "u32" } });
    assert.match(result.code, /texture_depth_2d/);
    assert.match(result.code, /sampler_comparison/);
    assert.match(result.code, /texture_2d<u32>/);
    const texture = result.bindings.find(b => b.binding === 34);
    assert.equal(texture.sampleType, "depth");
    console.log("PASS: arrays, cubes, comparisons, ld, resinfo, gradients, gather, 1D as 2D, derivatives");
}

// ---- two destinations, one of them a source: sincos r1.x, r0.x, r1.x ----------

{
    const SINCOS = program(PROGRAM.PS,
        dcl_input_ps(1, XYZW, INTERPOLATION.LINEAR),
        dcl_output(0, XYZW),
        dcl_temps(2),
        ins(OP.MOV, r(1, { mask: XYZW }), v(1, XYZW_S)),
        ins(OP.SINCOS, r(1, { mask: X }), r(0, { mask: X }), r(1, { select: 0 })),
        ins(OP.IMUL, r(1, { mask: Y }), r(0, { mask: Y }), r(1, { select: 1 }), r(1, { select: 1 })),
        ins(OP.MOV, r(0, { mask: Z | W_ }), r(1, XYZW_S)),
        ins(OP.MOV, o(0, { mask: XYZW }), r(0, XYZW_S)),
        RET);
    const { result } = translate("sincos", SINCOS, { targets: { 0: "f32" } });
    // the cosine is of the source, not of the sine just written over it
    assert.match(result.code, /let a = [^;]*r\[1u\][^;]*;\s*r\[1u\]\.x = [^;]*sin\(a\)[^;]*;\s*r\[0u\]\.x = [^;]*cos\(a\)/);
    assert.match(result.code, /let a = [^;]*;\s*let b = [^;]*;\s*r\[1u\]\.y = [^;]*gx_imul_hi\(a, b\)[^;]*;\s*r\[0u\]\.y = [^;]*a \* b/);
    console.log("PASS: sincos and imul whose destination is their source read it first");
}

// ---- compute (SM5): typed texture UAVs, an append counter, raw atomics, shared memory ----

{
    const uav = (i, sel) => operand(OPERAND.UAV, [i], sel || { mask: XYZW });
    const g = (i, sel) => operand(OPERAND.THREAD_GROUP_SHARED_MEMORY, [i], sel || { mask: X });
    const tid = sel => operand(OPERAND.INPUT_THREAD_ID, [], sel || XYZW_S);
    const RET4 = (t) => t | t << 4 | t << 8 | t << 12;
    const CS = (() => {
        const p = program(PROGRAM.CS,
            ins(OP.DCL_THREAD_GROUP, 8, 8, 1),
            ins(OP.DCL_UAV_TYPED, { controls: DIM.TEXTURE2D }, uav(0, { zero: true }), RET4(RETURN.FLOAT)),
            ins(OP.DCL_UAV_TYPED, { controls: DIM.TEXTURE2D }, uav(1, { zero: true }), RET4(RETURN.UINT)),
            ins(OP.DCL_UAV_STRUCTURED, uav(2, { zero: true }), 16),
            ins(OP.DCL_UAV_RAW, uav(3, { zero: true })),
            ins(OP.DCL_TGSM_RAW, g(0, { zero: true }), 64),
            ins(OP.DCL_INPUT, tid({ mask: XY })),
            dcl_temps(4),
            ins(OP.STORE_UAV_TYPED, uav(0), tid(SW(0, 1, 1, 1)), imm(1.0, 0.0, 0.0, 1.0)),
            ins(OP.LD_UAV_TYPED, r(0, { mask: X }), tid(SW(0, 1, 1, 1)), uav(1, SW(0, 0, 0, 0))),
            ins(OP.IADD, r(0, { mask: X }), r(0, { select: 0 }), imm(1)),
            ins(OP.STORE_UAV_TYPED, uav(1), tid(SW(0, 1, 1, 1)), r(0, SW(0, 0, 0, 0))),
            ins(OP.IMM_ATOMIC_ALLOC, r(1, { mask: X }), uav(2, { zero: true })),
            ins(OP.STORE_STRUCTURED, uav(2), r(1, { select: 0 }), imm(0), tid(SW(0, 1, 0, 1))),
            ins(OP.ATOMIC_IADD, uav(3, { mask: X }), imm(0), imm(1)),
            ins(OP.STORE_RAW, g(0), imm(0), r(0, { select: 0 })),
            ins(OP.SYNC, { controls: 1 | 2 }),
            ins(OP.LD_RAW, r(2, { mask: X }), imm(0), g(0, SW(0, 0, 0, 0))),
            ins(OP.BUFINFO, r(3, { mask: X }), uav(2, SW(0, 0, 0, 0))),
            RET);
        p[0] = PROGRAM.CS << 16 | 5 << 4 | 0;     // version 5.0
        return p;
    })();
    const { result } = translate("compute", CS, { uavFormats: { 0: { format: "rgba8unorm" } } });
    assert.match(result.code, /var u0: texture_storage_2d<rgba8unorm, write>;/);
    assert.match(result.code, /var u1: texture_storage_2d<r32uint, read_write>;/, "a read R32 UAV is read-write");
    assert.match(result.code, /var<storage, read_write> uc2: atomic<u32>;/, "the append counter");
    assert.match(result.code, /atomicAdd\(&uc2, 1u\)/);
    assert.match(result.code, /textureStore\(u0, /);
    assert.match(result.code, /textureLoad\(u1, /);
    assert.match(result.code, /gx_view_base\(2u\)/, "a view's first element");
    assert.match(result.code, /@compute @workgroup_size\(8, 8, 1\)/);
    const kinds = result.bindings.map(b => b.type).sort();
    assert.deepEqual(kinds, ["uav", "uav", "uav-counter", "uav-texture", "uav-texture", "views"]);
    console.log("PASS: compute: typed texture UAVs (write, R32 read-write), an append counter, raw atomics, shared memory, bufinfo");
}

// ---- tessellation: a hull shader's phases, a domain shader, as compute ------

{
    const icp = (cp, reg, sel) => operand(OPERAND.INPUT_CONTROL_POINT, [cp, reg], sel || XYZW_S);
    // vicp[vOutputControlPointID][0]: the first index relative to a register
    const icpByID = sel => {
        const token = (2 | 1 << 2 | 0xE4 << 4 | OPERAND.INPUT_CONTROL_POINT << 12 | 2 << 20 | 2 /* relative */ << 22) >>> 0;
        return [token, ...operand(OPERAND.OUTPUT_CONTROL_POINT_ID, [], { select: 0 }), 0];
    };
    const HS = (() => {
        const p = program(PROGRAM.HS,
            ins(OP.HS_DECLS),
            ins(OP.DCL_INPUT_CONTROL_POINT_COUNT, { controls: 4 }),
            ins(OP.DCL_OUTPUT_CONTROL_POINT_COUNT, { controls: 4 }),
            ins(OP.DCL_TESS_DOMAIN, { controls: 3 }),
            ins(OP.DCL_TESS_PARTITIONING, { controls: 1 }),
            ins(OP.DCL_TESS_OUTPUT_PRIMITIVE, { controls: 3 }),
            ins(OP.DCL_HS_MAX_TESSFACTOR, f32(64)),
            ins(OP.HS_CONTROL_POINT_PHASE),
            ins(OP.DCL_INPUT, icp(4, 0, { mask: XYZW })),
            ins(OP.DCL_INPUT, operand(OPERAND.OUTPUT_CONTROL_POINT_ID, [], { zero: true })),
            dcl_output(0, XYZW),
            ins(OP.MOV, o(0, { mask: XYZW }), icpByID()),
            RET,
            ins(OP.HS_FORK_PHASE),
            ins(OP.DCL_HS_FORK_PHASE_INSTANCE_COUNT, 1),
            dcl_output_siv(0, X, NAME.FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR),
            dcl_output_siv(1, X, NAME.FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR),
            dcl_output_siv(2, X, NAME.FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR),
            dcl_output_siv(3, X, NAME.FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR),
            ins(OP.MOV, o(0, { mask: X }), imm(4.0)),
            ins(OP.MOV, o(1, { mask: X }), imm(4.0)),
            ins(OP.MOV, o(2, { mask: X }), imm(4.0)),
            ins(OP.MOV, o(3, { mask: X }), imm(4.0)),
            RET,
            ins(OP.HS_JOIN_PHASE),
            dcl_output_siv(4, X, NAME.FINAL_QUAD_U_INSIDE_TESSFACTOR),
            dcl_output_siv(5, X, NAME.FINAL_QUAD_V_INSIDE_TESSFACTOR),
            ins(OP.MOV, o(4, { mask: X }), operand(OPERAND.INPUT_PATCH_CONSTANT, [0], { select: 0 })),
            ins(OP.MOV, o(5, { mask: X }), imm(3.0)),
            RET);
        p[0] = PROGRAM.HS << 16 | 5 << 4;
        return p;
    })();
    const hs = translate("hull", HS, { group: 0, mode: "hull" });
    const h = hs.result.hull;
    assert.deepEqual([h.inCPs, h.outCPs, h.cpRegs, h.pcRegs, h.domain, h.partitioning, h.outputPrimitive], [4, 4, 1, 6, 3, 1, 3]);
    assert.equal(hs.result.record, 4 * 1 + 6 + 2, "control points, patch constants, tess factors");
    assert.match(hs.result.code, /fn hs_phase1\(\)/);
    assert.match(hs.result.code, /vicp\[[^\]]*hs_cpid[^\]]*\]\[0u\]/, "the control point the invocation makes");
    assert.match(hs.result.code, /opc\[0u\]\.x = /, "fork phases write patch constants");
    assert.match(hs.result.code, /vec4<f32>\(bitcast<f32>\(opc\[0\]\.x\), bitcast<f32>\(opc\[1\]\.x\)/, "the edge tess factors");

    const DS = (() => {
        const neg = 1;
        const p = program(PROGRAM.DS,
            ins(OP.DCL_INPUT_CONTROL_POINT_COUNT, { controls: 4 }),
            ins(OP.DCL_TESS_DOMAIN, { controls: 3 }),
            ins(OP.DCL_INPUT, operand(OPERAND.INPUT_DOMAIN_POINT, [], { mask: XY })),
            ins(OP.DCL_INPUT, icp(4, 0, { mask: XY })),
            dcl_output_siv(0, XYZW, NAME.POSITION),
            dcl_temps(2),
            ins(OP.ADD, r(0, { mask: XY }), icp(0, 0, XYZW_S).map((w, i) => i === 0 ? w : w), icp(1, 0)),
            ins(OP.MAD, r(0, { mask: XY }), operand(OPERAND.INPUT_DOMAIN_POINT, [], SW(0, 0, 0, 0)), r(0, XYZW_S), icp(0, 0)),
            ins(OP.ADD, r(1, { mask: XY }), operand(OPERAND.INPUT_CONTROL_POINT, [3, 0], XYZW_S, neg), icp(2, 0)),
            ins(OP.MAD, r(1, { mask: XY }), operand(OPERAND.INPUT_DOMAIN_POINT, [], SW(0, 0, 0, 0)), r(1, XYZW_S), icp(3, 0)),
            ins(OP.ADD, r(1, { mask: XY }), r(0, XYZW_S, neg), r(1, XYZW_S)),
            ins(OP.MAD, o(0, { mask: XY }), operand(OPERAND.INPUT_DOMAIN_POINT, [], SW(1, 1, 1, 1)), r(1, XYZW_S), r(0, XYZW_S)),
            ins(OP.MOV, o(0, { mask: Z | W_ }), imm(0.0, 0.0, 0.0, 1.0)),
            RET);
        p[0] = PROGRAM.DS << 16 | 5 << 4;
        return p;
    })();
    const ds = translate("domain", DS, { group: 0, mode: "domain" });
    assert.match(ds.result.code, /gx_domain = vec3<f32>\(u, v, 0\.0\);/, "a quad's domain point");
    assert.match(ds.result.code, /vicp\[0u\]\[0u\]/);
    assert.deepEqual(ds.result.bindings.map(b => b.type).sort(), ["domain", "stage-in", "stage-out", "tess-args", "tess-points"]);
    console.log("PASS: tessellation: a hull shader's control point, fork and join phases, a domain shader, as compute");
}

// ---- doubles (as floats), msad, eval_* --------------------------------------

{
    const d64 = (...values) => {
        const words = new Uint32Array(new Float64Array(values).buffer);
        const token = (values.length === 2 ? 2 : 1) | OPERAND.IMMEDIATE64 << 12;
        return [token, ...words];
    };
    const DOUBLES = (() => {
        const p = program(PROGRAM.PS,
            dcl_input_ps(1, XYZW, INTERPOLATION.LINEAR),
            dcl_output(0, XYZW),
            dcl_temps(3),
            ins(OP.FTOD, r(0, { mask: XYZW }), v(1, SW(0, 1, 0, 1))),
            ins(OP.DADD, r(0, { mask: XYZW }), r(0, XYZW_S), d64(0.5, -0.25)),
            ins(OP.DMUL, r(0, { mask: X | Y }), r(0, XYZW_S, 1 /* neg */), r(0, XYZW_S)),
            ins(OP.DEQ, r(1, { mask: X }), r(0, XYZW_S), d64(1.0, 1.0)),
            ins(OP.DTOF, r(1, { mask: Z | W_ }), r(0, XYZW_S)),
            ins(OP.MSAD, r(2, { mask: XYZW }), v(1, XYZW_S), v(1, SW(1, 2, 3, 0)), imm(0, 0, 0, 0)),
            ins(OP.EVAL_CENTROID, r(2, { mask: X }), v(1, { select: 0 })),
            ins(OP.ADD, o(0, { mask: XYZW }), r(1, XYZW_S), r(2, XYZW_S)),
            RET);
        p[0] = PROGRAM.PS << 16 | 5 << 4;
        return p;
    })();
    const { result } = translate("doubles", DOUBLES, { targets: { 0: "f32" } });
    assert.match(result.code, /fn gx_d2f\(/);
    assert.match(result.code, /gx_f2d2\(a \+ b\)/);
    assert.match(result.code, /\^ vec4<u32>\(0u, 0x80000000u, 0u, 0x80000000u\)/, "a negated double flips its high word's sign");
    assert.match(result.code, /gx_spread_f32\(gx_d2f2\([^)]*\), 12u\)/, "dtof into z and w");
    assert.match(result.code, /gx_msad\(/);
    console.log("PASS: doubles (computed as floats), msad, eval_centroid");
}

// ---- shader model 4.1: cube arrays, lod, the rasterizer's samples, per-sample inputs ----

const rasterizer = sel => operand(OPERAND.RASTERIZER, [], sel || XYZW_S);
const SM41 = (() => {
    const p = program(PROGRAM.PS,
        dcl_sampler(0),
        dcl_resource(0, DIM.TEXTURECUBEARRAY), dcl_resource(1, DIM.TEXTURE2D), dcl_resource(2, DIM.TEXTURE2DMS),
        dcl_input_ps(1, XYZW, INTERPOLATION.LINEAR_SAMPLE),
        dcl_input_ps_siv(0, XYZW, INTERPOLATION.LINEAR_NOPERSPECTIVE, NAME.POSITION),
        dcl_output(0, XYZW),
        dcl_temps(5),
        ins(OP.SAMPLE, r(0, { mask: XYZW }), v(1, XYZW_S), t(0), s(0)),
        ins(OP.GATHER4, r(1, { mask: XYZW }), v(1, XYZW_S), t(0), operand(OPERAND.SAMPLER, [0], { select: 0 })),
        ins(OP.LOD, r(2, { mask: XY }), v(1, XYZW_S), t(0), s(0)),
        ins(OP.LOD, r(2, { mask: Z | W_ }), v(1, XYZW_S), t(1, SW(0, 0, 1, 1)), s(0)),
        ins(OP.SAMPLE_INFO, { controls: 1 }, r(3, { mask: X }), rasterizer(SW(0, 0, 0, 0))),
        ins(OP.SAMPLE_INFO, r(3, { mask: Y }), t(2, SW(0, 0, 0, 0))),
        ins(OP.SAMPLE_POS, r(3, { mask: Z | W_ }), rasterizer(SW(0, 0, 0, 1)), imm(1)),
        // sample 2 of the multisampled texture, at the pixel
        ins(OP.FTOI, r(4, { mask: XY }), v(0, XYZW_S)),
        ins(OP.LD_MS, r(4, { mask: XYZW }), r(4, XYZW_S), t(2), imm(2)),
        ins(OP.ADD, r(3, { mask: XYZW }), r(3, XYZW_S), r(4, XYZW_S)),
        ins(OP.ADD, r(0, { mask: XYZW }), r(0, XYZW_S), r(1, XYZW_S)),
        ins(OP.ADD, r(0, { mask: XYZW }), r(0, XYZW_S), r(2, XYZW_S)),
        ins(OP.ADD, o(0, { mask: XYZW }), r(0, XYZW_S), r(3, XYZW_S)),
        RET);
    p[0] = PROGRAM.PS << 16 | 4 << 4 | 1;     // version 4.1
    return p;
})();
{
    const { p, result } = translate("sm41", SM41, { targets: { 0: "f32" } });
    assert.equal(p.minor, 1);
    assert.match(result.code, /texture_cube_array<f32>/);
    // multisampled surfaces are supersampled: plain textures, a sample a texel
    assert.match(result.code, /var t2: texture_2d<f32>/);
    assert.match(result.code, /textureLoad\(t2, .*\.xy\) \* 2 \+ gx_ms_texel\(/);
    assert.match(result.code, /override gx_ss: u32 = 0u;/);
    assert.match(result.code, /gx_sample = select\(select\(0u, \(u32\(input\.position\.x\) & 1u\)/, "4 samples: 2 x 2");
    assert.match(result.code, /\(u32\(input\.position\.x\) & 3u\) \| \(\(u32\(input\.position\.y\) & 1u\) << 2u\)/, "8 samples: 4 x 2");
    assert.match(result.code, /input\.position\.xy \/ gx_scale/, "per-sample shading sees the sample's position");
    assert.match(result.code, /\{ discard; \}/);
    assert.match(result.code, /override gx_samples: u32 = 1u;/);
    assert.ok(result.usesSamples, "the rasterizer's samples are the pipeline's");
    assert.match(result.code, /fn gx_lod\(/);
    assert.match(result.code, /gx_cube_face\(/);
    assert.match(result.code, /vec4<f32>\(f32\(4u\)/, "sample_info of the texture: 4");
    assert.match(result.code, /@interpolate\(perspective, sample\)/);
    assert.ok(!result.warnings.some(w => /lod/.test(w)), "lod is computed, not approximated");
    const cube = result.bindings.find(b => b.type === "texture" && b.dimension === "cube-array");
    assert.ok(cube, "a cube array binding");
    console.log("PASS: shader model 4.1: cube arrays, gather4, lod, sample_info/sample_pos of the rasterizer, per-sample inputs");
}

// ---- compute variants for geometry shaders: a vertex shader that pulls its
// vertices, and geometry shaders ------------------------------------------------

{
    const fetch = [
        { reg: 0, slot: 0, offset: 0, format: "float32x4", instanced: false },
        { reg: 1, slot: 1, offset: 4, format: "unorm8x4-bgra", instanced: true },
    ];
    const { result } = translate("vs-compute", VS, { mode: "vertex-compute", fetch });
    assert.match(result.code, /@compute @workgroup_size\(64\) fn main/);
    assert.equal(result.record, 2, "a record of its two outputs");
    const types = Object.fromEntries(result.bindings.map(b => [b.binding, b.type]));
    assert.equal(types[200], "vertex-buffer");
    assert.equal(types[201], "vertex-buffer");
    assert.equal(types[230], "fetch");
    assert.equal(types[231], "index");
    assert.equal(types[233], "stage-out");
    // every format the GX table has, pulled
    const formats = ["float32", "float32x2", "float32x3", "float16", "float16x2", "float16x4", "unorm8", "unorm8x2", "unorm8x4",
        "snorm8x4", "uint8x4", "sint8x2", "unorm16x4", "snorm16x2", "uint16", "sint16x4", "uint32x3", "sint32x4",
        "unorm10-10-10-2", "pull:uint10-10-10-2", "pull:ufloat11-11-10"];
    const many = formats.map((format, i) => ({ reg: 0, slot: i % 4, offset: 4 * i, format, instanced: false }));
    for (const f of many) translate("fetch-" + f.format.replace(/[^a-z0-9]/g, "_"), VS, { mode: "vertex-compute", fetch: [f] });
    console.log("PASS: a vertex shader as compute, pulling " + formats.length + " vertex formats");
}

const vin = (vertex, reg, sel) => operand(OPERAND.INPUT, [vertex, reg], sel);
const GS = program(PROGRAM.GS,
    ins(OP.DCL_GS_INPUT_PRIMITIVE, { controls: 3 /* triangle */ }),
    ins(OP.DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, { controls: 5 /* triangle strip */ }),
    ins(OP.DCL_MAX_OUTPUT_VERTEX_COUNT, 6),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT, [3, 0], { mask: XYZW })),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT, [3, 1], { mask: XYZW })),
    dcl_output_siv(0, XYZW, NAME.POSITION), dcl_output(1, XYZW),
    dcl_temps(1),
    // each vertex as it came, then a cut, then the first again, alone
    ...[0, 1, 2].map(i => [ins(OP.MOV, o(0, { mask: XYZW }), vin(i, 0, XYZW_S)), ins(OP.MOV, o(1, { mask: XYZW }), vin(i, 1, XYZW_S)),
        ins(OP.EMIT)]).flat(),
    ins(OP.CUT),
    ins(OP.MOV, o(0, { mask: XYZW }), vin(0, 0, XYZW_S)),
    ins(OP.EMITTHENCUT),
    RET);
{
    const { p, result } = translate("gs", GS, { mode: "geometry" });
    assert.equal(p.stage, "gs");
    assert.deepEqual(result.gs, { vertices: 3, topology: "triangle-list", perPrim: 3, maxPrims: 4, instances: 1 });
    assert.equal(result.record, 3, "two outputs and the flag");
    assert.match(result.code, /var<private> v: array<array<vec4<u32>, 2>, 3>/);
    assert.match(result.code, /gs_emit\(\);/);
    assert.match(result.code, /gs_cut\(\);/);
    assert.throws(() => W.emit(p, {}), /emulated elsewhere/, "only as compute");
    console.log("PASS: a geometry shader as compute: 2D inputs, emit and cut, triangles from strips");
}

const GS_POINTS = program(PROGRAM.GS,
    ins(OP.DCL_GS_INPUT_PRIMITIVE, { controls: 1 /* point */ }),
    ins(OP.DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, { controls: 5 }),
    ins(OP.DCL_MAX_OUTPUT_VERTEX_COUNT, 4),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT, [1, 0], { mask: XYZW })),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT_PRIMITIVEID, [], { zero: true })),
    dcl_output_siv(0, XYZW, NAME.POSITION), dcl_output(1, X),
    dcl_temps(1),
    ...[[-0.1, -0.1], [-0.1, 0.1], [0.1, -0.1], [0.1, 0.1]].map(([dx, dy]) => [
        ins(OP.ADD, o(0, { mask: XYZW }), vin(0, 0, XYZW_S), imm(dx, dy, 0.0, 0.0)),
        ins(OP.MOV, o(1, { mask: X }), operand(OPERAND.INPUT_PRIMITIVEID, [], { select: 0 })),
        ins(OP.EMIT)]).flat(),
    RET);
{
    const { result } = translate("gs-points", GS_POINTS, { mode: "geometry" });
    assert.deepEqual(result.gs, { vertices: 1, topology: "triangle-list", perPrim: 3, maxPrims: 2, instances: 1 });
    assert.match(result.code, /vec4<u32>\(prim_id\)/);
    console.log("PASS: a geometry shader making quads of points, with the primitive id");
}

// GS instancing: three invocations a point, each moved by its SV_GSInstanceID
const GS_INSTANCED = program(PROGRAM.GS,
    ins(OP.DCL_GS_INPUT_PRIMITIVE, { controls: 1 }),
    ins(OP.DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, { controls: 1 /* points */ }),
    ins(OP.DCL_MAX_OUTPUT_VERTEX_COUNT, 1),
    ins(OP.DCL_GS_INSTANCE_COUNT, 3),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT, [1, 0], { mask: XYZW })),
    ins(OP.DCL_INPUT, operand(OPERAND.INPUT_GS_INSTANCE_ID, [], { zero: true })),
    dcl_output_siv(0, XYZW, NAME.POSITION),
    dcl_temps(1),
    ins(OP.UTOF, r(0, { mask: X }), operand(OPERAND.INPUT_GS_INSTANCE_ID, [], { select: 0 })),
    ins(OP.MAD, o(0, { mask: X }), r(0, { select: 0 }), imm(0.1), vin(0, 0, { select: 0 })),
    ins(OP.MOV, o(0, { mask: Y | Z | W_ }), vin(0, 0, XYZW_S)),
    ins(OP.EMIT),
    RET);
{
    const { result } = translate("gs-instanced", GS_INSTANCED, { mode: "geometry" });
    assert.equal(result.gs.instances, 3);
    assert.match(result.code, /gs_instance = k % 3u;/);
    assert.match(result.code, /vec4<u32>\(gs_instance\)/);
    console.log("PASS: GS instancing: three invocations a primitive, SV_GSInstanceID");
}

console.log("PASS: " + checked + " shaders" + (naga ? " validated by naga" : " (naga not found: not validated)"));
fs.rmSync(scratch, { recursive: true, force: true });
         source/v64/tests/glbridge/gl_arb_program_test.js                                                    0000644 0000000 0000000 00000033250 00000000000 017162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unit tests for glbridge/gl-webgpu/gl_arb_program.js -- GL_ARB_vertex_program
// and GL_ARB_fragment_program assembly translated to WGSL.
//
// The fixtures are written the way a real program is: a header, declarations,
// a flat instruction list, END. What is checked is that the register machine's
// semantics survive -- swizzles, write masks, saturation, the address register,
// the state bindings resolving into the *same* GLState block the fixed pipeline
// uses -- and that the output is WGSL naga accepts.

"use strict";

const assert = require("assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync, execFileSync } = require("child_process");
const arb = require("../../src/browser/glbridge/gl-webgpu/gl_arb_program.js");

function findNaga() {
    if (process.env.GL_NAGA) return process.env.GL_NAGA;
    if (spawnSync("naga", ["--version"], { encoding: "utf8" }).status === 0)
        return "naga";
    const cargo = path.join(os.homedir(), ".cargo", "bin", "naga");
    return fs.existsSync(cargo) ? cargo : null;
}

const naga = findNaga();
const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), "glwg-arb-"));
let passed = 0;
const failures = [];

function test(name, fn) {
    try { fn(); ++passed; } catch (error) { failures.push([name, error]); }
}

function compile(source, label, options) {
    const result = arb.compileARBProgram(source, options || {});
    if (!result.ok) throw new Error(result.log);
    if (naga) {
        const file = path.join(outputDir,
            (label || "program").replace(/[^A-Za-z0-9_.-]/g, "_") + ".wgsl");
        fs.writeFileSync(file, result.wgsl);
        try {
            execFileSync(naga, [file], { stdio: "pipe" });
        } catch (error) {
            throw new Error("naga rejected the generated WGSL:\n" +
                String(error.stderr || error.stdout || error).slice(0, 800));
        }
    }
    return result;
}

/* ---- the canonical transform ---- */

const TRANSFORM = `!!ARBvp1.0
ATTRIB pos = vertex.position;
PARAM mvp[4] = { state.matrix.mvp };
OUTPUT oPos = result.position;
DP4 oPos.x, mvp[0], pos;
DP4 oPos.y, mvp[1], pos;
DP4 oPos.z, mvp[2], pos;
DP4 oPos.w, mvp[3], pos;
MOV result.color, vertex.color;
END`;

test("the canonical DP4 transform translates", () => {
    const result = compile(TRANSFORM, "transform");
    assert.strictEqual(result.target, "vertex");
    assert.ok(result.reflection.stateFields.indexOf("mvp") >= 0,
        "state.matrix.mvp resolves into the shared GL state block");
    assert.ok(result.wgsl.indexOf("clip.y = -clip.y;") >= 0,
        "the same clip-space flip every other path applies");
    assert.ok(result.wgsl.indexOf("clip.z = (clip.z + clip.w) * 0.5;") >= 0);
    const attributes = result.reflection.attributes.map(a => a.location);
    assert.ok(attributes.indexOf(0) >= 0, "vertex.position is attribute 0");
});

test("a fixed fragment stage can require ARB texture-coordinate outputs", () => {
    const result = compile(`!!ARBvp1.0
MOV result.position, vertex.position;
END`, "fixed_fragment_outputs", {
        forceVertexTexCoords: [0, 1],
        forceStateFields: ["mvp", "texEnvColor"],
        forceFlatVaryings: [0, 1],
    });
    assert.ok(result.wgsl.includes(
        "@location(3) texcoord0 : vec4<f32>"));
    assert.ok(result.wgsl.includes(
        "@location(4) texcoord1 : vec4<f32>"));
    assert.ok(result.wgsl.includes("out.texcoord0 = texcoord0;"));
    assert.ok(result.wgsl.includes(
        "@interpolate(flat) @location(0) frontColor"));
    assert.ok(result.wgsl.includes("texEnvColor"),
        "the mixed stages use a byte-identical GLState layout");
});

test("a write mask writes only the components it names", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0;
MOV r0, vertex.position;
MOV result.color.xz, r0;
MOV result.position, r0;
END`, "writemask");
    assert.ok(result.wgsl.indexOf("frontColor.x = ") >= 0);
    assert.ok(result.wgsl.indexOf("frontColor.z = ") >= 0);
    assert.ok(result.wgsl.indexOf("frontColor.y = ") < 0,
        "an unnamed component keeps its previous value");
});

test("a one-component swizzle replicates", () => {
    assert.strictEqual(arb.applySwizzle("v", "x"), "vec4<f32>((v).x)");
    assert.strictEqual(arb.applySwizzle("v", "xyzw"), "(v).xyzw");
    assert.strictEqual(arb.applySwizzle("v", "wzyx"), "(v).wzyx");
    assert.ok(arb.applySwizzle("v", "x1").indexOf("1.0") >= 0,
        "the extended swizzle's literal components survive");
});

test("source modifiers negate and take the absolute value", () => {
    const result = compile(`!!ARBfp1.0
TEMP r0;
MOV r0, -fragment.color;
MOV result.color, |r0|;
END`, "modifiers");
    assert.ok(result.wgsl.indexOf("(-(") >= 0);
    assert.ok(result.wgsl.indexOf("abs(") >= 0);
});

test("_SAT clamps the result", () => {
    const result = compile(`!!ARBfp1.0
TEMP r0;
ADD_SAT r0, fragment.color, fragment.color;
MOV result.color, r0;
END`, "saturate");
    assert.ok(result.wgsl.indexOf("clamp(") >= 0);
});

/* ---- instruction semantics ---- */

test("LIT and LOG emit their helper rather than an approximation", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0;
LIT r0, vertex.position;
LOG r0, vertex.position;
MOV result.position, r0;
END`, "lit_log");
    assert.ok(result.wgsl.indexOf("fn arbLit") >= 0);
    assert.ok(result.wgsl.indexOf("fn arbLog") >= 0);
});

test("scalar instructions read only the x component", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0;
RCP r0, vertex.position;
RSQ r0, r0;
POW r0, r0, r0;
MOV result.position, r0;
END`, "scalar");
    assert.ok(result.wgsl.indexOf("1.0 / ") >= 0);
    assert.ok(result.wgsl.indexOf("inverseSqrt(max(abs(") >= 0,
        "RSQ guards against a zero operand the way hardware does");
});

test("DST assembles the distance vector from both operands", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0, r1;
MOV r0, vertex.position;
MOV r1, vertex.normal;
DST r0, r0, r1;
MOV result.position, r0;
END`, "dst");
    assert.ok(result.wgsl.indexOf("vec4<f32>(1.0, ") >= 0);
});

test("KIL discards", () => {
    const result = compile(`!!ARBfp1.0
KIL fragment.color;
MOV result.color, fragment.color;
END`, "kil");
    assert.ok(result.wgsl.indexOf("discard;") >= 0);
    assert.strictEqual(result.reflection.usesKill, true);
});

test("CMP and LRP are fragment-only", () => {
    const ok = compile(`!!ARBfp1.0
TEMP r0;
CMP r0, fragment.color, fragment.color, fragment.color;
LRP r0, r0, r0, r0;
MOV result.color, r0;
END`, "cmp_lrp");
    assert.ok(ok.wgsl.indexOf("select(") >= 0);
    const rejected = arb.compileARBProgram(`!!ARBvp1.0
TEMP r0;
CMP r0, vertex.position, vertex.position, vertex.position;
MOV result.position, r0;
END`, {});
    assert.strictEqual(rejected.ok, false);
    assert.ok(rejected.log.indexOf("fragment-program only") >= 0, rejected.log);
});

/* ---- texture instructions ---- */

test("TEX, TXP and TXB reach the right unit and target", () => {
    const result = compile(`!!ARBfp1.0
TEMP r0, r1, r2;
TEX r0, fragment.texcoord[0], texture[0], 2D;
TXP r1, fragment.texcoord[1], texture[1], 2D;
TXB r2, fragment.texcoord[2], texture[2], CUBE;
ADD r0, r0, r1;
ADD result.color, r0, r2;
END`, "textures");
    assert.strictEqual(result.reflection.textures.length, 3);
    assert.strictEqual(result.reflection.textures[2].target, "CUBE");
    assert.ok(result.wgsl.indexOf("textureSample(t0") >= 0);
    assert.ok(result.wgsl.indexOf(".xy / ") >= 0, "TXP divides by w");
    assert.ok(result.wgsl.indexOf("textureSampleBias(t2") >= 0);
    assert.ok(result.wgsl.indexOf("texture_cube<f32>") >= 0);
});

/* ---- parameters and state ---- */

test("program.env and program.local share one binding", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0;
MUL r0, vertex.position, program.env[7];
ADD r0, r0, program.local[3];
MOV result.position, r0;
END`, "params");
    assert.ok(result.wgsl.indexOf("arbParams.env[7]") >= 0);
    assert.ok(result.wgsl.indexOf("arbParams.local[3]") >= 0);
    assert.ok(result.wgsl.indexOf("@group(1) @binding(1)") >= 0,
        "a program which reads parameters declares their uniform binding");
    assert.strictEqual(result.reflection.usesEnv, true);
    assert.strictEqual(result.reflection.usesLocal, true);
    assert.strictEqual(result.reflection.maxParameters, 28,
        "28, not the ARB minimum of 24 -- see openglproxy/README.md");
});

test("an ARB program without parameters omits their unused binding", () => {
    const result = compile(`!!ARBvp1.0
MOV result.position, vertex.position;
MOV result.color, vertex.color;
END`, "no_params");
    assert.strictEqual(result.reflection.usesEnv, false);
    assert.strictEqual(result.reflection.usesLocal, false);
    assert.ok(result.wgsl.indexOf("@group(1) @binding(1)") < 0,
        "auto pipeline layout must not lose a declared-but-unused binding");
});

test("a parameter beyond the advertised count is refused", () => {
    const result = arb.compileARBProgram(`!!ARBvp1.0
MOV result.position, program.env[40];
END`, {});
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("28") >= 0, result.log);
});

test("relative addressing through ARL indexes the uniform array", () => {
    const result = compile(`!!ARBvp1.0
ADDRESS A0;
TEMP r0;
ARL A0.x, vertex.position;
MOV r0, program.env[A0.x + 2];
MOV result.position, r0;
END`, "relative");
    assert.ok(result.wgsl.indexOf("clamp(") >= 0,
        "the index is clamped, because WGSL does not define an out-of-range read");
    assert.strictEqual(result.reflection.usesAddress, true);
});

test("state bindings resolve into the shared GL state block", () => {
    const result = compile(`!!ARBvp1.0
TEMP r0;
MOV r0, state.light[2].position;
ADD r0, r0, state.lightprod[2].diffuse;
ADD r0, r0, state.material.specular;
ADD r0, r0, state.fog.params;
ADD r0, r0, state.clip[1].plane;
MOV result.position, r0;
END`, "state");
    const fields = result.reflection.stateFields;
    for (const field of ["lights", "frontLightProduct", "frontMaterial",
            "fogParams", "clipPlanes"])
        assert.ok(fields.indexOf(field) >= 0, field + " is requested");
    assert.ok(result.wgsl.indexOf("glState.lights[2].position") >= 0);
});

test("a matrix row binding gathers the row rather than a column", () => {
    const result = compile(`!!ARBvp1.0
PARAM m0 = state.matrix.mvp.row[1];
MOV result.position, m0;
END`, "matrix_row");
    // WGSL indexes a matrix by column, so an ARB row has to be assembled.
    assert.ok(result.wgsl.indexOf("glState.mvp[0][1]") >= 0, result.wgsl);
    assert.ok(result.wgsl.indexOf("glState.mvp[3][1]") >= 0);
});

test("an unknown state binding is refused with its name", () => {
    const result = arb.compileARBProgram(`!!ARBvp1.0
MOV result.position, state.nonsense.thing;
END`, {});
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("state.nonsense.thing") >= 0, result.log);
});

test("a literal PARAM is inlined as a constant", () => {
    const result = compile(`!!ARBvp1.0
PARAM half = { 0.5, 0.5, 0.5, 1.0 };
TEMP r0;
MUL r0, vertex.position, half;
MOV result.position, r0;
END`, "literal");
    assert.ok(result.wgsl.indexOf("vec4<f32>(0.5, 0.5, 0.5, 1.0)") >= 0);
});

test("a scalar PARAM splats all four components like glview's half", () => {
    const result = compile(`!!ARBvp1.0
PARAM half = 0.5;
TEMP light_surf;
MAD result.color, light_surf, half, half;
MOV result.position, vertex.position;
END`, "glview_scalar_param");
    assert.ok(result.wgsl.indexOf(
        "vec4<f32>(0.5, 0.5, 0.5, 0.5)") >= 0, result.wgsl);
    assert.ok(result.wgsl.indexOf(
        "vec4<f32>(0.5, 0.0, 0.0, 1.0)") < 0,
        "a PARAM scalar is not expanded like a one-component vertex array");
});

test("ALIAS and ATTRIB declarations resolve", () => {
    const result = compile(`!!ARBvp1.0
ATTRIB iPos = vertex.position;
TEMP r0;
ALIAS scratch = r0;
MOV scratch, iPos;
MOV result.position, scratch;
END`, "alias");
    assert.ok(result.ok);
});

test("OPTION ARB_position_invariant supplies the transform", () => {
    const result = compile(`!!ARBvp1.0
OPTION ARB_position_invariant;
MOV result.color, vertex.color;
END`, "position_invariant");
    assert.strictEqual(result.reflection.positionInvariant, true);
    assert.ok(result.wgsl.indexOf("glState.mvp * vin.gl_Vertex") >= 0,
        "the same expression ftransform() uses, or a depth pre-pass z-fights");
});

/* ---- diagnostics ---- */

test("a missing header is refused", () => {
    const result = arb.compileARBProgram("MOV result.position, vertex.position;\nEND", {});
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("!!ARBvp1.0") >= 0, result.log);
});

test("an unknown instruction names itself", () => {
    const result = arb.compileARBProgram(`!!ARBvp1.0
FROB result.position, vertex.position;
END`, {});
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("FROB") >= 0, result.log);
});

test("a program with no END is refused", () => {
    const result = arb.compileARBProgram(`!!ARBvp1.0
MOV result.position, vertex.position;`, {});
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("END") >= 0, result.log);
});

test("comments and blank lines are ignored", () => {
    const result = compile(`!!ARBvp1.0
# the canonical transform
PARAM mvp[4] = { state.matrix.mvp };   # four rows

DP4 result.position.x, mvp[0], vertex.position;  # x
DP4 result.position.y, mvp[1], vertex.position;
DP4 result.position.z, mvp[2], vertex.position;
DP4 result.position.w, mvp[3], vertex.position;
END`, "comments");
    assert.ok(result.ok);
});

for (const [name, error] of failures)
    console.error("FAIL: " + name + "\n    " + (error && error.message));
console.log(passed + " passed, " + failures.length + " failed" +
    (naga ? " (WGSL validated with naga)" : " (naga absent)"));
fs.rmSync(outputDir, { recursive: true, force: true });
process.exit(failures.length ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/glbridge/gl_executor_test.js                                                       0000644 0000000 0000000 00000335667 00000000000 016546  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unit tests for glbridge/gl-webgpu/gl_executor.js -- the OpenGL state machine
// and draw path, driven by real command records and a fake GPUDevice.
//
// Every fixture here is encoded through gl_stream_builder.js, which uses the
// same signature table the executor decodes with, so a layout mistake shows up
// as a decode mismatch rather than as a plausible-looking wrong picture. What
// the assertions check is the *decision*: which pipeline state a GL state
// produced, which vertex layout, which bind groups, and what a synchronous
// query answered.

"use strict";

const assert = require("assert");
const { createFakeHost } = require("./gl_fake_gpu.js");
const { GLStream, GL, GLFN } = require("./gl_stream_builder.js");
const executorModule = require("../../src/browser/glbridge/gl-webgpu/gl_executor.js");

let passed = 0;
const failures = [];

function test(name, fn) {
    try {
        fn();
        ++passed;
    } catch (error) {
        failures.push([name, error]);
    }
}

/*
 * Two results in this path cannot be answered inside the batch that asked for
 * them -- glReadPixels and occlusion queries both wait on a buffer mapping.
 * Their tests therefore have to await the same microtask the real bridge does,
 * which is the whole point: a synchronous assertion would pass against an
 * executor that never completes them at all.
 */
const asyncTests = [];
function asyncTest(name, fn) {
    asyncTests.push([name, fn]);
}

function newExecutor(options) {
    const { host, log } = createFakeHost();
    const executor = new executorModule.GLWebGPUExecutor(null,
        Object.assign({ host }, options || {}));
    executor.initializeSync = () => {
        // initialize() is async only because a real adapter request is; the
        // fake resolves immediately, so the tests drive it synchronously.
        executor.device = host.device;
        executor.deviceFeatures = host.deviceFeatures;
        executor.limits = host.limits;
        executor.uniformCapacity = 1 << 20;
        executor.vertexCapacity = 1 << 20;
        executor.uniformRing = host.device.createBuffer({ size: executor.uniformCapacity });
        executor.uniformStaging = new Uint8Array(executor.uniformCapacity);
        executor.vertexRing = host.device.createBuffer({ size: executor.vertexCapacity });
        executor.vertexStaging = new Uint8Array(executor.vertexCapacity);
        executor.fallbackTexture = host.device.createTexture({
            size: { width: 1, height: 1 }, format: "rgba8unorm" });
        executor.fallbackView = executor.fallbackTexture.createView();
        executor.fallbackSampler = host.device.createSampler({});
        executor.fallbackComparisonSampler = host.device.createSampler({});
        executor.readyPromise = Promise.resolve(executor);
    };
    executor.initializeSync();
    return { executor, log, host };
}

function run(executor, stream) {
    executor.submit(stream.bytes(), {});
}

/* ---- the state machine ---- */

test("a context is created on demand and keeps GL's defaults", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(7, 0, 0, 320, 240));
    const state = executor.current;
    assert.ok(state, "makeCurrent creates a context");
    assert.strictEqual(state.depthFunc, GL.LESS);
    assert.strictEqual(state.depthMask, true);
    assert.strictEqual(state.frontFace, GL.CCW);
    assert.strictEqual(state.cullFace, GL.BACK);
    assert.strictEqual(state.shadeModel, GL.SMOOTH);
    assert.strictEqual(state.blend.srcRGB, GL.ONE);
    assert.strictEqual(state.blend.dstRGB, GL.ZERO);
    assert.strictEqual(state.lights[0].diffuse[0], 1,
        "GL_LIGHT0 starts with a white diffuse and the rest black");
    assert.strictEqual(state.lights[1].diffuse[0], 0);
    assert.ok(state.polygonStipple.every(value => value === 0xff),
        "the default 32x32 polygon stipple is all ones");
    const ambient = [...state.material.front.ambient];
    assert.ok(Math.abs(ambient[0] - 0.2) < 1e-6 && ambient[3] === 1,
        "the default front material ambient is 0.2, 0.2, 0.2, 1");
});

// opengl32_proxy.c reports the drawing window from WinEvent hooks: covered by
// other windows entirely (Warcraft III's cinematic popup under -opengl) or in
// part, hidden or minimised
test("window-state records describe the drawing window", () => {
    const surfaces = [];
    const { executor } = newExecutor({ onSurface: (surface, reason) => surfaces.push({ ...surface, reason }) });
    run(executor, new GLStream().makeCurrent(7, 40, 30, 200, 100));
    const IS_WINDOW = 1, VISIBLE = 2, ICONIC = 4, OCCLUDED = 64;
    run(executor, new GLStream().windowState(7, IS_WINDOW | VISIBLE | OCCLUDED, 40, 30, 200, 100));
    let last = surfaces[surfaces.length - 1];
    assert.strictEqual(last.reason, "window-state");
    assert.strictEqual(last.occluded, true);
    assert.strictEqual(last.visible, true, "covered, not hidden");
    run(executor, new GLStream().windowState(7, IS_WINDOW | VISIBLE, 50, 60, 200, 100,
        [[0, 0, 200, 40], [0, 40, 80, 100]]));
    last = surfaces[surfaces.length - 1];
    assert.strictEqual(last.occluded, false);
    assert.deepStrictEqual([last.x, last.y], [50, 60], "the window moved");
    assert.deepStrictEqual(last.visibleRegion, {
        rects: [{ left: 0, top: 0, right: 200, bottom: 40 }, { left: 0, top: 40, right: 80, bottom: 100 }],
        baseWidth: 200, baseHeight: 100, originX: 50, originY: 60 });
    run(executor, new GLStream().makeCurrent(7, 50, 60, 200, 100));
    assert.ok(executor.surface.visibleRegion, "making the context current again keeps the region");
    run(executor, new GLStream().windowState(7, IS_WINDOW | VISIBLE | ICONIC, 50, 60, 200, 100));
    last = surfaces[surfaces.length - 1];
    assert.strictEqual(last.reason, "hide");
    assert.strictEqual(last.visible, false, "a minimised window takes the picture down");
    run(executor, new GLStream().windowState(7, IS_WINDOW | VISIBLE, 50, 60, 200, 100));
    assert.strictEqual(surfaces[surfaces.length - 1].visibleRegion, null);
    assert.strictEqual(surfaces[surfaces.length - 1].visible, true, "restored");
});

test("WGL context ids separate state while share-group ids share objects", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(77, 0, 0, 64, 64, 1, 11)
        .names(GLFN.GEN_TEXTURES, [91]));
    const first = executor.current;

    run(executor, new GLStream().makeCurrent(77, 0, 0, 64, 64, 2, 22));
    const second = executor.current;
    assert.notStrictEqual(second, first,
        "two HGLRCs on one HWND must not alias context state");
    assert.notStrictEqual(second.shareGroup, first.shareGroup);
    assert.ok(!second.shareGroup.textures.has(91));

    run(executor, new GLStream().makeCurrent(88, 0, 0, 64, 64, 3, 11));
    const shared = executor.current;
    assert.notStrictEqual(shared, first);
    assert.strictEqual(shared.shareGroup, first.shareGroup,
        "wglShareLists contexts use the same object namespace");
    assert.ok(shared.shareGroup.textures.has(91));
});

test("late teardown deletes and ARB unbinds are silent no-ops", () => {
    const { executor } = newExecutor();
    let warnings = 0;
    const originalWarn = console.warn;
    console.warn = () => { ++warnings; };
    try {
        run(executor, new GLStream()
            .names(GLFN.DELETE_TEXTURES, [91])
            .call("BIND_PROGRAM_ARB", GL.VERTEX_PROGRAM_ARB, 0)
            .call("BIND_PROGRAM_ARB", GL.FRAGMENT_PROGRAM_ARB, 0));
        assert.strictEqual(warnings, 0,
            "process-detach cleanup must not produce a no-context warning");
        run(executor, new GLStream()
            .call("BIND_PROGRAM_ARB", GL.VERTEX_PROGRAM_ARB, 7));
        assert.strictEqual(warnings, 1,
            "a non-zero context-free bind still exposes a real ordering bug");
    } finally {
        console.warn = originalWarn;
    }
});

test("the matrix stack multiplies in GL's order", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("MATRIX_MODE", GL.MODELVIEW)
        .call("LOAD_IDENTITY")
        .call("TRANSLATEF", 1, 2, 3)
        .call("SCALEF", 2, 2, 2);
    run(executor, stream);
    const m = executor.topOf(GL.MODELVIEW);
    // glTranslate then glScale means the scale is applied first to a vertex.
    assert.strictEqual(m[0], 2);
    assert.strictEqual(m[12], 1);
    assert.strictEqual(m[13], 2);
    assert.strictEqual(m[14], 3);
});

test("SGI color matrix transforms pixel rectangles before post scale and bias", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("MATRIX_MODE", GL.COLOR)
        .call("LOAD_IDENTITY")
        .call("SCALEF", 0.5, 1, 1)
        .call("PIXEL_TRANSFERF", GL.POST_COLOR_MATRIX_RED_BIAS_SGI, 0.25));
    const rgba = new Uint8Array([200, 64, 0, 255]);
    executor.applyPixelTransfer(rgba);
    assert.deepStrictEqual([...rgba], [164, 64, 0, 255]);
});

test("glPushMatrix past the stack depth raises GL_STACK_OVERFLOW", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("MATRIX_MODE", GL.PROJECTION);
    for (let i = 0; i < 8; ++i) stream.call("PUSH_MATRIX");
    run(executor, stream);
    assert.strictEqual(executor.current.error, GL.STACK_OVERFLOW);
});

test("glEnable routes per-unit capabilities to the active unit", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0 + 3)
        .call("ENABLE", GL.TEXTURE_2D)
        .call("ENABLE", GL.TEXTURE_GEN_S));
    const units = executor.current.textureUnits;
    assert.ok(units[3].enabledTargets.has(GL.TEXTURE_2D));
    assert.ok(!units[0].enabledTargets.has(GL.TEXTURE_2D),
        "the capability belongs to the active unit alone");
    assert.strictEqual(units[3].texGen[0].enabled, true);
});

test("glLight POSITION is captured in eye space at call time", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("MATRIX_MODE", GL.MODELVIEW)
        .call("LOAD_IDENTITY")
        .call("TRANSLATEF", 10, 0, 0)
        .call("LIGHTFV", GL.LIGHT0, GL.POSITION, 4, 0, 0, 0, 1)
        .call("TRANSLATEF", 100, 0, 0);
    run(executor, stream);
    const light = executor.current.lights[0];
    assert.strictEqual(light.eyePosition[0], 10,
        "a later modelview change must not move an already-positioned light");
});

/* ---- synchronous queries ---- */

test("glGetError reports the first error and clears it", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0 + 99);
    const first = stream.queryError();
    const second = stream.queryError();
    run(executor, stream);
    assert.strictEqual(first.view.getUint32(0, true), executorModule.SYNC_STATUS_OK);
    assert.strictEqual(first.view.getUint32(4, true), GL.INVALID_ENUM);
    assert.strictEqual(second.view.getUint32(4, true), GL.NO_ERROR,
        "the error queue is emptied by a read");
});

test("glGetIntegerv is answered without touching the GPU", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
    const answer = stream.queryInteger(GL.MAX_TEXTURE_UNITS);
    const sampleBuffers = stream.queryInteger(GL.SAMPLE_BUFFERS);
    const samples = stream.queryInteger(GL.SAMPLES);
    const before = log.submits.length;
    run(executor, stream);
    assert.strictEqual(answer.view.getUint32(4, true), executorModule.SYNC_STATUS_OK);
    assert.strictEqual(answer.view.getUint32(8, true), 8);
    assert.strictEqual(sampleBuffers.view.getUint32(8, true), 0);
    assert.strictEqual(samples.view.getUint32(8, true), 0,
        "a non-multisample pixel format reports zero GL samples");
    assert.strictEqual(log.submits.length, before,
        "answering a state query must not submit GPU work");
});

test("the extension string only advertises what the adapter backs", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64));
    const withBC = executor.extensionString();
    assert.ok(withBC.indexOf("GL_EXT_texture_compression_s3tc") >= 0);
    executor.deviceFeatures = { bc: false, float32Filterable: false };
    const withoutBC = executor.extensionString();
    assert.ok(withoutBC.indexOf("GL_EXT_texture_compression_s3tc") < 0,
        "S3TC is not advertised when the adapter has no BC formats");
    assert.ok(withoutBC.indexOf("GL_ARB_multitexture") >= 0);
    for (const extension of [
        "GL_ARB_texture_compression", "GL_ARB_multisample",
        "GL_ARB_texture_border_clamp", "GL_EXT_generate_mipmap",
        "GL_SGI_color_matrix",
    ]) {
        assert.ok(withoutBC.split(" ").includes(extension),
            extension + " is part of the bridge-guaranteed 1.3/1.4 profile");
    }
});

test("ARB sample coverage reaches the WebGPU pipeline mask", () => {
    const { executor, log } = newExecutor();
    run(executor, immediateTriangle(
        new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("ENABLE", GL.SAMPLE_COVERAGE)
        .call("SAMPLE_COVERAGE", 0, 0)));
    assert.strictEqual(log.draws[0].pipeline.descriptor.multisample.mask, 0,
        "zero sample coverage suppresses the one-sample framebuffer");
});

test("glGetString reports GL 2.1 and GLSL 1.20", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
    const version = stream.queryString(GL.VERSION, 64);
    const glsl = stream.queryString(GL.SHADING_LANGUAGE_VERSION, 64);
    run(executor, stream);
    const read = answer => {
        const payload = answer.bytes;
        let text = "";
        for (let i = 16; i < payload.length && payload[i]; ++i)
            text += String.fromCharCode(payload[i]);
        return text;
    };
    assert.ok(read(version).startsWith("2.1"), read(version));
    assert.strictEqual(read(glsl), "1.20");
});

/* ---- clears and the frame ---- */

test("glClear before any draw becomes a load operation", () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("CLEAR_COLOR", 0.25, 0.5, 0.75, 1)
        .call("CLEAR", GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT));
    assert.strictEqual(log.passes.length, 1);
    const attachment = log.passes[0].descriptor.colorAttachments[0];
    assert.strictEqual(attachment.loadOp, "clear");
    assert.strictEqual(attachment.clearValue.r, 0.25);
    assert.strictEqual(
        log.passes[0].descriptor.depthStencilAttachment.depthLoadOp, "clear");
});

test("scissored and masked clears are rendered instead of widening the clear", () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("ENABLE", GL.SCISSOR_TEST)
        .call("SCISSOR", 10, 20, 30, 40)
        .call("COLOR_MASK", 1, 0, 1, 0)
        .call("CLEAR_COLOR", 0.2, 0.4, 0.6, 1)
        .call("CLEAR", GL.COLOR_BUFFER_BIT));
    const pass = log.passes.find(entry =>
        entry.descriptor.label === "GL masked/scissored clear");
    assert.ok(pass, "the restricted clear uses its dedicated draw pass");
    assert.deepStrictEqual(pass.scissor, [10, 20, 30, 40]);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].pipeline.descriptor.fragment.targets[0].writeMask,
        1 | 4);
});

test("a depth-only FBO omits stencil operations from its render pass", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_FRAMEBUFFERS, [1])
        .names(GLFN.GEN_RENDERBUFFERS, [1])
        .call("BIND_RENDERBUFFER", GL.RENDERBUFFER_EXT, 1)
        .call("RENDERBUFFER_STORAGE", GL.RENDERBUFFER_EXT,
            GL.DEPTH_COMPONENT24, 64, 64)
        .call("BIND_FRAMEBUFFER", GL.FRAMEBUFFER_EXT, 1)
        .call("FRAMEBUFFER_RENDERBUFFER", GL.FRAMEBUFFER_EXT,
            GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER_EXT, 1)
        .call("DRAW_BUFFER", GL.NONE)
        .call("CLEAR", GL.DEPTH_BUFFER_BIT);
    immediateTriangle(stream);
    run(executor, stream);

    const pass = log.passes.find(entry =>
        entry.descriptor.label === "GL pass");
    const attachment = pass.descriptor.depthStencilAttachment;
    assert.strictEqual(attachment.view.texture.descriptor.format,
        "depth32float");
    assert.strictEqual(attachment.depthLoadOp, "clear");
    assert.ok(!("stencilLoadOp" in attachment));
    assert.ok(!("stencilStoreOp" in attachment));
    assert.ok(!("stencilClearValue" in attachment));
});

test("a masked depth clear also omits stencil operations on a depth-only FBO", () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_FRAMEBUFFERS, [1])
        .names(GLFN.GEN_RENDERBUFFERS, [1])
        .call("BIND_RENDERBUFFER", GL.RENDERBUFFER_EXT, 1)
        .call("RENDERBUFFER_STORAGE", GL.RENDERBUFFER_EXT,
            GL.DEPTH_COMPONENT24, 64, 64)
        .call("BIND_FRAMEBUFFER", GL.FRAMEBUFFER_EXT, 1)
        .call("FRAMEBUFFER_RENDERBUFFER", GL.FRAMEBUFFER_EXT,
            GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER_EXT, 1)
        .call("DRAW_BUFFER", GL.NONE)
        .call("ENABLE", GL.SCISSOR_TEST)
        .call("SCISSOR", 2, 2, 32, 32)
        .call("CLEAR", GL.DEPTH_BUFFER_BIT));

    const pass = log.passes.find(entry =>
        entry.descriptor.label === "GL masked/scissored clear");
    const attachment = pass.descriptor.depthStencilAttachment;
    assert.ok(!("stencilLoadOp" in attachment));
    assert.ok(!("stencilStoreOp" in attachment));
});

/* ---- drawing ---- */

function immediateTriangle(stream) {
    return stream.call("BEGIN", GL.TRIANGLES)
        .call("COLOR4F", 1, 0, 0, 1).call("VERTEX3F", -1, -1, 0)
        .call("COLOR4F", 0, 1, 0, 1).call("VERTEX3F", 1, -1, 0)
        .call("COLOR4F", 0, 0, 1, 1).call("VERTEX3F", 0, 1, 0)
        .call("END");
}

test("an immediate-mode triangle produces one draw with one vertex buffer", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240);
    immediateTriangle(stream);
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].count, 3);
    const pipeline = log.draws[0].pipeline;
    assert.strictEqual(pipeline.descriptor.vertex.buffers.length, 1);
    const attributes = pipeline.descriptor.vertex.buffers[0].attributes;
    // Position at location 0 and colour at 3 -- the historical slots every
    // engine of this era assumes.
    assert.deepStrictEqual(attributes.map(a => a.shaderLocation).sort((a, b) => a - b),
        [0, 3]);
    assert.strictEqual(executor.stats.immediateBatches, 1);
});

test("immediate mode ignores stale client-array attributes", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("ENABLE_CLIENT_STATE", GL.NORMAL_ARRAY);
    immediateTriangle(stream);
    run(executor, stream);

    const descriptor = log.draws[0].pipeline.descriptor.vertex;
    assert.ok(!descriptor.module.code.includes("@location(2) normal"),
        "an enabled normal array is irrelevant to glBegin/glEnd vertices");
    assert.deepStrictEqual(descriptor.buffers[0].attributes.map(attribute =>
        attribute.shaderLocation).sort((a, b) => a - b), [0, 3],
        "the shader and immediate buffer agree on their attribute slots");
});

test("GL_QUADS expands to two triangles with GL's provoking vertex first", () => {
    const expanded = executorModule.expandIndices(GL.QUADS, 4, 0);
    assert.strictEqual(expanded.length, 6);
    // GL takes a quad's flat colour from its fourth vertex, so vertex 3 leads
    // both triangles -- WGSL's @interpolate(flat) uses the first.
    assert.strictEqual(expanded[0], 3);
    assert.strictEqual(expanded[3], 3);
    const fan = executorModule.expandIndices(GL.TRIANGLE_FAN, 5, 0);
    assert.strictEqual(fan.length, 9);
    assert.strictEqual(fan[0], 1, "a fan's provoking vertex is not the centre");
    const loop = executorModule.expandIndices(GL.LINE_LOOP, 4, 0);
    assert.deepStrictEqual([...loop], [0, 1, 2, 3, 0]);
});

test("a GL_QUADS draw is issued as an indexed triangle list", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("BEGIN", GL.QUADS);
    for (const [x, y] of [[-1, -1], [1, -1], [1, 1], [-1, 1]])
        stream.call("VERTEX3F", x, y, 0);
    stream.call("END");
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].indexed, true);
    assert.strictEqual(log.draws[0].count, 6);
    assert.strictEqual(log.draws[0].pipeline.descriptor.primitive.topology,
        "triangle-list");
});

test("glPolygonMode line and point rasterize triangle edges and vertices", () => {
    const line = newExecutor();
    let stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("POLYGON_MODE", GL.FRONT_AND_BACK, GL.LINE);
    immediateTriangle(stream);
    run(line.executor, stream);
    assert.strictEqual(line.log.draws[0].indexed, true);
    assert.strictEqual(line.log.draws[0].count, 6);
    assert.strictEqual(line.log.draws[0].pipeline.descriptor.primitive.topology,
        "line-list");

    const point = newExecutor();
    stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("POLYGON_MODE", GL.FRONT_AND_BACK, GL.POINT);
    immediateTriangle(stream);
    run(point.executor, stream);
    assert.strictEqual(point.log.draws[0].count, 3);
    assert.strictEqual(point.log.draws[0].pipeline.descriptor.primitive.topology,
        "point-list");
});

test("culling both faces drops polygon draws", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("ENABLE", GL.CULL_FACE)
        .call("CULL_FACE", GL.FRONT_AND_BACK);
    immediateTriangle(stream);
    run(executor, stream);
    assert.strictEqual(log.draws.length, 0);
});

test("wide points and point sprites expand to instanced quads", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("POINT_SIZE", 8)
        .call("BEGIN", GL.POINTS)
        .call("VERTEX3F", 0, 0, 0)
        .call("END");
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].count, 6,
        "one logical point is rendered as a six-vertex quad");
    assert.strictEqual(log.draws[0].instances, 1);
    const buffers = log.draws[0].pipeline.descriptor.vertex.buffers;
    assert.strictEqual(buffers[0].stepMode, "instance");
    assert.strictEqual(buffers[buffers.length - 1].stepMode, "vertex");
    assert.strictEqual(
        buffers[buffers.length - 1].attributes[0].shaderLocation,
        require("../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js").POINT_CORNER_LOCATION);
    assert.strictEqual(log.draws[0].pipeline.descriptor.primitive.topology,
        "triangle-list");
});

test("colour logic XOR snapshots the attachment and disables blending", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("ENABLE", GL.BLEND)
        .call("ENABLE", GL.COLOR_LOGIC_OP)
        .call("LOGIC_OP", GL.XOR);
    immediateTriangle(stream);
    run(executor, stream);
    assert.ok(log.encoders.some(encoder =>
        encoder.copies.some(copy => copy[0] === "t2t")),
    "the destination colour attachment is copied before drawing");
    const draw = log.draws[0];
    assert.equal(draw.pipeline.descriptor.fragment.targets[0].blend, undefined,
        "logic operations take precedence over blending");
    assert.match(draw.pipeline.descriptor.fragment.module.code, /s \^ d/);
    assert.ok(draw.pass.calls.some(call =>
        call[0] === "bindGroup" && call[1] === 3));
});

test("point-sprite lower-left origin reaches the generated shader", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("POINT_PARAMETERI", GL.POINT_SPRITE_COORD_ORIGIN, GL.LOWER_LEFT)
        .call("POINT_SIZE", 4)
        .call("BEGIN", GL.POINTS)
        .call("VERTEX3F", 0, 0, 0)
        .call("END");
    run(executor, stream);
    assert.match(log.draws[0].pipeline.descriptor.vertex.module.code,
        /vin\.corner\.y \* 0\.5 \+ 0\.5/);
});

test("the clip-space flip is paired with reversed winding", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("ENABLE", GL.CULL_FACE)
        .call("FRONT_FACE", GL.CCW)
        .call("CULL_FACE", GL.BACK);
    immediateTriangle(stream);
    run(executor, stream);
    const primitive = log.draws[0].pipeline.descriptor.primitive;
    assert.strictEqual(primitive.frontFace, "cw",
        "GL_CCW is reported as cw because the vertex shader negates clip Y");
    assert.strictEqual(primitive.cullMode, "back");
    assert.ok(log.draws[0].pipeline.descriptor.vertex.module.code
        .indexOf("clip.y = -clip.y;") >= 0, "the flip is in the shader");
});

test("blend and depth state reach the pipeline descriptor", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("ENABLE", GL.BLEND)
        .call("BLEND_FUNC_SEPARATE", GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA,
            GL.ONE, GL.ZERO)
        .call("BLEND_EQUATION_SEPARATE", GL.FUNC_ADD, GL.FUNC_SUBTRACT)
        .call("ENABLE", GL.DEPTH_TEST)
        .call("DEPTH_FUNC", GL.LEQUAL)
        .call("DEPTH_MASK", 0)
        .call("COLOR_MASK", 1, 1, 0, 1);
    immediateTriangle(stream);
    run(executor, stream);
    const descriptor = log.draws[0].pipeline.descriptor;
    const target = descriptor.fragment.targets[0];
    assert.strictEqual(target.blend.color.srcFactor, "src-alpha");
    assert.strictEqual(target.blend.color.dstFactor, "one-minus-src-alpha");
    assert.strictEqual(target.blend.alpha.operation, "subtract");
    assert.strictEqual(target.writeMask, 1 | 2 | 8);
    assert.strictEqual(descriptor.depthStencil.depthCompare, "less-equal");
    assert.strictEqual(descriptor.depthStencil.depthWriteEnabled, false);
});

test("changing a state that changes the shader produces a second pipeline", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240);
    immediateTriangle(stream);
    stream.call("ENABLE", GL.FOG).call("FOGI", GL.FOG_MODE, GL.LINEAR);
    immediateTriangle(stream);
    run(executor, stream);
    assert.strictEqual(log.draws.length, 2);
    assert.notStrictEqual(log.draws[0].pipeline, log.draws[1].pipeline,
        "enabling fog must reach the fixed-function signature");
    assert.ok(log.draws[1].pipeline.descriptor.fragment.module.code
        .indexOf("fogFactor") >= 0);
});

test("a client-array draw packs every enabled array into one buffer", () => {
    const { executor, log } = newExecutor();
    const positions = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);
    const colors = new Uint8Array([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]);
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, stride: 12,
                      data: new Uint8Array(positions.buffer) },
            color: { size: 4, type: GL.UNSIGNED_BYTE, stride: 4, data: colors },
        });
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].count, 3);
    const buffers = log.draws[0].pipeline.descriptor.vertex.buffers;
    assert.strictEqual(buffers.length, 1);
    assert.strictEqual(buffers[0].arrayStride, (4 + 4) * 4,
        "position is always a vec4 and colour is widened to float");
});

test("Warcraft unlit indexed draws ignore a stale normal array", () => {
    const { executor, log } = newExecutor();
    const positions = new Float32Array([
        -1, -1, 0, 1, -1, 0, 0, 1, 0,
    ]);
    const normals = new Float32Array([
        0, 0, 1, 0, 0, 1, 0, 0, 1,
    ]);
    const indices = new Uint16Array([0, 1, 2]);
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("ENABLE_CLIENT_STATE", GL.VERTEX_ARRAY)
        .call("ENABLE_CLIENT_STATE", GL.NORMAL_ARRAY)
        .drawElements(GL.TRIANGLES,
            new Uint8Array(indices.buffer), GL.UNSIGNED_SHORT, {
                vertex: { size: 3, type: GL.FLOAT, stride: 12,
                    data: new Uint8Array(positions.buffer) },
                normal: { size: 3, type: GL.FLOAT, stride: 12,
                    data: new Uint8Array(normals.buffer) },
            });
    run(executor, stream);

    assert.strictEqual(log.draws.length, 1);
    const vertex = log.draws[0].pipeline.descriptor.vertex;
    assert.ok(!vertex.module.code.includes("@location(2) normal"),
        "an unlit pass must not make VSIn consume the stale normal array");
    assert.deepStrictEqual(vertex.buffers[0].attributes.map(attribute =>
        attribute.shaderLocation).sort((a, b) => a - b), [0, 3],
        "the fixed shader and the packed layout expose the same slots");
});

/* ---- textures ---- */

test("a LUMINANCE upload is expanded to (l, l, l, 1)", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [5])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 5)
        .texImage2D(GL.TEXTURE_2D, 0, GL.LUMINANCE, 2, 1, GL.LUMINANCE,
            GL.UNSIGNED_BYTE, new Uint8Array([64, 200]));
    run(executor, stream);
    const texture = executor.current.shareGroup.textures.get(5);
    const pixels = texture.levels[0][0].pixels;
    assert.deepStrictEqual([...pixels.subarray(0, 8)],
        [64, 64, 64, 255, 200, 200, 200, 255]);
    assert.strictEqual(texture.baseFormat, "LUMINANCE");
});

test("an ALPHA upload leaves RGB at zero", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [6])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 6)
        .texImage2D(GL.TEXTURE_2D, 0, GL.ALPHA, 1, 1, GL.ALPHA,
            GL.UNSIGNED_BYTE, new Uint8Array([137])));
    const texture = executor.current.shareGroup.textures.get(6);
    assert.deepStrictEqual([...texture.levels[0][0].pixels], [0, 0, 0, 137]);
});

test("BGRA and packed 5-6-5 sources are converted", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [7, 8])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 7)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 1, 1, GL.BGRA,
            GL.UNSIGNED_BYTE, new Uint8Array([1, 2, 3, 4]))
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 8)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGB, 1, 1, GL.RGB,
            GL.UNSIGNED_SHORT_5_6_5, new Uint8Array([0x00, 0xf8]));
    run(executor, stream);
    const bgra = executor.current.shareGroup.textures.get(7);
    assert.deepStrictEqual([...bgra.levels[0][0].pixels], [3, 2, 1, 4]);
    const packed = executor.current.shareGroup.textures.get(8);
    // 0xf800 is full red in 5-6-5, and GL widens by bit replication.
    assert.deepStrictEqual([...packed.levels[0][0].pixels], [255, 0, 0, 255]);
});

test("an incomplete texture samples as opaque black", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [9])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 9)
        .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER,
            GL.LINEAR_MIPMAP_LINEAR)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 4, 4, GL.RGBA, GL.UNSIGNED_BYTE,
            new Uint8Array(4 * 4 * 4)));
    const texture = executor.current.shareGroup.textures.get(9);
    assert.strictEqual(executor.textureIsComplete(texture), false,
        "a mipmapped filter with only level 0 is incomplete");
});

test("glDrawPixels uploads a pixel rectangle and draws it at the raster position", () => {
    const { executor, log } = newExecutor();
    const pixels = new Uint8Array([
        255, 0, 0, 255, 0, 255, 0, 255,
        0, 0, 255, 255, 255, 255, 255, 255,
    ]);
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("WINDOW_POS3F", 10, 12, 0.5)
        .drawPixels(2, 2, GL.RGBA, GL.UNSIGNED_BYTE, pixels);
    run(executor, stream);
    assert.strictEqual(log.textureWrites.length, 1);
    assert.strictEqual(log.textureWrites[0].byteLength, 16);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.draws[0].count, 6);
    assert.strictEqual(executor.stats.refusals, 0);
});

test("glBitmap expands bits with the current colour and advances raster position", () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("WINDOW_POS3F", 4, 5, 0)
        .call("COLOR4F", 1, 0.5, 0, 1)
        .bitmap(8, 1, 0, 0, 3, -2, new Uint8Array([0x81, 0, 0, 0]));
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(executor.current.current.rasterPos[0], 7);
    assert.strictEqual(executor.current.current.rasterPos[1], 3);
    assert.strictEqual(executor.stats.refusals, 0);
});

test("glGenerateMipmap builds the whole chain", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [10])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 10)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 4, 4, GL.RGBA, GL.UNSIGNED_BYTE,
            new Uint8Array(4 * 4 * 4).fill(128))
        .call("GENERATE_MIPMAP", GL.TEXTURE_2D));
    const texture = executor.current.shareGroup.textures.get(10);
    assert.strictEqual(texture.levels[0].length, 3);
    assert.strictEqual(texture.levels[0][2].width, 1);
    assert.strictEqual(texture.levels[0][1].pixels[0], 128,
        "a box filter over a constant image is that constant");
});

test("DXT1 decodes deterministically when the adapter has no BC", () => {
    // Two-colour block: colour0 red, colour1 blue, all texels index 0.
    const block = new Uint8Array([0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]);
    const rgba = executorModule.decodeDXT(1, block, 4, 4);
    assert.strictEqual(rgba.length, 4 * 4 * 4);
    assert.deepStrictEqual([...rgba.subarray(0, 4)], [255, 0, 0, 255]);
});

test("native BC textures omit render-attachment usage", () => {
    const { executor, log } = newExecutor();
    const blocks = new Uint8Array(16).fill(0x5a);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [227])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 227)
        .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER,
            GL.LINEAR)
        .compressedTexImage2D(GL.TEXTURE_2D, 0,
            GL.COMPRESSED_RGBA_S3TC_DXT5_EXT, 4, 4, blocks));
    const texture = executor.current.shareGroup.textures.get(227);
    assert.deepStrictEqual([...texture.levels[0][0].pixels], [...blocks],
        "the fixed 2D wire header must not consume the DXT payload");
    const gpuTexture = executor.ensureTextureUploaded(texture);
    assert.ok(gpuTexture, "the BC3 texture is created successfully");
    assert.strictEqual(gpuTexture.descriptor.format, "bc3-rgba-unorm");
    assert.strictEqual(gpuTexture.descriptor.usage & 0x10, 0,
        "RENDER_ATTACHMENT is illegal for block-compressed formats");
    assert.ok(gpuTexture.descriptor.usage & 0x04,
        "the compressed texture remains sampleable");
    assert.strictEqual(log.textureWrites.length, 1,
        "the authored DXT block is uploaded normally");
});

test("compressed 2D subimages use the guest's fixed z/depth wire fields", () => {
    const { executor } = newExecutor();
    const initial = new Uint8Array(8).fill(1);
    const replacement = new Uint8Array(8).fill(7);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [228])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 228)
        .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER,
            GL.LINEAR)
        .compressedTexImage2D(GL.TEXTURE_2D, 0,
            GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, 4, 4, initial)
        .compressedTexSubImage2D(GL.TEXTURE_2D, 0, 0, 0, 4, 4,
            GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, replacement));
    const texture = executor.current.shareGroup.textures.get(228);
    assert.deepStrictEqual([...texture.levels[0][0].pixels], [...replacement]);
});

test("native BC tail mips upload using their complete physical block", () => {
    for (const [name, size] of [[229, 2], [230, 1]]) {
        const { executor, log } = newExecutor();
        const block = new Uint8Array(8).fill(size);
        run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
            .names(GLFN.GEN_TEXTURES, [name])
            .call("BIND_TEXTURE", GL.TEXTURE_2D, name)
            .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER,
                GL.LINEAR)
            .compressedTexImage2D(GL.TEXTURE_2D, 0,
                GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, size, size, block));
        const texture = executor.current.shareGroup.textures.get(name);
        executor.ensureTextureUploaded(texture);
        const write = log.textureWrites.at(-1);
        assert.deepStrictEqual(write.size,
            { width: 4, height: 4, depthOrArrayLayers: 1 },
            size + "x" + size + " still occupies one DXT block");
        assert.strictEqual(write.byteLength, 8);
    }
});

test("glTexImage with an S3TC internal format stores ordinary pixels as RGBA8", () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_TEXTURES, [43])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 43)
        .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER,
            GL.LINEAR)
        .texImage2D(GL.TEXTURE_2D, 0,
            GL.COMPRESSED_RGBA_S3TC_DXT1_EXT, 4, 4,
            GL.RGBA, GL.UNSIGNED_BYTE, new Uint8Array(4 * 4 * 4).fill(127)));
    const texture = executor.current.shareGroup.textures.get(43);
    const level = texture.levels[0][0];
    assert.strictEqual(level.compressed, false,
        "glTexImage input consists of texels, not pre-encoded BC blocks");
    assert.strictEqual(level.gpuFormat, "rgba8unorm");
    const gpuTexture = executor.ensureTextureUploaded(texture);
    assert.strictEqual(gpuTexture.descriptor.format, "rgba8unorm");
    assert.ok(gpuTexture.descriptor.usage & 0x10,
        "the compatibility allocation can receive environment-map rendering");
    assert.strictEqual(log.textureWrites.at(-1).byteLength, 4 * 4 * 4,
        "all RGBA source texels are uploaded");
});

/* ---- programs ---- */

const VS = "attribute vec4 vvertex;\nuniform mat4 mvp;\nvarying vec2 tc;\n" +
    "void main(void) { gl_Position = mvp * vvertex; tc = vvertex.xy; }";
const FS = "uniform sampler2D tex0;\nuniform vec4 tint;\nvarying vec2 tc;\n" +
    "void main(void) { gl_FragColor = texture2D(tex0, tc) * tint; }";

function linkedProgram(executor) {
    const stream = new GLStream().makeCurrent(1, 0, 0, 320, 240)
        .call("CREATE_PROGRAM", 1)
        .call("CREATE_SHADER", 10, GL.VERTEX_SHADER)
        .call("CREATE_SHADER", 11, GL.FRAGMENT_SHADER)
        .shaderSource(10, VS)
        .shaderSource(11, FS)
        .call("COMPILE_SHADER", 10)
        .call("COMPILE_SHADER", 11)
        .call("ATTACH_SHADER", 1, 10)
        .call("ATTACH_SHADER", 1, 11)
        .call("LINK_PROGRAM", 1)
        .call("USE_PROGRAM", 1);
    run(executor, stream);
    return executor.current.shareGroup.programs.get(1);
}

test("a GLSL program links and reports its reflection", () => {
    const { executor } = newExecutor();
    const program = linkedProgram(executor);
    assert.strictEqual(program.linked, true, program.log);
    const reflection = program.link.reflection;
    assert.ok(reflection.attributes.some(a => a.name === "vvertex"));
    assert.ok(reflection.uniforms.some(u => u.name === "mvp"));
    assert.ok(reflection.samplers.some(s => s.name === "tex0"));
});

test("glGetUniformLocation and glGetAttribLocation answer synchronously", () => {
    const { executor } = newExecutor();
    linkedProgram(executor);
    const stream = new GLStream();
    // V86GL_LOCATION_KIND_UNIFORM is 1 and _ATTRIB is 2, which is the order
    // openglproxy sends and the opposite of what this test used to assume.
    const uniform = stream.queryLocation(1, 1, "tint", 32);
    const attribute = stream.queryLocation(2, 1, "vvertex", 32);
    const missing = stream.queryLocation(1, 1, "nosuch", 32);
    run(executor, stream);
    const status = a => a.view.getUint32(12, true);
    const location = a => a.view.getInt32(16, true);
    assert.strictEqual(status(uniform), executorModule.SYNC_STATUS_OK);
    assert.ok(location(uniform) >= 0);
    assert.ok(location(attribute) >= 0);
    assert.strictEqual(location(missing), -1);
});

test("uniform locations do not alias across GLSL programs", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
    for (const [program, vertex, fragment] of [[1, 10, 11], [2, 20, 21]]) {
        stream.call("CREATE_PROGRAM", program)
            .call("CREATE_SHADER", vertex, GL.VERTEX_SHADER)
            .call("CREATE_SHADER", fragment, GL.FRAGMENT_SHADER)
            .shaderSource(vertex, VS)
            .shaderSource(fragment, FS)
            .call("COMPILE_SHADER", vertex)
            .call("COMPILE_SHADER", fragment)
            .call("ATTACH_SHADER", program, vertex)
            .call("ATTACH_SHADER", program, fragment)
            .call("LINK_PROGRAM", program);
    }
    run(executor, stream);

    const first = executor.current.shareGroup.programs.get(1);
    const second = executor.current.shareGroup.programs.get(2);
    const firstTint = first.uniformByName.get("tint");
    const secondTint = second.uniformByName.get("tint");
    assert.notStrictEqual(firstTint.location, secondTint.location,
        "the guest proxy indexes locations globally, not by current program");

    run(executor, new GLStream().call("USE_PROGRAM", 2)
        .uniformfv(secondTint.location, 4, 1, [0.1, 0.2, 0.3, 0.4]));
    const at = secondTint.offsetBytes >> 2;
    assert.ok(Math.abs(second.uniformFloats[at] - 0.1) < 1e-6);
    assert.strictEqual(first.uniformFloats[firstTint.offsetBytes >> 2], 0,
        "updating program B must not land in program A's uniform storage");
});

test("uniform locations also remain unique across non-shared contexts", () => {
    const { executor } = newExecutor();
    const link = (context, shareGroup, vertex, fragment) => {
        const stream = new GLStream().makeCurrent(context, 0, 0, 64, 64,
            context, shareGroup)
            .call("CREATE_PROGRAM", 1)
            .call("CREATE_SHADER", vertex, GL.VERTEX_SHADER)
            .call("CREATE_SHADER", fragment, GL.FRAGMENT_SHADER)
            .shaderSource(vertex, VS)
            .shaderSource(fragment, FS)
            .call("COMPILE_SHADER", vertex)
            .call("COMPILE_SHADER", fragment)
            .call("ATTACH_SHADER", 1, vertex)
            .call("ATTACH_SHADER", 1, fragment)
            .call("LINK_PROGRAM", 1);
        run(executor, stream);
        return executor.current.shareGroup.programs.get(1);
    };
    const first = link(1, 11, 10, 11);
    const second = link(2, 22, 20, 21);
    assert.notStrictEqual(first.uniformByName.get("tint").location,
        second.uniformByName.get("tint").location,
        "the guest location table spans every HGLRC in the process");
});

test("glUniform4fv lands where the reflection says it does", () => {
    const { executor } = newExecutor();
    const program = linkedProgram(executor);
    const tint = program.uniformByName.get("tint");
    run(executor, new GLStream().uniformfv(tint.location, 4, 1,
        [0.25, 0.5, 0.75, 1]));
    const at = tint.offsetBytes >> 2;
    assert.deepStrictEqual([...program.uniformFloats.subarray(at, at + 4)],
        [0.25, 0.5, 0.75, 1]);
});

test("glUniform1i on a sampler rebinds a texture unit rather than writing a value", () => {
    const { executor } = newExecutor();
    const program = linkedProgram(executor);
    const sampler = program.uniformByName.get("tex0");
    run(executor, new GLStream().uniformiv(sampler.location, 1, 1, [3]));
    assert.strictEqual(program.samplerUnits.get("tex0"), 3);
});

test("glGetShaderiv reports a compile failure with a usable log", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_SHADER", 20, GL.VERTEX_SHADER)
        .shaderSource(20, "void main(void) { gl_Position = nonsense; }")
        .call("COMPILE_SHADER", 20);
    const status = stream.queryObjectiv(1, 20, GL.COMPILE_STATUS);
    run(executor, stream);
    assert.strictEqual(status.view.getUint32(16, true), 0);
    const shader = executor.current.shareGroup.shaders.get(20);
    assert.ok(shader.compiled.log.indexOf("undeclared identifier") >= 0,
        shader.compiled.log);
});

test("a program draw binds the sampler's unit, not the sampler's index", () => {
    const { executor, log } = newExecutor();
    const program = linkedProgram(executor);
    const sampler = program.uniformByName.get("tex0");
    const stream = new GLStream()
        .names(GLFN.GEN_TEXTURES, [30])
        .call("ACTIVE_TEXTURE", GL.TEXTURE0 + 2)
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 30)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 1, 1, GL.RGBA, GL.UNSIGNED_BYTE,
            new Uint8Array([9, 9, 9, 255]))
        .call("TEX_PARAMETERI", GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR)
        .uniformiv(sampler.location, 1, 1, [2]);
    immediateTriangle(stream);
    run(executor, stream);
    assert.strictEqual(log.draws.length, 1);
    const groups = log.bindGroups.filter(g =>
        g.descriptor.layout.index === 2);
    assert.ok(groups.length, "the texture group is created");
});

test("program bind groups omit resources used only by uncalled helpers", () => {
    const { executor, log } = newExecutor();
    const vertex =
        "uniform mat4 transform;\n" +
        "vec4 deadState(void) {\n" +
        "  return gl_ModelViewMatrix * gl_Vertex;\n" +
        "}\n" +
        "vec4 livePosition(void) { return transform * gl_Vertex; }\n" +
        "void main(void) { gl_Position = livePosition(); }\n";
    const fragment =
        "uniform sampler2D deadTexture;\n" +
        "uniform sampler2D liveTexture;\n" +
        "vec4 deadSample(void) {\n" +
        "  return texture2D(deadTexture, vec2(0.5));\n" +
        "}\n" +
        "vec4 liveSample(void) {\n" +
        "  return texture2D(liveTexture, vec2(0.5));\n" +
        "}\n" +
        "void main(void) {\n" +
        "  gl_FragColor = liveSample();\n" +
        "}\n";
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_PROGRAM", 1)
        .call("CREATE_SHADER", 10, GL.VERTEX_SHADER)
        .call("CREATE_SHADER", 11, GL.FRAGMENT_SHADER)
        .shaderSource(10, vertex)
        .shaderSource(11, fragment)
        .call("COMPILE_SHADER", 10)
        .call("COMPILE_SHADER", 11)
        .call("ATTACH_SHADER", 1, 10)
        .call("ATTACH_SHADER", 1, 11)
        .call("LINK_PROGRAM", 1)
        .call("USE_PROGRAM", 1);
    immediateTriangle(stream);
    run(executor, stream);

    assert.strictEqual(log.draws.length, 1);
    const uniformGroup = log.bindGroups.find(group =>
        group.descriptor.layout.index === 1);
    assert.deepStrictEqual(uniformGroup.descriptor.entries.map(entry =>
        entry.binding), [1],
        "deadState must not add fixed-state binding 0 to the auto layout");
    const textureGroup = log.bindGroups.find(group =>
        group.descriptor.layout.index === 2);
    assert.deepStrictEqual(textureGroup.descriptor.entries.map(entry =>
        entry.binding), [2, 3],
        "only the sampler reachable from fs_main belongs to the auto layout");
});

/* ---- refusals ---- */

test("the accumulation buffer implements clear, load, arithmetic and return", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CLEAR_ACCUM", 0.1, 0.2, 0.3, 0.4)
        .call("CLEAR", GL.ACCUM_BUFFER_BIT)
        .call("ACCUM", 0x0101, 0.5)  // GL_LOAD
        .call("ACCUM", 0x0100, 0.25) // GL_ACCUM
        .call("ACCUM", 0x0103, 2)    // GL_MULT
        .call("ACCUM", 0x0104, 0.1)  // GL_ADD
        .call("ACCUM", 0x0102, 1));  // GL_RETURN
    assert.ok(executor.accumBuffer);
    assert.strictEqual(executor.accumBuffer.currentTexture.descriptor.format,
        "rgba16float");
    assert.strictEqual(executor.stats.refusals, 0);
});

test("invalid accumulation operations are refused loudly", () => {
    const { executor } = newExecutor();
    const original = console.error;
    console.error = () => {};
    try {
        run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
            .call("ACCUM", 0xDEAD, 1));
    } finally {
        console.error = original;
    }
    assert.strictEqual(executor.stats.refusals, 1);
});

test("a truncated record stops the batch instead of reading past it", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
    const bytes = stream.bytes();
    const truncated = bytes.subarray(0, bytes.length - 4);
    const original = console.error;
    console.error = () => {};
    try {
        executor.submit(truncated, {});
    } finally {
        console.error = original;
    }
    assert.ok(executor.stats.refusals >= 1);
});


test("glDrawElements draws with the indices the guest sent", () => {
    const { executor, log } = newExecutor();
    // 0x544D4143 is the multitexture magic that sits between the fixed header
    // and the indices. Reading the indices from the end of the fixed header
    // instead yielded 16707 and 21581 -- the two halves of that word -- so
    // every indexed draw referenced vertices that were never there.
    const indices = new Uint8Array(new Uint16Array([2, 0, 1]).buffer);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .drawElements(GL.TRIANGLES, indices, GL.UNSIGNED_SHORT, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } }));

    assert.strictEqual(log.draws.length, 1, "the indexed draw must reach the GPU");
    const bind = log.draws[0].pass.calls.filter(call => call[0] === "indexBuffer").pop();
    assert.ok(bind, "an indexed draw binds an index buffer");
    const uploaded = new Uint32Array(executor.vertexStaging.buffer,
        executor.vertexStaging.byteOffset + bind[3], 3);
    assert.deepStrictEqual([...uploaded], [2, 0, 1],
        "the indices must be the guest's own, not the bytes of the header " +
        "that precedes them");
});

/* ---- ARB program error reporting ---- */

function readQueriedString(answer) {
    const payload = answer.bytes;
    let text = "";
    for (let i = 16; i < payload.length && payload[i]; ++i)
        text += String.fromCharCode(payload[i]);
    return text;
}

test("a bad ARB program is the app's error, not a host refusal", () => {
    const { executor } = newExecutor();
    const bad = "this is not a program\nEND\n";
    const payload = new Uint8Array(16 + bad.length);
    const view = new DataView(payload.buffer);
    view.setUint32(0, GL.VERTEX_PROGRAM_ARB, true);
    view.setUint32(4, GL.PROGRAM_FORMAT_ASCII_ARB, true);
    view.setInt32(8, bad.length, true);
    for (let i = 0; i < bad.length; ++i) payload[16 + i] = bad.charCodeAt(i);
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_PROGRAMS_ARB, [1])
        .call("BIND_PROGRAM_ARB", GL.VERTEX_PROGRAM_ARB, 1)
        .record(GLFN.PROGRAM_STRING_ARB, payload);
    const position = stream.queryInteger(GL.PROGRAM_ERROR_POSITION_ARB);
    const text = stream.queryString(GL.PROGRAM_ERROR_STRING_ARB, 256);
    const error = stream.queryError();
    const before = executor.stats.refusals;
    const warn = console.warn;
    console.warn = () => {};
    try { run(executor, stream); } finally { console.warn = warn; }

    assert.strictEqual(executor.stats.refusals, before,
        "the app wrote a bad program; the host refused nothing. Counting it " +
        "would make refusals useless as 'what did the host fail to draw'");
    assert.strictEqual(error.view.getUint32(4, true), GL.INVALID_OPERATION,
        "the extension reports a bad program through glGetError");
    assert.ok(readQueriedString(text).length > 0,
        "GL_PROGRAM_ERROR_STRING_ARB must say why, or the app shows a blank " +
        "error dialog");
    assert.ok(position.view.getInt32(8, true) >= 0,
        "GL_PROGRAM_ERROR_POSITION_ARB is a character offset into the source");
});

test("GL_PROGRAM_ERROR_POSITION_ARB is -1 when nothing failed", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
    const position = stream.queryInteger(GL.PROGRAM_ERROR_POSITION_ARB);
    const text = stream.queryString(GL.PROGRAM_ERROR_STRING_ARB, 64);
    run(executor, stream);
    assert.strictEqual(position.view.getInt32(8, true), -1,
        "0 would read as 'an error at character 0' and make a conformance " +
        "viewer report a failure on a program that compiled");
    assert.strictEqual(readQueriedString(text), "");
});

/* ---- results that arrive after the batch ---- */

test("vertex ring rollover during index expansion keeps the draw's allocations alive", () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64));
    executor.vertexCapacity = 1024;
    const stride = executor.wantedAttributes(null).reduce((n, a) => n + a.components, 0) * 4;
    executor.vertexCursor = 1024 - 4 * stride;
    const original = executor.vertexRing;
    run(executor, new GLStream().drawArrays(GL.QUADS, 4, { vertex: { size: 3, type: GL.FLOAT,
            data: new Uint8Array(48) } }));
    assert.strictEqual(executor.stats.refusals, 0);
    assert.strictEqual(log.draws.length, 1);
    const calls = log.draws[0].pass.calls;
    const vb = calls.find(c => c[0] === "vertexBuffer");
    const ib = calls.find(c => c[0] === "indexBuffer");
    assert.strictEqual(vb[2], original);
    assert.notStrictEqual(vb[2], ib[1], "indices use the new page, vertices the old one");
    assert.strictEqual(ib[3], 0);
    assert.strictEqual(log.submits.length, 1, "submit only after encoding the whole draw");
});

test("uniform rollover retains active uniform slices and an open draw pass", () => {
    const { executor, log } = newExecutor();
    executor.uniformCapacity = 1024;
    executor.uniformCursor = 1024;
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .drawArrays(GL.TRIANGLES, 3, { vertex: { size: 3, type: GL.FLOAT,
            data: new Uint8Array(36) } }));
    assert.strictEqual(executor.stats.refusals, 0);
    assert.strictEqual(log.draws.length, 1);
    assert.strictEqual(log.submits.length, 1);
});

test("bind groups use each uniform slice's page across a rollover", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_PROGRAM", 1)
        .call("CREATE_SHADER", 2, GL.VERTEX_SHADER)
        .call("CREATE_SHADER", 3, GL.FRAGMENT_SHADER)
        .shaderSource(2, "void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }")
        .shaderSource(3, "uniform vec4 tint; void main() { gl_FragColor = tint; }")
        .call("COMPILE_SHADER", 2).call("COMPILE_SHADER", 3)
        .call("ATTACH_SHADER", 1, 2).call("ATTACH_SHADER", 1, 3)
        .call("LINK_PROGRAM", 1).call("USE_PROGRAM", 1));
    executor.uniformCapacity = 1024;
    executor.uniformCursor = 768;
    const original = executor.uniformRing;
    executor.ensurePass();
    const shaders = executor.resolveShaders();
    const pipeline = executor.ensurePipeline(shaders, { mode: GL.TRIANGLES,
        buffers: [] }, null);
    const groups = executor.buildBindGroups(pipeline, shaders);
    const entries = groups.find(g => g.index === 1).group.descriptor.entries;
    assert.ok(entries[0].resource.buffer === original);
    assert.ok(entries[1].resource.buffer === executor.uniformRing);
    assert.notStrictEqual(entries[0].resource.buffer, entries[1].resource.buffer);
    assert.strictEqual(entries[0].resource.offset, 768);
    assert.strictEqual(entries[1].resource.offset, 0);
});

asyncTest("query slot exhaustion submits completed segments and resumes the same GL query", async () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [1]).call("BEGIN_QUERY", GL.SAMPLES_PASSED, 1));
    executor.occlusionCapacity = 2;
    executor.endPass(); executor.ensurePass();
    executor.endPass(); executor.ensurePass();
    executor.endQuery(GL.SAMPLES_PASSED);
    executor.flushFrame();
    await Promise.resolve(); await Promise.resolve();
    assert.deepStrictEqual(log.queryResolves.map(r => r.count), [2, 1]);
    assert.strictEqual(executor.queries.get(1).ready, true);
    assert.strictEqual(executor.queries.get(1).result, 0);
    assert.strictEqual(executor.stats.refusals, 0);
});

asyncTest("occlusion segments across passes are ORed, not overwritten", async () => {
    for (const samples of [[1, 0], [0, 1], [0, 0]]) {
        const { executor, log } = newExecutor();
        run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
            .names(GLFN.GEN_QUERIES, [1]).call("BEGIN_QUERY", GL.SAMPLES_PASSED, 1));
        executor.endPass();
        executor.ensurePass();
        executor.endQuery(GL.SAMPLES_PASSED);
        executor.flushFrame();
        const staging = findBuffer(log, "GL occlusion readback");
        const words = new Uint32Array(staging.storage);
        samples.forEach((sample, slot) => { words[slot * 2] = sample; });
        await Promise.resolve(); await Promise.resolve();
        assert.strictEqual(log.queryResolves[0].count, 2);
        const query = executor.queries.get(1);
        assert.strictEqual(query.ready, true);
        assert.strictEqual(query.result > 0, samples.some(Boolean));
    }
});

asyncTest("query spanning submissions waits for every segment, even out of order", async () => {
    const { executor, log } = newExecutor();
    const maps = [];
    const create = executor.device.createBuffer.bind(executor.device);
    executor.device.createBuffer = desc => {
        const buffer = create(desc);
        if (desc.label === "GL occlusion readback")
            buffer.mapAsync = () => new Promise(resolve => maps.push(resolve));
        return buffer;
    };
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [1]).call("BEGIN_QUERY", GL.SAMPLES_PASSED, 1));
    executor.flushFrame();
    const first = findBuffer(log, "GL occlusion readback");
    executor.ensurePass();
    executor.endQuery(GL.SAMPLES_PASSED);
    executor.flushFrame();
    assert.strictEqual(maps.length, 2);
    const query = executor.queries.get(1);
    maps[1]();
    await Promise.resolve(); await Promise.resolve();
    assert.strictEqual(query.ready, false, "the earlier submission is still pending");
    new Uint32Array(first.storage)[0] = 1;
    maps[0]();
    await Promise.resolve(); await Promise.resolve();
    assert.strictEqual(query.ready, true);
    assert.ok(query.result > 0);
});

function findBuffer(log, label) {
    return log.buffers.filter(buffer => buffer.descriptor.label === label).pop();
}

asyncTest("an occlusion query resolves and reports a visible result", async () => {
    const { executor, log } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [5])
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 5)
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } })
        .call("END_QUERY", GL.SAMPLES_PASSED);
    run(executor, stream);
    executor.flushFrame();

    assert.strictEqual(log.queryResolves.length, 1,
        "ending a query must resolve the set with the work that produced it");
    assert.strictEqual(log.queryResolves[0].first, 0);
    assert.strictEqual(log.queryResolves[0].count, 1,
        "one query in flight resolves one slot");

    // The GPU says slot 0 had samples pass.
    const staging = findBuffer(log, "GL occlusion readback");
    assert.ok(staging, "the resolved set is copied into a mappable buffer");
    new DataView(staging.storage).setUint32(0, 1, true);
    await Promise.resolve();
    await Promise.resolve();

    const query = executor.queries.get(5);
    assert.strictEqual(query.ready, true,
        "the guest spins on GL_QUERY_RESULT_AVAILABLE; it must become true");
    assert.ok(query.result > 0, "a visible query reports a saturated count");
});

asyncTest("a query the GPU says was fully occluded reports zero", async () => {
    const { executor, log } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [9])
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 9)
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } })
        .call("END_QUERY", GL.SAMPLES_PASSED));
    executor.flushFrame();
    findBuffer(log, "GL occlusion readback");   // left zeroed
    await Promise.resolve();
    await Promise.resolve();
    const query = executor.queries.get(9);
    assert.strictEqual(query.ready, true, "an occluded query is still answered");
    assert.strictEqual(query.result, 0);
});

asyncTest("a failed occlusion readback falls back to visible", async () => {
    const { executor } = newExecutor();
    const originalCreateBuffer = executor.device.createBuffer.bind(executor.device);
    executor.device.createBuffer = descriptor => {
        const buffer = originalCreateBuffer(descriptor);
        if (descriptor.label === "GL occlusion readback")
            buffer.mapAsync = () => Promise.reject(new Error("map failed"));
        return buffer;
    };
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [11])
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 11)
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } })
        .call("END_QUERY", GL.SAMPLES_PASSED));
    executor.flushFrame();
    await Promise.resolve();
    await Promise.resolve();
    await Promise.resolve();
    const query = executor.queries.get(11);
    assert.strictEqual(query.ready, true);
    assert.ok(query.result > 0,
        "a transport failure is not proof that the geometry was occluded");
});

asyncTest("query slots are reused after each resolve", async () => {
    const { executor, log } = newExecutor();
    const frame = name => new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [name])
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, name)
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } })
        .call("END_QUERY", GL.SAMPLES_PASSED);
    run(executor, frame(1));
    executor.flushFrame();
    run(executor, frame(2));
    executor.flushFrame();
    assert.strictEqual(log.queryResolves.length, 2);
    assert.deepStrictEqual(
        log.queryResolves.map(resolve => resolve.first), [0, 0],
        "a frame's queries start again at slot 0, or the set fills up and " +
        "later queries are refused");
    await Promise.resolve();
});

asyncTest("a late query readback cannot overwrite a reused Cube 2 query", async () => {
    const { executor } = newExecutor();
    const originalCreateBuffer = executor.device.createBuffer.bind(executor.device);
    const stagingBuffers = [];
    const mapResolvers = [];
    executor.device.createBuffer = descriptor => {
        const buffer = originalCreateBuffer(descriptor);
        if (descriptor.label === "GL occlusion readback") {
            stagingBuffers.push(buffer);
            buffer.mapAsync = () => new Promise(resolve => mapResolvers.push(resolve));
        }
        return buffer;
    };
    const triangle = { vertex: { size: 3, type: GL.FLOAT,
        data: new Uint8Array(36) } };
    const queryFrame = includeName => {
        const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64);
        if (includeName) stream.names(GLFN.GEN_QUERIES, [7]);
        return stream.call("BEGIN_QUERY", GL.SAMPLES_PASSED, 7)
            .drawArrays(GL.TRIANGLES, 3, triangle)
            .call("END_QUERY", GL.SAMPLES_PASSED);
    };

    run(executor, queryFrame(true));
    executor.flushFrame();
    run(executor, queryFrame(false));
    executor.flushFrame();
    assert.strictEqual(mapResolvers.length, 2,
        "both generations should have independent asynchronous readbacks");

    // Complete generation one as occluded after generation two has already
    // reused the object. It must not make generation two ready with stale 0.
    mapResolvers[0]();
    await Promise.resolve();
    await Promise.resolve();
    const query = executor.queries.get(7);
    assert.strictEqual(query.generation, 2);
    assert.strictEqual(query.ready, false,
        "a stale readback must not publish into the current generation");

    // The current generation remains authoritative and completes normally.
    new DataView(stagingBuffers[1].storage).setUint32(0, 1, true);
    mapResolvers[1]();
    await Promise.resolve();
    await Promise.resolve();
    assert.strictEqual(query.ready, true);
    assert.ok(query.result > 0);
});

asyncTest("a pass already open is rebuilt to carry the occlusion query set", () => {
    const { executor, log } = newExecutor();
    const triangle = { vertex: { size: 3, type: GL.FLOAT,
        data: new Uint8Array(36) } };
    // Draw first, so a render pass exists before any query set does.
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .drawArrays(GL.TRIANGLES, 3, triangle)
        .names(GLFN.GEN_QUERIES, [3])
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 3)
        .drawArrays(GL.TRIANGLES, 3, triangle)
        .call("END_QUERY", GL.SAMPLES_PASSED));
    const querying = log.passes.filter(pass =>
        pass.calls.some(call => call[0] === "beginQuery"));
    assert.strictEqual(querying.length, 1);
    assert.ok(querying[0].descriptor.occlusionQuerySet,
        "beginOcclusionQuery is a validation error unless the pass was " +
        "created with the set");
    return Promise.resolve();
});

asyncTest("glReadPixels writes the pixels and then the status word", async () => {
    const { executor, log } = newExecutor();
    const writes = [];
    executor.options.writeGuestMemory = (offset, data) =>
        writes.push({ offset, bytes: Uint8Array.from(data) });
    executor.current = executor.current || null;
    const stream = new GLStream().makeCurrent(1, 0, 0, 4, 4)
        // Read back something that exists: the attachment is created by work,
        // and a readPixels with no colour buffer is a legitimate failure.
        .drawArrays(GL.TRIANGLES, 3, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(36) } });
    const payload = new Uint8Array(32 + 4 * 4 * 4);
    const view = new DataView(payload.buffer);
    view.setInt32(0, 0, true);        // x
    view.setInt32(4, 0, true);        // y
    view.setInt32(8, 4, true);        // width
    view.setInt32(12, 4, true);       // height
    view.setUint32(16, GL.RGBA, true);
    view.setUint32(20, GL.UNSIGNED_BYTE, true);
    view.setUint32(24, 4 * 4 * 4, true);
    stream.record(GLFN.READ_PIXELS, payload);
    const record = stream.payloadView();
    run(executor, stream);

    assert.strictEqual(record.view.getUint32(28, true), 0,
        "the status must still read PENDING when the batch returns -- the " +
        "guest's single check was exactly this bug");
    await Promise.resolve();
    await Promise.resolve();
    assert.strictEqual(record.view.getUint32(28, true), 1,
        "the mapping completes and the status becomes OK");
    assert.deepStrictEqual(writes.map(write => write.offset).slice(-2).sort(
        (a, b) => a - b).length, 2);
    const last = writes[writes.length - 1];
    assert.strictEqual(last.bytes.byteLength, 4,
        "the status word is written last, after the pixels it announces");
});

/* ---- buffer objects and the VBO-direct draw path ---- */

test("pipeline cache separates constant attributes from vertex streams", () => {
    const { executor } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64));
    executor.ensurePass();
    const shaders = executor.resolveShaders();
    const request = { mode: GL.TRIANGLES, buffers: [{ stride: 16,
        attributes: [{ location: 0, format: "float32x4", offset: 0 }] }] };
    const vertex = executor.ensurePipeline(shaders, request, null);
    const constant = executor.ensurePipeline(shaders, { ...request,
        buffers: request.buffers.map(b => ({ ...b, stepMode: "instance" })) }, null);
    assert.notStrictEqual(vertex, constant,
        "the same attribute layout with a different stepping rule is a different pipeline");
    assert.strictEqual(constant.descriptor.vertex.buffers[0].stepMode, "instance");
    assert.strictEqual(executor.ensurePipeline(shaders, request, null), vertex);
});

test("VBO subdata preserves storage referenced by an unsubmitted draw", () => {
    const { executor, log } = newExecutor();
    const data = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_BUFFERS, [4])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 4)
        .bufferData(GL.ARRAY_BUFFER, data.byteLength, GL.STATIC_DRAW,
            new Uint8Array(data.buffer))
        .call("ENABLE_CLIENT_STATE", GL.VERTEX_ARRAY)
        .pointerVBO("VERTEX_POINTER_VBO", 3, GL.FLOAT, 12, 0)
        .call("DRAW_ARRAYS_DIRECT", GL.TRIANGLES, 0, 3));
    const buffer = executor.current.shareGroup.buffers.get(4);
    const original = buffer.gpuBuffer;
    const writeCount = log.bufferWrites.filter(w => w.buffer === original).length;
    executor.bufferSubData(GL.ARRAY_BUFFER, 0,
        new Uint8Array(new Float32Array([2, 2, 2]).buffer));
    assert.notStrictEqual(buffer.gpuBuffer, original,
        "queue.writeBuffer precedes submission, so pending draws need the old storage");
    assert.strictEqual(log.bufferWrites.filter(w => w.buffer === original).length,
        writeCount, "old geometry is never overwritten before its draw executes");
    assert.strictEqual(original.destroyed, false, "retire only after submission");
    const replacement = buffer.gpuBuffer;
    executor.bufferSubData(GL.ARRAY_BUFFER, 12, new Uint8Array([1, 2, 3, 4]));
    assert.strictEqual(buffer.gpuBuffer, replacement,
        "storage not yet used by a draw can still be updated in place");
    executor.flushFrame();
    assert.strictEqual(original.destroyed, true);
});

test("odd-sized VBO data and subdata retain their final bytes", () => {
    const { executor, log } = newExecutor();
    const uploads = [];
    const write = executor.device.queue.writeBuffer;
    executor.device.queue.writeBuffer = (buffer, offset, data, start, size) => {
        write(buffer, offset, data, start, size);
        uploads.push(new Uint8Array(data.buffer, data.byteOffset + start, size).slice());
    };
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_BUFFERS, [4])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 4)
        .bufferData(GL.ARRAY_BUFFER, 6, GL.STATIC_DRAW,
            new Uint8Array([1, 2, 3, 4, 5, 6])));
    assert.strictEqual(log.bufferWrites.at(-1).size, 8,
        "upload the padded storage, not just its first four bytes");
    assert.deepStrictEqual([...uploads.at(-1)], [1, 2, 3, 4, 5, 6, 0, 0]);
    executor.bufferSubData(GL.ARRAY_BUFFER, 5, new Uint8Array([7]));
    assert.strictEqual(log.bufferWrites.at(-1).size, 4);
    assert.deepStrictEqual([...uploads.at(-1)], [5, 7, 0, 0]);
    assert.deepStrictEqual([...executor.bufferFor(GL.ARRAY_BUFFER).shadow],
        [1, 2, 3, 4, 5, 7], "the GL-visible storage remains its requested size");
});

/*
 * openglproxy sends GL_ARRAY_BUFFER_ARB (0x8892) -- the name ARB_vertex_buffer_object
 * gave the target, and the only one any GL 1.5 caller uses. The host's enum
 * table happened to carry ARRAY_BUFFER_ARB but not ARRAY_BUFFER, so the
 * comparison in glBindBuffer read `undefined` and refused every array binding
 * ever made: no vertex data reached the GPU and every VBO draw was skipped.
 * That is what a GLview render test looks like as a black window.
 */
test("glBindBuffer accepts GL_ARRAY_BUFFER and glBufferData fills it", () => {
    const { executor, log } = newExecutor();
    const data = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_BUFFERS, [4])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 4)
        .bufferData(GL.ARRAY_BUFFER, data.byteLength, GL.STATIC_DRAW,
            new Uint8Array(data.buffer)));

    assert.deepStrictEqual(log.refusals || [], [],
        "binding the array buffer is not a refusal");
    assert.strictEqual(executor.current.arrayBuffer, 4);
    const buffer = executor.current.shareGroup.buffers.get(4);
    assert.ok(buffer && buffer.gpuBuffer, "glBufferData allocated storage");
    assert.strictEqual(buffer.size, data.byteLength);
    assert.deepStrictEqual(new Float32Array(buffer.shadow.buffer,
        buffer.shadow.byteOffset, 9), data);
});

test("a client-array draw promoted to VBOs reaches the GPU", () => {
    const { executor, log } = newExecutor();
    const vertices = new Float32Array([-1, -1, 0, 1, -1, 0, 0, 1, 0]);
    const indices = new Uint16Array([0, 1, 2]);
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_BUFFERS, [1, 2])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 1)
        .bufferData(GL.ARRAY_BUFFER, vertices.byteLength, GL.STATIC_DRAW,
            new Uint8Array(vertices.buffer))
        .call("BIND_BUFFER", GL.ELEMENT_ARRAY_BUFFER, 2)
        .bufferData(GL.ELEMENT_ARRAY_BUFFER, indices.byteLength, GL.STATIC_DRAW,
            new Uint8Array(indices.buffer))
        .call("ENABLE_CLIENT_STATE", GL.VERTEX_ARRAY)
        .pointerVBO("VERTEX_POINTER_VBO", 3, GL.FLOAT, 12, 0)
        .drawElementsDirect(GL.TRIANGLES, 3, GL.UNSIGNED_SHORT, 0));

    assert.strictEqual(log.draws.length, 1, "the VBO draw was issued");
    assert.strictEqual(log.draws[0].indexed, true);
    assert.strictEqual(log.draws[0].count, 3);
    const bound = log.draws[0].pass.calls.filter(call => call[0] === "vertexBuffer");
    assert.ok(bound.length >= 1, "the vertex buffer was bound to the pass");
    assert.strictEqual(bound[0][2],
        executor.current.shareGroup.buffers.get(1).gpuBuffer,
        "the pass reads the buffer glBufferData filled, not a scratch upload");
});

test("glVertexAttribPointer does not re-enable Cube 2's constant model color", () => {
    const { executor, log } = newExecutor();
    const vertexShader = "attribute vec4 vvertex, vcolor;\n" +
        "varying vec4 color;\n" +
        "void main() { gl_Position = vvertex; color = vcolor; }";
    const fragmentShader = "varying vec4 color;\n" +
        "void main() { gl_FragColor = color; }";
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_PROGRAM", 1)
        .call("CREATE_SHADER", 2, GL.VERTEX_SHADER)
        .call("CREATE_SHADER", 3, GL.FRAGMENT_SHADER)
        .shaderSource(2, vertexShader)
        .shaderSource(3, fragmentShader)
        .call("COMPILE_SHADER", 2)
        .call("COMPILE_SHADER", 3)
        .call("ATTACH_SHADER", 1, 2)
        .call("ATTACH_SHADER", 1, 3)
        .call("LINK_PROGRAM", 1)
        .call("USE_PROGRAM", 1));

    const program = executor.current.shareGroup.programs.get(1);
    assert.ok(program.linked, program.log);
    const vertexLocation = program.link.reflection.attributes.find(
        attribute => attribute.name === "vvertex").location;
    const colorLocation = program.link.reflection.attributes.find(
        attribute => attribute.name === "vcolor").location;
    const vertices = new Float32Array([
        -1, -1, 0, 1,
         1, -1, 0, 1,
         0,  1, 0, 1,
    ]);
    const indices = new Uint16Array([0, 1, 2]);
    const draw = new GLStream()
        .names(GLFN.GEN_BUFFERS, [11, 12])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 11)
        .bufferData(GL.ARRAY_BUFFER, vertices.byteLength, GL.STATIC_DRAW,
            new Uint8Array(vertices.buffer))
        .attribPointerVBO(vertexLocation, 4, GL.FLOAT, false, 16, 0)
        .call("ENABLE_VERTEX_ATTRIB_ARRAY", vertexLocation)
        .attribPointerVBO(colorLocation, 4, GL.FLOAT, false, 16, 0)
        .call("ENABLE_VERTEX_ATTRIB_ARRAY", colorLocation)
        .call("DISABLE_VERTEX_ATTRIB_ARRAY", colorLocation)
        .call("VERTEX_ATTRIB4F", colorLocation, 1, 1, 1, 1)
        // Cube 2 is allowed to update the dormant pointer while keeping the
        // array disabled.  The draw must still consume the current constant.
        .attribPointerVBO(colorLocation, 4, GL.FLOAT, false, 16, 0)
        .call("BIND_BUFFER", GL.ELEMENT_ARRAY_BUFFER, 12)
        .bufferData(GL.ELEMENT_ARRAY_BUFFER, indices.byteLength,
            GL.STATIC_DRAW, new Uint8Array(indices.buffer))
        .drawElementsDirect(GL.TRIANGLES, 3, GL.UNSIGNED_SHORT, 0);
    run(executor, draw);

    assert.strictEqual(executor.current.genericAttribs[colorLocation].enabled,
        false);
    assert.strictEqual(executor.current.arrays["generic" + colorLocation].enabled,
        false, "the VBO array view follows the generic attribute enable");
    assert.strictEqual(log.draws.length, 1);
    const buffers = log.draws[0].pipeline.descriptor.vertex.buffers;
    const constant = buffers.find(buffer => buffer.stepMode === "instance" &&
        buffer.attributes.some(attribute =>
            attribute.shaderLocation === colorLocation));
    assert.ok(constant, "disabled vcolor is supplied by a constant buffer");
    assert.ok(!buffers.some(buffer => buffer.stepMode !== "instance" &&
        buffer.attributes.some(attribute =>
            attribute.shaderLocation === colorLocation)),
        "the stale color VBO is not read by the model draw");
});

/* ---- the ARB program parameter and info-log records ---- */

/*
 * These six-word query headers are where the two sides disagreed silently:
 * every one of them writes its answer back into the record the guest is still
 * holding, so a field in the wrong place is not an error anywhere, just a
 * wrong number handed to the application.
 */
const ARB_PARAMETER_ENV = 1;
const ARB_PARAMETER_LOCAL = 2;

const ARB_VERTEX_PROGRAM = "!!ARBvp1.0\n" +
    "PARAM mvp[4] = { state.matrix.mvp };\n" +
    "TEMP position;\n" +
    "DP4 position.x, mvp[0], vertex.position;\n" +
    "DP4 position.y, mvp[1], vertex.position;\n" +
    "DP4 position.z, mvp[2], vertex.position;\n" +
    "DP4 position.w, mvp[3], vertex.position;\n" +
    "MOV result.position, position;\n" +
    "MOV result.color, program.env[3];\n" +
    "END\n";

const ARB_MULTITEXTURE_VERTEX_PROGRAM = "!!ARBvp1.0\n" +
    "MOV result.position, vertex.position;\n" +
    "MOV result.color, vertex.color;\n" +
    "MOV result.texcoord[0], vertex.texcoord[0];\n" +
    "MOV result.texcoord[1], vertex.texcoord[1];\n" +
    "END\n";

const ARB_IMMEDIATE_VERTEX_PROGRAM = "!!ARBvp1.0\n" +
    "MOV result.position, vertex.position;\n" +
    "ADD result.color, vertex.normal, vertex.attrib[6];\n" +
    "END\n";

function boundARBProgram(executor, stream) {
    return stream.names(GLFN.GEN_PROGRAMS_ARB, [1])
        .call("BIND_PROGRAM_ARB", GL.VERTEX_PROGRAM_ARB, 1);
}

test("ARB immediate mode binds every shader-read vertex attribute", () => {
    const { executor, log } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB,
            ARB_IMMEDIATE_VERTEX_PROGRAM)
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("NORMAL3F", 0, 0, 1)
        .call("VERTEX_ATTRIB4F", 6, 0.25, 0.5, 0.75, 1);
    immediateTriangle(stream);
    run(executor, stream);

    assert.strictEqual(log.draws.length, 1);
    const descriptor = log.draws[0].pipeline.descriptor.vertex;
    assert.deepStrictEqual(descriptor.buffers[0].attributes.map(attribute =>
        attribute.shaderLocation).sort((a, b) => a - b), [0, 2, 6],
        "normal slot 2 and unaliased generic slot 6 are both present");
    const packed = packedAttributes(executor, log, 3);
    assert.deepStrictEqual(packed[2][0], [0, 0, 1]);
    assert.deepStrictEqual(packed[6][0], [0.25, 0.5, 0.75, 1]);
});

test("an ARB program string arrives intact and assembles", () => {
    const { executor, log } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM);
    run(executor, stream);
    const program = executor.current.shareGroup.arbPrograms.get(1);
    assert.strictEqual(program.source, ARB_VERTEX_PROGRAM,
        "the assembly text is read from offset 16, after {target, format, " +
        "length, reserved}");
    assert.ok(program.compiled && program.compiled.ok,
        "it assembled: " + (program.compiled && program.compiled.log));
    assert.strictEqual(executor.arbErrorPosition, -1);
});

test("an ARB vertex program drives the fixed multitexture fragment stage", () => {
    const { executor, log } = newExecutor();
    const vertices = new Float32Array([
        -1, -1, 0, 1,  -1, 1, 0, 1,  1, -1, 0, 1,
    ]);
    const tex0 = new Float32Array([0, 0, 0, 1, 1, 0]);
    const tex1 = new Float32Array([0, 1, 1, 1, 1, 0]);
    const block = (data, size) => ({
        size, type: GL.FLOAT, stride: 0,
        data: new Uint8Array(data.buffer),
    });
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB,
            ARB_MULTITEXTURE_VERTEX_PROGRAM)
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("SHADE_MODEL", GL.FLAT)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0)
        .call("ENABLE", GL.TEXTURE_2D)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0 + 1)
        .call("ENABLE", GL.TEXTURE_2D)
        .drawElements(GL.TRIANGLES, new Uint16Array([0, 1, 2]),
            GL.UNSIGNED_SHORT, {
                vertex: block(vertices, 4),
                texCoord0: block(tex0, 2),
                texCoord1: block(tex1, 2),
            });
    run(executor, stream);

    assert.deepStrictEqual(log.refusals || [], [],
        "the mixed ARB/fixed pipeline is no longer refused");
    assert.strictEqual(log.draws.length, 1,
        "glDrawElements reaches the GPU instead of producing a black frame");
    const pipeline = log.draws[0].pipeline.descriptor;
    assert.ok(pipeline.vertex.module.code.includes(
        "generated by gl_arb_program.js r2"));
    assert.ok(pipeline.fragment.module.code.includes(
        "generated by gl_fixed_function.js r2"));
    assert.ok(pipeline.fragment.module.code.includes(
        "@location(3) v3 : vec4<f32>"));
    assert.ok(pipeline.fragment.module.code.includes(
        "@location(4) v4 : vec4<f32>"));
    assert.ok(pipeline.vertex.module.code.includes(
        "@interpolate(flat) @location(0) frontColor"));
    assert.ok(pipeline.fragment.module.code.includes(
        "@interpolate(flat) @location(0) v0"),
        "GL_FLAT has matching interpolation on both shader stages");
    assert.ok(!pipeline.vertex.module.code.includes(
        "@group(1) @binding(1)"),
        "the parameter-free ARB program does not declare an unused binding");
    const uniformGroup = log.bindGroups.find(group =>
        group.descriptor.layout.index === 1);
    assert.strictEqual(uniformGroup, undefined,
        "the shared state declaration is used by neither selected entry point, " +
        "so WebGPU omits group 1 from the automatic pipeline layout");
});

/*
 * ARB_vertex_program section 2.14.3: generic attributes 0-5 and 8-15 alias the
 * conventional ones. glview's 1.4 vertex-program test draws through that
 * aliasing, and the two directions below both used to pack the generic
 * attribute's (0, 0, 0, 1) default into every vertex -- a black frame with no
 * refusal, no GL error and a draw that reached the GPU looking healthy.
 */
const ARB_ALIASED_POSITION_PROGRAM = "!!ARBvp1.0\n" +
    "MOV result.position, vertex.position;\n" +
    "MOV result.texcoord[0], vertex.texcoord[0];\n" +
    "END\n";

const ARB_GENERIC_POSITION_PROGRAM = "!!ARBvp1.0\n" +
    "MOV result.position, vertex.attrib[0];\n" +
    "MOV result.texcoord[0], vertex.attrib[8];\n" +
    "END\n";

const ALIAS_VERTICES = new Float32Array([
    -1, -1, 0, 1,  -1, 1, 0, 1,  1, -1, 0, 1,
]);
const ALIAS_TEXCOORDS = new Float32Array([0, 0, 0, 1, 1, 0]);

/* The packed vertex data the draw uploaded, as {location -> [components]}. */
function packedAttributes(executor, log, vertexCount) {
    const draw = log.draws[0];
    const out = {};
    for (const [slot, buffer] of draw.pipeline.descriptor.vertex.buffers.entries()) {
        const binding = draw.pass.calls.find(c => c[0] === "vertexBuffer" && c[1] === slot);
        const floats = new Float32Array(binding[2].storage, binding[3] || 0);
        const stride = buffer.arrayStride / 4;
        for (const attribute of buffer.attributes) {
            assert.ok(attribute.format.startsWith("float32"));
            const components = Number(/x(\d)$/.exec(attribute.format) ?
                /x(\d)$/.exec(attribute.format)[1] : 1);
            const at = attribute.offset / 4;
            out[attribute.shaderLocation] = [];
            for (let v = 0; v < vertexCount; ++v) {
                const start = (buffer.stepMode === "instance" ? 0 : v * stride) + at;
                out[attribute.shaderLocation].push(
                    Array.from(floats.subarray(start, start + components)));
            }
        }
    }
    return out;
}

test("vertex.position reads the array sent as generic attribute 0", () => {
    const { executor, log } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_ALIASED_POSITION_PROGRAM)
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0)
        .call("ENABLE", GL.TEXTURE_2D)
        .drawElementsGL2(GL.TRIANGLES, new Uint16Array([0, 1, 2]),
            GL.UNSIGNED_SHORT, {}, [
                { index: 0, size: 4, type: GL.FLOAT, stride: 0,
                  normalized: false,
                  data: new Uint8Array(ALIAS_VERTICES.buffer) },
                { index: 8, size: 2, type: GL.FLOAT, stride: 0,
                  normalized: false,
                  data: new Uint8Array(ALIAS_TEXCOORDS.buffer) },
            ]);
    run(executor, stream);

    assert.deepStrictEqual(log.refusals || [], []);
    assert.strictEqual(log.draws.length, 1);
    const packed = packedAttributes(executor, log, 3);
    assert.deepStrictEqual(packed[0][0], [-1, -1, 0, 1],
        "generic attribute 0 feeds vertex.position rather than its default");
    assert.deepStrictEqual(packed[0][1], [-1, 1, 0, 1]);
    assert.deepStrictEqual(packed[8][1], [0, 1, 0, 1],
        "generic attribute 8 feeds vertex.texcoord[0]");
});

test("vertex.attrib[0] reads the array sent through glVertexPointer", () => {
    const { executor, log } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_GENERIC_POSITION_PROGRAM)
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0)
        .call("ENABLE", GL.TEXTURE_2D)
        .drawElementsGL2(GL.TRIANGLES, new Uint16Array([0, 1, 2]),
            GL.UNSIGNED_SHORT, {
                vertex: { size: 4, type: GL.FLOAT, stride: 0,
                          data: new Uint8Array(ALIAS_VERTICES.buffer) },
                texCoord0: { size: 2, type: GL.FLOAT, stride: 0,
                             data: new Uint8Array(ALIAS_TEXCOORDS.buffer) },
            }, []);
    run(executor, stream);

    assert.deepStrictEqual(log.refusals || [], []);
    assert.strictEqual(log.draws.length, 1);
    const packed = packedAttributes(executor, log, 3);
    assert.deepStrictEqual(packed[0][0], [-1, -1, 0, 1],
        "glVertexPointer's array feeds vertex.attrib[0]");
    assert.deepStrictEqual(packed[8][1], [0, 1, 0, 1],
        "glTexCoordPointer's array feeds vertex.attrib[8]");
});

test("glview's ARB bump program draws from widened interleaved VBO arrays", () => {
    const { executor, log } = newExecutor();
    const program = `!!ARBvp1.0
ATTRIB iPos = vertex.position;
ATTRIB iNormal = vertex.normal;
ATTRIB iTangent = vertex.attrib[6];
ATTRIB iTex0 = vertex.texcoord[0];
ATTRIB iTex1 = vertex.texcoord[1];
PARAM mvp[4] = { state.matrix.mvp };
PARAM lightDir = program.env[0];
PARAM half = 0.5;
OUTPUT oPos = result.position;
OUTPUT oColor = result.color;
OUTPUT oTex0 = result.texcoord[0];
OUTPUT oTex1 = result.texcoord[1];
TEMP T;
TEMP N;
TEMP B;
TEMP light_surf;
DP4 oPos.x, mvp[0], iPos;
DP4 oPos.y, mvp[1], iPos;
DP4 oPos.z, mvp[2], iPos;
DP4 oPos.w, mvp[3], iPos;
MOV T, iTangent;
MOV N, iNormal;
MUL B, N.zxyw, T.yzxw;
MAD B, N.yzxw, T.zxyw, -B;
MUL B.xyz, B, T.w;
DP3 light_surf.x, T, lightDir;
DP3 light_surf.y, B, lightDir;
DP3 light_surf.z, N, lightDir;
MAD oColor, light_surf, half, half;
MOV oTex0, iTex0;
MOV oTex1, iTex1;
END`;
    // position3, normal3, tangent4, texcoord0.xy, texcoord1.xy
    const vertices = new Float32Array([
        -1, -1, 0,  0, 0, 1,  1, 0, 0, 1,  0, 0,  0, 0,
         1, -1, 0,  0, 0, 1,  1, 0, 0, 1,  1, 0,  1, 0,
         0,  1, 0,  0, 0, 1,  1, 0, 0, 1,  0, 1,  0, 1,
    ]);
    const indices = new Uint16Array([0, 1, 2]);
    const stride = 14 * 4;
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, program)
        .programParameterARB(ARB_PARAMETER_ENV, GL.VERTEX_PROGRAM_ARB, 0,
            [0, 0, 1, 0])
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0)
        .call("ENABLE", GL.TEXTURE_2D)
        .call("ACTIVE_TEXTURE", GL.TEXTURE0 + 1)
        .call("ENABLE", GL.TEXTURE_2D)
        .names(GLFN.GEN_BUFFERS, [1, 2])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 1)
        .bufferData(GL.ARRAY_BUFFER, vertices.byteLength, GL.STATIC_DRAW,
            new Uint8Array(vertices.buffer))
        .pointerVBO("VERTEX_POINTER_VBO", 3, GL.FLOAT, stride, 0)
        .call("ENABLE_CLIENT_STATE", GL.VERTEX_ARRAY)
        .pointerVBO("NORMAL_POINTER_VBO", 3, GL.FLOAT, stride, 3 * 4)
        .call("ENABLE_CLIENT_STATE", GL.NORMAL_ARRAY)
        .attribPointerVBO(6, 4, GL.FLOAT, false, stride, 6 * 4)
        .call("ENABLE_VERTEX_ATTRIB_ARRAY", 6)
        .call("CLIENT_ACTIVE_TEXTURE", GL.TEXTURE0)
        .pointerVBO("TEX_COORD_POINTER_VBO", 2, GL.FLOAT, stride, 10 * 4)
        .call("ENABLE_CLIENT_STATE", GL.TEXTURE_COORD_ARRAY)
        .call("CLIENT_ACTIVE_TEXTURE", GL.TEXTURE0 + 1)
        .pointerVBO("TEX_COORD_POINTER_VBO", 2, GL.FLOAT, stride, 12 * 4)
        .call("ENABLE_CLIENT_STATE", GL.TEXTURE_COORD_ARRAY)
        .call("BIND_BUFFER", GL.ELEMENT_ARRAY_BUFFER, 2)
        .bufferData(GL.ELEMENT_ARRAY_BUFFER, indices.byteLength, GL.STATIC_DRAW,
            new Uint8Array(indices.buffer))
        .drawElementsDirect(GL.TRIANGLES, 3, GL.UNSIGNED_SHORT, 0);
    run(executor, stream);

    assert.deepStrictEqual(log.refusals || [], []);
    assert.strictEqual(log.draws.length, 1,
        "the exact 1.5 program/VBO shape reaches a draw");
    const descriptor = log.draws[0].pipeline.descriptor.vertex;
    assert.deepStrictEqual(descriptor.buffers.flatMap(b => b.attributes).map(a =>
        [a.shaderLocation, a.format]).sort((a, b) => a[0] - b[0]), [
        [0, "float32x4"], [6, "float32x4"], [2, "float32x3"],
        [8, "float32x4"], [9, "float32x4"],
    ].sort((a, b) => a[0] - b[0]),
    "GL size-3/2 arrays are widened to the ARB program input widths");
    const packed = packedAttributes(executor, log, 3);
    assert.deepStrictEqual(packed[0][0], [-1, -1, 0, 1]);
    assert.deepStrictEqual(packed[8][1], [1, 0, 0, 1]);
    assert.deepStrictEqual(packed[9][2], [0, 1, 0, 1]);
    assert.ok(descriptor.module.code.includes(
        "vec4<f32>(0.5, 0.5, 0.5, 0.5)"),
        "the shared 1.4 scalar-PARAM fix is present in the 1.5 shader too");
});

test("a vertex and a fragment program keep separate parameter namespaces", () => {
    const { executor, log } = newExecutor();
    const vertexProgram = "!!ARBvp1.0\n" +
        "PARAM scale = program.local[0];\n" +
        "MUL result.position, vertex.position, scale;\n" +
        "END\n";
    const fragmentProgram = "!!ARBfp1.0\n" +
        "PARAM tint = program.local[0];\n" +
        "MOV result.color, tint;\n" +
        "END\n";
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_PROGRAMS_ARB, [1, 2])
        .call("BIND_PROGRAM_ARB", GL.VERTEX_PROGRAM_ARB, 1)
        .programStringARB(GL.VERTEX_PROGRAM_ARB, vertexProgram)
        .programParameterARB(ARB_PARAMETER_LOCAL, GL.VERTEX_PROGRAM_ARB, 0,
            [7, 7, 7, 7])
        .call("BIND_PROGRAM_ARB", GL.FRAGMENT_PROGRAM_ARB, 2)
        .programStringARB(GL.FRAGMENT_PROGRAM_ARB, fragmentProgram)
        .programParameterARB(ARB_PARAMETER_LOCAL, GL.FRAGMENT_PROGRAM_ARB, 0,
            [0.25, 0.5, 0.75, 1])
        .call("ENABLE", GL.VERTEX_PROGRAM_ARB)
        .call("ENABLE", GL.FRAGMENT_PROGRAM_ARB)
        .drawElements(GL.TRIANGLES, new Uint16Array([0, 1, 2]),
            GL.UNSIGNED_SHORT, {
                vertex: { size: 4, type: GL.FLOAT, stride: 0,
                          data: new Uint8Array(ALIAS_VERTICES.buffer) },
            });
    run(executor, stream);

    assert.deepStrictEqual(log.refusals || [], []);
    assert.strictEqual(log.draws.length, 1);
    const group = log.bindGroups.find(entry =>
        entry.descriptor.layout.index === 1);
    assert.deepStrictEqual(group.descriptor.entries.map(e => e.binding),
        [1, 2], "each stage's parameters get a binding of their own");

    // program.local is per-program: the vertex stage must not be handed the
    // fragment program's block, which is what one shared binding did.
    const count = 28 * 4;
    const localOf = binding => {
        const entry = group.descriptor.entries.find(e => e.binding === binding);
        return Array.from(new Float32Array(executor.uniformStaging.buffer,
            entry.resource.offset, count * 2).subarray(count, count + 4));
    };
    assert.deepStrictEqual(localOf(1), [7, 7, 7, 7]);
    assert.deepStrictEqual(localOf(2), [0.25, 0.5, 0.75, 1]);
});

test("glProgramEnvParameter4fv lands in env, not in local", () => {
    const { executor } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM)
        .programParameterARB(ARB_PARAMETER_ENV, GL.VERTEX_PROGRAM_ARB, 3,
            [0.25, 0.5, 0.75, 1])
        .programParameterARB(ARB_PARAMETER_LOCAL, GL.VERTEX_PROGRAM_ARB, 2,
            [9, 8, 7, 6]);
    run(executor, stream);

    const program = executor.current.shareGroup.arbPrograms.get(1);
    assert.deepStrictEqual([...program.env.subarray(12, 16)],
        [0.25, 0.5, 0.75, 1]);
    assert.deepStrictEqual([...program.local.subarray(8, 12)], [9, 8, 7, 6]);
    assert.deepStrictEqual([...program.local.subarray(12, 16)], [0, 0, 0, 0],
        "the env write must not have gone to local as well");
});

test("glProgramEnvParameters4fv writes the whole run", () => {
    const { executor } = newExecutor();
    const values = [];
    for (let i = 0; i < 12; ++i) values.push(i + 1);
    run(executor, boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM)
        .programParameterARB(ARB_PARAMETER_ENV, GL.VERTEX_PROGRAM_ARB, 1, values));
    const program = executor.current.shareGroup.arbPrograms.get(1);
    assert.deepStrictEqual([...program.env.subarray(4, 16)], values,
        "the count word is honoured, not ignored after the first parameter");
});

test("an env parameter set before the program compiles is accepted", () => {
    const { executor, log } = newExecutor();
    run(executor, boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programParameterARB(ARB_PARAMETER_ENV, GL.VERTEX_PROGRAM_ARB, 0,
            [1, 2, 3, 4]));
    assert.deepStrictEqual(log.refusals || [], [],
        "ARB environment parameters are context state, not program state");
    assert.deepStrictEqual(
        [...executor.current.shareGroup.arbPrograms.get(1).env.subarray(0, 4)],
        [1, 2, 3, 4]);
});

test("glGetProgramEnvParameterfv reads back what was written", () => {
    const { executor } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM)
        .programParameterARB(ARB_PARAMETER_ENV, GL.VERTEX_PROGRAM_ARB, 5,
            [1.5, 2.5, 3.5, 4.5]);
    const answer = stream.queryProgramParameterARB(ARB_PARAMETER_ENV,
        GL.VERTEX_PROGRAM_ARB, 5);
    run(executor, stream);

    assert.strictEqual(answer.view.getUint32(12, true), 1, "status is OK");
    assert.deepStrictEqual([24, 28, 32, 36].map(at =>
        answer.view.getFloat32(at, true)), [1.5, 2.5, 3.5, 4.5]);
});

test("glGetProgramStringARB returns the text at the offset the guest reads", () => {
    const { executor } = newExecutor();
    const stream = boundARBProgram(executor,
        new GLStream().makeCurrent(1, 0, 0, 64, 64))
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM);
    const answer = stream.queryProgramStringARB(GL.VERTEX_PROGRAM_ARB,
        ARB_VERTEX_PROGRAM.length);
    run(executor, stream);

    assert.strictEqual(answer.view.getUint32(8, true), 1, "status is OK");
    assert.strictEqual(answer.view.getUint32(12, true), ARB_VERTEX_PROGRAM.length);
    let text = "";
    for (let i = 0; i < ARB_VERTEX_PROGRAM.length; ++i)
        text += String.fromCharCode(answer.bytes[24 + i]);
    assert.strictEqual(text, ARB_VERTEX_PROGRAM);
});

test("glGetShaderInfoLog reaches the guest's buffer whole", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_SHADER", 1, GL.FRAGMENT_SHADER)
        .shaderSource(1, "void main() { this is not GLSL }")
        .call("COMPILE_SHADER", 1);
    const status = stream.queryObjectiv(1, 1, GL.COMPILE_STATUS);
    const answer = stream.queryObjectLog(1, 1, 256);
    run(executor, stream);

    assert.strictEqual(status.view.getUint32(12, true), 1, "the query answered");
    assert.strictEqual(status.view.getUint32(16, true), 0, "it did not compile");
    assert.strictEqual(answer.view.getUint32(12, true), 1, "log status is OK");
    const length = answer.view.getUint32(16, true);
    let text = "";
    for (let i = 0; i < length; ++i)
        text += String.fromCharCode(answer.bytes[24 + i]);
    assert.strictEqual(text,
        executor.current.shareGroup.shaders.get(1).compiled.log,
        "the log starts at 24 -- four bytes earlier and its first word is lost");
    assert.ok(length > 0, "a failed compile says why");
    assert.strictEqual(answer.bytes[24 + length], 0, "and is NUL-terminated");
});

test("glGetActiveUniform's name, size and type land in the right words", () => {
    const { executor } = newExecutor();
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CREATE_PROGRAM", 1)
        .call("CREATE_SHADER", 2, GL.VERTEX_SHADER)
        .shaderSource(2, "uniform vec4 tint;\nvoid main() {\n" +
            "  gl_Position = gl_Vertex + tint;\n}\n")
        .call("COMPILE_SHADER", 2)
        .call("CREATE_SHADER", 3, GL.FRAGMENT_SHADER)
        .shaderSource(3, "void main() { gl_FragColor = vec4(1.0); }\n")
        .call("COMPILE_SHADER", 3)
        .call("ATTACH_SHADER", 1, 2)
        .call("ATTACH_SHADER", 1, 3)
        .call("LINK_PROGRAM", 1);
    const answer = stream.queryActive(1, 1, 0, 64);
    run(executor, stream);

    assert.strictEqual(answer.view.getUint32(16, true), 1, "status is OK");
    const length = answer.view.getUint32(20, true);
    let name = "";
    for (let i = 0; i < length; ++i)
        name += String.fromCharCode(answer.bytes[40 + i]);
    assert.strictEqual(name, "tint");
    assert.strictEqual(answer.view.getUint32(24, true), 1, "size is one element");
    assert.strictEqual(answer.view.getUint32(28, true), GL.FLOAT_VEC4);
});

test("variable payloads survive a non-zero batch byteOffset", () => {
    const { executor } = newExecutor();
    const bufferBytes = Uint8Array.from([11, 22, 33, 44, 55, 66, 77, 88]);
    const stream = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_BUFFERS, [4])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 4)
        .bufferData(GL.ARRAY_BUFFER, bufferBytes.length, GL.STATIC_DRAW,
            bufferBytes)
        .names(GLFN.GEN_TEXTURES, [5])
        .call("BIND_TEXTURE", GL.TEXTURE_2D, 5)
        .texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, 1, 1, GL.RGBA,
            GL.UNSIGNED_BYTE, Uint8Array.from([1, 2, 3, 4]))
        .call("CREATE_SHADER", 7, GL.VERTEX_SHADER)
        .shaderSource(7, "void main() { gl_Position = gl_Vertex; }")
        .call("COMPILE_SHADER", 7);
    boundARBProgram(executor, stream)
        .programStringARB(GL.VERTEX_PROGRAM_ARB, ARB_VERTEX_PROGRAM);
    stream.queryString(GL.RENDERER, 64);

    // PCI batches are views into the emulator's RAM and therefore normally
    // have a non-zero byteOffset.  Unit fixtures used to start at byte zero,
    // hiding a double-subtraction that corrupted every variable-size payload.
    const encoded = stream.bytes();
    const guestRAM = new Uint8Array(encoded.byteLength + 160);
    guestRAM.set(encoded, 96);
    executor.submit(guestRAM.subarray(96, 96 + encoded.byteLength), {});

    const group = executor.current.shareGroup;
    assert.deepStrictEqual([...group.buffers.get(4).shadow], [...bufferBytes]);
    assert.deepStrictEqual([...group.textures.get(5).levels[0][0].pixels],
        [1, 2, 3, 4]);
    assert.ok(group.shaders.get(7).compiled.ok,
        group.shaders.get(7).compiled.log);
    assert.strictEqual(group.arbPrograms.get(1).source, ARB_VERTEX_PROGRAM);
    assert.ok(group.arbPrograms.get(1).compiled.ok);
    assert.ok(new TextDecoder().decode(guestRAM).includes("v86 WebGPU bridge"),
        "variable-size query output is written into the submitted view");
});

/* ---- draw hot-path regressions ---- */

test("packed indexed draws discard unused prefixes and sparse gaps", () => {
    for (const source of [[60002, 60000, 60001], [60000, 2, 40000, 60000]]) {
        const { executor, log } = newExecutor();
        run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64));
        const values = new Float32Array(60003 * 3);
        for (const i of source) values.set([i, i + 1, i + 2], i * 3);
        let request;
        executor.issueDraw = r => { request = r; };
        executor.drawPacked(GL.TRIANGLES, source.length, {
            vertex: { size: 3, type: GL.FLOAT, data: new Uint8Array(values.buffer) },
        }, { type: GL.UNSIGNED_INT, data: new Uint8Array(new Uint32Array(source).buffer) });
        assert.ok(request);
        const vb = request.buffers[0];
        const uploaded = new Float32Array(vb.gpuBuffer.storage, vb.baseOffset);
        assert.deepStrictEqual(Array.from(request.index.source, i =>
            uploaded[i * vb.stride / 4]), source);
        assert.ok(log.bufferWrites.reduce((n, w) => n + w.size, 0) < 256,
            "a three-vertex draw must not upload 60003 vertices");
    }
});

function normalVBOScene(executor) {
    const data = new Uint8Array(3 * 16);
    const view = new DataView(data.buffer);
    for (let i = 0; i < 3; ++i) {
        view.setFloat32(i * 16, i - 1, true);
        data.set([127, 0, 129], i * 16 + 12);
    }
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 10)
        .bufferData(GL.ARRAY_BUFFER, data.length, GL.STATIC_DRAW, data)
        .pointerVBO("VERTEX_POINTER_VBO", 3, GL.FLOAT, 16, 0)
        .pointerVBO("NORMAL_POINTER_VBO", 3, GL.BYTE, 16, 12)
        .call("ENABLE_CLIENT_STATE", GL.VERTEX_ARRAY)
        .call("ENABLE_CLIENT_STATE", GL.NORMAL_ARRAY)
        .call("ENABLE", GL.LIGHTING)
        .call("BIND_BUFFER", GL.ELEMENT_ARRAY_BUFFER, 11)
        .bufferData(GL.ELEMENT_ARRAY_BUFFER, 8, GL.STATIC_DRAW,
            new Uint8Array(new Uint16Array([99, 0, 1, 2]).buffer)));
}

test("only incompatible VBO attributes are converted and unchanged draws reuse them", () => {
    const { executor, log } = newExecutor();
    normalVBOScene(executor);
    const s = executor.current;
    const vb = s.shareGroup.buffers.get(10);
    const eb = s.shareGroup.buffers.get(11);
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3,
        { type: GL.UNSIGNED_SHORT, bufferOffset: 2 });
    const converted = [...vb.convertedAttributes.values()][0].gpuBuffer;
    assert.deepStrictEqual(Array.from(new Float32Array(converted.storage, 0, 3)),
        [1, 0, -1], "conventional signed-byte normals are normalized");
    const calls = log.draws[0].pass.calls;
    assert.ok(calls.some(c => c[0] === "vertexBuffer" && c[2] === vb.gpuBuffer));
    assert.ok(calls.some(c => c[0] === "vertexBuffer" && c[2] === converted));
    assert.ok(calls.some(c => c[0] === "indexBuffer" && c[1] === eb.gpuBuffer &&
        c[2] === "uint16" && c[3] === 2));
    const writes = log.bufferWrites.length;
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3,
        { type: GL.UNSIGNED_SHORT, bufferOffset: 2 });
    // Constant current attributes still have a tiny per-draw instance upload.
    assert.ok(log.bufferWrites.slice(writes).every(w =>
        w.buffer === executor.vertexRing && w.size <= 32));
    assert.strictEqual(log.bufferWrites.filter(w => w.buffer === converted).length, 1);
});

test("VBO and direct EBO mutations preserve already encoded draw snapshots", () => {
    const { executor } = newExecutor();
    normalVBOScene(executor);
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3,
        { type: GL.UNSIGNED_SHORT, bufferOffset: 2 });
    const vb = executor.current.shareGroup.buffers.get(10);
    const eb = executor.current.shareGroup.buffers.get(11);
    const oldNormal = [...vb.convertedAttributes.values()][0].gpuBuffer;
    const oldIndex = eb.gpuBuffer;
    executor.bufferSubData(GL.ARRAY_BUFFER, 12, new Uint8Array([0, 127, 0]));
    executor.bufferSubData(GL.ELEMENT_ARRAY_BUFFER, 2,
        new Uint8Array(new Uint16Array([2, 1, 0]).buffer));
    assert.notStrictEqual(oldIndex, eb.gpuBuffer);
    assert.deepStrictEqual(Array.from(new Uint16Array(oldIndex.storage, 2, 3)), [0, 1, 2]);
    assert.strictEqual(oldNormal.destroyed, false);
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3,
        { type: GL.UNSIGNED_SHORT, bufferOffset: 2 });
    const nextNormal = [...vb.convertedAttributes.values()][0].gpuBuffer;
    assert.notStrictEqual(oldNormal, nextNormal);
    assert.deepStrictEqual(Array.from(new Float32Array(nextNormal.storage, 0, 3)), [0, 1, 0]);
    executor.flushFrame();
    assert.strictEqual(oldNormal.destroyed, true);
    assert.strictEqual(oldIndex.destroyed, true);
    run(executor, new GLStream().names(GLFN.DELETE_BUFFERS, [10]));
    assert.strictEqual(executor.convertedVertexBytes, 0);
    assert.strictEqual(executor.convertedVertexCache.size, 0);
});

test("conversion keys include normalization and component defaults and reset releases them", () => {
    const { executor } = newExecutor();
    normalVBOScene(executor);
    const buffer = executor.current.shareGroup.buffers.get(10);
    const array = executor.current.arrays.normal;
    const a = executor.convertVertexAttribute(buffer, array, 4, true);
    const b = executor.convertVertexAttribute(buffer, array, 3, false);
    assert.deepStrictEqual(Array.from(new Float32Array(a.storage, 0, 4)), [1, 0, -1, 1]);
    assert.deepStrictEqual(Array.from(new Float32Array(b.storage, 0, 3)), [127, 0, -127]);
    executor.resetForReplay();
    assert.strictEqual(a.destroyed, true);
    assert.strictEqual(b.destroyed, true);
    assert.strictEqual(executor.convertedVertexBytes, 0);
});

test("uint32 list indices are direct while strips and polygon edges retain CPU indices", () => {
    const { executor } = newExecutor();
    normalVBOScene(executor);
    executor.bufferData(GL.ELEMENT_ARRAY_BUFFER, 12, GL.STATIC_DRAW,
        new Uint8Array(new Uint32Array([0, 1, 2]).buffer));
    let request;
    executor.issueDraw = r => { request = r; };
    const info = { type: GL.UNSIGNED_INT, bufferOffset: 0 };
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3, info);
    assert.strictEqual(request.index.buffer, executor.bufferFor(GL.ELEMENT_ARRAY_BUFFER).gpuBuffer);
    assert.strictEqual(request.index.format, "uint32");
    executor.drawFromBuffers(GL.TRIANGLE_STRIP, 0, 3, info);
    assert.deepStrictEqual(Array.from(request.index.source), [0, 1, 2]);
    run(executor, new GLStream().call("POLYGON_MODE", GL.FRONT_AND_BACK, GL.LINE));
    executor.drawFromBuffers(GL.TRIANGLES, 0, 3, info);
    assert.deepStrictEqual(Array.from(request.index.source), [0, 1, 2]);
});

test("uniform snapshots reuse unchanged bytes without overwriting earlier draws", () => {
    const { executor, log } = newExecutor();
    const values = new Uint8Array([1, 2, 3, 4]);
    const a = executor.writeUniformSnapshot("test", values);
    assert.strictEqual(executor.writeUniformSnapshot("test", values), a);
    assert.strictEqual(log.bufferWrites.length, 1);
    values[0] = 9;
    const b = executor.writeUniformSnapshot("test", values);
    assert.notStrictEqual(a.offset, b.offset);
    assert.strictEqual(new Uint8Array(a.buffer.storage)[a.offset], 1);
    assert.strictEqual(new Uint8Array(b.buffer.storage)[b.offset], 9);
    executor.finishFrame(false);
    const writes = log.bufferWrites.length;
    executor.writeUniformSnapshot("test", values);
    assert.strictEqual(log.bufferWrites.length, writes + 1,
        "rewound ring slices are never reused from the preceding frame");
});

test("bind group cache keys include pipeline, resource identity and buffer offset", () => {
    const { executor, log, host } = newExecutor();
    const descriptor = { vertex: { module: { code: "@group(1) @binding(0)" } } };
    const a = host.device.createRenderPipeline(descriptor);
    const b = host.device.createRenderPipeline(descriptor);
    const entries = offset => [{ binding: 0, resource: {
        buffer: executor.uniformRing, offset, size: 256,
    } }];
    const first = executor.cachedBindGroup(a, 1, entries(0));
    assert.strictEqual(executor.cachedBindGroup(a, 1, entries(0)), first);
    assert.notStrictEqual(executor.cachedBindGroup(a, 1, entries(256)), first);
    assert.notStrictEqual(executor.cachedBindGroup(b, 1, entries(0)), first);
    assert.strictEqual(log.bindGroups.length, 3);
});

test("inactive uniform blocks allocate and upload nothing", () => {
    const { executor, log, host } = newExecutor();
    run(executor, new GLStream().makeCurrent(1, 0, 0, 64, 64));
    const pipeline = host.device.createRenderPipeline({});
    pipeline.glActiveBindings = new Set();
    const shaders = { kind: "ff", stateFields: [], textures: [],
        wgslVertex: "", wgslFragment: "" };
    const writes = log.bufferWrites.length;
    assert.deepStrictEqual(executor.buildBindGroups(pipeline, shaders), []);
    assert.strictEqual(log.bufferWrites.length, writes);
    assert.strictEqual(executor.uniformCursor, 0);
});

/* ---- report ---- */

(async () => {
    for (const [name, fn] of asyncTests) {
        try {
            await fn();
            ++passed;
        } catch (error) {
            failures.push([name, error]);
        }
    }
    for (const [name, error] of failures)
        console.error("FAIL: " + name + "\n    " + (error && error.message));
    console.log(passed + " passed, " + failures.length + " failed");
    process.exit(failures.length ? 1 : 0);
})();
                                                                         source/v64/tests/glbridge/gl_fake_gpu.js                                                            0000644 0000000 0000000 00000024655 00000000000 015422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A minimal fake WebGPU device for the OpenGL executor's Node tests.
//
// It records what was asked of it rather than rendering: the point of the
// executor suite is to check that a GL command stream produces the right
// pipeline state, the right vertex layout and the right bind groups, none of
// which needs a GPU. The browser suites cover what pixels come out.

"use strict";

class FakeBuffer {
    constructor(descriptor) {
        this.descriptor = descriptor;
        this.size = descriptor.size;
        this.destroyed = false;
        this.writes = [];
        // Persistent, so a test can seed what a readback will find -- a fresh
        // buffer per getMappedRange would make every mapped result zero and
        // hide the difference between "read a zero" and "read nothing".
        this.storage = new ArrayBuffer(descriptor.size);
    }
    destroy() { this.destroyed = true; }
    mapAsync() { return Promise.resolve(); }
    getMappedRange() { return this.storage; }
    unmap() {}
}

class FakeTexture {
    constructor(descriptor) {
        this.descriptor = descriptor;
        this.destroyed = false;
        this.views = [];
    }
    createView(options) {
        const view = { texture: this, options: options || {} };
        this.views.push(view);
        return view;
    }
    destroy() { this.destroyed = true; }
}

class FakeRenderPass {
    constructor(descriptor, log) {
        this.descriptor = descriptor;
        this.log = log;
        this.ended = false;
        log.passes.push(this);
        this.calls = [];
    }
    checkOpen() {
        if (this.ended) throw new Error("render pass is already ended");
    }
    setPipeline(pipeline) { this.checkOpen(); this.pipeline = pipeline; this.calls.push(["pipeline", pipeline]); }
    setBindGroup(index, group) { this.calls.push(["bindGroup", index, group]); }
    setVertexBuffer(slot, buffer, offset) {
        this.calls.push(["vertexBuffer", slot, buffer, offset]);
    }
    setIndexBuffer(buffer, format, offset) {
        this.calls.push(["indexBuffer", buffer, format, offset]);
    }
    setViewport(...args) { this.viewport = args; }
    setScissorRect(...args) { this.scissor = args; }
    setStencilReference(value) { this.stencilReference = value; }
    setBlendConstant(value) { this.blendConstant = value; }
    beginOcclusionQuery(index) {
        this.checkOpen();
        if (!this.descriptor.occlusionQuerySet || this.activeQuery !== undefined)
            throw new Error("invalid occlusion query begin");
        this.usedQueries = this.usedQueries || new Set();
        if (this.usedQueries.has(index)) throw new Error("query slot reused in one pass");
        this.usedQueries.add(index);
        this.activeQuery = index;
        this.calls.push(["beginQuery", index]);
    }
    endOcclusionQuery() {
        this.checkOpen();
        if (this.activeQuery === undefined) throw new Error("no occlusion query is active");
        this.activeQuery = undefined;
        this.calls.push(["endQuery"]);
    }
    draw(count, instances, first) {
        this.checkOpen();
        this.log.draws.push({ pass: this, count, instances, first,
                              pipeline: this.pipeline });
        this.calls.push(["draw", count]);
    }
    drawIndexed(count, instances, firstIndex, baseVertex) {
        this.checkOpen();
        this.log.draws.push({ pass: this, count, instances, firstIndex,
                              baseVertex, indexed: true, pipeline: this.pipeline });
        this.calls.push(["drawIndexed", count]);
    }
    end() {
        this.checkOpen();
        if (this.activeQuery !== undefined) throw new Error("incomplete occlusion query");
        this.ended = true;
    }
}

class FakeEncoder {
    constructor(log) { this.log = log; this.copies = []; }
    beginRenderPass(descriptor) {
        const attachment = descriptor.depthStencilAttachment;
        if (attachment) {
            const format = attachment.view && attachment.view.texture &&
                attachment.view.texture.descriptor.format;
            if (format && format.indexOf("stencil") < 0 &&
                    ("stencilLoadOp" in attachment ||
                     "stencilStoreOp" in attachment ||
                     "stencilClearValue" in attachment))
                throw new Error("stencil operations require a stencil aspect");
        }
        return new FakeRenderPass(descriptor, this.log);
    }
    copyTextureToTexture(...args) { this.copies.push(["t2t", ...args]); }
    copyTextureToBuffer(...args) { this.copies.push(["t2b", ...args]); }
    copyBufferToBuffer(...args) { this.copies.push(["b2b", ...args]); }
    resolveQuerySet(querySet, first, count, destination, offset) {
        this.log.queryResolves.push({ querySet, first, count, destination, offset });
        this.copies.push(["resolve", querySet, first, count]);
    }
    finish() { return { encoder: this }; }
}

class FakeDevice {
    constructor(log) {
        this.log = log;
        this.features = new Set(["texture-compression-bc"]);
        this.limits = {
            maxTextureDimension2D: 8192, maxTextureDimension3D: 2048,
            maxColorAttachments: 8, maxVertexBuffers: 8,
            maxVertexAttributes: 16, maxBindGroups: 4,
        };
        this.lost = new Promise(() => {});
        this.queue = {
            writeBuffer: (buffer, offset, data, dataOffset, size) => {
                log.bufferWrites.push({ buffer, offset, size });
                const elementBytes = data.BYTES_PER_ELEMENT || 1;
                const start = (dataOffset || 0) * elementBytes;
                const length = size === undefined ? data.byteLength - start :
                    size * elementBytes;
                const bytes = new Uint8Array(data.buffer || data,
                    (data.byteOffset || 0) + start, length);
                new Uint8Array(buffer.storage).set(bytes, offset);
            },
            writeTexture: (destination, data, layout, size) => {
                const format = destination.texture &&
                    destination.texture.descriptor.format || "";
                if (/^bc\d-/.test(format)) {
                    if ((size.width & 3) || (size.height & 3))
                        throw new Error("compressed copies require whole 4x4 blocks");
                    const blockBytes = format.indexOf("bc1-") === 0 ? 8 : 16;
                    const required = (size.width >> 2) * (size.height >> 2) *
                        (size.depthOrArrayLayers || 1) * blockBytes;
                    if (data.byteLength < required)
                        throw new Error("compressed texture upload is truncated");
                }
                log.textureWrites.push({ destination, layout, size,
                                         byteLength: data.byteLength });
            },
            submit: buffers => { log.submits.push(buffers); },
            onSubmittedWorkDone: () => Promise.resolve(),
        };
    }
    createBuffer(descriptor) {
        const buffer = new FakeBuffer(descriptor);
        this.log.buffers.push(buffer);
        return buffer;
    }
    createTexture(descriptor) {
        if (/^bc\d-/.test(descriptor.format || "") &&
                (descriptor.usage & 0x10))
            throw new Error("compressed textures cannot be render attachments");
        const texture = new FakeTexture(descriptor);
        this.log.textures.push(texture);
        return texture;
    }
    createSampler(descriptor) {
        const sampler = { descriptor };
        this.log.samplers.push(sampler);
        return sampler;
    }
    createShaderModule(descriptor) {
        const module = { code: descriptor.code };
        this.log.modules.push(module);
        return module;
    }
    createRenderPipeline(descriptor) {
        const pipeline = {
            descriptor,
            getBindGroupLayout: index => {
                const code = (descriptor.vertex && descriptor.vertex.module.code || "") +
                    "\n" + (descriptor.fragment &&
                        descriptor.fragment.module.code || "");
                const bindings = new Set();
                const expression = /@group\((\d+)\)\s+@binding\((\d+)\)/g;
                for (const match of code.matchAll(expression))
                    if (Number(match[1]) === index) bindings.add(Number(match[2]));
                if (!bindings.size)
                    throw new Error("no bind group layout at index " + index);
                return { index, bindings };
            },
        };
        this.log.pipelines.push(pipeline);
        return pipeline;
    }
    createBindGroup(descriptor) {
        if (descriptor.layout && descriptor.layout.bindings) {
            for (const entry of descriptor.entries)
                if (!descriptor.layout.bindings.has(entry.binding))
                    throw new Error("binding " + entry.binding +
                        " is not declared by group " + descriptor.layout.index);
        }
        const group = { descriptor };
        this.log.bindGroups.push(group);
        return group;
    }
    createCommandEncoder() {
        const encoder = new FakeEncoder(this.log);
        this.log.encoders.push(encoder);
        return encoder;
    }
    createQuerySet(descriptor) {
        const set = { descriptor };
        this.log.querySets.push(set);
        return set;
    }
}

function createFakeHost(canvas) {
    const log = {
        buffers: [], textures: [], samplers: [], modules: [], pipelines: [],
        bindGroups: [], encoders: [], passes: [], draws: [],
        bufferWrites: [], textureWrites: [], submits: [],
        querySets: [], queryResolves: [],
        presented: 0,
    };
    const device = new FakeDevice(log);
    const host = {
        canvas: canvas || null,
        device,
        format: "bgra8unorm",
        limits: device.limits,
        deviceFeatures: { bc: true, float32Filterable: true,
                          float32Blendable: false, timestampQuery: false,
                          depthClipControl: false, clipDistances: false },
        context: {
            configure() {},
            getCurrentTexture() {
                ++log.presented;
                return new FakeTexture({ label: "swapchain" });
            },
        },
        initialize() { return Promise.resolve(host); },
        onDeviceLost() { return () => {}; },
        claimPresenter() { return 1; },
        canPresent(token) { return token === 1; },
        releasePresenter() {},
        resizeCanvas() { return false; },
    };
    return { host, log, device };
}

module.exports = { createFakeHost, FakeDevice, FakeTexture, FakeBuffer };
                                                                                   source/v64/tests/glbridge/gl_fixed_function_wgsl_test.js                                            0000644 0000000 0000000 00000041565 00000000000 020737  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unit tests for glbridge/gl-webgpu/gl_fixed_function.js -- the OpenGL fixed
// pipeline generated as WGSL.
//
// Two things are checked. First, that a signature produces the code the GL
// spec calls for: the texture environment table, the lighting equation's
// terms, fog, texgen. Second, that the result is WGSL a compiler accepts --
// through `naga` when it is available, because a generator that emits
// plausible-looking invalid code fails in the browser and nowhere else.

"use strict";

const assert = require("assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync, execFileSync } = require("child_process");
const ff = require("../../src/browser/glbridge/gl-webgpu/gl_fixed_function.js");

function findNaga() {
    if (process.env.GL_NAGA) return process.env.GL_NAGA;
    if (spawnSync("naga", ["--version"], { encoding: "utf8" }).status === 0)
        return "naga";
    const cargo = path.join(os.homedir(), ".cargo", "bin", "naga");
    return fs.existsSync(cargo) ? cargo : null;
}

const naga = findNaga();
const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), "glwg-ff-"));
let passed = 0;
const failures = [];

function test(name, fn) {
    try { fn(); ++passed; } catch (error) { failures.push([name, error]); }
}

function generate(signature) {
    const result = ff.generate(signature);
    if (naga) {
        for (const [suffix, wgsl] of [["vert", result.wgslVertex],
                ["frag", result.wgslFragment]]) {
            const file = path.join(outputDir,
                (signature._name || "case") + "." + suffix + ".wgsl");
            fs.writeFileSync(file, wgsl);
            try {
                execFileSync(naga, [file], { stdio: "pipe" });
            } catch (error) {
                throw new Error("naga rejected the " + suffix + " shader:\n" +
                    String(error.stderr || error.stdout || error).slice(0, 700));
            }
        }
    }
    return result;
}

const POSITION_ONLY = { attributes: { position: { components: 3 } } };

function textured(env, format, extra) {
    return Object.assign({
        attributes: { position: { components: 3 }, color: true,
                      texCoord: [{ components: 2 }] },
        texture: [{ enabled: true, target: "2D", format: format || "RGBA", env }],
    }, extra || {});
}

/* ---- the shape of the generated code ---- */

test("a bare signature transforms and nothing else", () => {
    const result = generate(Object.assign({ _name: "minimal" }, POSITION_ONLY));
    assert.deepStrictEqual(result.stateFields, ["mvp"],
        "a untextured, unlit draw needs one matrix and no more");
    assert.strictEqual(result.attributes.length, 1);
    assert.strictEqual(result.textures.length, 0);
    assert.ok(result.wgslVertex.indexOf("clip.y = -clip.y;") >= 0);
    assert.ok(result.wgslVertex.indexOf("clip.z = (clip.z + clip.w) * 0.5;") >= 0);
});

test("attributes sit at their historical locations", () => {
    const result = generate({
        _name: "attributes",
        attributes: { position: { components: 4 }, normal: true, color: true,
                      secondaryColor: true, fogCoord: true,
                      texCoord: [{ components: 2 }, null, { components: 3 }] },
        texture: [{ enabled: true, target: "2D", env: { mode: "MODULATE" } },
                  { enabled: false },
                  { enabled: true, target: "3D", env: { mode: "MODULATE" } }],
        fog: { enabled: true, mode: "linear", coordSource: "coord" },
    });
    const byName = new Map(result.attributes.map(a => [a.name, a.location]));
    assert.strictEqual(byName.get("position"), 0);
    assert.strictEqual(byName.get("normal"), 2);
    assert.strictEqual(byName.get("color"), 3);
    assert.strictEqual(byName.get("secondaryColor"), 4);
    assert.strictEqual(byName.get("fogCoord"), 5);
    assert.strictEqual(byName.get("texCoord0"), 8);
    assert.strictEqual(byName.get("texCoord2"), 10);
});

test("an ARB vertex program can feed the fixed multitexture fragment stage", () => {
    const result = generate({
        _name: "arb_vertex_fixed_fragment",
        varyingInterface: "arb",
        attributes: { position: { components: 4 }, color: true,
                      texCoord: [{ components: 4 }, { components: 4 }] },
        texture: [
            { enabled: true, target: "2D", env: { mode: "MODULATE" } },
            { enabled: true, target: "2D", env: { mode: "ADD" } },
        ],
    });
    const fragment = result.wgslFragment;
    assert.ok(fragment.includes("@location(0) v0 : vec4<f32>"),
        "ARB result.color is the primary fixed-function colour");
    assert.ok(fragment.includes("@location(3) v3 : vec4<f32>"),
        "ARB result.texcoord[0] keeps its compatibility location");
    assert.ok(fragment.includes("@location(4) v4 : vec4<f32>"),
        "ARB result.texcoord[1] keeps its compatibility location");
    assert.ok(!fragment.includes("@location(1) v1 : vec4<f32>"),
        "unused compatibility outputs are not required from the vertex stage");
});

/* ---- texture environment, GL 1.5 table 3.22 ---- */

test("GL_REPLACE on an RGB texture leaves alpha alone", () => {
    const result = generate(textured({ mode: "REPLACE" }, "RGB"));
    result.signature._name = "replace_rgb";
    assert.ok(result.wgslFragment.indexOf(
        "frag = vec4<f32>(tex0.rgb, frag.a);") >= 0, result.wgslFragment);
});

test("GL_REPLACE on an RGBA texture replaces both", () => {
    const result = generate(textured({ mode: "REPLACE" }, "RGBA"));
    assert.ok(result.wgslFragment.indexOf("frag = tex0;") >= 0);
});

test("GL_MODULATE on an ALPHA texture leaves RGB alone", () => {
    const result = generate(textured({ mode: "MODULATE" }, "ALPHA"));
    assert.ok(result.wgslFragment.indexOf(
        "frag = vec4<f32>(frag.rgb, frag.a * tex0.a);") >= 0,
        result.wgslFragment);
});

test("GL_DECAL on RGBA interpolates by the texture's alpha", () => {
    const result = generate(textured({ mode: "DECAL" }, "RGBA"));
    assert.ok(result.wgslFragment.indexOf("mix(frag.rgb, tex0.rgb, tex0.a)") >= 0);
});

test("GL_DECAL on a LUMINANCE texture is documented as undefined", () => {
    const result = generate(textured({ mode: "DECAL" }, "LUMINANCE"));
    assert.ok(result.wgslFragment.indexOf("GL_DECAL is undefined") >= 0);
});

test("GL_BLEND on INTENSITY blends alpha as well as colour", () => {
    const result = generate(textured({ mode: "BLEND" }, "INTENSITY"));
    assert.ok(result.wgslFragment.indexOf("mix(frag.a,") >= 0,
        "intensity is the one base format whose alpha is blended too");
});

test("GL_COMBINE DOT3_RGBA drives alpha from the dot product", () => {
    const result = generate(textured({
        mode: "COMBINE", combineRGB: "DOT3_RGBA", combineAlpha: "REPLACE",
        srcRGB: ["TEXTURE", "PRIMARY_COLOR", "CONSTANT"],
        operandRGB: ["SRC_COLOR", "SRC_COLOR", "SRC_ALPHA"],
        srcAlpha: ["TEXTURE", "PREVIOUS", "CONSTANT"],
        operandAlpha: ["SRC_ALPHA", "SRC_ALPHA", "SRC_ALPHA"],
        rgbScale: 1, alphaScale: 1,
    }));
    assert.ok(result.wgslFragment.indexOf("4.0 * dot(") >= 0);
    assert.ok(result.wgslFragment.indexOf("let combinedA = clamp((dot3)") >= 0,
        result.wgslFragment);
});

test("GL_COMBINE crossbar reads another unit's sample", () => {
    const result = generate({
        _name: "crossbar",
        attributes: { position: { components: 3 }, color: true,
                      texCoord: [{ components: 2 }, { components: 2 }] },
        texture: [
            { enabled: true, target: "2D", env: { mode: "MODULATE" } },
            { enabled: true, target: "2D", env: {
                mode: "COMBINE", combineRGB: "INTERPOLATE",
                combineAlpha: "MODULATE",
                srcRGB: ["TEXTURE0", "PREVIOUS", "CONSTANT"],
                operandRGB: ["SRC_COLOR", "SRC_COLOR", "SRC_ALPHA"],
                srcAlpha: ["TEXTURE", "PREVIOUS", "CONSTANT"],
                operandAlpha: ["SRC_ALPHA", "SRC_ALPHA", "SRC_ALPHA"],
                rgbScale: 4, alphaScale: 2 } },
        ],
    });
    assert.ok(result.wgslFragment.indexOf("(tex0).rgb") >= 0,
        "stage 1 reads stage 0's sample, so both are taken before the chain runs");
    assert.ok(result.wgslFragment.indexOf("* 4.0") >= 0, "RGB_SCALE is applied");
});

/* ---- lighting ---- */

test("the lighting equation carries every term the spec lists", () => {
    const result = generate({
        _name: "lighting",
        attributes: { position: { components: 3 }, normal: true, color: true },
        lighting: {
            enabled: true, twoSide: true, localViewer: true,
            separateSpecular: true, normalMode: "normalize",
            colorMaterial: { enabled: true, face: "FRONT_AND_BACK",
                             mode: "AMBIENT_AND_DIFFUSE" },
            lights: [{ enabled: true, positional: true, spot: true },
                     { enabled: true, positional: false }],
        },
    });
    const vertex = result.wgslVertex;
    assert.ok(vertex.indexOf("constantAttenuation") >= 0, "attenuation");
    assert.ok(vertex.indexOf("spotCosCutoff") >= 0, "the spotlight cutoff");
    assert.ok(vertex.indexOf("spotExponent") >= 0, "the spotlight exponent");
    assert.ok(vertex.indexOf("normalize(-eyePos)") >= 0, "the local viewer");
    assert.ok(vertex.indexOf("backColor") >= 0, "the back face");
    assert.ok(vertex.indexOf("vertexColor.rgb * glState.lights[0].ambient.rgb") >= 0,
        "colour material replaces the tracked property");
    assert.ok(result.stateFields.indexOf("backMaterial") >= 0);
});

test("a directional light has no attenuation term", () => {
    const result = generate({
        _name: "directional",
        attributes: { position: { components: 3 }, normal: true },
        lighting: { enabled: true,
            lights: [{ enabled: true, positional: false }] },
    });
    assert.ok(result.wgslVertex.indexOf("var atten = 1.0;") >= 0);
    // The GLLight struct always declares the attenuation members; what matters
    // is that the generated body never reads them for a directional light.
    const body = result.wgslVertex.slice(result.wgslVertex.indexOf("@vertex"));
    assert.ok(body.indexOf("constantAttenuation") < 0, body);
});

test("an unlit signature asks for no lighting state", () => {
    const result = generate(Object.assign({ _name: "unlit" }, POSITION_ONLY));
    assert.ok(result.stateFields.indexOf("lights") < 0);
    assert.ok(result.stateFields.indexOf("frontMaterial") < 0);
});

/* ---- fog, texgen, alpha test, clipping, points ---- */

test("each fog mode emits its own factor", () => {
    for (const [mode, needle] of [["linear", "glState.fogParams.w"],
            ["exp", "exp(-glState.fogParams.x"], ["exp2", "fogArg * fogArg"]]) {
        const result = generate({
            _name: "fog_" + mode,
            attributes: { position: { components: 3 } },
            fog: { enabled: true, mode, coordSource: "depth" },
        });
        assert.ok(result.wgslFragment.indexOf(needle) >= 0,
            mode + ": " + result.wgslFragment);
    }
});

test("texgen builds each coordinate separately", () => {
    const result = generate({
        _name: "texgen",
        attributes: { position: { components: 4 }, normal: true },
        texture: [{ enabled: true, target: "2D", matrix: true,
            texGen: ["OBJECT", "EYE", "SPHERE", null],
            env: { mode: "MODULATE" } }],
    });
    const vertex = result.wgslVertex;
    assert.ok(vertex.indexOf("dot(objectPos, glState.texGenPlanes[0])") >= 0,
        "the object plane for S is slot 0 of the unit");
    assert.ok(vertex.indexOf("glState.texGenPlanes[5]") >= 0,
        "the eye plane for T is slot 4 + 1");
    assert.ok(vertex.indexOf("sphereM0") >= 0);
    assert.ok(vertex.indexOf("glState.textureMatrix[0] * tc0") >= 0);
});

test("alpha test and clip planes both discard", () => {
    const result = generate({
        _name: "discard",
        attributes: { position: { components: 3 } },
        alphaTest: "gequal", clipPlaneCount: 2,
    });
    assert.ok(result.wgslFragment.indexOf(
        "if (!(frag.a >= glState.alphaRef.x)) { discard; }") >= 0);
    assert.ok(result.wgslFragment.indexOf(
        "if (any(fin.clipDist < vec4<f32>(0.0))) { discard; }") >= 0);
    assert.ok(result.usesDiscard);
});

test("a point-sprite signature expands the point in clip space", () => {
    const result = generate({
        _name: "pointsprite",
        attributes: { position: { components: 3 }, color: true },
        pointSprite: true,
    });
    assert.ok(result.wgslVertex.indexOf("vin.corner.x * ptSize") >= 0);
    assert.ok(result.wgslVertex.indexOf("0.5 - vin.corner.y * 0.5") >= 0,
        "GL_POINT_SPRITE_COORD_ORIGIN defaults to GL_UPPER_LEFT");
    assert.ok(result.attributes.some(a => a.name === "corner" && a.location === 7));
});

test("point sprites honour a lower-left coordinate origin", () => {
    const result = generate({
        _name: "pointsprite_lower_left",
        attributes: { position: { components: 3 }, color: true },
        pointSprite: true,
        pointCoordLowerLeft: true,
    });
    assert.ok(result.wgslVertex.indexOf(
        "vin.corner.y * 0.5 + 0.5") >= 0);
});

test("polygon stipple tests the 32 by 32 pattern in fragment coordinates", () => {
    const result = generate({
        _name: "polygon_stipple",
        attributes: { position: { components: 3 }, color: true },
        polygonStipple: true,
    });
    assert.ok(result.stateFields.includes("polygonStipple"));
    assert.ok(result.wgslFragment.indexOf("stippleByteIndex") >= 0);
    assert.ok(result.wgslFragment.indexOf("stippleBit") >= 0);
});

test("colour logic XOR is emitted as an attachment-sampling bit operation", () => {
    const result = generate({
        _name: "logic_xor",
        attributes: { position: { components: 3 }, color: true },
        logicOp: 0x1506,
    });
    assert.ok(result.wgslFragment.includes(
        "@group(3) @binding(0) var glLogicTarget0"));
    assert.ok(result.wgslFragment.includes("let r = (s ^ d)"));
    assert.ok(result.wgslFragment.includes("glApplyLogic(frag"));
});

test("point-sprite coordinate replacement samples gl_PointCoord", () => {
    const result = generate({
        _name: "point_coord_replace",
        attributes: { position: { components: 3 },
            texCoord: [{ components: 4 }] },
        pointSprite: true,
        texture: [{ enabled: true, target: "2D", format: "RGBA",
            texGen: [null, null, null, null],
            env: { mode: "REPLACE", coordReplace: true } }],
    });
    assert.ok(result.wgslFragment.indexOf(
        "vec4<f32>(fin.pointCoord, 0.0, 1.0)") >= 0,
    "GL_COORD_REPLACE uses the generated point coordinate");
});

test("eight textured units still fit the varying budget", () => {
    const result = generate({
        _name: "eight_units",
        attributes: { position: { components: 3 }, color: true,
            texCoord: Array.from({ length: 8 }, () => ({ components: 2 })) },
        texture: Array.from({ length: 8 }, () => ({ enabled: true,
            target: "2D", env: { mode: "MODULATE" } })),
    });
    assert.ok(result.varyingSlots <= 16, result.varyingSlots);
    assert.strictEqual(result.textures.length, 8);
});

/* ---- the signature is the cache key ---- */

test("every field that changes the code changes the key", () => {
    const base = { attributes: { position: { components: 3 }, color: true } };
    const key = ff.signatureKey(base);
    const variations = [
        { attributes: { position: { components: 3 }, color: true, normal: true } },
        { attributes: base.attributes, fog: { enabled: true, mode: "exp" } },
        { attributes: base.attributes, alphaTest: "less" },
        { attributes: base.attributes, clipPlaneCount: 1 },
        { attributes: base.attributes, pointSprite: true },
        { attributes: base.attributes, polygonStipple: true },
        { attributes: base.attributes, flatShading: true },
        { attributes: base.attributes, colorTargets: 2 },
        { attributes: base.attributes, lighting: { enabled: true,
            lights: [{ enabled: true }] } },
        { attributes: base.attributes, texture: [{ enabled: true, target: "2D",
            env: { mode: "MODULATE" } }] },
    ];
    for (const variation of variations)
        assert.notStrictEqual(ff.signatureKey(variation), key,
            "a state that changes the shader must change the signature");
});

test("the same signature produces the same key regardless of field order", () => {
    const a = { attributes: { color: true, position: { components: 3 } },
                alphaTest: "less" };
    const b = { alphaTest: "less",
                attributes: { position: { components: 3 }, color: true } };
    assert.strictEqual(ff.signatureKey(a), ff.signatureKey(b));
});

for (const [name, error] of failures)
    console.error("FAIL: " + name + "\n    " + (error && error.message));
console.log(passed + " passed, " + failures.length + " failed" +
    (naga ? " (WGSL validated with naga)" : " (naga absent; WGSL not validated)"));
fs.rmSync(outputDir, { recursive: true, force: true });
process.exit(failures.length ? 1 : 0);
                                                                                                                                           source/v64/tests/glbridge/gl_multipass_browser_runner.js                                            0000644 0000000 0000000 00000007407 00000000000 021012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Real GPU test, isolated from the game page and the user's browser profile.
// GL_CHROME can select a Chromium executable on non-macOS hosts; GL_TIMEOUT_MS
// the time a page has (60 s). A page can save files (screenshots) by POSTing
// them to /__test_file?name=<name>: they land in build/browser-test-output/.
"use strict";
const http = require("http"), fs = require("fs"), path = require("path");
const { spawn } = require("child_process");
const root = path.resolve(__dirname, "../..");
const profile = fs.mkdtempSync(path.join(require("os").tmpdir(), "gl-multipass-"));
let browser, timeout;
const server = http.createServer((req, res) => {
    if (req.method === "POST" && req.url.startsWith("/__test_file?")) {
        const name = path.basename(new URL(req.url, "http://localhost").searchParams.get("name") || "file");
        const chunks = [];
        req.on("data", data => chunks.push(data));
        req.on("end", () => {
            const directory = path.join(root, "build/browser-test-output");
            fs.mkdirSync(directory, { recursive: true });
            fs.writeFileSync(path.join(directory, name), Buffer.concat(chunks));
            res.end("OK");
        });
        return;
    }
    if (req.method === "POST" && req.url === "/__test_result") {
        let body = "";
        req.on("data", data => { body += data; });
        req.on("end", () => {
            res.end("OK");
            console.log(body);
            finish(JSON.parse(body).status === "PASS" ? 0 : 1);
        });
        return;
    }
    const pathname = new URL(req.url, "http://localhost").pathname;
    const file = path.resolve(root, "." + pathname);
    if (!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; }
    fs.readFile(file, (error, data) => {
        if (error) { res.writeHead(404).end(); return; }
        res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" :
            /\.(js|mjs)$/.test(file) ? "text/javascript" : "text/html");
        if (file.endsWith(".html")) data = Buffer.concat([data, Buffer.from(`<script>
            const reporter = new MutationObserver(() => {
                const result = document.getElementById("result");
                const text = result && result.textContent || "";
                if (!/^(PASS|FAIL)\\b/.test(text)) return;
                reporter.disconnect();
                fetch("/__test_result", { method: "POST", body: JSON.stringify({
                    status: text.startsWith("PASS") ? "PASS" : "FAIL", details: text
                }) });
            });
            reporter.observe(document.body || document.documentElement, { subtree: true, childList: true, characterData: true });
        </script>`)]);
        res.end(data);
    });
});
function finish(code) {
    clearTimeout(timeout);
    if (browser) browser.kill();
    server.close();
    process.exitCode = code;
}
server.listen(0, "127.0.0.1", () => {
    const page = process.argv[2] || "gl_multipass_browser_test.html";
    const url = `http://127.0.0.1:${server.address().port}/tests/glbridge/${page}${page.includes("?") ? "&" : "?"}report=1`;
    browser = spawn(process.env.GL_CHROME ||
        "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--enable-unsafe-webgpu", "--no-first-run",
        "--no-default-browser-check", "--disable-background-networking",
        `--user-data-dir=${profile}`, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", data => { stderr = (stderr + data).slice(-4000); });
    browser.on("error", error => { console.error(error); finish(1); });
    timeout = setTimeout(() => {
        console.error("FAIL: real GPU test timed out\n" + stderr);
        finish(1);
    }, +process.env.GL_TIMEOUT_MS || 60000);
});
                                                                                                                                                                                                                                                         source/v64/tests/glbridge/gl_multipass_browser_test.html                                            0000644 0000000 0000000 00000033010 00000000000 020775  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GL multipass pixel regression</title>
<canvas id="gpu" width="128" height="128"></canvas>
<pre id="result">RUNNING</pre>
<script src="../../src/browser/glbridge/webgpu_host.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_constants.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_wire.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_state_layout.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_fixed_function.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_arb_program.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_executor.js"></script>
<script src="gl_stream_builder.js"></script>
<script>
(async () => {
    const { GLStream, GL, GLFN } = GLTestStream;
    const executor = new GLWebGPUExecutorModule.GLWebGPUExecutor(
        document.getElementById("gpu"));
    await executor.initialize();
    const device = executor.device;
    device.pushErrorScope("validation");
    const run = stream => executor.submit(stream.bytes(), {});
    run(new GLStream().makeCurrent(1, 0, 0, 128, 128));
    const position = "attribute vec4 vvertex; uniform mat4 camprojmatrix;";
    const transform = "gl_Position = camprojmatrix * vvertex;";
    const programs = [
        [position + "void main() {" + transform + "}", "void main() {}"],
        [position + "attribute vec4 vcolor; varying vec4 color;" +
            "void main() {" + transform + "color = vcolor;}",
            "varying vec4 color; void main() {gl_FragColor = color;}"],
        [position + "attribute vec4 vcolor; attribute vec3 vnormal; varying vec4 color;" +
            "void main() {" + transform + "color = vcolor * abs(vnormal.z);}",
            "varying vec4 color; void main() {gl_FragColor = color;}"],
    ];
    for (let i = 0; i < programs.length; ++i) {
        const name = i + 1, vs = 10 + i * 2, fs = vs + 1;
        run(new GLStream().call("CREATE_PROGRAM", name)
            .call("CREATE_SHADER", vs, GL.VERTEX_SHADER)
            .call("CREATE_SHADER", fs, GL.FRAGMENT_SHADER)
            .shaderSource(vs, programs[i][0]).shaderSource(fs, programs[i][1])
            .call("COMPILE_SHADER", vs).call("COMPILE_SHADER", fs)
            .call("ATTACH_SHADER", name, vs).call("ATTACH_SHADER", name, fs));
        const p = executor.current.shareGroup.programs.get(name);
        // Cube 2 binds position at 0 and color at 1 before linking.
        p.bindAttribLocations.set("vvertex", 0);
        p.bindAttribLocations.set("vcolor", 1);
        p.bindAttribLocations.set("vnormal", 2);
        run(new GLStream().call("LINK_PROGRAM", name));
        if (!p.linked) throw new Error(p.log);
    }
    const attributes = name => executor.current.shareGroup.programs.get(name)
        .link.reflection.attributes;
    const location = (name, attribute) => attributes(name)
        .find(a => a.name === attribute).location;
    const colorLocation = location(2, "vcolor");
    const vertices = [];
    // Large world coordinates and sloping planes stress depth equality after
    // cancellation in camprojmatrix * vvertex, as in Cube 2's world prepass.
    for (let i = 0; i < 12; ++i) {
        const d = 32 * (i + 1), s = d * 0.72;
        for (const [x, y, z] of [[-s,-s,-d], [s,-s,-d*1.1], [s,s,-d*1.1],
                [-s,-s,-d], [s,s,-d*1.1], [-s,s,-d]])
            vertices.push(4096 + x, 4096 + y, 4096 + z);
    }
    const data = new Float32Array(vertices);
    const colors = new Float32Array(vertices.length / 3 * 4);
    const normals = new Int8Array(colors.length);
    for (let i = 0; i < colors.length; i += 4) colors.set([0, 1, 0, 1], i);
    for (let i = 0; i < normals.length; i += 4) normals.set([0, 0, 127, 0], i);
    run(new GLStream().names(GLFN.GEN_BUFFERS, [1, 2, 3])
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 1)
        .bufferData(GL.ARRAY_BUFFER, data.byteLength, GL.STATIC_DRAW,
            new Uint8Array(data.buffer))
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 2)
        .bufferData(GL.ARRAY_BUFFER, colors.byteLength, GL.STATIC_DRAW,
            new Uint8Array(colors.buffer))
        .attribPointerVBO(colorLocation, 4, GL.FLOAT, false, 16, 0)
        .call("BIND_BUFFER", GL.ARRAY_BUFFER, 3)
        .bufferData(GL.ARRAY_BUFFER, normals.byteLength, GL.STATIC_DRAW,
            new Uint8Array(normals.buffer)));

    function draw(program, constantColor) {
        const vertexLocation = location(program, "vvertex");
        const stream = new GLStream().call("USE_PROGRAM", program)
            .call("BIND_BUFFER", GL.ARRAY_BUFFER, 1)
            .attribPointerVBO(vertexLocation, 3, GL.FLOAT, false, 12, 0)
            .call("ENABLE_VERTEX_ATTRIB_ARRAY", vertexLocation);
        if (program >= 2) {
            stream.call(constantColor ? "DISABLE_VERTEX_ATTRIB_ARRAY" :
                "ENABLE_VERTEX_ATTRIB_ARRAY", colorLocation)
                .call("VERTEX_ATTRIB4F", colorLocation, 0, 1, 0, 1);
        }
        if (program === 3) {
            stream.call("BIND_BUFFER", GL.ARRAY_BUFFER, 3)
                .attribPointerVBO(2, 3, GL.BYTE, true, 4, 0)
                .call("ENABLE_VERTEX_ATTRIB_ARRAY", 2);
        }
        run(stream.call("DRAW_ARRAYS_DIRECT", GL.TRIANGLES, 0, data.length / 3));
    }
    async function pixels(prepass, constantColor, eyeOffset, packed) {
        const n = 1, f = 100000, a = (f+n)/(n-f), b = 2*f*n/(n-f);
        const matrix = new Float32Array([1,0,0,0, 0,1,0,0, 0,0,a,-1,
            -4096-eyeOffset, -4096, b-a*4096, 4096]);
        for (const p of executor.current.shareGroup.programs.values()) {
            const u = p.uniformByName.get("camprojmatrix");
            p.uniformFloats.set(matrix, u.offsetBytes / 4);
        }
        run(new GLStream().call("CLEAR_COLOR", 0, 0, 0, 1)
            .call("CLEAR_DEPTH", 1).call("DEPTH_MASK", 1)
            .call("COLOR_MASK", 1, 1, 1, 1)
            .call("CLEAR", GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT)
            .call("ENABLE", GL.DEPTH_TEST).call("DEPTH_FUNC", GL.LESS));
        if (prepass) {
            run(new GLStream().call("COLOR_MASK", 0, 0, 0, 0));
            draw(1, false);
            run(new GLStream().call("COLOR_MASK", 1, 1, 1, 1)
                .call("DEPTH_MASK", 0).call("DEPTH_FUNC", GL.LEQUAL));
        }
        draw(packed ? 3 : 2, constantColor);
        executor.flushFrame();
        return readBack();
    }
    async function readBack() {
        const staging = device.createBuffer({ size: 128*128*4,
            usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
        const encoder = device.createCommandEncoder();
        encoder.copyTextureToBuffer({ texture: executor.backBuffer },
            { buffer: staging, bytesPerRow: 128*4 }, [128,128]);
        device.queue.submit([encoder.finish()]);
        await staging.mapAsync(GPUMapMode.READ);
        const result = new Uint8Array(staging.getMappedRange().slice(0));
        staging.unmap(); staging.destroy();
        return result;
    }
    let checkedPixels = 0;
    for (const packed of [false, true]) for (const eye of [0, 0.123, 3.17, -9.41]) {
        const reference = await pixels(false, false, eye, packed);
        if (!reference.some((v,i) => i % 4 === 1 && v > 128))
            throw new Error("reference scene is empty");
        for (const constant of [false, true]) {
            const actual = await pixels(true, constant, eye, packed);
            let mismatched = 0;
            for (let i=0; i<actual.length; i+=4)
                if (actual[i+1] !== reference[i+1]) ++mismatched;
            if (mismatched) throw new Error(JSON.stringify({ eye, packed, constant, mismatched }));
            checkedPixels += 128*128;
        }
    }
    // Force both rings to roll inside a GL query and during a quad draw.
    // This reproduces the game's 8 MiB boundary without loading a full map.
    const p = executor.current.shareGroup.programs.get(2);
    p.uniformFloats.set([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1],
        p.uniformByName.get("camprojmatrix").offsetBytes / 4);
    const quad = new Float32Array([-0.75,-0.75,0, 0.75,-0.75,0,
        0.75,0.75,0, -0.75,0.75,0]);
    const quadStream = () => new GLStream().drawArraysGL2(GL.QUADS, 4, {}, [
        { index: 0, enabled: true, size: 3, type: GL.FLOAT,
            data: new Uint8Array(quad.buffer) },
    ]);
    async function ringFrame(stress) {
        run(new GLStream().call("USE_PROGRAM", 2).call("DISABLE", GL.DEPTH_TEST)
            .call("COLOR_MASK", 1,1,1,1).call("CLEAR_COLOR", 0,0,0,1)
            .call("CLEAR", GL.COLOR_BUFFER_BIT)
            .call("VERTEX_ATTRIB4F", 1, 0,1,0,1));
        if (stress) {
            run(new GLStream().names(GLFN.GEN_QUERIES, [77])
                .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 77));
            // Four packed vec4 positions + vec4 colors exactly fill the page;
            // expanded indices need a new page. Force active uniforms to rotate too.
            executor.vertexCursor = executor.vertexCapacity - 128;
            executor.uniformCursor = executor.uniformCapacity;
        }
        run(quadStream());
        if (stress) {
            executor.endPass(); // resume without a submission
            run(quadStream());
            executor.flushFrame(); // resume across submissions
            run(quadStream().call("END_QUERY", GL.SAMPLES_PASSED));
        }
        executor.flushFrame();
        return readBack();
    }
    const plain = await ringFrame(false), wrapped = await ringFrame(true);
    if (!plain.some((v,i) => i % 4 === 1 && v > 128))
        throw new Error("ring reference is empty");
    if (plain.some((v,i) => v !== wrapped[i]))
        throw new Error("ring rollover changed rendered pixels");
    checkedPixels += 128*128;
    const query = executor.queries.get(77);
    const deadline = performance.now() + 5000;
    while (!query.ready && performance.now() < deadline)
        await new Promise(resolve => setTimeout(resolve, 5));
    if (!query.ready || !query.result) throw new Error("segmented visible query did not complete");

    // Compare compact client indices and native EBOs + cached byte3 normal
    // conversion against the same non-indexed reference, including sparse gaps.
    const litProgram = executor.current.shareGroup.programs.get(3);
    litProgram.uniformFloats.set([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1],
        litProgram.uniformByName.get("camprojmatrix").offsetBytes / 4);
    for (const slots of [[60000,60001,60002,60003], [60000,2,40000,9]]) {
        const positions = new Float32Array(60004 * 3);
        const normals = new Uint8Array(60004 * 4);
        for (let i = 0; i < 4; ++i) {
            positions.set(quad.subarray(i * 3, i * 3 + 3), slots[i] * 3);
            normals[slots[i] * 4 + 2] = 127;
        }
        const indices = new Uint16Array([slots[0], slots[1], slots[2],
            slots[0], slots[2], slots[3]]);
        for (const resident of [false, true]) {
            run(new GLStream().call("USE_PROGRAM", 3)
                .call("CLEAR", GL.COLOR_BUFFER_BIT)
                .call("DISABLE_VERTEX_ATTRIB_ARRAY", 1)
                .call("VERTEX_ATTRIB4F", 1, 0,1,0,1));
            if (resident) {
                run(new GLStream().call("BIND_BUFFER", GL.ARRAY_BUFFER, 90)
                    .bufferData(GL.ARRAY_BUFFER, positions.byteLength, GL.STATIC_DRAW,
                        new Uint8Array(positions.buffer))
                    .attribPointerVBO(0, 3, GL.FLOAT, false, 12, 0)
                    .call("ENABLE_VERTEX_ATTRIB_ARRAY", 0)
                    .call("BIND_BUFFER", GL.ARRAY_BUFFER, 91)
                    .bufferData(GL.ARRAY_BUFFER, normals.byteLength, GL.STATIC_DRAW, normals)
                    .attribPointerVBO(2, 3, GL.BYTE, true, 4, 0)
                    .call("ENABLE_VERTEX_ATTRIB_ARRAY", 2)
                    .call("BIND_BUFFER", GL.ELEMENT_ARRAY_BUFFER, 92)
                    .bufferData(GL.ELEMENT_ARRAY_BUFFER, indices.byteLength,
                        GL.STATIC_DRAW, new Uint8Array(indices.buffer))
                    .drawElementsDirect(GL.TRIANGLES, 6, GL.UNSIGNED_SHORT, 0)
                    .drawElementsDirect(GL.TRIANGLES, 6, GL.UNSIGNED_SHORT, 0));
            } else {
                run(new GLStream().drawElementsGL2(GL.TRIANGLES, indices,
                    GL.UNSIGNED_SHORT, {}, [
                        { index: 0, size: 3, type: GL.FLOAT,
                            data: new Uint8Array(positions.buffer) },
                        { index: 2, size: 3, type: GL.BYTE, stride: 4,
                            normalized: true, data: normals },
                    ]));
            }
            executor.flushFrame();
            const actual = await readBack();
            if (plain.some((v, i) => v !== actual[i]))
                throw new Error("indexed conversion pixels differ: " + JSON.stringify({ slots, resident }));
            checkedPixels += 128*128;
        }
    }
    const error = await device.popErrorScope();
    if (error || executor.getStats().refusals) throw new Error(
        error ? error.message : "executor refused a draw");
    const info = executor.host.adapter.info;
    return { status: "PASS", checkedPixels,
        adapter: { vendor: info.vendor, architecture: info.architecture },
        stats: executor.getStats() };
})().catch(error => ({ status: "FAIL", error: error.stack })).then(async result => {
    document.getElementById("result").textContent = JSON.stringify(result);
    document.title = result.status + " GL multipass pixel regression";
    if (new URLSearchParams(location.search).has("report"))
        await fetch("/__test_result", { method: "POST", body: JSON.stringify(result) });
});
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/glbridge/gl_shader_translator_test.js                                              0000644 0000000 0000000 00000040333 00000000000 020406  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unit tests for glbridge/gl-webgpu/gl_shader_translator.js -- the GLSL
// 1.10/1.20 front end.
//
// These assert on translation *structure*: which types an expression gets,
// where an implicit conversion was inserted, which uniforms and varyings a
// program exposes, and where glUniform* has to write. Whether the WGSL is
// something a compiler accepts is gl_shader_wgsl_validation_test.js's job --
// the split matters because a shader can be structurally right and still not
// compile, and the two failures need different fixes.

"use strict";

const assert = require("assert");
const t = require("../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js");

let passed = 0;
const failures = [];
function test(name, fn) {
    try { fn(); ++passed; } catch (error) { failures.push([name, error]); }
}

function compile(source, stage, options) {
    return t.compileShader(source, stage || "fragment", options || {});
}

function link(vsSource, fsSource, options) {
    const vs = compile(vsSource, "vertex");
    const fs = compile(fsSource, "fragment");
    assert.ok(vs.ok, "vertex: " + vs.log);
    assert.ok(fs.ok, "fragment: " + fs.log);
    return t.linkProgram(vs, fs, options || {});
}

const TRIVIAL_VS = "void main(void) { gl_Position = ftransform(); }";

test("depth prepass and shaded programs declare invariant clip positions", () => {
    const position = "attribute vec4 vvertex; uniform mat4 camprojmatrix;\n" +
        "void main() { gl_Position = camprojmatrix * vvertex; }";
    for (const fragment of ["void main() {}",
            "void main() { gl_FragColor = vec4(1.0); }"]) {
        const result = link(position, fragment);
        assert.ok(result.ok, result.log);
        assert.match(result.wgslVertex,
            /@invariant\s+@builtin\(position\) position/);
        assert.ok(!result.wgslFragment.includes("@invariant"),
            "invariance applies to vertex outputs, not fragment inputs");
    }
});

/* ---- preprocessor ---- */

test("#define with parameters expands", () => {
    const result = compile(
        "#define SCALE(v, k) ((v) * (k))\n" +
        "void main(void) { gl_FragColor = SCALE(vec4(1.0), 0.5); }");
    assert.ok(result.ok, result.log);
});

test("#if arithmetic and defined() are evaluated", () => {
    const source =
        "#define A 2\n" +
        "#if (A * 3) > 5 && defined(A)\n" +
        "void main(void) { gl_FragColor = vec4(1.0); }\n" +
        "#else\n" +
        "syntax error here\n" +
        "#endif\n";
    assert.ok(compile(source).ok);
});

test("nested conditionals track their parent's state", () => {
    const source =
        "#if 0\n" +
        "#if 1\n" +
        "this is not code\n" +
        "#endif\n" +
        "#endif\n" +
        "void main(void) { gl_FragColor = vec4(0.0); }\n";
    assert.ok(compile(source).ok);
});

test("a self-referential macro terminates", () => {
    assert.ok(compile("#define A A + 1\n" +
        "void main(void) { float x = 0.0; gl_FragColor = vec4(x); }").ok);
});

test("#version above 120 warns rather than failing", () => {
    const result = compile("#version 130\n" +
        "void main(void) { gl_FragColor = vec4(1.0); }");
    assert.ok(result.ok, result.log);
    assert.ok(result.warnings.some(w => w.indexOf("130") >= 0));
});

test("a required unknown extension is an error", () => {
    const result = compile("#extension GL_NV_nonexistent : require\n" +
        "void main(void) { gl_FragColor = vec4(1.0); }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("not supported") >= 0, result.log);
});

test("line numbers survive block comments", () => {
    const result = compile("/* one\ntwo\nthree */\nvoid main(void) { bad; }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("0:4:") >= 0, result.log);
});

/* ---- types and conversions ---- */

test("int converts to float implicitly, and the conversion is recorded", () => {
    const result = compile(
        "void main(void) { float x = 1; gl_FragColor = vec4(x); }");
    assert.ok(result.ok, result.log);
    const main = result.ast.decls.find(d => d.name === "main");
    const declaration = main.body.stmts[0].declarators[0];
    assert.ok(declaration.init.convertTo, "the int literal is marked for widening");
    assert.strictEqual(declaration.init.convertTo.name, "float");
});

test("float does not convert to int", () => {
    const result = compile("void main(void) { int x = 1.0; gl_FragColor = vec4(0.0); }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("cannot convert") >= 0, result.log);
});

test("matrix and vector multiplication agree on dimensions", () => {
    assert.ok(compile("uniform mat4 m;\nvoid main(void) {\n" +
        "  vec4 v = m * vec4(1.0);\n  gl_FragColor = v;\n}").ok);
    const bad = compile("uniform mat4 m;\nvoid main(void) {\n" +
        "  vec3 v = m * vec3(1.0);\n  gl_FragColor = vec4(v, 1.0);\n}");
    assert.strictEqual(bad.ok, false);
});

test("a swizzle out of range is rejected", () => {
    const result = compile(
        "void main(void) { vec2 v = vec2(1.0); gl_FragColor = vec4(v.xyzw); }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("out of range") >= 0, result.log);
});

test("a repeated component in an l-value swizzle is rejected", () => {
    const result = compile("void main(void) { vec4 v; v.xx = vec2(1.0); " +
        "gl_FragColor = v; }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("may not repeat") >= 0, result.log);
});

test("overload resolution prefers an exact match", () => {
    const result = compile(
        "float f(float x) { return x; }\n" +
        "float f(vec2 x) { return x.x; }\n" +
        "void main(void) { gl_FragColor = vec4(f(vec2(1.0))); }");
    assert.ok(result.ok, result.log);
});

test("an ambiguous call is an error, not a first-match win", () => {
    const result = compile(
        "float f(float a, vec2 b) { return a; }\n" +
        "float f(vec2 a, float b) { return b; }\n" +
        "void main(void) { gl_FragColor = vec4(f(1, 1)); }");
    assert.strictEqual(result.ok, false);
});

test("a reserved word is refused with its name", () => {
    const result = compile("void main(void) { int switch = 1; }");
    assert.strictEqual(result.ok, false);
    assert.ok(result.log.indexOf("switch") >= 0, result.log);
});

test("discard outside a fragment shader is refused", () => {
    const result = compile("void main(void) { discard; gl_Position = vec4(0.0); }",
        "vertex");
    assert.strictEqual(result.ok, false);
});

/* ---- usage tracking ---- */

test("compatibility attributes are recorded with their historical slots", () => {
    const result = compile(
        "void main(void) { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" +
        "  gl_TexCoord[0] = gl_MultiTexCoord0; }", "vertex");
    assert.ok(result.ok, result.log);
    const attributes = result.usage.attributes;
    assert.strictEqual(attributes.get("gl_Vertex").location, 0);
    assert.strictEqual(attributes.get("gl_MultiTexCoord0").location, 8);
    assert.ok(result.usage.stateFields.has("mvp"));
    assert.strictEqual(result.usage.texCoordMax, 0);
});

test("ftransform() pulls in gl_Vertex even when the shader never names it", () => {
    const result = compile(TRIVIAL_VS, "vertex");
    assert.ok(result.ok, result.log);
    assert.ok(result.usage.attributes.has("gl_Vertex"));
    assert.ok(result.usage.stateFields.has("mvp"));
});

test("only the state a shader reads is requested", () => {
    const result = compile(
        "void main(void) { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; }",
        "vertex");
    assert.deepStrictEqual([...result.usage.stateFields], ["mvp"]);
});

test("a sampler is a binding, not a uniform-block member", () => {
    const result = compile("uniform sampler2D tex;\nuniform float k;\n" +
        "void main(void) { gl_FragColor = texture2D(tex, vec2(0.0)) * k; }");
    assert.ok(result.ok, result.log);
    assert.strictEqual(result.usage.samplers.length, 1);
    assert.strictEqual(result.usage.samplers[0].name, "tex");
    assert.strictEqual(result.usage.uniforms.length, 1);
    assert.strictEqual(result.usage.uniforms[0].name, "k");
});

test("a texture fetch in uniform control flow is counted separately", () => {
    const result = compile("uniform sampler2D tex;\nvarying vec2 tc;\n" +
        "void main(void) {\n" +
        "  vec4 c = texture2D(tex, tc);\n" +
        "  if (tc.x > 0.5) { c += texture2D(tex, tc * 2.0); }\n" +
        "  gl_FragColor = c;\n}");
    assert.ok(result.ok, result.log);
    assert.strictEqual(result.usage.uniformSamples, 1);
    assert.strictEqual(result.usage.nonUniformSamples, 1,
        "the conditional fetch needs explicit gradients (plan 4.10)");
});

/* ---- linking ---- */

test("a program's uniform block places each member on a 16-byte boundary", () => {
    const program = link(TRIVIAL_VS,
        "uniform float a;\nuniform vec3 b;\nuniform mat4 m;\n" +
        "void main(void) { gl_FragColor = vec4(a) + vec4(b, 1.0) + m[0]; }");
    assert.ok(program.ok, program.log);
    const byName = new Map(program.reflection.uniforms.map(u => [u.name, u]));
    assert.strictEqual(byName.get("a").offsetBytes % 16, 0);
    assert.strictEqual(byName.get("b").offsetBytes % 16, 0);
    assert.strictEqual(byName.get("m").offsetBytes % 16, 0);
    assert.strictEqual(byName.get("m").matrixColumnStrideBytes, 16);
});

test("a GLSL program variant injects colour logic operations", () => {
    const program = link(TRIVIAL_VS,
        "void main(void) { gl_FragColor = vec4(0.25); }",
        { variant: { logicOp: 0x150A, colorTargets: 1 } });
    assert.ok(program.ok, program.log);
    assert.ok(program.wgslFragment.includes("let r = (~d)"));
    assert.ok(program.wgslFragment.includes("glApplyLogic(gl_FragColor"));
});

test("a uniform array of floats is widened to a vec4 stride", () => {
    const program = link(TRIVIAL_VS,
        "uniform float weights[4];\n" +
        "void main(void) { gl_FragColor = vec4(weights[2]); }");
    assert.ok(program.ok, program.log);
    const weights = program.reflection.uniforms.find(u => u.name === "weights");
    assert.strictEqual(weights.arraySize, 4);
    assert.strictEqual(weights.arrayStrideBytes, 16,
        "the uniform address space requires a 16-byte array stride");
});

test("uniform locations follow GL's array rule", () => {
    const program = link(TRIVIAL_VS,
        "uniform vec4 colors[3];\nuniform float k;\n" +
        "void main(void) { gl_FragColor = colors[1] * k; }");
    const colors = program.reflection.uniforms.find(u => u.name === "colors");
    const k = program.reflection.uniforms.find(u => u.name === "k");
    assert.strictEqual(k.location, colors.location + 3,
        "an array occupies one location per element");
});

test("a uniform declared differently in the two stages fails to link", () => {
    const vs = compile("uniform vec4 shared_value;\n" +
        "void main(void) { gl_Position = shared_value; }", "vertex");
    const fs = compile("uniform vec2 shared_value;\n" +
        "void main(void) { gl_FragColor = vec4(shared_value, 0.0, 1.0); }");
    const program = t.linkProgram(vs, fs, {});
    assert.strictEqual(program.ok, false);
    assert.ok(program.log.indexOf("different types") >= 0, program.log);
});

test("only varyings both stages use get a slot", () => {
    const program = link(
        "varying vec4 used;\nvarying vec4 unused;\n" +
        "void main(void) { gl_Position = gl_Vertex; used = vec4(1.0); " +
        "unused = vec4(2.0); }",
        "varying vec4 used;\nvoid main(void) { gl_FragColor = used; }");
    assert.ok(program.ok, program.log);
    assert.strictEqual(program.reflection.varyingSlots, 1,
        "a varying the fragment stage never reads costs nothing");
});

test("small varyings are packed into a shared slot", () => {
    const program = link(
        "varying float a;\nvarying vec2 b;\n" +
        "void main(void) { gl_Position = gl_Vertex; a = 1.0; b = vec2(2.0); }",
        "varying float a;\nvarying vec2 b;\n" +
        "void main(void) { gl_FragColor = vec4(a, b, 1.0); }");
    assert.ok(program.ok, program.log);
    assert.strictEqual(program.reflection.varyingSlots, 1,
        "a float and a vec2 fit in one vec4 slot");
});

test("too many varyings fails to link with a message naming the limit", () => {
    let vs = "";
    let fs = "";
    for (let i = 0; i < 20; ++i) {
        vs += "varying vec4 v" + i + ";\n";
        fs += "varying vec4 v" + i + ";\n";
    }
    vs += "void main(void) { gl_Position = gl_Vertex;";
    fs += "void main(void) { vec4 sum = vec4(0.0);";
    for (let i = 0; i < 20; ++i) {
        vs += " v" + i + " = vec4(float(" + i + "));";
        fs += " sum += v" + i + ";";
    }
    vs += " }";
    fs += " gl_FragColor = sum; }";
    const program = link(vs, fs);
    assert.strictEqual(program.ok, false);
    assert.ok(program.log.indexOf("D-12") >= 0, program.log);
});

test("gl_Color in the fragment stage is fed by gl_FrontColor", () => {
    const program = link(
        "void main(void) { gl_Position = gl_Vertex; gl_FrontColor = gl_Color; }",
        "void main(void) { gl_FragColor = gl_Color; }");
    assert.ok(program.ok, program.log);
    assert.ok(program.wgslFragment.indexOf("gl_Color = fsin.v0") >= 0,
        program.wgslFragment);
});

test("a variant changes the cache key and the generated code", () => {
    const vs = compile(TRIVIAL_VS, "vertex");
    const fs = compile("void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 0.5); }");
    const plain = t.linkProgram(vs, fs, {});
    const tested = t.linkProgram(vs, fs, { variant: { alphaTest: "greater" } });
    assert.notStrictEqual(plain.cacheKey, tested.cacheKey);
    assert.ok(tested.wgslFragment.indexOf("discard") >= 0);
    assert.ok(plain.wgslFragment.indexOf("discard") < 0);
    assert.ok(tested.reflection.stateFields.indexOf("alphaRef") >= 0);
});

test("a programmable polygon-stipple variant injects the fragment test", () => {
    const vs = compile(TRIVIAL_VS, "vertex");
    const fs = compile("void main(void) { gl_FragColor = vec4(1.0); }");
    const plain = t.linkProgram(vs, fs, {});
    const stippled = t.linkProgram(vs, fs,
        { variant: { polygonStipple: true } });
    assert.ok(stippled.ok, stippled.log);
    assert.notStrictEqual(plain.cacheKey, stippled.cacheKey);
    assert.ok(stippled.reflection.stateFields.includes("polygonStipple"));
    assert.ok(stippled.wgslFragment.indexOf("stippleByteIndex") >= 0);
});

test("gl_FragData decides the colour target count", () => {
    const program = link(TRIVIAL_VS,
        "void main(void) { gl_FragData[0] = vec4(1.0); gl_FragData[2] = vec4(0.0); }");
    assert.ok(program.ok, program.log);
    assert.strictEqual(program.reflection.colorTargets, 3);
});

test("writing both gl_FragColor and gl_FragData is refused", () => {
    const program = link(TRIVIAL_VS,
        "void main(void) { gl_FragColor = vec4(1.0); gl_FragData[0] = vec4(0.0); }");
    assert.strictEqual(program.ok, false);
});

test("the generated vertex shader always remaps depth and flips Y", () => {
    const program = link(TRIVIAL_VS, "void main(void) { gl_FragColor = vec4(1.0); }");
    assert.ok(program.wgslVertex.indexOf(
        "clip.z = (clip.z + clip.w) * 0.5;") >= 0);
    assert.ok(program.wgslVertex.indexOf("clip.y = -clip.y;") >= 0);
});

test("out parameters become pointers with a write-back", () => {
    const program = link(TRIVIAL_VS,
        "void split(vec4 v, out vec3 rgb, out float a) { rgb = v.rgb; a = v.a; }\n" +
        "void main(void) {\n" +
        "  vec3 c; float alpha;\n" +
        "  split(vec4(1.0), c, alpha);\n" +
        "  gl_FragColor = vec4(c, alpha);\n}");
    assert.ok(program.ok, program.log);
    assert.ok(program.wgslFragment.indexOf("ptr<function") >= 0);
    assert.ok(program.wgslFragment.indexOf("&_t") >= 0,
        "the argument is copied into a temporary and written back");
});

test("mod() is emitted with GLSL's floor semantics", () => {
    const program = link(TRIVIAL_VS,
        "void main(void) { gl_FragColor = vec4(mod(-1.5, 1.0)); }");
    assert.ok(program.wgslFragment.indexOf("floor(") >= 0,
        "'%' would give C's truncating remainder, which differs for negatives");
});

for (const [name, error] of failures)
    console.error("FAIL: " + name + "\n    " + (error && error.message));
console.log(passed + " passed, " + failures.length + " failed");
process.exit(failures.length ? 1 : 0);
                                                                                                                                                                                                                                                                                                     source/v64/tests/glbridge/gl_shader_wgsl_validation_test.js                                         0000644 0000000 0000000 00000033147 00000000000 021410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Validates that gl_shader_translator.js emits WGSL a real compiler accepts.
//
// gl_shader_translator_test.js asserts on translation structure and would
// happily pass on WGSL no driver can compile. This file closes that gap by
// running the generated source through `naga`, the WGSL front end wgpu and
// Firefox use, which performs the same shape of validation Tint does inside
// createShaderModule(). Running it here means a syntax or type error surfaces
// in Node in a second instead of as a black screen inside v86.
//
// The corpus is Cube 2's own shaders, because they are the acceptance target
// for M4 and because a generator-written shader exercises paths no hand-written
// fixture would think to.
//
// naga is optional: install it with
//     cargo install naga-cli
// and either put it on PATH or point GL_NAGA at the binary. Without it this
// test skips (exit 0) rather than blocking a machine that only wants the pure
// JavaScript suites.

"use strict";

const assert = require("assert");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawnSync, execFileSync } = require("child_process");
const t = require("../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js");

function findNaga() {
    if (process.env.GL_NAGA) return process.env.GL_NAGA;
    if (spawnSync("naga", ["--version"], { encoding: "utf8" }).status === 0)
        return "naga";
    const cargo = path.join(os.homedir(), ".cargo", "bin", "naga");
    return fs.existsSync(cargo) ? cargo : null;
}

const naga = findNaga();
if (!naga) {
    console.log("SKIP: no `naga` binary (install with `cargo install naga-cli` " +
        "or set GL_NAGA) -- WGSL validation not run");
    process.exit(0);
}

const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), "glwg-wgsl-"));
let passed = 0;
const failures = [];

function validate(label, wgsl) {
    const file = path.join(outputDir, label.replace(/[^A-Za-z0-9_.-]/g, "_") + ".wgsl");
    fs.writeFileSync(file, wgsl);
    try {
        execFileSync(naga, [file], { stdio: "pipe" });
        return null;
    } catch (error) {
        return String(error.stderr || error.stdout || error);
    }
}

function checkProgram(label, vsSource, fsSource, options) {
    const vs = t.compileShader(vsSource, "vertex", {});
    const fs2 = t.compileShader(fsSource, "fragment", {});
    if (!vs.ok || !fs2.ok) {
        failures.push([label, (vs.ok ? "" : "vertex: " + vs.log) +
            (fs2.ok ? "" : " fragment: " + fs2.log)]);
        return;
    }
    const program = t.linkProgram(vs, fs2, options || {});
    if (!program.ok) { failures.push([label, "link: " + program.log]); return; }
    const vertexError = validate(label + ".vert", program.wgslVertex);
    const fragmentError = validate(label + ".frag", program.wgslFragment);
    if (vertexError || fragmentError)
        failures.push([label, (vertexError || "") + (fragmentError || "")]);
    else ++passed;
}

/* ---- Cube 2's own shaders ---- */

require("./cube2_glsl_direct_corpus_r6889.js");
const corpus = globalThis.CUBE2_DIRECT_GLSL_CORPUS_R6889;
assert.ok(corpus && corpus.length, "the Cube 2 corpus is present");
for (const entry of corpus)
    checkProgram("cube2_" + entry.name, entry.vertex, entry.fragment);

// Cube 2 rewrites skyfog's //:variantoverride directive after showing the
// "Shader: skyfog" loading message, then compiles the rewritten source as a
// second program.  Keep that runtime-only source in the real WGSL compiler
// corpus as well; the direct cfg extraction above contains only the base text.
const skyfog = corpus.find(entry => entry.name === "skyfog");
assert.ok(skyfog, "the Cube 2 corpus contains skyfog");
const skyfogVariantLines = skyfog.fragment.split("\n");
const skyfogVariantLine = skyfogVariantLines.findIndex(line =>
    line.indexOf("//:variantoverride") >= 0);
assert.ok(skyfogVariantLine >= 0 && skyfogVariantLine + 1 < skyfogVariantLines.length,
    "skyfog contains the generic variant directive and overridden line");
skyfogVariantLines[skyfogVariantLine] = skyfogVariantLines[skyfogVariantLine]
    .replace("//:variantoverride", " ".repeat("//:variantoverride".length));
skyfogVariantLines[skyfogVariantLine + 1] =
    " ".repeat(skyfogVariantLines[skyfogVariantLine + 1].length);
checkProgram("cube2_skyfog_generic_variant", skyfog.vertex,
    skyfogVariantLines.join("\n"));
const corpusFailures = failures.length;

/* ---- the compatibility surface, which the corpus barely touches ---- */

checkProgram("compat_fixed_state",
    "varying vec4 lit;\n" +
    "void main(void) {\n" +
    "  vec3 n = normalize(gl_NormalMatrix * gl_Normal);\n" +
    "  vec3 eye = (gl_ModelViewMatrix * gl_Vertex).xyz;\n" +
    "  vec4 c = gl_FrontLightModelProduct.sceneColor;\n" +
    "  for (int i = 0; i < 4; i++) {\n" +
    "    vec3 vp = normalize(gl_LightSource[i].position.xyz - eye);\n" +
    "    float att = 1.0 / (gl_LightSource[i].constantAttenuation +\n" +
    "                       gl_LightSource[i].linearAttenuation);\n" +
    "    c += att * max(dot(n, vp), 0.0) * gl_FrontLightProduct[i].diffuse;\n" +
    "    c += pow(max(dot(n, gl_LightSource[i].halfVector.xyz), 0.0),\n" +
    "             gl_FrontMaterial.shininess) * gl_FrontLightProduct[i].specular;\n" +
    "  }\n" +
    "  lit = c;\n" +
    "  gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n" +
    "  gl_FogFragCoord = abs(eye.z);\n" +
    "  gl_Position = ftransform();\n}",
    "varying vec4 lit;\n" +
    "void main(void) {\n" +
    "  float f = clamp((gl_Fog.end - gl_FogFragCoord) * gl_Fog.scale, 0.0, 1.0);\n" +
    "  gl_FragColor = mix(gl_Fog.color, lit * gl_TexCoord[0], f);\n}");

checkProgram("compat_shadow_and_cube",
    "varying vec4 shadowcoord;\nvarying vec3 dir;\n" +
    "void main(void) {\n" +
    "  shadowcoord = gl_TextureMatrix[1] * gl_Vertex;\n" +
    "  dir = gl_Normal;\n" +
    "  gl_Position = ftransform();\n}",
    "uniform sampler2DShadow shadowmap;\nuniform samplerCube env;\n" +
    "varying vec4 shadowcoord;\nvarying vec3 dir;\n" +
    "void main(void) {\n" +
    "  float lit = shadow2DProj(shadowmap, shadowcoord).r;\n" +
    "  gl_FragColor = textureCube(env, dir) * lit;\n}");

checkProgram("structs_and_out_params",
    "attribute vec4 pos;\nvoid main(void) { gl_Position = pos; }",
    "struct Light { vec3 color; float power; };\n" +
    "uniform Light lights[2];\n" +
    "uniform float gamma;\n" +
    "void apply(Light l, inout vec3 acc) { acc += l.color * l.power; }\n" +
    "void main(void) {\n" +
    "  vec3 acc = vec3(0.0);\n" +
    "  apply(lights[0], acc);\n" +
    "  apply(lights[1], acc);\n" +
    "  gl_FragColor = vec4(pow(acc, vec3(gamma)), 1.0);\n}");

checkProgram("control_flow_and_conversions",
    "attribute vec4 pos;\nvarying float k;\n" +
    "void main(void) {\n" +
    "  k = 0.0;\n" +
    "  for (int i = 0; i < 8; i++) { k += float(i) * 0.5; }\n" +
    "  int j = 0;\n" +
    "  while (j < 3) { k = k * 2.0; j++; }\n" +
    "  do { k -= 1.0; } while (k > 100.0);\n" +
    "  gl_Position = pos * (k > 0.0 ? 1.0 : -1.0);\n}",
    "varying float k;\nuniform bool invert;\nuniform int mode;\n" +
    "void main(void) {\n" +
    "  vec4 c = vec4(k);\n" +
    "  if (invert) { c = 1.0 - c; }\n" +
    "  if (mode == 2) { discard; }\n" +
    "  gl_FragColor = c;\n}");

checkProgram("non_uniform_sampling",
    "attribute vec4 pos;\nvarying vec2 tc;\n" +
    "void main(void) { tc = pos.xy; gl_Position = pos; }",
    "uniform sampler2D tex;\nvarying vec2 tc;\n" +
    "void main(void) {\n" +
    "  vec4 c = vec4(0.0);\n" +
    "  if (tc.x > 0.5) { c = texture2D(tex, tc); }\n" +
    "  for (int i = 0; i < 4; i++) { c += texture2D(tex, tc * float(i)); }\n" +
    "  gl_FragColor = c;\n}");

checkProgram("vertex_texture_fetch",
    "uniform sampler2D heightmap;\nattribute vec4 pos;\n" +
    "void main(void) {\n" +
    "  float h = texture2D(heightmap, pos.xy).r;\n" +
    "  gl_Position = gl_ModelViewProjectionMatrix * (pos + vec4(0.0, h, 0.0, 0.0));\n}",
    "void main(void) { gl_FragColor = vec4(1.0); }");

checkProgram("matrix_builtins",
    "attribute vec4 pos;\nuniform mat3 rot;\nvarying vec3 v;\n" +
    "void main(void) {\n" +
    "  mat3 t = transpose(rot);\n" +
    "  mat3 m = matrixCompMult(rot, t);\n" +
    "  v = m * pos.xyz;\n" +
    "  gl_Position = pos;\n}",
    "varying vec3 v;\nvoid main(void) { gl_FragColor = vec4(v, 1.0); }");

checkProgram("point_sprite_and_clip",
    "attribute vec4 pos;\n" +
    "void main(void) {\n" +
    "  gl_Position = gl_ModelViewProjectionMatrix * pos;\n" +
    "  gl_ClipVertex = gl_ModelViewMatrix * pos;\n" +
    "  gl_PointSize = 8.0;\n}",
    "uniform sampler2D sprite;\n" +
    "void main(void) { gl_FragColor = texture2D(sprite, gl_PointCoord); }",
    { variant: { pointSprite: true, clipPlaneCount: 3, alphaTest: "gequal" } });

checkProgram("two_sided_flat",
    "void main(void) {\n" +
    "  gl_Position = ftransform();\n" +
    "  gl_FrontColor = gl_Color;\n  gl_BackColor = gl_Color * 0.5;\n}",
    "void main(void) { gl_FragColor = gl_Color; }",
    { variant: { twoSided: true, flatShading: true } });

checkProgram("mrt",
    "attribute vec4 pos;\nvoid main(void) { gl_Position = pos; }",
    "void main(void) {\n" +
    "  gl_FragData[0] = vec4(1.0, 0.0, 0.0, 1.0);\n" +
    "  gl_FragData[1] = vec4(0.0, 1.0, 0.0, 1.0);\n" +
    "  gl_FragDepth = 0.5;\n}");

/* ---- operators WGSL takes differently (desktop: GLSL ES 1.00 reserves the
 * integer ones) ---- */

checkProgram("integer_operators",
    "attribute vec4 pos;\nvoid main(void) { gl_Position = pos; }",
    "uniform int k;\nuniform ivec2 v;\n" +
    "void main(void) {\n" +
    "  ivec2 a = v & k;\n" +
    "  ivec2 b = k | v;\n" +
    "  int s = k << k;\n" +
    "  ivec2 c = v >> k;\n" +
    "  ivec2 d = v << v;\n" +
    "  a ^= k;\n" +
    "  s >>= 2;\n" +
    "  gl_FragColor = vec4(vec2(a + b + c + d), float(s), float(~k));\n}");

/* ---- GLSL ES 1.00 (the GLES host's dialect) ---- */

function checkProgramES(label, vsSource, fsSource) {
    const vs = t.compileShader(vsSource, "vertex", { es: true });
    const fs2 = t.compileShader(fsSource, "fragment", { es: true });
    if (!vs.ok || !fs2.ok) {
        failures.push([label, (vs.ok ? "" : "vertex: " + vs.log) +
            (fs2.ok ? "" : " fragment: " + fs2.log)]);
        return;
    }
    const program = t.linkProgram(vs, fs2, { es: true });
    if (!program.ok) { failures.push([label, "link: " + program.log]); return; }
    const vertexError = validate(label + ".vert", program.wgslVertex);
    const fragmentError = validate(label + ".frag", program.wgslFragment);
    if (vertexError || fragmentError)
        failures.push([label, (vertexError || "") + (fragmentError || "")]);
    else ++passed;
}

checkProgramES("es_equality",
    "attribute vec4 pos;\nvarying vec2 tc;\n" +
    "void main(void) { tc = pos.xy; gl_Position = pos; }",
    "precision mediump float;\n" +
    "struct S { vec2 a; mat2 m; };\n" +
    "uniform S s0;\nuniform S s1;\nuniform mat3 m0;\nuniform mat3 m1;\n" +
    "uniform ivec3 i0;\nvarying vec2 tc;\n" +
    "void main(void) {\n" +
    "  bool e = tc == vec2(0.5) || m0 != m1 || s0 == s1 || i0 == ivec3(1, 2, 3);\n" +
    "  gl_FragColor = e ? vec4(1.0) : vec4(0.0);\n}");

checkProgramES("es_non_uniform_sampling_and_in_params",
    "attribute vec4 pos;\nvarying vec2 tc;\n" +
    "void main(void) { tc = pos.xy; gl_Position = pos; }",
    "precision mediump float;\n" +
    "uniform sampler2D tex;\nuniform samplerCube cube;\nvarying vec2 tc;\n" +
    "vec4 look(vec2 c) { c = c * 2.0; return texture2D(tex, c); }\n" +
    "void main(void) {\n" +
    "  vec4 c = vec4(0.0);\n" +
    "  if (tc.x > 0.5) { c = look(tc); }\n" +
    "  if (tc.y > 0.5) { gl_FragColor = c; return; }\n" +
    "  for (int i = 0; i < 4; i++) {\n" +
    "    if (tc.x > float(i) * 0.25) break;\n" +
    "    c += textureCube(cube, vec3(tc, 1.0));\n" +
    "  }\n" +
    "  gl_FragColor = c + texture2D(tex, tc);\n}");

checkProgramES("es_matrix_componentwise",
    "attribute vec4 pos;\nvoid main(void) { gl_Position = pos; }",
    "precision mediump float;\nuniform mat3 a;\nuniform mat3 b;\nuniform float s;\n" +
    "const mat2 c = mat2(1.0);\nconst mat2 d = mat2(1.0, 2.0, 3.0, 4.0);\n" +
    "void main(void) {\n" +
    "  mat3 r = a + s; r = s - r; r = r / b; r = -r; r = r / s; r = s / r;\n" +
    "  mat2 q = c + d; q = -c; q = c / d; q++; --q; q += 1.0; q /= d;\n" +
    "  gl_FragColor = vec4(r[0], 1.0) + vec4(q[0], q[1]);\n}");

checkProgramES("es_struct_with_struct_array",
    "attribute vec4 pos;\nvoid main(void) { gl_Position = pos; }",
    "precision mediump float;\nstruct L { vec3 c; float k; };\nstruct S { L l[2]; vec2 p; };\n" +
    "uniform S s;\nvoid main(void) { gl_FragColor = vec4(s.l[1].c * s.l[0].k, s.p.x); }");

// These shaders bypass the GLSL translator, so exercise them directly too.
// A syntax error here otherwise appears only when CopyTexImage, mipmap, or a
// scaling framebuffer blit first runs on a real adapter.
const executorSource = fs.readFileSync(path.join(__dirname, "../../src/browser/glbridge/gl-webgpu",
    "gl_executor.js"), "utf8");
for (const name of ["COLOR_COPY_WGSL", "MIPMAP_WGSL", "COLOR_BLIT_WGSL"]) {
    const match = new RegExp("const\\s+" + name + "\\s*=\\s*`([\\s\\S]*?)`;" )
        .exec(executorSource);
    if (!match) failures.push([name, "shader constant is missing"]);
    else {
        const error = validate(name, match[1]);
        if (error) failures.push([name, error]);
        else ++passed;
    }
}

for (const [name, log] of failures)
    console.error("FAIL: " + name + "\n" + String(log).slice(0, 900));
console.log(passed + " shader pairs validated (" + corpus.length +
    " from the Cube 2 corpus), " + failures.length + " failed");
void corpusFailures;
fs.rmSync(outputDir, { recursive: true, force: true });
process.exit(failures.length ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/glbridge/gl_stream_builder.js                                                      0000644 0000000 0000000 00000060426 00000000000 016636  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Builds OpenGL command records the way openglproxy/opengl32_proxy.c does.
//
// The tests need to speak the guest's wire format exactly, so this encodes
// from the same signature table gl_executor.js decodes with. Anything the
// table cannot describe -- textures, draws, shader source -- gets an explicit
// builder here, and those are precisely the records worth hand-checking.

"use strict";

const wire = typeof require === "function" ?
    require("../../src/browser/glbridge/gl-webgpu/gl_wire.js") : globalThis.GLWireFormat;
const constants = typeof require === "function" ?
    require("../../src/browser/glbridge/gl-webgpu/gl_constants.js") : globalThis.GLWGConstants;

const GL = constants.GL;
const GLFN = constants.GLFN;

class GLStream {
    constructor() {
        this.buffer = new Uint8Array(4096);
        this.length = 0;
    }

    reserve(extra) {
        if (this.length + extra <= this.buffer.byteLength) return;
        let size = this.buffer.byteLength * 2;
        while (size < this.length + extra) size *= 2;
        const grown = new Uint8Array(size);
        grown.set(this.buffer.subarray(0, this.length));
        this.buffer = grown;
    }

    /*
     * Returns a view of the payload *inside* the assembled stream, because a
     * synchronous query is answered by writing into the record the guest
     * submitted. A test holding a detached copy would never see the answer,
     * which is the same mistake a bridge that copies the batch would make.
     */
    record(opcode, payloadBytes) {
        const payload = payloadBytes || new Uint8Array(0);
        const extended = payload.byteLength > 0xFFFE;
        this.reserve((extended ? 8 : 4) + payload.byteLength);
        const view = new DataView(this.buffer.buffer);
        view.setUint16(this.length, opcode, true);
        if (extended) {
            view.setUint16(this.length + 2, 0xFFFF, true);
            view.setUint32(this.length + 4, payload.byteLength, true);
            this.length += 8;
        } else {
            view.setUint16(this.length + 2, payload.byteLength, true);
            this.length += 4;
        }
        const at = this.length;
        this.buffer.set(payload, at);
        this.length += payload.byteLength;
        this.lastPayload = { offset: at, length: payload.byteLength };
        return this;
    }

    /* The payload of the record just appended, as a live view. */
    payloadView() {
        const { offset, length } = this.lastPayload;
        const stream = this;
        return {
            get bytes() {
                return stream.buffer.subarray(offset, offset + length);
            },
            get view() {
                return new DataView(stream.buffer.buffer, offset, length);
            },
        };
    }

    /* Encodes from the declarative signature, which is what keeps the tests
     * honest about the layout the executor expects. */
    call(name, ...args) {
        const signature = wire.SIGNATURES[name];
        if (!signature) throw new Error("no signature for " + name);
        const types = signature[1];
        const payload = new Uint8Array(wire.payloadBytes(types));
        const view = new DataView(payload.buffer);
        let offset = 0;
        for (let i = 0; i < types.length; ++i) {
            const value = args[i] === undefined ? 0 : args[i];
            switch (types[i]) {
            case "i": view.setInt32(offset, value | 0, true); offset += 4; break;
            case "u": view.setUint32(offset, value >>> 0, true); offset += 4; break;
            case "f": view.setFloat32(offset, value, true); offset += 4; break;
            default: view.setFloat64(offset, value, true); offset += 8; break;
            }
        }
        return this.record(GLFN[name], payload);
    }

    makeCurrent(hwnd, x, y, width, height, contextId, shareGroup) {
        const extended = contextId !== undefined || shareGroup !== undefined;
        const payload = new Uint8Array(extended ? 28 : 20);
        const view = new DataView(payload.buffer);
        view.setUint32(0, hwnd, true);
        view.setInt32(4, x, true);
        view.setInt32(8, y, true);
        view.setUint32(12, width, true);
        view.setUint32(16, height, true);
        if (extended) {
            view.setUint32(20, (contextId || 0) >>> 0, true);
            view.setUint32(24, (shareGroup || 0) >>> 0, true);
        }
        return this.record(constants.CTRL.MAKE_CURRENT, payload);
    }

    // V86GL_CTRL_WINDOW_STATE: flags as D9WGWindowState's; `rects` (client
    // coordinates, [left, top, right, bottom]) sets the region flag
    windowState(hwnd, flags, x, y, width, height, rects) {
        const payload = new Uint8Array(24 + (rects ? 4 + rects.length * 16 : 0));
        const view = new DataView(payload.buffer);
        view.setUint32(0, hwnd, true);
        view.setUint32(4, (flags | (rects ? 1 << 7 : 0)) >>> 0, true);
        view.setInt32(8, x, true);
        view.setInt32(12, y, true);
        view.setUint32(16, width, true);
        view.setUint32(20, height, true);
        if (rects) {
            view.setUint32(24, rects.length, true);
            rects.forEach((rect, i) => rect.forEach((v, j) => view.setInt32(28 + i * 16 + j * 4, v, true)));
        }
        return this.record(constants.CTRL.WINDOW_STATE, payload);
    }

    names(opcode, list) {
        const payload = new Uint8Array(4 + list.length * 4);
        const view = new DataView(payload.buffer);
        view.setUint32(0, list.length, true);
        list.forEach((name, i) => view.setUint32(4 + i * 4, name, true));
        return this.record(opcode, payload);
    }

    texImage2D(target, level, internalFormat, width, height, format, type, data) {
        const bytes = data || new Uint8Array(0);
        const payload = new Uint8Array(36 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        let at = 0;
        for (const value of [target, level, internalFormat, width, height, 0,
                format, type, bytes.byteLength]) {
            view.setUint32(at, value >>> 0, true);
            at += 4;
        }
        payload.set(bytes, at);
        return this.record(GLFN.TEX_IMAGE_2D, payload.subarray(0, at + bytes.byteLength));
    }

    compressedTexImage2D(target, level, internalFormat, width, height, data,
            border) {
        const bytes = data || new Uint8Array(0);
        // This is the guest proxy's fixed CompressedTexImage wire struct.  It
        // retains a depth word for 2D uploads rather than using a shorter
        // dimension-specific record.
        const payload = new Uint8Array(32 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        view.setUint32(0, target >>> 0, true);
        view.setInt32(4, level | 0, true);
        view.setUint32(8, internalFormat >>> 0, true);
        view.setInt32(12, width | 0, true);
        view.setInt32(16, height | 0, true);
        view.setInt32(20, 1, true);
        view.setInt32(24, (border || 0) | 0, true);
        view.setUint32(28, bytes.byteLength >>> 0, true);
        payload.set(bytes, 32);
        return this.record(GLFN.COMPRESSED_TEX_IMAGE_2D, payload);
    }

    compressedTexSubImage2D(target, level, x, y, width, height, format, data) {
        const bytes = data || new Uint8Array(0);
        // The subimage command likewise always includes z and depth.
        const payload = new Uint8Array(40 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        view.setUint32(0, target >>> 0, true);
        view.setInt32(4, level | 0, true);
        view.setInt32(8, x | 0, true);
        view.setInt32(12, y | 0, true);
        view.setInt32(16, 0, true);
        view.setInt32(20, width | 0, true);
        view.setInt32(24, height | 0, true);
        view.setInt32(28, 1, true);
        view.setUint32(32, format >>> 0, true);
        view.setUint32(36, bytes.byteLength >>> 0, true);
        payload.set(bytes, 40);
        return this.record(GLFN.COMPRESSED_TEX_SUB_IMAGE_2D, payload);
    }

    drawPixels(width, height, format, type, data) {
        const bytes = data || new Uint8Array(0);
        const payload = new Uint8Array(20 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        view.setInt32(0, width, true);
        view.setInt32(4, height, true);
        view.setUint32(8, format, true);
        view.setUint32(12, type, true);
        view.setUint32(16, bytes.byteLength, true);
        payload.set(bytes, 20);
        return this.record(GLFN.DRAW_PIXELS, payload);
    }

    bitmap(width, height, xorig, yorig, xmove, ymove, data) {
        const bytes = data || new Uint8Array(0);
        const payload = new Uint8Array(28 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        view.setInt32(0, width, true);
        view.setInt32(4, height, true);
        view.setFloat32(8, xorig, true);
        view.setFloat32(12, yorig, true);
        view.setFloat32(16, xmove, true);
        view.setFloat32(20, ymove, true);
        view.setUint32(24, bytes.byteLength, true);
        payload.set(bytes, 28);
        return this.record(GLFN.BITMAP, payload);
    }

    /*
     * The packed client-array draw. Thirteen blocks in the guest's order --
     * vertex, colour, normal, eight texture coordinates, secondary colour, fog
     * coordinate -- behind the 'CAMT' header.
     */
    drawArrays(mode, count, arrays) {
        const order = ["vertex", "color", "normal",
            "texCoord0", "texCoord1", "texCoord2", "texCoord3",
            "texCoord4", "texCoord5", "texCoord6", "texCoord7",
            "secondaryColor", "fogCoord"];
        const blocks = order.map(name => arrays[name] || null);
        let size = 20;
        for (const block of blocks)
            size += 20 + (block && block.data ? block.data.byteLength : 0);
        const payload = new Uint8Array(size);
        const view = new DataView(payload.buffer);
        view.setUint32(0, mode, true);
        view.setInt32(4, count, true);
        view.setUint32(8, 0x544D4143, true);
        view.setUint32(12, (8 | 0x80000000 | 0x40000000) >>> 0, true);
        view.setUint32(16, 0, true);
        let at = 20;
        for (const block of blocks) {
            const data = block && block.data ? block.data : null;
            view.setUint32(at, block ? 1 : 0, true);
            view.setInt32(at + 4, block ? block.size : 0, true);
            view.setUint32(at + 8, block ? block.type : 0, true);
            view.setInt32(at + 12, block ? (block.stride || 0) : 0, true);
            view.setUint32(at + 16, data ? data.byteLength : 0, true);
            at += 20;
            if (data) { payload.set(data, at); at += data.byteLength; }
        }
        return this.record(GLFN.DRAW_ARRAYS, payload);
    }

    /*
     * The indexed twin of drawArrays. It exists because the suite had none:
     * the multitexture header sits between the fixed header and the indices,
     * and with no indexed fixture nothing noticed that the executor was
     * slicing its indices from the wrong offset and drawing the magic word.
     */
    drawElements(mode, indices, indexType, arrays) {
        indices = new Uint8Array(indices.buffer, indices.byteOffset, indices.byteLength);
        const order = ["vertex", "color", "normal",
            "texCoord0", "texCoord1", "texCoord2", "texCoord3",
            "texCoord4", "texCoord5", "texCoord6", "texCoord7",
            "secondaryColor", "fogCoord"];
        const blocks = order.map(name => arrays[name] || null);
        const count = indexType === GL.UNSIGNED_SHORT ? indices.byteLength / 2 :
            (indexType === GL.UNSIGNED_INT ? indices.byteLength / 4 :
                indices.byteLength);
        let size = 28 + indices.byteLength;
        for (const block of blocks)
            size += 20 + (block && block.data ? block.data.byteLength : 0);
        const payload = new Uint8Array(size);
        const view = new DataView(payload.buffer);
        view.setUint32(0, mode, true);
        view.setInt32(4, count, true);
        view.setUint32(8, indexType, true);
        view.setUint32(12, indices.byteLength, true);
        view.setUint32(16, 0x544D4143, true);
        view.setUint32(20, (8 | 0x80000000 | 0x40000000) >>> 0, true);
        view.setUint32(24, 0, true);
        let at = 28;
        payload.set(indices, at); at += indices.byteLength;
        for (const block of blocks) {
            const data = block && block.data ? block.data : null;
            view.setUint32(at, block ? 1 : 0, true);
            view.setInt32(at + 4, block ? block.size : 0, true);
            view.setUint32(at + 8, block ? block.type : 0, true);
            view.setInt32(at + 12, block ? (block.stride || 0) : 0, true);
            view.setUint32(at + 16, data ? data.byteLength : 0, true);
            at += 20;
            if (data) { payload.set(data, at); at += data.byteLength; }
        }
        return this.record(GLFN.DRAW_ELEMENTS, payload);
    }

    /*
     * The GL2 variants. The guest switches to these the moment any generic
     * vertex attribute array is enabled: same layout, plus a generic-attribute
     * count in the header and a block per enabled attribute after the
     * conventional ones. Each generic block is seven words -- index,
     * normalized, enabled, size, type, stride, byte count -- then its data.
     */
    drawElementsGL2(mode, indices, indexType, arrays, generics) {
        return this.packedGL2Draw(mode, indices, indexType, arrays,
            generics || []);
    }

    drawArraysGL2(mode, count, arrays, generics) {
        return this.packedGL2Draw(mode, count, null, arrays, generics || []);
    }

    packedGL2Draw(mode, indicesOrCount, indexType, arrays, generics) {
        if (indexType !== null)
            indicesOrCount = new Uint8Array(indicesOrCount.buffer,
                indicesOrCount.byteOffset, indicesOrCount.byteLength);
        const order = ["vertex", "color", "normal",
            "texCoord0", "texCoord1", "texCoord2", "texCoord3",
            "texCoord4", "texCoord5", "texCoord6", "texCoord7",
            "secondaryColor", "fogCoord"];
        const indexed = indexType !== null;
        const indices = indexed ? indicesOrCount : null;
        const count = indexed ?
            (indexType === GL.UNSIGNED_SHORT ? indices.byteLength / 2 :
                (indexType === GL.UNSIGNED_INT ? indices.byteLength / 4 :
                    indices.byteLength)) : indicesOrCount;
        const blocks = order.map(name => arrays[name] || null);
        const headerBytes = indexed ? 32 : 24;
        let size = headerBytes + (indexed ? indices.byteLength : 0);
        for (const block of blocks)
            size += 20 + (block && block.data ? block.data.byteLength : 0);
        for (const generic of generics)
            size += 28 + (generic.data ? generic.data.byteLength : 0);
        const payload = new Uint8Array(size);
        const view = new DataView(payload.buffer);
        view.setUint32(0, mode, true);
        view.setInt32(4, count, true);
        let at = 8;
        if (indexed) {
            view.setUint32(at, indexType, true);
            view.setUint32(at + 4, indices.byteLength, true);
            at += 8;
        }
        view.setUint32(at, 0x544D4143, true);
        view.setUint32(at + 4, (8 | 0x80000000 | 0x40000000) >>> 0, true);
        view.setUint32(at + 8, 0, true);
        view.setUint32(at + 12, generics.length, true);
        at += 16;
        if (indexed) { payload.set(indices, at); at += indices.byteLength; }
        for (const block of blocks) {
            const data = block && block.data ? block.data : null;
            view.setUint32(at, block ? 1 : 0, true);
            view.setInt32(at + 4, block ? block.size : 0, true);
            view.setUint32(at + 8, block ? block.type : 0, true);
            view.setInt32(at + 12, block ? (block.stride || 0) : 0, true);
            view.setUint32(at + 16, data ? data.byteLength : 0, true);
            at += 20;
            if (data) { payload.set(data, at); at += data.byteLength; }
        }
        for (const generic of generics) {
            const data = generic.data || null;
            view.setUint32(at, generic.index, true);
            view.setUint32(at + 4, generic.normalized ? 1 : 0, true);
            view.setUint32(at + 8, 1, true);
            view.setInt32(at + 12, generic.size, true);
            view.setUint32(at + 16, generic.type, true);
            view.setInt32(at + 20, generic.stride || 0, true);
            view.setUint32(at + 24, data ? data.byteLength : 0, true);
            at += 28;
            if (data) { payload.set(data, at); at += data.byteLength; }
        }
        return this.record(indexed ? GLFN.DRAW_ELEMENTS_GL2 :
            GLFN.DRAW_ARRAYS_GL2, payload);
    }
    shaderSource(shader, source) {
        const text = source + "\0";
        const payload = new Uint8Array(8 + text.length);
        const view = new DataView(payload.buffer);
        view.setUint32(0, shader, true);
        view.setUint32(4, text.length, true);
        for (let i = 0; i < text.length; ++i)
            payload[8 + i] = text.charCodeAt(i) & 0xff;
        return this.record(GLFN.SHADER_SOURCE, payload);
    }

    /* {target, size, usage, data_size} then the contents. */
    bufferData(target, byteCount, usage, data) {
        const bytes = data || new Uint8Array(0);
        const payload = new Uint8Array(16 + bytes.byteLength);
        const view = new DataView(payload.buffer);
        view.setUint32(0, target, true);
        view.setInt32(4, byteCount, true);
        view.setUint32(8, usage, true);
        view.setUint32(12, bytes.byteLength, true);
        payload.set(bytes, 16);
        return this.record(GLFN.BUFFER_DATA, payload);
    }

    /* The VBOPointerPayload the guest sends once the array lives in a buffer:
     * no data travels, only where in the bound buffer to read it. */
    pointerVBO(name, size, type, stride, offset) {
        const payload = new Uint8Array(16);
        const view = new DataView(payload.buffer);
        view.setInt32(0, size, true);
        view.setUint32(4, type, true);
        view.setInt32(8, stride, true);
        view.setUint32(12, offset, true);
        return this.record(GLFN[name], payload);
    }

    attribPointerVBO(index, size, type, normalized, stride, offset) {
        const payload = new Uint8Array(24);
        const view = new DataView(payload.buffer);
        view.setUint32(0, index, true);
        view.setInt32(4, size, true);
        view.setUint32(8, type, true);
        view.setUint32(12, normalized ? 1 : 0, true);
        view.setInt32(16, stride, true);
        view.setUint32(20, offset, true);
        return this.record(GLFN.VERTEX_ATTRIB_POINTER_VBO, payload);
    }

    drawElementsDirect(mode, count, type, offset, start, end) {
        const payload = new Uint8Array(24);
        const view = new DataView(payload.buffer);
        view.setUint32(0, mode, true);
        view.setUint32(4, start || 0, true);
        view.setUint32(8, end === undefined ? count : end, true);
        view.setInt32(12, count, true);
        view.setUint32(16, type, true);
        view.setUint32(20, offset, true);
        return this.record(GLFN.DRAW_ELEMENTS_DIRECT, payload);
    }

    /* {target, format, length, reserved} then the assembly text. */
    programStringARB(target, source) {
        const payload = new Uint8Array(16 + source.length);
        const view = new DataView(payload.buffer);
        view.setUint32(0, target, true);
        view.setUint32(4, GL.PROGRAM_FORMAT_ASCII_ARB, true);
        view.setInt32(8, source.length, true);
        for (let i = 0; i < source.length; ++i)
            payload[16 + i] = source.charCodeAt(i) & 0xff;
        return this.record(GLFN.PROGRAM_STRING_ARB, payload);
    }

    /* {kind, target, index, count} then count*4 floats -- the parameter kind
     * leads, and it is 1 for env and 2 for local. */
    programParameterARB(kind, target, index, values) {
        const payload = new Uint8Array(16 + values.length * 4);
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, target, true);
        view.setUint32(8, index, true);
        view.setUint32(12, values.length / 4, true);
        values.forEach((value, i) => view.setFloat32(16 + i * 4, value, true));
        return this.record(GLFN.PROGRAM_PARAMETER_FV_ARB, payload);
    }

    queryProgramParameterARB(kind, target, index) {
        const payload = new Uint8Array(40);
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, target, true);
        view.setUint32(8, index, true);
        view.setUint32(16, 16, true);
        this.record(GLFN.QUERY_PROGRAM_PARAMETER_FV_ARB, payload);
        return this.payloadView();
    }

    queryProgramStringARB(target, capacity) {
        const payload = new Uint8Array(24 + capacity);
        const view = new DataView(payload.buffer);
        view.setUint32(0, target, true);
        view.setUint32(4, GL.PROGRAM_STRING_ARB, true);
        view.setUint32(16, capacity, true);
        this.record(GLFN.QUERY_PROGRAM_STRING_ARB, payload);
        return this.payloadView();
    }

    queryObjectLog(kind, name, capacity) {
        const payload = new Uint8Array(24 + capacity);
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, name, true);
        view.setUint32(8, capacity, true);
        view.setUint32(20, capacity, true);
        this.record(GLFN.QUERY_OBJECT_LOG, payload);
        return this.payloadView();
    }

    queryActive(kind, program, index, capacity) {
        const payload = new Uint8Array(40 + capacity);
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, program, true);
        view.setUint32(8, index, true);
        view.setUint32(12, capacity, true);
        view.setUint32(32, capacity, true);
        this.record(GLFN.QUERY_ACTIVE, payload);
        return this.payloadView();
    }

    queryInteger(pname) {
        const payload = new Uint8Array(16);
        new DataView(payload.buffer).setUint32(0, pname, true);
        this.record(GLFN.QUERY_INTEGER, payload);
        return this.payloadView();
    }

    queryError() {
        const payload = new Uint8Array(16);
        this.record(GLFN.QUERY_ERROR, payload);
        return this.payloadView();
    }

    queryString(pname, capacity) {
        const payload = new Uint8Array(16 + capacity);
        const view = new DataView(payload.buffer);
        view.setUint32(0, pname, true);
        view.setUint32(12, capacity, true);
        this.record(GLFN.QUERY_GL_STRING, payload);
        return this.payloadView();
    }

    queryLocation(kind, program, name, capacity) {
        const text = name + "\0";
        const payload = new Uint8Array(32 + Math.max(capacity || 0, text.length));
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, program, true);
        view.setUint32(28, text.length, true);
        for (let i = 0; i < text.length; ++i)
            payload[32 + i] = text.charCodeAt(i) & 0xff;
        this.record(GLFN.QUERY_LOCATION, payload);
        return this.payloadView();
    }

    queryObjectiv(kind, name, pname) {
        const payload = new Uint8Array(24);
        const view = new DataView(payload.buffer);
        view.setUint32(0, kind, true);
        view.setUint32(4, name, true);
        view.setUint32(8, pname, true);
        this.record(GLFN.QUERY_OBJECT_IV, payload);
        return this.payloadView();
    }

    uniformfv(location, components, count, values) {
        const payload = new Uint8Array(12 + values.length * 4);
        const view = new DataView(payload.buffer);
        view.setInt32(0, location, true);
        view.setInt32(4, components, true);
        view.setInt32(8, count, true);
        values.forEach((value, i) => view.setFloat32(12 + i * 4, value, true));
        return this.record(GLFN.UNIFORM_FV, payload);
    }

    uniformiv(location, components, count, values) {
        const payload = new Uint8Array(12 + values.length * 4);
        const view = new DataView(payload.buffer);
        view.setInt32(0, location, true);
        view.setInt32(4, components, true);
        view.setInt32(8, count, true);
        values.forEach((value, i) => view.setInt32(12 + i * 4, value | 0, true));
        return this.record(GLFN.UNIFORM_IV, payload);
    }

    bytes() {
        return this.buffer.subarray(0, this.length);
    }
}

if (typeof module !== "undefined" && module.exports)
    module.exports = { GLStream, GL, GLFN };
else
    globalThis.GLTestStream = { GLStream, GL, GLFN };
                                                                                                                                                                                                                                          source/v64/tests/glbridge/gl_webgpu_browser_test.html                                               0000644 0000000 0000000 00000012012 00000000000 020244  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GL WebGPU browser test</title>
<canvas id="gpu" width="96" height="64"></canvas>
<pre id="result">RUNNING</pre>
<script src="../../src/browser/glbridge/webgpu_host.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_constants.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_wire.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_state_layout.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_fixed_function.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_arb_program.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_executor.js"></script>
<script>
(async () => {
    const C = GLWGConstants;
    const GL = C.GL;
    const records = [];
    function record(opcode, payload) {
        payload = payload || new Uint8Array(0);
        const extended = payload.byteLength > 0xfffe;
        const result = new Uint8Array((extended ? 8 : 4) + payload.byteLength);
        const view = new DataView(result.buffer);
        view.setUint16(0, opcode, true);
        view.setUint16(2, extended ? 0xffff : payload.byteLength, true);
        if (extended) view.setUint32(4, payload.byteLength, true);
        result.set(payload, extended ? 8 : 4);
        records.push(result);
    }
    function call(name, ...args) {
        const types = GLWireFormat.SIGNATURES[name][1];
        const payload = new Uint8Array(GLWireFormat.payloadBytes(types));
        const view = new DataView(payload.buffer);
        let at = 0;
        for (let i = 0; i < types.length; ++i) {
            const value = args[i] === undefined ? 0 : args[i];
            if (types[i] === "i") view.setInt32(at, value | 0, true);
            else if (types[i] === "u") view.setUint32(at, value >>> 0, true);
            else if (types[i] === "f") view.setFloat32(at, value, true);
            else { view.setFloat64(at, value, true); at += 4; }
            at += 4;
        }
        record(C.GLFN[name], payload);
    }
    function makeCurrent() {
        const payload = new Uint8Array(20);
        const view = new DataView(payload.buffer);
        view.setUint32(0, 1, true);
        view.setUint32(12, 96, true);
        view.setUint32(16, 64, true);
        record(C.CTRL.MAKE_CURRENT, payload);
    }
    function drawPixels() {
        const pixels = new Uint8Array(4 * 4 * 4);
        for (let i = 0; i < pixels.length; i += 4)
            pixels.set([255, 64, 16, 255], i);
        const payload = new Uint8Array(20 + pixels.byteLength);
        const view = new DataView(payload.buffer);
        view.setInt32(0, 4, true);
        view.setInt32(4, 4, true);
        view.setUint32(8, GL.RGBA, true);
        view.setUint32(12, GL.UNSIGNED_BYTE, true);
        view.setUint32(16, pixels.byteLength, true);
        payload.set(pixels, 20);
        record(C.GLFN.DRAW_PIXELS, payload);
    }
    function concat() {
        const length = records.reduce((sum, item) => sum + item.byteLength, 0);
        const bytes = new Uint8Array(length);
        let at = 0;
        for (const item of records) { bytes.set(item, at); at += item.byteLength; }
        return bytes;
    }

    makeCurrent();
    call("CLEAR_COLOR", 0.08, 0.12, 0.2, 1);
    call("CLEAR", GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);
    call("ENABLE", GL.COLOR_LOGIC_OP);
    call("LOGIC_OP", GL.XOR);
    call("BEGIN", GL.TRIANGLES);
    call("COLOR4F", 1, 0.2, 0.1, 1);
    call("VERTEX3F", -0.8, -0.7, 0);
    call("VERTEX3F", 0.8, -0.7, 0);
    call("VERTEX3F", 0, 0.8, 0);
    call("END");
    call("DISABLE", GL.COLOR_LOGIC_OP);
    call("CLEAR_ACCUM", 0, 0, 0, 0);
    call("CLEAR", GL.ACCUM_BUFFER_BIT);
    call("ACCUM", 0x0101, 1); // GL_LOAD
    call("ACCUM", 0x0103, 0.5); // GL_MULT
    call("ACCUM", 0x0104, 0.1); // GL_ADD
    call("ACCUM", 0x0102, 1); // GL_RETURN
    call("WINDOW_POS3F", 6, 6, 0);
    drawPixels();

    const executor = new GLWebGPUExecutorModule.GLWebGPUExecutor(
        document.getElementById("gpu"));
    await executor.initialize();
    const errors = [];
    executor.device.addEventListener("uncapturederror", event =>
        errors.push(String(event.error && event.error.message || event.error)));
    executor.device.pushErrorScope("validation");
    executor.submit(concat(), {});
    executor.onSwapBuffers();
    await executor.device.queue.onSubmittedWorkDone();
    const scoped = await executor.device.popErrorScope();
    if (scoped) errors.push(scoped.message);
    const stats = executor.getStats();
    if (errors.length || stats.refusals || stats.draws !== 2)
        throw new Error(JSON.stringify({ errors, stats }));
    document.getElementById("result").textContent = "PASS " +
        JSON.stringify({ draws: stats.draws, pipelines: stats.pipelines });
    document.title = "PASS gl_webgpu_browser_test";
})().catch(error => {
    document.getElementById("result").textContent = "FAIL " + error.stack;
    document.title = "FAIL gl_webgpu_browser_test";
    console.error(error);
});
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/glbridge/gles3_executor_browser_test.html                                          0000644 0000000 0000000 00000310423 00000000000 021233  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLES executor: GLES 3.0 on WebGPU</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The GLES executor's GLES 3.0 draws (src/gles/page/gles3_executor.js;
// docs/gles3-plan.md L3) on a real GPU: a GLES 3.0 context's commands
// encoded as the guest's, run first through a CPU side's shadow state with
// glslang (as gles_host.js does: a link's result goes to the page before
// its glLinkProgram), then as batches on the executor, pixels read back:
// - a vertex array object, an instanced array, a uniform block, a matrix
//   uniform, integer attributes, GL's depth range (a negative z drawn);
// - textures: R8, RGBA16F from floats, a 2D array's layer, an unsigned
//   integer texture fetched, a sampler object's filter over the texture's;
// - two draw buffers, glClearBufferfv, glReadBuffer;
// - a depth texture drawn to and sampled by a shadow sampler;
// - indices: a strip with restarts from client memory and from a buffer,
//   a fan from a buffer.
import { encode_command } from "../../src/gles/gles_wire.js";
import { GLES, GLES_MAGIC, GXWriter } from "../../src/graphics_adapters/renderer_protocol.js";
import { GLESShadow } from "../../src/gles/gles_shadow.js";
import { compile_glslang, create_glslang } from "../../src/gles/glslang.js";
import { pack_program } from "../../src/gles/glsl_program.js";
import { read_gles_batch } from "../../src/gles/gles_batch.js";
import { CONFIGS } from "../../src/gles/gles_caps.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };

(async () => {
    try {
        const adapter = await navigator.gpu.requestAdapter();
        const optional = ["texture-compression-etc2", "texture-compression-astc", "texture-component-swizzle"].filter(f => adapter.features.has(f));
        const device = await adapter.requestDevice({ requiredFeatures: optional });
        checks.push("the adapter's optional features: " + optional.join(", "));
        const errors = [];
        device.onuncapturederror = e => { console.error(e.error.message); errors.push(e.error.message); };
        let executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        globalThis.glesExecutor = executor;
        globalThis.webgpuErrors = errors;

        // the CPU side: a shadow state with glslang, as the GLES host's
        const glslang = await create_glslang(await compile_glslang(new Uint8Array(await (await fetch("../../bios/glslang.wasm")).arrayBuffer())));
        const cpu = new GLESShadow({ images: new Map(), color_buffers: new Map(), max_version: 30 });
        cpu.glslang = glslang;
        cpu.keep_bytes = true;

        let writer = new GXWriter(GLES_MAGIC);
        let request = 1;
        const answers = new Map();
        let current = 1;
        const call = (name, ret, args) => {
            const bytes = encode_command("gles2:" + name, args);
            const one = new GXWriter(GLES_MAGIC);
            one.command(GLES.COMMAND, [1, ret, bytes.length], bytes);
            const [r] = read_gles_batch(one.finish(), true);
            cpu.given_name = ret;
            const { keep } = cpu.call(current, r.command, r.args);
            cpu.given_name = 0;
            if(keep && (name === "glLinkProgram" || name === "glCreateShaderProgramvAEMU") && cpu.last_link) {
                const packed = pack_program(cpu.last_link);
                writer.command(GLES.PROGRAM_LINK, [1, name === "glLinkProgram" ? args[0] : ret, packed.length], packed);
                cpu.last_link = null;
            }
            // (what only asks or names stays on the CPU side, as gles_host.js's is_query)
            const error = cpu.context(current).error;
            check(keep || /^gl(Get|Is|Gen|MapBufferRange)/.test(name) && !error, name + " is taken (error 0x" + (error || 0).toString(16) + ")");
            checks.pop();
            if(keep) writer.command(GLES.COMMAND, [1, ret, bytes.length], bytes);
        };
        const gl = (name, ...args) => call(name, 0, args);
        const record = (op, ...dwords) => writer.command(op, dwords);
        const run = async () => {
            const bytes = writer.finish();
            await executor.submit(bytes, {
                writeResponse: (offset, data) => {
                    const view = new DataView(data.buffer, data.byteOffset);
                    answers.set(view.getUint32(0, true), view.getUint32(12, true) === 1 ? data.slice(16) : null);
                },
            });
            await device.queue.onSubmittedWorkDone();
            check(!executor.stats.errors.length, "no executor errors: " + executor.stats.errors.join("; "));
            checks.pop();
        };
        const read_pixels = async (x, y, w, h) => {
            const id = request++;
            record(GLES.READ_PIXELS, 1, id, x, y, w, h, 0x1908, 0x1401);
            await run();
            return answers.get(id);
        };
        const pixel = (rgba, w, x, y) => { globalThis.lastPixels = Array.from(rgba || []); return Array.from(rgba.subarray((y * w + x) * 4, (y * w + x) * 4 + 4)); };
        const near = (a, b, tolerance = 3) => a.every((v, i) => Math.abs(v - b[i]) <= tolerance);
        const text = s => new TextEncoder().encode(s + "\0");
        const floats = values => new Uint8Array(new Float32Array(values).buffer);
        const ints = values => new Uint8Array(new Int32Array(values).buffer);
        // (glGen*'s names: each kind's from 1, as both shadows make them)
        const names = new Map();
        const gen = kind => { const name = (names.get(kind) || 0) + 1; names.set(kind, name); gl("glGen" + kind, 1, 4); return name; };
        let shader_name = 100;
        const program = (vs_text, fs_text, varyings) => {
            const vs = shader_name++, fs = shader_name++, p = shader_name++;
            call("glCreateShader", vs, [0x8B31]);
            call("glCreateShader", fs, [0x8B30]);
            gl("glShaderString", vs, text(vs_text), vs_text.length + 1);
            gl("glShaderString", fs, text(fs_text), fs_text.length + 1);
            gl("glCompileShader", vs);
            gl("glCompileShader", fs);
            call("glCreateProgram", p, []);
            gl("glAttachShader", p, vs);
            gl("glAttachShader", p, fs);
            if(varyings) gl("glTransformFeedbackVaryingsAEMU", p, varyings.length, text(varyings.join(";")), varyings.join(";").length + 1, 0x8C8C);
            gl("glLinkProgram", p);
            const info = cpu.context(current).group.objects.get(p).info;
            check(info && info.ok, "linked: " + (info && info.log));
            checks.pop();
            gl("glUseProgram", p);
            return { name: p, at: uniform => info.locations.get(uniform), attribute: a => info.attributes.find(x => x.name === a).location };
        };

        // a GLES 3.0 context on an 8 by 8 window (RGBA8888, depth 24, stencil 8: config 3)
        const W = 8;
        record(GLES.CONTEXT_CREATE, 1, 3, 0, 30);
        record(GLES.SURFACE_CREATE, 2, 3, W, W);
        record(GLES.COLOR_BUFFER_CREATE, 3, W, W, 0x1908);
        record(GLES.SURFACE_COLOR_BUFFER, 2, 3);
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        cpu.create_context(1, 30, 0);
        cpu.make_current(1, { width: W, height: W, config: CONFIGS[3] });

        // ---- a vertex array object; an instanced array; a uniform block; GL's depth
        const quads = program(`#version 300 es
            layout(location = 0) in vec2 position;
            layout(location = 1) in vec4 color;
            layout(location = 2) in vec2 offset;
            layout(location = 3) in ivec2 code;
            uniform mat2 scale;
            uniform float depth;
            out vec4 v_color;
            flat out ivec2 v_code;
            void main() { v_color = color; v_code = code; gl_Position = vec4(scale * position + offset, depth, 1.0); }`, `#version 300 es
            precision mediump float;
            layout(std140) uniform Tint { vec4 tint; float gain; };
            in vec4 v_color;
            flat in ivec2 v_code;
            out vec4 o;
            void main() { o = v_color * tint * gain; if(v_code.x == 7 && v_code.y == -2) o.b = 1.0; }`);
        const vao = gen("VertexArrays");
        gl("glBindVertexArray", vao);
        const vertices = gen("Buffers");
        gl("glBindBuffer", 0x8892, vertices);
        // (a strip: position, color, a byte code each)
        const strip = new ArrayBuffer(4 * 28), sv = new DataView(strip);
        [[-1, -1], [1, -1], [-1, 1], [1, 1]].forEach(([x, y], i) => {
            [x, y, 1, 0.5, 0, 1].forEach((v, k) => sv.setFloat32(i * 28 + 4 * k, v, true));
            sv.setInt8(i * 28 + 24, 7);
            sv.setInt8(i * 28 + 25, -2);
        });
        gl("glBufferData", 0x8892, strip.byteLength, new Uint8Array(strip), 0x88E4);
        gl("glEnableVertexAttribArray", 0);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 28, 0);
        gl("glEnableVertexAttribArray", 1);
        gl("glVertexAttribPointerOffset", 1, 4, 0x1406, 0, 28, 8);
        gl("glEnableVertexAttribArray", 3);
        gl("glVertexAttribIPointerOffsetAEMU", 3, 2, 0x1400, 28, 24);
        const instances = gen("Buffers");
        gl("glBindBuffer", 0x8892, instances);
        gl("glBufferData", 0x8892, 16, floats([-0.5, 0, 0.5, 0]), 0x88E4);
        gl("glEnableVertexAttribArray", 2);
        gl("glVertexAttribPointerOffset", 2, 2, 0x1406, 0, 0, 0);
        gl("glVertexAttribDivisor", 2, 1);
        const ubo = gen("Buffers");
        gl("glBindBuffer", 0x8A11, ubo);
        gl("glBufferData", 0x8A11, 32, floats([0.5, 1, 1, 1, 2, 0, 0, 0]), 0x88E4);
        gl("glBindBufferBase", 0x8A11, 0, ubo);
        gl("glUniformMatrix2fv", quads.at("scale"), 1, 0, floats([0.25, 0, 0, 0.25]));
        gl("glUniform1f", quads.at("depth"), 0);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000 | 0x0100);
        gl("glDrawArraysInstanced", 5, 0, 4, 2);
        let window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 2, 4), [255, 255, 255, 255]), "instance 0: the vertex array's color through the uniform block, the integer attribute's blue");
        check(near(pixel(window, W, 6, 4), [255, 255, 255, 255]) && near(pixel(window, W, 4, 4), [0, 0, 0, 255]), "instance 1 by its divisor, nothing between");

        // GL's depth: z -0.5 is drawn (WebGPU's own range would clip it), z 0.8 behind z 0.5 fails the test
        gl("glUniformMatrix2fv", quads.at("scale"), 1, 0, floats([4, 0, 0, 4]));
        gl("glEnable", 0x0B71);
        gl("glClear", 0x4000 | 0x0100);
        gl("glUniform1f", quads.at("depth"), 0.5);
        gl("glBufferSubData", 0x8A11, 0, 16, floats([1, 0, 0, 0.5]));
        gl("glDrawArrays", 5, 0, 4);
        gl("glUniform1f", quads.at("depth"), 0.8);
        gl("glBufferSubData", 0x8A11, 0, 16, floats([0, 1, 0, 0.5]));
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [255, 0, 255, 255]), "z 0.8 behind z 0.5: still the first draw (a buffer's new bytes reached the GPU)");
        gl("glUniform1f", quads.at("depth"), -0.5);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [0, 255, 255, 255]), "z -0.5 in front, drawn: GL's clip space depth");
        gl("glDisable", 0x0B71);
        // a disabled attribute's current value: the context's, set while another vertex array was bound (GLES 3.0 table 6.6)
        gl("glBindVertexArray", 0);
        gl("glVertexAttrib4f", 1, 1, 0.25, 0, 1);
        gl("glBindVertexArray", vao);
        gl("glDisableVertexAttribArray", 1);
        gl("glUniform1f", quads.at("depth"), 0);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [0, 128, 255, 255]), "a disabled attribute's current value set under another vertex array: " +
            pixel(window, W, 1, 1));
        gl("glEnableVertexAttribArray", 1);
        gl("glBindVertexArray", 0);

        // ---- textures
        const textured = program(`#version 300 es
            layout(location = 0) in vec2 position;
            out vec2 uv;
            void main() { uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            uniform sampler2D red;
            uniform sampler2D half_floats;
            uniform mediump sampler2DArray layers;
            uniform highp usampler2D counts;
            uniform int which;
            in vec2 uv;
            out vec4 o;
            void main() {
                if(which == 0) o = vec4(texture(red, uv).r, 0.0, 0.0, 1.0);
                else if(which == 1) o = texture(half_floats, uv);
                else if(which == 2) o = texture(layers, vec3(uv, 1.0));
                else o = vec4(float(texelFetch(counts, ivec2(0, 0), 0).r) / 255.0, 0.0, 0.0, 1.0);
            }`);
        const full = floats([-1, -1, 1, -1, -1, 1, 1, 1]);
        gl("glEnableVertexAttribArray", 0);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, full, full.length);
        gl("glDisableVertexAttribArray", 1);
        gl("glDisableVertexAttribArray", 2);
        gl("glDisableVertexAttribArray", 3);
        let next_texture = 1;
        const texture = (unit, target) => { const t = next_texture++; gl("glActiveTexture", 0x84C0 + unit); gl("glBindTexture", target, t); return t; };
        // R8 (2 by 1: 255, 0), nearest; a sampler object on unit 0 makes it linear
        texture(0, 0x0DE1);
        gl("glPixelStorei", 0x0CF5, 1);
        gl("glTexImage2D", 0x0DE1, 0, 0x8229, 2, 1, 0, 0x1903, 0x1401, new Uint8Array([255, 0]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2802, 0x812F);
        gl("glUniform1i", textured.at("red"), 0);
        // RGBA16F from floats
        texture(1, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x881A, 1, 1, 0, 0x1908, 0x1406, floats([0.25, 0.5, 0.75, 1]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glUniform1i", textured.at("half_floats"), 1);
        // a 2D array of two layers, RGBA8
        texture(2, 0x8C1A);
        gl("glTexImage3D", 0x8C1A, 0, 0x8058, 1, 1, 2, 0, 0x1908, 0x1401, new Uint8Array([255, 0, 0, 255, 0, 0, 255, 255]));
        gl("glTexParameteri", 0x8C1A, 0x2801, 0x2600);
        gl("glUniform1i", textured.at("layers"), 2);
        // R32UI, fetched
        texture(3, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x8236, 1, 1, 0, 0x8D94, 0x1405, ints([128]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glUniform1i", textured.at("counts"), 3);
        const which = async (n, x = 3, y = 4) => {
            gl("glUniform1i", textured.at("which"), n);
            gl("glDrawArrays", 5, 0, 4);
            return pixel(await read_pixels(0, 0, W, W), W, x, y);
        };
        check(near(await which(0, 1), [255, 0, 0, 255]) && near(await which(0, 6), [0, 0, 0, 255]), "R8, nearest");
        const sampler = gen("Samplers");
        gl("glBindSampler", 0, sampler);
        gl("glSamplerParameteri", sampler, 0x2801, 0x2601);
        gl("glSamplerParameteri", sampler, 0x2800, 0x2601);
        gl("glSamplerParameteri", sampler, 0x2802, 0x812F);
        const mid = await which(0, 4);
        check(mid[0] > 64 && mid[0] < 192, "a sampler object's linear filter over the texture's nearest: " + mid);
        gl("glBindSampler", 0, 0);
        check(near(await which(1), [64, 128, 191, 255]), "RGBA16F from floats");
        check(near(await which(2), [0, 0, 255, 255]), "a 2D array's layer 1");
        check(near(await which(3), [128, 0, 0, 255]), "an unsigned integer texture, fetched");
        // an integer texture sampled (texture(), not texelFetch) by both stages, its sampler's REPEAT: coordinate -0.6 of
        // four texels is texel -3, wrapped to 1 (20): not the clamped 0 (10), nor a remainder's -3 (out of the image)
        texture(4, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x8236, 4, 1, 0, 0x8D94, 0x1405, ints([10, 20, 30, 40]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        // (and a 2D array's layer 1: 50 to 80)
        texture(5, 0x8C1A);
        gl("glTexImage3D", 0x8C1A, 0, 0x8236, 4, 1, 2, 0, 0x8D94, 0x1405, ints([10, 20, 30, 40, 50, 60, 70, 80]));
        gl("glTexParameteri", 0x8C1A, 0x2801, 0x2600);
        gl("glTexParameteri", 0x8C1A, 0x2800, 0x2600);
        const repeated = program(`#version 300 es
            layout(location = 0) in vec2 position;
            uniform highp usampler2D u;
            out float from_vertex;
            void main() { from_vertex = float(texture(u, vec2(-0.6, 0.5)).r); gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            uniform highp usampler2D u;
            uniform highp usampler2DArray ua;
            in float from_vertex;
            out vec4 o;
            void main() { o = vec4(float(texture(u, vec2(-0.6, 0.5)).r) / 255.0, from_vertex / 255.0, float(texture(ua, vec3(-0.6, 0.5, 1.0)).r) / 255.0, 1.0); }`);
        gl("glUniform1i", repeated.at("u"), 4);
        gl("glUniform1i", repeated.at("ua"), 5);
        gl("glDrawArrays", 5, 0, 4);
        const repeat_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(repeat_pixel, [20, 20, 60, 255]), "integer textures sampled where their samplers repeat, in both stages, a 2D array's too: " + repeat_pixel);
        gl("glUseProgram", textured.name);
        // textureSize of a level past the base where the filter takes no mipmaps (the view holds the base alone): 8 by 4 at lod 2 is 2 by 1
        texture(6, 0x0DE1);
        for(let level = 0; level < 4; level++) gl("glTexImage2D", 0x0DE1, level, 0x8058, 8 >> level, Math.max(1, 4 >> level), 0, 0x1908, 0x1401, null);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        const sized = program(`#version 300 es
            layout(location = 0) in vec2 position;
            uniform highp sampler2D s;
            uniform int lod;
            out vec4 size_color;
            void main() { size_color = vec4(vec2(textureSize(s, lod)) / 255.0, 0.0, 1.0); gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            in vec4 size_color;
            out vec4 o;
            void main() { o = size_color; }`);
        gl("glUniform1i", sized.at("s"), 6);
        gl("glUniform1i", sized.at("lod"), 2);
        gl("glDrawArrays", 5, 0, 4);
        const size_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(size_pixel, [2, 1, 0, 255]), "textureSize of level 2 with a filter of no mipmaps: " + size_pixel);
        // atan(y, 0) and tanh past 10, which Chrome's Metal compiler gets wrong: pi/2 (its half, 200 of 255) and 1
        const guarded = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            uniform float y, x, t;
            out vec4 o;
            void main() { vec2 a = atan(vec2(y, -y), vec2(x, x)); o = vec4(a.x / 3.14159265, tanh(t), (a.y / -3.14159265) * tanh(vec2(-t, t)).y, 1.0); }`);
        gl("glUniform1f", guarded.at("y"), 1);
        gl("glUniform1f", guarded.at("x"), 0);
        gl("glUniform1f", guarded.at("t"), 50);
        gl("glDrawArrays", 5, 0, 4);
        const guard_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(guard_pixel, [128, 255, 128, 255]), "atan(±1, 0) of vectors is ±pi/2, tanh(50) is 1: " + guard_pixel);
        // a color format GL reads with alpha 1 (RGB8, kept as rgba8unorm): cleared with alpha 0, drawn with alpha 0, read with alpha 1,
        // blitted into RGBA8 with alpha 1
        const rgb_fbo = gen("Framebuffers"), rgba_fbo = gen("Framebuffers");
        const rgb_texture = texture(7, 0x0DE1);
        gl("glTexStorage2D", 0x0DE1, 1, 0x8051, W, W);
        gl("glBindFramebuffer", 0x8D40, rgb_fbo);
        gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x0DE1, rgb_texture, 0);
        gl("glClearBufferfv", 0x1800, 0, floats([0.5, 0, 0, 0]));
        const rgb_cleared = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        const zero_alpha = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            out vec4 o;
            void main() { o = vec4(0.0, 1.0, 0.0, 0.0); }`);
        void zero_alpha;
        gl("glDrawArrays", 5, 0, 4);
        const rgb_drawn = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        const rgba_texture = texture(7, 0x0DE1);
        gl("glTexStorage2D", 0x0DE1, 1, 0x8058, W, W);
        gl("glBindFramebuffer", 0x8D40, rgba_fbo);
        gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x0DE1, rgba_texture, 0);
        gl("glBindFramebuffer", 0x8CA8, rgb_fbo);
        gl("glBlitFramebuffer", 0, 0, W, W, 0, 0, W, W, 0x4000, 0x2600);
        gl("glBindFramebuffer", 0x8CA8, rgba_fbo);
        const rgb_blitted = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        gl("glBindFramebuffer", 0x8D40, 0);
        check(near(rgb_cleared, [128, 0, 0, 255]) && near(rgb_drawn, [0, 255, 0, 255]) && near(rgb_blitted, [0, 255, 0, 255]),
            "RGB8 read with alpha 1, cleared, drawn and blitted: " + [rgb_cleared, rgb_drawn, rgb_blitted].join(" / "));
        // a depth and stencil renderbuffer attached as the stencil alone: no depth buffer, so the depth test passes (depth 0 cleared, LESS)
        const ds_fbo = gen("Framebuffers"), ds_color = gen("Renderbuffers"), ds_rb = gen("Renderbuffers");
        gl("glBindRenderbuffer", 0x8D41, ds_color);
        gl("glRenderbufferStorage", 0x8D41, 0x8058, W, W);
        gl("glBindRenderbuffer", 0x8D41, ds_rb);
        gl("glRenderbufferStorage", 0x8D41, 0x88F0, W, W);
        gl("glBindFramebuffer", 0x8D40, ds_fbo);
        gl("glFramebufferRenderbuffer", 0x8D40, 0x8CE0, 0x8D41, ds_color);
        gl("glFramebufferRenderbuffer", 0x8D40, 0x8D20, 0x8D41, ds_rb);
        gl("glClearBufferfv", 0x1800, 0, floats([0, 0, 1, 1]));
        gl("glClearBufferfi", 0x84F9, 0, 0, 0);
        gl("glUseProgram", zero_alpha.name);
        gl("glEnable", 0x0B71);
        gl("glDrawArrays", 5, 0, 4);
        gl("glDisable", 0x0B71);
        const stencil_alone = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        // a blit whose source's left half is outside its image: that half of the destination left as it was (blue)
        gl("glBindFramebuffer", 0x8D40, rgba_fbo);
        gl("glClearBufferfv", 0x1800, 0, floats([0, 0, 1, 1]));
        gl("glBindFramebuffer", 0x8CA8, ds_fbo);
        gl("glBlitFramebuffer", -W, 0, W, W, 0, 0, W, W, 0x4000, 0x2600);
        gl("glBindFramebuffer", 0x8CA8, rgba_fbo);
        const blit_window = await read_pixels(0, 0, W, W);
        gl("glBindFramebuffer", 0x8D40, 0);
        // a uniform block's instance array (two blocks, a binding point each) beside a sampler, in a shared layout (std140 here)
        const block_instances = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            layout(shared) uniform Tint { mediump mat2 m; float f; vec4 color; } tints[2];
            uniform sampler2D red;
            out vec4 o;
            void main() { o = vec4(texture(red, vec2(0.25, 0.5)).r * tints[1].color.r, tints[0].color.g * tints[1].f, tints[1].m[1].y, 1.0); }`);
        const tint_buffer = gen("Buffers");
        gl("glBindBuffer", 0x8A11, tint_buffer);
        // (std140: m at 0, columns 16 apart; f at 32; color at 48; a block 64 bytes, the second at 256)
        const tints = new Float32Array(64 + 16);
        tints.set([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], 0);
        tints.set([0, 0.5, 0, 0], 48 / 4);
        tints.set([0, 0, 0, 0, 0, 0.75, 0, 0, 0.5, 0, 0, 0, 1, 0, 0, 0], 256 / 4);
        gl("glBufferData", 0x8A11, tints.byteLength, new Uint8Array(tints.buffer), 0x88E4);
        // (Tint[0] and Tint[1]: blocks 0 and 1)
        gl("glUniformBlockBinding", block_instances.name, 0, 2);
        gl("glUniformBlockBinding", block_instances.name, 1, 3);
        gl("glBindBufferRange", 0x8A11, 2, tint_buffer, 0, 64);
        gl("glBindBufferRange", 0x8A11, 3, tint_buffer, 256, 64);
        gl("glUniform1i", block_instances.at("red"), 0);
        gl("glActiveTexture", 0x84C0);
        gl("glBindTexture", 0x0DE1, 1);
        gl("glDrawArrays", 5, 0, 4);
        const instance_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(instance_pixel, [255, 64, 191, 255]), "a uniform block's instance array beside a sampler: " + instance_pixel);
        // a flat varying takes the primitive's last vertex's value (GL's provoking vertex; WebGPU's is the first): blue
        const flat_program = program(`#version 300 es
            layout(location = 0) in vec2 position;
            layout(location = 1) in vec4 color;
            flat out vec4 c;
            void main() { c = color; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            flat in vec4 c;
            out vec4 o;
            void main() { o = c; }`);
        void flat_program;
        const big_triangle = floats([-1, -1, 3, -1, -1, 3]);
        const corner_colors = floats([1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1]);
        gl("glBindBuffer", 0x8892, 0);
        gl("glEnableVertexAttribArray", 0);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, big_triangle, big_triangle.length);
        gl("glEnableVertexAttribArray", 1);
        gl("glVertexAttribPointerData", 1, 4, 0x1406, 0, 0, corner_colors, corner_colors.length);
        gl("glDrawArrays", 4, 0, 3);
        const provoked = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        gl("glDisableVertexAttribArray", 1);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, full, full.length);
        check(near(provoked, [0, 0, 255, 255]), "a flat varying, the last vertex's: " + provoked);
        // a vertex shader's instance array of a block of 84 bytes (not a whole number of 16), a buffer of 84 bytes each element
        const odd_blocks = program(`#version 300 es
            layout(location = 0) in vec2 position;
            layout(std140) uniform BlockB { mediump mat3 a; lowp ivec2 b; highp vec4 c; bool d; } blockB[2];
            out vec4 color;
            void main() { color = vec4(blockB[1].a[2].z, float(blockB[1].b.y) / 255.0, blockB[0].d ? 1.0 : 0.0, 1.0); gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            in vec4 color;
            out vec4 o;
            void main() { o = color; }`);
        const odd_buffers = [gen("Buffers"), gen("Buffers")];
        [[0, 0, 1], [0.75, 128, 0]].forEach(([z, y, d], i) =>
        {
            const bytes = new ArrayBuffer(84);
            new Float32Array(bytes, 40, 1)[0] = z;
            new Int32Array(bytes, 52, 1)[0] = y;
            new Uint32Array(bytes, 80, 1)[0] = d;
            gl("glBindBuffer", 0x8A11, odd_buffers[i]);
            gl("glBufferData", 0x8A11, 84, new Uint8Array(bytes), 0x88E4);
            gl("glUniformBlockBinding", odd_blocks.name, i, 4 + i);
            gl("glBindBufferBase", 0x8A11, 4 + i, odd_buffers[i]);
        });
        gl("glDrawArrays", 5, 0, 4);
        const odd_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(odd_pixel, [191, 128, 255, 255]), "a vertex shader's instance array of 84-byte blocks: " + odd_pixel);
        // RASTERIZER_DISCARD: clears ignored too
        gl("glEnable", 0x8C89);
        gl("glClearColor", 1, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glClearBufferfv", 0x1800, 0, floats([1, 0, 0, 1]));
        gl("glDisable", 0x8C89);
        const discarded = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        check(near(discarded, odd_pixel), "clears ignored while RASTERIZER_DISCARD is on: " + discarded);
        check(near(stencil_alone, [0, 255, 0, 0]) && near(pixel(blit_window, W, 1, 3), [0, 0, 255, 255]) && near(pixel(blit_window, W, 6, 3), [0, 255, 0, 0]),
            "the depth test passes with the stencil attached alone; a blit's pixels from outside its source left alone: " +
            [stencil_alone, pixel(blit_window, W, 1, 3), pixel(blit_window, W, 6, 3)].join(" / "));
        gl("glUseProgram", textured.name);
        gl("glUseProgram", textured.name);

        const flat = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            out vec4 o;
            void main() { o = vec4(1.0, 1.0, 0.0, 1.0); }`);
        gl("glUseProgram", textured.name);

        // ---- two draw buffers
        const mrt = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            layout(location = 0) out vec4 first;
            layout(location = 1) out vec4 second;
            void main() { first = vec4(1.0, 0.0, 0.0, 1.0); second = vec4(0.0, 1.0, 0.0, 1.0); }`);
        void mrt;
        const fbo = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, fbo);
        const targets = [texture(4, 0x0DE1), texture(5, 0x0DE1)];
        for(const [i, t] of targets.entries()) {
            gl("glActiveTexture", 0x84C4 + i);
            gl("glTexStorage2D", 0x0DE1, 1, 0x8058, 4, 4);
            gl("glFramebufferTexture2D", 0x8D40, 0x8CE0 + i, 0x0DE1, t, 0);
        }
        gl("glDrawBuffers", 2, ints([0x8CE0, 0x8CE1]));
        gl("glViewport", 0, 0, 4, 4);
        gl("glDrawArrays", 5, 0, 4);
        gl("glReadBuffer", 0x8CE1);
        check(near(pixel(await read_pixels(0, 0, 4, 4), 4, 1, 1), [0, 255, 0, 255]), "draw buffer 1: the second output");
        gl("glClearBufferfv", 0x1800, 1, floats([0, 0, 1, 1]));
        check(near(pixel(await read_pixels(0, 0, 4, 4), 4, 1, 1), [0, 0, 255, 255]), "glClearBufferfv on draw buffer 1");
        gl("glReadBuffer", 0x8CE0);
        check(near(pixel(await read_pixels(0, 0, 4, 4), 4, 1, 1), [255, 0, 0, 255]), "draw buffer 0 kept its red");

        // ---- reads of other formats: R32UI, RGB10_A2, sRGB
        const read_as = async (x, y, w, h, format, type) => {
            const id = request++;
            record(GLES.READ_PIXELS, 1, id, x, y, w, h, format, type);
            await run();
            return answers.get(id);
        };
        const formats_fbo = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, formats_fbo);
        gl("glDrawBuffers", 1, ints([0x8CE0]));
        gl("glReadBuffer", 0x8CE0);
        const attach = (internal) => {
            const t = texture(7, 0x0DE1);
            gl("glTexStorage2D", 0x0DE1, 1, internal, 4, 4);
            gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x0DE1, t, 0);
            return t;
        };
        attach(0x8236);
        gl("glClearBufferuiv", 0x1800, 0, ints([12345, 0, 0, 0]));
        let raw = await read_as(0, 0, 1, 1, 0x8D99, 0x1405);
        check(Array.from(new Uint32Array(raw.slice().buffer)).join() === "12345,0,0,1", "R32UI read as RGBA_INTEGER, UNSIGNED_INT: " + Array.from(new Uint32Array(raw.slice().buffer)));
        attach(0x8059);
        gl("glClearBufferfv", 0x1800, 0, floats([1, 0.5, 0, 1]));
        raw = await read_as(0, 0, 1, 1, 0x1908, 0x8368);
        const packed = new Uint32Array(raw.slice().buffer)[0];
        check((packed & 1023) === 1023 && Math.abs((packed >>> 10 & 1023) - 511.5) < 2 && (packed >>> 20 & 1023) === 0 && packed >>> 30 === 3,
            "RGB10_A2 read as UNSIGNED_INT_2_10_10_10_REV");
        attach(0x8C43);
        gl("glClearBufferfv", 0x1800, 0, floats([0.5, 0.5, 0.5, 1]));
        check(near(pixel(await read_pixels(0, 0, 4, 4), 4, 2, 2), [188, 188, 188, 255]), "SRGB8_ALPHA8: 0.5 stored encoded");
        gl("glBindFramebuffer", 0x8D40, 0);

        // ---- blits: scaled and flipped, a multisampled resolve, depth
        const blit_source = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, blit_source);
        attach(0x8058);
        gl("glEnable", 0x0C11);
        gl("glScissor", 0, 0, 2, 4);
        gl("glClearBufferfv", 0x1800, 0, floats([1, 0, 0, 1]));
        gl("glScissor", 2, 0, 2, 4);
        gl("glClearBufferfv", 0x1800, 0, floats([0, 1, 0, 1]));
        gl("glDisable", 0x0C11);
        gl("glBindFramebuffer", 0x8CA9, 0);
        gl("glBlitFramebuffer", 0, 0, 4, 4, W, 0, 0, W, 0x4000, 0x2600);
        gl("glBindFramebuffer", 0x8D40, 0);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [0, 255, 0, 255]) && near(pixel(window, W, 6, 6), [255, 0, 0, 255]), "a blit scaled by 2 and flipped in x");
        const ms = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, ms);
        const rb = gen("Renderbuffers");
        gl("glBindRenderbuffer", 0x8D41, rb);
        gl("glRenderbufferStorageMultisample", 0x8D41, 4, 0x8058, W, W);
        gl("glFramebufferRenderbuffer", 0x8D40, 0x8CE0, 0x8D41, rb);
        gl("glViewport", 0, 0, W, W);
        gl("glUseProgram", flat.name);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, full, full.length);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        gl("glBindFramebuffer", 0x8CA9, 0);
        gl("glBlitFramebuffer", 0, 0, W, W, 0, 0, W, W, 0x4000, 0x2600);
        gl("glBindFramebuffer", 0x8D40, 0);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 255, 0, 255]), "a multisampled renderbuffer drawn, resolved by a blit");
        const depth_source = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, depth_source);
        const ds = texture(7, 0x0DE1);
        gl("glTexStorage2D", 0x0DE1, 1, 0x88F0, W, W);
        gl("glFramebufferTexture2D", 0x8D40, 0x821A, 0x0DE1, ds, 0);
        gl("glDrawBuffers", 1, ints([0]));
        gl("glReadBuffer", 0);
        gl("glClearBufferfi", 0x84F9, 0, 0.75, 0);
        gl("glBindFramebuffer", 0x8D40, 0);
        gl("glClearDepthf", 0);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000 | 0x0100);
        gl("glClearDepthf", 1);
        gl("glBindFramebuffer", 0x8CA8, depth_source);
        gl("glBlitFramebuffer", 0, 0, W, W, 0, 0, W, W, 0x0100, 0x2600);
        gl("glBindFramebuffer", 0x8D40, 0);
        gl("glEnable", 0x0B71);
        gl("glDepthFunc", 0x0201);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 255, 0, 255]), "a blit's depth (0.75, over a cleared 0) behind z 0 (0.5)");
        gl("glDisable", 0x0B71);
        gl("glUseProgram", textured.name);

        // ---- a depth texture: drawn to, sampled by a shadow sampler
        const depth_fbo = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, depth_fbo);
        const depth_texture = texture(6, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x81A6, 4, 4, 0, 0x1902, 0x1405, null);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glFramebufferTexture2D", 0x8D40, 0x8D00, 0x0DE1, depth_texture, 0);
        gl("glDrawBuffers", 1, ints([0]));
        gl("glReadBuffer", 0);
        gl("glEnable", 0x0B71);
        gl("glClear", 0x0100);
        gl("glUseProgram", mrt.name);
        gl("glDrawArrays", 5, 0, 4);
        gl("glDisable", 0x0B71);
        gl("glTexParameteri", 0x0DE1, 0x884C, 0x884E);
        gl("glTexParameteri", 0x0DE1, 0x884D, 0x0203);
        gl("glBindFramebuffer", 0x8D40, 0);
        gl("glViewport", 0, 0, W, W);
        const shadowed = program(`#version 300 es
            layout(location = 0) in vec2 position;
            out vec2 uv;
            void main() { uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            uniform highp sampler2DShadow depths;
            uniform float reference;
            in vec2 uv;
            out vec4 o;
            void main() { o = vec4(texture(depths, vec3(uv, reference)), 0.0, 0.0, 1.0); }`);
        gl("glUniform1i", shadowed.at("depths"), 6);
        gl("glUniform1f", shadowed.at("reference"), 0.25);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 0, 0, 255]), "a shadow sampler: 0.25 <= the depth drawn (0.5)");
        gl("glUniform1f", shadowed.at("reference"), 0.75);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 0, 0, 255]), "a shadow sampler: 0.75 is not");

        // a depth image with data (drawn: WebGPU copies none into depth32float), compared
        texture(6, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x8CAC, 2, 1, 0, 0x1902, 0x1406, floats([0.25, 0.75]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x884C, 0x884E);
        gl("glTexParameteri", 0x0DE1, 0x884D, 0x0203);
        gl("glUniform1f", shadowed.at("reference"), 0.5);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 3), [0, 0, 0, 255]) && near(pixel(window, W, 6, 3), [255, 0, 0, 255]), "a DEPTH_COMPONENT32F image's values, drawn");

        // ---- a 3D texture's mipmaps; a pack buffer; a copy into LUMINANCE
        const volume = program(`#version 300 es
            layout(location = 0) in vec2 position;
            out vec2 uv;
            void main() { uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision highp float;
            uniform mediump sampler3D volume;
            uniform sampler2D plain;
            uniform int which;
            in vec2 uv;
            out vec4 o;
            void main() { o = which == 0 ? textureLod(volume, vec3(0.5), 1.0) : texture(plain, uv); }`);
        texture(8, 0x806F);
        gl("glTexImage3D", 0x806F, 0, 0x8058, 2, 2, 2, 0, 0x1908, 0x1401,
            new Uint8Array([255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255]));
        gl("glGenerateMipmap", 0x806F);
        gl("glUniform1i", volume.at("volume"), 8);
        gl("glUniform1i", volume.at("which"), 0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [128, 0, 128, 255], 3), "a 3D texture's level 1 made by glGenerateMipmap");
        const pack_fbo = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, pack_fbo);
        attach(0x8058);
        gl("glClearBufferfv", 0x1800, 0, floats([0.2, 0.4, 0.6, 1]));
        const pbo = gen("Buffers");
        gl("glBindBuffer", 0x88EB, pbo);
        gl("glBufferData", 0x88EB, 64, null, 0x88E1);
        gl("glReadPixelsOffsetAEMU", 0, 0, 4, 4, 0x1908, 0x1401, 0);
        gl("glBindBuffer", 0x88EB, 0);
        const pack_read = request++;
        record(GLES.BUFFER_READ, 1, pack_read, pbo, 0, 64);
        await run();
        check(near(Array.from(answers.get(pack_read).subarray(20, 24)), [51, 102, 153, 255]), "glReadPixels into a pack buffer, mapped in the same batch");
        texture(9, 0x0DE1);
        gl("glCopyTexImage2D", 0x0DE1, 0, 0x1909, 0, 0, 2, 2, 0);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glBindFramebuffer", 0x8D40, 0);
        gl("glViewport", 0, 0, W, W);
        gl("glUniform1i", volume.at("plain"), 9);
        gl("glUniform1i", volume.at("which"), 1);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [51, 51, 51, 255]), "glCopyTexImage2D into LUMINANCE: red as luminance, alpha 1");
        // a pixel unpack buffer written through a mapping, as hwui's glyphs: the map stays on the CPU side (a query),
        // its bytes come with the unmap; then an image from it at an offset, with a row length
        const unpack = gen("Buffers");
        gl("glBindBuffer", 0x88EC, unpack);
        gl("glBufferData", 0x88EC, 16, null, 0x88E8);
        gl("glMapBufferRangeAEMU", 0x88EC, 0, 16, 3, 16);
        gl("glUnmapBufferAEMU", 0x88EC, 0, 16, 3, new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 200, 200, 0, 0, 200, 200, 0, 0]), 4);
        texture(9, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x1909, 2, 2, 0, 0x1909, 0x1401, null);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glPixelStorei", 0x0CF2, 4);
        gl("glTexSubImage2DOffsetAEMU", 0x0DE1, 0, 0, 0, 2, 2, 0x1909, 0x1401, 8);
        gl("glPixelStorei", 0x0CF2, 0);
        gl("glBindBuffer", 0x88EC, 0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [200, 200, 200, 255]), "an unpack buffer's mapped bytes (the unmap's), uploaded from it");
        // an ETC2 RGB8 block (differential, red 31 + 2): WebGPU's when the device has it, else decoded
        texture(9, 0x0DE1);
        gl("glCompressedTexImage2D", 0x0DE1, 0, 0x9274, 4, 4, 0, 8, new Uint8Array([0xF8, 0, 0, 0x02, 0, 0, 0, 0]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 2, 2, 255]), "an ETC2 RGB8 block");
        // 5 by 5 texels of ETC2 RGB8 (2 by 2 blocks, all that one): not whole blocks, WebGPU will not take them; decoded by the GPU
        gl("glCompressedTexImage2D", 0x0DE1, 0, 0x9274, 5, 5, 0, 32, new Uint8Array(Array.from({ length: 4 }, () => [0xF8, 0, 0, 0x02, 0, 0, 0, 0]).flat()));
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 2, 2, 255]), "5 by 5 texels of ETC2 RGB8, decoded");
        // TEXTURE_SWIZZLE_R/G/B/A: (green, red, one, zero)
        gl("glTexParameteri", 0x0DE1, 0x8E42, 0x1904);
        gl("glTexParameteri", 0x0DE1, 0x8E43, 0x1903);
        gl("glTexParameteri", 0x0DE1, 0x8E44, 1);
        gl("glTexParameteri", 0x0DE1, 0x8E45, 0);
        gl("glDisable", 0x0BE2);
        gl("glDrawArrays", 5, 0, 4);
        if(device.features.has("texture-component-swizzle")) {
            check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [2, 255, 255, 0]), "a texture's swizzle");
        }
        gl("glUseProgram", flat.name);

        // ---- indices: restarts, fans
        gl("glUseProgram", flat.name);
        // two quads: x -1 to -0.5 and 0.5 to 1, a strip each
        const two = floats([-1, -1, -0.5, -1, -1, 1, -0.5, 1, 0.5, -1, 1, -1, 0.5, 1, 1, 1]);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, two, two.length);
        gl("glEnable", 0x8D69);
        const restarted = new Uint8Array(new Uint16Array([0, 1, 2, 3, 0xFFFF, 4, 5, 6, 7]).buffer);
        gl("glClear", 0x4000);
        gl("glDrawElementsData", 5, 9, 0x1403, restarted, restarted.length);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 4), [255, 255, 0, 255]) && near(pixel(window, W, 7, 4), [255, 255, 0, 255]) &&
            near(pixel(window, W, 4, 4), [0, 0, 0, 255]), "a strip restarted, from client memory");
        const elements = gen("Buffers");
        const positions = gen("Buffers");
        gl("glBindBuffer", 0x8892, positions);
        gl("glBufferData", 0x8892, two.length, two, 0x88E4);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        gl("glBindBuffer", 0x8893, elements);
        gl("glBufferData", 0x8893, restarted.length + 2, new Uint8Array([0, 0, ...restarted]), 0x88E4);
        gl("glClear", 0x4000);
        gl("glDrawElementsOffset", 5, 9, 0x1403, 2);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 4), [255, 255, 0, 255]) && near(pixel(window, W, 7, 4), [255, 255, 0, 255]) &&
            near(pixel(window, W, 4, 4), [0, 0, 0, 255]), "a strip restarted, from an element buffer as it is");
        gl("glClear", 0x4000);
        gl("glDrawArrays", 6, 4, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 7, 1), [255, 255, 0, 255]) && near(pixel(window, W, 0, 1), [0, 0, 0, 255]), "a fan from a buffer, from vertex 4");
        // (an element buffer of 6 bytes, not a whole number of words: its GPU copy padded past its end)
        const six = gen("Buffers");
        gl("glBindBuffer", 0x8893, six);
        const triangle = new Uint8Array(new Uint16Array([0, 1, 2]).buffer);
        gl("glBufferData", 0x8893, triangle.length, triangle, 0x88E4);
        gl("glClear", 0x4000);
        gl("glDrawElementsOffset", 4, 3, 0x1403, 0);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 4), [255, 255, 0, 255]) && near(pixel(window, W, 4, 4), [0, 0, 0, 255]) &&
            near(pixel(window, W, 7, 4), [0, 0, 0, 255]), "a triangle from an element buffer of 6 bytes");

        // ---- transform feedback: captured, drawn from, read back
        gl("glDisable", 0x8D69);
        const captured = program(`#version 300 es
            layout(location = 0) in vec2 position;
            out vec4 moved;
            out float doubled;
            void main() { moved = vec4(position, 1.0, 2.0); doubled = position.x * 2.0; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            in vec4 moved;
            out vec4 o;
            void main() { o = vec4(0.0, 1.0, 1.0, 1.0); }`, ["moved", "doubled"]);
        void captured;
        const feedback = gen("Buffers");
        gl("glBindBuffer", 0x8C8E, feedback);
        gl("glBufferData", 0x8C8E, 60, null, 0x88E8);
        gl("glBindBufferBase", 0x8C8E, 0, feedback);
        gl("glBindBuffer", 0x8892, 0);
        const big = floats([-1, -1, 3, -1, -1, 3]);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, big, big.length);
        gl("glEnable", 0x8C89);
        gl("glBeginTransformFeedback", 4);
        gl("glDrawArrays", 4, 0, 3);
        gl("glEndTransformFeedback");
        gl("glDisable", 0x8C89);
        const id = request++;
        record(GLES.BUFFER_READ, 1, id, feedback, 0, 60);
        await run();
        const got = Array.from(new Float32Array(answers.get(id).slice().buffer));
        check(got.join() === [-1, -1, 1, 2, -2, 3, -1, 1, 2, 6, -1, 3, 1, 2, -2].join(), "captured, interleaved, read back: " + got);
        // an array element and a struct member captured (each copied into an output of its own)
        const parts = program(`#version 300 es
            layout(location = 0) in vec2 position;
            struct S { float a; vec2 b; };
            out vec2 target[3];
            out S s;
            void main() {
                target[0] = vec2(9.0); target[1] = position * 3.0; target[2] = vec2(9.0); s.a = 9.0; s.b = vec2(position.y, 7.0);
                gl_Position = vec4(position, 0.0, 1.0);
            }`, `#version 300 es
            precision mediump float;
            out vec4 o;
            void main() { o = vec4(1.0); }`, ["target[1]", "s.b"]);
        void parts;
        const parts_feedback = gen("Buffers");
        gl("glBindBuffer", 0x8C8E, parts_feedback);
        gl("glBufferData", 0x8C8E, 48, null, 0x88E8);
        gl("glBindBufferBase", 0x8C8E, 0, parts_feedback);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, big, big.length);
        gl("glEnable", 0x8C89);
        gl("glBeginTransformFeedback", 4);
        gl("glDrawArrays", 4, 0, 3);
        gl("glEndTransformFeedback");
        gl("glDisable", 0x8C89);
        const parts_id = request++;
        record(GLES.BUFFER_READ, 1, parts_id, parts_feedback, 0, 48);
        await run();
        const parts_got = Array.from(new Float32Array(answers.get(parts_id).slice().buffer)).join();
        check(parts_got === [-3, -3, -1, 7, 9, -3, -1, 7, -3, 9, 3, 7].join(), "an array element and a struct member captured: " + parts_got);
        // a flat varying captured: in GL's order, drawn with GL's provoking vertex (the last) as without transform feedback
        const flat_tf = program(`#version 300 es
            layout(location = 0) in vec2 position;
            flat out uint id;
            void main() { id = uint(gl_VertexID) + 1u; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            flat in uint id;
            out vec4 o;
            void main() { o = vec4(float(id) / 4.0, 0.0, 0.0, 1.0); }`, ["id"]);
        void flat_tf;
        gl("glBindBuffer", 0x8C8E, parts_feedback);
        gl("glBufferData", 0x8C8E, 12, null, 0x88E8);
        gl("glBindBufferBase", 0x8C8E, 0, parts_feedback);
        gl("glClear", 0x4000);
        gl("glBeginTransformFeedback", 4);
        gl("glDrawArrays", 4, 0, 3);
        gl("glEndTransformFeedback");
        const flat_pixel = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        const flat_id = request++;
        record(GLES.BUFFER_READ, 1, flat_id, parts_feedback, 0, 12);
        await run();
        const flat_got = Array.from(new Uint32Array(answers.get(flat_id).slice().buffer)).join();
        check(flat_got === "1,2,3" && near(flat_pixel, [191, 0, 0, 255]), "a flat varying captured in GL's order, drawn with the last vertex's: " +
            flat_got + " / " + flat_pixel);
        gl("glBindBufferBase", 0x8C8E, 0, feedback);
        gl("glUseProgram", flat.name);
        gl("glBindBuffer", 0x8892, feedback);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 20, 0);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 4, 0, 3);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 5, 5), [255, 255, 0, 255]), "the captured buffer drawn from");

        // ---- occlusion queries: a draw that passes, one the depth test fails entirely
        const occlusion_queries = [];
        const occlusion = async (depth_func) => {
            const q = gen("Queries");
            occlusion_queries.push(q);
            gl("glEnable", 0x0B71);
            gl("glDepthFunc", depth_func);
            gl("glBeginQuery", 0x8C2F, q);
            gl("glDrawArrays", 4, 0, 3);
            gl("glEndQuery", 0x8C2F);
            gl("glDisable", 0x0B71);
            const id = request++;
            record(GLES.QUERY_READ, 1, id, q);
            await run();
            return new Uint32Array(answers.get(id).slice().buffer)[0];
        };
        check(await occlusion(0x0207) === 1, "an occlusion query: samples passed");
        check(await occlusion(0x0200) === 0, "an occlusion query: none passed (GL_NEVER), though it drew");

        // ---- a GLES 2.0 context of a host with glslang (api 20): GLSL ES 1.00 through glslang, drawn as GLES 3.x's
        record(GLES.CONTEXT_CREATE, 5, 3, 0, 20);
        record(GLES.MAKE_CURRENT, 1, 5, 2, 2);
        cpu.create_context(5, 20, 0);
        cpu.make_current(5, { width: W, height: W, config: CONFIGS[3] });
        current = 5;
        const es2 = program(`attribute vec2 position; attribute vec4 color; varying vec4 v; varying vec2 uv; uniform mat4 m;
            void main() { v = color; uv = position * 0.5 + 0.5; gl_Position = m * vec4(position, 0.0, 1.0); }`, `precision mediump float;
            varying vec4 v; varying vec2 uv; uniform sampler2D tex; uniform int which;
            void main() { gl_FragColor = which == 0 ? v : texture2D(tex, uv); }`);
        gl("glUniformMatrix4fv", es2.at("m"), 1, 0, floats([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]));
        gl("glEnableVertexAttribArray", es2.attribute("position"));
        gl("glVertexAttribPointerData", es2.attribute("position"), 2, 0x1406, 0, 0, full, full.length);
        gl("glVertexAttrib4f", es2.attribute("color"), 0.2, 0.4, 0.6, 1);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [51, 102, 153, 255]), "GLES 2.0 through glslang: an attribute's current value");
        const es2_textures = [
            ["LUMINANCE", [0x1909, 0x1909, 0x1401, new Uint8Array([100])], [100, 100, 100, 255]],
            ["RGB 565", [0x1907, 0x1907, 0x8363, new Uint8Array(new Uint16Array([0xF800]).buffer)], [255, 0, 0, 255]],
            ["RGBA 4444", [0x1908, 0x1908, 0x8033, new Uint8Array(new Uint16Array([0x0F0F]).buffer)], [0, 255, 0, 255]],
        ];
        gl("glUniform1i", es2.at("which"), 1);
        for(const [what, [internal, format, type, data], expected] of es2_textures) {
            gl("glBindTexture", 0x0DE1, 40 + es2_textures.findIndex(t => t[0] === what));
            gl("glTexImage2D", 0x0DE1, 0, internal, 1, 1, 0, format, type, data);
            gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
            gl("glDrawArrays", 5, 0, 4);
            check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), expected), "GLES 2.0 through glslang: " + what);
        }
        gl("glBindTexture", 0x0DE1, 50);
        gl("glCompressedTexImage2D", 0x0DE1, 0, 0x8D64, 4, 4, 0, 8, new Uint8Array([0xF8, 0, 0, 0x02, 0, 0, 0, 0]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 2, 2, 255]), "GLES 2.0 through glslang: ETC1");
        // a snapshot of it, restored on a new executor: the texture's block, the program's link kept
        const es2_saved = await executor.save();
        executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        executor.restore(es2_saved);
        globalThis.glesExecutor = executor;
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 2, 2, 255]), "restored: GLES 2.0 through glslang, an ETC1 texture and its program");
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        current = 1;

        // ---- GLES 3.1: compute, storage, atomic counters, images, indirect draws, multisampled textures, separable programs
        record(GLES.CONTEXT_CREATE, 6, 3, 0, 31);
        record(GLES.MAKE_CURRENT, 1, 6, 2, 2);
        cpu.create_context(6, 31, 0);
        cpu.make_current(6, { width: W, height: W, config: CONFIGS[3] });
        current = 6;
        names.clear();
        const compute = source => {
            const sh = shader_name++, p = shader_name++;
            call("glCreateShader", sh, [0x91B9]);
            gl("glShaderString", sh, text(source), source.length + 1);
            gl("glCompileShader", sh);
            call("glCreateProgram", p, []);
            gl("glAttachShader", p, sh);
            gl("glLinkProgram", p);
            const info = cpu.context(6).group.objects.get(p).info;
            check(info && info.ok, "a compute program links: " + (info && info.log));
            checks.pop();
            gl("glUseProgram", p);
            return p;
        };
        const read_buffer = async (buffer, length) => {
            const id = request++;
            record(GLES.BUFFER_READ, 1, id, buffer, 0, length);
            await run();
            return answers.get(id);
        };
        // a storage buffer written by a dispatch; an atomic counter
        compute(`#version 310 es
            layout(local_size_x = 4) in;
            layout(std430, binding = 0) buffer Data { uint values[]; };
            layout(binding = 0, offset = 0) uniform atomic_uint counter;
            void main() { values[gl_GlobalInvocationID.x] = gl_GlobalInvocationID.x * 2u; atomicCounterIncrement(counter); }`);
        const data31 = gen("Buffers"), counter31 = gen("Buffers");
        gl("glBindBuffer", 0x90D2, data31);
        gl("glBufferData", 0x90D2, 32, null, 0x88E8);
        gl("glBindBufferBase", 0x90D2, 0, data31);
        gl("glBindBuffer", 0x92C0, counter31);
        gl("glBufferData", 0x92C0, 4, ints([5]), 0x88E8);
        gl("glBindBufferBase", 0x92C0, 0, counter31);
        gl("glDispatchCompute", 2, 1, 1);
        check(Array.from(new Uint32Array((await read_buffer(data31, 32)).slice().buffer)).join() === "0,2,4,6,8,10,12,14", "a dispatch's storage buffer");
        check(new Uint32Array((await read_buffer(counter31, 4)).slice().buffer)[0] === 13, "an atomic counter incremented 8 times from 5");
        // atomic counters at their layout offsets: past 0, in reverse order, an array's elements by a dynamic index; a decrement
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(binding = 0, offset = 12) uniform atomic_uint first;
            layout(binding = 0, offset = 4) uniform atomic_uint second;
            layout(binding = 0, offset = 16) uniform atomic_uint row[2];
            void main() { atomicCounterIncrement(first); atomicCounterDecrement(second); atomicCounterIncrement(row[gl_GlobalInvocationID.x]); }`);
        gl("glBindBuffer", 0x92C0, counter31);
        gl("glBufferData", 0x92C0, 24, ints([0, 10, 0, 20, 30, 40]), 0x88E8);
        gl("glDispatchCompute", 2, 1, 1);
        const counters31 = Array.from(new Uint32Array((await read_buffer(counter31, 24)).slice().buffer)).join();
        check(counters31 === "0,8,0,22,31,41", "atomic counters at their offsets (past 0, in reverse order, an array's by a dynamic index), decremented: " +
            counters31);
        // indirect dispatches of parameters the guest uploaded, each command's results in a range of one buffer (dEQP's upload_buffer)
        compute(`#version 310 es
            layout(local_size_x = 3, local_size_y = 1, local_size_z = 2) in;
            layout(binding = 0, std430) buffer Result { uvec3 expectedGroupCount; coherent uint numPassed; } result;
            void main() { if(all(equal(result.expectedGroupCount, gl_NumWorkGroups))) atomicAdd(result.numPassed, 1u); }`);
        const commands31 = gen("Buffers"), results31 = gen("Buffers");
        const command_words = new Int32Array(256);
        command_words.set([1, 1, 1], 0);
        command_words.set([1, 1, 4], 13);
        command_words.set([1, 3, 1], 26);
        gl("glBindBuffer", 0x90EE, commands31);
        gl("glBufferData", 0x90EE, 1024, new Uint8Array(command_words.buffer), 0x88E4);
        const result_words = new Int32Array(64 * 3);
        [[1, 1, 1], [1, 3, 1], [1, 1, 4]].forEach((g, i) => result_words.set(g, 64 * i));
        gl("glBindBuffer", 0x90D2, results31);
        gl("glBufferData", 0x90D2, 768, new Uint8Array(result_words.buffer), 0x88E5);
        [0, 104, 52].forEach((offset, i) =>
        {
            gl("glBindBufferRange", 0x90D2, 0, results31, 256 * i, 256);
            gl("glDispatchComputeIndirect", offset);
        });
        const passed31 = new Uint32Array((await read_buffer(results31, 768)).slice().buffer);
        check([passed31[3], passed31[64 + 3], passed31[128 + 3]].join() === "6,18,24", "indirect dispatches of uploaded parameters: " +
            [passed31[3], passed31[64 + 3], passed31[128 + 3]].join());
        // an instance array of storage blocks, its elements at the binding points after the array's, each a range of one buffer
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(shared, binding = 0) buffer Block { highp ivec4 var; } block[3];
            layout(binding = 0) uniform atomic_uint ac_numPassed;
            void main() {
                bool ok = block[0].var == ivec4(-7, 9, -5, 6) && block[1].var == ivec4(3, 4, 2, -3) && block[2].var == ivec4(-3, -3, -5, -5);
                if(ok) atomicCounterIncrement(ac_numPassed);
                block[0].var = ivec4(5, -9, 5, -6); block[1].var = ivec4(-2, -4, 1, -9); block[2].var = ivec4(7, 3, 6, 8);
            }`);
        const blocks31 = gen("Buffers");
        const block_words = new Int32Array(192);
        block_words.set([-7, 9, -5, 6], 0);
        block_words.set([3, 4, 2, -3], 64);
        block_words.set([-3, -3, -5, -5], 128);
        gl("glBindBuffer", 0x90D2, blocks31);
        gl("glBufferData", 0x90D2, 768, new Uint8Array(block_words.buffer), 0x88E8);
        for(let i = 0; i < 3; i++) gl("glBindBufferRange", 0x90D2, i, blocks31, 256 * i, 16);
        gl("glBindBuffer", 0x92C0, counter31);
        gl("glBufferData", 0x92C0, 4, ints([0]), 0x88E8);
        gl("glBindBufferBase", 0x92C0, 0, counter31);
        gl("glDispatchCompute", 1, 1, 1);
        const block_read31 = new Int32Array((await read_buffer(blocks31, 768)).slice().buffer);
        const passed_blocks31 = new Uint32Array((await read_buffer(counter31, 4)).slice().buffer)[0];
        const blocks_seen31 = [passed_blocks31, ...block_read31.slice(0, 4), ...block_read31.slice(64, 68), ...block_read31.slice(128, 132)].join();
        check(blocks_seen31 === "1,5,-9,5,-6,-2,-4,1,-9,7,3,6,8", "an instance array of storage blocks read and written: " + blocks_seen31);
        // one whose last member is an unsized array of struct arrays: each element's range its own length (vx_naga's blockarrays.rs
        // drops the array's types, which naga refuses, and gives length() the element's variable)
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            struct S { highp ivec3 a; highp vec4 c; };
            layout(std430, binding = 0) buffer Block { highp uint u; highp vec4 v; S s[][2]; } block[3];
            void main() {
                block[0].u = uint(block[0].s.length()); block[1].u = uint(block[1].s.length()); block[2].u = uint(block[2].s.length());
                block[1].s[2][1].c = block[1].v + vec4(block[2].s[0][0].a, 1.0);
            }`);
        const unsized31 = gen("Buffers");
        const unsized_words = new Int32Array(192);
        unsized_words.set(new Int32Array(new Float32Array([1, 2, 3, 4]).buffer), 64 + 4);
        unsized_words.set([10, 20, 30], 128 + 8);
        gl("glBindBuffer", 0x90D2, unsized31);
        gl("glBufferData", 0x90D2, 768, new Uint8Array(unsized_words.buffer), 0x88E8);
        [1, 3, 2].forEach((n, i) => gl("glBindBufferRange", 0x90D2, i, unsized31, 256 * i, 32 + 64 * n));
        gl("glDispatchCompute", 1, 1, 1);
        const unsized_read = await read_buffer(unsized31, 768);
        const unsized_seen = [...[0, 64, 128].map(i => new Uint32Array(unsized_read.slice().buffer)[i]),
            ...new Float32Array(unsized_read.slice().buffer).slice(116, 120)].join();
        check(unsized_seen === "1,3,2,11,22,33,5", "an instance array of storage blocks with unsized arrays of structs: lengths, a store: " + unsized_seen);
        // ranges shorter than their blocks' WGSL size (an unsized array of no elements): the members still the buffer's, a whole
        // buffer of 16 bytes and 16 bytes at the end of one (the GPU buffer grown to the binding's least size, G-81)
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(std430, binding = 0) buffer Short { highp vec4 a; highp float e[]; } s;
            layout(std430, binding = 1) buffer Tail { highp vec4 a; highp float e[]; } t;
            void main() { s.a = s.a * 2.0; t.a = t.a + vec4(10.0); }`);
        const short31 = gen("Buffers"), tail31 = gen("Buffers");
        gl("glBindBuffer", 0x90D2, short31);
        gl("glBufferData", 0x90D2, 16, floats([1, 2, 3, 4]), 0x88E8);
        gl("glBindBufferBase", 0x90D2, 0, short31);
        const tail_floats = new Float32Array(68);
        tail_floats.set([5, 6, 7, 8], 64);
        gl("glBindBuffer", 0x90D2, tail31);
        gl("glBufferData", 0x90D2, 272, new Uint8Array(tail_floats.buffer), 0x88E8);
        gl("glBindBufferRange", 0x90D2, 1, tail31, 256, 16);
        gl("glDispatchCompute", 1, 1, 1);
        const short_seen = [...new Float32Array((await read_buffer(short31, 16)).slice().buffer),
            ...new Float32Array((await read_buffer(tail31, 272)).slice().buffer).slice(64)].join();
        check(short_seen === "2,4,6,8,15,16,17,18", "storage ranges shorter than their blocks' WGSL size: " + short_seen);
        // stores into std140 arrays of 16-byte elements (their padding kept) and row major matrices (rows 8 bytes apart in std430)
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(std140, binding = 0) buffer A { highp vec2 var[3]; float f[2]; };
            layout(packed, row_major, binding = 1) buffer B { highp mat2x3 mv; highp mat3 m[2]; };
            void main() {
                bool ok = var[1] == vec2(-8.0, -7.0) && f[1] == 2.0 && mv == mat2x3(5.0, -7.0, 8.0, -5.0, 5.0, -3.0);
                var[0] = vec2(3.0, 8.0); var[2].y = ok ? 1.0 : 0.0; f[0] = 5.0;
                mv = mat2x3(-9.0, 1.0, -5.0, 1.0, 5.0, -3.0); m[1][2] = vec3(ok ? 1.0 : 0.0); m[0][1].y = 4.0;
            }`);
        const std140_31 = gen("Buffers"), row_major31 = gen("Buffers");
        const std140_floats = new Float32Array(20).fill(99);
        std140_floats.set([-8, -7], 4);
        std140_floats[16] = 2;
        gl("glBindBuffer", 0x90D2, std140_31);
        gl("glBufferData", 0x90D2, 80, new Uint8Array(std140_floats.buffer), 0x88E8);
        gl("glBindBufferBase", 0x90D2, 0, std140_31);
        const row_floats = new Float32Array(32);
        row_floats.set([5, -5, -7, 5, 8, -3]);
        gl("glBindBuffer", 0x90D2, row_major31);
        gl("glBufferData", 0x90D2, 128, new Uint8Array(row_floats.buffer), 0x88E8);
        gl("glBindBufferBase", 0x90D2, 1, row_major31);
        gl("glDispatchCompute", 1, 1, 1);
        const std140_read = Array.from(new Float32Array((await read_buffer(std140_31, 80)).slice().buffer)).join();
        check(std140_read === "3,8,99,99,-8,-7,99,99,99,1,99,99,5,99,99,99,2,99,99,99", "stores into std140 arrays, their padding kept: " + std140_read);
        const row_read = new Float32Array((await read_buffer(row_major31, 128)).slice().buffer);
        const row_seen = [...row_read.slice(0, 6), row_read[13], row_read[22], row_read[26], row_read[30]].join();
        check(row_seen === "-9,1,1,5,-5,-3,4,1,1,1", "stores into row major matrices: " + row_seen);
        // images WebGPU has no storage view of: a cube's faces (a 2D array), a texture of another format of the
        // same texel size (a copy of its bits), a 3D texture's layer as a 2D image (a copy of the layer)
        const image_out31 = gen("Buffers");
        gl("glBindBuffer", 0x90D2, image_out31);
        gl("glBufferData", 0x90D2, 64, null, 0x88E8);
        gl("glBindBufferBase", 0x90D2, 0, image_out31);
        const cube31 = next_texture++;
        gl("glBindTexture", 0x8513, cube31);
        gl("glTexStorage2D", 0x8513, 1, 0x8D7C, 2, 2);
        compute(`#version 310 es
            layout(local_size_x = 2, local_size_y = 2, local_size_z = 6) in;
            layout(rgba8ui, binding = 0) writeonly uniform highp uimageCube faces;
            void main() { ivec3 p = ivec3(gl_LocalInvocationID); imageStore(faces, p, uvec4(uint(p.z * 10 + p.x), uint(p.y), 0u, 1u)); }`);
        gl("glBindImageTexture", 0, cube31, 0, 1, 0, 0x88B9, 0x8D7C);
        gl("glDispatchCompute", 1, 1, 1);
        gl("glMemoryBarrier", 0x20);
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(rgba8ui, binding = 0) readonly uniform highp uimageCube faces;
            layout(std430, binding = 0) buffer Out { uvec4 a; uvec4 b; ivec2 size; } o;
            void main() { o.a = imageLoad(faces, ivec3(1, 0, 3)); o.b = imageLoad(faces, ivec3(0, 1, 5)); o.size = imageSize(faces); }`);
        gl("glBindImageTexture", 0, cube31, 0, 1, 0, 0x88B8, 0x8D7C);
        gl("glDispatchCompute", 1, 1, 1);
        const cube_read31 = Array.from(new Uint32Array((await read_buffer(image_out31, 40)).slice().buffer)).join();
        check(cube_read31 === "31,0,0,1,50,1,0,1,2,2", "a cube image's faces stored and loaded, its size: " + cube_read31);
        const r32ui31 = next_texture++;
        gl("glBindTexture", 0x0DE1, r32ui31);
        gl("glTexStorage2D", 0x0DE1, 1, 0x8236, 1, 1);
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(rgba8ui, binding = 0) writeonly uniform highp uimage2D bytes;
            void main() { imageStore(bytes, ivec2(0), uvec4(1u, 2u, 3u, 4u)); }`);
        gl("glBindImageTexture", 0, r32ui31, 0, 0, 0, 0x88B9, 0x8D7C);
        gl("glDispatchCompute", 1, 1, 1);
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(r32ui, binding = 0) readonly uniform highp uimage2D word;
            layout(std430, binding = 0) buffer Out { uint value; } o;
            void main() { o.value = imageLoad(word, ivec2(0)).x; }`);
        gl("glBindImageTexture", 0, r32ui31, 0, 0, 0, 0x88B8, 0x8236);
        gl("glDispatchCompute", 1, 1, 1);
        const word31 = new Uint32Array((await read_buffer(image_out31, 4)).slice().buffer)[0];
        check(word31 === 0x04030201, "an R32UI texture written as an RGBA8UI image: " + word31.toString(16));
        const volume31 = next_texture++;
        gl("glBindTexture", 0x806F, volume31);
        gl("glTexStorage3D", 0x806F, 1, 0x8D7C, 2, 2, 2);
        compute(`#version 310 es
            layout(local_size_x = 2, local_size_y = 2) in;
            layout(rgba8ui, binding = 0) writeonly uniform highp uimage2D layer;
            void main() { imageStore(layer, ivec2(gl_LocalInvocationID.xy), uvec4(7u, gl_LocalInvocationID.xy, 1u)); }`);
        gl("glBindImageTexture", 0, volume31, 0, 0, 1, 0x88B9, 0x8D7C);
        gl("glDispatchCompute", 1, 1, 1);
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(rgba8ui, binding = 0) readonly uniform highp uimage3D volume;
            layout(std430, binding = 0) buffer Out { uvec4 a; uvec4 b; } o;
            void main() { o.a = imageLoad(volume, ivec3(1, 0, 1)); o.b = imageLoad(volume, ivec3(1, 0, 0)); }`);
        gl("glBindImageTexture", 0, volume31, 0, 1, 0, 0x88B8, 0x8D7C);
        gl("glDispatchCompute", 1, 1, 1);
        const volume_read31 = Array.from(new Uint32Array((await read_buffer(image_out31, 32)).slice().buffer)).join();
        check(volume_read31 === "7,1,0,1,0,0,0,0", "a 3D texture's layer 1 written as a 2D image: " + volume_read31);
        // an image written by a dispatch, sampled by a draw
        const image31 = next_texture++;
        gl("glActiveTexture", 0x84C0);
        gl("glBindTexture", 0x0DE1, image31);
        gl("glTexStorage2D", 0x0DE1, 1, 0x8058, 4, 4);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        compute(`#version 310 es
            layout(local_size_x = 4, local_size_y = 4) in;
            layout(rgba8, binding = 0) writeonly uniform highp image2D target;
            void main() { imageStore(target, ivec2(gl_GlobalInvocationID.xy), vec4(0.0, 1.0, 0.5, 1.0)); }`);
        gl("glBindImageTexture", 0, image31, 0, 0, 0, 0x88B9, 0x8058);
        gl("glDispatchCompute", 1, 1, 1);
        gl("glMemoryBarrier", 0x20);
        const sampled31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            out vec2 uv;
            void main() { uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            uniform sampler2D image;
            in vec2 uv;
            out vec4 o;
            void main() { o = texture(image, uv); }`);
        gl("glUniform1i", sampled31.at("image"), 0);
        const vao31 = gen("VertexArrays");
        gl("glBindVertexArray", vao31);
        const quad31 = gen("Buffers");
        gl("glBindBuffer", 0x8892, quad31);
        gl("glBufferData", 0x8892, full.length, full, 0x88E4);
        // (GLES 3.1's vertex attribute binding)
        gl("glVertexAttribFormat", 0, 2, 0x1406, 0, 0);
        gl("glVertexAttribBinding", 0, 3);
        gl("glBindVertexBuffer", 3, quad31, 0, 8);
        gl("glEnableVertexAttribArray", 0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 255, 128, 255]), "an image a dispatch stored, sampled; a vertex buffer binding point");
        // an indirect draw whose parameters a dispatch wrote (the GPU reads them), and one with them in the command
        compute(`#version 310 es
            layout(local_size_x = 1) in;
            layout(std430, binding = 1) buffer Command { uint count; uint instances; uint first; uint reserved; };
            void main() { count = 4u; instances = 1u; first = 0u; reserved = 0u; }`);
        const command31 = gen("Buffers");
        gl("glBindBuffer", 0x90D2, command31);
        gl("glBufferData", 0x90D2, 16, null, 0x88E8);
        gl("glBindBufferBase", 0x90D2, 1, command31);
        gl("glDispatchCompute", 1, 1, 1);
        gl("glMemoryBarrier", 0x100);
        const flat31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            uniform vec4 color;
            out vec4 o;
            void main() { o = color; }`);
        gl("glUniform4f", flat31.at("color"), 1, 0, 1, 1);
        gl("glBindBuffer", 0x8F3F, command31);
        gl("glClear", 0x4000);
        gl("glDrawArraysIndirectOffsetAEMU", 5, 0);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 0, 255, 255]), "an indirect draw of the parameters a dispatch wrote");
        gl("glUniform4f", flat31.at("color"), 0, 1, 1, 1);
        gl("glDrawArraysIndirectDataAEMU", 5, ints([4, 1, 0, 0]), 16);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 255, 255, 255]), "an indirect draw of the command's parameters");
        // an instance array of uniform blocks with a binding: its elements at the binding points after it
        const block_array31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            layout(std140, binding = 1) uniform Block { vec4 color; } blocks[2];
            out vec4 o;
            void main() { o = blocks[1].color; }`);
        void block_array31;
        const block_colors31 = gen("Buffers");
        gl("glBindBuffer", 0x8A11, block_colors31);
        gl("glBufferData", 0x8A11, 512, new Uint8Array(new Float32Array([1, 0, 0, 1, ...new Array(60).fill(0), 0, 0, 1, 1]).buffer), 0x88E4);
        gl("glBindBufferRange", 0x8A11, 1, block_colors31, 0, 16);
        gl("glBindBufferRange", 0x8A11, 2, block_colors31, 256, 16);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 0, 255, 255]), "an array of uniform blocks: element 1 at the binding after the array's");
        // a multisampled texture drawn to, its sample fetched
        const ms31 = next_texture++;
        gl("glBindTexture", 0x9100, ms31);
        gl("glTexStorage2DMultisample", 0x9100, 4, 0x8058, 4, 4, 1);
        const ms_fbo31 = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, ms_fbo31);
        gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x9100, ms31, 0);
        gl("glClearBufferfv", 0x1800, 0, floats([1, 1, 0, 1]));
        gl("glBindFramebuffer", 0x8D40, 0);
        const fetched31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            uniform mediump sampler2DMS samples;
            out vec4 o;
            void main() { o = texelFetch(samples, ivec2(1, 1), 2); }`);
        gl("glUniform1i", fetched31.at("samples"), 1);
        gl("glActiveTexture", 0x84C1);
        gl("glBindTexture", 0x9100, ms31);
        gl("glActiveTexture", 0x84C0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 255, 0, 255]), "a multisampled texture's sample, fetched");
        // GLSL ES 3.10's extended integer functions (helpers of plain arithmetic: naga reads none of their SPIR-V), read as integers
        const extended = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision highp float;
            uniform highp uint a, b;
            uniform highp int x, y, which;
            layout(location = 0) out highp uvec4 o;
            void main() {
                if(which == 0) { uint c, hi, lo; uint s = uaddCarry(a, 2u, c); umulExtended(a, b, hi, lo); o = uvec4(s, c, hi, lo); }
                else { int hi, lo; uint br; imulExtended(x, y, hi, lo); uint d = usubBorrow(2u, b, br); o = uvec4(uint(hi), uint(lo), d, br); }
            }`);
        const extended_fbo = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, extended_fbo);
        const extended_texture = texture(3, 0x0DE1);
        gl("glTexStorage2D", 0x0DE1, 1, 0x8D70, 1, 1);
        gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x0DE1, extended_texture, 0);
        gl("glActiveTexture", 0x84C0);
        gl("glUniform1ui", extended.at("a"), 0xFFFFFFFF);
        gl("glUniform1ui", extended.at("b"), 0xFFFFFFFF);
        gl("glUniform1i", extended.at("x"), -2);
        gl("glUniform1i", extended.at("y"), 3);
        const integers = [];
        for(const which of [0, 1])
        {
            gl("glUniform1i", extended.at("which"), which);
            gl("glDrawArrays", 5, 0, 4);
            integers.push(...new Uint32Array((await read_as(0, 0, 1, 1, 0x8D99, 0x1405)).slice().buffer));
        }
        gl("glBindFramebuffer", 0x8D40, 0);
        check(integers.map(v => v.toString(16)).join() === "1,1,fffffffe,1,ffffffff,fffffffa,3,1",
            "uaddCarry, umulExtended, imulExtended, usubBorrow: " + integers.map(v => v.toString(16)));
        // a depth and stencil texture sampled as its stencil (DEPTH_STENCIL_TEXTURE_MODE STENCIL_INDEX): the upload's stencil values
        const stencil31 = texture(2, 0x0DE1);
        gl("glTexImage2D", 0x0DE1, 0, 0x88F0, 2, 2, 0, 0x84F9, 0x84FA, new Uint8Array(new Uint32Array([0x80000042, 0x80000042, 0x80000042, 0x80000042]).buffer));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x90EA, 0x1901);
        void stencil31;
        const stenciled31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            uniform highp usampler2D stencil;
            out vec4 o;
            void main() { o = vec4(float(texture(stencil, vec2(0.5)).r) / 255.0, 0.0, 0.0, 1.0); }`);
        gl("glUniform1i", stenciled31.at("stencil"), 2);
        gl("glActiveTexture", 0x84C0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0x42, 0, 0, 255]), "a depth and stencil texture's stencil, sampled (STENCIL_INDEX)");
        // a rectangle of its stencil replaced (WebGPU copies whole levels' stencil only: through a buffer patched by a compute pass)
        gl("glActiveTexture", 0x84C2);
        gl("glTexSubImage2D", 0x0DE1, 0, 1, 1, 1, 1, 0x84F9, 0x84FA, new Uint8Array(new Uint32Array([0x80000017]).buffer));
        gl("glActiveTexture", 0x84C0);
        const fetched_stencil31 = program(`#version 310 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 310 es
            precision mediump float;
            uniform highp usampler2D stencil;
            out vec4 o;
            void main() { o = vec4(float(texelFetch(stencil, ivec2(1, 1), 0).r) / 255.0, float(texelFetch(stencil, ivec2(0, 1), 0).r) / 255.0, 0.0, 1.0); }`);
        gl("glUniform1i", fetched_stencil31.at("stencil"), 2);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0x17, 0x42, 0, 255]), "a rectangle of a depth and stencil texture's stencil replaced");
        // a pipeline of two separable programs, one made by glCreateShaderProgramv, their uniforms by glProgramUniform
        const separable_vs = `#version 310 es
            layout(location = 0) in vec2 position;
            uniform float scale;
            void main() { gl_Position = vec4(position * scale, 0.0, 1.0); }`;
        const separable_fs = `#version 310 es
            precision mediump float;
            uniform vec4 color;
            layout(location = 0) out vec4 o;
            void main() { o = color; }`;
        call("glCreateShaderProgramvAEMU", 300, [0x8B31, 1, text(separable_vs), separable_vs.length + 1]);
        call("glCreateShaderProgramvAEMU", 301, [0x8B30, 1, text(separable_fs), separable_fs.length + 1]);
        const at = (p, uniform) => cpu.context(6).group.objects.get(p).info.locations.get(uniform);
        const pipeline31 = gen("ProgramPipelines");
        gl("glUseProgram", 0);
        gl("glBindProgramPipeline", pipeline31);
        gl("glUseProgramStages", pipeline31, 1, 300);
        gl("glUseProgramStages", pipeline31, 2, 301);
        gl("glProgramUniform1f", 300, at(300, "scale"), 0.5);
        gl("glProgramUniform4f", 301, at(301, "color"), 1, 0.5, 0, 1);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 4, 4), [255, 128, 0, 255]) && near(pixel(window, W, 0, 0), [0, 0, 0, 255]),
            "a pipeline of separable programs: the vertex program's scale, the fragment program's color");
        gl("glBindProgramPipeline", 0);
        gl("glBindVertexArray", 0);
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        current = 1;

        // ---- GLES 3.2: a cube map array's layer, an ASTC block (a void extent: one color)
        record(GLES.CONTEXT_CREATE, 7, 3, 0, 32);
        record(GLES.MAKE_CURRENT, 1, 7, 2, 2);
        cpu.create_context(7, 32, 0);
        cpu.make_current(7, { width: W, height: W, config: CONFIGS[3] });
        current = 7;
        names.clear();
        const cubes32 = program(`#version 320 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            precision mediump float;
            uniform mediump samplerCubeArray cubes;
            uniform sampler2D astc;
            uniform int which;
            out vec4 o;
            void main() { o = which == 0 ? texture(cubes, vec4(1.0, 0.0, 0.0, 1.0)) : texture(astc, vec2(0.5)); }`);
        const vao32 = gen("VertexArrays");
        gl("glBindVertexArray", vao32);
        const quad32 = gen("Buffers");
        gl("glBindBuffer", 0x8892, quad32);
        gl("glBufferData", 0x8892, full.length, full, 0x88E4);
        gl("glEnableVertexAttribArray", 0);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        const cube_array = next_texture++;
        gl("glActiveTexture", 0x84C0);
        gl("glBindTexture", 0x9009, cube_array);
        // (two cubes of 1 by 1: layer-face 6 + face is cube 1's face; +X of cube 1 blue, the rest red)
        const faces = new Uint8Array(12 * 4);
        for(let i = 0; i < 12; i++) faces.set(i === 6 ? [0, 0, 255, 255] : [255, 0, 0, 255], 4 * i);
        gl("glTexImage3D", 0x9009, 0, 0x8058, 1, 1, 12, 0, 0x1908, 0x1401, faces);
        gl("glTexParameteri", 0x9009, 0x2801, 0x2600);
        gl("glUniform1i", cubes32.at("cubes"), 0);
        gl("glUniform1i", cubes32.at("which"), 0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 0, 255, 255]), "a cube map array's cube 1, +X");
        const astc = next_texture++;
        gl("glActiveTexture", 0x84C1);
        gl("glBindTexture", 0x0DE1, astc);
        gl("glCompressedTexImage2D", 0x0DE1, 0, 0x93B0, 4, 4, 0, 16,
            new Uint8Array([0xFC, 0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 0xFF, 0xFF]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glActiveTexture", 0x84C0);
        gl("glUniform1i", cubes32.at("astc"), 1);
        gl("glUniform1i", cubes32.at("which"), 1);
        gl("glDrawArrays", 5, 0, 4);
        if(device.features.has("texture-compression-astc")) {
            check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 0, 0, 255]), "an ASTC 4x4 block");
        }
        // geometry shaders: points made quads, colored by gl_PrimitiveIDIn; a triangle cut in two by two invocations
        const geometry_program = (vs_text, gs_text, fs_text) => {
            const vs = shader_name++, gs = shader_name++, fs = shader_name++, p = shader_name++;
            for(const [name, type, source] of [[vs, 0x8B31, vs_text], [gs, 0x8DD9, gs_text], [fs, 0x8B30, fs_text]]) {
                call("glCreateShader", name, [type]);
                gl("glShaderString", name, text(source), source.length + 1);
                gl("glCompileShader", name);
            }
            call("glCreateProgram", p, []);
            for(const name of [vs, gs, fs]) gl("glAttachShader", p, name);
            gl("glLinkProgram", p);
            const info = cpu.context(current).group.objects.get(p).info;
            check(info && info.ok, "linked: " + (info && info.log));
            checks.pop();
            gl("glUseProgram", p);
            return { name: p, at: uniform => info.locations.get(uniform) };
        };
        const sprites = geometry_program(`#version 320 es
            layout(location = 0) in vec2 position;
            out float v_size;
            void main() { v_size = 0.4; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            layout(points) in;
            layout(triangle_strip, max_vertices = 4) out;
            in float v_size[];
            flat out int g_id;
            uniform float scale;
            void main() {
                for (int i = 0; i < 4; i++) {
                    vec2 corner = vec2(i % 2 == 0 ? -1.0 : 1.0, i < 2 ? -1.0 : 1.0) * v_size[0] * scale;
                    g_id = gl_PrimitiveIDIn;
                    gl_Position = gl_in[0].gl_Position + vec4(corner, 0.0, 0.0);
                    EmitVertex();
                }
            }`, `#version 320 es
            precision mediump float;
            flat in int g_id;
            out vec4 o;
            void main() { o = g_id == 0 ? vec4(1.0, 0.0, 0.0, 1.0) : vec4(0.0, 1.0, 0.0, 1.0); }`);
        gl("glUniform1f", sprites.at("scale"), 1);
        const points32 = gen("Buffers");
        gl("glBindBuffer", 0x8892, points32);
        const two_points = floats([-0.5, -0.5, 0.5, 0.5]);
        gl("glBufferData", 0x8892, two_points.length, two_points, 0x88E4);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 0, 0, 2);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 2, 2), [255, 0, 0, 255]) && near(pixel(window, W, 5, 5), [0, 255, 0, 255]) &&
            near(pixel(window, W, 2, 5), [0, 0, 0, 255]), "a geometry shader: points made quads, gl_PrimitiveIDIn's colors");
        const halves = geometry_program(`#version 320 es
            layout(location = 0) in vec2 position;
            out vec4 v_color;
            void main() { v_color = vec4(0.0, 0.0, 1.0, 1.0); gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            layout(triangles, invocations = 2) in;
            layout(triangle_strip, max_vertices = 4) out;
            in vec4 v_color[];
            out vec4 g_color;
            void main() {
                // (the input's bounds: invocation 0 the left half, 1 the right, of another color)
                float x0 = gl_InvocationID == 0 ? -1.0 : 0.0;
                for (int i = 0; i < 4; i++) {
                    g_color = gl_InvocationID == 0 ? v_color[0] : vec4(1.0, 1.0, 0.0, 1.0);
                    gl_Position = vec4(x0 + (i % 2 == 0 ? 0.0 : 1.0), i < 2 ? -1.0 : 1.0, gl_in[i % 3].gl_Position.z, 1.0);
                    EmitVertex();
                }
                EndPrimitive();
            }`, `#version 320 es
            precision mediump float;
            in vec4 g_color;
            out vec4 o;
            void main() { o = g_color; }`);
        gl("glBindBuffer", 0x8892, quad32);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 4, 0, 3);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 4), [0, 0, 255, 255]) && near(pixel(window, W, 6, 4), [255, 255, 0, 255]),
            "a geometry shader's two invocations, a strip each");
        // sample variables: a 4x renderbuffer's samples colored by gl_SampleID and gl_SamplePosition, one sample by gl_SampleMask
        const per_sample = program(`#version 320 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            precision highp float;
            uniform int masked;
            out vec4 o;
            void main() {
                o = vec4(float(gl_SampleID) / 3.0, gl_SamplePosition.x, gl_SamplePosition.y, 1.0);
                if (masked == 1) { o = vec4(1.0); gl_SampleMask[0] = 1; }
            }`);
        const ms32 = gen("Framebuffers");
        gl("glBindFramebuffer", 0x8D40, ms32);
        const rb32 = gen("Renderbuffers");
        gl("glBindRenderbuffer", 0x8D41, rb32);
        gl("glRenderbufferStorageMultisample", 0x8D41, 4, 0x8058, W, W);
        gl("glFramebufferRenderbuffer", 0x8D40, 0x8CE0, 0x8D41, rb32);
        gl("glBindBuffer", 0x8892, quad32);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        const resolved = async masked => {
            gl("glBindFramebuffer", 0x8D40, ms32);
            gl("glUniform1i", per_sample.at("masked"), masked);
            gl("glClearColor", 0, 0, 0, 1);
            gl("glClear", 0x4000);
            gl("glDrawArrays", 5, 0, 4);
            gl("glBindFramebuffer", 0x8CA9, 0);
            gl("glBlitFramebuffer", 0, 0, W, W, 0, 0, W, W, 0x4000, 0x2600);
            gl("glBindFramebuffer", 0x8D40, 0);
            return pixel(await read_pixels(0, 0, W, W), W, 3, 3);
        };
        const averaged = await resolved(0);
        check(near(averaged, [128, 128, 128, 255], 4), "per-sample shading: gl_SampleID and gl_SamplePosition averaged: " + averaged);
        const one = await resolved(1);
        check(near(one, [64, 64, 64, 255], 4), "gl_SampleMask: one sample of four written: " + one);
        // clamp to border: a red texture whose S clamps to a green border, sampled from u -1 to 1
        const bordered = program(`#version 320 es
            layout(location = 0) in vec2 position;
            out vec2 uv;
            void main() { uv = vec2(position.x, 0.5); gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            precision mediump float;
            uniform sampler2D tex;
            in vec2 uv;
            out vec4 o;
            void main() { o = texture(tex, uv); }`);
        const border_texture = next_texture++;
        gl("glActiveTexture", 0x84C0);
        gl("glBindTexture", 0x0DE1, border_texture);
        gl("glTexImage2D", 0x0DE1, 0, 0x8058, 1, 1, 0, 0x1908, 0x1401, new Uint8Array([255, 0, 0, 255]));
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2802, 0x812D);
        gl("glTexParameterfv", 0x0DE1, 0x1004, floats([0, 1, 0, 1]));
        gl("glUniform1i", bordered.at("tex"), 0);
        gl("glBindBuffer", 0x8892, quad32);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 4), [0, 255, 0, 255]) && near(pixel(window, W, 6, 4), [255, 0, 0, 255]), "clamp to border: the border's green left of u 0");
        // advanced blend equations: MULTIPLY and SCREEN of (1, 0.5, 0, 1) over (0.5, 1, 1, 1)
        const advanced = program(`#version 320 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 320 es
            precision mediump float;
            layout(blend_support_multiply, blend_support_screen) out;
            layout(location = 0) out vec4 color;
            void main() { color = vec4(1.0, 0.5, 0.0, 1.0); }`);
        void advanced;
        gl("glEnable", 0x0BE2);
        for(const [equation, expected, what] of [[0x9294, [128, 128, 0, 255], "MULTIPLY"], [0x9295, [255, 255, 255, 255], "SCREEN"]]) {
            gl("glClearColor", 0.5, 1, 1, 1);
            gl("glClear", 0x4000);
            gl("glBlendEquation", equation);
            gl("glDrawArrays", 5, 0, 4);
            const got = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
            check(near(got, expected), "an advanced blend equation: " + what + " " + got);
        }
        gl("glBlendEquation", 0x8006);
        gl("glDisable", 0x0BE2);
        // tessellation: a patch of 3 over the window, the control shader's colors and patch output, back faces culled (the
        // winding counterclockwise as the patch's); an outer level of 0 discards the patch
        const tess_shader = (type, source) => {
            const name = shader_name++;
            call("glCreateShader", name, [type]);
            gl("glShaderString", name, text(source), source.length + 1);
            gl("glCompileShader", name);
            return name;
        };
        const tessellated = shader_name++;
        const tess_shaders = [tess_shader(0x8B31, `#version 320 es
            layout(location = 0) in vec2 position;
            out vec4 v_color;
            void main() { v_color = vec4(1.0, 0.0, 0.0, 1.0); gl_Position = vec4(position, 0.0, 1.0); }`), tess_shader(0x8E88, `#version 320 es
            layout(vertices = 3) out;
            in vec4 v_color[];
            out vec4 c_color[];
            patch out vec4 p_tint;
            uniform float level;
            void main() {
                c_color[gl_InvocationID] = v_color[gl_InvocationID];
                gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;
                if (gl_InvocationID == 0) {
                    gl_TessLevelOuter[0] = level; gl_TessLevelOuter[1] = level; gl_TessLevelOuter[2] = level; gl_TessLevelInner[0] = level;
                    p_tint = vec4(0.0, 0.5, 0.0, 0.0);
                }
            }`), tess_shader(0x8E87, `#version 320 es
            layout(triangles, equal_spacing, ccw) in;
            in vec4 c_color[];
            patch in vec4 p_tint;
            out vec4 e_color;
            void main() {
                e_color = c_color[0] * gl_TessCoord.x + c_color[1] * gl_TessCoord.y + c_color[2] * gl_TessCoord.z + p_tint;
                gl_Position = gl_in[0].gl_Position * gl_TessCoord.x + gl_in[1].gl_Position * gl_TessCoord.y + gl_in[2].gl_Position * gl_TessCoord.z;
            }`), tess_shader(0x8B30, `#version 320 es
            precision mediump float;
            in vec4 e_color;
            out vec4 o;
            void main() { o = e_color; }`)];
        call("glCreateProgram", tessellated, []);
        for(const name of tess_shaders) gl("glAttachShader", tessellated, name);
        gl("glLinkProgram", tessellated);
        const tess_info = cpu.context(current).group.objects.get(tessellated).info;
        check(tess_info && tess_info.ok, "a program of tessellation shaders links: " + (tess_info && tess_info.log));
        gl("glUseProgram", tessellated);
        const patch32 = gen("Buffers");
        gl("glBindBuffer", 0x8892, patch32);
        const patch_vertices = floats([-1, -1, 3, -1, -1, 3]);
        gl("glBufferData", 0x8892, patch_vertices.length, patch_vertices, 0x88E4);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        gl("glEnable", 0x0B44);
        for(const [level, expected, what] of [[4, [255, 128, 0, 255], "tessellated, culled as the patch's winding"], [0, [0, 0, 0, 255], "an outer level of 0: no patch"]]) {
            gl("glUniform1f", tess_info.locations.get("level"), level);
            gl("glClearColor", 0, 0, 0, 1);
            gl("glClear", 0x4000);
            gl("glDrawArrays", 0xE, 0, 3);
            const got = pixel(await read_pixels(0, 0, W, W), W, 3, 3);
            check(near(got, expected), "tessellation: " + what + ": " + got);
        }
        gl("glDisable", 0x0B44);
        gl("glBindBuffer", 0x8892, quad32);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 0, 0);
        // struct varyings: a struct of a mat2, a flat struct of an int
        const structs = program(`#version 300 es
            layout(location = 0) in vec2 position;
            struct S { mediump mat2 a; };
            struct T { mediump int b; };
            out S s;
            flat out T t;
            void main() { s.a = mat2(0.25, 0.5, 0.75, 1.0); t.b = 3; gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            struct S { mediump mat2 a; };
            struct T { mediump int b; };
            in S s;
            flat in T t;
            out vec4 o;
            void main() { o = vec4(s.a[0][0], s.a[0][1], s.a[1][0], t.b == 3 ? 1.0 : 0.0); }`);
        void structs;
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [64, 128, 191, 255]), "struct varyings: a mat2's, a flat int's");
        // the negation of unsigned integers: two's complement
        const negated = program(`#version 300 es
            layout(location = 0) in vec2 position;
            void main() { gl_Position = vec4(position, 0.0, 1.0); }`, `#version 300 es
            precision mediump float;
            uniform highp uint u;
            out vec4 o;
            void main() {
                highp uvec2 r = -uvec2(u, 2u * u);
                // (and % of signed integers, of a vector by a scalar)
                ivec3 m = ivec3(7, 9, 11) % int(u + 3u);
                o = vec4(r.x == 0xFFFFFFFFu ? 1.0 : 0.0, r.y == 0xFFFFFFFEu ? 1.0 : 0.0, m == ivec3(3, 1, 3) ? 1.0 : 0.0, 1.0);
            }`);
        gl("glUniform1ui", negated.at("u"), 1);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [255, 255, 255, 255]), "an unsigned negation: two's complement; ivec3 % int");
        gl("glBindVertexArray", 0);
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        current = 1;

        // ---- a snapshot of the GLES 3.x contexts, restored on a new executor: buffers the GPU wrote (a dispatch's,
        // transform feedback's), an occlusion query's result, a cube map array, a vertex array of a binding point, a pipeline
        const es3_saved = await executor.save();
        executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        executor.restore(es3_saved);
        globalThis.glesExecutor = executor;
        const query_read = async q => {
            const id = request++;
            record(GLES.QUERY_READ, 1, id, q);
            await run();
            return new Uint32Array(answers.get(id).slice().buffer)[0];
        };
        check(await query_read(occlusion_queries[0]) === 1 && await query_read(occlusion_queries[1]) === 0, "restored: the occlusion queries' results");
        const restored_feedback = Array.from(new Float32Array((await read_buffer(feedback, 60)).slice().buffer));
        check(restored_feedback.join() === [-1, -1, 1, 2, -2, 3, -1, 1, 2, 6, -1, 3, 1, 2, -2].join(), "restored: the captured buffer: " + restored_feedback);
        record(GLES.MAKE_CURRENT, 1, 6, 2, 2);
        current = 6;
        check(Array.from(new Uint32Array((await read_buffer(data31, 32)).slice().buffer)).join() === "0,2,4,6,8,10,12,14", "restored: a dispatch's storage buffer");
        gl("glBindVertexArray", vao31);
        gl("glBindProgramPipeline", pipeline31);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 5, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 4, 4), [255, 128, 0, 255]) && near(pixel(window, W, 0, 0), [0, 0, 0, 255]),
            "restored: the pipeline, its programs' uniforms, the vertex array's binding point");
        gl("glBindProgramPipeline", 0);
        gl("glBindVertexArray", 0);
        record(GLES.MAKE_CURRENT, 1, 7, 2, 2);
        current = 7;
        gl("glBindVertexArray", vao32);
        gl("glUseProgram", halves.name);
        gl("glClear", 0x4000);
        gl("glDrawArrays", 4, 0, 3);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 4), [0, 0, 255, 255]) && near(pixel(window, W, 6, 4), [255, 255, 0, 255]), "restored: a geometry shader's program");
        gl("glUseProgram", cubes32.name);
        gl("glUniform1i", cubes32.at("which"), 0);
        gl("glDrawArrays", 5, 0, 4);
        check(near(pixel(await read_pixels(0, 0, W, W), W, 3, 3), [0, 0, 255, 255]), "restored: a cube map array's cube 1, +X");
        gl("glBindVertexArray", 0);
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        current = 1;

        check(!errors.length, "no WebGPU validation errors: " + errors.join("; "));
        check(!executor.stats.gles3, "nothing GLES 3.0's left out: " + JSON.stringify(executor.stats.gles3));
        check(!executor.stats.refused, "the page's shadow took what the CPU side took: " + JSON.stringify(executor.stats.refused_by));
        result.textContent = "PASS " + checks.length + " checks\n" + checks.join("\n");
    } catch(error) {
        const executor = globalThis.glesExecutor;
        result.textContent = "FAIL " + (error && error.stack || error) + "\nlast: " + JSON.stringify(globalThis.lastPixels || null) +
            "\nstats: " + JSON.stringify(executor && executor.stats) + "\nwebgpu: " + JSON.stringify(globalThis.webgpuErrors || []) +
            "\npassed: " + checks.join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                             source/v64/tests/glbridge/gles_executor_browser_test.html                                           0000644 0000000 0000000 00000063547 00000000000 021164  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLES executor: GLES batches on WebGPU</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The GLES executor (src/gles/page/gles_executor.js; docs/gles-proxy-plan.md
// E3) on a real GPU, fed batches as the GLES host writes them (the guest's
// commands encoded by gles_wire.js's encoder), its pixels read back:
// - clears, the scissor and the orientations: GL's rows from the bottom in
//   what is drawn to, color buffers in memory order (row 0 the top) after
//   rcFlushWindowColorBuffer;
// - draws from client arrays and buffers, fans; uniforms;
// - textures: RGB with an unpack alignment of 1, LUMINANCE, ETC1, mipmaps;
//   render to a texture through a framebuffer, glReadPixels from it and from
//   the window; blending, the depth test;
// - color buffers written and read back as they are; an EGL image of one
//   sampled through samplerExternalOES; a post handed over as a frame;
// - GLES 1.1's fixed function, draw_texture;
// - an empty glReadPixels answered;
// - a snapshot (E5): the executor's state saved (the GPU's contents read
//   back) and restored on a new executor: the window's and a color buffer's
//   pictures, textures (one rendered to), a buffer's bytes, programs linked
//   again, an EGL image, GLES 1.1's state.
import { encode_command } from "../../src/gles/gles_wire.js";
import { GLES, GLES_MAGIC, GXWriter } from "../../src/graphics_adapters/renderer_protocol.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };

(async () => {
    try {
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        device.onuncapturederror = e => { console.error(e.error.message); errors.push(e.error.message); };
        const errors = [];
        let executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        globalThis.glesExecutor = executor;
        globalThis.webgpuErrors = errors;

        // a batch being written, and its answers
        let writer = new GXWriter(GLES_MAGIC);
        let request = 1;
        const answers = new Map(), frames = [];
        const gl = (name, ...args) => {
            const bytes = encode_command("gles2:" + name, args);
            writer.command(GLES.COMMAND, [1, 0, bytes.length], bytes);
        };
        const created = (name, ret, ...args) => {
            const bytes = encode_command("gles2:" + name, args);
            writer.command(GLES.COMMAND, [1, ret, bytes.length], bytes);
            return ret;
        };
        const record = (op, ...dwords) => writer.command(op, dwords);
        const run = async () => {
            const bytes = writer.finish();
            await executor.submit(bytes, {
                writeResponse: (offset, data) => {
                    const view = new DataView(data.buffer, data.byteOffset);
                    answers.set(view.getUint32(0, true), view.getUint32(12, true) === 1 ? data.slice(16) : null);
                },
                frame: (rgba, width, height) => frames.push({ rgba, width, height }),
            });
            await device.queue.onSubmittedWorkDone();
            check(!executor.stats.errors.length, "no executor errors: " + executor.stats.errors.join("; "));
        };
        const read_color_buffer = async (handle, w, h) => {
            const id = request++;
            record(GLES.COLOR_BUFFER_READ, handle, 0, 0, w, h, 0x1908, 0x1401, id);
            await run();
            return answers.get(id);
        };
        const read_pixels = async (x, y, w, h) => {
            const id = request++;
            record(GLES.READ_PIXELS, 1, id, x, y, w, h, 0x1908, 0x1401);
            await run();
            return answers.get(id);
        };
        const pixel = (rgba, w, x, y) => { globalThis.lastPixels = Array.from(rgba); return Array.from(rgba.subarray((y * w + x) * 4, (y * w + x) * 4 + 4)); };
        const near = (a, b, tolerance = 2) => a.every((v, i) => Math.abs(v - b[i]) <= tolerance);
        const text = s => new TextEncoder().encode(s + "\0");
        const floats = values => new Uint8Array(new Float32Array(values).buffer);

        // a GLES 2.0 context on an 8 by 8 window (RGBA8888, depth 24, stencil 8: config 3) with its color buffer
        const W = 8;
        record(GLES.CONTEXT_CREATE, 1, 3, 0, 2);
        record(GLES.SURFACE_CREATE, 2, 3, W, W);
        record(GLES.COLOR_BUFFER_CREATE, 3, W, W, 0x1908);
        record(GLES.SURFACE_COLOR_BUFFER, 2, 3);
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);

        // ---- clears, the scissor, the orientations
        gl("glClearColor", 1, 0, 0, 1);
        gl("glClear", 0x4000);
        gl("glEnable", 0x0C11);
        gl("glScissor", 0, 0, W, W / 2);       // GL's bottom half
        gl("glClearColor", 0, 1, 0, 1);
        gl("glClear", 0x4000);
        gl("glDisable", 0x0C11);
        record(GLES.FLUSH_SURFACE, 2);
        let rgba = await read_color_buffer(3, W, W);
        check(near(pixel(rgba, W, 0, 0), [255, 0, 0, 255]), "the color buffer's row 0 is the top: red");
        check(near(pixel(rgba, W, 0, W - 1), [0, 255, 0, 255]), "its last row the bottom: the scissored green");
        let window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 0), [0, 255, 0, 255]), "glReadPixels' row 0 is GL's bottom: green");

        // ---- a program; a triangle from a client array; a fan from a buffer
        const vs = created("glCreateShader", 10, 0x8B31), fs = created("glCreateShader", 11, 0x8B30);
        const vs_text = "attribute vec2 position; attribute vec2 uv; varying vec2 v_uv; void main() { v_uv = uv; gl_Position = vec4(position, 0.0, 1.0); }";
        const fs_text = "precision mediump float; uniform vec4 color; uniform sampler2D tex; uniform float mix_tex; varying vec2 v_uv; " +
            "void main() { gl_FragColor = mix(color, texture2D(tex, v_uv), mix_tex); }";
        gl("glShaderString", vs, text(vs_text), vs_text.length + 1);
        gl("glShaderString", fs, text(fs_text), fs_text.length + 1);
        gl("glCompileShader", vs);
        gl("glCompileShader", fs);
        const program = created("glCreateProgram", 12);
        gl("glAttachShader", program, vs);
        gl("glAttachShader", program, fs);
        gl("glBindAttribLocation", program, 0, text("position"));
        gl("glBindAttribLocation", program, 1, text("uv"));
        gl("glLinkProgram", program);
        gl("glUseProgram", program);
        // (the locations the shadow state gives: color 0, mix_tex 1, tex 2)
        gl("glUniform4f", 0, 0, 0, 1, 1);
        gl("glUniform1f", 1, 0);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000 | 0x0100);
        // the left half: a triangle, client data (tight, from the first vertex)
        gl("glEnableVertexAttribArray", 0);
        const tri = [-1, -1, 0, -1, -1, 3];
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, floats(tri), 24);
        gl("glVertexAttrib2f", 1, 0, 0);
        gl("glDrawArrays", 4, 0, 3);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [0, 0, 255, 255]) && near(pixel(window, W, 1, 6), [0, 0, 255, 255]), "the left half drawn blue");
        check(near(pixel(window, W, 6, 1), [0, 0, 0, 255]), "the right half clear");

        // a texture: 2 by 2 RGB, unpack alignment 1 (rows of 6 bytes), nearest
        gl("glPixelStorei", 0x0CF5, 1);
        gl("glBindTexture", 0x0DE1, 20);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        // (row 0, t = 0: red, green; row 1: blue, white)
        gl("glTexImage2D", 0x0DE1, 0, 0x1907, 2, 2, 0, 0x1907, 0x1401, new Uint8Array([255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255]));
        gl("glUniform1i", 2, 0);
        gl("glUniform1f", 1, 1);
        // a full-window fan from a buffer: position and uv interleaved
        gl("glBindBuffer", 0x8892, 30);
        const quad = [-1, -1, 0, 0, 1, -1, 1, 0, 1, 1, 1, 1, -1, 1, 0, 1];
        gl("glBufferData", 0x8892, 64, floats(quad), 0x88E4);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 16, 0);
        gl("glEnableVertexAttribArray", 1);
        gl("glVertexAttribPointerOffset", 1, 2, 0x1406, 0, 16, 8);
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [255, 0, 0, 255]), "texture row 0 (t = 0) at GL's bottom left: red");
        check(near(pixel(window, W, 6, 1), [0, 255, 0, 255]), "bottom right: green");
        check(near(pixel(window, W, 1, 6), [0, 0, 255, 255]), "top left: blue");
        record(GLES.FLUSH_SURFACE, 2);
        rgba = await read_color_buffer(3, W, W);
        check(near(pixel(rgba, W, 1, 0), [0, 0, 255, 255]), "in the color buffer, flipped: blue at the top left");

        // LUMINANCE: (L, L, L, 1); ETC1: a block decoded
        gl("glTexImage2D", 0x0DE1, 0, 0x1909, 1, 1, 0, 0x1909, 0x1401, new Uint8Array([100]));
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 3, 3), [100, 100, 100, 255]), "a luminance texel");
        // (individual mode: colors 8 << 4 | 8 = 136 each, table 0, every pixel's index 0: +2)
        gl("glCompressedTexImage2D", 0x0DE1, 0, 0x8D64, 4, 4, 0, 8, new Uint8Array([0x88, 0x88, 0x88, 0x00, 0, 0, 0, 0]));
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 3, 3), [138, 138, 138, 255]), "an ETC1 block decoded");

        // ---- render to a texture; read it; sample it
        gl("glBindTexture", 0x0DE1, 21);
        gl("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl("glTexImage2D", 0x0DE1, 0, 0x1908, 4, 4, 0, 0x1908, 0x1401, null);
        gl("glBindFramebuffer", 0x8D40, 40);
        gl("glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x0DE1, 21, 0);
        gl("glViewport", 0, 0, 4, 4);
        gl("glClearColor", 1, 1, 0, 1);
        gl("glClear", 0x4000);
        gl("glUniform1f", 1, 0);
        gl("glUniform4f", 0, 0, 1, 1, 1);
        gl("glDisableVertexAttribArray", 1);
        gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, floats(tri), 24);
        gl("glDrawArrays", 4, 0, 3);
        const fbo = await read_pixels(0, 0, 4, 4);
        check(near(pixel(fbo, 4, 0, 0), [0, 255, 255, 255]) && near(pixel(fbo, 4, 3, 0), [255, 255, 0, 255]), "the framebuffer's pixels, GL's rows");
        gl("glBindFramebuffer", 0x8D40, 0);
        gl("glViewport", 0, 0, W, W);
        gl("glBindTexture", 0x0DE1, 21);
        gl("glUniform1f", 1, 1);
        gl("glEnableVertexAttribArray", 1);
        gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 16, 0);
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 0), [0, 255, 255, 255]) && near(pixel(window, W, 7, 0), [255, 255, 0, 255]), "the rendered texture, the same way up");

        // ---- blending, the depth test
        gl("glUniform1f", 1, 0);
        gl("glClearColor", 0, 0, 0, 1);
        gl("glClear", 0x4000 | 0x0100);
        gl("glEnable", 0x0BE2);
        gl("glBlendFunc", 0x0302, 0x0303);
        gl("glUniform4f", 0, 1, 1, 1, 0.5);
        gl("glDrawArrays", 6, 0, 4);
        gl("glDisable", 0x0BE2);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 4, 4), [128, 128, 128, 191], 3), "half white over black (alpha blended too: 0.75)");
        gl("glEnable", 0x0B71);
        gl("glUniform4f", 0, 1, 0, 0, 1);
        gl("glDrawArrays", 6, 0, 4);  // z 0: drawn (depth was 1)
        gl("glUniform4f", 0, 0, 1, 0, 1);
        gl("glDrawArrays", 6, 0, 4);  // z 0 again: GL_LESS fails
        gl("glDisable", 0x0B71);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 4, 4), [255, 0, 0, 255]), "the depth test kept the first");

        // ---- color buffers as they are; an EGL image of one
        const bytes = new Uint8Array(4 * 4 * 4).map((_, i) => i * 3);
        record(GLES.COLOR_BUFFER_CREATE, 50, 4, 4, 0x1908);
        writer.command(GLES.COLOR_BUFFER_UPDATE, [50, 0, 0, 4, 4, 0x1908, 0x1401, bytes.length], bytes);
        const back = await read_color_buffer(50, 4, 4);
        check(back.every((v, i) => v === bytes[i]), "a color buffer reads back what was written");
        record(GLES.IMAGE_CREATE, 60, 0, 0x3140, 50);
        const ext_text = "#extension GL_OES_EGL_image_external : require\nprecision mediump float; uniform samplerExternalOES tex; varying vec2 v_uv; " +
            "void main() { gl_FragColor = texture2D(tex, v_uv); }";
        const efs = created("glCreateShader", 13, 0x8B30);
        gl("glShaderString", efs, text(ext_text), ext_text.length + 1);
        gl("glCompileShader", efs);
        const ep = created("glCreateProgram", 14);
        gl("glAttachShader", ep, vs);
        gl("glAttachShader", ep, efs);
        gl("glBindAttribLocation", ep, 0, text("position"));
        gl("glBindAttribLocation", ep, 1, text("uv"));
        gl("glLinkProgram", ep);
        gl("glUseProgram", ep);
        gl("glBindTexture", 0x8D65, 22);
        gl("glEGLImageTargetTexture2DOES", 0x8D65, 60);
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        // (the color buffer's row 0 sampled at t = 0: GL's bottom row of the window)
        check(near(pixel(window, W, 0, 0), Array.from(bytes.subarray(0, 4))), "an EGL image's color buffer sampled as it is");

        // ---- a post
        record(GLES.FLUSH_SURFACE, 2);
        record(GLES.POST, 3);
        await run();
        check(frames.length === 1 && frames[0].width === W && frames[0].rgba.length === W * W * 4, "a post is a frame");
        check(near(pixel(frames[0].rgba, W, 0, W - 1), Array.from(bytes.subarray(0, 4))), "the frame from the top: the image's row 0 at its bottom");

        // ---- separate stencil state for the two faces (glStencilFuncSeparate:
        // WebGPU has one reference, so a draw goes once per face)
        {
            gl("glUseProgram", program);
            gl("glUniform1f", 1, 0);
            gl("glDisableVertexAttribArray", 1);
            gl("glClearStencil", 0);
            gl("glClearColor", 0, 0, 0, 1);
            gl("glClear", 0x4000 | 0x0400);
            gl("glEnable", 0x0B90);
            gl("glStencilFuncSeparate", 0x0404, 0x0207, 1, 0xFF);   // front: ALWAYS, ref 1
            gl("glStencilFuncSeparate", 0x0405, 0x0207, 2, 0xFF);   // back: ALWAYS, ref 2
            gl("glStencilOp", 0x1E00, 0x1E00, 0x1E01);             // REPLACE on pass
            // (the left half counter-clockwise: front; the right half clockwise: back)
            gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, floats([-1, -1, 0, -1, -1, 1, 0, -1, 0, 1, -1, 1, 0.01, -1, 0.01, 1, 1, -1, 1, -1, 0.01, 1, 1, 1]), 96);
            gl("glUniform4f", 0, 0, 0, 1, 1);
            gl("glDrawArrays", 4, 0, 12);
            // (then what the stencil holds: red where 1, green where 2)
            gl("glStencilFunc", 0x0202, 1, 0xFF);
            gl("glStencilOp", 0x1E00, 0x1E00, 0x1E00);
            gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, floats([-1, -1, 3, -1, -1, 3]), 24);
            gl("glUniform4f", 0, 1, 0, 0, 1);
            gl("glDrawArrays", 4, 0, 3);
            gl("glStencilFunc", 0x0202, 2, 0xFF);
            gl("glUniform4f", 0, 0, 1, 0, 1);
            gl("glDrawArrays", 4, 0, 3);
            gl("glDisable", 0x0B90);
            window = await read_pixels(0, 0, W, W);
            check(near(pixel(window, W, 1, 4), [255, 0, 0, 255]) && near(pixel(window, W, 6, 4), [0, 255, 0, 255]),
                "separate stencil: the front faces wrote 1, the back faces 2");
            gl("glEnableVertexAttribArray", 1);
        }

        // ---- a cube map: 2 by 2 faces of distinct texels, sampled by direction
        // (GLES 2.0 table 3.21: +X sc = -rz, tc = -ry; the texel (s, t) from row t)
        {
            const cvs = "attribute vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); }";
            const cfs = "precision mediump float; uniform samplerCube cube; uniform vec3 dir; void main() { gl_FragColor = textureCube(cube, dir); }";
            const v = created("glCreateShader", 90, 0x8B31), f = created("glCreateShader", 91, 0x8B30);
            gl("glShaderString", v, text(cvs), cvs.length + 1);
            gl("glShaderString", f, text(cfs), cfs.length + 1);
            gl("glCompileShader", v);
            gl("glCompileShader", f);
            const p = created("glCreateProgram", 92);
            gl("glAttachShader", p, v);
            gl("glAttachShader", p, f);
            gl("glBindAttribLocation", p, 0, text("position"));
            gl("glLinkProgram", p);
            gl("glUseProgram", p);
            gl("glActiveTexture", 0x84C0 + 3);
            gl("glBindTexture", 0x8513, 93);
            gl("glTexParameteri", 0x8513, 0x2801, 0x2600);
            gl("glTexParameteri", 0x8513, 0x2800, 0x2600);
            // (face f's texel (s, t): red 40 * f + 10 * (2 * t + s), green 100 + t, blue s;
            // uploaded -X first, as dEQP's tcu::CubeFace order: +X is not the first face given)
            for(const face of [1, 0, 3, 2, 5, 4])
            {
                const texels = new Uint8Array(16);
                for(let t = 0; t < 2; t++) for(let s0 = 0; s0 < 2; s0++) texels.set([40 * face + 10 * (2 * t + s0), 100 + t, s0 * 200, 255], (t * 2 + s0) * 4);
                gl("glTexImage2D", 0x8515 + face, 0, 0x1908, 2, 2, 0, 0x1908, 0x1401, texels);
            }
            // (sampler unit 3: the program's locations, dir 0 then cube 1, as the shadow gives them)
            gl("glUniform1i", 1, 3);
            gl("glDisable", 0x0BE2);
            gl("glDisable", 0x0B71);
            gl("glBindBuffer", 0x8892, 0);
            gl("glDisableVertexAttribArray", 1);
            gl("glEnableVertexAttribArray", 0);
            gl("glVertexAttribPointerData", 0, 2, 0x1406, 0, 0, floats([-1, -1, 3, -1, -1, 3]), 24);
            const probe = async (dir, face, s0, t) =>
            {
                gl("glUniform3f", 0, ...dir);
                gl("glDrawArrays", 4, 0, 3);
                const got = pixel(await read_pixels(0, 0, W, W), W, 4, 4);
                const want = [40 * face + 10 * (2 * t + s0), 100 + t, s0 * 200, 255];
                check(near(got, want), `cube: direction ${dir} samples face ${face}'s texel (${s0}, ${t}): got ${got}, want ${want}`);
            };
            // (+X: s from -rz, t from -ry; -X: s from rz, t from -ry; +Y: s from rx, t from rz;
            //  -Y: s from rx, t from -rz; +Z: s from rx, t from -ry; -Z: s from -rx, t from -ry)
            await probe([1, -0.5, -0.5], 0, 1, 1);
            await probe([1, 0.5, 0.5], 0, 0, 0);
            await probe([-1, -0.5, 0.5], 1, 1, 1);
            await probe([0.5, 1, 0.5], 2, 1, 1);
            await probe([0.5, -1, -0.5], 3, 1, 1);
            await probe([0.5, -0.5, 1], 4, 1, 1);
            await probe([-0.5, -0.5, -1], 5, 1, 1);
            // (the arrays as the sections after this one expect them: the quad's buffer)
            gl("glActiveTexture", 0x84C0);
            gl("glBindBuffer", 0x8892, 30);
            gl("glVertexAttribPointerOffset", 0, 2, 0x1406, 0, 16, 0);
            gl("glEnableVertexAttribArray", 1);
        }

        // ---- GLES 1.1: the fixed function
        const gl1 = (name, ...args) => {
            const bytes = encode_command("gles1:" + name, args);
            writer.command(GLES.COMMAND, [1, 0, bytes.length], bytes);
        };
        record(GLES.CONTEXT_CREATE, 70, 3, 0, 1);
        record(GLES.MAKE_CURRENT, 1, 70, 2, 2);
        gl1("glClearColor", 0, 0, 0, 1);
        gl1("glClear", 0x4000 | 0x0100);
        gl1("glMatrixMode", 0x1701);
        gl1("glLoadIdentity");
        gl1("glOrthof", 0, W, 0, W, -1, 1);
        gl1("glMatrixMode", 0x1700);
        gl1("glLoadIdentity");
        // the left half, from a client array, the current color
        gl1("glColor4f", 1, 0.5, 0, 1);
        gl1("glEnableClientState", 0x8074);
        gl1("glVertexPointerData", 2, 0x1406, 0, floats([0, 0, W / 2, 0, W / 2, W, 0, 0, W / 2, W, 0, W]), 48);
        gl1("glDrawArrays", 4, 0, 6);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [255, 128, 0, 255]) && near(pixel(window, W, 6, 6), [0, 0, 0, 255]), "GLES 1.1: glOrthof, a client array, the current color");
        // a texture, MODULATE with a color array (unsigned bytes, normalized), GL_TEXTURE_2D on unit 0
        gl1("glBindTexture", 0x0DE1, 80);
        gl1("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl1("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl1("glTexImage2D", 0x0DE1, 0, 0x1908, 1, 1, 0, 0x1908, 0x1401, new Uint8Array([255, 255, 255, 255]));
        gl1("glEnable", 0x0DE1);
        gl1("glEnableClientState", 0x8076);
        gl1("glColorPointerData", 4, 0x1401, 0, new Uint8Array(24).map((_, i) => [0, 255, 0, 255][i % 4]), 24);
        gl1("glEnableClientState", 0x8078);
        gl1("glTexCoordPointerData", 0, 2, 0x1406, 0, floats(new Array(12).fill(0.5)), 48);
        gl1("glTranslatef", W / 2, 0, 0);
        gl1("glDrawArrays", 4, 0, 6);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 6, 2), [0, 255, 0, 255]) && near(pixel(window, W, 1, 1), [255, 128, 0, 255]), "a texture modulated by a color array, translated");
        // a light: directional, along +z, a white material's diffuse
        gl1("glDisable", 0x0DE1);
        gl1("glDisableClientState", 0x8076);
        gl1("glDisableClientState", 0x8078);
        gl1("glLoadIdentity");
        gl1("glEnable", 0x0B50);
        gl1("glEnable", 0x4000);
        gl1("glLightfv", 0x4000, 0x1203, floats([0, 0, 1, 0]));
        gl1("glMaterialfv", 0x0408, 0x1201, floats([0.5, 0.5, 0.5, 1]));
        gl1("glMaterialfv", 0x0408, 0x1200, floats([0, 0, 0, 1]));
        gl1("glLightModelfv", 0x0B53, floats([0, 0, 0, 1]));
        gl1("glNormal3f", 0, 0, 1);
        gl1("glDrawArrays", 4, 0, 6);
        gl1("glDisable", 0x0B50);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 1, 1), [128, 128, 128, 255], 3), "lit by one light: the material's diffuse");
        // draw_texture: the texture's crop rectangle at a window rectangle
        gl1("glBindTexture", 0x0DE1, 81);
        gl1("glTexParameteri", 0x0DE1, 0x2801, 0x2600);
        gl1("glTexParameteri", 0x0DE1, 0x2800, 0x2600);
        gl1("glTexImage2D", 0x0DE1, 0, 0x1907, 2, 1, 0, 0x1907, 0x1401, new Uint8Array([255, 0, 0, 0, 0, 255]));
        gl1("glTexParameteriv", 0x0DE1, 0x8B9D, new Uint8Array(new Int32Array([1, 0, 1, 1]).buffer));
        gl1("glEnable", 0x0DE1);
        gl1("glColor4f", 1, 1, 1, 1);
        gl1("glTexEnvi", 0x2300, 0x2200, 0x1E01);
        gl1("glDrawTexiOES", 4, 4, 0, 4, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 6, 6), [0, 0, 255, 255]) && near(pixel(window, W, 1, 1), [128, 128, 128, 255], 3), "glDrawTexiOES: the crop rectangle's texel at the window rectangle");

        // ---- points: one pixel each (WebGPU's point list)
        gl1("glDisable", 0x0DE1);
        gl1("glClear", 0x4000);
        gl1("glColor4f", 0, 1, 0, 1);
        gl1("glVertexPointerData", 2, 0x1406, 0, floats([4.5, 4.5]), 8);
        gl1("glDrawArrays", 0, 0, 1);
        gl1("glEnable", 0x0DE1);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 4, 4), [0, 255, 0, 255]) && near(pixel(window, W, 1, 1), [0, 0, 0, 255]), "a point: its pixel");

        // ---- an empty read is answered (no rows to copy)
        const empty = await read_pixels(0, 0, 0, 0);
        check(empty && empty.length === 0, "an empty glReadPixels is answered");

        // ---- a snapshot: saved, restored on a new executor
        const same = (a, b) => a && b && a.length === b.length && a.every((v, i) => v === b[i]);
        const window_before = await read_pixels(0, 0, W, W);
        const cb_before = await read_color_buffer(3, W, W);
        const saved = await executor.save();
        check(typeof saved[0] === "string" && saved[1].length > 0, "a snapshot's page state: " + saved[0].length + " bytes of JSON, " +
            saved[1].length + " contents");
        executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        executor.restore(saved);
        check(same(await read_pixels(0, 0, W, W), window_before), "restored: the window surface's picture");
        check(same(await read_color_buffer(3, W, W), cb_before), "restored: a color buffer's picture");
        gl1("glClear", 0x4000);
        gl1("glDrawTexiOES", 4, 4, 0, 4, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 6, 6), [0, 0, 255, 255]) && near(pixel(window, W, 1, 1), [0, 0, 0, 255]),
            "restored: GLES 1.1's texture, crop rectangle and environment");
        record(GLES.MAKE_CURRENT, 1, 1, 2, 2);
        gl("glUseProgram", program);
        gl("glBindTexture", 0x0DE1, 21);
        gl("glUniform1f", 1, 1);
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 0), [0, 255, 255, 255]) && near(pixel(window, W, 7, 0), [255, 255, 0, 255]),
            "restored: a program linked again, a buffer's bytes, a texture rendered to");
        gl("glUseProgram", ep);
        gl("glDrawArrays", 6, 0, 4);
        window = await read_pixels(0, 0, W, W);
        check(near(pixel(window, W, 0, 0), Array.from(bytes.subarray(0, 4))), "restored: an EGL image's color buffer");

        check(!errors.length, "no WebGPU validation errors: " + errors.join("; "));
        result.textContent = "PASS " + checks.length + " checks\n" + checks.join("\n");
    } catch(error) {
        const executor = globalThis.glesExecutor;
        result.textContent = "FAIL " + (error && error.stack || error) + "\nlast: " + JSON.stringify(globalThis.lastPixels || null) +
            "\nstats: " + JSON.stringify(executor && executor.stats) + "\nwebgpu: " + JSON.stringify(globalThis.webgpuErrors || []) +
            "\npassed: " + checks.join("\n");
    }
})();
</script>
                                                                                                                                                         source/v64/tests/glbridge/gles_remote_renderer.html                                                 0000644 0000000 0000000 00000014335 00000000000 017674  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLES renderer for a Node test</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
// The page end of tests/gles/chrome_renderer.mjs: the renderer
// (V86SVGARenderer, its GLES executor) on this page's GPU, its channel's
// messages over HTTP (GET /gles/next, POST /gles/reply; five u32s, then the
// bytes padded to a u32; a snapshot's GLES state as tests/gles/chrome_renderer.mjs's encode_state).
// A request that fails (a suspend breaks them all) is made again: the
// answers read so far go with /gles/next, a reply's number with /gles/reply.
"use strict";
const KIND = { submit: 1, reset: 2, hello: 3, gles_save: 4, gles_restore: 5, done: 11, write: 12, frame: 13, lost: 14, caps: 15, gles_saved: 16 };

function encode_state([json, buffers])
{
    const text = new TextEncoder().encode(json);
    const out = new Uint8Array(8 + text.length + buffers.reduce((n, b) => n + 4 + b.length, 0));
    const view = new DataView(out.buffer);
    view.setUint32(0, text.length, true);
    out.set(text, 4);
    let at = 4 + text.length;
    view.setUint32(at, buffers.length, true);
    at += 4;
    for(const b of buffers)
    {
        view.setUint32(at, b.length, true);
        out.set(b, at + 4);
        at += 4 + b.length;
    }
    return out;
}

function decode_state(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const length = view.getUint32(0, true);
    const json = new TextDecoder().decode(bytes.subarray(4, 4 + length));
    let at = 4 + length;
    const count = view.getUint32(at, true);
    at += 4;
    const buffers = [];
    for(let i = 0; i < count; i++)
    {
        const n = view.getUint32(at, true);
        buffers.push(bytes.slice(at + 4, at + 4 + n));
        at += 4 + n;
    }
    return [json, buffers];
}
let handler = null;
let outbox = [];
let sending = null;
let replies = 0;
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

/** a line on the test's console (lost if the server is out of reach) */
function log(text)
{
    fetch("/gles/log", { method: "POST", body: text }).catch(() => {});
}

function encode(messages)
{
    const size = messages.reduce((n, m) => n + 20 + ((m.bytes ? m.bytes.length : 0) + 3 & ~3), 0);
    const out = new Uint8Array(size), view = new DataView(out.buffer);
    let at = 0;
    for(const m of messages)
    {
        const length = m.bytes ? m.bytes.length : 0;
        [m.kind, m.a >>> 0, m.b >>> 0, 0, length].forEach((v, i) => view.setUint32(at + 4 * i, v, true));
        if(length) out.set(m.bytes, at + 20);
        at += 20 + (length + 3 & ~3);
    }
    return out;
}

/** the renderer's answers, posted together (in order) */
function flush()
{
    if(sending || !outbox.length) return;
    const body = encode(outbox);
    outbox = [];
    const n = ++replies;
    const post = () => fetch("/gles/reply?n=" + n, { method: "POST", body }).then(response => { if(!response.ok) throw new Error("HTTP " + response.status); })
        .catch(error => { log("reply " + n + " again after " + error); return pause(1000).then(post); });
    sending = post().finally(() => { sending = null; flush(); });
}

const channel = {
    post(message)
    {
        switch(message.type)
        {
            case "done": outbox.push({ kind: KIND.done, a: message.seq, b: 0, bytes: null }); break;
            case "write": outbox.push({ kind: KIND.write, a: message.offset || 0, b: 0, bytes: new Uint8Array(message.bytes) }); break;
            case "frame": outbox.push({ kind: KIND.frame, a: message.width, b: message.height, bytes: new Uint8Array(message.bytes) }); break;
            case "lost": outbox.push({ kind: KIND.lost, a: 0, b: 0, bytes: new TextEncoder().encode(String(message.reason)) }); break;
            case "caps": outbox.push({ kind: KIND.caps, a: message.present ? 1 : 0, b: 0, bytes: null }); break;
            case "gles_saved":
                outbox.push({ kind: KIND.gles_saved, a: message.id, b: message.state ? 1 : 0, bytes: message.state ? encode_state(message.state) : null });
                break;
        }
        queueMicrotask(flush);
    },
    listen(h) { handler = h; },
};

(async () => {
    try {
        globalThis.renderer = globalThis.V86SVGARenderer(channel, {});
        for(let got = 0; ; got++)
        {
            let bytes;
            for(;;)
            {
                try { bytes = new Uint8Array(await (await fetch("/gles/next?got=" + got)).arrayBuffer()); break; }
                catch(error) { log("next again after " + error); await pause(1000); }
            }
            const view = new DataView(bytes.buffer);
            for(let at = 0; at + 20 <= bytes.length;)
            {
                const kind = view.getUint32(at, true), a = view.getUint32(at + 4, true), stream = view.getUint32(at + 12, true);
                const length = view.getUint32(at + 16, true);
                const body = bytes.slice(at + 20, at + 20 + length);
                at += 20 + (length + 3 & ~3);
                if(kind === KIND.submit) handler({ type: "submit", seq: a, bytes: body, stream: stream === 1 ? "gles" : undefined });
                else if(kind === KIND.reset) handler({ type: "reset" });
                else if(kind === KIND.hello) handler({ type: "hello" });
                else if(kind === KIND.gles_save) handler({ type: "gles_save", id: a });
                else if(kind === KIND.gles_restore) handler({ type: "gles_restore", state: decode_state(body) });
            }
        }
    } catch(error) {
        log(String(error && error.stack || error));
        document.getElementById("result").textContent = "FAIL " + error;
    }
})();
setInterval(() => {
    // (WebGPU's validation errors and a lost device's reason, reported once the device is up)
    const device = globalThis.renderer && globalThis.renderer.executor.device;
    if(device && !device.onuncapturederror)
    {
        device.onuncapturederror = e => log("WebGPU: " + e.error.message);
        device.lost.then(info => log("WebGPU device lost (" + info.reason + "): " + info.message));
    }
    const g = globalThis.renderer && globalThis.renderer.gles;
    if(g && g.stats.errors.length) log("executor errors: " + JSON.stringify(g.stats.errors.splice(0)));
}, 5000);
</script>
                                                                                                                                                                                                                                                                                                   source/v64/tests/glbridge/gles_replay_browser_test.html                                             0000644 0000000 0000000 00000005760 00000000000 020613  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLES executor: a recorded boot replayed</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A boot's GLES batches as the GLES host sent them (tests/a32/android_boot.mjs
// with A32_ANDROID_GPU=host records them: each a u32 length, then the batch),
// run through the GLES executor on a real GPU (docs/gles-proxy-plan.md E3).
// Every post's frame is kept; the last one, and every tenth, go to
// build/browser-test-output/ as PNGs (gles-replay-<n>.png). PASS: every
// batch ran without the executor's or WebGPU's errors, and a frame was posted.
// ?batches=<path from the repository's root>
const result = document.getElementById("result");
const params = new URLSearchParams(location.search);

/** RGBA rows from the top as a PNG */
async function png(rgba, width, height)
{
    const canvas = new OffscreenCanvas(width, height);
    canvas.getContext("2d").putImageData(new ImageData(new Uint8ClampedArray(rgba), width, height), 0, 0);
    return new Uint8Array(await (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer());
}
const save = (name, bytes) => fetch("/__test_file?name=" + name, { method: "POST", body: bytes });

(async () => {
    try {
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        const errors = [];
        device.onuncapturederror = e => { if(errors.length < 20) errors.push(e.error.message); };
        const executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        const bytes = new Uint8Array(await (await fetch("../../" + params.get("batches"))).arrayBuffer());
        const frames = [];
        let at = 0, batches = 0;
        const started = performance.now();
        while(at < bytes.length)
        {
            const length = new DataView(bytes.buffer, at, 4).getUint32(0, true);
            await executor.submit(bytes.slice(at + 4, at + 4 + length), {
                writeResponse: () => {},
                frame: (rgba, width, height) => frames.push({ rgba, width, height, batch: batches }),
            });
            at += 4 + length;
            batches++;
        }
        await device.queue.onSubmittedWorkDone();
        const ms = performance.now() - started;
        for(let i = 0; i < frames.length; i++)
        {
            if(i % 10 && i !== frames.length - 1) continue;
            const f = frames[i];
            await save(`gles-replay-${i === frames.length - 1 ? "last" : i}.png`, await png(f.rgba, f.width, f.height));
        }
        const stats = JSON.stringify(executor.stats);
        const ok = !executor.stats.errors.length && !errors.length && frames.length;
        result.textContent = (ok ? "PASS " : "FAIL ") + `${batches} batches, ${frames.length} frames in ${ms.toFixed(0)} ms\n${stats}\n` +
            errors.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error && error.stack || error);
    }
})();
</script>
                source/v64/tests/glbridge/gles_replay_stats_browser_test.html                                       0000644 0000000 0000000 00000005552 00000000000 022030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLES executor: a recorded run timed</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A recorded run's GLES batches (tests/a32/android_boot.mjs's
// gles-batches.bin: each batch a u32 length, then the batch) replayed on a
// fresh GLES executor in order, as the page runs them (gles_replay_browser_test.html
// keeps their frames; this one keeps nothing): the time they take
// on this GPU and the executor's stats (translations and their time,
// pipelines, vertex arrays and index lists assembled on the CPU), for
// docs/gles3-plan.md L7. ?file=<the recording, from the repository's root>.
// PASS when no batch failed and WebGPU reported no error.
const result = document.getElementById("result");
(async () => {
    try {
        const file = new URLSearchParams(location.search).get("file") || "build/a32-android/runs/v86-gles3-boot/gles-batches.bin";
        const adapter = await navigator.gpu.requestAdapter();
        const optional = ["texture-compression-etc2", "texture-compression-astc", "texture-component-swizzle"].filter(f => adapter.features.has(f));
        const device = await adapter.requestDevice({ requiredFeatures: optional });
        const errors = [];
        device.onuncapturederror = e => errors.push(e.error.message);
        const executor = new globalThis.V86GLESExecutor.GLESExecutor({ device, layer: null });
        const bytes = new Uint8Array(await (await fetch("../../" + file)).arrayBuffer());
        const sink = { writeResponse() {} };
        let at = 0, batches = 0, slowest = 0;
        const start = performance.now();
        while(at + 4 <= bytes.length) {
            const length = new DataView(bytes.buffer, at, 4).getUint32(0, true);
            const t = performance.now();
            await executor.submit(bytes.slice(at + 4, at + 4 + length), sink);
            slowest = Math.max(slowest, performance.now() - t);
            at += 4 + length;
            batches++;
        }
        await device.queue.onSubmittedWorkDone();
        const ms = performance.now() - start;
        const s = executor.stats;
        const summary = { file, batches, bytes: bytes.length, ms: Math.round(ms), per_batch_ms: +(ms / batches).toFixed(2), slowest_batch_ms: Math.round(slowest),
            draws: s.draws, pipelines: s.pipelines, translations: s.translations || 0, translate_ms: Math.round(s.translate_ms || 0),
            cpu_arrays: s.cpu_arrays || 0, index_lists: s.index_lists || 0, uploads: s.uploads, posts: s.posts, refused: s.refused, gles3: s.gles3 || {} };
        if(s.errors.length || errors.length) throw new Error("errors: " + s.errors.concat(errors).slice(0, 5).join("; "));
        result.textContent = "PASS " + JSON.stringify(summary);
    } catch(e) {
        result.textContent = "FAIL " + (e.stack || e);
    }
})();
</script>
                                                                                                                                                      source/v64/tests/glbridge/gles_shader_browser_test.html                                             0000644 0000000 0000000 00000014027 00000000000 020561  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GLSL to WGSL through Chrome's Tint</title>
<pre id="result">RUNNING</pre>
<script src="../../src/browser/glbridge/gl-webgpu/gl_state_layout.js"></script>
<script src="../../src/browser/glbridge/gl-webgpu/gl_shader_translator.js"></script>
<script type="module">
// The shader translator's output checked by Chrome's own WGSL compiler
// (createShaderModule, getCompilationInfo). naga, which
// gl_shader_wgsl_validation_test.js uses, does not check the fragment
// stage's uniformity; Tint does, and refuses a derivative in non-uniform
// control flow unless the module turns derivative_uniformity off
// (docs/gles3-plan.md L0). The cases are the four that failed before:
// a sample in a varying-dependent if, in a function called from one, after
// an early return under a varying condition, and in a loop after a
// varying-dependent break; with a write to an `in` parameter and the
// equality and integer operators WGSL takes differently.
const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const T = globalThis.GLShaderTranslator;

const VS = "attribute vec4 pos;\nvarying vec2 tc;\nvoid main(void) { tc = pos.xy; gl_Position = pos; }";
const ES_CASES = {
    "a sample in a varying-dependent if":
        "precision mediump float;\nuniform sampler2D tex;\nvarying vec2 tc;\n" +
        "void main(void) {\n  vec4 c = vec4(0.0);\n  if (tc.x > 0.5) { c = texture2D(tex, tc); }\n  gl_FragColor = c;\n}",
    "a sample in a function called from one, which writes its in parameter":
        "precision mediump float;\nuniform sampler2D tex;\nvarying vec2 tc;\n" +
        "vec4 look(vec2 c) { c = c * 2.0; return texture2D(tex, c); }\n" +
        "void main(void) {\n  vec4 c = vec4(0.0);\n  if (tc.y > 0.5) { c = look(tc); }\n  gl_FragColor = c;\n}",
    "a sample after an early return":
        "precision mediump float;\nuniform sampler2D tex;\nvarying vec2 tc;\n" +
        "void main(void) {\n  if (tc.x > 0.5) { gl_FragColor = vec4(1.0); return; }\n  gl_FragColor = texture2D(tex, tc);\n}",
    "a sample in a loop after a break":
        "precision mediump float;\nuniform samplerCube cube;\nvarying vec2 tc;\n" +
        "void main(void) {\n  vec4 c = vec4(0.0);\n  for (int i = 0; i < 4; i++) {\n" +
        "    if (tc.x > float(i) * 0.25) break;\n    c += textureCube(cube, vec3(tc, 1.0));\n  }\n  gl_FragColor = c;\n}",
    "equality of vectors, matrices and structs":
        "precision mediump float;\nstruct S { vec2 a; mat2 m; };\nuniform S s0;\nuniform S s1;\n" +
        "uniform mat3 m0;\nuniform mat3 m1;\nvarying vec2 tc;\n" +
        "void main(void) {\n  bool e = tc == vec2(0.5) || m0 != m1 || s0 == s1;\n  gl_FragColor = e ? vec4(1.0) : vec4(0.0);\n}",
};
const DESKTOP_CASES = {
    "integer operators beside vectors, shifts":
        "uniform int k;\nuniform ivec2 v;\n" +
        "void main(void) {\n  ivec2 a = v & k;\n  int s = k << k;\n  ivec2 c = v >> k;\n  a ^= k;\n" +
        "  gl_FragColor = vec4(vec2(a + c), float(s), 1.0);\n}",
};
const ES_REFUSED = {
    "'%' in GLSL ES 1.00": "precision mediump float;\nuniform int k;\nvoid main(void) { gl_FragColor = vec4(float(k % 2)); }",
    "'&' in GLSL ES 1.00": "precision mediump float;\nuniform int k;\nvoid main(void) { gl_FragColor = vec4(float(k & 1)); }",
};

async function compiles(device, wgsl)
{
    const module = device.createShaderModule({ code: wgsl });
    const info = await module.getCompilationInfo();
    return info.messages.filter(m => m.type === "error").map(m => m.lineNum + ": " + m.message);
}

// ?corpus=<file>: the WGSL tests/gles/shader_corpus.mjs --wgsl wrote (the
// GLES host's glslang and vx_naga path), every module compiled here too
const corpus = new URLSearchParams(location.search).get("corpus");

(async () => {
    try {
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        if(corpus)
        {
            const modules = await (await fetch("../../" + corpus)).json();
            const failed = [];
            for(const m of modules)
            {
                const errors = await compiles(device, m.wgsl);
                if(errors.length) failed.push(m.label + ": " + errors.slice(0, 2).join("; "));
            }
            check(!failed.length, modules.length + " corpus modules, " + failed.length + " refused by Tint" +
                (failed.length ? ":\n" + failed.slice(0, 20).join("\n") : ""));
            result.textContent = "PASS " + checks.length + " checks\n" + checks.join("\n");
            return;
        }
        const link = (vs, fs, es) => {
            const v = T.compileShader(vs, "vertex", { es });
            const f = T.compileShader(fs, "fragment", { es });
            if(!v.ok || !f.ok) throw new Error("compile: " + v.log + f.log);
            const p = T.linkProgram(v, f, { es });
            if(!p.ok) throw new Error("link: " + p.log);
            return p;
        };
        for(const [label, fs] of Object.entries(ES_CASES))
        {
            const p = link(VS, fs, true);
            const errors = [...await compiles(device, p.wgslVertex), ...await compiles(device, p.wgslFragment)];
            check(!errors.length, "ES: " + label + (errors.length ? ": " + errors.join("; ") : ""));
        }
        for(const [label, fs] of Object.entries(DESKTOP_CASES))
        {
            const p = link(VS, fs, false);
            const errors = [...await compiles(device, p.wgslVertex), ...await compiles(device, p.wgslFragment)];
            check(!errors.length, "desktop: " + label + (errors.length ? ": " + errors.join("; ") : ""));
        }
        for(const [label, fs] of Object.entries(ES_REFUSED))
        {
            check(!T.compileShader(fs, "fragment", { es: true }).ok, "refused: " + label);
        }
        result.textContent = "PASS " + checks.length + " checks\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error && error.stack || error) + "\npassed: " + checks.join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/glbridge/graphics_checkpoint_browser_test.html                                     0000644 0000000 0000000 00000023710 00000000000 022307  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>Graphics checkpoint GPU round trip</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script src="../../build/libv86.js"></script>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script src="gl_stream_builder.js"></script>
<script>
(async () => {
    const errors = [], checks = [];
    let mainCompressions = 0;
    const NativeCompressionStream = globalThis.CompressionStream;
    globalThis.CompressionStream = class extends NativeCompressionStream {
        constructor(format) { super(format); ++mainCompressions; }
    };
    const check = (ok, text) => { if (!ok) throw new Error(text); checks.push(text); };
    // A compositor window layer, or an overlay canvas
    const shown = canvas => canvas.layer ? canvas.layer.visible : getComputedStyle(canvas).display !== "none";
    const gpu = {
        getPreferredCanvasFormat: () => navigator.gpu.getPreferredCanvasFormat(),
        async requestAdapter(options) {
            const adapter = await navigator.gpu.requestAdapter(options);
            return { features: adapter.features, async requestDevice(descriptor) {
                const device = await adapter.requestDevice(descriptor);
                device.addEventListener("uncapturederror", event => errors.push(event.error.message));
                return device;
            } };
        },
    };
    const create = async state => {
        const emulator = new V86({ graphics_adapter: "bochs_vga", wasm_path: "../../build/v86.wasm",
            memory_size: 32 * 1024 * 1024,
            bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
            screen_container: document.getElementById("screen"),
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false,
            graphics_proxy: { graphicsJournalMemoryBytes: 1, hostOptions: { gpu }, gl: { hostOptions: { gpu } } },
            initial_state: state ? { buffer: state } : undefined });
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        emulator.v86.cpu.devices.vga.graphical_mode = true;
        emulator.screen_adapter.set_mode(true);
        return emulator;
    };
    const words = values => {
        const bytes = new Uint8Array(values.length * 4), view = new DataView(bytes.buffer);
        values.forEach((value, i) => view.setUint32(i * 4, value >>> 0, true));
        return bytes;
    };
    const batch = (api, session, commands) => {
        const payloads = commands.map(([op, values]) => ({ op, bytes: words(values) }));
        const count = payloads.reduce((size, cmd) => size + ((16 + cmd.bytes.length + 7) & ~7), 0);
        const bytes = new Uint8Array(40 + count), view = new DataView(bytes.buffer);
        view.setUint16(0, api === 8 ? 0xffe0 : 0xffe1, true);
        view.setUint16(2, 0xffff, true); view.setUint32(4, 32 + count, true);
        view.setUint32(8, api === 8 ? 0x47573844 : 0x47573944, true);
        view.setUint16(12, 1, true); view.setUint16(14, 7, true);
        view.setUint32(24, commands.length, true); view.setUint32(28, count, true);
        view.setUint32(32, session, true);
        let offset = 40;
        for (const cmd of payloads) {
            const size = (16 + cmd.bytes.length + 7) & ~7;
            view.setUint16(offset, cmd.op, true); view.setUint32(offset + 4, size, true);
            bytes.set(cmd.bytes, offset + 16); offset += size;
        }
        return bytes;
    };
    const send = (emulator, bytes, flags = 0) => emulator.graphics_proxy.bridge.pushPCIBatch({
        bytes, flags, batchAddr: 0x100020, descAddr: 0x100000,
        writeGuestMemory() { throw new Error("unexpected DMA write in pixel fixture"); } });
    // D3D9 heartbeat writes are normal live traffic, but replay has no guest writer.
    const sendD3D = (emulator, bytes) => emulator.graphics_proxy.bridge.pushPCIBatch({ bytes,
        writeGuestMemory() {}, batchAddr: 0x100020, descAddr: 0x100000 });
    const createDevice = [2, [2, 0x1234, 0, 0, 64, 64, 22, 1, 0x20, 0, 75, 0, 0]];
    const color = (value) => [5, [2, 1, value, 0x3f800000, 0, 0]];
    let emulator = await create();
    const { GLStream, GL } = GLTestStream;
    send(emulator, new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CLEAR_COLOR", 1, 1, 1, 1).call("CLEAR", GL.COLOR_BUFFER_BIT).bytes(), 1);
    await sendD3D(emulator, batch(8, 8, [[1, [32, 0, 8, 0]],
        [2, createDevice[1].slice(0, 11)], color(0xff0000ff)]));
    await sendD3D(emulator, batch(9, 9, [createDevice,
        [0x110, [2, 0x301, 64, 64, 1, 21, 1, 0, 0, 0]],
        [0x20f, [2, 0, 0x301, 0]], color(0xffff0000)]));
    await sendD3D(emulator, batch(9, 10, [createDevice,
        [0x110, [2, 0x302, 64, 64, 1, 21, 1, 0, 0, 0]],
        [0x500, [2, 0, 0, 0, 0, 0, 0, 0, 0x302, 0, 0, 16,
            0, 0, 64, 64, 0xff00ff00, 0, 0, 0]] ]));
    emulator.write_memory(new Uint8Array([42]), 0x80000);
    const saved = await emulator.save_state();
    const journal = emulator.graphics_proxy.bridge.graphicsJournal;
    check(!!journal.compressor.worker, "journal compression runs in a dedicated worker");
    check(mainCompressions === 0, "saving does not compress on the emulation thread");
    check(journal.residentBytes <= 1 && journal.pages.some(page => page.key), "compressed pages spill to IndexedDB");
    check(!emulator.graphics_proxy.bridge.preparedCheckpoint, "save releases its temporary compressed checkpoint");
    const pixel = async (device, texture) => {
        const buffer = device.createBuffer({ size: 256, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
        const encoder = device.createCommandEncoder();
        encoder.copyTextureToBuffer({ texture }, { buffer, bytesPerRow: 256 }, [1, 1, 1]);
        device.queue.submit([encoder.finish()]);
        await buffer.mapAsync(GPUMapMode.READ);
        const rgba = [...new Uint8Array(buffer.getMappedRange()).slice(0, 4)];
        buffer.unmap(); buffer.destroy();
        if (texture.format.startsWith("bgra")) [rgba[0], rgba[2]] = [rgba[2], rgba[0]];
        return rgba.join();
    };
    const verify = async label => {
        const bridge = emulator.graphics_proxy.bridge, device = bridge.glExecutor.device;
        check(await pixel(device, bridge.glExecutor.backBuffer) === "255,255,255,255", label + " GL rendered pixels");
        check(await pixel(device, bridge.d3d8Executor.devices.get(2).backBuffer) === "0,0,255,255", label + " D3D8 unfinished back buffer");
        const sessions = bridge.d3d9Executor.sessionStates;
        check(await pixel(device, sessions.get("0000000000000009").resources.get(0x301).gpuTexture) === "255,0,0,255", label + " D3D9 render target");
        check(await pixel(device, sessions.get("000000000000000a").resources.get(0x302).gpuTexture) === "0,255,0,255", label + " DirectDraw color fill");
        check(emulator.read_memory(0x80000, 1)[0] === 42, label + " guest RAM");
    };
    await verify("before save");
    // This tick used to expire the D3D8 canvas attachment mid-frame.
    await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
    const bridge = emulator.graphics_proxy.bridge;
    const execute = bridge.executePCIBatch.bind(bridge);
    let replayFrames = 0;
    bridge.executePCIBatch = async (event, bytes) => {
        await execute(event, bytes);
        if (event.replay) {
            await bridge.waitForIdle(false);
            await new Promise(requestAnimationFrame);
            const canvases = new Set([bridge.glCanvas, bridge.d3d8Canvas, bridge.d3d9Canvas,
                ...bridge.d3d9SwapChainCanvases.values()]);
            check([...canvases].every(canvas => !shown(canvas)),
                "historical GPU frame stays invisible across browser paint " + (++replayFrames));
        }
    };
    await emulator.restore_state(saved);
    check(replayFrames >= 4, "visibility checked while replaying all four APIs");
    check(bridge.activeOwner && shown(bridge.ownerCanvas(bridge.activeOwner)),
        "only the final restored graphics surface becomes visible");
    check(!journal.compressor.worker, "restore terminates the discarded journal worker");
    await verify("same instance restore");
    const savedAgain = await emulator.save_state();
    await emulator.destroy();
    emulator = await create(savedAgain);
    await verify("new instance restore");
    await emulator.destroy();
    check(!errors.length, "no WebGPU validation errors: " + errors.join("; "));
    check(mainCompressions === 0, "round trips keep compression off the emulation thread");
    const NativeWorker = globalThis.Worker;
    const badWorkerURL = URL.createObjectURL(new Blob(["throw new Error('startup test');"], { type: "text/javascript" }));
    try {
        for (const asynchronous of [false, true]) {
            globalThis.Worker = class {
                constructor() {
                    if (asynchronous) return new NativeWorker(badWorkerURL);
                    throw new Error("worker unavailable");
                }
            };
            const fallback = new V86GraphicsJournal({ budget: 1 });
            fallback.append({ bytes: new Uint8Array([1, 2, 3]), frameId: 123 });
            const checkpoint = await fallback.snapshot();
            const record = (await V86GraphicsJournal.records(V86GraphicsJournal.parse(checkpoint)).next()).value;
            check(record.frameId === 123 && record.bytes.join() === "1,2,3",
                (asynchronous ? "async" : "sync") + " worker startup failure preserves checkpoint data");
            await fallback.destroy();
        }
    } finally {
        globalThis.Worker = NativeWorker;
        globalThis.CompressionStream = NativeCompressionStream;
        URL.revokeObjectURL(badWorkerURL);
    }
    return { status: "PASS", checks };
})().catch(error => ({ status: "FAIL", error: error.stack })).then(async result => {
    document.getElementById("result").textContent = JSON.stringify(result);
    await fetch("/__test_result", { method: "POST", body: JSON.stringify(result) });
});
</script>
                                                        source/v64/tests/glbridge/graphics_checkpoint_test.js                                               0000644 0000000 0000000 00000022723 00000000000 020217  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
const assert = require("node:assert/strict");
const { GLStream, GL, GLFN } = require("./gl_stream_builder.js");
const { createFakeHost } = require("./gl_fake_gpu.js");
const { GLWebGPUExecutor } = require("../../src/browser/glbridge/gl-webgpu/gl_executor.js");
const d8 = require("./d3d8_webgpu_executor_test.js");
const d9 = require("./d3d9_webgpu_executor_test.js");
const dd = require("./ddraw_webgpu_executor_test.js");
require("../../src/browser/glbridge/v86_network_bridge.js");
const { V86WebGPUCompositor } = require("../../src/browser/glbridge/webgpu_compositor.js");

function envelope(opcode, payload) {
    const bytes = new Uint8Array(8 + payload.byteLength);
    const view = new DataView(bytes.buffer);
    view.setUint16(0, opcode, true);
    view.setUint16(2, 0xffff, true);
    view.setUint32(4, payload.byteLength, true);
    bytes.set(payload, 8);
    return bytes;
}
async function fixture() {
    const { host, log } = createFakeHost();
    const gl = new GLWebGPUExecutor(null, { host });
    await gl.initialize();
    const fake8 = d8.makeFakeWebGPU();
    const direct8 = new d8.D3D8WebGPUExecutor({ width: 64, height: 64,
        getContext: () => fake8.context }, { gpu: fake8.gpu });
    const direct9 = d9.makeExecutor();
    direct9.fake.device.queue.onSubmittedWorkDone = () => Promise.resolve();
    const bridge = global.installV86GLNetworkBridge(null, null, {
        compositor: new V86WebGPUCompositor({ width: 64, height: 64 }),
        managedState: true, glExecutor: gl,
        d3d8Executor: direct8, d3d9Executor: direct9.executor,
    });
    let writes = 0;
    const send = (bytes, flags = 0) => bridge.pushPCIBatch({ bytes, flags,
        descAddr: 0x100000, batchAddr: 0x100020, responseBase: 0xc00000 - 32,
        writeGuestMemory() { writes++; }, isMemoryValid: () => true });
    const save = async () => {
        await bridge.prepareSaveState();
        return bridge.serializeCheckpoint();
    };
    const restore = async bytes => {
        bridge.beginStateRestore();
        bridge.onPCIStateRestored(bytes);
        await bridge.finishStateRestore();
    };
    return { bridge, gl, log, direct8, direct9, send, save, restore, writes: () => writes };
}

const timeout = setTimeout(() => { throw new Error("checkpoint test timed out"); }, 15000);
(async () => {
    const a = await fixture();
    a.send(new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .names(GLFN.GEN_QUERIES, [7, 8])
        .names(GLFN.DELETE_QUERIES, [8])
        .call("CLEAR_COLOR", 0.25, 0.5, 0.75, 1).call("CLEAR", GL.COLOR_BUFFER_BIT)
        .call("BEGIN_QUERY", GL.SAMPLES_PASSED, 7).bytes());
    const device8 = 0x100002, buffer8 = 0x100003;
    const create8 = d8.u32Payload(device8, buffer8, 1, 16, 0, 0, 0, 0);
    const data8 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
    const batch8 = d8.batch([
        d8.command(1, d8.u32Payload(32, 0, 0xA0010001, 0x20260802)),
        d8.command(2, d8.createDevicePayload(device8, 64, 64)),
        d8.command(0x100, create8),
        d8.command(0x101, d8.u32Payload(buffer8, 0, 16, 0, 0, 0), data8),
        d8.command(5, d8.u32Payload(device8, 1, 0xff112233, 0x3f800000, 0, 0)),
    ], 1);
    batch8.writeUInt32LE(0, 12); // save while the frame is unfinished
    await a.send(envelope(0xffe0, batch8));
    const buffer9 = 0x201;
    const shader = d9.shaderCreatePayload(0x400, [0xffff0101, 1, 0x800f0000, 0x90e40000, 0xffff]);
    await a.send(envelope(0xffe1, d9.buildBatch([
        d9.command(d9.OP.CREATE_DEVICE, d9.createDevicePayload(64, 64)),
        d9.command(d9.OP.CREATE_BUFFER, d9.createBufferPayload(buffer9, 1, 96)),
        d9.command(d9.OP.UPDATE_BUFFER, d9.u32(buffer9, 0, 16, 0, 0, 0), data8, 12),
        d9.command(d9.OP.CREATE_PIXEL_SHADER, shader.payload, shader.blob, shader.blobOffsetField),
        d9.command(d9.OP.SET_RENDER_STATE, d9.u32(d9.DEVICE, 7, 0)),
        d9.command(d9.OP.CLEAR, d9.u32(d9.DEVICE, 1, 0xffaabbcc, 0x3f800000, 0)),
    ], { sessionLow: 1 })));
    const indices = Buffer.from([7, 9, 11, 13]);
    const texture = dd.updateTexturePayload(0x300, 2, 2, 2, indices);
    const palette = dd.palettePayload(3, i => (0xff000000 | i) >>> 0);
    await a.send(envelope(0xffe1, dd.buildBatch([
        dd.command(dd.OP.CREATE_DEVICE, dd.createDevicePayload(64, 64)),
        dd.command(dd.OP.CREATE_TEXTURE_2D,
            dd.createSurfacePayload(0x300, 2, 2, dd.FMT_P8, dd.USAGE_DDRAW_INDEXED)),
        dd.command(dd.OP.UPDATE_TEXTURE, texture.payload, texture.blob, texture.blobOffsetField),
        dd.command(dd.OP.SET_PALETTE, palette.payload, palette.blob, palette.blobOffsetField),
        dd.command(dd.OP.DD_SET_SURFACE_PALETTE, dd.u32(0x300, 3, 1, 0)),
        dd.command(dd.OP.DD_SET_COLOR_KEY, dd.u32(0x300, 0, 7, 9, 1, 0)),
        dd.command(dd.OP.DD_BLT, dd.bltPayload({ sourceHandle: 0x300,
            sourceRect: [0, 0, 2, 2], destinationRect: [0, 0, 2, 2] })),
    ], { sessionLow: 2 })));
    const snapshot = await a.save();
    assert.equal(a.direct8.frame, null, "save flushes unfinished D3D8 drawing");
    const queryState = a.gl.queries.get(7);
    assert.equal(queryState.ended, false);
    const expected9 = a.direct9.executor.sessionStates.get("0000000000000001");
    assert.ok(expected9.resources.has(0x400), "shader was created before save");
    const expectedDD = a.direct9.executor.resources.get(0x300);
    const ddPalette = JSON.stringify(expectedDD.ddPaletteIndex);
    async function checkRestored(b) {
        assert.equal(b.gl.queries.has(7), true);
        assert.equal(b.gl.queries.has(8), false);
        assert.equal(b.gl.activeQuery.name, 7, "unfinished GL query survives");
        assert.deepEqual(b.direct8.resources.get(buffer8).shadow.slice(0, 16), new Uint8Array(data8));
        const session = b.direct9.executor.sessionStates.get("0000000000000001");
        assert.deepEqual(session.resources.get(buffer9).shadow.slice(0, 16), new Uint8Array(data8));
        assert.ok(session.resources.has(0x400), "shader reconstructed");
        assert.equal(session.devices.get(d9.DEVICE).renderStates.get(7), 0);
        const surface = b.direct9.executor.resources.get(0x300);
        assert.equal(surface.ddIndexed, true);
        assert.deepEqual([...surface.textureShadows.values()][0].data.slice(0, 4), new Uint8Array(indices));
        assert.equal(JSON.stringify(surface.ddPaletteIndex), ddPalette);
        assert.ok(b.direct9.executor.palettes.size > 0);
        b.send(new GLStream().call("END_QUERY", GL.SAMPLES_PASSED).bytes());
        await b.save();
        assert.equal(b.gl.activeQuery, null);
        assert.equal(b.gl.queries.get(7).ready, true);
    }
    // Roll back all four frontends after additional commands destroyed state.
    a.send(new GLStream().names(GLFN.DELETE_QUERIES, [7]).bytes());
    await a.send(envelope(0xffe1, d9.buildBatch([
        d9.command(d9.OP.DESTROY_RESOURCE, d9.u32(buffer9)),
    ], { sessionLow: 1 })));
    const beforeWrites = a.writes();
    a.direct9.executor.failed = new Error("discarded timeline failed");
    await a.restore(snapshot);
    assert.equal(a.writes(), beforeWrites, "replay never writes historical DMA responses");
    await checkRestored(a);
    const b = await fixture();
    await b.restore(snapshot);
    assert.equal(b.writes(), 0, "cold restore never writes historical DMA responses");
    await checkRestored(b);
    // Saving a restored guest must retain its complete ancestry.
    const second = await b.save();
    const c = await fixture();
    await c.restore(second);
    assert.equal(c.gl.queries.get(7).ready, true);
    assert.ok(c.direct9.executor.resources.has(0x300));
    // Large legal GL batches used to overflow Array.push's argument stack.
    const large = new GLStream();
    for (let i = 0; i < 150000; i++) large.call("LOAD_IDENTITY");
    const commands = c.gl.stats.commands;
    c.send(large.bytes());
    assert.equal(c.gl.stats.commands - commands, 150000);
    const malformed = snapshot.slice();
    new DataView(malformed.buffer).setUint32(32, 0xffffffff, true);
    assert.throws(() => c.bridge.parseCheckpoint(malformed), /invalid/i);
    // A fence response must reach guest memory before save resolves. Executor
    // idle() intentionally waits only for decoding; checkpointIdle() includes
    // asynchronous query completion as well.
    const q = await fixture();
    let completeFence;
    const fence = new Promise(resolve => { completeFence = resolve; });
    q.direct9.fake.device.queue.onSubmittedWorkDone = () => fence;
    await q.send(envelope(0xffe1, d9.buildBatch([
        d9.command(d9.OP.CREATE_DEVICE, d9.createDevicePayload(64, 64)),
        d9.command(d9.OP.CREATE_QUERY, d9.u32(d9.DEVICE, 0x902, 8, 0)),
        d9.command(d9.OP.END_QUERY, d9.u32(d9.DEVICE, 0x902, 0, 41)),
    ], { versionMinor: 3 })));
    const writesBeforeFence = q.writes();
    let savedQuery = false;
    const querySave = q.save().then(value => { savedQuery = true; return value; });
    for (let i = 0; i < 10; ++i) await Promise.resolve();
    assert.equal(savedQuery, false);
    completeFence();
    const querySnapshot = await querySave;
    assert.ok(q.writes() > writesBeforeFence, "save includes completed query DMA responses");
    const queryWrites = q.writes();
    await q.restore(querySnapshot);
    assert.equal(q.writes(), queryWrites, "query replay cannot overwrite restored DMA responses");

    console.log("graphics_checkpoint_test: four APIs, hot/cold restore, query continuation, DMA isolation and large batches passed");
})().catch(error => { console.error(error); process.exitCode = 1; }).finally(() => clearTimeout(timeout));
                                             source/v64/tests/glbridge/graphics_journal_perf_test.html                                           0000644 0000000 0000000 00000004401 00000000000 021077  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>Graphics journal frame overhead</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
(async () => {
    const params = new URLSearchParams(location.search);
    if (params.has("baseline")) {
        await new Promise((resolve, reject) => {
            const script = document.createElement("script");
            script.src = "../../build/glbridge/graphics_journal_baseline.js";
            script.onload = resolve; script.onerror = reject; document.head.append(script);
        });
    }
    const journal = params.has("disabled") ? { append() {}, async snapshot() {}, async destroy() {} } :
        new V86GraphicsJournal({ budget: 1024 * 1024, worker: !params.has("local") });
    const record = { bytes: new Uint8Array(128), frameId: 0, commandCount: 1 };
    const times = [], intervals = [];
    let previous = 0;
    const started = performance.now();
    for (let frame = 0; frame < 180; frame++) {
        const now = await new Promise(requestAnimationFrame);
        if (previous) intervals.push(now - previous);
        previous = now;
        const start = performance.now();
        for (let n = 0; n < 4096; n++) {
            record.frameId++;
            record.bytes[0] = n & 255;
            journal.append(record);
        }
        times.push(performance.now() - start);
    }
    await journal.snapshot();
    const elapsed = performance.now() - started;
    await journal.destroy();
    const percentile = (values, p) => [...values].sort((a,b) => a-b)[Math.floor((values.length - 1) * p)];
    return { status: "PASS", mode: params.has("disabled") ? "disabled" : params.has("baseline") ? "baseline" : params.has("local") ? "local" : "worker", rawMiB: 180 * 4096 * 160 / 1048576,
        appendMs: { median: percentile(times, .5), p95: percentile(times, .95), max: Math.max(...times) },
        frameMs: { median: percentile(intervals, .5), p95: percentile(intervals, .95), max: Math.max(...intervals) }, elapsedMs: elapsed };
})().catch(error => ({ status: "FAIL", error: String(error.stack) })).then(result => {
    document.getElementById("result").textContent = JSON.stringify(result);
    fetch("/__test_result", { method: "POST", body: JSON.stringify(result) });
});
</script>
                                                                                                                                                                                                                                                               source/v64/tests/glbridge/graphics_journal_test.js                                                  0000644 0000000 0000000 00000010523 00000000000 017535  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
const assert = require("node:assert/strict");
const { GraphicsJournal } = require("../../src/browser/glbridge/graphics_journal.js");
const timeout = setTimeout(() => { throw new Error("journal test timed out"); }, 60000);
(async () => {
    const data = new Map();
    let writes = 0, reads = 0;
    const store = {
        async put(bytes) { const key = writes++; data.set(key, bytes.slice()); return key; },
        async get(key) { reads++; return data.get(key).slice(); },
        async destroy() { data.clear(); },
    };
    const journal = new GraphicsJournal({ budget: 16 * 1024, store });
    const payload = new Uint8Array(8 * 1024 * 1024);
    // Cross the old 512 MiB total-history boundary using distinct immutable
    // records, without requiring a half-gigabyte resident test fixture.
    for (let i = 0; i < 66; ++i) {
        payload[0] = i;
        journal.append({ bytes: payload, frameId: i, flags: i % 2, commandCount: 1 });
        payload[0] = 255;
        await journal.work;
    }
    assert.ok(journal.rawBytes > 512 * 1024 * 1024);
    assert.ok(writes > 0, "compressed pages spill after the RAM cache budget");
    assert.ok(journal.residentBytes <= journal.budget);
    const saved = await journal.snapshot();
    assert.ok(saved.length < 2 * 1024 * 1024, "repetitive command history is compressed");
    const parsed = GraphicsJournal.parse(saved);
    let count = 0;
    for await (const record of GraphicsJournal.records(parsed)) {
        assert.equal(record.frameId, count);
        assert.equal(record.flags, count % 2);
        assert.equal(record.bytes[0], count, "history owns bytes before guest reuses the arena");
        assert.equal(record.bytes.length, payload.length);
        assert.equal(record.bytes[record.bytes.length - 1], 0);
        count++;
    }
    assert.equal(count, 66, "every record after 512 MiB is retained and portable");
    assert.ok(reads > 0);
    const again = await journal.snapshot();
    assert.deepEqual(again, saved, "saving twice does not consume spooled pages");
    await journal.destroy();
    assert.equal(data.size, 0, "destroy deletes this session's cache pages");

    // Short/unaligned records and oversized batches must survive page rollover
    // without aliasing the guest's subsequently reused command arena.
    const packed = new GraphicsJournal({ pageBytes: 1024, store: null });
    const sizes = [0, 1, 127, 997, 4096];
    for (let i = 0; i < 100; ++i) {
        const bytes = new Uint8Array(sizes[i % sizes.length]).fill(i);
        packed.append({ frameId: i, flags: i % 2, responseBase: 8192 + i }, bytes);
        bytes.fill(255);
    }
    let packedCount = 0;
    for await (const record of GraphicsJournal.records(GraphicsJournal.parse(await packed.snapshot()))) {
        assert.equal(record.frameId, packedCount);
        assert.equal(record.flags, packedCount % 2);
        assert.equal(record.responseBase, 8192 + packedCount);
        assert.deepEqual(record.bytes, new Uint8Array(sizes[packedCount % sizes.length]).fill(packedCount));
        packedCount++;
    }
    assert.equal(packedCount, 100);
    await packed.destroy();

    const warning = console.warn;
    console.warn = () => {};
    try {
        const fallback = new GraphicsJournal({ budget: 1, pageBytes: 1024,
            store: { async put() { throw new Error("quota exhausted"); }, async destroy() {} } });
        fallback.append({ bytes: payload.subarray(0, 4096), frameId: 7 });
        await fallback.work;
        assert.ok(fallback.cacheError);
        const compressed = await fallback.snapshot();
        const restored = [];
        for await (const record of GraphicsJournal.records(GraphicsJournal.parse(compressed))) restored.push(record);
        assert.equal(restored[0].frameId, 7, "cache failure preserves history in RAM");
        await fallback.destroy();
    } finally { console.warn = warning; }

    const truncated = saved.subarray(0, saved.length - 1);
    assert.throws(() => GraphicsJournal.parse(truncated), /Invalid/);
    const corrupt = saved.slice();
    new DataView(corrupt.buffer).setUint32(36, 64 * 1024 * 1024, true);
    assert.throws(() => GraphicsJournal.parse(corrupt), /Invalid/);
    console.log("graphics_journal_test: 528 MiB round trip, compression, spill, quota fallback and cleanup passed");
})().catch(error => { console.error(error); process.exitCode = 1; }).finally(() => clearTimeout(timeout));
                                                                                                                                                                             source/v64/tests/glbridge/graphics_proxy_test.js                                                    0000644 0000000 0000000 00000027516 00000000000 017256  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
// The graphics proxy's host side (graphics_proxy.js): one screen canvas, owned
// by the WebGPU compositor, with each API's output a window layer placed in
// guest desktop pixels; WebGPU failing hands the screen back to the 2D canvas.
// As a device plugin it takes batches from its device over a channel, answers
// readbacks through it, and tells the device whether a renderer is there.
const assert = require("node:assert/strict");
require("../../src/browser/glbridge/v86_network_bridge.js");
require("../../src/browser/glbridge/webgpu_compositor.js");
require("../../src/browser/glbridge/v86gl_device.js");
const { V86GraphicsProxy, createGraphicsBridge } = require("../../src/browser/glbridge/graphics_proxy.js");

function fixture({ webgpu = true } = {}) {
    const screen = { width: 640, height: 480, toDataURL: () => "data:image/png;base64,",
        ownerDocument: { defaultView: { Image: class { } } } };
    let graphical = true, terminated = 0;
    const hosts = [], resets = [], backend = [], errors = [];
    const makeHost = () => {
        const host = { format: "bgra8unorm", destroyed: false, deviceLostHandlers: new Set(),
            context: { configure() {}, unconfigure() {} },
            device: { destroyed: 0, destroy() { this.destroyed++; },
                createShaderModule: () => ({}), createRenderPipeline: () => ({}), createSampler: () => ({}) },
            initialize: () => webgpu ? Promise.resolve() : Promise.reject(new Error("no WebGPU")),
            onDeviceLost(fn) { this.deviceLostHandlers.add(fn); } };
        hosts.push(host);
        return host;
    };
    let current = null;
    global.V86GPUHost = {
        acquire(canvas) { assert.equal(canvas, screen); return current || (current = makeHost()); },
        reset(canvas) { resets.push(canvas); current = null; },
    };
    const executor = () => ({ initialize() { return Promise.resolve(); }, work: Promise.resolve() });
    const emulator = {};
    const options = { screenCanvas: screen,
        screenBackend: { set: value => backend.push(["set", value]), fallback: () => backend.push(["fallback"]) },
        onError: error => errors.push(error),
        isGraphical: () => graphical, glExecutor: executor(), d3d8Executor: executor(), d3d9Executor: executor() };
    options.d3d9Executor.shaderWorker = { terminate() { terminated++; } };
    return { emulator, options, screen, hosts, resets, backend, errors,
        setGraphical(value) { graphical = value; }, terminated: () => terminated };
}

const placed = layer => [layer.x, layer.y, layer.width, layer.height, layer.visible];

(async () => {
    const f = fixture();
    assert.throws(() => createGraphicsBridge(f.emulator, { ...f.options, screenBackend: undefined }),
        /screen canvas/, "the adapter draws through the emulator's screen, nothing else");
    const bridge = createGraphicsBridge(f.emulator, f.options);
    const compositor = bridge.compositor;
    assert.equal(compositor.canvas, f.screen, "the compositor owns the screen canvas");
    assert.equal(compositor.host, f.hosts[0], "executors created before WebGPU is up already share its host");
    await bridge.ready;
    assert.ok(compositor.attached);
    assert.deepEqual(f.backend, [["set", compositor]], "the screen draws through the compositor once WebGPU is up");
    assert.deepEqual(compositor.layers.map(layer => layer.name), ["gl", "d3d8", "d3d9"]);
    const gl = bridge.glCanvas.layer, d3d9 = bridge.d3d9Canvas.layer;
    assert.ok(compositor.layers.every(layer => !layer.visible), "boot shows only the guest desktop");

    bridge.glSurface = { x: 50, y: 60, width: 200, height: 100 };
    bridge.showOwner("gl");
    assert.deepEqual(placed(gl), [50, 60, 200, 100, true], "placed in guest desktop pixels");
    assert.deepEqual(gl.clip, { left: 0, top: 0, right: 1, bottom: 1 });
    bridge.glSurface = { x: -20, y: -10, width: 200, height: 100 };
    bridge.placeLayers();
    assert.deepEqual(gl.clip, { left: 0.1, top: 0.1, right: 1, bottom: 1 }, "off-desktop pixels are clipped");
    bridge.glSurface = { x: 400, y: 300, width: 640, height: 480, ddDesktopPrimary: true,
        clipRect: { left: 32, top: 24, right: 608, bottom: 456, baseWidth: 640, baseHeight: 480 } };
    bridge.placeLayers();
    assert.deepEqual(placed(gl), [0, 0, 640, 480, true], "a DirectDraw primary stays aligned to the desktop");
    assert.deepEqual(gl.clip, { left: 0.05, top: 0.05, right: 0.95, bottom: 0.95 });

    bridge.showOwner("d3d9");
    assert.equal(gl.visible, false, "one API's window at a time");
    assert.equal(d3d9.visible, true);

    const extra = compositor.createLayer("d3d9 swap chain 7").canvas;
    bridge.d3d9SwapChainCanvases.set(7, extra);
    bridge.placeD3D9SwapChain({ swapChain: 7, x: 10, y: 20, width: 100, height: 80 });
    assert.deepEqual(placed(extra.layer), [10, 20, 100, 80, true]);
    bridge.hideLayers();
    assert.equal(extra.layer.visible, true, "hiding a primary window preserves independent swap-chain windows");

    f.setGraphical(false);
    bridge.screenChanged();
    assert.ok(compositor.layers.every(layer => !layer.visible), "text mode shows no window layers");
    f.setGraphical(true);
    bridge.screenChanged();
    assert.ok(compositor.layers.every(layer => !layer.visible), "return to graphics waits for a fresh Present");

    // A reset starts over on a fresh device; the compositor moves with it
    const first = f.hosts[0];
    await bridge.reset();
    assert.equal(first.device.destroyed, 1, "the old device is destroyed");
    assert.deepEqual(f.resets, [f.screen]);
    assert.equal(compositor.host, f.hosts[1]);
    assert.ok(compositor.attached);
    assert.equal(f.backend.length, 1, "the screen stays with the compositor");
    assert.equal(f.terminated(), 1, "the executors' workers are stopped");

    const promise = bridge.destroy();
    assert.equal(bridge.destroy(), promise, "destroy is idempotent");
    await promise;
    assert.ok(compositor.attached, "the compositor keeps drawing the screen");
    bridge.showOwner("gl");
    assert.equal(gl.visible, false, "late callbacks cannot resurrect a destroyed window");

    // Without WebGPU, the screen goes back to its 2D canvas
    const g = fixture({ webgpu: false });
    const failed = createGraphicsBridge(g.emulator, g.options);
    await failed.ready;
    assert.deepEqual(g.backend, [["fallback"]]);
    assert.equal(g.errors.length, 1);
    assert.ok(failed.failed);
    assert.equal(failed.makeScreenshot(), null, "no composed screenshot without WebGPU");
    await failed.destroy();

    // The plugin: its device on one end of a channel, the renderer on the other
    const p = fixture();
    const toDevice = [];
    let toHost = null;
    const channel = { remote: false, post: message => toDevice.push(message), listen: handler => { toHost = handler; } };
    const plugin = V86GraphicsProxy({ onError: p.options.onError, glExecutor: p.options.glExecutor,
        d3d8Executor: p.options.d3d8Executor, d3d9Executor: p.options.d3d9Executor });
    assert.equal(plugin.name, "v86gl");
    assert.ok(plugin.wants_screen);
    assert.equal(typeof plugin.create_device({ remote: false, post() {}, listen() {} }).notify, "function",
        "the device comes from v86gl_device.js");
    const started = plugin.start({ emulator: p.emulator, channel, screen: {
        canvas: p.screen, set_backend: value => p.backend.push(["set", value]),
        fallback: () => p.backend.push(["fallback"]), is_graphical: () => true } });
    assert.deepEqual(toDevice, [{ type: "available", value: true }], "batches are taken while WebGPU starts");
    await started;
    assert.equal(toDevice.length, 1, "and still once it is up");
    assert.equal(p.backend[0][0], "set");
    const pushed = [];
    plugin.bridge.pushPCIBatch = event => pushed.push(event);
    const bytes = new Uint8Array([1, 2, 3]);
    toHost({ type: "batch", id: 7, generation: 3, frameId: 9, flags: 1, commandCount: 1, descAddr: 0x1000,
        descLen: 35, batchAddr: 0x1020, responseBase: 0, submitCount: 1, bytes });
    assert.equal(pushed.length, 1);
    assert.equal(pushed[0].bytes, bytes, "on one thread the batch is not copied");
    assert.equal(pushed[0].frameId, 9);
    assert.deepEqual(toDevice.at(-1), { type: "done", id: 7 }, "on one thread done follows at once");
    pushed[0].writeGuestMemory(0x40, new Uint8Array([5]));
    assert.deepEqual(toDevice.at(-1), { type: "write", generation: 3, offset: 0x40, bytes: new Uint8Array([5]) },
        "a readback goes to the arena generation of its batch");
    assert.ok(pushed[0].isMemoryValid());
    plugin.bridge.beginStateRestore = () => {};
    plugin.bridge.waitForIdle = async () => {};
    await plugin.before_restore();
    const sent = toDevice.length;
    pushed[0].writeGuestMemory(0x40, new Uint8Array([6]));
    assert.equal(toDevice.length, sent, "readbacks from before a restore are dropped");
    assert.ok(!pushed[0].isMemoryValid());
    plugin.bridge.prepareSaveState = async () => {};
    plugin.bridge.serializeCheckpoint = () => bytes;
    assert.equal(await plugin.prepare_save(), bytes, "the checkpoint is the device's host state");
    await plugin.destroy();
    assert.deepEqual(toDevice.at(-1), { type: "available", value: false });

    // Across threads: one batch at a time, acknowledged when the renderer is done
    const r = fixture();
    const toRemote = [];
    let fromRemote = null;
    const remote = V86GraphicsProxy({ glExecutor: r.options.glExecutor, d3d8Executor: r.options.d3d8Executor,
        d3d9Executor: r.options.d3d9Executor });
    await remote.start({ emulator: r.emulator, channel: { remote: true, post: (m, transfer) => toRemote.push([m, transfer]),
        listen: handler => { fromRemote = handler; } }, screen: { canvas: r.screen, set_backend() {}, fallback() {}, is_graphical: () => true } });
    const order = [];
    let finish;
    remote.bridge.pushPCIBatch = event => { order.push("push " + event.frameId); remote.lastEvent = event; };
    remote.bridge.waitForSubmittedBatches = () => new Promise(resolve => { finish = resolve; });
    const batch = (id, frameId) => fromRemote({ type: "batch", id, generation: 1, frameId, flags: 0, commandCount: 1,
        descAddr: 0, descLen: 33, batchAddr: 32, responseBase: 0, submitCount: id, bytes: new Uint8Array([id]) });
    batch(1, 10);
    batch(2, 11);
    assert.deepEqual(remote.stats, { graphics_batches: 2, graphics_bytes: 2, graphics_pending: 2, graphics_peak_pending: 2 });
    await Promise.resolve(); await Promise.resolve();
    assert.deepEqual(order, ["push 10"], "the second batch waits for the first");
    const buffer = new Uint8Array([9, 9]);
    remote.lastEvent.writeGuestMemory(8, buffer);
    const [write, transfer] = toRemote.at(-1);
    assert.notEqual(write.bytes.buffer, buffer.buffer, "a readback crosses the thread as a copy");
    assert.deepEqual(transfer, [write.bytes.buffer]);
    finish();
    await new Promise(resolve => setTimeout(resolve, 0));
    assert.ok(toRemote.some(([m]) => m.type === "done" && m.id === 1));
    assert.deepEqual(order, ["push 10", "push 11"]);
    finish();
    await remote.idle();
    assert.ok(toRemote.some(([m]) => m.type === "done" && m.id === 2));
    assert.equal(remote.stats.graphics_pending, 0);
    await remote.destroy();

    // Without WebGPU the device hears that nothing renders
    const q = fixture({ webgpu: false });
    const toFailedDevice = [];
    const failedPlugin = V86GraphicsProxy({ onError: q.options.onError, glExecutor: q.options.glExecutor,
        d3d8Executor: q.options.d3d8Executor, d3d9Executor: q.options.d3d9Executor });
    await failedPlugin.start({ emulator: q.emulator, channel: { remote: false, post: m => toFailedDevice.push(m), listen() {} },
        screen: { canvas: q.screen, set_backend() {}, fallback() {}, is_graphical: () => true } });
    assert.deepEqual(toFailedDevice.map(m => m.value), [true, false]);
    await failedPlugin.destroy();

    console.log("graphics_proxy_test: ok");
})().catch(error => { console.error(error); process.exitCode = 1; });
                                                                                                                                                                                  source/v64/tests/glbridge/graphics_state_integration_test.js                                        0000644 0000000 0000000 00000012325 00000000000 021610  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
const assert = require("node:assert/strict");
(async () => {
    global.DEBUG = false;
    const { PCI } = await import("../../src/pci.js");
    const { V86 } = await import("../../src/browser/starter.js");
    // A device plugin's host state travels in the snapshot with its device
    // (docs/graphics-proxy-plugin-plan.md): V86 asks the plugin before saving
    // and hands the state back after restoring
    const checkpoint = new Uint8Array([1, 2, 3]);
    const calls = [];
    const device = { name: "v86gl", host_state: undefined, restored_host_state: undefined };
    const plugin = {
        name: "v86gl",
        async prepare_save() { calls.push("prepare"); return checkpoint; },
        release_save() { calls.push("release"); },
        async before_restore() { calls.push("begin"); },
        async after_restore(value) { calls.push(value); await Promise.resolve(); calls.push("finish"); },
        cancel_restore() { calls.push("cancel"); },
    };
    const lifecycle = {
        plugin_device: V86.prototype.plugin_device,
        save_with_plugins: V86.prototype.save_with_plugins,
        restore_with_plugins: V86.prototype.restore_with_plugins,
        with_device_state: V86.prototype.with_device_state,
        // (no display adapter or GLES host here: nothing of them on the GPU)
        adapter_host_state: V86.prototype.adapter_host_state,
        prepare_host_state: V86.prototype.prepare_host_state,
    };
    const emulator = { ...lifecycle, device_plugins: [plugin],
        is_running() { return false; }, async stop() {},
        v86: {
            cpu: { devices: { virtio_devices: [device] } },
            save_state() { calls.push("save"); return [device.host_state]; },
            restore_state(state) { calls.push("restore"); device.restored_host_state = state[0]; },
        } };
    const saved = await V86.prototype.save_state.call(emulator);
    assert.deepEqual(calls, ["prepare", "save", "release"]);
    assert.equal(saved[0], checkpoint);
    assert.equal(device.host_state, undefined, "the host state is only there while saving");
    calls.length = 0;
    await V86.prototype.restore_state.call(emulator, saved);
    assert.deepEqual(calls, ["begin", "restore", checkpoint, "finish"]);
    assert.equal(device.restored_host_state, undefined);
    calls.length = 0;
    await V86.prototype.restore_state.call(emulator, [undefined]);
    assert.deepEqual(calls, ["begin", "restore", undefined, "finish"], "snapshots without graphics data clear replay state");
    emulator.v86.restore_state = () => { throw new Error("bad state"); };
    calls.length = 0;
    await assert.rejects(V86.prototype.restore_state.call(emulator, saved), /bad state/);
    assert.deepEqual(calls, ["begin", "cancel"]);
    // The public API must stop the CPU before awaiting host work, serialize
    // concurrent requests, and resume only after the snapshot is consistent.
    const sequence = [];
    let release;
    const gate = new Promise(resolve => { release = resolve; });
    const live = {
        ...lifecycle,
        running: true, value: 0,
        is_running() { return this.running; },
        async stop() { this.running = false; sequence.push("stop"); },
        run() { this.running = true; sequence.push("run"); },
        device_plugins: [{
            name: "v86gl",
            async prepare_save() {
                sequence.push("prepare");
                assert.equal(live.running, false);
                await gate;
                live.value = 42; // an accepted GPU readback completes here
            },
            async before_restore() {}, async after_restore() {}, cancel_restore() {},
        }],
        v86: {
            cpu: { devices: { virtio_devices: [{ name: "v86gl" }] } },
            save_state() { sequence.push("save"); return live.value; },
            restore_state() { throw new Error("invalid checkpoint"); },
        },
    };
    const first = V86.prototype.save_state.call(live);
    const second = V86.prototype.save_state.call(live);
    for (let i = 0; i < 5; ++i) await Promise.resolve();
    assert.deepEqual(sequence, ["stop", "prepare"]);
    release();
    assert.deepEqual(await Promise.all([first, second]), [42, 42]);
    assert.deepEqual(sequence, ["stop", "prepare", "save", "run", "stop", "prepare", "save", "run"]);
    await assert.rejects(V86.prototype.restore_state.call(live, new ArrayBuffer(0)), /invalid checkpoint/);
    assert.equal(live.running, false, "a failed restore cannot resume a partially restored guest");

    const bus = Object.create(PCI.prototype);
    const config = new Int32Array(64);
    config[4] = 1;
    const fixed = { fixed: true, original_bar: 0xf101 };
    bus.devices = [{ name: "sparse BARs", pci_bars: [undefined, fixed] }];
    bus.device_spaces = [new Int32Array(64)];
    const pciState = [];
    pciState[0] = config;
    for (const [i, key] of ["pci_addr", "pci_value", "pci_response", "pci_status"].entries()) {
        bus[key] = new Uint8Array(4);
        pciState[256 + i] = new Uint8Array(4);
    }
    bus.set_state(pciState);
    assert.equal(bus.device_spaces[0][5], 0xf101, "restore skips absent BARs and preserves the fixed graphics port");
    console.log("graphics_state_integration_test: ok");
})().catch(error => { console.error(error); process.exitCode = 1; });
                                                                                                                                                                                                                                                                                                           source/v64/tests/glbridge/graphics_vga_browser_test.html                                            0000644 0000000 0000000 00000023637 00000000000 020745  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VGA + WebGPU integration</title>
<style>
    #screen { width: 800px; height: 600px; border: 5px solid black; padding: 12px;
        display: flex; align-items: center; justify-content: center; transform: scale(.75); transform-origin: top left; }
</style>
<div id="screen"><div></div><canvas id="vga"></canvas></div>
<pre id="result">RUNNING</pre>
<script src="../../build/libv86.js"></script>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script src="gl_stream_builder.js"></script>
<script>
// The graphics adapter end to end: the guest's VGA desktop and a GL window
// in the one screen canvas (docs/display-design.md), frames
// through the v86gl virtqueue, save/restore, restart and old snapshots.
(async () => {
    const checks = [];
    const check = (value, label) => {
        if (!value) throw new Error(label);
        checks.push(label);
        document.getElementById("result").textContent = "RUNNING\n" + checks.join("\n");
    };
    const container = document.getElementById("screen");
    const vga = document.getElementById("vga");
    const { GLStream, GL } = GLTestStream;
    const create = (initial_state, graphics = true) => new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: "../../build/v86.wasm", memory_size: 32 * 1024 * 1024,
        bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
        screen_container: container, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" },
        graphics_proxy: graphics,
        initial_state, autostart: false,
    });
    const loaded = emulator => new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    let emulator = create();
    await loaded(emulator);
    const bridge = emulator.graphics_proxy.bridge;
    const compositor = bridge.compositor;
    const layers = () => compositor.layers;
    check(!bridge.failed, "graphics initialization succeeded");
    check(compositor.canvas === vga && container.querySelectorAll("canvas").length === 1,
        "the compositor owns the one screen canvas");
    check(bridge.glExecutor.device === compositor.device && bridge.d3d9Executor.device === compositor.device &&
        bridge.d3d8Executor.device === compositor.device, "all executors share the compositor's GPUDevice");
    check(layers().every(layer => !layer.visible), "text-mode boot shows no window layer");
    const gpu = bridge.glExecutor.device;
    const errors = [];
    gpu.addEventListener("uncapturederror", event => errors.push(event.error.message));
    gpu.pushErrorScope("validation");
    const screen = emulator.screen_adapter;
    const cpu = emulator.v86.cpu, io = cpu.io;
    // The guest desktop: 640x480x32 through the Bochs VBE LFB, all blue
    const dispi = (index, value) => { io.port_write16(0x1ce, index); io.port_write16(0x1cf, value); };
    dispi(4, 0); dispi(1, 640); dispi(2, 480); dispi(3, 32); dispi(4, 0x41);
    const vga_device = cpu.devices.vga;
    new Uint32Array(vga_device.svga_memory.buffer, vga_device.svga_memory.byteOffset, 640 * 480).fill(0x000000ff);
    cpu.mmio_ram_mark_dirty(vga_device.lfb_region);
    cpu.devices.display.request_frame(true);
    check(vga.width === 640 && vga.height === 480, "the canvas is the guest's mode");
    // Exercise the same modern virtio queue ABI as v86gl.sys before rendering.
    const ram = cpu.read_blob(0, 32 * 1024 * 1024);
    const memory = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
    const table = 0x10000, avail = table + 128, used = table + 160;
    const request = table + 256, reply = table + 288, arena = 0x100000;
    const w8 = (off, value) => io.port_write8(0xf100 + off, value);
    const w16 = (off, value) => io.port_write16(0xf100 + off, value);
    const w32 = (off, value) => io.port_write32(0xf100 + off, value);
    w8(20, 0); w8(20, 3);
    w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1); w8(20, 11);
    check(io.port_read8(0xf114) === 11, "virtio features negotiated");
    w16(22, 0); w16(24, 8);
    w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0);
    w32(48, used); w32(52, 0);
    memory.setUint32(table, request, true); memory.setUint32(table + 8, 24, true);
    memory.setUint16(table + 12, 1, true); memory.setUint16(table + 14, 1, true);
    memory.setUint32(table + 16, reply, true); memory.setUint32(table + 24, 16, true);
    memory.setUint16(table + 28, 2, true); memory.setUint16(avail, 1, true);
    w16(28, 1); w8(20, 15);
    let idx = 0;
    const submit = (opcode, address, length, flags) => {
        [opcode, address, 0, length, flags, 0].forEach((v, i) => memory.setUint32(request + i * 4, v, true));
        memory.setUint32(reply, 0xffffffff, true);
        memory.setUint16(avail + 4 + (idx & 7) * 2, 0, true);
        memory.setUint16(avail + 2, ++idx, true);
        io.port_write16(0xf200, 0);
        if(memory.getUint16(used + 2, true) !== idx || memory.getUint32(reply, true) !== 0)
            throw new Error("virtio request failed: " + memory.getUint32(reply, true));
    };
    submit(1, arena, 16 * 1024 * 1024, 0);
    const draw = () => {
        const commands = new GLStream().makeCurrent(1, 100, 80, 200, 120)
            .call("CLEAR_COLOR", 1, 0, 0, 1).call("CLEAR", GL.COLOR_BUFFER_BIT).bytes();
        [0x324c4756, 1, 1, 1, 3, commands.length, 0, 0].forEach((v, i) => memory.setUint32(arena + i * 4, v, true));
        ram.set(commands, arena + 32);
        submit(2, 0, 32 + commands.length, 1);
    };
    draw();
    check(cpu.devices.virtio_devices.find(device => device.name === "v86gl").descriptor.get_state()[5] === 1, "virtqueue submitted a real WebGPU frame");
    const gl = bridge.glCanvas.layer;
    const placed = () => [gl.x, gl.y, gl.width, gl.height, gl.visible].join();
    check(placed() === "100,80,200,120,true", "the GL window is a layer where the guest put it: " + placed());
    await bridge.glExecutor.work;
    const screenshot = emulator.screen_make_screenshot();
    if (!screenshot.complete) await new Promise((resolve, reject) => { screenshot.onload = resolve; screenshot.onerror = reject; });
    const capture = document.createElement("canvas");
    capture.width = 640; capture.height = 480;
    const captureContext = capture.getContext("2d");
    captureContext.drawImage(screenshot, 0, 0);
    const pixel = (x, y) => Array.from(captureContext.getImageData(x, y, 1, 1).data);
    check(pixel(20, 20).join() === "0,0,255,255", "screenshot retains VGA outside the game window");
    check(pixel(150, 100).join() === "255,0,0,255", "screenshot composites WebGPU over VGA");
    emulator.screen_set_scale(2, 2);
    check(placed() === "100,80,200,120,true", "scaling the canvas cannot misalign a layer: it is in guest pixels");
    check(!!bridge.d3d9Executor.shaderWorker, "bundled D3D9 worker starts");
    const tokens = new Uint32Array([0xfffe0101, 1, 0xc00f0000, 0x90e40000, 0xffff]);
    const translated = await bridge.d3d9Executor.compileShaderInWorker(tokens);
    const local = D3D9ShaderPipeline.compileShader(tokens);
    check(translated.ok && JSON.stringify(translated) === JSON.stringify(local), "worker and main-thread shader translations agree");
    check(D3D9ShaderPipeline.TRANSLATOR_REVISION === V86GL_BUILD_REVISION, "shader cache uses the bundle revision");
    const state = await emulator.save_state();
    const journalBytes = bridge.glJournalBytes;
    await emulator.restore_state(state);
    check(bridge.glJournalBytes === journalBytes && !bridge.restoringState, "restore awaits the graphics checkpoint");
    screen.set_mode(false);
    check(layers().every(layer => !layer.visible), "text-mode transition hides stale game pixels");
    screen.set_mode(true);
    check(layers().every(layer => !layer.visible), "the desktop resumes before the next game Present");
    draw();
    check(gl.visible, "the next Present shows the window again");
    bridge.hideLayers();
    check(layers().every(layer => !layer.visible), "game exit exposes the desktop");
    const validation = await gpu.popErrorScope();
    check(!validation && !errors.length, "no WebGPU validation errors: " + (validation && validation.message || errors.join(";")));
    await emulator.destroy();
    check(container.querySelectorAll("canvas").length === 1 && bridge.destroyed, "destroy preserves the caller-owned canvas and stops graphics");
    emulator = create({ buffer: state });
    await loaded(emulator);
    check(emulator.graphics_proxy.bridge.glJournalBytes === journalBytes && !emulator.graphics_proxy.bridge.restoringState,
        "initial_state restores graphics before emulator-loaded");
    await emulator.restart();
    check(emulator.graphics_proxy.bridge.glJournalBytes === 0 && emulator.graphics_proxy.bridge.activeOwner === null,
        "restart clears graphics resources and returns to VGA");
    await emulator.destroy();
    emulator = create(undefined, false);
    await loaded(emulator);
    check(!emulator.graphics_proxy && !emulator.v86.cpu.devices.virtio_devices,
        "VGA-only instances do not create graphics hardware or a GPU adapter");
    check(container.querySelectorAll("canvas").length === 1 && container.querySelector("canvas").getContext("2d"),
        "the next emulator in the container draws in 2D although WebGPU had its canvas");
    const vgaOnlyState = await emulator.save_state();
    await emulator.restore_state(vgaOnlyState);
    await emulator.destroy();
    emulator = create({ buffer: vgaOnlyState });
    await loaded(emulator);
    check(emulator.graphics_proxy.bridge.glJournalBytes === 0 && !emulator.graphics_proxy.bridge.restoringState,
        "old snapshots without the graphics PCI device load with an empty graphics checkpoint");
    await emulator.destroy();
    return { status: "PASS", checks };
})().catch(error => ({ status: "FAIL", error: error.stack })).then(async result => {
    document.getElementById("result").textContent = JSON.stringify(result);
    if (new URLSearchParams(location.search).has("report"))
        await fetch("/__test_result", { method: "POST", body: JSON.stringify(result) });
});
</script>
                                                                                                 source/v64/tests/glbridge/package.json                                                              0000644 0000000 0000000 00000000043 00000000000 015070  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {"type":"commonjs","private":true}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/glbridge/run.cjs                                                                   0000644 0000000 0000000 00000001566 00000000000 014122  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
"use strict";
const { readdirSync } = require("node:fs");
const { join } = require("node:path");
const { spawnSync } = require("node:child_process");
let failures = 0;
for (const file of readdirSync(__dirname).sort()) {
    if (!file.endsWith("_test.js") || file.includes("_perf_") || file.includes("_corpus_")) continue;
    const result = spawnSync(process.execPath, [join(__dirname, file)], { encoding: "utf8", timeout: 120000 });
    const ok = result.status === 0;
    const skipped = ok && /^SKIP:/m.test(result.stdout || "");
    console.log(`${skipped ? "SKIP" : ok ? "PASS" : "FAIL"} ${file}`);
    if (ok && /naga absent/.test(result.stdout || "")) console.log("  WGSL compiler unavailable; structural assertions passed");
    if (!ok) { failures++; console.error(result.stdout, result.stderr, result.error || ""); }
}
process.exitCode = failures ? 1 : 0;
                                                                                                                                          source/v64/tests/glbridge/speaker_restore_test.js                                                   0000644 0000000 0000000 00000014305 00000000000 017402  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
const assert = require("node:assert/strict");
const vm = require("node:vm");

(async () => {
    global.DEBUG = false;
    const { SpeakerAdapter } = await import("../../src/browser/speaker.js");
    const { SB16 } = await import("../../src/audio_devices/sb16/sb16.js");
    const { Bus } = await import("../../src/bus.js");
    let Processor;
    const node = () => ({ gain: { setValueAtTime() {} }, frequency: { setValueAtTime() {} },
        connect() {}, disconnect() {}, start() {} });
    class Context {
        constructor() {
            this.currentTime = 0;
            this.audioWorklet = { addModule: async url => {
                const source = await (await fetch(url)).text();
                vm.runInNewContext(source, { DEBUG: false, sampleRate: 48000,
                    AudioWorkletProcessor: class { constructor() { this.port = { postMessage() {} }; } },
                    registerProcessor(name, value) { Processor = value; } });
            } };
        }
        createGain() { return node(); }
        createBiquadFilter() { return node(); }
        createChannelMerger() { return node(); }
        createChannelSplitter() { return node(); }
        createOscillator() { return node(); }
        createBuffer(channels, length, rate) {
            this.lastRate = rate;
            const data = Array.from({ length: channels }, () => new Float32Array(length));
            return { copyToChannel(values, channel) { data[channel].set(values); } };
        }
        createBufferSource() {
            let ended;
            return { ...node(), addEventListener(name, callback) { ended = callback; },
                stop() { ended(); } };
        }
        suspend() { return Promise.resolve(); }
        resume() { return Promise.resolve(); }
        close() {}
    }
    global.window = { AudioContext: Context, AudioWorklet: true };
    global.AudioContext = Context;
    global.AudioWorkletNode = class {
        constructor() {
            this.processor = new Processor();
            this.port = { postMessage: data => this.processor.port.onmessage({ data }), close() {} };
        }
        connect() {}
    };
    const [host, guest] = Bus.create();
    const speaker = new SpeakerAdapter(host);
    for (let n = 0; !speaker.dac.node_processor && n < 100; n++) await new Promise(resolve => setTimeout(resolve, 1));
    assert.ok(speaker.dac.node_processor);
    let requests = 0;
    guest.register("dac-request-data", () => requests++);
    const processor = speaker.dac.node_processor.processor;
    const sb = Object.create(SB16.prototype);
    // (its machine's speaker messages: the bus, as src/cpu.js's handle has them)
    sb.machine = { bus_send: (name, data, transfer) => guest.send(name, data, transfer) };
    let cleared = 0;
    sb.dac_buffers = [{ clear() { cleared++; } }, { clear() { cleared++; } }];
    const state = new Array(36).fill(0);
    state[6] = new Uint8Array(0);
    state[24] = new Uint8Array(32);
    state[27] = 44100;
    state[35] = new Uint8Array(16);

    guest.send("dac-tell-sampling-rate", 22050);
    guest.send("emulator-started");
    guest.send("dac-enable");
    const old = new Float32Array(4096).fill(.5);
    guest.send("dac-send-data", [old, old.slice()]);
    const previousGeneration = speaker.dac.generation;
    guest.send("emulator-stopped");
    const pausedRequests = requests;
    speaker.dac.node_processor.port.onmessage({ data: { type: "pump", generation: previousGeneration } });
    assert.equal(requests, pausedRequests, "paused audio cannot advance DMA during graphics replay");
    sb.set_state(state);
    assert.equal(cleared, 2, "discard CPU-side samples from the abandoned timeline");
    assert.equal(speaker.dac.sampling_rate, 44100);
    assert.equal(processor.source_samples_per_destination, 44100 / 48000);
    assert.equal(processor.queue_length, 0);
    assert.equal(processor.source_time, 0);
    const out = [new Float32Array(128), new Float32Array(128)];
    processor.process([], [out], {});
    assert.ok(out[0].every(value => value === 0), "restored audio contains no old queued tone");
    guest.send("emulator-started");
    const resumedRequests = requests;
    speaker.dac.node_processor.port.onmessage({ data: { type: "pump", generation: previousGeneration } });
    assert.equal(requests, resumedRequests, "late pump requests from the old timeline are ignored");

    // Render a 1 kHz source sampled at the saved rate. A stale 22050 Hz host
    // setting would play this one octave lower, at 500 Hz.
    const tone = new Float32Array(44100);
    for (let i = 0; i < tone.length; i++) tone[i] = Math.sin(2 * Math.PI * 1000 * i / 44100);
    guest.send("dac-send-data", [tone, tone.slice()]);
    const rendered = [];
    for (let block = 0; block < 180; block++) {
        processor.process([], [out], {});
        if (block >= 10) rendered.push(...out[0]);
    }
    let crossings = 0;
    for (let i = 1; i < rendered.length; i++) if (rendered[i - 1] <= 0 && rendered[i] > 0) crossings++;
    const hz = crossings * 48000 / rendered.length;
    assert.ok(Math.abs(hz - 1000) < 5, "restored tone stays at 1 kHz: " + hz);
    speaker.destroy();

    global.window.AudioWorklet = false;
    const [fallbackHost, fallbackGuest] = Bus.create();
    const fallback = new SpeakerAdapter(fallbackHost);
    let fallbackRequests = 0;
    fallbackGuest.register("dac-request-data", () => fallbackRequests++);
    fallbackGuest.send("emulator-started");
    fallbackGuest.send("dac-enable");
    fallbackGuest.send("dac-tell-sampling-rate", 44100);
    fallbackGuest.send("dac-send-data", [tone, tone.slice()]);
    assert.equal(fallback.audio_context.lastRate, 44100);
    assert.equal(fallback.dac.sources.size, 1);
    const beforeReset = fallbackRequests;
    fallbackGuest.send("dac-reset");
    assert.equal(fallback.dac.sources.size, 0, "legacy output stops queued AudioBufferSources");
    assert.equal(fallback.dac.buffered_time, 0);
    await new Promise(resolve => setTimeout(resolve, 5));
    assert.equal(fallbackRequests, beforeReset, "legacy output ignores stale ended/timer callbacks");
    fallback.destroy();
    console.log("speaker_restore_test: sampling rate, queue reset, paused DMA, stale pump and 1 kHz pitch passed");
})().catch(error => { console.error(error); process.exitCode = 1; });
                                                                                                                                                                                                                                                                                                                           source/v64/tests/glbridge/speaker_unlock_browser_test.mjs                                           0000644 0000000 0000000 00000012002 00000000000 021122  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The speaker under the browser's autoplay policy (docs/arm64-virt-android16-plan.md
// P12.5; src/browser/speaker.js): headless Chrome with the policy that wants
// a user gesture, a page that starts v86 without one, then a trusted click
// through the DevTools protocol. The AudioContext must be suspended before
// the click and running after it (SpeakerAdapter's unlock).
// GL_CHROME can select a Chromium executable on non-macOS hosts.
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const page = `<!doctype html><meta charset="utf-8"><title>speaker unlock</title><pre id="state">loading</pre>
<script type="module">
import { V86 } from "/build/libv86.mjs";
window.vm = new V86({ graphics_adapter: "none", wasm_path: "/build/v86.wasm", bios: { url: "/build/cpu-worker-test.bin" },
    memory_size: 32 << 20, disable_keyboard: true, disable_mouse: true, net_device: { type: "none" }, autostart: true });
window.vm.add_listener("emulator-started", () => { window.started = true; });
</script>`;
const server = http.createServer((req, res) => {
    const pathname = new URL(req.url, "http://localhost").pathname;
    if(pathname === "/unlock.html") { res.setHeader("Content-Type", "text/html"); res.end(page); return; }
    const file = path.resolve(root, "." + pathname);
    if(!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; }
    fs.readFile(file, (error, data) => {
        if(error) { res.writeHead(404).end(); return; }
        res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" : /\.(js|mjs)$/.test(file) ? "text/javascript" : "application/octet-stream");
        res.end(data);
    });
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const profile = fs.mkdtempSync(path.join(os.tmpdir(), "speaker-unlock-"));
const browser = spawn(process.env.GL_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
    "--headless=new", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
    "--autoplay-policy=document-user-activation-required", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "about:blank",
], { stdio: ["ignore", "ignore", "pipe"] });
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const deadline = setTimeout(() => { console.error("FAIL: timed out"); browser.kill(); process.exit(1); }, 60000);
try
{
    // (the DevTools endpoint, from Chrome's stderr)
    let stderr = "";
    const endpoint = await new Promise((resolve, reject) => {
        browser.stderr.on("data", data => {
            stderr += data;
            const m = /DevTools listening on (ws:\/\/\S+)/.exec(stderr);
            if(m) resolve(m[1]);
        });
        browser.on("exit", code => reject(new Error("Chrome exited " + code + "\n" + stderr)));
    });
    const port = new URL(endpoint).port;
    const target = await (await fetch(`http://127.0.0.1:${port}/json/new?http://127.0.0.1:${server.address().port}/unlock.html`, { method: "PUT" })).json();
    const socket = new WebSocket(target.webSocketDebuggerUrl);
    await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; });
    let next = 1;
    const pending = new Map();
    socket.onmessage = event => {
        const m = JSON.parse(event.data);
        if(pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); }
    };
    const call = (method, params = {}) => new Promise(resolve => {
        const id = next++;
        pending.set(id, resolve);
        socket.send(JSON.stringify({ id, method, params }));
    });
    const evaluate = async expression => (await call("Runtime.evaluate", { expression, returnByValue: true })).result.result.value;
    while(!await evaluate("!!window.started")) await sleep(100);
    await sleep(500);
    const before = await evaluate("window.vm.speaker_adapter.audio_context.state");
    assert.equal(before, "suspended", "the context before a gesture");
    for(const type of ["mousePressed", "mouseReleased"])
    {
        await call("Input.dispatchMouseEvent", { type, x: 10, y: 10, button: "left", clickCount: 1 });
    }
    let after = before;
    for(let i = 0; i < 50 && after !== "running"; i++)
    {
        await sleep(100);
        after = await evaluate("window.vm.speaker_adapter.audio_context.state");
    }
    assert.equal(after, "running", "the context after a click");
    const listener = await evaluate("window.vm.speaker_adapter.unlock === null");
    assert.ok(listener, "the unlock listener removed once the context runs");
    console.log(`PASS speaker unlock: ${before} before a gesture, ${after} after a click`);
    socket.close();
}
catch(e)
{
    console.error("FAIL " + (e && e.stack || e));
    process.exitCode = 1;
}
finally
{
    clearTimeout(deadline);
    browser.kill();
    server.close();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/glbridge/svga_compute_browser_test.html                                            0000644 0000000 0000000 00000026423 00000000000 021000  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: compute shaders and UAVs</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A compute shader (SM5) of 8x8 threads, dispatched once: each thread writes
// its position into a typed UAV (an RGBA8 texture), appends its index to an
// append buffer, and counts itself into a raw buffer with an atomic add.
// Then the append buffer's counter is copied into a buffer, and a UAV clear
// sets the raw buffer to 7.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const OPERAND = { TEMP: 0, IMMEDIATE32: 4, UAV: 30, INPUT_THREAD_ID: 32 };
const token = (type, indices, sel) => [(sel | type << 12 | indices.length << 20) >>> 0, ...indices];
const mask = m => 2 | m << 4, swz = (x, y, z, w) => 2 | 1 << 2 | (x | y << 2 | z << 4 | w << 6) << 4, one = c => 2 | 2 << 2 | c << 4;
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const imm = (...values) => [(values.length === 4 ? 2 : 1) | OPERAND.IMMEDIATE32 << 12, ...values];
const r = (i, sel) => token(OPERAND.TEMP, [i], sel);
const u = (i, sel) => token(OPERAND.UAV, [i], sel);
const tid = sel => token(OPERAND.INPUT_THREAD_ID, [], sel);
const OP = { DCL_THREAD_GROUP: 155, DCL_UAV_TYPED: 156, DCL_UAV_RAW: 157, DCL_UAV_STRUCTURED: 158, DCL_INPUT: 95, DCL_TEMPS: 104,
    UTOF: 86, MUL: 56, MOV: 54, IMAD: 35, STORE_UAV_TYPED: 164, IMM_ATOMIC_ALLOC: 178, STORE_STRUCTURED: 168, ATOMIC_IADD: 173, RET: 62 };
const CS = (() => {
    const body = [
        ins(OP.DCL_THREAD_GROUP, 8, 8, 1),
        insc(OP.DCL_UAV_TYPED, 3 /* TEXTURE2D */, u(0, 0), 0x5555 /* float */),
        ins(OP.DCL_UAV_STRUCTURED, u(1, 0), 4),
        ins(OP.DCL_UAV_RAW, u(2, 0)),
        ins(OP.DCL_INPUT, tid(mask(3))),
        ins(OP.DCL_TEMPS, 2),
        ins(OP.UTOF, r(0, mask(3)), tid(swz(0, 1, 0, 0))),
        ins(OP.MUL, r(0, mask(3)), r(0, swz(0, 1, 0, 0)), imm(f32(0.125), f32(0.125), 0, 0)),
        ins(OP.MOV, r(0, mask(12)), imm(0, 0, 0, f32(1))),
        ins(OP.STORE_UAV_TYPED, u(0, mask(15)), tid(swz(0, 1, 1, 1)), r(0, swz(0, 1, 2, 3))),
        ins(OP.IMAD, r(1, mask(1)), tid(one(1)), imm(8), tid(one(0))),
        ins(OP.IMM_ATOMIC_ALLOC, r(1, mask(2)), u(1, 0)),
        ins(OP.STORE_STRUCTURED, u(1, mask(1)), r(1, one(1)), imm(0), r(1, one(0))),
        ins(OP.ATOMIC_IADD, u(2, mask(1)), imm(0), imm(1)),
        ins(OP.RET),
    ].flat();
    return new Uint32Array([5 << 16 | 5 << 4, 2 + body.length, ...body]);
})();

// a vertex shader passing the position on; a pixel shader counting its pixels into u0 (no targets)
const VS = (() => {
    const body = [
        ins(95 /* DCL_INPUT */, token(1, [0], mask(3))),
        ins(103 /* DCL_OUTPUT_SIV */, token(2, [0], mask(15)), 1),
        ins(OP.MOV, token(2, [0], mask(3)), token(1, [0], swz(0, 1, 0, 0))),
        ins(OP.MOV, token(2, [0], mask(12)), imm(0, 0, 0, f32(1))),
        ins(OP.RET),
    ].flat();
    return new Uint32Array([1 << 16 | 5 << 4, 2 + body.length, ...body]);
})();
const PS = (() => {
    const body = [
        ins(OP.DCL_UAV_RAW, u(0, 0)),
        ins(OP.ATOMIC_IADD, u(0, mask(1)), imm(0), imm(1)),
        ins(OP.RET),
    ].flat();
    return new Uint32Array([0 << 16 | 5 << 4, 2 + body.length, ...body]);
})();

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx11",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        const TEX = 10, APPEND = 11, RAW = 12, COUNT = 13;
        const U8 = C.SVGA3D_R8G8B8A8_UNORM;
        mobs.set(1, new Uint8Array(8 * 8 * 4));
        mobs.set(2, new Uint8Array(64 * 4));
        mobs.set(3, new Uint8Array(16));
        mobs.set(4, new Uint8Array(16));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(CS.buffer), 0);
        shaders.set(new Uint8Array(VS.buffer), 1024);
        shaders.set(new Uint8Array(PS.buffer), 2048);
        mobs.set(5, shaders);
        // DEFINE_GB_SURFACE_V3: sid, flags (low, high), format, mips, samples, pattern, quality, filter, width, height, depth, array size
        const UAV_HIGH = 2;     // SVGA3D_SURFACE_BIND_UAVIEW >> 32
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, TEX, C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE, UAV_HIGH, U8, 1, 0, 0, 0, 0, 8, 8, 1, 1);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, APPEND, 0, UAV_HIGH, C.SVGA3D_BUFFER, 1, 0, 0, 0, 0, 64 * 4, 1, 1, 1);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, RAW, 0, UAV_HIGH, C.SVGA3D_BUFFER, 1, 0, 0, 0, 0, 16, 1, 1, 1);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, COUNT, 0, 0, C.SVGA3D_BUFFER, 1, 0, 0, 0, 0, 16, 1, 1, 1);
        for(const [sid, mob] of [[TEX, 1], [APPEND, 2], [RAW, 3], [COUNT, 4]]) run(C.SVGA_3D_CMD_BIND_GB_SURFACE, sid, mob);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        // DEFINE_UA_VIEW: id, sid, format, dimension, desc (buffer: first element, elements, flags)
        run(C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW, 0, TEX, U8, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW, 1, APPEND, C.SVGA3D_FORMAT_INVALID, C.SVGA3D_RESOURCE_BUFFER, 0, 64, C.SVGA3D_UABUFFER_APPEND, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_UA_VIEW, 2, RAW, C.SVGA3D_R32_TYPELESS, C.SVGA3D_RESOURCE_BUFFER, 0, 4, C.SVGA3D_UABUFFER_RAW, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_CS, CS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 5, 0);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_CS);
        run(C.SVGA_3D_CMD_DX_SET_CS_UA_VIEWS, 0, 0, 1, 2);
        run(C.SVGA_3D_CMD_DX_SET_STRUCTURE_COUNT, 1, 0);
        run(C.SVGA_3D_CMD_DX_DISPATCH, 1, 1, 1);
        run(C.SVGA_3D_CMD_DX_COPY_STRUCTURE_COUNT, 1, COUNT, 4);
        for(const sid of [TEX, APPEND, RAW, COUNT]) run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, sid, 0);
        await finished();
        const gx = renderer.gx;
        check(gx && gx.stats.dispatches === 1, "one dispatch (" + JSON.stringify(gx && gx.stats) + ")");
        const tex = mobs.get(1);
        const texel = (x, y) => Array.from(tex.subarray((y * 8 + x) * 4, (y * 8 + x) * 4 + 4)).join();
        check(texel(0, 0) === "0,0,0,255" && texel(4, 2) === "128,64,0,255", "the typed UAV: each thread's position (" + texel(0, 0) + " / " + texel(4, 2) + ")");
        const raw = new Uint32Array(mobs.get(3).buffer);
        check(raw[0] === 64, "the raw UAV: 64 atomic adds (" + raw[0] + ")");
        const count = new Uint32Array(mobs.get(4).buffer);
        check(count[1] === 64, "the append counter, copied out: 64 (" + count[1] + ")");
        const appended = Array.from(new Uint32Array(mobs.get(2).buffer)).sort((a, b) => a - b);
        check(appended.every((v, i) => v === i), "the append buffer has every thread's index once (" + appended.slice(0, 8) + "...)");

        // a UAV clear: the raw buffer's words become 7
        run(C.SVGA_3D_CMD_DX_CLEAR_UA_VIEW_UINT, 2, 7, 7, 7, 7);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RAW, 0);
        await finished();
        check(Array.from(new Uint32Array(mobs.get(3).buffer)).join() === "7,7,7,7", "CLEAR_UA_VIEW_UINT on the raw buffer: " + Array.from(new Uint32Array(mobs.get(3).buffer)));

        // a draw with no targets: the pixel shader's UAV (the raw buffer, cleared) counts the 8 x 8 pixels
        const VB = 14;
        mobs.set(6, new Uint8Array(new Float32Array([-1, -1, -1, 3, 3, -1]).buffer));
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V3, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, 0, C.SVGA3D_BUFFER, 1, 0, 0, 0, 0, 24, 1, 1, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 6);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 3, C.SVGA3D_SHADERTYPE_PS, PS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 5, 1024);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 3, 5, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 8, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF);
        run(C.SVGA_3D_CMD_DX_SET_UA_VIEWS, 0, 2);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(8), f32(8), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_UA_VIEW_UINT, 2, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RAW, 0);
        await finished();
        check(new Uint32Array(mobs.get(3).buffer)[0] === 64, "a draw without targets: its pixel shader's UAV counts 64 pixels (" + new Uint32Array(mobs.get(3).buffer)[0] + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                             source/v64/tests/glbridge/svga_cube_array_browser_test.html                                         0000644 0000000 0000000 00000021672 00000000000 021441  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: cube arrays</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// Two cubes in one cube array (shader model 4.1), each face its own colour.
// Twelve one-pixel draws sample the faces +X, -X, +Y, -Y, +Z, -Z of cube 0,
// then of cube 1: pixel n has the colour of layer n.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const OPERAND = { INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, SAMPLER: 6, RESOURCE: 7, CONSTANT_BUFFER: 8 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const zero = (type, indices) => [(0 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4 | 1, 2 + body.length, ...body]); };
const DCL_RESOURCE = 88, DCL_CONSTANT_BUFFER = 89, DCL_SAMPLER = 90, DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103;
const MOV = 54, SAMPLE = 69, RET = 62;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 3), swizzled(OPERAND.INPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 12), imm(0, 0, 0, 1)),
    ins(RET));
// o0 = t0.sample(s0, cb0[0]): the direction and the cube in the constant buffer
const PS = program(0,
    ins(DCL_CONSTANT_BUFFER, swizzled(OPERAND.CONSTANT_BUFFER, [0, 1])),
    ins(DCL_SAMPLER, zero(OPERAND.SAMPLER, [0])),
    insc(DCL_RESOURCE, 10 /* TEXTURECUBEARRAY */, zero(OPERAND.RESOURCE, [0]), 0x5555),
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(SAMPLE, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.CONSTANT_BUFFER, [0, 0]), swizzled(OPERAND.RESOURCE, [0]), zero(OPERAND.SAMPLER, [0])),
    ins(RET));

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10.1",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        const RT = 10, CUBES = 11, VB = 12, CB = 13;
        const U8 = C.SVGA3D_R8G8B8A8_UNORM;
        const colour = layer => [layer * 20, 255 - layer * 20, (layer % 6) * 40, 255];
        mobs.set(1, new Uint8Array(12 * 4));
        // the cubes: 12 layers of 2x2 texels
        const texels = new Uint8Array(12 * 16);
        for(let layer = 0; layer < 12; layer++) for(let i = 0; i < 4; i++) texels.set(colour(layer), layer * 16 + i * 4);
        mobs.set(2, texels);
        mobs.set(3, new Uint8Array(new Float32Array([-1, -1, -1, 3, 3, -1]).buffer));
        const directions = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];
        const constants = new Float32Array(12 * 4);
        for(let n = 0; n < 12; n++) constants.set([...directions[n % 6].map(v => v * 0.9), n < 6 ? 0 : 1], n * 4);
        mobs.set(4, new Uint8Array(constants.buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(PS.buffer), 2048);
        mobs.set(5, shaders);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, C.SVGA3D_SURFACE_BIND_RENDER_TARGET, U8, 1, 0, 0, 12, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, CUBES, C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE | C.SVGA3D_SURFACE_CUBEMAP | C.SVGA3D_SURFACE_ARRAY,
            U8, 1, 0, 0, 2, 2, 1, 12, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 24, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, CB, C.SVGA3D_SURFACE_BIND_CONSTANT_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 12 * 16, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, CUBES, 2);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 3);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, CB, 4);
        run(C.SVGA_3D_CMD_UPDATE_GB_SURFACE, CUBES);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, U8, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        // mostDetailedMip, firstArraySlice, mipLevels, arraySize (cubes)
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW, 0, CUBES, U8, C.SVGA3D_RESOURCE_TEXTURECUBE, 0, 0, 1, 2);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_PS, PS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 5, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 5, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER_RESOURCES, 0, C.SVGA3D_SHADERTYPE_PS, 0);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 8, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(0));
        for(let n = 0; n < 12; n++)
        {
            run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(n), f32(0), f32(1), f32(1), f32(0), f32(1));
            run(C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER, 0, C.SVGA3D_SHADERTYPE_PS, CB, n * 16, 16);
            run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        }
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const out = mobs.get(1);
        const got = [], want = [];
        for(let n = 0; n < 12; n++)
        {
            got.push(Array.from(out.subarray(n * 4, n * 4 + 4)).join(","));
            want.push(colour(n).join(","));
        }
        const names = ["+X", "-X", "+Y", "-Y", "+Z", "-Z"];
        const wrong = got.map((g, n) => g === want[n] ? null : "cube " + (n / 6 | 0) + " " + names[n % 6] + ": " + g + " (want " + want[n] + ")").filter(Boolean);
        check(!wrong.length, "each direction samples its face of its cube" + (wrong.length ? ": " + wrong.join("; ") : ""));
        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                      source/v64/tests/glbridge/svga_depth_upload_browser_test.html                                       0000644 0000000 0000000 00000020643 00000000000 021772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: depth and stencil from the guest</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A D24_UNORM_S8_UINT surface whose MOB holds depth 0.25 on the left, 0.75
// on the right, and stencil 5 everywhere. WebGPU copies nothing into a 24-bit
// depth aspect: GX draws the depth in and copies the stencil. A quad at depth
// 0.5 with LESS and stencil EQUAL 5 then shows on the right half only; a
// second one at depth 0 with stencil EQUAL 6 shows nowhere.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const OPERAND = { INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, MOV = 54, RET = 62;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
// VS: the position as given (xyz), w 1
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 7), swizzled(OPERAND.INPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 8), imm(0, 0, 0, 1)),
    ins(RET));
const colour = (...rgba) => program(0,
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), imm(...rgba)),
    ins(RET));
const WHITE = colour(1, 1, 1, 1), RED = colour(1, 0, 0, 1);

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MOB 1: the target; 2: the depth surface; 3: two quads; 4: the shaders
        const RT = 10, DS = 11, VB = 12;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        const depth = new Uint32Array(64 * 64);
        for(let y = 0; y < 64; y++) for(let x = 0; x < 64; x++)
            depth[y * 64 + x] = Math.round((x < 32 ? 0.25 : 0.75) * 0xFFFFFF) | 5 << 24;
        mobs.set(2, new Uint8Array(depth.buffer));
        const quad = z => [-1, -1, z, -1, 1, z, 1, -1, z, 1, -1, z, -1, 1, z, 1, 1, z];
        mobs.set(3, new Uint8Array(new Float32Array([...quad(0.5), ...quad(0.0)]).buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(WHITE.buffer), 1024);
        shaders.set(new Uint8Array(RED.buffer), 2048);
        mobs.set(4, shaders);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, C.SVGA3D_SURFACE_BIND_RENDER_TARGET, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, DS, C.SVGA3D_SURFACE_BIND_DEPTH_STENCIL, C.SVGA3D_D24_UNORM_S8_UINT, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 2 * 18 * 4, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, DS, 2);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 3);
        run(C.SVGA_3D_CMD_UPDATE_GB_SURFACE, DS);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW, 0, DS, C.SVGA3D_D24_UNORM_S8_UINT, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1, 0);
        // depth LESS without writes; stencil EQUAL, keep (comparison: LESS 2, EQUAL 3; KEEP 1)
        const face = 1 | 1 << 8 | 1 << 16 | 3 << 24;
        run(C.SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE, 0, 1 | 0 << 8 | 2 << 16 | 1 << 24, 1 | 1 << 8 | 0xFF << 16 | 0 << 24, face, face);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32B32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_PS, WHITE.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 3, C.SVGA3D_SHADERTYPE_PS, RED.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 4, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 4, 1024);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 3, 4, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 12, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(64), f32(64), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE, 0, 5);
        run(C.SVGA_3D_CMD_DX_DRAW, 6, 0);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE, 0, 6);
        run(C.SVGA_3D_CMD_DX_DRAW, 6, 6);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const target = mobs.get(1);
        // B8G8R8A8: blue, green, red, alpha
        const pixel = (x, y) => Array.from(target.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4)).join();
        check(pixel(16, 32) === "0,0,0,255", "the left half's depth 0.25 hides the quad at 0.5 (" + pixel(16, 32) + ")");
        check(pixel(48, 32) === "255,255,255,255", "the right half's depth 0.75 lets it through, with stencil 5 (" + pixel(48, 32) + ")");
        check(pixel(8, 8) !== "0,0,255,255" && pixel(56, 56) !== "0,0,255,255", "stencil 6 matches nowhere: no red");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                             source/v64/tests/glbridge/svga_dx_browser_test.html                                                 0000644 0000000 0000000 00000017245 00000000000 017741  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: VGPU10 through GX to WebGPU and back</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The DX path end to end, without a guest: GB surfaces in MOBs, a DX context
// with views, an input layout, VGPU10 shaders and state, through the device's
// DX layer (svga3d_dx.js), GX batches, the renderer (svga_renderer.js) and GX
// (gx/gx_executor.js) on a real GPU, and the picture back into the render
// target's MOB: a blue clear with a red triangle over its top left half.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

// a VGPU10 assembler: just what these shaders need
const OPERAND = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, CONSTANT_BUFFER: 8 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, DCL_CONSTANT_BUFFER = 89, MOV = 54, RET = 62;
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0])),
    ins(RET));
const PS = program(0,
    ins(DCL_CONSTANT_BUFFER, swizzled(OPERAND.CONSTANT_BUFFER, [0, 1])),
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.CONSTANT_BUFFER, [0, 0])),
    ins(RET));

(async () => {
    try {
        // MOBs: plain arrays
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaRenderer = renderer;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MOB 1: the 64x64 target; 2: three vertices; 3: the color; 4: the shaders
        const RT = 10, VB = 11, CB = 12;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        mobs.set(2, new Uint8Array(new Float32Array([-1, 1, 0, 1, 1, 1, 0, 1, -1, -1, 0, 1]).buffer));
        mobs.set(3, new Uint8Array(new Float32Array([1, 0, 0, 1]).buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(PS.buffer), 1024);
        mobs.set(4, shaders);
        const BIND_RT = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, BIND_RT, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 48, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, CB, C.SVGA3D_SURFACE_BIND_CONSTANT_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 16, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, CB, 3);

        // the DX context and its objects
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32B32A32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_PS, PS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 4, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 4, 1024);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 16, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER, 0, C.SVGA3D_SHADERTYPE_PS, CB, 0, 16);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(64), f32(64), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(1), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const gx = renderer.gx;
        check(gx, "GX made on the D3D9 executor's device");
        check(gx.stats.draws === 1 && gx.stats.pipelines === 1, "one draw, one pipeline (" + JSON.stringify(gx.stats) + ")");
        const target = mobs.get(1);
        const pixel = (x, y) => Array.from(target.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4));
        check(pixel(8, 8).join() === "0,0,255,255", "inside the triangle: red, as BGRA (" + pixel(8, 8) + ")");
        check(pixel(56, 56).join() === "255,0,0,255", "outside: the blue clear (" + pixel(56, 56) + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/glbridge/svga_fixed_function_browser_test.html                                     0000644 0000000 0000000 00000026266 00000000000 022335  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II 3D: a fixed-function vertex stage with a pixel shader</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The legacy 3D path end to end, without a guest: SVGA3D commands into the
// device's 3D layer (src/graphics_adapters/vmware_svga/svga3d.js), its D9WG
// batches through the renderer (src/browser/glbridge/svga_renderer.js) and the
// D3D9 executor on a real GPU, and the pictures back: a cleared render target
// with a triangle presented on a screen object, and a texture uploaded with
// SURFACE_DMA and read back into guest memory.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

(async () => {
    try {
        // GMR 1: 64 KiB of "guest memory"
        const guest = new Uint8Array(65536);
        const gmrs = {
            read: (id, offset, length) => id === 1 && offset + length <= guest.length ? guest.slice(offset, offset + length) : null,
            write: (id, offset, bytes) => { if(id !== 1 || offset + bytes.length > guest.length) return false; guest.set(bytes, offset); return true; },
        };
        const screens = new ScreenObjects(gmrs);
        const screen_def = [44, 0, C.SVGA_SCREEN_MUST_BE_SET | C.SVGA_SCREEN_IS_PRIMARY, 64, 64, 0, 0, C.SVGA_GMR_NULL, 0, 0, 0];
        check(screens.define(i => screen_def[i], 11), "a 64x64 screen object");
        const screen = screens.screens.get(0);
        let irq = 0;
        // at level dx10, with MOBs: a GB surface gets its D9WG texture when
        // legacy 3D first uses it
        const mob = new Uint8Array(16 * 16 * 4);
        const mobs = {
            read: (id, offset, length) => id === 1 && offset + length <= mob.length ? mob.slice(offset, offset + length) : null,
            write: (id, offset, bytes) => { if(id !== 1 || offset + bytes.length > mob.length) return false; mob.set(bytes, offset); return true; },
            size: id => id === 1 ? mob.length : -1,
        };
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10", gmrs, mobs, otables: null,
            screens, set_irq: flags => { irq |= flags; }, svga_active: () => false };

        // the two ends of the channel, as the page's local channel does it
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaExecutor = renderer.executor;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));
        const NO_MIPS = [0, 0, 0, 0, 0];

        // a 64x64 render target and a triangle's vertex buffer
        // What VMware's D3D9 driver sends for a textured quad of
        // pre-transformed vertices (XYZRHW, DIFFUSE, TEX1): no vertex shader,
        // and a ps_2_0 it made for the texture stages, which reads t0
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 1, C.SVGA3D_SURFACE_HINT_RENDERTARGET, C.SVGA3D_X8R8G8B8, 1, ...NO_MIPS, 64, 64, 1);
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 2, C.SVGA3D_SURFACE_HINT_VERTEXBUFFER, C.SVGA3D_BUFFER, 1, ...NO_MIPS, 6 * 28, 1, 1);
        // the texture is guest-backed, as the driver makes it: in MOB 1, a
        // render target too, and updated before anything draws with it.
        // Texel (x, y) is ARGB(255, 16x, 16y, 128), as the guest's test makes it.
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, 3, C.SVGA3D_SURFACE_HINT_TEXTURE | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE |
            C.SVGA3D_SURFACE_BIND_RENDER_TARGET, C.SVGA3D_A8R8G8B8, 1, 0, 0, 16, 16, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, 3, 1);
        const texels = new Uint32Array(mob.buffer);
        for(let y = 0; y < 16; y++) for(let x = 0; x < 16; x++) texels[y * 16 + x] = (0xFF000000 | x * 16 << 16 | y * 16 << 8 | 128) >>> 0;
        run(C.SVGA_3D_CMD_UPDATE_GB_IMAGE, 3, 0, 0, 0, 0, 0, 16, 16, 1);
        // two triangles over the whole target: x, y, z, rhw, diffuse, u, v
        const corner = (x, y) => [x * 64, y * 64, 0.5, 1, 0xFFFFFFFF, x, y];
        const quad = [corner(0, 0), corner(1, 0), corner(0, 1), corner(0, 1), corner(1, 0), corner(1, 1)];
        const vertices = new DataView(guest.buffer, 0, 6 * 28);
        quad.forEach((v, i) => {
            for(let k = 0; k < 7; k++)
            {
                if(k === 4) vertices.setUint32(i * 28 + 16, v[k], true);
                else vertices.setFloat32(i * 28 + 4 * k, v[k], true);
            }
        });
        run(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0, 6 * 28, 2, 0, 0, C.SVGA3D_WRITE_HOST_VRAM, 0, 0, 0, 6 * 28, 1, 1, 0, 0, 0);

        const CID = 1;
        run(C.SVGA_3D_CMD_CONTEXT_DEFINE, CID);
        run(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_COLOR0, 1, 0, 0);
        run(C.SVGA_3D_CMD_SETVIEWPORT, CID, 0, 0, 64, 64);
        run(C.SVGA_3D_CMD_SETZRANGE, CID, f32(0), f32(1));
        run(C.SVGA_3D_CMD_SETRENDERSTATE, CID, C.SVGA3D_RS_CULLMODE, C.SVGA3D_FACE_NONE, C.SVGA3D_RS_ZENABLE, 0,
            C.SVGA3D_RS_BLENDENABLE, 0, C.SVGA3D_RS_COLORWRITEENABLE, 0xF, C.SVGA3D_RS_LIGHTINGENABLE, 0);
        run(C.SVGA_3D_CMD_CLEAR, CID, C.SVGA3D_CLEAR_COLOR, 0xFF202020, f32(1), 0);
        run(C.SVGA_3D_CMD_SETTEXTURESTATE, CID, 0, C.SVGA3D_TS_BIND_TEXTURE, 3,
            0, C.SVGA3D_TS_MINFILTER, C.SVGA3D_TEX_FILTER_NEAREST, 0, C.SVGA3D_TS_MAGFILTER, C.SVGA3D_TEX_FILTER_NEAREST,
            0, C.SVGA3D_TS_TEXCOORDINDEX, 0);
        run(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 1, C.SVGA3D_SHADERTYPE_PS,
            0xffff0200, 0x2fffe, 0x54584554, 0x464624, 0x200001f, 0x80000000, 0x900f0000, 0x200001f, 0x80000000,
            0xb00f0000, 0x200001f, 0x90000000, 0xa00f0800, 0x3000042, 0x802f0001, 0xb0e40000, 0xa0e40800, 0x3000005,
            0x80370005, 0x80e40001, 0x90e40000, 0x2000001, 0x80380005, 0x80e40001, 0x2000001, 0x802f0001, 0x80e40005,
            0x2000001, 0x802f0800, 0x80e40001, 0xffff);
        run(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_PS, 1);
        const decl = (type, usage, offset) => [type, C.SVGA3D_DECLMETHOD_DEFAULT, usage, 0, 2, offset, 28, 0, 5];
        run(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 3, 1,
            ...decl(C.SVGA3D_DECLTYPE_FLOAT4, C.SVGA3D_DECLUSAGE_POSITIONT, 0),
            ...decl(C.SVGA3D_DECLTYPE_D3DCOLOR, C.SVGA3D_DECLUSAGE_COLOR, 16),
            ...decl(C.SVGA3D_DECLTYPE_FLOAT2, C.SVGA3D_DECLUSAGE_TEXCOORD, 20),
            C.SVGA3D_PRIMITIVE_TRIANGLELIST, 2, -1, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 64, 64, 0, 0, 0, 64, 64);
        await finished();
        const pixel = (x, y) => Array.from(screen.rgba.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 3));
        const near = (a, b) => a.every((v, i) => Math.abs(v - b[i]) <= 2);
        // pixel (x, y) shows texel (x / 4, y / 4)
        check(near(pixel(9, 9), [32, 32, 128]), "the texture's texel (2, 2) at pixel (9, 9): " + pixel(9, 9));
        check(near(pixel(61, 33), [240, 128, 128]), "texel (15, 8) at pixel (61, 33): " + pixel(61, 33));

        // A vertex shader left bound does not apply to pre-transformed
        // vertices: the quad is drawn as before, here in its vertex colour
        // (white) through a pixel shader showing v0
        run(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 3, C.SVGA3D_SHADERTYPE_PS,
            0xFFFF0200, 0x0200001F, 0x80000000, 0x900F0000, 0x02000001, 0x800F0800, 0x90E40000, 0x0000FFFF);
        run(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_PS, 3);
        const VS = [0xFFFE0200, 0x0200001F, 0x80000000, 0x900F0000, 0x0200001F, 0x8000000A, 0x900F0001,
            0x0200001F, 0x80000005, 0x900F0002, 0x02000001, 0xC00F0000, 0x90E40000,
            0x02000001, 0xD00F0000, 0x90E40001, 0x02000001, 0xE00F0000, 0x90E40002, 0x0000FFFF];
        run(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 2, C.SVGA3D_SHADERTYPE_VS, ...VS);
        run(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_VS, 2);
        run(C.SVGA_3D_CMD_CLEAR, CID, C.SVGA3D_CLEAR_COLOR, 0xFF00FF00, f32(1), 0);
        run(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 3, 1,
            ...decl(C.SVGA3D_DECLTYPE_FLOAT4, C.SVGA3D_DECLUSAGE_POSITIONT, 0),
            ...decl(C.SVGA3D_DECLTYPE_D3DCOLOR, C.SVGA3D_DECLUSAGE_COLOR, 16),
            ...decl(C.SVGA3D_DECLTYPE_FLOAT2, C.SVGA3D_DECLUSAGE_TEXCOORD, 20),
            C.SVGA3D_PRIMITIVE_TRIANGLELIST, 2, -1, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 64, 64, 0, 0, 0, 64, 64);
        await finished();
        check(near(pixel(9, 9), [255, 255, 255]), "POSITIONT with a vertex shader bound: drawn pre-transformed: " + pixel(9, 9));

        // The shader's COLOR and TEXCOORD inputs are not in this declaration:
        // they read (0, 0, 0, 1), and a pixel shader showing v0 makes the quad black
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 4, C.SVGA3D_SURFACE_HINT_VERTEXBUFFER, C.SVGA3D_BUFFER, 1, ...NO_MIPS, 6 * 16, 1, 1);
        new Float32Array(guest.buffer, 0x3000, 24).set([-1, 1, 0, 1, 1, 1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, 1, 1, -1, 0, 1]);
        run(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0x3000, 6 * 16, 4, 0, 0, C.SVGA3D_WRITE_HOST_VRAM, 0, 0, 0, 6 * 16, 1, 1, 0, 0, 0);
        run(C.SVGA_3D_CMD_CLEAR, CID, C.SVGA3D_CLEAR_COLOR, 0xFF00FF00, f32(1), 0);
        run(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 1, 1,
            C.SVGA3D_DECLTYPE_FLOAT4, C.SVGA3D_DECLMETHOD_DEFAULT, C.SVGA3D_DECLUSAGE_POSITION, 0, 4, 0, 16, 0, 5,
            C.SVGA3D_PRIMITIVE_TRIANGLELIST, 2, -1, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 64, 64, 0, 0, 0, 64, 64);
        await finished();
        check(near(pixel(9, 9), [0, 0, 0]), "inputs the declaration does not supply read (0, 0, 0, 1): " + pixel(9, 9));
        check(!irq, "the renderer reported no errors");
        const stats = renderer.executor.stats;
        check(stats.commandsFailed === 0 && stats.malformedBatches === 0, "the executor ran every command");
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        const executor = globalThis.svgaExecutor;
        const stats = executor ? Object.entries(executor.stats).filter(([, v]) => v).map(([k, v]) => k + "=" + v).join(" ") : "";
        result.textContent = "FAIL " + (error && error.stack || error) + "\n" + checks.join("\n") + "\nstats: " + stats +
            "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                          source/v64/tests/glbridge/svga_gs_browser_test.html                                                 0000644 0000000 0000000 00000022300 00000000000 017723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: a geometry shader, emulated with compute</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A geometry shader through GX, which has no such WebGPU stage: the vertex
// shader runs as compute pulling its vertices, the geometry shader as compute
// on what it stored, and the triangles it emitted are drawn. Four points
// become four 16x16 quads, each coloured by its primitive id.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

// a VGPU10 assembler: just what these shaders need
const OPERAND = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, CONSTANT_BUFFER: 8 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, DCL_CONSTANT_BUFFER = 89, MOV = 54, RET = 62;
const ADD = 0, UTOF = 86, MUL = 56, EMIT = 19;
const DCL_GS_INPUT_PRIMITIVE = 93, DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY = 92, DCL_MAX_OUTPUT_VERTEX_COUNT = 94;
const INPUT_PRIMITIVEID = 11;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
const selected = (type, indices, lane) => [(2 | 2 << 2 | lane << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
// VS: the position from the input layout, as it is
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0])),
    ins(RET));
// GS: a point into a quad (a strip of four), o1 = (primitive id, 0, 0, 1)
const corner = (dx, dy) => [
    ins(ADD, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0, 0]), imm(dx, dy, 0, 0)),
    ins(UTOF, operand(OPERAND.OUTPUT, [1], 1), selected(INPUT_PRIMITIVEID, [], 0)),
    ins(MOV, operand(OPERAND.OUTPUT, [1], 14), imm(0, 0, 1, 1)),
    ins(EMIT)];
const GS = program(2,
    insc(DCL_GS_INPUT_PRIMITIVE, 1),
    insc(DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, 5),
    ins(DCL_MAX_OUTPUT_VERTEX_COUNT, 4),
    ins(DCL_INPUT, operand(OPERAND.INPUT, [1, 0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [1])),
    ...corner(-0.25, -0.25), ...corner(-0.25, 0.25), ...corner(0.25, -0.25), ...corner(0.25, 0.25),
    ins(RET));
// PS: red from the primitive id / 4, green 1, blue from the input
const PS = program(0,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [1])),
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MUL, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [1]), imm(0.25, 0, 1, 1)),
    ins(ADD, operand(OPERAND.OUTPUT, [0], 2), swizzled(OPERAND.INPUT, [1]), imm(1, 1, 1, 1)),
    ins(RET));

(async () => {
    try {
        // MOBs: plain arrays
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaRenderer = renderer;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MOB 1: the 64x64 target; 2: four points; 4: the shaders
        const RT = 10, VB = 11;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        mobs.set(2, new Uint8Array(new Float32Array([-0.5, 0.5, 0, 1, 0.5, 0.5, 0, 1, -0.5, -0.5, 0, 1, 0.5, -0.5, 0, 1]).buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(GS.buffer), 1024);
        shaders.set(new Uint8Array(PS.buffer), 2048);
        mobs.set(4, shaders);
        const BIND_RT = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, BIND_RT, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 64, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);

        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32B32A32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_GS, GS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 3, C.SVGA3D_SHADERTYPE_PS, PS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 4, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 4, 1024);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 3, 4, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_GS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 16, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_POINTLIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(64), f32(64), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW, 4, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const gx = renderer.gx;
        check(gx && gx.stats.geometryDraws === 1, "one draw through the geometry path (" + JSON.stringify(gx && gx.stats) + ")");
        const target = mobs.get(1);
        const pixel = (x, y) => Array.from(target.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4));
        // point i at NDC (+-0.5, +-0.5): pixels 16 or 48; BGRA, red = i / 4 * 255
        const expect = [[16, 16, 0], [48, 16, 1], [16, 48, 2], [48, 48, 3]];
        for (const [x, y, i] of expect) {
            const p = pixel(x, y);
            check(Math.abs(p[2] - Math.round(i / 4 * 255)) <= 2 && p[1] === 255 && p[0] === 255,
                "quad " + i + " at (" + x + ", " + y + "), coloured by its primitive id: " + p);
        }
        check(pixel(32, 32).join() === "0,0,0,255", "between the quads: the clear (" + pixel(32, 32) + ")");
        check(pixel(16, 6).join() === "0,0,0,255", "outside a quad's 8-pixel half size: the clear (" + pixel(16, 6) + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                source/v64/tests/glbridge/svga_msaa_browser_test.html                                               0000644 0000000 0000000 00000031063 00000000000 020241  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: multisampling, supersampled</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// GX supersamples 4x multisampled surfaces: a texture twice as wide and
// high, each sample a texel. So every format multisamples, here
// R32G32B32A32_FLOAT, which WebGPU cannot. A triangle's edge resolves to
// partly covered pixels; a pixel shader run per sample sees its sample index
// (and the resolve averages them); a sample mask of one sample leaves a
// quarter of the coverage.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const OPERAND = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const selected = (type, indices, lane) => [(2 | 2 << 2 | lane << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4 | 1, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_INPUT_PS_SGV = 99, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, DCL_TEMPS = 104, MOV = 54, MUL = 56, UTOF = 86, RET = 62;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 3), swizzled(OPERAND.INPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 12), imm(0, 0, 0, 1)),
    ins(RET));
const WHITE = program(0,
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), imm(1, 1, 1, 1)),
    ins(RET));
// o0 = sample index / 3, so the four samples' mean is 0.5
const SAMPLE = program(0,
    insc(DCL_INPUT_PS_SGV, 1 /* constant */, operand(OPERAND.INPUT, [1], 1), 10 /* SAMPLE_INDEX */),
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(DCL_TEMPS, 1),
    ins(UTOF, operand(OPERAND.TEMP, [0], 1), selected(OPERAND.INPUT, [1], 0)),
    ins(MUL, operand(OPERAND.OUTPUT, [0]), selected(OPERAND.TEMP, [0], 0), imm(1 / 3, 1 / 3, 1 / 3, 1 / 3)),
    ins(RET));

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10.1",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MS: the multisampled target; OUT: what it resolves into (MOB 1); VB: a triangle (MOB 2); shaders (MOB 3)
        const MS = 10, OUT = 11, VB = 12, MS8 = 13, OUT8 = 14, X8 = 15, OUTX8 = 16;
        const SIZE = 16, F = C.SVGA3D_R32G32B32A32_FLOAT, U8 = C.SVGA3D_R8G8B8A8_UNORM;
        mobs.set(1, new Uint8Array(SIZE * SIZE * 16));
        mobs.set(4, new Uint8Array(SIZE * SIZE * 4));
        mobs.set(5, new Uint8Array(SIZE * SIZE * 16));
        // the lower left half, with a diagonal edge; then a quad over everything
        mobs.set(2, new Uint8Array(new Float32Array([-1, -1, -1, 1, 1, -1,  -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1]).buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(WHITE.buffer), 1024);
        shaders.set(new Uint8Array(SAMPLE.buffer), 2048);
        mobs.set(3, shaders);
        const BIND = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        // DEFINE_GB_SURFACE_V2: sid, flags, format, mips, samples, filter, width, height, depth, array size, (pad)
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, MS, BIND, F, 1, 4, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, OUT, BIND, F, 1, 0, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, MS8, BIND, U8, 1, 4, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, OUT8, BIND, U8, 1, 0, 0, SIZE, SIZE, 1, 1, 0);
        // eight samples: 4 x 2 texels a pixel
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, X8, BIND, F, 1, 8, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, OUTX8, BIND, F, 1, 0, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 72, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, OUT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, OUT8, 4);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, OUTX8, 5);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, MS, F, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 1, MS8, U8, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 2, X8, F, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32_FLOAT, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 2, C.SVGA3D_SHADERTYPE_PS, WHITE.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 3, C.SVGA3D_SHADERTYPE_PS, SAMPLE.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 3, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 2, 3, 1024);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 3, 3, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 8, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(SIZE), f32(SIZE), f32(0), f32(1));

        // 1. the triangle into the float target, resolved
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(0));
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        run(C.SVGA_3D_CMD_DX_RESOLVE_COPY, OUT, 0, MS, 0, F);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, OUT, 0);
        // 2. per sample: the sample index, resolved to the mean
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 1);
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 1, f32(0), f32(0), f32(0), f32(0));
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_DRAW, 6, 3);
        // 3. then white through a sample mask of sample 0, over the right half only (a scissor would be simpler; a viewport will do)
        run(C.SVGA_3D_CMD_DX_SET_BLEND_STATE, 0xFFFFFFFF, f32(0), f32(0), f32(0), f32(0), 1);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(SIZE / 2), f32(0), f32(SIZE / 2), f32(SIZE), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_DRAW, 6, 3);
        run(C.SVGA_3D_CMD_DX_RESOLVE_COPY, OUT8, 0, MS8, 0, U8);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, OUT8, 0);
        // 4. eight samples: the triangle's edge in eighths; per sample, indices / 3
        run(C.SVGA_3D_CMD_DX_SET_BLEND_STATE, 0xFFFFFFFF, f32(0), f32(0), f32(0), f32(0), 0xFFFFFFFF);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(SIZE), f32(SIZE), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 2);
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 2, f32(0), f32(0), f32(0), f32(0));
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(SIZE / 2), f32(0), f32(SIZE / 2), f32(SIZE), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW, 6, 3);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(SIZE / 2), f32(SIZE), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        run(C.SVGA_3D_CMD_DX_RESOLVE_COPY, OUTX8, 0, X8, 0, F);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, OUTX8, 0);
        await finished();

        const floats = new Float32Array(mobs.get(1).buffer);
        const red = (x, y) => floats[(y * SIZE + x) * 4];
        check(red(2, 13) === 1 && red(13, 2) === 0, "inside the triangle 1, outside 0 (" + red(2, 13) + ", " + red(13, 2) + ")");
        // the diagonal from (0, 0) to (16, 16): pixels on it are partly covered
        const partial = [];
        for(let x = 0; x < SIZE; x++) if(red(x, x) > 0 && red(x, x) < 1) partial.push(x + ":" + red(x, x));
        check(partial.length >= SIZE / 2, "the edge's pixels are partly covered: " + partial.join(" "));
        const bytes = mobs.get(4);
        const px = (x, y) => Array.from(bytes.subarray((y * SIZE + x) * 4, (y * SIZE + x) * 4 + 4));
        check(Math.abs(px(4, 8)[0] - 128) <= 2, "per-sample shading: the samples' indices / 3 resolve to 0.5 (" + px(4, 8) + ")");
        // the right half: sample 0 white, the others from step 2 (1/3, 2/3, 1): (1 + 1/3 + 2/3 + 1) / 4
        check(Math.abs(px(12, 8)[0] - 191) <= 2, "a sample mask of sample 0 changes a quarter (" + px(12, 8) + ")");

        const x8 = new Float32Array(mobs.get(5).buffer);
        const at8 = (x, y) => x8[(y * SIZE + x) * 4];
        // (the left half: the triangle squeezed into it; its edge from (0, 0) to (8, 16))
        const eighths = new Set();
        for(let y = 0; y < SIZE; y++) for(let x = 0; x < SIZE / 2; x++) { const v = at8(x, y); if(v > 0 && v < 1) eighths.add(v * 8); }
        check(eighths.size >= 2 && [...eighths].every(v => Math.abs(v - Math.round(v)) < 1e-4),
            "8x: partly covered edge pixels in eighths (" + [...eighths].sort((a, b) => a - b).join(", ") + " / 8)");
        const meanX8 = at8(12, 8);
        // (a float target: nothing clamps)
        check(Math.abs(meanX8 - (0 + 1 + 2 + 3 + 4 + 5 + 6 + 7) / 3 / 8) < 1e-4, "8x per-sample shading: the eight indices / 3 resolve to their mean (" + meanX8 + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/glbridge/svga_pull_browser_test.html                                               0000644 0000000 0000000 00000021136 00000000000 020274  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: vertices WebGPU cannot fetch, pulled</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A draw whose input layout WebGPU's vertex fetch cannot take (here an
// instance step rate of 2) goes through GX's compute path: the vertex shader
// pulls its vertices, and its records are drawn. Four instances of a
// triangle, every two sharing their offset: two triangles show.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

// a VGPU10 assembler: just what these shaders need
const OPERAND = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, CONSTANT_BUFFER: 8 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, DCL_CONSTANT_BUFFER = 89, MOV = 54, RET = 62;
const ADD = 0, UTOF = 86, MUL = 56, EMIT = 19;
const DCL_GS_INPUT_PRIMITIVE = 93, DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY = 92, DCL_MAX_OUTPUT_VERTEX_COUNT = 94;
const INPUT_PRIMITIVEID = 11;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
const selected = (type, indices, lane) => [(2 | 2 << 2 | lane << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
// VS: position (v0.xy) + the instance's offset (v1.xy)
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_INPUT, operand(OPERAND.INPUT, [1])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(ADD, operand(OPERAND.OUTPUT, [0], 3), swizzled(OPERAND.INPUT, [0]), swizzled(OPERAND.INPUT, [1])),
    ins(MOV, operand(OPERAND.OUTPUT, [0], 12), imm(0, 0, 0, 1)),
    ins(RET));
const PS = program(0,
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), imm(1, 1, 1, 1)),
    ins(RET));

(async () => {
    try {
        // MOBs: plain arrays
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaRenderer = renderer;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MOB 1: the target; 2: a small triangle; 3: the instances' offsets; 4: the shaders
        const RT = 10, VB = 11, IB = 12;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        mobs.set(2, new Uint8Array(new Float32Array([-0.2, -0.2, 0, 0.2, 0.2, -0.2]).buffer));  // clockwise: front-facing
        // offsets: four, but with a step rate of 2 only the first two are read
        mobs.set(3, new Uint8Array(new Float32Array([-0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5]).buffer));
        const shaders = new Uint8Array(4096);
        shaders.set(new Uint8Array(VS.buffer), 0);
        shaders.set(new Uint8Array(PS.buffer), 2048);
        mobs.set(4, shaders);
        const BIND_RT = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, BIND_RT, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 24, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, IB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 32, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, IB, 3);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        // slot, offset, format, class (1: per instance), step rate, register
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0,
            0, 0, C.SVGA3D_R32G32_FLOAT, 0, 0, 0,
            1, 0, C.SVGA3D_R32G32_FLOAT, 1, 2, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 1, C.SVGA3D_SHADERTYPE_VS, VS.byteLength);
        run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, 3, C.SVGA3D_SHADERTYPE_PS, PS.byteLength);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 1, 4, 0);
        run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, 3, 4, 2048);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 8, 0, IB, 8, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(64), f32(64), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW_INSTANCED, 3, 4, 0, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const gx = renderer.gx;
        check(gx && gx.stats.pulledDraws === 1, "the draw went through the pulling path (" + JSON.stringify(gx && gx.stats) + ")");
        const target = mobs.get(1);
        const pixel = (x, y) => Array.from(target.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4)).join();
        // offset 0 (-0.5, 0.5): around pixel (16, 16); offset 1 (0.5, -0.5): around (48, 48)
        const white = [];
        for (let y = 0; y < 64; y += 4) for (let x = 0; x < 64; x += 4) if (target[(y * 64 + x) * 4] > 128) white.push(x + "," + y);
        check(pixel(16, 17) === "255,255,255,255", "instances 0 and 1: the first offset (" + pixel(16, 17) + "; white at " + white.join(" ") + ")");
        check(pixel(48, 49) === "255,255,255,255", "instances 2 and 3: the second offset (" + pixel(48, 49) + ")");
        check(pixel(48, 17) === "0,0,0,255", "no triangle at the third offset, which a step rate of 1 would read (" + pixel(48, 17) + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/glbridge/svga_remote_renderer.html                                                 0000644 0000000 0000000 00000010005 00000000000 017670  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>Remote SVGA renderer</title>
<pre id="status">connecting</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
// The browser half of tests/x64/gpu_remote_renderer.mjs: the SVGA renderer,
// on this page's WebGPU, for a device in a node process at the other end of
// the WebSocket. The frame format is described there.
const TYPES = { submit: 1, reset: 2, write: 3, done: 4, lost: 5, ready: 6, submit_gx: 7, log: 8, submit_vx: 9 };
// the renderer's warnings go to the harness, for its log
for(const method of ["warn", "error"])
{
    const original = console[method];
    console[method] = (...args) => {
        original.apply(console, args);
        const text = args.map(a => typeof a === "object" ? (a && a.stack) || JSON.stringify(a) : String(a)).join(" ");
        if(globalThis.remoteSocket && globalThis.remoteSocket.readyState === 1) {
            globalThis.remoteSocket.send(new Uint8Array([TYPES.log, ...new TextEncoder().encode(text.slice(0, 4000))]));
        }
    };
}
const status = document.getElementById("status");
const socket = new WebSocket(new URLSearchParams(location.search).get("ws"));
socket.binaryType = "arraybuffer";
let to_renderer = null;
const send = (type, number, bytes) => {
    const message = new Uint8Array(5 + (bytes ? bytes.length : 0));
    message[0] = type;
    new DataView(message.buffer).setUint32(1, number >>> 0, true);
    if(bytes) message.set(bytes, 5);
    socket.send(message);
};
// every 10 s, to the harness's log: batches, bytes, and how long they took
// from arriving to done (the device's fences wait for that)
const arrived = new Map();
let window_stats = { batches: 0, bytes: 0, latency: 0, max: 0, start: performance.now() };
setInterval(() => {
    const w = window_stats, seconds = (performance.now() - w.start) / 1000;
    if(w.batches) console.warn("renderer-stats " + JSON.stringify({ seconds: +seconds.toFixed(1), batches: w.batches, mib: +(w.bytes / 1048576).toFixed(1),
        latency_ms: +(w.latency / w.batches).toFixed(1), max_ms: +w.max.toFixed(1), pending: arrived.size }));
    window_stats = { batches: 0, bytes: 0, latency: 0, max: 0, start: performance.now() };
}, 10000);
const renderer = V86SVGARenderer({
    post: message => {
        if(message.type === "write") send(TYPES.write, message.offset, message.bytes);
        else if(message.type === "done")
        {
            const t = arrived.get(message.seq);
            if(t !== undefined)
            {
                arrived.delete(message.seq);
                const ms = performance.now() - t;
                window_stats.batches++; window_stats.latency += ms; window_stats.max = Math.max(window_stats.max, ms);
            }
            send(TYPES.done, message.seq);
        }
        else if(message.type === "lost") socket.send(new Uint8Array([TYPES.lost, ...new TextEncoder().encode(message.reason)]));
    },
    listen: handler => { to_renderer = handler; },
}, {});
let batches = 0;
globalThis.remoteSocket = socket;
socket.onopen = () => {
    status.textContent = "connected";
    socket.send(new Uint8Array([TYPES.ready]));
};
socket.onmessage = event => {
    const bytes = new Uint8Array(event.data);
    if(bytes[0] === TYPES.submit_gx || bytes[0] === TYPES.submit_vx || bytes[0] === TYPES.submit)
    {
        arrived.set(new DataView(event.data).getUint32(1, true), performance.now());
        window_stats.bytes += bytes.length;
    }
    if(bytes[0] === TYPES.submit_gx || bytes[0] === TYPES.submit_vx)
    {
        to_renderer({ type: "submit", stream: bytes[0] === TYPES.submit_gx ? "gx" : "vx", seq: new DataView(event.data).getUint32(1, true), bytes: bytes.subarray(5) });
    }
    else if(bytes[0] === TYPES.submit)
    {
        batches++;
        to_renderer({ type: "submit", seq: new DataView(event.data).getUint32(1, true), bytes: bytes.subarray(5) });
    }
    else if(bytes[0] === TYPES.reset)
    {
        to_renderer({ type: "reset" });
    }
};
socket.onclose = () => { status.textContent = "closed after " + batches + " batches"; };
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/glbridge/svga_renderer_browser_test.html                                           0000644 0000000 0000000 00000016261 00000000000 021131  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II 3D: SVGA3D through D9WG to WebGPU and back</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The legacy 3D path end to end, without a guest: SVGA3D commands into the
// device's 3D layer (src/graphics_adapters/vmware_svga/svga3d.js), its D9WG
// batches through the renderer (src/browser/glbridge/svga_renderer.js) and the
// D3D9 executor on a real GPU, and the pictures back: a cleared render target
// with a triangle presented on a screen object, and a texture uploaded with
// SURFACE_DMA and read back into guest memory.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

(async () => {
    try {
        // GMR 1: 64 KiB of "guest memory"
        const guest = new Uint8Array(65536);
        const gmrs = {
            read: (id, offset, length) => id === 1 && offset + length <= guest.length ? guest.slice(offset, offset + length) : null,
            write: (id, offset, bytes) => { if(id !== 1 || offset + bytes.length > guest.length) return false; guest.set(bytes, offset); return true; },
        };
        const screens = new ScreenObjects(gmrs);
        const screen_def = [44, 0, C.SVGA_SCREEN_MUST_BE_SET | C.SVGA_SCREEN_IS_PRIMARY, 64, 64, 0, 0, C.SVGA_GMR_NULL, 0, 0, 0];
        check(screens.define(i => screen_def[i], 11), "a 64x64 screen object");
        const screen = screens.screens.get(0);
        let irq = 0;
        const device = { gmrs, screens, set_irq: flags => { irq |= flags; }, svga_active: () => false };

        // the two ends of the channel, as the page's local channel does it
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaExecutor = renderer.executor;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));
        const NO_MIPS = [0, 0, 0, 0, 0];

        // a 64x64 render target and a triangle's vertex buffer
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 1, C.SVGA3D_SURFACE_HINT_RENDERTARGET, C.SVGA3D_X8R8G8B8, 1, ...NO_MIPS, 64, 64, 1);
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 2, C.SVGA3D_SURFACE_HINT_VERTEXBUFFER, C.SVGA3D_BUFFER, 1, ...NO_MIPS, 36, 1, 1);
        // the top left half of the target, clockwise on the screen
        new Float32Array(guest.buffer, 0, 9).set([-1, 1, 0, 1, 1, 0, -1, -1, 0]);
        run(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0, 36, 2, 0, 0, C.SVGA3D_WRITE_HOST_VRAM, 0, 0, 0, 36, 1, 1, 0, 0, 0);

        const CID = 1;
        run(C.SVGA_3D_CMD_CONTEXT_DEFINE, CID);
        run(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_COLOR0, 1, 0, 0);
        run(C.SVGA_3D_CMD_SETRENDERTARGET, CID, C.SVGA3D_RT_DEPTH, -1, 0, 0);
        run(C.SVGA_3D_CMD_SETVIEWPORT, CID, 0, 0, 64, 64);
        run(C.SVGA_3D_CMD_SETZRANGE, CID, f32(0), f32(1));
        run(C.SVGA_3D_CMD_SETRENDERSTATE, CID, C.SVGA3D_RS_CULLMODE, C.SVGA3D_FACE_NONE, C.SVGA3D_RS_ZENABLE, 0,
            C.SVGA3D_RS_BLENDENABLE, 0, C.SVGA3D_RS_COLORWRITEENABLE, 0xF);
        run(C.SVGA_3D_CMD_CLEAR, CID, C.SVGA3D_CLEAR_COLOR, 0xFF0000FF, f32(1), 0);
        // vs_3_0: dcl_position v0; dcl_position o0; mov o0, v0
        run(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 1, C.SVGA3D_SHADERTYPE_VS, 0xFFFE0300,
            0x0200001F, 0x80000000, 0x900F0000, 0x0200001F, 0x80000000, 0xE00F0000,
            0x02000001, 0xE00F0000, 0x90E40000, 0x0000FFFF);
        // ps_3_0: mov oC0, c0
        run(C.SVGA_3D_CMD_SHADER_DEFINE, CID, 2, C.SVGA3D_SHADERTYPE_PS, 0xFFFF0300,
            0x02000001, 0x800F0800, 0xA0E40000, 0x0000FFFF);
        run(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_VS, 1);
        run(C.SVGA_3D_CMD_SET_SHADER, CID, C.SVGA3D_SHADERTYPE_PS, 2);
        run(C.SVGA_3D_CMD_SET_SHADER_CONST, CID, 0, C.SVGA3D_SHADERTYPE_PS, C.SVGA3D_CONST_TYPE_FLOAT, f32(1), f32(0.5), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DRAW_PRIMITIVES, CID, 1, 1,
            C.SVGA3D_DECLTYPE_FLOAT3, C.SVGA3D_DECLMETHOD_DEFAULT, C.SVGA3D_DECLUSAGE_POSITION, 0, 2, 0, 12, 0, 2,
            C.SVGA3D_PRIMITIVE_TRIANGLELIST, 1, -1, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN, 1, 0, 0, 0, 0, 64, 64, 0, 0, 0, 64, 64);
        await finished();
        const pixel = (x, y) => Array.from(screen.rgba.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 3));
        const near = (a, b) => a.every((v, i) => Math.abs(v - b[i]) <= 2);
        check(near(pixel(8, 8), [255, 128, 0]), "the triangle, in the pixel shader's colour: " + pixel(8, 8));
        check(near(pixel(56, 56), [0, 0, 255]), "the clear colour beside it: " + pixel(56, 56));
        check(screen.dirty_max > screen.dirty_min, "the screen has new rows to show");

        // a 4x4 A8R8G8B8 texture: up with SURFACE_DMA, and back down
        run(C.SVGA_3D_CMD_SURFACE_DEFINE, 3, C.SVGA3D_SURFACE_HINT_TEXTURE, C.SVGA3D_A8R8G8B8, 1, ...NO_MIPS, 4, 4, 1);
        for(let i = 0; i < 64; i++) guest[0x1000 + i] = i * 3 + 1;
        run(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0x1000, 16, 3, 0, 0, C.SVGA3D_WRITE_HOST_VRAM, 0, 0, 0, 4, 4, 1, 0, 0, 0);
        run(C.SVGA_3D_CMD_SURFACE_DMA, 1, 0x2000, 32, 3, 0, 0, C.SVGA3D_READ_HOST_VRAM, 1, 1, 0, 2, 2, 1, 0, 0, 0);
        await finished();
        const expect = [], got = [];
        for(let row = 0; row < 2; row++) for(let i = 0; i < 8; i++)
        {
            expect.push(guest[0x1000 + (1 + row) * 16 + 4 + i]);
            got.push(guest[0x2000 + row * 32 + i]);
        }
        check(expect.join() === got.join(), "texels (1..2, 1..2) came back where the guest asked: " + got);
        check(!irq, "the renderer reported no errors");
        const stats = renderer.executor.stats;
        check(stats.commandsFailed === 0 && stats.malformedBatches === 0, "the executor ran every command");
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        const executor = globalThis.svgaExecutor;
        const stats = executor ? Object.entries(executor.stats).filter(([, v]) => v).map(([k, v]) => k + "=" + v).join(" ") : "";
        result.textContent = "FAIL " + (error && error.stack || error) + "\n" + checks.join("\n") + "\nstats: " + stats +
            "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                               source/v64/tests/glbridge/svga_share_browser_test.html                                              0000644 0000000 0000000 00000014664 00000000000 020432  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II: surfaces legacy 3D and DX share</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A D3D9 app on Windows draws with legacy SVGA3D commands (D9WG) and DWM
// composes with DX (GX), and they share surfaces: the app's picture is copied
// into DWM's, and the app draws over what DX drew. The device keeps such a
// surface in both executors and copies it between them on the GPU
// (GX SURFACE_IMPORT and SURFACE_EXPORT) when the other side needs it.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));
        const pixel = (mob, x, y) => Array.from(mobs.get(mob).subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4)).join();

        // APP: the D3D9 app's back buffer (X8R8G8B8); WIN: DWM's surface for
        // its window (B8G8R8A8), which DWM draws with DX
        const APP = 20, WIN = 21, CID = 1, LEGACY = 5;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        mobs.set(2, new Uint8Array(64 * 64 * 4));
        const BIND_RT = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, APP, C.SVGA3D_SURFACE_HINT_RENDERTARGET, C.SVGA3D_X8R8G8B8, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, WIN, BIND_RT, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, APP, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, WIN, 2);

        // DWM clears its surface red
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, WIN, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(1), f32(0), f32(0), f32(1));

        // the app clears its back buffer green (alpha 0: an X format's is
        // ignored) and presents: a copy of its top left quarter into DWM's
        run(C.SVGA_3D_CMD_CONTEXT_DEFINE, LEGACY);
        run(C.SVGA_3D_CMD_SETRENDERTARGET, LEGACY, C.SVGA3D_RT_COLOR0, APP, 0, 0);
        run(C.SVGA_3D_CMD_CLEAR, LEGACY, C.SVGA3D_CLEAR_COLOR, 0x0000FF00, f32(1), 0);
        run(C.SVGA_3D_CMD_SURFACE_COPY, APP, 0, 0, WIN, 0, 0, 0, 0, 0, 32, 32, 1, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, WIN, 0);
        await finished();
        check(pixel(2, 8, 8) === "0,255,0,255", "the app's picture reached DWM's surface, opaque (" + pixel(2, 8, 8) + ")");
        check(pixel(2, 56, 56) === "0,0,255,255", "and the rest is DWM's red (" + pixel(2, 56, 56) + ")");

        // now the app draws into DWM's surface: a blue clear of its top
        // right quarter, over what DX drew
        run(C.SVGA_3D_CMD_SETRENDERTARGET, LEGACY, C.SVGA3D_RT_COLOR0, WIN, 0, 0);
        run(C.SVGA_3D_CMD_CLEAR, LEGACY, C.SVGA3D_CLEAR_COLOR, 0xFF0000FF, f32(1), 0, 32, 0, 32, 32);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, WIN, 0);
        await finished();
        check(pixel(2, 48, 8) === "255,0,0,255", "legacy 3D drew into DWM's surface (" + pixel(2, 48, 8) + ")");
        check(pixel(2, 8, 8) === "0,255,0,255", "over what was there: the copy (" + pixel(2, 8, 8) + ")");
        check(pixel(2, 56, 56) === "0,0,255,255", "and DX's clear (" + pixel(2, 56, 56) + ")");

        // and DWM draws on: a DX clear sees the app's blue first
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 1, WIN, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 1);
        run(C.SVGA_3D_CMD_DX_PRED_COPY_REGION, WIN, 0, APP, 0, 0, 56, 0, 8, 8, 1, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, WIN, 0);
        await finished();
        check(pixel(2, 48, 8) === "255,0,0,255", "the app's blue is in GX's copy too (" + pixel(2, 48, 8) + ")");
        check(pixel(2, 4, 60) === "0,255,0,255", "and a DX copy from the app's back buffer (" + pixel(2, 4, 60) + ")");
        check(renderer.gx, "GX made on the D3D9 executor's device");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU|d3d9/i.test(w));
        check(!warnings.length, "no warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                            source/v64/tests/glbridge/svga_so_browser_test.html                                                 0000644 0000000 0000000 00000026441 00000000000 017745  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: stream output and DrawAuto</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// Stream output through GX: a triangle's vertices, as the vertex shader made
// them, written into a buffer by GX's ordered compute pass; read back; then
// drawn again from that buffer with DrawAuto, which takes its vertex count
// from the filled size GX keeps on the GPU. Then the same with a geometry
// shader that makes a quad of a point: two triangles captured.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

// a VGPU10 assembler: just what these shaders need
const OPERAND = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, CONSTANT_BUFFER: 8 };
const operand = (type, indices, mask) => [(2 | (mask === undefined ? 15 : mask) << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const swizzled = (type, indices) => [(2 | 1 << 2 | 0xE4 << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const program = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 4 << 4, 2 + body.length, ...body]); };
const DCL_INPUT = 95, DCL_OUTPUT = 101, DCL_OUTPUT_SIV = 103, DCL_CONSTANT_BUFFER = 89, MOV = 54, RET = 62;
const ADD = 0, UTOF = 86, MUL = 56, EMIT = 19;
const DCL_GS_INPUT_PRIMITIVE = 93, DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY = 92, DCL_MAX_OUTPUT_VERTEX_COUNT = 94;
const INPUT_PRIMITIVEID = 11;
const imm = (...values) => [(2 | OPERAND.IMMEDIATE32 << 12) >>> 0, ...values.map(f32)];
const selected = (type, indices, lane) => [(2 | 2 << 2 | lane << 4 | type << 12 | indices.length << 20) >>> 0, ...indices];
// VS: the position from the input layout, as it is
const VS = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0])),
    ins(RET));
// VS2: the position moved right by 1
const VS2 = program(1,
    ins(DCL_INPUT, operand(OPERAND.INPUT, [0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ins(ADD, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0]), imm(1, 0, 0, 0)),
    ins(RET));
// GS: a point into a quad of half size 0.25
const corner = (dx, dy) => [ins(ADD, operand(OPERAND.OUTPUT, [0]), swizzled(OPERAND.INPUT, [0, 0]), imm(dx, dy, 0, 0)), ins(EMIT)];
const GS = program(2,
    insc(DCL_GS_INPUT_PRIMITIVE, 1),
    insc(DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY, 5),
    ins(DCL_MAX_OUTPUT_VERTEX_COUNT, 4),
    ins(DCL_INPUT, operand(OPERAND.INPUT, [1, 0])),
    ins(DCL_OUTPUT_SIV, operand(OPERAND.OUTPUT, [0]), 1),
    ...corner(-0.25, -0.25), ...corner(-0.25, 0.25), ...corner(0.25, -0.25), ...corner(0.25, 0.25),
    ins(RET));
// PS: white
const PS = program(0,
    ins(DCL_OUTPUT, operand(OPERAND.OUTPUT, [0])),
    ins(MOV, operand(OPERAND.OUTPUT, [0]), imm(1, 1, 1, 1)),
    ins(RET));

(async () => {
    try {
        // MOBs: plain arrays
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx10",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };

        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaRenderer = renderer;
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        // MOB 1: the 64x64 target; 2: the triangle's vertices; 3: the stream
        // output buffer; 4: the shaders
        const RT = 10, VB = 11, SOB = 12;
        mobs.set(1, new Uint8Array(64 * 64 * 4));
        const triangle = [-1, -1, 0, 1, -1, 0, 0, 1, 0, -1, 0, 1];
        mobs.set(2, new Uint8Array(new Float32Array(triangle).buffer));
        mobs.set(3, new Uint8Array(256));
        const shaders = new Uint8Array(8192);
        [VS, VS2, GS, PS].forEach((code, i) => shaders.set(new Uint8Array(code.buffer), 1024 * i));
        mobs.set(4, shaders);
        const BIND_RT = C.SVGA3D_SURFACE_BIND_RENDER_TARGET | C.SVGA3D_SURFACE_BIND_SHADER_RESOURCE;
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, BIND_RT, C.SVGA3D_B8G8R8A8_UNORM, 1, 0, 0, 64, 64, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 48, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, SOB, C.SVGA3D_SURFACE_BIND_STREAM_OUTPUT | C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER,
            C.SVGA3D_BUFFER, 1, 0, 0, 256, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, SOB, 3);

        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, C.SVGA3D_B8G8R8A8_UNORM, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32B32A32_FLOAT, 0, 0, 0);
        [[1, C.SVGA3D_SHADERTYPE_VS, VS], [2, C.SVGA3D_SHADERTYPE_VS, VS2], [3, C.SVGA3D_SHADERTYPE_GS, GS], [4, C.SVGA3D_SHADERTYPE_PS, PS]]
            .forEach(([id, type, code], i) => {
                run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, id, type, code.byteLength);
                run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, id, 4, 1024 * i);
            });
        // the declaration: register 0 (the position), all of it, into buffer 0, 16 bytes a vertex
        const decls = new Array(64 * 4).fill(0);
        decls.splice(0, 4, 0, 0, 0xF, 0);
        run(C.SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT, 0, 1, ...decls, 16, 0, 0, 0, 0);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 4, C.SVGA3D_SHADERTYPE_PS);
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 16, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_TRIANGLELIST);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(64), f32(64), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_SOTARGETS, 0, SOB, 0, 256);
        run(C.SVGA_3D_CMD_DX_DRAW, 3, 0);
        // no more stream output; the captured triangle drawn again, moved right
        run(C.SVGA_3D_CMD_DX_SET_SOTARGETS, 0, 0xFFFFFFFF, 0, 0);
        run(C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT, 0xFFFFFFFF);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 2, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, SOB, 16, 0);
        run(C.SVGA_3D_CMD_DX_DRAW_AUTO);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, SOB, 0);
        await finished();
        const gx = renderer.gx;
        check(gx && gx.stats.streamOutputs === 1, "one stream output pass (" + JSON.stringify(gx && gx.stats) + ")");
        const captured = Array.from(new Float32Array(mobs.get(3).buffer, 0, 12));
        check(captured.join() === triangle.join(), "the buffer has the triangle's three positions: " + captured);
        const target = mobs.get(1);
        const pixel = (x, y) => Array.from(target.subarray((y * 64 + x) * 4, (y * 64 + x) * 4 + 4));
        // the triangle covers the lower left; moved right by 1 (32 pixels), the lower middle
        check(pixel(10, 56).join() === "255,255,255,255", "the first draw (" + pixel(10, 56) + ")");
        check(pixel(42, 56).join() === "255,255,255,255", "DrawAuto drew the captured triangle, moved right (" + pixel(42, 56) + ")");
        check(pixel(60, 10).join() === "0,0,0,255", "and nothing else (" + pixel(60, 10) + ")");

        // with a geometry shader: a point's quad, two triangles, appended after the first
        mobs.set(2, new Uint8Array(new Float32Array([0, 0, 0, 1, ...new Array(8).fill(0)]).buffer));
        run(C.SVGA_3D_CMD_UPDATE_GB_SURFACE, VB);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 1, C.SVGA3D_SHADERTYPE_VS);
        run(C.SVGA_3D_CMD_DX_SET_SHADER, 3, C.SVGA3D_SHADERTYPE_GS);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 16, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_POINTLIST);
        run(C.SVGA_3D_CMD_DX_SET_STREAMOUTPUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_SOTARGETS, 0, SOB, 0xFFFFFFFF, 256);
        run(C.SVGA_3D_CMD_DX_DRAW, 1, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, SOB, 0);
        await finished();
        const all = Array.from(new Float32Array(mobs.get(3).buffer, 0, 36));
        // (strip triangle 1 is (v2, v1, v3): odd triangles swap their first two, D3D's and GL's order)
        const quad = [[-0.25, -0.25], [-0.25, 0.25], [0.25, -0.25], [0.25, -0.25], [-0.25, 0.25], [0.25, 0.25]];
        check(all.slice(0, 12).join() === triangle.join(), "appended: the first triangle stays");
        check(quad.every(([x, y], i) => all[12 + 4 * i] === x && all[13 + 4 * i] === y && all[15 + 4 * i] === 1),
            "after it the quad's two triangles, strip winding kept: " + all.slice(12).join());

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                               source/v64/tests/glbridge/svga_tess_browser_test.html                                               0000644 0000000 0000000 00000025115 00000000000 020277  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VMware SVGA II DX: tessellation</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// A quad patch of four control points through the hull shader (control
// point, fork and join phases: tess factors 4, inside 4 and 3), the D3D11
// tessellator and a domain shader that places each point bilinearly between
// the control points and colours it by its (u, v). The square they span is
// filled, its colour the domain location: red grows to the right, green
// downwards.
import * as C from "../../src/graphics_adapters/vmware_svga/svga_constants.js";
import { SVGA3D } from "../../src/graphics_adapters/vmware_svga/svga3d.js";
import { ScreenObjects } from "../../src/graphics_adapters/vmware_svga/svga_screens.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

const T = { TEMP: 0, INPUT: 1, OUTPUT: 2, IMMEDIATE32: 4, OUTPUT_CONTROL_POINT_ID: 22, INPUT_CONTROL_POINT: 25, INPUT_PATCH_CONSTANT: 27, INPUT_DOMAIN_POINT: 28 };
const tok = (type, indices, sel, neg) => {
    const words = [(sel | type << 12 | indices.length << 20 | (neg ? 1 << 31 : 0)) >>> 0];
    if(neg) words.push(1 | 1 << 6);
    return [...words, ...indices];
};
const mask = m => 2 | m << 4, swz = (x, y, z, w) => 2 | 1 << 2 | (x | y << 2 | z << 4 | w << 6) << 4, one = c => 2 | 2 << 2 | c << 4;
const XYZW = swz(0, 1, 2, 3);
const ins = (op, ...operands) => { const body = operands.flat(); return [(op | (1 + body.length) << 24) >>> 0, ...body]; };
const insc = (op, controls, ...operands) => { const body = operands.flat(); return [(op | controls << 11 | (1 + body.length) << 24) >>> 0, ...body]; };
const imm = (...values) => [(values.length === 4 ? 2 : 1) | T.IMMEDIATE32 << 12, ...values.map(f32)];
const prog = (type, ...code) => { const body = code.flat(); return new Uint32Array([type << 16 | 5 << 4, 2 + body.length, ...body]); };
const OP = { ADD: 0, MAD: 50, MOV: 54, RET: 62, DCL_INPUT: 95, DCL_OUTPUT: 101, DCL_OUTPUT_SIV: 103, DCL_TEMPS: 104,
    HS_DECLS: 113, HS_CP: 114, HS_FORK: 115, HS_JOIN: 116, DCL_ICP: 147, DCL_OCP: 148, DCL_DOMAIN: 149, DCL_PARTITIONING: 150,
    DCL_PRIMITIVE: 151, DCL_MAX_TF: 152, DCL_FORK_COUNT: 153 };
const icp = (cp, reg, sel, neg) => tok(T.INPUT_CONTROL_POINT, [cp, reg], sel === undefined ? XYZW : sel, neg);
const dom = sel => tok(T.INPUT_DOMAIN_POINT, [], sel);
const r = (i, sel, neg) => tok(T.TEMP, [i], sel, neg);
const o = (i, sel) => tok(T.OUTPUT, [i], sel);

// VS: the control point's position
const VS = prog(1,
    ins(OP.DCL_INPUT, tok(T.INPUT, [0], mask(3))),
    ins(OP.DCL_OUTPUT, o(0, mask(15))),
    ins(OP.MOV, o(0, mask(3)), tok(T.INPUT, [0], XYZW)),
    ins(OP.MOV, o(0, mask(12)), imm(0, 0, 0, 1)),
    ins(OP.RET));
// HS: control points through vicp[vOutputControlPointID]; edges 4, inside 4 x 3
const icpByID = [(2 | 1 << 2 | 0xE4 << 4 | T.INPUT_CONTROL_POINT << 12 | 2 << 20 | 2 << 22) >>> 0, ...tok(T.OUTPUT_CONTROL_POINT_ID, [], one(0)), 0];
const HS = prog(3,
    ins(OP.HS_DECLS),
    insc(OP.DCL_ICP, 4), insc(OP.DCL_OCP, 4), insc(OP.DCL_DOMAIN, 3), insc(OP.DCL_PARTITIONING, 1), insc(OP.DCL_PRIMITIVE, 3),
    ins(OP.DCL_MAX_TF, f32(64)),
    ins(OP.HS_CP),
    ins(OP.DCL_INPUT, icp(4, 0, mask(15))),
    ins(OP.DCL_INPUT, tok(T.OUTPUT_CONTROL_POINT_ID, [], 0)),
    ins(OP.DCL_OUTPUT, o(0, mask(15))),
    ins(OP.MOV, o(0, mask(15)), icpByID),
    ins(OP.RET),
    ins(OP.HS_FORK),
    ins(OP.DCL_FORK_COUNT, 1),
    ...[0, 1, 2, 3].map(i => ins(OP.DCL_OUTPUT_SIV, o(i, mask(1)), 11 + i)),
    ...[0, 1, 2, 3].map(i => ins(OP.MOV, o(i, mask(1)), imm(4))),
    ins(OP.RET),
    ins(OP.HS_JOIN),
    ins(OP.DCL_OUTPUT_SIV, o(4, mask(1)), 15),
    ins(OP.DCL_OUTPUT_SIV, o(5, mask(1)), 16),
    ins(OP.MOV, o(4, mask(1)), imm(4)),
    ins(OP.MOV, o(5, mask(1)), imm(3)),
    ins(OP.RET));
// DS: bilinear between the corners (0 top left, 1 top right, 2 bottom right, 3 bottom left); colour (u, v)
const DS = prog(4,
    insc(OP.DCL_ICP, 4), insc(OP.DCL_DOMAIN, 3),
    ins(OP.DCL_INPUT, dom(mask(3))),
    ins(OP.DCL_INPUT, icp(4, 0, mask(3))),
    ins(OP.DCL_OUTPUT_SIV, o(0, mask(15)), 1),
    ins(OP.DCL_OUTPUT, o(1, mask(15))),
    ins(OP.DCL_TEMPS, 2),
    ins(OP.ADD, r(0, mask(3)), icp(0, 0, XYZW, true), icp(1, 0)),
    ins(OP.MAD, r(0, mask(3)), dom(swz(0, 0, 0, 0)), r(0, XYZW), icp(0, 0)),
    ins(OP.ADD, r(1, mask(3)), icp(3, 0, XYZW, true), icp(2, 0)),
    ins(OP.MAD, r(1, mask(3)), dom(swz(0, 0, 0, 0)), r(1, XYZW), icp(3, 0)),
    ins(OP.ADD, r(1, mask(3)), r(0, XYZW, true), r(1, XYZW)),
    ins(OP.MAD, o(0, mask(3)), dom(swz(1, 1, 1, 1)), r(1, XYZW), r(0, XYZW)),
    ins(OP.MOV, o(0, mask(12)), imm(0, 0, 0, 1)),
    ins(OP.MOV, o(1, mask(3)), dom(XYZW)),
    ins(OP.MOV, o(1, mask(12)), imm(0, 0, 0, 1)),
    ins(OP.RET));
const PS = new Uint32Array([0 << 16 | 4 << 4, 0, ...[
    ins(98 /* DCL_INPUT_PS */, tok(T.INPUT, [1], mask(15))).map((w, i) => i === 0 ? (w | 2 << 11) >>> 0 : w),
    ins(OP.DCL_OUTPUT, o(0, mask(15))),
    ins(OP.MOV, o(0, mask(15)), tok(T.INPUT, [1], XYZW)),
    ins(OP.RET)].flat()]);
PS[1] = PS.length;

(async () => {
    try {
        const mobs = new Map();
        const mob_table = {
            read: (id, offset, length) => { const m = mobs.get(id); return m && offset + length <= m.length ? m.slice(offset, offset + length) : null; },
            write: (id, offset, bytes) => { const m = mobs.get(id); if(!m || offset + bytes.length > m.length) return false; m.set(bytes, offset); return true; },
            size: id => mobs.has(id) ? mobs.get(id).length : -1,
        };
        const screens = new ScreenObjects({ read: () => null, write: () => false });
        const device = { caps: C.SVGA_CAP_3D | C.SVGA_CAP_GBOBJECTS | C.SVGA_CAP_DX, level: "dx11",
            gmrs: { read: () => null, write: () => false }, mobs: mob_table, otables: null, screens,
            set_irq: () => {}, svga_active: () => false };
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        globalThis.svgaWarnings = [];
        for(const method of ["warn", "error"])
        {
            const original = console[method];
            console[method] = (...args) => { globalThis.svgaWarnings.push(args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")); original.apply(console, args); };
        }
        const svga3d = new SVGA3D(device, end(0, 1));
        const run = (id, ...body) => svga3d.command(id, Int32Array.from(body, v => v | 0));
        const finished = () => new Promise(resolve => svga3d.after_work(resolve));

        const RT = 10, VB = 11, U8 = C.SVGA3D_R8G8B8A8_UNORM, SIZE = 64;
        mobs.set(1, new Uint8Array(SIZE * SIZE * 4));
        mobs.set(2, new Uint8Array(new Float32Array([-0.75, 0.75, 0.75, 0.75, 0.75, -0.75, -0.75, -0.75]).buffer));
        const shaders = new Uint8Array(8192);
        [VS, HS, DS, PS].forEach((s, i) => shaders.set(new Uint8Array(s.buffer), i * 2048));
        mobs.set(3, shaders);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, RT, C.SVGA3D_SURFACE_BIND_RENDER_TARGET, U8, 1, 0, 0, SIZE, SIZE, 1, 1, 0);
        run(C.SVGA_3D_CMD_DEFINE_GB_SURFACE_V2, VB, C.SVGA3D_SURFACE_BIND_VERTEX_BUFFER, C.SVGA3D_BUFFER, 1, 0, 0, 32, 1, 1, 1, 0);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, RT, 1);
        run(C.SVGA_3D_CMD_BIND_GB_SURFACE, VB, 2);
        const CID = 1;
        run(C.SVGA_3D_CMD_DX_DEFINE_CONTEXT, CID);
        svga3d.dx_context = CID;
        run(C.SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW, 0, RT, U8, C.SVGA3D_RESOURCE_TEXTURE2D, 0, 0, 1);
        run(C.SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT, 0, 0, 0, C.SVGA3D_R32G32_FLOAT, 0, 0, 0);
        // solid, no culling, depth clip
        run(C.SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE, 0, 3 | 1 << 8, 0, 0, 0, 1, f32(1), 0);
        const types = [C.SVGA3D_SHADERTYPE_VS, C.SVGA3D_SHADERTYPE_HS, C.SVGA3D_SHADERTYPE_DS, C.SVGA3D_SHADERTYPE_PS];
        [VS, HS, DS, PS].forEach((s, i) => {
            run(C.SVGA_3D_CMD_DX_DEFINE_SHADER, i + 1, types[i], s.byteLength);
            run(C.SVGA_3D_CMD_DX_BIND_SHADER, CID, i + 1, 3, i * 2048);
            run(C.SVGA_3D_CMD_DX_SET_SHADER, i + 1, types[i]);
        });
        run(C.SVGA_3D_CMD_DX_SET_INPUT_LAYOUT, 0);
        run(C.SVGA_3D_CMD_DX_SET_RASTERIZER_STATE, 0);
        run(C.SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS, 0, VB, 8, 0);
        run(C.SVGA_3D_CMD_DX_SET_TOPOLOGY, C.SVGA3D_PRIMITIVE_4_CONTROL_POINT_PATCH);
        run(C.SVGA_3D_CMD_DX_SET_RENDERTARGETS, 0xFFFFFFFF, 0);
        run(C.SVGA_3D_CMD_DX_SET_VIEWPORTS, 0, f32(0), f32(0), f32(SIZE), f32(SIZE), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW, 0, f32(0), f32(0), f32(0), f32(1));
        run(C.SVGA_3D_CMD_DX_DRAW, 4, 0);
        run(C.SVGA_3D_CMD_DX_READBACK_SUBRESOURCE, RT, 0);
        await finished();
        const gx = renderer.gx;
        check(gx && gx.stats.tessellatedDraws === 1, "one tessellated draw (" + JSON.stringify(gx && gx.stats) + ")");
        const out = mobs.get(1);
        const pixel = (x, y) => Array.from(out.subarray((y * SIZE + x) * 4, (y * SIZE + x) * 4 + 4));
        const centre = pixel(32, 32), left = pixel(12, 32), right = pixel(51, 32), top = pixel(32, 12), bottom = pixel(32, 51);
        check(Math.abs(centre[0] - 128) < 8 && Math.abs(centre[1] - 128) < 8, "the centre is (u, v) = (0.5, 0.5): " + centre);
        check(left[0] < 40 && right[0] > 215, "u grows to the right: " + left + " / " + right);
        check(top[1] < 40 && bottom[1] > 215, "v grows downwards: " + top + " / " + bottom);
        check(pixel(2, 2).join() === "0,0,0,255" && pixel(61, 61).join() === "0,0,0,255", "outside the square: the clear colour");
        // every pixel inside is covered: no cracks between the tessellated triangles
        let holes = 0;
        for(let y = 10; y < 54; y++) for(let x = 10; x < 54; x++) if(pixel(x, y)[3] === 255 && pixel(x, y)[0] + pixel(x, y)[1] === 0 && (x > 10 || y > 10)) holes++;
        check(holes === 0, "no holes inside (" + holes + ")");

        const warnings = globalThis.svgaWarnings.filter(w => /\[gx\]|WGSL|WebGPU/.test(w));
        check(!warnings.length, "no GX warnings: " + warnings.join(" / "));
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n") + "\nwarnings: " + (globalThis.svgaWarnings || []).join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/glbridge/svga_trace_replay_browser_test.html                                       0000644 0000000 0000000 00000013751 00000000000 021776  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>GPU trace replay</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
// Run a GPU trace (tests/x64/gpu_trace.mjs) through the renderer of the
// VMware SVGA II adapter on a real GPU, without the guest that made it:
//
//   GL_TIMEOUT_MS=600000 node tests/glbridge/gl_multipass_browser_runner.js \
//       'svga_trace_replay_browser_test.html?trace=build/x64-linux/gpu-vmware_svga-vgpu9/trace.bin'
//
// It fails on commands the executor could not run, and saves the last
// picture each read back texture had (what the guest presented, mostly) as
// build/browser-test-output/trace-<texture>.png.
const RESPONSE_REGION_OFFSET = 12 << 20;
const result = document.getElementById("result");

(async () => {
    const warnings = new Map();
    for(const method of ["warn", "error"])
    {
        const original = console[method];
        console[method] = (...args) => {
            const text = args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ").slice(0, 300);
            warnings.set(text, (warnings.get(text) || 0) + 1);
            original.apply(console, args);
        };
    }
    try {
        const parameters = new URLSearchParams(location.search);
        const response = await fetch("../../" + parameters.get("trace"));
        if(!response.ok) throw new Error("no trace at " + parameters.get("trace"));
        const bytes = new Uint8Array(await response.arrayBuffer());
        if(new TextDecoder().decode(bytes.subarray(0, 8)) !== "V86GTRC1") throw new Error("not a GPU trace");
        const view = new DataView(bytes.buffer);
        let note = null;
        const batches = [];
        for(let at = 8; at + 8 <= bytes.length;)
        {
            const type = view.getUint32(at, true), length = view.getUint32(at + 4, true);
            if(type === 2) note = JSON.parse(new TextDecoder().decode(bytes.subarray(at + 8, at + 8 + length)));
            if(type === 1) batches.push(bytes.subarray(at + 8, at + 8 + length));
            at += 8 + length;
        }

        // what each readback is of, from its command
        const requests = new Map();
        const pictures = new Map();
        let device = null;
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = V86SVGARenderer(end(1, 0), {});
        let done = 0;
        end(0, 1).listen(message => {
            if(message.type === "done") done = message.seq;
            if(message.type !== "write" || message.offset < 16384) return;
            const answer = new DataView(message.bytes.buffer, message.bytes.byteOffset);
            const request = requests.get(answer.getUint32(0, true));
            if(!request || answer.getUint32(12, true) !== 1 || request.pitch !== request.width * 4) return;
            let picture = pictures.get(request.texture);
            if(!picture || picture.width !== request.width || picture.height !== request.height)
            {
                picture = { width: request.width, height: request.height, rgba: new Uint8ClampedArray(request.width * request.height * 4) };
                pictures.set(request.texture, picture);
            }
            const rows = message.bytes.subarray(16);
            for(let i = 0; i < request.rows * request.width; i++)
            {
                const t = (request.first * request.width + i) * 4, s = i * 4;
                picture.rgba[t] = rows[s + 2]; picture.rgba[t + 1] = rows[s + 1]; picture.rgba[t + 2] = rows[s]; picture.rgba[t + 3] = 255;
            }
        });
        const started = performance.now();
        for(let i = 0; i < batches.length; i++)
        {
            const batch = batches[i], v = new DataView(batch.buffer, batch.byteOffset, batch.byteLength);
            for(let at = 32; at < 32 + v.getUint32(20, true);)
            {
                const size = v.getUint32(at + 4, true), p = at + 16;
                if(v.getUint16(at, true) === 12)
                {
                    requests.set(v.getUint32(p + 44, true), { texture: v.getUint32(p + 4, true), width: v.getUint32(p + 16, true),
                        height: v.getUint32(p + 20, true), first: v.getUint32(p + 24, true), rows: v.getUint32(p + 28, true),
                        pitch: v.getUint32(p + 32, true) });
                }
                at += size;
            }
            end(0, 1).post({ type: "submit", seq: i + 1, bytes: batch.slice() });
            // keep a bounded number in flight
            if(i - done > 32) await renderer.idle();
        }
        await renderer.idle();
        const seconds = (performance.now() - started) / 1000;

        for(const [texture, picture] of pictures)
        {
            const canvas = new OffscreenCanvas(picture.width, picture.height);
            canvas.getContext("2d").putImageData(new ImageData(picture.rgba, picture.width, picture.height), 0, 0);
            const png = await canvas.convertToBlob({ type: "image/png" });
            await fetch("/__test_file?name=trace-" + texture + ".png", { method: "POST", body: png });
        }
        const stats = renderer.executor.stats;
        const summary = Object.entries(stats).filter(([, v]) => v).map(([k, v]) => k + "=" + v).join(" ");
        const lines = [
            "trace: " + JSON.stringify(note) + ", " + batches.length + " batches in " + seconds.toFixed(1) + " s",
            "pictures: " + [...pictures.keys()].map(t => "trace-" + t + ".png").join(" "),
            "stats: " + summary,
            "warnings:", ...[...warnings].map(([text, count]) => "  " + count + "x " + text),
        ];
        const failed = stats.commandsFailed || stats.malformedBatches || stats.droppedDraws;
        result.textContent = (failed ? "FAIL " : "PASS ") + lines.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error && error.stack || error) + "\nwarnings:\n" + [...warnings.keys()].join("\n");
    }
})();
</script>
                       source/v64/tests/glbridge/tessellator_browser_test.html                                             0000644 0000000 0000000 00000016342 00000000000 020644  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>The D3D11 tessellator on the GPU</title>
<pre id="result">RUNNING</pre>
<script src="../../src/browser/glbridge/gx/tessellator.js"></script>
<script src="../../src/browser/glbridge/gx/tessellator_wgsl.js"></script>
<script type="module">
// GX's tessellator in WGSL (tessellator_wgsl.js) against the JavaScript port
// it mirrors (tessellator.js, itself checked against Microsoft's reference):
// batches of patches with random tess factors, for every domain,
// partitioning and output primitive, must give the same points (u, v,
// patch) and indices.
const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const { tessellate } = globalThis.V86Tessellator;
const { TESSELLATOR_WGSL } = globalThis.V86TessellatorWGSL;

(async () => {
    try {
        const adapter = await navigator.gpu.requestAdapter();
        const device = await adapter.requestDevice();
        const module = device.createShaderModule({ code: TESSELLATOR_WGSL });
        const info = await module.getCompilationInfo();
        const errors = info.messages.filter(m => m.type === "error");
        check(!errors.length, "the WGSL compiles" + (errors.length ? ": " + errors.map(e => e.lineNum + ": " + e.message).join("; ") : ""));
        const layout = device.createBindGroupLayout({ entries: [
            { binding: 0, visibility: 4, buffer: { type: "uniform" } },
            { binding: 1, visibility: 4, buffer: { type: "read-only-storage" } },
            ...[2, 3, 4, 5, 6].map(binding => ({ binding, visibility: 4, buffer: { type: "storage" } })),
        ] });
        const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [layout] });
        const pipeline = entryPoint => device.createComputePipeline({ layout: pipelineLayout, compute: { module, entryPoint } });
        const count = pipeline("count"), scan = pipeline("scan"), generate = pipeline("generate");

        let seed = 777;
        const rand = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
        const pick = () => { const r = rand(); return r < 0.2 ? Math.ceil(rand() * 8) : r < 0.3 ? rand() * 70 : r < 0.35 ? 1 : r < 0.37 ? 0 : rand() * 12 + 0.5; };
        const PATCHES = 48, MAX_POINTS = PATCHES * 4500, MAX_INDICES = PATCHES * 26000;
        const STORAGE = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
        let batches = 0, totalPatches = 0;
        for(let domain = 1; domain <= 3; domain++)
        for(let partitioning = 1; partitioning <= 4; partitioning++)
        for(let primitive = 1; primitive <= (domain === 1 ? 2 : 4); primitive++)
        {
            const n = domain === 3 ? 6 : domain === 2 ? 4 : 2;
            const factors = Array.from({ length: PATCHES }, () => Array.from({ length: n }, pick).map(Math.fround));
            // the hull records: two vec4s of factors each
            const hull = new Float32Array(PATCHES * 8);
            factors.forEach((f, i) => hull.set(f, i * 8));
            const params = new Uint32Array([PATCHES, domain, partitioning, primitive, 2, 0, MAX_POINTS, MAX_INDICES]);
            const buffer = (data, size, usage) => {
                const b = device.createBuffer({ size: size || data.byteLength, usage });
                if(data) device.queue.writeBuffer(b, 0, data);
                return b;
            };
            const uniform = buffer(params, 0, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
            const hullBuffer = buffer(hull, 0, STORAGE);
            const counts = buffer(null, PATCHES * 8, STORAGE), offsets = buffer(null, PATCHES * 8, STORAGE);
            const points = buffer(null, MAX_POINTS * 16, STORAGE), indices = buffer(null, MAX_INDICES * 4, STORAGE);
            const args = buffer(null, 32, STORAGE | GPUBufferUsage.INDIRECT);
            const group = device.createBindGroup({ layout, entries: [uniform, hullBuffer, counts, offsets, points, indices, args]
                .map((b, binding) => ({ binding, resource: { buffer: b } })) });
            const encoder = device.createCommandEncoder();
            for(const [pipe, x] of [[count, Math.ceil(PATCHES / 64)], [scan, 1], [generate, Math.ceil(PATCHES / 64)]])
            {
                const pass = encoder.beginComputePass();
                pass.setPipeline(pipe);
                pass.setBindGroup(0, group);
                pass.dispatchWorkgroups(x);
                pass.end();
            }
            const read = [args, offsets, points, indices].map(b => {
                const r = device.createBuffer({ size: b.size, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
                encoder.copyBufferToBuffer(b, 0, r, 0, b.size);
                return r;
            });
            device.queue.submit([encoder.finish()]);
            await Promise.all(read.map(r => r.mapAsync(GPUMapMode.READ)));
            const [gotArgs, gotOffsets, gotPoints, gotIndices] = [
                new Uint32Array(read[0].getMappedRange()), new Uint32Array(read[1].getMappedRange()),
                new Uint32Array(read[2].getMappedRange()), new Uint32Array(read[3].getMappedRange())];
            const pointsF = new Float32Array(gotPoints.buffer);
            // the reference, patch by patch
            let pointBase = 0, indexBase = 0;
            for(let p = 0; p < PATCHES; p++)
            {
                const ref = tessellate({ domain, partitioning, primitive, factors: factors[p] });
                const where = `domain ${domain} partitioning ${partitioning} primitive ${primitive} patch ${p} factors ${factors[p].map(f => f.toFixed(3))}`;
                if(gotOffsets[p * 2] !== pointBase || gotOffsets[p * 2 + 1] !== indexBase)
                    throw new Error("offsets " + gotOffsets[p * 2] + "/" + gotOffsets[p * 2 + 1] + " vs " + pointBase + "/" + indexBase + ": " + where);
                for(let i = 0; i < ref.points.length / 2; i++)
                {
                    const at = (pointBase + i) * 4;
                    if(pointsF[at] !== ref.points[i * 2] || pointsF[at + 1] !== ref.points[i * 2 + 1] || gotPoints[at + 2] !== p)
                        throw new Error(`point ${i}: ${pointsF[at]},${pointsF[at + 1]} vs ${ref.points[i * 2]},${ref.points[i * 2 + 1]}: ` + where);
                }
                for(let i = 0; i < ref.indices.length; i++)
                {
                    if(gotIndices[indexBase + i] !== pointBase + ref.indices[i])
                        throw new Error(`index ${i}: ${gotIndices[indexBase + i] - pointBase} vs ${ref.indices[i]}: ` + where);
                }
                pointBase += ref.points.length / 2;
                indexBase += ref.indices.length;
            }
            if(gotArgs[3] !== indexBase || gotArgs[7] !== pointBase) throw new Error("the indirect arguments: " + Array.from(gotArgs));
            read.forEach(r => r.unmap());
            batches++;
            totalPatches += PATCHES;
        }
        check(batches === 4 * 2 + 2 * 4 * 4, batches + " batches (" + totalPatches + " patches) match the reference, points and indices");
        result.textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        result.textContent = "FAIL " + (error.stack || error) + "\n" + checks.join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                              source/v64/tests/glbridge/tessellator_test.js                                                       0000644 0000000 0000000 00000006141 00000000000 016545  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The D3D11 tessellator's port (src/browser/glbridge/gx/tessellator.js)
// against Microsoft's reference: for each case, the number of points and
// indices and a checksum of both, as the reference (CHWTessellator from
// Mesa's src/gallium/auxiliary/tessellator, built natively) gave them.
// tessellator_browser_test.html checks the WGSL port against this one.
"use strict";

const assert = require("assert/strict");
const { tessellate } = require("../../src/browser/glbridge/gx/tessellator.js");

// domain (1 isoline, 2 tri, 3 quad), partitioning (1 integer, 2 pow2,
// 3 fractional_odd, 4 fractional_even), primitive (1 point, 2 line,
// 3 triangle_cw, 4 triangle_ccw), tess factors, points, indices, point
// checksum, index checksum
const CASES = [
    [3, 1, 3, [1, 1, 1, 1, 1, 1], 4, 6, 1572864, 30597376],
    [3, 1, 3, [4, 4, 4, 4, 4, 4], 25, 96, 28573696, 871542293],
    [3, 1, 4, [2, 3, 5, 7, 4, 6], 32, 135, 46323026, 864199540],
    [3, 3, 3, [3.3, 2.7, 5.1, 1.2, 4.4, 3.9], 34, 144, 49707327, 861807487],
    [3, 4, 3, [2.5, 6.2, 3.1, 9.7, 7.3, 2.2], 47, 198, 90441030, 195548004],
    [3, 2, 3, [64, 64, 64, 64, 64, 64], 4225, 24576, 465986526, 995813054],
    [3, 1, 1, [3, 2, 4, 5, 3, 2], 16, 16, 15106047, 474293891],
    [3, 4, 2, [2.2, 3.3, 4.4, 5.5, 6.6, 7.7], 69, 136, 181115218, 731816722],
    [3, 3, 3, [1, 1, 1, 1, 1.5, 1], 8, 30, 4172460, 388039772],
    [3, 1, 3, [0, 1, 1, 1, 1, 1], 0, 0, 0, 0],
    [2, 1, 3, [1, 1, 1, 1], 3, 3, 655360, 1026],
    [2, 1, 3, [5, 5, 5, 5], 27, 111, 20827342, 956385304],
    [2, 3, 4, [3.7, 2.1, 6.6, 4.9], 27, 111, 21809894, 102937995],
    [2, 4, 3, [2.5, 7.5, 4.25, 3.3], 25, 90, 18360395, 100074146],
    [2, 2, 3, [33, 17, 9, 64], 3036, 18033, 796911218, 355795131],
    [2, 3, 1, [4.4, 2.2, 3.3, 5.5], 40, 40, 42457966, 43791062],
    [2, 1, 2, [3, 4, 5, 6], 31, 60, 26727737, 790190988],
    [2, 4, 4, [63.9, 2, 2, 2], 69, 204, 74008150, 656067277],
    [1, 1, 2, [4, 3], 16, 24, 11905708, 603087170],
    [1, 3, 2, [2.5, 6.6], 24, 42, 23505606, 651174205],
    [1, 4, 1, [3, 7.7], 27, 27, 29171733, 643608609],
    [1, 1, 2, [64, 64], 4160, 8192, 568061947, 460932118],
    [1, 2, 1, [1, 1], 2, 2, 131072, 33],
    [1, 3, 2, [0, 5], 0, 0, 0, 0],
];

for (const [domain, partitioning, primitive, factors, points, indices, pointSum, indexSum] of CASES) {
    const r = tessellate({ domain, partitioning, primitive, factors });
    const where = `domain ${domain}, partitioning ${partitioning}, primitive ${primitive}, factors ${factors}`;
    assert.equal(r.points.length / 2, points, "points: " + where);
    assert.equal(r.indices.length, indices, "indices: " + where);
    let us = 0, idx = 0;
    for (let i = 0; i < points; i++) {
        us = (us + Math.round(r.points[i * 2] * 65536) * (i + 1) + Math.round(r.points[i * 2 + 1] * 65536) * (i + 7)) % 1000000007;
    }
    for (let i = 0; i < indices; i++) idx = (idx * 31 + r.indices[i] + 1) % 1000000007;
    assert.equal(us, pointSum, "the points: " + where);
    assert.equal(idx, indexSum, "the indices: " + where);
}
console.log("PASS: " + CASES.length + " tessellations match D3D11's reference (points, indices)");
                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/glbridge/v86_network_bridge_d3d8_route_test.js                                     0000644 0000000 0000000 00000010161 00000000000 021751  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

const assert = require("node:assert/strict");

require("../../src/browser/glbridge/v86_network_bridge.js");
const { V86WebGPUCompositor } = require("../../src/browser/glbridge/webgpu_compositor.js");

const listeners = Object.create(null);
const routed = [];
let d3d8Options;
const compositor = new V86WebGPUCompositor({ width: 1024, height: 768 });
const bridge = globalThis.installV86GLNetworkBridge({
    add_listener(name, callback) { listeners[name] = callback; },
}, null, {
    compositor,
    glExecutor: { submit() {}, onSwapBuffers() {} },
    installD3D8WebGPUExecutor(installedCanvas, options) {
        assert.equal(installedCanvas, bridge_d3d8Canvas());
        assert.equal(options.host, installedCanvas.layer.host, "the executor draws through its layer's host");
        d3d8Options = options;
        return {
            submit(bytes, metadata) { routed.push({ bytes: Buffer.from(bytes), metadata }); },
        };
    },
});
function bridge_d3d8Canvas() { return compositor.layers.find(layer => layer.name === "d3d8").canvas; }
const d3d8Layer = bridge.d3d8Canvas.layer, glLayer = bridge.glCanvas.layer;
const placed = layer => [layer.x, layer.y, layer.width, layer.height, layer.visible];

bridge.lastPresentedFrameId = 999;
const d8wg = Buffer.alloc(32);
d8wg.writeUInt32LE(0x47573844, 0);
d8wg.writeUInt16LE(1, 4);
d8wg.writeUInt16LE(7, 6);
d8wg.writeUInt32LE(0xA0010001, 24);
d8wg.writeUInt32LE(0x20260802, 28);
const envelope = Buffer.alloc(8 + d8wg.length);
envelope.writeUInt16LE(0xFFE0, 0);
envelope.writeUInt16LE(0xFFFF, 2);
envelope.writeUInt32LE(d8wg.length, 4);
d8wg.copy(envelope, 8);

bridge.pushPCIBatch({
    bytes: envelope,
    frameId: 1,
    submitCount: 7,
    commandCount: 1,
    flags: 0,
});

assert.equal(routed.length, 1,
    "D8WG routing must not be rejected by the OpenGL stale-frame counter");
assert.deepEqual(routed[0].bytes, d8wg);
assert.deepEqual(routed[0].metadata, {
    pciFrameId: 1,
    submitCount: 7,
    descriptorCommandCount: 1,
});

d3d8Options.onSurface({ hwnd: 0x1234, x: 10, y: 20, width: 640,
    height: 480, displayWidth: 640, displayHeight: 480, visible: true }, "create");
d3d8Options.onPresent({ hwnd: 0x1234, x: 10, y: 20, width: 640,
    height: 480, displayWidth: 640, displayHeight: 480, visible: true }, {});
assert.deepEqual(placed(d3d8Layer), [10, 20, 640, 480, true], "a presented window is a visible layer where the guest has it");
assert.equal(glLayer.visible, false);

d3d8Options.onSurface({ hwnd: 0x1234, x: 30, y: 40, width: 640,
    height: 480, displayWidth: 800, displayHeight: 600, visible: true }, "move");
assert.deepEqual(placed(d3d8Layer).slice(0, 4), [30, 40, 800, 600], "the layer follows the window");
d3d8Options.onPresent({ hwnd: 0x1234, x: 524, y: 40, width: 640,
    height: 480, displayWidth: 800, displayHeight: 600, visible: true }, {});
assert.deepEqual(placed(d3d8Layer), [524, 40, 800, 600, true]);
assert.deepEqual(d3d8Layer.clip, { left: 0, top: 0, right: 500 / 800, bottom: 1 },
    "the part of the window past the desktop's edge is clipped");

d3d8Options.onSurface({ hwnd: 0x1234, x: 0, y: 0, width: 640,
    height: 480, displayWidth: 800, displayHeight: 600, visible: false }, "hide");
assert.equal(d3d8Layer.visible, false, "a hidden window hides its layer");
d3d8Options.onPresent({ sessionKey: "new-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, {});
assert.equal(d3d8Layer.visible, true);

d3d8Options.onDestroy({ sessionKey: "old-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, "device");
assert.equal(d3d8Layer.visible, true,
    "late teardown from an old process session must not hide the new owner");
d3d8Options.onDestroy({ sessionKey: "new-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, "device");
assert.equal(d3d8Layer.visible, false);

bridge.showOwner("gl");
assert.equal(d3d8Layer.visible, false);
assert.equal(glLayer.visible, true, "one API's window at a time");

console.log("v86_network_bridge_d3d8_route_test: ok");
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/glbridge/v86_network_bridge_d3d9_route_test.js                                     0000644 0000000 0000000 00000023236 00000000000 021761  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

const assert = require("node:assert/strict");

require("../../src/browser/glbridge/v86_network_bridge.js");
const { V86WebGPUCompositor } = require("../../src/browser/glbridge/webgpu_compositor.js");

const listeners = Object.create(null);
const routed = [];
let d3d9Options;
const compositor = new V86WebGPUCompositor({ width: 1024, height: 768 });
/*
 * write_memory is modelled on v86's real one rather than just recording its
 * arguments, because the bug this guards against is invisible to a recorder:
 * v86 spells it write_memory(blob, address) -- the opposite order to
 * read_memory(address, length) -- and it bottoms out in mem8.set(blob, addr).
 * Called the other way round, TypedArray.set() gets a number as its source,
 * copies nothing and throws nothing. Every readback response and query answer
 * was being dropped exactly that way, and the guest could only report a
 * timeout.
 */
const guestMemory = new Uint8Array(4096);
const bridge = globalThis.installV86GLNetworkBridge({
    add_listener(name, callback) { listeners[name] = callback; },
    write_memory(blob, address) { guestMemory.set(blob, address); },
}, null, {
    compositor,
    glExecutor: { submit() {}, onSwapBuffers() {} },
    installD3D9WebGPUExecutor(installedCanvas, options) {
        assert.equal(installedCanvas.layer.name, "d3d9", "D3D9 draws into its own window layer");
        assert.equal(options.host, installedCanvas.layer.host);
        d3d9Options = options;
        return {
            submit(bytes, metadata) { routed.push({ bytes: Buffer.from(bytes), metadata }); },
        };
    },
});

const d3d9Layer = bridge.d3d9Canvas.layer, glLayer = bridge.glCanvas.layer;
const placed = layer => [layer.x, layer.y, layer.width, layer.height, layer.visible];

bridge.lastPresentedFrameId = 999;
const d9wg = Buffer.alloc(32);
d9wg.writeUInt32LE(0x47573944, 0);
d9wg.writeUInt16LE(1, 4);
d9wg.writeUInt16LE(3, 6);
d9wg.writeUInt32LE(0xA0010001, 24);
d9wg.writeUInt32LE(0x20260806, 28);
const envelope = Buffer.alloc(8 + d9wg.length);
envelope.writeUInt16LE(0xFFE1, 0);
envelope.writeUInt16LE(0xFFFF, 2);
envelope.writeUInt32LE(d9wg.length, 4);
d9wg.copy(envelope, 8);

bridge.pushPCIBatch({
    bytes: envelope,
    frameId: 1,
    submitCount: 7,
    commandCount: 1,
    flags: 0,
});

assert.equal(routed.length, 1,
    "D9WG routing must not be rejected by the OpenGL stale-frame counter");
assert.deepEqual(routed[0].bytes, d9wg);
assert.equal(routed[0].metadata.pciFrameId, 1);
assert.equal(routed[0].metadata.submitCount, 7);
assert.equal(routed[0].metadata.descriptorCommandCount, 1);
assert.equal(routed[0].metadata.descriptorBase, 0);
assert.equal(typeof routed[0].metadata.writeGuestMemory, "function");

// The bytes have to actually land, at the address asked for.
routed[0].metadata.writeGuestMemory(64, Uint8Array.from([1, 2, 3, 4]));
assert.deepEqual([...guestMemory.subarray(64, 68)], [1, 2, 3, 4],
    "a host->guest write must reach guest memory at the requested offset");
assert.deepEqual([...guestMemory.subarray(0, 4)], [0, 0, 0, 0],
    "and must not land at offset 0 instead");
// The arena bound is still enforced.
assert.throws(() => routed[0].metadata.writeGuestMemory(16 * 1024 * 1024,
    Uint8Array.from([9])), RangeError);

d3d9Options.onSurface({ hwnd: 0x1234, x: 10, y: 20, width: 640,
    height: 480, displayWidth: 640, displayHeight: 480, visible: true }, "create");
d3d9Options.onPresent({ hwnd: 0x1234, x: 10, y: 20, width: 640,
    height: 480, displayWidth: 640, displayHeight: 480, visible: true }, {});
assert.deepEqual(placed(d3d9Layer), [10, 20, 640, 480, true]);
assert.equal(glLayer.visible, false);

// A DDSCL_NORMAL primary is the whole desktop even when the application that
// presents it is a small splash HWND. The dirty rectangle clips the layer;
// the HWND must not resize and stretch the desktop texture into 420x170.
d3d9Options.onPresent({ hwnd: 0x1234, x: 302, y: 299, width: 420,
    height: 170, displayWidth: 1024, displayHeight: 768,
    ddDesktopPrimary: true, visible: true,
    clipRect: { left: 302, top: 299, right: 722, bottom: 469,
        baseWidth: 1024, baseHeight: 768 } }, {});
assert.deepEqual(placed(d3d9Layer), [0, 0, 1024, 768, true]);
assert.deepEqual(d3d9Layer.clip, { left: 302 / 1024, top: 299 / 768, right: 722 / 1024, bottom: 469 / 768 },
    "the desktop layer must expose only the splash dirty rectangle");

d3d9Options.onSurface({ hwnd: 0x1234, x: 30, y: 40, width: 640,
    height: 480, displayWidth: 800, displayHeight: 600,
    ddDesktopPrimary: false, clipRect: null, visible: true }, "move");
assert.deepEqual(placed(d3d9Layer).slice(0, 4), [30, 40, 800, 600]);

d3d9Options.onSurface({ hwnd: 0x1234, x: 0, y: 0, width: 640,
    height: 480, displayWidth: 800, displayHeight: 600, visible: false }, "hide");
assert.equal(d3d9Layer.visible, false);
d3d9Options.onPresent({ sessionKey: "new-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, {});
assert.deepEqual(placed(d3d9Layer), [30, 40, 800, 600, true]);

d3d9Options.onSurface({ sessionKey: "pending-session", hwnd: 0x5678,
    x: 500, y: 600, width: 320, height: 200, visible: true }, "create");
assert.deepEqual(placed(d3d9Layer), [30, 40, 800, 600, true],
    "a helper session's CreateDevice must not hide or move the presenting owner");
d3d9Options.onDestroy({ sessionKey: "pending-session", hwnd: 0x5678,
    x: 500, y: 600, width: 320, height: 200, visible: false }, "session-end");
assert.equal(d3d9Layer.visible, true,
    "tearing down a non-owner session must leave the owner visible");

d3d9Options.onDestroy({ sessionKey: "old-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, "device");
assert.equal(d3d9Layer.visible, true,
    "late teardown from an old process session must not hide the new owner");
d3d9Options.onDestroy({ sessionKey: "new-session", hwnd: 0x1234,
    x: 30, y: 40, width: 640, height: 480, displayWidth: 800,
    displayHeight: 600, visible: true }, "device");
assert.equal(d3d9Layer.visible, false);

d3d9Options.onSurface({ sessionKey: "next-session", hwnd: 0x9999,
    x: 5, y: 6, width: 320, height: 200, visible: true }, "create");
assert.equal(d3d9Layer.visible, false,
    "a new session stays hidden until its own first Present");
d3d9Options.onPresent({ sessionKey: "next-session", hwnd: 0x9999,
    x: 5, y: 6, width: 320, height: 200, displayWidth: 320, displayHeight: 200, visible: true }, {});
assert.deepEqual(placed(d3d9Layer), [5, 6, 320, 200, true]);

// Covered by other guest windows: hidden, whatever is presented meanwhile,
// until the guest says it is uncovered
const next = { sessionKey: "next-session", hwnd: 0x9999, x: 5, y: 6, width: 320, height: 200,
    displayWidth: 320, displayHeight: 200, visible: true };
d3d9Options.onSurface({ ...next, occluded: true, visibleRegion: null }, "window-state");
assert.equal(d3d9Layer.visible, false, "a covered window's picture is not drawn");
assert.equal(bridge.activeOwner, "d3d9", "it is still the one on screen");
d3d9Options.onPresent({ ...next }, {});
assert.equal(d3d9Layer.visible, false, "a Present behind the popup does not uncover it");
// A message box over the right half: only the left half shows
d3d9Options.onSurface({ ...next, occluded: false, visibleRegion: { rects: [{ left: 0, top: 0, right: 160, bottom: 200 }],
    baseWidth: 320, baseHeight: 200, originX: 5, originY: 6 } }, "window-state");
assert.equal(d3d9Layer.visible, true, "uncovered: shown again right away");
assert.deepEqual(d3d9Layer.visibleRegion, [{ left: 0, top: 0, right: 0.5, bottom: 1 }]);
d3d9Options.onPresent({ ...next }, {});
assert.deepEqual(d3d9Layer.visibleRegion, [{ left: 0, top: 0, right: 0.5, bottom: 1 }],
    "the region holds across Presents");
d3d9Options.onSurface({ ...next, visibleRegion: null }, "window-state");
assert.equal(d3d9Layer.visibleRegion, null, "all of it shows once the box closes");

// A DirectDraw desktop primary is the whole desktop: the region is placed
// where the presenting window's client area is on it
d3d9Options.onPresent({ ...next, x: 302, y: 299, width: 420, height: 170, displayWidth: 1024,
    displayHeight: 768, ddDesktopPrimary: true,
    visibleRegion: { rects: [{ left: 0, top: 0, right: 210, bottom: 170 }],
        baseWidth: 420, baseHeight: 170, originX: 302, originY: 299 } }, {});
assert.deepEqual(placed(d3d9Layer), [0, 0, 1024, 768, true]);
assert.deepEqual(d3d9Layer.visibleRegion, [{ left: 302 / 1024, top: 299 / 768, right: 512 / 1024, bottom: 469 / 768 }]);
d3d9Options.onPresent({ ...next, ddDesktopPrimary: false, clipRect: null, visibleRegion: null }, {});

bridge.showOwner("gl");
assert.equal(d3d9Layer.visible, false);
assert.equal(glLayer.visible, true);

// Additional swap chains are layers of their own, placed like the owner's
const swapChainCanvas = d3d9Options.createSwapChainCanvas({ swapChain: 7, width: 100, height: 80 });
assert.equal(swapChainCanvas.layer.name, "d3d9 swap chain 7");
bridge.placeD3D9SwapChain({ swapChain: 7, x: 10, y: 20, width: 100, height: 80, visible: true });
assert.deepEqual(placed(swapChainCanvas.layer), [10, 20, 100, 80, true]);
bridge.hideLayers();
assert.equal(swapChainCanvas.layer.visible, true, "hiding the primary window keeps other swap chains");
bridge.hideLayers(true);
assert.equal(swapChainCanvas.layer.visible, false);
bridge.removeD3D9SwapChain(7);
assert.ok(!compositor.layers.includes(swapChainCanvas.layer), "a destroyed swap chain's layer goes");

const beforeReset = guestMemory.slice();
++bridge.memoryGeneration;
routed[0].metadata.writeGuestMemory(0, new Uint8Array([123]));
assert.deepEqual(guestMemory, beforeReset, "a late GPU readback cannot overwrite memory after restore/restart");
console.log("v86_network_bridge_d3d9_route_test: ok");
                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/glbridge/v86_network_bridge_gl_route_test.js                                       0000644 0000000 0000000 00000012600 00000000000 021611  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";

// The bridge's OpenGL routing.
//
// A bare GL record stream -- no VGL2 envelope, which is how the OpenGL path has
// always framed itself -- must reach gl_executor.js directly,
// and the D3D8/D3D9 envelopes must keep reaching their own executors untouched.
// The reason to test the negative is that all three arrive through one
// pushPCIBatch, so a routing mistake sends a D3D batch into the GL
// decoder and produces a wall of "no handler" rather than anything legible.

const assert = require("node:assert/strict");

require("../../src/browser/glbridge/v86_network_bridge.js");
const { V86WebGPUCompositor } = require("../../src/browser/glbridge/webgpu_compositor.js");

const { GLStream, GL } = require("./gl_stream_builder.js");

const listeners = Object.create(null);
const compositor = new V86WebGPUCompositor({ width: 1024, height: 768 });

const glBatches = [];
const d3d9Batches = [];
let glOptions = null;
let presented = 0;
const guestMemory = new Uint8Array(1 << 16);

const bridge = globalThis.installV86GLNetworkBridge({
    add_listener(name, callback) { listeners[name] = callback; },
    write_memory(blob, address) { guestMemory.set(blob, address); },
}, null, {
    compositor,
    installGLWebGPUExecutor(installedCanvas, options) {
        assert.equal(installedCanvas.layer.name, "gl", "OpenGL draws into its own window layer");
        assert.equal(options.host, installedCanvas.layer.host,
            "through a host that shares the compositor's device");
        glOptions = options;
        return {
            submit(bytes, metadata) {
                glBatches.push({ bytes: Buffer.from(bytes), metadata });
            },
            onSwapBuffers() { ++presented; },
        };
    },
    installD3D9WebGPUExecutor() {
        return {
            submit(bytes, metadata) {
                d3d9Batches.push({ bytes: Buffer.from(bytes), metadata });
            },
        };
    },
});

assert.ok(bridge.glExecutor, "the executor is installed at bridge creation");
assert.ok(glOptions && typeof glOptions.writeGuestMemory === "function",
    "the executor is given a way to answer a readback after the batch returns");

/* ---- a bare GL stream reaches the GL executor ---- */

const stream = new GLStream()
    .makeCurrent(1, 0, 0, 320, 240)
    .call("CLEAR_COLOR", 0.5, 0.25, 0.125, 1)
    .call("CLEAR", GL.COLOR_BUFFER_BIT);
const glBytes = stream.bytes();

bridge.pushPCIBatch({
    bytes: glBytes, frameId: 1, submitCount: 1, commandCount: 3, flags: 0,
    batchAddr: 0x1000,
});
assert.equal(glBatches.length, 1, "the bare GL stream routed to the executor");
assert.deepEqual(glBatches[0].bytes, Buffer.from(glBytes));
assert.equal(glBatches[0].metadata.batchAddress, 0x1000,
    "the batch's guest address travels with it, for the readback write-back");
assert.equal(presented, 0, "no present flag, no present");

bridge.pushPCIBatch({
    bytes: glBytes, frameId: 2, submitCount: 2, commandCount: 3, flags: 1,
    batchAddr: 0x1000,
});
assert.equal(glBatches.length, 2);
assert.equal(presented, 1, "the descriptor's present flag swaps buffers");

/* ---- a D3D9 envelope still goes to the D3D9 executor ---- */

const d3d9Batch = Buffer.alloc(8 + 16);
d3d9Batch.writeUInt16LE(0xFFE1, 0);          // V86GL_CTRL_D3D9_BATCH
d3d9Batch.writeUInt16LE(0xFFFF, 2);          // extended record
d3d9Batch.writeUInt32LE(16, 4);              // payload bytes
bridge.pushPCIBatch({
    bytes: new Uint8Array(d3d9Batch), frameId: 3, submitCount: 3,
    commandCount: 1, flags: 0, descAddr: 0x2000,
});
assert.equal(d3d9Batches.length, 1, "the D3D9 envelope is not swallowed by GL");
assert.equal(glBatches.length, 2, "and it did not also reach the GL executor");

/* ---- window-state reports place the GL layer without claiming the screen ---- */

const glLayer = bridge.glCanvas.layer;
bridge.hideLayers();
glOptions.onSurface({ hwnd: 7, x: 40, y: 30, width: 200, height: 100, visible: true,
    occluded: false, visibleRegion: null }, "window-state");
assert.notEqual(bridge.activeOwner, "gl", "a window-state report alone does not put OpenGL on screen");
bridge.showOwner("gl");
glOptions.onSurface({ hwnd: 7, x: 40, y: 30, width: 200, height: 100, visible: true,
    occluded: true, visibleRegion: null }, "window-state");
assert.equal(glLayer.visible, false, "covered by another window: not drawn");
assert.equal(bridge.activeOwner, "gl");
glOptions.onSurface({ hwnd: 7, x: 40, y: 30, width: 200, height: 100, visible: true, occluded: false,
    visibleRegion: { rects: [{ left: 0, top: 50, right: 200, bottom: 100 }], baseWidth: 200, baseHeight: 100,
        originX: 40, originY: 30 } }, "window-state");
assert.equal(glLayer.visible, true);
assert.deepEqual([glLayer.x, glLayer.y, glLayer.width, glLayer.height], [40, 30, 200, 100]);
assert.deepEqual(glLayer.visibleRegion, [{ left: 0, top: 0.5, right: 1, bottom: 1 }], "only the part that shows");
glOptions.onSurface({ hwnd: 7, visible: false }, "hide");
assert.equal(glLayer.visible, false, "a hidden window takes the picture down");
assert.equal(bridge.activeOwner, null);

assert.equal("glBackend" in bridge, false,
    "the removed GL4ES fallback cannot be selected at runtime");

const beforeReset = guestMemory.slice();
++bridge.memoryGeneration;
glOptions.writeGuestMemory(0, new Uint8Array([123]), glBatches[0].metadata);
assert.deepEqual(guestMemory, beforeReset, "late GL readback belongs to the previous graphics generation");
console.log("v86_network_bridge_gl_route_test: ok");
                                                                                                                                source/v64/tests/glbridge/v86_network_bridge_webgpu_state_test.js                                   0000644 0000000 0000000 00000010047 00000000000 022465  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
"use strict";

const assert = require("node:assert/strict");
const { GLStream, GL } = require("./gl_stream_builder.js");
require("../../src/browser/glbridge/v86_network_bridge.js");
const { V86WebGPUCompositor } = require("../../src/browser/glbridge/webgpu_compositor.js");

function recordOpcodes(bytes) {
    const result = [];
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    let offset = 0;
    while (offset < bytes.byteLength) {
        const fn = view.getUint16(offset, true);
        let size = view.getUint16(offset + 2, true);
        offset += 4;
        if (size === 0xffff) {
            size = view.getUint32(offset, true);
            offset += 4;
        }
        result.push(fn);
        offset += size;
    }
    return result;
}

(async () => {
    const calls = [];
    const executor = {
        submit(bytes, metadata) {
            calls.push(["submit", bytes.slice(), metadata]);
        },
        onSwapBuffers() { calls.push(["swap"]); },
        resetForReplay() { calls.push(["reset"]); },
    };
    const bridge = globalThis.installV86GLNetworkBridge(null, null, {
        compositor: new V86WebGPUCompositor({ width: 64, height: 64 }),
        glExecutor: executor,
    });

    const authored = new GLStream().makeCurrent(1, 0, 0, 64, 64)
        .call("CLEAR_COLOR", 0.25, 0.5, 0.75, 1)
        .call("CLEAR", GL.COLOR_BUFFER_BIT);
    authored.queryError();
    bridge.pushPCIBatch({ bytes: authored.bytes(), frameId: 1,
        submitCount: 1, commandCount: 4, flags: 1 });

    const summary = await bridge.prepareSaveState();
    assert.ok(summary.entries >= 2);
    // What graphics_proxy.js stores as the device's host state
    const checkpoint = bridge.serializeCheckpoint();
    assert.ok(checkpoint instanceof Uint8Array);
    const parsed = bridge.parseCheckpoint(checkpoint);
    const { GraphicsJournal } = require("../../src/browser/glbridge/graphics_journal.js");
    const glBytes = (await GraphicsJournal.records(parsed).next()).value.bytes;
    assert.ok(recordOpcodes(glBytes).includes(211),
        "query commands replay locally without writing restored guest RAM");

    bridge.beginStateRestore();
    bridge.onPCIStateRestored(checkpoint);
    const queued = new GLStream().makeCurrent(2, 0, 0, 32, 32).bytes();
    bridge.pushPCIBatch({ bytes: queued, frameId: 2,
        submitCount: 2, commandCount: 1, flags: 0 });
    await bridge.finishStateRestore();

    const resetAt = calls.findIndex(call => call[0] === "reset");
    const replayAt = calls.findIndex((call, index) => index > resetAt &&
        call[0] === "submit" && call[2].replay === true);
    const queuedAt = calls.findIndex((call, index) => index > replayAt &&
        call[0] === "submit" && call[2].pciFrameId === 2);
    assert.ok(resetAt >= 0 && replayAt > resetAt && queuedAt > replayAt,
        "restore resets, replays, then drains newly arriving guest work");
    assert.equal(bridge.glJournalBytes, glBytes.byteLength + queued.byteLength);

    // Version 2 stored raw records; keep existing saves loadable after moving
    // new saves to the paged compressed format.
    const version2 = new Uint8Array(32 + 32 + glBytes.length + 32);
    const v2 = new DataView(version2.buffer);
    v2.setUint32(0, 0x32534756, true);
    v2.setUint16(4, 2, true);
    v2.setUint16(6, 32, true);
    v2.setUint32(8, version2.length, true);
    v2.setUint32(16, 2, true);
    v2.setUint32(32, glBytes.length, true);
    v2.setUint32(36, 1, true);
    version2.set(glBytes, 64);
    v2.setUint32(64 + glBytes.length + 24, 1, true);
    await bridge.restoreCheckpoint(version2);
    assert.equal(bridge.glJournalBytes, glBytes.length);
    await bridge.prepareSaveState();
    const migrated = bridge.parseCheckpoint(bridge.serializeCheckpoint());
    assert.equal(migrated.version, 3);
    assert.deepEqual((await GraphicsJournal.records(migrated).next()).value.bytes, glBytes);
    await bridge.graphicsJournal.destroy();
    console.log("v86_network_bridge_webgpu_state_test: ok");
})().catch(error => {
    console.error(error);
    process.exit(1);
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/glbridge/virtio_gpu_present_browser_test.html                                      0000644 0000000 0000000 00000021326 00000000000 022230  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>virtio-gpu: a 3D scanout shown without readbacks</title>
<div id="screen"><div></div><canvas></canvas></div>
<pre id="result">RUNNING</pre>
<script src="../../build/libv86.js"></script>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script>
// docs/gfxstream-plan.md G4. virtio-gpu at level virgl43 with the graphics
// proxy: the display adapter's renderer (svga_renderer.js) runs on the
// compositor's device and has a layer of it. A 3D resource gets its pixels
// from guest memory (TRANSFER_TO_HOST_3D: a blue left half, a yellow right
// half), is the scanout and is flushed: the renderer copies it into the
// layer on the GPU (GX's SURFACE_PRESENT) and the screen shows it, with no
// readback; SET_SCANOUT 0 takes it away. The device's side of the choice
// is tests/devices/virtio_gpu_present.js.
(async () => {
    const checks = [];
    const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
    const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
    let emulator;
    try {
        // hlt forever
        const floppy = new Uint8Array(1474560);
        floppy.set([0xfa, 0xf4, 0xeb, 0xfd]);
        floppy[510] = 0x55;
        floppy[511] = 0xAA;
        const container = document.getElementById("screen");
        emulator = new V86({
            graphics_adapter: "virtio_gpu", graphics_adapter_test: { level: "virgl43" },
            wasm_path: "../../build/v86.wasm", memory_size: 64 << 20, vram_size: 16 << 20,
            bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
            fda: { buffer: floppy.buffer }, boot_order: 0x321,
            screen: { container },
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: true,
            graphics_proxy: true,
        });
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const bridge = emulator.graphics_proxy.bridge;
        await bridge.ready;
        check(!bridge.failed, "graphics initializes");
        const compositor = bridge.compositor;
        const gpu = emulator.v86.cpu.devices.graphics_adapter.device["virtio_gpu"];
        for(let i = 0; i < 100 && !gpu.virgl.direct_present; i++) await sleep(50);
        check(gpu.virgl.direct_present, "the renderer has the compositor's layer: it shows pictures");
        const renderer = emulator.adapter_renderer;
        await renderer.executor.initialize();
        check(renderer.executor.device === compositor.device, "the renderer and the compositor share one GPUDevice");
        for(let i = 0; i < 200 && !emulator.screen_adapter.get_text_screen().join("").includes("Booting from Floppy"); i++) await sleep(50);
        await emulator.stop();

        // The transport (virtio-vga's capabilities in BAR2)
        const cpu = emulator.v86.cpu, io = cpu.io;
        const BDF = 0x12 << 3;
        const pci_read = reg => { io.port_write32(0xcf8, 0x80000000 | BDF << 8 | reg); return io.port_read32(0xcfc) >>> 0; };
        const pci_read8 = reg => pci_read(reg & ~3) >>> 8 * (reg & 3) & 0xFF;
        let common = 0, notify = 0;
        const bar2 = (pci_read(0x18) & ~0xF) >>> 0;
        for(let at = pci_read8(0x34); at; at = pci_read8(at + 1))
        {
            if(pci_read8(at) !== 0x09) continue;
            const type = pci_read8(at + 3);
            if(type === 1) common = bar2 + pci_read(at + 8);
            if(type === 2) notify = bar2 + pci_read(at + 8);
        }
        const write32 = (address, value) => { for(let i = 0; i < 4; i++) cpu.write8(address + i, value >>> 8 * i & 0xFF); };
        const read32 = address => (cpu.read8(address) | cpu.read8(address + 1) << 8 | cpu.read8(address + 2) << 16 | cpu.read8(address + 3) << 24) >>> 0;
        const w8 = (offset, value) => cpu.write8(common + offset, value);
        const w16 = (offset, value) => { cpu.write8(common + offset, value & 0xFF); cpu.write8(common + offset + 1, value >> 8); };
        const QUEUES = [{ size: 0, desc: 0x100000, avail: 0x101000, used: 0x102000, avail_idx: 0 },
            { size: 0, desc: 0x110000, avail: 0x111000, used: 0x112000, avail_idx: 0 }];
        w8(20, 0); w8(20, 3);
        write32(common, 0);
        const features0 = read32(common + 4);
        write32(common + 8, 0); write32(common + 12, features0);
        write32(common + 8, 1); write32(common + 12, 1);
        w8(20, 11);
        QUEUES.forEach((q, i) => {
            w16(22, i);
            q.size = cpu.read8(common + 24) | cpu.read8(common + 25) << 8;
            write32(common + 32, q.desc); write32(common + 36, 0);
            write32(common + 40, q.avail); write32(common + 44, 0);
            write32(common + 48, q.used); write32(common + 52, 0);
            emulator.write_memory(new Uint8Array(0x3000), q.desc);
            w16(28, 1);
        });
        w8(20, 15);
        const REQUEST = 0x200000, REPLY = 0x280000;
        const command = (type, ...values) => {
            const out = new Uint32Array(6 + values.length);
            out[0] = type;
            out.set(values, 6);
            const q = QUEUES[0];
            emulator.write_memory(new Uint8Array(out.buffer), REQUEST);
            write32(q.desc, REQUEST); write32(q.desc + 4, 0); write32(q.desc + 8, out.byteLength);
            cpu.write8(q.desc + 12, 1); cpu.write8(q.desc + 14, 1);
            write32(q.desc + 16, REPLY); write32(q.desc + 20, 0); write32(q.desc + 24, 64);
            cpu.write8(q.desc + 28, 2);
            write32(q.avail + 4 + (q.avail_idx % q.size) * 2, 0);
            q.avail_idx = q.avail_idx + 1 & 0xFFFF;
            cpu.write8(q.avail + 2, q.avail_idx & 0xFF);
            cpu.write8(q.avail + 3, q.avail_idx >> 8);
            cpu.write8(notify, 0);
            cpu.write8(notify + 1, 0);
            return read32(REPLY);
        };
        const OK = 0x1100;
        const W = 64, H = 48, PIXELS = 0x300000;
        // B8G8R8A8: blue on the left, yellow on the right
        const pixels = new Uint8Array(W * H * 4);
        for(let y = 0; y < H; y++) for(let x = 0; x < W; x++) pixels.set(x < W / 2 ? [255, 0, 0, 255] : [0, 255, 255, 255], (y * W + x) * 4);
        emulator.write_memory(pixels, PIXELS);
        // RESOURCE_CREATE_3D (PIPE_TEXTURE_2D, B8G8R8A8_UNORM, RENDER_TARGET | SCANOUT), ATTACH_BACKING, TRANSFER_TO_HOST_3D
        check(command(0x0204, 1, 2, 1, 0x2 | 0x40000, W, H, 1, 1, 0, 0, 0, 0) === OK, "RESOURCE_CREATE_3D");
        check(command(0x0106, 1, 1, PIXELS, 0, W * H * 4, 0) === OK, "ATTACH_BACKING");
        check(command(0x0205, 0, 0, 0, W, H, 1, 0, 0, 1, 0, W * 4, 0) === OK, "TRANSFER_TO_HOST_3D");
        await emulator.run();
        const gx_stats = () => renderer.gx ? { ...renderer.gx.stats } : {};
        await emulator.stop();
        check(command(0x0103, 0, 0, W, H, 0, 1) === OK, "SET_SCANOUT");
        check(command(0x0104, 0, 0, W, H, 1, 0) === OK, "RESOURCE_FLUSH");
        await emulator.run();
        await renderer.idle();
        const before = gx_stats();

        const shot = async () => {
            const image = emulator.screen_make_screenshot();
            await image.decode();
            const capture = document.createElement("canvas");
            capture.width = image.width;
            capture.height = image.height;
            const context = capture.getContext("2d");
            context.drawImage(image, 0, 0);
            return (x, y) => [...context.getImageData(x, y, 1, 1).data.slice(0, 3)];
        };
        const near = (pixel, rgb) => pixel.every((v, i) => Math.abs(v - rgb[i]) < 8);
        let pixel;
        for(let i = 0; i < 60; i++)
        {
            await sleep(50);
            pixel = await shot();
            if(near(pixel(8, 8), [0, 0, 255]) && near(pixel(W - 8, 8), [255, 255, 0])) break;
        }
        check(near(pixel(8, 8), [0, 0, 255]) && near(pixel(W - 8, H - 8), [255, 255, 0]),
            "the screen shows the 3D resource: " + pixel(8, 8) + " " + pixel(W - 8, H - 8));
        check(before.presents >= 1 && !before.readbacks, "presented on the GPU, no readback: " + JSON.stringify(before));
        check(gpu.scanouts[0].direct === 1, "the device: the renderer shows scanout 0");

        // SET_SCANOUT 0: the layer goes
        await emulator.stop();
        check(command(0x0103, 0, 0, 0, 0, 0, 0) === OK, "SET_SCANOUT 0");
        await emulator.run();
        await renderer.idle();
        const layer = compositor.layers.find(l => l.name === "display adapter");
        check(layer && !layer.visible, "the layer hidden");
        document.getElementById("result").textContent = "PASS\n" + checks.join("\n");
    } catch(error) {
        document.getElementById("result").textContent = "FAIL " + (error && error.stack || error) + "\n" + checks.join("\n");
    }
})();
</script>
                                                                                                                                                                                                                                                                                                          source/v64/tests/glbridge/virtio_transport_bench.cjs                                                0000644 0000000 0000000 00000011625 00000000000 020102  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Run manually; this microbenchmark is not an FPS or CI timing assertion.
// For an A/B run, run it at another commit (a git worktree) with the same node.
"use strict";
const assert = require("node:assert/strict");
const path = require("node:path");
const { createV86GLDevice } = require("../../src/browser/glbridge/v86gl_device.js");
(async () => {
    global.DEBUG = false;
    const { V86 } = await import("../../src/browser/starter.js");
    // A renderer that takes every batch at once
    let toDevice = null;
    const descriptor = createV86GLDevice({ remote: false, listen: handler => { toDevice = handler; },
        post: message => toDevice({ type: "done", id: message.id }) });
    toDevice({ type: "available", value: true });
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: path.join(__dirname,"../../build/v86.wasm"),
        memory_size: 32 * 1024 * 1024,
        bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" }, autostart: false,
        virtio_devices: [descriptor],
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    try {
        const cpu = emulator.v86.cpu, io = cpu.io;
        const pci = cpu.devices.virtio_devices[0].virtio;
        assert.equal(pci.pci_space[0] | pci.pci_space[1] << 8, 0x1af4);
        assert.equal(pci.pci_space[2] | pci.pci_space[3] << 8, 0x107f);
        assert.ok(!pci.pci_bars.some(bar => bar && bar.fixed), "BARs can relocate");
        const ram = cpu.read_blob(0, 32 * 1024 * 1024);
        const mem = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
        let common = 0xf100, notify = 0xf200;
        const arena = 0x100000;
        const table = 0x10000, avail = table + 128, used = table + 160;
        const req = table + 256, reply = table + 288;
        const w8 = (o, v) => io.port_write8(common + o, v);
        const w16 = (o, v) => io.port_write16(common + o, v);
        const w32 = (o, v) => io.port_write32(common + o, v);
        let idx = 0;
        function setup() {
            w8(20, 0); w8(20, 3);
            w32(0, 1); assert.equal(io.port_read32(common + 4), 1);
            w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1);
            w8(20, 11); assert.equal(io.port_read8(common + 20), 11);
            w16(22, 0); w16(24, 8);
            w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0);
            w32(48, used); w32(52, 0);
            for (let i = 0; i < 320; i++) mem.setUint8(table + i, 0);
            mem.setUint32(table, req, true); mem.setUint32(table + 8, 24, true);
            mem.setUint16(table + 12, 1, true); mem.setUint16(table + 14, 1, true);
            mem.setUint32(table + 16, reply, true); mem.setUint32(table + 24, 16, true);
            mem.setUint16(table + 28, 2, true);
            mem.setUint16(avail, 1, true);
            w16(28, 1); w8(20, 15); idx = 0;
        }
        function request(op, address = 0, length = 0, flags = 0, high = 0) {
            [op,address,high,length,flags,0].forEach((v,i) => mem.setUint32(req+i*4,v,true));
            mem.setUint32(reply, 0xffffffff, true);
            mem.setUint16(avail + 4 + (idx & 7) * 2, 0, true);
            idx = (idx + 1) & 0xffff;
            mem.setUint16(avail + 2, idx, true);
            io.port_write16(notify, 0);
            assert.equal(mem.getUint16(used + 2, true), idx, "used ring acknowledges request");
            assert.equal(mem.getUint32(used + 4 + ((idx - 1) & 7)*8+4,true),16);
            return mem.getUint32(reply, true);
        }
        setup();
        assert.equal(request(1,arena,16*1024*1024),0);
        [0x324c4756,1,0,42,1,4,0,0].forEach((v,i)=>mem.setUint32(arena+i*4,v,true));
        mem.setUint16(arena+32,0xfff1,true); mem.setUint16(arena+34,0,true);
        mem.setUint32(req,2,true); mem.setUint32(req+4,0,true); mem.setUint32(req+12,36,true);
        function run(count) {
            const start=process.hrtime.bigint();
            for (let i=0;i<count;i++) {
                mem.setUint16(avail+4+(idx&7)*2,0,true);
                idx=(idx+1)&65535; mem.setUint16(avail+2,idx,true);
                io.port_write16(notify,0);
            }
            assert.equal(mem.getUint16(used+2,true),idx);
            assert.equal(mem.getUint32(reply,true),0);
            return Number(process.hrtime.bigint()-start)/count;
        }
        run(20000);
        const iterations = Number(process.env.BENCH_ITERATIONS || 100000);
        assert.ok(Number.isInteger(iterations) && iterations > 0);
        const samples=Array.from({length:9},()=>run(iterations)).sort((a,b)=>a-b);
        console.log(JSON.stringify({scope:"Host virtio submission only; no guest execution or GPU rendering",node:process.version,iterations,ns_per_submit_median:samples[4],samples},null,2));
    } finally { await emulator.destroy(); }
})().catch(error=>{console.error(error);process.exitCode=1;});
                                                                                                           source/v64/tests/glbridge/virtio_v86gl_high_test.js                                                 0000644 0000000 0000000 00000010576 00000000000 017554  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
// virtio-v86gl on the physical bus: an arena in RAM relocated above 4 GiB
// (high_memory_size) is accepted, submitted and written back through the
// bus; the low alias it leaves (an open-bus hole) is rejected.
const assert = require("node:assert/strict");
const path = require("node:path");
const { createV86GLDevice } = require("../../src/browser/glbridge/v86gl_device.js");
(async () => {
    global.DEBUG = false;
    const { V86 } = await import("../../src/browser/starter.js");
    const MiB = 1024 * 1024;
    let host = null, last;
    const descriptor = createV86GLDevice({ remote: false, post: message => { last = message; },
        listen: handler => { host = handler; } });
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: path.join(__dirname, "../../build/v86.wasm"),
        memory_size: 64 * MiB, high_memory_size: 16 * MiB,
        bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" }, autostart: false,
        virtio_devices: [descriptor],
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    try {
        const cpu = emulator.v86.cpu, io = cpu.io;
        const ram = cpu.read_blob(0, 48 * MiB);
        const mem = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
        const common = 0xf100, notify = 0xf200;
        const table = 0x10000, avail = table + 128, used = table + 160;
        const req = table + 256, reply = table + 288;
        const w8 = (o, v) => io.port_write8(common + o, v);
        const w16 = (o, v) => io.port_write16(common + o, v);
        const w32 = (o, v) => io.port_write32(common + o, v);
        let idx = 0;
        w8(20, 0); w8(20, 3);
        w32(0, 1); w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1);
        w8(20, 11);
        w16(22, 0); w16(24, 8);
        w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0); w32(48, used); w32(52, 0);
        for (let i = 0; i < 320; i++) mem.setUint8(table + i, 0);
        mem.setUint32(table, req, true); mem.setUint32(table + 8, 24, true);
        mem.setUint16(table + 12, 1, true); mem.setUint16(table + 14, 1, true);
        mem.setUint32(table + 16, reply, true); mem.setUint32(table + 24, 16, true);
        mem.setUint16(table + 28, 2, true);
        mem.setUint16(avail, 1, true);
        w16(28, 1); w8(20, 15);
        function request(op, address = 0, length = 0, flags = 0, high = 0) {
            [op, address, high, length, flags, 0].forEach((v, i) => mem.setUint32(req + i * 4, v, true));
            mem.setUint32(reply, 0xffffffff, true);
            mem.setUint16(avail + 4 + (idx & 7) * 2, 0, true);
            idx = (idx + 1) & 0xffff;
            mem.setUint16(avail + 2, idx, true);
            io.port_write16(notify, 0);
            assert.equal(mem.getUint16(used + 2, true), idx);
            return mem.getUint32(reply, true);
        }
        assert.equal(cpu.low_memory_size, 48 * MiB);
        assert.equal(request(1, 48 * MiB, 16 * MiB), 1, "the low alias of relocated RAM is a hole");
        assert.equal(request(1, 0, 16 * MiB, 0, 1), 0, "arena in RAM above 4 GiB");
        assert.equal(descriptor.get_state()[1], 4 * 1024 * MiB);
        const header = new Uint8Array(36), view = new DataView(header.buffer);
        [0x324c4756, 1, 0, 77, 1, 4, 0, 0].forEach((v, i) => view.setUint32(i * 4, v, true));
        view.setUint16(32, 0xfff1, true);
        cpu.write_blob_physical(header, 4 * 1024 * MiB);
        host({ type: "available", value: true });
        assert.equal(request(2, 0, 36), 0, "submission from high RAM");
        assert.equal(last.frameId, 77);
        assert.deepEqual([...last.bytes], [0xf1, 0xff, 0, 0]);
        // The relocated range is the top of the backing store, not low RAM.
        assert.equal(new Uint8Array(cpu.mem8.buffer, cpu.mem8.byteOffset + 48 * MiB, 4)[0], 0x56);
        host({ type: "write", generation: last.generation, offset: 0x200, bytes: new Uint8Array([0xA5, 0x5A]) });
        assert.deepEqual([...cpu.read_blob_physical(4 * 1024 * MiB + 0x200, 2)], [0xA5, 0x5A], "write-back reaches high RAM");
        console.log("virtio_v86gl_high_test: arena above 4 GiB accepted, low hole rejected, submit and write-back through the physical bus passed");
    } finally { await emulator.destroy(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
                                                                                                                                  source/v64/tests/glbridge/virtio_v86gl_test.js                                                      0000644 0000000 0000000 00000031112 00000000000 016542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       "use strict";
// The v86gl device (glbridge/v86gl_device.js) on v86's virtio_devices, driven
// through its ports: PCI identity, negotiation, a real virtqueue, request
// validation, the renderer channel (batches, readbacks, availability), reset,
// state, index wrap and BAR relocation.
const assert = require("node:assert/strict");
const path = require("node:path");
const { createV86GLDevice } = require("../../src/browser/glbridge/v86gl_device.js");

function localChannel() {
    const handlers = [null, null];
    const end = (self, other) => ({ remote: false, post: message => handlers[other] && handlers[other](message),
        listen: handler => { handlers[self] = handler; } });
    return { device: end(0, 1), host: end(1, 0) };
}

(async () => {
    global.DEBUG = false;
    const { V86 } = await import("../../src/browser/starter.js");
    const channel = localChannel();
    const descriptor = createV86GLDevice(channel.device);
    let lastEvent;
    let expectedCommandBytes = 4;
    let batches = 0;
    channel.host.listen(message => {
        assert.equal(message.type, "batch");
        batches++;
        lastEvent = message;
        assert.equal(message.frameId, 42);
        assert.equal(message.bytes.byteLength, expectedCommandBytes);
        channel.host.post({ type: "done", id: message.id });
    });
    const write = (event, offset, bytes) =>
        channel.host.post({ type: "write", generation: event.generation, offset, bytes });
    const arenaBytes = () => descriptor.get_state()[2];

    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: path.join(__dirname, "../../build/v86.wasm"),
        memory_size: 32 * 1024 * 1024,
        bios: { buffer: new Uint8Array(65536).fill(0xf4).buffer },
        disable_keyboard: true, disable_mouse: true, disable_speaker: true,
        net_device: { type: "none" }, autostart: false,
        virtio_devices: [descriptor],
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    try {
        const cpu = emulator.v86.cpu, io = cpu.io;
        const pci = cpu.devices.virtio_devices[0].virtio;
        assert.equal(pci.pci_id, 0x13 << 3, "the slot the installed driver knows");
        assert.equal(pci.pci_space[0] | pci.pci_space[1] << 8, 0x1af4);
        assert.equal(pci.pci_space[2] | pci.pci_space[3] << 8, 0x107f);
        assert.ok(!pci.pci_bars.some(bar => bar && bar.fixed), "BARs can relocate");
        const ram = cpu.read_blob(0, 32 * 1024 * 1024);
        const mem = new DataView(ram.buffer, ram.byteOffset, ram.byteLength);
        let common = 0xf100, notify = 0xf200;
        const arena = 0x100000;
        const table = 0x10000, avail = table + 128, used = table + 160;
        const req = table + 256, reply = table + 288;
        const w8 = (o, v) => io.port_write8(common + o, v);
        const w16 = (o, v) => io.port_write16(common + o, v);
        const w32 = (o, v) => io.port_write32(common + o, v);
        let idx = 0;
        function setup() {
            w8(20, 0); w8(20, 3);
            w32(0, 1); assert.equal(io.port_read32(common + 4), 1);
            w32(8, 0); w32(12, 1); w32(8, 1); w32(12, 1);
            w8(20, 11); assert.equal(io.port_read8(common + 20), 11);
            w16(22, 0); w16(24, 8);
            w32(32, table); w32(36, 0); w32(40, avail); w32(44, 0);
            w32(48, used); w32(52, 0);
            for (let i = 0; i < 320; i++) mem.setUint8(table + i, 0);
            mem.setUint32(table, req, true); mem.setUint32(table + 8, 24, true);
            mem.setUint16(table + 12, 1, true); mem.setUint16(table + 14, 1, true);
            mem.setUint32(table + 16, reply, true); mem.setUint32(table + 24, 16, true);
            mem.setUint16(table + 28, 2, true);
            mem.setUint16(avail, 1, true);
            w16(28, 1); w8(20, 15); idx = 0;
        }
        function request(op, address = 0, length = 0, flags = 0, high = 0) {
            [op, address, high, length, flags, 0].forEach((v, i) => mem.setUint32(req + i * 4, v, true));
            mem.setUint32(reply, 0xffffffff, true);
            mem.setUint16(avail + 4 + (idx & 7) * 2, 0, true);
            idx = (idx + 1) & 0xffff;
            mem.setUint16(avail + 2, idx, true);
            io.port_write16(notify, 0);
            assert.equal(mem.getUint16(used + 2, true), idx, "used ring acknowledges request");
            assert.equal(mem.getUint32(used + 4 + ((idx - 1) & 7) * 8 + 4, true), 16);
            return mem.getUint32(reply, true);
        }
        assert.equal(io.port_read32(0xf400) >>> 0, 0x324c4756, "configuration space: magic");
        assert.equal(io.port_read32(0xf408), 16 * 1024 * 1024, "configuration space: arena bytes");
        setup();
        assert.equal(request(2, 0, 32), 2, "submit without registered arena fails");
        assert.equal(request(1, arena, 16 * 1024 * 1024, 0, 1), 1, "64-bit address without RAM rejected");
        assert.equal(request(1, 0x2000000, 16 * 1024 * 1024), 1, "out-of-RAM arena rejected");
        assert.equal(request(1, arena, 16 * 1024 * 1024), 0);
        assert.equal(request(1, arena, 16 * 1024 * 1024), 1, "registration cannot replace live arena");
        [0x324c4756, 1, 0, 42, 1, 4, 0, 0].forEach((v, i) => mem.setUint32(arena + i * 4, v, true));
        mem.setUint16(arena + 32, 0xfff1, true); mem.setUint16(arena + 34, 0, true);
        assert.equal(request(2, 0, 36), 3, "missing host renderer is visible to guest");
        assert.equal(batches, 0);
        channel.host.post({ type: "available", value: true });
        assert.equal(request(2, 0, 36, 1), 0);
        assert.equal(lastEvent.flags, 1);
        assert.equal(lastEvent.batchAddr, arena + 32);
        assert.equal(lastEvent.bytes.buffer, ram.buffer, "on one thread the batch is a view of guest RAM");
        write(lastEvent, 0x100, new Uint8Array([7]));
        assert.equal(mem.getUint8(arena + 0x100), 7);
        assert.throws(() => write(lastEvent, 16 * 1024 * 1024, new Uint8Array([1])), /outside/);
        const beforeUnregister = lastEvent;
        assert.equal(request(3), 0);
        write(beforeUnregister, 0x100, new Uint8Array([9]));
        assert.equal(mem.getUint8(arena + 0x100), 7, "unregistration revokes readbacks of earlier batches");
        assert.equal(request(1, arena, 16 * 1024 * 1024), 0);
        assert.equal(request(2, 0, 36), 0);
        const beforeReset = lastEvent;
        // [name, transport, device state, host state], as in a snapshot
        const device = cpu.devices.virtio_devices[0];
        const saved = device.get_state();
        saved[1] = pci.get_state().map(x => x && typeof x.get_state === "function" ? x.get_state() : x);
        w8(20, 0);
        assert.equal(arenaBytes(), 0, "guest virtio reset revokes the arena");
        write(beforeReset, 0x100, new Uint8Array([9]));
        assert.equal(mem.getUint8(arena + 0x100), 7);
        device.set_state(saved);
        assert.equal(arenaBytes(), 16 * 1024 * 1024);
        assert.equal(io.port_read8(common + 20), 15, "transport restored with the device");
        assert.throws(() => descriptor.set_state([1, 0, 32, 1, 0, 0, 0, 0]), /Unsupported/);
        // state[92] from before virtio_devices: [magic, transport, arena, bytes, frame, last, submits, 0, checkpoint]
        const checkpoint = new Uint8Array([1, 2]);
        assert.deepEqual(descriptor.upgrade_state([0x56514731, ["transport"], arena, 16 * 1024 * 1024, 5, 6, 7, 0, checkpoint]),
            [["transport"], [2, arena, 16 * 1024 * 1024, 5, 6, 7], checkpoint]);
        assert.equal(descriptor.upgrade_state(["virtio_devices", 1]), null);
        // Real split-ring 16-bit wrap, rather than just modulo queue size.
        idx = 65535;
        pci.queues[0].avail_last_idx = idx;
        mem.setUint16(used + 2, idx, true); mem.setUint16(avail + 2, idx, true);
        assert.equal(request(2, 0, 36), 0);
        assert.equal(idx, 0);
        setup();
        mem.setUint32(req, 1, true); mem.setUint16(avail + 2, 1, true);
        mem.setUint16(table + 14, 0, true); // descriptor cycle
        io.port_write16(notify, 0);
        assert.ok(io.port_read8(common + 20) & 64, "malformed queue requests a device reset");
        setup();
        w8(20, 3);
        mem.setUint16(avail + 2, 1, true);
        io.port_write16(notify, 0);
        assert.equal(mem.getUint16(used + 2, true), 0, "no consumption before DRIVER_OK");
        setup();
        // Relocate every BAR via real PCI config writes, as an OS enumerator can.
        for (let bar = 0; bar < 4; bar++) {
            io.port_write32(0xcf8, (0x80000000 | (0x13 << 11) | (0x10 + bar * 4)) >>> 0);
            io.port_write32(0xcfc, 0xe001 + bar * 0x100);
        }
        common = 0xe000; notify = 0xe100;
        assert.equal(io.port_read8(common + 20), 15);
        assert.equal(io.port_read32(0xe300) >>> 0, 0x324c4756);
        assert.equal(request(1, arena, 16 * 1024 * 1024), 0);
        assert.equal(request(2, 0, 36), 0, "submissions work after PCI BAR relocation");
        // The shipping D3D9, D3D8 and DirectDraw DLLs put D9WG_MAGIC in
        // VGL2 reserved0. Only OpenGL zeroes it; it is not a virtio field.
        const envelope = new Uint8Array(40);
        const d9 = new DataView(envelope.buffer);
        d9.setUint16(0, 0xffe1, true); d9.setUint16(2, 0xffff, true);
        d9.setUint32(4, 32, true); d9.setUint32(8, 0x47573944, true);
        d9.setUint16(12, 1, true); d9.setUint16(14, 3, true);
        d9.setUint32(16, 42, true); d9.setUint32(32, 1, true); d9.setUint32(36, 1, true);
        expectedCommandBytes = envelope.length;
        mem.setUint32(arena + 20, envelope.length, true);
        mem.setUint32(arena + 24, 0x47573944, true);
        ram.set(envelope, arena + 32);
        assert.equal(request(2, 0, 32 + envelope.length), 0, "shipping D9WG descriptor accepted by virtqueue");
        assert.deepEqual([...lastEvent.bytes], [...envelope]);
        // Two outstanding requests are drained with one used-index/IRQ flush.
        setup();
        [1, arena, 0, 16 * 1024 * 1024, 0, 0].forEach((v, i) => mem.setUint32(req + i * 4, v, true));
        const req2 = table + 320, reply2 = table + 352;
        [3, 0, 0, 0, 0, 0].forEach((v, i) => mem.setUint32(req2 + i * 4, v, true));
        mem.setUint32(table + 32, req2, true); mem.setUint32(table + 40, 24, true);
        mem.setUint16(table + 44, 1, true); mem.setUint16(table + 46, 3, true);
        mem.setUint32(table + 48, reply2, true); mem.setUint32(table + 56, 16, true);
        mem.setUint16(table + 60, 2, true);
        mem.setUint16(avail, 0, true);
        mem.setUint16(avail + 4, 0, true); mem.setUint16(avail + 6, 2, true); mem.setUint16(avail + 2, 2, true);
        let interrupts = 0, invalidations = 0;
        const raise = pci.raise_irq;
        pci.raise_irq = function(type) { interrupts++; return raise.call(this, type); };
        const dirty = cpu.jit_dirty_cache;
        cpu.jit_dirty_cache = (start, end) => {
            if ((start === reply || start === reply2) && end === start + 16) invalidations++;
            return dirty(start, end);
        };
        io.port_write16(notify, 0);
        cpu.jit_dirty_cache = dirty; pci.raise_irq = raise;
        assert.equal(mem.getUint16(used + 2, true), 2);
        assert.equal(mem.getUint32(reply, true), 0); assert.equal(mem.getUint32(reply2, true), 0);
        assert.equal(interrupts, 1, "one completion interrupt for multiple pending requests");
        assert.equal(invalidations, 2, "direct replies invalidate guest JIT code as before");
        assert.equal(arenaBytes(), 0);
        setup();
        [1, arena, 0, 16 * 1024 * 1024, 0, 0].forEach((v, i) => mem.setUint32(req + i * 4, v, true));
        mem.setUint16(avail + 4, 0, true); mem.setUint16(avail + 6, 8, true); mem.setUint16(avail + 2, 2, true);
        io.port_write16(notify, 0);
        assert.equal(mem.getUint16(used + 2, true), 1, "publish accepted reply before rejecting later malformed head");
        assert.ok(io.port_read8(common + 20) & 64);
        setup();
        mem.setUint32(table + 16, 0xa0000, true); mem.setUint16(avail + 2, 1, true);
        io.port_write16(notify, 0);
        assert.ok(io.port_read8(common + 20) & 64, "direct replies must target RAM, not VGA MMIO");
        setup();
        assert.equal(request(1, arena, 16 * 1024 * 1024), 0, "register again after a reset");
        // The renderer going away is visible to the guest again
        channel.host.post({ type: "available", value: false });
        assert.equal(request(2, 0, 32 + envelope.length), 3);
        console.log("virtio_v86gl_test: PCI capabilities, negotiation, real virtqueue, validation, renderer channel, reset, state, wrap and BAR relocation passed");
    } finally { await emulator.destroy(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/glbridge/vx_corpus_browser_test.html                                               0000644 0000000 0000000 00000006355 00000000000 020336  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VX: a corpus of Venus pipelines</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The pipelines a guest made on Venus, as tests/x64/gpu_remote_renderer.mjs
// dumps them (A64_ANDROID_SHADER_DIR: <hash>.spv and pipelines.jsonl, and
// index.json, the list of the shaders), made again by VX: each shader
// translated, each pipeline created on WebGPU. ?dir=<the directory, from the
// repository's root>. PASS when none fails; the failures by message.
import { GXWriter, VX, VX_MAGIC } from "../../src/graphics_adapters/renderer_protocol.js";

const result = document.getElementById("result");
const dir = new URLSearchParams(location.search).get("dir") || "build/a64-android/shader-corpus";

(async () => {
    try {
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        const device = end(0, 1);
        const done = new Map();
        device.listen(message => {
            if(message.type === "done") { const resolve = done.get(message.seq); if(resolve) resolve(); }
        });
        let seq = 0;
        const w = new GXWriter(VX_MAGIC);
        const send = () => {
            const s = ++seq;
            const finished = new Promise(resolve => done.set(s, resolve));
            device.post({ type: "submit", seq: s, bytes: w.finish(), stream: "vx" });
            return finished;
        };
        const json = o => new TextEncoder().encode(JSON.stringify(o));
        const root = "../../" + dir + "/";
        const shaders = await (await fetch(root + "index.json")).json();
        const ids = new Map();
        let next = 1;
        for(const name of shaders)
        {
            const spirv = new Uint8Array(await (await fetch(root + name)).arrayBuffer());
            ids.set(name, next);
            w.command(VX.SHADER_CREATE, [next++, spirv.length], spirv);
        }
        await send();
        const lines = (await (await fetch(root + "pipelines.jsonl")).text()).split("\n").filter(Boolean);
        const seen = new Set();
        let pipelines = 0;
        for(const line of lines)
        {
            const d = JSON.parse(line);
            if(d.stages.some(s => !ids.has(s.file))) continue;
            for(const s of d.stages) s.shader = ids.get(s.file);
            const key = JSON.stringify(d);
            if(seen.has(key)) continue;
            seen.add(key);
            w.command(VX.PIPELINE_CREATE, [next++], json(d));
            pipelines++;
            if(pipelines % 50 === 0) await send();
        }
        await send();
        // (pipelines are made asynchronously: their failures come in later)
        await new Promise(resolve => setTimeout(resolve, 3000));
        const vx = renderer.vx;
        const failed = vx.warnings.filter(text => /failed|WebGPU/.test(text));
        result.textContent = (failed.length ? "FAIL " : "PASS ") + shaders.length + " shaders, " + pipelines + " pipelines\n" + vx.warnings.join("\n");
    } catch(e) {
        result.textContent = "FAIL " + (e.stack || e);
    }
})();
</script>
                                                                                                                                                                                                                                                                                   source/v64/tests/glbridge/vx_transfer_browser_test.html                                             0000644 0000000 0000000 00000261755 00000000000 020656  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>VX: Venus's transfers on WebGPU</title>
<pre id="result">RUNNING</pre>
<script src="../../build/glbridge/libv86-webgpu.js"></script>
<script type="module">
// The renderer half of virtio-gpu's Venus contexts (vx/vx_executor.js),
// through the page's renderer (svga_renderer.js) as the device drives it:
// VX batches of memory and images, a submission's transfer commands
// (copies, fills, updates, buffer-image copies of WebGPU's pitch and of
// others, clears, blits, resolves), and readbacks of memory.
import { GXWriter, VX, VX_MAGIC, QUERY_REGION_BYTES } from "../../src/graphics_adapters/renderer_protocol.js";

const result = document.getElementById("result");
const checks = [];
const check = (value, message) => { if(!value) throw new Error(message); checks.push(message); };
const f32 = v => new Uint32Array(new Float32Array([v]).buffer)[0];

(async () => {
    try {
        const handlers = [null, null];
        const end = (self, other) => ({ post: message => handlers[other] && handlers[other](message), listen: handler => { handlers[self] = handler; } });
        const renderer = globalThis.V86SVGARenderer(end(1, 0), {});
        const device = end(0, 1);
        const answers = new Map(), done = new Map();
        device.listen(message => {
            if(message.type === "write" && message.offset === QUERY_REGION_BYTES)
            {
                const v = new DataView(message.bytes.buffer, message.bytes.byteOffset);
                answers.set(v.getUint32(0, true), v.getUint32(12, true) === 1 ? message.bytes.slice(16, 16 + v.getUint32(4, true)) : null);
            }
            if(message.type === "done") { const resolve = done.get(message.seq); if(resolve) resolve(); }
            if(message.type === "lost") throw new Error("renderer lost: " + message.reason);
        });
        let seq = 0, request = 1;
        const w = new GXWriter(VX_MAGIC);
        const send = () => {
            const s = ++seq;
            const finished = new Promise(resolve => done.set(s, resolve));
            device.post({ type: "submit", seq: s, bytes: w.finish(), stream: "vx" });
            return finished;
        };
        /** read memory back: the bytes */
        const read = async (id, offset, length) => {
            const r = request++;
            w.command(VX.MEMORY_READ, [id, offset, 0, length, r]);
            await send();
            return answers.get(r);
        };

        // Memory: writes, copies, fills, updates
        const A = 1, B = 2;
        w.command(VX.MEMORY_CREATE, [A, 4096, 0]);
        w.command(VX.MEMORY_CREATE, [B, 4096, 0]);
        const pattern = Uint8Array.from({ length: 4096 }, (_, i) => i * 7 & 0xFF);
        w.command(VX.MEMORY_WRITE, [A, 0, 0, 4096], pattern);
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER, [A, 64, 0, B, 128, 0, 64, 0]);
        w.command(VX.FILL_BUFFER, [B, 512, 0, 64, 0, 0xAABBCCDD]);
        w.command(VX.FILL_BUFFER, [B, 1024, 0, 16, 0, 0]);
        w.command(VX.UPDATE_BUFFER, [B, 768, 0, 6], Uint8Array.from([1, 2, 3, 4, 5, 6]));
        w.command(VX.END, []);
        let bytes = await read(B, 0, 2048);
        check(bytes && bytes.length === 2048, "memory read back");
        check(bytes.slice(128, 192).every((v, i) => v === pattern[64 + i]), "COPY_BUFFER");
        check(new Uint32Array(bytes.buffer, 512, 16).every(v => v === 0xAABBCCDD), "FILL_BUFFER with a value");
        check(bytes.slice(768, 774).join() === "1,2,3,4,5,6", "UPDATE_BUFFER");
        check((await read(A, 3, 5)).join() === Array.from(pattern.slice(3, 8)).join(), "a read at an odd offset");
        // copies not in whole dwords (VX's compute shader): 7 bytes from 3 to 1029
        // of another memory, the bytes around them kept; 6 within one memory
        w.command(VX.BEGIN, []);
        w.command(VX.FILL_BUFFER, [B, 1024, 0, 16, 0, 0x55555555]);
        w.command(VX.COPY_BUFFER, [A, 3, 0, B, 1029, 0, 7, 0]);
        w.command(VX.COPY_BUFFER, [B, 1030, 0, B, 1501, 0, 6, 0]);
        w.command(VX.END, []);
        bytes = await read(B, 1024, 512);
        check(bytes.slice(0, 16).join() === [85, 85, 85, 85, 85, ...pattern.slice(3, 10), 85, 85, 85, 85].join() &&
            bytes.slice(477, 483).join() === Array.from(pattern.slice(4, 10)).join(),
            "buffer copies not in whole dwords: " + bytes.slice(0, 16).join() + " / " + bytes.slice(477, 483).join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // An image of R8G8B8A8_UNORM, 16x16, 2 mips: in from memory at a
        // pitch of 64 bytes (row by row), out at 256 (WebGPU's)
        const IMG = 3, IMG2 = 4;
        w.command(VX.TEXTURE_CREATE, [IMG, 37, 1, 16, 16, 1, 2, 1, 1, 0x17, 0]);
        w.command(VX.TEXTURE_CREATE, [IMG2, 37, 1, 16, 16, 1, 1, 1, 1, 0x17, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER_IMAGE, [1, A, 0, 0, 0, 0, IMG, 1, 0, 0, 1, 0, 0, 0, 16, 16, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, IMG, 1, 0, 0, 1, 0, 0, 0, 16, 16, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 4096);
        check(Array.from({ length: 16 }).every((_, r) => bytes.slice(r * 256, r * 256 + 64).every((v, i) => v === pattern[r * 64 + i])),
            "COPY_BUFFER_IMAGE: in at a pitch of 64, out at 256");

        // CLEAR_IMAGE (0.5, 0.25, 1, 0) on mip 1; COPY_IMAGE of mip 0 into the other image
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [IMG, 1, 1, 1, 0, 1, f32(0.5), f32(0.25), f32(1), f32(0)]);
        w.command(VX.COPY_IMAGE, [IMG, 1, 0, 0, 4, 4, 0, IMG2, 1, 0, 0, 0, 0, 0, 8, 8, 1, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 0, 0, IMG, 1, 1, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 1024, 0, 0, 0, IMG2, 1, 0, 0, 1, 0, 0, 0, 16, 16, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 4096);
        check(bytes.slice(0, 4).join() === "128,64,255,0", "CLEAR_IMAGE of mip 1: " + bytes.slice(0, 4).join());
        check(bytes.slice(1024, 1028).join() === Array.from(pattern.slice(4 * 64 + 16, 4 * 64 + 20)).join(), "COPY_IMAGE");

        // BLIT_IMAGE: mip 0 (16x16) into IMG2's 8x8 corner, flipped horizontally, nearest
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [IMG2, 1, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.BLIT_IMAGE, [IMG, 0, 0, 0, 0, 0, 16, 16, 1, IMG2, 0, 0, 8, 0, 0, 0, 8, 1, 1, 0]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, IMG2, 1, 0, 0, 1, 0, 0, 0, 16, 16, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 4096);
        // dst (0, 0) of the flipped blit samples the source near (15, 0)
        const src = (x, y) => Array.from(pattern.slice((y * 16 + x) * 4, (y * 16 + x) * 4 + 4)).join();
        check(bytes.slice(0, 4).join() === src(15, 1) || bytes.slice(0, 4).join() === src(14, 0) || bytes.slice(0, 4).join() === src(15, 0),
            "BLIT_IMAGE, flipped: " + bytes.slice(0, 4).join() + " vs " + src(15, 0));
        check(bytes.slice(8 * 4, 8 * 4 + 4).join() === "0,0,0,0", "outside of the blit: the clear");

        // Depth: D32_SFLOAT cleared to 0.75, copied out
        const DEPTH = 5;
        w.command(VX.TEXTURE_CREATE, [DEPTH, 126, 1, 8, 8, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [DEPTH, 2, 0, 1, 0, 1, f32(0.75), 0, 0, 0]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, DEPTH, 2, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 256);
        check(new Float32Array(bytes.buffer, 0, 1)[0] === 0.75, "depth cleared and copied: " + new Float32Array(bytes.buffer, 0, 1)[0]);

        // MSAA: a 4x image cleared, resolved into a 1x one
        const MS = 6, RES = 7;
        w.command(VX.TEXTURE_CREATE, [MS, 37, 1, 8, 8, 1, 1, 1, 4, 0x10, 0]);
        w.command(VX.TEXTURE_CREATE, [RES, 37, 1, 8, 8, 1, 1, 1, 1, 0x13, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [MS, 1, 0, 1, 0, 1, f32(1), f32(0), f32(0.5), f32(1)]);
        w.command(VX.RESOLVE_IMAGE, [MS, 0, 0, 0, 0, RES, 0, 0, 0, 0, 8, 8, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, RES, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 4);
        check(bytes.join() === "255,0,128,255", "RESOLVE_IMAGE: " + bytes.join());

        // a resolve of a region (4x4 from (2, 2)) into an image of another
        // size (16x16) at (8, 4): the rest of the image keeps its clear
        const BIG = 8;
        w.command(VX.TEXTURE_CREATE, [BIG, 37, 1, 16, 16, 1, 1, 1, 1, 0x13, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [BIG, 1, 0, 1, 0, 1, f32(0), f32(1), f32(0), f32(1)]);
        w.command(VX.RESOLVE_IMAGE, [MS, 0, 0, 2, 2, BIG, 0, 0, 8, 4, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, BIG, 1, 0, 0, 1, 0, 0, 0, 16, 16, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 4096);
        const pixel = (x, y) => bytes.slice(y * 256 + x * 4, y * 256 + x * 4 + 4).join();
        check(pixel(8, 4) === "255,0,128,255" && pixel(11, 7) === "255,0,128,255", "RESOLVE_IMAGE of a region: " + pixel(8, 4) + " " + pixel(11, 7));
        check(pixel(7, 4) === "0,255,0,255" && pixel(12, 4) === "0,255,0,255" && pixel(8, 8) === "0,255,0,255",
            "outside the resolved region: the clear: " + pixel(7, 4) + " " + pixel(12, 4) + " " + pixel(8, 8));

        // Transform feedback (VK_EXT_transform_feedback, vx/naga/src/xfb.rs): the
        // SPIR-V of this vertex shader (glslc -fshader-stage=vert --target-env=vulkan1.1):
        //   layout(location = 0) in vec2 a_pos;
        //   layout(location = 1) in vec4 a_color;   // R8G8B8A8_UNORM
        //   layout(location = 2) in uint a_id;      // R32_UINT
        //   layout(set = 0, binding = 0) uniform U { vec4 scale; } u;
        //   layout(location = 0, xfb_buffer = 0, xfb_offset = 16, xfb_stride = 32) out vec4 v_color;
        //   layout(location = 1, xfb_buffer = 1, xfb_offset = 0, xfb_stride = 4) out flat uint v_id;
        //   out gl_PerVertex { layout(xfb_buffer = 0, xfb_offset = 0) vec4 gl_Position; };
        //   void main() { gl_Position = vec4(a_pos * u.scale.xy, 0.0, 1.0); v_color = a_color;
        //       v_id = a_id * 10u + uint(gl_VertexIndex) + 100u * uint(gl_InstanceIndex); }
        // 3 points, 2 instances, rasterizer discard: buffer 0 gets the position
        // and the color (32 bytes a vertex), buffer 1 the id; End writes the
        // counters, the query the primitives; a second draw resumes from the
        // counters and fits 2 of its 3 points into buffer 0's 256 bytes
        const XFB_SPV = Uint8Array.from(atob("AwIjBwADAQAKAA0ANwAAAAAAAAARAAIAAQAAABEAAgA1AAAACwAGAAEAAABHTFNMLnN0ZC40NTAAAAAADgADAAAAAAABAAAADwANAAAAAAAEAAAAbWFpbgAAAAAKAAAADwAAACAAAAAiAAAAJgAAACgAAAAtAAAAMgAAABAAAwAEAAAACwAAAAMAAwACAAAAwgEAAAQACgBHTF9HT09HTEVfY3BwX3N0eWxlX2xpbmVfZGlyZWN0aXZlAAAEAAgAR0xfR09PR0xFX2luY2x1ZGVfZGlyZWN0aXZlAAUABAAEAAAAbWFpbgAAAAAFAAYACAAAAGdsX1BlclZlcnRleAAAAAAGAAYACAAAAAAAAABnbF9Qb3NpdGlvbgAFAAMACgAAAAAAAAAFAAQADwAAAGFfcG9zAAAABQADABEAAABVAAAABgAFABEAAAAAAAAAc2NhbGUAAAAFAAMAEwAAAHUAAAAFAAQAIAAAAHZfY29sb3IABQAEACIAAABhX2NvbG9yAAUABAAmAAAAdl9pZAAAAAAFAAQAKAAAAGFfaWQAAAAABQAGAC0AAABnbF9WZXJ0ZXhJbmRleAAABQAHADIAAABnbF9JbnN0YW5jZUluZGV4AAAAAEgABQAIAAAAAAAAACMAAAAAAAAASAAFAAgAAAAAAAAACwAAAAAAAABHAAMACAAAAAIAAABHAAQACgAAACQAAAAAAAAARwAEAAoAAAAlAAAAIAAAAEcABAAPAAAAHgAAAAAAAABIAAUAEQAAAAAAAAAjAAAAAAAAAEcAAwARAAAAAgAAAEcABAATAAAAIgAAAAAAAABHAAQAEwAAACEAAAAAAAAARwAEACAAAAAeAAAAAAAAAEcABAAgAAAAJAAAAAAAAABHAAQAIAAAACUAAAAgAAAARwAEACAAAAAjAAAAEAAAAEcABAAiAAAAHgAAAAEAAABHAAMAJgAAAA4AAABHAAQAJgAAAB4AAAABAAAARwAEACYAAAAkAAAAAQAAAEcABAAmAAAAJQAAAAQAAABHAAQAJgAAACMAAAAAAAAARwAEACgAAAAeAAAAAgAAAEcABAAtAAAACwAAACoAAABHAAQAMgAAAAsAAAArAAAAEwACAAIAAAAhAAMAAwAAAAIAAAAWAAMABgAAACAAAAAXAAQABwAAAAYAAAAEAAAAHgADAAgAAAAHAAAAIAAEAAkAAAADAAAACAAAADsABAAJAAAACgAAAAMAAAAVAAQACwAAACAAAAABAAAAKwAEAAsAAAAMAAAAAAAAABcABAANAAAABgAAAAIAAAAgAAQADgAAAAEAAAANAAAAOwAEAA4AAAAPAAAAAQAAAB4AAwARAAAABwAAACAABAASAAAAAgAAABEAAAA7AAQAEgAAABMAAAACAAAAIAAEABQAAAACAAAABwAAACsABAAGAAAAGQAAAAAAAAArAAQABgAAABoAAAAAAIA/IAAEAB4AAAADAAAABwAAADsABAAeAAAAIAAAAAMAAAAgAAQAIQAAAAEAAAAHAAAAOwAEACEAAAAiAAAAAQAAABUABAAkAAAAIAAAAAAAAAAgAAQAJQAAAAMAAAAkAAAAOwAEACUAAAAmAAAAAwAAACAABAAnAAAAAQAAACQAAAA7AAQAJwAAACgAAAABAAAAKwAEACQAAAAqAAAACgAAACAABAAsAAAAAQAAAAsAAAA7AAQALAAAAC0AAAABAAAAKwAEACQAAAAxAAAAZAAAADsABAAsAAAAMgAAAAEAAAA2AAUAAgAAAAQAAAAAAAAAAwAAAPgAAgAFAAAAPQAEAA0AAAAQAAAADwAAAEEABQAUAAAAFQAAABMAAAAMAAAAPQAEAAcAAAAWAAAAFQAAAE8ABwANAAAAFwAAABYAAAAWAAAAAAAAAAEAAACFAAUADQAAABgAAAAQAAAAFwAAAFEABQAGAAAAGwAAABgAAAAAAAAAUQAFAAYAAAAcAAAAGAAAAAEAAABQAAcABwAAAB0AAAAbAAAAHAAAABkAAAAaAAAAQQAFAB4AAAAfAAAACgAAAAwAAAA+AAMAHwAAAB0AAAA9AAQABwAAACMAAAAiAAAAPgADACAAAAAjAAAAPQAEACQAAAApAAAAKAAAAIQABQAkAAAAKwAAACkAAAAqAAAAPQAEAAsAAAAuAAAALQAAAHwABAAkAAAALwAAAC4AAACAAAUAJAAAADAAAAArAAAALwAAAD0ABAALAAAAMwAAADIAAAB8AAQAJAAAADQAAAAzAAAAhAAFACQAAAA1AAAAMQAAADQAAACAAAUAJAAAADYAAAAwAAAANQAAAD4AAwAmAAAANgAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const SH = 20, PIPE = 21, VB0 = 22, VB1 = 23, UB = 24, XB0 = 25, XB1 = 26, CNT = 27, XRT = 28, XRTV = 29, QP = 30, QPM = 31;
        for(const [id, size] of [[VB0, 256], [VB1, 256], [UB, 256], [XB0, 256], [XB1, 256], [CNT, 256], [QPM, 256]]) w.command(VX.MEMORY_CREATE, [id, size, 0]);
        w.command(VX.MEMORY_WRITE, [VB0, 0, 0, 24], new Uint8Array(Float32Array.from([1, 2, 3, 4, 5, 6]).buffer));
        const vb1 = new DataView(new ArrayBuffer(24));
        [[255, 0, 128, 51, 7], [0, 255, 0, 255, 8], [51, 102, 153, 204, 9]].forEach(([r, g, bl, a, id], i) => {
            vb1.setUint8(i * 8, r); vb1.setUint8(i * 8 + 1, g); vb1.setUint8(i * 8 + 2, bl); vb1.setUint8(i * 8 + 3, a); vb1.setUint32(i * 8 + 4, id, true);
        });
        w.command(VX.MEMORY_WRITE, [VB1, 0, 0, 24], new Uint8Array(vb1.buffer));
        w.command(VX.MEMORY_WRITE, [UB, 0, 0, 16], new Uint8Array(Float32Array.from([0.5, 2, 0, 0]).buffer));
        w.command(VX.TEXTURE_CREATE, [XRT, 37, 1, 8, 8, 1, 1, 1, 1, 0x13, 0]);
        w.command(VX.VIEW_CREATE, [XRTV, XRT, 1, 37, 1, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.QUERY_POOL_CREATE, [QP, 1000028004, 1]);
        w.command(VX.SHADER_CREATE, [SH, XFB_SPV.length], XFB_SPV);
        const json = o => new TextEncoder().encode(JSON.stringify(o));
        w.command(VX.PIPELINE_CREATE, [PIPE], json({ kind: "graphics", stages: [{ shader: SH, stage: 1, entry: "main", constants: {} }],
            buffers: [{ binding: 0, stride: 8, rate: 0 }, { binding: 1, stride: 8, rate: 0 }],
            attributes: [{ location: 0, binding: 0, format: 103, offset: 0 }, { location: 1, binding: 1, format: 37, offset: 0 }, { location: 2, binding: 1, format: 98, offset: 4 }],
            topology: 0, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: true, depth_bias: null, samples: 1, sample_mask: 0xFFFFFFFF,
            alpha_to_coverage: false, depth: null, depth_format: 0, targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 1, push_size: 0 }));
        const xfb_draw = (draw, resume) => {
            w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }], depth: null, width: 8, height: 8 }));
            w.command(VX.BIND_PIPELINE, [PIPE]);
            w.command(VX.SET_BIND_GROUP, [0, 1, 0, 0, 6, UB, 0, 0, 0, 16]);
            w.command(VX.SET_VERTEX_BUFFER, [0, VB0, 0, 0, 256, 0]);
            w.command(VX.SET_VERTEX_BUFFER, [1, VB1, 0, 0, 256, 0]);
            w.command(VX.XFB_BIND, [0, XB0, 0, 0, 256, 0]);
            w.command(VX.XFB_BIND, [1, XB1, 0, 0, 256, 0]);
            w.command(VX.BEGIN_QUERY, [QP, 0]);
            w.command(VX.XFB_BEGIN, resume ? [0, 2, CNT, 0, 0, CNT, 4, 0] : [0, 0]);
            w.command(VX.DRAW, draw);
            w.command(VX.XFB_END, [0, 2, CNT, 0, 0, CNT, 4, 0]);
            w.command(VX.END_QUERY, [QP, 0, QPM]);
            w.command(VX.END_PASS, []);
        };
        w.command(VX.BEGIN, []);
        xfb_draw([3, 2, 0, 0], false);
        w.command(VX.END, []);
        const xb0 = new Float32Array((await read(XB0, 0, 256)).buffer), xb1 = new Uint32Array((await read(XB1, 0, 256)).buffer);
        const cnt = new Uint32Array((await read(CNT, 0, 8)).buffer), qp = new Uint32Array((await read(QPM, 0, 16)).buffer);
        const near = (a, b) => Math.abs(a - b) < 1e-5;
        const positions = [0, 1, 2, 3, 4, 5].map(k => Array.from(xb0.subarray(k * 8, k * 8 + 4)));
        check(positions.every((p, k) => near(p[0], [0.5, 1.5, 2.5][k % 3]) && near(p[1], [4, 8, 12][k % 3]) && p[2] === 0 && p[3] === 1),
            "transform feedback: the positions, instance by instance: " + JSON.stringify(positions) + " (" + renderer.vx.warnings.join("; ") + ")");
        check(near(xb0[4], 1) && near(xb0[5], 0) && near(xb0[6], 128 / 255) && near(xb0[7], 51 / 255) && near(xb0[8 + 5], 1),
            "transform feedback: the colors (R8G8B8A8_UNORM): " + Array.from(xb0.subarray(4, 8)));
        check(Array.from(xb1.subarray(0, 6)).join() === "70,81,92,170,181,192", "transform feedback: the ids (vertex and instance indices): " + Array.from(xb1.subarray(0, 6)));
        check(cnt[0] === 192 && cnt[1] === 24, "transform feedback: the counters End wrote: " + Array.from(cnt));
        check(qp[0] === 6 && qp[2] === 6, "transform feedback: the query, 6 primitives written of 6: " + Array.from(qp));
        w.command(VX.BEGIN, []);
        xfb_draw([3, 1, 0, 1], true);
        w.command(VX.END, []);
        const again = new Uint32Array((await read(XB1, 0, 64)).buffer), cnt2 = new Uint32Array((await read(CNT, 0, 8)).buffer);
        const qp2 = new Uint32Array((await read(QPM, 0, 16)).buffer);
        check(Array.from(again.subarray(6, 9)).join() === "170,181,0" && cnt2[0] === 256 && cnt2[1] === 32 && qp2[0] === 2 && qp2[2] === 3,
            "transform feedback: resumed from the counters, 2 of 3 points fit: " + [Array.from(again.subarray(6, 9)), Array.from(cnt2), Array.from(qp2)].join(" "));

        // Dynamic stencil masks (VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK, _WRITE_MASK):
        // WebGPU's are the pipeline's, so VX makes a variant per pair. The SPIR-V
        // (naga, from WGSL) of a vertex shader drawing the whole target from
        // vertex_index, and of a fragment shader writing green; a D24S8 target
        // cleared to 0, a draw replacing with 0xFF through write mask 0x0F, then
        // one replacing with 0x3C through 0xF0: 0x3F, the stencil read back
        const STENCIL_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAHQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAAAAAADQAAAG1haW4AAAAACAAAAAsAAABHAAQACAAAAAsAAAAqAAAARwAEAAsAAAALAAAAAAAAABMAAgACAAAAFQAEAAMAAAAgAAAAAAAAABYAAwAFAAAAIAAAABcABAAEAAAABQAAAAQAAAAXAAQABgAAAAUAAAACAAAAIAAEAAkAAAABAAAAAwAAADsABAAJAAAACAAAAAEAAAAgAAQADAAAAAMAAAAEAAAAOwAEAAwAAAALAAAAAwAAACEAAwAOAAAAAgAAACsABAADAAAADwAAAAEAAAArAAQABQAAABAAAAAAAABAKwAEAAUAAAARAAAAAACAPywABQAGAAAAEgAAABEAAAARAAAAKwAEAAUAAAATAAAAAAAAADYABQACAAAADQAAAAAAAAAOAAAA+AACAAcAAAA9AAQAAwAAAAoAAAAIAAAA+QACABQAAAD4AAIAFAAAAMcABQADAAAAFQAAAAoAAAAPAAAAcAAEAAUAAAAWAAAAFQAAAMIABQADAAAAFwAAAAoAAAAPAAAAcAAEAAUAAAAYAAAAFwAAAFAABQAGAAAAGQAAABYAAAAYAAAAjgAFAAYAAAAaAAAAGQAAABAAAACDAAUABgAAABsAAAAaAAAAEgAAAFAABgAEAAAAHAAAABsAAAATAAAAEQAAAD4AAwALAAAAHAAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const STENCIL_FS = Uint8Array.from(atob("AwIjBwAAAQAcAAAADgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABgAEAAAACAAAAG1haW4AAAAABgAAABAAAwAIAAAABwAAAEcABAAGAAAAHgAAAAAAAAATAAIAAgAAABYAAwAEAAAAIAAAABcABAADAAAABAAAAAQAAAAgAAQABwAAAAMAAAADAAAAOwAEAAcAAAAGAAAAAwAAACEAAwAJAAAAAgAAACsABAAEAAAACgAAAAAAAAArAAQABAAAAAsAAAAAAIA/LAAHAAMAAAAMAAAACgAAAAsAAAAKAAAACwAAADYABQACAAAACAAAAAAAAAAJAAAA+AACAAUAAAD5AAIADQAAAPgAAgANAAAAPgADAAYAAAAMAAAA/QABADgAAQA="), c => c.charCodeAt(0));
        const SVS = 40, SFS = 41, SPIPE = 42, DS = 43, DSV = 44;
        w.command(VX.SHADER_CREATE, [SVS, STENCIL_VS.length], STENCIL_VS);
        w.command(VX.SHADER_CREATE, [SFS, STENCIL_FS.length], STENCIL_FS);
        w.command(VX.TEXTURE_CREATE, [DS, 129, 1, 8, 8, 1, 1, 1, 1, 0x21, 0]);
        w.command(VX.VIEW_CREATE, [DSV, DS, 1, 129, 6, 0, 1, 0, 1, 0, 0, 0, 0]);
        const replace = { fail: 0, pass: 2, depth_fail: 0, compare: 7, read_mask: 0, write_mask: 0, reference: 0 };
        w.command(VX.PIPELINE_CREATE, [SPIPE], json({ kind: "graphics",
            stages: [{ shader: SVS, stage: 1, entry: "main", constants: {} }, { shader: SFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 4, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false,
            depth: { test: false, write: false, compare: 7, stencil: true, front: replace, back: replace }, depth_format: 129,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [6, 7, 8],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        const stencil_draw = (first, write_mask, reference) => {
            w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }],
                depth: { view: DSV, load: 1, clear_depth: 1, store: 0, stencil_load: first ? 1 : 0, clear_stencil: 0, stencil_store: 0 }, width: 8, height: 8 }));
            w.command(VX.BIND_PIPELINE, [SPIPE]);
            w.command(VX.SET_STENCIL_COMPARE_MASK, [3, 0xFF]);
            w.command(VX.SET_STENCIL_WRITE_MASK, [3, write_mask]);
            w.command(VX.SET_STENCIL_REFERENCE, [3, reference]);
            w.command(VX.DRAW, [4, 1, 0, 0]);
            w.command(VX.END_PASS, []);
        };
        w.command(VX.BEGIN, []);
        stencil_draw(true, 0x0F, 0xFF);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 0, 0, DS, 4, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 64);
        check(bytes.every(v => v === 0x0F), "dynamic stencil write mask 0x0F: " + bytes.slice(0, 8).join() + " (" + renderer.vx.warnings.join("; ") + ")");
        w.command(VX.BEGIN, []);
        stencil_draw(false, 0xF0, 0x3C);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 0, 0, DS, 4, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 256, 0, 0, 0, XRT, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 512);
        check(bytes.slice(0, 64).every(v => v === 0x3F), "then write mask 0xF0 with 0x3C: " + bytes.slice(0, 8).join());
        check(bytes.slice(256, 260).join() === "0,255,0,255", "the draws' color: " + bytes.slice(256, 260).join());

        // Triangle fans (WebGPU has none: lists through an index buffer of
        // Vulkan's (i + 1, i + 2, 0)) and indexed strips (a variant with the
        // strip index format): the shaders above; a fan of the 4 corners
        // covers all but the wedge right of the diagonals, an indexed strip
        // of them the whole target
        const FANP = 45, STRIPP = 46, IB = 47;
        const plain = topology => json({ kind: "graphics",
            stages: [{ shader: SVS, stage: 1, entry: "main", constants: {} }, { shader: SFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false, depth: null, depth_format: 0,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 });
        w.command(VX.PIPELINE_CREATE, [FANP], plain(5));
        w.command(VX.PIPELINE_CREATE, [STRIPP], plain(4));
        w.command(VX.MEMORY_CREATE, [IB, 256, 0]);
        w.command(VX.MEMORY_WRITE, [IB, 0, 0, 8], new Uint8Array(Uint16Array.from([0, 1, 2, 3]).buffer));
        const one_draw = (pipeline, indexed) => {
            w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }], depth: null, width: 8, height: 8 }));
            w.command(VX.BIND_PIPELINE, [pipeline]);
            if(indexed)
            {
                w.command(VX.SET_INDEX_BUFFER, [IB, 0, 0, 8, 0, 0]);
                w.command(VX.DRAW_INDEXED, [4, 1, 0, 0, 0]);
            }
            else w.command(VX.DRAW, [4, 1, 0, 0]);
            w.command(VX.END_PASS, []);
            w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, XRT, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        };
        w.command(VX.BEGIN, []);
        one_draw(FANP, false);
        w.command(VX.END, []);
        bytes = await read(B, 0, 2048);
        check(pixel(0, 4) === "0,255,0,255" && pixel(7, 4) === "0,0,0,0", "a triangle fan: " + pixel(0, 4) + " " + pixel(7, 4) +
            " (" + renderer.vx.warnings.join("; ") + ")");
        w.command(VX.BEGIN, []);
        one_draw(STRIPP, true);
        w.command(VX.END, []);
        bytes = await read(B, 0, 2048);
        check(pixel(0, 4) === "0,255,0,255" && pixel(7, 4) === "0,255,0,255", "an indexed triangle strip: " + pixel(0, 4) + " " + pixel(7, 4));

        // Matrices of a std140 block that naga does not read as they are (vx/naga/src/layout.rs):
        // a column major mat2 (columns 16 bytes apart), a row major mat4x3 and an
        // array of 2 row major mat2x3, each read whole, by column and by element,
        // and the whole block loaded, by a compute shader (SPIR-V assembled by
        // hand) into a storage buffer; the block's float i is i
        const STD140_SPV = Uint8Array.from(atob("AwIjBwAAAQAAAAAApwAAAAAAAAARAAIAAQAAAA4AAwAAAAAAAQAAAA8ABQAFAAAAAQAAAG1haW4AAAAAEAAGAAEAAAARAAAAAQAAAAEAAAABAAAARwADAAIAAAACAAAASAAFAAIAAAAAAAAAIwAAAAAAAABIAAQAAgAAAAAAAAAFAAAASAAFAAIAAAAAAAAABwAAABAAAABIAAUAAgAAAAEAAAAjAAAAIAAAAEgABAACAAAAAQAAAAQAAABIAAUAAgAAAAEAAAAHAAAAEAAAAEgABQACAAAAAgAAACMAAABQAAAASAAEAAIAAAACAAAABAAAAEgABQACAAAAAgAAAAcAAAAQAAAARwAEAAMAAAAGAAAAMAAAAEcABAAEAAAAIgAAAAAAAABHAAQABAAAACEAAAAAAAAARwADAAUAAAACAAAASAAFAAUAAAAAAAAAIwAAAAAAAABHAAQABgAAAAYAAAAEAAAARwAEAAcAAAAiAAAAAAAAAEcABAAHAAAAIQAAAAEAAAATAAIACAAAACEAAwAJAAAACAAAABYAAwAKAAAAIAAAABUABAALAAAAIAAAAAEAAAAXAAQADAAAAAoAAAACAAAAFwAEAA0AAAAKAAAAAwAAABcABAAOAAAACgAAAAQAAAAYAAQADwAAAAwAAAACAAAAGAAEABAAAAANAAAABAAAABgABAARAAAADQAAAAIAAAArAAQACwAAABIAAAAAAAAAKwAEAAsAAAATAAAAAQAAACsABAALAAAAFAAAAAIAAAArAAQACwAAABUAAAADAAAAKwAEAAsAAAAWAAAABAAAACsABAALAAAAFwAAAAUAAAArAAQACwAAABgAAAAGAAAAKwAEAAsAAAAZAAAABwAAACsABAALAAAAGgAAAAgAAAArAAQACwAAABsAAAAJAAAAKwAEAAsAAAAcAAAACgAAACsABAALAAAAHQAAAAsAAAArAAQACwAAAB4AAAAMAAAAKwAEAAsAAAAfAAAADQAAACsABAALAAAAIAAAAA4AAAArAAQACwAAACEAAAAPAAAAKwAEAAsAAAAiAAAAEAAAACsABAALAAAAIwAAABEAAAArAAQACwAAACQAAAASAAAAKwAEAAsAAAAlAAAAEwAAACsABAALAAAAJgAAABQAAAArAAQACwAAACcAAAAVAAAAKwAEAAsAAAAoAAAAFgAAACsABAALAAAAKQAAABcAAAArAAQACwAAACoAAAAYAAAAKwAEAAsAAAArAAAAGQAAACsABAALAAAALAAAABoAAAArAAQACwAAAC0AAAAbAAAAKwAEAAsAAAAuAAAAHAAAACsABAALAAAALwAAAB0AAAArAAQACwAAADAAAAAeAAAAKwAEAAsAAAAxAAAAHwAAACsABAALAAAAMgAAACAAAAArAAQACwAAADMAAAAhAAAAKwAEAAsAAAA0AAAAIgAAACsABAALAAAANQAAACMAAAArAAQACwAAADYAAAAkAAAAKwAEAAsAAAA3AAAAJQAAACsABAALAAAAOAAAACYAAAArAAQACwAAADkAAAAnAAAAKwAEAAsAAAA6AAAAKAAAACsABAALAAAAOwAAACkAAAArAAQACwAAADwAAAAqAAAAKwAEAAsAAAA9AAAAKwAAACsABAALAAAAPgAAACwAAAArAAQACwAAAD8AAAAtAAAAKwAEAAsAAABAAAAALgAAACsABAALAAAAQQAAAC8AAAArAAQACwAAAEIAAAAwAAAAKwAEAAsAAABDAAAAMQAAACsABAALAAAARAAAADIAAAArAAQACwAAAEUAAAAzAAAAKwAEAAsAAABGAAAANAAAACsABAALAAAARwAAADUAAAArAAQACwAAAEgAAAA2AAAAKwAEAAsAAABJAAAANwAAACsABAALAAAASgAAADgAAAArAAQACwAAAEsAAAA5AAAAKwAEAAsAAABMAAAAOgAAACsABAALAAAATQAAADsAAAArAAQACwAAAE4AAAA8AAAAKwAEAAsAAABPAAAAPQAAACsABAALAAAAUAAAAD4AAAArAAQACwAAAFEAAAA/AAAAHAAEAAMAAAARAAAAFAAAAB4ABQACAAAADwAAABAAAAADAAAAIAAEAFIAAAACAAAAAgAAADsABABSAAAABAAAAAIAAAAdAAMABgAAAAoAAAAeAAMABQAAAAYAAAAgAAQAUwAAAAwAAAAFAAAAOwAEAFMAAAAHAAAADAAAACAABABUAAAAAgAAAA8AAAAgAAQAVQAAAAIAAAAMAAAAIAAEAFYAAAACAAAACgAAACAABABXAAAAAgAAABAAAAAgAAQAWAAAAAIAAAANAAAAIAAEAFkAAAACAAAAEQAAACAABABaAAAADAAAAAoAAAA2AAUACAAAAAEAAAAAAAAACQAAAPgAAgBbAAAAQQAFAFQAAABcAAAABAAAABIAAAA9AAQADwAAAF0AAABcAAAAUQAGAAoAAABeAAAAXQAAAAAAAAAAAAAAQQAGAFoAAABfAAAABwAAABIAAAASAAAAPgADAF8AAABeAAAAUQAGAAoAAABgAAAAXQAAAAAAAAABAAAAQQAGAFoAAABhAAAABwAAABIAAAATAAAAPgADAGEAAABgAAAAUQAGAAoAAABiAAAAXQAAAAEAAAAAAAAAQQAGAFoAAABjAAAABwAAABIAAAAUAAAAPgADAGMAAABiAAAAUQAGAAoAAABkAAAAXQAAAAEAAAABAAAAQQAGAFoAAABlAAAABwAAABIAAAAVAAAAPgADAGUAAABkAAAAQQAGAFUAAABmAAAABAAAABIAAAATAAAAPQAEAAwAAABnAAAAZgAAAFEABQAKAAAAaAAAAGcAAAAAAAAAQQAGAFoAAABpAAAABwAAABIAAAAWAAAAPgADAGkAAABoAAAAUQAFAAoAAABqAAAAZwAAAAEAAABBAAYAWgAAAGsAAAAHAAAAEgAAABcAAAA+AAMAawAAAGoAAABBAAcAVgAAAGwAAAAEAAAAEgAAABMAAAASAAAAPQAEAAoAAABiAAAAbAAAAEEABgBaAAAAbQAAAAcAAAASAAAAGAAAAD4AAwBtAAAAYgAAAEEABQBXAAAAbgAAAAQAAAATAAAAPQAEABAAAABvAAAAbgAAAFEABgAKAAAAcAAAAG8AAAAAAAAAAAAAAEEABgBaAAAAcQAAAAcAAAASAAAAGQAAAD4AAwBxAAAAcAAAAFEABgAKAAAAcgAAAG8AAAAAAAAAAQAAAEEABgBaAAAAcwAAAAcAAAASAAAAGgAAAD4AAwBzAAAAcgAAAFEABgAKAAAAdAAAAG8AAAAAAAAAAgAAAEEABgBaAAAAdQAAAAcAAAASAAAAGwAAAD4AAwB1AAAAdAAAAFEABgAKAAAAdgAAAG8AAAABAAAAAAAAAEEABgBaAAAAdwAAAAcAAAASAAAAHAAAAD4AAwB3AAAAdgAAAFEABgAKAAAAeAAAAG8AAAABAAAAAQAAAEEABgBaAAAAeQAAAAcAAAASAAAAHQAAAD4AAwB5AAAAeAAAAFEABgAKAAAAegAAAG8AAAABAAAAAgAAAEEABgBaAAAAewAAAAcAAAASAAAAHgAAAD4AAwB7AAAAegAAAFEABgAKAAAAfAAAAG8AAAACAAAAAAAAAEEABgBaAAAAfQAAAAcAAAASAAAAHwAAAD4AAwB9AAAAfAAAAFEABgAKAAAAfgAAAG8AAAACAAAAAQAAAEEABgBaAAAAfwAAAAcAAAASAAAAIAAAAD4AAwB/AAAAfgAAAFEABgAKAAAAgAAAAG8AAAACAAAAAgAAAEEABgBaAAAAgQAAAAcAAAASAAAAIQAAAD4AAwCBAAAAgAAAAFEABgAKAAAAggAAAG8AAAADAAAAAAAAAEEABgBaAAAAgwAAAAcAAAASAAAAIgAAAD4AAwCDAAAAggAAAFEABgAKAAAAhAAAAG8AAAADAAAAAQAAAEEABgBaAAAAhQAAAAcAAAASAAAAIwAAAD4AAwCFAAAAhAAAAFEABgAKAAAAhgAAAG8AAAADAAAAAgAAAEEABgBaAAAAhwAAAAcAAAASAAAAJAAAAD4AAwCHAAAAhgAAAEEABgBYAAAAiAAAAAQAAAATAAAAFAAAAD0ABAANAAAAiQAAAIgAAABRAAUACgAAAIoAAACJAAAAAAAAAEEABgBaAAAAiwAAAAcAAAASAAAAJQAAAD4AAwCLAAAAigAAAFEABQAKAAAAjAAAAIkAAAABAAAAQQAGAFoAAACNAAAABwAAABIAAAAmAAAAPgADAI0AAACMAAAAUQAFAAoAAACOAAAAiQAAAAIAAABBAAYAWgAAAI8AAAAHAAAAEgAAACcAAAA+AAMAjwAAAI4AAABBAAcAVgAAAJAAAAAEAAAAEwAAABUAAAATAAAAPQAEAAoAAACEAAAAkAAAAEEABgBaAAAAkQAAAAcAAAASAAAAKAAAAD4AAwCRAAAAhAAAAEEABgBZAAAAkgAAAAQAAAAUAAAAEwAAAD0ABAARAAAAkwAAAJIAAABRAAYACgAAAJQAAACTAAAAAAAAAAAAAABBAAYAWgAAAJUAAAAHAAAAEgAAACkAAAA+AAMAlQAAAJQAAABRAAYACgAAAJYAAACTAAAAAAAAAAEAAABBAAYAWgAAAJcAAAAHAAAAEgAAACoAAAA+AAMAlwAAAJYAAABRAAYACgAAAJgAAACTAAAAAAAAAAIAAABBAAYAWgAAAJkAAAAHAAAAEgAAACsAAAA+AAMAmQAAAJgAAABRAAYACgAAAJoAAACTAAAAAQAAAAAAAABBAAYAWgAAAJsAAAAHAAAAEgAAACwAAAA+AAMAmwAAAJoAAABRAAYACgAAAJwAAACTAAAAAQAAAAEAAABBAAYAWgAAAJ0AAAAHAAAAEgAAAC0AAAA+AAMAnQAAAJwAAABRAAYACgAAAJ4AAACTAAAAAQAAAAIAAABBAAYAWgAAAJ8AAAAHAAAAEgAAAC4AAAA+AAMAnwAAAJ4AAAA9AAQAAgAAAKAAAAAEAAAAUQAHAAoAAAChAAAAoAAAAAAAAAABAAAAAQAAAEEABgBaAAAAogAAAAcAAAASAAAALwAAAD4AAwCiAAAAoQAAAFEABwAKAAAAowAAAKAAAAABAAAAAAAAAAIAAABBAAYAWgAAAKQAAAAHAAAAEgAAADAAAAA+AAMApAAAAKMAAABRAAgACgAAAKUAAACgAAAAAgAAAAAAAAABAAAAAgAAAEEABgBaAAAApgAAAAcAAAASAAAAMQAAAD4AAwCmAAAApQAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const MSH = 50, MPIPE = 51, MUB = 52, MOUT = 53;
        w.command(VX.SHADER_CREATE, [MSH, STD140_SPV.length], STD140_SPV);
        w.command(VX.PIPELINE_CREATE, [MPIPE], json({ kind: "compute", stages: [{ shader: MSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [MUB, 256, 0]);
        w.command(VX.MEMORY_CREATE, [MOUT, 256, 0]);
        w.command(VX.MEMORY_WRITE, [MUB, 0, 0, 192], new Uint8Array(Float32Array.from({ length: 48 }, (_, i) => i).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [MPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 2, 0, 0, 6, MUB, 0, 0, 0, 192, 1, 0, 7, MOUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const got = Array.from(new Float32Array((await read(MOUT, 0, 128)).buffer));
        const expected = [0, 1, 4, 5, 4, 5, 4, 8, 12, 16, 9, 13, 17, 10, 14, 18, 11, 15, 19, 10, 14, 18, 15, 32, 36, 40, 33, 37, 41, 5, 16, 29];
        check(got.join() === expected.join(), "std140 matrices (2-row, row major, arrays, the whole block): " + got.join() +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // A dispatch that reads one range of a memory and writes another (ANGLE's
        // conversions do, its buffers in one memory): WebGPU allows no other use
        // of a buffer a dispatch writes, so VX binds a copy of the range read.
        // The SPIR-V (naga, from GLSL): d.b[i] = s.a[i] * 2 + 1, 8 invocations
        const ALIAS_SPV = Uint8Array.from(atob("AwIjBwAAAQAcAAAALwAAAAAAAAARAAIAAQAAAAoACwBTUFZfS0hSX3N0b3JhZ2VfYnVmZmVyX3N0b3JhZ2VfY2xhc3MAAAAACwAGAAEAAABHTFNMLnN0ZC40NTAAAAAADgADAAAAAAABAAAADwAGAAUAAAAsAAAAbWFpbgAAAAApAAAAEAAGACwAAAARAAAABAAAAAEAAAABAAAARwAEAAQAAAAGAAAABAAAAEgABQAFAAAAAAAAACMAAAAAAAAARwADAAUAAAACAAAASAAFAAYAAAAAAAAAIwAAAAAAAABHAAMABgAAAAIAAABHAAMADAAAABgAAABHAAQADAAAACIAAAAAAAAARwAEAAwAAAAhAAAAAAAAAEcABAAOAAAAIgAAAAAAAABHAAQADgAAACEAAAABAAAARwAEACkAAAALAAAAHAAAABMAAgACAAAAFQAEAAMAAAAgAAAAAAAAAB0AAwAEAAAAAwAAAB4AAwAFAAAABAAAAB4AAwAGAAAABAAAABcABAAHAAAAAwAAAAMAAAAVAAQACQAAACAAAAABAAAAKwAEAAkAAAAIAAAABAAAACsABAAJAAAACgAAAAAAAAArAAQACQAAAAsAAAABAAAAIAAEAA0AAAAMAAAABQAAADsABAANAAAADAAAAAwAAAAgAAQADwAAAAwAAAAGAAAAOwAEAA8AAAAOAAAADAAAACAABAARAAAABgAAAAcAAAAuAAMABwAAABIAAAA7AAUAEQAAABAAAAAGAAAAEgAAACEAAwAVAAAAAgAAACsABAADAAAAFgAAAAIAAAArAAQAAwAAABcAAAABAAAAIAAEABkAAAAHAAAAAwAAAC4AAwADAAAAGgAAACAABAAfAAAADAAAAAQAAAAgAAQAIAAAAAwAAAADAAAAKwAEAAMAAAAiAAAAAAAAACAABAAqAAAAAQAAAAcAAAA7AAQAKgAAACkAAAABAAAANgAFAAIAAAAUAAAAAAAAABUAAAD4AAIAEwAAADsABQAZAAAAGAAAAAcAAAAaAAAA+QACABsAAAD4AAIAGwAAAD0ABAAHAAAAHAAAABAAAABRAAUAAwAAAB0AAAAcAAAAAAAAAD4AAwAYAAAAHQAAAD0ABAADAAAAHgAAABgAAAA9AAQAAwAAACEAAAAYAAAAQQAGACAAAAAjAAAADAAAACIAAAAhAAAAPQAEAAMAAAAkAAAAIwAAAIQABQADAAAAJQAAACQAAAAWAAAAgAAFAAMAAAAmAAAAJQAAABcAAABBAAYAIAAAACcAAAAOAAAAIgAAAB4AAAA+AAMAJwAAACYAAAD9AAEAOAABADYABQACAAAALAAAAAAAAAAVAAAA+AACACgAAAA9AAQABwAAACsAAAApAAAA+QACAC0AAAD4AAIALQAAAD4AAwAQAAAAKwAAADkABAACAAAALgAAABQAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const ASH = 60, APIPE = 61, AM = 62;
        w.command(VX.SHADER_CREATE, [ASH, ALIAS_SPV.length], ALIAS_SPV);
        w.command(VX.PIPELINE_CREATE, [APIPE], json({ kind: "compute", stages: [{ shader: ASH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [AM, 512, 0]);
        w.command(VX.MEMORY_WRITE, [AM, 0, 0, 32], new Uint8Array(Uint32Array.from([0, 1, 2, 3, 4, 5, 6, 7]).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [APIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 2, 0, 0, 7, AM, 0, 0, 0, 32, 1, 0, 7, AM, 0, 256, 0, 32]);
        w.command(VX.DISPATCH, [2, 1, 1]);
        w.command(VX.END, []);
        const aliased = Array.from(new Uint32Array((await read(AM, 256, 32)).buffer));
        check(aliased.join() === "1,3,5,7,9,11,13,15", "a dispatch reading and writing one memory: " + aliased.join() +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // An input attachment of the subpass's own color attachment (framebuffer
        // fetch, ANGLE's advanced blending): the SPIR-V (assembled by hand) reads
        // it and adds 0.25 to red; VX copies the attachment before each such draw
        // (WebGPU samples no attachment of the pass it is in). Cleared to 0.25,
        // two draws: 0.75
        const FETCH_SPV = Uint8Array.from(atob("AwIjBwADAQAAAAAAFgAAAAAAAAARAAIAAQAAABEAAgAoAAAADgADAAAAAAABAAAADwAGAAQAAAABAAAAbWFpbgAAAAACAAAAEAADAAEAAAAHAAAARwAEAAIAAAAeAAAAAAAAAEcABAADAAAAIgAAAAAAAABHAAQAAwAAACEAAAAAAAAARwAEAAMAAAArAAAAAAAAABMAAgAEAAAAIQADAAUAAAAEAAAAFgADAAYAAAAgAAAAFQAEAAcAAAAgAAAAAQAAABcABAAIAAAABgAAAAQAAAAXAAQACQAAAAcAAAACAAAAGQAJAAoAAAAGAAAABgAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAIAAEAAsAAAAAAAAACgAAADsABAALAAAAAwAAAAAAAAAgAAQADAAAAAMAAAAIAAAAOwAEAAwAAAACAAAAAwAAACsABAAHAAAADQAAAAAAAAAsAAUACQAAAA4AAAANAAAADQAAACsABAAGAAAADwAAAAAAAAArAAQABgAAABAAAAAAAIA+LAAHAAgAAAARAAAAEAAAAA8AAAAPAAAADwAAADYABQAEAAAAAQAAAAAAAAAFAAAA+AACABIAAAA9AAQACgAAABMAAAADAAAAYgAFAAgAAAAUAAAAEwAAAA4AAACBAAUACAAAABUAAAAUAAAAEQAAAD4AAwACAAAAFQAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const FSH = 70, FPIPE = 71;
        w.command(VX.SHADER_CREATE, [FSH, FETCH_SPV.length], FETCH_SPV);
        w.command(VX.PIPELINE_CREATE, [FPIPE], json({ kind: "graphics",
            stages: [{ shader: SVS, stage: 1, entry: "main", constants: {} }, { shader: FSH, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 4, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false, depth: null, depth_format: 0,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 1, push_size: 0 }));
        w.command(VX.BEGIN, []);
        w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [f32(0.25), 0, 0, f32(1)], resolve: 0 }], depth: null, width: 8, height: 8 }));
        w.command(VX.BIND_PIPELINE, [FPIPE]);
        w.command(VX.SET_BIND_GROUP, [0, 1, 0, 0, 10, XRTV, 0, 0, 0, 0]);
        w.command(VX.DRAW, [4, 1, 0, 0]);
        w.command(VX.DRAW, [4, 1, 0, 0]);
        w.command(VX.END_PASS, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, XRT, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 2048);
        check(Math.abs(bytes[0] - 191) <= 1 && pixel(5, 6).split(",")[0] === String(bytes[0]),
            "framebuffer fetch, two draws: " + pixel(0, 0) + " " + pixel(5, 6) + " (" + renderer.vx.warnings.join("; ") + ")");

        // Buffer-image copies of rows not in whole dwords (an R8 image 7 texels
        // wide, rows 7 bytes apart): repacked by VX's compute shader; in from
        // byte 0, out to byte 1001 of a memory of 0x55, the bytes around kept
        const R8 = 80, RM = 81;
        w.command(VX.TEXTURE_CREATE, [R8, 9, 1, 7, 3, 1, 1, 1, 1, 0x3, 0]);
        w.command(VX.MEMORY_CREATE, [RM, 2048, 0]);
        const r8 = Uint8Array.from({ length: 21 }, (_, i) => 10 + i);
        w.command(VX.MEMORY_WRITE, [RM, 0, 0, 24], Uint8Array.from([...r8, 0, 0, 0]));
        w.command(VX.BEGIN, []);
        w.command(VX.FILL_BUFFER, [RM, 1000, 0, 32, 0, 0x55555555]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, RM, 0, 0, 0, 0, R8, 1, 0, 0, 1, 0, 0, 0, 7, 3, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, RM, 1001, 0, 0, 0, R8, 1, 0, 0, 1, 0, 0, 0, 7, 3, 1]);
        w.command(VX.END, []);
        bytes = await read(RM, 1000, 32);
        check(bytes[0] === 0x55 && bytes.slice(1, 22).join() === Array.from(r8).join() && bytes[22] === 0x55,
            "buffer-image copies of rows not in whole dwords: " + bytes.slice(0, 24).join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // A descriptor array of 3 uniform blocks (GLSL's uniform B { float x; } b[3]):
        // each element a variable of its own (vx/naga/src/blockarrays.rs); the
        // SPIR-V (by hand) reads b[0], b[2] and b[1] (the last through a pointer
        // to the block), the blocks 1.0, 2.0 and 3.0 in one memory
        const BLOCKS_SPV = Uint8Array.from(atob("AwIjBwADAQAAAAAAIAAAAAAAAAARAAIAAQAAAA4AAwAAAAAAAQAAAA8ABQAFAAAAAQAAAG1haW4AAAAAEAAGAAEAAAARAAAAAQAAAAEAAAABAAAARwADAAIAAAACAAAASAAFAAIAAAAAAAAAIwAAAAAAAABHAAQAAwAAACIAAAAAAAAARwAEAAMAAAAhAAAAAAAAAEcAAwAEAAAAAgAAAEgABQAEAAAAAAAAACMAAAAAAAAARwAEAAUAAAAGAAAABAAAAEcABAAGAAAAIgAAAAAAAABHAAQABgAAACEAAAABAAAAEwACAAcAAAAhAAMACAAAAAcAAAAWAAMACQAAACAAAAAVAAQACgAAACAAAAABAAAAKwAEAAoAAAALAAAAAAAAACsABAAKAAAADAAAAAEAAAArAAQACgAAAA0AAAACAAAAKwAEAAoAAAAOAAAAAwAAAB4AAwACAAAACQAAABwABAAPAAAAAgAAAA4AAAAgAAQAEAAAAAIAAAAPAAAAOwAEABAAAAADAAAAAgAAAB0AAwAFAAAACQAAAB4AAwAEAAAABQAAACAABAARAAAADAAAAAQAAAA7AAQAEQAAAAYAAAAMAAAAIAAEABIAAAACAAAACQAAACAABAATAAAADAAAAAkAAAAgAAQAFAAAAAIAAAACAAAANgAFAAcAAAABAAAAAAAAAAgAAAD4AAIAFQAAAEEABgASAAAAFgAAAAMAAAALAAAACwAAAD0ABAAJAAAAFwAAABYAAABBAAYAEwAAABgAAAAGAAAACwAAAAsAAAA+AAMAGAAAABcAAABBAAYAEgAAABkAAAADAAAADQAAAAsAAAA9AAQACQAAABoAAAAZAAAAQQAGABMAAAAbAAAABgAAAAsAAAAMAAAAPgADABsAAAAaAAAAQQAFABQAAAAcAAAAAwAAAAwAAABBAAUAEgAAAB0AAAAcAAAACwAAAD0ABAAJAAAAHgAAAB0AAABBAAYAEwAAAB8AAAAGAAAACwAAAA0AAAA+AAMAHwAAAB4AAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const BSH = 90, BPIPE = 91, BM = 92, BOUT = 93;
        w.command(VX.SHADER_CREATE, [BSH, BLOCKS_SPV.length], BLOCKS_SPV);
        w.command(VX.PIPELINE_CREATE, [BPIPE], json({ kind: "compute", stages: [{ shader: BSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [BM, 1024, 0]);
        w.command(VX.MEMORY_CREATE, [BOUT, 256, 0]);
        for(const [k, v] of [[0, 1], [1, 2], [2, 3]]) w.command(VX.MEMORY_WRITE, [BM, k * 256, 0, 4], new Uint8Array(Float32Array.from([v]).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [BPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 4, 0, 0, 6, BM, 0, 0, 0, 16, 0, 1, 6, BM, 0, 256, 0, 16, 0, 2, 6, BM, 0, 512, 0, 16,
            1, 0, 7, BOUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const blocks = Array.from(new Float32Array((await read(BOUT, 0, 12)).buffer));
        check(blocks.join() === "1,3,2", "a descriptor array of uniform blocks: " + blocks.join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // An integer cube (usamplerCube, R32_UINT 2x2 faces, texel 100 face +
        // 10 y + x) and an array of two integer 2D samplers (200 and 300 +
        // 10 y + x): WGSL samples neither, so vx/naga loads from the cube's
        // faces as a 2D array (cubes.rs) and from each element's own binding
        // (blockarrays.rs). The SPIR-V (by hand) samples the cube at
        // (-1, 0.1, 0.2) (face -x, texel (1, 0)) and (0.3, -0.5, -1) (face -z,
        // texel (0, 1)), s[1] at (0.75, 0.25) and s[0] at (0.25, 0.75)
        const CUBE_SPV = Uint8Array.from(atob("AwIjBwADAQAAAAAAPAAAAAAAAAARAAIAAQAAAA4AAwAAAAAAAQAAAA8ABQAFAAAAAQAAAG1haW4AAAAAEAAGAAEAAAARAAAAAQAAAAEAAAABAAAARwAEAAIAAAAiAAAAAAAAAEcABAACAAAAIQAAAAAAAABHAAQAAwAAACIAAAAAAAAARwAEAAMAAAAhAAAAAQAAAEcAAwAEAAAAAgAAAEgABQAEAAAAAAAAACMAAAAAAAAARwAEAAUAAAAGAAAABAAAAEcABAAGAAAAIgAAAAAAAABHAAQABgAAACEAAAACAAAAEwACAAcAAAAhAAMACAAAAAcAAAAWAAMACQAAACAAAAAVAAQACgAAACAAAAABAAAAFQAEAAsAAAAgAAAAAAAAABcABAAMAAAACQAAAAIAAAAXAAQADQAAAAkAAAADAAAAFwAEAA4AAAALAAAABAAAACsABAAKAAAADwAAAAAAAAArAAQACgAAABAAAAABAAAAKwAEAAoAAAARAAAAAgAAACsABAAKAAAAEgAAAAMAAAArAAQACQAAABMAAAAAAAAAKwAEAAkAAAAUAAAAAACAvysABAAJAAAAFQAAAM3MzD0rAAQACQAAABYAAADNzEw+KwAEAAkAAAAXAAAAmpmZPisABAAJAAAAGAAAAAAAAL8rAAQACQAAABkAAAAAAEA/KwAEAAkAAAAaAAAAAACAPiwABgANAAAAGwAAABQAAAAVAAAAFgAAACwABgANAAAAHAAAABcAAAAYAAAAFAAAACwABQAMAAAAHQAAABkAAAAaAAAALAAFAAwAAAAeAAAAGgAAABkAAAAZAAkAHwAAAAsAAAADAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAbAAMAIAAAAB8AAAAgAAQAIQAAAAAAAAAgAAAAOwAEACEAAAACAAAAAAAAABkACQAiAAAACwAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAABsAAwAjAAAAIgAAABwABAAkAAAAIwAAABEAAAAgAAQAJQAAAAAAAAAkAAAAOwAEACUAAAADAAAAAAAAACAABAAmAAAAAAAAACMAAAAdAAMABQAAAAsAAAAeAAMABAAAAAUAAAAgAAQAJwAAAAwAAAAEAAAAOwAEACcAAAAGAAAADAAAACAABAAoAAAADAAAAAsAAAA2AAUABwAAAAEAAAAAAAAACAAAAPgAAgApAAAAPQAEACAAAAAqAAAAAgAAAFgABwAOAAAAKwAAACoAAAAbAAAAAgAAABMAAABRAAUACwAAACwAAAArAAAAAAAAAEEABgAoAAAALQAAAAYAAAAPAAAADwAAAD4AAwAtAAAALAAAAD0ABAAgAAAALgAAAAIAAABYAAcADgAAAC8AAAAuAAAAHAAAAAIAAAATAAAAUQAFAAsAAAAwAAAALwAAAAAAAABBAAYAKAAAADEAAAAGAAAADwAAABAAAAA+AAMAMQAAADAAAABBAAUAJgAAADIAAAADAAAAEAAAAD0ABAAjAAAAMwAAADIAAABYAAcADgAAADQAAAAzAAAAHQAAAAIAAAATAAAAUQAFAAsAAAA1AAAANAAAAAAAAABBAAYAKAAAADYAAAAGAAAADwAAABEAAAA+AAMANgAAADUAAABBAAUAJgAAADcAAAADAAAADwAAAD0ABAAjAAAAOAAAADcAAABYAAcADgAAADkAAAA4AAAAHgAAAAIAAAATAAAAUQAFAAsAAAA6AAAAOQAAAAAAAABBAAYAKAAAADsAAAAGAAAADwAAABIAAAA+AAMAOwAAADoAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const CSH = 100, CPIPE = 101, CUBE = 102, CUBEV = 103, S0 = 104, S0V = 105, S1 = 106, S1V = 107, SMP = 108, CM = 109, COUT = 110;
        w.command(VX.SHADER_CREATE, [CSH, CUBE_SPV.length], CUBE_SPV);
        w.command(VX.PIPELINE_CREATE, [CPIPE], json({ kind: "compute", stages: [{ shader: CSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.TEXTURE_CREATE, [CUBE, 98, 1, 2, 2, 1, 1, 6, 1, 0x7, 0x10]);
        w.command(VX.VIEW_CREATE, [CUBEV, CUBE, 3, 98, 1, 0, 1, 0, 6, 0, 0, 0, 0]);
        w.command(VX.TEXTURE_CREATE, [S0, 98, 1, 2, 2, 1, 1, 1, 1, 0x7, 0]);
        w.command(VX.VIEW_CREATE, [S0V, S0, 1, 98, 1, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.TEXTURE_CREATE, [S1, 98, 1, 2, 2, 1, 1, 1, 1, 0x7, 0]);
        w.command(VX.VIEW_CREATE, [S1V, S1, 1, 98, 1, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.SAMPLER_CREATE, [SMP, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0]);
        w.command(VX.MEMORY_CREATE, [CM, 256, 0]);
        w.command(VX.MEMORY_CREATE, [COUT, 256, 0]);
        const texels = base => Array.from({ length: 4 }, (_, i) => base + 10 * (i >> 1) + (i & 1));
        const cube_texels = Uint32Array.from([0, 1, 2, 3, 4, 5].flatMap(face => texels(100 * face)));
        w.command(VX.MEMORY_WRITE, [CM, 0, 0, 96], new Uint8Array(cube_texels.buffer));
        w.command(VX.MEMORY_WRITE, [CM, 128, 0, 32], new Uint8Array(Uint32Array.from([...texels(200), ...texels(300)]).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER_IMAGE, [1, CM, 0, 0, 0, 0, CUBE, 1, 0, 0, 6, 0, 0, 0, 2, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, CM, 128, 0, 0, 0, S0, 1, 0, 0, 1, 0, 0, 0, 2, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, CM, 144, 0, 0, 0, S1, 1, 0, 0, 1, 0, 0, 0, 2, 2, 1]);
        w.command(VX.BIND_PIPELINE, [CPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 4, 0, 0, 1, CUBEV, SMP, 0, 0, 0, 1, 0, 1, S0V, SMP, 0, 0, 0, 1, 1, 1, S1V, SMP, 0, 0, 0,
            2, 0, 7, COUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const fetched = Array.from(new Uint32Array((await read(COUT, 0, 16)).buffer));
        check(fetched.join() === "101,510,301,210", "an integer cube and an array of integer samplers: " + fetched.join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // Vertex input WebGPU cannot take (ANGLE's: an attribute a binding, 10
        // of them): the positions R16G16_SNORM 6 bytes apart, bound at offset 2,
        // the others constants (stride 0); VX repacks them into its own buffers
        // at the draw (VX.packVertices). The SPIR-V (naga, from WGSL) colors
        // with (a1 + a2, a8, a9, 1) = (0.5, 0.75, 1, 1); drawn, then drawn indexed
        const VIN_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAIgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ADAAAAAAAFwAAAG1haW4AAAAACAAAAAsAAAAOAAAAEAAAABIAAAAUAAAAFgAAAEgABQAFAAAAAAAAACMAAAAAAAAASAAFAAUAAAABAAAAIwAAABAAAABHAAQACAAAAB4AAAAAAAAARwAEAAsAAAAeAAAAAQAAAEcABAAOAAAAHgAAAAIAAABHAAQAEAAAAB4AAAAIAAAARwAEABIAAAAeAAAACQAAAEcABAAUAAAACwAAAAAAAABHAAQAFgAAAB4AAAAAAAAAEwACAAIAAAAWAAMAAwAAACAAAAAXAAQABAAAAAMAAAAEAAAAHgAEAAUAAAAEAAAABAAAABcABAAGAAAAAwAAAAIAAAAgAAQACQAAAAEAAAAGAAAAOwAEAAkAAAAIAAAAAQAAACAABAAMAAAAAQAAAAMAAAA7AAQADAAAAAsAAAABAAAAOwAEAAwAAAAOAAAAAQAAADsABAAMAAAAEAAAAAEAAAA7AAQADAAAABIAAAABAAAAIAAEABUAAAADAAAABAAAADsABAAVAAAAFAAAAAMAAAA7AAQAFQAAABYAAAADAAAAIQADABgAAAACAAAAKwAEAAMAAAAZAAAAAAAAACsABAADAAAAGgAAAAAAgD82AAUAAgAAABcAAAAAAAAAGAAAAPgAAgAHAAAAPQAEAAYAAAAKAAAACAAAAD0ABAADAAAADQAAAAsAAAA9AAQAAwAAAA8AAAAOAAAAPQAEAAMAAAARAAAAEAAAAD0ABAADAAAAEwAAABIAAAD5AAIAGwAAAPgAAgAbAAAAUAAGAAQAAAAcAAAACgAAABkAAAAaAAAAgQAFAAMAAAAdAAAADQAAAA8AAABQAAcABAAAAB4AAAAdAAAAEQAAABMAAAAaAAAAUAAFAAUAAAAfAAAAHAAAAB4AAABRAAUABAAAACAAAAAfAAAAAAAAAD4AAwAUAAAAIAAAAFEABQAEAAAAIQAAAB8AAAABAAAAPgADABYAAAAhAAAA/QABADgAAQA="), c => c.charCodeAt(0));
        const VIN_FS = Uint8Array.from(atob("AwIjBwAAAQAcAAAADgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAEAAAACwAAAG1haW4AAAAABgAAAAkAAAAQAAMACwAAAAcAAABHAAQABgAAAB4AAAAAAAAARwAEAAkAAAAeAAAAAAAAABMAAgACAAAAFgADAAQAAAAgAAAAFwAEAAMAAAAEAAAABAAAACAABAAHAAAAAQAAAAMAAAA7AAQABwAAAAYAAAABAAAAIAAEAAoAAAADAAAAAwAAADsABAAKAAAACQAAAAMAAAAhAAMADAAAAAIAAAA2AAUAAgAAAAsAAAAAAAAADAAAAPgAAgAFAAAAPQAEAAMAAAAIAAAABgAAAPkAAgANAAAA+AACAA0AAAA+AAMACQAAAAgAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const VVS = 120, VFS = 121, VPIPE = 122, VM = 123;
        w.command(VX.SHADER_CREATE, [VVS, VIN_VS.length], VIN_VS);
        w.command(VX.SHADER_CREATE, [VFS, VIN_FS.length], VIN_FS);
        w.command(VX.PIPELINE_CREATE, [VPIPE], json({ kind: "graphics",
            stages: [{ shader: VVS, stage: 1, entry: "main", constants: {} }, { shader: VFS, stage: 16, entry: "main", constants: {} }],
            buffers: Array.from({ length: 10 }, (_, k) => ({ binding: k, stride: k ? 0 : 6, rate: 0 })),
            attributes: Array.from({ length: 10 }, (_, k) => ({ location: k, binding: k, format: k ? 100 : 78, offset: 0 })),
            topology: 4, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false, depth: null, depth_format: 0,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [VM, 256, 0]);
        const corners = new Int16Array(12);
        [[-1, -1], [1, -1], [-1, 1], [1, 1]].forEach(([x, y], i) => { corners[3 * i] = x * 32767; corners[3 * i + 1] = y * 32767; });
        w.command(VX.MEMORY_WRITE, [VM, 0, 0, 28], Uint8Array.from([0, 0, ...new Uint8Array(corners.buffer), 0, 0]));
        w.command(VX.MEMORY_WRITE, [VM, 64, 0, 40], new Uint8Array(Float32Array.from([0, 0.25, 0.25, 0, 0, 0, 0, 0, 0.75, 1]).buffer));
        const vin_draw = indexed => {
            w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }], depth: null, width: 8, height: 8 }));
            w.command(VX.BIND_PIPELINE, [VPIPE]);
            w.command(VX.SET_VERTEX_BUFFER, [0, VM, 2, 0, 24, 0]);
            for(let k = 1; k < 10; k++) w.command(VX.SET_VERTEX_BUFFER, [k, VM, 64 + 4 * k, 0, 4, 0]);
            if(indexed)
            {
                w.command(VX.SET_INDEX_BUFFER, [IB, 0, 0, 8, 0, 0]);
                w.command(VX.DRAW_INDEXED, [4, 1, 0, 0, 0]);
            }
            else w.command(VX.DRAW, [4, 1, 0, 0]);
            w.command(VX.END_PASS, []);
            w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, XRT, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        };
        const vin = [];
        for(const indexed of [false, true])
        {
            w.command(VX.BEGIN, []);
            vin_draw(indexed);
            w.command(VX.END, []);
            bytes = await read(B, 0, 2048);
            vin.push(pixel(0, 0), pixel(7, 7));
        }
        check(vin.every(v => v === "128,191,255,255"), "vertex input of 10 bindings, a stride of 6, an offset of 2: " + vin.join(" ") +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // A uniform buffer bound smaller than its block (GL's std140 size without
        // the padding at its end: 20 bytes of a 32-byte struct { vec4 a; float b; }):
        // WebGPU wants the whole block, so VX binds the memory after it too
        const SHORT_SPV = Uint8Array.from(atob("AwIjBwAAAQAcAAAAIAAAAAAAAAARAAIAAQAAAAoACwBTUFZfS0hSX3N0b3JhZ2VfYnVmZmVyX3N0b3JhZ2VfY2xhc3MAAAAACwAGAAEAAABHTFNMLnN0ZC40NTAAAAAADgADAAAAAAABAAAADwAFAAUAAAAOAAAAbWFpbgAAAAAQAAYADgAAABEAAAABAAAAAQAAAAEAAABIAAUABQAAAAAAAAAjAAAAAAAAAEgABQAFAAAAAQAAACMAAAAQAAAARwAEAAYAAAAGAAAABAAAAEgABQAHAAAAAAAAACMAAAAAAAAARwADAAcAAAACAAAARwAEAAgAAAAiAAAAAAAAAEcABAAIAAAAIQAAAAAAAABHAAMACQAAAAIAAABIAAUACQAAAAAAAAAjAAAAAAAAAEcABAALAAAAIgAAAAAAAABHAAQACwAAACEAAAABAAAAEwACAAIAAAAWAAMAAwAAACAAAAAXAAQABAAAAAMAAAAEAAAAHgAEAAUAAAAEAAAAAwAAAB0AAwAGAAAAAwAAAB4AAwAHAAAABgAAAB4AAwAJAAAABQAAACAABAAKAAAAAgAAAAkAAAA7AAQACgAAAAgAAAACAAAAIAAEAAwAAAAMAAAABwAAADsABAAMAAAACwAAAAwAAAAhAAMADwAAAAIAAAAgAAQAEAAAAAIAAAAFAAAAFQAEABIAAAAgAAAAAAAAACsABAASAAAAEQAAAAAAAAAgAAQAFQAAAAwAAAAGAAAAIAAEABYAAAAMAAAAAwAAACAABAAXAAAAAgAAAAMAAAArAAQAEgAAABgAAAABAAAAIAAEABsAAAACAAAABAAAADYABQACAAAADgAAAAAAAAAPAAAA+AACAA0AAABBAAUAEAAAABMAAAAIAAAAEQAAAPkAAgAUAAAA+AACABQAAABBAAUAFwAAABkAAAATAAAAGAAAAD0ABAADAAAAGgAAABkAAABBAAYAFwAAABwAAAATAAAAEQAAABgAAAA9AAQAAwAAAB0AAAAcAAAAgQAFAAMAAAAeAAAAGgAAAB0AAABBAAYAFgAAAB8AAAALAAAAEQAAABEAAAA+AAMAHwAAAB4AAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const USH = 130, UPIPE = 131, UM = 132, UOUT = 133;
        w.command(VX.SHADER_CREATE, [USH, SHORT_SPV.length], SHORT_SPV);
        w.command(VX.PIPELINE_CREATE, [UPIPE], json({ kind: "compute", stages: [{ shader: USH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [UM, 256, 0]);
        w.command(VX.MEMORY_CREATE, [UOUT, 256, 0]);
        w.command(VX.MEMORY_WRITE, [UM, 0, 0, 20], new Uint8Array(Float32Array.from([0, 2, 0, 0, 5]).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [UPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 2, 0, 0, 6, UM, 0, 0, 0, 20, 1, 0, 7, UOUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const short = new Float32Array((await read(UOUT, 0, 4)).buffer)[0];
        check(short === 7, "a uniform buffer bound smaller than its block: " + short + " (" + renderer.vx.warnings.join("; ") + ")");

        // GL's provoking vertex (VK_EXT_provoking_vertex's last): a strip of 4
        // vertices with a flat color (red 0.25 per vertex index), drawn as it is
        // and indexed; each of its triangles has its last vertex's color (2's
        // and 3's: 128 and 191; WebGPU's first would give 0 and 64). The SPIR-V
        // is naga's, from WGSL
        const FLAT_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAJgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ACAAAAAAADwAAAG1haW4AAAAACQAAAAwAAAAOAAAASAAFAAUAAAAAAAAAIwAAAAAAAABIAAUABQAAAAEAAAAjAAAAEAAAAEcABAAJAAAACwAAACoAAABHAAQADAAAAAsAAAAAAAAARwAEAA4AAAAeAAAAAAAAAEcAAwAOAAAADgAAABMAAgACAAAAFgADAAQAAAAgAAAAFwAEAAMAAAAEAAAABAAAAB4ABAAFAAAAAwAAAAMAAAAVAAQABgAAACAAAAAAAAAAFwAEAAcAAAAEAAAAAgAAACAABAAKAAAAAQAAAAYAAAA7AAQACgAAAAkAAAABAAAAIAAEAA0AAAADAAAAAwAAADsABAANAAAADAAAAAMAAAA7AAQADQAAAA4AAAADAAAAIQADABAAAAACAAAAKwAEAAYAAAARAAAAAQAAACsABAAEAAAAEgAAAAAAAEArAAQABAAAABMAAAAAAIA/LAAFAAcAAAAUAAAAEwAAABMAAAArAAQABAAAABUAAAAAAAAAKwAEAAQAAAAWAAAAAACAPjYABQACAAAADwAAAAAAAAAQAAAA+AACAAgAAAA9AAQABgAAAAsAAAAJAAAA+QACABcAAAD4AAIAFwAAAMcABQAGAAAAGAAAAAsAAAARAAAAcAAEAAQAAAAZAAAAGAAAAMIABQAGAAAAGgAAAAsAAAARAAAAcAAEAAQAAAAbAAAAGgAAAFAABQAHAAAAHAAAABkAAAAbAAAAjgAFAAcAAAAdAAAAHAAAABIAAACDAAUABwAAAB4AAAAdAAAAFAAAAFAABgADAAAAHwAAAB4AAAAVAAAAEwAAAHAABAAEAAAAIAAAAAsAAACFAAUABAAAACEAAAAgAAAAFgAAAFAABwADAAAAIgAAACEAAAAVAAAAFQAAABMAAABQAAUABQAAACMAAAAfAAAAIgAAAFEABQADAAAAJAAAACMAAAAAAAAAPgADAAwAAAAkAAAAUQAFAAMAAAAlAAAAIwAAAAEAAAA+AAMADgAAACUAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const FLAT_FS = Uint8Array.from(atob("AwIjBwAAAQAcAAAADgAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAEAAAACwAAAG1haW4AAAAABgAAAAkAAAAQAAMACwAAAAcAAABHAAQABgAAAB4AAAAAAAAARwADAAYAAAAOAAAARwAEAAkAAAAeAAAAAAAAABMAAgACAAAAFgADAAQAAAAgAAAAFwAEAAMAAAAEAAAABAAAACAABAAHAAAAAQAAAAMAAAA7AAQABwAAAAYAAAABAAAAIAAEAAoAAAADAAAAAwAAADsABAAKAAAACQAAAAMAAAAhAAMADAAAAAIAAAA2AAUAAgAAAAsAAAAAAAAADAAAAPgAAgAFAAAAPQAEAAMAAAAIAAAABgAAAPkAAgANAAAA+AACAA0AAAA+AAMACQAAAAgAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const PVS = 140, PFS = 141, PPIPE = 142;
        w.command(VX.SHADER_CREATE, [PVS, FLAT_VS.length], FLAT_VS);
        w.command(VX.SHADER_CREATE, [PFS, FLAT_FS.length], FLAT_FS);
        w.command(VX.PIPELINE_CREATE, [PPIPE], json({ kind: "graphics",
            stages: [{ shader: PVS, stage: 1, entry: "main", constants: {} }, { shader: PFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 4, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, provoking_last: true,
            discard: false, depth_bias: null, samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false, depth: null, depth_format: 0,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        const flats = [];
        for(const indexed of [false, true])
        {
            w.command(VX.BEGIN, []);
            one_draw(PPIPE, indexed);
            w.command(VX.END, []);
            bytes = await read(B, 0, 2048);
            flats.push([pixel(0, 0), pixel(7, 7)].map(x => x.split(",")[0]).sort().join("/"));
        }
        check(flats.every(f => f === "128/191"), "the last vertex's flat color, drawn and indexed: " + flats.join(" ") + " (" + renderer.vx.warnings.join("; ") + ")");

        // A blit of 3D images (ANGLE makes a 3D texture's mipmaps so): a 2x2x2
        // source, slice 0 all 0x40 and slice 1 all 0xC0, nearest into 2x2x4:
        // slices 0 and 1 from source slice 0, 2 and 3 from slice 1
        const V3 = 150, V3D = 151, V3M = 152;
        w.command(VX.TEXTURE_CREATE, [V3, 37, 2, 2, 2, 2, 1, 1, 1, 0x17, 0]);
        w.command(VX.TEXTURE_CREATE, [V3D, 37, 2, 2, 2, 4, 1, 1, 1, 0x17, 0]);
        w.command(VX.MEMORY_CREATE, [V3M, 1024, 0]);
        w.command(VX.MEMORY_WRITE, [V3M, 0, 0, 32], Uint8Array.from({ length: 32 }, (_, i) => i < 16 ? 0x40 : 0xC0));
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER_IMAGE, [1, V3M, 0, 0, 0, 0, V3, 1, 0, 0, 1, 0, 0, 0, 2, 2, 2]);
        w.command(VX.BLIT_IMAGE, [V3, 0, 0, 0, 0, 0, 2, 2, 2, V3D, 0, 0, 0, 0, 0, 2, 2, 4, 1, 0]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, V3M, 256, 0, 0, 0, V3D, 1, 0, 0, 1, 0, 0, 0, 2, 2, 4]);
        w.command(VX.END, []);
        // (a texel of each slice: 16 bytes a slice)
        const slices3d = Array.from(await read(V3M, 256, 64)).filter((_, i) => i % 16 === 0);
        check(slices3d.join() === "64,64,192,192", "a blit of 3D images: " + slices3d.join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // The dynamic depth bias (VK_DYNAMIC_STATE_DEPTH_BIAS, GL's glPolygonOffset):
        // a pipeline variant per bias. A D16 target cleared to 1, the whole of it
        // drawn at z 0.5 with a bias of 100 units (100 / 65536 for D16): about
        // 32868 of 65535, not 32768
        const HALF_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAHQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAAAAAADQAAAG1haW4AAAAACAAAAAsAAABHAAQACAAAAAsAAAAqAAAARwAEAAsAAAALAAAAAAAAABMAAgACAAAAFQAEAAMAAAAgAAAAAAAAABYAAwAFAAAAIAAAABcABAAEAAAABQAAAAQAAAAXAAQABgAAAAUAAAACAAAAIAAEAAkAAAABAAAAAwAAADsABAAJAAAACAAAAAEAAAAgAAQADAAAAAMAAAAEAAAAOwAEAAwAAAALAAAAAwAAACEAAwAOAAAAAgAAACsABAADAAAADwAAAAEAAAArAAQABQAAABAAAAAAAABAKwAEAAUAAAARAAAAAACAPywABQAGAAAAEgAAABEAAAARAAAAKwAEAAUAAAATAAAAAAAAPzYABQACAAAADQAAAAAAAAAOAAAA+AACAAcAAAA9AAQAAwAAAAoAAAAIAAAA+QACABQAAAD4AAIAFAAAAMcABQADAAAAFQAAAAoAAAAPAAAAcAAEAAUAAAAWAAAAFQAAAMIABQADAAAAFwAAAAoAAAAPAAAAcAAEAAUAAAAYAAAAFwAAAFAABQAGAAAAGQAAABYAAAAYAAAAjgAFAAYAAAAaAAAAGQAAABAAAACDAAUABgAAABsAAAAaAAAAEgAAAFAABgAEAAAAHAAAABsAAAATAAAAEQAAAD4AAwALAAAAHAAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const BVS = 160, BPIPE2 = 161, BD = 162, BDV = 163;
        w.command(VX.SHADER_CREATE, [BVS, HALF_VS.length], HALF_VS);
        w.command(VX.TEXTURE_CREATE, [BD, 124, 1, 8, 8, 1, 1, 1, 1, 0x21, 0]);
        w.command(VX.VIEW_CREATE, [BDV, BD, 1, 124, 2, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.PIPELINE_CREATE, [BPIPE2], json({ kind: "graphics",
            stages: [{ shader: BVS, stage: 1, entry: "main", constants: {} }, { shader: SFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 4, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false,
            depth_bias: { constant: 0, clamp: 0, slope: 0 }, samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false,
            depth: { test: true, write: true, compare: 7, stencil: false, front: null, back: null }, depth_format: 124,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [3],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        w.command(VX.BEGIN, []);
        w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }],
            depth: { view: BDV, load: 1, clear_depth: 1, store: 0, stencil_load: 0, clear_stencil: 0, stencil_store: 0 }, width: 8, height: 8 }));
        w.command(VX.BIND_PIPELINE, [BPIPE2]);
        w.command(VX.SET_DEPTH_BIAS, [f32(100), 0, 0]);
        w.command(VX.DRAW, [4, 1, 0, 0]);
        w.command(VX.END_PASS, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 0, 0, BD, 2, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        const biased = new Uint16Array((await read(B, 0, 16)).buffer)[0];
        check(biased > 32800 && biased < 32950, "the dynamic depth bias: " + biased + " (" + renderer.vx.warnings.join("; ") + ")");

        // 16-bit packed formats (R5G6B5, A1R5G5B5: GL ES's RGB565 and RGB5_A1),
        // textures of rgba8unorm here: a 3x2 image's texels in from byte 2 of a
        // memory and out to byte 66 (the bytes around kept), unpacked and packed
        // by VX's compute shader, the same 16 bits back; then a clear of
        // (1, 0.5, 0, 1): 0xFC00
        const P565 = 170, P1555 = 171, PM = 172;
        w.command(VX.TEXTURE_CREATE, [P565, 4, 1, 3, 2, 1, 1, 1, 1, 0x17, 0]);
        w.command(VX.TEXTURE_CREATE, [P1555, 8, 1, 3, 2, 1, 1, 1, 1, 0x17, 0]);
        w.command(VX.MEMORY_CREATE, [PM, 256, 0]);
        const packed16 = Uint16Array.from([0x1234, 0xF81F, 0x07E0, 0xFFFF, 0x0000, 0xA5A5]);
        w.command(VX.MEMORY_WRITE, [PM, 0, 0, 16], Uint8Array.from([0, 0, ...new Uint8Array(packed16.buffer), 0, 0]));
        const packed_results = [];
        for(const image of [P565, P1555])
        {
            w.command(VX.BEGIN, []);
            w.command(VX.FILL_BUFFER, [PM, 64, 0, 32, 0, 0x55555555]);
            w.command(VX.COPY_BUFFER_IMAGE, [1, PM, 2, 0, 0, 0, image, 1, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
            w.command(VX.COPY_BUFFER_IMAGE, [0, PM, 66, 0, 0, 0, image, 1, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
            w.command(VX.END, []);
            const back = await read(PM, 64, 16);
            packed_results.push(back[0] === 0x55 && back[1] === 0x55 && back[14] === 0x55 &&
                Array.from(new Uint16Array(back.buffer, 2, 6)).join() === Array.from(packed16).join() ? "same" : Array.from(back).join());
        }
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [P565, 1, 0, 1, 0, 1, f32(1), f32(0.5), f32(0), f32(1)]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, PM, 128, 0, 0, 0, P565, 1, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
        w.command(VX.END, []);
        const cleared565 = new Uint16Array((await read(PM, 128, 4)).buffer)[0];
        check(packed_results.join() === "same,same" && cleared565 === 0xFC00, "16-bit packed formats: " + packed_results.join(" ") + ", cleared " +
            cleared565.toString(16) + " (" + renderer.vx.warnings.join("; ") + ")");

        // Stencil references of each face (GL's glStencilFuncSeparate; WebGPU's
        // is one for both): a triangle of each winding, replacing with 0x11 on
        // front faces and 0x22 on back ones; VX draws twice, a face each
        const FACES_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAIQAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAAAAAADwAAAG1haW4AAAAACgAAAA0AAABHAAQABwAAAAYAAAAIAAAARwAEAAoAAAALAAAAKgAAAEcABAANAAAACwAAAAAAAAATAAIAAgAAABUABAADAAAAIAAAAAAAAAAWAAMABQAAACAAAAAXAAQABAAAAAUAAAAEAAAAFwAEAAYAAAAFAAAAAgAAACsABAADAAAACAAAAAYAAAAcAAQABwAAAAYAAAAIAAAAIAAEAAsAAAABAAAAAwAAADsABAALAAAACgAAAAEAAAAgAAQADgAAAAMAAAAEAAAAOwAEAA4AAAANAAAAAwAAACEAAwAQAAAAAgAAACsABAAFAAAAEQAAAAAAgL8sAAUABgAAABIAAAARAAAAEQAAACsABAAFAAAAEwAAAAAAgD8sAAUABgAAABQAAAARAAAAEwAAACsABAAFAAAAFQAAAAAAAAAsAAUABgAAABYAAAAVAAAAEQAAACwABQAGAAAAFwAAABMAAAARAAAALAAFAAYAAAAYAAAAEwAAABMAAAAsAAkABwAAABkAAAASAAAAFAAAABYAAAAWAAAAFwAAABgAAAAgAAQAGwAAAAcAAAAHAAAAIAAEAB0AAAAHAAAABgAAADYABQACAAAADwAAAAAAAAAQAAAA+AACAAkAAAA7AAUAGwAAABoAAAAHAAAAGQAAAD0ABAADAAAADAAAAAoAAAD5AAIAHAAAAPgAAgAcAAAAQQAFAB0AAAAeAAAAGgAAAAwAAAA9AAQABgAAAB8AAAAeAAAAUAAGAAQAAAAgAAAAHwAAABUAAAATAAAAPgADAA0AAAAgAAAA/QABADgAAQA="), c => c.charCodeAt(0));
        const FVS2 = 180, FPIPE2 = 181;
        w.command(VX.SHADER_CREATE, [FVS2, FACES_VS.length], FACES_VS);
        const replace_face = { fail: 0, pass: 2, depth_fail: 0, compare: 7, read_mask: 0xFF, write_mask: 0xFF, reference: 0 };
        w.command(VX.PIPELINE_CREATE, [FPIPE2], json({ kind: "graphics",
            stages: [{ shader: FVS2, stage: 1, entry: "main", constants: {} }, { shader: SFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 3, restart: false, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false,
            depth: { test: false, write: false, compare: 7, stencil: true, front: replace_face, back: replace_face }, depth_format: 129,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [8],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        w.command(VX.BEGIN, []);
        w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }],
            depth: { view: DSV, load: 1, clear_depth: 1, store: 0, stencil_load: 1, clear_stencil: 0, stencil_store: 0 }, width: 8, height: 8 }));
        w.command(VX.BIND_PIPELINE, [FPIPE2]);
        w.command(VX.SET_STENCIL_REFERENCE, [1, 0x11]);
        w.command(VX.SET_STENCIL_REFERENCE, [2, 0x22]);
        w.command(VX.DRAW, [6, 1, 0, 0]);
        w.command(VX.END_PASS, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 0, 0, DS, 4, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        const sides = await read(B, 0, 64);
        check([sides[8 * 4 + 1], sides[8 * 4 + 6]].sort().join() === "17,34", "stencil references of each face: " + sides[8 * 4 + 1] + " " + sides[8 * 4 + 6] +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // View swizzles (VkComponentMapping: ANGLE's GL_LUMINANCE and GL_ALPHA on
        // R8, GL ES 3.0's texture swizzles; WebGPU's views have none): an R8
        // texture (0x40, 0x80) as (r, r, r, 1) and (0, 0, 0, r), loaded by a
        // compute shader from VX's swizzled copies; then the texture written
        // again (0xC0 at texel 1), and the copy with it
        const SWZ_SPV = Uint8Array.from(atob("AwIjBwAAAQAcAAAAMAAAAAAAAAARAAIAAQAAAAoACwBTUFZfS0hSX3N0b3JhZ2VfYnVmZmVyX3N0b3JhZ2VfY2xhc3MAAAAACwAGAAEAAABHTFNMLnN0ZC40NTAAAAAADgADAAAAAAABAAAADwAFAAUAAAAPAAAAbWFpbgAAAAAQAAYADwAAABEAAAABAAAAAQAAAAEAAABHAAQABQAAAAYAAAAEAAAASAAFAAYAAAAAAAAAIwAAAAAAAABHAAMABgAAAAIAAABHAAQACQAAACIAAAAAAAAARwAEAAkAAAAhAAAAAAAAAEcABAALAAAAIgAAAAAAAABHAAQACwAAACEAAAABAAAARwAEAAwAAAAiAAAAAAAAAEcABAAMAAAAIQAAAAIAAAATAAIAAgAAABYAAwADAAAAIAAAABkACQAEAAAAAwAAAAEAAAAAAAAAAAAAAAAAAAABAAAAAAAAAB0AAwAFAAAAAwAAAB4AAwAGAAAABQAAABUABAAIAAAAIAAAAAEAAAAXAAQABwAAAAgAAAACAAAAIAAEAAoAAAAAAAAABAAAADsABAAKAAAACQAAAAAAAAA7AAQACgAAAAsAAAAAAAAAIAAEAA0AAAAMAAAABgAAADsABAANAAAADAAAAAwAAAAhAAMAEAAAAAIAAAArAAQACAAAABMAAAABAAAAKwAEAAgAAAAUAAAAAAAAACwABQAHAAAAFQAAABMAAAAUAAAALAAFAAcAAAAWAAAAFAAAABQAAAAXAAQAGAAAAAMAAAAEAAAAIAAEABsAAAAMAAAABQAAACAABAAcAAAADAAAAAMAAAAVAAQAHwAAACAAAAAAAAAAKwAEAB8AAAAeAAAAAAAAACsABAAfAAAAIgAAAAEAAAArAAQAHwAAACUAAAACAAAAKwAEAB8AAAAoAAAAAwAAACsABAAfAAAAKwAAAAQAAAArAAQAHwAAAC4AAAAFAAAANgAFAAIAAAAPAAAAAAAAABAAAAD4AAIADgAAAD0ABAAEAAAAEQAAAAkAAAA9AAQABAAAABIAAAALAAAA+QACABcAAAD4AAIAFwAAAF8ABwAYAAAAGQAAABEAAAAVAAAAAgAAABQAAABfAAcAGAAAABoAAAASAAAAFgAAAAIAAAAUAAAAUQAFAAMAAAAdAAAAGQAAAAAAAABBAAYAHAAAACAAAAAMAAAAHgAAAB4AAAA+AAMAIAAAAB0AAABRAAUAAwAAACEAAAAZAAAAAQAAAEEABgAcAAAAIwAAAAwAAAAeAAAAIgAAAD4AAwAjAAAAIQAAAFEABQADAAAAJAAAABkAAAACAAAAQQAGABwAAAAmAAAADAAAAB4AAAAlAAAAPgADACYAAAAkAAAAUQAFAAMAAAAnAAAAGQAAAAMAAABBAAYAHAAAACkAAAAMAAAAHgAAACgAAAA+AAMAKQAAACcAAABRAAUAAwAAACoAAAAaAAAAAAAAAEEABgAcAAAALAAAAAwAAAAeAAAAKwAAAD4AAwAsAAAAKgAAAFEABQADAAAALQAAABoAAAADAAAAQQAGABwAAAAvAAAADAAAAB4AAAAuAAAAPgADAC8AAAAtAAAA/QABADgAAQA="), c => c.charCodeAt(0));
        const ZSH = 190, ZPIPE = 191, ZT = 192, ZLUM = 193, ZALPHA = 194, ZM = 195, ZOUT = 196;
        w.command(VX.SHADER_CREATE, [ZSH, SWZ_SPV.length], SWZ_SPV);
        w.command(VX.PIPELINE_CREATE, [ZPIPE], json({ kind: "compute", stages: [{ shader: ZSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.TEXTURE_CREATE, [ZT, 9, 1, 2, 1, 1, 1, 1, 1, 0x7, 0]);
        w.command(VX.VIEW_CREATE, [ZLUM, ZT, 1, 9, 1, 0, 1, 0, 1, 3, 3, 3, 2]);
        w.command(VX.VIEW_CREATE, [ZALPHA, ZT, 1, 9, 1, 0, 1, 0, 1, 1, 1, 1, 3]);
        w.command(VX.MEMORY_CREATE, [ZM, 256, 0]);
        w.command(VX.MEMORY_CREATE, [ZOUT, 256, 0]);
        w.command(VX.MEMORY_WRITE, [ZM, 0, 0, 4], Uint8Array.from([0x40, 0x80, 0xC0, 0]));
        const swizzled = [];
        for(const from of [0, 1])
        {
            w.command(VX.BEGIN, []);
            w.command(VX.COPY_BUFFER_IMAGE, [1, ZM, from, 0, 0, 0, ZT, 1, 0, 0, 1, 0, 0, 0, 2, 1, 1]);
            w.command(VX.BIND_PIPELINE, [ZPIPE]);
            w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 3, 0, 0, 2, ZLUM, 0, 0, 0, 0, 1, 0, 2, ZALPHA, 0, 0, 0, 0, 2, 0, 7, ZOUT, 0, 0, 0, 256]);
            w.command(VX.DISPATCH, [1, 1, 1]);
            w.command(VX.END, []);
            swizzled.push(Array.from(new Float32Array((await read(ZOUT, 0, 24)).buffer), x => Math.round(x * 255)).join());
        }
        check(swizzled.join(" ") === "128,128,128,255,0,64 192,192,192,255,0,128", "view swizzles: " + swizzled.join(" ") +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // D32_SFLOAT_S8_UINT (GL ES 3.0's DEPTH32F_STENCIL8: WebGPU's optional
        // depth32float-stencil8): depth cleared to 0.3, stencil to 7, both read back
        const D32S8 = 200, D32M = 201;
        w.command(VX.TEXTURE_CREATE, [D32S8, 130, 1, 4, 4, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.MEMORY_CREATE, [D32M, 1024, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [D32S8, 6, 0, 1, 0, 1, f32(0.3), 7, 0, 0]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, D32M, 0, 0, 0, 0, D32S8, 2, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, D32M, 512, 0, 0, 0, D32S8, 4, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.END, []);
        const d32s8 = await read(D32M, 0, 1024);
        const depth32 = new Float32Array(d32s8.buffer, 0, 1)[0], stencil8 = d32s8[512];
        check(near(depth32, 0.3) && stencil8 === 7, "D32_SFLOAT_S8_UINT: " + depth32 + ", " + stencil8 + " (" + renderer.vx.warnings.join("; ") + ")");

        // A depth view sampled as a float texture (GL's sampler2D of a depth
        // texture; WebGPU binds depth as depth or unfilterable float): through a
        // copy of (d, 0, 0, 1), the swizzle test's shader; a D32 image cleared to 0.6
        const DR = 205, DRV = 206;
        w.command(VX.TEXTURE_CREATE, [DR, 126, 1, 2, 1, 1, 1, 1, 1, 0x27, 0]);
        w.command(VX.VIEW_CREATE, [DRV, DR, 1, 126, 2, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [DR, 2, 0, 1, 0, 1, f32(0.6), 0, 0, 0]);
        w.command(VX.BIND_PIPELINE, [ZPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 3, 0, 0, 2, DRV, 0, 0, 0, 0, 1, 0, 2, DRV, 0, 0, 0, 0, 2, 0, 7, ZOUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const depth_read = Array.from(new Float32Array((await read(ZOUT, 0, 24)).buffer), x => Math.round(x * 100) / 100).join();
        check(depth_read === "0.6,0,0,1,0.6,1", "a depth view sampled as a float texture: " + depth_read + " (" + renderer.vx.warnings.join("; ") + ")");

        // A snapshot's stencil back into its texture (TEXTURE_WRITE of the stencil aspect), then copied out
        const SW = 210, SWM = 211;
        w.command(VX.TEXTURE_CREATE, [SW, 129, 1, 4, 2, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.MEMORY_CREATE, [SWM, 256, 0]);
        w.command(VX.TEXTURE_WRITE, [SW, 4, 0, 0, 8], Uint8Array.from([1, 2, 3, 4, 5, 6, 7, 8]));
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, SWM, 0, 0, 0, 0, SW, 4, 0, 0, 1, 0, 0, 0, 4, 2, 1]);
        w.command(VX.END, []);
        const stencil_back = Array.from((await read(SWM, 0, 8))).join();
        check(stencil_back === "1,2,3,4,5,6,7,8", "a snapshot's stencil restored: " + stencil_back + " (" + renderer.vx.warnings.join("; ") + ")");

        // std140 arrays of scalars and vec2s, 16 bytes apart (naga writes WGSL's
        // 4 and 8): vec4 arrays (vx/naga/src/layout.rs). U { int n; float a[3];
        // vec2 b[2]; }: a[n - 1], a[1], b[1].y, the whole a's [2], the whole b's [0].x
        const PADDED_SPV = Uint8Array.from(atob("AwIjBwADAQAAAAAALwAAAAAAAAARAAIAAQAAAA4AAwAAAAAAAQAAAA8ABQAFAAAAAQAAAG1haW4AAAAAEAAGAAEAAAARAAAAAQAAAAEAAAABAAAARwADAAIAAAACAAAASAAFAAIAAAAAAAAAIwAAAAAAAABIAAUAAgAAAAEAAAAjAAAAEAAAAEgABQACAAAAAgAAACMAAABAAAAARwAEAAMAAAAGAAAAEAAAAEcABAAEAAAABgAAABAAAABHAAQABQAAACIAAAAAAAAARwAEAAUAAAAhAAAAAAAAAEcAAwAGAAAAAgAAAEgABQAGAAAAAAAAACMAAAAAAAAARwAEAAcAAAAGAAAABAAAAEcABAAIAAAAIgAAAAAAAABHAAQACAAAACEAAAABAAAAEwACAAkAAAAhAAMACgAAAAkAAAAWAAMACwAAACAAAAAVAAQADAAAACAAAAABAAAAFwAEAA0AAAALAAAAAgAAACsABAAMAAAADgAAAAAAAAArAAQADAAAAA8AAAABAAAAKwAEAAwAAAAQAAAAAgAAACsABAAMAAAAEQAAAAMAAAArAAQADAAAABIAAAAEAAAAHAAEAAMAAAALAAAAEQAAABwABAAEAAAADQAAABAAAAAeAAUAAgAAAAwAAAADAAAABAAAACAABAATAAAAAgAAAAIAAAA7AAQAEwAAAAUAAAACAAAAHQADAAcAAAALAAAAHgADAAYAAAAHAAAAIAAEABQAAAAMAAAABgAAADsABAAUAAAACAAAAAwAAAAgAAQAFQAAAAIAAAAMAAAAIAAEABYAAAACAAAACwAAACAABAAXAAAAAgAAAAMAAAAgAAQAGAAAAAIAAAAEAAAAIAAEABkAAAAMAAAACwAAADYABQAJAAAAAQAAAAAAAAAKAAAA+AACABoAAABBAAUAFQAAABsAAAAFAAAADgAAAD0ABAAMAAAAHAAAABsAAACCAAUADAAAAB0AAAAcAAAADwAAAEEABgAWAAAAHgAAAAUAAAAPAAAAHQAAAD0ABAALAAAAHwAAAB4AAABBAAYAGQAAACAAAAAIAAAADgAAAA4AAAA+AAMAIAAAAB8AAABBAAYAFgAAACEAAAAFAAAADwAAAA8AAAA9AAQACwAAACIAAAAhAAAAQQAGABkAAAAjAAAACAAAAA4AAAAPAAAAPgADACMAAAAiAAAAQQAHABYAAAAkAAAABQAAABAAAAAPAAAADwAAAD0ABAALAAAAJQAAACQAAABBAAYAGQAAACYAAAAIAAAADgAAABAAAAA+AAMAJgAAACUAAABBAAUAFwAAACcAAAAFAAAADwAAAD0ABAADAAAAKAAAACcAAABRAAUACwAAACkAAAAoAAAAAgAAAEEABgAZAAAAKgAAAAgAAAAOAAAAEQAAAD4AAwAqAAAAKQAAAEEABQAYAAAAKwAAAAUAAAAQAAAAPQAEAAQAAAAsAAAAKwAAAFEABgALAAAALQAAACwAAAAAAAAAAAAAAEEABgAZAAAALgAAAAgAAAAOAAAAEgAAAD4AAwAuAAAALQAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const PSH = 215, PPIPE3 = 216, PUM = 217, POUT = 218;
        w.command(VX.SHADER_CREATE, [PSH, PADDED_SPV.length], PADDED_SPV);
        w.command(VX.PIPELINE_CREATE, [PPIPE3], json({ kind: "compute", stages: [{ shader: PSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [PUM, 256, 0]);
        w.command(VX.MEMORY_CREATE, [POUT, 256, 0]);
        const ublock = new Float32Array(24);
        new Int32Array(ublock.buffer)[0] = 3;
        [10, 11, 12].forEach((v, k) => { ublock[4 + 4 * k] = v; });
        [[20, 21], [22, 23]].forEach(([x, y], k) => { ublock[16 + 4 * k] = x; ublock[17 + 4 * k] = y; });
        w.command(VX.MEMORY_WRITE, [PUM, 0, 0, 96], new Uint8Array(ublock.buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [PPIPE3]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 2, 0, 0, 6, PUM, 0, 0, 0, 96, 1, 0, 7, POUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const padded = Array.from(new Float32Array((await read(POUT, 0, 20)).buffer)).join();
        check(padded === "12,11,23,12,20", "std140 arrays of scalars and vec2s: " + padded + " (" + renderer.vx.warnings.join("; ") + ")");

        // Integer images sampled outside [0, 1] with samplers that repeat (GL's
        // default wrap; the fetch clamps otherwise): the cube test's two R32_UINT
        // images, s[0] repeating at (1.25, 0.25): texel (0, 0), 200; s[1]
        // mirrored at (-0.75, 1.25): texel (1, 1), 311
        const WRAP_SPV = Uint8Array.from(atob("AwIjBwADAQAAAAAANgAAAAAAAAARAAIAAQAAAA4AAwAAAAAAAQAAAA8ABQAFAAAAAQAAAG1haW4AAAAAEAAGAAEAAAARAAAAAQAAAAEAAAABAAAARwAEAAIAAAAiAAAAAAAAAEcABAACAAAAIQAAAAAAAABHAAQAAwAAACIAAAAAAAAARwAEAAMAAAAhAAAAAQAAAEcAAwAEAAAAAgAAAEgABQAEAAAAAAAAACMAAAAAAAAARwAEAAUAAAAGAAAABAAAAEcABAAGAAAAIgAAAAAAAABHAAQABgAAACEAAAACAAAAEwACAAcAAAAhAAMACAAAAAcAAAAWAAMACQAAACAAAAAVAAQACgAAACAAAAABAAAAFQAEAAsAAAAgAAAAAAAAABcABAAMAAAACQAAAAIAAAAXAAQADQAAAAkAAAADAAAAFwAEAA4AAAALAAAABAAAACsABAAKAAAADwAAAAAAAAArAAQACgAAABAAAAABAAAAKwAEAAoAAAARAAAAAgAAACsABAAKAAAAEgAAAAMAAAArAAQACQAAABMAAAAAAAAAKwAEAAkAAAAUAAAAAACAvysABAAJAAAAFQAAAM3MzD0rAAQACQAAABYAAADNzEw+KwAEAAkAAAAXAAAAmpmZPisABAAJAAAAGAAAAAAAAL8rAAQACQAAABkAAAAAAEA/KwAEAAkAAAAaAAAAAACAPisABAAJAAAAGwAAAAAAoD8rAAQACQAAABwAAAAAAEC/LAAGAA0AAAAdAAAAFAAAABUAAAAWAAAALAAGAA0AAAAeAAAAFwAAABgAAAAUAAAALAAFAAwAAAAfAAAAGwAAABoAAAAsAAUADAAAACAAAAAcAAAAGwAAABkACQAhAAAACwAAAAMAAAAAAAAAAAAAAAAAAAABAAAAAAAAABsAAwAiAAAAIQAAACAABAAjAAAAAAAAACIAAAA7AAQAIwAAAAIAAAAAAAAAGQAJACQAAAALAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGwADACUAAAAkAAAAHAAEACYAAAAlAAAAEQAAACAABAAnAAAAAAAAACYAAAA7AAQAJwAAAAMAAAAAAAAAIAAEACgAAAAAAAAAJQAAAB0AAwAFAAAACwAAAB4AAwAEAAAABQAAACAABAApAAAADAAAAAQAAAA7AAQAKQAAAAYAAAAMAAAAIAAEACoAAAAMAAAACwAAADYABQAHAAAAAQAAAAAAAAAIAAAA+AACACsAAABBAAUAKAAAACwAAAADAAAADwAAAD0ABAAlAAAALQAAACwAAABYAAcADgAAAC4AAAAtAAAAHwAAAAIAAAATAAAAUQAFAAsAAAAvAAAALgAAAAAAAABBAAYAKgAAADAAAAAGAAAADwAAAA8AAAA+AAMAMAAAAC8AAABBAAUAKAAAADEAAAADAAAAEAAAAD0ABAAlAAAAMgAAADEAAABYAAcADgAAADMAAAAyAAAAIAAAAAIAAAATAAAAUQAFAAsAAAA0AAAAMwAAAAAAAABBAAYAKgAAADUAAAAGAAAADwAAABAAAAA+AAMANQAAADQAAAD9AAEAOAABAA=="), c => c.charCodeAt(0));
        const WSH = 220, WPIPE = 221, WREP = 222, WMIR = 223;
        w.command(VX.SHADER_CREATE, [WSH, WRAP_SPV.length], WRAP_SPV);
        w.command(VX.PIPELINE_CREATE, [WPIPE], json({ kind: "compute", stages: [{ shader: WSH, stage: 32, entry: "main", constants: {} }],
            set_count: 1, push_size: 0 }));
        w.command(VX.SAMPLER_CREATE, [WREP, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
        w.command(VX.SAMPLER_CREATE, [WMIR, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.BIND_PIPELINE, [WPIPE]);
        w.command(VX.SET_BIND_GROUP, [1 << 16 | 0, 3, 1, 0, 1, S0V, WREP, 0, 0, 0, 1, 1, 1, S1V, WMIR, 0, 0, 0, 2, 0, 7, COUT, 0, 0, 0, 256]);
        w.command(VX.DISPATCH, [1, 1, 1]);
        w.command(VX.END, []);
        const wrapped = Array.from(new Uint32Array((await read(COUT, 0, 8)).buffer)).join();
        check(wrapped === "200,311", "integer images sampled with samplers that repeat: " + wrapped + " (" + renderer.vx.warnings.join("; ") + ")");

        // Depth from a memory into D32_SFLOAT and D24_UNORM_S8_UINT images (WebGPU
        // copies buffers into depth16unorm only: a draw writing frag_depth), and
        // 24-bit depth back out (a dispatch: WebGPU copies none out): 3x2 texels
        const UD32 = 230, UD24 = 231, UDM = 232;
        w.command(VX.TEXTURE_CREATE, [UD32, 126, 1, 3, 2, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.TEXTURE_CREATE, [UD24, 129, 1, 3, 2, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.MEMORY_CREATE, [UDM, 512, 0]);
        const d32in = Float32Array.from([0.1, 0.2, 0.3, 0.4, 0.5, 0.6]);
        const d24in = Uint32Array.from([0, 0x400000, 0x800000, 0xC00000, 0xFFFFFF, 0x123456]);
        w.command(VX.MEMORY_WRITE, [UDM, 0, 0, 24], new Uint8Array(d32in.buffer));
        w.command(VX.MEMORY_WRITE, [UDM, 32, 0, 24], new Uint8Array(d24in.buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.COPY_BUFFER_IMAGE, [1, UDM, 0, 0, 0, 0, UD32, 2, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, UDM, 32, 0, 0, 0, UD24, 2, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, UDM, 256, 0, 0, 0, UD32, 2, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, UDM, 384, 0, 0, 0, UD24, 2, 0, 0, 1, 0, 0, 0, 3, 2, 1]);
        w.command(VX.END, []);
        const dback = await read(UDM, 256, 160);
        const d32out = Array.from(new Float32Array(dback.buffer, 0, 6)), d24out = Array.from(new Uint32Array(dback.buffer, 128, 6));
        check(d32out.every((v, i) => near(v, d32in[i])) && d24out.every((v, i) => Math.abs(v - d24in[i]) <= 1),
            "depth into D32 and D24S8 by a draw, 24-bit depth out by a dispatch: " + d32out.map(v => v.toFixed(2)).join() + " / " + d24out.join() +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // A snapshot's 24-bit depth: written into D24S8 (TEXTURE_WRITE, by a draw)
        // and read again (TEXTURE_READ, by a dispatch)
        const snapIn = Uint32Array.from([7, 0x111111, 0x222222, 0x333333, 0x444444, 0xFFFFFF]);
        w.command(VX.TEXTURE_WRITE, [UD24, 2, 0, 0, 24], new Uint8Array(snapIn.buffer));
        const snapRequest = request++;
        w.command(VX.TEXTURE_READ, [UD24, 2, 0, 0, snapRequest]);
        await send();
        const snapOut = answers.get(snapRequest) ? Array.from(new Uint32Array(answers.get(snapRequest).buffer.slice(answers.get(snapRequest).byteOffset,
            answers.get(snapRequest).byteOffset + 24))) : [];
        check(snapOut.length === 6 && snapOut.every((v, i) => Math.abs(v - snapIn[i]) <= 1), "a snapshot's 24-bit depth written and read: " + snapOut.join() +
            " (" + renderer.vx.warnings.join("; ") + ")");

        // Parts of depth and stencil (WebGPU copies only whole subresources of
        // them): 2x2 of 16-bit depth in at (1, 1) of a 4x4 D16 image, the whole read
        // out; 2x2 of a D24S8 image's depth and stencil from (1, 1) to (2, 0) of another
        const PD16 = 235, PS1 = 236, PS2 = 237, PDM = 238;
        w.command(VX.TEXTURE_CREATE, [PD16, 124, 1, 4, 4, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.TEXTURE_CREATE, [PS1, 129, 1, 4, 4, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.TEXTURE_CREATE, [PS2, 129, 1, 4, 4, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.MEMORY_CREATE, [PDM, 1024, 0]);
        w.command(VX.MEMORY_WRITE, [PDM, 0, 0, 8], new Uint8Array(Uint16Array.from([1000, 2000, 3000, 4000]).buffer));
        const s1depth = Uint32Array.from({ length: 16 }, (_, i) => i * 0x10000), s1stencil = Uint8Array.from({ length: 16 }, (_, i) => i + 1);
        w.command(VX.MEMORY_WRITE, [PDM, 64, 0, 64], new Uint8Array(s1depth.buffer));
        w.command(VX.MEMORY_WRITE, [PDM, 128, 0, 16], s1stencil);
        w.command(VX.BEGIN, []);
        w.command(VX.CLEAR_IMAGE, [PD16, 2, 0, 1, 0, 1, f32(0), 0, 0, 0]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, PDM, 0, 0, 0, 0, PD16, 2, 0, 0, 1, 1, 1, 0, 2, 2, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, PDM, 256, 0, 0, 0, PD16, 2, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, PDM, 64, 0, 0, 0, PS1, 2, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [1, PDM, 128, 0, 0, 0, PS1, 4, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.CLEAR_IMAGE, [PS2, 6, 0, 1, 0, 1, f32(0), 0, 0, 0]);
        w.command(VX.COPY_IMAGE, [PS1, 6, 0, 0, 1, 1, 0, PS2, 6, 0, 0, 2, 0, 0, 2, 2, 1, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, PDM, 320, 0, 0, 0, PS2, 2, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, PDM, 400, 0, 0, 0, PS2, 4, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.END, []);
        const pback = await read(PDM, 256, 160);
        const d16 = Array.from(new Uint16Array(pback.buffer, 0, 16)), d24 = Array.from(new Uint32Array(pback.buffer, 64, 16)), st = Array.from(pback.slice(144, 160));
        const ok16 = d16.join() === "0,0,0,0,0,1000,2000,0,0,3000,4000,0,0,0,0,0";
        const ok24 = d24.every((v, i) => Math.abs(v - [0, 0, s1depth[5], s1depth[6], 0, 0, s1depth[9], s1depth[10], 0, 0, 0, 0, 0, 0, 0, 0][i]) <= 1);
        const okSt = st.join() === [0, 0, 6, 7, 0, 0, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0].join();
        check(ok16 && ok24 && okSt, "parts of depth and stencil copied: " + d16.join() + " / " + d24.join() + " / " + st.join() + " (" + renderer.vx.warnings.join("; ") + ")");

        // Primitive restart in a list (GL ES 3.0's; WebGPU restarts strips only): an
        // indexed point list of (0, 0xFFFF, 0) with restart; the restart index's
        // point (at x +0.5) is not drawn, vertex 0's (at -0.5) is
        const RESTART_VS = Uint8Array.from(atob("AwIjBwAAAQAcAAAAGAAAAAAAAAARAAIAAQAAAAsABgABAAAAR0xTTC5zdGQuNDUwAAAAAA4AAwAAAAAAAQAAAA8ABwAAAAAADAAAAG1haW4AAAAABwAAAAoAAABHAAQABwAAAAsAAAAqAAAARwAEAAoAAAALAAAAAAAAABMAAgACAAAAFQAEAAMAAAAgAAAAAAAAABYAAwAFAAAAIAAAABcABAAEAAAABQAAAAQAAAAgAAQACAAAAAEAAAADAAAAOwAEAAgAAAAHAAAAAQAAACAABAALAAAAAwAAAAQAAAA7AAQACwAAAAoAAAADAAAAIQADAA0AAAACAAAAKwAEAAMAAAAOAAAA//8AACsABAAFAAAADwAAAAAAAL8rAAQABQAAABAAAAAAAAA/KwAEAAUAAAARAAAAAAAAACsABAAFAAAAEgAAAAAAgD8UAAIAFAAAADYABQACAAAADAAAAAAAAAANAAAA+AACAAYAAAA9AAQAAwAAAAkAAAAHAAAA+QACABMAAAD4AAIAEwAAAKoABQAUAAAAFQAAAAkAAAAOAAAAqQAGAAUAAAAWAAAAFQAAABAAAAAPAAAAUAAHAAQAAAAXAAAAFgAAABEAAAARAAAAEgAAAD4AAwAKAAAAFwAAAP0AAQA4AAEA"), c => c.charCodeAt(0));
        const RVS = 240, RPIPE = 241, RIB = 242;
        w.command(VX.SHADER_CREATE, [RVS, RESTART_VS.length], RESTART_VS);
        w.command(VX.PIPELINE_CREATE, [RPIPE], json({ kind: "graphics",
            stages: [{ shader: RVS, stage: 1, entry: "main", constants: {} }, { shader: SFS, stage: 16, entry: "main", constants: {} }],
            buffers: [], attributes: [], topology: 0, restart: true, cull: 0, front: 0, polygon: 0, depth_clamp: false, discard: false, depth_bias: null,
            samples: 1, sample_mask: 0xFFFFFFFF, alpha_to_coverage: false, depth: null, depth_format: 0,
            targets: [{ format: 37, blend: false, write_mask: 15 }], blend_constants: [0, 0, 0, 0], dynamic: [],
            viewport: { x: 0, y: 0, width: 8, height: 8, minDepth: 0, maxDepth: 1 }, scissor: { offset: { x: 0, y: 0 }, extent: { width: 8, height: 8 } },
            set_count: 0, push_size: 0 }));
        w.command(VX.MEMORY_CREATE, [RIB, 256, 0]);
        w.command(VX.MEMORY_WRITE, [RIB, 0, 0, 8], new Uint8Array(Uint16Array.from([0, 0xFFFF, 0, 0]).buffer));
        w.command(VX.BEGIN, []);
        w.command(VX.BEGIN_PASS, [], json({ colors: [{ view: XRTV, load: 1, store: 0, clear: [0, 0, 0, 0], resolve: 0 }], depth: null, width: 8, height: 8 }));
        w.command(VX.BIND_PIPELINE, [RPIPE]);
        w.command(VX.SET_INDEX_BUFFER, [RIB, 0, 0, 8, 0, 0]);
        w.command(VX.DRAW_INDEXED, [3, 1, 0, 0, 0]);
        w.command(VX.END_PASS, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, B, 0, 0, 64, 0, XRT, 1, 0, 0, 1, 0, 0, 0, 8, 8, 1]);
        w.command(VX.END, []);
        bytes = await read(B, 0, 2048);
        const lit = [];
        for(let y = 0; y < 8; y++) for(let x = 0; x < 8; x++) if(pixel(x, y) !== "0,0,0,0") lit.push(x + ":" + y);
        check(lit.length === 1 && +lit[0].split(":")[0] < 4, "primitive restart in a point list: " + lit.join(" ") + " (" + renderer.vx.warnings.join("; ") + ")");

        // Depth and stencil resolves (VK_KHR_depth_stencil_resolve's sample zero;
        // WebGPU resolves colors only): a 4x D24S8 cleared to 0.25 and 0x5A in a
        // pass that resolves into a single-sample D24S8, both read back
        const MSD = 245, MSDV = 246, RSD = 247, RSDV = 248, RSM = 249;
        w.command(VX.TEXTURE_CREATE, [MSD, 129, 1, 4, 4, 1, 1, 1, 4, 0x24, 0]);
        w.command(VX.VIEW_CREATE, [MSDV, MSD, 1, 129, 6, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.TEXTURE_CREATE, [RSD, 129, 1, 4, 4, 1, 1, 1, 1, 0x23, 0]);
        w.command(VX.VIEW_CREATE, [RSDV, RSD, 1, 129, 6, 0, 1, 0, 1, 0, 0, 0, 0]);
        w.command(VX.MEMORY_CREATE, [RSM, 256, 0]);
        w.command(VX.BEGIN, []);
        w.command(VX.BEGIN_PASS, [], json({ colors: [], depth: { view: MSDV, load: 1, clear_depth: 0.25, store: 1, stencil_load: 1, clear_stencil: 0x5A,
            stencil_store: 1, resolve: RSDV, resolve_depth: true, resolve_stencil: true }, width: 4, height: 4 }));
        w.command(VX.END_PASS, []);
        w.command(VX.COPY_BUFFER_IMAGE, [0, RSM, 0, 0, 0, 0, RSD, 2, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.COPY_BUFFER_IMAGE, [0, RSM, 128, 0, 0, 0, RSD, 4, 0, 0, 1, 0, 0, 0, 4, 4, 1]);
        w.command(VX.END, []);
        const rsback = await read(RSM, 0, 144);
        const rdepth = new Uint32Array(rsback.buffer, 0, 16), rstencil = Array.from(rsback.slice(128, 144));
        check(Array.from(rdepth).every(v => Math.abs(v - 0x400000) <= 1) && rstencil.every(v => v === 0x5A),
            "depth and stencil resolved: " + rdepth[0] + " " + rstencil[0] + " (" + renderer.vx.warnings.join("; ") + ")");

        // DESTROY, then a read of what is gone fails
        w.command(VX.DESTROY, [A]);
        check(await read(A, 0, 4) === null, "a destroyed memory reads as nothing");

        const vx = renderer.vx;
        check(vx.errors === 0, "no errors: " + vx.warnings.join("; "));
        result.textContent = "PASS " + checks.length + " checks\n" + checks.join("\n");
    } catch(e) {
        result.textContent = "FAIL " + (e.stack || e) + "\n" + checks.join("\n");
    }
})();
</script>
                   source/v64/tests/glbridge/webgpu_shared_device_test.js                                              0000644 0000000 0000000 00000015224 00000000000 020344  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// One canvas, one GPUDevice -- across every guest graphics backend.
//
// A GPUCanvasContext belongs to whichever device last called configure() on
// it, and getCurrentTexture() then returns a texture only that device may use.
// The page loads the D3D8, D3D9/DDraw and OpenGL executors whether or not the
// guest uses them, and they all share #d3d_webgpu_canvas, so a backend that
// acquires its own device does not merely waste one: it makes every other
// backend's present pass fail validation with
//
//   [TextureView of Texture "...WebgpuSwapChainTexture..."] is associated with
//   [Device], and cannot be used with [Device]
//
// which is what OpenGL did in the guest while its own 45 unit tests passed,
// because each executor's tests only ever build one executor.

"use strict";

const assert = require("assert");
const gpuHost = require("../../src/browser/glbridge/webgpu_host.js");

let passed = 0;
const failures = [];

function test(name, fn) {
    try { fn(); ++passed; } catch (error) { failures.push([name, error]); }
}

/* A fake just complete enough for three initialize() paths to run. */
function makeFake() {
    const log = { devices: [], configures: [], adapters: 0 };
    const makeDevice = features => {
        const device = {
            features: new Set(features),
            limits: { maxTextureDimension2D: 8192, maxTextureDimension3D: 2048,
                      maxColorAttachments: 8 },
            lost: new Promise(() => {}),
            queue: { writeBuffer() {}, writeTexture() {}, submit() {},
                     onSubmittedWorkDone: () => Promise.resolve() },
            createBuffer: descriptor => ({ descriptor, destroy() {},
                mapAsync: () => Promise.resolve(),
                getMappedRange: () => new ArrayBuffer(descriptor.size || 4),
                unmap() {} }),
            createTexture: descriptor => ({ descriptor, destroy() {},
                createView: () => ({ texture: descriptor }) }),
            createSampler: descriptor => ({ descriptor }),
            createShaderModule: descriptor => ({ code: descriptor.code,
                getCompilationInfo: async () => ({ messages: [] }) }),
            createCommandEncoder: () => ({
                beginRenderPass: () => ({ end() {}, setPipeline() {},
                    setBindGroup() {}, setVertexBuffer() {}, draw() {} }),
                copyTextureToBuffer() {}, copyBufferToBuffer() {},
                copyTextureToTexture() {}, resolveQuerySet() {},
                finish: () => ({}) }),
            createQuerySet: descriptor => ({ descriptor }),
            createBindGroup: descriptor => ({ descriptor }),
            createRenderPipeline: descriptor => ({ descriptor,
                getBindGroupLayout: () => ({}) }),
            pushErrorScope() {}, popErrorScope: () => Promise.resolve(null),
        };
        log.devices.push(device);
        return device;
    };
    const context = {
        configure(descriptor) { log.configures.push(descriptor); },
        getCurrentTexture: () => ({ width: 640, height: 480,
            createView: () => ({ swapchain: true }) }),
    };
    const gpu = {
        async requestAdapter() {
            ++log.adapters;
            return {
                features: new Set(["texture-compression-bc", "timestamp-query"]),
                limits: { maxTextureDimension2D: 8192 },
                async requestDevice(descriptor) {
                    return makeDevice((descriptor &&
                        descriptor.requiredFeatures) || []);
                },
            };
        },
        getPreferredCanvasFormat: () => "bgra8unorm",
    };
    const canvas = { width: 640, height: 480, getContext: () => context };
    return { gpu, canvas, context, log };
}

async function initAll() {
    const { gpu, canvas, log } = makeFake();
    gpuHost.reset(canvas);
    const built = [];
    // Load order matches game.html: D3D8, then D3D9/DDraw, then OpenGL.
    const d3d8 = require("../../src/browser/glbridge/d3d8-webgpu/d3d8_executor.js");
    const d3d9 = require("../../src/browser/glbridge/d3d9-webgpu/d3d9_executor.js");
    const gl = require("../../src/browser/glbridge/gl-webgpu/gl_executor.js");
    const a = new d3d8.D3D8WebGPUExecutor(canvas, { gpu });
    const b = new d3d9.D3D9WebGPUExecutor(canvas, { gpu });
    const c = new gl.GLWebGPUExecutor(canvas, { gpu, hostOptions: { gpu } });
    for (const executor of [a, b, c]) {
        await executor.initialize();
        built.push(executor);
    }
    return { built, log, canvas };
}

const checks = [];
checks.push(initAll().then(({ built, log }) => {
    const [d3d8, d3d9, gl] = built;
    test("every backend on one canvas ends up on one GPUDevice", () => {
        assert.strictEqual(d3d9.device, d3d8.device,
            "D3D9 and D3D8 must share the device that configured the canvas");
        assert.strictEqual(gl.device, d3d8.device,
            "OpenGL's present pass uses the canvas texture; a second device " +
            "here is the swap-chain validation failure this test exists for");
    });
    test("only one device is ever requested", () => {
        assert.strictEqual(log.devices.length, 1,
            "a second requestDevice means a second owner of the canvas");
        assert.strictEqual(log.adapters, 1);
    });
    test("every canvas configure names the shared device", () => {
        assert.ok(log.configures.length >= 1, "the canvas must be configured");
        for (const descriptor of log.configures)
            assert.strictEqual(descriptor.device, d3d8.device);
    });
    test("the shared device carries the union of requested features", () => {
        // D3D8 alone used to request none, so whichever backend won the race
        // decided whether DXT textures worked for all of them.
        assert.ok(d3d8.device.features.has("texture-compression-bc"),
            "BCn must survive regardless of which backend initialised first");
    });
    test("the swap-chain usages every backend needs are configured once", () => {
        const usage = log.configures[0].usage;
        assert.ok(usage & 0x10, "RENDER_ATTACHMENT");
        assert.ok(usage & 0x01, "COPY_SRC -- D3D9 StretchRect off the back buffer");
        assert.ok(usage & 0x02, "COPY_DST");
        assert.ok(usage & 0x04, "TEXTURE_BINDING -- GL glCopyTexImage2D");
    });
}));

Promise.all(checks).catch(error => {
    failures.push(["harness", error]);
}).then(() => {
    for (const [name, error] of failures)
        console.error("FAIL: " + name + "\n    " + (error && error.message));
    console.log("webgpu_shared_device_test: " +
        (failures.length ? "FAILED" : "ok") +
        " (" + passed + " passed, " + failures.length + " failed)");
    process.exit(failures.length ? 1 : 0);
});
                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/gles/batch.mjs                                                                     0000644 0000000 0000000 00000020746 00000000000 013565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// GLES batches (src/gles/gles_host.js, gles_batch.js; docs/gles-proxy-plan.md
// E2): what the host sends the renderer channel and when:
// - records as written and read back (every field, a command's bytes and
//   its decoded arguments, an update's pixels);
// - sent at the flush points (a frame, glFinish, a post), not before; a big
//   upload sends the batch at once;
// - backpressure: with MAX_IN_FLIGHT batches not yet run, the frame's
//   answer waits for the oldest; glFinish's likewise;
// - reads: glReadPixels and rcReadColorBuffer wait for the page's pixels;
// - a lost renderer: what waited is answered (zeros), nothing more is sent;
//   without a renderer nothing waits at all;
// - the reader refuses what is not a batch.
import assert from "node:assert/strict";
import { GLESHost, FLUSH_BYTES, MAX_IN_FLIGHT } from "../../src/gles/gles_host.js";
import { read_gles_batch } from "../../src/gles/gles_batch.js";
import { GLES, GLES_MAGIC, GXWriter } from "../../src/graphics_adapters/renderer_protocol.js";
import { client, cstring, fake_renderer, settle } from "./lib.mjs";

const DISPLAY = { width: 480, height: 800, dpi: 240 };

/** A host, a connection with a GLES 2.0 context on a 64 by 64 window and its color buffer */
async function setup(renderer)
{
    const host = new GLESHost(DISPLAY, renderer);
    const conn = await client(host).connect();
    const context = (await conn.call("rcCreateContext", 0, 0, 2)).ret;
    const surface = (await conn.call("rcCreateWindowSurface", 0, 64, 64)).ret;
    const buffer = (await conn.call("rcCreateColorBuffer", 64, 64, 0x1908)).ret;
    await conn.call("rcSetWindowColorBuffer", surface, buffer);
    await conn.call("rcMakeCurrent", context, surface, surface);
    return { host, conn, context, surface, buffer };
}

// ---- records, flush points

{
    const renderer = fake_renderer();
    const { host, conn, context, surface, buffer } = await setup(renderer);
    assert.equal(renderer.batches.length, 0, "nothing sent before a flush point");
    conn.send("gles2:glClearColor", 0.25, 0.5, 0.75, 1);
    conn.send("gles2:glClear", 0x4000);
    const pixels = new Uint8Array(8 * 8 * 4).map((_, i) => i);
    await conn.call("rcUpdateColorBuffer", buffer, 4, 4, 8, 8, 0x1908, 0x1401, pixels);
    assert.equal(renderer.batches.length, 0);
    assert.equal((await conn.call("rcFlushWindowColorBuffer", surface)).ret, 0);
    assert.equal(renderer.batches.length, 1, "the frame sent the batch");
    const records = read_gles_batch(renderer.batches[0], true);
    const names = records.map(r => r.name);
    assert.deepEqual(names, ["CONTEXT_CREATE", "SURFACE_CREATE", "COLOR_BUFFER_CREATE", "SURFACE_COLOR_BUFFER", "MAKE_CURRENT",
        "COMMAND", "COMMAND", "COLOR_BUFFER_UPDATE", "FLUSH_SURFACE"]);
    const by = name => records.find(r => r.name === name);
    assert.deepEqual([by("CONTEXT_CREATE").context, by("CONTEXT_CREATE").config, by("CONTEXT_CREATE").share, by("CONTEXT_CREATE").api], [context, 0, 0, 2]);
    assert.deepEqual([by("SURFACE_CREATE").width, by("SURFACE_CREATE").height], [64, 64]);
    assert.deepEqual([by("MAKE_CURRENT").context, by("MAKE_CURRENT").draw, by("MAKE_CURRENT").read], [context, surface, surface]);
    const clear = records[5];
    assert.equal(clear.command.name, "glClearColor");
    assert.deepEqual(clear.args, [0.25, 0.5, 0.75, 1]);
    assert.equal(records[6].command.name, "glClear");
    const update = by("COLOR_BUFFER_UPDATE");
    assert.deepEqual([update.color_buffer, update.x, update.y, update.width, update.height, update.length], [buffer, 4, 4, 8, 8, 256]);
    assert.deepEqual(update.bytes, pixels);
    assert.equal(by("FLUSH_SURFACE").surface, surface);
    // a post, glFinish
    await conn.call("rcFBPost", buffer);
    assert.equal(renderer.batches.length, 2);
    assert.deepEqual(read_gles_batch(renderer.batches[1]).map(r => r.name), ["POST"]);
    conn.send("gles2:glViewport", 0, 0, 32, 32);
    assert.equal((await conn.call("gles2:glFinishRoundTrip")).ret, 0);
    assert.equal(renderer.batches.length, 3, "glFinishRoundTrip sent it");
    await conn.call("gles2:glFinishRoundTrip");
    assert.equal(renderer.batches.length, 3, "an empty batch is not sent");
    // a big upload: sent once the batch passes FLUSH_BYTES
    const big = new Uint8Array(1024 * 1024 * 4 + 1024);
    for(let i = 0; i * big.length <= FLUSH_BYTES; i++) await conn.call("rcUpdateColorBuffer", buffer, 0, 0, 1024, 1025, 0x1908, 0x1401, big);
    assert.equal(renderer.batches.length, 4, "the size sent it");
    assert.equal(host.summary().batches.submitted, 4);
    console.log("PASS: records, flush points");
}

// ---- backpressure

{
    const renderer = fake_renderer({ manual: true });
    const { conn, surface } = await setup(renderer);
    const frames = [];
    for(let i = 0; i < MAX_IN_FLIGHT; i++)
    {
        conn.send("gles2:glClear", 0x4000);
        frames.push(await conn.call("rcFlushWindowColorBuffer", surface));
    }
    assert.ok(frames.every(f => f.ret === 0), "two frames in flight: answered at once");
    conn.send("gles2:glClear", 0x4000);
    let answered = false;
    const third = conn.call("rcFlushWindowColorBuffer", surface).then(r => { answered = true; return r; });
    await settle();
    assert.equal(answered, false, "a third waits for the first to run");
    renderer.run(1);
    assert.equal((await third).ret, 0);
    assert.ok(answered);
    renderer.run();
    console.log("PASS: backpressure");
}

// ---- reads

{
    const renderer = fake_renderer({ manual: true });
    const { conn, buffer } = await setup(renderer);
    let read = null;
    const pending = conn.call("gles2:glReadPixels", 0, 0, 2, 2, 0x1908, 0x1401, 16).then(r => { read = r; });
    await settle();
    assert.equal(read, null, "the read waits for the page");
    const sent = read_gles_batch(renderer.batches.at(-1));
    const request = sent.find(r => r.name === "READ_PIXELS");
    assert.deepEqual([request.x, request.y, request.width, request.height, request.format, request.type], [0, 0, 2, 2, 0x1908, 0x1401]);
    renderer.run();
    await pending;
    assert.deepEqual(read.outs[0], new Uint8Array(16).fill(request.request), "the page's pixels");
    const cb = conn.call("rcReadColorBuffer", buffer, 0, 0, 1, 1, 0x1908, 0x1401, 4);
    await settle();
    renderer.run();
    const answer = await cb;
    assert.equal(answer.outs[0].length, 4);
    // a refused read is not sent and does not wait
    const before = renderer.batches.length;
    assert.deepEqual((await conn.call("gles2:glReadPixels", 0, 0, 2, 2, 0x1907, 0x1401, 12)).outs[0], new Uint8Array(12));
    assert.equal(renderer.batches.length, before);
    assert.equal((await conn.call("gles2:glGetError")).ret, 0x0502, "RGB is not a read format");
    console.log("PASS: reads");
}

// ---- a lost renderer; none

{
    const renderer = fake_renderer({ manual: true });
    const { host, conn, surface } = await setup(renderer);
    let read = null;
    const pending = conn.call("gles2:glReadPixels", 0, 0, 1, 1, 0x1908, 0x1401, 4).then(r => { read = r; });
    await settle();
    const warn = console.warn;
    console.warn = () => {};
    host.receive({ type: "lost", reason: "test" });
    console.warn = warn;
    await pending;
    assert.deepEqual(read.outs[0], new Uint8Array(4), "answered: zeros");
    const count = renderer.batches.length;
    conn.send("gles2:glClear", 0x4000);
    assert.equal((await conn.call("rcFlushWindowColorBuffer", surface)).ret, 0);
    assert.equal(renderer.batches.length, count, "nothing more is sent");

    const alone = await setup(null);
    alone.conn.send("gles2:glClear", 0x4000);
    assert.equal((await alone.conn.call("rcFlushWindowColorBuffer", alone.surface)).ret, 0);
    assert.deepEqual((await alone.conn.call("gles2:glReadPixels", 0, 0, 1, 1, 0x1908, 0x1401, 4)).outs[0], new Uint8Array(4));
    assert.equal(alone.host.summary().batches.submitted, 0);
    void cstring;
    console.log("PASS: a lost renderer, none");
}

// ---- the reader

{
    const writer = new GXWriter(GLES_MAGIC);
    writer.command(GLES.POST, [7]);
    const bytes = writer.finish();
    assert.deepEqual(read_gles_batch(bytes), [{ op: GLES.POST, name: "POST", color_buffer: 7 }]);
    const bad = bytes.slice();
    bad[0] ^= 1;
    assert.throws(() => read_gles_batch(bad), /magic/);
    const short = bytes.slice(0, bytes.length - 4);
    assert.throws(() => read_gles_batch(short), /dwords in the header/);
    const gx = new GXWriter();
    gx.command(1, [1]);
    assert.throws(() => read_gles_batch(gx.finish()), /magic/, "a GX batch is not a GLES one");
    console.log("PASS: the reader");
}
                          source/v64/tests/gles/chrome_renderer.mjs                                                           0000644 0000000 0000000 00000026640 00000000000 015646  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A renderer channel to a real GPU for Node tests (docs/gles-proxy-plan.md
// E3): headless Chrome (WebGPU) runs the page's renderer
// (tests/glbridge/gles_remote_renderer.html: V86SVGARenderer, its GLES
// executor) and the channel's messages cross over HTTP: the page long-polls
// GET /gles/next for what the device posts, POSTs /gles/reply with the
// renderer's answers. Each message is five u32s (kind, two values, the
// stream, the byte length), then its bytes padded to a u32. Both are
// numbered so that a request a suspend (the laptop's sleep) breaks is
// asked again without losing or repeating anything: the page asks
// /gles/next?got=<the answers it has read> and gets the last answer again
// when that one never arrived, and posts /gles/reply?n=<its number>, which
// is taken once. A snapshot's
// GLES state ([json, buffers], src/gles/gles_snapshot.js) crosses as one
// byte string (encode_state).
//
// chrome_renderer({ record }) resolves to the channel once the page is up;
// with `record` every batch also goes into that file (as recording_renderer
// writes them). close() ends Chrome and the server. GL_CHROME names another
// Chromium.
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
/** message kinds: the device's, then the renderer's */
export const KIND = { submit: 1, reset: 2, hello: 3, gles_save: 4, gles_restore: 5, done: 11, write: 12, frame: 13, lost: 14, caps: 15,
    gles_saved: 16 };

/** A packed state ([json, buffers]) as bytes: the JSON's length and UTF-8, the count, each buffer's length and bytes */
export function encode_state([json, buffers])
{
    const text = new TextEncoder().encode(json);
    const out = new Uint8Array(8 + text.length + buffers.reduce((n, b) => n + 4 + b.length, 0));
    const view = new DataView(out.buffer);
    view.setUint32(0, text.length, true);
    out.set(text, 4);
    let at = 4 + text.length;
    view.setUint32(at, buffers.length, true);
    at += 4;
    for(const b of buffers)
    {
        view.setUint32(at, b.length, true);
        out.set(b, at + 4);
        at += 4 + b.length;
    }
    return out;
}

/** @param {!Uint8Array} bytes encode_state's @return {!Array<*>} [json, buffers] */
export function decode_state(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const length = view.getUint32(0, true);
    const json = new TextDecoder().decode(bytes.subarray(4, 4 + length));
    let at = 4 + length;
    const count = view.getUint32(at, true);
    at += 4;
    const buffers = [];
    for(let i = 0; i < count; i++)
    {
        const n = view.getUint32(at, true);
        buffers.push(bytes.slice(at + 4, at + 4 + n));
        at += 4 + n;
    }
    return [json, buffers];
}

/** @param {!Array<{kind: number, a: number, b: number, stream: number, bytes: ?Uint8Array}>} messages @return {!Uint8Array} */
export function encode_messages(messages)
{
    const size = messages.reduce((n, m) => n + 20 + ((m.bytes ? m.bytes.length : 0) + 3 & ~3), 0);
    const out = new Uint8Array(size), view = new DataView(out.buffer);
    let at = 0;
    for(const m of messages)
    {
        const length = m.bytes ? m.bytes.length : 0;
        [m.kind, m.a >>> 0, m.b >>> 0, m.stream || 0, length].forEach((v, i) => view.setUint32(at + 4 * i, v, true));
        if(length) out.set(m.bytes, at + 20);
        at += 20 + (length + 3 & ~3);
    }
    return out;
}

/** @param {!Uint8Array} bytes @return {!Array<{kind: number, a: number, b: number, stream: number, bytes: !Uint8Array}>} */
export function decode_messages(bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const messages = [];
    for(let at = 0; at + 20 <= bytes.length;)
    {
        const length = view.getUint32(at + 16, true);
        messages.push({ kind: view.getUint32(at, true), a: view.getUint32(at + 4, true), b: view.getUint32(at + 8, true),
            stream: view.getUint32(at + 12, true), bytes: bytes.slice(at + 20, at + 20 + length) });
        at += 20 + (length + 3 & ~3);
    }
    return messages;
}

/**
 * @param {{record: (string|undefined), timeout: (number|undefined)}=} options
 * @return {!Promise<!Object>} the channel: post, listen, close, stats
 */
export async function chrome_renderer(options = {})
{
    let listener = () => {};
    const outbox = [];
    let waiting = null;
    // (the answers to /gles/next handed out and the last one's bytes; the last reply taken)
    let sent = 0, last = Buffer.alloc(0), replied = 0;
    // (lose_answers(): the next answer each way lost, its connection broken)
    const lose = { next: false, reply: false };
    const stats = { submitted: 0, bytes: 0, frames: 0, writes: 0, done: 0, resent: 0, repeated: 0 };
    if(options.record) fs.writeFileSync(options.record, new Uint8Array(0));
    let ready;
    const up = new Promise(resolve => { ready = resolve; });
    const answer = (res, body) =>
    {
        sent++;
        last = body;
        if(lose.next) { lose.next = false; res.socket.destroy(); return; }
        res.end(body);
    };
    const send_waiting = () =>
    {
        if(!waiting || !outbox.length) return;
        const res = waiting;
        waiting = null;
        answer(res, Buffer.from(encode_messages(outbox.splice(0))));
    };
    const server = http.createServer((req, res) =>
    {
        const url = new URL(req.url, "http://localhost");
        if(url.pathname === "/gles/next")
        {
            ready();
            // (a request the page gave up on: its answer, if any, is the one sent again below)
            if(waiting) waiting.end(Buffer.alloc(0));
            waiting = null;
            if(Number(url.searchParams.get("got") ?? sent) < sent)
            {
                stats.resent++;
                res.end(last);
                return;
            }
            waiting = res;
            send_waiting();
            // (an empty answer now and then: the page asks again)
            setTimeout(() => { if(waiting === res) { waiting = null; answer(res, Buffer.alloc(0)); } }, 15000);
            return;
        }
        if(url.pathname === "/gles/reply" && req.method === "POST")
        {
            const chunks = [];
            const n = Number(url.searchParams.get("n") || 0);
            req.on("data", d => chunks.push(d));
            req.on("end", () =>
            {
                if(lose.reply) { lose.reply = false; res.socket.destroy(); }
                else res.end("OK");
                // (a reply posted again after a broken request: taken already)
                if(n && n <= replied) { stats.repeated++; return; }
                if(n) replied = n;
                for(const m of decode_messages(new Uint8Array(Buffer.concat(chunks))))
                {
                    switch(m.kind)
                    {
                        case KIND.done: stats.done++; listener({ type: "done", seq: m.a }); break;
                        case KIND.write: stats.writes++; listener({ type: "write", offset: m.a, bytes: m.bytes }); break;
                        case KIND.frame: stats.frames++; listener({ type: "frame", width: m.a, height: m.b, bytes: m.bytes }); break;
                        case KIND.lost: listener({ type: "lost", reason: new TextDecoder().decode(m.bytes) }); break;
                        case KIND.caps: listener({ type: "caps", present: !!m.a }); break;
                        case KIND.gles_saved: listener({ type: "gles_saved", id: m.a, state: m.b ? decode_state(m.bytes) : null }); break;
                    }
                }
            });
            return;
        }
        if(url.pathname === "/gles/log" && req.method === "POST")
        {
            let body = "";
            req.on("data", d => { body += d; });
            req.on("end", () => { res.end("OK"); console.log("[chrome] " + body.slice(0, 2000)); });
            return;
        }
        const file = path.resolve(root, "." + url.pathname);
        if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
        fs.readFile(file, (error, data) =>
        {
            if(error) { res.writeHead(404).end(); return; }
            res.setHeader("Content-Type", /\.(js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".wasm") ? "application/wasm" : "text/html");
            res.end(data);
        });
    });
    await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
    const profile = fs.mkdtempSync(path.join(os.tmpdir(), "gles-renderer-"));
    const url = `http://127.0.0.1:${server.address().port}/tests/glbridge/gles_remote_renderer.html`;
    const browser = spawn(process.env.GL_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--enable-unsafe-webgpu", "--no-first-run", "--no-default-browser-check",
        "--disable-background-networking", "--disable-background-timer-throttling", "--disable-renderer-backgrounding",
        `--user-data-dir=${profile}`, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", d => { stderr = (stderr + d).slice(-4000); });
    // (Chrome goes with the test, however it ends)
    process.once("exit", () => browser.kill());
    for(const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { browser.kill(); process.exit(128 + (signal === "SIGINT" ? 2 : 15)); });
    const timer = setTimeout(() => ready(new Error("Chrome's renderer page did not start\n" + stderr)), options.timeout || 30000);
    const started = await up;
    clearTimeout(timer);
    if(started instanceof Error) throw started;
    const queue = message =>
    {
        outbox.push(message);
        send_waiting();
    };
    return {
        stats,
        listen(handler) { listener = handler; },
        post(message)
        {
            switch(message.type)
            {
                case "submit":
                    stats.submitted++;
                    stats.bytes += message.bytes.length;
                    if(options.record)
                    {
                        fs.appendFileSync(options.record, new Uint8Array(new Uint32Array([message.bytes.length]).buffer));
                        fs.appendFileSync(options.record, message.bytes);
                    }
                    queue({ kind: KIND.submit, a: message.seq, b: 0, stream: message.stream === "gles" ? 1 : 0, bytes: message.bytes });
                    break;
                case "reset": queue({ kind: KIND.reset, a: 0, b: 0, bytes: null }); break;
                case "hello": queue({ kind: KIND.hello, a: 0, b: 0, bytes: null }); break;
                case "gles_save": queue({ kind: KIND.gles_save, a: message.id, b: 0, bytes: null }); break;
                case "gles_restore": queue({ kind: KIND.gles_restore, a: 0, b: 0, bytes: encode_state(message.state) }); break;
            }
        },
        /** the next answer to the page and the next to its reply lost, as a suspend loses them (tests) */
        lose_answers() { lose.next = lose.reply = true; },
        close()
        {
            browser.kill();
            if(waiting) waiting.end(Buffer.alloc(0));
            server.close();
            server.closeAllConnections?.();
            // (Chrome may still be writing its profile: removed once it is gone)
            browser.once("exit", () => { try { fs.rmSync(profile, { recursive: true, force: true }); } catch(e) { /* left in the temporary directory */ } });
        },
    };
}
                                                                                                source/v64/tests/gles/chrome_renderer_test.mjs                                                      0000644 0000000 0000000 00000007126 00000000000 016703  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The GLES host with a real GPU behind it (tests/gles/chrome_renderer.mjs:
// headless Chrome's renderer page): a window cleared green with a
// scissored red corner, its frame flushed into its color buffer and posted,
// the frame read back (rows from the top: the red corner, GL's bottom left,
// at the frame's bottom left), a color buffer read with its pixels; a
// snapshot's page state over the bridge and back; a read whose answers
// both ways are lost on the way (a suspend breaks the requests) asked again.
import assert from "node:assert/strict";
import { GLESHost } from "../../src/gles/gles_host.js";
import { chrome_renderer } from "./chrome_renderer.mjs";
import { client } from "./lib.mjs";

const renderer = await chrome_renderer();
try
{
    const frames = [];
    const host = new GLESHost({ width: 8, height: 8, dpi: 160 }, renderer, (rgba, width, height) => frames.push({ rgba, width, height }));
    const { call, send } = await client(host).connect();
    const context = (await call("rcCreateContext", 3, 0, 2)).ret;
    const surface = (await call("rcCreateWindowSurface", 3, 8, 8)).ret;
    const buffer = (await call("rcCreateColorBuffer", 8, 8, 0x1908)).ret;
    await call("rcSetWindowColorBuffer", surface, buffer);
    await call("rcMakeCurrent", context, surface, surface);
    send("gles2:glClearColor", 0, 1, 0, 1);
    send("gles2:glClear", 0x4000);
    send("gles2:glEnable", 0x0C11);
    send("gles2:glScissor", 0, 0, 2, 2);
    send("gles2:glClearColor", 1, 0, 0, 1);
    send("gles2:glClear", 0x4000);
    assert.equal((await call("rcFlushWindowColorBuffer", surface)).ret, 0);
    await call("rcFBPost", buffer);
    const read = await call("rcReadColorBuffer", buffer, 0, 7, 1, 1, 0x1908, 0x1401, 4);
    assert.deepEqual(Array.from(read.outs[0]), [255, 0, 0, 255], "the color buffer's last row (the bottom) begins red");
    for(let i = 0; i < 100 && !frames.length; i++) await new Promise(resolve => setTimeout(resolve, 50));
    assert.equal(frames.length, 1, "the post came back as a frame");
    const f = frames[0];
    const at = (x, y) => Array.from(f.rgba.subarray((y * f.width + x) * 4, (y * f.width + x) * 4 + 4));
    assert.deepEqual([f.width, f.height, at(0, 7), at(0, 0), at(7, 7)], [8, 8, [255, 0, 0, 255], [0, 255, 0, 255], [0, 255, 0, 255]]);
    // a snapshot over the bridge (E5): the page's state fetched, the page
    // reset and given it back; the color buffer reads as before
    await host.prepare_save();
    const state = host.get_state();
    assert.ok(state[2] && state[2][1].length > 0, "the page's state, with the GPU's contents");
    host.set_state(state);
    const back = await call("rcReadColorBuffer", buffer, 0, 0, 8, 8, 0x1908, 0x1401, 256);
    const px = (x, y) => Array.from(back.outs[0].subarray((y * 8 + x) * 4, (y * 8 + x) * 4 + 4));
    assert.deepEqual([px(0, 7), px(0, 0), px(7, 7)], [[255, 0, 0, 255], [0, 255, 0, 255], [0, 255, 0, 255]], "restored: the color buffer's picture");
    // the device's batch and the page's reply each lost once: the page asks
    // for the batch again and posts its reply again, which is taken once
    renderer.lose_answers();
    const lost = await call("rcReadColorBuffer", buffer, 0, 7, 1, 1, 0x1908, 0x1401, 4);
    assert.deepEqual(Array.from(lost.outs[0]), [255, 0, 0, 255], "read after the lost answers");
    assert.ok(renderer.stats.resent >= 1 && renderer.stats.repeated >= 1, "the batch sent again, the reply posted again: " + JSON.stringify(renderer.stats));
    console.log("PASS: the GLES host on a real GPU, a snapshot round trip (" + JSON.stringify(renderer.stats) + ")");
}
finally
{
    renderer.close();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/gles/lib.mjs                                                                       0000644 0000000 0000000 00000015545 00000000000 013253  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the GLES tests share: a renderer channel that keeps the batches it
// is sent (and answers them: done, reads with a pattern), and a guest
// client of a host's services (a process pipe, connections whose calls are
// encoded as the guest's encoder does and whose replies are read back).
import fs from "node:fs";
import { command_of_name, decode_reply, encode_command, has_reply } from "../../src/gles/gles_wire.js";
import { read_gles_batch } from "../../src/gles/gles_batch.js";
import { READBACK_HEADER_BYTES, RESPONSE_OK } from "../../src/graphics_adapters/renderer_protocol.js";

/**
 * A renderer channel: `batches` the submitted batches' bytes; with `manual`
 * nothing is answered until run(); reads are answered with bytes of the
 * request id's value; a snapshot's page state (gles_save) is
 * ["page state <n>", []], and the states given back are `restored`
 * @param {{manual: (boolean|undefined)}=} options
 */
export function fake_renderer(options = {})
{
    let listener = null;
    const pending = [];
    const channel = {
        batches: [], messages: [], restored: [], saves: 0,
        post(message)
        {
            channel.messages.push(message.type);
            if(message.type === "gles_save")
            {
                const id = message.id, n = ++channel.saves;
                setTimeout(() => listener({ type: "gles_saved", id, state: ["page state " + n, []] }), 0);
                return;
            }
            if(message.type === "gles_restore") channel.restored.push(message.state);
            if(message.type !== "submit") return;
            channel.batches.push(message.bytes);
            pending.push(message);
            if(!options.manual) channel.run();
        },
        listen(handler) { listener = handler; },
        /** answer the batches sent so far (at most `count`): their reads, then done */
        run(count = Infinity)
        {
            while(pending.length && count-- > 0)
            {
                const message = pending.shift();
                for(const record of read_gles_batch(message.bytes))
                {
                    if(!["READ_PIXELS", "COLOR_BUFFER_READ", "BUFFER_READ", "QUERY_READ"].includes(record.name)) continue;
                    const size = record.name === "BUFFER_READ" ? record.length : record.name === "QUERY_READ" ? 4 : record.width * record.height * 4;
                    const bytes = new Uint8Array(READBACK_HEADER_BYTES + size);
                    const view = new DataView(bytes.buffer);
                    view.setUint32(0, record.request, true);
                    view.setUint32(4, size, true);
                    view.setUint32(12, RESPONSE_OK, true);
                    bytes.fill(record.request & 0xFF, READBACK_HEADER_BYTES);
                    listener({ type: "write", offset: 0, bytes });
                }
                listener({ type: "done", seq: message.seq });
            }
        },
        /** every record of every batch so far */
        records(decode = true) { return channel.batches.flatMap(bytes => read_gles_batch(bytes, decode)); },
    };
    return channel;
}

/** Let promises settle (replies that waited) */
export const settle = () => new Promise(resolve => setTimeout(resolve, 0));

/**
 * A guest process of a host: its process id from GLProcessPipe, and
 * connections whose calls return their decoded replies
 * @param {!Object} host a GLESHost
 */
export function client(host)
{
    const process_pipe = host.service("GLProcessPipe", () => {});
    process_pipe.write(new Uint8Array(new Uint32Array([100]).buffer));
    const id = process_pipe.read(8);
    const puid = new DataView(id.buffer, id.byteOffset).getUint32(0, true);
    const connect = async () =>
    {
        const service = host.service("opengles", () => {});
        service.write(new Uint8Array(4));
        /** @return {!Promise<{outs: !Array<!Uint8Array>, ret: number}>} */
        const call = async (name, ...args) =>
        {
            service.write(encode_command(name, args));
            await settle();
            // (a reply that waits for the page: until it is there, or a broken stream's none)
            for(let tries = 0; has_reply(command_of_name(name)) && !service.available(); tries++)
            {
                if(tries > 20000) throw new Error(name + ": no reply (" + JSON.stringify(host.summary().malformed) + ")");
                await settle();
            }
            const parts = [];
            for(let bytes; (bytes = service.read(1 << 20));) parts.push(bytes.slice());
            const reply = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
            let at = 0;
            for(const p of parts) { reply.set(p, at); at += p.length; }
            return reply.length ? decode_reply(name, args, reply) : { outs: [], ret: undefined };
        };
        /** a call whose reply is not read (it does not have one) */
        const send = (name, ...args) => service.write(encode_command(name, args));
        await call("rcSetPuid", puid);
        return { call, send, service };
    };
    return { puid, process_pipe, connect };
}

export const i32s = bytes => Array.from(new Int32Array(bytes.slice().buffer));
export const f32s = bytes => Array.from(new Float32Array(bytes.slice().buffer));
export const text = bytes => new TextDecoder().decode(bytes.subarray(0, bytes.indexOf(0)));
export const ints = values => new Uint8Array(new Int32Array(values).buffer);
export const floats = values => new Uint8Array(new Float32Array(values).buffer);
export const cstring = s => new TextEncoder().encode(s + "\0");

/**
 * A renderer channel that records every batch into a file (each a u32
 * length, then the batch: tools/gles/batches.mjs reads them) and answers as
 * the page without an executor does: reads failed (the guest reads zeros),
 * each batch done
 * @param {string} file
 */
export function recording_renderer(file)
{
    fs.writeFileSync(file, new Uint8Array(0));
    let listener = null;
    const channel = {
        batches: 0, bytes: 0,
        post(message)
        {
            if(message.type !== "submit") return;
            const length = new Uint8Array(new Uint32Array([message.bytes.length]).buffer);
            fs.appendFileSync(file, length);
            fs.appendFileSync(file, message.bytes);
            channel.batches++;
            channel.bytes += message.bytes.length;
            for(const record of read_gles_batch(message.bytes))
            {
                if(record.name !== "READ_PIXELS" && record.name !== "COLOR_BUFFER_READ") continue;
                const bytes = new Uint8Array(READBACK_HEADER_BYTES);
                new DataView(bytes.buffer).setUint32(0, record.request, true);
                new DataView(bytes.buffer).setUint32(12, 2, true);
                listener({ type: "write", offset: 0, bytes });
            }
            listener({ type: "done", seq: message.seq });
        },
        listen(handler) { listener = handler; },
    };
    return channel;
}
                                                                                                                                                           source/v64/tests/gles/protocol.mjs                                                                  0000644 0000000 0000000 00000024003 00000000000 014333  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The GLES wire format (docs/gles-proxy-plan.md "协议与生成器", E1):
// - the generated tables (src/gles/gles_protocol.js): each API's base and
//   size, ranges that do not overlap, the layouts of commands whose shape
//   the guest's encoder (API 25's libGLESv2_enc, lib_renderControl_enc) is
//   known to use; every renderControl command the API 25 guest calls;
// - every command encoded as the guest's encoder would (gles_wire.js's test
//   encoder), decoded, answered and the answer read back: the same values;
// - a command whose parameters do not fill it is refused;
// - with the pinned specs at hand (build/gles/gfxstream-7e9d595b, or
//   GLES_SPECS), tools/gles/gen.mjs makes the same file.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import { fileURLToPath } from "node:url";
import { GLES_APIS } from "../../src/gles/gles_protocol.js";
import { GLES_RANGES, KIND_BYTES, OutBuffer, command_of_name, command_of_opcode, decode_arguments, decode_reply, encode_command,
    encode_reply, has_reply } from "../../src/gles/gles_wire.js";

const root = fileURLToPath(new URL("../../", import.meta.url));

// ---- the tables

{
    assert.deepEqual(Object.fromEntries(Object.entries(GLES_APIS).map(([api, { base, commands }]) => [api, [base, commands.length]])),
        { rc: [10000, 72], gles1: [1024, 293], gles2: [2048, 439] }, "the pinned specs' bases and sizes");
    const sorted = [...GLES_RANGES].sort((a, b) => a.first - b.first);
    for(let i = 1; i < sorted.length; i++) assert.ok(sorted[i].first > sorted[i - 1].last, "ranges apart: " + sorted[i].api);
    assert.equal(command_of_opcode(10000).name, "rcGetRendererVersion");
    assert.equal(command_of_opcode(1024).name, "glAlphaFunc");
    assert.equal(command_of_opcode(2048).name, "glActiveTexture");
    assert.equal(command_of_opcode(10072), null);
    assert.equal(command_of_opcode(1023), null);
    // (GLESv1's and GLESv2's names apart; a bare name is the first API's)
    assert.equal(command_of_name("gles2:glGetIntegerv").api, "gles2");
    assert.equal(command_of_name("gles1:glGetIntegerv").api, "gles1");

    const shape = name => { const c = command_of_name(name); return [c.ret, c.params.map(p => p.slice(1).flat().join(" "))]; };
    assert.deepEqual(shape("rcChooseConfig"), ["i32", ["ptr in", "u32", "ptr out nullAllowed", "u32"]]);
    assert.deepEqual(shape("rcCreateSyncKHR"), ["void", ["u32", "ptr in", "u32", "i32", "ptr out", "ptr out"]]);
    assert.deepEqual(shape("rcClientWaitSyncKHR"), ["i32", ["u64", "i32", "u64"]]);
    assert.deepEqual(shape("rcUpdateColorBuffer"), ["i32", ["u32", "i32", "i32", "i32", "i32", "u32", "u32", "ptr in isLarge"]]);
    assert.deepEqual(shape("rcUpdateColorBufferDMA")[1].slice(7), ["ptr in DMA", "u32"]);
    assert.deepEqual(shape("gles2:glTexImage2D"), ["void", ["u32", "i32", "i32", "i32", "i32", "i32", "u32", "u32", "ptr in nullAllowed isLarge"]]);
    assert.deepEqual(shape("gles2:glVertexAttribPointerData"), ["void", ["u32", "i32", "u32", "u8", "i32", "ptr in", "u32"]]);
    assert.deepEqual(shape("gles2:glShaderString"), ["void", ["u32", "ptr in", "i32"]]);
    assert.deepEqual(shape("gles2:glGetShaderPrecisionFormat"), ["void", ["u32", "u32", "ptr out", "ptr out"]]);
    assert.deepEqual(shape("gles2:glFinishRoundTrip"), ["i32", []]);
    assert.deepEqual(shape("gles1:glClearColorx"), ["void", ["i32", "i32", "i32", "i32"]]);
    assert.deepEqual(shape("gles1:glDrawTexsOES"), ["void", ["i16", "i16", "i16", "i16", "i16"]]);
    assert.ok(command_of_name("gles2:glGetString").flags.includes("unsupported"), "glGetString never on the wire (rcGetGLString instead)");

    // the API 25 guest's renderControl (lib_renderControl_enc's symbols, docs/gles-proxy-plan.md "复核结论")
    for(const name of ["rcGetRendererVersion", "rcGetEGLVersion", "rcQueryEGLString", "rcGetGLString", "rcGetNumConfigs", "rcGetConfigs",
        "rcChooseConfig", "rcGetFBParam", "rcCreateContext", "rcDestroyContext", "rcCreateWindowSurface", "rcDestroyWindowSurface",
        "rcCreateColorBuffer", "rcOpenColorBuffer", "rcOpenColorBuffer2", "rcCloseColorBuffer", "rcSetWindowColorBuffer",
        "rcFlushWindowColorBuffer", "rcFlushWindowColorBufferAsync", "rcMakeCurrent", "rcFBPost", "rcFBSetSwapInterval", "rcBindTexture",
        "rcBindRenderbuffer", "rcColorBufferCacheFlush", "rcReadColorBuffer", "rcUpdateColorBuffer", "rcUpdateColorBufferDMA",
        "rcCreateColorBufferDMA", "rcCreateClientImage", "rcDestroyClientImage", "rcSelectChecksumHelper", "rcCreateSyncKHR",
        "rcClientWaitSyncKHR", "rcWaitSyncKHR", "rcDestroySyncKHR", "rcSetPuid"])
    {
        assert.equal(command_of_name(name)?.api, "rc", name);
    }
    console.log("PASS: the tables");
}

// ---- every command: encoded, decoded, answered, the answer read back

{
    let seed = 1;
    const random = () => (seed = seed * 1103515245 + 12345 >>> 0) / 0x100000000;
    const value_of = kind =>
    {
        switch(kind)
        {
            case "u8": return random() * 256 | 0;
            case "i16": return (random() * 65536 | 0) - 32768;
            case "u16": return random() * 65536 | 0;
            case "i32": return (random() * 0x100000000 | 0);
            case "u32": return random() * 0x100000000 >>> 0;
            case "f32": return Math.fround(random() * 200 - 100);
            case "u64": return Math.floor(random() * 2 ** 52);
            case "i64": return Math.floor(random() * 2 ** 52) - 2 ** 51;
        }
        throw new Error(kind);
    };
    let checked = 0, answered = 0;
    for(const [api, { commands }] of Object.entries(GLES_APIS))
    {
        for(const [name] of commands)
        {
            const command = command_of_name(api + ":" + name);
            const args = command.params.map(([, kind, dir, flags]) =>
            {
                if(kind !== "ptr") return value_of(kind);
                if(flags && flags.includes("DMA")) return Math.floor(random() * 2 ** 40);
                const length = random() * 40 | 0;
                if(dir === "out") return length;
                return Uint8Array.from({ length }, () => random() * 256 | 0);
            });
            const bytes = encode_command(api + ":" + name, args);
            assert.equal(new DataView(bytes.buffer).getUint32(0, true), command.opcode, name);
            assert.equal(new DataView(bytes.buffer).getUint32(4, true), bytes.length, name);
            const decoded = decode_arguments(command, bytes);
            const outs = [];
            command.params.forEach(([, kind, dir, flags], i) =>
            {
                const got = decoded[i];
                if(kind !== "ptr") assert.equal(got, args[i], name + " " + i);
                else if(flags && flags.includes("DMA")) assert.deepEqual(got, { dma: args[i] }, name + " " + i);
                else if(dir === "out")
                {
                    assert.ok(got instanceof OutBuffer && got.size === args[i], name + " " + i);
                    got.data.set(Uint8Array.from({ length: got.size }, () => random() * 256 | 0));
                    outs.push(got.data.slice());
                }
                else if(dir === "inout")
                {
                    assert.deepEqual(got.data, args[i], name + " " + i);
                    got.data.reverse();
                    outs.push(got.data.slice());
                }
                else if(!args[i].length && flags && flags.includes("nullAllowed")) assert.equal(got, null, name + " " + i);
                else assert.deepEqual(got, args[i], name + " " + i);
            });
            const ret = command.ret === "void" ? undefined : value_of(command.ret);
            const reply = encode_reply(command, decoded, ret);
            if(has_reply(command) && reply)
            {
                const back = decode_reply(api + ":" + name, args, reply);
                assert.deepEqual(back.outs.map(b => b.slice()), outs, name + "'s out pointers");
                if(command.ret !== "void") assert.equal(back.ret, command.ret === "f32" ? Math.fround(ret) : ret, name + "'s return value");
                answered++;
            }
            else
            {
                assert.equal(KIND_BYTES[command.ret] + outs.reduce((n, b) => n + b.length, 0), 0, name + ": no reply, nothing to answer");
            }
            checked++;
        }
    }
    assert.equal(checked, 72 + 293 + 439);
    console.log(`PASS: ${checked} commands round trip (${answered} with a reply)`);
}

// ---- a command its parameters do not fill

{
    const command = command_of_name("rcFBPost");
    const bytes = encode_command("rcFBPost", [5]);
    assert.deepEqual(decode_arguments(command, bytes), [5]);
    const longer = new Uint8Array(bytes.length + 4);
    longer.set(bytes);
    new DataView(longer.buffer).setUint32(4, longer.length, true);
    assert.throws(() => decode_arguments(command, longer), /take 12 bytes, the command has 16/);
    const shader = encode_command("gles2:glShaderString", [3, new TextEncoder().encode("void main(){}\0"), 14]);
    new DataView(shader.buffer).setUint32(12, 1000, true);
    assert.throws(() => decode_arguments(command_of_name("gles2:glShaderString"), shader), /beyond the command/);
    console.log("PASS: malformed commands");
}

// ---- the generator against the pinned specs

{
    const specs = process.env.GLES_SPECS || [root + "build/gles/gfxstream-7e9d595b/codegen", root + "../../build/gles/gfxstream-7e9d595b/codegen"]
        .find(dir => fs.existsSync(dir));
    if(specs && fs.existsSync(specs))
    {
        const out = fs.mkdtempSync(os.tmpdir() + "/gles-gen-") + "/gles_protocol.js";
        execFileSync(process.execPath, [root + "tools/gles/gen.mjs", specs, out], { encoding: "utf8" });
        assert.equal(fs.readFileSync(out, "utf8"), fs.readFileSync(root + "src/gles/gles_protocol.js", "utf8"), "gen.mjs makes the same tables");
        fs.rmSync(out.replace(/\/[^/]+$/, ""), { recursive: true });
        console.log("PASS: tools/gles/gen.mjs (" + specs + ")");
    }
    else
    {
        console.log("SKIP: tools/gles/gen.mjs (no pinned specs: GLES_SPECS)");
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/gles/render_control.mjs                                                            0000644 0000000 0000000 00000030317 00000000000 015516  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// renderControl (src/gles/render_control.js; docs/gles-proxy-plan.md E1,
// E2), through the host's services as a transport drives them, the guest's
// bytes made by the test encoder:
// - the configurations as gfxstream packs them (the attributes' row, then
//   one row each), eglChooseConfig's matching and order for what
//   SurfaceFlinger and GLSurfaceView ask, the EGL and GL strings by the
//   current context's API, the screen's parameters;
// - contexts, window surfaces, make-current; color buffers opened and
//   closed by reference, a process's going (its GLProcessPipe closed)
//   dropping what it had, and the page hearing of every object made and
//   gone; sync objects; client images;
// - the plugin as built (build/v86-gles.js): its descriptor and service.
import assert from "node:assert/strict";
import fs from "node:fs";
import { fileURLToPath, pathToFileURL as path_to_file_url } from "node:url";
import { GLESHost } from "../../src/gles/gles_host.js";
import { CONFIGS, CONFIG_ATTRIBUTES, EGL, choose_configs } from "../../src/gles/gles_caps.js";
import { encode_command } from "../../src/gles/gles_wire.js";
import { client, fake_renderer, i32s, ints, settle, text } from "./lib.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const DISPLAY = { width: 480, height: 800, dpi: 240 };

// ---- configurations

{
    const host = new GLESHost(DISPLAY, fake_renderer());
    const { call } = await client(host).connect();
    assert.equal((await call("rcGetRendererVersion")).ret, 1);
    const version = await call("rcGetEGLVersion", 4, 4);
    assert.deepEqual([i32s(version.outs[0])[0], i32s(version.outs[1])[0], version.ret], [1, 4, EGL.TRUE]);
    const count = await call("rcGetNumConfigs", 4);
    assert.equal(count.ret, CONFIGS.length);
    assert.equal(i32s(count.outs[0])[0], CONFIG_ATTRIBUTES.length);
    const size = (CONFIGS.length + 1) * CONFIG_ATTRIBUTES.length * 4;
    assert.equal((await call("rcGetConfigs", 16, 16)).ret, -size, "too small: minus the size needed");
    const configs = await call("rcGetConfigs", size, size);
    assert.equal(configs.ret, CONFIGS.length);
    const table = i32s(configs.outs[0]);
    assert.deepEqual(table.slice(0, CONFIG_ATTRIBUTES.length), CONFIG_ATTRIBUTES, "the attributes' ids first");
    const row = (config, attribute) => table[(config + 1) * CONFIG_ATTRIBUTES.length + CONFIG_ATTRIBUTES.indexOf(attribute)];
    assert.deepEqual([EGL.DEPTH_SIZE, EGL.STENCIL_SIZE, EGL.RENDERABLE_TYPE, EGL.SURFACE_TYPE, EGL.CONFIG_ID].map(a => CONFIG_ATTRIBUTES.indexOf(a)),
        [0, 1, 2, 3, 4], "gfxstream's first five");
    for(let c = 0; c < CONFIGS.length; c++) assert.equal(row(c, EGL.CONFIG_ID), c + 1);

    // SurfaceFlinger's (RenderEngine's selectEGLConfig with GLES 2.0)
    const surfaceflinger = [EGL.RENDERABLE_TYPE, EGL.OPENGL_ES2_BIT, EGL.RECORDABLE_ANDROID, EGL.TRUE,
        EGL.SURFACE_TYPE, EGL.WINDOW_BIT | EGL.PBUFFER_BIT, EGL.FRAMEBUFFER_TARGET_ANDROID, EGL.TRUE,
        EGL.RED_SIZE, 8, EGL.GREEN_SIZE, 8, EGL.BLUE_SIZE, 8, EGL.NONE, EGL.NONE];
    const n = await call("rcChooseConfig", ints(surfaceflinger), surfaceflinger.length * 4, 0, 0);
    assert.equal(n.ret, 8, "the 8-bit configurations, with and without alpha");
    const chosen = await call("rcChooseConfig", ints(surfaceflinger), surfaceflinger.length * 4, 16, 4);
    assert.equal(chosen.ret, 4);
    const first = i32s(chosen.outs[0]);
    assert.deepEqual(first.map(c => [row(c, EGL.ALPHA_SIZE), row(c, EGL.DEPTH_SIZE), row(c, EGL.STENCIL_SIZE)]),
        [[0, 0, 0], [0, 16, 0], [0, 24, 0], [0, 24, 8]], "EGL's order: the smaller buffer, then the smaller depth and stencil");
    assert.equal(row(first[0], EGL.NATIVE_VISUAL_ID), 2, "HAL_PIXEL_FORMAT_RGBX_8888");
    // (the fallback: any configuration whose visual is RGBA_8888)
    assert.ok(choose_configs([EGL.NONE]).some(c => CONFIGS[c][CONFIG_ATTRIBUTES.indexOf(EGL.NATIVE_VISUAL_ID)] === 1));
    // GLSurfaceView's default (8, 8, 8, 0 with depth 16), RGB565, ES 1, ES 3 (none), a config id
    const pick = list => choose_configs([...list, EGL.NONE]).map(c => c + 1);
    assert.deepEqual(pick([EGL.RED_SIZE, 8, EGL.GREEN_SIZE, 8, EGL.BLUE_SIZE, 8, EGL.DEPTH_SIZE, 16, EGL.RENDERABLE_TYPE, EGL.OPENGL_ES2_BIT]),
        [6, 7, 8, 2, 3, 4], "depth 16 and up; RGBX before RGBA (the smaller buffer)");
    const rgb565 = pick([EGL.RED_SIZE, 5, EGL.GREEN_SIZE, 6, EGL.BLUE_SIZE, 5]);
    assert.deepEqual([rgb565.length, rgb565[0], rgb565[8]], [12, 5, 9], "EGL's rule: the most color bits first, RGB565 last");
    assert.deepEqual(pick([EGL.RENDERABLE_TYPE, EGL.OPENGL_ES3_BIT]), []);
    assert.deepEqual(pick([EGL.CONFIG_ID, 6]), [6]);
    assert.deepEqual(pick([EGL.BUFFER_SIZE, 16, EGL.RED_SIZE, 5, EGL.ALPHA_SIZE, EGL.DONT_CARE]).slice(0, 1), [5],
        "red asked: its bits count, then the smaller buffer");
    // (no attributes at all: every configuration with a window and ES 1)
    assert.equal((await call("rcChooseConfig", null, 0, 0, 0)).ret, CONFIGS.length);

    // the screen
    const params = [];
    for(const p of [1, 2, 3, 4, 5, 6, 7, 99]) params.push((await call("rcGetFBParam", p)).ret);
    assert.deepEqual(params, [480, 800, 240, 240, 60, 1, 1, -1]);
    // strings: EGL's, GL's by the current context's API
    const egl = await call("rcQueryEGLString", EGL.VENDOR, 64, 64);
    assert.equal(text(egl.outs[0]), "v86");
    assert.equal((await call("rcQueryEGLString", EGL.VERSION, 2, 2)).ret, -8, "too small: minus the length with the NUL");
    // (as the guest's EGL asks: the size first, then the string)
    const gl = async name =>
    {
        const size = -(await call("rcGetGLString", name, 0, 0)).ret;
        const reply = await call("rcGetGLString", name, size, size);
        assert.equal(reply.ret, size);
        return text(reply.outs[0]);
    };
    assert.equal(await gl(0x1F02), "OpenGL ES 2.0 v86", "no context: GLES 2.0's");
    assert.match(await gl(0x1F03), /GL_OES_EGL_image_external /);
    assert.doesNotMatch(await gl(0x1F03), /ANDROID_EMU/, "no host features: no checksums, GLES 2.0");
    const context1 = (await call("rcCreateContext", 1, 0, 1)).ret;
    const surface = (await call("rcCreateWindowSurface", 1, 480, 800)).ret;
    assert.equal((await call("rcMakeCurrent", context1, surface, surface)).ret, EGL.TRUE);
    assert.equal(await gl(0x1F02), "OpenGL ES-CM 1.1 v86");
    assert.match(await gl(0x1F03), /GL_OES_draw_texture/);
    console.log("PASS: configurations, the screen, strings");
}

// ---- contexts, surfaces, color buffers, processes

{
    const renderer = fake_renderer();
    const host = new GLESHost(DISPLAY, renderer);
    const rc = host.rc;
    const a = client(host), b = client(host);
    assert.notEqual(a.puid, b.puid, "each process its own id");
    const ca = (await a.connect()).call, cb = (await b.connect()).call;
    // (SurfaceFlinger's process: a context, a window surface, current)
    const context = (await ca("rcCreateContext", 0, 0, 2)).ret;
    const shared = (await ca("rcCreateContext", 0, context, 2)).ret;
    assert.ok(context > 0 && shared > context);
    assert.equal((await ca("rcCreateContext", 99, 0, 2)).ret, 0, "no such configuration");
    assert.equal((await ca("rcCreateContext", 0, 12345, 2)).ret, 0, "no such context to share with");
    const surface = (await ca("rcCreateWindowSurface", 0, 480, 800)).ret;
    assert.equal((await ca("rcMakeCurrent", context, surface, surface)).ret, EGL.TRUE);
    assert.equal((await ca("rcMakeCurrent", 999, surface, surface)).ret, EGL.FALSE);
    assert.equal((await ca("rcMakeCurrent", context, 0, 0)).ret, EGL.TRUE, "surfaceless");
    assert.equal((await ca("rcMakeCurrent", 0, 0, 0)).ret, EGL.TRUE, "nothing current");
    // gralloc: a buffer of process a, imported by b, freed by a, released by b
    const buffer = (await ca("rcCreateColorBuffer", 480, 800, 0x1908)).ret;
    assert.ok(buffer > 0);
    assert.equal((await cb("rcOpenColorBuffer2", buffer)).ret, 0);
    assert.equal((await cb("rcOpenColorBuffer2", 4242)).ret, -1);
    await ca("rcSetWindowColorBuffer", surface, buffer);
    assert.equal(rc.surfaces.get(surface).color_buffer, buffer);
    assert.equal((await ca("rcFlushWindowColorBuffer", surface)).ret, 0);
    assert.equal((await ca("rcFlushWindowColorBuffer", 4242)).ret, -1);
    await ca("rcFBPost", buffer);
    assert.equal(rc.posts, 1);
    const pixels = new Uint8Array(480 * 800 * 4);
    assert.equal((await cb("rcUpdateColorBuffer", buffer, 0, 0, 480, 800, 0x1908, 0x1401, pixels)).ret, 0);
    assert.equal(rc.update_bytes, pixels.length);
    const read = await cb("rcReadColorBuffer", buffer, 0, 0, 2, 2, 0x1908, 0x1401, 16);
    assert.ok(read.outs[0].length === 16 && read.outs[0].every(v => v === read.outs[0][0] && v !== 0), "the page's pixels");
    await ca("rcCloseColorBuffer", buffer);
    assert.ok(rc.color_buffers.has(buffer), "b's reference keeps it");
    await cb("rcCloseColorBuffer", buffer);
    assert.ok(!rc.color_buffers.has(buffer), "the last reference gone");
    // images: a texture of a context, a gralloc buffer
    const other = (await cb("rcCreateColorBuffer", 64, 64, 0x1908)).ret;
    const image = (await cb("rcCreateClientImage", 0, 0x3140, other)).ret;
    assert.ok(image > 0);
    assert.equal((await cb("rcCreateClientImage", 0, 0x3140, 777)).ret, 0, "no such buffer");
    assert.equal((await cb("rcDestroyClientImage", image)).ret, 1);
    // syncs signal at once
    const sync = await ca("rcCreateSyncKHR", 0x30F9, ints([EGL.NONE]), 4, 0, 8, 8);
    const handle = Number(new BigUint64Array(sync.outs[0].slice().buffer)[0]);
    assert.ok(rc.syncs.has(handle));
    assert.equal((await ca("rcClientWaitSyncKHR", handle, 0, 1e9)).ret, EGL.CONDITION_SATISFIED_KHR);
    assert.equal((await ca("rcDestroySyncKHR", handle)).ret, 0);
    assert.ok(!rc.syncs.has(handle));
    // a process goes: its objects and references go with it
    const kept = (await cb("rcCreateColorBuffer", 32, 32, 0x1908)).ret;
    await ca("rcOpenColorBuffer", kept);
    a.process_pipe.close();
    assert.ok(!rc.contexts.has(context) && !rc.contexts.has(shared) && !rc.surfaces.has(surface), "process a's contexts and surface");
    assert.ok(rc.color_buffers.has(kept) && !rc.color_buffers.get(kept).refs.has("p" + a.puid), "b's buffer stays, a's reference goes");
    b.process_pipe.close();
    assert.equal(rc.color_buffers.size, 0);
    // (and the page heard of it all: every object made, every one gone)
    host.flush();
    const key = r => r.name.replace(/_(CREATE|DESTROY)$/, "") + ":" + (r.context || r.surface || r.color_buffer || r.image);
    const made = new Set(renderer.records().filter(r => r.name.endsWith("_CREATE")).map(key));
    const gone = new Set(renderer.records().filter(r => r.name.endsWith("_DESTROY")).map(key));
    assert.deepEqual([...made].sort(), [...gone].sort(), "every object the page heard of is gone again");
    assert.ok(made.has("CONTEXT:" + context) && made.has("COLOR_BUFFER:" + kept) && made.has("IMAGE:" + image));
    console.log("PASS: contexts, surfaces, color buffers, images, syncs, processes");
}

// ---- the plugin as built

{
    const file = root + "build/v86-gles.js";
    assert.ok(fs.existsSync(file), "build/v86-gles.js (make build/v86-gles.js)");
    await import(path_to_file_url(file).href);
    const descriptor = globalThis.V86GlesHosts && globalThis.V86GlesHosts.gles;
    assert.equal(descriptor.name, "gles");
    const renderer = fake_renderer();
    const device = descriptor.create({}, { display: DISPLAY, renderer });
    for(const name of ["service", "summary", "get_state", "set_state", "reset"]) assert.equal(typeof device[name], "function", name);
    assert.equal(device.service("qemud:other", () => {}), null);
    const service = device.service("opengles", () => {});
    service.write(new Uint8Array(4));
    service.write(encode_command("rcGetFBParam", [1]));
    await settle();
    assert.ok(service.available());
    assert.deepEqual(service.read(16), new Uint8Array([224, 1, 0, 0]), "480");
    assert.equal(device.summary().counts.rcGetFBParam, 1);
    service.close();
    device.set_state(device.get_state());
    // (the count of connections made is kept; none is open)
    assert.equal(device.summary().connections, 1);
    assert.equal(device.summary().open_connections, 0);
    assert.ok(renderer.messages.includes("hello") && renderer.messages.includes("reset"));
    console.log("PASS: build/v86-gles.js");
}
                                                                                                                                                                                                                                                                                                                 source/v64/tests/gles/shader_corpus.mjs                                                             0000644 0000000 0000000 00000047202 00000000000 015341  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The GLES host's shader path on a corpus (docs/gles3-plan.md L1): glslang's
// check pass against what dEQP expects of each shader case, then for the
// programs that link the whole way to WGSL: the code pass (SPIR-V),
// glsl_program.js's interface and bindings, vx_naga, and naga's validation
// of the WGSL (when `naga` is installed; Tint's is
// tests/glbridge/gles_shader_browser_test.html, over the WGSL this writes).
//
// The corpus is dEQP's shader library (the .test files of CTS 7.1's
// com.drawelements.deqp.apk: gles2, gles3 and gles31 shaders), filled in
// as dEQP's ShaderLibrary does (simplified: inputs are uniforms, outputs
// globals), and this file's own GLSL ES 3.10/3.20 cases. Without the APK
// (build/a32-android/cts, tools/a32_cts.mjs) only the own cases run.
//
//   node tests/gles/shader_corpus.mjs [--naga] [--filter regexp] [--wgsl file] [--verbose]

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { compile_glslang, create_glslang, STAGE } from "../../src/gles/glslang.js";
import { link_glslang_program } from "../../src/gles/glsl_program.js";
import { es3_rules, glsl_version } from "../../src/gles/glsl_es_rewrite.js";
import { glslang_limits } from "../../src/gles/gles31_state.js";
import { zip_entries, zip_read } from "../../src/android/zip.js";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const argv = process.argv.slice(2);
const option = name => argv.includes(name) ? argv[argv.indexOf(name) + 1] : undefined;
const verbose = argv.includes("--verbose");
const filter = option("--filter") ? new RegExp(option("--filter")) : null;
const LIMITS = { maxVaryingVectors: 15, maxDrawBuffers: 4 };

const glslang = await create_glslang(await compile_glslang(fs.readFileSync(root + "bios/glslang.wasm")));
glslang.set_limits({ MaxDrawBuffers: 4, MaxVaryingVectors: 15 });

// ---- vx_naga (no imports)
const naga_wasm = root + "build/glbridge/vx_naga.wasm";
const naga = fs.existsSync(naga_wasm) ? (await WebAssembly.instantiate(fs.readFileSync(naga_wasm), {})).instance.exports : null;
function translate(words)
{
    const bytes = new Uint8Array(words.buffer, words.byteOffset, words.byteLength);
    const input = naga.vx_alloc(bytes.length);
    new Uint8Array(naga.memory.buffer, input, bytes.length).set(bytes);
    const out = naga.vx_translate(input, bytes.length, 3, 0, 0, 0, 0, 0, 0);
    naga.vx_free(input, bytes.length);
    const length = new DataView(naga.memory.buffer).getUint32(out, true);
    const text = new TextDecoder().decode(new Uint8Array(naga.memory.buffer, out + 4, length));
    naga.vx_free(out, length + 4);
    return JSON.parse(text);
}

// ---- naga's CLI, for the WGSL
function find_naga()
{
    if(process.env.GL_NAGA) return process.env.GL_NAGA;
    const cargo = path.join(os.homedir(), ".cargo", "bin", "naga");
    return fs.existsSync(cargo) ? cargo : null;
}
const naga_cli = argv.includes("--naga") ? find_naga() : null;
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "gles-corpus-"));
function validate_wgsl(label, wgsl)
{
    const file = path.join(scratch, label.replace(/[^A-Za-z0-9_.-]/g, "_").slice(-120) + ".wgsl");
    fs.writeFileSync(file, wgsl);
    const r = spawnSync(naga_cli, [file], { encoding: "utf8" });
    return r.status === 0 ? null : (r.stderr || r.stdout).split("\n").slice(0, 8).join("\n");
}

// ---- dEQP's .test files
/**
 * @param {string} text
 * @return {!Array<!Object>} the cases: {name, version, expect, requires, values, sources: {both|vertex|...}}
 */
function parse_tests(text, prefix)
{
    const lines = text.split("\n");
    const cases = [];
    const groups = [];
    let current = null;
    for(let i = 0; i < lines.length; i++)
    {
        const line = lines[i].trim();
        if(!line || line.startsWith("#")) continue;
        let m;
        if((m = /^group\s+(\S+)/.exec(line))) { groups.push(m[1]); continue; }
        if((m = /^case\s+(\S+)/.exec(line)))
        {
            current = { name: prefix + [...groups, m[1]].join("."), version: "100", expect: "pass", requires: [], values: [], sources: {}, skip: null };
            continue;
        }
        if(line === "end")
        {
            if(current) { cases.push(current); current = null; }
            else groups.pop();
            continue;
        }
        if(!current) continue;
        if((m = /^version\s+(.+)$/.exec(line))) current.version = m[1].trim();
        else if((m = /^expect\s+(\S+)/.exec(line))) current.expect = m[1];
        else if(line.startsWith("require")) current.requires.push(line);
        else if(line.startsWith("pipeline_program") || line.startsWith("active_stages")) current.skip = "separable pipeline";
        else if(line.startsWith("values"))
        {
            let body = line;
            while(!body.includes("}")) body += " " + lines[++i];
            for(const v of body.slice(body.indexOf("{") + 1, body.lastIndexOf("}")).split(";"))
            {
                const d = /^\s*(input|output|uniform)\s+(.+?)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(\[[^\]]*\])?\s*=/.exec(v);
                if(d) current.values.push({ kind: d[1], type: d[2], name: d[3] });
            }
        }
        else if((m = /^(both|vertex|fragment|geometry|tessellation_control|tessellation_evaluation)\s+""\s*$/.exec(line)))
        {
            const body = [];
            while(++i < lines.length && lines[i].trim() !== "\"\"") body.push(lines[i]);
            current.sources[m[1]] = body.join("\n");
        }
    }
    return cases;
}

const EXTENSIONS_WE_HAVE = /GL_EXT_geometry_shader|GL_EXT_tessellation_shader|GL_EXT_shader_io_blocks|GL_OES_geometry_shader|GL_OES_tessellation_shader|GL_OES_shader_io_blocks/;

/** The programs a case runs: dEQP's specialization, simplified */
function specialize(c)
{
    const es = !/^100\b/.test(c.version);
    const version_line = es ? "#version " + c.version + "\n" : "";
    const frag_color = es ? "dEQP_FragColor" : "gl_FragColor";
    const precision = t => /^(lowp|mediump|highp)\b/.test(t) || /^(bool|bvec)/.test(t) ? "" : (/^(u?int|[iu]vec)/.test(t) ? "highp " : "mediump ");
    const inputs = c.values.filter(v => v.kind === "input"), outputs = c.values.filter(v => v.kind === "output");
    const uniforms = c.values.filter(v => v.kind === "uniform");
    // (inputs: uniforms, copied into locals by ${SETUP} where there is one)
    const has_setup = Object.values(c.sources).some(s => /\$\{(VERTEX_)?SETUP\}/.test(s));
    const prefix = has_setup ? "u_" : "";
    const uniform_decls = [...inputs.map(v => "uniform " + precision(v.type) + v.type + " " + prefix + v.name + ";"),
        ...uniforms.map(v => "uniform " + precision(v.type) + v.type + " " + v.name + ";")].join("\n");
    const setup = inputs.map(v => v.type + " " + v.name + " = u_" + v.name + ";").join("\n");
    const output_decls = outputs.map(v => precision(v.type) + v.type + " " + v.name + ";").join("\n");
    const position = (es ? "in" : "attribute") + " highp vec4 dEQP_Position;";
    const frag_out = es ? "layout(location = 0) out mediump vec4 dEQP_FragColor;" : "";
    const extension_lines = {};
    for(const r of c.requires)
    {
        const m = /extension\s*\{([^}]*)\}(?:\s*in\s*\{([^}]*)\})?/.exec(r);
        if(!m) { if(/limit "GL_MAX_VERTEX_(SHADER_STORAGE_BLOCKS|IMAGE_UNIFORMS|ATOMIC_COUNTERS)"/.test(r)) return { skip: "a vertex-stage limit of 0" }; continue; }
        const names = m[1].split("|").map(s => s.trim().replace(/"/g, ""));
        const name = names.find(n => EXTENSIONS_WE_HAVE.test(n));
        if(!name) return { skip: "extension " + names.join("|") };
        const stages = m[2] ? m[2].split(",").map(s => s.trim()) : ["vertex", "fragment", "geometry", "tessellation_control", "tessellation_evaluation"];
        for(const s of stages) extension_lines[s] = (extension_lines[s] || "") + "#extension " + name + " : require\n";
    }
    const fill = (source, stage, variant) =>
    {
        const decls = stage === "vertex" ? [position, uniform_decls, variant === "vertex" ? output_decls : ""].join("\n") :
            stage === "fragment" ? [frag_out, uniform_decls, variant !== "vertex" ? output_decls : ""].join("\n") : "";
        let s = source;
        if(!/^\s*#version/.test(s)) s = version_line + s;
        if(extension_lines[stage]) s = s.replace(/^(\s*#version[^\n]*\n)/, "$1" + extension_lines[stage]);
        return s.replace(/\$\{DECLARATIONS\}/g, decls)
            .replace(/\$\{VERTEX_DECLARATIONS\}/g, [position, uniform_decls].join("\n"))
            .replace(/\$\{FRAGMENT_DECLARATIONS\}/g, [frag_out, uniform_decls, output_decls].join("\n"))
            .replace(/\$\{GEOMETRY_DECLARATIONS\}/g, "layout (triangles) in;\nlayout (triangle_strip, max_vertices=3) out;")
            .replace(/\$\{TESSELLATION_CONTROL_DECLARATIONS\}/g, "layout (vertices=3) out;")
            .replace(/\$\{TESSELLATION_EVALUATION_DECLARATIONS\}/g, "layout (triangles) in;")
            .replace(/\$\{TESSELLATION_CONTROL_OUTPUT\}/g, "gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;")
            .replace(/\$\{TESSELLATION_EVALUATION_OUTPUT\}/g, "gl_Position = gl_in[0].gl_Position;")
            .replace(/\$\{GL_MAX_PATCH_VERTICES\}/g, "32")
            .replace(/\$\{SETUP\}|\$\{VERTEX_SETUP\}/g, setup)
            .replace(/\$\{POSITION_FRAG_COLOR\}/g, stage === "vertex" ? "gl_Position" : frag_color)
            .replace(/\$\{FRAG_COLOR\}/g, frag_color)
            .replace(/\$\{VERTEX_OUTPUT\}/g, "gl_Position = dEQP_Position;")
            .replace(/\$\{FRAGMENT_OUTPUT\}/g, frag_color + " = vec4(1.0);")
            .replace(/\$\{OUTPUT\}/g, stage === "vertex" ? "gl_Position = dEQP_Position;" : frag_color + " = vec4(1.0);");
    };
    const plain_vs = version_line + position + "\nvoid main() { gl_Position = dEQP_Position; }\n";
    const plain_fs = version_line + "precision mediump float;\n" + frag_out + "\nvoid main() { " + frag_color + " = vec4(1.0); }\n";
    const programs = [];
    if(c.sources.both !== undefined)
    {
        programs.push({ variant: "vertex", shaders: [{ stage: "vertex", source: fill(c.sources.both, "vertex", "vertex") },
            { stage: "fragment", source: fill(plain_fs, "fragment", "vertex") }] });
        programs.push({ variant: "fragment", shaders: [{ stage: "vertex", source: fill(plain_vs, "vertex", "fragment") },
            { stage: "fragment", source: fill(c.sources.both, "fragment", "fragment") }] });
    }
    else
    {
        const shaders = [];
        for(const stage of ["vertex", "tessellation_control", "tessellation_evaluation", "geometry", "fragment"])
        {
            if(c.sources[stage] === undefined) continue;
            const name = { tessellation_control: "tess_control", tessellation_evaluation: "tess_evaluation" }[stage] || stage;
            shaders.push({ stage: name, source: fill(c.sources[stage], stage, "separate") });
        }
        programs.push({ variant: "program", shaders });
    }
    return { programs };
}

// ---- this file's own cases: GLSL ES 3.10 and 3.20 that dEQP's library does not cover
const OWN = [
    { name: "own.compute_ssbo_atomics_images", expect: "pass", shaders: [{ stage: "compute", source: `#version 310 es
layout(local_size_x = 8, local_size_y = 4) in;
layout(std430, binding = 1) buffer B { uint n; int m; float v[]; } b;
layout(binding = 0) uniform atomic_uint counter;
layout(rgba8, binding = 2) writeonly uniform highp image2D img;
layout(r32ui, binding = 3) uniform highp uimage2D counts;
shared float s[32];
void main() {
    uint i = gl_LocalInvocationIndex;
    s[i] = b.v[i];
    barrier();
    b.v[i] = s[31u - i];
    atomicCounterIncrement(counter);
    imageStore(img, ivec2(gl_GlobalInvocationID.xy), vec4(1.0));
    imageStore(counts, ivec2(gl_GlobalInvocationID.xy), imageLoad(counts, ivec2(0)) + uvec4(1u));
    atomicAdd(b.n, 1u);
    atomicMin(b.m, -int(i));
}` }] },
    { name: "own.es300_ubo_mrt_integer", expect: "pass", shaders: [{ stage: "vertex", source: `#version 300 es
layout(location = 1) in vec4 pos;
in ivec2 id;
uniform Block { mat4 mvp; vec2 off[3]; } blk;
flat out ivec2 vid;
out vec2 tc;
void main() { vid = id; tc = blk.off[gl_VertexID % 3]; gl_Position = blk.mvp * pos; }` }, { stage: "fragment", source: `#version 300 es
precision highp float;
precision highp usampler2D;
precision mediump sampler2DArray;
uniform usampler2D utex;
uniform sampler2DArray arr;
flat in ivec2 vid;
in vec2 tc;
layout(location = 0) out vec4 c0;
layout(location = 1) out uvec4 c1;
void main() { c0 = texture(arr, vec3(tc, 1.0)); c1 = texelFetch(utex, vid, 0) + uvec4(textureSize(utex, 0), 0, 0); }` }] },
    // (instance arrays of storage blocks whose last member is an unsized array of structs, arrays or matrices: element 1's block
    // alone, the split array's types gone although a member's offset is the pointer type's id, dEQP-GLES31
    // ssbo.layout.unsized_struct_array and 2_level_unsized_struct_array's *_instance_array)
    ...["S s[];", "S s[][2];", "mat2x4 s[][2];"].map((member, i) => ({ name: "own.ssbo_instance_array_unsized_" + i, expect: "pass", shaders: [
        { stage: "compute", source: `#version 310 es
layout(local_size_x = 1) in;
struct S { highp ivec3 a; highp vec4 c; };
layout(std430, binding = 0) buffer Block { lowp uint u; mediump vec4 v; ${member} } b[3];
void main() { b[1].u = uint(b[1].s.length()); }` }] })),
    // (an unused storage block of an unsized array of row major matrices, which layout.rs lays out again: the old pointer type gone
    // although the int type's width is its id, dEQP-GLES31 ssbo.layout.random.nested_structs.3)
    { name: "own.ssbo_unused_row_major_unsized", expect: "pass", shaders: [{ stage: "compute", source: `#version 310 es
layout(local_size_x = 1) in;
layout(row_major, binding = 0) buffer BlockB { highp mat3x2 a[]; };
layout(binding = 0) uniform atomic_uint ac_numPassed;
void main() { bool allOk = true; if(allOk) atomicCounterIncrement(ac_numPassed); }` }] },
    { name: "own.es320_geometry", expect: "pass", shaders: [
        { stage: "vertex", source: "#version 320 es\nin vec4 pos;\nout vec2 tc;\nvoid main(){ tc = pos.xy; gl_Position = pos; }" },
        { stage: "geometry", source: "#version 320 es\nlayout(triangles) in;\nlayout(triangle_strip, max_vertices=3) out;\nin vec2 tc[];\nout vec2 gtc;\nvoid main(){ for(int i=0;i<3;i++){ gtc = tc[i]; gl_Position = gl_in[i].gl_Position; EmitVertex(); } EndPrimitive(); }" },
        { stage: "fragment", source: "#version 320 es\nprecision mediump float;\nin vec2 gtc;\nout vec4 c;\nvoid main(){ c = vec4(gtc, 0.0, 1.0); }" }] },
];

// ---- the run
const stats = { cases: 0, skipped: 0, programs: 0, agree: 0, disagree: 0, linked: 0, link_errors: 0, spirv: 0,
    naga_ok: 0, naga_errors: 0, wgsl_ok: 0, wgsl_errors: 0, stage_unsupported: 0, check_ms: 0, code_ms: 0 };
const disagreements = [], failures = [];
let own_failures = 0;
const wgsl_out = [];
/** @param {!Object} program @param {string} expect @param {string} label @param {string=} known an expected failure's reason */
function run_program(label, shaders, expect, known)
{
    stats.programs++;
    // the check pass, shader by shader then linked: what dEQP expects
    const t0 = performance.now();
    // (with the GLSL ES rules the shadow adds to glslang's check and its limits, gles_shadow.js's compile)
    glslang.set_limits(glslang_limits(glsl_version(shaders[0].source)));
    const compiled = shaders.map(s =>
    {
        const checked = glslang.check_shader(STAGE[s.stage], s.source);
        const refused = checked.ok ? es3_rules(s.source) : null;
        return refused ? { ok: false, log: refused } : checked;
    });
    const compiles = compiled.every(c => c.ok);
    const t1 = performance.now();
    const linked = compiles ? link_glslang_program(glslang, shaders, { limits: LIMITS }) : null;
    const t2 = performance.now();
    stats.check_ms += t1 - t0;
    stats.code_ms += t2 - t1;
    const links = !!(linked && linked.ok);
    const ok = expect === "compile_fail" ? !compiles : expect === "link_fail" ? compiles && !links :
        expect === "compile_or_link_fail" ? !links : links;
    if(ok) stats.agree++;
    else
    {
        stats.disagree++;
        if(label.startsWith("own.")) own_failures++;
        disagreements.push(label + ": expected " + expect + ", " + (!compiles ? "did not compile: " + compiled.map(c => c.log).join(" ").slice(0, 300) :
            !links ? "did not link: " + (linked && linked.log || "").slice(0, 300) : "built"));
    }
    if(!links) return;
    stats.linked++;
    for(const module of linked.spirv)
    {
        stats.spirv++;
        if(!naga) continue;
        if(module.stage !== "vertex" && module.stage !== "fragment" && module.stage !== "compute") { stats.stage_unsupported++; continue; }
        let t;
        try { t = translate(module.words); }
        catch(e) { t = { error: "vx_naga panicked: " + e.message }; }
        if(t.error)
        {
            stats.naga_errors++;
            failures.push(label + " " + module.stage + ": " + t.error.slice(0, 400));
            if(label.startsWith("own.") && !known) own_failures++;
            continue;
        }
        stats.naga_ok++;
        const wgsl = "diagnostic(off, derivative_uniformity);\n" + t.wgsl;
        wgsl_out.push({ label: label + "." + module.stage, wgsl });
        if(naga_cli)
        {
            const error = validate_wgsl(label + "." + module.stage, wgsl);
            if(error) { stats.wgsl_errors++; failures.push(label + " " + module.stage + " WGSL: " + error); }
            else stats.wgsl_ok++;
        }
    }
}

const apk = root + "build/a32-android/cts/com.drawelements.deqp.apk";
if(fs.existsSync(apk))
{
    const fd = fs.openSync(apk, "r");
    const size = fs.fstatSync(fd).size;
    const read = async(offset, length) => { const b = Buffer.alloc(length); fs.readSync(fd, b, 0, length, offset); return new Uint8Array(b); };
    const entries = await zip_entries(read, size);
    for(const e of entries.filter(e => /^assets\/gles(2|3|31)\/shaders\/.*\.test$/.test(e.name)))
    {
        const api = /assets\/(gles\d+)\//.exec(e.name)[1];
        const prefix = "dEQP-" + api.toUpperCase() + ".functional.shaders." + path.basename(e.name, ".test") + ".";
        const text = new TextDecoder().decode(await zip_read(read, e));
        for(const c of parse_tests(text, prefix))
        {
            if(filter && !filter.test(c.name)) continue;
            stats.cases++;
            if(c.skip) { stats.skipped++; continue; }
            const s = specialize(c);
            if(s.skip) { stats.skipped++; continue; }
            for(const p of s.programs) run_program(c.name + (s.programs.length > 1 ? "." + p.variant : ""), p.shaders, c.expect === "build_successful" ? "pass" : c.expect);
        }
    }
    fs.closeSync(fd);
}
else console.log("(no " + apk + ": dEQP's shader library not run; tools/a32_cts.mjs --download)");
for(const c of OWN)
{
    if(filter && !filter.test(c.name)) continue;
    stats.cases++;
    run_program(c.name, c.shaders, c.expect, c.known);
}

if(verbose) for(const d of disagreements) console.log("DISAGREE " + d);
for(const f of failures.slice(0, verbose ? failures.length : 15)) console.log("FAIL " + f);
if(!verbose && disagreements.length) console.log(disagreements.slice(0, 10).map(d => "DISAGREE " + d).join("\n"));
console.log(JSON.stringify(stats));
if(option("--wgsl")) fs.writeFileSync(option("--wgsl"), JSON.stringify(wgsl_out));
fs.rmSync(scratch, { recursive: true, force: true });
// (what L1 reached, docs/gles3-plan.md: a fall below it is a regression)
const deqp_programs = stats.programs - OWN.length;
const regressed = own_failures || stats.wgsl_errors || deqp_programs > 0 && (stats.agree < 0.98 * stats.programs || stats.naga_errors > 2);
if(regressed) console.log("FAIL: below L5's results (own cases, 98% agreement with dEQP, 2 vx_naga errors, no WGSL errors)");
process.exit(regressed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/gles/shadow.mjs                                                                    0000644 0000000 0000000 00000075445 00000000000 013777  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The shadow state (src/gles/gles_shadow.js; docs/gles-proxy-plan.md E2)
// against the OpenGL ES 2.0 specification, through the host as the guest
// drives it:
// - the initial state and glGet's conversions (booleans, integers, floats,
//   normalized colors), enables;
// - errors: the first one stays until glGetError; a refused call changes
//   nothing and does not reach the page, nor does a query;
// - names and objects: glGen reserves, binding makes, deleting unbinds and
//   detaches; textures' images, formats and parameters (and external ones');
//   buffers; renderbuffers; framebuffers and their completeness, draws on an
//   incomplete one refused; the bits of what is drawn to;
// - shaders and programs with GLSL ES (compile logs, link, active
//   attributes and uniforms, locations, glUniform's checks and values,
//   deletion while in use); vertex attributes;
// - a GLES 1.1 context's limits and its texture parameters.
import assert from "node:assert/strict";
import { GLESHost } from "../../src/gles/gles_host.js";
import { client, cstring, f32s, fake_renderer, floats, i32s, ints, text } from "./lib.mjs";

const GL = {
    NO_ERROR: 0, INVALID_ENUM: 0x0500, INVALID_VALUE: 0x0501, INVALID_OPERATION: 0x0502, INVALID_FRAMEBUFFER_OPERATION: 0x0506,
    TEXTURE_2D: 0x0DE1, TEXTURE_CUBE_MAP: 0x8513, TEXTURE_EXTERNAL_OES: 0x8D65, RGBA: 0x1908, RGB: 0x1907, LUMINANCE: 0x1909,
    UNSIGNED_BYTE: 0x1401, UNSIGNED_SHORT_5_6_5: 0x8363, UNSIGNED_SHORT_4_4_4_4: 0x8033, FLOAT: 0x1406,
    ARRAY_BUFFER: 0x8892, ELEMENT_ARRAY_BUFFER: 0x8893, STATIC_DRAW: 0x88E4, FRAMEBUFFER: 0x8D40, RENDERBUFFER: 0x8D41,
    COLOR_ATTACHMENT0: 0x8CE0, DEPTH_ATTACHMENT: 0x8D00, STENCIL_ATTACHMENT: 0x8D20, DEPTH_COMPONENT16: 0x81A5,
    RGB565: 0x8D62, RGBA8_OES: 0x8058, DEPTH24_STENCIL8_OES: 0x88F0, STENCIL_INDEX8: 0x8D48,
    VERTEX_SHADER: 0x8B31, FRAGMENT_SHADER: 0x8B30, BLEND: 0x0BE2, DITHER: 0x0BD0,
};

const DISPLAY = { width: 480, height: 800, dpi: 240 };
const renderer = fake_renderer();
const host = new GLESHost(DISPLAY, renderer);
const { call, send } = await client(host).connect();
// (config 3: RGBA8888 with 24-bit depth and 8-bit stencil)
const context = (await call("rcCreateContext", 3, 0, 2)).ret;
const surface = (await call("rcCreateWindowSurface", 3, 320, 240)).ret;
await call("rcMakeCurrent", context, surface, surface);
const c = host.shadow.context(context);
const error = async () => (await call("gles2:glGetError")).ret;
const get_i = async (pname, n = 1) => i32s((await call("gles2:glGetIntegerv", pname, 4 * n)).outs[0]);
const get_f = async (pname, n = 1) => f32s((await call("gles2:glGetFloatv", pname, 4 * n)).outs[0]);
const get_b = async (pname, n = 1) => Array.from((await call("gles2:glGetBooleanv", pname, n)).outs[0]);
/** one call after another: replies on a connection come in order */
const each = async (list, f) => { const out = []; for(const item of list) out.push(...await f(item)); return out; };
/** the GLES commands that reached the page */
const sent = () => { host.flush(); return renderer.records().filter(r => r.name === "COMMAND").map(r => r.command.name); };

// ---- the initial state, glGet's conversions, enables

{
    assert.deepEqual(await get_i(0x0BA2, 4), [0, 0, 320, 240], "GL_VIEWPORT: the surface's at the first MakeCurrent");
    assert.deepEqual(await get_i(0x0C10, 4), [0, 0, 320, 240], "GL_SCISSOR_BOX");
    assert.deepEqual(await get_f(0x0B70, 2), [0, 1], "GL_DEPTH_RANGE");
    assert.deepEqual(await get_i(0x0B70, 2), [0, 0x7FFFFFFF], "GL_DEPTH_RANGE as integers: 1.0 is the largest");
    assert.deepEqual(await get_b(0x0C23, 4), [1, 1, 1, 1], "GL_COLOR_WRITEMASK");
    assert.deepEqual(await get_i(0x0B74), [0x0201], "GL_DEPTH_FUNC: GL_LESS");
    assert.deepEqual(await get_i(0x0B98), [-1], "GL_STENCIL_WRITEMASK: all ones");
    assert.deepEqual(await get_i(0x0CF5), [4], "GL_UNPACK_ALIGNMENT");
    assert.deepEqual(await get_i(0x0D33), [4096], "GL_MAX_TEXTURE_SIZE");
    assert.deepEqual(await each([0x0D52, 0x0D53, 0x0D54, 0x0D55, 0x0D56, 0x0D57], p => get_i(p)),
        [8, 8, 8, 8, 24, 8], "the surface's bits");
    assert.equal((await call("gles2:glIsEnabled", GL.DITHER)).ret, 1, "GL_DITHER on at first");
    assert.equal((await call("gles2:glIsEnabled", GL.BLEND)).ret, 0);
    await call("gles2:glEnable", GL.BLEND);
    assert.deepEqual(await get_b(GL.BLEND), [1]);
    await call("gles2:glClearColor", 0.5, -1, 2, 0.25);
    assert.deepEqual(await get_f(0x0C22, 4), [0.5, 0, 1, 0.25], "clamped to [0, 1]");
    await call("gles2:glLineWidth", 2.5);
    assert.deepEqual(await get_i(0x0B21), [3], "a float as an integer: rounded");
    assert.equal(await error(), GL.NO_ERROR);
    await call("gles2:glGetIntegerv", 0x1234, 4);
    assert.equal(await error(), GL.INVALID_ENUM, "an unknown pname");
    console.log("PASS: the initial state, glGet's conversions, enables");
}

// ---- errors

{
    await call("gles2:glEnable", 0x0B10); // GL_POINT_SMOOTH: GLES 1.1's only
    await call("gles2:glBlendFunc", 0x0300, 0x0308); // SRC_ALPHA_SATURATE as the destination
    assert.equal(await error(), GL.INVALID_ENUM, "the first error");
    assert.equal(await error(), GL.NO_ERROR, "only the first: the second was dropped");
    await call("gles2:glLineWidth", 0);
    assert.equal(await error(), GL.INVALID_VALUE);
    assert.deepEqual(await get_f(0x0B21), [2.5], "a refused call changes nothing");
    await call("gles2:glViewport", 0, 0, -1, 5);
    await call("gles2:glPixelStorei", 0x0CF5, 3);
    await call("gles2:glStencilOpSeparate", 0x0404, 0x1E00, 0x1E00, 0x1234);
    assert.equal(await error(), GL.INVALID_VALUE);
    const commands = sent();
    for(const refused of ["glLineWidth", "glPixelStorei", "glStencilOpSeparate", "glViewport"]) assert.equal(commands.filter(n => n === refused).length, refused === "glLineWidth" ? 1 : 0, refused);
    assert.ok(!commands.some(n => /^gl(Get|Is)/.test(n)), "no query reaches the page");
    console.log("PASS: errors");
}

// ---- textures

{
    const names = i32s((await call("gles2:glGenTextures", 3, 12)).outs[0]);
    assert.equal(names.length, 3);
    assert.equal((await call("gles2:glIsTexture", names[0])).ret, 0, "generated, not yet an object");
    await call("gles2:glBindTexture", GL.TEXTURE_2D, names[0]);
    assert.equal((await call("gles2:glIsTexture", names[0])).ret, 1);
    // (glCopyTexSubImage2D: a level above log2 of the largest size is INVALID_VALUE, not "no image")
    await call("gles2:glCopyTexSubImage2D", GL.TEXTURE_2D, 13, 0, 0, 0, 0, 1, 1);
    assert.equal(await error(), GL.INVALID_VALUE);
    await call("gles2:glBindTexture", GL.TEXTURE_CUBE_MAP, names[0]);
    assert.equal(await error(), GL.INVALID_OPERATION, "a texture keeps its first target");
    const rgba = new Uint8Array(16 * 16 * 4);
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 16, 16, 0, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.NO_ERROR);
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGB, 16, 16, 0, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_OPERATION, "format and internal format differ");
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 16, 16, 0, GL.RGBA, GL.UNSIGNED_SHORT_5_6_5, rgba);
    assert.equal(await error(), GL.INVALID_OPERATION, "RGBA with 5_6_5");
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 16, 16, 1, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_VALUE, "a border");
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 13, GL.RGBA, 1, 1, 0, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_VALUE, "a level beyond log2 of the largest size");
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 16, 16, 0, 0x1234, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_ENUM, "no such format");
    await call("gles2:glTexSubImage2D", GL.TEXTURE_2D, 0, 8, 8, 9, 8, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_VALUE, "beyond the image");
    await call("gles2:glTexSubImage2D", GL.TEXTURE_2D, 1, 0, 0, 1, 1, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.INVALID_OPERATION, "a level with no image");
    await call("gles2:glGenerateMipmap", GL.TEXTURE_2D);
    await call("gles2:glTexSubImage2D", GL.TEXTURE_2D, 4, 0, 0, 1, 1, GL.RGBA, GL.UNSIGNED_BYTE, rgba);
    assert.equal(await error(), GL.NO_ERROR, "glGenerateMipmap made levels 1 to 4");
    // ETC1: the size by its blocks; no partial updates
    await call("gles2:glCompressedTexImage2D", GL.TEXTURE_2D, 0, 0x8D64, 6, 6, 0, 32, new Uint8Array(32));
    assert.equal(await error(), GL.NO_ERROR);
    await call("gles2:glCompressedTexImage2D", GL.TEXTURE_2D, 0, 0x8D64, 6, 6, 0, 24, new Uint8Array(24));
    assert.equal(await error(), GL.INVALID_VALUE);
    await call("gles2:glCompressedTexSubImage2D", GL.TEXTURE_2D, 0, 0, 0, 4, 4, 0x8D64, 8, new Uint8Array(8));
    assert.equal(await error(), GL.INVALID_OPERATION);
    // parameters
    const param = async (target, pname) => i32s((await call("gles2:glGetTexParameteriv", target, pname, 4)).outs[0])[0];
    assert.equal(await param(GL.TEXTURE_2D, 0x2801), 0x2702, "MIN_FILTER: NEAREST_MIPMAP_LINEAR");
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x2802, 0x812F);
    assert.equal(await param(GL.TEXTURE_2D, 0x2802), 0x812F);
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x2800, 0x2701);
    assert.equal(await error(), GL.INVALID_ENUM, "a mipmap filter for magnification");
    await call("gles2:glBindTexture", GL.TEXTURE_EXTERNAL_OES, names[1]);
    assert.equal(await param(GL.TEXTURE_EXTERNAL_OES, 0x2801), 0x2601, "an external texture: LINEAR");
    assert.equal(await param(GL.TEXTURE_EXTERNAL_OES, 0x2803), 0x812F, "CLAMP_TO_EDGE");
    await call("gles2:glTexParameteri", GL.TEXTURE_EXTERNAL_OES, 0x2802, 0x2901);
    assert.equal(await error(), GL.INVALID_ENUM, "external textures only clamp");
    // deleting unbinds
    await call("gles2:glActiveTexture", 0x84C3);
    await call("gles2:glBindTexture", GL.TEXTURE_2D, names[2]);
    assert.deepEqual(await get_i(0x8069), [names[2]]);
    await call("gles2:glDeleteTextures", 1, ints([names[2]]));
    assert.deepEqual(await get_i(0x8069), [0], "the binding went with it");
    await call("gles2:glActiveTexture", 0x84C0 + 32);
    assert.equal(await error(), GL.INVALID_ENUM, "unit 32 is beyond the 32 units");
    await call("gles2:glActiveTexture", 0x84C0);
    console.log("PASS: textures");
}

// ---- buffers

{
    const [buffer] = i32s((await call("gles2:glGenBuffers", 1, 4)).outs[0]);
    await call("gles2:glBindBuffer", GL.ARRAY_BUFFER, 0);
    await call("gles2:glBufferData", GL.ARRAY_BUFFER, 16, new Uint8Array(16), GL.STATIC_DRAW);
    assert.equal(await error(), GL.INVALID_OPERATION, "no buffer bound");
    await call("gles2:glBindBuffer", GL.ARRAY_BUFFER, buffer);
    await call("gles2:glBufferData", GL.ARRAY_BUFFER, 64, new Uint8Array(64), 0x88E8);
    const parameter = async pname => i32s((await call("gles2:glGetBufferParameteriv", GL.ARRAY_BUFFER, pname, 4)).outs[0])[0];
    assert.deepEqual([await parameter(0x8764), await parameter(0x8765)], [64, 0x88E8]);
    await call("gles2:glBufferSubData", GL.ARRAY_BUFFER, 60, 8, new Uint8Array(8));
    assert.equal(await error(), GL.INVALID_VALUE, "beyond the buffer");
    await call("gles2:glBufferData", GL.ARRAY_BUFFER, 4, null, 0x1234);
    assert.equal(await error(), GL.INVALID_ENUM, "no such usage");
    await call("gles2:glVertexAttribPointerOffset", 3, 2, GL.FLOAT, 0, 8, 16);
    const attrib = async pname => i32s((await call("gles2:glGetVertexAttribiv", 3, pname, 16)).outs[0]);
    assert.deepEqual([...await attrib(0x8623), ...await attrib(0x8624), ...await attrib(0x889F)].slice(0, 9).filter((v, i) => i % 4 === 0),
        [2, 8, buffer], "size, stride, the buffer");
    await call("gles2:glDeleteBuffers", 1, ints([buffer]));
    assert.deepEqual(await get_i(0x8894), [0]);
    assert.equal((await attrib(0x889F))[0], 0, "the attribute's binding went with it");
    await call("gles2:glVertexAttrib3f", 5, 1, 2, 3);
    assert.deepEqual(f32s((await call("gles2:glGetVertexAttribfv", 5, 0x8626, 16)).outs[0]), [1, 2, 3, 1], "the current value, w 1");
    await call("gles2:glVertexAttrib1f", 16, 1);
    assert.equal(await error(), GL.INVALID_VALUE, "attribute 16 of 16");
    console.log("PASS: buffers, vertex attributes");
}

// ---- renderbuffers and framebuffers

{
    const status = async () => (await call("gles2:glCheckFramebufferStatus", GL.FRAMEBUFFER)).ret;
    assert.equal(await status(), 0x8CD5, "the window: complete");
    const [fbo] = i32s((await call("gles2:glGenFramebuffers", 1, 4)).outs[0]);
    const [color, depth] = i32s((await call("gles2:glGenRenderbuffers", 2, 8)).outs[0]);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.RENDERBUFFER, color);
    assert.equal(await error(), GL.INVALID_OPERATION, "framebuffer 0 has no attachments");
    await call("gles2:glBindFramebuffer", GL.FRAMEBUFFER, fbo);
    assert.equal(await status(), 0x8CD7, "MISSING_ATTACHMENT");
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, color);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.RGB565, 64, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.RENDERBUFFER, color);
    assert.equal(await status(), 0x8CD5);
    assert.deepEqual(await each([0x0D52, 0x0D53, 0x0D54, 0x0D55, 0x0D56], p => get_i(p)), [5, 6, 5, 0, 0],
        "the bits of the framebuffer's images");
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, depth);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.DEPTH_COMPONENT16, 32, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, depth);
    assert.equal(await status(), 0x8CD9, "INCOMPLETE_DIMENSIONS");
    const draws = sent().filter(n => n === "glDrawArrays").length;
    await call("gles2:glDrawArrays", 4, 0, 3);
    assert.equal(await error(), GL.INVALID_FRAMEBUFFER_OPERATION);
    assert.equal(sent().filter(n => n === "glDrawArrays").length, draws, "the refused draw is not sent");
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.DEPTH_COMPONENT16, 64, 32);
    assert.equal(await status(), 0x8CD5);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.RENDERBUFFER, depth);
    assert.equal(await status(), 0x8CD6, "a depth image as the color attachment: INCOMPLETE_ATTACHMENT");
    // a texture attachment: a luminance one is not color-renderable
    const [texture] = i32s((await call("gles2:glGenTextures", 1, 4)).outs[0]);
    await call("gles2:glBindTexture", GL.TEXTURE_2D, texture);
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.LUMINANCE, 64, 32, 0, GL.LUMINANCE, GL.UNSIGNED_BYTE, null);
    await call("gles2:glFramebufferTexture2D", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture, 0);
    assert.equal(await status(), 0x8CD6);
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 64, 32, 0, GL.RGBA, GL.UNSIGNED_SHORT_4_4_4_4, null);
    assert.equal(await status(), 0x8CD5, "RGBA4444: color-renderable");
    const attachment = async pname => i32s((await call("gles2:glGetFramebufferAttachmentParameteriv", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, pname, 4)).outs[0])[0];
    assert.deepEqual([await attachment(0x8CD0), await attachment(0x8CD1), await attachment(0x8CD2)], [0x1702, texture, 0]);
    await call("gles2:glFramebufferTexture2D", GL.FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, texture, 1);
    assert.equal(await error(), GL.INVALID_VALUE, "GLES 2.0 attaches level 0 only");
    // depth and stencil: one packed renderbuffer, or unsupported
    const [stencil] = i32s((await call("gles2:glGenRenderbuffers", 1, 4)).outs[0]);
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, stencil);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.STENCIL_INDEX8, 64, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.STENCIL_ATTACHMENT, GL.RENDERBUFFER, stencil);
    assert.equal(await status(), 0x8CDD, "UNSUPPORTED: separate depth and stencil");
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.DEPTH24_STENCIL8_OES, 64, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, stencil);
    assert.equal(await status(), 0x8CD5, "the packed one for both");
    const rb = async pname => i32s((await call("gles2:glGetRenderbufferParameteriv", GL.RENDERBUFFER, pname, 4)).outs[0])[0];
    assert.deepEqual([await rb(0x8D42), await rb(0x8D43), await rb(0x8D44), await rb(0x8D54), await rb(0x8D55)], [64, 32, GL.DEPTH24_STENCIL8_OES, 24, 8]);
    // deleting an attached renderbuffer detaches it
    await call("gles2:glDeleteRenderbuffers", 1, ints([stencil]));
    assert.equal(await status(), 0x8CD5);
    assert.equal(i32s((await call("gles2:glGetFramebufferAttachmentParameteriv", GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, 0x8CD0, 4)).outs[0])[0], 0);
    await call("gles2:glDeleteFramebuffers", 1, ints([fbo]));
    assert.deepEqual(await get_i(0x8CA6), [0], "deleting the bound framebuffer binds the window");
    console.log("PASS: renderbuffers, framebuffers and their completeness");
}

// ---- shaders and programs

{
    const vs_source = "attribute vec4 position; attribute vec2 uv; uniform mat4 mvp; uniform vec4 tints[2]; varying vec2 v; " +
        "void main() { v = uv; gl_Position = mvp * position + tints[1]; }";
    const fs_source = "precision mediump float; uniform sampler2D tex; uniform bool flip; uniform ivec2 offset; varying vec2 v; " +
        "void main() { gl_FragColor = texture2D(tex, flip ? v.yx : v) + vec4(float(offset.x)); }";
    const shader = async (type, source) =>
    {
        const name = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", name);
        return name;
    };
    const shader_iv = async (name, pname) => i32s((await call("gles2:glGetShaderiv", name, pname, 4)).outs[0])[0];
    const program_iv = async (name, pname) => i32s((await call("gles2:glGetProgramiv", name, pname, 4)).outs[0])[0];
    const vs = await shader(GL.VERTEX_SHADER, vs_source), fs = await shader(GL.FRAGMENT_SHADER, fs_source);
    assert.deepEqual([await shader_iv(vs, 0x8B81), await shader_iv(fs, 0x8B81)], [1, 1], "both compile");
    assert.equal(await shader_iv(vs, 0x8B4F), GL.VERTEX_SHADER);
    assert.equal(await shader_iv(vs, 0x8B88), vs_source.length + 1, "GL_SHADER_SOURCE_LENGTH");
    const bad = await shader(GL.FRAGMENT_SHADER, "void main() { gl_FragColor = undeclared; }");
    assert.equal(await shader_iv(bad, 0x8B81), 0);
    const log_length = await shader_iv(bad, 0x8B84);
    const log = await call("gles2:glGetShaderInfoLog", bad, log_length, 4, log_length);
    assert.match(text(log.outs[1]), /ERROR: 0:1: .*undeclared/);
    assert.equal(i32s(log.outs[0])[0], log_length - 1);
    const program = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", program, vs);
    await call("gles2:glAttachShader", program, bad);
    assert.equal(await error(), GL.NO_ERROR);
    await call("gles2:glAttachShader", program, fs);
    assert.equal(await error(), GL.INVALID_OPERATION, "a second fragment shader");
    await call("gles2:glLinkProgram", program);
    assert.equal(await program_iv(program, 0x8B82), 0, "the bad fragment shader: no link");
    await call("gles2:glUseProgram", program);
    assert.equal(await error(), GL.INVALID_OPERATION, "a program that did not link is not used");
    await call("gles2:glDetachShader", program, bad);
    await call("gles2:glAttachShader", program, fs);
    await call("gles2:glBindAttribLocation", program, 5, cstring("uv"));
    await call("gles2:glBindAttribLocation", program, 1, cstring("gl_Vertex"));
    assert.equal(await error(), GL.INVALID_OPERATION, "gl_ names are reserved");
    await call("gles2:glLinkProgram", program);
    assert.equal(await program_iv(program, 0x8B82), 1);
    assert.deepEqual([await program_iv(program, 0x8B89), await program_iv(program, 0x8B86)], [2, 5], "2 attributes, 5 uniforms");
    assert.equal((await call("gles2:glGetAttribLocation", program, cstring("uv"))).ret, 5, "the bound location");
    assert.equal((await call("gles2:glGetAttribLocation", program, cstring("position"))).ret, 0);
    const active = [];
    for(let i = 0; i < 5; i++)
    {
        const r = await call("gles2:glGetActiveUniform", program, i, 64, 4, 4, 4, 64);
        active.push([text(r.outs[3]), i32s(r.outs[1])[0], i32s(r.outs[2])[0].toString(16)]);
    }
    assert.deepEqual(active.sort(), [["flip", 1, "8b56"], ["mvp", 1, "8b5c"], ["offset", 1, "8b53"], ["tex", 1, "8b5e"], ["tints[0]", 2, "8b52"]]);
    const location = async name => (await call("gles2:glGetUniformLocation", program, cstring(name))).ret;
    const [mvp, tints, tints1, flip, offset, tex] = [await location("mvp"), await location("tints"), await location("tints[1]"),
        await location("flip"), await location("offset"), await location("tex")];
    assert.equal(tints1, tints + 1);
    assert.equal(await location("nothing"), -1);
    await call("gles2:glUseProgram", program);
    await call("gles2:glUniform4f", tints, 1, 2, 3, 4);
    assert.equal(await error(), GL.NO_ERROR);
    await call("gles2:glUniform4fv", tints1, 2, floats([5, 6, 7, 8, 9, 9, 9, 9]));
    assert.deepEqual(f32s((await call("gles2:glGetUniformfv", program, tints1, 16)).outs[0]), [5, 6, 7, 8], "the rest of the array is cut off");
    await call("gles2:glUniform3f", tints, 1, 2, 3);
    assert.equal(await error(), GL.INVALID_OPERATION, "a vec3 function on a vec4");
    await call("gles2:glUniform1f", tex, 1);
    assert.equal(await error(), GL.INVALID_OPERATION, "a sampler takes glUniform1i only");
    await call("gles2:glUniform1i", tex, 3);
    await call("gles2:glUniform1f", flip, 2.5);
    await call("gles2:glUniform2i", offset, 7, -1);
    await call("gles2:glUniform2f", offset, 7, -1);
    assert.equal(await error(), GL.INVALID_OPERATION, "a float function on an ivec2");
    assert.deepEqual(i32s((await call("gles2:glGetUniformiv", program, flip, 4)).outs[0]), [1], "a bool: true");
    assert.deepEqual(i32s((await call("gles2:glGetUniformiv", program, offset, 8)).outs[0]), [7, -1]);
    await call("gles2:glUniformMatrix4fv", mvp, 1, 1, new Uint8Array(64));
    assert.equal(await error(), GL.INVALID_VALUE, "transpose must be GL_FALSE");
    await call("gles2:glUniform1f", -1, 1);
    assert.equal(await error(), GL.NO_ERROR, "location -1 is ignored");
    await call("gles2:glUniform1f", 99, 1);
    assert.equal(await error(), GL.INVALID_OPERATION, "no such location");
    // deleting a program in use: it stays until it is not
    await call("gles2:glDeleteProgram", program);
    assert.equal((await call("gles2:glIsProgram", program)).ret, 1);
    assert.equal(await program_iv(program, 0x8B80), 1, "GL_DELETE_STATUS");
    await call("gles2:glDeleteShader", vs);
    assert.equal((await call("gles2:glIsShader", vs)).ret, 1, "attached: deleted later");
    await call("gles2:glUseProgram", 0);
    assert.equal((await call("gles2:glIsProgram", program)).ret, 0);
    assert.equal((await call("gles2:glIsShader", vs)).ret, 0, "its program went: so did it");
    await call("gles2:glGetShaderiv", program, 0x8B81, 4);
    assert.equal(await error(), GL.INVALID_VALUE, "no such object");
    await call("gles2:glGetProgramiv", fs, 0x8B82, 4);
    assert.equal(await error(), GL.INVALID_OPERATION, "a shader is no program");
    // (the page got the names: glCreateShader's answer with the command)
    host.flush();
    const created = renderer.records().filter(r => r.name === "COMMAND" && r.command.name === "glCreateShader").map(r => r.ret);
    assert.ok(created.includes(vs) && created.includes(fs));
    console.log("PASS: shaders and programs, uniforms");
}

// ---- GLES 1.1

{
    const context1 = (await call("rcCreateContext", 3, 0, 1)).ret;
    await call("rcMakeCurrent", context1, surface, surface);
    assert.deepEqual(i32s((await call("gles1:glGetIntegerv", 0x0D31, 4)).outs[0]), [8], "GL_MAX_LIGHTS");
    assert.deepEqual(i32s((await call("gles1:glGetFixedv", 0x0B53, 16)).outs[0]), [13107, 13107, 13107, 65536], "GL_LIGHT_MODEL_AMBIENT as 16.16");
    await call("gles1:glEnable", 0x0B50);
    assert.equal((await call("gles1:glGetError")).ret, GL.NO_ERROR, "GL_LIGHTING is a GLES 1.1 capability");
    assert.equal((await call("gles1:glIsEnabled", 0x809D)).ret, 1, "GL_MULTISAMPLE on at first");
    const [texture] = i32s((await call("gles1:glGenTextures", 1, 4)).outs[0]);
    assert.equal(texture, 1, "its own share group");
    await call("gles1:glBindTexture", GL.TEXTURE_2D, texture);
    await call("gles1:glTexParameteri", GL.TEXTURE_2D, 0x8191, 1);
    assert.deepEqual(i32s((await call("gles1:glGetTexParameteriv", GL.TEXTURE_2D, 0x8191, 4)).outs[0]), [1], "GL_GENERATE_MIPMAP");
    await call("gles1:glActiveTexture", 0x84C4);
    assert.equal((await call("gles1:glGetError")).ret, GL.INVALID_ENUM, "4 texture units");
    await call("rcMakeCurrent", context, surface, surface);
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x8191, 1);
    assert.equal(await error(), GL.INVALID_ENUM, "GLES 2.0 has no GL_GENERATE_MIPMAP");
    void c;
    void send;
    console.log("PASS: GLES 1.1");
}

// ---- GLES 1.1's fixed-function state

{
    const context1 = (await call("rcCreateContext", 3, 0, 1)).ret;
    await call("rcMakeCurrent", context1, surface, surface);
    const e1 = async () => (await call("gles1:glGetError")).ret;
    const getf = async (pname, n) => f32s((await call("gles1:glGetFloatv", pname, 4 * n)).outs[0]);
    // matrices: the stacks' depths and their errors
    assert.deepEqual(await getf(0x0BA6, 16), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], "GL_MODELVIEW_MATRIX: the identity");
    await call("gles1:glTranslatef", 1, 2, 3);
    await call("gles1:glScalef", 2, 2, 2);
    assert.deepEqual(await getf(0x0BA6, 16), [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 1, 2, 3, 1], "translate, then scale");
    await call("gles1:glMatrixMode", 0x1701);
    await call("gles1:glPushMatrix");
    await call("gles1:glPushMatrix");
    assert.equal(await e1(), 0x0503, "GL_STACK_OVERFLOW: the projection stack holds 2");
    await call("gles1:glPopMatrix");
    await call("gles1:glPopMatrix");
    assert.equal(await e1(), 0x0504, "GL_STACK_UNDERFLOW");
    await call("gles1:glOrthof", 0, 1, 0, 1, 1, 1);
    assert.equal(await e1(), 0x0501, "an orthographic projection with near = far");
    await call("gles1:glFrustumx", -65536, 65536, -65536, 65536, 65536, 10 * 65536);
    const frustum = await getf(0x0BA7, 16);
    assert.ok(Math.abs(frustum[0] - 1) < 1e-6 && frustum[11] === -1, "glFrustumx: 16.16 arguments");
    await call("gles1:glMatrixMode", 0x1234);
    assert.equal(await e1(), 0x0500);
    await call("gles1:glMatrixMode", 0x1700);
    // a light's position in eye coordinates: the modelview when it was set
    await call("gles1:glLoadIdentity");
    await call("gles1:glTranslatef", 0, 0, -5);
    await call("gles1:glLightfv", 0x4001, 0x1203, floats([1, 0, 0, 1]));
    assert.deepEqual(f32s((await call("gles1:glGetLightfv", 0x4001, 0x1203, 16)).outs[0]), [1, 0, -5, 1]);
    await call("gles1:glLightf", 0x4001, 0x1206, 120);
    assert.equal(await e1(), 0x0501, "a spot cutoff of 120 degrees");
    assert.deepEqual(f32s((await call("gles1:glGetLightfv", 0x4000, 0x1201, 16)).outs[0]), [1, 1, 1, 1], "light 0's diffuse: white");
    assert.deepEqual(f32s((await call("gles1:glGetLightfv", 0x4001, 0x1201, 16)).outs[0]), [0, 0, 0, 1], "the others': black");
    // the material: front and back together
    await call("gles1:glMaterialfv", 0x0404, 0x1201, floats([1, 0, 0, 1]));
    assert.equal(await e1(), 0x0500, "GLES 1.1 sets both faces only");
    await call("gles1:glMaterialx", 0x0408, 0x1601, 64 * 65536);
    assert.deepEqual(f32s((await call("gles1:glGetMaterialfv", 0x0405, 0x1601, 4)).outs[0]), [64], "GL_SHININESS by its 16.16");
    // texture environments: per unit, enums as themselves in the fixed form
    await call("gles1:glActiveTexture", 0x84C1);
    await call("gles1:glTexEnvx", 0x2300, 0x2200, 0x8570);
    assert.deepEqual(i32s((await call("gles1:glGetTexEnviv", 0x2300, 0x2200, 4)).outs[0]), [0x8570], "unit 1: GL_COMBINE");
    await call("gles1:glActiveTexture", 0x84C0);
    assert.deepEqual(i32s((await call("gles1:glGetTexEnviv", 0x2300, 0x2200, 4)).outs[0]), [0x2100], "unit 0: GL_MODULATE still");
    await call("gles1:glTexEnvi", 0x2300, 0x8573, 3);
    assert.equal(await e1(), 0x0501, "GL_RGB_SCALE: 1, 2 or 4");
    // fog, the alpha test, the shade model
    await call("gles1:glFogx", 0x0B65, 0x2601);
    await call("gles1:glFogf", 0x0B62, -1);
    assert.equal(await e1(), 0x0501, "a negative fog density");
    assert.deepEqual(i32s((await call("gles1:glGetIntegerv", 0x0B65, 4)).outs[0]), [0x2601], "GL_FOG_MODE: GL_LINEAR");
    await call("gles1:glAlphaFunc", 0x0204, 2);
    assert.deepEqual(await getf(0x0BC2, 1), [1], "the alpha reference clamped to 1");
    await call("gles1:glShadeModel", 0x1D00);
    assert.deepEqual(i32s((await call("gles1:glGetIntegerv", 0x0B54, 4)).outs[0]), [0x1D00]);
    // a clip plane in eye coordinates: the inverse modelview's
    await call("gles1:glClipPlanef", 0x3000, floats([0, 0, 1, 0]));
    assert.deepEqual(f32s((await call("gles1:glGetClipPlanef", 0x3000, 16)).outs[0]), [0, 0, 1, 5], "z = 0 in object space is z = -5 in eye space");
    // client arrays: glEnableClientState's, not glEnable's; their pointers
    await call("gles1:glEnable", 0x8074);
    assert.equal(await e1(), 0x0500, "GL_VERTEX_ARRAY is not glEnable's");
    await call("gles1:glEnableClientState", 0x8074);
    assert.equal((await call("gles1:glIsEnabled", 0x8074)).ret, 1);
    await call("gles1:glVertexPointerData", 1, 0x1406, 0, floats([0, 0]), 8);
    assert.equal(await e1(), 0x0501, "a vertex array of size 1");
    await call("gles1:glColorPointerData", 3, 0x1401, 0, new Uint8Array(3), 3);
    assert.equal(await e1(), 0x0501, "a color array of size 3");
    await call("gles1:glClientActiveTexture", 0x84C1);
    await call("gles1:glTexCoordPointerOffset", 2, 0x140C, 8, 0);
    assert.deepEqual(i32s((await call("gles1:glGetIntegerv", 0x8088, 4)).outs[0]), [2], "unit 1's texture coordinates: size 2");
    assert.deepEqual(i32s((await call("gles1:glGetIntegerv", 0x84E1, 4)).outs[0]), [0x84C1], "GL_CLIENT_ACTIVE_TEXTURE");
    // the texture enable is per unit
    await call("gles1:glEnable", 0x0DE1);
    await call("gles1:glActiveTexture", 0x84C1);
    assert.equal((await call("gles1:glIsEnabled", 0x0DE1)).ret, 0, "GL_TEXTURE_2D off on unit 1");
    await call("gles1:glActiveTexture", 0x84C0);
    assert.equal((await call("gles1:glIsEnabled", 0x0DE1)).ret, 1, "on on unit 0");
    // the current values; draw_texture's checks
    await call("gles1:glColor4ub", 255, 0, 51, 255);
    assert.deepEqual(await getf(0x0B00, 4), [1, 0, 0.2, 1].map(Math.fround));
    await call("gles1:glDrawTexiOES", 0, 0, 0, 0, 4);
    assert.equal(await e1(), 0x0501, "a draw_texture rectangle of width 0");
    assert.equal(await e1(), 0);
    console.log("PASS: GLES 1.1's fixed-function state");
}
                                                                                                                                                                                                                           source/v64/tests/gles/shadow3.mjs                                                                   0000644 0000000 0000000 00000122663 00000000000 014055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The GLES host's GLES 3.x (docs/gles3-plan.md L2): the versions announced
// and the contexts made, GLSL ES 3.x's shaders compiled and linked by
// glslang on the CPU side, their link handed to the page in the batch
// (PROGRAM_LINK), and GLES 3.0's state, queries and errors, against the
// GLES 3.0 specification.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { GLESHost } from "../../src/gles/gles_host.js";
import { GLESShadow } from "../../src/gles/gles_shadow.js";
import { compile_glslang, create_glslang } from "../../src/gles/glslang.js";
import { link_glslang_program, unpack_program } from "../../src/gles/glsl_program.js";
import { block_layout, parse_spirv } from "../../src/gles/spirv_patch.js";
import { client, cstring, fake_renderer, i32s, text } from "./lib.mjs";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const glslang = await create_glslang(await compile_glslang(fs.readFileSync(root + "bios/glslang.wasm")));
const DISPLAY = { width: 480, height: 800, dpi: 240 };
const GL_VERSION = 0x1F02, GL_EXTENSIONS = 0x1F03, GL_SHADING_LANGUAGE_VERSION = 0x8B8C;

/** A host announcing `max_version`, a connection, a context of `api` current on a surface */
async function setup(max_version, api)
{
    const renderer = fake_renderer();
    const host = new GLESHost(DISPLAY, renderer, undefined, { glslang, max_version });
    const { call } = await client(host).connect();
    const context = (await call("rcCreateContext", 3, 0, api)).ret;
    let c = null;
    if(context)
    {
        const surface = (await call("rcCreateWindowSurface", 3, 320, 240)).ret;
        await call("rcMakeCurrent", context, surface, surface);
        c = host.shadow.context(context);
    }
    const gl_string = async name => text((await call("rcGetGLString", name, 2048, 2048)).outs[0]);
    return { host, renderer, call, context, c, gl_string };
}

// ---- versions: what is announced, what contexts are made
{
    const two = await setup("2.0", 3);
    assert.equal(two.context, 0, "no GLES 3 context where 2.0 is the highest announced");
    assert.ok(!(await two.gl_string(GL_EXTENSIONS)).includes("ANDROID_EMU"), "2.0: no host feature string");

    for(const [max, number] of [["3.0", 30], ["3.1", 31], ["3.2", 32]])
    {
        const s = await setup(max, 3);
        assert.ok(s.context, max + ": a GLES 3 context");
        assert.equal(s.c.api, 3);
        assert.equal(s.c.version, number, max + ": the context is the highest version announced");
        assert.equal(await s.gl_string(GL_VERSION), "OpenGL ES " + max + " v86");
        assert.equal(await s.gl_string(GL_SHADING_LANGUAGE_VERSION), "OpenGL ES GLSL ES " + (number / 10).toFixed(2));
        assert.ok((await s.gl_string(GL_EXTENSIONS)).includes("ANDROID_EMU_gles_max_version_" + max.replace(".", "_")),
            max + ": the host feature string the guest's libraries look for");
        // (GLES 2.0's extensions that 3.0 has in core: the guest's EGL makes GLES 2.0 contexts 3.x ones)
        const extensions = (await s.gl_string(GL_EXTENSIONS)).split(" ");
        for(const e of ["GL_OES_texture_npot", "GL_OES_element_index_uint", "GL_OES_standard_derivatives", "GL_OES_depth24"]) assert.ok(extensions.includes(e), max + ": " + e);
    }
    const four = await setup("3.2", 4);
    assert.equal(four.c.version, 32, "the guest asks 4 for 3.1 and 3.2");
    const es2 = await setup("3.2", 2);
    assert.equal(es2.c.api, 2, "a GLES 2.0 context stays one where 3.2 is announced");
    assert.equal(await es2.gl_string(GL_VERSION), "OpenGL ES 2.0 v86");
    console.log("PASS: versions announced, contexts made");
}

// ---- GLSL ES 3.x: glslang compiles and links on the CPU side; the page gets the link
{
    const { host, renderer, call } = await setup("3.0", 3);
    const VERTEX = 0x8B31, FRAGMENT = 0x8B30;
    const shader = async (type, source) =>
    {
        const name = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", name);
        return name;
    };
    const shader_iv = async (name, pname) => i32s((await call("gles2:glGetShaderiv", name, pname, 4)).outs[0])[0];
    const program_iv = async (name, pname) => i32s((await call("gles2:glGetProgramiv", name, pname, 4)).outs[0])[0];
    const vs = await shader(VERTEX, "#version 300 es\nlayout(location = 2) in vec4 pos;\nin vec2 uv;\nuniform mat4 mvp;\nuniform float k[3];\n" +
        "out vec2 tc;\nvoid main() { tc = uv * k[2]; gl_Position = mvp * pos; }");
    const fs_ = await shader(FRAGMENT, "#version 300 es\nprecision mediump float;\nuniform sampler2D tex;\nin vec2 tc;\n" +
        "layout(location = 0) out vec4 color;\nvoid main() { color = texture(tex, tc); }");
    assert.equal(await shader_iv(vs, 0x8B81), 1, "a 300 es vertex shader compiles (GL_COMPILE_STATUS)");
    assert.equal(await shader_iv(fs_, 0x8B81), 1);
    const bad = await shader(FRAGMENT, "#version 300 es\nprecision mediump float;\nout vec4 c;\nvoid main() { c = vec4(1) + uint(1); }");
    assert.equal(await shader_iv(bad, 0x8B81), 0, "glslang's errors are the shader's");
    assert.ok(await shader_iv(bad, 0x8B84) > 1, "with an info log (GL_INFO_LOG_LENGTH)");

    const program = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", program, vs);
    await call("gles2:glAttachShader", program, fs_);
    await call("gles2:glBindAttribLocation", program, 5, cstring("uv"));
    await call("gles2:glLinkProgram", program);
    assert.equal(await program_iv(program, 0x8B82), 1, "linked (GL_LINK_STATUS)");
    assert.equal(await program_iv(program, 0x8B86), 3, "three active uniforms (GL_ACTIVE_UNIFORMS)");
    assert.equal(await program_iv(program, 0x8B89), 2, "two active attributes");
    assert.equal((await call("gles2:glGetAttribLocation", program, cstring("pos"))).ret, 2, "layout(location) wins");
    assert.equal((await call("gles2:glGetAttribLocation", program, cstring("uv"))).ret, 5, "glBindAttribLocation's");
    const location = async name => (await call("gles2:glGetUniformLocation", program, cstring(name))).ret;
    const mvp = await location("mvp"), k = await location("k"), k2 = await location("k[2]"), tex = await location("tex");
    assert.ok(mvp >= 0 && k >= 0 && tex >= 0 && k2 === k + 2, "uniform locations; an array's elements one after another");

    // the batch: the link's result before the glLinkProgram, which the page links with
    host.flush();
    const records = renderer.records();
    const at = records.findIndex(r => r.name === "PROGRAM_LINK");
    assert.ok(at >= 0 && records[at + 1].name === "COMMAND" && records[at + 1].command.name === "glLinkProgram",
        "PROGRAM_LINK goes just before its glLinkProgram");
    const info = unpack_program(records[at].bytes);
    assert.equal(info.ok, true);
    assert.deepEqual([info.locations.get("mvp"), info.locations.get("k[2]"), info.locations.get("tex")], [mvp, k2, tex],
        "the page's view of the program is the CPU side's");
    assert.deepEqual(info.spirv.map(m => m.stage), ["vertex", "fragment"], "with each stage's SPIR-V");
    assert.equal(info.spirv[0].words[0], 0x07230203, "SPIR-V's magic");
    const block = info.uniforms.find(u => u.name === "k[0]");
    assert.equal(block.array_stride, 16, "the default block is std140: a float array's stride is 16");

    // the page's shadow (no glslang) links with what came: the same view
    const page = new GLESShadow(null);
    page.create_context(1, 30, 0);
    const c = page.context(1);
    const object = { kind: "program", shaders: new Set(), bindings: new Map(), provided: info };
    assert.equal(page.link(object, [{ compiled: { glslang: true, ok: true }, type: VERTEX }]), info, "the provided link is the page's");
    assert.equal(object.provided, null, "and used once");
    assert.equal(page.link({ kind: "program", bindings: new Map() }, [{ compiled: { glslang: true, ok: true } }]).ok, false,
        "none provided: the page cannot link it");
    void c;
    console.log("PASS: GLSL ES 3.00 through glslang; the link in the batch");
}

// ---- GLES 3.0's state, queries and errors (GLES 3.0's tables 6.x and the commands' errors)
{
    const { call, c } = await setup("3.0", 3);
    const error = async () => (await call("gles2:glGetError")).ret;
    const get_i = async (pname, n = 1) => i32s((await call("gles2:glGetIntegerv", pname, 4 * n)).outs[0]);
    const gen = async (command, n = 1) => i32s((await call("gles2:" + command, n, 4 * n)).outs[0]);
    const ints = values => new Uint8Array(new Int32Array(values).buffer);
    const GL = { TEXTURE_2D: 0x0DE1, TEXTURE_3D: 0x806F, TEXTURE_2D_ARRAY: 0x8C1A, RGBA: 0x1908, RGBA8: 0x8058, UNSIGNED_BYTE: 0x1401,
        R32F: 0x822E, RED: 0x1903, FLOAT: 0x1406, RGBA32UI: 0x8D70, RGBA_INTEGER: 0x8D99, UNSIGNED_INT: 0x1405, FRAMEBUFFER: 0x8D40,
        DRAW_FRAMEBUFFER: 0x8CA9, READ_FRAMEBUFFER: 0x8CA8, RENDERBUFFER: 0x8D41, COLOR_ATTACHMENT0: 0x8CE0, DEPTH_ATTACHMENT: 0x8D00,
        STENCIL_ATTACHMENT: 0x8D20, DEPTH_STENCIL_ATTACHMENT: 0x821A, DEPTH24_STENCIL8: 0x88F0, DEPTH_COMPONENT16: 0x81A5,
        STENCIL_INDEX8: 0x8D48, ARRAY_BUFFER: 0x8892, ELEMENT_ARRAY_BUFFER: 0x8893, UNIFORM_BUFFER: 0x8A11, COPY_READ: 0x8F36,
        COPY_WRITE: 0x8F37, STATIC_DRAW: 0x88E4, DYNAMIC_READ: 0x88E9 };

    assert.deepEqual(await get_i(0x821B), [3], "GL_MAJOR_VERSION");
    assert.deepEqual(await get_i(0x821C), [0], "GL_MINOR_VERSION");
    assert.deepEqual(await get_i(0x8D57), [4], "GL_MAX_SAMPLES");
    assert.deepEqual(await get_i(0x8CDF), [4], "GL_MAX_COLOR_ATTACHMENTS");
    assert.deepEqual(await get_i(0x8D6B), [0x7FFFFFFF], "GL_MAX_ELEMENT_INDEX through glGetIntegerv: clamped");
    const i64 = Array.from(new BigInt64Array((await call("gles2:glGetInteger64v", 0x8D6B, 8)).outs[0].slice().buffer));
    assert.deepEqual(i64, [0xFFFFFFFFn], "and its 64 bits through glGetInteger64v");
    assert.deepEqual(await get_i(0x8825), [0x0405], "GL_DRAW_BUFFER0 of the default framebuffer: GL_BACK");
    assert.equal(await error(), 0);

    // vertex array objects keep the attributes and the element buffer
    const [b1, b2] = await gen("glGenBuffers", 2);
    const [vao] = await gen("glGenVertexArrays");
    await call("gles2:glBindBuffer", GL.ELEMENT_ARRAY_BUFFER, b1);
    await call("gles2:glBindVertexArray", vao);
    assert.deepEqual(await get_i(0x8895), [0], "a new vertex array has no element buffer");
    await call("gles2:glBindBuffer", GL.ELEMENT_ARRAY_BUFFER, b2);
    await call("gles2:glEnableVertexAttribArray", 3);
    await call("gles2:glBindVertexArray", 0);
    assert.deepEqual(await get_i(0x8895), [b1], "the default one's came back");
    await call("gles2:glBindVertexArray", vao);
    assert.deepEqual(await get_i(0x8895), [b2], "and the vertex array's");
    assert.deepEqual(i32s((await call("gles2:glGetVertexAttribiv", 3, 0x8622, 4)).outs[0]), [1], "its enabled attribute");
    await call("gles2:glBindVertexArray", 0);
    assert.deepEqual(i32s((await call("gles2:glGetVertexAttribiv", 3, 0x8622, 4)).outs[0]), [0], "not the default one's");
    await call("gles2:glBindVertexArray", 12345);
    assert.equal(await error(), 0x0502, "binding a name glGenVertexArrays did not give: INVALID_OPERATION");
    // current values: the context's, whichever form set them last (a float form after an integer one: dEQP-GLES3
    // state_query.shader.current_vertex_attrib_float_to_int after _int and _uint), the same under another vertex array
    await call("gles2:glVertexAttribI4i", 5, -3, 4, 5, 6);
    await call("gles2:glVertexAttrib4f", 5, 2.5, -7.25, 63999.5, 1);
    assert.deepEqual(i32s((await call("gles2:glGetVertexAttribiv", 5, 0x8626, 16)).outs[0]), [3, -7, 64000, 1],
        "GL_CURRENT_VERTEX_ATTRIB of a float form after an integer one, rounded");
    await call("gles2:glBindVertexArray", vao);
    assert.deepEqual(Array.from(new Float32Array((await call("gles2:glGetVertexAttribfv", 5, 0x8626, 16)).outs[0].slice().buffer)),
        [2.5, -7.25, 63999.5, 1], "and under another vertex array");
    await call("gles2:glVertexAttrib2fv", 5, new Uint8Array(new Float32Array([-1.5, 8]).buffer));
    assert.deepEqual(i32s((await call("gles2:glGetVertexAttribiv", 5, 0x8626, 16)).outs[0]), [-1, 8, 0, 1], "glVertexAttrib2fv's, z 0 and w 1");
    await call("gles2:glBindVertexArray", 0);

    // buffers: targets, copies, mapping answers from the CPU side's bytes
    c.group; // (the share group holds buffers)
    await call("gles2:glBindBuffer", GL.COPY_READ, b1);
    await call("gles2:glBufferData", GL.COPY_READ, 8, ints([7, 9]), GL.STATIC_DRAW);
    await call("gles2:glBindBuffer", GL.COPY_WRITE, b2);
    await call("gles2:glBufferData", GL.COPY_WRITE, 8, null, GL.DYNAMIC_READ);
    assert.equal(await error(), 0);
    await call("gles2:glCopyBufferSubData", GL.COPY_READ, GL.COPY_WRITE, 0, 4, 4);
    const mapped = (await call("gles2:glMapBufferRangeAEMU", GL.COPY_WRITE, 0, 8, 1, 8)).outs[0];
    assert.deepEqual(i32s(mapped), [0, 7], "glMapBufferRange(READ) answers the copy's bytes");
    await call("gles2:glMapBufferRangeAEMU", GL.COPY_WRITE, 0, 8, 1, 8);
    assert.equal(await error(), 0x0502, "mapping a mapped buffer: INVALID_OPERATION");
    await call("gles2:glUnmapBufferAEMU", GL.COPY_WRITE, 0, 8, 1, ints([0, 0]), 1);
    await call("gles2:glMapBufferRangeAEMU", GL.COPY_WRITE, 0, 8, 2 | 4, 8);
    await call("gles2:glUnmapBufferAEMU", GL.COPY_WRITE, 0, 8, 2 | 4, ints([5, 6]), 1);
    assert.deepEqual(i32s((await call("gles2:glMapBufferRangeAEMU", GL.COPY_WRITE, 0, 8, 1, 8)).outs[0]), [5, 6], "what a write mapping wrote");
    await call("gles2:glUnmapBufferAEMU", GL.COPY_WRITE, 0, 8, 1, ints([0, 0]), 1);
    await call("gles2:glMapBufferRangeAEMU", GL.COPY_WRITE, 0, 8, 1 | 4, 8);
    assert.equal(await error(), 0x0502, "READ with INVALIDATE: INVALID_OPERATION");

    // indexed uniform buffer bindings
    await call("gles2:glBindBufferRange", GL.UNIFORM_BUFFER, 2, b1, 256, 4);
    assert.deepEqual(i32s((await call("gles2:glGetIntegeri_v", 0x8A28, 2, 4)).outs[0]), [b1], "GL_UNIFORM_BUFFER_BINDING[2]");
    assert.deepEqual(i32s((await call("gles2:glGetIntegeri_v", 0x8A29, 2, 4)).outs[0]), [256], "its start");
    await call("gles2:glBindBufferRange", GL.UNIFORM_BUFFER, 2, b1, 4, 4);
    assert.equal(await error(), 0x0501, "an offset not GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT's multiple: INVALID_VALUE");

    // textures: 3D, arrays, storage, sized formats, parameters
    const [t3, ta, t2] = await gen("glGenTextures", 3);
    await call("gles2:glBindTexture", GL.TEXTURE_3D, t3);
    await call("gles2:glTexImage3D", GL.TEXTURE_3D, 0, GL.RGBA8, 4, 4, 4, 0, GL.RGBA, GL.UNSIGNED_BYTE, new Uint8Array(256));
    assert.equal(await error(), 0, "a 3D texture's image");
    await call("gles2:glTexImage3D", GL.TEXTURE_3D, 0, GL.RGBA8, 4, 4, 4, 0, GL.RGBA, GL.FLOAT, null);
    assert.equal(await error(), 0x0502, "RGBA8 of floats: INVALID_OPERATION");
    await call("gles2:glBindTexture", GL.TEXTURE_2D_ARRAY, ta);
    await call("gles2:glTexStorage3D", GL.TEXTURE_2D_ARRAY, 3, GL.R32F, 8, 8, 2);
    assert.equal(await error(), 0);
    const tex_i = async (target, pname) => i32s((await call("gles2:glGetTexParameteriv", target, pname, 4)).outs[0])[0];
    assert.equal(await tex_i(GL.TEXTURE_2D_ARRAY, 0x912F), 1, "GL_TEXTURE_IMMUTABLE_FORMAT");
    assert.equal(await tex_i(GL.TEXTURE_2D_ARRAY, 0x82DF), 3, "GL_TEXTURE_IMMUTABLE_LEVELS");
    await call("gles2:glTexImage3D", GL.TEXTURE_2D_ARRAY, 0, GL.R32F, 8, 8, 2, 0, GL.RED, GL.FLOAT, null);
    assert.equal(await error(), 0x0502, "an immutable texture's image: INVALID_OPERATION");
    await call("gles2:glTexStorage3D", GL.TEXTURE_2D_ARRAY, 5, GL.R32F, 8, 8, 2);
    assert.equal(await error(), 0x0502, "more levels than log2(8) + 1: INVALID_OPERATION");
    await call("gles2:glBindTexture", GL.TEXTURE_2D, t2);
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x8E42, 0x1906);
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x813C, 2);
    assert.equal(await tex_i(GL.TEXTURE_2D, 0x8E42), 0x1906, "GL_TEXTURE_SWIZZLE_R");
    assert.equal(await tex_i(GL.TEXTURE_2D, 0x813C), 2, "GL_TEXTURE_BASE_LEVEL");
    await call("gles2:glTexParameteri", GL.TEXTURE_2D, 0x813C, -1);
    assert.equal(await error(), 0x0501, "a negative base level: INVALID_VALUE");

    // samplers
    const [s1] = i32s((await call("gles2:glGenSamplers", 1, 4)).outs[0]);
    await call("gles2:glBindSampler", 3, s1);
    await call("gles2:glSamplerParameteri", s1, 0x2802, 0x812F);
    assert.deepEqual(i32s((await call("gles2:glGetSamplerParameteriv", s1, 0x2802, 4)).outs[0]), [0x812F], "a sampler's wrap");
    await call("gles2:glActiveTexture", 0x84C3);
    assert.deepEqual(await get_i(0x8919), [s1], "GL_SAMPLER_BINDING of unit 3");
    await call("gles2:glSamplerParameteri", s1, 0x813C, 1);
    assert.equal(await error(), 0x0500, "a texture's own parameter on a sampler: INVALID_ENUM");

    // framebuffers: draw and read, GLES 3.0's completeness
    const [fbo] = await gen("glGenFramebuffers");
    const [rb_color, rb_depth] = await gen("glGenRenderbuffers", 2);
    await call("gles2:glBindFramebuffer", GL.DRAW_FRAMEBUFFER, fbo);
    assert.deepEqual(await get_i(0x8CA6), [fbo], "GL_DRAW_FRAMEBUFFER_BINDING");
    assert.deepEqual(await get_i(0x8CAA), [0], "GL_READ_FRAMEBUFFER_BINDING stays");
    const status = async target => (await call("gles2:glCheckFramebufferStatus", target)).ret;
    assert.equal(await status(GL.DRAW_FRAMEBUFFER), 0x8CD7, "no attachment: INCOMPLETE_MISSING_ATTACHMENT");
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, rb_color);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.RGBA8, 16, 16);
    await call("gles2:glFramebufferRenderbuffer", GL.DRAW_FRAMEBUFFER, GL.COLOR_ATTACHMENT0 + 1, GL.RENDERBUFFER, rb_color);
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, rb_depth);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.DEPTH24_STENCIL8, 32, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.DRAW_FRAMEBUFFER, GL.DEPTH_STENCIL_ATTACHMENT, GL.RENDERBUFFER, rb_depth);
    assert.equal(await status(GL.DRAW_FRAMEBUFFER), 0x8CD5, "complete: sizes may differ in GLES 3.0");
    const attachment_i = async (attachment, pname) =>
        i32s((await call("gles2:glGetFramebufferAttachmentParameteriv", GL.DRAW_FRAMEBUFFER, attachment, pname, 4)).outs[0])[0];
    assert.equal(await attachment_i(GL.STENCIL_ATTACHMENT, 0x8CD1), rb_depth, "DEPTH_STENCIL_ATTACHMENT attached both");
    assert.equal(await attachment_i(GL.COLOR_ATTACHMENT0 + 1, 0x8215), 8, "GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE");
    assert.equal(await attachment_i(GL.COLOR_ATTACHMENT0 + 1, 0x8211), 0x8C17, "GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE");
    await call("gles2:glDrawBuffers", 2, ints([0, GL.COLOR_ATTACHMENT0 + 1]));
    assert.deepEqual([...await get_i(0x8825), ...await get_i(0x8826)], [0, GL.COLOR_ATTACHMENT0 + 1], "GL_DRAW_BUFFER0 and 1");
    await call("gles2:glDrawBuffers", 1, ints([GL.COLOR_ATTACHMENT0 + 1]));
    assert.equal(await error(), 0x0502, "COLOR_ATTACHMENT1 as draw buffer 0: INVALID_OPERATION");
    const [rb_stencil] = await gen("glGenRenderbuffers");
    await call("gles2:glBindRenderbuffer", GL.RENDERBUFFER, rb_stencil);
    await call("gles2:glRenderbufferStorage", GL.RENDERBUFFER, GL.STENCIL_INDEX8, 32, 32);
    await call("gles2:glFramebufferRenderbuffer", GL.DRAW_FRAMEBUFFER, GL.STENCIL_ATTACHMENT, GL.RENDERBUFFER, rb_stencil);
    assert.equal(await status(GL.DRAW_FRAMEBUFFER), 0x8CDD, "depth and stencil as two images: UNSUPPORTED");
    await call("gles2:glRenderbufferStorageMultisample", GL.RENDERBUFFER, 4, GL.RGBA32UI, 8, 8);
    assert.equal(await error(), 0x0502, "an integer format multisampled: INVALID_OPERATION");
    await call("gles2:glRenderbufferStorageMultisample", GL.RENDERBUFFER, 4, GL.RGBA8, 8, 8);
    assert.deepEqual(i32s((await call("gles2:glGetRenderbufferParameteriv", GL.RENDERBUFFER, 0x8CAB, 4)).outs[0]), [4], "GL_RENDERBUFFER_SAMPLES");
    await call("gles2:glBindFramebuffer", GL.FRAMEBUFFER, 0);
    await call("gles2:glBlitFramebuffer", 0, 0, 1, 1, 0, 0, 1, 1, 0x0100, 0x2601);
    assert.equal(await error(), 0x0502, "a linear blit of depth: INVALID_OPERATION");
    await call("gles2:glClearBufferfv", 0x1800, 4, ints([0, 0, 0, 0]));
    assert.equal(await error(), 0x0501, "clearing draw buffer 4 of 4: INVALID_VALUE");

    // queries and syncs
    const [q] = await gen("glGenQueries");
    await call("gles2:glBeginQuery", 0x8C2F, q);
    await call("gles2:glBeginQuery", 0x8D6A, q);
    assert.equal(await error(), 0x0502, "two occlusion queries at once: INVALID_OPERATION");
    assert.deepEqual(i32s((await call("gles2:glGetQueryiv", 0x8C2F, 0x8865, 4)).outs[0]), [q], "GL_CURRENT_QUERY");
    await call("gles2:glDrawArrays", 4, 0, 3);
    await call("gles2:glEndQuery", 0x8C2F);
    assert.deepEqual(i32s((await call("gles2:glGetQueryObjectuiv", q, 0x8867, 4)).outs[0]), [1], "GL_QUERY_RESULT_AVAILABLE");
    const sync = (await call("gles2:glFenceSyncAEMU", 0x9117, 0)).ret;
    assert.ok(sync > 0, "a fence");
    assert.equal((await call("gles2:glClientWaitSyncAEMU", sync, 0, 0)).ret, 0x911A, "GL_ALREADY_SIGNALED");
    assert.equal((await call("gles2:glIsSyncAEMU", sync)).ret, 1);
    await call("gles2:glDeleteSyncAEMU", sync);
    assert.equal((await call("gles2:glIsSyncAEMU", sync)).ret, 0);
    assert.equal(await error(), 0);
    // (an unused name bound makes a buffer, texture, framebuffer or renderbuffer, as in GLES 2.0: the guest's
    // EGL makes GLES 2.0's contexts the host's highest version, and dEQP-GLES2 binds names it never generated;
    // a vertex array's must be generated)
    await call("gles2:glBindBuffer", 0x8892, 900);
    await call("gles2:glBindBufferBase", 0x8A11, 0, 901);
    await call("gles2:glBindTexture", 0x0DE1, 902);
    await call("gles2:glBindFramebuffer", 0x8D40, 903);
    await call("gles2:glBindRenderbuffer", 0x8D41, 904);
    await call("gles2:glRenderbufferStorage", 0x8D41, 0x8058, 4, 4);
    await call("gles2:glFramebufferRenderbuffer", 0x8D40, 0x8CE0, 0x8D41, 904);
    assert.equal(await error(), 0, "unused names bound");
    assert.deepEqual(i32s((await call("gles2:glGetFramebufferAttachmentParameteriv", 0x8D40, 0x8CE0, 0x8CD1, 4)).outs[0]), [904]);
    assert.equal((await call("gles2:glIsFramebuffer", 903)).ret, 1);
    await call("gles2:glBindFramebuffer", 0x8D40, 0);
    await call("gles2:glBindVertexArray", 905);
    assert.equal(await error(), 0x0502, "an unused vertex array name: INVALID_OPERATION");
    // (errors dEQP-GLES3's negative_api expects of these: a 3D texture of depth's format, a depth of 0, an unpack buffer's
    // offset not a whole number of the type's datums, a level past the largest; SAMPLES of a multisampled framebuffer)
    const tex3d = 910, tex_array = 911, unpack = 912;
    await call("gles2:glBindTexture", 0x806F, tex3d);
    await call("gles2:glTexImage3D", 0x806F, 0, 0x84F9, 1, 1, 1, 0, 0x84F9, 0x84FA, null);
    assert.equal(await error(), 0x0502, "TexImage3D of TEXTURE_3D and DEPTH_STENCIL: INVALID_OPERATION");
    await call("gles2:glTexStorage3D", 0x806F, 1, 0x8058, 4, 4, 0);
    assert.equal(await error(), 0x0501, "TexStorage3D of depth 0: INVALID_VALUE");
    await call("gles2:glBindTexture", 0x0DE1, 913);
    await call("gles2:glTexStorage2D", 0x0DE1, 1, 0x8056, 4, 4);
    await call("gles2:glBindBuffer", 0x88EC, unpack);
    await call("gles2:glBufferData", 0x88EC, 64, null, 0x88E4);
    await call("gles2:glTexSubImage2DOffsetAEMU", 0x0DE1, 0, 0, 0, 4, 4, 0x1908, 0x8033, 3);
    assert.equal(await error(), 0x0502, "an unpack buffer's offset of 3 for 16-bit datums: INVALID_OPERATION");
    await call("gles2:glBindBuffer", 0x88EC, 0);
    await call("gles2:glBindTexture", 0x8C1A, tex_array);
    await call("gles2:glCompressedTexSubImage3D", 0x8C1A, 13, 0, 0, 0, 0, 0, 0, 0x9278, 0, null);
    assert.equal(await error(), 0x0501, "CompressedTexSubImage3D of level 13: INVALID_VALUE");
    await call("gles2:glBindRenderbuffer", 0x8D41, 914);
    await call("gles2:glRenderbufferStorageMultisample", 0x8D41, 4, 0x8058, 4, 4);
    await call("gles2:glBindFramebuffer", 0x8D40, 915);
    await call("gles2:glFramebufferRenderbuffer", 0x8D40, 0x8CE0, 0x8D41, 914);
    assert.deepEqual([i32s((await call("gles2:glGetIntegerv", 0x80A8, 4)).outs[0])[0], i32s((await call("gles2:glGetIntegerv", 0x80A9, 4)).outs[0])[0]], [1, 4],
        "SAMPLE_BUFFERS and SAMPLES of a multisampled framebuffer");
    await call("gles2:glBindFramebuffer", 0x8D40, 0);
    assert.equal(await error(), 0);
    // (a buffer deleted is unbound from the bound vertex array alone; a cube map face's attachment answers its target;
    // a renderbuffer of GLES 3.0's sized formats its sizes)
    const two_vaos = i32s((await call("gles2:glGenVertexArrays", 2, 8)).outs[0]);
    const kept = i32s((await call("gles2:glGenBuffers", 1, 4)).outs[0])[0];
    await call("gles2:glBindVertexArray", two_vaos[1]);
    await call("gles2:glBindBuffer", 0x8893, kept);
    await call("gles2:glBindVertexArray", two_vaos[0]);
    await call("gles2:glDeleteBuffers", 1, new Uint8Array(new Int32Array([kept]).buffer));
    await call("gles2:glBindVertexArray", two_vaos[1]);
    assert.deepEqual(i32s((await call("gles2:glGetIntegerv", 0x8895, 4)).outs[0]), [kept], "another vertex array keeps a deleted buffer's name");
    await call("gles2:glBindVertexArray", 0);
    await call("gles2:glBindTexture", 0x8513, 920);
    await call("gles2:glTexStorage2D", 0x8513, 1, 0x8058, 4, 4);
    await call("gles2:glBindFramebuffer", 0x8D40, 921);
    await call("gles2:glFramebufferTexture2D", 0x8D40, 0x8CE0, 0x8515, 920, 0);
    assert.deepEqual(i32s((await call("gles2:glGetFramebufferAttachmentParameteriv", 0x8D40, 0x8CE0, 0x8CD3, 4)).outs[0]), [0x8515], "the face POSITIVE_X");
    await call("gles2:glBindFramebuffer", 0x8D40, 0);
    await call("gles2:glBindRenderbuffer", 0x8D41, 922);
    await call("gles2:glRenderbufferStorage", 0x8D41, 0x8229, 4, 4);
    assert.deepEqual(i32s((await call("gles2:glGetRenderbufferParameteriv", 0x8D41, 0x8D50, 4)).outs[0]), [8], "R8's RENDERBUFFER_RED_SIZE");
    assert.equal(await error(), 0);
    // (a stencil mask is unsigned, a level of detail rounded by an integer query)
    await call("gles2:glStencilFunc", 0x0207, 0, 0xFFFFFFFF);
    assert.deepEqual(Array.from(new Float32Array((await call("gles2:glGetFloatv", 0x0B93, 4)).outs[0].slice().buffer)), [4294967296], "STENCIL_VALUE_MASK as a float");
    await call("gles2:glTexParameterf", 0x0DE1, 0x813A, -74.75);
    assert.deepEqual(i32s((await call("gles2:glGetTexParameteriv", 0x0DE1, 0x813A, 4)).outs[0]), [-75], "TEXTURE_MIN_LOD rounded");
    // (GLES 3.0 takes SRC_ALPHA_SATURATE as a destination factor too; GLES 2.0 as a source's alone)
    await call("gles2:glBlendFuncSeparate", 0x0305, 0x0308, 0x0303, 0x0308);
    assert.equal(await error(), 0, "SRC_ALPHA_SATURATE as a destination factor");
    console.log("PASS: GLES 3.0's state: vertex arrays, buffers, textures, samplers, framebuffers, queries, syncs; unused names bound");
}

// ---- GLES 3.0's programs: uniform blocks, unsigned and non-square uniforms, transform feedback's varyings
{
    const { call, renderer } = await setup("3.0", 3);
    const error = async () => (await call("gles2:glGetError")).ret;
    const shader = async (type, source) =>
    {
        const name = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", name);
        return name;
    };
    const vs = await shader(0x8B31, "#version 300 es\nlayout(std140) uniform Light { vec4 color; mat3 m; float k[2]; } light;\n" +
        "uniform uint count;\nuniform mat2x3 tm;\nin vec4 pos;\nout vec3 v;\nflat out uint n;\n" +
        "void main() { v = light.m * light.color.rgb * light.k[1] + tm * vec2(1.0); n = count; gl_Position = pos; }");
    const fs_ = await shader(0x8B30, "#version 300 es\nprecision mediump float;\nin vec3 v;\nflat in uint n;\nout vec4 c;\n" +
        "void main() { c = vec4(v, float(n)); }");
    const program = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", program, vs);
    await call("gles2:glAttachShader", program, fs_);
    await call("gles2:glTransformFeedbackVaryingsAEMU", program, 2, cstring("v;gl_Position;"), 16, 0x8C8C);
    await call("gles2:glLinkProgram", program);
    assert.equal(i32s((await call("gles2:glGetProgramiv", program, 0x8B82, 4)).outs[0])[0], 1, "linked");
    const block = (await call("gles2:glGetUniformBlockIndex", program, cstring("Light"))).ret;
    assert.equal(block, 0, "glGetUniformBlockIndex");
    const block_iv = async pname => i32s((await call("gles2:glGetActiveUniformBlockiv", program, block, pname, 64)).outs[0]);
    assert.equal((await block_iv(0x8A40))[0], 96, "GL_UNIFORM_BLOCK_DATA_SIZE: std140's vec4, mat3, float[2]");
    assert.equal((await block_iv(0x8A42))[0], 3, "three active uniforms in it");
    const indices = i32s((await call("gles2:glGetUniformIndicesAEMU", program, 2, cstring("Light.m;Light.k[0]"), 18, 8)).outs[0]);
    assert.ok(indices.every(i => i >= 0), "glGetUniformIndices");
    const offsets = i32s((await call("gles2:glGetActiveUniformsiv", program, 2, new Uint8Array(new Int32Array(indices).buffer), 0x8A3B, 8)).outs[0]);
    assert.deepEqual(offsets, [16, 64], "std140 offsets: mat3 at 16, the float array at 64");
    const strides = i32s((await call("gles2:glGetActiveUniformsiv", program, 2, new Uint8Array(new Int32Array(indices).buffer), 0x8A3C, 8)).outs[0]);
    assert.deepEqual(strides, [0, 16], "the array's stride 16");
    await call("gles2:glUniformBlockBinding", program, block, 5);
    assert.equal((await block_iv(0x8A3F))[0], 5, "GL_UNIFORM_BLOCK_BINDING");

    await call("gles2:glUseProgram", program);
    const count = (await call("gles2:glGetUniformLocation", program, cstring("count"))).ret;
    const tm = (await call("gles2:glGetUniformLocation", program, cstring("tm"))).ret;
    await call("gles2:glUniform1ui", count, 0xFFFFFFF0);
    assert.deepEqual(Array.from(new Uint32Array((await call("gles2:glGetUniformuiv", program, count, 4)).outs[0].slice().buffer)), [0xFFFFFFF0],
        "glUniform1ui and glGetUniformuiv");
    await call("gles2:glUniform1i", count, 3);
    assert.equal(await error(), 0x0502, "glUniform1i on a uint: INVALID_OPERATION");
    await call("gles2:glUniformMatrix2x3fv", tm, 1, 0, new Uint8Array(new Float32Array([1, 2, 3, 4, 5, 6]).buffer));
    assert.equal(await error(), 0);
    await call("gles2:glUniformMatrix3x2fv", tm, 1, 0, new Uint8Array(new Float32Array([1, 2, 3, 4, 5, 6]).buffer));
    assert.equal(await error(), 0x0502, "a 3x2 matrix into a 2x3: INVALID_OPERATION");

    assert.deepEqual(i32s((await call("gles2:glGetProgramiv", program, 0x8C83, 4)).outs[0]), [2], "GL_TRANSFORM_FEEDBACK_VARYINGS");
    const varying = await call("gles2:glGetTransformFeedbackVarying", program, 0, 16, 4, 4, 4, 16);
    assert.deepEqual([text(varying.outs[3]), i32s(varying.outs[2])[0], i32s(varying.outs[1])[0]], ["v", 0x8B51, 1], "varying 0: v, vec3");
    const bad = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", bad, vs);
    await call("gles2:glAttachShader", bad, fs_);
    await call("gles2:glTransformFeedbackVaryingsAEMU", bad, 1, cstring("nothing;"), 9, 0x8C8C);
    await call("gles2:glLinkProgram", bad);
    assert.equal(i32s((await call("gles2:glGetProgramiv", bad, 0x8B82, 4)).outs[0])[0], 0, "a varying the shader lacks: no link");

    // a buffer transform feedback wrote: its map's bytes are the page's (BUFFER_READ), unless the map invalidates them
    const feedback = i32s((await call("gles2:glGenBuffers", 1, 4)).outs[0])[0];
    await call("gles2:glBindBuffer", 0x8C8E, feedback);
    await call("gles2:glBufferData", 0x8C8E, 84, null, 0x88E1);
    await call("gles2:glBindBufferBase", 0x8C8E, 0, feedback);
    await call("gles2:glBeginTransformFeedback", 4);
    await call("gles2:glDrawArrays", 4, 0, 3);
    await call("gles2:glEndTransformFeedback");
    assert.equal(await error(), 0, "a capture of a triangle");
    const reads = () => renderer.records().filter(r => r.name === "BUFFER_READ");
    const mapped = (await call("gles2:glMapBufferRangeAEMU", 0x8C8E, 8, 76, 1, 76)).outs[0];
    const read = reads().at(-1);
    assert.ok(read && read.buffer === feedback && read.offset === 8 && read.length === 76, "glMapBufferRange of it asks the page");
    assert.ok(mapped.every(b => b === (read.request & 0xFF)), "the page's bytes mapped");
    await call("gles2:glUnmapBufferAEMU", 0x8C8E, 8, 76, 1, null, 4);
    await call("gles2:glMapBufferRangeAEMU", 0x8C8E, 0, 84, 2 | 8, 84);
    assert.equal(reads().length, 1, "a map that invalidates the buffer asks nothing");
    await call("gles2:glUnmapBufferAEMU", 0x8C8E, 0, 84, 2 | 8, new Uint8Array(84), 4);

    // occlusion queries: the page's result for one that drew (asked once), none for one that did not
    const queries = i32s((await call("gles2:glGenQueries", 2, 8)).outs[0]);
    const asked = () => renderer.records().filter(r => r.name === "QUERY_READ");
    await call("gles2:glBeginQuery", 0x8C2F, queries[0]);
    await call("gles2:glEndQuery", 0x8C2F);
    assert.equal(i32s((await call("gles2:glGetQueryObjectuiv", queries[0], 0x8866, 4)).outs[0])[0], 0, "nothing drawn: 0");
    assert.equal(asked().length, 0, "and the page not asked");
    await call("gles2:glBeginQuery", 0x8C2F, queries[1]);
    await call("gles2:glDrawArrays", 4, 0, 3);
    await call("gles2:glEndQuery", 0x8C2F);
    await call("gles2:glGetQueryObjectuiv", queries[1], 0x8866, 4);
    await call("gles2:glGetQueryObjectuiv", queries[1], 0x8866, 4);
    assert.ok(asked().length === 1 && asked()[0].query === queries[1], "a query that drew: the page asked, once");
    console.log("PASS: GLES 3.0's programs: uniform blocks, uint and 2x3 uniforms, transform feedback's varyings");
}

// ---- uniform blocks without a packing of their own (shared, std140 from a default statement): their structs' arrays and
// matrices at std140's offsets too, which glslang's reflection gives only blocks that name std140 (dEQP-GLES3 ubo.random.nested_structs.22)
{
    const vs = `#version 300 es
struct sB { highp mat4x2 mA[3]; highp uvec4 mB; };
struct sC { mediump uvec3 mA; sB mC; };
struct sA { mediump vec3 mA; highp mat2x3 mB; lowp mat2x3 mC; };
layout(column_major) uniform BlockC { sC d; mediump vec2 e; };
layout(std140) uniform;
layout(row_major) uniform BlockB { sA b; } blockB;
in vec4 p;
void main() { gl_Position = p + vec4(d.mC.mA[2][3], float(d.mC.mB.x), e) + vec4(blockB.b.mC[1], 1.0); }`;
    const info = link_glslang_program(glslang, [{ stage: "vertex", source: vs },
        { stage: "fragment", source: "#version 300 es\nprecision mediump float;\nout vec4 o;\nvoid main() { o = vec4(1.0); }" }], {});
    assert.ok(info.ok, info.log);
    const at = name => { const u = info.uniforms.find(x => x.name === name); return [u.offset, u.array_stride, u.matrix_stride]; };
    assert.deepEqual(["d.mC.mA[0]", "d.mC.mB", "e"].map(at), [[16, 64, 16], [208, 0, 0], [224, 0, 0]],
        "a shared block's struct: mat4x2's 64-byte elements, the members after them");
    assert.deepEqual(["BlockB.b.mB", "BlockB.b.mC"].map(at), [[16, 0, 16], [64, 0, 16]], "a default std140 block's struct: row major mat2x3s 48 bytes each");
    // (the code's offsets, the SPIR-V's)
    const words = new Uint32Array(info.spirv.find(m => m.stage === "vertex").words);
    for(const [block, prefix] of [["BlockC", ""], ["BlockB", "BlockB."]])
    {
        for(const [name, leaf] of block_layout(words, parse_spirv(words), block)) assert.equal(at(prefix + name)[0], leaf.offset, name + ": the code's offset");
    }
    console.log("PASS: uniform blocks of the default packing: their structs at std140's offsets");
}

// ---- GLSL ES 1.00 through glslang: what 3.00 reads differently
{
    const link = (vs, fs, bindings = new Map()) => link_glslang_program(glslang, [{ stage: "vertex", source: vs }, { stage: "fragment", source: fs }],
        { bindings, separable: false });
    // (a user overload of a built-in, which 1.00 allows: its calls the user's, step's own the built-in's)
    const overload = link("attribute vec4 p; void main() { gl_Position = p; }",
        "precision mediump float; int step(float i, float j, int a) { return -a; }\n" +
        "void main() { gl_FragColor = vec4(float(step(0.0, 1.0, 2)), step(0.5, 1.0), 0.0, 1.0); }");
    assert.ok(overload.ok, "an overload of step links: " + overload.log);
    // (a built-in called in a global's initializer, its argument in parentheses: a call, not the user's overload;
    // dEQP-GLES2 random.all_features)
    const global_call = link("attribute vec4 p; float b = exp(log2((float(5))) - 1.0); const float c = sqrt((4.0));\n" +
        "void main() { gl_Position = p * b * c; }", "precision mediump float; void main() { gl_FragColor = vec4(1.0); }");
    assert.ok(global_call.ok, "built-ins called in globals' initializers: " + global_call.log);
    // (unused attributes: locations of their own, not one glBindAttribLocation gave a used one)
    const unused = link("attribute vec4 a_coords; attribute vec4 a_position; attribute mat2 a_m; void main() { gl_Position = a_position; }",
        "precision mediump float; void main() { gl_FragColor = vec4(1.0); }", new Map([["a_position", 1]]));
    assert.ok(unused.ok, unused.log);
    assert.deepEqual(unused.attributes.map(a => [a.name, a.location]), [["a_position", 1]]);
    const locations = unused.unused_inputs.map(u => u.location);
    assert.ok(!locations.includes(1) && new Set(locations).size === 3, "the unused inputs' locations: " + locations);
    assert.deepEqual(unused.unused_inputs.map(u => u.components), [4, 2, 2], "a vec4, a mat2's two columns");
    // (a struct's array of one active element is still an array: a count past it is ignored, not refused)
    const nested = link("attribute vec4 p; struct T { float a; vec2 b[2]; }; uniform T t[2]; varying vec2 v; void main() { v = t[1].b[0]; gl_Position = p; }",
        "precision mediump float; varying vec2 v; void main() { gl_FragColor = vec4(v, 0.0, 1.0); }");
    const b = nested.uniforms.find(u => u.base === "t[1].b");
    assert.ok(b && b.size === 1 && b.name === "t[1].b[0]", JSON.stringify(nested.uniforms.map(u => u.name)));
    const { call } = await setup("3.0", 2);
    const program = (await call("gles2:glCreateProgram")).ret;
    for(const [type, source] of [[0x8B31, "attribute vec4 p; struct T { float a; vec2 b[2]; }; uniform T t[2]; varying vec2 v; " +
        "void main() { v = t[1].b[0]; gl_Position = p; }"], [0x8B30, "precision mediump float; varying vec2 v; void main() { gl_FragColor = vec4(v, 0.0, 1.0); }"]])
    {
        const shader = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", shader, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", shader);
        await call("gles2:glAttachShader", program, shader);
    }
    await call("gles2:glLinkProgram", program);
    await call("gles2:glUseProgram", program);
    const location = (await call("gles2:glGetUniformLocation", program, cstring("t[1].b"))).ret;
    await call("gles2:glUniform2fv", location, 2, new Uint8Array(new Float32Array([1, 2, 3, 4]).buffer));
    assert.equal((await call("gles2:glGetError")).ret, 0, "glUniform2fv of 2 into t[1].b");
    // (GLSL ES 3.00: an #extension after the shader's code does not compile)
    const late = (await call("gles2:glCreateShader", 0x8B31)).ret;
    const late_source = "#version 300 es\nprecision mediump float;\n#extension GL_OES_EGL_image_external : enable\nvoid main() { gl_Position = vec4(0.0); }";
    await call("gles2:glShaderString", late, cstring(late_source), late_source.length + 1);
    await call("gles2:glCompileShader", late);
    assert.deepEqual(i32s((await call("gles2:glGetShaderiv", late, 0x8B81, 4)).outs[0]), [0], "an #extension after code: not compiled");
    // (the built-in constants are glGet's answers: an array sized -1 when one differs does not compile)
    const compiles = async (type, source) =>
    {
        const shader = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", shader, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", shader);
        return i32s((await call("gles2:glGetShaderiv", shader, 0x8B81, 4)).outs[0])[0];
    };
    const sized = (version, test) => `${version}float a[${test} ? 1 : -1]; void main() { gl_Position = vec4(a[0]); }`;
    for(const [name, pname] of [["gl_MaxVertexAttribs", 0x8869], ["gl_MaxVertexUniformVectors", 0x8DFB], ["gl_MaxVaryingVectors", 0x8DFC],
        ["gl_MaxFragmentUniformVectors", 0x8DFD], ["gl_MaxCombinedTextureImageUnits", 0x8B4D], ["gl_MaxVertexTextureImageUnits", 0x8B4C],
        ["gl_MaxTextureImageUnits", 0x8872]])
    {
        const value = i32s((await call("gles2:glGetIntegerv", pname, 4)).outs[0])[0];
        assert.equal(await compiles(0x8B31, sized("", `${name} == ${value}`)), 1, `GLSL ES 1.00's ${name} is ${value}`);
        // (GLSL ES 3.00 has no gl_MaxVaryingVectors: its outputs' and inputs' instead)
        if(pname !== 0x8DFC) assert.equal(await compiles(0x8B31, sized("#version 300 es\n", `${name} == ${value}`)), 1, `GLSL ES 3.00's ${name} is ${value}`);
    }
    assert.equal(await compiles(0x8B31, sized("", "gl_MaxDrawBuffers == 1")), 1, "GLSL ES 1.00's gl_MaxDrawBuffers: 1");
    assert.equal(await compiles(0x8B31, sized("#version 300 es\n", "gl_MaxDrawBuffers == 4 && gl_MaxVertexOutputVectors == 16 && " +
        "gl_MaxFragmentInputVectors == 15 && gl_MinProgramTexelOffset == -8 && gl_MaxProgramTexelOffset == 7")), 1, "GLSL ES 3.00's");
    assert.equal(await compiles(0x8B31, sized("", "gl_MaxVertexTextureImageUnits == 32")), 0, "glslang's own default is not");
    console.log("PASS: GLSL ES 1.00 through glslang: overloads of built-ins, unused attributes, a one-element array; a late #extension; " +
        "the built-in constants");
}
                                                                             source/v64/tests/gles/shadow31.mjs                                                                  0000644 0000000 0000000 00000064632 00000000000 014137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// GLES 3.1's shadow state (src/gles/gles31_state.js; docs/gles3-plan.md
// L5) through the GLES host as the guest drives it: compute dispatches and
// what they write, storage and atomic counter buffers, image units, vertex
// attribute bindings, separable programs and pipelines, glProgramUniform,
// the program interface queries, multisampled textures, framebuffers
// without attachments, glCreateShaderProgramv and its link in the batch.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { GLESHost } from "../../src/gles/gles_host.js";
import { compile_glslang, create_glslang } from "../../src/gles/glslang.js";
import { client, cstring, fake_renderer, i32s, text } from "./lib.mjs";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
const glslang = await create_glslang(await compile_glslang(fs.readFileSync(root + "bios/glslang.wasm")));
const DISPLAY = { width: 480, height: 800, dpi: 240 };

const renderer = fake_renderer();
const host = new GLESHost(DISPLAY, renderer, undefined, { glslang, max_version: "3.1" });
const { call } = await client(host).connect();
const context = (await call("rcCreateContext", 3, 0, 4)).ret;
const surface = (await call("rcCreateWindowSurface", 3, 320, 240)).ret;
await call("rcMakeCurrent", context, surface, surface);
const c = host.shadow.context(context);
const error = async () => (await call("gles2:glGetError")).ret;
const ints = async (name, ...args) => i32s((await call("gles2:" + name, ...args)).outs[0]);
const gen = async kind => (await ints("glGen" + kind, 1, 4))[0];
const shader = async (type, source) =>
{
    const name = (await call("gles2:glCreateShader", type)).ret;
    await call("gles2:glShaderString", name, cstring(source), source.length + 1);
    await call("gles2:glCompileShader", name);
    return name;
};
const program = async (sources, separable) =>
{
    const p = (await call("gles2:glCreateProgram")).ret;
    for(const [type, source] of sources) await call("gles2:glAttachShader", p, await shader(type, source));
    if(separable) await call("gles2:glProgramParameteri", p, 0x8258, 1);
    await call("gles2:glLinkProgram", p);
    return p;
};
const linked = async p => (await ints("glGetProgramiv", p, 0x8B82, 4))[0];

// ---- the version
assert.equal(c.version, 31, "a GLES 3.1 context (the guest asks 4)");
assert.deepEqual(await ints("glGetIntegerv", 0x821C, 4), [1], "GL_MINOR_VERSION");
assert.deepEqual(await ints("glGetIntegeri_v", 0x91BF, 2, 4), [64], "GL_MAX_COMPUTE_WORK_GROUP_SIZE's z");
console.log("PASS: a GLES 3.1 context and its limits");

// ---- compute: a dispatch of a program with a compute shader, its storage buffer the GPU's then
{
    const compute = await program([[0x91B9, "#version 310 es\nlayout(local_size_x = 4) in;\n" +
        "layout(std430, binding = 0) buffer Data { uint values[]; };\nvoid main() { values[gl_GlobalInvocationID.x] = gl_GlobalInvocationID.x * 2u; }"]]);
    assert.equal(await linked(compute), 1, "a compute program links");
    assert.deepEqual(await ints("glGetProgramiv", compute, 0x8267, 12), [4, 1, 1], "GL_COMPUTE_WORK_GROUP_SIZE");
    assert.deepEqual(await ints("glGetProgramiv", compute, 0x8258, 4), [0], "GL_PROGRAM_SEPARABLE: not");
    await call("gles2:glDispatchCompute", 1, 1, 1);
    assert.equal(await error(), 0x0502, "no current program: INVALID_OPERATION");
    await call("gles2:glUseProgram", compute);
    const data = await gen("Buffers");
    await call("gles2:glBindBuffer", 0x90D2, data);
    await call("gles2:glBufferData", 0x90D2, 16, null, 0x88E8);
    await call("gles2:glBindBufferRange", 0x90D2, 0, data, 4, 12);
    assert.equal(await error(), 0x0501, "a storage range's offset not a multiple of 256: INVALID_VALUE");
    await call("gles2:glBindBufferBase", 0x90D2, 0, data);
    assert.deepEqual(await ints("glGetIntegeri_v", 0x90D3, 0, 4), [data], "GL_SHADER_STORAGE_BUFFER_BINDING, indexed");
    await call("gles2:glDispatchCompute", 70000, 1, 1);
    assert.equal(await error(), 0x0501, "past MAX_COMPUTE_WORK_GROUP_COUNT: INVALID_VALUE");
    await call("gles2:glDispatchCompute", 1, 1, 1);
    assert.equal(await error(), 0, "a dispatch");
    assert.ok(c.group.buffers.get(data).gpu_newer, "the storage buffer is the GPU's now");
    const mapped = (await call("gles2:glMapBufferRangeAEMU", 0x90D2, 0, 16, 1, 16)).outs[0];
    const read = renderer.records().filter(r => r.name === "BUFFER_READ").at(-1);
    assert.ok(read && read.buffer === data && mapped.every(b => b === (read.request & 0xFF)), "its map asks the page");
    await call("gles2:glUnmapBufferAEMU", 0x90D2, 0, 16, 1, null, 4);
    console.log("PASS: compute, a storage buffer the dispatch wrote");
}

// ---- image units
{
    const mutable = await gen("Textures");
    await call("gles2:glBindTexture", 0x0DE1, mutable);
    await call("gles2:glTexImage2D", 0x0DE1, 0, 0x8814, 4, 4, 0, 0x1908, 0x1406, null);
    await call("gles2:glBindImageTexture", 0, mutable, 0, 0, 0, 0x88BA, 0x8814);
    assert.equal(await error(), 0x0502, "a mutable texture: INVALID_OPERATION");
    const storage = await gen("Textures");
    await call("gles2:glBindTexture", 0x0DE1, storage);
    await call("gles2:glTexStorage2D", 0x0DE1, 1, 0x8814, 4, 4);
    await call("gles2:glBindImageTexture", 0, storage, 0, 0, 0, 0x88BA, 0x8814);
    assert.equal(await error(), 0);
    assert.deepEqual(await ints("glGetIntegeri_v", 0x8F3A, 0, 4), [storage], "GL_IMAGE_BINDING_NAME");
    assert.deepEqual(await ints("glGetIntegeri_v", 0x906E, 0, 4), [0x8814], "GL_IMAGE_BINDING_FORMAT");
    console.log("PASS: image units");
}

// ---- vertex attribute bindings
{
    await call("gles2:glBindVertexBuffer", 0, 1, 0, 16);
    assert.equal(await error(), 0x0502, "no vertex array object: INVALID_OPERATION");
    const vao = await gen("VertexArrays");
    await call("gles2:glBindVertexArray", vao);
    const buffer = await gen("Buffers");
    await call("gles2:glBindBuffer", 0x8892, buffer);
    await call("gles2:glBufferData", 0x8892, 64, null, 0x88E4);
    await call("gles2:glVertexAttribFormat", 2, 3, 0x1406, 0, 8);
    await call("gles2:glVertexAttribBinding", 2, 5);
    await call("gles2:glBindVertexBuffer", 5, buffer, 16, 20);
    await call("gles2:glVertexBindingDivisor", 5, 3);
    assert.equal(await error(), 0);
    assert.deepEqual(await ints("glGetVertexAttribiv", 2, 0x82D4, 4), [5], "GL_VERTEX_ATTRIB_BINDING");
    assert.deepEqual(await ints("glGetVertexAttribiv", 2, 0x82D5, 4), [8], "GL_VERTEX_ATTRIB_RELATIVE_OFFSET");
    assert.deepEqual(await ints("glGetVertexAttribiv", 2, 0x889F, 4), [buffer], "the attribute's buffer is its binding point's");
    assert.deepEqual(await ints("glGetIntegeri_v", 0x82D8, 5, 4), [20], "GL_VERTEX_BINDING_STRIDE");
    const a = c.attribs[2];
    assert.deepEqual([a.buffer, a.offset, a.stride, a.divisor], [buffer, 24, 20, 3], "what the executor reads: offset 16 + 8");
    await call("gles2:glVertexAttribPointerOffset", 3, 2, 0x1406, 0, 0, 4);
    assert.deepEqual(await ints("glGetVertexAttribiv", 3, 0x82D4, 4), [3], "glVertexAttribPointer: the attribute's own binding point");
    assert.deepEqual(await ints("glGetIntegeri_v", 0x82D7, 3, 4), [4], "its offset");
    await call("gles2:glBindVertexArray", 0);
    console.log("PASS: vertex attribute bindings");
}

// ---- separable programs, a pipeline, glProgramUniform, the interface queries
const vs = "#version 310 es\nlayout(location = 0) in vec4 position;\nuniform float scale;\nvoid main() { gl_Position = position * scale; }";
const fs_ = "#version 310 es\nprecision mediump float;\nuniform vec4 color;\nlayout(location = 0) out vec4 o;\nvoid main() { o = color; }";
{
    const vertex = await program([[0x8B31, vs]], true), fragment = await program([[0x8B30, fs_]], true);
    assert.equal(await linked(vertex), 1, "a separable vertex program");
    assert.deepEqual(await ints("glGetProgramiv", vertex, 0x8258, 4), [1], "GL_PROGRAM_SEPARABLE");
    await call("gles2:glGetProgramiv", vertex, 0x8267, 12);
    assert.equal(await error(), 0x0502, "GL_COMPUTE_WORK_GROUP_SIZE of no compute stage: INVALID_OPERATION");
    assert.equal(await linked(fragment), 1, "a separable fragment program");
    const pipeline = await gen("ProgramPipelines");
    await call("gles2:glUseProgram", 0);
    await call("gles2:glBindProgramPipeline", pipeline);
    await call("gles2:glUseProgramStages", pipeline, 1, vertex);
    await call("gles2:glUseProgramStages", pipeline, 2, fragment);
    assert.equal(await error(), 0);
    assert.deepEqual(await ints("glGetProgramPipelineiv", pipeline, 0x8B31, 4), [vertex], "the pipeline's vertex program");
    await call("gles2:glValidateProgramPipeline", pipeline);
    assert.deepEqual(await ints("glGetProgramPipelineiv", pipeline, 0x8B83, 4), [1], "GL_VALIDATE_STATUS");
    const color = (await call("gles2:glGetUniformLocation", fragment, cstring("color"))).ret;
    await call("gles2:glProgramUniform4f", fragment, color, 1, 0.5, 0, 1);
    assert.equal(await error(), 0, "glProgramUniform4f");
    const got = new Float32Array((await call("gles2:glGetUniformfv", fragment, color, 16)).outs[0].slice().buffer);
    assert.deepEqual(Array.from(got), [1, 0.5, 0, 1], "the program's value");
    await call("gles2:glActiveShaderProgram", pipeline, vertex);
    const scale = (await call("gles2:glGetUniformLocation", vertex, cstring("scale"))).ret;
    await call("gles2:glUniform1f", scale, 2);
    assert.equal(await error(), 0, "glUniform with a pipeline: its active program's");
    assert.deepEqual(Array.from(new Float32Array((await call("gles2:glGetUniformfv", vertex, scale, 4)).outs[0].slice().buffer)), [2]);

    assert.deepEqual(await ints("glGetProgramInterfaceiv", fragment, 0x92E1, 0x92F5, 4), [1], "GL_UNIFORM's GL_ACTIVE_RESOURCES");
    const index = (await call("gles2:glGetProgramResourceIndex", fragment, 0x92E1, cstring("color"))).ret;
    assert.equal(index, 0, "glGetProgramResourceIndex");
    const resource = (await call("gles2:glGetProgramResourceiv", fragment, 0x92E1, index, 2, new Uint8Array(new Int32Array([0x92FA, 0x930E]).buffer),
        2, 4, 8)).outs;
    assert.deepEqual([i32s(resource[0]), i32s(resource[1])], [[2], [0x8B52, color]], "its type (vec4) and location, two values");
    assert.equal((await call("gles2:glGetProgramResourceLocation", vertex, 0x92E3, cstring("position"))).ret, 0, "an input's location");
    assert.deepEqual(await ints("glGetProgramInterfaceiv", fragment, 0x92E4, 0x92F5, 4), [1], "one output");
    await call("gles2:glBindProgramPipeline", 0);
    console.log("PASS: separable programs, a pipeline, glProgramUniform, the program interface");
}

// ---- block instance arrays: each element lists the array's variables (dEQP sizes an element's buffer by its unsized array's
// stride); a shared buffer block nothing uses stays active, a packed one does not
{
    const compute = await program([[0x91B9, `#version 310 es
layout(local_size_x = 1) in;
struct S { highp uvec2 a; mediump vec3 c; };
layout(std430, binding = 0) buffer Block { lowp vec2 u; S s[]; } block[3];
layout(shared, binding = 3) buffer Unused { highp ivec2 l[]; };
layout(packed, binding = 4) buffer Packed { highp int k[]; };
layout(std140, binding = 1) uniform Values { highp vec4 v; } values[2];
void main() { block[0].u = values[1].v.xy; block[2].s[1].a = uvec2(1u); }`]]);
    assert.equal(await linked(compute), 1, "a compute program of block instance arrays links");
    const index = async (iface, name) => (await call("gles2:glGetProgramResourceIndex", compute, iface, cstring(name))).ret >>> 0;
    const props = async (iface, i, list, n) => i32s((await call("gles2:glGetProgramResourceiv", compute, iface, i, list.length,
        new Uint8Array(new Int32Array(list).buffer), n, 4, 4 * n)).outs[1]);
    assert.deepEqual(await ints("glGetProgramInterfaceiv", compute, 0x92E6, 0x92F5, 4), [4], "four storage blocks: Block[0..2], Unused");
    const variables = await props(0x92E6, await index(0x92E6, "Block[0]"), [0x9304, 0x9305], 4);
    assert.equal(variables[0], 3, "Block[0]'s variables: u, s[0].a, s[0].c");
    for(const element of ["Block[1]", "Block[2]"])
    {
        assert.deepEqual(await props(0x92E6, await index(0x92E6, element), [0x9304, 0x9305], 4), variables, element + "'s variables, Block[0]'s");
    }
    const unused = await index(0x92E6, "Unused");
    assert.notEqual(unused, 0xFFFFFFFF, "a shared block nothing uses is active");
    assert.deepEqual(await props(0x92E6, unused, [0x9302, 0x9304], 2), [3, 1], "its binding and variable");
    assert.equal(await index(0x92E6, "Packed"), 0xFFFFFFFF, "a packed block nothing uses is not");
    assert.notEqual(await index(0x92E5, "l[0]"), 0xFFFFFFFF, "the shared block's variable");
    const uniforms = await props(0x92E2, await index(0x92E2, "Values[0]"), [0x9304, 0x9305], 2);
    assert.deepEqual(await props(0x92E2, await index(0x92E2, "Values[1]"), [0x9304, 0x9305], 2), uniforms, "Values[1]'s uniforms, Values[0]'s");
    assert.deepEqual(await ints("glGetActiveUniformBlockiv", compute, await index(0x92E2, "Values[1]"), 0x8A42, 4), [1],
        "GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS of Values[1]");
    assert.equal(await error(), 0);
    // (a buffer block std140 from a default statement: its struct's arrays and matrices at std140's offsets, as glslang's reflection
    // gives only blocks that name std140; an array of arrays of matrices in a uniform block's struct the same, dEQP-GLES31
    // ubo.random.all_shared_buffer.37)
    const std140 = await program([[0x91B9, `#version 310 es
layout(local_size_x = 1) in;
layout(std140) buffer;
struct S { highp mat3x2 m[2]; float f; };
buffer B { S s; float g; };
struct T { highp mat4x2 mA[3][3]; highp uvec4 mB; };
layout(column_major) uniform U { mediump uvec3 a; T t; };
void main() { g = s.m[1][2].y + s.f + t.mA[2][1][3].x + float(t.mB.x); }`]]);
    assert.equal(await linked(std140), 1, "a program of std140 structs links");
    const std140_props = async (iface, name, list) => i32s((await call("gles2:glGetProgramResourceiv", std140, iface,
        (await call("gles2:glGetProgramResourceIndex", std140, iface, cstring(name))).ret, list.length, new Uint8Array(new Int32Array(list).buffer),
        list.length, 4, 4 * list.length)).outs[1]);
    assert.deepEqual(await std140_props(0x92E5, "s.m[0]", [0x92FC, 0x92FE, 0x92FF]), [0, 48, 16], "a struct's mat3x2[2] in a std140 buffer block");
    assert.deepEqual([(await std140_props(0x92E5, "s.f", [0x92FC]))[0], (await std140_props(0x92E5, "g", [0x92FC]))[0]], [96, 112], "the members after it");
    assert.deepEqual(await std140_props(0x92E1, "t.mA[1][0]", [0x92FC, 0x92FE]), [208, 64], "a struct's mat4x2[3][3] in a shared uniform block");
    assert.deepEqual(await std140_props(0x92E1, "t.mB", [0x92FC]), [592], "the member after it");
    assert.equal(await error(), 0);
    console.log("PASS: block instance arrays' variables, an unused shared block, std140 structs");
}

// ---- multisampled textures, framebuffers without attachments
{
    const texture = await gen("Textures");
    await call("gles2:glBindTexture", 0x9100, texture);
    await call("gles2:glTexStorage2DMultisample", 0x9100, 4, 0x8058, 8, 8, 1);
    assert.equal(await error(), 0);
    assert.deepEqual(await ints("glGetTexLevelParameteriv", 0x9100, 0, 0x9106, 4), [4], "GL_TEXTURE_SAMPLES");
    assert.deepEqual(await ints("glGetTexLevelParameteriv", 0x9100, 0, 0x1000, 4), [8], "GL_TEXTURE_WIDTH");
    const position = new Float32Array((await call("gles2:glGetMultisamplefv", 0x8E50, 1, 8)).outs[0].slice().buffer);
    assert.deepEqual(Array.from(position), [0.875, 0.375], "sample 1's position");
    const fbo = await gen("Framebuffers");
    await call("gles2:glBindFramebuffer", 0x8D40, fbo);
    assert.equal((await call("gles2:glCheckFramebufferStatus", 0x8D40)).ret, 0x8CD7, "no attachments, no default size: incomplete");
    await call("gles2:glFramebufferParameteri", 0x8D40, 0x9310, 16);
    await call("gles2:glFramebufferParameteri", 0x8D40, 0x9311, 8);
    assert.equal((await call("gles2:glCheckFramebufferStatus", 0x8D40)).ret, 0x8CD5, "a default size: complete");
    await call("gles2:glBindFramebuffer", 0x8D40, 0);
    console.log("PASS: multisampled textures, framebuffers without attachments");
}

// ---- glCreateShaderProgramv: the program's name its answer, its link in the batch before it
{
    const source = "#version 310 es\nprecision mediump float;\nlayout(location = 0) out vec4 o;\nvoid main() { o = vec4(1.0); }";
    const made = (await call("gles2:glCreateShaderProgramvAEMU", 0x8B30, 1, cstring(source), source.length + 1)).ret;
    assert.ok(made, "a program");
    assert.equal(await linked(made), 1, "linked");
    assert.equal(c.group.objects.get(made).separable, true, "separable");
    host.flush();
    const records = renderer.records();
    const command = records.findIndex(r => r.name === "COMMAND" && r.command.name === "glCreateShaderProgramvAEMU");
    const link = records.findIndex(r => r.name === "PROGRAM_LINK" && r.program === made);
    assert.ok(command >= 0 && link >= 0 && link < command, "the page gets the command, its link first");
    console.log("PASS: glCreateShaderProgramv");
}
void text;

// ---- EXT_robustness: no reset; glReadnPixelsEXT reads as glReadPixels, its buffer's size checked
{
    assert.equal((await call("gles2:glGetGraphicsResetStatusEXT")).ret, 0, "GL_NO_ERROR: never reset");
    await call("gles2:glReadnPixelsEXT", 0, 0, 2, 2, 0x1908, 0x1401, 15, 16);
    assert.equal(await error(), 0x0502, "a buffer too small: INVALID_OPERATION");
    const before = renderer.records().filter(r => r.name === "READ_PIXELS").length;
    await call("gles2:glReadnPixelsEXT", 0, 0, 2, 2, 0x1908, 0x1401, 16, 16);
    assert.equal(await error(), 0);
    assert.equal(renderer.records().filter(r => r.name === "READ_PIXELS").length, before + 1, "the page reads them");
    console.log("PASS: EXT_robustness");
}

// ---- GLES 3.2's state: KHR_debug's initial values, the stages' limits, the bounding box, sample shading
{
    const renderer32 = fake_renderer();
    const host32 = new GLESHost(DISPLAY, renderer32, undefined, { glslang, max_version: "3.2" });
    const { call: call32 } = await client(host32).connect();
    const context32 = (await call32("rcCreateContext", 3, 0, 4)).ret;
    const surface32 = (await call32("rcCreateWindowSurface", 3, 320, 240)).ret;
    await call32("rcMakeCurrent", context32, surface32, surface32);
    const get = async pname => i32s((await call32("gles2:glGetIntegerv", pname, 32)).outs[0]).slice(0, 1)[0];
    assert.equal(host32.shadow.context(context32).version, 32);
    assert.equal(await get(0x8DE0), 256, "GL_MAX_GEOMETRY_OUTPUT_VERTICES");
    assert.equal(await get(0x8E7D), 32, "GL_MAX_PATCH_VERTICES");
    assert.equal(await get(0x82E8), 256, "GL_MAX_LABEL_LENGTH");
    const box = new Float32Array((await call32("gles2:glGetFloatv", 0x92BE, 32)).outs[0].slice().buffer);
    assert.deepEqual(Array.from(box), [-1, -1, -1, 1, 1, 1, 1, 1], "GL_PRIMITIVE_BOUNDING_BOX");
    await call32("gles2:glEnable", 0x8C36);
    assert.equal((await call32("gles2:glIsEnabled", 0x8C36)).ret, 1, "GL_SAMPLE_SHADING");
    assert.equal((await call32("gles2:glGetError")).ret, 0);
    console.log("PASS: GLES 3.2's state");

    // a geometry shader: its program's layout, the draws' modes it takes, adjacency
    const shader32 = async (type, source) =>
    {
        const name = (await call32("gles2:glCreateShader", type)).ret;
        await call32("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call32("gles2:glCompileShader", name);
        return name;
    };
    const p = (await call32("gles2:glCreateProgram")).ret;
    await call32("gles2:glAttachShader", p, await shader32(0x8B31, "#version 320 es\nin vec4 position;\nvoid main() { gl_Position = position; }"));
    await call32("gles2:glAttachShader", p, await shader32(0x8DD9, "#version 320 es\nlayout(lines_adjacency, invocations = 3) in;\n" +
        "layout(line_strip, max_vertices = 2) out;\nvoid main() { gl_Position = gl_in[1].gl_Position; EmitVertex(); gl_Position = gl_in[2].gl_Position; EmitVertex(); }"));
    await call32("gles2:glAttachShader", p, await shader32(0x8B30, "#version 320 es\nprecision mediump float;\nout vec4 o;\nvoid main() { o = vec4(1.0); }"));
    await call32("gles2:glLinkProgram", p);
    const program_ints = async pname => i32s((await call32("gles2:glGetProgramiv", p, pname, 4)).outs[0])[0];
    assert.equal(await program_ints(0x8B82), 1, "a program of a geometry shader links");
    assert.deepEqual([await program_ints(0x8917), await program_ints(0x8918), await program_ints(0x8916), await program_ints(0x887F)],
        [0x000A, 0x0003, 2, 3], "GL_GEOMETRY_LINKED_INPUT_TYPE, _OUTPUT_TYPE, _VERTICES_OUT, GL_GEOMETRY_SHADER_INVOCATIONS");
    await call32("gles2:glUseProgram", p);
    await call32("gles2:glDrawArrays", 0x0004, 0, 3);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0502, "triangles to a shader of lines with adjacency: INVALID_OPERATION");
    await call32("gles2:glDrawArrays", 0x000B, 0, 5);
    assert.equal((await call32("gles2:glGetError")).ret, 0, "a line strip with adjacency");
    await call32("gles2:glUseProgram", 0);
    await call32("gles2:glDrawArrays", 0x000F, 0, 3);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0500, "no such mode: INVALID_ENUM");
    console.log("PASS: GLES 3.2's geometry shaders");

    // clamp to border: the wrap and the color, a texture's and a sampler's; the scalar calls refused
    const tex32 = i32s((await call32("gles2:glGenTextures", 1, 4)).outs[0])[0];
    await call32("gles2:glBindTexture", 0x0DE1, tex32);
    await call32("gles2:glTexParameteri", 0x0DE1, 0x2802, 0x812D);
    assert.equal((await call32("gles2:glGetError")).ret, 0, "GL_CLAMP_TO_BORDER");
    await call32("gles2:glTexParameterfv", 0x0DE1, 0x1004, new Uint8Array(new Float32Array([0.25, 0.5, 0.75, 1]).buffer));
    assert.deepEqual(Array.from(new Float32Array((await call32("gles2:glGetTexParameterfv", 0x0DE1, 0x1004, 16)).outs[0].slice().buffer)),
        [0.25, 0.5, 0.75, 1], "GL_TEXTURE_BORDER_COLOR");
    await call32("gles2:glTexParameterf", 0x0DE1, 0x1004, 1);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0500, "a border color of one value: INVALID_ENUM");
    const sampler32 = i32s((await call32("gles2:glGenSamplers", 1, 4)).outs[0])[0];
    await call32("gles2:glSamplerParameteriv", sampler32, 0x1004, new Uint8Array(new Int32Array([0x7FFFFFFF, 0, 0, 0x7FFFFFFF]).buffer));
    const color = Array.from(new Float32Array((await call32("gles2:glGetSamplerParameterfv", sampler32, 0x1004, 16)).outs[0].slice().buffer));
    assert.ok(color[0] === 1 && Math.abs(color[1]) < 1e-6 && color[3] === 1, "an integer border color, normalized: " + color);
    assert.deepEqual(i32s((await call32("gles2:glGetSamplerParameteriv", sampler32, 0x1004, 16)).outs[0]), [0x7FFFFFFF, 0, 0, 0x7FFFFFFF]);
    assert.equal((await call32("gles2:glGetError")).ret, 0);
    console.log("PASS: GLES 3.2's clamp to border");

    // blend equations: MIN and MAX (GLES 3.0's); the advanced ones glBlendEquation's alone, a draw by one the fragment shader's declared
    await call32("gles2:glBlendEquation", 0x8007);
    assert.equal((await call32("gles2:glGetError")).ret, 0, "GL_MIN");
    await call32("gles2:glBlendEquationSeparate", 0x9294, 0x8006);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0500, "an advanced equation, separate: INVALID_ENUM");
    await call32("gles2:glBlendEquation", 0x9294);
    assert.deepEqual(i32s((await call32("gles2:glGetIntegerv", 0x8009, 4)).outs[0]), [0x9294], "GL_BLEND_EQUATION_RGB: MULTIPLY_KHR");
    const blending = async declared =>
    {
        const program = (await call32("gles2:glCreateProgram")).ret;
        await call32("gles2:glAttachShader", program, await shader32(0x8B31, "#version 320 es\nin vec4 p;\nvoid main() { gl_Position = p; }"));
        await call32("gles2:glAttachShader", program, await shader32(0x8B30, "#version 320 es\nprecision mediump float;\n" + declared +
            "out vec4 o;\nvoid main() { o = vec4(1.0); }"));
        await call32("gles2:glLinkProgram", program);
        await call32("gles2:glUseProgram", program);
        await call32("gles2:glDrawArrays", 4, 0, 3);
        return (await call32("gles2:glGetError")).ret;
    };
    await call32("gles2:glEnable", 0x0BE2);
    assert.equal(await blending(""), 0x0502, "a fragment shader without blend_support_multiply: INVALID_OPERATION");
    assert.equal(await blending("layout(blend_support_all_equations) out;\n"), 0, "blend_support_all_equations");
    await call32("gles2:glDisable", 0x0BE2);
    await call32("gles2:glBlendEquation", 0x8006);
    await call32("gles2:glUseProgram", 0);
    console.log("PASS: GLES 3.2's blend equations");

    // tessellation: the program's layout; patches its draws', and only its
    const tessellation = (await call32("gles2:glCreateProgram")).ret;
    await call32("gles2:glAttachShader", tessellation, await shader32(0x8B31, "#version 320 es\nin vec4 p;\nvoid main() { gl_Position = p; }"));
    await call32("gles2:glAttachShader", tessellation, await shader32(0x8E88, "#version 320 es\nlayout(vertices = 4) out;\n" +
        "void main() { gl_out[gl_InvocationID].gl_Position = gl_in[0].gl_Position; gl_TessLevelOuter[0] = 2.0; }"));
    await call32("gles2:glAttachShader", tessellation, await shader32(0x8E87, "#version 320 es\nlayout(quads, fractional_odd_spacing, cw, point_mode) in;\n" +
        "void main() { gl_Position = gl_in[0].gl_Position; }"));
    await call32("gles2:glAttachShader", tessellation, await shader32(0x8B30, "#version 320 es\nprecision mediump float;\nout vec4 o;\nvoid main() { o = vec4(1.0); }"));
    await call32("gles2:glLinkProgram", tessellation);
    const tess_ints = async pname => i32s((await call32("gles2:glGetProgramiv", tessellation, pname, 4)).outs[0])[0];
    assert.equal(await tess_ints(0x8B82), 1, "a program of tessellation shaders links");
    assert.deepEqual([await tess_ints(0x8E75), await tess_ints(0x8E76), await tess_ints(0x8E77), await tess_ints(0x8E78), await tess_ints(0x8E79)],
        [4, 0x0007, 0x8E7B, 0x0900, 1], "TESS_CONTROL_OUTPUT_VERTICES, TESS_GEN_MODE, _SPACING, _VERTEX_ORDER, _POINT_MODE");
    await call32("gles2:glUseProgram", tessellation);
    await call32("gles2:glDrawArrays", 4, 0, 3);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0502, "triangles to tessellation: INVALID_OPERATION");
    await call32("gles2:glDrawArrays", 0xE, 0, 3);
    assert.equal((await call32("gles2:glGetError")).ret, 0, "patches");
    await call32("gles2:glUseProgram", 0);
    await call32("gles2:glDrawArrays", 0xE, 0, 3);
    assert.equal((await call32("gles2:glGetError")).ret, 0x0502, "patches without tessellation: INVALID_OPERATION");
    console.log("PASS: GLES 3.2's tessellation");
}
                                                                                                      source/v64/tests/gles/snapshot.mjs                                                                  0000644 0000000 0000000 00000053523 00000000000 014342  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// GLES state in snapshots (docs/gles-proxy-plan.md E5; src/gles/gles_snapshot.js,
// gles_host.js, src/virt/goldfish.js):
// - the packing: Maps, Sets, typed arrays, objects reached twice, classes,
//   undefined and the numbers JSON has no words for;
// - a host's state and a connection's restored on a new host, as the pipe
//   does at a restore: renderControl's objects, the shadow state (a linked
//   program's uniforms, a texture, the viewport), the bytes of a command not
//   whole yet; the page reset and given its state back; new handles go on
//   from the old ones;
// - a GLES 3.1 context's objects (vertex arrays and their binding points,
//   samplers, queries, storage bindings, program pipelines, glslang's
//   programs linked again as they were linked, a buffer the GPU wrote)
//   restored on a new host with glslang;
// - prepare_save answers the calls that wait for the page first: the reply
//   is kept for the guest to read after the restore;
// - the goldfish pipe keeps its channels with their services' state; a
//   snapshot of the old kind (channels only) closes them.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { GLESHost } from "../../src/gles/gles_host.js";
import { compile_glslang, create_glslang } from "../../src/gles/glslang.js";
import { pack, unpack } from "../../src/gles/gles_snapshot.js";
import { GoldfishPipe } from "../../src/virt/goldfish.js";
import { decode_reply, encode_command } from "../../src/gles/gles_wire.js";
import { client, cstring, f32s, fake_renderer, i32s, settle } from "./lib.mjs";

const DISPLAY = { width: 480, height: 800, dpi: 240 };
const GL = { TEXTURE_2D: 0x0DE1, RGBA: 0x1908, UNSIGNED_BYTE: 0x1401, VERTEX_SHADER: 0x8B31, FRAGMENT_SHADER: 0x8B30, LINK_STATUS: 0x8B82,
    VIEWPORT: 0x0BA2, COLOR_CLEAR_VALUE: 0x0C22, TEXTURE_BINDING_2D: 0x8069, CURRENT_PROGRAM: 0x8B8D };

/** Whether a value is what v86's snapshots hold (src/state.js): no plain objects */
function snapshot_safe(value, path = "state")
{
    if(value === null || typeof value !== "object") return assert.notEqual(typeof value, "function", path);
    if(ArrayBuffer.isView(value)) return undefined;
    if(value instanceof Map) return [...value].forEach(([k, v], i) => { snapshot_safe(k, path + ".key" + i); snapshot_safe(v, path + "." + k); });
    assert.ok(Array.isArray(value), path + " is a plain object");
    return value.forEach((v, i) => snapshot_safe(v, path + "[" + i + "]"));
}

// ---- the packing

{
    function Thing() { this.n = 1; }
    Thing.prototype.twice = function() { return this.n * 2; };
    const shared = { name: "group" };
    const value = {
        map: new Map([[1, "one"], ["two", [2, 2]]]), set: new Set([3, "x"]), bytes: new Uint8Array([1, 2, 3]),
        floats: new Float32Array([0.5, -1]).subarray(1), a: shared, b: shared, thing: new Thing(), missing: undefined,
        numbers: [NaN, Infinity, -Infinity, -0, 1e300], nested: [[{ deep: true }]], gone: () => 1, gpu: { texture: 1 },
    };
    const packed = pack(value, { classes: { "Thing": Thing.prototype }, skip: key => key === "gpu" });
    snapshot_safe(packed);
    assert.equal(typeof packed[0], "string");
    const back = unpack(packed, { "Thing": Thing.prototype });
    assert.deepEqual([...back.map], [[1, "one"], ["two", [2, 2]]]);
    assert.deepEqual([...back.set], [3, "x"]);
    assert.ok(back.bytes instanceof Uint8Array);
    assert.deepEqual([...back.bytes], [1, 2, 3]);
    assert.ok(back.floats instanceof Float32Array);
    assert.deepEqual([...back.floats], [-1], "a view: its own elements");
    assert.equal(back.a, back.b, "an object reached twice is one object");
    assert.equal(back.thing.twice(), 2, "a class's prototype");
    assert.ok("missing" in back && back.missing === undefined);
    assert.ok(Number.isNaN(back.numbers[0]));
    assert.deepEqual(back.numbers.slice(1), [Infinity, -Infinity, -0, 1e300]);
    assert.ok(Object.is(back.numbers[3], -0));
    assert.deepEqual(back.nested, [[{ deep: true }]]);
    assert.equal(back.gone, undefined, "a function is left out");
    assert.equal("gpu" in back, false, "a key skipped");
    // (an instance of a class not named: left out, as the GPU's objects are)
    class Device {}
    assert.equal(unpack(pack({ device: new Device() })).device, undefined);
    console.log("ok - the packing");
}

// ---- a host and a connection, saved and restored on a new host

/** A connection's calls on a service (the guest's encoder; replies read back) */
function caller(service)
{
    return async (name, ...args) =>
    {
        service.write(encode_command(name, args));
        await settle();
        const parts = [];
        for(let bytes; (bytes = service.read(1 << 20));) parts.push(bytes.slice());
        const reply = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
        let at = 0;
        for(const p of parts) { reply.set(p, at); at += p.length; }
        return reply.length ? decode_reply(name, args, reply) : { outs: [], ret: undefined };
    };
}

{
    const renderer = fake_renderer();
    const host = new GLESHost(DISPLAY, renderer);
    const guest = client(host);
    const conn = await guest.connect();
    const call = conn.call;
    const context = (await call("rcCreateContext", 0, 0, 2)).ret;
    const surface = (await call("rcCreateWindowSurface", 0, 64, 64)).ret;
    const buffer = (await call("rcCreateColorBuffer", 64, 64, GL.RGBA)).ret;
    await call("rcSetWindowColorBuffer", surface, buffer);
    await call("rcMakeCurrent", context, surface, surface);
    const shader = async (type, source) =>
    {
        const name = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", name);
        return name;
    };
    const vs = await shader(GL.VERTEX_SHADER, "attribute vec4 position; void main() { gl_Position = position; }");
    const fs = await shader(GL.FRAGMENT_SHADER, "precision mediump float; uniform vec4 tint; void main() { gl_FragColor = tint; }");
    const program = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", program, vs);
    await call("gles2:glAttachShader", program, fs);
    await call("gles2:glLinkProgram", program);
    // (the shader's source changed after the link: the program keeps what it linked)
    await call("gles2:glShaderString", fs, cstring("not GLSL"), 9);
    await call("gles2:glUseProgram", program);
    const tint = (await call("gles2:glGetUniformLocation", program, cstring("tint"))).ret;
    await call("gles2:glUniform4f", tint, 0.25, 0.5, 0.75, 1);
    const [texture] = i32s((await call("gles2:glGenTextures", 1, 4)).outs[0]);
    await call("gles2:glBindTexture", GL.TEXTURE_2D, texture);
    await call("gles2:glTexImage2D", GL.TEXTURE_2D, 0, GL.RGBA, 4, 4, 0, GL.RGBA, GL.UNSIGNED_BYTE, new Uint8Array(64));
    await call("gles2:glViewport", 1, 2, 30, 40);
    await call("gles2:glClearColor", 0.5, 0.25, 1, 0);
    // (half a command written when the machine stops)
    const viewport_get = encode_command("gles2:glGetIntegerv", [GL.VIEWPORT, 16]);
    conn.service.write(viewport_get.subarray(0, 5));

    await host.prepare_save();
    const connection_state = conn.service.get_state();
    const process_state = guest.process_pipe.get_state();
    const state = host.get_state();
    snapshot_safe(connection_state, "connection");
    snapshot_safe(process_state, "process");
    snapshot_safe(state, "host");
    assert.deepEqual(state[2], ["page state 1", []], "the page's state, fetched by prepare_save");
    assert.equal(host.get_state()[2], null, "kept for one snapshot");

    const renderer2 = fake_renderer();
    const host2 = new GLESHost(DISPLAY, renderer2);
    // (as at a restore: the pipe's channels first, then the host's slot)
    const service = host2.service("opengles", () => {}, connection_state);
    host2.service("GLProcessPipe", () => {}, process_state);
    host2.set_state(state);
    assert.deepEqual(renderer2.messages.slice(-2), ["reset", "gles_restore"]);
    assert.deepEqual(renderer2.restored, [["page state 1", []]]);
    // (the rest of the command the guest was writing)
    service.write(viewport_get.subarray(5));
    await settle();
    const viewport = decode_reply("gles2:glGetIntegerv", [GL.VIEWPORT, 16], service.read(1 << 20));
    assert.deepEqual(i32s(viewport.outs[0]), [1, 2, 30, 40], "the viewport, through the command written across the snapshot");
    const call2 = caller(service);
    assert.deepEqual(f32s((await call2("gles2:glGetFloatv", GL.COLOR_CLEAR_VALUE, 16)).outs[0]), [0.5, 0.25, 1, 0]);
    assert.deepEqual(i32s((await call2("gles2:glGetIntegerv", GL.CURRENT_PROGRAM, 4)).outs[0]), [program]);
    assert.deepEqual(i32s((await call2("gles2:glGetProgramiv", program, GL.LINK_STATUS, 4)).outs[0]), [1], "linked again from what it linked");
    assert.equal((await call2("gles2:glGetUniformLocation", program, cstring("tint"))).ret, tint);
    assert.deepEqual(f32s((await call2("gles2:glGetUniformfv", program, tint, 16)).outs[0]), [0.25, 0.5, 0.75, 1]);
    assert.deepEqual(i32s((await call2("gles2:glGetIntegerv", GL.TEXTURE_BINDING_2D, 4)).outs[0]), [texture]);
    assert.equal((await call2("gles2:glIsTexture", texture)).ret, 1);
    assert.equal((await call2("gles2:glGetError")).ret, 0);
    // (the program draws: its link info is back)
    await call2("gles2:glUseProgram", program);
    assert.equal((await call2("gles2:glGetError")).ret, 0);
    // (new handles after the old ones; the process's objects still its)
    const buffer2 = (await call2("rcCreateColorBuffer", 8, 8, GL.RGBA)).ret;
    assert.ok(buffer2 > buffer, `${buffer2} after ${buffer}`);
    assert.equal(host2.rc.color_buffers.size, 2);
    assert.equal(host2.rc.contexts.get(context).owner, "p" + guest.puid);
    // (and the page's batches go on)
    assert.equal((await call2("rcFlushWindowColorBuffer", surface)).ret, 0);
    const names = renderer2.records().map(r => r.name);
    assert.ok(names.includes("FLUSH_SURFACE"), names.join());
    assert.equal(host2.summary().connections, 1);
    console.log("ok - a host and its connection restored on a new host");
}

// ---- a GLES 3.1 context's objects restored on a new host

{
    const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..") + "/";
    const glslang = await create_glslang(await compile_glslang(fs.readFileSync(root + "bios/glslang.wasm")));
    const host = new GLESHost(DISPLAY, fake_renderer(), undefined, { glslang, max_version: "3.1" });
    const guest = client(host);
    const conn = await guest.connect();
    const call = conn.call;
    const ints = async (name, ...args) => i32s((await call("gles2:" + name, ...args)).outs[0]);
    const gen = async kind => (await ints("glGen" + kind, 1, 4))[0];
    const context = (await call("rcCreateContext", 3, 0, 4)).ret;
    const surface = (await call("rcCreateWindowSurface", 3, 64, 64)).ret;
    await call("rcMakeCurrent", context, surface, surface);
    const shader = async (type, source) =>
    {
        const name = (await call("gles2:glCreateShader", type)).ret;
        await call("gles2:glShaderString", name, cstring(source), source.length + 1);
        await call("gles2:glCompileShader", name);
        return name;
    };
    // (a vertex array of a binding point)
    const vao = await gen("VertexArrays");
    await call("gles2:glBindVertexArray", vao);
    const quad = await gen("Buffers");
    await call("gles2:glBindBuffer", 0x8892, quad);
    await call("gles2:glBufferData", 0x8892, 32, null, 0x88E4);
    await call("gles2:glVertexAttribFormat", 0, 2, 0x1406, 0, 4);
    await call("gles2:glVertexAttribBinding", 0, 3);
    await call("gles2:glBindVertexBuffer", 3, quad, 0, 8);
    // (a sampler on unit 1)
    const sampler = await gen("Samplers");
    await call("gles2:glActiveTexture", 0x84C1);
    await call("gles2:glBindSampler", 1, sampler);
    await call("gles2:glSamplerParameteri", sampler, 0x2801, 0x2600);
    // (a compute program's dispatch writes a storage buffer: the GPU's then)
    const compute = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", compute, await shader(0x91B9, "#version 310 es\nlayout(local_size_x = 4) in;\n" +
        "layout(std430, binding = 2) buffer Data { uint values[]; };\nvoid main() { values[gl_GlobalInvocationID.x] = 1u; }"));
    await call("gles2:glLinkProgram", compute);
    await call("gles2:glUseProgram", compute);
    const data = await gen("Buffers");
    await call("gles2:glBindBuffer", 0x90D2, data);
    await call("gles2:glBufferData", 0x90D2, 16, null, 0x88E8);
    await call("gles2:glBindBufferBase", 0x90D2, 2, data);
    await call("gles2:glDispatchCompute", 1, 1, 1);
    await call("gles2:glUseProgram", 0);
    // (a program of one varying captured, then asked for two: it keeps what it linked)
    const captured = (await call("gles2:glCreateProgram")).ret;
    await call("gles2:glAttachShader", captured, await shader(GL.VERTEX_SHADER,
        "#version 300 es\nin vec4 position;\nout vec4 v;\nvoid main() { v = position; gl_Position = position; }"));
    await call("gles2:glAttachShader", captured, await shader(GL.FRAGMENT_SHADER,
        "#version 300 es\nprecision mediump float;\nin vec4 v;\nout vec4 o;\nvoid main() { o = v; }"));
    await call("gles2:glTransformFeedbackVaryingsAEMU", captured, 1, cstring("v;"), 3, 0x8C8C);
    await call("gles2:glLinkProgram", captured);
    await call("gles2:glTransformFeedbackVaryingsAEMU", captured, 2, cstring("v;gl_Position;"), 16, 0x8C8C);
    // (a pipeline of a separable program, its uniform set by glProgramUniform; an occlusion query)
    const fs_source = "#version 310 es\nprecision mediump float;\nuniform vec4 color;\nlayout(location = 0) out vec4 o;\nvoid main() { o = color; }";
    const separable = (await call("gles2:glCreateShaderProgramvAEMU", 0x8B30, 1, cstring(fs_source), fs_source.length + 1)).ret;
    const color = (await call("gles2:glGetUniformLocation", separable, cstring("color"))).ret;
    await call("gles2:glProgramUniform4f", separable, color, 1, 0.5, 0, 1);
    const pipeline = await gen("ProgramPipelines");
    await call("gles2:glBindProgramPipeline", pipeline);
    await call("gles2:glUseProgramStages", pipeline, 2, separable);
    const query = await gen("Queries");
    await call("gles2:glBeginQuery", 0x8C2F, query);
    await call("gles2:glEndQuery", 0x8C2F);
    assert.equal((await call("gles2:glGetError")).ret, 0);

    await host.prepare_save();
    const connection_state = conn.service.get_state();
    const process_state = guest.process_pipe.get_state();
    const state = host.get_state();
    snapshot_safe(state, "host");
    const renderer2 = fake_renderer();
    const host2 = new GLESHost(DISPLAY, renderer2, undefined, { glslang, max_version: "3.1" });
    const service = host2.service("opengles", () => {}, connection_state);
    host2.service("GLProcessPipe", () => {}, process_state);
    host2.set_state(state);
    const call2 = caller(service);
    const ints2 = async (name, ...args) => i32s((await call2("gles2:" + name, ...args)).outs[0]);
    assert.deepEqual(await ints2("glGetIntegerv", 0x821C, 4), [1], "GLES 3.1 still");
    assert.deepEqual(await ints2("glGetIntegerv", 0x85B5, 4), [vao], "the vertex array bound");
    assert.deepEqual(await ints2("glGetVertexAttribiv", 0, 0x82D4, 4), [3], "its attribute's binding point");
    assert.deepEqual(await ints2("glGetVertexAttribiv", 0, 0x82D5, 4), [4], "its relative offset");
    assert.deepEqual(await ints2("glGetIntegeri_v", 0x8F4F, 3, 4), [quad], "the binding point's buffer");
    assert.deepEqual(await ints2("glGetIntegerv", 0x8919, 4), [sampler], "the sampler on the active unit (1)");
    assert.deepEqual(await ints2("glGetSamplerParameteriv", sampler, 0x2801, 4), [0x2600], "its filter");
    assert.deepEqual(await ints2("glGetIntegeri_v", 0x90D3, 2, 4), [data], "the storage binding");
    assert.deepEqual(await ints2("glGetProgramiv", compute, GL.LINK_STATUS, 4), [1], "the compute program, linked again");
    assert.deepEqual(await ints2("glGetProgramiv", captured, 0x8C83, 4), [1], "the captured program: the one varying it linked");
    assert.deepEqual(await ints2("glGetProgramiv", separable, 0x8258, 4), [1], "glCreateShaderProgramv's: separable");
    assert.equal((await call2("gles2:glGetUniformLocation", separable, cstring("color"))).ret, color);
    assert.deepEqual(f32s((await call2("gles2:glGetUniformfv", separable, color, 16)).outs[0]), [1, 0.5, 0, 1], "its uniform");
    assert.deepEqual(await ints2("glGetProgramPipelineiv", pipeline, GL.FRAGMENT_SHADER, 4), [separable], "the pipeline's fragment program");
    assert.equal((await call2("gles2:glIsQuery", query)).ret, 1, "the query");
    // (the storage buffer is still the GPU's: its map asks the page)
    await call2("gles2:glMapBufferRangeAEMU", 0x90D2, 0, 16, 1, 16);
    assert.ok(renderer2.records().some(r => r.name === "BUFFER_READ" && r.buffer === data), "the buffer the GPU wrote, read from the page");
    assert.equal((await call2("gles2:glGetError")).ret, 0);
    console.log("ok - a GLES 3.1 context's objects restored on a new host");
}

// ---- prepare_save answers what waits

{
    const renderer = fake_renderer({ manual: true });
    const host = new GLESHost(DISPLAY, renderer);
    const conn = await client(host).connect();
    const context = (await conn.call("rcCreateContext", 0, 0, 2)).ret;
    const surface = (await conn.call("rcCreateWindowSurface", 0, 16, 16)).ret;
    await conn.call("rcMakeCurrent", context, surface, surface);
    renderer.run();
    // (glReadPixels waits for the page; then a command after it, held back)
    conn.send("gles2:glReadPixels", 0, 0, 2, 2, GL.RGBA, GL.UNSIGNED_BYTE, 16);
    conn.send("gles2:glGetError");
    await settle();
    assert.equal(conn.service.available(), false, "the read waits");
    const saved = host.prepare_save();
    await settle();
    renderer.run();
    await saved;
    const state = conn.service.get_state();
    const host_state = host.get_state();
    const host2 = new GLESHost(DISPLAY, fake_renderer());
    const service = host2.service("opengles", () => {}, state);
    host2.set_state(host_state);
    const reply = service.read(1 << 20);
    const pixels = decode_reply("gles2:glReadPixels", [0, 0, 2, 2, GL.RGBA, GL.UNSIGNED_BYTE, 16], reply.subarray(0, 16));
    assert.deepEqual([...pixels.outs[0]], new Array(16).fill(host.next_request - 2 & 0xFF), "the read's pixels, answered before the save");
    assert.equal(decode_reply("gles2:glGetError", [], reply.subarray(16)).ret, 0, "and the call after it");
    console.log("ok - prepare_save answers what waits for the page");
}

// ---- the pipe's channels

{
    const memory = new Uint8Array(4096);
    let irq = false;
    let mmio = null;
    const cpu = {
        io: { register_mmio: (base, size, handlers) => { mmio = handlers; } },
        set_irq: (intid, level) => { irq = level; },
        read_blob_physical: (address, size) => memory.slice(address, address + size),
        write_blob_physical: (bytes, address) => memory.set(bytes, address),
    };
    const services = [];
    const pipe = new GoldfishPipe(cpu, 0, 32, { "ro.test": "1" }, (name, wake, saved) =>
    {
        if(name !== "echo") return null;
        let bytes = saved ? saved : new Uint8Array(0);
        const service = { write: b => { bytes = b.slice(); }, read: () => { const out = bytes; bytes = new Uint8Array(0); return out.length ? out : null; },
            available: () => bytes.length > 0, close() {}, get_state: () => bytes.slice(), saved };
        services.push(service);
        return service;
    });
    const machine = { pipe, mmio: () => mmio };
    const REG = { COMMAND: 0x00, STATUS: 0x04, CHANNEL: 0x08, SIZE: 0x0C, ADDRESS: 0x10 };
    const command = (target, channel, code, bytes) =>
    {
        const io = target.mmio();
        if(bytes) memory.set(bytes, 0);
        io.write(REG.CHANNEL, 4, channel);
        io.write(REG.SIZE, 4, bytes ? bytes.length : 256);
        io.write(REG.ADDRESS, 4, 0);
        io.write(REG.COMMAND, 4, code);
        return io.read(REG.STATUS) | 0;
    };
    const OPEN = 1, WRITE = 4, READ = 6;
    const text = s => new TextEncoder().encode(s);
    command(machine, 7, OPEN);
    command(machine, 7, WRITE, text("pipe:qemud:boot-properties\0"));
    command(machine, 7, WRITE, text("0004list"));
    command(machine, 9, OPEN);
    command(machine, 9, WRITE, text("pipe:echo\0"));
    command(machine, 9, WRITE, text("hello"));
    command(machine, 11, OPEN);
    command(machine, 11, WRITE, text("pipe:ec"));
    const state = pipe.get_state();
    snapshot_safe(state, "pipe");

    // (a new machine's pipe, its state set)
    const pipe2 = new GoldfishPipe(cpu, 0, 32, { "ro.test": "1" }, (name, wake, saved) =>
    {
        if(name !== "echo") return null;
        let bytes = saved || new Uint8Array(0);
        return { write: b => { bytes = b.slice(); }, read: () => { const out = bytes; bytes = new Uint8Array(0); return out.length ? out : null; },
            available: () => bytes.length > 0, close() {}, get_state: () => bytes.slice() };
    });
    pipe2.set_state(state);
    const machine2 = { pipe: pipe2, mmio: () => mmio };
    const read = (target, channel) =>
    {
        const n = command(target, channel, READ);
        return n > 0 ? new TextDecoder().decode(memory.slice(0, n)) : n;
    };
    assert.match(read(machine2, 7), /ro\.test=1/, "qemud's answer, not read before the snapshot");
    assert.equal(read(machine2, 9), "hello", "a service's own state");
    assert.equal(command(machine2, 11, WRITE, text("ho\0")), 3, "a name written across the snapshot");
    assert.equal(command(machine2, 11, WRITE, text("again")), 5);
    assert.equal(read(machine2, 11), "again");
    // (a snapshot of the old kind: its channels closed)
    const pipe3 = new GoldfishPipe(cpu, 0, 32, {}, () => null);
    pipe3.set_state([7, 9]);
    assert.equal(command({ mmio: () => mmio }, 9, READ), 0, "closed: end of stream");
    assert.equal(irq, true, "the closed channels' wakes");
    console.log("ok - the goldfish pipe's channels");
}
                                                                                                                                                                             source/v64/tests/gles/stream.mjs                                                                    0000644 0000000 0000000 00000017012 00000000000 013767  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// One connection's stream (src/gles/gles_stream.js; docs/gles-proxy-plan.md E1):
// - the client flags, then commands, written whole, split at every byte
//   and in random pieces: the same commands decoded, the same replies;
// - a reply that waits (a promise) keeps the replies in the commands'
//   order; what the guest wrote meanwhile is decoded after it;
// - an opcode of no range is counted and skipped, so is a command whose
//   parameters do not fill it; a size below 8 breaks the stream;
// - reading the replies in pieces of any size;
// - a decoder that throws: the call answered with zeros, counted.
import assert from "node:assert/strict";
import { GLESStream } from "../../src/gles/gles_stream.js";
import { decode_reply, encode_command } from "../../src/gles/gles_wire.js";

const join = parts =>
{
    const bytes = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
    let at = 0;
    for(const p of parts) { bytes.set(p, at); at += p.length; }
    return bytes;
};
const FLAGS = new Uint8Array([0, 0, 0, 0]);

/** A decoder that answers rcGetRendererVersion 1, rcGetFBParam(p) p * 10, glGetIntegerv a counter */
function decoder(log)
{
    let n = 0;
    return (command, args) =>
    {
        log.push(command.name);
        switch(command.name)
        {
            case "rcGetRendererVersion": return 1;
            case "rcGetFBParam": return args[0] * 10;
            case "glGetIntegerv":
                args[1].view.setInt32(0, ++n, true);
                return undefined;
        }
        return 0;
    };
}

const commands = [
    ["rcGetRendererVersion", []],
    ["gles2:glClearColor", [0.25, 0.5, 0.75, 1]],
    ["rcGetFBParam", [2]],
    ["gles2:glShaderString", [7, new TextEncoder().encode("precision mediump float; void main() {}\0"), 40]],
    ["gles2:glGetIntegerv", [0x0D33, 4]],
    ["rcFBPost", [3]],
    ["gles2:glTexImage2D", [0x0DE1, 0, 0x1908, 16, 16, 0, 0x1908, 0x1401, new Uint8Array(1024).map((_, i) => i)]],
    ["gles2:glGetIntegerv", [0x0D33, 4]],
];
const stream_bytes = join([FLAGS, ...commands.map(([name, args]) => encode_command(name, args))]);
const expected_names = commands.map(([name]) => name.replace(/^gles2:/, ""));
const expected_replies = join([
    new Uint8Array([1, 0, 0, 0]), new Uint8Array([20, 0, 0, 0]), new Uint8Array([1, 0, 0, 0]), new Uint8Array([2, 0, 0, 0]),
]);

/** @param {function(!Uint8Array): !Array<!Uint8Array>} split */
function run(split)
{
    const log = [];
    const stream = new GLESStream(decoder(log));
    for(const piece of split(stream_bytes)) stream.write(piece);
    assert.deepEqual(log, expected_names);
    assert.equal(stream.flags, 0);
    const reply = stream.read(1 << 20);
    assert.deepEqual(reply, expected_replies);
    assert.equal(stream.read(16), null, "nothing more");
    assert.equal(stream.counts.get("glGetIntegerv"), 2);
}

// ---- splitting

{
    run(bytes => [bytes]);
    run(bytes => Array.from(bytes, b => new Uint8Array([b])));
    let seed = 7;
    for(let round = 0; round < 50; round++)
    {
        run(bytes =>
        {
            const pieces = [];
            for(let at = 0; at < bytes.length;)
            {
                seed = seed * 1103515245 + 12345 >>> 0;
                const n = 1 + seed % 300;
                pieces.push(bytes.slice(at, at + n));
                at += n;
            }
            return pieces;
        });
    }
    console.log("PASS: commands split anywhere");
}

// ---- a reply that waits

{
    const log = [];
    let release;
    const stream = new GLESStream((command, args) =>
    {
        log.push(command.name);
        if(command.name === "rcGetFBParam") return new Promise(resolve => { release = resolve; });
        return command.name === "rcGetRendererVersion" ? 1 : 0;
    }, () => log.push("readable"));
    stream.write(FLAGS);
    stream.write(encode_command("rcGetFBParam", [1]));
    stream.write(join([encode_command("rcFBPost", [1]), encode_command("rcGetRendererVersion", [])]));
    assert.deepEqual(log, ["rcGetFBParam"], "nothing decoded while the reply waits");
    assert.equal(stream.read(64), null);
    release(480);
    await Promise.resolve();
    assert.deepEqual(log, ["rcGetFBParam", "rcFBPost", "rcGetRendererVersion", "readable"]);
    assert.deepEqual(stream.read(64), new Uint8Array([224, 1, 0, 0, 1, 0, 0, 0]), "480, then 1: in the commands' order");
    console.log("PASS: a waiting reply keeps the order");
}

// ---- unknown, malformed, broken

{
    const log = [];
    const stream = new GLESStream(decoder(log));
    const unknown = new Uint8Array(12);
    new DataView(unknown.buffer).setUint32(0, 9000, true);
    new DataView(unknown.buffer).setUint32(4, 12, true);
    const malformed = encode_command("rcGetFBParam", [1]).slice();
    const padded = join([malformed, new Uint8Array(4)]);
    new DataView(padded.buffer).setUint32(4, padded.length, true);
    const warn = console.warn;
    console.warn = () => {};
    stream.write(join([FLAGS, unknown, padded, encode_command("rcGetRendererVersion", [])]));
    console.warn = warn;
    assert.deepEqual(log, ["rcGetRendererVersion"]);
    assert.deepEqual([...stream.unknown], [[9000, 1]]);
    assert.deepEqual([...stream.malformed], [["rcGetFBParam", 1]]);
    assert.deepEqual(stream.read(64), new Uint8Array([1, 0, 0, 0]));

    const broken = new GLESStream(decoder([]));
    const bad = new Uint8Array(8);
    new DataView(bad.buffer).setUint32(0, 10000, true);
    new DataView(bad.buffer).setUint32(4, 4, true);
    console.warn = () => {};
    broken.write(join([FLAGS, bad, encode_command("rcGetRendererVersion", [])]));
    console.warn = warn;
    assert.equal(broken.broken, true);
    assert.equal(broken.dropped_bytes, 8);
    broken.write(new Uint8Array(5));
    assert.equal(broken.dropped_bytes, 13, "the rest of the connection dropped");
    assert.equal(broken.read(64), null);
    console.log("PASS: unknown opcodes, malformed commands, a broken stream");
}

// ---- reading in pieces

{
    const stream = new GLESStream((command, args) => { args[1].data.fill(0xAB); return 7; });
    stream.write(FLAGS);
    // (rcGetConfigs: bufSize, an out buffer of 300 bytes; the reply its bytes, then an i32)
    for(let i = 0; i < 3; i++) stream.write(encode_command("rcGetConfigs", [300, 300]));
    const parts = [];
    for(let bytes; (bytes = stream.read(97));) parts.push(bytes);
    const all = join(parts);
    assert.equal(all.length, 3 * 304);
    assert.ok(parts.every(p => p.length <= 97));
    for(let i = 0; i < 3; i++)
    {
        const { outs, ret } = decode_reply("rcGetConfigs", [300, 300], all.subarray(i * 304, i * 304 + 304));
        assert.equal(ret, 7);
        assert.ok(outs[0].every(b => b === 0xAB));
    }
    console.log("PASS: replies read in pieces");
}

// a decoder that fails: the call is answered with zeros and counted, the stream goes on
{
    const stream = new GLESStream(command =>
    {
        if(command.name === "rcGetFBParam") throw new TypeError("a bug in a decoder");
        return 7;
    });
    const warn = console.warn;
    console.warn = () => {};
    stream.write(join([FLAGS, encode_command("rcGetFBParam", [1]), encode_command("rcGetRendererVersion", [])]));
    console.warn = warn;
    const reply = stream.read(1 << 20);
    assert.equal(decode_reply("rcGetFBParam", [1], reply.subarray(0, 4)).ret, 0, "the failed call: zeros");
    assert.equal(decode_reply("rcGetRendererVersion", [], reply.subarray(4)).ret, 7, "the next call answered");
    assert.deepEqual([...stream.failed], [["rcGetFBParam", 1]]);
    assert.equal(stream.broken, false);
    console.log("ok - a decoder's fault answers zeros");
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/gpu/shaders/tgsi/es2gears-vs.txt                                                   0000644 0000000 0000000 00000002233 00000000000 017122  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL IN[1]
DCL OUT[0], POSITION
DCL OUT[1], GENERIC[0]
DCL CONST[0..9]
DCL TEMP[0..19]
IMM[0] UINT32 {0, 1045220557, 0, 0}
DCL TEMP[20..23]
  0: MUL TEMP[0].xyz, CONST[4].xyzz, IN[1].xxxx
  1: MUL TEMP[1].xyz, CONST[5].xyzz, IN[1].yyyy
  2: ADD TEMP[2].xyz, TEMP[0].xyzx, TEMP[1].xyzx
  3: MUL TEMP[3].xyz, CONST[6].xyzz, IN[1].zzzz
  4: ADD TEMP[4].xyz, TEMP[2].xyzx, TEMP[3].xyzx
  5: ADD TEMP[5].xyz, TEMP[4].xyzx, CONST[7].xyzz
  6: DP3 TEMP[6].x, TEMP[5].xyzx, TEMP[5].xyzx
  7: RSQ TEMP[7].x, TEMP[6].xxxx
  8: MUL TEMP[8].xyz, TEMP[5].xyzz, TEMP[7].xxxx
  9: DP3 TEMP[9].x, CONST[8].xyzx, CONST[8].xyzx
 10: RSQ TEMP[10].x, TEMP[9].xxxx
 11: MUL TEMP[11].xyz, CONST[8].xyzz, TEMP[10].xxxx
 12: DP3 TEMP[12].x, TEMP[8].xyzx, TEMP[11].xyzx
 13: MAX TEMP[13].x, TEMP[12].xxxx, IMM[0].xxxx
 14: ADD TEMP[14].x, IMM[0].yyyy, TEMP[13].xxxx
 15: MUL OUT[1].xyz, TEMP[14].xxxx, CONST[9].xyzx
 16: MUL TEMP[15], CONST[0], IN[0].xxxx
 17: MUL TEMP[16], CONST[1], IN[0].yyyy
 18: ADD TEMP[17], TEMP[15], TEMP[16]
 19: MUL TEMP[18], CONST[2], IN[0].zzzz
 20: ADD TEMP[19], TEMP[17], TEMP[18]
 21: ADD OUT[0], TEMP[19], CONST[3]
 22: MOV OUT[1].w, CONST[9].xxxw
 23: END
                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/gpu/shaders/tgsi/gltest-compute-cs.txt                                             0000644 0000000 0000000 00000003504 00000000000 020342  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       COMP
PROPERTY CS_FIXED_BLOCK_WIDTH 8
PROPERTY CS_FIXED_BLOCK_HEIGHT 8
PROPERTY CS_FIXED_BLOCK_DEPTH 1
DCL SV[0], BLOCK_ID
DCL SV[1], THREAD_ID
DCL SV[2], GRID_SIZE
DCL IMAGE[0], 2D, PIPE_FORMAT_R8G8B8A8_UNORM, WR
DCL BUFFER[0]
DCL MEMORY[1], SHARED
DCL CONST[0]
DCL TEMP[0..24]
IMM[0] UINT32 {3, 2, 24, 252}
IMM[1] UINT32 {0, 1, 6, 4}
IMM[2] UINT32 {1000, 100000, 1115684864, 1065353216}
DCL TEMP[25..28]
DCL TEMP[29]
  0: MOV TEMP[29].xyz, SV[0].xyzz
  1: SHL TEMP[2].xy, TEMP[29].xyzx, IMM[0].xxxx
  2: UADD TEMP[3].xy, TEMP[2].xyxx, SV[1].xyxx
  3: SHL TEMP[4].x, SV[1].yxxx, IMM[0].xxxx
  4: UADD TEMP[5].x, TEMP[4].xxxx, SV[1].xxxx
  5: SHL TEMP[6].x, TEMP[5].xxxx, IMM[0].yyyy
  6: UMUL TEMP[7].x, TEMP[3].xxxx, CONST[0].xxxx
  7: UADD TEMP[8].x, TEMP[7].xxxx, TEMP[3].yxxx
  8: STORE MEMORY[0].x, TEMP[6].xxxx, TEMP[8].xxxx
  9: MEMBAR IMM[0].zzzz
 10: BARRIER
 11: INEG TEMP[9].x, TEMP[5].xxxx
 12: SHL TEMP[10].x, TEMP[9].xxxx, IMM[0].yyyy
 13: UADD TEMP[11].x, TEMP[10].xxxx, IMM[0].wwww
 14: LOAD TEMP[12].x, MEMORY[0], TEMP[11].xxxx
 15: ATOMUADD TEMP[13].x, BUFFER[0], IMM[1].xxxx, IMM[1].yyyy
 16: SHL TEMP[14].x, TEMP[3].yxxx, IMM[1].zzzz
 17: UADD TEMP[15].x, TEMP[14].xxxx, TEMP[3].xxxx
 18: SHL TEMP[16].x, TEMP[15].xxxx, IMM[0].yyyy
 19: UADD TEMP[17].x, TEMP[16].xxxx, IMM[1].wwww
 20: UMUL TEMP[18].x, TEMP[29].xxxx, IMM[2].xxxx
 21: UADD TEMP[19].x, TEMP[12].xxxx, TEMP[18].xxxx
 22: UMUL TEMP[20].x, SV[2].xxxx, IMM[2].yyyy
 23: UADD TEMP[21].x, TEMP[19].xxxx, TEMP[20].xxxx
 24: STORE BUFFER[0].x, TEMP[17].xxxx, TEMP[21].xxxx
 25: U2F TEMP[22].xy, TEMP[3].xyyy
 26: DIV TEMP[1].xy, TEMP[22].xyxx, IMM[2].zzzz
 27: U2F TEMP[23].x, TEMP[5].xxxx
 28: DIV TEMP[1].z, TEMP[23].xxxx, IMM[2].zzzz
 29: MOV TEMP[1].w, IMM[2].wwww
 30: MOV TEMP[0].xy, TEMP[3].xyxx
 31: STORE IMAGE[0], TEMP[0], TEMP[1], 2D, PIPE_FORMAT_R8G8B8A8_UNORM
 32: END
                                                                                                                                                                                            source/v64/tests/gpu/shaders/tgsi/gltest-doubles-fs.txt                                             0000644 0000000 0000000 00000002736 00000000000 020334  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
DCL IN[0].xy, GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
DCL CONST[0]
DCL TEMP[0..10]
IMM[0] UINT32 {0, 1070596096, 1071644672, 3220176896}
IMM[1] UINT32 {1065353216, 0, 0, 0}
DCL TEMP[11..14]
  0: F2D TEMP[0].xy, IN[0].xyyy
  1: F2D TEMP[1].xy, IN[0].yyyy
  2: MOV TEMP[11].xy, TEMP[0].xyxy
  3: MOV TEMP[12].xy, CONST[0].xyxy
  4: MOV TEMP[13].xy, IMM[0].xyxy
  5: DMAD TEMP[2].xy, TEMP[11], TEMP[12], TEMP[13]
  6: MOV TEMP[11].xy, TEMP[1].xyxy
  7: MOV TEMP[12].xy, CONST[0].xyxy
  8: MOV TEMP[13].xy, IMM[0].xzxz
  9: DMAD TEMP[3].xy, TEMP[11], TEMP[12], TEMP[13]
 10: MOV TEMP[11].xy, TEMP[2].xyxy
 11: DFRAC TEMP[4].xy, TEMP[11]
 12: MOV TEMP[11].xy, TEMP[3].xyxy
 13: DFRAC TEMP[5].xy, TEMP[11]
 14: MOV TEMP[11].xy, TEMP[4].xyxy
 15: D2F OUT[0].x, TEMP[11]
 16: MOV TEMP[11].xy, TEMP[5].xyxy
 17: D2F OUT[0].y, TEMP[11]
 18: MOV TEMP[11].xy, TEMP[2].xyxy
 19: MOV TEMP[12].xy, TEMP[3].xyxy
 20: DMAX TEMP[6].xy, TEMP[11], TEMP[12]
 21: MOV TEMP[11].xy, TEMP[5].xyxy
 22: MOV TEMP[12].xy, IMM[0].xwxw
 23: MOV TEMP[13].xy, TEMP[3].xyxy
 24: DMAD TEMP[7].xy, TEMP[11], TEMP[12], TEMP[13]
 25: MOV TEMP[11].xy, TEMP[7].xyxy
 26: MOV TEMP[12].xy, IMM[0].xwxw
 27: MOV TEMP[13].xy, TEMP[6].xyxy
 28: DMAD TEMP[8].xy, TEMP[11], TEMP[12], TEMP[13]
 29: MOV TEMP[11].xy, TEMP[8].xyxy
 30: MOV TEMP[12].xy, IMM[0].xzxz
 31: DMUL TEMP[9].xy, TEMP[11], TEMP[12]
 32: MOV TEMP[11].xy, TEMP[9].xyxy
 33: D2F TEMP[10].x, TEMP[11]
 34: MOV OUT[0].z, TEMP[10].xxxx
 35: MOV OUT[0].w, IMM[1].xxxx
 36: END
                                  source/v64/tests/gpu/shaders/tgsi/gltest-gather-fs.txt                                              0000644 0000000 0000000 00000000766 00000000000 020152  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
DCL IN[0].xy, GENERIC[0], PERSPECTIVE
DCL IN[1].x, GENERIC[1], CONSTANT
DCL OUT[0], COLOR
DCL SAMP[0]
DCL SVIEW[0], 2D, FLOAT
DCL TEMP[0..2]
IMM[0] UINT32 {1, 1056964608, 1065353216, 0}
DCL TEMP[3..6]
  0: MOV TEMP[0].x, IN[1].xxxx
  1: MOV TEMP[0].y, IMM[0].xxxx
  2: TG4 TEMP[1], IN[0].xyyy, IMM[0].xxxx, SAMP[0], 2D, TEMP[0].xyz
  3: ADD TEMP[2].x, TEMP[1].zxxx, TEMP[1].wxxx
  4: MUL OUT[0].z, IMM[0].yyyy, TEMP[2].xxxx
  5: MOV OUT[0].xy, TEMP[1].xyxx
  6: MOV OUT[0].w, IMM[0].zzzz
  7: END
          source/v64/tests/gpu/shaders/tgsi/gltest-storage-fs.txt                                             0000644 0000000 0000000 00000002475 00000000000 020343  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COORD_ORIGIN LOWER_LEFT
PROPERTY FS_COORD_PIXEL_CENTER HALF_INTEGER
DCL IN[0], POSITION, LINEAR
DCL OUT[0], COLOR
DCL IMAGE[0], 2D, PIPE_FORMAT_R32_UINT
DCL BUFFER[0]
DCL CONST[0]
DCL TEMP[0..18]
IMM[0] UINT32 {2, 0, 1, 4}
IMM[1] UINT32 {255, 1132396544, 8, 1048576000}
IMM[2] UINT32 {1048576000, 1065353216, 0, 0}
DCL TEMP[19..22]
  0: MUL TEMP[2].x, IN[0].yxxx, CONST[0].xxxx
  1: ADD TEMP[1].y, TEMP[2].xxxx, CONST[0].yyxx
  2: MOV TEMP[1].x, IN[0].xxxx
  3: F2I TEMP[3].xy, TEMP[1].xyyy
  4: ISSG TEMP[4].xy, TEMP[3].xyxx
  5: IABS TEMP[5].xy, TEMP[3].xyxx
  6: USHR TEMP[6].xy, TEMP[5].xyxx, IMM[0].xxxx
  7: UMUL TEMP[0].xy, TEMP[4].xyxx, TEMP[6].xyxx
  8: LOAD TEMP[8], IMAGE[0], TEMP[0], 2D, PIPE_FORMAT_R32_UINT
  9: ATOMUADD TEMP[9].x, BUFFER[0], IMM[0].yyyy, IMM[0].zzzz
 10: SHL TEMP[10].x, TEMP[3].yxxx, IMM[0].xxxx
 11: UADD TEMP[11].x, IMM[0].wwww, TEMP[10].xxxx
 12: MOV TEMP[12].x, TEMP[3].xxxx
 13: ATOMUMAX TEMP[13].x, BUFFER[0], TEMP[11].xxxx, TEMP[12].xxxx
 14: AND TEMP[14].x, TEMP[8].xxxx, IMM[1].xxxx
 15: U2F TEMP[15].x, TEMP[14].xxxx
 16: DIV OUT[0].x, TEMP[15].xxxx, IMM[1].yyyy
 17: USHR TEMP[16].x, TEMP[8].xxxx, IMM[1].zzzz
 18: AND TEMP[17].x, TEMP[16].xxxx, IMM[1].xxxx
 19: U2F TEMP[18].x, TEMP[17].xxxx
 20: DIV OUT[0].y, TEMP[18].xxxx, IMM[1].yyyy
 21: MOV OUT[0].zw, IMM[2].xxxy
 22: END
                                                                                                                                                                                                   source/v64/tests/gpu/shaders/tgsi/gltest-tess-tcs.txt                                               0000644 0000000 0000000 00000001446 00000000000 020033  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       TESS_CTRL
PROPERTY TCS_VERTICES_OUT 4
DCL IN[][0], POSITION
DCL SV[0], INVOCATIONID
DCL OUT[][0].xy, POSITION
DCL OUT[1], TESSOUTER
DCL OUT[2].xy, TESSINNER
DCL TEMP[0..2]
DCL ADDR[0..1]
IMM[0] UINT32 {1063675494, 0, 1073741824, 1077936128}
IMM[1] UINT32 {1073741824, 1077936128, 1082130432, 1084227584}
DCL TEMP[3..6]
  0: UARL ADDR[1].x, SV[0].xxxx
  1: MOV TEMP[0].xy, IN[ADDR[1].x][0].xyyy
  2: MUL TEMP[1].xy, TEMP[0].xyyy, IMM[0].xxxx
  3: UARL ADDR[1].x, SV[0].xxxx
  4: MOV OUT[ADDR[1].x][0].xy, TEMP[1].xyxx
  5: USEQ TEMP[2].x, SV[0].xxxx, IMM[0].yyyy
  6: UIF TEMP[2].xxxx :13
  7:   MOV OUT[1].x, IMM[0].zzzz
  8:   MOV OUT[1].y, IMM[0].zwzz
  9:   MOV OUT[1].z, IMM[1].xxzx
 10:   MOV OUT[1].w, IMM[1].xxxw
 11:   MOV OUT[2].x, IMM[1].zzzz
 12:   MOV OUT[2].y, IMM[1].zyzz
 13: ENDIF
 14: END
                                                                                                                                                                                                                          source/v64/tests/gpu/shaders/tgsi/gltest-tess-tes.txt                                               0000644 0000000 0000000 00000001152 00000000000 020027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       TESS_EVAL
PROPERTY TES_PRIM_MODE 7
PROPERTY TES_SPACING 2
PROPERTY TES_VERTEX_ORDER_CW 0
PROPERTY TES_POINT_MODE 0
DCL IN[][0], POSITION
DCL SV[0], TESSCOORD
DCL OUT[0], POSITION
DCL OUT[1].xy, GENERIC[0]
DCL TEMP[0..3]
IMM[0] UINT32 {0, 1065353216, 0, 0}
DCL TEMP[4..7]
  0: LRP TEMP[1].xy, SV[0].xxxx, IN[1][0].xyyy, IN[0][0].xyyy
  1: LRP TEMP[2].xy, SV[0].xxxx, IN[2][0].xyyy, IN[3][0].xyyy
  2: LRP TEMP[0].xy, SV[0].yyyy, TEMP[2].xyxx, TEMP[1].xyxx
  3: MOV TEMP[0].z, IMM[0].xxxx
  4: MOV TEMP[0].w, IMM[0].yyyy
  5: MOV OUT[0], TEMP[0]
  6: MOV TEMP[3].xy, SV[0].xyxx
  7: MOV OUT[1].xy, TEMP[3].xyxx
  8: END
                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/gpu/shaders/tgsi/gltest-tess-vs.txt                                                0000644 0000000 0000000 00000000136 00000000000 017665  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL OUT[0].xy, POSITION
DCL TEMP[0..3]
  0: MOV OUT[0].xy, IN[0].xyxx
  1: END
                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/gpu/shaders/tgsi/kmscube-fs.txt                                                    0000644 0000000 0000000 00000000337 00000000000 017023  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL IN[0].xyz, GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
IMM[0] UINT32 {1065353216, 0, 0, 0}
DCL TEMP[0..3]
  0: MOV OUT[0].xyz, IN[0].xyzx
  1: MOV OUT[0].w, IMM[0].xxxx
  2: END
                                                                                                                                                                                                                                                                                                 source/v64/tests/gpu/shaders/tgsi/kmscube-rgba-fs.txt                                               0000644 0000000 0000000 00000000605 00000000000 017732  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL IN[0].xyz, GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
DCL SAMP[0]
DCL SVIEW[0], 2D, FLOAT
DCL TEMP[0..2]
IMM[0] UINT32 {1065353216, 0, 0, 0}
DCL TEMP[3..6]
  0: MOV TEMP[1].xy, IN[0].yzxx
  1: TEX TEMP[2], TEMP[1].xyxx, SAMP[0], 2D
  2: MOV TEMP[0].x, IN[0].xxxx
  3: MOV TEMP[0].y, IMM[0].xxxx
  4: MUL OUT[0], TEMP[0].xxxy, TEMP[2]
  5: END
                                                                                                                           source/v64/tests/gpu/shaders/tgsi/kmscube-rgba-vs.txt                                               0000644 0000000 0000000 00000002464 00000000000 017757  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL IN[1]
DCL IN[2]
DCL OUT[0], POSITION
DCL OUT[1].xyz, GENERIC[0]
DCL CONST[0..10]
DCL TEMP[0..24]
IMM[0] UINT32 {1073741824, 1101004800, 0, 0}
DCL TEMP[25..28]
  0: MUL TEMP[0], CONST[4], IN[0].xxxx
  1: MUL TEMP[1], CONST[5], IN[0].yyyy
  2: ADD TEMP[2], TEMP[0], TEMP[1]
  3: MUL TEMP[3], CONST[6], IN[0].zzzz
  4: ADD TEMP[4], TEMP[2], TEMP[3]
  5: MUL TEMP[5], CONST[7], IN[0].wwww
  6: ADD OUT[0], TEMP[4], TEMP[5]
  7: MUL TEMP[6], CONST[0], IN[0].xxxx
  8: MUL TEMP[7], CONST[1], IN[0].yyyy
  9: ADD TEMP[8], TEMP[6], TEMP[7]
 10: MUL TEMP[9], CONST[2], IN[0].zzzz
 11: ADD TEMP[10], TEMP[8], TEMP[9]
 12: MUL TEMP[11], CONST[3], IN[0].wwww
 13: ADD TEMP[12], TEMP[10], TEMP[11]
 14: DIV TEMP[13].xyz, TEMP[12].xyzz, TEMP[12].wwwx
 15: MUL TEMP[14].xyz, CONST[8].xyzz, IN[1].xxxx
 16: MUL TEMP[15].xyz, CONST[9].xyzz, IN[1].yyyx
 17: ADD TEMP[16].xyz, TEMP[14].xyzz, TEMP[15].xyzz
 18: MUL TEMP[17].xyz, CONST[10].xyzz, IN[1].zzzx
 19: ADD TEMP[18].xyz, TEMP[16].xyzz, TEMP[17].xyzz
 20: ADD TEMP[20].xyz, IMM[0].xxyx, -TEMP[13].xyzx
 21: DP3 TEMP[21].x, TEMP[20].xyzx, TEMP[20].xyzx
 22: RSQ TEMP[22].x, TEMP[21].xxxx
 23: MUL TEMP[23].xyz, TEMP[20].xyzz, TEMP[22].xxxx
 24: DP3 TEMP[24].x, TEMP[18].xyzx, TEMP[23].xyzx
 25: MAX OUT[1].x, IMM[0].zzzz, TEMP[24].xxxx
 26: MOV OUT[1].yz, IN[2].xxyx
 27: END
                                                                                                                                                                                                            source/v64/tests/gpu/shaders/tgsi/kmscube-vs.txt                                                    0000644 0000000 0000000 00000002506 00000000000 017043  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL IN[1]
DCL IN[2]
DCL OUT[0], POSITION
DCL OUT[1].xyz, GENERIC[0]
DCL CONST[0..10]
DCL TEMP[0..25]
IMM[0] UINT32 {1073741824, 1101004800, 0, 0}
DCL TEMP[26..29]
  0: MUL TEMP[0], CONST[4], IN[0].xxxx
  1: MUL TEMP[1], CONST[5], IN[0].yyyy
  2: ADD TEMP[2], TEMP[0], TEMP[1]
  3: MUL TEMP[3], CONST[6], IN[0].zzzz
  4: ADD TEMP[4], TEMP[2], TEMP[3]
  5: MUL TEMP[5], CONST[7], IN[0].wwww
  6: ADD OUT[0], TEMP[4], TEMP[5]
  7: MUL TEMP[6], CONST[0], IN[0].xxxx
  8: MUL TEMP[7], CONST[1], IN[0].yyyy
  9: ADD TEMP[8], TEMP[6], TEMP[7]
 10: MUL TEMP[9], CONST[2], IN[0].zzzz
 11: ADD TEMP[10], TEMP[8], TEMP[9]
 12: MUL TEMP[11], CONST[3], IN[0].wwww
 13: ADD TEMP[12], TEMP[10], TEMP[11]
 14: DIV TEMP[13].xyz, TEMP[12].xyzz, TEMP[12].wwwx
 15: MUL TEMP[14].xyz, CONST[8].xyzz, IN[1].xxxx
 16: MUL TEMP[15].xyz, CONST[9].xyzz, IN[1].yyyx
 17: ADD TEMP[16].xyz, TEMP[14].xyzz, TEMP[15].xyzz
 18: MUL TEMP[17].xyz, CONST[10].xyzz, IN[1].zzzx
 19: ADD TEMP[18].xyz, TEMP[16].xyzz, TEMP[17].xyzz
 20: ADD TEMP[20].xyz, IMM[0].xxyx, -TEMP[13].xyzx
 21: DP3 TEMP[21].x, TEMP[20].xyzx, TEMP[20].xyzx
 22: RSQ TEMP[22].x, TEMP[21].xxxx
 23: MUL TEMP[23].xyz, TEMP[20].xyzz, TEMP[22].xxxx
 24: DP3 TEMP[24].x, TEMP[18].xyzx, TEMP[23].xyzx
 25: MAX TEMP[25].x, IMM[0].zzzz, TEMP[24].xxxx
 26: MUL OUT[1].xyz, TEMP[25].xxxx, IN[2].xyzz
 27: END
                                                                                                                                                                                          source/v64/tests/gpu/shaders/tgsi/simple-egl-fs.txt                                                 0000644 0000000 0000000 00000000217 00000000000 017425  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL IN[0], GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
DCL TEMP[0..3]
  0: MOV OUT[0], IN[0]
  1: END
                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/gpu/shaders/tgsi/simple-egl-vs.txt                                                 0000644 0000000 0000000 00000000627 00000000000 017452  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL IN[1]
DCL OUT[0], POSITION
DCL OUT[1], GENERIC[0]
DCL CONST[0..3]
DCL TEMP[0..5]
DCL TEMP[6..9]
  0: MUL TEMP[0], CONST[0], IN[0].xxxx
  1: MUL TEMP[1], CONST[1], IN[0].yyyy
  2: ADD TEMP[2], TEMP[0], TEMP[1]
  3: MUL TEMP[3], CONST[2], IN[0].zzzz
  4: ADD TEMP[4], TEMP[2], TEMP[3]
  5: MUL TEMP[5], CONST[3], IN[0].wwww
  6: ADD OUT[0], TEMP[4], TEMP[5]
  7: MOV OUT[1], IN[1]
  8: END
                                                                                                         source/v64/tests/gpu/shaders/tgsi/synthetic-fs.txt                                                  0000644 0000000 0000000 00000003356 00000000000 017410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
PROPERTY FS_COORD_PIXEL_CENTER INTEGER
DCL IN[0], POSITION, LINEAR
DCL IN[1].xy, GENERIC[0], PERSPECTIVE
DCL IN[2], COLOR, COLOR
DCL IN[3].x, GENERIC[1], CONSTANT
DCL SV[0], FACE
DCL OUT[0], COLOR
DCL OUT[1], POSITION
DCL SAMP[0]
DCL SAMP[1]
DCL SAMP[2]
DCL SVIEW[0], 2D, FLOAT
DCL SVIEW[1], SHADOW2D, FLOAT
DCL SVIEW[2], 2D_ARRAY, UINT
DCL CONST[0][0..3]
DCL CONST[1][0..15]
DCL TEMP[0..7]
DCL TEMP[8..11], ARRAY(1)
DCL ADDR[0]
IMM[0] UINT32 {1065353216, 0, 1056964608, 3212836864}
IMM[1] INT32 {1, 2, 3, 0}
  0: TEX TEMP[0], IN[1].xyyy, SAMP[0], 2D
  1: MOV TEMP[1].xy, IN[1].xyxx
  2: MOV TEMP[1].z, IMM[0].zzzz
  3: TEX TEMP[2].x, TEMP[1].xyzz, SAMP[1], SHADOW2D
  4: F2I TEMP[3], IN[0]
  5: TXF TEMP[4], TEMP[3], SAMP[2], 2D_ARRAY, IMM[1].xyz
  6: TXQ TEMP[5], IMM[1].wwww, SAMP[0], 2D
  7: UARL ADDR[0].x, IN[3].xxxx
  8: MOV TEMP[6], CONST[1][ADDR[0].x+2]
  9: MOV TEMP[ADDR[0].x+8](1), TEMP[6]
 10: ADD TEMP[7], TEMP[9](1), -|SV[0].xxxx|
 11: FSLT TEMP[3].x, TEMP[0].wwww, IMM[0].zzzz
 12: UIF TEMP[3].xxxx :14
 13: KILL
 14: ENDIF
 15: KILL_IF TEMP[7].xyzw
 16: LRP_SAT TEMP[0], TEMP[2].xxxx, TEMP[0], IN[2]
 17: POW TEMP[1].x, TEMP[0].xxxx, IMM[0].zzzz
 18: SLT TEMP[1].y, TEMP[0].yyyy, CONST[0][1].xxxx
 19: CMP TEMP[1].zw, -TEMP[0].zzww, IMM[0].xxxx, IMM[0].yyyy
 20: SIN TEMP[2].y, TEMP[0].xxxx
 21: COS TEMP[2].z, TEMP[0].xxxx
 22: UMSB TEMP[3].y, TEMP[4].xxxx
 23: UBFE TEMP[3].z, TEMP[4].yyyy, IMM[1].xxxx, IMM[1].yyyy
 24: IDIV TEMP[3].w, TEMP[4].zzzz, IMM[1].yyyy
 25: BGNLOOP :30
 26: USGE TEMP[3].x, TEMP[3].wwww, IMM[1].zzzz
 27: UIF TEMP[3].xxxx :29
 28: BRK
 29: ENDIF
 30: UADD TEMP[3].w, TEMP[3].wwww, IMM[1].xxxx
 31: ENDLOOP :25
 32: ADD OUT[0], TEMP[0], TEMP[1]
 33: MOV OUT[1].z, TEMP[1].xxxx
 34: END
                                                                                                                                                                                                                                                                                  source/v64/tests/gpu/shaders/tgsi/weston-solid-fs.txt                                               0000644 0000000 0000000 00000000216 00000000000 020015  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL OUT[0], COLOR
DCL CONST[0..1]
DCL TEMP[0..3]
  0: MUL OUT[0], CONST[1], CONST[0].xxxx
  1: END
                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/gpu/shaders/tgsi/weston-solid-vs.txt                                               0000644 0000000 0000000 00000000357 00000000000 020043  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL OUT[0], POSITION
DCL CONST[0..3]
DCL TEMP[0..2]
DCL TEMP[3..6]
  0: MUL TEMP[0], CONST[0], IN[0].xxxx
  1: MUL TEMP[1], CONST[1], IN[0].yyyy
  2: ADD TEMP[2], TEMP[0], CONST[3]
  3: ADD OUT[0], TEMP[2], TEMP[1]
  4: END
                                                                                                                                                                                                                                                                                 source/v64/tests/gpu/shaders/tgsi/weston-texture-fs.txt                                             0000644 0000000 0000000 00000000564 00000000000 020411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL IN[0].xy, GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
DCL SAMP[0]
DCL SVIEW[0], 2D, FLOAT
DCL CONST[0]
DCL TEMP[0..1]
IMM[0] UINT32 {1065353216, 0, 0, 0}
DCL TEMP[2..5]
  0: TEX TEMP[1], IN[0].xyyy, SAMP[0], 2D
  1: MOV TEMP[0].xyz, TEMP[1].xyzx
  2: MOV TEMP[0].w, IMM[0].xxxx
  3: MUL OUT[0], TEMP[0], CONST[0].xxxx
  4: END
                                                                                                                                            source/v64/tests/gpu/shaders/tgsi/weston-texture-vs.txt                                             0000644 0000000 0000000 00000000707 00000000000 020430  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       VERT
DCL IN[0]
DCL OUT[0], POSITION
DCL OUT[1].xy, GENERIC[0]
DCL CONST[0..7]
DCL TEMP[0..5]
DCL TEMP[6..9]
  0: MUL TEMP[0], CONST[0], IN[0].xxxx
  1: MUL TEMP[1], CONST[1], IN[0].yyyy
  2: ADD TEMP[2], TEMP[0], CONST[3]
  3: ADD OUT[0], TEMP[2], TEMP[1]
  4: MUL TEMP[3].xy, CONST[4].xyyy, IN[0].xxxx
  5: MUL TEMP[4].xy, CONST[5].xyyy, IN[0].yyyy
  6: ADD TEMP[5].xy, TEMP[3].xyxx, CONST[7].xyyy
  7: ADD OUT[1].xy, TEMP[5].xyxx, TEMP[4].xyxx
  8: END
                                                         source/v64/tests/gpu/shaders/tgsi/weston-texture-x-fs.txt                                           0000644 0000000 0000000 00000000412 00000000000 020646  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       FRAG
PROPERTY FS_COLOR0_WRITES_ALL_CBUFS 1
DCL IN[0].xy, GENERIC[0], PERSPECTIVE
DCL OUT[0], COLOR
DCL SAMP[0]
DCL SVIEW[0], 2D, FLOAT
DCL CONST[0]
DCL TEMP[0]
DCL TEMP[1..4]
  0: TEX TEMP[0], IN[0].xyyy, SAMP[0], 2D
  1: MUL OUT[0], TEMP[0], CONST[0].xxxx
  2: END
                                                                                                                                                                                                                                                      source/v64/tests/image/browser_runner.mjs                                                           0000755 0000000 0000000 00000020211 00000000000 015676  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Disk images in headless Chrome (docs/disk-image-formats-plan.md, "运行入口"):
// tests/image/disk_image_browser_test.html, on the page and in the CPU
// Worker, with the images read over HTTP Range requests from this server
// (status 206, Content-Range, a strong ETag, as a static server answers).
// Needs build/libv86.mjs, build/cpu-worker.js, build/v86.wasm and Chrome
// (CHROME). The server counts the requests and bytes of each image.
//   node tests/image/browser_runner.mjs [worker=0|1]

import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, execFileSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { build_qcow2 } from "./tiny_qcow2.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const out = path.join(root, "build/disk-image-browser");
fs.mkdirSync(out, { recursive: true });

// MS-DOS 6.22 in a QCOW2 image (its non-zero clusters), and a file that is
// not one
const raw = fs.readFileSync(path.join(root, "images/msdos622.img"));
const data = [];
for(let offset = 0; offset < raw.length; offset += 65536)
{
    const cluster = raw.subarray(offset, offset + 65536);
    if(cluster.some(b => b)) data.push([offset, new Uint8Array(cluster)]);
}
fs.writeFileSync(path.join(out, "msdos622.qcow2"), build_qcow2({ size: raw.length, data }));
fs.writeFileSync(path.join(out, "not-qcow2.qcow2"), new Uint8Array(65536));
// with the samples of tests/image/samples.mjs (qemu-img): hdb, a compressed
// child (deflate) on a parent with Zstandard clusters
const samples = path.join(root, "build/disk-image-samples");
const params = [];
if(fs.existsSync(path.join(samples, "child-zlib.qcow2")))
{
    for(const name of ["child-zlib.qcow2", "v3-zstd.qcow2"]) fs.copyFileSync(path.join(samples, name), path.join(out, name));
    params.push("child_sha256=" + create_hash("sha256").update(fs.readFileSync(path.join(samples, "child.raw"))).digest("hex"));
}
else
{
    console.log("(no samples in build/disk-image-samples: run tests/image/samples.mjs for the hdb test)");
}
// an OVA of tests/image/vmdk.mjs: its disk, a streamOptimized VMDK of the
// samples' base
if(fs.existsSync(path.join(samples, "dos-ustar.ova")))
{
    fs.copyFileSync(path.join(samples, "dos-ustar.ova"), path.join(out, "dos.ova"));
    params.push("base_sha256=" + create_hash("sha256").update(fs.readFileSync(path.join(samples, "base.raw"))).digest("hex"));
}
else
{
    console.log("(no OVA in build/disk-image-samples: run tests/image/vmdk.mjs for the OVA test)");
}

const stats = new Map();
const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-image-browser-"));
let browser, timeout;

const QEMU_IMG = process.env.QEMU_IMG || (fs.existsSync("/opt/homebrew/bin/qemu-img") ? "/opt/homebrew/bin/qemu-img" : "qemu-img");
const received = [];

const server = http.createServer((req, res) =>
{
    if(req.method === "POST" && req.url.startsWith("/__test_file?"))
    {
        // a file the page made (an exported image)
        const name = path.basename(new URL(req.url, "http://localhost").searchParams.get("name") || "file");
        const chunks = [];
        req.on("data", d => chunks.push(d));
        req.on("end", () =>
        {
            fs.writeFileSync(path.join(out, name), Buffer.concat(chunks));
            received.push(name);
            res.end("OK");
        });
        return;
    }
    if(req.method === "POST" && req.url === "/__test_result")
    {
        let body = "";
        req.on("data", d => { body += d; });
        req.on("end", () =>
        {
            res.end("OK");
            const result = JSON.parse(body);
            console.log(result.details);
            // the QCOW2 export of MS-DOS's disk: qemu-img check, and compare with msdos622.img
            for(const name of received.filter(n => n.endsWith(".qcow2")))
            {
                try
                {
                    execFileSync(QEMU_IMG, ["check", "-q", "-f", "qcow2", path.join(out, name)]);
                    execFileSync(QEMU_IMG, ["compare", "-q", "-f", "qcow2", "-F", "raw", path.join(out, name), path.join(root, "images/msdos622.img")]);
                    console.log(name + ": qemu-img check: no errors; qemu-img compare: equal to msdos622.img");
                }
                catch(error)
                {
                    console.log(name + ": FAIL " + error.message);
                    result.status = "FAIL";
                }
            }
            for(const [name, s] of stats) console.log("served " + name + ": " + s.requests + " requests, " + s.bytes + " bytes of " + s.size);
            finish(result.status === "PASS" ? 0 : 1);
        });
        return;
    }
    const pathname = decodeURIComponent(new URL(req.url, "http://localhost").pathname);
    const file = path.resolve(root, "." + pathname);
    if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
    let stat;
    try { stat = fs.statSync(file); }
    catch(e) { res.writeHead(404).end(); return; }
    const type = file.endsWith(".wasm") ? "application/wasm" : /\.(js|mjs)$/.test(file) ? "text/javascript" :
        file.endsWith(".html") ? "text/html" : "application/octet-stream";
    const etag = "\"" + stat.size + "-" + Math.floor(stat.mtimeMs) + "\"";
    const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers["range"] || "");
    if(range && file.startsWith(out))
    {
        const start = +range[1], end = Math.min(+range[2], stat.size - 1);
        const name = path.basename(file);
        const s = stats.get(name) || { requests: 0, bytes: 0, size: stat.size };
        s.requests++;
        s.bytes += end - start + 1;
        stats.set(name, s);
        const fd = fs.openSync(file, "r");
        const buffer = Buffer.alloc(end - start + 1);
        fs.readSync(fd, buffer, 0, buffer.length, start);
        fs.closeSync(fd);
        res.writeHead(206, { "Content-Type": type, "Content-Range": "bytes " + start + "-" + end + "/" + stat.size,
            "Content-Length": buffer.length, "ETag": etag, "Accept-Ranges": "bytes" });
        res.end(buffer);
        return;
    }
    let body = fs.readFileSync(file);
    if(file.endsWith(".html"))
    {
        body = Buffer.concat([body, Buffer.from(`<script>
            const reporter = new MutationObserver(() => {
                const text = document.getElementById("result")?.textContent || "";
                if(!/^(PASS|FAIL)\\b/.test(text)) return;
                reporter.disconnect();
                fetch("/__test_result", { method: "POST", body: JSON.stringify({ status: text.startsWith("PASS") ? "PASS" : "FAIL", details: text }) });
            });
            reporter.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
        </script>`)]);
    }
    res.writeHead(200, { "Content-Type": type, "ETag": etag, "Accept-Ranges": "bytes" });
    res.end(body);
});

function finish(code)
{
    clearTimeout(timeout);
    server.close();
    process.exitCode = code;
    const remove = () => { try { fs.rmSync(profile, { recursive: true, force: true }); } catch(e) {} };
    if(browser && browser.exitCode === null)
    {
        browser.on("exit", remove);
        browser.kill();
    }
    else remove();
}

server.listen(0, "127.0.0.1", () =>
{
    const query = process.argv.slice(2).concat(params, ["raw_sha256=" + create_hash("sha256").update(raw).digest("hex")]).join("&");
    const url = "http://127.0.0.1:" + server.address().port + "/tests/image/disk_image_browser_test.html" + (query ? "?" + query : "");
    console.log(url);
    browser = spawn(process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
        "--user-data-dir=" + profile, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", d => { stderr = (stderr + d).slice(-4000); });
    browser.on("error", error => { console.error(error); finish(1); });
    timeout = setTimeout(() =>
    {
        console.error("FAIL: timed out\n" + stderr);
        finish(1);
    }, +process.env.TIMEOUT_MS || 300000);
});
                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/image/disk_image.mjs                                                               0000755 0000000 0000000 00000052316 00000000000 014731  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The common parts of disk images (docs/disk-image-formats-plan.md P0): the
// guest's writes over the image (write then read, part of a cluster, across
// clusters, a read that began before a write, the memory budget), snapshots
// of the changes with the image's identity, cancellation and shared reads of
// the read cache, errors that end the request, and the checks of every HTTP
// response (status, Content-Range, length, ETag) with a transport that
// answers as a server would.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createHash as create_hash } from "node:crypto";
import { make_samples, SAMPLES_DIR } from "./samples.mjs";
import { create_disk_image, check_image_options } from "../../src/image/factory.js";
import { URLSource, PartsSource, CachedSource, MemorySource, DiskImageError } from "../../src/image/source.js";
import { DiskImage, ImageReader, EXTENT_DATA } from "../../src/image/disk_image.js";
import { WriteOverlay } from "../../src/image/overlay.js";

process.on("unhandledRejection", exn => { throw exn; });

const manifest = make_samples();
const file = name => path.join(SAMPLES_DIR, name);
const base = fs.readFileSync(file("base.raw"));

const get = (disk, offset, length, options) => new Promise((resolve, reject) =>
    disk.get(offset, length, (data, error) => error ? reject(error) : resolve(data), options));
const set = (disk, offset, data) => new Promise((resolve, reject) =>
    disk.set(offset, data, error => error ? reject(error) : resolve()));
const equal_bytes = (actual, expected, what) => assert.ok(Buffer.compare(Buffer.from(actual), Buffer.from(expected)) === 0, what);

async function open_disk(name, extra = {}, settings = {})
{
    const disk = create_disk_image("hda", { url: file(name), async: true, format: "qcow2", ...extra }, settings);
    await disk.load();
    return disk;
}

// writes over the image
{
    const disk = await open_disk("v3.qcow2");
    assert.equal(disk.byteLength, base.length, "the guest sees the virtual size");
    const data = new Uint8Array(3 * 65536 + 1024).map((_, i) => i * 13 + 7);
    // across clusters, starting in the middle of one
    await set(disk, 65536 - 512, data);
    const expected = new Uint8Array(base.subarray(0, 5 * 65536));
    expected.set(data, 65536 - 512);
    equal_bytes(await get(disk, 0, 5 * 65536), expected, "written over the image, across clusters");
    // part of a block of 256: the read of a sector around it
    await set(disk, 4 * 65536 + 768, new Uint8Array(256).fill(0xAB));
    expected.fill(0xAB, 4 * 65536 + 768, 4 * 65536 + 1024);
    equal_bytes(await get(disk, 4 * 65536, 65536), expected.subarray(4 * 65536), "a write of part of a cluster");
    // covered by the writes: from memory, synchronously
    let sync = false;
    disk.get(65536, 512, () => { sync = true; });
    assert.ok(sync, "a read of written blocks completes at once");
    // get_from_cache: written blocks, and blocks read with get_and_cache
    equal_bytes(disk.get_from_cache(65536, 512), data.subarray(512, 1024), "get_from_cache: written");
    assert.equal(disk.get_from_cache(10 * 65536, 512), undefined, "get_from_cache: not read");
    await new Promise(resolve => disk.get_and_cache(10 * 65536, 512, resolve));
    equal_bytes(disk.get_from_cache(10 * 65536, 512), base.subarray(10 * 65536, 10 * 65536 + 512), "get_from_cache: read before");
    // the image itself is not written
    assert.equal(create_hash("sha256").update(fs.readFileSync(file("v3.qcow2"))).digest("hex"), manifest.samples["v3.qcow2"].sha256);
    console.log("ok - writes over the image: across clusters, part of a cluster, from the overlay, get_from_cache");
}

// the other sources: a whole download (url without async), a file read in
// ranges given its size, the length checked against it
{
    const whole = await open_disk("v3.qcow2", { async: false });
    assert.equal(whole.reader.source.constructor.name, "MemorySource", "downloaded whole");
    equal_bytes(await get(whole, 20 << 20, 1 << 20), base.subarray(20 << 20, 21 << 20), "a whole download");
    const sized = await open_disk("v3.qcow2", { size: manifest.samples["v3.qcow2"].length });
    equal_bytes(await get(sized, 0, 65536), base.subarray(0, 65536), "the size given");
    await assert.rejects(open_disk("v3.qcow2", { size: 12345 }), /the file has \d+ bytes, its size is given as 12345/);
    console.log("ok - sources: a whole download, a file read in ranges with its size; a wrong size refused");
}

// a read that began before a write returns the write's data, and the read
// cache does not keep data older than the write
{
    let release;
    const gate = new Promise(resolve => { release = resolve; });
    const disk = create_disk_image("hda", { url: file("v3.qcow2"), async: true, format: "qcow2" }, {
        open_source: async (name, descriptor) =>
        {
            const inner = new URLSource(descriptor.url, undefined, name);
            // reads that wait for the gate
            const slow = {
                name, sync: false,
                get byteLength() { return inner.byteLength; },
                open: callback => inner.open(callback),
                read: (offset, length, callback, signal) => gate.then(() => inner.read(offset, length, callback, signal)),
            };
            const cached = new CachedSource(slow);
            await new Promise((resolve, reject) => cached.open(e => e ? reject(e) : resolve()));
            // (open reads through the gate too: released below)
            return cached;
        },
    });
    const loading = disk.load();
    release();
    await loading;
    let release2;
    const gate2 = new Promise(resolve => { release2 = resolve; });
    const source = disk.reader.source;
    const inner_read = source.inner.read;
    source.inner.read = (offset, length, callback, signal) => gate2.then(() => inner_read(offset, length, callback, signal));
    const reading = get(disk, 20 * 65536, 65536);
    const written = new Uint8Array(512).fill(0x42);
    await set(disk, 20 * 65536 + 4096, written);
    release2();
    const result = await reading;
    const expected = new Uint8Array(base.subarray(20 * 65536, 21 * 65536));
    expected.set(written, 4096);
    equal_bytes(result, expected, "the read sees the later write");
    equal_bytes(await get(disk, 20 * 65536, 65536), expected, "and so does the next read");
    console.log("ok - a read that began before a write: the write wins, now and later");
}

// the memory budget: a write beyond it fails as a whole
{
    const disk = await open_disk("v3.qcow2", { overlay_limit: 65536 });
    await set(disk, 0, new Uint8Array(65536).fill(1));
    await set(disk, 0, new Uint8Array(4096).fill(2));
    await assert.rejects(set(disk, 65536, new Uint8Array(512).fill(3)), /memory budget/);
    equal_bytes(await get(disk, 65536, 512), base.subarray(65536, 65536 + 512), "the failed write left nothing");
    const overlay = new WriteOverlay(1 << 20, 1024);
    assert.ok(overlay.write(0, new Uint8Array(2048)) instanceof DiskImageError);
    assert.equal(overlay.size(), 0);
    console.log("ok - the memory budget: writes past it fail, nothing of them is written");
}

// snapshots: the changes with the image's identity
{
    const disk = await open_disk("v3.qcow2");
    const data = new Uint8Array(70000 * 256).map((_, i) => i * 7);
    await set(disk, 512, data.subarray(0, 512));
    await set(disk, 30 * 65536, data);
    const state = disk.get_state();
    assert.equal(state[0], "v86-disk-image");
    const again = await open_disk("v3.qcow2");
    again.set_state(state);
    equal_bytes(await get(again, 0, 1024), Buffer.concat([base.subarray(0, 512), data.subarray(0, 512)]), "restored: a sector");
    equal_bytes(await get(again, 30 * 65536, data.length), data, "restored: 17 MiB in two chunks");
    // the same disk from memory: the same image
    const from_memory = create_disk_image("hda", { buffer: new Uint8Array(fs.readFileSync(file("v3.qcow2"))).buffer, format: "qcow2" }, {});
    await from_memory.load();
    from_memory.check_state(state);
    // another image of the same disk (version 2), an image_id, RAW state
    const other = await open_disk("v2.qcow2");
    assert.throws(() => other.set_state(state), /another image/);
    const with_id = await open_disk("v3.qcow2", { image_id: "release-2" });
    assert.throws(() => with_id.check_state(state), /image_id "" in the snapshot, "release-2" here/);
    assert.throws(() => again.check_state([null, new Float64Array(0), []]), /is a RAW image/);
    assert.throws(() => again.check_state(null), /has no disk hda/);
    const bad = state.slice();
    bad[3] = new Float64Array([1e15]);
    bad[4] = [new Uint8Array(256)];
    assert.throws(() => again.check_state(bad), /block numbers/);
    // a child with its parent: the parent is part of the identity
    const child = await open_disk("child.qcow2", { backing: { url: file("parent.qcow2") } });
    await set(child, 0, new Uint8Array(512).fill(9));
    const child_state = child.get_state();
    (await open_disk("child.qcow2", { backing: { url: file("v3.qcow2") } })).check_state(child_state);
    const other_parent = await open_disk("child.qcow2", { backing: { url: file("v3-512.qcow2") } });
    assert.throws(() => other_parent.check_state(child_state), /another image \(parent: /);
    console.log("ok - snapshots: restored onto the same image only (file or memory), refused for another; the parent too");
}

// cancellation: a cancelled read never calls back; one shared with another
// read goes on for it; a request no read waits for is ended
{
    const requests = [];
    const inner = {
        name: "test", byteLength: 1 << 20, sync: false,
        open(callback) { callback(); },
        read(offset, length, callback, signal)
        {
            const request = { offset, length, callback, signal, aborted: false };
            signal.addEventListener("abort", () => { request.aborted = true; });
            requests.push(request);
        },
    };
    const cache = new CachedSource(inner, 65536);
    // (each byte: the number of its 64 KiB window)
    const answer = request => request.callback(new Uint8Array(request.length).map((_, i) => request.offset + i >> 16));
    const one = new AbortController(), two = new AbortController();
    const calls = [];
    cache.read(0, 512, data => calls.push(["one", data[0]]), one.signal);
    cache.read(256, 512, data => calls.push(["two", data[0]]), two.signal);
    assert.equal(requests.length, 1, "the second read waits for the first one's request");
    one.abort();
    assert.equal(requests[0].aborted, false, "still needed by the second read");
    answer(requests[0]);
    assert.deepEqual(calls, [["two", 0]], "only the read not cancelled calls back");
    // adjacent windows in one request, cached ones not again
    cache.read(65536, 3 * 65536, data => calls.push(["three", data.length]));
    assert.equal(requests.length, 2);
    assert.deepEqual([requests[1].offset, requests[1].length], [65536, 3 * 65536], "one request for adjacent windows");
    answer(requests[1]);
    cache.read(0, 4 * 65536, data => calls.push(["four", data[3 * 65536]]));
    assert.equal(requests.length, 2, "all cached");
    // a request only cancelled reads wait for is ended
    const three = new AbortController();
    cache.read(8 * 65536, 512, () => calls.push(["never"]), three.signal);
    three.abort();
    assert.equal(requests[2].aborted, true, "no read waits for it: ended");
    answer(requests[2]);
    // an error ends every read waiting
    cache.read(9 * 65536, 512, (data, error) => calls.push(["error", error.message]));
    requests[3].callback(undefined, new DiskImageError("broken"));
    assert.deepEqual(calls.slice(1), [["three", 3 * 65536], ["four", 3], ["error", "broken"]]);
    console.log("ok - the read cache: cancelled reads, shared requests, adjacent windows, errors");
}

// a fake HTTP server: the checks of every response
function server(bytes, behave = {})
{
    const log = [];
    const transport = (url, start, length, callback, signal) =>
    {
        log.push([start, length]);
        const n = log.length;
        const respond = () =>
        {
            if(signal && signal.aborted) return;
            const etag = typeof behave.etag === "function" ? behave.etag(n) : "\"v1\"";
            if(behave.fail && behave.fail(n))
            {
                callback(undefined, behave.fail(n) === "network" ? undefined : { status: 503 },
                    new DiskImageError("network error", "io"));
                return;
            }
            if(length === undefined)
            {
                callback(bytes, { status: 200, etag });
                return;
            }
            const end = Math.min(bytes.length, start + length);
            let data = bytes.subarray(start, end);
            if(behave.short) data = data.subarray(0, data.length - 1);
            callback(data, {
                status: behave.status || 206,
                content_range: behave.content_range ? behave.content_range(start, end) : "bytes " + start + "-" + (end - 1) + "/" + bytes.length,
                content_encoding: behave.encoding || null,
                etag, last_modified: null,
            });
        };
        setTimeout(respond, 1);
    };
    return { transport, log };
}

{
    const bytes = new Uint8Array(1 << 20).map((_, i) => i);
    const open = async (behave, size) =>
    {
        const { transport, log } = server(bytes, behave);
        const source = new URLSource("http://test/disk.img", size, "hda", transport, [1, 1, 1]);
        await new Promise((resolve, reject) => source.open(e => e ? reject(e) : resolve()));
        return { source, log };
    };
    const read = (source, offset, length) => new Promise((resolve, reject) =>
        source.read(offset, length, (data, error) => error ? reject(error) : resolve(data)));

    const { source, log } = await open({});
    assert.equal(source.byteLength, bytes.length, "the length from Content-Range of a read of byte 0");
    assert.deepEqual(log[0], [0, 1]);
    equal_bytes(await read(source, 1000, 5000), bytes.subarray(1000, 6000), "a read");

    await assert.rejects(open({ status: 200 }), /status 200/);
    const sized = await open({}, 12345);
    await assert.rejects(read(sized.source, 0, 512), /the server reports 1048576 bytes, the size is given as 12345/);
    const wrong_range = await open({ content_range: (s, e) => s === 0 ? "bytes 0-0/" + bytes.length : "bytes 0-99/" + bytes.length });
    await assert.rejects(read(wrong_range.source, 4096, 512), /is for bytes 0-99/);
    const short = await open({ short: true }, bytes.length);
    await assert.rejects(read(short.source, 4096, 512), /has 511 bytes/);
    const encoded = await open({ encoding: "gzip" }, bytes.length);
    await assert.rejects(read(encoded.source, 0, 512), /Content-Encoding gzip/);
    // the file changes on the server: no more reads from it
    const changing = await open({ etag: n => n < 3 ? "\"v1\"" : "\"v2\"" });
    await read(changing.source, 0, 512);
    await assert.rejects(read(changing.source, 512, 512), /changed on the server/);
    await assert.rejects(read(changing.source, 0, 512), /changed on the server/);
    assert.equal(changing.log.length, 3, "no request after the change");
    // 5xx and network errors are tried again, a bounded number of times
    const flaky = await open({ fail: n => n === 2 || n === 3 ? "network" : false });
    equal_bytes(await read(flaky.source, 0, 512), bytes.subarray(0, 512), "after two failed tries");
    assert.equal(flaky.source.stats.retries, 2);
    const down = await open({ fail: n => n > 1 ? "network" : false });
    await assert.rejects(read(down.source, 0, 512), /network error/);
    assert.equal(down.log.length, 1 + 4, "the first try and three more");
    console.log("ok - HTTP: status, Content-Range, length, encoding, a file that changes, retries");

    // split files
    const parts = server(bytes, {});
    const split = new PartsSource("http://test/disk.img", bytes.length, 65536, false, undefined, "hda",
        (url, start, length, callback, signal) =>
        {
            const match = /disk-(\d+)-(\d+)\.img$/.exec(url);
            assert.ok(match, url);
            parts.transport(url, +match[1], undefined, (data, info, error) =>
                callback(data && data.subarray(+match[1], +match[2]), info, error), signal);
        });
    await new Promise(resolve => split.open(resolve));
    equal_bytes(await read(split, 65536 - 100, 200), bytes.subarray(65536 - 100, 65436 + 200), "across two parts");
    console.log("ok - split files: a read across parts");
}

// a source that fails: the device's read ends with the error
{
    const reader = new ImageReader(new MemorySource(new Uint8Array(4096), "x"), "x");
    reader.format = "test";
    reader.virtual_size = 1 << 20;
    reader.map = (offset, length, callback) => callback([{ type: EXTENT_DATA, length, host_offset: 1 << 30 }]);
    const failing = new DiskImage("hda", async () => reader);
    await failing.load();
    // (a data extent past the end of the file reads as zeros)
    equal_bytes(await get(failing, 0, 512), new Uint8Array(512), "past the end of the file");
    reader.source = { byteLength: 2 ** 31, read: (o, l, callback) => callback(undefined, new DiskImageError("gone")) };
    const errors = [];
    const original = console.error;
    console.error = message => errors.push(message);
    await assert.rejects(get(failing, 0, 512), /gone/);
    await assert.rejects(get(failing, 512, 512), /gone/);
    console.error = original;
    assert.deepEqual(errors, ["Disk hda: gone"], "told once");
    const broken = new DiskImage("hda", async () => { throw new DiskImageError("cannot open"); });
    let told;
    broken.onerror = error => { told = error; };
    await assert.rejects(broken.load(), /cannot open/);
    assert.match(told.message, /cannot open/);
    console.log("ok - errors: a read fails with the source's error, a disk that cannot be opened fails load");
}

// export (P2): RAW of the whole disk, the image's data with the guest's
// writes; progress, backpressure, cancellation
{
    const { export_raw } = await import("../../src/image/export.js");
    const disk = await open_disk("v3-zlib.qcow2", {}, { zstd_decompress: undefined });
    const writes = [[0, 4096], [10 * 65536 + 512, 70000 * 256], [base.length - 1024, 1024]];
    const expected = new Uint8Array(base);
    for(const [offset, length] of writes)
    {
        const data = new Uint8Array(length).map((_, i) => i * 3 + offset);
        await set(disk, offset, data);
        expected.set(data, offset);
    }
    const chunks = [], progress = [];
    let writing = 0;
    const total = await export_raw(disk, async chunk =>
    {
        assert.equal(writing, 0, "one chunk at a time");
        writing++;
        await new Promise(resolve => setTimeout(resolve, 1));
        chunks.push(chunk);
        writing--;
    }, { progress: p => progress.push(p.loaded) });
    assert.equal(total, base.length);
    equal_bytes(Buffer.concat(chunks), expected, "the export: the image with the writes");
    assert.equal(progress[0], 0);
    assert.equal(progress[progress.length - 1], base.length);
    assert.ok(chunks.every(c => c.length <= 1024 * 1024), "chunks of at most 1 MiB");
    const controller = new AbortController();
    let count = 0;
    await assert.rejects(export_raw(disk, () => { if(++count === 3) controller.abort(); }, { signal: controller.signal }), /cancelled at 3145728/);
    console.log("ok - export: RAW of the disk with the guest's writes, in order, backpressure, progress, cancellation");
}

// the options of a descriptor
{
    assert.equal(check_image_options("hda", { url: "x" }, true), undefined, "no format: RAW as before");
    assert.equal(check_image_options("hda", { url: "x", format: "raw" }, true), undefined);
    assert.equal(check_image_options("hda", { url: "x", format: "qcow2" }, true), "qcow2");
    assert.equal(check_image_options("hda", { url: "x", format: "auto", disk_option: "read_only" }, true), "auto");
    assert.throws(() => check_image_options("hda", { url: "x", format: "qcow3" }, true), /unknown format "qcow3"/);
    assert.equal(check_image_options("hda", { url: "x", format: "vhd" }, true), "vhd");
    for(const format of ["vdi", "vmdk", "vhdx", "vpc"]) assert.equal(check_image_options("hda", { url: "x", format }, true), format);
    assert.throws(() => check_image_options("hda", { url: "x", format: "qed" }, true), /unknown format "qed"/);
    assert.throws(() => check_image_options("hda", { url: "x", format: "vmdk", files: { "a.vmdk": "a.vmdk" } }, true), /files must map/);
    assert.throws(() => check_image_options("hda", { url: "x", format: "vmdk", archive_member: 7 }, true), /archive_member/);
    assert.throws(() => check_image_options("cdrom", { url: "x", format: "qcow2" }, false), /for hard disks/);
    // (read_write: written back, docs/disk-persistence-plan.md; whether the source can be is checked when the machine starts)
    assert.equal(check_image_options("hda", { url: "x", disk_option: "read_write" }, true), undefined);
    assert.throws(() => check_image_options("hda", { url: "x", disk_option: "rw" }, true), /not one of/);
    assert.throws(() => check_image_options("bios", { url: "x", disk_option: "read_only" }, false), /for disks/);
    assert.throws(() => check_image_options("hda", { get() {}, set() {}, load() {}, format: "qcow2" }, true), /descriptors/);
    console.log("ok - options: format and disk_option checked");
}

console.log("disk image tests passed");
                                                                                                                                                                                                                                                                                                                  source/v64/tests/image/disk_image_browser_test.html                                                 0000644 0000000 0000000 00000023707 00000000000 017705  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>Disk images in the browser</title>
<div id="screen"><div style="white-space: pre; font: 14px monospace; line-height: 14px"></div><canvas style="display: none"></canvas></div>
<pre id="result">RUNNING</pre>
<script type="module">
// docs/disk-image-formats-plan.md ("运行入口"): a QCOW2 disk read with HTTP
// Range requests, on the page (worker=0) or in the CPU Worker (worker=1):
// MS-DOS boots from it, writes a file, the file is there after a snapshot
// restored; an image that is not of its format fails the start
// (emulator-error), in the Worker too; disks of 4096-byte sectors. Run by
// tests/image/browser_runner.mjs.
import { V86 } from "../../build/libv86.mjs";
const params = new URLSearchParams(location.search);
const worker = params.get("worker") === "1";
const log = [];
const result = document.getElementById("result");
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const config = (hda, hdb) => ({
    wasm_path: "../../build/v86.wasm", cpu_worker: worker, cpu_worker_url: "../../build/cpu-worker.js",
    bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
    graphics_adapter: "bochs_vga", graphics_adapter_path: "../../build/v86-bochs-vga.js",
    hda, hdb, memory_size: 32 << 20, autostart: true, disable_speaker: true,
    screen: { container: document.getElementById("screen") },
});
const screen = vm => (vm.screen_adapter ? vm.screen_adapter.get_text_screen() : []).map(l => l.replace(/\x00/g, " "));
async function until(condition, what, timeout = 120000)
{
    const end = performance.now() + timeout;
    while(!condition())
    {
        if(performance.now() > end) throw new Error("timeout: " + what + "\n" + screen(vm_current).join("\n"));
        await sleep(100);
    }
}
let vm_current;
async function dos(vm, command)
{
    await vm.keyboard_send_text("cls\n", 20);
    await until(() => { const l = screen(vm).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await vm.keyboard_send_text(command + "\n", 20);
    await until(() => screen(vm).filter(x => x.startsWith("C:\\>")).length >= 2, command);
    return screen(vm).join("\n");
}
try
{
    // hdb (with the samples): a compressed child, its parent given as backing
    const hdb = params.get("child_sha256") ? { url: "../../build/disk-image-browser/child-zlib.qcow2", async: true, format: "qcow2",
        backing: { url: "../../build/disk-image-browser/v3-zstd.qcow2", async: true } } : undefined;
    const vm = vm_current = new V86(config({ url: "../../build/disk-image-browser/msdos622.qcow2", async: true, format: "qcow2" }, hdb));
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    if(worker && vm.v86) throw new Error("the machine is on the page, not in the Worker");
    // (the prompt alone on its line for a second: AUTOEXEC.BAT is done)
    let stable = 0;
    await until(() => { const l = screen(vm).filter(x => x.trim()); stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0; return stable >= 10; }, "C:\\>");
    log.push("C:\\> from the QCOW2 disk over HTTP Range (" + (worker ? "CPU Worker" : "page") + ")");
    // export (P2): before the guest writes, MS-DOS's disk as it is
    const exported = async () =>
    {
        const parts = [];
        let progress = 0;
        const size = await vm.export_disk_image("hda", { write: async chunk => { parts.push(chunk); await sleep(0); },
            progress: p => { progress = p.loaded / p.total; } });
        const blob = new Blob(parts);
        if(blob.size !== size || progress !== 1) throw new Error("export: " + blob.size + " bytes, " + size + " reported, progress " + progress);
        return new Uint8Array(await blob.arrayBuffer());
    };
    const hex = async bytes => Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), b => b.toString(16).padStart(2, "0")).join("");
    const info = await vm.disk_image_info("hda");
    const first = await exported();
    if(await hex(first) !== params.get("raw_sha256") && info.written === 0) throw new Error("the export is not msdos622.img");
    log.push("export_disk_image: " + first.length + " bytes (" + info.format + ", " + info.written + " bytes written before)");
    // the same image as a File (a disk the user picks): read with
    // FileReaderSync in the Worker, FileReader on the page
    {
        const blob = await (await fetch("../../build/disk-image-browser/msdos622.qcow2")).blob();
        const file_vm = vm_current = new V86({ ...config({ buffer: new File([blob], "msdos622.qcow2"), format: "auto" }), autostart: false });
        await new Promise((resolve, reject) => { file_vm.add_listener("emulator-loaded", resolve); file_vm.add_listener("emulator-error", reject); });
        const parts = [];
        await file_vm.export_disk_image("hda", { write: chunk => { parts.push(chunk); } });
        if(await hex(await new Blob(parts).arrayBuffer()) !== params.get("raw_sha256")) throw new Error("the File's disk is not msdos622.img");
        await file_vm.destroy();
        vm_current = vm;
        log.push("a File (format auto): the disk is msdos622.img");
    }
    // a new QCOW2 image of it: checked and compared by the runner (qemu-img)
    {
        const parts = [];
        const size = await vm.export_disk_image("hda", { format: "qcow2", write: chunk => { parts.push(chunk); } });
        const response = await fetch("/__test_file?name=hda-" + (worker ? "worker" : "page") + ".qcow2", { method: "POST", body: new Blob(parts) });
        if(!response.ok) throw new Error("the runner did not take the QCOW2 export");
        log.push("export_disk_image (qcow2): " + size + " bytes, sent to the runner");
    }
    if(hdb)
    {
        const parts = [];
        await vm.export_disk_image("hdb", { write: chunk => { parts.push(chunk); } });
        if(await hex(await new Blob(parts).arrayBuffer()) !== params.get("child_sha256")) throw new Error("hdb: not the RAW of qemu-img");
        log.push("hdb: a compressed QCOW2 child on a parent with Zstandard clusters, as qemu-img reads it");
    }
    await dos(vm, "echo BROWSER > C:\\BROWSER.TXT");
    if(!/^BROWSER\s*$/m.test(await dos(vm, "type C:\\BROWSER.TXT"))) throw new Error("the file written is not there");
    log.push("the guest wrote a file");
    const second = await exported();
    const text = new TextDecoder("latin1").decode(second);
    if(!text.includes("BROWSER \r\n")) throw new Error("the export has not the file's data");
    log.push("the export after the write has the file");
    const state = await vm.save_state();
    await dos(vm, "del C:\\BROWSER.TXT");
    await vm.restore_state(state);
    if(!/^BROWSER\s*$/m.test(await dos(vm, "type C:\\BROWSER.TXT"))) throw new Error("the file is not there after the restore");
    log.push("a snapshot restored has the file");
    await vm.destroy();

    const bad = vm_current = new V86(config({ url: "../../build/disk-image-browser/not-qcow2.qcow2", async: true, format: "qcow2" }));
    const error = await Promise.race([new Promise(resolve => bad.add_listener("emulator-error", resolve)),
        new Promise(resolve => bad.add_listener("emulator-loaded", () => resolve(null))), sleep(30000).then(() => "timeout")]);
    if(!error || error === "timeout" || !/not a qcow2 image/.test(error.message)) throw new Error("no emulator-error for a bad image: " + (error && error.message || error));
    log.push("an image that is not of its format: emulator-error \"" + error.message + "\"");
    try { await bad.destroy(); } catch(e) {}

    // 4096-byte logical sectors (the plan's appendix): a RAW disk's
    // logical_sector_size and a VHDX image's own reach the drives (in the
    // Worker: the option crosses with the descriptor)
    {
        const { build_vhdx } = await import("./tiny_vhdx.mjs");
        const vhdx = build_vhdx({ size: 8 << 20, logical_sector_size: 4096, data: [[0, new Uint8Array(4096).fill(0x4B)]] });
        const sector_vm = vm_current = new V86({ ...config({ buffer: new ArrayBuffer(8 << 20), logical_sector_size: 4096 },
            { buffer: vhdx.image.buffer, format: "vhdx" }), autostart: false });
        await new Promise((resolve, reject) => { sector_vm.add_listener("emulator-loaded", resolve); sector_vm.add_listener("emulator-error", reject); });
        const sizes = [(await sector_vm.disk_image_info("hda")).logical_sector_size, (await sector_vm.disk_image_info("hdb")).logical_sector_size];
        if(sizes[0] !== 4096 || sizes[1] !== 4096) throw new Error("logical sectors: " + sizes.join(", "));
        await sector_vm.destroy();
        log.push("4096-byte logical sectors: a RAW disk's logical_sector_size and a VHDX image's own");
    }

    // an OVA (with the samples): V86.import_ova on the page, the disk read in
    // the archive (in the Worker: archive_member crosses with the descriptor)
    if(params.get("base_sha256"))
    {
        const imported = await V86.import_ova({ url: "../../build/disk-image-browser/dos.ova", async: true });
        if(imported.options.memory_size !== 32 << 20 || imported.disks.length !== 2) throw new Error("import_ova: " + JSON.stringify(imported.options));
        const ova_vm = vm_current = new V86({ ...config(imported.options.hda), autostart: false });
        await new Promise((resolve, reject) => { ova_vm.add_listener("emulator-loaded", resolve); ova_vm.add_listener("emulator-error", reject); });
        const parts = [];
        await ova_vm.export_disk_image("hda", { write: chunk => { parts.push(chunk); } });
        if(await hex(await new Blob(parts).arrayBuffer()) !== params.get("base_sha256")) throw new Error("the OVA's disk is not the VMDK's data");
        log.push("V86.import_ova: the disk in the archive (" + imported.files.join(", ") + "), as qemu-img reads it; " + imported.notes.length + " notes");
        await ova_vm.destroy();
    }
    result.textContent = "PASS\n" + log.join("\n");
}
catch(error)
{
    result.textContent = "FAIL " + (error && error.stack || error) + "\n" + log.join("\n");
}
</script>
                                                         source/v64/tests/image/guest.mjs                                                                    0000755 0000000 0000000 00000014710 00000000000 013760  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// A guest on each format qemu-img makes (docs/disk-image-formats-plan.md,
// "客体回归"): MS-DOS 6.22 (images/msdos622.img) converted by qemu-img, read in
// ranges from the file, boots, writes a file, finds it after a restart and
// after a snapshot restored; the file is not changed. DISK_IMAGE_GUEST
// selects formats (comma separated names below).

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { SAMPLES_DIR } from "./samples.mjs";

process.on("unhandledRejection", exn => { throw exn; });

const root = fileURLToPath(new URL("../../", import.meta.url));
const QEMU_IMG = process.env.QEMU_IMG || (fs.existsSync("/opt/homebrew/bin/qemu-img") ? "/opt/homebrew/bin/qemu-img" : "qemu-img");
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

// [name, format option, qemu-img output format, qemu-img options]
const FORMATS = [
    ["qcow2-zlib", "qcow2", "qcow2", ["-c"]],
    ["vhd-dynamic", "vhd", "vpc", []],
    ["vhd-fixed", "vhd", "vpc", ["-o", "subformat=fixed"]],
    ["vdi", "vdi", "vdi", []],
    ["vmdk-sparse", "vmdk", "vmdk", []],
    ["vhdx", "vhdx", "vhdx", []],
    ["vmdk-stream", "vmdk", "vmdk", ["-o", "subformat=streamOptimized"]],
    // (the streamOptimized VMDK in an OVA, through V86.import_ova)
    ["ova", "vmdk", "vmdk", ["-o", "subformat=streamOptimized"]],
];
const selected = process.env.DISK_IMAGE_GUEST ? process.env.DISK_IMAGE_GUEST.split(",") : FORMATS.map(f => f[0]);

const dir = path.join(SAMPLES_DIR, "guest");
fs.mkdirSync(dir, { recursive: true });
const raw = path.join(root, "images/msdos622.img");

const lines = emulator => emulator.screen_adapter ? emulator.screen_adapter.get_text_screen().map(l => l.replace(/\x00/g, " ")) : [""];
async function until(emulator, condition, what, timeout = 120000)
{
    const start = Date.now();
    while(!condition())
    {
        if(Date.now() - start > timeout)
        {
            console.error(lines(emulator).join("\n"));
            throw new Error("Timeout waiting for " + what);
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}
/** the prompt, alone on its line, for a second: AUTOEXEC.BAT is done */
async function prompt(emulator, what)
{
    let stable = 0;
    await until(emulator, () =>
    {
        const l = lines(emulator).filter(x => x.trim());
        stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0;
        return stable >= 10;
    }, what);
}
async function dos(emulator, command)
{
    await emulator.keyboard_send_text("cls\n", 20);
    await until(emulator, () => { const l = lines(emulator).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await emulator.keyboard_send_text(command + "\n", 20);
    await until(emulator, () => lines(emulator).filter(x => x.startsWith("C:\\>")).length >= 2, command);
    return lines(emulator).join("\n");
}

for(const [name, format, qemu_format, options] of FORMATS.filter(f => selected.includes(f[0])))
{
    let image = path.join(dir, "msdos622-" + name + "." + qemu_format);
    if(!fs.existsSync(image)) execFileSync(QEMU_IMG, ["convert", "-f", "raw", "-O", qemu_format, ...options, raw, image]);
    let hda = { url: image, async: true, format };
    let machine = { memory_size: 32 << 20 };
    if(name === "ova")
    {
        // an OVF descriptor (64 MiB of memory, one CPU) and the disk in a TAR archive
        fs.writeFileSync(path.join(dir, "dos.ovf"), `<?xml version="1.0"?>
<Envelope xmlns="http://schemas.dmtf.org/ovf/envelope/1" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
    xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData">
  <References><File ovf:href="msdos622-ova.vmdk" ovf:id="file1"/></References>
  <DiskSection><Disk ovf:capacity="67108864" ovf:diskId="vmdisk1" ovf:fileRef="file1"
      ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"/></DiskSection>
  <VirtualSystem ovf:id="dos"><VirtualHardwareSection>
    <Item><rasd:InstanceID>1</rasd:InstanceID><rasd:ResourceType>3</rasd:ResourceType><rasd:VirtualQuantity>1</rasd:VirtualQuantity></Item>
    <Item><rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits><rasd:InstanceID>2</rasd:InstanceID><rasd:ResourceType>4</rasd:ResourceType><rasd:VirtualQuantity>64</rasd:VirtualQuantity></Item>
  </VirtualHardwareSection></VirtualSystem>
</Envelope>
`);
        const ova = path.join(dir, "msdos622.ova");
        execFileSync("tar", ["-cf", ova, "--format", "ustar", "-C", dir, "dos.ovf", path.basename(image)]);
        image = ova;
        const imported = await V86.import_ova({ url: ova, async: true });
        assert.equal(imported.options.memory_size, 64 << 20);
        hda = imported.options.hda;
        machine = { memory_size: imported.options.memory_size, cpu_cores: imported.options.cpu_cores };
    }
    const sha256 = create_hash("sha256").update(fs.readFileSync(image)).digest("hex");
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
        hda, ...machine,
        autostart: true, log_level: 0,
    });
    emulator.add_listener("emulator-error", error => { throw error; });
    await prompt(emulator, "C:\\>");
    const word = "V86" + name.replace(/-/g, "").toUpperCase().slice(0, 8);
    await dos(emulator, "echo " + word + " > C:\\FORMAT.TXT");
    assert.match(await dos(emulator, "type C:\\FORMAT.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    await emulator.restart();
    await new Promise(resolve => setTimeout(resolve, 2000));
    await prompt(emulator, "C:\\> after the restart");
    assert.match(await dos(emulator, "type C:\\FORMAT.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    const state = await emulator.save_state();
    await dos(emulator, "del C:\\FORMAT.TXT");
    await emulator.restore_state(state);
    assert.match(await dos(emulator, "type C:\\FORMAT.TXT"), new RegExp("^" + word + "\\s*$", "m"));
    await emulator.destroy();
    assert.equal(create_hash("sha256").update(fs.readFileSync(image)).digest("hex"), sha256, "the image file is unchanged");
    console.log("ok - " + name + ": MS-DOS boots, writes a file, finds it after a restart and after a snapshot restored");
}
console.log("guest tests passed");
                                                        source/v64/tests/image/helpers.mjs                                                                  0000644 0000000 0000000 00000012045 00000000000 014267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // What the format tests share: reading through a reader, comparing with the
// RAW of qemu-img (whole, 1 MiB at a time, and in random ranges) or with a
// sample's writes, expecting errors.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { SAMPLES_DIR, random_generator, expected_from_writes, zstd_decompress } from "./samples.mjs";
import { open_image } from "../../src/image/factory.js";

/** the files of a sample in several files, as a descriptor's files */
export const sample_files = sample => Object.fromEntries((sample.files || []).map(name => [name, { url: sample_file(name), async: true }]));

export const settings = { zstd_decompress };
export const sample_file = name => path.join(SAMPLES_DIR, name);

export function read(reader, offset, length)
{
    return new Promise((resolve, reject) => reader.read(offset, length, (data, error) => error ? reject(error) : resolve(data)));
}

/** open a sample as a local file read in ranges (as an async URL in Node) or from memory */
export function open_sample(name, format, how, extra = {})
{
    const descriptor = how === "memory" ?
        { buffer: new Uint8Array(fs.readFileSync(sample_file(name))).buffer, format, ...extra } :
        { url: sample_file(name), async: true, format, ...extra };
    return open_image("hda", descriptor, settings);
}

/** open bytes from memory (a damaged copy) */
export function open_bytes(bytes, format, extra = {})
{
    return open_image("hda", { buffer: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), format, ...extra }, settings);
}

export async function rejects(promise, pattern, kind)
{
    try
    {
        await promise;
    }
    catch(error)
    {
        assert.match(error.message, pattern);
        if(kind) assert.equal(error.kind, kind, error.message);
        return error;
    }
    assert.fail("expected an error matching " + pattern);
}

export function compare(actual, expected, what)
{
    if(actual.length !== expected.length || Buffer.compare(Buffer.from(actual.buffer, actual.byteOffset, actual.length), Buffer.from(expected)) !== 0)
    {
        let i = 0;
        while(i < actual.length && actual[i] === expected[i]) i++;
        assert.fail(what + ": differs at byte " + i + " (" + actual[i] + " instead of " + expected[i] + ", lengths " +
            actual.length + "/" + expected.length + ")");
    }
}

/**
 * A sample against its RAW reference: whole and in random ranges, as a
 * file and from memory (synchronous); the bytes compared
 */
export async function check_against_reference(manifest, name, format, extra = {})
{
    const sample = manifest.samples[name];
    const reference = fs.readFileSync(sample_file(sample.reference));
    let compared = 0;
    for(const how of ["url", "memory"])
    {
        const reader = await open_sample(name, format, how, extra);
        assert.equal(reader.virtual_size, reference.length, name + ": the virtual size");
        assert.equal(reader.format, format);
        const step = 1 << 20;
        for(let offset = 0; offset < reference.length; offset += step)
        {
            const length = Math.min(step, reference.length - offset);
            compare(await read(reader, offset, length), reference.subarray(offset, offset + length), name + " at " + offset);
            compared += length;
        }
        const next = random_generator(name.length * 77 + (how === "memory" ? 1 : 2));
        const ranges = [[0, 512], [reference.length - 512, 512], [reference.length - 3 * 65536 - 512, 3 * 65536]];
        for(let i = 0; i < 200; i++)
        {
            const length = (1 + next() % 512) * 512;
            const offset = Math.floor(next() / 2 ** 32 * (reference.length - length) / 512) * 512;
            ranges.push([offset, length]);
        }
        for(const [offset, length] of ranges)
        {
            compare(await read(reader, offset, length), reference.subarray(offset, offset + length), name + " range " + offset + "+" + length);
        }
        if(how === "memory")
        {
            let done = false;
            reader.read(0, 4096, () => { done = true; });
            assert.ok(done, name + ": a read from memory is synchronous");
        }
    }
    return compared;
}

/** a large sparse sample: at and around its writes, and zeros elsewhere */
export async function check_writes(manifest, name, format, extra = {})
{
    const sample = manifest.samples[name];
    const reader = await open_sample(name, format, "url", extra);
    assert.equal(reader.virtual_size, sample.size, name + ": the virtual size");
    for(const [offset, length] of sample.writes)
    {
        for(const [start, size] of [[offset - 4096, length + 8192], [offset + 512, 1024], [offset + length - 512, 512]])
        {
            const from = Math.max(0, start), to = Math.min(sample.size, start + size);
            compare(await read(reader, from, to - from), expected_from_writes(sample, from, to - from), name + " at " + from);
        }
    }
    compare(await read(reader, 1024 ** 3, 65536), new Uint8Array(65536), name + ": unallocated, zeros");
    return reader;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/image/inflate.mjs                                                                  0000755 0000000 0000000 00000006662 00000000000 014262  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// src/virt/inflate.js against Node's zlib: stored, fixed and dynamic blocks,
// gzip; the output limit of QCOW2 and VMDK compressed clusters
// (docs/disk-image-formats-plan.md P2); damaged streams fail instead of
// giving wrong data.

import assert from "node:assert/strict";
import zlib from "node:zlib";
import { inflate, gunzip } from "../../src/virt/inflate.js";
import { random_generator, random_bytes } from "./samples.mjs";

const next = random_generator(7);
const inputs = {
    "random (stored blocks)": random_bytes(next, 200000),
    "text (dynamic blocks)": new TextEncoder().encode("v86 disk images ".repeat(5000) + "QCOW2 VMDK VHD VDI VHDX".repeat(300)),
    "zeros": new Uint8Array(65536),
    "short (fixed block)": Uint8Array.of(1, 2, 3, 4, 5),
    "mixed": Uint8Array.from({ length: 150000 }, (_, i) => i % 1000 < 500 ? (next() & 0xFF) : i & 7),
};
for(const [name, data] of Object.entries(inputs))
{
    for(const level of [0, 1, 6, 9])
    {
        const compressed = zlib.deflateRawSync(data, { level });
        const { output, end } = inflate(compressed, 0, data.length);
        assert.deepEqual(output, data, name + " level " + level);
        assert.equal(end, compressed.length, name + ": the end of the stream");
        // a limit: the first bytes, decoding stops there
        const half = Math.floor(data.length / 2);
        assert.deepEqual(inflate(compressed, 0, half, half).output, data.subarray(0, half), name + " limited");
        // trailing bytes after the stream (a cluster's last sector)
        const padded = new Uint8Array(compressed.length + 300);
        padded.set(compressed);
        padded.fill(0xA5, compressed.length);
        assert.deepEqual(inflate(padded, 0, data.length, data.length).output, data, name + " with garbage after it");
    }
}
assert.deepEqual(gunzip(new Uint8Array(zlib.gzipSync(inputs["mixed"]))), inputs["mixed"], "gunzip");
console.log("ok - inflate: the data of zlib's raw deflate at levels 0-9, limited, with trailing bytes; gunzip");

// damaged streams
const text = zlib.deflateRawSync(inputs["text (dynamic blocks)"]);
assert.throws(() => inflate(text.subarray(0, text.length >> 1)), /ends early/, "cut short");
const stored = new Uint8Array(zlib.deflateRawSync(inputs["random (stored blocks)"], { level: 0 }));
stored[3] ^= 0xFF;
assert.throws(() => inflate(stored), /length check/, "a stored block's NLEN");
const reserved = Uint8Array.of(0x07, 0, 0); // BFINAL, BTYPE 3
assert.throws(() => inflate(reserved), /reserved block type/);
// a fixed block whose first code is a match (no data before it)
const far = Uint8Array.of(0x03, 0x01, 0x00);
assert.throws(() => inflate(far), /distance before the start|ends early|invalid/);
let failures = 0, wrong = 0;
const data = inputs["mixed"];
const good = zlib.deflateRawSync(data);
for(let i = 0; i < 300; i++)
{
    const broken = new Uint8Array(good);
    broken[10 + next() % (broken.length - 20)] ^= 1 << (next() & 7);
    try
    {
        const { output } = inflate(broken, 0, data.length, data.length);
        if(output.length === data.length && Buffer.compare(Buffer.from(output), Buffer.from(data)) !== 0) wrong++;
    }
    catch(e)
    {
        failures++;
    }
}
console.log("ok - damaged streams: cut short, NLEN, reserved block, distances; of 300 single bit flips " + failures +
    " fail, " + wrong + " decode to other data of the full length (deflate has no checksum: QCOW2 clusters cannot tell)");
console.log("inflate tests passed");
                                                                              source/v64/tests/image/qcow2.mjs                                                                    0000755 0000000 0000000 00000051011 00000000000 013657  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The QCOW2 reader (docs/disk-image-formats-plan.md P1, P2) against the RAW
// that qemu-img converts the same image to: every sample read whole and in
// random ranges, through a local file read in ranges (as a URL in Node) and
// from memory; the features that are refused; damaged images, each with an
// error that names what is wrong.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { make_samples, SAMPLES_DIR, random_generator, expected_from_writes, TB3, zstd_decompress } from "./samples.mjs";
import { open_image, detect_format } from "../../src/image/factory.js";

process.on("unhandledRejection", exn => { throw exn; });

const manifest = make_samples();
console.log("samples by " + manifest.tool + " in " + SAMPLES_DIR);
const file = name => path.join(SAMPLES_DIR, name);

function read(reader, offset, length)
{
    return new Promise((resolve, reject) => reader.read(offset, length, (data, error) => error ? reject(error) : resolve(data)));
}

const settings = { zstd_decompress };

/** open a sample as a local file read in ranges (async: true) or from memory */
async function open(name, how, extra = {})
{
    const descriptor = how === "memory" ?
        { buffer: new Uint8Array(fs.readFileSync(file(name))).buffer, format: "qcow2", ...extra } :
        { url: file(name), async: true, format: "qcow2", ...extra };
    return open_image("hda", descriptor, settings);
}

/** open bytes from memory (a damaged copy) */
function open_bytes(bytes, format = "qcow2")
{
    return open_image("hda", { buffer: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length), format }, settings);
}

async function rejects(promise, pattern, kind)
{
    try
    {
        await promise;
    }
    catch(error)
    {
        assert.match(error.message, pattern);
        if(kind) assert.equal(error.kind, kind, error.message);
        return error;
    }
    assert.fail("expected an error matching " + pattern);
}

function compare(actual, expected, what)
{
    if(Buffer.compare(Buffer.from(actual.buffer, actual.byteOffset, actual.length), expected) !== 0)
    {
        let i = 0;
        while(actual[i] === expected[i]) i++;
        assert.fail(what + ": differs at byte " + i + " (" + actual[i] + " instead of " + expected[i] + ")");
    }
}

let checked_bytes = 0;

async function check_against_reference(name, how)
{
    const sample = manifest.samples[name];
    const reference = fs.readFileSync(file(sample.reference));
    const reader = await open(name, how);
    assert.equal(reader.virtual_size, reference.length, name + ": the virtual size");
    assert.equal(reader.format, "qcow2");

    // whole, 1 MiB at a time
    const step = 1 << 20;
    for(let offset = 0; offset < reference.length; offset += step)
    {
        compare(await read(reader, offset, step), reference.subarray(offset, offset + step), name + " at " + offset);
        checked_bytes += step;
    }

    // random ranges: first and last sectors, across clusters
    const next = random_generator(name.length * 77 + (how === "memory" ? 1 : 2));
    const ranges = [[0, 512], [reference.length - 512, 512], [reference.length - 3 * 65536 - 512, 3 * 65536]];
    for(let i = 0; i < 300; i++)
    {
        const length = (1 + next() % 512) * 512;
        const offset = Math.floor(next() / 2 ** 32 * (reference.length - length) / 512) * 512;
        ranges.push([offset, length]);
    }
    for(const [offset, length] of ranges)
    {
        compare(await read(reader, offset, length), reference.subarray(offset, offset + length), name + " range " + offset + "+" + length);
    }
    if(how === "memory")
    {
        // from memory, a read completes before read() returns (as SyncBuffer)
        let done = false;
        reader.read(0, 4096, () => { done = true; });
        assert.ok(done, name + ": a read from memory is synchronous");
    }
    return reader;
}

for(const name of ["v3.qcow2", "v2.qcow2", "v3-512.qcow2", "v3-2m.qcow2", "v2-4k.qcow2", "v3-zlib.qcow2", "v3-zstd.qcow2", "v2-zlib.qcow2"])
{
    for(const how of ["url", "memory"])
    {
        await check_against_reference(name, how);
    }
    console.log("ok - " + name + ": the RAW of qemu-img, whole and in ranges (local file, memory)");
}

// written with qemu-io: zero clusters, a discard, partial clusters, an
// internal snapshot (the active disk is read); one compressed cluster
{
    const name = "io.qcow2";
    const reference = fs.readFileSync(file("io.raw"));
    const reader = await open(name, "url");
    assert.equal(reader.snapshots, 1, "the internal snapshot is there");
    for(let offset = 0; offset < reference.length; offset += 65536)
    {
        compare(await read(reader, offset, 65536), reference.subarray(offset, offset + 65536), name + " at " + offset);
    }
    const compressed = await new Promise(resolve => reader.map(16842752, 65536, resolve));
    assert.equal(compressed[0].type, 3, "the cluster qemu-io wrote compressed is a compressed cluster");
    for(const [offset, length] of [[0, 65536], [131072, 131072]])
    {
        const extents = await new Promise(resolve => reader.map(offset, length, resolve));
        assert.deepEqual(extents.map(e => [e.type, e.length]), [[1, length]], "zero clusters (allocated and unmapped) at " + offset);
    }
    console.log("ok - io.qcow2: zero clusters, discard, partial clusters, a compressed write, an internal snapshot");
}

// 3 TiB: offsets beyond 4 GiB and 2^32 sectors
{
    const sample = manifest.samples["3t.qcow2"];
    const reader = await open("3t.qcow2", "url");
    assert.equal(reader.virtual_size, TB3);
    for(const [offset, length] of sample.writes)
    {
        for(const [start, size] of [[offset - 4096, length + 8192], [offset + 512, 1024], [offset + length - 512, 512]])
        {
            const from = Math.max(0, start), to = Math.min(TB3, start + size);
            compare(await read(reader, from, to - from), Buffer.from(expected_from_writes(sample, from, to - from)),
                "3 TiB at " + from);
        }
    }
    // across the sector 2^32 boundary, 512 bytes each side
    const boundary = 2 ** 32 * 512;
    compare(await read(reader, boundary - 512, 1024), Buffer.from(expected_from_writes(sample, boundary - 512, 1024)), "at 2^32 sectors");
    compare(await read(reader, 1024 ** 4, 65536), Buffer.alloc(65536), "unallocated: zeros");
    console.log("ok - 3 TiB qcow2: reads beyond 4 GiB and across 2^32 sectors");
}

// parents (P2): given as backing; the child's zero clusters hide the
// parent's data; a parent smaller than the child (RAW)
for(const [name, backing] of [["child.qcow2", { url: file("parent.qcow2"), async: true }],
    ["child-raw.qcow2", { url: file("base.raw"), async: true }], ["child.qcow2", { url: file("parent.qcow2"), async: true, format: "qcow2" }],
    ["child-of-zlib.qcow2", { url: file("v3-zlib.qcow2"), async: true }], ["child-zlib.qcow2", { url: file("parent.qcow2") }]])
{
    const reference = fs.readFileSync(file(manifest.samples[name].reference));
    const reader = await open(name, "url", { backing });
    assert.equal(reader.virtual_size, reference.length);
    assert.equal(reader.parent.format, name === "child-raw.qcow2" ? "raw" : "qcow2");
    for(let offset = 0; offset < reference.length; offset += 1 << 20)
    {
        compare(await read(reader, offset, 1 << 20), reference.subarray(offset, offset + (1 << 20)), name + " at " + offset);
    }
}
{
    const base = fs.readFileSync(file("base.raw"));
    assert.ok(base.subarray(0, 512).some(b => b), "the parent has data where the child has zero clusters");
}
await rejects(open("child.qcow2", "url"), /continues in a parent image.*give it as backing/, "config");
await rejects(open("v3.qcow2", "url", { backing: { url: file("base.raw") } }), /backing is given, but the image has no parent/, "config");
await rejects(open("child.qcow2", "url", { backing: { url: file("base.raw"), format: "raw" } }),
    /names its parent's format qcow2, backing is given as raw/, "config");
await rejects(open("child.qcow2", "url", { backing: { url: file("v3.qcow2"), format: "vhd" } }), /names its parent's format qcow2/, "config");
const circular = { url: file("child.qcow2"), async: true, format: "qcow2" };
circular.backing = circular;
await rejects(open_image("hda", circular, settings), /circular/, "config");
const child_bytes = fs.readFileSync(file("child.qcow2"));
let deep = { buffer: new Uint8Array(fs.readFileSync(file("parent.qcow2"))).buffer, format: "qcow2" };
for(let i = 0; i < 17; i++) deep = { buffer: new Uint8Array(child_bytes).buffer, format: "qcow2", backing: deep };
await rejects(open_image("hda", deep, settings), /more than 16 parent images/, "config");
{
    const a = await open("child.qcow2", "url", { backing: { url: file("parent.qcow2") } });
    const b = await open("child.qcow2", "url", { backing: { url: file("v3.qcow2") } });
    const c = await open("child.qcow2", "url", { backing: { url: file("v3-512.qcow2") } });
    assert.deepEqual(a.identity(), b.identity(), "the same parent (the same bytes) under another name");
    assert.notDeepEqual(a.identity()["parent"], c.identity()["parent"], "another parent of the same data");
}
console.log("ok - parents: QCOW2 and RAW, compressed parents and children; explicit only; missing, unexpected, of another format, circular, too deep: refused");

// features that are refused
await rejects(open("extl2.qcow2", "url"), /extended L2/, "unsupported");
await rejects(open("data-file.qcow2", "url"), /external data file/, "unsupported");
await rejects(open("luks.qcow2", "url"), /encrypt/, "unsupported");
console.log("ok - refused: extended L2 entries, an external data file, encryption");

// damaged headers and tables (a copy of v3.qcow2 in memory)
const v3 = fs.readFileSync(file("v3.qcow2"));
const view = bytes => new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
const patched = (patch) =>
{
    const bytes = new Uint8Array(v3);
    patch(bytes, view(bytes));
    return bytes;
};
const v3_l1_offset = Number(view(v3).getBigUint64(40));
const first_l2 = Number(view(v3).getBigUint64(v3_l1_offset) & 0x00FFFFFFFFFFFE00n);
const reference = fs.readFileSync(file("base.raw"));
{
    await rejects(open_bytes(patched((b, v) => v.setUint32(0, 0x12345678))), /not a qcow2 image/, "config");
    await rejects(open_bytes(patched((b, v) => v.setUint32(0, 0x12345678)), "auto"), /could not be determined/, "config");
    await rejects(open_bytes(patched((b, v) => v.setUint32(4, 4))), /version 4/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setUint32(20, 8))), /cluster_bits 8/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setUint32(20, 22))), /cluster_bits 22/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(24, 64n * 1024n * 1024n + 100n))), /multiple of 512/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(24, 1n << 60n))), /too large/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setUint32(32, 1))), /encrypted/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(72, 1n << 5n))), /unknown incompatible features 0x20/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(72, 1n))), /dirty/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(72, 2n))), /corrupt/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setUint32(36, 0))), /L1 table has 0 entries/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(40, BigInt(v3_l1_offset + 512)))), /not aligned/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(v3_l1_offset, v.getBigUint64(v3_l1_offset) | 1n))), /reserved bits/, "corrupt");
    await rejects(open_bytes(v3.subarray(0, v3_l1_offset + 4)), /L1 table .* past the end of the file/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setUint32(100, 100))), /header_length 100/, "corrupt");
    console.log("ok - damaged headers: each refused with what is wrong");

    // unknown compatible and autoclear features, an unknown header
    // extension: read as before
    const compatible = await open_bytes(patched((b, v) =>
    {
        v.setBigUint64(80, v.getBigUint64(80) | 1n << 7n);
        v.setBigUint64(88, v.getBigUint64(88) | 1n << 9n);
        // an unknown extension in front of the others
        const header_length = v.getUint32(100);
        const rest = b.slice(header_length, 4000);
        v.setUint32(header_length, 0x12345678);
        v.setUint32(header_length + 4, 5);
        b.set([1, 2, 3, 4, 5, 0, 0, 0], header_length + 8);
        b.set(rest.subarray(0, 4000 - header_length - 16), header_length + 16);
    }));
    compare(await read(compatible, 0, 1 << 20), reference.subarray(0, 1 << 20), "with unknown compatible features");
    console.log("ok - unknown compatible/autoclear features and header extensions are ignored");

    // tables: an L2 table past the end of the file, an L2 entry with
    // reserved bits, a data cluster not aligned, the zero flag in version 2
    const truncated = await open_bytes(v3.subarray(0, first_l2));
    await rejects(read(truncated, 0, 512), /L2 table at \d+ is past the end of the file/, "corrupt");
    const entry = (bytes, index) => first_l2 + index * 8;
    const reserved = await open_bytes(patched((b, v) => v.setBigUint64(entry(b, 0), v.getBigUint64(entry(b, 0)) | 2n)));
    await rejects(read(reserved, 0, 512), /guest offset 0 .*reserved bits/, "corrupt");
    compare(await read(reserved, 65536, 65536), reference.subarray(65536, 131072), "the other clusters still read");
    const unaligned = await open_bytes(patched((b, v) => v.setBigUint64(entry(b, 0), v.getBigUint64(entry(b, 0)) + 512n)));
    await rejects(read(unaligned, 0, 512), /not aligned/, "corrupt");
    const v2 = fs.readFileSync(file("v2.qcow2"));
    const v2_l2 = Number(view(v2).getBigUint64(Number(view(v2).getBigUint64(40))) & 0x00FFFFFFFFFFFE00n);
    const v2_zero = new Uint8Array(v2);
    view(v2_zero).setBigUint64(v2_l2, view(v2_zero).getBigUint64(v2_l2) | 1n);
    await rejects(read(await open_bytes(v2_zero), 0, 512), /zero flag in a version 2 image/, "corrupt");
    // a data cluster past the end of the file reads as zeros (as QEMU)
    const past_end = (Math.ceil(v3.length / 65536) + 4) * 65536;
    const past = await open_bytes(patched((b, v) => v.setBigUint64(entry(b, 1), BigInt(past_end) | 1n << 63n)));
    compare(await read(past, 65536, 65536), Buffer.alloc(65536), "a cluster past the end of the file");
    console.log("ok - damaged tables: the read fails with what is wrong; past the end of the file: zeros");
}

// damaged compressed clusters: the stream cut short, past the end of the
// file, the copied flag
{
    const zlib_image = fs.readFileSync(file("v3-zlib.qcow2"));
    const zv = view(zlib_image);
    const l1 = Number(zv.getBigUint64(40));
    const l2 = Number(zv.getBigUint64(l1) & 0x00FFFFFFFFFFFE00n);
    // the first compressed cluster (bit 62) of more than one sector
    const x = 62n - (16n - 8n);
    const sectors_mask = ((1n << (62n - x)) - 1n) << x;
    let index = 0;
    while(!(zv.getBigUint64(l2 + index * 8) & 1n << 62n) || !(zv.getBigUint64(l2 + index * 8) & sectors_mask)) index++;
    const at = l2 + index * 8;
    const entry = zv.getBigUint64(at);
    const offset = entry & ((1n << x) - 1n);
    const patch = value => { const b = new Uint8Array(zlib_image); view(b).setBigUint64(at, value); return b; };
    const guest = index * 65536;
    await rejects(read(await open_bytes(patch(entry & ~sectors_mask)), guest, 512), /compressed cluster at \d+ is invalid: inflate|has \d+ bytes, not a cluster/, "corrupt");
    await rejects(read(await open_bytes(patch(1n << 62n | BigInt(zlib_image.length + 4096))), guest, 512), /past the end of the file/, "corrupt");
    await rejects(read(await open_bytes(patch(entry | 1n << 63n)), guest, 512), /compressed cluster with the copied flag/, "corrupt");
    void offset;
    console.log("ok - damaged compressed clusters: cut short, past the end of the file, the copied flag");
}

// through the emulator: zstd clusters decoded by the core's Zstandard
// decoder (src/browser/starter.js), a damaged one an error, not a crash
{
    const { V86 } = await import("../../src/main.js");
    const root = path.join(path.dirname(new URL(import.meta.url).pathname), "../../");
    const zstd_image = new Uint8Array(fs.readFileSync(file("v3-zstd.qcow2")));
    const zv = view(zstd_image);
    const l2 = Number(zv.getBigUint64(Number(zv.getBigUint64(40))) & 0x00FFFFFFFFFFFE00n);
    // a compressed cluster of more than one sector, its frame's magic
    // damaged (damage inside the data is not seen: QEMU's frames have no
    // checksum)
    let index = 0;
    while(!(zv.getBigUint64(l2 + index * 8) & 1n << 62n) || !(zv.getBigUint64(l2 + index * 8) >> 54n & 0xFFn)) index++;
    const host = Number(zv.getBigUint64(l2 + index * 8) & ((1n << 54n) - 1n));
    zstd_image.fill(0x55, host, host + 4);
    const emulator = new V86({
        bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" }, graphics_adapter: "bochs_vga",
        hda: { buffer: zstd_image.buffer, format: "auto" }, autostart: false, memory_size: 32 << 20, log_level: 0,
    });
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    const disk = emulator.v86.cpu.devices.ide.primary.master.buffer;
    const get = (offset, length) => new Promise((resolve, reject) => disk.get(offset, length, (data, error) => error ? reject(error) : resolve(data)));
    const base = fs.readFileSync(file("base.raw"));
    let compared = 0;
    for(let offset = 0; offset < base.length; offset += 1 << 20)
    {
        if(offset <= index * 65536 && index * 65536 < offset + (1 << 20)) continue;
        compare(await get(offset, 1 << 20), base.subarray(offset, offset + (1 << 20)), "zstd through the core at " + offset);
        compared++;
    }
    const errors = console.error, traces = console.trace;
    console.error = console.trace = () => {};
    await rejects(get(index * 65536, 512), /compressed cluster at \d+ is invalid|not a Zstandard frame/, "corrupt");
    console.error = errors;
    console.trace = traces;
    const after = (Math.floor(index * 65536 / (1 << 20)) + 1) * (1 << 20);
    compare(await get(after, 1 << 20), base.subarray(after, after + (1 << 20)), "the disk after the damaged cluster");
    emulator.destroy();
    console.log("ok - zstd clusters through the core's decoder (" + compared + " MiB); a damaged cluster: an I/O error");
}

// the format from the signature (auto) and the ones not read
{
    const head = n => new Uint8Array(n);
    const text = (bytes, offset, s) => { for(let i = 0; i < s.length; i++) bytes[offset + i] = s.charCodeAt(i); return bytes; };
    assert.equal(detect_format(new Uint8Array(v3.subarray(0, 4096)), new Uint8Array(512)), "qcow2");
    assert.equal(detect_format(text(head(4096), 0, "QFI\xfb\0\0\0\x01"), head(512)), "qcow");
    assert.equal(detect_format(text(head(4096), 0, "QED\0"), head(512)), "qed");
    assert.equal(detect_format(head(4096), text(head(512), 0, "conectix")), "vhd");
    assert.equal(detect_format(text(head(4096), 0, "conectix"), head(512)), "vhd");
    const vdi = head(4096);
    new DataView(vdi.buffer).setUint32(0x40, 0xBEDA107F, true);
    assert.equal(detect_format(vdi, head(512)), "vdi");
    assert.equal(detect_format(text(head(4096), 0, "KDMV"), head(512)), "vmdk");
    assert.equal(detect_format(text(head(4096), 0, "# Disk DescriptorFile\n"), head(512)), "vmdk");
    assert.equal(detect_format(text(head(4096), 0, "vhdxfile"), head(512)), "vhdx");
    assert.equal(detect_format(text(head(0x9000), 0x8001, "CD001"), head(512)), "iso");
    assert.equal(detect_format(head(4096), head(512)), "");
    const raw = new Uint8Array(4096 * 4);
    await rejects(open_bytes(raw, "auto"), /could not be determined/, "config");
    await rejects(open_bytes(text(head(65536), 0, "QED\0"), "auto"), /qed is not supported/, "unsupported");
    const auto = await open_bytes(new Uint8Array(v3), "auto");
    assert.equal(auto.format, "qcow2");
    console.log("ok - auto: the format from its signature; RAW and unknown ones need a format");
}

// identity: the same image twice, the same disk in another image
{
    const a = await open("v3.qcow2", "url"), b = await open("v3.qcow2", "memory"), c = await open("v2.qcow2", "url");
    assert.deepEqual(a.identity(), b.identity(), "the same image from a file and from memory");
    assert.notEqual(a.identity()["metadata_sha256"], c.identity()["metadata_sha256"], "another image of the same disk");
    console.log("ok - identity: the image's metadata, not where it is read from");
}

console.log("qcow2 tests passed (" + (checked_bytes >> 20) + " MiB compared)");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/image/qcow2_export.mjs                                                             0000755 0000000 0000000 00000014053 00000000000 015265  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Export of a disk as a new QCOW2 image (docs/disk-image-formats-plan.md P5):
// qemu-img check finds no errors in it and qemu-img compare finds it equal
// to the RAW export of the same disk view; the reader of v86 reads it back.
// Disks: a compressed QCOW2 child on its parent with the guest's writes, a
// VHD whose size is not a multiple of a cluster, a RAW disk in memory.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { make_samples, SAMPLES_DIR } from "./samples.mjs";
import { sample_file, settings, read, compare } from "./helpers.mjs";
import { open_image } from "../../src/image/factory.js";

process.on("unhandledRejection", exn => { throw exn; });

const root = fileURLToPath(new URL("../../", import.meta.url));
const QEMU_IMG = process.env.QEMU_IMG || (fs.existsSync("/opt/homebrew/bin/qemu-img") ? "/opt/homebrew/bin/qemu-img" : "qemu-img");
make_samples();
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const out = path.join(SAMPLES_DIR, "export");
fs.mkdirSync(out, { recursive: true });

async function machine(hda)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
        hda, autostart: false, memory_size: 32 << 20, log_level: 0,
    });
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    return emulator;
}

async function export_to(emulator, format, file)
{
    const chunks = [], progress = [];
    const size = await emulator.export_disk_image("hda", { format, write: chunk => { chunks.push(chunk); }, progress: p => progress.push(p) });
    const bytes = Buffer.concat(chunks);
    assert.equal(bytes.length, size);
    fs.writeFileSync(file, bytes);
    return { size, progress };
}

const cases = [
    ["child", { url: sample_file("child-zlib.qcow2"), async: true, format: "qcow2", backing: { url: sample_file("parent.qcow2"), async: true } }],
    ["vhd", { url: sample_file("dynamic.vhd"), async: true, format: "vhd" }],
    ["raw", { buffer: new Uint8Array(fs.readFileSync(sample_file("base.raw"))).buffer }],
];
for(const [name, hda] of cases)
{
    const emulator = await machine(hda);
    // the guest's writes: in the first cluster, across clusters, at the end
    const disk = emulator.v86.cpu.devices.ide.primary.master;
    const size = disk.buffer.byteLength;
    for(const [offset, length, fill] of [[512, 1024, 0x11], [3 * 65536 - 512, 70000, 0x22], [size - 1024, 1024, 0x33], [40 << 20, 65536, 0]])
    {
        await new Promise(resolve => disk.write_to_backend(offset, new Uint8Array(length - length % 512).fill(fill), resolve));
    }
    const raw = path.join(out, name + ".raw"), qcow2 = path.join(out, name + ".qcow2");
    const raw_result = await export_to(emulator, "raw", raw);
    const qcow2_result = await export_to(emulator, "qcow2", qcow2);
    assert.equal(raw_result.size, size);
    assert.equal(qcow2_result.progress[qcow2_result.progress.length - 1].loaded, qcow2_result.size, "progress to the end");
    execFileSync(QEMU_IMG, ["check", "-q", "-f", "qcow2", qcow2]);
    execFileSync(QEMU_IMG, ["compare", "-q", "-f", "qcow2", "-F", "raw", qcow2, raw]);
    const info = JSON.parse(execFileSync(QEMU_IMG, ["info", "--output=json", "-f", "qcow2", qcow2]).toString());
    assert.equal(info["virtual-size"], size, "the virtual size");
    const reader = await open_image("hda", { url: qcow2, async: true, format: "auto" }, settings);
    const expected = fs.readFileSync(raw);
    for(let offset = 0; offset < size; offset += 4 << 20)
    {
        const length = Math.min(4 << 20, size - offset);
        compare(await read(reader, offset, length), expected.subarray(offset, offset + length), name + ": read back at " + offset);
    }
    emulator.destroy();
    console.log("ok - " + name + ": the QCOW2 export (" + qcow2_result.size + " bytes of a " + size + "-byte disk) passes qemu-img check, " +
        "equals the RAW export (qemu-img compare), reads back");
}
// an unknown format; cancelled during the scan and during the writes
{
    const emulator = await machine({ url: sample_file("v3.qcow2"), async: true, format: "qcow2" });
    await assert.rejects(emulator.export_disk_image("hda", { format: "vhdx", write() {} }), /unknown format "vhdx"/);
    for(const after of ["scan", "write"])
    {
        const controller = new AbortController();
        await assert.rejects(emulator.export_disk_image("hda", { format: "qcow2", signal: controller.signal, write() {},
            progress: p => { if(p.phase === after && p.loaded > 0) controller.abort(); } }), /cancelled/);
    }
    // the machine goes on after an export
    assert.equal(emulator.is_running(), false);
    emulator.destroy();
    console.log("ok - an unknown export format is refused; an export cancelled while scanning or writing fails");
}

// large sparse disks: the parts without data are not read; qemu-img compare
// with the source image
for(const [name, format] of [["3t.qcow2", "qcow2"], ["3t.vdi", "vdi"], ["100g.vhd", "vhd"]])
{
    const emulator = await machine({ url: sample_file(name), async: true, format });
    const qcow2 = path.join(out, name + ".qcow2");
    const source = emulator.v86.cpu.devices.ide.primary.master.buffer.reader.source;
    const before = source.inner ? source.inner.stats.bytes : 0;
    const { size } = await export_to(emulator, "qcow2", qcow2);
    const read_bytes = (source.inner ? source.inner.stats.bytes : 0) - before;
    execFileSync(QEMU_IMG, ["check", "-q", "-f", "qcow2", qcow2]);
    execFileSync(QEMU_IMG, ["compare", "-q", "-f", "qcow2", "-F", format === "vhd" ? "vpc" : format, qcow2, sample_file(name)]);
    emulator.destroy();
    console.log("ok - " + name + ": exported as QCOW2 (" + size + " bytes), " + read_bytes + " bytes of the image read; qemu-img check and compare");
}
console.log("QCOW2 export tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/image/samples.mjs                                                                  0000755 0000000 0000000 00000046642 00000000000 014306  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Disk image samples for the format tests (docs/disk-image-formats-plan.md,
// "验收矩阵"), made by an independent tool: qemu-img and qemu-io (QEMU_IMG,
// QEMU_IO; Homebrew's by default). A RAW image of 64 MiB with random, zero
// and patterned regions is converted to each format; others are written
// with qemu-io (zero clusters, snapshots, a disk of 3 TiB). Each sample has
// a RAW reference converted back by qemu-img (or, for the 3 TiB one, the
// list of its writes). The samples are made once in build/disk-image-samples
// (DISK_IMAGE_SAMPLES), the commands and the tool's version in manifest.json.

import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import zlib from "node:zlib";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
export const SAMPLES_DIR = process.env.DISK_IMAGE_SAMPLES || path.join(root, "build/disk-image-samples");
const QEMU_IMG = process.env.QEMU_IMG || (fs.existsSync("/opt/homebrew/bin/qemu-img") ? "/opt/homebrew/bin/qemu-img" : "qemu-img");
const QEMU_IO = process.env.QEMU_IO || (fs.existsSync("/opt/homebrew/bin/qemu-io") ? "/opt/homebrew/bin/qemu-io" : "qemu-io");

// changing a sample: change this, and the samples are made again
const SAMPLES_VERSION = 7;

export const BASE_SIZE = 64 * 1024 * 1024;
export const TB3 = 3 * 1024 ** 4;

/**
 * A reproducible pseudo-random generator (xorshift32)
 * @param {number} seed
 */
export function random_generator(seed)
{
    let x = seed >>> 0 || 1;
    return () =>
    {
        x ^= x << 13; x >>>= 0;
        x ^= x >>> 17;
        x ^= x << 5; x >>>= 0;
        return x;
    };
}

/**
 * Bytes from the generator
 * @param {function():number} next
 * @param {number} length
 */
export function random_bytes(next, length)
{
    const bytes = new Uint8Array(length);
    for(let i = 0; i < length; i += 4)
    {
        const value = next();
        bytes[i] = value; bytes[i + 1] = value >>> 8; bytes[i + 2] = value >>> 16; bytes[i + 3] = value >>> 24;
    }
    return bytes;
}

/**
 * The RAW base: 64 KiB regions, random, zero, a few sectors, 0xFF; the first
 * and last regions random
 */
function make_base()
{
    const next = random_generator(0x86);
    const disk = new Uint8Array(BASE_SIZE);
    const region = 64 * 1024;
    for(let i = 0; i < BASE_SIZE / region; i++)
    {
        const kind = i === 0 || i === BASE_SIZE / region - 1 ? 0 : next() % 8;
        const start = i * region;
        if(kind <= 2) disk.set(random_bytes(next, region), start);
        else if(kind === 5)
        {
            for(let s = 0; s < 4; s++)
            {
                const sector = next() % (region / 512);
                disk.set(random_bytes(next, 512), start + sector * 512);
            }
        }
        else if(kind === 6) disk.fill(0xFF, start, start + region);
    }
    return disk;
}

function run(tool, args, log)
{
    log.push([path.basename(tool), ...args.map(a => a.startsWith(SAMPLES_DIR) ? path.relative(SAMPLES_DIR, a) : a)].join(" "));
    return execFileSync(tool, args, { stdio: ["ignore", "pipe", "pipe"] }).toString();
}

function sha256_file(file)
{
    const hash = create_hash("sha256");
    const fd = fs.openSync(file, "r");
    const buffer = Buffer.alloc(1 << 20);
    for(;;)
    {
        const n = fs.readSync(fd, buffer, 0, buffer.length, null);
        if(!n) break;
        hash.update(buffer.subarray(0, n));
    }
    fs.closeSync(fd);
    return hash.digest("hex");
}

/**
 * Make the samples (if needed) and describe them
 * @return {{dir: string, version: string, samples: Object}}
 */
export function make_samples()
{
    const manifest_path = path.join(SAMPLES_DIR, "manifest.json");
    if(fs.existsSync(manifest_path))
    {
        const manifest = JSON.parse(fs.readFileSync(manifest_path, "utf8"));
        if(manifest.samples_version === SAMPLES_VERSION) return manifest;
    }
    let version;
    try
    {
        version = execFileSync(QEMU_IMG, ["--version"]).toString().split("\n")[0];
    }
    catch(e)
    {
        throw new Error("The disk image tests need qemu-img and qemu-io (QEMU_IMG, QEMU_IO): " + e.message);
    }
    fs.rmSync(SAMPLES_DIR, { recursive: true, force: true });
    fs.mkdirSync(SAMPLES_DIR, { recursive: true });
    const log = [];
    const file = name => path.join(SAMPLES_DIR, name);
    const samples = {};
    const add = (name, format, reference, extra = {}) =>
    {
        samples[name] = { file: name, format, reference, ...extra };
    };

    fs.writeFileSync(file("base.raw"), make_base());
    log.push("base.raw: 64 MiB from tests/image/samples.mjs (make_base, seed 0x86)");

    // QCOW2 from the RAW base: versions, cluster sizes
    const convert = (name, options) =>
    {
        run(QEMU_IMG, ["convert", "-f", "raw", "-O", "qcow2", ...options, file("base.raw"), file(name)], log);
        add(name, "qcow2", "base.raw");
    };
    convert("v3.qcow2", ["-o", "compat=1.1"]);
    convert("v2.qcow2", ["-o", "compat=0.10"]);
    convert("v3-512.qcow2", ["-o", "compat=1.1,cluster_size=512"]);
    convert("v3-2m.qcow2", ["-o", "compat=1.1,cluster_size=2M"]);
    convert("v2-4k.qcow2", ["-o", "compat=0.10,cluster_size=4096"]);
    convert("v3-zlib.qcow2", ["-c", "-o", "compat=1.1"]);
    convert("v3-zstd.qcow2", ["-c", "-o", "compat=1.1,compression_type=zstd"]);
    convert("v2-zlib.qcow2", ["-c", "-o", "compat=0.10"]);

    // written with qemu-io: data, zero clusters (with and without the
    // cluster's allocation kept), discarded clusters, a compressed write;
    // an internal snapshot of the state before the last writes
    const pattern = file("pattern.bin");
    fs.writeFileSync(pattern, random_bytes(random_generator(0x1234), 1 << 20));
    run(QEMU_IMG, ["convert", "-f", "raw", "-O", "qcow2", "-o", "compat=1.1", file("base.raw"), file("io.qcow2")], log);
    run(QEMU_IMG, ["snapshot", "-c", "before", file("io.qcow2")], log);
    run(QEMU_IO, ["-f", "qcow2",
        "-c", "write -q -z 0 65536",                  // a zero cluster, its allocation kept
        "-c", "write -q -z -u 131072 131072",         // zero clusters, unmapped
        "-c", "write -q -s " + pattern + " 1048576 196608",
        "-c", "write -q -P 0x5a 4194816 1024",        // part of a cluster
        "-c", "write -q -z 8389120 512",              // part of a cluster: zeroes written
        "-c", "discard -q 16777216 1048576",
        // compressed (a pattern that compresses), in the discarded part: a
        // compressed write needs an unallocated cluster
        "-c", "write -q -c -P 0x33 16842752 65536",
        file("io.qcow2")], log);
    run(QEMU_IMG, ["convert", "-O", "raw", file("io.qcow2"), file("io.raw")], log);
    add("io.qcow2", "qcow2", "io.raw", { snapshots: 1 });

    // a parent and a child: the child's zero clusters hide the parent's data
    run(QEMU_IMG, ["convert", "-f", "raw", "-O", "qcow2", "-o", "compat=1.1", file("base.raw"), file("parent.qcow2")], log);
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1", "-b", "parent.qcow2", "-F", "qcow2", file("child.qcow2")], log);
    run(QEMU_IO, ["-f", "qcow2",
        "-c", "write -q -z 0 131072",
        "-c", "write -q -s " + pattern + " 524288 262144",
        "-c", "write -q -P 0xc3 3145728 4096",
        file("child.qcow2")], log);
    run(QEMU_IMG, ["convert", "-O", "raw", file("child.qcow2"), file("child.raw")], log);
    add("child.qcow2", "qcow2", "child.raw", { backing: "parent.qcow2" });
    // compression and parents: a child of a compressed parent, a compressed
    // child (convert -c -B: only what differs from the parent)
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1", "-b", "v3-zlib.qcow2", "-F", "qcow2", file("child-of-zlib.qcow2")], log);
    run(QEMU_IO, ["-f", "qcow2", "-c", "write -q -z 65536 65536", "-c", "write -q -s " + pattern + " 2097152 131072",
        file("child-of-zlib.qcow2")], log);
    run(QEMU_IMG, ["convert", "-O", "raw", file("child-of-zlib.qcow2"), file("child-of-zlib.raw")], log);
    add("child-of-zlib.qcow2", "qcow2", "child-of-zlib.raw", { backing: "v3-zlib.qcow2" });
    run(QEMU_IMG, ["convert", "-c", "-O", "qcow2", "-o", "compat=1.1", "-B", "parent.qcow2", "-F", "qcow2",
        file("child.qcow2"), file("child-zlib.qcow2")], log);
    add("child-zlib.qcow2", "qcow2", "child.raw", { backing: "parent.qcow2" });
    // a child of a RAW parent, smaller than the child
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1", "-b", "base.raw", "-F", "raw", file("child-raw.qcow2"), "80M"], log);
    run(QEMU_IO, ["-f", "qcow2", "-c", "write -q -P 0x77 66060288 1048576", "-c", "write -q -P 0x11 4096 4096",
        file("child-raw.qcow2")], log);
    run(QEMU_IMG, ["convert", "-O", "raw", file("child-raw.qcow2"), file("child-raw.raw")], log);
    add("child-raw.qcow2", "qcow2", "child-raw.raw", { backing: "base.raw", backing_format: "raw" });

    // 3 TiB: writes around 4 GiB and 2^32 sectors (2 TiB), and at the end
    const big_writes = [
        [4 * 1024 ** 3 - 4096, 8192],
        [2 * 1024 ** 4 - 65536 - 512, 131072],
        [TB3 - 65536, 65536],
    ];
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1", file("3t.qcow2"), String(TB3)], log);
    run(QEMU_IO, ["-f", "qcow2", ...big_writes.flatMap(([offset, length], i) =>
        ["-c", "write -q -s " + pattern + " " + offset + " " + length]), file("3t.qcow2")], log);
    add("3t.qcow2", "qcow2", null, { size: TB3, writes: big_writes, pattern: "pattern.bin" });

    // VHD (qemu-img's "vpc"; P3): dynamic and fixed, the size from the CHS
    // geometry (creator "qemu") or exact (force_size: "qem2"); the
    // references converted back with -f vpc (qemu-img does not probe a fixed
    // VHD: its footer is at the end)
    const vhd = (name, options) =>
    {
        run(QEMU_IMG, ["convert", "-f", "raw", "-O", "vpc", ...options, file("base.raw"), file(name)], log);
        run(QEMU_IMG, ["convert", "-f", "vpc", "-O", "raw", file(name), file(name + ".raw")], log);
        add(name, "vhd", name + ".raw");
    };
    vhd("dynamic.vhd", []);
    vhd("dynamic-force.vhd", ["-o", "force_size=on"]);
    vhd("fixed.vhd", ["-o", "subformat=fixed"]);
    vhd("fixed-force.vhd", ["-o", "subformat=fixed,force_size=on"]);
    // a sparse dynamic VHD of 100 GiB, written beyond 4 GiB and at its end
    const vhd_writes = [[5 * 1024 ** 3 - 4096, 8192], [100 * 1024 ** 3 - 65536, 65536]];
    run(QEMU_IMG, ["create", "-q", "-f", "vpc", "-o", "force_size=on", file("100g.vhd"), "100G"], log);
    run(QEMU_IO, ["-f", "vpc", ...vhd_writes.flatMap(([offset, length]) => ["-c", "write -q -s " + pattern + " " + offset + " " + length]),
        file("100g.vhd")], log);
    add("100g.vhd", "vhd", null, { size: 100 * 1024 ** 3, writes: vhd_writes, pattern: "pattern.bin" });

    // VDI (P3): dynamic and fixed ("static"), and 3 TiB dynamic written
    // across 2^32 sectors
    const vdi = (name, options) =>
    {
        run(QEMU_IMG, ["convert", "-f", "raw", "-O", "vdi", ...options, file("base.raw"), file(name)], log);
        add(name, "vdi", "base.raw");
    };
    vdi("dynamic.vdi", []);
    vdi("static.vdi", ["-o", "static=on"]);
    run(QEMU_IMG, ["create", "-q", "-f", "vdi", file("3t.vdi"), String(TB3)], log);
    run(QEMU_IO, ["-f", "vdi", ...big_writes.flatMap(([offset, length]) => ["-c", "write -q -s " + pattern + " " + offset + " " + length]),
        file("3t.vdi")], log);
    add("3t.vdi", "vdi", null, { size: TB3, writes: big_writes, pattern: "pattern.bin" });

    // VMDK (P4): the subformats qemu-img makes; zeroed grains; a child with
    // its parent (parentCID); 100 GiB sparse, 5 GiB in 2 GiB extents (sparse
    // and flat) written across an extent's end
    const vmdk = (name, options, extra = {}) =>
    {
        run(QEMU_IMG, ["convert", "-f", "raw", "-O", "vmdk", ...options, file("base.raw"), file(name)], log);
        add(name, "vmdk", "base.raw", extra);
    };
    vmdk("sparse.vmdk", []);
    vmdk("stream.vmdk", ["-o", "subformat=streamOptimized"]);
    vmdk("flat.vmdk", ["-o", "subformat=monolithicFlat"], { files: ["flat-flat.vmdk"] });
    vmdk("2gbsparse.vmdk", ["-o", "subformat=twoGbMaxExtentSparse"], { files: ["2gbsparse-s001.vmdk"] });
    vmdk("2gbflat.vmdk", ["-o", "subformat=twoGbMaxExtentFlat"], { files: ["2gbflat-f001.vmdk"] });
    run(QEMU_IMG, ["convert", "-f", "raw", "-O", "vmdk", "-o", "zeroed_grain=on", file("base.raw"), file("zeroed.vmdk")], log);
    run(QEMU_IO, ["-f", "vmdk", "-c", "write -q -z 0 131072", "-c", "write -q -z 1048576 65536", file("zeroed.vmdk")], log);
    run(QEMU_IMG, ["convert", "-f", "vmdk", "-O", "raw", file("zeroed.vmdk"), file("zeroed.vmdk.raw")], log);
    add("zeroed.vmdk", "vmdk", "zeroed.vmdk.raw");
    run(QEMU_IMG, ["create", "-q", "-f", "vmdk", "-b", "sparse.vmdk", "-F", "vmdk", file("child.vmdk")], log);
    run(QEMU_IO, ["-f", "vmdk", "-c", "write -q -s " + pattern + " 524288 262144", "-c", "write -q -P 0xc3 3145728 4096",
        file("child.vmdk")], log);
    run(QEMU_IMG, ["convert", "-f", "vmdk", "-O", "raw", file("child.vmdk"), file("child.vmdk.raw")], log);
    add("child.vmdk", "vmdk", "child.vmdk.raw", { backing: "sparse.vmdk" });
    const vmdk_writes = [[5 * 1024 ** 3 - 4096, 8192], [100 * 1024 ** 3 - 65536, 65536]];
    run(QEMU_IMG, ["create", "-q", "-f", "vmdk", file("100g.vmdk"), "100G"], log);
    run(QEMU_IO, ["-f", "vmdk", ...vmdk_writes.flatMap(([offset, length]) => ["-c", "write -q -s " + pattern + " " + offset + " " + length]),
        file("100g.vmdk")], log);
    add("100g.vmdk", "vmdk", null, { size: 100 * 1024 ** 3, writes: vmdk_writes, pattern: "pattern.bin" });
    const extent_writes = [[2 * 1024 ** 3 - 65536 - 512, 131072], [5 * 1024 ** 3 - 4096, 4096]];
    for(const [name, subformat] of [["5g-sparse.vmdk", "twoGbMaxExtentSparse"], ["5g-flat.vmdk", "twoGbMaxExtentFlat"]])
    {
        run(QEMU_IMG, ["create", "-q", "-f", "vmdk", "-o", "subformat=" + subformat, file(name), "5G"], log);
        run(QEMU_IO, ["-f", "vmdk", ...extent_writes.flatMap(([offset, length]) => ["-c", "write -q -s " + pattern + " " + offset + " " + length]),
            file(name)], log);
        const stem = name.replace(/\.vmdk$/, "");
        const letter = subformat.endsWith("Sparse") ? "s" : "f";
        add(name, "vmdk", null, { size: 5 * 1024 ** 3, writes: extent_writes, pattern: "pattern.bin",
            files: [1, 2, 3].map(i => stem + "-" + letter + String(i).padStart(3, "0") + ".vmdk") });
    }

    // VHDX (P5): dynamic and fixed, block sizes, ZERO blocks off; 3 TiB
    // dynamic written across 2^32 sectors
    const vhdx = (name, options) =>
    {
        run(QEMU_IMG, ["convert", "-f", "raw", "-O", "vhdx", ...options, file("base.raw"), file(name)], log);
        add(name, "vhdx", "base.raw");
    };
    vhdx("dynamic.vhdx", []);
    vhdx("fixed.vhdx", ["-o", "subformat=fixed"]);
    vhdx("1m.vhdx", ["-o", "block_size=1M"]);
    vhdx("256m.vhdx", ["-o", "block_size=256M"]);
    run(QEMU_IMG, ["create", "-q", "-f", "vhdx", "-o", "block_state_zero=off", file("io.vhdx"), "64M"], log);
    run(QEMU_IO, ["-f", "vhdx", "-c", "write -q -s " + pattern + " 1048576 2097152", "-c", "write -q -z 1048576 1048576",
        "-c", "write -q -P 0x42 40000000 4096", file("io.vhdx")], log);
    run(QEMU_IMG, ["convert", "-f", "vhdx", "-O", "raw", file("io.vhdx"), file("io.vhdx.raw")], log);
    add("io.vhdx", "vhdx", "io.vhdx.raw");
    run(QEMU_IMG, ["create", "-q", "-f", "vhdx", file("3t.vhdx"), String(TB3)], log);
    run(QEMU_IO, ["-f", "vhdx", ...big_writes.flatMap(([offset, length]) => ["-c", "write -q -s " + pattern + " " + offset + " " + length]),
        file("3t.vhdx")], log);
    add("3t.vhdx", "vhdx", null, { size: TB3, writes: big_writes, pattern: "pattern.bin" });

    // features that are refused
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1,extended_l2=on", file("extl2.qcow2"), "16M"], log);
    // (the data file's name relative to the working directory: the image
    // records the path given)
    run(QEMU_IMG, ["create", "-q", "-f", "qcow2", "-o", "compat=1.1,data_file=" + file("data-file.raw"), file("data-file.qcow2"), "16M"], log);
    // (a test key, nothing secret)
    run(QEMU_IMG, ["create", "-q", "--object", "secret,id=sec0,data=v86test", "-f", "qcow2",
        "-o", "encrypt.format=luks,encrypt.key-secret=sec0,encrypt.iter-time=10", file("luks.qcow2"), "16M"], log);
    add("extl2.qcow2", "qcow2", null, { refused: "extended L2" });
    add("data-file.qcow2", "qcow2", null, { refused: "external data file" });
    add("luks.qcow2", "qcow2", null, { refused: "encrypted" });

    // (QEMU's names of the formats: a fixed VHD is not probed)
    const qemu_format = format => format === "vhd" ? "vpc" : format;
    for(const sample of Object.values(samples))
    {
        sample.sha256 = sha256_file(file(sample.file));
        sample.length = fs.statSync(file(sample.file)).size;
        if(!sample.size)
        {
            sample.size = Number(JSON.parse(run(QEMU_IMG, ["info", "--output=json", "-U", "-f", qemu_format(sample.format),
                file(sample.file)], []))["virtual-size"]);
        }
    }
    for(const sample of Object.values(samples))
    {
        // (qemu-img has no check of VHD)
        if(!sample.refused && sample.format !== "vhd") run(QEMU_IMG, ["check", "-q", "-U", "-f", qemu_format(sample.format), file(sample.file)], log);
    }
    const manifest = { samples_version: SAMPLES_VERSION, tool: version, dir: SAMPLES_DIR, commands: log, samples };
    fs.writeFileSync(manifest_path, JSON.stringify(manifest, null, 2));
    return manifest;
}

/**
 * Zstandard for the readers in Node (v86 itself uses its core's decoder):
 * the first frame of the data (a QCOW2 cluster's bytes end in a sector, the
 * rest is not the frame's), found by walking its blocks, decoded by zlib
 * @param {number} size
 * @param {Uint8Array} bytes
 */
export function zstd_decompress(size, bytes)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    if(view.getUint32(0, true) !== 0xFD2FB528) throw new Error("not a Zstandard frame");
    const descriptor = bytes[4];
    const single_segment = descriptor >> 5 & 1;
    const fcs = [single_segment ? 1 : 0, 2, 4, 8][descriptor >> 6];
    let position = 5 + (single_segment ? 0 : 1) + [0, 1, 2, 4][descriptor & 3] + fcs;
    for(;;)
    {
        const header = bytes[position] | bytes[position + 1] << 8 | bytes[position + 2] << 16;
        const type = header >> 1 & 3, block_size = header >> 3;
        position += 3 + (type === 1 ? 1 : block_size);
        if(header & 1) break;
    }
    if(descriptor & 4) position += 4;
    const output = zlib.zstdDecompressSync(bytes.subarray(0, position));
    return new Uint8Array(output.buffer, output.byteOffset, Math.min(size, output.length));
}

/**
 * The expected bytes of [offset, offset + length) of a sample without a RAW
 * reference: its writes (from the pattern file) and zeros
 */
export function expected_from_writes(sample, offset, length)
{
    const pattern = fs.readFileSync(path.join(SAMPLES_DIR, sample.pattern));
    const result = new Uint8Array(length);
    for(const [start, size] of sample.writes)
    {
        const from = Math.max(start, offset), to = Math.min(start + size, offset + length);
        if(from < to) result.set(pattern.subarray(from - start, to - start), from - offset);
    }
    return result;
}

if(process.argv[1] === fileURLToPath(import.meta.url))
{
    const manifest = make_samples();
    console.log(manifest.tool);
    for(const [name, sample] of Object.entries(manifest.samples))
    {
        console.log(name.padEnd(20), String(sample.length).padStart(10), sample.sha256);
    }
}
                                                                                              source/v64/tests/image/sector_size.mjs                                                              0000755 0000000 0000000 00000031142 00000000000 015160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Logical sectors of 4096 bytes in the image layer (docs/disk-image-formats-plan.md,
// the appendix's "4K 逻辑扇区"):
// - the VHDX builder (tests/image/tiny_vhdx.mjs) against qemu-img: its
//   512-byte images pass qemu-img check and convert to the data written,
//   also past a chunk's sector bitmap entry (qemu-img neither makes nor
//   opens VHDX images with 4096-byte logical sectors)
// - VHDX with 4096-byte logical sectors: qemu-img's dynamic.vhdx with its
//   logical sector size changed (the BAT is the same while the disk has
//   fewer blocks than a chunk) reads as base.raw; a built 100 GiB image with
//   blocks of 1 MiB (a chunk: 32 GiB) across its sector bitmap entries, ZERO
//   and NOT_PRESENT blocks
// - the descriptor's logical_sector_size: for RAW, QCOW2, VHD, VDI and VMDK
//   images (whose files have no sector size of their own), a VHDX's own must
//   agree, a parent that has one gives it to its child; 512 or 4096 only, a
//   size that is not a multiple of it, hard disks only

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { make_samples, SAMPLES_DIR, random_bytes, random_generator } from "./samples.mjs";
import { sample_file, read, open_sample, open_bytes, rejects, compare } from "./helpers.mjs";
import { build_vhdx } from "./tiny_vhdx.mjs";
import { check_image_options, create_disk_image, open_image } from "../../src/image/factory.js";
import { settings } from "./helpers.mjs";

process.on("unhandledRejection", exn => { throw exn; });

const QEMU_IMG = process.env.QEMU_IMG || (fs.existsSync("/opt/homebrew/bin/qemu-img") ? "/opt/homebrew/bin/qemu-img" : "qemu-img");
const manifest = make_samples();
const base = fs.readFileSync(sample_file("base.raw"));
const KiB = 1024, MiB = 1024 * 1024, GiB = 1024 * MiB;
const work = path.join(SAMPLES_DIR, "..", "disk-image-sector-size");
fs.rmSync(work, { recursive: true, force: true });
fs.mkdirSync(work, { recursive: true });
const qemu_img = (...args) => execFileSync(QEMU_IMG, args, { stdio: ["ignore", "pipe", "pipe"] }).toString();
/** a file read in ranges (an async URL in Node) */
const open_file = (file, format, extra = {}) => open_image("hda", { url: file, async: true, format, ...extra }, settings);

const next = random_generator(0x4096);
const chunk = (offset, length) => [offset, random_bytes(next, length)];
/** the bytes of `data` ([offset, bytes]) in [offset, offset + length) */
const expected = (data, offset, length) =>
{
    const result = new Uint8Array(length);
    for(const [start, bytes] of data)
    {
        const from = Math.max(start, offset), to = Math.min(start + bytes.length, offset + length);
        if(from < to) result.set(bytes.subarray(from - start, to - start), from - offset);
    }
    return result;
};

// the builder against qemu-img: 5 GiB of 1 MiB blocks with 512-byte
// sectors (a chunk of 4096 blocks, 4 GiB: the sector bitmap entry 4096)
{
    const data = [chunk(0, 8192), chunk(4 * GiB - 4096, 12288), chunk(5 * GiB - 65536, 65536)];
    const built = build_vhdx({ size: 5 * GiB, logical_sector_size: 512, data, zero: [3 * MiB] });
    assert.equal(built.chunk_ratio, 4096);
    const file = path.join(work, "built-512.vhdx");
    fs.writeFileSync(file, built.image);
    const check = qemu_img("check", "-f", "vhdx", file);
    assert.match(check, /No errors were found/, "qemu-img check: " + check);
    const info = JSON.parse(qemu_img("info", "--output=json", "-f", "vhdx", file));
    assert.equal(info["virtual-size"], 5 * GiB, "qemu-img: the virtual size");
    // (converted whole: a sparse file of 5 GiB)
    const raw = path.join(work, "built-512.raw");
    qemu_img("convert", "-f", "vhdx", "-O", "raw", file, raw);
    const fd = fs.openSync(raw, "r");
    const reader = await open_bytes(built.image, "vhdx");
    assert.equal(reader.logical_sector_size, 512);
    for(const [offset, length] of [[0, 65536], [4 * GiB - 65536, 131072], [5 * GiB - 131072, 131072], [3 * MiB, 65536]])
    {
        const part = new Uint8Array(length);
        assert.equal(fs.readSync(fd, part, 0, length, offset), length);
        compare(part, expected(data, offset, length), "qemu-img reads the built image at " + offset);
        compare(await read(reader, offset, length), expected(data, offset, length), "v86 reads the built image at " + offset);
    }
    fs.closeSync(fd);
    fs.rmSync(raw);
    console.log("ok - the VHDX builder: qemu-img check passes, qemu-img and v86 read what was written, across a sector bitmap entry");
}

// qemu-img's dynamic.vhdx with 4096-byte logical sectors
const image = fs.readFileSync(sample_file("dynamic.vhdx"));
const view = b => new DataView(b.buffer, b.byteOffset, b.length);
const metadata_offset = (() =>
{
    const v = view(image);
    for(let i = 0; i < v.getUint32(192 * KiB + 8, true); i++)
    {
        const entry = 192 * KiB + 16 + i * 32;
        if(v.getUint32(entry, true) === 0x8B7CA206) return Number(v.getBigUint64(entry + 16, true));
    }
    throw new Error("no metadata region");
})();
const item = (b, guid_first) =>
{
    const v = view(b);
    for(let i = 0; i < v.getUint16(metadata_offset + 10, true); i++)
    {
        const entry = metadata_offset + 32 + i * 32;
        if(v.getUint32(entry, true) === guid_first) return metadata_offset + v.getUint32(entry + 16, true);
    }
    throw new Error("no metadata item " + guid_first.toString(16));
};
const LOGICAL = 0x8141BF1D, PHYSICAL = 0xCDA348C7;
const image_4k = new Uint8Array(image);
view(image_4k).setUint32(item(image_4k, LOGICAL), 4096, true);
view(image_4k).setUint32(item(image_4k, PHYSICAL), 4096, true);
{
    for(const how of ["memory", "url"])
    {
        let reader;
        if(how === "memory") reader = await open_bytes(image_4k, "vhdx");
        else
        {
            fs.writeFileSync(path.join(work, "dynamic-4k.vhdx"), image_4k);
            reader = await open_file(path.join(work, "dynamic-4k.vhdx"), "auto");
        }
        assert.equal(reader.logical_sector_size, 4096, "the image's sector size");
        assert.equal(reader.virtual_size, base.length);
        for(let offset = 0; offset < base.length; offset += MiB)
        {
            compare(await read(reader, offset, MiB), base.subarray(offset, offset + MiB), "4K dynamic.vhdx at " + offset);
        }
        for(const [offset, length] of [[4096, 4096], [base.length - 4096, 4096], [12288, 3 * 65536]])
        {
            compare(await read(reader, offset, length), base.subarray(offset, offset + length), "4K dynamic.vhdx range " + offset);
        }
    }
    // a disk of 4096-byte sectors for the devices
    const disk = create_disk_image("hda", { buffer: image_4k.slice().buffer, format: "vhdx" }, settings);
    await disk.load();
    assert.equal(disk.logical_sector_size, 4096, "the device's sector size");
    assert.equal(disk.byteLength, base.length);
    // (QEMU does not open such an image: the reference is the unchanged one's)
    assert.throws(() => qemu_img("info", "-f", "vhdx", path.join(work, "dynamic-4k.vhdx")), /Operation not supported/,
        "qemu-img refuses a VHDX with 4096-byte logical sectors");
    console.log("ok - VHDX with 4096-byte logical sectors (qemu-img's dynamic.vhdx, its sector sizes changed): reads as base.raw " +
        "(qemu-img itself does not open it)");
}

// a built 100 GiB 4K image: blocks of 1 MiB, a chunk of 32768 blocks (32 GiB)
{
    const data = [chunk(0, 8192), chunk(32 * GiB - 8192, 16384), chunk(64 * GiB + 4096, 4096), chunk(100 * GiB - 4096, 4096)];
    const built = build_vhdx({ size: 100 * GiB, logical_sector_size: 4096, data, zero: [50 * GiB] });
    assert.equal(built.chunk_ratio, 32768);
    const reader = await open_bytes(built.image, "vhdx");
    assert.equal(reader.logical_sector_size, 4096);
    assert.equal(reader.virtual_size, 100 * GiB);
    assert.equal(reader.bat_index(32768), 32769, "the sector bitmap entry after the first chunk");
    for(const [offset, length] of [[0, 65536], [32 * GiB - 65536, 131072], [64 * GiB, 65536], [100 * GiB - 65536, 65536],
        [50 * GiB, MiB], [80 * GiB, MiB]])
    {
        compare(await read(reader, offset, length), expected(data, offset, length), "the built 4K image at " + offset);
    }
    // a block whose entry is the sector bitmap's: the payload entries around it are the disk's
    const shifted = new Uint8Array(built.image);
    view(shifted).setBigUint64(built.bat_offset + 32768 * 8, 6n | 1n << 20n, true);
    const shifted_reader = await open_bytes(shifted, "vhdx");
    compare(await read(shifted_reader, 32 * GiB - 8192, 16384), expected(data, 32 * GiB - 8192, 16384), "a sector bitmap entry is not a block's");
    console.log("ok - a built 100 GiB VHDX with 4096-byte sectors: across the sector bitmap entries, ZERO and NOT_PRESENT blocks");
}

// the descriptor's logical_sector_size
{
    const option = { logical_sector_size: 4096 };
    for(const [name, format] of [["v3.qcow2", "qcow2"], ["dynamic.vhd", "vhd"], ["dynamic.vdi", "vdi"], ["sparse.vmdk", "vmdk"]])
    {
        const reader = await open_sample(name, format, "url", option);
        assert.equal(reader.logical_sector_size, 4096, name);
        const plain = await open_sample(name, format, "url");
        assert.equal(plain.logical_sector_size, 512, name + " without the option");
        compare(await read(reader, 65536, 65536), await read(plain, 65536, 65536), name + ": the same data");
    }
    // RAW through the factory (as a parent is: format "raw")
    const raw = await open_bytes(base, "raw", option);
    assert.equal(raw.logical_sector_size, 4096);
    // a size that is not a multiple of 4096
    await rejects(open_bytes(base.subarray(0, base.length - 512), "raw", option), /size 67108352 is not a multiple of its 4096-byte sectors/, "config");
    assert.equal((await open_bytes(base.subarray(0, base.length - 512), "raw")).logical_sector_size, 512, "512: as before");
    // a VHDX's own must agree
    await rejects(open_bytes(image_4k, "vhdx", { logical_sector_size: 512 }),
        /logical sectors of 512 bytes \(logical_sector_size\), but the image's are 4096 bytes/, "config");
    await rejects(open_bytes(new Uint8Array(image), "vhdx", option),
        /logical sectors of 4096 bytes \(logical_sector_size\), but the image's are 512 bytes/, "config");
    assert.equal((await open_bytes(image_4k, "vhdx", option)).logical_sector_size, 4096, "the same: accepted");
    assert.equal((await open_bytes(new Uint8Array(image), "vhdx", { logical_sector_size: 512 })).logical_sector_size, 512);
    console.log("ok - logical_sector_size of the descriptor: for formats without their own, a VHDX's must agree");
}

// a parent with a sector size gives it to its child; the child's descriptor must agree
{
    const child = path.join(work, "child-of-4k.qcow2");
    qemu_img("create", "-q", "-f", "qcow2", "-u", "-o", "compat=1.1", "-b", "parent-4k.vhdx", "-F", "vhdx", child, String(base.length));
    const backing = { buffer: image_4k.slice().buffer, format: "vhdx" };
    const reader = await open_file(child, "qcow2", { backing });
    assert.equal(reader.logical_sector_size, 4096, "the child of a 4K parent");
    compare(await read(reader, 0, MiB), base.subarray(0, MiB), "the child reads the parent");
    await rejects(open_file(child, "qcow2", { backing, logical_sector_size: 512 }),
        /logical sectors of 512 bytes \(logical_sector_size\), but the parent image's are 4096 bytes/, "config");
    // a parent without a sector size of its own: the child's
    const plain_parent = await open_file(child, "qcow2", { backing: { buffer: new Uint8Array(image).buffer, format: "vhdx" } });
    assert.equal(plain_parent.logical_sector_size, 512, "a 512-byte VHDX parent");
    console.log("ok - a child image takes its parent's 4096-byte sectors; a descriptor's 512 then is an error");
}

// options: the values, hard disks only
{
    for(const value of [1024, 0, "4096", 520, 8192])
    {
        assert.throws(() => check_image_options("hda", { buffer: new ArrayBuffer(8192), logical_sector_size: value }, true),
            /logical_sector_size/, String(value));
    }
    assert.throws(() => check_image_options("cdrom", { buffer: new ArrayBuffer(8192), logical_sector_size: 4096 }, false),
        /logical_sector_size is for hard disks/);
    assert.throws(() => check_image_options("fda", { buffer: new ArrayBuffer(8192), logical_sector_size: 512 }, false),
        /logical_sector_size is for hard disks/);
    assert.equal(check_image_options("hda", { buffer: new ArrayBuffer(8192), logical_sector_size: 4096 }, true), undefined,
        "RAW: a buffer of src/buffer.js");
    console.log("ok - logical_sector_size: 512 or 4096, for hard disks");
}

fs.rmSync(work, { recursive: true, force: true });
console.log("sector size tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/image/sector_size_guest.mjs                                                        0000755 0000000 0000000 00000017720 00000000000 016375  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Linux on disks of 4096-byte logical sectors (docs/disk-image-formats-plan.md,
// the appendix's "4K 逻辑扇区"): the kernel of images/linux4.iso (Linux 4.16)
// booted directly with its CD as the root, two such disks, a RAW one
// (logical_sector_size 4096) and a VHDX image with 4096-byte sectors
// (tests/image/tiny_vhdx.mjs), on
// - i440FX: IDE (ata_piix), with DMA;
// - Q35: AHCI (native command queuing).
// (Not PIO: this kernel's libata counts PIO data blocks of 512 bytes for
// reads and writes whatever the sector size, and waits for an interrupt
// after each, where the device asks for one per 4096-byte block as ATA
// has it; tests/devices/disk_sector_size.js checks the PIO protocol.)
// The guest's sd driver must see 4096-byte logical (and physical) blocks
// and the disks' size; it reads what the host put there, writes 2 MiB
// whose MD5 the host finds in the image, reads it back after dropping its
// caches; it sees no libata errors. SECTOR_GUEST selects machines (ide,
// ahci; comma separated).

import assert from "node:assert/strict";
import fs from "node:fs";
import { createHash as create_hash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { build_vhdx } from "./tiny_vhdx.mjs";

process.on("unhandledRejection", exn => { throw exn; });

const root = fileURLToPath(new URL("../../", import.meta.url));
const SHOW_LOGS = +process.env.SHOW_LOGS;
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const ISO = root + "images/linux4.iso";
const MACHINES = process.env.SECTOR_GUEST ? process.env.SECTOR_GUEST.split(",") : ["ide", "ahci"];

/**
 * A file from an ISO9660 image (plain names, without version or Rock Ridge),
 * as tests/devices/acpi_guest.js reads the kernel
 * @param {string} file
 * @param {!Array<string>} names
 * @return {!ArrayBuffer}
 */
function iso_file(file, names)
{
    const iso = fs.readFileSync(file);
    let extent = iso.readUInt32LE(16 * 2048 + 156 + 2), size = iso.readUInt32LE(16 * 2048 + 156 + 10);
    for(const name of names)
    {
        let found = false;
        for(let at = extent * 2048; at < extent * 2048 + size;)
        {
            const length = iso[at];
            if(!length) { at = (Math.floor(at / 2048) + 1) * 2048; continue; }
            const entry = iso.toString("latin1", at + 33, at + 33 + iso[at + 32]).replace(/;\d+$/, "").replace(/\.$/, "");
            if(entry === name)
            {
                extent = iso.readUInt32LE(at + 2);
                size = iso.readUInt32LE(at + 10);
                found = true;
                break;
            }
            at += length;
        }
        assert.ok(found, name + " in " + file);
    }
    return iso.buffer.slice(iso.byteOffset + extent * 2048, iso.byteOffset + extent * 2048 + size);
}
const bzimage = iso_file(ISO, ["BOOT", "BZIMAGE"]);

const md5 = bytes => create_hash("md5").update(bytes).digest("hex");
const RAW_SIZE = 32 << 20, VHDX_SIZE = 48 << 20;
const PROMPT = /~% $/;

for(const kind of MACHINES)
{
    const raw = new Uint8Array(RAW_SIZE).map((_, i) => i * 7 + (i >> 12) & 0xFF);
    const vhdx_data = new Uint8Array(4 << 20).map((_, i) => i * 13 + (i >> 9) & 0xFF);
    const vhdx = build_vhdx({ size: VHDX_SIZE, logical_sector_size: 4096, data: [[0, vhdx_data]] });
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: root + "bios/seabios.bin" },
        vga_bios: { url: root + "bios/vgabios.bin" },
        machine_type: kind === "ahci" ? "q35" : undefined,
        memory_size: 256 << 20,
        autostart: true,
        log_level: 0,
        cdrom: { url: ISO },
        bzimage: { buffer: bzimage },
        cmdline: "root=/dev/sr0 nokaslr",
        hda: { buffer: raw.buffer, logical_sector_size: 4096 },
        hdb: { buffer: vhdx.image.buffer, format: "vhdx" },
    });
    let serial = "";
    emulator.add_listener("serial0-output-byte", byte =>
    {
        const c = String.fromCharCode(byte);
        if(SHOW_LOGS) process.stdout.write(c);
        serial += c;
    });
    const wait = async (what, timeout) =>
    {
        const start = Date.now();
        while(!PROMPT.test(serial))
        {
            if(Date.now() - start > timeout) throw new Error(kind + ": timed out waiting for " + what + "; serial:\n" + serial.slice(-2000));
            await new Promise(resolve => setTimeout(resolve, 50));
        }
    };
    const command = async (text, timeout = 120000) =>
    {
        serial = "";
        emulator.serial0_send(text + "\n");
        await wait(JSON.stringify(text), timeout);
        return serial.slice(text.length).replace(PROMPT, "");
    };
    try
    {
        await wait("the shell", 300000);
        const sizes = await command("for d in sda sdb; do echo DISK $d $(cat /sys/block/$d/queue/logical_block_size) " +
            "$(cat /sys/block/$d/queue/physical_block_size) $(cat /sys/block/$d/size); done");
        const disk = name => sizes.match(new RegExp("DISK " + name + " (\\d+) (\\d+) (\\d+)"))?.slice(1).map(Number);
        assert.deepEqual(disk("sda"), [4096, 4096, RAW_SIZE / 512], kind + ": sda (RAW): " + sizes);
        assert.deepEqual(disk("sdb"), [4096, 4096, VHDX_SIZE / 512], kind + ": sdb (VHDX): " + sizes);
        const dmesg = await command("dmesg");
        assert.match(dmesg, /\[sda\] 8192 4096-byte logical blocks/, kind + ": sd's message for sda");
        assert.match(dmesg, /\[sdb\] 12288 4096-byte logical blocks/, kind + ": sd's message for sdb");
        if(kind === "ide") assert.match(dmesg, /ata1\.00: configured for MWDMA2/, "DMA: " + dmesg);
        if(kind === "ahci") assert.match(dmesg, /ata1\.00: .*NCQ \(depth/, "NCQ: " + dmesg);

        // what the host put there
        const read = await command("dd if=/dev/sda bs=4096 count=1024 2>/dev/null | md5sum; dd if=/dev/sdb bs=4096 count=1024 2>/dev/null | md5sum");
        const read_sums = read.match(/[0-9a-f]{32}/g);
        assert.deepEqual(read_sums, [md5(raw.subarray(0, 4 << 20)), md5(vhdx_data)], kind + ": the disks' first 4 MiB: " + read);

        // 2 MiB written, at 4096-byte sector 1000 of sda and 3000 of sdb
        const written = await command("dd if=/dev/urandom of=/tmp/x bs=4096 count=512 2>/dev/null; md5sum /tmp/x; " +
            "dd if=/tmp/x of=/dev/sda bs=4096 seek=1000 conv=fsync 2>/dev/null; dd if=/tmp/x of=/dev/sdb bs=4096 seek=3000 conv=fsync 2>/dev/null; " +
            "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda bs=4096 skip=1000 count=512 2>/dev/null | md5sum; " +
            "dd if=/dev/sdb bs=4096 skip=3000 count=512 2>/dev/null | md5sum; " +
            // (and in 512-byte reads, which the page cache makes 4096-byte ones)
            "dd if=/dev/sdb bs=512 skip=24000 count=4096 2>/dev/null | md5sum");
        const sums = written.match(/[0-9a-f]{32}/g);
        assert.ok(sums && sums.length === 4 && sums.every(s => s === sums[0]), kind + ": read back what was written: " + written);
        assert.equal(md5(raw.subarray(1000 * 4096, 1512 * 4096)), sums[0], kind + ": the RAW image holds the guest's data");
        const hdb = emulator.disk_buffer("hdb");
        const in_vhdx = await new Promise((resolve, reject) => hdb.get(3000 * 4096, 2 << 20, (data, error) => error ? reject(error) : resolve(data)));
        assert.equal(md5(in_vhdx), sums[0], kind + ": the VHDX disk holds the guest's data (in its overlay)");
        assert.equal(md5(raw.subarray(1512 * 4096, 1513 * 4096)), md5(new Uint8Array(4096).map((_, i) => (1512 * 4096 + i) * 7 + (1512) & 0xFF)),
            kind + ": the sector after the write is unchanged");

        const errors = await command("dmesg");
        assert.ok(!/exception Emask|failed command|hard resetting link|I\/O error|timeout/i.test(errors), kind + ": no disk errors: " + errors);
        console.log("ok - " + kind + ": Linux sees 4096-byte logical blocks on the RAW and the VHDX disk, reads them, writes 2 MiB, " +
            "reads it back; the images hold it");
    }
    finally
    {
        await emulator.destroy();
    }
}
console.log("sector size guest tests passed");
                                                source/v64/tests/image/tiny_qcow2.mjs                                                               0000644 0000000 0000000 00000005603 00000000000 014725  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A small QCOW2 image built in memory, for the device tests (they run without
// qemu-img; tests/image/qcow2.mjs checks the reader against qemu-img's
// images): version 3, data clusters where given, zero clusters, damaged L2
// entries on request. The refcounts are not kept (the reader does not read
// them), so qemu-img check would complain.

/**
 * @param {{size: number, cluster_bits?: number, data?: Array<[number, Uint8Array]>,
 *          zero?: Array<number>, damaged?: Array<number>}} options
 *   data: [guest offset (cluster aligned), bytes (whole clusters)];
 *   zero: guest offsets of zero clusters; damaged: guest offsets of clusters
 *   whose L2 entry has a reserved bit set
 * @return {Uint8Array}
 */
export function build_qcow2({ size, cluster_bits = 16, data = [], zero = [], damaged = [] })
{
    const cluster = 2 ** cluster_bits;
    const l2_entries = cluster / 8;
    const l1_size = Math.ceil(size / (cluster * l2_entries));
    const l1_clusters = Math.max(1, Math.ceil(l1_size * 8 / cluster));
    // cluster 0: header, then the L1 table, an empty refcount table, then
    // L2 tables and data as needed
    let next = 1 + l1_clusters + 1;
    const l2_tables = new Map();
    const clusters = [];
    const l2_for = guest =>
    {
        const index = Math.floor(guest / (cluster * l2_entries));
        if(!l2_tables.has(index))
        {
            l2_tables.set(index, { at: next++ * cluster, table: new Uint8Array(cluster) });
        }
        return [l2_tables.get(index), Math.floor(guest / cluster) % l2_entries];
    };
    const set_entry = (guest, value) =>
    {
        const [l2, index] = l2_for(guest);
        new DataView(l2.table.buffer).setBigUint64(index * 8, value);
    };
    for(const [guest, bytes] of data)
    {
        for(let i = 0; i < bytes.length; i += cluster)
        {
            const at = next++ * cluster;
            const chunk = new Uint8Array(cluster);
            chunk.set(bytes.subarray(i, i + cluster));
            clusters.push([at, chunk]);
            set_entry(guest + i, BigInt(at) | 1n << 63n);
        }
    }
    for(const guest of zero) set_entry(guest, 1n);
    for(const guest of damaged) set_entry(guest, BigInt((next + 1000) * cluster) | 2n);

    const image = new Uint8Array(next * cluster);
    const view = new DataView(image.buffer);
    view.setUint32(0, 0x514649FB);
    view.setUint32(4, 3);
    view.setUint32(20, cluster_bits);
    view.setBigUint64(24, BigInt(size));
    view.setUint32(36, l1_size);
    view.setBigUint64(40, BigInt(cluster));
    view.setBigUint64(48, BigInt((1 + l1_clusters) * cluster));
    view.setUint32(56, 1);
    view.setUint32(96, 4);
    view.setUint32(100, 104);
    for(const [index, { at, table }] of l2_tables)
    {
        view.setBigUint64(cluster + index * 8, BigInt(at) | 1n << 63n);
        image.set(table, at);
    }
    for(const [at, chunk] of clusters) image.set(chunk, at);
    return image;
}
                                                                                                                             source/v64/tests/image/tiny_vhdx.mjs                                                                0000644 0000000 0000000 00000015462 00000000000 014647  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A small VHDX image built in memory ([MS-VHDX] 2.2), for the tests of
// logical sectors of 4096 bytes, which qemu-img does not make: the file type
// identifier, two headers and two region tables with their CRC-32C, an empty
// log, the metadata (block size, virtual size, disk ID, logical and physical
// sector sizes) and the BAT, whose sector bitmap entries follow every
// chunk_ratio = 2^23 * logical sector size / block size payload blocks.
// Blocks with data are FULLY_PRESENT (the rest of such a block is zeros),
// blocks listed in `zero` are ZERO, the others NOT_PRESENT. tests/image/
// sector_size.mjs checks the builder's 512-byte images against qemu-img.

import { crc32c } from "../../src/image/vhdx.js";

const KiB = 1024, MiB = 1024 * 1024;

/**
 * A GUID's 16 bytes ([MS-DTYP]: the first three fields little-endian)
 * @param {string} text
 * @return {!Uint8Array}
 */
function guid_bytes(text)
{
    const hex = text.replace(/-/g, "");
    const bytes = Uint8Array.from({ length: 16 }, (_, i) => parseInt(hex.substr(i * 2, 2), 16));
    return Uint8Array.from([3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15].map(i => bytes[i]));
}

const GUID_BAT = "2dc27766-f623-4200-9d64-115e9bfd4a08";
const GUID_METADATA = "8b7ca206-4790-4b9a-b8fe-575f050f886e";
const GUID_FILE_PARAMETERS = "caa16737-fa36-4d43-b3b6-33f0aa44e76b";
const GUID_VIRTUAL_DISK_SIZE = "2fa54224-cd1b-4876-b211-5dbed83bf4b8";
const GUID_VIRTUAL_DISK_ID = "beca12ab-b2e6-4523-93ef-c309e000c746";
const GUID_LOGICAL_SECTOR_SIZE = "8141bf1d-a96f-4709-ba47-f233a8faab5f";
const GUID_PHYSICAL_SECTOR_SIZE = "cda348c7-445d-4471-9cc9-e9885251c556";

const PAYLOAD_NOT_PRESENT = 0, PAYLOAD_ZERO = 2, PAYLOAD_FULLY_PRESENT = 6;

/**
 * @param {{size: number, block_size?: number, logical_sector_size?: number, physical_sector_size?: number,
 *          data?: Array<[number, Uint8Array]>, zero?: Array<number>}} options
 *   data: [guest offset, bytes]; zero: guest offsets of ZERO blocks
 * @return {{image: !Uint8Array, chunk_ratio: number, bat_offset: number, bat_index: function(number):number}}
 */
export function build_vhdx({ size, block_size = MiB, logical_sector_size = 4096, physical_sector_size = logical_sector_size,
    data = [], zero = [] })
{
    const chunk_ratio = 2 ** 23 * logical_sector_size / block_size;
    const payload_blocks = Math.ceil(size / block_size);
    const bat_entries = payload_blocks + Math.floor((payload_blocks - 1) / chunk_ratio);
    const bat_index = block => block + Math.floor(block / chunk_ratio);
    const LOG = 1 * MiB, METADATA = 2 * MiB, BAT = 3 * MiB;
    const bat_length = Math.ceil(bat_entries * 8 / MiB) * MiB;
    let next = BAT + bat_length;

    // the blocks with data, in the order of their first byte
    const blocks = new Map();
    for(const [offset, bytes] of data)
    {
        for(let at = offset; at < offset + bytes.length;)
        {
            const block = Math.floor(at / block_size);
            if(!blocks.has(block))
            {
                blocks.set(block, { file_offset: next, bytes: new Uint8Array(block_size) });
                next += block_size;
            }
            const in_block = at - block * block_size;
            const count = Math.min(block_size - in_block, offset + bytes.length - at);
            blocks.get(block).bytes.set(bytes.subarray(at - offset, at - offset + count), in_block);
            at += count;
        }
    }

    const image = new Uint8Array(next);
    const view = new DataView(image.buffer);
    image.set(new TextEncoder().encode("vhdxfile"), 0);
    // the creator (UTF-16)
    [..."v86 tests"].forEach((c, i) => view.setUint16(8 + 2 * i, c.charCodeAt(0), true));

    for(const [at, sequence] of [[64 * KiB, 1n], [128 * KiB, 2n]])
    {
        image.set(new TextEncoder().encode("head"), at);
        view.setBigUint64(at + 8, sequence, true);
        image.set(guid_bytes("11111111-2222-3333-4444-555555555555"), at + 16);
        image.set(guid_bytes("66666666-7777-8888-9999-aaaaaaaaaaaa"), at + 32);
        // (the log GUID stays zero: no log to replay)
        view.setUint16(at + 64, 0, true);
        view.setUint16(at + 66, 1, true);
        view.setUint32(at + 68, MiB, true);
        view.setBigUint64(at + 72, BigInt(LOG), true);
        view.setUint32(at + 4, crc32c(image.subarray(at, at + 4 * KiB), 4), true);
    }

    for(const at of [192 * KiB, 256 * KiB])
    {
        image.set(new TextEncoder().encode("regi"), at);
        view.setUint32(at + 8, 2, true);
        const regions = [[GUID_BAT, BAT, bat_length], [GUID_METADATA, METADATA, MiB]];
        regions.forEach(([id, offset, length], i) =>
        {
            const entry = at + 16 + i * 32;
            image.set(guid_bytes(id), entry);
            view.setBigUint64(entry + 16, BigInt(offset), true);
            view.setUint32(entry + 24, length, true);
            view.setUint32(entry + 28, 1, true);
        });
        view.setUint32(at + 4, crc32c(image.subarray(at, at + 64 * KiB), 4), true);
    }

    image.set(new TextEncoder().encode("metadata"), METADATA);
    const REQUIRED = 4, VIRTUAL_DISK = 2;
    const items = [
        [GUID_FILE_PARAMETERS, REQUIRED, bytes => { new DataView(bytes.buffer).setUint32(0, block_size, true); }, 8],
        [GUID_VIRTUAL_DISK_SIZE, REQUIRED | VIRTUAL_DISK, bytes => { new DataView(bytes.buffer).setBigUint64(0, BigInt(size), true); }, 8],
        [GUID_VIRTUAL_DISK_ID, REQUIRED | VIRTUAL_DISK, bytes => { bytes.set(guid_bytes("0123abcd-4567-89ef-0123-456789abcdef")); }, 16],
        [GUID_LOGICAL_SECTOR_SIZE, REQUIRED | VIRTUAL_DISK, bytes => { new DataView(bytes.buffer).setUint32(0, logical_sector_size, true); }, 4],
        [GUID_PHYSICAL_SECTOR_SIZE, REQUIRED | VIRTUAL_DISK, bytes => { new DataView(bytes.buffer).setUint32(0, physical_sector_size, true); }, 4],
    ];
    view.setUint16(METADATA + 10, items.length, true);
    let item_offset = 64 * KiB;
    items.forEach(([id, flags, fill, length], i) =>
    {
        const entry = METADATA + 32 + i * 32;
        image.set(guid_bytes(id), entry);
        view.setUint32(entry + 16, item_offset, true);
        view.setUint32(entry + 20, length, true);
        view.setUint32(entry + 24, flags, true);
        const bytes = new Uint8Array(length);
        fill(bytes);
        image.set(bytes, METADATA + item_offset);
        item_offset += 64;
    });

    const set_entry = (block, state, file_offset) =>
        view.setBigUint64(BAT + bat_index(block) * 8, BigInt(file_offset / MiB) << 20n | BigInt(state), true);
    for(let block = 0; block < payload_blocks; block++) set_entry(block, PAYLOAD_NOT_PRESENT, 0);
    for(const offset of zero) set_entry(Math.floor(offset / block_size), PAYLOAD_ZERO, 0);
    for(const [block, { file_offset, bytes }] of blocks)
    {
        set_entry(block, PAYLOAD_FULLY_PRESENT, file_offset);
        image.set(bytes, file_offset);
    }
    return { image, chunk_ratio, bat_offset: BAT, bat_index };
}
                                                                                                                                                                                                              source/v64/tests/image/vhd_vdi.mjs                                                                  0000755 0000000 0000000 00000017264 00000000000 014263  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// VHD and VDI (docs/disk-image-formats-plan.md P3) against qemu-img: fixed
// and dynamic images read whole and in ranges as qemu-img reads them (the
// VHD's size from its CHS geometry or exact, as QEMU decides), large sparse
// ones beyond 4 GiB and across 2^32 sectors; damaged footers, headers and
// tables, each with what is wrong; differencing images refused.

import assert from "node:assert/strict";
import fs from "node:fs";
import { make_samples } from "./samples.mjs";
import { sample_file, read, open_sample, open_bytes, rejects, compare, check_against_reference, check_writes } from "./helpers.mjs";

process.on("unhandledRejection", exn => { throw exn; });

const manifest = make_samples();
let compared = 0;

// VHD
for(const name of ["dynamic.vhd", "dynamic-force.vhd", "fixed.vhd", "fixed-force.vhd"])
{
    compared += await check_against_reference(manifest, name, "vhd");
    const auto = await open_sample(name, "auto", "url");
    assert.equal(auto.format, "vhd", name + ": auto");
    assert.equal(auto.virtual_size, manifest.samples[name].size, name + ": the size qemu-img reports");
}
assert.equal((await open_sample("dynamic.vhd", "vpc", "url")).format, "vhd", "vpc: QEMU's name");
assert.notEqual((await open_sample("dynamic.vhd", "vhd", "url")).virtual_size, 64 << 20, "the CHS geometry (creator qemu)");
assert.equal((await open_sample("dynamic-force.vhd", "vhd", "url")).virtual_size, 64 << 20, "the current size (creator qem2)");
console.log("ok - VHD: dynamic and fixed, the size from the geometry or exact, as qemu-img reads them; auto, vpc");
await check_writes(manifest, "100g.vhd", "vhd");
console.log("ok - VHD: 100 GiB dynamic, beyond 4 GiB and at the end");

const be32 = (b, o) => (b[o] << 24 | b[o + 1] << 16 | b[o + 2] << 8 | b[o + 3]) >>> 0;
const set_be32 = (b, o, v) => { b[o] = v >>> 24; b[o + 1] = v >>> 16; b[o + 2] = v >>> 8; b[o + 3] = v; };
const checksum = (b, start, length, at) =>
{
    let sum = 0;
    for(let i = start; i < start + length; i++) if(i < start + at || i >= start + at + 4) sum += b[i];
    set_be32(b, start + at, ~sum >>> 0);
};
{
    const dynamic = fs.readFileSync(sample_file("dynamic-force.vhd"));
    const header = Number(new DataView(dynamic.buffer, dynamic.byteOffset).getBigUint64(16));
    const patched = (patch, fix_footer = true, fix_header = true) =>
    {
        const b = new Uint8Array(dynamic);
        patch(b);
        if(fix_footer) checksum(b, 0, 512, 64);
        if(fix_header) checksum(b, header, 1024, 36);
        return b;
    };
    await rejects(open_bytes(patched(b => { b[100] ^= 1; }, false), "vhd"), /footer's checksum is wrong/, "corrupt");
    await rejects(open_bytes(patched(b => { b[header + 600] ^= 1; }, true, false), "vhd"), /dynamic disk header's checksum is wrong/, "corrupt");
    await rejects(open_bytes(patched(b => { b[header] = 0x41; }), "vhd"), /no dynamic disk header/, "corrupt");
    await rejects(open_bytes(patched(b => set_be32(b, 60, 4)), "vhd"), /differencing disks are not supported/, "unsupported");
    await rejects(open_bytes(patched(b => set_be32(b, 60, 5)), "vhd"), /disk type 5 is not supported/, "unsupported");
    await rejects(open_bytes(patched(b => set_be32(b, 12, 0x00020000)), "vhd"), /version 0x20000 is not supported/, "unsupported");
    await rejects(open_bytes(patched(b => set_be32(b, header + 32, 3 << 20)), "vhd"), /block size 3145728 is not a power of two/, "corrupt");
    await rejects(open_bytes(patched(b => set_be32(b, header + 28, 8)), "vhd"), /BAT .* is too small/, "corrupt");
    const bat = Number(new DataView(dynamic.buffer, dynamic.byteOffset).getBigUint64(header + 16));
    await rejects(open_bytes(dynamic.subarray(0, bat + 16), "vhd"), /the BAT .* past the end of the file/, "corrupt");
    // an unallocated block reads as zeros; a block past the end of the file too
    const unallocated = await open_bytes(patched(b => set_be32(b, bat, 0xFFFFFFFF)), "vhd");
    compare(await read(unallocated, 0, 65536), new Uint8Array(65536), "an unallocated block");
    console.log("ok - VHD: damaged footers, headers and BAT: refused with what is wrong; differencing disks refused");

    const fixed = fs.readFileSync(sample_file("fixed-force.vhd"));
    const short = new Uint8Array(fixed.length - 1024 * 1024);
    short.set(fixed.subarray(0, short.length - 512));
    short.set(fixed.subarray(fixed.length - 512), short.length - 512);
    await rejects(open_bytes(short, "vhd"), /does not fit before the footer/, "corrupt");
    await rejects(open_bytes(fixed.subarray(0, fixed.length - 1024), "vhd"), /not a vhd image/, "config");
    console.log("ok - VHD: a truncated fixed disk is refused");
}

// VDI
for(const name of ["dynamic.vdi", "static.vdi"])
{
    compared += await check_against_reference(manifest, name, "vdi");
    assert.equal((await open_sample(name, "auto", "url")).format, "vdi", name + ": auto");
}
const a = await open_sample("dynamic.vdi", "vdi", "url"), b = await open_sample("static.vdi", "vdi", "url");
assert.notEqual(a.identity()["metadata_sha256"], b.identity()["metadata_sha256"], "dynamic and fixed: other images");
console.log("ok - VDI: dynamic and fixed, as qemu-img reads them; auto");
await check_writes(manifest, "3t.vdi", "vdi");
const vdi_3t = await open_sample("3t.vdi", "vdi", "url");
const boundary = 2 ** 32 * 512;
const { expected_from_writes } = await import("./samples.mjs");
compare(await read(vdi_3t, boundary - 512, 1024), expected_from_writes(manifest.samples["3t.vdi"], boundary - 512, 1024), "across 2^32 sectors");
console.log("ok - VDI: 3 TiB dynamic, beyond 4 GiB and across 2^32 sectors");
{
    const dynamic = fs.readFileSync(sample_file("dynamic.vdi"));
    const le32 = (bytes, o, v) => new DataView(bytes.buffer, bytes.byteOffset).setUint32(o, v, true);
    const patched = patch => { const bytes = new Uint8Array(dynamic); patch(bytes); return bytes; };
    const bmap = new DataView(dynamic.buffer, dynamic.byteOffset).getUint32(0x154, true);
    await rejects(open_bytes(patched(x => le32(x, 0x40, 0)), "vdi"), /not a vdi image/, "config");
    await rejects(open_bytes(patched(x => le32(x, 0x40, 0)), "auto"), /could not be determined/, "config");
    await rejects(open_bytes(patched(x => le32(x, 0x44, 0x00010000)), "vdi"), /version 0x10000 is not supported/, "unsupported");
    await rejects(open_bytes(patched(x => le32(x, 0x4C, 4)), "vdi"), /image type 4 is not supported/, "unsupported");
    await rejects(open_bytes(patched(x => le32(x, 0x4C, 3)), "vdi"), /image type 3 is not supported/, "unsupported");
    await rejects(open_bytes(patched(x => le32(x, 0x178, 2 << 20)), "vdi"), /block size 2097152 is not supported/, "unsupported");
    await rejects(open_bytes(patched(x => le32(x, 0x17C, 512)), "vdi"), /extra block data/, "unsupported");
    await rejects(open_bytes(patched(x => { x[0x1B8] = 1; }), "vdi"), /differencing image/, "unsupported");
    await rejects(open_bytes(patched(x => le32(x, 0x180, 10)), "vdi"), /larger than its 10 blocks/, "corrupt");
    await rejects(open_bytes(patched(x => le32(x, 0x158, 0x1001)), "vdi"), /not aligned to a sector/, "corrupt");
    await rejects(open_bytes(dynamic.subarray(0, bmap + 8), "vdi"), /block map .* past the end of the file/, "corrupt");
    const beyond = await open_bytes(patched(x => le32(x, bmap, 1000)), "vdi");
    await rejects(read(beyond, 0, 512), /beyond the image's 64 blocks/, "corrupt");
    const discarded = await open_bytes(patched(x => { le32(x, bmap, 0xFFFFFFFE); le32(x, bmap + 4, 0xFFFFFFFF); }), "vdi");
    compare(await read(discarded, 0, 2 << 20), new Uint8Array(2 << 20), "discarded and unallocated blocks");
    console.log("ok - VDI: damaged headers and block maps: refused with what is wrong; differencing images refused");
}
console.log("VHD and VDI tests passed (" + (compared >> 20) + " MiB compared)");
                                                                                                                                                                                                                                                                                                                                            source/v64/tests/image/vhdx.mjs                                                                     0000755 0000000 0000000 00000017271 00000000000 013607  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// VHDX (docs/disk-image-formats-plan.md P5) against qemu-img: dynamic and
// fixed images, block sizes of 1, 32 and 256 MiB, ZERO and NOT_PRESENT
// blocks, 3 TiB across 2^32 sectors; the headers (the current one: valid,
// the higher sequence number), region tables and metadata with their
// CRC-32C; 4096-byte logical sectors (more in tests/image/sector_size.mjs);
// refused: a log to replay, a parent, unknown required regions and metadata,
// block states of differencing disks.

import assert from "node:assert/strict";
import fs from "node:fs";
import { make_samples } from "./samples.mjs";
import { sample_file, read, open_sample, open_bytes, rejects, compare, check_against_reference, check_writes } from "./helpers.mjs";
import { crc32c } from "../../src/image/vhdx.js";

process.on("unhandledRejection", exn => { throw exn; });

const manifest = make_samples();
let compared = 0;
for(const name of ["dynamic.vhdx", "fixed.vhdx", "1m.vhdx", "256m.vhdx", "io.vhdx"])
{
    compared += await check_against_reference(manifest, name, "vhdx");
    const reader = await open_sample(name, "auto", "url");
    assert.equal(reader.format, "vhdx", name + ": auto");
    console.log("ok - " + name + " (blocks of " + (reader.block_size >> 20) + " MiB): as qemu-img reads it, whole and in ranges");
}
await check_writes(manifest, "3t.vhdx", "vhdx");
{
    const { expected_from_writes } = await import("./samples.mjs");
    const reader = await open_sample("3t.vhdx", "vhdx", "url");
    const boundary = 2 ** 32 * 512;
    compare(await read(reader, boundary - 512, 1024), expected_from_writes(manifest.samples["3t.vhdx"], boundary - 512, 1024), "across 2^32 sectors");
}
console.log("ok - VHDX: 3 TiB, beyond 4 GiB and across 2^32 sectors");

// CRC-32C: the check value of "123456789"
assert.equal(crc32c(new TextEncoder().encode("123456789")), 0xE3069283);

const image = fs.readFileSync(sample_file("dynamic.vhdx"));
const KiB = 1024;
const view = b => new DataView(b.buffer, b.byteOffset, b.length);
const fix_header = (b, offset) => view(b).setUint32(offset + 4, crc32c(b.subarray(offset, offset + 4 * KiB), 4), true);
const fix_regions = (b, offset) => view(b).setUint32(offset + 4, crc32c(b.subarray(offset, offset + 64 * KiB), 4), true);
const patched = patch => { const b = new Uint8Array(image); patch(b, view(b)); return b; };
const current_header = () =>
{
    const s1 = view(image).getBigUint64(64 * KiB + 8, true), s2 = view(image).getBigUint64(128 * KiB + 8, true);
    return s1 > s2 ? 64 * KiB : 128 * KiB;
};
const other_header = () => current_header() === 64 * KiB ? 128 * KiB : 64 * KiB;
{
    // headers: the valid one with the higher sequence number
    const broken_current = await open_bytes(patched(b => { b[current_header() + 100] ^= 1; }), "vhdx");
    compare(await read(broken_current, 0, 1 << 20), fs.readFileSync(sample_file("base.raw")).subarray(0, 1 << 20), "the other header");
    await rejects(open_bytes(patched(b => { b[64 * KiB + 100] ^= 1; b[128 * KiB + 100] ^= 1; }), "vhdx"), /neither header is valid/, "corrupt");
    // a log to replay
    await rejects(open_bytes(patched(b => { b[current_header() + 48] = 1; fix_header(b, current_header()); }), "vhdx"),
        /a log to replay/, "unsupported");
    await rejects(open_bytes(patched((b, v) => { v.setUint16(current_header() + 66, 2, true); fix_header(b, current_header()); }), "vhdx"),
        /version 2 is not supported/, "unsupported");
    // region tables
    await rejects(open_bytes(patched(b => { b[192 * KiB + 100] ^= 1; b[256 * KiB + 100] ^= 1; }), "vhdx"), /neither region table is valid/, "corrupt");
    const second_table = await open_bytes(patched(b => { b[192 * KiB + 100] ^= 1; }), "vhdx");
    assert.equal(second_table.virtual_size, 64 << 20, "the second region table");
    const regions = patched((b, v) =>
    {
        // a third region: unknown and required
        for(const at of [192 * KiB, 256 * KiB])
        {
            const count = v.getUint32(at + 8, true);
            const entry = at + 16 + count * 32;
            b.fill(0x77, entry, entry + 16);
            v.setBigUint64(entry + 16, 1n << 30n, true);
            v.setUint32(entry + 24, 1 << 20, true);
            v.setUint32(entry + 28, 1, true);
            v.setUint32(at + 8, count + 1, true);
            fix_regions(b, at);
        }
    });
    await rejects(open_bytes(regions, "vhdx"), /an unknown required region/, "unsupported");
    // metadata: the table follows the region table's metadata entry
    const metadata_offset = (() =>
    {
        const v = view(image);
        for(let i = 0; i < v.getUint32(192 * KiB + 8, true); i++)
        {
            const entry = 192 * KiB + 16 + i * 32;
            if(v.getUint32(entry, true) === 0x8B7CA206) return Number(v.getBigUint64(entry + 16, true));
        }
        throw new Error("no metadata region");
    })();
    const item = (b, guid_first) =>
    {
        const v = view(b);
        for(let i = 0; i < v.getUint16(metadata_offset + 10, true); i++)
        {
            const entry = metadata_offset + 32 + i * 32;
            if(v.getUint32(entry, true) === guid_first) return { entry, data: metadata_offset + v.getUint32(entry + 16, true) };
        }
        throw new Error("no metadata item " + guid_first.toString(16));
    };
    const sectors_4k = await open_bytes(patched((b, v) => v.setUint32(item(b, 0x8141BF1D).data, 4096, true)), "vhdx");
    assert.equal(sectors_4k.logical_sector_size, 4096, "4096-byte logical sectors: the disk's");
    compare(await read(sectors_4k, 0, 1 << 20), fs.readFileSync(sample_file("base.raw")).subarray(0, 1 << 20), "4096-byte logical sectors");
    await rejects(open_bytes(patched((b, v) => v.setUint32(item(b, 0x8141BF1D).data, 1000, true)), "vhdx"), /sector sizes 1000\/\d+ are invalid/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setUint32(item(b, 0xCAA16737).data + 4, 2, true)), "vhdx"), /differencing disk/, "unsupported");
    await rejects(open_bytes(patched((b, v) => v.setUint32(item(b, 0xCAA16737).data, 3 << 20, true)), "vhdx"), /block size 3145728 is invalid/, "corrupt");
    await rejects(open_bytes(patched((b, v) => v.setBigUint64(item(b, 0x2FA54224).data, (64n << 20n) + 100n, true)), "vhdx"),
        /not a multiple of the sector size/, "corrupt");
    await rejects(open_bytes(patched((b, v) =>
    {
        const { entry } = item(b, 0x8141BF1D);
        v.setUint32(entry, 0x12345678, true);
        v.setUint32(entry + 24, v.getUint32(entry + 24, true) | 4, true);
    }), "vhdx"), /an unknown required metadata item|missing/, "");
    // the BAT: a state of differencing disks
    const bat_offset = (() =>
    {
        const v = view(image);
        for(let i = 0; i < v.getUint32(192 * KiB + 8, true); i++)
        {
            const entry = 192 * KiB + 16 + i * 32;
            if(v.getUint32(entry, true) === 0x2DC27766) return Number(v.getBigUint64(entry + 16, true));
        }
        throw new Error("no BAT");
    })();
    await rejects(open_bytes(patched(b => { b[bat_offset] = b[bat_offset] & ~7 | 7; }), "vhdx"), /state 7/, "corrupt");
    await rejects(open_bytes(patched(b => { b[bat_offset] = b[bat_offset] & ~7 | 4; }), "vhdx"), /state 4/, "corrupt");
    const not_present = await open_bytes(patched(b => { b[bat_offset] = b[bat_offset] & ~7; }), "vhdx");
    compare(await read(not_present, 0, 65536), new Uint8Array(65536), "a block not present");
    await rejects(open_bytes(image.subarray(0, bat_offset + 4), "vhdx"), /past the end of the file/, "corrupt");
    void other_header;
    console.log("ok - VHDX: headers (the current one, CRC-32C), region tables, metadata, BAT states: refused with what is wrong; " +
        "a log to replay and a parent refused, 4096-byte sectors read");
}
console.log("VHDX tests passed (" + (compared >> 20) + " MiB compared)");
                                                                                                                                                                                                                                                                                                                                       source/v64/tests/image/vmdk.mjs                                                                     0000755 0000000 0000000 00000034733 00000000000 013601  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// VMDK and OVA (docs/disk-image-formats-plan.md P4) against qemu-img: each
// subformat qemu-img makes (monolithicSparse, streamOptimized,
// monolithicFlat, twoGbMaxExtentSparse, twoGbMaxExtentFlat), zeroed grains,
// a child with its parent (CID), large sparse disks and extents across 2 GiB;
// damaged descriptors, headers, tables and grains; OVA archives (ustar and
// pax) of an OVF descriptor and a streamOptimized disk: the disk read in the
// archive as qemu-img reads the VMDK, the hardware mapped with notes.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { make_samples, SAMPLES_DIR } from "./samples.mjs";
import { sample_file, sample_files, settings, read, open_sample, open_bytes, rejects, compare,
    check_against_reference, check_writes } from "./helpers.mjs";
import { open_image, import_ova } from "../../src/image/factory.js";
import { parse_xml, read_ovf } from "../../src/image/ova.js";

process.on("unhandledRejection", exn => { throw exn; });

const manifest = make_samples();
const base = fs.readFileSync(sample_file("base.raw"));
let compared = 0;

for(const name of ["sparse.vmdk", "stream.vmdk", "flat.vmdk", "2gbsparse.vmdk", "2gbflat.vmdk", "zeroed.vmdk"])
{
    const files = sample_files(manifest.samples[name]);
    compared += await check_against_reference(manifest, name, "vmdk", { files });
    const reader = await open_sample(name, "auto", "url", { files });
    assert.equal(reader.format, "vmdk", name + ": auto");
    console.log("ok - " + name + " (" + reader.create_type + "): as qemu-img reads it, whole and in ranges");
}
{
    const zeroed = await open_sample("zeroed.vmdk", "vmdk", "url");
    const extents = await new Promise(resolve => zeroed.map(0, 131072, resolve));
    assert.deepEqual(extents.map(e => e.type), [1], "zeroed grains (GTE 1) read as zeros");
}
for(const name of ["5g-sparse.vmdk", "5g-flat.vmdk"])
{
    await check_writes(manifest, name, "vmdk", { files: sample_files(manifest.samples[name]) });
}
await check_writes(manifest, "100g.vmdk", "vmdk");
console.log("ok - VMDK: 2 GiB extents (sparse and flat) written across an extent's end, 100 GiB beyond 4 GiB");

// a child: the parent given, a VMDK whose CID is the child's parentCID
compared += await check_against_reference(manifest, "child.vmdk", "vmdk", { backing: { url: sample_file("sparse.vmdk"), async: true } });
await rejects(open_sample("child.vmdk", "vmdk", "url"), /continues in a parent image/, "config");
await rejects(open_sample("child.vmdk", "vmdk", "url", { backing: { url: sample_file("stream.vmdk") } }), /the parent's CID is .*: not its parent/, "config");
await rejects(open_sample("child.vmdk", "vmdk", "url", { backing: { url: sample_file("v3.qcow2") } }), /a VMDK's parent is a VMDK/, "config");
console.log("ok - VMDK: a child with its parent; missing, another CID, another format: refused");

// damaged descriptors, headers, tables, grains
{
    const text = fs.readFileSync(sample_file("flat.vmdk"), "utf8");
    const descriptor = (t, files = sample_files(manifest.samples["flat.vmdk"])) =>
        open_image("hda", { buffer: new TextEncoder().encode(t).buffer, format: "vmdk", files }, settings);
    await rejects(descriptor(text.replace("monolithicFlat", "vmfsSparse")), /createType vmfsSparse is not supported/, "unsupported");
    await rejects(descriptor(text.replace(/^RW /m, "NOACCESS ")), /NOACCESS/, "unsupported");
    await rejects(descriptor(text.replace(" FLAT ", " VMFSRDM ")), /VMFSRDM are not supported/, "unsupported");
    await rejects(descriptor(text.replace(" FLAT ", " BOGUS ")), /an extent line that is not understood/, "unsupported");
    await rejects(descriptor(text, {}), /"flat-flat.vmdk" is not given: name it in files/, "config");
    await rejects(descriptor(text, { "flat-flat.vmdk": { buffer: new ArrayBuffer(1 << 20) } }), /the flat extent .* past the end of its file/, "corrupt");
    // createType vmfs: a flat extent of type VMFS (ESX); a ZERO extent
    const vmfs = await descriptor('# Disk DescriptorFile\nversion=1\nCID=12345678\nparentCID=ffffffff\ncreateType="vmfs"\n' +
        'RW 65536 VMFS "base-flat.vmdk"\nRW 2048 ZERO\nRW 65536 FLAT "base-flat.vmdk" 65536\n', { "base-flat.vmdk": { url: sample_file("base.raw") } });
    assert.equal(vmfs.virtual_size, (65536 + 2048 + 65536) * 512);
    compare(await read(vmfs, 0, 65536 * 512), base.subarray(0, 65536 * 512), "a VMFS extent");
    compare(await read(vmfs, 65536 * 512, 2048 * 512), new Uint8Array(2048 * 512), "a ZERO extent");
    compare(await read(vmfs, (65536 + 2048) * 512, 65536 * 512), base.subarray(65536 * 512, 2 * 65536 * 512), "a FLAT extent at an offset");
    compare(await read(vmfs, 65536 * 512 - 4096, 8192 + 2048 * 512), Buffer.concat([base.subarray(65536 * 512 - 4096, 65536 * 512),
        new Uint8Array(2048 * 512), base.subarray(65536 * 512, 65536 * 512 + 4096)]), "a read across three extents");
    // a file named with a directory is found by its name
    const named = await descriptor(text, { "elsewhere/flat-flat.vmdk": { url: sample_file("flat-flat.vmdk") } });
    compare(await read(named, 0, 1 << 20), base.subarray(0, 1 << 20), "an extent by its name without the directory");

    const sparse = fs.readFileSync(sample_file("sparse.vmdk"));
    const sv = new DataView(sparse.buffer, sparse.byteOffset, sparse.length);
    const patched = patch => { const b = new Uint8Array(sparse); patch(new DataView(b.buffer), b); return b; };
    await rejects(open_bytes(patched(v => v.setUint32(4, 4, true)), "vmdk"), /sparse version 4 is not supported/, "unsupported");
    await rejects(open_bytes(patched(v => v.setBigUint64(20, 7n, true)), "vmdk"), /grain size 7 sectors is invalid/, "corrupt");
    await rejects(open_bytes(patched(v => v.setUint32(44, 1024, true)), "vmdk"), /1024 entries per grain table is invalid/, "corrupt");
    const gd = Number(sv.getBigUint64(56, true)) * 512;
    await rejects(open_bytes(sparse.subarray(0, gd + 4), "vmdk"), /grain directory .* past the end/, "corrupt");
    const gt = sv.getUint32(gd, true) * 512;
    const no_gt = await open_bytes(patched(v => v.setUint32(gd, (sparse.length >> 9) + 100, true)), "vmdk");
    await rejects(read(no_gt, 0, 512), /grain table at \d+ is past the end/, "corrupt");
    void gt;

    // a stream with its grain directory's place in a footer (GD_AT_END, as
    // VMware writes them; qemu-img writes it into the header): the footer
    // marker, the footer (the header with the place), the end-of-stream marker
    const qemu_stream = fs.readFileSync(sample_file("stream.vmdk"));
    const stream = new Uint8Array(qemu_stream.length + 1536);
    stream.set(qemu_stream);
    const footer = new DataView(stream.buffer, qemu_stream.length);
    footer.setBigUint64(0, 1n, true);
    footer.setUint32(12, 3, true);
    stream.set(qemu_stream.subarray(0, 512), qemu_stream.length + 512);
    new DataView(stream.buffer).setBigUint64(56, 0xFFFFFFFFFFFFFFFFn, true);
    const with_footer = await open_bytes(stream, "vmdk");
    for(let offset = 0; offset < base.length; offset += 4 << 20)
    {
        compare(await read(with_footer, offset, 1 << 20), base.subarray(offset, offset + (1 << 20)), "GD_AT_END at " + offset);
    }
    const streamed = patch => { const b = new Uint8Array(stream); patch(b); return b; };
    await rejects(open_bytes(streamed(b => { b[b.length - 1536 + 12] = 7; }), "vmdk"), /the stream's footer is invalid/, "corrupt");
    await rejects(open_bytes(streamed(b => { b[b.length - 512 + 12] = 1; }), "vmdk"), /the stream's footer is invalid/, "corrupt");
    // the first compressed grain: its data damaged, its checksum wrong
    const stv = new DataView(stream.buffer, stream.byteOffset, stream.length);
    const footer_gd = Number(stv.getBigUint64(stream.length - 1024 + 56, true)) * 512;
    const first_gt = stv.getUint32(footer_gd, true) * 512;
    let grain = 0;
    while(!stv.getUint32(first_gt + grain * 4, true)) grain++;
    const marker = stv.getUint32(first_gt + grain * 4, true) * 512;
    const size = stv.getUint32(marker + 8, true);
    const bad_sum = await open_bytes(streamed(b => { b[marker + 12 + size - 1] ^= 0xFF; }), "vmdk");
    await rejects(read(bad_sum, grain * 65536, 512), /wrong Adler-32 checksum|is not zlib data|invalid/, "corrupt");
    const bad_size = await open_bytes(streamed(b => new DataView(b.buffer).setUint32(marker + 8, 1 << 30, true)), "vmdk");
    await rejects(read(bad_size, grain * 65536, 512), /grain marker .* has the size/, "corrupt");
    compare(await read(bad_sum, (grain + 32) * 65536, 65536), base.subarray((grain + 32) * 65536, (grain + 33) * 65536), "the other grains");
    console.log("ok - VMDK: damaged descriptors, sparse headers, tables, streams and grains: refused with what is wrong");
}

// OVA: an OVF descriptor and the streamOptimized disk in a TAR archive
const ovf = `<?xml version="1.0" encoding="UTF-8"?>
<!-- a VMware-like descriptor -->
<Envelope vmw:buildId="build-1" xmlns="http://schemas.dmtf.org/ovf/envelope/1" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1"
    xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vmw="http://www.vmware.com/schema/ovf"
    xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData">
  <References>
    <File ovf:href="disk1.vmdk" ovf:id="file1" ovf:size="${fs.statSync(sample_file("stream.vmdk")).size}"/>
    <File ovf:href="missing.vmdk" ovf:id="file2"/>
  </References>
  <DiskSection>
    <Info>Virtual disk information</Info>
    <Disk ovf:capacity="64" ovf:capacityAllocationUnits="byte * 2^20" ovf:diskId="vmdisk1" ovf:fileRef="file1"
        ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"/>
    <Disk ovf:capacity="1" ovf:capacityAllocationUnits="byte * 2^30" ovf:diskId="vmdisk2" ovf:fileRef="file2"
        ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"/>
  </DiskSection>
  <VirtualSystem ovf:id="dos">
    <Info>A virtual machine &amp; its hardware</Info>
    <OperatingSystemSection ovf:id="1" vmw:osType="dosGuest"><Info>The guest</Info><Description>MS-DOS</Description></OperatingSystemSection>
    <VirtualHardwareSection>
      <Info>Virtual hardware requirements</Info>
      <Item><rasd:InstanceID>1</rasd:InstanceID><rasd:ResourceType>3</rasd:ResourceType><rasd:VirtualQuantity>2</rasd:VirtualQuantity></Item>
      <Item><rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits><rasd:InstanceID>2</rasd:InstanceID><rasd:ResourceType>4</rasd:ResourceType><rasd:VirtualQuantity>32</rasd:VirtualQuantity></Item>
      <Item><rasd:ElementName>IDE 0</rasd:ElementName><rasd:InstanceID>3</rasd:InstanceID><rasd:ResourceType>5</rasd:ResourceType></Item>
      <Item><rasd:ElementName>SCSI controller 0</rasd:ElementName><rasd:InstanceID>4</rasd:InstanceID><rasd:ResourceSubType>lsilogic</rasd:ResourceSubType><rasd:ResourceType>6</rasd:ResourceType></Item>
      <Item><rasd:HostResource>ovf:/disk/vmdisk1</rasd:HostResource><rasd:InstanceID>5</rasd:InstanceID><rasd:Parent>3</rasd:Parent><rasd:ResourceType>17</rasd:ResourceType></Item>
      <Item><rasd:HostResource>ovf:/disk/vmdisk2</rasd:HostResource><rasd:InstanceID>6</rasd:InstanceID><rasd:Parent>4</rasd:Parent><rasd:ResourceType>17</rasd:ResourceType></Item>
      <Item><rasd:ElementName>Ethernet 1</rasd:ElementName><rasd:InstanceID>7</rasd:InstanceID><rasd:ResourceSubType>E1000</rasd:ResourceSubType><rasd:ResourceType>10</rasd:ResourceType></Item>
      <vmw:Config ovf:required="false" vmw:key="firmware" vmw:value="efi"/>
    </VirtualHardwareSection>
  </VirtualSystem>
</Envelope>
`;
const ova_dir = path.join(SAMPLES_DIR, "ova");
fs.mkdirSync(ova_dir, { recursive: true });
fs.writeFileSync(path.join(ova_dir, "dos.ovf"), ovf);
fs.copyFileSync(sample_file("stream.vmdk"), path.join(ova_dir, "disk1.vmdk"));
for(const format of ["ustar", "pax"])
{
    const ova = path.join(SAMPLES_DIR, "dos-" + format + ".ova");
    execFileSync("tar", ["-cf", ova, "--format", format, "-C", ova_dir, "dos.ovf", "disk1.vmdk"]);
    const result = await import_ova({ url: ova, async: true }, settings);
    assert.deepEqual(result.files, ["dos.ovf", "disk1.vmdk"], format + ": the archive's files");
    assert.equal(result.disks.length, 2);
    assert.equal(result.disks[0].controller, "ide");
    assert.equal(result.disks[0].capacity, 64 << 20);
    assert.equal(result.disks[1].descriptor, null, "the disk whose file is not in the archive");
    assert.equal(result.options.memory_size, 32 << 20);
    assert.equal(result.options.cpu_cores, 2);
    assert.deepEqual(result.options.hda, { url: ova, buffer: undefined, async: true, size: undefined, archive_member: "disk1.vmdk", format: "vmdk" });
    for(const note of [/missing\.vmdk is not in the archive/, /SCSI controller scsi \(lsilogic\)/, /E1000/, /EFI/, /MS-DOS/])
    {
        assert.ok(result.notes.some(n => note.test(n)), format + ": a note " + note + " in " + JSON.stringify(result.notes));
    }
    const disk = await open_image("hda", result.options.hda, settings);
    for(let offset = 0; offset < base.length; offset += 1 << 20)
    {
        compare(await read(disk, offset, 1 << 20), base.subarray(offset, offset + (1 << 20)), format + " OVA disk at " + offset);
    }
    const from_memory = await open_image("hda", { buffer: new Uint8Array(fs.readFileSync(ova)).buffer, archive_member: "disk1.vmdk", format: "auto" }, settings);
    compare(await read(from_memory, 0, 1 << 20), base.subarray(0, 1 << 20), "from memory");
    await rejects(open_image("hda", { url: ova, archive_member: "nothing.vmdk", format: "vmdk" }, settings), /has no file "nothing.vmdk"/, "config");
    console.log("ok - OVA (" + format + "): the OVF's disks and hardware, notes; the disk read in the archive as qemu-img reads the VMDK");
}
{
    // OVF details: units, an OVF without disks, damaged XML, VirtualBox's EFI
    assert.throws(() => parse_xml("<a><b></a>"), /closes a where b is open/);
    assert.throws(() => read_ovf("<x/>"), /no Envelope/);
    const vbox = read_ovf(`<Envelope><DiskSection/><VirtualSystem><VirtualHardwareSection>
        <Item><ResourceType>4</ResourceType><VirtualQuantity>2</VirtualQuantity><AllocationUnits>GigaBytes</AllocationUnits></Item>
        </VirtualHardwareSection><vbox:Machine><Hardware><Firmware type="EFI"/></Hardware></vbox:Machine></VirtualSystem></Envelope>`);
    assert.equal(vbox.options.memory_size, 2 * 1024 ** 3);
    assert.ok(vbox.notes.some(n => /EFI/.test(n)));
    console.log("ok - OVF: allocation units, VirtualBox's firmware, damaged XML");
}
console.log("VMDK and OVA tests passed (" + (compared >> 20) + " MiB compared)");
                                     source/v64/tests/ios/tools.mjs                                                                      0000644 0000000 0000000 00000062554 00000000000 013507  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The iOS firmware tools on samples the test makes itself, with made-up
// keys (docs/iphone4-plan.md "测试": no Apple files): AES, SHA-1, HMAC,
// IMG3, LZSS, the root filesystem's chunk encryption, UDIF, HFS+/HFSX
// (B-tree descent, extents overflow, hard links, decmpfs), Apple's device
// tree, Mach-O, XML plists.

import assert from "node:assert/strict";
import zlib from "node:zlib";
import { AES, SHA1, HMAC_SHA1, from_hex, to_hex } from "../../src/ios/crypto.js";
import { img3_build, img3_payload, img3_parse } from "../../src/ios/img3.js";
import { lzss_decompress, complzss_decompress, adler32 } from "../../src/ios/lzss.js";
import { VFDecrypt, vfdecrypt_stream, encrcdsa_header } from "../../src/ios/vfdecrypt.js";
import { udif_trailer, udif_partitions, udif_partition_stream, CHUNK } from "../../src/ios/udif.js";
import { plist_parse } from "../../src/ios/plist.js";
import { HFSPlus } from "../../src/ios/hfsplus.js";
import { keys_parse, check_payload } from "../../src/ios/ipsw.js";
import { dt_parse, dt_serialize, dt_find, dt_property, dt_strings, dt_cells, dt_set } from "../../src/apple/devicetree.js";
import { macho_parse, macho_symbols, macho_offset } from "../../src/apple/macho.js";

let seed = 12345;
const random_bytes = n => Uint8Array.from({ length: n }, () => (seed = seed * 1103515245 + 12345 >>> 0) >>> 24);
const ascii = s => Uint8Array.from(s, c => c.charCodeAt(0));
const be32 = (b, at, v) => { b[at] = v >>> 24; b[at + 1] = v >>> 16; b[at + 2] = v >>> 8; b[at + 3] = v; };
const be16 = (b, at, v) => { b[at] = v >>> 8; b[at + 1] = v; };
const be64 = (b, at, v) => { be32(b, at, Math.floor(v / 0x100000000)); be32(b, at + 4, v >>> 0); };
const tests = [];
const test = (name, f) => tests.push([name, f]);

test("AES: FIPS 197 appendix C, CBC both ways", () =>
{
    const pt = "00112233445566778899aabbccddeeff";
    for(const [key, ct] of [["000102030405060708090a0b0c0d0e0f", "69c4e0d86a7b0430d8cdb78070b4c55a"],
        ["000102030405060708090a0b0c0d0e0f1011121314151617", "dda97ca4864cdfe06eaf70a0ec0d7191"],
        ["000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "8ea2b7ca516745bfeafc49904b496089"]])
    {
        const aes = new AES(from_hex(key)), b = from_hex(pt);
        aes.block(b, 0, false);
        assert.equal(to_hex(b), ct);
        aes.block(b, 0, true);
        assert.equal(to_hex(b), pt);
    }
    const aes = new AES(random_bytes(32)), iv = random_bytes(16), data = random_bytes(4096);
    const c = new Uint8Array(data);
    const next = aes.cbc(c, iv, false);
    assert.deepEqual(next, c.subarray(c.length - 16));
    aes.cbc(c, iv, true);
    assert.deepEqual(c, data);
    assert.throws(() => aes.cbc(new Uint8Array(15), iv, true), /whole blocks/);
});

test("SHA-1 and HMAC-SHA1: FIPS 180 and RFC 2202 vectors", () =>
{
    assert.equal(new SHA1().update(ascii("abc")).hex(), "a9993e364706816aba3e25717850c26c9cd0d89d");
    assert.equal(new SHA1().update(ascii("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")).hex(),
        "84983e441c3bd26ebaae4aa1f95129e5e54670f1");
    const million = new SHA1();
    for(let i = 0; i < 1000; i++) million.update(new Uint8Array(1000).fill(0x61));
    assert.equal(million.hex(), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
    assert.equal(to_hex(new HMAC_SHA1(new Uint8Array(20).fill(0x0b)).mac(ascii("Hi There"))), "b617318655057264e28bc0b6fb378c8ef146be00");
    assert.equal(to_hex(new HMAC_SHA1(new Uint8Array(80).fill(0xaa)).mac(ascii("Test Using Larger Than Block-Size Key - Hash Key First"))),
        "aa4ae5e15272d00e95705637ce8a3b55ed402112");
    const h = new HMAC_SHA1(ascii("key"));
    assert.equal(to_hex(h.mac(ascii("The quick brown fox jumps over the lazy dog"))), "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9");
    assert.equal(to_hex(h.mac(ascii("The quick brown fox jumps over the lazy dog"))), "de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9");
});

test("IMG3: encrypted DATA padded past its length, KBAG's key size, unencrypted images", () =>
{
    const key = random_bytes(32), iv = random_bytes(16), payload = random_bytes(1000);
    const room = new Uint8Array(1008);
    room.set(payload);
    new AES(key).cbc(room, iv, false);
    const kbag = new Uint8Array(8 + 16 + 32);
    new DataView(kbag.buffer).setUint32(0, 1, true);
    new DataView(kbag.buffer).setUint32(4, 256, true);
    const file = img3_build("krnl", [{ magic: "TYPE", data: ascii("lnrk") }, { magic: "DATA", data: payload, room },
        { magic: "KBAG", data: kbag }]);
    const image = img3_parse(file);
    assert.equal(image.type, "krnl");
    assert.deepEqual(image.tags.map(t => t.magic), ["TYPE", "DATA", "KBAG"]);
    const out = img3_payload(file, { iv: to_hex(iv), key: to_hex(key) });
    assert.equal(out.encrypted, true);
    assert.deepEqual(out.data, payload);
    assert.throws(() => img3_payload(file, { iv: to_hex(iv), key: to_hex(key.subarray(0, 16)) }), /AES-256/);
    assert.throws(() => img3_payload(file), /no key/);
    const plain = img3_build("logo", [{ magic: "DATA", data: ascii("iBootIm\0rest") }]);
    assert.deepEqual(img3_payload(plain).data, ascii("iBootIm\0rest"));
    assert.equal(check_payload("logo", img3_payload(plain).data), "iBootIm image");
    assert.throws(() => img3_parse(ascii("not an image at all")), /Img3/);
});

/** A greedy LZSS encoder in lzss.c's format (the decoder's other half, for the test) */
function lzss_compress(src)
{
    const N = 4096, F = 18, ring = new Uint8Array(N).fill(0x20, 0, N - F);
    const out = [];
    let r = N - F, i = 0;
    while(i < src.length)
    {
        const flag_at = out.length;
        out.push(0);
        for(let bit = 0; bit < 8 && i < src.length; bit++)
        {
            let best = 0, best_pos = 0;
            for(let p = 0; p < N && best < F; p++)
            {
                let n = 0;
                // (a match may run into the bytes it writes, as the decoder copies through the ring)
                while(n < F && i + n < src.length && (p + n - r & N - 1) !== 0 && ring[p + n & N - 1] === src[i + n]) n++;
                if(n > best) { best = n; best_pos = p; }
            }
            if(best >= 3)
            {
                out.push(best_pos & 0xFF, (best_pos >> 4 & 0xF0) | best - 3);
                for(let k = 0; k < best; k++) { ring[r] = src[i++]; r = r + 1 & N - 1; }
            }
            else
            {
                out[flag_at] |= 1 << bit;
                out.push(src[i]);
                ring[r] = src[i++];
                r = r + 1 & N - 1;
            }
        }
    }
    return Uint8Array.from(out);
}

test("LZSS: complzss header, the ring's spaces, matches, Adler-32", () =>
{
    const text = ascii("    leading spaces come from the ring; " + "abcabcabcabc".repeat(20) + " the end");
    const data = new Uint8Array(text.length + 300);
    data.set(text);
    data.set(random_bytes(300), text.length);
    const packed = lzss_compress(data);
    assert.ok(packed.length < data.length);
    assert.deepEqual(lzss_decompress(packed, data.length), data);
    const file = new Uint8Array(0x180 + packed.length);
    file.set(ascii("complzss"));
    be32(file, 8, adler32(data));
    be32(file, 12, data.length);
    be32(file, 16, packed.length);
    file.set(packed, 0x180);
    assert.deepEqual(complzss_decompress(file), data);
    assert.equal(adler32(ascii("Wikipedia")), 0x11E60398);
    file[0x180 + 5] ^= 1;
    assert.throws(() => complzss_decompress(file), /Adler-32|bytes decompressed/);
});

/** An encrcdsa v2 file of plain, chunks of 512 bytes, at offset 0x200 */
function encrcdsa(plain, key)
{
    const block = 512, offset = 0x200, chunks = Math.ceil(plain.length / block);
    const file = new Uint8Array(offset + chunks * block);
    file.set(ascii("encrcdsa"));
    be32(file, 8, 2);
    be32(file, 52, block);
    be64(file, 56, plain.length);
    be64(file, 64, offset);
    const cipher = new VFDecrypt(key, block);
    for(let n = 0; n < chunks; n++)
    {
        const chunk = new Uint8Array(block);
        chunk.set(plain.subarray(n * block, (n + 1) * block));
        cipher.encrypt(chunk, n);
        file.set(chunk, offset + n * block);
    }
    return file;
}

test("root filesystem: encrcdsa chunks with HMAC-SHA1 IVs, streamed in odd pieces", async () =>
{
    const key = to_hex(random_bytes(36)), plain = random_bytes(512 * 5 + 100);
    const file = encrcdsa(plain, key);
    assert.deepEqual(encrcdsa_header(file), { block_size: 512, data_size: plain.length, data_offset: 0x200 });
    const parts = [];
    const stream = vfdecrypt_stream(key, (bytes, offset) => { parts.push([offset, bytes]); });
    for(let at = 0; at < file.length; at += 77) await stream.write(file.subarray(at, at + 77));
    await stream.end();
    const out = new Uint8Array(plain.length);
    for(const [offset, bytes] of parts) out.set(bytes, offset);
    assert.deepEqual(out, plain);
    // (only the chunks wanted are decrypted)
    const wanted = [];
    const some = vfdecrypt_stream(key, (bytes, offset) => { wanted.push(offset); }, { want: offset => offset >= 2048 });
    await some.write(file);
    await some.end();
    assert.deepEqual(wanted, [2048, 2560]);
    const short = vfdecrypt_stream(key, () => {});
    await short.write(file.subarray(0, file.length - 512));
    await assert.rejects(short.end(), /cut short/);
    assert.throws(() => new VFDecrypt(key.slice(0, 64), 512), /36/);
});

/** A UDIF image of one partition: a raw chunk, a zero chunk, a zlib chunk */
function udif(partition)
{
    const raw = partition.subarray(0, 1024), zeros = partition.subarray(1024, 2048), packed = zlib.deflateSync(partition.subarray(2048));
    assert.ok(zeros.every(x => !x));
    const data = new Uint8Array(raw.length + packed.length);
    data.set(raw);
    data.set(packed, raw.length);
    const chunk_list = [[CHUNK.RAW, 0, 2, 0, raw.length], [CHUNK.ZERO, 2, 2, raw.length, 0],
        [CHUNK.ZLIB, 4, (partition.length - 2048) / 512, raw.length, packed.length], [CHUNK.END, partition.length / 512, 0, 0, 0]];
    const mish = new Uint8Array(0xCC + 40 * chunk_list.length);
    mish.set(ascii("mish"));
    be32(mish, 4, 1);
    be64(mish, 0x10, partition.length / 512);
    be32(mish, 0xC8, chunk_list.length);
    chunk_list.forEach(([type, sector, sectors, offset, length], i) =>
    {
        const at = 0xCC + 40 * i;
        be32(mish, at, type);
        be64(mish, at + 8, sector);
        be64(mish, at + 16, sectors);
        be64(mish, at + 24, offset);
        be64(mish, at + 32, length);
    });
    const xml = ascii(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>resource-fork</key><dict><key>blkx</key><array><dict>
<key>Attributes</key><string>0x0050</string><key>Data</key><data>
${Buffer.from(mish).toString("base64").replace(/.{1,52}/g, "\t$&\n")}</data><key>ID</key><string>3</string>
<key>Name</key><string>disk image (Apple_HFSX : 3)</string></dict></array></dict></dict></plist>`);
    const koly = new Uint8Array(512);
    koly.set(ascii("koly"));
    be64(koly, 0x20, data.length);
    be64(koly, 0xD8, data.length);
    be64(koly, 0xE0, xml.length);
    be64(koly, 0x1EC, partition.length / 512);
    const image = new Uint8Array(data.length + xml.length + 512);
    image.set(data);
    image.set(xml, data.length);
    image.set(koly, data.length + xml.length);
    return image;
}

test("UDIF: trailer, blkx plist, raw/zero/zlib chunks streamed out", async () =>
{
    const partition = new Uint8Array(512 * 12);
    partition.set(random_bytes(1024));
    partition.set(ascii("compressible ".repeat(300)), 2048);
    const image = udif(partition);
    const trailer = udif_trailer(image.subarray(image.length - 512));
    const [p] = udif_partitions(image.subarray(trailer.xml_offset, trailer.xml_offset + trailer.xml_length));
    assert.equal(p.name, "disk image (Apple_HFSX : 3)");
    assert.equal(p.sectors, 12);
    const out = new Uint8Array(partition.length);
    const offsets = [];
    const stream = udif_partition_stream(p, (offset, bytes) => { offsets.push(offset); out.set(bytes, offset); });
    for(let at = 0; at < image.length; at += 100) await stream.write(image.subarray(at, at + 100));
    await stream.end();
    assert.deepEqual(out, partition);
    assert.deepEqual(offsets, [0, 2048]);
    const short = udif_partition_stream(p, () => {});
    await short.write(image.subarray(0, 900));
    await assert.rejects(short.end(), /missing/);
});

test("plist: dicts, arrays, ID/IDREF, hexadecimal and 64-bit integers, data, entities", () =>
{
    const v = plist_parse(`<?xml version="1.0"?><!-- c --><plist version="1.0"><dict>
        <key>a &amp; b</key><string ID="1">x &lt;y&gt; &#65;</string>
        <key>again</key><string IDREF="1"/>
        <key>n</key><integer size="32">0x10</integer><key>big</key><integer>0xFFFFFFFFFFFFFFFF</integer>
        <key>neg</key><integer>-5</integer><key>r</key><real>1.5</real>
        <key>t</key><true/><key>f</key><false/><key>d</key><data>aGVs
        bG8=</data><key>list</key><array><dict/><array></array><string></string></array>
        <key>empty</key><array/></dict></plist>`);
    assert.equal(v["a & b"], "x <y> A");
    assert.equal(v.again, "x <y> A");
    assert.equal(v.n, 16);
    assert.equal(v.big, 0xFFFFFFFFFFFFFFFFn);
    assert.equal(v.neg, -5);
    assert.equal(v.r, 1.5);
    assert.equal(v.t, true);
    assert.equal(v.f, false);
    assert.deepEqual(v.d, ascii("hello"));
    assert.deepEqual(v.list, [{}, [], ""]);
    assert.deepEqual(v.empty, []);
    assert.throws(() => plist_parse("<plist><dict><key>x</key><string IDREF=\"9\"/></dict></plist>"), /IDREF/);
});

/**
 * A small HFSX volume (4096-byte blocks and nodes): /a.txt, /dir/b.txt,
 * /frag.bin in ten one-block extents (two in the extents overflow tree),
 * /c.txt compressed (decmpfs type 3, zlib), /link a hard link to iNode20
 */
function hfsx(contents)
{
    const B = 4096;
    const image = new Uint8Array(B * 40);
    const unistr = name => { const b = new Uint8Array(2 + 2 * name.length); be16(b, 0, name.length); for(let i = 0; i < name.length; i++) be16(b, 2 + 2 * i, name.charCodeAt(i)); return b; };
    const catalog_key = (parent, name) => { const n = unistr(name), k = new Uint8Array(6 + n.length); be16(k, 0, 4 + n.length); be32(k, 2, parent); k.set(n, 6); return k; };
    const folder = (id, valence) => { const r = new Uint8Array(88); be16(r, 0, 1); be32(r, 4, valence); be32(r, 8, id); be16(r, 42, 0o40755); return r; };
    const file = (id, size, extents, flags = 0, type = "", creator = "", special = 0) =>
    {
        const r = new Uint8Array(248);
        be16(r, 0, 2);
        be32(r, 8, id);
        r[41] = flags;
        be16(r, 42, 0o100644);
        be32(r, 44, special);
        r.set(ascii(type.padEnd(4, "\0")), 48);
        r.set(ascii(creator.padEnd(4, "\0")), 52);
        be64(r, 88, size);
        be32(r, 100, extents.reduce((n, e) => n + e[1], 0));
        extents.slice(0, 8).forEach(([start, count], i) => { be32(r, 104 + 8 * i, start); be32(r, 108 + 8 * i, count); });
        return r;
    };
    const thread = (type, parent, name) => { const n = unistr(name), r = new Uint8Array(8 + n.length); be16(r, 0, type); be32(r, 4, parent); r.set(n, 8); return r; };
    // (block layout: 0 header, 1-2 catalog, 3 extents, 4 attributes, 5.. data)
    const data_at = { "a.txt": 5, "b.txt": 6, link: 0, inode: 7 };
    const frag = Array.from({ length: 10 }, (_, i) => [8 + i * 2, 1]);
    const records = [
        [catalog_key(1, "Volume"), folder(2, 6)],
        [catalog_key(2, ""), thread(3, 1, "Volume")],
        [catalog_key(2, "\0\0\0\0HFS+ Private Data"), folder(18, 1)],
        [catalog_key(2, "a.txt"), file(16, contents.a.length, [[data_at["a.txt"], 1]])],
        [catalog_key(2, "c.txt"), file(21, 0, [], 0x20)],
        [catalog_key(2, "dir"), folder(17, 1)],
        [catalog_key(2, "frag.bin"), file(22, 10 * B, frag)],
        [catalog_key(2, "link"), file(23, 0, [], 0, "hlnk", "hfs+", 20)],
        [catalog_key(16, ""), thread(4, 2, "a.txt")],
        [catalog_key(17, ""), thread(3, 2, "dir")],
        [catalog_key(17, "b.txt"), file(19, contents.b.length, [[data_at["b.txt"], 1]])],
        [catalog_key(18, ""), thread(3, 2, "\0\0\0\0HFS+ Private Data")],
        [catalog_key(18, "iNode20"), file(20, contents.inode.length, [[data_at.inode, 1]])],
    ];
    const node = (kind, height, recs, next = 0) =>
    {
        const n = new Uint8Array(B);
        be32(n, 0, next);
        n[8] = kind & 0xFF;
        n[9] = height;
        be16(n, 10, recs.length);
        let at = 14;
        recs.forEach((r, i) => { be16(n, B - 2 * (i + 1), at); n.set(r, at); at += r.length; });
        be16(n, B - 2 * (recs.length + 1), at);
        return n;
    };
    const header = (root, first, depth, key_compare) =>
    {
        const h = new Uint8Array(106);
        be16(h, 0, depth);
        be32(h, 2, root);
        be32(h, 10, first);
        be16(h, 18, B);
        h[37] = key_compare;
        return node(1, 0, [h, new Uint8Array(128), new Uint8Array(256)]);
    };
    const join = (k, d) => { const r = new Uint8Array(k.length + d.length); r.set(k); r.set(d, k.length); return r; };
    image.set(header(1, 1, 1, 0xBC), B * 1);
    image.set(node(-1, 1, records.map(([k, d]) => join(k, d))), B * 2);
    // (the extents overflow tree: frag.bin's extents 8 and 9, from block 8 on)
    const ext_key = new Uint8Array(12);
    be16(ext_key, 0, 10);
    be32(ext_key, 4, 22);
    be32(ext_key, 8, 8);
    const ext_rec = new Uint8Array(64);
    frag.slice(8).forEach(([start, count], i) => { be32(ext_rec, 8 * i, start); be32(ext_rec, 8 * i + 4, count); });
    image.set(header(1, 1, 1, 0), B * 3);
    image.set(node(-1, 1, [join(ext_key, ext_rec)]), B * 28);
    // (the attributes tree: c.txt's decmpfs header, zlib inline)
    const packed = zlib.deflateSync(contents.c);
    const decmpfs = new Uint8Array(16 + packed.length);
    decmpfs.set(ascii("fpmc"));
    decmpfs[4] = 3;
    new DataView(decmpfs.buffer).setUint32(8, contents.c.length, true);
    decmpfs.set(packed, 16);
    const name = "com.apple.decmpfs", attr_key = new Uint8Array(14 + 2 * name.length);
    be16(attr_key, 0, attr_key.length - 2);
    be32(attr_key, 4, 21);
    be16(attr_key, 12, name.length);
    for(let i = 0; i < name.length; i++) be16(attr_key, 14 + 2 * i, name.charCodeAt(i));
    const attr_rec = new Uint8Array(16 + decmpfs.length + (decmpfs.length & 1));
    be32(attr_rec, 0, 0x10);
    be32(attr_rec, 12, decmpfs.length);
    attr_rec.set(decmpfs, 16);
    image.set(header(1, 1, 1, 0), B * 4);
    image.set(node(-1, 1, [join(attr_key, attr_rec)]), B * 29);
    image.set(contents.a, B * data_at["a.txt"]);
    image.set(contents.b, B * data_at["b.txt"]);
    image.set(contents.inode, B * data_at.inode);
    frag.forEach(([start], i) => image.fill(0x30 + i, B * start, B * (start + 1)));
    // (the volume header; the B-trees' forks: catalog nodes 0-1 in blocks 1-2, the others' header then leaf)
    const vh = image.subarray(1024, 1536);
    vh.set(ascii("HX"));
    be16(vh, 2, 5);
    be32(vh, 0x28, B);
    be32(vh, 0x2C, 40);
    const fork_at = (at, size, extents) => { be64(vh, at, size); extents.forEach(([s, c], i) => { be32(vh, at + 16 + 8 * i, s); be32(vh, at + 20 + 8 * i, c); }); };
    fork_at(0x110, 2 * B, [[1, 2]]);
    fork_at(0xC0, 2 * B, [[3, 1], [28, 1]]);
    fork_at(0x160, 2 * B, [[4, 1], [29, 1]]);
    return image;
}

test("HFS+: descent by parent ID, lookup, extents overflow, hard links, decmpfs", async () =>
{
    const contents = { a: ascii("contents of a\n"), b: ascii("b in a directory\n"), c: ascii("compressed! ".repeat(100)), inode: ascii("the linked file\n") };
    const image = hfsx(contents);
    const volume = await new HFSPlus((offset, length) => image.subarray(offset, offset + length)).open();
    assert.equal(volume.case_sensitive, true);
    const root = await volume.list(2);
    assert.deepEqual(root.map(e => e.name), ["\0\0\0\0HFS+ Private Data", "a.txt", "c.txt", "dir", "frag.bin", "link"]);
    assert.deepEqual(await volume.contents(await volume.lookup("/a.txt")), contents.a);
    assert.deepEqual(await volume.contents(await volume.lookup("/dir/b.txt")), contents.b);
    assert.equal(await volume.lookup("/A.TXT"), null);
    const frag = await volume.contents(await volume.lookup("/frag.bin"));
    assert.equal(frag.length, 10 * 4096);
    for(let i = 0; i < 10; i++) assert.equal(frag[i * 4096 + 5], 0x30 + i, `extent ${i}`);
    const c = await volume.lookup("/c.txt");
    assert.equal(c.compressed, true);
    assert.deepEqual(await volume.contents(c), contents.c);
    const link = await volume.lookup("/link");
    assert.equal(link.type, "hardlink");
    assert.deepEqual(await volume.contents(link), contents.inode);
    const seen = [];
    await volume.walk_tree("/dir", p => { seen.push(p); });
    assert.deepEqual(seen, ["/dir/b.txt"]);
});

test("device tree: parse, serialize, placeholders, paths", () =>
{
    const p = (name, value, placeholder = false) => ({ name, value, placeholder });
    const tree = { properties: [p("name", ascii("device-tree\0")), p("compatible", ascii("N90AP\0iPhone3,1\0AppleARM\0"))], children: [
        { properties: [p("name", ascii("chosen\0")), p("random-seed", new Uint8Array(2), true)], children: [] },
        { properties: [p("name", ascii("arm-io\0")), p("reg", Uint8Array.of(0, 0, 0xc0, 0xbf, 0, 0x10, 0, 0))], children: [
            { properties: [p("name", ascii("uart0\0")), p("interrupts", Uint8Array.of(0x16, 0, 0, 0))], children: [] }] }] };
    const bytes = dt_serialize(tree);
    const back = dt_parse(bytes);
    assert.deepEqual(dt_serialize(back), bytes);
    assert.deepEqual(dt_strings(dt_property(back, "compatible").value), ["N90AP", "iPhone3,1", "AppleARM"]);
    assert.equal(dt_property(dt_find(back, "/chosen"), "random-seed").placeholder, true);
    assert.deepEqual(dt_cells(dt_property(dt_find(back, "/arm-io"), "reg").value), [0xbfc00000, 0x1000]);
    assert.deepEqual(dt_cells(dt_property(dt_find(back, "/arm-io/uart0"), "interrupts").value), [0x16]);
    assert.equal(dt_find(back, "/arm-io/uart9"), null);
    dt_set(dt_find(back, "/chosen"), "random-seed", Uint8Array.of(1, 2, 3, 4, 5));
    const again = dt_parse(dt_serialize(back));
    assert.equal(dt_property(dt_find(again, "/chosen"), "random-seed").placeholder, false);
    assert.equal(dt_property(dt_find(again, "/chosen"), "random-seed").value.length, 5);
});

test("Mach-O: segments, sections, the entry point, UUID, symbols", () =>
{
    const b = new Uint8Array(0x1000), v = new DataView(b.buffer);
    const name = (at, s) => b.set(ascii(s), at);
    v.setUint32(0, 0xFEEDFACE, true);
    v.setUint32(4, 12, true);
    v.setUint32(8, 9, true);
    v.setUint32(12, 2, true);
    v.setUint32(16, 4, true);
    let at = 28;
    // LC_SEGMENT __TEXT with __text
    v.setUint32(at, 1, true); v.setUint32(at + 4, 56 + 68, true); name(at + 8, "__TEXT");
    v.setUint32(at + 24, 0x80001000, true); v.setUint32(at + 28, 0x1000, true); v.setUint32(at + 32, 0, true); v.setUint32(at + 36, 0x1000, true);
    v.setUint32(at + 48, 1, true);
    name(at + 56, "__text"); name(at + 72, "__TEXT"); v.setUint32(at + 88, 0x80001800, true); v.setUint32(at + 92, 0x100, true); v.setUint32(at + 96, 0x800, true);
    at += 56 + 68;
    // LC_UNIXTHREAD: ARM_THREAD_STATE, pc 0x80001801
    v.setUint32(at, 5, true); v.setUint32(at + 4, 16 + 17 * 4, true); v.setUint32(at + 8, 1, true); v.setUint32(at + 12, 17, true);
    v.setUint32(at + 16 + 15 * 4, 0x80001801, true);
    at += 16 + 17 * 4;
    // LC_UUID
    v.setUint32(at, 0x1B, true); v.setUint32(at + 4, 24, true); b.fill(0xAB, at + 8, at + 24);
    at += 24;
    // LC_SYMTAB: two symbols
    v.setUint32(at, 2, true); v.setUint32(at + 4, 24, true); v.setUint32(at + 8, 0xC00, true); v.setUint32(at + 12, 2, true);
    v.setUint32(at + 16, 0xD00, true); v.setUint32(at + 20, 32, true);
    name(0xD01, "_start\0_main\0");
    v.setUint32(0xC00, 1, true); b[0xC04] = 0x0F; b[0xC05] = 1; v.setUint32(0xC08, 0x80001800, true);
    v.setUint32(0xC0C, 8, true); b[0xC10] = 0x0F; b[0xC11] = 1; v.setUint32(0xC14, 0x80001820, true);
    const m = macho_parse(b);
    assert.equal(m.cputype, 12);
    assert.equal(m.entry, 0x80001801);
    assert.equal(m.uuid, "ab".repeat(16));
    assert.equal(m.segments[0].name, "__TEXT");
    assert.deepEqual(m.segments[0].sections.map(s => [s.name, s.addr, s.size, s.offset]), [["__text", 0x80001800, 0x100, 0x800]]);
    assert.deepEqual(macho_symbols(b, m).map(s => [s.name, s.value]), [["_start", 0x80001800], ["_main", 0x80001820]]);
    assert.equal(macho_offset(m, 0x80001804), 0x804);
    assert.equal(macho_offset(m, 0x90000000), -1);
});

test("key files: format, hex lengths, the root filesystem's 36-byte key", () =>
{
    const good = { format: "v86-ios-keys", version: 1, device: "iPhone3,1", build: "10B329", images: {
        Kernelcache: { file: "kernelcache.release.n90", iv: "00".repeat(16), key: "11".repeat(32) },
        RootFileSystem: { file: "048-2748-005.dmg", key: "22".repeat(36) } } };
    assert.equal(keys_parse(JSON.stringify(good)).device, "iPhone3,1");
    assert.throws(() => keys_parse({ ...good, format: "other" }), /v86-ios-keys/);
    assert.throws(() => keys_parse({ ...good, images: { RootFileSystem: { file: "x", key: "22".repeat(32) } } }), /36 bytes/);
    assert.throws(() => keys_parse({ ...good, images: { Kernelcache: { file: "x", iv: "00", key: "11".repeat(32) } } }), /IV/);
});

let failed = 0;
for(const [name, f] of tests)
{
    try
    {
        await f();
        console.log("ok   " + name);
    }
    catch(e)
    {
        failed++;
        console.log("FAIL " + name);
        console.log(e);
    }
}
console.log(`${tests.length - failed}/${tests.length} passed`);
process.exit(failed ? 1 : 0);
                                                                                                                                                    source/v64/tests/ir/differential/build_rep_reference.py                                             0000644 0000000 0000000 00000006251 00000000000 020435  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env python3
"""Build an isolated CPU whose interpreter strings use the pinned pre-refactor body."""
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import tempfile

ROOT = Path(__file__).resolve().parents[3]
COMMIT = "8ee73e538daaab15411344d39a1f271e778ac7f3"
SOURCE = "src/rust/cpu/string.rs"
old = subprocess.check_output(["git", "show", f"{COMMIT}:{SOURCE}"], cwd=ROOT).decode()
start = old.index("// We implement all string instructions here")
end = old.index("\n#[no_mangle]\npub unsafe fn movsb_rep", start)
body = old[start:end].replace("unsafe fn string_instruction(", "unsafe fn string_instruction_reference(", 1)
# (memory::in_svga_lfb and memcpy_into_svga_lfb are gone: the pinned body
# takes its generic path into the frame buffer, which only its MOVS fast path
# skipped; the string semantics the tests compare are the same)
body = body.replace("memory::in_svga_lfb(addr)", "false").replace(
    "memory::memcpy_into_svga_lfb(", "reference_lfb_copy(")
body += "\nunsafe fn reference_lfb_copy(_: u32, _: u32, _: u32) { unreachable!() }\n"
current = (ROOT / SOURCE).read_text()
# (the comment above the interpreter's string_instruction, reworded in bb8979f3)
start = current.index("// Single-core interpreter callers retain their original page-bounded policy.")
end = current.index("/// Explicit progress", start)
wrapper = """#[inline(always)]
unsafe fn string_instruction(is_asize_32: bool, ds_or_prefix: i32, instruction: Instruction, size: Size, rep: Rep) {
    string_instruction_reference(is_asize_32, ds_or_prefix, instruction, size, rep)
}

"""
reference = current[:start] + wrapper + current[end:] + "\n" + body
with tempfile.TemporaryDirectory(prefix="rep-reference-", dir=ROOT / "build") as stage_name:
    stage = Path(stage_name)
    shutil.copytree(ROOT / "src/rust", stage / "src/rust")
    # (test cores include tests/decode/legacy_modrm.rs: cpu/modrm.rs)
    shutil.copytree(ROOT / "tests/decode", stage / "tests/decode")
    for name in ["Cargo.toml", "Cargo.lock"]:
        if (ROOT / name).exists():
            shutil.copy2(ROOT / name, stage / name)
    (stage / SOURCE).write_text(reference)
    target = ROOT / "build/rep-reference-target"
    subprocess.run([
        "cargo", "rustc", "--manifest-path", str(stage / "Cargo.toml"),
        "--target-dir", str(target), "--features", "ir-test-hooks", "--target", "wasm32-unknown-unknown", "--",
        "-C", f"linker={ROOT / 'tools/rust-lld-wrapper'}",
        "-C", "link-args=--import-table --global-base=4096",
        "-C", f"link-args={ROOT / 'build/softfloat.o'}", "-C", f"link-args={ROOT / 'build/zstddeclib.o'}",
        "-C", "target-feature=+bulk-memory,+multivalue,+simd128",
    ], cwd=ROOT, check=True)
    output = ROOT / "build/v86-rep-reference.wasm"
    shutil.copy2(target / "wasm32-unknown-unknown/debug/v86.wasm", output)
    (ROOT / "build/rep-reference.json").write_text(json.dumps({
        "commit": COMMIT, "source": SOURCE,
        "engine_sha256": hashlib.sha256(body.encode()).hexdigest(),
        "wasm_sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
        "scope": "Legacy string_instruction body pinned; other CPU code from working tree",
    }, indent=2) + "\n")
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/ir/differential/page_crossing.mjs                                                  0000644 0000000 0000000 00000011677 00000000000 017446  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Legacy-mode code over several pages in a loop (the x64 page tier, P7.3).
//
// 1. Straight-line code: the first instruction of each page, entered from
//    the page before, must be an entry of its page's function. Before M9 it
//    was not (straight-line code is no entry), and every page after the first
//    stepped through to its end on each round: tests/rust/sse4.mjs's
//    PCMPxSTRx program, 23 KiB without a branch, ran a third of its
//    instructions as steps.
// 2. One instruction per page and a jump to the next (as 708.pages), one
//    multi-page function (P7.3b), with chaining and without (x64_chaining=0,
//    an engine without Wasm tail calls): until M9 the entry of a multi-page
//    function left a value per page on the stack, which only a chaining
//    function's final return hid; without chaining each failed validation.
//
//   node tests/ir/differential/page_crossing.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const CODE = 0x500000, COUNTER = 0x600000, PAGES = 6;
const le32 = n => [...new Uint8Array(new Int32Array([n]).buffer)];
// DEC DWORD [COUNTER]; JNZ program start; HLT
const round_end = body => {
    body.push(0xFF, 0x0D, ...le32(COUNTER));
    body.push(0x0F, 0x85, ...le32(-(body.length + 6)), 0xF4);
};

// ADD EAX, imm32 (5 bytes: instructions straddle the page ends) over PAGES
// pages
function straight_line() {
    const body = [];
    let adds = 0;
    while(body.length < PAGES * 4096 - 32) { body.push(0x05, 1, 0, 0, 0); adds++; }
    round_end(body);
    return { body, adds, rounds: 200 };
}
// At each page's start ADD EAX, 1, then JMP to the next page (from the last
// one, the round's end)
function hops() {
    const body = [];
    for(let p = 0; p < PAGES; p++) {
        while(body.length < p * 4096) body.push(0x90);
        body.push(0x05, 1, 0, 0, 0);
        if(p < PAGES - 1) body.push(0xE9, ...le32((p + 1) * 4096 - (body.length + 5)));
    }
    round_end(body);
    return { body, adds: PAGES, rounds: 4000 };
}

async function run({ body, adds, rounds }, switches, check) {
    const vm = new V86({ jit_switches: switches, graphics_adapter: "bochs_vga", wasm_path: wasm, memory_size: 128 << 20, ir_sync_publication: true,
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const ready = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < ready, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();

    cpu.mem8.set(body, CODE);
    new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).setUint32(COUNTER, rounds, true);
    cpu.reg32[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    e.update_state_flags();
    const native = e.x64_page_stat(1), steps = e.x64_page_stat(4);
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        assert(performance.now() < end, "timeout");
        await sleep(1);
    }
    await vm.stop();
    const label = JSON.stringify(switches);
    assert.equal(cpu.reg32[0] >>> 0, adds * rounds >>> 0, `${label}: EAX`);
    const stats = {
        ran: e.x64_page_stat(1) - native, stepped: e.x64_page_stat(4) - steps,
        failed: e.x64_page_stat(7), spans: e.x64_page_stat(38),
    };
    await vm.destroy();
    assert.equal(stats.failed, 0, `${label}: ${stats.failed} page functions failed to compile or were rejected`);
    check(stats, label, adds * rounds);
    console.log(`PASS ${label}: ${stats.ran} instructions native, ${stats.stepped} steps, ${stats.spans} multi-page functions`);
}

await run(straight_line(), {}, ({ ran, stepped }, label, adds) => {
    // (the first rounds run interpreted until the pages are hot)
    assert.ok(ran > adds * 0.6, `${label}: the page tier ran ${ran} of ${adds} additions natively`);
    assert.ok(stepped < 200, `${label}: ${stepped} steps (each page's first instruction is an entry)`);
});
for(const chaining of [1, 0]) {
    await run(hops(), { x64_chaining: chaining, x64_span_crossings: 16, x64_legacy_heat: 2000 }, ({ ran, spans }, label, adds) => {
        assert.ok(spans > 0, `${label}: no multi-page function`);
        assert.ok(ran > adds, `${label}: the page tier ran ${ran} instructions natively`);
    });
}
process.exit(0);
                                                                 source/v64/tests/ir/differential/page_smc.mjs                                                       0000644 0000000 0000000 00000021665 00000000000 016377  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Writes to a page of compiled legacy-mode code (docs/jit-unification-plan.md
// P7.3, x64::pages::dirty_bytes): a hot loop calls a function on another page;
// every 4096th iteration it writes data on that page next to the code (the
// function retires); every 64th iteration it rewrites the immediates
// of the function's instructions (8, 16 and 32 bits, sign-extended or not:
// MOV, ADD, IMUL, CMP, PUSH, a 16-bit MOV to memory, TEST; volatile in the
// next compile, which loads them from the page); every 8192nd it changes an
// ADD into a SUB (an opcode byte: the function retires); every 16384th it
// replaces the MOV with an instruction of another shape for 64 iterations
// (XOR EDX, EDX and three NOPs: a volatile instruction that changed form).
// Registers, memory and the instruction count must be the interpreter's.
//
//   node tests/ir/differential/page_smc.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, CALLEE = 0x501000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 40000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const u16 = n => [n & 255, n >>> 8 & 255];

// The callee: EBX = DATA; EAX, ESI and EDI accumulate
const callee = [
    0xBA, ...u32(0x1234567),        //  0 MOV EDX, imm32 (imm at 1)
    0x01, 0xD0,                     //  5 ADD EAX, EDX (SUB: 0x29)
    0x83, 0xC0, 0x05,               //  7 ADD EAX, imm8 (at 9)
    0x69, 0xC8, ...u32(0x9E3779B1), // 10 IMUL ECX, EAX, imm32 (at 12)
    0x31, 0xC8,                     // 16 XOR EAX, ECX
    0x3D, ...u32(0x80000000),       // 18 CMP EAX, imm32 (at 19)
    0x83, 0xD6, 0x00,               // 23 ADC ESI, 0
    0x68, ...u32(0x55AA),           // 26 PUSH imm32 (at 27)
    0x5F,                           // 31 POP EDI
    0x01, 0xFE,                     // 32 ADD ESI, EDI
    0x66, 0xC7, 0x43, 0x08, ...u16(0x7777), // 34 MOV WORD [EBX+8], imm16 (at 38)
    0x66, 0x81, 0xC6, ...u16(0x1111), // 40 ADD SI, imm16 (at 43)
    0xA9, ...u32(0x00F000F0),       // 45 TEST EAX, imm32 (at 46)
    0x0F, 0x95, 0xC1,               // 50 SETNZ CL
    0x01, 0xCE,                     // 53 ADD ESI, ECX
    0x6B, 0xC0, 0x03,               // 55 IMUL EAX, EAX, imm8 (at 57)
    0xC3,                           // 58 RET
];

// The loop: EBP counts iterations, [EBX+124] the ones left
const code = [], labels = {}, fixups = [];
const emit = (...bytes) => code.push(...bytes);
const label = name => { labels[name] = code.length; };
const jump = (opcode, name) => { emit(...opcode); fixups.push([code.length, name]); emit(0, 0, 0, 0); };
const at = offset => u32(CALLEE + offset);
label("top");
emit(0x45);                                     // INC EBP
emit(0xF7, 0xC5, ...u32(63));                   // TEST EBP, 63
jump([0x0F, 0x85], "call");                     // JNZ call
emit(0x80, 0x3D, ...at(0), 0x31);               // CMP BYTE [callee], 31h (the other shape?)
jump([0x0F, 0x85], "immediates");               // JNE
emit(0xC6, 0x05, ...at(0), 0xBA);               // MOV BYTE [callee], 0BAh (MOV EDX again)
label("immediates");
emit(0x89, 0xE9);                               // MOV ECX, EBP
emit(0x89, 0x2D, ...at(1));                     // MOV [callee+1], EBP
emit(0x88, 0x0D, ...at(9));                     // MOV [callee+9], CL
emit(0x89, 0x2D, ...at(12));                    // MOV [callee+12], EBP
emit(0x89, 0x2D, ...at(19));                    // MOV [callee+19], EBP
emit(0x89, 0x2D, ...at(27));                    // MOV [callee+27], EBP
emit(0x66, 0x89, 0x2D, ...at(38));              // MOV [callee+38], BP
emit(0x66, 0x89, 0x2D, ...at(43));              // MOV [callee+43], BP
emit(0x89, 0x2D, ...at(46));                    // MOV [callee+46], EBP
emit(0x88, 0x0D, ...at(57));                    // MOV [callee+57], CL
emit(0xF7, 0xC5, ...u32(4095));                 // TEST EBP, 4095
jump([0x0F, 0x85], "call");                     // JNZ call
emit(0x89, 0x2D, ...at(0x800));                 // MOV [callee+800h], EBP (data on the page)
emit(0xF7, 0xC5, ...u32(8191));                 // TEST EBP, 8191
jump([0x0F, 0x85], "call");                     // JNZ call
emit(0x80, 0x35, ...at(5), 0x28);               // XOR BYTE [callee+5], 28h (ADD <-> SUB)
emit(0xF7, 0xC5, ...u32(16383));                // TEST EBP, 16383
jump([0x0F, 0x85], "call");                     // JNZ call
emit(0xC7, 0x05, ...at(0), ...u32(0x9090D231)); // MOV DWORD [callee], XOR EDX, EDX; NOP; NOP
emit(0xC6, 0x05, ...at(4), 0x90);               // MOV BYTE [callee+4], NOP
label("call");
emit(0xE8, ...u32(CALLEE - (CODE + code.length + 5))); // CALL callee
emit(0xFF, 0x4B, 124);                          // DEC DWORD [EBX+124]
jump([0x0F, 0x85], "top");                      // JNZ top
emit(0xF4, 0xEB, 0xFE);                         // HLT
for(const [at, name] of fixups) code.splice(at, 4, ...u32(labels[name] - (at + 4)));

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_page_legacy32: 1, x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(compiled) assert(e.jit_set_page32(1));
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE);
    cpu.mem8.fill(0, CALLEE, CALLEE + 4096);
    cpu.mem8.set(callee, CALLEE);
    cpu.mem8.fill(0, DATA, DATA + 128);
    view.setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const native = compiled ? e.x64_page_stat(1) : 0;
    const invalidated = compiled ? e.x64_page_stat(5) : 0;
    vm.run();
    const end = performance.now() + 60000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        data: Array.from(cpu.mem8.subarray(DATA, DATA + 128)),
        callee: Array.from(cpu.mem8.subarray(CALLEE, CALLEE + 4096)),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        native: compiled ? e.x64_page_stat(1) - native : 0,
        invalidated: compiled ? e.x64_page_stat(5) - invalidated : 0,
        compiles: compiled ? e.x64_page_stat(37) : 0,
    };
}

const reference = await run(await machine(false));
const compiled = await run(await machine(true));
// (each iteration runs 24 instructions or more, the callee's 20 among them;
// with each immediate's rewrite retiring the callee's function, about 300000
// ran natively)
assert(compiled.native > ITERATIONS * 16, `the page tier ran too few instructions natively: ${compiled.native}`);
// (the first rewrite of each of 9 immediates retires the callee's function
// once, the data on the page 9 times, the opcode changes 4 and the changed
// form 4; later rewrites of immediates none)
assert(compiled.invalidated <= 26, `writes retired the callee's function ${compiled.invalidated} times`);
const strip = ({ native, invalidated, compiles, ...rest }) => rest;
assert.deepEqual(strip(compiled), strip(reference), "the page tier's self-modifying code differs from the interpreter's");
console.log(`PASS: ${ITERATIONS} calls of a function whose page is written, its immediates every 64th, an opcode every 8192nd, ` +
    `as in the interpreter (${compiled.compiles} compiles, ${compiled.invalidated} retired, ${compiled.native} native instructions)`);
process.exit(0);
                                                                           source/v64/tests/ir/differential/page_step_budget.mjs                                               0000644 0000000 0000000 00000013462 00000000000 020116  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Small budgets under compiled legacy-mode code (docs/jit-unification-plan.md
// P7.3; pagegen's budget_flags), run by run_cpu_slice with budgets of 1 to 40
// instructions, around one unit of the budget above its flag bits (16; below
// it the interpreter runs the slice). Each slice must end near its budget:
// - steps: a hot loop steps an IN (a port read, after which the function
//   goes on) in every iteration, and a step takes its unit of the budget
//   (once a step wrapped the budget around, and the activation ran on until
//   the loop ended: a loop that waits for a timer interrupt never did, Linux's
//   boot on 4 cores in workers)
// - chains: a loop's two halves on two pages, each function chaining to the
//   other after an instruction or two (once each chain handed on a budget
//   rounded up, which never ran out: MS-DOS's boot, its far calls between
//   pages, waited for a timer tick that never came)
// Registers, data and the instruction count must be the interpreter's.
//
//   node tests/ir/differential/page_step_budget.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// (each program at its own address: code written from here retires no
// compiled code)
const STEPS = 0x500000, CHAINS = 0x502000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 20000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];

// EBX = DATA: [ebx+124] iterations left, [ebx+64] the sum of what IN read
const steps = [];
steps.push(
    0x31, 0xC0,                           // XOR EAX, EAX
    0xE4, 0x80,                           // IN AL, 0x80 (stepped)
    0x01, 0x43, 64,                       // ADD [EBX+64], EAX
    0xFF, 0x4B, 124,                      // DEC DWORD [EBX+124]
);
steps.push(0x0F, 0x85, ...u32(-(steps.length + 6)));  // JNZ STEPS
steps.push(0xF4, 0xEB, 0xFE);             // HLT
// CHAINS: INC ECX, JMP CHAINS + 0x1000; there: DEC DWORD [EBX+124], JNZ CHAINS
const chains = new Array(0x1000 + 16).fill(0x90);
chains.splice(0, 6, 0x41, 0xE9, ...u32(0x1000 - 6));
chains.splice(0x1000, 13, 0xFF, 0x4B, 124, 0x0F, 0x85, ...u32(-(0x1000 + 9)), 0xF4, 0xEB, 0xFE);

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_page_legacy32: 1, x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(compiled) assert(e.jit_set_page32(1));
    return { vm, cpu, e, compiled };
}

function run({ cpu, e, compiled }, code, at) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, at);
    cpu.mem8.fill(0, DATA, DATA + 128);
    view.setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = at;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const native = compiled ? e.x64_page_stat(1) : 0;
    // (the machine stays stopped: slices are run here, one budget after
    // another; a slice that does not return hangs the test)
    let slices = 0, longest = 0;
    while(!cpu.in_hlt[0]) {
        assert(slices < 10 * ITERATIONS * 5, `${compiled ? "page tier" : "interpreter"}: no HLT after ${slices} slices`);
        const budget = 1 + slices % 40;
        longest = Math.max(longest, cpu.run_cpu_slice(budget) - budget);
        slices++;
    }
    // (an activation may finish its block, and its flags add up to 15)
    assert(longest <= 32, `${compiled ? "page tier" : "interpreter"}: a slice ran ${longest} instructions past its budget`);
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        data: Array.from(cpu.mem8.subarray(DATA, DATA + 128)),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        native: compiled ? e.x64_page_stat(1) - native : 0,
    };
}

const reference = await machine(false), page_tier = await machine(true);
const strip = ({ native, ...rest }) => rest;
for(const [name, code, at] of [["stepping IN in every iteration", steps, STEPS], ["chaining between two pages in every iteration", chains, CHAINS]])
{
    const expected = run(reference, code, at);
    const compiled = run(page_tier, code, at);
    assert(compiled.native > ITERATIONS, `${name}: the page tier ran too few instructions natively: ${compiled.native}`);
    assert.deepEqual(strip(compiled), strip(expected), `${name}: the page tier's run differs from the interpreter's`);
    console.log(`PASS: a loop ${name}, in slices of 1 to 40 instructions, as in the interpreter (${compiled.native} native instructions)`);
}
process.exit(0);
                                                                                                                                                                                                              source/v64/tests/ir/differential/page_vector_ts.mjs                                                 0000644 0000000 0000000 00000013654 00000000000 017624  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// CR0.TS under compiled legacy-mode SSE and x87 code (docs/jit-unification-
// plan.md P7.3; pagegen's budget_flags, which the page tier computes at entry
// and after each step): a hot loop adds with ADDPS and FADD, and every 8th
// iteration sets CR0.TS with MOV CR0 (a step); the next SSE or x87
// instruction raises #NM, whose handler counts it, clears TS with CLTS and
// returns to the instruction. Faults, registers and the instruction count
// must be the interpreter's.
//
//   node tests/ir/differential/page_vector_ts.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, HANDLER = 0x503000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 40000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];

// EBX = DATA: [ebx+124] iterations left, [ebx+108] #NM taken, [ebx] the
// SSE operand
const code = [
    0xDB, 0xE3,                           // FNINIT
    0xD9, 0xE8,                           // FLD1
    0x0F, 0x28, 0x0B,                     // MOVAPS XMM1, [EBX]
];
const top = code.length;
code.push(
    0x0F, 0x58, 0xC1,                     // ADDPS XMM0, XMM1
    0xD8, 0xC0,                           // FADD ST0, ST0
    0xD9, 0xE1,                           // FABS
    0x0F, 0x58, 0xD0,                     // ADDPS XMM2, XMM0
    0xF7, 0x43, 124, ...u32(7),           // TEST DWORD [EBX+124], 7
    0x75, 9,                              // JNZ +9
    0x0F, 0x20, 0xC0,                     // MOV EAX, CR0
    0x83, 0xC8, 0x08,                     // OR EAX, 8 (TS)
    0x0F, 0x22, 0xC0,                     // MOV CR0, EAX
    0xFF, 0x4B, 124,                      // DEC DWORD [EBX+124]
);
code.push(0x0F, 0x85, ...u32(top - (code.length + 6)));  // JNZ top
code.push(0xDD, 0x5B, 64);                // FSTP QWORD [EBX+64]
code.push(0x0F, 0x29, 0x53, 32);          // MOVAPS [EBX+32], XMM2
code.push(0xF4, 0xEB, 0xFE);              // HLT
const handler = [
    0xFF, 0x43, 108,                      // INC DWORD [EBX+108]
    0x0F, 0x06,                           // CLTS
    0xCF,                                 // IRETD (to the faulting instruction)
];

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_page_legacy32: 1, x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(compiled) assert(e.jit_set_page32(1));
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE);
    cpu.mem8.set(handler, HANDLER);
    cpu.mem8.fill(0, DATA, DATA + 128);
    for(let i = 0; i < 4; i++) view.setFloat32(DATA + 4 * i, 0.25 * (i + 1), true);
    view.setUint32(DATA + 124, ITERATIONS, true);
    // Vector 7: a present 32-bit interrupt gate to the handler
    view.setUint16(0x7000 + 7 * 8, HANDLER & 0xFFFF, true);
    view.setUint16(0x7000 + 7 * 8 + 2, 8, true);
    view.setUint16(0x7000 + 7 * 8 + 4, 0x8E00, true);
    view.setUint16(0x7000 + 7 * 8 + 6, HANDLER >>> 16, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const native = compiled ? e.x64_page_stat(1) : 0;
    vm.run();
    const end = performance.now() + 60000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        data: Array.from(cpu.mem8.subarray(DATA, DATA + 128)),
        cr0: cpu.cr[0] >>> 0,
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        native: compiled ? e.x64_page_stat(1) - native : 0,
    };
}

const reference = await run(await machine(false));
const faults = new DataView(Uint8Array.from(reference.data).buffer).getUint32(108, true);
assert.equal(faults, ITERATIONS / 8, "the interpreter took a #NM after each MOV CR0 that set TS");
const compiled = await run(await machine(true));
assert(compiled.native > ITERATIONS * 4, `the page tier ran too few instructions natively: ${compiled.native}`);
const strip = ({ native, ...rest }) => rest;
assert.deepEqual(strip(compiled), strip(reference), "the page tier's #NM differs from the interpreter's");
console.log(`PASS: ${faults} #NM after CR0.TS set in compiled SSE and x87 code, as in the interpreter (${compiled.native} native instructions)`);
process.exit(0);
                                                                                    source/v64/tests/ir/differential/page_x87_cw.mjs                                                    0000644 0000000 0000000 00000013402 00000000000 016722  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// FLDCW in compiled legacy-mode code (docs/jit-unification-plan.md M8,
// pages::x64_page_fldcw): a hot loop converts values with FISTP under each
// rounding mode in turn (FNSTCW, the RC field set, FLDCW, FISTP, FLDCW of
// the saved word, as compilers truncate) and once in a while lowers the
// precision control; the integers, the x87 state and the instruction count
// must be the interpreter's.
//
//   node tests/ir/differential/page_x87_cw.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 40000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];

// EBX = DATA: [ebx] the value (a double), [ebx+8] its step, [ebx+16] the
// saved control word, [ebx+20] the one loaded, [ebx+24] the integer,
// [ebx+28] their sum, [ebx+124] iterations left; ECX counts up
const code = [0xDB, 0xE3];                // FNINIT
const top = code.length;
code.push(
    0xDD, 0x03,                           // FLD QWORD [EBX]
    0xDC, 0x43, 8,                        // FADD QWORD [EBX+8]
    0xDD, 0x13,                           // FST QWORD [EBX]
    0xD9, 0x7B, 16,                       // FNSTCW [EBX+16]
    0x0F, 0xB7, 0x43, 16,                 // MOVZX EAX, WORD [EBX+16]
    0x89, 0xCA,                           // MOV EDX, ECX
    0x83, 0xE2, 0x03,                     // AND EDX, 3 (the rounding mode)
    0xC1, 0xE2, 0x0A,                     // SHL EDX, 10
    0x80, 0xE4, 0xF3,                     // AND AH, 0F3h
    0x09, 0xD0,                           // OR EAX, EDX
    0xF7, 0xC1, ...u32(1023),             // TEST ECX, 1023
    0x75, 3,                              // JNZ +3
    0x80, 0xE4, 0xFC,                     // AND AH, 0FCh (precision: single)
    0x66, 0x89, 0x43, 20,                 // MOV [EBX+20], AX
    0xD9, 0x6B, 20,                       // FLDCW [EBX+20]
    0xDB, 0x5B, 24,                       // FISTP DWORD [EBX+24]
    0xD9, 0x6B, 16,                       // FLDCW [EBX+16]
    0x8B, 0x43, 24,                       // MOV EAX, [EBX+24]
    0x01, 0x43, 28,                       // ADD [EBX+28], EAX
    0x41,                                 // INC ECX
    0xFF, 0x4B, 124,                      // DEC DWORD [EBX+124]
);
code.push(0x0F, 0x85, ...u32(top - (code.length + 6)));  // JNZ top
code.push(0xD9, 0x7B, 32);                // FNSTCW [EBX+32]
code.push(0xF4, 0xEB, 0xFE);              // HLT

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE);
    cpu.mem8.fill(0, DATA, DATA + 128);
    view.setFloat64(DATA, -1000.3, true);
    view.setFloat64(DATA + 8, 0.0371, true);
    view.setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const native = compiled ? e.x64_page_stat(1) : 0;
    vm.run();
    const end = performance.now() + 60000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        data: Array.from(cpu.mem8.subarray(DATA, DATA + 64)),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        native: compiled ? e.x64_page_stat(1) - native : 0,
    };
}

const reference = await run(await machine(false));
const compiled = await run(await machine(true));
assert(compiled.native > ITERATIONS * 20, `the page tier ran too few instructions natively: ${compiled.native}`);
const strip = ({ native, ...rest }) => rest;
assert.deepEqual(strip(compiled), strip(reference), `the page tier's FLDCW and FISTP differ from the interpreter's`);
const sum = new DataView(Uint8Array.from(reference.data).buffer).getInt32(28, true);
console.log(`PASS: ${ITERATIONS} FISTP under each rounding mode set by FLDCW in the page tier as in the interpreter (sum ${sum}` +
    `, ${compiled.native} native instructions)`);
process.exit(0);
                                                                                                                                                                                                                                                              source/v64/tests/ir/differential/prot16_fuzz.mjs                                                    0000644 0000000 0000000 00000070165 00000000000 017031  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// 16-bit differential fuzzing (docs/jit-unification-plan.md P7.7(6), P7.8):
// random 16-bit programs run hot in a loop in a 16-bit code segment of
// protected mode, real mode or virtual-8086 mode (FUZZ_MODE prot16, real or
// v86; so their page is compiled by the x64 page tier with x64_page_prot16
// or x64_page_v86; prot16ss32: protected mode with a 32-bit stack, M11) and
// must leave exactly the interpreter's state: the GPRs, FLAGS (PUSHF inside
// the loop stores them), the data, stack and counter segments, and the
// retired-instruction count. Each program must also have run in page
// functions, most of its instructions there.
//
// A 32-bit prologue loads SS (16-bit stack), DS and ES (the loop counter's
// segment) with 16-bit descriptors and jumps far to the program. Every case
// runs on a fresh code page, its code segment based so that the page starts
// at IP 0x840 (or, with FUZZ_STRADDLE=1, the program straddles two pages);
// the data and stack segments are 64 KiB each, so every 16-bit address is
// in them (the interpreter checks no data segment limits).
// Real mode and virtual-8086 mode set the machine state directly instead of
// a prologue, below 1 MiB (segment bases are the selectors shifted left by
// 4; at most 24 cases a run). Virtual-8086 programs run with IOPL 3 and
// paging off (boot.bin's page tables are not user pages); their final HLT
// is #GP, which a ring-0 handler of our own (TSS at 0x8000, IDT vector 13)
// halts at.
//
//   node tests/ir/differential/prot16_fuzz.mjs [cases=40] [seed=1] [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
// FUZZ_KIND restricts the programs: a (ALU and moves), m (memory operands),
// s (stack: pushes, pops, calls, LEAVE and ENTER frames, 32-bit pushes),
// j (jumps, LOOP, JCXZ), g (segment register loads, LES, LDS), x
// (multiplies, divides, shifts, extensions), f (far calls into a second
// code segment), l (LODS), z (a null ES loaded at the last round, then an
// ES access: #GP; protected mode only), c (self-modifying code: the round
// counter written over the immediate of the next instruction, through FS,
// flat, with a 32-bit address), y (protected mode: at the last round a far
// call to a selector past the GDT's limit, or a RETF popping one: #GP, in
// the page tier's far transfer helper, M11), i (virtual-8086 mode only: IOPL 0, no
// PUSHF captures, and at the last round PUSHF, POPF, CLI or STI: #GP), k
// (as i, but that instruction first, behind JMP +1 and reached by the JMP
// -3 after it: cold code, the page tier's interpreted blocks (a backward
// jump ends one), the #GP in the second one's first instruction; the
// handler's stack frame, the faulting IP, compared too).
// FUZZ_FAR32=1 (protected mode): the second code segment is flat 32-bit
// code (base 0: the page tier runs no 32-bit code with a CS base), called
// with CALL FAR ptr16:32 (66 9A) and returning with RETF or RETF 2: far
// calls and returns between 16-bit code and 32-bit code on the same stack,
// which the page tier chains across its modes (M11; 32-bit code on a 16-bit
// stack in prot16, on a 32-bit stack in prot16ss32).
// FUZZ_DEBUG=1 prints each case. JIT_SWITCHES applies to the compiled machine.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const cases = Number(process.argv[2] || 40);
let seed = Number(process.argv[3] || 1) >>> 0;
const wasm = process.argv[4] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const only = process.env.FUZZ_KIND || "";
const straddle = process.env.FUZZ_STRADDLE === "1";
const MODE = process.env.FUZZ_MODE || "prot16";
assert(["prot16", "prot16ss32", "real", "v86"].includes(MODE), "FUZZ_MODE: prot16, prot16ss32, real or v86");
const paragraphs = MODE === "real" || MODE === "v86";
assert(!paragraphs || cases <= 24, "real and virtual-8086 mode: at most 24 cases (below 1 MiB)");
assert(!paragraphs || only !== "z" && only !== "y", "kinds z and y need protected mode (no null selectors, no descriptors)");
assert(!["i", "k"].includes(only) || MODE === "v86", "kinds i and k need virtual-8086 mode");
const iopl0 = ["i", "k"].includes(only);
const far32 = process.env.FUZZ_FAR32 === "1";
const ledger = !!jit_switches_from_env().mode_ledger;
assert(!far32 || !paragraphs, "FUZZ_FAR32 needs protected mode (a code segment's D bit)");

// The prologue's page, the code pages (one per case), the segments
const { PROLOGUE, CODE, DATA, STACK, COUNTER, FAR } = paragraphs ?
    // (a page after the stack: a 32-bit push at SP 2 writes past its end)
    { PROLOGUE: 0, CODE: 0x6B000, DATA: 0x30000, STACK: 0x40000, COUNTER: 0x51000, FAR: 0x52000 } :
    { PROLOGUE: 0x480000, CODE: 0x500000, DATA: 0x600000, STACK: 0x620000, COUNTER: 0x640000, FAR: 0x680000 };
const IP = 0x840, ITERATIONS = 20000;
// (selectors; in real and virtual-8086 mode the segments' paragraphs: the
// far routine's and code's per case, see run)
const SEL = paragraphs ? { data: DATA >> 4, stack: STACK >> 4, counter: COUNTER >> 4, far: 0 } :
    { code: 0x20, data: 0x28, stack: 0x30, counter: 0x38, far: 0x40 };
// Virtual-8086 mode's #GP handler (HLT), TSS and ring-0 stack
const V86_HANDLER = 0x8100, V86_TSS = 0x8000, V86_STACK0 = 0x9000, TSS_SELECTOR = 0x48;
// the far routine's IP in its code segment
const FAR_IP = 0x100;
const random = () => {
    seed ^= seed << 13; seed >>>= 0; seed ^= seed >>> 17; seed ^= seed << 5; seed >>>= 0;
    return seed;
};
const pick = list => list[random() % list.length];
const u16 = n => [n & 255, n >>> 8 & 255];
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
/** A 16-bit descriptor (G = 0, D/B = 0, or `flags` 0x40: B = 1): base, limit 0xFFFF, access byte */
const descriptor = (base, access, flags = 0) => [0xFF, 0xFF, base & 255, base >>> 8 & 255, base >>> 16 & 255, access, flags, base >>> 24 & 255];

// Registers: AX CX DX BX SP BP SI DI; destinations never SP (4)
const DESTINATIONS = [0, 1, 2, 3, 5, 6, 7];
const dst = () => pick(DESTINATIONS);
const any = () => random() & 7;
const rr = (r, m) => 0xC0 | r << 3 | m;
// A 16-bit memory operand: mod 0-2, every r/m (BP's forms address SS),
// with r/m 6 and mod 0 a 16-bit displacement
function memory(r) {
    const mod = random() % 3, m = random() & 7;
    if(mod === 0 && m === 6) return [r << 3 | 6, ...u16(random())];
    if(mod === 0) return [r << 3 | m];
    if(mod === 1) return [0x40 | r << 3 | m, random() & 255];
    return [0x80 | r << 3 | m, ...u16(random())];
}
const rm = r => random() % 3 ? [rr(r, dst())] : memory(r);
const rm_source = r => random() % 3 ? [rr(r, any())] : memory(r);

function alu() {
    const code = random() & 7, form = random() % 6;
    switch(form) {
        case 0: return [code << 3 | 1, ...rm(any())];                       // op r/m16, r16
        case 1: return [code << 3 | 3, ...rm_source(dst())];                // op r16, r/m16
        case 2: return [code << 3 | 0, ...random() % 3 ? [rr(any(), any())] : memory(any())]; // op r/m8, r8
        case 3: return [0x81, ...rm(code), ...u16(random())];               // op r/m16, imm16
        case 4: return [0x83, ...rm(code), random() & 255];                 // op r/m16, imm8
        default: return [code << 3 | 5, ...u16(random())];                  // op AX, imm16
    }
}
function move() {
    switch(random() % 8) {
        case 7: return [pick([0x2E, 0x26, 0x36]), 0x8B, ...memory(dst())];   // MOV r16, CS:/ES:/SS:m (reads)
        case 0: return [0x89, ...rm(any())];                                // MOV r/m16, r16
        case 1: return [0x8B, ...rm_source(dst())];                         // MOV r16, r/m16
        case 2: return [0xB8 | dst(), ...u16(random())];                    // MOV r16, imm16
        case 3: return [0xC7, ...rm(0), ...u16(random())];                  // MOV r/m16, imm16
        case 4: return [0x8D, ...memory(dst())];                            // LEA r16, m
        case 5: return [0x87, ...random() % 3 ? [rr(dst(), dst())] : memory(dst())];  // XCHG r16, r/m16
        default: return [0x88, ...rm(any())];                               // MOV r/m8, r8
    }
}
function unary() {
    switch(random() % 6) {
        case 0: return [0x40 | dst()];                                      // INC r16
        case 1: return [0x48 | dst()];                                      // DEC r16
        case 2: return [0xF7, ...rm(2 + (random() & 1))];                   // NOT/NEG r/m16
        case 3: return [0xFF, ...rm(random() & 1)];                         // INC/DEC r/m16
        case 4: return [0x85, ...rm_source(any())];                         // TEST r/m16, r16
        default: return [pick([0x98, 0x99, 0xF8, 0xF9, 0xF5, 0x9E, 0x9F])]; // CBW CWD CLC STC CMC SAHF LAHF
    }
}
function wide() {
    switch(random() % 8) {
        case 7: return [0xB9, ...u16(1 + random() % 0xFFFF), 0x31, 0xD2, 0xF7, 0xF1]; // MOV CX, n; XOR DX, DX; DIV CX
        case 0: return [0xF7, ...rm_source(4 + (random() & 1))];            // MUL/IMUL r/m16 (DX:AX)
        case 1: return [0x0F, 0xAF, ...rm_source(dst())];                   // IMUL r16, r/m16
        case 2: return [0x6B, ...rm_source(dst()), random() & 255];         // IMUL r16, r/m16, imm8
        case 3: return [0xD1, ...rm(pick([0, 1, 2, 3, 4, 5, 7]))];          // shifts and rotates by 1
        case 4: return [0xC1, ...rm(pick([0, 1, 4, 5, 7])), random() & 31]; // by imm8
        case 5: return [0x0F, pick([0xB6, 0xBE]), ...rm_source(dst())];     // MOVZX/MOVSX r16, r/m8
        default: return [0x0F, 0x40 | random() & 15, ...rm_source(dst())]; // CMOVcc r16, r/m16
    }
}
// PUSHF; POP WORD [disp16]: FLAGS where the comparison sees them
const capture = () => [0x9C, 0x8F, 0x06, ...u16(random() & 0xFFFE)];
function stack() {
    switch(random() % 7) {
        case 4: return [0x66, 0x50 | any(), ...simple(), 0x66, 0x58 | dst()];                      // PUSH r32 ... POP r32
        case 5: return [0x66, 0xFF, ...memory(6), 0x66, 0x8F, ...memory(0)];                       // PUSH m32; POP m32
        case 6: return [0xC8, ...u16(random() & 0x3E), 0, ...simple(), 0xC9];                     // ENTER n, 0; ...; LEAVE
        case 0: { const body = [0x50 | any(), ...simple(), 0x58 | dst()]; return body; }            // PUSH r16 ... POP r16
        case 1: return [0x6A, random() & 255, 0x58 | dst()];                                        // PUSH imm8; POP r16
        case 2: return [0x55, 0x89, 0xE5, ...simple(), 0xC9];                                       // PUSH BP; MOV BP, SP; ...; LEAVE
        default: return [0x68, ...u16(random()), 0xFF, ...memory(6)];                               // PUSH imm16; PUSH m16 (two pushes)
    }
}
function jumps() {
    const skip = simple();
    switch(random() % 3) {
        case 0: return [0x70 | random() & 15, skip.length, ...skip];                               // Jcc over an instruction
        case 1: return [0xEB, skip.length, ...skip];                                                // JMP over one
        default: {                                                                                  // MOV CX, n; L: op; LOOP L
            const loop = pick([[0x05, ...u16(random())], [0x42], [0x31, rr(3, 0)], [0x01, 0x06, ...u16(random() & 0xFFFE)]]);
            return [0xB9, ...u16(1 + random() % 4), ...loop, pick([0xE2, 0xE1, 0xE0]), -(loop.length + 2) & 255];
        }
    }
}
function segments() {
    // reload DS (or ES) with its own selector, through a register or the
    // stack, or from a far pointer at [disp16] (LES with the counter's
    // selector, LDS with the data's; 16- or 32-bit offsets)
    if(random() % 3 === 0) {
        const at = random() & 0xFFF0, les = random() & 1, wide = random() & 1;
        const offset = wide ? [0x66, 0xC7, 0x06, ...u16(at), ...u32(random())] : [0xC7, 0x06, ...u16(at), ...u16(random())];
        return [...offset, 0xC7, 0x06, ...u16(at + (wide ? 4 : 2)), ...u16(les ? SEL.counter : SEL.data),
            ...wide ? [0x66] : [], les ? 0xC4 : 0xC5, 0x06 | dst() << 3, ...u16(at)];
    }
    return pick([
        [0xB8, ...u16(SEL.data), 0x8E, 0xD8],     // MOV AX, data; MOV DS, AX
        [0x1E, 0x1F],                             // PUSH DS; POP DS
        [0x06, 0x07],                             // PUSH ES; POP ES
        [0x8C, 0xD8, 0x8E, 0xD8],                 // MOV AX, DS; MOV DS, AX
    ]);
}
// LODSB or LODSW, with DF clear or set (SI moves either way)
const lods = () => [pick([0xFC, 0xFD]), pick([0xAC, 0xAD]), 0xFC];
// CALL FAR to the routine in the second code segment, which RETFs (or
// with `far_pop`, RETF 2 after the caller pushed a word)
let far_pop = false;
// (real and virtual-8086 mode: the paragraph is patched per case, run)
const far = () => far32 ?
    // (the routine's linear address at `far_at`, set per case: run)
    ({ bytes: [...far_pop ? [0x6A, random() & 127] : [], 0x66, 0x9A, ...u32(0), ...u16(SEL.far)], far_at: far_pop ? 4 : 2 }) :
    ({ bytes: [...far_pop ? [0x6A, random() & 127] : [], 0x9A, ...u16(FAR_IP), ...u16(SEL.far)], far_at: far_pop ? 5 : 3 });
/** The far routine: register operands, then RETF */
const far_routine = () => far32 ?
    // (32-bit code: INC r32, ADD EAX, imm32, XOR r32, r32)
    [...pick([[0x40 | dst()], [0x05, ...u16(random()), ...u16(random())], [0x31, rr(any(), dst())]]),
        ...far_pop ? [0xCA, 2, 0] : [0xCB]] :
    [...pick([[0x40 | dst()], [0x05, ...u16(random())], [0x31, rr(any(), dst())]]),
        ...far_pop ? [0xCA, 2, 0] : [0xCB]];
// At the last round (ES:[0] 1): MOV ES, a null selector, then MOV AX,
// ES:[BX], #GP(0) (CMP WORD ES:[0], 1; JNE over the rest)
const fault = () => [0x26, 0x83, 0x3E, 0, 0, 1, 0x75, 7, 0x31, 0xC0, 0x8E, 0xC0, 0x26, 0x8B, 0x07];
// At the last round (ES:[0] 1): CALL FAR 0xF8:0x100, or PUSH 0xF8; PUSH
// 0x100; RETF, whose selector is past the GDT's limit (kind y)
const far_fault = () => {
    const transfer = pick([[0x9A, 0x00, 0x01, 0xF8, 0x00], [0x68, 0xF8, 0x00, 0x68, 0x00, 0x01, 0xCB]]);
    return [0x26, 0x83, 0x3E, 0, 0, 1, 0x75, transfer.length, ...transfer];
};
// At the last round, an instruction IOPL governs in virtual-8086 mode
// (kind i: IOPL 0, #GP)
const iopl = () => [0x26, 0x83, 0x3E, 0, 0, 1, 0x75, 1, pick([0x9C, 0x9D, 0xFA, 0xFB])];
// MOV AX, ES:[0]; MOV FS:[linear address of the imm16 below], AX (67, A3);
// ADD AX, imm16 (an object: program() records where the address goes)
const smc = () => ({ bytes: [0x26, 0xA1, 0, 0, 0x64, 0x67, 0xA3, 0, 0, 0, 0, 0x05, ...u16(random())], address_at: 7, target_at: 12 });
// one instruction that leaves SP alone
function simple() { return pick([alu, move, unary])(); }
function instruction() {
    const kinds = { a: [alu, move, unary], m: [move, alu], s: [stack], j: [jumps], g: [segments], x: [wide], f: [far, alu], l: [lods, move],
        z: [fault, alu, move], c: [smc, alu, move], i: [iopl, alu, move, unary], y: [far_fault, far, alu] }[only];
    return pick(kinds || [alu, alu, move, move, unary, wide, stack, jumps, segments, far, lods, smc])();
}
function program() {
    const body = only === "k" ? [0xEB, 0x01, pick([0x9C, 0x9D, 0xFA, 0xFB]), 0xEB, 0xFD] : [], fixups = [];
    for(let k = 0; k < 24; k++) {
        const next = instruction();
        if(Array.isArray(next)) body.push(...next);
        else {
            if(next.far_at !== undefined) fixups.push({ at: body.length + next.far_at, far: true });
            else fixups.push({ at: body.length + next.address_at, target: body.length + next.target_at });
            body.push(...next.bytes);
        }
        if(k % 4 === 3 && !iopl0) body.push(...capture());
    }
    // a call of a subroutine after the loop
    const call_at = body.length;
    body.push(0xE8, 0, 0);
    // DEC WORD ES:[0]; JNZ top; HLT; the subroutine: an instruction, RET
    const tail = [0x26, 0xFF, 0x0E, 0, 0];
    const jnz = -(body.length + tail.length + 4);
    const code = [...body, ...tail, 0x0F, 0x85, ...u16(jnz), 0xF4];
    // (register operands only: a memory write could hit its return address)
    const subroutine = code.length;
    code.push(...pick([[random() & 0x38 | 1, rr(any(), dst())], [0x40 | dst()], [0xB8 | dst(), ...u16(random())]]), 0xC3);
    // (rel16 from the call's next instruction)
    const rel = subroutine - (call_at + 3);
    code[call_at + 1] = rel & 255; code[call_at + 2] = rel >> 8 & 255;
    code.fixups = fixups;
    return code;
}

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20,
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_page_prot16: 1, x64_page_v86: 1, x64_block_count: 0, x64_legacy_heat: 2000,
            x64_legacy_recompile_misses: 64, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    const gdt = cpu.gdtr_offset[0] >>> 0;
    if(!paragraphs) {
        cpu.mem8.set(descriptor(DATA, 0x93), gdt + SEL.data);
        cpu.mem8.set(far32 ? descriptor(0, 0x9B, 0xCF) : descriptor(FAR - FAR_IP, 0x9B), gdt + SEL.far);
        // (prot16ss32: a 32-bit stack, SS.B set)
        cpu.mem8.set(descriptor(STACK, 0x93, MODE === "prot16ss32" ? 0x40 : 0), gdt + SEL.stack);
        cpu.mem8.set(descriptor(COUNTER, 0x93), gdt + SEL.counter);
        cpu.gdtr_size[0] = SEL.far + 7;
    }
    if(MODE === "v86") {
        // A 32-bit TSS (ESP0, SS0 the flat data segment; no I/O bitmap) in
        // TR, and vector 13 an interrupt gate to HLT
        const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        cpu.mem8.fill(0, V86_TSS, V86_TSS + 0x68);
        view.setUint32(V86_TSS + 4, V86_STACK0, true);
        view.setUint16(V86_TSS + 8, 0x10, true);
        view.setUint16(V86_TSS + 0x66, 0x68, true);
        cpu.mem8.set([0x67, 0, V86_TSS & 255, V86_TSS >> 8 & 255, V86_TSS >> 16 & 255, 0x8B, 0, V86_TSS >>> 24], gdt + TSS_SELECTOR);
        cpu.gdtr_size[0] = TSS_SELECTOR + 7;
        cpu.sreg[6] = TSS_SELECTOR; cpu.segment_offsets[6] = V86_TSS; cpu.segment_limits[6] = 0x67; cpu.tss_size_32[0] = 1;
        cpu.mem8[V86_HANDLER] = 0xF4;
        const gate = (cpu.idtr_offset[0] >>> 0) + 13 * 8;
        cpu.mem8.set([V86_HANDLER & 255, V86_HANDLER >> 8 & 255, 0x08, 0, 0, 0x8E, V86_HANDLER >> 16 & 255, V86_HANDLER >>> 24], gate);
    }
    return { vm, cpu, e, compiled };
}

async function run(m, code, init, c, split) {
    const { vm, cpu, e } = m;
    // (again after the run: the core's heap may grow, detaching the buffer)
    let view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    // A fresh code page per case (mem8.set bypasses code-write detection),
    // the code segment based so that its first byte is at IP 0x840 less
    // `split` (then it straddles the page before)
    const page = CODE + c * 0x2000 + (split ? 0x1000 : 0);
    const start = page - split, base = page - IP;
    // (the far routine: a fresh page too)
    const far_page = FAR + c * 0x1000;
    if(!paragraphs) {
        cpu.mem8.set(descriptor(base, 0x9B), (cpu.gdtr_offset[0] >>> 0) + SEL.code);
        cpu.mem8.set(far32 ? descriptor(0, 0x9B, 0xCF) : descriptor(far_page - FAR_IP, 0x9B), (cpu.gdtr_offset[0] >>> 0) + SEL.far);
    }
    cpu.mem8.set(init.far, far_page);
    // (the self-modifying writes' linear addresses; in real and virtual-8086
    // mode the far routine's paragraph)
    const placed = Uint8Array.from(code);
    for(const { at, target, far } of code.fixups) {
        if(far) { if(paragraphs) placed.set(u16(far_page - FAR_IP >> 4), at); else if(far32) placed.set(u32(far_page), at); }
        else placed.set(u32(start + target), at);
    }
    cpu.mem8.set(placed, start);
    cpu.mem8.set(init.data, DATA);
    cpu.mem8.set(init.stack, STACK);
    if(MODE === "v86") cpu.mem8.fill(0, V86_STACK0 - 64, V86_STACK0);
    cpu.mem8.fill(0, COUNTER, COUNTER + 16);
    view.setUint16(COUNTER, ITERATIONS, true);
    view.setUint32(0x608, 0, true);
    // MOV AX, sel; MOV SS, AX; MOV ESP, 0xFFF0; MOV AX, data; MOV DS, AX;
    // MOV AX, counter; MOV ES, AX; MOV EAX, init; JMP FAR code:IP
    const prologue = [0x66, 0xB8, ...u16(SEL.stack), 0x8E, 0xD0, 0xBC, ...u32(0xFFF0),
        0x66, 0xB8, ...u16(SEL.data), 0x8E, 0xD8, 0x66, 0xB8, ...u16(SEL.counter), 0x8E, 0xC0,
        0xB8, ...u32(init.regs[0]), 0xEA, ...u32(IP - split), ...u16(SEL.code)];
    if(!paragraphs) cpu.mem8.set(prologue, PROLOGUE);
    // The prologue is 32-bit code: back to the BIOS's flat segments (the
    // last case halted in its 16-bit code segment; FS the flat alias the
    // self-modifying code writes through)
    for(const [r, selector, access] of [[0, 0x10, 0x93], [1, 0x08, 0x9B], [2, 0x10, 0x93], [3, 0x10, 0x93], [4, 0x10, 0x93]]) {
        cpu.sreg[r] = selector; cpu.segment_offsets[r] = 0; cpu.segment_limits[r] = -1;
        cpu.segment_access_bytes[r] = access; cpu.segment_is_null[r] = 0;
    }
    cpu.is_32[0] = 1; cpu.stack_size_32[0] = 1;
    cpu.reg32.set(init.regs);
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = PROLOGUE;
    if(paragraphs) {
        // Real mode (CR0.PE and PG clear) or virtual-8086 mode (EFLAGS.VM,
        // IOPL 3, CPL 3; paging off), the segments loaded as there, and the
        // program entered directly
        for(const [r, paragraph] of [[0, SEL.counter], [1, base >> 4], [2, SEL.stack], [3, SEL.data], [4, 0], [5, 0]]) {
            cpu.sreg[r] = paragraph; cpu.segment_offsets[r] = paragraph << 4; cpu.segment_limits[r] = 0xFFFF;
            cpu.segment_access_bytes[r] = r === 1 ? 0x9B : 0x93; cpu.segment_is_null[r] = 0;
        }
        cpu.is_32[0] = 0; cpu.stack_size_32[0] = 0;
        cpu.cr[0] = MODE === "real" ? cpu.cr[0] & ~0x80000001 : (cpu.cr[0] | 1) & ~0x80000000;
        cpu.protected_mode[0] = MODE === "real" ? 0 : 1;
        cpu.cpl[0] = MODE === "real" ? 0 : 3;
        cpu.flags[0] = MODE === "real" ? 2 : 0x20000 | (iopl0 ? 0 : 0x3000) | 2;
        cpu.instruction_pointer[0] = start;
    }
    e.update_state_flags();
    e.full_clear_tlb();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const activations = e.x64_page_stat(13), native = e.x64_page_stat(1), steps = e.x64_page_stat(4);
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${m.compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `counter ${view.getUint16(COUNTER, true)} code ${Buffer.from(code).toString("hex")}`);
        }
        await sleep(0);
    }
    await vm.stop();
    view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const count = new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0;
    m.entries = e.x64_page_stat(13) - activations;
    m.native = e.x64_page_stat(1) - native;
    m.interpreted = Math.max(0, count - m.native - (e.x64_page_stat(4) - steps));
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        eip: cpu.instruction_pointer[0] >>> 0,
        eflags: e.get_eflags() >>> 0,
        sregs: Array.from(cpu.sreg.subarray(0, 6)),
        data: Buffer.from(cpu.mem8.subarray(DATA, DATA + 0x10000)).toString("base64"),
        stack: Buffer.from(cpu.mem8.subarray(STACK, STACK + 0x10000)).toString("base64"),
        counter: view.getUint16(COUNTER, true),
        count,
        // (boot.bin's fault stubs write the vector, and the faulting EIP
        // after it, at [0x608] through DS: the data segment's then)
        status: view.getUint32(0x608, true) || view.getUint32(DATA + 0x608, true),
        fault_eip: view.getUint32(DATA + 0x60C, true),
        // (virtual-8086 mode: the #GP handler's frame)
        ...MODE === "v86" ? { ring0: Buffer.from(cpu.mem8.subarray(V86_STACK0 - 64, V86_STACK0)).toString("hex") } : {},
    };
}

const reference = await machine(false), compiled = await machine(true);
assert.equal(compiled.e.x64_page_stat(paragraphs ? 44 : 42), 1, paragraphs ? "x64_page_v86 is on" : "x64_page_prot16 is on");
// (16-bit protected-mode compiles, or real-mode and virtual-8086 ones)
const compile_stat = paragraphs ? 45 : 43;
let failures = 0, uncompiled = 0, retired = 0, native = 0;
for(let c = 0; c < cases; c++) {
    far_pop = (random() & 1) === 1;
    const code = program();
    const init = {
        regs: Array.from({ length: 8 }, () => random()),
        data: Uint8Array.from({ length: 0x10000 }, () => random() & 255),
        stack: Uint8Array.from({ length: 0x10000 }, () => random() & 255),
        far: far_routine(),
    };
    init.regs[4] = 0xFFF0;
    // (a 32-bit stack: LEAVE sets ESP from all of EBP, whose random high
    // half would leave the stack segment)
    if(MODE === "prot16ss32") init.regs[5] &= 0xFFFF;
    const split = straddle ? 4 + random() % Math.max(1, code.length - 8) : 0;
    const expected = await run(reference, code, init, c, split), actual = await run(compiled, code, init, c, split);
    if(process.env.FUZZ_DEBUG) console.log(`case ${c}: count ${expected.count} entries ${compiled.entries} native ${compiled.native} ` +
        `interpreted ${compiled.interpreted} (compiles ${compiled.e.x64_page_stat(compile_stat)}, retries ${compiled.e.x64_page_stat(2)}, ` +
        `unknown exits ${compiled.e.x64_page_stat(3)}, steps ${compiled.e.x64_page_stat(4)}) status ${expected.status.toString(16)} eip ${expected.eip.toString(16)} eflags ${expected.eflags.toString(16)} ` +
        `code ${Buffer.from(code).toString("hex")}`);
    retired += actual.count;
    native += compiled.native;
    // (FUZZ_FAR32's far calls and returns chain across the two modes: far
    // fewer activations than rounds; with the mode ledger on they leave)
    if(far32 && only === "f" && !ledger && compiled.entries * 10 > ITERATIONS) {
        failures++;
        console.log(`case ${c}: ${compiled.entries} activations for ${ITERATIONS} rounds: the far transfers did not chain across modes`);
    }
    if(!compiled.entries && only !== "k") {
        uncompiled++;
        console.log(`case ${c}: no page function ran (${actual.count} instructions, eip ${actual.eip.toString(16)}, status ${actual.status.toString(16)}, ` +
            `faulting IP ${actual.fault_eip.toString(16)})\n` +
            `  code ${Buffer.from(code).toString("hex")}`);
    }
    for(const key of Object.keys(expected)) {
        try { assert.deepEqual(actual[key], expected[key]); }
        catch{
            failures++;
            const show = v => typeof v === "string" ? `(${v.length} base64 chars)` : JSON.stringify(v);
            let where = "";
            if(key === "data" || key === "stack") {
                const a = Buffer.from(actual[key], "base64"), b = Buffer.from(expected[key], "base64");
                const at = a.findIndex((x, i) => x !== b[i]);
                where = ` first difference at ${at.toString(16)}: ${a[at]} vs ${b[at]}`;
            }
            console.log(`case ${c}: ${key} differs${where}\n  code ${Buffer.from(code).toString("hex")}\n  expected ${show(expected[key])}\n  actual   ${show(actual[key])}`);
            break;
        }
    }
}
const compiles = compiled.e.x64_page_stat(compile_stat);
await reference.vm.destroy(); await compiled.vm.destroy();
const percent = share => `${(100 * share).toFixed(1)}%`;
const coverage = `${percent(native / retired)} of the instructions ran natively, ${compiles} 16-bit page compiles`;
// (kind k faults in cold code: interpreted only)
if(failures || uncompiled || only !== "k" && (compiles === 0 || native * 2 < retired)) {
    console.log(`FAIL: ${failures}/${cases} cases differ, no page function ran in ${uncompiled}; ${coverage}`);
    process.exit(1);
}
console.log(`PASS: ${cases} random 16-bit programs (${MODE}${far32 ? ", a 32-bit far routine" : ""}) in the page tier match the interpreter; ${coverage}`);
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/ir/differential/rep_cpu.mjs                                                        0000644 0000000 0000000 00000011273 00000000000 016250  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import {V86} from "../../../build/libv86.mjs";
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
const SOURCE=0x310000,DEST=0x330000,PC=0x8000,STACK=0x90000,HANDLER=0x180000;
const source=k=>[0,1,3,6].includes(k),destination=k=>k!==3&&k!==6;
const input=c=>c.kind===5,output=c=>c.kind===6;
const encode=c=>{const b=[];if(c.width!==1&&c.mode===(c.width===2))b.push(0x66);if(c.mode!==c.asize)b.push(0x67);if(c.seg!==3)b.push([0x26,0x2E,0x36,0x3E,0x64,0x65][c.seg]);b.push(c.repne?0xF2:0xF3);b.push([0xA4,0xA6,0xAA,0xAC,0xAE,0x6C,0x6E][c.kind]+Number(c.width!==1));return b;};
export async function boot(path){
    const vm=new V86({graphics_adapter: "bochs_vga", wasm_path:path,memory_size:32<<20,bios:{buffer:Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer},disable_keyboard:true,disable_mouse:true,disable_speaker:true,net_device:{type:"none"},autostart:false});
    await new Promise(r=>vm.add_listener("emulator-loaded",r));const cpu=vm.v86.cpu,e=cpu.wm.exports,mem=cpu.mem8,words=new Uint32Array(e.memory.buffer),v=new DataView(mem.buffer,mem.byteOffset),set32=(a,n)=>v.setUint32(a,n,true),get32=a=>v.getUint32(a,true);
    vm.run();const until=performance.now()+10000;while(v.getUint16(0x500,true)!==0xCAFE){assert(performance.now()<until);await sleep(1);} await vm.stop();
    const cr0=cpu.cr[0];let events=[],from,to,windows=[],on_event,active;
    function observe(kind,a,width,value){events.push({kind,a,width,value,regs:Array.from(cpu.reg32,x=>x>>>0),flags:e.get_eflags()>>>0,ip:cpu.instruction_pointer[0]>>>0});on_event?.();}
    cpu.io.register_read(0x500,null,()=>{observe("in",0x500,1);return 0xEF;},()=>{observe("in",0x500,2);return 0xCDEF;},()=>{observe("in",0x500,4);return 0x89ABCDEF|0;});
    cpu.io.register_write(0x500,null,n=>observe("out",0x500,1,n),n=>observe("out",0x500,2,n),n=>observe("out",0x500,4,n>>>0));
    const physical=a=>(a>=0xA1000?(to&~4095):(from&~4095))+(a&4095);
    cpu.io.mmap_register(0xA0000,0x4000,a=>{observe("read",a,1);return mem[physical(a)];},(a,n)=>{observe("write",a,1,n);mem[physical(a)]=n;},a=>{observe("read",a,4);return get32(physical(a))|0;},(a,n)=>{observe("write",a,4,n>>>0);set32(physical(a),n);});
    function reset(c){active=c;on_event=undefined;e.ir_test_set_cr0(cr0|0x10000);cpu.cr[2]=0xBADF000;
        cpu.segment_offsets.set([DEST,c.seg===1?SOURCE:0,0,SOURCE,SOURCE,SOURCE]);cpu.segment_is_null.fill(0,0,6);cpu.segment_limits.fill(0xFFFFFFFF,0,6);cpu.sreg.set([16,8,16,16,16,16]);cpu.segment_access_bytes.set([0x93,0x9B,0x93,0x93,0x93,0x93]);cpu.stack_size_32[0]=1;cpu.is_32[0]=+c.mode;words[612>>2]=0;
        const si=c.si??0x40,di=c.di??0x80;cpu.reg32.set([0x55555555,c.asize?c.count:0xAAAA0000|c.count&65535,0xBEEF0500,0x12345678,STACK,0xABCDDCBA,c.asize?si:0xBBBB0000|si&65535,c.asize?di:0xCCCC0000|di&65535]);
        cpu.flags[0]=0x8D7|c.df<<10;cpu.flags_changed[0]=0;words[104>>2]=0x76543210;cpu.in_hlt[0]=0;words[664>>2]=100;
        cpu.idtr_offset[0]=0x2000;cpu.idtr_size[0]=0x7FF;const handler=c.handler??HANDLER;for(const vector of [13,14]){set32(0x2000+vector*8,8<<16|handler&65535);set32(0x2004+vector*8,handler&0xFFFF0000|0x8E00);}
        set32(0x12000,0x13003);set32(0x13000+8*4,0x8003);for(let p=0x310;p<=0x350;p++)set32(0x13000+p*4,p*4096|3);
        from=(cpu.segment_offsets[c.seg]+(c.asize?si:si&65535))>>>0;to=DEST+(c.asize?di:di&65535);mem.fill(0x55,SOURCE,SOURCE+0x11000);mem.fill(c.repne?0x66:0x55,DEST,DEST+0x11000);mem.fill(0xCC,STACK-96,STACK+16);
        const bytes=encode(c);cpu.instruction_pointer[0]=PC+cpu.segment_offsets[1];mem.set(bytes,cpu.instruction_pointer[0]);windows=[[SOURCE,0x11000],[DEST,0x11000],[STACK-96,112]];e.full_clear_tlb();e.update_state_flags();events=[];
    }
    function step(){e.ir_test_step();}
    function batch(limit){const ip=cpu.instruction_pointer[0]>>>0;words[560>>2]=ip;cpu.instruction_pointer[0]=ip+encode(active).length;const packed=e.ir_test_rep_batch(active.kind,active.width,active.asize,active.seg,active.repne,limit);return {outcome:Number(packed&0xFFFFFFFFn),iterations:Number(packed>>32n)};}
    const state=()=>({regs:Array.from(cpu.reg32,x=>x>>>0),flags:e.get_eflags()>>>0,last:words[104>>2],ip:cpu.instruction_pointer[0]>>>0,cr2:cpu.cr[2]>>>0,cpl:words[612>>2]&255,mode:cpu.is_32[0],ss32:cpu.stack_size_32[0],base:Array.from(cpu.segment_offsets.slice(0,6),x=>x>>>0),count:words[664>>2],sreg:Array.from(cpu.sreg.slice(0,6)),data:windows.map(([a,n])=>Buffer.from(mem.slice(a,a+n)))});
    return {vm,cpu,e,mem,words,set32,set16:(a,n)=>v.setUint16(a,n,true),window:(a,n)=>windows.push([a,n]),state,reset,step,batch,events:()=>events,addresses:()=>[from,to],onEvent:f=>{on_event=f;}};
}

export { SOURCE, DEST, PC, STACK, HANDLER, source, destination, encode };
                                                                                                                                                                                                                                                                                                                                     source/v64/tests/ir/differential/rep_engine.mjs                                                     0000644 0000000 0000000 00000023204 00000000000 016723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import {boot, SOURCE, DEST, PC, STACK, HANDLER, source, destination, encode} from "./rep_cpu.mjs";
const reference=await boot(process.env.IR_REP_REFERENCE||"build/v86-rep-reference.wasm"),current=await boot("build/v86-ir-test.wasm");
try {
    const cases=[];for(const mode of [false,true]) for(const asize of [false,true]) for(const width of [1,2,4]) for(let kind=0;kind<7;kind++) for(const repne of [false,true]) for(const df of [0,1]) for(const count of [0,1,3,17])cases.push({mode,asize,width,kind,repne,df,count,seg:3});
    let ordinary=0;
    for(const c of cases){reference.reset(c);reference.step();const expected=reference.state(),events=reference.events();
        current.reset(c);current.step();assert.deepEqual(current.state(),expected,`legacy REP ${JSON.stringify(c)}`);assert.deepEqual(current.events(),events);
        current.reset(c);const result=current.batch(0xFFFFFFFF);assert.deepEqual(current.state(),expected,`explicit REP ${JSON.stringify(c)}`);assert.deepEqual(current.events(),events);assert.equal(result.outcome,expected.ip===PC?1:0);assert.equal(result.iterations,c.count-(expected.regs[1]&(c.asize?-1:65535)));ordinary++;
    }
    console.log(`PASS: ${ordinary} old/new legacy and explicit REP engine comparisons`);
    const selected=cases.filter(c=>!c.mode&&c.count===17&&c.df===0);
    let device=0;
    for(const c of selected){const configure=x=>{x.reset(c);const [from,to]=x.addresses();if(source(c.kind))x.set32(0x13000+(from>>>12)*4,0xA0003);if(destination(c.kind))x.set32(0x13000+(to>>>12)*4,0xA1003);x.e.full_clear_tlb();};
        configure(reference);reference.step();const expected=reference.state(),events=reference.events();configure(current);const result=current.batch(0xFFFFFFFF);assert.equal(result.outcome,0);assert.deepEqual(current.state(),expected);assert.deepEqual(current.events(),events,`REP device ${JSON.stringify(c)}`);device++;
    }
    console.log(`PASS: ${device} complete REP memory/port device event sequences`);
    let faults=0;
    for(const base of selected) for(const fault of ["segment","first","later"]){const c={...base,si:fault==="later"?0x1000-3*base.width:0x40,di:fault==="later"?0x1000-3*base.width:0x80};
        const configure=x=>{x.reset(c);const [from,to]=x.addresses();if(fault==="segment")x.cpu.segment_is_null[destination(c.kind)?0:3]=1;else {x.set32(0x13000+((destination(c.kind)?to:from)>>>12)*4+(fault==="later"?4:0),0);}x.e.full_clear_tlb();x.e.update_state_flags();};
        configure(reference);reference.step();const expected=reference.state(),events=reference.events();configure(current);const result=current.batch(0xFFFFFFFF);assert.deepEqual(current.state(),expected,`REP fault ${JSON.stringify(c)}/${fault}`);assert.deepEqual(current.events(),events);assert.equal(result.outcome,expected.ip===HANDLER?2:1);assert.equal(result.iterations,c.count-(expected.regs[1]& (c.asize?-1:65535)));faults++;
    }
    console.log(`PASS: ${faults} REP segment/page faults and partial-progress states`);
    let bounded=0;
    for(const base of selected) for(const limit of [0,1,2,5,16,17,18]){const c={...base,count:17};current.reset(c);const initial=current.state();const result=current.batch(limit),actual=current.state();assert(result.iterations<=limit);assert.equal(result.iterations,Math.min(limit,c.count));assert.equal(result.outcome,limit<c.count?1:0);assert.equal(actual.regs[1]&(c.asize?-1:65535),c.count-result.iterations);assert.equal(actual.count,100);
        if(limit===0){assert.deepEqual(actual,initial);assert.equal(current.events().length,0);} else if(limit<c.count){assert.equal(actual.ip,PC);if([1,4].includes(c.kind)){assert.equal(actual.flags,initial.flags);assert.equal(actual.last,initial.last);}}
        bounded++;
    }
    console.log(`PASS: ${bounded} zero/exact/partial REP element budgets`);
    let continuation=0;
    for(const c of selected){reference.reset(c);reference.step();const expected=reference.state();current.reset(c);let iterations=0,calls=0;for(;;){const result=current.batch(3);iterations+=result.iterations;calls++;assert(calls<10);if(result.outcome===0) break;assert.equal(result.outcome,1);}assert.equal(iterations,c.count);assert.deepEqual(current.state(),expected,`REP resume ${JSON.stringify(c)}`);continuation++;}
    console.log(`PASS: ${continuation} repeated bounded entries without duplicated iterations`);
    let termination=0;
    for(const c of selected) if([1,4].includes(c.kind)) for(const stop of [0,1,3,16]) for(const limit of [1,2,5]){
        const configure=x=>{x.reset(c);const [,to]=x.addresses();x.mem.fill(c.repne?0x55:0x66,to+stop*c.width,to+(stop+1)*c.width);};
        configure(reference);reference.step();const expected=reference.state();configure(current);let iterations=0,calls=0;for(;;){const result=current.batch(limit);iterations+=result.iterations;assert(++calls<30);if(result.outcome===0) break;assert.equal(result.outcome,1);}assert.equal(iterations,stop+1);assert.deepEqual(current.state(),expected);termination++;
    }
    console.log(`PASS: ${termination} REPE/REPNE early termination across budget cuts`);
    let huge=0;
    for(const base of selected){const c={...base,count:0xFFFFFFFF};current.reset(c);const result=current.batch(2),actual=current.state();assert.equal(result.outcome,1);assert.equal(result.iterations,2);assert.equal(actual.regs[1],c.asize?0xFFFFFFFD:0xAAAAFFFD);assert.equal(actual.ip,PC);huge++;}
    console.log(`PASS: ${huge} maximal unsigned counters bounded to two iterations`);
    let zero=0;
    for(const base of selected){const c={...base,count:0};for(const x of [reference,current]){x.reset(c);x.cpu.segment_is_null.fill(1,0,6);x.e.update_state_flags();}reference.step();const result=current.batch(0);assert.equal(result.outcome,0);assert.equal(result.iterations,0);assert.deepEqual(current.state(),reference.state());assert.equal(current.events().length,0);zero++;}
    console.log(`PASS: ${zero} zero-count precedence over budget, segments and devices`);
    let refault=0;
    for(const base of selected) if(base.asize){const c={...base,si:0x1000-base.width*3,di:0x1000-base.width*3};const configure=x=>{x.reset(c);const [from,to]=x.addresses();x.set32(0x13000+((destination(c.kind)?to:from)>>>12)*4+4,0);x.e.full_clear_tlb();};
        configure(reference);reference.step();reference.step();const expected=reference.state();configure(current);const first=current.batch(0xFFFFFFFF),second=current.batch(0xFFFFFFFF);assert.equal(first.outcome,1);assert.equal(first.iterations,3);assert.equal(second.outcome,2);assert.equal(second.iterations,0);assert.deepEqual(current.state(),expected);assert.deepEqual(current.events(),reference.events());refault++;}
    console.log(`PASS: ${refault} page-batch reentry faults without duplicated progress`);
    let same_ip_fault=0;
    for(const base of selected){const c={...base,handler:PC+encode(base).length};const configure=x=>{x.reset(c);x.cpu.segment_is_null[destination(c.kind)?0:3]=1;x.e.update_state_flags();};configure(reference);reference.step();configure(current);const result=current.batch(3);assert.equal(result.outcome,2);assert.equal(result.iterations,0);assert.equal(current.state().ip,c.handler);assert.deepEqual(current.state(),reference.state());same_ip_fault++;}
    console.log(`PASS: ${same_ip_fault} explicit fault outcomes when handler IP equals decoded next IP`);
    let aliases=0;
    for(const asize of [false,true]) for(const width of [1,2,4]) for(const df of [0,1]) for(const gap of [-width,0,width,3*width]) for(const limit of [1,2,5]){
        const c={mode:true,asize,width,kind:0,repne:false,df,count:17,seg:3,si:0x100,di:0x100+gap};
        const configure=x=>{x.reset(c);const [from,to]=x.addresses();for(let n=-128;n<128;n++)x.mem[from+n]=(n*7+93)&255;x.set32(0x13000+(to>>>12)*4,(from&~4095)|3);x.e.full_clear_tlb();};
        configure(reference);reference.step();const expected=reference.state();configure(current);let iterations=0,calls=0;for(;;){const result=current.batch(limit);iterations+=result.iterations;assert(++calls<30);if(result.outcome===0) break;assert.equal(result.outcome,1);}assert.equal(iterations,c.count);assert.deepEqual(current.state(),expected);aliases++;
    }
    console.log(`PASS: ${aliases} physical-alias and LZ overlap copies across budget cuts`);
    let privilege_faults=0;
    for(const c of selected) if(c.kind>=5){const configure=x=>{x.reset(c);x.words[612>>2]=3;x.cpu.sreg[1]=0x1B;x.cpu.sreg[2]=0x23;x.cpu.segment_access_bytes[1]=0xFB;x.cpu.segment_access_bytes[2]=0xF3;x.cpu.segment_offsets[6]=0x4000;x.cpu.segment_limits[6]=0x67;x.cpu.tss_size_32[0]=0;x.set16(0x4002,0x9000);x.set16(0x4004,16);x.mem.fill(0xCC,0x8FA0,0x9000);x.window(0x8FA0,96);x.set32(0x12000,0x13007);x.set32(0x13000+4*4,0x4003);x.set32(0x13000+8*4,0x8007);x.e.full_clear_tlb();x.e.update_state_flags();};
        configure(reference);reference.step();configure(current);const result=current.batch(3);assert.equal(result.outcome,2);assert.equal(result.iterations,0);assert.deepEqual(current.state(),reference.state());assert.equal(current.events().length,0);privilege_faults++;}
    console.log(`PASS: ${privilege_faults} REP I/O permission failures with explicit zero progress`);
    let overrides=0;
    for(const base of selected) for(const seg of [0,1,2,3,4,5]){
        const c={...base,seg};const configure=x=>{x.reset(c);const [from]=x.addresses();if(source(c.kind))x.mem.fill(0x55,from,from+128);};
        configure(reference);reference.step();configure(current);const result=current.batch(0xFFFFFFFF);assert.deepEqual(current.state(),reference.state());assert.deepEqual(current.events(),reference.events());assert.equal(result.outcome,0);overrides++;
    }
    console.log(`PASS: ${overrides} REP segment overrides and fixed ES destinations`);
} finally {await reference.vm.destroy();await current.vm.destroy();}
                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/ir/differential/sse_fp_tracking.mjs                                                0000644 0000000 0000000 00000017010 00000000000 017747  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// What compiled code knows about XMM registers within a block (the x64 page
// tier's Emitter::xmm_clean, IR Tier-0's Page::xmm_clean until P7.5: lanes
// neither NaN nor denormal, whose checks native SSE
// floating point then skips, see x86tpl::native_fp). Each sequence makes a wrong
// fact visible: a consumer skips the check of a denormal, and MXCSR.DE is
// missing. The sequences run hot, each iteration starting with LDMXCSR and
// MOVAPS of every register (so that a later iteration does not set the flag),
// and must leave the interpreter's XMM registers and MXCSR.
//
//   node tests/ir/differential/sse_fp_tracking.mjs [wasm]
// (TRACKING_DEBUG=1 prints each sequence's MXCSR on both sides)
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "../../rust/compiled_arms.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, DONE = 0x600, ITERATIONS = 100000;

// singles and doubles: one, the smallest normal and the next, a denormal
const ONE = 0x3F800000, MIN = 0x00800000, MIN1 = 0x00800001, DENORMAL = 0x00000003;
const D_ONE = [0, 0x3FF00000], D_MIN = [0, 0x00100000], D_MIN1 = [1, 0x00100000], D_DENORMAL = [3, 0];
const ones = [ONE, ONE, ONE, ONE];
const d_ones = [...D_ONE, ...D_ONE];
const rr = (r, m) => 0xC0 | r << 3 | m;

// [name, registers xmm0..3 (each four words), code]
const SEQUENCES = [
    ["a sum or difference may be an exact denormal", [[MIN1, MIN1, MIN1, MIN1], [MIN, MIN, MIN, MIN], ones, ones],
        [0x0F, 0x5C, rr(0, 1), 0x0F, 0x58, rr(2, 0)]],                                   // SUBPS 0, 1; ADDPS 2, 0
    ["(double precision)", [[...D_MIN1, ...D_MIN1], [...D_MIN, ...D_MIN], d_ones, d_ones],
        [0x66, 0x0F, 0x5C, rr(0, 1), 0x66, 0x0F, 0x58, rr(2, 0)]],
    ["a scalar form checks lane 0 only", [ones, [ONE, DENORMAL, ONE, ONE], ones, ones],
        [0xF3, 0x0F, 0x58, rr(0, 1), 0x0F, 0x58, rr(2, 1)]],                             // ADDSS 0, 1; ADDPS 2, 1
    ["(double precision)", [d_ones, [...D_ONE, ...D_DENORMAL], d_ones, d_ones],
        [0xF2, 0x0F, 0x58, rr(0, 1), 0x66, 0x0F, 0x58, rr(2, 1)]],
    ["a shuffle keeps what it moves", [ones, [ONE, ONE, DENORMAL, ONE], ones, ones],
        [0x0F, 0x59, rr(0, 0), 0x0F, 0xC6, rr(0, 1), 0xE4, 0x0F, 0x58, rr(2, 0)]],      // MULPS 0, 0; SHUFPS 0, 1; ADDPS 2, 0
    ["(UNPCKHPD)", [d_ones, [...D_ONE, ...D_DENORMAL], d_ones, d_ones],
        [0x66, 0x0F, 0x59, rr(0, 0), 0x66, 0x0F, 0x15, rr(0, 1), 0x66, 0x0F, 0x58, rr(2, 0)]],
    ["(UNPCKLPS)", [ones, [ONE, DENORMAL, ONE, ONE], ones, ones],
        [0x0F, 0x59, rr(0, 0), 0x0F, 0x14, rr(0, 1), 0x0F, 0x58, rr(2, 0)]],
    ["a copy is what it copies", [ones, [ONE, ONE, ONE, DENORMAL], ones, ones],
        [0x0F, 0x59, rr(3, 3), 0x0F, 0x28, rr(3, 1), 0x0F, 0x58, rr(2, 3)]],             // MULPS 3, 3; MOVAPS 3, 1; ADDPS 2, 3
    ["(MOVAPS to a register)", [ones, [ONE, ONE, ONE, DENORMAL], ones, ones],
        [0x0F, 0x59, rr(3, 3), 0x0F, 0x29, rr(1, 3), 0x0F, 0x58, rr(2, 3)]],            // MOVAPS xmm3, xmm1 (0F 29)
    ["a scalar move replaces lane 0", [ones, [DENORMAL, ONE, ONE, ONE], ones, ones],
        [0x0F, 0x59, rr(0, 0), 0xF3, 0x0F, 0x10, rr(0, 1), 0x0F, 0x58, rr(2, 0)]],      // MULPS 0, 0; MOVSS 0, 1; ADDPS 2, 0
    ["a conversion checks the lanes it reads", [ones, [ONE, ONE, DENORMAL, ONE], ones, ones],
        [0x0F, 0x5A, rr(0, 1), 0x0F, 0x58, rr(2, 1)]],                                   // CVTPS2PD 0, 1; ADDPS 2, 1
    ["a comparison checks lane 0", [ones, [ONE, DENORMAL, ONE, ONE], ones, ones],
        [0x0F, 0x2F, rr(0, 1), 0x0F, 0x58, rr(2, 1)]],                                   // COMISS 0, 1; ADDPS 2, 1
    ["a scalar result keeps the other lanes", [[ONE, DENORMAL, ONE, ONE], ones, ones, ones],
        [0xF3, 0x0F, 0x59, rr(0, 1), 0x0F, 0x58, rr(2, 0)]],                             // MULSS 0, 1; ADDPS 2, 0
    ["MAXPS of clean operands", [[MIN1, MIN1, MIN1, MIN1], [MIN, MIN, MIN, MIN], ones, ones],
        [0x0F, 0x5C, rr(0, 1), 0x0F, 0x5F, rr(2, 0)]],                                   // SUBPS 0, 1; MAXPS 2, 0
    ["XORPS of a register with itself", [[DENORMAL, DENORMAL, DENORMAL, DENORMAL], ones, ones, ones],
        [0x0F, 0x57, rr(0, 0), 0x0F, 0x58, rr(2, 0), 0x0F, 0x58, rr(3, 1)]],
];

async function machine(options) {
    const vm = new V86({
        graphics_adapter: "bochs_vga", wasm_path: wasm, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
        ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
    const word = a => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
    vm.run();
    while(word(0x500) !== 0xCAFE) await sleep(1);
    await vm.stop();
    return { vm, word };
}

async function run({ vm, word }, registers, code, page) {
    const cpu = vm.v86.cpu;
    const words = registers.flat();
    vm.write_memory(new Uint8Array(Uint32Array.from([...words, 0x1FA0]).buffer), DATA);
    // CR4.OSFXSR; ECX iterations; loop: LDMXCSR; MOVAPS xmm0..3; the code; DEC ECX; JNZ
    const p = [0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0, 0xB9, ...u32(ITERATIONS)];
    const top = p.length;
    p.push(0x0F, 0xAE, 0x15, ...u32(DATA + 64));
    for(let k = 0; k < 4; k++) p.push(0x0F, 0x28, 0x05 | k << 3, ...u32(DATA + 16 * k));
    p.push(...code, 0x49, 0x0F, 0x85);
    p.push(...u32(top - (p.length + 4)));
    p.push(0x0F, 0xAE, 0x1D, ...u32(DATA + 80), 0xC7, 0x05, ...u32(DONE), ...u32(0xCAFE), 0xF4, 0xEB, 0xFD);
    const base = CODE + page * 0x1000;
    vm.write_memory(Uint8Array.from(p), base);
    vm.write_memory(new Uint8Array(4), DONE);
    cpu.reg32[4] = 0x8000; cpu.instruction_pointer[0] = base; cpu.in_hlt[0] = 0;
    vm.run();
    while(word(DONE) !== 0xCAFE) await sleep(1);
    await vm.stop();
    return { mxcsr: word(DATA + 80), xmm: Array.from(cpu.reg_xmm32s.subarray(0, 16), v => v >>> 0) };
}

const reference = await machine({ disable_jit: true });
const arms = [];
for(const arm of COMPILED_ARMS) arms.push({ ...arm, m: await machine(arm.options) });
try {
    for(const [n, [name, registers, code]] of SEQUENCES.entries()) {
        const expected = await run(reference, registers, code, n);
        for(const arm of arms) {
            const before = compiled_activations(arm.m.vm.v86.cpu.wm.exports);
            const actual = await run(arm.m, registers, code, n);
            const label = `${name} (${Buffer.from(code).toString("hex")}) on ${arm.label}`;
            assert(compiled_activations(arm.m.vm.v86.cpu.wm.exports) !== before, label + ": not compiled");
            if(process.env.TRACKING_DEBUG) console.log(label, expected.mxcsr.toString(16), actual.mxcsr.toString(16));
            assert.equal(actual.mxcsr.toString(16), expected.mxcsr.toString(16), label + ": MXCSR");
            assert.deepEqual(actual.xmm, expected.xmm, label + ": XMM");
        }
        assert(expected.mxcsr & 2 || name.startsWith("XORPS"), `${name}: the sequence should raise DE`);
    }
    console.log(`PASS: ${SEQUENCES.length} sequences on what compiled code knows about XMM registers match the interpreter`);
}
finally {
    await reference.vm.destroy();
    for(const arm of arms) await arm.m.vm.destroy();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/ir/differential/tier0_fetch_fault.mjs                                              0000644 0000000 0000000 00000017031 00000000000 020200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Instruction fetch faults in the x64 page tier (legacy mode, P7.3; written
// for IR Tier-0, deleted in P7.5): a hot loop calls a function on another
// page and every 64 iterations unmaps that page (PTE present bit, INVLPG), so
// entering the callee's page function must fault on the fetch. The #PF
// handler records the faulting EIP and CR2 and maps the page back. The fault
// frame must name the callee's first instruction: a stale EIP (the last
// retired instruction, on the caller's page) makes IRET re-execute it, which
// is how XP lost lsass/csrss and bugchecked in NTFS when pageable code was
// paged out.
//
//   node tests/ir/differential/tier0_fetch_fault.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
// The page tier compiles at 2000 instructions.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CALLER = 0x500000, CALLEE = 0x502000, HANDLER = 0x503000, DATA = 0x600000, STACK = 0x610000;
const PTE = 0x11000 + (CALLEE >>> 12) * 4, ITERATIONS = 50000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const rel = (from, to) => u32(to - from >>> 0);

// EBX = DATA: [ebx+124] loop counter, [ebx+120] calls, [ebx+116] last CR2,
// [ebx+112] last fault EIP, [ebx+108] faults, [ebx+104] faults elsewhere.
const caller = [];
caller.push(0xF6, 0x43, 124, 63);                                   // top: TEST BYTE [ebx+124], 63
caller.push(0x75, 14);                                              // JNZ call
caller.push(0x83, 0x25, ...u32(PTE), 0xFE);                         // AND DWORD [pte], ~1
caller.push(0x0F, 0x01, 0x3D, ...u32(CALLEE));                      // INVLPG [callee]
caller.push(0xE8, ...rel(CALLER + caller.length + 5, CALLEE));      // call: CALL callee
caller.push(0xFF, 0x4B, 124);                                       // DEC DWORD [ebx+124]
caller.push(0x0F, 0x85, ...rel(CALLER + caller.length + 6, CALLER)); // JNZ top
caller.push(0xF4);                                                  // HLT
const callee = [0xFF, 0x43, 120, 0xC3];                             // INC DWORD [ebx+120]; RET
const handler = [
    0x50,                                                           // PUSH EAX
    0x8B, 0x44, 0x24, 0x08,                                         // MOV EAX, [esp+8] (EIP)
    0x89, 0x43, 112,                                                // MOV [ebx+112], EAX
    0x3D, ...u32(CALLEE),                                           // CMP EAX, callee
    0x74, 3,                                                        // JE +3
    0xFF, 0x43, 104,                                                // INC DWORD [ebx+104]
    0x0F, 0x20, 0xD0,                                               // MOV EAX, CR2
    0x89, 0x43, 116,                                                // MOV [ebx+116], EAX
    0xFF, 0x43, 108,                                                // INC DWORD [ebx+108]
    0x83, 0x0D, ...u32(PTE), 0x01,                                  // OR DWORD [pte], 1
    0x0F, 0x01, 0x3D, ...u32(CALLEE),                               // INVLPG [callee]
    0x58,                                                           // POP EAX
    0x83, 0xC4, 0x04,                                               // ADD ESP, 4 (error code)
    0xCF,                                                           // IRETD
];

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        // (the page tier counts each instruction, compiles early, and its
        // functions are installed as they are compiled)
        ...compiled ? { jit_switches: { x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env() }, ir_sync_publication: true } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    cpu.mem8.set(caller, CALLER);
    cpu.mem8.set(callee, CALLEE);
    cpu.mem8.set(handler, HANDLER);
    cpu.mem8.fill(0, DATA, DATA + 128);
    cpu.mem8.fill(0, STACK - 0x1000, STACK);
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    view.setUint32(DATA + 124, ITERATIONS, true);
    // Vector 14: a present 32-bit interrupt gate to the handler.
    view.setUint16(0x7000 + 14 * 8, HANDLER & 0xFFFF, true);
    view.setUint16(0x7000 + 14 * 8 + 2, 8, true);
    view.setUint16(0x7000 + 14 * 8 + 4, 0x8E00, true);
    view.setUint16(0x7000 + 14 * 8 + 6, HANDLER >>> 16, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CALLER;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `status ${view.getUint32(0x608, true).toString(16)} counter ${view.getUint32(DATA + 124, true)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        status: view.getUint32(0x608, true),
        eip: cpu.instruction_pointer[0] >>> 0,
        esp: cpu.reg32[4] >>> 0,
        calls: view.getUint32(DATA + 120, true),
        faults: view.getUint32(DATA + 108, true),
        stray: view.getUint32(DATA + 104, true),
        fault_eip: view.getUint32(DATA + 112, true),
        cr2: view.getUint32(DATA + 116, true),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        pages: compiled ? e.x64_page_stat(37) : 0,
        native: compiled ? e.x64_page_stat(1) : 0,
    };
}

const reference = await run(await machine(false));
const page = await run(await machine(true));
assert.equal(reference.stray, 0, "the interpreter reported a fault away from the callee");
assert.equal(reference.faults, Math.floor(ITERATIONS / 64), "the interpreter took one fetch fault per unmapping");
assert(page.pages > 0, "no page was compiled");
assert(page.native > 0, "the page tier ran no instruction natively");
const strip = ({ pages, native, ...rest }) => rest;
const { pages, native } = page, actual = strip(page), expected = strip(reference);
assert.deepEqual(actual, expected, "the page tier's fetch faults differ from the interpreter");
console.log(`PASS: ${expected.faults} fetch faults on a callee page of the page tier (${pages} page compiles, ` +
    `${native} native instructions) match the interpreter`);
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/ir/differential/tier0_fuzz.mjs                                                     0000644 0000000 0000000 00000124713 00000000000 016720  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Legacy-mode differential fuzzing: random integer/SSE/x87 instruction
// sequences run hot in a loop (so their page is compiled by the x64 page tier,
// x64_page_legacy32, docs/jit-unification-plan.md P7.3; written for IR Tier-0,
// deleted in P7.5) and must leave exactly the interpreter's state: GPRs,
// EFLAGS (including the rarely read AF/OF, captured by PUSHFD/LAHF inside the
// loop), memory, XMM and x87 registers, and the retired-instruction count.
// Each program must also have entered page functions, and most of all
// programs' instructions must have run in them: else the comparison proves
// nothing about the page tier.
//
//   node tests/ir/differential/tier0_fuzz.mjs [cases=40] [seed=1] [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
// FUZZ_STRADDLE=1 places each program across a page boundary (multi-page
// functions, P7.3b). Debugging: FUZZ_DEBUG=1 prints each case's MXCSR and
// code, FUZZ_BODY=<hex> replaces the random instructions. JIT_SWITCHES applies
// to the compiled machine (tests/lib/jit_switches.mjs). FUZZ_COVERAGE=<share>
// lowers the share of instructions that must run in page functions (0.5).
// FUZZ_SS16=1 runs the programs on a 16-bit stack (SS.B clear, a 64 KiB
// segment at SS16; half the cases start at SP 0xFFF0, half at SP 8, whose
// pushes wrap): 32-bit code on a 16-bit stack, as Windows 98's thunks (M11).
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const cases = Number(process.argv[2] || 40);
let seed = Number(process.argv[3] || 1) >>> 0;
const wasm = process.argv[4] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// (a program's first instructions run interpreted until its page is hot; FP
// programs also reload MXCSR, interpreted, at the top, and the page tier
// must recompile the page with an entry after it)
const CODE = 0x500000, DATA = 0x600000, STACK = 0x610000, SS16 = 0x640000, ITERATIONS = 50000;
const random = () => {
    seed ^= seed << 13; seed >>>= 0; seed ^= seed >>> 17; seed ^= seed << 5; seed >>>= 0;
    return seed;
};
const pick = list => list[random() % list.length];
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
// EBX holds DATA (never written); ESP the stack. Byte registers exclude BL/BH.
const REGS = [0, 1, 2, 5, 6, 7];
const BYTE_REGS = [0, 1, 2, 4, 5, 6];
const reg = () => pick(REGS);
const disp = () => random() % 28 * 4;                    // [ebx + disp8], 0..108 (signed disp8)
const mem = r => [0x43 | r << 3, disp()];                 // modrm for [ebx + disp8]
const rr = (r, m) => 0xC0 | r << 3 | m;

// FUZZ_KIND=i0..i33 / s0..s13 restricts programs to one instruction kind
// (s11: SSE floating point over special values, see fp_instruction; s13: VEX
// forms among legacy ones, see vex_instruction; b: BMI, see bmi_instruction;
// j, g, e, d, o, a, m, v, c, p: P3.7's templates, r: P3.1's, see
// p37_instruction).
const only = process.env.FUZZ_KIND || "";
const straddle = process.env.FUZZ_STRADDLE === "1";
const ss16 = process.env.FUZZ_SS16 === "1";
function instruction() {
    const op = random() % 8, r = reg(), m = reg();
    const kind = random() % 34;
    switch(only.startsWith("i") ? Number(only.slice(1)) : kind) {
        case 0: return [op << 3 | 1, rr(r, m)];                                  // ALU r/m32, r32
        case 1: return [0x81, rr(op, m), ...u32(random())];                       // ALU r/m32, imm32
        case 2: return [0x83, rr(op, m), random() & 255];                         // ALU r/m32, imm8
        case 3: return [op << 3 | 3, ...mem(r)];                                  // ALU r32, m32
        case 4: return [op << 3 | 1, ...mem(r)];                                  // ALU m32, r32
        case 5: return [op << 3, rr(pick(BYTE_REGS), pick(BYTE_REGS))];          // ALU r/m8, r8
        case 6: return [0x66, op << 3 | 1, rr(r, m)];                             // ALU r/m16, r16
        case 7: return [0x80, rr(op, pick(BYTE_REGS)), random() & 255];           // ALU r/m8, imm8
        case 8: return [pick([0x40, 0x48]) | r];                                   // INC/DEC r32
        case 9: return [0xFF, 0x43 | (random() & 1) << 3, disp()];                // INC/DEC m32
        case 10: return [0xF7, rr(pick([2, 3]), m)];                              // NOT/NEG
        case 11: return [0xC1, rr(op, m), random() & 63];                         // shift/rotate imm
        case 12: return [0xD1, rr(op, m)];                                        // shift/rotate 1
        case 13: return [0xD3, rr(op, m)];                                        // shift/rotate CL
        case 14: return [0xC0, rr(op, pick(BYTE_REGS)), random() & 31];           // 8-bit shift/rotate
        case 15: return [0x66, 0xD3, rr(op, m)];                                  // 16-bit by CL
        case 16: return [0x0F, 0xAF, rr(r, m)];                                   // IMUL r, r/m
        case 17: return [0x6B, rr(r, m), random() & 255];                         // IMUL r, r/m, imm8
        case 18: return [0xF7, rr(pick([4, 5]), m)];                              // MUL/IMUL edx:eax
        case 19: return [0x0F, pick([0xA3, 0xAB, 0xB3, 0xBB]), rr(r, m)];         // BT* r, r
        case 20: return [0x0F, 0xBA, rr(4 + (random() & 3), m), random() & 255];  // BT* r, imm8
        case 21: return [0x0F, pick([0xBC, 0xBD]), rr(r, m)];                     // BSF/BSR
        case 22: return [0x0F, pick([0xA4, 0xAC]), rr(r, m), random() & 31];      // SHLD/SHRD imm
        case 23: return [0x0F, pick([0xA5, 0xAD]), rr(r, m)];                     // SHLD/SHRD CL
        case 24: return [0x0F, 0x40 | random() % 16, rr(r, m)];                   // CMOVcc
        case 25: return [0x0F, 0x90 | random() % 16, 0x43, disp()];               // SETcc m8
        case 26: return [0x0F, pick([0xC1, 0xB1]), rr(r, m)];                     // XADD/CMPXCHG
        case 27: return [0x0F, pick([0xC1, 0xB1]), ...mem(r)];                    // on memory
        case 28: return [0x9C, 0x8F, 0x43, disp()];                               // PUSHFD; POP m32
        case 29: return [0x9F, 0x88, 0x63, disp()];                               // LAHF; MOV m8, AH
        case 30: return [0x8D, 0x44 | r << 3, (random() & 3) << 6 | m << 3 | 3, random() & 255]; // LEA
        case 31: return [0x0F, pick([0xB6, 0xB7, 0xBE, 0xBF]), rr(r, m)];         // MOVZX/MOVSX
        case 32: return [pick([0x99, 0x98]), 0x87, rr(r, m)];                     // CDQ/CWDE; XCHG
        default: {                                                                 // DIV/IDIV ecx
            const signed = random() & 1;
            return [0xB9, ...u32(random() | 0x10000), 0x31, 0xD2, 0xF7, rr(6 + signed, 1)];
        }
    }
}
// P3.7's templates (docs/jit-unification-plan.md; IR Tier-0's, one kind per
// switch, t0_*, now the page tier's forms), among integer instructions:
// j: JECXZ and JCXZ over the instruction after them, taken and
//   not: ECX is often zero, or CX zero with the rest of ECX not
// g: MOV r32/r16/m16, Sreg; PUSH Sreg then POP r32 (the
//   push writes 16 bits of the slot)
// e: XCHG [ebx + disp8] with r32, r16 and r8
// d: CLD and STD
// o: POP m32 after PUSH r32/imm32/m32; POP [esp + disp8]
//   stays a step (its address uses ESP)
// a: PUSHAD, an instruction, POPAD
// v: MOVQ from MMX and XMM, MOVDQU and MOVSS stores
//   across the end of DATA's page (EDI = EBX + 0xFFE), which the fast path
//   refuses (the bytes there are compared)
// c: CLI (IF is clear in these programs: PUSHFD shows it)
// p: POP [ESP] and POP [ESP + 4]
// r (P3.1t): REP MOVS and STOS of bytes,
//   words and dwords between ESI and EDI in DATA: apart, overlapping
//   forward and backward, with DF set, ECX 0, across the end of DATA's
//   page, with a 16-bit address size or a DS override, STOS of a repeated
//   byte and of other values
// m: MOV ES/FS/GS from r16 and m16 with the flat data
//   selector, a null one or 0x18 (based at 4 KiB, added to the GDT for
//   it), then a load through the segment; MOV DS with the flat selector;
//   DS to 0x18 and back, which change flat segmentation (refused: steps)
function p37_instruction() {
    if(random() % 3 === 0) return instruction();
    const r = reg(), seg = random() % 6;
    switch(only) {
        case "j": switch(random() % 4) {
            case 0: return random() & 1 ? [0x31, 0xC9] : [0xB9, ...u32(random() & 0xFFFF0000)]; // ECX 0, CX 0
            case 1: { const next = instruction(); return [0x67, 0xE3, next.length, ...next]; }   // JCXZ over it
            default: { const next = instruction(); return [0xE3, next.length, ...next]; }       // JECXZ over it
        }
        case "g": switch(random() % 4) {
            case 0: return [0x8C, rr(seg, r)];                                    // MOV r32, Sreg
            case 1: return [0x66, 0x8C, rr(seg, r)];                              // MOV r16, Sreg
            case 2: return [0x8C, 0x43 | seg << 3, disp()];                       // MOV m16, Sreg
            default: return [...pick([[0x06], [0x0E], [0x16], [0x1E], [0x0F, 0xA0], [0x0F, 0xA8]]), 0x58 | r]; // PUSH Sreg; POP r32
        }
        case "e": switch(random() % 3) {
            case 0: return [0x87, ...mem(r)];                                     // XCHG m32, r32
            case 1: return [0x66, 0x87, ...mem(r)];                               // XCHG m16, r16
            default: return [0x86, 0x43 | pick(BYTE_REGS) << 3, disp()];          // XCHG m8, r8
        }
        case "d": return [pick([0xFC, 0xFD])];                                    // CLD, STD
        case "o": switch(random() % 4) {
            case 0: return [0x50 | r, 0x8F, 0x43, disp()];                        // PUSH r32; POP m32
            case 1: return [0x68, ...u32(random()), 0x8F, 0x43, disp()];          // PUSH imm32; POP m32
            case 2: return [0xFF, 0x73, disp(), 0x8F, 0x43, disp()];              // PUSH m32; POP m32
            default: return [0x50 | r, 0x50 | r, 0x8F, 0x44, 0x24, 0x00, 0x58 | r]; // POP [esp] (a step)
        }
        case "r": {
            const size = pick([1, 2, 4]), movs = random() & 1;
            const op = [...size === 2 ? [0x66] : [], (movs ? 0xA4 : 0xAA) | (size > 1 ? 1 : 0)];
            const lea = (register, offset) => [0x8D, 0x83 | register << 3, ...u32(offset)]; // LEA r32, [EBX + offset]
            const count = n => [0xB9, ...u32(n)];                                 // MOV ECX, n
            // (stores stay below DATA + 120, the loop counter at 124: at
            // most 56 bytes from a destination at most 60)
            const n = random() % (56 / size + 1);
            const a = random() % 120, b = random() % 61;
            const rep = (prefix = [], stos = false) => [0xF3, ...prefix, ...stos ? [...size === 2 ? [0x66] : [], 0xAA | (size > 1 ? 1 : 0)] : op];
            switch(random() % 8) {
                case 0: return [...lea(6, a), ...lea(7, b), ...count(n), ...rep()];       // apart or overlapping
                case 1: { const s = random() % 48; return [...lea(6, s), ...lea(7, s + size * (1 + random() % 3)), ...count(n), ...rep()]; } // forward overlap
                case 2: return [...lea(6, 60 + a % 40), ...lea(7, 60 + b % 40), ...count(n), 0xFD, ...rep(), 0xFC]; // DF set: downward
                case 3: return [...lea(6, a), ...lea(7, b), ...count(0), ...rep()];       // ECX 0
                case 4: return [...lea(6, a), ...lea(7, 0xFF0 - 2 * (random() & 7)), ...count(4 + random() % 8), ...rep()]; // across the page end
                case 5: return [0xB8, ...u32(pick([0, 0x41414141, 0xFFFFFFFF, random()])), ...lea(7, b), ...count(n), ...rep([], true)]; // STOS values
                case 6: return [...lea(6, a), ...lea(7, b), ...count(0x10000), 0x67, ...rep()]; // 16-bit address size: CX 0
                default: return [...lea(6, a), ...lea(7, b), ...count(n), ...rep([0x3E])]; // a DS override
            }
        }
        case "v": {
            const x = random() & 7;
            const store = pick([[0x0F, 0x7F], [0x66, 0x0F, 0xD6], [0xF3, 0x0F, 0x7F], [0xF3, 0x0F, 0x11]]);
            return [0x8D, 0xBB, ...u32(0xFFE), ...store, 0x07 | x << 3];          // LEA EDI, [EBX+0xFFE]; store [EDI]
        }
        case "c": return [0xFA];                                                  // CLI
        case "p": return random() & 1
            ? [0x50 | r, 0x50 | r, 0x8F, 0x04, 0x24, 0x58 | r, 0x58 | r]          // POP [ESP]
            : [0x50 | r, 0x50 | r, 0x50 | r, 0x8F, 0x44, 0x24, 0x04, 0x58 | r, 0x58 | r]; // POP [ESP+4]
        case "m": {
            // (ES, FS or GS, and its segment-override prefix)
            const s = pick([0, 4, 5]), prefix = { 0: 0x26, 4: 0x64, 5: 0x65 }[s], sel = pick([0x10, 0x18]);
            const load = (selector, sreg) => [0x66, 0xB8 | r, selector, 0x00, 0x8E, rr(sreg, r)];
            switch(random() % 6) {
                case 0: return load(sel, s);                                      // MOV Sreg, r16
                case 1: { const d = disp(); return [0x66, 0xC7, 0x43, d, sel, 0x00, 0x8E, 0x43 | s << 3, d]; } // MOV Sreg, m16
                case 2: return [0x66, 0x31, rr(r, r), 0x8E, rr(s, r), ...load(0x18, s)]; // null, then 0x18
                case 3: return load(0x10, 3);                                     // MOV DS, the flat selector
                case 4: return [...load(0x18, 3), 0x8B, 0x43 | r << 3, disp(), ...load(0x10, 3)]; // DS non-flat and back
                default: return [...load(0x18, s), prefix, 0x8B, 0x43 | r << 3, disp()]; // a load through it
            }
        }
        default: return [0x60, ...instruction(), 0x61];                          // PUSHAD; ...; POPAD
    }
}
// b: BMI1 and BMI2's VEX forms, TZCNT, LZCNT and MOVBE (P10; the page tier
// has templates for the hot ones of plan 5.1 and steps the others) on registers
// and [ebx + disp8]
function bmi_instruction() {
    // (then a SETcc m8 half the time: a condition right after the flags,
    // mostly of CF)
    const setcc = random() & 1 ? [0x0F, 0x90 | (random() & 1 ? pick([2, 3, 6, 7]) : random() % 16), 0x43, disp()] : [];
    return [...bmi_form(), ...setcc];
}
function bmi_form() {
    const r = reg(), v = reg(), m = reg();
    const rm = field => random() % 3 ? [rr(field, m)] : [0x43 | field << 3, disp()];
    const vex = (map, pp, op, field, vvvv) => [0xC4, 0xE0 | map, (~vvvv & 15) << 3 | pp, op, ...rm(field)];
    switch(random() % 10) {
        case 0: return vex(2, 0, 0xF2, r, v);                                        // ANDN
        case 1: return vex(2, 0, 0xF3, 1 + random() % 3, v);                         // BLSR/BLSMSK/BLSI
        case 2: return [0xB8 | v, ...u32(random() % 40), ...vex(2, 0, 0xF5, r, v)];  // BZHI (index 0-39)
        case 3: return vex(2, 1 + random() % 3, 0xF7, r, v);                         // SHLX/SARX/SHRX
        case 4: return [...random() & 1 ? [0xB8 | m, 0, 0, 0, 0] : [], 0xF3, 0x0F, pick([0xBC, 0xBD]), rr(r, m)]; // TZCNT/LZCNT (of 0: CF)
        case 5: return [...random() & 1 ? [] : [0xF3, 0x0F, pick([0xBC, 0xBD]), 0x43 | r << 3, disp()], 0x66, 0xF3, 0x0F, pick([0xBC, 0xBD]), ...rm(r)]; // (memory, 16-bit)
        case 6: return [...pick([[], [0x66]]), 0x0F, 0x38, pick([0xF0, 0xF1]), 0x43 | r << 3, disp()]; // MOVBE
        case 7: return [0xB8 | v, ...u32(random() & 0xFF0F), ...vex(2, 0, 0xF7, r, v)]; // BEXTR
        case 8: return vex(2, pick([2, 3]), 0xF5, r, v);                             // PEXT/PDEP
        default: return random() & 1 ? vex(2, 3, 0xF6, r, v)                         // MULX
            : [0xC4, 0xE3, 0x7B, 0xF0, ...rm(r), random() & 255];                  // RORX
    }
}
// SSE floating point (docs/simd-xsave-plan.md 7.4): the arithmetic forms,
// conversions and compares, and the moves and shuffles carrying values between
// them (compiled code tracks which registers hold neither NaNs nor denormals), on
// zeros, denormals, infinities, NaNs and values that overflow or underflow.
function fp_instruction(x, y) {
    const prefix = pick([[], [0x66], [0xF3], [0xF2]]);
    const packed = prefix.length === 0 || prefix[0] === 0x66;
    const source = () => random() % 3 ? [rr(x, y)] : [0x43 | x << 3, packed ? disp() & ~15 : disp() & ~7];
    switch(random() % 16) {
        case 0: case 1: case 2: case 3: case 4: case 5:
            return [...prefix, 0x0F, pick([0x51, 0x58, 0x59, 0x5C, 0x5D, 0x5E, 0x5F]), ...source()];
        case 6: return [...pick([[], [0xF3]]), 0x0F, pick([0x52, 0x53]), rr(x, y)];      // RCP/RSQRT
        case 7: return [...prefix, 0x0F, 0x5A, rr(x, y)];                                  // CVTPS2PD...
        case 8: return [...pick([[], [0x66], [0xF3]]), 0x0F, 0x5B, rr(x, y)];              // CVTDQ2PS...
        case 9: return [...pick([[0x66], [0xF2], [0xF3]]), 0x0F, 0xE6, rr(x, y)];          // CVTDQ2PD...
        case 10: {                                                                     // CVTSI2SS... CVT(T)SS2SI...
            const op = pick([0x2A, 0x2C, 0x2D]);
            return [pick([0xF3, 0xF2]), 0x0F, op, op === 0x2A ? rr(x, y) : rr(reg(), y)];
        }
        case 11: return [...pick([[], [0x66]]), 0x0F, pick([0x2E, 0x2F]), rr(x, y)];        // (U)COMIS*
        case 12: return random() % 3 ? [pick([0xF3, 0xF2]), 0x0F, 0x10, rr(x, y)]         // MOVSS/MOVSD
            : [0x0F, 0x28, rr(x, y)];                                                      // MOVAPS
        case 13: return random() & 1 ? [0x0F, pick([0x14, 0x15, 0x16]), rr(x, y)]          // UNPCK*/MOVLHPS
            : [0x0F, 0xC6, rr(x, y), random() & 255];                                      // SHUFPS
        case 14: return [0x0F, 0x57, rr(x, random() & 1 ? x : y)];                         // XORPS (zero idiom)
        default: return random() & 1 ? [0x0F, 0x28, 0x43 | x << 3, disp() & ~15]          // MOVAPS xmm, m128
            : [pick([0xF3, 0xF2]), 0x0F, 0x10, 0x43 | x << 3, disp() & ~7];               // MOVSS/MOVSD xmm, m
    }
}
const SPECIAL_SINGLE = [0, 0x80000000, 0x3F800000, 0xBF800000, 1, 0x807FFFFF, 0x00800000, 0x00800001, 0x7F7FFFFF,
    0x7F800000, 0xFF800000, 0x7FC00000, 0x7FA00000, 0xFFC12345, 0x3EFFFFFF, 0x01000000, 0x1F800000, 0x5F000000,
    0x40490FDB, 0x3DCCCCCD, 0x4F000000, 0xCF000001];
const SPECIAL_DOUBLE = [[0, 0], [0, 0x80000000], [0, 0x3FF00000], [1, 0], [0xFFFFFFFF, 0x800FFFFF], [0, 0x00100000],
    [1, 0x00100000], [0xFFFFFFFF, 0x7FEFFFFF], [0, 0x7FF00000], [0, 0xFFF00000], [0, 0x7FF80000], [1, 0x7FF00000],
    [0xFFFFFFFF, 0x3FDFFFFF], [0, 0x00200000], [0, 0x1FF00000], [0, 0x5FF00000], [0x54442D18, 0x400921FB],
    [0x9999999A, 0x3FB99999], [0, 0x41E00000], [0, 0xC1E00000]];
/** 16 bytes of special floats (4 singles or 2 doubles) as words */
function special_words() {
    if(random() & 1) return Array.from({ length: 4 }, () => random() % 5 ? pick(SPECIAL_SINGLE) : random());
    return Array.from({ length: 2 }, () => random() % 5 ? pick(SPECIAL_DOUBLE) : [random(), random()]).flat();
}
// s12: what compiled code knows about registers within a block. Values around the
// smallest normal, whose sums and differences are exact denormals, consumed
// by forms that are then admitted natively unless that knowledge is right
// (MXCSR with only PE set keeps a missed DE or IE visible).
// (no denormals or NaNs to begin with: they would set DE and IE anyway)
const NEAR_SINGLE = [0x00800000, 0x00800001, 0x00800003, 0x80800000, 0x80800001, 0x00C00000, 0x3F800000,
    0x4B000000, 0, 0x80000000];
const NEAR_DOUBLE = [[0, 0x00100000], [1, 0x00100000], [3, 0x00100000], [0, 0x80100000], [1, 0x80100000],
    [0, 0x00180000], [0, 0x3FF00000], [0, 0x43300000], [0, 0], [0, 0x80000000]];
// (one precision per program: the halves of doubles are often denormal
// singles, which would set DE anyway)
let near_single = true, last = 0;
function near_words() {
    const near = (list, k) => random() & 1 ? list[k] : pick(list);
    // (a fourth of the registers with a denormal or NaN above lane 0, which a
    // check of lane 0 alone or a wrong shuffle would let through)
    const odd = random() % 4 ? -1 : 1 + random() % (near_single ? 3 : 1);
    if(near_single) return Array.from({ length: 4 }, (_, i) => i === odd ? pick([0x00000003, 0x80400000, 0x7FC00000]) : near(NEAR_SINGLE, random() % 5));
    return Array.from({ length: 2 }, (_, i) => i === odd ? pick([[3, 0], [0, 0x80080000], [0, 0x7FF80000]]) : near(NEAR_DOUBLE, random() % 5)).flat();
}
function tracking_instruction(x, y) {
    const single = near_single;
    // Patterns for each fact compiled code keeps, a consumer reading what a wrong
    // fact would leave unchecked (z: another register)
    const z = (x + 1 + random() % 7) & 7;
    const packed = single ? [] : [0x66], scalar = single ? [0xF3] : [0xF2];
    switch(random() % 8) {
        case 0: // a clean register shuffled with an unchecked one
            return [...packed, 0x0F, 0x59, rr(x, x),
                ...single ? [0x0F, 0xC6, rr(x, y), random() & 255] : [0x66, 0x0F, pick([0x14, 0x15]), rr(x, y)],
                ...packed, 0x0F, 0x58, rr(z, x)];
        case 1: // a scalar check covers lane 0 only
            return [...scalar, 0x0F, pick([0x58, 0x59, 0x5D]), rr(x, y), ...packed, 0x0F, pick([0x58, 0x5F]), rr(z, y)];
        case 2: // a sum may be an exact denormal
            return [...packed, 0x0F, pick([0x58, 0x5C]), rr(x, y), ...packed, 0x0F, pick([0x58, 0x5D, 0x59]), rr(z, x)];
        case 3: // copies and scalar moves
            return [...packed, 0x0F, 0x59, rr(x, x), ...pick([[0x0F, 0x28, rr(z, y)], [...scalar, 0x0F, 0x10, rr(x, y)]]),
                ...packed, 0x0F, 0x58, rr(z, x)];
    }
    // (reading the last result half of the time)
    if(random() & 1) y = last;
    last = x;
    const prefix = single ? pick([[], [0xF3]]) : pick([[0x66], [0xF2]]);
    switch(random() % 10) {
        case 0: case 1: case 2: return [...prefix, 0x0F, pick([0x58, 0x5C]), rr(x, y)];        // ADD/SUB
        case 3: return [...prefix, 0x0F, pick([0x59, 0x5D, 0x5F, 0x51, 0x5E]), rr(x, y)];      // MUL/MIN/MAX/SQRT/DIV
        // (only templated forms: an interpreted one ends the block)
        case 4: return [single ? 0xF3 : 0xF2, 0x0F, 0x10, rr(x, y)];                             // MOVSS/MOVSD
        case 5: return [...(single ? [] : [0x66]), 0x0F, pick([0x2E, 0x2F]), rr(x, y)];         // (U)COMIS*
        case 6: return [0x0F, 0x28, rr(x, y)];                                                    // MOVAPS
        case 7: return single ? [0x0F, 0xC6, rr(x, y), random() & 255]                          // SHUFPS
            : random() & 1 ? [0x66, 0x0F, 0xC6, rr(x, y), random() & 3]                          // SHUFPD
            : [0x66, 0x0F, pick([0x14, 0x15]), rr(x, y)];                                        // UNPCKxPD
        case 8: return single ? [0x0F, 0x5A, rr(x, y)] : [0x66, 0x0F, 0x28, rr(x, y)];          // CVTPS2PD / MOVAPD
        default: return [0x0F, 0x57, rr(x, x)];                                                   // XORPS x, x
    }
}
// s13: VEX forms (AVX, P5 part 5; their templates are the legacy ones
// with a first source and bits 255:128 of the destination zeroed) among legacy
// forms with templates (CMPPS, MOVMSKPS, PMOVMSKB, BLENDVPS...), over special
// values. VEX.vvvv (z) is the first source; an immediate shift's destination.
function vex_instruction(x, y) {
    const z = random() & 7;
    const c5 = (pp, vvvv = 0) => [0xC5, 0x80 | (~vvvv & 15) << 3 | pp];
    const c4 = (map, pp, vvvv = 0) => [0xC4, 0xE0 | map, (~vvvv & 15) << 3 | pp];
    const source = () => random() % 3 ? [rr(x, y)] : [0x43 | x << 3, disp()];
    const legacy_source = aligned => random() % 3 ? [rr(x, y)] : [0x43 | x << 3, aligned ? disp() & ~15 : disp() & ~7];
    switch(random() % 20) {
        case 0: case 1: case 2: {                                                 // VSQRT VADD VMUL VSUB VMIN VDIV VMAX
            const pp = random() & 3, op = pick([0x51, 0x58, 0x59, 0x5C, 0x5D, 0x5E, 0x5F]);
            return [...c5(pp, op === 0x51 && pp < 2 ? 0 : z), op, ...source()];
        }
        case 3: return [...c5(pick([0, 1]), z), pick([0x54, 0x55, 0x56, 0x57, 0x14, 0x15]), ...source()]; // logic, unpacks
        case 4: return [...c5(1, z), pick([0xFC, 0xFE, 0xEF, 0xDB, 0xDF, 0x74, 0x76, 0x64, 0xD5, 0xF6, 0x62, 0x6B, 0xD2, 0xE2]), ...source()];
        case 5: return [...c5(random() & 3, z), 0xC2, ...source(), random() & 31];   // VCMPxx
        case 6: return [...c5(pick([0, 1])), pick([0x2E, 0x2F]), rr(x, y)];          // V(U)COMIS*
        case 7: return [...c5(pick([2, 3]), z), 0x10, rr(x, y)];                     // VMOVSS/SD xmm, xmm, xmm
        case 8: return [...c5(pick([2, 3])), pick([0x10, 0x11]), 0x43 | x << 3, disp()]; // VMOVSS/SD with memory
        case 9: return [...c5(pick([0, 1])), pick([0x28, 0x10, 0x11]), rr(x, y)];   // VMOVAPS/UPS
        case 10: {                                                                    // VPMOVMSKB, VMOVMSKPS/PD
            // (VPMOVMSKB has no NP form: #UD would end the program early)
            const pp = pick([0, 1, 1]), op = random() & 1 ? 0xD7 : 0x50;
            return [...c5(op === 0xD7 ? 1 : pp), op, rr(reg(), y)];
        }
        case 11: return [...c4(3, 1, z), pick([0x4A, 0x4B, 0x4C]), ...source(), (random() & 7) << 4]; // VBLENDVPS/PD, VPBLENDVB
        case 12: {                                                                    // VPSxx imm: VEX.vvvv the destination
            const op = pick([0x71, 0x72, 0x73]);
            return [...c5(1, x), op, rr(op === 0x73 ? pick([2, 3, 6, 7]) : pick([2, 4, 6]), y), random() & 63];
        }
        case 13: return [...c5(0), 0x77];                                             // VZEROUPPER
        case 14: return [...c5(pick([2, 3]), z), 0x5A, ...source()];                 // VCVTSS2SD/SD2SS
        case 15: return [...c5(pick([2, 3]), z), 0x2A, rr(x, reg())];                // VCVTSI2SS/SD
        case 16: return [...c5(pick([2, 3])), pick([0x2C, 0x2D]), rr(reg(), y)];     // VCVT(T)SS2SI/SD2SI
        case 17: return [...pick([[], [0x66], [0xF3], [0xF2]]), 0x0F, 0xC2, ...legacy_source(true), random() & 255]; // CMPxx
        case 18: return [...pick([[], [0x66]]), 0x0F, 0x50, rr(reg(), y)];          // MOVMSKPS/PD
        default: return random() & 1 ? [0x66, 0x0F, 0xD7, rr(reg(), y)]             // PMOVMSKB
            : [0x66, 0x0F, 0x38, pick([0x10, 0x14, 0x15]), ...legacy_source(true)];   // PBLENDVB, BLENDVPS/PD
    }
}
// Masked MXCSRs: defaults, PE set, all flags set, rounding modes, DAZ and FZ
const FP_MXCSRS = [0x1F80, 0x1FA0, 0x1FBF, 0x3FA0, 0x5F80, 0x7FA0, 0x1FE0, 0x9FA0, 0x9FE0];
function simd() {
    const x = random() & 7, y = random() & 7;
    const kind = random() % 13;
    switch(only.startsWith("s") ? Number(only.slice(1)) : kind) {
        case 0: return [0x0F, 0x10, 0x43 | x << 3, disp() & ~15];                 // MOVUPS xmm, m128
        case 1: return [0x0F, pick([0x58, 0x59, 0x5C, 0x5D, 0x5F]), rr(x, y)];     // ADDPS...
        case 2: return random() & 1 ? [0xF2, 0x0F, pick([0x58, 0x59, 0x5C, 0x51]), rr(x, y)] // ADDSD...
            : [0xF2, 0x0F, pick([0x10, 0x11, 0x58, 0x59]), 0x43 | x << 3, disp()];
        case 3: return [0x66, 0x0F, pick([0xFE, 0xFD, 0xEF, 0xDB, 0xD5, 0xF6, 0x62, 0x6B]), rr(x, y)];
        case 4: return random() & 1 ? [0x0F, 0xC6, rr(x, y), random() & 255]      // SHUFPS
            : [0x0F, 0xC6, 0x43 | x << 3, disp() & ~15, random() & 255];
        case 5: return [0x66, 0x0F, 0x70, rr(x, y), random() & 255];              // PSHUFD
        case 6: return [0x0F, 0x2E, rr(x, y)];                                    // UCOMISS
        case 7: return [0xF2, 0x0F, 0x2C, rr(reg(), y)];                          // CVTTSD2SI
        case 8: return [0x0F, 0x11, 0x43 | x << 3, disp() & ~15];                 // MOVUPS m128, xmm
        case 10: {                                                                 // SSSE3
            const op = pick([0x00, 0x00, 0x01, 0x04, 0x0B, 0x1C]);                 // (PSHUFB has a template)
            switch(random() % 3) {
                case 0: return [0x66, 0x0F, 0x38, op, rr(x, y)];
                case 1: return [0x66, 0x0F, 0x38, op, 0x43 | x << 3, disp() & ~15];
                default: return [0x66, 0x0F, 0x3A, 0x0F, rr(x, y), random() & 31];  // PALIGNR
            }
        }
        case 11: return fp_instruction(x, y);
        case 12: return tracking_instruction(x, y);
        case 13: return vex_instruction(x, y);
        default: return [0x66, 0x0F, 0x72, rr(pick([2, 4, 6]), x), random() & 63]; // PSxLD imm
    }
}
// Register-only x87 runs between loads and stores (depth-tracked).
function x87_run() {
    const d = () => disp() & ~7, out = [];
    let depth = 0;
    for(let k = 0; k < 2 + (random() & 1); k++) { out.push(0xDD, 0x43, d()); depth++; }
    for(let k = 0; k < 4 + random() % 8; k++) {
        const r = random() % depth, op = random() % 11;
        if(op === 0 && depth < 7) { out.push(0xD9, 0xC0 + r); depth++; }                       // FLD ST(r)
        else if(op === 1 && depth < 7) { out.push(0xD9, random() & 1 ? 0xE8 : 0xEE); depth++; } // FLD1/FLDZ
        else if(op === 2) out.push(0xD9, 0xC8 + r);                                              // FXCH
        else if(op === 3) out.push(0xD8, 0xC0 + 8 * pick([0, 1, 4, 5, 6, 7]) + r);               // Fop ST0, ST(r)
        else if(op === 4) out.push(0xDC, 0xC0 + 8 * pick([0, 1, 4, 5, 6, 7]) + r);               // Fop ST(r), ST0
        else if(op === 5 && depth >= 2) { out.push(0xDE, 0xC0 + 8 * pick([0, 1, 4, 5, 6, 7]) + Math.max(1, r)); depth--; } // FopP
        else if(op === 6) out.push(0xD9, random() & 1 ? 0xE0 : 0xE1);                           // FCHS/FABS
        else if(op === 7) out.push(0xDD, 0xD0 + r);                                              // FST ST(r)
        else if(op === 8 && depth >= 2) { out.push(0xDD, 0xD8 + Math.max(1, r)); depth--; }      // FSTP ST(r)
    }
    while(depth--) out.push(0xDD, 0x5B, d());                                                   // FSTP m64
    return out;
}
// Balanced x87 sequences (the stack is empty between them).
function x87() {
    const d = () => disp() & ~7, i = random() & 1;
    if(random() & 1) return x87_run();
    switch(random() % 8) {
        case 0: return [0xD9, 0x43, d(), 0xDD, 0x43, d(), 0xDE, 0xC9, 0xD8, 0xC0, 0xDD, 0x5B, d()]; // FLD m32; FLD m64; FMULP; FADD st0; FSTP m64
        case 1: return [0xDB, 0x43, d(), 0xDB, 0x5B, d()];                                   // FILD m32; FISTP m32
        case 2: return [0xD9, 0xE8, 0xD9, 0xEE, 0xDF, 0xF1, 0xDD, 0xD8];                     // FLD1; FLDZ; FCOMIP st1; FSTP st0
        case 3: return [0xD9, 0x43, d(), 0xD9, 0xE0, 0xD9, 0xE1, 0xD9, 0x5B, d()];            // FLD; FCHS; FABS; FSTP m32
        case 4: return [0xDD, 0x43, d(), 0xDD, 0x43, d(), 0xD9, 0xC9, 0xDE, 0xE9, 0xDF, 0xE0, 0xDD, 0x5B, d()]; // FXCH; FSUBP; FNSTSW AX
        case 5: return [0xD9, 0xE8, 0xDD, 0x43, d(), 0xDB, 0xF1, 0xDA, 0xC1 + 8 * i, 0xDD, 0xD9, 0xDD, 0xD8]; // FCOMI; FCMOVB/E
        case 6: return [0xDF, 0x43, d(), 0xDE, 0x43, d(), 0xDF, 0x5B, d()];                  // FILD m16; FIADD m16; FISTP m16
        default: return [0xD9, 0x7B, d(), 0xD9, 0x6B, d(), 0xDD, 0x43, d(), 0xDD, 0x5B, d()];  // FNSTCW; FLDCW; FLD; FSTP
    }
}
// s11/s12 iterations start alike: LDMXCSR and MOVAPS of all registers from
// DATA + 256.. (not compared), so that a flag missed in compiled code is not
// set by a later iteration (MXCSR's flags are sticky).
const RESET = 256;
function reset() {
    const out = [0x0F, 0xAE, 0x93, ...u32(RESET + 128)];
    for(let k = 0; k < 8; k++) out.push(0x0F, 0x28, 0x83 | k << 3, ...u32(RESET + 16 * k));
    return out;
}
function program() {
    const body = ["s11", "s12", "s13"].includes(only) ? reset() : [];
    const mix = random() % 5;
    if(process.env.FUZZ_BODY) body.push(...process.env.FUZZ_BODY.match(/../g).map(h => parseInt(h, 16)));
    else
    // (s12: short, so that one missed flag is not set by anything else)
    for(let k = 0; k < (only === "s12" ? 4 + random() % 6 : 40); k++) {
        const vector = only ? only.startsWith("s") : !(mix && random() % 5);
        const float = only ? only === "x" : random() % 7 === 0;
        // Single-kind programs still interleave PUSHFD/LAHF to expose FLAGS.
        body.push(...(only && only !== "s12" && k % 4 === 3 ? [0x9C, 0x8F, 0x43, disp()] : only === "b" ? bmi_instruction() :
            ["j", "g", "e", "d", "o", "a", "m", "v", "c", "p", "r"].includes(only) ? p37_instruction() :
            float ? x87() : vector ? simd() : instruction()));
    }
    // DEC DWORD [ebx + 124]; JNZ top; HLT
    const tail = [0xFF, 0x4B, 124];
    const jump = -(body.length + tail.length + 6);
    return [...body, ...tail, 0x0F, 0x85, ...u32(jump), 0xF4];
}

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        // (page functions are installed as they are compiled, not in a Promise
        // continuation, which a whole program can run ahead of)
        ir_sync_publication: true,
        // (AVX for s13: CR4.OSXSAVE and XCR0 set in run; BMI for b, with the
        // x86-64 profile's LZCNT)
        cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", ...only === "b" ? ["BMI1", "BMI2", "LZCNT", "MOVBE"] : []],
        ...only === "b" ? { cpu_type: "x86_64" } : {}, cpu_features_unreleased: true,
        // (the page tier counts each instruction: blocks count theirs at
        // entry by default, more than run when a retry leaves one early; and
        // compiles, and recompiles for new entries, as soon as long mode)
        ...compiled ? { jit_switches: { x64_block_count: 0, x64_legacy_heat: 2000, x64_legacy_recompile_misses: 64,
            ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(only === "m") {
        // A fourth descriptor: data based at 0x1000, not yet accessed (run
        // clears the bit again for each case)
        const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset), gdt = cpu.gdtr_offset[0] >>> 0;
        view.setUint32(gdt + 24, 0x1000FFFF, true);
        view.setUint32(gdt + 28, 0x00CF9200, true);
        cpu.gdtr_size[0] = 31;
    }
    return { vm, cpu, e, compiled };
}

async function run(m, code, init, page, split) {
    const { vm, cpu, e } = m;
    // A fresh code page per case: mem8.set bypasses code-write detection.
    // Straddling programs start `split` bytes before the end of a page.
    const base = split ? CODE + page * 0x2000 + 0x1000 - split : CODE + page * 0x1000;
    cpu.mem8.set(code, base);
    cpu.mem8.set(init.data, DATA);
    if(only === "v" || only === "r") cpu.mem8.fill(0, DATA + 0xFF0, DATA + 0x1010);
    if(only === "m") cpu.mem8[(cpu.gdtr_offset[0] >>> 0) + 29] &= ~1;
    cpu.mem8.fill(0, STACK - 0x1000, STACK);
    new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.set(init.regs);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    if(ss16) {
        // (SS 0x20, a 16-bit data segment at SS16)
        cpu.mem8.fill(0, SS16, SS16 + 0x10000);
        cpu.sreg[2] = 0x20; cpu.segment_offsets[2] = SS16; cpu.segment_limits[2] = 0xFFFF;
        cpu.segment_access_bytes[2] = 0x93; cpu.segment_is_null[2] = 0; cpu.stack_size_32[0] = 0;
        cpu.reg32[4] = init.sp16;
    }
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = base;
    e.fpu_discard_cache();
    new Uint32Array(cpu.reg_xmm32s.buffer, cpu.reg_xmm32s.byteOffset, 32).set(init.xmm);
    // AVX: CR4.OSXSAVE, XCR0 7 and the YMM registers' upper halves (gp::xcr0
    // and gp::ymm_hi, 1600 and 1616 bytes after the XMM registers)
    cpu.cr[4] |= 1 << 18;
    new Uint32Array(cpu.reg_xmm32s.buffer, cpu.reg_xmm32s.byteOffset + 1600, 2).set([7, 0]);
    new Uint32Array(cpu.reg_xmm32s.buffer, cpu.reg_xmm32s.byteOffset + 1616, 32).set(init.ymm);
    cpu.mxcsr[0] = init.mxcsr;
    cpu.fpu_st.fill(0); cpu.fpu_stack_empty[0] = 255; cpu.fpu_stack_ptr[0] = 0;
    e.set_control_word(0x37F); cpu.fpu_status_word[0] = 0;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    // (page function activations, and native and stepped instructions)
    const activations = e.x64_page_stat(13), native = e.x64_page_stat(1), steps = e.x64_page_stat(4);
    vm.run();
    const end = performance.now() + 20000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            const v = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
            throw new Error(`timeout (${m.compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `status ${v.getUint32(0x608, true).toString(16)} counter ${v.getUint32(DATA + 124, true)} ` +
                `retired ${new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0} code ${Buffer.from(code).toString("hex")}`);
        }
        await sleep(0);
    }
    await vm.stop();
    const count = new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0;
    m.entries = e.x64_page_stat(13) - activations;
    m.interpreted = Math.max(0, count - (e.x64_page_stat(1) - native) - (e.x64_page_stat(4) - steps));
    return {
        regs: Array.from(cpu.reg32, v => v >>> 0),
        eip: cpu.instruction_pointer[0] >>> 0,
        eflags: e.get_eflags() >>> 0,
        data: Array.from(cpu.mem8.subarray(DATA, DATA + 256)),
        stack: Array.from(cpu.mem8.subarray(STACK - 64, STACK)),
        ...ss16 ? { stack_low: Array.from(cpu.mem8.subarray(SS16, SS16 + 64)), stack_top: Array.from(cpu.mem8.subarray(SS16 + 0xFFC0, SS16 + 0x10000)) } : {},
        xmm: Array.from(new Uint32Array(cpu.reg_xmm32s.buffer, cpu.reg_xmm32s.byteOffset, 32), v => v >>> 0),
        ymm: Array.from(new Uint32Array(cpu.reg_xmm32s.buffer, cpu.reg_xmm32s.byteOffset + 1616, 32), v => v >>> 0),
        mxcsr: cpu.mxcsr[0] >>> 0,
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        fpu: (e.fpu_sync_all(), [cpu.fpu_stack_ptr[0], cpu.fpu_stack_empty[0], cpu.fpu_status_word[0], ...Array.from(new Uint8Array(cpu.fpu_st.buffer, cpu.fpu_st.byteOffset, 128))]),
        status: new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x608, true),
        // (v: the bytes across the end of DATA's page)
        ...only === "v" || only === "r" ? { page_end: Array.from(cpu.mem8.subarray(DATA + 0xFF0, DATA + 0x1010)) } : {},
        // (m: the descriptor at 0x18, whose accessed bit its first load sets)
        ...only === "m" ? { descriptor: Array.from(cpu.mem8.subarray((cpu.gdtr_offset[0] >>> 0) + 24, (cpu.gdtr_offset[0] >>> 0) + 32)) } : {},
    };
}

const reference = await machine(false), page = await machine(true);
// (instructions retired in all, and in page functions; the smallest share of
// one program's in page functions)
let failures = 0, uncompiled = 0, retired = 0, compiled = 0, least = 1;
for(let c = 0; c < cases; c++) {
    near_single = (random() & 1) === 1;
    const code = program();
    const special = only === "s11" || only === "s13", near = only === "s12";
    const reset_state = (xmm, mxcsr) => [...xmm.flatMap(u32), ...u32(mxcsr)];
    const init = {
        regs: Array.from({ length: 8 }, () => random()),
        // (FUZZ_SS16: the initial SP, below STACK or wrapping)
        sp16: ss16 ? random() & 1 ? 0xFFF0 : 8 : 0,
        data: special ? Array.from({ length: 16 }, () => special_words().flatMap(u32)).flat()
            : Array.from({ length: 256 }, () => random() & 255),
        // Finite floats: exponents kept in range so arithmetic rarely makes NaNs.
        xmm: special ? Array.from({ length: 8 }, special_words).flat()
            : near ? Array.from({ length: 8 }, near_words).flat()
            : Array.from({ length: 32 }, () => random() & 0xBFFFFFFF),
        mxcsr: special ? pick(FP_MXCSRS) : near ? 0x1FA0 : 0x1F80,
        ymm: Array.from({ length: 32 }, () => random()),
    };
    if(special || near) init.data.push(...reset_state(init.xmm, init.mxcsr));
    const split = straddle ? 4 + random() % (code.length - 8) : 0;
    const expected = await run(reference, code, init, c, split), actual = await run(page, code, init, c, split);
    if(process.env.FUZZ_DEBUG) console.log(`case ${c}: mxcsr ${expected.mxcsr.toString(16)} / ${actual.mxcsr.toString(16)} count ${expected.count} ` +
        `page function entries ${page.entries} interpreted ${page.interpreted} code ${Buffer.from(code).toString("hex")}` +
        ` (compiled ${page.e.x64_page_stat(0)} failed ${page.e.x64_page_stat(7)} retries ` +
        `${page.e.x64_page_stat(2)} steps ${page.e.x64_page_stat(4)} unknown ${page.e.x64_page_stat(3)})`);
    retired += actual.count;
    compiled += actual.count - page.interpreted;
    least = Math.min(least, 1 - page.interpreted / actual.count);
    if(!page.entries) {
        uncompiled++;
        console.log(`case ${c}: no page function ran (${actual.count} instructions, eip ${actual.eip.toString(16)}, status ${actual.status.toString(16)})\n` +
            `  code ${Buffer.from(code).toString("hex")}`);
    }
    for(const key of Object.keys(expected)) {
        try { assert.deepEqual(actual[key], expected[key]); }
        catch{
            failures++;
            console.log(`case ${c}: ${key} differs\n  code ${Buffer.from(code).toString("hex")}\n  expected ${JSON.stringify(expected[key])}\n  actual   ${JSON.stringify(actual[key])}`);
            break;
        }
    }
}
// (legacy-mode compiles, x64_page_stat 37, and steps: instructions that page
// functions left to the interpreter)
const pages = page.e.x64_page_stat(37), stepped = page.e.x64_page_stat(4);
await reference.vm.destroy(); await page.vm.destroy();
assert(pages > 0, "no page was compiled");
const percent = share => `${(100 * share).toFixed(1)}%`;
const coverage = `${percent(compiled / retired)} of the instructions ran in page functions (${percent((compiled - stepped) / retired)} ` +
    `templated), at least ${percent(least)} of each program's`;
if(failures || uncompiled || compiled < retired * Number(process.env.FUZZ_COVERAGE || 0.5)) {
    console.log(`FAIL: ${failures}/${cases} cases differ, no page function ran in ${uncompiled}; ${coverage}`);
    process.exit(1);
}
console.log(`PASS: ${cases} random programs, the page tier (${pages} page compiles) matches the interpreter; ${coverage}`);
process.exit(0);
                                                     source/v64/tests/ir/differential/tier0_irq_slow.mjs                                                 0000755 0000000 0000000 00000020720 00000000000 017555  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Interrupts that a page function's own device access makes deliverable
// (docs/jit-unification-plan.md P3.0b; written for IR Tier-0, deleted in
// P7.5, now run on the x64 page tier in legacy mode, P7.3). A hot loop sends itself
// an IPI through the local APIC's ICR, then sends another while the TPR
// blocks it and lowers the TPR. Each interrupt must arrive right after the
// APIC write that made it deliverable: the handler compares the return EIP
// with the one the loop stored, and EOIs. The interpreter delivers inside
// the write, after EIP advanced; a page function, whose GPRs and EIP are
// in Wasm locals, must leave that write to the interpreter: the page tier
// retries device accesses there. Delivered inside a page function's write,
// the interrupt frame would be built from stale state, IF cleared and the
// vector left in service: no further interrupt arrives.
//
//   node tests/ir/differential/tier0_irq_slow.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { set_jit_switches } from "../../../src/jit_switches.js";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, HANDLER = 0x503000, DATA = 0x600000, STACK = 0x610000;
const APIC = 0xFEE00000, APIC_TABLE = 0x21000, VECTOR = 0x40, ITERATIONS = 20000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const apic_write = (register, value) => [0xC7, 0x05, ...u32(APIC + register), ...u32(value)]; // MOV DWORD [apic+r], imm32
const expect = eip => [0xC7, 0x43, 92, ...u32(eip)];                                         // MOV DWORD [ebx+92], imm32
const SELF_IPI = 1 << 18 | VECTOR; // fixed delivery, destination shorthand "self"

// EBX = DATA: [ebx+124] loop counter, [ebx+108] interrupts taken, [ebx+104]
// interrupts at another EIP than [ebx+92], [ebx+100] last such EIP, [ebx+96]
// instructions run while an interrupt was pending behind the TPR.
const code = [
    0xB0, 0xFF, 0xE6, 0x21, 0xE6, 0xA1,             // MOV AL, 0xFF; OUT 0x21, AL; OUT 0xA1, AL (mask the PIC)
    ...apic_write(0xF0, 0x1FF),                     // SVR: APIC software enabled
    ...apic_write(0x80, 0),                         // TPR 0
    0xFB,                                           // STI
];
const top = CODE + code.length;
const loop = [];
const at = () => top + loop.length;
loop.push(...expect(at() + 7 + 10));                // the IPI arrives after the ICR write
loop.push(...apic_write(0x300, SELF_IPI));
loop.push(...apic_write(0x80, 0xF0));               // TPR class 15: vector 0x40 waits
loop.push(...expect(at() + 7 + 10 + 3 + 10));       // ... until the TPR write below
loop.push(...apic_write(0x300, SELF_IPI));
loop.push(0xFF, 0x43, 96);                          // INC DWORD [ebx+96]
loop.push(...apic_write(0x80, 0));
loop.push(0xFF, 0x4B, 124);                         // DEC DWORD [ebx+124]
loop.push(0x0F, 0x85, ...u32(top - (at() + 6)));    // JNZ top
loop.push(0xFA, 0xF4);                              // CLI; HLT
code.push(...loop);
const handler = [
    0x50,                                           // PUSH EAX
    0x8B, 0x44, 0x24, 0x04,                         // MOV EAX, [esp+4] (EIP)
    0x3B, 0x43, 92,                                 // CMP EAX, [ebx+92]
    0x74, 6,                                        // JE +6
    0xFF, 0x43, 104,                                // INC DWORD [ebx+104]
    0x89, 0x43, 100,                                // MOV [ebx+100], EAX
    0xFF, 0x43, 108,                                // INC DWORD [ebx+108]
    ...apic_write(0xB0, 0),                         // EOI
    0x58,                                           // POP EAX
    0xCF,                                           // IRETD
];

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga", acpi: true,
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        // (page functions are installed as they are compiled, not in a Promise
        // continuation, which the whole loop can run ahead of)
        ir_sync_publication: true,
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(compiled) set_jit_switches(e, cpu.wasm_memory, { x64_legacy_heat: 2000, ...jit_switches_from_env() }, "tier0_irq_slow");
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE);
    cpu.mem8.set(handler, HANDLER);
    cpu.mem8.fill(0, DATA, DATA + 128);
    cpu.mem8.fill(0, STACK - 0x1000, STACK);
    view.setUint32(DATA + 124, ITERATIONS, true);
    // The local APIC's page, identity mapped (the BIOS maps the first 64 MiB).
    cpu.mem8.fill(0, APIC_TABLE, APIC_TABLE + 4096);
    view.setUint32(0x10000 + (APIC >>> 22) * 4, APIC_TABLE | 3, true);
    view.setUint32(APIC_TABLE + (APIC >>> 12 & 1023) * 4, APIC | 3, true);
    // The vector's interrupt gate; the BIOS's IDT covers the exceptions only.
    view.setUint16(0x7000 + VECTOR * 8, HANDLER & 0xFFFF, true);
    view.setUint16(0x7000 + VECTOR * 8 + 2, 8, true);
    view.setUint16(0x7000 + VECTOR * 8 + 4, 0x8E00, true);
    view.setUint16(0x7000 + VECTOR * 8 + 6, HANDLER >>> 16, true);
    cpu.idtr_size[0] = 256 * 8 - 1;
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    e.full_clear_tlb();
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `status ${view.getUint32(0x608, true).toString(16)} counter ${view.getUint32(DATA + 124, true)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        status: view.getUint32(0x608, true),
        eip: cpu.instruction_pointer[0] >>> 0,
        esp: cpu.reg32[4] >>> 0,
        counter: view.getUint32(DATA + 124, true),
        taken: view.getUint32(DATA + 108, true),
        misplaced: view.getUint32(DATA + 104, true),
        misplaced_eip: view.getUint32(DATA + 100, true),
        pending_runs: view.getUint32(DATA + 96, true),
        pages: compiled ? e.x64_page_stat(37) : 0,
        // (the APIC writes, MOV DWORD [disp32], imm32, the page tier retried
        // in the interpreter)
        apic_steps: compiled ? e.x64_page_stat(2) : 0,
    };
}

const reference = await run(await machine(false));
assert.equal(reference.status, 0, "the interpreter took an exception");
assert.equal(reference.taken, 2 * ITERATIONS, "the interpreter took two interrupts per iteration");
assert.equal(reference.misplaced, 0, `the interpreter delivered at ${reference.misplaced_eip.toString(16)}`);
assert.equal(reference.pending_runs, ITERATIONS);
assert.equal(reference.esp, STACK);

const page = await run(await machine(true));
assert(page.pages > 0, "no page was compiled");
assert(page.apic_steps >= ITERATIONS, `the page tier retried ${page.apic_steps} APIC writes; the loop did not run in a page function`);
const strip = ({ pages, apic_steps, ...rest }) => rest;
assert.deepEqual(strip(page), strip(reference), "interrupts from the page tier's APIC writes differ from the interpreter");
console.log(`PASS: ${reference.taken} interrupts from APIC writes in page tier pages (${page.pages} page compiles, ` +
    `${page.apic_steps} retries) match the interpreter`);
process.exit(0);
                                                source/v64/tests/ir/differential/tier0_mode_ledger.mjs                                              0000755 0000000 0000000 00000011310 00000000000 020157  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The mode ledger (docs/jit-unification-plan.md P0.6) with the x64 page tier
// in legacy mode (written for IR Tier-0, deleted in P7.5): on from
// the machine's construction (the JIT switch mode_ledger), it must account
// for every retired instruction (cross-phase rule 3: its sum is
// core_statistics_get(0, 0)) and file them by mode and how they ran. The
// benchmark BIOS starts in real mode; then a hot loop in flat 32-bit code
// runs in a page function that steps CPUID and MOV DS, and loads DS
// with a segment based at 4 KiB for a few instructions, which therefore run
// as 32-bit code without flat segments.
//
//   node tests/ir/differential/tier0_mode_ledger.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build).
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { mode_ledger, mode_ledger_total } from "../../../tools/bench/jit_stats.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 30000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const code = [
    0x31, 0xC0,                                     // XOR EAX, EAX
    0x0F, 0xA2,                                     // CPUID
    0x66, 0xB8, 0x18, 0x00,                         // MOV AX, 0x18 (based at 0x1000)
    0x8E, 0xD8,                                     // MOV DS, AX
    0xA1, ...u32(0),                                // MOV EAX, [0] (linear 0x1000)
    0x01, 0xC6,                                     // ADD ESI, EAX
    0x66, 0xB8, 0x10, 0x00,                         // MOV AX, 0x10
    0x8E, 0xD8,                                     // MOV DS, AX
    0xFF, 0x0D, ...u32(DATA + 124),                 // DEC DWORD [DATA+124]
];
code.push(0x0F, 0x85, ...u32(-(code.length + 6)), 0xF4); // JNZ top; HLT

const vm = new V86({
    graphics_adapter: "bochs_vga", wasm_path: wasm, memory_size: 128 << 20, ir_sync_publication: true,
    // (the page tier compiles a page after 2000 instructions)
    jit_switches: { mode_ledger: 1, x64_legacy_heat: 2000 },
    bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
    disable_speaker: true, net_device: { type: "none" }, autostart: false,
});
await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
const cpu = vm.v86.cpu, e = cpu.wm.exports;
vm.run();
const ready = performance.now() + 15000;
while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
    assert(performance.now() < ready, "benchmark BIOS did not start");
    await sleep(1);
}
await vm.stop();

const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
// A fourth descriptor: a data segment based at 0x1000.
const gdt = cpu.gdtr_offset[0] >>> 0;
view.setUint32(gdt + 24, 0x1000FFFF, true);
view.setUint32(gdt + 28, 0x00CF9200, true);
cpu.gdtr_size[0] = 31;
cpu.mem8.set(code, CODE);
cpu.mem8.fill(0, DATA, DATA + 128);
view.setUint32(DATA + 124, ITERATIONS, true);
cpu.reg32.fill(0);
cpu.reg32[4] = STACK;
cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
cpu.instruction_pointer[0] = CODE;
e.update_state_flags();
e.full_clear_tlb();
vm.run();
const end = performance.now() + 30000;
while(!cpu.in_hlt[0]) {
    if(performance.now() > end) {
        await vm.stop();
        throw new Error(`timeout: eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} counter ${view.getUint32(DATA + 124, true)}`);
    }
    await sleep(0);
}
await vm.stop();
assert.equal(view.getUint32(0x608, true), 0, "the guest took an exception");
assert.equal(view.getUint32(DATA + 124, true), 0);

const ledger = mode_ledger(e), retired = e.core_statistics_get(0, 0);
const row = name => ledger[name] || {};
assert.equal(mode_ledger_total(ledger), retired, `the ledger accounts for every retired instruction: ${JSON.stringify(ledger)}`);
assert(row("real").interpreted > 0, "the BIOS's real-mode start is in the ledger");
assert(row("prot32.flat").page_native > ITERATIONS, `flat 32-bit code ran in a page function: ${JSON.stringify(ledger)}`);
assert(row("prot32.flat").page_step >= ITERATIONS / 2, `CPUID and MOV DS were stepped: ${JSON.stringify(ledger)}`);
assert(mode_ledger_total({ prot32: row("prot32") }) >= ITERATIONS / 2, `the instructions with DS based at 0x1000: ${JSON.stringify(ledger)}`);
await vm.destroy();
console.log(`PASS: the mode ledger accounts for ${retired} retired instructions: ${JSON.stringify(ledger)}`);
process.exit(0);
                                                                                                                                                                                                                                                                                                                        source/v64/tests/ir/differential/tier0_rep_fault.mjs                                                0000644 0000000 0000000 00000013444 00000000000 017701  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// REP MOVS/STOS faults with the x64 page tier's REP templates in legacy mode
// (docs/jit-unification-plan.md P3.1t and P7.3(5); written for IR Tier-0's,
// deleted in P7.5): a hot loop of REP MOVSD and REP STOSD whose last
// iteration's source, or destination, runs across the end of the mapped
// 64 MiB. The template leaves an operand that crosses a page to the
// interpreter, which copies to the page's end and faults; compiled code must leave
// exactly the interpreter's state: the registers (ESI, EDI and ECX where the
// copy stopped), the exception, CR2 and the bytes copied.
//
//   node tests/ir/differential/tier0_rep_fault.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build). The page tier compiles at
// 2000 instructions.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 20000;
// the last mapped bytes: 16 of them before 64 MiB
const EDGE = 0x4000000 - 16;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];

function program(stos)
{
    // ECX = 8; ESI, EDI in DATA; on the last iteration ([DATA+124] = 1) the
    // source (MOVS) or the destination (STOS) at EDGE instead
    const loop = [
        0xB9, ...u32(8),                                // MOV ECX, 8
        0xBE, ...u32(DATA + 0x100),                     // MOV ESI, DATA+0x100
        0xBF, ...u32(DATA + 0x200),                     // MOV EDI, DATA+0x200
        0xB8, ...u32(0),                                // MOV EAX, 0
        0x83, 0x3D, ...u32(DATA + 124), 0x01,           // CMP DWORD [DATA+124], 1
        0x75, 0x05,                                     // JNE +5
        stos ? 0xBF : 0xBE, ...u32(EDGE),               // MOV EDI/ESI, EDGE
        0xF3, stos ? 0xAB : 0xA5,                       // REP STOSD / REP MOVSD
        0xFF, 0x0D, ...u32(DATA + 124),                 // DEC DWORD [DATA+124]
    ];
    loop.push(0x0F, 0x85, ...u32(-(loop.length + 6)), 0xF4); // JNZ top; HLT
    return loop;
}

async function machine(compiled)
{
    const vm = new V86({
        graphics_adapter: "bochs_vga", wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const ready = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < ready, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    return { vm, cpu, e };
}

async function run({ vm, cpu, e }, code, page)
{
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE + page * 0x1000);
    for(let k = 0; k < 64; k++) view.setUint32(DATA + 0x100 + 4 * k, 0x01010101 * (k + 1), true);
    cpu.mem8.fill(0, DATA + 0x200, DATA + 0x300);
    for(let k = 0; k < 16; k++) cpu.mem8[EDGE + k] = 0xA0 + k;
    view.setUint32(DATA + 124, ITERATIONS, true);
    view.setUint32(0x608, 0, true);
    cpu.reg32.fill(0);
    cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE + page * 0x1000;
    e.update_state_flags();
    e.full_clear_tlb();
    const entries = e.x64_page_stat(13);
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        assert(performance.now() < end, `timeout: eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)}`);
        await sleep(0);
    }
    await vm.stop();
    return {
        regs: Array.from(cpu.reg32.subarray(0, 8), v => v >>> 0).filter((_, r) => r !== 4),
        status: view.getUint32(0x608, true),
        cr2: cpu.cr[2] >>> 0,
        counter: view.getUint32(DATA + 124, true),
        copied: Array.from(cpu.mem8.subarray(DATA + 0x200, DATA + 0x220)),
        edge: Array.from(cpu.mem8.subarray(EDGE, EDGE + 16)),
        entries: e.x64_page_stat(13) - entries,
    };
}

const reference = await machine(false), compiled = await machine(true);
for(const [page, stos] of [[0, false], [1, true]]) {
    const code = program(stos);
    const expected = await run(reference, code, page), actual = await run(compiled, code, page);
    assert(actual.entries > 0, `${stos ? "STOS" : "MOVS"}: no page function ran`);
    assert.equal(expected.status >>> 0, (0x80000000 | 14) >>> 0, `${stos ? "STOS" : "MOVS"}: the reference took no #PF: ${expected.status.toString(16)}`);
    for(const key of ["regs", "status", "cr2", "counter", "copied", "edge"])
        assert.deepEqual(actual[key], expected[key], `${stos ? "STOS" : "MOVS"}: ${key} differs`);
    console.log(`${stos ? "REP STOSD" : "REP MOVSD"}: #PF at ${expected.cr2.toString(16)} after ${ITERATIONS - 1} iterations, ` +
        `ESI ${expected.regs[6 - 1].toString(16)} EDI ${expected.regs[7 - 1].toString(16)} ECX ${expected.regs[1]}: as the interpreter`);
}
await reference.vm.destroy();
await compiled.vm.destroy();
console.log("PASS: REP MOVSD and STOSD faulting across the end of mapped memory leave the interpreter's state in the page tier");
process.exit(0);
                                                                                                                                                                                                                            source/v64/tests/ir/differential/tier0_segment_fault.mjs                                            0000644 0000000 0000000 00000016633 00000000000 020560  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Accesses through a null segment selector in compiled 32-bit code
// (docs/jit-unification-plan.md P7.2(3)): a hot loop loads a data segment
// based at 0x1000 into ES, so its code runs with other than flat segments,
// loads a null selector into DS, ES, FS or GS in turn, reads through it (#GP,
// whose handler counts it and skips the 3-byte read), and reloads the
// segment. The page tier's functions compiled for segment bases (written for
// IR Tier-0's for other than flat segments, deleted in P7.5) check the
// selector at each access; the faults, registers and counters must
// be the interpreter's.
//
//   node tests/ir/differential/tier0_segment_fault.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CODE = 0x500000, HANDLER = 0x503000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 40000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
// (ES, DS, FS, GS: the segment register, its override prefix)
const SEGMENTS = [[0, 0x26], [3, 0x3E], [4, 0x64], [5, 0x65]];
const load = (selector, sreg) => [0x66, 0xB8, selector, 0x00, 0x8E, 0xC0 | sreg << 3];   // MOV AX, sel; MOV Sreg, AX

// EBX = DATA (0x1000 less in the segment based at 0x1000): [ebx+124] loop
// counter, [ebx+108] faults, [ebx+104] faults at another EIP than [ebx+100]
const code = [];
code.push(...load(0x18, 0));                                         // ES: the segment based at 0x1000
for(const [sreg, prefix] of SEGMENTS) {
    code.push(...load(0, sreg));                                     // a null selector
    code.push(0x36, 0xC7, 0x43, 100, ...u32(CODE + code.length + 8)); // MOV DWORD SS:[ebx+100], the read's EIP
    code.push(prefix, 0x8B, 0x0B);                                   // MOV ECX, seg:[ebx] (#GP)
    code.push(...load(sreg === 0 ? 0x18 : 0x10, sreg));              // the segment again
    code.push(0x8B, 0x53, 64);                                       // MOV EDX, [ebx+64] (through DS)
}
code.push(0xFF, 0x4B, 124);                                          // DEC DWORD [ebx+124]
code.push(0x0F, 0x85, ...u32(-(code.length + 6)));                   // JNZ top
code.push(...load(0x10, 0), 0xF4, 0xEB, 0xFE);                       // ES flat; HLT
const handler = [
    0x50,                                                            // PUSH EAX
    0x8B, 0x44, 0x24, 0x08,                                          // MOV EAX, [esp+8] (EIP)
    0x36, 0x3B, 0x43, 100,                                           // CMP EAX, SS:[ebx+100]
    0x74, 4,                                                         // JE +4
    0x36, 0xFF, 0x43, 104,                                           // INC DWORD SS:[ebx+104]
    0x36, 0xFF, 0x43, 108,                                           // INC DWORD SS:[ebx+108]
    0x83, 0x44, 0x24, 0x08, 0x03,                                    // ADD DWORD [esp+8], 3 (skip the read)
    0x58,                                                            // POP EAX
    0x83, 0xC4, 0x04,                                                // ADD ESP, 4 (error code)
    0xCF,                                                            // IRETD
];

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env() } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    // A fourth descriptor: data based at 0x1000
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset), gdt = cpu.gdtr_offset[0] >>> 0;
    view.setUint32(gdt + 24, 0x1000FFFF, true);
    view.setUint32(gdt + 28, 0x00CF9300, true);
    cpu.gdtr_size[0] = 31;
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.set(code, CODE);
    cpu.mem8.set(handler, HANDLER);
    cpu.mem8.fill(0, DATA, DATA + 128);
    cpu.mem8.fill(0, STACK - 0x1000, STACK);
    view.setUint32(DATA + 124, ITERATIONS, true);
    view.setUint32(DATA + 64, 0x12345678, true);
    // Vector 13: a present 32-bit interrupt gate to the handler
    view.setUint16(0x7000 + 13 * 8, HANDLER & 0xFFFF, true);
    view.setUint16(0x7000 + 13 * 8 + 2, 8, true);
    view.setUint16(0x7000 + 13 * 8 + 4, 0x8E00, true);
    view.setUint16(0x7000 + 13 * 8 + 6, HANDLER >>> 16, true);
    cpu.reg32.fill(0);
    cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    const native = e.x64_page_stat(1);
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `counter ${view.getUint32(DATA + 124, true)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        status: view.getUint32(0x608, true),
        regs: Array.from(cpu.reg32, v => v >>> 0),
        faults: view.getUint32(DATA + 108, true),
        stray: view.getUint32(DATA + 104, true),
        counter: view.getUint32(DATA + 124, true),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        pages: compiled ? e.x64_page_stat(37) : 0,
        native: compiled ? e.x64_page_stat(1) - native : 0,
    };
}

const reference = await run(await machine(false));
assert.equal(reference.stray, 0, "the interpreter faulted elsewhere");
assert.equal(reference.faults, 4 * ITERATIONS, "the interpreter took a #GP per null access");
const compiled = await run(await machine(true));
assert(compiled.pages > 0, "no page was compiled");
assert(compiled.native > ITERATIONS, "the page tier ran the loop's instructions natively too seldom");
const strip = ({ pages, native, ...rest }) => rest;
assert.deepEqual(strip(compiled), strip(reference), "the page tier's null segment accesses differ from the interpreter");
console.log(`PASS: ${reference.faults} accesses through null DS, ES, FS and GS in the page tier (${compiled.pages} page compiles, ` +
    `${compiled.native} native instructions) fault as in the interpreter`);
process.exit(0);
                                                                                                     source/v64/tests/ir/differential/tier0_span_remap.mjs                                               0000644 0000000 0000000 00000014715 00000000000 020047  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// A remapped page of a multi-page function (docs/jit-unification-plan.md
// P7.3b, x64_page_clusters): a hot loop on one page calls into the next
// linear page and back, so the page tier compiles both into one function,
// and every 64th iteration points the second page's PTE at another physical
// page with other code (then INVLPG). The function verifies its pages at
// entry, and INVLPG ends an activation: the counters must be the
// interpreter's.
//
//   node tests/ir/differential/tier0_span_remap.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
// Runs the page tier (x64_page_legacy32 and x64_page_clusters) on top of
// JIT_SWITCHES.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// The loop at CODE, the called page at CODE + 0x1000 (linear), backed by
// PAGE_A or PAGE_B (physical, identity mapped elsewhere)
const CODE = 0x500000, PAGE_A = 0x520000, PAGE_B = 0x521000, DATA = 0x600000, STACK = 0x610000, ITERATIONS = 60000;
const PTE = 0x11000 + ((CODE + 0x1000) >>> 12) * 4;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const rel = (from, to) => u32(to - from >>> 0);

// EBX = DATA: [ebx+124] loop counter, [ebx+120] A's calls, [ebx+116] B's
// calls, [ebx+112] PTE flips
const loop = [];
loop.push(0xF6, 0x43, 124, 63);                                     // top: TEST BYTE [ebx+124], 63
loop.push(0x75, 25);                                                // JNZ call
loop.push(0xA1, ...u32(PTE));                                       // MOV EAX, [pte]
loop.push(0x35, ...u32((PAGE_A ^ PAGE_B) >>> 0));                   // XOR EAX, A ^ B
loop.push(0xA3, ...u32(PTE));                                       // MOV [pte], EAX
loop.push(0x0F, 0x01, 0x3D, ...u32(CODE + 0x1000));                 // INVLPG [page]
loop.push(0xFF, 0x43, 112);                                         // INC DWORD [ebx+112]
loop.push(0xE8, ...rel(CODE + loop.length + 5, CODE + 0x1000));     // call: CALL page
loop.push(0xFF, 0x4B, 124);                                         // DEC DWORD [ebx+124]
loop.push(0x0F, 0x85, ...u32(-(loop.length + 6)));                  // JNZ top
loop.push(0xF4, 0xEB, 0xFE);                                        // HLT
const code_a = [0xFF, 0x43, 120, 0x01, 0xD1, 0xC3];                 // INC DWORD [ebx+120]; ADD ECX, EDX; RET
const code_b = [0xFF, 0x43, 116, 0x29, 0xD1, 0xC3];                 // INC DWORD [ebx+116]; SUB ECX, EDX; RET

async function machine(compiled) {
    const vm = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: wasm, disable_jit: !compiled, memory_size: 128 << 20, // reference: the interpreter only
        ir_sync_publication: true,
        ...compiled ? { jit_switches: { x64_block_count: 0, x64_legacy_heat: 2000, ...jit_switches_from_env(),
            x64_page_legacy32: 1, x64_page_clusters: 1, x64_span_crossings: 64 } } : {},
        bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
        disable_speaker: true, net_device: { type: "none" }, autostart: false,
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run();
    const end = performance.now() + 15000;
    while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
        assert(performance.now() < end, "benchmark BIOS did not start");
        await sleep(1);
    }
    await vm.stop();
    if(compiled) assert(e.jit_set_page32(1));
    return { vm, cpu, e, compiled };
}

async function run({ vm, cpu, e, compiled }) {
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    cpu.mem8.fill(0xCC, CODE, CODE + 0x2000);
    cpu.mem8.set(loop, CODE);
    cpu.mem8.fill(0xCC, PAGE_A, PAGE_A + 0x2000);
    cpu.mem8.set(code_a, PAGE_A);
    cpu.mem8.set(code_b, PAGE_B);
    view.setUint32(PTE, PAGE_A | 3, true);
    cpu.mem8.fill(0, DATA, DATA + 128);
    cpu.mem8.fill(0, STACK - 0x1000, STACK);
    view.setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.fill(0);
    cpu.reg32[2] = 3; cpu.reg32[3] = DATA; cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = CODE;
    e.update_state_flags();
    e.full_clear_tlb();
    new Uint32Array(e.memory.buffer)[664 >> 2] = 0;
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout (${compiled ? "page tier" : "interpreter"}): eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} ` +
                `counter ${view.getUint32(DATA + 124, true)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    return {
        status: view.getUint32(0x608, true),
        regs: Array.from(cpu.reg32, v => v >>> 0),
        a: view.getUint32(DATA + 120, true),
        b: view.getUint32(DATA + 116, true),
        flips: view.getUint32(DATA + 112, true),
        counter: view.getUint32(DATA + 124, true),
        count: new Uint32Array(e.memory.buffer)[664 >> 2] >>> 0,
        spans: compiled ? e.x64_page_stat(38) : 0,
        native: compiled ? e.x64_page_stat(1) : 0,
    };
}

const reference = await run(await machine(false));
assert.equal(reference.a + reference.b, ITERATIONS, "the interpreter called the page once per iteration");
assert(reference.a > 0 && reference.b > 0, "the interpreter ran both mappings");
const compiled = await run(await machine(true));
assert(compiled.spans > 0, "the page tier compiled no span");
assert(compiled.native > ITERATIONS, "the page tier ran the loop's instructions natively too seldom");
const strip = ({ spans, native, ...rest }) => rest;
assert.deepEqual(strip(compiled), strip(reference), "a span's remapped page runs other code than in the interpreter");
console.log(`PASS: a span's second page remapped ${reference.flips} times: ${reference.a} calls to one mapping, ${reference.b} to the other, ` +
    `as in the interpreter (${compiled.spans} span compiles, ${compiled.native} native instructions)`);
process.exit(0);
                                                   source/v64/tests/ir/differential/tier0_step_profile.mjs                                             0000755 0000000 0000000 00000014226 00000000000 020415  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The step profile of the x64 page tier in legacy mode (docs/jit-unification-
// plan.md P0.5; written for IR Tier-0, deleted in P7.5): a hot loop whose
// page function steps CPUID and an IN at the last byte of its page. The next
// linear page is mapped to another physical page, so the instruction's
// second byte must be read through the page tables: Tier-0's two-byte
// histogram used to read it from the next physical page. With the JIT switch
// step_profile on, both steps land under their StepKeys (32-bit protected
// mode, x64page), as often as the two-byte histogram (x64_page_steps) counts
// them; off, the profile is gone.
//
//   node tests/ir/differential/tier0_step_profile.mjs [wasm]
// Needs build/bench/boot.bin (make bench-build): flat protected mode, paging.
import fs from "node:fs";
import assert from "node:assert/strict";
import { V86 } from "../../../build/libv86.mjs";
import { get_jit_switches, set_jit_switches } from "../../../src/jit_switches.js";
import { step_key, step_key_name, step_profile } from "../../../tools/step_profile.mjs";

const wasm = process.argv[2] || "build/v86.wasm";
const manifest = JSON.parse(fs.readFileSync("build/bench/manifest.json", "utf8"));
const boot = fs.readFileSync(manifest.boot);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// The loop starts at TOP, jumps to the IN at the last byte of its page; the
// next linear page (NEXT) is backed by the physical page ELSEWHERE, while
// the physical page after TOP's is filled with NOPs.
const TOP = 0x500F00, LAST = 0x500FFF, NEXT = 0x501000, ELSEWHERE = 0x700000;
const DATA = 0x600000, STACK = 0x610000, ITERATIONS = 20000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const top = [
    0x31, 0xC0,                                     // XOR EAX, EAX
    0x0F, 0xA2,                                     // CPUID
    0xBA, ...u32(0x80),                             // MOV EDX, 0x80
];
top.push(0xE9, ...u32(LAST - (TOP + top.length + 5))); // JMP last
const next = [0xFF, 0x0D, ...u32(DATA + 124)];      // DEC DWORD [DATA+124]
next.push(0x0F, 0x85, ...u32(TOP - (NEXT + next.length + 6)), 0xF4); // JNZ top; HLT

// the names of a few keys (tools/step_profile.mjs)
assert.equal(step_key_name(step_key({ opcode: 0xA2, map: 1 })), "prot32 x64page 0F A2");
assert.equal(step_key_name(step_key({ opcode: 0xA5, rep: true, mode: "long64", stepper: "x64page", retry: true })), "long64 x64page retry F3 A5");
assert.equal(step_key_name(step_key({ opcode: 0x18, map: 2, vex: true, vex_l: true, vex_pp: 1, mode: "long64" })), "long64 x64page VEX.256.66.0F38 18");
assert.equal(step_key_name(step_key({ opcode: 0xFF, reg: 2, mode: "real" })), "real x64page FF /2");

const vm = new V86({
    graphics_adapter: "bochs_vga", wasm_path: wasm, memory_size: 128 << 20,
    // (page functions are installed as they are compiled)
    ir_sync_publication: true,
    // (the page tier compiles a page after 2000 instructions)
    jit_switches: { x64_legacy_heat: 2000 },
    bios: { buffer: Uint8Array.from(boot).buffer }, disable_keyboard: true, disable_mouse: true,
    disable_speaker: true, net_device: { type: "none" }, autostart: false,
});
await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
const cpu = vm.v86.cpu, e = cpu.wm.exports;
vm.run();
const ready = performance.now() + 15000;
while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x500, true) !== 0xCAFE) {
    assert(performance.now() < ready, "benchmark BIOS did not start");
    await sleep(1);
}
await vm.stop();
assert.equal(get_jit_switches(e, cpu.wasm_memory).step_profile, 0, "the step profile is off by default");
set_jit_switches(e, cpu.wasm_memory, { step_profile: 1 }, "tier0_step_profile");

const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
cpu.mem8.fill(0x90, TOP & ~0xFFF, NEXT + 0x1000);
cpu.mem8.set(top, TOP);
cpu.mem8[LAST] = 0xEC;                              // IN AL, DX
cpu.mem8.set(next, ELSEWHERE);
view.setUint32(0x11000 + (NEXT >>> 12) * 4, ELSEWHERE | 3, true);

async function run() {
    cpu.mem8.fill(0, DATA, DATA + 128);
    view.setUint32(DATA + 124, ITERATIONS, true);
    cpu.reg32.fill(0);
    cpu.reg32[4] = STACK;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0; cpu.in_hlt[0] = 0;
    cpu.instruction_pointer[0] = TOP;
    e.update_state_flags();
    e.full_clear_tlb();
    vm.run();
    const end = performance.now() + 30000;
    while(!cpu.in_hlt[0]) {
        if(performance.now() > end) {
            await vm.stop();
            throw new Error(`timeout: eip ${(cpu.instruction_pointer[0] >>> 0).toString(16)} counter ${view.getUint32(DATA + 124, true)}`);
        }
        await sleep(0);
    }
    await vm.stop();
    assert.equal(view.getUint32(0x608, true), 0, "the guest took an exception");
    assert.equal(view.getUint32(DATA + 124, true), 0);
}
// (the first run compiles the pages)
await run();
e.x64_page_steps_reset();
e.step_profile_reset();
await run();

const raw_in = e.x64_page_steps(0xFFEC), raw_cpuid = e.x64_page_steps(0xA20F);
assert.equal(e.x64_page_steps(0x90EC), 0, "the IN's second byte was read from the wrong physical page");
assert(raw_in >= ITERATIONS * 0.9 && raw_cpuid >= ITERATIONS * 0.9, `the page tier stepped the IN ${raw_in} and CPUID ${raw_cpuid} times`);
const steps = step_profile(e);
const count = key => steps.find(r => r.key === key)?.count ?? 0;
assert.equal(count(step_key({ opcode: 0xEC })), raw_in, `IN: ${JSON.stringify(steps.slice(0, 4))}`);
assert.equal(count(step_key({ opcode: 0xA2, map: 1 })), raw_cpuid, `CPUID: ${JSON.stringify(steps.slice(0, 4))}`);
assert.equal(e.step_profile_get(step_key({ opcode: 0xA2, map: 1 })), raw_cpuid);
assert.deepEqual(steps.slice(0, 2).map(r => r.name).sort(), ["prot32 x64page 0F A2", "prot32 x64page EC"]);

set_jit_switches(e, cpu.wasm_memory, { step_profile: 0 }, "tier0_step_profile");
assert.equal(e.step_profile_snapshot(), 0, "the profile is dropped when the switch goes off");
await vm.destroy();
console.log(`PASS: the page tier stepped CPUID ${raw_cpuid} times and the IN at a page's last byte ${raw_in} times, ` +
    `the same in the two-byte histogram and under their StepKeys`);
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/ir/differential/verr_flags_baseline.mjs                                            0000644 0000000 0000000 00000004725 00000000000 020613  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Interpreter-only diagnostic contract for VERR/VERW: raw versus computed ZF.
import assert from "node:assert/strict";
import fs from "node:fs";
import {V86} from "../../../build/libv86.mjs";
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
for(const release of [false,true]){
    const vm=new V86({graphics_adapter: "bochs_vga", wasm_path:release?"build/v86-ir-test-release.wasm":"build/v86-ir-test.wasm",memory_size:32<<20,bios:{buffer:Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer},disable_keyboard:true,disable_mouse:true,disable_speaker:true,net_device:{type:"none"},autostart:false});
    try {
        await new Promise(r=>vm.add_listener("emulator-loaded",r));const cpu=vm.v86.cpu,e=cpu.wm.exports,mem=cpu.mem8,words=new Uint32Array(e.memory.buffer),v=new DataView(mem.buffer,mem.byteOffset),set32=(a,n)=>v.setUint32(a,n,true);
        vm.run();const deadline=performance.now()+10000;while(v.getUint16(0x500,true)!==0xCAFE){assert(performance.now()<deadline);await sleep(1);} await vm.stop();
        for(const modrm of [0xE0,0xE8]) for(const zero of [false,true]){
            cpu.segment_offsets.fill(0,0,6);cpu.segment_limits.fill(0xFFFFFFFF,0,6);cpu.segment_is_null.fill(0,0,6);cpu.sreg.set([16,8,16,16,16,16]);cpu.segment_access_bytes.set([0x93,0x9B,0x93,0x93,0x93,0x93]);cpu.is_32[0]=1;cpu.stack_size_32[0]=1;words[612>>2]=0;
            cpu.gdtr_offset[0]=0x5000;cpu.gdtr_size[0]=0x10FF;set32(0x5008,0xFFFF);set32(0x500C,0xCF9B00);set32(0x5010,0xFFFF);set32(0x5014,0xCF9300);
            cpu.idtr_offset[0]=0x2000;cpu.idtr_size[0]=0x7FF;set32(0x2000+14*8,8<<16|0x200);set32(0x2004+14*8,0x180000|0x8E00);
            set32(0x12000,0x13003);set32(0x13000+5*4,0x5003);set32(0x13000+6*4,0);e.full_clear_tlb();e.update_state_flags();
            cpu.instruction_pointer[0]=0x8000;cpu.reg32[0]=0x1000;cpu.reg32[3]=zero?-1:1;cpu.reg32[4]=0x90000;cpu.flags[0]=zero?2:0x42;cpu.flags_changed[0]=0;mem.set([0x43,0x0F,0x00,modrm],0x8000);
            e.ir_test_step();const computed=Number(!!(e.get_eflags()&64)),raw=Number(!!(cpu.flags[0]&64));e.ir_test_step();assert.equal(cpu.instruction_pointer[0],0x180200);assert.equal(cpu.cr[2],0x6000);
            const saved=Number(!!(v.getUint32(0x90000-4,true)&64));assert.equal(computed,+zero);assert.equal(raw,+!zero);assert.equal(saved,raw);
            console.log(`PASS (${release?"release":"debug"}): ${modrm===0xE0?"VERR":"VERW"} descriptor #PF ZF computed=${computed}, raw/saved=${saved}`);
        }
    } finally {await vm.destroy();}
}
                                           source/v64/tests/ir/performance/cpu_profile_report.mjs                                              0000644 0000000 0000000 00000004002 00000000000 020352  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // V8 sampling complements the emitted timers; idle is kept separate.
import fs from "node:fs";
import assert from "node:assert/strict";
const profile=JSON.parse(fs.readFileSync(process.argv[2],"utf8"));
const nodes=new Map(profile.nodes.map(n=>[n.id,n]));
const parents=new Map();
for(const n of profile.nodes) for(const child of n.children||[]) parents.set(child,n.id);
const own=new Map(),groups=new Map();let total=0;
for(let i=0;i<profile.samples.length;i++) {
 const id=profile.samples[i],ms=profile.timeDeltas[i]/1000;
 assert(Number.isFinite(ms)&&ms>=0);
 const stack=[];for(let at=id;at;at=parents.get(at)) stack.push(nodes.get(at).callFrame);
 const names=stack.map(f=>f.functionName).join(" ");
 const group=names.includes("(idle)")?"idle":
  /compile_lifted|compile_cpu|lower_draft|ir.*passes/.test(names)?"IR compiler":
  /jit_generate_module|jit_analyze_and_generate/.test(names)?"legacy compiler":
  stack.some(f=>f.url.startsWith("wasm:")&&!f.url.includes("v86.wasm"))?"generated code and called helpers":
  // The uninstrumented IR dispatch inlines jit_run_interpreted into main_loop.
  // Keep its generated interpreter frame and descendants in the same group.
  /jit_run_interpreted|gen.*interpreter.*run/.test(names)?"interpreter":
  /ir.*runtime.*schedule/.test(names)?"IR scheduler":
  /ir.*runtime.*cache/.test(names)?"IR admission and dispatch":
  /wasm/.test(stack[0].url)?"other core":
  names.includes("(garbage collector)")?"GC":"host and devices";
 groups.set(group,(groups.get(group)||0)+ms);
 const key=stack[0].functionName;own.set(key,(own.get(key)||0)+ms);total+=ms;
}
const rank=rows=>[...rows].map(([name,ms])=>({name,ms,pct:ms/total*100})).sort((a,b)=>b.ms-a.ms);
console.log(JSON.stringify({sampled_ms:total,groups:rank(groups),leaf_functions:rank(own).slice(0,30),
 caveat:"Sample intervals and stack-name grouping, including idle; not OS CPU accounting. Inlined code without a recognizable frame remains in other core. Profiling perturbs execution. Use profiling-off paired medians for acceptance."},null,2));
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/ir/performance/game_state.mjs                                                      0000644 0000000 0000000 00000036251 00000000000 016574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Headless game-state profiler: restores a saved state (made in the browser
// with the v86gl graphics proxy) and runs it, reporting guest MIPS and the
// frames the guest submits per second.
//
//   node tests/ir/performance/game_state.mjs --state kartrider.bin \
//       --hda windowsxp.img [--hdb game.img] [--wasm core.wasm] [--tier0 0|1]
//       (--tier0: ir_tier0, 32-bit code in the x64 page tier; 0, in the regions)
//       [--seconds 60] [--profile-from 30 --profile-out game.cpuprofile]
//       [--sync-publication 0|1]
//
// Windows 98 (docs/jit-unification-plan.md P0.15): the site's states have
// neither the 9p filesystem nor the v86gl device, --filesystem 0 --v86gl 0
// (or --win98, both). Without --state the machine cold-boots from hda
// (--memory MiB, default 256 as the site's Windows 98 games), and the summary
// gives `desktop_s`: when the first graphics mode of at least 640x480 is set,
// a display-mode milestone as xp_boot.mjs's (Windows 98 does not halt when
// idle, so idle time cannot tell the desktop). --modes samples the CPU
// mode at the end of every main-loop slice (about 1 ms, TIME_PER_FRAME),
// weighted by the wall time since the previous one (the time a halted guest
// waits counts as idle): real, vm86, prot16 and prot32 (".flat" with flat
// segments) by ring. --ledger adds the mode ledger (the JIT switch
// mode_ledger, docs/profiling.md): the retired instructions by mode and how
// they ran. JIT_SWITCHES applies (tests/lib/jit_switches.mjs); JIT_STATS=1
// prints the JIT statistics record at the end (tools/bench/jit_stats.mjs).
//
// Memory and VRAM sizes come from the state. Graphics: an infinitely fast
// null renderer (batches acknowledged; D9WG queries, readbacks and the
// heartbeat answered as the WebGPU host does), so only guest CPU work is
// measured. Audio: a speaker that consumes SB16 DMA at the sampling rate, so
// the guest's audio path runs as in the browser. Disk writes stay in RAM.
import fs from "node:fs";
import inspector from "node:inspector";
import { createRequire as create_require } from "node:module";
import { V86 } from "../../../build/libv86.mjs";
import { STATE_OFFSETS } from "../../../src/state_layout.js";
import { jit_stats_enabled, mode_ledger, print_jit_stats } from "../../../tools/bench/jit_stats.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";
const { createV86GLDevice: create_v86gl_device } = create_require(import.meta.url)("../../../src/browser/glbridge/v86gl_device.js");

const args = process.argv.slice(2);
const option = (name, fallback) => { const i = args.indexOf("--" + name); return i < 0 ? fallback : args[i + 1]; };
const state_path = option("state"), hda = option("hda"), hdb = option("hdb");
if(!hda) {
    console.error("usage: game_state.mjs [--state file.bin] --hda disk.img [--hdb disk.img] [--wasm core.wasm] [--tier0 0|1] [--seconds 60]" +
        " [--win98 | --filesystem 0|1 --v86gl 0|1] [--memory 256] [--modes] [--ledger]");
    process.exit(2);
}
const win98 = args.includes("--win98");
const with_filesystem = option("filesystem", win98 ? "0" : "1") === "1", with_v86gl = option("v86gl", win98 ? "0" : "1") === "1";
const sample_modes = args.includes("--modes"), with_ledger = args.includes("--ledger");
const seconds = Number(option("seconds", 60));
const profile_from = option("profile-from");
const profile_out = option("profile-out", "game.cpuprofile");

class SyncDisk {
    constructor(path) { this.fd = fs.openSync(path, "r"); this.byteLength = fs.fstatSync(this.fd).size; this.overlay = new Map(); }
    load() { this.onload && this.onload({}); }
    get(start, len, fn) {
        const out = new Uint8Array(len);
        fs.readSync(this.fd, out, 0, len, start);
        for(let sector = Math.floor(start / 512); sector * 512 < start + len; sector++) {
            const data = this.overlay.get(sector);
            if(!data) continue;
            const from = Math.max(start, sector * 512), to = Math.min(start + len, sector * 512 + 512);
            out.set(data.subarray(from - sector * 512, to - sector * 512), from - start);
        }
        fn(out);
    }
    get_and_cache(start, len, fn) { this.get(start, len, fn); }
    get_from_cache() { return undefined; }
    set(start, slice, fn) {
        for(let at = 0; at < slice.length;) {
            const offset = start + at, sector = Math.floor(offset / 512), within = offset - sector * 512;
            let data = this.overlay.get(sector);
            if(!data) { data = new Uint8Array(512); this.get(sector * 512, 512, b => data.set(b)); this.overlay.set(sector, data); }
            const n = Math.min(512 - within, slice.length - at);
            data.set(slice.subarray(at, at + n), within);
            at += n;
        }
        fn && fn();
    }
    get_buffer(fn) { fn(); }
    get_state() { return []; }
    set_state() {}
}

// The state's info block (an uncompressed v6 state): memory and VRAM sizes.
let raw = null, memory_size = Number(option("memory", 256)) << 20, vga_memory_size = 16 << 20;
if(state_path) {
    raw = fs.readFileSync(state_path);
    const header = new DataView(raw.buffer, raw.byteOffset, 16);
    if(header.getInt32(0, true) !== (0x86768676 | 0))
        throw new Error("expected an uncompressed v86 state (decompress .zst first)");
    const info = JSON.parse(raw.subarray(16, 16 + header.getUint32(12, true)).toString("utf8"));
    memory_size = info.state[0];
    // state[52]: ["graphics_adapter", version, name, VGA state], or before
    // display adapter plugins the Bochs VGA's own state
    const adapter_state = info.state[52];
    const vga_state = Array.isArray(adapter_state) && adapter_state[0] === "graphics_adapter" ? adapter_state[3] : adapter_state;
    vga_memory_size = Array.isArray(vga_state) ? vga_state[0] : 8 * 1024 * 1024;
}

// --- null renderer ---------------------------------------------------------
const RESPONSE_REGION = 16 * 1024 * 1024 - 4 * 1024 * 1024;
const HEARTBEAT = RESPONSE_REGION + 4 * 1024 * 1024 - 16;
const g = { batches: 0, bytes: 0, presents: 0, draws: 0 };
// Wall-clock intervals between presents (ms, rounded), in the second half.
const intervals = new Map();
let last_present = 0, measuring = false;
const queries = new Map();
let heartbeat = 0;
// The v86gl device with the null renderer on the other end of its channel
function null_renderer_device() {
    let to_device = null;
    const descriptor = create_v86gl_device({ remote: false,
        listen: handler => { to_device = handler; },
        post: message => {
            on_submit({ ...message, writeGuestMemory: (offset, bytes) =>
                to_device({ type: "write", generation: message.generation, offset, bytes }) });
            to_device({ type: "done", id: message.id });
        } });
    to_device({ type: "available", value: true });
    return descriptor;
}

function on_submit(event) {
    event.handled = true;
    const b = event.bytes;
    g.batches++; g.bytes += b.byteLength;
    const envelope = b.byteLength >= 8 ? b[0] | b[1] << 8 : 0;
    if(envelope !== 0xFFE0 && envelope !== 0xFFE1) return;
    const d = new DataView(b.buffer, b.byteOffset + 8, b.byteLength - 8);
    if(d.byteLength < 32 || d.getUint32(0, true) !== 0x47573944) return; // "D9WG"
    const end = 32 + d.getUint32(20, true);
    const write = (offset, bytes) => { try { event.writeGuestMemory(offset, bytes); } catch(e) {} };
    for(let at = 32; at + 16 <= end;) {
        const op = d.getUint16(at, true), size = d.getUint32(at + 4, true), p = at + 16;
        if(size < 16 || at + size > end) break;
        if(op === 4 || op === 0x226) {
            g.presents++;
            const now = performance.now();
            if(measuring && last_present) { const ms = Math.round(now - last_present); intervals.set(ms, (intervals.get(ms) || 0) + 1); }
            last_present = now;
        }
        if(op >= 0x300 && op <= 0x303) g.draws++;
        if(op === 0x123 && size >= 32) queries.set(d.getUint32(p + 4, true), { type: d.getUint32(p + 8, true), offset: d.getUint32(p + 12, true) });
        if(op === 0x401 && size >= 32) {
            const q = queries.get(d.getUint32(p + 4, true));
            if(q) {
                const out = new Uint8Array(16), v = new DataView(out.buffer);
                const value = q.type === 8 ? 1 : q.type === 9 ? 1000 : q.type === 12 ? 1e9 : q.type === 10 ? Math.floor(performance.now() * 1e6) : 0;
                v.setUint32(0, d.getUint32(p + 12, true), true);
                v.setUint32(4, value >>> 0, true);
                v.setUint32(8, Math.floor(value / 2 ** 32) >>> 0, true);
                v.setUint32(12, 1, true);
                write(RESPONSE_REGION + q.offset, out);
            }
        }
        if(op === 12 && size >= 16 + 48) {
            const bytes = d.getUint32(p + 36, true), offset = d.getUint32(p + 40, true);
            const out = new Uint8Array(16 + bytes), v = new DataView(out.buffer);
            v.setUint32(0, d.getUint32(p + 44, true), true);
            v.setUint32(4, bytes, true);
            v.setUint32(12, 1, true);
            write(RESPONSE_REGION + offset, out);
        }
        at += size;
    }
    heartbeat = heartbeat + 1 >>> 0;
    write(HEARTBEAT, new Uint8Array([heartbeat & 255, heartbeat >> 8 & 255, heartbeat >> 16 & 255, heartbeat >>> 24]));
}

const vm = new V86({
    graphics_adapter: "bochs_vga",
    wasm_path: option("wasm", "build/v86.wasm"),
    ir_tier0: option("tier0", "1") === "1",
    memory_size, vram_size: vga_memory_size,
    bios: { url: "bios/seabios.bin" }, vga_bios: { url: "bios/vgabios.bin" },
    hda: new SyncDisk(hda), ...(hdb ? { hdb: new SyncDisk(hdb) } : {}),
    x87_fast_math: true, x87_jit_cache: true,
    ir_sync_publication: option("sync-publication", "0") === "1",
    ...with_v86gl ? { virtio_devices: [null_renderer_device()] } : {},
    ...with_filesystem ? { filesystem: {} } : {},
    // (JIT_SWITCHES, and the mode ledger for --ledger)
    jit_switches: { ...jit_switches_from_env(), ...with_ledger ? { mode_ledger: 1 } : {} },
    disable_keyboard: true, disable_mouse: true, disable_speaker: true,
    net_device: { type: "ne2k" }, autostart: false,
});
await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
const cpu = vm.v86.cpu, e = cpu.wm.exports;
if(raw) await vm.restore_state(raw.buffer.slice(raw.byteOffset, raw.byteOffset + raw.byteLength));

// --- CPU mode at the end of each main-loop slice --------------------------------
const mode_ms = new Map(), mode_ms_late = new Map();
let mode_late = false, last_slice = 0;
function mode_now() {
    if(cpu.in_hlt[0]) return "idle";
    if(!cpu.protected_mode[0]) return "real";
    if(cpu.flags[0] & 1 << 17) return "vm86";
    const flat = new Uint8Array(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.state_flags, 1)[0] & 8;
    return (cpu.is_32[0] ? flat ? "prot32.flat" : "prot32" : "prot16") + ".r" + cpu.cpl[0];
}
if(sample_modes || !raw) {
    const run_cores = cpu.run_cores.bind(cpu);
    cpu.run_cores = () => {
        const delay = run_cores(), now = performance.now(), mode = mode_now();
        if(last_slice) {
            mode_ms.set(mode, (mode_ms.get(mode) || 0) + now - last_slice);
            if(mode_late) mode_ms_late.set(mode, (mode_ms_late.get(mode) || 0) + now - last_slice);
        }
        last_slice = now;
        return delay;
    };
}
const shares = map => {
    const total = [...map.values()].reduce((a, b) => a + b, 0);
    return Object.fromEntries([...map].sort((a, b) => b[1] - a[1]).map(([mode, ms]) => [mode, +(ms / total).toFixed(4)]));
};
// (cold boot) the desktop: the first graphics mode of at least 640x480
let desktop_s = null, boot_started = 0;
vm.add_listener("screen-set-size", size => {
    if(!raw && boot_started && desktop_s === null && size[0] >= 640 && size[1] >= 480 && size[2] >= 8) {
        desktop_s = +((performance.now() - boot_started) / 1000).toFixed(1);
        console.log(JSON.stringify({ event: "desktop", s: desktop_s, mode: size }));
    }
});

// --- speaker ------------------------------------------------------------------
let rate = 22050, queued = 0, last = performance.now();
vm.bus.register("dac-tell-sampling-rate", r => { rate = r; });
vm.bus.register("dac-send-data", data => { queued += data[0].length; });
const speaker = setInterval(() => {
    const now = performance.now();
    queued = Math.max(0, queued - rate * (now - last) / 1000);
    last = now;
    if(queued < rate * 0.2) vm.bus.send("dac-request-data");
}, 5);

const session = profile_from !== undefined ? new inspector.Session() : null;
const post = (method, params) => new Promise((resolve, reject) => session.post(method, params || {}, (err, r) => err ? reject(err) : resolve(r)));
if(session) { session.connect(); await post("Profiler.enable"); await post("Profiler.setSamplingInterval", { interval: 200 }); }
let profiling = false, instructions = 0, counter = vm.get_instruction_counter() >>> 0;
let prev = { instructions: 0, presents: 0, draws: 0, t: performance.now() };
const steady = [];
const started = boot_started = performance.now();
vm.run();
await new Promise(resolve => {
    const tick = setInterval(() => {
        const c = vm.get_instruction_counter() >>> 0;
        instructions += (c - counter) >>> 0; counter = c;
        const now = performance.now(), dt = (now - prev.t) / 1000, s = (now - started) / 1000;
        const line = {
            s: +s.toFixed(1),
            mips: +((instructions - prev.instructions) / dt / 1e6).toFixed(1),
            fps: +((g.presents - prev.presents) / dt).toFixed(1),
            draws: Math.round((g.draws - prev.draws) / dt),
            // (the x64 page tier's legacy- and compatibility-mode compiles)
            page_compiles: e.x64_page_stat(37) + e.x64_page_stat(36),
        };
        console.log(JSON.stringify(line));
        if(s >= seconds / 2) { steady.push(line); measuring = true; mode_late = true; }
        prev = { instructions, presents: g.presents, draws: g.draws, t: now };
        if(session && !profiling && s >= Number(profile_from)) { profiling = true; post("Profiler.start"); }
        if(s >= seconds) { clearInterval(tick); resolve(); }
    }, 1000);
});
await vm.stop();
clearInterval(speaker);
if(profiling) fs.writeFileSync(profile_out, JSON.stringify((await post("Profiler.stop")).profile));
const mean = key => steady.reduce((t, l) => t + l[key], 0) / Math.max(1, steady.length);
// (the x64 page tier, which compiles 32-bit protected-mode code since M8)
const page = { compiles: e.x64_page_stat(0), functions: e.x64_page_stat(12), native: e.x64_page_stat(1), steps: e.x64_page_stat(4),
    retries: e.x64_page_stat(2), pages: e.x64_page_stat(21), bytes: e.x64_page_stat(24) };
console.log(JSON.stringify({ event: "summary", seconds, second_half: { mips: +mean("mips").toFixed(1), fps: +mean("fps").toFixed(1), draws: Math.round(mean("draws")) },
    frame_ms: Object.fromEntries([...intervals].sort((a, b) => b[1] - a[1]).slice(0, 8)), page_tier: page,
    ...mode_ms.size ? { modes: shares(mode_ms), modes_second_half: shares(mode_ms_late) } : {},
    ...!raw ? { desktop_s } : {},
    ...with_ledger ? { ledger: mode_ledger(e) } : {} }));
// (tools/bench/jit_stats.mjs, docs/jit-unification-plan.md P0.7)
if(jit_stats_enabled()) print_jit_stats(vm, { script: "game_state", wasm: option("wasm", "build/v86.wasm"), state: state_path || null, seconds });
await vm.destroy();
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/ir/performance/xp_boot.mjs                                                         0000644 0000000 0000000 00000014471 00000000000 016135  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import fs from "node:fs";
import assert from "node:assert/strict";
import { createRequire as create_require } from "node:module";
import { V86 } from "../../../build/libv86.mjs";
import { jit_switches_from_env } from "../../lib/jit_switches.mjs";
import { jit_stats_enabled, print_jit_stats } from "../../../tools/bench/jit_stats.mjs";
// The guest's v86gl driver finds its device; no renderer answers
const { createV86GLDevice: create_v86gl_device } = create_require(import.meta.url)("../../../src/browser/glbridge/v86gl_device.js");

// Headless CPU/disk diagnostic. Disk writes stay in AsyncXHRBuffer's RAM overlay.
// Run one process per core so 2 GiB guest memories do not overlap.
// node tests/ir/performance/xp_boot.mjs disk.img [core.wasm]
// XP_CPU_TYPE=x86_64: a CPU with NX, for which XP boots its PAE kernel (the
// result's cr4 shows PAE, bit 5).
const [disk, wasm = "build/v86.wasm", ...extra] = process.argv.slice(2);
assert(disk && !extra.length, "usage: xp_boot.mjs disk.img [core.wasm]");
const duration = Number(process.env.IR_BOOT_MS || 30000);
assert(Number.isFinite(duration) && duration >= 1000);
const target = process.env.IR_BOOT_TARGET || "time";
assert(["time", "desktop"].includes(target));
// IR_SYNC_DISK=1: reads complete synchronously from the image and writes stay
// in a RAM sector overlay. This removes host I/O latency from the boot, so the
// milestone time measures emulated CPU work (a benchmarking aid, not the
// default acceptance configuration).
class SyncDisk {
    constructor(path) {
        this.fd = fs.openSync(path, "r");
        this.byteLength = fs.fstatSync(this.fd).size;
        this.overlay = new Map();
    }
    load() { this.onload && this.onload({}); }
    get(start, len, fn) {
        const out = new Uint8Array(len);
        fs.readSync(this.fd, out, 0, len, start);
        for(let sector = Math.floor(start / 512); sector * 512 < start + len; sector++) {
            const data = this.overlay.get(sector);
            if(!data) continue;
            const from = Math.max(start, sector * 512), to = Math.min(start + len, sector * 512 + 512);
            out.set(data.subarray(from - sector * 512, to - sector * 512), from - start);
        }
        fn(out);
    }
    get_and_cache(start, len, fn) { this.get(start, len, fn); }
    get_from_cache() { return undefined; }
    set(start, slice, fn) {
        for(let at = 0; at < slice.length;) {
            const offset = start + at, sector = Math.floor(offset / 512), within = offset - sector * 512;
            let data = this.overlay.get(sector);
            if(!data) { data = new Uint8Array(512); this.get(sector * 512, 512, b => data.set(b)); this.overlay.set(sector, data); }
            const n = Math.min(512 - within, slice.length - at);
            data.set(slice.subarray(at, at + n), within);
            at += n;
        }
        fn && fn();
    }
    get_buffer(fn) { fn(); }
    get_state() { return []; }
    set_state() {}
}
let milestone = null;
let phase = "bios";
const vm = new V86({
    graphics_adapter: "bochs_vga",
    wasm_path: wasm,
    ...(process.env.IR_SYNC_PUB !== undefined ? {ir_sync_publication: process.env.IR_SYNC_PUB === "1"} : {}),
    memory_size: 2048 * 1024 * 1024, vram_size: 16 * 1024 * 1024,
    ...(process.env.XP_CPU_TYPE ? { cpu_type: process.env.XP_CPU_TYPE } : {}),
    bios: { url: "bios/seabios.bin" }, vga_bios: { url: "bios/vgabios.bin" },
    hda: process.env.IR_SYNC_DISK === "1" ? new SyncDisk(disk) : { url: disk, size: fs.statSync(disk).size, async: true },
    x87_fast_math: true, x87_jit_cache: true,
    virtio_devices: [create_v86gl_device({ remote: false, post() {}, listen() {} })],
    disable_keyboard: true, disable_mouse: true, disable_speaker: true,
    net_device: { type: "ne2k" }, autostart: false,
    // (JIT_SWITCHES, tests/lib/jit_switches.mjs)
    ...Object.keys(jit_switches_from_env()).length ? { jit_switches: jit_switches_from_env() } : {},
});
let started, previous, count, total = 0;
vm.add_listener("screen-set-size", size => {
    const ms = started ? performance.now() - started : 0;
    phase = size.join("x");
    console.log(JSON.stringify({ event: "screen", ms, size }));
    // This is a reproducible display-mode milestone, not proof of desktop idle.
    if(started && !milestone && size[0] === 800 && size[1] === 600 && size[2] === 32) {
        milestone = {ms, instructions: total + (((vm.get_instruction_counter() >>> 0) - count) >>> 0)};
        console.log(JSON.stringify({event:"milestone", name:"800x600x32", ...milestone}));
    }
});
try {
    await new Promise((resolve, reject) => {
        vm.add_listener("emulator-loaded", resolve);
        vm.add_listener("emulator-error", reject);
    });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    started = previous = performance.now();
    count = vm.get_instruction_counter() >>> 0;
    vm.run();
    while(performance.now() - started < duration && !(target === "desktop" && milestone)) {
        await new Promise(resolve => setTimeout(resolve, target === "desktop" ? 250 : 5000));
        const now = performance.now(), next = vm.get_instruction_counter() >>> 0;
        const steps = (next - count) >>> 0;
        total += steps;
        console.log(JSON.stringify({ wasm, ms: now - started,
            phase, instructions: total,
            requested_ms: duration, overrun_ms: Math.max(0, now - started - duration),
            mips: steps / (now - previous) / 1000, avg_mips: total / (now - started) / 1000,
            jit: vm.get_jit_info(),
        }));
        previous = now; count = next;
    }
    await vm.stop();
    total+=((vm.get_instruction_counter()>>>0)-count)>>>0;
    console.log(JSON.stringify({event:"page_tier", compiles:e.x64_page_stat(0), legacy_compiles:e.x64_page_stat(37), native:e.x64_page_stat(1),
        steps:e.x64_page_stat(4), retries:e.x64_page_stat(2), activations:e.x64_page_stat(13), pages:e.x64_page_stat(21), bytes:e.x64_page_stat(24),
        memory:e.memory.buffer.byteLength}));
    // (tools/bench/jit_stats.mjs, docs/jit-unification-plan.md P0.7)
    if(jit_stats_enabled()) print_jit_stats(vm, { script: "xp_boot", wasm, target, milestone, ms: performance.now() - started });
    console.log(JSON.stringify({event:"result", target, completed:target === "time" || !!milestone,
        ms:performance.now()-started, instructions:total, milestone, jit:vm.get_jit_info(), cr4:cpu.cr[4]>>>0}));
} finally {
    await vm.destroy();
}
                                                                                                                                                                                                       source/v64/tests/jit-paging/Makefile                                                                0000644 0000000 0000000 00000002463 00000000000 014524  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       CC=gcc
CC_I386=$(CC) -m32
CFLAGS=-Wall -g -fno-strict-aliasing -fPIC -static
LDFLAGS=

ifeq ($(shell uname -s),Darwin)
# macOS has no Linux i386 toolchain: build freestanding static ELF binaries
# with clang against the minimal libc in freestanding/, linked by rust-lld.
RUST_LLD=$(shell rustc --print sysroot)/lib/rustlib/$(shell rustc -vV | sed -n 's/^host: //p')/bin/rust-lld
FREESTANDING_CFLAGS=-target i386-unknown-linux-gnu -ffreestanding -nostdlibinc -I$(CURDIR)/freestanding \
	-fno-pic -fno-stack-protector -Wall -g -fno-strict-aliasing
FREESTANDING_LIBC=freestanding/libc.c $(wildcard freestanding/*.h freestanding/sys/*.h)
define build_i386
	clang $(FREESTANDING_CFLAGS) -c $(1) -o $(2).o
	clang $(FREESTANDING_CFLAGS) -c freestanding/libc.c -o $(2).libc.o
	$(RUST_LLD) -flavor gnu -m elf_i386 -static -e _start -o $(2) $(2).o $(2).libc.o
	rm -f $(2).o $(2).libc.o
endef
else
FREESTANDING_LIBC=
define build_i386
	$(CC_I386) $(CFLAGS) $(LDFLAGS) -o $(2) $(1)
endef
endif

test-jit: test-jit.c $(FREESTANDING_LIBC)
	$(call build_i386,$(<D)/test-jit.c,$@)
test-jit-smc: test-jit-smc.c $(FREESTANDING_LIBC)
	$(call build_i386,$(<D)/test-jit-smc.c,$@)
test-jit-smc-fstenv: test-jit-smc-fstenv.c $(FREESTANDING_LIBC)
	$(call build_i386,$(<D)/test-jit-smc-fstenv.c,$@)

clean:
	rm -f test-jit test-jit-smc test-jit-smc-fstenv
                                                                                                                                                                                                             source/v64/tests/jit-paging/README.md                                                               0000644 0000000 0000000 00000001311 00000000000 014332  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # About

These tests map 2 adjacent pages to the exact same physical frame. Code is
written to one page and executed from the other, then overwritten and executed
again, in order to trigger cache activity. Unlike `/tests/jit/`, this folder is
meant to test the JIT in protected mode with paging setup, not in real-mode.

# Run

- Obtain the `linux4.iso` image (see [Readme.md](../../Readme.md))
- Run `make jitpagingtests` in the root of the project

The test programs are static Linux i386 binaries. On Linux they are built with
`gcc -m32`; on macOS, which has no such toolchain, they are built freestanding
with clang against the minimal libc in `freestanding/` and linked with the Rust
toolchain's `rust-lld`.
                                                                                                                                                                                                                                                                                                                       source/v64/tests/jit-paging/freestanding/libc.c                                                     0000644 0000000 0000000 00000010665 00000000000 016615  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Just enough of a Linux i386 libc for test-jit*.c, for hosts without a
// Linux toolchain (macOS): system calls through int 0x80, no dynamic state.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

enum { SYS_exit_group = 252, SYS_write = 4, SYS_open = 5, SYS_getpid = 20, SYS_kill = 37,
    SYS_old_mmap = 90, SYS_munmap = 91, SYS_ftruncate = 93 };

static long syscall3(long n, long a, long b, long c)
{
    long result;
    __asm__ volatile("int $0x80" : "=a"(result) : "a"(n), "b"(a), "c"(b), "d"(c) : "memory");
    return result;
}

static long check(long result)
{
    // Kernel errors are -4095..-1; there is no errno.
    return (unsigned long)result > -4096UL ? -1 : result;
}

void exit(int status)
{
    for(;;) syscall3(SYS_exit_group, status, 0, 0);
}

void abort(void)
{
    syscall3(SYS_kill, syscall3(SYS_getpid, 0, 0, 0), 6 /* SIGABRT */, 0);
    exit(127);
}

void *memcpy(void *dest, const void *src, size_t n)
{
    unsigned char *d = dest;
    const unsigned char *s = src;
    while(n--) *d++ = *s++;
    return dest;
}

void *memset(void *dest, int c, size_t n)
{
    unsigned char *d = dest;
    while(n--) *d++ = (unsigned char)c;
    return dest;
}

void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
    // old_mmap takes its six arguments in memory (no EBP juggling).
    unsigned long args[6] = { (unsigned long)addr, length, prot, flags, fd, offset };
    long result = syscall3(SYS_old_mmap, (long)args, 0, 0);
    return check(result) == -1 ? MAP_FAILED : (void *)result;
}

int munmap(void *addr, size_t length)
{
    return check(syscall3(SYS_munmap, (long)addr, length, 0));
}

int ftruncate(int fd, off_t length)
{
    return check(syscall3(SYS_ftruncate, fd, length, 0));
}

int mkstemp(char *template)
{
    size_t length = 0;
    while(template[length]) length++;
    if(length < 6) return -1;
    unsigned value = syscall3(SYS_getpid, 0, 0, 0);
    for(int attempt = 0; attempt < 100; attempt++, value = value * 1103515245 + 12345)
    {
        unsigned v = value;
        for(size_t i = length - 6; i < length; i++, v /= 36) template[i] = "0123456789abcdefghijklmnopqrstuvwxyz"[v % 36];
        long fd = check(syscall3(SYS_open, (long)template, 02 | 0100 | 0200 /* O_RDWR|O_CREAT|O_EXCL */, 0600));
        if(fd != -1) return fd;
    }
    return -1;
}

static FILE files[] = { { 1 }, { 2 } };
FILE *stdout = &files[0], *stderr = &files[1];

int fflush(FILE *stream)
{
    (void)stream;
    return 0;
}

// Unbuffered; supports %d, %u, %x, %s and %%.
int vfprintf(FILE *stream, const char *format, va_list args)
{
    char buffer[512];
    size_t n = 0;
    for(const char *p = format; *p && n < sizeof buffer - 16; p++)
    {
        if(*p != '%')
        {
            buffer[n++] = *p;
            continue;
        }
        char conversion = *++p;
        if(conversion == 's')
        {
            for(const char *s = va_arg(args, const char *); *s && n < sizeof buffer - 16; s++) buffer[n++] = *s;
        }
        else if(conversion == 'd' || conversion == 'u' || conversion == 'x')
        {
            unsigned base = conversion == 'x' ? 16 : 10;
            unsigned value = va_arg(args, unsigned);
            if(conversion == 'd' && (int)value < 0)
            {
                buffer[n++] = '-';
                value = -value;
            }
            char digits[12];
            int count = 0;
            do digits[count++] = "0123456789abcdef"[value % base]; while(value /= base);
            while(count) buffer[n++] = digits[--count];
        }
        else if(conversion)
        {
            buffer[n++] = conversion;
        }
        else
        {
            break;
        }
    }
    syscall3(SYS_write, stream->fd, (long)buffer, n);
    return n;
}

int fprintf(FILE *stream, const char *format, ...)
{
    va_list args;
    va_start(args, format);
    int n = vfprintf(stream, format, args);
    va_end(args);
    return n;
}

int printf(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    int n = vfprintf(stdout, format, args);
    va_end(args);
    return n;
}

int main();
void __libc_start(void) { exit(main()); }
__asm__(".text\n.globl _start\n_start:\n xorl %ebp, %ebp\n andl $-16, %esp\n call __libc_start\n hlt\n");

// test-jit.c copies a whole page starting at one of its functions: keep that
// page inside the text segment, as it is in a (large) libc-linked binary.
__asm__(".text\n.fill 8192, 1, 0xCC\n");
                                                                           source/v64/tests/jit-paging/freestanding/stdio.h                                                    0000644 0000000 0000000 00000000554 00000000000 017027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Minimal Linux i386 libc for test-jit*.c on hosts without a Linux toolchain; see libc.c.
#pragma once
#include <stdarg.h>
typedef struct { int fd; } FILE;
extern FILE *stdout, *stderr;
int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int vfprintf(FILE *stream, const char *format, va_list args);
int fflush(FILE *stream);
                                                                                                                                                    source/v64/tests/jit-paging/freestanding/stdlib.h                                                   0000644 0000000 0000000 00000000147 00000000000 017164  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
_Noreturn void abort(void);
_Noreturn void exit(int status);
int mkstemp(char *template);
                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/jit-paging/freestanding/string.h                                                   0000644 0000000 0000000 00000000201 00000000000 017200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
#include <stddef.h>
void *memcpy(void *dest, const void *src, size_t n);
void *memset(void *dest, int c, size_t n);
                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/jit-paging/freestanding/sys/mman.h                                                 0000644 0000000 0000000 00000000527 00000000000 017453  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
#include <sys/types.h>
#define PROT_READ 1
#define PROT_WRITE 2
#define PROT_EXEC 4
#define MAP_SHARED 1
#define MAP_PRIVATE 2
#define MAP_FIXED 0x10
#define MAP_ANONYMOUS 0x20
#define MAP_FAILED ((void *)-1)
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
int munmap(void *addr, size_t length);
                                                                                                                                                                         source/v64/tests/jit-paging/freestanding/sys/types.h                                                0000644 0000000 0000000 00000000065 00000000000 017664  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
#include <stddef.h>
typedef long off_t;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/jit-paging/freestanding/sys/user.h                                                 0000644 0000000 0000000 00000000044 00000000000 017473  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
#define PAGE_SIZE 4096
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/jit-paging/freestanding/unistd.h                                                   0000644 0000000 0000000 00000000111 00000000000 017200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #pragma once
#include <sys/types.h>
int ftruncate(int fd, off_t length);
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/jit-paging/run-smc.js                                                              0000755 0000000 0000000 00000004222 00000000000 015004  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import url from "node:url";
process.on("unhandledRejection", exn => { throw exn; });

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

var test_executable = new Uint8Array(fs.readFileSync(__dirname + "/test-jit-smc"));

var emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
});

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
    emulator.create_file("test-jit-smc", test_executable);
});

var ran_command = false;
var line = "";

emulator.add_listener("serial0-output-byte", async function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        var new_line = line;
        console.error("Serial: %s", line);
        line = "";
    }
    else
    {
        line += chr;
    }

    if(!ran_command && line.endsWith("~% "))
    {
        ran_command = true;
        emulator.serial0_send("chmod +x /mnt/test-jit-smc\n");
        emulator.serial0_send("/mnt/test-jit-smc 2>&1 | tee /mnt/result\n");
        emulator.serial0_send("echo test fini''shed\n");
    }

    if(new_line && new_line.includes("test finished"))
    {
        console.error("Done. Reading result ...");

        const data = await emulator.read_file("/result");

        emulator.destroy();

        let result = Buffer.from(data).toString();
        if(result !== "test_smc_multipage passed\n")
        {
            console.error("[!] Error. Result was:\n" + result);
            process.exit(1);
        }
        else
        {
            console.log("[+] Test passed");
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/jit-paging/run.js                                                                  0000755 0000000 0000000 00000004234 00000000000 014227  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import url from "node:url";
process.on("unhandledRejection", exn => { throw exn; });

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

var test_executable = new Uint8Array(fs.readFileSync(__dirname + "/test-jit"));

var emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
});

emulator.bus.register("emulator-started", function()
{
    console.log("Booting now, please stand by");
    emulator.create_file("test-jit", test_executable);
});

var ran_command = false;
var line = "";

emulator.add_listener("serial0-output-byte", async function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        var new_line = line;
        console.error("Serial: %s", line);
        line = "";
    }
    else
    {
        line += chr;
    }

    if(!ran_command && line.endsWith("~% "))
    {
        ran_command = true;
        emulator.serial0_send("chmod +x /mnt/test-jit\n");
        emulator.serial0_send("/mnt/test-jit 2>&1 | tee /mnt/result\n");
        emulator.serial0_send("echo test fini''shed\n");
    }

    if(new_line && new_line.includes("test finished"))
    {
        console.error("Done. Reading result ...");

        const data = await emulator.read_file("/result");

        emulator.destroy();

        let result = Buffer.from(data).toString();
        if(result !== "test_shared passed\ntest_consecutive_written passed\n")
        {
            console.error("[!] Error. Result was:\n" + result);
            process.exit(1);
        }
        else
        {
            console.log("[+] Test passed");
        }
    }
});
                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/jit-paging/test-jit-smc.c                                                          0000644 0000000 0000000 00000005362 00000000000 015554  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/user.h>
#include <unistd.h>

static volatile uint32_t counter = 0;
static volatile uint32_t do_write = 0;

int main(void)
{
    uint8_t *const base = mmap(NULL, 2 * PAGE_SIZE,
            PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    if(base == MAP_FAILED)
    {
        printf("*** FATAL ERROR: mmap\n");
        return 1;
    }

    memset(base, 0x90, 2 * PAGE_SIZE);

    const uint32_t entry_off = 0xFC0; // entry near (but not at) the end of page0
    const uint32_t target_off = 0x1010; // 0x10 bytes into page1
    uint8_t *const entry = base + entry_off;
    uint8_t *const target = base + target_off;
    uint8_t *const patch_imm = target + 1; // the imm8 of "mov al, imm8"

    // --- page0 ---
    uint8_t *p = entry;
    // cmp dword [do_write], 0
    *p++ = 0x83; *p++ = 0x3D; *(uint32_t *)p = (uint32_t)(uintptr_t)&do_write; p += 4; *p++ = 0x00;
    // je skip_store (over the three store instructions: 6 + 5 + 5 = 16 bytes)
    *p++ = 0x74; *p++ = 0x10;
    // inc dword [counter]
    *p++ = 0xFF; *p++ = 0x05; *(uint32_t *)p = (uint32_t)(uintptr_t)&counter; p += 4;
    // mov eax, [counter]
    *p++ = 0xA1; *(uint32_t *)p = (uint32_t)(uintptr_t)&counter; p += 4;
    // mov [patch_imm], al
    *p++ = 0xA2; *(uint32_t *)p = (uint32_t)(uintptr_t)patch_imm; p += 4;
    // skip_store: jmp target
    *p++ = 0xE9;
    int32_t rel = (int32_t)((intptr_t)target - (intptr_t)(p + 4));
    *(int32_t *)p = rel; p += 4;

    // --- page1 ---
    uint8_t *q = target;
    // mov al, imm8 (imm8 patched by page0)
    *q++ = 0xB0; *q++ = 0x00;
    // movzx eax, al
    *q++ = 0x0F; *q++ = 0xB6; *q++ = 0xC0;
    // ret
    *q++ = 0xC3;

    int (*f)(void) = (int (*)(void))entry;

    const int rounds = 40;
    const int warmup = 300000;
    int failures = 0;
    for(int round = 0; round < rounds; round++)
    {
        do_write = 0;
        *patch_imm = 0;
        for(int i = 0; i < warmup; i++)
        {
            int got = f();
            if(got != 0)
            {
                printf("*** FATAL ERROR: warmup got %d, expected 0\n", got);
                return 1;
            }
        }

        do_write = 1;
        uint32_t expected = (counter + 1) & 0xFF;
        int got = f();
        do_write = 0;
        if((uint32_t)got != expected)
        {
            failures++;
            if(failures <= 5)
            {
                printf("stale result in round %d: got=%d expected=%u\n", round, got, expected);
            }
        }
    }

    if(failures == 0)
    {
        printf("test_smc_multipage passed\n");
    }
    else
    {
        printf("test_smc_multipage FAILED: %d/%d stale results\n", failures, rounds);
    }

    return 0;
}
                                                                                                                                                                                                                                                                              source/v64/tests/jit-paging/test-jit.c                                                              0000644 0000000 0000000 00000011214 00000000000 014765  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>
#include <sys/user.h>
#include <unistd.h>


int fib(int n)
{
    int first = 0, second = 1, next = 0, i = 0;
    while(i <= n)
    {
        if(i < 2)
        {
            next = i;
        }
        else
        {
            next = first + second;
            first = second;
            second = next;
        }
        i++;
    }
    return next;
}

int pass_test()
{
    return 0x42;
}

void fatal(char *msg)
{
    fprintf(stderr, "*** FATAL ERROR: %s\n", (msg ? msg : "no message"));
    fflush(stderr);
    abort();
}

void test_shared()
{
    static char filename[] = "/tmp/DoubleMapXXXXXX";
    int fd = mkstemp(filename);
    if(fd == -1)
    {
        fatal("mkstemp");
    }
    if(ftruncate(fd, PAGE_SIZE) == -1)
    {
        fatal("ftruncate");
    }

    uint8_t *const write_addr = mmap(0, 2 * PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    uint8_t *const exec_addr = mmap(write_addr+PAGE_SIZE, PAGE_SIZE,
            PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED | MAP_FIXED, fd, 0);

    if(write_addr == MAP_FAILED || exec_addr == MAP_FAILED)
    {
        fatal("mmap");
    }

    size_t size = PAGE_SIZE;
    memcpy(write_addr, fib, size);

    int (*fun_pointer)(int) = (void*)exec_addr;

    // Give the JIT something to potentially cache
    for(int i = 0; i < 15000; i++)
    {
        if(fun_pointer(20) != 6765)
        {
            fatal("fibonacci");
        }
    }

    memcpy(write_addr, pass_test, size);
    if(fun_pointer(0) == 0x42)
    {
        printf("test_shared passed\n");
    }

    munmap(write_addr, 2 * size);
    munmap(exec_addr, size);
}


void test_consecutive()
{
    uint8_t *const page0 = mmap(NULL,
            2 * PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    // throwaway mmap to reduce likelhood of page0 and page1 mapping to consecutive physical frames
    uint8_t *const throwaway = mmap(NULL,
            PAGE_SIZE, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    uint8_t *const page1 = mmap(page0 + PAGE_SIZE, PAGE_SIZE,
            PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);

    if(page0 == MAP_FAILED || throwaway == MAP_FAILED || page1 == MAP_FAILED)
    {
        fatal("mmap");
    }

    // Attempt to influence virtual to physical mapping - we want page0->page1 to not be contiguous
    // physically
    page0[0] = 0;
    throwaway[0] = 0;
    page1[0] = 0;

    for(int32_t i = 0; i < 100; i++)
    {
        uint8_t* start = (uint8_t*)(page1 - i - 1);
        memcpy(start, fib, PAGE_SIZE);
        int (*fun_pointer)(int) = (void*)start;

        for(int j = 0; j < 15000; j++)
        {
            if(fun_pointer(20) != 6765)
            {
                fatal("fibonacci");
            }
        }
    }

    printf("test_consecutive passed\n");
}

void test_consecutive_written()
{
    uint8_t *const page0 = mmap(NULL,
            2 * PAGE_SIZE, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    // throwaway mmap to reduce likelhood of page0 and page1 mapping to consecutive physical frames
    uint8_t *const throwaway = mmap(NULL,
            PAGE_SIZE, PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    uint8_t *const page1 = mmap(page0 + PAGE_SIZE, PAGE_SIZE,
            PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);

    if(page0 == MAP_FAILED || throwaway == MAP_FAILED || page1 == MAP_FAILED)
    {
        fatal("mmap");
    }

    // Attempt to influence virtual to physical mapping - we want page0->page1 to not be contiguous
    // physically
    page0[0] = 0;
    throwaway[0] = 0;
    page1[0] = 0;

    uint8_t* start = page1 - 8;
    uint8_t* ptr = start;
    const int32_t INC_COUNT = 16;

    // xor eax, eax
    *ptr++ = 0x31;
    *ptr++ = 0xc0;

    for(int i = 0; i < INC_COUNT; i++)
    {
        // inc eax
        *ptr++ = 0x40;
    }

    // ret
    *ptr++ = 0xC3;

    int (*fun_pointer)() = (void*)start;

    for(int i = 0; i < 15000; i++)
    {
        int32_t result = fun_pointer();

        if(result != INC_COUNT)
        {
            fatal("test_consecutive_written");
        }
    }

    // overwrite one INC at the start of the second page with a NOP
    *page1 = 0x90;

    int32_t result = fun_pointer();

    if(result != INC_COUNT - 1)
    {
        fatal("test_consecutive_written after overwrite");
    }

    printf("test_consecutive_written passed\n");
}

int main()
{
    test_shared();

    // disabled for now, takes long and not sure if it actually catches bugs
    //test_consecutive();

    test_consecutive_written();

    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/.gitignore                                                          0000644 0000000 0000000 00000000303 00000000000 015724  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       .gdbinit
*.a
*.d
*.o
*.flat
*.elf
.pc
patches
.stgit-*
cscope.*
*.swp
/lib/asm
/config.mak
/*-run
/msr.out
/tests
/build-head
/logs/
/logs.old/
/api/api-sample
/api/dirty-log
/api/dirty-log-perf
                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/COPYRIGHT                                                           0000644 0000000 0000000 00000000757 00000000000 015244  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       Copyright (C) 2006 Qumranet.
Copyright (C) 2007-2017 by various contributors (see source files for details)

The kvm-unit-tests are free software; the whole package can be redistributed
and/or modified under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

Many files in this directory and its subdirectories are also licensed under
the less restrictive GNU LGPL, version 2, or other compatible licenses. See
the individual files for details.
                 source/v64/tests/kvm-unit-tests/MAINTAINERS                                                         0000644 0000000 0000000 00000006071 00000000000 015441  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       KVM Unit Tests Maintainers
==========================

The intention of this file is not to establish who owns what portions of the
code base, but to provide a set of names that developers can consult when they
have a question about a particular subset and also to provide a set of names
to be CC'd when submitting a patch to obtain appropriate review.

In general, if you have a question about inclusion of a patch, you
should consult the KVM mailing list <kvm@vger.kernel.org> and not any
specific individual privately.

Descriptions of section entries:

	M: Mail patches to: FullName <address@domain>
	L: Mailing list that is relevant to this area
	W: Web-page with status/info
	Q: Patchwork web based patch tracking system site
	T: SCM tree type and location.  Type is one of: git, hg, quilt, stgit.
	S: Status, one of the following:
	   Supported:	Someone is actually paid to look after this.
	   Maintained:	Someone actually looks after it.
	   Odd Fixes:	It has a maintainer but they don't have time to do
			much other than throw the odd patch in. See below.
	   Orphan:	No current maintainer [but maybe you could take the
			role as you write your new code].
	   Obsolete:	Old code. Something tagged obsolete generally means
			it has been replaced by a better system and you
			should be using that.
	F: Files and directories with wildcard patterns.
	   A trailing slash includes all files and subdirectory files.
	   F:	drivers/net/	all files in and below drivers/net
	   F:	drivers/net/*	all files in drivers/net, but not below
	   F:	*/net/*		all files in "any top level directory"/net
	   One pattern per line.  Multiple F: lines acceptable.
	X: Files and directories that are NOT maintained, same rules as F:
	   Files exclusions are tested before file matches.
	   Can be useful for excluding a specific subdirectory, for instance:
	   F:	net/
	   X:	net/ipv6/
	   matches all files in and below net excluding net/ipv6/
	K: Keyword perl extended regex pattern to match content in a
	   patch or file.  For instance:
	   K: of_get_profile
	      matches patches or files that contain "of_get_profile"
	   K: \b(printk|pr_(info|err))\b
	      matches patches or files that contain one or more of the words
	      printk, pr_info or pr_err
	   One regex pattern per line.  Multiple K: lines acceptable.


Maintainers
-----------
M: Paolo Bonzini <pbonzini@redhat.com>
M: Radim Krčmář <rkrcmar@redhat.com>
L: kvm@vger.kernel.org
T: git://git.kernel.org/pub/scm/virt/kvm/kvm-unit-tests.git

Architecture Specific Code:
---------------------------

ARM
M: Drew Jones <drjones@redhat.com>
L: kvm@vger.kernel.org
L: kvmarm@lists.cs.columbia.edu
F: arm/*
F: lib/arm/*
F: lib/arm64/*

POWERPC
M: Laurent Vivier <lvivier@redhat.com>
M: Thomas Huth <thuth@redhat.com>
L: kvm@vger.kernel.org
L: kvm-ppc@vger.kernel.org
F: powerpc/*
F: lib/powerpc/*
F: lib/ppc64/*

S390X
M: Thomas Huth <thuth@redhat.com>
M: David Hildenbrand <david@redhat.com>
L: kvm@vger.kernel.org
F: s390x/*
F: lib/s390x/*

X86
M: Paolo Bonzini <pbonzini@redhat.com>
M: Radim Krčmář <rkrcmar@redhat.com>
L: kvm@vger.kernel.org
F: x86/*
F: lib/x86/*
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/Makefile                                                            0000644 0000000 0000000 00000007012 00000000000 015400  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
SHELL := /usr/bin/env bash

ifeq ($(wildcard config.mak),)
$(error run ./configure first. See ./configure -h)
endif

include config.mak

# Set search path for all sources
VPATH = $(SRCDIR)

libdirs-get = $(shell [ -d "lib/$(1)" ] && echo "lib/$(1) lib/$(1)/asm")
ARCH_LIBDIRS := $(call libdirs-get,$(ARCH)) $(call libdirs-get,$(TEST_DIR))
OBJDIRS := $(ARCH_LIBDIRS)

DESTDIR := $(PREFIX)/share/kvm-unit-tests/

.PHONY: arch_clean clean distclean cscope

#make sure env CFLAGS variable is not used
CFLAGS =

libgcc := $(shell $(CC) --print-libgcc-file-name)

libcflat := lib/libcflat.a
cflatobjs := \
	lib/argv.o \
	lib/printf.o \
	lib/string.o \
	lib/abort.o \
	lib/report.o \
	lib/stack.o

# libfdt paths
LIBFDT_objdir = lib/libfdt
LIBFDT_srcdir = $(SRCDIR)/lib/libfdt
LIBFDT_archive = $(LIBFDT_objdir)/libfdt.a
LIBFDT_include = $(addprefix $(LIBFDT_srcdir)/,$(LIBFDT_INCLUDES))
LIBFDT_version = $(addprefix $(LIBFDT_srcdir)/,$(LIBFDT_VERSION))

OBJDIRS += $(LIBFDT_objdir)

#include architecture specific make rules
include $(SRCDIR)/$(TEST_DIR)/Makefile

# cc-option
# Usage: OP_CFLAGS+=$(call cc-option, -falign-functions=0, -malign-functions=0)

cc-option = $(shell if $(CC) $(1) -S -o /dev/null -xc /dev/null \
              > /dev/null 2>&1; then echo "$(1)"; else echo "$(2)"; fi ;)

COMMON_CFLAGS += -g $(autodepend-flags)
COMMON_CFLAGS += -Wall -Wwrite-strings -Wclobbered -Wempty-body -Wuninitialized
COMMON_CFLAGS += -Wignored-qualifiers -Wunused-but-set-parameter
COMMON_CFLAGS += -Werror
frame-pointer-flag=-f$(if $(KEEP_FRAME_POINTER),no-,)omit-frame-pointer
fomit_frame_pointer := $(call cc-option, $(frame-pointer-flag), "")
fnostack_protector := $(call cc-option, -fno-stack-protector, "")
fnostack_protector_all := $(call cc-option, -fno-stack-protector-all, "")
wno_frame_address := $(call cc-option, -Wno-frame-address, "")
fno_pic := $(call cc-option, -fno-pic, "")
no_pie := $(call cc-option, -no-pie, "")
COMMON_CFLAGS += $(fomit_frame_pointer)
COMMON_CFLAGS += $(fno_stack_protector)
COMMON_CFLAGS += $(fno_stack_protector_all)
COMMON_CFLAGS += $(wno_frame_address)
COMMON_CFLAGS += $(if $(U32_LONG_FMT),-D__U32_LONG_FMT__,)
COMMON_CFLAGS += $(fno_pic) $(no_pie)

CFLAGS += $(COMMON_CFLAGS)
CFLAGS += -Wmissing-parameter-type -Wold-style-declaration -Woverride-init

CXXFLAGS += $(COMMON_CFLAGS)

autodepend-flags = -MMD -MF $(dir $*).$(notdir $*).d

LDFLAGS += $(CFLAGS)

$(libcflat): $(cflatobjs)
	$(AR) rcs $@ $^

include $(LIBFDT_srcdir)/Makefile.libfdt
$(LIBFDT_archive): CFLAGS += -ffreestanding -I $(SRCDIR)/lib -I $(SRCDIR)/lib/libfdt -Wno-sign-compare
$(LIBFDT_archive): $(addprefix $(LIBFDT_objdir)/,$(LIBFDT_OBJS))
	$(AR) rcs $@ $^


# Build directory target
.PHONY: directories
directories:
	@mkdir -p $(OBJDIRS)

%.o: %.S
	$(CC) $(CFLAGS) -c -nostdlib -o $@ $<

-include */.*.d */*/.*.d

all: directories $(shell cd $(SRCDIR) && git rev-parse --verify --short=8 HEAD >$(PWD)/build-head 2>/dev/null)

standalone: all
	@scripts/mkstandalone.sh

install: standalone
	mkdir -p $(DESTDIR)
	install tests/* $(DESTDIR)

clean: arch_clean
	$(RM) lib/.*.d $(libcflat) $(cflatobjs)

libfdt_clean:
	$(RM) $(LIBFDT_archive) \
	$(addprefix $(LIBFDT_objdir)/,$(LIBFDT_OBJS)) \
	$(LIBFDT_objdir)/.*.d

distclean: clean libfdt_clean
	$(RM) lib/asm config.mak $(TEST_DIR)-run msr.out cscope.* build-head
	$(RM) -r tests logs logs.old

cscope: cscope_dirs = lib lib/libfdt lib/linux $(TEST_DIR) $(ARCH_LIBDIRS) lib/asm-generic
cscope:
	$(RM) ./cscope.*
	find -L $(cscope_dirs) -maxdepth 1 \
		-name '*.[chsS]' -print | sed 's,^\./,,' | sort -u > ./cscope.files
	cscope -bk
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/README.md                                                           0000644 0000000 0000000 00000007142 00000000000 015223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # kvm-unit-tests for v86

Run the following to run this test:

```sh
./configure
make
make -C ../../build/libv86.js
./run.js x86/realmode.flat
./run.js x86/setjmp.flat
./run.js x86/cmpxchg8b.flat
./run.js x86/sieve.flat
./run.js x86/ioapic.flat
./run.js x86/apic.flat
./run.js x86/pae.flat
```

Tests can also be run in browser by going to `?profile=test-$name` (for
example, `?profile=test-realmode`).

Most tests require you to set `acpi: true` in the v86 constructor.


# Welcome to kvm-unit-tests

See http://www.linux-kvm.org/page/KVM-unit-tests for a high-level
description of this project, as well as running tests and adding
tests HOWTOs.

# Building the tests

This directory contains sources for a kvm test suite.

To create the test images do:

    ./configure
    make

in this directory. Test images are created in ./<ARCH>/*.flat

## Standalone tests

The tests can be built as standalone
To create and use standalone tests do:

    ./configure
    make standalone
    (send tests/some-test somewhere)
    (go to somewhere)
    ./some-test

'make install' will install all tests in PREFIX/share/kvm-unit-tests/tests,
each as a standalone test.


# Running the tests

Then use the runner script to detect the correct invocation and
invoke the test:

    ./x86-run ./x86/msr.flat
or:

    ./run_tests.sh

to run them all.

To select a specific qemu binary, specify the QEMU=<path>
environment variable:

    QEMU=/tmp/qemu/x86_64-softmmu/qemu-system-x86_64 ./x86-run ./x86/msr.flat

# Unit test inputs

Unit tests use QEMU's '-append <args...>' parameter for command line
inputs, i.e. all args will be available as argv strings in main().
Additionally a file of the form

KEY=VAL
KEY2=VAL
...

may be passed with '-initrd <file>' to become the unit test's environ,
which can then be accessed in the usual ways, e.g. VAL = getenv("KEY")
Any key=val strings can be passed, but some have reserved meanings in
the framework. The list of reserved environment variables is below

 QEMU_ACCEL            ... either kvm or tcg
 QEMU_VERSION_STRING   ... string of the form `qemu -h | head -1`
 KERNEL_VERSION_STRING ... string of the form `uname -r`

Additionally these self-explanatory variables are reserved

 QEMU_MAJOR, QEMU_MINOR, QEMU_MICRO, KERNEL_VERSION, KERNEL_PATCHLEVEL,
 KERNEL_SUBLEVEL, KERNEL_EXTRAVERSION

# Contributing

## Directory structure

    .:				configure script, top-level Makefile, and run_tests.sh
    ./scripts:		helper scripts for building and running tests
    ./lib:			general architecture neutral services for the tests
    ./lib/<ARCH>:	architecture dependent services for the tests
    ./<ARCH>:		the sources of the tests and the created objects/images

See <ARCH>/README for architecture specific documentation.

## Style

Currently there is a mix of indentation styles so any changes to
existing files should be consistent with the existing style. For new
files:

  - C: please use standard linux-with-tabs
  - Shell: use TABs for indentation

## Patches

Patches are welcome at the KVM mailing list <kvm@vger.kernel.org>.

Please prefix messages with: [kvm-unit-tests PATCH]

You can add the following to .git/config to do this automatically for you:

    [format]
        subjectprefix = kvm-unit-tests PATCH

Additionally it's helpful to have a common order of file types in patches.
Our chosen order attempts to place the more declarative files before
the code files. We also start with common code and finish with unit test
code. git-diff's orderFile feature allows us to specify the order in a
file. The orderFile we use is `scripts/git.difforder`. Adding the config
with `git config diff.orderFile scripts/git.difforder` enables it.
                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/api/api-sample.cc                                                   0000644 0000000 0000000 00000001026 00000000000 017047  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "kvmxx.hh"
#include "identity.hh"
#include "exception.hh"
#include <stdio.h>

static int global = 0;

static void set_global()
{
    global = 1;
}

int test_main(int ac, char** av)
{
    kvm::system system;
    kvm::vm vm(system);
    mem_map memmap(vm);
    identity::vm ident_vm(vm, memmap);
    kvm::vcpu vcpu(vm, 0);
    identity::vcpu thread(vcpu, set_global);
    vcpu.run();
    printf("global %d\n", global);
    return global == 1 ? 0 : 1;
}

int main(int ac, char** av)
{
    return try_main(test_main, ac, av);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/kvm-unit-tests/api/dirty-log-perf.cc                                               0000644 0000000 0000000 00000010013 00000000000 017657  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "kvmxx.hh"
#include "exception.hh"
#include "memmap.hh"
#include "identity.hh"
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>

namespace {

const int page_size	= 4096;
int64_t nr_total_pages	= 256 * 1024;
int64_t nr_slot_pages	= 256 * 1024;

// Return the current time in nanoseconds.
uint64_t time_ns()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * (uint64_t)1000000000 + ts.tv_nsec;
}

// Update nr_to_write pages selected from nr_pages pages.
void write_mem(void* slot_head, int64_t nr_to_write, int64_t nr_pages)
{
    char* var = static_cast<char*>(slot_head);
    int64_t interval = nr_pages / nr_to_write;

    for (int64_t i = 0; i < nr_to_write; ++i) {
        ++(*var);
        var += interval * page_size;
    }
}

// Let the guest update nr_to_write pages selected from nr_pages pages.
void do_guest_write(kvm::vcpu& vcpu, void* slot_head,
                    int64_t nr_to_write, int64_t nr_pages)
{
    identity::vcpu guest_write_thread(vcpu, std::bind(write_mem, slot_head,
                                                      nr_to_write, nr_pages));
    vcpu.run();
}

// Check how long it takes to update dirty log.
void check_dirty_log(kvm::vcpu& vcpu, mem_slot& slot, void* slot_head)
{
    slot.set_dirty_logging(true);
    slot.update_dirty_log();

    for (int64_t i = 1; i <= nr_slot_pages; i *= 2) {
        do_guest_write(vcpu, slot_head, i, nr_slot_pages);

        uint64_t start_ns = time_ns();
        int n = slot.update_dirty_log();
        uint64_t end_ns = time_ns();

        printf("get dirty log: %10lld ns for %10d dirty pages (expected %lld)\n",
               end_ns - start_ns, n, i);
    }

    slot.set_dirty_logging(false);
}

}

void parse_options(int ac, char **av)
{
    int opt;
    char *endptr;

    while ((opt = getopt(ac, av, "n:m:")) != -1) {
        switch (opt) {
        case 'n':
            errno = 0;
            nr_slot_pages = strtol(optarg, &endptr, 10);
            if (errno || endptr == optarg) {
                printf("dirty-log-perf: Invalid number: -n %s\n", optarg);
                exit(1);
            }
            if (*endptr == 'k' || *endptr == 'K') {
                nr_slot_pages *= 1024;
            }
            break;
        case 'm':
            errno = 0;
            nr_total_pages = strtol(optarg, &endptr, 10);
            if (errno || endptr == optarg) {
                printf("dirty-log-perf: Invalid number: -m %s\n", optarg);
                exit(1);
            }
            if (*endptr == 'k' || *endptr == 'K') {
                nr_total_pages *= 1024;
            }
            break;
        default:
            printf("dirty-log-perf: Invalid option\n");
            exit(1);
        }
    }

    if (nr_slot_pages > nr_total_pages) {
        printf("dirty-log-perf: Invalid setting: slot %lld > mem %lld\n",
               nr_slot_pages, nr_total_pages);
        exit(1);
    }
    printf("dirty-log-perf: %lld slot pages / %lld mem pages\n",
           nr_slot_pages, nr_total_pages);
}

int test_main(int ac, char **av)
{
    kvm::system sys;
    kvm::vm vm(sys);
    mem_map memmap(vm);

    parse_options(ac, av);

    void* mem_head;
    int64_t mem_size = nr_total_pages * page_size;
    if (posix_memalign(&mem_head, page_size, mem_size)) {
        printf("dirty-log-perf: Could not allocate guest memory.\n");
        exit(1);
    }
    uint64_t mem_addr = reinterpret_cast<uintptr_t>(mem_head);

    identity::hole hole(mem_head, mem_size);
    identity::vm ident_vm(vm, memmap, hole);
    kvm::vcpu vcpu(vm, 0);

    uint64_t slot_size = nr_slot_pages * page_size;
    uint64_t next_size = mem_size - slot_size;
    uint64_t next_addr = mem_addr + slot_size;
    mem_slot slot(memmap, mem_addr, slot_size, mem_head);
    mem_slot other_slot(memmap, next_addr, next_size, (void *)next_addr);

    // pre-allocate shadow pages
    do_guest_write(vcpu, mem_head, nr_total_pages, nr_total_pages);
    check_dirty_log(vcpu, slot, mem_head);
    return 0;
}

int main(int ac, char** av)
{
    return try_main(test_main, ac, av);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/api/dirty-log.cc                                                    0000644 0000000 0000000 00000004315 00000000000 016735  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "kvmxx.hh"
#include "exception.hh"
#include "memmap.hh"
#include "identity.hh"
#include <thread>
#include <stdlib.h>
#include <stdio.h>

namespace {

void delay_loop(unsigned n)
{
    for (unsigned i = 0; i < n; ++i) {
        asm volatile("pause");
    }
 }

void write_mem(volatile bool& running, volatile int* shared_var)
{
    while (running) {
        ++*shared_var;
        delay_loop(1000);
    }
}

void check_dirty_log(mem_slot& slot,
                     volatile bool& running,
                     volatile int* shared_var,
                     int& nr_fail)
{
    uint64_t shared_var_gpa = reinterpret_cast<uint64_t>(shared_var);
    slot.set_dirty_logging(true);
    slot.update_dirty_log();
    for (int i = 0; i < 10000000; ++i) {
        int sample1 = *shared_var;
        delay_loop(600);
        int sample2 = *shared_var;
        slot.update_dirty_log();
        if (!slot.is_dirty(shared_var_gpa) && sample1 != sample2) {
            ++nr_fail;
        }
    }
    running = false;
    slot.set_dirty_logging(false);
}

}

int test_main(int ac, char **av)
{
    kvm::system sys;
    kvm::vm vm(sys);
    mem_map memmap(vm);
    void* logged_slot_virt;
    int ret = posix_memalign(&logged_slot_virt, 4096, 4096);
    if (ret) {
        throw errno_exception(ret);
    }
    volatile int* shared_var = static_cast<volatile int*>(logged_slot_virt);
    identity::hole hole(logged_slot_virt, 4096);
    identity::vm ident_vm(vm, memmap, hole);
    kvm::vcpu vcpu(vm, 0);
    bool running = true;
    int nr_fail = 0;
    mem_slot logged_slot(memmap,
                         reinterpret_cast<uintptr_t>(logged_slot_virt),
                         4096, logged_slot_virt);
    std::thread host_poll_thread(check_dirty_log, std::ref(logged_slot),
                                   std::ref(running),
                                   shared_var, std::ref(nr_fail));
    identity::vcpu guest_write_thread(vcpu,
                                      std::bind(write_mem,
					       	std::ref(running),
						shared_var));
    vcpu.run();
    host_poll_thread.join();
    printf("Dirty bitmap failures: %d\n", nr_fail);
    return nr_fail == 0 ? 0 : 1;
}

int main(int ac, char** av)
{
    return try_main(test_main, ac, av);
}
                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/api/exception.cc                                                    0000644 0000000 0000000 00000001257 00000000000 017023  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "exception.hh"
#include <cstdio>
#include <cstring>

errno_exception::errno_exception(int errno)
    : _errno(errno)
{
}

int errno_exception::errno() const
{
    return _errno;
}

const char *errno_exception::what()
{
    std::snprintf(_buf, sizeof _buf, "error: %s (%d)",
		  std::strerror(_errno), _errno);
    return _buf;
}

int try_main(int (*main)(int argc, char** argv), int argc, char** argv,
	     int ret_on_exception)
{
    try {
        return main(argc, argv);
    } catch (std::exception& e) {
        std::fprintf(stderr, "exception: %s\n", e.what());
    } catch (...) {
        std::fprintf(stderr, "unknown exception\n");
    }
    return ret_on_exception;
}
                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/kvm-unit-tests/api/exception.hh                                                    0000644 0000000 0000000 00000000577 00000000000 017041  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef EXCEPTION_HH
#define EXCEPTION_HH

#include <exception>

class errno_exception : public std::exception {
public:
    explicit errno_exception(int err_no);
    int errno() const;
    virtual const char *what();
private:
    int _errno;
    char _buf[1000];
};

int try_main(int (*main)(int argc, char** argv), int argc, char** argv,
	     int ret_on_exception = 127);

#endif
                                                                                                                                 source/v64/tests/kvm-unit-tests/api/identity.cc                                                     0000644 0000000 0000000 00000006421 00000000000 016654  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "identity.hh"
#include "exception.hh"
#include <stdlib.h>
#include <stdio.h>

namespace identity {

typedef unsigned long ulong;

hole::hole()
    : address(), size()
{
}

hole::hole(void* address, size_t size)
    : address(address), size(size)
{
}

vm::vm(kvm::vm& vm, mem_map& mmap, hole h)
{
    int ret = posix_memalign(&tss, 4096, 4 * 4096);
    if (ret) {
        throw errno_exception(ret);
    }

    uint64_t hole_gpa = reinterpret_cast<uintptr_t>(h.address);
    char* hole_hva = static_cast<char*>(h.address);
    uint64_t tss_addr = reinterpret_cast<uintptr_t>(tss);
    uint64_t tss_end = tss_addr + 4 * 4096;
    uint64_t hole_end = hole_gpa + h.size;

    if (hole_gpa < tss_addr) {
        if (hole_gpa) {
            _slots.push_back(mem_slot_ptr(new mem_slot(mmap, 0, hole_gpa, NULL)));
        }
        _slots.push_back(mem_slot_ptr(new mem_slot(mmap, hole_end, tss_addr - hole_end,
						   hole_hva + h.size)));
        _slots.push_back(mem_slot_ptr(new mem_slot(mmap, tss_end, (uint32_t)-tss_end,
						   (char*)tss + 4 * 4096)));
    } else {
        _slots.push_back(mem_slot_ptr(new mem_slot(mmap, 0, tss_addr, NULL)));
        _slots.push_back(mem_slot_ptr(new mem_slot(mmap, tss_end, hole_gpa - tss_end,
						   (char*)tss + 4 * 4096)));
        _slots.push_back(mem_slot_ptr(new mem_slot(mmap, hole_end, (uint32_t)-hole_end,
						   hole_hva + h.size)));
    }

    vm.set_tss_addr(tss_addr);
    vm.set_ept_identity_map_addr(tss_addr + 3 * 4096);
}

vm::~vm()
{
    free(tss);
}

void vcpu::setup_sregs()
{
    kvm_sregs sregs = { };
    kvm_segment dseg = { };
    dseg.base = 0; dseg.limit = -1U; dseg.type = 3; dseg.present = 1;
    dseg.dpl = 3; dseg.db = 1; dseg.s = 1; dseg.l = 0; dseg.g = 1;
    kvm_segment cseg = dseg;
    cseg.type = 11;

    sregs.cs = cseg; asm ("mov %%cs, %0" : "=rm"(sregs.cs.selector));
    sregs.ds = dseg; asm ("mov %%ds, %0" : "=rm"(sregs.ds.selector));
    sregs.es = dseg; asm ("mov %%es, %0" : "=rm"(sregs.es.selector));
    sregs.fs = dseg; asm ("mov %%fs, %0" : "=rm"(sregs.fs.selector));
    sregs.gs = dseg; asm ("mov %%gs, %0" : "=rm"(sregs.gs.selector));
    sregs.ss = dseg; asm ("mov %%ss, %0" : "=rm"(sregs.ss.selector));

    uint32_t gsbase;
    asm ("mov %%gs:0, %0" : "=r"(gsbase));
    sregs.gs.base = gsbase;

    sregs.tr.base = reinterpret_cast<uintptr_t>(&*_stack.begin());
    sregs.tr.type = 11;
    sregs.tr.s = 0;
    sregs.tr.present = 1;

    sregs.cr0 = 0x11; /* PE, ET, !PG */
    sregs.cr4 = 0;
    sregs.efer = 0;
    sregs.apic_base = 0xfee00000;
    _vcpu.set_sregs(sregs);
}

void vcpu::thunk(vcpu* zis)
{
    zis->_guest_func();
    asm volatile("outb %%al, %%dx" : : "a"(0), "d"(0));
}

void vcpu::setup_regs()
{
    kvm_regs regs = {};
    regs.rflags = 0x3202;
    regs.rsp = reinterpret_cast<ulong>(&*_stack.end());
    regs.rsp &= ~15UL;
    ulong* sp = reinterpret_cast<ulong *>(regs.rsp);
    *--sp = reinterpret_cast<ulong>((char*)this);
    *--sp = 0;
    regs.rsp = reinterpret_cast<ulong>(sp);
    regs.rip = reinterpret_cast<ulong>(&vcpu::thunk);
    printf("rip %llx\n", regs.rip);
    _vcpu.set_regs(regs);
}

vcpu::vcpu(kvm::vcpu& vcpu, std::function<void ()> guest_func,
           unsigned long stack_size)
    : _vcpu(vcpu), _guest_func(guest_func), _stack(stack_size)
{
    setup_sregs();
    setup_regs();
}

}
                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/api/identity.hh                                                     0000644 0000000 0000000 00000001467 00000000000 016673  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef API_IDENTITY_HH
#define API_IDENTITY_HH

#include "kvmxx.hh"
#include "memmap.hh"
#include <functional>
#include <memory>
#include <vector>

namespace identity {

struct hole {
    hole();
    hole(void* address, size_t size);
    void* address;
    size_t size;
};

class vm {
public:
    vm(kvm::vm& vm, mem_map& mmap, hole address_space_hole = hole());
    ~vm();
private:
    void *tss;
    typedef std::shared_ptr<mem_slot> mem_slot_ptr;
    std::vector<mem_slot_ptr> _slots;
};

class vcpu {
public:
    vcpu(kvm::vcpu& vcpu, std::function<void ()> guest_func,
	 unsigned long stack_size = 256 * 1024);
private:
    static void thunk(vcpu* vcpu);
    void setup_regs();
    void setup_sregs();
private:
    kvm::vcpu& _vcpu;
    std::function<void ()> _guest_func;
    std::vector<char> _stack;
};

}

#endif
                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/api/kvmxx.cc                                                        0000644 0000000 0000000 00000010033 00000000000 016172  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "kvmxx.hh"
#include "exception.hh"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <memory>
#include <algorithm>

namespace kvm {

static long check_error(long r)
{
    if (r == -1) {
	throw errno_exception(errno);
    }
    return r;
}

fd::fd(int fd)
    : _fd(fd)
{
}

fd::fd(const fd& other)
    : _fd(::dup(other._fd))
{
    check_error(_fd);
}

fd::fd(std::string device_node, int flags)
    : _fd(::open(device_node.c_str(), flags))
{
    check_error(_fd);
}

long fd::ioctl(unsigned nr, long arg)
{
    return check_error(::ioctl(_fd, nr, arg));
}

vcpu::vcpu(vm& vm, int id)
    : _vm(vm), _fd(vm._fd.ioctl(KVM_CREATE_VCPU, id)), _shared(NULL)
    , _mmap_size(_vm._system._fd.ioctl(KVM_GET_VCPU_MMAP_SIZE, 0))

{
    kvm_run *shared = static_cast<kvm_run*>(::mmap(NULL, _mmap_size,
						   PROT_READ | PROT_WRITE,
						   MAP_SHARED,
						   _fd.get(), 0));
    if (shared == MAP_FAILED) {
	throw errno_exception(errno);
    }
    _shared = shared;
}

vcpu::~vcpu()
{
    munmap(_shared, _mmap_size);
}

void vcpu::run()
{
    _fd.ioctl(KVM_RUN, 0);
}

kvm_regs vcpu::regs()
{
    kvm_regs regs;
    _fd.ioctlp(KVM_GET_REGS, &regs);
    return regs;
}

void vcpu::set_regs(const kvm_regs& regs)
{
    _fd.ioctlp(KVM_SET_REGS, const_cast<kvm_regs*>(&regs));
}

kvm_sregs vcpu::sregs()
{
    kvm_sregs sregs;
    _fd.ioctlp(KVM_GET_SREGS, &sregs);
    return sregs;
}

void vcpu::set_sregs(const kvm_sregs& sregs)
{
    _fd.ioctlp(KVM_SET_SREGS, const_cast<kvm_sregs*>(&sregs));
}

class vcpu::kvm_msrs_ptr {
public:
    explicit kvm_msrs_ptr(size_t nmsrs);
    ~kvm_msrs_ptr() { ::free(_kvm_msrs); }
    kvm_msrs* operator->() { return _kvm_msrs; }
    kvm_msrs* get() { return _kvm_msrs; }
private:
    kvm_msrs* _kvm_msrs;
};

vcpu::kvm_msrs_ptr::kvm_msrs_ptr(size_t nmsrs)
    : _kvm_msrs(0)
{
    size_t size = sizeof(kvm_msrs) + sizeof(kvm_msr_entry) * nmsrs;
    _kvm_msrs = static_cast<kvm_msrs*>(::malloc(size));
    if (!_kvm_msrs) {
	throw std::bad_alloc();
    }
}

std::vector<kvm_msr_entry> vcpu::msrs(std::vector<uint32_t> indices)
{
    kvm_msrs_ptr msrs(indices.size());
    msrs->nmsrs = indices.size();
    for (unsigned i = 0; i < msrs->nmsrs; ++i) {
	msrs->entries[i].index = indices[i];
    }
    _fd.ioctlp(KVM_GET_MSRS, msrs.get());
    return std::vector<kvm_msr_entry>(msrs->entries,
				      msrs->entries + msrs->nmsrs);
}

void vcpu::set_msrs(const std::vector<kvm_msr_entry>& msrs)
{
    kvm_msrs_ptr _msrs(msrs.size());
    _msrs->nmsrs = msrs.size();
    std::copy(msrs.begin(), msrs.end(), _msrs->entries);
    _fd.ioctlp(KVM_SET_MSRS, _msrs.get());
}

void vcpu::set_debug(uint64_t dr[8], bool enabled, bool singlestep)
{
    kvm_guest_debug gd;

    gd.control = 0;
    if (enabled) {
	gd.control |= KVM_GUESTDBG_ENABLE;
    }
    if (singlestep) {
	gd.control |= KVM_GUESTDBG_SINGLESTEP;
    }
    for (int i = 0; i < 8; ++i) {
	gd.arch.debugreg[i] = dr[i];
    }
    _fd.ioctlp(KVM_SET_GUEST_DEBUG, &gd);
}

vm::vm(system& system)
    : _system(system), _fd(system._fd.ioctl(KVM_CREATE_VM, 0))
{
}

void vm::set_memory_region(int slot, void *addr, uint64_t gpa, size_t len,
                           uint32_t flags)
{
    struct kvm_userspace_memory_region umr;

    umr.slot = slot;
    umr.flags = flags;
    umr.guest_phys_addr = gpa;
    umr.memory_size = len;
    umr.userspace_addr = reinterpret_cast<uintptr_t>(addr);
    _fd.ioctlp(KVM_SET_USER_MEMORY_REGION, &umr);
}

void vm::get_dirty_log(int slot, void *log)
{
    struct kvm_dirty_log kdl;
    kdl.slot = slot;
    kdl.dirty_bitmap = log;
    _fd.ioctlp(KVM_GET_DIRTY_LOG, &kdl);
}

void vm::set_tss_addr(uint32_t addr)
{
    _fd.ioctl(KVM_SET_TSS_ADDR, addr);
}

void vm::set_ept_identity_map_addr(uint64_t addr)
{
    _fd.ioctlp(KVM_SET_IDENTITY_MAP_ADDR, &addr);
}

system::system(std::string device_node)
    : _fd(device_node, O_RDWR)
{
}

bool system::check_extension(int extension)
{
    return _fd.ioctl(KVM_CHECK_EXTENSION, extension);
}

int system::get_extension_int(int extension)
{
    return _fd.ioctl(KVM_CHECK_EXTENSION, extension);
}

};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/api/kvmxx.hh                                                        0000644 0000000 0000000 00000003430 00000000000 016207  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef KVMXX_H
#define KVMXX_H

#include <string>
#include <signal.h>
#include <unistd.h>
#include <vector>
#include <errno.h>
#include <linux/kvm.h>
#include <stdint.h>

namespace kvm {

class system;
class vm;
class vcpu;
class fd;

class fd {
public:
    explicit fd(int n);
    explicit fd(std::string path, int flags);
    fd(const fd& other);
    ~fd() { ::close(_fd); }
    int get() { return _fd; }
    long ioctl(unsigned nr, long arg);
    long ioctlp(unsigned nr, void *arg) {
	return ioctl(nr, reinterpret_cast<long>(arg));
    }
private:
    int _fd;
};

class vcpu {
public:
    vcpu(vm& vm, int fd);
    ~vcpu();
    void run();
    kvm_run *shared();
    kvm_regs regs();
    void set_regs(const kvm_regs& regs);
    kvm_sregs sregs();
    void set_sregs(const kvm_sregs& sregs);
    std::vector<kvm_msr_entry> msrs(std::vector<uint32_t> indices);
    void set_msrs(const std::vector<kvm_msr_entry>& msrs);
    void set_debug(uint64_t dr[8], bool enabled, bool singlestep);
private:
    class kvm_msrs_ptr;
private:
    vm& _vm;
    fd _fd;
    kvm_run *_shared;
    unsigned _mmap_size;
    friend class vm;
};

class vm {
public:
    explicit vm(system& system);
    void set_memory_region(int slot, void *addr, uint64_t gpa, size_t len,
                           uint32_t flags = 0);
    void get_dirty_log(int slot, void *log);
    void set_tss_addr(uint32_t addr);
    void set_ept_identity_map_addr(uint64_t addr);
    system& sys() { return _system; }
private:
    system& _system;
    fd _fd;
    friend class system;
    friend class vcpu;
};

class system {
public:
    explicit system(std::string device_node = "/dev/kvm");
    bool check_extension(int extension);
    int get_extension_int(int extension);
private:
    fd _fd;
    friend class vcpu;
    friend class vm;
};

};

#endif
                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/api/memmap.cc                                                       0000644 0000000 0000000 00000004176 00000000000 016304  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "memmap.hh"
#include <numeric>

mem_slot::mem_slot(mem_map& map, uint64_t gpa, uint64_t size, void* hva)
    : _map(map)
    , _slot(map._free_slots.top())
    , _gpa(gpa)
    , _size(size)
    , _hva(hva)
    , _dirty_log_enabled(false)
    , _log()
{
    map._free_slots.pop();
    if (_size) {
        update();
    }
}

mem_slot::~mem_slot()
{
    if (!_size) {
        return;
    }
    _size = 0;
    try {
        update();
        _map._free_slots.push(_slot);
    } catch (...) {
        // can't do much if we can't undo slot registration - leak the slot
    }
}

void mem_slot::set_dirty_logging(bool enabled)
{
    if (_dirty_log_enabled != enabled) {
        _dirty_log_enabled = enabled;
        if (enabled) {
            int logsize = ((_size >> 12) + bits_per_word - 1) / bits_per_word;
            _log.resize(logsize);
        } else {
            _log.resize(0);
        }
        if (_size) {
            update();
        }
    }
}

void mem_slot::update()
{
    uint32_t flags = 0;
    if (_dirty_log_enabled) {
        flags |= KVM_MEM_LOG_DIRTY_PAGES;
    }
    _map._vm.set_memory_region(_slot, _hva, _gpa, _size, flags);
}

bool mem_slot::dirty_logging() const
{
    return _dirty_log_enabled;
}

static inline int hweight(uint64_t w)
{
    w -= (w >> 1) & 0x5555555555555555;
    w =  (w & 0x3333333333333333) + ((w >> 2) & 0x3333333333333333);
    w =  (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0f;
    return (w * 0x0101010101010101) >> 56;
}

int mem_slot::update_dirty_log()
{
    _map._vm.get_dirty_log(_slot, &_log[0]);
    return std::accumulate(_log.begin(), _log.end(), 0,
                           [] (int prev, ulong elem) -> int {
                               return prev + hweight(elem);
                           });
}

bool mem_slot::is_dirty(uint64_t gpa) const
{
    uint64_t pagenr = (gpa - _gpa) >> 12;
    ulong wordnr = pagenr / bits_per_word;
    ulong bit = 1ULL << (pagenr % bits_per_word);
    return _log[wordnr] & bit;
}

mem_map::mem_map(kvm::vm& vm)
    : _vm(vm)
{
    int nr_slots = vm.sys().get_extension_int(KVM_CAP_NR_MEMSLOTS);
    for (int i = 0; i < nr_slots; ++i) {
        _free_slots.push(i);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/api/memmap.hh                                                       0000644 0000000 0000000 00000001465 00000000000 016314  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef MEMMAP_HH
#define MEMMAP_HH

#include "kvmxx.hh"
#include <stdint.h>
#include <vector>
#include <stack>

class mem_map;
class mem_slot;

class mem_slot {
public:
    mem_slot(mem_map& map, uint64_t gpa, uint64_t size, void *hva);
    ~mem_slot();
    void set_dirty_logging(bool enabled);
    bool dirty_logging() const;
    int update_dirty_log();
    bool is_dirty(uint64_t gpa) const;
private:
    void update();
private:
    typedef unsigned long ulong;
    static const int bits_per_word = sizeof(ulong) * 8;
    mem_map& _map;
    int _slot;
    uint64_t _gpa;
    uint64_t _size;
    void *_hva;
    bool _dirty_log_enabled;
    std::vector<ulong> _log;
};

class mem_map {
public:
    mem_map(kvm::vm& vm);
private:
    kvm::vm& _vm;
    std::stack<int> _free_slots;
    friend class mem_slot;
};

#endif
                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/arm32.mjs                                                           0000644 0000000 0000000 00000005336 00000000000 015406  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The 32-bit arm kvm-unit-tests of docs/aarch32-plan.md R5.1 (upstream
// arm/unittests.cfg's entries for arm; its timer, cache, debug and fpu
// tests are arm64's, the gicv2 ones need a GICv2, pci-test the PCIe host
// the 32-bit virt has not), built by build.sh arm and run by run.mjs.
//
//   node tests/kvm-unit-tests/arm32.mjs [--qemu]
//   (without --qemu on v86's cpu_type "arm32", its cooperative cores for the SMP cases)
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const here = fileURLToPath(new URL(".", import.meta.url));
const MAX_SMP = 4;
// (the interpreter's cores take turns: the spinlock test's rounds need longer
// there; sieve's three sieves of 100 MB are some 5 billion instructions)
const V86_TIMEOUT = { "spinlock-test": 300, sieve: 1800 };
// [name, file, cores, test_args, memory MiB]
const CASES = [
    ["selftest-setup", "selftest", 2, "setup smp=2 mem=256", 256],
    ["selftest-vectors-kernel", "selftest", 1, "vectors-kernel"],
    ["selftest-vectors-user", "selftest", 1, "vectors-user"],
    ["selftest-smp", "selftest", MAX_SMP, "smp"],
    // (no PMU in profile arm32-v1, none in the reference's cortex-a15 with pmu=off: skipped)
    ["pmu-cycle-counter", "pmu", 1, "cycle-counter 0"],
    ["gicv3-ipi", "gic", MAX_SMP, "ipi"],
    ["gicv3-active", "gic", MAX_SMP, "active"],
    ["psci", "psci", MAX_SMP, ""],
    ["pl031", "pl031", 1, ""],
    ["spinlock-test", "spinlock-test", MAX_SMP, ""],
    // (its three 100 MB mallocs: more than the default memory)
    ["sieve", "sieve", 1, "", 256],
];

const qemu = process.argv.includes("--qemu");
const build = spawnSync("bash", [here + "build.sh", "arm"], { encoding: "utf8" });
if(build.status !== 0) { console.log(`arm: build failed\n${build.stdout.slice(-3000)}${build.stderr}`); process.exit(1); }
let failed = 0;
for(const [name, file, cores, test_args, memory] of CASES)
{
    const timeout = !qemu && V86_TIMEOUT[name] || 60;
    const run = spawnSync("node", [here + "run.mjs", "--arm32", ...(qemu ? ["--qemu"] : []),
        "--cores", String(cores), ...(memory ? ["--memory", String(memory)] : []), "--append", test_args, "--timeout", String(timeout),
        `${here}../../build/kvm-unit-tests/arm/arm/${file}.flat`], { encoding: "utf8" });
    const result = run.stdout.trim().split("\n").pop();
    // (exit(77), EXIT: STATUS=77 (code 38): the test found nothing to test and skipped)
    const skipped = /code=38 /.test(result) && /test skipped/.test(run.stdout);
    console.log(`arm ${name}: ${skipped ? "SKIPPED " + result : result}`);
    if(run.status !== 0 && !skipped) { failed++; console.log(run.stdout.slice(-2000)); }
}
console.log(failed ? `${failed} failed` : "all passed");
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/arm64.mjs                                                           0000644 0000000 0000000 00000006650 00000000000 015413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The arm64 kvm-unit-tests subset of docs/arm64-virt-android16-plan.md P0.6
// (upstream arm/unittests.cfg entries, and fpu.flat, pl031.flat and
// spinlock-test.flat run directly), built by build.sh for each translation
// granule and run by run.mjs.
//
//   node tests/kvm-unit-tests/arm64.mjs [--qemu] [--single-core] [4k 16k 64k]
//   (without --qemu the cases run on v86's ARM core, its cooperative cores for
//   the SMP ones (P3.9), and the 16k and 64k builds with profile v1.1's
//   granules; --single-core only the cases of one core)
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const here = fileURLToPath(new URL(".", import.meta.url));
const MAX_SMP = 4;
// (the interpreter's cores take turns: the spinlock test's 4 x 10 million
// lock rounds need longer there than the 60 s the others get)
const V86_TIMEOUT = { "spinlock-test": 300 };
// [name, file, cores, test_args, memory MiB]
export const CASES = [
    ["selftest-setup", "selftest", 2, "setup smp=2 mem=256", 256],
    ["selftest-vectors-kernel", "selftest", 1, "vectors-kernel"],
    ["selftest-vectors-user", "selftest", 1, "vectors-user"],
    ["selftest-smp", "selftest", MAX_SMP, "smp"],
    ["psci", "psci", MAX_SMP, ""],
    ["timer", "timer", 1, ""],
    ["gicv3-ipi", "gic", MAX_SMP, "ipi"],
    ["gicv3-active", "gic", MAX_SMP, "active"],
    ["cache", "cache", 1, ""],
    ["debug-bp", "debug", 1, "bp"],
    ["debug-wp", "debug", 1, "wp"],
    ["debug-sstep", "debug", 1, "ss"],
    ["fpu-context", "fpu", 2, ""],
    ["pl031", "pl031", 1, ""],
    ["spinlock-test", "spinlock-test", MAX_SMP, ""],
];

const args = process.argv.slice(2);
const qemu = args.includes("--qemu");
const single_core = args.includes("--single-core");
const granules = args.filter(a => /^\d+k$/.test(a));
let failed = 0;
for(const granule of granules.length ? granules : ["4k", "16k", "64k"])
{
    const build = spawnSync("bash", [here + "build.sh", "arm64-" + granule], { encoding: "utf8" });
    if(build.status !== 0) { console.log(`arm64-${granule}: build failed\n${build.stdout.slice(-3000)}${build.stderr}`); process.exit(1); }
    for(const [name, file, cores, test_args, memory] of CASES)
    {
        if(single_core && cores > 1) continue;
        const timeout = !qemu && V86_TIMEOUT[name] || 60;
        const once = () => spawnSync("node", [here + "run.mjs", "--arm64", ...(qemu ? ["--qemu"] : granule !== "4k" ? ["--granules-all"] : []),
            "--cores", String(cores), ...(memory ? ["--memory", String(memory)] : []), "--append", test_args, "--timeout", String(timeout),
            `${here}../../build/kvm-unit-tests/arm64-${granule}/arm/${file}.flat`], { encoding: "utf8" });
        let run = once(), note = "";
        // (the timer test's "latency within 10 ms" checks measure the host:
        // a loaded machine fails them now and then, so they get one retry)
        const failures = run.stdout.match(/^FAIL: .*$/gm) || [];
        if(run.status !== 0 && failures.length && failures.every(line => /latency within/.test(line)))
        {
            note = ` (retried after ${failures.join("; ")})`;
            run = once();
        }
        const result = run.stdout.trim().split("\n").pop();
        console.log(`arm64-${granule} ${name}: ${result}${note}`);
        if(run.status !== 0) { failed++; console.log(run.stdout.slice(-2000)); }
    }
}
console.log(failed ? `${failed} failed` : "all passed");
process.exit(failed ? 1 : 0);
                                                                                        source/v64/tests/kvm-unit-tests/build.sh                                                            0000755 0000000 0000000 00000012445 00000000000 015404  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/bin/bash
# Build kvm-unit-tests out of tree, in build/kvm-unit-tests/<arch>/ of the v86
# checkout, so that i386 and x86_64 builds do not overwrite each other.
#
# usage: build.sh [ARCH [TEST.flat...]]
#   ARCH defaults to i386; the tests default to the ones in `make kvm-unit-test`
#   ARCH arm64-4k, arm64-16k or arm64-64k: upstream's arm64 tests with that
#   translation granule (docs/arm64-virt-android16-plan.md P0.6), built from
#   the pinned upstream checkout KUT_ARM64_SRC (default build/a64-ref/
#   kvm-unit-tests at $kut_arm64_commit): this copy's lib/ is years older
#   than upstream's arm/ and lib/arm*.
set -euo pipefail

src="$(cd "$(dirname "$0")"; pwd)"
arch="${1:-i386}"
shift || true
kut_arm64_commit=5a221342a025948fa7d84f0c404748f6ba57f3ad

case "$arch" in arm64-*|arm)
    page="${arch#arm64-}"
    ksrc="${KUT_ARM64_SRC:-$src/../../build/a64-ref/kvm-unit-tests}"
    ksrc="$(cd "$ksrc"; pwd)"
    if [ "$(git -C "$ksrc" rev-parse HEAD)" != "$kut_arm64_commit" ]
    then
        echo "$ksrc is not kvm-unit-tests $kut_arm64_commit" >&2
        exit 1
    fi
    if [ $# -eq 0 ] && [ "$arch" = arm ]
    then
        # (ARCH arm: the 32-bit tests, cpu_type arm32's: docs/aarch32-plan.md R5.1)
        # (upstream's timer, cache, debug and fpu tests are arm64's)
        set -- arm/selftest.flat arm/psci.flat arm/gic.flat arm/pmu.flat arm/pl031.flat arm/spinlock-test.flat arm/sieve.flat
    elif [ $# -eq 0 ]
    then
        set -- arm/selftest.flat arm/psci.flat arm/timer.flat arm/gic.flat arm/cache.flat arm/debug.flat \
            arm/fpu.flat arm/pl031.flat arm/spinlock-test.flat
    fi
    out="$src/../../build/kvm-unit-tests/$arch"
    mkdir -p "$out"
    out="$(cd "$out"; pwd)"
    cd "$out"
    rust_bin="$(rustc --print sysroot)/lib/rustlib/$(rustc -vV | sed -n 's/^host: //p')/bin"
    llvm="${LLVM_BIN:-$(dirname "$(command -v llvm-objcopy || echo /opt/homebrew/opt/llvm/bin/llvm-objcopy)")}"
    mkdir -p tools
    ln -sf "$rust_bin/rust-lld" tools/ld.lld
    if [ "$arch" = arm ]
    then
        cc="clang -target armv7a-unknown-linux-gnueabi --ld-path=$out/tools/ld.lld -Wno-unknown-warning-option -Wno-unused-command-line-argument"
        configure_args=(--arch=arm)
    else
        cc="clang -target aarch64-unknown-linux-gnu --ld-path=$out/tools/ld.lld -Wno-unknown-warning-option -Wno-unused-command-line-argument"
        configure_args=(--arch=arm64 --page-size="$page")
    fi
    if [ ! -f config.mak ]
    then
        # (upstream's configure insists on bash 4 but runs on macOS's 3.2)
        sed -e '/BASH_VERSINFO/,/^fi$/d' -e "s|^srcdir=.*|srcdir=\"$ksrc\"|" "$ksrc/configure" > configure
        bash ./configure "${configure_args[@]}" --cc="$cc" --ld="$out/tools/ld.lld" --disable-werror
    fi
    tools=(CC="$cc" LD="$out/tools/ld.lld" OBJCOPY="$llvm/llvm-objcopy" OBJDUMP="$llvm/llvm-objdump" READELF="$llvm/llvm-readelf" AR="$llvm/llvm-ar")
    # (the object directories: only `make all` creates them)
    make "${tools[@]}" directories
    make "${tools[@]}" "$@"
    exit 0
esac
if [ $# -eq 0 ]
then
    set -- x86/realmode.flat x86/taskswitch.flat x86/taskswitch2.flat
fi

out="$src/../../build/kvm-unit-tests/$arch"
mkdir -p "$out"
out="$(cd "$out"; pwd)"
cd "$out"

# the test code must not use SSE/MMX; warnings clang has about the library
# (lib/pci.c's constants) and x86/xsave.c's printf formats are not errors
flags="-std=gnu11 -mno-sse -mno-sse2 -mno-mmx -Wno-error=format -Wno-error=constant-conversion"

if [ "$(uname -s)" = Darwin ]
then
    # No Linux gcc on macOS: clang's <arch>-linux target, the lld and objcopy
    # that come with Rust, a GNU-format ar with an ELF symbol index (v86/ar.py)
    # and the 64-bit division helpers libgcc would provide (v86/builtins.c)
    rust_bin="$(rustc --print sysroot)/lib/rustlib/$(rustc -vV | sed -n 's/^host: //p')/bin"
    mkdir -p tools
    ln -sf "$rust_bin/rust-lld" tools/ld.lld
    target="$arch-unknown-linux-gnu"
    # -no-pie here, not only in CFLAGS: clang links PIE by default for Linux
    # targets and some link rules don't pass CFLAGS
    cc="clang -target $target --ld-path=$out/tools/ld.lld -no-pie -Wno-unknown-warning-option -Wno-unused-command-line-argument -Wno-varargs -Wno-error=unused-function"
    [ -f config.mak ] || "$src/configure" --arch="$arch" --cc="$cc" --ld="$out/tools/ld.lld"
    # an archive, like libgcc: link rules add both the *.o prerequisites and libgcc
    clang -target "$target" -ffreestanding -fno-pic -O2 $flags -c "$src/v86/builtins.c" -o builtins.o
    python3 "$src/v86/ar.py" rcs libbuiltins.a builtins.o
    tools=(CC="$cc $flags" OBJCOPY="$rust_bin/rust-objcopy" AR="python3 $src/v86/ar.py" libgcc="$out/libbuiltins.a")
    # the object directories (lib/x86, ...): only `make all` creates them
    make "${tools[@]}" directories
    # realmode.c relies on gcc's `asm(".code16gcc")`; clang needs -m16 for
    # 16-bit code, so that object is built first with bits=16
    for test in "$@"
    do
        if [ "$test" = x86/realmode.flat ]
        then
            make "${tools[@]}" bits=16 x86/realmode.o
        fi
    done
    make "${tools[@]}" "$@"
else
    [ -f config.mak ] || "$src/configure" --arch="$arch"
    # the object directories (lib/x86, ...): only `make all` creates them, and
    # gcc does not create the directory of a dependency file (-MF)
    make CC="gcc $flags" directories
    make CC="gcc $flags" "$@"
fi
                                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/configure                                                           0000755 0000000 0000000 00000010773 00000000000 015657  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env bash

srcdir=$(cd "$(dirname "$0")"; pwd)
prefix=/usr/local
cc=gcc
cxx=g++
ld=ld
objcopy=objcopy
objdump=objdump
ar=ar
addr2line=addr2line
arch=`uname -m | sed -e 's/i.86/i386/;s/arm.*/arm/;s/ppc64.*/ppc64/'`
host=$arch
cross_prefix=
endian=""
pretty_print_stacks=yes
environ_default=yes
u32_long=

usage() {
    cat <<-EOF
	Usage: $0 [options]

	Options include:
	    --arch=ARCH            architecture to compile for ($arch)
	    --processor=PROCESSOR  processor to compile for ($arch)
	    --cross-prefix=PREFIX  cross compiler prefix
	    --cc=CC		   c compiler to use ($cc)
	    --cxx=CXX		   c++ compiler to use ($cxx)
	    --ld=LD		   ld linker to use ($ld)
	    --prefix=PREFIX        where to install things ($prefix)
	    --endian=ENDIAN        endianness to compile for (little or big, ppc64 only)
	    --[enable|disable]-pretty-print-stacks
	                           enable or disable pretty stack printing (enabled by default)
	    --[enable|disable]-default-environ
	                           enable or disable the generation of a default environ when
	                           no environ is provided by the user (enabled by default)
EOF
    exit 1
}

while [[ "$1" = -* ]]; do
    opt="$1"; shift
    arg=
    if [[ "$opt" = *=* ]]; then
	arg="${opt#*=}"
	opt="${opt%%=*}"
    fi
    case "$opt" in
	--prefix)
	    prefix="$arg"
	    ;;
        --arch)
	    arch="$arg"
	    ;;
        --processor)
	    processor="$arg"
	    ;;
	--cross-prefix)
	    cross_prefix="$arg"
	    ;;
	--endian)
	    endian="$arg"
	    ;;
	--cc)
	    cc="$arg"
	    ;;
	--cxx)
	    cxx="$arg"
	    ;;
	--ld)
	    ld="$arg"
	    ;;
	--enable-pretty-print-stacks)
	    pretty_print_stacks=yes
	    ;;
	--disable-pretty-print-stacks)
	    pretty_print_stacks=no
	    ;;
	--enable-default-environ)
	    environ_default=yes
	    ;;
	--disable-default-environ)
	    environ_default=no
	    ;;
	--help)
	    usage
	    ;;
	*)
	    usage
	    ;;
    esac
done

arch_name=$arch
[ "$arch" = "aarch64" ] && arch="arm64"
[ "$arch_name" = "arm64" ] && arch_name="aarch64"

[ -z "$processor" ] && processor="$arch"

if [ "$processor" = "arm64" ]; then
    processor="cortex-a57"
elif [ "$processor" = "arm" ]; then
    processor="cortex-a15"
fi

if [ "$arch" = "i386" ] || [ "$arch" = "x86_64" ]; then
    testdir=x86
elif [ "$arch" = "arm" ] || [ "$arch" = "arm64" ]; then
    testdir=arm
elif [ "$arch" = "ppc64" ]; then
    testdir=powerpc
    firmware="$testdir/boot_rom.bin"
    if [ "$endian" != "little" ] && [ "$endian" != "big" ]; then
        echo "You must provide endianness (big or little)!"
        usage
    fi
else
    testdir=$arch
fi
if [ ! -d "$srcdir/$testdir" ]; then
    echo "$testdir does not exist!"
    exit 1
fi
if [ -f "$srcdir/$testdir/run" ]; then
    ln -fs "$srcdir/$testdir/run" $testdir-run
fi

# check if uint32_t needs a long format modifier
cat << EOF > lib-test.c
__UINT32_TYPE__
EOF
u32_long=$($cross_prefix$cc -E lib-test.c | grep -v '^#' | grep -q long && echo yes)
rm -f lib-test.c

# api/: check for dependent 32 bit libraries and gnu++11 support
if [ "$testdir" = "x86" ]; then
    echo 'int main () {}' > lib-test.c
    $cc -m32 -o /dev/null -lstdc++ -lpthread -lrt lib-test.c &> /dev/null
    exit=$?
    $cxx -m32 -o /dev/null -std=gnu++11 lib-test.c &> /dev/null
    if [ $? -eq 0 -a $exit -eq 0 ]; then
        api=true
    fi
    rm -f lib-test.c
fi

# Are we in a separate build tree? If so, link the Makefile
# and shared stuff so that 'make' and run_tests.sh work.
if test ! -e Makefile; then
    echo "linking Makefile..."
    ln -s "$srcdir/Makefile" .

    echo "linking tests..."
    mkdir -p $testdir
    ln -sf "$srcdir/$testdir/run" $testdir/
    ln -sf "$srcdir/$testdir/unittests.cfg" $testdir/
    ln -sf "$srcdir/run_tests.sh"

    echo "linking scripts..."
    ln -sf "$srcdir/scripts"
fi

# link lib/asm for the architecture
rm -f lib/asm
asm=asm-generic
if [ -d "$srcdir/lib/$arch/asm" ]; then
	asm="$srcdir/lib/$arch/asm"
elif [ -d "$srcdir/lib/$testdir/asm" ]; then
	asm="$srcdir/lib/$testdir/asm"
fi
mkdir -p lib
ln -sf "$asm" lib/asm


# create the config
cat <<EOF > config.mak
SRCDIR=$srcdir
PREFIX=$prefix
HOST=$host
ARCH=$arch
ARCH_NAME=$arch_name
PROCESSOR=$processor
CC=$cross_prefix$cc
CXX=$cross_prefix$cxx
LD=$cross_prefix$ld
OBJCOPY=$cross_prefix$objcopy
OBJDUMP=$cross_prefix$objdump
AR=$cross_prefix$ar
ADDR2LINE=$cross_prefix$addr2line
API=$api
TEST_DIR=$testdir
FIRMWARE=$firmware
ENDIAN=$endian
PRETTY_PRINT_STACKS=$pretty_print_stacks
ENVIRON_DEFAULT=$environ_default
ERRATATXT=errata.txt
U32_LONG_FMT=$u32_long
EOF
     source/v64/tests/kvm-unit-tests/lib/abort.c                                                         0000644 0000000 0000000 00000001141 00000000000 015756  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

/*
 * When exit(code) is invoked, qemu will exit with ((code << 1) | 1),
 * leaving us 128 exit status codes. To avoid confusion with signal
 * status, we further limit exit codes to those resulting in qemu
 * exiting with a status < 128. We give abort() the highest (127),
 * leaving the lower status codes for unit tests.
 */
#define ABORT_EXIT_STATUS 63	/* 127 exit status from qemu */

void abort(void)
{
	exit(ABORT_EXIT_STATUS);
}
                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/lib/alloc.c                                                         0000644 0000000 0000000 00000007601 00000000000 015750  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "alloc.h"
#include "asm/spinlock.h"
#include "asm/io.h"

#define PHYS_ALLOC_NR_REGIONS	256

struct phys_alloc_region {
	phys_addr_t base;
	phys_addr_t size;
};

static struct phys_alloc_region regions[PHYS_ALLOC_NR_REGIONS];
static int nr_regions;

static struct spinlock lock;
static phys_addr_t base, top, align_min;

void phys_alloc_show(void)
{
	int i;

	spin_lock(&lock);
	printf("phys_alloc minimum alignment: %#" PRIx64 "\n",
		(u64)align_min);
	for (i = 0; i < nr_regions; ++i)
		printf("%016" PRIx64 "-%016" PRIx64 " [%s]\n",
			(u64)regions[i].base,
			(u64)(regions[i].base + regions[i].size - 1),
			"USED");
	printf("%016" PRIx64 "-%016" PRIx64 " [%s]\n",
		(u64)base, (u64)(top - 1), "FREE");
	spin_unlock(&lock);
}

void phys_alloc_init(phys_addr_t base_addr, phys_addr_t size)
{
	spin_lock(&lock);
	base = base_addr;
	top = base + size;
	align_min = DEFAULT_MINIMUM_ALIGNMENT;
	nr_regions = 0;
	spin_unlock(&lock);
}

void phys_alloc_set_minimum_alignment(phys_addr_t align)
{
	assert(align && !(align & (align - 1)));
	spin_lock(&lock);
	align_min = align;
	spin_unlock(&lock);
}

static phys_addr_t phys_alloc_aligned_safe(phys_addr_t size,
					   phys_addr_t align, bool safe)
{
	static bool warned = false;
	phys_addr_t addr, size_orig = size;
	u64 top_safe;

	spin_lock(&lock);

	top_safe = top;

	if (safe && sizeof(long) == 4)
		top_safe = MIN(top_safe, 1ULL << 32);

	align = MAX(align, align_min);

	addr = ALIGN(base, align);
	size += addr - base;

	if ((top_safe - base) < size) {
		printf("phys_alloc: requested=%#" PRIx64
		       " (align=%#" PRIx64 "), "
		       "need=%#" PRIx64 ", but free=%#" PRIx64 ". "
		       "top=%#" PRIx64 ", top_safe=%#" PRIx64 "\n",
		       (u64)size_orig, (u64)align, (u64)size, top_safe - base,
		       (u64)top, top_safe);
		spin_unlock(&lock);
		return INVALID_PHYS_ADDR;
	}

	base += size;

	if (nr_regions < PHYS_ALLOC_NR_REGIONS) {
		regions[nr_regions].base = addr;
		regions[nr_regions].size = size_orig;
		++nr_regions;
	} else if (!warned) {
		printf("WARNING: phys_alloc: No free log entries, "
		       "can no longer log allocations...\n");
		warned = true;
	}

	spin_unlock(&lock);

	return addr;
}

static phys_addr_t phys_zalloc_aligned_safe(phys_addr_t size,
					    phys_addr_t align, bool safe)
{
	phys_addr_t addr = phys_alloc_aligned_safe(size, align, safe);
	if (addr == INVALID_PHYS_ADDR)
		return addr;

	memset(phys_to_virt(addr), 0, size);
	return addr;
}

phys_addr_t phys_alloc_aligned(phys_addr_t size, phys_addr_t align)
{
	return phys_alloc_aligned_safe(size, align, false);
}

phys_addr_t phys_zalloc_aligned(phys_addr_t size, phys_addr_t align)
{
	return phys_zalloc_aligned_safe(size, align, false);
}

phys_addr_t phys_alloc(phys_addr_t size)
{
	return phys_alloc_aligned(size, align_min);
}

phys_addr_t phys_zalloc(phys_addr_t size)
{
	return phys_zalloc_aligned(size, align_min);
}

static void *early_malloc(size_t size)
{
	phys_addr_t addr = phys_alloc_aligned_safe(size, align_min, true);
	if (addr == INVALID_PHYS_ADDR)
		return NULL;

	return phys_to_virt(addr);
}

static void *early_calloc(size_t nmemb, size_t size)
{
	phys_addr_t addr = phys_zalloc_aligned_safe(nmemb * size,
						    align_min, true);
	if (addr == INVALID_PHYS_ADDR)
		return NULL;

	return phys_to_virt(addr);
}

static void early_free(void *ptr __unused)
{
}

static void *early_memalign(size_t alignment, size_t size)
{
	phys_addr_t addr;

	assert(alignment && !(alignment & (alignment - 1)));

	addr = phys_alloc_aligned_safe(size, alignment, true);
	if (addr == INVALID_PHYS_ADDR)
		return NULL;

	return phys_to_virt(addr);
}

static struct alloc_ops early_alloc_ops = {
	.malloc = early_malloc,
	.calloc = early_calloc,
	.free = early_free,
	.memalign = early_memalign,
};

struct alloc_ops *alloc_ops = &early_alloc_ops;
                                                                                                                               source/v64/tests/kvm-unit-tests/lib/alloc.h                                                         0000644 0000000 0000000 00000006666 00000000000 015767  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ALLOC_H_
#define _ALLOC_H_
/*
 * alloc supplies three ingredients to the test framework that are all
 * related to the support of dynamic memory allocation.
 *
 * The first is a set of alloc function wrappers for malloc and its
 * friends. Using wrappers allows test code and common code to use the
 * same interface for memory allocation at all stages, even though the
 * implementations may change with the stage, e.g. pre/post paging.
 *
 * The second is a set of implementations for the alloc function
 * interfaces. These implementations are named early_*, as they can be
 * used almost immediately by the test framework.
 *
 * The third is a very simple physical memory allocator, which the
 * early_* alloc functions build on.
 *
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

struct alloc_ops {
	void *(*malloc)(size_t size);
	void *(*calloc)(size_t nmemb, size_t size);
	void (*free)(void *ptr);
	void *(*memalign)(size_t alignment, size_t size);
};

/*
 * alloc_ops is initialized to early_alloc_ops
 */
extern struct alloc_ops *alloc_ops;

static inline void *malloc(size_t size)
{
	assert(alloc_ops && alloc_ops->malloc);
	return alloc_ops->malloc(size);
}

static inline void *calloc(size_t nmemb, size_t size)
{
	assert(alloc_ops && alloc_ops->calloc);
	return alloc_ops->calloc(nmemb, size);
}

static inline void free(void *ptr)
{
	assert(alloc_ops && alloc_ops->free);
	alloc_ops->free(ptr);
}

static inline void *memalign(size_t alignment, size_t size)
{
	assert(alloc_ops && alloc_ops->memalign);
	return alloc_ops->memalign(alignment, size);
}

/*
 * phys_alloc is a very simple allocator which allows physical memory
 * to be partitioned into regions until all memory is allocated.
 *
 * Note: This is such a simple allocator that there is no way to free
 * a region. For more complicated memory management a single region
 * can be allocated, but then have its memory managed by a more
 * sophisticated allocator, e.g. a page allocator.
 */
#define DEFAULT_MINIMUM_ALIGNMENT 32

/*
 * phys_alloc_init creates the initial free memory region of size @size
 * at @base. The minimum alignment is set to DEFAULT_MINIMUM_ALIGNMENT.
 */
extern void phys_alloc_init(phys_addr_t base, phys_addr_t size);

/*
 * phys_alloc_set_minimum_alignment sets the minimum alignment to
 * @align.
 */
extern void phys_alloc_set_minimum_alignment(phys_addr_t align);

/*
 * phys_alloc_aligned returns the base address of a region of size @size,
 * where the address is aligned to @align, or INVALID_PHYS_ADDR if there
 * isn't enough free memory to satisfy the request.
 */
extern phys_addr_t phys_alloc_aligned(phys_addr_t size, phys_addr_t align);

/*
 * phys_zalloc_aligned is like phys_alloc_aligned, but zeros the memory
 * before returning the address.
 */
extern phys_addr_t phys_zalloc_aligned(phys_addr_t size, phys_addr_t align);

/*
 * phys_alloc returns the base address of a region of size @size, or
 * INVALID_PHYS_ADDR if there isn't enough free memory to satisfy the
 * request.
 */
extern phys_addr_t phys_alloc(phys_addr_t size);

/*
 * phys_zalloc is like phys_alloc, but zeros the memory before returning.
 */
extern phys_addr_t phys_zalloc(phys_addr_t size);

/*
 * phys_alloc_show outputs all currently allocated regions with the
 * following format
 *   <start_addr>-<end_addr> [<USED|FREE>]
 */
extern void phys_alloc_show(void);

#endif /* _ALLOC_H_ */
                                                                          source/v64/tests/kvm-unit-tests/lib/argv.c                                                          0000644 0000000 0000000 00000004752 00000000000 015621  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Set up arguments for main() and prepare environment variables
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */

#include "libcflat.h"
#include "argv.h"
#include "auxinfo.h"

int __argc;
const char *__args;
char *__argv[100];
char *__environ[200];

char **environ = __environ;

static char args_copy[1000];
static char *copy_ptr = args_copy;

#define isblank(c) ((c) == ' ' || (c) == '\t')
#define isalpha(c) (((c) >= 'A' && (c) <= 'Z') || ((c) >= 'a' && (c) <= 'z') || (c) == '_')
#define isalnum(c) (isalpha(c) || ((c) >= '0' && (c) <= '9'))

static const char *skip_blanks(const char *p)
{
	while (isblank(*p))
		++p;
	return p;
}

void __setup_args(void)
{
	const char *args = __args;
	char **argv = __argv + __argc;

	while (*(args = skip_blanks(args)) != '\0') {
		*argv++ = copy_ptr;
		while (*args != '\0' && !isblank(*args))
			*copy_ptr++ = *args++;
		*copy_ptr++ = '\0';
	}
	__argc = argv - __argv;
}

static void setup_args(const char *args)
{
	if (!args)
		return;

	__args = args;
	__setup_args();
}

void setup_args_progname(const char *args)
{
	__argv[0] = copy_ptr;
	strcpy(__argv[0], auxinfo.progname);
	copy_ptr += strlen(auxinfo.progname) + 1;
	++__argc;
	setup_args(args);
}

static char *env_eol(char *env)
{
	while (*env && *env != '\n')
		++env;
	return env;
}

static char *env_invalid_eol(char *env)
{
	char *eol = env_eol(env);
	char eol_old = *eol;

	*eol = '\0';
	printf("Invalid environment variable: %s\n", env);
	*eol = eol_old;
	return eol;
}

static char *env_next(char *env)
{
	char *p;

	if (!*env)
		return env;

	if (isalpha(*env)) {
		bool invalid = false;

		p = env + 1;
		while (*p && *p != '=' && *p != '\n') {
			if (!isalnum(*p))
				invalid = true;
			++p;
		}

		if (*p != '=')
			invalid = true;

		if (invalid) {
			env = env_invalid_eol(env);
			return *env ? env_next(env + 1) : env;
		}
		return env;
	}

	p = env;
	while (isblank(*p))
		++p;

	if (*p == '\n')
		return env_next(p + 1);

	if (*p == '#')
		env = env_eol(env);
	else
		env = env_invalid_eol(env);

	return *env ? env_next(env + 1) : env;
}

void setup_env(char *env, int size)
{
	char *eof = env + size, *p = env;
	bool newline = false;
	int i = 0;

	while (*p)
		++p;
	if (p == eof)
		newline = true;

	while (env < eof) {
		if (newline)
			env = env_next(env);
		if (!*env || env >= eof)
			break;
		__environ[i++] = env;
		while (env < eof && *env && !(newline && *env == '\n'))
			++env;
		*env++ = '\0';
	}
}
                      source/v64/tests/kvm-unit-tests/lib/argv.h                                                          0000644 0000000 0000000 00000000533 00000000000 015617  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Set up arguments for main() and prepare environment variables
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */

extern void __setup_args(void);
extern void setup_args_progname(const char *args);
extern void setup_env(char *env, int size);
                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/asm-generic/atomic.h                                            0000644 0000000 0000000 00000001714 00000000000 020330  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __ASM_GENERIC_ATOMIC_H__
#define __ASM_GENERIC_ATOMIC_H__

/* From QEMU include/qemu/atomic.h */
#define atomic_fetch_inc(ptr)  __sync_fetch_and_add(ptr, 1)
#define atomic_fetch_dec(ptr)  __sync_fetch_and_add(ptr, -1)
#define atomic_fetch_add(ptr, n) __sync_fetch_and_add(ptr, n)
#define atomic_fetch_sub(ptr, n) __sync_fetch_and_sub(ptr, n)
#define atomic_fetch_and(ptr, n) __sync_fetch_and_and(ptr, n)
#define atomic_fetch_or(ptr, n) __sync_fetch_and_or(ptr, n)
#define atomic_fetch_xor(ptr, n) __sync_fetch_and_xor(ptr, n)

#define atomic_inc_fetch(ptr)  __sync_add_and_fetch(ptr, 1)
#define atomic_dec_fetch(ptr)  __sync_add_and_fetch(ptr, -1)
#define atomic_add_fetch(ptr, n) __sync_add_and_fetch(ptr, n)
#define atomic_sub_fetch(ptr, n) __sync_sub_and_fetch(ptr, n)
#define atomic_and_fetch(ptr, n) __sync_and_and_fetch(ptr, n)
#define atomic_or_fetch(ptr, n) __sync_or_and_fetch(ptr, n)
#define atomic_xor_fetch(ptr, n) __sync_xor_and_fetch(ptr, n)

#endif
                                                    source/v64/tests/kvm-unit-tests/lib/asm-generic/barrier.h                                           0000644 0000000 0000000 00000001221 00000000000 020473  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_BARRIER_H_
#define _ASM_BARRIER_H_
/*
 * asm-generic/barrier.h
 *
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */

#ifndef mb
#define mb()	asm volatile("":::"memory")
#endif
#ifndef rmb
#define rmb()	asm volatile("":::"memory")
#endif
#ifndef wmb
#define wmb()	asm volatile("":::"memory")
#endif

#ifndef smp_mb
#define smp_mb()	mb()
#endif
#ifndef smp_rmb
#define smp_rmb()	rmb()
#endif
#ifndef smp_wmb
#define smp_wmb()	wmb()
#endif

#ifndef cpu_relax
#define cpu_relax()	asm volatile ("":::"memory")
#endif

#endif /* _ASM_BARRIER_H_ */
                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/lib/asm-generic/io.h                                                0000644 0000000 0000000 00000011356 00000000000 017466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_GENERIC_IO_H_
#define _ASM_GENERIC_IO_H_
/*
 * asm-generic/io.h
 *  adapted from the Linux kernel's include/asm-generic/io.h
 *  and arch/arm/include/asm/io.h
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */
#include "libcflat.h"
#include "asm/page.h"
#include "asm/barrier.h"

#ifndef __raw_readb
static inline u8 __raw_readb(const volatile void *addr)
{
	return *(const volatile u8 *)addr;
}
#endif

#ifndef __raw_readw
static inline u16 __raw_readw(const volatile void *addr)
{
	return *(const volatile u16 *)addr;
}
#endif

#ifndef __raw_readl
static inline u32 __raw_readl(const volatile void *addr)
{
	return *(const volatile u32 *)addr;
}
#endif

#ifndef __raw_readq
static inline u64 __raw_readq(const volatile void *addr)
{
	assert(sizeof(unsigned long) == sizeof(u64));
	return *(const volatile u64 *)addr;
}
#endif

#ifndef __raw_writeb
static inline void __raw_writeb(u8 b, volatile void *addr)
{
	*(volatile u8 *)addr = b;
}
#endif

#ifndef __raw_writew
static inline void __raw_writew(u16 b, volatile void *addr)
{
	*(volatile u16 *)addr = b;
}
#endif

#ifndef __raw_writel
static inline void __raw_writel(u32 b, volatile void *addr)
{
	*(volatile u32 *)addr = b;
}
#endif

#ifndef __raw_writeq
static inline void __raw_writeq(u64 b, volatile void *addr)
{
	assert(sizeof(unsigned long) == sizeof(u64));
	*(volatile u64 *)addr = b;
}
#endif

#ifndef __bswap16
static inline u16 __bswap16(u16 x)
{
	return ((x >> 8) & 0xff) | ((x & 0xff) << 8);
}
#endif

#ifndef __bswap32
static inline u32 __bswap32(u32 x)
{
	return ((x & 0xff000000) >> 24) | ((x & 0x00ff0000) >>  8) |
	       ((x & 0x0000ff00) <<  8) | ((x & 0x000000ff) << 24);
}
#endif

#ifndef __bswap64
static inline u64 __bswap64(u64 x)
{
	return ((x & 0x00000000000000ffULL) << 56) |
	       ((x & 0x000000000000ff00ULL) << 40) |
	       ((x & 0x0000000000ff0000ULL) << 24) |
	       ((x & 0x00000000ff000000ULL) <<  8) |
	       ((x & 0x000000ff00000000ULL) >>  8) |
	       ((x & 0x0000ff0000000000ULL) >> 24) |
	       ((x & 0x00ff000000000000ULL) >> 40) |
	       ((x & 0xff00000000000000ULL) >> 56);
}
#endif

#ifndef __cpu_is_be
#define __cpu_is_be() (0)
#endif

#define le16_to_cpu(x) \
	({ u16 __r = __cpu_is_be() ? __bswap16(x) : ((u16)x); __r; })
#define cpu_to_le16 le16_to_cpu

#define le32_to_cpu(x) \
	({ u32 __r = __cpu_is_be() ? __bswap32(x) : ((u32)x); __r; })
#define cpu_to_le32 le32_to_cpu

#define le64_to_cpu(x) \
	({ u64 __r = __cpu_is_be() ? __bswap64(x) : ((u64)x); __r; })
#define cpu_to_le64 le64_to_cpu

#define be16_to_cpu(x) \
	({ u16 __r = !__cpu_is_be() ? __bswap16(x) : ((u16)x); __r; })
#define cpu_to_be16 be16_to_cpu

#define be32_to_cpu(x) \
	({ u32 __r = !__cpu_is_be() ? __bswap32(x) : ((u32)x); __r; })
#define cpu_to_be32 be32_to_cpu

#define be64_to_cpu(x) \
	({ u64 __r = !__cpu_is_be() ? __bswap64(x) : ((u64)x); __r; })
#define cpu_to_be64 be64_to_cpu

#define readb(addr) \
	({ u8 __r = __raw_readb(addr); rmb(); __r; })
#define readw(addr) \
	({ u16 __r = le16_to_cpu(__raw_readw(addr)); rmb(); __r; })
#define readl(addr) \
	({ u32 __r = le32_to_cpu(__raw_readl(addr)); rmb(); __r; })
#define readq(addr) \
	({ u64 __r = le64_to_cpu(__raw_readq(addr)); rmb(); __r; })

#define writeb(b, addr) \
	({ wmb(); __raw_writeb(b, addr); })
#define writew(b, addr) \
	({ wmb(); __raw_writew(cpu_to_le16(b), addr); })
#define writel(b, addr) \
	({ wmb(); __raw_writel(cpu_to_le32(b), addr); })
#define writeq(b, addr) \
	({ wmb(); __raw_writeq(cpu_to_le64(b), addr); })

#ifndef inb
static inline uint8_t inb(unsigned long port)
{
	return readb((const volatile void __iomem *)port);
}
#endif

#ifndef inw
static inline uint16_t inw(unsigned long port)
{
	return readw((const volatile void __iomem *)port);
}
#endif

#ifndef inl
static inline uint32_t inl(unsigned long port)
{
	return readl((const volatile void __iomem *)port);
}
#endif

#ifndef outb
static inline void outb(uint8_t value, unsigned long port)
{
	writeb(value, (volatile void __iomem *)port);
}
#endif

#ifndef outw
static inline void outw(uint16_t value, unsigned long port)
{
	writew(value, (volatile void __iomem *)port);
}
#endif

#ifndef outl
static inline void outl(uint32_t value, unsigned long port)
{
	writel(value, (volatile void __iomem *)port);
}
#endif

#ifndef ioremap
static inline void __iomem *ioremap(phys_addr_t phys_addr, size_t size __unused)
{
	assert(sizeof(long) == 8 || !(phys_addr >> 32));
	return (void __iomem *)(unsigned long)phys_addr;
}
#endif

#ifndef virt_to_phys
static inline unsigned long virt_to_phys(volatile void *address)
{
	return __pa((unsigned long)address);
}
#endif

#ifndef phys_to_virt
static inline void *phys_to_virt(unsigned long address)
{
	return __va(address);
}
#endif

#endif /* _ASM_GENERIC_IO_H_ */
                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/lib/asm-generic/page.h                                              0000644 0000000 0000000 00000001364 00000000000 017771  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_GENERIC_PAGE_H_
#define _ASM_GENERIC_PAGE_H_
/*
 * asm-generic/page.h
 *  adapted from the Linux kernel's include/asm-generic/page.h
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */

#include <linux/const.h>

#define PAGE_SHIFT		12
#define PAGE_SIZE		(_AC(1,UL) << PAGE_SHIFT)
#define PAGE_MASK		(~(PAGE_SIZE-1))

#ifndef __ASSEMBLY__

#define PAGE_ALIGN(addr)	ALIGN(addr, PAGE_SIZE)

#define __va(x)			((void *)((unsigned long) (x)))
#define __pa(x)			((unsigned long) (x))
#define virt_to_pfn(kaddr)	(__pa(kaddr) >> PAGE_SHIFT)
#define pfn_to_virt(pfn)	__va((pfn) << PAGE_SHIFT)

#endif /* !__ASSEMBLY__ */

#endif /* _ASM_GENERIC_PAGE_H_ */
                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/asm-generic/pci-host-bridge.h                                   0000644 0000000 0000000 00000001566 00000000000 022041  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_PCI_HOST_BRIDGE_H_
#define _ASM_PCI_HOST_BRIDGE_H_
/*
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

phys_addr_t pci_host_bridge_get_paddr(uint64_t addr);

static inline
phys_addr_t pci_translate_addr(pcidevaddr_t dev __unused, uint64_t addr)
{
	/*
	 * Assume we only have single PCI host bridge in a system.
	 */
	return pci_host_bridge_get_paddr(addr);
}

uint8_t pci_config_readb(pcidevaddr_t dev, uint8_t reg);
uint16_t pci_config_readw(pcidevaddr_t dev, uint8_t reg);
uint32_t pci_config_readl(pcidevaddr_t dev, uint8_t reg);
void pci_config_writeb(pcidevaddr_t dev, uint8_t reg, uint8_t val);
void pci_config_writew(pcidevaddr_t dev, uint8_t reg, uint16_t val);
void pci_config_writel(pcidevaddr_t dev, uint8_t reg, uint32_t val);

#endif
                                                                                                                                          source/v64/tests/kvm-unit-tests/lib/asm-generic/pci.h                                               0000644 0000000 0000000 00000000153 00000000000 017623  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_GENERIC_PCI_H_
#define _ASM_GENERIC_PCI_H_
#error need architecture specific asm/pci.h
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/asm-generic/spinlock.h                                          0000644 0000000 0000000 00000000470 00000000000 020674  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_GENERIC_SPINLOCK_H_
#define _ASM_GENERIC_SPINLOCK_H_

struct spinlock {
    unsigned int v;
};

static inline void spin_lock(struct spinlock *lock)
{
	while (__sync_lock_test_and_set(&lock->v, 1));
}

static inline void spin_unlock(struct spinlock *lock)
{
	__sync_lock_release(&lock->v);
}

#endif
                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/auxinfo.c                                                       0000644 0000000 0000000 00000000074 00000000000 016324  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "auxinfo.h"
struct auxinfo auxinfo = { PROGNAME };
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/lib/auxinfo.h                                                       0000644 0000000 0000000 00000000465 00000000000 016335  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */
#ifndef _AUXINFO_H_
#define _AUXINFO_H_
struct auxinfo {
	const char *progname;
};

/* No extern!  Define a common symbol.  */
struct auxinfo auxinfo;
#endif
                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/lib/bitops.h                                                        0000644 0000000 0000000 00000002007 00000000000 016156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _BITOPS_H_
#define _BITOPS_H_

/*
 * Adapted from
 *   include/linux/bitops.h
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */

#define BITS_PER_LONG_LONG	64
#define BIT(nr)			(1UL << (nr))
#define BIT_ULL(nr)		(1ULL << (nr))
#define BIT_MASK(nr)		(1UL << ((nr) % BITS_PER_LONG))
#define BIT_WORD(nr)		((nr) / BITS_PER_LONG)
#define BIT_ULL_MASK(nr)	(1ULL << ((nr) % BITS_PER_LONG_LONG))
#define BIT_ULL_WORD(nr)	((nr) / BITS_PER_LONG_LONG)
#define BITS_PER_BYTE		8
#define BITS_TO_LONGS(nr)	DIV_ROUND_UP(nr, BITS_PER_BYTE * sizeof(long))

#include <asm/bitops.h>

/*
 * Create a contiguous bitmask starting at bit position @l and ending at
 * position @h. For example
 * GENMASK_ULL(39, 21) gives us the 64bit vector 0x000000ffffe00000.
 */
#define GENMASK(h, l) \
	(((~0UL) << (l)) & (~0UL >> (BITS_PER_LONG - 1 - (h))))

#define GENMASK_ULL(h, l) \
	(((~0ULL) << (l)) & (~0ULL >> (BITS_PER_LONG_LONG - 1 - (h))))

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/lib/chr-testdev.c                                                   0000644 0000000 0000000 00000002420 00000000000 017100  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"
#include "virtio.h"
#include "asm/spinlock.h"

#define TESTDEV_NAME "chr-testdev"

static struct virtio_device *vcon;
static struct virtqueue *in_vq, *out_vq;
static struct spinlock lock;

static void __testdev_send(char *buf, unsigned int len)
{
	int ret;

	ret = virtqueue_add_outbuf(out_vq, buf, len);
	virtqueue_kick(out_vq);

	if (ret < 0)
		return;

	while (!virtqueue_get_buf(out_vq, &len))
		;
}

void chr_testdev_exit(int code)
{
	unsigned int len;
	char buf[8];

	snprintf(buf, sizeof(buf), "%dq", code);
	len = strlen(buf);

	spin_lock(&lock);

	if (!vcon)
		goto out;

	__testdev_send(buf, len);

out:
	spin_unlock(&lock);
}

void chr_testdev_init(void)
{
	const char *io_names[] = { "input", "output" };
	struct virtqueue *vqs[2];
	int ret;

	vcon = virtio_bind(VIRTIO_ID_CONSOLE);
	if (vcon == NULL) {
		printf("%s: %s: can't find a virtio-console\n",
				__func__, TESTDEV_NAME);
		return;
	}

	ret = vcon->config->find_vqs(vcon, 2, vqs, NULL, io_names);
	if (ret < 0) {
		printf("%s: %s: can't init virtqueues\n",
				__func__, TESTDEV_NAME);
		vcon = NULL;
		return;
	}

	in_vq = vqs[0];
	out_vq = vqs[1];
}
                                                                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/lib/chr-testdev.h                                                   0000644 0000000 0000000 00000000727 00000000000 017115  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _CHR_TESTDEV_H_
#define _CHR_TESTDEV_H_
/*
 * chr-testdev is a driver for the chr-testdev qemu backend.
 * The chr-testdev backend exposes a simple control interface to
 * qemu for kvm-unit-tests accessible through virtio-console.
 *
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
extern void chr_testdev_init(void);
extern void chr_testdev_exit(int code);
#endif
                                         source/v64/tests/kvm-unit-tests/lib/devicetree.c                                                    0000644 0000000 0000000 00000015323 00000000000 016775  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"
#include "libfdt/libfdt.h"
#include "devicetree.h"

static const void *fdt;

const void *dt_fdt(void)
{
	return fdt;
}

bool dt_available(void)
{
	return fdt_check_header(fdt) == 0;
}

int dt_get_nr_cells(int fdtnode, u32 *nr_address_cells, u32 *nr_size_cells)
{
	const struct fdt_property *prop;
	u32 *nr_cells;
	int len, nac, nsc;

	prop = fdt_get_property(fdt, fdtnode, "#address-cells", &len);
	if (prop == NULL)
		return len;

	nr_cells = (u32 *)prop->data;
	nac = fdt32_to_cpu(*nr_cells);

	prop = fdt_get_property(fdt, fdtnode, "#size-cells", &len);
	if (prop == NULL)
		return len;

	nr_cells = (u32 *)prop->data;
	nsc = fdt32_to_cpu(*nr_cells);

	*nr_address_cells = nac;
	*nr_size_cells = nsc;

	return 0;
}

void dt_reg_init(struct dt_reg *reg, u32 nr_address_cells, u32 nr_size_cells)
{
	memset(reg, 0, sizeof(struct dt_reg));
	reg->nr_address_cells = nr_address_cells;
	reg->nr_size_cells = nr_size_cells;
}

int dt_get_reg(int fdtnode, int regidx, struct dt_reg *reg)
{
	const struct fdt_property *prop;
	u32 *cells, i;
	unsigned nr_tuple_cells;
	int len;

	prop = fdt_get_property(fdt, fdtnode, "reg", &len);
	if (prop == NULL)
		return len;

	cells = (u32 *)prop->data;
	nr_tuple_cells = reg->nr_address_cells + reg->nr_size_cells;
	regidx *= nr_tuple_cells;

	if (regidx + nr_tuple_cells > len/sizeof(u32))
		return -FDT_ERR_NOTFOUND;

	for (i = 0; i < reg->nr_address_cells; ++i)
		reg->address_cells[i] = fdt32_to_cpu(cells[regidx + i]);

	regidx += reg->nr_address_cells;
	for (i = 0; i < reg->nr_size_cells; ++i)
		reg->size_cells[i] = fdt32_to_cpu(cells[regidx + i]);

	return 0;
}

int dt_pbus_translate_node(int fdtnode, int regidx,
			   struct dt_pbus_reg *pbus_reg)
{
	struct dt_reg raw_reg;
	u32 nac, nsc;
	int parent, ret;

	parent = fdt_parent_offset(fdt, fdtnode);
	if (parent < 0)
		return parent;

	ret = dt_get_nr_cells(parent, &nac, &nsc);
	if (ret != 0)
		return ret;

	dt_reg_init(&raw_reg, nac, nsc);

	ret = dt_get_reg(fdtnode, regidx, &raw_reg);
	if (ret < 0)
		return ret;

	pbus_reg->addr = dt_pbus_read_cells(raw_reg.nr_address_cells,
					    raw_reg.address_cells);
	pbus_reg->size = dt_pbus_read_cells(raw_reg.nr_size_cells,
					    raw_reg.size_cells);

	return 0;
}

int dt_pbus_translate(const struct dt_device *dev, int regidx,
		      void *reg)
{
	return dt_pbus_translate_node(dev->fdtnode, regidx, reg);
}

int dt_bus_match_any(const struct dt_device *dev __unused, int fdtnode)
{
	/* matches any device with a valid node */
	return fdtnode < 0 ? fdtnode : 1;
}

static const struct dt_bus dt_default_bus = {
	.match = dt_bus_match_any,
	.translate = dt_pbus_translate,
};

void dt_bus_init_defaults(struct dt_bus *bus)
{
	memcpy(bus, &dt_default_bus, sizeof(struct dt_bus));
}

void dt_device_init(struct dt_device *dev, const struct dt_bus *bus,
		    void *info)
{
	memset(dev, 0, sizeof(struct dt_device));
	dev->bus = bus;
	dev->info = info;
}

int dt_device_find_compatible(const struct dt_device *dev,
			      const char *compatible)
{
	int node, ret;

	node = fdt_node_offset_by_compatible(fdt, -1, compatible);
	while (node >= 0) {
		ret = dev->bus->match(dev, node);
		if (ret < 0)
			return ret;
		else if (ret)
			break;
		node = fdt_node_offset_by_compatible(fdt, node, compatible);
	}
	return node;
}

int dt_pbus_get_base_compatible(const char *compatible,
				struct dt_pbus_reg *base)
{
	struct dt_device dev;
	int node;

	dt_device_init(&dev, &dt_default_bus, NULL);

	node = dt_device_find_compatible(&dev, compatible);
	if (node < 0)
		return node;

	dt_device_bind_node(&dev, node);

	return dt_pbus_get_base(&dev, base);
}

int dt_get_memory_params(struct dt_pbus_reg *regs, int nr_regs)
{
	const char *pn = "device_type", *pv = "memory";
	int node, ret, reg_idx, pl = strlen(pv) + 1, nr = 0;
	struct dt_pbus_reg reg;

	node = fdt_node_offset_by_prop_value(fdt, -1, pn, pv, pl);

	while (node >= 0) {

		reg_idx = 0;

		while (nr < nr_regs) {
			ret = dt_pbus_translate_node(node, reg_idx, &reg);
			if (ret == -FDT_ERR_NOTFOUND)
				break;
			if (ret < 0)
				return ret;
			regs[nr].addr = reg.addr;
			regs[nr].size = reg.size;
			++nr, ++reg_idx;
		}

		node = fdt_node_offset_by_prop_value(fdt, node, pn, pv, pl);
	}

	return node != -FDT_ERR_NOTFOUND ? node : nr;
}

int dt_for_each_cpu_node(void (*func)(int fdtnode, u64 regval, void *info),
			 void *info)
{
	const struct fdt_property *prop;
	int cpus, cpu, ret, len;
	struct dt_reg raw_reg;
	u32 nac, nsc;
	u64 regval;

	cpus = fdt_path_offset(fdt, "/cpus");
	if (cpus < 0)
		return cpus;

	ret = dt_get_nr_cells(cpus, &nac, &nsc);
	if (ret < 0)
		return ret;

	dt_reg_init(&raw_reg, nac, nsc);

	dt_for_each_subnode(cpus, cpu) {

		prop = fdt_get_property(fdt, cpu, "device_type", &len);
		if (prop == NULL)
			return len;

		if (len != 4 || strcmp((char *)prop->data, "cpu"))
			continue;

		ret = dt_get_reg(cpu, 0, &raw_reg);
		if (ret < 0)
			return ret;

		regval = raw_reg.address_cells[0];
		if (nac == 2)
			regval = (regval << 32) | raw_reg.address_cells[1];

		func(cpu, regval, info);
	}

	return 0;
}

int dt_get_bootargs(const char **bootargs)
{
	const struct fdt_property *prop;
	int node, len;

	*bootargs = NULL;

	node = fdt_path_offset(fdt, "/chosen");
	if (node < 0)
		return node;

	prop = fdt_get_property(fdt, node, "bootargs", &len);
	if (!prop)
		return len;

	*bootargs = prop->data;
	return 0;
}

int dt_get_default_console_node(void)
{
	const struct fdt_property *prop;
	int node, len;

	node = fdt_path_offset(fdt, "/chosen");
	if (node < 0)
		return node;

	prop = fdt_get_property(fdt, node, "stdout-path", &len);
	if (!prop) {
		prop = fdt_get_property(fdt, node, "linux,stdout-path", &len);
		if (!prop)
			return len;
	}

	return fdt_path_offset(fdt, prop->data);
}

int dt_get_initrd(const char **initrd, u32 *size)
{
	const struct fdt_property *prop;
	const char *start, *end;
	int node, len;
	u32 *data;

	*initrd = NULL;
	*size = 0;

	node = fdt_path_offset(fdt, "/chosen");
	if (node < 0)
		return node;

	prop = fdt_get_property(fdt, node, "linux,initrd-start", &len);
	if (!prop)
		return len;
	data = (u32 *)prop->data;
	start = (const char *)(unsigned long)fdt32_to_cpu(*data);

	prop = fdt_get_property(fdt, node, "linux,initrd-end", &len);
	if (!prop) {
		assert(len != -FDT_ERR_NOTFOUND);
		return len;
	}
	data = (u32 *)prop->data;
	end = (const char *)(unsigned long)fdt32_to_cpu(*data);

	*initrd = start;
	*size = (unsigned long)end - (unsigned long)start;

	return 0;
}

int dt_init(const void *fdt_ptr)
{
	int ret;

	ret = fdt_check_header(fdt_ptr);
	if (ret < 0)
		return ret;

	/* Sanity check the path.  */
	ret = fdt_path_offset(fdt_ptr, "/");
	if (ret < 0)
		return ret;

	fdt = fdt_ptr;
	return 0;
}
                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/lib/devicetree.h                                                    0000644 0000000 0000000 00000016645 00000000000 017012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _DEVICETREE_H_
#define _DEVICETREE_H_
/*
 * devicetree builds on libfdt to implement abstractions and accessors
 * for Linux required device tree content. The accessors provided are
 * common across architectures. See section III of the kernel doc
 * Documentation/devicetree/booting-without-of.txt
 *
 * Copyright (C) 2014, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"
#include "libfdt/libfdt.h"

/**********************************************************************
 * devicetree init and libfdt helpers
 **********************************************************************/

/* dt_init initializes devicetree with a pointer to an fdt, @fdt_ptr */
extern int dt_init(const void *fdt_ptr);

/* get the fdt pointer that devicetree is using */
extern const void *dt_fdt(void);

/* check for an initialized, valid devicetree */
extern bool dt_available(void);

/* traverse child nodes */
#define dt_for_each_subnode(n, s)					\
	for (s = fdt_first_subnode(dt_fdt(), n);			\
	     s != -FDT_ERR_NOTFOUND;					\
	     s = fdt_next_subnode(dt_fdt(), s))

/**********************************************************************
 * Abstractions for required node types and properties
 **********************************************************************/

struct dt_device {
	int fdtnode;
	const struct dt_bus *bus;

	/*
	 * info is a pointer to device specific data, which may be
	 * used by the bus match() and translate() functions
	 */
	void *info;
};

struct dt_bus {
	/*
	 * match a device @dev to an fdt node @fdtnode
	 * returns
	 *  - a positive value on match
	 *  - zero on no match
	 *  - a negative FDT_ERR_* value on failure
	 */
	int (*match)(const struct dt_device *dev, int fdtnode);

	/*
	 * translate the @regidx'th "address size" tuple of
	 * @dev's fdt node's "reg" property, and store the result
	 * in @reg, a bus specific structure
	 * returns
	 *  - zero on success
	 *  - a negative FDT_ERR_* value on failure
	 */
	int (*translate)(const struct dt_device *dev, int regidx, void *reg);
};

/* dt_bus_match_any matches any fdt node, i.e. it always returns true */
extern int dt_bus_match_any(const struct dt_device *dev, int fdtnode);

/* the processor bus (pbus) address type and register tuple */
typedef u64 dt_pbus_addr_t;
struct dt_pbus_reg {
	dt_pbus_addr_t addr;
	dt_pbus_addr_t size;
};

static inline dt_pbus_addr_t dt_pbus_read_cells(u32 nr_cells, u32 *cells)
{
	switch (nr_cells) {
	case 1: return cells[0];
	case 2: return ((u64)cells[0] << 32) | cells[1];
	}
	return (~0ULL);
}

/*
 * dt_pbus_translate translates device node regs for the
 * processor bus using the parent node's #address-cells
 * and #size-cells and dt_pbus_read_cells()
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_pbus_translate(const struct dt_device *dev, int regidx,
			     void *reg);

/*
 * dt_pbus_translate_node is the same as dt_pbus_translate but
 * operates on an fdt node instead of a dt_device
 */
extern int dt_pbus_translate_node(int fdtnode, int regidx,
				  struct dt_pbus_reg *reg);

/*
 * dt_pbus_get_base is an alias for
 *     dt_pbus_translate(dev, 0, base)
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
static inline int dt_pbus_get_base(const struct dt_device *dev,
				   struct dt_pbus_reg *base)
{
	return dt_pbus_translate(dev, 0, base);
}

/*
 * dt_bus_init_defaults initializes @bus with
 *  match		<- dt_bus_match_any
 *  translate		<- dt_pbus_translate
 */
extern void dt_bus_init_defaults(struct dt_bus *bus);

/*
 * dt_device_init initializes a dt_device with the given parameters
 */
extern void dt_device_init(struct dt_device *dev, const struct dt_bus *bus,
			   void *info);

static inline void dt_device_bind_node(struct dt_device *dev, int fdtnode)
{
	dev->fdtnode = fdtnode;
}

/*
 * dt_device_find_compatible finds a @compatible node
 * returns
 *  - node (>= 0) on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_device_find_compatible(const struct dt_device *dev,
				     const char *compatible);

/*
 * dt_pbus_get_base_compatible simply bundles many functions into one.
 * It finds the first @compatible fdt node, then translates the 0th reg
 * tuple (the base) using the processor bus translation, and finally it
 * stores that result in @base.
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_pbus_get_base_compatible(const char *compatible,
				       struct dt_pbus_reg *base);

/**********************************************************************
 * Low-level accessors for required node types and properties
 **********************************************************************/

/*
 * dt_get_nr_cells sets @nr_address_cells and @nr_size_cells to the
 * #address-cells and #size-cells properties of @fdtnode
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_get_nr_cells(int fdtnode, u32 *nr_address_cells,
					u32 *nr_size_cells);

/* dt_reg is a structure for "raw" reg tuples */
#define MAX_ADDRESS_CELLS	4
#define MAX_SIZE_CELLS		4
struct dt_reg {
	u32 nr_address_cells, nr_size_cells;
	u32 address_cells[MAX_ADDRESS_CELLS];
	u32 size_cells[MAX_SIZE_CELLS];
};

/*
 * dt_reg_init initialize a dt_reg struct to zero and sets
 * nr_address_cells and nr_size_cells to @nr_address_cells and
 * @nr_size_cells respectively.
 */
extern void dt_reg_init(struct dt_reg *reg, u32 nr_address_cells,
					    u32 nr_size_cells);

/*
 * dt_get_reg gets the @regidx'th reg tuple of @fdtnode's reg property
 * and stores it in @reg. @reg must be initialized.
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_get_reg(int fdtnode, int regidx, struct dt_reg *reg);

/**********************************************************************
 * High-level accessors for required node types and properties
 **********************************************************************/

/*
 * dt_get_bootargs gets the string pointer from /chosen/bootargs
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure, and @bootargs
 *    will be set to NULL
 */
extern int dt_get_bootargs(const char **bootargs);

/*
 * dt_get_default_console_node gets the node of the path stored in
 * /chosen/stdout-path (or the deprecated /chosen/linux,stdout-path)
 * returns
 *  - the node (>= 0) on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_get_default_console_node(void);

/*
 * dt_get_initrd gets the physical address of the initrd and its
 * size from /chosen
 * returns
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure, and @initrd will be
 *    set to NULL and @size set to zero
 */
extern int dt_get_initrd(const char **initrd, u32 *size);

/*
 * dt_get_memory_params gets the memory parameters from the /memory node(s)
 * storing each memory region ("address size" tuple) in consecutive entries
 * of @regs, up to @nr_regs
 * returns
 *  - number of memory regions found on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_get_memory_params(struct dt_pbus_reg *regs, int nr_regs);

/*
 * dt_for_each_cpu_node runs @func on each cpu node in the /cpus node
 * passing it its fdt node, its reg property value, and @info
 *  - zero on success
 *  - a negative FDT_ERR_* value on failure
 */
extern int dt_for_each_cpu_node(void (*func)(int fdtnode, u64 regval,
				void *info), void *info);

#endif /* _DEVICETREE_H_ */
                                                                                           source/v64/tests/kvm-unit-tests/lib/errata.h                                                        0000644 0000000 0000000 00000001646 00000000000 016144  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * errata functions
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */
#ifndef _ERRATA_H_
#define _ERRATA_H_

#define _ERRATA(erratum) errata("ERRATA_" # erratum)
#define ERRATA(erratum) _ERRATA(erratum)

#define _ERRATA_RELAXED(erratum) errata_relaxed("ERRATA_" # erratum)
#define ERRATA_RELAXED(erratum) _ERRATA_RELAXED(erratum)

static inline bool errata_force(void)
{
	char *s = getenv("ERRATA_FORCE");

	return s && (*s == '1' || *s == 'y' || *s == 'Y');
}

static inline bool errata(const char *erratum)
{
	char *s;

	if (errata_force())
		return true;

	s = getenv(erratum);

	return s && (*s == '1' || *s == 'y' || *s == 'Y');
}

static inline bool errata_relaxed(const char *erratum)
{
	char *s;

	if (errata_force())
		return true;

	s = getenv(erratum);

	return !(s && (*s == '0' || *s == 'n' || *s == 'N'));
}

#endif
                                                                                          source/v64/tests/kvm-unit-tests/lib/kbuild.h                                                        0000644 0000000 0000000 00000000432 00000000000 016130  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _KBUILD_H_
#define _KBUILD_H_
#define DEFINE(sym, val) \
	asm volatile("\n->" #sym " %0 " #val : : "i" (val))
#define OFFSET(sym, str, mem)	DEFINE(sym, offsetof(struct str, mem))
#define COMMENT(x)		asm volatile("\n->#" x)
#define BLANK()			asm volatile("\n->" : : )
#endif
                                                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/lib/libcflat.h                                                      0000644 0000000 0000000 00000011170 00000000000 016437  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2, as
 * published by the Free Software Foundation.
 *
 * 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, write to the Free Software
 * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * Copyright IBM Corp. 2008
 *
 * Authors: Hollis Blanchard <hollisb@us.ibm.com>
 */

#ifndef __LIBCFLAT_H
#define __LIBCFLAT_H

#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>

#define __unused __attribute__((__unused__))

#define xstr(s...) xxstr(s)
#define xxstr(s...) #s

#define __ALIGN_MASK(x, mask)	(((x) + (mask)) & ~(mask))
#define __ALIGN(x, a)		__ALIGN_MASK(x, (typeof(x))(a) - 1)
#define ALIGN(x, a)		__ALIGN((x), (a))
#define IS_ALIGNED(x, a)	(((x) & ((typeof(x))(a) - 1)) == 0)

#define SZ_4K			(1 << 12)
#define SZ_64K			(1 << 16)
#define SZ_2M			(1 << 21)
#define SZ_1G			(1 << 30)

#define MIN(a, b)		((a) < (b) ? (a) : (b))
#define MAX(a, b)		((a) > (b) ? (a) : (b))

typedef uint8_t		u8;
typedef int8_t		s8;
typedef uint16_t	u16;
typedef int16_t		s16;
typedef uint32_t	u32;
typedef int32_t		s32;
typedef uint64_t	u64;
typedef int64_t		s64;
typedef unsigned long	ulong;

typedef _Bool		bool;
#define false 0
#define true  1

#if __SIZEOF_LONG__ == 8
#  define __PRI32_PREFIX
#  define __PRI64_PREFIX	"l"
#  define __PRIPTR_PREFIX	"l"
#else
#if defined(__U32_LONG_FMT__)
#  define __PRI32_PREFIX        "l"
#else
#  define __PRI32_PREFIX
#endif
#  define __PRI64_PREFIX	"ll"
#  define __PRIPTR_PREFIX
#endif
#define PRId32  __PRI32_PREFIX	"d"
#define PRIu32  __PRI32_PREFIX	"u"
#define PRIx32  __PRI32_PREFIX	"x"
#define PRId64  __PRI64_PREFIX	"d"
#define PRIu64  __PRI64_PREFIX	"u"
#define PRIx64  __PRI64_PREFIX	"x"
#define PRIxPTR __PRIPTR_PREFIX	"x"

typedef u64			phys_addr_t;
#define INVALID_PHYS_ADDR	(~(phys_addr_t)0)

extern void puts(const char *s);
extern void exit(int code);
extern void abort(void);
extern long atol(const char *ptr);
extern char *getenv(const char *name);

extern int printf(const char *fmt, ...)
					__attribute__((format(printf, 1, 2)));
extern int snprintf(char *buf, int size, const char *fmt, ...)
					__attribute__((format(printf, 3, 4)));
extern int vsnprintf(char *buf, int size, const char *fmt, va_list va)
					__attribute__((format(printf, 3, 0)));
extern int vprintf(const char *fmt, va_list va)
					__attribute__((format(printf, 1, 0)));

void report_prefix_pushf(const char *prefix_fmt, ...)
					__attribute__((format(printf, 1, 2)));
extern void report_prefix_push(const char *prefix);
extern void report_prefix_pop(void);
extern void report(const char *msg_fmt, bool pass, ...)
					__attribute__((format(printf, 1, 3)));
extern void report_xfail(const char *msg_fmt, bool xfail, bool pass, ...)
					__attribute__((format(printf, 1, 4)));
extern void report_abort(const char *msg_fmt, ...)
					__attribute__((format(printf, 1, 2)));
extern void report_skip(const char *msg_fmt, ...)
					__attribute__((format(printf, 1, 2)));
extern void report_info(const char *msg_fmt, ...)
					__attribute__((format(printf, 1, 2)));
extern void report_pass(void);
extern int report_summary(void);

bool simple_glob(const char *text, const char *pattern);

extern void dump_stack(void);
extern void dump_frame_stack(const void *instruction, const void *frame);

#define ARRAY_SIZE(_a) (sizeof(_a)/sizeof((_a)[0]))

#define container_of(ptr, type, member) ({				\
	const typeof( ((type *)0)->member ) *__mptr = (ptr);		\
	(type *)( (char *)__mptr - offsetof(type,member) );})

#define assert(cond)							\
do {									\
	if (!(cond)) {							\
		printf("%s:%d: assert failed: %s\n",			\
		       __FILE__, __LINE__, #cond);			\
		dump_stack();						\
		abort();						\
	}								\
} while (0)

#define assert_msg(cond, fmt, args...)					\
do {									\
	if (!(cond)) {							\
		printf("%s:%d: assert failed: %s: " fmt "\n",		\
		       __FILE__, __LINE__, #cond, ## args);		\
		dump_stack();						\
		abort();						\
	}								\
} while (0)

static inline bool is_power_of_2(unsigned long n)
{
	return n && !(n & (n - 1));
}

/*
 * One byte per bit, a ' between each group of 4 bits, and a null terminator.
 */
#define BINSTR_SZ (sizeof(unsigned long) * 8 + sizeof(unsigned long) * 2)
void binstr(unsigned long x, char out[BINSTR_SZ]);
void print_binstr(unsigned long x);

#endif
                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/libfdt/Makefile.libfdt                                          0000644 0000000 0000000 00000000612 00000000000 020654  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # Makefile.libfdt
#
# This is not a complete Makefile of itself.  Instead, it is designed to
# be easily embeddable into other systems of Makefiles.
#
LIBFDT_soname = libfdt.$(SHAREDLIB_EXT).1
LIBFDT_INCLUDES = fdt.h libfdt.h libfdt_env.h
LIBFDT_VERSION = version.lds
LIBFDT_SRCS = fdt.c fdt_ro.c fdt_wip.c fdt_sw.c fdt_rw.c fdt_strerror.c fdt_empty_tree.c
LIBFDT_OBJS = $(LIBFDT_SRCS:%.c=%.o)
                                                                                                                      source/v64/tests/kvm-unit-tests/lib/libfdt/README                                                   0000644 0000000 0000000 00000000205 00000000000 016627  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
The code in this directory is originally imported from the libfdt
directory of git://git.jdl.com/software/dtc.git - version 1.4.0.

                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/lib/libfdt/fdt.c                                                    0000644 0000000 0000000 00000014562 00000000000 016703  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

int fdt_check_header(const void *fdt)
{
	if (fdt_magic(fdt) == FDT_MAGIC) {
		/* Complete tree */
		if (fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION)
			return -FDT_ERR_BADVERSION;
		if (fdt_last_comp_version(fdt) > FDT_LAST_SUPPORTED_VERSION)
			return -FDT_ERR_BADVERSION;
	} else if (fdt_magic(fdt) == FDT_SW_MAGIC) {
		/* Unfinished sequential-write blob */
		if (fdt_size_dt_struct(fdt) == 0)
			return -FDT_ERR_BADSTATE;
	} else {
		return -FDT_ERR_BADMAGIC;
	}

	return 0;
}

const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)
{
	const char *p;

	if (fdt_version(fdt) >= 0x11)
		if (((offset + len) < offset)
		    || ((offset + len) > fdt_size_dt_struct(fdt)))
			return NULL;

	p = _fdt_offset_ptr(fdt, offset);

	if (p + len < p)
		return NULL;
	return p;
}

uint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)
{
	const fdt32_t *tagp, *lenp;
	uint32_t tag;
	int offset = startoffset;
	const char *p;

	*nextoffset = -FDT_ERR_TRUNCATED;
	tagp = fdt_offset_ptr(fdt, offset, FDT_TAGSIZE);
	if (!tagp)
		return FDT_END; /* premature end */
	tag = fdt32_to_cpu(*tagp);
	offset += FDT_TAGSIZE;

	*nextoffset = -FDT_ERR_BADSTRUCTURE;
	switch (tag) {
	case FDT_BEGIN_NODE:
		/* skip name */
		do {
			p = fdt_offset_ptr(fdt, offset++, 1);
		} while (p && (*p != '\0'));
		if (!p)
			return FDT_END; /* premature end */
		break;

	case FDT_PROP:
		lenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));
		if (!lenp)
			return FDT_END; /* premature end */
		/* skip-name offset, length and value */
		offset += sizeof(struct fdt_property) - FDT_TAGSIZE
			+ fdt32_to_cpu(*lenp);
		break;

	case FDT_END:
	case FDT_END_NODE:
	case FDT_NOP:
		break;

	default:
		return FDT_END;
	}

	if (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))
		return FDT_END; /* premature end */

	*nextoffset = FDT_TAGALIGN(offset);
	return tag;
}

int _fdt_check_node_offset(const void *fdt, int offset)
{
	if ((offset < 0) || (offset % FDT_TAGSIZE)
	    || (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE))
		return -FDT_ERR_BADOFFSET;

	return offset;
}

int _fdt_check_prop_offset(const void *fdt, int offset)
{
	if ((offset < 0) || (offset % FDT_TAGSIZE)
	    || (fdt_next_tag(fdt, offset, &offset) != FDT_PROP))
		return -FDT_ERR_BADOFFSET;

	return offset;
}

int fdt_next_node(const void *fdt, int offset, int *depth)
{
	int nextoffset = 0;
	uint32_t tag;

	if (offset >= 0)
		if ((nextoffset = _fdt_check_node_offset(fdt, offset)) < 0)
			return nextoffset;

	do {
		offset = nextoffset;
		tag = fdt_next_tag(fdt, offset, &nextoffset);

		switch (tag) {
		case FDT_PROP:
		case FDT_NOP:
			break;

		case FDT_BEGIN_NODE:
			if (depth)
				(*depth)++;
			break;

		case FDT_END_NODE:
			if (depth && ((--(*depth)) < 0))
				return nextoffset;
			break;

		case FDT_END:
			if ((nextoffset >= 0)
			    || ((nextoffset == -FDT_ERR_TRUNCATED) && !depth))
				return -FDT_ERR_NOTFOUND;
			else
				return nextoffset;
		}
	} while (tag != FDT_BEGIN_NODE);

	return offset;
}

int fdt_first_subnode(const void *fdt, int offset)
{
	int depth = 0;

	offset = fdt_next_node(fdt, offset, &depth);
	if (offset < 0 || depth != 1)
		return -FDT_ERR_NOTFOUND;

	return offset;
}

int fdt_next_subnode(const void *fdt, int offset)
{
	int depth = 1;

	/*
	 * With respect to the parent, the depth of the next subnode will be
	 * the same as the last.
	 */
	do {
		offset = fdt_next_node(fdt, offset, &depth);
		if (offset < 0 || depth < 1)
			return -FDT_ERR_NOTFOUND;
	} while (depth > 1);

	return offset;
}

const char *_fdt_find_string(const char *strtab, int tabsize, const char *s)
{
	int len = strlen(s) + 1;
	const char *last = strtab + tabsize - len;
	const char *p;

	for (p = strtab; p <= last; p++)
		if (memcmp(p, s, len) == 0)
			return p;
	return NULL;
}

int fdt_move(const void *fdt, void *buf, int bufsize)
{
	FDT_CHECK_HEADER(fdt);

	if (fdt_totalsize(fdt) > bufsize)
		return -FDT_ERR_NOSPACE;

	memmove(buf, fdt, fdt_totalsize(fdt));
	return 0;
}
                                                                                                                                              source/v64/tests/kvm-unit-tests/lib/libfdt/fdt.h                                                    0000644 0000000 0000000 00000007666 00000000000 016717  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _FDT_H
#define _FDT_H
/*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 * Copyright 2012 Kim Phillips, Freescale Semiconductor.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef __ASSEMBLY__

struct fdt_header {
	fdt32_t magic;			 /* magic word FDT_MAGIC */
	fdt32_t totalsize;		 /* total size of DT block */
	fdt32_t off_dt_struct;		 /* offset to structure */
	fdt32_t off_dt_strings;		 /* offset to strings */
	fdt32_t off_mem_rsvmap;		 /* offset to memory reserve map */
	fdt32_t version;		 /* format version */
	fdt32_t last_comp_version;	 /* last compatible version */

	/* version 2 fields below */
	fdt32_t boot_cpuid_phys;	 /* Which physical CPU id we're
					    booting on */
	/* version 3 fields below */
	fdt32_t size_dt_strings;	 /* size of the strings block */

	/* version 17 fields below */
	fdt32_t size_dt_struct;		 /* size of the structure block */
};

struct fdt_reserve_entry {
	fdt64_t address;
	fdt64_t size;
};

struct fdt_node_header {
	fdt32_t tag;
	char name[0];
};

struct fdt_property {
	fdt32_t tag;
	fdt32_t len;
	fdt32_t nameoff;
	char data[0];
};

#endif /* !__ASSEMBLY */

#define FDT_MAGIC	0xd00dfeed	/* 4: version, 4: total size */
#define FDT_TAGSIZE	sizeof(fdt32_t)

#define FDT_BEGIN_NODE	0x1		/* Start node: full name */
#define FDT_END_NODE	0x2		/* End node */
#define FDT_PROP	0x3		/* Property: name off,
					   size, content */
#define FDT_NOP		0x4		/* nop */
#define FDT_END		0x9

#define FDT_V1_SIZE	(7*sizeof(fdt32_t))
#define FDT_V2_SIZE	(FDT_V1_SIZE + sizeof(fdt32_t))
#define FDT_V3_SIZE	(FDT_V2_SIZE + sizeof(fdt32_t))
#define FDT_V16_SIZE	FDT_V3_SIZE
#define FDT_V17_SIZE	(FDT_V16_SIZE + sizeof(fdt32_t))

#endif /* _FDT_H */
                                                                          source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_empty_tree.c                                         0000644 0000000 0000000 00000005527 00000000000 021141  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2012 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

int fdt_create_empty_tree(void *buf, int bufsize)
{
	int err;

	err = fdt_create(buf, bufsize);
	if (err)
		return err;

	err = fdt_finish_reservemap(buf);
	if (err)
		return err;

	err = fdt_begin_node(buf, "");
	if (err)
		return err;

	err =  fdt_end_node(buf);
	if (err)
		return err;

	err = fdt_finish(buf);
	if (err)
		return err;

	return fdt_open_into(buf, buf, bufsize);
}

                                                                                                                                                                         source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_ro.c                                                 0000644 0000000 0000000 00000033303 00000000000 017375  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

static int _fdt_nodename_eq(const void *fdt, int offset,
			    const char *s, int len)
{
	const char *p = fdt_offset_ptr(fdt, offset + FDT_TAGSIZE, len+1);

	if (! p)
		/* short match */
		return 0;

	if (memcmp(p, s, len) != 0)
		return 0;

	if (p[len] == '\0')
		return 1;
	else if (!memchr(s, '@', len) && (p[len] == '@'))
		return 1;
	else
		return 0;
}

const char *fdt_string(const void *fdt, int stroffset)
{
	return (const char *)fdt + fdt_off_dt_strings(fdt) + stroffset;
}

static int _fdt_string_eq(const void *fdt, int stroffset,
			  const char *s, int len)
{
	const char *p = fdt_string(fdt, stroffset);

	return (strlen(p) == len) && (memcmp(p, s, len) == 0);
}

int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size)
{
	FDT_CHECK_HEADER(fdt);
	*address = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->address);
	*size = fdt64_to_cpu(_fdt_mem_rsv(fdt, n)->size);
	return 0;
}

int fdt_num_mem_rsv(const void *fdt)
{
	int i = 0;

	while (fdt64_to_cpu(_fdt_mem_rsv(fdt, i)->size) != 0)
		i++;
	return i;
}

static int _nextprop(const void *fdt, int offset)
{
	uint32_t tag;
	int nextoffset;

	do {
		tag = fdt_next_tag(fdt, offset, &nextoffset);

		switch (tag) {
		case FDT_END:
			if (nextoffset >= 0)
				return -FDT_ERR_BADSTRUCTURE;
			else
				return nextoffset;

		case FDT_PROP:
			return offset;
		}
		offset = nextoffset;
	} while (tag == FDT_NOP);

	return -FDT_ERR_NOTFOUND;
}

int fdt_subnode_offset_namelen(const void *fdt, int offset,
			       const char *name, int namelen)
{
	int depth;

	FDT_CHECK_HEADER(fdt);

	for (depth = 0;
	     (offset >= 0) && (depth >= 0);
	     offset = fdt_next_node(fdt, offset, &depth))
		if ((depth == 1)
		    && _fdt_nodename_eq(fdt, offset, name, namelen))
			return offset;

	if (depth < 0)
		return -FDT_ERR_NOTFOUND;
	return offset; /* error */
}

int fdt_subnode_offset(const void *fdt, int parentoffset,
		       const char *name)
{
	return fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name));
}

int fdt_path_offset(const void *fdt, const char *path)
{
	const char *end = path + strlen(path);
	const char *p = path;
	int offset = 0;

	FDT_CHECK_HEADER(fdt);

	/* see if we have an alias */
	if (*path != '/') {
		const char *q = strchr(path, '/');

		if (!q)
			q = end;

		p = fdt_get_alias_namelen(fdt, p, q - p);
		if (!p)
			return -FDT_ERR_BADPATH;
		offset = fdt_path_offset(fdt, p);

		p = q;
	}

	while (*p) {
		const char *q;

		while (*p == '/')
			p++;
		if (! *p)
			return offset;
		q = strchr(p, '/');
		if (! q)
			q = end;

		offset = fdt_subnode_offset_namelen(fdt, offset, p, q-p);
		if (offset < 0)
			return offset;

		p = q;
	}

	return offset;
}

const char *fdt_get_name(const void *fdt, int nodeoffset, int *len)
{
	const struct fdt_node_header *nh = _fdt_offset_ptr(fdt, nodeoffset);
	int err;

	if (((err = fdt_check_header(fdt)) != 0)
	    || ((err = _fdt_check_node_offset(fdt, nodeoffset)) < 0))
			goto fail;

	if (len)
		*len = strlen(nh->name);

	return nh->name;

 fail:
	if (len)
		*len = err;
	return NULL;
}

int fdt_first_property_offset(const void *fdt, int nodeoffset)
{
	int offset;

	if ((offset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
		return offset;

	return _nextprop(fdt, offset);
}

int fdt_next_property_offset(const void *fdt, int offset)
{
	if ((offset = _fdt_check_prop_offset(fdt, offset)) < 0)
		return offset;

	return _nextprop(fdt, offset);
}

const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
						      int offset,
						      int *lenp)
{
	int err;
	const struct fdt_property *prop;

	if ((err = _fdt_check_prop_offset(fdt, offset)) < 0) {
		if (lenp)
			*lenp = err;
		return NULL;
	}

	prop = _fdt_offset_ptr(fdt, offset);

	if (lenp)
		*lenp = fdt32_to_cpu(prop->len);

	return prop;
}

const struct fdt_property *fdt_get_property_namelen(const void *fdt,
						    int offset,
						    const char *name,
						    int namelen, int *lenp)
{
	for (offset = fdt_first_property_offset(fdt, offset);
	     (offset >= 0);
	     (offset = fdt_next_property_offset(fdt, offset))) {
		const struct fdt_property *prop;

		if (!(prop = fdt_get_property_by_offset(fdt, offset, lenp))) {
			offset = -FDT_ERR_INTERNAL;
			break;
		}
		if (_fdt_string_eq(fdt, fdt32_to_cpu(prop->nameoff),
				   name, namelen))
			return prop;
	}

	if (lenp)
		*lenp = offset;
	return NULL;
}

const struct fdt_property *fdt_get_property(const void *fdt,
					    int nodeoffset,
					    const char *name, int *lenp)
{
	return fdt_get_property_namelen(fdt, nodeoffset, name,
					strlen(name), lenp);
}

const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
				const char *name, int namelen, int *lenp)
{
	const struct fdt_property *prop;

	prop = fdt_get_property_namelen(fdt, nodeoffset, name, namelen, lenp);
	if (! prop)
		return NULL;

	return prop->data;
}

const void *fdt_getprop_by_offset(const void *fdt, int offset,
				  const char **namep, int *lenp)
{
	const struct fdt_property *prop;

	prop = fdt_get_property_by_offset(fdt, offset, lenp);
	if (!prop)
		return NULL;
	if (namep)
		*namep = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
	return prop->data;
}

const void *fdt_getprop(const void *fdt, int nodeoffset,
			const char *name, int *lenp)
{
	return fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);
}

uint32_t fdt_get_phandle(const void *fdt, int nodeoffset)
{
	const fdt32_t *php;
	int len;

	/* FIXME: This is a bit sub-optimal, since we potentially scan
	 * over all the properties twice. */
	php = fdt_getprop(fdt, nodeoffset, "phandle", &len);
	if (!php || (len != sizeof(*php))) {
		php = fdt_getprop(fdt, nodeoffset, "linux,phandle", &len);
		if (!php || (len != sizeof(*php)))
			return 0;
	}

	return fdt32_to_cpu(*php);
}

const char *fdt_get_alias_namelen(const void *fdt,
				  const char *name, int namelen)
{
	int aliasoffset;

	aliasoffset = fdt_path_offset(fdt, "/aliases");
	if (aliasoffset < 0)
		return NULL;

	return fdt_getprop_namelen(fdt, aliasoffset, name, namelen, NULL);
}

const char *fdt_get_alias(const void *fdt, const char *name)
{
	return fdt_get_alias_namelen(fdt, name, strlen(name));
}

int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)
{
	int pdepth = 0, p = 0;
	int offset, depth, namelen;
	const char *name;

	FDT_CHECK_HEADER(fdt);

	if (buflen < 2)
		return -FDT_ERR_NOSPACE;

	for (offset = 0, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		while (pdepth > depth) {
			do {
				p--;
			} while (buf[p-1] != '/');
			pdepth--;
		}

		if (pdepth >= depth) {
			name = fdt_get_name(fdt, offset, &namelen);
			if (!name)
				return namelen;
			if ((p + namelen + 1) <= buflen) {
				memcpy(buf + p, name, namelen);
				p += namelen;
				buf[p++] = '/';
				pdepth++;
			}
		}

		if (offset == nodeoffset) {
			if (pdepth < (depth + 1))
				return -FDT_ERR_NOSPACE;

			if (p > 1) /* special case so that root path is "/", not "" */
				p--;
			buf[p] = '\0';
			return 0;
		}
	}

	if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
		return -FDT_ERR_BADOFFSET;
	else if (offset == -FDT_ERR_BADOFFSET)
		return -FDT_ERR_BADSTRUCTURE;

	return offset; /* error from fdt_next_node() */
}

int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
				 int supernodedepth, int *nodedepth)
{
	int offset, depth;
	int supernodeoffset = -FDT_ERR_INTERNAL;

	FDT_CHECK_HEADER(fdt);

	if (supernodedepth < 0)
		return -FDT_ERR_NOTFOUND;

	for (offset = 0, depth = 0;
	     (offset >= 0) && (offset <= nodeoffset);
	     offset = fdt_next_node(fdt, offset, &depth)) {
		if (depth == supernodedepth)
			supernodeoffset = offset;

		if (offset == nodeoffset) {
			if (nodedepth)
				*nodedepth = depth;

			if (supernodedepth > depth)
				return -FDT_ERR_NOTFOUND;
			else
				return supernodeoffset;
		}
	}

	if ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))
		return -FDT_ERR_BADOFFSET;
	else if (offset == -FDT_ERR_BADOFFSET)
		return -FDT_ERR_BADSTRUCTURE;

	return offset; /* error from fdt_next_node() */
}

int fdt_node_depth(const void *fdt, int nodeoffset)
{
	int nodedepth;
	int err;

	err = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);
	if (err)
		return (err < 0) ? err : -FDT_ERR_INTERNAL;
	return nodedepth;
}

int fdt_parent_offset(const void *fdt, int nodeoffset)
{
	int nodedepth = fdt_node_depth(fdt, nodeoffset);

	if (nodedepth < 0)
		return nodedepth;
	return fdt_supernode_atdepth_offset(fdt, nodeoffset,
					    nodedepth - 1, NULL);
}

int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
				  const char *propname,
				  const void *propval, int proplen)
{
	int offset;
	const void *val;
	int len;

	FDT_CHECK_HEADER(fdt);

	/* FIXME: The algorithm here is pretty horrible: we scan each
	 * property of a node in fdt_getprop(), then if that didn't
	 * find what we want, we scan over them again making our way
	 * to the next node.  Still it's the easiest to implement
	 * approach; performance can come later. */
	for (offset = fdt_next_node(fdt, startoffset, NULL);
	     offset >= 0;
	     offset = fdt_next_node(fdt, offset, NULL)) {
		val = fdt_getprop(fdt, offset, propname, &len);
		if (val && (len == proplen)
		    && (memcmp(val, propval, len) == 0))
			return offset;
	}

	return offset; /* error from fdt_next_node() */
}

int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle)
{
	int offset;

	if ((phandle == 0) || (phandle == -1))
		return -FDT_ERR_BADPHANDLE;

	FDT_CHECK_HEADER(fdt);

	/* FIXME: The algorithm here is pretty horrible: we
	 * potentially scan each property of a node in
	 * fdt_get_phandle(), then if that didn't find what
	 * we want, we scan over them again making our way to the next
	 * node.  Still it's the easiest to implement approach;
	 * performance can come later. */
	for (offset = fdt_next_node(fdt, -1, NULL);
	     offset >= 0;
	     offset = fdt_next_node(fdt, offset, NULL)) {
		if (fdt_get_phandle(fdt, offset) == phandle)
			return offset;
	}

	return offset; /* error from fdt_next_node() */
}

int fdt_stringlist_contains(const char *strlist, int listlen, const char *str)
{
	int len = strlen(str);
	const char *p;

	while (listlen >= len) {
		if (memcmp(str, strlist, len+1) == 0)
			return 1;
		p = memchr(strlist, '\0', listlen);
		if (!p)
			return 0; /* malformed strlist.. */
		listlen -= (p-strlist) + 1;
		strlist = p + 1;
	}
	return 0;
}

int fdt_node_check_compatible(const void *fdt, int nodeoffset,
			      const char *compatible)
{
	const void *prop;
	int len;

	prop = fdt_getprop(fdt, nodeoffset, "compatible", &len);
	if (!prop)
		return len;
	if (fdt_stringlist_contains(prop, len, compatible))
		return 0;
	else
		return 1;
}

int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
				  const char *compatible)
{
	int offset, err;

	FDT_CHECK_HEADER(fdt);

	/* FIXME: The algorithm here is pretty horrible: we scan each
	 * property of a node in fdt_node_check_compatible(), then if
	 * that didn't find what we want, we scan over them again
	 * making our way to the next node.  Still it's the easiest to
	 * implement approach; performance can come later. */
	for (offset = fdt_next_node(fdt, startoffset, NULL);
	     offset >= 0;
	     offset = fdt_next_node(fdt, offset, NULL)) {
		err = fdt_node_check_compatible(fdt, offset, compatible);
		if ((err < 0) && (err != -FDT_ERR_NOTFOUND))
			return err;
		else if (err == 0)
			return offset;
	}

	return offset; /* error from fdt_next_node() */
}
                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_rw.c                                                 0000644 0000000 0000000 00000031247 00000000000 017412  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

static int _fdt_blocks_misordered(const void *fdt,
			      int mem_rsv_size, int struct_size)
{
	return (fdt_off_mem_rsvmap(fdt) < FDT_ALIGN(sizeof(struct fdt_header), 8))
		|| (fdt_off_dt_struct(fdt) <
		    (fdt_off_mem_rsvmap(fdt) + mem_rsv_size))
		|| (fdt_off_dt_strings(fdt) <
		    (fdt_off_dt_struct(fdt) + struct_size))
		|| (fdt_totalsize(fdt) <
		    (fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt)));
}

static int _fdt_rw_check_header(void *fdt)
{
	FDT_CHECK_HEADER(fdt);

	if (fdt_version(fdt) < 17)
		return -FDT_ERR_BADVERSION;
	if (_fdt_blocks_misordered(fdt, sizeof(struct fdt_reserve_entry),
				   fdt_size_dt_struct(fdt)))
		return -FDT_ERR_BADLAYOUT;
	if (fdt_version(fdt) > 17)
		fdt_set_version(fdt, 17);

	return 0;
}

#define FDT_RW_CHECK_HEADER(fdt) \
	{ \
		int err; \
		if ((err = _fdt_rw_check_header(fdt)) != 0) \
			return err; \
	}

static inline int _fdt_data_size(void *fdt)
{
	return fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
}

static int _fdt_splice(void *fdt, void *splicepoint, int oldlen, int newlen)
{
	char *p = splicepoint;
	char *end = (char *)fdt + _fdt_data_size(fdt);

	if (((p + oldlen) < p) || ((p + oldlen) > end))
		return -FDT_ERR_BADOFFSET;
	if ((end - oldlen + newlen) > ((char *)fdt + fdt_totalsize(fdt)))
		return -FDT_ERR_NOSPACE;
	memmove(p + newlen, p + oldlen, end - p - oldlen);
	return 0;
}

static int _fdt_splice_mem_rsv(void *fdt, struct fdt_reserve_entry *p,
			       int oldn, int newn)
{
	int delta = (newn - oldn) * sizeof(*p);
	int err;
	err = _fdt_splice(fdt, p, oldn * sizeof(*p), newn * sizeof(*p));
	if (err)
		return err;
	fdt_set_off_dt_struct(fdt, fdt_off_dt_struct(fdt) + delta);
	fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
	return 0;
}

static int _fdt_splice_struct(void *fdt, void *p,
			      int oldlen, int newlen)
{
	int delta = newlen - oldlen;
	int err;

	if ((err = _fdt_splice(fdt, p, oldlen, newlen)))
		return err;

	fdt_set_size_dt_struct(fdt, fdt_size_dt_struct(fdt) + delta);
	fdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);
	return 0;
}

static int _fdt_splice_string(void *fdt, int newlen)
{
	void *p = (char *)fdt
		+ fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);
	int err;

	if ((err = _fdt_splice(fdt, p, 0, newlen)))
		return err;

	fdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) + newlen);
	return 0;
}

static int _fdt_find_add_string(void *fdt, const char *s)
{
	char *strtab = (char *)fdt + fdt_off_dt_strings(fdt);
	const char *p;
	char *new;
	int len = strlen(s) + 1;
	int err;

	p = _fdt_find_string(strtab, fdt_size_dt_strings(fdt), s);
	if (p)
		/* found it */
		return (p - strtab);

	new = strtab + fdt_size_dt_strings(fdt);
	err = _fdt_splice_string(fdt, len);
	if (err)
		return err;

	memcpy(new, s, len);
	return (new - strtab);
}

int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size)
{
	struct fdt_reserve_entry *re;
	int err;

	FDT_RW_CHECK_HEADER(fdt);

	re = _fdt_mem_rsv_w(fdt, fdt_num_mem_rsv(fdt));
	err = _fdt_splice_mem_rsv(fdt, re, 0, 1);
	if (err)
		return err;

	re->address = cpu_to_fdt64(address);
	re->size = cpu_to_fdt64(size);
	return 0;
}

int fdt_del_mem_rsv(void *fdt, int n)
{
	struct fdt_reserve_entry *re = _fdt_mem_rsv_w(fdt, n);
	int err;

	FDT_RW_CHECK_HEADER(fdt);

	if (n >= fdt_num_mem_rsv(fdt))
		return -FDT_ERR_NOTFOUND;

	err = _fdt_splice_mem_rsv(fdt, re, 1, 0);
	if (err)
		return err;
	return 0;
}

static int _fdt_resize_property(void *fdt, int nodeoffset, const char *name,
				int len, struct fdt_property **prop)
{
	int oldlen;
	int err;

	*prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
	if (! (*prop))
		return oldlen;

	if ((err = _fdt_splice_struct(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),
				      FDT_TAGALIGN(len))))
		return err;

	(*prop)->len = cpu_to_fdt32(len);
	return 0;
}

static int _fdt_add_property(void *fdt, int nodeoffset, const char *name,
			     int len, struct fdt_property **prop)
{
	int proplen;
	int nextoffset;
	int namestroff;
	int err;

	if ((nextoffset = _fdt_check_node_offset(fdt, nodeoffset)) < 0)
		return nextoffset;

	namestroff = _fdt_find_add_string(fdt, name);
	if (namestroff < 0)
		return namestroff;

	*prop = _fdt_offset_ptr_w(fdt, nextoffset);
	proplen = sizeof(**prop) + FDT_TAGALIGN(len);

	err = _fdt_splice_struct(fdt, *prop, 0, proplen);
	if (err)
		return err;

	(*prop)->tag = cpu_to_fdt32(FDT_PROP);
	(*prop)->nameoff = cpu_to_fdt32(namestroff);
	(*prop)->len = cpu_to_fdt32(len);
	return 0;
}

int fdt_set_name(void *fdt, int nodeoffset, const char *name)
{
	char *namep;
	int oldlen, newlen;
	int err;

	FDT_RW_CHECK_HEADER(fdt);

	namep = (char *)(uintptr_t)fdt_get_name(fdt, nodeoffset, &oldlen);
	if (!namep)
		return oldlen;

	newlen = strlen(name);

	err = _fdt_splice_struct(fdt, namep, FDT_TAGALIGN(oldlen+1),
				 FDT_TAGALIGN(newlen+1));
	if (err)
		return err;

	memcpy(namep, name, newlen+1);
	return 0;
}

int fdt_setprop(void *fdt, int nodeoffset, const char *name,
		const void *val, int len)
{
	struct fdt_property *prop;
	int err;

	FDT_RW_CHECK_HEADER(fdt);

	err = _fdt_resize_property(fdt, nodeoffset, name, len, &prop);
	if (err == -FDT_ERR_NOTFOUND)
		err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
	if (err)
		return err;

	memcpy(prop->data, val, len);
	return 0;
}

int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
		   const void *val, int len)
{
	struct fdt_property *prop;
	int err, oldlen, newlen;

	FDT_RW_CHECK_HEADER(fdt);

	prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);
	if (prop) {
		newlen = len + oldlen;
		err = _fdt_splice_struct(fdt, prop->data,
					 FDT_TAGALIGN(oldlen),
					 FDT_TAGALIGN(newlen));
		if (err)
			return err;
		prop->len = cpu_to_fdt32(newlen);
		memcpy(prop->data + oldlen, val, len);
	} else {
		err = _fdt_add_property(fdt, nodeoffset, name, len, &prop);
		if (err)
			return err;
		memcpy(prop->data, val, len);
	}
	return 0;
}

int fdt_delprop(void *fdt, int nodeoffset, const char *name)
{
	struct fdt_property *prop;
	int len, proplen;

	FDT_RW_CHECK_HEADER(fdt);

	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
	if (! prop)
		return len;

	proplen = sizeof(*prop) + FDT_TAGALIGN(len);
	return _fdt_splice_struct(fdt, prop, proplen, 0);
}

int fdt_add_subnode_namelen(void *fdt, int parentoffset,
			    const char *name, int namelen)
{
	struct fdt_node_header *nh;
	int offset, nextoffset;
	int nodelen;
	int err;
	uint32_t tag;
	fdt32_t *endtag;

	FDT_RW_CHECK_HEADER(fdt);

	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
	if (offset >= 0)
		return -FDT_ERR_EXISTS;
	else if (offset != -FDT_ERR_NOTFOUND)
		return offset;

	/* Try to place the new node after the parent's properties */
	fdt_next_tag(fdt, parentoffset, &nextoffset); /* skip the BEGIN_NODE */
	do {
		offset = nextoffset;
		tag = fdt_next_tag(fdt, offset, &nextoffset);
	} while ((tag == FDT_PROP) || (tag == FDT_NOP));

	nh = _fdt_offset_ptr_w(fdt, offset);
	nodelen = sizeof(*nh) + FDT_TAGALIGN(namelen+1) + FDT_TAGSIZE;

	err = _fdt_splice_struct(fdt, nh, 0, nodelen);
	if (err)
		return err;

	nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
	memset(nh->name, 0, FDT_TAGALIGN(namelen+1));
	memcpy(nh->name, name, namelen);
	endtag = (fdt32_t *)((char *)nh + nodelen - FDT_TAGSIZE);
	*endtag = cpu_to_fdt32(FDT_END_NODE);

	return offset;
}

int fdt_add_subnode(void *fdt, int parentoffset, const char *name)
{
	return fdt_add_subnode_namelen(fdt, parentoffset, name, strlen(name));
}

int fdt_del_node(void *fdt, int nodeoffset)
{
	int endoffset;

	FDT_RW_CHECK_HEADER(fdt);

	endoffset = _fdt_node_end_offset(fdt, nodeoffset);
	if (endoffset < 0)
		return endoffset;

	return _fdt_splice_struct(fdt, _fdt_offset_ptr_w(fdt, nodeoffset),
				  endoffset - nodeoffset, 0);
}

static void _fdt_packblocks(const char *old, char *new,
			    int mem_rsv_size, int struct_size)
{
	int mem_rsv_off, struct_off, strings_off;

	mem_rsv_off = FDT_ALIGN(sizeof(struct fdt_header), 8);
	struct_off = mem_rsv_off + mem_rsv_size;
	strings_off = struct_off + struct_size;

	memmove(new + mem_rsv_off, old + fdt_off_mem_rsvmap(old), mem_rsv_size);
	fdt_set_off_mem_rsvmap(new, mem_rsv_off);

	memmove(new + struct_off, old + fdt_off_dt_struct(old), struct_size);
	fdt_set_off_dt_struct(new, struct_off);
	fdt_set_size_dt_struct(new, struct_size);

	memmove(new + strings_off, old + fdt_off_dt_strings(old),
		fdt_size_dt_strings(old));
	fdt_set_off_dt_strings(new, strings_off);
	fdt_set_size_dt_strings(new, fdt_size_dt_strings(old));
}

int fdt_open_into(const void *fdt, void *buf, int bufsize)
{
	int err;
	int mem_rsv_size, struct_size;
	int newsize;
	const char *fdtstart = fdt;
	const char *fdtend = fdtstart + fdt_totalsize(fdt);
	char *tmp;

	FDT_CHECK_HEADER(fdt);

	mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
		* sizeof(struct fdt_reserve_entry);

	if (fdt_version(fdt) >= 17) {
		struct_size = fdt_size_dt_struct(fdt);
	} else {
		struct_size = 0;
		while (fdt_next_tag(fdt, struct_size, &struct_size) != FDT_END)
			;
		if (struct_size < 0)
			return struct_size;
	}

	if (!_fdt_blocks_misordered(fdt, mem_rsv_size, struct_size)) {
		/* no further work necessary */
		err = fdt_move(fdt, buf, bufsize);
		if (err)
			return err;
		fdt_set_version(buf, 17);
		fdt_set_size_dt_struct(buf, struct_size);
		fdt_set_totalsize(buf, bufsize);
		return 0;
	}

	/* Need to reorder */
	newsize = FDT_ALIGN(sizeof(struct fdt_header), 8) + mem_rsv_size
		+ struct_size + fdt_size_dt_strings(fdt);

	if (bufsize < newsize)
		return -FDT_ERR_NOSPACE;

	/* First attempt to build converted tree at beginning of buffer */
	tmp = buf;
	/* But if that overlaps with the old tree... */
	if (((tmp + newsize) > fdtstart) && (tmp < fdtend)) {
		/* Try right after the old tree instead */
		tmp = (char *)(uintptr_t)fdtend;
		if ((tmp + newsize) > ((char *)buf + bufsize))
			return -FDT_ERR_NOSPACE;
	}

	_fdt_packblocks(fdt, tmp, mem_rsv_size, struct_size);
	memmove(buf, tmp, newsize);

	fdt_set_magic(buf, FDT_MAGIC);
	fdt_set_totalsize(buf, bufsize);
	fdt_set_version(buf, 17);
	fdt_set_last_comp_version(buf, 16);
	fdt_set_boot_cpuid_phys(buf, fdt_boot_cpuid_phys(fdt));

	return 0;
}

int fdt_pack(void *fdt)
{
	int mem_rsv_size;

	FDT_RW_CHECK_HEADER(fdt);

	mem_rsv_size = (fdt_num_mem_rsv(fdt)+1)
		* sizeof(struct fdt_reserve_entry);
	_fdt_packblocks(fdt, fdt, mem_rsv_size, fdt_size_dt_struct(fdt));
	fdt_set_totalsize(fdt, _fdt_data_size(fdt));

	return 0;
}
                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_strerror.c                                           0000644 0000000 0000000 00000006511 00000000000 020640  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

struct fdt_errtabent {
	const char *str;
};

#define FDT_ERRTABENT(val) \
	[(val)] = { .str = #val, }

static struct fdt_errtabent fdt_errtable[] = {
	FDT_ERRTABENT(FDT_ERR_NOTFOUND),
	FDT_ERRTABENT(FDT_ERR_EXISTS),
	FDT_ERRTABENT(FDT_ERR_NOSPACE),

	FDT_ERRTABENT(FDT_ERR_BADOFFSET),
	FDT_ERRTABENT(FDT_ERR_BADPATH),
	FDT_ERRTABENT(FDT_ERR_BADSTATE),

	FDT_ERRTABENT(FDT_ERR_TRUNCATED),
	FDT_ERRTABENT(FDT_ERR_BADMAGIC),
	FDT_ERRTABENT(FDT_ERR_BADVERSION),
	FDT_ERRTABENT(FDT_ERR_BADSTRUCTURE),
	FDT_ERRTABENT(FDT_ERR_BADLAYOUT),
};
#define FDT_ERRTABSIZE	(sizeof(fdt_errtable) / sizeof(fdt_errtable[0]))

const char *fdt_strerror(int errval)
{
	if (errval > 0)
		return "<valid offset/length>";
	else if (errval == 0)
		return "<no error>";
	else if (errval > -FDT_ERRTABSIZE) {
		const char *s = fdt_errtable[-errval].str;

		if (s)
			return s;
	}

	return "<unknown error>";
}
                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_sw.c                                                 0000644 0000000 0000000 00000015756 00000000000 017422  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

static int _fdt_sw_check_header(void *fdt)
{
	if (fdt_magic(fdt) != FDT_SW_MAGIC)
		return -FDT_ERR_BADMAGIC;
	/* FIXME: should check more details about the header state */
	return 0;
}

#define FDT_SW_CHECK_HEADER(fdt) \
	{ \
		int err; \
		if ((err = _fdt_sw_check_header(fdt)) != 0) \
			return err; \
	}

static void *_fdt_grab_space(void *fdt, size_t len)
{
	int offset = fdt_size_dt_struct(fdt);
	int spaceleft;

	spaceleft = fdt_totalsize(fdt) - fdt_off_dt_struct(fdt)
		- fdt_size_dt_strings(fdt);

	if ((offset + len < offset) || (offset + len > spaceleft))
		return NULL;

	fdt_set_size_dt_struct(fdt, offset + len);
	return _fdt_offset_ptr_w(fdt, offset);
}

int fdt_create(void *buf, int bufsize)
{
	void *fdt = buf;

	if (bufsize < sizeof(struct fdt_header))
		return -FDT_ERR_NOSPACE;

	memset(buf, 0, bufsize);

	fdt_set_magic(fdt, FDT_SW_MAGIC);
	fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
	fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
	fdt_set_totalsize(fdt,  bufsize);

	fdt_set_off_mem_rsvmap(fdt, FDT_ALIGN(sizeof(struct fdt_header),
					      sizeof(struct fdt_reserve_entry)));
	fdt_set_off_dt_struct(fdt, fdt_off_mem_rsvmap(fdt));
	fdt_set_off_dt_strings(fdt, bufsize);

	return 0;
}

int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size)
{
	struct fdt_reserve_entry *re;
	int offset;

	FDT_SW_CHECK_HEADER(fdt);

	if (fdt_size_dt_struct(fdt))
		return -FDT_ERR_BADSTATE;

	offset = fdt_off_dt_struct(fdt);
	if ((offset + sizeof(*re)) > fdt_totalsize(fdt))
		return -FDT_ERR_NOSPACE;

	re = (struct fdt_reserve_entry *)((char *)fdt + offset);
	re->address = cpu_to_fdt64(addr);
	re->size = cpu_to_fdt64(size);

	fdt_set_off_dt_struct(fdt, offset + sizeof(*re));

	return 0;
}

int fdt_finish_reservemap(void *fdt)
{
	return fdt_add_reservemap_entry(fdt, 0, 0);
}

int fdt_begin_node(void *fdt, const char *name)
{
	struct fdt_node_header *nh;
	int namelen = strlen(name) + 1;

	FDT_SW_CHECK_HEADER(fdt);

	nh = _fdt_grab_space(fdt, sizeof(*nh) + FDT_TAGALIGN(namelen));
	if (! nh)
		return -FDT_ERR_NOSPACE;

	nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
	memcpy(nh->name, name, namelen);
	return 0;
}

int fdt_end_node(void *fdt)
{
	fdt32_t *en;

	FDT_SW_CHECK_HEADER(fdt);

	en = _fdt_grab_space(fdt, FDT_TAGSIZE);
	if (! en)
		return -FDT_ERR_NOSPACE;

	*en = cpu_to_fdt32(FDT_END_NODE);
	return 0;
}

static int _fdt_find_add_string(void *fdt, const char *s)
{
	char *strtab = (char *)fdt + fdt_totalsize(fdt);
	const char *p;
	int strtabsize = fdt_size_dt_strings(fdt);
	int len = strlen(s) + 1;
	int struct_top, offset;

	p = _fdt_find_string(strtab - strtabsize, strtabsize, s);
	if (p)
		return p - strtab;

	/* Add it */
	offset = -strtabsize - len;
	struct_top = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
	if (fdt_totalsize(fdt) + offset < struct_top)
		return 0; /* no more room :( */

	memcpy(strtab + offset, s, len);
	fdt_set_size_dt_strings(fdt, strtabsize + len);
	return offset;
}

int fdt_property(void *fdt, const char *name, const void *val, int len)
{
	struct fdt_property *prop;
	int nameoff;

	FDT_SW_CHECK_HEADER(fdt);

	nameoff = _fdt_find_add_string(fdt, name);
	if (nameoff == 0)
		return -FDT_ERR_NOSPACE;

	prop = _fdt_grab_space(fdt, sizeof(*prop) + FDT_TAGALIGN(len));
	if (! prop)
		return -FDT_ERR_NOSPACE;

	prop->tag = cpu_to_fdt32(FDT_PROP);
	prop->nameoff = cpu_to_fdt32(nameoff);
	prop->len = cpu_to_fdt32(len);
	memcpy(prop->data, val, len);
	return 0;
}

int fdt_finish(void *fdt)
{
	char *p = (char *)fdt;
	fdt32_t *end;
	int oldstroffset, newstroffset;
	uint32_t tag;
	int offset, nextoffset;

	FDT_SW_CHECK_HEADER(fdt);

	/* Add terminator */
	end = _fdt_grab_space(fdt, sizeof(*end));
	if (! end)
		return -FDT_ERR_NOSPACE;
	*end = cpu_to_fdt32(FDT_END);

	/* Relocate the string table */
	oldstroffset = fdt_totalsize(fdt) - fdt_size_dt_strings(fdt);
	newstroffset = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);
	memmove(p + newstroffset, p + oldstroffset, fdt_size_dt_strings(fdt));
	fdt_set_off_dt_strings(fdt, newstroffset);

	/* Walk the structure, correcting string offsets */
	offset = 0;
	while ((tag = fdt_next_tag(fdt, offset, &nextoffset)) != FDT_END) {
		if (tag == FDT_PROP) {
			struct fdt_property *prop =
				_fdt_offset_ptr_w(fdt, offset);
			int nameoff;

			nameoff = fdt32_to_cpu(prop->nameoff);
			nameoff += fdt_size_dt_strings(fdt);
			prop->nameoff = cpu_to_fdt32(nameoff);
		}
		offset = nextoffset;
	}
	if (nextoffset < 0)
		return nextoffset;

	/* Finally, adjust the header */
	fdt_set_totalsize(fdt, newstroffset + fdt_size_dt_strings(fdt));
	fdt_set_magic(fdt, FDT_MAGIC);
	return 0;
}
                  source/v64/tests/kvm-unit-tests/lib/libfdt/fdt_wip.c                                                0000644 0000000 0000000 00000007124 00000000000 017556  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libfdt_env.h"

#include <fdt.h>
#include <libfdt.h>

#include "libfdt_internal.h"

int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
			const void *val, int len)
{
	void *propval;
	int proplen;

	propval = fdt_getprop_w(fdt, nodeoffset, name, &proplen);
	if (! propval)
		return proplen;

	if (proplen != len)
		return -FDT_ERR_NOSPACE;

	memcpy(propval, val, len);
	return 0;
}

static void _fdt_nop_region(void *start, int len)
{
	fdt32_t *p;

	for (p = start; (char *)p < ((char *)start + len); p++)
		*p = cpu_to_fdt32(FDT_NOP);
}

int fdt_nop_property(void *fdt, int nodeoffset, const char *name)
{
	struct fdt_property *prop;
	int len;

	prop = fdt_get_property_w(fdt, nodeoffset, name, &len);
	if (! prop)
		return len;

	_fdt_nop_region(prop, len + sizeof(*prop));

	return 0;
}

int _fdt_node_end_offset(void *fdt, int offset)
{
	int depth = 0;

	while ((offset >= 0) && (depth >= 0))
		offset = fdt_next_node(fdt, offset, &depth);

	return offset;
}

int fdt_nop_node(void *fdt, int nodeoffset)
{
	int endoffset;

	endoffset = _fdt_node_end_offset(fdt, nodeoffset);
	if (endoffset < 0)
		return endoffset;

	_fdt_nop_region(fdt_offset_ptr_w(fdt, nodeoffset, 0),
			endoffset - nodeoffset);
	return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/libfdt/libfdt.h                                                 0000644 0000000 0000000 00000155430 00000000000 017377  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _LIBFDT_H
#define _LIBFDT_H
/*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <libfdt_env.h>
#include <fdt.h>

#define FDT_FIRST_SUPPORTED_VERSION	0x10
#define FDT_LAST_SUPPORTED_VERSION	0x11

/* Error codes: informative error codes */
#define FDT_ERR_NOTFOUND	1
	/* FDT_ERR_NOTFOUND: The requested node or property does not exist */
#define FDT_ERR_EXISTS		2
	/* FDT_ERR_EXISTS: Attemped to create a node or property which
	 * already exists */
#define FDT_ERR_NOSPACE		3
	/* FDT_ERR_NOSPACE: Operation needed to expand the device
	 * tree, but its buffer did not have sufficient space to
	 * contain the expanded tree. Use fdt_open_into() to move the
	 * device tree to a buffer with more space. */

/* Error codes: codes for bad parameters */
#define FDT_ERR_BADOFFSET	4
	/* FDT_ERR_BADOFFSET: Function was passed a structure block
	 * offset which is out-of-bounds, or which points to an
	 * unsuitable part of the structure for the operation. */
#define FDT_ERR_BADPATH		5
	/* FDT_ERR_BADPATH: Function was passed a badly formatted path
	 * (e.g. missing a leading / for a function which requires an
	 * absolute path) */
#define FDT_ERR_BADPHANDLE	6
	/* FDT_ERR_BADPHANDLE: Function was passed an invalid phandle
	 * value.  phandle values of 0 and -1 are not permitted. */
#define FDT_ERR_BADSTATE	7
	/* FDT_ERR_BADSTATE: Function was passed an incomplete device
	 * tree created by the sequential-write functions, which is
	 * not sufficiently complete for the requested operation. */

/* Error codes: codes for bad device tree blobs */
#define FDT_ERR_TRUNCATED	8
	/* FDT_ERR_TRUNCATED: Structure block of the given device tree
	 * ends without an FDT_END tag. */
#define FDT_ERR_BADMAGIC	9
	/* FDT_ERR_BADMAGIC: Given "device tree" appears not to be a
	 * device tree at all - it is missing the flattened device
	 * tree magic number. */
#define FDT_ERR_BADVERSION	10
	/* FDT_ERR_BADVERSION: Given device tree has a version which
	 * can't be handled by the requested operation.  For
	 * read-write functions, this may mean that fdt_open_into() is
	 * required to convert the tree to the expected version. */
#define FDT_ERR_BADSTRUCTURE	11
	/* FDT_ERR_BADSTRUCTURE: Given device tree has a corrupt
	 * structure block or other serious error (e.g. misnested
	 * nodes, or subnodes preceding properties). */
#define FDT_ERR_BADLAYOUT	12
	/* FDT_ERR_BADLAYOUT: For read-write functions, the given
	 * device tree has it's sub-blocks in an order that the
	 * function can't handle (memory reserve map, then structure,
	 * then strings).  Use fdt_open_into() to reorganize the tree
	 * into a form suitable for the read-write operations. */

/* "Can't happen" error indicating a bug in libfdt */
#define FDT_ERR_INTERNAL	13
	/* FDT_ERR_INTERNAL: libfdt has failed an internal assertion.
	 * Should never be returned, if it is, it indicates a bug in
	 * libfdt itself. */

#define FDT_ERR_MAX		13

/**********************************************************************/
/* Low-level functions (you probably don't need these)                */
/**********************************************************************/

const void *fdt_offset_ptr(const void *fdt, int offset, unsigned int checklen);
static inline void *fdt_offset_ptr_w(void *fdt, int offset, int checklen)
{
	return (void *)(uintptr_t)fdt_offset_ptr(fdt, offset, checklen);
}

uint32_t fdt_next_tag(const void *fdt, int offset, int *nextoffset);

/**********************************************************************/
/* Traversal functions                                                */
/**********************************************************************/

int fdt_next_node(const void *fdt, int offset, int *depth);

/**
 * fdt_first_subnode() - get offset of first direct subnode
 *
 * @fdt:	FDT blob
 * @offset:	Offset of node to check
 * @return offset of first subnode, or -FDT_ERR_NOTFOUND if there is none
 */
int fdt_first_subnode(const void *fdt, int offset);

/**
 * fdt_next_subnode() - get offset of next direct subnode
 *
 * After first calling fdt_first_subnode(), call this function repeatedly to
 * get direct subnodes of a parent node.
 *
 * @fdt:	FDT blob
 * @offset:	Offset of previous subnode
 * @return offset of next subnode, or -FDT_ERR_NOTFOUND if there are no more
 * subnodes
 */
int fdt_next_subnode(const void *fdt, int offset);

/**********************************************************************/
/* General functions                                                  */
/**********************************************************************/

#define fdt_get_header(fdt, field) \
	(fdt32_to_cpu(((const struct fdt_header *)(fdt))->field))
#define fdt_magic(fdt) 			(fdt_get_header(fdt, magic))
#define fdt_totalsize(fdt)		(fdt_get_header(fdt, totalsize))
#define fdt_off_dt_struct(fdt)		(fdt_get_header(fdt, off_dt_struct))
#define fdt_off_dt_strings(fdt)		(fdt_get_header(fdt, off_dt_strings))
#define fdt_off_mem_rsvmap(fdt)		(fdt_get_header(fdt, off_mem_rsvmap))
#define fdt_version(fdt)		(fdt_get_header(fdt, version))
#define fdt_last_comp_version(fdt) 	(fdt_get_header(fdt, last_comp_version))
#define fdt_boot_cpuid_phys(fdt) 	(fdt_get_header(fdt, boot_cpuid_phys))
#define fdt_size_dt_strings(fdt) 	(fdt_get_header(fdt, size_dt_strings))
#define fdt_size_dt_struct(fdt)		(fdt_get_header(fdt, size_dt_struct))

#define __fdt_set_hdr(name) \
	static inline void fdt_set_##name(void *fdt, uint32_t val) \
	{ \
		struct fdt_header *fdth = (struct fdt_header*)fdt; \
		fdth->name = cpu_to_fdt32(val); \
	}
__fdt_set_hdr(magic);
__fdt_set_hdr(totalsize);
__fdt_set_hdr(off_dt_struct);
__fdt_set_hdr(off_dt_strings);
__fdt_set_hdr(off_mem_rsvmap);
__fdt_set_hdr(version);
__fdt_set_hdr(last_comp_version);
__fdt_set_hdr(boot_cpuid_phys);
__fdt_set_hdr(size_dt_strings);
__fdt_set_hdr(size_dt_struct);
#undef __fdt_set_hdr

/**
 * fdt_check_header - sanity check a device tree or possible device tree
 * @fdt: pointer to data which might be a flattened device tree
 *
 * fdt_check_header() checks that the given buffer contains what
 * appears to be a flattened device tree with sane information in its
 * header.
 *
 * returns:
 *     0, if the buffer appears to contain a valid device tree
 *     -FDT_ERR_BADMAGIC,
 *     -FDT_ERR_BADVERSION,
 *     -FDT_ERR_BADSTATE, standard meanings, as above
 */
int fdt_check_header(const void *fdt);

/**
 * fdt_move - move a device tree around in memory
 * @fdt: pointer to the device tree to move
 * @buf: pointer to memory where the device is to be moved
 * @bufsize: size of the memory space at buf
 *
 * fdt_move() relocates, if possible, the device tree blob located at
 * fdt to the buffer at buf of size bufsize.  The buffer may overlap
 * with the existing device tree blob at fdt.  Therefore,
 *     fdt_move(fdt, fdt, fdt_totalsize(fdt))
 * should always succeed.
 *
 * returns:
 *     0, on success
 *     -FDT_ERR_NOSPACE, bufsize is insufficient to contain the device tree
 *     -FDT_ERR_BADMAGIC,
 *     -FDT_ERR_BADVERSION,
 *     -FDT_ERR_BADSTATE, standard meanings
 */
int fdt_move(const void *fdt, void *buf, int bufsize);

/**********************************************************************/
/* Read-only functions                                                */
/**********************************************************************/

/**
 * fdt_string - retrieve a string from the strings block of a device tree
 * @fdt: pointer to the device tree blob
 * @stroffset: offset of the string within the strings block (native endian)
 *
 * fdt_string() retrieves a pointer to a single string from the
 * strings block of the device tree blob at fdt.
 *
 * returns:
 *     a pointer to the string, on success
 *     NULL, if stroffset is out of bounds
 */
const char *fdt_string(const void *fdt, int stroffset);

/**
 * fdt_num_mem_rsv - retrieve the number of memory reserve map entries
 * @fdt: pointer to the device tree blob
 *
 * Returns the number of entries in the device tree blob's memory
 * reservation map.  This does not include the terminating 0,0 entry
 * or any other (0,0) entries reserved for expansion.
 *
 * returns:
 *     the number of entries
 */
int fdt_num_mem_rsv(const void *fdt);

/**
 * fdt_get_mem_rsv - retrieve one memory reserve map entry
 * @fdt: pointer to the device tree blob
 * @address, @size: pointers to 64-bit variables
 *
 * On success, *address and *size will contain the address and size of
 * the n-th reserve map entry from the device tree blob, in
 * native-endian format.
 *
 * returns:
 *     0, on success
 *     -FDT_ERR_BADMAGIC,
 *     -FDT_ERR_BADVERSION,
 *     -FDT_ERR_BADSTATE, standard meanings
 */
int fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);

/**
 * fdt_subnode_offset_namelen - find a subnode based on substring
 * @fdt: pointer to the device tree blob
 * @parentoffset: structure block offset of a node
 * @name: name of the subnode to locate
 * @namelen: number of characters of name to consider
 *
 * Identical to fdt_subnode_offset(), but only examine the first
 * namelen characters of name for matching the subnode name.  This is
 * useful for finding subnodes based on a portion of a larger string,
 * such as a full path.
 */
int fdt_subnode_offset_namelen(const void *fdt, int parentoffset,
			       const char *name, int namelen);
/**
 * fdt_subnode_offset - find a subnode of a given node
 * @fdt: pointer to the device tree blob
 * @parentoffset: structure block offset of a node
 * @name: name of the subnode to locate
 *
 * fdt_subnode_offset() finds a subnode of the node at structure block
 * offset parentoffset with the given name.  name may include a unit
 * address, in which case fdt_subnode_offset() will find the subnode
 * with that unit address, or the unit address may be omitted, in
 * which case fdt_subnode_offset() will find an arbitrary subnode
 * whose name excluding unit address matches the given name.
 *
 * returns:
 *	structure block offset of the requested subnode (>=0), on success
 *	-FDT_ERR_NOTFOUND, if the requested subnode does not exist
 *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
 *      -FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings.
 */
int fdt_subnode_offset(const void *fdt, int parentoffset, const char *name);

/**
 * fdt_path_offset - find a tree node by its full path
 * @fdt: pointer to the device tree blob
 * @path: full path of the node to locate
 *
 * fdt_path_offset() finds a node of a given path in the device tree.
 * Each path component may omit the unit address portion, but the
 * results of this are undefined if any such path component is
 * ambiguous (that is if there are multiple nodes at the relevant
 * level matching the given component, differentiated only by unit
 * address).
 *
 * returns:
 *	structure block offset of the node with the requested path (>=0), on success
 *	-FDT_ERR_BADPATH, given path does not begin with '/' or is invalid
 *	-FDT_ERR_NOTFOUND, if the requested node does not exist
 *      -FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings.
 */
int fdt_path_offset(const void *fdt, const char *path);

/**
 * fdt_get_name - retrieve the name of a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: structure block offset of the starting node
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_get_name() retrieves the name (including unit address) of the
 * device tree node at structure block offset nodeoffset.  If lenp is
 * non-NULL, the length of this name is also returned, in the integer
 * pointed to by lenp.
 *
 * returns:
 *	pointer to the node's name, on success
 *		If lenp is non-NULL, *lenp contains the length of that name (>=0)
 *	NULL, on error
 *		if lenp is non-NULL *lenp contains an error code (<0):
 *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *		-FDT_ERR_BADMAGIC,
 *		-FDT_ERR_BADVERSION,
 *		-FDT_ERR_BADSTATE, standard meanings
 */
const char *fdt_get_name(const void *fdt, int nodeoffset, int *lenp);

/**
 * fdt_first_property_offset - find the offset of a node's first property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: structure block offset of a node
 *
 * fdt_first_property_offset() finds the first property of the node at
 * the given structure block offset.
 *
 * returns:
 *	structure block offset of the property (>=0), on success
 *	-FDT_ERR_NOTFOUND, if the requested node has no properties
 *	-FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_BEGIN_NODE tag
 *      -FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings.
 */
int fdt_first_property_offset(const void *fdt, int nodeoffset);

/**
 * fdt_next_property_offset - step through a node's properties
 * @fdt: pointer to the device tree blob
 * @offset: structure block offset of a property
 *
 * fdt_next_property_offset() finds the property immediately after the
 * one at the given structure block offset.  This will be a property
 * of the same node as the given property.
 *
 * returns:
 *	structure block offset of the next property (>=0), on success
 *	-FDT_ERR_NOTFOUND, if the given property is the last in its node
 *	-FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_PROP tag
 *      -FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings.
 */
int fdt_next_property_offset(const void *fdt, int offset);

/**
 * fdt_get_property_by_offset - retrieve the property at a given offset
 * @fdt: pointer to the device tree blob
 * @offset: offset of the property to retrieve
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_get_property_by_offset() retrieves a pointer to the
 * fdt_property structure within the device tree blob at the given
 * offset.  If lenp is non-NULL, the length of the property value is
 * also returned, in the integer pointed to by lenp.
 *
 * returns:
 *	pointer to the structure representing the property
 *		if lenp is non-NULL, *lenp contains the length of the property
 *		value (>=0)
 *	NULL, on error
 *		if lenp is non-NULL, *lenp contains an error code (<0):
 *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
 *		-FDT_ERR_BADMAGIC,
 *		-FDT_ERR_BADVERSION,
 *		-FDT_ERR_BADSTATE,
 *		-FDT_ERR_BADSTRUCTURE,
 *		-FDT_ERR_TRUNCATED, standard meanings
 */
const struct fdt_property *fdt_get_property_by_offset(const void *fdt,
						      int offset,
						      int *lenp);

/**
 * fdt_get_property_namelen - find a property based on substring
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to find
 * @name: name of the property to find
 * @namelen: number of characters of name to consider
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * Identical to fdt_get_property_namelen(), but only examine the first
 * namelen characters of name for matching the property name.
 */
const struct fdt_property *fdt_get_property_namelen(const void *fdt,
						    int nodeoffset,
						    const char *name,
						    int namelen, int *lenp);

/**
 * fdt_get_property - find a given property in a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to find
 * @name: name of the property to find
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_get_property() retrieves a pointer to the fdt_property
 * structure within the device tree blob corresponding to the property
 * named 'name' of the node at offset nodeoffset.  If lenp is
 * non-NULL, the length of the property value is also returned, in the
 * integer pointed to by lenp.
 *
 * returns:
 *	pointer to the structure representing the property
 *		if lenp is non-NULL, *lenp contains the length of the property
 *		value (>=0)
 *	NULL, on error
 *		if lenp is non-NULL, *lenp contains an error code (<0):
 *		-FDT_ERR_NOTFOUND, node does not have named property
 *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *		-FDT_ERR_BADMAGIC,
 *		-FDT_ERR_BADVERSION,
 *		-FDT_ERR_BADSTATE,
 *		-FDT_ERR_BADSTRUCTURE,
 *		-FDT_ERR_TRUNCATED, standard meanings
 */
const struct fdt_property *fdt_get_property(const void *fdt, int nodeoffset,
					    const char *name, int *lenp);
static inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,
						      const char *name,
						      int *lenp)
{
	return (struct fdt_property *)(uintptr_t)
		fdt_get_property(fdt, nodeoffset, name, lenp);
}

/**
 * fdt_getprop_by_offset - retrieve the value of a property at a given offset
 * @fdt: pointer to the device tree blob
 * @ffset: offset of the property to read
 * @namep: pointer to a string variable (will be overwritten) or NULL
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_getprop_by_offset() retrieves a pointer to the value of the
 * property at structure block offset 'offset' (this will be a pointer
 * to within the device blob itself, not a copy of the value).  If
 * lenp is non-NULL, the length of the property value is also
 * returned, in the integer pointed to by lenp.  If namep is non-NULL,
 * the property's namne will also be returned in the char * pointed to
 * by namep (this will be a pointer to within the device tree's string
 * block, not a new copy of the name).
 *
 * returns:
 *	pointer to the property's value
 *		if lenp is non-NULL, *lenp contains the length of the property
 *		value (>=0)
 *		if namep is non-NULL *namep contiains a pointer to the property
 *		name.
 *	NULL, on error
 *		if lenp is non-NULL, *lenp contains an error code (<0):
 *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag
 *		-FDT_ERR_BADMAGIC,
 *		-FDT_ERR_BADVERSION,
 *		-FDT_ERR_BADSTATE,
 *		-FDT_ERR_BADSTRUCTURE,
 *		-FDT_ERR_TRUNCATED, standard meanings
 */
const void *fdt_getprop_by_offset(const void *fdt, int offset,
				  const char **namep, int *lenp);

/**
 * fdt_getprop_namelen - get property value based on substring
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to find
 * @name: name of the property to find
 * @namelen: number of characters of name to consider
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * Identical to fdt_getprop(), but only examine the first namelen
 * characters of name for matching the property name.
 */
const void *fdt_getprop_namelen(const void *fdt, int nodeoffset,
				const char *name, int namelen, int *lenp);

/**
 * fdt_getprop - retrieve the value of a given property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to find
 * @name: name of the property to find
 * @lenp: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_getprop() retrieves a pointer to the value of the property
 * named 'name' of the node at offset nodeoffset (this will be a
 * pointer to within the device blob itself, not a copy of the value).
 * If lenp is non-NULL, the length of the property value is also
 * returned, in the integer pointed to by lenp.
 *
 * returns:
 *	pointer to the property's value
 *		if lenp is non-NULL, *lenp contains the length of the property
 *		value (>=0)
 *	NULL, on error
 *		if lenp is non-NULL, *lenp contains an error code (<0):
 *		-FDT_ERR_NOTFOUND, node does not have named property
 *		-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *		-FDT_ERR_BADMAGIC,
 *		-FDT_ERR_BADVERSION,
 *		-FDT_ERR_BADSTATE,
 *		-FDT_ERR_BADSTRUCTURE,
 *		-FDT_ERR_TRUNCATED, standard meanings
 */
const void *fdt_getprop(const void *fdt, int nodeoffset,
			const char *name, int *lenp);
static inline void *fdt_getprop_w(void *fdt, int nodeoffset,
				  const char *name, int *lenp)
{
	return (void *)(uintptr_t)fdt_getprop(fdt, nodeoffset, name, lenp);
}

/**
 * fdt_get_phandle - retrieve the phandle of a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: structure block offset of the node
 *
 * fdt_get_phandle() retrieves the phandle of the device tree node at
 * structure block offset nodeoffset.
 *
 * returns:
 *	the phandle of the node at nodeoffset, on success (!= 0, != -1)
 *	0, if the node has no phandle, or another error occurs
 */
uint32_t fdt_get_phandle(const void *fdt, int nodeoffset);

/**
 * fdt_get_alias_namelen - get alias based on substring
 * @fdt: pointer to the device tree blob
 * @name: name of the alias th look up
 * @namelen: number of characters of name to consider
 *
 * Identical to fdt_get_alias(), but only examine the first namelen
 * characters of name for matching the alias name.
 */
const char *fdt_get_alias_namelen(const void *fdt,
				  const char *name, int namelen);

/**
 * fdt_get_alias - retreive the path referenced by a given alias
 * @fdt: pointer to the device tree blob
 * @name: name of the alias th look up
 *
 * fdt_get_alias() retrieves the value of a given alias.  That is, the
 * value of the property named 'name' in the node /aliases.
 *
 * returns:
 *	a pointer to the expansion of the alias named 'name', if it exists
 *	NULL, if the given alias or the /aliases node does not exist
 */
const char *fdt_get_alias(const void *fdt, const char *name);

/**
 * fdt_get_path - determine the full path of a node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose path to find
 * @buf: character buffer to contain the returned path (will be overwritten)
 * @buflen: size of the character buffer at buf
 *
 * fdt_get_path() computes the full path of the node at offset
 * nodeoffset, and records that path in the buffer at buf.
 *
 * NOTE: This function is expensive, as it must scan the device tree
 * structure from the start to nodeoffset.
 *
 * returns:
 *	0, on success
 *		buf contains the absolute path of the node at
 *		nodeoffset, as a NUL-terminated string.
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_NOSPACE, the path of the given node is longer than (bufsize-1)
 *		characters and will not fit in the given buffer.
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);

/**
 * fdt_supernode_atdepth_offset - find a specific ancestor of a node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose parent to find
 * @supernodedepth: depth of the ancestor to find
 * @nodedepth: pointer to an integer variable (will be overwritten) or NULL
 *
 * fdt_supernode_atdepth_offset() finds an ancestor of the given node
 * at a specific depth from the root (where the root itself has depth
 * 0, its immediate subnodes depth 1 and so forth).  So
 *	fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);
 * will always return 0, the offset of the root node.  If the node at
 * nodeoffset has depth D, then:
 *	fdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);
 * will return nodeoffset itself.
 *
 * NOTE: This function is expensive, as it must scan the device tree
 * structure from the start to nodeoffset.
 *
 * returns:

 *	structure block offset of the node at node offset's ancestor
 *		of depth supernodedepth (>=0), on success
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
*	-FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of nodeoffset
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,
				 int supernodedepth, int *nodedepth);

/**
 * fdt_node_depth - find the depth of a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose parent to find
 *
 * fdt_node_depth() finds the depth of a given node.  The root node
 * has depth 0, its immediate subnodes depth 1 and so forth.
 *
 * NOTE: This function is expensive, as it must scan the device tree
 * structure from the start to nodeoffset.
 *
 * returns:
 *	depth of the node at nodeoffset (>=0), on success
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_node_depth(const void *fdt, int nodeoffset);

/**
 * fdt_parent_offset - find the parent of a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose parent to find
 *
 * fdt_parent_offset() locates the parent node of a given node (that
 * is, it finds the offset of the node which contains the node at
 * nodeoffset as a subnode).
 *
 * NOTE: This function is expensive, as it must scan the device tree
 * structure from the start to nodeoffset, *twice*.
 *
 * returns:
 *	structure block offset of the parent of the node at nodeoffset
 *		(>=0), on success
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_parent_offset(const void *fdt, int nodeoffset);

/**
 * fdt_node_offset_by_prop_value - find nodes with a given property value
 * @fdt: pointer to the device tree blob
 * @startoffset: only find nodes after this offset
 * @propname: property name to check
 * @propval: property value to search for
 * @proplen: length of the value in propval
 *
 * fdt_node_offset_by_prop_value() returns the offset of the first
 * node after startoffset, which has a property named propname whose
 * value is of length proplen and has value equal to propval; or if
 * startoffset is -1, the very first such node in the tree.
 *
 * To iterate through all nodes matching the criterion, the following
 * idiom can be used:
 *	offset = fdt_node_offset_by_prop_value(fdt, -1, propname,
 *					       propval, proplen);
 *	while (offset != -FDT_ERR_NOTFOUND) {
 *		// other code here
 *		offset = fdt_node_offset_by_prop_value(fdt, offset, propname,
 *						       propval, proplen);
 *	}
 *
 * Note the -1 in the first call to the function, if 0 is used here
 * instead, the function will never locate the root node, even if it
 * matches the criterion.
 *
 * returns:
 *	structure block offset of the located node (>= 0, >startoffset),
 *		 on success
 *	-FDT_ERR_NOTFOUND, no node matching the criterion exists in the
 *		tree after startoffset
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_node_offset_by_prop_value(const void *fdt, int startoffset,
				  const char *propname,
				  const void *propval, int proplen);

/**
 * fdt_node_offset_by_phandle - find the node with a given phandle
 * @fdt: pointer to the device tree blob
 * @phandle: phandle value
 *
 * fdt_node_offset_by_phandle() returns the offset of the node
 * which has the given phandle value.  If there is more than one node
 * in the tree with the given phandle (an invalid tree), results are
 * undefined.
 *
 * returns:
 *	structure block offset of the located node (>= 0), on success
 *	-FDT_ERR_NOTFOUND, no node with that phandle exists
 *	-FDT_ERR_BADPHANDLE, given phandle value was invalid (0 or -1)
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle);

/**
 * fdt_node_check_compatible: check a node's compatible property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of a tree node
 * @compatible: string to match against
 *
 *
 * fdt_node_check_compatible() returns 0 if the given node contains a
 * 'compatible' property with the given string as one of its elements,
 * it returns non-zero otherwise, or on error.
 *
 * returns:
 *	0, if the node has a 'compatible' property listing the given string
 *	1, if the node has a 'compatible' property, but it does not list
 *		the given string
 *	-FDT_ERR_NOTFOUND, if the given node has no 'compatible' property
 * 	-FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_node_check_compatible(const void *fdt, int nodeoffset,
			      const char *compatible);

/**
 * fdt_node_offset_by_compatible - find nodes with a given 'compatible' value
 * @fdt: pointer to the device tree blob
 * @startoffset: only find nodes after this offset
 * @compatible: 'compatible' string to match against
 *
 * fdt_node_offset_by_compatible() returns the offset of the first
 * node after startoffset, which has a 'compatible' property which
 * lists the given compatible string; or if startoffset is -1, the
 * very first such node in the tree.
 *
 * To iterate through all nodes matching the criterion, the following
 * idiom can be used:
 *	offset = fdt_node_offset_by_compatible(fdt, -1, compatible);
 *	while (offset != -FDT_ERR_NOTFOUND) {
 *		// other code here
 *		offset = fdt_node_offset_by_compatible(fdt, offset, compatible);
 *	}
 *
 * Note the -1 in the first call to the function, if 0 is used here
 * instead, the function will never locate the root node, even if it
 * matches the criterion.
 *
 * returns:
 *	structure block offset of the located node (>= 0, >startoffset),
 *		 on success
 *	-FDT_ERR_NOTFOUND, no node matching the criterion exists in the
 *		tree after startoffset
 * 	-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE, standard meanings
 */
int fdt_node_offset_by_compatible(const void *fdt, int startoffset,
				  const char *compatible);

/**
 * fdt_stringlist_contains - check a string list property for a string
 * @strlist: Property containing a list of strings to check
 * @listlen: Length of property
 * @str: String to search for
 *
 * This is a utility function provided for convenience. The list contains
 * one or more strings, each terminated by \0, as is found in a device tree
 * "compatible" property.
 *
 * @return: 1 if the string is found in the list, 0 not found, or invalid list
 */
int fdt_stringlist_contains(const char *strlist, int listlen, const char *str);

/**********************************************************************/
/* Write-in-place functions                                           */
/**********************************************************************/

/**
 * fdt_setprop_inplace - change a property's value, but not its size
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: pointer to data to replace the property value with
 * @len: length of the property value
 *
 * fdt_setprop_inplace() replaces the value of a given property with
 * the data in val, of length len.  This function cannot change the
 * size of a property, and so will only work if len is equal to the
 * current length of the property.
 *
 * This function will alter only the bytes in the blob which contain
 * the given property value, and will not alter or move any other part
 * of the tree.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, if len is not equal to the property's current length
 *	-FDT_ERR_NOTFOUND, node does not have the named property
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,
			const void *val, int len);

/**
 * fdt_setprop_inplace_u32 - change the value of a 32-bit integer property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 32-bit integer value to replace the property with
 *
 * fdt_setprop_inplace_u32() replaces the value of a given property
 * with the 32-bit integer value in val, converting val to big-endian
 * if necessary.  This function cannot change the size of a property,
 * and so will only work if the property already exists and has length
 * 4.
 *
 * This function will alter only the bytes in the blob which contain
 * the given property value, and will not alter or move any other part
 * of the tree.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, if the property's length is not equal to 4
 *	-FDT_ERR_NOTFOUND, node does not have the named property
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_setprop_inplace_u32(void *fdt, int nodeoffset,
					  const char *name, uint32_t val)
{
	fdt32_t tmp = cpu_to_fdt32(val);
	return fdt_setprop_inplace(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_setprop_inplace_u64 - change the value of a 64-bit integer property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 64-bit integer value to replace the property with
 *
 * fdt_setprop_inplace_u64() replaces the value of a given property
 * with the 64-bit integer value in val, converting val to big-endian
 * if necessary.  This function cannot change the size of a property,
 * and so will only work if the property already exists and has length
 * 8.
 *
 * This function will alter only the bytes in the blob which contain
 * the given property value, and will not alter or move any other part
 * of the tree.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, if the property's length is not equal to 8
 *	-FDT_ERR_NOTFOUND, node does not have the named property
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_setprop_inplace_u64(void *fdt, int nodeoffset,
					  const char *name, uint64_t val)
{
	fdt64_t tmp = cpu_to_fdt64(val);
	return fdt_setprop_inplace(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_setprop_inplace_cell - change the value of a single-cell property
 *
 * This is an alternative name for fdt_setprop_inplace_u32()
 */
static inline int fdt_setprop_inplace_cell(void *fdt, int nodeoffset,
					   const char *name, uint32_t val)
{
	return fdt_setprop_inplace_u32(fdt, nodeoffset, name, val);
}

/**
 * fdt_nop_property - replace a property with nop tags
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to nop
 * @name: name of the property to nop
 *
 * fdt_nop_property() will replace a given property's representation
 * in the blob with FDT_NOP tags, effectively removing it from the
 * tree.
 *
 * This function will alter only the bytes in the blob which contain
 * the property, and will not alter or move any other part of the
 * tree.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOTFOUND, node does not have the named property
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_nop_property(void *fdt, int nodeoffset, const char *name);

/**
 * fdt_nop_node - replace a node (subtree) with nop tags
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node to nop
 *
 * fdt_nop_node() will replace a given node's representation in the
 * blob, including all its subnodes, if any, with FDT_NOP tags,
 * effectively removing it from the tree.
 *
 * This function will alter only the bytes in the blob which contain
 * the node and its properties and subnodes, and will not alter or
 * move any other part of the tree.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_nop_node(void *fdt, int nodeoffset);

/**********************************************************************/
/* Sequential write functions                                         */
/**********************************************************************/

int fdt_create(void *buf, int bufsize);
int fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size);
int fdt_finish_reservemap(void *fdt);
int fdt_begin_node(void *fdt, const char *name);
int fdt_property(void *fdt, const char *name, const void *val, int len);
static inline int fdt_property_u32(void *fdt, const char *name, uint32_t val)
{
	fdt32_t tmp = cpu_to_fdt32(val);
	return fdt_property(fdt, name, &tmp, sizeof(tmp));
}
static inline int fdt_property_u64(void *fdt, const char *name, uint64_t val)
{
	fdt64_t tmp = cpu_to_fdt64(val);
	return fdt_property(fdt, name, &tmp, sizeof(tmp));
}
static inline int fdt_property_cell(void *fdt, const char *name, uint32_t val)
{
	return fdt_property_u32(fdt, name, val);
}
#define fdt_property_string(fdt, name, str) \
	fdt_property(fdt, name, str, strlen(str)+1)
int fdt_end_node(void *fdt);
int fdt_finish(void *fdt);

/**********************************************************************/
/* Read-write functions                                               */
/**********************************************************************/

int fdt_create_empty_tree(void *buf, int bufsize);
int fdt_open_into(const void *fdt, void *buf, int bufsize);
int fdt_pack(void *fdt);

/**
 * fdt_add_mem_rsv - add one memory reserve map entry
 * @fdt: pointer to the device tree blob
 * @address, @size: 64-bit values (native endian)
 *
 * Adds a reserve map entry to the given blob reserving a region at
 * address address of length size.
 *
 * This function will insert data into the reserve map and will
 * therefore change the indexes of some entries in the table.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new reservation entry
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size);

/**
 * fdt_del_mem_rsv - remove a memory reserve map entry
 * @fdt: pointer to the device tree blob
 * @n: entry to remove
 *
 * fdt_del_mem_rsv() removes the n-th memory reserve map entry from
 * the blob.
 *
 * This function will delete data from the reservation table and will
 * therefore change the indexes of some entries in the table.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOTFOUND, there is no entry of the given index (i.e. there
 *		are less than n+1 reserve map entries)
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_del_mem_rsv(void *fdt, int n);

/**
 * fdt_set_name - change the name of a given node
 * @fdt: pointer to the device tree blob
 * @nodeoffset: structure block offset of a node
 * @name: name to give the node
 *
 * fdt_set_name() replaces the name (including unit address, if any)
 * of the given node with the given string.  NOTE: this function can't
 * efficiently check if the new name is unique amongst the given
 * node's siblings; results are undefined if this function is invoked
 * with a name equal to one of the given node's siblings.
 *
 * This function may insert or delete data from the blob, and will
 * therefore change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob
 *		to contain the new name
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE, standard meanings
 */
int fdt_set_name(void *fdt, int nodeoffset, const char *name);

/**
 * fdt_setprop - create or change a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: pointer to data to set the property value to
 * @len: length of the property value
 *
 * fdt_setprop() sets the value of the named property in the given
 * node to the given value and length, creating the property if it
 * does not already exist.
 *
 * This function may insert or delete data from the blob, and will
 * therefore change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_setprop(void *fdt, int nodeoffset, const char *name,
		const void *val, int len);

/**
 * fdt_setprop_u32 - set a property to a 32-bit integer
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 32-bit integer value for the property (native endian)
 *
 * fdt_setprop_u32() sets the value of the named property in the given
 * node to the given 32-bit integer value (converting to big-endian if
 * necessary), or creates a new property with that value if it does
 * not already exist.
 *
 * This function may insert or delete data from the blob, and will
 * therefore change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_setprop_u32(void *fdt, int nodeoffset, const char *name,
				  uint32_t val)
{
	fdt32_t tmp = cpu_to_fdt32(val);
	return fdt_setprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_setprop_u64 - set a property to a 64-bit integer
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 64-bit integer value for the property (native endian)
 *
 * fdt_setprop_u64() sets the value of the named property in the given
 * node to the given 64-bit integer value (converting to big-endian if
 * necessary), or creates a new property with that value if it does
 * not already exist.
 *
 * This function may insert or delete data from the blob, and will
 * therefore change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_setprop_u64(void *fdt, int nodeoffset, const char *name,
				  uint64_t val)
{
	fdt64_t tmp = cpu_to_fdt64(val);
	return fdt_setprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_setprop_cell - set a property to a single cell value
 *
 * This is an alternative name for fdt_setprop_u32()
 */
static inline int fdt_setprop_cell(void *fdt, int nodeoffset, const char *name,
				   uint32_t val)
{
	return fdt_setprop_u32(fdt, nodeoffset, name, val);
}

/**
 * fdt_setprop_string - set a property to a string value
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @str: string value for the property
 *
 * fdt_setprop_string() sets the value of the named property in the
 * given node to the given string value (using the length of the
 * string to determine the new length of the property), or creates a
 * new property with that value if it does not already exist.
 *
 * This function may insert or delete data from the blob, and will
 * therefore change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
#define fdt_setprop_string(fdt, nodeoffset, name, str) \
	fdt_setprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)

/**
 * fdt_appendprop - append to or create a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to append to
 * @val: pointer to data to append to the property value
 * @len: length of the data to append to the property value
 *
 * fdt_appendprop() appends the value to the named property in the
 * given node, creating the property if it does not already exist.
 *
 * This function may insert data into the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_appendprop(void *fdt, int nodeoffset, const char *name,
		   const void *val, int len);

/**
 * fdt_appendprop_u32 - append a 32-bit integer value to a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 32-bit integer value to append to the property (native endian)
 *
 * fdt_appendprop_u32() appends the given 32-bit integer value
 * (converting to big-endian if necessary) to the value of the named
 * property in the given node, or creates a new property with that
 * value if it does not already exist.
 *
 * This function may insert data into the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_appendprop_u32(void *fdt, int nodeoffset,
				     const char *name, uint32_t val)
{
	fdt32_t tmp = cpu_to_fdt32(val);
	return fdt_appendprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_appendprop_u64 - append a 64-bit integer value to a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @val: 64-bit integer value to append to the property (native endian)
 *
 * fdt_appendprop_u64() appends the given 64-bit integer value
 * (converting to big-endian if necessary) to the value of the named
 * property in the given node, or creates a new property with that
 * value if it does not already exist.
 *
 * This function may insert data into the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
static inline int fdt_appendprop_u64(void *fdt, int nodeoffset,
				     const char *name, uint64_t val)
{
	fdt64_t tmp = cpu_to_fdt64(val);
	return fdt_appendprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));
}

/**
 * fdt_appendprop_cell - append a single cell value to a property
 *
 * This is an alternative name for fdt_appendprop_u32()
 */
static inline int fdt_appendprop_cell(void *fdt, int nodeoffset,
				      const char *name, uint32_t val)
{
	return fdt_appendprop_u32(fdt, nodeoffset, name, val);
}

/**
 * fdt_appendprop_string - append a string to a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to change
 * @name: name of the property to change
 * @str: string value to append to the property
 *
 * fdt_appendprop_string() appends the given string to the value of
 * the named property in the given node, or creates a new property
 * with that value if it does not already exist.
 *
 * This function may insert data into the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOSPACE, there is insufficient free space in the blob to
 *		contain the new property value
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
#define fdt_appendprop_string(fdt, nodeoffset, name, str) \
	fdt_appendprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)

/**
 * fdt_delprop - delete a property
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node whose property to nop
 * @name: name of the property to nop
 *
 * fdt_del_property() will delete the given property.
 *
 * This function will delete data from the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_NOTFOUND, node does not have the named property
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_delprop(void *fdt, int nodeoffset, const char *name);

/**
 * fdt_add_subnode_namelen - creates a new node based on substring
 * @fdt: pointer to the device tree blob
 * @parentoffset: structure block offset of a node
 * @name: name of the subnode to locate
 * @namelen: number of characters of name to consider
 *
 * Identical to fdt_add_subnode(), but use only the first namelen
 * characters of name as the name of the new node.  This is useful for
 * creating subnodes based on a portion of a larger string, such as a
 * full path.
 */
int fdt_add_subnode_namelen(void *fdt, int parentoffset,
			    const char *name, int namelen);

/**
 * fdt_add_subnode - creates a new node
 * @fdt: pointer to the device tree blob
 * @parentoffset: structure block offset of a node
 * @name: name of the subnode to locate
 *
 * fdt_add_subnode() creates a new node as a subnode of the node at
 * structure block offset parentoffset, with the given name (which
 * should include the unit address, if any).
 *
 * This function will insert data into the blob, and will therefore
 * change the offsets of some existing nodes.

 * returns:
 *	structure block offset of the created nodeequested subnode (>=0), on success
 *	-FDT_ERR_NOTFOUND, if the requested subnode does not exist
 *	-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE tag
 *	-FDT_ERR_EXISTS, if the node at parentoffset already has a subnode of
 *		the given name
 *	-FDT_ERR_NOSPACE, if there is insufficient free space in the
 *		blob to contain the new node
 *	-FDT_ERR_NOSPACE
 *	-FDT_ERR_BADLAYOUT
 *      -FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings.
 */
int fdt_add_subnode(void *fdt, int parentoffset, const char *name);

/**
 * fdt_del_node - delete a node (subtree)
 * @fdt: pointer to the device tree blob
 * @nodeoffset: offset of the node to nop
 *
 * fdt_del_node() will remove the given node, including all its
 * subnodes if any, from the blob.
 *
 * This function will delete data from the blob, and will therefore
 * change the offsets of some existing nodes.
 *
 * returns:
 *	0, on success
 *	-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag
 *	-FDT_ERR_BADLAYOUT,
 *	-FDT_ERR_BADMAGIC,
 *	-FDT_ERR_BADVERSION,
 *	-FDT_ERR_BADSTATE,
 *	-FDT_ERR_BADSTRUCTURE,
 *	-FDT_ERR_TRUNCATED, standard meanings
 */
int fdt_del_node(void *fdt, int nodeoffset);

/**********************************************************************/
/* Debugging / informational functions                                */
/**********************************************************************/

const char *fdt_strerror(int errval);

#endif /* _LIBFDT_H */
                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/libfdt/libfdt_env.h                                             0000644 0000000 0000000 00000007736 00000000000 020254  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _LIBFDT_ENV_H
#define _LIBFDT_ENV_H
/*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 * Copyright 2012 Kim Phillips, Freescale Semiconductor.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stddef.h>
#include <stdint.h>
#include <string.h>

#ifdef __CHECKER__
#define __force __attribute__((force))
#define __bitwise __attribute__((bitwise))
#else
#define __force
#define __bitwise
#endif

typedef uint16_t __bitwise fdt16_t;
typedef uint32_t __bitwise fdt32_t;
typedef uint64_t __bitwise fdt64_t;

#define EXTRACT_BYTE(x, n)	((unsigned long long)((uint8_t *)&x)[n])
#define CPU_TO_FDT16(x) ((EXTRACT_BYTE(x, 0) << 8) | EXTRACT_BYTE(x, 1))
#define CPU_TO_FDT32(x) ((EXTRACT_BYTE(x, 0) << 24) | (EXTRACT_BYTE(x, 1) << 16) | \
			 (EXTRACT_BYTE(x, 2) << 8) | EXTRACT_BYTE(x, 3))
#define CPU_TO_FDT64(x) ((EXTRACT_BYTE(x, 0) << 56) | (EXTRACT_BYTE(x, 1) << 48) | \
			 (EXTRACT_BYTE(x, 2) << 40) | (EXTRACT_BYTE(x, 3) << 32) | \
			 (EXTRACT_BYTE(x, 4) << 24) | (EXTRACT_BYTE(x, 5) << 16) | \
			 (EXTRACT_BYTE(x, 6) << 8) | EXTRACT_BYTE(x, 7))

static inline uint16_t fdt16_to_cpu(fdt16_t x)
{
	return (__force uint16_t)CPU_TO_FDT16(x);
}
static inline fdt16_t cpu_to_fdt16(uint16_t x)
{
	return (__force fdt16_t)CPU_TO_FDT16(x);
}

static inline uint32_t fdt32_to_cpu(fdt32_t x)
{
	return (__force uint32_t)CPU_TO_FDT32(x);
}
static inline fdt32_t cpu_to_fdt32(uint32_t x)
{
	return (__force fdt32_t)CPU_TO_FDT32(x);
}

static inline uint64_t fdt64_to_cpu(fdt64_t x)
{
	return (__force uint64_t)CPU_TO_FDT64(x);
}
static inline fdt64_t cpu_to_fdt64(uint64_t x)
{
	return (__force fdt64_t)CPU_TO_FDT64(x);
}
#undef CPU_TO_FDT64
#undef CPU_TO_FDT32
#undef CPU_TO_FDT16
#undef EXTRACT_BYTE

#endif /* _LIBFDT_ENV_H */
                                  source/v64/tests/kvm-unit-tests/lib/libfdt/libfdt_internal.h                                        0000644 0000000 0000000 00000007124 00000000000 021267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _LIBFDT_INTERNAL_H
#define _LIBFDT_INTERNAL_H
/*
 * libfdt - Flat Device Tree manipulation
 * Copyright (C) 2006 David Gibson, IBM Corporation.
 *
 * libfdt is dual licensed: you can use it either under the terms of
 * the GPL, or the BSD license, at your option.
 *
 *  a) This library 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 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 General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public
 *     License along with this library; if not, write to the Free
 *     Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
 *     MA 02110-1301 USA
 *
 * Alternatively,
 *
 *  b) Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *     1. Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *     2. Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include <fdt.h>

#define FDT_ALIGN(x, a)		(((x) + (a) - 1) & ~((a) - 1))
#define FDT_TAGALIGN(x)		(FDT_ALIGN((x), FDT_TAGSIZE))

#define FDT_CHECK_HEADER(fdt) \
	{ \
		int err; \
		if ((err = fdt_check_header(fdt)) != 0) \
			return err; \
	}

int _fdt_check_node_offset(const void *fdt, int offset);
int _fdt_check_prop_offset(const void *fdt, int offset);
const char *_fdt_find_string(const char *strtab, int tabsize, const char *s);
int _fdt_node_end_offset(void *fdt, int nodeoffset);

static inline const void *_fdt_offset_ptr(const void *fdt, int offset)
{
	return (const char *)fdt + fdt_off_dt_struct(fdt) + offset;
}

static inline void *_fdt_offset_ptr_w(void *fdt, int offset)
{
	return (void *)(uintptr_t)_fdt_offset_ptr(fdt, offset);
}

static inline const struct fdt_reserve_entry *_fdt_mem_rsv(const void *fdt, int n)
{
	const struct fdt_reserve_entry *rsv_table =
		(const struct fdt_reserve_entry *)
		((const char *)fdt + fdt_off_mem_rsvmap(fdt));

	return rsv_table + n;
}
static inline struct fdt_reserve_entry *_fdt_mem_rsv_w(void *fdt, int n)
{
	return (void *)(uintptr_t)_fdt_mem_rsv(fdt, n);
}

#define FDT_SW_MAGIC		(~FDT_MAGIC)

#endif /* _LIBFDT_INTERNAL_H */
                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/libfdt/version.lds                                              0000644 0000000 0000000 00000002204 00000000000 020141  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       LIBFDT_1.2 {
	global:
		fdt_next_node;
		fdt_check_header;
		fdt_move;
		fdt_string;
		fdt_num_mem_rsv;
		fdt_get_mem_rsv;
		fdt_subnode_offset_namelen;
		fdt_subnode_offset;
		fdt_path_offset;
		fdt_get_name;
		fdt_get_property_namelen;
		fdt_get_property;
		fdt_getprop_namelen;
		fdt_getprop;
		fdt_get_phandle;
		fdt_get_alias_namelen;
		fdt_get_alias;
		fdt_get_path;
		fdt_supernode_atdepth_offset;
		fdt_node_depth;
		fdt_parent_offset;
		fdt_node_offset_by_prop_value;
		fdt_node_offset_by_phandle;
		fdt_node_check_compatible;
		fdt_node_offset_by_compatible;
		fdt_setprop_inplace;
		fdt_nop_property;
		fdt_nop_node;
		fdt_create;
		fdt_add_reservemap_entry;
		fdt_finish_reservemap;
		fdt_begin_node;
		fdt_property;
		fdt_end_node;
		fdt_finish;
		fdt_open_into;
		fdt_pack;
		fdt_add_mem_rsv;
		fdt_del_mem_rsv;
		fdt_set_name;
		fdt_setprop;
		fdt_delprop;
		fdt_add_subnode_namelen;
		fdt_add_subnode;
		fdt_del_node;
		fdt_strerror;
		fdt_offset_ptr;
		fdt_next_tag;
		fdt_appendprop;
		fdt_create_empty_tree;
		fdt_first_property_offset;
		fdt_get_property_by_offset;
		fdt_getprop_by_offset;
		fdt_next_property_offset;

	local:
		*;
};
                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/linux/const.h                                                   0000644 0000000 0000000 00000001241 00000000000 017142  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* const.h: Macros for dealing with constants.  */

#ifndef _LINUX_CONST_H
#define _LINUX_CONST_H

/* Some constant macros are used in both assembler and
 * C code.  Therefore we cannot annotate them always with
 * 'UL' and other type specifiers unilaterally.  We
 * use the following macros to deal with this.
 *
 * Similarly, _AT() will cast an expression with a type in C, but
 * leave it unchanged in asm.
 */

#ifdef __ASSEMBLY__
#define _AC(X,Y)	X
#define _AT(T,X)	X
#else
#define __AC(X,Y)	(X##Y)
#define _AC(X,Y)	__AC(X,Y)
#define _AT(T,X)	((T)(X))
#endif

#define _BITUL(x)	(_AC(1,UL) << (x))
#define _BITULL(x)	(_AC(1,ULL) << (x))

#endif /* !(_LINUX_CONST_H) */
                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/lib/linux/pci_regs.h                                                0000644 0000000 0000000 00000137665 00000000000 017633  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 *	pci_regs.h
 *
 *	PCI standard defines
 *	Copyright 1994, Drew Eckhardt
 *	Copyright 1997--1999 Martin Mares <mj@ucw.cz>
 *
 *	For more information, please consult the following manuals (look at
 *	http://www.pcisig.com/ for how to get them):
 *
 *	PCI BIOS Specification
 *	PCI Local Bus Specification
 *	PCI to PCI Bridge Specification
 *	PCI System Design Guide
 *
 *	For HyperTransport information, please consult the following manuals
 *	from http://www.hypertransport.org
 *
 *	The HyperTransport I/O Link Specification
 */

#ifndef LINUX_PCI_REGS_H
#define LINUX_PCI_REGS_H

/*
 * Under PCI, each device has 256 bytes of configuration address space,
 * of which the first 64 bytes are standardized as follows:
 */
#define PCI_STD_HEADER_SIZEOF	64
#define PCI_VENDOR_ID		0x00	/* 16 bits */
#define PCI_DEVICE_ID		0x02	/* 16 bits */
#define PCI_COMMAND		0x04	/* 16 bits */
#define  PCI_COMMAND_IO		0x1	/* Enable response in I/O space */
#define  PCI_COMMAND_MEMORY	0x2	/* Enable response in Memory space */
#define  PCI_COMMAND_MASTER	0x4	/* Enable bus mastering */
#define  PCI_COMMAND_SPECIAL	0x8	/* Enable response to special cycles */
#define  PCI_COMMAND_INVALIDATE	0x10	/* Use memory write and invalidate */
#define  PCI_COMMAND_VGA_PALETTE 0x20	/* Enable palette snooping */
#define  PCI_COMMAND_PARITY	0x40	/* Enable parity checking */
#define  PCI_COMMAND_WAIT	0x80	/* Enable address/data stepping */
#define  PCI_COMMAND_SERR	0x100	/* Enable SERR */
#define  PCI_COMMAND_FAST_BACK	0x200	/* Enable back-to-back writes */
#define  PCI_COMMAND_INTX_DISABLE 0x400 /* INTx Emulation Disable */

#define PCI_STATUS		0x06	/* 16 bits */
#define  PCI_STATUS_INTERRUPT	0x08	/* Interrupt status */
#define  PCI_STATUS_CAP_LIST	0x10	/* Support Capability List */
#define  PCI_STATUS_66MHZ	0x20	/* Support 66 MHz PCI 2.1 bus */
#define  PCI_STATUS_UDF		0x40	/* Support User Definable Features [obsolete] */
#define  PCI_STATUS_FAST_BACK	0x80	/* Accept fast-back to back */
#define  PCI_STATUS_PARITY	0x100	/* Detected parity error */
#define  PCI_STATUS_DEVSEL_MASK	0x600	/* DEVSEL timing */
#define  PCI_STATUS_DEVSEL_FAST		0x000
#define  PCI_STATUS_DEVSEL_MEDIUM	0x200
#define  PCI_STATUS_DEVSEL_SLOW		0x400
#define  PCI_STATUS_SIG_TARGET_ABORT	0x800 /* Set on target abort */
#define  PCI_STATUS_REC_TARGET_ABORT	0x1000 /* Master ack of " */
#define  PCI_STATUS_REC_MASTER_ABORT	0x2000 /* Set on master abort */
#define  PCI_STATUS_SIG_SYSTEM_ERROR	0x4000 /* Set when we drive SERR */
#define  PCI_STATUS_DETECTED_PARITY	0x8000 /* Set on parity error */

#define PCI_CLASS_REVISION	0x08	/* High 24 bits are class, low 8 revision */
#define PCI_REVISION_ID		0x08	/* Revision ID */
#define PCI_CLASS_PROG		0x09	/* Reg. Level Programming Interface */
#define PCI_CLASS_DEVICE	0x0a	/* Device class */

#define PCI_CACHE_LINE_SIZE	0x0c	/* 8 bits */
#define PCI_LATENCY_TIMER	0x0d	/* 8 bits */
#define PCI_HEADER_TYPE		0x0e	/* 8 bits */
#define  PCI_HEADER_TYPE_NORMAL		0
#define  PCI_HEADER_TYPE_BRIDGE		1
#define  PCI_HEADER_TYPE_CARDBUS	2

#define PCI_BIST		0x0f	/* 8 bits */
#define  PCI_BIST_CODE_MASK	0x0f	/* Return result */
#define  PCI_BIST_START		0x40	/* 1 to start BIST, 2 secs or less */
#define  PCI_BIST_CAPABLE	0x80	/* 1 if BIST capable */

/*
 * Base addresses specify locations in memory or I/O space.
 * Decoded size can be determined by writing a value of
 * 0xffffffff to the register, and reading it back.  Only
 * 1 bits are decoded.
 */
#define PCI_BASE_ADDRESS_0	0x10	/* 32 bits */
#define PCI_BASE_ADDRESS_1	0x14	/* 32 bits [htype 0,1 only] */
#define PCI_BASE_ADDRESS_2	0x18	/* 32 bits [htype 0 only] */
#define PCI_BASE_ADDRESS_3	0x1c	/* 32 bits */
#define PCI_BASE_ADDRESS_4	0x20	/* 32 bits */
#define PCI_BASE_ADDRESS_5	0x24	/* 32 bits */
#define  PCI_BASE_ADDRESS_SPACE		0x01	/* 0 = memory, 1 = I/O */
#define  PCI_BASE_ADDRESS_SPACE_IO	0x01
#define  PCI_BASE_ADDRESS_SPACE_MEMORY	0x00
#define  PCI_BASE_ADDRESS_MEM_TYPE_MASK	0x06
#define  PCI_BASE_ADDRESS_MEM_TYPE_32	0x00	/* 32 bit address */
#define  PCI_BASE_ADDRESS_MEM_TYPE_1M	0x02	/* Below 1M [obsolete] */
#define  PCI_BASE_ADDRESS_MEM_TYPE_64	0x04	/* 64 bit address */
#define  PCI_BASE_ADDRESS_MEM_PREFETCH	0x08	/* prefetchable? */
#define  PCI_BASE_ADDRESS_MEM_MASK	(~0x0fUL)
#define  PCI_BASE_ADDRESS_IO_MASK	(~0x03UL)
/* bit 1 is reserved if address_space = 1 */

/* Header type 0 (normal devices) */
#define PCI_CARDBUS_CIS		0x28
#define PCI_SUBSYSTEM_VENDOR_ID	0x2c
#define PCI_SUBSYSTEM_ID	0x2e
#define PCI_ROM_ADDRESS		0x30	/* Bits 31..11 are address, 10..1 reserved */
#define  PCI_ROM_ADDRESS_ENABLE	0x01
#define PCI_ROM_ADDRESS_MASK	(~0x7ffUL)

#define PCI_CAPABILITY_LIST	0x34	/* Offset of first capability list entry */

/* 0x35-0x3b are reserved */
#define PCI_INTERRUPT_LINE	0x3c	/* 8 bits */
#define PCI_INTERRUPT_PIN	0x3d	/* 8 bits */
#define PCI_MIN_GNT		0x3e	/* 8 bits */
#define PCI_MAX_LAT		0x3f	/* 8 bits */

/* Header type 1 (PCI-to-PCI bridges) */
#define PCI_PRIMARY_BUS		0x18	/* Primary bus number */
#define PCI_SECONDARY_BUS	0x19	/* Secondary bus number */
#define PCI_SUBORDINATE_BUS	0x1a	/* Highest bus number behind the bridge */
#define PCI_SEC_LATENCY_TIMER	0x1b	/* Latency timer for secondary interface */
#define PCI_IO_BASE		0x1c	/* I/O range behind the bridge */
#define PCI_IO_LIMIT		0x1d
#define  PCI_IO_RANGE_TYPE_MASK	0x0fUL	/* I/O bridging type */
#define  PCI_IO_RANGE_TYPE_16	0x00
#define  PCI_IO_RANGE_TYPE_32	0x01
#define  PCI_IO_RANGE_MASK	(~0x0fUL) /* Standard 4K I/O windows */
#define  PCI_IO_1K_RANGE_MASK	(~0x03UL) /* Intel 1K I/O windows */
#define PCI_SEC_STATUS		0x1e	/* Secondary status register, only bit 14 used */
#define PCI_MEMORY_BASE		0x20	/* Memory range behind */
#define PCI_MEMORY_LIMIT	0x22
#define  PCI_MEMORY_RANGE_TYPE_MASK 0x0fUL
#define  PCI_MEMORY_RANGE_MASK	(~0x0fUL)
#define PCI_PREF_MEMORY_BASE	0x24	/* Prefetchable memory range behind */
#define PCI_PREF_MEMORY_LIMIT	0x26
#define  PCI_PREF_RANGE_TYPE_MASK 0x0fUL
#define  PCI_PREF_RANGE_TYPE_32	0x00
#define  PCI_PREF_RANGE_TYPE_64	0x01
#define  PCI_PREF_RANGE_MASK	(~0x0fUL)
#define PCI_PREF_BASE_UPPER32	0x28	/* Upper half of prefetchable memory range */
#define PCI_PREF_LIMIT_UPPER32	0x2c
#define PCI_IO_BASE_UPPER16	0x30	/* Upper half of I/O addresses */
#define PCI_IO_LIMIT_UPPER16	0x32
/* 0x34 same as for htype 0 */
/* 0x35-0x3b is reserved */
#define PCI_ROM_ADDRESS1	0x38	/* Same as PCI_ROM_ADDRESS, but for htype 1 */
/* 0x3c-0x3d are same as for htype 0 */
#define PCI_BRIDGE_CONTROL	0x3e
#define  PCI_BRIDGE_CTL_PARITY	0x01	/* Enable parity detection on secondary interface */
#define  PCI_BRIDGE_CTL_SERR	0x02	/* The same for SERR forwarding */
#define  PCI_BRIDGE_CTL_ISA	0x04	/* Enable ISA mode */
#define  PCI_BRIDGE_CTL_VGA	0x08	/* Forward VGA addresses */
#define  PCI_BRIDGE_CTL_MASTER_ABORT	0x20  /* Report master aborts */
#define  PCI_BRIDGE_CTL_BUS_RESET	0x40	/* Secondary bus reset */
#define  PCI_BRIDGE_CTL_FAST_BACK	0x80	/* Fast Back2Back enabled on secondary interface */

/* Header type 2 (CardBus bridges) */
#define PCI_CB_CAPABILITY_LIST	0x14
/* 0x15 reserved */
#define PCI_CB_SEC_STATUS	0x16	/* Secondary status */
#define PCI_CB_PRIMARY_BUS	0x18	/* PCI bus number */
#define PCI_CB_CARD_BUS		0x19	/* CardBus bus number */
#define PCI_CB_SUBORDINATE_BUS	0x1a	/* Subordinate bus number */
#define PCI_CB_LATENCY_TIMER	0x1b	/* CardBus latency timer */
#define PCI_CB_MEMORY_BASE_0	0x1c
#define PCI_CB_MEMORY_LIMIT_0	0x20
#define PCI_CB_MEMORY_BASE_1	0x24
#define PCI_CB_MEMORY_LIMIT_1	0x28
#define PCI_CB_IO_BASE_0	0x2c
#define PCI_CB_IO_BASE_0_HI	0x2e
#define PCI_CB_IO_LIMIT_0	0x30
#define PCI_CB_IO_LIMIT_0_HI	0x32
#define PCI_CB_IO_BASE_1	0x34
#define PCI_CB_IO_BASE_1_HI	0x36
#define PCI_CB_IO_LIMIT_1	0x38
#define PCI_CB_IO_LIMIT_1_HI	0x3a
#define  PCI_CB_IO_RANGE_MASK	(~0x03UL)
/* 0x3c-0x3d are same as for htype 0 */
#define PCI_CB_BRIDGE_CONTROL	0x3e
#define  PCI_CB_BRIDGE_CTL_PARITY	0x01	/* Similar to standard bridge control register */
#define  PCI_CB_BRIDGE_CTL_SERR		0x02
#define  PCI_CB_BRIDGE_CTL_ISA		0x04
#define  PCI_CB_BRIDGE_CTL_VGA		0x08
#define  PCI_CB_BRIDGE_CTL_MASTER_ABORT	0x20
#define  PCI_CB_BRIDGE_CTL_CB_RESET	0x40	/* CardBus reset */
#define  PCI_CB_BRIDGE_CTL_16BIT_INT	0x80	/* Enable interrupt for 16-bit cards */
#define  PCI_CB_BRIDGE_CTL_PREFETCH_MEM0 0x100	/* Prefetch enable for both memory regions */
#define  PCI_CB_BRIDGE_CTL_PREFETCH_MEM1 0x200
#define  PCI_CB_BRIDGE_CTL_POST_WRITES	0x400
#define PCI_CB_SUBSYSTEM_VENDOR_ID	0x40
#define PCI_CB_SUBSYSTEM_ID		0x42
#define PCI_CB_LEGACY_MODE_BASE		0x44	/* 16-bit PC Card legacy mode base address (ExCa) */
/* 0x48-0x7f reserved */

/* Capability lists */

#define PCI_CAP_LIST_ID		0	/* Capability ID */
#define  PCI_CAP_ID_PM		0x01	/* Power Management */
#define  PCI_CAP_ID_AGP		0x02	/* Accelerated Graphics Port */
#define  PCI_CAP_ID_VPD		0x03	/* Vital Product Data */
#define  PCI_CAP_ID_SLOTID	0x04	/* Slot Identification */
#define  PCI_CAP_ID_MSI		0x05	/* Message Signalled Interrupts */
#define  PCI_CAP_ID_CHSWP	0x06	/* CompactPCI HotSwap */
#define  PCI_CAP_ID_PCIX	0x07	/* PCI-X */
#define  PCI_CAP_ID_HT		0x08	/* HyperTransport */
#define  PCI_CAP_ID_VNDR	0x09	/* Vendor-Specific */
#define  PCI_CAP_ID_DBG		0x0A	/* Debug port */
#define  PCI_CAP_ID_CCRC	0x0B	/* CompactPCI Central Resource Control */
#define  PCI_CAP_ID_SHPC	0x0C	/* PCI Standard Hot-Plug Controller */
#define  PCI_CAP_ID_SSVID	0x0D	/* Bridge subsystem vendor/device ID */
#define  PCI_CAP_ID_AGP3	0x0E	/* AGP Target PCI-PCI bridge */
#define  PCI_CAP_ID_SECDEV	0x0F	/* Secure Device */
#define  PCI_CAP_ID_EXP		0x10	/* PCI Express */
#define  PCI_CAP_ID_MSIX	0x11	/* MSI-X */
#define  PCI_CAP_ID_SATA	0x12	/* SATA Data/Index Conf. */
#define  PCI_CAP_ID_AF		0x13	/* PCI Advanced Features */
#define  PCI_CAP_ID_EA		0x14	/* PCI Enhanced Allocation */
#define  PCI_CAP_ID_MAX		PCI_CAP_ID_EA
#define PCI_CAP_LIST_NEXT	1	/* Next capability in the list */
#define PCI_CAP_FLAGS		2	/* Capability defined flags (16 bits) */
#define PCI_CAP_SIZEOF		4

/* Power Management Registers */

#define PCI_PM_PMC		2	/* PM Capabilities Register */
#define  PCI_PM_CAP_VER_MASK	0x0007	/* Version */
#define  PCI_PM_CAP_PME_CLOCK	0x0008	/* PME clock required */
#define  PCI_PM_CAP_RESERVED    0x0010  /* Reserved field */
#define  PCI_PM_CAP_DSI		0x0020	/* Device specific initialization */
#define  PCI_PM_CAP_AUX_POWER	0x01C0	/* Auxiliary power support mask */
#define  PCI_PM_CAP_D1		0x0200	/* D1 power state support */
#define  PCI_PM_CAP_D2		0x0400	/* D2 power state support */
#define  PCI_PM_CAP_PME		0x0800	/* PME pin supported */
#define  PCI_PM_CAP_PME_MASK	0xF800	/* PME Mask of all supported states */
#define  PCI_PM_CAP_PME_D0	0x0800	/* PME# from D0 */
#define  PCI_PM_CAP_PME_D1	0x1000	/* PME# from D1 */
#define  PCI_PM_CAP_PME_D2	0x2000	/* PME# from D2 */
#define  PCI_PM_CAP_PME_D3	0x4000	/* PME# from D3 (hot) */
#define  PCI_PM_CAP_PME_D3cold	0x8000	/* PME# from D3 (cold) */
#define  PCI_PM_CAP_PME_SHIFT	11	/* Start of the PME Mask in PMC */
#define PCI_PM_CTRL		4	/* PM control and status register */
#define  PCI_PM_CTRL_STATE_MASK	0x0003	/* Current power state (D0 to D3) */
#define  PCI_PM_CTRL_NO_SOFT_RESET	0x0008	/* No reset for D3hot->D0 */
#define  PCI_PM_CTRL_PME_ENABLE	0x0100	/* PME pin enable */
#define  PCI_PM_CTRL_DATA_SEL_MASK	0x1e00	/* Data select (??) */
#define  PCI_PM_CTRL_DATA_SCALE_MASK	0x6000	/* Data scale (??) */
#define  PCI_PM_CTRL_PME_STATUS	0x8000	/* PME pin status */
#define PCI_PM_PPB_EXTENSIONS	6	/* PPB support extensions (??) */
#define  PCI_PM_PPB_B2_B3	0x40	/* Stop clock when in D3hot (??) */
#define  PCI_PM_BPCC_ENABLE	0x80	/* Bus power/clock control enable (??) */
#define PCI_PM_DATA_REGISTER	7	/* (??) */
#define PCI_PM_SIZEOF		8

/* AGP registers */

#define PCI_AGP_VERSION		2	/* BCD version number */
#define PCI_AGP_RFU		3	/* Rest of capability flags */
#define PCI_AGP_STATUS		4	/* Status register */
#define  PCI_AGP_STATUS_RQ_MASK	0xff000000	/* Maximum number of requests - 1 */
#define  PCI_AGP_STATUS_SBA	0x0200	/* Sideband addressing supported */
#define  PCI_AGP_STATUS_64BIT	0x0020	/* 64-bit addressing supported */
#define  PCI_AGP_STATUS_FW	0x0010	/* FW transfers supported */
#define  PCI_AGP_STATUS_RATE4	0x0004	/* 4x transfer rate supported */
#define  PCI_AGP_STATUS_RATE2	0x0002	/* 2x transfer rate supported */
#define  PCI_AGP_STATUS_RATE1	0x0001	/* 1x transfer rate supported */
#define PCI_AGP_COMMAND		8	/* Control register */
#define  PCI_AGP_COMMAND_RQ_MASK 0xff000000  /* Master: Maximum number of requests */
#define  PCI_AGP_COMMAND_SBA	0x0200	/* Sideband addressing enabled */
#define  PCI_AGP_COMMAND_AGP	0x0100	/* Allow processing of AGP transactions */
#define  PCI_AGP_COMMAND_64BIT	0x0020	/* Allow processing of 64-bit addresses */
#define  PCI_AGP_COMMAND_FW	0x0010	/* Force FW transfers */
#define  PCI_AGP_COMMAND_RATE4	0x0004	/* Use 4x rate */
#define  PCI_AGP_COMMAND_RATE2	0x0002	/* Use 2x rate */
#define  PCI_AGP_COMMAND_RATE1	0x0001	/* Use 1x rate */
#define PCI_AGP_SIZEOF		12

/* Vital Product Data */

#define PCI_VPD_ADDR		2	/* Address to access (15 bits!) */
#define  PCI_VPD_ADDR_MASK	0x7fff	/* Address mask */
#define  PCI_VPD_ADDR_F		0x8000	/* Write 0, 1 indicates completion */
#define PCI_VPD_DATA		4	/* 32-bits of data returned here */
#define PCI_CAP_VPD_SIZEOF	8

/* Slot Identification */

#define PCI_SID_ESR		2	/* Expansion Slot Register */
#define  PCI_SID_ESR_NSLOTS	0x1f	/* Number of expansion slots available */
#define  PCI_SID_ESR_FIC	0x20	/* First In Chassis Flag */
#define PCI_SID_CHASSIS_NR	3	/* Chassis Number */

/* Message Signalled Interrupts registers */

#define PCI_MSI_FLAGS		2	/* Message Control */
#define  PCI_MSI_FLAGS_ENABLE	0x0001	/* MSI feature enabled */
#define  PCI_MSI_FLAGS_QMASK	0x000e	/* Maximum queue size available */
#define  PCI_MSI_FLAGS_QSIZE	0x0070	/* Message queue size configured */
#define  PCI_MSI_FLAGS_64BIT	0x0080	/* 64-bit addresses allowed */
#define  PCI_MSI_FLAGS_MASKBIT	0x0100	/* Per-vector masking capable */
#define PCI_MSI_RFU		3	/* Rest of capability flags */
#define PCI_MSI_ADDRESS_LO	4	/* Lower 32 bits */
#define PCI_MSI_ADDRESS_HI	8	/* Upper 32 bits (if PCI_MSI_FLAGS_64BIT set) */
#define PCI_MSI_DATA_32		8	/* 16 bits of data for 32-bit devices */
#define PCI_MSI_MASK_32		12	/* Mask bits register for 32-bit devices */
#define PCI_MSI_PENDING_32	16	/* Pending intrs for 32-bit devices */
#define PCI_MSI_DATA_64		12	/* 16 bits of data for 64-bit devices */
#define PCI_MSI_MASK_64		16	/* Mask bits register for 64-bit devices */
#define PCI_MSI_PENDING_64	20	/* Pending intrs for 64-bit devices */

/* MSI-X registers */
#define PCI_MSIX_FLAGS		2	/* Message Control */
#define  PCI_MSIX_FLAGS_QSIZE	0x07FF	/* Table size */
#define  PCI_MSIX_FLAGS_MASKALL	0x4000	/* Mask all vectors for this function */
#define  PCI_MSIX_FLAGS_ENABLE	0x8000	/* MSI-X enable */
#define PCI_MSIX_TABLE		4	/* Table offset */
#define  PCI_MSIX_TABLE_BIR	0x00000007 /* BAR index */
#define  PCI_MSIX_TABLE_OFFSET	0xfffffff8 /* Offset into specified BAR */
#define PCI_MSIX_PBA		8	/* Pending Bit Array offset */
#define  PCI_MSIX_PBA_BIR	0x00000007 /* BAR index */
#define  PCI_MSIX_PBA_OFFSET	0xfffffff8 /* Offset into specified BAR */
#define PCI_MSIX_FLAGS_BIRMASK	PCI_MSIX_PBA_BIR /* deprecated */
#define PCI_CAP_MSIX_SIZEOF	12	/* size of MSIX registers */

/* MSI-X Table entry format */
#define PCI_MSIX_ENTRY_SIZE		16
#define  PCI_MSIX_ENTRY_LOWER_ADDR	0
#define  PCI_MSIX_ENTRY_UPPER_ADDR	4
#define  PCI_MSIX_ENTRY_DATA		8
#define  PCI_MSIX_ENTRY_VECTOR_CTRL	12
#define   PCI_MSIX_ENTRY_CTRL_MASKBIT	1

/* CompactPCI Hotswap Register */

#define PCI_CHSWP_CSR		2	/* Control and Status Register */
#define  PCI_CHSWP_DHA		0x01	/* Device Hiding Arm */
#define  PCI_CHSWP_EIM		0x02	/* ENUM# Signal Mask */
#define  PCI_CHSWP_PIE		0x04	/* Pending Insert or Extract */
#define  PCI_CHSWP_LOO		0x08	/* LED On / Off */
#define  PCI_CHSWP_PI		0x30	/* Programming Interface */
#define  PCI_CHSWP_EXT		0x40	/* ENUM# status - extraction */
#define  PCI_CHSWP_INS		0x80	/* ENUM# status - insertion */

/* PCI Advanced Feature registers */

#define PCI_AF_LENGTH		2
#define PCI_AF_CAP		3
#define  PCI_AF_CAP_TP		0x01
#define  PCI_AF_CAP_FLR		0x02
#define PCI_AF_CTRL		4
#define  PCI_AF_CTRL_FLR	0x01
#define PCI_AF_STATUS		5
#define  PCI_AF_STATUS_TP	0x01
#define PCI_CAP_AF_SIZEOF	6	/* size of AF registers */

/* PCI Enhanced Allocation registers */

#define PCI_EA_NUM_ENT		2	/* Number of Capability Entries */
#define  PCI_EA_NUM_ENT_MASK	0x3f	/* Num Entries Mask */
#define PCI_EA_FIRST_ENT	4	/* First EA Entry in List */
#define PCI_EA_FIRST_ENT_BRIDGE	8	/* First EA Entry for Bridges */
#define  PCI_EA_ES		0x00000007 /* Entry Size */
#define  PCI_EA_BEI		0x000000f0 /* BAR Equivalent Indicator */
/* 0-5 map to BARs 0-5 respectively */
#define   PCI_EA_BEI_BAR0		0
#define   PCI_EA_BEI_BAR5		5
#define   PCI_EA_BEI_BRIDGE		6	/* Resource behind bridge */
#define   PCI_EA_BEI_ENI		7	/* Equivalent Not Indicated */
#define   PCI_EA_BEI_ROM		8	/* Expansion ROM */
/* 9-14 map to VF BARs 0-5 respectively */
#define   PCI_EA_BEI_VF_BAR0		9
#define   PCI_EA_BEI_VF_BAR5		14
#define   PCI_EA_BEI_RESERVED		15	/* Reserved - Treat like ENI */
#define  PCI_EA_PP		0x0000ff00	/* Primary Properties */
#define  PCI_EA_SP		0x00ff0000	/* Secondary Properties */
#define   PCI_EA_P_MEM			0x00	/* Non-Prefetch Memory */
#define   PCI_EA_P_MEM_PREFETCH		0x01	/* Prefetchable Memory */
#define   PCI_EA_P_IO			0x02	/* I/O Space */
#define   PCI_EA_P_VF_MEM_PREFETCH	0x03	/* VF Prefetchable Memory */
#define   PCI_EA_P_VF_MEM		0x04	/* VF Non-Prefetch Memory */
#define   PCI_EA_P_BRIDGE_MEM		0x05	/* Bridge Non-Prefetch Memory */
#define   PCI_EA_P_BRIDGE_MEM_PREFETCH	0x06	/* Bridge Prefetchable Memory */
#define   PCI_EA_P_BRIDGE_IO		0x07	/* Bridge I/O Space */
/* 0x08-0xfc reserved */
#define   PCI_EA_P_MEM_RESERVED		0xfd	/* Reserved Memory */
#define   PCI_EA_P_IO_RESERVED		0xfe	/* Reserved I/O Space */
#define   PCI_EA_P_UNAVAILABLE		0xff	/* Entry Unavailable */
#define  PCI_EA_WRITABLE	0x40000000	/* Writable: 1 = RW, 0 = HwInit */
#define  PCI_EA_ENABLE		0x80000000	/* Enable for this entry */
#define PCI_EA_BASE		4		/* Base Address Offset */
#define PCI_EA_MAX_OFFSET	8		/* MaxOffset (resource length) */
/* bit 0 is reserved */
#define  PCI_EA_IS_64		0x00000002	/* 64-bit field flag */
#define  PCI_EA_FIELD_MASK	0xfffffffc	/* For Base & Max Offset */

/* PCI-X registers (Type 0 (non-bridge) devices) */

#define PCI_X_CMD		2	/* Modes & Features */
#define  PCI_X_CMD_DPERR_E	0x0001	/* Data Parity Error Recovery Enable */
#define  PCI_X_CMD_ERO		0x0002	/* Enable Relaxed Ordering */
#define  PCI_X_CMD_READ_512	0x0000	/* 512 byte maximum read byte count */
#define  PCI_X_CMD_READ_1K	0x0004	/* 1Kbyte maximum read byte count */
#define  PCI_X_CMD_READ_2K	0x0008	/* 2Kbyte maximum read byte count */
#define  PCI_X_CMD_READ_4K	0x000c	/* 4Kbyte maximum read byte count */
#define  PCI_X_CMD_MAX_READ	0x000c	/* Max Memory Read Byte Count */
				/* Max # of outstanding split transactions */
#define  PCI_X_CMD_SPLIT_1	0x0000	/* Max 1 */
#define  PCI_X_CMD_SPLIT_2	0x0010	/* Max 2 */
#define  PCI_X_CMD_SPLIT_3	0x0020	/* Max 3 */
#define  PCI_X_CMD_SPLIT_4	0x0030	/* Max 4 */
#define  PCI_X_CMD_SPLIT_8	0x0040	/* Max 8 */
#define  PCI_X_CMD_SPLIT_12	0x0050	/* Max 12 */
#define  PCI_X_CMD_SPLIT_16	0x0060	/* Max 16 */
#define  PCI_X_CMD_SPLIT_32	0x0070	/* Max 32 */
#define  PCI_X_CMD_MAX_SPLIT	0x0070	/* Max Outstanding Split Transactions */
#define  PCI_X_CMD_VERSION(x)	(((x) >> 12) & 3) /* Version */
#define PCI_X_STATUS		4	/* PCI-X capabilities */
#define  PCI_X_STATUS_DEVFN	0x000000ff	/* A copy of devfn */
#define  PCI_X_STATUS_BUS	0x0000ff00	/* A copy of bus nr */
#define  PCI_X_STATUS_64BIT	0x00010000	/* 64-bit device */
#define  PCI_X_STATUS_133MHZ	0x00020000	/* 133 MHz capable */
#define  PCI_X_STATUS_SPL_DISC	0x00040000	/* Split Completion Discarded */
#define  PCI_X_STATUS_UNX_SPL	0x00080000	/* Unexpected Split Completion */
#define  PCI_X_STATUS_COMPLEX	0x00100000	/* Device Complexity */
#define  PCI_X_STATUS_MAX_READ	0x00600000	/* Designed Max Memory Read Count */
#define  PCI_X_STATUS_MAX_SPLIT	0x03800000	/* Designed Max Outstanding Split Transactions */
#define  PCI_X_STATUS_MAX_CUM	0x1c000000	/* Designed Max Cumulative Read Size */
#define  PCI_X_STATUS_SPL_ERR	0x20000000	/* Rcvd Split Completion Error Msg */
#define  PCI_X_STATUS_266MHZ	0x40000000	/* 266 MHz capable */
#define  PCI_X_STATUS_533MHZ	0x80000000	/* 533 MHz capable */
#define PCI_X_ECC_CSR		8	/* ECC control and status */
#define PCI_CAP_PCIX_SIZEOF_V0	8	/* size of registers for Version 0 */
#define PCI_CAP_PCIX_SIZEOF_V1	24	/* size for Version 1 */
#define PCI_CAP_PCIX_SIZEOF_V2	PCI_CAP_PCIX_SIZEOF_V1	/* Same for v2 */

/* PCI-X registers (Type 1 (bridge) devices) */

#define PCI_X_BRIDGE_SSTATUS	2	/* Secondary Status */
#define  PCI_X_SSTATUS_64BIT	0x0001	/* Secondary AD interface is 64 bits */
#define  PCI_X_SSTATUS_133MHZ	0x0002	/* 133 MHz capable */
#define  PCI_X_SSTATUS_FREQ	0x03c0	/* Secondary Bus Mode and Frequency */
#define  PCI_X_SSTATUS_VERS	0x3000	/* PCI-X Capability Version */
#define  PCI_X_SSTATUS_V1	0x1000	/* Mode 2, not Mode 1 */
#define  PCI_X_SSTATUS_V2	0x2000	/* Mode 1 or Modes 1 and 2 */
#define  PCI_X_SSTATUS_266MHZ	0x4000	/* 266 MHz capable */
#define  PCI_X_SSTATUS_533MHZ	0x8000	/* 533 MHz capable */
#define PCI_X_BRIDGE_STATUS	4	/* Bridge Status */

/* PCI Bridge Subsystem ID registers */

#define PCI_SSVID_VENDOR_ID     4	/* PCI Bridge subsystem vendor ID */
#define PCI_SSVID_DEVICE_ID     6	/* PCI Bridge subsystem device ID */

/* PCI Express capability registers */

#define PCI_EXP_FLAGS		2	/* Capabilities register */
#define PCI_EXP_FLAGS_VERS	0x000f	/* Capability version */
#define PCI_EXP_FLAGS_TYPE	0x00f0	/* Device/Port type */
#define  PCI_EXP_TYPE_ENDPOINT	0x0	/* Express Endpoint */
#define  PCI_EXP_TYPE_LEG_END	0x1	/* Legacy Endpoint */
#define  PCI_EXP_TYPE_ROOT_PORT 0x4	/* Root Port */
#define  PCI_EXP_TYPE_UPSTREAM	0x5	/* Upstream Port */
#define  PCI_EXP_TYPE_DOWNSTREAM 0x6	/* Downstream Port */
#define  PCI_EXP_TYPE_PCI_BRIDGE 0x7	/* PCIe to PCI/PCI-X Bridge */
#define  PCI_EXP_TYPE_PCIE_BRIDGE 0x8	/* PCI/PCI-X to PCIe Bridge */
#define  PCI_EXP_TYPE_RC_END	0x9	/* Root Complex Integrated Endpoint */
#define  PCI_EXP_TYPE_RC_EC	0xa	/* Root Complex Event Collector */
#define PCI_EXP_FLAGS_SLOT	0x0100	/* Slot implemented */
#define PCI_EXP_FLAGS_IRQ	0x3e00	/* Interrupt message number */
#define PCI_EXP_DEVCAP		4	/* Device capabilities */
#define  PCI_EXP_DEVCAP_PAYLOAD	0x00000007 /* Max_Payload_Size */
#define  PCI_EXP_DEVCAP_PHANTOM	0x00000018 /* Phantom functions */
#define  PCI_EXP_DEVCAP_EXT_TAG	0x00000020 /* Extended tags */
#define  PCI_EXP_DEVCAP_L0S	0x000001c0 /* L0s Acceptable Latency */
#define  PCI_EXP_DEVCAP_L1	0x00000e00 /* L1 Acceptable Latency */
#define  PCI_EXP_DEVCAP_ATN_BUT	0x00001000 /* Attention Button Present */
#define  PCI_EXP_DEVCAP_ATN_IND	0x00002000 /* Attention Indicator Present */
#define  PCI_EXP_DEVCAP_PWR_IND	0x00004000 /* Power Indicator Present */
#define  PCI_EXP_DEVCAP_RBER	0x00008000 /* Role-Based Error Reporting */
#define  PCI_EXP_DEVCAP_PWR_VAL	0x03fc0000 /* Slot Power Limit Value */
#define  PCI_EXP_DEVCAP_PWR_SCL	0x0c000000 /* Slot Power Limit Scale */
#define  PCI_EXP_DEVCAP_FLR     0x10000000 /* Function Level Reset */
#define PCI_EXP_DEVCTL		8	/* Device Control */
#define  PCI_EXP_DEVCTL_CERE	0x0001	/* Correctable Error Reporting En. */
#define  PCI_EXP_DEVCTL_NFERE	0x0002	/* Non-Fatal Error Reporting Enable */
#define  PCI_EXP_DEVCTL_FERE	0x0004	/* Fatal Error Reporting Enable */
#define  PCI_EXP_DEVCTL_URRE	0x0008	/* Unsupported Request Reporting En. */
#define  PCI_EXP_DEVCTL_RELAX_EN 0x0010 /* Enable relaxed ordering */
#define  PCI_EXP_DEVCTL_PAYLOAD	0x00e0	/* Max_Payload_Size */
#define  PCI_EXP_DEVCTL_EXT_TAG	0x0100	/* Extended Tag Field Enable */
#define  PCI_EXP_DEVCTL_PHANTOM	0x0200	/* Phantom Functions Enable */
#define  PCI_EXP_DEVCTL_AUX_PME	0x0400	/* Auxiliary Power PM Enable */
#define  PCI_EXP_DEVCTL_NOSNOOP_EN 0x0800  /* Enable No Snoop */
#define  PCI_EXP_DEVCTL_READRQ	0x7000	/* Max_Read_Request_Size */
#define  PCI_EXP_DEVCTL_READRQ_128B  0x0000 /* 128 Bytes */
#define  PCI_EXP_DEVCTL_READRQ_256B  0x1000 /* 256 Bytes */
#define  PCI_EXP_DEVCTL_READRQ_512B  0x2000 /* 512 Bytes */
#define  PCI_EXP_DEVCTL_READRQ_1024B 0x3000 /* 1024 Bytes */
#define  PCI_EXP_DEVCTL_BCR_FLR 0x8000  /* Bridge Configuration Retry / FLR */
#define PCI_EXP_DEVSTA		10	/* Device Status */
#define  PCI_EXP_DEVSTA_CED	0x0001	/* Correctable Error Detected */
#define  PCI_EXP_DEVSTA_NFED	0x0002	/* Non-Fatal Error Detected */
#define  PCI_EXP_DEVSTA_FED	0x0004	/* Fatal Error Detected */
#define  PCI_EXP_DEVSTA_URD	0x0008	/* Unsupported Request Detected */
#define  PCI_EXP_DEVSTA_AUXPD	0x0010	/* AUX Power Detected */
#define  PCI_EXP_DEVSTA_TRPND	0x0020	/* Transactions Pending */
#define PCI_EXP_LNKCAP		12	/* Link Capabilities */
#define  PCI_EXP_LNKCAP_SLS	0x0000000f /* Supported Link Speeds */
#define  PCI_EXP_LNKCAP_SLS_2_5GB 0x00000001 /* LNKCAP2 SLS Vector bit 0 */
#define  PCI_EXP_LNKCAP_SLS_5_0GB 0x00000002 /* LNKCAP2 SLS Vector bit 1 */
#define  PCI_EXP_LNKCAP_MLW	0x000003f0 /* Maximum Link Width */
#define  PCI_EXP_LNKCAP_ASPMS	0x00000c00 /* ASPM Support */
#define  PCI_EXP_LNKCAP_L0SEL	0x00007000 /* L0s Exit Latency */
#define  PCI_EXP_LNKCAP_L1EL	0x00038000 /* L1 Exit Latency */
#define  PCI_EXP_LNKCAP_CLKPM	0x00040000 /* Clock Power Management */
#define  PCI_EXP_LNKCAP_SDERC	0x00080000 /* Surprise Down Error Reporting Capable */
#define  PCI_EXP_LNKCAP_DLLLARC	0x00100000 /* Data Link Layer Link Active Reporting Capable */
#define  PCI_EXP_LNKCAP_LBNC	0x00200000 /* Link Bandwidth Notification Capability */
#define  PCI_EXP_LNKCAP_PN	0xff000000 /* Port Number */
#define PCI_EXP_LNKCTL		16	/* Link Control */
#define  PCI_EXP_LNKCTL_ASPMC	0x0003	/* ASPM Control */
#define  PCI_EXP_LNKCTL_ASPM_L0S 0x0001	/* L0s Enable */
#define  PCI_EXP_LNKCTL_ASPM_L1  0x0002	/* L1 Enable */
#define  PCI_EXP_LNKCTL_RCB	0x0008	/* Read Completion Boundary */
#define  PCI_EXP_LNKCTL_LD	0x0010	/* Link Disable */
#define  PCI_EXP_LNKCTL_RL	0x0020	/* Retrain Link */
#define  PCI_EXP_LNKCTL_CCC	0x0040	/* Common Clock Configuration */
#define  PCI_EXP_LNKCTL_ES	0x0080	/* Extended Synch */
#define  PCI_EXP_LNKCTL_CLKREQ_EN 0x0100 /* Enable clkreq */
#define  PCI_EXP_LNKCTL_HAWD	0x0200	/* Hardware Autonomous Width Disable */
#define  PCI_EXP_LNKCTL_LBMIE	0x0400	/* Link Bandwidth Management Interrupt Enable */
#define  PCI_EXP_LNKCTL_LABIE	0x0800	/* Link Autonomous Bandwidth Interrupt Enable */
#define PCI_EXP_LNKSTA		18	/* Link Status */
#define  PCI_EXP_LNKSTA_CLS	0x000f	/* Current Link Speed */
#define  PCI_EXP_LNKSTA_CLS_2_5GB 0x0001 /* Current Link Speed 2.5GT/s */
#define  PCI_EXP_LNKSTA_CLS_5_0GB 0x0002 /* Current Link Speed 5.0GT/s */
#define  PCI_EXP_LNKSTA_CLS_8_0GB 0x0003 /* Current Link Speed 8.0GT/s */
#define  PCI_EXP_LNKSTA_NLW	0x03f0	/* Negotiated Link Width */
#define  PCI_EXP_LNKSTA_NLW_X1	0x0010	/* Current Link Width x1 */
#define  PCI_EXP_LNKSTA_NLW_X2	0x0020	/* Current Link Width x2 */
#define  PCI_EXP_LNKSTA_NLW_X4	0x0040	/* Current Link Width x4 */
#define  PCI_EXP_LNKSTA_NLW_X8	0x0080	/* Current Link Width x8 */
#define  PCI_EXP_LNKSTA_NLW_SHIFT 4	/* start of NLW mask in link status */
#define  PCI_EXP_LNKSTA_LT	0x0800	/* Link Training */
#define  PCI_EXP_LNKSTA_SLC	0x1000	/* Slot Clock Configuration */
#define  PCI_EXP_LNKSTA_DLLLA	0x2000	/* Data Link Layer Link Active */
#define  PCI_EXP_LNKSTA_LBMS	0x4000	/* Link Bandwidth Management Status */
#define  PCI_EXP_LNKSTA_LABS	0x8000	/* Link Autonomous Bandwidth Status */
#define PCI_CAP_EXP_ENDPOINT_SIZEOF_V1	20	/* v1 endpoints end here */
#define PCI_EXP_SLTCAP		20	/* Slot Capabilities */
#define  PCI_EXP_SLTCAP_ABP	0x00000001 /* Attention Button Present */
#define  PCI_EXP_SLTCAP_PCP	0x00000002 /* Power Controller Present */
#define  PCI_EXP_SLTCAP_MRLSP	0x00000004 /* MRL Sensor Present */
#define  PCI_EXP_SLTCAP_AIP	0x00000008 /* Attention Indicator Present */
#define  PCI_EXP_SLTCAP_PIP	0x00000010 /* Power Indicator Present */
#define  PCI_EXP_SLTCAP_HPS	0x00000020 /* Hot-Plug Surprise */
#define  PCI_EXP_SLTCAP_HPC	0x00000040 /* Hot-Plug Capable */
#define  PCI_EXP_SLTCAP_SPLV	0x00007f80 /* Slot Power Limit Value */
#define  PCI_EXP_SLTCAP_SPLS	0x00018000 /* Slot Power Limit Scale */
#define  PCI_EXP_SLTCAP_EIP	0x00020000 /* Electromechanical Interlock Present */
#define  PCI_EXP_SLTCAP_NCCS	0x00040000 /* No Command Completed Support */
#define  PCI_EXP_SLTCAP_PSN	0xfff80000 /* Physical Slot Number */
#define PCI_EXP_SLTCTL		24	/* Slot Control */
#define  PCI_EXP_SLTCTL_ABPE	0x0001	/* Attention Button Pressed Enable */
#define  PCI_EXP_SLTCTL_PFDE	0x0002	/* Power Fault Detected Enable */
#define  PCI_EXP_SLTCTL_MRLSCE	0x0004	/* MRL Sensor Changed Enable */
#define  PCI_EXP_SLTCTL_PDCE	0x0008	/* Presence Detect Changed Enable */
#define  PCI_EXP_SLTCTL_CCIE	0x0010	/* Command Completed Interrupt Enable */
#define  PCI_EXP_SLTCTL_HPIE	0x0020	/* Hot-Plug Interrupt Enable */
#define  PCI_EXP_SLTCTL_AIC	0x00c0	/* Attention Indicator Control */
#define  PCI_EXP_SLTCTL_ATTN_IND_ON    0x0040 /* Attention Indicator on */
#define  PCI_EXP_SLTCTL_ATTN_IND_BLINK 0x0080 /* Attention Indicator blinking */
#define  PCI_EXP_SLTCTL_ATTN_IND_OFF   0x00c0 /* Attention Indicator off */
#define  PCI_EXP_SLTCTL_PIC	0x0300	/* Power Indicator Control */
#define  PCI_EXP_SLTCTL_PWR_IND_ON     0x0100 /* Power Indicator on */
#define  PCI_EXP_SLTCTL_PWR_IND_BLINK  0x0200 /* Power Indicator blinking */
#define  PCI_EXP_SLTCTL_PWR_IND_OFF    0x0300 /* Power Indicator off */
#define  PCI_EXP_SLTCTL_PCC	0x0400	/* Power Controller Control */
#define  PCI_EXP_SLTCTL_PWR_ON         0x0000 /* Power On */
#define  PCI_EXP_SLTCTL_PWR_OFF        0x0400 /* Power Off */
#define  PCI_EXP_SLTCTL_EIC	0x0800	/* Electromechanical Interlock Control */
#define  PCI_EXP_SLTCTL_DLLSCE	0x1000	/* Data Link Layer State Changed Enable */
#define PCI_EXP_SLTSTA		26	/* Slot Status */
#define  PCI_EXP_SLTSTA_ABP	0x0001	/* Attention Button Pressed */
#define  PCI_EXP_SLTSTA_PFD	0x0002	/* Power Fault Detected */
#define  PCI_EXP_SLTSTA_MRLSC	0x0004	/* MRL Sensor Changed */
#define  PCI_EXP_SLTSTA_PDC	0x0008	/* Presence Detect Changed */
#define  PCI_EXP_SLTSTA_CC	0x0010	/* Command Completed */
#define  PCI_EXP_SLTSTA_MRLSS	0x0020	/* MRL Sensor State */
#define  PCI_EXP_SLTSTA_PDS	0x0040	/* Presence Detect State */
#define  PCI_EXP_SLTSTA_EIS	0x0080	/* Electromechanical Interlock Status */
#define  PCI_EXP_SLTSTA_DLLSC	0x0100	/* Data Link Layer State Changed */
#define PCI_EXP_RTCTL		28	/* Root Control */
#define  PCI_EXP_RTCTL_SECEE	0x0001	/* System Error on Correctable Error */
#define  PCI_EXP_RTCTL_SENFEE	0x0002	/* System Error on Non-Fatal Error */
#define  PCI_EXP_RTCTL_SEFEE	0x0004	/* System Error on Fatal Error */
#define  PCI_EXP_RTCTL_PMEIE	0x0008	/* PME Interrupt Enable */
#define  PCI_EXP_RTCTL_CRSSVE	0x0010	/* CRS Software Visibility Enable */
#define PCI_EXP_RTCAP		30	/* Root Capabilities */
#define  PCI_EXP_RTCAP_CRSVIS	0x0001	/* CRS Software Visibility capability */
#define PCI_EXP_RTSTA		32	/* Root Status */
#define PCI_EXP_RTSTA_PME	0x00010000 /* PME status */
#define PCI_EXP_RTSTA_PENDING	0x00020000 /* PME pending */
/*
 * The Device Capabilities 2, Device Status 2, Device Control 2,
 * Link Capabilities 2, Link Status 2, Link Control 2,
 * Slot Capabilities 2, Slot Status 2, and Slot Control 2 registers
 * are only present on devices with PCIe Capability version 2.
 * Use pcie_capability_read_word() and similar interfaces to use them
 * safely.
 */
#define PCI_EXP_DEVCAP2		36	/* Device Capabilities 2 */
#define  PCI_EXP_DEVCAP2_ARI		0x00000020 /* Alternative Routing-ID */
#define  PCI_EXP_DEVCAP2_LTR		0x00000800 /* Latency tolerance reporting */
#define  PCI_EXP_DEVCAP2_OBFF_MASK	0x000c0000 /* OBFF support mechanism */
#define  PCI_EXP_DEVCAP2_OBFF_MSG	0x00040000 /* New message signaling */
#define  PCI_EXP_DEVCAP2_OBFF_WAKE	0x00080000 /* Re-use WAKE# for OBFF */
#define PCI_EXP_DEVCTL2		40	/* Device Control 2 */
#define  PCI_EXP_DEVCTL2_COMP_TIMEOUT	0x000f	/* Completion Timeout Value */
#define  PCI_EXP_DEVCTL2_ARI		0x0020	/* Alternative Routing-ID */
#define  PCI_EXP_DEVCTL2_IDO_REQ_EN	0x0100	/* Allow IDO for requests */
#define  PCI_EXP_DEVCTL2_IDO_CMP_EN	0x0200	/* Allow IDO for completions */
#define  PCI_EXP_DEVCTL2_LTR_EN		0x0400	/* Enable LTR mechanism */
#define  PCI_EXP_DEVCTL2_OBFF_MSGA_EN	0x2000	/* Enable OBFF Message type A */
#define  PCI_EXP_DEVCTL2_OBFF_MSGB_EN	0x4000	/* Enable OBFF Message type B */
#define  PCI_EXP_DEVCTL2_OBFF_WAKE_EN	0x6000	/* OBFF using WAKE# signaling */
#define PCI_EXP_DEVSTA2		42	/* Device Status 2 */
#define PCI_CAP_EXP_ENDPOINT_SIZEOF_V2	44	/* v2 endpoints end here */
#define PCI_EXP_LNKCAP2		44	/* Link Capabilities 2 */
#define  PCI_EXP_LNKCAP2_SLS_2_5GB	0x00000002 /* Supported Speed 2.5GT/s */
#define  PCI_EXP_LNKCAP2_SLS_5_0GB	0x00000004 /* Supported Speed 5.0GT/s */
#define  PCI_EXP_LNKCAP2_SLS_8_0GB	0x00000008 /* Supported Speed 8.0GT/s */
#define  PCI_EXP_LNKCAP2_CROSSLINK	0x00000100 /* Crosslink supported */
#define PCI_EXP_LNKCTL2		48	/* Link Control 2 */
#define PCI_EXP_LNKSTA2		50	/* Link Status 2 */
#define PCI_EXP_SLTCAP2		52	/* Slot Capabilities 2 */
#define PCI_EXP_SLTCTL2		56	/* Slot Control 2 */
#define PCI_EXP_SLTSTA2		58	/* Slot Status 2 */

/* Extended Capabilities (PCI-X 2.0 and Express) */
#define PCI_EXT_CAP_ID(header)		(header & 0x0000ffff)
#define PCI_EXT_CAP_VER(header)		((header >> 16) & 0xf)
#define PCI_EXT_CAP_NEXT(header)	((header >> 20) & 0xffc)

#define PCI_EXT_CAP_ID_ERR	0x01	/* Advanced Error Reporting */
#define PCI_EXT_CAP_ID_VC	0x02	/* Virtual Channel Capability */
#define PCI_EXT_CAP_ID_DSN	0x03	/* Device Serial Number */
#define PCI_EXT_CAP_ID_PWR	0x04	/* Power Budgeting */
#define PCI_EXT_CAP_ID_RCLD	0x05	/* Root Complex Link Declaration */
#define PCI_EXT_CAP_ID_RCILC	0x06	/* Root Complex Internal Link Control */
#define PCI_EXT_CAP_ID_RCEC	0x07	/* Root Complex Event Collector */
#define PCI_EXT_CAP_ID_MFVC	0x08	/* Multi-Function VC Capability */
#define PCI_EXT_CAP_ID_VC9	0x09	/* same as _VC */
#define PCI_EXT_CAP_ID_RCRB	0x0A	/* Root Complex RB? */
#define PCI_EXT_CAP_ID_VNDR	0x0B	/* Vendor-Specific */
#define PCI_EXT_CAP_ID_CAC	0x0C	/* Config Access - obsolete */
#define PCI_EXT_CAP_ID_ACS	0x0D	/* Access Control Services */
#define PCI_EXT_CAP_ID_ARI	0x0E	/* Alternate Routing ID */
#define PCI_EXT_CAP_ID_ATS	0x0F	/* Address Translation Services */
#define PCI_EXT_CAP_ID_SRIOV	0x10	/* Single Root I/O Virtualization */
#define PCI_EXT_CAP_ID_MRIOV	0x11	/* Multi Root I/O Virtualization */
#define PCI_EXT_CAP_ID_MCAST	0x12	/* Multicast */
#define PCI_EXT_CAP_ID_PRI	0x13	/* Page Request Interface */
#define PCI_EXT_CAP_ID_AMD_XXX	0x14	/* Reserved for AMD */
#define PCI_EXT_CAP_ID_REBAR	0x15	/* Resizable BAR */
#define PCI_EXT_CAP_ID_DPA	0x16	/* Dynamic Power Allocation */
#define PCI_EXT_CAP_ID_TPH	0x17	/* TPH Requester */
#define PCI_EXT_CAP_ID_LTR	0x18	/* Latency Tolerance Reporting */
#define PCI_EXT_CAP_ID_SECPCI	0x19	/* Secondary PCIe Capability */
#define PCI_EXT_CAP_ID_PMUX	0x1A	/* Protocol Multiplexing */
#define PCI_EXT_CAP_ID_PASID	0x1B	/* Process Address Space ID */
#define PCI_EXT_CAP_ID_MAX	PCI_EXT_CAP_ID_PASID

#define PCI_EXT_CAP_DSN_SIZEOF	12
#define PCI_EXT_CAP_MCAST_ENDPOINT_SIZEOF 40

/* Advanced Error Reporting */
#define PCI_ERR_UNCOR_STATUS	4	/* Uncorrectable Error Status */
#define  PCI_ERR_UNC_UND	0x00000001	/* Undefined */
#define  PCI_ERR_UNC_DLP	0x00000010	/* Data Link Protocol */
#define  PCI_ERR_UNC_SURPDN	0x00000020	/* Surprise Down */
#define  PCI_ERR_UNC_POISON_TLP	0x00001000	/* Poisoned TLP */
#define  PCI_ERR_UNC_FCP	0x00002000	/* Flow Control Protocol */
#define  PCI_ERR_UNC_COMP_TIME	0x00004000	/* Completion Timeout */
#define  PCI_ERR_UNC_COMP_ABORT	0x00008000	/* Completer Abort */
#define  PCI_ERR_UNC_UNX_COMP	0x00010000	/* Unexpected Completion */
#define  PCI_ERR_UNC_RX_OVER	0x00020000	/* Receiver Overflow */
#define  PCI_ERR_UNC_MALF_TLP	0x00040000	/* Malformed TLP */
#define  PCI_ERR_UNC_ECRC	0x00080000	/* ECRC Error Status */
#define  PCI_ERR_UNC_UNSUP	0x00100000	/* Unsupported Request */
#define  PCI_ERR_UNC_ACSV	0x00200000	/* ACS Violation */
#define  PCI_ERR_UNC_INTN	0x00400000	/* internal error */
#define  PCI_ERR_UNC_MCBTLP	0x00800000	/* MC blocked TLP */
#define  PCI_ERR_UNC_ATOMEG	0x01000000	/* Atomic egress blocked */
#define  PCI_ERR_UNC_TLPPRE	0x02000000	/* TLP prefix blocked */
#define PCI_ERR_UNCOR_MASK	8	/* Uncorrectable Error Mask */
	/* Same bits as above */
#define PCI_ERR_UNCOR_SEVER	12	/* Uncorrectable Error Severity */
	/* Same bits as above */
#define PCI_ERR_COR_STATUS	16	/* Correctable Error Status */
#define  PCI_ERR_COR_RCVR	0x00000001	/* Receiver Error Status */
#define  PCI_ERR_COR_BAD_TLP	0x00000040	/* Bad TLP Status */
#define  PCI_ERR_COR_BAD_DLLP	0x00000080	/* Bad DLLP Status */
#define  PCI_ERR_COR_REP_ROLL	0x00000100	/* REPLAY_NUM Rollover */
#define  PCI_ERR_COR_REP_TIMER	0x00001000	/* Replay Timer Timeout */
#define  PCI_ERR_COR_ADV_NFAT	0x00002000	/* Advisory Non-Fatal */
#define  PCI_ERR_COR_INTERNAL	0x00004000	/* Corrected Internal */
#define  PCI_ERR_COR_LOG_OVER	0x00008000	/* Header Log Overflow */
#define PCI_ERR_COR_MASK	20	/* Correctable Error Mask */
	/* Same bits as above */
#define PCI_ERR_CAP		24	/* Advanced Error Capabilities */
#define  PCI_ERR_CAP_FEP(x)	((x) & 31)	/* First Error Pointer */
#define  PCI_ERR_CAP_ECRC_GENC	0x00000020	/* ECRC Generation Capable */
#define  PCI_ERR_CAP_ECRC_GENE	0x00000040	/* ECRC Generation Enable */
#define  PCI_ERR_CAP_ECRC_CHKC	0x00000080	/* ECRC Check Capable */
#define  PCI_ERR_CAP_ECRC_CHKE	0x00000100	/* ECRC Check Enable */
#define PCI_ERR_HEADER_LOG	28	/* Header Log Register (16 bytes) */
#define PCI_ERR_ROOT_COMMAND	44	/* Root Error Command */
/* Correctable Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_COR_EN		0x00000001
/* Non-fatal Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_NONFATAL_EN	0x00000002
/* Fatal Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_FATAL_EN	0x00000004
#define PCI_ERR_ROOT_STATUS	48
#define PCI_ERR_ROOT_COR_RCV		0x00000001	/* ERR_COR Received */
/* Multi ERR_COR Received */
#define PCI_ERR_ROOT_MULTI_COR_RCV	0x00000002
/* ERR_FATAL/NONFATAL Received */
#define PCI_ERR_ROOT_UNCOR_RCV		0x00000004
/* Multi ERR_FATAL/NONFATAL Received */
#define PCI_ERR_ROOT_MULTI_UNCOR_RCV	0x00000008
#define PCI_ERR_ROOT_FIRST_FATAL	0x00000010	/* First Fatal */
#define PCI_ERR_ROOT_NONFATAL_RCV	0x00000020	/* Non-Fatal Received */
#define PCI_ERR_ROOT_FATAL_RCV		0x00000040	/* Fatal Received */
#define PCI_ERR_ROOT_ERR_SRC	52	/* Error Source Identification */

/* Virtual Channel */
#define PCI_VC_PORT_CAP1	4
#define  PCI_VC_CAP1_EVCC	0x00000007	/* extended VC count */
#define  PCI_VC_CAP1_LPEVCC	0x00000070	/* low prio extended VC count */
#define  PCI_VC_CAP1_ARB_SIZE	0x00000c00
#define PCI_VC_PORT_CAP2	8
#define  PCI_VC_CAP2_32_PHASE		0x00000002
#define  PCI_VC_CAP2_64_PHASE		0x00000004
#define  PCI_VC_CAP2_128_PHASE		0x00000008
#define  PCI_VC_CAP2_ARB_OFF		0xff000000
#define PCI_VC_PORT_CTRL	12
#define  PCI_VC_PORT_CTRL_LOAD_TABLE	0x00000001
#define PCI_VC_PORT_STATUS	14
#define  PCI_VC_PORT_STATUS_TABLE	0x00000001
#define PCI_VC_RES_CAP		16
#define  PCI_VC_RES_CAP_32_PHASE	0x00000002
#define  PCI_VC_RES_CAP_64_PHASE	0x00000004
#define  PCI_VC_RES_CAP_128_PHASE	0x00000008
#define  PCI_VC_RES_CAP_128_PHASE_TB	0x00000010
#define  PCI_VC_RES_CAP_256_PHASE	0x00000020
#define  PCI_VC_RES_CAP_ARB_OFF		0xff000000
#define PCI_VC_RES_CTRL		20
#define  PCI_VC_RES_CTRL_LOAD_TABLE	0x00010000
#define  PCI_VC_RES_CTRL_ARB_SELECT	0x000e0000
#define  PCI_VC_RES_CTRL_ID		0x07000000
#define  PCI_VC_RES_CTRL_ENABLE		0x80000000
#define PCI_VC_RES_STATUS	26
#define  PCI_VC_RES_STATUS_TABLE	0x00000001
#define  PCI_VC_RES_STATUS_NEGO		0x00000002
#define PCI_CAP_VC_BASE_SIZEOF		0x10
#define PCI_CAP_VC_PER_VC_SIZEOF	0x0C

/* Power Budgeting */
#define PCI_PWR_DSR		4	/* Data Select Register */
#define PCI_PWR_DATA		8	/* Data Register */
#define  PCI_PWR_DATA_BASE(x)	((x) & 0xff)	    /* Base Power */
#define  PCI_PWR_DATA_SCALE(x)	(((x) >> 8) & 3)    /* Data Scale */
#define  PCI_PWR_DATA_PM_SUB(x)	(((x) >> 10) & 7)   /* PM Sub State */
#define  PCI_PWR_DATA_PM_STATE(x) (((x) >> 13) & 3) /* PM State */
#define  PCI_PWR_DATA_TYPE(x)	(((x) >> 15) & 7)   /* Type */
#define  PCI_PWR_DATA_RAIL(x)	(((x) >> 18) & 7)   /* Power Rail */
#define PCI_PWR_CAP		12	/* Capability */
#define  PCI_PWR_CAP_BUDGET(x)	((x) & 1)	/* Included in system budget */
#define PCI_EXT_CAP_PWR_SIZEOF	16

/* Vendor-Specific (VSEC, PCI_EXT_CAP_ID_VNDR) */
#define PCI_VNDR_HEADER		4	/* Vendor-Specific Header */
#define  PCI_VNDR_HEADER_ID(x)	((x) & 0xffff)
#define  PCI_VNDR_HEADER_REV(x)	(((x) >> 16) & 0xf)
#define  PCI_VNDR_HEADER_LEN(x)	(((x) >> 20) & 0xfff)

/*
 * HyperTransport sub capability types
 *
 * Unfortunately there are both 3 bit and 5 bit capability types defined
 * in the HT spec, catering for that is a little messy. You probably don't
 * want to use these directly, just use pci_find_ht_capability() and it
 * will do the right thing for you.
 */
#define HT_3BIT_CAP_MASK	0xE0
#define HT_CAPTYPE_SLAVE	0x00	/* Slave/Primary link configuration */
#define HT_CAPTYPE_HOST		0x20	/* Host/Secondary link configuration */

#define HT_5BIT_CAP_MASK	0xF8
#define HT_CAPTYPE_IRQ		0x80	/* IRQ Configuration */
#define HT_CAPTYPE_REMAPPING_40	0xA0	/* 40 bit address remapping */
#define HT_CAPTYPE_REMAPPING_64 0xA2	/* 64 bit address remapping */
#define HT_CAPTYPE_UNITID_CLUMP	0x90	/* Unit ID clumping */
#define HT_CAPTYPE_EXTCONF	0x98	/* Extended Configuration Space Access */
#define HT_CAPTYPE_MSI_MAPPING	0xA8	/* MSI Mapping Capability */
#define  HT_MSI_FLAGS		0x02		/* Offset to flags */
#define  HT_MSI_FLAGS_ENABLE	0x1		/* Mapping enable */
#define  HT_MSI_FLAGS_FIXED	0x2		/* Fixed mapping only */
#define  HT_MSI_FIXED_ADDR	0x00000000FEE00000ULL	/* Fixed addr */
#define  HT_MSI_ADDR_LO		0x04		/* Offset to low addr bits */
#define  HT_MSI_ADDR_LO_MASK	0xFFF00000	/* Low address bit mask */
#define  HT_MSI_ADDR_HI		0x08		/* Offset to high addr bits */
#define HT_CAPTYPE_DIRECT_ROUTE	0xB0	/* Direct routing configuration */
#define HT_CAPTYPE_VCSET	0xB8	/* Virtual Channel configuration */
#define HT_CAPTYPE_ERROR_RETRY	0xC0	/* Retry on error configuration */
#define HT_CAPTYPE_GEN3		0xD0	/* Generation 3 HyperTransport configuration */
#define HT_CAPTYPE_PM		0xE0	/* HyperTransport power management configuration */
#define HT_CAP_SIZEOF_LONG	28	/* slave & primary */
#define HT_CAP_SIZEOF_SHORT	24	/* host & secondary */

/* Alternative Routing-ID Interpretation */
#define PCI_ARI_CAP		0x04	/* ARI Capability Register */
#define  PCI_ARI_CAP_MFVC	0x0001	/* MFVC Function Groups Capability */
#define  PCI_ARI_CAP_ACS	0x0002	/* ACS Function Groups Capability */
#define  PCI_ARI_CAP_NFN(x)	(((x) >> 8) & 0xff) /* Next Function Number */
#define PCI_ARI_CTRL		0x06	/* ARI Control Register */
#define  PCI_ARI_CTRL_MFVC	0x0001	/* MFVC Function Groups Enable */
#define  PCI_ARI_CTRL_ACS	0x0002	/* ACS Function Groups Enable */
#define  PCI_ARI_CTRL_FG(x)	(((x) >> 4) & 7) /* Function Group */
#define PCI_EXT_CAP_ARI_SIZEOF	8

/* Address Translation Service */
#define PCI_ATS_CAP		0x04	/* ATS Capability Register */
#define  PCI_ATS_CAP_QDEP(x)	((x) & 0x1f)	/* Invalidate Queue Depth */
#define  PCI_ATS_MAX_QDEP	32	/* Max Invalidate Queue Depth */
#define PCI_ATS_CTRL		0x06	/* ATS Control Register */
#define  PCI_ATS_CTRL_ENABLE	0x8000	/* ATS Enable */
#define  PCI_ATS_CTRL_STU(x)	((x) & 0x1f)	/* Smallest Translation Unit */
#define  PCI_ATS_MIN_STU	12	/* shift of minimum STU block */
#define PCI_EXT_CAP_ATS_SIZEOF	8

/* Page Request Interface */
#define PCI_PRI_CTRL		0x04	/* PRI control register */
#define  PCI_PRI_CTRL_ENABLE	0x01	/* Enable */
#define  PCI_PRI_CTRL_RESET	0x02	/* Reset */
#define PCI_PRI_STATUS		0x06	/* PRI status register */
#define  PCI_PRI_STATUS_RF	0x001	/* Response Failure */
#define  PCI_PRI_STATUS_UPRGI	0x002	/* Unexpected PRG index */
#define  PCI_PRI_STATUS_STOPPED	0x100	/* PRI Stopped */
#define PCI_PRI_MAX_REQ		0x08	/* PRI max reqs supported */
#define PCI_PRI_ALLOC_REQ	0x0c	/* PRI max reqs allowed */
#define PCI_EXT_CAP_PRI_SIZEOF	16

/* Process Address Space ID */
#define PCI_PASID_CAP		0x04    /* PASID feature register */
#define  PCI_PASID_CAP_EXEC	0x02	/* Exec permissions Supported */
#define  PCI_PASID_CAP_PRIV	0x04	/* Privilege Mode Supported */
#define PCI_PASID_CTRL		0x06    /* PASID control register */
#define  PCI_PASID_CTRL_ENABLE	0x01	/* Enable bit */
#define  PCI_PASID_CTRL_EXEC	0x02	/* Exec permissions Enable */
#define  PCI_PASID_CTRL_PRIV	0x04	/* Privilege Mode Enable */
#define PCI_EXT_CAP_PASID_SIZEOF	8

/* Single Root I/O Virtualization */
#define PCI_SRIOV_CAP		0x04	/* SR-IOV Capabilities */
#define  PCI_SRIOV_CAP_VFM	0x01	/* VF Migration Capable */
#define  PCI_SRIOV_CAP_INTR(x)	((x) >> 21) /* Interrupt Message Number */
#define PCI_SRIOV_CTRL		0x08	/* SR-IOV Control */
#define  PCI_SRIOV_CTRL_VFE	0x01	/* VF Enable */
#define  PCI_SRIOV_CTRL_VFM	0x02	/* VF Migration Enable */
#define  PCI_SRIOV_CTRL_INTR	0x04	/* VF Migration Interrupt Enable */
#define  PCI_SRIOV_CTRL_MSE	0x08	/* VF Memory Space Enable */
#define  PCI_SRIOV_CTRL_ARI	0x10	/* ARI Capable Hierarchy */
#define PCI_SRIOV_STATUS	0x0a	/* SR-IOV Status */
#define  PCI_SRIOV_STATUS_VFM	0x01	/* VF Migration Status */
#define PCI_SRIOV_INITIAL_VF	0x0c	/* Initial VFs */
#define PCI_SRIOV_TOTAL_VF	0x0e	/* Total VFs */
#define PCI_SRIOV_NUM_VF	0x10	/* Number of VFs */
#define PCI_SRIOV_FUNC_LINK	0x12	/* Function Dependency Link */
#define PCI_SRIOV_VF_OFFSET	0x14	/* First VF Offset */
#define PCI_SRIOV_VF_STRIDE	0x16	/* Following VF Stride */
#define PCI_SRIOV_VF_DID	0x1a	/* VF Device ID */
#define PCI_SRIOV_SUP_PGSIZE	0x1c	/* Supported Page Sizes */
#define PCI_SRIOV_SYS_PGSIZE	0x20	/* System Page Size */
#define PCI_SRIOV_BAR		0x24	/* VF BAR0 */
#define  PCI_SRIOV_NUM_BARS	6	/* Number of VF BARs */
#define PCI_SRIOV_VFM		0x3c	/* VF Migration State Array Offset*/
#define  PCI_SRIOV_VFM_BIR(x)	((x) & 7)	/* State BIR */
#define  PCI_SRIOV_VFM_OFFSET(x) ((x) & ~7)	/* State Offset */
#define  PCI_SRIOV_VFM_UA	0x0	/* Inactive.Unavailable */
#define  PCI_SRIOV_VFM_MI	0x1	/* Dormant.MigrateIn */
#define  PCI_SRIOV_VFM_MO	0x2	/* Active.MigrateOut */
#define  PCI_SRIOV_VFM_AV	0x3	/* Active.Available */
#define PCI_EXT_CAP_SRIOV_SIZEOF 64

#define PCI_LTR_MAX_SNOOP_LAT	0x4
#define PCI_LTR_MAX_NOSNOOP_LAT	0x6
#define  PCI_LTR_VALUE_MASK	0x000003ff
#define  PCI_LTR_SCALE_MASK	0x00001c00
#define  PCI_LTR_SCALE_SHIFT	10
#define PCI_EXT_CAP_LTR_SIZEOF	8

/* Access Control Service */
#define PCI_ACS_CAP		0x04	/* ACS Capability Register */
#define  PCI_ACS_SV		0x01	/* Source Validation */
#define  PCI_ACS_TB		0x02	/* Translation Blocking */
#define  PCI_ACS_RR		0x04	/* P2P Request Redirect */
#define  PCI_ACS_CR		0x08	/* P2P Completion Redirect */
#define  PCI_ACS_UF		0x10	/* Upstream Forwarding */
#define  PCI_ACS_EC		0x20	/* P2P Egress Control */
#define  PCI_ACS_DT		0x40	/* Direct Translated P2P */
#define PCI_ACS_EGRESS_BITS	0x05	/* ACS Egress Control Vector Size */
#define PCI_ACS_CTRL		0x06	/* ACS Control Register */
#define PCI_ACS_EGRESS_CTL_V	0x08	/* ACS Egress Control Vector */

#define PCI_VSEC_HDR		4	/* extended cap - vendor-specific */
#define  PCI_VSEC_HDR_LEN_SHIFT	20	/* shift for length field */

/* SATA capability */
#define PCI_SATA_REGS		4	/* SATA REGs specifier */
#define  PCI_SATA_REGS_MASK	0xF	/* location - BAR#/inline */
#define  PCI_SATA_REGS_INLINE	0xF	/* REGS in config space */
#define PCI_SATA_SIZEOF_SHORT	8
#define PCI_SATA_SIZEOF_LONG	16

/* Resizable BARs */
#define PCI_REBAR_CTRL		8	/* control register */
#define  PCI_REBAR_CTRL_NBAR_MASK	(7 << 5)	/* mask for # bars */
#define  PCI_REBAR_CTRL_NBAR_SHIFT	5	/* shift for # bars */

/* Dynamic Power Allocation */
#define PCI_DPA_CAP		4	/* capability register */
#define  PCI_DPA_CAP_SUBSTATE_MASK	0x1F	/* # substates - 1 */
#define PCI_DPA_BASE_SIZEOF	16	/* size with 0 substates */

/* TPH Requester */
#define PCI_TPH_CAP		4	/* capability register */
#define  PCI_TPH_CAP_LOC_MASK	0x600	/* location mask */
#define   PCI_TPH_LOC_NONE	0x000	/* no location */
#define   PCI_TPH_LOC_CAP	0x200	/* in capability */
#define   PCI_TPH_LOC_MSIX	0x400	/* in MSI-X */
#define PCI_TPH_CAP_ST_MASK	0x07FF0000	/* st table mask */
#define PCI_TPH_CAP_ST_SHIFT	16	/* st table shift */
#define PCI_TPH_BASE_SIZEOF	12	/* size with no st table */

#endif /* LINUX_PCI_REGS_H */
                                                                           source/v64/tests/kvm-unit-tests/lib/linux/psci.h                                                    0000644 0000000 0000000 00000007426 00000000000 016765  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * ARM Power State and Coordination Interface (PSCI) header
 *
 * This header holds common PSCI defines and macros shared
 * by: ARM kernel, ARM64 kernel, KVM ARM/ARM64 and user space.
 *
 * Copyright (C) 2014 Linaro Ltd.
 * Author: Anup Patel <anup.patel@linaro.org>
 */

#ifndef _UAPI_LINUX_PSCI_H
#define _UAPI_LINUX_PSCI_H

/*
 * PSCI v0.1 interface
 *
 * The PSCI v0.1 function numbers are implementation defined.
 *
 * Only PSCI return values such as: SUCCESS, NOT_SUPPORTED,
 * INVALID_PARAMS, and DENIED defined below are applicable
 * to PSCI v0.1.
 */

/* PSCI v0.2 interface */
#define PSCI_0_2_FN_BASE			0x84000000
#define PSCI_0_2_FN(n)				(PSCI_0_2_FN_BASE + (n))
#define PSCI_0_2_64BIT				0x40000000
#define PSCI_0_2_FN64_BASE			\
					(PSCI_0_2_FN_BASE + PSCI_0_2_64BIT)
#define PSCI_0_2_FN64(n)			(PSCI_0_2_FN64_BASE + (n))

#define PSCI_0_2_FN_PSCI_VERSION		PSCI_0_2_FN(0)
#define PSCI_0_2_FN_CPU_SUSPEND			PSCI_0_2_FN(1)
#define PSCI_0_2_FN_CPU_OFF			PSCI_0_2_FN(2)
#define PSCI_0_2_FN_CPU_ON			PSCI_0_2_FN(3)
#define PSCI_0_2_FN_AFFINITY_INFO		PSCI_0_2_FN(4)
#define PSCI_0_2_FN_MIGRATE			PSCI_0_2_FN(5)
#define PSCI_0_2_FN_MIGRATE_INFO_TYPE		PSCI_0_2_FN(6)
#define PSCI_0_2_FN_MIGRATE_INFO_UP_CPU		PSCI_0_2_FN(7)
#define PSCI_0_2_FN_SYSTEM_OFF			PSCI_0_2_FN(8)
#define PSCI_0_2_FN_SYSTEM_RESET		PSCI_0_2_FN(9)

#define PSCI_0_2_FN64_CPU_SUSPEND		PSCI_0_2_FN64(1)
#define PSCI_0_2_FN64_CPU_ON			PSCI_0_2_FN64(3)
#define PSCI_0_2_FN64_AFFINITY_INFO		PSCI_0_2_FN64(4)
#define PSCI_0_2_FN64_MIGRATE			PSCI_0_2_FN64(5)
#define PSCI_0_2_FN64_MIGRATE_INFO_UP_CPU	PSCI_0_2_FN64(7)

#define PSCI_1_0_FN_PSCI_FEATURES		PSCI_0_2_FN(10)
#define PSCI_1_0_FN_SYSTEM_SUSPEND		PSCI_0_2_FN(14)

#define PSCI_1_0_FN64_SYSTEM_SUSPEND		PSCI_0_2_FN64(14)

/* PSCI v0.2 power state encoding for CPU_SUSPEND function */
#define PSCI_0_2_POWER_STATE_ID_MASK		0xffff
#define PSCI_0_2_POWER_STATE_ID_SHIFT		0
#define PSCI_0_2_POWER_STATE_TYPE_SHIFT		16
#define PSCI_0_2_POWER_STATE_TYPE_MASK		\
				(0x1 << PSCI_0_2_POWER_STATE_TYPE_SHIFT)
#define PSCI_0_2_POWER_STATE_AFFL_SHIFT		24
#define PSCI_0_2_POWER_STATE_AFFL_MASK		\
				(0x3 << PSCI_0_2_POWER_STATE_AFFL_SHIFT)

/* PSCI extended power state encoding for CPU_SUSPEND function */
#define PSCI_1_0_EXT_POWER_STATE_ID_MASK	0xfffffff
#define PSCI_1_0_EXT_POWER_STATE_ID_SHIFT	0
#define PSCI_1_0_EXT_POWER_STATE_TYPE_SHIFT	30
#define PSCI_1_0_EXT_POWER_STATE_TYPE_MASK	\
				(0x1 << PSCI_1_0_EXT_POWER_STATE_TYPE_SHIFT)

/* PSCI v0.2 affinity level state returned by AFFINITY_INFO */
#define PSCI_0_2_AFFINITY_LEVEL_ON		0
#define PSCI_0_2_AFFINITY_LEVEL_OFF		1
#define PSCI_0_2_AFFINITY_LEVEL_ON_PENDING	2

/* PSCI v0.2 multicore support in Trusted OS returned by MIGRATE_INFO_TYPE */
#define PSCI_0_2_TOS_UP_MIGRATE			0
#define PSCI_0_2_TOS_UP_NO_MIGRATE		1
#define PSCI_0_2_TOS_MP				2

/* PSCI version decoding (independent of PSCI version) */
#define PSCI_VERSION_MAJOR_SHIFT		16
#define PSCI_VERSION_MINOR_MASK			\
		((1U << PSCI_VERSION_MAJOR_SHIFT) - 1)
#define PSCI_VERSION_MAJOR_MASK			~PSCI_VERSION_MINOR_MASK
#define PSCI_VERSION_MAJOR(ver)			\
		(((ver) & PSCI_VERSION_MAJOR_MASK) >> PSCI_VERSION_MAJOR_SHIFT)
#define PSCI_VERSION_MINOR(ver)			\
		((ver) & PSCI_VERSION_MINOR_MASK)

/* PSCI features decoding (>=1.0) */
#define PSCI_1_0_FEATURES_CPU_SUSPEND_PF_SHIFT	1
#define PSCI_1_0_FEATURES_CPU_SUSPEND_PF_MASK	\
			(0x1 << PSCI_1_0_FEATURES_CPU_SUSPEND_PF_SHIFT)

/* PSCI return values (inclusive of all PSCI versions) */
#define PSCI_RET_SUCCESS			0
#define PSCI_RET_NOT_SUPPORTED			-1
#define PSCI_RET_INVALID_PARAMS			-2
#define PSCI_RET_DENIED				-3
#define PSCI_RET_ALREADY_ON			-4
#define PSCI_RET_ON_PENDING			-5
#define PSCI_RET_INTERNAL_FAILURE		-6
#define PSCI_RET_NOT_PRESENT			-7
#define PSCI_RET_DISABLED			-8
#define PSCI_RET_INVALID_ADDRESS		-9

#endif /* _UAPI_LINUX_PSCI_H */
                                                                                                                                                                                                                                          source/v64/tests/kvm-unit-tests/lib/pci-edu.c                                                       0000644 0000000 0000000 00000003360 00000000000 016202  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Edu PCI device.
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Authors:
 *   Peter Xu <peterx@redhat.com>,
 *
 * This work is licensed under the terms of the GNU LGPL, version 2 or
 * later.
 */

#include "pci-edu.h"
#include "asm/barrier.h"

/* Return true if alive */
static inline bool edu_check_alive(struct pci_edu_dev *dev)
{
	static uint32_t live_count = 1;
	uint32_t value;

	edu_reg_writel(dev, EDU_REG_ALIVE, live_count++);
	value = edu_reg_readl(dev, EDU_REG_ALIVE);
	return (live_count - 1 == ~value);
}

bool edu_init(struct pci_edu_dev *dev)
{
	pcidevaddr_t dev_addr;

	dev_addr = pci_find_dev(PCI_VENDOR_ID_QEMU, PCI_DEVICE_ID_EDU);
	if (dev_addr == PCIDEVADDR_INVALID)
		return false;

	pci_dev_init(&dev->pci_dev, dev_addr);
	pci_enable_defaults(&dev->pci_dev);
	dev->reg_base = ioremap(dev->pci_dev.resource[EDU_BAR], PAGE_SIZE);
	assert(edu_check_alive(dev));
	return true;
}

void edu_dma(struct pci_edu_dev *dev, iova_t iova,
	     size_t size, unsigned int dev_offset, bool from_device)
{
	uint64_t from, to;
	uint32_t cmd = EDU_CMD_DMA_START;

	assert(size <= EDU_DMA_SIZE_MAX);
	assert(dev_offset < EDU_DMA_SIZE_MAX);

	printf("edu device DMA start %s addr %#" PRIx64 " size %lu off %#x\n",
	       from_device ? "FROM" : "TO",
	       iova, (ulong)size, dev_offset);

	if (from_device) {
		from = dev_offset + EDU_DMA_START;
		to = iova;
		cmd |= EDU_CMD_DMA_FROM;
	} else {
		from = iova;
		to = EDU_DMA_START + dev_offset;
		cmd |= EDU_CMD_DMA_TO;
	}

	edu_reg_writeq(dev, EDU_REG_DMA_SRC, from);
	edu_reg_writeq(dev, EDU_REG_DMA_DST, to);
	edu_reg_writeq(dev, EDU_REG_DMA_COUNT, size);
	edu_reg_writel(dev, EDU_REG_DMA_CMD, cmd);

	/* Wait until DMA finished */
	while (edu_reg_readl(dev, EDU_REG_DMA_CMD) & EDU_CMD_DMA_START)
		cpu_relax();
}
                                                                                                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/lib/pci-edu.h                                                       0000644 0000000 0000000 00000004373 00000000000 016214  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Edu PCI device header.
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Authors:
 *   Peter Xu <peterx@redhat.com>,
 *
 * This work is licensed under the terms of the GNU LGPL, version 2 or
 * later.
 *
 * Edu device is a virtualized device in QEMU. Please refer to
 * docs/specs/edu.txt in QEMU repository for EDU device manual.
 */
#ifndef __PCI_EDU_H__
#define __PCI_EDU_H__

#include "pci.h"
#include "asm/io.h"

#define  PCI_VENDOR_ID_QEMU              0x1234
#define  PCI_DEVICE_ID_EDU               0x11e8

/* The only bar used by EDU device */
#define EDU_BAR                     0
#define EDU_MAGIC                   0xed
#define EDU_VERSION                 0x100
#define EDU_DMA_BUF_SIZE            (1 << 20)
#define EDU_INPUT_BUF_SIZE          256

#define EDU_REG_ID                  0x0
#define EDU_REG_ALIVE               0x4
#define EDU_REG_FACTORIAL           0x8
#define EDU_REG_STATUS              0x20
#define EDU_REG_INTR_STATUS         0x24
#define EDU_REG_INTR_RAISE          0x60
#define EDU_REG_INTR_ACK            0x64
#define EDU_REG_DMA_SRC             0x80
#define EDU_REG_DMA_DST             0x88
#define EDU_REG_DMA_COUNT           0x90
#define EDU_REG_DMA_CMD             0x98

#define EDU_CMD_DMA_START           0x01
#define EDU_CMD_DMA_FROM            0x02
#define EDU_CMD_DMA_TO              0x00

#define EDU_STATUS_FACTORIAL        0x1
#define EDU_STATUS_INT_ENABLE       0x80

#define EDU_DMA_START               0x40000
#define EDU_DMA_SIZE_MAX            4096

struct pci_edu_dev {
	struct pci_dev pci_dev;
	volatile void *reg_base;
};

#define edu_reg(d, r) (volatile void *)((d)->reg_base + (r))

static inline uint64_t edu_reg_readq(struct pci_edu_dev *dev, int reg)
{
	return __raw_readq(edu_reg(dev, reg));
}

static inline uint32_t edu_reg_readl(struct pci_edu_dev *dev, int reg)
{
	return __raw_readl(edu_reg(dev, reg));
}

static inline void edu_reg_writeq(struct pci_edu_dev *dev, int reg,
				  uint64_t val)
{
	__raw_writeq(val, edu_reg(dev, reg));
}

static inline void edu_reg_writel(struct pci_edu_dev *dev, int reg,
				  uint32_t val)
{
	__raw_writel(val, edu_reg(dev, reg));
}

bool edu_init(struct pci_edu_dev *dev);
void edu_dma(struct pci_edu_dev *dev, iova_t iova,
	     size_t size, unsigned int dev_offset, bool from_device);

#endif
                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/pci-host-generic.c                                              0000644 0000000 0000000 00000017115 00000000000 020017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Generic PCI host controller as described in PCI Bus Binding to Open Firmware
 *
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"
#include "devicetree.h"
#include "alloc.h"
#include "pci.h"
#include "asm/pci.h"
#include "asm/io.h"
#include "pci-host-generic.h"
#include <linux/pci_regs.h>

static struct pci_host_bridge *pci_host_bridge;

static int of_flags_to_pci_type(u32 of_flags)
{
	static int type_map[] = {
		[1] = PCI_BASE_ADDRESS_SPACE_IO,
		[2] = PCI_BASE_ADDRESS_MEM_TYPE_32,
		[3] = PCI_BASE_ADDRESS_MEM_TYPE_64
	};
	int idx = (of_flags >> 24) & 0x03;
	int res;

	assert(idx > 0);
	res = type_map[idx];

	if (of_flags & 0x40000000)
		res |= PCI_BASE_ADDRESS_MEM_PREFETCH;

	return res;
}

static int pci_bar_type(u32 bar)
{
	if (bar & PCI_BASE_ADDRESS_SPACE)
		return PCI_BASE_ADDRESS_SPACE_IO;
	else
		return bar & (PCI_BASE_ADDRESS_MEM_TYPE_MASK |
			      PCI_BASE_ADDRESS_MEM_PREFETCH);
}

/*
 * Probe DT for a generic PCI host controller
 * See kernel Documentation/devicetree/bindings/pci/host-generic-pci.txt
 * and function gen_pci_probe() in drivers/pci/host/pci-host-generic.c
 */
static struct pci_host_bridge *pci_dt_probe(void)
{
	struct pci_host_bridge *host;
	const void *fdt = dt_fdt();
	const struct fdt_property *prop;
	struct dt_pbus_reg base;
	struct dt_device dt_dev;
	struct dt_bus dt_bus;
	struct pci_addr_space *as;
	fdt32_t *data;
	u32 bus, bus_max;
	u32 nac, nsc, nac_root, nsc_root;
	int nr_range_cells, nr_addr_spaces;
	int ret, node, len, i;

	if (!dt_available()) {
		printf("No device tree found\n");
		return NULL;
	}

	dt_bus_init_defaults(&dt_bus);
	dt_device_init(&dt_dev, &dt_bus, NULL);

	node = fdt_path_offset(fdt, "/");
	assert(node >= 0);

	ret = dt_get_nr_cells(node, &nac_root, &nsc_root);
	assert(ret == 0);
	assert(nac_root == 1 || nac_root == 2);

	node = fdt_node_offset_by_compatible(fdt, node,
					     "pci-host-ecam-generic");
	if (node == -FDT_ERR_NOTFOUND) {
		printf("No PCIe ECAM compatible controller found\n");
		return NULL;
	}
	assert(node >= 0);

	prop = fdt_get_property(fdt, node, "device_type", &len);
	assert(prop && len == 4 && !strcmp((char *)prop->data, "pci"));

	dt_device_bind_node(&dt_dev, node);
	ret = dt_pbus_get_base(&dt_dev, &base);
	assert(ret == 0);

	prop = fdt_get_property(fdt, node, "bus-range", &len);
	if (prop == NULL) {
		assert(len == -FDT_ERR_NOTFOUND);
		bus		= 0x00;
		bus_max		= 0xff;
	} else {
		data		= (fdt32_t *)prop->data;
		bus		= fdt32_to_cpu(data[0]);
		bus_max		= fdt32_to_cpu(data[1]);
		assert(bus <= bus_max);
	}
	assert(bus_max < base.size / (1 << PCI_ECAM_BUS_SHIFT));

	ret = dt_get_nr_cells(node, &nac, &nsc);
	assert(ret == 0);
	assert(nac == 3 && nsc == 2);

	prop = fdt_get_property(fdt, node, "ranges", &len);
	assert(prop != NULL);

	nr_range_cells = nac + nsc + nac_root;
	nr_addr_spaces = (len / 4) / nr_range_cells;
	assert(nr_addr_spaces);

	host = malloc(sizeof(*host) +
		      sizeof(host->addr_space[0]) * nr_addr_spaces);
	assert(host != NULL);

	host->start		= base.addr;
	host->size		= base.size;
	host->bus		= bus;
	host->bus_max		= bus_max;
	host->nr_addr_spaces	= nr_addr_spaces;

	data = (fdt32_t *)prop->data;
	as = &host->addr_space[0];

	for (i = 0; i < nr_addr_spaces; i++) {
		/*
		 * The PCI binding encodes the PCI address with three
		 * cells as follows:
		 *
		 * phys.hi  cell: npt000ss bbbbbbbb dddddfff rrrrrrrr
		 * phys.mid cell: hhhhhhhh hhhhhhhh hhhhhhhh hhhhhhhh
		 * phys.lo  cell: llllllll llllllll llllllll llllllll
		 *
		 * PCI device bus address and flags are encoded into phys.high
		 * PCI 64 bit address is encoded into phys.mid and phys.low
		 */
		as->type = of_flags_to_pci_type(fdt32_to_cpu(data[0]));
		as->pci_start = ((u64)fdt32_to_cpu(data[1]) << 32) |
				fdt32_to_cpu(data[2]);

		if (nr_range_cells == 6) {
			as->start = fdt32_to_cpu(data[3]);
			as->size  = ((u64)fdt32_to_cpu(data[4]) << 32) |
				    fdt32_to_cpu(data[5]);
		} else {
			as->start = ((u64)fdt32_to_cpu(data[3]) << 32) |
				    fdt32_to_cpu(data[4]);
			as->size  = ((u64)fdt32_to_cpu(data[5]) << 32) |
				    fdt32_to_cpu(data[6]);
		}

		data += nr_range_cells;
		as++;
	}

	return host;
}

static bool pci_alloc_resource(struct pci_dev *dev, int bar_num, u64 *addr)
{
	struct pci_host_bridge *host = pci_host_bridge;
	struct pci_addr_space *as = &host->addr_space[0];
	u32 bar;
	u64 size, pci_addr;
	int type, i;

	*addr = INVALID_PHYS_ADDR;

	size = pci_bar_size(dev, bar_num);
	if (!size)
		return false;

	bar = pci_bar_get(dev, bar_num);
	type = pci_bar_type(bar);
	if (type & PCI_BASE_ADDRESS_MEM_TYPE_MASK)
		type &= ~PCI_BASE_ADDRESS_MEM_PREFETCH;

	for (i = 0; i < host->nr_addr_spaces; i++) {
		if (as->type == type)
			break;
		as++;
	}

	if (i >= host->nr_addr_spaces) {
		printf("%s: warning: can't satisfy request for ", __func__);
		pci_dev_print_id(dev);
		printf(" ");
		pci_bar_print(dev, bar_num);
		printf("\n");
		return false;
	}

	pci_addr = ALIGN(as->pci_start + as->allocated, size);
	size += pci_addr - (as->pci_start + as->allocated);
	assert(as->allocated + size <= as->size);
	*addr = pci_addr;
	as->allocated += size;

	return true;
}

bool pci_probe(void)
{
	struct pci_dev pci_dev;
	pcidevaddr_t dev;
	u8 header;
	u32 cmd;
	int i;

	assert(!pci_host_bridge);
	pci_host_bridge = pci_dt_probe();
	if (!pci_host_bridge)
		return false;

	for (dev = 0; dev < PCI_DEVFN_MAX; dev++) {
		if (!pci_dev_exists(dev))
			continue;

		pci_dev_init(&pci_dev, dev);

		/* We are only interested in normal PCI devices */
		header = pci_config_readb(dev, PCI_HEADER_TYPE);
		if ((header & PCI_HEADER_TYPE_MASK) != PCI_HEADER_TYPE_NORMAL)
			continue;

		cmd = PCI_COMMAND_SERR | PCI_COMMAND_PARITY;

		for (i = 0; i < PCI_BAR_NUM; i++) {
			u64 addr;

			if (pci_alloc_resource(&pci_dev, i, &addr)) {
				pci_bar_set_addr(&pci_dev, i, addr);

				if (pci_bar_is_memory(&pci_dev, i))
					cmd |= PCI_COMMAND_MEMORY;
				else
					cmd |= PCI_COMMAND_IO;
			}

			if (pci_bar_is64(&pci_dev, i))
				i++;
		}

		pci_config_writew(dev, PCI_COMMAND, cmd);
	}

	return true;
}

/*
 * This function is to be called from pci_translate_addr() to provide
 * mapping between this host bridge's PCI busses address and CPU physical
 * address.
 */
phys_addr_t pci_host_bridge_get_paddr(u64 pci_addr)
{
	struct pci_host_bridge *host = pci_host_bridge;
	struct pci_addr_space *as = &host->addr_space[0];
	int i;

	for (i = 0; i < host->nr_addr_spaces; i++) {
		if (pci_addr >= as->pci_start &&
		    pci_addr < as->pci_start + as->size)
			return as->start + (pci_addr - as->pci_start);
		as++;
	}

	return INVALID_PHYS_ADDR;
}

static void __iomem *pci_get_dev_conf(struct pci_host_bridge *host, int devfn)
{
	return (void __iomem *)(unsigned long)
		host->start + (devfn << PCI_ECAM_DEVFN_SHIFT);
}

u8 pci_config_readb(pcidevaddr_t dev, u8 off)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	return readb(conf + off);
}

u16 pci_config_readw(pcidevaddr_t dev, u8 off)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	return readw(conf + off);
}

u32 pci_config_readl(pcidevaddr_t dev, u8 off)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	return readl(conf + off);
}

void pci_config_writeb(pcidevaddr_t dev, u8 off, u8 val)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	writeb(val, conf + off);
}

void pci_config_writew(pcidevaddr_t dev, u8 off, u16 val)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	writew(val, conf + off);
}

void pci_config_writel(pcidevaddr_t dev, u8 off, u32 val)
{
	void __iomem *conf = pci_get_dev_conf(pci_host_bridge, dev);
	writel(val, conf + off);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/lib/pci-host-generic.h                                              0000644 0000000 0000000 00000002263 00000000000 020022  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef PCI_HOST_GENERIC_H
#define PCI_HOST_GENERIC_H
/*
 * PCI host bridge supporting structures and constants
 *
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

struct pci_addr_space {
	phys_addr_t		pci_start;
	phys_addr_t		start;
	phys_addr_t		size;
	phys_addr_t		allocated;
	int			type;
};

struct pci_host_bridge {
	phys_addr_t		start;
	phys_addr_t		size;
	int			bus;
	int			bus_max;
	int			nr_addr_spaces;
	struct pci_addr_space	addr_space[];
};

/*
 * The following constants are derived from Linux, see this source:
 *
 *         drivers/pci/host/pci-host-generic.c
 *                 struct gen_pci_cfg_bus_ops::bus_shift
 *                 int gen_pci_parse_map_cfg_windows(struct gen_pci *pci)
 *
 * Documentation/devicetree/bindings/pci/host-generic-pci.txt describes
 * ECAM Configuration Space is be memory-mapped by concatenating the various
 * components to form an offset:
 *
 *	cfg_offset(bus, device, function, register) =
 *		   bus << 20 | device << 15 | function << 12 | register
 */
#define PCI_ECAM_BUS_SHIFT	20
#define PCI_ECAM_DEVFN_SHIFT	12

#endif
                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/lib/pci-testdev.c                                                   0000644 0000000 0000000 00000010210 00000000000 017073  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * QEMU "pci-testdev" PCI test device
 *
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "pci.h"
#include "asm/io.h"

struct pci_testdev_ops {
	u8 (*io_readb)(const volatile void *addr);
	u16 (*io_readw)(const volatile void *addr);
	u32 (*io_readl)(const volatile void *addr);
	void (*io_writeb)(u8 value, volatile void *addr);
	void (*io_writew)(u16 value, volatile void *addr);
	void (*io_writel)(u32 value, volatile void *addr);
};

static u8 pio_readb(const volatile void *addr)
{
	return inb((unsigned long)addr);
}

static u16 pio_readw(const volatile void *addr)
{
	return inw((unsigned long)addr);
}

static u32 pio_readl(const volatile void *addr)
{
	return inl((unsigned long)addr);
}

static void pio_writeb(u8 value, volatile void *addr)
{
	outb(value, (unsigned long)addr);
}

static void pio_writew(u16 value, volatile void *addr)
{
	outw(value, (unsigned long)addr);
}

static void pio_writel(u32 value, volatile void *addr)
{
	outl(value, (unsigned long)addr);
}

static struct pci_testdev_ops pci_testdev_io_ops = {
	.io_readb	= pio_readb,
	.io_readw	= pio_readw,
	.io_readl	= pio_readl,
	.io_writeb	= pio_writeb,
	.io_writew	= pio_writew,
	.io_writel	= pio_writel
};

static u8 mmio_readb(const volatile void *addr)
{
	return *(const volatile u8 __force *)addr;
}

static u16 mmio_readw(const volatile void *addr)
{
	return *(const volatile u16 __force *)addr;
}

static u32 mmio_readl(const volatile void *addr)
{
	return *(const volatile u32 __force *)addr;
}

static void mmio_writeb(u8 value, volatile void *addr)
{
	*(volatile u8 __force *)addr = value;
}

static void mmio_writew(u16 value, volatile void *addr)
{
	*(volatile u16 __force *)addr = value;
}

static void mmio_writel(u32 value, volatile void *addr)
{
	*(volatile u32 __force *)addr = value;
}

static struct pci_testdev_ops pci_testdev_mem_ops = {
	.io_readb	= mmio_readb,
	.io_readw	= mmio_readw,
	.io_readl	= mmio_readl,
	.io_writeb	= mmio_writeb,
	.io_writew	= mmio_writew,
	.io_writel	= mmio_writel
};

static bool pci_testdev_one(struct pci_test_dev_hdr *test,
			    int test_nr,
			    struct pci_testdev_ops *ops)
{
	u8 width;
	u32 count, sig, off;
	const int nr_writes = 16;
	int i;

	ops->io_writeb(test_nr, &test->test);
	count = ops->io_readl(&test->count);
	if (count != 0)
		return false;

	width = ops->io_readb(&test->width);
	if (width != 1 && width != 2 && width != 4)
		return false;

	sig = ops->io_readl(&test->data);
	off = ops->io_readl(&test->offset);

	for (i = 0; i < nr_writes; i++) {
		switch (width) {
		case 1: ops->io_writeb(sig, (void *)test + off); break;
		case 2: ops->io_writew(sig, (void *)test + off); break;
		case 4: ops->io_writel(sig, (void *)test + off); break;
		}
	}

	count = ops->io_readl(&test->count);
	if (!count)
		return true;

	return (int)count == nr_writes;
}

static void pci_testdev_print(struct pci_test_dev_hdr *test,
			      struct pci_testdev_ops *ops)
{
	bool io = (ops == &pci_testdev_io_ops);
	int i;

	printf("pci-testdev %3s: ", io ? "io" : "mem");
	for (i = 0;; ++i) {
		char c = ops->io_readb(&test->name[i]);
		if (!c)
			break;
		printf("%c", c);
	}
	printf("\n");
}

static int pci_testdev_all(struct pci_test_dev_hdr *test,
			   struct pci_testdev_ops *ops)
{
	int i;

	for (i = 0;; i++) {
		if (!pci_testdev_one(test, i, ops))
			break;
		pci_testdev_print(test, ops);
	}

	return i;
}

int pci_testdev(void)
{
	struct pci_dev pci_dev;
	pcidevaddr_t dev;
	phys_addr_t addr;
	void __iomem *mem, *io;
	int nr_tests = 0;
	bool ret;

	dev = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
	if (dev == PCIDEVADDR_INVALID) {
		printf("'pci-testdev' device is not found, "
		       "check QEMU '-device pci-testdev' parameter\n");
		return -1;
	}
	pci_dev_init(&pci_dev, dev);

	ret = pci_bar_is_valid(&pci_dev, 0) && pci_bar_is_valid(&pci_dev, 1);
	assert(ret);

	addr = pci_bar_get_addr(&pci_dev, 0);
	mem = ioremap(addr, PAGE_SIZE);

	addr = pci_bar_get_addr(&pci_dev, 1);
	io = (void *)(unsigned long)addr;

	nr_tests += pci_testdev_all(mem, &pci_testdev_mem_ops);
	nr_tests += pci_testdev_all(io, &pci_testdev_io_ops);

	return nr_tests;
}
                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/pci.c                                                           0000644 0000000 0000000 00000021562 00000000000 015433  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2013, Red Hat Inc, Michael S. Tsirkin <mst@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include <linux/pci_regs.h>
#include "pci.h"
#include "asm/pci.h"

void pci_cap_walk(struct pci_dev *dev, pci_cap_handler_t handler)
{
	uint8_t cap_offset;
	uint8_t cap_id;
	int count = 0;

	cap_offset = pci_config_readb(dev->bdf, PCI_CAPABILITY_LIST);
	while (cap_offset) {
		cap_id = pci_config_readb(dev->bdf, cap_offset);
		assert(cap_id < PCI_CAP_ID_MAX + 1);
		handler(dev, cap_offset, cap_id);
		cap_offset = pci_config_readb(dev->bdf, cap_offset + 1);
		/* Avoid dead loop during cap walk */
		assert(++count <= 255);
	}
}

void pci_msi_set_enable(struct pci_dev *dev, bool enabled)
{
	uint16_t msi_control;
	uint16_t offset;

	offset = dev->msi_offset;
	msi_control = pci_config_readw(dev->bdf, offset + PCI_MSI_FLAGS);

	if (enabled)
		msi_control |= PCI_MSI_FLAGS_ENABLE;
	else
		msi_control &= ~PCI_MSI_FLAGS_ENABLE;

	pci_config_writew(dev->bdf, offset + PCI_MSI_FLAGS, msi_control);
}

bool pci_setup_msi(struct pci_dev *dev, uint64_t msi_addr, uint32_t msi_data)
{
	uint16_t msi_control;
	uint16_t offset;
	pcidevaddr_t addr;

	assert(dev);

	if (!dev->msi_offset) {
		printf("MSI: dev %#x does not support MSI.\n", dev->bdf);
		return false;
	}

	addr = dev->bdf;
	offset = dev->msi_offset;
	msi_control = pci_config_readw(addr, offset + PCI_MSI_FLAGS);
	pci_config_writel(addr, offset + PCI_MSI_ADDRESS_LO,
			  msi_addr & 0xffffffff);

	if (msi_control & PCI_MSI_FLAGS_64BIT) {
		pci_config_writel(addr, offset + PCI_MSI_ADDRESS_HI,
				  (uint32_t)(msi_addr >> 32));
		pci_config_writel(addr, offset + PCI_MSI_DATA_64, msi_data);
	} else {
		pci_config_writel(addr, offset + PCI_MSI_DATA_32, msi_data);
	}

	pci_msi_set_enable(dev, true);

	return true;
}

void pci_cmd_set_clr(struct pci_dev *dev, uint16_t set, uint16_t clr)
{
	uint16_t val = pci_config_readw(dev->bdf, PCI_COMMAND);

	/* No overlap is allowed */
	assert((set & clr) == 0);
	val |= set;
	val &= ~clr;

	pci_config_writew(dev->bdf, PCI_COMMAND, val);
}

bool pci_dev_exists(pcidevaddr_t dev)
{
	return (pci_config_readw(dev, PCI_VENDOR_ID) != 0xffff &&
		pci_config_readw(dev, PCI_DEVICE_ID) != 0xffff);
}

/* Scan bus look for a specific device. Only bus 0 scanned for now. */
pcidevaddr_t pci_find_dev(uint16_t vendor_id, uint16_t device_id)
{
	pcidevaddr_t dev;

	for (dev = 0; dev < PCI_DEVFN_MAX; ++dev) {
		if (pci_config_readw(dev, PCI_VENDOR_ID) == vendor_id &&
		    pci_config_readw(dev, PCI_DEVICE_ID) == device_id)
			return dev;
	}

	return PCIDEVADDR_INVALID;
}

uint32_t pci_bar_mask(uint32_t bar)
{
	return (bar & PCI_BASE_ADDRESS_SPACE_IO) ?
		PCI_BASE_ADDRESS_IO_MASK : PCI_BASE_ADDRESS_MEM_MASK;
}

uint32_t pci_bar_get(struct pci_dev *dev, int bar_num)
{
	ASSERT_BAR_NUM(bar_num);

	return pci_config_readl(dev->bdf, PCI_BASE_ADDRESS_0 +
				bar_num * 4);
}

static phys_addr_t __pci_bar_get_addr(struct pci_dev *dev, int bar_num)
{
	uint32_t bar = pci_bar_get(dev, bar_num);
	uint32_t mask = pci_bar_mask(bar);
	uint64_t addr = bar & mask;
	phys_addr_t phys_addr;

	if (pci_bar_is64(dev, bar_num))
		addr |= (uint64_t)pci_bar_get(dev, bar_num + 1) << 32;

	phys_addr = pci_translate_addr(dev->bdf, addr);
	assert(phys_addr != INVALID_PHYS_ADDR);

	return phys_addr;
}

phys_addr_t pci_bar_get_addr(struct pci_dev *dev, int bar_num)
{
	ASSERT_BAR_NUM(bar_num);

	return dev->resource[bar_num];
}

void pci_bar_set_addr(struct pci_dev *dev, int bar_num, phys_addr_t addr)
{
	int off = PCI_BASE_ADDRESS_0 + bar_num * 4;

	assert(addr != INVALID_PHYS_ADDR);
	assert(dev->resource[bar_num] != INVALID_PHYS_ADDR);

	ASSERT_BAR_NUM(bar_num);
	if (pci_bar_is64(dev, bar_num))
		ASSERT_BAR_NUM(bar_num + 1);
	else
		assert((addr >> 32) == 0);

	pci_config_writel(dev->bdf, off, (uint32_t)addr);
	dev->resource[bar_num] = addr;

	if (pci_bar_is64(dev, bar_num)) {
		pci_config_writel(dev->bdf, off + 4, (uint32_t)(addr >> 32));
		dev->resource[bar_num + 1] = dev->resource[bar_num];
	}
}

/*
 * To determine the amount of address space needed by a PCI device,
 * one must save the original value of the BAR, write a value of
 * all 1's to the register, and then read it back. The amount of
 * memory can be then determined by masking the information bits,
 * performing a bitwise NOT, and incrementing the value by 1.
 *
 * The following pci_bar_size_helper() and pci_bar_size() functions
 * implement the algorithm.
 */
static uint32_t pci_bar_size_helper(struct pci_dev *dev, int bar_num)
{
	int off = PCI_BASE_ADDRESS_0 + bar_num * 4;
	uint16_t bdf = dev->bdf;
	uint32_t bar, val;

	bar = pci_config_readl(bdf, off);
	pci_config_writel(bdf, off, ~0u);
	val = pci_config_readl(bdf, off);
	pci_config_writel(bdf, off, bar);

	return val;
}

phys_addr_t pci_bar_size(struct pci_dev *dev, int bar_num)
{
	uint32_t bar, size;

	size = pci_bar_size_helper(dev, bar_num);
	if (!size)
		return 0;

	bar = pci_bar_get(dev, bar_num);
	size &= pci_bar_mask(bar);

	if (pci_bar_is64(dev, bar_num)) {
		phys_addr_t size64 = pci_bar_size_helper(dev, bar_num + 1);
		size64 = (size64 << 32) | size;

		return ~size64 + 1;
	} else {
		return ~size + 1;
	}
}

bool pci_bar_is_memory(struct pci_dev *dev, int bar_num)
{
	uint32_t bar = pci_bar_get(dev, bar_num);

	return !(bar & PCI_BASE_ADDRESS_SPACE_IO);
}

bool pci_bar_is_valid(struct pci_dev *dev, int bar_num)
{
	return dev->resource[bar_num] != INVALID_PHYS_ADDR;
}

bool pci_bar_is64(struct pci_dev *dev, int bar_num)
{
	uint32_t bar = pci_bar_get(dev, bar_num);

	if (bar & PCI_BASE_ADDRESS_SPACE_IO)
		return false;

	return (bar & PCI_BASE_ADDRESS_MEM_TYPE_MASK) ==
		      PCI_BASE_ADDRESS_MEM_TYPE_64;
}

void pci_bar_print(struct pci_dev *dev, int bar_num)
{
	phys_addr_t size, start, end;
	uint32_t bar;

	if (!pci_bar_is_valid(dev, bar_num))
		return;

	bar = pci_bar_get(dev, bar_num);
	size = pci_bar_size(dev, bar_num);
	start = pci_bar_get_addr(dev, bar_num);
	end = start + size - 1;

	if (pci_bar_is64(dev, bar_num)) {
		printf("BAR#%d,%d [%" PRIx64 "-%" PRIx64 " ",
		       bar_num, bar_num + 1, start, end);
	} else {
		printf("BAR#%d [%02x-%02x ",
		       bar_num, (uint32_t)start, (uint32_t)end);
	}

	if (bar & PCI_BASE_ADDRESS_SPACE_IO) {
		printf("PIO");
	} else {
		printf("MEM");
		switch (bar & PCI_BASE_ADDRESS_MEM_TYPE_MASK) {
		case PCI_BASE_ADDRESS_MEM_TYPE_32:
			printf("32");
			break;
		case PCI_BASE_ADDRESS_MEM_TYPE_1M:
			printf("1M");
			break;
		case PCI_BASE_ADDRESS_MEM_TYPE_64:
			printf("64");
			break;
		default:
			assert(0);
		}
	}

	if (bar & PCI_BASE_ADDRESS_MEM_PREFETCH)
		printf("/p");

	printf("]");
}

void pci_dev_print_id(struct pci_dev *dev)
{
	pcidevaddr_t bdf = dev->bdf;

	printf("00.%02x.%1x %04x:%04x", bdf / 8, bdf % 8,
		pci_config_readw(bdf, PCI_VENDOR_ID),
		pci_config_readw(bdf, PCI_DEVICE_ID));
}

static void pci_cap_print(struct pci_dev *dev, int cap_offset, int cap_id)
{
	switch (cap_id) {
	case PCI_CAP_ID_MSI: {
		uint16_t control = pci_config_readw(dev->bdf, cap_offset + PCI_MSI_FLAGS);
		printf("\tMSI,%s-bit capability ", control & PCI_MSI_FLAGS_64BIT ? "64" : "32");
		break;
	}
	default:
		printf("\tcapability %#04x ", cap_id);
		break;
	}
	printf("at offset %#04x\n", cap_offset);
}

void pci_dev_print(struct pci_dev *dev)
{
	pcidevaddr_t bdf = dev->bdf;
	uint8_t header = pci_config_readb(bdf, PCI_HEADER_TYPE);
	uint8_t progif = pci_config_readb(bdf, PCI_CLASS_PROG);
	uint8_t subclass = pci_config_readb(bdf, PCI_CLASS_DEVICE);
	uint8_t class = pci_config_readb(bdf, PCI_CLASS_DEVICE + 1);
	int i;

	pci_dev_print_id(dev);
	printf(" type %02x progif %02x class %02x subclass %02x\n",
	       header, progif, class, subclass);

	pci_cap_walk(dev, pci_cap_print);

	if ((header & PCI_HEADER_TYPE_MASK) != PCI_HEADER_TYPE_NORMAL)
		return;

	for (i = 0; i < PCI_BAR_NUM; i++) {
		if (pci_bar_is_valid(dev, i)) {
			printf("\t");
			pci_bar_print(dev, i);
			printf("\n");
		}
		if (pci_bar_is64(dev, i))
			i++;
	}
}

void pci_print(void)
{
	pcidevaddr_t devfn;
	struct pci_dev pci_dev;

	for (devfn = 0; devfn < PCI_DEVFN_MAX; ++devfn) {
		if (pci_dev_exists(devfn)) {
			pci_dev_init(&pci_dev, devfn);
			pci_dev_print(&pci_dev);
		}
	}
}

void pci_dev_init(struct pci_dev *dev, pcidevaddr_t bdf)
{
	int i;

	memset(dev, 0, sizeof(*dev));
	dev->bdf = bdf;

	for (i = 0; i < PCI_BAR_NUM; i++) {
		if (pci_bar_size(dev, i)) {
			dev->resource[i] = __pci_bar_get_addr(dev, i);
			if (pci_bar_is64(dev, i)) {
				assert(i + 1 < PCI_BAR_NUM);
				dev->resource[i + 1] = dev->resource[i];
				i++;
			}
		} else {
			dev->resource[i] = INVALID_PHYS_ADDR;
		}
	}
}

uint8_t pci_intx_line(struct pci_dev *dev)
{
	return pci_config_readb(dev->bdf, PCI_INTERRUPT_LINE);
}

static void pci_cap_setup(struct pci_dev *dev, int cap_offset, int cap_id)
{
	switch (cap_id) {
	case PCI_CAP_ID_MSI:
		dev->msi_offset = cap_offset;
		break;
	}
}

void pci_enable_defaults(struct pci_dev *dev)
{
	/* Enable device DMA operations */
	pci_cmd_set_clr(dev, PCI_COMMAND_MASTER, 0);
	pci_cap_walk(dev, pci_cap_setup);
}
                                                                                                                                              source/v64/tests/kvm-unit-tests/lib/pci.h                                                           0000644 0000000 0000000 00000006565 00000000000 015446  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef PCI_H
#define PCI_H
/*
 * API for scanning a PCI bus for a given device, as well to access
 * BAR registers.
 *
 * Copyright (C) 2013, Red Hat Inc, Michael S. Tsirkin <mst@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

typedef uint16_t pcidevaddr_t;
enum {
	PCIDEVADDR_INVALID = 0xffff,
};

#define PCI_BAR_NUM                     6
#define PCI_DEVFN_MAX                   256

#define ASSERT_BAR_NUM(bar_num)	\
	do { assert(bar_num >= 0 && bar_num < PCI_BAR_NUM); } while (0)

#define PCI_BDF_GET_DEVFN(x)            ((x) & 0xff)
#define PCI_BDF_GET_BUS(x)              (((x) >> 8) & 0xff)

struct pci_dev {
	uint16_t bdf;
	uint16_t msi_offset;
	phys_addr_t resource[PCI_BAR_NUM];
};

extern void pci_dev_init(struct pci_dev *dev, pcidevaddr_t bdf);
extern void pci_cmd_set_clr(struct pci_dev *dev, uint16_t set, uint16_t clr);
typedef void (*pci_cap_handler_t)(struct pci_dev *dev, int cap_offset, int cap_id);
extern void pci_cap_walk(struct pci_dev *dev, pci_cap_handler_t handler);
extern void pci_enable_defaults(struct pci_dev *dev);
extern bool pci_setup_msi(struct pci_dev *dev, uint64_t msi_addr,
			  uint32_t msi_data);

typedef phys_addr_t iova_t;

extern bool pci_probe(void);
extern void pci_print(void);
extern bool pci_dev_exists(pcidevaddr_t dev);
extern pcidevaddr_t pci_find_dev(uint16_t vendor_id, uint16_t device_id);

/*
 * @bar_num in all BAR access functions below is the index of the 32-bit
 * register starting from the PCI_BASE_ADDRESS_0 offset.
 *
 * In cases where the BAR size is 64-bit, a caller should still provide
 * @bar_num in terms of 32-bit words. For example, if a device has a 64-bit
 * BAR#0 and a 32-bit BAR#1, then caller should provide 2 to address BAR#1,
 * not 1.
 *
 * It is expected the caller is aware of the device BAR layout and never
 * tries to address the middle of a 64-bit register.
 */
extern phys_addr_t pci_bar_get_addr(struct pci_dev *dev, int bar_num);
extern void pci_bar_set_addr(struct pci_dev *dev, int bar_num, phys_addr_t addr);
extern phys_addr_t pci_bar_size(struct pci_dev *dev, int bar_num);
extern uint32_t pci_bar_get(struct pci_dev *dev, int bar_num);
extern uint32_t pci_bar_mask(uint32_t bar);
extern bool pci_bar_is64(struct pci_dev *dev, int bar_num);
extern bool pci_bar_is_memory(struct pci_dev *dev, int bar_num);
extern bool pci_bar_is_valid(struct pci_dev *dev, int bar_num);
extern void pci_bar_print(struct pci_dev *dev, int bar_num);
extern void pci_dev_print_id(struct pci_dev *dev);
extern void pci_dev_print(struct pci_dev *dev);
extern uint8_t pci_intx_line(struct pci_dev *dev);
void pci_msi_set_enable(struct pci_dev *dev, bool enabled);

extern int pci_testdev(void);

/*
 * pci-testdev is a driver for the pci-testdev qemu pci device. The
 * device enables testing mmio and portio exits, and measuring their
 * speed.
 */
#define PCI_VENDOR_ID_REDHAT		0x1b36
#define PCI_DEVICE_ID_REDHAT_TEST	0x0005

/*
 * pci-testdev supports at least three types of tests (via mmio and
 * portio BARs): no-eventfd, wildcard-eventfd and datamatch-eventfd
 */
#define PCI_TESTDEV_BAR_MEM		0
#define PCI_TESTDEV_BAR_IO		1
#define PCI_TESTDEV_NUM_BARS		2
#define PCI_TESTDEV_NUM_TESTS		3

struct pci_test_dev_hdr {
	uint8_t  test;
	uint8_t  width;
	uint8_t  pad0[2];
	uint32_t offset;
	uint32_t data;
	uint32_t count;
	uint8_t  name[];
};

#define  PCI_HEADER_TYPE_MASK		0x7f

#endif /* PCI_H */
                                                                                                                                           source/v64/tests/kvm-unit-tests/lib/printf.c                                                        0000644 0000000 0000000 00000012634 00000000000 016162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libc printf and friends
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */

#include "libcflat.h"

#define BUFSZ 2000

typedef struct pstream {
    char *buffer;
    int remain;
    int added;
} pstream_t;

typedef struct strprops {
    char pad;
    int npad;
    bool alternate;
} strprops_t;

static void addchar(pstream_t *p, char c)
{
    if (p->remain) {
	*p->buffer++ = c;
	--p->remain;
    }
    ++p->added;
}

static void print_str(pstream_t *p, const char *s, strprops_t props)
{
    const char *s_orig = s;
    int npad = props.npad;

    if (npad > 0) {
	npad -= strlen(s_orig);
	while (npad > 0) {
	    addchar(p, props.pad);
	    --npad;
	}
    }

    while (*s)
	addchar(p, *s++);

    if (npad < 0) {
	props.pad = ' '; /* ignore '0' flag with '-' flag */
	npad += strlen(s_orig);
	while (npad < 0) {
	    addchar(p, props.pad);
	    ++npad;
	}
    }
}

static char digits[16] = "0123456789abcdef";

static void print_int(pstream_t *ps, long long n, int base, strprops_t props)
{
    char buf[sizeof(long) * 3 + 2], *p = buf;
    int s = 0, i;

    if (n < 0) {
	n = -n;
	s = 1;
    }

    while (n) {
	*p++ = digits[n % base];
	n /= base;
    }

    if (s)
	*p++ = '-';

    if (p == buf)
	*p++ = '0';

    for (i = 0; i < (p - buf) / 2; ++i) {
	char tmp;

	tmp = buf[i];
	buf[i] = p[-1-i];
	p[-1-i] = tmp;
    }

    *p = 0;

    print_str(ps, buf, props);
}

static void print_unsigned(pstream_t *ps, unsigned long long n, int base,
			   strprops_t props)
{
    char buf[sizeof(long) * 3 + 3], *p = buf;
    int i;

    while (n) {
	*p++ = digits[n % base];
	n /= base;
    }

    if (p == buf)
	*p++ = '0';
    else if (props.alternate && base == 16) {
	if (props.pad == '0') {
	    addchar(ps, '0');
	    addchar(ps, 'x');

	    if (props.npad > 0)
		props.npad = MAX(props.npad - 2, 0);
	} else {
	    *p++ = 'x';
	    *p++ = '0';
	}
    }

    for (i = 0; i < (p - buf) / 2; ++i) {
	char tmp;

	tmp = buf[i];
	buf[i] = p[-1-i];
	p[-1-i] = tmp;
    }

    *p = 0;

    print_str(ps, buf, props);
}

static int fmtnum(const char **fmt)
{
    const char *f = *fmt;
    int len = 0, num;

    if (*f == '-')
	++f, ++len;

    while (*f >= '0' && *f <= '9')
	++f, ++len;

    num = atol(*fmt);
    *fmt += len;
    return num;
}

int vsnprintf(char *buf, int size, const char *fmt, va_list va)
{
    pstream_t s;

    s.buffer = buf;
    s.remain = size - 1;
    s.added = 0;
    while (*fmt) {
	char f = *fmt++;
	int nlong = 0;
	strprops_t props;
	memset(&props, 0, sizeof(props));
	props.pad = ' ';

	if (f != '%') {
	    addchar(&s, f);
	    continue;
	}
    morefmt:
	f = *fmt++;
	switch (f) {
	case '%':
	    addchar(&s, '%');
	    break;
	case 'c':
            addchar(&s, va_arg(va, int));
	    break;
	case '\0':
	    --fmt;
	    break;
	case '#':
	    props.alternate = true;
	    goto morefmt;
	case '0':
	    props.pad = '0';
	    ++fmt;
	    /* fall through */
	case '1'...'9':
	case '-':
	    --fmt;
	    props.npad = fmtnum(&fmt);
	    goto morefmt;
	case 'l':
	    ++nlong;
	    goto morefmt;
	case 't':
	case 'z':
	    /* Here we only care that sizeof(size_t) == sizeof(long).
	     * On a 32-bit platform it doesn't matter that size_t is
	     * typedef'ed to int or long; va_arg will work either way.
	     * Same for ptrdiff_t (%td).
	     */
	    nlong = 1;
	    goto morefmt;
	case 'd':
	    switch (nlong) {
	    case 0:
		print_int(&s, va_arg(va, int), 10, props);
		break;
	    case 1:
		print_int(&s, va_arg(va, long), 10, props);
		break;
	    default:
		print_int(&s, va_arg(va, long long), 10, props);
		break;
	    }
	    break;
	case 'u':
	    switch (nlong) {
	    case 0:
		print_unsigned(&s, va_arg(va, unsigned), 10, props);
		break;
	    case 1:
		print_unsigned(&s, va_arg(va, unsigned long), 10, props);
		break;
	    default:
		print_unsigned(&s, va_arg(va, unsigned long long), 10, props);
		break;
	    }
	    break;
	case 'x':
	    switch (nlong) {
	    case 0:
		print_unsigned(&s, va_arg(va, unsigned), 16, props);
		break;
	    case 1:
		print_unsigned(&s, va_arg(va, unsigned long), 16, props);
		break;
	    default:
		print_unsigned(&s, va_arg(va, unsigned long long), 16, props);
		break;
	    }
	    break;
	case 'p':
	    props.alternate = true;
	    print_unsigned(&s, (unsigned long)va_arg(va, void *), 16, props);
	    break;
	case 's':
	    print_str(&s, va_arg(va, const char *), props);
	    break;
	default:
	    addchar(&s, f);
	    break;
	}
    }
    *s.buffer = 0;
    return s.added;
}


int snprintf(char *buf, int size, const char *fmt, ...)
{
    va_list va;
    int r;

    va_start(va, fmt);
    r = vsnprintf(buf, size, fmt, va);
    va_end(va);
    return r;
}

int vprintf(const char *fmt, va_list va)
{
    char buf[BUFSZ];
    int r;

    r = vsnprintf(buf, sizeof(buf), fmt, va);
    puts(buf);
    return r;
}

int printf(const char *fmt, ...)
{
    va_list va;
    char buf[BUFSZ];
    int r;

    va_start(va, fmt);
    r = vsnprintf(buf, sizeof buf, fmt, va);
    va_end(va);
    puts(buf);
    return r;
}

void binstr(unsigned long x, char out[BINSTR_SZ])
{
	int i;
	char *c;
	int n;

	n = sizeof(unsigned long) * 8;
	i = 0;
	c = &out[0];
	for (;;) {
		*c++ = (x & (1ul << (n - i - 1))) ? '1' : '0';
		i++;

		if (i == n) {
			*c = '\0';
			break;
		}
		if (i % 4 == 0)
			*c++ = '\'';
	}
	assert(c + 1 - &out[0] == BINSTR_SZ);
}

void print_binstr(unsigned long x)
{
	char out[BINSTR_SZ];
	binstr(x, out);
	printf("%s", out);
}
                                                                                                    source/v64/tests/kvm-unit-tests/lib/report.c                                                        0000644 0000000 0000000 00000006553 00000000000 016176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Test result reporting
 *
 * Copyright (c) Siemens AG, 2014
 *
 * Authors:
 *  Jan Kiszka <jan.kiszka@siemens.com>
 *  Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */

#include "libcflat.h"
#include "asm/spinlock.h"

static unsigned int tests, failures, xfailures, skipped;
static char prefixes[256];
static struct spinlock lock;

#define PREFIX_DELIMITER ": "

void report_pass(void)
{
	spin_lock(&lock);
	tests++;
	spin_unlock(&lock);
}

void report_prefix_pushf(const char *prefix_fmt, ...)
{
	va_list va;
	unsigned int len;
	int start;

	spin_lock(&lock);

	len = strlen(prefixes);
	assert_msg(len < sizeof(prefixes), "%d >= %zu", len, sizeof(prefixes));
	start = len;

	va_start(va, prefix_fmt);
	len += vsnprintf(&prefixes[len], sizeof(prefixes) - len, prefix_fmt,
			 va);
	va_end(va);
	assert_msg(len < sizeof(prefixes), "%d >= %zu", len, sizeof(prefixes));

	assert_msg(!strstr(&prefixes[start], PREFIX_DELIMITER),
		   "Prefix \"%s\" contains delimiter \"" PREFIX_DELIMITER "\"",
		   &prefixes[start]);

	len += snprintf(&prefixes[len], sizeof(prefixes) - len,
			PREFIX_DELIMITER);
	assert_msg(len < sizeof(prefixes), "%d >= %zu", len, sizeof(prefixes));

	spin_unlock(&lock);
}

void report_prefix_push(const char *prefix)
{
	report_prefix_pushf("%s", prefix);
}

void report_prefix_pop(void)
{
	char *p, *q;

	spin_lock(&lock);

	if (!*prefixes)
		return;

	for (p = prefixes, q = strstr(p, PREFIX_DELIMITER) + 2;
			*q;
			p = q, q = strstr(p, PREFIX_DELIMITER) + 2)
		;
	*p = '\0';

	spin_unlock(&lock);
}

static void va_report(const char *msg_fmt,
		bool pass, bool xfail, bool skip, va_list va)
{
	const char *prefix = skip ? "SKIP"
				  : xfail ? (pass ? "XPASS" : "XFAIL")
					  : (pass ? "PASS"  : "FAIL");

	spin_lock(&lock);

	tests++;
	printf("%s: ", prefix);
	puts(prefixes);
	vprintf(msg_fmt, va);
	puts("\n");
	if (skip)
		skipped++;
	else if (xfail && !pass)
		xfailures++;
	else if (xfail || !pass)
		failures++;

	spin_unlock(&lock);
}

void report(const char *msg_fmt, bool pass, ...)
{
	va_list va;
	va_start(va, pass);
	va_report(msg_fmt, pass, false, false, va);
	va_end(va);
}

void report_xfail(const char *msg_fmt, bool xfail, bool pass, ...)
{
	va_list va;
	va_start(va, pass);
	va_report(msg_fmt, pass, xfail, false, va);
	va_end(va);
}

void report_skip(const char *msg_fmt, ...)
{
	va_list va;
	va_start(va, msg_fmt);
	va_report(msg_fmt, false, false, true, va);
	va_end(va);
}

void report_info(const char *msg_fmt, ...)
{
	va_list va;

	spin_lock(&lock);
	puts("INFO: ");
	puts(prefixes);
	va_start(va, msg_fmt);
	vprintf(msg_fmt, va);
	va_end(va);
	puts("\n");
	spin_unlock(&lock);
}

int report_summary(void)
{
	spin_lock(&lock);

	printf("SUMMARY: %d tests", tests);
	if (failures)
		printf(", %d unexpected failures", failures);
	if (xfailures)
		printf(", %d expected failures", xfailures);
	if (skipped)
		printf(", %d skipped", skipped);
	printf("\n");

	if (tests == skipped)
		/* Blame AUTOTOOLS for using 77 for skipped test and QEMU for
		 * mangling error codes in a way that gets 77 if we ... */
		return 77 >> 1;

	return failures > 0 ? 1 : 0;

	spin_unlock(&lock);
}

void report_abort(const char *msg_fmt, ...)
{
	va_list va;

	spin_lock(&lock);
	puts("ABORT: ");
	puts(prefixes);
	va_start(va, msg_fmt);
	vprintf(msg_fmt, va);
	va_end(va);
	puts("\n");
	spin_unlock(&lock);
	report_summary();
	abort();
}
                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/setjmp.h                                                        0000644 0000000 0000000 00000000722 00000000000 016162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * setjmp/longjmp prototypes
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */
#ifndef LIBCFLAT_SETJMP_H
#define LIBCFLAT_SETJMP_H 1

typedef struct jmp_buf_tag {
	long int regs[8];
} jmp_buf[1];

extern int setjmp (struct jmp_buf_tag env[1]);
extern void longjmp (struct jmp_buf_tag env[1], int val)
     __attribute__ ((__noreturn__));

#endif /* setjmp.h  */
                                              source/v64/tests/kvm-unit-tests/lib/stack.c                                                         0000644 0000000 0000000 00000004334 00000000000 015763  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * stack related functions
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */

#include <libcflat.h>
#include <stack.h>

#define MAX_DEPTH 20

static void print_stack(const void **return_addrs, int depth,
			bool top_is_return_address)
{
	int i = 0;

	printf("\tSTACK:");

	/* @addr indicates a non-return address, as expected by the stack
	 * pretty printer script. */
	if (depth > 0 && !top_is_return_address) {
		printf(" @%lx", (unsigned long) return_addrs[0]);
		i++;
	}

	for (; i < depth; i++) {
		printf(" %lx", (unsigned long) return_addrs[i]);
	}
	printf("\n");
}

void dump_stack(void)
{
	const void *return_addrs[MAX_DEPTH];
	int depth;

	depth = backtrace(return_addrs, MAX_DEPTH);
	print_stack(&return_addrs[1], depth ? depth - 1 : 0, true);
}

void dump_frame_stack(const void *instruction, const void *frame)
{
	const void *return_addrs[MAX_DEPTH];
	int depth;

	return_addrs[0] = instruction;
	depth = backtrace_frame(frame, &return_addrs[1], MAX_DEPTH - 1);
	print_stack(return_addrs, depth + 1, false);
}

#ifndef HAVE_ARCH_BACKTRACE
int backtrace(const void **return_addrs, int max_depth)
{
	static int walking;
	int depth = 0;
	void *addr;

	if (walking) {
		printf("RECURSIVE STACK WALK!!!\n");
		return 0;
	}
	walking = 1;

	/* __builtin_return_address requires a compile-time constant argument */
#define GET_RETURN_ADDRESS(i)						\
	if (max_depth == i)						\
		goto done;						\
	addr = __builtin_return_address(i);				\
	if (!addr)							\
		goto done;						\
	return_addrs[i] = __builtin_extract_return_addr(addr);		\
	depth = i + 1;							\

	GET_RETURN_ADDRESS(0)
	GET_RETURN_ADDRESS(1)
	GET_RETURN_ADDRESS(2)
	GET_RETURN_ADDRESS(3)
	GET_RETURN_ADDRESS(4)
	GET_RETURN_ADDRESS(5)
	GET_RETURN_ADDRESS(6)
	GET_RETURN_ADDRESS(7)
	GET_RETURN_ADDRESS(8)
	GET_RETURN_ADDRESS(9)
	GET_RETURN_ADDRESS(10)
	GET_RETURN_ADDRESS(11)
	GET_RETURN_ADDRESS(12)
	GET_RETURN_ADDRESS(13)
	GET_RETURN_ADDRESS(14)
	GET_RETURN_ADDRESS(15)
	GET_RETURN_ADDRESS(16)
	GET_RETURN_ADDRESS(17)
	GET_RETURN_ADDRESS(18)
	GET_RETURN_ADDRESS(19)
	GET_RETURN_ADDRESS(20)

#undef GET_RETURN_ADDRESS

done:
	walking = 0;
	return depth;
}
#endif  /* HAVE_ARCH_BACKTRACE */
                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/lib/stack.h                                                         0000644 0000000 0000000 00000001164 00000000000 015766  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Header for stack related functions
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */
#ifndef _STACK_H_
#define _STACK_H_

#include <libcflat.h>
#include <asm/stack.h>

#ifdef HAVE_ARCH_BACKTRACE_FRAME
extern int backtrace_frame(const void *frame, const void **return_addrs,
			   int max_depth);
#else
static inline int
backtrace_frame(const void *frame __unused, const void **return_addrs __unused,
		int max_depth __unused)
{
	return 0;
}
#endif

extern int backtrace(const void **return_addrs, int max_depth);

#endif
                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/string.c                                                        0000644 0000000 0000000 00000007073 00000000000 016167  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * libc string functions
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */

#include "libcflat.h"

unsigned long strlen(const char *buf)
{
    unsigned long len = 0;

    while (*buf++)
	++len;
    return len;
}

char *strcat(char *dest, const char *src)
{
    char *p = dest;

    while (*p)
	++p;
    while ((*p++ = *src++) != 0)
	;
    return dest;
}

char *strcpy(char *dest, const char *src)
{
    *dest = 0;
    return strcat(dest, src);
}

int strncmp(const char *a, const char *b, size_t n)
{
    for (; n--; ++a, ++b)
        if (*a != *b || *a == '\0')
            return *a - *b;

    return 0;
}

int strcmp(const char *a, const char *b)
{
    return strncmp(a, b, SIZE_MAX);
}

char *strchr(const char *s, int c)
{
    while (*s != (char)c)
	if (*s++ == '\0')
	    return NULL;
    return (char *)s;
}

char *strstr(const char *s1, const char *s2)
{
    size_t l1, l2;

    l2 = strlen(s2);
    if (!l2)
	return (char *)s1;
    l1 = strlen(s1);
    while (l1 >= l2) {
	l1--;
	if (!memcmp(s1, s2, l2))
	    return (char *)s1;
	s1++;
    }
    return NULL;
}

void *memset(void *s, int c, size_t n)
{
    size_t i;
    char *a = s;

    for (i = 0; i < n; ++i)
        a[i] = c;

    return s;
}

void *memcpy(void *dest, const void *src, size_t n)
{
    size_t i;
    char *a = dest;
    const char *b = src;

    for (i = 0; i < n; ++i)
        a[i] = b[i];

    return dest;
}

int memcmp(const void *s1, const void *s2, size_t n)
{
    const unsigned char *a = s1, *b = s2;
    int ret = 0;

    while (n--) {
	ret = *a - *b;
	if (ret)
	    break;
	++a, ++b;
    }
    return ret;
}

void *memmove(void *dest, const void *src, size_t n)
{
    const unsigned char *s = src;
    unsigned char *d = dest;

    if (d <= s) {
	while (n--)
	    *d++ = *s++;
    } else {
	d += n, s += n;
	while (n--)
	    *--d = *--s;
    }
    return dest;
}

void *memchr(const void *s, int c, size_t n)
{
    const unsigned char *str = s, chr = (unsigned char)c;

    while (n--)
	if (*str++ == chr)
	    return (void *)(str - 1);
    return NULL;
}

long atol(const char *ptr)
{
    long acc = 0;
    const char *s = ptr;
    int neg, c;

    while (*s == ' ' || *s == '\t')
        s++;
    if (*s == '-'){
        neg = 1;
        s++;
    } else {
        neg = 0;
        if (*s == '+')
            s++;
    }

    while (*s) {
        if (*s < '0' || *s > '9')
            break;
        c = *s - '0';
        acc = acc * 10 + c;
        s++;
    }

    if (neg)
        acc = -acc;

    return acc;
}

extern char **environ;

char *getenv(const char *name)
{
    char **envp = environ, *delim;

    while (*envp) {
        delim = strchr(*envp, '=');
        if (delim && strncmp(name, *envp, delim - *envp) == 0)
            return delim + 1;
        ++envp;
    }
    return NULL;
}

/* Very simple glob matching. Allows '*' at beginning and end of pattern. */
bool simple_glob(const char *text, const char *pattern)
{
	bool star_start = false;
	bool star_end = false;
	size_t n = strlen(pattern);
	char copy[n + 1];

	if (pattern[0] == '*') {
		pattern += 1;
		n -= 1;
		star_start = true;
	}

	strcpy(copy, pattern);

	if (n > 0 && pattern[n - 1] == '*') {
		n -= 1;
		copy[n] = '\0';
		star_end = true;
	}

	if (star_start && star_end)
		return strstr(text, copy);

	if (star_end)
		return strstr(text, copy) == text;

	if (star_start) {
		size_t text_len = strlen(text);
		const char *suffix;

		if (n > text_len)
			return false;
		suffix = text + text_len - n;
		return !strcmp(suffix, copy);
	}

	return !strcmp(text, copy);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/string.h                                                        0000644 0000000 0000000 00000001600 00000000000 016162  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Header for libc string functions
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Library General Public License version 2.
 */
#ifndef __STRING_H
#define __STRING_H

extern unsigned long strlen(const char *buf);
extern char *strcat(char *dest, const char *src);
extern char *strcpy(char *dest, const char *src);
extern int strcmp(const char *a, const char *b);
extern int strncmp(const char *a, const char *b, size_t n);
extern char *strchr(const char *s, int c);
extern char *strstr(const char *haystack, const char *needle);
extern void *memset(void *s, int c, size_t n);
extern void *memcpy(void *dest, const void *src, size_t n);
extern int memcmp(const void *s1, const void *s2, size_t n);
extern void *memmove(void *dest, const void *src, size_t n);
extern void *memchr(const void *s, int c, size_t n);

#endif /* _STRING_H */
                                                                                                                                source/v64/tests/kvm-unit-tests/lib/util.c                                                          0000644 0000000 0000000 00000000500 00000000000 015622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright (C) 2016, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include <libcflat.h>
#include "util.h"

int parse_keyval(char *s, long *val)
{
	char *p;

	p = strchr(s, '=');
	if (!p)
		return -1;

	*val = atol(p+1);
	return p - s;
}
                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/lib/util.h                                                          0000644 0000000 0000000 00000001373 00000000000 015640  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _UTIL_H_
#define _UTIL_H_
/*
 * Collection of utility functions to share between unit tests.
 *
 * Copyright (C) 2016, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */

/*
 * parse_keyval extracts the integer from a string formatted as
 * string=integer. This is useful for passing expected values to
 * the unit test on the command line, i.e. it helps parse QEMU
 * command lines that include something like -append var1=1 var2=2
 * @s is the input string, likely a command line parameter, and
 * @val is a pointer to where the integer will be stored.
 *
 * Returns the offset of the '=', or -1 if no keyval pair is found.
 */
extern int parse_keyval(char *s, long *val);

#endif
                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/virtio-mmio.c                                                   0000644 0000000 0000000 00000010532 00000000000 017126  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * virtqueue support adapted from the Linux kernel.
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */
#include "libcflat.h"
#include "devicetree.h"
#include "alloc.h"
#include "asm/page.h"
#include "asm/io.h"
#include "virtio.h"
#include "virtio-mmio.h"

static void vm_get(struct virtio_device *vdev, unsigned offset,
		   void *buf, unsigned len)
{
	struct virtio_mmio_device *vm_dev = to_virtio_mmio_device(vdev);
	u8 *p = buf;
	unsigned i;

	for (i = 0; i < len; ++i)
		p[i] = readb(vm_dev->base + VIRTIO_MMIO_CONFIG + offset + i);
}

static void vm_set(struct virtio_device *vdev, unsigned offset,
		   const void *buf, unsigned len)
{
	struct virtio_mmio_device *vm_dev = to_virtio_mmio_device(vdev);
	const u8 *p = buf;
	unsigned i;

	for (i = 0; i < len; ++i)
		writeb(p[i], vm_dev->base + VIRTIO_MMIO_CONFIG + offset + i);
}

static bool vm_notify(struct virtqueue *vq)
{
	struct virtio_mmio_device *vm_dev = to_virtio_mmio_device(vq->vdev);
	writel(vq->index, vm_dev->base + VIRTIO_MMIO_QUEUE_NOTIFY);
	return true;
}

static struct virtqueue *vm_setup_vq(struct virtio_device *vdev,
				     unsigned index,
				     void (*callback)(struct virtqueue *vq),
				     const char *name)
{
	struct virtio_mmio_device *vm_dev = to_virtio_mmio_device(vdev);
	struct vring_virtqueue *vq;
	void *queue;
	unsigned num = VIRTIO_MMIO_QUEUE_NUM_MIN;

	vq = calloc(1, sizeof(*vq));
	queue = memalign(PAGE_SIZE, VIRTIO_MMIO_QUEUE_SIZE_MIN);
	assert(vq && queue);

	writel(index, vm_dev->base + VIRTIO_MMIO_QUEUE_SEL);

	assert(readl(vm_dev->base + VIRTIO_MMIO_QUEUE_NUM_MAX) >= num);

	if (readl(vm_dev->base + VIRTIO_MMIO_QUEUE_PFN) != 0) {
		printf("%s: virtqueue %d already setup! base=%p\n",
				__func__, index, vm_dev->base);
		return NULL;
	}

	writel(num, vm_dev->base + VIRTIO_MMIO_QUEUE_NUM);
	writel(VIRTIO_MMIO_VRING_ALIGN,
			vm_dev->base + VIRTIO_MMIO_QUEUE_ALIGN);
	writel(virt_to_pfn(queue), vm_dev->base + VIRTIO_MMIO_QUEUE_PFN);

	vring_init_virtqueue(vq, index, num, VIRTIO_MMIO_VRING_ALIGN,
			     vdev, queue, vm_notify, callback, name);

	return &vq->vq;
}

static int vm_find_vqs(struct virtio_device *vdev, unsigned nvqs,
		       struct virtqueue *vqs[], vq_callback_t *callbacks[],
		       const char *names[])
{
	unsigned i;

	for (i = 0; i < nvqs; ++i) {
		vqs[i] = vm_setup_vq(vdev, i,
				     callbacks ? callbacks[i] : NULL,
				     names ? names[i] : "");
		if (vqs[i] == NULL)
			return -1;
	}

	return 0;
}

static const struct virtio_config_ops vm_config_ops = {
	.get = vm_get,
	.set = vm_set,
	.find_vqs = vm_find_vqs,
};

static void vm_device_init(struct virtio_mmio_device *vm_dev)
{
	vm_dev->vdev.id.device = readl(vm_dev->base + VIRTIO_MMIO_DEVICE_ID);
	vm_dev->vdev.id.vendor = readl(vm_dev->base + VIRTIO_MMIO_VENDOR_ID);
	vm_dev->vdev.config = &vm_config_ops;

	writel(PAGE_SIZE, vm_dev->base + VIRTIO_MMIO_GUEST_PAGE_SIZE);
}

/******************************************************
 * virtio-mmio device tree support
 ******************************************************/

struct vm_dt_info {
	u32 devid;
	void *base;
};

static int vm_dt_match(const struct dt_device *dev, int fdtnode)
{
	struct vm_dt_info *info = (struct vm_dt_info *)dev->info;
	struct dt_pbus_reg base;
	u32 magic;
	int ret;

	dt_device_bind_node((struct dt_device *)dev, fdtnode);

	ret = dt_pbus_get_base(dev, &base);
	assert(ret == 0);
	info->base = ioremap(base.addr, base.size);

	magic = readl(info->base + VIRTIO_MMIO_MAGIC_VALUE);
	if (magic != ('v' | 'i' << 8 | 'r' << 16 | 't' << 24))
		return false;

	return readl(info->base + VIRTIO_MMIO_DEVICE_ID) == info->devid;
}

static struct virtio_device *virtio_mmio_dt_bind(u32 devid)
{
	struct virtio_mmio_device *vm_dev;
	struct dt_device dt_dev;
	struct dt_bus dt_bus;
	struct vm_dt_info info;
	int node;

	if (!dt_available())
		return NULL;

	dt_bus_init_defaults(&dt_bus);
	dt_bus.match = vm_dt_match;

	info.devid = devid;

	dt_device_init(&dt_dev, &dt_bus, &info);

	node = dt_device_find_compatible(&dt_dev, "virtio,mmio");
	assert(node >= 0 || node == -FDT_ERR_NOTFOUND);

	if (node == -FDT_ERR_NOTFOUND)
		return NULL;

	vm_dev = calloc(1, sizeof(*vm_dev));
	assert(vm_dev != NULL);

	vm_dev->base = info.base;
	vm_device_init(vm_dev);

	return &vm_dev->vdev;
}

struct virtio_device *virtio_mmio_bind(u32 devid)
{
	return virtio_mmio_dt_bind(devid);
}
                                                                                                                                                                      source/v64/tests/kvm-unit-tests/lib/virtio-mmio.h                                                   0000644 0000000 0000000 00000004024 00000000000 017132  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _VIRTIO_MMIO_H_
#define _VIRTIO_MMIO_H_
/*
 * A minimal implementation of virtio-mmio. Adapted from the Linux Kernel.
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */
#include "libcflat.h"
#include "asm/page.h"
#include "virtio.h"

#define VIRTIO_MMIO_MAGIC_VALUE		0x000
#define VIRTIO_MMIO_VERSION		0x004
#define VIRTIO_MMIO_DEVICE_ID		0x008
#define VIRTIO_MMIO_VENDOR_ID		0x00c
#define VIRTIO_MMIO_HOST_FEATURES	0x010
#define VIRTIO_MMIO_HOST_FEATURES_SEL	0x014
#define VIRTIO_MMIO_GUEST_FEATURES	0x020
#define VIRTIO_MMIO_GUEST_FEATURES_SEL	0x024
#define VIRTIO_MMIO_GUEST_PAGE_SIZE	0x028
#define VIRTIO_MMIO_QUEUE_SEL		0x030
#define VIRTIO_MMIO_QUEUE_NUM_MAX	0x034
#define VIRTIO_MMIO_QUEUE_NUM		0x038
#define VIRTIO_MMIO_QUEUE_ALIGN		0x03c
#define VIRTIO_MMIO_QUEUE_PFN		0x040
#define VIRTIO_MMIO_QUEUE_NOTIFY	0x050
#define VIRTIO_MMIO_INTERRUPT_STATUS	0x060
#define VIRTIO_MMIO_INTERRUPT_ACK	0x064
#define VIRTIO_MMIO_STATUS		0x070
#define VIRTIO_MMIO_CONFIG		0x100

#define VIRTIO_MMIO_INT_VRING		(1 << 0)
#define VIRTIO_MMIO_INT_CONFIG		(1 << 1)

#define VIRTIO_MMIO_VRING_ALIGN		PAGE_SIZE

/*
 * The minimum queue size is 2*VIRTIO_MMIO_VRING_ALIGN, which
 * means the largest queue num for the minimum queue size is 128, i.e.
 * 2*VIRTIO_MMIO_VRING_ALIGN = vring_size(128, VIRTIO_MMIO_VRING_ALIGN),
 * where vring_size is
 *
 * unsigned vring_size(unsigned num, unsigned long align)
 * {
 *     return ((sizeof(struct vring_desc) * num + sizeof(u16) * (3 + num)
 *              + align - 1) & ~(align - 1))
 *             + sizeof(u16) * 3 + sizeof(struct vring_used_elem) * num;
 * }
 */
#define VIRTIO_MMIO_QUEUE_SIZE_MIN	(2*VIRTIO_MMIO_VRING_ALIGN)
#define VIRTIO_MMIO_QUEUE_NUM_MIN	128

#define to_virtio_mmio_device(vdev_ptr) \
	container_of(vdev_ptr, struct virtio_mmio_device, vdev)

struct virtio_mmio_device {
	struct virtio_device vdev;
	void *base;
};

extern struct virtio_device *virtio_mmio_bind(u32 devid);

#endif /* _VIRTIO_MMIO_H_ */
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/virtio.c                                                        0000644 0000000 0000000 00000005244 00000000000 016173  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * virtqueue support adapted from the Linux kernel.
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */
#include "libcflat.h"
#include "asm/io.h"
#include "virtio.h"
#include "virtio-mmio.h"

void vring_init(struct vring *vr, unsigned int num, void *p,
		       unsigned long align)
{
	vr->num = num;
	vr->desc = p;
	vr->avail = p + num*sizeof(struct vring_desc);
	vr->used = (void *)(((unsigned long)&vr->avail->ring[num] + sizeof(u16)
		+ align-1) & ~(align - 1));
}

void vring_init_virtqueue(struct vring_virtqueue *vq, unsigned index,
			  unsigned num, unsigned vring_align,
			  struct virtio_device *vdev, void *pages,
			  bool (*notify)(struct virtqueue *),
			  void (*callback)(struct virtqueue *),
			  const char *name)
{
	unsigned i;

	vring_init(&vq->vring, num, pages, vring_align);
	vq->vq.callback = callback;
	vq->vq.vdev = vdev;
	vq->vq.name = name;
	vq->vq.num_free = num;
	vq->vq.index = index;
	vq->notify = notify;
	vq->last_used_idx = 0;
	vq->num_added = 0;
	vq->free_head = 0;

	for (i = 0; i < num-1; i++) {
		vq->vring.desc[i].next = i+1;
		vq->data[i] = NULL;
	}
	vq->data[i] = NULL;
}

int virtqueue_add_outbuf(struct virtqueue *_vq, char *buf, unsigned int len)
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	unsigned avail;
	int head;

	assert(buf != NULL);
	assert(len != 0);

	if (!vq->vq.num_free)
		return -1;

	--vq->vq.num_free;

	head = vq->free_head;

	vq->vring.desc[head].flags = 0;
	vq->vring.desc[head].addr = virt_to_phys(buf);
	vq->vring.desc[head].len = len;

	vq->free_head = vq->vring.desc[head].next;

	vq->data[head] = buf;

	avail = (vq->vring.avail->idx & (vq->vring.num-1));
	vq->vring.avail->ring[avail] = head;
	wmb();
	vq->vring.avail->idx++;
	vq->num_added++;

	return 0;
}

bool virtqueue_kick(struct virtqueue *_vq)
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	mb();
	return vq->notify(_vq);
}

void detach_buf(struct vring_virtqueue *vq, unsigned head)
{
	unsigned i = head;

	vq->data[head] = NULL;

	while (vq->vring.desc[i].flags & VRING_DESC_F_NEXT) {
		i = vq->vring.desc[i].next;
		vq->vq.num_free++;
	}

	vq->vring.desc[i].next = vq->free_head;
	vq->free_head = head;
	vq->vq.num_free++;
}

void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len)
{
	struct vring_virtqueue *vq = to_vvq(_vq);
	u16 last_used;
	unsigned i;
	void *ret;

	rmb();

	last_used = (vq->last_used_idx & (vq->vring.num-1));
	i = vq->vring.used->ring[last_used].id;
	*len = vq->vring.used->ring[last_used].len;

	ret = vq->data[i];
	detach_buf(vq, i);

	vq->last_used_idx++;

	return ret;
}

struct virtio_device *virtio_bind(u32 devid)
{
	return virtio_mmio_bind(devid);
}
                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/virtio.h                                                        0000644 0000000 0000000 00000006444 00000000000 016203  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _VIRTIO_H_
#define _VIRTIO_H_
/*
 * A minimal implementation of virtio.
 * Structures adapted from the Linux Kernel.
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */
#include "libcflat.h"

#define VIRTIO_ID_CONSOLE 3

struct virtio_device_id {
	u32 device;
	u32 vendor;
};

struct virtio_device {
	struct virtio_device_id id;
	const struct virtio_config_ops *config;
};

struct virtqueue {
	void (*callback)(struct virtqueue *vq);
	const char *name;
	struct virtio_device *vdev;
	unsigned int index;
	unsigned int num_free;
	void *priv;
};

typedef void vq_callback_t(struct virtqueue *);
struct virtio_config_ops {
	void (*get)(struct virtio_device *vdev, unsigned offset,
		    void *buf, unsigned len);
	void (*set)(struct virtio_device *vdev, unsigned offset,
		    const void *buf, unsigned len);
	int (*find_vqs)(struct virtio_device *vdev, unsigned nvqs,
			struct virtqueue *vqs[],
			vq_callback_t *callbacks[],
			const char *names[]);
};

static inline u8
virtio_config_readb(struct virtio_device *vdev, unsigned offset)
{
	u8 val;
	vdev->config->get(vdev, offset, &val, 1);
	return val;
}

static inline u16
virtio_config_readw(struct virtio_device *vdev, unsigned offset)
{
	u16 val;
	vdev->config->get(vdev, offset, &val, 2);
	return val;
}

static inline u32
virtio_config_readl(struct virtio_device *vdev, unsigned offset)
{
	u32 val;
	vdev->config->get(vdev, offset, &val, 4);
	return val;
}

static inline void
virtio_config_writeb(struct virtio_device *vdev, unsigned offset, u8 val)
{
	vdev->config->set(vdev, offset, &val, 1);
}

static inline void
virtio_config_writew(struct virtio_device *vdev, unsigned offset, u16 val)
{
	vdev->config->set(vdev, offset, &val, 2);
}

static inline void
virtio_config_writel(struct virtio_device *vdev, unsigned offset, u32 val)
{
	vdev->config->set(vdev, offset, &val, 4);
}

#define VRING_DESC_F_NEXT	1
#define VRING_DESC_F_WRITE	2

struct vring_desc {
	u64 addr;
	u32 len;
	u16 flags;
	u16 next;
};

struct vring_avail {
	u16 flags;
	u16 idx;
	u16 ring[];
};

struct vring_used_elem {
	u32 id;
	u32 len;
};

struct vring_used {
	u16 flags;
	u16 idx;
	struct vring_used_elem ring[];
};

struct vring {
	unsigned int num;
	struct vring_desc *desc;
	struct vring_avail *avail;
	struct vring_used *used;
};

struct vring_virtqueue {
	struct virtqueue vq;
	struct vring vring;
	unsigned int free_head;
	unsigned int num_added;
	u16 last_used_idx;
	bool (*notify)(struct virtqueue *vq);
	void *data[];
};

#define to_vvq(_vq) container_of(_vq, struct vring_virtqueue, vq)

extern void vring_init(struct vring *vr, unsigned int num, void *p,
		       unsigned long align);
extern void vring_init_virtqueue(struct vring_virtqueue *vq, unsigned index,
				 unsigned num, unsigned vring_align,
				 struct virtio_device *vdev, void *pages,
				 bool (*notify)(struct virtqueue *),
				 void (*callback)(struct virtqueue *),
				 const char *name);
extern int virtqueue_add_outbuf(struct virtqueue *vq, char *buf,
				unsigned int len);
extern bool virtqueue_kick(struct virtqueue *vq);
extern void detach_buf(struct vring_virtqueue *vq, unsigned head);
extern void *virtqueue_get_buf(struct virtqueue *_vq, unsigned int *len);

extern struct virtio_device *virtio_bind(u32 devid);

#endif /* _VIRTIO_H_ */
                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/x86/acpi.c                                                      0000644 0000000 0000000 00000002314 00000000000 016213  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "acpi.h"

void* find_acpi_table_addr(u32 sig)
{
    unsigned long addr;
    struct rsdp_descriptor *rsdp;
    struct rsdt_descriptor_rev1 *rsdt;
    void *end;
    int i;

    /* FACS is special... */
    if (sig == FACS_SIGNATURE) {
        struct fadt_descriptor_rev1 *fadt;
        fadt = find_acpi_table_addr(FACP_SIGNATURE);
        if (!fadt) {
            return NULL;
        }
        return (void*)(ulong)fadt->firmware_ctrl;
    }

    for(addr = 0xf0000; addr < 0x100000; addr += 16) {
	rsdp = (void*)addr;
	if (rsdp->signature == 0x2052545020445352LL)
          break;
    }
    if (addr == 0x100000) {
        printf("Can't find RSDP\n");
        return 0;
    }

    if (sig == RSDP_SIGNATURE) {
        return rsdp;
    }

    rsdt = (void*)(ulong)rsdp->rsdt_physical_address;
    if (!rsdt || rsdt->signature != RSDT_SIGNATURE)
        return 0;

    if (sig == RSDT_SIGNATURE) {
        return rsdt;
    }

    end = (void*)rsdt + rsdt->length;
    for (i=0; (void*)&rsdt->table_offset_entry[i] < end; i++) {
        struct acpi_table *t = (void*)(ulong)rsdt->table_offset_entry[i];
        if (t && t->signature == sig) {
            return t;
        }
    }
   return NULL;
}
                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/lib/x86/acpi.h                                                      0000644 0000000 0000000 00000012327 00000000000 016225  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef KVM_ACPI_H
#define KVM_ACPI_H 1

#include "libcflat.h"

#define ACPI_SIGNATURE(c1, c2, c3, c4) \
	((c1) | ((c2) << 8) | ((c3) << 16) | ((c4) << 24))

#define RSDP_SIGNATURE ACPI_SIGNATURE('R','S','D','P')
#define RSDT_SIGNATURE ACPI_SIGNATURE('R','S','D','T')
#define FACP_SIGNATURE ACPI_SIGNATURE('F','A','C','P')
#define FACS_SIGNATURE ACPI_SIGNATURE('F','A','C','S')

struct rsdp_descriptor {        /* Root System Descriptor Pointer */
    u64 signature;              /* ACPI signature, contains "RSD PTR " */
    u8  checksum;               /* To make sum of struct == 0 */
    u8  oem_id [6];             /* OEM identification */
    u8  revision;               /* Must be 0 for 1.0, 2 for 2.0 */
    u32 rsdt_physical_address;  /* 32-bit physical address of RSDT */
    u32 length;                 /* XSDT Length in bytes including hdr */
    u64 xsdt_physical_address;  /* 64-bit physical address of XSDT */
    u8  extended_checksum;      /* Checksum of entire table */
    u8  reserved [3];           /* Reserved field must be 0 */
};

#define ACPI_TABLE_HEADER_DEF   /* ACPI common table header */ \
    u32 signature;          /* ACPI signature (4 ASCII characters) */ \
    u32 length;                 /* Length of table, in bytes, including header */ \
    u8  revision;               /* ACPI Specification minor version # */ \
    u8  checksum;               /* To make sum of entire table == 0 */ \
    u8  oem_id [6];             /* OEM identification */ \
    u8  oem_table_id [8];       /* OEM table identification */ \
    u32 oem_revision;           /* OEM revision number */ \
    u8  asl_compiler_id [4];    /* ASL compiler vendor ID */ \
    u32 asl_compiler_revision;  /* ASL compiler revision number */

struct acpi_table {
    ACPI_TABLE_HEADER_DEF
    char data[0];
};

struct rsdt_descriptor_rev1 {
    ACPI_TABLE_HEADER_DEF
    u32 table_offset_entry[0];
};

struct fadt_descriptor_rev1
{
    ACPI_TABLE_HEADER_DEF     /* ACPI common table header */
    u32 firmware_ctrl;          /* Physical address of FACS */
    u32 dsdt;                   /* Physical address of DSDT */
    u8  model;                  /* System Interrupt Model */
    u8  reserved1;              /* Reserved */
    u16 sci_int;                /* System vector of SCI interrupt */
    u32 smi_cmd;                /* Port address of SMI command port */
    u8  acpi_enable;            /* Value to write to smi_cmd to enable ACPI */
    u8  acpi_disable;           /* Value to write to smi_cmd to disable ACPI */
    u8  S4bios_req;             /* Value to write to SMI CMD to enter S4BIOS state */
    u8  reserved2;              /* Reserved - must be zero */
    u32 pm1a_evt_blk;           /* Port address of Power Mgt 1a acpi_event Reg Blk */
    u32 pm1b_evt_blk;           /* Port address of Power Mgt 1b acpi_event Reg Blk */
    u32 pm1a_cnt_blk;           /* Port address of Power Mgt 1a Control Reg Blk */
    u32 pm1b_cnt_blk;           /* Port address of Power Mgt 1b Control Reg Blk */
    u32 pm2_cnt_blk;            /* Port address of Power Mgt 2 Control Reg Blk */
    u32 pm_tmr_blk;             /* Port address of Power Mgt Timer Ctrl Reg Blk */
    u32 gpe0_blk;               /* Port addr of General Purpose acpi_event 0 Reg Blk */
    u32 gpe1_blk;               /* Port addr of General Purpose acpi_event 1 Reg Blk */
    u8  pm1_evt_len;            /* Byte length of ports at pm1_x_evt_blk */
    u8  pm1_cnt_len;            /* Byte length of ports at pm1_x_cnt_blk */
    u8  pm2_cnt_len;            /* Byte Length of ports at pm2_cnt_blk */
    u8  pm_tmr_len;             /* Byte Length of ports at pm_tm_blk */
    u8  gpe0_blk_len;           /* Byte Length of ports at gpe0_blk */
    u8  gpe1_blk_len;           /* Byte Length of ports at gpe1_blk */
    u8  gpe1_base;              /* Offset in gpe model where gpe1 events start */
    u8  reserved3;              /* Reserved */
    u16 plvl2_lat;              /* Worst case HW latency to enter/exit C2 state */
    u16 plvl3_lat;              /* Worst case HW latency to enter/exit C3 state */
    u16 flush_size;             /* Size of area read to flush caches */
    u16 flush_stride;           /* Stride used in flushing caches */
    u8  duty_offset;            /* Bit location of duty cycle field in p_cnt reg */
    u8  duty_width;             /* Bit width of duty cycle field in p_cnt reg */
    u8  day_alrm;               /* Index to day-of-month alarm in RTC CMOS RAM */
    u8  mon_alrm;               /* Index to month-of-year alarm in RTC CMOS RAM */
    u8  century;                /* Index to century in RTC CMOS RAM */
    u8  reserved4;              /* Reserved */
    u8  reserved4a;             /* Reserved */
    u8  reserved4b;             /* Reserved */
};

struct facs_descriptor_rev1
{
    u32 signature;           /* ACPI Signature */
    u32 length;                 /* Length of structure, in bytes */
    u32 hardware_signature;     /* Hardware configuration signature */
    u32 firmware_waking_vector; /* ACPI OS waking vector */
    u32 global_lock;            /* Global Lock */
    u32 S4bios_f        : 1;    /* Indicates if S4BIOS support is present */
    u32 reserved1       : 31;   /* Must be 0 */
    u8  reserved3 [40];         /* Reserved - must be zero */
};

void* find_acpi_table_addr(u32 sig);

#endif
                                                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/lib/x86/apic-defs.h                                                 0000644 0000000 0000000 00000010430 00000000000 017135  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_X86_APICDEF_H
#define _ASM_X86_APICDEF_H

/*
 * Constants for various Intel APICs. (local APIC, IOAPIC, etc.)
 *
 * Alan Cox <Alan.Cox@linux.org>, 1995.
 * Ingo Molnar <mingo@redhat.com>, 1999, 2000
 */

#define	APIC_DEFAULT_PHYS_BASE	0xfee00000
#define APIC_BSP		(1UL << 8)
#define APIC_EXTD		(1UL << 10)
#define APIC_EN			(1UL << 11)

#define	APIC_ID		0x20

#define	APIC_LVR	0x30
#define		APIC_LVR_MASK		0xFF00FF
#define		GET_APIC_VERSION(x)	((x) & 0xFFu)
#define		GET_APIC_MAXLVT(x)	(((x) >> 16) & 0xFFu)
#ifdef CONFIG_X86_32
#  define	APIC_INTEGRATED(x)	((x) & 0xF0u)
#else
#  define	APIC_INTEGRATED(x)	(1)
#endif
#define		APIC_XAPIC(x)		((x) >= 0x14)
#define	APIC_TASKPRI	0x80
#define		APIC_TPRI_MASK		0xFFu
#define	APIC_ARBPRI	0x90
#define		APIC_ARBPRI_MASK	0xFFu
#define	APIC_PROCPRI	0xA0
#define	APIC_EOI	0xB0
#define		APIC_EIO_ACK		0x0
#define	APIC_RRR	0xC0
#define	APIC_LDR	0xD0
#define		APIC_LDR_MASK		(0xFFu << 24)
#define		GET_APIC_LOGICAL_ID(x)	(((x) >> 24) & 0xFFu)
#define		SET_APIC_LOGICAL_ID(x)	(((x) << 24))
#define		APIC_ALL_CPUS		0xFFu
#define	APIC_DFR	0xE0
#define		APIC_DFR_CLUSTER		0x0FFFFFFFul
#define		APIC_DFR_FLAT			0xFFFFFFFFul
#define	APIC_SPIV	0xF0
#define		APIC_SPIV_FOCUS_DISABLED	(1 << 9)
#define		APIC_SPIV_APIC_ENABLED		(1 << 8)
#define	APIC_ISR	0x100
#define	APIC_ISR_NR     0x8     /* Number of 32 bit ISR registers. */
#define	APIC_TMR	0x180
#define	APIC_IRR	0x200
#define	APIC_ESR	0x280
#define		APIC_ESR_SEND_CS	0x00001
#define		APIC_ESR_RECV_CS	0x00002
#define		APIC_ESR_SEND_ACC	0x00004
#define		APIC_ESR_RECV_ACC	0x00008
#define		APIC_ESR_SENDILL	0x00020
#define		APIC_ESR_RECVILL	0x00040
#define		APIC_ESR_ILLREGA	0x00080
#define	APIC_ICR	0x300
#define		APIC_DEST_SELF		0x40000
#define		APIC_DEST_ALLINC	0x80000
#define		APIC_DEST_ALLBUT	0xC0000
#define		APIC_ICR_RR_MASK	0x30000
#define		APIC_ICR_RR_INVALID	0x00000
#define		APIC_ICR_RR_INPROG	0x10000
#define		APIC_ICR_RR_VALID	0x20000
#define		APIC_INT_LEVELTRIG	0x08000
#define		APIC_INT_ASSERT		0x04000
#define		APIC_ICR_BUSY		0x01000
#define		APIC_DEST_LOGICAL	0x00800
#define		APIC_DEST_PHYSICAL	0x00000
#define		APIC_DM_FIXED		0x00000
#define		APIC_DM_LOWEST		0x00100
#define		APIC_DM_SMI		0x00200
#define		APIC_DM_REMRD		0x00300
#define		APIC_DM_NMI		0x00400
#define		APIC_DM_INIT		0x00500
#define		APIC_DM_STARTUP		0x00600
#define		APIC_DM_EXTINT		0x00700
#define		APIC_VECTOR_MASK	0x000FF
#define	APIC_ICR2	0x310
#define		GET_APIC_DEST_FIELD(x)	(((x) >> 24) & 0xFF)
#define		SET_APIC_DEST_FIELD(x)	((x) << 24)
#define	APIC_LVTT	0x320
#define	APIC_LVTTHMR	0x330
#define	APIC_LVTPC	0x340
#define	APIC_LVT0	0x350
#define		APIC_LVT_TIMER_BASE_MASK	(0x3 << 18)
#define		GET_APIC_TIMER_BASE(x)		(((x) >> 18) & 0x3)
#define		SET_APIC_TIMER_BASE(x)		(((x) << 18))
#define		APIC_TIMER_BASE_CLKIN		0x0
#define		APIC_TIMER_BASE_TMBASE		0x1
#define		APIC_TIMER_BASE_DIV		0x2
#define		APIC_LVT_TIMER_ONESHOT		(0 << 17)
#define		APIC_LVT_TIMER_PERIODIC		(1 << 17)
#define		APIC_LVT_TIMER_TSCDEADLINE	(2 << 17)
#define		APIC_LVT_MASKED			(1 << 16)
#define		APIC_LVT_LEVEL_TRIGGER		(1 << 15)
#define		APIC_LVT_REMOTE_IRR		(1 << 14)
#define		APIC_INPUT_POLARITY		(1 << 13)
#define		APIC_SEND_PENDING		(1 << 12)
#define		APIC_MODE_MASK			0x700
#define		GET_APIC_DELIVERY_MODE(x)	(((x) >> 8) & 0x7)
#define		SET_APIC_DELIVERY_MODE(x, y)	(((x) & ~0x700) | ((y) << 8))
#define			APIC_MODE_FIXED		0x0
#define			APIC_MODE_NMI		0x4
#define			APIC_MODE_EXTINT	0x7
#define	APIC_LVT1	0x360
#define	APIC_LVTERR	0x370
#define	APIC_TMICT	0x380
#define	APIC_TMCCT	0x390
#define	APIC_TDCR	0x3E0
#define APIC_SELF_IPI	0x3F0
#define		APIC_TDR_DIV_TMBASE	(1 << 2)
#define		APIC_TDR_DIV_1		0xB
#define		APIC_TDR_DIV_2		0x0
#define		APIC_TDR_DIV_4		0x1
#define		APIC_TDR_DIV_8		0x2
#define		APIC_TDR_DIV_16		0x3
#define		APIC_TDR_DIV_32		0x8
#define		APIC_TDR_DIV_64		0x9
#define		APIC_TDR_DIV_128	0xA
#define	APIC_EILVT0     0x500
#define		APIC_EILVT_NR_AMD_K8	1	/* # of extended interrupts */
#define		APIC_EILVT_NR_AMD_10H	4
#define		APIC_EILVT_LVTOFF(x)	(((x) >> 4) & 0xF)
#define		APIC_EILVT_MSG_FIX	0x0
#define		APIC_EILVT_MSG_SMI	0x2
#define		APIC_EILVT_MSG_NMI	0x4
#define		APIC_EILVT_MSG_EXT	0x7
#define		APIC_EILVT_MASKED	(1 << 16)
#define	APIC_EILVT1     0x510
#define	APIC_EILVT2     0x520
#define	APIC_EILVT3     0x530

#define APIC_BASE_MSR	0x800

#endif /* _ASM_X86_APICDEF_H */
                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/x86/apic.c                                                      0000644 0000000 0000000 00000010174 00000000000 016216  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "apic.h"
#include "msr.h"
#include "processor.h"

static void *g_apic = (void *)0xfee00000;
static void *g_ioapic = (void *)0xfec00000;

struct apic_ops {
    u32 (*reg_read)(unsigned reg);
    void (*reg_write)(unsigned reg, u32 val);
    void (*icr_write)(u32 val, u32 dest);
    u32 (*id)(void);
};

static void outb(unsigned char data, unsigned short port)
{
    asm volatile ("out %0, %1" : : "a"(data), "d"(port));
}

void eoi(void)
{
    apic_write(APIC_EOI, 0);
}

static u32 xapic_read(unsigned reg)
{
    return *(volatile u32 *)(g_apic + reg);
}

static void xapic_write(unsigned reg, u32 val)
{
    *(volatile u32 *)(g_apic + reg) = val;
}

static void xapic_icr_write(u32 val, u32 dest)
{
    while (xapic_read(APIC_ICR) & APIC_ICR_BUSY)
        ;
    xapic_write(APIC_ICR2, dest << 24);
    xapic_write(APIC_ICR, val);
}

static uint32_t xapic_id(void)
{
    return xapic_read(APIC_ID) >> 24;
}

static const struct apic_ops xapic_ops = {
    .reg_read = xapic_read,
    .reg_write = xapic_write,
    .icr_write = xapic_icr_write,
    .id = xapic_id,
};

static const struct apic_ops *apic_ops = &xapic_ops;

static u32 x2apic_read(unsigned reg)
{
    unsigned a, d;

    asm volatile ("rdmsr" : "=a"(a), "=d"(d) : "c"(APIC_BASE_MSR + reg/16));
    return a | (u64)d << 32;
}

static void x2apic_write(unsigned reg, u32 val)
{
    asm volatile ("wrmsr" : : "a"(val), "d"(0), "c"(APIC_BASE_MSR + reg/16));
}

static void x2apic_icr_write(u32 val, u32 dest)
{
    asm volatile ("wrmsr" : : "a"(val), "d"(dest),
                  "c"(APIC_BASE_MSR + APIC_ICR/16));
}

static uint32_t x2apic_id(void)
{
    return x2apic_read(APIC_ID);
}

static const struct apic_ops x2apic_ops = {
    .reg_read = x2apic_read,
    .reg_write = x2apic_write,
    .icr_write = x2apic_icr_write,
    .id = x2apic_id,
};

u32 apic_read(unsigned reg)
{
    return apic_ops->reg_read(reg);
}

void apic_write(unsigned reg, u32 val)
{
    apic_ops->reg_write(reg, val);
}

bool apic_read_bit(unsigned reg, int n)
{
    reg += (n >> 5) << 4;
    n &= 31;
    return (apic_read(reg) & (1 << n)) != 0;
}

void apic_icr_write(u32 val, u32 dest)
{
    apic_ops->icr_write(val, dest);
}

uint32_t apic_id(void)
{
    return apic_ops->id();
}

uint8_t apic_get_tpr(void)
{
	unsigned long tpr;

#ifdef __x86_64__
	asm volatile ("mov %%cr8, %0" : "=r"(tpr));
#else
	tpr = apic_read(APIC_TASKPRI) >> 4;
#endif
	return tpr;
}

void apic_set_tpr(uint8_t tpr)
{
#ifdef __x86_64__
	asm volatile ("mov %0, %%cr8" : : "r"((unsigned long) tpr));
#else
	apic_write(APIC_TASKPRI, tpr << 4);
#endif
}

int enable_x2apic(void)
{
    unsigned a, b, c, d;

    asm ("cpuid" : "=a"(a), "=b"(b), "=c"(c), "=d"(d) : "0"(1));

    if (c & (1 << 21)) {
        asm ("rdmsr" : "=a"(a), "=d"(d) : "c"(MSR_IA32_APICBASE));
        a |= 1 << 10;
        asm ("wrmsr" : : "a"(a), "d"(d), "c"(MSR_IA32_APICBASE));
        apic_ops = &x2apic_ops;
        return 1;
    } else {
        return 0;
    }
}

void reset_apic(void)
{
    u64 disabled = rdmsr(MSR_IA32_APICBASE) & ~(APIC_EN | APIC_EXTD);
    wrmsr(MSR_IA32_APICBASE, disabled);
    apic_ops = &xapic_ops;
    wrmsr(MSR_IA32_APICBASE, disabled | APIC_EN);
}

u32 ioapic_read_reg(unsigned reg)
{
    *(volatile u32 *)g_ioapic = reg;
    return *(volatile u32 *)(g_ioapic + 0x10);
}

void ioapic_write_reg(unsigned reg, u32 value)
{
    *(volatile u32 *)g_ioapic = reg;
    *(volatile u32 *)(g_ioapic + 0x10) = value;
}

void ioapic_write_redir(unsigned line, ioapic_redir_entry_t e)
{
    ioapic_write_reg(0x10 + line * 2 + 0, ((u32 *)&e)[0]);
    ioapic_write_reg(0x10 + line * 2 + 1, ((u32 *)&e)[1]);
}

ioapic_redir_entry_t ioapic_read_redir(unsigned line)
{
    ioapic_redir_entry_t e;

    ((u32 *)&e)[0] = ioapic_read_reg(0x10 + line * 2 + 0);
    ((u32 *)&e)[1] = ioapic_read_reg(0x10 + line * 2 + 1);
    return e;

}

void set_mask(unsigned line, int mask)
{
    ioapic_redir_entry_t e = ioapic_read_redir(line);

    e.mask = mask;
    ioapic_write_redir(line, e);
}

void enable_apic(void)
{
    printf("enabling apic\n");
    xapic_write(0xf0, 0x1ff); /* spurious vector register */
}

void mask_pic_interrupts(void)
{
    outb(0xff, 0x21);
    outb(0xff, 0xa1);
}
                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/lib/x86/apic.h                                                      0000644 0000000 0000000 00000002155 00000000000 016223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef CFLAT_APIC_H
#define CFLAT_APIC_H

#include <stdint.h>
#include "apic-defs.h"

typedef struct {
    uint8_t vector;
    uint8_t delivery_mode:3;
    uint8_t dest_mode:1;
    uint8_t delivery_status:1;
    uint8_t polarity:1;
    uint8_t remote_irr:1;
    uint8_t trig_mode:1;
    uint8_t mask:1;
    uint8_t reserve:7;
    uint8_t reserved[4];
    uint8_t dest_id;
} ioapic_redir_entry_t;

typedef enum trigger_mode {
	TRIGGER_EDGE = 0,
	TRIGGER_LEVEL,
	TRIGGER_MAX,
} trigger_mode_t;

void mask_pic_interrupts(void);

void eoi(void);
uint8_t apic_get_tpr(void);
void apic_set_tpr(uint8_t tpr);

void ioapic_write_redir(unsigned line, ioapic_redir_entry_t e);
void ioapic_write_reg(unsigned reg, uint32_t value);
ioapic_redir_entry_t ioapic_read_redir(unsigned line);
uint32_t ioapic_read_reg(unsigned reg);

void set_mask(unsigned line, int mask);

void enable_apic(void);
uint32_t apic_read(unsigned reg);
bool apic_read_bit(unsigned reg, int n);
void apic_write(unsigned reg, uint32_t val);
void apic_icr_write(uint32_t val, uint32_t dest);
uint32_t apic_id(void);

int enable_x2apic(void);
void reset_apic(void);

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/lib/x86/asm/barrier.h                                               0000644 0000000 0000000 00000001154 00000000000 017513  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_X86_BARRIER_H_
#define _ASM_X86_BARRIER_H_
/*
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */

#define mb()	asm volatile("mfence":::"memory")
#define rmb()	asm volatile("lfence":::"memory")
#define wmb()	asm volatile("sfence":::"memory")

#define smp_rmb()	barrier()
#define smp_wmb()	barrier()

/* REP NOP (PAUSE) is a good thing to insert into busy-wait loops. */
static inline void rep_nop(void)
{
	asm volatile("rep; nop" ::: "memory");
}

static inline void cpu_relax(void)
{
	rep_nop();
}

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/lib/x86/asm/bitops.h                                                0000644 0000000 0000000 00000000331 00000000000 017361  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASMX86_BITOPS_H_
#define _ASMX86_BITOPS_H_

#ifndef _BITOPS_H_
#error only <bitops.h> can be included directly
#endif

#ifdef __x86_64__
#define BITS_PER_LONG	64
#else
#define BITS_PER_LONG	32
#endif

#endif
                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/lib/x86/asm/io.h                                                    0000644 0000000 0000000 00000002706 00000000000 016500  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_X86_IO_H_
#define _ASM_X86_IO_H_

#define __iomem

#define inb inb
static inline uint8_t inb(unsigned long port)
{
    unsigned char value;
    asm volatile("inb %w1, %0" : "=a" (value) : "Nd" ((unsigned short)port));
    return value;
}

#define inw inw
static inline uint16_t inw(unsigned long port)
{
    unsigned short value;
    asm volatile("inw %w1, %0" : "=a" (value) : "Nd" ((unsigned short)port));
    return value;
}

#define inl inl
static inline uint32_t inl(unsigned long port)
{
    unsigned int value;
    asm volatile("inl %w1, %0" : "=a" (value) : "Nd" ((unsigned short)port));
    return value;
}

#define outb outb
static inline void outb(uint8_t value, unsigned long port)
{
    asm volatile("outb %b0, %w1" : : "a"(value), "Nd"((unsigned short)port));
}

#define outw outw
static inline void outw(uint16_t value, unsigned long port)
{
    asm volatile("outw %w0, %w1" : : "a"(value), "Nd"((unsigned short)port));
}

#define outl outl
static inline void outl(uint32_t value, unsigned long port)
{
    asm volatile("outl %0, %w1" : : "a"(value), "Nd"((unsigned short)port));
}

#define virt_to_phys virt_to_phys
static inline unsigned long virt_to_phys(const void *virt)
{
    return (unsigned long)virt;
}

#define phys_to_virt phys_to_virt
static inline void *phys_to_virt(unsigned long phys)
{
    return (void *)phys;
}

#define ioremap ioremap
void __iomem *ioremap(phys_addr_t phys_addr, size_t size);

#include <asm-generic/io.h>

#endif
                                                          source/v64/tests/kvm-unit-tests/lib/x86/asm/page.h                                                  0000644 0000000 0000000 00000002263 00000000000 017003  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_X86_PAGE_H_
#define _ASM_X86_PAGE_H_
/*
 * Copyright (C) 2016, Red Hat Inc, Alexander Gordeev <agordeev@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */


#include <linux/const.h>
#include <bitops.h>

#define PAGE_SHIFT	12
#define PAGE_SIZE	(_AC(1,UL) << PAGE_SHIFT)
#define PAGE_MASK	(~(PAGE_SIZE-1))

#ifndef __ASSEMBLY__

#ifdef __x86_64__
#define LARGE_PAGE_SIZE	(512 * PAGE_SIZE)
#else
#define LARGE_PAGE_SIZE	(1024 * PAGE_SIZE)
#endif

#define PT_PRESENT_MASK		(1ull << 0)
#define PT_WRITABLE_MASK	(1ull << 1)
#define PT_USER_MASK		(1ull << 2)
#define PT_ACCESSED_MASK	(1ull << 5)
#define PT_DIRTY_MASK		(1ull << 6)
#define PT_PAGE_SIZE_MASK	(1ull << 7)
#define PT64_NX_MASK		(1ull << 63)
#define PT_ADDR_MASK		GENMASK_ULL(51, 12)

#define PT_AD_MASK              (PT_ACCESSED_MASK | PT_DIRTY_MASK)

#ifdef __x86_64__
#define	PAGE_LEVEL	4
#define	PGDIR_WIDTH	9
#define	PGDIR_MASK	511
#else
#define	PAGE_LEVEL	2
#define	PGDIR_WIDTH	10
#define	PGDIR_MASK	1023
#endif

#define PGDIR_BITS(lvl)        (((lvl) - 1) * PGDIR_WIDTH + PAGE_SHIFT)
#define PGDIR_OFFSET(va, lvl)  (((va) >> PGDIR_BITS(lvl)) & PGDIR_MASK)

#endif /* !__ASSEMBLY__ */
#endif
                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/lib/x86/asm/pci.h                                                   0000644 0000000 0000000 00000002646 00000000000 016647  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef ASM_PCI_H
#define ASM_PCI_H
/*
 * Copyright (C) 2013, Red Hat Inc, Michael S. Tsirkin <mst@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"
#include "pci.h"
#include "x86/asm/io.h"

#define PCI_CONF1_ADDRESS(dev, reg)	((0x1 << 31) | (dev << 8) | reg)

static inline uint8_t pci_config_readb(pcidevaddr_t dev, uint8_t reg)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    return inb(0xCFC);
}

static inline uint16_t pci_config_readw(pcidevaddr_t dev, uint8_t reg)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    return inw(0xCFC);
}

static inline uint32_t pci_config_readl(pcidevaddr_t dev, uint8_t reg)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    return inl(0xCFC);
}

static inline void pci_config_writeb(pcidevaddr_t dev, uint8_t reg,
                                     uint8_t val)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    outb(val, 0xCFC);
}

static inline void pci_config_writew(pcidevaddr_t dev, uint8_t reg,
                                     uint16_t val)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    outw(val, 0xCFC);
}

static inline void pci_config_writel(pcidevaddr_t dev, uint8_t reg,
                                     uint32_t val)
{
    outl(PCI_CONF1_ADDRESS(dev, reg), 0xCF8);
    outl(val, 0xCFC);
}

static inline
phys_addr_t pci_translate_addr(pcidevaddr_t dev __unused, uint64_t addr)
{
    return addr;
}

#endif
                                                                                          source/v64/tests/kvm-unit-tests/lib/x86/asm/spinlock.h                                              0000644 0000000 0000000 00000000135 00000000000 017705  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __ASM_SPINLOCK_H
#define __ASM_SPINLOCK_H

#include <asm-generic/spinlock.h>

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/lib/x86/asm/stack.h                                                 0000644 0000000 0000000 00000000325 00000000000 017171  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _X86ASM_STACK_H_
#define _X86ASM_STACK_H_

#ifndef _STACK_H_
#error Do not directly include <asm/stack.h>. Just use <stack.h>.
#endif

#define HAVE_ARCH_BACKTRACE_FRAME
#define HAVE_ARCH_BACKTRACE

#endif
                                                                                                                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/lib/x86/atomic.c                                                    0000644 0000000 0000000 00000001456 00000000000 016561  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include <libcflat.h>
#include "atomic.h"

#ifdef __i386__

u64 atomic64_cmpxchg(atomic64_t *v, u64 old, u64 new)
{
        u32 low = new;
        u32 high = new >> 32;

        asm volatile("lock cmpxchg8b %1\n"
                     : "+A" (old),
                       "+m" (*(volatile long long *)&v->counter)
                     : "b" (low), "c" (high)
                     : "memory"
                     );

        return old;
}

#else

u64 atomic64_cmpxchg(atomic64_t *v, u64 old, u64 new)
{
        u64 ret;
        u64 _old = old;
        u64 _new = new;

        asm volatile("lock cmpxchgq %2,%1"
                     : "=a" (ret), "+m" (*(volatile long *)&v->counter)
                     : "r" (_new), "0" (_old)
                     : "memory"
                     );
        return ret;
}

#endif
                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/lib/x86/atomic.h                                                    0000644 0000000 0000000 00000006216 00000000000 016565  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __ATOMIC_H
#define __ATOMIC_H

#include "asm-generic/atomic.h"

typedef struct {
	volatile int counter;
} atomic_t;

#ifdef __i386__

/**
 * atomic_read - read atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically reads the value of @v.
 */
static inline int atomic_read(const atomic_t *v)
{
	return v->counter;
}

/**
 * atomic_set - set atomic variable
 * @v: pointer of type atomic_t
 * @i: required value
 *
 * Atomically sets the value of @v to @i.
 */
static inline void atomic_set(atomic_t *v, int i)
{
	v->counter = i;
}

/**
 * atomic_inc - increment atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically increments @v by 1.
 */
static inline void atomic_inc(atomic_t *v)
{
	asm volatile("lock incl %0"
		     : "+m" (v->counter));
}

/**
 * atomic_dec - decrement atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically decrements @v by 1.
 */
static inline void atomic_dec(atomic_t *v)
{
	asm volatile("lock decl %0"
		     : "+m" (v->counter));
}

typedef struct {
	u64 __attribute__((aligned(8))) counter;
} atomic64_t;

#define ATOMIC64_INIT(val)	{ (val) }

/**
 * atomic64_read - read atomic64 variable
 * @ptr:      pointer to type atomic64_t
 *
 * Atomically reads the value of @ptr and returns it.
 */
static inline u64 atomic64_read(atomic64_t *ptr)
{
	u64 res;

	/*
	 * Note, we inline this atomic64_t primitive because
	 * it only clobbers EAX/EDX and leaves the others
	 * untouched. We also (somewhat subtly) rely on the
	 * fact that cmpxchg8b returns the current 64-bit value
	 * of the memory location we are touching:
	 */
	asm volatile("mov %%ebx, %%eax\n\t"
                     "mov %%ecx, %%edx\n\t"
                     "lock cmpxchg8b %1\n"
                     : "=&A" (res)
                     : "m" (*ptr)
                     );
	return res;
}

u64 atomic64_cmpxchg(atomic64_t *v, u64 old, u64 new);

#elif defined(__x86_64__)

/**
 * atomic_read - read atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically reads the value of @v.
 */
static inline int atomic_read(const atomic_t *v)
{
	return v->counter;
}

/**
 * atomic_set - set atomic variable
 * @v: pointer of type atomic_t
 * @i: required value
 *
 * Atomically sets the value of @v to @i.
 */
static inline void atomic_set(atomic_t *v, int i)
{
	v->counter = i;
}

/**
 * atomic_inc - increment atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically increments @v by 1.
 */
static inline void atomic_inc(atomic_t *v)
{
	asm volatile("lock incl %0"
		     : "=m" (v->counter)
		     : "m" (v->counter));
}

/**
 * atomic_dec - decrement atomic variable
 * @v: pointer of type atomic_t
 *
 * Atomically decrements @v by 1.
 */
static inline void atomic_dec(atomic_t *v)
{
	asm volatile("lock decl %0"
		     : "=m" (v->counter)
		     : "m" (v->counter));
}

typedef struct {
	long long counter;
} atomic64_t;

#define ATOMIC64_INIT(i)	{ (i) }

/**
 * atomic64_read - read atomic64 variable
 * @v: pointer of type atomic64_t
 *
 * Atomically reads the value of @v.
 * Doesn't imply a read memory barrier.
 */
static inline long atomic64_read(const atomic64_t *v)
{
	return v->counter;
}

u64 atomic64_cmpxchg(atomic64_t *v, u64 old, u64 new);

#endif

#endif
                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/lib/x86/desc.c                                                      0000644 0000000 0000000 00000021250 00000000000 016215  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "desc.h"
#include "processor.h"
#include <setjmp.h>

void set_idt_entry(int vec, void *addr, int dpl)
{
    idt_entry_t *e = &boot_idt[vec];
    memset(e, 0, sizeof *e);
    e->offset0 = (unsigned long)addr;
    e->selector = read_cs();
    e->ist = 0;
    e->type = 14;
    e->dpl = dpl;
    e->p = 1;
    e->offset1 = (unsigned long)addr >> 16;
#ifdef __x86_64__
    e->offset2 = (unsigned long)addr >> 32;
#endif
}

void set_idt_dpl(int vec, u16 dpl)
{
    idt_entry_t *e = &boot_idt[vec];
    e->dpl = dpl;
}

void set_idt_sel(int vec, u16 sel)
{
    idt_entry_t *e = &boot_idt[vec];
    e->selector = sel;
}

struct ex_record {
    unsigned long rip;
    unsigned long handler;
};

extern struct ex_record exception_table_start, exception_table_end;

static const char* exception_mnemonic(int vector)
{
	switch(vector) {
	case 0: return "#DE";
	case 1: return "#DB";
	case 2: return "#NMI";
	case 3: return "#BP";
	case 4: return "#OF";
	case 5: return "#BR";
	case 6: return "#UD";
	case 7: return "#NM";
	case 8: return "#DF";
	case 10: return "#TS";
	case 11: return "#NP";
	case 12: return "#SS";
	case 13: return "#GP";
	case 14: return "#PF";
	case 16: return "#MF";
	case 17: return "#AC";
	case 18: return "#MC";
	case 19: return "#XM";
	default: return "#??";
	}
}

static void unhandled_exception(struct ex_regs *regs, bool cpu)
{
	printf("Unhandled %sexception %ld %s at ip %016lx\n",
	       cpu ? "cpu " : "", regs->vector,
	       exception_mnemonic(regs->vector), regs->rip);
	if (regs->vector == 14)
		printf("PF at %#lx addr %#lx\n", regs->rip, read_cr2());

	printf("error_code=%04lx      rflags=%08lx      cs=%08lx\n"
	       "rax=%016lx rcx=%016lx rdx=%016lx rbx=%016lx\n"
	       "rbp=%016lx rsi=%016lx rdi=%016lx\n"
#ifdef __x86_64__
	       " r8=%016lx  r9=%016lx r10=%016lx r11=%016lx\n"
	       "r12=%016lx r13=%016lx r14=%016lx r15=%016lx\n"
#endif
	       "cr0=%016lx cr2=%016lx cr3=%016lx cr4=%016lx\n"
#ifdef __x86_64__
	       "cr8=%016lx\n"
#endif
	       ,
	       regs->error_code, regs->rflags, regs->cs,
	       regs->rax, regs->rcx, regs->rdx, regs->rbx,
	       regs->rbp, regs->rsi, regs->rdi,
#ifdef __x86_64__
	       regs->r8, regs->r9, regs->r10, regs->r11,
	       regs->r12, regs->r13, regs->r14, regs->r15,
#endif
	       read_cr0(), read_cr2(), read_cr3(), read_cr4()
#ifdef __x86_64__
	       , read_cr8()
#endif
	);
	dump_frame_stack((void*) regs->rip, (void*) regs->rbp);
	abort();
}

static void check_exception_table(struct ex_regs *regs)
{
    struct ex_record *ex;
    unsigned ex_val;

    ex_val = regs->vector | (regs->error_code << 16) |
		(((regs->rflags >> 16) & 1) << 8);
    asm("mov %0, %%gs:4" : : "r"(ex_val));

    for (ex = &exception_table_start; ex != &exception_table_end; ++ex) {
        if (ex->rip == regs->rip) {
            regs->rip = ex->handler;
            return;
        }
    }
    unhandled_exception(regs, false);
}

static handler exception_handlers[32];

handler handle_exception(u8 v, handler fn)
{
	handler old;

	old = exception_handlers[v];
	if (v < 32)
		exception_handlers[v] = fn;
	return old;
}

#ifndef __x86_64__
__attribute__((regparm(1)))
#endif
void do_handle_exception(struct ex_regs *regs)
{
	if (regs->vector < 32 && exception_handlers[regs->vector]) {
		exception_handlers[regs->vector](regs);
		return;
	}
	unhandled_exception(regs, true);
}

#define EX(NAME, N) extern char NAME##_fault;	\
	asm (".pushsection .text \n\t"		\
	     #NAME"_fault: \n\t"		\
	     "push"W" $0 \n\t"			\
	     "push"W" $"#N" \n\t"		\
	     "jmp __handle_exception \n\t"	\
	     ".popsection")

#define EX_E(NAME, N) extern char NAME##_fault;	\
	asm (".pushsection .text \n\t"		\
	     #NAME"_fault: \n\t"		\
	     "push"W" $"#N" \n\t"		\
	     "jmp __handle_exception \n\t"	\
	     ".popsection")

EX(de, 0);
EX(db, 1);
EX(nmi, 2);
EX(bp, 3);
EX(of, 4);
EX(br, 5);
EX(ud, 6);
EX(nm, 7);
EX_E(df, 8);
EX_E(ts, 10);
EX_E(np, 11);
EX_E(ss, 12);
EX_E(gp, 13);
EX_E(pf, 14);
EX(mf, 16);
EX_E(ac, 17);
EX(mc, 18);
EX(xm, 19);

asm (".pushsection .text \n\t"
     "__handle_exception: \n\t"
#ifdef __x86_64__
     "push %r15; push %r14; push %r13; push %r12 \n\t"
     "push %r11; push %r10; push %r9; push %r8 \n\t"
#endif
     "push %"R "di; push %"R "si; push %"R "bp; sub $"S", %"R "sp \n\t"
     "push %"R "bx; push %"R "dx; push %"R "cx; push %"R "ax \n\t"
#ifdef __x86_64__
     "mov %"R "sp, %"R "di \n\t"
#else
     "mov %"R "sp, %"R "ax \n\t"
#endif
     "call do_handle_exception \n\t"
     "pop %"R "ax; pop %"R "cx; pop %"R "dx; pop %"R "bx \n\t"
     "add $"S", %"R "sp; pop %"R "bp; pop %"R "si; pop %"R "di \n\t"
#ifdef __x86_64__
     "pop %r8; pop %r9; pop %r10; pop %r11 \n\t"
     "pop %r12; pop %r13; pop %r14; pop %r15 \n\t"
#endif
     "add $"S", %"R "sp \n\t"
     "add $"S", %"R "sp \n\t"
     "iret"W" \n\t"
     ".popsection");

static void *idt_handlers[32] = {
	[0] = &de_fault,
	[1] = &db_fault,
	[2] = &nmi_fault,
	[3] = &bp_fault,
	[4] = &of_fault,
	[5] = &br_fault,
	[6] = &ud_fault,
	[7] = &nm_fault,
	[8] = &df_fault,
	[10] = &ts_fault,
	[11] = &np_fault,
	[12] = &ss_fault,
	[13] = &gp_fault,
	[14] = &pf_fault,
	[16] = &mf_fault,
	[17] = &ac_fault,
	[18] = &mc_fault,
	[19] = &xm_fault,
};

void setup_idt(void)
{
    int i;
    static bool idt_initialized = false;

    if (idt_initialized) {
        return;
    }
    idt_initialized = true;
    for (i = 0; i < 32; i++)
	    if (idt_handlers[i])
		    set_idt_entry(i, idt_handlers[i], 0);
    handle_exception(0, check_exception_table);
    handle_exception(6, check_exception_table);
    handle_exception(13, check_exception_table);
}

unsigned exception_vector(void)
{
    unsigned char vector;

    asm("movb %%gs:4, %0" : "=q"(vector));
    return vector;
}

unsigned exception_error_code(void)
{
    unsigned short error_code;

    asm("mov %%gs:6, %0" : "=r"(error_code));
    return error_code;
}

bool exception_rflags_rf(void)
{
    unsigned char rf_flag;

    asm("movb %%gs:5, %b0" : "=q"(rf_flag));
    return rf_flag & 1;
}

static char intr_alt_stack[4096];

#ifndef __x86_64__
void set_gdt_entry(int sel, u32 base,  u32 limit, u8 access, u8 gran)
{
	int num = sel >> 3;

	/* Setup the descriptor base address */
	gdt32[num].base_low = (base & 0xFFFF);
	gdt32[num].base_middle = (base >> 16) & 0xFF;
	gdt32[num].base_high = (base >> 24) & 0xFF;

	/* Setup the descriptor limits */
	gdt32[num].limit_low = (limit & 0xFFFF);
	gdt32[num].granularity = ((limit >> 16) & 0x0F);

	/* Finally, set up the granularity and access flags */
	gdt32[num].granularity |= (gran & 0xF0);
	gdt32[num].access = access;
}

void set_gdt_task_gate(u16 sel, u16 tss_sel)
{
    set_gdt_entry(sel, tss_sel, 0, 0x85, 0); // task, present
}

void set_idt_task_gate(int vec, u16 sel)
{
    idt_entry_t *e = &boot_idt[vec];

    memset(e, 0, sizeof *e);

    e->selector = sel;
    e->ist = 0;
    e->type = 5;
    e->dpl = 0;
    e->p = 1;
}

/*
 * 0 - main task
 * 1 - interrupt task
 */

tss32_t tss_intr;

void setup_tss32(void)
{
	u16 desc_size = sizeof(tss32_t);

	tss.cr3 = read_cr3();
	tss_intr.cr3 = read_cr3();
	tss_intr.ss0 = tss_intr.ss1 = tss_intr.ss2 = 0x10;
	tss_intr.esp = tss_intr.esp0 = tss_intr.esp1 = tss_intr.esp2 =
		(u32)intr_alt_stack + 4096;
	tss_intr.cs = 0x08;
	tss_intr.ds = tss_intr.es = tss_intr.fs = tss_intr.gs = tss_intr.ss = 0x10;
	tss_intr.iomap_base = (u16)desc_size;
	set_gdt_entry(TSS_INTR, (u32)&tss_intr, desc_size - 1, 0x89, 0x0f);
}

void set_intr_task_gate(int e, void *fn)
{
	tss_intr.eip = (u32)fn;
	set_idt_task_gate(e, TSS_INTR);
}

void setup_alt_stack(void)
{
	setup_tss32();
}

void set_intr_alt_stack(int e, void *fn)
{
	set_intr_task_gate(e, fn);
}

void print_current_tss_info(void)
{
	u16 tr = str();

	if (tr != TSS_MAIN && tr != TSS_INTR)
		printf("Unknown TSS %x\n", tr);
	else
		printf("TR=%x (%s) Main TSS back link %x. Intr TSS back link %x\n",
		       tr, tr ? "interrupt" : "main", tss.prev, tss_intr.prev);
}
#else
void set_intr_alt_stack(int e, void *addr)
{
	set_idt_entry(e, addr, 0);
	boot_idt[e].ist = 1;
}

void setup_alt_stack(void)
{
	tss.ist1 = (u64)intr_alt_stack + 4096;
}
#endif

static bool exception;
static jmp_buf *exception_jmpbuf;

static void exception_handler_longjmp(void)
{
	longjmp(*exception_jmpbuf, 1);
}

static void exception_handler(struct ex_regs *regs)
{
	/* longjmp must happen after iret, so do not do it now.  */
	exception = true;
	regs->rip = (unsigned long)&exception_handler_longjmp;
	regs->cs = read_cs();
}

bool test_for_exception(unsigned int ex, void (*trigger_func)(void *data),
			void *data)
{
	handler old;
	jmp_buf jmpbuf;
	int ret;

	old = handle_exception(ex, exception_handler);
	ret = set_exception_jmpbuf(jmpbuf);
	if (ret == 0)
		trigger_func(data);
	handle_exception(ex, old);
	return ret;
}

void __set_exception_jmpbuf(jmp_buf *addr)
{
	exception_jmpbuf = addr;
}
                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/lib/x86/desc.h                                                      0000644 0000000 0000000 00000011111 00000000000 016215  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __IDT_TEST__
#define __IDT_TEST__

#include <setjmp.h>

void setup_idt(void);
void setup_alt_stack(void);

struct ex_regs {
    unsigned long rax, rcx, rdx, rbx;
    unsigned long dummy, rbp, rsi, rdi;
#ifdef __x86_64__
    unsigned long r8, r9, r10, r11;
    unsigned long r12, r13, r14, r15;
#endif
    unsigned long vector;
    unsigned long error_code;
    unsigned long rip;
    unsigned long cs;
    unsigned long rflags;
};

typedef void (*handler)(struct ex_regs *regs);

typedef struct {
	u16 prev;
	u16 res1;
	u32 esp0;
	u16 ss0;
	u16 res2;
	u32 esp1;
	u16 ss1;
	u16 res3;
	u32 esp2;
	u16 ss2;
	u16 res4;
	u32 cr3;
	u32 eip;
	u32 eflags;
	u32 eax, ecx, edx, ebx, esp, ebp, esi, edi;
	u16 es;
	u16 res5;
	u16 cs;
	u16 res6;
	u16 ss;
	u16 res7;
	u16 ds;
	u16 res8;
	u16 fs;
	u16 res9;
	u16 gs;
	u16 res10;
	u16 ldt;
	u16 res11;
	u16 t:1;
	u16 res12:15;
	u16 iomap_base;
} tss32_t;

typedef struct  __attribute__((packed)) {
	u32 res1;
	u64 rsp0;
	u64 rsp1;
	u64 rsp2;
	u64 res2;
	u64 ist1;
	u64 ist2;
	u64 ist3;
	u64 ist4;
	u64 ist5;
	u64 ist6;
	u64 ist7;
	u64 res3;
	u16 res4;
	u16 iomap_base;
} tss64_t;

#define ASM_TRY(catch)                                  \
    "movl $0, %%gs:4 \n\t"                              \
    ".pushsection .data.ex \n\t"                        \
    ".quad 1111f, " catch "\n\t"                        \
    ".popsection \n\t"                                  \
    "1111:"

#define DB_VECTOR   1
#define BP_VECTOR   3
#define UD_VECTOR   6
#define GP_VECTOR   13

/*
 * selector     32-bit                        64-bit
 * 0x00         NULL descriptor               NULL descriptor
 * 0x08         ring-0 code segment (32-bit)  ring-0 code segment (64-bit)
 * 0x10         ring-0 data segment (32-bit)  ring-0 data segment (32/64-bit)
 * 0x18         ring-0 code segment (P=0)     ring-0 code segment (64-bit, P=0)
 * 0x20         intr_alt_stack TSS            ring-0 code segment (32-bit)
 * 0x28         ring-0 code segment (16-bit)  same
 * 0x30         ring-0 data segment (16-bit)  same
 * 0x38 (0x3b)  ring-3 code segment (32-bit)  same
 * 0x40 (0x43)  ring-3 data segment (32-bit)  ring-3 data segment (32/64-bit)
 * 0x48 (0x4b)  **unused**                    ring-3 code segment (64-bit)
 * 0x50--0x78   free to use for test cases    same
 * 0x80         primary TSS (CPU 0)           same
 *
 * Note that the same segment can be used for 32-bit and 64-bit data segments
 * (the L bit is only defined for code segments)
 *
 * Selectors 0x08-0x10 and 0x3b-0x4b are set up for use with the SYSCALL
 * and SYSRET instructions.
 */

#define KERNEL_CS   0x08
#define KERNEL_DS   0x10
#define NP_SEL      0x18
#ifdef __x86_64__
#define KERNEL_CS32 0x20
#else
#define TSS_INTR    0x20
#endif
#define KERNEL_CS16 0x28
#define KERNEL_DS16 0x30
#define USER_CS32   0x3b
#define USER_DS     0x43
#ifdef __x86_64__
#define USER_CS64   0x4b
#endif

/* Synonyms */
#define KERNEL_DS32 KERNEL_DS
#define USER_DS32   USER_DS

#ifdef __x86_64__
#define KERNEL_CS64 KERNEL_CS
#define USER_CS     USER_CS64
#define KERNEL_DS64 KERNEL_DS
#define USER_DS64   USER_DS
#else
#define KERNEL_CS32 KERNEL_CS
#define USER_CS     USER_CS32
#endif

#define FIRST_SPARE_SEL 0x50
#define TSS_MAIN 0x80

typedef struct {
    unsigned short offset0;
    unsigned short selector;
    unsigned short ist : 3;
    unsigned short : 5;
    unsigned short type : 4;
    unsigned short : 1;
    unsigned short dpl : 2;
    unsigned short p : 1;
    unsigned short offset1;
#ifdef __x86_64__
    unsigned offset2;
    unsigned reserved;
#endif
} idt_entry_t;

typedef struct {
	u16 limit_low;
	u16 base_low;
	u8 base_middle;
	u8 access;
	u8 granularity;
	u8 base_high;
} gdt_entry_t;

extern idt_entry_t boot_idt[256];

#ifndef __x86_64__
extern gdt_entry_t gdt32[];
extern tss32_t tss;
extern tss32_t tss_intr;
void set_gdt_task_gate(u16 tss_sel, u16 sel);
void set_idt_task_gate(int vec, u16 sel);
void set_intr_task_gate(int vec, void *fn);
void setup_tss32(void);
#else
extern tss64_t tss;
#endif

unsigned exception_vector(void);
unsigned exception_error_code(void);
bool exception_rflags_rf(void);
void set_idt_entry(int vec, void *addr, int dpl);
void set_idt_sel(int vec, u16 sel);
void set_idt_dpl(int vec, u16 dpl);
void set_gdt_entry(int sel, u32 base,  u32 limit, u8 access, u8 gran);
void set_intr_alt_stack(int e, void *fn);
void print_current_tss_info(void);
handler handle_exception(u8 v, handler fn);

bool test_for_exception(unsigned int ex, void (*trigger_func)(void *data),
			void *data);
void __set_exception_jmpbuf(jmp_buf *addr);
#define set_exception_jmpbuf(jmpbuf) \
	(setjmp(jmpbuf) ? : (__set_exception_jmpbuf(&(jmpbuf)), 0))

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/lib/x86/fake-apic.h                                                 0000644 0000000 0000000 00000000461 00000000000 017125  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef SILLY_APIC_H
#define SILLY_APIC_H

#define APIC_BASE 0x1000
#define APIC_SIZE 0x100

#define APIC_REG_NCPU        0x00
#define APIC_REG_ID          0x04
#define APIC_REG_SIPI_ADDR   0x08
#define APIC_REG_SEND_SIPI   0x0c
#define APIC_REG_IPI_VECTOR  0x10
#define APIC_REG_SEND_IPI    0x14

#endif
                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/lib/x86/fwcfg.c                                                     0000644 0000000 0000000 00000001541 00000000000 016374  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "fwcfg.h"
#include "smp.h"

static struct spinlock lock;

static uint64_t fwcfg_get_u(uint16_t index, int bytes)
{
    uint64_t r = 0;
    uint8_t b;
    int i;

    spin_lock(&lock);
    asm volatile ("out %0, %1" : : "a"(index), "d"((uint16_t)BIOS_CFG_IOPORT));
    for (i = 0; i < bytes; ++i) {
        asm volatile ("in %1, %0" : "=a"(b) : "d"((uint16_t)(BIOS_CFG_IOPORT + 1)));
        r |= (uint64_t)b << (i * 8);
    }
    spin_unlock(&lock);
    return r;
}

uint8_t fwcfg_get_u8(unsigned index)
{
    return fwcfg_get_u(index, 1);
}

uint16_t fwcfg_get_u16(unsigned index)
{
    return fwcfg_get_u(index, 2);
}

uint32_t fwcfg_get_u32(unsigned index)
{
    return fwcfg_get_u(index, 4);
}

uint64_t fwcfg_get_u64(unsigned index)
{
    return fwcfg_get_u(index, 8);
}

unsigned fwcfg_get_nb_cpus(void)
{
    return fwcfg_get_u16(FW_CFG_NB_CPUS);
}
                                                                                                                                                               source/v64/tests/kvm-unit-tests/lib/x86/fwcfg.h                                                     0000644 0000000 0000000 00000002367 00000000000 016410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef FWCFG_H
#define FWCFG_H

#include <stdint.h>

#define FW_CFG_SIGNATURE        0x00
#define FW_CFG_ID               0x01
#define FW_CFG_UUID             0x02
#define FW_CFG_RAM_SIZE         0x03
#define FW_CFG_NOGRAPHIC        0x04
#define FW_CFG_NB_CPUS          0x05
#define FW_CFG_MACHINE_ID       0x06
#define FW_CFG_KERNEL_ADDR      0x07
#define FW_CFG_KERNEL_SIZE      0x08
#define FW_CFG_KERNEL_CMDLINE   0x09
#define FW_CFG_INITRD_ADDR      0x0a
#define FW_CFG_INITRD_SIZE      0x0b
#define FW_CFG_BOOT_DEVICE      0x0c
#define FW_CFG_NUMA             0x0d
#define FW_CFG_BOOT_MENU        0x0e
#define FW_CFG_MAX_CPUS         0x0f
#define FW_CFG_MAX_ENTRY        0x10

#define FW_CFG_WRITE_CHANNEL    0x4000
#define FW_CFG_ARCH_LOCAL       0x8000
#define FW_CFG_ENTRY_MASK       ~(FW_CFG_WRITE_CHANNEL | FW_CFG_ARCH_LOCAL)

#define FW_CFG_INVALID          0xffff

#define BIOS_CFG_IOPORT 0x510

#define FW_CFG_ACPI_TABLES (FW_CFG_ARCH_LOCAL + 0)
#define FW_CFG_SMBIOS_ENTRIES (FW_CFG_ARCH_LOCAL + 1)
#define FW_CFG_IRQ0_OVERRIDE (FW_CFG_ARCH_LOCAL + 2)

uint8_t fwcfg_get_u8(unsigned index);
uint16_t fwcfg_get_u16(unsigned index);
uint32_t fwcfg_get_u32(unsigned index);
uint64_t fwcfg_get_u64(unsigned index);

unsigned fwcfg_get_nb_cpus(void);

#endif

                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/lib/x86/intel-iommu.c                                               0000644 0000000 0000000 00000022621 00000000000 017541  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Intel IOMMU APIs
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Authors:
 *   Peter Xu <peterx@redhat.com>,
 *
 * This work is licensed under the terms of the GNU LGPL, version 2 or
 * later.
 */

#include "intel-iommu.h"
#include "libcflat.h"
#include "pci.h"
#include "atomic.h"

/*
 * VT-d in QEMU currently only support 39 bits address width, which is
 * 3-level translation.
 */
#define VTD_PAGE_LEVEL      3
#define VTD_CE_AW_39BIT     0x1

typedef uint64_t vtd_pte_t;

struct vtd_root_entry {
	/* Quad 1 */
	uint64_t present:1;
	uint64_t __reserved:11;
	uint64_t context_table_p:52;
	/* Quad 2 */
	uint64_t __reserved_2;
} __attribute__ ((packed));
typedef struct vtd_root_entry vtd_re_t;

struct vtd_context_entry {
	/* Quad 1 */
	uint64_t present:1;
	uint64_t disable_fault_report:1;
	uint64_t trans_type:2;
	uint64_t __reserved:8;
	uint64_t slptptr:52;
	/* Quad 2 */
	uint64_t addr_width:3;
	uint64_t __ignore:4;
	uint64_t __reserved_2:1;
	uint64_t domain_id:16;
	uint64_t __reserved_3:40;
} __attribute__ ((packed));
typedef struct vtd_context_entry vtd_ce_t;

struct vtd_irte {
	uint32_t present:1;
	uint32_t fault_disable:1;    /* Fault Processing Disable */
	uint32_t dest_mode:1;        /* Destination Mode */
	uint32_t redir_hint:1;       /* Redirection Hint */
	uint32_t trigger_mode:1;     /* Trigger Mode */
	uint32_t delivery_mode:3;    /* Delivery Mode */
	uint32_t __avail:4;          /* Available spaces for software */
	uint32_t __reserved_0:3;     /* Reserved 0 */
	uint32_t irte_mode:1;        /* IRTE Mode */
	uint32_t vector:8;           /* Interrupt Vector */
	uint32_t __reserved_1:8;     /* Reserved 1 */
	uint32_t dest_id;            /* Destination ID */
	uint16_t source_id:16;       /* Source-ID */
	uint64_t sid_q:2;            /* Source-ID Qualifier */
	uint64_t sid_vtype:2;        /* Source-ID Validation Type */
	uint64_t __reserved_2:44;    /* Reserved 2 */
} __attribute__ ((packed));
typedef struct vtd_irte vtd_irte_t;

#define VTD_RTA_MASK  (PAGE_MASK)
#define VTD_IRTA_MASK (PAGE_MASK)

void *vtd_reg_base;

static uint64_t vtd_root_table(void)
{
	/* No extend root table support yet */
	return vtd_readq(DMAR_RTADDR_REG) & VTD_RTA_MASK;
}

static uint64_t vtd_ir_table(void)
{
	return vtd_readq(DMAR_IRTA_REG) & VTD_IRTA_MASK;
}

static void vtd_gcmd_or(uint32_t cmd)
{
	uint32_t status;

	/* We only allow set one bit for each time */
	assert(is_power_of_2(cmd));

	status = vtd_readl(DMAR_GSTS_REG);
	vtd_writel(DMAR_GCMD_REG, status | cmd);

	if (cmd & VTD_GCMD_ONE_SHOT_BITS) {
		/* One-shot bits are taking effect immediately */
		return;
	}

	/* Make sure IOMMU handled our command request */
	while (!(vtd_readl(DMAR_GSTS_REG) & cmd))
		cpu_relax();
}

static void vtd_dump_init_info(void)
{
	uint32_t version;

	version = vtd_readl(DMAR_VER_REG);

	/* Major version >= 1 */
	assert(((version >> 3) & 0xf) >= 1);

	printf("VT-d version:   %#x\n", version);
	printf("     cap:       %#018lx\n", vtd_readq(DMAR_CAP_REG));
	printf("     ecap:      %#018lx\n", vtd_readq(DMAR_ECAP_REG));
}

static void vtd_setup_root_table(void)
{
	void *root = alloc_page();

	memset(root, 0, PAGE_SIZE);
	vtd_writeq(DMAR_RTADDR_REG, virt_to_phys(root));
	vtd_gcmd_or(VTD_GCMD_ROOT);
	printf("DMAR table address: %#018lx\n", vtd_root_table());
}

static void vtd_setup_ir_table(void)
{
	void *root = alloc_page();

	memset(root, 0, PAGE_SIZE);
	/* 0xf stands for table size (2^(0xf+1) == 65536) */
	vtd_writeq(DMAR_IRTA_REG, virt_to_phys(root) | 0xf);
	vtd_gcmd_or(VTD_GCMD_IR_TABLE);
	printf("IR table address: %#018lx\n", vtd_ir_table());
}

static void vtd_install_pte(vtd_pte_t *root, iova_t iova,
			    phys_addr_t pa, int level_target)
{
	int level;
	unsigned int offset;
	void *page;

	for (level = VTD_PAGE_LEVEL; level > level_target; level--) {
		offset = PGDIR_OFFSET(iova, level);
		if (!(root[offset] & VTD_PTE_RW)) {
			page = alloc_page();
			memset(page, 0, PAGE_SIZE);
			root[offset] = virt_to_phys(page) | VTD_PTE_RW;
		}
		root = (uint64_t *)(phys_to_virt(root[offset] &
						 VTD_PTE_ADDR));
	}

	offset = PGDIR_OFFSET(iova, level);
	root[offset] = pa | VTD_PTE_RW;
	if (level != 1) {
		/* This is huge page */
		root[offset] |= VTD_PTE_HUGE;
	}
}

/**
 * vtd_map_range: setup IO address mapping for specific memory range
 *
 * @sid: source ID of the device to setup
 * @iova: start IO virtual address
 * @pa: start physical address
 * @size: size of the mapping area
 */
void vtd_map_range(uint16_t sid, iova_t iova, phys_addr_t pa, size_t size)
{
	uint8_t bus_n, devfn;
	void *slptptr;
	vtd_ce_t *ce;
	vtd_re_t *re = phys_to_virt(vtd_root_table());

	assert(IS_ALIGNED(iova, SZ_4K));
	assert(IS_ALIGNED(pa, SZ_4K));
	assert(IS_ALIGNED(size, SZ_4K));

	bus_n = PCI_BDF_GET_BUS(sid);
	devfn = PCI_BDF_GET_DEVFN(sid);

	/* Point to the correct root entry */
	re += bus_n;

	if (!re->present) {
		ce = alloc_page();
		memset(ce, 0, PAGE_SIZE);
		memset(re, 0, sizeof(*re));
		re->context_table_p = virt_to_phys(ce) >> VTD_PAGE_SHIFT;
		re->present = 1;
		printf("allocated vt-d root entry for PCI bus %d\n",
		       bus_n);
	} else
		ce = phys_to_virt(re->context_table_p << VTD_PAGE_SHIFT);

	/* Point to the correct context entry */
	ce += devfn;

	if (!ce->present) {
		slptptr = alloc_page();
		memset(slptptr, 0, PAGE_SIZE);
		memset(ce, 0, sizeof(*ce));
		/* To make it simple, domain ID is the same as SID */
		ce->domain_id = sid;
		/* We only test 39 bits width case (3-level paging) */
		ce->addr_width = VTD_CE_AW_39BIT;
		ce->slptptr = virt_to_phys(slptptr) >> VTD_PAGE_SHIFT;
		ce->trans_type = VTD_CONTEXT_TT_MULTI_LEVEL;
		ce->present = 1;
		/* No error reporting yet */
		ce->disable_fault_report = 1;
		printf("allocated vt-d context entry for devfn %#x\n",
		       devfn);
	} else
		slptptr = phys_to_virt(ce->slptptr << VTD_PAGE_SHIFT);

	while (size) {
		/* TODO: currently we only map 4K pages (level = 1) */
		printf("map 4K page IOVA %#lx to %#lx (sid=%#06x)\n",
		       iova, pa, sid);
		vtd_install_pte(slptptr, iova, pa, 1);
		size -= VTD_PAGE_SIZE;
		iova += VTD_PAGE_SIZE;
		pa += VTD_PAGE_SIZE;
	}
}

static uint16_t vtd_intr_index_alloc(void)
{
	static volatile int index_ctr = 0;
	int ctr;

	assert(index_ctr < 65535);
	ctr = atomic_inc_fetch(&index_ctr);
	printf("INTR: alloc IRTE index %d\n", ctr);
	return ctr;
}

static void vtd_setup_irte(struct pci_dev *dev, vtd_irte_t *irte,
			   int vector, int dest_id, trigger_mode_t trigger)
{
	assert(sizeof(vtd_irte_t) == 16);
	memset(irte, 0, sizeof(*irte));
	irte->fault_disable = 1;
	irte->dest_mode = 0;	 /* physical */
	irte->trigger_mode = trigger;
	irte->delivery_mode = 0; /* fixed */
	irte->irte_mode = 0;	 /* remapped */
	irte->vector = vector;
	irte->dest_id = dest_id;
	irte->source_id = dev->bdf;
	irte->sid_q = 0;
	irte->sid_vtype = 1;     /* full-sid verify */
	irte->present = 1;
}

struct vtd_msi_addr {
	uint32_t __dont_care:2;
	uint32_t handle_15:1;	 /* handle[15] */
	uint32_t shv:1;
	uint32_t interrupt_format:1;
	uint32_t handle_0_14:15; /* handle[0:14] */
	uint32_t head:12;	 /* 0xfee */
	uint32_t addr_hi;	 /* not used except with x2apic */
} __attribute__ ((packed));
typedef struct vtd_msi_addr vtd_msi_addr_t;

struct vtd_msi_data {
	uint16_t __reserved;
	uint16_t subhandle;
} __attribute__ ((packed));
typedef struct vtd_msi_data vtd_msi_data_t;

struct vtd_ioapic_entry {
	uint64_t vector:8;
	uint64_t __zeros:3;
	uint64_t index_15:1;
	uint64_t delivery_status:1;
	uint64_t polarity:1;
	uint64_t remote_irr:1;
	uint64_t trigger_mode:1;
	uint64_t mask:1;
	uint64_t __zeros_2:31;
	uint64_t interrupt_format:1;
	uint64_t index_0_14:15;
} __attribute__ ((packed));
typedef struct vtd_ioapic_entry vtd_ioapic_entry_t;

/**
 * vtd_setup_msi - setup MSI message for a device
 *
 * @dev: PCI device to setup MSI
 * @vector: interrupt vector
 * @dest_id: destination processor
 */
bool vtd_setup_msi(struct pci_dev *dev, int vector, int dest_id)
{
	vtd_msi_data_t msi_data = {};
	vtd_msi_addr_t msi_addr = {};
	vtd_irte_t *irte = phys_to_virt(vtd_ir_table());
	uint16_t index = vtd_intr_index_alloc();

	assert(sizeof(vtd_msi_addr_t) == 8);
	assert(sizeof(vtd_msi_data_t) == 4);

	/* Use edge irq as default */
	vtd_setup_irte(dev, irte + index, vector,
		       dest_id, TRIGGER_EDGE);

	msi_addr.handle_15 = index >> 15 & 1;
	msi_addr.shv = 0;
	msi_addr.interrupt_format = 1;
	msi_addr.handle_0_14 = index & 0x7fff;
	msi_addr.head = 0xfee;
	msi_data.subhandle = 0;

	printf("%s: msi_addr=%#" PRIx64 ", msi_data=%#x\n", __func__,
		*(uint64_t *)&msi_addr, *(uint32_t *)&msi_data);

	return pci_setup_msi(dev, *(uint64_t *)&msi_addr,
			     *(uint32_t *)&msi_data);
}

void vtd_setup_ioapic_irq(struct pci_dev *dev, int vector,
			  int dest_id, trigger_mode_t trigger)
{
	vtd_ioapic_entry_t entry = {};
	vtd_irte_t *irte = phys_to_virt(vtd_ir_table());
	ioapic_redir_entry_t *entry_2 = (ioapic_redir_entry_t *)&entry;
	uint16_t index = vtd_intr_index_alloc();
	uint8_t line;

	assert(dev);
	assert(sizeof(vtd_ioapic_entry_t) == 8);

	vtd_setup_irte(dev, irte + index, vector,
		       dest_id, trigger);

	entry.vector = vector;
	entry.trigger_mode = trigger;
	entry.index_15 = (index >> 15) & 1;
	entry.interrupt_format = 1;
	entry.index_0_14 = index & 0x7fff;

	line = pci_intx_line(dev);
	ioapic_write_redir(line, *entry_2);
}

void vtd_init(void)
{
	setup_vm();
	smp_init();

	vtd_reg_base = ioremap(Q35_HOST_BRIDGE_IOMMU_ADDR, PAGE_SIZE);

	vtd_dump_init_info();
	vtd_gcmd_or(VTD_GCMD_QI); /* Enable QI */
	vtd_setup_root_table();
	vtd_setup_ir_table();
	vtd_gcmd_or(VTD_GCMD_DMAR); /* Enable DMAR */
	vtd_gcmd_or(VTD_GCMD_IR);   /* Enable IR */
}
                                                                                                               source/v64/tests/kvm-unit-tests/lib/x86/intel-iommu.h                                               0000644 0000000 0000000 00000013172 00000000000 017547  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Intel IOMMU header
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Authors:
 *   Peter Xu <peterx@redhat.com>,
 *
 * This work is licensed under the terms of the GNU LGPL, version 2 or
 * later.
 *
 * (From include/linux/intel-iommu.h)
 */

#ifndef __INTEL_IOMMU_H__
#define __INTEL_IOMMU_H__

#include "libcflat.h"
#include "vm.h"
#include "isr.h"
#include "smp.h"
#include "desc.h"
#include "pci.h"
#include "asm/io.h"
#include "apic.h"

#define Q35_HOST_BRIDGE_IOMMU_ADDR  0xfed90000ULL
#define VTD_PAGE_SHIFT              PAGE_SHIFT
#define VTD_PAGE_SIZE               PAGE_SIZE

/*
 * Intel IOMMU register specification
 */
#define DMAR_VER_REG            0x0  /* Arch version supported by this IOMMU */
#define DMAR_CAP_REG            0x8  /* Hardware supported capabilities */
#define DMAR_CAP_REG_HI         0xc  /* High 32-bit of DMAR_CAP_REG */
#define DMAR_ECAP_REG           0x10 /* Extended capabilities supported */
#define DMAR_ECAP_REG_HI        0X14
#define DMAR_GCMD_REG           0x18 /* Global command */
#define DMAR_GSTS_REG           0x1c /* Global status */
#define DMAR_RTADDR_REG         0x20 /* Root entry table */
#define DMAR_RTADDR_REG_HI      0X24
#define DMAR_CCMD_REG           0x28 /* Context command */
#define DMAR_CCMD_REG_HI        0x2c
#define DMAR_FSTS_REG           0x34 /* Fault status */
#define DMAR_FECTL_REG          0x38 /* Fault control */
#define DMAR_FEDATA_REG         0x3c /* Fault event interrupt data */
#define DMAR_FEADDR_REG         0x40 /* Fault event interrupt addr */
#define DMAR_FEUADDR_REG        0x44 /* Upper address */
#define DMAR_AFLOG_REG          0x58 /* Advanced fault control */
#define DMAR_AFLOG_REG_HI       0X5c
#define DMAR_PMEN_REG           0x64 /* Enable protected memory region */
#define DMAR_PLMBASE_REG        0x68 /* PMRR low addr */
#define DMAR_PLMLIMIT_REG       0x6c /* PMRR low limit */
#define DMAR_PHMBASE_REG        0x70 /* PMRR high base addr */
#define DMAR_PHMBASE_REG_HI     0X74
#define DMAR_PHMLIMIT_REG       0x78 /* PMRR high limit */
#define DMAR_PHMLIMIT_REG_HI    0x7c
#define DMAR_IQH_REG            0x80 /* Invalidation queue head */
#define DMAR_IQH_REG_HI         0X84
#define DMAR_IQT_REG            0x88 /* Invalidation queue tail */
#define DMAR_IQT_REG_HI         0X8c
#define DMAR_IQA_REG            0x90 /* Invalidation queue addr */
#define DMAR_IQA_REG_HI         0x94
#define DMAR_ICS_REG            0x9c /* Invalidation complete status */
#define DMAR_IRTA_REG           0xb8 /* Interrupt remapping table addr */
#define DMAR_IRTA_REG_HI        0xbc
#define DMAR_IECTL_REG          0xa0 /* Invalidation event control */
#define DMAR_IEDATA_REG         0xa4 /* Invalidation event data */
#define DMAR_IEADDR_REG         0xa8 /* Invalidation event address */
#define DMAR_IEUADDR_REG        0xac /* Invalidation event address */
#define DMAR_PQH_REG            0xc0 /* Page request queue head */
#define DMAR_PQH_REG_HI         0xc4
#define DMAR_PQT_REG            0xc8 /* Page request queue tail*/
#define DMAR_PQT_REG_HI         0xcc
#define DMAR_PQA_REG            0xd0 /* Page request queue address */
#define DMAR_PQA_REG_HI         0xd4
#define DMAR_PRS_REG            0xdc /* Page request status */
#define DMAR_PECTL_REG          0xe0 /* Page request event control */
#define DMAR_PEDATA_REG         0xe4 /* Page request event data */
#define DMAR_PEADDR_REG         0xe8 /* Page request event address */
#define DMAR_PEUADDR_REG        0xec /* Page event upper address */
#define DMAR_MTRRCAP_REG        0x100 /* MTRR capability */
#define DMAR_MTRRCAP_REG_HI     0x104
#define DMAR_MTRRDEF_REG        0x108 /* MTRR default type */
#define DMAR_MTRRDEF_REG_HI     0x10c

#define VTD_GCMD_IR_TABLE       0x1000000
#define VTD_GCMD_IR             0x2000000
#define VTD_GCMD_QI             0x4000000
#define VTD_GCMD_WBF            0x8000000  /* Write Buffer Flush */
#define VTD_GCMD_SFL            0x20000000 /* Set Fault Log */
#define VTD_GCMD_ROOT           0x40000000
#define VTD_GCMD_DMAR           0x80000000
#define VTD_GCMD_ONE_SHOT_BITS  (VTD_GCMD_IR_TABLE | VTD_GCMD_WBF | \
				 VTD_GCMD_SFL | VTD_GCMD_ROOT)

/* Supported Adjusted Guest Address Widths */
#define VTD_CAP_SAGAW_SHIFT         8
/* 39-bit AGAW, 3-level page-table */
#define VTD_CAP_SAGAW_39bit         (0x2ULL << VTD_CAP_SAGAW_SHIFT)
/* 48-bit AGAW, 4-level page-table */
#define VTD_CAP_SAGAW_48bit         (0x4ULL << VTD_CAP_SAGAW_SHIFT)
#define VTD_CAP_SAGAW               VTD_CAP_SAGAW_39bit

/* Both 1G/2M huge pages */
#define VTD_CAP_SLLPS               ((1ULL << 34) | (1ULL << 35))

#define VTD_CONTEXT_TT_MULTI_LEVEL  0
#define VTD_CONTEXT_TT_DEV_IOTLB    1
#define VTD_CONTEXT_TT_PASS_THROUGH 2

#define VTD_PTE_R                   (1 << 0)
#define VTD_PTE_W                   (1 << 1)
#define VTD_PTE_RW                  (VTD_PTE_R | VTD_PTE_W)
#define VTD_PTE_ADDR                GENMASK_ULL(63, 12)
#define VTD_PTE_HUGE                (1 << 7)

extern void *vtd_reg_base;
#define vtd_reg(reg) ({ assert(vtd_reg_base); \
			(volatile void *)(vtd_reg_base + reg); })

static inline void vtd_writel(unsigned int reg, uint32_t value)
{
	__raw_writel(value, vtd_reg(reg));
}

static inline void vtd_writeq(unsigned int reg, uint64_t value)
{
	__raw_writeq(value, vtd_reg(reg));
}

static inline uint32_t vtd_readl(unsigned int reg)
{
	return __raw_readl(vtd_reg(reg));
}

static inline uint64_t vtd_readq(unsigned int reg)
{
	return __raw_readq(vtd_reg(reg));
}

void vtd_init(void);
void vtd_map_range(uint16_t sid, phys_addr_t iova, phys_addr_t pa, size_t size);
bool vtd_setup_msi(struct pci_dev *dev, int vector, int dest_id);
void vtd_setup_ioapic_irq(struct pci_dev *dev, int vector,
			  int dest_id, trigger_mode_t trigger);

#endif
                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/lib/x86/io.c                                                        0000644 0000000 0000000 00000004175 00000000000 015715  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "vm.h"
#include "smp.h"
#include "asm/io.h"
#include "asm/page.h"
#ifndef USE_SERIAL
#define USE_SERIAL
#endif

static struct spinlock lock;
static int serial_iobase = 0x3f8;
static int serial_inited = 0;

static void serial_outb(char ch)
{
        u8 lsr;

        do {
                lsr = inb(serial_iobase + 0x05);
        } while (!(lsr & 0x20));

        outb(ch, serial_iobase + 0x00);
}

static void serial_init(void)
{
        u8 lcr;

        /* set DLAB */
        lcr = inb(serial_iobase + 0x03);
        lcr |= 0x80;
        outb(lcr, serial_iobase + 0x03);

        /* set baud rate to 115200 */
        outb(0x01, serial_iobase + 0x00);
        outb(0x00, serial_iobase + 0x01);

        /* clear DLAB */
        lcr = inb(serial_iobase + 0x03);
        lcr &= ~0x80;
        outb(lcr, serial_iobase + 0x03);
}

static void print_serial(const char *buf)
{
	unsigned long len = strlen(buf);
#ifdef USE_SERIAL
        unsigned long i;
        if (!serial_inited) {
            serial_init();
            serial_inited = 1;
        }

        for (i = 0; i < len; i++) {
            serial_outb(buf[i]);
        }
#else
        asm volatile ("rep/outsb" : "+S"(buf), "+c"(len) : "d"(0xf1));
#endif
}

void puts(const char *s)
{
	spin_lock(&lock);
	print_serial(s);
	spin_unlock(&lock);
}

void exit(int code)
{
#ifdef USE_SERIAL
        static const char shutdown_str[8] = "Shutdown";
        int i;

        /* test device exit (with status) */
        outl(code, 0xf4);

        /* if that failed, try the Bochs poweroff port */
        for (i = 0; i < 8; i++) {
                outb(shutdown_str[i], 0x8900);
        }
#else
        asm volatile("out %0, %1" : : "a"(code), "d"((short)0xf4));
#endif
}

void __iomem *ioremap(phys_addr_t phys_addr, size_t size)
{
	phys_addr_t base = phys_addr & PAGE_MASK;
	phys_addr_t offset = phys_addr - base;

	/*
	 * The kernel sets PTEs for an ioremap() with page cache disabled,
	 * but we do not do that right now. It would make sense that I/O
	 * mappings would be uncached - and may help us find bugs when we
	 * properly map that way.
	 */
	return vmap(phys_addr, size) + offset;
}
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/lib/x86/isr.c                                                       0000644 0000000 0000000 00000005362 00000000000 016102  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "isr.h"
#include "vm.h"
#include "desc.h"

extern char isr_entry_point[];

asm (
    "isr_entry_point: \n"
#ifdef __x86_64__
    "push %r15 \n\t"
    "push %r14 \n\t"
    "push %r13 \n\t"
    "push %r12 \n\t"
    "push %r11 \n\t"
    "push %r10 \n\t"
    "push %r9  \n\t"
    "push %r8  \n\t"
#endif
    "push %"R "di \n\t"
    "push %"R "si \n\t"
    "push %"R "bp \n\t"
    "push %"R "sp \n\t"
    "push %"R "bx \n\t"
    "push %"R "dx \n\t"
    "push %"R "cx \n\t"
    "push %"R "ax \n\t"
#ifdef __x86_64__
    "mov %rsp, %rdi \n\t"
    "callq *8*16(%rsp) \n\t"
#else
    "push %esp \n\t"
    "calll *4+4*8(%esp) \n\t"
    "add $4, %esp \n\t"
#endif
    "pop %"R "ax \n\t"
    "pop %"R "cx \n\t"
    "pop %"R "dx \n\t"
    "pop %"R "bx \n\t"
    "pop %"R "bp \n\t"
    "pop %"R "bp \n\t"
    "pop %"R "si \n\t"
    "pop %"R "di \n\t"
#ifdef __x86_64__
    "pop %r8  \n\t"
    "pop %r9  \n\t"
    "pop %r10 \n\t"
    "pop %r11 \n\t"
    "pop %r12 \n\t"
    "pop %r13 \n\t"
    "pop %r14 \n\t"
    "pop %r15 \n\t"
#endif
    ".globl isr_iret_ip\n\t"
#ifdef __x86_64__
    "add $8, %rsp \n\t"
    "isr_iret_ip: \n\t"
    "iretq \n\t"
#else
    "add $4, %esp \n\t"
    "isr_iret_ip: \n\t"
    "iretl \n\t"
#endif
    );

void handle_irq(unsigned vec, void (*func)(isr_regs_t *regs))
{
    u8 *thunk = vmalloc(50);

    set_idt_entry(vec, thunk, 0);

#ifdef __x86_64__
    /* sub $8, %rsp */
    *thunk++ = 0x48; *thunk++ = 0x83; *thunk++ = 0xec; *thunk++ = 0x08;
    /* mov $func_low, %(rsp) */
    *thunk++ = 0xc7; *thunk++ = 0x04; *thunk++ = 0x24;
    *(u32 *)thunk = (ulong)func; thunk += 4;
    /* mov $func_high, %(rsp+4) */
    *thunk++ = 0xc7; *thunk++ = 0x44; *thunk++ = 0x24; *thunk++ = 0x04;
    *(u32 *)thunk = (ulong)func >> 32; thunk += 4;
    /* jmp isr_entry_point */
    *thunk ++ = 0xe9;
    *(u32 *)thunk = (ulong)isr_entry_point - (ulong)(thunk + 4);
#else
    /* push $func */
    *thunk++ = 0x68;
    *(u32 *)thunk = (ulong)func; thunk += 4;
    /* jmp isr_entry_point */
    *thunk++ = 0xe9;
    *(u32 *)thunk = (ulong)isr_entry_point - (ulong)(thunk + 4);
#endif
}

void handle_external_interrupt(int vector)
{
	idt_entry_t *idt = &boot_idt[vector];
	unsigned long entry =
		idt->offset0 | ((unsigned long)idt->offset1 << 16);
#ifdef __x86_64__
	unsigned long tmp;
	entry |= ((unsigned long)idt->offset2 << 32);
#endif

	asm volatile(
#ifdef __x86_64__
		     "mov %%rsp, %[sp]\n\t"
		     "and $0xfffffffffffffff0, %%rsp\n\t"
		     "push $%c[ss]\n\t"
		     "push %[sp]\n\t"
#endif
		     "pushf\n\t"
		     "orl $0x200, (%%"R "sp)\n\t"
		     "push $%c[cs]\n\t"
		     "call *%[entry]\n\t"
		     :
#ifdef __x86_64__
		     [sp]"=&r"(tmp)
#endif
		     :
		     [entry]"r"(entry),
		     [ss]"i"(KERNEL_DS),
		     [cs]"i"(KERNEL_CS)
		     );
}
                                                                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/lib/x86/isr.h                                                       0000644 0000000 0000000 00000000435 00000000000 016103  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __ISR_TEST__
#define __ISR_TEST__

typedef struct {
    ulong regs[sizeof(ulong)*2];
    ulong func;
    ulong rip;
    ulong cs;
    ulong rflags;
} isr_regs_t;

void handle_irq(unsigned vec, void (*func)(isr_regs_t *regs));
void handle_external_interrupt(int vector);
#endif
                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/lib/x86/msr.h                                                       0000644 0000000 0000000 00000035120 00000000000 016106  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef _ASM_X86_MSR_INDEX_H
#define _ASM_X86_MSR_INDEX_H

/* CPU model specific register (MSR) numbers */

/* x86-64 specific MSRs */
#define MSR_EFER		0xc0000080 /* extended feature register */
#define MSR_STAR		0xc0000081 /* legacy mode SYSCALL target */
#define MSR_LSTAR		0xc0000082 /* long mode SYSCALL target */
#define MSR_CSTAR		0xc0000083 /* compat mode SYSCALL target */
#define MSR_SYSCALL_MASK	0xc0000084 /* EFLAGS mask for syscall */
#define MSR_FS_BASE		0xc0000100 /* 64bit FS base */
#define MSR_GS_BASE		0xc0000101 /* 64bit GS base */
#define MSR_KERNEL_GS_BASE	0xc0000102 /* SwapGS GS shadow */
#define MSR_TSC_AUX		0xc0000103 /* Auxiliary TSC */

/* EFER bits: */
#define _EFER_SCE		0  /* SYSCALL/SYSRET */
#define _EFER_LME		8  /* Long mode enable */
#define _EFER_LMA		10 /* Long mode active (read-only) */
#define _EFER_NX		11 /* No execute enable */
#define _EFER_SVME		12 /* Enable virtualization */
#define _EFER_LMSLE		13 /* Long Mode Segment Limit Enable */
#define _EFER_FFXSR		14 /* Enable Fast FXSAVE/FXRSTOR */

#define EFER_SCE		(1<<_EFER_SCE)
#define EFER_LME		(1<<_EFER_LME)
#define EFER_LMA		(1<<_EFER_LMA)
#define EFER_NX			(1<<_EFER_NX)
#define EFER_SVME		(1<<_EFER_SVME)
#define EFER_LMSLE		(1<<_EFER_LMSLE)
#define EFER_FFXSR		(1<<_EFER_FFXSR)

/* Intel MSRs. Some also available on other CPUs */
#define MSR_IA32_PERFCTR0		0x000000c1
#define MSR_IA32_PERFCTR1		0x000000c2
#define MSR_FSB_FREQ			0x000000cd

#define MSR_MTRRcap			0x000000fe
#define MSR_IA32_BBL_CR_CTL		0x00000119

#define MSR_IA32_SYSENTER_CS		0x00000174
#define MSR_IA32_SYSENTER_ESP		0x00000175
#define MSR_IA32_SYSENTER_EIP		0x00000176

#define MSR_IA32_MCG_CAP		0x00000179
#define MSR_IA32_MCG_STATUS		0x0000017a
#define MSR_IA32_MCG_CTL		0x0000017b

#define MSR_IA32_PEBS_ENABLE		0x000003f1
#define MSR_IA32_DS_AREA		0x00000600
#define MSR_IA32_PERF_CAPABILITIES	0x00000345

#define MSR_MTRRfix64K_00000		0x00000250
#define MSR_MTRRfix16K_80000		0x00000258
#define MSR_MTRRfix16K_A0000		0x00000259
#define MSR_MTRRfix4K_C0000		0x00000268
#define MSR_MTRRfix4K_C8000		0x00000269
#define MSR_MTRRfix4K_D0000		0x0000026a
#define MSR_MTRRfix4K_D8000		0x0000026b
#define MSR_MTRRfix4K_E0000		0x0000026c
#define MSR_MTRRfix4K_E8000		0x0000026d
#define MSR_MTRRfix4K_F0000		0x0000026e
#define MSR_MTRRfix4K_F8000		0x0000026f
#define MSR_MTRRdefType			0x000002ff

#define MSR_IA32_CR_PAT			0x00000277

#define MSR_IA32_DEBUGCTLMSR		0x000001d9
#define MSR_IA32_LASTBRANCHFROMIP	0x000001db
#define MSR_IA32_LASTBRANCHTOIP		0x000001dc
#define MSR_IA32_LASTINTFROMIP		0x000001dd
#define MSR_IA32_LASTINTTOIP		0x000001de

/* DEBUGCTLMSR bits (others vary by model): */
#define DEBUGCTLMSR_LBR			(1UL <<  0) /* last branch recording */
#define DEBUGCTLMSR_BTF			(1UL <<  1) /* single-step on branches */
#define DEBUGCTLMSR_TR			(1UL <<  6)
#define DEBUGCTLMSR_BTS			(1UL <<  7)
#define DEBUGCTLMSR_BTINT		(1UL <<  8)
#define DEBUGCTLMSR_BTS_OFF_OS		(1UL <<  9)
#define DEBUGCTLMSR_BTS_OFF_USR		(1UL << 10)
#define DEBUGCTLMSR_FREEZE_LBRS_ON_PMI	(1UL << 11)

#define MSR_IA32_MC0_CTL		0x00000400
#define MSR_IA32_MC0_STATUS		0x00000401
#define MSR_IA32_MC0_ADDR		0x00000402
#define MSR_IA32_MC0_MISC		0x00000403

#define MSR_IA32_MCx_CTL(x)		(MSR_IA32_MC0_CTL + 4*(x))
#define MSR_IA32_MCx_STATUS(x)		(MSR_IA32_MC0_STATUS + 4*(x))
#define MSR_IA32_MCx_ADDR(x)		(MSR_IA32_MC0_ADDR + 4*(x))
#define MSR_IA32_MCx_MISC(x)		(MSR_IA32_MC0_MISC + 4*(x))

/* These are consecutive and not in the normal 4er MCE bank block */
#define MSR_IA32_MC0_CTL2		0x00000280
#define MSR_IA32_MCx_CTL2(x)		(MSR_IA32_MC0_CTL2 + (x))

#define CMCI_EN			(1ULL << 30)
#define CMCI_THRESHOLD_MASK		0xffffULL

#define MSR_P6_PERFCTR0			0x000000c1
#define MSR_P6_PERFCTR1			0x000000c2
#define MSR_P6_EVNTSEL0			0x00000186
#define MSR_P6_EVNTSEL1			0x00000187

/* AMD64 MSRs. Not complete. See the architecture manual for a more
   complete list. */

#define MSR_AMD64_PATCH_LEVEL		0x0000008b
#define MSR_AMD64_NB_CFG		0xc001001f
#define MSR_AMD64_PATCH_LOADER		0xc0010020
#define MSR_AMD64_OSVW_ID_LENGTH	0xc0010140
#define MSR_AMD64_OSVW_STATUS		0xc0010141
#define MSR_AMD64_DC_CFG		0xc0011022
#define MSR_AMD64_IBSFETCHCTL		0xc0011030
#define MSR_AMD64_IBSFETCHLINAD		0xc0011031
#define MSR_AMD64_IBSFETCHPHYSAD	0xc0011032
#define MSR_AMD64_IBSOPCTL		0xc0011033
#define MSR_AMD64_IBSOPRIP		0xc0011034
#define MSR_AMD64_IBSOPDATA		0xc0011035
#define MSR_AMD64_IBSOPDATA2		0xc0011036
#define MSR_AMD64_IBSOPDATA3		0xc0011037
#define MSR_AMD64_IBSDCLINAD		0xc0011038
#define MSR_AMD64_IBSDCPHYSAD		0xc0011039
#define MSR_AMD64_IBSCTL		0xc001103a

/* Fam 10h MSRs */
#define MSR_FAM10H_MMIO_CONF_BASE	0xc0010058
#define FAM10H_MMIO_CONF_ENABLE		(1<<0)
#define FAM10H_MMIO_CONF_BUSRANGE_MASK	0xf
#define FAM10H_MMIO_CONF_BUSRANGE_SHIFT 2
#define FAM10H_MMIO_CONF_BASE_MASK	0xfffffff
#define FAM10H_MMIO_CONF_BASE_SHIFT	20
#define MSR_FAM10H_NODE_ID		0xc001100c

/* K8 MSRs */
#define MSR_K8_TOP_MEM1			0xc001001a
#define MSR_K8_TOP_MEM2			0xc001001d
#define MSR_K8_SYSCFG			0xc0010010
#define MSR_K8_INT_PENDING_MSG		0xc0010055
/* C1E active bits in int pending message */
#define K8_INTP_C1E_ACTIVE_MASK		0x18000000
#define MSR_K8_TSEG_ADDR		0xc0010112
#define K8_MTRRFIXRANGE_DRAM_ENABLE	0x00040000 /* MtrrFixDramEn bit    */
#define K8_MTRRFIXRANGE_DRAM_MODIFY	0x00080000 /* MtrrFixDramModEn bit */
#define K8_MTRR_RDMEM_WRMEM_MASK	0x18181818 /* Mask: RdMem|WrMem    */

/* K7 MSRs */
#define MSR_K7_EVNTSEL0			0xc0010000
#define MSR_K7_PERFCTR0			0xc0010004
#define MSR_K7_EVNTSEL1			0xc0010001
#define MSR_K7_PERFCTR1			0xc0010005
#define MSR_K7_EVNTSEL2			0xc0010002
#define MSR_K7_PERFCTR2			0xc0010006
#define MSR_K7_EVNTSEL3			0xc0010003
#define MSR_K7_PERFCTR3			0xc0010007
#define MSR_K7_CLK_CTL			0xc001001b
#define MSR_K7_HWCR			0xc0010015
#define MSR_K7_FID_VID_CTL		0xc0010041
#define MSR_K7_FID_VID_STATUS		0xc0010042

/* K6 MSRs */
#define MSR_K6_EFER			0xc0000080
#define MSR_K6_STAR			0xc0000081
#define MSR_K6_WHCR			0xc0000082
#define MSR_K6_UWCCR			0xc0000085
#define MSR_K6_EPMR			0xc0000086
#define MSR_K6_PSOR			0xc0000087
#define MSR_K6_PFIR			0xc0000088

/* Centaur-Hauls/IDT defined MSRs. */
#define MSR_IDT_FCR1			0x00000107
#define MSR_IDT_FCR2			0x00000108
#define MSR_IDT_FCR3			0x00000109
#define MSR_IDT_FCR4			0x0000010a

#define MSR_IDT_MCR0			0x00000110
#define MSR_IDT_MCR1			0x00000111
#define MSR_IDT_MCR2			0x00000112
#define MSR_IDT_MCR3			0x00000113
#define MSR_IDT_MCR4			0x00000114
#define MSR_IDT_MCR5			0x00000115
#define MSR_IDT_MCR6			0x00000116
#define MSR_IDT_MCR7			0x00000117
#define MSR_IDT_MCR_CTRL		0x00000120

/* VIA Cyrix defined MSRs*/
#define MSR_VIA_FCR			0x00001107
#define MSR_VIA_LONGHAUL		0x0000110a
#define MSR_VIA_RNG			0x0000110b
#define MSR_VIA_BCR2			0x00001147

/* Transmeta defined MSRs */
#define MSR_TMTA_LONGRUN_CTRL		0x80868010
#define MSR_TMTA_LONGRUN_FLAGS		0x80868011
#define MSR_TMTA_LRTI_READOUT		0x80868018
#define MSR_TMTA_LRTI_VOLT_MHZ		0x8086801a

/* Intel defined MSRs. */
#define MSR_IA32_P5_MC_ADDR		0x00000000
#define MSR_IA32_P5_MC_TYPE		0x00000001
#define MSR_IA32_TSC			0x00000010
#define MSR_IA32_PLATFORM_ID		0x00000017
#define MSR_IA32_EBL_CR_POWERON		0x0000002a
#define MSR_IA32_FEATURE_CONTROL        0x0000003a

#define FEATURE_CONTROL_LOCKED				(1<<0)
#define FEATURE_CONTROL_VMXON_ENABLED_INSIDE_SMX	(1<<1)
#define FEATURE_CONTROL_VMXON_ENABLED_OUTSIDE_SMX	(1<<2)

#define MSR_IA32_APICBASE		0x0000001b
#define MSR_IA32_APICBASE_BSP		(1<<8)
#define MSR_IA32_APICBASE_ENABLE	(1<<11)
#define MSR_IA32_APICBASE_BASE		(0xfffff<<12)

#define MSR_IA32_UCODE_WRITE		0x00000079
#define MSR_IA32_UCODE_REV		0x0000008b

#define MSR_IA32_PERF_STATUS		0x00000198
#define MSR_IA32_PERF_CTL		0x00000199

#define MSR_IA32_MPERF			0x000000e7
#define MSR_IA32_APERF			0x000000e8

#define MSR_IA32_THERM_CONTROL		0x0000019a
#define MSR_IA32_THERM_INTERRUPT	0x0000019b

#define THERM_INT_LOW_ENABLE		(1 << 0)
#define THERM_INT_HIGH_ENABLE		(1 << 1)

#define MSR_IA32_THERM_STATUS		0x0000019c

#define THERM_STATUS_PROCHOT		(1 << 0)

#define MSR_THERM2_CTL			0x0000019d

#define MSR_THERM2_CTL_TM_SELECT	(1ULL << 16)

#define MSR_IA32_MISC_ENABLE		0x000001a0

#define MSR_IA32_TEMPERATURE_TARGET	0x000001a2

/* MISC_ENABLE bits: architectural */
#define MSR_IA32_MISC_ENABLE_FAST_STRING	(1ULL << 0)
#define MSR_IA32_MISC_ENABLE_TCC		(1ULL << 1)
#define MSR_IA32_MISC_ENABLE_EMON		(1ULL << 7)
#define MSR_IA32_MISC_ENABLE_BTS_UNAVAIL	(1ULL << 11)
#define MSR_IA32_MISC_ENABLE_PEBS_UNAVAIL	(1ULL << 12)
#define MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP	(1ULL << 16)
#define MSR_IA32_MISC_ENABLE_MWAIT		(1ULL << 18)
#define MSR_IA32_MISC_ENABLE_LIMIT_CPUID	(1ULL << 22)
#define MSR_IA32_MISC_ENABLE_XTPR_DISABLE	(1ULL << 23)
#define MSR_IA32_MISC_ENABLE_XD_DISABLE		(1ULL << 34)

/* MISC_ENABLE bits: model-specific, meaning may vary from core to core */
#define MSR_IA32_MISC_ENABLE_X87_COMPAT		(1ULL << 2)
#define MSR_IA32_MISC_ENABLE_TM1		(1ULL << 3)
#define MSR_IA32_MISC_ENABLE_SPLIT_LOCK_DISABLE	(1ULL << 4)
#define MSR_IA32_MISC_ENABLE_L3CACHE_DISABLE	(1ULL << 6)
#define MSR_IA32_MISC_ENABLE_SUPPRESS_LOCK	(1ULL << 8)
#define MSR_IA32_MISC_ENABLE_PREFETCH_DISABLE	(1ULL << 9)
#define MSR_IA32_MISC_ENABLE_FERR		(1ULL << 10)
#define MSR_IA32_MISC_ENABLE_FERR_MULTIPLEX	(1ULL << 10)
#define MSR_IA32_MISC_ENABLE_TM2		(1ULL << 13)
#define MSR_IA32_MISC_ENABLE_ADJ_PREF_DISABLE	(1ULL << 19)
#define MSR_IA32_MISC_ENABLE_SPEEDSTEP_LOCK	(1ULL << 20)
#define MSR_IA32_MISC_ENABLE_L1D_CONTEXT	(1ULL << 24)
#define MSR_IA32_MISC_ENABLE_DCU_PREF_DISABLE	(1ULL << 37)
#define MSR_IA32_MISC_ENABLE_TURBO_DISABLE	(1ULL << 38)
#define MSR_IA32_MISC_ENABLE_IP_PREF_DISABLE	(1ULL << 39)

/* P4/Xeon+ specific */
#define MSR_IA32_MCG_EAX		0x00000180
#define MSR_IA32_MCG_EBX		0x00000181
#define MSR_IA32_MCG_ECX		0x00000182
#define MSR_IA32_MCG_EDX		0x00000183
#define MSR_IA32_MCG_ESI		0x00000184
#define MSR_IA32_MCG_EDI		0x00000185
#define MSR_IA32_MCG_EBP		0x00000186
#define MSR_IA32_MCG_ESP		0x00000187
#define MSR_IA32_MCG_EFLAGS		0x00000188
#define MSR_IA32_MCG_EIP		0x00000189
#define MSR_IA32_MCG_RESERVED		0x0000018a

/* Pentium IV performance counter MSRs */
#define MSR_P4_BPU_PERFCTR0		0x00000300
#define MSR_P4_BPU_PERFCTR1		0x00000301
#define MSR_P4_BPU_PERFCTR2		0x00000302
#define MSR_P4_BPU_PERFCTR3		0x00000303
#define MSR_P4_MS_PERFCTR0		0x00000304
#define MSR_P4_MS_PERFCTR1		0x00000305
#define MSR_P4_MS_PERFCTR2		0x00000306
#define MSR_P4_MS_PERFCTR3		0x00000307
#define MSR_P4_FLAME_PERFCTR0		0x00000308
#define MSR_P4_FLAME_PERFCTR1		0x00000309
#define MSR_P4_FLAME_PERFCTR2		0x0000030a
#define MSR_P4_FLAME_PERFCTR3		0x0000030b
#define MSR_P4_IQ_PERFCTR0		0x0000030c
#define MSR_P4_IQ_PERFCTR1		0x0000030d
#define MSR_P4_IQ_PERFCTR2		0x0000030e
#define MSR_P4_IQ_PERFCTR3		0x0000030f
#define MSR_P4_IQ_PERFCTR4		0x00000310
#define MSR_P4_IQ_PERFCTR5		0x00000311
#define MSR_P4_BPU_CCCR0		0x00000360
#define MSR_P4_BPU_CCCR1		0x00000361
#define MSR_P4_BPU_CCCR2		0x00000362
#define MSR_P4_BPU_CCCR3		0x00000363
#define MSR_P4_MS_CCCR0			0x00000364
#define MSR_P4_MS_CCCR1			0x00000365
#define MSR_P4_MS_CCCR2			0x00000366
#define MSR_P4_MS_CCCR3			0x00000367
#define MSR_P4_FLAME_CCCR0		0x00000368
#define MSR_P4_FLAME_CCCR1		0x00000369
#define MSR_P4_FLAME_CCCR2		0x0000036a
#define MSR_P4_FLAME_CCCR3		0x0000036b
#define MSR_P4_IQ_CCCR0			0x0000036c
#define MSR_P4_IQ_CCCR1			0x0000036d
#define MSR_P4_IQ_CCCR2			0x0000036e
#define MSR_P4_IQ_CCCR3			0x0000036f
#define MSR_P4_IQ_CCCR4			0x00000370
#define MSR_P4_IQ_CCCR5			0x00000371
#define MSR_P4_ALF_ESCR0		0x000003ca
#define MSR_P4_ALF_ESCR1		0x000003cb
#define MSR_P4_BPU_ESCR0		0x000003b2
#define MSR_P4_BPU_ESCR1		0x000003b3
#define MSR_P4_BSU_ESCR0		0x000003a0
#define MSR_P4_BSU_ESCR1		0x000003a1
#define MSR_P4_CRU_ESCR0		0x000003b8
#define MSR_P4_CRU_ESCR1		0x000003b9
#define MSR_P4_CRU_ESCR2		0x000003cc
#define MSR_P4_CRU_ESCR3		0x000003cd
#define MSR_P4_CRU_ESCR4		0x000003e0
#define MSR_P4_CRU_ESCR5		0x000003e1
#define MSR_P4_DAC_ESCR0		0x000003a8
#define MSR_P4_DAC_ESCR1		0x000003a9
#define MSR_P4_FIRM_ESCR0		0x000003a4
#define MSR_P4_FIRM_ESCR1		0x000003a5
#define MSR_P4_FLAME_ESCR0		0x000003a6
#define MSR_P4_FLAME_ESCR1		0x000003a7
#define MSR_P4_FSB_ESCR0		0x000003a2
#define MSR_P4_FSB_ESCR1		0x000003a3
#define MSR_P4_IQ_ESCR0			0x000003ba
#define MSR_P4_IQ_ESCR1			0x000003bb
#define MSR_P4_IS_ESCR0			0x000003b4
#define MSR_P4_IS_ESCR1			0x000003b5
#define MSR_P4_ITLB_ESCR0		0x000003b6
#define MSR_P4_ITLB_ESCR1		0x000003b7
#define MSR_P4_IX_ESCR0			0x000003c8
#define MSR_P4_IX_ESCR1			0x000003c9
#define MSR_P4_MOB_ESCR0		0x000003aa
#define MSR_P4_MOB_ESCR1		0x000003ab
#define MSR_P4_MS_ESCR0			0x000003c0
#define MSR_P4_MS_ESCR1			0x000003c1
#define MSR_P4_PMH_ESCR0		0x000003ac
#define MSR_P4_PMH_ESCR1		0x000003ad
#define MSR_P4_RAT_ESCR0		0x000003bc
#define MSR_P4_RAT_ESCR1		0x000003bd
#define MSR_P4_SAAT_ESCR0		0x000003ae
#define MSR_P4_SAAT_ESCR1		0x000003af
#define MSR_P4_SSU_ESCR0		0x000003be
#define MSR_P4_SSU_ESCR1		0x000003bf /* guess: not in manual */

#define MSR_P4_TBPU_ESCR0		0x000003c2
#define MSR_P4_TBPU_ESCR1		0x000003c3
#define MSR_P4_TC_ESCR0			0x000003c4
#define MSR_P4_TC_ESCR1			0x000003c5
#define MSR_P4_U2L_ESCR0		0x000003b0
#define MSR_P4_U2L_ESCR1		0x000003b1

#define MSR_P4_PEBS_MATRIX_VERT		0x000003f2

/* Intel Core-based CPU performance counters */
#define MSR_CORE_PERF_FIXED_CTR0	0x00000309
#define MSR_CORE_PERF_FIXED_CTR1	0x0000030a
#define MSR_CORE_PERF_FIXED_CTR2	0x0000030b
#define MSR_CORE_PERF_FIXED_CTR_CTRL	0x0000038d
#define MSR_CORE_PERF_GLOBAL_STATUS	0x0000038e
#define MSR_CORE_PERF_GLOBAL_CTRL	0x0000038f
#define MSR_CORE_PERF_GLOBAL_OVF_CTRL	0x00000390

/* Geode defined MSRs */
#define MSR_GEODE_BUSCONT_CONF0		0x00001900

/* Intel VT MSRs */
#define MSR_IA32_VMX_BASIC              0x00000480
#define MSR_IA32_VMX_PINBASED_CTLS      0x00000481
#define MSR_IA32_VMX_PROCBASED_CTLS     0x00000482
#define MSR_IA32_VMX_EXIT_CTLS          0x00000483
#define MSR_IA32_VMX_ENTRY_CTLS         0x00000484
#define MSR_IA32_VMX_MISC               0x00000485
#define MSR_IA32_VMX_CR0_FIXED0         0x00000486
#define MSR_IA32_VMX_CR0_FIXED1         0x00000487
#define MSR_IA32_VMX_CR4_FIXED0         0x00000488
#define MSR_IA32_VMX_CR4_FIXED1         0x00000489
#define MSR_IA32_VMX_VMCS_ENUM          0x0000048a
#define MSR_IA32_VMX_PROCBASED_CTLS2    0x0000048b
#define MSR_IA32_VMX_EPT_VPID_CAP       0x0000048c
#define MSR_IA32_VMX_TRUE_PIN		0x0000048d
#define MSR_IA32_VMX_TRUE_PROC		0x0000048e
#define MSR_IA32_VMX_TRUE_EXIT		0x0000048f
#define MSR_IA32_VMX_TRUE_ENTRY		0x00000490

#define MSR_IA32_TSCDEADLINE		0x000006e0

/* AMD-V MSRs */

#define MSR_VM_CR                       0xc0010114
#define MSR_VM_IGNNE                    0xc0010115
#define MSR_VM_HSAVE_PA                 0xc0010117

#endif /* _ASM_X86_MSR_INDEX_H */
                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/lib/x86/processor.h                                                 0000644 0000000 0000000 00000021104 00000000000 017321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef LIBCFLAT_PROCESSOR_H
#define LIBCFLAT_PROCESSOR_H

#include "libcflat.h"
#include "msr.h"
#include <stdint.h>

#ifdef __x86_64__
#  define R "r"
#  define W "q"
#  define S "8"
#else
#  define R "e"
#  define W "l"
#  define S "4"
#endif

#define X86_CR0_PE     0x00000001
#define X86_CR0_MP     0x00000002
#define X86_CR0_TS     0x00000008
#define X86_CR0_WP     0x00010000
#define X86_CR0_AM     0x00040000
#define X86_CR0_PG     0x80000000
#define X86_CR4_TSD    0x00000004
#define X86_CR4_DE     0x00000008
#define X86_CR4_PSE    0x00000010
#define X86_CR4_PAE    0x00000020
#define X86_CR4_VMXE   0x00002000
#define X86_CR4_PCIDE  0x00020000
#define X86_CR4_SMAP   0x00200000
#define X86_CR4_PKE    0x00400000

#define X86_EFLAGS_CF    0x00000001
#define X86_EFLAGS_FIXED 0x00000002
#define X86_EFLAGS_PF    0x00000004
#define X86_EFLAGS_AF    0x00000010
#define X86_EFLAGS_ZF    0x00000040
#define X86_EFLAGS_SF    0x00000080
#define X86_EFLAGS_TF    0x00000100
#define X86_EFLAGS_IF    0x00000200
#define X86_EFLAGS_DF    0x00000400
#define X86_EFLAGS_OF    0x00000800
#define X86_EFLAGS_NT    0x00004000
#define X86_EFLAGS_AC    0x00040000

#define X86_IA32_EFER          0xc0000080
#define X86_EFER_LMA           (1UL << 8)

struct far_pointer32 {
	u32 offset;
	u16 selector;
} __attribute__((packed));

struct descriptor_table_ptr {
    u16 limit;
    ulong base;
} __attribute__((packed));

static inline void barrier(void)
{
    asm volatile ("" : : : "memory");
}

static inline void clac(void)
{
    asm volatile (".byte 0x0f, 0x01, 0xca" : : : "memory");
}

static inline void stac(void)
{
    asm volatile (".byte 0x0f, 0x01, 0xcb" : : : "memory");
}

static inline u16 read_cs(void)
{
    unsigned val;

    asm volatile ("mov %%cs, %0" : "=mr"(val));
    return val;
}

static inline u16 read_ds(void)
{
    unsigned val;

    asm volatile ("mov %%ds, %0" : "=mr"(val));
    return val;
}

static inline u16 read_es(void)
{
    unsigned val;

    asm volatile ("mov %%es, %0" : "=mr"(val));
    return val;
}

static inline u16 read_ss(void)
{
    unsigned val;

    asm volatile ("mov %%ss, %0" : "=mr"(val));
    return val;
}

static inline u16 read_fs(void)
{
    unsigned val;

    asm volatile ("mov %%fs, %0" : "=mr"(val));
    return val;
}

static inline u16 read_gs(void)
{
    unsigned val;

    asm volatile ("mov %%gs, %0" : "=mr"(val));
    return val;
}

static inline unsigned long read_rflags(void)
{
	unsigned long f;
	asm volatile ("pushf; pop %0\n\t" : "=rm"(f));
	return f;
}

static inline void write_ds(unsigned val)
{
    asm volatile ("mov %0, %%ds" : : "rm"(val) : "memory");
}

static inline void write_es(unsigned val)
{
    asm volatile ("mov %0, %%es" : : "rm"(val) : "memory");
}

static inline void write_ss(unsigned val)
{
    asm volatile ("mov %0, %%ss" : : "rm"(val) : "memory");
}

static inline void write_fs(unsigned val)
{
    asm volatile ("mov %0, %%fs" : : "rm"(val) : "memory");
}

static inline void write_gs(unsigned val)
{
    asm volatile ("mov %0, %%gs" : : "rm"(val) : "memory");
}

static inline void write_rflags(unsigned long f)
{
    asm volatile ("push %0; popf\n\t" : : "rm"(f));
}

static inline u64 rdmsr(u32 index)
{
    u32 a, d;
    asm volatile ("rdmsr" : "=a"(a), "=d"(d) : "c"(index) : "memory");
    return a | ((u64)d << 32);
}

static inline void wrmsr(u32 index, u64 val)
{
    u32 a = val, d = val >> 32;
    asm volatile ("wrmsr" : : "a"(a), "d"(d), "c"(index) : "memory");
}

static inline uint64_t rdpmc(uint32_t index)
{
    uint32_t a, d;
    asm volatile ("rdpmc" : "=a"(a), "=d"(d) : "c"(index));
    return a | ((uint64_t)d << 32);
}

static inline void write_cr0(ulong val)
{
    asm volatile ("mov %0, %%cr0" : : "r"(val) : "memory");
}

static inline ulong read_cr0(void)
{
    ulong val;
    asm volatile ("mov %%cr0, %0" : "=r"(val) : : "memory");
    return val;
}

static inline void write_cr2(ulong val)
{
    asm volatile ("mov %0, %%cr2" : : "r"(val) : "memory");
}

static inline ulong read_cr2(void)
{
    ulong val;
    asm volatile ("mov %%cr2, %0" : "=r"(val) : : "memory");
    return val;
}

static inline void write_cr3(ulong val)
{
    asm volatile ("mov %0, %%cr3" : : "r"(val) : "memory");
}

static inline ulong read_cr3(void)
{
    ulong val;
    asm volatile ("mov %%cr3, %0" : "=r"(val) : : "memory");
    return val;
}

static inline void write_cr4(ulong val)
{
    asm volatile ("mov %0, %%cr4" : : "r"(val) : "memory");
}

static inline ulong read_cr4(void)
{
    ulong val;
    asm volatile ("mov %%cr4, %0" : "=r"(val) : : "memory");
    return val;
}

static inline void write_cr8(ulong val)
{
    asm volatile ("mov %0, %%cr8" : : "r"(val) : "memory");
}

static inline ulong read_cr8(void)
{
    ulong val;
    asm volatile ("mov %%cr8, %0" : "=r"(val) : : "memory");
    return val;
}

static inline void lgdt(const struct descriptor_table_ptr *ptr)
{
    asm volatile ("lgdt %0" : : "m"(*ptr));
}

static inline void sgdt(struct descriptor_table_ptr *ptr)
{
    asm volatile ("sgdt %0" : "=m"(*ptr));
}

static inline void lidt(const struct descriptor_table_ptr *ptr)
{
    asm volatile ("lidt %0" : : "m"(*ptr));
}

static inline void sidt(struct descriptor_table_ptr *ptr)
{
    asm volatile ("sidt %0" : "=m"(*ptr));
}

static inline void lldt(unsigned val)
{
    asm volatile ("lldt %0" : : "rm"(val));
}

static inline u16 sldt(void)
{
    u16 val;
    asm volatile ("sldt %0" : "=rm"(val));
    return val;
}

static inline void ltr(u16 val)
{
    asm volatile ("ltr %0" : : "rm"(val));
}

static inline u16 str(void)
{
    u16 val;
    asm volatile ("str %0" : "=rm"(val));
    return val;
}

static inline void write_dr6(ulong val)
{
    asm volatile ("mov %0, %%dr6" : : "r"(val) : "memory");
}

static inline ulong read_dr6(void)
{
    ulong val;
    asm volatile ("mov %%dr6, %0" : "=r"(val));
    return val;
}

static inline void write_dr7(ulong val)
{
    asm volatile ("mov %0, %%dr7" : : "r"(val) : "memory");
}

static inline ulong read_dr7(void)
{
    ulong val;
    asm volatile ("mov %%dr7, %0" : "=r"(val));
    return val;
}

struct cpuid { u32 a, b, c, d; };

static inline struct cpuid raw_cpuid(u32 function, u32 index)
{
    struct cpuid r;
    asm volatile ("cpuid"
                  : "=a"(r.a), "=b"(r.b), "=c"(r.c), "=d"(r.d)
                  : "0"(function), "2"(index));
    return r;
}

static inline struct cpuid cpuid_indexed(u32 function, u32 index)
{
    u32 level = raw_cpuid(function & 0xf0000000, 0).a;
    if (level < function)
        return (struct cpuid) { 0, 0, 0, 0 };
    return raw_cpuid(function, index);
}

static inline struct cpuid cpuid(u32 function)
{
    return cpuid_indexed(function, 0);
}

static inline u8 cpuid_maxphyaddr(void)
{
    if (raw_cpuid(0x80000000, 0).a < 0x80000008)
        return 36;
    return raw_cpuid(0x80000008, 0).a & 0xff;
}


static inline void pause(void)
{
    asm volatile ("pause");
}

static inline void cli(void)
{
    asm volatile ("cli");
}

static inline void sti(void)
{
    asm volatile ("sti");
}

static inline unsigned long long rdtsc()
{
	long long r;

#ifdef __x86_64__
	unsigned a, d;

	asm volatile ("rdtsc" : "=a"(a), "=d"(d));
	r = a | ((long long)d << 32);
#else
	asm volatile ("rdtsc" : "=A"(r));
#endif
	return r;
}

static inline unsigned long long rdtscp(u32 *aux)
{
       long long r;

#ifdef __x86_64__
       unsigned a, d;

       asm volatile ("rdtscp" : "=a"(a), "=d"(d), "=c"(*aux));
       r = a | ((long long)d << 32);
#else
       asm volatile ("rdtscp" : "=A"(r), "=c"(*aux));
#endif
       return r;
}

static inline void wrtsc(u64 tsc)
{
	unsigned a = tsc, d = tsc >> 32;

	asm volatile("wrmsr" : : "a"(a), "d"(d), "c"(0x10));
}

static inline void irq_disable(void)
{
    asm volatile("cli");
}

/* Note that irq_enable() does not ensure an interrupt shadow due
 * to the vagaries of compiler optimizations.  If you need the
 * shadow, use a single asm with "sti" and the instruction after it.
 */
static inline void irq_enable(void)
{
    asm volatile("sti");
}

static inline void invlpg(volatile void *va)
{
	asm volatile("invlpg (%0)" ::"r" (va) : "memory");
}

static inline void safe_halt(void)
{
	asm volatile("sti; hlt");
}

static inline u32 read_pkru(void)
{
    unsigned int eax, edx;
    unsigned int ecx = 0;
    unsigned int pkru;

    asm volatile(".byte 0x0f,0x01,0xee\n\t"
                 : "=a" (eax), "=d" (edx)
                 : "c" (ecx));
    pkru = eax;
    return pkru;
}

static inline void write_pkru(u32 pkru)
{
    unsigned int eax = pkru;
    unsigned int ecx = 0;
    unsigned int edx = 0;

    asm volatile(".byte 0x0f,0x01,0xef\n\t"
        : : "a" (eax), "c" (ecx), "d" (edx));
}

static inline bool is_canonical(u64 addr)
{
	return (s64)(addr << 16) >> 16 == addr;
}

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/lib/x86/setjmp32.S                                                  0000644 0000000 0000000 00000001000 00000000000 016715  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       .globl setjmp
setjmp:
	mov (%esp), %ecx	// get return EIP
	mov 4(%esp), %eax	// get jmp_buf
	mov %ecx, (%eax)
	mov %esp, 4(%eax)
	mov %ebp, 8(%eax)
	mov %ebx, 12(%eax)
	mov %esi, 16(%eax)
	mov %edi, 20(%eax)
	xor %eax, %eax
	ret

.globl longjmp
longjmp:
	mov 8(%esp), %eax	// get return value
	mov 4(%esp), %ecx	// get jmp_buf
	mov 20(%ecx), %edi
	mov 16(%ecx), %esi
	mov 12(%ecx), %ebx
	mov 8(%ecx), %ebp
	mov 4(%ecx), %esp
	mov (%ecx), %ecx	// get saved EIP
	mov %ecx, (%esp)	// and store it on the stack
	ret
source/v64/tests/kvm-unit-tests/lib/x86/setjmp64.S                                                  0000644 0000000 0000000 00000000723 00000000000 016735  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       .globl setjmp
setjmp:
	mov (%rsp), %rsi
	mov %rsi, (%rdi)
	mov %rsp, 0x8(%rdi)
	mov %rbp, 0x10(%rdi)
	mov %rbx, 0x18(%rdi)
	mov %r12, 0x20(%rdi)
	mov %r13, 0x28(%rdi)
	mov %r14, 0x30(%rdi)
	mov %r15, 0x38(%rdi)
	xor %eax, %eax
	ret

.globl longjmp
longjmp:
	mov %esi, %eax
	mov 0x38(%rdi), %r15
	mov 0x30(%rdi), %r14
	mov 0x28(%rdi), %r13
	mov 0x20(%rdi), %r12
	mov 0x18(%rdi), %rbx
	mov 0x10(%rdi), %rbp
	mov 0x8(%rdi), %rsp
	mov (%rdi), %rsi
	mov %rsi, (%rsp)
	ret
                                             source/v64/tests/kvm-unit-tests/lib/x86/setup.c                                                     0000644 0000000 0000000 00000001761 00000000000 016444  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Initialize machine setup information
 *
 * Copyright (C) 2017, Red Hat Inc, Andrew Jones <drjones@redhat.com>
 *
 * This work is licensed under the terms of the GNU LGPL, version 2.
 */
#include "libcflat.h"

#define MBI_MODS_COUNT	20
#define MBI_MODS_ADDR	24
#define MB_MOD_START	 0
#define MB_MOD_END	 4

#define ENV_SIZE 16384

extern void setup_env(char *env, int size);

char *initrd;
u32 initrd_size;

static char env[ENV_SIZE];

void setup_get_initrd(u8 *bootinfo)
{
	u32 *mods_addr, *mod_start, *mod_end;

	if (*((u32 *)&bootinfo[MBI_MODS_COUNT]) != 1)
		return;

	mods_addr = (u32 *)&bootinfo[MBI_MODS_ADDR];
	mod_start = (u32 *)(ulong)(*mods_addr + MB_MOD_START);
	mod_end = (u32 *)(ulong)(*mods_addr + MB_MOD_END);

	initrd = (char *)(ulong)*mod_start;
	initrd_size = *mod_end - *mod_start;
}

void setup_environ(void)
{
	if (initrd) {
		/* environ is currently the only file in the initrd */
		u32 size = MIN(initrd_size, ENV_SIZE);
		memcpy(env, initrd, size);
		setup_env(env, size);
	}
}
               source/v64/tests/kvm-unit-tests/lib/x86/smp.c                                                       0000644 0000000 0000000 00000004540 00000000000 016101  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include <libcflat.h>
#include "processor.h"
#include "atomic.h"
#include "smp.h"
#include "apic.h"
#include "fwcfg.h"
#include "desc.h"

#define IPI_VECTOR 0x20

typedef void (*ipi_function_type)(void *data);

static struct spinlock ipi_lock;
static volatile ipi_function_type ipi_function;
static void *volatile ipi_data;
static volatile int ipi_done;
static volatile bool ipi_wait;
static int _cpu_count;
static atomic_t active_cpus;

static __attribute__((used)) void ipi()
{
    void (*function)(void *data) = ipi_function;
    void *data = ipi_data;
    bool wait = ipi_wait;

    if (!wait) {
	ipi_done = 1;
	apic_write(APIC_EOI, 0);
    }
    function(data);
    atomic_dec(&active_cpus);
    if (wait) {
	ipi_done = 1;
	apic_write(APIC_EOI, 0);
    }
}

asm (
     "ipi_entry: \n"
     "   call ipi \n"
#ifndef __x86_64__
     "   iret"
#else
     "   iretq"
#endif
     );

int cpu_count(void)
{
    return _cpu_count;
}

int smp_id(void)
{
    unsigned id;

    asm ("mov %%gs:0, %0" : "=r"(id));
    return id;
}

static void setup_smp_id(void *data)
{
    asm ("mov %0, %%gs:0" : : "r"(apic_id()) : "memory");
}

static void __on_cpu(int cpu, void (*function)(void *data), void *data,
                     int wait)
{
    spin_lock(&ipi_lock);
    if (cpu == smp_id())
	function(data);
    else {
	atomic_inc(&active_cpus);
	ipi_done = 0;
	ipi_function = function;
	ipi_data = data;
	ipi_wait = wait;
	apic_icr_write(APIC_INT_ASSERT | APIC_DEST_PHYSICAL | APIC_DM_FIXED
                       | IPI_VECTOR,
                       cpu);
	while (!ipi_done)
	    ;
    }
    spin_unlock(&ipi_lock);
}

void on_cpu(int cpu, void (*function)(void *data), void *data)
{
    __on_cpu(cpu, function, data, 1);
}

void on_cpu_async(int cpu, void (*function)(void *data), void *data)
{
    __on_cpu(cpu, function, data, 0);
}

void on_cpus(void (*function)(void *data), void *data)
{
    int cpu;

    for (cpu = cpu_count() - 1; cpu >= 0; --cpu)
        on_cpu_async(cpu, function, data);

    while (cpus_active() > 1)
        pause();
}

int cpus_active(void)
{
    return atomic_read(&active_cpus);
}

void smp_init(void)
{
    int i;
    void ipi_entry(void);

    _cpu_count = fwcfg_get_nb_cpus();

    setup_idt();
    set_idt_entry(IPI_VECTOR, ipi_entry, 0);

    setup_smp_id(0);
    for (i = 1; i < cpu_count(); ++i)
        on_cpu(i, setup_smp_id, 0);

    atomic_inc(&active_cpus);
}
                                                                                                                                                                source/v64/tests/kvm-unit-tests/lib/x86/smp.h                                                       0000644 0000000 0000000 00000000525 00000000000 016105  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __SMP_H
#define __SMP_H
#include <asm/spinlock.h>

void smp_init(void);

int cpu_count(void);
int smp_id(void);
int cpus_active(void);
void on_cpu(int cpu, void (*function)(void *data), void *data);
void on_cpu_async(int cpu, void (*function)(void *data), void *data);
void on_cpus(void (*function)(void *data), void *data);

#endif
                                                                                                                                                                           source/v64/tests/kvm-unit-tests/lib/x86/stack.c                                                     0000644 0000000 0000000 00000001213 00000000000 016401  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include <libcflat.h>
#include <stack.h>

int backtrace_frame(const void *frame, const void **return_addrs, int max_depth)
{
	static int walking;
	int depth = 0;
	const unsigned long *bp = (unsigned long *) frame;

	if (walking) {
		printf("RECURSIVE STACK WALK!!!\n");
		return 0;
	}
	walking = 1;

	for (depth = 0; bp && depth < max_depth; depth++) {
		return_addrs[depth] = (void *) bp[1];
		if (return_addrs[depth] == 0)
			break;
		bp = (unsigned long *) bp[0];
	}

	walking = 0;
	return depth;
}

int backtrace(const void **return_addrs, int max_depth)
{
	return backtrace_frame(__builtin_frame_address(0), return_addrs,
			       max_depth);
}
                                                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/lib/x86/vm.c                                                        0000644 0000000 0000000 00000017672 00000000000 015736  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "fwcfg.h"
#include "vm.h"
#include "libcflat.h"

static void *free = 0;
static void *vfree_top = 0;

static void free_memory(void *mem, unsigned long size)
{
	void *end;

	assert_msg((unsigned long) mem % PAGE_SIZE == 0,
		   "mem not page aligned: %p", mem);

	assert_msg(size % PAGE_SIZE == 0, "size not page aligned: %#lx", size);

	assert_msg(size == 0 || mem + size > mem,
		   "mem + size overflow: %p + %#lx", mem, size);

	if (size == 0) {
		free = NULL;
		return;
	}

	free = mem;
	end = mem + size;
	while (mem + PAGE_SIZE != end) {
		*(void **)mem = (mem + PAGE_SIZE);
		mem += PAGE_SIZE;
	}

	*(void **)mem = NULL;
}

void *alloc_page()
{
    void *p;

    if (!free)
	return 0;

    p = free;
    free = *(void **)free;

    return p;
}

/*
 * Allocates (1 << order) physically contiguous and naturally aligned pages.
 * Returns NULL if there's no memory left.
 */
void *alloc_pages(unsigned long order)
{
	/* Generic list traversal. */
	void *prev;
	void *curr = NULL;
	void *next = free;

	/* Looking for a run of length (1 << order). */
	unsigned long run = 0;
	const unsigned long n = 1ul << order;
	const unsigned long align_mask = (n << PAGE_SHIFT) - 1;
	void *run_start = NULL;
	void *run_prev = NULL;
	unsigned long run_next_pa = 0;
	unsigned long pa;

	assert(order < sizeof(unsigned long) * 8);

	for (;;) {
		prev = curr;
		curr = next;
		next = curr ? *((void **) curr) : NULL;

		if (!curr)
			return 0;

		pa = virt_to_phys(curr);

		if (run == 0) {
			if (!(pa & align_mask)) {
				run_start = curr;
				run_prev = prev;
				run_next_pa = pa + PAGE_SIZE;
				run = 1;
			}
		} else if (pa == run_next_pa) {
			run_next_pa += PAGE_SIZE;
			run += 1;
		} else {
			run = 0;
		}

		if (run == n) {
			if (run_prev)
				*((void **) run_prev) = next;
			else
				free = next;
			return run_start;
		}
	}
}


void free_page(void *page)
{
    *(void **)page = free;
    free = page;
}

extern char edata;
static unsigned long end_of_memory;

unsigned long *install_pte(unsigned long *cr3,
			   int pte_level,
			   void *virt,
			   unsigned long pte,
			   unsigned long *pt_page)
{
    int level;
    unsigned long *pt = cr3;
    unsigned offset;

    for (level = PAGE_LEVEL; level > pte_level; --level) {
	offset = PGDIR_OFFSET((unsigned long)virt, level);
	if (!(pt[offset] & PT_PRESENT_MASK)) {
	    unsigned long *new_pt = pt_page;
            if (!new_pt)
                new_pt = alloc_page();
            else
                pt_page = 0;
	    memset(new_pt, 0, PAGE_SIZE);
	    pt[offset] = virt_to_phys(new_pt) | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
	}
	pt = phys_to_virt(pt[offset] & PT_ADDR_MASK);
    }
    offset = PGDIR_OFFSET((unsigned long)virt, level);
    pt[offset] = pte;
    return &pt[offset];
}

/*
 * Finds last PTE in the mapping of @virt that's at or above @lowest_level. The
 * returned PTE isn't necessarily present, but its parent is.
 */
struct pte_search find_pte_level(unsigned long *cr3, void *virt,
				 int lowest_level)
{
	unsigned long *pt = cr3, pte;
	unsigned offset;
	unsigned long shift;
	struct pte_search r;

	assert(lowest_level >= 1 && lowest_level <= PAGE_LEVEL);

	for (r.level = PAGE_LEVEL;; --r.level) {
		shift = (r.level - 1) * PGDIR_WIDTH + 12;
		offset = ((unsigned long)virt >> shift) & PGDIR_MASK;
		r.pte = &pt[offset];
		pte = *r.pte;

		if (!(pte & PT_PRESENT_MASK))
			return r;

		if ((r.level == 2 || r.level == 3) && (pte & PT_PAGE_SIZE_MASK))
			return r;

		if (r.level == lowest_level)
			return r;

		pt = phys_to_virt(pte & 0xffffffffff000ull);
	}
}

/*
 * Returns the leaf PTE in the mapping of @virt (i.e., 4K PTE or a present huge
 * PTE). Returns NULL if no leaf PTE exists.
 */
unsigned long *get_pte(unsigned long *cr3, void *virt)
{
	struct pte_search search;

	search = find_pte_level(cr3, virt, 1);
	return found_leaf_pte(search) ? search.pte : NULL;
}

/*
 * Returns the PTE in the mapping of @virt at the given level @pte_level.
 * Returns NULL if the PT at @pte_level isn't present (i.e., the mapping at
 * @pte_level - 1 isn't present).
 */
unsigned long *get_pte_level(unsigned long *cr3, void *virt, int pte_level)
{
	struct pte_search search;

	search = find_pte_level(cr3, virt, pte_level);
	return search.level == pte_level ? search.pte : NULL;
}

unsigned long *install_large_page(unsigned long *cr3,
				  unsigned long phys,
				  void *virt)
{
    return install_pte(cr3, 2, virt,
		       phys | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK | PT_PAGE_SIZE_MASK, 0);
}

unsigned long *install_page(unsigned long *cr3,
			    unsigned long phys,
			    void *virt)
{
    return install_pte(cr3, 1, virt, phys | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK, 0);
}

void install_pages(unsigned long *cr3, unsigned long phys, unsigned long len,
		   void *virt)
{
	unsigned long max = (u64)len + (u64)phys;
	assert(phys % PAGE_SIZE == 0);
	assert((unsigned long) virt % PAGE_SIZE == 0);
	assert(len % PAGE_SIZE == 0);

	while (phys + PAGE_SIZE <= max) {
		install_page(cr3, phys, virt);
		phys += PAGE_SIZE;
		virt = (char *) virt + PAGE_SIZE;
	}
}

bool any_present_pages(unsigned long *cr3, void *virt, unsigned long len)
{
	unsigned long max = (unsigned long) virt + len;
	unsigned long curr;

	for (curr = (unsigned long) virt; curr < max; curr += PAGE_SIZE) {
		unsigned long *ptep = get_pte(cr3, (void *) curr);
		if (ptep && (*ptep & PT_PRESENT_MASK))
			return true;
	}
	return false;
}

static void setup_mmu_range(unsigned long *cr3, unsigned long start,
			    unsigned long len)
{
	u64 max = (u64)len + (u64)start;
	u64 phys = start;

	while (phys + LARGE_PAGE_SIZE <= max) {
		install_large_page(cr3, phys, (void *)(ulong)phys);
		phys += LARGE_PAGE_SIZE;
	}
	install_pages(cr3, phys, max - phys, (void *)(ulong)phys);
}

static void setup_mmu(unsigned long len)
{
    unsigned long *cr3 = alloc_page();

    memset(cr3, 0, PAGE_SIZE);

#ifdef __x86_64__
    if (len < (1ul << 32))
        len = (1ul << 32);  /* map mmio 1:1 */

    setup_mmu_range(cr3, 0, len);
#else
    if (len > (1ul << 31))
	    len = (1ul << 31);

    /* 0 - 2G memory, 2G-3G valloc area, 3G-4G mmio */
    setup_mmu_range(cr3, 0, len);
    setup_mmu_range(cr3, 3ul << 30, (1ul << 30));
    vfree_top = (void*)(3ul << 30);
#endif

    write_cr3(virt_to_phys(cr3));
#ifndef __x86_64__
    write_cr4(X86_CR4_PSE);
#endif
    write_cr0(X86_CR0_PG |X86_CR0_PE | X86_CR0_WP);

    printf("paging enabled\n");
    printf("cr0 = %lx\n", read_cr0());
    printf("cr3 = %lx\n", read_cr3());
    printf("cr4 = %lx\n", read_cr4());
}

void setup_vm()
{
    assert(!end_of_memory);
    end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
    free_memory(&edata, end_of_memory - (unsigned long)&edata);
    setup_mmu(end_of_memory);
}

void *vmalloc(unsigned long size)
{
    void *mem, *p;
    unsigned pages;

    size += sizeof(unsigned long);

    size = (size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
    vfree_top -= size;
    mem = p = vfree_top;
    pages = size / PAGE_SIZE;
    while (pages--) {
	install_page(phys_to_virt(read_cr3()), virt_to_phys(alloc_page()), p);
	p += PAGE_SIZE;
    }
    *(unsigned long *)mem = size;
    mem += sizeof(unsigned long);
    return mem;
}

uint64_t virt_to_phys_cr3(void *mem)
{
    return (*get_pte(phys_to_virt(read_cr3()), mem) & PT_ADDR_MASK) + ((ulong)mem & (PAGE_SIZE - 1));
}

void vfree(void *mem)
{
    unsigned long size = ((unsigned long *)mem)[-1];

    while (size) {
	free_page(phys_to_virt(*get_pte(phys_to_virt(read_cr3()), mem) & PT_ADDR_MASK));
	mem += PAGE_SIZE;
	size -= PAGE_SIZE;
    }
}

void *vmap(unsigned long long phys, unsigned long size)
{
    void *mem, *p;
    unsigned pages;

    size = (size + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
    vfree_top -= size;
    phys &= ~(unsigned long long)(PAGE_SIZE - 1);

    mem = p = vfree_top;
    pages = size / PAGE_SIZE;
    while (pages--) {
	install_page(phys_to_virt(read_cr3()), phys, p);
	phys += PAGE_SIZE;
	p += PAGE_SIZE;
    }
    return mem;
}

void *alloc_vpages(ulong nr)
{
	vfree_top -= PAGE_SIZE * nr;
	return vfree_top;
}

void *alloc_vpage(void)
{
    return alloc_vpages(1);
}
                                                                      source/v64/tests/kvm-unit-tests/lib/x86/vm.h                                                        0000644 0000000 0000000 00000003243 00000000000 015730  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef VM_H
#define VM_H

#include "processor.h"
#include "asm/page.h"
#include "asm/io.h"

void setup_vm();

void *vmalloc(unsigned long size);
void vfree(void *mem);
void *vmap(unsigned long long phys, unsigned long size);
void *alloc_vpage(void);
void *alloc_vpages(ulong nr);
uint64_t virt_to_phys_cr3(void *mem);

struct pte_search {
	int level;
	unsigned long *pte;
};

static inline bool found_huge_pte(struct pte_search search)
{
	return (search.level == 2 || search.level == 3) &&
	       (*search.pte & PT_PRESENT_MASK) &&
	       (*search.pte & PT_PAGE_SIZE_MASK);
}

static inline bool found_leaf_pte(struct pte_search search)
{
	return search.level == 1 || found_huge_pte(search);
}

struct pte_search find_pte_level(unsigned long *cr3, void *virt,
				 int lowest_level);
unsigned long *get_pte(unsigned long *cr3, void *virt);
unsigned long *get_pte_level(unsigned long *cr3, void *virt, int pte_level);
unsigned long *install_pte(unsigned long *cr3,
                           int pte_level,
                           void *virt,
                           unsigned long pte,
                           unsigned long *pt_page);

void *alloc_page();
void *alloc_pages(unsigned long order);
void free_page(void *page);

unsigned long *install_large_page(unsigned long *cr3,unsigned long phys,
                                  void *virt);
unsigned long *install_page(unsigned long *cr3, unsigned long phys, void *virt);
void install_pages(unsigned long *cr3, unsigned long phys, unsigned long len,
		   void *virt);
bool any_present_pages(unsigned long *cr3, void *virt, unsigned long len);

static inline void *current_page_table(void)
{
	return phys_to_virt(read_cr3());
}
#endif
                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/run.mjs                                                             0000755 0000000 0000000 00000022700 00000000000 015263  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Run one kvm-unit-tests binary (a multiboot .flat file) in v86 and classify
// the result.
//
// usage: run.mjs [options] TEST.flat
//   --acpi            enable ACPI (in v86 this also enables the local APIC and IOAPIC)
//   --cores N         cores of the processor (N > 1 implies --acpi)
//   --memory MIB      guest memory (default 64)
//   --timeout SEC     give up after SEC seconds (default 60)
//   --expect-pass N   require at least N "PASS:" reports: a test that exits 0
//                     without reaching its checks does not count as passed
//   --cpu-features L  CPU features of docs/simd-xsave-plan.md, comma-separated
//   --cpu-type T      x86 (default) or x86_64, for the x86_64 builds
//   --quiet           don't echo the serial output
//   --arm64           an arm64 build (build.sh arm64-*): booted as an arm64
//                     Image on the virt board, the status read from upstream's
//                     "EXIT: STATUS=" line on the PL011, PSCI SYSTEM_OFF ends it
//   --append ARGS     the test's arguments (unittests.cfg test_args), arm64
//   --qemu            run arm64 tests on the fixed QEMU reference
//                     (docs/arm64-virt-android16-plan.md P0.6); v86 runs need
//                     the ARM core
//   --arm32           a 32-bit arm build (build.sh arm): booted as arm64's are,
//                     on cpu_type "arm32" or QEMU's cortex-a15 (docs/aarch32-plan.md R5.1)
//   --granules-all    (v86, arm64) the 16 and 64 KiB granules set explicitly
//                     (P3.4; profile v1.1, the default, has them), for the 16k and 64k builds
// Environment: TEST_RELEASE_BUILD=1 uses build/libv86.mjs, DISABLE_JIT=1 the interpreter,
// JIT_SWITCHES the JIT switches (tests/lib/jit_switches.mjs).
//
// Exit status: 0 passed, 1 failed, 2 crashed (the emulator threw), 3 timed out,
// 4 test file missing. The last line is machine readable:
//   RESULT <passed|failed|crashed|timeout|missing> <test> code=<exit code> passes=<n> failures=<n> skips=<n>

import fs from "node:fs";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const options = { acpi: false, cores: 1, memory: 64, timeout: 60, expect_pass: 0, quiet: false, cpu_features: undefined, cpu_type: undefined,
    arm64: false, arm32: false, append: "", qemu: false, granules_all: false };
let test_file;
for(let i = 2; i < process.argv.length; i++)
{
    const arg = process.argv[i];
    if(arg === "--acpi") options.acpi = true;
    else if(arg === "--quiet") options.quiet = true;
    else if(arg === "--memory") options.memory = +process.argv[++i];
    else if(arg === "--cores") { options.cores = +process.argv[++i]; options.acpi ||= options.cores > 1; }
    else if(arg === "--timeout") options.timeout = +process.argv[++i];
    else if(arg === "--expect-pass") options.expect_pass = +process.argv[++i];
    else if(arg === "--cpu-features") options.cpu_features = process.argv[++i].split(",");
    else if(arg === "--cpu-type") options.cpu_type = process.argv[++i];
    else if(arg === "--arm64") options.arm64 = true;
    else if(arg === "--arm32") options.arm64 = options.arm32 = true;
    else if(arg === "--granules-all") options.granules_all = true;
    else if(arg === "--append") options.append = process.argv[++i];
    else if(arg === "--qemu") options.qemu = true;
    else if(arg.startsWith("--")) { console.error("unknown option " + arg); process.exit(4); }
    else test_file = arg;
}

const STATUS = { passed: 0, failed: 1, crashed: 2, timeout: 3, missing: 4 };
const name = test_file ? path.basename(test_file) : "(none)";
let serial = "";

function finish(status, code, detail)
{
    const count = prefix => (serial.match(new RegExp("^" + prefix + ":", "gm")) || []).length;
    const passes = count("PASS");
    const failures = count("FAIL");
    const skips = count("SKIP");

    if(status === "passed" && (failures > 0 || passes < options.expect_pass))
    {
        detail = failures > 0 ? failures + " FAIL report(s) despite exit code 0" :
            "only " + passes + " PASS report(s), expected at least " + options.expect_pass;
        status = "failed";
    }
    if(detail) console.log("\n" + detail);
    console.log(`\nRESULT ${status} ${name} code=${code} passes=${passes} failures=${failures} skips=${skips}`);
    process.exit(STATUS[status]);
}

if(!test_file || !fs.existsSync(test_file))
{
    finish("missing", -1, "test file not found: " + test_file);
}

process.on("uncaughtException", e => finish("crashed", -1, "emulator exception: " + (e && e.stack || e)));
process.on("unhandledRejection", e => finish("crashed", -1, "emulator exception: " + (e && e.stack || e)));

if(options.arm64 && !options.qemu)
{
    // the ARM core: the .flat file is the kernel, the arguments the device tree's bootargs
    const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    const { root, jit_options } = await import("../a64/guest_runner.mjs");
    const emulator = new V86({
        cpu_type: options.arm32 ? "arm32" : "arm64", graphics_adapter: "none", cpu_cores: options.cores, memory_size: options.memory << 20,
        wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm", kernel: { url: test_file }, cmdline: options.append,
        autostart: !options.granules_all, log_level: 0, ...jit_options(),
    });
    if(options.granules_all)
    {
        // (the 16 and 64 KiB granules, before the guest runs: v1.1's, the default profile's)
        emulator.add_listener("emulator-loaded", () => {
            emulator.v86.cpu.wm.exports["a64_set_granules"](7);
            emulator.run();
        });
    }
    emulator.add_listener("serial0-output-byte", byte => {
        const c = String.fromCharCode(byte);
        serial += c;
        if(!options.quiet) process.stdout.write(c);
        const status = serial.match(/^EXIT: STATUS=(\d+)/m);
        if(status && serial.endsWith("\n"))
        {
            const code = +status[1] >> 1;
            finish(code === 0 ? "passed" : "failed", code);
        }
    });
    setTimeout(() => finish("timeout", -1, "no exit after " + options.timeout + " s; " +
        JSON.stringify(emulator.v86?.cpu?.get_diagnostics?.())), options.timeout * 1000);
    setInterval(() => {
        if(emulator.v86?.cpu?.powered_off?.())
        {
            const status = serial.match(/^EXIT: STATUS=(\d+)/m);
            if(!status) finish("crashed", -1, "the guest turned the machine off without EXIT: STATUS=");
            const code = +status[1] >> 1;
            finish(code === 0 ? "passed" : "failed", code);
        }
    }, 50);
    await new Promise(() => {});
}

if(options.arm64)
{
    const { spawn } = await import("node:child_process");
    const { QEMU_MACHINE, QEMU_CPU, qemu_binary, smp } = await import("../a64/guest_runner.mjs");
    const { QEMU_MACHINE32, QEMU_CPU32 } = options.arm32 ? await import("../a32/runner.mjs") : {};
    const child = spawn(qemu_binary(), ["-nodefaults", "-machine", options.arm32 ? QEMU_MACHINE32 : QEMU_MACHINE,
        "-cpu", options.arm32 ? QEMU_CPU32 : QEMU_CPU, "-m", (options.memory === 64 ? 128 : options.memory) + "M",
        "-smp", smp(options.cores), "-display", "none", "-serial", "stdio", "-kernel", test_file, "-append", options.append], { stdio: ["ignore", "pipe", "pipe"] });
    process.on("exit", () => child.kill("SIGKILL"));
    let error = "";
    child.stderr.on("data", data => error += data);
    child.stdout.on("data", data => {
        serial += data.toString("latin1");
        if(!options.quiet) process.stdout.write(data);
    });
    setTimeout(() => finish("timeout", -1, "no exit after " + options.timeout + " s"), options.timeout * 1000);
    // (exit(code) prints EXIT: STATUS=<code << 1 | 1>, then PSCI SYSTEM_OFF ends QEMU)
    child.on("exit", () => {
        const status = serial.match(/^EXIT: STATUS=(\d+)/m);
        if(!status) finish("crashed", -1, "QEMU exited without EXIT: STATUS=: " + error);
        const code = +status[1] >> 1;
        finish(code === 0 ? "passed" : "failed", code);
    });
    // (finish() ends the process)
    await new Promise(() => {});
}

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { with_jit_switches } = await import("../lib/jit_switches.mjs");
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const emulator = new V86(with_jit_switches({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    multiboot: { url: test_file },
    autostart: true,
    memory_size: options.memory * 1024 * 1024,
    acpi: options.acpi,
    cpu_cores: options.cores,
    cpu_features: options.cpu_features,
    cpu_features_unreleased: true,
    cpu_type: options.cpu_type,
    disable_jit: +process.env.DISABLE_JIT,
    log_level: 0,
}));

setTimeout(async () => {
    const diagnostics = await emulator.get_diagnostics();
    finish("timeout", -1, "no exit after " + options.timeout + " s\n" + JSON.stringify(diagnostics, null, 1));
}, options.timeout * 1000);

emulator.bus.register("emulator-started", function()
{
    // kvm-unit-tests' exit(): the status goes to the isa-debug-exit port
    const exit = value => finish(value === 0 ? "passed" : "failed", value);
    emulator.v86.cpu.io.register_write(0xF4, {}, exit, exit, exit);
});

emulator.add_listener("serial0-output-byte", function(byte)
{
    const chr = String.fromCharCode(byte);
    serial += chr;
    if(!options.quiet) process.stdout.write(chr);
});
                                                                source/v64/tests/kvm-unit-tests/v86/ar.py                                                           0000644 0000000 0000000 00000007500 00000000000 015341  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env python3
"""Minimal GNU-format `ar rcs` for ELF objects, used when building
kvm-unit-tests on macOS: the system ar writes BSD archives whose symbol index
ld.lld cannot use for ELF objects.

usage: ar.py rcs ARCHIVE OBJECT...
"""

import struct
import sys


def defined_globals(data):
    """Names of the global and weak symbols an ELF32/ELF64 object defines"""
    if data[:4] != b"\x7fELF":
        return []
    is64 = data[4] == 2
    little = data[5] == 1
    e = "<" if little else ">"
    if is64:
        shoff, = struct.unpack_from(e + "Q", data, 0x28)
        shentsize, shnum = struct.unpack_from(e + "HH", data, 0x3A)
    else:
        shoff, = struct.unpack_from(e + "I", data, 0x20)
        shentsize, shnum = struct.unpack_from(e + "HH", data, 0x2E)

    def section(i):
        base = shoff + i * shentsize
        if is64:
            _name, sh_type, _flags, _addr, offset, size, link, _info, _align, entsize = \
                struct.unpack_from(e + "IIQQQQIIQQ", data, base)
        else:
            _name, sh_type, _flags, _addr, offset, size, link, _info, _align, entsize = \
                struct.unpack_from(e + "IIIIIIIIII", data, base)
        return sh_type, offset, size, link, entsize

    names = []
    for i in range(shnum):
        sh_type, offset, size, link, entsize = section(i)
        if sh_type != 2:  # SHT_SYMTAB
            continue
        _, str_offset, _, _, _ = section(link)
        for sym in range(offset + entsize, offset + size, entsize):  # skip the null symbol
            if is64:
                st_name, st_info, _other, st_shndx = struct.unpack_from(e + "IBBH", data, sym)
            else:
                st_name, = struct.unpack_from(e + "I", data, sym)
                st_info, _other, st_shndx = struct.unpack_from(e + "BBH", data, sym + 12)
            binding = st_info >> 4
            if binding in (1, 2) and st_shndx != 0:  # GLOBAL/WEAK, defined
                end = data.index(b"\0", str_offset + st_name)
                names.append(data[str_offset + st_name:end])
    return names


def header(name, size):
    return b"%-16s%-12d%-6d%-6d%-8o%-10d`\n" % (name, 0, 0, 0, 0o644, size)


def main():
    if len(sys.argv) < 3 or "r" not in sys.argv[1]:
        sys.exit(__doc__)
    archive, paths = sys.argv[2], sys.argv[3:]
    members = [(path.rsplit("/", 1)[-1].encode(), open(path, "rb").read()) for path in paths]

    # long name table for names that do not fit in 16 bytes
    long_names = b""
    member_names = []
    for name, _ in members:
        if len(name) < 16:
            member_names.append(name + b"/")
        else:
            member_names.append(b"/%d" % len(long_names))
            long_names += name + b"/\n"

    symbols = [[sym for sym in defined_globals(data)] for _, data in members]
    symbol_count = sum(len(s) for s in symbols)
    symbol_names = b"".join(sym + b"\0" for s in symbols for sym in s)
    index_size = 4 + 4 * symbol_count + len(symbol_names)

    # offsets of the member headers
    offset = 8 + 60 + index_size + (index_size & 1)
    if long_names:
        offset += 60 + len(long_names) + (len(long_names) & 1)
    member_offsets = []
    for _, data in members:
        member_offsets.append(offset)
        offset += 60 + len(data) + (len(data) & 1)

    out = [b"!<arch>\n", header(b"/", index_size), struct.pack(">I", symbol_count)]
    for member_offset, s in zip(member_offsets, symbols):
        out.append(struct.pack(">I", member_offset) * len(s))
    out.append(symbol_names + b"\n" * (index_size & 1))
    if long_names:
        out.append(header(b"//", len(long_names)) + long_names + b"\n" * (len(long_names) & 1))
    for name, (_, data) in zip(member_names, members):
        out.append(header(name, len(data)) + data + b"\n" * (len(data) & 1))

    with open(archive, "wb") as f:
        f.write(b"".join(out))


if __name__ == "__main__":
    main()
                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/v86/builtins.c                                                      0000644 0000000 0000000 00000002555 00000000000 016367  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * The 64-bit division helpers that 32-bit x86 code calls into libgcc (or
 * compiler-rt), for building kvm-unit-tests on macOS where neither exists for
 * i386-linux. Written without 64-bit division, so they cannot call themselves.
 */

typedef unsigned long long u64;
typedef long long s64;

u64 __udivmoddi4(u64 n, u64 d, u64 *rem)
{
    u64 q = 0, r = 0;
    int i;

    if (d == 0) {
        /* divide error, like the hardware */
        volatile unsigned zero = 0;
        return 1 / zero;
    }

    if ((n >> 32) == 0 && (d >> 32) == 0) {
        unsigned n32 = (unsigned)n, d32 = (unsigned)d;
        if (rem)
            *rem = n32 % d32;
        return n32 / d32;
    }

    for (i = 63; i >= 0; i--) {
        r = (r << 1) | ((n >> i) & 1);
        if (r >= d) {
            r -= d;
            q |= 1ULL << i;
        }
    }

    if (rem)
        *rem = r;
    return q;
}

u64 __udivdi3(u64 n, u64 d)
{
    return __udivmoddi4(n, d, 0);
}

u64 __umoddi3(u64 n, u64 d)
{
    u64 r;
    __udivmoddi4(n, d, &r);
    return r;
}

s64 __divdi3(s64 n, s64 d)
{
    int negative = (n < 0) != (d < 0);
    u64 q = __udivmoddi4(n < 0 ? -(u64)n : (u64)n, d < 0 ? -(u64)d : (u64)d, 0);
    return negative ? -(s64)q : (s64)q;
}

s64 __moddi3(s64 n, s64 d)
{
    u64 r;
    __udivmoddi4(n < 0 ? -(u64)n : (u64)n, d < 0 ? -(u64)d : (u64)d, &r);
    return n < 0 ? -(s64)r : (s64)r;
}
                                                                                                                                                   source/v64/tests/kvm-unit-tests/x86/Makefile                                                        0000644 0000000 0000000 00000000057 00000000000 016027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       include $(SRCDIR)/$(TEST_DIR)/Makefile.$(ARCH)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/kvm-unit-tests/x86/Makefile.common                                                 0000644 0000000 0000000 00000005361 00000000000 017321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #This is a make file with common rules for both x86 & x86-64

all: directories test_cases

cflatobjs += lib/pci.o
cflatobjs += lib/pci-edu.o
cflatobjs += lib/x86/setup.o
cflatobjs += lib/x86/io.o
cflatobjs += lib/x86/smp.o
cflatobjs += lib/x86/vm.o
cflatobjs += lib/x86/fwcfg.o
cflatobjs += lib/x86/apic.o
cflatobjs += lib/x86/atomic.o
cflatobjs += lib/x86/desc.o
cflatobjs += lib/x86/isr.o
cflatobjs += lib/x86/acpi.o
cflatobjs += lib/x86/stack.o

OBJDIRS += lib/x86

$(libcflat): LDFLAGS += -nostdlib
$(libcflat): CFLAGS += -ffreestanding -I $(SRCDIR)/lib -I lib

COMMON_CFLAGS += -m$(bits)
COMMON_CFLAGS += -O1
COMMON_CFLAGS += -fno-stack-protector

# stack.o relies on frame pointers.
KEEP_FRAME_POINTER := y

libgcc := $(shell $(CC) -m$(bits) --print-libgcc-file-name)

# We want to keep intermediate file: %.elf and %.o 
.PRECIOUS: %.elf %.o

FLATLIBS = lib/libcflat.a $(libgcc)
%.elf: %.o $(FLATLIBS) $(SRCDIR)/x86/flat.lds $(cstart.o)
	$(CC) $(CFLAGS) -nostdlib -o $@ -Wl,-T,$(SRCDIR)/x86/flat.lds \
		$(filter %.o, $^) $(FLATLIBS)

%.flat: %.elf
	$(OBJCOPY) -O elf32-i386 $^ $@

tests-common = $(TEST_DIR)/vmexit.flat $(TEST_DIR)/tsc.flat \
               $(TEST_DIR)/smptest.flat  $(TEST_DIR)/port80.flat \
               $(TEST_DIR)/realmode.flat $(TEST_DIR)/msr.flat \
               $(TEST_DIR)/hypercall.flat $(TEST_DIR)/sieve.flat \
               $(TEST_DIR)/kvmclock_test.flat  $(TEST_DIR)/eventinj.flat \
               $(TEST_DIR)/s3.flat $(TEST_DIR)/pmu.flat $(TEST_DIR)/setjmp.flat \
               $(TEST_DIR)/tsc_adjust.flat $(TEST_DIR)/asyncpf.flat \
               $(TEST_DIR)/init.flat $(TEST_DIR)/smap.flat \
               $(TEST_DIR)/hyperv_synic.flat $(TEST_DIR)/hyperv_stimer.flat \
               $(TEST_DIR)/hyperv_connections.flat \
               $(TEST_DIR)/pae.flat \

ifdef API
tests-api = api/api-sample api/dirty-log api/dirty-log-perf

OBJDIRS += api
endif

test_cases: $(tests-common) $(tests) $(tests-api)

$(TEST_DIR)/%.o: CFLAGS += -std=gnu99 -ffreestanding -I $(SRCDIR)/lib -I $(SRCDIR)/lib/x86 -I lib

$(TEST_DIR)/realmode.elf: $(TEST_DIR)/realmode.o
	$(CC) -m32 -nostdlib -o $@ -Wl,-T,$(SRCDIR)/$(TEST_DIR)/realmode.lds $^

$(TEST_DIR)/realmode.o: bits = 32

$(TEST_DIR)/kvmclock_test.elf: $(TEST_DIR)/kvmclock.o

$(TEST_DIR)/hyperv_synic.elf: $(TEST_DIR)/hyperv.o

$(TEST_DIR)/hyperv_stimer.elf: $(TEST_DIR)/hyperv.o

$(TEST_DIR)/hyperv_connections.elf: $(TEST_DIR)/hyperv.o

arch_clean:
	$(RM) $(TEST_DIR)/*.o $(TEST_DIR)/*.flat $(TEST_DIR)/*.elf \
	$(TEST_DIR)/.*.d lib/x86/.*.d \
	$(tests-api) api/*.o api/*.a api/.*.d

api/%.o: CXXFLAGS += -m32 -std=gnu++11

api/%: LDLIBS += -lstdc++ -lpthread -lrt
api/%: LDFLAGS += -m32

api/libapi.a: api/kvmxx.o api/identity.o api/exception.o api/memmap.o
	$(AR) rcs $@ $^

$(tests-api) : % : %.o api/libapi.a
                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/x86/Makefile.i386                                                   0000644 0000000 0000000 00000001512 00000000000 016514  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       cstart.o = $(TEST_DIR)/cstart.o
bits = 32
ldarch = elf32-i386

cflatobjs += lib/x86/setjmp32.o

tests = $(TEST_DIR)/taskswitch.flat $(TEST_DIR)/taskswitch2.flat \
	$(TEST_DIR)/cmpxchg8b.flat


# added some tests from Makefile.x86_64
tests += $(TEST_DIR)/apic.flat \
	  $(TEST_DIR)/rmap_chain.flat \
	  $(TEST_DIR)/ioapic.flat $(TEST_DIR)/memory.flat


# These tests from Makefile.x86_64 don't compile. emulator.c would be nice to have
# $(TEST_DIR)/emulator.flat
# $(TEST_DIR)/access.flat
# $(TEST_DIR)/idt_test.flat
# $(TEST_DIR)/xsave.flat
# $(TEST_DIR)/pcid.flat
# $(TEST_DIR)/debug.flat
# $(TEST_DIR)/pku.flat
# $(TEST_DIR)/hyperv_clock.flat

#tests += $(TEST_DIR)/svm.flat
#tests += $(TEST_DIR)/vmx.flat
tests += $(TEST_DIR)/tscdeadline_latency.flat
#tests += $(TEST_DIR)/intel-iommu.flat


include $(SRCDIR)/$(TEST_DIR)/Makefile.common
                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/x86/Makefile.x86_64                                                 0000644 0000000 0000000 00000001465 00000000000 016770  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       cstart.o = $(TEST_DIR)/cstart64.o
bits = 64
ldarch = elf64-x86-64
COMMON_CFLAGS += -mno-red-zone

cflatobjs += lib/x86/setjmp64.o
cflatobjs += lib/x86/intel-iommu.o

tests = $(TEST_DIR)/access.flat $(TEST_DIR)/apic.flat \
	  $(TEST_DIR)/emulator.flat $(TEST_DIR)/idt_test.flat \
	  $(TEST_DIR)/xsave.flat $(TEST_DIR)/rmap_chain.flat \
	  $(TEST_DIR)/pcid.flat $(TEST_DIR)/debug.flat \
	  $(TEST_DIR)/ioapic.flat $(TEST_DIR)/memory.flat \
	  $(TEST_DIR)/pku.flat $(TEST_DIR)/hyperv_clock.flat
tests += $(TEST_DIR)/syscall.flat
tests += $(TEST_DIR)/svm.flat
tests += $(TEST_DIR)/vmx.flat
tests += $(TEST_DIR)/tscdeadline_latency.flat
tests += $(TEST_DIR)/intel-iommu.flat

include $(SRCDIR)/$(TEST_DIR)/Makefile.common

$(TEST_DIR)/hyperv_clock.elf: $(TEST_DIR)/hyperv_clock.o

$(TEST_DIR)/vmx.elf: $(TEST_DIR)/vmx_tests.o
                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/x86/README                                                          0000644 0000000 0000000 00000004371 00000000000 015252  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
Tests for the x86 architecture are run as kernel images for qemu that support
multiboot format. The tests use an infrastructure called from the bios code.
The infrastructure initialize the system/cpus, switches to long-mode, and
calls the 'main' function of the individual test. Tests use a qemu virtual
test device, named testdev, for services like printing, exiting, querying
memory size, etc. See file docs/testdev.txt for more details.

Examples of a test invocation:
 These invocations run the msr test case and outputs to stdio.

 Using qemu-kvm:

	qemu-kvm -device testdev,chardev=testlog \
		 -chardev file,id=testlog,path=msr.out \
		 -serial stdio -kernel ./x86/msr.flat

 Using qemu (supported since qemu 1.3):

	qemu-system-x86_64 -enable-kvm -device pc-testdev -serial stdio \
			   -device isa-debug-exit,iobase=0xf4,iosize=0x4 \
			   -kernel ./x86/msr.flat

Tests in this directory and what they do:
 access:	lots of page table related access (pte/pde) (read/write)
 apic:		enable x2apic, self ipi, ioapic intr, ioapic simultaneous
 emulator:	move to/from regs, cmps, push, pop, to/from cr8, smsw and lmsw
 hypercall:	intel and amd hypercall insn
 msr:		write to msr (only KERNEL_GS_BASE for now)
 port80:	lots of out to port 80
 realmode:	goes back to realmode, shld, push/pop, mov immediate, cmp
		immediate, add immediate, io, eflags instructions
		(clc, cli, etc.), jcc short, jcc near, call, long jmp, xchg
 sieve:		heavy memory access with no paging and with paging static and
		with paging vmalloc'ed
 smptest:	run smp_id() on every cpu and compares return value to number
 tsc:		write to tsc(0) and write to tsc(100000000000) and read it back
 vmexit:	long loops for each: cpuid, vmcall, mov_from_cr8, mov_to_cr8,
		inl_pmtimer, ipi, ipi+halt
 kvmclock_test:	test of wallclock, monotonic cycle and performance of kvmclock
 pcid:		basic functionality test of PCID/INVPCID feature

Legacy notes:
 The exit status of the binary is inconsistent; with qemu-system, after
 the unit-test is done, the exit status of qemu is 1, different from the
 'old style' qemu-kvm, whose exit status in successful completion is 0.
 The run script converts the qemu-system exit status to 0 (SUCCESS), and
 treats the legacy exit status of 0 as an error, converting it to an exit
 status of 1.
                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/x86/access.c                                                        0000644 0000000 0000000 00000060342 00000000000 015777  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "libcflat.h"
#include "desc.h"
#include "processor.h"
#include "asm/page.h"

#define smp_id() 0

#define true 1
#define false 0

static _Bool verbose = false;

typedef unsigned long pt_element_t;
static int cpuid_7_ebx;
static int cpuid_7_ecx;
static int invalid_mask;

#define PT_BASE_ADDR_MASK ((pt_element_t)((((pt_element_t)1 << 40) - 1) & PAGE_MASK))
#define PT_PSE_BASE_ADDR_MASK (PT_BASE_ADDR_MASK & ~(1ull << 21))

#define CR0_WP_MASK (1UL << 16)
#define CR4_SMEP_MASK (1UL << 20)

#define PFERR_PRESENT_MASK (1U << 0)
#define PFERR_WRITE_MASK (1U << 1)
#define PFERR_USER_MASK (1U << 2)
#define PFERR_RESERVED_MASK (1U << 3)
#define PFERR_FETCH_MASK (1U << 4)
#define PFERR_PK_MASK (1U << 5)

#define MSR_EFER 0xc0000080
#define EFER_NX_MASK		(1ull << 11)

#define PT_INDEX(address, level)       \
       ((address) >> (12 + ((level)-1) * 9)) & 511

/*
 * page table access check tests
 */

enum {
    AC_PTE_PRESENT_BIT,
    AC_PTE_WRITABLE_BIT,
    AC_PTE_USER_BIT,
    AC_PTE_ACCESSED_BIT,
    AC_PTE_DIRTY_BIT,
    AC_PTE_NX_BIT,
    AC_PTE_BIT51_BIT,

    AC_PDE_PRESENT_BIT,
    AC_PDE_WRITABLE_BIT,
    AC_PDE_USER_BIT,
    AC_PDE_ACCESSED_BIT,
    AC_PDE_DIRTY_BIT,
    AC_PDE_PSE_BIT,
    AC_PDE_NX_BIT,
    AC_PDE_BIT51_BIT,
    AC_PDE_BIT13_BIT,

    AC_PKU_AD_BIT,
    AC_PKU_WD_BIT,
    AC_PKU_PKEY_BIT,

    AC_ACCESS_USER_BIT,
    AC_ACCESS_WRITE_BIT,
    AC_ACCESS_FETCH_BIT,
    AC_ACCESS_TWICE_BIT,

    AC_CPU_EFER_NX_BIT,
    AC_CPU_CR0_WP_BIT,
    AC_CPU_CR4_SMEP_BIT,
    AC_CPU_CR4_PKE_BIT,

    NR_AC_FLAGS
};

#define AC_PTE_PRESENT_MASK   (1 << AC_PTE_PRESENT_BIT)
#define AC_PTE_WRITABLE_MASK  (1 << AC_PTE_WRITABLE_BIT)
#define AC_PTE_USER_MASK      (1 << AC_PTE_USER_BIT)
#define AC_PTE_ACCESSED_MASK  (1 << AC_PTE_ACCESSED_BIT)
#define AC_PTE_DIRTY_MASK     (1 << AC_PTE_DIRTY_BIT)
#define AC_PTE_NX_MASK        (1 << AC_PTE_NX_BIT)
#define AC_PTE_BIT51_MASK     (1 << AC_PTE_BIT51_BIT)

#define AC_PDE_PRESENT_MASK   (1 << AC_PDE_PRESENT_BIT)
#define AC_PDE_WRITABLE_MASK  (1 << AC_PDE_WRITABLE_BIT)
#define AC_PDE_USER_MASK      (1 << AC_PDE_USER_BIT)
#define AC_PDE_ACCESSED_MASK  (1 << AC_PDE_ACCESSED_BIT)
#define AC_PDE_DIRTY_MASK     (1 << AC_PDE_DIRTY_BIT)
#define AC_PDE_PSE_MASK       (1 << AC_PDE_PSE_BIT)
#define AC_PDE_NX_MASK        (1 << AC_PDE_NX_BIT)
#define AC_PDE_BIT51_MASK     (1 << AC_PDE_BIT51_BIT)
#define AC_PDE_BIT13_MASK     (1 << AC_PDE_BIT13_BIT)

#define AC_PKU_AD_MASK        (1 << AC_PKU_AD_BIT)
#define AC_PKU_WD_MASK        (1 << AC_PKU_WD_BIT)
#define AC_PKU_PKEY_MASK      (1 << AC_PKU_PKEY_BIT)

#define AC_ACCESS_USER_MASK   (1 << AC_ACCESS_USER_BIT)
#define AC_ACCESS_WRITE_MASK  (1 << AC_ACCESS_WRITE_BIT)
#define AC_ACCESS_FETCH_MASK  (1 << AC_ACCESS_FETCH_BIT)
#define AC_ACCESS_TWICE_MASK  (1 << AC_ACCESS_TWICE_BIT)

#define AC_CPU_EFER_NX_MASK   (1 << AC_CPU_EFER_NX_BIT)
#define AC_CPU_CR0_WP_MASK    (1 << AC_CPU_CR0_WP_BIT)
#define AC_CPU_CR4_SMEP_MASK  (1 << AC_CPU_CR4_SMEP_BIT)
#define AC_CPU_CR4_PKE_MASK   (1 << AC_CPU_CR4_PKE_BIT)

const char *ac_names[] = {
    [AC_PTE_PRESENT_BIT] = "pte.p",
    [AC_PTE_ACCESSED_BIT] = "pte.a",
    [AC_PTE_WRITABLE_BIT] = "pte.rw",
    [AC_PTE_USER_BIT] = "pte.user",
    [AC_PTE_DIRTY_BIT] = "pte.d",
    [AC_PTE_NX_BIT] = "pte.nx",
    [AC_PTE_BIT51_BIT] = "pte.51",
    [AC_PDE_PRESENT_BIT] = "pde.p",
    [AC_PDE_ACCESSED_BIT] = "pde.a",
    [AC_PDE_WRITABLE_BIT] = "pde.rw",
    [AC_PDE_USER_BIT] = "pde.user",
    [AC_PDE_DIRTY_BIT] = "pde.d",
    [AC_PDE_PSE_BIT] = "pde.pse",
    [AC_PDE_NX_BIT] = "pde.nx",
    [AC_PDE_BIT51_BIT] = "pde.51",
    [AC_PDE_BIT13_BIT] = "pde.13",
    [AC_PKU_AD_BIT] = "pkru.ad",
    [AC_PKU_WD_BIT] = "pkru.wd",
    [AC_PKU_PKEY_BIT] = "pkey=1",
    [AC_ACCESS_WRITE_BIT] = "write",
    [AC_ACCESS_USER_BIT] = "user",
    [AC_ACCESS_FETCH_BIT] = "fetch",
    [AC_ACCESS_TWICE_BIT] = "twice",
    [AC_CPU_EFER_NX_BIT] = "efer.nx",
    [AC_CPU_CR0_WP_BIT] = "cr0.wp",
    [AC_CPU_CR4_SMEP_BIT] = "cr4.smep",
    [AC_CPU_CR4_PKE_BIT] = "cr4.pke",
};

static inline void *va(pt_element_t phys)
{
    return (void *)phys;
}

typedef struct {
    pt_element_t pt_pool;
    unsigned pt_pool_size;
    unsigned pt_pool_current;
} ac_pool_t;

typedef struct {
    unsigned flags;
    void *virt;
    pt_element_t phys;
    pt_element_t *ptep;
    pt_element_t expected_pte;
    pt_element_t *pdep;
    pt_element_t expected_pde;
    pt_element_t ignore_pde;
    int expected_fault;
    unsigned expected_error;
} ac_test_t;

typedef struct {
    unsigned short limit;
    unsigned long linear_addr;
} __attribute__((packed)) descriptor_table_t;


static void ac_test_show(ac_test_t *at);

int write_cr4_checking(unsigned long val)
{
    asm volatile(ASM_TRY("1f")
            "mov %0,%%cr4\n\t"
            "1:": : "r" (val));
    return exception_vector();
}

void set_cr0_wp(int wp)
{
    unsigned long cr0 = read_cr0();
    unsigned long old_cr0 = cr0;

    cr0 &= ~CR0_WP_MASK;
    if (wp)
	cr0 |= CR0_WP_MASK;
    if (old_cr0 != cr0)
        write_cr0(cr0);
}

void set_cr4_smep(int smep)
{
    unsigned long cr4 = read_cr4();
    unsigned long old_cr4 = cr4;
    extern u64 ptl2[];

    cr4 &= ~CR4_SMEP_MASK;
    if (smep)
	cr4 |= CR4_SMEP_MASK;
    if (old_cr4 == cr4)
        return;

    if (smep)
        ptl2[2] &= ~PT_USER_MASK;
    write_cr4(cr4);
    if (!smep)
        ptl2[2] |= PT_USER_MASK;
}

void set_cr4_pke(int pke)
{
    unsigned long cr4 = read_cr4();
    unsigned long old_cr4 = cr4;

    cr4 &= ~X86_CR4_PKE;
    if (pke)
	cr4 |= X86_CR4_PKE;
    if (old_cr4 == cr4)
        return;

    /* Check that protection keys do not affect accesses when CR4.PKE=0.  */
    if ((read_cr4() & X86_CR4_PKE) && !pke) {
        write_pkru(0xfffffffc);
    }
    write_cr4(cr4);
}

void set_efer_nx(int nx)
{
    unsigned long long efer = rdmsr(MSR_EFER);
    unsigned long long old_efer = efer;

    efer &= ~EFER_NX_MASK;
    if (nx)
	efer |= EFER_NX_MASK;
    if (old_efer != efer)
        wrmsr(MSR_EFER, efer);
}

static void ac_env_int(ac_pool_t *pool)
{
    extern char page_fault, kernel_entry;
    set_idt_entry(14, &page_fault, 0);
    set_idt_entry(0x20, &kernel_entry, 3);

    pool->pt_pool = 33 * 1024 * 1024;
    pool->pt_pool_size = 120 * 1024 * 1024 - pool->pt_pool;
    pool->pt_pool_current = 0;
}

void ac_test_init(ac_test_t *at, void *virt)
{
    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NX_MASK);
    set_cr0_wp(1);
    at->flags = 0;
    at->virt = virt;
    at->phys = 32 * 1024 * 1024;
}

int ac_test_bump_one(ac_test_t *at)
{
    at->flags = ((at->flags | invalid_mask) + 1) & ~invalid_mask;
    return at->flags < (1 << NR_AC_FLAGS);
}

#define F(x)  ((flags & x##_MASK) != 0)

_Bool ac_test_legal(ac_test_t *at)
{
    int flags = at->flags;

    if (F(AC_ACCESS_FETCH) && F(AC_ACCESS_WRITE))
	return false;

    /*
     * Since we convert current page to kernel page when cr4.smep=1,
     * we can't switch to user mode.
     */
    if (F(AC_ACCESS_USER) && F(AC_CPU_CR4_SMEP))
	return false;

    /*
     * Only test protection key faults if CR4.PKE=1.
     */
    if (!F(AC_CPU_CR4_PKE) &&
        (F(AC_PKU_AD) || F(AC_PKU_WD))) {
	return false;
    }

    /*
     * pde.bit13 checks handling of reserved bits in largepage PDEs.  It is
     * meaningless if there is a PTE.
     */
    if (!F(AC_PDE_PSE) && F(AC_PDE_BIT13))
        return false;

    return true;
}

int ac_test_bump(ac_test_t *at)
{
    int ret;

    ret = ac_test_bump_one(at);
    while (ret && !ac_test_legal(at))
	ret = ac_test_bump_one(at);
    return ret;
}

pt_element_t ac_test_alloc_pt(ac_pool_t *pool)
{
    pt_element_t ret = pool->pt_pool + pool->pt_pool_current;
    pool->pt_pool_current += PAGE_SIZE;
    return ret;
}

_Bool ac_test_enough_room(ac_pool_t *pool)
{
    return pool->pt_pool_current + 4 * PAGE_SIZE <= pool->pt_pool_size;
}

void ac_test_reset_pt_pool(ac_pool_t *pool)
{
    pool->pt_pool_current = 0;
}

pt_element_t ac_test_permissions(ac_test_t *at, unsigned flags, bool writable,
                                 bool user, bool executable)
{
    bool kwritable = !F(AC_CPU_CR0_WP) && !F(AC_ACCESS_USER);
    pt_element_t expected = 0;

    if (F(AC_ACCESS_USER) && !user)
	at->expected_fault = 1;

    if (F(AC_ACCESS_WRITE) && !writable && !kwritable)
	at->expected_fault = 1;

    if (F(AC_ACCESS_FETCH) && !executable)
	at->expected_fault = 1;

    if (F(AC_ACCESS_FETCH) && user && F(AC_CPU_CR4_SMEP))
        at->expected_fault = 1;

    if (user && !F(AC_ACCESS_FETCH) && F(AC_PKU_PKEY) && F(AC_CPU_CR4_PKE)) {
        if (F(AC_PKU_AD)) {
            at->expected_fault = 1;
            at->expected_error |= PFERR_PK_MASK;
        } else if (F(AC_ACCESS_WRITE) && F(AC_PKU_WD) && !kwritable) {
            at->expected_fault = 1;
            at->expected_error |= PFERR_PK_MASK;
        }
    }

    if (!at->expected_fault) {
        expected |= PT_ACCESSED_MASK;
        if (F(AC_ACCESS_WRITE))
            expected |= PT_DIRTY_MASK;
    }

    return expected;
}

void ac_emulate_access(ac_test_t *at, unsigned flags)
{
    bool pde_valid, pte_valid;
    bool user, writable, executable;

    if (F(AC_ACCESS_USER))
	at->expected_error |= PFERR_USER_MASK;

    if (F(AC_ACCESS_WRITE))
	at->expected_error |= PFERR_WRITE_MASK;

    if (F(AC_ACCESS_FETCH))
	at->expected_error |= PFERR_FETCH_MASK;

    if (!F(AC_PDE_ACCESSED))
        at->ignore_pde = PT_ACCESSED_MASK;

    pde_valid = F(AC_PDE_PRESENT)
        && !F(AC_PDE_BIT51) && !F(AC_PDE_BIT13)
        && !(F(AC_PDE_NX) && !F(AC_CPU_EFER_NX));

    if (!pde_valid) {
        at->expected_fault = 1;
	if (F(AC_PDE_PRESENT)) {
            at->expected_error |= PFERR_RESERVED_MASK;
        } else {
            at->expected_error &= ~PFERR_PRESENT_MASK;
        }
	goto fault;
    }

    writable = F(AC_PDE_WRITABLE);
    user = F(AC_PDE_USER);
    executable = !F(AC_PDE_NX);

    if (F(AC_PDE_PSE)) {
        at->expected_pde |= ac_test_permissions(at, flags, writable, user,
                                                executable);
	goto no_pte;
    }

    at->expected_pde |= PT_ACCESSED_MASK;

    pte_valid = F(AC_PTE_PRESENT)
        && !F(AC_PTE_BIT51)
        && !(F(AC_PTE_NX) && !F(AC_CPU_EFER_NX));

    if (!pte_valid) {
        at->expected_fault = 1;
	if (F(AC_PTE_PRESENT)) {
            at->expected_error |= PFERR_RESERVED_MASK;
        } else {
            at->expected_error &= ~PFERR_PRESENT_MASK;
        }
	goto fault;
    }

    writable &= F(AC_PTE_WRITABLE);
    user &= F(AC_PTE_USER);
    executable &= !F(AC_PTE_NX);

    at->expected_pte |= ac_test_permissions(at, flags, writable, user,
                                            executable);

no_pte:
fault:
    if (!at->expected_fault)
        at->ignore_pde = 0;
    if (!F(AC_CPU_EFER_NX) && !F(AC_CPU_CR4_SMEP))
        at->expected_error &= ~PFERR_FETCH_MASK;
}

void ac_set_expected_status(ac_test_t *at)
{
    invlpg(at->virt);

    if (at->ptep)
	at->expected_pte = *at->ptep;
    at->expected_pde = *at->pdep;
    at->ignore_pde = 0;
    at->expected_fault = 0;
    at->expected_error = PFERR_PRESENT_MASK;

    if (at->flags & AC_ACCESS_TWICE_MASK) {
        ac_emulate_access(at, at->flags & ~AC_ACCESS_WRITE_MASK
                          & ~AC_ACCESS_FETCH_MASK & ~AC_ACCESS_USER_MASK);
        at->expected_fault = 0;
	at->expected_error = PFERR_PRESENT_MASK;
        at->ignore_pde = 0;
    }

    ac_emulate_access(at, at->flags);
}

void __ac_setup_specific_pages(ac_test_t *at, ac_pool_t *pool, u64 pd_page,
			       u64 pt_page)

{
    unsigned long root = read_cr3();
    int flags = at->flags;

    if (!ac_test_enough_room(pool))
	ac_test_reset_pt_pool(pool);

    at->ptep = 0;
    for (int i = 4; i >= 1 && (i >= 2 || !F(AC_PDE_PSE)); --i) {
	pt_element_t *vroot = va(root & PT_BASE_ADDR_MASK);
	unsigned index = PT_INDEX((unsigned long)at->virt, i);
	pt_element_t pte = 0;
	switch (i) {
	case 4:
	case 3:
	    pte = pd_page ? pd_page : ac_test_alloc_pt(pool);
	    pte |= PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
	    break;
	case 2:
	    if (!F(AC_PDE_PSE)) {
		pte = pt_page ? pt_page : ac_test_alloc_pt(pool);
		/* The protection key is ignored on non-leaf entries.  */
                if (F(AC_PKU_PKEY))
                    pte |= 2ull << 59;
	    } else {
		pte = at->phys & PT_PSE_BASE_ADDR_MASK;
		pte |= PT_PAGE_SIZE_MASK;
                if (F(AC_PKU_PKEY))
                    pte |= 1ull << 59;
	    }
	    if (F(AC_PDE_PRESENT))
		pte |= PT_PRESENT_MASK;
	    if (F(AC_PDE_WRITABLE))
		pte |= PT_WRITABLE_MASK;
	    if (F(AC_PDE_USER))
		pte |= PT_USER_MASK;
	    if (F(AC_PDE_ACCESSED))
		pte |= PT_ACCESSED_MASK;
	    if (F(AC_PDE_DIRTY))
		pte |= PT_DIRTY_MASK;
	    if (F(AC_PDE_NX))
		pte |= PT64_NX_MASK;
	    if (F(AC_PDE_BIT51))
		pte |= 1ull << 51;
	    if (F(AC_PDE_BIT13))
		pte |= 1ull << 13;
	    at->pdep = &vroot[index];
	    break;
	case 1:
	    pte = at->phys & PT_BASE_ADDR_MASK;
	    if (F(AC_PKU_PKEY))
		pte |= 1ull << 59;
	    if (F(AC_PTE_PRESENT))
		pte |= PT_PRESENT_MASK;
	    if (F(AC_PTE_WRITABLE))
		pte |= PT_WRITABLE_MASK;
	    if (F(AC_PTE_USER))
		pte |= PT_USER_MASK;
	    if (F(AC_PTE_ACCESSED))
		pte |= PT_ACCESSED_MASK;
	    if (F(AC_PTE_DIRTY))
		pte |= PT_DIRTY_MASK;
	    if (F(AC_PTE_NX))
		pte |= PT64_NX_MASK;
	    if (F(AC_PTE_BIT51))
		pte |= 1ull << 51;
	    at->ptep = &vroot[index];
	    break;
	}
	vroot[index] = pte;
	root = vroot[index];
    }
    ac_set_expected_status(at);
}

static void ac_test_setup_pte(ac_test_t *at, ac_pool_t *pool)
{
	__ac_setup_specific_pages(at, pool, 0, 0);
}

static void ac_setup_specific_pages(ac_test_t *at, ac_pool_t *pool,
				    u64 pd_page, u64 pt_page)
{
	return __ac_setup_specific_pages(at, pool, pd_page, pt_page);
}

static void dump_mapping(ac_test_t *at)
{
	unsigned long root = read_cr3();
        int flags = at->flags;
	int i;

	printf("Dump mapping: address: %p\n", at->virt);
	for (i = 4; i >= 1 && (i >= 2 || !F(AC_PDE_PSE)); --i) {
		pt_element_t *vroot = va(root & PT_BASE_ADDR_MASK);
		unsigned index = PT_INDEX((unsigned long)at->virt, i);
		pt_element_t pte = vroot[index];

		printf("------L%d: %lx\n", i, pte);
		root = vroot[index];
	}
}

static void ac_test_check(ac_test_t *at, _Bool *success_ret, _Bool cond,
                          const char *fmt, ...)
{
    va_list ap;
    char buf[500];

    if (!*success_ret) {
        return;
    }

    if (!cond) {
        return;
    }

    *success_ret = false;

    if (!verbose) {
        puts("\n");
        ac_test_show(at);
    }

    va_start(ap, fmt);
    vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    printf("FAIL: %s\n", buf);
    dump_mapping(at);
}

static int pt_match(pt_element_t pte1, pt_element_t pte2, pt_element_t ignore)
{
    pte1 &= ~ignore;
    pte2 &= ~ignore;
    return pte1 == pte2;
}

int ac_test_do_access(ac_test_t *at)
{
    static unsigned unique = 42;
    int fault = 0;
    unsigned e;
    static unsigned char user_stack[4096];
    unsigned long rsp;
    _Bool success = true;
    int flags = at->flags;

    ++unique;
    if (!(unique & 65535)) {
        puts(".");
    }

    *((unsigned char *)at->phys) = 0xc3; /* ret */

    unsigned r = unique;
    set_cr0_wp(F(AC_CPU_CR0_WP));
    set_efer_nx(F(AC_CPU_EFER_NX));
    set_cr4_pke(F(AC_CPU_CR4_PKE));
    if (F(AC_CPU_CR4_PKE)) {
        /* WD2=AD2=1, WD1=F(AC_PKU_WD), AD1=F(AC_PKU_AD) */
        write_pkru(0x30 | (F(AC_PKU_WD) ? 8 : 0) |
                   (F(AC_PKU_AD) ? 4 : 0));
    }

    set_cr4_smep(F(AC_CPU_CR4_SMEP));

    if (F(AC_ACCESS_TWICE)) {
	asm volatile (
	    "mov $fixed2, %%rsi \n\t"
	    "mov (%[addr]), %[reg] \n\t"
	    "fixed2:"
	    : [reg]"=r"(r), [fault]"=a"(fault), "=b"(e)
	    : [addr]"r"(at->virt)
	    : "rsi"
	    );
	fault = 0;
    }

    asm volatile ("mov $fixed1, %%rsi \n\t"
		  "mov %%rsp, %%rdx \n\t"
		  "cmp $0, %[user] \n\t"
		  "jz do_access \n\t"
		  "push %%rax; mov %[user_ds], %%ax; mov %%ax, %%ds; pop %%rax  \n\t"
		  "pushq %[user_ds] \n\t"
		  "pushq %[user_stack_top] \n\t"
		  "pushfq \n\t"
		  "pushq %[user_cs] \n\t"
		  "pushq $do_access \n\t"
		  "iretq \n"
		  "do_access: \n\t"
		  "cmp $0, %[fetch] \n\t"
		  "jnz 2f \n\t"
		  "cmp $0, %[write] \n\t"
		  "jnz 1f \n\t"
		  "mov (%[addr]), %[reg] \n\t"
		  "jmp done \n\t"
		  "1: mov %[reg], (%[addr]) \n\t"
		  "jmp done \n\t"
		  "2: call *%[addr] \n\t"
		  "done: \n"
		  "fixed1: \n"
		  "int %[kernel_entry_vector] \n\t"
		  "back_to_kernel:"
		  : [reg]"+r"(r), "+a"(fault), "=b"(e), "=&d"(rsp)
		  : [addr]"r"(at->virt),
		    [write]"r"(F(AC_ACCESS_WRITE)),
		    [user]"r"(F(AC_ACCESS_USER)),
		    [fetch]"r"(F(AC_ACCESS_FETCH)),
		    [user_ds]"i"(USER_DS),
		    [user_cs]"i"(USER_CS),
		    [user_stack_top]"r"(user_stack + sizeof user_stack),
		    [kernel_entry_vector]"i"(0x20)
		  : "rsi");

    asm volatile (".section .text.pf \n\t"
		  "page_fault: \n\t"
		  "pop %rbx \n\t"
		  "mov %rsi, (%rsp) \n\t"
		  "movl $1, %eax \n\t"
		  "iretq \n\t"
		  ".section .text");

    asm volatile (".section .text.entry \n\t"
		  "kernel_entry: \n\t"
		  "mov %rdx, %rsp \n\t"
		  "jmp back_to_kernel \n\t"
		  ".section .text");

    ac_test_check(at, &success, fault && !at->expected_fault,
                  "unexpected fault");
    ac_test_check(at, &success, !fault && at->expected_fault,
                  "unexpected access");
    ac_test_check(at, &success, fault && e != at->expected_error,
                  "error code %x expected %x", e, at->expected_error);
    ac_test_check(at, &success, at->ptep && *at->ptep != at->expected_pte,
                  "pte %x expected %x", *at->ptep, at->expected_pte);
    ac_test_check(at, &success,
                  !pt_match(*at->pdep, at->expected_pde, at->ignore_pde),
                  "pde %x expected %x", *at->pdep, at->expected_pde);

    if (success && verbose) {
	if (at->expected_fault) {
            printf("PASS (%x)\n", at->expected_error);
	} else {
            printf("PASS\n");
	}
    }
    return success;
}

static void ac_test_show(ac_test_t *at)
{
    char line[5000];

    *line = 0;
    strcat(line, "test");
    for (int i = 0; i < NR_AC_FLAGS; ++i)
	if (at->flags & (1 << i)) {
	    strcat(line, " ");
	    strcat(line, ac_names[i]);
	}
    strcat(line, ": ");
    printf("%s", line);
}

/*
 * This test case is used to triger the bug which is fixed by
 * commit e09e90a5 in the kvm tree
 */
static int corrupt_hugepage_triger(ac_pool_t *pool)
{
    ac_test_t at1, at2;

    ac_test_init(&at1, (void *)(0x123400000000));
    ac_test_init(&at2, (void *)(0x666600000000));

    at2.flags = AC_CPU_CR0_WP_MASK | AC_PDE_PSE_MASK | AC_PDE_PRESENT_MASK;
    ac_test_setup_pte(&at2, pool);
    if (!ac_test_do_access(&at2))
        goto err;

    at1.flags = at2.flags | AC_PDE_WRITABLE_MASK;
    ac_test_setup_pte(&at1, pool);
    if (!ac_test_do_access(&at1))
        goto err;

    at1.flags |= AC_ACCESS_WRITE_MASK;
    ac_set_expected_status(&at1);
    if (!ac_test_do_access(&at1))
        goto err;

    at2.flags |= AC_ACCESS_WRITE_MASK;
    ac_set_expected_status(&at2);
    if (!ac_test_do_access(&at2))
        goto err;

    return 1;

err:
    printf("corrupt_hugepage_triger test fail\n");
    return 0;
}

/*
 * This test case is used to triger the bug which is fixed by
 * commit 3ddf6c06e13e in the kvm tree
 */
static int check_pfec_on_prefetch_pte(ac_pool_t *pool)
{
	ac_test_t at1, at2;

	ac_test_init(&at1, (void *)(0x123406001000));
	ac_test_init(&at2, (void *)(0x123406003000));

	at1.flags = AC_PDE_PRESENT_MASK | AC_PTE_PRESENT_MASK;
	ac_setup_specific_pages(&at1, pool, 30 * 1024 * 1024, 30 * 1024 * 1024);

        at2.flags = at1.flags | AC_PTE_NX_MASK;
	ac_setup_specific_pages(&at2, pool, 30 * 1024 * 1024, 30 * 1024 * 1024);

	if (!ac_test_do_access(&at1)) {
		printf("%s: prepare fail\n", __FUNCTION__);
		goto err;
	}

	if (!ac_test_do_access(&at2)) {
		printf("%s: check PFEC on prefetch pte path fail\n",
			__FUNCTION__);
		goto err;
	}

	return 1;

err:
    return 0;
}

/*
 * If the write-fault access is from supervisor and CR0.WP is not set on the
 * vcpu, kvm will fix it by adjusting pte access - it sets the W bit on pte
 * and clears U bit. This is the chance that kvm can change pte access from
 * readonly to writable.
 *
 * Unfortunately, the pte access is the access of 'direct' shadow page table,
 * means direct sp.role.access = pte_access, then we will create a writable
 * spte entry on the readonly shadow page table. It will cause Dirty bit is
 * not tracked when two guest ptes point to the same large page. Note, it
 * does not have other impact except Dirty bit since cr0.wp is encoded into
 * sp.role.
 *
 * Note: to trigger this bug, hugepage should be disabled on host.
 */
static int check_large_pte_dirty_for_nowp(ac_pool_t *pool)
{
	ac_test_t at1, at2;

	ac_test_init(&at1, (void *)(0x123403000000));
	ac_test_init(&at2, (void *)(0x666606000000));

        at2.flags = AC_PDE_PRESENT_MASK | AC_PDE_PSE_MASK;
	ac_test_setup_pte(&at2, pool);
	if (!ac_test_do_access(&at2)) {
		printf("%s: read on the first mapping fail.\n", __FUNCTION__);
		goto err;
	}

        at1.flags = at2.flags | AC_ACCESS_WRITE_MASK;
	ac_test_setup_pte(&at1, pool);
	if (!ac_test_do_access(&at1)) {
		printf("%s: write on the second mapping fail.\n", __FUNCTION__);
		goto err;
	}

	at2.flags |= AC_ACCESS_WRITE_MASK;
	ac_set_expected_status(&at2);
	if (!ac_test_do_access(&at2)) {
		printf("%s: write on the first mapping fail.\n", __FUNCTION__);
		goto err;
	}

	return 1;

err:
	return 0;
}

static int check_smep_andnot_wp(ac_pool_t *pool)
{
	ac_test_t at1;
	int err_prepare_andnot_wp, err_smep_andnot_wp;

	if (!(cpuid_7_ebx & (1 << 7))) {
	    return 1;
	}

	ac_test_init(&at1, (void *)(0x123406001000));

	at1.flags = AC_PDE_PRESENT_MASK | AC_PTE_PRESENT_MASK |
            AC_PDE_USER_MASK | AC_PTE_USER_MASK |
            AC_PDE_ACCESSED_MASK | AC_PTE_ACCESSED_MASK |
            AC_CPU_CR4_SMEP_MASK |
            AC_CPU_CR0_WP_MASK |
            AC_ACCESS_WRITE_MASK;
	ac_test_setup_pte(&at1, pool);

	/*
	 * Here we write the ro user page when
	 * cr0.wp=0, then we execute it and SMEP
	 * fault should happen.
	 */
	err_prepare_andnot_wp = ac_test_do_access(&at1);
	if (!err_prepare_andnot_wp) {
		printf("%s: SMEP prepare fail\n", __FUNCTION__);
		goto clean_up;
	}

        at1.flags &= ~AC_ACCESS_WRITE_MASK;
        at1.flags |= AC_ACCESS_FETCH_MASK;
        ac_set_expected_status(&at1);
        err_smep_andnot_wp = ac_test_do_access(&at1);

clean_up:
	set_cr4_smep(0);

	if (!err_prepare_andnot_wp)
		goto err;
	if (!err_smep_andnot_wp) {
		printf("%s: check SMEP without wp fail\n", __FUNCTION__);
		goto err;
	}
	return 1;

err:
	return 0;
}

int ac_test_exec(ac_test_t *at, ac_pool_t *pool)
{
    int r;

    if (verbose) {
        ac_test_show(at);
    }
    ac_test_setup_pte(at, pool);
    r = ac_test_do_access(at);
    return r;
}

typedef int (*ac_test_fn)(ac_pool_t *pool);
const ac_test_fn ac_test_cases[] =
{
	corrupt_hugepage_triger,
	check_pfec_on_prefetch_pte,
	check_large_pte_dirty_for_nowp,
	check_smep_andnot_wp
};

int ac_test_run(void)
{
    ac_test_t at;
    ac_pool_t pool;
    int i, tests, successes;

    printf("run\n");
    tests = successes = 0;

    if (cpuid_7_ecx & (1 << 3)) {
        set_cr4_pke(1);
        set_cr4_pke(0);
        /* Now PKRU = 0xFFFFFFFF.  */
    } else {
	unsigned long cr4 = read_cr4();
	tests++;
	if (write_cr4_checking(cr4 | X86_CR4_PKE) == GP_VECTOR) {
            successes++;
            invalid_mask |= AC_PKU_AD_MASK;
            invalid_mask |= AC_PKU_WD_MASK;
            invalid_mask |= AC_PKU_PKEY_MASK;
            invalid_mask |= AC_CPU_CR4_PKE_MASK;
            printf("CR4.PKE not available, disabling PKE tests\n");
	} else {
            printf("Set PKE in CR4 - expect #GP: FAIL!\n");
            set_cr4_pke(0);
	}
    }

    if (!(cpuid_7_ebx & (1 << 7))) {
	unsigned long cr4 = read_cr4();
	tests++;
	if (write_cr4_checking(cr4 | CR4_SMEP_MASK) == GP_VECTOR) {
            successes++;
            invalid_mask |= AC_CPU_CR4_SMEP_MASK;
            printf("CR4.SMEP not available, disabling SMEP tests\n");
	} else {
            printf("Set SMEP in CR4 - expect #GP: FAIL!\n");
            set_cr4_smep(0);
	}
    }

    ac_env_int(&pool);
    ac_test_init(&at, (void *)(0x123400000000 + 16 * smp_id()));
    do {
	++tests;
	successes += ac_test_exec(&at, &pool);
    } while (ac_test_bump(&at));

    for (i = 0; i < ARRAY_SIZE(ac_test_cases); i++) {
	++tests;
	successes += ac_test_cases[i](&pool);
    }

    printf("\n%d tests, %d failures\n", tests, tests - successes);

    return successes == tests;
}

int main()
{
    int r;

    setup_idt();

    cpuid_7_ebx = cpuid(7).b;
    cpuid_7_ecx = cpuid(7).c;

    printf("starting test\n\n");
    r = ac_test_run();
    return r ? 0 : 1;
}
                                                                                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/x86/apic.c                                                          0000644 0000000 0000000 00000027461 00000000000 015457  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "apic.h"
#include "vm.h"
#include "smp.h"
#include "desc.h"
#include "isr.h"
#include "msr.h"
#include "atomic.h"

static void test_lapic_existence(void)
{
    u32 lvr;

    lvr = apic_read(APIC_LVR);
    printf("apic version: %x\n", lvr);
    report("apic existence", (u16)lvr == 0x14);
}

#define TSC_DEADLINE_TIMER_VECTOR 0xef
#define BROADCAST_VECTOR 0xcf

static int tdt_count;

static void tsc_deadline_timer_isr(isr_regs_t *regs)
{
    ++tdt_count;
    eoi();
}

static void __test_tsc_deadline_timer(void)
{
    handle_irq(TSC_DEADLINE_TIMER_VECTOR, tsc_deadline_timer_isr);
    irq_enable();

    wrmsr(MSR_IA32_TSCDEADLINE, rdmsr(MSR_IA32_TSC));
    asm volatile ("nop");
    report("tsc deadline timer", tdt_count == 1);
    report("tsc deadline timer clearing", rdmsr(MSR_IA32_TSCDEADLINE) == 0);
}

static int enable_tsc_deadline_timer(void)
{
    uint32_t lvtt;

    if (cpuid(1).c & (1 << 24)) {
        lvtt = APIC_LVT_TIMER_TSCDEADLINE | TSC_DEADLINE_TIMER_VECTOR;
        apic_write(APIC_LVTT, lvtt);
        return 1;
    } else {
        return 0;
    }
}

static void test_tsc_deadline_timer(void)
{
    if(enable_tsc_deadline_timer()) {
        __test_tsc_deadline_timer();
    } else {
        report_skip("tsc deadline timer not detected");
    }
}

static void do_write_apicbase(void *data)
{
    wrmsr(MSR_IA32_APICBASE, *(u64 *)data);
}

void test_enable_x2apic(void)
{
    u64 invalid_state = APIC_DEFAULT_PHYS_BASE | APIC_BSP | APIC_EXTD;
    u64 apic_enabled = APIC_DEFAULT_PHYS_BASE | APIC_BSP | APIC_EN;
    u64 x2apic_enabled =
        APIC_DEFAULT_PHYS_BASE | APIC_BSP | APIC_EN | APIC_EXTD;

    if (enable_x2apic()) {
        printf("x2apic enabled\n");

        report("x2apic enabled to invalid state",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &invalid_state));
        report("x2apic enabled to apic enabled",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &apic_enabled));

        wrmsr(MSR_IA32_APICBASE, APIC_DEFAULT_PHYS_BASE | APIC_BSP);
        report("disabled to invalid state",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &invalid_state));
        report("disabled to x2apic enabled",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &x2apic_enabled));

        wrmsr(MSR_IA32_APICBASE, apic_enabled);
        report("apic enabled to invalid state",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &invalid_state));

        wrmsr(MSR_IA32_APICBASE, x2apic_enabled);
        apic_write(APIC_SPIV, 0x1ff);
    } else {
        printf("x2apic not detected\n");

        report("enable unsupported x2apic",
               test_for_exception(GP_VECTOR, do_write_apicbase,
                                  &x2apic_enabled));
    }
}

static void test_apic_disable(void)
{
    u64 orig_apicbase = rdmsr(MSR_IA32_APICBASE);

    report_prefix_push("apic_disable");

    report("Local apic enabled", orig_apicbase & APIC_EN);
    report("CPUID.1H:EDX.APIC[bit 9] is set", cpuid(1).d & (1 << 9));

    wrmsr(MSR_IA32_APICBASE, orig_apicbase & ~(APIC_EN | APIC_EXTD));
    report("Local apic disabled", !(rdmsr(MSR_IA32_APICBASE) & APIC_EN));
    report("CPUID.1H:EDX.APIC[bit 9] is clear", !(cpuid(1).d & (1 << 9)));

    wrmsr(MSR_IA32_APICBASE, orig_apicbase & ~APIC_EXTD);
    wrmsr(MSR_IA32_APICBASE, orig_apicbase);
    apic_write(APIC_SPIV, 0x1ff);
    report("Local apic enabled", rdmsr(MSR_IA32_APICBASE) & APIC_EN);
    report("CPUID.1H:EDX.APIC[bit 9] is set", cpuid(1).d & (1 << 9));

    report_prefix_pop();
}

#define ALTERNATE_APIC_BASE	0x42000000

static void test_apicbase(void)
{
    u64 orig_apicbase = rdmsr(MSR_IA32_APICBASE);
    u32 lvr = apic_read(APIC_LVR);
    u64 value;

    wrmsr(MSR_IA32_APICBASE, orig_apicbase & ~(APIC_EN | APIC_EXTD));
    wrmsr(MSR_IA32_APICBASE, ALTERNATE_APIC_BASE | APIC_BSP | APIC_EN);

    report_prefix_push("apicbase");

    report("relocate apic",
           *(volatile u32 *)(ALTERNATE_APIC_BASE + APIC_LVR) == lvr);

    value = orig_apicbase | (1UL << cpuid_maxphyaddr());
    report("reserved physaddr bits",
           test_for_exception(GP_VECTOR, do_write_apicbase, &value));

    value = orig_apicbase | 1;
    report("reserved low bits",
           test_for_exception(GP_VECTOR, do_write_apicbase, &value));

    wrmsr(MSR_IA32_APICBASE, orig_apicbase);
    apic_write(APIC_SPIV, 0x1ff);

    report_prefix_pop();
}

static void do_write_apic_id(void *id)
{
    apic_write(APIC_ID, *(u32 *)id);
}

static void __test_apic_id(void * unused)
{
    u32 id, newid;
    u8  initial_xapic_id = cpuid(1).b >> 24;
    u32 initial_x2apic_id = cpuid(0xb).d;
    bool x2apic_mode = rdmsr(MSR_IA32_APICBASE) & APIC_EXTD;

    if (x2apic_mode)
        reset_apic();

    id = apic_id();
    report("xapic id matches cpuid", initial_xapic_id == id);

    newid = (id + 1) << 24;
    report("writeable xapic id",
            !test_for_exception(GP_VECTOR, do_write_apic_id, &newid) &&
            id + 1 == apic_id());

    if (!enable_x2apic())
        goto out;

    report("non-writeable x2apic id",
            test_for_exception(GP_VECTOR, do_write_apic_id, &newid));
    report("sane x2apic id", initial_xapic_id == (apic_id() & 0xff));

    /* old QEMUs do not set initial x2APIC ID */
    report("x2apic id matches cpuid",
           initial_xapic_id == (initial_x2apic_id & 0xff) &&
           initial_x2apic_id == apic_id());

out:
    reset_apic();

    report("correct xapic id after reset", initial_xapic_id == apic_id());

    /* old KVMs do not reset xAPIC ID */
    if (id != apic_id())
        apic_write(APIC_ID, id << 24);

    if (x2apic_mode)
        enable_x2apic();
}

static void test_apic_id(void)
{
    if (cpu_count() < 2)
        return;

    on_cpu(1, __test_apic_id, NULL);
}

static int ipi_count;

static void self_ipi_isr(isr_regs_t *regs)
{
    ++ipi_count;
    eoi();
}

static void test_self_ipi(void)
{
    int vec = 0xf1;

    handle_irq(vec, self_ipi_isr);
    irq_enable();
    apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL | APIC_DM_FIXED | vec,
                   0);
    asm volatile ("nop");
    report("self ipi", ipi_count == 1);
}

volatile int nmi_counter_private, nmi_counter, nmi_hlt_counter, sti_loop_active;

/* noinline: the asm defines the global label post_sti, which must exist once (clang inlines this) */
__attribute__((noinline)) void sti_nop(char *p)
{
    asm volatile (
		  ".globl post_sti \n\t"
		  "sti \n"
		  /*
		   * vmx won't exit on external interrupt if blocked-by-sti,
		   * so give it a reason to exit by accessing an unmapped page.
		   */
		  "post_sti: testb $0, %0 \n\t"
		  "nop \n\t"
		  "cli"
		  : : "m"(*p)
		  );
    nmi_counter = nmi_counter_private;
}

static void sti_loop(void *ignore)
{
    unsigned k = 0;

    while (sti_loop_active) {
	sti_nop((char *)(ulong)((k++ * 4096) % (128 * 1024 * 1024)));
    }
}

static void nmi_handler(isr_regs_t *regs)
{
    extern void post_sti(void);
    ++nmi_counter_private;
    nmi_hlt_counter += regs->rip == (ulong)post_sti;
}

static void update_cr3(void *cr3)
{
    write_cr3((ulong)cr3);
}

static void test_sti_nmi(void)
{
    unsigned old_counter;

    if (cpu_count() < 2) {
	return;
    }

    handle_irq(2, nmi_handler);
    on_cpu(1, update_cr3, (void *)read_cr3());

    sti_loop_active = 1;
    on_cpu_async(1, sti_loop, 0);
    while (nmi_counter < 30000) {
	old_counter = nmi_counter;
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, 1);
	while (nmi_counter == old_counter) {
	    ;
	}
    }
    sti_loop_active = 0;
    report("nmi-after-sti", nmi_hlt_counter == 0);
}

static volatile bool nmi_done, nmi_flushed;
static volatile int nmi_received;
static volatile int cpu0_nmi_ctr1, cpu1_nmi_ctr1;
static volatile int cpu0_nmi_ctr2, cpu1_nmi_ctr2;

static void multiple_nmi_handler(isr_regs_t *regs)
{
    ++nmi_received;
}

static void kick_me_nmi(void *blah)
{
    while (!nmi_done) {
	++cpu1_nmi_ctr1;
	while (cpu1_nmi_ctr1 != cpu0_nmi_ctr1 && !nmi_done) {
	    pause();
	}
	if (nmi_done) {
	    return;
	}
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, 0);
	/* make sure the NMI has arrived by sending an IPI after it */
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_FIXED | APIC_INT_ASSERT
		       | 0x44, 0);
	++cpu1_nmi_ctr2;
	while (cpu1_nmi_ctr2 != cpu0_nmi_ctr2 && !nmi_done) {
	    pause();
	}
    }
}

static void flush_nmi(isr_regs_t *regs)
{
    nmi_flushed = true;
    apic_write(APIC_EOI, 0);
}

static void test_multiple_nmi(void)
{
    int i;
    bool ok = true;

    if (cpu_count() < 2) {
	return;
    }

    sti();
    handle_irq(2, multiple_nmi_handler);
    handle_irq(0x44, flush_nmi);
    on_cpu_async(1, kick_me_nmi, 0);
    for (i = 0; i < 1000000; ++i) {
	nmi_flushed = false;
	nmi_received = 0;
	++cpu0_nmi_ctr1;
	while (cpu1_nmi_ctr1 != cpu0_nmi_ctr1) {
	    pause();
	}
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, 0);
	while (!nmi_flushed) {
	    pause();
	}
	if (nmi_received != 2) {
	    ok = false;
	    break;
	}
	++cpu0_nmi_ctr2;
	while (cpu1_nmi_ctr2 != cpu0_nmi_ctr2) {
	    pause();
	}
    }
    nmi_done = true;
    report("multiple nmi", ok);
}

static volatile int lvtt_counter = 0;

static void lvtt_handler(isr_regs_t *regs)
{
    lvtt_counter++;
    eoi();
}

static void test_apic_timer_one_shot(void)
{
    uint64_t tsc1, tsc2;
    static const uint32_t interval = 0x10000;

#define APIC_LVT_TIMER_VECTOR    (0xee)

    handle_irq(APIC_LVT_TIMER_VECTOR, lvtt_handler);
    irq_enable();

    /* One shot mode */
    apic_write(APIC_LVTT, APIC_LVT_TIMER_ONESHOT |
               APIC_LVT_TIMER_VECTOR);
    /* Divider == 1 */
    apic_write(APIC_TDCR, 0x0000000b);

    tsc1 = rdtsc();
    /* Set "Initial Counter Register", which starts the timer */
    apic_write(APIC_TMICT, interval);
    while (!lvtt_counter);
    tsc2 = rdtsc();

    /*
     * For LVT Timer clock, SDM vol 3 10.5.4 says it should be
     * derived from processor's bus clock (IIUC which is the same
     * as TSC), however QEMU seems to be using nanosecond. In all
     * cases, the following should satisfy on all modern
     * processors.
     */
    report("APIC LVT timer one shot", (lvtt_counter == 1) &&
           (tsc2 - tsc1 >= interval));
}

static atomic_t broadcast_counter;

static void broadcast_handler(isr_regs_t *regs)
{
	atomic_inc(&broadcast_counter);
	eoi();
}

static bool broadcast_received(unsigned ncpus)
{
	unsigned counter;
	u64 start = rdtsc();

	do {
		counter = atomic_read(&broadcast_counter);
		if (counter >= ncpus)
			break;
		pause();
	} while (rdtsc() - start < 1000000000);

	atomic_set(&broadcast_counter, 0);

	return counter == ncpus;
}

static void test_physical_broadcast(void)
{
	unsigned ncpus = cpu_count();
	unsigned long cr3 = read_cr3();
	u32 broadcast_address = enable_x2apic() ? 0xffffffff : 0xff;

	handle_irq(BROADCAST_VECTOR, broadcast_handler);
	for (int c = 1; c < ncpus; c++)
		on_cpu(c, update_cr3, (void *)cr3);

	printf("starting broadcast (%s)\n", enable_x2apic() ? "x2apic" : "xapic");
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_FIXED | APIC_INT_ASSERT |
			BROADCAST_VECTOR, broadcast_address);
	report("APIC physical broadcast address", broadcast_received(ncpus));

	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_FIXED | APIC_INT_ASSERT |
			BROADCAST_VECTOR | APIC_DEST_ALLINC, 0);
	report("APIC physical broadcast shorthand", broadcast_received(ncpus));
}

int main()
{
    setup_vm();
    smp_init();

    test_lapic_existence();

    mask_pic_interrupts();
    test_apic_id();
    test_apic_disable();

    // Disabled in v86: Not supported
    //test_enable_x2apic();
    if(false) test_apicbase();

    test_self_ipi();
    test_physical_broadcast();

    test_sti_nmi();
    test_multiple_nmi();

    test_apic_timer_one_shot();
    test_tsc_deadline_timer();

    return report_summary();
}
                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/x86/asyncpf.c                                                       0000644 0000000 0000000 00000005175 00000000000 016204  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Async PF test. For the test to actually do anything it needs to be started
 * in memory cgroup with 512M of memory and with more then 1G memory provided
 * to the guest.
 *
 * To create cgroup do as root:
 * mkdir /dev/cgroup
 * mount -t cgroup none -omemory /dev/cgroup
 * chmod a+rxw /dev/cgroup/
 *
 * From a shell you will start qemu from:
 * mkdir /dev/cgroup/1
 * echo $$ >  /dev/cgroup/1/tasks
 * echo 512M > /dev/cgroup/1/memory.limit_in_bytes
 *
 */
#include "x86/msr.h"
#include "x86/processor.h"
#include "x86/apic-defs.h"
#include "x86/apic.h"
#include "x86/desc.h"
#include "x86/isr.h"
#include "x86/vm.h"

#include "libcflat.h"
#include <stdint.h>

#define KVM_PV_REASON_PAGE_NOT_PRESENT 1
#define KVM_PV_REASON_PAGE_READY 2

#define MSR_KVM_ASYNC_PF_EN 0x4b564d02

#define KVM_ASYNC_PF_ENABLED                    (1 << 0)
#define KVM_ASYNC_PF_SEND_ALWAYS                (1 << 1)

volatile uint32_t apf_reason __attribute__((aligned(64)));
char *buf;
volatile uint64_t  i;
volatile uint64_t phys;

static inline uint32_t get_apf_reason(void)
{
	uint32_t r = apf_reason;
	apf_reason = 0;
	return r;
}

static void pf_isr(struct ex_regs *r)
{
	void* virt = (void*)((ulong)(buf+i) & ~(PAGE_SIZE-1));
	uint32_t reason = get_apf_reason();

	switch (reason) {
		case 0:
			report("unexpected #PF at %#lx", false, read_cr2());
			break;
		case KVM_PV_REASON_PAGE_NOT_PRESENT:
			phys = virt_to_phys_cr3(virt);
			install_pte(phys_to_virt(read_cr3()), 1, virt, phys, 0);
			write_cr3(read_cr3());
			report("Got not present #PF token %lx virt addr %p phys addr %#" PRIx64,
					true, read_cr2(), virt, phys);
			while(phys) {
				safe_halt(); /* enables irq */
				irq_disable();
			}
			break;
		case KVM_PV_REASON_PAGE_READY:
			report("Got present #PF token %lx", true, read_cr2());
			if ((uint32_t)read_cr2() == ~0)
				break;
			install_pte(phys_to_virt(read_cr3()), 1, virt, phys | PT_PRESENT_MASK | PT_WRITABLE_MASK, 0);
			write_cr3(read_cr3());
			phys = 0;
			break;
		default:
			report("unexpected async pf reason %d", false, reason);
			break;
	}
}

#define MEM 1ull*1024*1024*1024

int main(int ac, char **av)
{
	int loop = 2;

	setup_vm();
	setup_idt();
	printf("install handler\n");
	handle_exception(14, pf_isr);
	apf_reason = 0;
	printf("enable async pf\n");
	wrmsr(MSR_KVM_ASYNC_PF_EN, virt_to_phys((void*)&apf_reason) |
			KVM_ASYNC_PF_SEND_ALWAYS | KVM_ASYNC_PF_ENABLED);
	printf("alloc memory\n");
	buf = vmalloc(MEM);
	irq_enable();
	while(loop--) {
		printf("start loop\n");
		/* access a lot of memory to make host swap it out */
		for (i=0; i < MEM; i+=4096)
			buf[i] = 1;
		printf("end loop\n");
	}
	irq_disable();

	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/x86/cmpxchg8b.c                                                     0000644 0000000 0000000 00000001052 00000000000 016412  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "ioram.h"
#include "vm.h"
#include "libcflat.h"
#include "desc.h"
#include "types.h"
#include "processor.h"

static void test_cmpxchg8b(u32 *mem)
{
    mem[1] = 2;
    mem[0] = 1;
    asm("push %%ebx\n"
        "mov %[ebx_val], %%ebx\n"
        "lock cmpxchg8b (%0)\n"
        "pop %%ebx" : : "D" (mem),
        "d" (2), "a" (1), "c" (4), [ebx_val] "i" (3) : "memory");
    report("cmpxchg8b", mem[0] == 3 && mem[1] == 4);
}

int main()
{
	setup_vm();
	setup_idt();

	test_cmpxchg8b(phys_to_virt(read_cr3()) + 4088);
	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/x86/cstart.S                                                        0000644 0000000 0000000 00000007077 00000000000 016024  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "apic-defs.h"

.globl boot_idt
boot_idt = 0

ipi_vector = 0x20

max_cpus = 64

.bss

	. = . + 4096 * max_cpus
	.align 16
stacktop:

	. = . + 4096
	.align 16
ring0stacktop:

.data

.align 4096
pt:
i = 0
        .rept 1024
        .long 0x1e7 | (i << 22)
        i = i + 1
        .endr

.globl gdt32
gdt32:
	.quad 0
	.quad 0x00cf9b000000ffff // flat 32-bit code segment
	.quad 0x00cf93000000ffff // flat 32-bit data segment
	.quad 0x00cf1b000000ffff // flat 32-bit code segment, not present
	.quad 0                  // TSS for task gates
	.quad 0x008f9b000000FFFF // 16-bit code segment
	.quad 0x008f93000000FFFF // 16-bit data segment
	.quad 0x00cffb000000ffff // 32-bit code segment (user)
	.quad 0x00cff3000000ffff // 32-bit data segment (user)
	.quad 0                  // unused

	.quad 0			 // 6 spare selectors
	.quad 0
	.quad 0
	.quad 0
	.quad 0
	.quad 0

tss_descr:
        .rept max_cpus
        .quad 0x000089000000ffff // 32-bit avail tss
        .endr
gdt32_end:

i = 0
.globl tss
tss:
        .rept max_cpus
        .long 0
        .long ring0stacktop - i * 4096
        .long 16
        .quad 0, 0
        .quad 0, 0, 0, 0, 0, 0, 0, 0
        .long 0, 0, 0
        i = i + 1
        .endr
tss_end:

idt_descr:
	.word 16 * 256 - 1
	.long boot_idt

.section .init

.code32

mb_magic = 0x1BADB002
mb_flags = 0x0

	# multiboot header
	.long mb_magic, mb_flags, 0 - (mb_magic + mb_flags)
mb_cmdline = 16

MSR_GS_BASE = 0xc0000101

.macro setup_percpu_area
	lea -4096(%esp), %eax
	mov $0, %edx
	mov $MSR_GS_BASE, %ecx
	wrmsr
.endm

.globl start
start:
        push %ebx
        call setup_get_initrd
        call setup_environ
        mov mb_cmdline(%ebx), %eax
        mov %eax, __args
        call __setup_args
        mov $stacktop, %esp
        setup_percpu_area
        call prepare_32
        jmpl $8, $start32

prepare_32:
        lgdtl gdt32_descr

	mov %cr4, %eax
	bts $4, %eax  // pse
	mov %eax, %cr4

	mov $pt, %eax
	mov %eax, %cr3

	mov %cr0, %eax
	bts $0, %eax
	bts $31, %eax
	mov %eax, %cr0
	ret

smp_stacktop:	.long 0xa0000

ap_start32:
	mov $0x10, %ax
	mov %ax, %ds
	mov %ax, %es
	mov %ax, %fs
	mov %ax, %gs
	mov %ax, %ss
	mov $-4096, %esp
	lock/xaddl %esp, smp_stacktop
	setup_percpu_area
	call prepare_32
	call load_tss
	call enable_apic
	call enable_x2apic
	sti
	nop
	lock incw cpu_online_count

1:	hlt
	jmp 1b

start32:
	call load_tss
	call mask_pic_interrupts
	call enable_apic
	call smp_init
	call enable_x2apic
        push $__environ
        push $__argv
        push __argc
        call main
	push %eax
	call exit

load_tss:
	lidt idt_descr
	mov $16, %eax
	mov %ax, %ss
	mov $(APIC_DEFAULT_PHYS_BASE + APIC_ID), %eax
	mov (%eax), %eax
	shr $24, %eax
	mov %eax, %ebx
	shl $3, %ebx
	mov $((tss_end - tss) / max_cpus), %edx
	imul %edx
	add $tss, %eax
	mov %ax, tss_descr+2(%ebx)
	shr $16, %eax
	mov %al, tss_descr+4(%ebx)
	shr $8, %eax
	mov %al, tss_descr+7(%ebx)
	lea tss_descr-gdt32(%ebx), %eax
	ltr %ax
	ret

smp_init:
	cld
	lea sipi_entry, %esi
	xor %edi, %edi
	mov $(sipi_end - sipi_entry), %ecx
	rep/movsb
	mov $APIC_DEFAULT_PHYS_BASE, %eax
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT), APIC_ICR(%eax)
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_INIT), APIC_ICR(%eax)
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_STARTUP), APIC_ICR(%eax)
	call fwcfg_get_nb_cpus
1:	pause
	cmpw %ax, cpu_online_count
	jne 1b
smp_init_done:
	ret

cpu_online_count:	.word 1

.code16
sipi_entry:
	mov %cr0, %eax
	or $1, %eax
	mov %eax, %cr0
	lgdtl gdt32_descr - sipi_entry
	ljmpl $8, $ap_start32

gdt32_descr:
	.word gdt32_end - gdt32 - 1
	.long gdt32

sipi_end:
                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/kvm-unit-tests/x86/cstart64.S                                                      0000644 0000000 0000000 00000010103 00000000000 016156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "apic-defs.h"

.globl boot_idt
boot_idt = 0

.globl idt_descr
.globl tss_descr
.globl gdt64_desc

ipi_vector = 0x20

max_cpus = 64

.bss

	. = . + 4096 * max_cpus
	.align 16
stacktop:

	. = . + 4096
	.align 16
ring0stacktop:

.data

.align 4096
.globl ptl2
ptl2:
i = 0
	.rept 512 * 4
	.quad 0x1e7 | (i << 21)
	i = i + 1
	.endr

.align 4096
ptl3:
	.quad ptl2 + 7 + 0 * 4096
	.quad ptl2 + 7 + 1 * 4096
	.quad ptl2 + 7 + 2 * 4096
	.quad ptl2 + 7 + 3 * 4096

.align 4096
ptl4:
	.quad ptl3 + 7

.align 4096

gdt64_desc:
	.word gdt64_end - gdt64 - 1
	.quad gdt64

gdt64:
	.quad 0
	.quad 0x00af9b000000ffff // 64-bit code segment
	.quad 0x00cf93000000ffff // 32/64-bit data segment
	.quad 0x00af1b000000ffff // 64-bit code segment, not present
	.quad 0x00cf9b000000ffff // 32-bit code segment
	.quad 0x008f9b000000FFFF // 16-bit code segment
	.quad 0x008f93000000FFFF // 16-bit data segment
	.quad 0x00cffb000000ffff // 32-bit code segment (user)
	.quad 0x00cff3000000ffff // 32/64-bit data segment (user)
	.quad 0x00affb000000ffff // 64-bit code segment (user)

	.quad 0			 // 6 spare selectors
	.quad 0
	.quad 0
	.quad 0
	.quad 0
	.quad 0

tss_descr:
	.rept max_cpus
	.quad 0x000089000000ffff // 64-bit avail tss
	.quad 0                  // tss high addr
	.endr
gdt64_end:

i = 0
.globl tss
tss:
	.rept max_cpus
	.long 0
	.quad ring0stacktop - i * 4096
	.quad 0, 0
	.quad 0, 0, 0, 0, 0, 0, 0, 0
	.long 0, 0, 0
i = i + 1
	.endr
tss_end:

mb_boot_info:	.quad 0

.section .init

.code32

mb_magic = 0x1BADB002
mb_flags = 0x0

	# multiboot header
	.long mb_magic, mb_flags, 0 - (mb_magic + mb_flags)
mb_cmdline = 16

MSR_GS_BASE = 0xc0000101

.macro setup_percpu_area
	lea -4096(%esp), %eax
	mov $0, %edx
	mov $MSR_GS_BASE, %ecx
	wrmsr
.endm

.globl start
start:
	mov %ebx, mb_boot_info
	mov $stacktop, %esp
	setup_percpu_area
	call prepare_64
	jmpl $8, $start64

prepare_64:
	lgdt gdt64_desc

	mov %cr4, %eax
	bts $5, %eax  // pae
	mov %eax, %cr4

	mov $ptl4, %eax
	mov %eax, %cr3

efer = 0xc0000080
	mov $efer, %ecx
	rdmsr
	bts $8, %eax
	wrmsr

	mov %cr0, %eax
	bts $0, %eax
	bts $31, %eax
	mov %eax, %cr0
	ret

smp_stacktop:	.long 0xa0000

.align 16

gdt32:
	.quad 0
	.quad 0x00cf9b000000ffff // flat 32-bit code segment
	.quad 0x00cf93000000ffff // flat 32-bit data segment
gdt32_end:

.code16
sipi_entry:
	mov %cr0, %eax
	or $1, %eax
	mov %eax, %cr0
	lgdtl gdt32_descr - sipi_entry
	ljmpl $8, $ap_start32

gdt32_descr:
	.word gdt32_end - gdt32 - 1
	.long gdt32

sipi_end:

.code32
ap_start32:
	mov $0x10, %ax
	mov %ax, %ds
	mov %ax, %es
	mov %ax, %fs
	mov %ax, %gs
	mov %ax, %ss
	mov $-4096, %esp
	lock/xaddl %esp, smp_stacktop
	setup_percpu_area
	call prepare_64
	ljmpl $8, $ap_start64

.code64
ap_start64:
	call load_tss
	call enable_apic
	call enable_x2apic
	sti
	nop
	lock incw cpu_online_count

1:	hlt
	jmp 1b

start64:
	call load_tss
	call mask_pic_interrupts
	call enable_apic
	call smp_init
	call enable_x2apic
	mov mb_boot_info(%rip), %rbx
	mov %rbx, %rdi
	call setup_get_initrd
	call setup_environ
	mov mb_cmdline(%rbx), %eax
	mov %rax, __args(%rip)
	call __setup_args
	mov __argc(%rip), %edi
	lea __argv(%rip), %rsi
	lea __environ(%rip), %rdx
	call main
	mov %eax, %edi
	call exit

idt_descr:
	.word 16 * 256 - 1
	.quad boot_idt

load_tss:
	lidtq idt_descr
	mov $(APIC_DEFAULT_PHYS_BASE + APIC_ID), %eax
	mov (%rax), %eax
	shr $24, %eax
	mov %eax, %ebx
	shl $4, %ebx
	mov $((tss_end - tss) / max_cpus), %edx
	imul %edx
	add $tss, %rax
	mov %ax, tss_descr+2(%rbx)
	shr $16, %rax
	mov %al, tss_descr+4(%rbx)
	shr $8, %rax
	mov %al, tss_descr+7(%rbx)
	shr $8, %rax
	mov %eax, tss_descr+8(%rbx)
	lea tss_descr-gdt64(%rbx), %rax
	ltr %ax
	ret

smp_init:
	cld
	lea sipi_entry, %rsi
	xor %rdi, %rdi
	mov $(sipi_end - sipi_entry), %rcx
	rep/movsb
	mov $APIC_DEFAULT_PHYS_BASE, %eax
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT), APIC_ICR(%rax)
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_INIT), APIC_ICR(%rax)
	movl $(APIC_DEST_ALLBUT | APIC_DEST_PHYSICAL | APIC_DM_STARTUP), APIC_ICR(%rax)
	call fwcfg_get_nb_cpus
1:	pause
	cmpw %ax, cpu_online_count
	jne 1b
smp_init_done:
	ret

cpu_online_count:	.word 1
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/x86/debug.c                                                         0000644 0000000 0000000 00000007760 00000000000 015631  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Test for x86 debugging facilities
 *
 * Copyright (c) Siemens AG, 2014
 *
 * Authors:
 *  Jan Kiszka <jan.kiszka@siemens.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */

#include "libcflat.h"
#include "desc.h"

static volatile unsigned long bp_addr[10], dr6[10];
static volatile unsigned int n;
static volatile unsigned long value;

static unsigned long get_dr6(void)
{
	unsigned long value;

	asm volatile("mov %%dr6,%0" : "=r" (value));
	return value;
}

static void set_dr0(void *value)
{
	asm volatile("mov %0,%%dr0" : : "r" (value));
}

static void set_dr1(void *value)
{
	asm volatile("mov %0,%%dr1" : : "r" (value));
}

static void set_dr6(unsigned long value)
{
	asm volatile("mov %0,%%dr6" : : "r" (value));
}

static void set_dr7(unsigned long value)
{
	asm volatile("mov %0,%%dr7" : : "r" (value));
}

static void handle_db(struct ex_regs *regs)
{
	bp_addr[n] = regs->rip;
	dr6[n] = get_dr6();

	if (dr6[n] & 0x1)
		regs->rflags |= (1 << 16);

	if (++n >= 10) {
		regs->rflags &= ~(1 << 8);
		set_dr7(0x00000400);
	}
}

static void handle_bp(struct ex_regs *regs)
{
	bp_addr[0] = regs->rip;
}

int main(int ac, char **av)
{
	unsigned long start;

	setup_idt();
	handle_exception(DB_VECTOR, handle_db);
	handle_exception(BP_VECTOR, handle_bp);

sw_bp:
	asm volatile("int3");
	report("#BP", bp_addr[0] == (unsigned long)&&sw_bp + 1);

	n = 0;
	set_dr0(&&hw_bp1);
	set_dr7(0x00000402);
hw_bp1:
	asm volatile("nop");
	report("hw breakpoint (test that dr6.BS is not set)",
	       n == 1 &&
	       bp_addr[0] == ((unsigned long)&&hw_bp1) && dr6[0] == 0xffff0ff1);

	n = 0;
	set_dr0(&&hw_bp2);
	set_dr6(0x00004002);
hw_bp2:
	asm volatile("nop");
	report("hw breakpoint (test that dr6.BS is not cleared)",
	       n == 1 &&
	       bp_addr[0] == ((unsigned long)&&hw_bp2) && dr6[0] == 0xffff4ff1);

	n = 0;
	set_dr6(0);
	asm volatile(
		"pushf\n\t"
		"pop %%rax\n\t"
		"or $(1<<8),%%rax\n\t"
		"push %%rax\n\t"
		"lea (%%rip),%0\n\t"
		"popf\n\t"
		"and $~(1<<8),%%rax\n\t"
		"push %%rax\n\t"
		"popf\n\t"
		: "=g" (start) : : "rax");
	report("single step",
	       n == 3 &&
	       bp_addr[0] == start+1+6 && dr6[0] == 0xffff4ff0 &&
	       bp_addr[1] == start+1+6+1 && dr6[1] == 0xffff4ff0 &&
	       bp_addr[2] == start+1+6+1+1 && dr6[2] == 0xffff4ff0);

	/*
	 * cpuid and rdmsr (among others) trigger VM exits and are then
	 * emulated. Test that single stepping works on emulated instructions.
	 */
	n = 0;
	set_dr6(0);
	asm volatile(
		"pushf\n\t"
		"pop %%rax\n\t"
		"or $(1<<8),%%rax\n\t"
		"push %%rax\n\t"
		"lea (%%rip),%0\n\t"
		"popf\n\t"
		"and $~(1<<8),%%rax\n\t"
		"push %%rax\n\t"
		"xor %%rax,%%rax\n\t"
		"cpuid\n\t"
		"movl $0x1a0,%%ecx\n\t"
		"rdmsr\n\t"
		"popf\n\t"
		: "=g" (start) : : "rax", "ebx", "ecx", "edx");
	report("single step emulated instructions",
	       n == 7 &&
	       bp_addr[0] == start+1+6 && dr6[0] == 0xffff4ff0 &&
	       bp_addr[1] == start+1+6+1 && dr6[1] == 0xffff4ff0 &&
	       bp_addr[2] == start+1+6+1+3 && dr6[2] == 0xffff4ff0 &&
	       bp_addr[3] == start+1+6+1+3+2 && dr6[3] == 0xffff4ff0 &&
	       bp_addr[4] == start+1+6+1+3+2+5 && dr6[4] == 0xffff4ff0 &&
	       bp_addr[5] == start+1+6+1+3+2+5+2 && dr6[5] == 0xffff4ff0 &&
	       bp_addr[6] == start+1+6+1+3+2+5+2+1 && dr6[6] == 0xffff4ff0);

	n = 0;
	set_dr1((void *)&value);
	set_dr7(0x00d0040a);

	asm volatile(
		"mov $42,%%rax\n\t"
		"mov %%rax,%0\n\t"
		: "=m" (value) : : "rax");
hw_wp1:
	report("hw watchpoint (test that dr6.BS is not cleared)",
	       n == 1 &&
	       bp_addr[0] == ((unsigned long)&&hw_wp1) && dr6[0] == 0xffff4ff2);

	n = 0;
	set_dr6(0);

	asm volatile(
		"mov $42,%%rax\n\t"
		"mov %%rax,%0\n\t"
		: "=m" (value) : : "rax");
hw_wp2:
	report("hw watchpoint (test that dr6.BS is not set)",
	       n == 1 &&
	       bp_addr[0] == ((unsigned long)&&hw_wp2) && dr6[0] == 0xffff0ff2);

	n = 0;
	set_dr6(0);
sw_icebp:
	asm volatile(".byte 0xf1");
	report("icebp",
	       n == 1 &&
	       bp_addr[0] == (unsigned long)&&sw_icebp + 1 &&
	       dr6[0] == 0xffff0ff0);

	return report_summary();
}
                source/v64/tests/kvm-unit-tests/x86/emulator.c                                                      0000644 0000000 0000000 00000101002 00000000000 016353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "ioram.h"
#include "vm.h"
#include "libcflat.h"
#include "desc.h"
#include "types.h"
#include "processor.h"

#define memset __builtin_memset
#define TESTDEV_IO_PORT 0xe0

static int exceptions;

struct regs {
	u64 rax, rbx, rcx, rdx;
	u64 rsi, rdi, rsp, rbp;
	u64 r8, r9, r10, r11;
	u64 r12, r13, r14, r15;
	u64 rip, rflags;
};
struct regs inregs, outregs, save;

struct insn_desc {
	u64 ptr;
	size_t len;
};

static char st1[] = "abcdefghijklmnop";

void test_stringio()
{
	unsigned char r = 0;
	asm volatile("cld \n\t"
		     "movw %0, %%dx \n\t"
		     "rep outsb \n\t"
		     : : "i"((short)TESTDEV_IO_PORT),
		       "S"(st1), "c"(sizeof(st1) - 1));
	asm volatile("inb %1, %0\n\t" : "=a"(r) : "i"((short)TESTDEV_IO_PORT));
	report("outsb up", r == st1[sizeof(st1) - 2]); /* last char */

	asm volatile("std \n\t"
		     "movw %0, %%dx \n\t"
		     "rep outsb \n\t"
		     : : "i"((short)TESTDEV_IO_PORT),
		       "S"(st1 + sizeof(st1) - 2), "c"(sizeof(st1) - 1));
	asm volatile("cld \n\t" : : );
	asm volatile("in %1, %0\n\t" : "=a"(r) : "i"((short)TESTDEV_IO_PORT));
	report("outsb down", r == st1[0]);
}

void test_cmps_one(unsigned char *m1, unsigned char *m3)
{
	void *rsi, *rdi;
	long rcx, tmp;

	rsi = m1; rdi = m3; rcx = 30;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsb"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsb (1)", rcx == 0 && rsi == m1 + 30 && rdi == m3 + 30);

	rsi = m1; rdi = m3; rcx = 30;
	asm volatile("or $1, %[tmp]\n\t" // clear ZF
		     "repe/cmpsb"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsb (1.zf)", rcx == 0 && rsi == m1 + 30 && rdi == m3 + 30);

	rsi = m1; rdi = m3; rcx = 15;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsw"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsw (1)", rcx == 0 && rsi == m1 + 30 && rdi == m3 + 30);

	rsi = m1; rdi = m3; rcx = 7;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsl"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpll (1)", rcx == 0 && rsi == m1 + 28 && rdi == m3 + 28);

	rsi = m1; rdi = m3; rcx = 4;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsq"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsq (1)", rcx == 0 && rsi == m1 + 32 && rdi == m3 + 32);

	rsi = m1; rdi = m3; rcx = 130;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsb"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsb (2)",
	       rcx == 29 && rsi == m1 + 101 && rdi == m3 + 101);

	rsi = m1; rdi = m3; rcx = 65;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsw"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsw (2)",
	       rcx == 14 && rsi == m1 + 102 && rdi == m3 + 102);

	rsi = m1; rdi = m3; rcx = 32;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsl"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpll (2)",
	       rcx == 6 && rsi == m1 + 104 && rdi == m3 + 104);

	rsi = m1; rdi = m3; rcx = 16;
	asm volatile("xor %[tmp], %[tmp] \n\t"
		     "repe/cmpsq"
		     : "+S"(rsi), "+D"(rdi), "+c"(rcx), [tmp]"=&r"(tmp)
		     : : "cc");
	report("repe/cmpsq (2)",
	       rcx == 3 && rsi == m1 + 104 && rdi == m3 + 104);

}

void test_cmps(void *mem)
{
	unsigned char *m1 = mem, *m2 = mem + 1024;
	unsigned char m3[1024];

	for (int i = 0; i < 100; ++i)
		m1[i] = m2[i] = m3[i] = i;
	for (int i = 100; i < 200; ++i)
		m1[i] = (m3[i] = m2[i] = i) + 1;
	test_cmps_one(m1, m3);
	test_cmps_one(m1, m2);
}

void test_scas(void *mem)
{
    bool z;
    void *di;

    *(ulong *)mem = 0x77665544332211;

    di = mem;
    asm ("scasb; setz %0" : "=rm"(z), "+D"(di) : "a"(0xff11));
    report("scasb match", di == mem + 1 && z);

    di = mem;
    asm ("scasb; setz %0" : "=rm"(z), "+D"(di) : "a"(0xff54));
    report("scasb mismatch", di == mem + 1 && !z);

    di = mem;
    asm ("scasw; setz %0" : "=rm"(z), "+D"(di) : "a"(0xff2211));
    report("scasw match", di == mem + 2 && z);

    di = mem;
    asm ("scasw; setz %0" : "=rm"(z), "+D"(di) : "a"(0xffdd11));
    report("scasw mismatch", di == mem + 2 && !z);

    di = mem;
    asm ("scasl; setz %0" : "=rm"(z), "+D"(di) : "a"(0xff44332211ul));
    report("scasd match", di == mem + 4 && z);

    di = mem;
    asm ("scasl; setz %0" : "=rm"(z), "+D"(di) : "a"(0x45332211));
    report("scasd mismatch", di == mem + 4 && !z);

    di = mem;
    asm ("scasq; setz %0" : "=rm"(z), "+D"(di) : "a"(0x77665544332211ul));
    report("scasq match", di == mem + 8 && z);

    di = mem;
    asm ("scasq; setz %0" : "=rm"(z), "+D"(di) : "a"(3));
    report("scasq mismatch", di == mem + 8 && !z);
}

void test_cr8(void)
{
	unsigned long src, dst;

	dst = 777;
	src = 3;
	asm volatile("mov %[src], %%cr8; mov %%cr8, %[dst]"
		     : [dst]"+r"(dst), [src]"+r"(src));
	report("mov %%cr8", dst == 3 && src == 3);
}

void test_push(void *mem)
{
	unsigned long tmp;
	unsigned long *stack_top = mem + 4096;
	unsigned long *new_stack_top;
	unsigned long memw = 0x123456789abcdeful;

	memset(mem, 0x55, (void *)stack_top - mem);

	asm volatile("mov %%rsp, %[tmp] \n\t"
		     "mov %[stack_top], %%rsp \n\t"
		     "pushq $-7 \n\t"
		     "pushq %[reg] \n\t"
		     "pushq (%[mem]) \n\t"
		     "pushq $-7070707 \n\t"
		     "mov %%rsp, %[new_stack_top] \n\t"
		     "mov %[tmp], %%rsp"
		     : [tmp]"=&r"(tmp), [new_stack_top]"=r"(new_stack_top)
		     : [stack_top]"r"(stack_top),
		       [reg]"r"(-17l), [mem]"r"(&memw)
		     : "memory");

	report("push $imm8", stack_top[-1] == -7ul);
	report("push %%reg", stack_top[-2] == -17ul);
	report("push mem", stack_top[-3] == 0x123456789abcdeful);
	report("push $imm", stack_top[-4] == -7070707);
}

void test_pop(void *mem)
{
	unsigned long tmp, tmp3, rsp, rbp;
	unsigned long *stack_top = mem + 4096;
	unsigned long memw = 0x123456789abcdeful;
	static unsigned long tmp2;

	memset(mem, 0x55, (void *)stack_top - mem);

	asm volatile("pushq %[val] \n\t"
		     "popq (%[mem])"
		     : : [val]"m"(memw), [mem]"r"(mem) : "memory");
	report("pop mem", *(unsigned long *)mem == memw);

	memw = 7 - memw;
	asm volatile("mov %%rsp, %[tmp] \n\t"
		     "mov %[stack_top], %%rsp \n\t"
		     "pushq %[val] \n\t"
		     "popq %[tmp2] \n\t"
		     "mov %[tmp], %%rsp"
		     : [tmp]"=&r"(tmp), [tmp2]"=m"(tmp2)
		     : [val]"r"(memw), [stack_top]"r"(stack_top)
		     : "memory");
	report("pop mem (2)", tmp2 == memw);

	memw = 129443 - memw;
	asm volatile("mov %%rsp, %[tmp] \n\t"
		     "mov %[stack_top], %%rsp \n\t"
		     "pushq %[val] \n\t"
		     "popq %[tmp2] \n\t"
		     "mov %[tmp], %%rsp"
		     : [tmp]"=&r"(tmp), [tmp2]"=r"(tmp2)
		     : [val]"r"(memw), [stack_top]"r"(stack_top)
		     : "memory");
	report("pop reg", tmp2 == memw);

	asm volatile("mov %%rsp, %[tmp] \n\t"
		     "mov %[stack_top], %%rsp \n\t"
		     "push $1f \n\t"
		     "ret \n\t"
		     "2: jmp 2b \n\t"
		     "1: mov %[tmp], %%rsp"
		     : [tmp]"=&r"(tmp) : [stack_top]"r"(stack_top)
		     : "memory");
	report("ret", 1);

	stack_top[-1] = 0x778899;
	asm volatile("mov %[stack_top], %%r8 \n\t"
		     "mov %%rsp, %%r9 \n\t"
		     "xchg %%rbp, %%r8 \n\t"
		     "leave \n\t"
		     "xchg %%rsp, %%r9 \n\t"
		     "xchg %%rbp, %%r8 \n\t"
		     "mov %%r9, %[tmp] \n\t"
		     "mov %%r8, %[tmp3]"
		     : [tmp]"=&r"(tmp), [tmp3]"=&r"(tmp3) : [stack_top]"r"(stack_top-1)
		     : "memory", "r8", "r9");
	report("leave", tmp == (ulong)stack_top && tmp3 == 0x778899);

	rbp = 0xaa55aa55bb66bb66ULL;
	rsp = (unsigned long)stack_top;
	asm volatile("mov %[rsp], %%r8 \n\t"
		     "mov %[rbp], %%r9 \n\t"
		     "xchg %%rsp, %%r8 \n\t"
		     "xchg %%rbp, %%r9 \n\t"
		     "enter $0x1238, $0 \n\t"
		     "xchg %%rsp, %%r8 \n\t"
		     "xchg %%rbp, %%r9 \n\t"
		     "xchg %%r8, %[rsp] \n\t"
		     "xchg %%r9, %[rbp]"
		     : [rsp]"+a"(rsp), [rbp]"+b"(rbp) : : "memory", "r8", "r9");
	report("enter",
	       rsp == (unsigned long)stack_top - 8 - 0x1238
	       && rbp == (unsigned long)stack_top - 8
	       && stack_top[-1] == 0xaa55aa55bb66bb66ULL);
}

void test_ljmp(void *mem)
{
    unsigned char *m = mem;
    volatile int res = 1;

    *(unsigned long**)m = &&jmpf;
    asm volatile ("data16/mov %%cs, %0":"=m"(*(m + sizeof(unsigned long))));
    asm volatile ("rex64/ljmp *%0"::"m"(*m));
    res = 0;
jmpf:
    report("ljmp", res);
}

void test_incdecnotneg(void *mem)
{
    unsigned long *m = mem, v = 1234;
    unsigned char *mb = mem, vb = 66;

    *m = 0;

    asm volatile ("incl %0":"+m"(*m));
    report("incl",  *m == 1);
    asm volatile ("decl %0":"+m"(*m));
    report("decl",  *m == 0);
    asm volatile ("incb %0":"+m"(*m));
    report("incb",  *m == 1);
    asm volatile ("decb %0":"+m"(*m));
    report("decb",  *m == 0);

    asm volatile ("lock incl %0":"+m"(*m));
    report("lock incl",  *m == 1);
    asm volatile ("lock decl %0":"+m"(*m));
    report("lock decl",  *m == 0);
    asm volatile ("lock incb %0":"+m"(*m));
    report("lock incb",  *m == 1);
    asm volatile ("lock decb %0":"+m"(*m));
    report("lock decb",  *m == 0);

    *m = v;

    asm ("lock negq %0" : "+m"(*m)); v = -v;
    report("lock negl", *m == v);
    asm ("lock notq %0" : "+m"(*m)); v = ~v;
    report("lock notl", *m == v);

    *mb = vb;

    asm ("lock negb %0" : "+m"(*mb)); vb = -vb;
    report("lock negb", *mb == vb);
    asm ("lock notb %0" : "+m"(*mb)); vb = ~vb;
    report("lock notb", *mb == vb);
}

void test_smsw(uint64_t *h_mem)
{
	char mem[16];
	unsigned short msw, msw_orig, *pmsw;
	int i, zero;

	msw_orig = read_cr0();

	asm("smsw %0" : "=r"(msw));
	report("smsw (1)", msw == msw_orig);

	memset(mem, 0, 16);
	pmsw = (void *)mem;
	asm("smsw %0" : "=m"(pmsw[4]));
	zero = 1;
	for (i = 0; i < 8; ++i)
		if (i != 4 && pmsw[i])
			zero = 0;
	report("smsw (2)", msw == pmsw[4] && zero);

	/* Trigger exit on smsw */
	*h_mem = 0x12345678abcdeful;
	asm volatile("smsw %0" : "+m"(*h_mem));
	report("smsw (3)", msw == (unsigned short)*h_mem &&
		(*h_mem & ~0xfffful) == 0x12345678ab0000ul);
}

void test_lmsw(void)
{
	char mem[16];
	unsigned short msw, *pmsw;
	unsigned long cr0;

	cr0 = read_cr0();

	msw = cr0 ^ 8;
	asm("lmsw %0" : : "r"(msw));
	printf("before %lx after %lx\n", cr0, read_cr0());
	report("lmsw (1)", (cr0 ^ read_cr0()) == 8);

	pmsw = (void *)mem;
	*pmsw = cr0;
	asm("lmsw %0" : : "m"(*pmsw));
	printf("before %lx after %lx\n", cr0, read_cr0());
	report("lmsw (2)", cr0 == read_cr0());

	/* lmsw can't clear cr0.pe */
	msw = (cr0 & ~1ul) ^ 4;  /* change EM to force trap */
	asm("lmsw %0" : : "r"(msw));
	report("lmsw (3)", (cr0 ^ read_cr0()) == 4 && (cr0 & 1));

	/* back to normal */
	msw = cr0;
	asm("lmsw %0" : : "r"(msw));
}

void test_xchg(void *mem)
{
	unsigned long *memq = mem;
	unsigned long rax;

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xchg %%al, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xchg reg, r/m (1)",
	       rax == 0xfedcba98765432ef && *memq == 0x123456789abcd10);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xchg %%ax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xchg reg, r/m (2)",
	       rax == 0xfedcba987654cdef && *memq == 0x123456789ab3210);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xchg %%eax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xchg reg, r/m (3)",
	       rax == 0x89abcdef && *memq == 0x123456776543210);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xchg %%rax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xchg reg, r/m (4)",
	       rax == 0x123456789abcdef && *memq == 0xfedcba9876543210);
}

void test_xadd(void *mem)
{
	unsigned long *memq = mem;
	unsigned long rax;

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xadd %%al, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xadd reg, r/m (1)",
	       rax == 0xfedcba98765432ef && *memq == 0x123456789abcdff);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xadd %%ax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xadd reg, r/m (2)",
	       rax == 0xfedcba987654cdef && *memq == 0x123456789abffff);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xadd %%eax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xadd reg, r/m (3)",
	       rax == 0x89abcdef && *memq == 0x1234567ffffffff);

	asm volatile("mov $0x123456789abcdef, %%rax\n\t"
		     "mov %%rax, (%[memq])\n\t"
		     "mov $0xfedcba9876543210, %%rax\n\t"
		     "xadd %%rax, (%[memq])\n\t"
		     "mov %%rax, %[rax]\n\t"
		     : [rax]"=r"(rax)
		     : [memq]"r"(memq)
		     : "memory", "rax");
	report("xadd reg, r/m (4)",
	       rax == 0x123456789abcdef && *memq == 0xffffffffffffffff);
}

void test_btc(void *mem)
{
	unsigned int *a = mem;

	memset(mem, 0, 4 * sizeof(unsigned int));

	asm ("btcl $32, %0" :: "m"(a[0]) : "memory");
	asm ("btcl $1, %0" :: "m"(a[1]) : "memory");
	asm ("btcl %1, %0" :: "m"(a[0]), "r"(66) : "memory");
	report("btcl imm8, r/m", a[0] == 1 && a[1] == 2 && a[2] == 4);

	asm ("btcl %1, %0" :: "m"(a[3]), "r"(-1) : "memory");
	report("btcl reg, r/m", a[0] == 1 && a[1] == 2 && a[2] == 0x80000004);

	asm ("btcq %1, %0" : : "m"(a[2]), "r"(-1l) : "memory");
	report("btcq reg, r/m", a[0] == 1 && a[1] == 0x80000002 &&
		a[2] == 0x80000004 && a[3] == 0);
}

void test_bsfbsr(void *mem)
{
	unsigned long rax, *memq = mem;
	unsigned eax, *meml = mem;
	unsigned short ax, *memw = mem;
	unsigned char z;

	*memw = 0xc000;
	asm("bsfw %[mem], %[a]" : [a]"=a"(ax) : [mem]"m"(*memw));
	report("bsfw r/m, reg", ax == 14);

	*meml = 0xc0000000;
	asm("bsfl %[mem], %[a]" : [a]"=a"(eax) : [mem]"m"(*meml));
	report("bsfl r/m, reg", eax == 30);

	*memq = 0xc00000000000;
	asm("bsfq %[mem], %[a]" : [a]"=a"(rax) : [mem]"m"(*memq));
	report("bsfq r/m, reg", rax == 46);

	*memq = 0;
	asm("bsfq %[mem], %[a]; setz %[z]"
	    : [a]"=a"(rax), [z]"=rm"(z) : [mem]"m"(*memq));
	report("bsfq r/m, reg", z == 1);

	*memw = 0xc000;
	asm("bsrw %[mem], %[a]" : [a]"=a"(ax) : [mem]"m"(*memw));
	report("bsrw r/m, reg", ax == 15);

	*meml = 0xc0000000;
	asm("bsrl %[mem], %[a]" : [a]"=a"(eax) : [mem]"m"(*meml));
	report("bsrl r/m, reg", eax == 31);

	*memq = 0xc00000000000;
	asm("bsrq %[mem], %[a]" : [a]"=a"(rax) : [mem]"m"(*memq));
	report("bsrq r/m, reg", rax == 47);

	*memq = 0;
	asm("bsrq %[mem], %[a]; setz %[z]"
	    : [a]"=a"(rax), [z]"=rm"(z) : [mem]"m"(*memq));
	report("bsrq r/m, reg", z == 1);
}

static void test_imul(ulong *mem)
{
    ulong a;

    *mem = 51; a = 0x1234567812345678UL;
    asm ("imulw %1, %%ax" : "+a"(a) : "m"(*mem));
    report("imul ax, mem", a == 0x12345678123439e8);

    *mem = 51; a = 0x1234567812345678UL;
    asm ("imull %1, %%eax" : "+a"(a) : "m"(*mem));
    report("imul eax, mem", a == 0xa06d39e8);

    *mem = 51; a = 0x1234567812345678UL;
    asm ("imulq %1, %%rax" : "+a"(a) : "m"(*mem));
    report("imul rax, mem", a == 0xA06D39EBA06D39E8UL);

    *mem  = 0x1234567812345678UL; a = 0x8765432187654321L;
    asm ("imulw $51, %1, %%ax" : "+a"(a) : "m"(*mem));
    report("imul ax, mem, imm8", a == 0x87654321876539e8);

    *mem = 0x1234567812345678UL;
    asm ("imull $51, %1, %%eax" : "+a"(a) : "m"(*mem));
    report("imul eax, mem, imm8", a == 0xa06d39e8);

    *mem = 0x1234567812345678UL;
    asm ("imulq $51, %1, %%rax" : "+a"(a) : "m"(*mem));
    report("imul rax, mem, imm8", a == 0xA06D39EBA06D39E8UL);

    *mem  = 0x1234567812345678UL; a = 0x8765432187654321L;
    asm ("imulw $311, %1, %%ax" : "+a"(a) : "m"(*mem));
    report("imul ax, mem, imm", a == 0x8765432187650bc8);

    *mem = 0x1234567812345678UL;
    asm ("imull $311, %1, %%eax" : "+a"(a) : "m"(*mem));
    report("imul eax, mem, imm", a == 0x1d950bc8);

    *mem = 0x1234567812345678UL;
    asm ("imulq $311, %1, %%rax" : "+a"(a) : "m"(*mem));
    report("imul rax, mem, imm", a == 0x1D950BDE1D950BC8L);
}

static void test_muldiv(long *mem)
{
    long a, d, aa, dd;
    u8 ex = 1;

    *mem = 0; a = 1; d = 2;
    asm (ASM_TRY("1f") "divq %3; movb $0, %2; 1:"
	 : "+a"(a), "+d"(d), "+q"(ex) : "m"(*mem));
    report("divq (fault)", a == 1 && d == 2 && ex);

    *mem = 987654321098765UL; a = 123456789012345UL; d = 123456789012345UL;
    asm (ASM_TRY("1f") "divq %3; movb $0, %2; 1:"
	 : "+a"(a), "+d"(d), "+q"(ex) : "m"(*mem));
    report("divq (1)",
	   a == 0x1ffffffb1b963b33ul && d == 0x273ba4384ede2ul && !ex);
    aa = 0x1111111111111111; dd = 0x2222222222222222;
    *mem = 0x3333333333333333; a = aa; d = dd;
    asm("mulb %2" : "+a"(a), "+d"(d) : "m"(*mem));
    report("mulb mem", a == 0x1111111111110363 && d == dd);
    *mem = 0x3333333333333333; a = aa; d = dd;
    asm("mulw %2" : "+a"(a), "+d"(d) : "m"(*mem));
    report("mulw mem", a == 0x111111111111c963 && d == 0x2222222222220369);
    *mem = 0x3333333333333333; a = aa; d = dd;
    asm("mull %2" : "+a"(a), "+d"(d) : "m"(*mem));
    report("mull mem", a == 0x962fc963 && d == 0x369d036);
    *mem = 0x3333333333333333; a = aa; d = dd;
    asm("mulq %2" : "+a"(a), "+d"(d) : "m"(*mem));
    report("mulq mem", a == 0x2fc962fc962fc963 && d == 0x369d0369d0369d0);
}

typedef unsigned __attribute__((vector_size(16))) sse128;

typedef union {
    sse128 sse;
    unsigned u[4];
} sse_union;

static bool sseeq(sse_union *v1, sse_union *v2)
{
    bool ok = true;
    int i;

    for (i = 0; i < 4; ++i) {
	ok &= v1->u[i] == v2->u[i];
    }

    return ok;
}

static void test_sse(sse_union *mem)
{
    sse_union v;

    write_cr0(read_cr0() & ~6); /* EM, TS */
    write_cr4(read_cr4() | 0x200); /* OSFXSR */
    v.u[0] = 1; v.u[1] = 2; v.u[2] = 3; v.u[3] = 4;
    asm("movdqu %1, %0" : "=m"(*mem) : "x"(v.sse));
    report("movdqu (read)", sseeq(&v, mem));
    mem->u[0] = 5; mem->u[1] = 6; mem->u[2] = 7; mem->u[3] = 8;
    asm("movdqu %1, %0" : "=x"(v.sse) : "m"(*mem));
    report("movdqu (write)", sseeq(mem, &v));

    v.u[0] = 1; v.u[1] = 2; v.u[2] = 3; v.u[3] = 4;
    asm("movaps %1, %0" : "=m"(*mem) : "x"(v.sse));
    report("movaps (read)", sseeq(mem, &v));
    mem->u[0] = 5; mem->u[1] = 6; mem->u[2] = 7; mem->u[3] = 8;
    asm("movaps %1, %0" : "=x"(v.sse) : "m"(*mem));
    report("movaps (write)", sseeq(&v, mem));

    v.u[0] = 1; v.u[1] = 2; v.u[2] = 3; v.u[3] = 4;
    asm("movapd %1, %0" : "=m"(*mem) : "x"(v.sse));
    report("movapd (read)", sseeq(mem, &v));
    mem->u[0] = 5; mem->u[1] = 6; mem->u[2] = 7; mem->u[3] = 8;
    asm("movapd %1, %0" : "=x"(v.sse) : "m"(*mem));
    report("movapd (write)", sseeq(&v, mem));
}

static void test_mmx(uint64_t *mem)
{
    uint64_t v;

    write_cr0(read_cr0() & ~6); /* EM, TS */
    asm volatile("fninit");
    v = 0x0102030405060708ULL;
    asm("movq %1, %0" : "=m"(*mem) : "y"(v));
    report("movq (mmx, read)", v == *mem);
    *mem = 0x8070605040302010ull;
    asm("movq %1, %0" : "=y"(v) : "m"(*mem));
    report("movq (mmx, write)", v == *mem);
}

static void test_rip_relative(unsigned *mem, char *insn_ram)
{
    /* movb $1, mem+2(%rip) */
    insn_ram[0] = 0xc6;
    insn_ram[1] = 0x05;
    *(unsigned *)&insn_ram[2] = 2 + (char *)mem - (insn_ram + 7);
    insn_ram[6] = 0x01;
    /* ret */
    insn_ram[7] = 0xc3;

    *mem = 0;
    asm("callq *%1" : "+m"(*mem) : "r"(insn_ram));
    report("movb $imm, 0(%%rip)", *mem == 0x10000);
}

static void test_shld_shrd(u32 *mem)
{
    *mem = 0x12345678;
    asm("shld %2, %1, %0" : "+m"(*mem) : "r"(0xaaaaaaaaU), "c"((u8)3));
    report("shld (cl)", *mem == ((0x12345678 << 3) | 5));
    *mem = 0x12345678;
    asm("shrd %2, %1, %0" : "+m"(*mem) : "r"(0x55555555U), "c"((u8)3));
    report("shrd (cl)", *mem == ((0x12345678 >> 3) | (5u << 29)));
}

static void test_cmov(u32 *mem)
{
	u64 val;
	*mem = 0xabcdef12u;
	asm ("movq $0x1234567812345678, %%rax\n\t"
	     "cmpl %%eax, %%eax\n\t"
	     "cmovnel (%[mem]), %%eax\n\t"
	     "movq %%rax, %[val]\n\t"
	     : [val]"=r"(val) : [mem]"r"(mem) : "%rax", "cc");
	report("cmovnel", val == 0x12345678ul);
}

#define INSN_XCHG_ALL				\
	"xchg %rax, 0+save \n\t"		\
	"xchg %rbx, 8+save \n\t"		\
	"xchg %rcx, 16+save \n\t"		\
	"xchg %rdx, 24+save \n\t"		\
	"xchg %rsi, 32+save \n\t"		\
	"xchg %rdi, 40+save \n\t"		\
	"xchg %rsp, 48+save \n\t"		\
	"xchg %rbp, 56+save \n\t"		\
	"xchg %r8, 64+save \n\t"		\
	"xchg %r9, 72+save \n\t"		\
	"xchg %r10, 80+save \n\t"		\
	"xchg %r11, 88+save \n\t"		\
	"xchg %r12, 96+save \n\t"		\
	"xchg %r13, 104+save \n\t"		\
	"xchg %r14, 112+save \n\t"		\
	"xchg %r15, 120+save \n\t"

asm(
	".align 4096\n\t"
	"insn_page:\n\t"
	"ret\n\t"
	"pushf\n\t"
	"push 136+save \n\t"
	"popf \n\t"
	INSN_XCHG_ALL
	"test_insn:\n\t"
	"in  (%dx),%al\n\t"
	".skip 31, 0x90\n\t"
	"test_insn_end:\n\t"
	INSN_XCHG_ALL
	"pushf \n\t"
	"pop 136+save \n\t"
	"popf \n\t"
	"ret \n\t"
	"insn_page_end:\n\t"
	".align 4096\n\t"
);

#define MK_INSN(name, str)				\
    asm (						\
	 ".pushsection .data.insn  \n\t"		\
	 "insn_" #name ": \n\t"				\
	 ".quad 1001f, 1002f - 1001f \n\t"		\
	 ".popsection \n\t"				\
	 ".pushsection .text.insn, \"ax\" \n\t"		\
	 "1001: \n\t"					\
	 "insn_code_" #name ": " str " \n\t"		\
	 "1002: \n\t"					\
	 ".popsection"					\
    );							\
    extern struct insn_desc insn_##name;

static void trap_emulator(uint64_t *mem, void *alt_insn_page,
			struct insn_desc *alt_insn)
{
	ulong *cr3 = (ulong *)read_cr3();
	void *insn_ram;
	extern u8 insn_page[], test_insn[];

	insn_ram = vmap(virt_to_phys(insn_page), 4096);
	memcpy(alt_insn_page, insn_page, 4096);
	memcpy(alt_insn_page + (test_insn - insn_page),
			(void *)(alt_insn->ptr), alt_insn->len);
	save = inregs;

	/* Load the code TLB with insn_page, but point the page tables at
	   alt_insn_page (and keep the data TLB clear, for AMD decode assist).
	   This will make the CPU trap on the insn_page instruction but the
	   hypervisor will see alt_insn_page. */
	install_page(cr3, virt_to_phys(insn_page), insn_ram);
	invlpg(insn_ram);
	/* Load code TLB */
	asm volatile("call *%0" : : "r"(insn_ram));
	install_page(cr3, virt_to_phys(alt_insn_page), insn_ram);
	/* Trap, let hypervisor emulate at alt_insn_page */
	asm volatile("call *%0": : "r"(insn_ram+1));

	outregs = save;
}

static unsigned long rip_advance;

static void advance_rip_and_note_exception(struct ex_regs *regs)
{
    ++exceptions;
    regs->rip += rip_advance;
}

static void test_mmx_movq_mf(uint64_t *mem, uint8_t *insn_page,
			     uint8_t *alt_insn_page, void *insn_ram)
{
    uint16_t fcw = 0;  /* all exceptions unmasked */
    /* movq %mm0, (%rax) */
    void *stack = alloc_page();

    write_cr0(read_cr0() & ~6);  /* TS, EM */
    exceptions = 0;
    handle_exception(MF_VECTOR, advance_rip_and_note_exception);
    asm volatile("fninit; fldcw %0" : : "m"(fcw));
    asm volatile("fldz; fldz; fdivp"); /* generate exception */

    MK_INSN(mmx_movq_mf, "movq %mm0, (%rax) \n\t");
    rip_advance = insn_mmx_movq_mf.len;
    inregs = (struct regs){ .rsp=(u64)stack+1024 };
    trap_emulator(mem, alt_insn_page, &insn_mmx_movq_mf);
    /* exit MMX mode */
    asm volatile("fnclex; emms");
    report("movq mmx generates #MF", exceptions == 1);
    handle_exception(MF_VECTOR, 0);
}

static void test_jmp_noncanonical(uint64_t *mem)
{
	extern char nc_jmp_start, nc_jmp_end;

	*mem = 0x1111111111111111ul;

	exceptions = 0;
	rip_advance = &nc_jmp_end - &nc_jmp_start;
	handle_exception(GP_VECTOR, advance_rip_and_note_exception);
	asm volatile ("nc_jmp_start: jmp *%0; nc_jmp_end:" : : "m"(*mem));
	report("jump to non-canonical address", exceptions == 1);
	handle_exception(GP_VECTOR, 0);
}

static void test_movabs(uint64_t *mem, uint8_t *insn_page,
		       uint8_t *alt_insn_page, void *insn_ram)
{
    /* mov $0x9090909090909090, %rcx */
    MK_INSN(movabs, "mov $0x9090909090909090, %rcx\n\t");
    inregs = (struct regs){ 0 };
    trap_emulator(mem, alt_insn_page, &insn_movabs);
    report("64-bit mov imm2", outregs.rcx == 0x9090909090909090);
}

static void test_smsw_reg(uint64_t *mem, uint8_t *insn_page,
		      uint8_t *alt_insn_page, void *insn_ram)
{
	unsigned long cr0 = read_cr0();
	inregs = (struct regs){ .rax = 0x1234567890abcdeful };

	MK_INSN(smsww, "smsww %ax\n\t");
	trap_emulator(mem, alt_insn_page, &insn_smsww);
	report("16-bit smsw reg", (u16)outregs.rax == (u16)cr0 &&
				  outregs.rax >> 16 == inregs.rax >> 16);

	MK_INSN(smswl, "smswl %eax\n\t");
	trap_emulator(mem, alt_insn_page, &insn_smswl);
	report("32-bit smsw reg", outregs.rax == (u32)cr0);

	MK_INSN(smswq, "smswq %rax\n\t");
	trap_emulator(mem, alt_insn_page, &insn_smswq);
	report("64-bit smsw reg", outregs.rax == cr0);
}

static void test_nop(uint64_t *mem, uint8_t *insn_page,
		uint8_t *alt_insn_page, void *insn_ram)
{
	inregs = (struct regs){ .rax = 0x1234567890abcdeful };
	MK_INSN(nop, "nop\n\t");
	trap_emulator(mem, alt_insn_page, &insn_nop);
	report("nop", outregs.rax == inregs.rax);
}

static void test_mov_dr(uint64_t *mem, uint8_t *insn_page,
		uint8_t *alt_insn_page, void *insn_ram)
{
	bool rtm_support = cpuid(7).b & (1 << 11);
	unsigned long dr6_fixed_1 = rtm_support ? 0xfffe0ff0ul : 0xffff0ff0ul;
	inregs = (struct regs){ .rax = 0 };
	MK_INSN(mov_to_dr6, "movq %rax, %dr6\n\t");
	trap_emulator(mem, alt_insn_page, &insn_mov_to_dr6);
	MK_INSN(mov_from_dr6, "movq %dr6, %rax\n\t");
	trap_emulator(mem, alt_insn_page, &insn_mov_from_dr6);
	report("mov_dr6", outregs.rax == dr6_fixed_1);
}

static void test_push16(uint64_t *mem)
{
	uint64_t rsp1, rsp2;
	uint16_t r;

	asm volatile (	"movq %%rsp, %[rsp1]\n\t"
			"pushw %[v]\n\t"
			"popw %[r]\n\t"
			"movq %%rsp, %[rsp2]\n\t"
			"movq %[rsp1], %%rsp\n\t" :
			[rsp1]"=r"(rsp1), [rsp2]"=r"(rsp2), [r]"=r"(r)
			: [v]"m"(*mem) : "memory");
	report("push16", rsp1 == rsp2);
}

static void test_crosspage_mmio(volatile uint8_t *mem)
{
    volatile uint16_t w, *pw;

    pw = (volatile uint16_t *)&mem[4095];
    mem[4095] = 0x99;
    mem[4096] = 0x77;
    asm volatile("mov %1, %0" : "=r"(w) : "m"(*pw) : "memory");
    report("cross-page mmio read", w == 0x7799);
    asm volatile("mov %1, %0" : "=m"(*pw) : "r"((uint16_t)0x88aa));
    report("cross-page mmio write", mem[4095] == 0xaa && mem[4096] == 0x88);
}

static void test_string_io_mmio(volatile uint8_t *mem)
{
	/* Cross MMIO pages.*/
	volatile uint8_t *mmio = mem + 4032;

	asm volatile("outw %%ax, %%dx  \n\t" : : "a"(0x9999), "d"(TESTDEV_IO_PORT));

	asm volatile ("cld; rep insb" : : "d" (TESTDEV_IO_PORT), "D" (mmio), "c" (1024));

	report("string_io_mmio", mmio[1023] == 0x99);
}

/* kvm doesn't allow lidt/lgdt from mmio, so the test is disabled */
#if 0
static void test_lgdt_lidt(volatile uint8_t *mem)
{
    struct descriptor_table_ptr orig, fresh = {};

    sgdt(&orig);
    *(struct descriptor_table_ptr *)mem = (struct descriptor_table_ptr) {
	.limit = 0xf234,
	.base = 0x12345678abcd,
    };
    cli();
    asm volatile("lgdt %0" : : "m"(*(struct descriptor_table_ptr *)mem));
    sgdt(&fresh);
    lgdt(&orig);
    sti();
    report("lgdt (long address)", orig.limit == fresh.limit && orig.base == fresh.base);

    sidt(&orig);
    *(struct descriptor_table_ptr *)mem = (struct descriptor_table_ptr) {
	.limit = 0x432f,
	.base = 0xdbca87654321,
    };
    cli();
    asm volatile("lidt %0" : : "m"(*(struct descriptor_table_ptr *)mem));
    sidt(&fresh);
    lidt(&orig);
    sti();
    report("lidt (long address)", orig.limit == fresh.limit && orig.base == fresh.base);
}
#endif

static void ss_bad_rpl(struct ex_regs *regs)
{
    extern char ss_bad_rpl_cont;

    ++exceptions;
    regs->rip = (ulong)&ss_bad_rpl_cont;
}

static void test_sreg(volatile uint16_t *mem)
{
    u16 ss = read_ss();

    // check for null segment load
    *mem = 0;
    asm volatile("mov %0, %%ss" : : "m"(*mem));
    report("mov null, %%ss", read_ss() == 0);

    // check for exception when ss.rpl != cpl on null segment load
    exceptions = 0;
    handle_exception(GP_VECTOR, ss_bad_rpl);
    *mem = 3;
    asm volatile("mov %0, %%ss; ss_bad_rpl_cont:" : : "m"(*mem));
    report("mov null, %%ss (with ss.rpl != cpl)", exceptions == 1 && read_ss() == 0);
    handle_exception(GP_VECTOR, 0);
    write_ss(ss);
}

/* Broken emulation causes triple fault, which skips the other tests. */
#if 0
static void test_lldt(volatile uint16_t *mem)
{
    u64 gdt[] = { 0, /* null descriptor */
#ifdef __X86_64__
		  0, /* ldt descriptor is 16 bytes in long mode */
#endif
		  0x0000f82000000ffffull /* ldt descriptor */ };
    struct descriptor_table_ptr gdt_ptr = { .limit = sizeof(gdt) - 1,
					    .base = (ulong)&gdt };
    struct descriptor_table_ptr orig_gdt;

    cli();
    sgdt(&orig_gdt);
    lgdt(&gdt_ptr);
    *mem = 0x8;
    asm volatile("lldt %0" : : "m"(*mem));
    lgdt(&orig_gdt);
    sti();
    report("lldt", sldt() == *mem);
}
#endif

static void test_ltr(volatile uint16_t *mem)
{
    struct descriptor_table_ptr gdt_ptr;
    uint64_t *gdt, *trp;
    uint16_t tr = str();
    uint64_t busy_mask = (uint64_t)1 << 41;

    sgdt(&gdt_ptr);
    gdt = (uint64_t *)gdt_ptr.base;
    trp = &gdt[tr >> 3];
    *trp &= ~busy_mask;
    *mem = tr;
    asm volatile("ltr %0" : : "m"(*mem) : "memory");
    report("ltr", str() == tr && (*trp & busy_mask));
}

static void test_simplealu(u32 *mem)
{
    *mem = 0x1234;
    asm("or %1, %0" : "+m"(*mem) : "r"(0x8001));
    report("or", *mem == 0x9235);
    asm("add %1, %0" : "+m"(*mem) : "r"(2));
    report("add", *mem == 0x9237);
    asm("xor %1, %0" : "+m"(*mem) : "r"(0x1111));
    report("xor", *mem == 0x8326);
    asm("sub %1, %0" : "+m"(*mem) : "r"(0x26));
    report("sub", *mem == 0x8300);
    asm("clc; adc %1, %0" : "+m"(*mem) : "r"(0x100));
    report("adc(0)", *mem == 0x8400);
    asm("stc; adc %1, %0" : "+m"(*mem) : "r"(0x100));
    report("adc(0)", *mem == 0x8501);
    asm("clc; sbb %1, %0" : "+m"(*mem) : "r"(0));
    report("sbb(0)", *mem == 0x8501);
    asm("stc; sbb %1, %0" : "+m"(*mem) : "r"(0));
    report("sbb(1)", *mem == 0x8500);
    asm("and %1, %0" : "+m"(*mem) : "r"(0xfe77));
    report("and", *mem == 0x8400);
    asm("test %1, %0" : "+m"(*mem) : "r"(0xf000));
    report("test", *mem == 0x8400);
}

static void illegal_movbe_handler(struct ex_regs *regs)
{
	extern char bad_movbe_cont;

	++exceptions;
	regs->rip = (ulong)&bad_movbe_cont;
}

static void test_illegal_movbe(void)
{
	if (!(cpuid(1).c & (1 << 22))) {
		report_skip("illegal movbe");
		return;
	}

	exceptions = 0;
	handle_exception(UD_VECTOR, illegal_movbe_handler);
	asm volatile(".byte 0x0f; .byte 0x38; .byte 0xf0; .byte 0xc0;\n\t"
		     " bad_movbe_cont:" : : : "rax");
	report("illegal movbe", exceptions == 1);
	handle_exception(UD_VECTOR, 0);
}

int main()
{
	void *mem;
	void *insn_page, *alt_insn_page;
	void *insn_ram;
	unsigned long t1, t2;

	setup_vm();
	setup_idt();
	mem = alloc_vpages(2);
	install_page((void *)read_cr3(), IORAM_BASE_PHYS, mem);
	// install the page twice to test cross-page mmio
	install_page((void *)read_cr3(), IORAM_BASE_PHYS, mem + 4096);
	insn_page = alloc_page();
	alt_insn_page = alloc_page();
	insn_ram = vmap(virt_to_phys(insn_page), 4096);

	// test mov reg, r/m and mov r/m, reg
	t1 = 0x123456789abcdef;
	asm volatile("mov %[t1], (%[mem]) \n\t"
		     "mov (%[mem]), %[t2]"
		     : [t2]"=r"(t2)
		     : [t1]"r"(t1), [mem]"r"(mem)
		     : "memory");
	report("mov reg, r/m (1)", t2 == 0x123456789abcdef);

	test_simplealu(mem);
	test_cmps(mem);
	test_scas(mem);

	test_push(mem);
	test_pop(mem);

	test_xchg(mem);
	test_xadd(mem);

	test_cr8();

	test_smsw(mem);
	test_lmsw();
	test_ljmp(mem);
	test_stringio();
	test_incdecnotneg(mem);
	test_btc(mem);
	test_bsfbsr(mem);
	test_imul(mem);
	test_muldiv(mem);
	test_sse(mem);
	test_mmx(mem);
	test_rip_relative(mem, insn_ram);
	test_shld_shrd(mem);
	//test_lgdt_lidt(mem);
	test_sreg(mem);
	//test_lldt(mem);
	test_ltr(mem);
	test_cmov(mem);

	test_mmx_movq_mf(mem, insn_page, alt_insn_page, insn_ram);
	test_movabs(mem, insn_page, alt_insn_page, insn_ram);
	test_smsw_reg(mem, insn_page, alt_insn_page, insn_ram);
	test_nop(mem, insn_page, alt_insn_page, insn_ram);
	test_mov_dr(mem, insn_page, alt_insn_page, insn_ram);
	test_push16(mem);
	test_crosspage_mmio(mem);

	test_string_io_mmio(mem);

	test_jmp_noncanonical(mem);
	test_illegal_movbe();

	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/x86/eventinj.c                                                      0000644 0000000 0000000 00000024045 00000000000 016360  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "processor.h"
#include "vm.h"
#include "desc.h"
#include "isr.h"
#include "apic.h"
#include "apic-defs.h"

#ifdef __x86_64__
#  define R "r"
#else
#  define R "e"
#endif

static inline void io_delay(void)
{
}

void apic_self_ipi(u8 v)
{
	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL | APIC_DM_FIXED |
		       APIC_INT_ASSERT | v, 0);
}

void apic_self_nmi(void)
{
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, 0);
}

#define flush_phys_addr(__s) outl(__s, 0xe4)
#define flush_stack() do {						\
		int __l;						\
		flush_phys_addr(virt_to_phys(&__l));			\
	} while (0)

extern char isr_iret_ip[];

static void flush_idt_page()
{
	struct descriptor_table_ptr ptr;
	sidt(&ptr);
	flush_phys_addr(virt_to_phys((void*)ptr.base));
}

static volatile unsigned int test_divider;
static volatile int test_count;

ulong stack_phys;
void *stack_va;

void do_pf_tss(void)
{
	printf("PF running\n");
	install_pte(phys_to_virt(read_cr3()), 1, stack_va,
		    stack_phys | PT_PRESENT_MASK | PT_WRITABLE_MASK, 0);
	invlpg(stack_va);
}

extern void pf_tss(void);

asm ("pf_tss: \n\t"
#ifdef __x86_64__
        // no task on x86_64, save/restore caller-save regs
        "push %rax; push %rcx; push %rdx; push %rsi; push %rdi\n"
        "push %r8; push %r9; push %r10; push %r11\n"
#endif
        "call do_pf_tss \n\t"
#ifdef __x86_64__
        "pop %r11; pop %r10; pop %r9; pop %r8\n"
        "pop %rdi; pop %rsi; pop %rdx; pop %rcx; pop %rax\n"
#endif
        "add $"S", %"R "sp\n\t"	// discard error code
        "iret"W" \n\t"
        "jmp pf_tss\n\t"
    );


#ifndef __x86_64__
static void of_isr(struct ex_regs *r)
{
	printf("OF isr running\n");
	test_count++;
}
#endif

static void np_isr(struct ex_regs *r)
{
	printf("NP isr running %lx err=%lx\n", r->rip, r->error_code);
	set_idt_sel(33, read_cs());
	test_count++;
}

static void de_isr(struct ex_regs *r)
{
	printf("DE isr running divider is %d\n", test_divider);
	test_divider = 10;
}

static void bp_isr(struct ex_regs *r)
{
	printf("BP isr running\n");
	test_count++;
}

static void nested_nmi_isr(struct ex_regs *r)
{
	printf("Nested NMI isr running rip=%lx\n", r->rip);

	if (r->rip != (ulong)&isr_iret_ip)
		test_count++;
}
static void nmi_isr(struct ex_regs *r)
{
	printf("NMI isr running %p\n", &isr_iret_ip);
	test_count++;
	handle_exception(2, nested_nmi_isr);
	printf("Sending nested NMI to self\n");
	apic_self_nmi();
	io_delay();
	printf("After nested NMI to self\n");
}

unsigned long *iret_stack;

static void nested_nmi_iret_isr(struct ex_regs *r)
{
	printf("Nested NMI isr running rip=%lx\n", r->rip);

	if (r->rip == iret_stack[-3])
		test_count++;
}

extern void do_iret(ulong phys_stack, void *virt_stack);

// Return to same privilege level won't pop SS or SP, so
// save it in RDX while we run on the nested stack

asm("do_iret:"
#ifdef __x86_64__
	"mov %rdi, %rax \n\t"		// phys_stack
	"mov %rsi, %rdx \n\t"		// virt_stack
#else
	"mov 4(%esp), %eax \n\t"	// phys_stack
	"mov 8(%esp), %edx \n\t"	// virt_stack
#endif
	"xchg %"R "dx, %"R "sp \n\t"	// point to new stack
	"pushf"W" \n\t"
	"mov %cs, %ecx \n\t"
	"push"W" %"R "cx \n\t"
	"push"W" $1f \n\t"
	"outl %eax, $0xe4 \n\t"		// flush page
	"iret"W" \n\t"
	"1: xchg %"R "dx, %"R "sp \n\t"	// point to old stack
	"ret\n\t"
   );

static void nmi_iret_isr(struct ex_regs *r)
{
	unsigned long *s = alloc_page();
	test_count++;
	printf("NMI isr running stack %p\n", s);
	handle_exception(2, nested_nmi_iret_isr);
	printf("Sending nested NMI to self\n");
	apic_self_nmi();
	printf("After nested NMI to self\n");
	iret_stack = &s[128];
	do_iret(virt_to_phys(s), iret_stack);
	printf("After iret\n");
}

static void tirq0(isr_regs_t *r)
{
	printf("irq0 running\n");
	if (test_count == 1)
		test_count++;
	eoi();
}

static void tirq1(isr_regs_t *r)
{
	printf("irq1 running\n");
	test_count++;
	eoi();
}

ulong saved_stack;

#define switch_stack(S) do {						\
		asm volatile ("mov %%" R "sp, %0":"=r"(saved_stack));	\
		asm volatile ("mov %0, %%" R "sp"::"r"(S));		\
	} while(0)

#define restore_stack() do {						\
		asm volatile ("mov %0, %%" R "sp"::"r"(saved_stack));	\
	} while(0)

int main()
{
	unsigned int res;
	ulong *pt, *cr3, i;

	setup_vm();
	setup_idt();
	setup_alt_stack();

	handle_irq(32, tirq0);
	handle_irq(33, tirq1);

	/* generate HW exception that will fault on IDT and stack */
	handle_exception(0, de_isr);
	printf("Try to divide by 0\n");
	flush_idt_page();
	flush_stack();
	asm volatile ("divl %3": "=a"(res)
		      : "d"(0), "a"(1500), "m"(test_divider));
	printf("Result is %d\n", res);
	report("DE exception", res == 150);

	/* generate soft exception (BP) that will fault on IDT and stack */
	test_count = 0;
	handle_exception(3, bp_isr);
	printf("Try int 3\n");
	flush_idt_page();
	flush_stack();
	asm volatile ("int $3");
	printf("After int 3\n");
	report("BP exception", test_count == 1);

#ifndef __x86_64__
	/* generate soft exception (OF) that will fault on IDT */
	test_count = 0;
	handle_exception(4, of_isr);
	flush_idt_page();
	printf("Try into\n");
	asm volatile ("addb $127, %b0\ninto"::"a"(127));
	printf("After into\n");
	report("OF exception", test_count == 1);

	/* generate soft exception (OF) using two bit instruction that will
	   fault on IDT */
	test_count = 0;
	handle_exception(4, of_isr);
	flush_idt_page();
	printf("Try into\n");
	asm volatile ("addb $127, %b0\naddr16 into"::"a"(127));
	printf("After into\n");
	report("2 byte OF exception", test_count == 1);
#endif

	/* generate HW interrupt that will fault on IDT */
	test_count = 0;
	flush_idt_page();
	printf("Sending vec 33 to self\n");
	irq_enable();
	apic_self_ipi(33);
	io_delay();
	irq_disable();
	printf("After vec 33 to self\n");
	report("vec 33", test_count == 1);

	/* generate soft interrupt that will fault on IDT and stack */
	test_count = 0;
	flush_idt_page();
	printf("Try int $33\n");
	flush_stack();
	asm volatile ("int $33");
	printf("After int $33\n");
	report("int $33", test_count == 1);

	/* Inject two HW interrupt than open iterrupt windows. Both interrupt
	   will fault on IDT access */
	test_count = 0;
	flush_idt_page();
	printf("Sending vec 32 and 33 to self\n");
	apic_self_ipi(32);
	apic_self_ipi(33);
	io_delay();
	irq_enable();
	asm volatile("nop");
	irq_disable();
	printf("After vec 32 and 33 to self\n");
	report("vec 32/33", test_count == 2);


	/* Inject HW interrupt, do sti and than (while in irq shadow) inject
	   soft interrupt. Fault during soft interrupt. Soft interrup shoud be
	   handled before HW interrupt */
	test_count = 0;
	flush_idt_page();
	printf("Sending vec 32 and int $33\n");
	apic_self_ipi(32);
	flush_stack();
	io_delay();
	asm volatile ("sti; int $33");
	irq_disable();
	printf("After vec 32 and int $33\n");
	report("vec 32/int $33", test_count == 2);

	/* test that TPR is honored */
	test_count = 0;
	handle_irq(62, tirq1);
	flush_idt_page();
	printf("Sending vec 33 and 62 and mask one with TPR\n");
	apic_write(APIC_TASKPRI, 0xf << 4);
	irq_enable();
	apic_self_ipi(32);
	apic_self_ipi(62);
	io_delay();
	apic_write(APIC_TASKPRI, 0x2 << 4);
	printf("After 33/62 TPR test\n");
	report("TPR", test_count == 1);
	apic_write(APIC_TASKPRI, 0x0);
	while(test_count != 2); /* wait for second irq */
	irq_disable();

	/* test fault durint NP delivery */
	printf("Before NP test\n");
	test_count = 0;
	handle_exception(11, np_isr);
	set_idt_sel(33, NP_SEL);
	flush_idt_page();
	flush_stack();
	asm volatile ("int $33");
	printf("After int33\n");
	report("NP exception", test_count == 2);

	/* generate NMI that will fault on IDT */
	test_count = 0;
	handle_exception(2, nmi_isr);
	flush_idt_page();
	printf("Sending NMI to self\n");
	apic_self_nmi();
	printf("After NMI to self\n");
	/* this is needed on VMX without NMI window notification.
	   Interrupt windows is used instead, so let pending NMI
	   to be injected */
	irq_enable();
	asm volatile ("nop");
	irq_disable();
	report("NMI", test_count == 2);

	/* generate NMI that will fault on IRET */
	printf("Before NMI IRET test\n");
	test_count = 0;
	handle_exception(2, nmi_iret_isr);
	printf("Sending NMI to self\n");
	apic_self_nmi();
	/* this is needed on VMX without NMI window notification.
	   Interrupt windows is used instead, so let pending NMI
	   to be injected */
	irq_enable();
	asm volatile ("nop");
	irq_disable();
	printf("After NMI to self\n");
	report("NMI", test_count == 2);
	stack_phys = (ulong)virt_to_phys(alloc_page());
	stack_va = alloc_vpage();

	/* Generate DE and PF exceptions serially */
	test_divider = 0;
	set_intr_alt_stack(14, pf_tss);
	handle_exception(0, de_isr);
	printf("Try to divide by 0\n");
	/* install read only pte */
	install_pte(phys_to_virt(read_cr3()), 1, stack_va,
		    stack_phys | PT_PRESENT_MASK, 0);
	invlpg(stack_va);
	flush_phys_addr(stack_phys);
	switch_stack(stack_va + 4095);
	flush_idt_page();
	asm volatile ("divl %3": "=a"(res)
		      : "d"(0), "a"(1500), "m"(test_divider));
	restore_stack();
	printf("Result is %d\n", res);
	report("DE PF exceptions", res == 150);

	/* Generate NP and PF exceptions serially */
	printf("Before NP test\n");
	test_count = 0;
	set_intr_alt_stack(14, pf_tss);
	handle_exception(11, np_isr);
	set_idt_sel(33, NP_SEL);
	/* install read only pte */
	install_pte(phys_to_virt(read_cr3()), 1, stack_va,
		    stack_phys | PT_PRESENT_MASK, 0);
	invlpg(stack_va);
	flush_idt_page();
	flush_phys_addr(stack_phys);
	switch_stack(stack_va + 4095);
	asm volatile ("int $33");
	restore_stack();
	printf("After int33\n");
	report("NP PF exceptions", test_count == 2);

	pt = alloc_page();
	cr3 = (void*)read_cr3();
	memset(pt, 0, 4096);
	/* use shadowed stack during interrupt delivery */
	for (i = 0; i < 4096/sizeof(ulong); i++) {
		if (!cr3[i]) {
			cr3[i] = virt_to_phys(pt) | PT_PRESENT_MASK | PT_WRITABLE_MASK;
			pt[0] = virt_to_phys(pt) | PT_PRESENT_MASK | PT_WRITABLE_MASK;
#ifndef __x86_64__
			((ulong*)(i<<22))[1] = 0;
#else
			((ulong*)(i<<39))[1] = 0;
#endif
			write_cr3(virt_to_phys(cr3));
			break;
		}
	}
	test_count = 0;
	printf("Try int 33 with shadowed stack\n");
	switch_stack(((char*)pt) + 4095);
	asm volatile("int $33");
	restore_stack();
	printf("After int 33 with shadowed stack\n");
	report("int 33 with shadowed stack", test_count == 1);

	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/kvm-unit-tests/x86/flat.lds                                                        0000644 0000000 0000000 00000000600 00000000000 016013  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       SECTIONS
{
    . = 4M + SIZEOF_HEADERS;
    stext = .;
    .text : { *(.init) *(.text) *(.text.*) }
    . = ALIGN(4K);
    .data : {
          *(.data)
          exception_table_start = .;
          *(.data.ex)
	  exception_table_end = .;
	  }
    . = ALIGN(16);
    .rodata : { *(.rodata) }
    . = ALIGN(16);
    .bss : { *(.bss) }
    . = ALIGN(4K);
    edata = .;
}

ENTRY(start)
                                                                                                                                source/v64/tests/kvm-unit-tests/x86/hypercall.c                                                     0000644 0000000 0000000 00000003603 00000000000 016516  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "vm.h"
#include "desc.h"

#define KVM_HYPERCALL_INTEL ".byte 0x0f,0x01,0xc1"
#define KVM_HYPERCALL_AMD ".byte 0x0f,0x01,0xd9"

static inline long kvm_hypercall0_intel(unsigned int nr)
{
	long ret;
	asm volatile(KVM_HYPERCALL_INTEL
		     : "=a"(ret)
		     : "a"(nr));
	return ret;
}

static inline long kvm_hypercall0_amd(unsigned int nr)
{
	long ret;
	asm volatile(KVM_HYPERCALL_AMD
		     : "=a"(ret)
		     : "a"(nr));
	return ret;
}


volatile unsigned long test_rip;
#ifdef __x86_64__
extern void gp_tss(void);
asm ("gp_tss: \n\t"
	"add $8, %rsp\n\t"            // discard error code
	"popq test_rip(%rip)\n\t"     // pop return address
	"pushq %rsi\n\t"              // new return address
	"iretq\n\t"
	"jmp gp_tss\n\t"
    );

static inline int
test_edge(void)
{
	test_rip = 0;
	asm volatile ("movq $-1, %%rax\n\t"			// prepare for vmcall
		      "leaq 1f(%%rip), %%rsi\n\t"		// save return address for gp_tss
		      "movabsq $0x7ffffffffffd, %%rbx\n\t"
		      "jmp *%%rbx; 1:" : : : "rax", "rbx", "rsi");
	printf("Return from int 13, test_rip = %lx\n", test_rip);
	return test_rip == (1ul << 47);
}
#endif

int main(int ac, char **av)
{
	kvm_hypercall0_intel(-1u);
	printf("Hypercall via VMCALL: OK\n");
	kvm_hypercall0_amd(-1u);
	printf("Hypercall via VMMCALL: OK\n");

#ifdef __x86_64__
	setup_vm();
	setup_idt();
	setup_alt_stack();
	set_intr_alt_stack(13, gp_tss);

	u8 *data1 = alloc_page();
	u8 *topmost = (void *) ((1ul << 47) - PAGE_SIZE);

	install_pte(phys_to_virt(read_cr3()), 1, topmost,
		    virt_to_phys(data1) | PT_PRESENT_MASK | PT_WRITABLE_MASK, 0);
	memset(topmost, 0xcc, PAGE_SIZE);
	topmost[4093] = 0x0f;
	topmost[4094] = 0x01;
	topmost[4095] = 0xc1;
	report("VMCALL on edge of canonical address space (intel)", test_edge());

	topmost[4095] = 0xd9;
	report("VMMCALL on edge of canonical address space (AMD)", test_edge());
#endif

	return report_summary();
}
                                                                                                                             source/v64/tests/kvm-unit-tests/x86/hyperv.c                                                        0000644 0000000 0000000 00000003243 00000000000 016050  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "hyperv.h"
#include "asm/io.h"
#include "smp.h"

enum {
    HV_TEST_DEV_SINT_ROUTE_CREATE = 1,
    HV_TEST_DEV_SINT_ROUTE_DESTROY,
    HV_TEST_DEV_SINT_ROUTE_SET_SINT,
    HV_TEST_DEV_MSG_CONN_CREATE,
    HV_TEST_DEV_MSG_CONN_DESTROY,
    HV_TEST_DEV_EVT_CONN_CREATE,
    HV_TEST_DEV_EVT_CONN_DESTROY,
};

static void synic_ctl(u32 ctl, u32 vcpu_id, u32 sint, u32 conn_id)
{
    outl((conn_id << 24) | (ctl << 16) | (vcpu_id << 8) | sint, 0x3000);
}

static void sint_enable(u8 sint, u8 vec, bool auto_eoi)
{
    wrmsr(HV_X64_MSR_SINT0 + sint,
          (u64)vec | (auto_eoi ? HV_SYNIC_SINT_AUTO_EOI : 0));
}

static void sint_disable(u8 sint)
{
    wrmsr(HV_X64_MSR_SINT0 + sint, 0xff | HV_SYNIC_SINT_MASKED);
}

void synic_sint_create(u8 sint, u8 vec, bool auto_eoi)
{
    synic_ctl(HV_TEST_DEV_SINT_ROUTE_CREATE, smp_id(), sint, 0);
    sint_enable(sint, vec, auto_eoi);
}

void synic_sint_set(u8 vcpu, u8 sint)
{
    synic_ctl(HV_TEST_DEV_SINT_ROUTE_SET_SINT, vcpu, sint, 0);
}

void synic_sint_destroy(u8 sint)
{
    sint_disable(sint);
    synic_ctl(HV_TEST_DEV_SINT_ROUTE_DESTROY, smp_id(), sint, 0);
}

void msg_conn_create(u8 sint, u8 vec, u8 conn_id)
{
    synic_ctl(HV_TEST_DEV_MSG_CONN_CREATE, smp_id(), sint, conn_id);
    sint_enable(sint, vec, true);
}

void msg_conn_destroy(u8 sint, u8 conn_id)
{
    sint_disable(sint);
    synic_ctl(HV_TEST_DEV_MSG_CONN_DESTROY, 0, 0, conn_id);
}

void evt_conn_create(u8 sint, u8 vec, u8 conn_id)
{
    synic_ctl(HV_TEST_DEV_EVT_CONN_CREATE, smp_id(), sint, conn_id);
    sint_enable(sint, vec, true);
}

void evt_conn_destroy(u8 sint, u8 conn_id)
{
    sint_disable(sint);
    synic_ctl(HV_TEST_DEV_EVT_CONN_DESTROY, 0, 0, conn_id);
}
                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/x86/hyperv.h                                                        0000644 0000000 0000000 00000016230 00000000000 016055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __HYPERV_H
#define __HYPERV_H

#include "libcflat.h"
#include "processor.h"

#define HYPERV_CPUID_FEATURES                   0x40000003

#define HV_X64_MSR_TIME_REF_COUNT_AVAILABLE     (1 << 1)
#define HV_X64_MSR_SYNIC_AVAILABLE              (1 << 2)
#define HV_X64_MSR_SYNTIMER_AVAILABLE           (1 << 3)

#define HV_X64_MSR_GUEST_OS_ID                  0x40000000
#define HV_X64_MSR_HYPERCALL                    0x40000001

#define HV_X64_MSR_TIME_REF_COUNT               0x40000020
#define HV_X64_MSR_REFERENCE_TSC                0x40000021

/* Define synthetic interrupt controller model specific registers. */
#define HV_X64_MSR_SCONTROL                     0x40000080
#define HV_X64_MSR_SVERSION                     0x40000081
#define HV_X64_MSR_SIEFP                        0x40000082
#define HV_X64_MSR_SIMP                         0x40000083
#define HV_X64_MSR_EOM                          0x40000084
#define HV_X64_MSR_SINT0                        0x40000090
#define HV_X64_MSR_SINT1                        0x40000091
#define HV_X64_MSR_SINT2                        0x40000092
#define HV_X64_MSR_SINT3                        0x40000093
#define HV_X64_MSR_SINT4                        0x40000094
#define HV_X64_MSR_SINT5                        0x40000095
#define HV_X64_MSR_SINT6                        0x40000096
#define HV_X64_MSR_SINT7                        0x40000097
#define HV_X64_MSR_SINT8                        0x40000098
#define HV_X64_MSR_SINT9                        0x40000099
#define HV_X64_MSR_SINT10                       0x4000009A
#define HV_X64_MSR_SINT11                       0x4000009B
#define HV_X64_MSR_SINT12                       0x4000009C
#define HV_X64_MSR_SINT13                       0x4000009D
#define HV_X64_MSR_SINT14                       0x4000009E
#define HV_X64_MSR_SINT15                       0x4000009F

/*
 * Synthetic Timer MSRs. Four timers per vcpu.
 */

#define HV_X64_MSR_STIMER0_CONFIG               0x400000B0
#define HV_X64_MSR_STIMER0_COUNT                0x400000B1
#define HV_X64_MSR_STIMER1_CONFIG               0x400000B2
#define HV_X64_MSR_STIMER1_COUNT                0x400000B3
#define HV_X64_MSR_STIMER2_CONFIG               0x400000B4
#define HV_X64_MSR_STIMER2_COUNT                0x400000B5
#define HV_X64_MSR_STIMER3_CONFIG               0x400000B6
#define HV_X64_MSR_STIMER3_COUNT                0x400000B7

#define HV_SYNIC_CONTROL_ENABLE                 (1ULL << 0)
#define HV_SYNIC_SIMP_ENABLE                    (1ULL << 0)
#define HV_SYNIC_SIEFP_ENABLE                   (1ULL << 0)
#define HV_SYNIC_SINT_MASKED                    (1ULL << 16)
#define HV_SYNIC_SINT_AUTO_EOI                  (1ULL << 17)
#define HV_SYNIC_SINT_VECTOR_MASK               (0xFF)
#define HV_SYNIC_SINT_COUNT                     16

#define HV_STIMER_ENABLE                (1ULL << 0)
#define HV_STIMER_PERIODIC              (1ULL << 1)
#define HV_STIMER_LAZY                  (1ULL << 2)
#define HV_STIMER_AUTOENABLE            (1ULL << 3)
#define HV_STIMER_SINT(config)          (__u8)(((config) >> 16) & 0x0F)

#define HV_SYNIC_STIMER_COUNT           (4)

/* Define synthetic interrupt controller message constants. */
#define HV_MESSAGE_SIZE                 (256)
#define HV_MESSAGE_PAYLOAD_BYTE_COUNT   (240)
#define HV_MESSAGE_PAYLOAD_QWORD_COUNT  (30)

/* Define hypervisor message types. */
enum hv_message_type {
        HVMSG_NONE                      = 0x00000000,

        /* Memory access messages. */
        HVMSG_UNMAPPED_GPA              = 0x80000000,
        HVMSG_GPA_INTERCEPT             = 0x80000001,

        /* Timer notification messages. */
        HVMSG_TIMER_EXPIRED                     = 0x80000010,

        /* Error messages. */
        HVMSG_INVALID_VP_REGISTER_VALUE = 0x80000020,
        HVMSG_UNRECOVERABLE_EXCEPTION   = 0x80000021,
        HVMSG_UNSUPPORTED_FEATURE               = 0x80000022,

        /* Trace buffer complete messages. */
        HVMSG_EVENTLOG_BUFFERCOMPLETE   = 0x80000040,

        /* Platform-specific processor intercept messages. */
        HVMSG_X64_IOPORT_INTERCEPT              = 0x80010000,
        HVMSG_X64_MSR_INTERCEPT         = 0x80010001,
        HVMSG_X64_CPUID_INTERCEPT               = 0x80010002,
        HVMSG_X64_EXCEPTION_INTERCEPT   = 0x80010003,
        HVMSG_X64_APIC_EOI                      = 0x80010004,
        HVMSG_X64_LEGACY_FP_ERROR               = 0x80010005
};

/* Define synthetic interrupt controller message flags. */
union hv_message_flags {
        uint8_t asu8;
        struct {
                uint8_t msg_pending:1;
                uint8_t reserved:7;
        };
};

union hv_port_id {
        uint32_t asu32;
        struct {
                uint32_t id:24;
                uint32_t reserved:8;
        } u;
};

/* Define port type. */
enum hv_port_type {
        HVPORT_MSG      = 1,
        HVPORT_EVENT            = 2,
        HVPORT_MONITOR  = 3
};

/* Define synthetic interrupt controller message header. */
struct hv_message_header {
        uint32_t message_type;
        uint8_t payload_size;
        union hv_message_flags message_flags;
        uint8_t reserved[2];
        union {
                uint64_t sender;
                union hv_port_id port;
        };
};

/* Define timer message payload structure. */
struct hv_timer_message_payload {
        uint32_t timer_index;
        uint32_t reserved;
        uint64_t expiration_time;       /* When the timer expired */
        uint64_t delivery_time; /* When the message was delivered */
};

/* Define synthetic interrupt controller message format. */
struct hv_message {
        struct hv_message_header header;
        union {
                uint64_t payload[HV_MESSAGE_PAYLOAD_QWORD_COUNT];
        } u;
};

/* Define the synthetic interrupt message page layout. */
struct hv_message_page {
        struct hv_message sint_message[HV_SYNIC_SINT_COUNT];
};

#define HV_EVENT_FLAGS_COUNT	(256 * 8)

struct hv_event_flags {
	ulong flags[HV_EVENT_FLAGS_COUNT / (8 * sizeof(ulong))];
};

struct hv_event_flags_page {
	struct hv_event_flags slot[HV_SYNIC_SINT_COUNT];
};

#define HV_X64_MSR_HYPERCALL_ENABLE             0x1

#define HV_HYPERCALL_FAST               (1u << 16)

#define HVCALL_POST_MESSAGE                     0x5c
#define HVCALL_SIGNAL_EVENT                     0x5d

struct hv_input_post_message {
	u32 connectionid;
	u32 reserved;
	u32 message_type;
	u32 payload_size;
	u64 payload[HV_MESSAGE_PAYLOAD_QWORD_COUNT];
};

static inline bool synic_supported(void)
{
   return cpuid(HYPERV_CPUID_FEATURES).a & HV_X64_MSR_SYNIC_AVAILABLE;
}

static inline bool stimer_supported(void)
{
    return cpuid(HYPERV_CPUID_FEATURES).a & HV_X64_MSR_SYNIC_AVAILABLE;
}

static inline bool hv_time_ref_counter_supported(void)
{
    return cpuid(HYPERV_CPUID_FEATURES).a & HV_X64_MSR_TIME_REF_COUNT_AVAILABLE;
}

void synic_sint_create(u8 sint, u8 vec, bool auto_eoi);
void synic_sint_set(u8 vcpu, u8 sint);
void synic_sint_destroy(u8 sint);
void msg_conn_create(u8 sint, u8 vec, u8 conn_id);
void msg_conn_destroy(u8 sint, u8 conn_id);
void evt_conn_create(u8 sint, u8 vec, u8 conn_id);
void evt_conn_destroy(u8 sint, u8 conn_id);

struct hv_reference_tsc_page {
        uint32_t tsc_sequence;
        uint32_t res1;
        uint64_t tsc_scale;
        int64_t tsc_offset;
};


#endif
                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/kvm-unit-tests/x86/hyperv_clock.c                                                  0000644 0000000 0000000 00000010643 00000000000 017225  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "smp.h"
#include "atomic.h"
#include "processor.h"
#include "hyperv.h"
#include "vm.h"

#define MAX_CPU 4
#define TICKS_PER_SEC (1000000000 / 100)

struct hv_reference_tsc_page *hv_clock;

/*
 * Scale a 64-bit delta by scaling and multiplying by a 32-bit fraction,
 * yielding a 64-bit result.
 */
static inline u64 scale_delta(u64 delta, u64 mul_frac)
{
	u64 product, unused;

	__asm__ (
		"mulq %3"
		: "=d" (product), "=a" (unused) : "1" (delta), "rm" ((u64)mul_frac) );

	return product;
}

static u64 hvclock_tsc_to_ticks(struct hv_reference_tsc_page *shadow, uint64_t tsc)
{
	u64 delta = tsc;
	return scale_delta(delta, shadow->tsc_scale) + shadow->tsc_offset;
}

/*
 * Reads a consistent set of time-base values from hypervisor,
 * into a shadow data area.
 */
static void hvclock_get_time_values(struct hv_reference_tsc_page *shadow,
				    struct hv_reference_tsc_page *page)
{
	int seq;
	do {
		seq = page->tsc_sequence;
		rmb();		/* fetch version before data */
		*shadow = *page;
		rmb();		/* test version after fetching data */
	} while (shadow->tsc_sequence != seq);
}

uint64_t hv_clock_read(void)
{
	struct hv_reference_tsc_page shadow;

	hvclock_get_time_values(&shadow, hv_clock);
	return hvclock_tsc_to_ticks(&shadow, rdtsc());
}

bool ok[MAX_CPU];
uint64_t loops[MAX_CPU];

#define iabs(x)   ((x) < 0 ? -(x) : (x))

static void hv_clock_test(void *data)
{
	int i = smp_id();
	uint64_t t = rdmsr(HV_X64_MSR_TIME_REF_COUNT);
	uint64_t end = t + 3 * TICKS_PER_SEC;
	uint64_t msr_sample = t + TICKS_PER_SEC;
	int min_delta = 123456, max_delta = -123456;
	bool got_drift = false;
	bool got_warp = false;

	ok[i] = true;
	do {
		uint64_t now = hv_clock_read();
		int delta = rdmsr(HV_X64_MSR_TIME_REF_COUNT) - now;

		min_delta = delta < min_delta ? delta : min_delta;
		if (t < msr_sample) {
			max_delta = delta > max_delta ? delta: max_delta;
		} else if (delta < 0 || delta > max_delta * 3 / 2) {
			printf("suspecting drift on CPU %d? delta = %d, acceptable [0, %d)\n", smp_id(),
			       delta, max_delta);
			ok[i] = false;
			got_drift = true;
			max_delta *= 2;
		}

		if (now < t && !got_warp) {
			printf("warp on CPU %d!\n", smp_id());
			ok[i] = false;
			got_warp = true;
			break;
		}
		t = now;
	} while(t < end);

	if (!got_drift)
		printf("delta on CPU %d was %d...%d\n", smp_id(), min_delta, max_delta);
	barrier();
}

static void check_test(int ncpus)
{
	int i;
	bool pass;

	on_cpus(hv_clock_test, NULL);

	pass = true;
	for (i = ncpus - 1; i >= 0; i--)
		pass &= ok[i];

	report("TSC reference precision test", pass);
}

static void hv_perf_test(void *data)
{
	uint64_t t = hv_clock_read();
	uint64_t end = t + 1000000000 / 100;
	uint64_t local_loops = 0;

	do {
		t = hv_clock_read();
		local_loops++;
	} while(t < end);

	loops[smp_id()] = local_loops;
}

static void perf_test(int ncpus)
{
	int i;
	uint64_t total_loops;

	on_cpus(hv_perf_test, NULL);

	total_loops = 0;
	for (i = ncpus - 1; i >= 0; i--)
		total_loops += loops[i];
	printf("iterations/sec:  %" PRId64"\n", total_loops / ncpus);
}

int main(int ac, char **av)
{
	int nerr = 0;
	int ncpus;
	struct hv_reference_tsc_page shadow;
	uint64_t tsc1, t1, tsc2, t2;
	uint64_t ref1, ref2;

	setup_vm();
	smp_init();

	ncpus = cpu_count();
	if (ncpus > MAX_CPU)
		report_abort("number cpus exceeds %d", MAX_CPU);

	hv_clock = alloc_page();
	wrmsr(HV_X64_MSR_REFERENCE_TSC, (u64)(uintptr_t)hv_clock | 1);
	report("MSR value after enabling",
	       rdmsr(HV_X64_MSR_REFERENCE_TSC) == ((u64)(uintptr_t)hv_clock | 1));

	hvclock_get_time_values(&shadow, hv_clock);
	if (shadow.tsc_sequence == 0 || shadow.tsc_sequence == 0xFFFFFFFF) {
		printf("Reference TSC page not available\n");
		exit(1);
	}

	printf("scale: %" PRIx64" offset: %" PRId64"\n", shadow.tsc_scale, shadow.tsc_offset);
	ref1 = rdmsr(HV_X64_MSR_TIME_REF_COUNT);
	tsc1 = rdtsc();
	t1 = hvclock_tsc_to_ticks(&shadow, tsc1);
	printf("refcnt %" PRId64", TSC %" PRIx64", TSC reference %" PRId64"\n",
	       ref1, tsc1, t1);

	do
		ref2 = rdmsr(HV_X64_MSR_TIME_REF_COUNT);
	while (ref2 < ref1 + 2 * TICKS_PER_SEC);

	tsc2 = rdtsc();
	t2 = hvclock_tsc_to_ticks(&shadow, tsc2);
	printf("refcnt %" PRId64" (delta %" PRId64"), TSC %" PRIx64", "
	       "TSC reference %" PRId64" (delta %" PRId64")\n",
	       ref2, ref2 - ref1, tsc2, t2, t2 - t1);

	check_test(ncpus);
	perf_test(ncpus);

	wrmsr(HV_X64_MSR_REFERENCE_TSC, 0LL);
	report("MSR value after disabling", rdmsr(HV_X64_MSR_REFERENCE_TSC) == 0);

	return nerr > 0 ? 1 : 0;
}
                                                                                             source/v64/tests/kvm-unit-tests/x86/hyperv_connections.c                                            0000644 0000000 0000000 00000020067 00000000000 020455  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "vm.h"
#include "smp.h"
#include "isr.h"
#include "atomic.h"
#include "hyperv.h"
#include "bitops.h"

#define MAX_CPUS 64

#define MSG_VEC 0xb0
#define EVT_VEC 0xb1
#define MSG_SINT 0x8
#define EVT_SINT 0x9
#define MSG_CONN_BASE 0x10
#define EVT_CONN_BASE 0x20
#define MSG_TYPE 0x12345678

#define WAIT_CYCLES 10000000

static atomic_t ncpus_done;

struct hv_vcpu {
	struct hv_message_page *msg_page;
	struct hv_event_flags_page *evt_page;
	struct hv_input_post_message *post_msg;
	u8 msg_conn;
	u8 evt_conn;
	u64 hvcall_status;
	atomic_t sint_received;
};

static struct hv_vcpu hv_vcpus[MAX_CPUS];

static void sint_isr(isr_regs_t *regs)
{
	atomic_inc(&hv_vcpus[smp_id()].sint_received);
}

static void *hypercall_page;

static void setup_hypercall(void)
{
	u64 guestid = (0x8f00ull << 48);

	hypercall_page = alloc_page();
	if (!hypercall_page)
		report_abort("failed to allocate hypercall page");
	memset(hypercall_page, 0, PAGE_SIZE);

	wrmsr(HV_X64_MSR_GUEST_OS_ID, guestid);

	wrmsr(HV_X64_MSR_HYPERCALL,
	      (u64)virt_to_phys(hypercall_page) | HV_X64_MSR_HYPERCALL_ENABLE);
}

static void teardown_hypercall(void)
{
	wrmsr(HV_X64_MSR_HYPERCALL, 0);
	wrmsr(HV_X64_MSR_GUEST_OS_ID, 0);
	free_page(hypercall_page);
}

static u64 do_hypercall(u16 code, u64 arg, bool fast)
{
	u64 ret;
	u64 ctl = code;
	if (fast)
		ctl |= HV_HYPERCALL_FAST;

	asm volatile ("call *%[hcall_page]"
#ifdef __x86_64__
		      "\n mov $0,%%r8"
		      : "=a"(ret)
		      : "c"(ctl), "d"(arg),
#else
		      : "=A"(ret)
		      : "A"(ctl),
			"b" ((u32)(arg >> 32)), "c" ((u32)arg),
			"D"(0), "S"(0),
#endif
		      [hcall_page] "m" (hypercall_page)
#ifdef __x86_64__
		      : "r8"
#endif
		     );

	return ret;
}

static void setup_cpu(void *ctx)
{
	int vcpu;
	struct hv_vcpu *hv;

	write_cr3((ulong)ctx);
	irq_enable();

	vcpu = smp_id();
	hv = &hv_vcpus[vcpu];

	hv->msg_page = alloc_page();
	hv->evt_page = alloc_page();
	hv->post_msg = alloc_page();
	if (!hv->msg_page || !hv->evt_page || !hv->post_msg)
		report_abort("failed to allocate synic pages for vcpu");
	memset(hv->msg_page, 0, sizeof(*hv->msg_page));
	memset(hv->evt_page, 0, sizeof(*hv->evt_page));
	memset(hv->post_msg, 0, sizeof(*hv->post_msg));
	hv->msg_conn = MSG_CONN_BASE + vcpu;
	hv->evt_conn = EVT_CONN_BASE + vcpu;

	wrmsr(HV_X64_MSR_SIMP,
	      (u64)virt_to_phys(hv->msg_page) | HV_SYNIC_SIMP_ENABLE);
	wrmsr(HV_X64_MSR_SIEFP,
	      (u64)virt_to_phys(hv->evt_page) | HV_SYNIC_SIEFP_ENABLE);
	wrmsr(HV_X64_MSR_SCONTROL, HV_SYNIC_CONTROL_ENABLE);

	msg_conn_create(MSG_SINT, MSG_VEC, hv->msg_conn);
	evt_conn_create(EVT_SINT, EVT_VEC, hv->evt_conn);

	hv->post_msg->connectionid = hv->msg_conn;
	hv->post_msg->message_type = MSG_TYPE;
	hv->post_msg->payload_size = 8;
	hv->post_msg->payload[0] = (u64)vcpu << 16;
}

static void teardown_cpu(void *ctx)
{
	int vcpu = smp_id();
	struct hv_vcpu *hv = &hv_vcpus[vcpu];

	evt_conn_destroy(EVT_SINT, hv->evt_conn);
	msg_conn_destroy(MSG_SINT, hv->msg_conn);

	wrmsr(HV_X64_MSR_SCONTROL, 0);
	wrmsr(HV_X64_MSR_SIEFP, 0);
	wrmsr(HV_X64_MSR_SIMP, 0);

	free_page(hv->post_msg);
	free_page(hv->evt_page);
	free_page(hv->msg_page);
}

static void do_msg(void *ctx)
{
	int vcpu = (ulong)ctx;
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	struct hv_input_post_message *msg = hv->post_msg;

	msg->payload[0]++;
	atomic_set(&hv->sint_received, 0);
	hv->hvcall_status = do_hypercall(HVCALL_POST_MESSAGE,
					 virt_to_phys(msg), 0);
	atomic_inc(&ncpus_done);
}

static void clear_msg(void *ctx)
{
	/* should only be done on the current vcpu */
	int vcpu = smp_id();
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	struct hv_message *msg = &hv->msg_page->sint_message[MSG_SINT];

	atomic_set(&hv->sint_received, 0);
	msg->header.message_type = 0;
	barrier();
	wrmsr(HV_X64_MSR_EOM, 0);
	atomic_inc(&ncpus_done);
}

static bool msg_ok(int vcpu)
{
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	struct hv_input_post_message *post_msg = hv->post_msg;
	struct hv_message *msg = &hv->msg_page->sint_message[MSG_SINT];

	return msg->header.message_type == post_msg->message_type &&
		msg->header.payload_size == post_msg->payload_size &&
		msg->header.message_flags.msg_pending == 0 &&
		msg->u.payload[0] == post_msg->payload[0] &&
		hv->hvcall_status == 0 &&
		atomic_read(&hv->sint_received) == 1;
}

static bool msg_busy(int vcpu)
{
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	struct hv_input_post_message *post_msg = hv->post_msg;
	struct hv_message *msg = &hv->msg_page->sint_message[MSG_SINT];

	return msg->header.message_type == post_msg->message_type &&
		msg->header.payload_size == post_msg->payload_size &&
		msg->header.message_flags.msg_pending == 1 &&
		msg->u.payload[0] == post_msg->payload[0] - 1 &&
		hv->hvcall_status == 0 &&
		atomic_read(&hv->sint_received) == 0;
}

static void do_evt(void *ctx)
{
	int vcpu = (ulong)ctx;
	struct hv_vcpu *hv = &hv_vcpus[vcpu];

	atomic_set(&hv->sint_received, 0);
	hv->hvcall_status = do_hypercall(HVCALL_SIGNAL_EVENT,
					 hv->evt_conn, 1);
	atomic_inc(&ncpus_done);
}

static void clear_evt(void *ctx)
{
	/* should only be done on the current vcpu */
	int vcpu = smp_id();
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	ulong *flags = hv->evt_page->slot[EVT_SINT].flags;

	atomic_set(&hv->sint_received, 0);
	flags[BIT_WORD(hv->evt_conn)] &= ~BIT_MASK(hv->evt_conn);
	barrier();
	atomic_inc(&ncpus_done);
}

static bool evt_ok(int vcpu)
{
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	ulong *flags = hv->evt_page->slot[EVT_SINT].flags;

	return flags[BIT_WORD(hv->evt_conn)] == BIT_MASK(hv->evt_conn) &&
		hv->hvcall_status == 0 &&
		atomic_read(&hv->sint_received) == 1;
}

static bool evt_busy(int vcpu)
{
	struct hv_vcpu *hv = &hv_vcpus[vcpu];
	ulong *flags = hv->evt_page->slot[EVT_SINT].flags;

	return flags[BIT_WORD(hv->evt_conn)] == BIT_MASK(hv->evt_conn) &&
		hv->hvcall_status == 0 &&
		atomic_read(&hv->sint_received) == 0;
}

static int run_test(int ncpus, int dst_add, ulong wait_cycles,
		    void (*func)(void *), bool (*is_ok)(int))
{
	int i, ret = 0;

	atomic_set(&ncpus_done, 0);
	for (i = 0; i < ncpus; i++) {
		ulong dst = (i + dst_add) % ncpus;
		on_cpu_async(i, func, (void *)dst);
	}
	while (atomic_read(&ncpus_done) != ncpus)
		pause();

	while (wait_cycles--)
		pause();

	if (is_ok)
		for (i = 0; i < ncpus; i++)
			ret += is_ok(i);
	return ret;
}

#define HV_STATUS_INVALID_HYPERCALL_CODE        2

int main(int ac, char **av)
{
	int ncpus, ncpus_ok, i;

	if (!synic_supported()) {
		report_skip("Hyper-V SynIC is not supported");
		goto summary;
	}

	setup_vm();
	smp_init();
	ncpus = cpu_count();
	if (ncpus > MAX_CPUS)
		report_abort("# cpus: %d > %d", ncpus, MAX_CPUS);

	handle_irq(MSG_VEC, sint_isr);
	handle_irq(EVT_VEC, sint_isr);

	setup_hypercall();

	if (do_hypercall(HVCALL_SIGNAL_EVENT, 0x1234, 1) ==
	    HV_STATUS_INVALID_HYPERCALL_CODE) {
		report_skip("Hyper-V SynIC connections are not supported");
		goto summary;
	}

	for (i = 0; i < ncpus; i++)
		on_cpu(i, setup_cpu, (void *)read_cr3());

	ncpus_ok = run_test(ncpus, 0, WAIT_CYCLES, do_msg, msg_ok);
	report("send message to self: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	run_test(ncpus, 0, 0, clear_msg, NULL);

	ncpus_ok = run_test(ncpus, 1, WAIT_CYCLES, do_msg, msg_ok);
	report("send message to another cpu: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	ncpus_ok = run_test(ncpus, 1, WAIT_CYCLES, do_msg, msg_busy);
	report("send message to busy slot: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	ncpus_ok = run_test(ncpus, 0, WAIT_CYCLES, clear_msg, msg_ok);
	report("receive pending message: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	ncpus_ok = run_test(ncpus, 0, WAIT_CYCLES, do_evt, evt_ok);
	report("signal event on self: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	run_test(ncpus, 0, 0, clear_evt, NULL);

	ncpus_ok = run_test(ncpus, 1, WAIT_CYCLES, do_evt, evt_ok);
	report("signal event on another cpu: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	ncpus_ok = run_test(ncpus, 1, WAIT_CYCLES, do_evt, evt_busy);
	report("signal event already set: %d/%d",
	       ncpus_ok == ncpus, ncpus_ok, ncpus);

	for (i = 0; i < ncpus; i++)
		on_cpu(i, teardown_cpu, NULL);

	teardown_hypercall();

summary:
	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/x86/hyperv_stimer.c                                                 0000644 0000000 0000000 00000022104 00000000000 017430  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "processor.h"
#include "msr.h"
#include "isr.h"
#include "vm.h"
#include "apic.h"
#include "desc.h"
#include "smp.h"
#include "atomic.h"
#include "hyperv.h"
#include "asm/barrier.h"

#define MAX_CPUS 4

#define SINT1_VEC 0xF1
#define SINT2_VEC 0xF2

#define SINT1_NUM 2
#define SINT2_NUM 3
#define ONE_MS_IN_100NS 10000

static struct spinlock g_synic_alloc_lock;

struct stimer {
    int sint;
    int index;
    atomic_t fire_count;
};

struct svcpu {
    int vcpu;
    void *msg_page;
    void *evt_page;
    struct stimer timer[HV_SYNIC_STIMER_COUNT];
};

static struct svcpu g_synic_vcpu[MAX_CPUS];

static void *synic_alloc_page(void)
{
    void *page;

    spin_lock(&g_synic_alloc_lock);
    page = alloc_page();
    spin_unlock(&g_synic_alloc_lock);
    return page;
}

static void synic_free_page(void *page)
{
    spin_lock(&g_synic_alloc_lock);
    free_page(page);
    spin_unlock(&g_synic_alloc_lock);
}

static void stimer_init(struct stimer *timer, int index)
{
    memset(timer, 0, sizeof(*timer));
    timer->index = index;
}

static void synic_enable(void)
{
    int vcpu = smp_id(), i;
    struct svcpu *svcpu = &g_synic_vcpu[vcpu];

    memset(svcpu, 0, sizeof(*svcpu));
    svcpu->vcpu = vcpu;
    svcpu->msg_page = synic_alloc_page();
    for (i = 0; i < ARRAY_SIZE(svcpu->timer); i++) {
        stimer_init(&svcpu->timer[i], i);
    }
    wrmsr(HV_X64_MSR_SIMP, (u64)virt_to_phys(svcpu->msg_page) |
            HV_SYNIC_SIMP_ENABLE);
    wrmsr(HV_X64_MSR_SCONTROL, HV_SYNIC_CONTROL_ENABLE);
}

static void stimer_shutdown(struct stimer *timer)
{
    wrmsr(HV_X64_MSR_STIMER0_CONFIG + 2*timer->index, 0);
}

static void process_stimer_expired(struct svcpu *svcpu, struct stimer *timer,
                                   u64 expiration_time, u64 delivery_time)
{
    atomic_inc(&timer->fire_count);
}

static void process_stimer_msg(struct svcpu *svcpu,
                              struct hv_message *msg, int sint)
{
    struct hv_timer_message_payload *payload =
                        (struct hv_timer_message_payload *)msg->u.payload;
    struct stimer *timer;

    if (msg->header.message_type != HVMSG_TIMER_EXPIRED &&
        msg->header.message_type != HVMSG_NONE) {
        report("invalid Hyper-V SynIC msg type", false);
        report_summary();
        abort();
    }

    if (msg->header.message_type == HVMSG_NONE) {
        return;
    }

    if (msg->header.payload_size < sizeof(*payload)) {
        report("invalid Hyper-V SynIC msg payload size", false);
        report_summary();
        abort();
    }

    /* Now process timer expiration message */

    if (payload->timer_index >= ARRAY_SIZE(svcpu->timer)) {
        report("invalid Hyper-V SynIC timer index", false);
        report_summary();
        abort();
    }
    timer = &svcpu->timer[payload->timer_index];
    process_stimer_expired(svcpu, timer, payload->expiration_time,
                          payload->delivery_time);

    msg->header.message_type = HVMSG_NONE;
    mb();
    if (msg->header.message_flags.msg_pending) {
        wrmsr(HV_X64_MSR_EOM, 0);
    }
}

static void __stimer_isr(int vcpu)
{
    struct svcpu *svcpu = &g_synic_vcpu[vcpu];
    struct hv_message_page *msg_page;
    struct hv_message *msg;
    int i;


    msg_page = (struct hv_message_page *)svcpu->msg_page;
    for (i = 0; i < ARRAY_SIZE(msg_page->sint_message); i++) {
        msg = &msg_page->sint_message[i];
        process_stimer_msg(svcpu, msg, i);
    }
}

static void stimer_isr(isr_regs_t *regs)
{
    int vcpu = smp_id();

    __stimer_isr(vcpu);
    eoi();
}

static void stimer_isr_auto_eoi(isr_regs_t *regs)
{
    int vcpu = smp_id();

    __stimer_isr(vcpu);
}

static void stimer_start(struct stimer *timer,
                         bool auto_enable, bool periodic,
                         u64 tick_100ns, int sint)
{
    u64 config, count;

    timer->sint = sint;
    atomic_set(&timer->fire_count, 0);

    config = 0;
    if (periodic) {
        config |= HV_STIMER_PERIODIC;
    }

    config |= ((u8)(sint & 0xFF)) << 16;
    config |= HV_STIMER_ENABLE;
    if (auto_enable) {
        config |= HV_STIMER_AUTOENABLE;
    }

    if (periodic) {
        count = tick_100ns;
    } else {
        count = rdmsr(HV_X64_MSR_TIME_REF_COUNT) + tick_100ns;
    }

    if (!auto_enable) {
        wrmsr(HV_X64_MSR_STIMER0_COUNT + timer->index*2, count);
        wrmsr(HV_X64_MSR_STIMER0_CONFIG + timer->index*2, config);
    } else {
        wrmsr(HV_X64_MSR_STIMER0_CONFIG + timer->index*2, config);
        wrmsr(HV_X64_MSR_STIMER0_COUNT + timer->index*2, count);
    }
}

static void stimers_shutdown(void)
{
    int vcpu = smp_id(), i;
    struct svcpu *svcpu = &g_synic_vcpu[vcpu];

    for (i = 0; i < ARRAY_SIZE(svcpu->timer); i++) {
        stimer_shutdown(&svcpu->timer[i]);
    }
}

static void synic_disable(void)
{
    int vcpu = smp_id();
    struct svcpu *svcpu = &g_synic_vcpu[vcpu];

    wrmsr(HV_X64_MSR_SCONTROL, 0);
    wrmsr(HV_X64_MSR_SIMP, 0);
    wrmsr(HV_X64_MSR_SIEFP, 0);
    synic_free_page(svcpu->msg_page);
}


static void stimer_test_prepare(void *ctx)
{
    write_cr3((ulong)ctx);
    synic_enable();
    synic_sint_create(SINT1_NUM, SINT1_VEC, false);
    synic_sint_create(SINT2_NUM, SINT2_VEC, true);
}

static void stimer_test_periodic(int vcpu, struct stimer *timer1,
                                 struct stimer *timer2)
{
    /* Check periodic timers */
    stimer_start(timer1, false, true, ONE_MS_IN_100NS, SINT1_NUM);
    stimer_start(timer2, false, true, ONE_MS_IN_100NS, SINT2_NUM);
    while ((atomic_read(&timer1->fire_count) < 1000) ||
           (atomic_read(&timer2->fire_count) < 1000)) {
        pause();
    }
    report("Hyper-V SynIC periodic timers test vcpu %d", true, vcpu);
    stimer_shutdown(timer1);
    stimer_shutdown(timer2);
}

static void stimer_test_one_shot(int vcpu, struct stimer *timer)
{
    /* Check one-shot timer */
    stimer_start(timer, false, false, ONE_MS_IN_100NS, SINT1_NUM);
    while (atomic_read(&timer->fire_count) < 1) {
        pause();
    }
    report("Hyper-V SynIC one-shot test vcpu %d", true, vcpu);
    stimer_shutdown(timer);
}

static void stimer_test_auto_enable_one_shot(int vcpu, struct stimer *timer)
{
    /* Check auto-enable one-shot timer */
    stimer_start(timer, true, false, ONE_MS_IN_100NS, SINT1_NUM);
    while (atomic_read(&timer->fire_count) < 1) {
        pause();
    }
    report("Hyper-V SynIC auto-enable one-shot timer test vcpu %d", true, vcpu);
    stimer_shutdown(timer);
}

static void stimer_test_auto_enable_periodic(int vcpu, struct stimer *timer)
{
    /* Check auto-enable periodic timer */
    stimer_start(timer, true, true, ONE_MS_IN_100NS, SINT1_NUM);
    while (atomic_read(&timer->fire_count) < 1000) {
        pause();
    }
    report("Hyper-V SynIC auto-enable periodic timer test vcpu %d", true, vcpu);
    stimer_shutdown(timer);
}

static void stimer_test_one_shot_busy(int vcpu, struct stimer *timer)
{
    struct hv_message_page *msg_page = g_synic_vcpu[vcpu].msg_page;
    struct hv_message *msg = &msg_page->sint_message[timer->sint];

    msg->header.message_type = HVMSG_TIMER_EXPIRED;
    wmb();

    stimer_start(timer, false, false, ONE_MS_IN_100NS, SINT1_NUM);

    do
        rmb();
    while (!msg->header.message_flags.msg_pending);

    report("no timer fired while msg slot busy: vcpu %d",
           !atomic_read(&timer->fire_count), vcpu);

    msg->header.message_type = HVMSG_NONE;
    wmb();
    wrmsr(HV_X64_MSR_EOM, 0);

    while (atomic_read(&timer->fire_count) < 1) {
        pause();
    }
    report("timer resumed when msg slot released: vcpu %d", true, vcpu);

    stimer_shutdown(timer);
}

static void stimer_test(void *ctx)
{
    int vcpu = smp_id();
    struct svcpu *svcpu = &g_synic_vcpu[vcpu];
    struct stimer *timer1, *timer2;

    irq_enable();

    timer1 = &svcpu->timer[0];
    timer2 = &svcpu->timer[1];

    stimer_test_periodic(vcpu, timer1, timer2);
    stimer_test_one_shot(vcpu, timer1);
    stimer_test_auto_enable_one_shot(vcpu, timer2);
    stimer_test_auto_enable_periodic(vcpu, timer1);
    stimer_test_one_shot_busy(vcpu, timer1);

    irq_disable();
}

static void stimer_test_cleanup(void *ctx)
{
    stimers_shutdown();
    synic_sint_destroy(SINT1_NUM);
    synic_sint_destroy(SINT2_NUM);
    synic_disable();
}

static void stimer_test_all(void)
{
    int ncpus;

    setup_vm();
    smp_init();
    enable_apic();

    ncpus = cpu_count();
    if (ncpus > MAX_CPUS)
        report_abort("number cpus exceeds %d", MAX_CPUS);
    printf("cpus = %d\n", ncpus);

    handle_irq(SINT1_VEC, stimer_isr);
    handle_irq(SINT2_VEC, stimer_isr_auto_eoi);

    on_cpus(stimer_test_prepare, (void *)read_cr3());
    on_cpus(stimer_test, NULL);
    on_cpus(stimer_test_cleanup, NULL);
}

int main(int ac, char **av)
{

    if (!synic_supported()) {
        report("Hyper-V SynIC is not supported", true);
        goto done;
    }

    if (!stimer_supported()) {
        report("Hyper-V SynIC timers are not supported", true);
        goto done;
    }

    if (!hv_time_ref_counter_supported()) {
        report("Hyper-V time reference counter is not supported", true);
        goto done;
    }

    stimer_test_all();
done:
    return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/x86/hyperv_synic.c                                                  0000644 0000000 0000000 00000007636 00000000000 017267  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "processor.h"
#include "msr.h"
#include "isr.h"
#include "vm.h"
#include "apic.h"
#include "desc.h"
#include "smp.h"
#include "atomic.h"
#include "hyperv.h"

#define MAX_CPUS 4

static atomic_t isr_enter_count[MAX_CPUS];

static void synic_sint_auto_eoi_isr(isr_regs_t *regs)
{
    atomic_inc(&isr_enter_count[smp_id()]);
}

static void synic_sint_isr(isr_regs_t *regs)
{
    atomic_inc(&isr_enter_count[smp_id()]);
    eoi();
}

struct sint_vec_entry {
    int vec;
    bool auto_eoi;
};

struct sint_vec_entry sint_vecs[HV_SYNIC_SINT_COUNT] = {
    {0xB0, false},
    {0xB1, false},
    {0xB2, false},
    {0xB3, true},
    {0xB4, false},
    {0xB5, false},
    {0xB6, false},
    {0xB7, false},
    {0xB8, true},
    {0xB9, false},
    {0xBA, true},
    {0xBB, false},
    {0xBC, false},
    {0xBD, false},
    {0xBE, true},
    {0xBF, false},
};

static void synic_prepare_sint_vecs(void)
{
    bool auto_eoi;
    int i, vec;

    for (i = 0; i < HV_SYNIC_SINT_COUNT; i++) {
        vec = sint_vecs[i].vec;
        auto_eoi = sint_vecs[i].auto_eoi;
        handle_irq(vec, (auto_eoi) ? synic_sint_auto_eoi_isr : synic_sint_isr);
    }
}

static void synic_sints_prepare(int vcpu)
{
    bool auto_eoi;
    int i, vec;

    for (i = 0; i < HV_SYNIC_SINT_COUNT; i++) {
        vec = sint_vecs[i].vec;
        auto_eoi = sint_vecs[i].auto_eoi;
        synic_sint_create(i, vec, auto_eoi);
    }
}

static void synic_test_prepare(void *ctx)
{
    u64 r;
    int i = 0;

    write_cr3((ulong)ctx);
    irq_enable();

    rdmsr(HV_X64_MSR_SVERSION);
    rdmsr(HV_X64_MSR_SIMP);
    rdmsr(HV_X64_MSR_SIEFP);
    rdmsr(HV_X64_MSR_SCONTROL);
    for (i = 0; i < HV_SYNIC_SINT_COUNT; i++) {
        rdmsr(HV_X64_MSR_SINT0 + i);
    }
    r = rdmsr(HV_X64_MSR_EOM);
    if (r != 0) {
        report("Hyper-V SynIC test, EOM read %#" PRIx64, false, r);
        return;
    }

    wrmsr(HV_X64_MSR_SIMP, (u64)virt_to_phys(alloc_page()) |
            HV_SYNIC_SIMP_ENABLE);
    wrmsr(HV_X64_MSR_SIEFP, (u64)virt_to_phys(alloc_page())|
            HV_SYNIC_SIEFP_ENABLE);
    wrmsr(HV_X64_MSR_SCONTROL, HV_SYNIC_CONTROL_ENABLE);

    synic_sints_prepare(smp_id());
}

static void synic_sints_test(int dst_vcpu)
{
    int i;

    atomic_set(&isr_enter_count[dst_vcpu], 0);
    for (i = 0; i < HV_SYNIC_SINT_COUNT; i++) {
        synic_sint_set(dst_vcpu, i);
    }

    while (atomic_read(&isr_enter_count[dst_vcpu]) != HV_SYNIC_SINT_COUNT) {
        pause();
    }
}

static void synic_test(void *ctx)
{
    int dst_vcpu = (ulong)ctx;

    irq_enable();
    synic_sints_test(dst_vcpu);
}

static void synic_test_cleanup(void *ctx)
{
    int i;

    irq_enable();
    for (i = 0; i < HV_SYNIC_SINT_COUNT; i++) {
        synic_sint_destroy(i);
    }

    wrmsr(HV_X64_MSR_SCONTROL, 0);
    wrmsr(HV_X64_MSR_SIMP, 0);
    wrmsr(HV_X64_MSR_SIEFP, 0);
}

int main(int ac, char **av)
{

    if (synic_supported()) {
        int ncpus, i;
        bool ok;

        setup_vm();
        smp_init();
        enable_apic();

        ncpus = cpu_count();
        if (ncpus > MAX_CPUS)
            report_abort("number cpus exceeds %d", MAX_CPUS);
        printf("ncpus = %d\n", ncpus);

        synic_prepare_sint_vecs();

        printf("prepare\n");
        on_cpus(synic_test_prepare, (void *)read_cr3());

        for (i = 0; i < ncpus; i++) {
            printf("test %d -> %d\n", i, ncpus - 1 - i);
            on_cpu_async(i, synic_test, (void *)(ulong)(ncpus - 1 - i));
        }
        while (cpus_active() > 1)
            pause();

        printf("cleanup\n");
        on_cpus(synic_test_cleanup, NULL);

        ok = true;
        for (i = 0; i < ncpus; ++i) {
            printf("isr_enter_count[%d] = %d\n",
                   i, atomic_read(&isr_enter_count[i]));
            ok &= atomic_read(&isr_enter_count[i]) == 16;
        }

        report("Hyper-V SynIC test", ok);
    } else {
        printf("Hyper-V SynIC is not supported");
    }

    return report_summary();
}
                                                                                                  source/v64/tests/kvm-unit-tests/x86/idt_test.c                                                      0000644 0000000 0000000 00000001566 00000000000 016360  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "desc.h"

int test_ud2(bool *rflags_rf)
{
    asm volatile(ASM_TRY("1f")
                 "ud2 \n\t"
                 "1:" :);
    *rflags_rf = exception_rflags_rf();
    return exception_vector();
}

int test_gp(bool *rflags_rf)
{
    unsigned long tmp;

    asm volatile("mov $0xffffffff, %0 \n\t"
                 ASM_TRY("1f")
		 "mov %0, %%cr4\n\t"
                 "1:"
                 : "=a"(tmp));
    *rflags_rf = exception_rflags_rf();
    return exception_vector();
}

int main(void)
{
    int r;
    bool rflags_rf;

    printf("Starting IDT test\n");
    setup_idt();
    r = test_gp(&rflags_rf);
    report("Testing #GP", r == GP_VECTOR);
    report("Testing #GP rflags.rf", rflags_rf);
    r = test_ud2(&rflags_rf);
    report("Testing #UD", r == UD_VECTOR);
    report("Testing #UD rflags.rf", rflags_rf);

    return report_summary();
}
                                                                                                                                          source/v64/tests/kvm-unit-tests/x86/init.c                                                          0000644 0000000 0000000 00000005201 00000000000 015472  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "apic.h"
#include "asm/io.h"

#define KBD_CCMD_READ_OUTPORT   0xD0    /* read output port */
#define KBD_CCMD_WRITE_OUTPORT  0xD1    /* write output port */
#define KBD_CCMD_RESET          0xFE    /* CPU reset */

static inline void kbd_cmd(u8 val)
{
    while (inb(0x64) & 2);
    outb(val, 0x64);
}

static inline u8 kbd_in(void)
{
    kbd_cmd(KBD_CCMD_READ_OUTPORT);
    while (inb(0x64) & 2);
    return inb(0x60);
}

static inline void kbd_out(u8 val)
{
    kbd_cmd(KBD_CCMD_WRITE_OUTPORT);
    while (inb(0x64) & 2);
    outb(val, 0x60);
}

static inline void rtc_out(u8 reg, u8 val)
{
    outb(reg, 0x70);
    outb(val, 0x71);
}

extern char resume_start, resume_end;

#define state (*(volatile int *)0x2000)
#define bad (*(volatile int *)0x2004)
#define resumed (*(volatile int *)0x2008)

int main(int argc, char **argv)
{
	volatile u16 *resume_vector_ptr = (u16 *)0x467L;
	char *addr, *resume_vec = (void*)0x1000;

	/* resume execution by indirect jump via 40h:0067h */
	rtc_out(0x0f, 0x0a);
	resume_vector_ptr[0] = ((u32)(ulong)resume_vec);
	resume_vector_ptr[1] = 0;

	for (addr = &resume_start; addr < &resume_end; addr++)
		*resume_vec++ = *addr;

	if (state != 0) {
		/*
		 * Strictly speaking this is a firmware problem, but let's check
		 * for it as well...
		 */
		if (resumed != 1) {
			printf("Uh, resume vector visited %d times?\n", resumed);
			bad |= 2;
		}
		/*
		 * Port 92 bit 0 is cleared on system reset.  On a soft reset it
		 * is left to 1.  Use this to distinguish INIT from hard reset.
		 */
		if (resumed != 0 && (inb(0x92) & 1) == 0) {
			printf("Uh, hard reset!\n");
			bad |= 1;
		}
	}

	resumed = 0;

	switch (state++) {
	case 0:
		printf("testing port 92 init... ");
		outb(inb(0x92) & ~1, 0x92);
		outb(inb(0x92) | 1, 0x92);
		break;

	case 1:
		printf("testing kbd controller reset... ");
		kbd_cmd(KBD_CCMD_RESET);
		break;

	case 2:
		printf("testing kbd controller init... ");
		kbd_out(kbd_in() & ~1);
		break;

	case 3:
		printf("testing 0xcf9h init... ");
		outb(0, 0xcf9);
		outb(4, 0xcf9);
		break;

	case 4:
		printf("testing init to BSP... ");
		apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL
			      | APIC_DM_INIT, 0);
		break;

	case 5:
		exit(bad);
	}

	/* The resume code will get us back to main.  */
	asm("cli; hlt");
	__builtin_unreachable();
}

asm (
	".global resume_start\n"
	".global resume_end\n"
	".code16\n"
	"resume_start:\n"
	"incb %cs:0x2008\n"		// resumed++;
	"mov $0x0f, %al\n"		// rtc_out(0x0f, 0x00);
	"out %al, $0x70\n"
	"mov $0x00, %al\n"
	"out %al, $0x71\n"
	"jmp $0xffff, $0x0000\n"	// BIOS reset
	"resume_end:\n"
#ifdef __i386__
	".code32\n"
#else
	".code64\n"
#endif
    );
                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/x86/intel-iommu.c                                                   0000644 0000000 0000000 00000007615 00000000000 017001  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Intel IOMMU unit test.
 *
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Authors:
 *   Peter Xu <peterx@redhat.com>,
 *
 * This work is licensed under the terms of the GNU LGPL, version 2 or
 * later.
 */

#include "intel-iommu.h"
#include "pci-edu.h"
#include "x86/apic.h"

#define VTD_TEST_DMAR_4B ("DMAR 4B memcpy test")
#define VTD_TEST_IR_MSI ("IR MSI")
#define VTD_TEST_IR_IOAPIC ("IR IOAPIC")

static struct pci_edu_dev edu_dev;

static void vtd_test_dmar(void)
{
	struct pci_edu_dev *dev = &edu_dev;
	void *page = alloc_page();

	report_prefix_push("vtd_dmar");

#define DMA_TEST_WORD (0x12345678)
	/* Modify the first 4 bytes of the page */
	*(uint32_t *)page = DMA_TEST_WORD;

	/*
	 * Map the newly allocated page into IOVA address 0 (size 4K)
	 * of the device address space. Root entry and context entry
	 * will be automatically created when needed.
	 */
	vtd_map_range(dev->pci_dev.bdf, 0, virt_to_phys(page), PAGE_SIZE);

	/*
	 * DMA the first 4 bytes of the page to EDU device buffer
	 * offset 0.
	 */
	edu_dma(dev, 0, 4, 0, false);

	/*
	 * DMA the first 4 bytes of EDU device buffer into the page
	 * with offset 4 (so it'll be using 4-7 bytes).
	 */
	edu_dma(dev, 4, 4, 0, true);

	/*
	 * Check data match between 0-3 bytes and 4-7 bytes of the
	 * page.
	 */
	report(VTD_TEST_DMAR_4B, *((uint32_t *)page + 1) == DMA_TEST_WORD);

	free_page(page);

	report_prefix_pop();
}

static volatile bool edu_intr_recved;

static void edu_isr(isr_regs_t *regs)
{
	edu_intr_recved = true;
	eoi();
	edu_reg_writel(&edu_dev, EDU_REG_INTR_ACK,
			edu_reg_readl(&edu_dev, EDU_REG_INTR_STATUS));
}

static void vtd_test_ir(void)
{
#define VTD_TEST_VECTOR_IOAPIC (0xed)
#define VTD_TEST_VECTOR_MSI (0xee)
	struct pci_edu_dev *dev = &edu_dev;
	struct pci_dev *pci_dev = &dev->pci_dev;

	report_prefix_push("vtd_ir");

	irq_enable();

	/* This will enable INTx */
	pci_msi_set_enable(pci_dev, false);
	vtd_setup_ioapic_irq(pci_dev, VTD_TEST_VECTOR_IOAPIC,
			     0, TRIGGER_EDGE);
	handle_irq(VTD_TEST_VECTOR_IOAPIC, edu_isr);

	edu_intr_recved = false;
	wmb();
	/* Manually trigger INTR */
	edu_reg_writel(dev, EDU_REG_INTR_RAISE, 1);

	while (!edu_intr_recved)
		cpu_relax();

	/* Clear INTR bits */
	edu_reg_writel(dev, EDU_REG_INTR_RAISE, 0);

	/* We are good as long as we reach here */
	report(VTD_TEST_IR_IOAPIC, edu_intr_recved == true);

	/*
	 * Setup EDU PCI device MSI, using interrupt remapping. By
	 * default, EDU device is using INTx.
	 */
	if (!vtd_setup_msi(pci_dev, VTD_TEST_VECTOR_MSI, 0)) {
		printf("edu device does not support MSI, skip test\n");
		report_skip(VTD_TEST_IR_MSI);
		return;
	}

	handle_irq(VTD_TEST_VECTOR_MSI, edu_isr);

	edu_intr_recved = false;
	wmb();
	/* Manually trigger INTR */
	edu_reg_writel(dev, EDU_REG_INTR_RAISE, 1);

	while (!edu_intr_recved)
		cpu_relax();

	/* We are good as long as we reach here */
	report(VTD_TEST_IR_MSI, edu_intr_recved == true);

	report_prefix_pop();
}

int main(int argc, char *argv[])
{
	vtd_init();

	report_prefix_push("vtd_init");

	report("fault status check", vtd_readl(DMAR_FSTS_REG) == 0);
	report("QI enablement", vtd_readl(DMAR_GSTS_REG) & VTD_GCMD_QI);
	report("DMAR table setup", vtd_readl(DMAR_GSTS_REG) & VTD_GCMD_ROOT);
	report("IR table setup", vtd_readl(DMAR_GSTS_REG) & VTD_GCMD_IR_TABLE);
	report("DMAR enablement", vtd_readl(DMAR_GSTS_REG) & VTD_GCMD_DMAR);
	report("IR enablement", vtd_readl(DMAR_GSTS_REG) & VTD_GCMD_IR);
	report("DMAR support 39 bits address width",
	       vtd_readq(DMAR_CAP_REG) & VTD_CAP_SAGAW);
	report("DMAR support huge pages", vtd_readq(DMAR_CAP_REG) & VTD_CAP_SLLPS);

	report_prefix_pop();

	if (!edu_init(&edu_dev)) {
		printf("Please specify \"-device edu\" to do "
		       "further IOMMU tests.\n");
		report_skip(VTD_TEST_DMAR_4B);
		report_skip(VTD_TEST_IR_IOAPIC);
		report_skip(VTD_TEST_IR_MSI);
	} else {
		printf("Found EDU device:\n");
		pci_dev_print(&edu_dev.pci_dev);
		vtd_test_dmar();
		vtd_test_ir();
	}

	return report_summary();
}
                                                                                                                   source/v64/tests/kvm-unit-tests/x86/ioapic.c                                                        0000644 0000000 0000000 00000021534 00000000000 016002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "apic.h"
#include "vm.h"
#include "smp.h"
#include "desc.h"
#include "isr.h"

static void set_ioapic_redir(unsigned line, unsigned vec,
			     trigger_mode_t trig_mode)
{
	ioapic_redir_entry_t e = {
		.vector = vec,
		.delivery_mode = 0,
		.trig_mode = trig_mode,
	};

	ioapic_write_redir(line, e);
}

static void set_irq_line(unsigned line, int val)
{
	asm volatile("out %0, %1" : : "a"((u8)val), "d"((u16)(0x2000 + line)));
}

static void toggle_irq_line(unsigned line)
{
	set_irq_line(line, 1);
	set_irq_line(line, 0);
}

static void ioapic_reg_version(void)
{
	u8 version_offset;
	uint32_t data_read, data_write;

	version_offset = 0x01;
	data_read = ioapic_read_reg(version_offset);
	data_write = data_read ^ 0xffffffff;

	ioapic_write_reg(version_offset, data_write);
	report("version register read only test",
	       data_read == ioapic_read_reg(version_offset));
}

static void ioapic_reg_id(void)
{
	u8 id_offset;
	uint32_t data_read, data_write, diff;

	id_offset = 0x0;
	data_read = ioapic_read_reg(id_offset);
	data_write = data_read ^ 0xffffffff;

	ioapic_write_reg(id_offset, data_write);

	diff = data_read ^ ioapic_read_reg(id_offset);
	report("id register only bits [24:27] writable",
	       diff == 0x0f000000);
}

static void ioapic_arbitration_id(void)
{
	u8 id_offset, arb_offset;
	uint32_t write;

	id_offset = 0x0;
	arb_offset = 0x2;
	write = 0x0f000000;

	ioapic_write_reg(id_offset, write);
	report("arbitration register set by id",
	       ioapic_read_reg(arb_offset) == write);

	ioapic_write_reg(arb_offset, 0x0);
	report("arbtration register read only",
               ioapic_read_reg(arb_offset) == write);
}

static volatile int g_isr_76;

static void ioapic_isr_76(isr_regs_t *regs)
{
	++g_isr_76;
	eoi();
}

static void test_ioapic_edge_intr(void)
{
	handle_irq(0x76, ioapic_isr_76);
	set_ioapic_redir(0x0e, 0x76, TRIGGER_EDGE);
	toggle_irq_line(0x0e);
	asm volatile ("nop");
	report("edge triggered intr", g_isr_76 == 1);
}

static volatile int g_isr_77;

static void ioapic_isr_77(isr_regs_t *regs)
{
	++g_isr_77;
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_level_intr(void)
{
	handle_irq(0x77, ioapic_isr_77);
	set_ioapic_redir(0x0e, 0x77, TRIGGER_LEVEL);
	set_irq_line(0x0e, 1);
	asm volatile ("nop");
	report("level triggered intr", g_isr_77 == 1);
}

static int g_78, g_66, g_66_after_78;
static ulong g_66_rip, g_78_rip;

static void ioapic_isr_78(isr_regs_t *regs)
{
	++g_78;
	g_78_rip = regs->rip;
	eoi();
}

static void ioapic_isr_66(isr_regs_t *regs)
{
	++g_66;
	if (g_78)
		++g_66_after_78;
	g_66_rip = regs->rip;
	eoi();
}

static void test_ioapic_simultaneous(void)
{
	handle_irq(0x78, ioapic_isr_78);
	handle_irq(0x66, ioapic_isr_66);
	set_ioapic_redir(0x0e, 0x78, TRIGGER_EDGE);
	set_ioapic_redir(0x0f, 0x66, TRIGGER_EDGE);
	irq_disable();
	toggle_irq_line(0x0f);
	toggle_irq_line(0x0e);
	irq_enable();
	asm volatile ("nop");
	report("ioapic simultaneous edge interrupts",
	       g_66 && g_78 && g_66_after_78 && g_66_rip == g_78_rip);
}

static volatile int g_tmr_79 = -1;

static void ioapic_isr_79(isr_regs_t *regs)
{
	g_tmr_79 = apic_read_bit(APIC_TMR, 0x79);
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_edge_tmr(bool expected_tmr_before)
{
	int tmr_before;

	handle_irq(0x79, ioapic_isr_79);
	set_ioapic_redir(0x0e, 0x79, TRIGGER_EDGE);
	tmr_before = apic_read_bit(APIC_TMR, 0x79);
	toggle_irq_line(0x0e);
	asm volatile ("nop");
	report("TMR for ioapic edge interrupts (expected %s)",
	       tmr_before == expected_tmr_before && !g_tmr_79,
	       expected_tmr_before ? "true" : "false");
}

static void test_ioapic_level_tmr(bool expected_tmr_before)
{
	int tmr_before;

	handle_irq(0x79, ioapic_isr_79);
	set_ioapic_redir(0x0e, 0x79, TRIGGER_LEVEL);
	tmr_before = apic_read_bit(APIC_TMR, 0x79);
	set_irq_line(0x0e, 1);
	asm volatile ("nop");
	report("TMR for ioapic level interrupts (expected %s)",
	       tmr_before == expected_tmr_before && g_tmr_79,
	       expected_tmr_before ? "true" : "false");
}

#define IPI_DELAY 1000000

static void delay(int count)
{
	while(count--) asm("");
}

static void toggle_irq_line_0x0e(void *data)
{
	irq_disable();
	delay(IPI_DELAY);
	toggle_irq_line(0x0e);
	irq_enable();
}

static void test_ioapic_edge_tmr_smp(bool expected_tmr_before)
{
	int tmr_before;
	int i;

	g_tmr_79 = -1;
	handle_irq(0x79, ioapic_isr_79);
	set_ioapic_redir(0x0e, 0x79, TRIGGER_EDGE);
	tmr_before = apic_read_bit(APIC_TMR, 0x79);
	on_cpu_async(1, toggle_irq_line_0x0e, 0);
	i = 0;
	while(g_tmr_79 == -1) i++;
	printf("%d iterations before interrupt received\n", i);
	report("TMR for ioapic edge interrupts (expected %s)",
	       tmr_before == expected_tmr_before && !g_tmr_79,
	       expected_tmr_before ? "true" : "false");
}

static void set_irq_line_0x0e(void *data)
{
	irq_disable();
	delay(IPI_DELAY);
	set_irq_line(0x0e, 1);
	irq_enable();
}

static void test_ioapic_level_tmr_smp(bool expected_tmr_before)
{
	int i, tmr_before;

	g_tmr_79 = -1;
	handle_irq(0x79, ioapic_isr_79);
	set_ioapic_redir(0x0e, 0x79, TRIGGER_LEVEL);
	tmr_before = apic_read_bit(APIC_TMR, 0x79);
	on_cpu_async(1, set_irq_line_0x0e, 0);
	i = 0;
	while(g_tmr_79 == -1) i++;
	printf("%d iterations before interrupt received\n", i);
	report("TMR for ioapic level interrupts (expected %s)",
	       tmr_before == expected_tmr_before && g_tmr_79,
	       expected_tmr_before ? "true" : "false");
}

static int g_isr_98;

static void ioapic_isr_98(isr_regs_t *regs)
{
	++g_isr_98;
	if (g_isr_98 == 1) {
		set_irq_line(0x0e, 0);
		set_irq_line(0x0e, 1);
	}
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_level_coalesce(void)
{
	handle_irq(0x98, ioapic_isr_98);
	set_ioapic_redir(0x0e, 0x98, TRIGGER_LEVEL);
	set_irq_line(0x0e, 1);
	asm volatile ("nop");
	report("coalesce simultaneous level interrupts", g_isr_98 == 1);
}

static int g_isr_99;

static void ioapic_isr_99(isr_regs_t *regs)
{
	++g_isr_99;
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_level_sequential(void)
{
	handle_irq(0x99, ioapic_isr_99);
	set_ioapic_redir(0x0e, 0x99, TRIGGER_LEVEL);
	set_irq_line(0x0e, 1);
	set_irq_line(0x0e, 1);
	asm volatile ("nop");
	report("sequential level interrupts", g_isr_99 == 2);
}

static volatile int g_isr_9a;

static void ioapic_isr_9a(isr_regs_t *regs)
{
	++g_isr_9a;
	if (g_isr_9a == 2)
		set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_level_retrigger(void)
{
	int i;

	handle_irq(0x9a, ioapic_isr_9a);
	set_ioapic_redir(0x0e, 0x9a, TRIGGER_LEVEL);

	asm volatile ("cli");
	set_irq_line(0x0e, 1);

	for (i = 0; i < 10; i++) {
		if (g_isr_9a == 2)
			break;

		asm volatile ("sti; hlt; cli");
	}

	asm volatile ("sti");

	report("retriggered level interrupts without masking", g_isr_9a == 2);
}

static volatile int g_isr_81;

static void ioapic_isr_81(isr_regs_t *regs)
{
	++g_isr_81;
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_edge_mask(void)
{
	handle_irq(0x81, ioapic_isr_81);
	set_ioapic_redir(0x0e, 0x81, TRIGGER_EDGE);

	set_mask(0x0e, true);
	set_irq_line(0x0e, 1);
	set_irq_line(0x0e, 0);

	asm volatile ("nop");
	report("masked level interrupt", g_isr_81 == 0);

	set_mask(0x0e, false);
	set_irq_line(0x0e, 1);

	asm volatile ("nop");
	report("unmasked level interrupt", g_isr_81 == 1);
}

static volatile int g_isr_82;

static void ioapic_isr_82(isr_regs_t *regs)
{
	++g_isr_82;
	set_irq_line(0x0e, 0);
	eoi();
}

static void test_ioapic_level_mask(void)
{
	handle_irq(0x82, ioapic_isr_82);
	set_ioapic_redir(0x0e, 0x82, TRIGGER_LEVEL);

	set_mask(0x0e, true);
	set_irq_line(0x0e, 1);

	asm volatile ("nop");
	report("masked level interrupt", g_isr_82 == 0);

	set_mask(0x0e, false);

	asm volatile ("nop");
	report("unmasked level interrupt", g_isr_82 == 1);
}

static volatile int g_isr_83;

static void ioapic_isr_83(isr_regs_t *regs)
{
	++g_isr_83;
	set_mask(0x0e, true);
	eoi();
}

static void test_ioapic_level_retrigger_mask(void)
{
	handle_irq(0x83, ioapic_isr_83);
	set_ioapic_redir(0x0e, 0x83, TRIGGER_LEVEL);

	set_irq_line(0x0e, 1);
	asm volatile ("nop");
	set_mask(0x0e, false);
	asm volatile ("nop");
	report("retriggered level interrupts with mask", g_isr_83 == 2);

	set_irq_line(0x0e, 0);
	set_mask(0x0e, false);
}


int main(void)
{
	setup_vm();
	smp_init();

	mask_pic_interrupts();

	if (enable_x2apic())
		printf("x2apic enabled\n");
	else
		printf("x2apic not detected\n");

	irq_enable();

	ioapic_reg_version();
	ioapic_reg_id();
	ioapic_arbitration_id();

	test_ioapic_edge_intr();
	test_ioapic_level_intr();
	test_ioapic_simultaneous();

	test_ioapic_level_coalesce();
	test_ioapic_level_sequential();
	test_ioapic_level_retrigger();

	test_ioapic_edge_mask();
	test_ioapic_level_mask();
	test_ioapic_level_retrigger_mask();

	test_ioapic_edge_tmr(false);
	test_ioapic_level_tmr(false);
	test_ioapic_level_tmr(true);
	test_ioapic_edge_tmr(true);

	if (cpu_count() > 1) {
		test_ioapic_edge_tmr_smp(false);
		test_ioapic_level_tmr_smp(false);
		test_ioapic_level_tmr_smp(true);
		test_ioapic_edge_tmr_smp(true);
	}

	return report_summary();
}
                                                                                                                                                                    source/v64/tests/kvm-unit-tests/x86/ioram.h                                                         0000644 0000000 0000000 00000000166 00000000000 015650  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __IO_RAM_H
#define __IO_RAM_H

#define IORAM_BASE_PHYS 0xff000000UL
#define IORAM_LEN       0x10000UL

#endif
                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/kvm-unit-tests/x86/kvmclock.c                                                      0000644 0000000 0000000 00000015442 00000000000 016350  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "smp.h"
#include "atomic.h"
#include "processor.h"
#include "kvmclock.h"
#include "asm/barrier.h"

#define unlikely(x)	__builtin_expect(!!(x), 0)
#define likely(x)	__builtin_expect(!!(x), 1)


struct pvclock_vcpu_time_info __attribute__((aligned(4))) hv_clock[MAX_CPU];
struct pvclock_wall_clock wall_clock;
static unsigned char valid_flags = 0;
static atomic64_t last_value = ATOMIC64_INIT(0);

/*
 * Scale a 64-bit delta by scaling and multiplying by a 32-bit fraction,
 * yielding a 64-bit result.
 */
static inline u64 scale_delta(u64 delta, u32 mul_frac, int shift)
{
	u64 product;
#ifdef __i386__
	u32 tmp1, tmp2;
#endif

	if (shift < 0)
		delta >>= -shift;
	else
		delta <<= shift;

#ifdef __i386__
	__asm__ (
		"mul  %5       ; "
		"mov  %4,%%eax ; "
		"mov  %%edx,%4 ; "
		"mul  %5       ; "
		"xor  %5,%5    ; "
		"add  %4,%%eax ; "
		"adc  %5,%%edx ; "
		: "=A" (product), "=r" (tmp1), "=r" (tmp2)
		: "a" ((u32)delta), "1" ((u32)(delta >> 32)), "2" (mul_frac) );
#elif defined(__x86_64__)
	__asm__ (
		"mul %%rdx ; shrd $32,%%rdx,%%rax"
		: "=a" (product) : "0" (delta), "d" ((u64)mul_frac) );
#else
#error implement me!
#endif

	return product;
}

#ifdef __i386__
# define do_div(n,base) ({					\
	u32 __base = (base);    				\
	u32 __rem;						\
	__rem = ((u64)(n)) % __base;                            \
	(n) = ((u64)(n)) / __base;				\
	__rem;							\
 })
#else
u32 __attribute__((weak)) __div64_32(u64 *n, u32 base)
{
	u64 rem = *n;
	u64 b = base;
	u64 res, d = 1;
	u32 high = rem >> 32;

	/* Reduce the thing a bit first */
	res = 0;
	if (high >= base) {
		high /= base;
		res = (u64) high << 32;
		rem -= (u64) (high*base) << 32;
	}

	while ((s64)b > 0 && b < rem) {
		b = b+b;
		d = d+d;
	}

	do {
		if (rem >= b) {
			rem -= b;
			res += d;
		}
		b >>= 1;
		d >>= 1;
	} while (d);

	*n = res;
	return rem;
}

# define do_div(n,base) ({				\
	u32 __base = (base);    			\
	u32 __rem;					\
	(void)(((typeof((n)) *)0) == ((u64 *)0));	\
	if (likely(((n) >> 32) == 0)) {			\
		__rem = (u32)(n) % __base;		\
		(n) = (u32)(n) / __base;		\
	} else 						\
		__rem = __div64_32(&(n), __base);	\
	__rem;						\
 })
#endif

/**
 * set_normalized_timespec - set timespec sec and nsec parts and normalize
 *
 * @ts:		pointer to timespec variable to be set
 * @sec:	seconds to set
 * @nsec:	nanoseconds to set
 *
 * Set seconds and nanoseconds field of a timespec variable and
 * normalize to the timespec storage format
 *
 * Note: The tv_nsec part is always in the range of
 *	0 <= tv_nsec < NSEC_PER_SEC
 * For negative values only the tv_sec field is negative !
 */
void set_normalized_timespec(struct timespec *ts, long sec, s64 nsec)
{
	while (nsec >= NSEC_PER_SEC) {
		/*
		 * The following asm() prevents the compiler from
		 * optimising this loop into a modulo operation. See
		 * also __iter_div_u64_rem() in include/linux/time.h
		 */
		asm("" : "+rm"(nsec));
		nsec -= NSEC_PER_SEC;
		++sec;
	}
	while (nsec < 0) {
		asm("" : "+rm"(nsec));
		nsec += NSEC_PER_SEC;
		--sec;
	}
	ts->tv_sec = sec;
	ts->tv_nsec = nsec;
}

static inline
unsigned pvclock_read_begin(const struct pvclock_vcpu_time_info *src)
{
	unsigned version = src->version & ~1;
	/* Make sure that the version is read before the data. */
	smp_rmb();
	return version;
}

static inline
bool pvclock_read_retry(const struct pvclock_vcpu_time_info *src,
			unsigned version)
{
	/* Make sure that the version is re-read after the data. */
	smp_rmb();
	return version != src->version;
}

static inline u64 rdtsc_ordered()
{
	/*
	 * FIXME: on Intel CPUs rmb() aka lfence is sufficient which brings up
	 * to 2x speedup
	 */
	mb();
	return rdtsc();
}

static inline
cycle_t __pvclock_read_cycles(const struct pvclock_vcpu_time_info *src)
{
	u64 delta = rdtsc_ordered() - src->tsc_timestamp;
	cycle_t offset = scale_delta(delta, src->tsc_to_system_mul,
					     src->tsc_shift);
	return src->system_time + offset;
}

cycle_t pvclock_clocksource_read(struct pvclock_vcpu_time_info *src)
{
	unsigned version;
	cycle_t ret;
	u64 last;
	u8 flags;

	do {
		version = pvclock_read_begin(src);
		ret = __pvclock_read_cycles(src);
		flags = src->flags;
	} while (pvclock_read_retry(src, version));

	if ((valid_flags & PVCLOCK_RAW_CYCLE_BIT) ||
            ((valid_flags & PVCLOCK_TSC_STABLE_BIT) &&
             (flags & PVCLOCK_TSC_STABLE_BIT)))
                return ret;

	/*
	 * Assumption here is that last_value, a global accumulator, always goes
	 * forward. If we are less than that, we should not be much smaller.
	 * We assume there is an error marging we're inside, and then the correction
	 * does not sacrifice accuracy.
	 *
	 * For reads: global may have changed between test and return,
	 * but this means someone else updated poked the clock at a later time.
	 * We just need to make sure we are not seeing a backwards event.
	 *
	 * For updates: last_value = ret is not enough, since two vcpus could be
	 * updating at the same time, and one of them could be slightly behind,
	 * making the assumption that last_value always go forward fail to hold.
	 */
	last = atomic64_read(&last_value);
	do {
		if (ret < last)
			return last;
		last = atomic64_cmpxchg(&last_value, last, ret);
	} while (unlikely(last != ret));

	return ret;
}

cycle_t kvm_clock_read()
{
        struct pvclock_vcpu_time_info *src;
        cycle_t ret;
        int index = smp_id();

        src = &hv_clock[index];
        ret = pvclock_clocksource_read(src);
        return ret;
}

void kvm_clock_init(void *data)
{
        int index = smp_id();
        struct pvclock_vcpu_time_info *hvc = &hv_clock[index];

        printf("kvm-clock: cpu %d, msr %p\n", index, hvc);
        wrmsr(MSR_KVM_SYSTEM_TIME_NEW, (unsigned long)hvc | 1);
}

void kvm_clock_clear(void *data)
{
        wrmsr(MSR_KVM_SYSTEM_TIME_NEW, 0LL);
}

void pvclock_read_wallclock(struct pvclock_wall_clock *wall_clock,
			    struct pvclock_vcpu_time_info *vcpu_time,
			    struct timespec *ts)
{
	u32 version;
	u64 delta;
	struct timespec now;

	/* get wallclock at system boot */
	do {
		version = wall_clock->version;
		rmb();		/* fetch version before time */
		now.tv_sec  = wall_clock->sec;
		now.tv_nsec = wall_clock->nsec;
		rmb();		/* fetch time before checking version */
	} while ((wall_clock->version & 1) || (version != wall_clock->version));

	delta = pvclock_clocksource_read(vcpu_time);	/* time since system boot */
	delta += now.tv_sec * (u64)NSEC_PER_SEC + now.tv_nsec;

	now.tv_nsec = do_div(delta, NSEC_PER_SEC);
	now.tv_sec = delta;

	set_normalized_timespec(ts, now.tv_sec, now.tv_nsec);
}

void kvm_get_wallclock(struct timespec *ts)
{
        struct pvclock_vcpu_time_info *vcpu_time;
        int index = smp_id();

        wrmsr(MSR_KVM_WALL_CLOCK_NEW, (unsigned long)&wall_clock);
        vcpu_time = &hv_clock[index];
        pvclock_read_wallclock(&wall_clock, vcpu_time, ts);
}

void pvclock_set_flags(unsigned char flags)
{
        valid_flags = flags;
}
                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/x86/kvmclock.h                                                      0000644 0000000 0000000 00000001573 00000000000 016355  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef KVMCLOCK_H
#define KVMCLOCK_H

#define MSR_KVM_WALL_CLOCK_NEW  0x4b564d00
#define MSR_KVM_SYSTEM_TIME_NEW 0x4b564d01

#define MAX_CPU 64

#define PVCLOCK_TSC_STABLE_BIT (1 << 0)
#define PVCLOCK_RAW_CYCLE_BIT (1 << 7) /* Get raw cycle */

# define NSEC_PER_SEC			1000000000ULL

typedef u64 cycle_t;

struct pvclock_vcpu_time_info {
	u32   version;
	u32   pad0;
	u64   tsc_timestamp;
	u64   system_time;
	u32   tsc_to_system_mul;
	s8    tsc_shift;
	u8    flags;
	u8    pad[2];
} __attribute__((__packed__)); /* 32 bytes */

struct pvclock_wall_clock {
	u32   version;
	u32   sec;
	u32   nsec;
} __attribute__((__packed__));

struct timespec {
        long   tv_sec;
        long   tv_nsec;
};

void pvclock_set_flags(unsigned char flags);
cycle_t kvm_clock_read();
void kvm_get_wallclock(struct timespec *ts);
void kvm_clock_init(void *data);
void kvm_clock_clear(void *data);

#endif
                                                                                                                                     source/v64/tests/kvm-unit-tests/x86/kvmclock_test.c                                                 0000644 0000000 0000000 00000011100 00000000000 017372  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "smp.h"
#include "atomic.h"
#include "processor.h"
#include "kvmclock.h"

#define DEFAULT_TEST_LOOPS 100000000L
#define DEFAULT_THRESHOLD  5L

long loops = DEFAULT_TEST_LOOPS;
long sec = 0;
long threshold = DEFAULT_THRESHOLD;

struct test_info {
        struct spinlock lock;
        u64 warps;                /* warp count */
        u64 stalls;               /* stall count */
        long long worst;          /* worst warp */
        volatile cycle_t last;    /* last cycle seen by test */
        int check;                /* check cycle ? */
};

struct test_info ti[4];

static void wallclock_test(void *data)
{
        int *p_err = data;
        long ksec, offset;
        struct timespec ts;

        kvm_get_wallclock(&ts);
        ksec = ts.tv_sec;

        offset = ksec - sec;
        printf("Raw nanoseconds value from kvmclock: %" PRIu64 " (cpu %d)\n", kvm_clock_read(), smp_id());
        printf("Seconds get from kvmclock: %ld (cpu %d, offset: %ld)\n", ksec, smp_id(), offset);

        if (offset > threshold || offset < -threshold) {
                printf("offset too large!\n");
                (*p_err)++;
        }
}

static void kvm_clock_test(void *data)
{
        struct test_info *hv_test_info = (struct test_info *)data;
        long i, check = hv_test_info->check;

        for (i = 0; i < loops; i++){
                cycle_t t0, t1;
                long long delta;

                if (check == 0) {
                        kvm_clock_read();
                        continue;
                }

                spin_lock(&hv_test_info->lock);
                t1 = kvm_clock_read();
                t0 = hv_test_info->last;
                hv_test_info->last = kvm_clock_read();
                spin_unlock(&hv_test_info->lock);

                delta = t1 - t0;
                if (delta < 0) {
                        spin_lock(&hv_test_info->lock);
                        ++hv_test_info->warps;
                        if (delta < hv_test_info->worst){
                                hv_test_info->worst = delta;
                                printf("Worst warp %lld\n", hv_test_info->worst);
                        }
                        spin_unlock(&hv_test_info->lock);
                }
                if (delta == 0)
                        ++hv_test_info->stalls;

                if (!((unsigned long)i & 31))
                        asm volatile("rep; nop");
        }
}

static int cycle_test(int check, struct test_info *ti)
{
        unsigned long long begin, end;

        begin = rdtsc();

        ti->check = check;
        on_cpus(kvm_clock_test, ti);

        end = rdtsc();

        printf("Total vcpus: %d\n", cpu_count());
        printf("Test  loops: %ld\n", loops);
        if (check == 1) {
                printf("Total warps:  %" PRId64 "\n", ti->warps);
                printf("Total stalls: %" PRId64 "\n", ti->stalls);
                printf("Worst warp:   %lld\n", ti->worst);
        } else
                printf("TSC cycles:  %lld\n", end - begin);

        return ti->warps ? 1 : 0;
}

int main(int ac, char **av)
{
        int nerr = 0;
        int ncpus;
        int i;

        if (ac > 1)
                loops = atol(av[1]);
        if (ac > 2)
                sec = atol(av[2]);
        if (ac > 3)
                threshold = atol(av[3]);

        smp_init();

        ncpus = cpu_count();
        if (ncpus > MAX_CPU)
                report_abort("number cpus exceeds %d", MAX_CPU);

        on_cpus(kvm_clock_init, NULL);

        if (ac > 2) {
                printf("Wallclock test, threshold %ld\n", threshold);
                printf("Seconds get from host:     %ld\n", sec);
                for (i = 0; i < ncpus; ++i)
                        on_cpu(i, wallclock_test, &nerr);
        }

        printf("Check the stability of raw cycle ...\n");
        pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT
                          | PVCLOCK_RAW_CYCLE_BIT);
        if (cycle_test(1, &ti[0]))
                printf("Raw cycle is not stable\n");
        else
                printf("Raw cycle is stable\n");

        pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT);
        printf("Monotonic cycle test:\n");
        nerr += cycle_test(1, &ti[1]);

        printf("Measure the performance of raw cycle ...\n");
        pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT
                          | PVCLOCK_RAW_CYCLE_BIT);
        cycle_test(0, &ti[2]);

        printf("Measure the performance of adjusted cycle ...\n");
        pvclock_set_flags(PVCLOCK_TSC_STABLE_BIT);
        cycle_test(0, &ti[3]);

        on_cpus(kvm_clock_clear, NULL);

        return nerr > 0 ? 1 : 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/kvm-unit-tests/x86/memory.c                                                        0000644 0000000 0000000 00000003607 00000000000 016047  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Test for x86 cache and memory instructions
 *
 * Copyright (c) 2015 Red Hat Inc
 *
 * Authors:
 *  Eduardo Habkost <ehabkost@redhat.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.
 */

#include "libcflat.h"
#include "desc.h"
#include "processor.h"

static long target;
static volatile int ud;
static volatile int isize;

static void handle_ud(struct ex_regs *regs)
{
	ud = 1;
	regs->rip += isize;
}

int main(int ac, char **av)
{
	struct cpuid cpuid7, cpuid1;
	int xfail;

	setup_idt();
	handle_exception(UD_VECTOR, handle_ud);

	cpuid1 = cpuid(1);
	cpuid7 = cpuid_indexed(7, 0);

	/* 3-byte instructions: */
	isize = 3;

	xfail = !(cpuid1.d & (1U << 19)); /* CLFLUSH */
	ud = 0;
	asm volatile("clflush (%0)" : : "b" (&target));
	report_xfail("clflush", xfail, ud == 0);

	xfail = !(cpuid1.d & (1U << 25)); /* SSE */
	ud = 0;
	asm volatile("sfence");
	report_xfail("sfence", xfail, ud == 0);

	xfail = !(cpuid1.d & (1U << 26)); /* SSE2 */
	ud = 0;
	asm volatile("lfence");
	report_xfail("lfence", xfail, ud == 0);

	ud = 0;
	asm volatile("mfence");
	report_xfail("mfence", xfail, ud == 0);

	/* 4-byte instructions: */
	isize = 4;

	xfail = !(cpuid7.b & (1U << 23)); /* CLFLUSHOPT */
	ud = 0;
	/* clflushopt (%rbx): */
	asm volatile(".byte 0x66, 0x0f, 0xae, 0x3b" : : "b" (&target));
	report_xfail("clflushopt", xfail, ud == 0);

	xfail = !(cpuid7.b & (1U << 24)); /* CLWB */
	ud = 0;
	/* clwb (%rbx): */
	asm volatile(".byte 0x66, 0x0f, 0xae, 0x33" : : "b" (&target));
	report_xfail("clwb", xfail, ud == 0);

	ud = 0;
	/* clwb requires a memory operand, the following is NOT a valid
	 * CLWB instruction (modrm == 0xF0).
	 */
	asm volatile(".byte 0x66, 0x0f, 0xae, 0xf0");
	report("fake clwb", ud);

	xfail = !(cpuid7.b & (1U << 22)); /* PCOMMIT */
	ud = 0;
	/* pcommit: */
	asm volatile(".byte 0x66, 0x0f, 0xae, 0xf8");
	report_xfail("pcommit", xfail, ud == 0);

	return report_summary();
}
                                                                                                                         source/v64/tests/kvm-unit-tests/x86/msr.c                                                           0000644 0000000 0000000 00000006640 00000000000 015340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* msr tests */

#include "libcflat.h"
#include "processor.h"
#include "msr.h"

struct msr_info {
    int index;
    const char *name;
    struct tc {
        int valid;
        unsigned long long value;
        unsigned long long expected;
    } val_pairs[20];
};


#define addr_64 0x0000123456789abcULL

struct msr_info msr_info[] =
{
    { .index = 0x00000174, .name = "IA32_SYSENTER_CS",
      .val_pairs = {{ .valid = 1, .value = 0x1234, .expected = 0x1234}}
    },
    { .index = 0x00000175, .name = "MSR_IA32_SYSENTER_ESP",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0x00000176, .name = "IA32_SYSENTER_EIP",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0x000001a0, .name = "MSR_IA32_MISC_ENABLE",
      // reserved: 1:2, 4:6, 8:10, 13:15, 17, 19:21, 24:33, 35:63
      .val_pairs = {{ .valid = 1, .value = 0x400c51889, .expected = 0x400c51889}}
    },
    { .index = 0x00000277, .name = "MSR_IA32_CR_PAT",
      .val_pairs = {{ .valid = 1, .value = 0x07070707, .expected = 0x07070707}}
    },
    { .index = 0xc0000100, .name = "MSR_FS_BASE",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0xc0000101, .name = "MSR_GS_BASE",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0xc0000102, .name = "MSR_KERNEL_GS_BASE",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
#ifdef __x86_64__
    { .index = 0xc0000080, .name = "MSR_EFER",
      .val_pairs = {{ .valid = 1, .value = 0xD00, .expected = 0xD00}}
    },
#endif
    { .index = 0xc0000082, .name = "MSR_LSTAR",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0xc0000083, .name = "MSR_CSTAR",
      .val_pairs = {{ .valid = 1, .value = addr_64, .expected = addr_64}}
    },
    { .index = 0xc0000084, .name = "MSR_SYSCALL_MASK",
      .val_pairs = {{ .valid = 1, .value = 0xffffffff, .expected = 0xffffffff}}
    },

//    MSR_IA32_DEBUGCTLMSR needs svm feature LBRV
//    MSR_VM_HSAVE_PA only AMD host
};

static int find_msr_info(int msr_index)
{
    int i;
    for (i = 0; i < sizeof(msr_info)/sizeof(msr_info[0]) ; i++) {
        if (msr_info[i].index == msr_index) {
            return i;
        }
    }
    return -1;
}

static void test_msr_rw(int msr_index, unsigned long long input, unsigned long long expected)
{
    unsigned long long r = 0;
    int index;
    const char *sptr;
    if ((index = find_msr_info(msr_index)) != -1) {
        sptr = msr_info[index].name;
    } else {
        printf("couldn't find name for msr # %#x, skipping\n", msr_index);
        return;
    }
    wrmsr(msr_index, input);
    r = rdmsr(msr_index);
    if (expected != r) {
        printf("testing %s: output = %#x:%#x expected = %#x:%#x\n", sptr,
               (u32)(r >> 32), (u32)r, (u32)(expected >> 32), (u32)expected);
    }
    report("%s", expected == r, sptr);
}

int main(int ac, char **av)
{
    int i, j;
    for (i = 0 ; i < sizeof(msr_info) / sizeof(msr_info[0]); i++) {
        for (j = 0; j < sizeof(msr_info[i].val_pairs) / sizeof(msr_info[i].val_pairs[0]); j++) {
            if (msr_info[i].val_pairs[j].valid) {
                test_msr_rw(msr_info[i].index, msr_info[i].val_pairs[j].value, msr_info[i].val_pairs[j].expected);
            } else {
                break;
            }
        }
    }

    return report_summary();
}

                                                                                                source/v64/tests/kvm-unit-tests/x86/pae.c                                                           0000644 0000000 0000000 00000006074 00000000000 015305  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Simple PAE paging test. See lib/x86/vm.c for similar code which sets up
 * non-PAE paging. */

#include "fwcfg.h"
#include "asm/page.h"
#include "processor.h"

#ifdef __x86_64__
#error This test is 32-bit only.
#endif

#define HUGE_PAGE_SIZE (1UL << 21)

uint64_t pdpt[4] __attribute__((aligned(0x20)));
uint64_t page_dirs[4 * 512] __attribute__((aligned(0x1000)));
uint64_t page_tables[512 * 512] __attribute__((aligned(0x1000)));

static bool is_pae_supported(void) {
    struct cpuid c = cpuid(1);
    return c.d & (1 << 6);
}

/* Fill page directory at `pd` with huge page entries. */
static void setup_pd_huge_pages(uint64_t *pd, uint64_t start, uint64_t end) {
    uint64_t phys = start;
    for (unsigned int i = 0; i < 512; i++) {
        *pd++ = phys | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK |
            PT_PAGE_SIZE_MASK;

        phys += HUGE_PAGE_SIZE;
        if (phys >= end)
            return;
    }
}

/* Fill page directory at `pd` with page table entries, and use memory at `pt`
 * to create page tables. */
static void setup_pd(uint64_t *pd, uint64_t *pt, uint64_t start, uint64_t end) {
    uint64_t phys = start;
    for (unsigned int i = 0; i < 512; i++) {
        *pd++ = (uint32_t)pt | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
        for (unsigned int j = 0; j < 512; j++) {
            *pt++ = phys | PT_PRESENT_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
            phys += PAGE_SIZE;
            if (phys >= end)
                return;
        }
    }
}

static void setup_mmu(void) {
    uint64_t mem_size = fwcfg_get_u64(FW_CFG_RAM_SIZE);
    if (mem_size > (1ULL << 32))
        mem_size = 1ULL << 32;

    /* Map physical memory at 0000_0000 using huge pages */
    pdpt[0] = (uint32_t)&page_dirs[0 * 512] | PT_PRESENT_MASK;
    setup_pd_huge_pages(&page_dirs[0 * 512], 0, mem_size);

    /* Map physical memory at 4000_0000 using huge pages */
    pdpt[1] = (uint32_t)&page_dirs[1 * 512] | PT_PRESENT_MASK;
    setup_pd_huge_pages(&page_dirs[1 * 512], 0, mem_size);

    /* Map physical memory at 8000_0000 using huge pages */
    pdpt[2] = (uint32_t)&page_dirs[2 * 512] | PT_PRESENT_MASK;
    setup_pd_huge_pages(&page_dirs[2 * 512], 0, mem_size);

    /* Map physical memory at C000_0000 using normal tables */
    pdpt[3] = (uint32_t)&page_dirs[3 * 512] | PT_PRESENT_MASK;
    setup_pd(&page_dirs[3 * 512], &page_tables[0], 0, mem_size);

    write_cr0(0);
    write_cr4(read_cr4() | X86_CR4_PAE);
    write_cr3((uint32_t)pdpt);
    write_cr0(X86_CR0_PG | X86_CR0_PE | X86_CR0_WP);

    printf("paging enabled\n");
}

int main(void)
{
    if (!is_pae_supported()) {
        printf("PAE not supported\n");
        return 1;
    }
    printf("PAE supported\n");
    setup_mmu();

    volatile unsigned int test;
    for (int i = 1; i < 4; i++) {
        volatile unsigned int *ptr = (unsigned int*)((uint32_t)&test + (i << 30));
        printf("writing %u to %p, and reading from %p\n", i, ptr, &test);
        *ptr = i;
        if (test != i) {
            printf("error, got %u\n", i);
            return 1;
        }
    }
    printf("everything OK\n");
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/kvm-unit-tests/x86/pcid.c                                                          0000644 0000000 0000000 00000007303 00000000000 015453  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Basic PCID & INVPCID functionality test */

#include "libcflat.h"
#include "processor.h"
#include "desc.h"

#define X86_FEATURE_PCID       (1 << 17)
#define X86_FEATURE_INVPCID    (1 << 10)

struct invpcid_desc {
    unsigned long pcid : 12;
    unsigned long rsv  : 52;
    unsigned long addr : 64;
};

int write_cr0_checking(unsigned long val)
{
    asm volatile(ASM_TRY("1f")
                 "mov %0, %%cr0\n\t"
                 "1:": : "r" (val));
    return exception_vector();
}

int write_cr4_checking(unsigned long val)
{
    asm volatile(ASM_TRY("1f")
                 "mov %0, %%cr4\n\t"
                 "1:": : "r" (val));
    return exception_vector();
}

int invpcid_checking(unsigned long type, void *desc)
{
    asm volatile (ASM_TRY("1f")
                  ".byte 0x66,0x0f,0x38,0x82,0x18 \n\t" /* invpcid (%rax), %rbx */
                  "1:" : : "a" (desc), "b" (type));
    return exception_vector();
}

void test_cpuid_consistency(int pcid_enabled, int invpcid_enabled)
{
    int passed = !(!pcid_enabled && invpcid_enabled);
    report("CPUID consistency", passed);
}

void test_pcid_enabled(void)
{
    int passed = 0;
    ulong cr0 = read_cr0(), cr3 = read_cr3(), cr4 = read_cr4();

    /* try setting CR4.PCIDE, no exception expected */
    if (write_cr4_checking(cr4 | X86_CR4_PCIDE) != 0)
        goto report;

    /* try clearing CR0.PG when CR4.PCIDE=1, #GP expected */
    if (write_cr0_checking(cr0 & ~X86_CR0_PG) != GP_VECTOR)
        goto report;

    write_cr4(cr4);

    /* try setting CR4.PCIDE when CR3[11:0] != 0 , #GP expected */
    write_cr3(cr3 | 0x001);
    if (write_cr4_checking(cr4 | X86_CR4_PCIDE) != GP_VECTOR)
        goto report;
    write_cr3(cr3);

    passed = 1;

report:
    report("Test on PCID when enabled", passed);
}

void test_pcid_disabled(void)
{
    int passed = 0;
    ulong cr4 = read_cr4();

    /* try setting CR4.PCIDE, #GP expected */
    if (write_cr4_checking(cr4 | X86_CR4_PCIDE) != GP_VECTOR)
        goto report;

    passed = 1;

report:
    report("Test on PCID when disabled", passed);
}

void test_invpcid_enabled(void)
{
    int passed = 0;
    ulong cr4 = read_cr4();
    struct invpcid_desc desc;
    desc.rsv = 0;

    /* try executing invpcid when CR4.PCIDE=0, desc.pcid=0 and type=1
     * no exception expected
     */
    desc.pcid = 0;
    if (invpcid_checking(1, &desc) != 0)
        goto report;

    /* try executing invpcid when CR4.PCIDE=0, desc.pcid=1 and type=1
     * #GP expected
     */
    desc.pcid = 1;
    if (invpcid_checking(1, &desc) != GP_VECTOR)
        goto report;

    if (write_cr4_checking(cr4 | X86_CR4_PCIDE) != 0)
        goto report;

    /* try executing invpcid when CR4.PCIDE=1
     * no exception expected
     */
    desc.pcid = 10;
    if (invpcid_checking(2, &desc) != 0)
        goto report;

    passed = 1;

report:
    report("Test on INVPCID when enabled", passed);
}

void test_invpcid_disabled(void)
{
    int passed = 0;
    struct invpcid_desc desc;

    /* try executing invpcid, #UD expected */
    if (invpcid_checking(2, &desc) != UD_VECTOR)
        goto report;

    passed = 1;

report:
    report("Test on INVPCID when disabled", passed);
}

int main(int ac, char **av)
{
    struct cpuid _cpuid;
    int pcid_enabled = 0, invpcid_enabled = 0;

    setup_idt();

    _cpuid = cpuid(1);
    if (_cpuid.c & X86_FEATURE_PCID)
        pcid_enabled = 1;
    _cpuid = cpuid_indexed(7, 0);
    if (_cpuid.b & X86_FEATURE_INVPCID)
        invpcid_enabled = 1;

    test_cpuid_consistency(pcid_enabled, invpcid_enabled);

    if (pcid_enabled)
        test_pcid_enabled();
    else
        test_pcid_disabled();

    if (invpcid_enabled)
        test_invpcid_enabled();
    else
        test_invpcid_disabled();

    return report_summary();
}
                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/x86/pku.c                                                           0000644 0000000 0000000 00000007011 00000000000 015327  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "x86/desc.h"
#include "x86/processor.h"
#include "x86/vm.h"
#include "x86/msr.h"

#define X86_FEATURE_PKU  3
#define CR0_WP_MASK      (1UL << 16)
#define PTE_PKEY_BIT     59
#define USER_BASE        (1 << 24)
#define USER_VAR(v)      (*((__typeof__(&(v))) (((unsigned long)&v) + USER_BASE)))

volatile int pf_count = 0;
volatile unsigned save;
volatile unsigned test;

void set_cr0_wp(int wp)
{
    unsigned long cr0 = read_cr0();

    cr0 &= ~CR0_WP_MASK;
    if (wp)
        cr0 |= CR0_WP_MASK;
    write_cr0(cr0);
}

void do_pf_tss(unsigned long error_code)
{
    pf_count++;
    save = test;
    write_pkru(0);
}

extern void pf_tss(void);

asm ("pf_tss: \n\t"
#ifdef __x86_64__
    // no task on x86_64, save/restore caller-save regs
    "push %rax; push %rcx; push %rdx; push %rsi; push %rdi\n"
    "push %r8; push %r9; push %r10; push %r11\n"
#endif
    "call do_pf_tss \n\t"
#ifdef __x86_64__
    "pop %r11; pop %r10; pop %r9; pop %r8\n"
    "pop %rdi; pop %rsi; pop %rdx; pop %rcx; pop %rax\n"
#endif
    "add $"S", %"R "sp\n\t" // discard error code
    "iret"W" \n\t"
    "jmp pf_tss\n\t"
    );

static void init_test()
{
    pf_count = 0;

    invlpg(&test);
    invlpg(&USER_VAR(test));
    write_pkru(0);
    set_cr0_wp(0);
}

int main(int ac, char **av)
{
    unsigned long i;
    unsigned int pkey = 0x2;
    unsigned int pkru_ad = 0x10;
    unsigned int pkru_wd = 0x20;

    if (!(cpuid_indexed(7, 0).c & (1 << X86_FEATURE_PKU))) {
        printf("PKU not enabled\n");
        return report_summary();
    }

    setup_vm();
    setup_alt_stack();
    set_intr_alt_stack(14, pf_tss);
    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_LMA);

    for (i = 0; i < USER_BASE; i += PAGE_SIZE) {
        *get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) &= ~PT_USER_MASK;
        *get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) |= ((unsigned long)pkey << PTE_PKEY_BIT);
        invlpg((void *)i);
    }

    for (i = USER_BASE; i < 2 * USER_BASE; i += PAGE_SIZE) {
        *get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) &= ~USER_BASE;
        *get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) |= ((unsigned long)pkey << PTE_PKEY_BIT);
        invlpg((void *)i);
    }

    write_cr4(read_cr4() | X86_CR4_PKE);
    write_cr3(read_cr3());

    init_test();
    set_cr0_wp(1);
    write_pkru(pkru_ad);
    test = 21;
    report("write to supervisor page when pkru is ad and wp == 1", pf_count == 0 && test == 21);

    init_test();
    set_cr0_wp(0);
    write_pkru(pkru_ad);
    test = 22;
    report("write to supervisor page when pkru is ad and wp == 0", pf_count == 0 && test == 22);

    init_test();
    set_cr0_wp(1);
    write_pkru(pkru_wd);
    test = 23;
    report("write to supervisor page when pkru is wd and wp == 1", pf_count == 0 && test == 23);

    init_test();
    set_cr0_wp(0);
    write_pkru(pkru_wd);
    test = 24;
    report("write to supervisor page when pkru is wd and wp == 0", pf_count == 0 && test == 24);

    init_test();
    write_pkru(pkru_wd);
    set_cr0_wp(0);
    USER_VAR(test) = 25;
    report("write to user page when pkru is wd and wp == 0", pf_count == 0 && test == 25);

    init_test();
    write_pkru(pkru_wd);
    set_cr0_wp(1);
    USER_VAR(test) = 26;
    report("write to user page when pkru is wd and wp == 1", pf_count == 1 && test == 26 && save == 25);

    init_test();
    write_pkru(pkru_ad);
    (void)USER_VAR(test);
    report("read from user page when pkru is ad", pf_count == 1 && save == 26);

    // TODO: implicit kernel access from ring 3 (e.g. int)

    return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/x86/pmu.c                                                           0000644 0000000 0000000 00000023056 00000000000 015340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#include "x86/msr.h"
#include "x86/processor.h"
#include "x86/apic-defs.h"
#include "x86/apic.h"
#include "x86/desc.h"
#include "x86/isr.h"
#include "x86/vm.h"

#include "libcflat.h"
#include <stdint.h>

#define FIXED_CNT_INDEX 32
#define PC_VECTOR	32

#define EVNSEL_EVENT_SHIFT	0
#define EVNTSEL_UMASK_SHIFT	8
#define EVNTSEL_USR_SHIFT	16
#define EVNTSEL_OS_SHIFT	17
#define EVNTSEL_EDGE_SHIFT	18
#define EVNTSEL_PC_SHIFT	19
#define EVNTSEL_INT_SHIFT	20
#define EVNTSEL_EN_SHIF		22
#define EVNTSEL_INV_SHIF	23
#define EVNTSEL_CMASK_SHIFT	24

#define EVNTSEL_EN	(1 << EVNTSEL_EN_SHIF)
#define EVNTSEL_USR	(1 << EVNTSEL_USR_SHIFT)
#define EVNTSEL_OS	(1 << EVNTSEL_OS_SHIFT)
#define EVNTSEL_PC	(1 << EVNTSEL_PC_SHIFT)
#define EVNTSEL_INT	(1 << EVNTSEL_INT_SHIFT)
#define EVNTSEL_INV	(1 << EVNTSEL_INV_SHIF)

#define N 1000000

typedef struct {
	uint32_t ctr;
	uint32_t config;
	uint64_t count;
	int idx;
} pmu_counter_t;

union cpuid10_eax {
	struct {
		unsigned int version_id:8;
		unsigned int num_counters:8;
		unsigned int bit_width:8;
		unsigned int mask_length:8;
	} split;
	unsigned int full;
} eax;

union cpuid10_ebx {
	struct {
		unsigned int no_unhalted_core_cycles:1;
		unsigned int no_instructions_retired:1;
		unsigned int no_unhalted_reference_cycles:1;
		unsigned int no_llc_reference:1;
		unsigned int no_llc_misses:1;
		unsigned int no_branch_instruction_retired:1;
		unsigned int no_branch_misses_retired:1;
	} split;
	unsigned int full;
} ebx;

union cpuid10_edx {
	struct {
		unsigned int num_counters_fixed:5;
		unsigned int bit_width_fixed:8;
		unsigned int reserved:19;
	} split;
	unsigned int full;
} edx;

struct pmu_event {
	const char *name;
	uint32_t unit_sel;
	int min;
	int max;
} gp_events[] = {
	{"core cycles", 0x003c, 1*N, 50*N},
	{"instructions", 0x00c0, 10*N, 10.2*N},
	{"ref cycles", 0x013c, 0.1*N, 30*N},
	{"llc refference", 0x4f2e, 1, 2*N},
	{"llc misses", 0x412e, 1, 1*N},
	{"branches", 0x00c4, 1*N, 1.1*N},
	{"branch misses", 0x00c5, 0, 0.1*N},
}, fixed_events[] = {
	{"fixed 1", MSR_CORE_PERF_FIXED_CTR0, 10*N, 10.2*N},
	{"fixed 2", MSR_CORE_PERF_FIXED_CTR0 + 1, 1*N, 30*N},
	{"fixed 3", MSR_CORE_PERF_FIXED_CTR0 + 2, 0.1*N, 30*N}
};

static int num_counters;

char *buf;

static inline void loop()
{
	unsigned long tmp, tmp2, tmp3;

	asm volatile("1: mov (%1), %2; add $64, %1; nop; nop; nop; nop; nop; nop; nop; loop 1b"
			: "=c"(tmp), "=r"(tmp2), "=r"(tmp3): "0"(N), "1"(buf));

}

volatile uint64_t irq_received;

static void cnt_overflow(isr_regs_t *regs)
{
	irq_received++;
	apic_write(APIC_EOI, 0);
}

static bool check_irq(void)
{
	int i;
	irq_received = 0;
	irq_enable();
	for (i = 0; i < 100000 && !irq_received; i++)
		asm volatile("pause");
	irq_disable();
	return irq_received;
}

static bool is_gp(pmu_counter_t *evt)
{
	return evt->ctr < MSR_CORE_PERF_FIXED_CTR0;
}

static int event_to_global_idx(pmu_counter_t *cnt)
{
	return cnt->ctr - (is_gp(cnt) ? MSR_IA32_PERFCTR0 :
		(MSR_CORE_PERF_FIXED_CTR0 - FIXED_CNT_INDEX));
}

static struct pmu_event* get_counter_event(pmu_counter_t *cnt)
{
	if (is_gp(cnt)) {
		int i;

		for (i = 0; i < sizeof(gp_events)/sizeof(gp_events[0]); i++)
			if (gp_events[i].unit_sel == (cnt->config & 0xffff))
				return &gp_events[i];
	} else
		return &fixed_events[cnt->ctr - MSR_CORE_PERF_FIXED_CTR0];

	return (void*)0;
}

static void global_enable(pmu_counter_t *cnt)
{
	cnt->idx = event_to_global_idx(cnt);

	wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, rdmsr(MSR_CORE_PERF_GLOBAL_CTRL) |
			(1ull << cnt->idx));
}

static void global_disable(pmu_counter_t *cnt)
{
	wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, rdmsr(MSR_CORE_PERF_GLOBAL_CTRL) &
			~(1ull << cnt->idx));
}


static void start_event(pmu_counter_t *evt)
{
    wrmsr(evt->ctr, evt->count);
    if (is_gp(evt))
	    wrmsr(MSR_P6_EVNTSEL0 + event_to_global_idx(evt),
			    evt->config | EVNTSEL_EN);
    else {
	    uint32_t ctrl = rdmsr(MSR_CORE_PERF_FIXED_CTR_CTRL);
	    int shift = (evt->ctr - MSR_CORE_PERF_FIXED_CTR0) * 4;
	    uint32_t usrospmi = 0;

	    if (evt->config & EVNTSEL_OS)
		    usrospmi |= (1 << 0);
	    if (evt->config & EVNTSEL_USR)
		    usrospmi |= (1 << 1);
	    if (evt->config & EVNTSEL_INT)
		    usrospmi |= (1 << 3); // PMI on overflow
	    ctrl = (ctrl & ~(0xf << shift)) | (usrospmi << shift);
	    wrmsr(MSR_CORE_PERF_FIXED_CTR_CTRL, ctrl);
    }
    global_enable(evt);
}

static void stop_event(pmu_counter_t *evt)
{
	global_disable(evt);
	if (is_gp(evt))
		wrmsr(MSR_P6_EVNTSEL0 + event_to_global_idx(evt),
				evt->config & ~EVNTSEL_EN);
	else {
		uint32_t ctrl = rdmsr(MSR_CORE_PERF_FIXED_CTR_CTRL);
		int shift = (evt->ctr - MSR_CORE_PERF_FIXED_CTR0) * 4;
		wrmsr(MSR_CORE_PERF_FIXED_CTR_CTRL, ctrl & ~(0xf << shift));
	}
	evt->count = rdmsr(evt->ctr);
}

static void measure(pmu_counter_t *evt, int count)
{
	int i;
	for (i = 0; i < count; i++)
		start_event(&evt[i]);
	loop();
	for (i = 0; i < count; i++)
		stop_event(&evt[i]);
}

static bool verify_event(uint64_t count, struct pmu_event *e)
{
	// printf("%lld >= %lld <= %lld\n", e->min, count, e->max);
	return count >= e->min  && count <= e->max;

}

static bool verify_counter(pmu_counter_t *cnt)
{
	return verify_event(cnt->count, get_counter_event(cnt));
}

static void check_gp_counter(struct pmu_event *evt)
{
	pmu_counter_t cnt = {
		.ctr = MSR_IA32_PERFCTR0,
		.config = EVNTSEL_OS | EVNTSEL_USR | evt->unit_sel,
	};
	int i;

	for (i = 0; i < num_counters; i++, cnt.ctr++) {
		cnt.count = 0;
		measure(&cnt, 1);
		report("%s-%d", verify_event(cnt.count, evt), evt->name, i);
	}
}

static void check_gp_counters(void)
{
	int i;

	for (i = 0; i < sizeof(gp_events)/sizeof(gp_events[0]); i++)
		if (!(ebx.full & (1 << i)))
			check_gp_counter(&gp_events[i]);
		else
			printf("GP event '%s' is disabled\n",
					gp_events[i].name);
}

static void check_fixed_counters(void)
{
	pmu_counter_t cnt = {
		.config = EVNTSEL_OS | EVNTSEL_USR,
	};
	int i;

	for (i = 0; i < edx.split.num_counters_fixed; i++) {
		cnt.count = 0;
		cnt.ctr = fixed_events[i].unit_sel;
		measure(&cnt, 1);
		report("fixed-%d", verify_event(cnt.count, &fixed_events[i]), i);
	}
}

static void check_counters_many(void)
{
	pmu_counter_t cnt[10];
	int i, n;

	for (i = 0, n = 0; n < num_counters; i++) {
		if (ebx.full & (1 << i))
			continue;

		cnt[n].count = 0;
		cnt[n].ctr = MSR_IA32_PERFCTR0 + n;
		cnt[n].config = EVNTSEL_OS | EVNTSEL_USR | gp_events[i].unit_sel;
		n++;
	}
	for (i = 0; i < edx.split.num_counters_fixed; i++) {
		cnt[n].count = 0;
		cnt[n].ctr = fixed_events[i].unit_sel;
		cnt[n].config = EVNTSEL_OS | EVNTSEL_USR;
		n++;
	}

	measure(cnt, n);

	for (i = 0; i < n; i++)
		if (!verify_counter(&cnt[i]))
			break;

	report("all counters", i == n);
}

static void check_counter_overflow(void)
{
	uint64_t count;
	int i;
	pmu_counter_t cnt = {
		.ctr = MSR_IA32_PERFCTR0,
		.config = EVNTSEL_OS | EVNTSEL_USR | gp_events[1].unit_sel /* instructions */,
		.count = 0,
	};
	measure(&cnt, 1);
	count = cnt.count;

	/* clear status before test */
	wrmsr(MSR_CORE_PERF_GLOBAL_OVF_CTRL, rdmsr(MSR_CORE_PERF_GLOBAL_STATUS));

	report_prefix_push("overflow");

	for (i = 0; i < num_counters + 1; i++, cnt.ctr++) {
		uint64_t status;
		int idx;
		if (i == num_counters)
			cnt.ctr = fixed_events[0].unit_sel;
		if (i % 2)
			cnt.config |= EVNTSEL_INT;
		else
			cnt.config &= ~EVNTSEL_INT;
		idx = event_to_global_idx(&cnt);
		cnt.count = 1 - count;
		measure(&cnt, 1);
		report("cntr-%d", cnt.count == 1, i);
		status = rdmsr(MSR_CORE_PERF_GLOBAL_STATUS);
		report("status-%d", status & (1ull << idx), i);
		wrmsr(MSR_CORE_PERF_GLOBAL_OVF_CTRL, status);
		status = rdmsr(MSR_CORE_PERF_GLOBAL_STATUS);
		report("status clear-%d", !(status & (1ull << idx)), i);
		report("irq-%d", check_irq() == (i % 2), i);
	}

	report_prefix_pop();
}

static void check_gp_counter_cmask(void)
{
	pmu_counter_t cnt = {
		.ctr = MSR_IA32_PERFCTR0,
		.config = EVNTSEL_OS | EVNTSEL_USR | gp_events[1].unit_sel /* instructions */,
		.count = 0,
	};
	cnt.config |= (0x2 << EVNTSEL_CMASK_SHIFT);
	measure(&cnt, 1);
	report("cmask", cnt.count < gp_events[1].min);
}

static void check_rdpmc(void)
{
	uint64_t val = 0x1f3456789ull;
	int i;

	report_prefix_push("rdpmc");

	for (i = 0; i < num_counters; i++) {
		uint64_t x = (val & 0xffffffff) |
			((1ull << (eax.split.bit_width - 32)) - 1) << 32;
		wrmsr(MSR_IA32_PERFCTR0 + i, val);
		report("cntr-%d", rdpmc(i) == x, i);
		report("fast-%d", rdpmc(i | (1<<31)) == (u32)val, i);
	}
	for (i = 0; i < edx.split.num_counters_fixed; i++) {
		uint64_t x = (val & 0xffffffff) |
			((1ull << (edx.split.bit_width_fixed - 32)) - 1) << 32;
		wrmsr(MSR_CORE_PERF_FIXED_CTR0 + i, val);
		report("fixed cntr-%d", rdpmc(i | (1 << 30)) == x, i);
		report("fixed fast-%d", rdpmc(i | (3<<30)) == (u32)val, i);
	}

	report_prefix_pop();
}

int main(int ac, char **av)
{
	struct cpuid id = cpuid(10);

	setup_vm();
	setup_idt();
	handle_irq(PC_VECTOR, cnt_overflow);
	buf = vmalloc(N*64);

	eax.full = id.a;
	ebx.full = id.b;
	edx.full = id.d;

	if (!eax.split.version_id) {
		printf("No pmu is detected!\n");
		return report_summary();
	}
	printf("PMU version:         %d\n", eax.split.version_id);
	printf("GP counters:         %d\n", eax.split.num_counters);
	printf("GP counter width:    %d\n", eax.split.bit_width);
	printf("Mask length:         %d\n", eax.split.mask_length);
	printf("Fixed counters:      %d\n", edx.split.num_counters_fixed);
	printf("Fixed counter width: %d\n", edx.split.bit_width_fixed);

	num_counters = eax.split.num_counters;
	if (num_counters > ARRAY_SIZE(gp_events))
		num_counters = ARRAY_SIZE(gp_events);

	apic_write(APIC_LVTPC, PC_VECTOR);

	check_gp_counters();
	check_fixed_counters();
	check_rdpmc();
	check_counters_many();
	check_counter_overflow();
	check_gp_counter_cmask();

	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/x86/port80.c                                                        0000644 0000000 0000000 00000000312 00000000000 015661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"

int main()
{
    int i;

    printf("begining port 0x80 write test\n");
    for (i = 0; i < 10000000; ++i)
	asm volatile("outb %al, $0x80");
    printf("done\n");
    return 0;
}
                                                                                                                                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/x86/realmode.c                                                      0000644 0000000 0000000 00000152062 00000000000 016327  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef USE_SERIAL
#define USE_SERIAL
#endif

#define ARRAY_SIZE(_a) (sizeof(_a)/sizeof((_a)[0]))

asm(".code16gcc");

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned u32;
typedef unsigned long long u64;

#ifndef NULL
#define NULL ((void*)0)
#endif

void realmode_start(void);
void test_function(void);

asm(
	"test_function: \n\t"
	"mov $0x1234, %eax \n\t"
	"ret"
   );

static int strlen(const char *str)
{
	int n;

	for (n = 0; *str; ++str)
		++n;
	return n;
}

static void outb(u8 data, u16 port)
{
	asm volatile("out %0, %1" : : "a"(data), "d"(port));
}

#ifdef USE_SERIAL
static int serial_iobase = 0x3f8;
static int serial_inited = 0;

static u8 inb(u16 port)
{
	u8 data;
	asm volatile("in %1, %0" : "=a"(data) : "d"(port));
	return data;
}

static void serial_outb(char ch)
{
	u8 lsr;

	do {
		lsr = inb(serial_iobase + 0x05);
	} while (!(lsr & 0x20));

	outb(ch, serial_iobase + 0x00);
}

static void serial_init(void)
{
	u8 lcr;

	/* set DLAB */
	lcr = inb(serial_iobase + 0x03);
	lcr |= 0x80;
	outb(lcr, serial_iobase + 0x03);

	/* set baud rate to 115200 */
	outb(0x01, serial_iobase + 0x00);
	outb(0x00, serial_iobase + 0x01);

	/* clear DLAB */
	lcr = inb(serial_iobase + 0x03);
	lcr &= ~0x80;
	outb(lcr, serial_iobase + 0x03);

	/* IER: disable interrupts */
	outb(0x00, serial_iobase + 0x01);
	/* LCR: 8 bits, no parity, one stop bit */
	outb(0x03, serial_iobase + 0x03);
	/* FCR: disable FIFO queues */
	outb(0x00, serial_iobase + 0x02);
	/* MCR: RTS, DTR on */
	outb(0x03, serial_iobase + 0x04);
}
#endif

static void print_serial(const char *buf)
{
	unsigned long len = strlen(buf);
#ifdef USE_SERIAL
	unsigned long i;
	if (!serial_inited) {
	    serial_init();
	    serial_inited = 1;
	}

	for (i = 0; i < len; i++) {
	    serial_outb(buf[i]);
	}
#else
	asm volatile ("addr32/rep/outsb" : "+S"(buf), "+c"(len) : "d"(0xf1));
#endif
}

static void print_serial_u32(u32 value)
{
	char n[12], *p;
	p = &n[11];
	*p = 0;
	do {
		*--p = '0' + (value % 10);
		value /= 10;
	} while (value > 0);
	print_serial(p);
}

static int failed;

static void exit(int code)
{
	outb(code, 0xf4);

	if (code == 0)
		print_serial("--- DONE: 0 ---\n");
	else
		print_serial("--- DONE: 1 ---\n");

	while (1) {
		asm volatile("hlt" ::: "memory");
	}
}

struct regs {
	u32 eax, ebx, ecx, edx;
	u32 esi, edi, esp, ebp;
	u32 eip, eflags;
};

struct table_descr {
	u16 limit;
	void *base;
} __attribute__((packed));

static u64 gdt[] = {
	0,
	0x00cf9b000000ffffull, // flat 32-bit code segment
	0x00cf93000000ffffull, // flat 32-bit data segment
};

static struct table_descr gdt_descr = {
	sizeof(gdt) - 1,
	gdt,
};

struct insn_desc {
    u16 ptr;
    u16 len;
};

struct {
	u32 stack[128];
	char top[];
} tmp_stack;

static struct regs inregs, outregs;

static inline void init_inregs(struct regs *regs)
{
	inregs = (struct regs){ 0 };
	if (regs)
		inregs = *regs;
	if (!inregs.esp)
		inregs.esp = (unsigned long)&tmp_stack.top;
}

/* noinline: the asm below defines global labels, which must exist once (clang inlines this) */
static __attribute__((noinline)) void exec_in_big_real_mode(struct insn_desc *insn)
{
	unsigned long tmp;
	static struct regs save;
	int i;
	extern u8 test_insn[], test_insn_end[];

	for (i = 0; i < insn->len; ++i)
	    test_insn[i] = ((u8 *)(unsigned long)insn->ptr)[i];
	for (; i < test_insn_end - test_insn; ++i)
		test_insn[i] = 0x90; // nop

	save = inregs;
	asm volatile(
		"lgdtl %[gdt_descr] \n\t"
		"mov %%cr0, %[tmp] \n\t"
		"or $1, %[tmp] \n\t"
		"mov %[tmp], %%cr0 \n\t"
		"mov %[bigseg], %%gs \n\t"
		"and $-2, %[tmp] \n\t"
		"mov %[tmp], %%cr0 \n\t"

		/* Save ES, because it is clobbered by some tests. */
		"pushw %%es \n\t"

		"pushw %[save]+36; popfw \n\t"
		"xchg %%eax, %[save]+0 \n\t"
		"xchg %%ebx, %[save]+4 \n\t"
		"xchg %%ecx, %[save]+8 \n\t"
		"xchg %%edx, %[save]+12 \n\t"
		"xchg %%esi, %[save]+16 \n\t"
		"xchg %%edi, %[save]+20 \n\t"
		"xchg %%esp, %[save]+24 \n\t"
		"xchg %%ebp, %[save]+28 \n\t"

		"test_insn: . = . + 32\n\t"
		"test_insn_end: \n\t"

		"xchg %%eax, %[save]+0 \n\t"
		"xchg %%ebx, %[save]+4 \n\t"
		"xchg %%ecx, %[save]+8 \n\t"
		"xchg %%edx, %[save]+12 \n\t"
		"xchg %%esi, %[save]+16 \n\t"
		"xchg %%edi, %[save]+20 \n\t"
		"xchg %%esp, %[save]+24 \n\t"
		"xchg %%ebp, %[save]+28 \n\t"

		/* Save EFLAGS in outregs*/
		"pushfl \n\t"
		"popl %[save]+36 \n\t"

		/* Restore ES for future rep string operations. */
		"popw %%es \n\t"

		/* Restore DF for the harness code */
		"cld\n\t"
		"xor %[tmp], %[tmp] \n\t"
		"mov %[tmp], %%gs \n\t"
		: [tmp]"=&r"(tmp), [save]"+m"(save)
		: [gdt_descr]"m"(gdt_descr), [bigseg]"r"((short)16)
		: "cc", "memory"
		);
	outregs = save;
}

#define R_AX 1
#define R_BX 2
#define R_CX 4
#define R_DX 8
#define R_SI 16
#define R_DI 32
#define R_SP 64
#define R_BP 128

static int regs_equal(int ignore)
{
	const u32 *p1 = &inregs.eax, *p2 = &outregs.eax;  // yuck
	int i;

	for (i = 0; i < 8; ++i)
		if (!(ignore & (1 << i)) && p1[i] != p2[i])
			return 0;
	return 1;
}

static void report(const char *name, u16 regs_ignore, _Bool ok)
{
    if (!regs_equal(regs_ignore)) {
	ok = 0;
    }
    print_serial(ok ? "PASS: " : "FAIL: ");
    print_serial(name);
    print_serial("\n");
    if (!ok)
	failed = 1;
}

#define MK_INSN(name, str)				\
    asm (						\
	 ".pushsection .data.insn  \n\t"		\
	 "insn_" #name ": \n\t"				\
	 ".word 1001f, 1002f - 1001f \n\t"		\
	 ".popsection \n\t"				\
	 ".pushsection .text.insn, \"ax\" \n\t"		\
	 "1001: \n\t"					\
	 "insn_code_" #name ": " str " \n\t"		\
	 "1002: \n\t"					\
	 ".popsection"					\
    );							\
    extern struct insn_desc insn_##name;

static void test_xchg(void)
{
	MK_INSN(xchg_test1, "xchg %eax,%eax\n\t");
	MK_INSN(xchg_test2, "xchg %eax,%ebx\n\t");
	MK_INSN(xchg_test3, "xchg %eax,%ecx\n\t");
	MK_INSN(xchg_test4, "xchg %eax,%edx\n\t");
	MK_INSN(xchg_test5, "xchg %eax,%esi\n\t");
	MK_INSN(xchg_test6, "xchg %eax,%edi\n\t");
	MK_INSN(xchg_test7, "xchg %eax,%ebp\n\t");
	MK_INSN(xchg_test8, "xchg %eax,%esp\n\t");

	inregs = (struct regs){ .eax = 0, .ebx = 1, .ecx = 2, .edx = 3, .esi = 4, .edi = 5, .ebp = 6, .esp = 7};

	exec_in_big_real_mode(&insn_xchg_test1);
	report("xchg 1", 0, 1);

	exec_in_big_real_mode(&insn_xchg_test2);
	report("xchg 2", R_AX | R_BX,
	       outregs.eax == inregs.ebx && outregs.ebx == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test3);
	report("xchg 3", R_AX | R_CX,
	       outregs.eax == inregs.ecx && outregs.ecx == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test4);
	report("xchg 4", R_AX | R_DX,
	       outregs.eax == inregs.edx && outregs.edx == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test5);
	report("xchg 5", R_AX | R_SI,
	       outregs.eax == inregs.esi && outregs.esi == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test6);
	report("xchg 6", R_AX | R_DI,
	       outregs.eax == inregs.edi && outregs.edi == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test7);
	report("xchg 7", R_AX | R_BP,
	       outregs.eax == inregs.ebp && outregs.ebp == inregs.eax);

	exec_in_big_real_mode(&insn_xchg_test8);
	report("xchg 8", R_AX | R_SP,
	       outregs.eax == inregs.esp && outregs.esp == inregs.eax);
}

static void test_shld(void)
{
	MK_INSN(shld_test, "shld $8,%edx,%eax\n\t");

	init_inregs(&(struct regs){ .eax = 0xbe, .edx = 0xef000000 });

	exec_in_big_real_mode(&insn_shld_test);
	report("shld", ~0, outregs.eax == 0xbeef);
}

static void test_mov_imm(void)
{
	MK_INSN(mov_r32_imm_1, "mov $1234567890, %eax");
	MK_INSN(mov_r16_imm_1, "mov $1234, %ax");
	MK_INSN(mov_r8_imm_1, "mov $0x12, %ah");
	MK_INSN(mov_r8_imm_2, "mov $0x34, %al");
	MK_INSN(mov_r8_imm_3, "mov $0x12, %ah\n\t" "mov $0x34, %al\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_mov_r16_imm_1);
	report("mov 1", R_AX, outregs.eax == 1234);

	/* test mov $imm, %eax */
	exec_in_big_real_mode(&insn_mov_r32_imm_1);
	report("mov 2", R_AX, outregs.eax == 1234567890);

	/* test mov $imm, %al/%ah */
	exec_in_big_real_mode(&insn_mov_r8_imm_1);
	report("mov 3", R_AX, outregs.eax == 0x1200);

	exec_in_big_real_mode(&insn_mov_r8_imm_2);
	report("mov 4", R_AX, outregs.eax == 0x34);

	exec_in_big_real_mode(&insn_mov_r8_imm_3);
	report("mov 5", R_AX, outregs.eax == 0x1234);
}

static void test_sub_imm(void)
{
	MK_INSN(sub_r32_imm_1, "mov $1234567890, %eax\n\t" "sub $10, %eax\n\t");
	MK_INSN(sub_r16_imm_1, "mov $1234, %ax\n\t" "sub $10, %ax\n\t");
	MK_INSN(sub_r8_imm_1, "mov $0x12, %ah\n\t" "sub $0x10, %ah\n\t");
	MK_INSN(sub_r8_imm_2, "mov $0x34, %al\n\t" "sub $0x10, %al\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_sub_r16_imm_1);
	report("sub 1", R_AX, outregs.eax == 1224);

	/* test mov $imm, %eax */
	exec_in_big_real_mode(&insn_sub_r32_imm_1);
	report("sub 2", R_AX, outregs.eax == 1234567880);

	/* test mov $imm, %al/%ah */
	exec_in_big_real_mode(&insn_sub_r8_imm_1);
	report("sub 3", R_AX, outregs.eax == 0x0200);

	exec_in_big_real_mode(&insn_sub_r8_imm_2);
	report("sub 4", R_AX, outregs.eax == 0x24);
}

static void test_xor_imm(void)
{
	MK_INSN(xor_r32_imm_1, "mov $1234567890, %eax\n\t" "xor $1234567890, %eax\n\t");
	MK_INSN(xor_r16_imm_1, "mov $1234, %ax\n\t" "xor $1234, %ax\n\t");
	MK_INSN(xor_r8_imm_1, "mov $0x12, %ah\n\t" "xor $0x12, %ah\n\t");
	MK_INSN(xor_r8_imm_2, "mov $0x34, %al\n\t" "xor $0x34, %al\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_xor_r16_imm_1);
	report("xor 1", R_AX, outregs.eax == 0);

	/* test mov $imm, %eax */
	exec_in_big_real_mode(&insn_xor_r32_imm_1);
	report("xor 2", R_AX, outregs.eax == 0);

	/* test mov $imm, %al/%ah */
	exec_in_big_real_mode(&insn_xor_r8_imm_1);
	report("xor 3", R_AX, outregs.eax == 0);

	exec_in_big_real_mode(&insn_xor_r8_imm_2);
	report("xor 4", R_AX, outregs.eax == 0);
}

static void test_cmp_imm(void)
{
	MK_INSN(cmp_test1, "mov $0x34, %al\n\t"
			   "cmp $0x34, %al\n\t");
	MK_INSN(cmp_test2, "mov $0x34, %al\n\t"
			   "cmp $0x39, %al\n\t");
	MK_INSN(cmp_test3, "mov $0x34, %al\n\t"
			   "cmp $0x24, %al\n\t");

	init_inregs(NULL);

	/* test cmp imm8 with AL */
	/* ZF: (bit 6) Zero Flag becomes 1 if an operation results
	 * in a 0 writeback, or 0 register
	 */
	exec_in_big_real_mode(&insn_cmp_test1);
	report("cmp 1", ~0, (outregs.eflags & (1<<6)) == (1<<6));

	exec_in_big_real_mode(&insn_cmp_test2);
	report("cmp 2", ~0, (outregs.eflags & (1<<6)) == 0);

	exec_in_big_real_mode(&insn_cmp_test3);
	report("cmp 3", ~0, (outregs.eflags & (1<<6)) == 0);
}

static void test_add_imm(void)
{
	MK_INSN(add_test1, "mov $0x43211234, %eax \n\t"
			   "add $0x12344321, %eax \n\t");
	MK_INSN(add_test2, "mov $0x12, %eax \n\t"
			   "add $0x21, %al\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_add_test1);
	report("add 1", ~0, outregs.eax == 0x55555555);

	exec_in_big_real_mode(&insn_add_test2);
	report("add 2", ~0, outregs.eax == 0x33);
}

static void test_eflags_insn(void)
{
	MK_INSN(clc, "clc");
	MK_INSN(stc, "stc");
	MK_INSN(cli, "cli");
	MK_INSN(sti, "sti");
	MK_INSN(cld, "cld");
	MK_INSN(std, "std");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_clc);
	report("clc", ~0, (outregs.eflags & 1) == 0);

	exec_in_big_real_mode(&insn_stc);
	report("stc", ~0, (outregs.eflags & 1) == 1);

	exec_in_big_real_mode(&insn_cli);
	report("cli", ~0, !(outregs.eflags & (1 << 9)));

	exec_in_big_real_mode(&insn_sti);
	report("sti", ~0, outregs.eflags & (1 << 9));

	exec_in_big_real_mode(&insn_cld);
	report("cld", ~0, !(outregs.eflags & (1 << 10)));

	exec_in_big_real_mode(&insn_std);
	report("std", ~0, (outregs.eflags & (1 << 10)));
}

static void test_io(void)
{
	MK_INSN(io_test1, "mov $0xff, %al \n\t"
		          "out %al, $0xe0 \n\t"
		          "mov $0x00, %al \n\t"
			  "in $0xe0, %al \n\t");
	MK_INSN(io_test2, "mov $0xffff, %ax \n\t"
			  "out %ax, $0xe0 \n\t"
			  "mov $0x0000, %ax \n\t"
			  "in $0xe0, %ax \n\t");
	MK_INSN(io_test3, "mov $0xffffffff, %eax \n\t"
			  "out %eax, $0xe0 \n\t"
			  "mov $0x000000, %eax \n\t"
			  "in $0xe0, %eax \n\t");
	MK_INSN(io_test4, "mov $0xe0, %dx \n\t"
			  "mov $0xff, %al \n\t"
			  "out %al, %dx \n\t"
			  "mov $0x00, %al \n\t"
			  "in %dx, %al \n\t");
	MK_INSN(io_test5, "mov $0xe0, %dx \n\t"
			  "mov $0xffff, %ax \n\t"
			  "out %ax, %dx \n\t"
			  "mov $0x0000, %ax \n\t"
			  "in %dx, %ax \n\t");
	MK_INSN(io_test6, "mov $0xe0, %dx \n\t"
			  "mov $0xffffffff, %eax \n\t"
			  "out %eax, %dx \n\t"
			  "mov $0x00000000, %eax \n\t"
			  "in %dx, %eax \n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_io_test1);
	report("pio 1", R_AX, outregs.eax == 0xff);

	exec_in_big_real_mode(&insn_io_test2);
	report("pio 2", R_AX, outregs.eax == 0xffff);

	exec_in_big_real_mode(&insn_io_test3);
	report("pio 3", R_AX, outregs.eax == 0xffffffff);

	exec_in_big_real_mode(&insn_io_test4);
	report("pio 4", R_AX|R_DX, outregs.eax == 0xff);

	exec_in_big_real_mode(&insn_io_test5);
	report("pio 5", R_AX|R_DX, outregs.eax == 0xffff);

	exec_in_big_real_mode(&insn_io_test6);
	report("pio 6", R_AX|R_DX, outregs.eax == 0xffffffff);
}

asm ("retf: lretw");
extern void retf(void);

asm ("retf_imm: lretw $10");
extern void retf_imm(void);

static void test_call(void)
{
	u32 addr;

	MK_INSN(call1, "mov $test_function, %eax \n\t"
		       "call *%eax\n\t");
	MK_INSN(call_near1, "jmp 2f\n\t"
			    "1: mov $0x1234, %eax\n\t"
			    "ret\n\t"
			    "2: call 1b\t");
	MK_INSN(call_near2, "call 1f\n\t"
			    "jmp 2f\n\t"
			    "1: mov $0x1234, %eax\n\t"
			    "ret\n\t"
			    "2:\t");
	MK_INSN(call_far1,  "lcallw *(%ebx)\n\t");
	MK_INSN(call_far2,  "lcallw $0, $retf\n\t");
	MK_INSN(ret_imm,    "sub $10, %sp; jmp 2f; 1: retw $10; 2: callw 1b");
	MK_INSN(retf_imm,   "sub $10, %sp; lcallw $0, $retf_imm");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_call1);
	report("call 1", R_AX, outregs.eax == 0x1234);

	exec_in_big_real_mode(&insn_call_near1);
	report("call near 1", R_AX, outregs.eax == 0x1234);

	exec_in_big_real_mode(&insn_call_near2);
	report("call near 2", R_AX, outregs.eax == 0x1234);

	addr = (((unsigned)retf >> 4) << 16) | ((unsigned)retf & 0x0f);
	inregs.ebx = (unsigned)&addr;
	exec_in_big_real_mode(&insn_call_far1);
	report("call far 1", 0, 1);

	exec_in_big_real_mode(&insn_call_far2);
	report("call far 2", 0, 1);

	exec_in_big_real_mode(&insn_ret_imm);
	report("ret imm 1", 0, 1);

	exec_in_big_real_mode(&insn_retf_imm);
	report("retf imm 1", 0, 1);
}

static void test_jcc_short(void)
{
	MK_INSN(jnz_short1, "jnz 1f\n\t"
			    "mov $0x1234, %eax\n\t"
		            "1:\n\t");
	MK_INSN(jnz_short2, "1:\n\t"
			    "cmp $0x1234, %eax\n\t"
			    "mov $0x1234, %eax\n\t"
		            "jnz 1b\n\t");
	MK_INSN(jmp_short1, "jmp 1f\n\t"
		      "mov $0x1234, %eax\n\t"
		      "1:\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_jnz_short1);
	report("jnz short 1", ~0, 1);

	exec_in_big_real_mode(&insn_jnz_short2);
	report("jnz short 2", R_AX, (outregs.eflags & (1 << 6)));

	exec_in_big_real_mode(&insn_jmp_short1);
	report("jmp short 1", ~0, 1);
}

static void test_jcc_near(void)
{
	/* encode near jmp manually. gas will not do it if offsets < 127 byte */
	MK_INSN(jnz_near1, ".byte 0x0f, 0x85, 0x06, 0x00\n\t"
		           "mov $0x1234, %eax\n\t");
	MK_INSN(jnz_near2, "cmp $0x1234, %eax\n\t"
			   "mov $0x1234, %eax\n\t"
		           ".byte 0x0f, 0x85, 0xf0, 0xff\n\t");
	MK_INSN(jmp_near1, ".byte 0xE9, 0x06, 0x00\n\t"
		           "mov $0x1234, %eax\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_jnz_near1);
	report("jnz near 1", 0, 1);

	exec_in_big_real_mode(&insn_jnz_near2);
	report("jnz near 2", R_AX, outregs.eflags & (1 << 6));

	exec_in_big_real_mode(&insn_jmp_near1);
	report("jmp near 1", 0, 1);
}

static void test_long_jmp(void)
{
	MK_INSN(long_jmp, "calll 1f\n\t"
			  "jmp 2f\n\t"
			  "1: jmp $0, $test_function\n\t"
		          "2:\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_long_jmp);
	report("jmp far 1", R_AX, outregs.eax == 0x1234);
}

static void test_push_pop(void)
{
	MK_INSN(push32, "mov $0x12345678, %eax\n\t"
			"push %eax\n\t"
			"pop %ebx\n\t");
	MK_INSN(push16, "mov $0x1234, %ax\n\t"
			"push %ax\n\t"
			"pop %bx\n\t");

	MK_INSN(push_es, "mov $0x231, %bx\n\t" //Just write a dummy value to see if it gets overwritten
			 "mov $0x123, %ax\n\t"
			 "mov %ax, %es\n\t"
			 "pushw %es\n\t"
			 "pop %bx \n\t"
			 );
	MK_INSN(pop_es, "push %ax\n\t"
			"popw %es\n\t"
			"mov %es, %bx\n\t"
			);
	MK_INSN(push_pop_ss, "pushw %ss\n\t"
			     "pushw %ax\n\t"
			     "popw %ss\n\t"
			     "mov %ss, %bx\n\t"
			     "popw %ss\n\t"
			);
	MK_INSN(push_pop_fs, "pushl %fs\n\t"
			     "pushl %eax\n\t"
			     "popl %fs\n\t"
			     "mov %fs, %ebx\n\t"
			     "popl %fs\n\t"
			);
	MK_INSN(push_pop_high_esp_bits,
		"xor $0x12340000, %esp \n\t"
		"push %ax; \n\t"
		"xor $0x12340000, %esp \n\t"
		"pop %bx");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_push32);
	report("push/pop 1", R_AX|R_BX,
	       outregs.eax == outregs.ebx && outregs.eax == 0x12345678);

	exec_in_big_real_mode(&insn_push16);
	report("push/pop 2", R_AX|R_BX,
	       outregs.eax == outregs.ebx && outregs.eax == 0x1234);

	exec_in_big_real_mode(&insn_push_es);
	report("push/pop 3", R_AX|R_BX,
	       outregs.ebx == outregs.eax && outregs.eax == 0x123);

	exec_in_big_real_mode(&insn_pop_es);
	report("push/pop 4", R_AX|R_BX, outregs.ebx == outregs.eax);

	exec_in_big_real_mode(&insn_push_pop_ss);
	report("push/pop 5", R_AX|R_BX, outregs.ebx == outregs.eax);

	exec_in_big_real_mode(&insn_push_pop_fs);
	report("push/pop 6", R_AX|R_BX, outregs.ebx == outregs.eax);

	inregs.eax = 0x9977;
	inregs.ebx = 0x7799;
	exec_in_big_real_mode(&insn_push_pop_high_esp_bits);
	report("push/pop with high bits set in %esp", R_BX, outregs.ebx == 0x9977);
}

static void test_null(void)
{
	MK_INSN(null, "");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_null);
	report("null", 0, 1);
}

static void test_pusha_popa(void)
{
	MK_INSN(pusha, "pushal\n\t"
		       "popl %edi\n\t"
		       "popl %esi\n\t"
		       "popl %ebp\n\t"
		       "addl $4, %esp\n\t"
		       "popl %ebx\n\t"
		       "popl %edx\n\t"
		       "popl %ecx\n\t"
		       "popl %eax\n\t"
		       );

	MK_INSN(popa, "pushl %eax\n\t"
		      "pushl %ecx\n\t"
		      "pushl %edx\n\t"
		      "pushl %ebx\n\t"
		      "pushl %esp\n\t"
		      "pushl %ebp\n\t"
		      "pushl %esi\n\t"
		      "pushl %edi\n\t"
		      "popal\n\t"
		      );

	init_inregs(&(struct regs){ .eax = 0, .ebx = 1, .ecx = 2, .edx = 3, .esi = 4, .edi = 5, .ebp = 6 });

	exec_in_big_real_mode(&insn_pusha);
	report("pusha/popa 1", 0, 1);

	exec_in_big_real_mode(&insn_popa);
	report("pusha/popa 1", 0, 1);
}

static void test_iret(void)
{
	MK_INSN(iret32, "pushfl\n\t"
			"pushl %cs\n\t"
			"calll 1f\n\t" /* a near call will push eip onto the stack */
			"jmp 2f\n\t"
			"1: iretl\n\t"
			"2:\n\t"
		     );

	MK_INSN(iret16, "pushfw\n\t"
			"pushw %cs\n\t"
			"callw 1f\n\t"
			"jmp 2f\n\t"
			"1: iretw\n\t"
			"2:\n\t");

	MK_INSN(iret_flags32, "pushfl\n\t"
			      "popl %eax\n\t"
			      "andl $~0x2, %eax\n\t"
			      "orl $0xffc18028, %eax\n\t"
			      "pushl %eax\n\t"
			      "pushl %cs\n\t"
			      "calll 1f\n\t"
			      "jmp 2f\n\t"
			      "1: iretl\n\t"
			      "2:\n\t");

	MK_INSN(iret_flags16, "pushfw\n\t"
			      "popw %ax\n\t"
			      "and $~0x2, %ax\n\t"
			      "or $0x8028, %ax\n\t"
			      "pushw %ax\n\t"
			      "pushw %cs\n\t"
			      "callw 1f\n\t"
			      "jmp 2f\n\t"
			      "1: iretw\n\t"
			      "2:\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_iret32);
	report("iret 1", 0, 1);

	exec_in_big_real_mode(&insn_iret16);
	report("iret 2", 0, 1);

	exec_in_big_real_mode(&insn_iret_flags32);
	report("iret 3", R_AX, 1);
	report("rflags.rf", ~0, !(outregs.eflags & (1 << 16)));

	exec_in_big_real_mode(&insn_iret_flags16);
	report("iret 4", R_AX, 1);
}

static void test_int(void)
{
	init_inregs(NULL);

	*(u32 *)(0x11 * 4) = 0x1000; /* Store a pointer to address 0x1000 in IDT entry 0x11 */
	*(u8 *)(0x1000) = 0xcf; /* 0x1000 contains an IRET instruction */

	MK_INSN(int11, "int $0x11\n\t");

	exec_in_big_real_mode(&insn_int11);
	report("int 1", 0, 1);
}

static void test_sti_inhibit(void)
{
	init_inregs(NULL);

	*(u32 *)(0x73 * 4) = 0x1000; /* Store IRQ 11 handler in the IDT */
	*(u8 *)(0x1000) = 0xcf; /* 0x1000 contains an IRET instruction */

	MK_INSN(sti_inhibit, "cli\n\t"
			     "movw $0x200b, %dx\n\t"
			     "movl $1, %eax\n\t"
			     "outl %eax, %dx\n\t" /* Set IRQ11 */
			     "movl $0, %eax\n\t"
			     "outl %eax, %dx\n\t" /* Clear IRQ11 */
			     "sti\n\t"
			     "hlt\n\t");
	exec_in_big_real_mode(&insn_sti_inhibit);

	report("sti inhibit", ~0, 1);
}

static void test_imul(void)
{
	MK_INSN(imul8_1, "mov $2, %al\n\t"
			"mov $-4, %cx\n\t"
			"imul %cl\n\t");

	MK_INSN(imul16_1, "mov $2, %ax\n\t"
		      "mov $-4, %cx\n\t"
		      "imul %cx\n\t");

	MK_INSN(imul32_1, "mov $2, %eax\n\t"
		       "mov $-4, %ecx\n\t"
		       "imul %ecx\n\t");

	MK_INSN(imul8_2, "mov $0x12340002, %eax\n\t"
			"mov $4, %cx\n\t"
			"imul %cl\n\t");

	MK_INSN(imul16_2, "mov $2, %ax\n\t"
			"mov $4, %cx\n\t"
			"imul %cx\n\t");

	MK_INSN(imul32_2, "mov $2, %eax\n\t"
			"mov $4, %ecx\n\t"
			"imul %ecx\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_imul8_1);
	report("imul 1", R_AX | R_CX | R_DX, (outregs.eax & 0xff) == (u8)-8);

	exec_in_big_real_mode(&insn_imul16_1);
	report("imul 2", R_AX | R_CX | R_DX, outregs.eax == (u16)-8);

	exec_in_big_real_mode(&insn_imul32_1);
	report("imul 3", R_AX | R_CX | R_DX, outregs.eax == (u32)-8);

	exec_in_big_real_mode(&insn_imul8_2);
	report("imul 4", R_AX | R_CX | R_DX,
	       (outregs.eax & 0xffff) == 8
	       && (outregs.eax & 0xffff0000) == 0x12340000);

	exec_in_big_real_mode(&insn_imul16_2);
	report("imul 5", R_AX | R_CX | R_DX, outregs.eax == 8);

	exec_in_big_real_mode(&insn_imul32_2);
	report("imul 6", R_AX | R_CX | R_DX, outregs.eax == 8);
}

static void test_mul(void)
{
	MK_INSN(mul8, "mov $2, %al\n\t"
			"mov $4, %cx\n\t"
			"imul %cl\n\t");

	MK_INSN(mul16, "mov $2, %ax\n\t"
			"mov $4, %cx\n\t"
			"imul %cx\n\t");

	MK_INSN(mul32, "mov $2, %eax\n\t"
			"mov $4, %ecx\n\t"
			"imul %ecx\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_mul8);
	report("mul 1", R_AX | R_CX | R_DX, (outregs.eax & 0xff) == 8);

	exec_in_big_real_mode(&insn_mul16);
	report("mul 2", R_AX | R_CX | R_DX, outregs.eax == 8);

	exec_in_big_real_mode(&insn_mul32);
	report("mul 3", R_AX | R_CX | R_DX, outregs.eax == 8);
}

static void test_div(void)
{
	MK_INSN(div8, "mov $257, %ax\n\t"
			"mov $2, %cl\n\t"
			"div %cl\n\t");

	MK_INSN(div16, "mov $512, %ax\n\t"
			"mov $5, %cx\n\t"
			"div %cx\n\t");

	MK_INSN(div32, "mov $512, %eax\n\t"
			"mov $5, %ecx\n\t"
			"div %ecx\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_div8);
	report("div 1", R_AX | R_CX | R_DX, outregs.eax == 384);

	exec_in_big_real_mode(&insn_div16);
	report("div 2", R_AX | R_CX | R_DX,
	       outregs.eax == 102 && outregs.edx == 2);

	exec_in_big_real_mode(&insn_div32);
	report("div 3", R_AX | R_CX | R_DX,
	       outregs.eax == 102 && outregs.edx == 2);
}

static void test_idiv(void)
{
	MK_INSN(idiv8, "mov $256, %ax\n\t"
			"mov $-2, %cl\n\t"
			"idiv %cl\n\t");

	MK_INSN(idiv16, "mov $512, %ax\n\t"
			"mov $-2, %cx\n\t"
			"idiv %cx\n\t");

	MK_INSN(idiv32, "mov $512, %eax\n\t"
			"mov $-2, %ecx\n\t"
			"idiv %ecx\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_idiv8);
	report("idiv 1", R_AX | R_CX | R_DX, outregs.eax == (u8)-128);

	exec_in_big_real_mode(&insn_idiv16);
	report("idiv 2", R_AX | R_CX | R_DX, outregs.eax == (u16)-256);

	exec_in_big_real_mode(&insn_idiv32);
	report("idiv 3", R_AX | R_CX | R_DX, outregs.eax == (u32)-256);
}

static void test_cbw(void)
{
	MK_INSN(cbw, "mov $0xFE, %eax \n\t"
		     "cbw\n\t");
	MK_INSN(cwde, "mov $0xFFFE, %eax \n\t"
		      "cwde\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_cbw);
	report("cbq 1", ~0, outregs.eax == 0xFFFE);

	exec_in_big_real_mode(&insn_cwde);
	report("cwde 1", ~0, outregs.eax == 0xFFFFFFFE);
}

static void test_loopcc(void)
{
	MK_INSN(loop, "mov $10, %ecx\n\t"
		      "1: inc %eax\n\t"
		      "loop 1b\n\t");

	MK_INSN(loope, "mov $10, %ecx\n\t"
		       "mov $1, %eax\n\t"
		       "1: dec %eax\n\t"
		       "loope 1b\n\t");

	MK_INSN(loopne, "mov $10, %ecx\n\t"
		        "mov $5, %eax\n\t"
		        "1: dec %eax\n\t"
			"loopne 1b\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_loop);
	report("LOOPcc short 1", R_AX, outregs.eax == 10);

	exec_in_big_real_mode(&insn_loope);
	report("LOOPcc short 2", R_AX | R_CX,
	       outregs.eax == -1 && outregs.ecx == 8);

	exec_in_big_real_mode(&insn_loopne);
	report("LOOPcc short 3", R_AX | R_CX,
	       outregs.eax == 0 && outregs.ecx == 5);
}

static void test_das(void)
{
    short i;
    u16 nr_fail = 0;
    static unsigned test_cases[1024] = {
        0x46000000, 0x8701a000, 0x9710fa00, 0x97119a00,
        0x02000101, 0x8301a101, 0x9310fb01, 0x93119b01,
        0x02000202, 0x8301a202, 0x9710fc02, 0x97119c02,
        0x06000303, 0x8701a303, 0x9310fd03, 0x93119d03,
        0x02000404, 0x8301a404, 0x9310fe04, 0x93119e04,
        0x06000505, 0x8701a505, 0x9710ff05, 0x97119f05,
        0x06000606, 0x8701a606, 0x56100006, 0x9711a006,
        0x02000707, 0x8301a707, 0x12100107, 0x9311a107,
        0x02000808, 0x8301a808, 0x12100208, 0x9311a208,
        0x06000909, 0x8701a909, 0x16100309, 0x9711a309,
        0x1200040a, 0x9301a40a, 0x1210040a, 0x9311a40a,
        0x1600050b, 0x9701a50b, 0x1610050b, 0x9711a50b,
        0x1600060c, 0x9701a60c, 0x1610060c, 0x9711a60c,
        0x1200070d, 0x9301a70d, 0x1210070d, 0x9311a70d,
        0x1200080e, 0x9301a80e, 0x1210080e, 0x9311a80e,
        0x1600090f, 0x9701a90f, 0x1610090f, 0x9711a90f,
        0x02001010, 0x8301b010, 0x16100a10, 0x9711aa10,
        0x06001111, 0x8701b111, 0x12100b11, 0x9311ab11,
        0x06001212, 0x8701b212, 0x16100c12, 0x9711ac12,
        0x02001313, 0x8301b313, 0x12100d13, 0x9311ad13,
        0x06001414, 0x8701b414, 0x12100e14, 0x9311ae14,
        0x02001515, 0x8301b515, 0x16100f15, 0x9711af15,
        0x02001616, 0x8301b616, 0x12101016, 0x9311b016,
        0x06001717, 0x8701b717, 0x16101117, 0x9711b117,
        0x06001818, 0x8701b818, 0x16101218, 0x9711b218,
        0x02001919, 0x8301b919, 0x12101319, 0x9311b319,
        0x1600141a, 0x9701b41a, 0x1610141a, 0x9711b41a,
        0x1200151b, 0x9301b51b, 0x1210151b, 0x9311b51b,
        0x1200161c, 0x9301b61c, 0x1210161c, 0x9311b61c,
        0x1600171d, 0x9701b71d, 0x1610171d, 0x9711b71d,
        0x1600181e, 0x9701b81e, 0x1610181e, 0x9711b81e,
        0x1200191f, 0x9301b91f, 0x1210191f, 0x9311b91f,
        0x02002020, 0x8701c020, 0x12101a20, 0x9311ba20,
        0x06002121, 0x8301c121, 0x16101b21, 0x9711bb21,
        0x06002222, 0x8301c222, 0x12101c22, 0x9311bc22,
        0x02002323, 0x8701c323, 0x16101d23, 0x9711bd23,
        0x06002424, 0x8301c424, 0x16101e24, 0x9711be24,
        0x02002525, 0x8701c525, 0x12101f25, 0x9311bf25,
        0x02002626, 0x8701c626, 0x12102026, 0x9711c026,
        0x06002727, 0x8301c727, 0x16102127, 0x9311c127,
        0x06002828, 0x8301c828, 0x16102228, 0x9311c228,
        0x02002929, 0x8701c929, 0x12102329, 0x9711c329,
        0x1600242a, 0x9301c42a, 0x1610242a, 0x9311c42a,
        0x1200252b, 0x9701c52b, 0x1210252b, 0x9711c52b,
        0x1200262c, 0x9701c62c, 0x1210262c, 0x9711c62c,
        0x1600272d, 0x9301c72d, 0x1610272d, 0x9311c72d,
        0x1600282e, 0x9301c82e, 0x1610282e, 0x9311c82e,
        0x1200292f, 0x9701c92f, 0x1210292f, 0x9711c92f,
        0x06003030, 0x8301d030, 0x12102a30, 0x9711ca30,
        0x02003131, 0x8701d131, 0x16102b31, 0x9311cb31,
        0x02003232, 0x8701d232, 0x12102c32, 0x9711cc32,
        0x06003333, 0x8301d333, 0x16102d33, 0x9311cd33,
        0x02003434, 0x8701d434, 0x16102e34, 0x9311ce34,
        0x06003535, 0x8301d535, 0x12102f35, 0x9711cf35,
        0x06003636, 0x8301d636, 0x16103036, 0x9311d036,
        0x02003737, 0x8701d737, 0x12103137, 0x9711d137,
        0x02003838, 0x8701d838, 0x12103238, 0x9711d238,
        0x06003939, 0x8301d939, 0x16103339, 0x9311d339,
        0x1200343a, 0x9701d43a, 0x1210343a, 0x9711d43a,
        0x1600353b, 0x9301d53b, 0x1610353b, 0x9311d53b,
        0x1600363c, 0x9301d63c, 0x1610363c, 0x9311d63c,
        0x1200373d, 0x9701d73d, 0x1210373d, 0x9711d73d,
        0x1200383e, 0x9701d83e, 0x1210383e, 0x9711d83e,
        0x1600393f, 0x9301d93f, 0x1610393f, 0x9311d93f,
        0x02004040, 0x8301e040, 0x16103a40, 0x9311da40,
        0x06004141, 0x8701e141, 0x12103b41, 0x9711db41,
        0x06004242, 0x8701e242, 0x16103c42, 0x9311dc42,
        0x02004343, 0x8301e343, 0x12103d43, 0x9711dd43,
        0x06004444, 0x8701e444, 0x12103e44, 0x9711de44,
        0x02004545, 0x8301e545, 0x16103f45, 0x9311df45,
        0x02004646, 0x8301e646, 0x12104046, 0x9311e046,
        0x06004747, 0x8701e747, 0x16104147, 0x9711e147,
        0x06004848, 0x8701e848, 0x16104248, 0x9711e248,
        0x02004949, 0x8301e949, 0x12104349, 0x9311e349,
        0x1600444a, 0x9701e44a, 0x1610444a, 0x9711e44a,
        0x1200454b, 0x9301e54b, 0x1210454b, 0x9311e54b,
        0x1200464c, 0x9301e64c, 0x1210464c, 0x9311e64c,
        0x1600474d, 0x9701e74d, 0x1610474d, 0x9711e74d,
        0x1600484e, 0x9701e84e, 0x1610484e, 0x9711e84e,
        0x1200494f, 0x9301e94f, 0x1210494f, 0x9311e94f,
        0x06005050, 0x8701f050, 0x12104a50, 0x9311ea50,
        0x02005151, 0x8301f151, 0x16104b51, 0x9711eb51,
        0x02005252, 0x8301f252, 0x12104c52, 0x9311ec52,
        0x06005353, 0x8701f353, 0x16104d53, 0x9711ed53,
        0x02005454, 0x8301f454, 0x16104e54, 0x9711ee54,
        0x06005555, 0x8701f555, 0x12104f55, 0x9311ef55,
        0x06005656, 0x8701f656, 0x16105056, 0x9711f056,
        0x02005757, 0x8301f757, 0x12105157, 0x9311f157,
        0x02005858, 0x8301f858, 0x12105258, 0x9311f258,
        0x06005959, 0x8701f959, 0x16105359, 0x9711f359,
        0x1200545a, 0x9301f45a, 0x1210545a, 0x9311f45a,
        0x1600555b, 0x9701f55b, 0x1610555b, 0x9711f55b,
        0x1600565c, 0x9701f65c, 0x1610565c, 0x9711f65c,
        0x1200575d, 0x9301f75d, 0x1210575d, 0x9311f75d,
        0x1200585e, 0x9301f85e, 0x1210585e, 0x9311f85e,
        0x1600595f, 0x9701f95f, 0x1610595f, 0x9711f95f,
        0x06006060, 0x47010060, 0x16105a60, 0x9711fa60,
        0x02006161, 0x03010161, 0x12105b61, 0x9311fb61,
        0x02006262, 0x03010262, 0x16105c62, 0x9711fc62,
        0x06006363, 0x07010363, 0x12105d63, 0x9311fd63,
        0x02006464, 0x03010464, 0x12105e64, 0x9311fe64,
        0x06006565, 0x07010565, 0x16105f65, 0x9711ff65,
        0x06006666, 0x07010666, 0x16106066, 0x57110066,
        0x02006767, 0x03010767, 0x12106167, 0x13110167,
        0x02006868, 0x03010868, 0x12106268, 0x13110268,
        0x06006969, 0x07010969, 0x16106369, 0x17110369,
        0x1200646a, 0x1301046a, 0x1210646a, 0x1311046a,
        0x1600656b, 0x1701056b, 0x1610656b, 0x1711056b,
        0x1600666c, 0x1701066c, 0x1610666c, 0x1711066c,
        0x1200676d, 0x1301076d, 0x1210676d, 0x1311076d,
        0x1200686e, 0x1301086e, 0x1210686e, 0x1311086e,
        0x1600696f, 0x1701096f, 0x1610696f, 0x1711096f,
        0x02007070, 0x03011070, 0x16106a70, 0x17110a70,
        0x06007171, 0x07011171, 0x12106b71, 0x13110b71,
        0x06007272, 0x07011272, 0x16106c72, 0x17110c72,
        0x02007373, 0x03011373, 0x12106d73, 0x13110d73,
        0x06007474, 0x07011474, 0x12106e74, 0x13110e74,
        0x02007575, 0x03011575, 0x16106f75, 0x17110f75,
        0x02007676, 0x03011676, 0x12107076, 0x13111076,
        0x06007777, 0x07011777, 0x16107177, 0x17111177,
        0x06007878, 0x07011878, 0x16107278, 0x17111278,
        0x02007979, 0x03011979, 0x12107379, 0x13111379,
        0x1600747a, 0x1701147a, 0x1610747a, 0x1711147a,
        0x1200757b, 0x1301157b, 0x1210757b, 0x1311157b,
        0x1200767c, 0x1301167c, 0x1210767c, 0x1311167c,
        0x1600777d, 0x1701177d, 0x1610777d, 0x1711177d,
        0x1600787e, 0x1701187e, 0x1610787e, 0x1711187e,
        0x1200797f, 0x1301197f, 0x1210797f, 0x1311197f,
        0x82008080, 0x03012080, 0x12107a80, 0x13111a80,
        0x86008181, 0x07012181, 0x16107b81, 0x17111b81,
        0x86008282, 0x07012282, 0x12107c82, 0x13111c82,
        0x82008383, 0x03012383, 0x16107d83, 0x17111d83,
        0x86008484, 0x07012484, 0x16107e84, 0x17111e84,
        0x82008585, 0x03012585, 0x12107f85, 0x13111f85,
        0x82008686, 0x03012686, 0x92108086, 0x13112086,
        0x86008787, 0x07012787, 0x96108187, 0x17112187,
        0x86008888, 0x07012888, 0x96108288, 0x17112288,
        0x82008989, 0x03012989, 0x92108389, 0x13112389,
        0x9600848a, 0x1701248a, 0x9610848a, 0x1711248a,
        0x9200858b, 0x1301258b, 0x9210858b, 0x1311258b,
        0x9200868c, 0x1301268c, 0x9210868c, 0x1311268c,
        0x9600878d, 0x1701278d, 0x9610878d, 0x1711278d,
        0x9600888e, 0x1701288e, 0x9610888e, 0x1711288e,
        0x9200898f, 0x1301298f, 0x9210898f, 0x1311298f,
        0x86009090, 0x07013090, 0x92108a90, 0x13112a90,
        0x82009191, 0x03013191, 0x96108b91, 0x17112b91,
        0x82009292, 0x03013292, 0x92108c92, 0x13112c92,
        0x86009393, 0x07013393, 0x96108d93, 0x17112d93,
        0x82009494, 0x03013494, 0x96108e94, 0x17112e94,
        0x86009595, 0x07013595, 0x92108f95, 0x13112f95,
        0x86009696, 0x07013696, 0x96109096, 0x17113096,
        0x82009797, 0x03013797, 0x92109197, 0x13113197,
        0x82009898, 0x03013898, 0x92109298, 0x13113298,
        0x86009999, 0x07013999, 0x96109399, 0x17113399,
        0x1300349a, 0x1301349a, 0x1310349a, 0x1311349a,
        0x1700359b, 0x1701359b, 0x1710359b, 0x1711359b,
        0x1700369c, 0x1701369c, 0x1710369c, 0x1711369c,
        0x1300379d, 0x1301379d, 0x1310379d, 0x1311379d,
        0x1300389e, 0x1301389e, 0x1310389e, 0x1311389e,
        0x1700399f, 0x1701399f, 0x1710399f, 0x1711399f,
        0x030040a0, 0x030140a0, 0x17103aa0, 0x17113aa0,
        0x070041a1, 0x070141a1, 0x13103ba1, 0x13113ba1,
        0x070042a2, 0x070142a2, 0x17103ca2, 0x17113ca2,
        0x030043a3, 0x030143a3, 0x13103da3, 0x13113da3,
        0x070044a4, 0x070144a4, 0x13103ea4, 0x13113ea4,
        0x030045a5, 0x030145a5, 0x17103fa5, 0x17113fa5,
        0x030046a6, 0x030146a6, 0x131040a6, 0x131140a6,
        0x070047a7, 0x070147a7, 0x171041a7, 0x171141a7,
        0x070048a8, 0x070148a8, 0x171042a8, 0x171142a8,
        0x030049a9, 0x030149a9, 0x131043a9, 0x131143a9,
        0x170044aa, 0x170144aa, 0x171044aa, 0x171144aa,
        0x130045ab, 0x130145ab, 0x131045ab, 0x131145ab,
        0x130046ac, 0x130146ac, 0x131046ac, 0x131146ac,
        0x170047ad, 0x170147ad, 0x171047ad, 0x171147ad,
        0x170048ae, 0x170148ae, 0x171048ae, 0x171148ae,
        0x130049af, 0x130149af, 0x131049af, 0x131149af,
        0x070050b0, 0x070150b0, 0x13104ab0, 0x13114ab0,
        0x030051b1, 0x030151b1, 0x17104bb1, 0x17114bb1,
        0x030052b2, 0x030152b2, 0x13104cb2, 0x13114cb2,
        0x070053b3, 0x070153b3, 0x17104db3, 0x17114db3,
        0x030054b4, 0x030154b4, 0x17104eb4, 0x17114eb4,
        0x070055b5, 0x070155b5, 0x13104fb5, 0x13114fb5,
        0x070056b6, 0x070156b6, 0x171050b6, 0x171150b6,
        0x030057b7, 0x030157b7, 0x131051b7, 0x131151b7,
        0x030058b8, 0x030158b8, 0x131052b8, 0x131152b8,
        0x070059b9, 0x070159b9, 0x171053b9, 0x171153b9,
        0x130054ba, 0x130154ba, 0x131054ba, 0x131154ba,
        0x170055bb, 0x170155bb, 0x171055bb, 0x171155bb,
        0x170056bc, 0x170156bc, 0x171056bc, 0x171156bc,
        0x130057bd, 0x130157bd, 0x131057bd, 0x131157bd,
        0x130058be, 0x130158be, 0x131058be, 0x131158be,
        0x170059bf, 0x170159bf, 0x171059bf, 0x171159bf,
        0x070060c0, 0x070160c0, 0x17105ac0, 0x17115ac0,
        0x030061c1, 0x030161c1, 0x13105bc1, 0x13115bc1,
        0x030062c2, 0x030162c2, 0x17105cc2, 0x17115cc2,
        0x070063c3, 0x070163c3, 0x13105dc3, 0x13115dc3,
        0x030064c4, 0x030164c4, 0x13105ec4, 0x13115ec4,
        0x070065c5, 0x070165c5, 0x17105fc5, 0x17115fc5,
        0x070066c6, 0x070166c6, 0x171060c6, 0x171160c6,
        0x030067c7, 0x030167c7, 0x131061c7, 0x131161c7,
        0x030068c8, 0x030168c8, 0x131062c8, 0x131162c8,
        0x070069c9, 0x070169c9, 0x171063c9, 0x171163c9,
        0x130064ca, 0x130164ca, 0x131064ca, 0x131164ca,
        0x170065cb, 0x170165cb, 0x171065cb, 0x171165cb,
        0x170066cc, 0x170166cc, 0x171066cc, 0x171166cc,
        0x130067cd, 0x130167cd, 0x131067cd, 0x131167cd,
        0x130068ce, 0x130168ce, 0x131068ce, 0x131168ce,
        0x170069cf, 0x170169cf, 0x171069cf, 0x171169cf,
        0x030070d0, 0x030170d0, 0x17106ad0, 0x17116ad0,
        0x070071d1, 0x070171d1, 0x13106bd1, 0x13116bd1,
        0x070072d2, 0x070172d2, 0x17106cd2, 0x17116cd2,
        0x030073d3, 0x030173d3, 0x13106dd3, 0x13116dd3,
        0x070074d4, 0x070174d4, 0x13106ed4, 0x13116ed4,
        0x030075d5, 0x030175d5, 0x17106fd5, 0x17116fd5,
        0x030076d6, 0x030176d6, 0x131070d6, 0x131170d6,
        0x070077d7, 0x070177d7, 0x171071d7, 0x171171d7,
        0x070078d8, 0x070178d8, 0x171072d8, 0x171172d8,
        0x030079d9, 0x030179d9, 0x131073d9, 0x131173d9,
        0x170074da, 0x170174da, 0x171074da, 0x171174da,
        0x130075db, 0x130175db, 0x131075db, 0x131175db,
        0x130076dc, 0x130176dc, 0x131076dc, 0x131176dc,
        0x170077dd, 0x170177dd, 0x171077dd, 0x171177dd,
        0x170078de, 0x170178de, 0x171078de, 0x171178de,
        0x130079df, 0x130179df, 0x131079df, 0x131179df,
        0x830080e0, 0x830180e0, 0x13107ae0, 0x13117ae0,
        0x870081e1, 0x870181e1, 0x17107be1, 0x17117be1,
        0x870082e2, 0x870182e2, 0x13107ce2, 0x13117ce2,
        0x830083e3, 0x830183e3, 0x17107de3, 0x17117de3,
        0x870084e4, 0x870184e4, 0x17107ee4, 0x17117ee4,
        0x830085e5, 0x830185e5, 0x13107fe5, 0x13117fe5,
        0x830086e6, 0x830186e6, 0x931080e6, 0x931180e6,
        0x870087e7, 0x870187e7, 0x971081e7, 0x971181e7,
        0x870088e8, 0x870188e8, 0x971082e8, 0x971182e8,
        0x830089e9, 0x830189e9, 0x931083e9, 0x931183e9,
        0x970084ea, 0x970184ea, 0x971084ea, 0x971184ea,
        0x930085eb, 0x930185eb, 0x931085eb, 0x931185eb,
        0x930086ec, 0x930186ec, 0x931086ec, 0x931186ec,
        0x970087ed, 0x970187ed, 0x971087ed, 0x971187ed,
        0x970088ee, 0x970188ee, 0x971088ee, 0x971188ee,
        0x930089ef, 0x930189ef, 0x931089ef, 0x931189ef,
        0x870090f0, 0x870190f0, 0x93108af0, 0x93118af0,
        0x830091f1, 0x830191f1, 0x97108bf1, 0x97118bf1,
        0x830092f2, 0x830192f2, 0x93108cf2, 0x93118cf2,
        0x870093f3, 0x870193f3, 0x97108df3, 0x97118df3,
        0x830094f4, 0x830194f4, 0x97108ef4, 0x97118ef4,
        0x870095f5, 0x870195f5, 0x93108ff5, 0x93118ff5,
        0x870096f6, 0x870196f6, 0x971090f6, 0x971190f6,
        0x830097f7, 0x830197f7, 0x931091f7, 0x931191f7,
        0x830098f8, 0x830198f8, 0x931092f8, 0x931192f8,
        0x870099f9, 0x870199f9, 0x971093f9, 0x971193f9,
        0x930094fa, 0x930194fa, 0x931094fa, 0x931194fa,
        0x970095fb, 0x970195fb, 0x971095fb, 0x971195fb,
        0x970096fc, 0x970196fc, 0x971096fc, 0x971196fc,
        0x930097fd, 0x930197fd, 0x931097fd, 0x931197fd,
        0x930098fe, 0x930198fe, 0x931098fe, 0x931198fe,
        0x970099ff, 0x970199ff, 0x971099ff, 0x971199ff,
    };

    MK_INSN(das, "das");

    init_inregs(NULL);

    for (i = 0; i < 1024; ++i) {
        unsigned tmp = test_cases[i];
        inregs.eax = tmp & 0xff;
        inregs.eflags = (tmp >> 16) & 0xff;
	exec_in_big_real_mode(&insn_das);
	if (!regs_equal(R_AX)
            || outregs.eax != ((tmp >> 8) & 0xff)
            || (outregs.eflags & 0xff) != (tmp >> 24)) {
	    ++nr_fail;
	    break;
        }
    }
    report("DAS", ~0, nr_fail == 0);
}

static void test_cwd_cdq(void)
{
	/* Sign-bit set */
	MK_INSN(cwd_1, "mov $0x8000, %ax\n\t"
		       "cwd\n\t");

	/* Sign-bit not set */
	MK_INSN(cwd_2, "mov $0x1000, %ax\n\t"
		       "cwd\n\t");

	/* Sign-bit set */
	MK_INSN(cdq_1, "mov $0x80000000, %eax\n\t"
		       "cdq\n\t");

	/* Sign-bit not set */
	MK_INSN(cdq_2, "mov $0x10000000, %eax\n\t"
		       "cdq\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_cwd_1);
	report("cwd 1", R_AX | R_DX,
	       outregs.eax == 0x8000 && outregs.edx == 0xffff);

	exec_in_big_real_mode(&insn_cwd_2);
	report("cwd 2", R_AX | R_DX,
	       outregs.eax == 0x1000 && outregs.edx == 0);

	exec_in_big_real_mode(&insn_cdq_1);
	report("cdq 1", R_AX | R_DX,
	       outregs.eax == 0x80000000 && outregs.edx == 0xffffffff);

	exec_in_big_real_mode(&insn_cdq_2);
	report("cdq 2", R_AX | R_DX,
	       outregs.eax == 0x10000000 && outregs.edx == 0);
}

static struct {
        void *address;
        unsigned short sel;
} __attribute__((packed)) desc = {
	(void *)0x1234,
	0x10,
};

static void test_lds_lss(void)
{
	init_inregs(&(struct regs){ .ebx = (unsigned long)&desc });

	MK_INSN(lds, "pushl %ds\n\t"
		     "lds (%ebx), %eax\n\t"
		     "mov %ds, %ebx\n\t"
		     "popl %ds\n\t");
	exec_in_big_real_mode(&insn_lds);
	report("lds", R_AX | R_BX,
		outregs.eax == (unsigned long)desc.address &&
		outregs.ebx == desc.sel);

	MK_INSN(les, "les (%ebx), %eax\n\t"
		     "mov %es, %ebx\n\t");
	exec_in_big_real_mode(&insn_les);
	report("les", R_AX | R_BX,
		outregs.eax == (unsigned long)desc.address &&
		outregs.ebx == desc.sel);

	MK_INSN(lfs, "pushl %fs\n\t"
		     "lfs (%ebx), %eax\n\t"
		     "mov %fs, %ebx\n\t"
		     "popl %fs\n\t");
	exec_in_big_real_mode(&insn_lfs);
	report("lfs", R_AX | R_BX,
		outregs.eax == (unsigned long)desc.address &&
		outregs.ebx == desc.sel);

	MK_INSN(lgs, "pushl %gs\n\t"
		     "lgs (%ebx), %eax\n\t"
		     "mov %gs, %ebx\n\t"
		     "popl %gs\n\t");
	exec_in_big_real_mode(&insn_lgs);
	report("lgs", R_AX | R_BX,
		outregs.eax == (unsigned long)desc.address &&
		outregs.ebx == desc.sel);

	MK_INSN(lss, "mov %ss, %dx\n\t"
		     "lss (%ebx), %eax\n\t"
		     "mov %ss, %ebx\n\t"
		     "mov %dx, %ss\n\t");
	exec_in_big_real_mode(&insn_lss);
	report("lss", R_AX | R_BX,
		outregs.eax == (unsigned long)desc.address &&
		outregs.ebx == desc.sel);
}

static void test_jcxz(void)
{
	MK_INSN(jcxz1, "jcxz 1f\n\t"
		       "mov $0x1234, %eax\n\t"
		       "1:\n\t");
	MK_INSN(jcxz2, "mov $0x100, %ecx\n\t"
		       "jcxz 1f\n\t"
		       "mov $0x1234, %eax\n\t"
		       "mov $0, %ecx\n\t"
		       "1:\n\t");
	MK_INSN(jcxz3, "mov $0x10000, %ecx\n\t"
		       "jcxz 1f\n\t"
		       "mov $0x1234, %eax\n\t"
		       "1:\n\t");
	MK_INSN(jecxz1, "jecxz 1f\n\t"
			"mov $0x1234, %eax\n\t"
			"1:\n\t");
	MK_INSN(jecxz2, "mov $0x10000, %ecx\n\t"
			"jecxz 1f\n\t"
			"mov $0x1234, %eax\n\t"
			"mov $0, %ecx\n\t"
			"1:\n\t");

	init_inregs(NULL);

	exec_in_big_real_mode(&insn_jcxz1);
	report("jcxz short 1", 0, 1);

	exec_in_big_real_mode(&insn_jcxz2);
	report("jcxz short 2", R_AX, outregs.eax == 0x1234);

	exec_in_big_real_mode(&insn_jcxz3);
	report("jcxz short 3", R_CX, outregs.ecx == 0x10000);

	exec_in_big_real_mode(&insn_jecxz1);
	report("jecxz short 1", 0, 1);

	exec_in_big_real_mode(&insn_jecxz2);
	report("jecxz short 2", R_AX, outregs.eax == 0x1234);
}

static void test_cpuid(void)
{
    MK_INSN(cpuid, "cpuid");
    unsigned function = 0x1234;
    unsigned eax, ebx, ecx, edx;

    init_inregs(&(struct regs){ .eax = function });

    eax = inregs.eax;
    ecx = inregs.ecx;
    asm("cpuid" : "+a"(eax), "=b"(ebx), "+c"(ecx), "=d"(edx));
    exec_in_big_real_mode(&insn_cpuid);
    report("cpuid", R_AX|R_BX|R_CX|R_DX,
	   outregs.eax == eax && outregs.ebx == ebx
	   && outregs.ecx == ecx && outregs.edx == edx);
}

static void test_ss_base_for_esp_ebp(void)
{
    MK_INSN(ssrel1, "mov %ss, %ax; mov %bx, %ss; movl (%ebp), %ebx; mov %ax, %ss");
    MK_INSN(ssrel2, "mov %ss, %ax; mov %bx, %ss; movl (%ebp,%edi,8), %ebx; mov %ax, %ss");
    static unsigned array[] = { 0x12345678, 0, 0, 0, 0x87654321 };

    init_inregs(&(struct regs){ .ebx = 1, .ebp = (unsigned)array });

    exec_in_big_real_mode(&insn_ssrel1);
    report("ss relative addressing (1)", R_AX | R_BX, outregs.ebx == 0x87654321);

    inregs.ebx = 1;
    inregs.ebp = (unsigned)array;
    inregs.edi = 0;
    exec_in_big_real_mode(&insn_ssrel2);
    report("ss relative addressing (2)", R_AX | R_BX, outregs.ebx == 0x87654321);
}

extern unsigned long long r_gdt[];

static void test_sgdt_sidt(void)
{
    MK_INSN(sgdt, "sgdtw (%eax)");
    MK_INSN(sidt, "sidtw (%eax)");
    struct table_descr x, y;

    init_inregs(&(struct regs){ .eax = (unsigned)&y });

    asm volatile("sgdtw %0" : "=m"(x));
    exec_in_big_real_mode(&insn_sgdt);
    report("sgdt", 0, x.limit == y.limit && x.base == y.base);

    inregs.eax = (unsigned)&y;
    asm volatile("sidtw %0" : "=m"(x));
    exec_in_big_real_mode(&insn_sidt);
    report("sidt", 0, x.limit == y.limit && x.base == y.base);
}

static void test_sahf(void)
{
    MK_INSN(sahf, "sahf; pushfw; mov (%esp), %al; popfw");

    init_inregs(&(struct regs){ .eax = 0xfd00 });

    exec_in_big_real_mode(&insn_sahf);
    report("sahf", R_AX, outregs.eax == (inregs.eax | 0xd7));
}

static void test_lahf(void)
{
    MK_INSN(lahf, "pushfw; mov %al, (%esp); popfw; lahf");

    init_inregs(&(struct regs){ .eax = 0xc7 });

    exec_in_big_real_mode(&insn_lahf);
    report("lahf", R_AX, (outregs.eax >> 8) == inregs.eax);
}

static void test_movzx_movsx(void)
{
    MK_INSN(movsx, "movsx %al, %ebx");
    MK_INSN(movzx, "movzx %al, %ebx");
    MK_INSN(movzsah, "movsx %ah, %ebx");
    MK_INSN(movzxah, "movzx %ah, %ebx");

    init_inregs(&(struct regs){ .eax = 0x1234569c });

    exec_in_big_real_mode(&insn_movsx);
    report("movsx", R_BX, outregs.ebx == (signed char)inregs.eax);
    exec_in_big_real_mode(&insn_movzx);
    report("movzx", R_BX, outregs.ebx == (unsigned char)inregs.eax);
    exec_in_big_real_mode(&insn_movzsah);
    report("movsx ah", R_BX, outregs.ebx == (signed char)(inregs.eax>>8));
    exec_in_big_real_mode(&insn_movzxah);
    report("movzx ah", R_BX, outregs.ebx == (unsigned char)(inregs.eax >> 8));
}

static void test_bswap(void)
{
    MK_INSN(bswap, "bswap %ecx");

    init_inregs(&(struct regs){ .ecx = 0x12345678 });

    exec_in_big_real_mode(&insn_bswap);
    report("bswap", R_CX, outregs.ecx == 0x78563412);
}

static void test_aad(void)
{
    MK_INSN(aad, "aad");

    init_inregs(&(struct regs){ .eax = 0x12345678 });

    exec_in_big_real_mode(&insn_aad);
    report("aad", R_AX, outregs.eax == 0x123400d4);
}

static void test_aam(void)
{
    MK_INSN(aam, "aam");

    init_inregs(&(struct regs){ .eax = 0x76543210 });

    exec_in_big_real_mode(&insn_aam);
    report("aam", R_AX, outregs.eax == 0x76540106);
}

static void test_xlat(void)
{
    MK_INSN(xlat, "xlat");
    u8 table[256];
    int i;

    for (i = 0; i < 256; i++) {
        table[i] = i + 1;
    }

    init_inregs(&(struct regs){ .eax = 0x89abcdef, .ebx = (u32)table });

    exec_in_big_real_mode(&insn_xlat);
    report("xlat", R_AX, outregs.eax == 0x89abcdf0);
}

static void test_salc(void)
{
    MK_INSN(clc_salc, "clc; .byte 0xd6");
    MK_INSN(stc_salc, "stc; .byte 0xd6");

    init_inregs(&(struct regs){ .eax = 0x12345678 });

    exec_in_big_real_mode(&insn_clc_salc);
    report("salc (1)", R_AX, outregs.eax == 0x12345600);
    exec_in_big_real_mode(&insn_stc_salc);
    report("salc (2)", R_AX, outregs.eax == 0x123456ff);
}

static void test_fninit(void)
{
	u16 fcw = -1, fsw = -1;
	MK_INSN(fninit, "fninit ; fnstsw (%eax) ; fnstcw (%ebx)");

	init_inregs(&(struct regs){ .eax = (u32)&fsw, .ebx = (u32)&fcw });

	exec_in_big_real_mode(&insn_fninit);
	report("fninit", 0, fsw == 0 && (fcw & 0x103f) == 0x003f);
}

static void test_nopl(void)
{
	MK_INSN(nopl1, ".byte 0x90\n\r"); // 1 byte nop
	MK_INSN(nopl2, ".byte 0x66, 0x90\n\r"); // 2 bytes nop
	MK_INSN(nopl3, ".byte 0x0f, 0x1f, 0x00\n\r"); // 3 bytes nop
	MK_INSN(nopl4, ".byte 0x0f, 0x1f, 0x40, 0x00\n\r"); // 4 bytes nop
	exec_in_big_real_mode(&insn_nopl1);
	exec_in_big_real_mode(&insn_nopl2);
	exec_in_big_real_mode(&insn_nopl3);
	exec_in_big_real_mode(&insn_nopl4);
	report("nopl", 0, 1);
}

static u64 perf_baseline;

#define PERF_COUNT_SHIFT (30)
// 2**27 = ~1 second at 100 mIPS
#define PERF_COUNT (1 << PERF_COUNT_SHIFT)

#define MK_INSN_PERF(name, insn)                                \
	MK_INSN(name, "rdtsc; mov %eax, %ebx; mov %edx, %esi\n" \
		      "1:" insn "\n"                            \
		      ".byte 0x67; loop 1b\n"                   \
		      "rdtsc");

static u64 cycles_in_big_real_mode(struct insn_desc *insn)
{
	u64 start, end;

	init_inregs(&(struct regs){ .ecx = PERF_COUNT });

	exec_in_big_real_mode(insn);
	start = ((u64)outregs.esi << 32) | outregs.ebx;
	end = ((u64)outregs.edx << 32) | outregs.eax;

	return end - start;
}

static void test_perf_loop(void)
{
	/*
	 * This test runs simple instructions that should roughly take the
	 * the same time to emulate: PERF_COUNT iterations of "loop" and 3
	 * setup instructions.  Other performance tests can run PERF_COUNT
	 * iterations of the same instruction and subtract the cycle count
	 * of this test.
	 */
	MK_INSN_PERF(perf_loop, "");
	perf_baseline = cycles_in_big_real_mode(&insn_perf_loop);
	print_serial_u32(perf_baseline * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated jump instruction\n");
}

static void test_perf_mov(void)
{
	u64 cyc;

	MK_INSN_PERF(perf_move, "mov %esi, %edi");
	cyc = cycles_in_big_real_mode(&insn_perf_move);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated move instruction\n");
}

static void test_perf_arith(void)
{
	u64 cyc;

	MK_INSN_PERF(perf_arith, "add $4, %edi");
	cyc = cycles_in_big_real_mode(&insn_perf_arith);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated arithmetic instruction\n");
}

static void test_perf_memory_load(void)
{
	u64 cyc, tmp;

	MK_INSN_PERF(perf_memory_load, "cmpl $0, (%edi)");

	init_inregs(&(struct regs){ .edi = (u32)&tmp });

	cyc = cycles_in_big_real_mode(&insn_perf_memory_load);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated memory load instruction\n");
}

static void test_perf_memory_store(void)
{
	u64 cyc, tmp;

	MK_INSN_PERF(perf_memory_store, "mov %ax, (%edi)");
	init_inregs(&(struct regs){ .edi = (u32)&tmp });

	cyc = cycles_in_big_real_mode(&insn_perf_memory_store);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated memory store instruction\n");
}

static void test_perf_memory_rmw(void)
{
	u64 cyc, tmp;

	MK_INSN_PERF(perf_memory_rmw, "addl $1, (%edi)");
	init_inregs(&(struct regs){ .edi = (u32)&tmp });
	cyc = cycles_in_big_real_mode(&insn_perf_memory_rmw);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated memory RMW instruction\n");
}

static void test_perf_memory_shl(void)
{
	u64 cyc, tmp;

	MK_INSN_PERF(perf_memory_shl, "shl $1, %edi");
	init_inregs(&(struct regs){ .edi = (u32)&tmp });
	cyc = cycles_in_big_real_mode(&insn_perf_memory_shl);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated SHL instruction\n");
}

static void test_perf_memory_adc(void)
{
	u64 cyc, tmp;

	MK_INSN_PERF(perf_memory_adc, "adc $1, %edi");
	init_inregs(&(struct regs){ .edi = (u32)&tmp });
	cyc = cycles_in_big_real_mode(&insn_perf_memory_adc);
	print_serial_u32(cyc * 1000 >> PERF_COUNT_SHIFT);
	print_serial(" millicycles/emulated ADC instruction\n");
}

static void test_dr_mod(void)
{
	MK_INSN(drmod, "movl %ebx, %dr0\n\t"
		       ".byte 0x0f \n\t .byte 0x21 \n\t .byte 0x0\n\t");

	init_inregs(&(struct regs){ .eax = 0xdead, .ebx = 0xaced });

	exec_in_big_real_mode(&insn_drmod);
	report("mov dr with mod bits", R_AX | R_BX, outregs.eax == 0xaced);
}

static void test_smsw(void)
{
	MK_INSN(smsw, "movl %cr0, %ebx\n\t"
		      "movl %ebx, %ecx\n\t"
		      "or $0x40000000, %ebx\n\t"
		      "movl %ebx, %cr0\n\t"
		      "smswl %eax\n\t"
		      "movl %ecx, %cr0\n\t");

	init_inregs(&(struct regs){ .eax = 0x12345678 });

	exec_in_big_real_mode(&insn_smsw);
	report("smsw", R_AX | R_BX | R_CX, outregs.eax == outregs.ebx);
}

static void test_xadd(void)
{
	MK_INSN(xadd, "xaddl %eax, %eax\n\t");

	init_inregs(&(struct regs){ .eax = 0x12345678 });

	exec_in_big_real_mode(&insn_xadd);
	report("xadd", R_AX, outregs.eax == inregs.eax * 2);
}


void realmode_start(void)
{
    // enable interrupts (v86 only)
    outb(0, 0x21);
    outb(0, 0xa1);

	test_null();

	test_shld();
	test_push_pop();
	test_pusha_popa();
	test_mov_imm();
	test_cmp_imm();
	test_add_imm();
	test_sub_imm();
	test_xor_imm();
	test_io();
	test_eflags_insn();
	test_jcc_short();
	test_jcc_near();
	/* test_call() uses short jump so call it after testing jcc */
	test_call();
	/* long jmp test uses call near so test it after testing call */
	test_long_jmp();
	test_xchg();
	test_iret();
	test_int();
	test_sti_inhibit();
	test_imul();
	test_mul();
	test_div();
	test_idiv();
	test_loopcc();
	test_cbw();
	test_cwd_cdq();
	test_das();
	test_lds_lss();
	test_jcxz();
	test_cpuid();
	test_ss_base_for_esp_ebp();
	test_sgdt_sidt();
	test_lahf();
	test_sahf();
	test_movzx_movsx();
	test_bswap();
	test_aad();
	test_aam();
	test_xlat();
	test_salc();
	test_fninit();
	test_dr_mod();
	test_smsw();
	test_nopl();
	test_xadd();
	test_perf_loop();
	test_perf_mov();
	test_perf_arith();
	test_perf_memory_shl();
	test_perf_memory_adc();
	test_perf_memory_load();
	test_perf_memory_store();
	test_perf_memory_rmw();

	exit(failed);
}

unsigned long long r_gdt[] = { 0, 0x9b000000ffff, 0x93000000ffff };

struct table_descr r_gdt_descr = { sizeof(r_gdt) - 1, &r_gdt };
struct table_descr r_idt_descr = { 0x3ff, 0 };

asm(
	".section .init \n\t"

	".code32 \n\t"

	"mb_magic = 0x1BADB002 \n\t"
	"mb_flags = 0x0 \n\t"

	"# multiboot header \n\t"
	".long mb_magic, mb_flags, 0 - (mb_magic + mb_flags) \n\t"

	".globl start \n\t"
	".data \n\t"
	". = . + 4096 \n\t"
	"stacktop: \n\t"

	".text \n\t"
	"start: \n\t"
	"lgdt r_gdt_descr \n\t"
	"lidt r_idt_descr \n\t"
	"ljmp $8, $1f; 1: \n\t"
	".code16gcc \n\t"
	"mov $16, %eax \n\t"
	"mov %ax, %ds \n\t"
	"mov %ax, %es \n\t"
	"mov %ax, %fs \n\t"
	"mov %ax, %gs \n\t"
	"mov %ax, %ss \n\t"
	"mov %cr0, %eax \n\t"
	"btc $0, %eax \n\t"
	"mov %eax, %cr0 \n\t"
	"ljmp $0, $realmode_entry \n\t"

	"realmode_entry: \n\t"

	"xor %ax, %ax \n\t"
	"mov %ax, %ds \n\t"
	"mov %ax, %es \n\t"
	"mov %ax, %ss \n\t"
	"mov %ax, %fs \n\t"
	"mov %ax, %gs \n\t"
	"mov $stacktop, %esp\n\t"
	"ljmp $0, $realmode_start \n\t"

	".code16gcc \n\t"
	);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/kvm-unit-tests/x86/realmode.lds                                                    0000644 0000000 0000000 00000000311 00000000000 016654  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       SECTIONS
{
    . = 16K;
    stext = .;
    .text : { *(.init) *(.text) }
    . = ALIGN(4K);
    .data : { *(.data) *(.rodata*) }
    . = ALIGN(16);
    .bss : { *(.bss) }
    edata = .;
}
ENTRY(start)
                                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/x86/rmap_chain.c                                                    0000644 0000000 0000000 00000002011 00000000000 016624  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* test long rmap chains */

#include "libcflat.h"
#include "fwcfg.h"
#include "vm.h"
#include "smp.h"

int main (void)
{
    int i;
    int nr_pages;
    void *target_page, *virt_addr;

    setup_vm();

    nr_pages = fwcfg_get_u64(FW_CFG_RAM_SIZE) / PAGE_SIZE;
    nr_pages -= 1000;
    target_page = alloc_page();

    virt_addr = (void *) 0xfffffa000;
    for (i = 0; i < nr_pages; i++) {
        install_page(phys_to_virt(read_cr3()), virt_to_phys(target_page),
                     virt_addr);
        virt_addr += PAGE_SIZE;
    }
    printf("created %d mappings\n", nr_pages);

    virt_addr = (void *) 0xfffffa000;
    for (i = 0; i < nr_pages; i++) {
        unsigned long *touch = virt_addr;

        *touch = 0;
        virt_addr += PAGE_SIZE;
    }
    printf("instantiated mappings\n");

    virt_addr += PAGE_SIZE;
    install_pte(phys_to_virt(read_cr3()), 1, virt_addr,
                0 | PT_PRESENT_MASK | PT_WRITABLE_MASK, target_page);

    *(unsigned long *)virt_addr = 0;
    printf("PASS\n");

    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/kvm-unit-tests/x86/s3.c                                                            0000644 0000000 0000000 00000004176 00000000000 015066  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "x86/acpi.h"
#include "asm/io.h"

u32* find_resume_vector_addr(void)
{
    struct facs_descriptor_rev1 *facs = find_acpi_table_addr(FACS_SIGNATURE);
    if (!facs)
        return 0;
    printf("FACS is at %p\n", facs);
    return &facs->firmware_waking_vector;
}

#define RTC_SECONDS_ALARM       1
#define RTC_MINUTES_ALARM       3
#define RTC_HOURS_ALARM         5
#define RTC_ALARM_DONT_CARE     0xC0

#define RTC_REG_A               10
#define RTC_REG_B               11
#define RTC_REG_C               12

#define REG_A_UIP               0x80
#define REG_B_AIE               0x20

static inline int rtc_in(u8 reg)
{
    outb(reg, 0x70);
    return inb(0x71);
}

static inline void rtc_out(u8 reg, u8 val)
{
    outb(reg, 0x70);
    outb(val, 0x71);
}

extern char resume_start, resume_end;

int main(int argc, char **argv)
{
	struct fadt_descriptor_rev1 *fadt = find_acpi_table_addr(FACP_SIGNATURE);
	volatile u32 *resume_vector_ptr = find_resume_vector_addr();
	char *addr, *resume_vec = (void*)0x1000;

	*resume_vector_ptr = (u32)(ulong)resume_vec;

	printf("resume vector addr is %p\n", resume_vector_ptr);
	for (addr = &resume_start; addr < &resume_end; addr++)
		*resume_vec++ = *addr;
	printf("copy resume code from %p\n", &resume_start);

	printf("PM1a event registers at %x\n", fadt->pm1a_evt_blk);
	outw(0x400, fadt->pm1a_evt_blk + 2);

	/* Setup RTC alarm to wake up on the next second.  */
	while ((rtc_in(RTC_REG_A) & REG_A_UIP) == 0);
	while ((rtc_in(RTC_REG_A) & REG_A_UIP) != 0);
	rtc_in(RTC_REG_C);
	rtc_out(RTC_SECONDS_ALARM, RTC_ALARM_DONT_CARE);
	rtc_out(RTC_MINUTES_ALARM, RTC_ALARM_DONT_CARE);
	rtc_out(RTC_HOURS_ALARM, RTC_ALARM_DONT_CARE);
	rtc_out(RTC_REG_B, rtc_in(RTC_REG_B) | REG_B_AIE);

	*(volatile int*)0 = 0;
	asm volatile("outw %0, %1" :: "a"((short)0x2400), "d"((short)fadt->pm1a_cnt_blk):"memory");
	while(1)
		*(volatile int*)0 = 1;

	return 0;
}

asm (
        ".global resume_start\n"
	".global resume_end\n"
	".code16\n"
	"resume_start:\n"
	"mov 0x0, %eax\n"
	"mov $0xf4, %dx\n"
	"out %eax, %dx\n"
	"1: hlt\n"
	"jmp 1b\n"
	"resume_end:\n"
#ifdef __i386__
	".code32\n"
#else
	".code64\n"
#endif
    );
                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/kvm-unit-tests/x86/setjmp.c                                                        0000644 0000000 0000000 00000000364 00000000000 016036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "setjmp.h"

int main()
{
    volatile int i;
    jmp_buf j;

    if (setjmp(j) == 0) {
	    i = 0;
    }
    printf("%d\n", i);
    if (++i < 10) {
	    longjmp(j, 1);
    }

    printf("done\n");
    return 0;
}
                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/x86/sieve.c                                                         0000644 0000000 0000000 00000001523 00000000000 015645  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "vm.h"
#include "libcflat.h"

int sieve(char* data, int size)
{
    int i, j, r = 0;

    for (i = 0; i < size; ++i)
	data[i] = 1;

    data[0] = data[1] = 0;

    for (i = 2; i < size; ++i)
	if (data[i]) {
	    ++r;
	    for (j = i*2; j < size; j += i)
		data[j] = 0;
	}
    return r;
}

void test_sieve(const char *msg, char *data, int size)
{
    int r;

    printf("%s:", msg);
    r = sieve(data, size);
    printf("%d out of %d\n", r, size);
}

#define STATIC_SIZE 1000000
#define VSIZE 2000000
char static_data[STATIC_SIZE];

int main()
{
    void *v;
    int i;

    printf("starting sieve\n");
    test_sieve("static", static_data, STATIC_SIZE);
    setup_vm();
    test_sieve("mapped", static_data, STATIC_SIZE);
    for (i = 0; i < 3; ++i) {
	v = vmalloc(VSIZE);
	test_sieve("virtual", v, VSIZE);
	vfree(v);
    }

    return 0;
}
                                                                                                                                                                             source/v64/tests/kvm-unit-tests/x86/smap.c                                                          0000644 0000000 0000000 00000010621 00000000000 015471  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "x86/desc.h"
#include "x86/processor.h"
#include "x86/vm.h"

#define X86_FEATURE_SMAP	20

volatile int pf_count = 0;
volatile int save;
volatile unsigned test;


// When doing ring 3 tests, page fault handlers will always run on a
// separate stack (the ring 0 stack).  Seems easier to use the alt_stack
// mechanism for both ring 0 and ring 3.

void do_pf_tss(unsigned long error_code)
{
	pf_count++;
	save = test;

#ifndef __x86_64__
	tss.eflags |= X86_EFLAGS_AC;
#endif
}

extern void pf_tss(void);
asm ("pf_tss:\n"
#ifdef __x86_64__
        // no task on x86_64, save/restore caller-save regs
        "push %rax; push %rcx; push %rdx; push %rsi; push %rdi\n"
        "push %r8; push %r9; push %r10; push %r11\n"
	"mov 9*8(%rsp),%rsi\n"
#endif
	"call do_pf_tss\n"
#ifdef __x86_64__
        "pop %r11; pop %r10; pop %r9; pop %r8\n"
        "pop %rdi; pop %rsi; pop %rdx; pop %rcx; pop %rax\n"
#endif
	"add $"S", %"R "sp\n"
#ifdef __x86_64__
	"orl $" xstr(X86_EFLAGS_AC) ", 2*"S"(%"R "sp)\n"  // set EFLAGS.AC and retry
#endif
        "iret"W" \n\t"
        "jmp pf_tss\n\t");


#define USER_BASE	(1 << 24)
#define USER_VAR(v)	(*((__typeof__(&(v))) (((unsigned long)&v) + USER_BASE)))
#define USER_ADDR(v)   ((void *)((unsigned long)(&v) + USER_BASE))

static void init_test(int i)
{
	pf_count = 0;
	if (i) {
		invlpg(&test);
		invlpg(&USER_VAR(test));
	}
}

static void check_smap_nowp(void)
{
	test = 0x99;

	*get_pte(phys_to_virt(read_cr3()), USER_ADDR(test)) &= ~PT_WRITABLE_MASK;

	write_cr4(read_cr4() & ~X86_CR4_SMAP);
	write_cr0(read_cr0() & ~X86_CR0_WP);
	clac();
	write_cr3(read_cr3());

	init_test(0);
	USER_VAR(test) = 0x99;
	report("write from user page with SMAP=0, AC=0, WP=0, PTE.U=1 && PTE.W=0", pf_count == 0);

	write_cr4(read_cr4() | X86_CR4_SMAP);
	write_cr3(read_cr3());

	init_test(0);
	(void)USER_VAR(test);
	report("read from user page with SMAP=1, AC=0, WP=0, PTE.U=1 && PTE.W=0", pf_count == 1 && save == 0x99);

	/* Undo changes */
	*get_pte(phys_to_virt(read_cr3()), USER_ADDR(test)) |= PT_WRITABLE_MASK;

	write_cr0(read_cr0() | X86_CR0_WP);
	write_cr3(read_cr3());
}

int main(int ac, char **av)
{
	unsigned long i;

	if (!(cpuid_indexed(7, 0).b & (1 << X86_FEATURE_SMAP))) {
		printf("SMAP not enabled\n");
		return report_summary();
	}

	setup_vm();
	setup_alt_stack();
	set_intr_alt_stack(14, pf_tss);

	// Map first 16MB as supervisor pages
	for (i = 0; i < USER_BASE; i += PAGE_SIZE) {
		*get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) &= ~PT_USER_MASK;
		invlpg((void *)i);
	}

	// Present the same 16MB as user pages in the 16MB-32MB range
	for (i = USER_BASE; i < 2 * USER_BASE; i += PAGE_SIZE) {
		*get_pte(phys_to_virt(read_cr3()), phys_to_virt(i)) &= ~USER_BASE;
		invlpg((void *)i);
	}

	clac();
	write_cr4(read_cr4() | X86_CR4_SMAP);
	write_cr3(read_cr3());

	for (i = 0; i < 2; i++) {
		if (i)
			printf("testing with INVLPG\n");
		else
			printf("testing without INVLPG\n");

		init_test(i);
		clac();
		test = 42;
		report("write to supervisor page", pf_count == 0 && test == 42);

		init_test(i);
		stac();
		(void)USER_VAR(test);
		report("read from user page with AC=1", pf_count == 0);

		init_test(i);
		clac();
		(void)USER_VAR(test);
		report("read from user page with AC=0", pf_count == 1 && save == 42);

		init_test(i);
		stac();
		save = 0;
		USER_VAR(test) = 43;
		report("write to user page with AC=1", pf_count == 0 && test == 43);

		init_test(i);
		clac();
		USER_VAR(test) = 44;
		report("read from user page with AC=0", pf_count == 1 && test == 44 && save == 43);

		init_test(i);
		stac();
		test = -1;
		asm("or $(" xstr(USER_BASE) "), %"R "sp \n"
		    "push $44 \n "
		    "decl test\n"
		    "and $~(" xstr(USER_BASE) "), %"R "sp \n"
		    "pop %"R "ax\n"
		    "movl %eax, test");
		report("write to user stack with AC=1", pf_count == 0 && test == 44);

		init_test(i);
		clac();
		test = -1;
		asm("or $(" xstr(USER_BASE) "), %"R "sp \n"
		    "push $45 \n "
		    "decl test\n"
		    "and $~(" xstr(USER_BASE) "), %"R "sp \n"
		    "pop %"R "ax\n"
		    "movl %eax, test");
		report("write to user stack with AC=0", pf_count == 1 && test == 45 && save == -1);

		/* This would be trapped by SMEP */
		init_test(i);
		clac();
		asm("jmp 1f + "xstr(USER_BASE)" \n"
		    "1: jmp 2f - "xstr(USER_BASE)" \n"
		    "2:");
		report("executing on user page with AC=0", pf_count == 0);
	}

	check_smap_nowp();

	// TODO: implicit kernel access from ring 3 (e.g. int)

	return report_summary();
}
                                                                                                               source/v64/tests/kvm-unit-tests/x86/smptest.c                                                       0000644 0000000 0000000 00000001007 00000000000 016226  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "smp.h"

unsigned nipis;

static void ipi_test(void *data)
{
    int n = (long)data;

    printf("ipi called, cpu %d\n", n);
    if (n != smp_id())
	printf("but wrong cpu %d\n", smp_id());
    else
        nipis++;
}

int main()
{
    int ncpus;
    int i;

    smp_init();

    ncpus = cpu_count();
    printf("found %d cpus\n", ncpus);
    for (i = 0; i < ncpus; ++i)
	on_cpu(i, ipi_test, (void *)(long)i);

    report("IPI to each CPU", nipis == ncpus);
    return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/kvm-unit-tests/x86/svm.c                                                           0000644 0000000 0000000 00000064104 00000000000 015343  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "svm.h"
#include "libcflat.h"
#include "processor.h"
#include "desc.h"
#include "msr.h"
#include "vm.h"
#include "smp.h"
#include "types.h"

/* for the nested page table*/
u64 *pml4e;
u64 *pdpe;
u64 *pde[4];
u64 *pte[2048];
void *scratch_page;

#define LATENCY_RUNS 1000000

u64 tsc_start;
u64 tsc_end;

u64 vmrun_sum, vmexit_sum;
u64 vmsave_sum, vmload_sum;
u64 stgi_sum, clgi_sum;
u64 latvmrun_max;
u64 latvmrun_min;
u64 latvmexit_max;
u64 latvmexit_min;
u64 latvmload_max;
u64 latvmload_min;
u64 latvmsave_max;
u64 latvmsave_min;
u64 latstgi_max;
u64 latstgi_min;
u64 latclgi_max;
u64 latclgi_min;
u64 runs;

u8 *io_bitmap;
u8 io_bitmap_area[16384];

static bool npt_supported(void)
{
   return cpuid(0x8000000A).d & 1;
}

static void setup_svm(void)
{
    void *hsave = alloc_page();
    u64 *page, address;
    int i,j;

    wrmsr(MSR_VM_HSAVE_PA, virt_to_phys(hsave));
    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_SVME);
    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NX);

    scratch_page = alloc_page();

    io_bitmap = (void *) (((ulong)io_bitmap_area + 4095) & ~4095);

    if (!npt_supported())
        return;

    printf("NPT detected - running all tests with NPT enabled\n");

    /*
     * Nested paging supported - Build a nested page table
     * Build the page-table bottom-up and map everything with 4k pages
     * to get enough granularity for the NPT unit-tests.
     */

    address = 0;

    /* PTE level */
    for (i = 0; i < 2048; ++i) {
        page = alloc_page();

        for (j = 0; j < 512; ++j, address += 4096)
            page[j] = address | 0x067ULL;

        pte[i] = page;
    }

    /* PDE level */
    for (i = 0; i < 4; ++i) {
        page = alloc_page();

        for (j = 0; j < 512; ++j)
            page[j] = (u64)pte[(i * 512) + j] | 0x027ULL;

        pde[i] = page;
    }

    /* PDPe level */
    pdpe   = alloc_page();
    for (i = 0; i < 4; ++i)
       pdpe[i] = ((u64)(pde[i])) | 0x27;

    /* PML4e level */
    pml4e    = alloc_page();
    pml4e[0] = ((u64)pdpe) | 0x27;
}

static u64 *npt_get_pde(u64 address)
{
    int i1, i2;

    address >>= 21;
    i1 = (address >> 9) & 0x3;
    i2 = address & 0x1ff;

    return &pde[i1][i2];
}

static u64 *npt_get_pte(u64 address)
{
    int i1, i2;

    address >>= 12;
    i1 = (address >> 9) & 0x7ff;
    i2 = address & 0x1ff;

    return &pte[i1][i2];
}

static void vmcb_set_seg(struct vmcb_seg *seg, u16 selector,
                         u64 base, u32 limit, u32 attr)
{
    seg->selector = selector;
    seg->attrib = attr;
    seg->limit = limit;
    seg->base = base;
}

static void vmcb_ident(struct vmcb *vmcb)
{
    u64 vmcb_phys = virt_to_phys(vmcb);
    struct vmcb_save_area *save = &vmcb->save;
    struct vmcb_control_area *ctrl = &vmcb->control;
    u32 data_seg_attr = 3 | SVM_SELECTOR_S_MASK | SVM_SELECTOR_P_MASK
        | SVM_SELECTOR_DB_MASK | SVM_SELECTOR_G_MASK;
    u32 code_seg_attr = 9 | SVM_SELECTOR_S_MASK | SVM_SELECTOR_P_MASK
        | SVM_SELECTOR_L_MASK | SVM_SELECTOR_G_MASK;
    struct descriptor_table_ptr desc_table_ptr;

    memset(vmcb, 0, sizeof(*vmcb));
    asm volatile ("vmsave" : : "a"(vmcb_phys) : "memory");
    vmcb_set_seg(&save->es, read_es(), 0, -1U, data_seg_attr);
    vmcb_set_seg(&save->cs, read_cs(), 0, -1U, code_seg_attr);
    vmcb_set_seg(&save->ss, read_ss(), 0, -1U, data_seg_attr);
    vmcb_set_seg(&save->ds, read_ds(), 0, -1U, data_seg_attr);
    sgdt(&desc_table_ptr);
    vmcb_set_seg(&save->gdtr, 0, desc_table_ptr.base, desc_table_ptr.limit, 0);
    sidt(&desc_table_ptr);
    vmcb_set_seg(&save->idtr, 0, desc_table_ptr.base, desc_table_ptr.limit, 0);
    ctrl->asid = 1;
    save->cpl = 0;
    save->efer = rdmsr(MSR_EFER);
    save->cr4 = read_cr4();
    save->cr3 = read_cr3();
    save->cr0 = read_cr0();
    save->dr7 = read_dr7();
    save->dr6 = read_dr6();
    save->cr2 = read_cr2();
    save->g_pat = rdmsr(MSR_IA32_CR_PAT);
    save->dbgctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
    ctrl->intercept = (1ULL << INTERCEPT_VMRUN) | (1ULL << INTERCEPT_VMMCALL);
    ctrl->iopm_base_pa = virt_to_phys(io_bitmap);

    if (npt_supported()) {
        ctrl->nested_ctl = 1;
        ctrl->nested_cr3 = (u64)pml4e;
    }
}

struct test {
    const char *name;
    bool (*supported)(void);
    void (*prepare)(struct test *test);
    void (*guest_func)(struct test *test);
    bool (*finished)(struct test *test);
    bool (*succeeded)(struct test *test);
    struct vmcb *vmcb;
    int exits;
    ulong scratch;
};

static inline void vmmcall(void)
{
    asm volatile ("vmmcall" : : : "memory");
}

static void test_thunk(struct test *test)
{
    test->guest_func(test);
    vmmcall();
}

struct regs {
        u64 rax;
        u64 rcx;
        u64 rdx;
        u64 rbx;
        u64 cr2;
        u64 rbp;
        u64 rsi;
        u64 rdi;
        u64 r8;
        u64 r9;
        u64 r10;
        u64 r11;
        u64 r12;
        u64 r13;
        u64 r14;
        u64 r15;
        u64 rflags;
};

struct regs regs;

// rax handled specially below

#define SAVE_GPR_C                              \
        "xchg %%rbx, regs+0x8\n\t"              \
        "xchg %%rcx, regs+0x10\n\t"             \
        "xchg %%rdx, regs+0x18\n\t"             \
        "xchg %%rbp, regs+0x28\n\t"             \
        "xchg %%rsi, regs+0x30\n\t"             \
        "xchg %%rdi, regs+0x38\n\t"             \
        "xchg %%r8, regs+0x40\n\t"              \
        "xchg %%r9, regs+0x48\n\t"              \
        "xchg %%r10, regs+0x50\n\t"             \
        "xchg %%r11, regs+0x58\n\t"             \
        "xchg %%r12, regs+0x60\n\t"             \
        "xchg %%r13, regs+0x68\n\t"             \
        "xchg %%r14, regs+0x70\n\t"             \
        "xchg %%r15, regs+0x78\n\t"

#define LOAD_GPR_C      SAVE_GPR_C

static void test_run(struct test *test, struct vmcb *vmcb)
{
    u64 vmcb_phys = virt_to_phys(vmcb);
    u64 guest_stack[10000];

    test->vmcb = vmcb;
    test->prepare(test);
    vmcb->save.rip = (ulong)test_thunk;
    vmcb->save.rsp = (ulong)(guest_stack + ARRAY_SIZE(guest_stack));
    regs.rdi = (ulong)test;
    do {
        tsc_start = rdtsc();
        asm volatile (
            "clgi \n\t"
            "vmload \n\t"
            "mov regs+0x80, %%r15\n\t"  // rflags
            "mov %%r15, 0x170(%0)\n\t"
            "mov regs, %%r15\n\t"       // rax
            "mov %%r15, 0x1f8(%0)\n\t"
            LOAD_GPR_C
            "vmrun \n\t"
            SAVE_GPR_C
            "mov 0x170(%0), %%r15\n\t"  // rflags
            "mov %%r15, regs+0x80\n\t"
            "mov 0x1f8(%0), %%r15\n\t"  // rax
            "mov %%r15, regs\n\t"
            "vmsave \n\t"
            "stgi"
            : : "a"(vmcb_phys)
            : "rbx", "rcx", "rdx", "rsi",
              "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15",
              "memory");
	tsc_end = rdtsc();
        ++test->exits;
    } while (!test->finished(test));

    report("%s", test->succeeded(test), test->name);
}

static bool smp_supported(void)
{
	return cpu_count() > 1;
}

static bool default_supported(void)
{
    return true;
}

static void default_prepare(struct test *test)
{
    vmcb_ident(test->vmcb);
    cli();
}

static bool default_finished(struct test *test)
{
    return true; /* one vmexit */
}

static void null_test(struct test *test)
{
}

static bool null_check(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_VMMCALL;
}

static void prepare_no_vmrun_int(struct test *test)
{
    test->vmcb->control.intercept &= ~(1ULL << INTERCEPT_VMRUN);
}

static bool check_no_vmrun_int(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_ERR;
}

static void test_vmrun(struct test *test)
{
    asm volatile ("vmrun" : : "a"(virt_to_phys(test->vmcb)));
}

static bool check_vmrun(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_VMRUN;
}

static void prepare_cr3_intercept(struct test *test)
{
    default_prepare(test);
    test->vmcb->control.intercept_cr_read |= 1 << 3;
}

static void test_cr3_intercept(struct test *test)
{
    asm volatile ("mov %%cr3, %0" : "=r"(test->scratch) : : "memory");
}

static bool check_cr3_intercept(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_READ_CR3;
}

static bool check_cr3_nointercept(struct test *test)
{
    return null_check(test) && test->scratch == read_cr3();
}

static void corrupt_cr3_intercept_bypass(void *_test)
{
    struct test *test = _test;
    extern volatile u32 mmio_insn;

    while (!__sync_bool_compare_and_swap(&test->scratch, 1, 2))
        pause();
    pause();
    pause();
    pause();
    mmio_insn = 0x90d8200f;  // mov %cr3, %rax; nop
}

static void prepare_cr3_intercept_bypass(struct test *test)
{
    default_prepare(test);
    test->vmcb->control.intercept_cr_read |= 1 << 3;
    on_cpu_async(1, corrupt_cr3_intercept_bypass, test);
}

static void test_cr3_intercept_bypass(struct test *test)
{
    ulong a = 0xa0000;

    test->scratch = 1;
    while (test->scratch != 2)
        barrier();

    asm volatile ("mmio_insn: mov %0, (%0); nop"
                  : "+a"(a) : : "memory");
    test->scratch = a;
}

static bool next_rip_supported(void)
{
    return (cpuid(SVM_CPUID_FUNC).d & 8);
}

static void prepare_next_rip(struct test *test)
{
    test->vmcb->control.intercept |= (1ULL << INTERCEPT_RDTSC);
}


static void test_next_rip(struct test *test)
{
    asm volatile ("rdtsc\n\t"
                  ".globl exp_next_rip\n\t"
                  "exp_next_rip:\n\t" ::: "eax", "edx");
}

static bool check_next_rip(struct test *test)
{
    extern char exp_next_rip;
    unsigned long address = (unsigned long)&exp_next_rip;

    return address == test->vmcb->control.next_rip;
}

static void prepare_mode_switch(struct test *test)
{
    test->vmcb->control.intercept_exceptions |= (1ULL << GP_VECTOR)
                                             |  (1ULL << UD_VECTOR)
                                             |  (1ULL << DF_VECTOR)
                                             |  (1ULL << PF_VECTOR);
    test->scratch = 0;
}

static void test_mode_switch(struct test *test)
{
    asm volatile("	cli\n"
		 "	ljmp *1f\n" /* jump to 32-bit code segment */
		 "1:\n"
		 "	.long 2f\n"
		 "	.long " xstr(KERNEL_CS32) "\n"
		 ".code32\n"
		 "2:\n"
		 "	movl %%cr0, %%eax\n"
		 "	btcl  $31, %%eax\n" /* clear PG */
		 "	movl %%eax, %%cr0\n"
		 "	movl $0xc0000080, %%ecx\n" /* EFER */
		 "	rdmsr\n"
		 "	btcl $8, %%eax\n" /* clear LME */
		 "	wrmsr\n"
		 "	movl %%cr4, %%eax\n"
		 "	btcl $5, %%eax\n" /* clear PAE */
		 "	movl %%eax, %%cr4\n"
		 "	movw %[ds16], %%ax\n"
		 "	movw %%ax, %%ds\n"
		 "	ljmpl %[cs16], $3f\n" /* jump to 16 bit protected-mode */
		 ".code16\n"
		 "3:\n"
		 "	movl %%cr0, %%eax\n"
		 "	btcl $0, %%eax\n" /* clear PE  */
		 "	movl %%eax, %%cr0\n"
		 "	ljmpl $0, $4f\n"   /* jump to real-mode */
		 "4:\n"
		 "	vmmcall\n"
		 "	movl %%cr0, %%eax\n"
		 "	btsl $0, %%eax\n" /* set PE  */
		 "	movl %%eax, %%cr0\n"
		 "	ljmpl %[cs32], $5f\n" /* back to protected mode */
		 ".code32\n"
		 "5:\n"
		 "	movl %%cr4, %%eax\n"
		 "	btsl $5, %%eax\n" /* set PAE */
		 "	movl %%eax, %%cr4\n"
		 "	movl $0xc0000080, %%ecx\n" /* EFER */
		 "	rdmsr\n"
		 "	btsl $8, %%eax\n" /* set LME */
		 "	wrmsr\n"
		 "	movl %%cr0, %%eax\n"
		 "	btsl  $31, %%eax\n" /* set PG */
		 "	movl %%eax, %%cr0\n"
		 "	ljmpl %[cs64], $6f\n"    /* back to long mode */
		 ".code64\n\t"
		 "6:\n"
		 "	vmmcall\n"
		 :: [cs16] "i"(KERNEL_CS16), [ds16] "i"(KERNEL_DS16),
		    [cs32] "i"(KERNEL_CS32), [cs64] "i"(KERNEL_CS64)
		 : "rax", "rbx", "rcx", "rdx", "memory");
}

static bool mode_switch_finished(struct test *test)
{
    u64 cr0, cr4, efer;

    cr0  = test->vmcb->save.cr0;
    cr4  = test->vmcb->save.cr4;
    efer = test->vmcb->save.efer;

    /* Only expect VMMCALL intercepts */
    if (test->vmcb->control.exit_code != SVM_EXIT_VMMCALL)
	    return true;

    /* Jump over VMMCALL instruction */
    test->vmcb->save.rip += 3;

    /* Do sanity checks */
    switch (test->scratch) {
    case 0:
        /* Test should be in real mode now - check for this */
        if ((cr0  & 0x80000001) || /* CR0.PG, CR0.PE */
            (cr4  & 0x00000020) || /* CR4.PAE */
            (efer & 0x00000500))   /* EFER.LMA, EFER.LME */
                return true;
        break;
    case 2:
        /* Test should be back in long-mode now - check for this */
        if (((cr0  & 0x80000001) != 0x80000001) || /* CR0.PG, CR0.PE */
            ((cr4  & 0x00000020) != 0x00000020) || /* CR4.PAE */
            ((efer & 0x00000500) != 0x00000500))   /* EFER.LMA, EFER.LME */
		    return true;
	break;
    }

    /* one step forward */
    test->scratch += 1;

    return test->scratch == 2;
}

static bool check_mode_switch(struct test *test)
{
	return test->scratch == 2;
}

static void prepare_ioio(struct test *test)
{
    test->vmcb->control.intercept |= (1ULL << INTERCEPT_IOIO_PROT);
    test->scratch = 0;
    memset(io_bitmap, 0, 8192);
    io_bitmap[8192] = 0xFF;
}

int get_test_stage(struct test *test)
{
    barrier();
    return test->scratch;
}

void inc_test_stage(struct test *test)
{
    barrier();
    test->scratch++;
    barrier();
}

static void test_ioio(struct test *test)
{
    // stage 0, test IO pass
    inb(0x5000);
    outb(0x0, 0x5000);
    if (get_test_stage(test) != 0)
        goto fail;

    // test IO width, in/out
    io_bitmap[0] = 0xFF;
    inc_test_stage(test);
    inb(0x0);
    if (get_test_stage(test) != 2)
        goto fail;

    outw(0x0, 0x0);
    if (get_test_stage(test) != 3)
        goto fail;

    inl(0x0);
    if (get_test_stage(test) != 4)
        goto fail;

    // test low/high IO port
    io_bitmap[0x5000 / 8] = (1 << (0x5000 % 8));
    inb(0x5000);
    if (get_test_stage(test) != 5)
        goto fail;

    io_bitmap[0x9000 / 8] = (1 << (0x9000 % 8));
    inw(0x9000);
    if (get_test_stage(test) != 6)
        goto fail;

    // test partial pass
    io_bitmap[0x5000 / 8] = (1 << (0x5000 % 8));
    inl(0x4FFF);
    if (get_test_stage(test) != 7)
        goto fail;

    // test across pages
    inc_test_stage(test);
    inl(0x7FFF);
    if (get_test_stage(test) != 8)
        goto fail;

    inc_test_stage(test);
    io_bitmap[0x8000 / 8] = 1 << (0x8000 % 8);
    inl(0x7FFF);
    if (get_test_stage(test) != 10)
        goto fail;

    io_bitmap[0] = 0;
    inl(0xFFFF);
    if (get_test_stage(test) != 11)
        goto fail;

    io_bitmap[0] = 0xFF;
    io_bitmap[8192] = 0;
    inl(0xFFFF);
    inc_test_stage(test);
    if (get_test_stage(test) != 12)
        goto fail;

    return;

fail:
    report("stage %d", false, get_test_stage(test));
    test->scratch = -1;
}

static bool ioio_finished(struct test *test)
{
    unsigned port, size;

    /* Only expect IOIO intercepts */
    if (test->vmcb->control.exit_code == SVM_EXIT_VMMCALL)
        return true;

    if (test->vmcb->control.exit_code != SVM_EXIT_IOIO)
        return true;

    /* one step forward */
    test->scratch += 1;

    port = test->vmcb->control.exit_info_1 >> 16;
    size = (test->vmcb->control.exit_info_1 >> SVM_IOIO_SIZE_SHIFT) & 7;

    while (size--) {
        io_bitmap[port / 8] &= ~(1 << (port & 7));
        port++;
    }

    return false;
}

static bool check_ioio(struct test *test)
{
    memset(io_bitmap, 0, 8193);
    return test->scratch != -1;
}

static void prepare_asid_zero(struct test *test)
{
    test->vmcb->control.asid = 0;
}

static void test_asid_zero(struct test *test)
{
    asm volatile ("vmmcall\n\t");
}

static bool check_asid_zero(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_ERR;
}

static void sel_cr0_bug_prepare(struct test *test)
{
    vmcb_ident(test->vmcb);
    test->vmcb->control.intercept |= (1ULL << INTERCEPT_SELECTIVE_CR0);
}

static bool sel_cr0_bug_finished(struct test *test)
{
	return true;
}

static void sel_cr0_bug_test(struct test *test)
{
    unsigned long cr0;

    /* read cr0, clear CD, and write back */
    cr0  = read_cr0();
    cr0 |= (1UL << 30);
    write_cr0(cr0);

    /*
     * If we are here the test failed, not sure what to do now because we
     * are not in guest-mode anymore so we can't trigger an intercept.
     * Trigger a tripple-fault for now.
     */
    report("sel_cr0 test. Can not recover from this - exiting", false);
    exit(report_summary());
}

static bool sel_cr0_bug_check(struct test *test)
{
    return test->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE;
}

static void npt_nx_prepare(struct test *test)
{

    u64 *pte;

    vmcb_ident(test->vmcb);
    pte = npt_get_pte((u64)null_test);

    *pte |= (1ULL << 63);
}

static bool npt_nx_check(struct test *test)
{
    u64 *pte = npt_get_pte((u64)null_test);

    *pte &= ~(1ULL << 63);

    test->vmcb->save.efer |= (1 << 11);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
           && (test->vmcb->control.exit_info_1 == 0x100000015ULL);
}

static void npt_us_prepare(struct test *test)
{
    u64 *pte;

    vmcb_ident(test->vmcb);
    pte = npt_get_pte((u64)scratch_page);

    *pte &= ~(1ULL << 2);
}

static void npt_us_test(struct test *test)
{
    (void) *(volatile u64 *)scratch_page;
}

static bool npt_us_check(struct test *test)
{
    u64 *pte = npt_get_pte((u64)scratch_page);

    *pte |= (1ULL << 2);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
           && (test->vmcb->control.exit_info_1 == 0x100000005ULL);
}

u64 save_pde;

static void npt_rsvd_prepare(struct test *test)
{
    u64 *pde;

    vmcb_ident(test->vmcb);
    pde = npt_get_pde((u64) null_test);

    save_pde = *pde;
    *pde = (1ULL << 19) | (1ULL << 7) | 0x27;
}

static bool npt_rsvd_check(struct test *test)
{
    u64 *pde = npt_get_pde((u64) null_test);

    *pde = save_pde;

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
            && (test->vmcb->control.exit_info_1 == 0x10000001dULL);
}

static void npt_rw_prepare(struct test *test)
{

    u64 *pte;

    vmcb_ident(test->vmcb);
    pte = npt_get_pte(0x80000);

    *pte &= ~(1ULL << 1);
}

static void npt_rw_test(struct test *test)
{
    u64 *data = (void*)(0x80000);

    *data = 0;
}

static bool npt_rw_check(struct test *test)
{
    u64 *pte = npt_get_pte(0x80000);

    *pte |= (1ULL << 1);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
           && (test->vmcb->control.exit_info_1 == 0x100000007ULL);
}

static void npt_rw_pfwalk_prepare(struct test *test)
{

    u64 *pte;

    vmcb_ident(test->vmcb);
    pte = npt_get_pte(read_cr3());

    *pte &= ~(1ULL << 1);
}

static bool npt_rw_pfwalk_check(struct test *test)
{
    u64 *pte = npt_get_pte(read_cr3());

    *pte |= (1ULL << 1);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
           && (test->vmcb->control.exit_info_1 == 0x200000006ULL)
	   && (test->vmcb->control.exit_info_2 == read_cr3());
}

static void npt_rsvd_pfwalk_prepare(struct test *test)
{

    vmcb_ident(test->vmcb);

    pdpe[0] |= (1ULL << 8);
}

static bool npt_rsvd_pfwalk_check(struct test *test)
{
    pdpe[0] &= ~(1ULL << 8);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
            && (test->vmcb->control.exit_info_1 == 0x200000006ULL);
}

static void npt_l1mmio_prepare(struct test *test)
{
    vmcb_ident(test->vmcb);
}

u32 nested_apic_version1;
u32 nested_apic_version2;

static void npt_l1mmio_test(struct test *test)
{
    volatile u32 *data = (volatile void*)(0xfee00030UL);

    nested_apic_version1 = *data;
    nested_apic_version2 = *data;
}

static bool npt_l1mmio_check(struct test *test)
{
    volatile u32 *data = (volatile void*)(0xfee00030);
    u32 lvr = *data;

    return nested_apic_version1 == lvr && nested_apic_version2 == lvr;
}

static void npt_rw_l1mmio_prepare(struct test *test)
{

    u64 *pte;

    vmcb_ident(test->vmcb);
    pte = npt_get_pte(0xfee00080);

    *pte &= ~(1ULL << 1);
}

static void npt_rw_l1mmio_test(struct test *test)
{
    volatile u32 *data = (volatile void*)(0xfee00080);

    *data = *data;
}

static bool npt_rw_l1mmio_check(struct test *test)
{
    u64 *pte = npt_get_pte(0xfee00080);

    *pte |= (1ULL << 1);

    return (test->vmcb->control.exit_code == SVM_EXIT_NPF)
           && (test->vmcb->control.exit_info_1 == 0x100000007ULL);
}

static void latency_prepare(struct test *test)
{
    default_prepare(test);
    runs = LATENCY_RUNS;
    latvmrun_min = latvmexit_min = -1ULL;
    latvmrun_max = latvmexit_max = 0;
    vmrun_sum = vmexit_sum = 0;
}

static void latency_test(struct test *test)
{
    u64 cycles;

start:
    tsc_end = rdtsc();

    cycles = tsc_end - tsc_start;

    if (cycles > latvmrun_max)
        latvmrun_max = cycles;

    if (cycles < latvmrun_min)
        latvmrun_min = cycles;

    vmrun_sum += cycles;

    tsc_start = rdtsc();

    asm volatile ("vmmcall" : : : "memory");
    goto start;
}

static bool latency_finished(struct test *test)
{
    u64 cycles;

    tsc_end = rdtsc();

    cycles = tsc_end - tsc_start;

    if (cycles > latvmexit_max)
        latvmexit_max = cycles;

    if (cycles < latvmexit_min)
        latvmexit_min = cycles;

    vmexit_sum += cycles;

    test->vmcb->save.rip += 3;

    runs -= 1;

    return runs == 0;
}

static bool latency_check(struct test *test)
{
    printf("    Latency VMRUN : max: %ld min: %ld avg: %ld\n", latvmrun_max,
            latvmrun_min, vmrun_sum / LATENCY_RUNS);
    printf("    Latency VMEXIT: max: %ld min: %ld avg: %ld\n", latvmexit_max,
            latvmexit_min, vmexit_sum / LATENCY_RUNS);
    return true;
}

static void lat_svm_insn_prepare(struct test *test)
{
    default_prepare(test);
    runs = LATENCY_RUNS;
    latvmload_min = latvmsave_min = latstgi_min = latclgi_min = -1ULL;
    latvmload_max = latvmsave_max = latstgi_max = latclgi_max = 0;
    vmload_sum = vmsave_sum = stgi_sum = clgi_sum;
}

static bool lat_svm_insn_finished(struct test *test)
{
    u64 vmcb_phys = virt_to_phys(test->vmcb);
    u64 cycles;

    for ( ; runs != 0; runs--) {
        tsc_start = rdtsc();
        asm volatile("vmload\n\t" : : "a"(vmcb_phys) : "memory");
        cycles = rdtsc() - tsc_start;
        if (cycles > latvmload_max)
            latvmload_max = cycles;
        if (cycles < latvmload_min)
            latvmload_min = cycles;
        vmload_sum += cycles;

        tsc_start = rdtsc();
        asm volatile("vmsave\n\t" : : "a"(vmcb_phys) : "memory");
        cycles = rdtsc() - tsc_start;
        if (cycles > latvmsave_max)
            latvmsave_max = cycles;
        if (cycles < latvmsave_min)
            latvmsave_min = cycles;
        vmsave_sum += cycles;

        tsc_start = rdtsc();
        asm volatile("stgi\n\t");
        cycles = rdtsc() - tsc_start;
        if (cycles > latstgi_max)
            latstgi_max = cycles;
        if (cycles < latstgi_min)
            latstgi_min = cycles;
        stgi_sum += cycles;

        tsc_start = rdtsc();
        asm volatile("clgi\n\t");
        cycles = rdtsc() - tsc_start;
        if (cycles > latclgi_max)
            latclgi_max = cycles;
        if (cycles < latclgi_min)
            latclgi_min = cycles;
        clgi_sum += cycles;
    }

    return true;
}

static bool lat_svm_insn_check(struct test *test)
{
    printf("    Latency VMLOAD: max: %ld min: %ld avg: %ld\n", latvmload_max,
            latvmload_min, vmload_sum / LATENCY_RUNS);
    printf("    Latency VMSAVE: max: %ld min: %ld avg: %ld\n", latvmsave_max,
            latvmsave_min, vmsave_sum / LATENCY_RUNS);
    printf("    Latency STGI:   max: %ld min: %ld avg: %ld\n", latstgi_max,
            latstgi_min, stgi_sum / LATENCY_RUNS);
    printf("    Latency CLGI:   max: %ld min: %ld avg: %ld\n", latclgi_max,
            latclgi_min, clgi_sum / LATENCY_RUNS);
    return true;
}
static struct test tests[] = {
    { "null", default_supported, default_prepare, null_test,
      default_finished, null_check },
    { "vmrun", default_supported, default_prepare, test_vmrun,
       default_finished, check_vmrun },
    { "ioio", default_supported, prepare_ioio, test_ioio,
       ioio_finished, check_ioio },
    { "vmrun intercept check", default_supported, prepare_no_vmrun_int,
      null_test, default_finished, check_no_vmrun_int },
    { "cr3 read intercept", default_supported, prepare_cr3_intercept,
      test_cr3_intercept, default_finished, check_cr3_intercept },
    { "cr3 read nointercept", default_supported, default_prepare,
      test_cr3_intercept, default_finished, check_cr3_nointercept },
    { "cr3 read intercept emulate", smp_supported,
      prepare_cr3_intercept_bypass, test_cr3_intercept_bypass,
      default_finished, check_cr3_intercept },
    { "next_rip", next_rip_supported, prepare_next_rip, test_next_rip,
      default_finished, check_next_rip },
    { "mode_switch", default_supported, prepare_mode_switch, test_mode_switch,
       mode_switch_finished, check_mode_switch },
    { "asid_zero", default_supported, prepare_asid_zero, test_asid_zero,
       default_finished, check_asid_zero },
    { "sel_cr0_bug", default_supported, sel_cr0_bug_prepare, sel_cr0_bug_test,
       sel_cr0_bug_finished, sel_cr0_bug_check },
    { "npt_nx", npt_supported, npt_nx_prepare, null_test,
	    default_finished, npt_nx_check },
    { "npt_us", npt_supported, npt_us_prepare, npt_us_test,
	    default_finished, npt_us_check },
    { "npt_rsvd", npt_supported, npt_rsvd_prepare, null_test,
	    default_finished, npt_rsvd_check },
    { "npt_rw", npt_supported, npt_rw_prepare, npt_rw_test,
	    default_finished, npt_rw_check },
    { "npt_rsvd_pfwalk", npt_supported, npt_rsvd_pfwalk_prepare, null_test,
	    default_finished, npt_rsvd_pfwalk_check },
    { "npt_rw_pfwalk", npt_supported, npt_rw_pfwalk_prepare, null_test,
	    default_finished, npt_rw_pfwalk_check },
    { "npt_l1mmio", npt_supported, npt_l1mmio_prepare, npt_l1mmio_test,
	    default_finished, npt_l1mmio_check },
    { "npt_rw_l1mmio", npt_supported, npt_rw_l1mmio_prepare, npt_rw_l1mmio_test,
	    default_finished, npt_rw_l1mmio_check },
    { "latency_run_exit", default_supported, latency_prepare, latency_test,
      latency_finished, latency_check },
    { "latency_svm_insn", default_supported, lat_svm_insn_prepare, null_test,
      lat_svm_insn_finished, lat_svm_insn_check },
};

int main(int ac, char **av)
{
    int i, nr;
    struct vmcb *vmcb;

    setup_vm();
    smp_init();

    if (!(cpuid(0x80000001).c & 4)) {
        printf("SVM not availble\n");
        return report_summary();
    }

    setup_svm();

    vmcb = alloc_page();

    nr = ARRAY_SIZE(tests);
    for (i = 0; i < nr; ++i) {
        if (!tests[i].supported())
            continue;
        test_run(&tests[i], vmcb);
    }

    return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/x86/svm.h                                                           0000644 0000000 0000000 00000017760 00000000000 015356  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __SVM_H
#define __SVM_H

#include "libcflat.h"

enum {
	INTERCEPT_INTR,
	INTERCEPT_NMI,
	INTERCEPT_SMI,
	INTERCEPT_INIT,
	INTERCEPT_VINTR,
	INTERCEPT_SELECTIVE_CR0,
	INTERCEPT_STORE_IDTR,
	INTERCEPT_STORE_GDTR,
	INTERCEPT_STORE_LDTR,
	INTERCEPT_STORE_TR,
	INTERCEPT_LOAD_IDTR,
	INTERCEPT_LOAD_GDTR,
	INTERCEPT_LOAD_LDTR,
	INTERCEPT_LOAD_TR,
	INTERCEPT_RDTSC,
	INTERCEPT_RDPMC,
	INTERCEPT_PUSHF,
	INTERCEPT_POPF,
	INTERCEPT_CPUID,
	INTERCEPT_RSM,
	INTERCEPT_IRET,
	INTERCEPT_INTn,
	INTERCEPT_INVD,
	INTERCEPT_PAUSE,
	INTERCEPT_HLT,
	INTERCEPT_INVLPG,
	INTERCEPT_INVLPGA,
	INTERCEPT_IOIO_PROT,
	INTERCEPT_MSR_PROT,
	INTERCEPT_TASK_SWITCH,
	INTERCEPT_FERR_FREEZE,
	INTERCEPT_SHUTDOWN,
	INTERCEPT_VMRUN,
	INTERCEPT_VMMCALL,
	INTERCEPT_VMLOAD,
	INTERCEPT_VMSAVE,
	INTERCEPT_STGI,
	INTERCEPT_CLGI,
	INTERCEPT_SKINIT,
	INTERCEPT_RDTSCP,
	INTERCEPT_ICEBP,
	INTERCEPT_WBINVD,
	INTERCEPT_MONITOR,
	INTERCEPT_MWAIT,
	INTERCEPT_MWAIT_COND,
};


struct __attribute__ ((__packed__)) vmcb_control_area {
	u16 intercept_cr_read;
	u16 intercept_cr_write;
	u16 intercept_dr_read;
	u16 intercept_dr_write;
	u32 intercept_exceptions;
	u64 intercept;
	u8 reserved_1[42];
	u16 pause_filter_count;
	u64 iopm_base_pa;
	u64 msrpm_base_pa;
	u64 tsc_offset;
	u32 asid;
	u8 tlb_ctl;
	u8 reserved_2[3];
	u32 int_ctl;
	u32 int_vector;
	u32 int_state;
	u8 reserved_3[4];
	u32 exit_code;
	u32 exit_code_hi;
	u64 exit_info_1;
	u64 exit_info_2;
	u32 exit_int_info;
	u32 exit_int_info_err;
	u64 nested_ctl;
	u8 reserved_4[16];
	u32 event_inj;
	u32 event_inj_err;
	u64 nested_cr3;
	u64 lbr_ctl;
	u64 reserved_5;
	u64 next_rip;
	u8 reserved_6[816];
};


#define TLB_CONTROL_DO_NOTHING 0
#define TLB_CONTROL_FLUSH_ALL_ASID 1

#define V_TPR_MASK 0x0f

#define V_IRQ_SHIFT 8
#define V_IRQ_MASK (1 << V_IRQ_SHIFT)

#define V_INTR_PRIO_SHIFT 16
#define V_INTR_PRIO_MASK (0x0f << V_INTR_PRIO_SHIFT)

#define V_IGN_TPR_SHIFT 20
#define V_IGN_TPR_MASK (1 << V_IGN_TPR_SHIFT)

#define V_INTR_MASKING_SHIFT 24
#define V_INTR_MASKING_MASK (1 << V_INTR_MASKING_SHIFT)

#define SVM_INTERRUPT_SHADOW_MASK 1

#define SVM_IOIO_STR_SHIFT 2
#define SVM_IOIO_REP_SHIFT 3
#define SVM_IOIO_SIZE_SHIFT 4
#define SVM_IOIO_ASIZE_SHIFT 7

#define SVM_IOIO_TYPE_MASK 1
#define SVM_IOIO_STR_MASK (1 << SVM_IOIO_STR_SHIFT)
#define SVM_IOIO_REP_MASK (1 << SVM_IOIO_REP_SHIFT)
#define SVM_IOIO_SIZE_MASK (7 << SVM_IOIO_SIZE_SHIFT)
#define SVM_IOIO_ASIZE_MASK (7 << SVM_IOIO_ASIZE_SHIFT)

#define SVM_VM_CR_VALID_MASK	0x001fULL
#define SVM_VM_CR_SVM_LOCK_MASK 0x0008ULL
#define SVM_VM_CR_SVM_DIS_MASK  0x0010ULL

struct __attribute__ ((__packed__)) vmcb_seg {
	u16 selector;
	u16 attrib;
	u32 limit;
	u64 base;
};

struct __attribute__ ((__packed__)) vmcb_save_area {
	struct vmcb_seg es;
	struct vmcb_seg cs;
	struct vmcb_seg ss;
	struct vmcb_seg ds;
	struct vmcb_seg fs;
	struct vmcb_seg gs;
	struct vmcb_seg gdtr;
	struct vmcb_seg ldtr;
	struct vmcb_seg idtr;
	struct vmcb_seg tr;
	u8 reserved_1[43];
	u8 cpl;
	u8 reserved_2[4];
	u64 efer;
	u8 reserved_3[112];
	u64 cr4;
	u64 cr3;
	u64 cr0;
	u64 dr7;
	u64 dr6;
	u64 rflags;
	u64 rip;
	u8 reserved_4[88];
	u64 rsp;
	u8 reserved_5[24];
	u64 rax;
	u64 star;
	u64 lstar;
	u64 cstar;
	u64 sfmask;
	u64 kernel_gs_base;
	u64 sysenter_cs;
	u64 sysenter_esp;
	u64 sysenter_eip;
	u64 cr2;
	u8 reserved_6[32];
	u64 g_pat;
	u64 dbgctl;
	u64 br_from;
	u64 br_to;
	u64 last_excp_from;
	u64 last_excp_to;
};

struct __attribute__ ((__packed__)) vmcb {
	struct vmcb_control_area control;
	struct vmcb_save_area save;
};

#define SVM_CPUID_FEATURE_SHIFT 2
#define SVM_CPUID_FUNC 0x8000000a

#define SVM_VM_CR_SVM_DISABLE 4

#define SVM_SELECTOR_S_SHIFT 4
#define SVM_SELECTOR_DPL_SHIFT 5
#define SVM_SELECTOR_P_SHIFT 7
#define SVM_SELECTOR_AVL_SHIFT 8
#define SVM_SELECTOR_L_SHIFT 9
#define SVM_SELECTOR_DB_SHIFT 10
#define SVM_SELECTOR_G_SHIFT 11

#define SVM_SELECTOR_TYPE_MASK (0xf)
#define SVM_SELECTOR_S_MASK (1 << SVM_SELECTOR_S_SHIFT)
#define SVM_SELECTOR_DPL_MASK (3 << SVM_SELECTOR_DPL_SHIFT)
#define SVM_SELECTOR_P_MASK (1 << SVM_SELECTOR_P_SHIFT)
#define SVM_SELECTOR_AVL_MASK (1 << SVM_SELECTOR_AVL_SHIFT)
#define SVM_SELECTOR_L_MASK (1 << SVM_SELECTOR_L_SHIFT)
#define SVM_SELECTOR_DB_MASK (1 << SVM_SELECTOR_DB_SHIFT)
#define SVM_SELECTOR_G_MASK (1 << SVM_SELECTOR_G_SHIFT)

#define SVM_SELECTOR_WRITE_MASK (1 << 1)
#define SVM_SELECTOR_READ_MASK SVM_SELECTOR_WRITE_MASK
#define SVM_SELECTOR_CODE_MASK (1 << 3)

#define INTERCEPT_CR0_MASK 1
#define INTERCEPT_CR3_MASK (1 << 3)
#define INTERCEPT_CR4_MASK (1 << 4)
#define INTERCEPT_CR8_MASK (1 << 8)

#define INTERCEPT_DR0_MASK 1
#define INTERCEPT_DR1_MASK (1 << 1)
#define INTERCEPT_DR2_MASK (1 << 2)
#define INTERCEPT_DR3_MASK (1 << 3)
#define INTERCEPT_DR4_MASK (1 << 4)
#define INTERCEPT_DR5_MASK (1 << 5)
#define INTERCEPT_DR6_MASK (1 << 6)
#define INTERCEPT_DR7_MASK (1 << 7)

#define SVM_EVTINJ_VEC_MASK 0xff

#define SVM_EVTINJ_TYPE_SHIFT 8
#define SVM_EVTINJ_TYPE_MASK (7 << SVM_EVTINJ_TYPE_SHIFT)

#define SVM_EVTINJ_TYPE_INTR (0 << SVM_EVTINJ_TYPE_SHIFT)
#define SVM_EVTINJ_TYPE_NMI (2 << SVM_EVTINJ_TYPE_SHIFT)
#define SVM_EVTINJ_TYPE_EXEPT (3 << SVM_EVTINJ_TYPE_SHIFT)
#define SVM_EVTINJ_TYPE_SOFT (4 << SVM_EVTINJ_TYPE_SHIFT)

#define SVM_EVTINJ_VALID (1 << 31)
#define SVM_EVTINJ_VALID_ERR (1 << 11)

#define SVM_EXITINTINFO_VEC_MASK SVM_EVTINJ_VEC_MASK
#define SVM_EXITINTINFO_TYPE_MASK SVM_EVTINJ_TYPE_MASK

#define	SVM_EXITINTINFO_TYPE_INTR SVM_EVTINJ_TYPE_INTR
#define	SVM_EXITINTINFO_TYPE_NMI SVM_EVTINJ_TYPE_NMI
#define	SVM_EXITINTINFO_TYPE_EXEPT SVM_EVTINJ_TYPE_EXEPT
#define	SVM_EXITINTINFO_TYPE_SOFT SVM_EVTINJ_TYPE_SOFT

#define SVM_EXITINTINFO_VALID SVM_EVTINJ_VALID
#define SVM_EXITINTINFO_VALID_ERR SVM_EVTINJ_VALID_ERR

#define SVM_EXITINFOSHIFT_TS_REASON_IRET 36
#define SVM_EXITINFOSHIFT_TS_REASON_JMP 38
#define SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE 44

#define	SVM_EXIT_READ_CR0 	0x000
#define	SVM_EXIT_READ_CR3 	0x003
#define	SVM_EXIT_READ_CR4 	0x004
#define	SVM_EXIT_READ_CR8 	0x008
#define	SVM_EXIT_WRITE_CR0 	0x010
#define	SVM_EXIT_WRITE_CR3 	0x013
#define	SVM_EXIT_WRITE_CR4 	0x014
#define	SVM_EXIT_WRITE_CR8 	0x018
#define	SVM_EXIT_READ_DR0 	0x020
#define	SVM_EXIT_READ_DR1 	0x021
#define	SVM_EXIT_READ_DR2 	0x022
#define	SVM_EXIT_READ_DR3 	0x023
#define	SVM_EXIT_READ_DR4 	0x024
#define	SVM_EXIT_READ_DR5 	0x025
#define	SVM_EXIT_READ_DR6 	0x026
#define	SVM_EXIT_READ_DR7 	0x027
#define	SVM_EXIT_WRITE_DR0 	0x030
#define	SVM_EXIT_WRITE_DR1 	0x031
#define	SVM_EXIT_WRITE_DR2 	0x032
#define	SVM_EXIT_WRITE_DR3 	0x033
#define	SVM_EXIT_WRITE_DR4 	0x034
#define	SVM_EXIT_WRITE_DR5 	0x035
#define	SVM_EXIT_WRITE_DR6 	0x036
#define	SVM_EXIT_WRITE_DR7 	0x037
#define SVM_EXIT_EXCP_BASE      0x040
#define SVM_EXIT_INTR		0x060
#define SVM_EXIT_NMI		0x061
#define SVM_EXIT_SMI		0x062
#define SVM_EXIT_INIT		0x063
#define SVM_EXIT_VINTR		0x064
#define SVM_EXIT_CR0_SEL_WRITE	0x065
#define SVM_EXIT_IDTR_READ	0x066
#define SVM_EXIT_GDTR_READ	0x067
#define SVM_EXIT_LDTR_READ	0x068
#define SVM_EXIT_TR_READ	0x069
#define SVM_EXIT_IDTR_WRITE	0x06a
#define SVM_EXIT_GDTR_WRITE	0x06b
#define SVM_EXIT_LDTR_WRITE	0x06c
#define SVM_EXIT_TR_WRITE	0x06d
#define SVM_EXIT_RDTSC		0x06e
#define SVM_EXIT_RDPMC		0x06f
#define SVM_EXIT_PUSHF		0x070
#define SVM_EXIT_POPF		0x071
#define SVM_EXIT_CPUID		0x072
#define SVM_EXIT_RSM		0x073
#define SVM_EXIT_IRET		0x074
#define SVM_EXIT_SWINT		0x075
#define SVM_EXIT_INVD		0x076
#define SVM_EXIT_PAUSE		0x077
#define SVM_EXIT_HLT		0x078
#define SVM_EXIT_INVLPG		0x079
#define SVM_EXIT_INVLPGA	0x07a
#define SVM_EXIT_IOIO		0x07b
#define SVM_EXIT_MSR		0x07c
#define SVM_EXIT_TASK_SWITCH	0x07d
#define SVM_EXIT_FERR_FREEZE	0x07e
#define SVM_EXIT_SHUTDOWN	0x07f
#define SVM_EXIT_VMRUN		0x080
#define SVM_EXIT_VMMCALL	0x081
#define SVM_EXIT_VMLOAD		0x082
#define SVM_EXIT_VMSAVE		0x083
#define SVM_EXIT_STGI		0x084
#define SVM_EXIT_CLGI		0x085
#define SVM_EXIT_SKINIT		0x086
#define SVM_EXIT_RDTSCP		0x087
#define SVM_EXIT_ICEBP		0x088
#define SVM_EXIT_WBINVD		0x089
#define SVM_EXIT_MONITOR	0x08a
#define SVM_EXIT_MWAIT		0x08b
#define SVM_EXIT_MWAIT_COND	0x08c
#define SVM_EXIT_NPF  		0x400

#define SVM_EXIT_ERR		-1

#define SVM_CR0_SELECTIVE_MASK (X86_CR0_TS | X86_CR0_MP)

#endif

                source/v64/tests/kvm-unit-tests/x86/syscall.c                                                       0000644 0000000 0000000 00000006472 00000000000 016214  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* msr tests */

#include "libcflat.h"
#include "processor.h"
#include "msr.h"
#include "desc.h"

static void test_syscall_lazy_load(void)
{
    extern void syscall_target();
    u16 cs = read_cs(), ss = read_ss();
    ulong tmp;

    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_SCE);
    wrmsr(MSR_LSTAR, (ulong)syscall_target);
    wrmsr(MSR_STAR, (uint64_t)cs << 32);
    asm volatile("pushf; syscall; syscall_target: popf" : "=c"(tmp) : : "r11");
    write_ss(ss);
    // will crash horribly if broken
    report("MSR_*STAR eager loading", true);
}

/*
 * test handling of TF in syscall/sysret: #DB is raised if TF
 * is 1 at the *end* of syscall/sysret.
 *
 * This uses 32-bit syscall/sysret because KVM emulates it on Intel processors.
 * However, the same bug happens with 64-bit syscall/sysret if two vCPUs
 * "race" to force the emulation of syscall/sysret.
 */

static uint16_t code_segment_upon_db;
static void handle_db(struct ex_regs *regs)
{
    code_segment_upon_db = regs->cs;
    regs->rflags &= ~(1 << 8);
}

/* expects desired ring 3 flags in rax */
asm("syscall32_target:\n"
    "   cmp $0, code_segment_upon_db(%rip)\n"
    "   jne back_to_test\n"
    "   mov %eax,%r11d\n"
    "   sysretl\n");

/* 32-bit, ring-3 part of test_syscall_tf */
asm("   .code32\n"
    "syscall_tf_user32:\n"
    "   pushf\n"
    "   pop %eax\n"
    "   or $(1<<8),%eax\n"
    "   push %eax\n"
    "   popf\n"
    "   syscall\n"  /* singlestep trap taken after syscall */
    "   syscall\n"  /* jumps back to test_syscall_tf's body */
    "   .code64\n");

static void test_syscall_tf(void)
{
    extern void syscall32_target();
    extern void syscall_tf_user32();
    ulong rcx;

    wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_SCE);
    wrmsr(MSR_CSTAR, (ulong)syscall32_target);
    wrmsr(MSR_STAR, ((uint64_t)USER_CS32 << 48) | ((uint64_t)KERNEL_CS64 << 32));
    wrmsr(MSR_SYSCALL_MASK, X86_EFLAGS_TF|X86_EFLAGS_DF|X86_EFLAGS_IF|X86_EFLAGS_NT);
    handle_exception(DB_VECTOR, handle_db);

    /* good:
     *   sysret to syscall_tf_user32
     *   popf sets TF (singlestep starts on the next instruction)
     *   syscall to syscall32_target -> TF cleared and no singlestep
     *   sysretl sets TF
     *   handle_db sets code_segment_upon_db to USER_CS32 and clears TF
     *   syscall to syscall32_target
     *   syscall32_target jumps to back_to_test
     *
     * bad:
     *   sysret to syscall_tf_user32
     *   popf sets TF (singlestep starts on the next instruction)
     *   syscall to syscall32_target, TF cleared and wrong singlestep exception
     *   handle_db sets code_segment_upon_db to KERNEL_CS64
     *   syscall32_target jumps to back_to_test
     */
    rcx = (ulong)syscall_tf_user32;
    asm volatile("  push %%rbp\n"
                 "  pushf; pop %%rax\n"   // expected by syscall32_target
                 "  sysret\n"
                 "back_to_test:\n"
                 "  pop %%rbp"
                 : "+c"(rcx) :
                 : "rax", "rbx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11",
                   "r12", "r13", "r14", "r15");
    if (code_segment_upon_db != USER_CS32) {
        printf("wrong CS (%#04x)!\n", code_segment_upon_db);
    }
    report("syscall TF handling", code_segment_upon_db == USER_CS32);
}

int main(int ac, char **av)
{
    setup_idt();
    test_syscall_lazy_load();
    test_syscall_tf();

    return report_summary();
}
                                                                                                                                                                                                      source/v64/tests/kvm-unit-tests/x86/taskswitch.c                                                    0000644 0000000 0000000 00000001433 00000000000 016716  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright 2010 Siemens AG
 * Author: Jan Kiszka
 *
 * Released under GPLv2.
 */

#include "libcflat.h"
#include "x86/desc.h"

#define TSS_RETURN		(FIRST_SPARE_SEL)

void fault_entry(void);

static __attribute__((used, regparm(1))) void
fault_handler(unsigned long error_code)
{
	print_current_tss_info();
	printf("error code %lx\n", error_code);

	tss.eip += 2;

	gdt32[TSS_MAIN / 8].access &= ~2;

	set_gdt_task_gate(TSS_RETURN, tss_intr.prev);
}

asm (
	"fault_entry:\n"
	"	mov (%esp),%eax\n"
	"	call fault_handler\n"
	"	jmp $" xstr(TSS_RETURN) ", $0\n"
);

int main(int ac, char **av)
{
	const long invalid_segment = 0x1234;

	setup_tss32();
	set_intr_task_gate(13, fault_entry);

	asm (
		"mov %0,%%es\n"
		: : "r" (invalid_segment) : "edi"
	);

	printf("post fault\n");

	return 0;
}
                                                                                                                                                                                                                                     source/v64/tests/kvm-unit-tests/x86/taskswitch2.c                                                   0000644 0000000 0000000 00000015700 00000000000 017002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "desc.h"
#include "apic-defs.h"
#include "apic.h"
#include "processor.h"
#include "vm.h"

#define MAIN_TSS_SEL (FIRST_SPARE_SEL + 0)
#define VM86_TSS_SEL (FIRST_SPARE_SEL + 8)
#define CONFORM_CS_SEL  (FIRST_SPARE_SEL + 16)

static volatile int test_count;
static volatile unsigned int test_divider;

static char *fault_addr;
static ulong fault_phys;

static inline void io_delay(void)
{
}

static void nmi_tss(void)
{
start:
	printf("NMI task is running\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("iret");
	goto start;
}

static void de_tss(void)
{
start:
	printf("DE task is running\n");
	print_current_tss_info();
	test_divider = 10;
	test_count++;
	asm volatile ("iret");
	goto start;
}

static void of_tss(void)
{
start:
	printf("OF task is running\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("iret");
	goto start;
}

static void bp_tss(void)
{
start:
	printf("BP task is running\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("iret");
	goto start;
}

void do_pf_tss(ulong *error_code)
{
	printf("PF task is running %p %lx\n", error_code, *error_code);
	print_current_tss_info();
	if (*error_code == 0x2) /* write access, not present */
		test_count++;
	install_pte(phys_to_virt(read_cr3()), 1, fault_addr,
		    fault_phys | PT_PRESENT_MASK | PT_WRITABLE_MASK, 0);
}

extern void pf_tss(void);

asm (
	"pf_tss: \n\t"
	"push %esp \n\t"
	"call do_pf_tss \n\t"
	"add $4, %esp \n\t"
	"iret\n\t"
	"jmp pf_tss\n\t"
    );

static void jmp_tss(void)
{
start:
	printf("JMP to task succeeded\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("ljmp $" xstr(TSS_MAIN) ", $0");
	goto start;
}

static void irq_tss(void)
{
start:
	printf("IRQ task is running\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("iret");
	test_count++;
	printf("IRQ task restarts after iret.\n");
	goto start;
}

static void user_tss(void)
{
start:
	printf("Conforming task is running\n");
	print_current_tss_info();
	test_count++;
	asm volatile ("iret");
	goto start;
}

void test_kernel_mode_int()
{
	unsigned int res;

	/* test that int $2 triggers task gate */
	test_count = 0;
	set_intr_task_gate(2, nmi_tss);
	printf("Triggering nmi 2\n");
	asm volatile ("int $2");
	printf("Return from nmi %d\n", test_count);
	report("NMI int $2", test_count == 1);

	// XXX: disabled for now, missing apic features
#if 0
	/* test that external NMI triggers task gate */
	test_count = 0;
	set_intr_task_gate(2, nmi_tss);
	printf("Triggering nmi through APIC\n");
	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, 0);
	io_delay();
	printf("Return from APIC nmi\n");
	report("NMI external", test_count == 1);

	/* test that external interrupt triggesr task gate */
	test_count = 0;
	printf("Trigger IRQ from APIC\n");
	set_intr_task_gate(0xf0, irq_tss);
	irq_enable();
	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL | APIC_DM_FIXED | APIC_INT_ASSERT | 0xf0, 0);
	io_delay();
	irq_disable();
	printf("Return from APIC IRQ\n");
	report("IRQ external", test_count == 1);
#endif

	/* test that HW exception triggesr task gate */
	set_intr_task_gate(0, de_tss);
	printf("Try to devide by 0\n");
	asm volatile ("divl %3": "=a"(res)
		      : "d"(0), "a"(1500), "m"(test_divider));
	printf("Result is %d\n", res);
	report("DE exeption", res == 150);

	/* test if call HW exeption DE by int $0 triggers task gate */
	test_count = 0;
	set_intr_task_gate(0, de_tss);
	printf("Call int 0\n");
	asm volatile ("int $0");
	printf("Return from int 0\n");
	report("int $0", test_count == 1);

	/* test if HW exception OF triggers task gate */
	test_count = 0;
	set_intr_task_gate(4, of_tss);
	printf("Call into\n");
	asm volatile ("addb $127, %b0\ninto"::"a"(127));
	printf("Return from into\n");
	report("OF exeption", test_count);

	/* test if HW exception BP triggers task gate */
	test_count = 0;
	set_intr_task_gate(3, bp_tss);
	printf("Call int 3\n");
	asm volatile ("int $3");
	printf("Return from int 3\n");
	report("BP exeption", test_count == 1);

	/*
	 * test that PF triggers task gate and error code is placed on
	 * exception task's stack
	 */
	fault_addr = alloc_vpage();
	fault_phys = (ulong)virt_to_phys(alloc_page());
	test_count = 0;
	set_intr_task_gate(14, pf_tss);
	printf("Access unmapped page\n");
	*fault_addr = 0;
	printf("Return from pf tss\n");
	report("PF exeption", test_count == 1);
}

void test_gdt_task_gate(void)
{
	/* test that calling a task by lcall works */
	test_count = 0;
	tss_intr.eip = (u32)irq_tss;
	printf("Calling task by lcall\n");
	/* hlt opcode is 0xf4 I use destination IP 0xf4f4f4f4 to catch
	   incorrect instruction length calculation */
	asm volatile("lcall $" xstr(TSS_INTR) ", $0xf4f4f4f4");
	printf("Return from call\n");
	report("lcall", test_count == 1);

	/* call the same task again and check that it restarted after iret */
	test_count = 0;
	asm volatile("lcall $" xstr(TSS_INTR) ", $0xf4f4f4f4");
	report("lcall2", test_count == 2);

	/* test that calling a task by ljmp works */
	test_count = 0;
	tss_intr.eip = (u32)jmp_tss;
	printf("Jumping to a task by ljmp\n");
	asm volatile ("ljmp $" xstr(TSS_INTR) ", $0xf4f4f4f4");
	printf("Jump back succeeded\n");
	report("ljmp", test_count == 1);
}

void test_vm86_switch(void)
{
    static tss32_t main_tss;
    static tss32_t vm86_tss;

    u8 *vm86_start;

    /* Write a 'ud2' instruction somewhere below 1 MB */
    vm86_start = (void*) 0x42000;
    vm86_start[0] = 0x0f;
    vm86_start[1] = 0x0b;

    /* Main TSS */
    set_gdt_entry(MAIN_TSS_SEL, (u32)&main_tss, sizeof(tss32_t) - 1, 0x89, 0);
    ltr(MAIN_TSS_SEL);
    main_tss = (tss32_t) {
        .prev   = VM86_TSS_SEL,
        .cr3    = read_cr3(),
    };

    /* VM86 TSS (marked as busy, so we can iret to it) */
    set_gdt_entry(VM86_TSS_SEL, (u32)&vm86_tss, sizeof(tss32_t) - 1, 0x8b, 0);
    vm86_tss = (tss32_t) {
        .eflags = 0x20002,
        .cr3    = read_cr3(),
        .eip    = (u32) vm86_start & 0x0f,
        .cs     = (u32) vm86_start >> 4,
        .ds     = 0x1234,
        .es     = 0x2345,
    };

    /* Setup task gate to main TSS for #UD */
    set_idt_task_gate(6, MAIN_TSS_SEL);

    /* Jump into VM86 task with iret, #UD lets it come back immediately */
    printf("Switch to VM86 task and back\n");
    asm volatile(
        "pushf\n"
        "orw $0x4000, (%esp)\n"
        "popf\n"
        "iret\n"
    );
    report("VM86", 1);
}

#define IOPL_SHIFT 12

void test_conforming_switch(void)
{
	/* test lcall with conforming segment, cs.dpl != cs.rpl */
	test_count = 0;

	tss_intr.cs = CONFORM_CS_SEL | 3;
	tss_intr.eip = (u32)user_tss;
	tss_intr.ss = USER_DS;
	tss_intr.ds = tss_intr.gs = tss_intr.es = tss_intr.fs = tss_intr.ss;
	tss_intr.eflags |= 3 << IOPL_SHIFT;
	set_gdt_entry(CONFORM_CS_SEL, 0, 0xffffffff, 0x9f, 0xc0);
	asm volatile("lcall $" xstr(TSS_INTR) ", $0xf4f4f4f4");
	report("lcall with cs.rpl != cs.dpl", test_count == 1);
}

int main()
{
	setup_vm();
	setup_idt();
	setup_tss32();

	test_gdt_task_gate();
	test_kernel_mode_int();
	test_vm86_switch();
	test_conforming_switch();

	return report_summary();
}
                                                                source/v64/tests/kvm-unit-tests/x86/tsc.c                                                           0000644 0000000 0000000 00000001475 00000000000 015331  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "processor.h"

#define CPUID_80000001_EDX_RDTSCP	    (1 << 27)
int check_cpuid_80000001_edx(unsigned int bit)
{
    return (cpuid(0x80000001).d & bit) != 0;
}


void test_wrtsc(u64 t1)
{
	u64 t2;

	wrtsc(t1);
	t2 = rdtsc();
	printf("rdtsc after wrtsc(%" PRId64 "): %" PRId64 "\n", t1, t2);
}

void test_rdtscp(u64 aux)
{
       u32 ecx;

       wrmsr(MSR_TSC_AUX, aux);
       rdtscp(&ecx);
       report("Test RDTSCP %" PRIu64, ecx == aux, aux);
}

int main()
{
	u64 t1, t2;

	t1 = rdtsc();
	t2 = rdtsc();
	printf("rdtsc latency %u\n", (unsigned)(t2 - t1));

	test_wrtsc(0);
	test_wrtsc(100000000000ull);

	if (check_cpuid_80000001_edx(CPUID_80000001_EDX_RDTSCP)) {
		test_rdtscp(0);
		test_rdtscp(10);
		test_rdtscp(0x100);
	} else
		printf("rdtscp not supported\n");
	return report_summary();
}
                                                                                                                                                                                                   source/v64/tests/kvm-unit-tests/x86/tsc_adjust.c                                                    0000644 0000000 0000000 00000002163 00000000000 016676  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "processor.h"

#define IA32_TSC_ADJUST 0x3b

int main()
{
	u64 t1, t2, t3, t4, t5;
	u64 est_delta_time;

	if (cpuid(7).b & (1 << 1)) { // IA32_TSC_ADJUST Feature is enabled?
		report("IA32_TSC_ADJUST msr initialization",
				rdmsr(IA32_TSC_ADJUST) == 0x0);
		t3 = 100000000000ull;
		t1 = rdtsc();
		wrmsr(IA32_TSC_ADJUST, t3);
		t2 = rdtsc();
		report("IA32_TSC_ADJUST msr read / write",
				rdmsr(IA32_TSC_ADJUST) == t3);
		report("TSC adjustment for IA32_TSC_ADJUST value",
				(t2 - t1) >= t3);
		t3 = 0x0;
		wrmsr(IA32_TSC_ADJUST, t3);
		report("IA32_TSC_ADJUST msr read / write",
				rdmsr(IA32_TSC_ADJUST) == t3);
		t4 = 100000000000ull;
		t1 = rdtsc();
		wrtsc(t4);
		t2 = rdtsc();
		t5 = rdmsr(IA32_TSC_ADJUST);
		// est of time between reading tsc and writing tsc,
		// (based on IA32_TSC_ADJUST msr value) should be small
		est_delta_time = t4 - t5 - t1;
		// arbitray 2x latency (wrtsc->rdtsc) threshold
		report("IA32_TSC_ADJUST msr adjustment on tsc write",
				est_delta_time <= (2 * (t2 - t4)));
	}
	else {
		report("IA32_TSC_ADJUST feature not enabled", true);
	}
	return report_summary();
}
                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/kvm-unit-tests/x86/tscdeadline_latency.c                                           0000644 0000000 0000000 00000005437 00000000000 020540  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * qemu command line | grep latency | cut -f 2 -d ":" > latency
 *
 * In octave:
 * load latency
 * min(latency)
 * max(latency)
 * mean(latency)
 * hist(latency, 50)
 */

/*
 * for host tracing of breakmax option:
 *
 * # cd /sys/kernel/debug/tracing/
 * # echo x86-tsc > trace_clock
 * # echo "kvm_exit kvm_entry kvm_msr" > set_event
 * # echo "sched_switch $extratracepoints" >> set_event
 * # echo apic_timer_fn > set_ftrace_filter
 * # echo "function" > current_tracer
 */

#include "libcflat.h"
#include "apic.h"
#include "vm.h"
#include "smp.h"
#include "desc.h"
#include "isr.h"
#include "msr.h"

static void test_lapic_existence(void)
{
    u32 lvr;

    lvr = apic_read(APIC_LVR);
    printf("apic version: %x\n", lvr);
    report("apic existence", (u16)lvr == 0x14);
}

#define TSC_DEADLINE_TIMER_VECTOR 0xef

static int tdt_count;
u64 exptime;
int delta;
#define TABLE_SIZE 10000
u64 table[TABLE_SIZE];
volatile int table_idx;
volatile int hitmax = 0;
int breakmax = 0;

static void tsc_deadline_timer_isr(isr_regs_t *regs)
{
    u64 now = rdtsc();
    ++tdt_count;

    if (table_idx < TABLE_SIZE && tdt_count > 1)
        table[table_idx++] = now - exptime;

    if (breakmax && tdt_count > 1 && (now - exptime) > breakmax) {
        hitmax = 1;
        apic_write(APIC_EOI, 0);
        return;
    }

    exptime = now+delta;
    wrmsr(MSR_IA32_TSCDEADLINE, now+delta);
    apic_write(APIC_EOI, 0);
}

static void start_tsc_deadline_timer(void)
{
    handle_irq(TSC_DEADLINE_TIMER_VECTOR, tsc_deadline_timer_isr);
    irq_enable();

    wrmsr(MSR_IA32_TSCDEADLINE, rdmsr(MSR_IA32_TSC)+delta);
    asm volatile ("nop");
}

static int enable_tsc_deadline_timer(void)
{
    uint32_t lvtt;

    if (cpuid(1).c & (1 << 24)) {
        lvtt = APIC_LVT_TIMER_TSCDEADLINE | TSC_DEADLINE_TIMER_VECTOR;
        apic_write(APIC_LVTT, lvtt);
        start_tsc_deadline_timer();
        return 1;
    } else {
        return 0;
    }
}

static void test_tsc_deadline_timer(void)
{
    if(enable_tsc_deadline_timer()) {
        printf("tsc deadline timer enabled\n");
    } else {
        printf("tsc deadline timer not detected, aborting\n");
        abort();
    }
}

int main(int argc, char **argv)
{
    int i, size;

    setup_vm();
    smp_init();

    test_lapic_existence();

    mask_pic_interrupts();

    delta = argc <= 1 ? 200000 : atol(argv[1]);
    size = argc <= 2 ? TABLE_SIZE : atol(argv[2]);
    breakmax = argc <= 3 ? 0 : atol(argv[3]);
    printf("breakmax=%d\n", breakmax);
    test_tsc_deadline_timer();
    irq_enable();

    do {
        asm volatile("hlt");
    } while (!hitmax && table_idx < size);

    for (i = 0; i < table_idx; i++) {
        if (hitmax && i == table_idx-1)
            printf("hit max: %d < ", breakmax);
        printf("latency: %" PRId64 "\n", table[i]);
    }

    return report_summary();
}
                                                                                                                                                                                                                                 source/v64/tests/kvm-unit-tests/x86/types.h                                                         0000644 0000000 0000000 00000000540 00000000000 015701  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __TYPES_H
#define __TYPES_H

#define DE_VECTOR 0
#define DB_VECTOR 1
#define BP_VECTOR 3
#define OF_VECTOR 4
#define BR_VECTOR 5
#define UD_VECTOR 6
#define NM_VECTOR 7
#define DF_VECTOR 8
#define TS_VECTOR 10
#define NP_VECTOR 11
#define SS_VECTOR 12
#define GP_VECTOR 13
#define PF_VECTOR 14
#define MF_VECTOR 16
#define MC_VECTOR 18

#endif
                                                                                                                                                                source/v64/tests/kvm-unit-tests/x86/vmexit.c                                                        0000644 0000000 0000000 00000025637 00000000000 016062  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "smp.h"
#include "processor.h"
#include "atomic.h"
#include "pci.h"
#include "x86/vm.h"
#include "x86/desc.h"
#include "x86/acpi.h"
#include "x86/apic.h"
#include "x86/isr.h"

#define IPI_TEST_VECTOR	0xb0

struct test {
	void (*func)(void);
	const char *name;
	int (*valid)(void);
	int parallel;
	bool (*next)(struct test *);
};

#define GOAL (1ull << 30)

static int nr_cpus;

static void cpuid_test(void)
{
	asm volatile ("push %%"R "bx; cpuid; pop %%"R "bx"
		      : : : "eax", "ecx", "edx");
}

static void vmcall(void)
{
	unsigned long a = 0, b, c, d;

	asm volatile ("vmcall" : "+a"(a), "=b"(b), "=c"(c), "=d"(d));
}

#define MSR_TSC_ADJUST 0x3b
#define MSR_EFER 0xc0000080
#define EFER_NX_MASK            (1ull << 11)

#ifdef __x86_64__
static void mov_from_cr8(void)
{
	unsigned long cr8;

	asm volatile ("mov %%cr8, %0" : "=r"(cr8));
}

static void mov_to_cr8(void)
{
	unsigned long cr8 = 0;

	asm volatile ("mov %0, %%cr8" : : "r"(cr8));
}
#endif

static int is_smp(void)
{
	return cpu_count() > 1;
}

static void nop(void *junk)
{
}

volatile int x = 0;

static void self_ipi_isr(isr_regs_t *regs)
{
	x++;
	eoi();
}

static void x2apic_self_ipi(int vec)
{
	wrmsr(0x83f, vec);
}

static void apic_self_ipi(int vec)
{
        apic_icr_write(APIC_INT_ASSERT | APIC_DEST_SELF | APIC_DEST_PHYSICAL |
		       APIC_DM_FIXED | IPI_TEST_VECTOR, vec);
}

static void self_ipi_sti_nop(void)
{
	x = 0;
	irq_disable();
	apic_self_ipi(IPI_TEST_VECTOR);
	asm volatile("sti; nop");
	if (x != 1) printf("%d", x);
}

static void self_ipi_sti_hlt(void)
{
	x = 0;
	irq_disable();
	apic_self_ipi(IPI_TEST_VECTOR);
	asm volatile("sti; hlt");
	if (x != 1) printf("%d", x);
}

static void self_ipi_tpr(void)
{
	x = 0;
	apic_set_tpr(0x0f);
	apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("nop");
	if (x != 1) printf("%d", x);
}

static void self_ipi_tpr_sti_nop(void)
{
	x = 0;
	irq_disable();
	apic_set_tpr(0x0f);
	apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("sti; nop");
	if (x != 1) printf("%d", x);
}

static void self_ipi_tpr_sti_hlt(void)
{
	x = 0;
	irq_disable();
	apic_set_tpr(0x0f);
	apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("sti; hlt");
	if (x != 1) printf("%d", x);
}

static int is_x2apic(void)
{
    return rdmsr(MSR_IA32_APICBASE) & APIC_EXTD;
}

static void x2apic_self_ipi_sti_nop(void)
{
	irq_disable();
	x2apic_self_ipi(IPI_TEST_VECTOR);
	asm volatile("sti; nop");
}

static void x2apic_self_ipi_sti_hlt(void)
{
	irq_disable();
	x2apic_self_ipi(IPI_TEST_VECTOR);
	asm volatile("sti; hlt");
}

static void x2apic_self_ipi_tpr(void)
{
	apic_set_tpr(0x0f);
	x2apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("nop");
}

static void x2apic_self_ipi_tpr_sti_nop(void)
{
	irq_disable();
	apic_set_tpr(0x0f);
	x2apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("sti; nop");
}

static void x2apic_self_ipi_tpr_sti_hlt(void)
{
	irq_disable();
	apic_set_tpr(0x0f);
	x2apic_self_ipi(IPI_TEST_VECTOR);
	apic_set_tpr(0x00);
	asm volatile("sti; hlt");
}

static void ipi(void)
{
	on_cpu(1, nop, 0);
}

static void ipi_halt(void)
{
	unsigned long long t;

	on_cpu(1, nop, 0);
	t = rdtsc() + 2000;
	while (rdtsc() < t)
		;
}

int pm_tmr_blk;
static void inl_pmtimer(void)
{
    inl(pm_tmr_blk);
}

static void inl_nop_qemu(void)
{
    inl(0x1234);
}

static void inl_nop_kernel(void)
{
    inb(0x4d0);
}

static void outl_elcr_kernel(void)
{
    outb(0, 0x4d0);
}

static void mov_dr(void)
{
    asm volatile("mov %0, %%dr7" : : "r" (0x400L));
}

static void ple_round_robin(void)
{
	struct counter {
		volatile int n1;
		int n2;
	} __attribute__((aligned(64)));
	static struct counter counters[64] = { { -1, 0 } };
	int me = smp_id();
	int you;
	volatile struct counter *p = &counters[me];

	while (p->n1 == p->n2)
		asm volatile ("pause");

	p->n2 = p->n1;
	you = me + 1;
	if (you == nr_cpus)
		you = 0;
	++counters[you].n1;
}

static void rd_tsc_adjust_msr(void)
{
	rdmsr(MSR_TSC_ADJUST);
}

static void wr_tsc_adjust_msr(void)
{
	wrmsr(MSR_TSC_ADJUST, 0x0);
}

static struct pci_test {
	unsigned iobar;
	unsigned ioport;
	volatile void *memaddr;
	volatile void *mem;
	int test_idx;
	uint32_t data;
	uint32_t offset;
} pci_test = {
	.test_idx = -1
};

static void pci_mem_testb(void)
{
	*(volatile uint8_t *)pci_test.mem = pci_test.data;
}

static void pci_mem_testw(void)
{
	*(volatile uint16_t *)pci_test.mem = pci_test.data;
}

static void pci_mem_testl(void)
{
	*(volatile uint32_t *)pci_test.mem = pci_test.data;
}

static void pci_io_testb(void)
{
	outb(pci_test.data, pci_test.ioport);
}

static void pci_io_testw(void)
{
	outw(pci_test.data, pci_test.ioport);
}

static void pci_io_testl(void)
{
	outl(pci_test.data, pci_test.ioport);
}

static uint8_t ioreadb(unsigned long addr, bool io)
{
	if (io) {
		return inb(addr);
	} else {
		return *(volatile uint8_t *)addr;
	}
}

static uint32_t ioreadl(unsigned long addr, bool io)
{
	/* Note: assumes little endian */
	if (io) {
		return inl(addr);
	} else {
		return *(volatile uint32_t *)addr;
	}
}

static void iowriteb(unsigned long addr, uint8_t data, bool io)
{
	if (io) {
		outb(data, addr);
	} else {
		*(volatile uint8_t *)addr = data;
	}
}

static bool pci_next(struct test *test, unsigned long addr, bool io)
{
	int i;
	uint8_t width;

	if (!pci_test.memaddr) {
		test->func = NULL;
		return true;
	}
	pci_test.test_idx++;
	iowriteb(addr + offsetof(struct pci_test_dev_hdr, test),
		 pci_test.test_idx, io);
	width = ioreadb(addr + offsetof(struct pci_test_dev_hdr, width),
			io);
	switch (width) {
		case 1:
			test->func = io ? pci_io_testb : pci_mem_testb;
			break;
		case 2:
			test->func = io ? pci_io_testw : pci_mem_testw;
			break;
		case 4:
			test->func = io ? pci_io_testl : pci_mem_testl;
			break;
		default:
			/* Reset index for purposes of the next test */
			pci_test.test_idx = -1;
			test->func = NULL;
			return false;
	}
	pci_test.data = ioreadl(addr + offsetof(struct pci_test_dev_hdr, data),
				io);
	pci_test.offset = ioreadl(addr + offsetof(struct pci_test_dev_hdr,
						  offset), io);
	for (i = 0; i < pci_test.offset; ++i) {
		char c = ioreadb(addr + offsetof(struct pci_test_dev_hdr,
						 name) + i, io);
		if (!c) {
			break;
		}
		printf("%c",c);
	}
	printf(":");
	return true;
}

static bool pci_mem_next(struct test *test)
{
	bool ret;
	ret = pci_next(test, ((unsigned long)pci_test.memaddr), false);
	if (ret) {
		pci_test.mem = pci_test.memaddr + pci_test.offset;
	}
	return ret;
}

static bool pci_io_next(struct test *test)
{
	bool ret;
	ret = pci_next(test, ((unsigned long)pci_test.iobar), true);
	if (ret) {
		pci_test.ioport = pci_test.iobar + pci_test.offset;
	}
	return ret;
}

static int has_tscdeadline(void)
{
    uint32_t lvtt;

    if (cpuid(1).c & (1 << 24)) {
        lvtt = APIC_LVT_TIMER_TSCDEADLINE | IPI_TEST_VECTOR;
        apic_write(APIC_LVTT, lvtt);
        return 1;
    } else {
        return 0;
    }
}

static void tscdeadline_immed(void)
{
	wrmsr(MSR_IA32_TSCDEADLINE, rdtsc());
	asm volatile("nop");
}

static void tscdeadline(void)
{
	x = 0;
	wrmsr(MSR_IA32_TSCDEADLINE, rdtsc()+3000);
	while (x == 0) barrier();
}

static struct test tests[] = {
	{ cpuid_test, "cpuid", .parallel = 1,  },
	{ vmcall, "vmcall", .parallel = 1, },
#ifdef __x86_64__
	{ mov_from_cr8, "mov_from_cr8", .parallel = 1, },
	{ mov_to_cr8, "mov_to_cr8" , .parallel = 1, },
#endif
	{ inl_pmtimer, "inl_from_pmtimer", .parallel = 1, },
	{ inl_nop_qemu, "inl_from_qemu", .parallel = 1 },
	{ inl_nop_kernel, "inl_from_kernel", .parallel = 1 },
	{ outl_elcr_kernel, "outl_to_kernel", .parallel = 1 },
	{ mov_dr, "mov_dr", .parallel = 1 },
	{ tscdeadline_immed, "tscdeadline_immed", has_tscdeadline, .parallel = 1, },
	{ tscdeadline, "tscdeadline", has_tscdeadline, .parallel = 1, },
	{ self_ipi_sti_nop, "self_ipi_sti_nop", .parallel = 0, },
	{ self_ipi_sti_hlt, "self_ipi_sti_hlt", .parallel = 0, },
	{ self_ipi_tpr, "self_ipi_tpr", .parallel = 0, },
	{ self_ipi_tpr_sti_nop, "self_ipi_tpr_sti_nop", .parallel = 0, },
	{ self_ipi_tpr_sti_hlt, "self_ipi_tpr_sti_hlt", .parallel = 0, },
	{ x2apic_self_ipi_sti_nop, "x2apic_self_ipi_sti_nop", is_x2apic, .parallel = 0, },
	{ x2apic_self_ipi_sti_hlt, "x2apic_self_ipi_sti_hlt", is_x2apic, .parallel = 0, },
	{ x2apic_self_ipi_tpr, "x2apic_self_ipi_tpr", is_x2apic, .parallel = 0, },
	{ x2apic_self_ipi_tpr_sti_nop, "x2apic_self_ipi_tpr_sti_nop", is_x2apic, .parallel = 0, },
	{ x2apic_self_ipi_tpr_sti_hlt, "x2apic_self_ipi_tpr_sti_hlt", is_x2apic, .parallel = 0, },
	{ ipi, "ipi", is_smp, .parallel = 0, },
	{ ipi_halt, "ipi+halt", is_smp, .parallel = 0, },
	{ ple_round_robin, "ple-round-robin", .parallel = 1 },
	{ wr_tsc_adjust_msr, "wr_tsc_adjust_msr", .parallel = 1 },
	{ rd_tsc_adjust_msr, "rd_tsc_adjust_msr", .parallel = 1 },
	{ NULL, "pci-mem", .parallel = 0, .next = pci_mem_next },
	{ NULL, "pci-io", .parallel = 0, .next = pci_io_next },
};

unsigned iterations;

static void run_test(void *_func)
{
    int i;
    void (*func)(void) = _func;

    for (i = 0; i < iterations; ++i)
        func();
}

static bool do_test(struct test *test)
{
	int i;
	unsigned long long t1, t2;
        void (*func)(void);

        iterations = 32;

        if (test->valid && !test->valid()) {
		printf("%s (skipped)\n", test->name);
		return false;
	}

	if (test->next && !test->next(test)) {
		return false;
	}

	func = test->func;
        if (!func) {
		printf("%s (skipped)\n", test->name);
		return false;
	}

	do {
		iterations *= 2;
		t1 = rdtsc();

		if (!test->parallel) {
			for (i = 0; i < iterations; ++i)
				func();
		} else {
			on_cpus(run_test, func);
		}
		t2 = rdtsc();
	} while ((t2 - t1) < GOAL);
	printf("%s %d\n", test->name, (int)((t2 - t1) / iterations));
	return test->next;
}

static void enable_nx(void *junk)
{
	if (cpuid(0x80000001).d & (1 << 20))
		wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_NX_MASK);
}

bool test_wanted(struct test *test, char *wanted[], int nwanted)
{
	int i;

	if (!nwanted)
		return true;

	for (i = 0; i < nwanted; ++i)
		if (strcmp(wanted[i], test->name) == 0)
			return true;

	return false;
}

int main(int ac, char **av)
{
	struct fadt_descriptor_rev1 *fadt;
	int i;
	unsigned long membar = 0;
	struct pci_dev pcidev;
	int ret;

	smp_init();
	setup_vm();
	handle_irq(IPI_TEST_VECTOR, self_ipi_isr);
	nr_cpus = cpu_count();

	irq_enable();
	on_cpus(enable_nx, NULL);

	fadt = find_acpi_table_addr(FACP_SIGNATURE);
	pm_tmr_blk = fadt->pm_tmr_blk;
	printf("PM timer port is %x\n", pm_tmr_blk);

	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
	if (ret != PCIDEVADDR_INVALID) {
		pci_dev_init(&pcidev, ret);
		assert(pci_bar_is_memory(&pcidev, PCI_TESTDEV_BAR_MEM));
		assert(!pci_bar_is_memory(&pcidev, PCI_TESTDEV_BAR_IO));
		membar = pcidev.resource[PCI_TESTDEV_BAR_MEM];
		pci_test.memaddr = ioremap(membar, PAGE_SIZE);
		pci_test.iobar = pcidev.resource[PCI_TESTDEV_BAR_IO];
		printf("pci-testdev at %#x membar %lx iobar %x\n",
		       pcidev.bdf, membar, pci_test.iobar);
	}

	for (i = 0; i < ARRAY_SIZE(tests); ++i)
		if (test_wanted(&tests[i], av + 1, ac - 1))
			while (do_test(&tests[i])) {}

	return 0;
}
                                                                                                 source/v64/tests/kvm-unit-tests/x86/vmx.c                                                           0000644 0000000 0000000 00000133324 00000000000 015351  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * x86/vmx.c : Framework for testing nested virtualization
 *	This is a framework to test nested VMX for KVM, which
 * 	started as a project of GSoC 2013. All test cases should
 *	be located in x86/vmx_tests.c and framework related
 *	functions should be in this file.
 *
 * How to write test cases?
 *	Add callbacks of test suite in variant "vmx_tests". You can
 *	write:
 *		1. init function used for initializing test suite
 *		2. main function for codes running in L2 guest, 
 *		3. exit_handler to handle vmexit of L2 to L1
 *		4. syscall handler to handle L2 syscall vmexit
 *		5. vmenter fail handler to handle direct failure of vmenter
 *		6. guest_regs is loaded when vmenter and saved when
 *			vmexit, you can read and set it in exit_handler
 *	If no special function is needed for a test suite, use
 *	coressponding basic_* functions as callback. More handlers
 *	can be added to "vmx_tests", see details of "struct vmx_test"
 *	and function test_run().
 *
 * Currently, vmx test framework only set up one VCPU and one
 * concurrent guest test environment with same paging for L2 and
 * L1. For usage of EPT, only 1:1 mapped paging is used from VFN
 * to PFN.
 *
 * Author : Arthur Chunqi Li <yzt356@gmail.com>
 */

#include "libcflat.h"
#include "processor.h"
#include "vm.h"
#include "desc.h"
#include "vmx.h"
#include "msr.h"
#include "smp.h"

u64 *vmxon_region;
struct vmcs *vmcs_root;
u32 vpid_cnt;
void *guest_stack, *guest_syscall_stack;
u32 ctrl_pin, ctrl_enter, ctrl_exit, ctrl_cpu[2];
struct regs regs;

struct vmx_test *current;

#define MAX_TEST_TEARDOWN_STEPS 10

struct test_teardown_step {
	test_teardown_func func;
	void *data;
};

static int teardown_count;
static struct test_teardown_step teardown_steps[MAX_TEST_TEARDOWN_STEPS];

static test_guest_func v2_guest_main;

u64 hypercall_field;
bool launched;
static int matched;
static int guest_finished;
static int in_guest;

union vmx_basic basic;
union vmx_ctrl_msr ctrl_pin_rev;
union vmx_ctrl_msr ctrl_cpu_rev[2];
union vmx_ctrl_msr ctrl_exit_rev;
union vmx_ctrl_msr ctrl_enter_rev;
union vmx_ept_vpid  ept_vpid;

extern struct descriptor_table_ptr gdt64_desc;
extern struct descriptor_table_ptr idt_descr;
extern struct descriptor_table_ptr tss_descr;
extern void *vmx_return;
extern void *entry_sysenter;
extern void *guest_entry;

static volatile u32 stage;

static jmp_buf abort_target;

struct vmcs_field {
	u64 mask;
	u64 encoding;
};

#define MASK(_bits) GENMASK_ULL((_bits) - 1, 0)
#define MASK_NATURAL MASK(sizeof(unsigned long) * 8)

static struct vmcs_field vmcs_fields[] = {
	{ MASK(16), VPID },
	{ MASK(16), PINV },
	{ MASK(16), EPTP_IDX },

	{ MASK(16), GUEST_SEL_ES },
	{ MASK(16), GUEST_SEL_CS },
	{ MASK(16), GUEST_SEL_SS },
	{ MASK(16), GUEST_SEL_DS },
	{ MASK(16), GUEST_SEL_FS },
	{ MASK(16), GUEST_SEL_GS },
	{ MASK(16), GUEST_SEL_LDTR },
	{ MASK(16), GUEST_SEL_TR },
	{ MASK(16), GUEST_INT_STATUS },

	{ MASK(16), HOST_SEL_ES },
	{ MASK(16), HOST_SEL_CS },
	{ MASK(16), HOST_SEL_SS },
	{ MASK(16), HOST_SEL_DS },
	{ MASK(16), HOST_SEL_FS },
	{ MASK(16), HOST_SEL_GS },
	{ MASK(16), HOST_SEL_TR },

	{ MASK(64), IO_BITMAP_A },
	{ MASK(64), IO_BITMAP_B },
	{ MASK(64), MSR_BITMAP },
	{ MASK(64), EXIT_MSR_ST_ADDR },
	{ MASK(64), EXIT_MSR_LD_ADDR },
	{ MASK(64), ENTER_MSR_LD_ADDR },
	{ MASK(64), VMCS_EXEC_PTR },
	{ MASK(64), TSC_OFFSET },
	{ MASK(64), APIC_VIRT_ADDR },
	{ MASK(64), APIC_ACCS_ADDR },
	{ MASK(64), EPTP },

	{ 0 /* read-only */, INFO_PHYS_ADDR },

	{ MASK(64), VMCS_LINK_PTR },
	{ MASK(64), GUEST_DEBUGCTL },
	{ MASK(64), GUEST_EFER },
	{ MASK(64), GUEST_PAT },
	{ MASK(64), GUEST_PERF_GLOBAL_CTRL },
	{ MASK(64), GUEST_PDPTE },

	{ MASK(64), HOST_PAT },
	{ MASK(64), HOST_EFER },
	{ MASK(64), HOST_PERF_GLOBAL_CTRL },

	{ MASK(32), PIN_CONTROLS },
	{ MASK(32), CPU_EXEC_CTRL0 },
	{ MASK(32), EXC_BITMAP },
	{ MASK(32), PF_ERROR_MASK },
	{ MASK(32), PF_ERROR_MATCH },
	{ MASK(32), CR3_TARGET_COUNT },
	{ MASK(32), EXI_CONTROLS },
	{ MASK(32), EXI_MSR_ST_CNT },
	{ MASK(32), EXI_MSR_LD_CNT },
	{ MASK(32), ENT_CONTROLS },
	{ MASK(32), ENT_MSR_LD_CNT },
	{ MASK(32), ENT_INTR_INFO },
	{ MASK(32), ENT_INTR_ERROR },
	{ MASK(32), ENT_INST_LEN },
	{ MASK(32), TPR_THRESHOLD },
	{ MASK(32), CPU_EXEC_CTRL1 },

	{ 0 /* read-only */, VMX_INST_ERROR },
	{ 0 /* read-only */, EXI_REASON },
	{ 0 /* read-only */, EXI_INTR_INFO },
	{ 0 /* read-only */, EXI_INTR_ERROR },
	{ 0 /* read-only */, IDT_VECT_INFO },
	{ 0 /* read-only */, IDT_VECT_ERROR },
	{ 0 /* read-only */, EXI_INST_LEN },
	{ 0 /* read-only */, EXI_INST_INFO },

	{ MASK(32), GUEST_LIMIT_ES },
	{ MASK(32), GUEST_LIMIT_CS },
	{ MASK(32), GUEST_LIMIT_SS },
	{ MASK(32), GUEST_LIMIT_DS },
	{ MASK(32), GUEST_LIMIT_FS },
	{ MASK(32), GUEST_LIMIT_GS },
	{ MASK(32), GUEST_LIMIT_LDTR },
	{ MASK(32), GUEST_LIMIT_TR },
	{ MASK(32), GUEST_LIMIT_GDTR },
	{ MASK(32), GUEST_LIMIT_IDTR },
	{ 0x1d0ff, GUEST_AR_ES },
	{ 0x1f0ff, GUEST_AR_CS },
	{ 0x1d0ff, GUEST_AR_SS },
	{ 0x1d0ff, GUEST_AR_DS },
	{ 0x1d0ff, GUEST_AR_FS },
	{ 0x1d0ff, GUEST_AR_GS },
	{ 0x1d0ff, GUEST_AR_LDTR },
	{ 0x1d0ff, GUEST_AR_TR },
	{ MASK(32), GUEST_INTR_STATE },
	{ MASK(32), GUEST_ACTV_STATE },
	{ MASK(32), GUEST_SMBASE },
	{ MASK(32), GUEST_SYSENTER_CS },
	{ MASK(32), PREEMPT_TIMER_VALUE },

	{ MASK(32), HOST_SYSENTER_CS },

	{ MASK_NATURAL, CR0_MASK },
	{ MASK_NATURAL, CR4_MASK },
	{ MASK_NATURAL, CR0_READ_SHADOW },
	{ MASK_NATURAL, CR4_READ_SHADOW },
	{ MASK_NATURAL, CR3_TARGET_0 },
	{ MASK_NATURAL, CR3_TARGET_1 },
	{ MASK_NATURAL, CR3_TARGET_2 },
	{ MASK_NATURAL, CR3_TARGET_3 },

	{ 0 /* read-only */, EXI_QUALIFICATION },
	{ 0 /* read-only */, IO_RCX },
	{ 0 /* read-only */, IO_RSI },
	{ 0 /* read-only */, IO_RDI },
	{ 0 /* read-only */, IO_RIP },
	{ 0 /* read-only */, GUEST_LINEAR_ADDRESS },

	{ MASK_NATURAL, GUEST_CR0 },
	{ MASK_NATURAL, GUEST_CR3 },
	{ MASK_NATURAL, GUEST_CR4 },
	{ MASK_NATURAL, GUEST_BASE_ES },
	{ MASK_NATURAL, GUEST_BASE_CS },
	{ MASK_NATURAL, GUEST_BASE_SS },
	{ MASK_NATURAL, GUEST_BASE_DS },
	{ MASK_NATURAL, GUEST_BASE_FS },
	{ MASK_NATURAL, GUEST_BASE_GS },
	{ MASK_NATURAL, GUEST_BASE_LDTR },
	{ MASK_NATURAL, GUEST_BASE_TR },
	{ MASK_NATURAL, GUEST_BASE_GDTR },
	{ MASK_NATURAL, GUEST_BASE_IDTR },
	{ MASK_NATURAL, GUEST_DR7 },
	{ MASK_NATURAL, GUEST_RSP },
	{ MASK_NATURAL, GUEST_RIP },
	{ MASK_NATURAL, GUEST_RFLAGS },
	{ MASK_NATURAL, GUEST_PENDING_DEBUG },
	{ MASK_NATURAL, GUEST_SYSENTER_ESP },
	{ MASK_NATURAL, GUEST_SYSENTER_EIP },

	{ MASK_NATURAL, HOST_CR0 },
	{ MASK_NATURAL, HOST_CR3 },
	{ MASK_NATURAL, HOST_CR4 },
	{ MASK_NATURAL, HOST_BASE_FS },
	{ MASK_NATURAL, HOST_BASE_GS },
	{ MASK_NATURAL, HOST_BASE_TR },
	{ MASK_NATURAL, HOST_BASE_GDTR },
	{ MASK_NATURAL, HOST_BASE_IDTR },
	{ MASK_NATURAL, HOST_SYSENTER_ESP },
	{ MASK_NATURAL, HOST_SYSENTER_EIP },
	{ MASK_NATURAL, HOST_RSP },
	{ MASK_NATURAL, HOST_RIP },
};

static inline u64 vmcs_field_value(struct vmcs_field *f, u8 cookie)
{
	u64 value;

	/* Incorporate the cookie and the field encoding into the value. */
	value = cookie;
	value |= (f->encoding << 8);
	value |= 0xdeadbeefull << 32;

	return value & f->mask;
}

static void set_vmcs_field(struct vmcs_field *f, u8 cookie)
{
	vmcs_write(f->encoding, vmcs_field_value(f, cookie));
}

static bool check_vmcs_field(struct vmcs_field *f, u8 cookie)
{
	u64 expected;
	u64 actual;
	int ret;

	ret = vmcs_read_checking(f->encoding, &actual);
	assert(!(ret & X86_EFLAGS_CF));
	/* Skip VMCS fields that aren't recognized by the CPU */
	if (ret & X86_EFLAGS_ZF)
		return true;

	expected = vmcs_field_value(f, cookie);
	actual &= f->mask;

	if (expected == actual)
		return true;

	printf("FAIL: VMWRITE/VMREAD %lx (expected: %lx, actual: %lx)\n",
	       f->encoding, (unsigned long) expected, (unsigned long) actual);

	return false;
}

static void set_all_vmcs_fields(u8 cookie)
{
	int i;

	for (i = 0; i < ARRAY_SIZE(vmcs_fields); i++)
		set_vmcs_field(&vmcs_fields[i], cookie);
}

static bool check_all_vmcs_fields(u8 cookie)
{
	bool pass = true;
	int i;

	for (i = 0; i < ARRAY_SIZE(vmcs_fields); i++) {
		if (!check_vmcs_field(&vmcs_fields[i], cookie))
			pass = false;
	}

	return pass;
}

void test_vmwrite_vmread(void)
{
	struct vmcs *vmcs = alloc_page();

	memset(vmcs, 0, PAGE_SIZE);
	vmcs->revision_id = basic.revision;
	assert(!vmcs_clear(vmcs));
	assert(!make_vmcs_current(vmcs));

	set_all_vmcs_fields(0x42);
	report("VMWRITE/VMREAD", check_all_vmcs_fields(0x42));

	assert(!vmcs_clear(vmcs));
	free_page(vmcs);
}

void test_vmcs_lifecycle(void)
{
	struct vmcs *vmcs[2] = {};
	int i;

	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
		vmcs[i] = alloc_page();
		memset(vmcs[i], 0, PAGE_SIZE);
		vmcs[i]->revision_id = basic.revision;
	}

#define VMPTRLD(_i) do { \
	assert(_i < ARRAY_SIZE(vmcs)); \
	assert(!make_vmcs_current(vmcs[_i])); \
	printf("VMPTRLD VMCS%d\n", (_i)); \
} while (0)

#define VMCLEAR(_i) do { \
	assert(_i < ARRAY_SIZE(vmcs)); \
	assert(!vmcs_clear(vmcs[_i])); \
	printf("VMCLEAR VMCS%d\n", (_i)); \
} while (0)

	VMCLEAR(0);
	VMPTRLD(0);
	set_all_vmcs_fields(0);
	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));

	VMCLEAR(0);
	VMPTRLD(0);
	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));

	VMCLEAR(1);
	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));

	VMPTRLD(1);
	set_all_vmcs_fields(1);
	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));

	VMPTRLD(0);
	report("current:VMCS0 active:[VMCS0,VCMS1]", check_all_vmcs_fields(0));
	VMPTRLD(1);
	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));
	VMPTRLD(1);
	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));

	VMCLEAR(0);
	report("current:VMCS1 active:[VCMS1]", check_all_vmcs_fields(1));

	/* VMPTRLD should not erase VMWRITEs to the current VMCS */
	set_all_vmcs_fields(2);
	VMPTRLD(1);
	report("current:VMCS1 active:[VCMS1]", check_all_vmcs_fields(2));

	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
		VMCLEAR(i);
		free_page(vmcs[i]);
	}

#undef VMPTRLD
#undef VMCLEAR
}

void vmx_set_test_stage(u32 s)
{
	barrier();
	stage = s;
	barrier();
}

u32 vmx_get_test_stage(void)
{
	u32 s;

	barrier();
	s = stage;
	barrier();
	return s;
}

void vmx_inc_test_stage(void)
{
	barrier();
	stage++;
	barrier();
}

/* entry_sysenter */
asm(
	".align	4, 0x90\n\t"
	".globl	entry_sysenter\n\t"
	"entry_sysenter:\n\t"
	SAVE_GPR
	"	and	$0xf, %rax\n\t"
	"	mov	%rax, %rdi\n\t"
	"	call	syscall_handler\n\t"
	LOAD_GPR
	"	vmresume\n\t"
);

static void __attribute__((__used__)) syscall_handler(u64 syscall_no)
{
	if (current->syscall_handler)
		current->syscall_handler(syscall_no);
}

static const char * const exit_reason_descriptions[] = {
	[VMX_EXC_NMI]		= "VMX_EXC_NMI",
	[VMX_EXTINT]		= "VMX_EXTINT",
	[VMX_TRIPLE_FAULT]	= "VMX_TRIPLE_FAULT",
	[VMX_INIT]		= "VMX_INIT",
	[VMX_SIPI]		= "VMX_SIPI",
	[VMX_SMI_IO]		= "VMX_SMI_IO",
	[VMX_SMI_OTHER]		= "VMX_SMI_OTHER",
	[VMX_INTR_WINDOW]	= "VMX_INTR_WINDOW",
	[VMX_NMI_WINDOW]	= "VMX_NMI_WINDOW",
	[VMX_TASK_SWITCH]	= "VMX_TASK_SWITCH",
	[VMX_CPUID]		= "VMX_CPUID",
	[VMX_GETSEC]		= "VMX_GETSEC",
	[VMX_HLT]		= "VMX_HLT",
	[VMX_INVD]		= "VMX_INVD",
	[VMX_INVLPG]		= "VMX_INVLPG",
	[VMX_RDPMC]		= "VMX_RDPMC",
	[VMX_RDTSC]		= "VMX_RDTSC",
	[VMX_RSM]		= "VMX_RSM",
	[VMX_VMCALL]		= "VMX_VMCALL",
	[VMX_VMCLEAR]		= "VMX_VMCLEAR",
	[VMX_VMLAUNCH]		= "VMX_VMLAUNCH",
	[VMX_VMPTRLD]		= "VMX_VMPTRLD",
	[VMX_VMPTRST]		= "VMX_VMPTRST",
	[VMX_VMREAD]		= "VMX_VMREAD",
	[VMX_VMRESUME]		= "VMX_VMRESUME",
	[VMX_VMWRITE]		= "VMX_VMWRITE",
	[VMX_VMXOFF]		= "VMX_VMXOFF",
	[VMX_VMXON]		= "VMX_VMXON",
	[VMX_CR]		= "VMX_CR",
	[VMX_DR]		= "VMX_DR",
	[VMX_IO]		= "VMX_IO",
	[VMX_RDMSR]		= "VMX_RDMSR",
	[VMX_WRMSR]		= "VMX_WRMSR",
	[VMX_FAIL_STATE]	= "VMX_FAIL_STATE",
	[VMX_FAIL_MSR]		= "VMX_FAIL_MSR",
	[VMX_MWAIT]		= "VMX_MWAIT",
	[VMX_MTF]		= "VMX_MTF",
	[VMX_MONITOR]		= "VMX_MONITOR",
	[VMX_PAUSE]		= "VMX_PAUSE",
	[VMX_FAIL_MCHECK]	= "VMX_FAIL_MCHECK",
	[VMX_TPR_THRESHOLD]	= "VMX_TPR_THRESHOLD",
	[VMX_APIC_ACCESS]	= "VMX_APIC_ACCESS",
	[VMX_GDTR_IDTR]		= "VMX_GDTR_IDTR",
	[VMX_LDTR_TR]		= "VMX_LDTR_TR",
	[VMX_EPT_VIOLATION]	= "VMX_EPT_VIOLATION",
	[VMX_EPT_MISCONFIG]	= "VMX_EPT_MISCONFIG",
	[VMX_INVEPT]		= "VMX_INVEPT",
	[VMX_PREEMPT]		= "VMX_PREEMPT",
	[VMX_INVVPID]		= "VMX_INVVPID",
	[VMX_WBINVD]		= "VMX_WBINVD",
	[VMX_XSETBV]		= "VMX_XSETBV",
	[VMX_APIC_WRITE]	= "VMX_APIC_WRITE",
	[VMX_RDRAND]		= "VMX_RDRAND",
	[VMX_INVPCID]		= "VMX_INVPCID",
	[VMX_VMFUNC]		= "VMX_VMFUNC",
	[VMX_RDSEED]		= "VMX_RDSEED",
	[VMX_PML_FULL]		= "VMX_PML_FULL",
	[VMX_XSAVES]		= "VMX_XSAVES",
	[VMX_XRSTORS]		= "VMX_XRSTORS",
};

const char *exit_reason_description(u64 reason)
{
	if (reason >= ARRAY_SIZE(exit_reason_descriptions))
		return "(unknown)";
	return exit_reason_descriptions[reason] ? : "(unused)";
}

void print_vmexit_info()
{
	u64 guest_rip, guest_rsp;
	ulong reason = vmcs_read(EXI_REASON) & 0xff;
	ulong exit_qual = vmcs_read(EXI_QUALIFICATION);
	guest_rip = vmcs_read(GUEST_RIP);
	guest_rsp = vmcs_read(GUEST_RSP);
	printf("VMEXIT info:\n");
	printf("\tvmexit reason = %ld\n", reason);
	printf("\texit qualification = %#lx\n", exit_qual);
	printf("\tBit 31 of reason = %lx\n", (vmcs_read(EXI_REASON) >> 31) & 1);
	printf("\tguest_rip = %#lx\n", guest_rip);
	printf("\tRAX=%#lx    RBX=%#lx    RCX=%#lx    RDX=%#lx\n",
		regs.rax, regs.rbx, regs.rcx, regs.rdx);
	printf("\tRSP=%#lx    RBP=%#lx    RSI=%#lx    RDI=%#lx\n",
		guest_rsp, regs.rbp, regs.rsi, regs.rdi);
	printf("\tR8 =%#lx    R9 =%#lx    R10=%#lx    R11=%#lx\n",
		regs.r8, regs.r9, regs.r10, regs.r11);
	printf("\tR12=%#lx    R13=%#lx    R14=%#lx    R15=%#lx\n",
		regs.r12, regs.r13, regs.r14, regs.r15);
}

void
print_vmentry_failure_info(struct vmentry_failure *failure) {
	if (failure->early) {
		printf("Early %s failure: ", failure->instr);
		switch (failure->flags & VMX_ENTRY_FLAGS) {
		case X86_EFLAGS_CF:
			printf("current-VMCS pointer is not valid.\n");
			break;
		case X86_EFLAGS_ZF:
			printf("error number is %ld. See Intel 30.4.\n",
			       vmcs_read(VMX_INST_ERROR));
			break;
		default:
			printf("unexpected flags %lx!\n", failure->flags);
		}
	} else {
		u64 reason = vmcs_read(EXI_REASON);
		u64 qual = vmcs_read(EXI_QUALIFICATION);

		printf("Non-early %s failure (reason=%#lx, qual=%#lx): ",
			failure->instr, reason, qual);

		switch (reason & 0xff) {
		case VMX_FAIL_STATE:
			printf("invalid guest state\n");
			break;
		case VMX_FAIL_MSR:
			printf("MSR loading\n");
			break;
		case VMX_FAIL_MCHECK:
			printf("machine-check event\n");
			break;
		default:
			printf("unexpected basic exit reason %ld\n",
			       reason & 0xff);
		}

		if (!(reason & VMX_ENTRY_FAILURE))
			printf("\tVMX_ENTRY_FAILURE BIT NOT SET!\n");

		if (reason & 0x7fff0000)
			printf("\tRESERVED BITS SET!\n");
	}
}

/*
 * VMCLEAR should ensures all VMCS state is flushed to the VMCS
 * region in memory.
 */
static void test_vmclear_flushing(void)
{
	struct vmcs *vmcs[3] = {};
	int i;

	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
		vmcs[i] = alloc_page();
		memset(vmcs[i], 0, PAGE_SIZE);
	}

	vmcs[0]->revision_id = basic.revision;
	assert(!vmcs_clear(vmcs[0]));
	assert(!make_vmcs_current(vmcs[0]));
	set_all_vmcs_fields(0x86);

	assert(!vmcs_clear(vmcs[0]));
	memcpy(vmcs[1], vmcs[0], basic.size);
	assert(!make_vmcs_current(vmcs[1]));
	report("test vmclear flush (current VMCS)", check_all_vmcs_fields(0x86));

	set_all_vmcs_fields(0x87);
	assert(!make_vmcs_current(vmcs[0]));
	assert(!vmcs_clear(vmcs[1]));
	memcpy(vmcs[2], vmcs[1], basic.size);
	assert(!make_vmcs_current(vmcs[2]));
	report("test vmclear flush (!current VMCS)", check_all_vmcs_fields(0x87));

	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
		assert(!vmcs_clear(vmcs[i]));
		free_page(vmcs[i]);
	}
}

static void test_vmclear(void)
{
	struct vmcs *tmp_root;
	int width = cpuid_maxphyaddr();

	/*
	 * Note- The tests below do not necessarily have a
	 * valid VMCS, but that's ok since the invalid vmcs
	 * is only used for a specific test and is discarded
	 * without touching its contents
	 */

	/* Unaligned page access */
	tmp_root = (struct vmcs *)((intptr_t)vmcs_root + 1);
	report("test vmclear with unaligned vmcs",
	       vmcs_clear(tmp_root) == 1);

	/* gpa bits beyond physical address width are set*/
	tmp_root = (struct vmcs *)((intptr_t)vmcs_root |
				   ((u64)1 << (width+1)));
	report("test vmclear with vmcs address bits set beyond physical address width",
	       vmcs_clear(tmp_root) == 1);

	/* Pass VMXON region */
	tmp_root = (struct vmcs *)vmxon_region;
	report("test vmclear with vmxon region",
	       vmcs_clear(tmp_root) == 1);

	/* Valid VMCS */
	report("test vmclear with valid vmcs region", vmcs_clear(vmcs_root) == 0);

	test_vmclear_flushing();
}

static void __attribute__((__used__)) guest_main(void)
{
	if (current->v2)
		v2_guest_main();
	else
		current->guest_main();
}

/* guest_entry */
asm(
	".align	4, 0x90\n\t"
	".globl	entry_guest\n\t"
	"guest_entry:\n\t"
	"	call guest_main\n\t"
	"	mov $1, %edi\n\t"
	"	call hypercall\n\t"
);

/* EPT paging structure related functions */
/* split_large_ept_entry: Split a 2M/1G large page into 512 smaller PTEs.
		@ptep : large page table entry to split
		@level : level of ptep (2 or 3)
 */
static void split_large_ept_entry(unsigned long *ptep, int level)
{
	unsigned long *new_pt;
	unsigned long gpa;
	unsigned long pte;
	unsigned long prototype;
	int i;

	pte = *ptep;
	assert(pte & EPT_PRESENT);
	assert(pte & EPT_LARGE_PAGE);
	assert(level == 2 || level == 3);

	new_pt = alloc_page();
	assert(new_pt);
	memset(new_pt, 0, PAGE_SIZE);

	prototype = pte & ~EPT_ADDR_MASK;
	if (level == 2)
		prototype &= ~EPT_LARGE_PAGE;

	gpa = pte & EPT_ADDR_MASK;
	for (i = 0; i < EPT_PGDIR_ENTRIES; i++) {
		new_pt[i] = prototype | gpa;
		gpa += 1ul << EPT_LEVEL_SHIFT(level - 1);
	}

	pte &= ~EPT_LARGE_PAGE;
	pte &= ~EPT_ADDR_MASK;
	pte |= virt_to_phys(new_pt);

	*ptep = pte;
}

/* install_ept_entry : Install a page to a given level in EPT
		@pml4 : addr of pml4 table
		@pte_level : level of PTE to set
		@guest_addr : physical address of guest
		@pte : pte value to set
		@pt_page : address of page table, NULL for a new page
 */
void install_ept_entry(unsigned long *pml4,
		int pte_level,
		unsigned long guest_addr,
		unsigned long pte,
		unsigned long *pt_page)
{
	int level;
	unsigned long *pt = pml4;
	unsigned offset;

	/* EPT only uses 48 bits of GPA. */
	assert(guest_addr < (1ul << 48));

	for (level = EPT_PAGE_LEVEL; level > pte_level; --level) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(level))
				& EPT_PGDIR_MASK;
		if (!(pt[offset] & (EPT_PRESENT))) {
			unsigned long *new_pt = pt_page;
			if (!new_pt)
				new_pt = alloc_page();
			else
				pt_page = 0;
			memset(new_pt, 0, PAGE_SIZE);
			pt[offset] = virt_to_phys(new_pt)
					| EPT_RA | EPT_WA | EPT_EA;
		} else if (pt[offset] & EPT_LARGE_PAGE)
			split_large_ept_entry(&pt[offset], level);
		pt = phys_to_virt(pt[offset] & EPT_ADDR_MASK);
	}
	offset = (guest_addr >> EPT_LEVEL_SHIFT(level)) & EPT_PGDIR_MASK;
	pt[offset] = pte;
}

/* Map a page, @perm is the permission of the page */
void install_ept(unsigned long *pml4,
		unsigned long phys,
		unsigned long guest_addr,
		u64 perm)
{
	install_ept_entry(pml4, 1, guest_addr, (phys & PAGE_MASK) | perm, 0);
}

/* Map a 1G-size page */
void install_1g_ept(unsigned long *pml4,
		unsigned long phys,
		unsigned long guest_addr,
		u64 perm)
{
	install_ept_entry(pml4, 3, guest_addr,
			(phys & PAGE_MASK) | perm | EPT_LARGE_PAGE, 0);
}

/* Map a 2M-size page */
void install_2m_ept(unsigned long *pml4,
		unsigned long phys,
		unsigned long guest_addr,
		u64 perm)
{
	install_ept_entry(pml4, 2, guest_addr,
			(phys & PAGE_MASK) | perm | EPT_LARGE_PAGE, 0);
}

/* setup_ept_range : Setup a range of 1:1 mapped page to EPT paging structure.
		@start : start address of guest page
		@len : length of address to be mapped
		@map_1g : whether 1G page map is used
		@map_2m : whether 2M page map is used
		@perm : permission for every page
 */
void setup_ept_range(unsigned long *pml4, unsigned long start,
		     unsigned long len, int map_1g, int map_2m, u64 perm)
{
	u64 phys = start;
	u64 max = (u64)len + (u64)start;

	if (map_1g) {
		while (phys + PAGE_SIZE_1G <= max) {
			install_1g_ept(pml4, phys, phys, perm);
			phys += PAGE_SIZE_1G;
		}
	}
	if (map_2m) {
		while (phys + PAGE_SIZE_2M <= max) {
			install_2m_ept(pml4, phys, phys, perm);
			phys += PAGE_SIZE_2M;
		}
	}
	while (phys + PAGE_SIZE <= max) {
		install_ept(pml4, phys, phys, perm);
		phys += PAGE_SIZE;
	}
}

/* get_ept_pte : Get the PTE of a given level in EPT,
    @level == 1 means get the latest level*/
bool get_ept_pte(unsigned long *pml4, unsigned long guest_addr, int level,
		unsigned long *pte)
{
	int l;
	unsigned long *pt = pml4, iter_pte;
	unsigned offset;

	assert(level >= 1 && level <= 4);

	for (l = EPT_PAGE_LEVEL; ; --l) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
		iter_pte = pt[offset];
		if (l == level)
			break;
		if (l < 4 && (iter_pte & EPT_LARGE_PAGE))
			return false;
		if (!(iter_pte & (EPT_PRESENT)))
			return false;
		pt = (unsigned long *)(iter_pte & EPT_ADDR_MASK);
	}
	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
	if (pte)
		*pte = pt[offset];
	return true;
}

static void clear_ept_ad_pte(unsigned long *pml4, unsigned long guest_addr)
{
	int l;
	unsigned long *pt = pml4;
	u64 pte;
	unsigned offset;

	for (l = EPT_PAGE_LEVEL; ; --l) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
		pt[offset] &= ~(EPT_ACCESS_FLAG|EPT_DIRTY_FLAG);
		pte = pt[offset];
		if (l == 1 || (l < 4 && (pte & EPT_LARGE_PAGE)))
			break;
		pt = (unsigned long *)(pte & EPT_ADDR_MASK);
	}
}

/* clear_ept_ad : Clear EPT A/D bits for the page table walk and the
   final GPA of a guest address.  */
void clear_ept_ad(unsigned long *pml4, u64 guest_cr3,
		  unsigned long guest_addr)
{
	int l;
	unsigned long *pt = (unsigned long *)guest_cr3, gpa;
	u64 pte, offset_in_page;
	unsigned offset;

	for (l = EPT_PAGE_LEVEL; ; --l) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;

		clear_ept_ad_pte(pml4, (u64) &pt[offset]);
		pte = pt[offset];
		if (l == 1 || (l < 4 && (pte & PT_PAGE_SIZE_MASK)))
			break;
		if (!(pte & PT_PRESENT_MASK))
			return;
		pt = (unsigned long *)(pte & PT_ADDR_MASK);
	}

	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
	offset_in_page = guest_addr & ((1 << EPT_LEVEL_SHIFT(l)) - 1);
	gpa = (pt[offset] & PT_ADDR_MASK) | (guest_addr & offset_in_page);
	clear_ept_ad_pte(pml4, gpa);
}

/* check_ept_ad : Check the content of EPT A/D bits for the page table
   walk and the final GPA of a guest address.  */
void check_ept_ad(unsigned long *pml4, u64 guest_cr3,
		  unsigned long guest_addr, int expected_gpa_ad,
		  int expected_pt_ad)
{
	int l;
	unsigned long *pt = (unsigned long *)guest_cr3, gpa;
	u64 ept_pte, pte, offset_in_page;
	unsigned offset;
	bool bad_pt_ad = false;

	for (l = EPT_PAGE_LEVEL; ; --l) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;

		if (!get_ept_pte(pml4, (u64) &pt[offset], 1, &ept_pte)) {
			printf("EPT - guest level %d page table is not mapped.\n", l);
			return;
		}

		if (!bad_pt_ad) {
			bad_pt_ad |= (ept_pte & (EPT_ACCESS_FLAG|EPT_DIRTY_FLAG)) != expected_pt_ad;
			if (bad_pt_ad)
				report("EPT - guest level %d page table A=%d/D=%d",
				       false, l,
				       !!(expected_pt_ad & EPT_ACCESS_FLAG),
				       !!(expected_pt_ad & EPT_DIRTY_FLAG));
		}

		pte = pt[offset];
		if (l == 1 || (l < 4 && (pte & PT_PAGE_SIZE_MASK)))
			break;
		if (!(pte & PT_PRESENT_MASK))
			return;
		pt = (unsigned long *)(pte & PT_ADDR_MASK);
	}

	if (!bad_pt_ad)
		report("EPT - guest page table structures A=%d/D=%d",
		       true,
		       !!(expected_pt_ad & EPT_ACCESS_FLAG),
		       !!(expected_pt_ad & EPT_DIRTY_FLAG));

	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
	offset_in_page = guest_addr & ((1 << EPT_LEVEL_SHIFT(l)) - 1);
	gpa = (pt[offset] & PT_ADDR_MASK) | (guest_addr & offset_in_page);

	if (!get_ept_pte(pml4, gpa, 1, &ept_pte)) {
		report("EPT - guest physical address is not mapped", false);
		return;
	}
	report("EPT - guest physical address A=%d/D=%d",
	       (ept_pte & (EPT_ACCESS_FLAG|EPT_DIRTY_FLAG)) == expected_gpa_ad,
	       !!(expected_gpa_ad & EPT_ACCESS_FLAG),
	       !!(expected_gpa_ad & EPT_DIRTY_FLAG));
}


void ept_sync(int type, u64 eptp)
{
	switch (type) {
	case INVEPT_SINGLE:
		if (ept_vpid.val & EPT_CAP_INVEPT_SINGLE) {
			invept(INVEPT_SINGLE, eptp);
			break;
		}
		/* else fall through */
	case INVEPT_GLOBAL:
		if (ept_vpid.val & EPT_CAP_INVEPT_ALL) {
			invept(INVEPT_GLOBAL, eptp);
			break;
		}
		/* else fall through */
	default:
		printf("WARNING: invept is not supported!\n");
	}
}

void set_ept_pte(unsigned long *pml4, unsigned long guest_addr,
		 int level, u64 pte_val)
{
	int l;
	unsigned long *pt = pml4;
	unsigned offset;

	assert(level >= 1 && level <= 4);

	for (l = EPT_PAGE_LEVEL; ; --l) {
		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
		if (l == level)
			break;
		assert(pt[offset] & EPT_PRESENT);
		pt = (unsigned long *)(pt[offset] & EPT_ADDR_MASK);
	}
	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
	pt[offset] = pte_val;
}

bool ept_2m_supported(void)
{
	return ept_vpid.val & EPT_CAP_2M_PAGE;
}

bool ept_1g_supported(void)
{
	return ept_vpid.val & EPT_CAP_1G_PAGE;
}

bool ept_huge_pages_supported(int level)
{
	if (level == 2)
		return ept_2m_supported();
	else if (level == 3)
		return ept_1g_supported();
	else
		return false;
}

bool ept_execute_only_supported(void)
{
	return ept_vpid.val & EPT_CAP_WT;
}

bool ept_ad_bits_supported(void)
{
	return ept_vpid.val & EPT_CAP_AD_FLAG;
}

void vpid_sync(int type, u16 vpid)
{
	switch(type) {
	case INVVPID_CONTEXT_GLOBAL:
		if (ept_vpid.val & VPID_CAP_INVVPID_CXTGLB) {
			invvpid(INVVPID_CONTEXT_GLOBAL, vpid, 0);
			break;
		}
	case INVVPID_ALL:
		if (ept_vpid.val & VPID_CAP_INVVPID_ALL) {
			invvpid(INVVPID_ALL, vpid, 0);
			break;
		}
	default:
		printf("WARNING: invvpid is not supported\n");
	}
}

static void init_vmcs_ctrl(void)
{
	/* 26.2 CHECKS ON VMX CONTROLS AND HOST-STATE AREA */
	/* 26.2.1.1 */
	vmcs_write(PIN_CONTROLS, ctrl_pin);
	/* Disable VMEXIT of IO instruction */
	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu[0]);
	if (ctrl_cpu_rev[0].set & CPU_SECONDARY) {
		ctrl_cpu[1] = (ctrl_cpu[1] | ctrl_cpu_rev[1].set) &
			ctrl_cpu_rev[1].clr;
		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu[1]);
	}
	vmcs_write(CR3_TARGET_COUNT, 0);
	vmcs_write(VPID, ++vpid_cnt);
}

static void init_vmcs_host(void)
{
	/* 26.2 CHECKS ON VMX CONTROLS AND HOST-STATE AREA */
	/* 26.2.1.2 */
	vmcs_write(HOST_EFER, rdmsr(MSR_EFER));

	/* 26.2.1.3 */
	vmcs_write(ENT_CONTROLS, ctrl_enter);
	vmcs_write(EXI_CONTROLS, ctrl_exit);

	/* 26.2.2 */
	vmcs_write(HOST_CR0, read_cr0());
	vmcs_write(HOST_CR3, read_cr3());
	vmcs_write(HOST_CR4, read_cr4());
	vmcs_write(HOST_SYSENTER_EIP, (u64)(&entry_sysenter));
	vmcs_write(HOST_SYSENTER_CS,  KERNEL_CS);

	/* 26.2.3 */
	vmcs_write(HOST_SEL_CS, KERNEL_CS);
	vmcs_write(HOST_SEL_SS, KERNEL_DS);
	vmcs_write(HOST_SEL_DS, KERNEL_DS);
	vmcs_write(HOST_SEL_ES, KERNEL_DS);
	vmcs_write(HOST_SEL_FS, KERNEL_DS);
	vmcs_write(HOST_SEL_GS, KERNEL_DS);
	vmcs_write(HOST_SEL_TR, TSS_MAIN);
	vmcs_write(HOST_BASE_TR, tss_descr.base);
	vmcs_write(HOST_BASE_GDTR, gdt64_desc.base);
	vmcs_write(HOST_BASE_IDTR, idt_descr.base);
	vmcs_write(HOST_BASE_FS, 0);
	vmcs_write(HOST_BASE_GS, 0);

	/* Set other vmcs area */
	vmcs_write(PF_ERROR_MASK, 0);
	vmcs_write(PF_ERROR_MATCH, 0);
	vmcs_write(VMCS_LINK_PTR, ~0ul);
	vmcs_write(VMCS_LINK_PTR_HI, ~0ul);
	vmcs_write(HOST_RIP, (u64)(&vmx_return));
}

static void init_vmcs_guest(void)
{
	/* 26.3 CHECKING AND LOADING GUEST STATE */
	ulong guest_cr0, guest_cr4, guest_cr3;
	/* 26.3.1.1 */
	guest_cr0 = read_cr0();
	guest_cr4 = read_cr4();
	guest_cr3 = read_cr3();
	if (ctrl_enter & ENT_GUEST_64) {
		guest_cr0 |= X86_CR0_PG;
		guest_cr4 |= X86_CR4_PAE;
	}
	if ((ctrl_enter & ENT_GUEST_64) == 0)
		guest_cr4 &= (~X86_CR4_PCIDE);
	if (guest_cr0 & X86_CR0_PG)
		guest_cr0 |= X86_CR0_PE;
	vmcs_write(GUEST_CR0, guest_cr0);
	vmcs_write(GUEST_CR3, guest_cr3);
	vmcs_write(GUEST_CR4, guest_cr4);
	vmcs_write(GUEST_SYSENTER_CS,  KERNEL_CS);
	vmcs_write(GUEST_SYSENTER_ESP,
		(u64)(guest_syscall_stack + PAGE_SIZE - 1));
	vmcs_write(GUEST_SYSENTER_EIP, (u64)(&entry_sysenter));
	vmcs_write(GUEST_DR7, 0);
	vmcs_write(GUEST_EFER, rdmsr(MSR_EFER));

	/* 26.3.1.2 */
	vmcs_write(GUEST_SEL_CS, KERNEL_CS);
	vmcs_write(GUEST_SEL_SS, KERNEL_DS);
	vmcs_write(GUEST_SEL_DS, KERNEL_DS);
	vmcs_write(GUEST_SEL_ES, KERNEL_DS);
	vmcs_write(GUEST_SEL_FS, KERNEL_DS);
	vmcs_write(GUEST_SEL_GS, KERNEL_DS);
	vmcs_write(GUEST_SEL_TR, TSS_MAIN);
	vmcs_write(GUEST_SEL_LDTR, 0);

	vmcs_write(GUEST_BASE_CS, 0);
	vmcs_write(GUEST_BASE_ES, 0);
	vmcs_write(GUEST_BASE_SS, 0);
	vmcs_write(GUEST_BASE_DS, 0);
	vmcs_write(GUEST_BASE_FS, 0);
	vmcs_write(GUEST_BASE_GS, 0);
	vmcs_write(GUEST_BASE_TR, tss_descr.base);
	vmcs_write(GUEST_BASE_LDTR, 0);

	vmcs_write(GUEST_LIMIT_CS, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_DS, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_ES, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_SS, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_FS, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_GS, 0xFFFFFFFF);
	vmcs_write(GUEST_LIMIT_LDTR, 0xffff);
	vmcs_write(GUEST_LIMIT_TR, tss_descr.limit);

	vmcs_write(GUEST_AR_CS, 0xa09b);
	vmcs_write(GUEST_AR_DS, 0xc093);
	vmcs_write(GUEST_AR_ES, 0xc093);
	vmcs_write(GUEST_AR_FS, 0xc093);
	vmcs_write(GUEST_AR_GS, 0xc093);
	vmcs_write(GUEST_AR_SS, 0xc093);
	vmcs_write(GUEST_AR_LDTR, 0x82);
	vmcs_write(GUEST_AR_TR, 0x8b);

	/* 26.3.1.3 */
	vmcs_write(GUEST_BASE_GDTR, gdt64_desc.base);
	vmcs_write(GUEST_BASE_IDTR, idt_descr.base);
	vmcs_write(GUEST_LIMIT_GDTR, gdt64_desc.limit);
	vmcs_write(GUEST_LIMIT_IDTR, idt_descr.limit);

	/* 26.3.1.4 */
	vmcs_write(GUEST_RIP, (u64)(&guest_entry));
	vmcs_write(GUEST_RSP, (u64)(guest_stack + PAGE_SIZE - 1));
	vmcs_write(GUEST_RFLAGS, 0x2);

	/* 26.3.1.5 */
	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
	vmcs_write(GUEST_INTR_STATE, 0);
}

static int init_vmcs(struct vmcs **vmcs)
{
	*vmcs = alloc_page();
	memset(*vmcs, 0, PAGE_SIZE);
	(*vmcs)->revision_id = basic.revision;
	/* vmclear first to init vmcs */
	if (vmcs_clear(*vmcs)) {
		printf("%s : vmcs_clear error\n", __func__);
		return 1;
	}

	if (make_vmcs_current(*vmcs)) {
		printf("%s : make_vmcs_current error\n", __func__);
		return 1;
	}

	/* All settings to pin/exit/enter/cpu
	   control fields should be placed here */
	ctrl_pin |= PIN_EXTINT | PIN_NMI | PIN_VIRT_NMI;
	ctrl_exit = EXI_LOAD_EFER | EXI_HOST_64;
	ctrl_enter = (ENT_LOAD_EFER | ENT_GUEST_64);
	/* DIsable IO instruction VMEXIT now */
	ctrl_cpu[0] &= (~(CPU_IO | CPU_IO_BITMAP));
	ctrl_cpu[1] = 0;

	ctrl_pin = (ctrl_pin | ctrl_pin_rev.set) & ctrl_pin_rev.clr;
	ctrl_enter = (ctrl_enter | ctrl_enter_rev.set) & ctrl_enter_rev.clr;
	ctrl_exit = (ctrl_exit | ctrl_exit_rev.set) & ctrl_exit_rev.clr;
	ctrl_cpu[0] = (ctrl_cpu[0] | ctrl_cpu_rev[0].set) & ctrl_cpu_rev[0].clr;

	init_vmcs_ctrl();
	init_vmcs_host();
	init_vmcs_guest();
	return 0;
}

static void init_vmx(void)
{
	ulong fix_cr0_set, fix_cr0_clr;
	ulong fix_cr4_set, fix_cr4_clr;

	vmxon_region = alloc_page();
	memset(vmxon_region, 0, PAGE_SIZE);

	fix_cr0_set =  rdmsr(MSR_IA32_VMX_CR0_FIXED0);
	fix_cr0_clr =  rdmsr(MSR_IA32_VMX_CR0_FIXED1);
	fix_cr4_set =  rdmsr(MSR_IA32_VMX_CR4_FIXED0);
	fix_cr4_clr = rdmsr(MSR_IA32_VMX_CR4_FIXED1);
	basic.val = rdmsr(MSR_IA32_VMX_BASIC);
	ctrl_pin_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_PIN
			: MSR_IA32_VMX_PINBASED_CTLS);
	ctrl_exit_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_EXIT
			: MSR_IA32_VMX_EXIT_CTLS);
	ctrl_enter_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_ENTRY
			: MSR_IA32_VMX_ENTRY_CTLS);
	ctrl_cpu_rev[0].val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_PROC
			: MSR_IA32_VMX_PROCBASED_CTLS);
	if ((ctrl_cpu_rev[0].clr & CPU_SECONDARY) != 0)
		ctrl_cpu_rev[1].val = rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2);
	else
		ctrl_cpu_rev[1].val = 0;
	if ((ctrl_cpu_rev[1].clr & (CPU_EPT | CPU_VPID)) != 0)
		ept_vpid.val = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
	else
		ept_vpid.val = 0;

	write_cr0((read_cr0() & fix_cr0_clr) | fix_cr0_set);
	write_cr4((read_cr4() & fix_cr4_clr) | fix_cr4_set | X86_CR4_VMXE);

	*vmxon_region = basic.revision;

	guest_stack = alloc_page();
	memset(guest_stack, 0, PAGE_SIZE);
	guest_syscall_stack = alloc_page();
	memset(guest_syscall_stack, 0, PAGE_SIZE);
}

static void do_vmxon_off(void *data)
{
	vmx_on();
	vmx_off();
}

static void do_write_feature_control(void *data)
{
	wrmsr(MSR_IA32_FEATURE_CONTROL, 0);
}

static int test_vmx_feature_control(void)
{
	u64 ia32_feature_control;
	bool vmx_enabled;

	ia32_feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
	vmx_enabled = ((ia32_feature_control & 0x5) == 0x5);
	if ((ia32_feature_control & 0x5) == 0x5) {
		printf("VMX enabled and locked by BIOS\n");
		return 0;
	} else if (ia32_feature_control & 0x1) {
		printf("ERROR: VMX locked out by BIOS!?\n");
		return 1;
	}

	wrmsr(MSR_IA32_FEATURE_CONTROL, 0);
	report("test vmxon with FEATURE_CONTROL cleared",
	       test_for_exception(GP_VECTOR, &do_vmxon_off, NULL));

	wrmsr(MSR_IA32_FEATURE_CONTROL, 0x4);
	report("test vmxon without FEATURE_CONTROL lock",
	       test_for_exception(GP_VECTOR, &do_vmxon_off, NULL));

	wrmsr(MSR_IA32_FEATURE_CONTROL, 0x5);
	vmx_enabled = ((rdmsr(MSR_IA32_FEATURE_CONTROL) & 0x5) == 0x5);
	report("test enable VMX in FEATURE_CONTROL", vmx_enabled);

	report("test FEATURE_CONTROL lock bit",
	       test_for_exception(GP_VECTOR, &do_write_feature_control, NULL));

	return !vmx_enabled;
}

static int test_vmxon(void)
{
	int ret, ret1;
	u64 *tmp_region = vmxon_region;
	int width = cpuid_maxphyaddr();

	/* Unaligned page access */
	vmxon_region = (u64 *)((intptr_t)vmxon_region + 1);
	ret1 = vmx_on();
	report("test vmxon with unaligned vmxon region", ret1);
	if (!ret1) {
		ret = 1;
		goto out;
	}

	/* gpa bits beyond physical address width are set*/
	vmxon_region = (u64 *)((intptr_t)tmp_region | ((u64)1 << (width+1)));
	ret1 = vmx_on();
	report("test vmxon with bits set beyond physical address width", ret1);
	if (!ret1) {
		ret = 1;
		goto out;
	}

	/* invalid revision indentifier */
	vmxon_region = tmp_region;
	*vmxon_region = 0xba9da9;
	ret1 = vmx_on();
	report("test vmxon with invalid revision identifier", ret1);
	if (!ret1) {
		ret = 1;
		goto out;
	}

	/* and finally a valid region */
	*vmxon_region = basic.revision;
	ret = vmx_on();
	report("test vmxon with valid vmxon region", !ret);

out:
	return ret;
}

static void test_vmptrld(void)
{
	struct vmcs *vmcs, *tmp_root;
	int width = cpuid_maxphyaddr();

	vmcs = alloc_page();
	vmcs->revision_id = basic.revision;

	/* Unaligned page access */
	tmp_root = (struct vmcs *)((intptr_t)vmcs + 1);
	report("test vmptrld with unaligned vmcs",
	       make_vmcs_current(tmp_root) == 1);

	/* gpa bits beyond physical address width are set*/
	tmp_root = (struct vmcs *)((intptr_t)vmcs |
				   ((u64)1 << (width+1)));
	report("test vmptrld with vmcs address bits set beyond physical address width",
	       make_vmcs_current(tmp_root) == 1);

	/* Pass VMXON region */
	make_vmcs_current(vmcs);
	tmp_root = (struct vmcs *)vmxon_region;
	report("test vmptrld with vmxon region",
	       make_vmcs_current(tmp_root) == 1);
	report("test vmptrld with vmxon region vm-instruction error",
	       vmcs_read(VMX_INST_ERROR) == VMXERR_VMPTRLD_VMXON_POINTER);

	report("test vmptrld with valid vmcs region", make_vmcs_current(vmcs) == 0);
}

static void test_vmptrst(void)
{
	int ret;
	struct vmcs *vmcs1, *vmcs2;

	vmcs1 = alloc_page();
	memset(vmcs1, 0, PAGE_SIZE);
	init_vmcs(&vmcs1);
	ret = vmcs_save(&vmcs2);
	report("test vmptrst", (!ret) && (vmcs1 == vmcs2));
}

struct vmx_ctl_msr {
	const char *name;
	u32 index, true_index;
	u32 default1;
} vmx_ctl_msr[] = {
	{ "MSR_IA32_VMX_PINBASED_CTLS", MSR_IA32_VMX_PINBASED_CTLS,
	  MSR_IA32_VMX_TRUE_PIN, 0x16 },
	{ "MSR_IA32_VMX_PROCBASED_CTLS", MSR_IA32_VMX_PROCBASED_CTLS,
	  MSR_IA32_VMX_TRUE_PROC, 0x401e172 },
	{ "MSR_IA32_VMX_PROCBASED_CTLS2", MSR_IA32_VMX_PROCBASED_CTLS2,
	  MSR_IA32_VMX_PROCBASED_CTLS2, 0 },
	{ "MSR_IA32_VMX_EXIT_CTLS", MSR_IA32_VMX_EXIT_CTLS,
	  MSR_IA32_VMX_TRUE_EXIT, 0x36dff },
	{ "MSR_IA32_VMX_ENTRY_CTLS", MSR_IA32_VMX_ENTRY_CTLS,
	  MSR_IA32_VMX_TRUE_ENTRY, 0x11ff },
};

static void test_vmx_caps(void)
{
	u64 val, default1, fixed0, fixed1;
	union vmx_ctrl_msr ctrl, true_ctrl;
	unsigned int n;
	bool ok;

	printf("\nTest suite: VMX capability reporting\n");

	report("MSR_IA32_VMX_BASIC",
	       (basic.revision & (1ul << 31)) == 0 &&
	       basic.size > 0 && basic.size <= 4096 &&
	       (basic.type == 0 || basic.type == 6) &&
	       basic.reserved1 == 0 && basic.reserved2 == 0);

	val = rdmsr(MSR_IA32_VMX_MISC);
	report("MSR_IA32_VMX_MISC",
	       (!(ctrl_cpu_rev[1].clr & CPU_URG) || val & (1ul << 5)) &&
	       ((val >> 16) & 0x1ff) <= 256 &&
	       (val & 0xc0007e00) == 0);

	for (n = 0; n < ARRAY_SIZE(vmx_ctl_msr); n++) {
		ctrl.val = rdmsr(vmx_ctl_msr[n].index);
		default1 = vmx_ctl_msr[n].default1;
		ok = (ctrl.set & default1) == default1;
		ok = ok && (ctrl.set & ~ctrl.clr) == 0;
		if (ok && basic.ctrl) {
			true_ctrl.val = rdmsr(vmx_ctl_msr[n].true_index);
			ok = ctrl.clr == true_ctrl.clr;
			ok = ok && ctrl.set == (true_ctrl.set | default1);
		}
		report("%s", ok, vmx_ctl_msr[n].name);
	}

	fixed0 = rdmsr(MSR_IA32_VMX_CR0_FIXED0);
	fixed1 = rdmsr(MSR_IA32_VMX_CR0_FIXED1);
	report("MSR_IA32_VMX_IA32_VMX_CR0_FIXED0/1",
	       ((fixed0 ^ fixed1) & ~fixed1) == 0);

	fixed0 = rdmsr(MSR_IA32_VMX_CR4_FIXED0);
	fixed1 = rdmsr(MSR_IA32_VMX_CR4_FIXED1);
	report("MSR_IA32_VMX_IA32_VMX_CR4_FIXED0/1",
	       ((fixed0 ^ fixed1) & ~fixed1) == 0);

	val = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
	report("MSR_IA32_VMX_VMCS_ENUM",
	       (val & 0x3e) >= 0x2a &&
	       (val & 0xfffffffffffffc01Ull) == 0);

	val = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
	report("MSR_IA32_VMX_EPT_VPID_CAP",
	       (val & 0xfffff07ef98cbebeUll) == 0);
}

/* This function can only be called in guest */
static void __attribute__((__used__)) hypercall(u32 hypercall_no)
{
	u64 val = 0;
	val = (hypercall_no & HYPERCALL_MASK) | HYPERCALL_BIT;
	hypercall_field = val;
	asm volatile("vmcall\n\t");
}

static bool is_hypercall()
{
	ulong reason, hyper_bit;

	reason = vmcs_read(EXI_REASON) & 0xff;
	hyper_bit = hypercall_field & HYPERCALL_BIT;
	if (reason == VMX_VMCALL && hyper_bit)
		return true;
	return false;
}

static int handle_hypercall()
{
	ulong hypercall_no;

	hypercall_no = hypercall_field & HYPERCALL_MASK;
	hypercall_field = 0;
	switch (hypercall_no) {
	case HYPERCALL_VMEXIT:
		return VMX_TEST_VMEXIT;
	case HYPERCALL_VMABORT:
		return VMX_TEST_VMABORT;
	case HYPERCALL_VMSKIP:
		return VMX_TEST_VMSKIP;
	default:
		printf("ERROR : Invalid hypercall number : %ld\n", hypercall_no);
	}
	return VMX_TEST_EXIT;
}

static void continue_abort(void)
{
	assert(!in_guest);
	printf("Host was here when guest aborted:\n");
	dump_stack();
	longjmp(abort_target, 1);
	abort();
}

void __abort_test(void)
{
	if (in_guest)
		hypercall(HYPERCALL_VMABORT);
	else
		longjmp(abort_target, 1);
	abort();
}

static void continue_skip(void)
{
	assert(!in_guest);
	longjmp(abort_target, 1);
	abort();
}

void test_skip(const char *msg)
{
	printf("%s skipping test: %s\n", in_guest ? "Guest" : "Host", msg);
	if (in_guest)
		hypercall(HYPERCALL_VMABORT);
	else
		longjmp(abort_target, 1);
	abort();
}

static int exit_handler()
{
	int ret;

	current->exits++;
	regs.rflags = vmcs_read(GUEST_RFLAGS);
	if (is_hypercall())
		ret = handle_hypercall();
	else
		ret = current->exit_handler();
	vmcs_write(GUEST_RFLAGS, regs.rflags);

	return ret;
}

/*
 * Called if vmlaunch or vmresume fails.
 *	@early    - failure due to "VMX controls and host-state area" (26.2)
 *	@vmlaunch - was this a vmlaunch or vmresume
 *	@rflags   - host rflags
 */
static int
entry_failure_handler(struct vmentry_failure *failure)
{
	if (current->entry_failure_handler)
		return current->entry_failure_handler(failure);
	else
		return VMX_TEST_EXIT;
}

/*
 * Tries to enter the guest. Returns true iff entry succeeded. Otherwise,
 * populates @failure.
 */
static bool vmx_enter_guest(struct vmentry_failure *failure)
{
	failure->early = 0;

	in_guest = 1;
	asm volatile (
		"mov %[HOST_RSP], %%rdi\n\t"
		"vmwrite %%rsp, %%rdi\n\t"
		LOAD_GPR_C
		"cmpb $0, %[launched]\n\t"
		"jne 1f\n\t"
		"vmlaunch\n\t"
		"jmp 2f\n\t"
		"1: "
		"vmresume\n\t"
		"2: "
		SAVE_GPR_C
		"pushf\n\t"
		"pop %%rdi\n\t"
		"mov %%rdi, %[failure_flags]\n\t"
		"movl $1, %[failure_flags]\n\t"
		"jmp 3f\n\t"
		"vmx_return:\n\t"
		SAVE_GPR_C
		"3: \n\t"
		: [failure_early]"+m"(failure->early),
		  [failure_flags]"=m"(failure->flags)
		: [launched]"m"(launched), [HOST_RSP]"i"(HOST_RSP)
		: "rdi", "memory", "cc"
	);
	in_guest = 0;

	failure->vmlaunch = !launched;
	failure->instr = launched ? "vmresume" : "vmlaunch";

	return !failure->early && !(vmcs_read(EXI_REASON) & VMX_ENTRY_FAILURE);
}

static int vmx_run()
{
	while (1) {
		u32 ret;
		bool entered;
		struct vmentry_failure failure;

		entered = vmx_enter_guest(&failure);

		if (entered) {
			/*
			 * VMCS isn't in "launched" state if there's been any
			 * entry failure (early or otherwise).
			 */
			launched = 1;
			ret = exit_handler();
		} else {
			ret = entry_failure_handler(&failure);
		}

		switch (ret) {
		case VMX_TEST_RESUME:
			continue;
		case VMX_TEST_VMEXIT:
			guest_finished = 1;
			return 0;
		case VMX_TEST_EXIT:
			break;
		default:
			printf("ERROR : Invalid %s_handler return val %d.\n",
			       entered ? "exit" : "entry_failure",
			       ret);
			break;
		}

		if (entered)
			print_vmexit_info();
		else
			print_vmentry_failure_info(&failure);
		abort();
	}
}

static void run_teardown_step(struct test_teardown_step *step)
{
	step->func(step->data);
}

static int test_run(struct vmx_test *test)
{
	int r;

	/* Validate V2 interface. */
	if (test->v2) {
		int ret = 0;
		if (test->init || test->guest_main || test->exit_handler ||
		    test->syscall_handler) {
			report("V2 test cannot specify V1 callbacks.", 0);
			ret = 1;
		}
		if (ret)
			return ret;
	}

	if (test->name == NULL)
		test->name = "(no name)";
	if (vmx_on()) {
		printf("%s : vmxon failed.\n", __func__);
		return 1;
	}

	init_vmcs(&(test->vmcs));
	/* Directly call test->init is ok here, init_vmcs has done
	   vmcs init, vmclear and vmptrld*/
	if (test->init && test->init(test->vmcs) != VMX_TEST_START)
		goto out;
	teardown_count = 0;
	v2_guest_main = NULL;
	test->exits = 0;
	current = test;
	regs = test->guest_regs;
	vmcs_write(GUEST_RFLAGS, regs.rflags | 0x2);
	launched = 0;
	guest_finished = 0;
	printf("\nTest suite: %s\n", test->name);

	r = setjmp(abort_target);
	if (r) {
		assert(!in_guest);
		goto out;
	}


	if (test->v2)
		test->v2();
	else
		vmx_run();

	while (teardown_count > 0)
		run_teardown_step(&teardown_steps[--teardown_count]);

	if (launched && !guest_finished)
		report("Guest didn't run to completion.", 0);

out:
	if (vmx_off()) {
		printf("%s : vmxoff failed.\n", __func__);
		return 1;
	}
	return 0;
}

/*
 * Add a teardown step. Executed after the test's main function returns.
 * Teardown steps executed in reverse order.
 */
void test_add_teardown(test_teardown_func func, void *data)
{
	struct test_teardown_step *step;

	TEST_ASSERT_MSG(teardown_count < MAX_TEST_TEARDOWN_STEPS,
			"There are already %d teardown steps.",
			teardown_count);
	step = &teardown_steps[teardown_count++];
	step->func = func;
	step->data = data;
}

/*
 * Set the target of the first enter_guest call. Can only be called once per
 * test. Must be called before first enter_guest call.
 */
void test_set_guest(test_guest_func func)
{
	assert(current->v2);
	TEST_ASSERT_MSG(!v2_guest_main, "Already set guest func.");
	v2_guest_main = func;
}

/*
 * Enters the guest (or launches it for the first time). Error to call once the
 * guest has returned (i.e., run past the end of its guest() function). Also
 * aborts if guest entry fails.
 */
void enter_guest(void)
{
	struct vmentry_failure failure;

	TEST_ASSERT_MSG(v2_guest_main,
			"Never called test_set_guest_func!");

	TEST_ASSERT_MSG(!guest_finished,
			"Called enter_guest() after guest returned.");

	if (!vmx_enter_guest(&failure)) {
		print_vmentry_failure_info(&failure);
		abort();
	}

	launched = 1;

	if (is_hypercall()) {
		int ret;

		ret = handle_hypercall();
		switch (ret) {
		case VMX_TEST_VMEXIT:
			guest_finished = 1;
			break;
		case VMX_TEST_VMABORT:
			continue_abort();
			break;
		case VMX_TEST_VMSKIP:
			continue_skip();
			break;
		default:
			printf("ERROR : Invalid handle_hypercall return %d.\n",
			       ret);
			abort();
		}
	}
}

extern struct vmx_test vmx_tests[];

static bool
test_wanted(const char *name, const char *filters[], int filter_count)
{
	int i;
	bool positive = false;
	bool match = false;
	char clean_name[strlen(name) + 1];
	char *c;
	const char *n;

	/* Replace spaces with underscores. */
	n = name;
	c = &clean_name[0];
	do *c++ = (*n == ' ') ? '_' : *n;
	while (*n++);

	for (i = 0; i < filter_count; i++) {
		const char *filter = filters[i];

		if (filter[0] == '-') {
			if (simple_glob(clean_name, filter + 1))
				return false;
		} else {
			positive = true;
			match |= simple_glob(clean_name, filter);
		}
	}

	if (!positive || match) {
		matched++;
		return true;
	} else {
		return false;
	}
}

int main(int argc, const char *argv[])
{
	int i = 0;

	setup_vm();
	setup_idt();
	hypercall_field = 0;

	argv++;
	argc--;

	if (!(cpuid(1).c & (1 << 5))) {
		printf("WARNING: vmx not supported, add '-cpu host'\n");
		goto exit;
	}
	init_vmx();
	if (test_wanted("test_vmx_feature_control", argv, argc)) {
		/* Sets MSR_IA32_FEATURE_CONTROL to 0x5 */
		if (test_vmx_feature_control() != 0)
			goto exit;
	} else {
		if ((rdmsr(MSR_IA32_FEATURE_CONTROL) & 0x5) != 0x5)
			wrmsr(MSR_IA32_FEATURE_CONTROL, 0x5);
	}

	if (test_wanted("test_vmxon", argv, argc)) {
		/* Enables VMX */
		if (test_vmxon() != 0)
			goto exit;
	} else {
		if (vmx_on()) {
			report("vmxon", 0);
			goto exit;
		}
	}

	if (test_wanted("test_vmptrld", argv, argc))
		test_vmptrld();
	if (test_wanted("test_vmclear", argv, argc))
		test_vmclear();
	if (test_wanted("test_vmptrst", argv, argc))
		test_vmptrst();
	if (test_wanted("test_vmwrite_vmread", argv, argc))
		test_vmwrite_vmread();
	if (test_wanted("test_vmcs_lifecycle", argv, argc))
		test_vmcs_lifecycle();
	if (test_wanted("test_vmx_caps", argv, argc))
		test_vmx_caps();

	/* Balance vmxon from test_vmxon. */
	vmx_off();

	for (; vmx_tests[i].name != NULL; i++) {
		if (!test_wanted(vmx_tests[i].name, argv, argc))
			continue;
		if (test_run(&vmx_tests[i]))
			goto exit;
	}

	if (!matched)
		report("command line didn't match any tests!", matched);

exit:
	return report_summary();
}
                                                                                                                                                                                                                                                                                                            source/v64/tests/kvm-unit-tests/x86/vmx.h                                                           0000644 0000000 0000000 00000050041 00000000000 015350  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #ifndef __VMX_H
#define __VMX_H

#include "libcflat.h"
#include "processor.h"
#include "bitops.h"
#include "asm/page.h"
#include "asm/io.h"

struct vmcs {
	u32 revision_id; /* vmcs revision identifier */
	u32 abort; /* VMX-abort indicator */
	/* VMCS data */
	char data[0];
};

struct invvpid_operand {
	u64 vpid;
	u64 gla;
};

struct regs {
	u64 rax;
	u64 rcx;
	u64 rdx;
	u64 rbx;
	u64 cr2;
	u64 rbp;
	u64 rsi;
	u64 rdi;
	u64 r8;
	u64 r9;
	u64 r10;
	u64 r11;
	u64 r12;
	u64 r13;
	u64 r14;
	u64 r15;
	u64 rflags;
};

struct vmentry_failure {
	/* Did a vmlaunch or vmresume fail? */
	bool vmlaunch;
	/* Instruction mnemonic (for convenience). */
	const char *instr;
	/* Did the instruction return right away, or did we jump to HOST_RIP? */
	bool early;
	/* Contents of [re]flags after failed entry. */
	unsigned long flags;
};

struct vmx_test {
	const char *name;
	int (*init)(struct vmcs *vmcs);
	void (*guest_main)();
	int (*exit_handler)();
	void (*syscall_handler)(u64 syscall_no);
	struct regs guest_regs;
	int (*entry_failure_handler)(struct vmentry_failure *failure);
	struct vmcs *vmcs;
	int exits;
	/* Alternative test interface. */
	void (*v2)(void);
};

union vmx_basic {
	u64 val;
	struct {
		u32 revision;
		u32	size:13,
			reserved1: 3,
			width:1,
			dual:1,
			type:4,
			insouts:1,
			ctrl:1,
			reserved2:8;
	};
};

union vmx_ctrl_msr {
	u64 val;
	struct {
		u32 set, clr;
	};
};

union vmx_ept_vpid {
	u64 val;
	struct {
		u32:16,
			super:2,
			: 2,
			invept:1,
			: 11;
		u32	invvpid:1;
	};
};

enum Encoding {
	/* 16-Bit Control Fields */
	VPID			= 0x0000ul,
	/* Posted-interrupt notification vector */
	PINV			= 0x0002ul,
	/* EPTP index */
	EPTP_IDX		= 0x0004ul,

	/* 16-Bit Guest State Fields */
	GUEST_SEL_ES		= 0x0800ul,
	GUEST_SEL_CS		= 0x0802ul,
	GUEST_SEL_SS		= 0x0804ul,
	GUEST_SEL_DS		= 0x0806ul,
	GUEST_SEL_FS		= 0x0808ul,
	GUEST_SEL_GS		= 0x080aul,
	GUEST_SEL_LDTR		= 0x080cul,
	GUEST_SEL_TR		= 0x080eul,
	GUEST_INT_STATUS	= 0x0810ul,
	GUEST_PML_INDEX         = 0x0812ul,

	/* 16-Bit Host State Fields */
	HOST_SEL_ES		= 0x0c00ul,
	HOST_SEL_CS		= 0x0c02ul,
	HOST_SEL_SS		= 0x0c04ul,
	HOST_SEL_DS		= 0x0c06ul,
	HOST_SEL_FS		= 0x0c08ul,
	HOST_SEL_GS		= 0x0c0aul,
	HOST_SEL_TR		= 0x0c0cul,

	/* 64-Bit Control Fields */
	IO_BITMAP_A		= 0x2000ul,
	IO_BITMAP_B		= 0x2002ul,
	MSR_BITMAP		= 0x2004ul,
	EXIT_MSR_ST_ADDR	= 0x2006ul,
	EXIT_MSR_LD_ADDR	= 0x2008ul,
	ENTER_MSR_LD_ADDR	= 0x200aul,
	VMCS_EXEC_PTR		= 0x200cul,
	TSC_OFFSET		= 0x2010ul,
	TSC_OFFSET_HI		= 0x2011ul,
	APIC_VIRT_ADDR		= 0x2012ul,
	APIC_ACCS_ADDR		= 0x2014ul,
	EPTP			= 0x201aul,
	EPTP_HI			= 0x201bul,
	PMLADDR                 = 0x200eul,
	PMLADDR_HI              = 0x200ful,


	/* 64-Bit Readonly Data Field */
	INFO_PHYS_ADDR		= 0x2400ul,

	/* 64-Bit Guest State */
	VMCS_LINK_PTR		= 0x2800ul,
	VMCS_LINK_PTR_HI	= 0x2801ul,
	GUEST_DEBUGCTL		= 0x2802ul,
	GUEST_DEBUGCTL_HI	= 0x2803ul,
	GUEST_EFER		= 0x2806ul,
	GUEST_PAT		= 0x2804ul,
	GUEST_PERF_GLOBAL_CTRL	= 0x2808ul,
	GUEST_PDPTE		= 0x280aul,

	/* 64-Bit Host State */
	HOST_PAT		= 0x2c00ul,
	HOST_EFER		= 0x2c02ul,
	HOST_PERF_GLOBAL_CTRL	= 0x2c04ul,

	/* 32-Bit Control Fields */
	PIN_CONTROLS		= 0x4000ul,
	CPU_EXEC_CTRL0		= 0x4002ul,
	EXC_BITMAP		= 0x4004ul,
	PF_ERROR_MASK		= 0x4006ul,
	PF_ERROR_MATCH		= 0x4008ul,
	CR3_TARGET_COUNT	= 0x400aul,
	EXI_CONTROLS		= 0x400cul,
	EXI_MSR_ST_CNT		= 0x400eul,
	EXI_MSR_LD_CNT		= 0x4010ul,
	ENT_CONTROLS		= 0x4012ul,
	ENT_MSR_LD_CNT		= 0x4014ul,
	ENT_INTR_INFO		= 0x4016ul,
	ENT_INTR_ERROR		= 0x4018ul,
	ENT_INST_LEN		= 0x401aul,
	TPR_THRESHOLD		= 0x401cul,
	CPU_EXEC_CTRL1		= 0x401eul,

	/* 32-Bit R/O Data Fields */
	VMX_INST_ERROR		= 0x4400ul,
	EXI_REASON		= 0x4402ul,
	EXI_INTR_INFO		= 0x4404ul,
	EXI_INTR_ERROR		= 0x4406ul,
	IDT_VECT_INFO		= 0x4408ul,
	IDT_VECT_ERROR		= 0x440aul,
	EXI_INST_LEN		= 0x440cul,
	EXI_INST_INFO		= 0x440eul,

	/* 32-Bit Guest State Fields */
	GUEST_LIMIT_ES		= 0x4800ul,
	GUEST_LIMIT_CS		= 0x4802ul,
	GUEST_LIMIT_SS		= 0x4804ul,
	GUEST_LIMIT_DS		= 0x4806ul,
	GUEST_LIMIT_FS		= 0x4808ul,
	GUEST_LIMIT_GS		= 0x480aul,
	GUEST_LIMIT_LDTR	= 0x480cul,
	GUEST_LIMIT_TR		= 0x480eul,
	GUEST_LIMIT_GDTR	= 0x4810ul,
	GUEST_LIMIT_IDTR	= 0x4812ul,
	GUEST_AR_ES		= 0x4814ul,
	GUEST_AR_CS		= 0x4816ul,
	GUEST_AR_SS		= 0x4818ul,
	GUEST_AR_DS		= 0x481aul,
	GUEST_AR_FS		= 0x481cul,
	GUEST_AR_GS		= 0x481eul,
	GUEST_AR_LDTR		= 0x4820ul,
	GUEST_AR_TR		= 0x4822ul,
	GUEST_INTR_STATE	= 0x4824ul,
	GUEST_ACTV_STATE	= 0x4826ul,
	GUEST_SMBASE		= 0x4828ul,
	GUEST_SYSENTER_CS	= 0x482aul,
	PREEMPT_TIMER_VALUE	= 0x482eul,

	/* 32-Bit Host State Fields */
	HOST_SYSENTER_CS	= 0x4c00ul,

	/* Natural-Width Control Fields */
	CR0_MASK		= 0x6000ul,
	CR4_MASK		= 0x6002ul,
	CR0_READ_SHADOW		= 0x6004ul,
	CR4_READ_SHADOW		= 0x6006ul,
	CR3_TARGET_0		= 0x6008ul,
	CR3_TARGET_1		= 0x600aul,
	CR3_TARGET_2		= 0x600cul,
	CR3_TARGET_3		= 0x600eul,

	/* Natural-Width R/O Data Fields */
	EXI_QUALIFICATION	= 0x6400ul,
	IO_RCX			= 0x6402ul,
	IO_RSI			= 0x6404ul,
	IO_RDI			= 0x6406ul,
	IO_RIP			= 0x6408ul,
	GUEST_LINEAR_ADDRESS	= 0x640aul,

	/* Natural-Width Guest State Fields */
	GUEST_CR0		= 0x6800ul,
	GUEST_CR3		= 0x6802ul,
	GUEST_CR4		= 0x6804ul,
	GUEST_BASE_ES		= 0x6806ul,
	GUEST_BASE_CS		= 0x6808ul,
	GUEST_BASE_SS		= 0x680aul,
	GUEST_BASE_DS		= 0x680cul,
	GUEST_BASE_FS		= 0x680eul,
	GUEST_BASE_GS		= 0x6810ul,
	GUEST_BASE_LDTR		= 0x6812ul,
	GUEST_BASE_TR		= 0x6814ul,
	GUEST_BASE_GDTR		= 0x6816ul,
	GUEST_BASE_IDTR		= 0x6818ul,
	GUEST_DR7		= 0x681aul,
	GUEST_RSP		= 0x681cul,
	GUEST_RIP		= 0x681eul,
	GUEST_RFLAGS		= 0x6820ul,
	GUEST_PENDING_DEBUG	= 0x6822ul,
	GUEST_SYSENTER_ESP	= 0x6824ul,
	GUEST_SYSENTER_EIP	= 0x6826ul,

	/* Natural-Width Host State Fields */
	HOST_CR0		= 0x6c00ul,
	HOST_CR3		= 0x6c02ul,
	HOST_CR4		= 0x6c04ul,
	HOST_BASE_FS		= 0x6c06ul,
	HOST_BASE_GS		= 0x6c08ul,
	HOST_BASE_TR		= 0x6c0aul,
	HOST_BASE_GDTR		= 0x6c0cul,
	HOST_BASE_IDTR		= 0x6c0eul,
	HOST_SYSENTER_ESP	= 0x6c10ul,
	HOST_SYSENTER_EIP	= 0x6c12ul,
	HOST_RSP		= 0x6c14ul,
	HOST_RIP		= 0x6c16ul
};

#define VMX_ENTRY_FAILURE	(1ul << 31)
#define VMX_ENTRY_FLAGS		(X86_EFLAGS_CF | X86_EFLAGS_PF | X86_EFLAGS_AF | \
				 X86_EFLAGS_ZF | X86_EFLAGS_SF | X86_EFLAGS_OF)

enum Reason {
	VMX_EXC_NMI		= 0,
	VMX_EXTINT		= 1,
	VMX_TRIPLE_FAULT	= 2,
	VMX_INIT		= 3,
	VMX_SIPI		= 4,
	VMX_SMI_IO		= 5,
	VMX_SMI_OTHER		= 6,
	VMX_INTR_WINDOW		= 7,
	VMX_NMI_WINDOW		= 8,
	VMX_TASK_SWITCH		= 9,
	VMX_CPUID		= 10,
	VMX_GETSEC		= 11,
	VMX_HLT			= 12,
	VMX_INVD		= 13,
	VMX_INVLPG		= 14,
	VMX_RDPMC		= 15,
	VMX_RDTSC		= 16,
	VMX_RSM			= 17,
	VMX_VMCALL		= 18,
	VMX_VMCLEAR		= 19,
	VMX_VMLAUNCH		= 20,
	VMX_VMPTRLD		= 21,
	VMX_VMPTRST		= 22,
	VMX_VMREAD		= 23,
	VMX_VMRESUME		= 24,
	VMX_VMWRITE		= 25,
	VMX_VMXOFF		= 26,
	VMX_VMXON		= 27,
	VMX_CR			= 28,
	VMX_DR			= 29,
	VMX_IO			= 30,
	VMX_RDMSR		= 31,
	VMX_WRMSR		= 32,
	VMX_FAIL_STATE		= 33,
	VMX_FAIL_MSR		= 34,
	VMX_MWAIT		= 36,
	VMX_MTF			= 37,
	VMX_MONITOR		= 39,
	VMX_PAUSE		= 40,
	VMX_FAIL_MCHECK		= 41,
	VMX_TPR_THRESHOLD	= 43,
	VMX_APIC_ACCESS		= 44,
	VMX_GDTR_IDTR		= 46,
	VMX_LDTR_TR		= 47,
	VMX_EPT_VIOLATION	= 48,
	VMX_EPT_MISCONFIG	= 49,
	VMX_INVEPT		= 50,
	VMX_PREEMPT		= 52,
	VMX_INVVPID		= 53,
	VMX_WBINVD		= 54,
	VMX_XSETBV		= 55,
	VMX_APIC_WRITE		= 56,
	VMX_RDRAND		= 57,
	VMX_INVPCID		= 58,
	VMX_VMFUNC		= 59,
	VMX_RDSEED		= 61,
	VMX_PML_FULL		= 62,
	VMX_XSAVES		= 63,
	VMX_XRSTORS		= 64,
};

enum Ctrl_exi {
	EXI_SAVE_DBGCTLS	= 1UL << 2,
	EXI_HOST_64		= 1UL << 9,
	EXI_LOAD_PERF		= 1UL << 12,
	EXI_INTA		= 1UL << 15,
	EXI_SAVE_PAT		= 1UL << 18,
	EXI_LOAD_PAT		= 1UL << 19,
	EXI_SAVE_EFER		= 1UL << 20,
	EXI_LOAD_EFER		= 1UL << 21,
	EXI_SAVE_PREEMPT	= 1UL << 22,
};

enum Ctrl_ent {
	ENT_LOAD_DBGCTLS	= 1UL << 2,
	ENT_GUEST_64		= 1UL << 9,
	ENT_LOAD_PAT		= 1UL << 14,
	ENT_LOAD_EFER		= 1UL << 15,
};

enum Ctrl_pin {
	PIN_EXTINT		= 1ul << 0,
	PIN_NMI			= 1ul << 3,
	PIN_VIRT_NMI		= 1ul << 5,
	PIN_PREEMPT		= 1ul << 6,
};

enum Ctrl0 {
	CPU_INTR_WINDOW		= 1ul << 2,
	CPU_HLT			= 1ul << 7,
	CPU_INVLPG		= 1ul << 9,
	CPU_MWAIT		= 1ul << 10,
	CPU_RDPMC		= 1ul << 11,
	CPU_RDTSC		= 1ul << 12,
	CPU_CR3_LOAD		= 1ul << 15,
	CPU_CR3_STORE		= 1ul << 16,
	CPU_CR8_LOAD		= 1ul << 19,
	CPU_CR8_STORE		= 1ul << 20,
	CPU_TPR_SHADOW		= 1ul << 21,
	CPU_NMI_WINDOW		= 1ul << 22,
	CPU_IO			= 1ul << 24,
	CPU_IO_BITMAP		= 1ul << 25,
	CPU_MSR_BITMAP		= 1ul << 28,
	CPU_MONITOR		= 1ul << 29,
	CPU_PAUSE		= 1ul << 30,
	CPU_SECONDARY		= 1ul << 31,
};

enum Ctrl1 {
	CPU_EPT			= 1ul << 1,
	CPU_DESC_TABLE		= 1ul << 2,
	CPU_RDTSCP		= 1ul << 3,
	CPU_VPID		= 1ul << 5,
	CPU_URG			= 1ul << 7,
	CPU_WBINVD		= 1ul << 6,
	CPU_RDRAND		= 1ul << 11,
	CPU_PML                 = 1ul << 17,
};

enum Intr_type {
	VMX_INTR_TYPE_EXT_INTR = 0,
	VMX_INTR_TYPE_NMI_INTR = 2,
	VMX_INTR_TYPE_HARD_EXCEPTION = 3,
	VMX_INTR_TYPE_SOFT_INTR = 4,
	VMX_INTR_TYPE_SOFT_EXCEPTION = 6,
};

/*
 * Interruption-information format
 */
#define INTR_INFO_VECTOR_MASK           0xff            /* 7:0 */
#define INTR_INFO_INTR_TYPE_MASK        0x700           /* 10:8 */
#define INTR_INFO_DELIVER_CODE_MASK     0x800           /* 11 */
#define INTR_INFO_UNBLOCK_NMI_MASK      0x1000          /* 12 */
#define INTR_INFO_VALID_MASK            0x80000000      /* 31 */

#define INTR_INFO_INTR_TYPE_SHIFT       8

/*
 * VM-instruction error numbers
 */
enum vm_instruction_error_number {
	VMXERR_VMCALL_IN_VMX_ROOT_OPERATION = 1,
	VMXERR_VMCLEAR_INVALID_ADDRESS = 2,
	VMXERR_VMCLEAR_VMXON_POINTER = 3,
	VMXERR_VMLAUNCH_NONCLEAR_VMCS = 4,
	VMXERR_VMRESUME_NONLAUNCHED_VMCS = 5,
	VMXERR_VMRESUME_AFTER_VMXOFF = 6,
	VMXERR_ENTRY_INVALID_CONTROL_FIELD = 7,
	VMXERR_ENTRY_INVALID_HOST_STATE_FIELD = 8,
	VMXERR_VMPTRLD_INVALID_ADDRESS = 9,
	VMXERR_VMPTRLD_VMXON_POINTER = 10,
	VMXERR_VMPTRLD_INCORRECT_VMCS_REVISION_ID = 11,
	VMXERR_UNSUPPORTED_VMCS_COMPONENT = 12,
	VMXERR_VMWRITE_READ_ONLY_VMCS_COMPONENT = 13,
	VMXERR_VMXON_IN_VMX_ROOT_OPERATION = 15,
	VMXERR_ENTRY_INVALID_EXECUTIVE_VMCS_POINTER = 16,
	VMXERR_ENTRY_NONLAUNCHED_EXECUTIVE_VMCS = 17,
	VMXERR_ENTRY_EXECUTIVE_VMCS_POINTER_NOT_VMXON_POINTER = 18,
	VMXERR_VMCALL_NONCLEAR_VMCS = 19,
	VMXERR_VMCALL_INVALID_VM_EXIT_CONTROL_FIELDS = 20,
	VMXERR_VMCALL_INCORRECT_MSEG_REVISION_ID = 22,
	VMXERR_VMXOFF_UNDER_DUAL_MONITOR_TREATMENT_OF_SMIS_AND_SMM = 23,
	VMXERR_VMCALL_INVALID_SMM_MONITOR_FEATURES = 24,
	VMXERR_ENTRY_INVALID_VM_EXECUTION_CONTROL_FIELDS_IN_EXECUTIVE_VMCS = 25,
	VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS = 26,
	VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID = 28,
};

#define SAVE_GPR				\
	"xchg %rax, regs\n\t"			\
	"xchg %rbx, regs+0x8\n\t"		\
	"xchg %rcx, regs+0x10\n\t"		\
	"xchg %rdx, regs+0x18\n\t"		\
	"xchg %rbp, regs+0x28\n\t"		\
	"xchg %rsi, regs+0x30\n\t"		\
	"xchg %rdi, regs+0x38\n\t"		\
	"xchg %r8, regs+0x40\n\t"		\
	"xchg %r9, regs+0x48\n\t"		\
	"xchg %r10, regs+0x50\n\t"		\
	"xchg %r11, regs+0x58\n\t"		\
	"xchg %r12, regs+0x60\n\t"		\
	"xchg %r13, regs+0x68\n\t"		\
	"xchg %r14, regs+0x70\n\t"		\
	"xchg %r15, regs+0x78\n\t"

#define LOAD_GPR	SAVE_GPR

#define SAVE_GPR_C				\
	"xchg %%rax, regs\n\t"			\
	"xchg %%rbx, regs+0x8\n\t"		\
	"xchg %%rcx, regs+0x10\n\t"		\
	"xchg %%rdx, regs+0x18\n\t"		\
	"xchg %%rbp, regs+0x28\n\t"		\
	"xchg %%rsi, regs+0x30\n\t"		\
	"xchg %%rdi, regs+0x38\n\t"		\
	"xchg %%r8, regs+0x40\n\t"		\
	"xchg %%r9, regs+0x48\n\t"		\
	"xchg %%r10, regs+0x50\n\t"		\
	"xchg %%r11, regs+0x58\n\t"		\
	"xchg %%r12, regs+0x60\n\t"		\
	"xchg %%r13, regs+0x68\n\t"		\
	"xchg %%r14, regs+0x70\n\t"		\
	"xchg %%r15, regs+0x78\n\t"

#define LOAD_GPR_C	SAVE_GPR_C

#define VMX_IO_SIZE_MASK	0x7
#define _VMX_IO_BYTE		0
#define _VMX_IO_WORD		1
#define _VMX_IO_LONG		3
#define VMX_IO_DIRECTION_MASK	(1ul << 3)
#define VMX_IO_IN		(1ul << 3)
#define VMX_IO_OUT		0
#define VMX_IO_STRING		(1ul << 4)
#define VMX_IO_REP		(1ul << 5)
#define VMX_IO_OPRAND_IMM	(1ul << 6)
#define VMX_IO_PORT_MASK	0xFFFF0000
#define VMX_IO_PORT_SHIFT	16

#define VMX_TEST_START		0
#define VMX_TEST_VMEXIT		1
#define VMX_TEST_EXIT		2
#define VMX_TEST_RESUME		3
#define VMX_TEST_VMABORT	4
#define VMX_TEST_VMSKIP		5

#define HYPERCALL_BIT		(1ul << 12)
#define HYPERCALL_MASK		0xFFF
#define HYPERCALL_VMEXIT	0x1
#define HYPERCALL_VMABORT	0x2
#define HYPERCALL_VMSKIP	0x3

#define EPTP_PG_WALK_LEN_SHIFT	3ul
#define EPTP_AD_FLAG		(1ul << 6)

#define EPT_MEM_TYPE_UC		0ul
#define EPT_MEM_TYPE_WC		1ul
#define EPT_MEM_TYPE_WT		4ul
#define EPT_MEM_TYPE_WP		5ul
#define EPT_MEM_TYPE_WB		6ul

#define EPT_RA			1ul
#define EPT_WA			2ul
#define EPT_EA			4ul
#define EPT_PRESENT		(EPT_RA | EPT_WA | EPT_EA)
#define EPT_ACCESS_FLAG		(1ul << 8)
#define EPT_DIRTY_FLAG		(1ul << 9)
#define EPT_LARGE_PAGE		(1ul << 7)
#define EPT_MEM_TYPE_SHIFT	3ul
#define EPT_IGNORE_PAT		(1ul << 6)
#define EPT_SUPPRESS_VE		(1ull << 63)

#define EPT_CAP_WT		1ull
#define EPT_CAP_PWL4		(1ull << 6)
#define EPT_CAP_UC		(1ull << 8)
#define EPT_CAP_WB		(1ull << 14)
#define EPT_CAP_2M_PAGE		(1ull << 16)
#define EPT_CAP_1G_PAGE		(1ull << 17)
#define EPT_CAP_INVEPT		(1ull << 20)
#define EPT_CAP_INVEPT_SINGLE	(1ull << 25)
#define EPT_CAP_INVEPT_ALL	(1ull << 26)
#define EPT_CAP_AD_FLAG		(1ull << 21)
#define VPID_CAP_INVVPID	(1ull << 32)
#define VPID_CAP_INVVPID_ADDR   (1ull << 40)
#define VPID_CAP_INVVPID_CXTGLB (1ull << 41)
#define VPID_CAP_INVVPID_ALL    (1ull << 42)
#define VPID_CAP_INVVPID_CXTLOC	(1ull << 43)

#define PAGE_SIZE_2M		(512 * PAGE_SIZE)
#define PAGE_SIZE_1G		(512 * PAGE_SIZE_2M)
#define EPT_PAGE_LEVEL		4
#define EPT_PGDIR_WIDTH		9
#define EPT_PGDIR_MASK		511
#define EPT_PGDIR_ENTRIES	(1 << EPT_PGDIR_WIDTH)
#define EPT_LEVEL_SHIFT(level)	(((level)-1) * EPT_PGDIR_WIDTH + 12)
#define EPT_ADDR_MASK		GENMASK_ULL(51, 12)
#define PAGE_MASK_2M		(~(PAGE_SIZE_2M-1))

#define EPT_VLT_RD		1
#define EPT_VLT_WR		(1 << 1)
#define EPT_VLT_FETCH		(1 << 2)
#define EPT_VLT_PERM_RD		(1 << 3)
#define EPT_VLT_PERM_WR		(1 << 4)
#define EPT_VLT_PERM_EX		(1 << 5)
#define EPT_VLT_PERMS		(EPT_VLT_PERM_RD | EPT_VLT_PERM_WR | \
				 EPT_VLT_PERM_EX)
#define EPT_VLT_LADDR_VLD	(1 << 7)
#define EPT_VLT_PADDR		(1 << 8)

#define MAGIC_VAL_1		0x12345678ul
#define MAGIC_VAL_2		0x87654321ul
#define MAGIC_VAL_3		0xfffffffful
#define MAGIC_VAL_4		0xdeadbeeful

#define INVEPT_SINGLE		1
#define INVEPT_GLOBAL		2

#define INVVPID_ADDR            0
#define INVVPID_CONTEXT_GLOBAL	1
#define INVVPID_ALL		2
#define INVVPID_CONTEXT_LOCAL	3

#define ACTV_ACTIVE		0
#define ACTV_HLT		1

extern struct regs regs;

extern union vmx_basic basic;
extern union vmx_ctrl_msr ctrl_pin_rev;
extern union vmx_ctrl_msr ctrl_cpu_rev[2];
extern union vmx_ctrl_msr ctrl_exit_rev;
extern union vmx_ctrl_msr ctrl_enter_rev;
extern union vmx_ept_vpid  ept_vpid;

extern u64 *vmxon_region;

void vmx_set_test_stage(u32 s);
u32 vmx_get_test_stage(void);
void vmx_inc_test_stage(void);

static int vmx_on(void)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;
	asm volatile ("push %1; popf; vmxon %2; setbe %0\n\t"
		      : "=q" (ret) : "q" (rflags), "m" (vmxon_region) : "cc");
	return ret;
}

static int vmx_off(void)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	asm volatile("push %1; popf; vmxoff; setbe %0\n\t"
		     : "=q"(ret) : "q" (rflags) : "cc");
	return ret;
}

static inline int make_vmcs_current(struct vmcs *vmcs)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	asm volatile ("push %1; popf; vmptrld %2; setbe %0"
		      : "=q" (ret) : "q" (rflags), "m" (vmcs) : "cc");
	return ret;
}

static inline int vmcs_clear(struct vmcs *vmcs)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	asm volatile ("push %1; popf; vmclear %2; setbe %0"
		      : "=q" (ret) : "q" (rflags), "m" (vmcs) : "cc");
	return ret;
}

static inline u64 vmcs_read(enum Encoding enc)
{
	u64 val;
	asm volatile ("vmread %1, %0" : "=rm" (val) : "r" ((u64)enc) : "cc");
	return val;
}

static inline int vmcs_read_checking(enum Encoding enc, u64 *value)
{
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;
	u64 encoding = enc;
	u64 val;

	asm volatile ("shl $8, %%rax;"
		      "sahf;"
		      "vmread %[encoding], %[val];"
		      "lahf;"
		      "shr $8, %%rax"
		      : /* output */ [val]"=rm"(val), "+a"(rflags)
		      : /* input */ [encoding]"r"(encoding)
		      : /* clobber */ "cc");

	*value = val;
	return rflags & (X86_EFLAGS_CF | X86_EFLAGS_ZF);
}

static inline int vmcs_write(enum Encoding enc, u64 val)
{
	bool ret;
	asm volatile ("vmwrite %1, %2; setbe %0"
		: "=q"(ret) : "rm" (val), "r" ((u64)enc) : "cc");
	return ret;
}

static inline int vmcs_save(struct vmcs **vmcs)
{
	bool ret;
	unsigned long pa;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	asm volatile ("push %2; popf; vmptrst %1; setbe %0"
		      : "=q" (ret), "=m" (pa) : "r" (rflags) : "cc");
	*vmcs = (pa == -1ull) ? NULL : phys_to_virt(pa);
	return ret;
}

static inline bool invept(unsigned long type, u64 eptp)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	struct {
		u64 eptp, gpa;
	} operand = {eptp, 0};
	asm volatile("push %1; popf; invept %2, %3; setbe %0"
		     : "=q" (ret) : "r" (rflags), "m"(operand),"r"(type) : "cc");
	return ret;
}

static inline bool invvpid(unsigned long type, u64 vpid, u64 gla)
{
	bool ret;
	u64 rflags = read_rflags() | X86_EFLAGS_CF | X86_EFLAGS_ZF;

	struct invvpid_operand operand = {vpid, gla};
	asm volatile("push %1; popf; invvpid %2, %3; setbe %0"
		     : "=q" (ret) : "r" (rflags), "m"(operand),"r"(type) : "cc");
	return ret;
}

const char *exit_reason_description(u64 reason);
void print_vmexit_info();
void print_vmentry_failure_info(struct vmentry_failure *failure);
void ept_sync(int type, u64 eptp);
void vpid_sync(int type, u16 vpid);
void install_ept_entry(unsigned long *pml4, int pte_level,
		unsigned long guest_addr, unsigned long pte,
		unsigned long *pt_page);
void install_1g_ept(unsigned long *pml4, unsigned long phys,
		unsigned long guest_addr, u64 perm);
void install_2m_ept(unsigned long *pml4, unsigned long phys,
		unsigned long guest_addr, u64 perm);
void install_ept(unsigned long *pml4, unsigned long phys,
		unsigned long guest_addr, u64 perm);
void setup_ept_range(unsigned long *pml4, unsigned long start,
		     unsigned long len, int map_1g, int map_2m, u64 perm);
bool get_ept_pte(unsigned long *pml4, unsigned long guest_addr, int level,
		unsigned long *pte);
void set_ept_pte(unsigned long *pml4, unsigned long guest_addr,
		int level, u64 pte_val);
void check_ept_ad(unsigned long *pml4, u64 guest_cr3,
		  unsigned long guest_addr, int expected_gpa_ad,
		  int expected_pt_ad);
void clear_ept_ad(unsigned long *pml4, u64 guest_cr3,
		  unsigned long guest_addr);

bool ept_2m_supported(void);
bool ept_1g_supported(void);
bool ept_huge_pages_supported(int level);
bool ept_execute_only_supported(void);
bool ept_ad_bits_supported(void);

void enter_guest(void);

typedef void (*test_guest_func)(void);
typedef void (*test_teardown_func)(void *data);
void test_set_guest(test_guest_func func);
void test_add_teardown(test_teardown_func func, void *data);
void test_skip(const char *msg);

void __abort_test(void);

#define TEST_ASSERT(cond) \
do { \
	if (!(cond)) { \
		report("%s:%d: Assertion failed: %s", 0, \
		       __FILE__, __LINE__, #cond); \
		dump_stack(); \
		__abort_test(); \
	} \
	report_pass(); \
} while (0)

#define TEST_ASSERT_MSG(cond, fmt, args...) \
do { \
	if (!(cond)) { \
		report("%s:%d: Assertion failed: %s\n" fmt, 0, \
		       __FILE__, __LINE__, #cond, ##args); \
		dump_stack(); \
		__abort_test(); \
	} \
	report_pass(); \
} while (0)

#define __TEST_EQ(a, b, a_str, b_str, assertion, fmt, args...) \
do { \
	typeof(a) _a = a; \
	typeof(b) _b = b; \
	if (_a != _b) { \
		char _bin_a[BINSTR_SZ]; \
		char _bin_b[BINSTR_SZ]; \
		binstr(_a, _bin_a); \
		binstr(_b, _bin_b); \
		report("%s:%d: %s failed: (%s) == (%s)\n" \
		       "\tLHS: %#018lx - %s - %lu\n" \
		       "\tRHS: %#018lx - %s - %lu%s" fmt, 0, \
		       __FILE__, __LINE__, \
		       assertion ? "Assertion" : "Expectation", a_str, b_str, \
		       (unsigned long) _a, _bin_a, (unsigned long) _a, \
		       (unsigned long) _b, _bin_b, (unsigned long) _b, \
		       fmt[0] == '\0' ? "" : "\n", ## args); \
		dump_stack(); \
		if (assertion) \
			__abort_test(); \
	} \
	report_pass(); \
} while (0)

#define TEST_ASSERT_EQ(a, b) __TEST_EQ(a, b, #a, #b, 1, "")
#define TEST_ASSERT_EQ_MSG(a, b, fmt, args...) \
	__TEST_EQ(a, b, #a, #b, 1, fmt, ## args)
#define TEST_EXPECT_EQ(a, b) __TEST_EQ(a, b, #a, #b, 0, "")
#define TEST_EXPECT_EQ_MSG(a, b, fmt, args...) \
	__TEST_EQ(a, b, #a, #b, 0, fmt, ## args)

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/kvm-unit-tests/x86/vmx_tests.c                                                     0000644 0000000 0000000 00000264745 00000000000 016607  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * All test cases of nested virtualization should be in this file
 *
 * Author : Arthur Chunqi Li <yzt356@gmail.com>
 */
#include "vmx.h"
#include "msr.h"
#include "processor.h"
#include "vm.h"
#include "fwcfg.h"
#include "isr.h"
#include "desc.h"
#include "apic.h"
#include "types.h"

#define NONCANONICAL            0xaaaaaaaaaaaaaaaaull

#define VPID_CAP_INVVPID_TYPES_SHIFT 40

u64 ia32_pat;
u64 ia32_efer;
void *io_bitmap_a, *io_bitmap_b;
u16 ioport;

unsigned long *pml4;
u64 eptp;
void *data_page1, *data_page2;

void *pml_log;
#define PML_INDEX 512

static inline unsigned ffs(unsigned x)
{
	int pos = -1;

	__asm__ __volatile__("bsf %1, %%eax; cmovnz %%eax, %0"
			     : "+r"(pos) : "rm"(x) : "eax");
	return pos + 1;
}

static inline void vmcall()
{
	asm volatile("vmcall");
}

void basic_guest_main()
{
	report("Basic VMX test", 1);
}

int basic_exit_handler()
{
	report("Basic VMX test", 0);
	print_vmexit_info();
	return VMX_TEST_EXIT;
}

void vmenter_main()
{
	u64 rax;
	u64 rsp, resume_rsp;

	report("test vmlaunch", 1);

	asm volatile(
		"mov %%rsp, %0\n\t"
		"mov %3, %%rax\n\t"
		"vmcall\n\t"
		"mov %%rax, %1\n\t"
		"mov %%rsp, %2\n\t"
		: "=r"(rsp), "=r"(rax), "=r"(resume_rsp)
		: "g"(0xABCD));
	report("test vmresume", (rax == 0xFFFF) && (rsp == resume_rsp));
}

int vmenter_exit_handler()
{
	u64 guest_rip;
	ulong reason;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	switch (reason) {
	case VMX_VMCALL:
		if (regs.rax != 0xABCD) {
			report("test vmresume", 0);
			return VMX_TEST_VMEXIT;
		}
		regs.rax = 0xFFFF;
		vmcs_write(GUEST_RIP, guest_rip + 3);
		return VMX_TEST_RESUME;
	default:
		report("test vmresume", 0);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

u32 preempt_scale;
volatile unsigned long long tsc_val;
volatile u32 preempt_val;
u64 saved_rip;

int preemption_timer_init()
{
	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
		printf("\tPreemption timer is not supported\n");
		return VMX_TEST_EXIT;
	}
	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
	preempt_val = 10000000;
	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;

	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
		printf("\tSave preemption value is not supported\n");

	return VMX_TEST_START;
}

void preemption_timer_main()
{
	tsc_val = rdtsc();
	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
		vmx_set_test_stage(0);
		vmcall();
		if (vmx_get_test_stage() == 1)
			vmcall();
	}
	vmx_set_test_stage(1);
	while (vmx_get_test_stage() == 1) {
		if (((rdtsc() - tsc_val) >> preempt_scale)
				> 10 * preempt_val) {
			vmx_set_test_stage(2);
			vmcall();
		}
	}
	tsc_val = rdtsc();
	asm volatile ("hlt");
	vmcall();
	vmx_set_test_stage(5);
	vmcall();
}

int preemption_timer_exit_handler()
{
	bool guest_halted;
	u64 guest_rip;
	ulong reason;
	u32 insn_len;
	u32 ctrl_exit;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	insn_len = vmcs_read(EXI_INST_LEN);
	switch (reason) {
	case VMX_PREEMPT:
		switch (vmx_get_test_stage()) {
		case 1:
		case 2:
			report("busy-wait for preemption timer",
			       ((rdtsc() - tsc_val) >> preempt_scale) >=
			       preempt_val);
			vmx_set_test_stage(3);
			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
			return VMX_TEST_RESUME;
		case 3:
			guest_halted =
				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
			report("preemption timer during hlt",
			       ((rdtsc() - tsc_val) >> preempt_scale) >=
			       preempt_val && guest_halted);
			vmx_set_test_stage(4);
			vmcs_write(PIN_CONTROLS,
				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
			return VMX_TEST_RESUME;
		case 4:
			report("preemption timer with 0 value",
			       saved_rip == guest_rip);
			break;
		default:
			report("Invalid stage.", false);
			print_vmexit_info();
			break;
		}
		break;
	case VMX_VMCALL:
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		switch (vmx_get_test_stage()) {
		case 0:
			report("Keep preemption value",
			       vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val);
			vmx_set_test_stage(1);
			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
			vmcs_write(EXI_CONTROLS, ctrl_exit);
			return VMX_TEST_RESUME;
		case 1:
			report("Save preemption value",
			       vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val);
			return VMX_TEST_RESUME;
		case 2:
			report("busy-wait for preemption timer", 0);
			vmx_set_test_stage(3);
			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
			return VMX_TEST_RESUME;
		case 3:
			report("preemption timer during hlt", 0);
			vmx_set_test_stage(4);
			/* fall through */
		case 4:
			vmcs_write(PIN_CONTROLS,
				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
			vmcs_write(PREEMPT_TIMER_VALUE, 0);
			saved_rip = guest_rip + insn_len;
			return VMX_TEST_RESUME;
		case 5:
			report("preemption timer with 0 value (vmcall stage 5)", 0);
			break;
		default:
			// Should not reach here
			report("unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		break;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}
	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
	return VMX_TEST_VMEXIT;
}

void msr_bmp_init()
{
	void *msr_bitmap;
	u32 ctrl_cpu0;

	msr_bitmap = alloc_page();
	memset(msr_bitmap, 0x0, PAGE_SIZE);
	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
	ctrl_cpu0 |= CPU_MSR_BITMAP;
	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
}

static int test_ctrl_pat_init()
{
	u64 ctrl_ent;
	u64 ctrl_exi;

	msr_bmp_init();
	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
		printf("\tSave/load PAT is not supported\n");
		return 1;
	}

	ctrl_ent = vmcs_read(ENT_CONTROLS);
	ctrl_exi = vmcs_read(EXI_CONTROLS);
	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
	vmcs_write(ENT_CONTROLS, ctrl_ent);
	vmcs_write(EXI_CONTROLS, ctrl_exi);
	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
	vmcs_write(GUEST_PAT, 0x0);
	vmcs_write(HOST_PAT, ia32_pat);
	return VMX_TEST_START;
}

static void test_ctrl_pat_main()
{
	u64 guest_ia32_pat;

	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
		printf("\tENT_LOAD_PAT is not supported.\n");
	else {
		if (guest_ia32_pat != 0) {
			report("Entry load PAT", 0);
			return;
		}
	}
	wrmsr(MSR_IA32_CR_PAT, 0x6);
	vmcall();
	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
		report("Entry load PAT", guest_ia32_pat == ia32_pat);
}

static int test_ctrl_pat_exit_handler()
{
	u64 guest_rip;
	ulong reason;
	u64 guest_pat;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	switch (reason) {
	case VMX_VMCALL:
		guest_pat = vmcs_read(GUEST_PAT);
		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
			printf("\tEXI_SAVE_PAT is not supported\n");
			vmcs_write(GUEST_PAT, 0x6);
		} else {
			report("Exit save PAT", guest_pat == 0x6);
		}
		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
			printf("\tEXI_LOAD_PAT is not supported\n");
		else
			report("Exit load PAT", rdmsr(MSR_IA32_CR_PAT) == ia32_pat);
		vmcs_write(GUEST_PAT, ia32_pat);
		vmcs_write(GUEST_RIP, guest_rip + 3);
		return VMX_TEST_RESUME;
	default:
		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
		break;
	}
	return VMX_TEST_VMEXIT;
}

static int test_ctrl_efer_init()
{
	u64 ctrl_ent;
	u64 ctrl_exi;

	msr_bmp_init();
	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
	ia32_efer = rdmsr(MSR_EFER);
	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
	return VMX_TEST_START;
}

static void test_ctrl_efer_main()
{
	u64 guest_ia32_efer;

	guest_ia32_efer = rdmsr(MSR_EFER);
	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
		printf("\tENT_LOAD_EFER is not supported.\n");
	else {
		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
			report("Entry load EFER", 0);
			return;
		}
	}
	wrmsr(MSR_EFER, ia32_efer);
	vmcall();
	guest_ia32_efer = rdmsr(MSR_EFER);
	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
		report("Entry load EFER", guest_ia32_efer == ia32_efer);
}

static int test_ctrl_efer_exit_handler()
{
	u64 guest_rip;
	ulong reason;
	u64 guest_efer;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	switch (reason) {
	case VMX_VMCALL:
		guest_efer = vmcs_read(GUEST_EFER);
		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
			printf("\tEXI_SAVE_EFER is not supported\n");
			vmcs_write(GUEST_EFER, ia32_efer);
		} else {
			report("Exit save EFER", guest_efer == ia32_efer);
		}
		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
			printf("\tEXI_LOAD_EFER is not supported\n");
			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
		} else {
			report("Exit load EFER", rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX));
		}
		vmcs_write(GUEST_PAT, ia32_efer);
		vmcs_write(GUEST_RIP, guest_rip + 3);
		return VMX_TEST_RESUME;
	default:
		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
		break;
	}
	return VMX_TEST_VMEXIT;
}

u32 guest_cr0, guest_cr4;

static void cr_shadowing_main()
{
	u32 cr0, cr4, tmp;

	// Test read through
	vmx_set_test_stage(0);
	guest_cr0 = read_cr0();
	if (vmx_get_test_stage() == 1)
		report("Read through CR0", 0);
	else
		vmcall();
	vmx_set_test_stage(1);
	guest_cr4 = read_cr4();
	if (vmx_get_test_stage() == 2)
		report("Read through CR4", 0);
	else
		vmcall();
	// Test write through
	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
	vmx_set_test_stage(2);
	write_cr0(guest_cr0);
	if (vmx_get_test_stage() == 3)
		report("Write throuth CR0", 0);
	else
		vmcall();
	vmx_set_test_stage(3);
	write_cr4(guest_cr4);
	if (vmx_get_test_stage() == 4)
		report("Write through CR4", 0);
	else
		vmcall();
	// Test read shadow
	vmx_set_test_stage(4);
	vmcall();
	cr0 = read_cr0();
	if (vmx_get_test_stage() != 5)
		report("Read shadowing CR0", cr0 == guest_cr0);
	vmx_set_test_stage(5);
	cr4 = read_cr4();
	if (vmx_get_test_stage() != 6)
		report("Read shadowing CR4", cr4 == guest_cr4);
	// Test write shadow (same value with shadow)
	vmx_set_test_stage(6);
	write_cr0(guest_cr0);
	if (vmx_get_test_stage() == 7)
		report("Write shadowing CR0 (same value with shadow)", 0);
	else
		vmcall();
	vmx_set_test_stage(7);
	write_cr4(guest_cr4);
	if (vmx_get_test_stage() == 8)
		report("Write shadowing CR4 (same value with shadow)", 0);
	else
		vmcall();
	// Test write shadow (different value)
	vmx_set_test_stage(8);
	tmp = guest_cr0 ^ X86_CR0_TS;
	asm volatile("mov %0, %%rsi\n\t"
		"mov %%rsi, %%cr0\n\t"
		::"m"(tmp)
		:"rsi", "memory", "cc");
	report("Write shadowing different X86_CR0_TS", vmx_get_test_stage() == 9);
	vmx_set_test_stage(9);
	tmp = guest_cr0 ^ X86_CR0_MP;
	asm volatile("mov %0, %%rsi\n\t"
		"mov %%rsi, %%cr0\n\t"
		::"m"(tmp)
		:"rsi", "memory", "cc");
	report("Write shadowing different X86_CR0_MP", vmx_get_test_stage() == 10);
	vmx_set_test_stage(10);
	tmp = guest_cr4 ^ X86_CR4_TSD;
	asm volatile("mov %0, %%rsi\n\t"
		"mov %%rsi, %%cr4\n\t"
		::"m"(tmp)
		:"rsi", "memory", "cc");
	report("Write shadowing different X86_CR4_TSD", vmx_get_test_stage() == 11);
	vmx_set_test_stage(11);
	tmp = guest_cr4 ^ X86_CR4_DE;
	asm volatile("mov %0, %%rsi\n\t"
		"mov %%rsi, %%cr4\n\t"
		::"m"(tmp)
		:"rsi", "memory", "cc");
	report("Write shadowing different X86_CR4_DE", vmx_get_test_stage() == 12);
}

static int cr_shadowing_exit_handler()
{
	u64 guest_rip;
	ulong reason;
	u32 insn_len;
	u32 exit_qual;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	insn_len = vmcs_read(EXI_INST_LEN);
	exit_qual = vmcs_read(EXI_QUALIFICATION);
	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
			report("Read through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
			break;
		case 1:
			report("Read through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
			break;
		case 2:
			report("Write through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
			break;
		case 3:
			report("Write through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
			break;
		case 4:
			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
			break;
		case 6:
			report("Write shadowing CR0 (same value)",
					guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)));
			break;
		case 7:
			report("Write shadowing CR4 (same value)",
					guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)));
			break;
		default:
			// Should not reach here
			report("unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	case VMX_CR:
		switch (vmx_get_test_stage()) {
		case 4:
			report("Read shadowing CR0", 0);
			vmx_inc_test_stage();
			break;
		case 5:
			report("Read shadowing CR4", 0);
			vmx_inc_test_stage();
			break;
		case 6:
			report("Write shadowing CR0 (same value)", 0);
			vmx_inc_test_stage();
			break;
		case 7:
			report("Write shadowing CR4 (same value)", 0);
			vmx_inc_test_stage();
			break;
		case 8:
		case 9:
			// 0x600 encodes "mov %esi, %cr0"
			if (exit_qual == 0x600)
				vmx_inc_test_stage();
			break;
		case 10:
		case 11:
			// 0x604 encodes "mov %esi, %cr4"
			if (exit_qual == 0x604)
				vmx_inc_test_stage();
			break;
		default:
			// Should not reach here
			report("unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

static int iobmp_init()
{
	u32 ctrl_cpu0;

	io_bitmap_a = alloc_page();
	io_bitmap_b = alloc_page();
	memset(io_bitmap_a, 0x0, PAGE_SIZE);
	memset(io_bitmap_b, 0x0, PAGE_SIZE);
	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
	ctrl_cpu0 |= CPU_IO_BITMAP;
	ctrl_cpu0 &= (~CPU_IO);
	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
	return VMX_TEST_START;
}

static void iobmp_main()
{
	// stage 0, test IO pass
	vmx_set_test_stage(0);
	inb(0x5000);
	outb(0x0, 0x5000);
	report("I/O bitmap - I/O pass", vmx_get_test_stage() == 0);
	// test IO width, in/out
	((u8 *)io_bitmap_a)[0] = 0xFF;
	vmx_set_test_stage(2);
	inb(0x0);
	report("I/O bitmap - trap in", vmx_get_test_stage() == 3);
	vmx_set_test_stage(3);
	outw(0x0, 0x0);
	report("I/O bitmap - trap out", vmx_get_test_stage() == 4);
	vmx_set_test_stage(4);
	inl(0x0);
	report("I/O bitmap - I/O width, long", vmx_get_test_stage() == 5);
	// test low/high IO port
	vmx_set_test_stage(5);
	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
	inb(0x5000);
	report("I/O bitmap - I/O port, low part", vmx_get_test_stage() == 6);
	vmx_set_test_stage(6);
	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
	inb(0x9000);
	report("I/O bitmap - I/O port, high part", vmx_get_test_stage() == 7);
	// test partial pass
	vmx_set_test_stage(7);
	inl(0x4FFF);
	report("I/O bitmap - partial pass", vmx_get_test_stage() == 8);
	// test overrun
	vmx_set_test_stage(8);
	memset(io_bitmap_a, 0x0, PAGE_SIZE);
	memset(io_bitmap_b, 0x0, PAGE_SIZE);
	inl(0xFFFF);
	report("I/O bitmap - overrun", vmx_get_test_stage() == 9);
	vmx_set_test_stage(9);
	vmcall();
	outb(0x0, 0x0);
	report("I/O bitmap - ignore unconditional exiting",
	       vmx_get_test_stage() == 9);
	vmx_set_test_stage(10);
	vmcall();
	outb(0x0, 0x0);
	report("I/O bitmap - unconditional exiting",
	       vmx_get_test_stage() == 11);
}

static int iobmp_exit_handler()
{
	u64 guest_rip;
	ulong reason, exit_qual;
	u32 insn_len, ctrl_cpu0;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	exit_qual = vmcs_read(EXI_QUALIFICATION);
	insn_len = vmcs_read(EXI_INST_LEN);
	switch (reason) {
	case VMX_IO:
		switch (vmx_get_test_stage()) {
		case 0:
		case 1:
			vmx_inc_test_stage();
			break;
		case 2:
			report("I/O bitmap - I/O width, byte",
					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE);
			report("I/O bitmap - I/O direction, in", exit_qual & VMX_IO_IN);
			vmx_inc_test_stage();
			break;
		case 3:
			report("I/O bitmap - I/O width, word",
					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD);
			report("I/O bitmap - I/O direction, out",
					!(exit_qual & VMX_IO_IN));
			vmx_inc_test_stage();
			break;
		case 4:
			report("I/O bitmap - I/O width, long",
					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG);
			vmx_inc_test_stage();
			break;
		case 5:
			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
				vmx_inc_test_stage();
			break;
		case 6:
			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
				vmx_inc_test_stage();
			break;
		case 7:
			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
				vmx_inc_test_stage();
			break;
		case 8:
			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
				vmx_inc_test_stage();
			break;
		case 9:
		case 10:
			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
			vmx_inc_test_stage();
			break;
		default:
			// Should not reach here
			report("unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 9:
			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
			break;
		case 10:
			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
			break;
		default:
			// Should not reach here
			report("unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	default:
		printf("guest_rip = %#lx\n", guest_rip);
		printf("\tERROR : Undefined exit reason, reason = %ld.\n", reason);
		break;
	}
	return VMX_TEST_VMEXIT;
}

#define INSN_CPU0		0
#define INSN_CPU1		1
#define INSN_ALWAYS_TRAP	2

#define FIELD_EXIT_QUAL		(1 << 0)
#define FIELD_INSN_INFO		(1 << 1)

asm(
	"insn_hlt: hlt;ret\n\t"
	"insn_invlpg: invlpg 0x12345678;ret\n\t"
	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
	"insn_rdtsc: rdtsc;ret\n\t"
	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
#ifdef __x86_64__
	"insn_cr8_load: mov %rax,%cr8;ret\n\t"
	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
#endif
	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
	"insn_pause: pause;ret\n\t"
	"insn_wbinvd: wbinvd;ret\n\t"
	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
	"insn_invd: invd;ret\n\t"
	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
	"insn_sidt: sidt idt_descr;ret\n\t"
	"insn_lidt: lidt idt_descr;ret\n\t"
	"insn_sldt: sldt %ax;ret\n\t"
	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
	"insn_str: str %ax;ret\n\t"
);
extern void insn_hlt();
extern void insn_invlpg();
extern void insn_mwait();
extern void insn_rdpmc();
extern void insn_rdtsc();
extern void insn_cr3_load();
extern void insn_cr3_store();
#ifdef __x86_64__
extern void insn_cr8_load();
extern void insn_cr8_store();
#endif
extern void insn_monitor();
extern void insn_pause();
extern void insn_wbinvd();
extern void insn_sgdt();
extern void insn_lgdt();
extern void insn_sidt();
extern void insn_lidt();
extern void insn_sldt();
extern void insn_lldt();
extern void insn_str();
extern void insn_cpuid();
extern void insn_invd();

u32 cur_insn;
u64 cr3;

struct insn_table {
	const char *name;
	u32 flag;
	void (*insn_func)();
	u32 type;
	u32 reason;
	ulong exit_qual;
	u32 insn_info;
	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
	// which field need to be tested, reason is always tested
	u32 test_field;
};

/*
 * Add more test cases of instruction intercept here. Elements in this
 * table is:
 *	name/control flag/insn function/type/exit reason/exit qulification/
 *	instruction info/field to test
 * The last field defines which fields (exit_qual and insn_info) need to be
 * tested in exit handler. If set to 0, only "reason" is checked.
 */
static struct insn_table insn_table[] = {
	// Flags for Primary Processor-Based VM-Execution Controls
	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
		0x12345678, 0, FIELD_EXIT_QUAL},
	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0},
	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
		FIELD_EXIT_QUAL},
	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
		FIELD_EXIT_QUAL},
#ifdef __x86_64__
	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
		FIELD_EXIT_QUAL},
	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
		FIELD_EXIT_QUAL},
#endif
	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0},
	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
	// Flags for Secondary Processor-Based VM-Execution Controls
	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
	// Instructions always trap
	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
	// Instructions never trap
	{NULL},
};

static int insn_intercept_init()
{
	u32 ctrl_cpu;

	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
	ctrl_cpu &= ctrl_cpu_rev[0].clr;
	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
	cr3 = read_cr3();
	return VMX_TEST_START;
}

static void insn_intercept_main()
{
	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
		vmx_set_test_stage(cur_insn * 2);
		if ((insn_table[cur_insn].type == INSN_CPU0 &&
		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
		    (insn_table[cur_insn].type == INSN_CPU1 &&
		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
			       insn_table[cur_insn].type - INSN_CPU0,
			       insn_table[cur_insn].name);
			continue;
		}

		if ((insn_table[cur_insn].type == INSN_CPU0 &&
		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
		    (insn_table[cur_insn].type == INSN_CPU1 &&
		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
			/* skip hlt, it stalls the guest and is tested below */
			if (insn_table[cur_insn].insn_func != insn_hlt)
				insn_table[cur_insn].insn_func();
			report("execute %s", vmx_get_test_stage() == cur_insn * 2,
					insn_table[cur_insn].name);
		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
			       insn_table[cur_insn].type - INSN_CPU0,
			       insn_table[cur_insn].name);

		vmcall();

		insn_table[cur_insn].insn_func();
		report("intercept %s", vmx_get_test_stage() == cur_insn * 2 + 1,
				insn_table[cur_insn].name);

		vmx_set_test_stage(cur_insn * 2 + 1);
		vmcall();
	}
}

static int insn_intercept_exit_handler()
{
	u64 guest_rip;
	u32 reason;
	ulong exit_qual;
	u32 insn_len;
	u32 insn_info;
	bool pass;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	exit_qual = vmcs_read(EXI_QUALIFICATION);
	insn_len = vmcs_read(EXI_INST_LEN);
	insn_info = vmcs_read(EXI_INST_INFO);

	if (reason == VMX_VMCALL) {
		u32 val = 0;

		if (insn_table[cur_insn].type == INSN_CPU0)
			val = vmcs_read(CPU_EXEC_CTRL0);
		else if (insn_table[cur_insn].type == INSN_CPU1)
			val = vmcs_read(CPU_EXEC_CTRL1);

		if (vmx_get_test_stage() & 1)
			val &= ~insn_table[cur_insn].flag;
		else
			val |= insn_table[cur_insn].flag;

		if (insn_table[cur_insn].type == INSN_CPU0)
			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
		else if (insn_table[cur_insn].type == INSN_CPU1)
			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
	} else {
		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
			insn_table[cur_insn].reason == reason;
		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
		    insn_table[cur_insn].exit_qual != exit_qual)
			pass = false;
		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
		    insn_table[cur_insn].insn_info != insn_info)
			pass = false;
		if (pass)
			vmx_inc_test_stage();
	}
	vmcs_write(GUEST_RIP, guest_rip + insn_len);
	return VMX_TEST_RESUME;
}


/* Enables EPT and sets up the identity map. */
static int setup_ept(bool enable_ad)
{
	unsigned long end_of_memory;
	u32 ctrl_cpu[2];

	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
		printf("\tEPT is not supported");
		return 1;
	}


	if (!(ept_vpid.val & EPT_CAP_UC) &&
			!(ept_vpid.val & EPT_CAP_WB)) {
		printf("\tEPT paging-structure memory type "
				"UC&WB are not supported\n");
		return 1;
	}
	if (ept_vpid.val & EPT_CAP_UC)
		eptp = EPT_MEM_TYPE_UC;
	else
		eptp = EPT_MEM_TYPE_WB;
	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
		printf("\tPWL4 is not supported\n");
		return 1;
	}
	ctrl_cpu[0] = vmcs_read(CPU_EXEC_CTRL0);
	ctrl_cpu[1] = vmcs_read(CPU_EXEC_CTRL1);
	ctrl_cpu[0] = (ctrl_cpu[0] | CPU_SECONDARY)
		& ctrl_cpu_rev[0].clr;
	ctrl_cpu[1] = (ctrl_cpu[1] | CPU_EPT)
		& ctrl_cpu_rev[1].clr;
	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu[0]);
	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu[1]);
	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
	pml4 = alloc_page();
	memset(pml4, 0, PAGE_SIZE);
	eptp |= virt_to_phys(pml4);
	if (enable_ad)
		eptp |= EPTP_AD_FLAG;
	vmcs_write(EPTP, eptp);
	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
	if (end_of_memory < (1ul << 32))
		end_of_memory = (1ul << 32);
	/* Cannot use large EPT pages if we need to track EPT
	 * accessed/dirty bits at 4K granularity.
	 */
	setup_ept_range(pml4, 0, end_of_memory, 0,
			!enable_ad && ept_2m_supported(),
			EPT_WA | EPT_RA | EPT_EA);
	return 0;
}

static void ept_enable_ad_bits(void)
{
	eptp |= EPTP_AD_FLAG;
	vmcs_write(EPTP, eptp);
}

static void ept_disable_ad_bits(void)
{
	eptp &= ~EPTP_AD_FLAG;
	vmcs_write(EPTP, eptp);
}

static void ept_enable_ad_bits_or_skip_test(void)
{
	if (!ept_ad_bits_supported())
		test_skip("EPT AD bits not supported.");
	ept_enable_ad_bits();
}

static int apic_version;

static int ept_init_common(bool have_ad)
{
	if (setup_ept(have_ad))
		return VMX_TEST_EXIT;
	data_page1 = alloc_page();
	data_page2 = alloc_page();
	memset(data_page1, 0x0, PAGE_SIZE);
	memset(data_page2, 0x0, PAGE_SIZE);
	*((u32 *)data_page1) = MAGIC_VAL_1;
	*((u32 *)data_page2) = MAGIC_VAL_2;
	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
			EPT_RA | EPT_WA | EPT_EA);

	apic_version = apic_read(APIC_LVR);
	return VMX_TEST_START;
}

static int ept_init()
{
	return ept_init_common(false);
}

static void ept_common()
{
	vmx_set_test_stage(0);
	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
			*((u32 *)data_page1) != MAGIC_VAL_1)
		report("EPT basic framework - read", 0);
	else {
		*((u32 *)data_page2) = MAGIC_VAL_3;
		vmcall();
		if (vmx_get_test_stage() == 1) {
			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
					*((u32 *)data_page2) == MAGIC_VAL_2)
				report("EPT basic framework", 1);
			else
				report("EPT basic framework - remap", 1);
		}
	}
	// Test EPT Misconfigurations
	vmx_set_test_stage(1);
	vmcall();
	*((u32 *)data_page1) = MAGIC_VAL_1;
	if (vmx_get_test_stage() != 2) {
		report("EPT misconfigurations", 0);
		goto t1;
	}
	vmx_set_test_stage(2);
	vmcall();
	*((u32 *)data_page1) = MAGIC_VAL_1;
	report("EPT misconfigurations", vmx_get_test_stage() == 3);
t1:
	// Test EPT violation
	vmx_set_test_stage(3);
	vmcall();
	*((u32 *)data_page1) = MAGIC_VAL_1;
	report("EPT violation - page permission", vmx_get_test_stage() == 4);
	// Violation caused by EPT paging structure
	vmx_set_test_stage(4);
	vmcall();
	*((u32 *)data_page1) = MAGIC_VAL_2;
	report("EPT violation - paging structure", vmx_get_test_stage() == 5);
}

static void ept_main()
{
	ept_common();

	// Test EPT access to L1 MMIO
	vmx_set_test_stage(6);
	report("EPT - MMIO access", *((u32 *)0xfee00030UL) == apic_version);

	// Test invalid operand for INVEPT
	vmcall();
	report("EPT - unsupported INVEPT", vmx_get_test_stage() == 7);
}

bool invept_test(int type, u64 eptp)
{
	bool ret, supported;

	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
	ret = invept(type, eptp);

	if (ret == !supported)
		return false;

	if (!supported)
		printf("WARNING: unsupported invept passed!\n");
	else
		printf("WARNING: invept failed!\n");

	return true;
}

static int pml_exit_handler(void)
{
	u16 index, count;
	ulong reason = vmcs_read(EXI_REASON) & 0xff;
	u64 *pmlbuf = pml_log;
	u64 guest_rip = vmcs_read(GUEST_RIP);;
	u64 guest_cr3 = vmcs_read(GUEST_CR3);
	u32 insn_len = vmcs_read(EXI_INST_LEN);

	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
			index = vmcs_read(GUEST_PML_INDEX);
			for (count = index + 1; count < PML_INDEX; count++) {
				if (pmlbuf[count] == (u64)data_page2) {
					vmx_inc_test_stage();
					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
					break;
				}
			}
			break;
		case 1:
			index = vmcs_read(GUEST_PML_INDEX);
			/* Keep clearing the dirty bit till a overflow */
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
			break;
		default:
			report("unexpected stage, %d.", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	case VMX_PML_FULL:
		vmx_inc_test_stage();
		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

static int ept_exit_handler_common(bool have_ad)
{
	u64 guest_rip;
	u64 guest_cr3;
	ulong reason;
	u32 insn_len;
	u32 exit_qual;
	static unsigned long data_page1_pte, data_page1_pte_pte;

	guest_rip = vmcs_read(GUEST_RIP);
	guest_cr3 = vmcs_read(GUEST_CR3);
	reason = vmcs_read(EXI_REASON) & 0xff;
	insn_len = vmcs_read(EXI_INST_LEN);
	exit_qual = vmcs_read(EXI_QUALIFICATION);
	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
			check_ept_ad(pml4, guest_cr3,
				     (unsigned long)data_page1,
				     have_ad ? EPT_ACCESS_FLAG : 0,
				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
			check_ept_ad(pml4, guest_cr3,
				     (unsigned long)data_page2,
				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
			if (have_ad)
				ept_sync(INVEPT_SINGLE, eptp);;
			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
					*((u32 *)data_page2) == MAGIC_VAL_2) {
				vmx_inc_test_stage();
				install_ept(pml4, (unsigned long)data_page2,
						(unsigned long)data_page2,
						EPT_RA | EPT_WA | EPT_EA);
			} else
				report("EPT basic framework - write", 0);
			break;
		case 1:
			install_ept(pml4, (unsigned long)data_page1,
 				(unsigned long)data_page1, EPT_WA);
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		case 2:
			install_ept(pml4, (unsigned long)data_page1,
 				(unsigned long)data_page1,
 				EPT_RA | EPT_WA | EPT_EA |
 				(2 << EPT_MEM_TYPE_SHIFT));
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		case 3:
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
						1, &data_page1_pte));
			set_ept_pte(pml4, (unsigned long)data_page1, 
				1, data_page1_pte & ~EPT_PRESENT);
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		case 4:
			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
						2, &data_page1_pte));
			data_page1_pte &= PAGE_MASK;
			TEST_ASSERT(get_ept_pte(pml4, data_page1_pte,
						2, &data_page1_pte_pte));
			set_ept_pte(pml4, data_page1_pte, 2,
				data_page1_pte_pte & ~EPT_PRESENT);
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		case 6:
			if (!invept_test(0, eptp))
				vmx_inc_test_stage();
			break;
		// Should not reach here
		default:
			report("ERROR - unexpected stage, %d.", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	case VMX_EPT_MISCONFIG:
		switch (vmx_get_test_stage()) {
		case 1:
		case 2:
			vmx_inc_test_stage();
			install_ept(pml4, (unsigned long)data_page1,
 				(unsigned long)data_page1,
 				EPT_RA | EPT_WA | EPT_EA);
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		// Should not reach here
		default:
			report("ERROR - unexpected stage, %d.", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		return VMX_TEST_RESUME;
	case VMX_EPT_VIOLATION:
		switch(vmx_get_test_stage()) {
		case 3:
			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
					EPT_VLT_PADDR))
				vmx_inc_test_stage();
			set_ept_pte(pml4, (unsigned long)data_page1,
				1, data_page1_pte | (EPT_PRESENT));
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		case 4:
			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
			if (exit_qual == (EPT_VLT_RD |
					  (have_ad ? EPT_VLT_WR : 0) |
					  EPT_VLT_LADDR_VLD))
				vmx_inc_test_stage();
			set_ept_pte(pml4, data_page1_pte, 2,
				data_page1_pte_pte | (EPT_PRESENT));
			ept_sync(INVEPT_SINGLE, eptp);
			break;
		default:
			// Should not reach here
			report("ERROR : unexpected stage, %d", false,
			       vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

static int ept_exit_handler()
{
	return ept_exit_handler_common(false);
}

static int eptad_init()
{
	int r = ept_init_common(true);

	if (r == VMX_TEST_EXIT)
		return r;

	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
		printf("\tEPT A/D bits are not supported");
		return VMX_TEST_EXIT;
	}

	return r;
}

static int pml_init()
{
	u32 ctrl_cpu;
	int r = eptad_init();

	if (r == VMX_TEST_EXIT)
		return r;

	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
		printf("\tPML is not supported");
		return VMX_TEST_EXIT;
	}

	pml_log = alloc_page();
	memset(pml_log, 0x0, PAGE_SIZE);
	vmcs_write(PMLADDR, (u64)pml_log);
	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);

	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);

	return VMX_TEST_START;
}

static void pml_main()
{
	int count = 0;

	vmx_set_test_stage(0);
	*((u32 *)data_page2) = 0x1;
	vmcall();
	report("PML - Dirty GPA Logging", vmx_get_test_stage() == 1);

	while (vmx_get_test_stage() == 1) {
		vmcall();
		*((u32 *)data_page2) = 0x1;
		if (count++ > PML_INDEX)
			break;
	}
	report("PML Full Event", vmx_get_test_stage() == 2);
}

static void eptad_main()
{
	ept_common();
}

static int eptad_exit_handler()
{
	return ept_exit_handler_common(true);
}

bool invvpid_test(int type, u16 vpid)
{
	bool ret, supported;

	supported = ept_vpid.val &
		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
	ret = invvpid(type, vpid, 0);

	if (ret == !supported)
		return false;

	if (!supported)
		printf("WARNING: unsupported invvpid passed!\n");
	else
		printf("WARNING: invvpid failed!\n");

	return true;
}

static int vpid_init()
{
	u32 ctrl_cpu1;

	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
		printf("\tVPID is not supported");
		return VMX_TEST_EXIT;
	}

	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
	ctrl_cpu1 |= CPU_VPID;
	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
	return VMX_TEST_START;
}

static void vpid_main()
{
	vmx_set_test_stage(0);
	vmcall();
	report("INVVPID SINGLE ADDRESS", vmx_get_test_stage() == 1);
	vmx_set_test_stage(2);
	vmcall();
	report("INVVPID SINGLE", vmx_get_test_stage() == 3);
	vmx_set_test_stage(4);
	vmcall();
	report("INVVPID ALL", vmx_get_test_stage() == 5);
}

static int vpid_exit_handler()
{
	u64 guest_rip;
	ulong reason;
	u32 insn_len;

	guest_rip = vmcs_read(GUEST_RIP);
	reason = vmcs_read(EXI_REASON) & 0xff;
	insn_len = vmcs_read(EXI_INST_LEN);

	switch (reason) {
	case VMX_VMCALL:
		switch(vmx_get_test_stage()) {
		case 0:
			if (!invvpid_test(INVVPID_ADDR, 1))
				vmx_inc_test_stage();
			break;
		case 2:
			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
				vmx_inc_test_stage();
			break;
		case 4:
			if (!invvpid_test(INVVPID_ALL, 1))
				vmx_inc_test_stage();
			break;
		default:
			report("ERROR: unexpected stage, %d", false,
					vmx_get_test_stage());
			print_vmexit_info();
			return VMX_TEST_VMEXIT;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

#define TIMER_VECTOR	222

static volatile bool timer_fired;

static void timer_isr(isr_regs_t *regs)
{
	timer_fired = true;
	apic_write(APIC_EOI, 0);
}

static int interrupt_init(struct vmcs *vmcs)
{
	msr_bmp_init();
	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
	handle_irq(TIMER_VECTOR, timer_isr);
	return VMX_TEST_START;
}

static void interrupt_main(void)
{
	long long start, loops;

	vmx_set_test_stage(0);

	apic_write(APIC_LVTT, TIMER_VECTOR);
	irq_enable();

	apic_write(APIC_TMICT, 1);
	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
		asm volatile ("nop");
	report("direct interrupt while running guest", timer_fired);

	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmcall();
	timer_fired = false;
	apic_write(APIC_TMICT, 1);
	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
		asm volatile ("nop");
	report("intercepted interrupt while running guest", timer_fired);

	irq_enable();
	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmcall();
	timer_fired = false;
	start = rdtsc();
	apic_write(APIC_TMICT, 1000000);

	asm volatile ("sti; hlt");

	report("direct interrupt + hlt",
	       rdtsc() - start > 1000000 && timer_fired);

	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmcall();
	timer_fired = false;
	start = rdtsc();
	apic_write(APIC_TMICT, 1000000);

	asm volatile ("sti; hlt");

	report("intercepted interrupt + hlt",
	       rdtsc() - start > 10000 && timer_fired);

	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmcall();
	timer_fired = false;
	start = rdtsc();
	apic_write(APIC_TMICT, 1000000);

	irq_enable();
	asm volatile ("nop");
	vmcall();

	report("direct interrupt + activity state hlt",
	       rdtsc() - start > 10000 && timer_fired);

	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmcall();
	timer_fired = false;
	start = rdtsc();
	apic_write(APIC_TMICT, 1000000);

	irq_enable();
	asm volatile ("nop");
	vmcall();

	report("intercepted interrupt + activity state hlt",
	       rdtsc() - start > 10000 && timer_fired);

	apic_write(APIC_TMICT, 0);
	irq_disable();
	vmx_set_test_stage(7);
	vmcall();
	timer_fired = false;
	apic_write(APIC_TMICT, 1);
	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
		asm volatile ("nop");
	report("running a guest with interrupt acknowledgement set", timer_fired);
}

static int interrupt_exit_handler(void)
{
	u64 guest_rip = vmcs_read(GUEST_RIP);
	ulong reason = vmcs_read(EXI_REASON) & 0xff;
	u32 insn_len = vmcs_read(EXI_INST_LEN);

	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
		case 2:
		case 5:
			vmcs_write(PIN_CONTROLS,
				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
			break;
		case 7:
			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
			vmcs_write(PIN_CONTROLS,
				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
			break;
		case 1:
		case 3:
			vmcs_write(PIN_CONTROLS,
				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
			break;
		case 4:
		case 6:
			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
			break;
		}
		vmx_inc_test_stage();
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	case VMX_EXTINT:
		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
			handle_external_interrupt(vector);
		} else {
			irq_enable();
			asm volatile ("nop");
			irq_disable();
		}
		if (vmx_get_test_stage() >= 2)
			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}

	return VMX_TEST_VMEXIT;
}

static int dbgctls_init(struct vmcs *vmcs)
{
	u64 dr7 = 0x402;
	u64 zero = 0;

	msr_bmp_init();
	asm volatile(
		"mov %0,%%dr0\n\t"
		"mov %0,%%dr1\n\t"
		"mov %0,%%dr2\n\t"
		"mov %1,%%dr7\n\t"
		: : "r" (zero), "r" (dr7));
	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
	vmcs_write(GUEST_DR7, 0x404);
	vmcs_write(GUEST_DEBUGCTL, 0x2);

	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);

	return VMX_TEST_START;
}

static void dbgctls_main(void)
{
	u64 dr7, debugctl;

	asm volatile("mov %%dr7,%0" : "=r" (dr7));
	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
	/* Commented out: KVM does not support DEBUGCTL so far */
	(void)debugctl;
	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);

	dr7 = 0x408;
	asm volatile("mov %0,%%dr7" : : "r" (dr7));
	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);

	vmx_set_test_stage(0);
	vmcall();
	report("Save debug controls", vmx_get_test_stage() == 1);

	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
		printf("\tDebug controls are always loaded/saved\n");
		return;
	}
	vmx_set_test_stage(2);
	vmcall();

	asm volatile("mov %%dr7,%0" : "=r" (dr7));
	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
	/* Commented out: KVM does not support DEBUGCTL so far */
	(void)debugctl;
	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);

	dr7 = 0x408;
	asm volatile("mov %0,%%dr7" : : "r" (dr7));
	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);

	vmx_set_test_stage(3);
	vmcall();
	report("Don't save debug controls", vmx_get_test_stage() == 4);
}

static int dbgctls_exit_handler(void)
{
	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
	u32 insn_len = vmcs_read(EXI_INST_LEN);
	u64 guest_rip = vmcs_read(GUEST_RIP);
	u64 dr7, debugctl;

	asm volatile("mov %%dr7,%0" : "=r" (dr7));
	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);

	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
			if (dr7 == 0x400 && debugctl == 0 &&
			    vmcs_read(GUEST_DR7) == 0x408 /* &&
			    Commented out: KVM does not support DEBUGCTL so far
			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
				vmx_inc_test_stage();
			break;
		case 2:
			dr7 = 0x402;
			asm volatile("mov %0,%%dr7" : : "r" (dr7));
			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
			vmcs_write(GUEST_DR7, 0x404);
			vmcs_write(GUEST_DEBUGCTL, 0x2);

			vmcs_write(ENT_CONTROLS,
				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
			vmcs_write(EXI_CONTROLS,
				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
			break;
		case 3:
			if (dr7 == 0x400 && debugctl == 0 &&
			    vmcs_read(GUEST_DR7) == 0x404 /* &&
			    Commented out: KVM does not support DEBUGCTL so far
			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
				vmx_inc_test_stage();
			break;
		}
		vmcs_write(GUEST_RIP, guest_rip + insn_len);
		return VMX_TEST_RESUME;
	default:
		report("Unknown exit reason, %d", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

struct vmx_msr_entry {
	u32 index;
	u32 reserved;
	u64 value;
} __attribute__((packed));

#define MSR_MAGIC 0x31415926
struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;

static int msr_switch_init(struct vmcs *vmcs)
{
	msr_bmp_init();
	exit_msr_store = alloc_page();
	exit_msr_load = alloc_page();
	entry_msr_load = alloc_page();
	memset(exit_msr_store, 0, PAGE_SIZE);
	memset(exit_msr_load, 0, PAGE_SIZE);
	memset(entry_msr_load, 0, PAGE_SIZE);
	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
	entry_msr_load[0].value = MSR_MAGIC;

	vmx_set_test_stage(1);
	vmcs_write(ENT_MSR_LD_CNT, 1);
	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
	vmcs_write(EXI_MSR_ST_CNT, 1);
	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
	vmcs_write(EXI_MSR_LD_CNT, 1);
	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
	return VMX_TEST_START;
}

static void msr_switch_main()
{
	if (vmx_get_test_stage() == 1) {
		report("VM entry MSR load",
			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
		vmx_set_test_stage(2);
		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
		exit_msr_load[0].value = MSR_MAGIC + 2;
	}
	vmcall();
}

static int msr_switch_exit_handler()
{
	ulong reason;

	reason = vmcs_read(EXI_REASON);
	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
		report("VM exit MSR store",
			exit_msr_store[0].value == MSR_MAGIC + 1);
		report("VM exit MSR load",
			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
		vmx_set_test_stage(3);
		entry_msr_load[0].index = MSR_FS_BASE;
		return VMX_TEST_RESUME;
	}
	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
		__func__, vmx_get_test_stage(), reason);
	return VMX_TEST_EXIT;
}

static int msr_switch_entry_failure(struct vmentry_failure *failure)
{
	ulong reason;

	if (failure->early) {
		printf("ERROR %s: early exit\n", __func__);
		return VMX_TEST_EXIT;
	}

	reason = vmcs_read(EXI_REASON);
	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
	    vmx_get_test_stage() == 3) {
		report("VM entry MSR load: try to load FS_BASE",
			vmcs_read(EXI_QUALIFICATION) == 1);
		return VMX_TEST_VMEXIT;
	}
	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
		__func__, vmx_get_test_stage(), reason);
	return VMX_TEST_EXIT;
}

static int vmmcall_init(struct vmcs *vmcs	)
{
	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
	return VMX_TEST_START;
}

static void vmmcall_main(void)
{
	asm volatile(
		"mov $0xABCD, %%rax\n\t"
		"vmmcall\n\t"
		::: "rax");

	report("VMMCALL", 0);
}

static int vmmcall_exit_handler()
{
	ulong reason;

	reason = vmcs_read(EXI_REASON);
	switch (reason) {
	case VMX_VMCALL:
		printf("here\n");
		report("VMMCALL triggers #UD", 0);
		break;
	case VMX_EXC_NMI:
		report("VMMCALL triggers #UD",
		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
		break;
	default:
		report("Unknown exit reason, %ld", false, reason);
		print_vmexit_info();
	}

	return VMX_TEST_VMEXIT;
}

static int disable_rdtscp_init(struct vmcs *vmcs)
{
	u32 ctrl_cpu1;

	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
		ctrl_cpu1 &= ~CPU_RDTSCP;
		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
	}

	return VMX_TEST_START;
}

static void disable_rdtscp_ud_handler(struct ex_regs *regs)
{
	switch (vmx_get_test_stage()) {
	case 0:
		report("RDTSCP triggers #UD", true);
		vmx_inc_test_stage();
		regs->rip += 3;
		break;
	case 2:
		report("RDPID triggers #UD", true);
		vmx_inc_test_stage();
		regs->rip += 4;
		break;
	}
	return;

}

static void disable_rdtscp_main(void)
{
	/* Test that #UD is properly injected in L2.  */
	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);

	vmx_set_test_stage(0);
	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
	vmcall();
	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
	vmcall();
}

static int disable_rdtscp_exit_handler(void)
{
	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;

	switch (reason) {
	case VMX_VMCALL:
		switch (vmx_get_test_stage()) {
		case 0:
			report("RDTSCP triggers #UD", false);
			vmx_inc_test_stage();
			/* fallthrough */
		case 1:
			vmx_inc_test_stage();
			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
			return VMX_TEST_RESUME;
		case 2:
			report("RDPID triggers #UD", false);
			break;
		}
		break;

	default:
		report("Unknown exit reason, %d", false, reason);
		print_vmexit_info();
	}
	return VMX_TEST_VMEXIT;
}

int int3_init()
{
	vmcs_write(EXC_BITMAP, ~0u);
	return VMX_TEST_START;
}

void int3_guest_main()
{
	asm volatile ("int3");
}

int int3_exit_handler()
{
	u32 reason = vmcs_read(EXI_REASON);
	u32 intr_info = vmcs_read(EXI_INTR_INFO);

	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
	       (intr_info & INTR_INFO_VALID_MASK) &&
	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);

	return VMX_TEST_VMEXIT;
}

int into_init()
{
	vmcs_write(EXC_BITMAP, ~0u);
	return VMX_TEST_START;
}

void into_guest_main()
{
	struct far_pointer32 fp = {
		.offset = (uintptr_t)&&into,
		.selector = KERNEL_CS32,
	};
	register uintptr_t rsp asm("rsp");

	if (fp.offset != (uintptr_t)&&into) {
		printf("Code address too high.\n");
		return;
	}
	if ((u32)rsp != rsp) {
		printf("Stack address too high.\n");
		return;
	}

	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
	return;
into:
	asm volatile (".code32;"
		      "movl $0x7fffffff, %eax;"
		      "addl %eax, %eax;"
		      "into;"
		      "lret;"
		      ".code64");
	__builtin_unreachable();
}

int into_exit_handler()
{
	u32 reason = vmcs_read(EXI_REASON);
	u32 intr_info = vmcs_read(EXI_INTR_INFO);

	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
	       (intr_info & INTR_INFO_VALID_MASK) &&
	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);

	return VMX_TEST_VMEXIT;
}

static void exit_monitor_from_l2_main(void)
{
	printf("Calling exit(0) from l2...\n");
	exit(0);
}

static int exit_monitor_from_l2_handler(void)
{
	report("The guest should have killed the VMM", false);
	return VMX_TEST_EXIT;
}

static void assert_exit_reason(u64 expected)
{
	u64 actual = vmcs_read(EXI_REASON);

	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
			   exit_reason_description(expected),
			   exit_reason_description(actual));
}

static void skip_exit_vmcall()
{
	u64 guest_rip = vmcs_read(GUEST_RIP);
	u32 insn_len = vmcs_read(EXI_INST_LEN);

	assert_exit_reason(VMX_VMCALL);
	vmcs_write(GUEST_RIP, guest_rip + insn_len);
}

static void v2_null_test_guest(void)
{
}

static void v2_null_test(void)
{
	test_set_guest(v2_null_test_guest);
	enter_guest();
	report(__func__, 1);
}

static void v2_multiple_entries_test_guest(void)
{
	vmx_set_test_stage(1);
	vmcall();
	vmx_set_test_stage(2);
}

static void v2_multiple_entries_test(void)
{
	test_set_guest(v2_multiple_entries_test_guest);
	enter_guest();
	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
	skip_exit_vmcall();
	enter_guest();
	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
	report(__func__, 1);
}

static int fixture_test_data = 1;

static void fixture_test_teardown(void *data)
{
	*((int *) data) = 1;
}

static void fixture_test_guest(void)
{
	fixture_test_data++;
}


static void fixture_test_setup(void)
{
	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
			   "fixture_test_teardown didn't run?!");
	fixture_test_data = 2;
	test_add_teardown(fixture_test_teardown, &fixture_test_data);
	test_set_guest(fixture_test_guest);
}

static void fixture_test_case1(void)
{
	fixture_test_setup();
	TEST_ASSERT_EQ(2, fixture_test_data);
	enter_guest();
	TEST_ASSERT_EQ(3, fixture_test_data);
	report(__func__, 1);
}

static void fixture_test_case2(void)
{
	fixture_test_setup();
	TEST_ASSERT_EQ(2, fixture_test_data);
	enter_guest();
	TEST_ASSERT_EQ(3, fixture_test_data);
	report(__func__, 1);
}

enum ept_access_op {
	OP_READ,
	OP_WRITE,
	OP_EXEC,
	OP_FLUSH_TLB,
	OP_EXIT,
};

static struct ept_access_test_data {
	unsigned long gpa;
	unsigned long *gva;
	unsigned long hpa;
	unsigned long *hva;
	enum ept_access_op op;
} ept_access_test_data;

extern unsigned char ret42_start;
extern unsigned char ret42_end;

/* Returns 42. */
asm(
	".align 64\n"
	"ret42_start:\n"
	"mov $42, %eax\n"
	"ret\n"
	"ret42_end:\n"
);

static void
diagnose_ept_violation_qual(u64 expected, u64 actual)
{

#define DIAGNOSE(flag)							\
do {									\
	if ((expected & flag) != (actual & flag))			\
		printf(#flag " %sexpected\n",				\
		       (expected & flag) ? "" : "un");			\
} while (0)

	DIAGNOSE(EPT_VLT_RD);
	DIAGNOSE(EPT_VLT_WR);
	DIAGNOSE(EPT_VLT_FETCH);
	DIAGNOSE(EPT_VLT_PERM_RD);
	DIAGNOSE(EPT_VLT_PERM_WR);
	DIAGNOSE(EPT_VLT_PERM_EX);
	DIAGNOSE(EPT_VLT_LADDR_VLD);
	DIAGNOSE(EPT_VLT_PADDR);

#undef DIAGNOSE
}

static void do_ept_access_op(enum ept_access_op op)
{
	ept_access_test_data.op = op;
	enter_guest();
}

/*
 * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
 * needed by tests that modify guest PTEs.
 */
static void ept_access_test_guest_flush_tlb(void)
{
	do_ept_access_op(OP_FLUSH_TLB);
	skip_exit_vmcall();
}

/*
 * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
 * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
 * a huge page.
 */
static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
				 unsigned long clear, unsigned long set)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long orig_pte;
	unsigned long pte;

	/* Screw with the mapping at the requested level. */
	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
	pte = orig_pte;
	if (mkhuge)
		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
	else
		pte = orig_pte;
	pte = (pte & ~clear) | set;
	set_ept_pte(pml4, gpa, level, pte);
	ept_sync(INVEPT_SINGLE, eptp);

	return orig_pte;
}

static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
{
	set_ept_pte(pml4, gpa, level, orig_pte);
}

static void do_ept_violation(bool leaf, enum ept_access_op op,
			     u64 expected_qual, u64 expected_paddr)
{
	u64 qual;

	/* Try the access and observe the violation. */
	do_ept_access_op(op);

	assert_exit_reason(VMX_EPT_VIOLATION);

	qual = vmcs_read(EXI_QUALIFICATION);

	diagnose_ept_violation_qual(expected_qual, qual);
	TEST_EXPECT_EQ(expected_qual, qual);

	#if 0
	/* Disable for now otherwise every test will fail */
	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
		       (unsigned long) (
			       op == OP_EXEC ? data->gva + 1 : data->gva));
	#endif
	/*
	 * TODO: tests that probe expected_paddr in pages other than the one at
	 * the beginning of the 1g region.
	 */
	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
}

static void
ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
			      unsigned long set, enum ept_access_op op,
			      u64 expected_qual)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long orig_pte;

	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);

	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
					 data->gpa);

	/* Fix the violation and resume the op loop. */
	ept_untwiddle(data->gpa, level, orig_pte);
	enter_guest();
	skip_exit_vmcall();
}

static void
ept_violation_at_level(int level, unsigned long clear, unsigned long set,
		       enum ept_access_op op, u64 expected_qual)
{
	ept_violation_at_level_mkhuge(false, level, clear, set, op,
				      expected_qual);
	if (ept_huge_pages_supported(level))
		ept_violation_at_level_mkhuge(true, level, clear, set, op,
					      expected_qual);
}

static void ept_violation(unsigned long clear, unsigned long set,
			  enum ept_access_op op, u64 expected_qual)
{
	ept_violation_at_level(1, clear, set, op, expected_qual);
	ept_violation_at_level(2, clear, set, op, expected_qual);
	ept_violation_at_level(3, clear, set, op, expected_qual);
	ept_violation_at_level(4, clear, set, op, expected_qual);
}

static void ept_access_violation(unsigned long access, enum ept_access_op op,
				       u64 expected_qual)
{
	ept_violation(EPT_PRESENT, access, op,
		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
}

/*
 * For translations that don't involve a GVA, that is physical address (paddr)
 * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
 * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
 * translations don't involve GVAs, such as when the hardware does the guest
 * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
 * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
 * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
 * the EPT_VLT_PADDR bit will be clear in the exit qualification.
 *
 * Note that paddr violations can also be triggered by loading PAE page tables
 * with wonky addresses. We don't test that yet.
 *
 * This function modifies the EPT entry that maps the GPA that the guest page
 * table entry mapping ept_access_data.gva resides on.
 *
 *	@ept_access	EPT permissions to set. Other permissions are cleared.
 *
 *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
 *
 *	@op		Guest operation to perform with ept_access_data.gva.
 *
 *	@expect_violation
 *			Is a violation expected during the paddr access?
 *
 *	@expected_qual	Expected qualification for the EPT violation.
 *			EPT_VLT_PADDR should be clear.
 */
static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
			     enum ept_access_op op, bool expect_violation,
			     u64 expected_qual)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long *ptep;
	unsigned long gpa;
	unsigned long orig_epte;

	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
	TEST_ASSERT(ptep);
	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
	ept_access_test_guest_flush_tlb();

	/*
	 * Now modify the access bits on the EPT entry for the GPA that the
	 * guest PTE resides on. Note that by modifying a single EPT entry,
	 * we're potentially affecting 512 guest PTEs. However, we've carefully
	 * constructed our test such that those other 511 PTEs aren't used by
	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
	 * PTE we're modifying is at the beginning of a 4K page and the
	 * following 511 entires are also under our control (and not touched by
	 * the guest).
	 */
	gpa = virt_to_phys(ptep);
	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
	/*
	 * Make sure the guest page table page is mapped with a 4K EPT entry,
	 * otherwise our level=1 twiddling below will fail. We use the
	 * identity map (gpa = gpa) since page tables are shared with the host.
	 */
	install_ept(pml4, gpa, gpa, EPT_PRESENT);
	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
				/*clear=*/EPT_PRESENT, /*set=*/ept_access);

	if (expect_violation) {
		do_ept_violation(/*leaf=*/true, op,
				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
		ept_untwiddle(gpa, /*level=*/1, orig_epte);
		do_ept_access_op(op);
	} else {
		do_ept_access_op(op);
		ept_untwiddle(gpa, /*level=*/1, orig_epte);
	}

	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
		TEST_ASSERT(*ptep & PT_DIRTY_MASK);

	skip_exit_vmcall();
}

static void ept_access_allowed_paddr(unsigned long ept_access,
				     unsigned long pte_ad,
				     enum ept_access_op op)
{
	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
			 /*expected_qual=*/-1);
}

static void ept_access_violation_paddr(unsigned long ept_access,
				       unsigned long pte_ad,
				       enum ept_access_op op,
				       u64 expected_qual)
{
	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
			 expected_qual);
}


static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
					unsigned long clear,
					unsigned long set,
					enum ept_access_op op)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long orig_pte;

	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);

	/* No violation. Should proceed to vmcall. */
	do_ept_access_op(op);
	skip_exit_vmcall();

	ept_untwiddle(data->gpa, level, orig_pte);
}

static void ept_allowed_at_level(int level, unsigned long clear,
				 unsigned long set, enum ept_access_op op)
{
	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
	if (ept_huge_pages_supported(level))
		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
}

static void ept_allowed(unsigned long clear, unsigned long set,
			enum ept_access_op op)
{
	ept_allowed_at_level(1, clear, set, op);
	ept_allowed_at_level(2, clear, set, op);
	ept_allowed_at_level(3, clear, set, op);
	ept_allowed_at_level(4, clear, set, op);
}

static void ept_ignored_bit(int bit)
{
	/* Set the bit. */
	ept_allowed(0, 1ul << bit, OP_READ);
	ept_allowed(0, 1ul << bit, OP_WRITE);
	ept_allowed(0, 1ul << bit, OP_EXEC);

	/* Clear the bit. */
	ept_allowed(1ul << bit, 0, OP_READ);
	ept_allowed(1ul << bit, 0, OP_WRITE);
	ept_allowed(1ul << bit, 0, OP_EXEC);
}

static void ept_access_allowed(unsigned long access, enum ept_access_op op)
{
	ept_allowed(EPT_PRESENT, access, op);
}


static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
					     unsigned long clear,
					     unsigned long set,
					     enum ept_access_op op)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long orig_pte;

	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);

	do_ept_access_op(op);
	assert_exit_reason(VMX_EPT_MISCONFIG);

	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
	#if 0
	/* broken: */
	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
	#endif
	#if 0
	/*
	 * broken:
	 * According to description of exit qual for EPT violation,
	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
	 * to be set for msiconfig.
	 */
	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
		       (unsigned long) (
			       op == OP_EXEC ? data->gva + 1 : data->gva));
	#endif

	/* Fix the violation and resume the op loop. */
	ept_untwiddle(data->gpa, level, orig_pte);
	enter_guest();
	skip_exit_vmcall();
}

static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
					  unsigned long clear,
					  unsigned long set)
{
	/* The op shouldn't matter (read, write, exec), so try them all! */
	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
}

static void ept_misconfig_at_level(int level, unsigned long clear,
				   unsigned long set)
{
	ept_misconfig_at_level_mkhuge(false, level, clear, set);
	if (ept_huge_pages_supported(level))
		ept_misconfig_at_level_mkhuge(true, level, clear, set);
}

static void ept_misconfig(unsigned long clear, unsigned long set)
{
	ept_misconfig_at_level(1, clear, set);
	ept_misconfig_at_level(2, clear, set);
	ept_misconfig_at_level(3, clear, set);
	ept_misconfig_at_level(4, clear, set);
}

static void ept_access_misconfig(unsigned long access)
{
	ept_misconfig(EPT_PRESENT, access);
}

static void ept_reserved_bit_at_level_nohuge(int level, int bit)
{
	/* Setting the bit causes a misconfig. */
	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);

	/* Making the entry non-present turns reserved bits into ignored. */
	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
}

static void ept_reserved_bit_at_level_huge(int level, int bit)
{
	/* Setting the bit causes a misconfig. */
	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);

	/* Making the entry non-present turns reserved bits into ignored. */
	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
}

static void ept_reserved_bit_at_level(int level, int bit)
{
	/* Setting the bit causes a misconfig. */
	ept_misconfig_at_level(level, 0, 1ul << bit);

	/* Making the entry non-present turns reserved bits into ignored. */
	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
}

static void ept_reserved_bit(int bit)
{
	ept_reserved_bit_at_level(1, bit);
	ept_reserved_bit_at_level(2, bit);
	ept_reserved_bit_at_level(3, bit);
	ept_reserved_bit_at_level(4, bit);
}

#define PAGE_2M_ORDER 9
#define PAGE_1G_ORDER 18

static void *get_1g_page(void)
{
	static void *alloc;

	if (!alloc)
		alloc = alloc_pages(PAGE_1G_ORDER);
	return alloc;
}

static void ept_access_test_teardown(void *unused)
{
	/* Exit the guest cleanly. */
	do_ept_access_op(OP_EXIT);
}

static void ept_access_test_guest(void)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	int (*code)(void) = (int (*)(void)) &data->gva[1];

	while (true) {
		switch (data->op) {
		case OP_READ:
			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
			break;
		case OP_WRITE:
			*data->gva = MAGIC_VAL_2;
			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
			*data->gva = MAGIC_VAL_1;
			break;
		case OP_EXEC:
			TEST_ASSERT_EQ(42, code());
			break;
		case OP_FLUSH_TLB:
			write_cr3(read_cr3());
			break;
		case OP_EXIT:
			return;
		default:
			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
		}
		vmcall();
	}
}

static void ept_access_test_setup(void)
{
	struct ept_access_test_data *data = &ept_access_test_data;
	unsigned long npages = 1ul << PAGE_1G_ORDER;
	unsigned long size = npages * PAGE_SIZE;
	unsigned long *page_table = current_page_table();
	unsigned long pte;

	if (setup_ept(false))
		test_skip("EPT not supported");

	test_set_guest(ept_access_test_guest);
	test_add_teardown(ept_access_test_teardown, NULL);

	data->hva = get_1g_page();
	TEST_ASSERT(data->hva);
	data->hpa = virt_to_phys(data->hva);

	data->gpa = 1ul << 40;
	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
				   size);
	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
	install_pages(page_table, data->gpa, size, data->gva);

	/*
	 * Make sure nothing's mapped here so the tests that screw with the
	 * pml4 entry don't inadvertently break something.
	 */
	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);

	data->hva[0] = MAGIC_VAL_1;
	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
}

static void ept_access_test_not_present(void)
{
	ept_access_test_setup();
	/* --- */
	ept_access_violation(0, OP_READ, EPT_VLT_RD);
	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
}

static void ept_access_test_read_only(void)
{
	ept_access_test_setup();

	/* r-- */
	ept_access_allowed(EPT_RA, OP_READ);
	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
}

static void ept_access_test_write_only(void)
{
	ept_access_test_setup();
	/* -w- */
	ept_access_misconfig(EPT_WA);
}

static void ept_access_test_read_write(void)
{
	ept_access_test_setup();
	/* rw- */
	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
}


static void ept_access_test_execute_only(void)
{
	ept_access_test_setup();
	/* --x */
	if (ept_execute_only_supported()) {
		ept_access_violation(EPT_EA, OP_READ,
				     EPT_VLT_RD | EPT_VLT_PERM_EX);
		ept_access_violation(EPT_EA, OP_WRITE,
				     EPT_VLT_WR | EPT_VLT_PERM_EX);
		ept_access_allowed(EPT_EA, OP_EXEC);
	} else {
		ept_access_misconfig(EPT_EA);
	}
}

static void ept_access_test_read_execute(void)
{
	ept_access_test_setup();
	/* r-x */
	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
}

static void ept_access_test_write_execute(void)
{
	ept_access_test_setup();
	/* -wx */
	ept_access_misconfig(EPT_WA | EPT_EA);
}

static void ept_access_test_read_write_execute(void)
{
	ept_access_test_setup();
	/* rwx */
	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
}

static void ept_access_test_reserved_bits(void)
{
	int i;
	int maxphyaddr;

	ept_access_test_setup();

	/* Reserved bits above maxphyaddr. */
	maxphyaddr = cpuid_maxphyaddr();
	for (i = maxphyaddr; i <= 51; i++) {
		report_prefix_pushf("reserved_bit=%d", i);
		ept_reserved_bit(i);
		report_prefix_pop();
	}

	/* Level-specific reserved bits. */
	ept_reserved_bit_at_level_nohuge(2, 3);
	ept_reserved_bit_at_level_nohuge(2, 4);
	ept_reserved_bit_at_level_nohuge(2, 5);
	ept_reserved_bit_at_level_nohuge(2, 6);
	/* 2M alignment. */
	for (i = 12; i < 20; i++) {
		report_prefix_pushf("reserved_bit=%d", i);
		ept_reserved_bit_at_level_huge(2, i);
		report_prefix_pop();
	}
	ept_reserved_bit_at_level_nohuge(3, 3);
	ept_reserved_bit_at_level_nohuge(3, 4);
	ept_reserved_bit_at_level_nohuge(3, 5);
	ept_reserved_bit_at_level_nohuge(3, 6);
	/* 1G alignment. */
	for (i = 12; i < 29; i++) {
		report_prefix_pushf("reserved_bit=%d", i);
		ept_reserved_bit_at_level_huge(3, i);
		report_prefix_pop();
	}
	ept_reserved_bit_at_level(4, 3);
	ept_reserved_bit_at_level(4, 4);
	ept_reserved_bit_at_level(4, 5);
	ept_reserved_bit_at_level(4, 6);
	ept_reserved_bit_at_level(4, 7);
}

static void ept_access_test_ignored_bits(void)
{
	ept_access_test_setup();
	/*
	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
	 * far as translation is concerned even if AD bits are enabled in the
	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
	 * control is 0.
	 */
	ept_ignored_bit(8);
	ept_ignored_bit(9);
	ept_ignored_bit(10);
	ept_ignored_bit(11);
	ept_ignored_bit(52);
	ept_ignored_bit(53);
	ept_ignored_bit(54);
	ept_ignored_bit(55);
	ept_ignored_bit(56);
	ept_ignored_bit(57);
	ept_ignored_bit(58);
	ept_ignored_bit(59);
	ept_ignored_bit(60);
	ept_ignored_bit(61);
	ept_ignored_bit(62);
	ept_ignored_bit(63);
}

static void ept_access_test_paddr_not_present_ad_disabled(void)
{
	ept_access_test_setup();
	ept_disable_ad_bits();

	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
}

static void ept_access_test_paddr_not_present_ad_enabled(void)
{
	u64 qual = EPT_VLT_RD | EPT_VLT_WR;

	ept_access_test_setup();
	ept_enable_ad_bits_or_skip_test();

	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
}

static void ept_access_test_paddr_read_only_ad_disabled(void)
{
	/*
	 * When EPT AD bits are disabled, all accesses to guest paging
	 * structures are reported separately as a read and (after
	 * translation of the GPA to host physical address) a read+write
	 * if the A/D bits have to be set.
	 */
	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;

	ept_access_test_setup();
	ept_disable_ad_bits();

	/* Can't update A bit, so all accesses fail. */
	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
	/* AD bits disabled, so only writes try to update the D bit. */
	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
	/* Both A and D already set, so read-only is OK. */
	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
}

static void ept_access_test_paddr_read_only_ad_enabled(void)
{
	/*
	 * When EPT AD bits are enabled, all accesses to guest paging
	 * structures are considered writes as far as EPT translation
	 * is concerned.
	 */
	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;

	ept_access_test_setup();
	ept_enable_ad_bits_or_skip_test();

	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
}

static void ept_access_test_paddr_read_write(void)
{
	ept_access_test_setup();
	/* Read-write access to paging structure. */
	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
}

static void ept_access_test_paddr_read_write_execute(void)
{
	ept_access_test_setup();
	/* RWX access to paging structure. */
	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
}

static void ept_access_test_paddr_read_execute_ad_disabled(void)
{
  	/*
	 * When EPT AD bits are disabled, all accesses to guest paging
	 * structures are reported separately as a read and (after
	 * translation of the GPA to host physical address) a read+write
	 * if the A/D bits have to be set.
	 */
	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;

	ept_access_test_setup();
	ept_disable_ad_bits();

	/* Can't update A bit, so all accesses fail. */
	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
	/* AD bits disabled, so only writes try to update the D bit. */
	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
	/* Both A and D already set, so read-only is OK. */
	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
}

static void ept_access_test_paddr_read_execute_ad_enabled(void)
{
	/*
	 * When EPT AD bits are enabled, all accesses to guest paging
	 * structures are considered writes as far as EPT translation
	 * is concerned.
	 */
	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;

	ept_access_test_setup();
	ept_enable_ad_bits_or_skip_test();

	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
}

static void ept_access_test_paddr_not_present_page_fault(void)
{
	ept_access_test_setup();
	/*
	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
	 * page is read-only in EPT but GVA is also mapped read only in PT.
	 * Thus guest page fault before host takes EPT violation for trying to
	 * update A bit.
	 */
}

static void ept_access_test_force_2m_page(void)
{
	ept_access_test_setup();

	TEST_ASSERT_EQ(ept_2m_supported(), true);
	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
				      EPT_VLT_WR | EPT_VLT_PERM_RD |
				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
}

static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
{
	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);

	TEST_ASSERT(msr & VPID_CAP_INVVPID);

	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
		return false;

	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
		return false;

	if (vpid >> 16)
		return false;

	if (type != INVVPID_ALL && !vpid)
		return false;

	if (type == INVVPID_ADDR && !is_canonical(gla))
		return false;

	return true;
}

static void try_invvpid(u64 type, u64 vpid, u64 gla)
{
	int rc;
	bool valid = invvpid_valid(type, vpid, gla);
	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
	/*
	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
	 * that we can tell if it is updated by INVVPID.
	 */
	vmcs_read(~0);
	rc = invvpid(type, vpid, gla);
	report("INVVPID type %ld VPID %lx GLA %lx %s",
	       !rc == valid, type, vpid, gla,
	       valid ? "passes" : "fails");
	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
	       vmcs_read(VMX_INST_ERROR) == expected,
	       rc ? "failed" : "successful",
	       expected, vmcs_read(VMX_INST_ERROR));
}

static void ds_invvpid(void *data)
{
	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;

	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
	asm volatile("invvpid %0, %1"
		     :
		     : "m"(*(struct invvpid_operand *)data),
		       "r"(type));
}

/*
 * The SS override is ignored in 64-bit mode, so we use an addressing
 * mode with %rsp as the base register to generate an implicit SS
 * reference.
 */
static void ss_invvpid(void *data)
{
	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;

	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
		     : "+r"(data)
		     : "r"(type));
}

static void invvpid_test_gp(void)
{
	bool fault;

	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
				   (void *)NONCANONICAL);
	report("INVVPID with non-canonical DS operand raises #GP", fault);
}

static void invvpid_test_ss(void)
{
	bool fault;

	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
				   (void *)NONCANONICAL);
	report("INVVPID with non-canonical SS operand raises #SS", fault);
}

static void invvpid_test_pf(void)
{
	void *vpage = alloc_vpage();
	bool fault;

	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
	report("INVVPID with unmapped operand raises #PF", fault);
}

static void try_compat_invvpid(void *unused)
{
	struct far_pointer32 fp = {
		.offset = (uintptr_t)&&invvpid,
		.selector = KERNEL_CS32,
	};
	register uintptr_t rsp asm("rsp");

	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
			"Code address too high.");
	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");

	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
	return;
invvpid:
	asm volatile (".code32;"
		      "invvpid (%eax), %eax;"
		      "lret;"
		      ".code64");
	__builtin_unreachable();
}

static void invvpid_test_compatibility_mode(void)
{
	bool fault;

	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
	report("Compatibility mode INVVPID raises #UD", fault);
}

static void invvpid_test_not_in_vmx_operation(void)
{
	bool fault;

	TEST_ASSERT(!vmx_off());
	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
	report("INVVPID outside of VMX operation raises #UD", fault);
	TEST_ASSERT(!vmx_on());
}

/*
 * This does not test real-address mode, virtual-8086 mode, protected mode,
 * or CPL > 0.
 */
static void invvpid_test_v2(void)
{
	u64 msr;
	int i;
	unsigned types = 0;
	unsigned type;

	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
		test_skip("VPID not supported");

	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);

	if (!(msr & VPID_CAP_INVVPID))
		test_skip("INVVPID not supported.\n");

	if (msr & VPID_CAP_INVVPID_ADDR)
		types |= 1u << INVVPID_ADDR;
	if (msr & VPID_CAP_INVVPID_CXTGLB)
		types |= 1u << INVVPID_CONTEXT_GLOBAL;
	if (msr & VPID_CAP_INVVPID_ALL)
		types |= 1u << INVVPID_ALL;
	if (msr & VPID_CAP_INVVPID_CXTLOC)
		types |= 1u << INVVPID_CONTEXT_LOCAL;

	if (!types)
		test_skip("No INVVPID types supported.\n");

	for (i = -127; i < 128; i++)
		try_invvpid(i, 0xffff, 0);

	/*
	 * VPID must not be more than 16 bits.
	 */
	for (i = 0; i < 64; i++)
		for (type = 0; type < 4; type++)
			if (types & (1u << type))
				try_invvpid(type, 1ul << i, 0);

	/*
	 * VPID must not be zero, except for "all contexts."
	 */
	for (type = 0; type < 4; type++)
		if (types & (1u << type))
			try_invvpid(type, 0, 0);

	/*
	 * The gla operand is only validated for single-address INVVPID.
	 */
	if (types & (1u << INVVPID_ADDR))
		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);

	invvpid_test_gp();
	invvpid_test_ss();
	invvpid_test_pf();
	invvpid_test_compatibility_mode();
	invvpid_test_not_in_vmx_operation();
}

/*
 * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
 * at least as far as the guest-state checks. Returns false if the
 * VMLAUNCH fails early and execution falls through to the next
 * instruction.
 */
static bool vmlaunch_succeeds(void)
{
	/*
	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
	 * unsupported VMCS component"). The caller can then check
	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
	 */
	vmcs_write(~0u, 0);

	vmcs_write(HOST_RIP, (uintptr_t)&&success);
	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
				   :
				   : "r" ((u64)HOST_RSP)
				   : "cc", "memory"
				   : success);
	return false;
success:
	TEST_ASSERT(vmcs_read(EXI_REASON) ==
		    (VMX_FAIL_STATE | VMX_ENTRY_FAILURE));
	return true;
}

/*
 * Try to launch the current VMCS.
 */
static void test_vmx_controls(bool controls_valid)
{
	bool success = vmlaunch_succeeds();
	u32 vmx_inst_err;

	report("vmlaunch %s", success == controls_valid,
	       controls_valid ? "succeeds" : "fails");
	if (!controls_valid) {
		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
		report("VMX inst error is %d (actual %d)",
		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
	}
}

/*
 * Test a particular address setting for a physical page reference in
 * the VMCS.
 */
static void test_vmcs_page_addr(const char *name,
				enum Encoding encoding,
				bool ignored,
				u64 addr)
{
	report_prefix_pushf("%s = %lx", name, addr);
	vmcs_write(encoding, addr);
	test_vmx_controls(ignored || (IS_ALIGNED(addr, PAGE_SIZE) &&
				  addr < (1ul << cpuid_maxphyaddr())));
	report_prefix_pop();
}

/*
 * Test interesting values for a physical page reference in the VMCS.
 */
static void test_vmcs_page_values(const char *name,
				  enum Encoding encoding,
				  bool ignored)
{
	unsigned i;
	u64 orig_val = vmcs_read(encoding);

	for (i = 0; i < 64; i++)
		test_vmcs_page_addr(name, encoding, ignored, 1ul << i);

	test_vmcs_page_addr(name, encoding, ignored, PAGE_SIZE - 1);
	test_vmcs_page_addr(name, encoding, ignored, PAGE_SIZE);
	test_vmcs_page_addr(name, encoding, ignored,
			    (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
	test_vmcs_page_addr(name, encoding, ignored, -1ul);

	vmcs_write(encoding, orig_val);
}

/*
 * Test a physical page reference in the VMCS, when the corresponding
 * feature is enabled and when the corresponding feature is disabled.
 */
static void test_vmcs_page_reference(u32 control_bit, enum Encoding field,
				     const char *field_name,
				     const char *control_name)
{
	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
	u64 page_addr;

	if (!(ctrl_cpu_rev[0].clr & control_bit))
		return;

	page_addr = vmcs_read(field);

	report_prefix_pushf("%s enabled", control_name);
	vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
	test_vmcs_page_values(field_name, field, false);
	report_prefix_pop();

	report_prefix_pushf("%s disabled", control_name);
	vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
	test_vmcs_page_values(field_name, field, true);
	report_prefix_pop();

	vmcs_write(field, page_addr);
	vmcs_write(CPU_EXEC_CTRL0, primary);
}

/*
 * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
 * each I/O-bitmap address must be 0. Neither address should set any
 * bits beyond the processor's physical-address width.
 * [Intel SDM]
 */
static void test_io_bitmaps(void)
{
	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_A,
				 "I/O bitmap A", "Use I/O bitmaps");
	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_B,
				 "I/O bitmap B", "Use I/O bitmaps");
}

/*
 * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
 * the MSR-bitmap address must be 0. The address should not set any
 * bits beyond the processor's physical-address width.
 * [Intel SDM]
 */
static void test_msr_bitmap(void)
{
	test_vmcs_page_reference(CPU_MSR_BITMAP, MSR_BITMAP,
				 "MSR bitmap", "Use MSR bitmaps");
}

static void vmx_controls_test(void)
{
	/*
	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
	 * fail due to invalid guest state, should we make it that
	 * far.
	 */
	vmcs_write(GUEST_RFLAGS, 0);

	test_io_bitmaps();
	test_msr_bitmap();
}

static bool valid_vmcs_for_vmentry(void)
{
	struct vmcs *current_vmcs = NULL;

	if (vmcs_save(&current_vmcs))
		return false;

	return current_vmcs && !(current_vmcs->revision_id >> 31);
}

static void try_vmentry_in_movss_shadow(void)
{
	u32 vm_inst_err;
	u32 flags;
	bool early_failure = false;
	u32 expected_flags = X86_EFLAGS_FIXED;
	bool valid_vmcs = valid_vmcs_for_vmentry();

	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;

	/*
	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
	 * unsupported VMCS component").
	 */
	vmcs_write(~0u, 0);

	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
			      "vmwrite %%rsp, %%rdx;"
			      "mov 0f, %%rax;"
			      "mov %[host_rip], %%edx;"
			      "vmwrite %%rax, %%rdx;"
			      "mov $-1, %%ah;"
			      "sahf;"
			      "mov %%ss, %%ax;"
			      "mov %%ax, %%ss;"
			      "vmlaunch;"
			      "mov $1, %[early_failure];"
			      "0: lahf;"
			      "movzbl %%ah, %[flags]"
			      : [early_failure] "+r" (early_failure),
				[flags] "=&a" (flags)
			      : [host_rsp] "i" (HOST_RSP),
				[host_rip] "i" (HOST_RIP)
			      : "rdx", "cc", "memory");
	vm_inst_err = vmcs_read(VMX_INST_ERROR);

	report("Early VM-entry failure", early_failure);
	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
	       expected_flags, flags);
	if (valid_vmcs)
		report("VM-instruction error is %d (actual %d)",
		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
}

static void vmentry_movss_shadow_test(void)
{
	struct vmcs *orig_vmcs;

	TEST_ASSERT(!vmcs_save(&orig_vmcs));

	/*
	 * Set the launched flag on the current VMCS to verify the correct
	 * error priority, below.
	 */
	test_set_guest(v2_null_test_guest);
	enter_guest();

	/*
	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
	 * fail due to invalid guest state (if we make it that far).
	 */
	vmcs_write(GUEST_RFLAGS, 0);

	/*
	 * "VM entry with events blocked by MOV SS" takes precedence over
	 * "VMLAUNCH with non-clear VMCS."
	 */
	report_prefix_push("valid current-VMCS");
	try_vmentry_in_movss_shadow();
	report_prefix_pop();

	/*
	 * VMfailInvalid takes precedence over "VM entry with events
	 * blocked by MOV SS."
	 */
	TEST_ASSERT(!vmcs_clear(orig_vmcs));
	report_prefix_push("no current-VMCS");
	try_vmentry_in_movss_shadow();
	report_prefix_pop();

	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
}

#define TEST(name) { #name, .v2 = name }

/* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
struct vmx_test vmx_tests[] = {
	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
	{ "preemption timer", preemption_timer_init, preemption_timer_main,
		preemption_timer_exit_handler, NULL, {0} },
	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
		test_ctrl_pat_exit_handler, NULL, {0} },
	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
		test_ctrl_efer_exit_handler, NULL, {0} },
	{ "CR shadowing", NULL, cr_shadowing_main,
		cr_shadowing_exit_handler, NULL, {0} },
	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
		NULL, {0} },
	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
		insn_intercept_exit_handler, NULL, {0} },
	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
	{ "interrupt", interrupt_init, interrupt_main,
		interrupt_exit_handler, NULL, {0} },
	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
		NULL, {0} },
	{ "MSR switch", msr_switch_init, msr_switch_main,
		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
		disable_rdtscp_exit_handler, NULL, {0} },
	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
		exit_monitor_from_l2_handler, NULL, {0} },
	/* Basic V2 tests. */
	TEST(v2_null_test),
	TEST(v2_multiple_entries_test),
	TEST(fixture_test_case1),
	TEST(fixture_test_case2),
	/* EPT access tests. */
	TEST(ept_access_test_not_present),
	TEST(ept_access_test_read_only),
	TEST(ept_access_test_write_only),
	TEST(ept_access_test_read_write),
	TEST(ept_access_test_execute_only),
	TEST(ept_access_test_read_execute),
	TEST(ept_access_test_write_execute),
	TEST(ept_access_test_read_write_execute),
	TEST(ept_access_test_reserved_bits),
	TEST(ept_access_test_ignored_bits),
	TEST(ept_access_test_paddr_not_present_ad_disabled),
	TEST(ept_access_test_paddr_not_present_ad_enabled),
	TEST(ept_access_test_paddr_read_only_ad_disabled),
	TEST(ept_access_test_paddr_read_only_ad_enabled),
	TEST(ept_access_test_paddr_read_write),
	TEST(ept_access_test_paddr_read_write_execute),
	TEST(ept_access_test_paddr_read_execute_ad_disabled),
	TEST(ept_access_test_paddr_read_execute_ad_enabled),
	TEST(ept_access_test_paddr_not_present_page_fault),
	TEST(ept_access_test_force_2m_page),
	/* Opcode tests. */
	TEST(invvpid_test_v2),
	/* VM-entry tests */
	TEST(vmx_controls_test),
	TEST(vmentry_movss_shadow_test),
	{ NULL, NULL, NULL, NULL, NULL, {0} },
};
                           source/v64/tests/kvm-unit-tests/x86/xsave.c                                                         0000644 0000000 0000000 00000012330 00000000000 015656  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #include "libcflat.h"
#include "desc.h"
#include "processor.h"

#ifdef __x86_64__
#define uint64_t unsigned long
#else
#define uint64_t unsigned long long
#endif

int xgetbv_checking(u32 index, u64 *result)
{
    u32 eax, edx;

    asm volatile(ASM_TRY("1f")
            ".byte 0x0f,0x01,0xd0\n\t" /* xgetbv */
            "1:"
            : "=a" (eax), "=d" (edx)
            : "c" (index));
    *result = eax + ((u64)edx << 32);
    return exception_vector();
}

int xsetbv_checking(u32 index, u64 value)
{
    u32 eax = value;
    u32 edx = value >> 32;

    asm volatile(ASM_TRY("1f")
            ".byte 0x0f,0x01,0xd1\n\t" /* xsetbv */
            "1:"
            : : "a" (eax), "d" (edx), "c" (index));
    return exception_vector();
}

int write_cr4_checking(unsigned long val)
{
    asm volatile(ASM_TRY("1f")
            "mov %0,%%cr4\n\t"
            "1:": : "r" (val));
    return exception_vector();
}

#define CPUID_1_ECX_XSAVE	    (1 << 26)
#define CPUID_1_ECX_OSXSAVE	    (1 << 27)
int check_cpuid_1_ecx(unsigned int bit)
{
    return (cpuid(1).c & bit) != 0;
}

uint64_t get_supported_xcr0(void)
{
    struct cpuid r;
    r = cpuid_indexed(0xd, 0);
    printf("eax %x, ebx %x, ecx %x, edx %x\n",
            r.a, r.b, r.c, r.d);
    return r.a + ((u64)r.d << 32);
}

#define X86_CR4_OSXSAVE			0x00040000
#define XCR_XFEATURE_ENABLED_MASK       0x00000000
#define XCR_XFEATURE_ILLEGAL_MASK       0x00000010

#define XSTATE_FP       0x1
#define XSTATE_SSE      0x2
#define XSTATE_YMM      0x4

void test_xsave(void)
{
    unsigned long cr4;
    uint64_t supported_xcr0;
    uint64_t test_bits;
    u64 xcr0;

    printf("Legal instruction testing:\n");

    supported_xcr0 = get_supported_xcr0();
    printf("Supported XCR0 bits: %#lx\n", supported_xcr0);

    test_bits = XSTATE_FP | XSTATE_SSE;
    report("Check minimal XSAVE required bits",
		    (supported_xcr0 & test_bits) == test_bits);

    cr4 = read_cr4();
    report("Set CR4 OSXSAVE", write_cr4_checking(cr4 | X86_CR4_OSXSAVE) == 0);
    report("Check CPUID.1.ECX.OSXSAVE - expect 1",
		    check_cpuid_1_ecx(CPUID_1_ECX_OSXSAVE));

    printf("\tLegal tests\n");
    test_bits = XSTATE_FP;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_FP)",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == 0);

    test_bits = XSTATE_FP | XSTATE_SSE;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_FP | XSTATE_SSE)",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == 0);
    report("        xgetbv(XCR_XFEATURE_ENABLED_MASK)",
	xgetbv_checking(XCR_XFEATURE_ENABLED_MASK, &xcr0) == 0);

    printf("\tIllegal tests\n");
    test_bits = 0;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, 0) - expect #GP",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == GP_VECTOR);

    test_bits = XSTATE_SSE;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_SSE) - expect #GP",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == GP_VECTOR);

    if (supported_xcr0 & XSTATE_YMM) {
        test_bits = XSTATE_YMM;
        report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_YMM) - expect #GP",
		xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == GP_VECTOR);

        test_bits = XSTATE_FP | XSTATE_YMM;
        report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_FP | XSTATE_YMM) - expect #GP",
		xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == GP_VECTOR);
    }

    test_bits = XSTATE_SSE;
    report("\t\txsetbv(XCR_XFEATURE_ILLEGAL_MASK, XSTATE_FP) - expect #GP",
	xsetbv_checking(XCR_XFEATURE_ILLEGAL_MASK, test_bits) == GP_VECTOR);

    test_bits = XSTATE_SSE;
    report("\t\txgetbv(XCR_XFEATURE_ILLEGAL_MASK, XSTATE_FP) - expect #GP",
	xsetbv_checking(XCR_XFEATURE_ILLEGAL_MASK, test_bits) == GP_VECTOR);

    cr4 &= ~X86_CR4_OSXSAVE;
    report("Unset CR4 OSXSAVE", write_cr4_checking(cr4) == 0);
    report("Check CPUID.1.ECX.OSXSAVE - expect 0",
	check_cpuid_1_ecx(CPUID_1_ECX_OSXSAVE) == 0);

    printf("\tIllegal tests:\n");
    test_bits = XSTATE_FP;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_FP) - expect #UD",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == UD_VECTOR);

    test_bits = XSTATE_FP | XSTATE_SSE;
    report("\t\txsetbv(XCR_XFEATURE_ENABLED_MASK, XSTATE_FP | XSTATE_SSE) - expect #UD",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, test_bits) == UD_VECTOR);

    printf("\tIllegal tests:\n");
    report("\txgetbv(XCR_XFEATURE_ENABLED_MASK) - expect #UD",
	xgetbv_checking(XCR_XFEATURE_ENABLED_MASK, &xcr0) == UD_VECTOR);
}

void test_no_xsave(void)
{
    unsigned long cr4;
    u64 xcr0;

    report("Check CPUID.1.ECX.OSXSAVE - expect 0",
	check_cpuid_1_ecx(CPUID_1_ECX_OSXSAVE) == 0);

    printf("Illegal instruction testing:\n");

    cr4 = read_cr4();
    report("Set OSXSAVE in CR4 - expect #GP",
	write_cr4_checking(cr4 | X86_CR4_OSXSAVE) == GP_VECTOR);

    report("Execute xgetbv - expect #UD",
	xgetbv_checking(XCR_XFEATURE_ENABLED_MASK, &xcr0) == UD_VECTOR);

    report("Execute xsetbv - expect #UD",
	xsetbv_checking(XCR_XFEATURE_ENABLED_MASK, 0x3) == UD_VECTOR);
}

int main(void)
{
    setup_idt();
    if (check_cpuid_1_ecx(CPUID_1_ECX_XSAVE)) {
        printf("CPU has XSAVE feature\n");
        test_xsave();
    } else {
        printf("CPU don't has XSAVE feature\n");
        test_no_xsave();
    }
    return report_summary();
}
                                                                                                                                                                                                                                                                                                        source/v64/tests/lib/aarch32_workload.mjs                                                           0000644 0000000 0000000 00000011407 00000000000 015437  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The 32-bit Arm workload (docs/aarch32-plan.md Q5.1, R5.2): what a Linux
// kernel's 32-bit processes run, the same on a 64-bit kernel's compat tasks
// (tests/a64/linux_boot.mjs, A64_WORKLOAD=aarch32) and on a 32-bit kernel
// (tests/a32/linux_boot.mjs): tests/a64/linux_probe32.c built for A32 and
// for T32, then Alpine's armv7 programs (tools/alpine_repo.mjs --arch armv7
// --set aarch32) in a chroot: BusyBox and musl's dynamic linker, Lua, xz,
// OpenSSL's digests and ciphers (the crypto instructions), SQLite, forks.
// The script prints the outputs between <PREFIX>_WORKLOAD_BEGIN and _END.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { output_directory } from "../../tools/alpine_repo.mjs";
import { ROOT } from "./alpine_image.mjs";

// (inside the chroot every command is its own line, the outputs deterministic:
// no addresses, timings or the MIDR's fields)
export const AARCH32_COMMANDS = [
    "/bin/busybox --install -s",
    "uname -m",
    "lua5.4 -e 'print(string.format(\"%.6f %.3e\", math.sin(1.0) * 1e6, 2^-60)); local t = {} for i = 1, 200000 do t[i] = i * i end print(#t, t[#t])'",
    "seq 1 50000 | xz -6e | md5sum",
    "seq 1 50000 | xz -6 | xz -d | md5sum",
    "seq 1 20000 | openssl dgst -sha256",
    "seq 1 20000 | openssl dgst -sha1",
    "seq 1 20000 | openssl enc -aes-128-cbc -K 000102030405060708090a0b0c0d0e0f -iv 0f0e0d0c0b0a09080706050403020100 | md5sum",
    "seq 1 20000 | openssl enc -aes-256-ctr -K 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f -iv 0f0e0d0c0b0a09080706050403020100 | md5sum",
    "seq 1 20000 | openssl enc -chacha20 -K 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f -iv 0f0e0d0c0b0a09080706050403020100 | md5sum",
    "sqlite3 -list :memory: 'with recursive c(x) as (select 1 union all select x + 1 from c where x < 20000) select count(*), sum(x), total(x * 0.5) from c;'",
    "for i in 1 2 3 4 5 6 7 8; do true & done; wait; echo forks done",
    "grep -m1 Features /proc/cpuinfo",
    // (PER_LINUX32: the 32-bit uname and /proc/cpuinfo)
    "linux32 uname -m",
    "linux32 grep -m1 Features /proc/cpuinfo",
];

/**
 * Stage the workload in `staging` (a directory made anew; a cpio of it goes
 * after an initramfs): /a32 the chroot, /<prefix>-probe32-a32 and -t32 (their
 * objects in `objects`), /<prefix>-aarch32-workload the script. `run` runs
 * a program and fails on its failure, `lld` is rust-lld.
 * @param {{ staging: string, objects: string, run: function(string, !Array<string>): string, lld: string, prefix: string }} options
 */
export async function aarch32_workload({ staging, objects, run, lld, prefix })
{
    const repo = path.join(output_directory("armv7"), "aarch32-repo");
    assert.ok(fs.existsSync(repo), repo + " is missing: node tools/alpine_repo.mjs --arch armv7 --set aarch32");
    fs.rmSync(staging, { recursive: true, force: true });
    fs.mkdirSync(staging + "a32", { recursive: true });
    for(const section of ["main", "community"])
    {
        const apks = path.join(repo, section, "armv7");
        if(!fs.existsSync(apks)) continue;
        for(const file of fs.readdirSync(apks).filter(f => f.endsWith(".apk")).sort())
        {
            run("bsdtar", ["-xf", path.join(apks, file), "-C", staging + "a32", "--exclude", ".PKGINFO", "--exclude", ".SIGN.*",
                "--exclude", ".*-install", "--exclude", ".*-upgrade", "--exclude", ".*-deinstall", "--exclude", ".trigger"]);
        }
    }
    // (bbsuid is setuid without read permission: the cpio needs to read it)
    run("chmod", ["-R", "u+rw", staging]);
    for(const [isa, flag] of [["a32", "-marm"], ["t32", "-mthumb"]])
    {
        run(process.env.CLANG || "clang", ["--target=armv7a-linux-gnueabihf", "-march=armv8-a", "-mfpu=crypto-neon-fp-armv8", "-mfloat-abi=hard",
            flag, "-O2", "-ffreestanding", "-fno-builtin", "-fno-stack-protector", "-fomit-frame-pointer", "-c",
            ROOT + "tests/a64/linux_probe32.c", "-o", objects + `probe32-${isa}.o`]);
        run(lld, ["-flavor", "gnu", "-m", "armelf_linux_eabi", "-static", "-e", "_start", "-o", staging + `${prefix}-probe32-${isa}`, objects + `probe32-${isa}.o`]);
        fs.chmodSync(staging + `${prefix}-probe32-${isa}`, 0o755);
    }
    const upper = prefix.toUpperCase();
    fs.writeFileSync(staging + `${prefix}-aarch32-workload`, [
        "#!/bin/busybox sh",
        "B=/bin/busybox",
        "$B mkdir -p /a32/proc /a32/dev /a32/tmp; $B mount -t proc proc /a32/proc; $B mount -o bind /dev /a32/dev",
        `$B echo ${upper}_WORKLOAD_BEGIN`,
        `/${prefix}-probe32-a32`,
        `/${prefix}-probe32-t32`,
        ...AARCH32_COMMANDS.map(c => `$B chroot /a32 /bin/busybox sh -c '${c.replace(/'/g, "'\\''")}' 2>&1`),
        `$B echo ${upper}_WORKLOAD_END`,
        ""].join("\n"), { mode: 0o755 });
}
                                                                                                                                                                                                                                                         source/v64/tests/lib/alpine_image.mjs                                                               0000644 0000000 0000000 00000011347 00000000000 014727  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The pinned Alpine Linux 3.24.0 images of the tests
// (docs/arm64-virt-android16-plan.md P0.1): each ISO's name and SHA-256, the
// directory it is cached in, and its kernel and initramfs (and for aarch64
// the modloop and the kernel configuration) unpacked with bsdtar. An ISO is
// downloaded once from dl-cdn.alpinelinux.org (or copied from
// ALPINE_CACHE=<dir>, where another worktree keeps it) and checked against
// its SHA-256 on every use.
//
// Alpine aarch64's vmlinuz-* is an EFI zboot image (a PE/COFF stub with a
// gzip payload): unzboot() gives the arm64 Image inside, whose header it
// checks.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import zlib from "node:zlib";
import { spawnSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { fileURLToPath } from "node:url";

export const ROOT = fileURLToPath(new URL("../../", import.meta.url));
const RELEASES = "https://dl-cdn.alpinelinux.org/alpine/v3.24/releases/";

/** The images, by architecture and flavour */
export const IMAGES = {
    "x86_64-virt": { arch: "x86_64", name: "alpine-virt-3.24.0-x86_64.iso",
        sha256: "6cd1a38ae05cf96a5d0cbb2ddd6c630834babfeca1ecc5d1f05ec0b06b886102", flavor: "virt" },
    "x86_64-lts": { arch: "x86_64", name: "alpine-standard-3.24.0-x86_64.iso",
        sha256: "9f8bf67c1604381bf056f907d77adaf301fad9cc7b9e1fb73660c1b66f3ebd9f", flavor: "lts" },
    // (checked against the published alpine-virt-3.24.0-aarch64.iso.sha256 on 2026-10-15)
    "aarch64-virt": { arch: "aarch64", name: "alpine-virt-3.24.0-aarch64.iso",
        sha256: "834469887c99227230e981cc8a5b66571f5eab98f12c6a675f9ea0dd640b7866", flavor: "virt" },
};

/** Where an architecture's images and their unpacked files are kept */
export function directory_of(arch)
{
    return ROOT + (arch === "x86_64" ? "build/x64-linux/" : "build/a64-linux/");
}

export const sha256 = bytes => create_hash("sha256").update(bytes).digest("hex");

/**
 * The image `key` of IMAGES, downloaded and checked, with `files` (paths in
 * the ISO; by default its kernel and initramfs) unpacked next to it:
 * { directory, iso, kernel, initrd, image, source }
 */
export async function prepare(key, files)
{
    const image = IMAGES[key];
    assert.ok(image, "no Alpine image " + key);
    const directory = directory_of(image.arch);
    const iso = directory + image.name;
    const source = RELEASES + image.arch + "/" + image.name;
    fs.mkdirSync(directory, { recursive: true });
    if(!fs.existsSync(iso))
    {
        const cached = process.env.ALPINE_CACHE && path.join(process.env.ALPINE_CACHE, image.name);
        let bytes;
        if(cached && fs.existsSync(cached))
        {
            bytes = fs.readFileSync(cached);
        }
        else
        {
            const response = await fetch(source);
            assert.ok(response.ok, `Alpine ISO ${image.name}: HTTP ${response.status}`);
            bytes = Buffer.from(await response.arrayBuffer());
        }
        assert.equal(sha256(bytes), image.sha256, "the pinned Alpine ISO's SHA-256: " + image.name);
        fs.writeFileSync(iso, bytes);
    }
    assert.equal(sha256(fs.readFileSync(iso)), image.sha256, "the pinned Alpine ISO's SHA-256: " + image.name);
    const kernel = `boot/vmlinuz-${image.flavor}`, initrd = `boot/initramfs-${image.flavor}`;
    for(const file of files || [kernel, initrd])
    {
        if(fs.existsSync(directory + file)) continue;
        const unpack = spawnSync("bsdtar", ["-xf", iso, "-C", directory, file], { encoding: "utf8" });
        assert.equal(unpack.status, 0, unpack.stderr);
    }
    return { directory, iso, kernel: directory + kernel, initrd: directory + initrd, image, source };
}

/**
 * The arm64 Image inside an EFI zboot image (Linux
 * drivers/firmware/efi/libstub/zboot-header.S: "MZ", "zimg" at 4, the
 * payload's offset at 8 and size at 12, the compression's name at 24), or
 * the bytes themselves when they are an Image already
 */
export function unzboot(bytes)
{
    const view = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    const is_image = b => b.length >= 64 && b.readUInt32LE(56) === 0x644D5241; // "ARM\x64"
    if(is_image(view)) return view;
    assert.equal(view.toString("latin1", 0, 2), "MZ", "zboot: no MZ header");
    assert.equal(view.toString("latin1", 4, 8), "zimg", "zboot: no zimg magic");
    const offset = view.readUInt32LE(8), size = view.readUInt32LE(12);
    const compression = view.toString("latin1", 24, 56).replace(/\0.*$/s, "");
    assert.equal(compression, "gzip", "zboot: payload compression " + compression);
    const image = zlib.gunzipSync(view.subarray(offset, offset + size));
    assert.ok(is_image(image), "zboot: the payload is not an arm64 Image");
    return image;
}
                                                                                                                                                                                                                                                                                         source/v64/tests/lib/authenticode.mjs                                                               0000644 0000000 0000000 00000025015 00000000000 014766  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Signing for Secure Boot tests (tests/uefi/secure_boot.mjs): test keys and
// certificates (the openssl command line makes them; their private keys stay
// in the test's directory), Authenticode signatures of PE images (the
// PKCS #7 SignedData of an SpcIndirectDataContent over the image's hash, in
// the image's certificate table) and signed variable updates
// (EFI_VARIABLE_AUTHENTICATION_2: a detached SignedData over the name, GUID,
// attributes, time and data). A small DER encoder and reader; RSA with
// SHA-256 from node:crypto.

import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { guid } from "../../tools/uefi_vars.mjs";

// --- DER

function length_bytes(n)
{
    if(n < 0x80) return [n];
    const bytes = [];
    for(; n; n >>>= 8) bytes.unshift(n & 0xFF);
    return [0x80 | bytes.length, ...bytes];
}
/** @param {number} tag @param {...(Uint8Array|Array<number>)} parts */
export function tlv(tag, ...parts)
{
    const content = Buffer.concat(parts.map(part => Buffer.from(part)));
    return Buffer.concat([Buffer.from([tag, ...length_bytes(content.length)]), content]);
}
const seq = (...parts) => tlv(0x30, ...parts);
const set = (...parts) => tlv(0x31, ...parts);
const octets = bytes => tlv(0x04, bytes);
const explicit = (n, ...parts) => tlv(0xA0 | n, ...parts);
const integer = n => tlv(0x02, [n]);
const NULL = Buffer.from([0x05, 0x00]);
function oid(text)
{
    const [a, b, ...rest] = text.split(".").map(Number);
    const bytes = [40 * a + b];
    for(const n of rest)
    {
        const part = [n & 0x7F];
        for(let v = Math.floor(n / 128); v; v = Math.floor(v / 128)) part.unshift(0x80 | v & 0x7F);
        bytes.push(...part);
    }
    return tlv(0x06, bytes);
}
const OID_SIGNED_DATA = "1.2.840.113549.1.7.2";
const OID_DATA = "1.2.840.113549.1.7.1";
const OID_SHA256 = "2.16.840.1.101.3.4.2.1";
const OID_RSA = "1.2.840.113549.1.1.1";
const OID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
const OID_MESSAGE_DIGEST = "1.2.840.113549.1.9.4";
const OID_SPC_INDIRECT_DATA = "1.3.6.1.4.1.311.2.1.4";
const OID_SPC_PE_IMAGE_DATA = "1.3.6.1.4.1.311.2.1.15";
const SHA256 = seq(oid(OID_SHA256), NULL);

/** The children of a DER constructed value: [tag, header and content] each */
function children(bytes)
{
    const result = [];
    let at = 0;
    while(at < bytes.length)
    {
        const tag = bytes[at];
        let length = bytes[at + 1], header = 2;
        if(length & 0x80)
        {
            const n = length & 0x7F;
            length = 0;
            for(let i = 0; i < n; i++) length = length * 256 + bytes[at + 2 + i];
            header += n;
        }
        result.push({ tag, whole: bytes.subarray(at, at + header + length), content: bytes.subarray(at + header, at + header + length) });
        at += header + length;
    }
    return result;
}

/** A certificate's issuer and serial number (DER) */
function issuer_and_serial(certificate)
{
    const tbs = children(children(certificate)[0].content)[0].content;
    const fields = children(tbs);
    // ([0] version, serialNumber, signature, issuer, ...)
    const start = fields[0].tag === 0xA0 ? 1 : 0;
    return seq(fields[start + 2].whole, fields[start].whole);
}

/**
 * A PKCS #7 SignedData (version 1, SHA-256, RSA)
 * @param {{content_type: string, content: ?Uint8Array, digest_of: !Uint8Array, attributes: boolean, key: !crypto.KeyObject, certificate: !Uint8Array}} o
 *     content: the encapsulated content's bytes (null: detached); digest_of:
 *     what is signed; attributes: with authenticated attributes (content type, message digest)
 */
function signed_data({ content_type, content, digest_of, attributes, key, certificate })
{
    const digest = crypto.createHash("sha256").update(digest_of).digest();
    let signer_attributes = Buffer.alloc(0), signature;
    if(attributes)
    {
        const attrs = [seq(oid(OID_CONTENT_TYPE), set(oid(content_type))), seq(oid(OID_MESSAGE_DIGEST), set(octets(digest)))];
        // (signed as a SET, carried as [0] IMPLICIT)
        signature = crypto.sign("sha256", set(...attrs), key);
        signer_attributes = tlv(0xA0, ...attrs);
    }
    else
    {
        signature = crypto.sign("sha256", digest_of, key);
    }
    const signer = seq(integer(1), issuer_and_serial(certificate), SHA256, signer_attributes, seq(oid(OID_RSA), NULL), octets(signature));
    return seq(integer(1), set(SHA256), seq(oid(content_type), ...content ? [explicit(0, content)] : []),
        explicit(0, certificate), set(signer));
}

// --- keys

/**
 * A test key and its self-signed certificate, made once in a directory
 * @param {string} directory
 * @param {string} name
 * @return {{key: !crypto.KeyObject, certificate: !Uint8Array, name: string}}
 */
export function test_key(directory, name)
{
    fs.mkdirSync(directory, { recursive: true });
    const key_file = path.join(directory, name + ".key"), cert_file = path.join(directory, name + ".der");
    if(!fs.existsSync(cert_file))
    {
        const result = spawnSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key_file, "-outform", "DER", "-out", cert_file,
            "-days", "3650", "-subj", "/CN=v86 Secure Boot test " + name, "-sha256"], { encoding: "utf8" });
        if(result.status !== 0) throw new Error("openssl: " + result.stderr);
    }
    return { key: crypto.createPrivateKey(fs.readFileSync(key_file)), certificate: new Uint8Array(fs.readFileSync(cert_file)), name };
}

// --- PE images

/** A PE image's layout: its checksum and certificate table directory entry, headers, sections */
function pe_layout(image)
{
    const view = new DataView(image.buffer, image.byteOffset, image.byteLength);
    const pe = view.getUint32(0x3C, true);
    if(view.getUint32(pe, true) !== 0x4550) throw new Error("not a PE image");
    const sections = view.getUint16(pe + 6, true), optional_size = view.getUint16(pe + 20, true);
    const optional = pe + 24;
    const magic = view.getUint16(optional, true);
    const directories = optional + (magic === 0x20B ? 112 : 96);
    return {
        checksum: optional + 64,
        security: directories + 4 * 8,
        headers: view.getUint32(optional + 60, true),
        table: pe + 24 + optional_size,
        sections,
        view,
    };
}

/**
 * The Authenticode SHA-256 of a PE image (its certificate table and checksum
 * left out), as the firmware computes it
 * @param {!Uint8Array} image
 */
export function pe_hash(image)
{
    const { checksum, security, headers, table, sections, view } = pe_layout(image);
    const hash = crypto.createHash("sha256");
    hash.update(image.subarray(0, checksum));
    hash.update(image.subarray(checksum + 4, security));
    hash.update(image.subarray(security + 8, headers));
    let hashed = headers;
    const raw = [];
    for(let i = 0; i < sections; i++)
    {
        const at = table + i * 40;
        const size = view.getUint32(at + 16, true), pointer = view.getUint32(at + 20, true);
        if(size) raw.push([pointer, size]);
    }
    raw.sort((a, b) => a[0] - b[0]);
    for(const [pointer, size] of raw)
    {
        hash.update(image.subarray(pointer, pointer + size));
        hashed += size;
    }
    const certificates = view.getUint32(security + 4, true);
    if(image.length > hashed + certificates) hash.update(image.subarray(hashed, image.length - certificates));
    return hash.digest();
}

/**
 * A PE image signed (Authenticode, one signature): the SignedData appended in
 * a WIN_CERTIFICATE, the certificate table pointing to it
 * @param {!Uint8Array} image unsigned
 * @param {{key: !crypto.KeyObject, certificate: !Uint8Array}} signer
 */
export function sign_pe(image, { key, certificate })
{
    const { security, view } = pe_layout(image);
    if(view.getUint32(security + 4, true)) throw new Error("the image is signed already");
    // (the table starts 8-byte aligned)
    const unsigned = Buffer.concat([image, Buffer.alloc(-image.length & 7)]);
    const digest = pe_hash(unsigned);
    const indirect = seq(seq(oid(OID_SPC_PE_IMAGE_DATA), seq(Buffer.from([0x03, 0x01, 0x00]), explicit(0, tlv(0xA2, tlv(0x80, Buffer.alloc(0)))))),
        seq(SHA256, octets(digest)));
    // (Authenticode signs the SpcIndirectDataContent's content, its SEQUENCE header left out)
    const pkcs7 = seq(oid(OID_SIGNED_DATA), explicit(0, signed_data({ content_type: OID_SPC_INDIRECT_DATA, content: indirect,
        digest_of: children(indirect)[0].content, attributes: true, key, certificate })));
    const certificate_length = 8 + pkcs7.length;
    const win_certificate = Buffer.alloc(certificate_length + (-certificate_length & 7));
    win_certificate.writeUInt32LE(certificate_length, 0);
    win_certificate.writeUInt16LE(0x0200, 4);
    win_certificate.writeUInt16LE(0x0002, 6);
    pkcs7.copy(win_certificate, 8);
    const signed = new Uint8Array(Buffer.concat([unsigned, win_certificate]));
    const signed_view = new DataView(signed.buffer);
    signed_view.setUint32(security, unsigned.length, true);
    signed_view.setUint32(security + 4, win_certificate.length, true);
    return signed;
}

// --- variable updates

/** EFI_TIME of a date (UTC) */
export function efi_time(date)
{
    const time = Buffer.alloc(16);
    time.writeUInt16LE(date.getUTCFullYear(), 0);
    time[2] = date.getUTCMonth() + 1;
    time[3] = date.getUTCDate();
    time[4] = date.getUTCHours();
    time[5] = date.getUTCMinutes();
    time[6] = date.getUTCSeconds();
    return time;
}

/**
 * A time-based authenticated variable update: EFI_VARIABLE_AUTHENTICATION_2
 * (its time, a WIN_CERTIFICATE_UEFI_GUID with the PKCS #7 SignedData) and the data
 * @param {{name: string, guid: string, attributes: number, time: !Date, data: !Uint8Array, signer: {key: !crypto.KeyObject, certificate: !Uint8Array}}} o
 */
export function signed_update({ name, guid: vendor, attributes, time, data, signer })
{
    const timestamp = efi_time(time);
    const attributes_bytes = Buffer.alloc(4);
    attributes_bytes.writeUInt32LE(attributes, 0);
    const signed = Buffer.concat([Buffer.from(name, "utf16le"), Buffer.from(guid(vendor)), attributes_bytes, timestamp, Buffer.from(data)]);
    // (the bare SignedData, detached; no authenticated attributes)
    const pkcs7 = signed_data({ content_type: OID_DATA, content: null, digest_of: signed, attributes: false, ...signer });
    const header = Buffer.alloc(24);
    header.writeUInt32LE(24 + pkcs7.length, 0);
    header.writeUInt16LE(0x0200, 4);
    header.writeUInt16LE(0x0EF1, 6);
    Buffer.from(guid("4aafd29d-68df-49ee-8aa9-347d375665a7")).copy(header, 8);
    return new Uint8Array(Buffer.concat([timestamp, header, pkcs7, Buffer.from(data)]));
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/lib/fat.mjs                                                                        0000644 0000000 0000000 00000013232 00000000000 013062  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A FAT16 disk image with directories, in memory: one MBR partition of type
// 0xEF (an EFI System Partition), 2 KiB clusters, 8.3 names (upper case):
// what a UEFI boot manager reads \EFI\BOOT\BOOTX64.EFI from. For tests that
// should not depend on a host's tools (tests/uefi/secure_boot.mjs).

const SECTOR = 512;
const PARTITION = 2048;
const CLUSTER_SECTORS = 4;
const CLUSTER = CLUSTER_SECTORS * SECTOR;
const ROOT_ENTRIES = 512;

/**
 * @param {!Object<string, !Uint8Array>} files by path ("EFI/BOOT/BOOTX64.EFI")
 * @param {number=} size_mb the disk's size (at least 16)
 * @return {!Uint8Array}
 */
export function make_esp(files, size_mb = 64)
{
    const disk = new Uint8Array(size_mb << 20), view = new DataView(disk.buffer);
    const sectors = disk.length / SECTOR - PARTITION;
    const clusters = Math.floor(sectors / CLUSTER_SECTORS);
    const fat_sectors = Math.ceil((clusters + 2) * 2 / SECTOR);
    const boot = PARTITION * SECTOR, fat = boot + SECTOR, root = fat + 2 * fat_sectors * SECTOR;
    const data = root + ROOT_ENTRIES * 32;
    const total_clusters = Math.floor((disk.length - data) / CLUSTER);
    if(total_clusters < 4085 || total_clusters > 65524) throw new Error("not a FAT16 size: " + size_mb + " MiB");

    // the MBR: one partition, type 0xEF
    disk[446] = 0x00;
    disk.set([0xFE, 0xFF, 0xFF], 447);
    disk[450] = 0xEF;
    disk.set([0xFE, 0xFF, 0xFF], 451);
    view.setUint32(454, PARTITION, true);
    view.setUint32(458, sectors, true);
    view.setUint16(510, 0xAA55, true);
    // the boot sector's BIOS parameter block
    disk.set([0xEB, 0x3C, 0x90], boot);
    disk.set(Buffer.from("V86 ESP "), boot + 3);
    view.setUint16(boot + 11, SECTOR, true);
    disk[boot + 13] = CLUSTER_SECTORS;
    view.setUint16(boot + 14, 1, true);
    disk[boot + 16] = 2;
    view.setUint16(boot + 17, ROOT_ENTRIES, true);
    view.setUint16(boot + 19, sectors < 0x10000 ? sectors : 0, true);
    disk[boot + 21] = 0xF8;
    view.setUint16(boot + 22, fat_sectors, true);
    view.setUint16(boot + 24, 63, true);
    view.setUint16(boot + 26, 255, true);
    view.setUint32(boot + 28, PARTITION, true);
    view.setUint32(boot + 32, sectors < 0x10000 ? 0 : sectors, true);
    disk[boot + 36] = 0x80;
    disk[boot + 38] = 0x29;
    view.setUint32(boot + 39, 0x86E5B007, true);
    disk.set(Buffer.from("V86 ESP    FAT16   "), boot + 43);
    view.setUint16(boot + 510, 0xAA55, true);

    const fat_entry = (cluster, value) => view.setUint16(fat + cluster * 2, value, true);
    fat_entry(0, 0xFFF8);
    fat_entry(1, 0xFFFF);
    let next = 2;
    /** Clusters for bytes (at least one), chained: the first */
    const allocate = bytes =>
    {
        const count = Math.max(1, Math.ceil(bytes.length / CLUSTER));
        if(next + count > total_clusters + 2) throw new Error("the files do not fit the disk");
        const first = next;
        for(let i = 0; i < count; i++) fat_entry(first + i, i + 1 === count ? 0xFFFF : first + i + 1);
        disk.set(bytes, data + (first - 2) * CLUSTER);
        next += count;
        return first;
    };
    const name83 = name =>
    {
        const [base, extension = ""] = name.toUpperCase().split(".");
        if(!base || base.length > 8 || extension.length > 3) throw new Error("not an 8.3 name: " + name);
        return Buffer.from(base.padEnd(8) + extension.padEnd(3), "ascii");
    };
    const entry = (name, attributes, cluster, size) =>
    {
        const e = new Uint8Array(32), v = new DataView(e.buffer);
        e.set(typeof name === "string" ? name83(name) : name, 0);
        e[11] = attributes;
        v.setUint16(22, 0, true);
        v.setUint16(24, (46 << 9) | (10 << 5) | 27, true);
        v.setUint16(26, cluster, true);
        v.setUint32(28, size, true);
        return e;
    };

    // the tree: directories and files
    const tree = new Map();
    for(const [path, bytes] of Object.entries(files))
    {
        const parts = path.split("/");
        let node = tree;
        for(const part of parts.slice(0, -1))
        {
            if(!node.has(part)) node.set(part, new Map());
            node = node.get(part);
        }
        node.set(parts[parts.length - 1], bytes);
    }
    /** A directory's entries, its subdirectories written first (cluster of the directory itself: parent's ".." needs it) */
    const write_directory = (node, self, parent) =>
    {
        const entries = [];
        if(self)
        {
            entries.push(entry(Buffer.from(".          "), 0x10, self, 0), entry(Buffer.from("..         "), 0x10, parent, 0));
        }
        for(const [name, child] of node)
        {
            if(child instanceof Map)
            {
                // (its cluster first, then its entries into it)
                const size = (child.size + 2) * 32;
                const cluster = allocate(new Uint8Array(size));
                const bytes = write_directory(child, cluster, self);
                disk.set(bytes, data + (cluster - 2) * CLUSTER);
                if(bytes.length > Math.max(1, Math.ceil(size / CLUSTER)) * CLUSTER) throw new Error("directory too large");
                entries.push(entry(name, 0x10, cluster, 0));
            }
            else
            {
                entries.push(entry(name, 0x20, child.length ? allocate(child) : 0, child.length));
            }
        }
        const bytes = new Uint8Array(entries.length * 32);
        entries.forEach((e, i) => bytes.set(e, i * 32));
        return bytes;
    };
    const root_bytes = write_directory(tree, 0, 0);
    if(root_bytes.length > ROOT_ENTRIES * 32) throw new Error("too many entries in the root directory");
    disk.set(root_bytes, root);
    disk.copyWithin(fat + fat_sectors * SECTOR, fat, fat + fat_sectors * SECTOR);
    return disk;
}
                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/lib/jit_switches.mjs                                                               0000644 0000000 0000000 00000002573 00000000000 015015  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The JIT switches in tests (docs/jit-unification-plan.md, cross-phase rule 1;
// src/jit_switches.js): JIT_SWITCHES="name=value,..." in the environment
// becomes the V86 option jit_switches, under a test's own values.

import { get_jit_switches, parse_jit_switches, set_jit_switches } from "../../src/jit_switches.js";

/** The switches of JIT_SWITCHES, { name: value } */
export function jit_switches_from_env(env = process.env)
{
    return parse_jit_switches(env["JIT_SWITCHES"] || "");
}

/** V86 options with the switches of JIT_SWITCHES added to their jit_switches */
export function with_jit_switches(options, env = process.env)
{
    const from_env = jit_switches_from_env(env);
    if(!Object.keys(from_env).length) return options;
    return { ...options, jit_switches: { ...from_env, ...parse_jit_switches(options.jit_switches) } };
}

function cpu_of(emulator)
{
    return emulator.v86 ? emulator.v86.cpu : emulator;
}

/** The switch values of an emulator (a V86, or its cpu) */
export function jit_switches_of(emulator)
{
    const cpu = cpu_of(emulator);
    return get_jit_switches(cpu.wm.exports, cpu.wasm_memory);
}

/** Sets switches of an emulator by name; throws like set_jit_switches */
export function set_emulator_jit_switches(emulator, values)
{
    const cpu = cpu_of(emulator);
    set_jit_switches(cpu.wm.exports, cpu.wasm_memory, values, "set_emulator_jit_switches");
}
                                                                                                                                     source/v64/tests/lib/picture_sink.mjs                                                               0000644 0000000 0000000 00000006201 00000000000 015005  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A screen adapter for Node that keeps the guest's picture, and PNG
// screenshots of it (tests/x64/linux_gpu.mjs, tests/a64/android_boot.mjs)
import fs from "node:fs";
import path from "node:path";
import { deflateSync as deflate_sync } from "node:zlib";

/**
 * A presenter that keeps the guest's picture, for screenshots in node
 */
export class PictureSink
{
    constructor() { this.width = 0; this.height = 0; this.rgba = new Uint8Array(0); this.graphical = false; this.text = []; }
    set_mode(graphical) { this.graphical = graphical; }
    set_size_text(cols, rows) { this.text = Array.from({ length: rows }, () => " ".repeat(cols)); }
    set_size_graphical(width, height) { this.width = width; this.height = height; this.rgba = new Uint8Array(width * height * 4); }
    put_char(row, col, chr) { const line = this.text[row]; if(line !== undefined) this.text[row] = line.slice(0, col) + String.fromCharCode(chr) + line.slice(col + 1); }
    update_cursor() {}
    update_cursor_scanline() {}
    set_font_bitmap() {}
    set_font_page() {}
    clear_screen() {}
    clear_text_state() {}
    update_buffer(layers)
    {
        for(const layer of layers)
        {
            const { pixels } = layer;
            for(let y = 0; y < layer.buffer_height; y++)
            {
                const sy = layer.buffer_y + y, dy = layer.screen_y + y;
                if(dy >= this.height) break;
                const from = (sy * pixels.width + layer.buffer_x) * 4;
                const count = Math.min(layer.buffer_width, this.width - layer.screen_x) * 4;
                this.rgba.set(pixels.data.subarray(from, from + count), (dy * this.width + layer.screen_x) * 4);
            }
        }
    }
    pause() {}
    continue() {}
    destroy() {}
    set_scale() {}
    get_text_screen() { return this.text; }
    get_text_row(y) { return this.text[y] || ""; }
}

/** the picture as <directory>/<name>.png, or null before the first frame */
export function save_png(sink, directory, name)
{
    const { width, height, rgba } = sink;
    if(!width) return null;
    const raw = Buffer.alloc((width * 3 + 1) * height);
    for(let y = 0; y < height; y++)
    {
        for(let x = 0; x < width; x++)
        {
            const s = (y * width + x) * 4, d = y * (width * 3 + 1) + 1 + x * 3;
            raw[d] = rgba[s]; raw[d + 1] = rgba[s + 1]; raw[d + 2] = rgba[s + 2];
        }
    }
    const crc = data => { let c = 0xFFFFFFFF; for(const byte of data) { c ^= byte; for(let i = 0; i < 8; i++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; } return (c ^ 0xFFFFFFFF) >>> 0; };
    const chunk = (tag, data) => { const body = Buffer.concat([Buffer.from(tag), data]), b = Buffer.alloc(data.length + 12); b.writeUInt32BE(data.length); body.copy(b, 4); b.writeUInt32BE(crc(body), b.length - 4); return b; };
    const header = Buffer.alloc(13); header.writeUInt32BE(width); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 2;
    const file = path.join(directory, name + ".png");
    fs.writeFileSync(file, Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflate_sync(raw)), chunk("IEND", Buffer.alloc(0))]));
    return file;
}
                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/lib/png_compare.mjs                                                                0000644 0000000 0000000 00000007514 00000000000 014610  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // PNG screenshots compared (docs/gles-proxy-plan.md E3: the host GPU's
// home screen against the guest's own rendering): a PNG read back to RGBA
// (8-bit RGB or RGBA, any filter, not interlaced), and SSIM over the
// luminance in 8 by 8 windows (Wang et al. 2004's constants), 1 for the
// same picture.
import fs from "node:fs";
import { inflateSync as inflate_sync } from "node:zlib";

/**
 * @param {string} file
 * @return {{width: number, height: number, rgba: !Uint8Array}}
 */
export function read_png(file)
{
    const data = fs.readFileSync(file);
    const width = data.readUInt32BE(16), height = data.readUInt32BE(20), depth = data[24], type = data[25];
    if(depth !== 8 || (type !== 2 && type !== 6) || data[28]) throw new Error(`${file}: an 8-bit RGB or RGBA PNG, not interlaced`);
    const idat = [];
    for(let at = 8; at < data.length;)
    {
        const length = data.readUInt32BE(at), tag = data.toString("latin1", at + 4, at + 8);
        if(tag === "IDAT") idat.push(data.subarray(at + 8, at + 8 + length));
        at += 12 + length;
    }
    const raw = inflate_sync(Buffer.concat(idat));
    const bpp = type === 6 ? 4 : 3, stride = width * bpp;
    const rgba = new Uint8Array(width * height * 4);
    let previous = new Uint8Array(stride);
    for(let y = 0; y < height; y++)
    {
        const filter = raw[y * (stride + 1)];
        const line = Uint8Array.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
        for(let i = 0; i < stride; i++)
        {
            const a = i >= bpp ? line[i - bpp] : 0, b = previous[i], c = i >= bpp ? previous[i - bpp] : 0;
            let p = 0;
            if(filter === 1) p = a;
            else if(filter === 2) p = b;
            else if(filter === 3) p = (a + b) >> 1;
            else if(filter === 4)
            {
                const q = a + b - c, pa = Math.abs(q - a), pb = Math.abs(q - b), pc = Math.abs(q - c);
                p = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
            }
            line[i] = line[i] + p & 255;
        }
        for(let x = 0; x < width; x++)
        {
            rgba.set(line.subarray(x * bpp, x * bpp + 3), (y * width + x) * 4);
            rgba[(y * width + x) * 4 + 3] = bpp === 4 ? line[x * bpp + 3] : 255;
        }
        previous = line;
    }
    return { width, height, rgba };
}

/**
 * The mean SSIM of two pictures' luminance, in 8 by 8 windows
 * @param {{width: number, height: number, rgba: !Uint8Array}} a
 * @param {{width: number, height: number, rgba: !Uint8Array}} b the same size
 * @return {number}
 */
export function ssim(a, b)
{
    if(a.width !== b.width || a.height !== b.height) throw new Error(`${a.width}x${a.height} and ${b.width}x${b.height}`);
    const luma = p => Float64Array.from({ length: p.width * p.height }, (_, i) =>
        0.299 * p.rgba[4 * i] + 0.587 * p.rgba[4 * i + 1] + 0.114 * p.rgba[4 * i + 2]);
    const la = luma(a), lb = luma(b);
    const C1 = (0.01 * 255) ** 2, C2 = (0.03 * 255) ** 2;
    let sum = 0, windows = 0;
    for(let y = 0; y + 8 <= a.height; y += 8)
    {
        for(let x = 0; x + 8 <= a.width; x += 8)
        {
            let ma = 0, mb = 0;
            for(let j = 0; j < 8; j++) for(let i = 0; i < 8; i++) { ma += la[(y + j) * a.width + x + i]; mb += lb[(y + j) * a.width + x + i]; }
            ma /= 64; mb /= 64;
            let va = 0, vb = 0, cov = 0;
            for(let j = 0; j < 8; j++)
            {
                for(let i = 0; i < 8; i++)
                {
                    const da = la[(y + j) * a.width + x + i] - ma, db = lb[(y + j) * a.width + x + i] - mb;
                    va += da * da; vb += db * db; cov += da * db;
                }
            }
            va /= 63; vb /= 63; cov /= 63;
            sum += (2 * ma * mb + C1) * (2 * cov + C2) / ((ma * ma + mb * mb + C1) * (va + vb + C2));
            windows++;
        }
    }
    return sum / windows;
}
                                                                                                                                                                                    source/v64/tests/lib/site.mjs                                                                       0000644 0000000 0000000 00000001204 00000000000 013250  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The owner's retro-gaming-site checkout (the Windows images and the
// Windows 98 states): next to the main v86 checkout, found from a worktree
// (build/wt-*) too through git's common directory
import { spawnSync } from "node:child_process";
import path from "node:path";

/** @param {string} root a v86 tree (the main checkout or a worktree) */
export function site_directory(root)
{
    const r = spawnSync("git", ["-C", root, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8" });
    const main = r.status === 0 ? path.dirname(r.stdout.trim()) : root;
    return path.resolve(main, "../retro-gaming-site");
}
                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/lib/smp_modes.mjs                                                                  0000644 0000000 0000000 00000003615 00000000000 014302  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The execution modes of the SMP tests (SMP_MODES; docs/jit-unification-plan.md
// M7 acceptance: the SMP matrix includes the page tier). "pages" is the
// default configuration since Legacy32's flip: 32-bit protected-mode code in
// the x64 page tier (x64_page_legacy32; IR Tier-0's "tier0" mode went with it
// in P7.5). The "region" mode, ir_tier0 off so that the region tiers ran that
// code, went with the region tiers in M11.

import { with_jit_switches } from "./jit_switches.mjs";

export const SMP_MODES = ["interpreter", "pages"];

/** The modes of SMP_MODES, else `fallback` */
export function smp_modes(fallback = SMP_MODES, env = process.env)
{
    const modes = env.SMP_MODES ? env.SMP_MODES.split(",") : fallback;
    if(!modes.every(mode => SMP_MODES.includes(mode))) throw new Error("SMP_MODES: " + SMP_MODES.join(", "));
    return modes;
}

/**
 * V86 options with `mode`'s ir_tier0 and JIT switches (and JIT_SWITCHES); with
 * `eager`, the page tier compiles a page after a few instructions
 */
export function with_smp_mode(options, mode, eager = true)
{
    const switches = mode === "pages" && eager ? { x64_legacy_heat: 2 } : {};
    return with_jit_switches({
        ...options,
        ir_tier0: mode === "pages",
        jit_switches: { ...switches, ...options.jit_switches },
    });
}

/** Compiled execution so far: instructions the page tier ran natively */
export function compiled_hits(exports)
{
    return exports.x64_page_stat(1) >>> 0;
}

/** Compiled execution in `mode`'s own engine (compiled_hits for the interpreter) */
export function mode_hits(exports, mode)
{
    switch(mode)
    {
        case "pages": return exports.x64_page_stat(1) >>> 0;
        default: return compiled_hits(exports);
    }
}

/** Code at linear (= physical) `address` is published: a page function of its page */
export function published(exports, address)
{
    return !!exports.x64_page_published(address);
}
                                                                                                                   source/v64/tests/lib/tpm_event_log.mjs                                                              0000644 0000000 0000000 00000004371 00000000000 015156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A TPM 2.0 event log (tests/tpm/): replayed, the PCRs it gives.

import assert from "node:assert/strict";
import crypto from "node:crypto";

/**
 * A crypto-agile TCG event log (TCG PC Client Platform Firmware Profile,
 * 10.2): the first event in the SHA-1 format, its Spec ID event naming the
 * digests of the others. The SHA-256 PCRs it extends (from zero; PCR 0 from
 * a startup locality event's locality), and the number of events.
 * @param {!Buffer} log
 * @return {{pcrs: !Map<number, !Buffer>, events: number}}
 */
export function replay(log)
{
    let at = 0;
    const u32 = () => { const value = log.readUInt32LE(at); at += 4; return value; };
    const u16 = () => { const value = log.readUInt16LE(at); at += 2; return value; };
    // the first event: index, type, a SHA-1 digest, the Spec ID event
    u32();
    assert.equal(u32(), 3, "the first event is EV_NO_ACTION");
    at += 20;
    const spec_size = u32(), spec = at;
    assert.equal(log.toString("latin1", spec, spec + 15), "Spec ID Event03", "a crypto-agile log");
    at = spec + 24;
    const sizes = new Map();
    for(let n = u32(); n > 0; n--) sizes.set(u16(), u16());
    assert.ok(sizes.has(0x0B), "SHA-256 digests in the log");
    at = spec + spec_size;
    const pcrs = new Map();
    let events = 0;
    while(at < log.length)
    {
        const index = u32(), type = u32();
        let sha256 = null;
        for(let n = u32(); n > 0; n--)
        {
            const algorithm = u16();
            const digest = log.subarray(at, at + sizes.get(algorithm));
            at += sizes.get(algorithm);
            if(algorithm === 0x0B) sha256 = digest;
        }
        const size = u32();
        const data = log.subarray(at, at + size);
        at += size;
        events++;
        if(type === 3)
        {
            // (EV_NO_ACTION: not extended; "StartupLocality" sets PCR 0's start)
            if(data.toString("latin1", 0, 16) === "StartupLocality\0")
            {
                pcrs.set(0, Buffer.concat([Buffer.alloc(31), data.subarray(16, 17)]));
            }
            continue;
        }
        const old = pcrs.get(index) || Buffer.alloc(32);
        pcrs.set(index, crypto.createHash("sha256").update(Buffer.concat([old, sha256])).digest());
    }
    return { pcrs, events };
}
                                                                                                                                                                                                                                                                       source/v64/tests/lib/uefi_disk.mjs                                                                  0000644 0000000 0000000 00000006354 00000000000 014261  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A GPT disk with an EFI System Partition that boots Alpine 3.24 x86_64
// under UEFI from the disk alone (docs/uefi.md; the plan's F1, GPT/ESP cold
// boot): the pinned virt ISO's tree (tests/lib/alpine_image.mjs) on a FAT32
// ESP. Its GRUB (efi/boot/bootx64.efi, what the boot manager starts from a
// disk without boot entries) searches for the ISO's volume label, finds none,
// and reads /boot/grub/grub.cfg of the ESP it was loaded from: here, with the
// serial console. Alpine's initramfs then finds its packages and modloop on
// the ESP, as on a USB stick. hdiutil (macOS) makes the FAT32 volume. The
// flavour "lts" has the standard ISO's LTS kernel (TPM drivers among its
// modules: docs/tpm.md).

import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { prepare as prepare_alpine, ROOT } from "./alpine_image.mjs";
import { gpt_writes } from "../../src/android/gpt.js";

export const ESP_TYPE = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B";
const MiB = 1 << 20;

/** @param {string} flavor */
const grub_cfg = flavor => `set timeout=1
menuentry "Alpine ${flavor} (UEFI, from the ESP)" {
linux /boot/vmlinuz-${flavor} console=ttyS0,115200 loglevel=4 modules=loop,squashfs,sd-mod,vfat,nls_cp437,nls_iso8859-1
initrd /boot/initramfs-${flavor}
}
`;

function run(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    if(result.status !== 0) throw new Error(program + " " + args.join(" ") + ": " + (result.stderr || result.error));
}

/**
 * The disk (built once, in build/uefi/): its path
 * @param {string=} flavor "virt" (the virt ISO) or "lts" (the standard ISO)
 * @return {Promise<string>}
 */
export async function prepare_esp_disk(flavor = "virt")
{
    const directory = ROOT + "build/uefi/";
    const disk = directory + (flavor === "virt" ? "alpine-esp.img" : "alpine-esp-" + flavor + ".img");
    if(fs.existsSync(disk)) return disk;
    const alpine = await prepare_alpine("x86_64-" + flavor);
    const volume_size = (flavor === "virt" ? 128 : 512) * MiB;
    fs.mkdirSync(directory, { recursive: true });

    const tree = directory + "esp/";
    fs.rmSync(tree, { recursive: true, force: true });
    fs.mkdirSync(tree);
    run("bsdtar", ["-xf", alpine.iso, "-C", tree]);
    run("chmod", ["-R", "u+w", tree]);
    // (BIOS boot, and the CD's El Torito image of the loader)
    fs.rmSync(tree + "boot/syslinux", { recursive: true });
    fs.rmSync(tree + "boot/grub/efi.img");
    fs.writeFileSync(tree + "boot/grub/grub.cfg", grub_cfg(flavor));

    run("hdiutil", ["create", "-quiet", "-size", volume_size / MiB + "m", "-fs", "MS-DOS FAT32", "-volname", "ALPINE", "-srcfolder", tree,
        "-format", "UDTO", "-layout", "NONE", "-ov", directory + "esp-volume"]);
    const volume = fs.readFileSync(directory + "esp-volume.cdr");
    fs.rmSync(directory + "esp-volume.cdr");
    fs.rmSync(tree, { recursive: true });

    const disk_size = MiB + volume.length + MiB;
    const bytes = Buffer.alloc(disk_size);
    for(const { offset, bytes: write } of gpt_writes(disk_size, [{ name: "ESP", start: MiB, size: volume.length, type: ESP_TYPE }]))
    {
        bytes.set(write, offset);
    }
    bytes.set(volume, MiB);
    fs.writeFileSync(disk + ".part", bytes);
    fs.renameSync(disk + ".part", disk);
    return disk;
}
                                                                                                                                                                                                                                                                                    source/v64/tests/manual/gc.html                                                                     0000644 0000000 0000000 00000002064 00000000000 013564  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<title>Test that emulator is GCed properly</title>

<script src="../../build/libv86.js"></script>
<script>
"use strict";

window.onload = function()
{
    var emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: "../../build/v86.wasm",
        memory_size: 32 * 1024 * 1024,
        vram_size: 2 * 1024 * 1024,
        screen_container: document.getElementById("screen_container"),
        bios: { url: "../../bios/seabios.bin" },
        vga_bios: { url: "../../bios/vgabios.bin" },
        cdrom: { url: "../../images/linux.iso" },
        autostart: true,
    });

    setTimeout(() => {
        emulator.destroy();
        console.log("Emulator freed. Check using devtools (in chromium: Memory -> Heap Snapshot -> click collect garbage -> take snapshot).");
    }, 3 * 1000);
}
</script>

<!-- A minimal structure for the ScreenAdapter defined in browser/screen.js -->
<div id="screen_container">
    <div style="white-space: pre; font: 14px monospace; line-height: 14px"></div>
    <canvas style="display: none"></canvas>
</div>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/Readme.md                                                                     0000644 0000000 0000000 00000000234 00000000000 013502  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # About

The tests in this folder are not comprehensive by any means at the
moment.

# Automated Testing

- Run `make nasmtests` in the root of the project
                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/arith-optimisations.asm                                                       0000644 0000000 0000000 00000000335 00000000000 016476  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    xor eax, eax
    pushf
    and dword [esp], 8ffh

    test ebx, ebx
    pushf
    and dword [esp], 8ffh

    cmp ecx, 0
    pushf
    and dword [esp], 8ffh

%include "footer.inc"
                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/btc-imm.asm                                                                   0000644 0000000 0000000 00000001307 00000000000 014017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0x03479aef
    mov dword [esp+4], 0x03479aef
    mov dword [esp+8], 0x03479aef
    mov dword [esp+12], 0x03479aef
    mov dword [esp+16], 0x03479aef
    mov dword [esp+20], 0x03479aef
    mov dword [esp+24], 0x03479aef
    mov dword [esp+28], 0x03479aef

    btc word [esp], 0
    btc word [esp], 4
    btc word [esp], 9
    btc word [esp], 16
    btc word [esp], 31
    btc word [esp], 32
    btc word [esp], 55
    btc word [esp], 200

    btc dword [esp], 1
    btc dword [esp], 5
    btc dword [esp], 10
    btc dword [esp], 17
    btc dword [esp], 30
    btc dword [esp], 33
    btc dword [esp], 56
    btc dword [esp], 201

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                         source/v64/tests/nasm/btc-reg16.asm                                                                 0000644 0000000 0000000 00000001144 00000000000 014160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0x03479aef
    mov dword [esp+4], 0x03479aef
    mov dword [esp+8], 0x03479aef
    mov dword [esp+12], 0x03479aef
    mov dword [esp+16], 0x03479aef
    mov dword [esp+20], 0x03479aef
    mov dword [esp+24], 0x03479aef
    mov dword [esp+28], 0x03479aef

    mov eax, 0
    btc word [esp], ax
    mov eax, -5
    btc word [esp + 4], ax
    mov eax, 1
    btc word [esp], ax
    mov eax, 31
    btc word [esp], ax
    mov eax, 32
    btc word [esp], ax
    mov eax, 63
    btc word [esp], ax
    mov eax, 99
    btc word [esp], ax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/btc-reg32.asm                                                                 0000644 0000000 0000000 00000001162 00000000000 014156  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0x03479aef
    mov dword [esp+4], 0x03479aef
    mov dword [esp+8], 0x03479aef
    mov dword [esp+12], 0x03479aef
    mov dword [esp+16], 0x03479aef
    mov dword [esp+20], 0x03479aef
    mov dword [esp+24], 0x03479aef
    mov dword [esp+28], 0x03479aef

    mov eax, 0
    btc dword [esp], eax
    mov eax, -5
    btc dword [esp + 4], eax
    mov eax, 1
    btc dword [esp], eax
    mov eax, 31
    btc dword [esp], eax
    mov eax, 32
    btc dword [esp], eax
    mov eax, 63
    btc dword [esp], eax
    mov eax, 99
    btc dword [esp], eax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/nasm/btr-imm.asm                                                                   0000644 0000000 0000000 00000001207 00000000000 014035  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], -1
    mov dword [esp+4], -1
    mov dword [esp+8], -1
    mov dword [esp+12], -1
    mov dword [esp+16], -1
    mov dword [esp+20], -1
    mov dword [esp+24], -1
    mov dword [esp+28], -1

    btr word [esp], 0
    btr word [esp], 4
    btr word [esp], 9
    btr word [esp], 16
    btr word [esp], 31
    btr word [esp], 32
    btr word [esp], 55
    btr word [esp], 200

    btr dword [esp], 1
    btr dword [esp], 5
    btr dword [esp], 10
    btr dword [esp], 17
    btr dword [esp], 30
    btr dword [esp], 33
    btr dword [esp], 56
    btr dword [esp], 201

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/nasm/btr-reg16.asm                                                                 0000644 0000000 0000000 00000001044 00000000000 014176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], -1
    mov dword [esp+4], -1
    mov dword [esp+8], -1
    mov dword [esp+12], -1
    mov dword [esp+16], -1
    mov dword [esp+20], -1
    mov dword [esp+24], -1
    mov dword [esp+28], -1

    mov eax, 0
    btr word [esp], ax
    mov eax, -5
    btr word [esp + 4], ax
    mov eax, 1
    btr word [esp], ax
    mov eax, 31
    btr word [esp], ax
    mov eax, 32
    btr word [esp], ax
    mov eax, 63
    btr word [esp], ax
    mov eax, 99
    btr word [esp], ax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/btr-reg32.asm                                                                 0000644 0000000 0000000 00000001062 00000000000 014174  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], -1
    mov dword [esp+4], -1
    mov dword [esp+8], -1
    mov dword [esp+12], -1
    mov dword [esp+16], -1
    mov dword [esp+20], -1
    mov dword [esp+24], -1
    mov dword [esp+28], -1

    mov eax, 0
    btr dword [esp], eax
    mov eax, -5
    btr dword [esp + 4], eax
    mov eax, 1
    btr dword [esp], eax
    mov eax, 31
    btr dword [esp], eax
    mov eax, 32
    btr dword [esp], eax
    mov eax, 63
    btr dword [esp], eax
    mov eax, 99
    btr dword [esp], eax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/nasm/bts-imm.asm                                                                   0000644 0000000 0000000 00000001177 00000000000 014044  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0
    mov dword [esp+4], 0
    mov dword [esp+8], 0
    mov dword [esp+12], 0
    mov dword [esp+16], 0
    mov dword [esp+20], 0
    mov dword [esp+24], 0
    mov dword [esp+28], 0

    bts word [esp], 0
    bts word [esp], 4
    bts word [esp], 9
    bts word [esp], 16
    bts word [esp], 31
    bts word [esp], 32
    bts word [esp], 55
    bts word [esp], 200

    bts dword [esp], 1
    bts dword [esp], 5
    bts dword [esp], 10
    bts dword [esp], 17
    bts dword [esp], 30
    bts dword [esp], 33
    bts dword [esp], 56
    bts dword [esp], 201

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/nasm/bts-reg16.asm                                                                 0000644 0000000 0000000 00000001034 00000000000 014176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0
    mov dword [esp+4], 0
    mov dword [esp+8], 0
    mov dword [esp+12], 0
    mov dword [esp+16], 0
    mov dword [esp+20], 0
    mov dword [esp+24], 0
    mov dword [esp+28], 0

    mov eax, 0
    bts word [esp], ax
    mov eax, -5
    bts word [esp + 4], ax
    mov eax, 1
    bts word [esp], ax
    mov eax, 31
    bts word [esp], ax
    mov eax, 32
    bts word [esp], ax
    mov eax, 63
    bts word [esp], ax
    mov eax, 99
    bts word [esp], ax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/bts-reg32.asm                                                                 0000644 0000000 0000000 00000001052 00000000000 014174  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp], 0
    mov dword [esp+4], 0
    mov dword [esp+8], 0
    mov dword [esp+12], 0
    mov dword [esp+16], 0
    mov dword [esp+20], 0
    mov dword [esp+24], 0
    mov dword [esp+28], 0

    mov eax, 0
    bts dword [esp], eax
    mov eax, -5
    bts dword [esp + 4], eax
    mov eax, 1
    bts dword [esp], eax
    mov eax, 31
    bts dword [esp], eax
    mov eax, 32
    bts dword [esp], eax
    mov eax, 63
    bts dword [esp], eax
    mov eax, 99
    bts dword [esp], eax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/nasm/cmp16-setbe.asm                                                               0000644 0000000 0000000 00000000150 00000000000 014510  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ax, -1
    cmp ax, -3
    setbe bl

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/nasm/cmpxchg-setbe.asm                                                             0000644 0000000 0000000 00000000176 00000000000 015223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov eax, 1
    mov edx, 2
    cmpxchg eax, edx
    setbe  cl

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/nasm/cmpxchg.asm                                                                   0000644 0000000 0000000 00000000660 00000000000 014121  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data

%include "header.inc"

    mov eax, 123456789
    mov ebx, 123456789
    mov edx, 123456789

    cmpxchg edx, ebx
    push eax
    push edx
    push ebx
    pushf
    and dword [esp], 8ffh

    cmpxchg ax, bx
    push eax
    push edx
    push ebx
    pushf
    and dword [esp], 8ffh

    cmpxchg al, bh
    push eax
    push edx
    push ebx
    pushf
    and dword [esp], 8ffh

%include "footer.inc"
                                                                                source/v64/tests/nasm/cmpxchg8b.asm                                                                 0000644 0000000 0000000 00000000450 00000000000 014350  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data

%include "header.inc"

    mov eax, 123456789
    mov edx, 987654321

    mov dword [esp], 123456789
    mov dword [esp+4], 987654321

    cmpxchg8b [esp]
    push eax
    push ecx
    push ebx
    push edx
    pushf
    and dword [esp], 8ffh

%include "footer.inc"
                                                                                                                                                                                                                        source/v64/tests/nasm/comiss.asm                                                                    0000644 0000000 0000000 00000001655 00000000000 013772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
controlword:
	dw	0
dwordmxcsr:
	dw	0
dword0:
	dd	1000.0
dword1:
	dd	5.0
dword2:
	dd	3000.0
dwSNaN:
	dd	__SNaN__
dwQNaN:
	dd	__QNaN__

; Moves EFLAGS into specified register
%macro moveflags 1
	pushf
	and			dword [esp], 0x45
	pop			eax
	movd		%1, eax
%endmacro

%include "header.inc"

	movd		xmm0, [dword0]
	; Equal
	comiss		xmm0, [dword0]
	moveflags	mm0				; [ZF] = 100000
	; Less than
	comiss		xmm0, [dword1]
	moveflags	mm1				; [CF] = 000001
	; Greater than
	comiss		xmm0, [dword2]
	moveflags	mm2				; [] = 000000

	; Unordered: Quiet NaN
	movd		xmm1, [dwQNaN]
	ucomiss		xmm0, xmm1
	moveflags	mm3				; [ZF][PF][CF] = 100101
	; Check #I exception
	stmxcsr		[dwordmxcsr]
	movd		mm4, [dwordmxcsr]

	; Unordered: Signaling NaN
	movd		xmm1,[dwSNaN]
	ucomiss		xmm0, xmm1
	moveflags	mm5				; [ZF][PF][CF] = 100101
	; Check #I exception
	stmxcsr		[dwordmxcsr]
	movd		mm6, [dwordmxcsr]

%include "footer.inc"
                                                                                   source/v64/tests/nasm/create_tests.js                                                               0000755 0000000 0000000 00000054574 00000000000 015031  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import fse from "node:fs/promises";
import path from "node:path";
import assert from "node:assert/strict";
import util from "node:util";
import url from "node:url";
import { execFile, spawnSync } from "node:child_process";

import encodings, { opcode_map, opcode_prefix } from "../../gen/x86_table.js";
import Rand from "./rand.js";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

// GNU ld where it links i386 ELF; otherwise (macOS) Rust's own rust-lld
// (LD_LLD selects another lld)
const LINKER = (() => {
    const gnu = spawnSync("ld", ["-V"], { encoding: "utf8" });
    if(gnu.status === 0 && gnu.stdout.includes("elf_i386")) return ["ld"];
    // (lld's image starts at 4 MiB unless told otherwise; one page below the
    // .multiboot section, its header stays in the file's first 8 KiB as the
    // multiboot loaders require)
    // (and the entry is .text's start, where GNU ld also puts it: `_start` is not global)
    const lld_args = ["-flavor", "gnu", "--image-base=0x1F000", "-z", "max-page-size=4096", "-e", "0x80000"];
    if(process.env.LD_LLD) return [process.env.LD_LLD, ...lld_args];
    const target = spawnSync("rustc", ["-vV"], { encoding: "utf8" }).stdout.match(/host: (.+)/)[1];
    const sysroot = spawnSync("rustc", ["--print", "sysroot"], { encoding: "utf8" }).stdout.trim();
    return [path.join(sysroot, "lib/rustlib", target, "bin/rust-lld"), ...lld_args];
})();

// number of tests per instruction
const NUMBER_TESTS = 5;
// arithmetic tests
const NUMBER_ARITH_TESTS = 100;

const MAX_PARALLEL_PROCS = +process.env.MAX_PARALLEL_PROCS || 32;

const FLAGS_IGNORE = 0xFFFF3200;
const CF = 1 << 0;
const PF = 1 << 2;
const AF = 1 << 4;
const ZF = 1 << 6;
const SF = 1 << 7;
const OF = 1 << 11;

const BUILD_DIR = __dirname + "/build/";
const LOG_VERBOSE = false;

const exec_file = util.promisify(execFile);

const header = fs.readFileSync(path.join(__dirname, "header.inc"));
const footer = fs.readFileSync(path.join(__dirname, "footer.inc"));

main();

async function main()
{
    try
    {
        fs.mkdirSync(BUILD_DIR);
    }
    catch(e)
    {
        if(e.code !== "EEXIST")
        {
            throw e;
        }
    }

    const tests = create_tests().reverse();

    const workers = [];
    for(let i = 0; i < MAX_PARALLEL_PROCS; i++)
    {
        workers.push(worker(make_test, tests));
    }

    await Promise.all(workers);
}

async function worker(f, work)
{
    while(work.length)
    {
        await f(work.pop());
    }
}

async function make_test(test)
{
    LOG_VERBOSE && console.log("Start", test.name || test.file);
    let asm_file;
    let img_file;
    let tmp_file;

    assert((test.asm && test.name) || test.file);
    if(test.asm)
    {
        asm_file = BUILD_DIR + test.name + ".asm";
        img_file = BUILD_DIR + test.name + ".img";
        tmp_file = "/tmp/" + test.name + ".o";

        let old_code = undefined;

        try
        {
            old_code = await fse.readFile(asm_file, { encoding: "ascii" });
        }
        catch(e)
        {
        }

        if(old_code === test.asm)
        {
            LOG_VERBOSE && console.log("Skip", test.name || test.file);
            return;
        }

        await fse.writeFile(asm_file, test.asm);
    }
    else
    {
        asm_file = path.join(__dirname, test.file);
        img_file = BUILD_DIR + test.file.replace(/\.asm$/, ".img");
        tmp_file = "/tmp/" + test.file + ".o";

        try
        {
            if((await fse.stat(asm_file)).mtime < (await fse.stat(img_file)).mtime)
            {
                return;
            }
        }
        catch(e)
        {
            if(e.code !== "ENOENT") throw e;
        }
    }

    const options = {
        cwd: __dirname,
    };

    LOG_VERBOSE && console.log("nasm", ["-w+error", "-felf32", "-o", tmp_file, asm_file].join(" "));
    await exec_file("nasm", ["-w+error", "-felf32", "-o", tmp_file, asm_file], options);
    const ld_args = ["-g", tmp_file, "-m", "elf_i386", "--section-start=.bss=0x100000", "--section-start=.text=0x80000", "--section-start=.multiboot=0x20000", "-o", img_file];
    LOG_VERBOSE && console.log(LINKER.join(" "), ld_args.join(" "));
    await exec_file(LINKER[0], LINKER.slice(1).concat(ld_args), options);
    await fse.unlink(tmp_file);

    console.log(test.name || test.file);
}

function create_tests()
{
    const tests = [];

    const asm_files = fs.readdirSync(__dirname).filter(f => f.endsWith(".asm"));
    tests.push.apply(tests, asm_files.map(file => ({ file })));

    for(const op of encodings)
    {
        const configurations = [
            { mem: 0, size: 16, },
            { mem: 0, size: 32, },
            { mem: 1, size: 16, },
            { mem: 1, size: 32, },
        ];

        let i = 0;

        for(const config of configurations)
        {
            for(let nth_test = 0; nth_test < NUMBER_TESTS; nth_test++)
            {
                if(nth_test > 0 && op.opcode === 0x8D)
                {
                    // is already tested exhaustively in first run
                    continue;
                }

                for(const asm of create_instruction_test(op, config, nth_test))
                {
                    tests.push({
                        name: "gen_" + format_opcode(op.opcode) + "_" + (op.fixed_g || 0) + "_" + i,
                        asm,
                    });

                    i++;
                }
            }
        }
    }

    for(let i = 0; i < NUMBER_ARITH_TESTS; i++)
    {
        tests.push(create_arith_test(i));
    }

    return tests;
}

function format_opcode(n)
{
    let x = n.toString(16);
    return x.length % 2 ? "0" + x : x;
}

function create_nasm_modrm_combinations_16()
{
    let result = [];

    for(let modrm = 0; modrm < 0xC0; modrm++)
    {
        let mod = modrm >> 6;
        let rm = modrm & 7;

        let has_imm8 = mod === 1;
        let has_imm16 = mod === 2 || rm === 6 && mod === 0;

        assert(!has_imm8 || !has_imm16);

        let line = ["db " + modrm];
        if(has_imm8) line.push("db 9ah");
        if(has_imm16) line.push("dw 9a1fh");
        result.push(line);
    }

    return result;
}

function create_nasm_modrm_combinations_32()
{
    let result = [];

    let sample_sib_bytes = [0x05, 0x65, 0xAD, 0xCD, 0x20, 0xFF];
    let exhaustive_sib_bytes = [];
    for(let sib = 0; sib < 0x100; sib++) exhaustive_sib_bytes.push(sib);

    for(let modrm = 0; modrm < 0xC0; modrm++)
    {
        let mod = modrm >> 6;
        let reg = modrm >> 3 & 7;
        let rm = modrm & 7;

        let has_imm8 = mod === 1;
        let has_imm32 = mod === 2 || rm === 5 && mod === 0;
        let has_sib = rm === 4;

        assert(!has_imm8 || !has_imm32);

        if(has_sib)
        {
            // avoid generating an excessive number of tests
            let sib_bytes = reg === 0 ? exhaustive_sib_bytes : sample_sib_bytes;

            for(let sib of sib_bytes)
            {
                let line = ["db " + modrm, "db " + sib];
                if(has_imm8) line.push("db 9ah");
                if(has_imm32 || mod === 0 && (sib & 7) === 5) line.push("dd 9a1fbcdeh");
                result.push(line);
            }
        }
        else
        {
            let line = ["db " + modrm];
            if(has_imm8) line.push("db 9ah");
            if(has_imm32) line.push("dd 9a1fbcdeh");
            result.push(line);
        }
    }

    return result;
}

function rand_reg_but_not_esp(rng)
{
    let r = rng.int32() & 7;
    return r === 4 ? rand_reg_but_not_esp(rng) : r;
}

function interesting_immediate(rng)
{
    if(rng.int32() & 1)
    {
        return rng.int32();
    }
    else
    {
        return rng.int32() << (rng.int32() & 31) >> (rng.int32() & 31);
    }
}

function create_instruction_test(op, config, nth_test)
{
    if(op.prefix || op.skip)
    {
        return [];
    }

    if(config.mem ? op.skip_mem : op.skip_reg)
    {
        // Not supported by test
        return [];
    }

    if(!op.e)
    {
        if(config.mem)
        {
            // doesn't use memory, don't test both
            return [];
        }
    }

    if(!op.os)
    {
        if(config.size === 16)
        {
            // equivalent to 32-bit version, don't test both
            return [];
        }
    }

    const rng = new Rand(1283698341 ^ op.opcode + nth_test * 0x10000);

    const size = (op.os || op.opcode % 2 === 1) ? config.size : 8;
    const is_modrm = op.e || op.fixed_g !== undefined;

    const codes = [];

    for(let reg of ["eax", "ecx", "edx", "ebx", "ebp", "esi", "edi"])
    {
        let rand = rng.int32();
        codes.push("mov " + reg + ", " + rand);
    }

    if(!op.is_fpu) // generate random mmx registers
    {
        codes.push("sub esp, 8");
        for(let i = 0; i < 8; i++)
        {
            codes.push("mov dword [esp], " + rng.int32());
            codes.push("mov dword [esp + 4], " + rng.int32());
            codes.push("movq mm" + i + ", [esp]");
        }
        codes.push("add esp, 8");
    }
    else // generate random fpu registers
    {
        codes.push("finit");
        codes.push("sub esp, 8");

        for(let i = 0; i < 8; i++)
        {
            codes.push("mov dword [esp], " + rng.int32());
            codes.push("mov dword [esp + 4], " + rng.int32());
            codes.push("fld qword [esp]");
        }

        for(let i = 0; i < 4; i++) // half full stack
        {
            codes.push("fstp qword [esp]");
        }

        codes.push("add esp, 8");
    }

    if(true) // generate random xmm registers
    {
        codes.push("sub esp, 16");
        for(let i = 0; i < 8; i++)
        {
            codes.push("mov dword [esp], " + rng.int32());
            codes.push("mov dword [esp + 4], " + rng.int32());
            codes.push("mov dword [esp + 8], " + rng.int32());
            codes.push("mov dword [esp + 12], " + rng.int32());
            codes.push("movdqu xmm" + i + ", [esp]");
        }
        codes.push("add esp, 16");
    }

    if(true) // generate random stack memory
    {
        for(let i = 0; i < 8; i++)
        {
            codes.push("sub esp, 4");
            codes.push("mov dword [esp], " + rng.int32());
        }
    }

    codes.push("push dword " + (rng.int32() & ~(1 << 8 | 1 << 9)));
    codes.push("popf");

    if(rng.int32() & 1)
    {
        // generate random flags using arithmetic instruction
        // not well-distributed, but can trigger bugs in lazy flag calculation
        if(rng.int32() & 1)
        {
            // rarely sets zero flag, other flags mostly well-distributed
            codes.push("add al, ah");
        }
        else
        {
            // always sets zero flag
            codes.push("sub al, al");
        }
    }

    if(op.is_string)
    {
        codes.push("mov ecx, 3");
        codes.push("mov edi, (102000h-16)");
        codes.push("mov esi, (102000h-20)");
    }

    if(size === 16)
    {
        codes.push("db 66h ; 16 bit");
    }

    let opcode = op.opcode;

    if([0x0FA5, 0x0FAD].includes(op.opcode) && size === 16)
    {
        // shld/shrd: immediates larger than opsize are undefined behaviour,
        // but it's anded with 31 automatically, so only bit 4 needs to be cleared
        codes.push("and cl, ~16");
    }

    if(opcode === 0x8D)
    {
        // special case: lea: generate 16-bit addressing and all modrm combinations
        assert(is_modrm);

        codes.push([].concat(
            create_nasm_modrm_combinations_16().map(lines => ["db 67h", "db 8dh"].concat(lines).join("\n")),
            create_nasm_modrm_combinations_32().map(lines => ["db 8dh"].concat(lines).join("\n"))
        ));
    }
    else
    {
        if(opcode_map(opcode) === "0F38" || opcode_map(opcode) === "0F3A")
        {
            // the three-byte maps: mandatory prefix, 0F 38/3A, opcode
            if(opcode_prefix(opcode)) codes.push("db " + opcode_prefix(opcode));
            codes.push("db " + 0x0F, "db " + (opcode >> 8 & 0xFF), "db " + (opcode & 0xFF));
        }
        else
        {
            assert(opcode < 0x1000000);
            if(opcode >= 0x10000)
            {
                let c = opcode >> 16;
                assert(c === 0x66 || c === 0xF3 || c === 0xF2);
                codes.push("db " + c);
                opcode &= ~0xFF0000;
            }
            if(opcode >= 0x100)
            {
                let c = opcode >> 8;
                assert(c === 0x0F || c === 0xF2 || c === 0xF3, "Expected 0F, F2, or F3 prefix, got " + c.toString(16));
                codes.push("db " + c);
                opcode &= ~0xFF00;
            }
            codes.push("db " + opcode);
        }

        if(is_modrm)
        {
            let g = rand_reg_but_not_esp(rng);

            if(op.fixed_g !== undefined)
            {
                g = op.fixed_g;
            }

            if(config.mem)
            {
                const e = 0x04; // [esp]
                const sib = 0x24;

                codes.push("db " + (e | g << 3));
                codes.push("db " + sib);
            }
            else
            {
                const es =
                    op.is_fpu ? [0, 1, 2, 3, 4, 5, 6, 7] : [
                        rand_reg_but_not_esp(rng)
                    ];
                const modrm_bytes = es.map(e => "db " + (0xC0 | g << 3 | e));
                codes.push(modrm_bytes);
            }
        }
    }

    if(op.opcode === 0xC8) // special case: enter
    {
        codes.push("dw 8h");
        codes.push("db 0h");
    }
    else if(op.imm8 || op.imm8s || op.imm16 || op.imm1632 || op.imm32 || op.immaddr)
    {
        if(op.imm8 || op.imm8s)
        {
            if([0x0FA4, 0x0FAC].includes(op.opcode))
            {
                // shld/shrd: immediates larger than opsize are undefined behaviour
                codes.push("db " + (rng.int32() & (size === 16 ? 15 : 31)));
            }
            else
            {
                codes.push("db " + (rng.int32() & 0xFF));
            }
        }
        else
        {
            if(op.immaddr)
            {
                // immaddr: depends on address size
                // generate valid pointer into bss section
                codes.push("dd (102000h-16)");
            }
            else
            {
                assert(op.imm1632 || op.imm16 || op.imm32);

                if(op.imm1632 && size === 16 || op.imm16)
                {
                    codes.push("dw " + (rng.int32() & 0xFFFF));
                }
                else
                {
                    assert(op.imm1632 && size === 32 || op.imm32);
                    codes.push("dd " + rng.int32());
                }
            }
        }
    }

    if(op.mask_flags)
    {
        codes.push(
            "pushf",
            "and dword [esp], ~" + (op.mask_flags | FLAGS_IGNORE),
            "popf",
            "mov dword [esp-4], 0",
        );
    }

    if(op.opcode === 0x06 || op.opcode === 0x0E || op.opcode === 0x16 || op.opcode === 0x1E ||
        op.opcode === 0x0FA0 || op.opcode === 0x0FA8)
    {
        // push sreg: mask result
        if(size === 16)
        {
            codes.push("mov word [esp], 0");
        }
        else
        {
            // NOTE: upper word is undefined behaviour (unchanged on Intel, zero on AMD)
            codes.push("mov dword [esp], 0");
        }
    }

    return all_combinations(codes).map(c => {
        return header + c.join("\n") + "\n" + footer;
    });
}

function create_arith_test(i)
{
    const rng = new Rand(916237867 ^ i);

    const registers_by_size = {
        8: ["al", "ah", "cl", "ch", "dl", "dh", "bl", "bh"],
        16: ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di"],
        32: ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"],
    };
    const mask_by_size = {
        8: 0xFF,
        16: 0xFFFF,
        32: -1,
    };
    const word_by_size = {
        8: "byte",
        16: "word",
        32: "dword",
    };
    const two_operand_instructions = ["add", "sub", "adc", "sbb", "and", "or", "xor", "cmp", "test"];
    const one_operand_instructions = [
        "inc", "dec", "neg",
        "mul", //"idiv", "div", // technically also eax:edx, but are implied by assembler
        "imul", // handled specifically below to also generate 2-/3-operand form
    ];
    const shift_instructions = ["shl", "shr", "sar", "rol", "ror", "rcl", "rcr"];
    // TODO: cmpxchg, xadd, bsf, bsr, shrd/shld, popcnt, bt*
    const instructions = [two_operand_instructions, one_operand_instructions, shift_instructions].flat();
    const conditions = [
        // suffix flag
        ["o", OF],
        ["c", CF],
        ["z", ZF],
        ["p", PF],
        ["s", SF],
        ["be", CF | ZF],
        ["l", SF | OF],
        ["le", SF | OF | ZF],
    ];

    let c = [];
    let address = 0x100000;

    for(let reg of registers_by_size[32])
    {
        if(reg !== "esp")
        {
            c.push(`mov ${reg}, ${interesting_immediate(rng)}`);
        }
    }

    let undefined_flags = 0;

    for(let i = 0; i < 2000; i++)
    {
        const ins = instructions[rng.uint32() % instructions.length];
        const size = [8, 16, 32][rng.uint32() % 3];
        const size_word = word_by_size[size];
        const dst_is_mem = rng.int32() & 1;
        const dst = dst_is_mem ?
            `${size_word} [${nasm_hex(address)}]` :
            registers_by_size[size][rand_reg_but_not_esp(rng)];
        let src_is_mem = false;
        if(ins === "imul" && (rng.int32() & 1)) // other encodings handled in one_operand_instructions
        {
            // dst must be reg, no 8-bit
            const size_imul = [16, 32][rng.int32() & 1];
            const dst_imul = registers_by_size[size_imul][rand_reg_but_not_esp(rng)];
            const src1 = dst_is_mem ?
                `${word_by_size[size_imul]} [${nasm_hex(address)}]` :
                registers_by_size[size_imul][rand_reg_but_not_esp(rng)];
            if(rng.int32() & 1)
            {
                c.push(`${ins} ${dst_imul}, ${src1}`);
            }
            else
            {
                const src2 = nasm_hex(interesting_immediate(rng) & mask_by_size[size_imul]);
                c.push(`${ins} ${dst_imul}, ${src1}, ${src2}`);
            }
        }
        else if(one_operand_instructions.includes(ins))
        {
            c.push(`${ins} ${dst}`);
        }
        else if(two_operand_instructions.includes(ins))
        {
            src_is_mem = !dst_is_mem && (rng.int32() & 1);
            const src = src_is_mem ?
                `${size_word} [${nasm_hex(address)}]` :
                (rng.int32() & 1) ?
                registers_by_size[size][rand_reg_but_not_esp(rng)] :
                nasm_hex(interesting_immediate(rng) & mask_by_size[size]);
            c.push(`${ins} ${dst}, ${src}`);
        }
        else if(shift_instructions.includes(ins))
        {
            if(rng.int32() & 1)
            {
                // unknown CL
                undefined_flags |= AF | OF;
                c.push(`${ins} ${dst}, cl`);
            }
            else
            {
                const shift = interesting_immediate(rng) & 0xFF;
                // TODO: shift mod {8,9,16,17,32,33} depending on bitsize/rotate/with-carry, shifts can clear undefined_flags if shift is not zero
                undefined_flags |= shift === 1 ? AF : AF | OF;
                if(rng.int32() & 1)
                {
                    // known CL
                    c.push(`mov cl, ${nasm_hex(shift)}`);
                    c.push(`${ins} ${dst}, cl`);
                }
                else
                {
                    // immediate
                    c.push(`${ins} ${dst}, ${nasm_hex(shift)}`);
                }
            }
        }

        if(dst_is_mem || src_is_mem)
        {
            if(rng.int32() & 1)
            {
                address += size / 8;
                // initialise next word
                c.push(`mov dword [${nasm_hex(address)}], ${nasm_hex(interesting_immediate(rng) & 0xFF)}`);
            }
        }

        if(ins === "imul" || ins === "mul" || ins === "idiv" || ins === "div")
        {
            undefined_flags = SF | ZF | AF | PF;
        }
        else if(!shift_instructions.includes(ins))
        {
            // adc/sbb/inc/dec read CF, but CF is never undefined
            undefined_flags = 0;
        }

        if(rng.int32() & 1)
        {
            // setcc
            const cond = random_pick(conditions.filter(([_, flag]) => 0 === (flag & undefined_flags)).map(([suffix]) => suffix), rng);
            assert(cond);
            const invert = (rng.int32() & 1) ? "n" : "";
            const ins2 = `set${invert}${cond}`;
            const dst2 = (rng.int32() & 1) ? `byte [${nasm_hex(address++)}]` : registers_by_size[8][rng.int32() & 7];
            c.push(`${ins2} ${dst2}`);
        }
        else if(rng.int32() & 1)
        {
            // cmovcc
            const cond = random_pick(conditions.filter(([_, flag]) => 0 === (flag & undefined_flags)).map(([suffix]) => suffix), rng);
            assert(cond);
            const invert = (rng.int32() & 1) ? "n" : "";
            const ins2 = `cmov${invert}${cond}`;
            const size = (rng.int32() & 1) ? 16 : 32;
            const src2 = registers_by_size[size][rng.int32() & 7];
            const dst2 = registers_by_size[size][rand_reg_but_not_esp(rng)];
            c.push(`${ins2} ${dst2}, ${src2}`);
        }
        else if(rng.int32() & 1)
        {
            c.push("pushf");
            c.push("and dword [esp], ~" + nasm_hex(FLAGS_IGNORE | undefined_flags));
            c.push(`pop ${registers_by_size[32][rand_reg_but_not_esp(rng)]}`);
        }
        else
        {
            // intentionally left blank
        }

        // TODO:
        // cmovcc
        // other random instructions (mov, etc.)
    }

    c.push("pushf");
    c.push("and dword [esp], ~" + nasm_hex(FLAGS_IGNORE | undefined_flags));
    c.push("popf");

    assert(address < 0x102000);

    const name = `arith_${i}`;
    const asm = header + c.join("\n") + "\n" + footer;

    return { name, asm };
}

function all_combinations(xs)
{
    let result = [xs];

    for(let i = 0; i < xs.length; i++)
    {
        let x = xs[i];

        if(x instanceof Array)
        {
            let new_result = [];

            for(let r of result)
            {
                for(let x_ of x)
                {
                    r = r.slice();
                    r[i] = x_;
                    new_result.push(r);
                }
            }

            result = new_result;
        }
    }

    return result;
}

function nasm_hex(x)
{
    return `0${(x >>> 0).toString(16).toUpperCase()}h`;
}

function random_pick(xs, rng)
{
    return xs[rng.uint32() % xs.length];
}
                                                                                                                                    source/v64/tests/nasm/cvtpi2ps.asm                                                                  0000644 0000000 0000000 00000000537 00000000000 014245  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
    align 16
quad0low:
    dd	1
quad0high:
    dd	2
quad1low:
    dd	-1234567
quad1high:
    dd	0
myaddress:
    dd	0xdeadbeef
%include "header.inc"

	cvtpi2ps	xmm0, [quad0low]
	; fill xmm1 in order to ensure that the high quadword remain inchanged
	pshufd		xmm1, xmm0, 0
	cvtpi2ps	xmm1, [quad1low]

%include "footer.inc"
                                                                                                                                                                 source/v64/tests/nasm/cvtps2pi.asm                                                                  0000644 0000000 0000000 00000001355 00000000000 014244  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
float0low:
	dd	12345.678
float0high:
	dd	1234.5
float1low:
	dd	0x80000001.0
float1high:
	dd	-2147483130.0
mxcsr:
	dd	0

; Set mxcsr regiter rouding bits
%macro  setRoundingBits 1
	stmxcsr		[mxcsr]
	mov			eax, [mxcsr]
	and 		ax, 0x9F80
	or			ah, %1
	mov			[mxcsr], eax
	ldmxcsr		[mxcsr]
%endmacro

%include "header.inc"

	setRoundingBits 0x00 ; Round to nearest
	cvtps2pi	mm0, [float0low]
	cvtps2pi	mm4, [float1low]
	setRoundingBits 0x20 ; Round down
	cvtps2pi	mm1, [float0low]
	cvtps2pi	mm5, [float1low]
	setRoundingBits 0x40 ; Round up
	cvtps2pi	mm2, [float0low]
	cvtps2pi	mm6, [float1low]
	setRoundingBits 0x60 ; Round toward zero
	cvtps2pi	mm3, [float0low]
	cvtps2pi	mm7, [float1low]

%include "footer.inc"
                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/cvttps2pi.asm                                                                 0000644 0000000 0000000 00000000712 00000000000 014424  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
float0low:
	dd	2147483647.0
float0high:
	dd	-2147483648.0
float1low:
	dd	1235.678
float1high:
	dd	1325400064
float2low:
	dd	-54.321
float2high:
	dd	-12345.6
float3low:
	dd	123.456
float3high:
	dd	1234.5678
myaddress:
	dd	0xdeadbeef
%include "header.inc"

    movaps	    xmm0, [float0low]
    cvttps2pi	mm0, xmm0
	cvttps2pi	mm1, [float1low]
	cvttps2pi	mm2, [float2low]
	cvttps2pi	mm3, [float3low]

%include "footer.inc"
                                                      source/v64/tests/nasm/double-segment-prefix.asm                                                     0000644 0000000 0000000 00000000265 00000000000 016676  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    cld
    mov dword [100ff8h], 0x11223344
    mov esi, 100ff8h
    mov edi, 101000h
    db 36h, 3eh ; ss ds
    movsd

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                           source/v64/tests/nasm/emms.asm                                                                      0000644 0000000 0000000 00000000324 00000000000 013426  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myquad:
	dq	0xad0000ceadad00ff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	emms
        ; TODO: Check tag word

%include "footer.inc"
                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/f2xm1.asm                                                                     0000644 0000000 0000000 00000000227 00000000000 013424  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldz
    f2xm1

    fld1
    f2xm1

    fld1
    fchs
    f2xm1

    fldln2
    f2xm1

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/nasm/fchs.asm                                                                      0000644 0000000 0000000 00000000117 00000000000 013410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldz
    fchs

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/nasm/fdecstp.asm                                                                   0000644 0000000 0000000 00000000111 00000000000 014107  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fdecstp

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/fdiv-zero.asm                                                                 0000644 0000000 0000000 00000000242 00000000000 014371  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    push 1234
    fild dword [esp]
    push 0
    fild dword [esp]
    fdiv

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/nasm/fdiv.asm                                                                      0000644 0000000 0000000 00000000130 00000000000 013410  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldz
    fldz
    fdiv

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/nasm/fdivr.asm                                                                     0000644 0000000 0000000 00000000131 00000000000 013573  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldz
    fldz
    fdivr

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/fincstp.asm                                                                   0000644 0000000 0000000 00000000111 00000000000 014125  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fincstp

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/footer.inc                                                                    0000644 0000000 0000000 00000000046 00000000000 013755  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
loop:
       hlt
       jmp     loop
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/fprem-distinct.asm                                                            0000644 0000000 0000000 00000000614 00000000000 015417  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    ; FPREM1 rounds the quotient: round(5 / 3) = 2, remainder = -1.
    mov dword [esp], 3
    fild dword [esp]
    mov dword [esp], 5
    fild dword [esp]
    fprem1

    ; FPREM truncates the quotient: trunc(5 / 3) = 1, remainder = 2.
    mov dword [esp], 3
    fild dword [esp]
    mov dword [esp], 5
    fild dword [esp]
    fprem

%include "footer.inc"
                                                                                                                    source/v64/tests/nasm/fprem.asm                                                                     0000644 0000000 0000000 00000000263 00000000000 013600  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fld1
    fldz
    fprem

    fld1
    fldpi
    fprem

    fld1
    fldl2t
    fprem

    fldz
    fldz
    fprem

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/fprem1.asm                                                                    0000644 0000000 0000000 00000000267 00000000000 013665  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fld1
    fldz
    fprem1

    fld1
    fldpi
    fprem1

    fld1
    fldl2t
    fprem1

    fldz
    fldz
    fprem1

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                         source/v64/tests/nasm/fptan.asm                                                                     0000644 0000000 0000000 00000000161 00000000000 013574  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldpi
    fptan

    fldpi
    fldpi
    fpatan

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/nasm/fpu_m80.asm                                                                   0000644 0000000 0000000 00000000215 00000000000 013742  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    push 1
    push 0
    push 0
    fld tword [esp-8]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/frndint.asm                                                                   0000644 0000000 0000000 00000000231 00000000000 014126  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldz
    frndint

    fldpi
    frndint

    fldl2t
    frndint

    fldln2
    frndint

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/fsave_frstor.asm                                                              0000644 0000000 0000000 00000000405 00000000000 015170  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    sub esp, 128
    fldz
    fld1
    fsave [esp]
    frstor [esp]
    mov dword [esp + 12], 0 ; fpu eip (currently not emulated)
    mov dword [esp + 16], 0 ; fpu cs/opcode (currently not emulated)

%include "footer.inc"
                                                                                                                                                                                                                                                           source/v64/tests/nasm/fscale.asm                                                                    0000644 0000000 0000000 00000000134 00000000000 013721  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldpi
    fldpi
    fscale

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/fsincos.asm                                                                   0000644 0000000 0000000 00000000264 00000000000 014134  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldpi
    fsincos
    fldz
    fsincos

    fldpi
    fsin
    fldz
    fsin

    fldpi
    fcos
    fldz
    fcos

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/fsqrt.asm                                                                     0000644 0000000 0000000 00000000121 00000000000 013617  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fldpi
    fsqrt

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/nasm/fst-st-empty-tag.asm                                                          0000644 0000000 0000000 00000000276 00000000000 015620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
value:
    dd 3f800000h

%include "header.inc"

    fldz
    fst st1
    fistp word [esp]
    fadd dword [value]
    fstp dword [esp + 4]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                  source/v64/tests/nasm/fstenv.asm                                                                    0000644 0000000 0000000 00000000375 00000000000 014000  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    fstenv [esp]

    ; zero undefined fields
    mov word [esp + 0 + 2], 0
    mov word [esp + 4 + 2], 0
    mov word [esp + 8 + 2], 0
    mov word [esp + 24 + 2], 0

%include "footer.inc"
                                                                                                                                                                                                                                                                   source/v64/tests/nasm/fstm80.asm                                                                    0000644 0000000 0000000 00000000303 00000000000 013603  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fstcw [esp]
    and word [esp], ~0x300
    or word [esp], 0x200
    fldcw [esp]

    fldpi
    fld1
    fmul
    fstp tword [esp]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/fstsw.asm                                                                     0000644 0000000 0000000 00000000204 00000000000 013630  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov eax, 12345678h
    fstsw ax
    push 87654321h
    fstsw [esp]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/fxtract-zero.asm                                                              0000644 0000000 0000000 00000000202 00000000000 015110  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    push 0
    fild dword [esp]
    fxtract

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/nasm/fxtract.asm                                                                   0000644 0000000 0000000 00000000206 00000000000 014137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    push 12345
    fild dword [esp]
    fxtract

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/fyl2x-zero.asm                                                                0000644 0000000 0000000 00000000243 00000000000 014506  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    push 1234
    fild dword [esp]
    push 0
    fild dword [esp]
    fyl2x

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/fyl2x.asm                                                                     0000644 0000000 0000000 00000000132 00000000000 013526  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fld1
    fldpi
    fyl2x

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/nasm/fyl2xp1.asm                                                                   0000644 0000000 0000000 00000000134 00000000000 013771  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    fld1
    fldpi
    fyl2xp1

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/gdb-extract-def                                                               0000644 0000000 0000000 00000010145 00000000000 014650  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # Invocation: gdb -x gdb-extract-def

# extract-state /path/to/foo.bin /path/to/foo.fixture
define extract-state
  file $arg0

  # Disables logging to stdout - only log to file
  set logging redirect on

  set logging file $arg1
  set logging overwrite on
  set logging on

  run

  printf "---BEGIN JSON---\n"
  printf "[\n"
  printf "    %d,\n", $eax
  printf "    %d,\n", $ecx
  printf "    %d,\n", $edx
  printf "    %d,\n", $ebx
  printf "    %d,\n", $esp
  printf "    %d,\n", $ebp
  printf "    %d,\n", $esi
  printf "    %d,\n", $edi
  printf "\n"

  printf "    %d,\n", $eip
  printf "\n"

  # For fpu registers, check the tag register first. If the tag index is
  # invalid and you try to access to corresponding register, gdb exits with an
  # error.
  set $top = $fstat >> 11 & 7
  if ($ftag >> (2 * (($top + 0) & 7)) & 3) != 2
    printf "    %.100e,\n", $st0
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 1) & 7)) & 3) != 2
    printf "    %.100e,\n", $st1
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 2) & 7)) & 3) != 2
    printf "    %.100e,\n", $st2
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 3) & 7)) & 3) != 2
    printf "    %.100e,\n", $st3
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 4) & 7)) & 3) != 2
    printf "    %.100e,\n", $st4
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 5) & 7)) & 3) != 2
    printf "    %.100e,\n", $st5
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 6) & 7)) & 3) != 2
    printf "    %.100e,\n", $st6
  else
    printf "    \"invalid\",\n"
  end
  if ($ftag >> (2 * (($top + 7) & 7)) & 3) != 2
    printf "    %.100e,\n", $st7
  else
    printf "    \"invalid\",\n"
  end
  printf "\n"

  printf "    %d,\n", $mm0.v2_int32[0]
  printf "    %d,\n", $mm0.v2_int32[1]
  printf "    %d,\n", $mm1.v2_int32[0]
  printf "    %d,\n", $mm1.v2_int32[1]
  printf "    %d,\n", $mm2.v2_int32[0]
  printf "    %d,\n", $mm2.v2_int32[1]
  printf "    %d,\n", $mm3.v2_int32[0]
  printf "    %d,\n", $mm3.v2_int32[1]
  printf "    %d,\n", $mm4.v2_int32[0]
  printf "    %d,\n", $mm4.v2_int32[1]
  printf "    %d,\n", $mm5.v2_int32[0]
  printf "    %d,\n", $mm5.v2_int32[1]
  printf "    %d,\n", $mm6.v2_int32[0]
  printf "    %d,\n", $mm6.v2_int32[1]
  printf "    %d,\n", $mm7.v2_int32[0]
  printf "    %d,\n", $mm7.v2_int32[1]
  printf "\n"

  printf "    %d,\n", $xmm0.v4_int32[0]
  printf "    %d,\n", $xmm0.v4_int32[1]
  printf "    %d,\n", $xmm0.v4_int32[2]
  printf "    %d,\n", $xmm0.v4_int32[3]
  printf "    %d,\n", $xmm1.v4_int32[0]
  printf "    %d,\n", $xmm1.v4_int32[1]
  printf "    %d,\n", $xmm1.v4_int32[2]
  printf "    %d,\n", $xmm1.v4_int32[3]
  printf "    %d,\n", $xmm2.v4_int32[0]
  printf "    %d,\n", $xmm2.v4_int32[1]
  printf "    %d,\n", $xmm2.v4_int32[2]
  printf "    %d,\n", $xmm2.v4_int32[3]
  printf "    %d,\n", $xmm3.v4_int32[0]
  printf "    %d,\n", $xmm3.v4_int32[1]
  printf "    %d,\n", $xmm3.v4_int32[2]
  printf "    %d,\n", $xmm3.v4_int32[3]
  printf "    %d,\n", $xmm4.v4_int32[0]
  printf "    %d,\n", $xmm4.v4_int32[1]
  printf "    %d,\n", $xmm4.v4_int32[2]
  printf "    %d,\n", $xmm4.v4_int32[3]
  printf "    %d,\n", $xmm5.v4_int32[0]
  printf "    %d,\n", $xmm5.v4_int32[1]
  printf "    %d,\n", $xmm5.v4_int32[2]
  printf "    %d,\n", $xmm5.v4_int32[3]
  printf "    %d,\n", $xmm6.v4_int32[0]
  printf "    %d,\n", $xmm6.v4_int32[1]
  printf "    %d,\n", $xmm6.v4_int32[2]
  printf "    %d,\n", $xmm6.v4_int32[3]
  printf "    %d,\n", $xmm7.v4_int32[0]
  printf "    %d,\n", $xmm7.v4_int32[1]
  printf "    %d,\n", $xmm7.v4_int32[2]
  printf "    %d,\n", $xmm7.v4_int32[3]
  printf "\n"


  set $addr=0x100000
  while($addr < 0x102000)
     printf "    %d, %d, %d, %d, %d, %d, %d, %d,\n", *(int*)($addr+0), *(int*)($addr+4), *(int*)($addr+8), *(int*)($addr+12), *(int*)($addr+16), *(int*)($addr+20), *(int*)($addr+24), *(int*)($addr+28)
     set $addr=$addr+32
  end
  printf "\n"

  printf "    %d,\n", $eflags
  printf "    %d,\n", $ftag
  printf "    %d\n", $fstat

  printf "]\n"
  printf "---END JSON---\n"

  set logging off

end
                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/nasm/gen_fixtures.js                                                               0000755 0000000 0000000 00000011663 00000000000 015036  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import assert from "node:assert/strict";
import os from "node:os";
import { spawn, spawnSync } from "node:child_process";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const DEBUG = process.env.DEBUG || false;
// Maximum number of gdb processes to spawn in parallel
const MAX_PARALLEL_PROCS = +process.env.MAX_PARALLEL_PROCS || 32;
// Default to true for now. It's slower, but async execution occasionally gets stuck
const SYNC_GDB_EXECUTION = process.env.SYNC_GDB_EXECUTION || true;

// Usage: console.log(CYAN_FMT, "This shows up in cyan!")
const CYAN_FMT = "\x1b[36m%s\x1b[0m";
const YELLOW_FMT = "\x1b[33m%s\x1b[0m";

const TEST_DIR = __dirname + "/";
const BUILD_DIR = path.join(TEST_DIR, "build");

const GDB_DEFAULT_ARGS = [
    "-batch",
    "--eval-command=set disable-randomization off", // allow execution on docker
    `--command=${TEST_DIR}gdb-extract-def`,
    // Set a breakpoint "in the future", which all the test binaries can then share
    "--eval-command=set breakpoint pending on",
    "--eval-command=break loop",
    "--eval-command=catch signal SIGFPE",
    "--eval-command=catch signal SIGILL",
    "--eval-command=catch signal SIGSEGV",
    "--eval-command=catch signal SIGBUS",
];

/* Split up an array into semi-evenly sized chunks */
function chunk(source, num_chunks)
{
    const arr = source.slice();
    const ret = [];

    let rem_chunks = num_chunks;
    while(rem_chunks > 0)
    {
        // We guarantee that the entire array is processed because when rem_chunk=1 -> len/1 = len
        ret.push(arr.splice(0, Math.floor(arr.length / rem_chunks)));
        rem_chunks--;
    }
    return ret;
}
assert(
    JSON.stringify(chunk("0 0 1 1 2 2 2 3 3 3".split(" "), 4)) ===
        JSON.stringify([["0", "0"],
                        ["1", "1"],
                        ["2", "2", "2"],
                        ["3", "3", "3"]]),
    "Chunk"
);

const dir_files = fs.readdirSync(BUILD_DIR);
const test_files = dir_files.filter(name => {
    return name.endsWith(".img");
}).map(name => {
    return name.slice(0, -4);
}).filter(name => {
    const bin_file = path.join(BUILD_DIR, `${name}.img`);
    const fixture_file = path.join(BUILD_DIR, `${name}.fixture`);
    if(!fs.existsSync(fixture_file))
    {
        return true;
    }
    return fs.statSync(bin_file).mtime > fs.statSync(fixture_file).mtime;
});

const nr_of_cpus = Math.min(
    os.cpus().length || 1,
    test_files.length,
    MAX_PARALLEL_PROCS
);

if(SYNC_GDB_EXECUTION)
{
    console.log("[+] Generating %d fixtures", test_files.length);
}
else
{
    console.log("[+] Using %d cpus to generate %d fixtures", nr_of_cpus, test_files.length);
}

const workloads = chunk(test_files, nr_of_cpus);

function test_arg_formatter(workload)
{
    return workload.map(test => {
        const test_path = path.join(BUILD_DIR, test);
        return `--eval-command=extract-state ${test_path}.img ${test_path}.fixture`;
    });
}

function set_proc_handlers(proc, n)
{
    proc.on("close", (code) => on_proc_close(code, n));

    if(DEBUG)
    {
        proc.stdout.on("data", (data) => {
            console.log(CYAN_FMT, "stdout", `${n}: ${data}`);
        });

        proc.stderr.on("data", (data) => {
            console.log(YELLOW_FMT, "stderr", `${n}: ${data}`);
        });
    }
}

function on_proc_close(code, n)
{
    console.log(`[+] child process ${n} exited with code ${code}`);
    if(code !== 0)
    {
        process.exit(code);
    }
}

// Without gdb (or NASM_ORACLE=qemu): the reference state comes from QEMU
// (qemu_oracle.js), for hosts that cannot run the i386 binaries natively.
const use_qemu = process.env.NASM_ORACLE === "qemu" ||
    process.env.NASM_ORACLE !== "gdb" && spawnSync("gdb", ["--version"]).status !== 0;
if(use_qemu)
{
    const { qemu_fixture } = await import("./qemu_oracle.js");
    let next = 0, done = 0;
    const worker = async () => {
        while(next < test_files.length)
        {
            const test = test_files[next++];
            const test_path = path.join(BUILD_DIR, test);
            fs.writeFileSync(test_path + ".fixture", await qemu_fixture(test_path + ".img"));
            if(++done % 200 === 0) console.log(`[+] ${done} of ${test_files.length} fixtures (QEMU)`);
        }
    };
    await Promise.all(Array.from({ length: Math.max(1, Math.min(os.cpus().length, MAX_PARALLEL_PROCS, test_files.length)) }, worker));
    console.log(`[+] ${done} fixtures from QEMU`);
}

for(let i = 0; !use_qemu && i < nr_of_cpus; i++)
{
    const gdb_args = GDB_DEFAULT_ARGS.concat(test_arg_formatter(workloads[i]));

    if(DEBUG)
    {
        console.log(CYAN_FMT, "[DEBUG]", "gdb", gdb_args.join(" "));
    }

    if(SYNC_GDB_EXECUTION || nr_of_cpus === 1)
    {
        const { status: code } = spawnSync("gdb", gdb_args);
        on_proc_close(code, i);
    }
    else
    {
        const gdb = spawn("gdb", gdb_args);
        set_proc_handlers(gdb, i);
    }
}
                                                                             source/v64/tests/nasm/header.inc                                                                    0000644 0000000 0000000 00000001510 00000000000 013704  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       MBALIGN     equ  1<<0                   ; align loaded modules on page boundaries
MEMINFO     equ  1<<1                   ; provide memory map
FLAGS       equ  0                      ; this is the Multiboot 'flag' field
MAGIC       equ  0x1BADB002             ; 'magic number' lets bootloader find the header
CHECKSUM    equ -(MAGIC + FLAGS)        ; checksum of above, to prove we are multiboot
section .multiboot
align 4
    dd MAGIC
    dd FLAGS
    dd CHECKSUM

section .bss
    resb 2*4096   ; 0x2000

stack_top:

section .text

_start:
main:
        xor eax, eax
        xor ecx, ecx
        xor edx, edx
        xor ebx, ebx
        mov esp, stack_top
        xor ebp, ebp
        xor esi, esi
        xor edi, edi

        pxor xmm0, xmm0

        ; make space for memory operations
        sub esp, 32

        push 0
        popf
                                                                                                                                                                                        source/v64/tests/nasm/idiv16-overflow.asm                                                           0000644 0000000 0000000 00000000174 00000000000 015433  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ax, 0000h
    mov dx, 8000h
    mov bx, -1
    idiv bx

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/idiv32-overflow.asm                                                           0000644 0000000 0000000 00000000210 00000000000 015420  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov eax, 00000000h
    mov edx, 80000000h
    mov ebx, -1
    idiv ebx

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/nasm/idiv8-overflow.asm                                                            0000644 0000000 0000000 00000000152 00000000000 015350  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ax, 8000h
    mov bl, -1
    idiv bl

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/nasm/indirect-call.asm                                                             0000644 0000000 0000000 00000000343 00000000000 015200  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data

%include "header.inc"

    mov eax, foo
    call eax
foo:
    xor eax, eax
    ; clear stack (pushed eip is not the same between vm and gdb execution)
    mov dword [esp], 0

%include "footer.inc"
                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/indirect-jump.asm                                                             0000644 0000000 0000000 00000000177 00000000000 015245  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data

%include "header.inc"

    mov eax, foo
    jmp eax
foo:
    xor eax, eax

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/nasm/jcxz.asm                                                                      0000644 0000000 0000000 00000000434 00000000000 013445  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ecx, 0x10000
    jecxz cont1
    or eax, 1
cont1:

    mov ecx, 0
    jecxz cont2
    or eax, 2
cont2:

    mov ecx, 0x1
    jcxz cont3
    or eax, 4
cont3:

    mov ecx, 0x10000
    jcxz cont4
    or eax, 8
cont4:

%include "footer.inc"
                                                                                                                                                                                                                                    source/v64/tests/nasm/jump.asm                                                                      0000644 0000000 0000000 00000001426 00000000000 013444  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    mov eax, 0
    mov ebx, 0
    mov ecx, 0
    mov edx, 0
    mov esi, 0
    mov edi, 0

    ; skip
    jmp .target1
    inc eax
.target1:

    ; conditional jump up
.target2:
    inc ebx
    inc ecx
    cmp ebx, 2
    jne .target2

    ; conditional jump down
.target3:
    cmp ebx, 4
    je .target4
    inc ebx
    inc edx
    jmp .target3

.target4:
    call .fun
    call .not_returning_fun
.after_call:
    jmp .after_fun

.fun:
    inc esi
    ret

.not_returning_fun:
    inc esi
    jmp .after_call
    inc esi
    ret

.after_fun:
    push .target5
    ret
.target5:

    ; clear stack (pushed eip is not the same between vm and gdb execution)
    mov dword [esp], 0
    mov dword [esp-4], 0

%include "footer.inc"
                                                                                                                                                                                                                                          source/v64/tests/nasm/lea-nop.asm                                                                   0000644 0000000 0000000 00000000472 00000000000 014024  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    ; nops
    lea edx, [edx]
    db 8Dh, 40h, 00h
    db 8Dh, 0B6h, 00h, 00h, 00h, 00h
    db 8Dh, 0BCh, 27h, 00h, 00h, 00h, 00h

    ; non-nops, but similar encodings
    lea eax, [bx+si]
    lea cx, [bx+di]
    lea edx, [edx+42]
    lea ebp, [ebp*2]

%include "footer.inc"
                                                                                                                                                                                                      source/v64/tests/nasm/leave16.asm                                                                   0000644 0000000 0000000 00000000211 00000000000 013723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    lea ebp, [esp+10h]
    mov dword [ebp], 123456789
    db 0x66
    leave

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/leave32.asm                                                                   0000644 0000000 0000000 00000000175 00000000000 013732  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    lea ebp, [esp+10h]
    mov dword [ebp], 123456789
    leave

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/loop.asm                                                                      0000644 0000000 0000000 00000000331 00000000000 013434  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ecx, 0x10042
    mov eax, 0
start1:
    inc eax
    loop start1

    mov ecx, 0x10005
    mov ebx, 0
start2:
    inc ebx
    db 67h
    loop start2

%include "footer.inc"
                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/loopnz.asm                                                                    0000644 0000000 0000000 00000000445 00000000000 014012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ecx, 0x10042
    mov eax, 42
start1:
    dec eax
    loopz start1

    mov ecx, 0x10005
    mov ebx, 51
start2:
    dec ebx
    db 67h
    loopz start2

    mov ecx, 0x10005
start3:
    or edx, 1
    db 67h
    loopz start3

%include "footer.inc"
                                                                                                                                                                                                                           source/v64/tests/nasm/loopz.asm                                                                     0000644 0000000 0000000 00000000450 00000000000 013630  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov ecx, 0x10042
    mov eax, -1
start1:
    inc eax
    loopz start1

    mov ecx, 0x10005
    mov ebx, -1
start2:
    inc ebx
    db 67h
    loopz start2

    mov ecx, 0x10005
start3:
    xor edx, edx
    db 67h
    loopz start3

%include "footer.inc"
                                                                                                                                                                                                                        source/v64/tests/nasm/maskmovdqu.asm                                                                0000644 0000000 0000000 00000001324 00000000000 014655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

dquad0:
	dq	0x1234567890abcdef
	dq	0xfedcba0987654321
dquad1:
	dq	0xffffffffffffffff
	dq	0xffffffffffffffff
mask0:
	dq	0x8081828384858687
	dq	0x88898a8b8c8d8e8f
mask1:
	dq	0x10203080405080ff
	dq	0x1234567890abcdef

%include "header.inc"

	movdqu	xmm0, [dquad0]
	movdqu	xmm1, [dquad1]
	movdqu	xmm2, [dquad0]
	movdqu	xmm3, [dquad1]
	movdqu	xmm6, [mask0]
	movdqu	xmm7, [mask1]

	;; Look out for size of extracted memory region
	mov esp, stack_top - 16

	mov		edi, esp
	maskmovdqu	xmm0, xmm6
	sub		esp, 16

	mov		edi, esp
	maskmovdqu	xmm1, xmm6
	sub		esp, 16

	mov		edi, esp
	maskmovdqu	xmm2, xmm7
	sub		esp, 16

	mov		edi, esp
	maskmovdqu	xmm3, xmm7
	sub		esp, 16

%include "footer.inc"
                                                                                                                                                                                                                                                                                                            source/v64/tests/nasm/maskmovq.asm                                                                  0000644 0000000 0000000 00000001114 00000000000 014321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

quad0:
	dq	0x1234567890abcdef
quad1:
	dq	0xffffffffffffffff
mask0:
	dq	0x8080808080808080
mask1:
	dq	0x10203080405080ff

%include "header.inc"

	movq	mm0, [quad0]
	movq	mm1, [quad1]
	movq	mm2, [quad0]
	movq	mm3, [quad1]
	movq	mm6, [mask0]
	movq	mm7, [mask1]

	;; Look out for size of extracted memory region
	mov esp, stack_top - 16

	mov		edi, esp
	maskmovq	mm0, mm6
	sub		esp, 8

	mov		edi, esp
	maskmovq	mm1, mm6
	sub		esp, 8

	mov		edi, esp
	maskmovq	mm2, mm7
	sub		esp, 8

	mov		edi, esp
	maskmovq	mm3, mm7
	sub		esp, 8

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/mov16.asm                                                                     0000644 0000000 0000000 00000001440 00000000000 013435  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ;;; Test JIT optimization of opcodes 0x89 and 0x8b

global _start

section .data
    align 16
mydword:
    dd  0xcafebabe
myaddress:
    dd  0xdeadbeef

%include "header.inc"

    ;; Load 32-bit values to confirm that the 16-bit movs do not overwrite existing values here
    mov eax, 0xcafeb055
    mov esi, 0x1bada551

    mov ecx, [mydword]
    mov edx, [myaddress]

    mov [myaddress], cx
    mov [mydword], dx

    ;; The following db's are used since mov reg, reg can be accomplished with several opcodes but
    ;; we want to test these specific ones

    ;; mov cx, si
    db 0x66
    db 0x89
    db 0xf1
    ;; mov dx, di
    db 0x66
    db 0x89
    db 0xfa

    ;; mov dx, ax
    db 0x66
    db 0x8b
    db 0xd0
    ;; mov ax, cx
    db 0x66
    db 0x8b
    db 0xc1

%include "footer.inc"
                                                                                                                                                                                                                                source/v64/tests/nasm/mov_sreg.asm                                                                  0000644 0000000 0000000 00000001075 00000000000 014312  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
    align 16
mydword:
    dd  0

%include "header.inc"

    ; 32-bit register move should set higher bits to zero
    mov eax, -1
    mov eax, ss
    and eax, 0xffff0000

    mov ebx, -1
    db 66h
    mov ebx, ss
    and ebx, 0xffff0000

    ; 32-bit memory move should preserver higher bits
    mov dword [mydword], 0xdeadbeef
    mov [mydword], ss
    mov ecx, [mydword]
    and ecx, 0xffff0000

    mov dword [mydword+4], 0xdeadbeef
    db 66h
    mov [mydword+4], ss
    mov edx, [mydword+4]
    and edx, 0xffff0000

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/mov_sreg_ud1.asm                                                              0000644 0000000 0000000 00000000123 00000000000 015054  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    db 8eh
    db 3fh

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/mov_sreg_ud2.asm                                                              0000644 0000000 0000000 00000000123 00000000000 015055  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    db 8ch
    db 3fh

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/movaps.asm                                                                    0000644 0000000 0000000 00000000452 00000000000 013774  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myfloat0:
	dd	1.234567e20
myfloat1:
	dd	2.345678e20
myfloat2:
	dd	3.456789e20
myfloat3:
	dd	4.567891e20
myaddress:
	dd	0xdeadbeef
%include "header.inc"

	movaps	xmm0, [myfloat0]
    movaps	[myaddress], xmm0
    movaps	xmm1, [myaddress]

%include "footer.inc"
                                                                                                                                                                                                                      source/v64/tests/nasm/movd.asm                                                                      0000644 0000000 0000000 00000000456 00000000000 013440  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myquad:
	dq	0x1234567890abcdef
mydword:
	dd	0xcafebabe
myaddress:
	dd	0xdeadbeef

%include "header.inc"


	movd	mm0, [mydword]
	movd	[myaddress], mm0
	movd	mm1, [myaddress]
	movd	eax, mm0
	movd	mm4, eax
	mov     eax, 0x42
	movd    mm6, eax

%include "footer.inc"
                                                                                                                                                                                                                  source/v64/tests/nasm/movntpd.asm                                                                   0000644 0000000 0000000 00000000453 00000000000 014157  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myfloat0:
	dd	1.234567e20
myfloat1:
	dd	2.345678e20
myfloat2:
	dd	3.456789e20
myfloat3:
	dd	4.567891e20
myaddress:
	dd	0xdeadbeef
%include "header.inc"

	movapd	xmm0, [myfloat0]
    movntpd	[myaddress], xmm0
    movapd	xmm1, [myaddress]

%include "footer.inc"
                                                                                                                                                                                                                     source/v64/tests/nasm/movntps.asm                                                                   0000644 0000000 0000000 00000000453 00000000000 014176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myfloat0:
	dd	1.234567e20
myfloat1:
	dd	2.345678e20
myfloat2:
	dd	3.456789e20
myfloat3:
	dd	4.567891e20
myaddress:
	dd	0xdeadbeef
%include "header.inc"

	movapd	xmm0, [myfloat0]
    movntps	[myaddress], xmm0
    movapd	xmm1, [myaddress]

%include "footer.inc"
                                                                                                                                                                                                                     source/v64/tests/nasm/movq.asm                                                                      0000644 0000000 0000000 00000000370 00000000000 013450  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myquad:
	dq	0x1234567890abcdef
mydword:
	dd	0xcafebabe
myaddress:
	dd	0xdeadbeef

%include "header.inc"

	movq	mm0, [myquad]
	movq	[myaddress], mm0
	movq	mm1, [myaddress]
	movq	mm4, mm0

%include "footer.inc"
                                                                                                                                                                                                                                                                        source/v64/tests/nasm/packssdw.asm                                                                  0000644 0000000 0000000 00000000653 00000000000 014311  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xffffffff0fffffff
quad2:
	dq	0x0000abcd80000000
quad3:
	dq	0xaaaaaaaaffffff00
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	packssdw	mm0, mm2
	packssdw	mm0, [quad1]
	packssdw	mm1, [quad3]
	packssdw	mm2, [quad1]
	packssdw	mm3, [quad1]


%include "footer.inc"
                                                                                     source/v64/tests/nasm/packsswb.asm                                                                  0000644 0000000 0000000 00000000657 00000000000 014313  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad00adad007fff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0x01008080f0f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	packsswb	mm0, [quad3]
	packsswb	mm0, [quad1]
	packsswb	mm1, [quad3]
	packsswb	mm2, [quad1]
	packsswb	mm3, [quad1]


%include "footer.inc"
                                                                                 source/v64/tests/nasm/packuswb.asm                                                                  0000644 0000000 0000000 00000001274 00000000000 014311  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xad0000ceadad00ff
quad2:
	dq	0xffffffffffffffff
quad3:
	dq	0x0000000000000000
quad4:
	dq	0x7fff8000ffff0808
myquad:
	dq	0x00ad00adad007fff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	packuswb	mm4, mm0
	packuswb	mm5, mm1
	packuswb	mm6, mm2
	packuswb	mm7, mm3
	packuswb	mm0, [quad2]
	packuswb	mm1, [quad3]
	packuswb	mm2, [quad4]
	packuswb	mm3, [quad1]
	packuswb	mm0, mm5
	packuswb	mm1, mm6
	packuswb	mm2, mm7
	packuswb	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/paddb.asm                                                                     0000644 0000000 0000000 00000000750 00000000000 013542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffbaef
quad2:
	dq	0x71ae010f0f000dbe
quad3:
	dq	0xf100808080f0af42
quad4:
	dq	0xffffffffffffffff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]
	movq		mm4, [quad4]

	paddb		mm0, [quad2]
	paddb		mm0, [quad1]
	paddb		mm1, mm2
	paddb		mm2, [quad1]
	paddb		mm3, [quad1]
	paddb		mm4, [quad4]


%include "footer.inc"
                        source/v64/tests/nasm/paddd.asm                                                                     0000644 0000000 0000000 00000000750 00000000000 013544  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad80ad0fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
quad4:
	dq	0xffffffffffffffff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]
	movq		mm4, [quad4]

	paddd		mm0, [quad2]
	paddd		mm0, [quad1]
	paddd		mm1, mm2
	paddd		mm2, [quad1]
	paddd		mm3, [quad1]
	paddd		mm4, [quad4]


%include "footer.inc"
                        source/v64/tests/nasm/paddsb.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 013731  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	paddsb		mm0, [quad2]
	paddsb		mm0, [quad1]
	paddsb		mm1, mm2
	paddsb		mm2, [quad1]
	paddsb		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/paddsw.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 013756  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	paddsw		mm0, [quad2]
	paddsw		mm0, [quad1]
	paddsw		mm1, mm2
	paddsw		mm2, [quad1]
	paddsw		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/paddusb.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014116  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	paddusb	mm0, [quad2]
	paddusb	mm0, [quad1]
	paddusb	mm1, mm2
	paddusb	mm2, [quad1]
	paddusb	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/paddusw.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014143  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	paddusw	mm0, [quad2]
	paddusw	mm0, [quad1]
	paddusw	mm1, mm2
	paddusw	mm2, [quad1]
	paddusw	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/paddw.asm                                                                     0000644 0000000 0000000 00000000335 00000000000 013566  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myquad:
	dq	0xad0000ceadad00ff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [myquad]
	paddw		mm0, [myaddress]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/pand.asm                                                                      0000644 0000000 0000000 00000000754 00000000000 013416  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xad0000ceadad00ff
quad2:
	dq	0xffffffffffffffff
quad3:
	dq	0x0000000000000000
quad4:
	dq	0x7fff8000ffff0808
mydword:
	dd	0xcafebabe

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]

	pand		mm1, [quad2]
	pand		mm1, mm2
	pand		mm2, [quad1]
	pand		mm2, mm3
	pand		mm3, [quad3]
	pand		mm3, mm4
	pand		mm4, [quad1]
	pand		mm4, mm1
	pand		mm4, mm3


%include "footer.inc"
                    source/v64/tests/nasm/pandn.asm                                                                     0000644 0000000 0000000 00000000641 00000000000 013567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pandn		mm0, [quad2]
	pandn		mm0, [quad1]
	pandn		mm1, mm2
	pandn		mm2, [quad1]
	pandn		mm3, [quad1]


%include "footer.inc"
                                                                                               source/v64/tests/nasm/pcmpeqb.asm                                                                   0000644 0000000 0000000 00000001040 00000000000 014110  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad00adad007fff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0x01008080f0f0ff42
quad4:
	dq	0x0000000000000000
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]

	pcmpeqb	mm1, [quad2]
	pcmpeqb	mm1, mm2
	pcmpeqb	mm2, [quad1]
	pcmpeqb	mm2, mm3
	pcmpeqb	mm3, [quad3]
	pcmpeqb	mm3, mm4
	pcmpeqb	mm4, [quad1]
	pcmpeqb	mm4, mm1
	pcmpeqb	mm4, mm3


%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/nasm/pcmpeqd.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014125  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x70ad80ad7fffffff
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pcmpeqd	mm0, [quad2]
	pcmpeqd	mm0, [quad1]
	pcmpeqd	mm1, mm2
	pcmpeqd	mm2, [quad1]
	pcmpeqd	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/pcmpeqw.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014150  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80adad007fff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0x01008080f0f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pcmpeqw	mm0, [quad2]
	pcmpeqw	mm0, [quad1]
	pcmpeqw	mm1, mm2
	pcmpeqw	mm2, [quad1]
	pcmpeqw	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/pcmpgtb.asm                                                                   0000644 0000000 0000000 00000001221 00000000000 014116  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad00adad007fff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0x01008080f0f0ff42
quad4:
	dq	0x0000000000000000
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	pcmpgtb	mm4, mm0
	pcmpgtb	mm5, mm1
	pcmpgtb	mm6, mm2
	pcmpgtb	mm7, mm3
	pcmpgtb	mm0, [quad2]
	pcmpgtb	mm1, [quad3]
	pcmpgtb	mm2, [quad4]
	pcmpgtb	mm3, [quad1]
	pcmpgtb	mm0, mm5
	pcmpgtb	mm1, mm6
	pcmpgtb	mm2, mm7
	pcmpgtb	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/nasm/pcmpgtd.asm                                                                   0000644 0000000 0000000 00000000647 00000000000 014133  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pcmpgtd	mm0, [quad2]
	pcmpgtd	mm0, [quad1]
	pcmpgtd	mm1, mm2
	pcmpgtd	mm2, [quad1]
	pcmpgtd	mm3, [quad1]


%include "footer.inc"

                                                                                         source/v64/tests/nasm/pcmpgtw.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014155  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80adad007fff
quad2:
	dq	0x7fff00428000ffff
quad3:
	dq	0x01008080f0f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pcmpgtw	mm0, [quad2]
	pcmpgtw	mm0, [quad1]
	pcmpgtw	mm1, mm2
	pcmpgtw	mm2, [quad1]
	pcmpgtw	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/pmaddwd.asm                                                                   0000644 0000000 0000000 00000000756 00000000000 014116  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
quad4:
	dq	0x8000800080008000
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]
	movq		mm4, [quad4]

	pmaddwd	mm0, [quad2]
	pmaddwd	mm0, [quad1]
	pmaddwd	mm1, mm2
	pmaddwd	mm2, [quad1]
	pmaddwd	mm3, [quad1]
	pmaddwd	mm4, [quad4]


%include "footer.inc"
                  source/v64/tests/nasm/pmulhw.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 014010  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pmulhw		mm0, [quad2]
	pmulhw		mm0, [quad1]
	pmulhw		mm1, mm2
	pmulhw		mm2, [quad1]
	pmulhw		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/pmullw.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 014014  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	pmullw		mm0, [quad2]
	pmullw		mm0, [quad1]
	pmullw		mm1, mm2
	pmullw		mm2, [quad1]
	pmullw		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/pmuludq.asm                                                                   0000644 0000000 0000000 00000001212 00000000000 014151  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
dword1:
	dd	0x00000002
dword2:
	dd	0xFFFFFF11
dword3:
	dd	0xFFF00000
dword4:
	dd	0x0000FFFF
dword5:
	dd	0xFFFFFFFF
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce
qword1:
	dq	0xffffffff00000001
%include "header.inc"

	movd		mm0, [dword1]
	movd		mm1, [dword2]
	movd		mm2, [dword1]
	movd		mm3, [dword2]
	movd		mm4, [dword4]
	movd		mm5, [dword5]
	
	pmuludq	mm0, [mydword]
	pmuludq	mm2, mm1
	pmuludq	mm3, [dword3]
	pmuludq	mm4, [dword3]
	pmuludq	mm5, [dword5]

	movd	   xmm1, [dword5]
	pshufd     xmm1, xmm1, 0
	pmuludq    xmm1, xmm1

	movd	   xmm2, [dword4]
	pmuludq    xmm2, xmm1

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/nasm/pop_esp.asm                                                                   0000644 0000000 0000000 00000000246 00000000000 014135  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    mov esp, stack_top-16
    mov dword [esp], 55aaaa55h
    pop dword [esp-12]

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/pop_esp2.asm                                                                  0000644 0000000 0000000 00000000240 00000000000 014211  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

%include "header.inc"

    ; pop esp encoded using 8F
    mov esp, stack_top-16
    db 8Fh, 0C4h

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/nasm/por.asm                                                                       0000644 0000000 0000000 00000000627 00000000000 013273  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	por		mm0, [quad2]
	por		mm0, [quad1]
	por		mm1, mm2
	por		mm2, [quad1]
	por		mm3, [quad1]


%include "footer.inc"
                                                                                                         source/v64/tests/nasm/pshufw.asm                                                                    0000644 0000000 0000000 00000000540 00000000000 014001  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
myquad:
	dq	0xad0000ceadad00ff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [myquad]
	pshufw		mm0, [myaddress], 0xAB
	pshufw		mm1, [myaddress], 0xFE
	pshufw		mm2, [myquad], 0xFF
	pshufw		mm6, [myaddress], 0x19
	pshufw		mm7, [myaddress], 0xB5
%include "footer.inc"
                                                                                                                                                                source/v64/tests/nasm/pslld.asm                                                                     0000644 0000000 0000000 00000001171 00000000000 013604  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
mydq0:
	dq	0xad0000ceadad00ff
	dq	0xff00dadaec0000da
mydq1:
	dq	0x0102030405060708
	dq	0x090a0b0c0d0e0f10
mydword:
	dd	0xcafebac0
shift0:
	dq	0x07
shift1:
	dq	-0x22

align 16
shift2:
	dq	0x07
	dq	0
shift3:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [mydq0]
	movq		mm1, [mydq0]
	movq		mm2, [mydq1]
	movq		mm6, [mydq1]

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq1]
	movq		xmm6, [mydq1]

	pslld		mm0, [shift0]
	pslld		mm1, 30
	pslld		mm2, [shift1]
	pslld		mm6, 0x5

	pslld		xmm0, [shift2]
	pslld		xmm1, 30
	pslld		xmm2, [shift3]
	pslld		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/psllq.asm                                                                     0000644 0000000 0000000 00000001317 00000000000 013623  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
dq0:
	dq	0x0102030405060708
	dq	0xffffaaaabbbbcccc
dq1:
	dq	0x8d0000ceadad00ff
	dq	0x0123456789abcdef
mydword:
	dd	0xcafebac0

align 16
shift1:
	dq	0x07
	dq	0
shift2:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [dq0]
	movq		mm1, [dq0]
	movq		mm2, [dq0]
	movq		mm3, [dq1]
	movq		mm4, [dq1]
	movq		mm6, [dq1]

	movq		xmm0, [dq0]
	movq		xmm1, [dq0]
	movq		xmm2, [dq0]
	movq		xmm3, [dq1]
	movq		xmm4, [dq1]
	movq		xmm6, [dq1]

	psllq		mm0, [shift1]
	psllq		mm1, [shift2]
	psllq		mm2, 50
	psllq		mm3, 28
	psllq		mm4, 68
	psllq		mm6, 0x5

	psllq		xmm0, [shift1]
	psllq		xmm1, [shift2]
	psllq		xmm2, 50
	psllq		xmm3, 28
	psllq		xmm4, 68
	psllq		xmm6, 0x5

%include "footer.inc"

                                                                                                                                                                                                                                                                                                                 source/v64/tests/nasm/psllw.asm                                                                     0000644 0000000 0000000 00000001363 00000000000 013632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
dq1:
	dq	0xad0000ceadad00ff
	dq	0xad0000ceadad00ff
dq2:
	dq	0x42ff88ff11aabbcc
	dq	0x42ff88ff11aabbcc
mydword:
	dd	0xcafebac0

align 16
shift1:
	dq	0x07
	dq	0
shift2:
	dq	-0x22
	dq	0
shift3:
	dq	8
	dq	0

%include "header.inc"

	movq		mm0, [dq1]
	movq		mm1, [dq1]
	movq		mm2, [dq1]
	movq		mm3, [dq2]
	movq		mm4, [dq2]
	movq		mm6, [dq2]

	movq		xmm0, [dq1]
	movq		xmm1, [dq1]
	movq		xmm2, [dq1]
	movq		xmm3, [dq2]
	movq		xmm4, [dq2]
	movq		xmm6, [dq2]

	psllw		mm0, [shift1]
	psllw		mm1, 0xff
	psllw		mm2, [shift2]
	psllw		mm3, 12
	psllw		mm4, [shift3]
	psllw		mm6, 0x5

	psllw		xmm0, [shift1]
	psllw		xmm1, 0xff
	psllw		xmm2, [shift2]
	psllw		xmm3, 12
	psllw		xmm4, [shift3]
	psllw		xmm6, 0x5

%include "footer.inc"

                                                                                                                                                                                                                                                                             source/v64/tests/nasm/psrad.asm                                                                     0000644 0000000 0000000 00000001106 00000000000 013575  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
dq0:
	dq	0x0102030405060708
	dq	0xffffaaaabbbbcccc
dq1:
	dq	0x8d0000ceadad00ff
	dq	0x0123456789abcdef
mydword:
	dd	0xcafebac0

align 16
shift1:
	dq	0x07
	dq	0
shift2:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [dq0]
	movq		mm1, [dq0]
	movq		mm2, [dq1]
	movq		mm6, [dq1]

	movq		xmm0, [dq0]
	movq		xmm1, [dq0]
	movq		xmm2, [dq1]
	movq		xmm6, [dq1]

	psrad		mm0, [shift1]
	psrad		mm1, 0x18
	psrad		mm2, [shift2]
	psrad		mm6, 0x5

	psrad		xmm0, [shift1]
	psrad		xmm1, 0x18
	psrad		xmm2, [shift2]
	psrad		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/psraw.asm                                                                     0000644 0000000 0000000 00000001126 00000000000 013622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
mydq0:
	dq	0xad0000ceadad00ff
	dq	0xff00dadaec0000da
mydq1:
	dq	0x0102030405060708
	dq	0x090a0b0c0d0e0f10
mydword:
	dd	0xcafebac0

align 16
shift0:
	dq	0x07
	dq	0
shift1:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [mydq0]
	movq		mm1, [mydq0]
	movq		mm2, [mydq1]
	movq		mm6, [mydq1]

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq1]
	movq		xmm6, [mydq1]

	psraw		mm0, [shift1]
	psraw		mm1, 18
	psraw		mm2, [shift0]
	psraw		mm6, 0x5

	psraw		xmm0, [shift1]
	psraw		xmm1, 18
	psraw		xmm2, [shift0]
	psraw		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/psrld.asm                                                                     0000644 0000000 0000000 00000001132 00000000000 013607  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
mydq0:
	dq	0xad0000ceadad00ff
	dq	0xff00dadaec0000da
mydq1:
	dq	0x0102030405060708
	dq	0x090a0b0c0d0e0f10
mydword:
	dd	0xcafebac0

align 16
shift0:
	dq	0x07
	dq	0
shift1:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [mydq0]
	movq		mm1, [mydq0]
	movq		mm2, [mydq1]
	movq		mm6, [mydq1]

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq1]
	movq		xmm6, [mydq1]

	psrld		mm0, [shift1]
	psrld		mm1, 0xff
	psrld		mm2, [shift0]
	psrld		mm6, 0x5

	psrld		xmm0, [shift1]
	psrld		xmm1, 0xff
	psrld		xmm2, [shift0]
	psrld		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/nasm/psrlq.asm                                                                     0000644 0000000 0000000 00000001540 00000000000 013627  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
mydq0:
	dq	0xad0000ceadad00ff
	dq	0xff00dadaec0000da
mydq1:
	dq	0x0102030405060708
	dq	0x090a0b0c0d0e0f10
mydword:
	dd	0xcafebac0

align 16
shift0:
	dq	0x07
	dq	0
shift1:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [mydq0]
	movq		mm1, [mydq0]
	movq		mm2, [mydq0]
	movq		mm3, [mydq1]
	movq		mm4, [mydq1]
	movq		mm6, [mydq1]

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq0]
	movq		xmm3, [mydq1]
	movq		xmm4, [mydq1]
	movq		xmm6, [mydq1]

	psrlq		mm0, [shift1]
	psrlq		mm1, [shift0]
	psrlq		mm2, 0x65
	psrlq		mm3, 0x25
	psrlq		mm4, 0x1F
	psrlq		mm6, 0x5

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq1]
	movq		xmm3, [mydq1]
	movq		xmm6, [mydq1]

	psrlq		xmm0, [shift1]
	psrlq		xmm1, [shift0]
	psrlq		xmm2, 0x65
	psrlq		xmm3, 0x25
	psrlq		xmm4, 0x1F
	psrlq		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                source/v64/tests/nasm/psrlw.asm                                                                     0000644 0000000 0000000 00000001240 00000000000 013632  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
mydq0:
	dq	0xad0000ceadad00ff
	dq	0xff00dadaec0000da
mydq1:
	dq	0x0102030405060708
	dq	0x090a0b0c0d0e0f10
mydword:
	dd	0xcafebac0

align 16
shift0:
	dq	0x07
	dq	0
shift1:
	dq	-0x22
	dq	0

%include "header.inc"

	movq		mm0, [mydq0]
	movq		mm1, [mydq0]
	movq		mm2, [mydq1]
	movq		mm3, [mydq1]
	movq		mm6, [mydq1]

	movq		xmm0, [mydq0]
	movq		xmm1, [mydq0]
	movq		xmm2, [mydq1]
	movq		xmm3, [mydq1]
	movq		xmm6, [mydq1]

	psrlw		mm0, [shift1]
	psrlw		mm1, 30
	psrlw		mm2, [shift0]
	psrlw		mm3, 12
	psrlw		mm6, 0x5

	psrlw		xmm0, [shift1]
	psrlw		xmm1, 30
	psrlw		xmm2, [shift0]
	psrlw		xmm3, 12
	psrlw		xmm6, 0x5

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/nasm/psubb.asm                                                                     0000644 0000000 0000000 00000000750 00000000000 013603  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
quad4:
	dq	0x8000800080008000
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]
	movq		mm4, [quad4]

	psubb		mm0, [quad2]
	psubb		mm0, [quad1]
	psubb		mm1, mm2
	psubb		mm2, [quad1]
	psubb		mm3, [quad1]
	psubb		mm4, [quad4]


%include "footer.inc"
                        source/v64/tests/nasm/psubd.asm                                                                     0000644 0000000 0000000 00000000750 00000000000 013605  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
quad4:
	dq	0xffffffffffffffff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]
	movq		mm4, [quad4]

	psubd		mm0, [quad2]
	psubd		mm0, [quad1]
	psubd		mm1, mm2
	psubd		mm2, [quad1]
	psubd		mm3, [quad1]
	psubd		mm4, [quad4]


%include "footer.inc"
                        source/v64/tests/nasm/psubsb.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 013772  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	psubsb		mm0, [quad2]
	psubsb		mm0, [quad1]
	psubsb		mm1, mm2
	psubsb		mm2, [quad1]
	psubsb		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/psubsw.asm                                                                    0000644 0000000 0000000 00000000646 00000000000 014017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	psubsw		mm0, [quad2]
	psubsw		mm0, [quad1]
	psubsw		mm1, mm2
	psubsw		mm2, [quad1]
	psubsw		mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/psubusb.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014157  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	psubusb	mm0, [quad2]
	psubusb	mm0, [quad1]
	psubusb	mm1, mm2
	psubusb	mm2, [quad1]
	psubusb	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/psubusw.asm                                                                   0000644 0000000 0000000 00000000646 00000000000 014204  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x70ad80ad7fffffff
quad2:
	dq	0x71ae01ff0f00ffbe
quad3:
	dq	0xf100808080f0ff42
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad2]

	psubusw	mm0, [quad2]
	psubusw	mm0, [quad1]
	psubusw	mm1, mm2
	psubusw	mm2, [quad1]
	psubusw	mm3, [quad1]


%include "footer.inc"
                                                                                          source/v64/tests/nasm/psubw.asm                                                                     0000644 0000000 0000000 00000001066 00000000000 013631  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xad0000ceadad00ff
quad2:
	dq	0xffffffffffffffff
quad3:
	dq	0x0000000000000000
quad4:
	dq	0x7fff8000ffff0808
myquad:
	dq	0xad0000ceadad00ff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]

	psubw		mm1, [quad2]
	psubw		mm1, mm2
	psubw		mm2, [quad1]
	psubw		mm2, mm3
	psubw		mm3, [quad3]
	psubw		mm3, mm4
	psubw		mm4, [quad1]
	psubw		mm4, mm1
	psubw		mm4, mm3


%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/nasm/punpckhbw.asm                                                                 0000644 0000000 0000000 00000000665 00000000000 014476  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

quad1:
	dq	0xccddccddad007fff
quad2:
	dq	0xaabbaabbad007fff
quad3:
	dq	0x00ff00ffad007fff

mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad3]
	movq		mm2, [quad2]
	movq		mm3, [quad3]

	punpckhbw	mm0, [myaddress]
	punpckhbw	mm0, mm1
	punpckhbw	mm1, [quad2]
	punpckhbw	mm2, [quad1]
	punpckhbw	mm3, [quad1]

%include "footer.inc"
                                                                           source/v64/tests/nasm/punpckhdq.asm                                                                 0000644 0000000 0000000 00000000665 00000000000 014472  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

quad1:
	dq	0xccddccddad007fff
quad2:
	dq	0xaabbaabbad007fff
quad3:
	dq	0x00ff00ffad007fff

mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad3]
	movq		mm2, [quad2]
	movq		mm3, [quad3]

	punpckhdq	mm0, [myaddress]
	punpckhdq	mm0, mm1
	punpckhdq	mm1, [quad2]
	punpckhdq	mm2, [quad1]
	punpckhdq	mm3, [quad1]

%include "footer.inc"
                                                                           source/v64/tests/nasm/punpckhwd.asm                                                                 0000644 0000000 0000000 00000000665 00000000000 014500  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16

quad1:
	dq	0xccddccddad007fff
quad2:
	dq	0xaabbaabbad007fff
quad3:
	dq	0x00ff00ffad007fff

mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad3]
	movq		mm2, [quad2]
	movq		mm3, [quad3]

	punpckhwd	mm0, [myaddress]
	punpckhwd	mm0, mm1
	punpckhwd	mm1, [quad2]
	punpckhwd	mm2, [quad1]
	punpckhwd	mm3, [quad1]

%include "footer.inc"
                                                                           source/v64/tests/nasm/punpcklbw.asm                                                                 0000644 0000000 0000000 00000001310 00000000000 014466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xad0000ceadad00ff
quad2:
	dq	0xffffffffffffffff
quad3:
	dq	0x0000000000000000
quad4:
	dq	0x7fff8000ffff0808
myquad:
	dq	0x00ad00adad007fff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	punpcklbw	mm4, mm0
	punpcklbw	mm5, mm1
	punpcklbw	mm6, mm2
	punpcklbw	mm7, mm3
	punpcklbw	mm0, [quad2]
	punpcklbw	mm1, [quad3]
	punpcklbw	mm2, [quad4]
	punpcklbw	mm3, [quad1]
	punpcklbw	mm0, mm5
	punpcklbw	mm1, mm6
	punpcklbw	mm2, mm7
	punpcklbw	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                        source/v64/tests/nasm/punpckldq.asm                                                                 0000644 0000000 0000000 00000001251 00000000000 014466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad00adad007fff
quad2:
	dq	0xac4b1b9de29df0ff
quad3:
	dq	0x01008080f0f0ff42
quad4:
	dq	0x0123456789abcdef
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	punpckldq	mm4, mm0
	punpckldq	mm5, mm1
	punpckldq	mm6, mm2
	punpckldq	mm7, mm3
	punpckldq	mm0, [quad2]
	punpckldq	mm1, [quad3]
	punpckldq	mm2, [quad4]
	punpckldq	mm3, [quad1]
	punpckldq	mm0, mm5
	punpckldq	mm1, mm6
	punpckldq	mm2, mm7
	punpckldq	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/punpcklwd.asm                                                                 0000644 0000000 0000000 00000001251 00000000000 014474  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0x00ad00adad007fff
quad2:
	dq	0xac4b1b9de29df0ff
quad3:
	dq	0x01008080f0f0ff42
quad4:
	dq	0x0123456789abcdef
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	punpcklwd	mm4, mm0
	punpcklwd	mm5, mm1
	punpcklwd	mm6, mm2
	punpcklwd	mm7, mm3
	punpcklwd	mm0, [quad2]
	punpcklwd	mm1, [quad3]
	punpcklwd	mm2, [quad4]
	punpcklwd	mm3, [quad1]
	punpcklwd	mm0, mm5
	punpcklwd	mm1, mm6
	punpcklwd	mm2, mm7
	punpcklwd	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/nasm/push.asm                                                                      0000644 0000000 0000000 00000001205 00000000000 013443  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
    align 16
myaddress:
    dd  0xdeadbeef

%include "header.inc"

    ;; push r/m - push edx
    db      0xff
    db      0xf2

    ;; push r/m - push bx
    db      0x66
    db      0xff
    db      0xf3

    ;; push imm
    push    0xdeadbeef
    push    WORD 0xd00d

    ;; push r/m - mem
    push    DWORD [myaddress]
    lea     eax, [myaddress]
    push    WORD [eax]

    ;; push reg
    mov     ecx, 0xcafe
    push    cx
    push    ecx

    xor     eax, eax

    pop     ax
    pop     eax
    pop     cx
    pop     ecx
    pop     dx
    pop     ebx
    pop     si
    pop     di

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/nasm/pushf.asm                                                                     0000644 0000000 0000000 00000000234 00000000000 013612  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    pushf
    and dword [esp], ~0x0200 ; if

    db 66h
    pushf
    and dword [esp], ~0x0200

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/pxor.asm                                                                      0000644 0000000 0000000 00000001214 00000000000 013454  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
quad1:
	dq	0xad0000ceadad00ff
quad2:
	dq	0xffffffffffffffff
quad3:
	dq	0x0000000000000000
quad4:
	dq	0x7fff8000ffff0808
myquad:
	dq	0xad0000ceadad00ff
mydword:
	dd	0xcafebabe
myaddress:
	dq	0x00adbeefc0de00ce

%include "header.inc"

	movq		mm0, [quad1]
	movq		mm1, [quad2]
	movq		mm2, [quad3]
	movq		mm3, [quad4]
	movq		mm4, [quad1]
	movq		mm5, [quad2]
	movq		mm6, [quad3]
	movq		mm7, [quad4]

	pxor	mm4, mm0
	pxor	mm5, mm1
	pxor	mm6, mm2
	pxor	mm7, mm3
	pxor	mm0, [quad2]
	pxor	mm1, [quad3]
	pxor	mm2, [quad4]
	pxor	mm3, [quad1]
	pxor	mm0, mm5
	pxor	mm1, mm6
	pxor	mm2, mm7
	pxor	mm3, mm4

%include "footer.inc"
                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/nasm/qemu_oracle.js                                                                0000644 0000000 0000000 00000042703 00000000000 014624  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Reference state for a nasm test from QEMU TCG instead of gdb, for hosts
// that cannot run the i386 test binaries natively (macOS, arm64): the image
// (a multiboot ELF) runs as the kernel of qemu-system-i386; at the final HLT
// the QMP monitor's "info registers" and "pmemsave" give the state that
// gdb-extract-def records at the `loop` label, and the fixture is written in
// the same format (run.js reads either). An exception is taken from the
// "-d int" log: its vector and faulting EIP, with the same "(signal ...)"
// markers gdb prints (only these are compared for such tests).
//
// The tests are written for Linux user mode; under QEMU they run at CPL 0
// without paging, which gives the same results for everything run.js
// compares (the arithmetic flags only, not IF/IOPL).
//
// Hardware sets the sign/exponent of an x87 register to 0xFFFF when an MMX
// instruction writes it; QEMU only writes the low 64 bits. The stub fills
// the eight physical registers with SENTINEL before FNINIT (which keeps
// their contents), so a register still carrying the sentinel exponent was
// written by MMX (reported with 0xFFFF) or not at all (reported as the zero
// a new Linux process has). Where QEMU itself differs from hardware (x87
// stack faults, some undefined flags and #UD cases), the fixture says
// "Reference: QEMU" and run.js applies the list in QEMU_DEVIATIONS.
//
// QEMU 10 TCG zeroes the operand of RCL/RCR with an immediate count that is
// a nonzero multiple of the operand width + 1; on hardware the masked count
// (COUNT AND 1FH) MOD 9 or 17 is then 0: operand and CF unchanged, OF
// undefined (Intel SDM, RCL/RCR/ROL/ROR). The image QEMU runs has such
// instructions replaced by NOPs of the same length (from a nasm listing of
// the test's source).

import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const SIGNALS = { 0: "SIGFPE", 6: "SIGILL", 13: "SIGSEGV", 14: "SIGSEGV", 17: "SIGBUS" };
// (a generator that exits without reaching `finally` must not leave QEMU running)
const children = new Set();
process.on("exit", () => { for(const child of children) child.kill("SIGKILL"); });
const BSS = 0x100000, MEMORY_BYTES = 0x2000;
const SENTINEL = { mantissa: 0xC0DE5EED1234ABCDn, exponent: 0x2ACE };
const NASM_DIRECTORY = fileURLToPath(new URL(".", import.meta.url));
export const QEMU_MARKER = "Reference: QEMU (tests/nasm/qemu_oracle.js)";

function qmp(child)
{
    let buffer = "";
    const waiting = [];
    child.stdout.on("data", data => {
        buffer += data;
        for(let newline; (newline = buffer.indexOf("\n")) >= 0;)
        {
            const line = buffer.slice(0, newline);
            buffer = buffer.slice(newline + 1);
            let message;
            try { message = JSON.parse(line); } catch(e) { continue; }
            if(("return" in message || "error" in message) && waiting.length) waiting.shift()(message);
        }
    });
    return (execute, args) => new Promise(resolve => {
        waiting.push(resolve);
        child.stdin.write(JSON.stringify(args ? { execute, arguments: args } : { execute }) + "\n");
    });
}

const hex = (text, name) => {
    const match = text.match(new RegExp(`\\b${name}=\\s*([0-9a-f]+)`, "i"));
    if(!match) throw new Error(`qemu oracle: no ${name} in:\n${text}`);
    return match[1];
};
const int32 = value => value | 0;

/** 80-bit extended (64-bit mantissa with explicit integer bit, 16-bit sign/exponent) as the nearest double */
function extended_to_double(mantissa, exponent_sign)
{
    const sign = exponent_sign & 0x8000 ? -1 : 1;
    const exponent = exponent_sign & 0x7FFF;
    if(exponent === 0x7FFF)
    {
        return (mantissa & 0x7FFFFFFFFFFFFFFFn) === 0n ? sign * Infinity : NaN;
    }
    if(mantissa === 0n) return sign * 0;
    // mantissa * 2^(exponent - 16383 - 63), rounded once through a 53-bit significand
    let shift = 0;
    let m = mantissa;
    while(m >= 1n << 53n) { m >>= 1n; shift++; }
    // round to nearest even on the dropped bits
    const dropped = mantissa - (m << BigInt(shift));
    const half = shift ? 1n << BigInt(shift - 1) : 0n;
    if(shift && (dropped > half || dropped === half && (m & 1n))) m++;
    return sign * Number(m) * Math.pow(2, exponent - 16383 - 63 + shift);
}

/** The tag gdb computes from an fxsave image (i387_tag): 0 valid, 1 zero,
 * 2 special; empty registers are 3. gdb-extract-def prints registers tagged
 * 2 as "invalid", and run.js reads 0xAAAA (all eight written by MMX) as
 * "compare the MMX registers" */
function tag(mantissa, exponent_sign)
{
    const exponent = exponent_sign & 0x7FFF;
    if(exponent === 0 && mantissa === 0n) return 1;                             // zero
    if(exponent === 0x7FFF || exponent === 0 || !(mantissa >> 63n)) return 2;   // special
    return 0;
}

function format_double(x)
{
    if(Number.isNaN(x)) return "nan";
    if(x === Infinity) return "inf";
    if(x === -Infinity) return "-inf";
    return x.toExponential(20).replace("e+", "e+");
}

/** Address of a section of an ELF32 image, by name */
function section_address(elf, name)
{
    const shoff = elf.readUInt32LE(32), shentsize = elf.readUInt16LE(46), shnum = elf.readUInt16LE(48);
    const strings = elf.readUInt32LE(shoff + elf.readUInt16LE(50) * shentsize + 16);
    for(let i = 0; i < shnum; i++)
    {
        const at = shoff + i * shentsize;
        const start = strings + elf.readUInt32LE(at);
        if(elf.toString("latin1", start, elf.indexOf(0, start)) === name) return elf.readUInt32LE(at + 12);
    }
    throw new Error("qemu oracle: no section " + name);
}

/**
 * The .text offsets and lengths of RCL/RCR instructions with an immediate
 * count that QEMU 10 mishandles (see above), from a nasm listing of the source
 * @param {string} source
 * @return {!Array<{offset: number, length: number}>}
 */
export function rotate_through_carry_noops(source)
{
    const text = fs.readFileSync(source, "utf8");
    if(!/^\s*rc[lr]\b.*,\s*(?!cl\b)\w+\s*$/im.test(text)) return [];
    const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "v86-nasm-list-"));
    try
    {
        const listing = path.join(scratch, "listing");
        const result = spawnSync("nasm", ["-felf32", "-l", listing, "-o", path.join(scratch, "object"), path.resolve(source)],
            { cwd: NASM_DIRECTORY, encoding: "utf8" });
        if(result.status !== 0) throw new Error("qemu oracle: nasm " + source + "\n" + result.stderr);
        const widths = { byte: 8, word: 16, dword: 32 };
        const register_width = r => /^[abcd][lh]$/.test(r) ? 8 : /^(ax|bx|cx|dx|sp|bp|si|di)$/.test(r) ? 16 : 32;
        const found = [];
        let section = "";
        for(const line of fs.readFileSync(listing, "utf8").split("\n"))
        {
            const directive = line.match(/^\s*\d+\s+(?:<\d+>\s+)?section\s+(\.\w+)/i);
            if(directive) { section = directive[1]; continue; }
            const code = line.match(/^\s*\d+\s+(?:<\d+>\s+)?([0-9A-F]{8}) ([0-9A-F]+)\s+(.*)$/);
            if(!code || section !== ".text") continue;
            const rotate = code[3].trim().match(/^rc[lr]\s+(?:(byte|word|dword)\s+\[[^\]]*\]|([a-z]+))\s*,\s*(0x[0-9a-f]+|[0-9][0-9a-f]*h|\d+)$/i);
            if(!rotate) continue;
            const width = rotate[1] ? widths[rotate[1].toLowerCase()] : register_width(rotate[2].toLowerCase());
            const literal = rotate[3].toLowerCase();
            const count = (literal.endsWith("h") ? parseInt(literal, 16) : Number(literal)) & 31;
            if(count && count % (width + 1) === 0) found.push({ offset: parseInt(code[1], 16), length: code[2].length / 2 });
        }
        return found;
    }
    finally
    {
        fs.rmSync(scratch, { recursive: true, force: true });
    }
}

/**
 * The test's ELF as a flat multiboot kernel (a header with address fields,
 * then the segments' bytes): QEMU loads that form regardless of how the
 * linker laid out the ELF.
 * @param {!Buffer} elf
 * @param {!Array<{offset: number, length: number}>=} noops .text ranges to replace by NOPs
 * @return {!Buffer}
 */
export function flat_multiboot(elf, noops = [])
{
    const entry = elf.readUInt32LE(24), phoff = elf.readUInt32LE(28);
    const phentsize = elf.readUInt16LE(42), phnum = elf.readUInt16LE(44);
    const segments = [];
    for(let i = 0; i < phnum; i++)
    {
        const at = phoff + i * phentsize;
        if(elf.readUInt32LE(at) !== 1 || !elf.readUInt32LE(at + 16)) continue; // PT_LOAD with bytes in the file
        segments.push({ offset: elf.readUInt32LE(at + 4), address: elf.readUInt32LE(at + 12), file: elf.readUInt32LE(at + 16) });
    }
    // The loader copies one contiguous range and would also clear any gap,
    // which must not reach the VGA/BIOS area at 640 KiB: segments below it
    // are loaded in place, the ones above 1 MiB (the tests' .data) are
    // staged after them and copied by the stub. (The BSS at 1 MiB is zero
    // RAM at boot.)
    const low_segments = segments.filter(s => s.address + s.file <= 0xA0000);
    const high_segments = segments.filter(s => s.address >= 0x100000);
    if(low_segments.length + high_segments.length !== segments.length) throw new Error("qemu oracle: a segment in the BIOS area");
    const low = Math.min(...low_segments.map(s => s.address));
    let staging = Math.max(...low_segments.map(s => s.address + s.file)) + 15 & ~15;
    const copies = high_segments.map(s => { const from = staging; staging += s.file + 15 & ~15; return { ...s, from }; });
    const load_end = staging;
    if(load_end > 0xA0000) throw new Error("qemu oracle: image too large for low memory");
    // the stub: the FPU/SSE state of a Linux process (CR0.MP/NE, no EM/TS;
    // CR4.OSFXSR/OSXMMEXCPT; FNINIT), the staged copies, then the entry
    const imm = v => [v & 0xFF, v >> 8 & 0xFF, v >> 16 & 0xFF, v >>> 24];
    // (FLD TBYTE of the sentinel eight times, then FNINIT), the staged
    // copies, then the entry; the sentinel's ten bytes follow the stub
    const code = sentinel_address => [0x0F, 0x20, 0xC0, 0x25, 0xF3, 0xFF, 0xFF, 0xFF, 0x83, 0xC8, 0x22, 0x0F, 0x22, 0xC0,
        0x0F, 0x20, 0xE0, 0x0D, 0x00, 0x06, 0x00, 0x00, 0x0F, 0x22, 0xE0,
        ...Array(8).fill([0xDB, 0x2D, ...imm(sentinel_address)]).flat(), 0xDB, 0xE3, 0xFC,
        ...copies.flatMap(c => [0xBE, ...imm(c.from), 0xBF, ...imm(c.address), 0xB9, ...imm(c.file), 0xF3, 0xA4]),
        0xB8, ...imm(entry), 0xFF, 0xE0];
    const sentinel = Buffer.alloc(10);
    sentinel.writeBigUInt64LE(SENTINEL.mantissa);
    sentinel.writeUInt16LE(SENTINEL.exponent, 8);
    const code_length = code(0).length;
    const HEADER = 32 + code_length + 10 + 15 & ~15, header_address = low - HEADER;
    const stub = code(header_address + 32 + code_length);
    const image = Buffer.alloc(HEADER + load_end - low);
    const flags = 0x10000;
    [0x1BADB002, flags, -(0x1BADB002 + flags) >>> 0, header_address, header_address, load_end, 0, header_address + 32]
        .forEach((value, i) => image.writeUInt32LE(value >>> 0, i * 4));
    Buffer.from(stub).copy(image, 32);
    sentinel.copy(image, 32 + code_length);
    for(const s of low_segments) elf.copy(image, HEADER + s.address - low, s.offset, s.offset + s.file);
    for(const c of copies) elf.copy(image, HEADER + c.from - low, c.offset, c.offset + c.file);
    if(noops.length)
    {
        const text = section_address(elf, ".text");
        for(const { offset, length } of noops) image.fill(0x90, HEADER + text + offset - low, HEADER + text + offset - low + length);
    }
    return image;
}

/**
 * @param {string} image path of the test's .img
 * @return {Promise<string>} fixture text
 */
export async function qemu_fixture(image)
{
    // generated tests keep their source next to the image, the others one directory up
    const name = path.basename(image, ".img") + ".asm";
    const source = [path.join(path.dirname(image), name), path.join(path.dirname(image), "..", name)].find(p => fs.existsSync(p));
    const noops = source ? rotate_through_carry_noops(source) : [];
    const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "v86-nasm-"));
    const log = path.join(scratch, "int.log"), dump = path.join(scratch, "memory.bin");
    const kernel = path.join(scratch, "kernel.bin");
    fs.writeFileSync(kernel, flat_multiboot(fs.readFileSync(image), noops));
    const child = spawn(process.env.QEMU_I386 || "qemu-system-i386", ["-machine", "pc,accel=tcg", "-cpu", "max", "-m", "32",
        "-display", "none", "-serial", "none", "-monitor", "none", "-qmp", "stdio", "-no-reboot", "-no-shutdown",
        "-d", "int", "-D", log, "-kernel", kernel], { stdio: ["pipe", "pipe", "pipe"] });
    children.add(child);
    let stderr = "", exited = false;
    child.stderr.on("data", data => { stderr += data; });
    child.on("exit", () => { exited = true; });
    const command = qmp(child);
    try
    {
        await command("qmp_capabilities");
        const deadline = Date.now() + 20000;
        let registers;
        for(;;)
        {
            if(Date.now() > deadline || exited) throw new Error("qemu oracle: " + image + (exited ? " exited" : " did not halt") + "\n" + stderr);
            const status = (await command("query-status")).return?.status;
            registers = (await command("human-monitor-command", { "command-line": "info registers" })).return || "";
            if(status === "shutdown" || /\bHLT=1\b/.test(registers)) break;
            await new Promise(resolve => setTimeout(resolve, 5));
        }
        const exception = first_exception(fs.existsSync(log) ? fs.readFileSync(log, "utf8") : "");
        await command("pmemsave", { val: BSS, size: MEMORY_BYTES, filename: dump });
        const memory = fs.existsSync(dump) ? fs.readFileSync(dump) : Buffer.alloc(MEMORY_BYTES);
        // registers stored by FSAVE/FXSAVE that were never written: zero, as in a new process
        const sentinel = Buffer.alloc(10);
        sentinel.writeBigUInt64LE(SENTINEL.mantissa);
        sentinel.writeUInt16LE(SENTINEL.exponent, 8);
        for(let at; (at = memory.indexOf(sentinel)) >= 0;) memory.fill(0, at, at + 10);
        return fixture(registers, memory, exception);
    }
    finally
    {
        child.kill("SIGKILL");
        children.delete(child);
        fs.rmSync(scratch, { recursive: true, force: true });
    }
}

/** The first CPU exception in QEMU's interrupt log: { vector, eip } */
function first_exception(text)
{
    for(const line of text.split("\n"))
    {
        const match = line.match(/^\s*\d+: v=([0-9a-f]+) .*?pc=([0-9a-f]+)/i);
        if(match && parseInt(match[1], 16) < 32) return { vector: parseInt(match[1], 16), eip: parseInt(match[2], 16) };
    }
    return null;
}

function fixture(registers, memory, exception)
{
    const values = [];
    for(const name of ["EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI"]) values.push(int32(parseInt(hex(registers, name), 16)));
    // gdb stops at `loop`, before the HLT QEMU has executed; after an
    // exception, at the faulting instruction
    const eip = exception ? exception.eip : parseInt(hex(registers, "EIP"), 16) - 1;
    values.push(int32(eip));

    const fsw = parseInt(hex(registers, "FSW"), 16);
    const abridged = parseInt(hex(registers, "FTW"), 16);
    const physical = [];
    for(let i = 0; i < 8; i++)
    {
        const match = registers.match(new RegExp(`FPR${i}=([0-9a-f]{16}) ([0-9a-f]{4})`, "i"));
        if(!match) throw new Error("qemu oracle: FPR" + i + "\n" + registers);
        let mantissa = BigInt("0x" + match[1]), exponent = parseInt(match[2], 16);
        if(exponent === SENTINEL.exponent)
        {
            // untouched: the zero of a new process; else written by MMX
            const untouched = mantissa === SENTINEL.mantissa;
            if(untouched) mantissa = 0n;
            exponent = untouched ? 0 : 0xFFFF;
        }
        physical.push({ mantissa, exponent });
    }
    let tags = 0;
    for(let i = 0; i < 8; i++)
    {
        const t = abridged >> i & 1 ? tag(physical[i].mantissa, physical[i].exponent) : 3;
        tags |= t << 2 * i;
    }
    const top = fsw >> 11 & 7;
    const st = [];
    for(let i = 0; i < 8; i++)
    {
        const r = (top + i) & 7;
        st.push((tags >> 2 * r & 3) === 2 ? "\"invalid\"" : format_double(extended_to_double(physical[r].mantissa, physical[r].exponent)));
    }
    const mmx = [];
    for(let i = 0; i < 8; i++)
    {
        mmx.push(int32(Number(physical[i].mantissa & 0xFFFFFFFFn)), int32(Number(physical[i].mantissa >> 32n)));
    }
    const xmm = [];
    for(let i = 0; i < 8; i++)
    {
        // "XMM0i=<high qword> <low qword>"
        const match = registers.match(new RegExp(`XMM0${i}=([0-9a-f]{16}) ([0-9a-f]{16})`, "i"));
        if(!match) throw new Error("qemu oracle: XMM" + i + "\n" + registers);
        const text = match[1] + match[2];
        for(let lane = 0; lane < 4; lane++) xmm.push(int32(parseInt(text.slice(24 - 8 * lane, 32 - 8 * lane), 16)));
    }
    const words = [];
    for(let i = 0; i < MEMORY_BYTES; i += 4) words.push(memory.readInt32LE(i));
    const eflags = parseInt(hex(registers, "EFL"), 16);
    const lines = [
        QEMU_MARKER,
        ...(exception ? [`Program received signal (signal ${SIGNALS[exception.vector] || "SIGSEGV"}), vector ${exception.vector}`] : []),
        "---BEGIN JSON---", "[",
        ...values.map(v => `    ${v},`), "",
        ...st.map(v => `    ${v},`), "",
        ...mmx.map(v => `    ${v},`), "",
        ...xmm.map(v => `    ${v},`), "",
    ];
    for(let i = 0; i < words.length; i += 8) lines.push("    " + words.slice(i, i + 8).join(", ") + ",");
    lines.push("", `    ${eflags},`, `    ${tags},`, `    ${fsw}`, "]", "---END JSON---", "");
    return lines.join("\n");
}
                                                             source/v64/tests/nasm/rand.js                                                                       0000644 0000000 0000000 00000003671 00000000000 013255  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // From http://baagoe.com/en/RandomMusings/javascript/
// Johannes Baagøe <baagoe@baagoe.com>, 2010
function Mash() {
  var n = 0xefc8249d;

  var mash = function(data) {
    data = data.toString();
    for(var i = 0; i < data.length; i++) {
      n += data.charCodeAt(i);
      var h = 0.02519603282416938 * n;
      n = h >>> 0;
      h -= n;
      h *= n;
      n = h >>> 0;
      h -= n;
      n += h * 0x100000000; // 2^32
    }
    return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
  };

  return mash;
}

// From http://baagoe.com/en/RandomMusings/javascript/
export default function KISS07() {
  return (function(args) {
    // George Marsaglia, 2007-06-23
    //http://groups.google.com/group/comp.lang.fortran/msg/6edb8ad6ec5421a5
    var x = 123456789;
    var y = 362436069;
    var z =  21288629;
    var w =  14921776;
    var c = 0;

    if(args.length === 0) {
      args = [+new Date];
    }
    var mash = Mash();
    for(var i = 0; i < args.length; i++) {
      x ^= mash(args[i]) * 0x100000000; // 2^32
      y ^= mash(args[i]) * 0x100000000;
      z ^= mash(args[i]) * 0x100000000;
      w ^= mash(args[i]) * 0x100000000;
    }
    if(y === 0) {
      y = 1;
    }
    c ^= z >>> 31;
    z &= 0x7fffffff;
    if((z % 7559) === 0) {
      z++;
    }
    w &= 0x7fffffff;
    if((w % 7559) === 0) {
      w++;
    }
    mash = null;

    var int32 = function() {
      var t;

      x += 545925293;
      x >>>= 0;

      y ^= y << 13;
      y ^= y >>> 17;
      y ^= y << 5;

      t = z + w + c;
      z = w;
      c = t >>> 31;
      w = t & 0x7fffffff;

      return x + y + w | 0;
    };
    var uint32 = function() {
      var t;

      x += 545925293;
      x >>>= 0;

      y ^= y << 13;
      y ^= y >>> 17;
      y ^= y << 5;

      t = z + w + c;
      z = w;
      c = t >>> 31;
      w = t & 0x7fffffff;

      return x + y + w >>> 0;
    };

    return {
        int32,
        uint32,
    };
  } (Array.prototype.slice.call(arguments)));
}
                                                                       source/v64/tests/nasm/ret-imm.asm                                                                   0000644 0000000 0000000 00000000315 00000000000 014037  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    jmp start
foo:
    mov eax, esp
    ret 123

start:
    call foo
    mov dword [eax], 0 ; clear the address pushed by the call instruction


%include "footer.inc"
                                                                                                                                                                                                                                                                                                                   source/v64/tests/nasm/run.js                                                                        0000755 0000000 0000000 00000053323 00000000000 013137  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import assert from "node:assert/strict";
import os from "node:os";
import cluster from "node:cluster";

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

process.on("unhandledRejection", exn => { throw exn; });

// Mapping between signals and x86 exceptions:
// "Program received signal SIGILL, Illegal instruction." -> #UD (6)
// "Program received signal SIGFPE, Arithmetic exception." -> #DE (0)
// to be determined -> #GP
// to be determined -> #NM
// to be determined -> #TS
// to be determined -> #NP
// to be determined -> #SS
// to be determined -> #PF

// A #UD might indicate a bug in the test generation

const MAX_PARALLEL_TESTS = +process.env.MAX_PARALLEL_TESTS || 99;
const TEST_NAME = new RegExp(process.env.TEST_NAME || "", "i");
const SINGLE_TEST_TIMEOUT = 10000;

const TEST_DIR = __dirname + "/build/";
const DONE_MSG = "DONE";
const TERMINATE_MSG = "DONE";
const READY_MSG = "READY";

const BSS = 0x100000;
const STACK_TOP = 0x102000;

// --force-jit: code compiles at the first opportunity (the x64 page tier's
// 32-bit pages after one instruction, regions after one visit), so code that runs more than once
// executes compiled.
const FORCE_JIT = process.argv.includes("--force-jit");

// alternative representation for infinity for json
const JSON_POS_INFINITY = "+INFINITY";
const JSON_NEG_INFINITY = "-INFINITY";
const JSON_POS_NAN = "+NAN";
const JSON_NEG_NAN = "-NAN";

const MASK_ARITH = 1 | 1 << 2 | 1 << 4 | 1 << 6 | 1 << 7 | 1 << 11;
const FPU_TAG_ALL_INVALID = 0xAAAA;
const FPU_STATUS_MASK = 0xFFFF & ~(1 << 9 | 1 << 5 | 1 << 3 | 1 << 1); // bits that are not correctly implemented by v86
const FP_COMPARISON_SIGNIFICANT_DIGITS = 7;

const CF = 1, PF = 1 << 2, AF = 1 << 4, ZF = 1 << 6, SF = 1 << 7, OF = 1 << 11;
const FPU_IE = 1, FPU_SF = 1 << 6, FPU_C0 = 1 << 8, FPU_C1 = 1 << 9, FPU_C3 = 1 << 14;

// Where QEMU TCG differs from hardware. Used only for fixtures from
// qemu_oracle.js (hosts without gdb, "Reference: QEMU" in the fixture): a
// difference a rule covers is not a failure, and the summary counts each
// rule's uses. `tests` limits a rule to test names, `when` to the state seen,
// `covers` says which differences it explains.
const flags_only = mask => f => f.name === "eflags" && ((f.actual ^ f.expected) & ~mask) === 0;
const QEMU_DEVIATIONS = [
    {
        // v86 saw an x87 stack under- or overflow (FSW.SF): hardware returns the
        // indefinite NaN, sets IE/SF and makes compares unordered; QEMU does not
        // look at the tag word and computes with the stale register contents
        name: "x87 stack fault (QEMU ignores empty registers)",
        when: seen => (seen.fpu_status & FPU_SF) !== 0,
        covers: f => /^st\d$|^fpu status word$/.test(f.name),
    },
    {
        // and the ZF/PF/CF of FCOMI/FUCOMI(P) that come from such a compare
        name: "x87 stack fault in FCOMI/FUCOMI",
        tests: /^gen_d[bf]_[56]_/,
        when: seen => (seen.fpu_status & FPU_SF) !== 0,
        covers: flags_only(ZF | PF | CF | OF | SF | AF),
    },
    {
        // SDM: FCOMI/FUCOMI(P) clear OF, SF and AF; QEMU leaves them
        name: "FCOMI/FUCOMI clear OF, SF, AF",
        tests: /^gen_d[bf]_[56]_/,
        covers: f => flags_only(OF | SF | AF)(f) && (f.actual & (OF | SF | AF)) === 0,
    },
    {
        // SDM: OF, SF, AF and PF are undefined after BT/BTS/BTR/BTC
        name: "BT/BTS/BTR/BTC undefined flags",
        tests: /^gen_0f(a3|ab|b3|bb|ba_[4-7])_/,
        covers: flags_only(OF | SF | AF | PF),
    },
    {
        // SDM: MOVLPD, MOVHPD, MOVNTQ and MOVNTDQ have memory forms only
        // (register forms raise #UD); QEMU executes the register forms
        name: "#UD for register forms of MOVLPD/MOVHPD/MOVNTQ/MOVNTDQ",
        tests: /^gen_(660f12|660f16|0fe7|660fe7)_/,
        when: (seen, fixture) => seen.exception === "UD" && !fixture.exception,
        covers: () => true,
    },
    {
        // hardware (the gdb fixtures these tests were written against) executes
        // CMPXCHG8B with an operand-size prefix and F6/F7 /1 (TEST); QEMU raises #UD
        name: "66 CMPXCHG8B and F6/F7 /1 execute",
        tests: /^gen_(0fc7_1|f6_1|f7_1)_/,
        when: (seen, fixture) => !seen.exception && fixture.exception === "UD",
        covers: () => true,
    },
    {
        // the reserved upper words of the 32-bit FSAVE/FSTENV image: 0xFFFF on
        // hardware (and v86), 0 from QEMU
        name: "FSAVE/FSTENV reserved words",
        tests: /fsave|fstenv/,
        covers: f => f.name.startsWith("mem[") && f.actual >>> 16 === 0xFFFF && f.expected >>> 16 === 0 &&
            ((f.actual ^ f.expected) & 0xFFFF) === 0,
    },
    {
        // SDM: FYL2XP1 outside |x| < 1 - sqrt(2)/2 has an undefined result, no
        // exception; QEMU sets IE
        name: "FYL2XP1 outside its domain",
        tests: /^fyl2xp1$/,
        covers: f => f.name === "fpu status word" && (f.actual ^ f.expected) === FPU_IE,
    },
    {
        // FPREM/FPREM1 of 0 by 0 (invalid): QEMU clears C3/C1/C0, Bochs and v86
        // keep the codes of the previous FPREM; the SDM does not say and there
        // is no hardware reference yet
        name: "FPREM condition codes after an invalid operation (unverified)",
        tests: /^fprem1?$/,
        covers: f => f.name === "fpu status word" && ((f.actual ^ f.expected) & ~(FPU_C0 | FPU_C1 | FPU_C3)) === 0,
    },
];

/** The rule that explains a difference, if any */
function qemu_deviation(test_name, failure, seen, fixture)
{
    return QEMU_DEVIATIONS.find(rule =>
        (!rule.tests || rule.tests.test(test_name)) && (!rule.when || rule.when(seen, fixture)) && rule.covers(failure));
}

function float_equal(x, y)
{
    assert(typeof x === "number");
    assert(typeof y === "number");

    if(x === Infinity && y === Infinity || x === -Infinity && y === -Infinity || isNaN(x) && isNaN(y))
    {
        return true;
    }

    const epsilon = Math.pow(10, -FP_COMPARISON_SIGNIFICANT_DIGITS);
    return Math.abs(x - y) < epsilon;
}

function format_value(v)
{
    if(typeof v === "number")
    {
        if((v >>> 0) !== v && (v | 0) !== v)
        {
            return String(v);
        }
        else
        {
            return "0x" + (v >>> 0).toString(16);
        }
    }
    else
    {
        return String(v);
    }
}

if(cluster.isMaster)
{
    function extract_json(name, fixture_text)
    {
        let exception;

        if(fixture_text.includes("(signal SIGFPE)"))
        {
            exception = "DE";
        }

        if(fixture_text.includes("(signal SIGILL)"))
        {
            exception = "UD";
        }

        if(fixture_text.includes("(signal SIGSEGV)"))
        {
            exception = "GP";
        }

        if(fixture_text.includes("(signal SIGBUS)"))
        {
            exception = "PF";
        }

        if(!exception && fixture_text.includes("Program received signal"))
        {
            throw new Error("Test was killed during execution by gdb: " + name + "\n" + fixture_text);
        }

        fixture_text = fixture_text.toString()
            .replace(/-inf\b/g, JSON.stringify(JSON_NEG_INFINITY))
            .replace(/\binf\b/g, JSON.stringify(JSON_POS_INFINITY))
            .replace(/-nan\b/g, JSON.stringify(JSON_NEG_NAN))
            .replace(/\bnan\b/g, JSON.stringify(JSON_POS_NAN));

        const json_regex = /---BEGIN JSON---([\s\[\]\.\+\w":\-,]*)---END JSON---/;
        const regex_match = json_regex.exec(fixture_text);
        if(!regex_match || regex_match.length < 2) {
            throw new Error("Could not find JSON in fixture text: " + fixture_text + "\nTest: " + name);
        }

        let array = JSON.parse(regex_match[1]);
        return {
            array: array,
            exception,
            qemu: fixture_text.startsWith("Reference: QEMU"),
        };
    }


    function send_work_to_worker(worker, message) {
        if(current_test < tests.length) {
            const test = tests[current_test];
            worker.send(test);
            current_test++;
        }
        else {
            worker.send(TERMINATE_MSG);
            worker.disconnect();

            setTimeout(() => {
                // The emulator currently doesn't cleanly exit, so this is necessary
                console.log("Worker killed");
                worker.kill();
            }, 100);

            finished_workers++;
            if(finished_workers === nr_of_cpus)
            {
                test_finished();
            }
        }
    }

    const dir_files = fs.readdirSync(TEST_DIR);
    const files = dir_files.filter((name) => {
        return name.endsWith(".img");
    }).map(name => {
        return name.slice(0, -4);
    }).filter(name => {
        return TEST_NAME.test(name + ".img");
    });

    const tests = files.map(name => {
        let fixture_name = name + ".fixture";
        let img_name = name + ".img";
        let fixture_text = fs.readFileSync(TEST_DIR + fixture_name);
        let fixture = extract_json(name, fixture_text);

        return {
            img_name: img_name,
            fixture: fixture,
        };
    });

    const nr_of_cpus = Math.min(
        os.cpus().length || 1,
        tests.length,
        MAX_PARALLEL_TESTS
    );
    console.log("Using %d cpus", nr_of_cpus);

    let current_test = 0;

    let failed_tests = [];
    const qemu_deviations = {};
    let finished_workers = 0;

    for(let i = 0; i < nr_of_cpus; i++)
    {
        let worker = cluster.fork();

        worker.on("message", function(message) {
            if(message !== DONE_MSG && message !== READY_MSG) {
                for(const name of message.deviations || [])
                {
                    qemu_deviations[name] = qemu_deviations[name] || new Set();
                    qemu_deviations[name].add(message.img_name);
                }
                if(message.failures.length) failed_tests.push(message);
            }
            send_work_to_worker(this);
        });

        worker.on("exit", function(code, signal) {
            if(code !== 0 &&  code !== null) {
                console.log("Worker error code:", code);
                process.exit(code);
            }
        });

        worker.on("error", function(error) {
            console.error("Worker error: ", error.toString(), error);
            process.exit(1);
        });
    }

    function test_finished()
    {
        console.log(
            "\n[+] Passed %d/%d tests.",
            tests.length - failed_tests.length,
            tests.length
        );
        const qemu_fixtures = tests.filter(t => t.fixture.qemu).length;
        if(qemu_fixtures)
        {
            console.log("[~] %d fixture(s) from QEMU; known QEMU deviations (tests/nasm/run.js QEMU_DEVIATIONS):", qemu_fixtures);
            for(const rule of QEMU_DEVIATIONS)
            {
                const seen = qemu_deviations[rule.name];
                if(seen) console.log("    %s: %d test(s), e.g. %s", rule.name, seen.size, [...seen].slice(0, 3).join(" "));
            }
        }
        if(failed_tests.length > 0) {
            console.log("[-] Failed %d test(s).", failed_tests.length);
            failed_tests.forEach(function(test_failure) {

                console.error("\n[-] %s:", test_failure.img_name);

                test_failure.failures.forEach(function(failure) {
                    console.error("\n\t" + failure.name);
                    console.error("\tActual:   " + failure.actual);
                    console.error("\tExpected: " + failure.expected);
                });
            });
            process.exit(1);
        }
    }
}
else {
    function run_test(test)
    {
        if(!loaded)
        {
            first_test = test;
            return;
        }

        waiting_to_receive_next_test = false;
        current_test = test;
        console.info("Testing", test.img_name);

        var cpu = emulator.v86.cpu;

        assert(!emulator.running);

        cpu.reboot_internal();
        cpu.reset_memory();
        cpu.load_multiboot(fs.readFileSync(TEST_DIR + current_test.img_name).buffer);
        // SSE enabled by the OS (CR4.OSFXSR and OSXMMEXCPT), as the QEMU
        // oracle's stub does (qemu_oracle.js): the BIOS and the multiboot
        // entry leave CR4 as it is
        cpu.cr[4] |= 0x600;

        test_timeout = setTimeout(() => {
            console.error("Test " + test.img_name + " timed out after " + (SINGLE_TEST_TIMEOUT / 1000) + " seconds.");
            process.exit(2);
        }, SINGLE_TEST_TIMEOUT);

        emulator.run();
    }

    let loaded = false;
    let current_test = undefined;
    let first_test = undefined;
    let waiting_to_receive_next_test = false;
    let recorded_exceptions = [];
    let test_timeout;

    let emulator = new V86({
        graphics_adapter: "bochs_vga",
        autostart: false,
        memory_size: 2 * 1024 * 1024,
        disable_jit: +process.env.DISABLE_JIT,
        // the references are hardware results: exact x87 arithmetic and flags
        x87_fast_math: false,
        // the generated tests include the forms of docs/simd-xsave-plan.md
        // that are implemented so far
        cpu_features: ["SSSE3", "SSE4.1", "SSE4.2"],
        ...FORCE_JIT ? { jit_switches: { x64_legacy_heat: 1, x64_legacy_recompile_misses: 1 } } : {},
        log_level: 0,
    });

    emulator.add_listener("emulator-loaded", function()
        {
            loaded = true;

            if(first_test)
            {
                run_test(first_test);
            }
        });

    emulator.cpu_exception_hook = function(n)
    {
        emulator.v86.cpu.instruction_counter[0] += 100000; // always make progress

        if(waiting_to_receive_next_test)
        {
            return true;
        }

        const exceptions = {
            0: "DE",
            6: "UD",
            13: "GP",
        };

        const exception = exceptions[n];

        if(exception === undefined)
        {
            console.error("Unexpected CPU exception: " + n);
            process.exit(1);
        }

        const eip = emulator.v86.cpu.instruction_pointer[0];
        emulator.v86.cpu.write32(emulator.v86.cpu.translate_address_system_read(eip), 0xF4F4F4F4); // hlt

        // XXX: On gdb execution is stopped at this point. On v86 we
        // currently don't have this ability, so we record the exception
        // and continue execution
        recorded_exceptions.push({ exception, eip });
        finish_test();
        return true;
    };

    emulator.bus.register("cpu-event-halt", function() {
        finish_test();
    });

    function finish_test()
    {
        if(waiting_to_receive_next_test)
        {
            return;
        }

        waiting_to_receive_next_test = true;
        clearTimeout(test_timeout);

        emulator.stop();
        var cpu = emulator.v86.cpu;

        const evaluated_fpu_regs = new Float64Array(8).map((_, i) => cpu.fpu_get_sti_f64(i));
        const evaluated_mmxs = new Int32Array(16).map((_, i) => cpu.fpu_st[(i & ~1) << 1 | (i & 1)]);
        const evaluated_xmms = cpu.reg_xmm32s;
        const evaluated_memory = new Int32Array(cpu.mem8.buffer, cpu.mem8.byteOffset + BSS, STACK_TOP - BSS >> 2);
        const evaluated_fpu_tag = cpu.fpu_load_tag_word();
        const evaluated_fpu_status = cpu.fpu_load_status_word() & FPU_STATUS_MASK;

        let individual_failures = [];

        assert(current_test.fixture.array);

        const FLOAT_TRANSLATION = {
            [JSON_POS_INFINITY]: Infinity,
            [JSON_NEG_INFINITY]: -Infinity,
            [JSON_POS_NAN]: NaN,
            [JSON_NEG_NAN]: NaN, // XXX: Ignore sign of NaN
        };

        let offset = 0;
        const expected_reg32 = current_test.fixture.array.slice(offset, offset += 8);
        const expected_eip = current_test.fixture.array[offset++];
        const expected_fpu_regs =
            current_test.fixture.array.slice(offset, offset += 8) .map(x => x in FLOAT_TRANSLATION ? FLOAT_TRANSLATION[x] : x);
        const expected_mmx_registers = current_test.fixture.array.slice(offset, offset += 16);
        const expected_xmm_registers = current_test.fixture.array.slice(offset, offset += 32);
        const expected_memory = current_test.fixture.array.slice(offset, offset += 8192 / 4);
        const expected_eflags = current_test.fixture.array[offset++] & MASK_ARITH;
        const fpu_tag = current_test.fixture.array[offset++];
        const fpu_status = current_test.fixture.array[offset++] & FPU_STATUS_MASK;

        if(offset !== current_test.fixture.array.length)
        {
            throw new Error("Bad fixture length in test " + current_test.img_name);
        }

        if(!current_test.fixture.exception)
        {
            for(let i = 0; i < cpu.reg32.length; i++) {
                let reg = cpu.reg32[i];
                if(reg !== expected_reg32[i]) {
                    individual_failures.push({
                        name: "cpu.reg32[" + i + "]",
                        expected: expected_reg32[i],
                        actual: reg,
                    });
                }
            }

            if(fpu_tag !== FPU_TAG_ALL_INVALID)
            {
                for(let i = 0; i < evaluated_fpu_regs.length; i++) {
                    if(expected_fpu_regs[i] !== "invalid" &&
                            !float_equal(evaluated_fpu_regs[i], expected_fpu_regs[i])) {
                        individual_failures.push({
                            name: "st" + i,
                            expected: expected_fpu_regs[i],
                            actual: evaluated_fpu_regs[i],
                        });
                    }
                }

                if(fpu_status !== evaluated_fpu_status)
                {
                    individual_failures.push({
                        name: "fpu status word",
                        expected: fpu_status,
                        actual: evaluated_fpu_status,
                    });
                }
            }
            else
            {
                for(let i = 0; i < evaluated_mmxs.length; i++) {
                    if(evaluated_mmxs[i] !== expected_mmx_registers[i]) {
                        individual_failures.push({
                            name: "mm" + (i >> 1) + ".int32[" + (i & 1) + "]",
                            expected: expected_mmx_registers[i],
                            actual: evaluated_mmxs[i],
                        });
                    }
                }
            }

            for(let i = 0; i < evaluated_xmms.length; i++) {
                if(evaluated_xmms[i] !== expected_xmm_registers[i]) {
                    individual_failures.push({
                        name: "xmm" + (i >> 2) + ".int32[" + (i & 3) + "] (cpu.reg_xmm[" + i + "])",
                        expected: expected_xmm_registers[i],
                        actual: evaluated_xmms[i],
                    });
                }
            }

            for(let i = 0; i < evaluated_memory.length; i++) {
                if(evaluated_memory[i] !== expected_memory[i]) {
                    individual_failures.push({
                        name: "mem[" + (BSS + 4 * i).toString(16).toUpperCase() + "]",
                        expected: expected_memory[i],
                        actual: evaluated_memory[i],
                    });
                }
            }

            const seen_eflags = cpu.get_eflags() & MASK_ARITH;
            if(seen_eflags !== expected_eflags)
            {
                individual_failures.push({
                    name: "eflags",
                    expected: expected_eflags,
                    actual: seen_eflags,
                });
            }
        }

        if(current_test.fixture.exception)
        {
            const seen_eip = (recorded_exceptions[0] || {}).eip;
            if(seen_eip !== expected_eip)
            {
                individual_failures.push({
                    name: "exception eip",
                    expected: expected_eip,
                    actual: seen_eip === undefined ? "(none)" : seen_eip,
                });
            }
        }

        const seen_exception = (recorded_exceptions[0] || {}).exception;
        if(current_test.fixture.exception !== seen_exception)
        {
            individual_failures.push({
                name: "Exception",
                actual: seen_exception || "(none)",
                expected: current_test.fixture.exception,
            });
        }

        const deviations = new Set();
        if(current_test.fixture.qemu)
        {
            const seen = { exception: seen_exception, fpu_status: cpu.fpu_load_status_word() };
            const test_name = current_test.img_name.replace(/\.img$/, "");
            individual_failures = individual_failures.filter(failure => {
                const rule = qemu_deviation(test_name, failure, seen, current_test.fixture);
                if(rule) deviations.add(rule.name);
                return !rule;
            });
        }

        individual_failures = individual_failures.map(({ name, actual, expected }) => {
            return {
                name,
                actual: format_value(actual),
                expected: format_value(expected),
            };
        });

        recorded_exceptions = [];

        if(individual_failures.length > 0 || deviations.size) {
            process.send({
                failures: individual_failures,
                deviations: [...deviations],
                img_name: current_test.img_name
            });
        }
        else {
            process.send(DONE_MSG);
        }
    }

    cluster.worker.on("message", function(message) {
        if(message === TERMINATE_MSG)
        {
            emulator.stop();
            emulator = null;
        }
        else
        {
            run_test(message);
        }
    });

    process.send(READY_MSG);
}
                                                                                                                                                                                                                                                                                                             source/v64/tests/nasm/shufps-edgecase.asm                                                           0000644 0000000 0000000 00000000325 00000000000 015534  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

%include "header.inc"

    mov dword [esp+0], 1
    mov dword [esp+4], 2
    mov dword [esp+8], 3
    mov dword [esp+12], 4
    movdqu xmm3, [esp]
    shufps xmm3, xmm3, 0x32

%include "footer.inc"
                                                                                                                                                                                                                                                                                                           source/v64/tests/nasm/ucomiss.asm                                                                   0000644 0000000 0000000 00000001661 00000000000 014154  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       global _start

section .data
	align 16
controlword:
	dw 0
dwordmxcsr:
	dw 0
dword0:
	dd	1000.0
dword1:
	dd	5.0
dword2:
	dd	3000.0
dwSNaN:
	dd	__SNaN__
dwQNaN:
	dd	__QNaN__

; Moves EFLAGS into specified register
%macro moveflags 1
	pushf
	and			dword [esp], 0x45
	pop			eax
	movd		%1, eax
%endmacro

%include "header.inc"

	movd		xmm0, [dword0]
	; Equal
	ucomiss		xmm0, [dword0]
	moveflags	mm0				; [ZF] = 100000
	; Less than
	ucomiss		xmm0, [dword1]
	moveflags	mm1				; [CF] = 000001
	; Greater than
	ucomiss		xmm0, [dword2]
	moveflags	mm2				; [] = 000000

	; Unordered: Quiet NaN
	movd		xmm1, [dwQNaN]
	ucomiss		xmm0, xmm1
	moveflags	mm3				; [ZF][PF][CF] = 100101
	; Check #I exception
	stmxcsr		[dwordmxcsr]
	movd		mm4, [dwordmxcsr]

	; Unordered: Signaling NaN
	movd		xmm1, [dwSNaN]
	ucomiss		xmm0, xmm1
	moveflags	mm5				; [ZF][PF][CF] = 100101
	; Check #I exception
	stmxcsr		[dwordmxcsr]
	movd		mm6, [dwordmxcsr]

%include "footer.inc"
                                                                               source/v64/tests/parallel/bench.asm                                                                 0000644 0000000 0000000 00000016225 00000000000 014411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Fixed-work throughput kernel (docs/multicore.md):
; the same total work, split over 1..N cores, cooperative or in vCPU workers.
; The BSP starts the APs with INIT/SIPI; then rounds repeat: every core waits
; until the host raises GO above the rounds done, processes items and adds
; its partial result to SUM, whose final value does not depend on the number
; of cores or on which core took which item. With CHUNK = 0 each core takes
; the static share [core * total / cores, (core + 1) * total / cores);
; otherwise the cores claim CHUNK items at a time from NEXT with LOCK XADD
; (as parallel programs balance load; host cores need not be equally fast).
;
; Workloads (WORKLOAD):
; 1 compute: 64 rounds of multiply/rotate/xor per item
; 2 lock:    a shared counter and record updated under an XCHG spin lock,
;            with 32 rounds of private work outside it
; 3 memory:  copy a 4 KiB block of a 4 MiB buffer (REP MOVSD) to the core's
;            scratch page and sum it
; 4 io:      read the ACPI PM timer and write port 0x80
;
; Host interface at CONTROL: +0 cores, +4 workload, +8 total items, +12 GO,
; +32 CHUNK (input); +16 rounds done, +20 SUM, +24 lock counter, +28 errors
; (output); +36 NEXT (reset by the host before each round).

bits 32
org 0x100000

MB_MAGIC equ 0x1BADB002
MB_FLAGS equ 0x10000
CONTROL equ 0x380000
CORES equ CONTROL + 0
WORKLOAD equ CONTROL + 4
TOTAL equ CONTROL + 8
GO equ CONTROL + 12
DONE equ CONTROL + 16
SUM equ CONTROL + 20
COUNTER equ CONTROL + 24
ERRORS equ CONTROL + 28
CHUNK equ CONTROL + 32
NEXT equ CONTROL + 36
BARRIER_COUNT equ CONTROL + 0x40
BARRIER_SENSE equ CONTROL + 0x80
SPIN equ CONTROL + 0xC0
SHARED_RECORD equ CONTROL + 0x100
RECORDS equ CONTROL + 0x400     ; 64 bytes per core: +0 barrier sense
BUFFER equ 0x1000000            ; 4 MiB, filled once by the BSP
SCRATCH equ 0x1400000           ; 4 KiB per core
PM_TIMER equ 0x608
LAPIC equ 0xFEE00000
STACKS equ 0x300000

header:
    dd MB_MAGIC, MB_FLAGS, -(MB_MAGIC + MB_FLAGS)
    dd header, header, end, end, start

start:
    cli
    cld
    lgdt [gdtr]
    jmp 8:.protected
.protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, STACKS + 0x10000
    mov al, 0xFF
    out 0x21, al
    out 0xA1, al
    ; the PIIX4 PM block at 0x600 (00:07.0: PMBA, then PMREGMISC)
    mov dx, 0xCF8
    mov eax, 0x80000000 | 7 << 11 | 0x40
    out dx, eax
    mov dx, 0xCFC
    mov eax, 0x601
    out dx, eax
    mov dx, 0xCF8
    mov eax, 0x80000000 | 7 << 11 | 0x80
    out dx, eax
    mov dx, 0xCFC
    mov eax, 1
    out dx, eax
    ; the memory workload's buffer: dword k = k * 0x9E3779B1
    mov edi, BUFFER
    xor eax, eax
    mov ecx, 0x100000
.fill:
    mov [edi], eax
    add eax, 0x9E3779B1
    add edi, 4
    loop .fill
    mov esi, trampoline
    mov edi, 0x8000
    mov ecx, trampoline_end - trampoline
    rep movsb
    mov dword [LAPIC + 0xF0], 0x1FF
    mov ebx, 1
.next_ap:
    cmp ebx, [CORES]
    jae .started
    mov ecx, ebx
    shl ecx, 24
    mov [LAPIC + 0x310], ecx
    mov dword [LAPIC + 0x300], 0xC500 ; INIT level assert
    mov dword [LAPIC + 0x300], 0x8500 ; INIT level deassert
    mov dword [LAPIC + 0x300], 0x608  ; SIPI vector 8
    inc ebx
    jmp .next_ap
.started:
    xor ebx, ebx
    jmp all_cores

bits 16
trampoline:
    cli
    lgdt [cs:trampoline_gdtr - trampoline]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:ap_start
trampoline_gdtr:
    dw gdt_end - gdt - 1
    dd gdt
trampoline_end:
bits 32

ap_start:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov ebx, [LAPIC + 0x20]
    shr ebx, 24
    lea esp, [ebx + 1]
    shl esp, 16
    add esp, STACKS

; ebx = core id (= APIC ID); ebp = rounds done
all_cores:
    xor ebp, ebp
.round:
    call barrier
.wait_go:
    cmp [GO], ebp
    ja .go
    pause
    jmp .wait_go
.go:
    push 0                          ; this core's partial result
    cmp dword [CHUNK], 0
    je .static
.claim:
    mov esi, [CHUNK]
    lock xadd [NEXT], esi           ; esi = first item of the claim
    cmp esi, [TOTAL]
    jae .claimed_all
    mov edi, esi
    add edi, [CHUNK]
    cmp edi, [TOTAL]
    jbe .bounded
    mov edi, [TOTAL]
.bounded:
    call dispatch
    add [esp], eax
    jmp .claim
.static:
    ; this core's items [esi, edi)
    mov eax, [TOTAL]
    mul ebx
    div dword [CORES]
    mov esi, eax
    lea eax, [ebx + 1]
    mul dword [TOTAL]
    div dword [CORES]
    mov edi, eax
    call dispatch
    add [esp], eax
.claimed_all:
    pop eax
.finish:
    lock add [SUM], eax
    call barrier
    inc ebp
    test ebx, ebx
    jnz .round
    mov [DONE], ebp
    jmp .round

; items [esi, edi) of WORKLOAD: eax = their partial result
dispatch:
    mov eax, [WORKLOAD]
    cmp eax, 1
    je work_compute
    cmp eax, 2
    je work_lock
    cmp eax, 3
    je work_memory
    cmp eax, 4
    je work_io
    lock inc dword [ERRORS]
    xor eax, eax
    ret

; eax = f(esi) summed over [esi, edi)
work_compute:
    xor edx, edx
.item:
    cmp esi, edi
    jae .done
    mov eax, esi
    mov ecx, 64
.mix:
    imul eax, eax, 0x9E3779B1
    rol eax, 13
    xor eax, ecx
    dec ecx
    jnz .mix
    add edx, eax
    inc esi
    jmp .item
.done:
    mov eax, edx
    ret

; the counter under the lock; eax = the private work's sum
work_lock:
    push ebp
    xor ebp, ebp
.item:
    cmp esi, edi
    jae .done
.acquire:
    mov eax, 1
    xchg [SPIN], eax
    test eax, eax
    jz .locked
    pause
    jmp .acquire
.locked:
    mov eax, [COUNTER]
    inc eax
    mov [COUNTER], eax
    mov [SHARED_RECORD], esi
    mov [SHARED_RECORD + 4], ebx
    mov dword [SPIN], 0
    mov eax, esi
    mov ecx, 32
.mix:
    imul eax, eax, 0x9E3779B1
    rol eax, 13
    xor eax, ecx
    dec ecx
    jnz .mix
    add ebp, eax
    inc esi
    jmp .item
.done:
    mov eax, ebp
    pop ebp
    ret

; eax = sum of the dwords of block (item % 1024), copied to scratch
work_memory:
    push ebp
    xor ebp, ebp
    mov edx, esi
.item:
    cmp edx, edi
    jae .done
    push edi
    mov esi, edx
    and esi, 1023
    shl esi, 12
    add esi, BUFFER
    mov edi, ebx
    shl edi, 12
    add edi, SCRATCH
    mov ecx, 1024
    rep movsd
    sub edi, 4096
    xor eax, eax
    mov ecx, 1024
.sum:
    add eax, [edi]
    add edi, 4
    dec ecx
    jnz .sum
    add ebp, eax
    pop edi
    inc edx
    jmp .item
.done:
    mov eax, ebp
    pop ebp
    ret

; eax = number of PM timer reads that returned a 24-bit value
work_io:
    push ebp
    xor ebp, ebp
.item:
    cmp esi, edi
    jae .done
    mov dx, PM_TIMER
    in eax, dx
    test eax, 0xFF000000
    jnz .bad
    inc ebp
.bad:
    out 0x80, al
    inc esi
    jmp .item
.done:
    mov eax, ebp
    pop ebp
    ret

; sense-reversing barrier over all cores
barrier:
    push eax
    push ecx
    push edi
    mov edi, ebx
    shl edi, 6
    add edi, RECORDS
    mov ecx, [edi]
    xor ecx, 1
    mov [edi], ecx
    mov eax, 1
    lock xadd [BARRIER_COUNT], eax
    inc eax
    cmp eax, [CORES]
    jne .wait
    mov dword [BARRIER_COUNT], 0
    mov [BARRIER_SENSE], ecx
    jmp .done
.wait:
    pause
    cmp [BARRIER_SENSE], ecx
    jne .wait
.done:
    pop edi
    pop ecx
    pop eax
    ret

align 8
gdt:
    dq 0
    dq 0x00CF9A000000FFFF
    dq 0x00CF92000000FFFF
gdt_end:
gdtr:
    dw gdt_end - gdt - 1
    dd gdt
end:
                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/parallel/bench.mjs                                                                 0000644 0000000 0000000 00000015472 00000000000 014425  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Multicore throughput (docs/multicore.md): the same total
// guest work (tests/parallel/bench.asm) on 1/2/4/8 cores, cooperative and in
// vCPU workers. Every round's checksum is checked against a reference
// computed here, so a configuration cannot finish early by doing less work.
// Each machine runs a cold round (fresh compiler caches) and warm rounds.
//
// Modes: "cooperative" (release v86.wasm), "cooperative-pbuild" (cooperative
// cores on v86-parallel.wasm: the cost of its atomics alone) and "parallel".
//
// Items are claimed in chunks by whichever core is free (BENCH_SPLIT=static:
// equal shares instead, where the slowest host core sets the time).
//
// BENCH_WORKLOADS (compute,lock,memory,io), BENCH_CORES (1,2,4,8),
// BENCH_MODES (cooperative,cooperative-pbuild,parallel), BENCH_ROUNDS (warm rounds, 3),
// BENCH_SCALE (work multiplier, 1), DISABLE_JIT=1, BENCH_REPORT (JSON file).
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import { spawnSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { PARALLEL_WASM, ROOT } from "./guest.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const kernel = ROOT + "build/parallel-bench.bin";
const assembled = spawnSync("nasm", ["-f", "bin", "-o", kernel, ROOT + "tests/parallel/bench.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);

const CONTROL = 0x380000;
const JIT = !+process.env.DISABLE_JIT;
const SCALE = +process.env.BENCH_SCALE || 1;
const WARM_ROUNDS = +process.env.BENCH_ROUNDS || 3;
const WORKLOADS = {
    compute: { id: 1, total: 1600000, chunk: 1024 },
    lock: { id: 2, total: 1200000, chunk: 1024 },
    memory: { id: 3, total: 40000, chunk: 32 },
    io: { id: 4, total: 200000, chunk: 256 },
};
const STATIC_SPLIT = process.env.BENCH_SPLIT === "static";
const workloads = (process.env.BENCH_WORKLOADS || "compute,lock,memory,io").split(",");
const core_counts = (process.env.BENCH_CORES || "1,2,4,8").split(",").map(Number);
const modes = (process.env.BENCH_MODES || "cooperative,cooperative-pbuild,parallel").split(",");

const mix = (x, rounds) => {
    for(let c = rounds; c > 0; c--)
    {
        x = Math.imul(x, 0x9E3779B1);
        x = (x << 13 | x >>> 19) ^ c;
    }
    return x >>> 0;
};
const block_sums = Array.from({ length: 1024 }, (_, b) => {
    let sum = 0;
    for(let k = 0; k < 1024; k++) sum = sum + Math.imul(b * 1024 + k, 0x9E3779B1) >>> 0;
    return sum;
});
function expected(name, total)
{
    let sum = 0;
    if(name === "compute") for(let i = 0; i < total; i++) sum = sum + mix(i, 64) >>> 0;
    if(name === "lock") for(let i = 0; i < total; i++) sum = sum + mix(i, 32) >>> 0;
    if(name === "memory") for(let i = 0; i < total; i++) sum = sum + block_sums[i & 1023] >>> 0;
    if(name === "io") sum = total;
    return sum;
}

async function measure(name, cores, mode)
{
    const total = Math.round(WORKLOADS[name].total * SCALE);
    const parallel = mode === "parallel";
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: kernel }, memory_size: 64 << 20, acpi: true, cpu_cores: cores,
        disable_jit: !JIT, experimental_smp_jit: JIT && cores > 1,
        ...(parallel ? { parallel: true, wasm_path: PARALLEL_WASM } :
            mode === "cooperative-pbuild" ? { wasm_path: PARALLEL_WASM } : { wasm_path: ROOT + "build/v86.wasm" }),
        autostart: false, log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const cpu = emulator.v86.cpu;
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const u32 = offset => view().getUint32(CONTROL + offset, true);
    const set = (offset, value) => view().setUint32(CONTROL + offset, value, true);
    set(0, cores);
    set(4, WORKLOADS[name].id);
    set(8, total);
    set(32, STATIC_SPLIT ? 0 : WORKLOADS[name].chunk);
    const reference = expected(name, total);
    emulator.run();
    const rounds = [];
    for(let round = 1; round <= 1 + WARM_ROUNDS; round++)
    {
        set(20, 0);
        set(24, 0);
        set(36, 0);
        const cpu0 = process.cpuUsage();
        const t0 = performance.now();
        set(12, round);
        const deadline = t0 + 600000;
        while(u32(16) < round)
        {
            if(performance.now() > deadline) throw new Error(`${name} ${cores}c ${mode}: round ${round} timed out`);
            await delay(1);
        }
        const ms = performance.now() - t0;
        const used = process.cpuUsage(cpu0);
        assert.equal(u32(28), 0, "kernel errors");
        assert.equal(u32(20), reference, `${name} ${cores}c ${mode} round ${round}: checksum`);
        if(name === "lock") assert.equal(u32(24), total, `${name} ${cores}c ${mode}: lock counter`);
        rounds.push({ ms, cpu_ratio: (used.user + used.system) / 1000 / ms });
    }
    const diagnostics = cpu.get_diagnostics();
    const result = {
        workload: name, cores, mode, total,
        cold_ms: rounds[0].ms,
        warm_ms: Math.min(...rounds.slice(1).map(r => r.ms)),
        warm_cpu_ratio: rounds.slice(1).reduce((a, r) => a + r.cpu_ratio, 0) / WARM_ROUNDS,
        rss_mb: process.memoryUsage().rss / 2 ** 20,
        io_served: diagnostics.parallel?.served ?? null,
        worker_waits: diagnostics.parallel?.cores.map(c => c.waits) ?? null,
        worker_jit: diagnostics.parallel?.cores.map(c => c.jit) ?? null,
    };
    await emulator.destroy();
    return result;
}

const host = { cpu: os.cpus()[0]?.model, logical_cores: os.cpus().length, node: process.version, platform: process.platform,
    arch: process.arch, memory_gb: os.totalmem() / 2 ** 30, jit: JIT, scale: SCALE, warm_rounds: WARM_ROUNDS,
    split: STATIC_SPLIT ? "static" : "chunks" };
console.log(JSON.stringify(host));
const results = [];
for(const name of workloads)
{
    let base = null;
    for(const cores of core_counts)
    {
        for(const mode of modes)
        {
            if(mode === "parallel" && cores === 1) continue;
            const r = await measure(name, cores, mode);
            if(cores === 1 && mode === "cooperative") base = r.warm_ms;
            r.speedup = base ? base / r.warm_ms : null;
            results.push(r);
            console.log(`${name.padEnd(8)} ${String(cores).padStart(2)}c ${mode.padEnd(11)} cold ${(r.cold_ms / 1000).toFixed(2)}s` +
                ` warm ${(r.warm_ms / 1000).toFixed(2)}s` + (r.speedup ? ` speedup ${r.speedup.toFixed(2)}x` : "") +
                ` cpu/wall ${r.warm_cpu_ratio.toFixed(2)} rss ${r.rss_mb.toFixed(0)} MiB` +
                (r.io_served !== null ? ` io ${r.io_served}` : ""));
        }
    }
}
if(process.env.BENCH_REPORT) fs.writeFileSync(process.env.BENCH_REPORT, JSON.stringify({ host, results }, null, 2));
console.log("benchmark checksums passed");
                                                                                                                                                                                                      source/v64/tests/parallel/browser.mjs                                                               0000644 0000000 0000000 00000011035 00000000000 015020  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// vCPU workers in a browser (docs/multicore.md): headless
// Chrome loads tests/parallel/browser_test.html from a local server. With
// COOP/COEP headers the page is cross-origin isolated and the cores run in
// vCPU module workers (source tree and bundles); without them "auto" keeps
// the cores cooperative and says why. tests/parallel/browser_graphics.html
// then shows a graphical screen with cores in workers (the VGA pixel buffer is
// in shared memory, which ImageData refuses). BROWSER_CHROME selects the browser.
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const chrome = process.env.BROWSER_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
for(const name of ["litmus", "graphics"])
{
    const assembled = spawnSync("nasm", ["-f", "bin", "-o", root + `build/parallel-${name}.bin`, root + `tests/parallel/${name}.asm`], { encoding: "utf8" });
    if(assembled.status !== 0) throw new Error(assembled.stderr);
}

function run(query, isolated, page = "browser_test.html")
{
    return new Promise((resolve, reject) => {
        const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-parallel-"));
        let browser, timer;
        const server = http.createServer((req, res) => {
            if(req.method === "POST" && req.url === "/__result")
            {
                let body = "";
                req.on("data", data => { body += data; });
                req.on("end", () => { res.end("OK"); finish(body); });
                return;
            }
            const file = path.resolve(root, "." + new URL(req.url, "http://localhost").pathname);
            if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
            fs.readFile(file, (error, data) => {
                if(error) { res.writeHead(404).end(); return; }
                if(isolated)
                {
                    res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
                    res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
                }
                res.setHeader("Content-Type", file.endsWith(".wasm") ? "application/wasm" :
                    /\.(js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".html") ? "text/html" : "application/octet-stream");
                if(file.endsWith(".html")) data = Buffer.concat([data, Buffer.from(`<script>
                    new MutationObserver((_, observer) => {
                        const text = document.getElementById("result").textContent;
                        if(!/^(PASS|FAIL)/.test(text)) return;
                        observer.disconnect();
                        fetch("/__result", { method: "POST", body: text + "\\n" + document.getElementById("log").textContent });
                    }).observe(document.body, { subtree: true, childList: true, characterData: true });
                </script>`)]);
                res.end(data);
            });
        });
        const finish = text => {
            clearTimeout(timer);
            browser?.kill();
            server.close();
            // (Chrome may still be writing its profile)
            try { fs.rmSync(profile, { recursive: true, force: true, maxRetries: 5 }); } catch(e) { /* left in the temporary directory */ }
            (text.startsWith("PASS") ? resolve : reject)(text);
        };
        server.listen(0, "127.0.0.1", () => {
            const url = `http://127.0.0.1:${server.address().port}/tests/parallel/${page}?${query}`;
            browser = spawn(chrome, ["--headless=new", "--no-first-run", "--no-default-browser-check",
                "--disable-background-networking", `--user-data-dir=${profile}`, url], { stdio: "ignore" });
            browser.on("error", error => finish("FAIL " + error));
            timer = setTimeout(() => finish("FAIL timeout"), 240000);
        });
    });
}

for(const [query, isolated, page] of [["expect=parallel", true], ["expect=parallel&build=bundle", true],
    ["expect=cooperative&cores=2&rounds=1000", false],
    // a graphical screen: the VGA pixel buffer is in shared memory then
    ["", true, "browser_graphics.html"], ["build=bundle", true, "browser_graphics.html"]])
{
    const result = await run(query, isolated, page);
    console.log(`${page || "browser_test.html"}?${query}${isolated ? " (COOP/COEP)" : " (not isolated)"}: ${result.split("\n")[0]}`);
}
console.log("parallel browser tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/parallel/browser_graphics.html                                                     0000644 0000000 0000000 00000005540 00000000000 017057  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>v86 graphics with vCPU workers</title>
<!-- vCPU workers (docs/multicore.md): a graphical screen while
     the cores run in vCPU workers, whose wasm memory is shared memory, which
     ImageData refuses (src/vga.js keeps a copy then). tests/parallel/graphics.asm
     draws red above row 240 and green below; the canvas must show both.
     ?build=bundle loads build/libv86.mjs. -->
<pre id="log"></pre>
<div id="result"></div>
<div id="screen_container">
    <div style="white-space: pre; font: 14px monospace; line-height: 14px"></div>
    <canvas style="display: none"></canvas>
</div>
<script type="module">
const params = new URLSearchParams(location.search);
const log = text => { document.getElementById("log").textContent += text + "\n"; };
const done = text => { document.getElementById("result").textContent = text; };
try
{
    const bundle = params.get("build") === "bundle";
    const { V86 } = await import(bundle ? "../../build/libv86.mjs" : "../../src/main.js");
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: "../../build/parallel-graphics.bin" }, memory_size: 32 << 20, acpi: true, cpu_cores: 2,
        screen_container: document.getElementById("screen_container"), vram_size: 8 << 20,
        autostart: false, log_level: 0, parallel: "auto", wasm_path: "../../build/v86-parallel.wasm",
        ...(bundle ? { vcpu_worker_url: "../../build/vcpu-worker.js" } : {}),
    });
    const failed = new Promise((_, reject) => emulator.add_listener("emulator-error", reject));
    await Promise.race([new Promise(resolve => emulator.add_listener("emulator-loaded", resolve)), failed]);
    const execution = emulator.v86.cpu.get_diagnostics().execution;
    log("execution " + JSON.stringify(execution));
    if(execution.mode !== "parallel") throw new Error("expected parallel, got " + JSON.stringify(execution));
    emulator.run();
    const canvas = document.querySelector("#screen_container canvas");
    const pixel = (x, y) => Array.from(canvas.getContext("2d").getImageData(x, y, 1, 1).data.slice(0, 3));
    const deadline = performance.now() + 30000;
    let top, bottom;
    for(;;)
    {
        await Promise.race([new Promise(resolve => setTimeout(resolve, 200)), failed]);
        if(canvas.width === 640 && canvas.height === 480)
        {
            top = pixel(320, 100);
            bottom = pixel(320, 400);
            if(top.join() === "255,0,0" && bottom.join() === "0,255,0") break;
        }
        if(performance.now() > deadline)
        {
            throw new Error(`canvas ${canvas.width}x${canvas.height}, pixels ${JSON.stringify([top, bottom])}`);
        }
    }
    await emulator.destroy();
    done(`PASS graphics with cores in workers: canvas 640x480, red ${top}, green ${bottom}`);
}
catch(error)
{
    done("FAIL " + (error && error.stack || error));
}
</script>
                                                                                                                                                                source/v64/tests/parallel/browser_test.html                                                         0000644 0000000 0000000 00000006662 00000000000 016244  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html>
<meta charset="utf-8">
<title>v86 vCPU workers in a browser</title>
<!-- vCPU workers (docs/multicore.md): the litmus kernel on
     cores in vCPU module workers. ?expect=parallel (the server sends
     COOP/COEP) or ?expect=cooperative (it does not: "auto" falls back);
     ?build=bundle loads build/libv86.mjs, which starts build/vcpu-worker.js. -->
<pre id="log"></pre>
<div id="result"></div>
<script type="module">
const params = new URLSearchParams(location.search);
const expect = params.get("expect") || "parallel";
const cores = +(params.get("cores") || 4), rounds = +(params.get("rounds") || 5000);
const log = text => { document.getElementById("log").textContent += text + "\n"; };
const done = text => { document.getElementById("result").textContent = text; };
try
{
    const { V86 } = await import(params.get("build") === "bundle" ? "../../build/libv86.mjs" : "../../src/main.js");
    log(`crossOriginIsolated=${globalThis.crossOriginIsolated}, SharedArrayBuffer=${typeof SharedArrayBuffer}`);
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: "../../build/parallel-litmus.bin" }, memory_size: 32 << 20, acpi: true, cpu_cores: cores,
        experimental_smp_jit: true, ir_sync_publication: true, autostart: false, log_level: 0,
        parallel: "auto", wasm_path: "../../build/v86-parallel.wasm",
        // (the bundles' default is build/vcpu-worker.js relative to the page)
        ...(params.get("build") === "bundle" ? { vcpu_worker_url: "../../build/vcpu-worker.js" } : {}),
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    const cpu = emulator.v86.cpu;
    const execution = cpu.get_diagnostics().execution;
    log("execution " + JSON.stringify(execution));
    if(execution.mode !== expect) throw new Error(`expected ${expect}, got ${JSON.stringify(execution)}`);
    const CONTROL = 0x380000;
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    view().setUint32(CONTROL, cores, true);
    view().setUint32(CONTROL + 4, rounds, true);
    const t0 = performance.now();
    emulator.run();
    while(view().getUint32(CONTROL + 128, true) !== cores)
    {
        if(performance.now() - t0 > 120000) throw new Error("litmus not finished: " + JSON.stringify(cpu.get_diagnostics().parallel));
        await new Promise(resolve => setTimeout(resolve, 20));
    }
    const u32 = offset => view().getUint32(CONTROL + offset, true);
    const expected = cores * rounds;
    const counters = [16, 20, 24, 28, 32, 40].map(u32);
    if(counters.join() !== [expected, 2 * expected, expected, expected, expected, expected].join()) throw new Error("counters " + counters);
    for(let phase = 1; phase < 5; phase++) if(u32(64 + 4 * phase)) throw new Error("phase " + phase + " violations: " + u32(64 + 4 * phase));
    for(let core = 0; core < cores; core++) if(u32(0x180 + 4 * core) !== rounds) throw new Error("IPIs of core " + core);
    const workers = cpu.get_diagnostics().parallel?.cores.map(c => c.steps) || [];
    await emulator.destroy();
    done(`PASS ${expect} ${cores} cores, ${rounds} rounds in ${((performance.now() - t0) / 1000).toFixed(1)}s` +
        (workers.length ? `, worker steps ${workers.join("/")}` : `, fallback: ${execution.fallback}`));
}
catch(error)
{
    log(String(error && error.stack || error));
    done("FAIL " + error);
}
</script>
                                                                              source/v64/tests/parallel/graphics.asm                                                              0000644 0000000 0000000 00000002466 00000000000 015134  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; A graphical screen with cores in vCPU workers (tests/parallel/browser_graphics.html):
; the BSP switches to 640x480x32 through the Bochs VBE registers and fills
; the linear frame buffer, red above row 240 and green below. With cores in
; workers the wasm memory, and so the VGA's pixel buffer, is shared memory.
; The frame buffer is where the firmware put the VGA's BAR0, as for a driver.

bits 32
org 0x100000

MB_MAGIC equ 0x1BADB002
MB_FLAGS equ 0x10000
VGA_BAR0 equ 0x80000000 | 0x12 << 11 | 0x10  ; PCI 00:12.0, register 0x10

header:
    dd MB_MAGIC, MB_FLAGS, -(MB_MAGIC + MB_FLAGS)
    dd header, header, end, end, start

%macro vbe 2
    mov dx, 0x1CE
    mov ax, %1
    out dx, ax
    mov dx, 0x1CF
    mov ax, %2
    out dx, ax
%endmacro

start:
    cli
    cld
    vbe 4, 0                    ; disable
    vbe 1, 640                  ; x resolution
    vbe 2, 480                  ; y resolution
    vbe 3, 32                   ; bits per pixel
    vbe 4, 0x41                 ; enable, linear frame buffer
    mov dx, 0xCF8
    mov eax, VGA_BAR0
    out dx, eax
    mov dx, 0xCFC
    in eax, dx
    and eax, ~0xF
    mov edi, eax
    mov ecx, 640 * 240
    mov eax, 0x00FF0000         ; red
    rep stosd
    mov ecx, 640 * 240
    mov eax, 0x0000FF00         ; green
    rep stosd
.halt:
    hlt
    jmp .halt
end:
                                                                                                                                                                                                          source/v64/tests/parallel/guest.mjs                                                                 0000644 0000000 0000000 00000007043 00000000000 014470  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Helpers for the host-parallel tests: linux4 (Linux 4.16, 32-bit, the CD's
// own kernel booted directly) and a serial shell on it.
import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";

export const ROOT = url.fileURLToPath(new URL("../../", import.meta.url));
export const PARALLEL_WASM = process.env.V86_PARALLEL_WASM || ROOT + "build/v86-parallel.wasm";

/** A file of an ISO9660 image, by its path of directory names */
export function iso_file(path, names)
{
    const iso = fs.readFileSync(path);
    let extent = iso.readUInt32LE(16 * 2048 + 156 + 2);
    let size = iso.readUInt32LE(16 * 2048 + 156 + 10);
    for(const name of names)
    {
        let found = false;
        for(let at = extent * 2048; at < extent * 2048 + size;)
        {
            const length = iso[at];
            if(!length) { at = (Math.floor(at / 2048) + 1) * 2048; continue; }
            const id = iso.toString("latin1", at + 33, at + 33 + iso[at + 32]).replace(/;1$/, "").replace(/\.$/, "");
            if(id === name)
            {
                extent = iso.readUInt32LE(at + 2);
                size = iso.readUInt32LE(at + 10);
                found = true;
                break;
            }
            at += length;
        }
        assert.ok(found, name + " in " + path);
    }
    return iso.buffer.slice(iso.byteOffset + extent * 2048, iso.byteOffset + extent * 2048 + size);
}

export function linux4_options()
{
    const iso = ROOT + "images/linux4.iso";
    return {
        bios: { url: ROOT + "bios/seabios.bin" },
        vga_bios: { url: ROOT + "bios/vgabios.bin" },
        cdrom: { url: iso },
        bzimage: { buffer: iso_file(iso, ["BOOT", "BZIMAGE"]) },
        cmdline: "root=/dev/sr0 nokaslr",
        acpi: true,
        autostart: true,
        log_level: 0,
    };
}

const PROMPT = /~% $/;

/** A serial console shell on a V86 instance */
export class Shell
{
    constructor(emulator, name)
    {
        this.emulator = emulator;
        this.name = name;
        this.serial = "";
        this.waiter = null;
        emulator.add_listener("serial0-output-byte", byte => {
            this.serial += String.fromCharCode(byte);
            if(this.waiter && this.waiter.pattern.test(this.serial))
            {
                const { resolve } = this.waiter;
                this.waiter = null;
                resolve(this.serial);
            }
        });
    }
    wait(pattern, what, timeout_ms)
    {
        return new Promise((resolve, reject) => {
            const timer = setTimeout(() => reject(new Error(this.name + ": timed out waiting for " + what + "\n" + this.serial.slice(-2000))), timeout_ms);
            this.waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
            if(pattern.test(this.serial))
            {
                this.waiter = null;
                clearTimeout(timer);
                resolve(this.serial);
            }
        });
    }
    async boot(timeout_ms = 300000)
    {
        await this.wait(PROMPT, "the shell", timeout_ms);
    }
    /** Run a command; its output without the echoed command line */
    async run(command, timeout_ms = 120000)
    {
        this.serial = "";
        this.emulator.serial0_send(command + "\n");
        const output = await this.wait(PROMPT, JSON.stringify(command), timeout_ms);
        return output.slice(command.length);
    }
}

export function value_of(output, key)
{
    const match = output.match(new RegExp(key + "=(\\S+)"));
    assert.ok(match, "no " + key + "= in " + JSON.stringify(output));
    return match[1];
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/parallel/lifecycle.mjs                                                             0000644 0000000 0000000 00000017246 00000000000 015306  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Lifecycle of vCPU workers (docs/multicore.md):
// stop-the-world while every core runs the litmus kernel
// (tests/parallel/litmus.asm), snapshots taken mid-run and restored into
// another machine, destroy while running, a failing worker (an exception, a
// trap inside the machine's critical sections, a worker that exits) and the
// "auto" backend policy's fallback.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { PARALLEL_WASM, ROOT } from "./guest.mjs";
import { with_jit_switches } from "../lib/jit_switches.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const kernel = ROOT + "build/parallel-litmus.bin";
const assembled = spawnSync("nasm", ["-f", "bin", "-o", kernel, ROOT + "tests/parallel/litmus.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);

const CONTROL = 0x380000;
const CORES = +process.env.CPU_CORES || 4;
const JIT = !+process.env.DISABLE_JIT;

async function machine(rounds, options = {})
{
    const emulator = new V86(with_jit_switches({
        graphics_adapter: "bochs_vga",
        multiboot: { url: kernel }, memory_size: 32 << 20, acpi: true, cpu_cores: CORES,
        disable_jit: !JIT, experimental_smp_jit: JIT, ir_sync_publication: true,
        parallel: true, wasm_path: PARALLEL_WASM, autostart: false, log_level: 0, ...options,
    }));
    const errors = [];
    emulator.add_listener("emulator-error", error => errors.push(error));
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    const cpu = emulator.v86.cpu;
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    view().setUint32(CONTROL, CORES, true);
    view().setUint32(CONTROL + 4, rounds, true);
    return { emulator, cpu, view, errors, u32: offset => view().getUint32(CONTROL + offset, true) };
}

function check_results(m, rounds, label)
{
    const expected = CORES * rounds;
    assert.deepEqual([16, 20, 24, 28, 32, 40].map(m.u32), [expected, 2 * expected, expected, expected, expected, expected],
        label + ": atomic counters");
    for(let phase = 1; phase < 5; phase++) assert.equal(m.u32(64 + 4 * phase), 0, label + ": errors in phase " + phase);
    assert.deepEqual(Array.from({ length: CORES }, (_, core) => m.u32(0x180 + 4 * core)), Array(CORES).fill(rounds),
        label + ": IPIs per core");
}

async function until_finished(m, label, timeout = 300000)
{
    const deadline = performance.now() + timeout;
    while(m.u32(128) !== CORES)
    {
        if(performance.now() > deadline)
        {
            throw new Error(label + ": not finished: " + JSON.stringify(m.cpu.get_diagnostics().parallel));
        }
        await delay(10);
    }
}

// 1. stop-the-world under load: the cores stop mid-phase (in barriers, spin
//    locks, HLT waiting for an IPI) and go on; one stop also saves a snapshot
{
    const rounds = 20000;
    const m = await machine(rounds);
    m.emulator.run();
    let stops = 0, snapshot = null;
    while(m.u32(128) !== CORES && stops < 400)
    {
        await delay(1 + Math.random() * 8);
        await m.emulator.stop();
        const status = m.cpu.get_diagnostics().parallel;
        for(const core of status.cores)
        {
            // parked, or never started (finished cores halt with interrupts off, still parked)
            assert.ok(core.status === "parked", `stop ${stops}: vCPU ${core.core} is ${core.status}`);
        }
        if(stops === 20) snapshot = await m.emulator.save_state();
        stops++;
        m.emulator.run();
    }
    await until_finished(m, "stops");
    check_results(m, rounds, "stops");
    assert.ok(snapshot, "a snapshot was taken mid-run");
    await m.emulator.destroy();
    console.log(`stop-the-world: ${stops} stops while running, results exact`);

    // 2. the snapshot continues in another machine
    const restored = await machine(rounds);
    await restored.emulator.restore_state(snapshot);
    assert.notEqual(restored.u32(128), CORES, "the snapshot was taken before the end");
    restored.emulator.run();
    await until_finished(restored, "restored");
    check_results(restored, rounds, "restored");
    await restored.emulator.destroy();
    console.log("snapshot taken mid-run finishes exactly in another machine");
}

// 3. destroy while every core runs: no worker executes afterwards
{
    const m = await machine(1000000);
    m.emulator.run();
    await delay(200);
    const steps = () => m.cpu.parallel.status().cores.map(core => core.steps);
    assert.ok(steps().every(n => n > 0), "the vCPUs ran");
    await m.emulator.destroy();
    const after = steps();
    await delay(300);
    assert.deepEqual(steps(), after, "no vCPU runs after destroy");
    console.log("destroy stops every vCPU");
}

// 4. a failing vCPU stops the machine with "emulator-error"; the machine's
//    thread does not hang on a lock the failed core held
for(const kind of ["throw", "trap", "exit"])
{
    const m = await machine(1000000, { parallel_fault: { core: CORES - 1, after_slices: 20, kind } });
    m.emulator.run();
    const deadline = performance.now() + 20000;
    while(!m.errors.length)
    {
        assert.ok(performance.now() < deadline, kind + ": no emulator-error");
        await delay(10);
    }
    assert.match(String(m.errors[0].message || m.errors[0]), kind === "exit" ? /exited/ : /vCPU \d failed/);
    assert.equal(m.emulator.is_running(), false, kind + ": the machine stopped");
    // the IOAPIC's lock (held by the trapping core) is free: this takes it
    m.cpu.wm.exports["get_ioapic_addr"]();
    const status = m.cpu.get_diagnostics().parallel;
    assert.ok(status.failure, kind + ": diagnostics name the failure");
    assert.equal(status.cores[CORES - 2].status, "failed");
    m.emulator.run();
    await delay(50);
    assert.equal(m.emulator.is_running(), false, kind + ": a failed machine does not run again");
    await assert.rejects(m.emulator.save_state(), kind + ": no snapshot of a failed machine");
    await m.emulator.destroy();
    console.log(`failing vCPU (${kind}): machine stopped, error reported, locks released`);
}

// 5. "auto" keeps the requested cores cooperative where parallel execution
//    is unavailable (here: a CPU core that is not v86-parallel.wasm)
{
    const rounds = 500;
    const m = await machine(rounds, { parallel: "auto", wasm_path: ROOT + "build/v86.wasm" });
    const execution = m.cpu.get_diagnostics().execution;
    assert.deepEqual(execution, { mode: "cooperative", fallback: "v86-parallel.wasm unavailable" });
    m.emulator.run();
    await until_finished(m, "auto fallback");
    check_results(m, rounds, "auto fallback");
    await m.emulator.destroy();
    const forced = new V86({ graphics_adapter: "bochs_vga", multiboot: { url: kernel }, memory_size: 32 << 20, acpi: true, cpu_cores: CORES,
        parallel: true, wasm_path: ROOT + "build/v86.wasm", autostart: false, log_level: 0 });
    const error = await new Promise(resolve => {
        forced.add_listener("emulator-error", resolve);
        forced.add_listener("emulator-loaded", () => resolve(null));
    });
    assert.match(String(error?.message), /not v86-parallel\.wasm/, "forced parallel fails without the parallel build");
    await forced.destroy();
    const auto = await machine(rounds, { parallel: "auto" });
    assert.deepEqual(auto.cpu.get_diagnostics().execution, { mode: "parallel", fallback: null });
    await auto.emulator.destroy();
    console.log("auto policy: parallel where possible, cooperative fallback with a reason");
}

console.log("parallel lifecycle tests passed");
                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/parallel/linux_boot.mjs                                                            0000755 0000000 0000000 00000003542 00000000000 015526  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Linux on a machine whose application processors run in vCPU workers
// (src/parallel), interpreted. The kernel brings every core online and runs
// work on all of them; the diagnostics show that each worker executed
// instructions and served I/O through the machine thread.
import assert from "node:assert/strict";
import { PARALLEL_WASM, Shell, linux4_options, value_of } from "./guest.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const CORES = +process.env.CPU_CORES || 2;

const timeout = setTimeout(() => { console.log("timeout\n" + shell.serial.slice(-3000)); process.exit(1); }, +process.env.TIMEOUT || 900000);
const JIT = !process.env.DISABLE_JIT || !+process.env.DISABLE_JIT;
const emulator = new V86({ graphics_adapter: "bochs_vga", ...linux4_options(), wasm_path: PARALLEL_WASM, memory_size: 128 << 20,
    cpu_cores: CORES, parallel: true, experimental_smp_jit: JIT, disable_jit: !JIT });
const shell = new Shell(emulator, "parallel");
const t0 = Date.now();
await shell.boot(+process.env.BOOT_TIMEOUT || 600000);
console.log(`booted with ${CORES} cores in ${((Date.now() - t0) / 1000).toFixed(1)}s`);
const cpus = await shell.run("echo CPUS=$(grep -c ^processor /proc/cpuinfo) ONLINE=$(cat /sys/devices/system/cpu/online)");
assert.equal(+value_of(cpus, "CPUS"), CORES);
// one busy loop per core
const work = await shell.run(`for i in $(seq ${CORES}); do (i=0; while [ $i -lt 3000 ]; do i=$((i+1)); done; echo DONE) & done; wait; echo ALL=1`, 600000);
assert.equal(+value_of(work, "ALL"), 1);
const d = emulator.v86.cpu.get_diagnostics();
console.log(JSON.stringify(d.parallel));
for(const core of d.parallel.cores) assert.ok(core.steps > 0, `vCPU ${core.core} executed instructions`);
await emulator.destroy();
clearTimeout(timeout);
console.log("parallel Linux boot passed");
                                                                                                                                                              source/v64/tests/parallel/litmus.asm                                                                0000644 0000000 0000000 00000045541 00000000000 014652  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Memory-model and atomicity litmus tests for cores that really run at the
; same time (docs/multicore.md). The same kernel
; runs on cooperative cores as a reference. The BSP starts the APs with
; INIT/SIPI; then every core runs the phases below, separated by barriers:
;
; 1. counters: LOCK INC, LOCK XADD, LOCK CMPXCHG loops, CMPXCHG8B loops, and
;    plain increments inside XCHG and LOCK BTS/BTR spin locks: exact totals;
;    and mixed widths on the same bytes: a LOCK ADD of a dword that crosses
;    a dword boundary (not one aligned atomic access) and a LOCK ADD of the
;    aligned word inside it
; 2. message passing around a ring of cores: plain stores and loads, the
;    payload is always observed with (after) its flag (TSO order)
; 3. store buffering with MFENCE between each pair of cores: never both
;    loads old
; 4. cross-modifying code: core 0 rewrites a function core 1 then calls
;    after a serializing CPUID; core 1 always sees the new code
; 5. wake-ups: a fixed IPI travels around the ring of cores ROUNDS times;
;    each core waits for it in STI; HLT (a lost wake-up hangs the ring)
; 6. paging: all cores enable paging with shared page tables and touch
;    their own pages, whose entries share page-table cache lines: every
;    entry ends up with exactly the right accessed/dirty bits
; 7. long mode (when CONTROL + 0x340 is set): every core enters 64-bit mode
;    and increments a 16-byte counter with LOCK CMPXCHG16B (both halves)
;    and its low qword with LOCK ADD: low = 2 * total, high = total; then
;    in 32-bit compatibility mode (WOW64's) LOCK XADD, a LOCK CMPXCHG loop
;    and LOCK INC on dwords: total, 3 * total, total
; 8. interrupts into 64-bit code from compatibility mode (with phase 7): a
;    fixed IPI travels around the ring of cores ROUNDS times, as in phase 5,
;    but each core waits for it in compatibility-mode code with interrupts
;    enabled, and the 64-bit IDT's gates point above 4 GiB, at an alias of
;    the handlers whose low 32 bits are not mapped. Code that went on as
;    32-bit code after such an interrupt would fetch there (Windows 8.1
;    x64 in parallel mode, WOW64 processes): the fault counts as an error.
;
; Results (host reads them): CONTROL + 0 cores (input), +4 rounds (input),
; +16.. counters, +64.. errors per phase, +128 finished cores, +0x180..
; IPIs received per core, +0x1C0.. phase 8's.

bits 32
org 0x100000

MB_MAGIC equ 0x1BADB002
MB_FLAGS equ 0x10000
CONTROL equ 0x380000
CORES equ CONTROL + 0
ROUNDS equ CONTROL + 4
BARRIER_COUNT equ CONTROL + 8
BARRIER_SENSE equ CONTROL + 12
COUNTERS equ CONTROL + 16       ; 6 dwords + 64-bit at +24 (see below)
C_INC equ COUNTERS + 0
C_XADD equ COUNTERS + 4
C_CMPXCHG equ COUNTERS + 8
C_XCHG_LOCKED equ COUNTERS + 12
C_BTS_LOCKED equ COUNTERS + 16
C_CMPXCHG8B equ COUNTERS + 24   ; 64 bits, 8-aligned
ERRORS equ CONTROL + 64         ; per phase
FINISHED equ CONTROL + 128
SPIN_XCHG equ CONTROL + 0x200
SPIN_BTS equ CONTROL + 0x240
C_MIXED equ CONTROL + 0x302     ; dword at an offset of 2: its low word is also added to
C_WIDE equ CONTROL + 0x320      ; 16 bytes, 16-aligned
LONG_MODE equ CONTROL + 0x340   ; input: run phase 7
LONG_TABLES equ CONTROL + 0x344 ; core 0 built the 4-level tables
C_COMPAT equ CONTROL + 0x350    ; 3 dwords: compatibility mode's counters
LM_PML4 equ 0x3A8000            ; then PDPT, PD: 32 MiB identity mapped
LM_PDPT_HIGH equ LM_PML4 + 0x3000 ; phase 8: HIGH_ALIAS + p -> p (the same PD)
LM_PD_LAPIC equ LM_PML4 + 0x4000 ; phase 8: the local APIC's 2 MiB
HIGH_ALIAS equ 0xFFFF800080000000 ; PML4 entry 256, PDPT entry 2
IDT64 equ 0x3B8000              ; phase 8: 256 16-byte gates
RECORDS equ CONTROL + 0x400     ; 64 bytes per core: +0 barrier sense
MP_DATA equ CONTROL + 0x1000    ; per core: data, flag, ack on separate lines
SB_X equ CONTROL + 0x2000       ; per pair, separate lines
SB_Y equ CONTROL + 0x2040
SB_RESULTS equ CONTROL + 0x3000 ; per pair and round: two bytes
SMC_FLAG equ CONTROL + 0x100
SMC_ACK equ CONTROL + 0x140
SMC_CODE equ 0x3B0000
IPI_COUNT equ CONTROL + 0x180   ; per core
IPI_COUNT64 equ CONTROL + 0x1C0 ; per core, phase 8
IPI_VECTOR equ 0x40
IDT equ 0x390000
PAGE_DIRECTORY equ 0x3A0000
PAGE_TABLES equ 0x3A1000        ; 4 tables: 16 MiB identity mapped
TOUCHED equ 0xC00000            ; per core 16 pages written, 16 pages read
LAPIC equ 0xFEE00000
STACKS equ 0x300000

header:
    dd MB_MAGIC, MB_FLAGS, -(MB_MAGIC + MB_FLAGS)
    dd header, header, end, end, start

start:
    cli
    cld
    lgdt [gdtr]
    jmp 8:.protected
.protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, STACKS + 0x10000
    mov al, 0xFF
    out 0x21, al
    out 0xA1, al
    mov esi, trampoline
    mov edi, 0x8000
    mov ecx, trampoline_end - trampoline
    rep movsb
    mov dword [LAPIC + 0xF0], 0x1FF
    mov ebx, 1
.next_ap:
    cmp ebx, [CORES]
    jae .started
    mov ecx, ebx
    shl ecx, 24
    mov [LAPIC + 0x310], ecx
    mov dword [LAPIC + 0x300], 0xC500 ; INIT level assert
    mov dword [LAPIC + 0x300], 0x8500 ; INIT level deassert
    mov dword [LAPIC + 0x300], 0x608  ; SIPI vector 8
    inc ebx
    jmp .next_ap
.started:
    xor ebx, ebx
    jmp all_cores

; Position-independent 16-bit code at 0x8000
bits 16
trampoline:
    cli
    lgdt [cs:trampoline_gdtr - trampoline]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:ap_start
trampoline_gdtr:
    dw gdt_end - gdt - 1
    dd gdt
trampoline_end:
bits 32

ap_start:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov ebx, [LAPIC + 0x20]
    shr ebx, 24
    lea esp, [ebx + 1]
    shl esp, 16
    add esp, STACKS

; ebx = core id (= APIC ID) from here on
all_cores:
    call barrier
    call phase_counters
    call barrier
    call phase_message_passing
    call barrier
    call phase_store_buffering
    call barrier
    call phase_smc
    call barrier
    call phase_ipi
    call barrier
    call phase_paging
    call barrier
    cmp dword [LONG_MODE], 0
    jne phase_long_mode
    lock inc dword [FINISHED]
.halt:
    cli
    hlt
    jmp .halt

; sense-reversing barrier over all cores
barrier:
    push eax
    push ecx
    push edi
    mov edi, ebx
    shl edi, 6
    add edi, RECORDS
    mov ecx, [edi]
    xor ecx, 1
    mov [edi], ecx
    mov eax, 1
    lock xadd [BARRIER_COUNT], eax
    inc eax
    cmp eax, [CORES]
    jne .wait
    mov dword [BARRIER_COUNT], 0
    mov [BARRIER_SENSE], ecx
    jmp .done
.wait:
    pause
    cmp [BARRIER_SENSE], ecx
    jne .wait
.done:
    pop edi
    pop ecx
    pop eax
    ret

phase_counters:
    mov ecx, [ROUNDS]
.loop:
    lock inc dword [C_INC]
    mov eax, 2
    lock xadd [C_XADD], eax
    ; CMPXCHG increment
    mov eax, [C_CMPXCHG]
.retry32:
    lea edx, [eax + 1]
    lock cmpxchg [C_CMPXCHG], edx
    jnz .retry32
    ; XCHG spin lock around a plain increment
.acquire_xchg:
    mov eax, 1
    xchg [SPIN_XCHG], eax
    test eax, eax
    jz .locked_xchg
    pause
    jmp .acquire_xchg
.locked_xchg:
    mov eax, [C_XCHG_LOCKED]
    inc eax
    mov [C_XCHG_LOCKED], eax
    mov dword [SPIN_XCHG], 0
    ; LOCK BTS spin lock, released with LOCK BTR
.acquire_bts:
    lock bts dword [SPIN_BTS], 0
    jnc .locked_bts
    pause
    jmp .acquire_bts
.locked_bts:
    mov eax, [C_BTS_LOCKED]
    inc eax
    mov [C_BTS_LOCKED], eax
    lock btr dword [SPIN_BTS], 0
    ; CMPXCHG8B increment of a 64-bit counter
    push ebx
    push ecx
    mov eax, [C_CMPXCHG8B]
    mov edx, [C_CMPXCHG8B + 4]
.retry64:
    mov ebx, eax
    mov ecx, edx
    add ebx, 1
    adc ecx, 0
    lock cmpxchg8b [C_CMPXCHG8B]
    jnz .retry64
    pop ecx
    pop ebx
    ; mixed widths: both add to the low word, which wraps for large totals;
    ; only the dword add carries into the upper word (litmus.mjs bounds it)
    lock add dword [C_MIXED], 1
    lock add word [C_MIXED], 1
    dec ecx
    jnz .loop
    ret

; core k sends 1..ROUNDS to core (k + 1) % cores, which checks each payload
phase_message_passing:
    mov esi, ebx                    ; my producer slot
    shl esi, 8
    add esi, MP_DATA
    mov eax, ebx                    ; predecessor slot
    test eax, eax
    jnz .has_previous
    mov eax, [CORES]
.has_previous:
    dec eax
    mov edi, eax
    shl edi, 8
    add edi, MP_DATA
    mov ecx, 1
.round:
    ; produce: payload, then flag
    lea eax, [ecx * 3]
    mov [esi], eax
    mov [esi + 64], ecx
    ; consume the predecessor's round
.wait_flag:
    mov eax, [edi + 64]
    cmp eax, ecx
    jae .consume
    pause
    jmp .wait_flag
.consume:
    mov eax, [edi]
    lea edx, [ecx * 3]
    cmp eax, edx
    je .payload_ok
    lock inc dword [ERRORS + 4]
.payload_ok:
    mov [edi + 128], ecx            ; ack
    ; wait until my consumer took this round before overwriting the payload
.wait_ack:
    mov eax, [esi + 128]
    cmp eax, ecx
    jae .next
    pause
    jmp .wait_ack
.next:
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .round
    ret

; pairs (2p, 2p+1): x = r; MFENCE; read y — never both old in one round
phase_store_buffering:
    mov eax, [CORES]
    and eax, ~1
    cmp ebx, eax
    jae .spectator
    mov esi, ebx
    shr esi, 1
    shl esi, 7                      ; pair offset
    lea ebp, [esi + SB_X]
    lea edi, [esi + SB_Y]
    test ebx, 1
    jz .roles
    xchg ebp, edi
.roles:
    ; ebp: my variable, edi: the other one
    mov ecx, 1
.sb_round:
    call barrier
    mov [ebp], ecx
    mfence
    mov eax, [edi]
    cmp eax, ecx
    setb al                         ; the other store was still invisible
    ; byte SB_RESULTS + pair * 4096 + 2 * (round % 2048) + (id & 1)
    mov edx, ebx
    shr edx, 1
    shl edx, 12
    add edx, SB_RESULTS
    push ecx
    and ecx, 2047
    lea edx, [edx + ecx * 2]
    mov ecx, ebx
    and ecx, 1
    add edx, ecx
    pop ecx
    mov [edx], al
    call barrier
    ; the even core checks this round
    test ebx, 1
    jnz .checked
    mov edx, ebx
    shr edx, 1
    shl edx, 12
    add edx, SB_RESULTS
    push ecx
    and ecx, 2047
    lea edx, [edx + ecx * 2]
    pop ecx
    mov al, [edx]
    and al, [edx + 1]
    jz .checked
    lock inc dword [ERRORS + 8]
.checked:
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .sb_round
    ret
.spectator:
    mov ecx, 1
.spectate:
    call barrier
    call barrier
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .spectate
    ret

; core 0 writes "mov eax, 7 * i; ret" at SMC_CODE, core 1 calls it
phase_smc:
    cmp ebx, 1
    ja .done
    mov ecx, 1
.round:
    test ebx, ebx
    jnz .executor
    mov byte [SMC_CODE], 0xB8
    imul eax, ecx, 7
    mov [SMC_CODE + 1], eax
    mov byte [SMC_CODE + 5], 0xC3
    mov [SMC_FLAG], ecx
.wait_ack:
    cmp [SMC_ACK], ecx
    jae .next
    pause
    jmp .wait_ack
.executor:
    cmp [SMC_FLAG], ecx
    jae .execute
    pause
    jmp .executor
.execute:
    push ebx
    push ecx
    xor eax, eax
    cpuid                           ; serializing, as cross-modifying code requires
    mov eax, SMC_CODE
    call eax
    pop ecx
    pop ebx
    imul edx, ecx, 7
    cmp eax, edx
    je .fresh
    lock inc dword [ERRORS + 12]
.fresh:
    mov [SMC_ACK], ecx
.next:
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .round
.done:
    ret

; core k waits for its r-th IPI, then sends one to core (k + 1) % cores;
; core 0 starts each round
phase_ipi:
    test ebx, ebx
    jnz .idt_built
    ; every vector ignores, IPI_VECTOR counts
    mov edi, IDT
    xor ecx, ecx
.gate:
    mov eax, ignore_interrupt
    cmp ecx, IPI_VECTOR
    jne .write_gate
    mov eax, ipi_interrupt
.write_gate:
    mov edx, eax
    and eax, 0xFFFF
    or eax, 8 << 16
    and edx, 0xFFFF0000
    or edx, 0x8E00                  ; present 32-bit interrupt gate
    mov [edi + ecx * 8], eax
    mov [edi + ecx * 8 + 4], edx
    inc ecx
    cmp ecx, 256
    jb .gate
.idt_built:
    call barrier
    lidt [idtr]
    mov dword [LAPIC + 0xF0], 0x1FF ; software-enable this core's APIC
    mov dword [LAPIC + 0x80], 0     ; TPR
    call barrier
    mov ecx, 1
.round:
    test ebx, ebx
    jnz .wait
    call send_ipi
.wait:
    cli
    mov eax, [IPI_COUNT + ebx * 4]
    cmp eax, ecx
    jae .received
    sti
    hlt
    jmp .wait
.received:
    test ebx, ebx
    jz .next                        ; back at core 0: the round is complete
    call send_ipi
.next:
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .round
    ret

send_ipi:
    push eax
    lea eax, [ebx + 1]
    cmp eax, [CORES]
    jb .target
    xor eax, eax
.target:
    shl eax, 24
    mov [LAPIC + 0x310], eax
    mov dword [LAPIC + 0x300], 0x4000 | IPI_VECTOR ; fixed, physical, assert
    pop eax
    ret

ipi_interrupt:
    push eax
    mov eax, [LAPIC + 0x20]
    shr eax, 24
    lock inc dword [IPI_COUNT + eax * 4]
    mov dword [LAPIC + 0xB0], 0     ; EOI
    pop eax
    iretd

ignore_interrupt:
    iretd

; identity-map 16 MiB with 4 KiB pages (core 0 builds the tables)
phase_paging:
    test ebx, ebx
    jnz .wait_tables
    mov edi, PAGE_TABLES
    mov eax, 0x3                    ; present, writable
    mov ecx, 4096
.pte:
    mov [edi], eax
    add eax, 4096
    add edi, 4
    loop .pte
    mov edi, PAGE_DIRECTORY
    mov eax, PAGE_TABLES | 3
    mov ecx, 4
.pde:
    mov [edi], eax
    add eax, 4096
    add edi, 4
    loop .pde
.wait_tables:
    call barrier
    mov eax, PAGE_DIRECTORY
    mov cr3, eax
    mov eax, cr0
    or eax, 0x80000000
    mov cr0, eax
    jmp .paged
.paged:
    ; write 16 pages and read 16 pages of my own; entries of all cores
    ; interleave in the same page table (core c, page i -> TOUCHED + (i * 8 + c) * 4096)
    xor ecx, ecx
.touch:
    mov eax, ecx
    shl eax, 3
    add eax, ebx
    shl eax, 12
    add eax, TOUCHED
    mov dword [eax], 0x1234
    mov eax, ecx
    add eax, 16
    shl eax, 3
    add eax, ebx
    shl eax, 12
    add eax, TOUCHED
    mov edx, [eax]
    inc ecx
    cmp ecx, 16
    jb .touch
    call barrier
    test ebx, ebx
    jnz .paging_done
    ; core 0: check every touched entry of every core
    xor esi, esi                    ; core
.check_core:
    xor ecx, ecx
.check_page:
    mov eax, ecx
    shl eax, 3
    add eax, esi
    shl eax, 12
    add eax, TOUCHED
    mov edx, eax
    shr edx, 12
    mov edx, [PAGE_TABLES + edx * 4]
    xor edx, eax
    cmp edx, 0x63                   ; P, RW, A, D and the right frame
    je .written_ok
    lock inc dword [ERRORS + 16]
.written_ok:
    mov eax, ecx
    add eax, 16
    shl eax, 3
    add eax, esi
    shl eax, 12
    add eax, TOUCHED
    mov edx, eax
    shr edx, 12
    mov edx, [PAGE_TABLES + edx * 4]
    xor edx, eax
    cmp edx, 0x23                   ; accessed, not dirty
    je .read_ok
    lock inc dword [ERRORS + 16]
.read_ok:
    inc ecx
    cmp ecx, 16
    jb .check_page
    inc esi
    cmp esi, [CORES]
    jb .check_core
.paging_done:
    ret

; (does not return: the core finishes in 64-bit mode)
phase_long_mode:
    mov eax, cr0
    and eax, 0x7FFFFFFF             ; paging off to set EFER.LME
    mov cr0, eax
    test ebx, ebx
    jnz .wait_tables
    mov edi, LM_PML4
    xor eax, eax
    mov ecx, 5 * 1024
    rep stosd
    mov dword [LM_PML4], LM_PML4 + 0x1000 + 3
    mov dword [LM_PML4 + 0x1000], LM_PML4 + 0x2000 + 3
    mov edi, LM_PML4 + 0x2000
    mov eax, 0x83                   ; 2 MiB pages
    mov ecx, 16
.pde:
    mov [edi], eax
    add eax, 0x200000
    add edi, 8
    loop .pde
    ; phase 8: the high alias of the first 32 MiB, and the local APIC
    mov dword [LM_PML4 + 256 * 8], LM_PDPT_HIGH + 3
    mov dword [LM_PDPT_HIGH + 2 * 8], LM_PML4 + 0x2000 + 3
    mov dword [LM_PML4 + 0x1000 + 3 * 8], LM_PD_LAPIC + 3
    mov dword [LM_PD_LAPIC + (LAPIC >> 21 & 511) * 8], LAPIC | 0x93 ; (PCD)
    ; and the 64-bit IDT: the IPI at handler_ipi64, every other vector at
    ; handler_fault64, both through the high alias
    mov edi, IDT64
    xor ecx, ecx
.gate64:
    mov eax, handler_fault64 + (HIGH_ALIAS & 0xFFFFFFFF)
    cmp ecx, IPI_VECTOR
    jne .write_gate64
    mov eax, handler_ipi64 + (HIGH_ALIAS & 0xFFFFFFFF)
.write_gate64:
    mov edx, eax
    and eax, 0xFFFF
    or eax, 24 << 16                ; the 64-bit code segment
    and edx, 0xFFFF0000
    or edx, 0x8E00                  ; present 64-bit interrupt gate
    mov [edi], eax
    mov [edi + 4], edx
    mov dword [edi + 8], HIGH_ALIAS >> 32
    mov dword [edi + 12], 0
    add edi, 16
    inc ecx
    cmp ecx, 256
    jb .gate64
    mov dword [LONG_TABLES], 1
.wait_tables:
    pause
    cmp dword [LONG_TABLES], 1
    jne .wait_tables
    mov eax, cr4
    or eax, 0x20                    ; PAE
    mov cr4, eax
    mov eax, LM_PML4
    mov cr3, eax
    mov ecx, 0xC0000080
    rdmsr
    or eax, 0x100                   ; LME
    wrmsr
    mov eax, cr0
    or eax, 0x80000000
    mov cr0, eax
    jmp 24:long_mode_entry

bits 64
long_mode_entry:
    lidt [idtr64]
    mov r8d, [ROUNDS]
.loop:
    mov rax, [C_WIDE]
    mov rdx, [C_WIDE + 8]
.retry:
    lea rbx, [rax + 1]
    lea rcx, [rdx + 1]
    lock cmpxchg16b [C_WIDE]
    jnz .retry                      ; (RDX:RAX now holds the current value)
    lock add qword [C_WIDE], 1
    dec r8d
    jnz .loop
    ; (to compatibility mode: the 32-bit code segment, LMA set)
    push 8
    mov eax, compat_entry
    push rax
    o64 retf
bits 32
compat_entry:
    mov ecx, [ROUNDS]
.round:
    mov eax, 1
    lock xadd [C_COMPAT], eax
    mov eax, [C_COMPAT + 4]
.cas:
    lea edx, [eax + 3]
    lock cmpxchg [C_COMPAT + 4], edx
    jnz .cas                        ; (EAX now holds the current value)
    lock inc dword [C_COMPAT + 8]
    dec ecx
    jnz .round
    ; phase 8: core k waits in this mode, with interrupts enabled, for its
    ; r-th IPI, then sends one to core (k + 1) % cores (send_ipi); core 0
    ; starts each round
    mov ebx, [LAPIC + 0x20]
    shr ebx, 24
    call barrier                    ; (every core's IDTR holds IDT64)
    sti
    mov ecx, 1
.ipi_round:
    test ebx, ebx
    jnz .ipi_wait
    call send_ipi
.ipi_wait:
    ; (a read across a page boundary: the page tier's parallel build
    ; leaves its function for the interpreter at each one, so that IPIs
    ; also arrive between two of its activations)
    mov eax, [CONTROL + 0xFFE]
    mov eax, [IPI_COUNT64 + ebx * 4]
    cmp eax, ecx
    jae .ipi_received
    pause                           ; (cores taking turns: the next one)
    jmp .ipi_wait
.ipi_received:
    test ebx, ebx
    jz .ipi_next                    ; back at core 0: the round is complete
    call send_ipi
.ipi_next:
    inc ecx
    cmp ecx, [ROUNDS]
    jbe .ipi_round
    cli
    lock inc dword [FINISHED]
.halt:
    cli
    hlt
    jmp .halt

; Phase 8's handlers, entered through HIGH_ALIAS (64-bit code: CONTROL and
; its counters are below 2 GiB, the local APIC is not)
bits 64
handler_ipi64:
    push rax
    push rdx
    mov edx, LAPIC
    mov eax, [rdx + 0x20]
    shr eax, 24
    lock inc dword [IPI_COUNT64 + rax * 4]
    mov dword [rdx + 0xB0], 0       ; EOI
    pop rdx
    pop rax
    iretq
handler_fault64:
    lock inc dword [ERRORS + 20]
    lock inc dword [FINISHED]
.halt:
    cli
    hlt
    jmp .halt
bits 32

align 8
gdt:
    dq 0
    dq 0x00CF9A000000FFFF
    dq 0x00CF92000000FFFF
    dq 0x00AF9A000000FFFF           ; 64-bit code
gdt_end:
gdtr:
    dw gdt_end - gdt - 1
    dd gdt
idtr:
    dw 256 * 8 - 1
    dd IDT
idtr64:
    dw 256 * 16 - 1
    dq IDT64
end:
                                                                                                                                                               source/v64/tests/parallel/litmus.mjs                                                                0000644 0000000 0000000 00000016235 00000000000 014661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Litmus tests (tests/parallel/litmus.asm) on cooperative cores (the
// reference) and on cores in vCPU workers that run at the same time:
// atomic counters and spin locks (also locked operations of different widths
// on the same bytes), message passing, store buffering with
// MFENCE, cross-modifying code, IPI wake-ups of halted cores and concurrent
// accessed/dirty updates; then (LITMUS_LONG_MODE, default 1) every core
// enters 64-bit mode for LOCK CMPXCHG16B against LOCK ADD on the same qword,
// and 32-bit compatibility mode (WOW64's) for locked dword counters, which
// the JIT modes compile in the page tier (x64_page_compat32, P7.2), and
// there waits for IPIs with interrupts enabled, which its 64-bit IDT sends
// to handlers above 4 GiB (no 32-bit code may run on at their RIP).
//
// LITMUS_MODES: comma-separated from cooperative, cooperative-jit, parallel,
// parallel-jit (default: all but parallel-jit), and a64-cooperative (the
// A64 litmus tests on the ARM core's cooperative cores, tests/a64/litmus.mjs);
// LITMUS_CORES (default 2,4); LITMUS_ROUNDS (default 2000).
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { PARALLEL_WASM, ROOT } from "./guest.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const kernel = ROOT + "build/parallel-litmus.bin";
const assembled = spawnSync("nasm", ["-f", "bin", "-o", kernel, ROOT + "tests/parallel/litmus.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);

const CONTROL = 0x380000;
const modes = (process.env.LITMUS_MODES || "cooperative,cooperative-jit,parallel").split(",");
const core_counts = (process.env.LITMUS_CORES || "2,4").split(",").map(Number);
const rounds = +process.env.LITMUS_ROUNDS || 2000;
const long_mode = process.env.LITMUS_LONG_MODE !== "0";
const PHASES = ["", "message passing", "store buffering", "cross-modifying code", "accessed/dirty bits",
    "interrupts from compatibility mode"];
const IPI_COUNT = 0x180, IPI_COUNT64 = 0x1C0;

async function run(mode, cores)
{
    const parallel = mode.startsWith("parallel");
    const jit = mode.endsWith("-jit");
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: kernel }, memory_size: 32 << 20, acpi: true, cpu_cores: cores,
        disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: true, cpu_type: long_mode ? "x86_64" : "x86",
        ...(jit ? { jit_switches: { x64_page_compat32: 1 } } : {}),
        ...(parallel ? { parallel: true, wasm_path: PARALLEL_WASM } : {}),
        autostart: false, log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const cpu = emulator.v86.cpu;
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    view().setUint32(CONTROL, cores, true);
    view().setUint32(CONTROL + 4, rounds, true);
    view().setUint32(CONTROL + 0x340, long_mode ? 1 : 0, true);
    const t0 = performance.now();
    emulator.run();
    const deadline = t0 + 300000;
    // (a fault in phase 8 stops its core, and so the ring of IPIs)
    while(view().getUint32(CONTROL + 128, true) !== cores && !view().getUint32(CONTROL + 64 + 20, true))
    {
        if(performance.now() > deadline)
        {
            const d = cpu.get_diagnostics();
            throw new Error(`${mode} ${cores} cores: not finished, ${view().getUint32(CONTROL + 128, true)} done: ` +
                JSON.stringify({ cores: d.cores.map(c => [c.state, c.linear_ip]), parallel: d.parallel }));
        }
        await delay(20);
    }
    const ms = performance.now() - t0;
    const u32 = offset => view().getUint32(CONTROL + offset, true);
    const u16 = offset => view().getUint16(CONTROL + offset, true);
    const expected = cores * rounds;
    // mixed widths: every dword and word add increments the low word, which
    // wraps once 2 * expected reaches 2^16; the upper word only takes the
    // carries of the wraps a dword add made (a word add drops its carry), so
    // it is at most the number of wraps
    const mixed_carries = u16(0x304);
    const mixed_wraps = Math.floor(2 * expected / 0x10000);
    const counters = { inc: u32(16), xadd: u32(20), cmpxchg: u32(24), xchg_lock: u32(28), bts_lock: u32(32),
        cmpxchg8b: u32(40) + u32(44) * 2 ** 32, mixed_widths: u16(0x302),
        ...(long_mode ? { cmpxchg16b_low: u32(0x320) + u32(0x324) * 2 ** 32, cmpxchg16b_high: u32(0x328) + u32(0x32C) * 2 ** 32,
            compat_xadd: u32(0x350), compat_cmpxchg: u32(0x354), compat_inc: u32(0x358) } : {}) };
    const errors = PHASES.map((_, i) => u32(64 + 4 * i));
    const ipis = Array.from({ length: cores }, (_, core) => u32(IPI_COUNT + 4 * core));
    const ipis64 = Array.from({ length: cores }, (_, core) => u32(IPI_COUNT64 + 4 * core));
    const steps = cpu.get_diagnostics().parallel?.cores.map(c => c.steps + (jit ? " (" + c.jit + " compiled entries)" : ""));
    // (cores on this thread: their compatibility-mode functions)
    const compat_compiles = jit && !parallel ? cpu.wm.exports.x64_page_stat(36) : null;
    await emulator.destroy();
    if(long_mode && compat_compiles !== null) assert.ok(compat_compiles > 0, `${mode} ${cores} cores: the page tier compiled the compatibility-mode loop`);
    assert.deepEqual(counters, { inc: expected, xadd: 2 * expected, cmpxchg: expected, xchg_lock: expected,
        bts_lock: expected, cmpxchg8b: expected, mixed_widths: 2 * expected % 0x10000,
        ...(long_mode ? { cmpxchg16b_low: 2 * expected, cmpxchg16b_high: expected,
            compat_xadd: expected, compat_cmpxchg: 3 * expected, compat_inc: expected } : {}) }, `${mode} ${cores} cores: atomic counters`);
    assert.ok(mixed_carries <= mixed_wraps,
        `${mode} ${cores} cores: mixed widths: ${mixed_carries} carries into the upper word, but the low word wrapped ${mixed_wraps} times`);
    errors.forEach((count, i) => i && assert.equal(count, 0, `${mode} ${cores} cores: ${PHASES[i]}: ${count} violations`));
    assert.deepEqual(ipis, Array(cores).fill(rounds), `${mode} ${cores} cores: IPIs received per core`);
    if(long_mode) assert.deepEqual(ipis64, Array(cores).fill(rounds), `${mode} ${cores} cores: IPIs received per core in compatibility mode`);
    console.log(`${mode} ${cores} cores: ${rounds} rounds passed in ${(ms / 1000).toFixed(1)}s` +
        (steps ? `, worker steps ${steps.join("/")}` : "") + (compat_compiles ? `, ${compat_compiles} compatibility-mode compiles` : ""));
}

for(const cores of core_counts)
{
    for(const mode of modes)
    {
        if(mode === "a64-cooperative")
        {
            // (the ARM core's own litmus guest and checks, tests/a64/litmus.mjs)
            const a64 = spawnSync("node", [ROOT + "tests/a64/litmus.mjs", "--cores", String(cores), "--rounds", String(rounds)],
                { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
            assert.equal(a64.status, 0, `a64-cooperative ${cores} cores:\n${a64.stdout}`);
            console.log(a64.stdout.trim());
            continue;
        }
        await run(mode, cores);
    }
}
console.log("litmus tests passed");
                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/parallel/relocation.mjs                                                            0000644 0000000 0000000 00000011572 00000000000 015502  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Relocated instances (docs/multicore.md): the same Wasm module runs on
// two independent state bases without crosstalk. Two machines share one
// memory: A is v86-parallel.wasm at base 0, B a relocated instance of it
// (src/parallel/relocate.js) with its own statics, stack, CPU state block,
// JIT and heap. Both boot Linux and run in one thread, interleaved by the
// event loop, with compiled code; A with two cooperative cores. Their results
// must match the reference values, and a snapshot of B must restore into B.
import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import { PARALLEL_WASM, Shell, linux4_options, value_of } from "./guest.mjs";
import { instantiate_relocated, memory_import, relocations, STATE_SLOT_SIZE } from "../../src/parallel/relocate.js";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const bytes = new Uint8Array(fs.readFileSync(PARALLEL_WASM));
assert.ok(memory_import(bytes)?.shared, "the parallel build imports a shared memory");
const table = relocations(bytes);
console.log(`relocation table: ${table.uleb5.length} offsets, ${table.sleb5.length} constants, ${table.u32.length} data pointers; ` +
    `of the state block ${table.uleb5_state.length}, ${table.sleb5_state.length}, ${table.u32_state.length}`);

const timeout = setTimeout(() => { console.log("timeout"); process.exit(1); }, 900000);

const a = new V86({ graphics_adapter: "bochs_vga", ...linux4_options(), wasm_path: PARALLEL_WASM, memory_size: 128 << 20, cpu_cores: 2, experimental_smp_jit: true });
await new Promise(resolve => a.add_listener("emulator-loaded", resolve));
const memory = a.v86.cpu.wasm_memory;
assert.ok(memory.buffer instanceof SharedArrayBuffer);

let base_b = 0;
const b = new V86({
    graphics_adapter: "bochs_vga",
    ...linux4_options(), memory_size: 96 << 20,
    wasm_fn: async env => {
        const { instance, base } = await instantiate_relocated(bytes, env, memory, 1);
        base_b = base;
        return instance.exports;
    },
});
await new Promise(resolve => b.add_listener("emulator-loaded", resolve));
const cpu_a = a.v86.cpu, cpu_b = b.v86.cpu;
assert.equal(cpu_b.wasm_memory, memory, "one memory");
assert.ok(base_b > 0 && cpu_a.state_base === 0 && cpu_b.state_base === STATE_SLOT_SIZE,
    "the state blocks are in slots 0 (A, where v86.wasm has it) and 1 (B)");
assert.notEqual(cpu_a.mem8.byteOffset, cpu_b.mem8.byteOffset);
assert.ok(cpu_b.mem8.byteOffset + cpu_b.mem8.length <= cpu_a.mem8.byteOffset ||
    cpu_a.mem8.byteOffset + cpu_a.mem8.length <= cpu_b.mem8.byteOffset, "guest RAM of A and B does not overlap");
console.log(`A: state ${cpu_a.state_base}, RAM ${cpu_a.mem8.byteOffset >>> 20} MiB; B: base ${base_b >>> 20} MiB, state ${cpu_b.state_base}, RAM ${cpu_b.mem8.byteOffset >>> 20} MiB`);

const shell_a = new Shell(a, "A"), shell_b = new Shell(b, "B");
const t0 = Date.now();
await Promise.all([shell_a.boot(), shell_b.boot()]);
console.log(`both booted in ${((Date.now() - t0) / 1000).toFixed(1)}s`);

// work with a known result, in both machines at once
let expected_sum = 0;
for(let i = 0; i < 20000; i++) expected_sum = (expected_sum * 31 + i) % 1000003;
const expected_md5 = crypto.createHash("md5").update(Buffer.alloc(2 << 20, "x")).digest("hex");
const WORK = "i=0; s=0; while [ $i -lt 20000 ]; do s=$(((s * 31 + i) % 1000003)); i=$((i+1)); done; echo SUM=$s; " +
    "echo MD5=$(dd if=/dev/zero bs=64k count=32 2>/dev/null | tr '\\0' 'x' | md5sum | cut -d' ' -f1); echo CPUS=$(grep -c ^processor /proc/cpuinfo)";
for(let round = 1; round <= 3; round++)
{
    const [out_a, out_b] = await Promise.all([shell_a.run(WORK), shell_b.run(WORK)]);
    for(const [name, out, cpus] of [["A", out_a, 2], ["B", out_b, 1]])
    {
        assert.equal(+value_of(out, "SUM"), expected_sum, name + ": shell arithmetic");
        assert.equal(value_of(out, "MD5"), expected_md5, name + ": md5sum");
        assert.equal(+value_of(out, "CPUS"), cpus, name + ": cores");
    }
    console.log(`round ${round}: A and B computed the reference results`);
}

// a snapshot of the relocated instance restores into it while A keeps running
const busy_a = shell_a.run(WORK);
await b.stop();
const state = await b.save_state();
await b.run();
await shell_b.run("echo 12345 > /tmp/marker; echo WROTE=1");
await b.stop();
await b.restore_state(state);
await b.run();
const after = await shell_b.run("echo MARKER=$(cat /tmp/marker 2>/dev/null || echo none); " + WORK);
assert.equal(value_of(after, "MARKER"), "none", "B restored its snapshot, from before the marker");
assert.equal(+value_of(after, "SUM"), expected_sum);
assert.equal(+value_of(await busy_a, "SUM"), expected_sum, "A was unaffected");
console.log(`snapshot of B (${(state.byteLength / 2 ** 20).toFixed(1)} MiB) restored while A ran`);

await a.destroy();
await b.destroy();
clearTimeout(timeout);
console.log("relocation test passed");
                                                                                                                                      source/v64/tests/parallel/soak.mjs                                                                  0000644 0000000 0000000 00000017037 00000000000 014302  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Parallel soak test (docs/multicore.md): linux4 on cores in
// vCPU workers for SOAK_MINUTES. Each iteration starts a workload on every
// core (arithmetic whose results are checked, a pipe and a tmpfs file with
// checksums), and while it runs pauses and resumes the machine and takes and
// restores a snapshot; every SOAK_SLEEP_EVERY iterations the guest suspends
// to RAM and an RTC alarm wakes it (a suspend the kernel aborts because the
// alarm came first is counted, not failed: the host was too slow for the
// alarm's lead). The kernel log must stay free of oopses,
// soft lockups, RCU stalls and hung tasks, every CPU keeps taking local timer
// interrupts, and the time keeps moving forward.
//
// SOAK_MINUTES (60), CPU_CORES (4), DISABLE_JIT=1, SOAK_SLEEP_EVERY (5),
// SOAK_ALARM_SECONDS (5).
import assert from "node:assert/strict";
import { setTimeout as delay } from "node:timers/promises";
import { PARALLEL_WASM, Shell, linux4_options, value_of } from "./guest.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const minutes = +(process.env.SOAK_MINUTES || 60), cores = +(process.env.CPU_CORES || 4);
const jit = !+process.env.DISABLE_JIT, sleep_every = +(process.env.SOAK_SLEEP_EVERY || 5);
const alarm_seconds = +(process.env.SOAK_ALARM_SECONDS || 5);
const emulator = new V86({ graphics_adapter: "bochs_vga", ...linux4_options(), wasm_path: PARALLEL_WASM, memory_size: 128 << 20,
    cpu_cores: cores, parallel: true, experimental_smp_jit: jit, disable_jit: !jit });
const errors = [];
emulator.add_listener("emulator-error", error => errors.push(error));
const shell = new Shell(emulator, "soak");
const started = Date.now();
await shell.boot(600000);
console.log(`booted with ${cores} cores in ${((Date.now() - started) / 1000).toFixed(0)} s`);

const loc = async () => {
    const text = await shell.run("grep LOC /proc/interrupts");
    return text.match(/LOC:((?:\s+\d+)+)/)[1].trim().split(/\s+/).map(Number);
};
const workload = `rm -f /tmp/soak.out; for i in $(seq ${cores}); do (s=0; j=0; while [ $j -lt 3000 ]; do j=$((j+1)); s=$((s+j*i)); done; echo R$i=$s >> /tmp/soak.out) & done; ` +
    `seq 1 5000 | md5sum > /tmp/soak.md5; dd if=/dev/urandom of=/tmp/soak.bin bs=1k count=256 2>/dev/null; md5sum /tmp/soak.bin > /tmp/soak.bin.md5; wait; ` +
    "echo WORK_DONE=1";
const PIPE_MD5 = (await shell.run("seq 1 5000 | md5sum")).match(/[0-9a-f]{32}/)[0];
const stats = { iterations: 0, stops: 0, snapshots: 0, sleeps: 0, aborted_suspends: 0 };
let suspends = 0;
emulator.add_listener("acpi-sleep", () => suspends++);
let last_loc = await loc(), last_uptime = 0;
// on a failure: every core, the workers and the serial console's interrupt
process.on("uncaughtException", error => {
    try
    {
        const cpu = emulator.v86.cpu, uart = cpu.devices.uart0;
        const ioapic = new Uint32Array(cpu.wasm_memory.buffer, cpu.get_ioapic_addr(), 52);
        const d = cpu.get_diagnostics();
        console.error("SOAK_FAILURE_STATE " + JSON.stringify({ stats, cores: d.cores.map(c => ({ state: c.state, ip: c.linear_ip,
            halted: c.halted, if: c.interrupts_enabled, irr: c.apic_irr, isr: c.apic_isr, retired: c.retired_instructions })),
            parallel: d.parallel, uart: { ier: uart.ier, iir: uart.iir, ints: uart.ints, lsr: uart.lsr, input: uart.input.length },
            ioapic4: { config: ioapic[4] >>> 0, destination: ioapic[28] >>> 0, irr: ioapic[50] & 16, line: ioapic[51] & 16 },
            code: { refused: cpu.wm.exports.parallel_code_stat(0), published: cpu.wm.exports.parallel_code_stat(1) } }));
    }
    catch(e) { console.error("(no failure state: " + e + ")"); }
    console.error(error);
    process.exit(1);
});
while(Date.now() - started < minutes * 60000)
{
    stats.iterations++;
    shell.serial = "";
    emulator.serial0_send(workload + "\n");
    // while the workload runs on every core: pauses, and a snapshot restored in place
    for(let i = 0; i < 3; i++)
    {
        await delay(200 + Math.random() * 800);
        await emulator.stop();
        stats.stops++;
        emulator.run();
    }
    await delay(300);
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    stats.snapshots++;
    emulator.run();
    await shell.wait(/WORK_DONE=1[\s\S]*~% $/, "the workload", 600000);
    const results = await shell.run("cat /tmp/soak.out; cat /tmp/soak.md5; md5sum -c /tmp/soak.bin.md5 && echo FILE_OK=1");
    for(let i = 1; i <= cores; i++) assert.equal(+value_of(results, "R" + i), i * 3000 * 3001 / 2, `core workload ${i}`);
    assert.ok(results.includes(PIPE_MD5), "pipe checksum");
    assert.equal(value_of(results, "FILE_OK"), "1", "tmpfs file checksum");
    if(stats.iterations % sleep_every === 0)
    {
        const suspends_before = suspends;
        const woke = new Promise(resolve => emulator.add_listener("acpi-wake", resolve));
        shell.serial = "";
        const returned = shell.wait(/SLEPT=\d+[\s\S]*~% $/, "echo mem", 300000);
        const slept = () => (shell.serial.match(/SLEPT=(\d+)/) || [])[1];
        emulator.serial0_send(`echo 0 > /sys/class/rtc/rtc0/wakealarm; echo +${alarm_seconds} > /sys/class/rtc/rtc0/wakealarm; ` +
            "echo mem > /sys/power/state; echo SLEPT=$?\n");
        const first = await Promise.race([woke, returned.then(() => "returned"), delay(120000).then(() => "timeout")]);
        if(first === "returned" && suspends === suspends_before && slept() !== "0")
        {
            // the kernel gave up before S3 (e.g. the alarm fired while suspending)
            stats.aborted_suspends++;
            console.log("suspend aborted by the guest:", (await shell.run("dmesg | grep -i -E 'abort|wakeup|PM:' | tail -5")).trim().split("\n").slice(-5).join(" | "));
            assert.ok(stats.aborted_suspends <= Math.max(2, stats.sleeps / 4), "too many aborted suspends");
        }
        else
        {
            const cpu = emulator.v86.cpu;
            assert.equal(first === "returned" ? await Promise.race([woke, delay(1000).then(() => "none")]) : first, "rtc",
                `RTC wake from S3 (suspends ${suspends - suspends_before}); acpi ${JSON.stringify(cpu.get_diagnostics().acpi)}; serial ${JSON.stringify(shell.serial.slice(-2000))}`);
            await returned;
            assert.equal(slept(), "0", "echo mem succeeded");
            stats.sleeps++;
        }
    }
    const health = await shell.run("echo PROBLEMS=$(dmesg | grep -c -i -E 'BUG:|Oops|soft lockup|rcu_sched self-detected|rcu.*stall|hung_task|blocked for more than') " +
        "UP=$(cut -d. -f1 /proc/uptime) ONLINE=$(cat /sys/devices/system/cpu/online)");
    assert.equal(+value_of(health, "PROBLEMS"), 0, "kernel log problems:\n" + await shell.run("dmesg | tail -40"));
    assert.equal(value_of(health, "ONLINE"), `0-${cores - 1}`, "every CPU online");
    const uptime = +value_of(health, "UP");
    assert.ok(uptime >= last_uptime, "uptime moves forward");
    last_uptime = uptime;
    const now_loc = await loc();
    now_loc.forEach((count, cpu) => assert.ok(count > last_loc[cpu], `CPU ${cpu} takes timer interrupts`));
    last_loc = now_loc;
    assert.equal(errors.length, 0, "emulator errors: " + errors);
    if(stats.iterations % 5 === 0 || Date.now() - started >= minutes * 60000)
    {
        const steps = emulator.v86.cpu.get_diagnostics().parallel.cores.map(c => c.steps);
        console.log(`${((Date.now() - started) / 60000).toFixed(1)} min: ${JSON.stringify(stats)} uptime ${uptime}s worker steps ${steps.join("/")}`);
    }
}
await emulator.destroy();
console.log(`SOAK_PASS ${minutes} min ${JSON.stringify(stats)}`);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/persistence/browser_runner.mjs                                                     0000755 0000000 0000000 00000026441 00000000000 017153  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The disk persistence plan in headless Chrome (docs/disk-persistence-plan.md):
// tests/persistence/browser_test.html, on the page and in the CPU Worker,
// with MS-DOS 6.22 (images/msdos622.img) read over HTTP Range requests from
// this server, which answers as a static server does (206, Content-Range, a
// strong ETag). D0 ("一致读取"): the server records every request's headers
// for the images (a read_only disk sends what it sent before), and changes
// an image's ETag on request (/__bump?name=...): the page checks that the
// disk read fails rather than mixing versions. A second server on another
// origin answers with CORS headers but does not expose the ETag: a
// cross-origin read_only disk works as before, unchecked.
// D2: a disk service (tools/disk-service.mjs, in this process, on another
// port, accepting this page's origin) serves service/*.img: the page writes
// back to it (part=d2), and the runner checks the service's files
// (/__service_file); part=close: the page writes, the runner kills the
// browser (SIGKILL) and finds the write in the service's file; part=pagehide:
// the page writes and navigates away, the runner checks that the session
// was closed (or, when the browser did not send it, that the lease ends);
// part=page: debug.html in a frame, MS-DOS on a disk written back to the
// service (the page's query arguments hda.url, hda.disk_option): the "Save
// and power off" button, the disk error prompt and its Retry
// (/__service_down, /__service_up), the session closed after powering off.
// Needs build/libv86.mjs, build/cpu-worker.js, build/v86.wasm and Chrome (CHROME).
//   node tests/persistence/browser_runner.mjs [worker=0|1] [part=d0|d2|close|pagehide|page]

import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import { create_disk_service } from "../../tools/disk-service.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const out = path.join(root, "build/persistence-browser");
fs.mkdirSync(out, { recursive: true });
// (one copy per machine of the test: each its own ETag)
for(const name of ["stop.img", "report.img", "cross.img"])
{
    fs.copyFileSync(path.join(root, "images/msdos622.img"), path.join(out, name));
}
const service_dir = path.join(out, "service");
fs.rmSync(service_dir, { recursive: true, force: true });
fs.mkdirSync(service_dir);
for(const name of ["dos.img", "shared.img", "close.img", "pagehide.img"])
{
    fs.copyFileSync(path.join(root, "images/msdos622.img"), path.join(service_dir, name));
}
const part = (process.argv.find(a => a.startsWith("part=")) || "part=d0").slice(5);
let service, service_listeners = null;
fs.copyFileSync(path.join(root, "images/msdos622.img"), path.join(service_dir, "page.img"));
fs.copyFileSync(path.join(root, "images/msdos622.img"), path.join(service_dir, "site.img"));

const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-persistence-browser-"));
let browser, timeout;
/** @type {!Map<string, number>} the version of each image's ETag */
const versions = new Map();
/** the headers of the image requests (the request lines' header names) */
const image_requests = [];

function serve(req, res, cross_origin)
{
    const address = new URL(req.url, "http://localhost");
    if(cross_origin)
    {
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Headers", "Range, X-Accept-Encoding");
        res.setHeader("Access-Control-Expose-Headers", "Content-Range");
        if(req.method === "OPTIONS") { res.writeHead(204).end(); return; }
    }
    else if(req.method === "POST" && address.pathname === "/__bump")
    {
        const name = address.searchParams.get("name");
        versions.set(name, (versions.get(name) || 0) + 1);
        res.end("OK");
        return;
    }
    else if(req.method === "GET" && address.pathname === "/__service_file")
    {
        // (the service's image: has it the text, has it a writer)
        const name = path.basename(address.searchParams.get("name"));
        const text = address.searchParams.get("contains") || "";
        const image = service.images.get(name);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ contains: !!text && fs.readFileSync(path.join(service_dir, name)).includes(text),
            writer: !!(image && image.writer && image.writer.expires > Date.now()), session_open: !!(image && image.writer) }));
        return;
    }
    else if(req.method === "POST" && (address.pathname === "/__service_down" || address.pathname === "/__service_up"))
    {
        // (part=page: the disk service unreachable, and back)
        if(address.pathname === "/__service_down")
        {
            service_listeners = service.server.listeners("request");
            service.server.removeAllListeners("request");
            service.server.on("request", request => request.socket.destroy());
        }
        else if(service_listeners)
        {
            service.server.removeAllListeners("request");
            for(const listener of service_listeners) service.server.on("request", listener);
            service_listeners = null;
        }
        res.end("OK");
        return;
    }
    else if(req.method === "POST" && address.pathname === "/__kill")
    {
        // part=close: the browser is killed, then the service's file is checked
        const name = path.basename(address.searchParams.get("name"));
        const text = address.searchParams.get("contains");
        res.end("OK");
        setTimeout(() =>
        {
            browser.kill("SIGKILL");
            browser.on("exit", () =>
            {
                const found = fs.readFileSync(path.join(service_dir, name)).includes(text);
                console.log((found ? "PASS" : "FAIL") + "\nthe browser killed (SIGKILL) after the guest wrote: the service's " + name +
                    (found ? " has" : " lacks") + " \"" + text + "\"");
                finish(found ? 0 : 1);
            });
        }, 100);
        return;
    }
    else if(req.method === "GET" && address.pathname === "/__requests")
    {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify(image_requests));
        return;
    }
    else if(req.method === "POST" && address.pathname === "/__test_result")
    {
        let body = "";
        req.on("data", d => { body += d; });
        req.on("end", () =>
        {
            res.end("OK");
            const result = JSON.parse(body);
            console.log(result.details);
            finish(result.status === "PASS" ? 0 : 1);
        });
        return;
    }
    const pathname = decodeURIComponent(address.pathname);
    const file = path.resolve(root, "." + pathname);
    if(!file.startsWith(root)) { res.writeHead(403).end(); return; }
    let stat;
    try { stat = fs.statSync(file); }
    catch(e) { res.writeHead(404).end(); return; }
    const type = file.endsWith(".wasm") ? "application/wasm" : /\.(js|mjs)$/.test(file) ? "text/javascript" :
        file.endsWith(".html") ? "text/html" : "application/octet-stream";
    const name = path.basename(file);
    const etag = "\"" + stat.size + "-" + Math.floor(stat.mtimeMs) + "-" + (versions.get(name) || 0) + "\"";
    const range = /^bytes=(\d+)-(\d+)$/.exec(req.headers["range"] || "");
    if(file.startsWith(out))
    {
        // (the headers v86 chose: not those every request of the browser
        // has, nor the browser's HTTP cache's revalidation: If-None-Match, If-Range)
        image_requests.push({ name, cross_origin, method: req.method,
            headers: Object.keys(req.headers).filter(h => !["host", "connection", "user-agent", "accept", "accept-language",
                "accept-encoding", "referer", "origin", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest",
                "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "if-none-match", "if-modified-since", "if-range", "cache-control",
                "pragma"].includes(h)).sort() });
    }
    if(range && file.startsWith(out))
    {
        const start = +range[1], end = Math.min(+range[2], stat.size - 1);
        const fd = fs.openSync(file, "r");
        const buffer = Buffer.alloc(end - start + 1);
        fs.readSync(fd, buffer, 0, buffer.length, start);
        fs.closeSync(fd);
        res.writeHead(206, { "Content-Type": type, "Content-Range": "bytes " + start + "-" + end + "/" + stat.size,
            "Content-Length": buffer.length, "ETag": etag, "Accept-Ranges": "bytes" });
        res.end(buffer);
        return;
    }
    let body = fs.readFileSync(file);
    if(file.endsWith(".html"))
    {
        body = Buffer.concat([body, Buffer.from(`<script>
            const reporter = new MutationObserver(() => {
                const text = document.getElementById("result")?.textContent || "";
                if(!/^(PASS|FAIL)\\b/.test(text)) return;
                reporter.disconnect();
                fetch("/__test_result", { method: "POST", body: JSON.stringify({ status: text.startsWith("PASS") ? "PASS" : "FAIL", details: text }) });
            });
            reporter.observe(document.documentElement, { subtree: true, childList: true, characterData: true });
        </script>`)]);
    }
    res.writeHead(200, { "Content-Type": type, "ETag": etag, "Accept-Ranges": "bytes" });
    res.end(body);
}

const server = http.createServer((req, res) => serve(req, res, false));
const cross = http.createServer((req, res) => serve(req, res, true));

function finish(code)
{
    clearTimeout(timeout);
    server.close();
    cross.close();
    process.exitCode = code;
    const remove = () => { try { fs.rmSync(profile, { recursive: true, force: true }); } catch(e) {} };
    if(service) service.close();
    if(browser && browser.exitCode === null && browser.signalCode === null)
    {
        browser.on("exit", remove);
        browser.kill();
    }
    else remove();
}

await new Promise(resolve => cross.listen(0, "127.0.0.1", resolve));
server.listen(0, "127.0.0.1", async () =>
{
    const page_origin = "http://127.0.0.1:" + server.address().port;
    service = create_disk_service({ dir: service_dir, origins: [page_origin], lease_ms: 3000 });
    await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
    // (the other origin: another port)
    const query = process.argv.slice(2).filter(a => !a.startsWith("part=")).concat(["cross=" + encodeURIComponent("http://127.0.0.1:" + cross.address().port),
        "service=" + encodeURIComponent("http://127.0.0.1:" + service.server.address().port), "part=" + part]).join("&");
    const url = "http://127.0.0.1:" + server.address().port + "/tests/persistence/browser_test.html?" + query;
    console.log(url);
    browser = spawn(process.env.CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
        "--user-data-dir=" + profile, url,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    let stderr = "";
    browser.stderr.on("data", d => { stderr = (stderr + d).slice(-4000); });
    browser.on("error", error => { console.error(error); finish(1); });
    timeout = setTimeout(() =>
    {
        console.error("FAIL: timed out\n" + stderr);
        finish(1);
    }, +process.env.TIMEOUT_MS || 300000);
});
                                                                                                                                                                                                                               source/v64/tests/persistence/browser_test.html                                                      0000644 0000000 0000000 00000046523 00000000000 016774  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>Disk persistence in the browser</title>
<div id="screen"><div style="white-space: pre; font: 14px monospace; line-height: 14px"></div><canvas style="display: none"></canvas></div>
<div id="screen2"><div style="white-space: pre; font: 14px monospace; line-height: 14px"></div><canvas style="display: none"></canvas></div>
<pre id="result">RUNNING</pre>
<script type="module">
// docs/disk-persistence-plan.md, on the page (worker=0) or in the CPU Worker
// (worker=1); run by tests/persistence/browser_runner.mjs.
// D0: MS-DOS from a RAW disk read with HTTP Range requests (read_only, as
// before): its requests have the headers they had (Range, X-Accept-Encoding);
// the image's ETag changes while it is read: with disk_error "stop" the read
// fails, "disk-error" says so and the machine stops, run() reports it to the
// guest (it cannot be retried); with "report" the guest sees the error at
// once; from another origin (the ETag not exposed) the disk works unchecked.
// D2 (part=d2): a static URL with disk_option "read_write" fails the start
// saying why; MS-DOS on a disk written back to the disk service: a file
// written is in the service's image when the command completes; a
// snapshot, destroy() closes the session; another machine reading the same
// image read_only while the first writes it gets "changed", not mixed
// sectors. part=close: the guest writes, the runner kills the browser;
// part=pagehide: the guest writes, the page goes away.
import { V86 } from "../../build/libv86.mjs";
const params = new URLSearchParams(location.search);
const worker = params.get("worker") === "1";
const part = params.get("part") || "d0";
const service = params.get("service");
const log = [];
const result = document.getElementById("result");
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const config = (hda, container = "screen") => ({
    wasm_path: "../../build/v86.wasm", cpu_worker: worker, cpu_worker_url: "../../build/cpu-worker.js",
    bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
    graphics_adapter: "bochs_vga", graphics_adapter_path: "../../build/v86-bochs-vga.js",
    hda, memory_size: 32 << 20, autostart: true, disable_speaker: true,
    screen: { container: document.getElementById(container) },
});
const screen = vm => (vm.screen_adapter ? vm.screen_adapter.get_text_screen() : []).map(l => l.replace(/\x00/g, " "));
let vm_current;
async function until(condition, what, timeout = 120000)
{
    const end = performance.now() + timeout;
    while(!condition())
    {
        if(performance.now() > end) throw new Error("timeout: " + what + "\n" + screen(vm_current).join("\n"));
        await sleep(100);
    }
}
async function boot(hda, container)
{
    const vm = vm_current = new V86(config(hda, container));
    const events = [];
    vm.add_listener("disk-error", event => events.push(event));
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    // (the prompt alone on its line for a second: AUTOEXEC.BAT is done)
    let stable = 0;
    await until(() => { const l = screen(vm).filter(x => x.trim()); stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0; return stable >= 10; }, "C:\\>");
    return { vm, events };
}
const bump = name => fetch("/__bump?name=" + name, { method: "POST" });
const images = "../../build/persistence-browser/";
const service_file = async (name, contains) => (await fetch("/__service_file?name=" + name + "&contains=" + encodeURIComponent(contains || ""))).json();
async function dos(vm, command)
{
    await vm.keyboard_send_text("cls\n", 20);
    await until(() => { const l = screen(vm).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await vm.keyboard_send_text(command + "\n", 20);
    await until(() => screen(vm).filter(x => x.startsWith("C:\\>")).length >= 2, command);
    return screen(vm).join("\n");
}
async function d2()
{
    // a static URL: the start fails, saying why
    {
        const vm = vm_current = new V86(config({ url: images + "stop.img", disk_option: "read_write" }));
        const error = await Promise.race([new Promise(resolve => vm.add_listener("emulator-error", resolve)),
            new Promise(resolve => vm.add_listener("emulator-loaded", () => resolve(null))), sleep(30000).then(() => "timeout")]);
        if(!error || error === "timeout" || !/can only be read, not written back .*disk service that supports writing/.test(error.message))
        {
            throw new Error("a static URL with read_write: " + (error && error.message || error));
        }
        log.push("a static URL with read_write: emulator-error \"" + error.message.slice(0, 100) + "...\"");
        try { await vm.destroy(); } catch(e) {}
    }
    // another origin whose CORS does not allow the protocol's requests
    {
        const vm = vm_current = new V86(config({ url: params.get("cross") + "/build/persistence-browser/cross.img", disk_option: "read_write" }));
        const error = await Promise.race([new Promise(resolve => vm.add_listener("emulator-error", resolve)),
            new Promise(resolve => vm.add_listener("emulator-loaded", () => resolve(null))), sleep(30000).then(() => "timeout")]);
        if(!error || error === "timeout" || !/cannot be reached, or does not let this page use it \(CORS/.test(error.message))
        {
            throw new Error("a cross-origin URL without CORS for the protocol: " + (error && error.message || error));
        }
        log.push("another origin, its CORS without the protocol's headers: emulator-error \"" + error.message.slice(0, 120) + "...\"");
        try { await vm.destroy(); } catch(e) {}
    }
    // written back to the disk service
    {
        const text = "WRITTEN IN THE BROWSER " + (worker ? "WORKER" : "PAGE");
        const { vm, events } = await boot({ url: service + "/dos.img", disk_option: "read_write" });
        log.push("C:\\> from the disk service, read_write (" + (worker ? "CPU Worker" : "page") + ")");
        if(!(await service_file("dos.img")).writer) throw new Error("no write session");
        await dos(vm, "echo " + text + " > C:\\BROWSER.TXT");
        if(!(await service_file("dos.img", text)).contains) throw new Error("the write is not in the service's image");
        log.push("the guest wrote a file: it is in the service's image when the command completes");
        const state = await vm.save_state();
        await vm.destroy();
        if((await service_file("dos.img")).session_open) throw new Error("destroy() did not close the session");
        log.push("save_state (" + state.byteLength + " bytes), destroy(): the session closed");
        if(events.length) throw new Error("disk-error: " + JSON.stringify(events));
        // the snapshot onto a read_only disk of the same image, read in ranges
        // (the service's ETag tells its identity and generation)
        const reader = await boot({ url: service + "/dos.img", async: true });
        await reader.vm.restore_state(state);
        if(!/WRITTEN IN THE BROWSER/.test(await dos(reader.vm, "type C:\\BROWSER.TXT"))) throw new Error("the restored read_only machine");
        log.push("the snapshot restored onto a read_only disk of the same image (the service's ETag): the file is there");
        await reader.vm.destroy();
    }
    // a read_only machine of the image another one writes: "changed"
    {
        const writer = await boot({ url: service + "/shared.img", disk_option: "read_write" }, "screen");
        const reader = await boot({ url: service + "/shared.img", async: true }, "screen2");
        await dos(writer.vm, "echo CHANGED > C:\\CHANGED.TXT");
        const stopped = new Promise(resolve => reader.vm.add_listener("emulator-stopped", resolve));
        await reader.vm.keyboard_send_text("copy C:\\DOS\\*.* NUL\n", 20);
        await Promise.race([stopped, sleep(30000).then(() => { throw new Error("the reader did not stop: " + JSON.stringify(reader.events)); })]);
        if(!reader.events.length || !/changed while it was read/.test(reader.events[0].reason)) throw new Error("reader: " + JSON.stringify(reader.events));
        log.push("a read_only machine of the image the other writes: \"" + reader.events[0].reason.slice(0, 90) + "...\"");
        await reader.vm.destroy();
        await writer.vm.destroy();
    }
}
async function write_and(what)
{
    const name = what + ".img";
    const text = "BEFORE THE " + what.toUpperCase() + " " + (worker ? "WORKER" : "PAGE");
    const { vm } = await boot({ url: service + "/" + name, disk_option: "read_write" });
    await dos(vm, "echo " + text + " > C:\\" + what.toUpperCase() + ".TXT");
    return { vm, name, text };
}
async function page_flow()
{
    // debug.html with a disk written back to the service
    const frame = document.createElement("iframe");
    frame.style.width = "1024px";
    frame.style.height = "768px";
    frame.src = "/debug.html?profile=custom&m=32&cpu_worker=" + (worker ? 1 : 0) + "&hda.url=" + encodeURIComponent(service + "/page.img") +
        "&hda.disk_option=read_write";
    document.body.appendChild(frame);
    await until(() => frame.contentWindow && frame.contentWindow.emulator, "the page's emulator");
    const vm = vm_current = frame.contentWindow.emulator;
    const $ = id => frame.contentDocument.getElementById(id);
    let stable = 0;
    await until(() => { const l = screen(vm).filter(x => x.trim()); stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0; return stable >= 10; }, "C:\\>");
    if($("save_and_power_off").style.display === "none") throw new Error("no Save and power off button");
    await dos(vm, "echo PAGE FLOW > C:\\PAGE.TXT");
    if(!(await service_file("page.img", "PAGE FLOW")).contains) throw new Error("the write is not in the service's image");
    log.push("debug.html, hda.url=<the service>, hda.disk_option=read_write (" + (worker ? "CPU Worker" : "page") + "): \"Save and power off\" shown, a write in the image");
    // the service unreachable: the prompt, Retry
    await fetch("/__service_down", { method: "POST" });
    await vm.keyboard_send_text("echo WHILE DOWN > C:\\DOWN.TXT\n", 20);
    await until(() => $("disk_error_box").style.display !== "none", "the disk error prompt", 60000);
    const prompt = $("disk_error_text").textContent;
    if(!/^Disk hda: the write of \d+ bytes at \d+ failed: .* retry once the disk can be reached again, or power off\.$/.test(prompt) ||
        $("disk_error_retry").textContent !== "Retry" || $("disk_error_retry").style.display === "none") throw new Error("the prompt: " + prompt);
    await fetch("/__service_up", { method: "POST" });
    $("disk_error_retry").click();
    if($("disk_error_box").style.display !== "none") throw new Error("the prompt stays");
    let landed = false;
    for(let i = 0; i < 300 && !landed; i++) { landed = (await service_file("page.img", "WHILE DOWN")).contains; if(!landed) await sleep(100); }
    if(!landed) throw new Error("the retried write is not in the image");
    let stable_again = 0;
    await until(() => { const l = screen(vm).filter(x => x.trim()); stable_again = l.length && l[l.length - 1].trim() === "C:\\>" ? stable_again + 1 : 0; return stable_again >= 10; }, "the prompt after Retry");
    log.push("the service unreachable: the prompt \"" + prompt.slice(0, 80) + "...\"; Retry: the write landed");
    // save and power off
    $("save_and_power_off").click();
    await until(() => $("disk_status").style.display !== "none", "the status after saving", 60000);
    if(!/^Saved the state \(v86state\.bin, \d+ bytes\) and powered off/.test($("disk_status").textContent)) throw new Error("status: " + $("disk_status").textContent);
    await sleep(200);
    if((await service_file("page.img")).session_open) throw new Error("the session is still open");
    log.push("Save and power off: \"" + $("disk_status").textContent.slice(0, 70) + "...\", the session closed");
    frame.remove();
    // index.html (the VM manager, docs/vm-manager-plan.md): the same address, its Power menu's "Save and power off"
    const site = document.createElement("iframe");
    site.style.width = "1024px";
    site.style.height = "768px";
    site.src = "/index.html?profile=custom&m=32&cpu_worker=" + (worker ? 1 : 0) + "&hda.url=" + encodeURIComponent(service + "/site.img") +
        "&hda.disk_option=read_write";
    document.body.appendChild(site);
    const $$ = selector => site.contentDocument && site.contentDocument.querySelector(selector);
    await until(() => $$("#menu_power") && site.contentWindow.v86_console, "index.html's machine");
    let open = false;
    for(let i = 0; i < 300 && !open; i++) { open = (await service_file("site.img")).session_open; if(!open) await sleep(100); }
    if(!open) throw new Error("index.html: no session");
    await sleep(3000);
    // (its download: kept from Chrome's download flow)
    site.contentWindow.HTMLAnchorElement.prototype.click = function() {};
    $$("#menu_power").click();
    await until(() => $$("#menu_save_and_power_off"), "index.html's Save and power off");
    $$("#menu_save_and_power_off").click();
    await until(() => /Powered off/.test($$(".console-status").textContent), "index.html powered off", 60000);
    if(!/^Saved the state/.test($$(".console-notice").textContent)) throw new Error("index.html notice: " + $$(".console-notice").textContent);
    await sleep(200);
    if((await service_file("site.img")).session_open) throw new Error("index.html: the session is still open");
    log.push("index.html (the VM manager): the same disk options, its Save and power off, the session closed");
}
try
{
    if(part === "page")
    {
        await page_flow();
        result.textContent = "PASS\n" + log.join("\n");
    }
    else if(part === "d2")
    {
        await d2();
        result.textContent = "PASS\n" + log.join("\n");
    }
    else if(part === "close")
    {
        // (the runner kills the browser and reads the service's image)
        const { name, text } = await write_and("close");
        await fetch("/__kill?name=" + name + "&contains=" + encodeURIComponent(text), { method: "POST" });
    }
    else if(part === "pagehide")
    {
        const { name, text } = await write_and("pagehide");
        sessionStorage.setItem("pagehide", JSON.stringify({ name, text, at: Date.now() }));
        location.href = location.pathname + "?part=after-pagehide&service=" + encodeURIComponent(service) + "&worker=" + (worker ? 1 : 0);
    }
    else if(part === "after-pagehide")
    {
        const { name, text, at } = JSON.parse(sessionStorage.getItem("pagehide"));
        await sleep(300);
        const file = await service_file(name, text);
        if(!file.contains) throw new Error("the write is not in the service's image");
        if(file.session_open)
        {
            // (the browser did not send the close: the lease ends)
            await until(() => Date.now() - at > 3500, "the lease", 10000);
            const later = await service_file(name);
            if(later.writer) throw new Error("the lease did not end");
            result.textContent = "PASS\nthe page went away: the write is in the service's image; the session was not closed by the page (" +
                (worker ? "CPU Worker" : "page") + "), its lease ended";
        }
        else
        {
            result.textContent = "PASS\nthe page went away: the write is in the service's image; pagehide closed the session (" +
                (worker ? "CPU Worker" : "page") + ")";
        }
    }
    else
    {
        await d0();
        result.textContent = "PASS\n" + log.join("\n");
    }
}
catch(error)
{
    result.textContent = "FAIL " + (error && error.stack || error) + "\n" + log.join("\n");
}
async function d0()
{
    // read_only from this origin, disk_error "stop" (the default)
    {
        const { vm, events } = await boot({ url: images + "stop.img", async: true });
        log.push("C:\\> from a RAW disk over HTTP Range (" + (worker ? "CPU Worker" : "page") + ")");
        await bump("stop.img");
        const stopped = new Promise(resolve => vm.add_listener("emulator-stopped", resolve));
        await vm.keyboard_send_text("copy C:\\DOS\\*.* NUL\n", 20);
        const before = (await (await fetch("/__requests")).json()).length;
        await Promise.race([stopped, sleep(30000).then(async () => { throw new Error("the machine did not stop: " + JSON.stringify(events) +
            " requests " + before + " -> " + (await (await fetch("/__requests")).json()).length + "\n" + screen(vm).join("\n")); })]);
        const event = events[0];
        if(!event || event.disk !== "hda" || event.operation !== "read" || event.retryable !== false || event.policy !== "stop" ||
            !/changed while it was read/.test(event.reason)) throw new Error("disk-error: " + JSON.stringify(events));
        if(vm.is_running()) throw new Error("the machine runs");
        let refused = false;
        try { await vm.save_state(); } catch(e) { refused = /held after an I\/O error/.test(e.message); }
        if(!refused) throw new Error("save_state was not refused while the read is held");
        log.push("the image's ETag changed: the read failed (\"" + event.reason + "\"), the machine stopped, save_state refused");
        // (each run() reports the held read to the guest; the BIOS and DOS
        // retry it, and each retry fails and stops the machine again)
        let runs = 0;
        await until(() =>
        {
            if(!vm.is_running() && runs < 50) { runs++; vm.run(); }
            return screen(vm).some(l => /reading drive C/i.test(l));
        }, "the guest's error message");
        log.push("run() (" + runs + " times, " + events.length + " disk-error events): the read cannot be retried, the guest sees the error (\"" +
            screen(vm).find(l => /reading drive C/i.test(l)).trim() + "\")");
        await vm.destroy();
    }
    // disk_error "report": the guest sees the error at once
    {
        const { vm, events } = await boot({ url: images + "report.img", async: true, disk_error: "report" });
        await bump("report.img");
        await vm.keyboard_send_text("copy C:\\DOS\\*.* NUL\n", 20);
        await until(() => screen(vm).some(l => /reading drive C/i.test(l)), "the guest's error message");
        if(!vm.is_running() || !events.length || events[0].policy !== "report") throw new Error("report: " + JSON.stringify(events));
        log.push("disk_error \"report\": the guest sees the error at once, the machine goes on");
        await vm.destroy();
    }
    // another origin, the ETag not exposed: unchecked, as before
    {
        const { vm, events } = await boot({ url: params.get("cross") + "/build/persistence-browser/cross.img", async: true });
        await vm.keyboard_send_text("copy C:\\DOS\\*.* NUL\n", 20);
        await until(() => screen(vm).some(l => /\d+ file\(s\) copied/.test(l)), "the copy");
        if(events.length) throw new Error("cross-origin: " + JSON.stringify(events));
        log.push("another origin (CORS, ETag not exposed): the disk works, unchecked");
        await vm.destroy();
    }
    // the requests of the read_only disks: what they were before
    const requests = await (await fetch("/__requests")).json();
    const kinds = new Set(requests.map(r => r.method + " " + r.headers.join(",")));
    for(const kind of kinds)
    {
        if(!/^(GET range,x-accept-encoding|OPTIONS access-control-request-headers,access-control-request-method)$/.test(kind)) throw new Error("a request: " + kind);
    }
    log.push(requests.length + " image requests, only: " + [...kinds].join("; "));
}
</script>
                                                                                                                                                                             source/v64/tests/persistence/disk_service.mjs                                                       0000755 0000000 0000000 00000035122 00000000000 016545  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The disk protocol (docs/disk-persistence-plan.md D2): tools/disk-service.mjs
// and its client, src/disk_service.js, in Node (fetch):
// - the service: reads as a static server (206, Content-Range, ETag the
//   generation, no-store), 416; a write session: open (the protocol
//   header), a second writer refused, writes in the file before the answer,
//   flush (fdatasync), mark and the next write's new generation (kept in
//   the state file), a repeated sequence number applied once, an older
//   write arriving after a newer overlapping one not applied, a takeover
//   after the lease ended and the old epoch's writes refused, renew,
//   close; the file changed behind its back: a new generation; Origin and
//   token checks; bad writes;
// - the client: a static server's URL and an unreachable one refused at
//   the start with the reason; reads (and their cache), writes, flush, the
//   snapshot reference; a write whose answer was lost is retried with its
//   sequence number (applied once); 5xx answers retried; a lost lease and
//   a full disk fail without retry.
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";

const { create_disk_service } = await import("../../tools/disk-service.mjs");
const { DiskServiceDisk } = await import("../../src/disk_service.js");

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-service-"));
const SIZE = 1 << 20;
fs.writeFileSync(path.join(temp, "disk.img"), new Uint8Array(SIZE).map((_, i) => i * 3 & 0xFF));
fs.writeFileSync(path.join(temp, "odd.img"), new Uint8Array(1000));
const listen = server => new Promise(resolve => server.listen(0, "127.0.0.1", () => resolve("http://127.0.0.1:" + server.address().port)));
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const call = (f, ...args) => new Promise(resolve => f(...args, (...result) => resolve(result)));
const file_bytes = (offset, length) => new Uint8Array(fs.readFileSync(path.join(temp, "disk.img")).subarray(offset, offset + length));

const service = create_disk_service({ dir: temp, origins: ["http://page.test"], token: undefined, lease_ms: 400 });
const base = await listen(service.server);
const url = base + "/disk.img";
const post = (op, headers = {}, body) => fetch(url, { method: "POST", headers: { "X-V86-Disk-Op": op, ...headers }, body });
const session_headers = s => ({ "X-V86-Disk-Session": s.session, "X-V86-Disk-Epoch": String(s.epoch) });
const write = (s, sequence, offset, data) => post("write", { ...session_headers(s), "X-V86-Disk-Sequence": String(sequence), "X-V86-Disk-Offset": String(offset) }, data);

try
{
    // reads
    let response = await fetch(url, { headers: { Range: "bytes=512-1023" } });
    assert.equal(response.status, 206);
    assert.equal(response.headers.get("content-range"), "bytes 512-1023/" + SIZE);
    assert.equal(response.headers.get("cache-control"), "no-store");
    const etag = response.headers.get("etag");
    assert.match(etag, /^"[0-9a-f-]{36}:\d+"$/);
    assert.deepEqual(new Uint8Array(await response.arrayBuffer()), file_bytes(512, 512));
    assert.equal((await fetch(url, { headers: { Range: "bytes=" + SIZE + "-" + (SIZE + 10) } })).status, 416);
    assert.equal((await fetch(base + "/missing.img")).status, 404);
    assert.equal((await fetch(base + "/.v86-disk-service.json")).status, 404, "the state file is not served");
    console.log("ok - service: Range reads (206, Content-Range, ETag, no-store), 416, 404");

    // a write session
    response = await post("open");
    assert.equal(response.status, 200);
    assert.equal(response.headers.get("x-v86-disk-protocol"), "1");
    const a = await response.json();
    assert.equal(a.size, SIZE);
    assert.equal(a.sector_size, 512);
    assert.equal(a.lease_ms, 400);
    response = await post("open");
    assert.equal(response.status, 409, "a second writer while the lease is valid");
    assert.equal((await response.json()).code, "writer");
    const data = new Uint8Array(1024).fill(0x71);
    response = await write(a, 1, 4096, data);
    assert.equal(response.status, 200);
    const generation = (await response.json()).generation;
    assert.deepEqual(file_bytes(4096, 1024), data, "in the file before the answer");
    assert.notEqual((await fetch(url, { headers: { Range: "bytes=0-511" } })).headers.get("etag"), etag, "the ETag is the generation");
    const before = service.stats.flushes;
    assert.equal((await post("flush", session_headers(a))).status, 200);
    assert.equal(service.stats.flushes, before + 1, "flush: fdatasync");
    // repeated and late writes
    const newer = new Uint8Array(512).fill(0x22), older = new Uint8Array(512).fill(0x11);
    await write(a, 3, 8192, newer);
    response = await write(a, 2, 8192, older);
    assert.equal(response.status, 200, "an older write arriving late: answered");
    assert.deepEqual(file_bytes(8192, 512), newer, "not applied over the newer one");
    response = await write(a, 3, 8192, older);
    assert.equal((await response.json()).repeated, true, "a repeated sequence number");
    assert.deepEqual(file_bytes(8192, 512), newer, "applied once");
    // mark
    response = await post("mark", session_headers(a));
    const marked = (await response.json()).generation;
    const state = JSON.parse(fs.readFileSync(path.join(temp, ".v86-disk-service.json"), "utf8"));
    assert.equal(String(state["disk.img"].generation), marked, "the marked generation is in the state file");
    response = await write(a, 4, 0, new Uint8Array(512));
    assert.notEqual((await response.json()).generation, marked, "the next write: another generation");
    assert.equal(String(JSON.parse(fs.readFileSync(path.join(temp, ".v86-disk-service.json"), "utf8"))["disk.img"].generation),
        String(+marked + 1), "kept before the data was written");
    // bad writes
    assert.equal((await write(a, 5, 100, new Uint8Array(512))).status, 400, "not sector aligned");
    assert.equal((await write(a, 6, SIZE, new Uint8Array(512))).status, 400, "past the end");
    // renew, then the lease ends: taken over, the old epoch refused
    assert.equal((await post("renew", session_headers(a))).status, 200);
    await wait(600);
    response = await post("open");
    assert.equal(response.status, 200, "the lease ended: taken over");
    const b = await response.json();
    assert.equal(b.epoch, a.epoch + 1);
    response = await write(a, 7, 0, new Uint8Array(512).fill(9));
    assert.equal(response.status, 409, "the old epoch's write");
    assert.equal((await response.json()).code, "epoch");
    assert.notDeepEqual(file_bytes(0, 512), new Uint8Array(512).fill(9));
    assert.equal((await post("close", session_headers(b))).status, 200);
    response = await post("open");
    assert.equal(response.status, 200, "closed: open again at once");
    assert.equal((await post("close", session_headers(await response.json()))).status, 200);
    console.log("ok - service: one writer; writes in the file; flush; repeated and late writes; mark; lease, takeover, old epoch refused; close");

    // changed behind its back
    const g1 = (await fetch(url, { headers: { Range: "bytes=0-511" } })).headers.get("etag");
    await wait(20);
    const fd = fs.openSync(path.join(temp, "disk.img"), "r+");
    fs.writeSync(fd, new Uint8Array(512).fill(5), 0, 512, 65536);
    fs.closeSync(fd);
    const g2 = (await fetch(url, { headers: { Range: "bytes=0-511" } })).headers.get("etag");
    assert.notEqual(g1, g2, "the file changed outside: another generation");
    console.log("ok - service: a change of the file behind its back is another generation");

    // Origin and token
    response = await fetch(url, { method: "POST", headers: { "X-V86-Disk-Op": "open", "Origin": "http://evil.test" } });
    assert.equal(response.status, 403);
    response = await fetch(url, { method: "OPTIONS", headers: { "Origin": "http://page.test", "Access-Control-Request-Method": "POST" } });
    assert.equal(response.headers.get("access-control-allow-origin"), "http://page.test");
    assert.match(response.headers.get("access-control-allow-headers"), /X-V86-Disk-Op/);
    assert.match(response.headers.get("access-control-expose-headers"), /ETag/);
    const locked = create_disk_service({ dir: temp, token: "s3cret", lease_ms: 400 });
    const locked_base = await listen(locked.server);
    response = await fetch(locked_base + "/odd.img", { method: "POST", headers: { "X-V86-Disk-Op": "open" } });
    assert.equal(response.status, 401, "no token");
    response = await fetch(locked_base + "/odd.img", { method: "POST", headers: { "X-V86-Disk-Op": "open", "Authorization": "Bearer s3cret" } });
    assert.equal(response.status, 200, "the token");
    await locked.close();
    console.log("ok - service: Origin checked, CORS for the origins given; the token");

    // the client: refused at the start
    const plain = http.createServer((req, res) => { res.writeHead(req.method === "GET" ? 200 : 405).end(); });
    const plain_base = await listen(plain);
    await assert.rejects(new DiskServiceDisk(plain_base + "/disk.img", { name: "hda" }).load(),
        /hda's URL can only be read, not written back .* use a disk service that supports writing .* or omit disk_option/);
    plain.close();
    await assert.rejects(new DiskServiceDisk("http://127.0.0.1:1/disk.img", { name: "hdb" }).load(), /hdb: the disk service at .* cannot be reached/);
    await assert.rejects(new DiskServiceDisk(base + "/odd.img", { name: "hda" }).load(), /not a whole number of 512-byte sectors/);
    await assert.rejects(new DiskServiceDisk(url, { name: "hda", size: 512 }).load(), /the descriptor's size says 512/);
    console.log("ok - client: a static server's URL, an unreachable service, odd sizes refused at the start");

    // the client: reads, writes, flush, the snapshot reference
    await wait(600);
    const disk = new DiskServiceDisk(url, { name: "hda" });
    await disk.load();
    assert.equal(disk.byteLength, SIZE);
    let [got, error] = await call(disk.get.bind(disk), 4096, 1024);
    assert.equal(error, undefined);
    assert.deepEqual(got, new Uint8Array(1024).fill(0x71));
    const requests = disk.requests;
    [got] = await call(disk.get.bind(disk), 4096 + 512, 512);
    assert.equal(disk.requests, requests, "cached");
    const fresh = new Uint8Array(512).fill(0x5D);
    [error] = await call(disk.set.bind(disk), 4096, fresh);
    assert.equal(error, undefined);
    assert.deepEqual(file_bytes(4096, 512), fresh, "in the file when it completes");
    assert.deepEqual(disk.get_from_cache(4096, 512), fresh, "the cache has the write");
    [error] = await call(disk.flush.bind(disk));
    assert.equal(disk.flushes, 1);
    assert.throws(() => disk.get_state(), /needs it flushed first/);
    [error] = await call(disk.prepare_snapshot.bind(disk));
    const reference = disk.get_state();
    assert.equal(reference[0], "v86-writeback");
    disk.check_state(reference);
    await call(disk.set.bind(disk), 0, new Uint8Array(512));
    assert.throws(() => disk.check_state(reference), /cannot go back to it/);
    assert.throws(() => disk.get_state(), /needs it flushed first/, "a write after the mark");
    console.log("ok - client: reads (cached), a write in the file and the cache when it completes, flush, the snapshot reference");

    // the answer of a write lost: retried, applied once
    const proxy_state = { drop_answer: 0, fail: 0, status: 0 };
    const proxy = http.createServer((req, res) =>
    {
        const chunks = [];
        req.on("data", c => chunks.push(c));
        req.on("end", async () =>
        {
            if(proxy_state.status && req.headers["x-v86-disk-op"] === "write")
            {
                proxy_state.status_count = (proxy_state.status_count || 0) + 1;
                res.writeHead(proxy_state.status, { "X-V86-Disk-Protocol": "1", "Content-Type": "application/json" });
                res.end(JSON.stringify({ code: proxy_state.status === 507 ? "no_space" : "io", error: "test" }));
                if(proxy_state.status !== 507 && --proxy_state.fail <= 0) proxy_state.status = 0;
                return;
            }
            const upstream = await fetch(url, { method: req.method, headers: Object.fromEntries(Object.entries(req.headers).filter(([k]) => k.startsWith("x-v86") || k === "range")), body: req.method === "POST" ? Buffer.concat(chunks) : undefined });
            const body = Buffer.from(await upstream.arrayBuffer());
            if(proxy_state.drop_answer && req.headers["x-v86-disk-op"] === "write")
            {
                proxy_state.drop_answer--;
                req.socket.destroy();
                return;
            }
            res.writeHead(upstream.status, Object.fromEntries([...upstream.headers].filter(([k]) => k !== "content-length" && k !== "transfer-encoding")));
            res.end(body);
        });
    });
    const proxy_base = await listen(proxy);
    await call(disk.close.bind(disk));
    const through = new DiskServiceDisk(proxy_base + "/disk.img", { name: "hda" });
    await through.load();
    const writes = service.stats.writes;
    proxy_state.drop_answer = 1;
    [error] = await call(through.set.bind(through), 16384, new Uint8Array(512).fill(0x44));
    assert.equal(error, undefined, "retried after the lost answer");
    assert.equal(service.stats.writes, writes + 1, "applied once");
    proxy_state.status = 503;
    proxy_state.fail = 2;
    [error] = await call(through.set.bind(through), 16384, new Uint8Array(512).fill(0x45));
    assert.equal(error, undefined, "5xx answers retried");
    assert.equal(proxy_state.status_count, 2);
    proxy_state.status = 507;
    [error] = await call(through.set.bind(through), 16384, new Uint8Array(512).fill(0x46));
    assert.equal(error.kind, "no_space");
    assert.equal(error.retryable, false, "a full disk: not retried");
    proxy_state.status = 0;
    console.log("ok - client: a lost answer retried with its sequence number (applied once); 5xx retried; 507 not");

    // a lost lease
    clearTimeout(through.renew_timer);
    await wait(600);
    const other = await post("open");
    assert.equal(other.status, 200, "another session took the image over");
    [error] = await call(through.set.bind(through), 0, new Uint8Array(512));
    assert.equal(error.kind, "lease");
    assert.equal(error.retryable, false);
    assert.match(error.message, /another session writes the image now/);
    [error] = await call(through.set.bind(through), 512, new Uint8Array(512));
    assert.equal(error.retryable, false, "and so do the next ones");
    proxy.close();
    console.log("ok - client: a lost lease fails the writes, not to be retried");
}
finally
{
    await service.close();
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("disk service tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/persistence/disk_service_sync.mjs                                                  0000755 0000000 0000000 00000024071 00000000000 017602  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The disk service client's synchronous requests (docs/disk-persistence-plan.md
// D2, src/disk_service.js): in a worker, reads and writes to the local disk
// service are synchronous XMLHttpRequests. Node has none: this test gives it
// one (a worker thread makes the request, this thread waits with
// Atomics.wait), against tools/disk-service.mjs (in that thread, which is
// free to answer while this one waits):
// - a read and a write complete before get and set return; a cached read
//   makes no request; the write is in the file when it completes;
// - a sync request that fails (no answer; an answer lost after the service
//   applied the write; a 5xx) goes the asynchronous way: the right data, the
//   write applied once;
// - a write overlapping one on its way waits for it (asynchronously), the
//   later data wins;
// - a refusal (the lease lost) is the error at once, not retried;
// - not on the page (window), not to another computer.
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { once } from "node:events";
import { Worker } from "node:worker_threads";

const { DiskServiceDisk } = await import("../../src/disk_service.js");

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-disk-service-sync-"));
const SIZE = 1 << 20;
fs.writeFileSync(path.join(temp, "disk.img"), new Uint8Array(SIZE).map((_, i) => i * 5 & 0xFF));

const shared = new SharedArrayBuffer(8 + (4 << 20));
const control = new Int32Array(shared, 0, 2);
const helper = new Worker(`
const { parentPort, workerData } = require("node:worker_threads");
const { shared, dir, module } = workerData;
const control = new Int32Array(shared, 0, 2);
const bytes = new Uint8Array(shared, 8);
let service;
import(module).then(async ({ create_disk_service }) =>
{
    service = create_disk_service({ dir, origins: [], lease_ms: 400 });
    await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
    parentPort.postMessage({ port: service.server.address().port });
});
parentPort.on("message", async ({ method, url, headers, body, mode, stats, close }) =>
{
    if(stats) { parentPort.postMessage({ stats: { ...service.stats } }); return; }
    if(close) { await service.close(); parentPort.postMessage({ closed: true }); return; }
    let answer;
    try
    {
        if(mode.startsWith("status:")) answer = { status: +mode.slice(7), headers: {}, body: new TextEncoder().encode("{}") };
        else
        {
            const response = await fetch(url, { method, headers, body: body || undefined });
            answer = { status: response.status, headers: Object.fromEntries(response.headers), body: new Uint8Array(await response.arrayBuffer()) };
        }
        if(mode === "lost") answer = null;
    }
    catch(e)
    {
        answer = null;
    }
    if(answer)
    {
        const head = new TextEncoder().encode(JSON.stringify({ status: answer.status, headers: answer.headers, length: answer.body.length }));
        new DataView(shared, 8).setUint32(0, head.length, true);
        bytes.set(head, 4);
        bytes.set(answer.body, 4 + head.length);
    }
    Atomics.store(control, 0, answer ? 1 : 2);
    Atomics.notify(control, 0);
});
`, { eval: true, workerData: { shared, dir: temp, module: new URL("../../tools/disk-service.mjs", import.meta.url).href } });
const port = (await once(helper, "message"))[0].port;
const stats = async () => { helper.postMessage({ stats: true }); return (await once(helper, "message"))[0].stats; };

/** A synchronous XMLHttpRequest, as a worker has one (what src/disk_service.js uses of it) */
class SyncXMLHttpRequest
{
    constructor() { this.headers = {}; this.status = 0; this.response = null; this.answer_headers = {}; this.responseType = ""; this.timeout = 0; }
    open(method, url, async) { assert.equal(async, false, "synchronous"); this.method = method; this.url = url; }
    setRequestHeader(name, value) { this.headers[name] = value; }
    getResponseHeader(name) { return this.answer_headers[name.toLowerCase()] ?? null; }
    send(body)
    {
        const mode = SyncXMLHttpRequest.next.shift() || "";
        SyncXMLHttpRequest.sent.push({ op: this.headers["X-V86-Disk-Op"] || this.method, mode });
        if(mode === "network") throw new Error("NetworkError: a network error occurred");
        Atomics.store(control, 0, 0);
        helper.postMessage({ method: this.method, url: this.url, headers: this.headers, body: body ? body.slice() : null, mode });
        assert.notEqual(Atomics.wait(control, 0, 0, this.timeout || 10000), "timed-out", "the helper answers");
        if(Atomics.load(control, 0) === 2) throw new Error("NetworkError: a network error occurred");
        const length = new DataView(shared, 8).getUint32(0, true);
        const head = JSON.parse(new TextDecoder().decode(new Uint8Array(shared, 12, length)));
        this.status = head.status;
        this.answer_headers = head.headers;
        this.response = new Uint8Array(shared, 12 + length, head.length).slice().buffer;
    }
}
/** @type {string[]} the next requests' failures: "network", "lost" (the service got it), "status:<n>" */
SyncXMLHttpRequest.next = [];
SyncXMLHttpRequest.sent = [];
globalThis.XMLHttpRequest = SyncXMLHttpRequest;

const file_bytes = (offset, length) => new Uint8Array(fs.readFileSync(path.join(temp, "disk.img")).subarray(offset, offset + length));
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
/** a call's callback: [synchronous?, its arguments] once it ran */
function call(f, ...args)
{
    let sync = true, result;
    const done = new Promise(resolve => f(...args, (...values) => { result = values; resolve([sync, values]); }));
    sync = result !== undefined;
    return done.then(([, values]) => [sync, values]);
}

const url = "http://127.0.0.1:" + port + "/disk.img";

try
{
    assert.equal(new DiskServiceDisk("http://disk.example/disk.img", { name: "hda" }).sync, false, "another computer: asynchronous");
    globalThis.window = {};
    assert.equal(new DiskServiceDisk(url, { name: "hda" }).sync, false, "on the page: asynchronous");
    delete globalThis.window;
    const disk = new DiskServiceDisk(url, { name: "hda" });
    assert.equal(disk.sync, true);
    await disk.load();
    console.log("ok - synchronous only in a worker, to this computer");

    // a read and a write, before get and set return
    let [sync, [data, error]] = await call(disk.get.bind(disk), 4096, 1024);
    assert(sync, "the read completed before get returned");
    assert.equal(error, undefined);
    assert.deepEqual(data, file_bytes(4096, 1024));
    const requests = disk.requests;
    [sync, [data]] = await call(disk.get.bind(disk), 4096 + 512, 512);
    assert(sync && disk.requests === requests, "cached");
    const first = new Uint8Array(1024).fill(0x31);
    const generation = disk.generation();
    let file_at_completion;
    disk.set(8192, first, e => { error = e; file_at_completion = file_bytes(8192, 1024); });
    assert(file_at_completion, "the write completed before set returned");
    assert.equal(error, undefined);
    assert.deepEqual(file_at_completion, first, "in the file when it completes");
    assert.notEqual(disk.generation(), generation, "the service's generation");
    assert.deepEqual(SyncXMLHttpRequest.sent.map(r => r.op), ["GET", "write"]);
    console.log("ok - a read and a write complete before get and set return; a cached read makes no request; the write in the file");

    // sync requests that fail: the asynchronous way
    SyncXMLHttpRequest.next.push("network");
    [sync, [data, error]] = await call(disk.get.bind(disk), 65536, 512);
    assert(!sync && error === undefined, "the read again, asynchronously");
    assert.deepEqual(data, file_bytes(65536, 512));
    const writes = (await stats()).writes;
    SyncXMLHttpRequest.next.push("lost");
    const second = new Uint8Array(512).fill(0x32);
    [sync, [error]] = await call(disk.set.bind(disk), 16384, second);
    assert(!sync && error === undefined, "the write again, asynchronously");
    assert.equal((await stats()).writes, writes + 1, "applied once (its sequence number)");
    assert.deepEqual(file_bytes(16384, 512), second);
    SyncXMLHttpRequest.next.push("status:503");
    const third = new Uint8Array(512).fill(0x33);
    [sync, [error]] = await call(disk.set.bind(disk), 16384, third);
    assert(!sync && error === undefined, "a 5xx: asynchronously");
    assert.deepEqual(file_bytes(16384, 512), third);
    console.log("ok - a failed sync request (no answer, an answer lost, 5xx) goes the asynchronous way; the write applied once");

    // a write overlapping one on its way
    SyncXMLHttpRequest.next.push("network");
    const sent = SyncXMLHttpRequest.sent.length;
    const a = call(disk.set.bind(disk), 32768, new Uint8Array(1024).fill(0x41));
    const b = call(disk.set.bind(disk), 33280, new Uint8Array(512).fill(0x42));
    assert.equal(SyncXMLHttpRequest.sent.length, sent + 1, "the overlapping write was not sent synchronously");
    const [[a_sync, [a_error]], [b_sync, [b_error]]] = await Promise.all([a, b]);
    assert(!a_sync && !b_sync && a_error === undefined && b_error === undefined);
    assert.deepEqual(file_bytes(32768, 1024), new Uint8Array(1024).fill(0x41).fill(0x42, 512), "the later write wins");
    console.log("ok - a write overlapping one on its way waits for it; the later data wins");

    // a refusal: the error at once
    clearTimeout(disk.renew_timer);
    await wait(600);
    const other = await fetch(url, { method: "POST", headers: { "X-V86-Disk-Op": "open" } });
    assert.equal(other.status, 200, "another session took the image over");
    [sync, [error]] = await call(disk.set.bind(disk), 0, new Uint8Array(512));
    assert(sync, "refused synchronously");
    assert.equal(error.kind, "lease");
    assert.equal(error.retryable, false);
    assert.match(error.message, /another session writes the image now/);
    console.log("ok - a refusal (the lease lost) at once, not retried");
}
finally
{
    helper.postMessage({ close: true });
    await once(helper, "message");
    await helper.terminate();
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("disk service sync tests passed");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/persistence/floppy.mjs                                                             0000755 0000000 0000000 00000022727 00000000000 015413  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Floppy disks written back (docs/disk-persistence-plan.md D3): MS-DOS 6.22
// boots from hda (read_only); fda is a local file, fdb an image of a disk
// service (tools/disk-service.mjs, in this process), both with disk_option
// "read_write" (720 KiB FAT12 disks, images/freedos722.img):
// - a file written to A: and B: is in the file, and the service's image,
//   when the command completes;
// - set_fda inserts another disk written back: the one taken out is
//   flushed and closed; the new one gets the guest's next file; eject
//   closes it;
// - a snapshot holds the floppies' references (no data): restored into a
//   new machine with the same disks;
// - the service gone, disk_error "report": the write fails, the guest sees
//   the error, "disk-error" tells the host; "stop" (the default): the
//   machine stops, the guest waits, a snapshot is refused; the service
//   back, run() tries the transfer again and the command completes, the
//   file in the image; the disk ejected while a transfer is held: the
//   guest sees the error;
// - a disk written back that is not of a floppy format's size is refused.
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { create_disk_service } = await import("../../tools/disk-service.mjs");
const ROOT = path.resolve(__dirname, "../..") + "/";
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-floppy-"));
for(const name of ["a.img", "a2.img", "b.img"]) fs.copyFileSync(ROOT + "images/freedos722.img", path.join(temp, name));
fs.writeFileSync(path.join(temp, "odd.img"), new Uint8Array(1 << 20));
const service = create_disk_service({ dir: temp, lease_ms: 3000 });
await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
const base = "http://127.0.0.1:" + service.server.address().port + "/";
const has = (name, text) => fs.readFileSync(path.join(temp, name)).includes(text);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
let service_listeners = null;
function service_down()
{
    service_listeners = service.server.listeners("request");
    service.server.removeAllListeners("request");
    service.server.on("request", req => req.socket.destroy());
}
function service_up()
{
    service.server.removeAllListeners("request");
    for(const listener of service_listeners) service.server.on("request", listener);
}

async function start(options)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga", bios: { url: ROOT + "bios/seabios.bin" }, vga_bios: { url: ROOT + "bios/vgabios.bin" },
        hda: { url: ROOT + "images/msdos622.img", async: true }, boot_order: 0x312,
        memory_size: 32 << 20, autostart: true, log_level: 0, ...options,
    });
    const events = [];
    emulator.add_listener("disk-error", event => events.push(event));
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    return { emulator, events };
}
const screen = emulator => emulator.screen_adapter ? emulator.screen_adapter.get_text_screen().map(l => l.replace(/\x00/g, " ")) : [];
async function until(condition, what, ms = 120000)
{
    const end = Date.now() + ms;
    while(!condition()) { if(Date.now() > end) throw new Error("timeout: " + what); await wait(100); }
}
async function prompt(emulator)
{
    let stable = 0;
    await until(() => { const l = screen(emulator).filter(x => x.trim()); stable = l.length && l[l.length - 1].trim() === "C:\\>" ? stable + 1 : 0; return stable >= 10; }, "C:\\>");
}
async function dos(emulator, command)
{
    await emulator.keyboard_send_text("cls\n", 20);
    await until(() => { const l = screen(emulator).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await emulator.keyboard_send_text(command + "\n", 20);
    await until(() => screen(emulator).filter(x => x.startsWith("C:\\>")).length >= 2 || screen(emulator).some(l => /Abort, Retry, Fail/.test(l)), command);
    return screen(emulator).join("\n");
}

try
{
    await assert.rejects(start({ fda: { url: path.join(temp, "odd.img"), disk_option: "read_write" } }),
        /fda: a floppy image written back must have the size of a floppy format .* not 1048576/);
    console.log("ok - a floppy written back of no floppy format's size is refused");

    const options = { fda: { url: path.join(temp, "a.img"), disk_option: "read_write" }, fdb: { url: base + "b.img", disk_option: "read_write" } };
    let { emulator } = await start(options);
    await prompt(emulator);
    const fdc = emulator.v86.cpu.devices.fdc;
    const fda = fdc.drives[0].buffer, fdb = fdc.drives[1].buffer;
    assert.ok(fda.writeback && fdb.writeback);
    await dos(emulator, "echo WRITTEN BACK TO A > A:\\A.TXT");
    assert.ok(has("a.img", "WRITTEN BACK TO A"), "A: the file has it when the command completes");
    await dos(emulator, "echo WRITTEN BACK TO B > B:\\B.TXT");
    assert.ok(has("b.img", "WRITTEN BACK TO B"), "B: the service's image has it");
    console.log("ok - A: (a local file) and B: (a disk service) written back: the files are in the images when the commands complete");

    // another disk in A:
    await emulator.set_fda({ url: path.join(temp, "a2.img"), disk_option: "read_write" });
    assert.ok(fda.closed, "the disk taken out: closed");
    await dos(emulator, "dir A: > NUL");
    await dos(emulator, "echo THE SECOND DISK > A:\\SECOND.TXT");
    assert.ok(has("a2.img", "THE SECOND DISK") && !has("a.img", "THE SECOND DISK"), "the new disk has the guest's next file");
    const second = fdc.drives[0].buffer;
    console.log("ok - set_fda: another disk written back; the one taken out is flushed and closed");

    // a snapshot: the references
    const state = await emulator.save_state();
    await emulator.destroy();
    assert.ok(second.closed && fdb.closed, "destroy(): the floppies' disks closed");
    ({ emulator } = await start({ ...options, fda: { url: path.join(temp, "a2.img"), disk_option: "read_write" }, autostart: false }));
    await emulator.restore_state(state);
    await emulator.run();
    const out = await dos(emulator, "type A:\\SECOND.TXT");
    assert.match(out, /THE SECOND DISK/);
    await emulator.eject_fda();
    assert.ok(emulator.v86.cpu.devices.fdc.drives[0].buffer === null);
    await emulator.destroy();
    console.log("ok - a snapshot with the floppies' references restored into a new machine; eject closes the disk");

    // the service gone, disk_error "report": the guest sees the error
    const m = await start({ fdb: { url: base + "b.img", disk_option: "read_write", disk_error: "report" } });
    await prompt(m.emulator);
    service_down();
    const failed = await dos(m.emulator, "echo LOST > B:\\LOST.TXT");
    assert.match(failed, /Abort, Retry, Fail/, "the guest sees the error");
    assert.ok(m.events.length && m.events[0].disk === "fdb" && m.events[0].policy === "report", JSON.stringify(m.events));
    service_up();
    await m.emulator.destroy();
    console.log("ok - the service gone, report: the floppy's write fails, the guest sees the error, disk-error (report) tells the host");

    // the service gone, disk_error "stop" (the default): the machine stops; run() tries again
    const s = await start({ fdb: { url: base + "b.img", disk_option: "read_write" } });
    await prompt(s.emulator);
    const held = async command =>
    {
        await s.emulator.keyboard_send_text("cls\n", 20);
        await until(() => { const l = screen(s.emulator).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
        const before = s.events.length;
        service_down();
        await s.emulator.keyboard_send_text(command + "\n", 20);
        await until(() => s.events.length > before && !s.emulator.is_running(), "the machine stopped");
        const event = s.events[before];
        assert.ok(event.disk === "fdb" && event.policy === "stop" && event.retryable === true, JSON.stringify(event));
        assert.ok(!screen(s.emulator).some(l => /Abort, Retry, Fail/.test(l)), "the guest does not see the error");
    };
    await held("echo HELD > B:\\HELD.TXT");
    await assert.rejects(s.emulator.save_state(), /held after an I\/O error/);
    service_up();
    await s.emulator.run();
    await until(() => screen(s.emulator).filter(x => x.startsWith("C:\\>")).length >= 2, "the command completes");
    assert.ok(!screen(s.emulator).some(l => /Abort, Retry, Fail/.test(l)), "the guest saw no error");
    await wait(1500);
    assert.ok(has("b.img", "HELD"), "the file in the service's image");
    console.log("ok - the service gone, stop: the machine stops (disk-error, stop), the guest waits, no snapshot; run() after the service is back: the command completes, the file in the image");
    await held("echo EJECTED > B:\\EJECTED.TXT");
    await s.emulator.eject_fdb();
    service_up();
    await s.emulator.run();
    await until(() => screen(s.emulator).some(l => /Abort, Retry, Fail/.test(l)), "the guest sees the error");
    await s.emulator.destroy();
    console.log("ok - the disk ejected while a transfer is held: the guest sees the error");
}
finally
{
    await service.close();
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("floppy write-back tests passed");
                                         source/v64/tests/persistence/guest.mjs                                                              0000755 0000000 0000000 00000036666 00000000000 015240  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Guests on disks written back (docs/disk-persistence-plan.md D1, "验收矩阵"):
// - Linux 4.16 (images/linux4.iso, from the CD drive), on Q35 (AHCI, NCQ)
//   and i440FX (IDE), hda a local file with disk_option "read_write", hdb a
//   file read_only: Linux sees hda's write cache enabled, hdb's not; data
//   written with fsync reaches the backend's flush and is in hda's file
//   after destroy(); writes written out without a FLUSH (sync of a block
//   device) are in the file when they complete; hdparm -W0 turns the cache
//   off and each write is then flushed; hdb's file never changes; a
//   snapshot saved and restored into a new machine ("save and power off")
//   goes on with the disk as it was (busybox 1.28 here: dd has no oflag);
// - power loss: an ext2 file system on a disk that records its writes and
//   keeps only the flushed ones when "power" is lost: every FLUSH the
//   guest issues completes after the writes completed before it are
//   flushed; a file synced before the loss is intact after it, the file
//   system mounts (the guest has no fsck, the host neither: busybox only);
// - MS-DOS 6.22 (images/msdos622.img), which never sends FLUSH CACHE: its
//   writes reach the file's stable storage by the timed flush.
//   PARTS=linux-q35,linux-ide,power,dos (default: all)

import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const PARTS = (process.env.PARTS || "linux-q35,linux-ide,power,dos").split(",");
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const ROOT = path.resolve(__dirname, "../..") + "/";
const IMAGES = ROOT + "images/";
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-writeback-guest-"));
const md5 = bytes => crypto.createHash("md5").update(bytes).digest("hex");
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

async function start(options)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga", bios: { url: ROOT + "bios/seabios.bin" }, vga_bios: { url: ROOT + "bios/vgabios.bin" },
        memory_size: 256 << 20, autostart: true, screen_dummy: true, log_level: 0, ...options,
    });
    const machine = { emulator, serial: "" };
    emulator.add_listener("serial0-output-byte", byte =>
    {
        const c = String.fromCharCode(byte);
        if(SHOW_LOGS) process.stdout.write(c);
        machine.serial += c;
    });
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    return machine;
}
function wait_for(what, predicate, timeout_ms)
{
    return new Promise((resolve, reject) =>
    {
        const begin = Date.now();
        const check = () =>
        {
            if(predicate()) return resolve();
            if(Date.now() - begin > timeout_ms) return reject(new Error("timed out waiting for " + what));
            setTimeout(check, 50);
        };
        check();
    });
}
const PROMPT = /~% $/;
async function command(machine, cmd, timeout_ms = 120000)
{
    machine.serial = "";
    machine.emulator.serial0_send(cmd + "\n");
    await wait_for(JSON.stringify(cmd), () => PROMPT.test(machine.serial), timeout_ms);
    return machine.serial.slice(cmd.length).replace(PROMPT, "");
}
const disk_buffer = (emulator, name) => emulator.v86.cpu.disk_devices().find(([n]) => n === name)[1].buffer;
/**
 * Wrap a drive's FLUSH CACHE (IDEInterface.when_writes_done: the devices
 * are not extensible, the prototype's method is wrapped for this one)
 * @return {function()} undo
 */
function on_flush_command(device, wrap)
{
    const prototype = Object.getPrototypeOf(device);
    const original = prototype.when_writes_done;
    prototype.when_writes_done = function(callback, ...rest)
    {
        return original.call(this, this === device ? wrap(callback) : callback, ...rest);
    };
    return () => { prototype.when_writes_done = original; };
}

async function linux(machine_type)
{
    const tag = "linux (" + (machine_type === "q35" ? "Q35, AHCI" : "i440FX, IDE") + ")";
    const hda_file = path.join(temp, "linux-" + machine_type + "-hda.img"), hdb_file = path.join(temp, "linux-" + machine_type + "-hdb.img");
    fs.writeFileSync(hda_file, new Uint8Array(0));
    fs.truncateSync(hda_file, 64 << 20);
    fs.writeFileSync(hdb_file, new Uint8Array(8 << 20).map((_, i) => i * 7 & 0xFF));
    const hdb_sum = md5(fs.readFileSync(hdb_file));
    const options = { machine_type, cdrom: { url: IMAGES + "linux4.iso" },
        hda: { url: hda_file, disk_option: "read_write" }, hdb: { url: hdb_file, async: true } };
    let machine = await start(options);
    await wait_for("the shell", () => PROMPT.test(machine.serial), 240000);
    const hda = disk_buffer(machine.emulator, "hda");

    const cache = await command(machine, "cat /sys/block/sda/queue/write_cache /sys/block/sdb/queue/write_cache; dmesg | grep 'Write cache'");
    assert.match(cache, /write back\s+write through/, "sda: write back, sdb: write through: " + cache);
    assert.match(cache, /\[sda\] Write cache: enabled/);
    assert.match(cache, /\[sdb\] Write cache: disabled/);
    console.log("ok - " + tag + ": Linux sees hda's write cache enabled (write back), hdb's not");

    // written and synced: in the file after destroy()
    const sum = (await command(machine, "dd if=/dev/urandom of=/tmp/x bs=1k count=2048 2>/dev/null; md5sum /tmp/x")).match(/[0-9a-f]{32}/)[0];
    const requests = hda.flush_requests;
    await command(machine, "dd if=/tmp/x of=/dev/sda bs=64k conv=fsync 2>/dev/null");
    assert.ok(hda.flush_requests > requests, "fsync: the guest's FLUSH reached the backend (" + (hda.flush_requests - requests) + ")");
    // completed writes (written out by sync, which sends no FLUSH for a
    // block device): in the file, without a flush
    const device = machine.emulator.v86.cpu.disk_devices().find(([n]) => n === "hda")[1];
    let flush_commands = 0;
    const undo = on_flush_command(device, callback => { flush_commands++; return callback; });
    const written = (await command(machine, "dd if=/dev/urandom of=/tmp/y bs=4k count=16 2>/dev/null; md5sum /tmp/y")).match(/[0-9a-f]{32}/)[0];
    await command(machine, "dd if=/tmp/y of=/dev/sda bs=4k seek=1024 2>/dev/null; sync");
    const in_file = Buffer.alloc(65536);
    const fd = fs.openSync(hda_file, "r");
    fs.readSync(fd, in_file, 0, 65536, 4 << 20);
    fs.closeSync(fd);
    assert.equal(flush_commands, 0, "no FLUSH CACHE");
    assert.equal(md5(in_file), written, "completed writes are in the file, before any flush");
    // hdparm -W0: the cache off, each write flushed
    const off = await command(machine, "hdparm -W0 /dev/sda; cat /sys/block/sda/queue/write_cache");
    assert.match(off, /setting drive write-caching to 0 \(off\)/, off);
    assert.equal(device.write_cache_enabled, false, "the drive's write cache is off");
    let writes = hda.writes, flushes = hda.flushes;
    await command(machine, "dd if=/tmp/y of=/dev/sda bs=4k seek=2048 2>/dev/null; sync");
    assert.ok(hda.writes > writes && hda.flushes - flushes >= hda.writes - writes,
        "each write flushed: " + (hda.writes - writes) + " writes, " + (hda.flushes - flushes) + " fdatasync");
    await command(machine, "hdparm -W1 /dev/sda");
    assert.equal(device.write_cache_enabled, true);
    writes = hda.writes;
    flushes = hda.flushes;
    await command(machine, "dd if=/tmp/x of=/dev/sda bs=4k seek=4096 count=64 2>/dev/null; sync");
    assert.ok(hda.flushes - flushes < hda.writes - writes, "the cache on again: not each write flushed (" +
        (hda.writes - writes) + " writes, " + (hda.flushes - flushes) + " fdatasync)");
    undo();
    console.log("ok - " + tag + ": completed writes are in the file without a flush; hdparm -W0: each write flushed, -W1: not");
    // hdb: written by the guest, its file unchanged
    await command(machine, "dd if=/dev/urandom of=/dev/sdb bs=64k count=16 2>/dev/null; sync");

    // save and power off, then go on in a new machine
    const state = await machine.emulator.save_state();
    await machine.emulator.destroy();
    assert.ok(hda.closed, "destroy() closed hda's file");
    assert.equal(md5(fs.readFileSync(hda_file).subarray(0, 2 << 20)), sum, "after destroy(): hda's file has the synced data");
    assert.equal(md5(fs.readFileSync(hdb_file)), hdb_sum, "hdb's file is unchanged");
    machine = await start({ ...options, autostart: false });
    await machine.emulator.restore_state(state);
    await machine.emulator.run();
    const after = await command(machine, "echo 3 > /proc/sys/vm/drop_caches; dd if=/dev/sda bs=64k count=32 2>/dev/null | md5sum");
    assert.ok(after.includes(sum), "the restored machine reads the disk: " + after);
    await command(machine, "dd if=/dev/zero of=/dev/sda bs=4k count=1 seek=4000 conv=fsync 2>/dev/null");
    await machine.emulator.destroy();
    console.log("ok - " + tag + ": synced data is in the file after destroy(); hdb's file unchanged; saved, powered off, restored, going on");
}

/**
 * A disk written back that keeps what it was told to flush, and loses the
 * rest when the power goes (a buffer object of one's own with the backend
 * contract)
 */
class PowerLossDisk
{
    constructor(size)
    {
        this.durable = new Uint8Array(size);
        this.byteLength = size;
        /** @type {!Map<number, !Uint8Array>} sectors written, not flushed */
        this.volatile = new Map();
        this.disk_option = "read_write";
        this.completed = 0;
        this.flushed_upto = 0;
        this.flushes = 0;
        this.lost = false;
    }
    load() { this.onload?.({}); }
    get(start, length, done) { done(this.get_from_cache(start, length)); }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache(start, length)
    {
        const data = this.durable.slice(start, start + length);
        for(let s = start / 512; s < (start + length) / 512; s++)
        {
            const sector = this.volatile.get(s);
            if(sector) data.set(sector, s * 512 - start);
        }
        return data;
    }
    set(start, data, done)
    {
        if(this.lost) { done(); return; }
        for(let i = 0; i < data.length; i += 512) this.volatile.set(start / 512 + i / 512, data.slice(i, i + 512));
        this.completed++;
        done();
    }
    flush(done)
    {
        if(!this.lost)
        {
            for(const [s, sector] of this.volatile) this.durable.set(sector, s * 512);
            this.volatile.clear();
            this.flushed_upto = this.completed;
            this.flushes++;
        }
        done();
    }
    close(done) { this.flush(done); }
    mark() { return this.generation(); }
    generation() { return String(this.completed); }
    get_buffer(done) { done(undefined); }
    get_state() { return ["v86-writeback", 1, "{}", this.generation(), this.byteLength]; }
    set_state() {}
    check_state() {}
    power_loss() { this.volatile.clear(); this.lost = true; }
}

async function power()
{
    const disk = new PowerLossDisk(64 << 20);
    let machine = await start({ machine_type: "q35", cdrom: { url: IMAGES + "linux4.iso" }, hda: disk });
    await wait_for("the shell", () => PROMPT.test(machine.serial), 240000);
    // every FLUSH CACHE: when it completes, the writes completed before it was issued are flushed
    const device = machine.emulator.v86.cpu.disk_devices().find(([n]) => n === "hda")[1];
    let checked = 0;
    const undo = on_flush_command(device, callback =>
    {
        const completed = disk.completed;
        return () =>
        {
            assert.ok(disk.flushed_upto >= completed, "FLUSH completed with " + (completed - disk.flushed_upto) + " earlier writes not flushed");
            checked++;
            callback();
        };
    });
    await command(machine, "mke2fs -q /dev/sda >/dev/null 2>&1; mkdir -p /mnt; mount /dev/sda /mnt && echo mounted");
    const sum = (await command(machine, "dd if=/dev/urandom of=/mnt/a bs=1k count=1024 2>/dev/null; sync; md5sum /mnt/a")).match(/[0-9a-f]{32}/)[0];
    // (another file, written out by the flusher thread at once, no FLUSH:
    // completed writes, not durable)
    await command(machine, "echo 1 > /proc/sys/vm/dirty_writeback_centisecs; echo 1 > /proc/sys/vm/dirty_expire_centisecs; " +
        "dd if=/dev/urandom of=/mnt/b bs=1k count=1024 2>/dev/null; sleep 3; echo written");
    assert.ok(checked > 0, "the guest's FLUSH commands were checked (" + checked + ")");
    const lost = disk.volatile.size;
    assert.ok(lost > 0, "writes completed and not flushed when the power goes");
    disk.power_loss();
    undo();
    await machine.emulator.destroy();
    console.log("ok - power loss: " + checked + " FLUSH commands, each after the writes before it were flushed; " + lost + " sectors not flushed are lost");
    // the disk as it was when the power went: the synced file is intact
    const after = new PowerLossDisk(64 << 20);
    after.durable = disk.durable;
    machine = await start({ machine_type: "q35", cdrom: { url: IMAGES + "linux4.iso" }, hda: after });
    await wait_for("the shell", () => PROMPT.test(machine.serial), 240000);
    const out = await command(machine, "mkdir -p /mnt; mount /dev/sda /mnt && echo mounted; md5sum /mnt/a; ls /mnt");
    assert.match(out, /mounted/, out);
    assert.ok(out.includes(sum), "the file synced before the power loss is intact: " + out);
    await machine.emulator.destroy();
    console.log("ok - power loss: the file system mounts, the file synced before is intact");
}

async function dos()
{
    const file = path.join(temp, "msdos622.img");
    fs.copyFileSync(IMAGES + "msdos622.img", file);
    const machine = await start({ hda: { url: file, disk_option: "read_write" }, memory_size: 32 << 20, screen_dummy: false });
    const hda = disk_buffer(machine.emulator, "hda");
    const device = machine.emulator.v86.cpu.disk_devices().find(([n]) => n === "hda")[1];
    let flush_commands = 0;
    const undo = on_flush_command(device, callback => { flush_commands++; return callback; });
    const screen = () => machine.emulator.screen_adapter ? machine.emulator.screen_adapter.get_text_screen().join("\n") : "";
    let stable = 0;
    await wait_for("C:\\>", () =>
    {
        const lines = screen().split("\n").filter(l => l.trim());
        stable = lines.length && lines[lines.length - 1].trim() === "C:\\>" ? stable + 1 : 0;
        return stable >= 20;
    }, 120000);
    await wait(1500);
    const flushes = hda.flushes;
    await machine.emulator.keyboard_send_text("echo WRITTEN BACK BY DOS > C:\\DOSDATA.TXT\n", 20);
    await wait_for("the write", () => hda.dirty_since, 30000);
    await wait_for("the timed flush", () => hda.flushes > flushes, 10000);
    assert.equal(flush_commands, 0, "MS-DOS sent no FLUSH CACHE");
    assert.ok(fs.readFileSync(file).includes("WRITTEN BACK BY DOS"), "the file has the text");
    undo();
    await machine.emulator.destroy();
    console.log("ok - MS-DOS (no FLUSH CACHE): its write reached the file and was flushed by the timed flush");
}

try
{
    if(PARTS.includes("linux-q35")) await linux("q35");
    if(PARTS.includes("linux-ide")) await linux("i440fx");
    if(PARTS.includes("power")) await power();
    if(PARTS.includes("dos")) await dos();
}
finally
{
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("write-back guest tests passed");
                                                                          source/v64/tests/persistence/node_file.mjs                                                          0000755 0000000 0000000 00000015661 00000000000 016025  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// NodeFileDisk (src/disk_writeback.js; docs/disk-persistence-plan.md D1): a
// local file written back, the backend contract on its own:
// - opening: a file that cannot be written, a size that is not whole
//   sectors or not the descriptor's, a file this process writes back
//   already: refused with the reason;
// - reads and writes are synchronous; a write is in the file when it
//   completes; flush makes it durable (fdatasync), and so does the timed
//   flush: 1 s after the last write, at most 5 s after the first one;
// - snapshots: a reference (identity: real path, device, inode;
//   generation), no data; the first write after it moves the generation
//   on; check_state takes only the same file in the same generation;
// - close flushes and closes; the file can then be opened again.
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const { NodeFileDisk, is_writeback_state, FLUSH_IDLE_MS, FLUSH_MAX_MS } = await import("../../src/disk_writeback.js");

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-writeback-"));
const file = path.join(temp, "disk.img");
const SIZE = 1 << 20;
fs.writeFileSync(file, new Uint8Array(SIZE).map((_, i) => i & 0xFF));
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const call = (f, ...args) => new Promise(resolve => f(...args, (...result) => resolve(result)));

async function open(name, size)
{
    const disk = new NodeFileDisk(file, { name, size });
    await disk.load();
    return disk;
}

try
{
    // opening
    fs.writeFileSync(path.join(temp, "odd.img"), new Uint8Array(1000));
    await assert.rejects(new NodeFileDisk(path.join(temp, "odd.img"), { name: "hda" }).load(), /hda: .*odd\.img has 1000 bytes, not a whole number of 512-byte sectors/);
    await assert.rejects(new NodeFileDisk(path.join(temp, "missing.img"), { name: "hda" }).load(), /hda: the file .*missing\.img cannot be opened for writing/);
    fs.writeFileSync(path.join(temp, "ro.img"), new Uint8Array(512));
    fs.chmodSync(path.join(temp, "ro.img"), 0o444);
    await assert.rejects(new NodeFileDisk(path.join(temp, "ro.img"), { name: "hdb" }).load(), /hdb: the file .*ro\.img cannot be opened for writing/);
    await assert.rejects(open("hda", SIZE * 2), /has 1048576 bytes, the descriptor's size says 2097152/);
    const disk = await open("hda");
    assert.equal(disk.byteLength, SIZE);
    fs.symlinkSync(file, path.join(temp, "link.img"));
    await assert.rejects(new NodeFileDisk(path.join(temp, "link.img"), { name: "hdb" }).load(), /written back by another disk of this process already/,
        "the same file by another name");
    console.log("ok - opening: unwritable, missing, not whole sectors, not the descriptor's size, written back already: refused");

    // reads, writes, flush
    let synchronous = false;
    disk.get(512, 512, data => { synchronous = true; assert.deepEqual(data, new Uint8Array(512).map((_, i) => i & 0xFF)); });
    assert.ok(synchronous, "a synchronous read");
    const data = new Uint8Array(1024).fill(0xA7);
    let [error] = await call(disk.set.bind(disk), 4096, data);
    assert.equal(error, undefined);
    const fd = fs.openSync(file, "r");
    const read = () => { const b = new Uint8Array(1024); fs.readSync(fd, b, 0, 1024, 4096); return b; };
    assert.deepEqual(read(), data, "the write is in the file when it completes");
    assert.equal(disk.flushes, 0);
    [error] = await call(disk.flush.bind(disk));
    assert.equal(error, undefined);
    assert.equal(disk.flushes, 1, "flush: fdatasync");
    [error] = await call(disk.flush.bind(disk));
    assert.equal(disk.flushes, 1, "nothing to flush: no fdatasync");
    console.log("ok - reads and writes are synchronous, a completed write is in the file, flush makes it durable");

    // the timed flush
    await call(disk.set.bind(disk), 0, new Uint8Array(512).fill(1));
    await wait(FLUSH_IDLE_MS / 2);
    assert.equal(disk.flushes, 1, "not yet");
    await wait(FLUSH_IDLE_MS / 2 + 300);
    assert.equal(disk.flushes, 2, "1 s after the last write");
    const started = Date.now();
    let flushed_at = 0;
    while(Date.now() - started < FLUSH_MAX_MS + 1500)
    {
        await call(disk.set.bind(disk), 0, new Uint8Array(512).fill(2));
        if(disk.flushes === 3 && !flushed_at) flushed_at = Date.now() - started;
        await wait(200);
    }
    assert.ok(flushed_at >= FLUSH_MAX_MS - 100 && flushed_at <= FLUSH_MAX_MS + 600, "writes every 200 ms: flushed after 5 s (" + flushed_at + " ms)");
    console.log("ok - the timed flush: " + FLUSH_IDLE_MS + " ms after the last write; with writes going on, after " + flushed_at + " ms");

    // snapshots
    const state = disk.get_state();
    assert.ok(is_writeback_state(state));
    assert.equal(state.length, 5);
    assert.equal(state[4], SIZE);
    const identity = JSON.parse(state[2]);
    assert.equal(identity.path, fs.realpathSync(file));
    assert.equal(identity.ino, String(fs.statSync(file).ino));
    assert.equal(disk.dirty_since, 0, "saved after a flush");
    disk.check_state(state);
    assert.throws(() => disk.check_state([[], []]), /has its changes in memory/, "a read_only disk's state");
    assert.throws(() => disk.check_state(undefined), /has no disk hda/);
    assert.throws(() => disk.check_state([state[0], 9, state[2], state[3], state[4]]), /version 9/);
    const generation = state[3];
    await call(disk.set.bind(disk), 0, new Uint8Array(512).fill(3));
    assert.notEqual(disk.generation(), generation, "the first write after the snapshot moves the generation on");
    assert.throws(() => disk.check_state(state), /in generation .* cannot go back to it/);
    const second = disk.get_state();
    await call(disk.set.bind(disk), 0, new Uint8Array(512).fill(3));
    assert.notEqual(disk.generation(), second[3], "also a write of the same data");
    console.log("ok - snapshots: a reference without data; the next write moves the generation on, the reference no longer fits");

    // a copy is another file
    const third = disk.get_state();
    let [closed] = await call(disk.close.bind(disk));
    assert.equal(closed, undefined);
    assert.ok(disk.closed);
    [error] = await call(disk.set.bind(disk), 0, new Uint8Array(512));
    assert.match(error.message, /the disk is closed/);
    assert.equal(error.retryable, false);
    const again = await open("hda");
    again.check_state(third);
    fs.copyFileSync(file, path.join(temp, "copy.img"));
    const copy = new NodeFileDisk(path.join(temp, "copy.img"), { name: "hdb" });
    await copy.load();
    assert.throws(() => copy.check_state(third), /is \{"path":.*disk\.img.*\} in generation/, "the same data in another file");
    await call(copy.close.bind(copy));
    await call(again.close.bind(again));
    console.log("ok - close: flushed and closed, opened again in the same generation; a copy is another image");
    fs.closeSync(fd);
}
finally
{
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("node file disk tests passed");
                                                                               source/v64/tests/persistence/response_version.mjs                                                   0000755 0000000 0000000 00000007566 00000000000 017511  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// check_response_version (src/buffer.js; docs/disk-persistence-plan.md
// "一致读取"): the first response's ETag, or without one its Last-Modified,
// is the version every later response of the file must have; responses
// without either (a cross-origin server that does not expose them) are not
// checked. The browser test (tests/persistence/browser_runner.mjs) covers
// the disks themselves.
import assert from "node:assert/strict";

const { check_response_version } = await import("../../src/buffer.js");
const response = headers => ({ getResponseHeader: name => headers[name] ?? null });
// (an XMLHttpRequest of a cross-origin response that exposes no ETag: getResponseHeader("ETag") would log
// "Refused to get unsafe header"; getAllResponseHeaders lists only what the page may read)
const cross_origin = headers => ({
    getAllResponseHeaders: () => Object.entries(headers).map(([name, value]) => name.toLowerCase() + ": " + value + "\r\n").join(""),
    getResponseHeader: name => { throw new Error("getResponseHeader(" + name + ") on a cross-origin response"); },
});

let versions = new Map();
assert.equal(check_response_version(versions, "a.img", response({ "ETag": "\"1\"", "Last-Modified": "Mon" })), undefined, "the first");
assert.equal(check_response_version(versions, "a.img", response({ "ETag": "\"1\"", "Last-Modified": "Tue" })), undefined,
    "the same ETag (Last-Modified is not compared when there is one)");
assert.equal(check_response_version(versions, "a.img", response({})), undefined, "a response without either: not checked");
const changed = check_response_version(versions, "a.img", response({ "ETag": "\"2\"" }));
assert.match(changed.message, /a\.img changed while it was read \(ETag "1", now "2"\)/);
assert.equal(changed.kind, "changed");
assert.equal(changed.retryable, false, "not retried");
assert.equal(check_response_version(versions, "b.img", response({ "ETag": "\"9\"" })), undefined, "each file its own (image parts)");
console.log("ok - the ETag of the first response is the version");

versions = new Map();
check_response_version(versions, "a.img", response({ "Last-Modified": "Mon" }));
assert.equal(check_response_version(versions, "a.img", response({ "Last-Modified": "Mon", "ETag": "\"5\"" })), undefined);
assert.match(check_response_version(versions, "a.img", response({ "Last-Modified": "Tue" })).message, /Last-Modified Mon, now Tue/);
console.log("ok - without an ETag: Last-Modified");

versions = new Map();
assert.equal(check_response_version(versions, "a.img", undefined), undefined, "Node: no response headers");
assert.equal(check_response_version(versions, "a.img", response({})), undefined);
assert.equal(check_response_version(versions, "a.img", response({ "ETag": "\"1\"" })), undefined, "the first with a version");
assert.equal(versions.get("a.img").etag, "\"1\"");
console.log("ok - responses without a version are not checked");

// a cross-origin response that exposes Last-Modified (always readable) but not ETag: the headers are read
// without getResponseHeader, Last-Modified is the version
versions = new Map();
assert.equal(check_response_version(versions, "c.img", cross_origin({ "Last-Modified": "Mon", "Content-Length": "1048576" })), undefined);
assert.deepEqual(versions.get("c.img"), { etag: null, last_modified: "Mon" });
assert.equal(check_response_version(versions, "c.img", cross_origin({ "Last-Modified": "Mon" })), undefined);
assert.match(check_response_version(versions, "c.img", cross_origin({ "Last-Modified": "Tue" })).message, /Last-Modified Mon, now Tue/);
versions = new Map();
check_response_version(versions, "d.img", cross_origin({ "ETag": "\"7\"", "Last-Modified": "Mon" }));
assert.equal(versions.get("d.img").etag, "\"7\"", "an exposed ETag is read (any case)");
console.log("ok - cross-origin responses: no getResponseHeader of headers they do not expose; Last-Modified then");
console.log("response version tests passed");
                                                                                                                                          source/v64/tests/persistence/service_machine.mjs                                                    0000755 0000000 0000000 00000033711 00000000000 017221  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Machines whose disks are written back to a disk service
// (docs/disk-persistence-plan.md D2; tools/disk-service.mjs in this
// process), in Node, driven through the IDE ports (no guest code runs),
// the AHCI controller of Q35 and virtio-blk on the virt machine:
// - IDE: a write is in the service's file when the command completes,
//   FLUSH CACHE is the service's fdatasync, the write cache is reported;
//   save_state flushes and records the generation (mark), destroy() closes
//   the session (another writer may open it at once), a new machine
//   restores the snapshot, and after a write refuses it;
// - errors: the service gone, disk_error "stop": the write is held, the
//   machine stops, save_state is refused; the service back, run() retries
//   it, it lands; "report": ERR at once; a lost lease (another session
//   took the image over) is not retried: run() reports it to the guest;
// - Q35: a drive written back to the service, pulled out: its session
//   closed (the lease released);
// - virtio-blk: a write in the file, FLUSH.
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });
const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { create_disk_service } = await import("../../tools/disk-service.mjs");
const root = path.resolve(__dirname, "../..") + "/";

const temp = fs.mkdtempSync(path.join(os.tmpdir(), "v86-service-machine-"));
const SIZE = 4 << 20;
for(const name of ["hda.img", "sata.img", "virtio.img"])
{
    const data = new Uint8Array(SIZE).map((_, i) => i * 5 + (i >> 9) & 0xFF);
    data.fill(0, 0, 512);
    data.set([0xEB, 0xFE], 0);
    data.set([0x55, 0xAA], 510);
    fs.writeFileSync(path.join(temp, name), data);
}
const file_bytes = (name, offset, length) => new Uint8Array(fs.readFileSync(path.join(temp, name)).subarray(offset, offset + length));
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

let service = create_disk_service({ dir: temp, lease_ms: 2000 });
await new Promise(resolve => service.server.listen(0, "127.0.0.1", resolve));
const port = service.server.address().port;
const base = "http://127.0.0.1:" + port + "/";
const writer = name => service.images.get(name)?.writer;

const bios = { url: root + "bios/seabios.bin" }, vga_bios = { url: root + "bios/vgabios.bin" };
async function machine(options)
{
    const emulator = new V86({ bios, vga_bios, graphics_adapter: "none", autostart: false, memory_size: 32 << 20, log_level: 0, ...options });
    const events = [];
    emulator.add_listener("disk-error", event => events.push(event));
    await new Promise((resolve, reject) => { emulator.add_listener("emulator-loaded", resolve); emulator.add_listener("emulator-error", reject); });
    return { emulator, events };
}
const DATA = 0x1F0, ERROR = 0x1F1, FEATURES = 0x1F1, COUNT = 0x1F2, LBA_LOW = 0x1F3, LBA_MID = 0x1F4, LBA_HIGH = 0x1F5, DEVICE = 0x1F6, COMMAND = 0x1F7, CONTROL = 0x3F6;
const DRQ = 0x08, ERR = 0x01, BSY = 0x80, ABRT = 0x04;
function ide(emulator)
{
    const io = emulator.v86.cpu.io;
    io.port_write8(CONTROL, 0x02);
    const status = () => io.port_read8(COMMAND);
    const until = async (condition, what, ms = 20000) =>
    {
        const end = Date.now() + ms;
        while(!condition()) { assert.ok(Date.now() < end, what); await wait(2); }
    };
    const command = (lba, count, cmd, features = 0) =>
    {
        io.port_write8(DEVICE, 0xE0 | lba >> 24 & 0x0F);
        io.port_write8(FEATURES, features);
        io.port_write8(COUNT, count);
        io.port_write8(LBA_LOW, lba & 0xFF);
        io.port_write8(LBA_MID, lba >> 8 & 0xFF);
        io.port_write8(LBA_HIGH, lba >> 16 & 0xFF);
        io.port_write8(COMMAND, cmd);
    };
    const start_write = (lba, bytes) =>
    {
        command(lba, bytes.length / 512, 0x30);
        for(let i = 0; i < bytes.length; i += 2) io.port_write16(DATA, bytes[i] | bytes[i + 1] << 8);
    };
    const write = async (lba, bytes) => { start_write(lba, bytes); await until(() => !(status() & BSY), "the write ends"); assert.equal(status() & ERR, 0); };
    const read = async (lba, count) =>
    {
        command(lba, count, 0x20);
        const bytes = new Uint8Array(count * 512);
        for(let s = 0; s < count; s++)
        {
            await until(() => !(status() & BSY), "the read");
            assert.equal(status() & (DRQ | ERR), DRQ);
            for(let i = 0; i < 256; i++) { const w = io.port_read16(DATA); bytes[s * 512 + 2 * i] = w; bytes[s * 512 + 2 * i + 1] = w >> 8; }
        }
        return bytes;
    };
    const identify = async () => { command(0, 0, 0xEC); await until(() => status() & DRQ, "IDENTIFY"); return Array.from({ length: 256 }, () => io.port_read16(DATA)); };
    const flush_cache = async () => { command(0, 0, 0xE7); await until(() => !(status() & BSY), "FLUSH CACHE"); assert.equal(status() & ERR, 0); };
    return { status, until, start_write, write, read, identify, flush_cache, io };
}

try
{
    // IDE
    const options = { hda: { url: base + "hda.img", disk_option: "read_write" } };
    let { emulator } = await machine(options);
    let d = ide(emulator);
    const hda = emulator.v86.cpu.devices.ide.primary.master.buffer;
    assert.ok(hda.writeback && typeof hda.prepare_snapshot === "function", "the disk service's backend");
    assert.ok(writer("hda.img"), "a write session");
    const pattern = new Uint8Array(1024).fill(0x6A);
    await d.write(100, pattern);
    assert.deepEqual(file_bytes("hda.img", 100 * 512, 1024), pattern, "in the service's file when the command completes");
    assert.deepEqual(await d.read(100, 2), pattern);
    const flushes = service.stats.flushes;
    await d.flush_cache();
    assert.equal(service.stats.flushes, flushes + 1, "FLUSH CACHE: the service's fdatasync");
    assert.equal((await d.identify())[85] & 1 << 5, 1 << 5, "the write cache reported");
    const state = await emulator.save_state();
    await emulator.destroy();
    assert.equal(writer("hda.img"), null, "destroy(): the session closed");
    ({ emulator } = await machine(options));
    await emulator.restore_state(state);
    d = ide(emulator);
    assert.deepEqual(await d.read(100, 2), pattern);
    await d.write(300, pattern);
    await assert.rejects(emulator.restore_state(state), /hda .* in generation/, "after a write: refused");
    await emulator.destroy();
    console.log("ok - IDE on a disk service: writes in the file, FLUSH CACHE, the write cache; save, destroy (session closed), restore; refused after a write");

    // the service gone: stop holds the write, run() retries it once the service is back
    {
        const m = await machine(options);
        d = ide(m.emulator);
        await service.close();
        d.start_write(400, pattern);
        await d.until(() => m.events.length === 1, "disk-error after the retries", 30000);
        assert.equal(m.events[0].operation, "write");
        assert.equal(m.events[0].retryable, true);
        assert.equal(m.events[0].policy, "stop");
        assert.equal(d.status() & BSY, BSY, "held");
        await assert.rejects(m.emulator.save_state(), /held after an I\/O error/);
        service = create_disk_service({ dir: temp, lease_ms: 2000 });
        await new Promise(resolve => service.server.listen(port, "127.0.0.1", resolve));
        // (the service restarted: it does not know the session, which only a
        // new machine opens again. The held write's retry is refused: held
        // again, not to be retried; the next run() reports it to the guest)
        m.emulator.v86.run();
        m.emulator.v86.stop();
        await d.until(() => m.events.length === 2, "the retry refused");
        assert.equal(m.events[1].retryable, false);
        assert.match(m.events[1].reason, /another session writes the image now|not the image's writer/);
        m.emulator.v86.run();
        m.emulator.v86.stop();
        await d.until(() => !(d.status() & BSY), "the write ends");
        assert.equal(d.status() & ERR, ERR, "the session was gone with the service: the guest sees an error");
        await m.emulator.destroy();
    }
    {
        // a service that comes back with the session (a network outage)
        const m = await machine(options);
        d = ide(m.emulator);
        const saved_listeners = service.server.listeners("request");
        service.server.removeAllListeners("request");
        service.server.on("request", (req, res) => { req.socket.destroy(); });
        d.start_write(500, pattern);
        await d.until(() => m.events.length === 1, "disk-error after the retries", 30000);
        assert.equal(m.events[0].retryable, true);
        service.server.removeAllListeners("request");
        for(const listener of saved_listeners) service.server.on("request", listener);
        m.emulator.v86.run();
        m.emulator.v86.stop();
        await d.until(() => !(d.status() & BSY), "the retried write ends");
        assert.equal(d.status() & ERR, 0, "the network back: run() retried the write");
        assert.deepEqual(file_bytes("hda.img", 500 * 512, 1024), pattern, "it landed");
        await m.emulator.destroy();
    }
    console.log("ok - the service unreachable: the write held (disk_error stop), save_state refused; run() retries it (lands, or reports a session gone with the service)");

    // report; a lost lease
    {
        const m = await machine({ hda: { url: base + "hda.img", disk_option: "read_write", disk_error: "report" } });
        d = ide(m.emulator);
        const disk = m.emulator.v86.cpu.devices.ide.primary.master.buffer;
        clearTimeout(disk.renew_timer);
        service.images.get("hda.img").writer.expires = 0;
        const other = await fetch(base + "hda.img", { method: "POST", headers: { "X-V86-Disk-Op": "open" } });
        assert.equal(other.status, 200, "another session takes the image over");
        d.start_write(600, pattern);
        await d.until(() => !(d.status() & BSY), "the write ends");
        assert.equal(d.status() & ERR, ERR, "report: ERR at once");
        assert.equal(d.io.port_read8(ERROR), ABRT);
        assert.equal(m.events[0].retryable, false, "a lost lease is not retried");
        await m.emulator.destroy();
        const answer = await other.json();
        await fetch(base + "hda.img", { method: "POST", headers: { "X-V86-Disk-Op": "close", "X-V86-Disk-Session": answer.session, "X-V86-Disk-Epoch": String(answer.epoch) } });
    }
    console.log("ok - report: ERR/ABRT at once; a lost lease is not retried");

    // Q35: pulled out, the session closed
    {
        const m = await machine({ machine_type: "q35" });
        await m.emulator.attach_sata_drive(3, { url: base + "sata.img", disk_option: "read_write" });
        assert.ok(writer("sata.img"));
        m.emulator.detach_sata_drive(3);
        await d.until(() => writer("sata.img") === null, "the session closed");
        await m.emulator.destroy();
    }
    console.log("ok - Q35: a drive written back to the service, pulled out: its session closed");

    // virtio-blk
    {
        const m = await machine({ cpu_type: "arm64", bios: undefined, vga_bios: undefined, wasm_path: root + "build/v86-arm64.wasm",
            virtio_disks: [{ url: base + "virtio.img", disk_option: "read_write" }] });
        const vcpu = m.emulator.v86.cpu;
        const transport = vcpu.virtio_mmio[31];
        const reg = (offset, value) => value === undefined ? transport.read(offset, 4) : transport.write(offset, 4, value);
        const RAM = 0x40000000, DESC = RAM + 0x10000, AVAIL = RAM + 0x11000, USED = RAM + 0x12000, BUF = RAM + 0x20000;
        const u16 = (a, v) => vcpu.write_blob_physical(new Uint8Array([v & 0xFF, v >> 8]), a);
        const u32 = (a, v) => vcpu.write_blob_physical(new Uint8Array(new Uint32Array([v]).buffer), a);
        reg(0x070, 0); reg(0x070, 3); reg(0x024, 1); reg(0x020, 1); reg(0x024, 0); reg(0x020, 0); reg(0x070, 11);
        reg(0x030, 0); reg(0x038, 8); reg(0x080, DESC); reg(0x084, 0); reg(0x090, AVAIL); reg(0x094, 0); reg(0x0A0, USED); reg(0x0A4, 0);
        vcpu.write_blob_physical(new Uint8Array(0x3000), DESC);
        reg(0x044, 1); reg(0x070, 15);
        let avail = 0;
        const request = async (type, sector, data) =>
        {
            const head = new Uint8Array(16);
            new DataView(head.buffer).setUint32(0, type, true);
            new DataView(head.buffer).setUint32(8, sector, true);
            vcpu.write_blob_physical(head, BUF);
            if(data) vcpu.write_blob_physical(data, BUF + 0x100);
            const desc = (i, address, length, flags, next) => { u32(DESC + 16 * i, address); u32(DESC + 16 * i + 4, 0); u32(DESC + 16 * i + 8, length); u16(DESC + 16 * i + 12, flags); u16(DESC + 16 * i + 14, next); };
            desc(0, BUF, 16, 1, data ? 1 : 2);
            if(data) desc(1, BUF + 0x100, data.length, 1, 2);
            desc(2, BUF + 0x1000, 1, 2, 0);
            u16(AVAIL + 4 + 2 * (avail % 8), 0);
            u16(AVAIL + 2, ++avail);
            reg(0x050, 0);
            for(let i = 0; i < 5000 && vcpu.read16_physical(USED + 2) !== avail; i++) await wait(1);
            assert.equal(vcpu.read16_physical(USED + 2), avail, "completed");
            return vcpu.read8_physical(BUF + 0x1000);
        };
        const data = new Uint8Array(512).fill(0x3C);
        assert.equal(await request(1, 50, data), 0);
        assert.deepEqual(file_bytes("virtio.img", 50 * 512, 512), data, "virtio-blk: the write is in the service's file");
        const before = service.stats.flushes;
        assert.equal(await request(4, 0), 0);
        assert.equal(service.stats.flushes, before + 1, "FLUSH: the service's fdatasync");
        await m.emulator.destroy();
        assert.equal(writer("virtio.img"), null);
    }
    console.log("ok - virtio-blk on a disk service: a write in the file, FLUSH");
}
finally
{
    await service.close();
    fs.rmSync(temp, { recursive: true, force: true });
}
console.log("service machine tests passed");
                                                       source/v64/tests/persistence/sync_xhr_bench.html                                                    0000644 0000000 0000000 00000013254 00000000000 017241  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       <!doctype html><meta charset="utf-8"><title>Disk service: synchronous requests</title>
<div id="screen"><div style="white-space: pre; font: 14px monospace; line-height: 14px"></div><canvas style="display: none"></canvas></div>
<pre id="log"></pre>
<pre id="result">RUNNING</pre>
<script type="module">
// docs/disk-persistence-plan.md, D2's synchronous XHR: MS-DOS 6.22 on a disk
// written back to the local disk service (the runner's dos.img), the CPU in
// its Worker, on i440FX (IDE) and Q35 (AHCI); the BIOS does all of DOS's
// disk I/O and polls for each command. Timed: the boot to the prompt, a
// copy that writes about 1.7 MB (COMMAND.COM 8 times, then that 4 times),
// a copy of it to NUL (reads). Each machine with the CPU Worker of this
// tree (build/cpu-worker.js) and with the one given as async=<path under
// build/> (a build of the client without synchronous requests), alternating,
// runs=<n> times each.
//   node tests/app/browser_runner.mjs tests/persistence/sync_xhr_bench.html service=1 async=cpu-worker-async.js runs=2
import { V86 } from "../../build/libv86.mjs";
const params = new URLSearchParams(location.search);
const url = params.get("service") + "dos.img";
const runs = +(params.get("runs") || 2);
const workers = [["sync", "../../build/cpu-worker.js"]].concat(params.get("async") ? [["async", "../../build/" + params.get("async")]] : []);
const lines = [];
const log = text => { lines.push(text); document.getElementById("log").textContent = lines.join("\n"); };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const screen = vm => (vm.screen_adapter ? vm.screen_adapter.get_text_screen() : []).map(l => l.replace(/\x00/g, " "));
async function until(vm, condition, what, timeout = 300000)
{
    const end = performance.now() + timeout;
    while(!condition())
    {
        if(performance.now() > end) throw new Error("timeout: " + what + "\n" + screen(vm).join("\n"));
        await sleep(10);
    }
    return performance.now();
}
const prompt_last = vm => { const l = screen(vm).filter(x => x.trim()); return l.length && l[l.length - 1].trim() === "C:\\>"; };
/** a command's time: from its Enter to the prompt after it */
async function command(vm, text)
{
    await vm.keyboard_send_text("cls\n", 20);
    await until(vm, () => { const l = screen(vm).filter(x => x.trim()); return l.length === 1 && l[0].startsWith("C:\\>"); }, "cls");
    await vm.keyboard_send_text(text, 20);
    await until(vm, () => screen(vm).some(l => l.includes(text.slice(-12))), "the command typed");
    const began = performance.now();
    await vm.keyboard_send_text("\n");
    return await until(vm, () => screen(vm).filter(x => x.startsWith("C:\\>")).length >= 2, text) - began;
}
async function run(machine, worker)
{
    const began = performance.now();
    const vm = new V86({
        wasm_path: "../../build/v86.wasm", cpu_worker: true, cpu_worker_url: worker,
        bios: { url: "../../bios/seabios.bin" }, vga_bios: { url: "../../bios/vgabios.bin" },
        graphics_adapter: "bochs_vga", graphics_adapter_path: "../../build/v86-bochs-vga.js",
        machine_type: machine, acpi: machine === "q35",
        hda: { url, disk_option: "read_write" }, memory_size: 32 << 20, autostart: true, disable_speaker: true,
        screen: { container: document.getElementById("screen") },
    });
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const prompt = await until(vm, () => prompt_last(vm), "the prompt");
    // (AUTOEXEC.BAT done: the prompt alone on its line for half a second)
    let since = performance.now();
    await until(vm, () => { if(!prompt_last(vm)) since = performance.now(); return performance.now() - since > 500; }, "a stable prompt");
    const boot = prompt - began;
    await command(vm, "del A.BIN");
    await command(vm, "del B.BIN");
    const write_a = await command(vm, "copy /b COMMAND.COM+COMMAND.COM+COMMAND.COM+COMMAND.COM+COMMAND.COM+COMMAND.COM+COMMAND.COM+COMMAND.COM A.BIN");
    const write_b = await command(vm, "copy /b A.BIN+A.BIN+A.BIN+A.BIN B.BIN");
    const read = await command(vm, "copy /b B.BIN NUL");
    const dir = screen(vm).join("\n");
    await command(vm, "dir B.BIN");
    const listed = screen(vm).find(l => /B\s+BIN/.test(l)) || "";
    await vm.destroy();
    return { boot, write: write_a + write_b, read, listed: listed.trim().replace(/\s+/g, " "), dir };
}

const results = [];
try
{
    for(let i = 0; i < runs; i++)
    {
        for(const machine of ["i440fx", "q35"])
        {
            for(const [mode, worker] of (i % 2 ? workers.slice().reverse() : workers))
            {
                const r = await run(machine, worker);
                results.push({ machine, mode, ...r });
                log(machine + " " + mode + ": boot " + (r.boot / 1000).toFixed(2) + " s, write " + (r.write / 1000).toFixed(2) +
                    " s, read " + (r.read / 1000).toFixed(2) + " s (" + r.listed + ")");
            }
        }
    }
    const median = list => { const s = list.slice().sort((a, b) => a - b); return s[s.length >> 1]; };
    const table = ["machine mode boot write read (medians, s)"];
    for(const machine of ["i440fx", "q35"])
    {
        for(const [mode] of workers)
        {
            const rows = results.filter(r => r.machine === machine && r.mode === mode);
            table.push([machine, mode].concat(["boot", "write", "read"].map(k => (median(rows.map(r => r[k])) / 1000).toFixed(2))).join(" "));
        }
    }
    document.getElementById("result").textContent = "PASS\n" + lines.join("\n") + "\n" + table.join("\n");
}
catch(e)
{
    document.getElementById("result").textContent = "FAIL " + (e.stack || e.message) + "\n" + lines.join("\n");
}
</script>
                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/platform/a64-profile.json                                                          0000644 0000000 0000000 00000066416 00000000000 015612  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
 "about": "The v86-aarch64-v1.1 CPU profile (docs/arm64-virt-android16-plan.md, 'CPU profile' and P0.3): every ID register, the IMPLEMENTATION DEFINED choices and the differences allowed against the QEMU cortex-a35 reference. tools/cpu_contract.mjs takes the a64 profiles' expected values from this file and compares the reference's registers with it; fields are [name, high bit, low bit, value].",
 "profile": "v86-aarch64-v1.1",
 "revision": 1,
 "architecture": "Armv8.0-A",
 "arm_arm": "Arm Architecture Reference Manual for A-profile architecture, DDI 0487 issue L.b (the latest issue found on 2026-10-15)",
 "reference": {
  "qemu": "9.2.0",
  "cpu": "cortex-a35,pmu=off,cntfrq=1000000000",
  "machine": "virt-9.2,gic-version=3,its=off,virtualization=off,secure=off"
 },
 "llvm_mattr": "+v8a,+fp-armv8,+neon,+aes,+sha2,+crc",
 "hwcap": {
  "value": "0x8ff",
  "names": "fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid"
 },
 "v2": {
  "profile": "v86-aarch64-v2",
  "cpu_profile": "generic-arm64",
  "llvm_mattr": "+v8a,+fp-armv8,+neon,+aes,+sha2,+crc,+pan",
  "about": "v1.1 and FEAT_PAN (optional in Armv8.0; docs/arm64-virt-android16-plan.md, profile v2 and appendix F3): PSTATE.PAN, MSR PAN (immediate and register), SPSR_EL1.PAN, SCTLR_EL1.SPAN; no PAN2 (AT S1E1RP/WP) or PAN3 (EPAN). HWCAP is v1.1's (PAN has none). tests/a64/pan.mjs checks it against QEMU's -cpu max",
  "id_space": { "S3_0_C0_C7_1": "0x0000000000100000" },
  "linux_cpu_features": ["Privileged Access Never"]
 },
 "v3": {
  "profile": "v86-aarch64-v3",
  "cpu_profile": "generic-arm64-compat32",
  "llvm_mattr": "+v8a,+fp-armv8,+neon,+aes,+sha2,+crc,+pan",
  "about": "v2 and AArch32 at EL0 (docs/aarch32-plan.md part 1): A32, T32 with IT blocks, VFPv4 and Advanced SIMD with the crypto instructions, CP15's EL0 registers. The AArch32 ID registers are the reference's (cortex-a35) for an AArch32 at EL0 only, as Cortex-A76 reports them: no AArch32 EL1 modes (ID_PFR1.ProgMod 0), no SETEND (ID_ISAR1.Endian 0: no mixed endianness), no SMC (ID_ISAR4.SMC 0: no EL3). tests/a64/aarch32_oracle.mjs and aarch32_el0.mjs check the instructions against the reference. id_space: v1.1's registers that differ (v2's PAN included)",
  "id_space": {
   "S3_0_C0_C4_0": "0x1100000001000012",
   "S3_0_C0_C7_1": "0x0000000000100000",
   "S3_0_C0_C1_0": "0x0000000000000131",
   "S3_0_C0_C1_1": "0x0000000010010000",
   "S3_0_C0_C1_2": "0x0000000000000006",
   "S3_0_C0_C1_3": "0x0000000000000000",
   "S3_0_C0_C1_4": "0x0000000010201105",
   "S3_0_C0_C1_5": "0x0000000040000000",
   "S3_0_C0_C1_6": "0x0000000001260000",
   "S3_0_C0_C1_7": "0x0000000002102211",
   "S3_0_C0_C2_0": "0x0000000002101110",
   "S3_0_C0_C2_1": "0x0000000013112110",
   "S3_0_C0_C2_2": "0x0000000021232042",
   "S3_0_C0_C2_3": "0x0000000001112131",
   "S3_0_C0_C2_4": "0x0000000000010142",
   "S3_0_C0_C2_5": "0x0000000000011121",
   "S3_0_C0_C2_6": "0x0000000000000000",
   "S3_0_C0_C2_7": "0x0000000000000000",
   "S3_0_C0_C3_0": "0x0000000010110222",
   "S3_0_C0_C3_1": "0x0000000012111111",
   "S3_0_C0_C3_2": "0x0000000000000043",
   "S3_0_C0_C3_3": "0x0000000000000000",
   "S3_0_C0_C3_4": "0x0000000000000000",
   "S3_0_C0_C3_5": "0x0000000000000000",
   "S3_0_C0_C3_6": "0x0000000000000000",
   "S3_0_C0_C3_7": "0x0000000000000000"
  },
  "reference_differences": {
   "registers": ["ID_AA64PFR0_EL1.EL1", "ID_AA64PFR0_EL1.CSV2", "ID_AA64PFR0_EL1.CSV3", "ID_PFR1_EL1.ProgMod", "ID_ISAR1_EL1.Endian", "ID_ISAR4_EL1.SMC"],
   "why": "AArch32 at EL0 only (the reference has it at EL1 too); no SETEND, no SMC; CSV2 and CSV3 as v1.1's. The rest of the AArch32 registers is the reference's"
  },
  "compat_hwcap": {
   "names": "half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt lpae evtstrm",
   "hwcap2": "aes pmull sha1 sha2 crc32",
   "why": "Linux's compat_elf_hwcap from these registers (docs/aarch32-plan.md Q0.4, checked in Q5.1 with a 32-bit /proc/cpuinfo)"
  }
 },
 "id_space_rules": ["op0=3, op1=0, CRn=0, CRm=0: MIDR_EL1 (op2=0), MPIDR_EL1 (op2=5), REVIDR_EL1 (op2=6); every other op2 is UNDEF at every EL (as QEMU)", "op0=3, op1=0, CRn=0, CRm=1-7: the registers listed; every unallocated encoding reads 0 at EL1 and is UNDEF at EL0 (Linux emulates EL0 reads with HWCAP_CPUID); Linux 6.18 reads ID_AA64MMFR3_EL1, MMFR4, ISAR3 and PFR2 unconditionally", "EL0 access to the ID registers is UNDEF (EC 0x00); there is no FEAT_IDST"],
 "id_space": [
  {
   "name": "MIDR_EL1",
   "encoding": "S3_0_C0_C0_0",
   "value": "0x00000000000f0860",
   "fields": [
    ["Implementer", 31, 24, 0],
    ["Variant", 23, 20, 0],
    ["Architecture", 19, 16, 15],
    ["PartNum", 15, 4, 134],
    ["Revision", 3, 0, 0]
   ],
   "note": "Implementer 0x00 is reserved for software use: not any Cortex part"
  },
  {
   "encoding": "S3_0_C0_C0_1",
   "value": "UNDEF"
  },
  {
   "encoding": "S3_0_C0_C0_2",
   "value": "UNDEF"
  },
  {
   "encoding": "S3_0_C0_C0_3",
   "value": "UNDEF"
  },
  {
   "encoding": "S3_0_C0_C0_4",
   "value": "UNDEF"
  },
  {
   "name": "MPIDR_EL1",
   "encoding": "S3_0_C0_C0_5",
   "value": "per core",
   "per_core": "0x80000000 | core",
   "fields": [
    ["RES1", 31, 31, 1],
    ["U", 30, 30, 0],
    ["MT", 24, 24, 0],
    ["Aff3", 39, 32, 0],
    ["Aff2", 23, 16, 0],
    ["Aff1", 15, 8, 0],
    ["Aff0", 7, 0, "core"]
   ]
  },
  {
   "name": "REVIDR_EL1",
   "encoding": "S3_0_C0_C0_6",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C0_7",
   "value": "UNDEF"
  },
  {
   "name": "ID_PFR0_EL1",
   "encoding": "S3_0_C0_C1_0",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_PFR1_EL1",
   "encoding": "S3_0_C0_C1_1",
   "value": "0x0000000000000000",
   "fields": [
    ["ProgMod", 3, 0, 0],
    ["Security", 7, 4, 0],
    ["MProgMod", 11, 8, 0],
    ["Virtualization", 15, 12, 0],
    ["GenTimer", 19, 16, 0],
    ["Sec_frac", 23, 20, 0],
    ["Virt_frac", 27, 24, 0],
    ["GIC", 31, 28, 0]
   ],
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_DFR0_EL1",
   "encoding": "S3_0_C0_C1_2",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_AFR0_EL1",
   "encoding": "S3_0_C0_C1_3",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR0_EL1",
   "encoding": "S3_0_C0_C1_4",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR1_EL1",
   "encoding": "S3_0_C0_C1_5",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR2_EL1",
   "encoding": "S3_0_C0_C1_6",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR3_EL1",
   "encoding": "S3_0_C0_C1_7",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR0_EL1",
   "encoding": "S3_0_C0_C2_0",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR1_EL1",
   "encoding": "S3_0_C0_C2_1",
   "value": "0x0000000000000000",
   "fields": [
    ["Endian", 3, 0, 0],
    ["Except", 7, 4, 0],
    ["Except_AR", 11, 8, 0],
    ["Extend", 15, 12, 0],
    ["IfThen", 19, 16, 0],
    ["Immediate", 23, 20, 0],
    ["Interwork", 27, 24, 0],
    ["Jazelle", 31, 28, 0]
   ],
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR2_EL1",
   "encoding": "S3_0_C0_C2_2",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR3_EL1",
   "encoding": "S3_0_C0_C2_3",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR4_EL1",
   "encoding": "S3_0_C0_C2_4",
   "value": "0x0000000000000000",
   "fields": [
    ["Unpriv", 3, 0, 0],
    ["WithShifts", 7, 4, 0],
    ["Writeback", 11, 8, 0],
    ["SMC", 15, 12, 0],
    ["Barrier", 19, 16, 0],
    ["SynchPrim_frac", 23, 20, 0],
    ["PSR_M", 27, 24, 0],
    ["SWP_frac", 31, 28, 0]
   ],
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR5_EL1",
   "encoding": "S3_0_C0_C2_5",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR4_EL1",
   "encoding": "S3_0_C0_C2_6",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_ISAR6_EL1",
   "encoding": "S3_0_C0_C2_7",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "MVFR0_EL1",
   "encoding": "S3_0_C0_C3_0",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "MVFR1_EL1",
   "encoding": "S3_0_C0_C3_1",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "MVFR2_EL1",
   "encoding": "S3_0_C0_C3_2",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "encoding": "S3_0_C0_C3_3",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_PFR2_EL1",
   "encoding": "S3_0_C0_C3_4",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_DFR1_EL1",
   "encoding": "S3_0_C0_C3_5",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "name": "ID_MMFR5_EL1",
   "encoding": "S3_0_C0_C3_6",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "AArch32 is not implemented"
  },
  {
   "encoding": "S3_0_C0_C3_7",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64PFR0_EL1",
   "encoding": "S3_0_C0_C4_0",
   "value": "0x1100000001000011",
   "fields": [
    ["EL0", 3, 0, 1],
    ["EL1", 7, 4, 1],
    ["EL2", 11, 8, 0],
    ["EL3", 15, 12, 0],
    ["FP", 19, 16, 0],
    ["AdvSIMD", 23, 20, 0],
    ["GIC", 27, 24, 1],
    ["RAS", 31, 28, 0],
    ["SVE", 35, 32, 0],
    ["SEL2", 39, 36, 0],
    ["MPAM", 43, 40, 0],
    ["AMU", 47, 44, 0],
    ["DIT", 51, 48, 0],
    ["RME", 55, 52, 0],
    ["CSV2", 59, 56, 1],
    ["CSV3", 63, 60, 1]
   ],
   "note": "AArch64 only at EL0 and EL1, no EL2 or EL3, FP and AdvSIMD without FP16, GICv3 system registers, CSV2 and CSV3 (the core does not speculate)"
  },
  {
   "name": "ID_AA64PFR1_EL1",
   "encoding": "S3_0_C0_C4_1",
   "value": "0x0000000000000000",
   "fields": [
    ["BT", 3, 0, 0],
    ["SSBS", 7, 4, 0],
    ["MTE", 11, 8, 0],
    ["RAS_frac", 15, 12, 0],
    ["MPAM_frac", 19, 16, 0],
    ["RES0", 23, 20, 0],
    ["SME", 27, 24, 0],
    ["RNDR_trap", 31, 28, 0],
    ["CSV2_frac", 35, 32, 0],
    ["NMI", 39, 36, 0],
    ["MTE_frac", 43, 40, 0],
    ["GCS", 47, 44, 0],
    ["THE", 51, 48, 0],
    ["MTEX", 55, 52, 0],
    ["DF2", 59, 56, 0],
    ["PFAR", 63, 60, 0]
   ]
  },
  {
   "name": "ID_AA64PFR2_EL1",
   "encoding": "S3_0_C0_C4_2",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C4_3",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64ZFR0_EL1",
   "encoding": "S3_0_C0_C4_4",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "name": "ID_AA64SMFR0_EL1",
   "encoding": "S3_0_C0_C4_5",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C4_6",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64FPFR0_EL1",
   "encoding": "S3_0_C0_C4_7",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "name": "ID_AA64DFR0_EL1",
   "encoding": "S3_0_C0_C5_0",
   "value": "0x0000000000101006",
   "fields": [
    ["DebugVer", 3, 0, 6],
    ["TraceVer", 7, 4, 0],
    ["PMUVer", 11, 8, 0],
    ["BRPs", 15, 12, 1],
    ["PMSS", 19, 16, 0],
    ["WRPs", 23, 20, 1],
    ["SEBEP", 27, 24, 0],
    ["CTX_CMPs", 31, 28, 0],
    ["PMSVer", 35, 32, 0],
    ["DoubleLock", 39, 36, 0],
    ["TraceFilt", 43, 40, 0],
    ["TraceBuffer", 47, 44, 0],
    ["MTPMU", 51, 48, 0],
    ["BRBE", 55, 52, 0],
    ["ExtTrcBuff", 59, 56, 0],
    ["HPMN0", 63, 60, 0]
   ],
   "note": "Armv8.0 debug, 2 breakpoints (1 context-aware), 2 watchpoints, no PMU, OS Double Lock"
  },
  {
   "name": "ID_AA64DFR1_EL1",
   "encoding": "S3_0_C0_C5_1",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "name": "ID_AA64DFR2_EL1",
   "encoding": "S3_0_C0_C5_2",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C5_3",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64AFR0_EL1",
   "encoding": "S3_0_C0_C5_4",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "name": "ID_AA64AFR1_EL1",
   "encoding": "S3_0_C0_C5_5",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C5_6",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C5_7",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64ISAR0_EL1",
   "encoding": "S3_0_C0_C6_0",
   "value": "0x0000000000011120",
   "fields": [
    ["RES0", 3, 0, 0],
    ["AES", 7, 4, 2],
    ["SHA1", 11, 8, 1],
    ["SHA2", 15, 12, 1],
    ["CRC32", 19, 16, 1],
    ["Atomic", 23, 20, 0],
    ["TME", 27, 24, 0],
    ["RDM", 31, 28, 0],
    ["SHA3", 35, 32, 0],
    ["SM3", 39, 36, 0],
    ["SM4", 43, 40, 0],
    ["DP", 47, 44, 0],
    ["FHM", 51, 48, 0],
    ["TS", 55, 52, 0],
    ["TLB", 59, 56, 0],
    ["RNDR", 63, 60, 0]
   ],
   "note": "AES with 64-bit PMULL, SHA1, SHA-256, CRC32; the same value as the cortex-a35 reference"
  },
  {
   "name": "ID_AA64ISAR1_EL1",
   "encoding": "S3_0_C0_C6_1",
   "value": "0x0000000000000000",
   "fields": [
    ["DPB", 3, 0, 0],
    ["APA", 7, 4, 0],
    ["API", 11, 8, 0],
    ["JSCVT", 15, 12, 0],
    ["FCMA", 19, 16, 0],
    ["LRCPC", 23, 20, 0],
    ["GPA", 27, 24, 0],
    ["GPI", 31, 28, 0],
    ["FRINTTS", 35, 32, 0],
    ["SB", 39, 36, 0],
    ["SPECRES", 43, 40, 0],
    ["BF16", 47, 44, 0],
    ["DGH", 51, 48, 0],
    ["I8MM", 55, 52, 0],
    ["XS", 59, 56, 0],
    ["LS64", 63, 60, 0]
   ],
   "note": "no PAuth: PACIASP and AUTIASP execute as hints"
  },
  {
   "name": "ID_AA64ISAR2_EL1",
   "encoding": "S3_0_C0_C6_2",
   "value": "0x0000000000000000",
   "fields": [
    ["WFxT", 3, 0, 0],
    ["RPRES", 7, 4, 0],
    ["GPA3", 11, 8, 0],
    ["APA3", 15, 12, 0],
    ["MOPS", 19, 16, 0],
    ["BC", 23, 20, 0],
    ["PAC_frac", 27, 24, 0],
    ["CLRBHB", 31, 28, 0],
    ["SYSREG_128", 35, 32, 0],
    ["SYSINSTR_128", 39, 36, 0],
    ["PRFMSLC", 43, 40, 0],
    ["PCDPHINT", 47, 44, 0],
    ["RPRFM", 51, 48, 0],
    ["CSSC", 55, 52, 0],
    ["LUT", 59, 56, 0],
    ["ATS1A", 63, 60, 0]
   ]
  },
  {
   "name": "ID_AA64ISAR3_EL1",
   "encoding": "S3_0_C0_C6_3",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C6_4",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C6_5",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C6_6",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C6_7",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "name": "ID_AA64MMFR0_EL1",
   "encoding": "S3_0_C0_C7_0",
   "value": "0x0000000000100022",
   "fields": [
    ["PARange", 3, 0, 2],
    ["ASIDBits", 7, 4, 2],
    ["BigEnd", 11, 8, 0],
    ["SNSMem", 15, 12, 0],
    ["BigEndEL0", 19, 16, 0],
    ["TGran16", 23, 20, 1],
    ["TGran64", 27, 24, 0],
    ["TGran4", 31, 28, 0],
    ["TGran16_2", 35, 32, 0],
    ["TGran64_2", 39, 36, 0],
    ["TGran4_2", 43, 40, 0],
    ["ExS", 47, 44, 0],
    ["RES0_48", 51, 48, 0],
    ["RES0_52", 55, 52, 0],
    ["FGT", 59, 56, 0],
    ["ECV", 63, 60, 0]
   ],
   "note": "40-bit PA, 16-bit ASIDs, the 4, 16 and 64 KiB granules (v1.1; v1, cpu_profile: \"generic-arm64-v1\", has 4 KiB only: TGran16 = 0, TGran64 = 0xF), no mixed endianness"
  },
  {
   "name": "ID_AA64MMFR1_EL1",
   "encoding": "S3_0_C0_C7_1",
   "value": "0x0000000000000000",
   "fields": [
    ["HAFDBS", 3, 0, 0],
    ["VMIDBits", 7, 4, 0],
    ["VH", 11, 8, 0],
    ["HPDS", 15, 12, 0],
    ["LO", 19, 16, 0],
    ["PAN", 23, 20, 0],
    ["SpecSEI", 27, 24, 0],
    ["XNX", 31, 28, 0],
    ["TWED", 35, 32, 0],
    ["ETS", 39, 36, 0],
    ["HCX", 43, 40, 0],
    ["AFP", 47, 44, 0],
    ["nTLBPA", 51, 48, 0],
    ["TIDCP1", 55, 52, 0],
    ["CMOW", 59, 56, 0],
    ["ECBHB", 63, 60, 0]
   ],
   "note": "no hardware AF/DBM, PAN, VHE"
  },
  {
   "name": "ID_AA64MMFR2_EL1",
   "encoding": "S3_0_C0_C7_2",
   "value": "0x0000000000000000",
   "fields": [
    ["CnP", 3, 0, 0],
    ["UAO", 7, 4, 0],
    ["LSM", 11, 8, 0],
    ["IESB", 15, 12, 0],
    ["VARange", 19, 16, 0],
    ["CCIDX", 23, 20, 0],
    ["NV", 27, 24, 0],
    ["ST", 31, 28, 0],
    ["AT", 35, 32, 0],
    ["IDS", 39, 36, 0],
    ["FWB", 43, 40, 0],
    ["RES0", 47, 44, 0],
    ["TTL", 51, 48, 0],
    ["BBM", 55, 52, 0],
    ["EVT", 59, 56, 0],
    ["E0PD", 63, 60, 0]
   ],
   "note": "no E0PD, 48-bit VA"
  },
  {
   "name": "ID_AA64MMFR3_EL1",
   "encoding": "S3_0_C0_C7_3",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "name": "ID_AA64MMFR4_EL1",
   "encoding": "S3_0_C0_C7_4",
   "value": "0x0000000000000000",
   "fields": "all 0"
  },
  {
   "encoding": "S3_0_C0_C7_5",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C7_6",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  },
  {
   "encoding": "S3_0_C0_C7_7",
   "value": "0x0000000000000000",
   "note": "unallocated: reads 0 at EL1, UNDEF at EL0"
  }
 ],
 "other_registers": [
  {
   "name": "CTR_EL0",
   "encoding": "S3_3_C0_C0_1",
   "value": "0x000000008444c004",
   "fields": [
    ["RES1", 31, 31, 1],
    ["TminLine", 37, 32, 0],
    ["DIC", 29, 29, 0],
    ["IDC", 28, 28, 0],
    ["CWG", 27, 24, 4],
    ["ERG", 23, 20, 4],
    ["DminLine", 19, 16, 4],
    ["L1Ip", 15, 14, 3],
    ["IminLine", 3, 0, 4]
   ],
   "note": "64-byte lines and granules, PIPT instruction cache, IDC = DIC = 0 (a test variant with IDC = DIC = 1 shows that v86 never needs the guest's IC)"
  },
  {
   "name": "DCZID_EL0",
   "encoding": "S3_3_C0_C0_7",
   "value": "0x0000000000000004",
   "fields": [
    ["DZP", 4, 4, "1 at EL0 when SCTLR_EL1.DZE = 0, else 0"],
    ["BS", 3, 0, 4]
   ]
  },
  {
   "name": "CLIDR_EL1",
   "encoding": "S3_1_C0_C0_1",
   "value": "0x000000000a200023",
   "fields": [
    ["ICB", 34, 30, 0],
    ["LoUU", 29, 27, 1],
    ["LoC", 26, 24, 2],
    ["LoUIS", 23, 21, 1],
    ["Ctype3", 8, 6, 0],
    ["Ctype2", 5, 3, 4],
    ["Ctype1", 2, 0, 3]
   ],
   "note": "separate L1 instruction and data caches, a unified L2; LoUIS = LoUU = 1, LoC = 2 (never 0: Linux would treat CTR.IDC as 1)"
  },
  {
   "name": "CCSIDR_EL1",
   "encoding": "S3_1_C0_C0_0",
   "value": "by CSSELR_EL1",
   "by_csselr": {
    "0": {
     "name": "L1 data",
     "encoding": "CSSELR 0",
     "value": "0x00000000700fe01a",
     "fields": [
      ["WT", 31, 31, 0],
      ["WB", 30, 30, 1],
      ["RA", 29, 29, 1],
      ["WA", 28, 28, 1],
      ["NumSets", 27, 13, 127],
      ["Associativity", 12, 3, 3],
      ["LineSize", 2, 0, 2]
     ],
     "note": "32 KiB, 4 ways, 64-byte lines (the cortex-a35 reference's geometry)"
    },
    "1": {
     "name": "L1 instruction",
     "encoding": "CSSELR 1",
     "value": "0x00000000200fe01a",
     "fields": [
      ["WT", 31, 31, 0],
      ["WB", 30, 30, 0],
      ["RA", 29, 29, 1],
      ["WA", 28, 28, 0],
      ["NumSets", 27, 13, 127],
      ["Associativity", 12, 3, 3],
      ["LineSize", 2, 0, 2]
     ],
     "note": "32 KiB, 4 ways, 64-byte lines"
    },
    "2": {
     "name": "L2",
     "encoding": "CSSELR 2",
     "value": "0x00000000703fe07a",
     "fields": [
      ["WT", 31, 31, 0],
      ["WB", 30, 30, 1],
      ["RA", 29, 29, 1],
      ["WA", 28, 28, 1],
      ["NumSets", 27, 13, 511],
      ["Associativity", 12, 3, 15],
      ["LineSize", 2, 0, 2]
     ],
     "note": "512 KiB, 16 ways, 64-byte lines"
    },
    "other": "0 (a level or type without a cache)"
   }
  },
  {
   "name": "CSSELR_EL1",
   "encoding": "S3_2_C0_C0_0",
   "value": "0x0000000000000000",
   "note": "read-write (InD, Level, TnD as written), saved in snapshots"
  },
  {
   "name": "AIDR_EL1",
   "encoding": "S3_1_C0_C0_7",
   "value": "0x0000000000000000",
   "fields": "all 0",
   "note": "read unconditionally by Linux 6.18 on every core: must not UNDEF"
  },
  {
   "encoding": "S3_1_C0_C0_2",
   "name": "CCSIDR2_EL1",
   "value": "UNDEF",
   "note": "no FEAT_CCIDX"
  },
  {
   "name": "CNTFRQ_EL0",
   "encoding": "S3_3_C14_C0_0",
   "value": "0x000000003b9aca00",
   "note": "reset value 1 GHz; writable at EL1, read-only at EL0 (CNTKCTL_EL1); a write changes the register only; snapshotted"
  },
  {
   "name": "FPCR",
   "value": "0x0000000000000000",
   "note": "reset value; RMode, FZ, DN and AHP take effect, the trap enables are RAZ/WI"
  },
  {
   "name": "FPSR",
   "value": "0x0000000000000000",
   "note": "reset value"
  },
  {
   "name": "ICC_SRE_EL1",
   "value": "0x0000000000000007",
   "note": "SRE RAO/WI (with DFB and DIB RAO/WI); 5 priority bits, 16-bit INTIDs, GICD_CTLR.DS = 1"
  }
 ],
 "implementation_defined": ["A store crossing a page checks both pages first: a fault in either writes nothing, FAR is the first faulting byte", "A load or store to a physical address with nothing mapped is a synchronous external abort (DFSC 0x10, FAR valid), as the reference (P0.2 platform probe); an address beyond the 40-bit PA range with the MMU off is an address size fault at level 0 (DFSC 0x00)", "Exclusives: a 64-byte reservation granule; STXR to an address other than the LDXR's fails; exception entry does not clear the local monitor (as QEMU); ERET and CLREX clear it", "TCR_EL1.TG0/TG1 naming a granule the profile does not declare, or a reserved encoding, act as 4 KiB (as QEMU's sanitize_gran_size)", "HVC is taken by the emulator as PSCI 1.1 and SMCCC whatever its immediate (the reference handles HVC #1 the same); unknown function IDs return NOT_SUPPORTED (-1); SMCCC_VERSION is NOT_SUPPORTED, as the reference; SMC is UNDEF (EC 0x00)", "One system counter, monotonic across cores and continuous over snapshot restore; without EL2, CNTVOFF is 0", "Unallocated and out-of-profile non-hint encodings are UNDEF (EC 0x00); unimplemented HINT #0-#127 are NOPs; every DMB and DSB CRm value is a full barrier"],
 "allowed_differences": {
  "cpu": [
   {
    "registers": ["MIDR_EL1", "REVIDR_EL1"],
    "why": "v86 does not claim to be a Cortex part (reference 0x411fd040)"
   },
   {
    "registers": ["ID_AA64PFR0_EL1.EL0", "ID_AA64PFR0_EL1.EL1", "ID_PFR0_EL1", "ID_PFR1_EL1", "ID_PFR2_EL1", "ID_DFR0_EL1", "ID_DFR1_EL1", "ID_AFR0_EL1", "ID_MMFR0_EL1", "ID_MMFR1_EL1", "ID_MMFR2_EL1", "ID_MMFR3_EL1", "ID_MMFR4_EL1", "ID_MMFR5_EL1", "ID_ISAR0_EL1", "ID_ISAR1_EL1", "ID_ISAR2_EL1", "ID_ISAR3_EL1", "ID_ISAR4_EL1", "ID_ISAR5_EL1", "ID_ISAR6_EL1", "MVFR0_EL1", "MVFR1_EL1", "MVFR2_EL1"],
    "why": "no AArch32: the reference runs AArch32 EL0 (probe aarch32=ran there, enoexec on v86) and /proc/cpuinfo lists 32-bit features"
   },
   {
    "registers": ["ID_AA64DFR0_EL1.BRPs", "ID_AA64DFR0_EL1.WRPs", "ID_AA64DFR0_EL1.CTX_CMPs"],
    "why": "2 breakpoints and 2 watchpoints (reference 6, 4 and 2 context breakpoints)"
   },
   {
    "registers": ["ID_AA64PFR0_EL1.CSV2", "ID_AA64PFR0_EL1.CSV3"],
    "why": "the reference reads 0 and Linux reaches the same mitigations through its MIDR safe list; the vulnerabilities/* texts may differ"
   },
   {
    "registers": ["CTR_EL0.L1Ip"],
    "why": "PIPT (reference VIPT, 0x84448004)"
   },
   {
    "registers": ["ID_AA64MMFR0_EL1.BigEnd", "ID_AA64MMFR0_EL1.SNSMem"],
    "why": "no mixed endianness (no big-endian data at EL1) and no Secure memory without EL3 (reference 1 and 1)"
   },
   {
    "behaviour": "SIMD stores (STP of Q registers, ST1-ST4) faulting across a page",
    "why": "the reference writes element by element and leaves a partial write; v86 writes nothing; tests/a64/system_oracle.mjs compares PC, ESR, FAR and registers only"
   },
   {
    "behaviour": "the probe's excl_aba on 2 and 4 cores",
    "why": "QEMU's STXR compares values, so an ABA write between LDXR and STXR goes unnoticed (excl_aba=0); v86 fails it (excl_aba=1)"
   },
   {
    "behaviour": "\"CPU features: detected\" lines in dmesg",
    "why": "follow from the register differences above"
   }
  ],
  "dtb": [
   {
    "node": "/chosen/rng-seed",
    "why": "v86 writes one (the reference runs with dtb-randomness=off)"
   },
   {
    "node": "flash@0, fw-cfg@9020000, pl061@9030000, gpio-keys, platform-bus@c000000",
    "why": "v86 has no pflash, fw-cfg, GPIO controller, power button or dynamic sysbus devices"
   },
   {
    "node": "memory",
    "why": "with extended RAM v86 has two memory ranges, from 0x4000_0000 and from 4 GiB; the reference has one from 0x4000_0000 (the probe's pagemap high-page check is judged on v86 only)"
   }
  ],
  "behavior": [{"instruction": "DC ZVA on Device memory (the MMU off, or a Device mapping)", "why": "v86 takes the alignment fault the Arm ARM requires for Device memory (DDI 0487 L.b, DC ZVA); QEMU 9.2 zeroes the block (target/arm/tcg/helper-a64.c, HELPER(dc_zva))"},
    {"instruction": "an unaligned load or store to a Device mapping with the MMU on", "why": "v86 takes the Alignment fault the Arm ARM requires for any unaligned access to Device memory; the reference QEMU 9.2 (TCG on the owner's arm64 Mac) completes it (tests/a64/mmu.mjs keeps its misaligned probes on Normal memory)"},
    {"instruction": "PSTATE.NZCV on exception entry", "why": "AArch64.TakeException leaves NZCV as it was, as v86 does; QEMU 9.2 clears it (pstate_write in arm_cpu_do_interrupt_aarch64); tests/a64/lockstep.mjs adopts QEMU's flags at an exception entry"},
    {"instruction": "reads of RAM below the kernel (0x4000_0000)", "why": "QEMU's boot stub lives at the start of RAM; v86 starts the kernel directly and leaves it zero"},
    {"instruction": "debug exceptions while OSLSR_EL1.OSLK is set (it is at reset)", "why": "the Arm ARM disables breakpoint, watchpoint and step exceptions under the OS Lock, as v86 does; QEMU 9.2 tests OSLSR bit 0 instead of OSLK (bit 1) and never blocks them (target/arm/debug_helper.c, arm_generate_debug_exceptions)"},
    {"instruction": "unlinked context ID breakpoints (DBGBCR.BT 0b0010)", "why": "v86 implements them on its context-aware breakpoint; QEMU 9.2 does not (LOG_UNIMP)"},
    {"instruction": "SP alignment checking (SCTLR_EL1.SA, SA0)", "why": "v86 takes the SP alignment fault (EC 0x26) the Arm ARM requires; QEMU 9.2 does not check SP alignment (an EL0 load through a misaligned SP becomes an ordinary alignment fault with the MMU off)"},
    {"instruction": "WFE at EL0 with SCTLR_EL1.nTWE 0", "why": "v86 traps it (EC 0x01) when it would wait, as the Arm ARM says; QEMU 9.2 never traps WFE (it yields)"},
    {"instruction": "the syndrome of a trapped MSR DAIFSet/DAIFClr at EL0", "why": "v86 reports the instruction's op1 3 and op2 6/7; QEMU 9.2 swaps op1 and op2 (syn_aa64_sysregtrap's arguments)"}]
 }
}
                                                                                                                                                                                                                                                  source/v64/tests/platform/cpu-contract.json                                                         0000644 0000000 0000000 00000222517 00000000000 016160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       {
 "about": "Observed CPUID (EAX, EBX, ECX, EDX per leaf.subleaf) and RDMSR (EDX:EAX or #GP) of the bootstrap processor per profile; the a64 profiles' ID registers (tests/a64/id_registers.c) are expected from tests/platform/a64-profile.json; generated by tools/cpu_contract.mjs, checked by `node tools/cpu_contract.mjs --check`",
 "vendor": "GenuineIntel",
 "profiles": {
  "legacy-1": {
   "options": {},
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc0800001",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-4": {
   "options": {
    "cpu_cores": 4,
    "acpi": true
   },
   "cpuid": {
    "0x00000000.0": [
     "0x0000001f",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00040800",
     "0xc0800001",
     "0x1780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x0c000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x0c000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x0c00c143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000001",
     "0x00000100",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000002",
     "0x00000004",
     "0x00000201",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000002",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-1": {
   "options": {
    "cpu_type": "x86_64"
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xf4d83201",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000328",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x0000000f",
     "0x00000240",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000021",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-4": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_cores": 4,
    "acpi": true
   },
   "cpuid": {
    "0x00000000.0": [
     "0x0000001f",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00040800",
     "0xf4d83201",
     "0x1789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x0c000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x0c000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x0c00c143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000328",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000001",
     "0x00000100",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000002",
     "0x00000004",
     "0x00000201",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000002",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x0000000f",
     "0x00000240",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000021",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-v2": {
   "options": {
    "cpu_features": "x86-64-v2"
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc0980201",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-v2": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_features": "x86-64-v2"
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc0982201",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000001",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-xsave": {
   "options": {
    "cpu_features": [
     "XSAVE"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc4800001",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000003",
     "0x00000240",
     "0x00000240",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-xsave": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_features": [
     "XSAVE"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc4802001",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000003",
     "0x00000240",
     "0x00000240",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000001",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-avx": {
   "options": {
    "cpu_features": [
     "SSSE3",
     "SSE4.1",
     "SSE4.2",
     "XSAVE",
     "AVX"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xd4980201",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-avx": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_features": [
     "SSSE3",
     "SSE4.1",
     "SSE4.2",
     "XSAVE",
     "AVX"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xd4982201",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000001",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-v3": {
   "options": {
    "cpu_features": [
     "SSSE3",
     "SSE4.1",
     "SSE4.2",
     "XSAVE",
     "AVX",
     "AVX2",
     "FMA",
     "F16C",
     "BMI1",
     "BMI2",
     "MOVBE"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xf4d81201",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000328",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-v3": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_features": "x86-64-v3"
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xf4d83201",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000328",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000007",
     "0x00000240",
     "0x00000340",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000021",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "legacy-xsaves": {
   "options": {
    "cpu_features": [
     "XSAVE",
     "XSAVEOPT",
     "XSAVEC",
     "XGETBV1",
     "XSAVES"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc4800001",
     "0x0780ab79"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000003",
     "0x00000240",
     "0x00000240",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x0000000f",
     "0x00000240",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x00000005",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "0x00000000:00000000",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "readable",
    "0x000000e8": "readable",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x00000000:00000000",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "0x00000000:00000000",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "0x00000000:00000000",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "0x00000000:00000000",
    "0xc0000080": "0x00000000:00000000",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "x64-xsaves": {
   "options": {
    "cpu_type": "x86_64",
    "cpu_features": [
     "XSAVE",
     "XSAVEOPT",
     "XSAVEC",
     "XGETBV1",
     "XSAVES"
    ]
   },
   "cpuid": {
    "0x00000000.0": [
     "0x00000016",
     "0x756e6547",
     "0x6c65746e",
     "0x49656e69"
    ],
    "0x00000001.0": [
     "0x00000673",
     "0x00010800",
     "0xc4802001",
     "0x0789fbfd"
    ],
    "0x00000002.0": [
     "0x665b5001",
     "0x00000000",
     "0x00000000",
     "0x007a7000"
    ],
    "0x00000004.0": [
     "0x00000121",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.1": [
     "0x00000122",
     "0x01c0003f",
     "0x0000003f",
     "0x00000001"
    ],
    "0x00000004.2": [
     "0x00000143",
     "0x05c0003f",
     "0x00000fff",
     "0x00000001"
    ],
    "0x00000004.3": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x00000007.0": [
     "0x00000000",
     "0x00000200",
     "0x00000000",
     "0x20000000"
    ],
    "0x00000007.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x20000000"
    ],
    "0x0000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.1": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000b.2": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x0000000d.0": [
     "0x00000003",
     "0x00000240",
     "0x00000240",
     "0x00000000"
    ],
    "0x0000000d.1": [
     "0x0000000f",
     "0x00000240",
     "0x00000000",
     "0x00000000"
    ],
    "0x40000000.0": [
     "0x00000000",
     "0x61774d56",
     "0x4d566572",
     "0x65726177"
    ],
    "0x80000000.0": [
     "0x80000008",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000001.0": [
     "0x00000000",
     "0x00000000",
     "0x00000001",
     "0x28100800"
    ],
    "0x80000002.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000003.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000004.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000005.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000006.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000007.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x80000008.0": [
     "0x00003024",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ],
    "0x8000000a.0": [
     "0x00000000",
     "0x00000000",
     "0x00000000",
     "0x00000000"
    ]
   },
   "msrs": {
    "0x00000010": "readable",
    "0x00000017": "0x00000000:00000000",
    "0x0000001b": "0x00000000:fee00900",
    "0x0000003a": "0x00000000:00000000",
    "0x0000003b": "#GP",
    "0x00000048": "0x00000000:00000000",
    "0x0000008b": "0x00000000:00000000",
    "0x000000e7": "#GP",
    "0x000000e8": "#GP",
    "0x000000fe": "0x00000000:00000508",
    "0x0000010a": "0x40000000:0d10e179",
    "0x00000174": "0x00000000:00000000",
    "0x00000175": "0x00000000:00000000",
    "0x00000176": "0x00000000:00000000",
    "0x00000179": "0x00000000:00000104",
    "0x0000017a": "0x00000000:00000000",
    "0x0000017b": "0x00000000:00000000",
    "0x000001a0": "0x00000000:00000001",
    "0x000001d9": "#GP",
    "0x00000200": "0x00000000:00000000",
    "0x00000201": "0x00000000:00000000",
    "0x0000020e": "0x00000000:00000000",
    "0x0000020f": "0x00000000:00000000",
    "0x00000250": "0x00000000:00000000",
    "0x00000258": "0x00000000:00000000",
    "0x00000259": "0x00000000:00000000",
    "0x00000268": "0x00000000:00000000",
    "0x0000026f": "0x00000000:00000000",
    "0x00000277": "0x00070406:00070406",
    "0x000002ff": "0x00000000:00000000",
    "0x00000345": "#GP",
    "0x00000400": "0x00000000:00000000",
    "0x00000401": "0x00000000:00000000",
    "0x00000402": "0x00000000:00000000",
    "0x00000403": "0x00000000:00000000",
    "0x0000040c": "0x00000000:00000000",
    "0x0000040f": "0x00000000:00000000",
    "0x000006e0": "#GP",
    "0xc0000080": "0x00000000:00000100",
    "0xc0000081": "0x00000000:00000000",
    "0xc0000082": "0x00000000:00000000",
    "0xc0000083": "0x00000000:00000000",
    "0xc0000084": "0x00000000:00000000",
    "0xc0000100": "0x00000000:00000000",
    "0xc0000101": "0x00000000:00000000",
    "0xc0000102": "0x00000000:00000000",
    "0xc0000103": "0x00000000:00000000"
   }
  },
  "a64-1": {
   "options": {
    "cpu_type": "aarch64",
    "cpu_cores": 1
   },
   "profile": "v86-aarch64-v1.1",
   "registers": {
    "S3_0_C0_C0_0": "0x00000000000f0860",
    "S3_0_C0_C0_1": "UNDEF",
    "S3_0_C0_C0_2": "UNDEF",
    "S3_0_C0_C0_3": "UNDEF",
    "S3_0_C0_C0_4": "UNDEF",
    "S3_0_C0_C0_5": "0x0000000080000000",
    "S3_0_C0_C0_6": "0x0000000000000000",
    "S3_0_C0_C0_7": "UNDEF",
    "S3_0_C0_C1_0": "0x0000000000000000",
    "S3_0_C0_C1_1": "0x0000000000000000",
    "S3_0_C0_C1_2": "0x0000000000000000",
    "S3_0_C0_C1_3": "0x0000000000000000",
    "S3_0_C0_C1_4": "0x0000000000000000",
    "S3_0_C0_C1_5": "0x0000000000000000",
    "S3_0_C0_C1_6": "0x0000000000000000",
    "S3_0_C0_C1_7": "0x0000000000000000",
    "S3_0_C0_C2_0": "0x0000000000000000",
    "S3_0_C0_C2_1": "0x0000000000000000",
    "S3_0_C0_C2_2": "0x0000000000000000",
    "S3_0_C0_C2_3": "0x0000000000000000",
    "S3_0_C0_C2_4": "0x0000000000000000",
    "S3_0_C0_C2_5": "0x0000000000000000",
    "S3_0_C0_C2_6": "0x0000000000000000",
    "S3_0_C0_C2_7": "0x0000000000000000",
    "S3_0_C0_C3_0": "0x0000000000000000",
    "S3_0_C0_C3_1": "0x0000000000000000",
    "S3_0_C0_C3_2": "0x0000000000000000",
    "S3_0_C0_C3_3": "0x0000000000000000",
    "S3_0_C0_C3_4": "0x0000000000000000",
    "S3_0_C0_C3_5": "0x0000000000000000",
    "S3_0_C0_C3_6": "0x0000000000000000",
    "S3_0_C0_C3_7": "0x0000000000000000",
    "S3_0_C0_C4_0": "0x1100000001000011",
    "S3_0_C0_C4_1": "0x0000000000000000",
    "S3_0_C0_C4_2": "0x0000000000000000",
    "S3_0_C0_C4_3": "0x0000000000000000",
    "S3_0_C0_C4_4": "0x0000000000000000",
    "S3_0_C0_C4_5": "0x0000000000000000",
    "S3_0_C0_C4_6": "0x0000000000000000",
    "S3_0_C0_C4_7": "0x0000000000000000",
    "S3_0_C0_C5_0": "0x0000000000101006",
    "S3_0_C0_C5_1": "0x0000000000000000",
    "S3_0_C0_C5_2": "0x0000000000000000",
    "S3_0_C0_C5_3": "0x0000000000000000",
    "S3_0_C0_C5_4": "0x0000000000000000",
    "S3_0_C0_C5_5": "0x0000000000000000",
    "S3_0_C0_C5_6": "0x0000000000000000",
    "S3_0_C0_C5_7": "0x0000000000000000",
    "S3_0_C0_C6_0": "0x0000000000011120",
    "S3_0_C0_C6_1": "0x0000000000000000",
    "S3_0_C0_C6_2": "0x0000000000000000",
    "S3_0_C0_C6_3": "0x0000000000000000",
    "S3_0_C0_C6_4": "0x0000000000000000",
    "S3_0_C0_C6_5": "0x0000000000000000",
    "S3_0_C0_C6_6": "0x0000000000000000",
    "S3_0_C0_C6_7": "0x0000000000000000",
    "S3_0_C0_C7_0": "0x0000000000100022",
    "S3_0_C0_C7_1": "0x0000000000000000",
    "S3_0_C0_C7_2": "0x0000000000000000",
    "S3_0_C0_C7_3": "0x0000000000000000",
    "S3_0_C0_C7_4": "0x0000000000000000",
    "S3_0_C0_C7_5": "0x0000000000000000",
    "S3_0_C0_C7_6": "0x0000000000000000",
    "S3_0_C0_C7_7": "0x0000000000000000",
    "CLIDR_EL1": "0x000000000a200023",
    "AIDR_EL1": "0x0000000000000000",
    "CCSIDR_EL1.0": "0x00000000700fe01a",
    "CSSELR_EL1.0": "0x0000000000000000",
    "CCSIDR_EL1.1": "0x00000000200fe01a",
    "CSSELR_EL1.1": "0x0000000000000001",
    "CCSIDR_EL1.2": "0x00000000703fe07a",
    "CSSELR_EL1.2": "0x0000000000000002",
    "CCSIDR_EL1.3": "0x0000000000000000",
    "CSSELR_EL1.3": "0x0000000000000003",
    "CCSIDR_EL1.4": "0x0000000000000000",
    "CSSELR_EL1.4": "0x0000000000000004",
    "CCSIDR_EL1.5": "0x0000000000000000",
    "CSSELR_EL1.5": "0x0000000000000005",
    "CCSIDR2_EL1": "UNDEF",
    "CTR_EL0": "0x000000008444c004",
    "DCZID_EL0": "0x0000000000000004",
    "CNTFRQ_EL0": "0x000000003b9aca00",
    "FPCR": "0x0000000000000000",
    "FPSR": "0x0000000000000000"
   },
   "mpidr": [
    "0x0000000080000000"
   ]
  },
  "a64-4": {
   "options": {
    "cpu_type": "aarch64",
    "cpu_cores": 4
   },
   "profile": "v86-aarch64-v1.1",
   "registers": {
    "S3_0_C0_C0_0": "0x00000000000f0860",
    "S3_0_C0_C0_1": "UNDEF",
    "S3_0_C0_C0_2": "UNDEF",
    "S3_0_C0_C0_3": "UNDEF",
    "S3_0_C0_C0_4": "UNDEF",
    "S3_0_C0_C0_5": "0x0000000080000000",
    "S3_0_C0_C0_6": "0x0000000000000000",
    "S3_0_C0_C0_7": "UNDEF",
    "S3_0_C0_C1_0": "0x0000000000000000",
    "S3_0_C0_C1_1": "0x0000000000000000",
    "S3_0_C0_C1_2": "0x0000000000000000",
    "S3_0_C0_C1_3": "0x0000000000000000",
    "S3_0_C0_C1_4": "0x0000000000000000",
    "S3_0_C0_C1_5": "0x0000000000000000",
    "S3_0_C0_C1_6": "0x0000000000000000",
    "S3_0_C0_C1_7": "0x0000000000000000",
    "S3_0_C0_C2_0": "0x0000000000000000",
    "S3_0_C0_C2_1": "0x0000000000000000",
    "S3_0_C0_C2_2": "0x0000000000000000",
    "S3_0_C0_C2_3": "0x0000000000000000",
    "S3_0_C0_C2_4": "0x0000000000000000",
    "S3_0_C0_C2_5": "0x0000000000000000",
    "S3_0_C0_C2_6": "0x0000000000000000",
    "S3_0_C0_C2_7": "0x0000000000000000",
    "S3_0_C0_C3_0": "0x0000000000000000",
    "S3_0_C0_C3_1": "0x0000000000000000",
    "S3_0_C0_C3_2": "0x0000000000000000",
    "S3_0_C0_C3_3": "0x0000000000000000",
    "S3_0_C0_C3_4": "0x0000000000000000",
    "S3_0_C0_C3_5": "0x0000000000000000",
    "S3_0_C0_C3_6": "0x0000000000000000",
    "S3_0_C0_C3_7": "0x0000000000000000",
    "S3_0_C0_C4_0": "0x1100000001000011",
    "S3_0_C0_C4_1": "0x0000000000000000",
    "S3_0_C0_C4_2": "0x0000000000000000",
    "S3_0_C0_C4_3": "0x0000000000000000",
    "S3_0_C0_C4_4": "0x0000000000000000",
    "S3_0_C0_C4_5": "0x0000000000000000",
    "S3_0_C0_C4_6": "0x0000000000000000",
    "S3_0_C0_C4_7": "0x0000000000000000",
    "S3_0_C0_C5_0": "0x0000000000101006",
    "S3_0_C0_C5_1": "0x0000000000000000",
    "S3_0_C0_C5_2": "0x0000000000000000",
    "S3_0_C0_C5_3": "0x0000000000000000",
    "S3_0_C0_C5_4": "0x0000000000000000",
    "S3_0_C0_C5_5": "0x0000000000000000",
    "S3_0_C0_C5_6": "0x0000000000000000",
    "S3_0_C0_C5_7": "0x0000000000000000",
    "S3_0_C0_C6_0": "0x0000000000011120",
    "S3_0_C0_C6_1": "0x0000000000000000",
    "S3_0_C0_C6_2": "0x0000000000000000",
    "S3_0_C0_C6_3": "0x0000000000000000",
    "S3_0_C0_C6_4": "0x0000000000000000",
    "S3_0_C0_C6_5": "0x0000000000000000",
    "S3_0_C0_C6_6": "0x0000000000000000",
    "S3_0_C0_C6_7": "0x0000000000000000",
    "S3_0_C0_C7_0": "0x0000000000100022",
    "S3_0_C0_C7_1": "0x0000000000000000",
    "S3_0_C0_C7_2": "0x0000000000000000",
    "S3_0_C0_C7_3": "0x0000000000000000",
    "S3_0_C0_C7_4": "0x0000000000000000",
    "S3_0_C0_C7_5": "0x0000000000000000",
    "S3_0_C0_C7_6": "0x0000000000000000",
    "S3_0_C0_C7_7": "0x0000000000000000",
    "CLIDR_EL1": "0x000000000a200023",
    "AIDR_EL1": "0x0000000000000000",
    "CCSIDR_EL1.0": "0x00000000700fe01a",
    "CSSELR_EL1.0": "0x0000000000000000",
    "CCSIDR_EL1.1": "0x00000000200fe01a",
    "CSSELR_EL1.1": "0x0000000000000001",
    "CCSIDR_EL1.2": "0x00000000703fe07a",
    "CSSELR_EL1.2": "0x0000000000000002",
    "CCSIDR_EL1.3": "0x0000000000000000",
    "CSSELR_EL1.3": "0x0000000000000003",
    "CCSIDR_EL1.4": "0x0000000000000000",
    "CSSELR_EL1.4": "0x0000000000000004",
    "CCSIDR_EL1.5": "0x0000000000000000",
    "CSSELR_EL1.5": "0x0000000000000005",
    "CCSIDR2_EL1": "UNDEF",
    "CTR_EL0": "0x000000008444c004",
    "DCZID_EL0": "0x0000000000000004",
    "CNTFRQ_EL0": "0x000000003b9aca00",
    "FPCR": "0x0000000000000000",
    "FPSR": "0x0000000000000000"
   },
   "mpidr": [
    "0x0000000080000000",
    "0x0000000080000001",
    "0x0000000080000002",
    "0x0000000080000003"
   ]
  }
 }
}
                                                                                                                                                                                 source/v64/tests/qemu/LICENSE                                                                       0000644 0000000 0000000 00000001225 00000000000 013002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       x86 CPU test

Copyright (c) 2003 Fabrice Bellard

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/>.
                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/qemu/Makefile                                                                      0000644 0000000 0000000 00000000650 00000000000 013436  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       CC=gcc
CC_I386=$(CC) -m32
CFLAGS=-Wall -O2 -g -fno-strict-aliasing -static -mmmx -msse
LDFLAGS=


# i386/x86_64 emulation test (test various opcodes) */
test-i386: test-i386.c test-i386-code16.S test-i386-vm86.S \
           test-i386.h test-i386-shift.h test-i386-muldiv.h
	$(CC_I386) $(CFLAGS) $(LDFLAGS) -o $@ \
              $(<D)/test-i386.c $(<D)/test-i386-code16.S $(<D)/test-i386-vm86.S -lm

clean:
	rm -f test-i386
                                                                                        source/v64/tests/qemu/Readme.md                                                                     0000644 0000000 0000000 00000000412 00000000000 013511  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       How to run:

- Obtain the `linux3.iso` image (see [Readme.md](../../Readme.md))
- Run `make test-i386`
- Get the result on the host: `./test-386 > reference`
- Get the result from the VM: `./run.js > result`
- The difference should be empty: `diff reference result`
                                                                                                                                                                                                                                                      source/v64/tests/qemu/compiler.h                                                                    0000644 0000000 0000000 00000006703 00000000000 013766  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* compiler.h: macros to abstract away compiler specifics
 *
 * This work is licensed under the terms of the GNU GPL, version 2 or later.
 * See the COPYING file in the top-level directory.
 */

#ifndef COMPILER_H
#define COMPILER_H

#if defined __clang_analyzer__ || defined __COVERITY__
#define QEMU_STATIC_ANALYSIS 1
#endif

/*----------------------------------------------------------------------------
| The macro QEMU_GNUC_PREREQ tests for minimum version of the GNU C compiler.
| The code is a copy of SOFTFLOAT_GNUC_PREREQ, see softfloat-macros.h.
*----------------------------------------------------------------------------*/
#if defined(__GNUC__) && defined(__GNUC_MINOR__)
# define QEMU_GNUC_PREREQ(maj, min) \
         ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
#else
# define QEMU_GNUC_PREREQ(maj, min) 0
#endif

#define QEMU_NORETURN __attribute__ ((__noreturn__))

#define QEMU_WARN_UNUSED_RESULT __attribute__((warn_unused_result))

#define QEMU_SENTINEL __attribute__((sentinel))

#if QEMU_GNUC_PREREQ(4, 3)
#define QEMU_ARTIFICIAL __attribute__((always_inline, artificial))
#else
#define QEMU_ARTIFICIAL
#endif

#if defined(_WIN32)
# define QEMU_PACKED __attribute__((gcc_struct, packed))
#else
# define QEMU_PACKED __attribute__((packed))
#endif

#define QEMU_ALIGNED(X) __attribute__((aligned(X)))

#ifndef glue
#define xglue(x, y) x ## y
#define glue(x, y) xglue(x, y)
#define stringify(s)	tostring(s)
#define tostring(s)	#s
#endif

#ifndef likely
#if __GNUC__ < 3
#define __builtin_expect(x, n) (x)
#endif

#define likely(x)   __builtin_expect(!!(x), 1)
#define unlikely(x)   __builtin_expect(!!(x), 0)
#endif

#ifndef container_of
#define container_of(ptr, type, member) ({                      \
        const typeof(((type *) 0)->member) *__mptr = (ptr);     \
        (type *) ((char *) __mptr - offsetof(type, member));})
#endif

/* Convert from a base type to a parent type, with compile time checking.  */
#ifdef __GNUC__
#define DO_UPCAST(type, field, dev) ( __extension__ ( { \
    char __attribute__((unused)) offset_must_be_zero[ \
        -offsetof(type, field)]; \
    container_of(dev, type, field);}))
#else
#define DO_UPCAST(type, field, dev) container_of(dev, type, field)
#endif

#define typeof_field(type, field) typeof(((type *)0)->field)
#define type_check(t1,t2) ((t1*)0 - (t2*)0)

#define QEMU_BUILD_BUG_ON_STRUCT(x) \
    struct { \
        int:(x) ? -1 : 1; \
    }

#if defined(CONFIG_STATIC_ASSERT)
#define QEMU_BUILD_BUG_ON(x) _Static_assert(!(x), "not expecting: " #x)
#elif defined(__COUNTER__)
#define QEMU_BUILD_BUG_ON(x) typedef QEMU_BUILD_BUG_ON_STRUCT(x) \
    glue(qemu_build_bug_on__, __COUNTER__) __attribute__((unused))
#else
#define QEMU_BUILD_BUG_ON(x)
#endif

#define QEMU_BUILD_BUG_ON_ZERO(x) (sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)) - \
                                   sizeof(QEMU_BUILD_BUG_ON_STRUCT(x)))

#if defined __GNUC__
# if !QEMU_GNUC_PREREQ(4, 4)
   /* gcc versions before 4.4.x don't support gnu_printf, so use printf. */
#  define GCC_FMT_ATTR(n, m) __attribute__((format(printf, n, m)))
# else
   /* Use gnu_printf when supported (qemu uses standard format strings). */
#  define GCC_FMT_ATTR(n, m) __attribute__((format(gnu_printf, n, m)))
#  if defined(_WIN32)
    /* Map __printf__ to __gnu_printf__ because we want standard format strings
     * even when MinGW or GLib include files use __printf__. */
#   define __printf__ __gnu_printf__
#  endif
# endif
#else
#define GCC_FMT_ATTR(n, m)
#endif

#endif /* COMPILER_H */
                                                             source/v64/tests/qemu/config-host.h                                                                 0000644 0000000 0000000 00000003536 00000000000 014375  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Automatically generated by create_config - do not modify */
#define CONFIG_QEMU_CONFDIR "/usr/local/etc/qemu"
#define CONFIG_QEMU_DATADIR "/usr/local/share/qemu"
#define CONFIG_QEMU_DOCDIR "/usr/local/share/doc/qemu"
#define CONFIG_QEMU_LOCALSTATEDIR "/usr/local/var"
#define CONFIG_QEMU_HELPERDIR "/usr/local/libexec"
#define HOST_I386 1
#define CONFIG_POSIX 1
#define CONFIG_LINUX 1
#define CONFIG_SLIRP 1
#define CONFIG_SMBD_COMMAND "/usr/sbin/smbd"
#define CONFIG_AC97 1
#define CONFIG_ES1370 1
#define CONFIG_SB16 1
#define CONFIG_HDA 1
#define CONFIG_AUDIO_DRIVERS \
    &oss_audio_driver,\

#define CONFIG_OSS 1
#define CONFIG_BDRV_WHITELIST \
    NULL
#define CONFIG_VNC 1
#define CONFIG_VNC_TLS 1
#define CONFIG_VNC_PNG 1
#define CONFIG_FNMATCH 1
#define QEMU_VERSION "1.3.1"
#define QEMU_PKGVERSION ""
#define CONFIG_SDL 1
#define CONFIG_CURSES 1
#define CONFIG_ATFILE 1
#define CONFIG_UTIMENSAT 1
#define CONFIG_PIPE2 1
#define CONFIG_ACCEPT4 1
#define CONFIG_SPLICE 1
#define CONFIG_EVENTFD 1
#define CONFIG_FALLOCATE 1
#define CONFIG_SYNC_FILE_RANGE 1
#define CONFIG_FIEMAP 1
#define CONFIG_DUP3 1
#define CONFIG_EPOLL 1
#define CONFIG_EPOLL_CREATE1 1
#define CONFIG_EPOLL_PWAIT 1
#define CONFIG_INOTIFY 1
#define CONFIG_INOTIFY1 1
#define CONFIG_BYTESWAP_H 1
#define CONFIG_CURL 1
#define CONFIG_ATTR 1
#define CONFIG_IOVEC 1
#define CONFIG_PREADV 1
#define CONFIG_SIGNALFD 1
#define CONFIG_FDATASYNC 1
#define CONFIG_MADVISE 1
#define CONFIG_POSIX_MADVISE 1
#define CONFIG_SIGEV_THREAD_ID 1
#define CONFIG_SMARTCARD 1
#define CONFIG_OPENGL 1
#define CONFIG_UNAME_RELEASE ""
#define CONFIG_ZERO_MALLOC 1
#define CONFIG_UCONTEXT_COROUTINE 1
#define CONFIG_OPEN_BY_HANDLE 1
#define CONFIG_LINUX_MAGIC_H 1
#define CONFIG_PRAGMA_DISABLE_UNUSED_BUT_SET 1
#define CONFIG_HAS_ENVIRON 1
#define CONFIG_TRACE_NOP 1
#define CONFIG_TRACE_FILE trace
#define CONFIG_TRACE_DEFAULT 1
                                                                                                                                                                  source/v64/tests/qemu/run-qemu.js                                                                   0000755 0000000 0000000 00000004025 00000000000 014110  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

const QEMU = "qemu-system-x86_64";

const share_dir_9p = fs.mkdtempSync("/tmp/v86-test-qemu-9p");

fs.copyFileSync(path.join(__dirname, "/test-i386"), path.join(share_dir_9p, "/test-i386"));

const qemu_version = spawnSync(QEMU, ["--version"]);
assert(qemu_version.status === 0, "QEMU not found, return code: " + qemu_version.status);
console.error("Using QEMU:");
console.error(qemu_version.stdout.toString("utf8"));

const qemu = spawn(QEMU,
    [
        "-serial", "stdio",
        "-cdrom", path.join(__dirname, "/../../images/linux4.iso"),
        "-device", "virtio-9p-pci,fsdev=fs9p,mount_tag=host9p",
        "-fsdev", `local,id=fs9p,path=${share_dir_9p},security_model=none`,
        "-display", "none",
        "-cpu", "Westmere", // default doesn't support popcnt

        //"-monitor", "telnet:127.0.0.1:1235,server,nowait",
    ]
);

let qemu_output = "";
let ran_command = false;
let finished = false;

qemu.stdout.on("data", data => {
    process.stderr.write(data);
    qemu_output += data.toString().replace(/\r/, "");

    if(!ran_command && qemu_output.endsWith("~% "))
    {
        ran_command = true;
        qemu.stdin.write("chmod +x /mnt/test-i386\n");
        qemu.stdin.write("/mnt/test-i386 > /mnt/result\n");
        qemu.stdin.write("echo test fini''shed\n");
    }

    if(ran_command && !finished && qemu_output.includes("test finished"))
    {
        const result_file = path.join(share_dir_9p, "result");

        finished = true;
        console.error("Finished");
        process.stdout.write(fs.readFileSync(result_file));

        fs.unlinkSync(result_file);
        fs.unlinkSync(path.join(share_dir_9p, "test-i386"));
        fs.rmdirSync(share_dir_9p);

        qemu.kill();
    }
});

qemu.stderr.on("data", data => {
    process.stderr.write(data);
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/qemu/run.js                                                                        0000755 0000000 0000000 00000004112 00000000000 013140  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import { fileURLToPath } from "url";
import path from "path";
import fs from "fs";
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

process.on("unhandledRejection", exn => { throw exn; });

var test_executable = new Uint8Array(fs.readFileSync(__dirname + "/test-i386"));

var emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    cdrom: { url: __dirname + "/../../images/linux4.iso" },
    autostart: true,
    memory_size: 32 * 1024 * 1024,
    filesystem: {},
    disable_jit: +process.env.DISABLE_JIT,
    log_level: +process.env.LOG_LEVEL || 0,
});

emulator.bus.register("emulator-started", function()
{
    emulator.create_file("test-i386", test_executable);
});

var ran_command = false;
var line = "";

let outfile = process.stdout;
if(process.argv[2])
{
    outfile = await fs.promises.open(process.argv[2], "w");
}

emulator.add_listener("serial0-output-byte", async function(byte)
{
    var chr = String.fromCharCode(byte);
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    if(chr === "\n")
    {
        var new_line = line;
        console.error("Serial: %s", line);
        line = "";
    }
    else if(chr >= " " && chr <= "~")
    {
        line += chr;
    }

    if(!ran_command && line.endsWith("~% "))
    {
        ran_command = true;
        emulator.serial0_send("chmod +x /mnt/test-i386\n");
        emulator.serial0_send("/mnt/test-i386 > /mnt/result\n");
        emulator.serial0_send("echo test fini''shed\n");
    }

    if(new_line && new_line.includes("test finished"))
    {
        console.error("Done. Reading result ...");

        const data = await emulator.read_file("/result");
        console.error("Got result, writing to stdout");

        outfile.write(Buffer.from(data));
        emulator.destroy();
    }
});
                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/qemu/test-i386-code16.S                                                            0000644 0000000 0000000 00000002447 00000000000 014655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                               .code16
        .globl code16_start
        .globl code16_end

CS_SEG = 0xf

code16_start:

        .globl code16_func1

        /* basic test */
code16_func1 = . - code16_start
        mov $1, %eax
        data32 lret

/* test push/pop in 16 bit mode */
        .globl code16_func2
code16_func2 = . - code16_start
        xor %eax, %eax
        mov $0x12345678, %ebx
        movl %esp, %ecx
        push %bx
        subl %esp, %ecx
        pop %ax
        data32 lret

/* test various jmp opcodes */
        .globl code16_func3
code16_func3 = . - code16_start
        jmp 1f
        nop
1:
        mov $4, %eax
        mov $0x12345678, %ebx
        xor %bx, %bx
        jz 2f
        add $2, %ax
2:

        call myfunc

        lcall $CS_SEG, $(myfunc2 - code16_start)

        ljmp $CS_SEG, $(myjmp1 - code16_start)
myjmp1_next:

        cs lcall *myfunc2_addr - code16_start

        cs ljmp *myjmp2_addr - code16_start
myjmp2_next:

        data32 lret

myfunc2_addr:
        .short myfunc2 - code16_start
        .short CS_SEG

myjmp2_addr:
        .short myjmp2 - code16_start
        .short CS_SEG

myjmp1:
        add $8, %ax
        jmp myjmp1_next

myjmp2:
        add $16, %ax
        jmp myjmp2_next

myfunc:
        add $1, %ax
        ret

myfunc2:
        add $4, %ax
        lret


code16_end:
                                                                                                                                                                                                                         source/v64/tests/qemu/test-i386-muldiv.h                                                            0000644 0000000 0000000 00000004201 00000000000 015107  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
void glue(glue(test_, OP), b)(long op0, long op1)
{
    long res, s1, s0, flags;
    s0 = op0;
    s1 = op1;
    res = s0;
    flags = 0;
    asm ("push %4\n\t"
         "popf\n\t"
         stringify(OP)"b %b2\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=a" (res), "=g" (flags)
         : "q" (s1), "0" (res), "1" (flags));
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CC=%04lx\n",
           stringify(OP) "b", s0, s1, res, flags & CC_MASK);
}

void glue(glue(test_, OP), w)(long op0h, long op0, long op1)
{
    long res, s1, flags, resh;
    s1 = op1;
    resh = op0h;
    res = op0;
    flags = 0;
    asm ("push %5\n\t"
         "popf\n\t"
         stringify(OP) "w %w3\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=a" (res), "=g" (flags), "=d" (resh)
         : "q" (s1), "0" (res), "1" (flags), "2" (resh));
    printf("%-10s AH=" FMTLX " AL=" FMTLX " B=" FMTLX " RH=" FMTLX " RL=" FMTLX " CC=%04lx\n",
           stringify(OP) "w", op0h, op0, s1, resh, res, flags & CC_MASK);
}

void glue(glue(test_, OP), l)(long op0h, long op0, long op1)
{
    long res, s1, flags, resh;
    s1 = op1;
    resh = op0h;
    res = op0;
    flags = 0;
    asm ("push %5\n\t"
         "popf\n\t"
         stringify(OP) "l %k3\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=a" (res), "=g" (flags), "=d" (resh)
         : "q" (s1), "0" (res), "1" (flags), "2" (resh));
    printf("%-10s AH=" FMTLX " AL=" FMTLX " B=" FMTLX " RH=" FMTLX " RL=" FMTLX " CC=%04lx\n",
           stringify(OP) "l", op0h, op0, s1, resh, res, flags & CC_MASK);
}

#if defined(__x86_64__)
void glue(glue(test_, OP), q)(long op0h, long op0, long op1)
{
    long res, s1, flags, resh;
    s1 = op1;
    resh = op0h;
    res = op0;
    flags = 0;
    asm ("push %5\n\t"
         "popf\n\t"
         stringify(OP) "q %3\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=a" (res), "=g" (flags), "=d" (resh)
         : "q" (s1), "0" (res), "1" (flags), "2" (resh));
    printf("%-10s AH=" FMTLX " AL=" FMTLX " B=" FMTLX " RH=" FMTLX " RL=" FMTLX " CC=%04lx\n",
           stringify(OP) "q", op0h, op0, s1, resh, res, flags & CC_MASK);
}
#endif

#undef OP
                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/qemu/test-i386-shift.h                                                             0000644 0000000 0000000 00000012140 00000000000 014725  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#define exec_op glue(exec_, OP)
#define exec_opq glue(glue(exec_, OP), q)
#define exec_opl glue(glue(exec_, OP), l)
#define exec_opw glue(glue(exec_, OP), w)
#define exec_opb glue(glue(exec_, OP), b)

#ifndef OP_SHIFTD

#ifdef OP_NOBYTE
#define EXECSHIFT(size, rsize, res, s1, s2, flags) \
    asm ("push %4\n\t"\
         "popf\n\t"\
         stringify(OP) size " %" rsize "2, %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=g" (res), "=g" (flags)\
         : "r" (s1), "0" (res), "1" (flags));
#else
#define EXECSHIFT(size, rsize, res, s1, s2, flags) \
    asm ("push %4\n\t"\
         "popf\n\t"\
         stringify(OP) size " %%cl, %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=q" (res), "=g" (flags)\
         : "c" (s1), "0" (res), "1" (flags));
#endif

#if defined(__x86_64__)
void exec_opq(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("q", "", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "q", s0, s1, res, iflags, flags & CC_MASK);
}
#endif

void exec_opl(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("l", "k", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "l", s0, s1, res, iflags, flags & CC_MASK);
}

void exec_opw(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("w", "w", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "w", s0, s1, res, iflags, flags & CC_MASK);
}

#else
#define EXECSHIFT(size, rsize, res, s1, s2, flags) \
    asm ("push %4\n\t"\
         "popf\n\t"\
         stringify(OP) size " %%cl, %" rsize "5, %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=g" (res), "=g" (flags)\
         : "c" (s1), "0" (res), "1" (flags), "r" (s2));

#if defined(__x86_64__)
void exec_opq(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("q", "", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " C=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "q", s0, s2, s1, res, iflags, flags & CC_MASK);
}
#endif

void exec_opl(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("l", "k", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " C=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "l", s0, s2, s1, res, iflags, flags & CC_MASK);
}

void exec_opw(long s2, long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("w", "w", res, s1, s2, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " C=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "w", s0, s2, s1, res, iflags, flags & CC_MASK);
}

#endif

#ifndef OP_NOBYTE
void exec_opb(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECSHIFT("b", "b", res, s1, 0, flags);
    /* overflow is undefined if count != 1 */
    if (s1 != 1)
      flags &= ~CC_O;
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n",
           stringify(OP) "b", s0, s1, res, iflags, flags & CC_MASK);
}
#endif

void exec_op(long s2, long s0, long s1)
{
    s2 = i2l(s2);
    s0 = i2l(s0);
#if defined(__x86_64__)
    exec_opq(s2, s0, s1, 0);
#endif
    exec_opl(s2, s0, s1, 0);
#ifdef OP_SHIFTD
    exec_opw(s2, s0, s1, 0);
#else
    exec_opw(s2, s0, s1, 0);
#endif
#ifndef OP_NOBYTE
    exec_opb(s0, s1, 0);
#endif
#ifdef OP_CC
#if defined(__x86_64__)
    exec_opq(s2, s0, s1, CC_C);
#endif
    exec_opl(s2, s0, s1, CC_C);
    exec_opw(s2, s0, s1, CC_C);
    exec_opb(s0, s1, CC_C);
#endif
}

void glue(test_, OP)(void)
{
    int i, n;
#if defined(__x86_64__)
    n = 64;
#else
    n = 32;
#endif
    for(i = 0; i < n; i++)
        exec_op(0x21ad3d34, 0x12345678, i);
    for(i = 0; i < n; i++)
        exec_op(0x813f3421, 0x82345679, i);
    for(i = 0; i < n; i++)
        exec_op(0x21ad3d34, 0x82345679, i);
    for(i = 0; i < n; i++)
        exec_op(0x813f3421, 0x12345678, i);
    for(i = 0; i < n; i++)
        exec_op(0x80008481, 0x80008688, i);
    for(i = 0; i < n; i++)
        exec_op(0xffffffff, 0xffffffff, i);
    for(i = 0; i < n; i++)
        exec_op(0xfffe0080, 0xfffe0080, i);
}

void *glue(_test_, OP) __init_call = glue(test_, OP);

#undef OP
#undef OP_CC
#undef OP_SHIFTD
#undef OP_NOBYTE
#undef EXECSHIFT
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/qemu/test-i386-vm86.S                                                              0000644 0000000 0000000 00000003430 00000000000 014365  0                                                                                                    ustar 00                                                                                                                                                                                                                                                               .code16
        .globl vm86_code_start
        .globl vm86_code_end

#define GET_OFFSET(x) ((x) - vm86_code_start + 0x100)

vm86_code_start:
        movw $GET_OFFSET(hello_world), %dx
        movb $0x09, %ah
        int $0x21

        /* prepare int 0x90 vector */
        xorw %ax, %ax
        movw %ax, %es
        es movw $GET_OFFSET(int90_test), 0x90 * 4
        es movw %cs, 0x90 * 4 + 2

        /* launch int 0x90 */

        int $0x90

        /* test IF support */
        movw $GET_OFFSET(IF_msg), %dx
        movb $0x09, %ah
        int $0x21

        pushf
        popw %dx
        movb $0xff, %ah
        int $0x21

        cli
        pushf
        popw %dx
        movb $0xff, %ah
        int $0x21

        sti
        pushfl
        popl %edx
        movb $0xff, %ah
        int $0x21

#if 0
        movw $GET_OFFSET(IF_msg1), %dx
        movb $0x09, %ah
        int $0x21

        pushf
        movw %sp, %bx
        andw $~0x200, (%bx)
        popf
#else
        cli
#endif

        pushf
        popw %dx
        movb $0xff, %ah
        int $0x21

        pushfl
        movw %sp, %bx
        orw $0x200, (%bx)
        popfl

        pushfl
        popl %edx
        movb $0xff, %ah
        int $0x21

        movb $0x00, %ah
        int $0x21

int90_test:
        pushf
        pop %dx
        movb $0xff, %ah
        int $0x21

        movw %sp, %bx
        movw 4(%bx), %dx
        movb $0xff, %ah
        int $0x21

        movw $GET_OFFSET(int90_msg), %dx
        movb $0x09, %ah
        int $0x21
        iret

int90_msg:
        .string "INT90 started\n$"

hello_world:
        .string "Hello VM86 world\n$"

IF_msg:
        .string "VM86 IF test\n$"

IF_msg1:
        .string "If you see a diff here, your Linux kernel is buggy, please update to 2.4.20 kernel\n$"

vm86_code_end:
                                                                                                                                                                                                                                        source/v64/tests/qemu/test-i386.c                                                                   0000644 0000000 0000000 00000270622 00000000000 013620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 *  x86 CPU test
 *
 *  Copyright (c) 2003 Fabrice Bellard
 *
 *  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/>.
 */
#define _GNU_SOURCE
#include "compiler.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <signal.h>
#include <setjmp.h>
#include <errno.h>
#include <sys/ucontext.h>
#include <sys/mman.h>
#include <sys/user.h>

#if !defined(__x86_64__)
#define TEST_VM86
#define TEST_SEGS
#endif
//#define LINUX_VM86_IOPL_FIX
//#define TEST_P4_FLAGS

//#ifdef __SSE__
#if 1
#define TEST_SSE
#define TEST_CMOV  1
#define TEST_FCOMI 1
#else
#undef TEST_SSE
#define TEST_CMOV  1
#define TEST_FCOMI 1
#endif

#if defined(__x86_64__)
#define FMT64X "%016lx"
#define FMTLX "%016lx"
#define X86_64_ONLY(x) x
#else
#define FMT64X "%016" PRIx64
#define FMTLX "%08lx"
#define X86_64_ONLY(x)
#endif

#ifdef TEST_VM86
#include <asm/vm86.h>
#endif

#define xglue(x, y) x ## y
#define glue(x, y) xglue(x, y)
#define stringify(s)	tostring(s)
#define tostring(s)	#s
#define UNUSED(s)	(void)(s)

#define CC_C   	0x0001
#define CC_P 	0x0004
#define CC_A	0x0010
#define CC_Z	0x0040
#define CC_S    0x0080
#define CC_O    0x0800

#define __init_call	__attribute__ ((unused,__section__ ("initcall")))

#define CC_MASK (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A)

#if defined(__x86_64__)
static inline long i2l(long v)
{
    return v | ((v ^ 0xabcd) << 32);
}
#else
static inline long i2l(long v)
{
    return v;
}
#endif

#define OP add
#include "test-i386.h"

#define OP sub
#include "test-i386.h"

#define OP xor
#include "test-i386.h"

#define OP and
#include "test-i386.h"

#define OP or
#include "test-i386.h"

#define OP cmp
#include "test-i386.h"

#define OP adc
#define OP_CC
#include "test-i386.h"

#define OP sbb
#define OP_CC
#include "test-i386.h"

#define OP inc
#define OP_CC
#define OP1
#include "test-i386.h"

#define OP dec
#define OP_CC
#define OP1
#include "test-i386.h"

#define OP neg
#define OP_CC
#define OP1
#include "test-i386.h"

#define OP not
#define OP_CC
#define OP1
#include "test-i386.h"

#undef CC_MASK
#define CC_MASK (CC_C | CC_P | CC_Z | CC_S | CC_O)

#define OP shl
#include "test-i386-shift.h"

#define OP shr
#include "test-i386-shift.h"

#define OP sar
#include "test-i386-shift.h"

#define OP rol
#include "test-i386-shift.h"

#define OP ror
#include "test-i386-shift.h"

#define OP rcr
#define OP_CC
#include "test-i386-shift.h"

#define OP rcl
#define OP_CC
#include "test-i386-shift.h"

#define OP shld
#define OP_SHIFTD
#define OP_NOBYTE
#include "test-i386-shift.h"

#define OP shrd
#define OP_SHIFTD
#define OP_NOBYTE
#include "test-i386-shift.h"

/* XXX: should be more precise ? */
#undef CC_MASK
#define CC_MASK (CC_C)

#define OP bt
#define OP_NOBYTE
#include "test-i386-shift.h"

#define OP bts
#define OP_NOBYTE
#include "test-i386-shift.h"

#define OP btr
#define OP_NOBYTE
#include "test-i386-shift.h"

#define OP btc
#define OP_NOBYTE
#include "test-i386-shift.h"

/* lea test (modrm support) */
#define TEST_LEAQ(STR)\
{\
    asm("lea " STR ", %0"\
        : "=r" (res)\
        : "a" (eax), "b" (ebx), "c" (ecx), "d" (edx), "S" (esi), "D" (edi));\
    printf("lea %s = " FMTLX "\n", STR, res);\
}

#define TEST_LEA(STR)\
{\
    asm("lea " STR ", %0"\
        : "=r" (res)\
        : "a" (eax), "b" (ebx), "c" (ecx), "d" (edx), "S" (esi), "D" (edi));\
    printf("lea %s = " FMTLX "\n", STR, res);\
}

#define TEST_LEA16(STR)\
{\
    asm(".code16 ; .byte 0x67 ; leal " STR ", %0 ; .code32"\
        : "=r" (res)\
        : "a" (eax), "b" (ebx), "c" (ecx), "d" (edx), "S" (esi), "D" (edi));\
    printf("lea %s = %08lx\n", STR, res);\
}


void test_lea(void)
{
    long eax, ebx, ecx, edx, esi, edi, res;
    eax = i2l(0x0001);
    ebx = i2l(0x0002);
    ecx = i2l(0x0004);
    edx = i2l(0x0008);
    esi = i2l(0x0010);
    edi = i2l(0x0020);

    TEST_LEA("0x4000");

    TEST_LEA("(%%eax)");
    TEST_LEA("(%%ebx)");
    TEST_LEA("(%%ecx)");
    TEST_LEA("(%%edx)");
    TEST_LEA("(%%esi)");
    TEST_LEA("(%%edi)");

    TEST_LEA("0x40(%%eax)");
    TEST_LEA("0x40(%%ebx)");
    TEST_LEA("0x40(%%ecx)");
    TEST_LEA("0x40(%%edx)");
    TEST_LEA("0x40(%%esi)");
    TEST_LEA("0x40(%%edi)");

    TEST_LEA("0x4000(%%eax)");
    TEST_LEA("0x4000(%%ebx)");
    TEST_LEA("0x4000(%%ecx)");
    TEST_LEA("0x4000(%%edx)");
    TEST_LEA("0x4000(%%esi)");
    TEST_LEA("0x4000(%%edi)");

    TEST_LEA("(%%eax, %%ecx)");
    TEST_LEA("(%%ebx, %%edx)");
    TEST_LEA("(%%ecx, %%ecx)");
    TEST_LEA("(%%edx, %%ecx)");
    TEST_LEA("(%%esi, %%ecx)");
    TEST_LEA("(%%edi, %%ecx)");

    TEST_LEA("0x40(%%eax, %%ecx)");
    TEST_LEA("0x4000(%%ebx, %%edx)");

    TEST_LEA("(%%ecx, %%ecx, 2)");
    TEST_LEA("(%%edx, %%ecx, 4)");
    TEST_LEA("(%%esi, %%ecx, 8)");

    TEST_LEA("(,%%eax, 2)");
    TEST_LEA("(,%%ebx, 4)");
    TEST_LEA("(,%%ecx, 8)");

    TEST_LEA("0x40(,%%eax, 2)");
    TEST_LEA("0x40(,%%ebx, 4)");
    TEST_LEA("0x40(,%%ecx, 8)");


    TEST_LEA("-10(%%ecx, %%ecx, 2)");
    TEST_LEA("-10(%%edx, %%ecx, 4)");
    TEST_LEA("-10(%%esi, %%ecx, 8)");

    TEST_LEA("0x4000(%%ecx, %%ecx, 2)");
    TEST_LEA("0x4000(%%edx, %%ecx, 4)");
    TEST_LEA("0x4000(%%esi, %%ecx, 8)");

#if defined(__x86_64__)
    TEST_LEAQ("0x4000");
    TEST_LEAQ("0x4000(%%rip)");

    TEST_LEAQ("(%%rax)");
    TEST_LEAQ("(%%rbx)");
    TEST_LEAQ("(%%rcx)");
    TEST_LEAQ("(%%rdx)");
    TEST_LEAQ("(%%rsi)");
    TEST_LEAQ("(%%rdi)");

    TEST_LEAQ("0x40(%%rax)");
    TEST_LEAQ("0x40(%%rbx)");
    TEST_LEAQ("0x40(%%rcx)");
    TEST_LEAQ("0x40(%%rdx)");
    TEST_LEAQ("0x40(%%rsi)");
    TEST_LEAQ("0x40(%%rdi)");

    TEST_LEAQ("0x4000(%%rax)");
    TEST_LEAQ("0x4000(%%rbx)");
    TEST_LEAQ("0x4000(%%rcx)");
    TEST_LEAQ("0x4000(%%rdx)");
    TEST_LEAQ("0x4000(%%rsi)");
    TEST_LEAQ("0x4000(%%rdi)");

    TEST_LEAQ("(%%rax, %%rcx)");
    TEST_LEAQ("(%%rbx, %%rdx)");
    TEST_LEAQ("(%%rcx, %%rcx)");
    TEST_LEAQ("(%%rdx, %%rcx)");
    TEST_LEAQ("(%%rsi, %%rcx)");
    TEST_LEAQ("(%%rdi, %%rcx)");

    TEST_LEAQ("0x40(%%rax, %%rcx)");
    TEST_LEAQ("0x4000(%%rbx, %%rdx)");

    TEST_LEAQ("(%%rcx, %%rcx, 2)");
    TEST_LEAQ("(%%rdx, %%rcx, 4)");
    TEST_LEAQ("(%%rsi, %%rcx, 8)");

    TEST_LEAQ("(,%%rax, 2)");
    TEST_LEAQ("(,%%rbx, 4)");
    TEST_LEAQ("(,%%rcx, 8)");

    TEST_LEAQ("0x40(,%%rax, 2)");
    TEST_LEAQ("0x40(,%%rbx, 4)");
    TEST_LEAQ("0x40(,%%rcx, 8)");


    TEST_LEAQ("-10(%%rcx, %%rcx, 2)");
    TEST_LEAQ("-10(%%rdx, %%rcx, 4)");
    TEST_LEAQ("-10(%%rsi, %%rcx, 8)");

    TEST_LEAQ("0x4000(%%rcx, %%rcx, 2)");
    TEST_LEAQ("0x4000(%%rdx, %%rcx, 4)");
    TEST_LEAQ("0x4000(%%rsi, %%rcx, 8)");
#else
    /* limited 16 bit addressing test */
    TEST_LEA16("0x4000");
    TEST_LEA16("(%%bx)");
    TEST_LEA16("(%%si)");
    TEST_LEA16("(%%di)");
    TEST_LEA16("0x40(%%bx)");
    TEST_LEA16("0x40(%%si)");
    TEST_LEA16("0x40(%%di)");
    TEST_LEA16("0x4000(%%bx)");
    TEST_LEA16("0x4000(%%si)");
    TEST_LEA16("(%%bx,%%si)");
    TEST_LEA16("(%%bx,%%di)");
    TEST_LEA16("0x40(%%bx,%%si)");
    TEST_LEA16("0x40(%%bx,%%di)");
    TEST_LEA16("0x4000(%%bx,%%si)");
    TEST_LEA16("0x4000(%%bx,%%di)");
#endif
}

#define TEST_JCC(JCC, v1, v2)\
{\
    int res;\
    asm("movl $1, %0\n\t"\
        "cmpl %2, %1\n\t"\
        "j" JCC " 1f\n\t"\
        "movl $0, %0\n\t"\
        "1:\n\t"\
        : "=r" (res)\
        : "r" (v1), "r" (v2));\
    printf("%-10s %d\n", "j" JCC, res);\
\
    asm("movl $0, %0\n\t"\
        "cmpl %2, %1\n\t"\
        "set" JCC " %b0\n\t"\
        : "=r" (res)\
        : "r" (v1), "r" (v2));\
    printf("%-10s %d\n", "set" JCC, res);\
 if (TEST_CMOV) {\
    long val = i2l(1);\
    long res = i2l(0x12345678);\
X86_64_ONLY(\
    asm("cmpl %2, %1\n\t"\
        "cmov" JCC "q %3, %0\n\t"\
        : "=r" (res)\
        : "r" (v1), "r" (v2), "m" (val), "0" (res));\
        printf("%-10s R=" FMTLX "\n", "cmov" JCC "q", res);)\
    asm("cmpl %2, %1\n\t"\
        "cmov" JCC "l %k3, %k0\n\t"\
        : "=r" (res)\
        : "r" (v1), "r" (v2), "m" (val), "0" (res));\
        printf("%-10s R=" FMTLX "\n", "cmov" JCC "l", res);\
    asm("cmpl %2, %1\n\t"\
        "cmov" JCC "w %w3, %w0\n\t"\
        : "=r" (res)\
        : "r" (v1), "r" (v2), "r" (1), "0" (res));\
        printf("%-10s R=" FMTLX "\n", "cmov" JCC "w", res);\
 } \
}

/* various jump tests */
void test_jcc(void)
{
    TEST_JCC("ne", 1, 1);
    TEST_JCC("ne", 1, 0);

    TEST_JCC("e", 1, 1);
    TEST_JCC("e", 1, 0);

    TEST_JCC("l", 1, 1);
    TEST_JCC("l", 1, 0);
    TEST_JCC("l", 1, -1);

    TEST_JCC("le", 1, 1);
    TEST_JCC("le", 1, 0);
    TEST_JCC("le", 1, -1);

    TEST_JCC("ge", 1, 1);
    TEST_JCC("ge", 1, 0);
    TEST_JCC("ge", -1, 1);

    TEST_JCC("g", 1, 1);
    TEST_JCC("g", 1, 0);
    TEST_JCC("g", 1, -1);

    TEST_JCC("b", 1, 1);
    TEST_JCC("b", 1, 0);
    TEST_JCC("b", 1, -1);

    TEST_JCC("be", 1, 1);
    TEST_JCC("be", 1, 0);
    TEST_JCC("be", 1, -1);

    TEST_JCC("ae", 1, 1);
    TEST_JCC("ae", 1, 0);
    TEST_JCC("ae", 1, -1);

    TEST_JCC("a", 1, 1);
    TEST_JCC("a", 1, 0);
    TEST_JCC("a", 1, -1);


    TEST_JCC("p", 1, 1);
    TEST_JCC("p", 1, 0);

    TEST_JCC("np", 1, 1);
    TEST_JCC("np", 1, 0);

    TEST_JCC("o", 0x7fffffff, 0);
    TEST_JCC("o", 0x7fffffff, -1);

    TEST_JCC("no", 0x7fffffff, 0);
    TEST_JCC("no", 0x7fffffff, -1);

    TEST_JCC("s", 0, 1);
    TEST_JCC("s", 0, -1);
    TEST_JCC("s", 0, 0);

    TEST_JCC("ns", 0, 1);
    TEST_JCC("ns", 0, -1);
    TEST_JCC("ns", 0, 0);
}

#define TEST_LOOP(insn) \
{\
    for(i = 0; i < sizeof(ecx_vals) / sizeof(long); i++) {\
        ecx = ecx_vals[i];\
        for(zf = 0; zf < 2; zf++) {\
    asm("test %2, %2\n\t"\
        "movl $1, %0\n\t"\
          insn " 1f\n\t" \
        "movl $0, %0\n\t"\
        "1:\n\t"\
        : "=a" (res)\
        : "c" (ecx), "b" (!zf)); \
    printf("%-10s ECX=" FMTLX " ZF=%ld r=%d\n", insn, ecx, zf, res);      \
        }\
   }\
}

void test_loop(void)
{
    long ecx, zf;
    const long ecx_vals[] = {
        0,
        1,
        0x10000,
        0x10001,
#if defined(__x86_64__)
        0x100000000L,
        0x100000001L,
#endif
    };
    int i, res;

#if !defined(__x86_64__)
    TEST_LOOP("jcxz");
    TEST_LOOP("loopw");
    TEST_LOOP("loopzw");
    TEST_LOOP("loopnzw");
#endif

    TEST_LOOP("jecxz");
    TEST_LOOP("loopl");
    TEST_LOOP("loopzl");
    TEST_LOOP("loopnzl");
}

#undef CC_MASK
#ifdef TEST_P4_FLAGS
#define CC_MASK (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A)
#else
#define CC_MASK (CC_O | CC_C)
#endif

#define OP mul
#include "test-i386-muldiv.h"

#define OP imul
#include "test-i386-muldiv.h"

void test_imulw2(long op0, long op1)
{
    long res, s1, s0, flags;
    s0 = op0;
    s1 = op1;
    res = s0;
    flags = 0;
    asm volatile ("push %4\n\t"
         "popf\n\t"
         "imulw %w2, %w0\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=q" (res), "=g" (flags)
         : "q" (s1), "0" (res), "1" (flags));
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CC=%04lx\n",
           "imulw", s0, s1, res, flags & CC_MASK);
}

void test_imull2(long op0, long op1)
{
    long res, s1, s0, flags;
    s0 = op0;
    s1 = op1;
    res = s0;
    flags = 0;
    asm volatile ("push %4\n\t"
         "popf\n\t"
         "imull %k2, %k0\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=q" (res), "=g" (flags)
         : "q" (s1), "0" (res), "1" (flags));
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CC=%04lx\n",
           "imull", s0, s1, res, flags & CC_MASK);
}

#if defined(__x86_64__)
void test_imulq2(long op0, long op1)
{
    long res, s1, s0, flags;
    s0 = op0;
    s1 = op1;
    res = s0;
    flags = 0;
    asm volatile ("push %4\n\t"
         "popf\n\t"
         "imulq %2, %0\n\t"
         "pushf\n\t"
         "pop %1\n\t"
         : "=q" (res), "=g" (flags)
         : "q" (s1), "0" (res), "1" (flags));
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CC=%04lx\n",
           "imulq", s0, s1, res, flags & CC_MASK);
}
#endif

#define TEST_IMUL_IM(size, rsize, op0, op1)\
{\
    long res, flags, s1;\
    flags = 0;\
    res = 0;\
    s1 = op1;\
    asm volatile ("push %3\n\t"\
         "popf\n\t"\
         "imul" size " $" #op0 ", %" rsize "2, %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=r" (res), "=g" (flags)\
         : "r" (s1), "1" (flags), "0" (res));\
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CC=%04lx\n",\
           "imul" size " im", (long)op0, (long)op1, res, flags & CC_MASK);\
}


#undef CC_MASK
#define CC_MASK (0)

#define OP div
#include "test-i386-muldiv.h"

#define OP idiv
#include "test-i386-muldiv.h"

void test_mul(void)
{
    test_imulb(0x1234561d, 4);
    test_imulb(3, -4);
    test_imulb(0x80, 0x80);
    test_imulb(0x10, 0x10);

    test_imulw(0, 0x1234001d, 45);
    test_imulw(0, 23, -45);
    test_imulw(0, 0x8000, 0x8000);
    test_imulw(0, 0x100, 0x100);

    test_imull(0, 0x1234001d, 45);
    test_imull(0, 23, -45);
    test_imull(0, 0x80000000, 0x80000000);
    test_imull(0, 0x10000, 0x10000);

    test_mulb(0x1234561d, 4);
    test_mulb(3, -4);
    test_mulb(0x80, 0x80);
    test_mulb(0x10, 0x10);

    test_mulw(0, 0x1234001d, 45);
    test_mulw(0, 23, -45);
    test_mulw(0, 0x8000, 0x8000);
    test_mulw(0, 0x100, 0x100);

    test_mull(0, 0x1234001d, 45);
    test_mull(0, 23, -45);
    test_mull(0, 0x80000000, 0x80000000);
    test_mull(0, 0x10000, 0x10000);

    test_mull(0, 0xffffffff, 0xffffffff);
    test_mull(0, 0xfffffffe, 0xffffffff);
    test_mull(0, 0xffffffff, 0xfffffffe);

    test_mull(0, 0xffffffff, 0);
    test_mull(0, 0xffffffff, 1);
    test_mull(0, 0xffffffff, 2);
    test_mull(0, 0xffffffff, 3);

    test_mull(0, 0, 0xffffffff);
    test_mull(0, 1, 0xffffffff);
    test_mull(0, 2, 0xffffffff);
    test_mull(0, 3, 0xffffffff);


    test_imulw2(0x1234001d, 45);
    test_imulw2(23, -45);
    test_imulw2(0x8000, 0x8000);
    test_imulw2(0x100, 0x100);

    test_imull2(0x1234001d, 45);
    test_imull2(23, -45);
    test_imull2(0x80000000, 0x80000000);
    test_imull2(0x10000, 0x10000);

    TEST_IMUL_IM("w", "w", 45, 0x1234);
    TEST_IMUL_IM("w", "w", -45, 23);
    TEST_IMUL_IM("w", "w", 0x8000, 0x80000000);
    TEST_IMUL_IM("w", "w", 0x7fff, 0x1000);

    TEST_IMUL_IM("l", "k", 45, 0x1234);
    TEST_IMUL_IM("l", "k", -45, 23);
    TEST_IMUL_IM("l", "k", 0x8000, 0x80000000);
    TEST_IMUL_IM("l", "k", 0x7fff, 0x1000);

    test_idivb(0x12341678, 0x127e);
    test_idivb(0x43210123, -5);
    test_idivb(0x12340004, -1);
    test_idivb(-20, 3);
    test_idivb(20, -3);
    test_idivb(-20, -3);

    test_idivw(0, 0x12345678, 12347);
    test_idivw(0, -23223, -45);
    test_idivw(0, 0x12348000, -1);
    test_idivw(0x12343, 0x12345678, 0x81238567);
    test_idivw(-20, 0, 300);
    test_idivw(20,  0, -300);
    test_idivw(-20, 0, -300);

    test_idivl(0, 0x12345678, 12347);
    test_idivl(0, -233223, -45);
    test_idivl(0, 0x80000000, -1);
    test_idivl(0x12343, 0x12345678, 0x81234567);

    test_divb(0x12341678, 0x127e);
    test_divb(0x43210123, -5);
    test_divb(0x12340004, -1);

    test_divw(0, 0x12345678, 12347);
    test_divw(0, -23223, -45);
    test_divw(0, 0x12348000, -1);
    test_divw(0x12343, 0x12345678, 0x81238567);

    test_divl(0, 0x12345678, 12347);
    test_divl(0, -233223, -45);
    test_divl(0, 0x80000000, -1);
    test_divl(0x12343, 0x12345678, 0x81234567);

    test_divl(0xfffffffe, 0xffffffff, 0xffffffff);
    test_divl(0xffffffe, 0xffffffff, 0xfffffff);
    test_divl(0xfffffe, 0xffffffff, 0xffffff);
    test_divl(0xffffe, 0xffffffff, 0xfffff);
    test_divl(0xfffe, 0xffffffff, 0xffff);
    test_divl(0xffe, 0xffffffff, 0xfff);
    test_divl(0xfe, 0xffffffff, 0xff);
    test_divl(0xe, 0xffffffff, 0xf);

    test_divl(0x7ffffffe, 0xffffffff, 0x7fffffff);
    test_divl(0x7fffffe, 0xffffffff, 0x7ffffff);
    test_divl(0x7ffffe, 0xffffffff, 0x7fffff);
    test_divl(0x7fffe, 0xffffffff, 0x7ffff);
    test_divl(0x7ffe, 0xffffffff, 0x7fff);
    test_divl(0x7fe, 0xffffffff, 0x7ff);
    test_divl(0x7e, 0xffffffff, 0x7f);

    test_divl(0x3ffffffe, 0xffffffff, 0x3fffffff);
    test_divl(0x3fffffe, 0xffffffff, 0x3ffffff);
    test_divl(0x3ffffe, 0xffffffff, 0x3fffff);
    test_divl(0x3fffe, 0xffffffff, 0x3ffff);
    test_divl(0x3ffe, 0xffffffff, 0x3fff);
    test_divl(0x3fe, 0xffffffff, 0x3ff);
    test_divl(0x3e, 0xffffffff, 0x3f);

    test_divl(0x1ffffffe, 0xffffffff, 0x1fffffff);
    test_divl(0x1fffffe, 0xffffffff, 0x1ffffff);
    test_divl(0x1ffffe, 0xffffffff, 0x1fffff);
    test_divl(0x1fffe, 0xffffffff, 0x1ffff);
    test_divl(0x1ffe, 0xffffffff, 0x1fff);
    test_divl(0x1fe, 0xffffffff, 0x1ff);
    test_divl(0x1e, 0xffffffff, 0x1f);

    int i;
    for(i = 0; i < 16; i++)
    {
        test_divl(0, 0xfffffffe, i + 1);
        test_divl(0, 0xffffffff, i + 1);
        test_divl(1, 0xfffffffe, i + 2);
        test_divl(1, 0xffffffff, i + 2);
        test_divl(2, 0xfffffffe, i + 3);
        test_divl(2, 0xffffffff, i + 3);
        test_divl(3, 0xfffffffe, i + 4);
        test_divl(3, 0xffffffff, i + 4);
        test_divl(4, 0xfffffffe, i + 5);
        test_divl(4, 0xffffffff, i + 5);

        test_divl(0xfffffffd, 0x00000000 + i, 0xfffffffe);
        test_divl(0xfffffffd, 0xfffffff0 + i, 0xfffffffe);

        test_divl(0xfffffffe, 0x00000000 + i, 0xffffffff);
        test_divl(0xfffffffe, 0xfffffff0 + i, 0xffffffff);

        test_divl(0, i, 0xfffffffa);
        test_divl(0, i, 0xfffffffb);
        test_divl(0, i, 0xfffffffc);
        test_divl(0, i, 0xfffffffd);
        test_divl(0, i, 0xfffffffe);
        test_divl(0, i, 0xffffffff);

        test_idivl(0, 1,  i + 1);
        test_idivl(-1, -1, i + 1);
        test_idivl(0, 1,  -(i + 1));
        test_idivl(-1, -1, -(i + 1));

        test_idivl(0,  0x7fffffff, i + 1);
        test_idivl(-1, 0x80000001, i + 1);
        test_idivl(0,  0x7fffffff, -(i + 1));
        test_idivl(-1, 0x80000001, -(i + 1));
    }

#if defined(__x86_64__)
    test_imulq(0, 0x1234001d1234001d, 45);
    test_imulq(0, 23, -45);
    test_imulq(0, 0x8000000000000000, 0x8000000000000000);
    test_imulq(0, 0x100000000, 0x100000000);

    test_mulq(0, 0x1234001d1234001d, 45);
    test_mulq(0, 23, -45);
    test_mulq(0, 0x8000000000000000, 0x8000000000000000);
    test_mulq(0, 0x100000000, 0x100000000);

    test_imulq2(0x1234001d1234001d, 45);
    test_imulq2(23, -45);
    test_imulq2(0x8000000000000000, 0x8000000000000000);
    test_imulq2(0x100000000, 0x100000000);

    TEST_IMUL_IM("q", "", 45, 0x12341234);
    TEST_IMUL_IM("q", "", -45, 23);
    TEST_IMUL_IM("q", "", 0x8000, 0x8000000000000000);
    TEST_IMUL_IM("q", "", 0x7fff, 0x10000000);

    test_idivq(0, 0x12345678abcdef, 12347);
    test_idivq(0, -233223, -45);
    test_idivq(0, 0x8000000000000000, -1);
    test_idivq(0x12343, 0x12345678, 0x81234567);

    test_divq(0, 0x12345678abcdef, 12347);
    test_divq(0, -233223, -45);
    test_divq(0, 0x8000000000000000, -1);
    test_divq(0x12343, 0x12345678, 0x81234567);
#endif
}

#define TEST_BSX(op, size, op0)\
{\
    long res, val, resz;\
    val = op0;\
    asm("xor %1, %1\n"\
        "mov $0x12345678, %0\n"\
        #op " %" size "2, %" size "0 ; setz %b1" \
        : "=&r" (res), "=&q" (resz)\
        : "r" (val));\
    printf("%-10s A=" FMTLX " R=" FMTLX " %ld\n", #op, val, res, resz);\
}

void test_bsx(void)
{
    TEST_BSX(bsrw, "w", 0);
    TEST_BSX(bsrw, "w", 0x12340128);
    TEST_BSX(bsrw, "w", 0xffffffff);
    TEST_BSX(bsrw, "w", 0xffff7fff);

    TEST_BSX(bsfw, "w", 0);
    TEST_BSX(bsfw, "w", 0x12340128);
    TEST_BSX(bsfw, "w", 0xffffffff);
    TEST_BSX(bsfw, "w", 0xfffffff7);

    TEST_BSX(bsrl, "k", 0);
    TEST_BSX(bsrl, "k", 0x00340128);
    TEST_BSX(bsrl, "k", 0xffffffff);
    TEST_BSX(bsrl, "k", 0x7fffffff);

    TEST_BSX(bsfl, "k", 0);
    TEST_BSX(bsfl, "k", 0x00340128);
    TEST_BSX(bsfl, "k", 0xffffffff);
    TEST_BSX(bsfl, "k", 0xfffffff7);

#if defined(__x86_64__)
    TEST_BSX(bsrq, "", 0);
    TEST_BSX(bsrq, "", 0x003401281234);
    TEST_BSX(bsfq, "", 0);
    TEST_BSX(bsfq, "", 0x003401281234);
#endif
}

#define TEST_POPCNT(size, op0)\
{\
    long res, val, resz;\
    val = op0;\
    asm("xor %1, %1\n"\
        "mov $0x12345678, %0\n"\
        "popcnt %" size "2, %" size "0 ; pushf; pop %1;" \
        : "=&r" (res), "=&q" (resz)\
        : "r" (val));\
    printf("popcnt A=" FMTLX " R=" FMTLX " flags=%lx\n", val, res, resz);\
}

void test_popcnt(void)
{
    TEST_POPCNT("w", 0);
}

/**********************************************/

union float64u {
    double d;
    uint64_t l;
};

union float64u q_nan = { .l = 0xFFF8000000000000LL };
union float64u s_nan = { .l = 0xFFF0000000000000LL };

void test_fops(double a, double b)
{
    int ib = (int)b;
    int dest = 0;

    printf("a=%f b=%f a+b=%f\n", a, b, a + b);
    printf("a=%f b=%f a-b=%f\n", a, b, a - b);
    printf("a=%f b=%f a*b=%f\n", a, b, a * b);
    printf("a=%f b=%f a/b=%f\n", a, b, a / b);
    printf("a=%f b=%f =%f\n", a, b, a + a + a + 3 * b / a * (a * a * a / b / b / (a + 1.0) - 3.5 + a * b / (3.7 * a / (a - b * b) + 6.5 * a / (b * b * a / -b - a * b) + 5.5 * (b - a))));
    //printf("a=%f b=%f fmod(a, b)=%f\n", a, b, fmod(a, b)); // difference in sign bit on zero and nan
    printf("a=%f fma(a,b,a)=%f\n", a, fma(a, b, a));
    printf("a=%f fdim(a,b)=%f\n", a, fdim(a, b));
    printf("a=%f copysign(a,b)=%f\n", a, copysign(a, b));
    printf("a=%f sqrt(a)=%f\n", a, sqrt(a));
    printf("a=%f sin(a)=%f\n", a, sin(a));
    printf("a=%f cos(a)=%f\n", a, cos(a));
    printf("a=%f tan(a)=%f\n", a, tan(a));
    if(a >= 0)
    {
        printf("a=%f log(a)=%f\n", a, log(a));
        printf("a=%f log10(a)=%f\n", a, log10(a));
        printf("a=%f log1p(a)=%f\n", a, log1p(a));
        printf("a=%f log2(a)=%f\n", a, log2(a));
    }
    printf("a=%f logb(a)=%f\n", a, logb(a));
    printf("a=%f ilogb(a)=%d\n", a, ilogb(a));
    printf("a=%f exp(a)=%f\n", a, exp(a));
    printf("a=%f exp2(a)=%f\n", a, exp2(a));
    printf("a=%f frexp(a)=%f, %d\n", a, frexp(a, &dest), dest);
    printf("a=%f ldexp(a,b)=%f\n", a, ldexp(a, ib));
    printf("a=%f scalbn(a,b)=%f\n", a, scalbn(a, ib));
    printf("a=%f sinh(a)=%f\n", a, sinh(a));
    printf("a=%f cosh(a)=%f\n", a, cosh(a));
    printf("a=%f tanh(a)=%f\n", a, tanh(a));
    printf("a=%f fabs(a)=%f\n", a, fabs(a));
    printf("a=%f pow(a,b)=%f\n", a, pow(a,b));
    printf("a=%f b=%f atan2(a, b)=%f\n", a, b, atan2(a, b));
    /* just to test some op combining */
    printf("a=%f asin(sin(a))=%f\n", a, asin(sin(a)));
    printf("a=%f acos(cos(a))=%f\n", a, acos(cos(a)));
    printf("a=%f atan(tan(a))=%f\n", a, atan(tan(a)));

}

void fpu_clear_exceptions(void)
{
    struct QEMU_PACKED {
        uint16_t fpuc;
        uint16_t dummy1;
        uint16_t fpus;
        uint16_t dummy2;
        uint16_t fptag;
        uint16_t dummy3;
        uint32_t ignored[4];
        long double fpregs[8];
    } float_env32;

    asm volatile ("fnstenv %0\n" : "=m" (float_env32));
    float_env32.fpus &= ~0x7f;
    asm volatile ("fldenv %0\n" : : "m" (float_env32));
}

/* XXX: display exception bits when supported */
#define FPUS_EMASK 0x007f

void test_fcmp(double a, double b)
{
    long eflags, fpus;

    fpu_clear_exceptions();
    asm("fcom %2\n"
        "fstsw %%ax\n"
        : "=a" (fpus)
        : "t" (a), "u" (b));
    printf("fcom(%f %f)=%04lx\n",
           a, b, fpus & (0x4500 | FPUS_EMASK & ~1));
    fpu_clear_exceptions();
    asm("fucom %2\n"
        "fstsw %%ax\n"
        : "=a" (fpus)
        : "t" (a), "u" (b));
    printf("fucom(%f %f)=%04lx\n",
           a, b, fpus & (0x4500 | FPUS_EMASK));
    if (TEST_FCOMI) {
        /* test f(u)comi instruction */
        fpu_clear_exceptions();
        asm("fcomi %3, %2\n"
            "fstsw %%ax\n"
            "pushf\n"
            "pop %0\n"
            : "=r" (eflags), "=a" (fpus)
            : "t" (a), "u" (b));
        printf("fcomi(%f %f)=%04lx %02lx\n",
               a, b, fpus & FPUS_EMASK & ~1, eflags & (CC_Z | CC_P | CC_C));
        fpu_clear_exceptions();
        asm("fucomi %3, %2\n"
            "fstsw %%ax\n"
            "pushf\n"
            "pop %0\n"
            : "=r" (eflags), "=a" (fpus)
            : "t" (a), "u" (b));
        printf("fucomi(%f %f)=%04lx %02lx\n",
               a, b, fpus & FPUS_EMASK, eflags & (CC_Z | CC_P | CC_C));
    }
    fpu_clear_exceptions();
    asm volatile("fxam\n"
                 "fstsw %%ax\n"
                 : "=a" (fpus)
                 : "t" (a));
    printf("fxam(%f)=%04lx\n", a, fpus & 0x4700);
    fpu_clear_exceptions();
}

void test_fcvt(double a)
{
    float fa;
    long double la;
    int16_t fpuc;
    int i;
    int64_t lla;
    int ia;
    int16_t wa;
    double ra;

    fa = a;
    la = a;
    printf("(float)%f = %f\n", a, fa);
    printf("(long double)%f = %Lf\n", a, la);
    printf("a=" FMT64X "\n", *(uint64_t *)&a);
    printf("la=" FMT64X " %04x\n", *(uint64_t *)&la,
           *(unsigned short *)((char *)(&la) + 8));

    /* test all roundings */
    asm volatile ("fstcw %0" : "=m" (fpuc));
    for(i=0;i<4;i++) {
        uint16_t val16;
        val16 = (fpuc & ~0x0c00) | (i << 10);
        asm volatile ("fldcw %0" : : "m" (val16));
        asm volatile ("fist %0" : "=m" (wa) : "t" (a));
        asm volatile ("fistl %0" : "=m" (ia) : "t" (a));
        asm volatile ("fistpll %0" : "=m" (lla) : "t" (a) : "st");
        asm volatile ("frndint ; fstl %0" : "=m" (ra) : "t" (a));
        asm volatile ("fldcw %0" : : "m" (fpuc));
        printf("(short)a = %d\n", wa);
        printf("(int)a = %d\n", ia);
        printf("(int64_t)a = " FMT64X "\n", lla);
        printf("rint(a) = %f\n", ra);
    }
}

#define TEST(N) \
    asm("fld" #N : "=t" (a)); \
    printf("fld" #N "= %f\n", a);

void test_fconst(void)
{
    double a;
    TEST(1);
    TEST(l2t);
    TEST(l2e);
    TEST(pi);
    TEST(lg2);
    TEST(ln2);
    TEST(z);
}

void test_fbcd(double a)
{
    unsigned short bcd[5];
    double b;

    asm("fbstp %0" : "=m" (bcd[0]) : "t" (a) : "st");
    //asm("fbld %1" : "=t" (b) : "m" (bcd[0]));
    printf("a=%f bcd=%04x%04x%04x%04x%04x b=%f\n",
           a, bcd[4], bcd[3], bcd[2], bcd[1], bcd[0], b);
}

#define TEST_ENV(env, save, restore)\
{\
    memset((env), 0xaa, sizeof(*(env)));\
    for(i=0;i<5;i++)\
        asm volatile ("fldl %0" : : "m" (dtab[i]));\
    asm volatile (save " %0\n" : : "m" (*(env)));\
    asm volatile (restore " %0\n": : "m" (*(env)));\
    for(i=0;i<5;i++)\
        asm volatile ("fstpl %0" : "=m" (rtab[i]));\
    for(i=0;i<5;i++)\
        printf("res[%d]=%f\n", i, rtab[i]);\
    printf("fpuc=%04x fpus=%04x fptag=%04x\n",\
           (env)->fpuc,\
           (env)->fpus & 0xff00,\
           (env)->fptag);\
}

void test_fenv(void)
{
    struct __attribute__((__packed__)) {
        uint16_t fpuc;
        uint16_t dummy1;
        uint16_t fpus;
        uint16_t dummy2;
        uint16_t fptag;
        uint16_t dummy3;
        uint32_t ignored[4];
        long double fpregs[8];
    } float_env32;
    struct __attribute__((__packed__)) {
        uint16_t fpuc;
        uint16_t fpus;
        uint16_t fptag;
        uint16_t ignored[4];
        long double fpregs[8];
    } float_env16;
    double dtab[8];
    double rtab[8];
    int i;

    for(i=0;i<8;i++)
        dtab[i] = i + 1;

    asm volatile ("fninit");
    //TEST_ENV(&float_env16, "data16 fnstenv", "data16 fldenv");
    //TEST_ENV(&float_env16, "data16 fnsave", "data16 frstor");
    TEST_ENV(&float_env32, "fnstenv", "fldenv");
    TEST_ENV(&float_env32, "fnsave", "frstor");

    /* test for ffree */
    for(i=0;i<5;i++)
        asm volatile ("fldl %0" : : "m" (dtab[i]));
    asm volatile("ffree %st(2)");
    asm volatile ("fnstenv %0\n" : : "m" (float_env32));
    asm volatile ("fninit");
    printf("fptag=%04x\n", float_env32.fptag);
}


#define TEST_FCMOV(a, b, eflags, CC)\
{\
    double res;\
    asm("push %3\n"\
        "popf\n"\
        "fcmov" CC " %2, %0\n"\
        : "=t" (res)\
        : "0" (a), "u" (b), "g" (eflags));\
    printf("fcmov%s eflags=0x%04lx-> %f\n", \
           CC, (long)eflags, res);\
}

void test_fcmov(void)
{
    double a, b;
    long eflags, i;

    a = 1.0;
    b = 2.0;
    for(i = 0; i < 4; i++) {
        eflags = 0;
        if (i & 1)
            eflags |= CC_C;
        if (i & 2)
            eflags |= CC_Z;
        TEST_FCMOV(a, b, eflags, "b");
        TEST_FCMOV(a, b, eflags, "e");
        TEST_FCMOV(a, b, eflags, "be");
        TEST_FCMOV(a, b, eflags, "nb");
        TEST_FCMOV(a, b, eflags, "ne");
        TEST_FCMOV(a, b, eflags, "nbe");
    }
    TEST_FCMOV(a, b, 0, "u");
    TEST_FCMOV(a, b, CC_P, "u");
    TEST_FCMOV(a, b, 0, "nu");
    TEST_FCMOV(a, b, CC_P, "nu");
}

void test_floats(void)
{
    test_fops(2, 3);
    test_fops(1.4, -5);
    test_fops(-20.5, 128);
    test_fops(-0.5, -4);
    test_fcmp(2, -1);
    test_fcmp(2, 2);
    test_fcmp(2, 3);
    test_fcmp(2, q_nan.d);
    test_fcmp(q_nan.d, -1);
    test_fcmp(-1.0/0.0, -1);
    test_fcmp(1.0/0.0, -1);
    test_fcvt(0.5);
    test_fcvt(-0.5);
    test_fcvt(1.0/7.0);
    test_fcvt(-1.0/9.0);
    test_fcvt(32768);
    // largest and smallest, odd and even numbers that have one bit left for the fractional part (2**52-1)
    test_fcvt(4503599627370494.5);
    test_fcvt(4503599627370495.5);
    test_fcvt(-4503599627370494.5);
    test_fcvt(-4503599627370495.5);
    test_fcvt(-1e20);
    test_fcvt(-1.0/0.0);
    test_fcvt(1.0/0.0);
    test_fcvt(q_nan.d);
    test_fconst();
    test_fbcd(0.0);
    test_fbcd(-0.0);
    test_fbcd(1.0);
    test_fbcd(-1.0);
    test_fbcd(1234567890123456.0);
    test_fbcd(-123451234567890.0);
    test_fbcd(341234567890123456.0);
    test_fbcd(-345123451234567890.0);
    test_fbcd(999999999999999900.0);
    test_fbcd(-999999999999999900.0);
    test_fbcd(1000000000000000000.0);
    test_fbcd(-1000000000000000000.0);
    test_fbcd(1000000000000000000000.0);
    test_fbcd(-1000000000000000000000.0);
    test_fenv();
    if (TEST_CMOV) {
        test_fcmov();
    }
}

/**********************************************/
#if !defined(__x86_64__)

#define TEST_BCD(op, op0, cc_in, cc_mask)\
{\
    int res, flags;\
    res = op0;\
    flags = cc_in;\
    asm ("push %3\n\t"\
         "popf\n\t"\
         #op "\n\t"\
         "pushf\n\t"\
         "pop %1\n\t"\
        : "=a" (res), "=g" (flags)\
        : "0" (res), "1" (flags));\
    printf("%-10s A=%08x R=%08x CCIN=%04x CC=%04x\n",\
           #op, op0, res, cc_in, flags & cc_mask);\
}

void test_bcd(void)
{
    TEST_BCD(daa, 0x12340503, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340506, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340507, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340559, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340560, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x1234059f, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x123405a0, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340503, 0, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340506, 0, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340503, CC_C, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340506, CC_C, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340503, CC_C | CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(daa, 0x12340506, CC_C | CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));

    TEST_BCD(das, 0x12340503, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340506, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340507, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340559, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340560, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x1234059f, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x123405a0, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340503, 0, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340506, 0, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340503, CC_C, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340506, CC_C, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340503, CC_C | CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));
    TEST_BCD(das, 0x12340506, CC_C | CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_A));

    TEST_BCD(aaa, 0x12340205, CC_A, (CC_C | CC_A));
    TEST_BCD(aaa, 0x12340306, CC_A, (CC_C | CC_A));
    TEST_BCD(aaa, 0x1234040a, CC_A, (CC_C | CC_A));
    TEST_BCD(aaa, 0x123405fa, CC_A, (CC_C | CC_A));
    TEST_BCD(aaa, 0x12340205, 0, (CC_C | CC_A));
    TEST_BCD(aaa, 0x12340306, 0, (CC_C | CC_A));
    TEST_BCD(aaa, 0x1234040a, 0, (CC_C | CC_A));
    TEST_BCD(aaa, 0x123405fa, 0, (CC_C | CC_A));

    TEST_BCD(aas, 0x12340205, CC_A, (CC_C | CC_A));
    TEST_BCD(aas, 0x12340306, CC_A, (CC_C | CC_A));
    TEST_BCD(aas, 0x1234040a, CC_A, (CC_C | CC_A));
    TEST_BCD(aas, 0x123405fa, CC_A, (CC_C | CC_A));
    TEST_BCD(aas, 0x12340205, 0, (CC_C | CC_A));
    TEST_BCD(aas, 0x12340306, 0, (CC_C | CC_A));
    TEST_BCD(aas, 0x1234040a, 0, (CC_C | CC_A));
    TEST_BCD(aas, 0x123405fa, 0, (CC_C | CC_A));

    TEST_BCD(aam, 0x12340547, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A));
    TEST_BCD(aad, 0x12340407, CC_A, (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A));
}
#endif

#define TEST_XCHG(op, size, opconst)\
{\
    long op0, op1;\
    op0 = i2l(0x12345678);\
    op1 = i2l(0xfbca7654);\
    asm(#op " %" size "0, %" size "1" \
        : "=q" (op0), opconst (op1) \
        : "0" (op0));\
    printf("%-10s A=" FMTLX " B=" FMTLX "\n",\
           #op, op0, op1);\
}

#define TEST_CMPXCHG(op, size, opconst, eax)\
{\
    long op0, op1, op2;\
    op0 = i2l(0x12345678);\
    op1 = i2l(0xfbca7654);\
    op2 = i2l(eax);\
    asm(#op " %" size "0, %" size "1" \
        : "=q" (op0), opconst (op1) \
        : "0" (op0), "a" (op2));\
    printf("%-10s EAX=" FMTLX " A=" FMTLX " C=" FMTLX "\n",\
           #op, op2, op0, op1);\
}

void test_xchg(void)
{
#if defined(__x86_64__)
    TEST_XCHG(xchgq, "", "+q");
#endif
    TEST_XCHG(xchgl, "k", "+q");
    TEST_XCHG(xchgw, "w", "+q");
    TEST_XCHG(xchgb, "b", "+q");

#if defined(__x86_64__)
    TEST_XCHG(xchgq, "", "=m");
#endif
    TEST_XCHG(xchgl, "k", "+m");
    TEST_XCHG(xchgw, "w", "+m");
    TEST_XCHG(xchgb, "b", "+m");

#if defined(__x86_64__)
    TEST_XCHG(xaddq, "", "+q");
#endif
    TEST_XCHG(xaddl, "k", "+q");
    TEST_XCHG(xaddw, "w", "+q");
    TEST_XCHG(xaddb, "b", "+q");

    {
        int res;
        res = 0x12345678;
        asm("xaddl %1, %0" : "=r" (res) : "0" (res));
        printf("xaddl same res=%08x\n", res);
    }

#if defined(__x86_64__)
    TEST_XCHG(xaddq, "", "+m");
#endif
    TEST_XCHG(xaddl, "k", "+m");
    TEST_XCHG(xaddw, "w", "+m");
    TEST_XCHG(xaddb, "b", "+m");

#if defined(__x86_64__)
    TEST_CMPXCHG(cmpxchgq, "", "+q", 0xfbca7654);
#endif
    TEST_CMPXCHG(cmpxchgl, "k", "+q", 0xfbca7654);
    TEST_CMPXCHG(cmpxchgw, "w", "+q", 0xfbca7654);
    TEST_CMPXCHG(cmpxchgb, "b", "+q", 0xfbca7654);

#if defined(__x86_64__)
    TEST_CMPXCHG(cmpxchgq, "", "+q", 0xfffefdfc);
#endif
    TEST_CMPXCHG(cmpxchgl, "k", "+q", 0xfffefdfc);
    TEST_CMPXCHG(cmpxchgw, "w", "+q", 0xfffefdfc);
    TEST_CMPXCHG(cmpxchgb, "b", "+q", 0xfffefdfc);

#if defined(__x86_64__)
    TEST_CMPXCHG(cmpxchgq, "", "+m", 0xfbca7654);
#endif
    TEST_CMPXCHG(cmpxchgl, "k", "+m", 0xfbca7654);
    TEST_CMPXCHG(cmpxchgw, "w", "+m", 0xfbca7654);
    TEST_CMPXCHG(cmpxchgb, "b", "+m", 0xfbca7654);

#if defined(__x86_64__)
    TEST_CMPXCHG(cmpxchgq, "", "+m", 0xfffefdfc);
#endif
    TEST_CMPXCHG(cmpxchgl, "k", "+m", 0xfffefdfc);
    TEST_CMPXCHG(cmpxchgw, "w", "+m", 0xfffefdfc);
    TEST_CMPXCHG(cmpxchgb, "b", "+m", 0xfffefdfc);

    {
        uint64_t op0, op1, op2;
        long eax, edx;
        long i, eflags;

        for(i = 0; i < 2; i++) {
            op0 = 0x123456789abcdLL;
            eax = i2l(op0 & 0xffffffff);
            edx = i2l(op0 >> 32);
            if (i == 0)
                op1 = 0xfbca765423456LL;
            else
                op1 = op0;
            op2 = 0x6532432432434LL;
            asm("cmpxchg8b %2\n"
                "pushf\n"
                "pop %3\n"
                : "=a" (eax), "=d" (edx), "=m" (op1), "=g" (eflags)
                : "0" (eax), "1" (edx), "m" (op1), "b" ((int)op2), "c" ((int)(op2 >> 32)));
            printf("cmpxchg8b: eax=" FMTLX " edx=" FMTLX " op1=" FMT64X " CC=%02lx\n",
                   eax, edx, op1, eflags & CC_Z);
        }
    }
}

#ifdef TEST_SEGS
/**********************************************/
/* segmentation tests */

#include <sys/syscall.h>
#include <unistd.h>
#include <asm/ldt.h>
#include <linux/version.h>

static inline int modify_ldt(int func, void * ptr, unsigned long bytecount)
{
    int result = syscall(__NR_modify_ldt, func, ptr, bytecount);
    if(result == -1)
    {
        fprintf(stderr, "Error: modify_ldt not available on this kernel. Check MODIFY_LDT_SYSCALL in /proc/config.gz.\n");
        exit(1);
    }
    return result;
}

#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 5, 66)
#define modify_ldt_ldt_s user_desc
#endif

#define MK_SEL(n) (((n) << 3) | 7)

uint8_t seg_data1[4096];
uint8_t seg_data2[4096];

#define TEST_LR(op, size, seg, mask)\
{\
    int res, res2;\
    uint16_t mseg = seg;\
    res = 0x12345678;\
    asm (op " %" size "2, %" size "0\n" \
         "movl $0, %1\n"\
         "jnz 1f\n"\
         "movl $1, %1\n"\
         "1:\n"\
         : "=r" (res), "=r" (res2) : "m" (mseg), "0" (res));\
    printf(op ": Z=%d %08x\n", res2, res & ~(mask));\
}

#define TEST_ARPL(op, size, op1, op2)\
{\
    long a, b, c;                               \
    a = (op1);                                  \
    b = (op2);                                  \
    asm volatile(op " %" size "3, %" size "0\n"\
                 "movl $0,%1\n"\
                 "jnz 1f\n"\
                 "movl $1,%1\n"\
                 "1:\n"\
                 : "=r" (a), "=r" (c) : "0" (a), "r" (b));    \
    printf(op size " A=" FMTLX " B=" FMTLX " R=" FMTLX " z=%ld\n",\
           (long)(op1), (long)(op2), a, c);\
}

/* NOTE: we use Linux modify_ldt syscall */
void test_segs(void)
{
    struct modify_ldt_ldt_s ldt;
    long long ldt_table[3];
    int res, res2;
    char tmp;
    struct {
        uint32_t offset;
        uint16_t seg;
    } __attribute__((__packed__)) segoff;

    ldt.entry_number = 1;
    ldt.base_addr = (unsigned long)&seg_data1;
    ldt.limit = (sizeof(seg_data1) + 0xfff) >> 12;
    ldt.seg_32bit = 1;
    ldt.contents = MODIFY_LDT_CONTENTS_DATA;
    ldt.read_exec_only = 0;
    ldt.limit_in_pages = 1;
    ldt.seg_not_present = 0;
    ldt.useable = 1;
    modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

    ldt.entry_number = 2;
    ldt.base_addr = (unsigned long)&seg_data2;
    ldt.limit = (sizeof(seg_data2) + 0xfff) >> 12;
    ldt.seg_32bit = 1;
    ldt.contents = MODIFY_LDT_CONTENTS_DATA;
    ldt.read_exec_only = 0;
    ldt.limit_in_pages = 1;
    ldt.seg_not_present = 0;
    ldt.useable = 1;
    modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

    modify_ldt(0, &ldt_table, sizeof(ldt_table)); /* read ldt entries */
    {
        int i;
        for(i=0;i<3;i++)
            printf("%d: %016Lx\n", i, ldt_table[i]);
    }
    /* do some tests with fs or gs */
    asm volatile ("movl %0, %%fs" : : "r" (MK_SEL(1)));

    seg_data1[1] = 0xaa;
    seg_data2[1] = 0x55;

    asm volatile ("fs movzbl 0x1, %0" : "=r" (res));
    printf("FS[1] = %02x\n", res);

    asm volatile ("pushl %%gs\n"
                  "movl %1, %%gs\n"
                  "gs movzbl 0x1, %0\n"
                  "popl %%gs\n"
                  : "=r" (res)
                  : "r" (MK_SEL(2)));
    printf("GS[1] = %02x\n", res);

    /* tests with ds/ss (implicit segment case) */
    tmp = 0xa5;
    asm volatile ("pushl %%ebp\n\t"
                  "pushl %%ds\n\t"
                  "movl %2, %%ds\n\t"
                  "movl %3, %%ebp\n\t"
                  "movzbl 0x1, %0\n\t"
                  "movzbl (%%ebp), %1\n\t"
                  "popl %%ds\n\t"
                  "popl %%ebp\n\t"
                  : "=r" (res), "=r" (res2)
                  : "r" (MK_SEL(1)), "r" (&tmp));
    printf("DS[1] = %02x\n", res);
    printf("SS[tmp] = %02x\n", res2);

    segoff.seg = MK_SEL(2);
    segoff.offset = 0xabcdef12;
    asm volatile("lfs %2, %0\n\t"
                 "movl %%fs, %1\n\t"
                 : "=r" (res), "=g" (res2)
                 : "m" (segoff));
    printf("FS:reg = %04x:%08x\n", res2, res);

    TEST_LR("larw", "w", MK_SEL(2), 0x0100);
    TEST_LR("larl", "", MK_SEL(2), 0x0100);
    TEST_LR("lslw", "w", MK_SEL(2), 0);
    TEST_LR("lsll", "", MK_SEL(2), 0);

    TEST_LR("larw", "w", 0xfff8, 0);
    TEST_LR("larl", "", 0xfff8, 0);
    TEST_LR("lslw", "w", 0xfff8, 0);
    TEST_LR("lsll", "", 0xfff8, 0);

    TEST_ARPL("arpl", "w", 0x12345678 | 3, 0x762123c | 1);
    TEST_ARPL("arpl", "w", 0x12345678 | 1, 0x762123c | 3);
    TEST_ARPL("arpl", "w", 0x12345678 | 1, 0x762123c | 1);
}

/* 16 bit code test */
extern char code16_start, code16_end;
extern char code16_func1;
extern char code16_func2;
extern char code16_func3;

void test_code16(void)
{
    struct modify_ldt_ldt_s ldt;
    int res, res2;

    /* build a code segment */
    ldt.entry_number = 1;
    ldt.base_addr = (unsigned long)&code16_start;
    ldt.limit = &code16_end - &code16_start;
    ldt.seg_32bit = 0;
    ldt.contents = MODIFY_LDT_CONTENTS_CODE;
    ldt.read_exec_only = 0;
    ldt.limit_in_pages = 0;
    ldt.seg_not_present = 0;
    ldt.useable = 1;
    modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

    /* call the first function */
    // XXX: Temporarily disabled: Fails to compile on newer gcc, wait for upstream fix
#if 0
    asm volatile ("lcall %1, %2"
                  : "=a" (res)
                  : "i" (MK_SEL(1)), "i" (&code16_func1): "memory", "cc");
    printf("func1() = 0x%08x\n", res);
    asm volatile ("lcall %2, %3"
                  : "=a" (res), "=c" (res2)
                  : "i" (MK_SEL(1)), "i" (&code16_func2): "memory", "cc");
    printf("func2() = 0x%08x spdec=%d\n", res, res2);
    asm volatile ("lcall %1, %2"
                  : "=a" (res)
                  : "i" (MK_SEL(1)), "i" (&code16_func3): "memory", "cc");
    printf("func3() = 0x%08x\n", res);
#endif
}
#endif

#if defined(__x86_64__)
asm(".globl func_lret\n"
    "func_lret:\n"
    "movl $0x87654641, %eax\n"
    "lretq\n");
#else
asm(".globl func_lret\n"
    "func_lret:\n"
    "movl $0x87654321, %eax\n"
    "lret\n"

    ".globl func_iret\n"
    "func_iret:\n"
    "movl $0xabcd4321, %eax\n"
    "iret\n");
#endif

extern char func_lret;
extern char func_iret;

void test_misc(void)
{
    char table[256];
    long res, i;

    for(i=0;i<256;i++) table[i] = 256 - i;
    res = 0x12345678;
    asm ("xlat" : "=a" (res) : "b" (table), "0" (res));
    printf("xlat: EAX=" FMTLX "\n", res);

#if defined(__x86_64__)
#if 0
    {
        /* XXX: see if Intel Core2 and AMD64 behavior really
           differ. Here we implemented the Intel way which is not
           compatible yet with QEMU. */
        static struct QEMU_PACKED {
            uint64_t offset;
            uint16_t seg;
        } desc;
        long cs_sel;

        asm volatile ("mov %%cs, %0" : "=r" (cs_sel));

        asm volatile ("push %1\n"
                      "call func_lret\n"
                      : "=a" (res)
                      : "r" (cs_sel) : "memory", "cc");
        printf("func_lret=" FMTLX "\n", res);

        desc.offset = (long)&func_lret;
        desc.seg = cs_sel;

        asm volatile ("xor %%rax, %%rax\n"
                      "rex64 lcall *(%%rcx)\n"
                      : "=a" (res)
                      : "c" (&desc)
                      : "memory", "cc");
        printf("func_lret2=" FMTLX "\n", res);

        asm volatile ("push %2\n"
                      "mov $ 1f, %%rax\n"
                      "push %%rax\n"
                      "rex64 ljmp *(%%rcx)\n"
                      "1:\n"
                      : "=a" (res)
                      : "c" (&desc), "b" (cs_sel)
                      : "memory", "cc");
        printf("func_lret3=" FMTLX "\n", res);
    }
#endif
#else

    // XXX: Temporarily disabled: Fails to compile on newer gcc, wait for upstream fix
#if 0
    asm volatile ("push %%cs ; call %1"
                  : "=a" (res)
                  : "m" (func_lret): "memory", "cc");
    printf("func_lret=" FMTLX "\n", res);

    asm volatile ("pushf ; push %%cs ; call %1"
                  : "=a" (res)
                  : "m" (func_iret): "memory", "cc");
    printf("func_iret=" FMTLX "\n", res);
#endif
#endif

#if defined(__x86_64__)
    /* specific popl test */
    asm volatile ("push $12345432 ; push $0x9abcdef ; pop (%%rsp) ; pop %0"
                  : "=g" (res));
    printf("popl esp=" FMTLX "\n", res);
#else
    /* specific popl test */
    asm volatile ("pushl $12345432 ; pushl $0x9abcdef ; popl (%%esp) ; popl %0"
                  : "=g" (res));
    printf("popl esp=" FMTLX "\n", res);

    /* specific popw test */
    asm volatile ("pushl $12345432 ; pushl $0x9abcdef ; popw (%%esp) ; addl $2, %%esp ; popl %0"
                  : "=g" (res));
    printf("popw esp=" FMTLX "\n", res);
#endif
}

void byte_read(uint8_t* buffer, uint16_t offset, size_t num_bytes);

// 8 pages in every direction
#define STR_BUFFER_SIZE (4096 * 16)
uint8_t __attribute__((aligned (4096))) str_buffer[STR_BUFFER_SIZE];

#define TEST_STRING1(OP, size_bytes, size, DF, REP, count, offset1, offset2)\
{\
    long esi, edi, eax, ecx, eflags, i;\
\
    for(i = 0; i < (count + 1) * size_bytes; i++) {\
        str_buffer[sizeof(str_buffer)/2 + offset1 + i] = i + 0x56;\
        str_buffer[sizeof(str_buffer)/2 + offset1 - i - 1] = i + 0x97;\
        str_buffer[sizeof(str_buffer)/2 + offset2 + i] = i + 0xa5;\
        str_buffer[sizeof(str_buffer)/2 + offset2 - i - 1] = i + 0x3e;\
    }\
    esi = (long)(str_buffer + sizeof(str_buffer)/2 + offset1);\
    edi = (long)(str_buffer + sizeof(str_buffer)/2 + offset2);\
    eax = i2l(0x12345678);\
    ecx = count;\
\
    asm volatile ("push $0\n\t"\
                  "popf\n\t"\
                  DF "\n\t"\
                  REP #OP size "\n\t"\
                  "cld\n\t"\
                  "pushf\n\t"\
                  "pop %4\n\t"\
                  : "=S" (esi), "=D" (edi), "=a" (eax), "=c" (ecx), "=g" (eflags)\
                  : "0" (esi), "1" (edi), "2" (eax), "3" (ecx));\
    printf("%-10s ESI=" FMTLX " EDI=" FMTLX " EAX=" FMTLX " ECX=" FMTLX " EFL=%04x\n",\
           REP #OP size, esi, edi, eax, ecx,\
           (int)(eflags & (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A)));\
    byte_read(str_buffer, offset1, 16); \
    if(count > 16) byte_read(str_buffer, offset1 + count * size_bytes - 16, 16);\
    if(count > 16) byte_read(str_buffer, offset1 - count * size_bytes, 16);\
    byte_read(str_buffer, offset2, 16); \
    if(count > 16) byte_read(str_buffer, offset2 + count * size_bytes - 16, 16);\
    if(count > 16) byte_read(str_buffer, offset2 - count * size_bytes, 16);\
}

#define TEST_STRING(OP, REP, count, offset1, offset2)\
    TEST_STRING1(OP, 1, "b", "", REP, count, offset1, offset2);\
    TEST_STRING1(OP, 2, "w", "", REP, count, offset1, offset2);\
    TEST_STRING1(OP, 4, "l", "", REP, count, offset1, offset2);\
    TEST_STRING1(OP, 1, "b", "std", REP, count, offset1, offset2);\
    TEST_STRING1(OP, 2, "w", "std", REP, count, offset1, offset2);\
    TEST_STRING1(OP, 4, "l", "std", REP, count, offset1, offset2);

void test_string(void)
{
   TEST_STRING(stos, "", 17, 4096, 4096 + 64);
   TEST_STRING(stos, "rep ", 17, 4096, 4096 + 64);

   TEST_STRING(lods, "", 17, 4096, 4096 + 64);
   TEST_STRING(lods, "rep ", 17, 4096, 4096 + 64);

   TEST_STRING(movs, "", 17, 4096, 4096 + 64);
   TEST_STRING(movs, "rep ", 17, 4096, 4096 + 64);

   /* XXX: better tests */
   TEST_STRING(scas, "", 17, 4096, 4096 + 64);
   TEST_STRING(scas, "repz ", 17, 4096, 4096 + 64);
   TEST_STRING(scas, "repnz ", 17, 4096, 4096 + 64);

   TEST_STRING(cmps, "", 17, 4096, 4096 + 64);
   TEST_STRING(cmps, "repz ", 17, 4096, 4096 + 64);
   TEST_STRING(cmps, "repnz ", 17, 4096, 4096 + 64);

   int counts[] = { 0, 1, 2, 3, 4095, 4096, 4097, 2047, 2048, 2049, 1023, 1024, 1025 };
   int offsets[] = { 0, 1, 2, 3, 4095, 4096, 4097, 2047, 2048, 2049, 1023, 1024, 1025 };

   for(int count = 0; count < sizeof(counts) / sizeof(int); count++)
   {
       for(int offset1 = 0; offset1 < sizeof(offsets) / sizeof(int); offset1++)
       {
           TEST_STRING(stos, "rep ", counts[count], offsets[offset1], offsets[offset1]);

           for(int offset2 = 0; offset2 < sizeof(offsets) / sizeof(int); offset2++)
           {
               TEST_STRING(movs, "rep ", counts[count], offsets[offset1], offsets[offset2]);
           }
       }
   }
}

#ifdef TEST_VM86
/* VM86 test */

static inline void set_bit(uint8_t *a, unsigned int bit)
{
    a[bit / 8] |= (1 << (bit % 8));
}

static inline uint8_t *seg_to_linear(unsigned int seg, unsigned int reg)
{
    return (uint8_t *)((seg << 4) + (reg & 0xffff));
}

static inline void pushw(struct vm86_regs *r, int val)
{
    r->esp = (r->esp & ~0xffff) | ((r->esp - 2) & 0xffff);
    *(uint16_t *)seg_to_linear(r->ss, r->esp) = val;
}

static inline int vm86(int func, struct vm86plus_struct *v86)
{
    return syscall(__NR_vm86, func, v86);
}

extern char vm86_code_start;
extern char vm86_code_end;

#define VM86_CODE_CS 0x100
#define VM86_CODE_IP 0x100

void test_vm86(void)
{
    struct vm86plus_struct ctx;
    struct vm86_regs *r;
    uint8_t *vm86_mem;
    int seg, ret;

    vm86_mem = mmap((void *)0x00000000, 0x110000,
                    PROT_WRITE | PROT_READ | PROT_EXEC,
                    MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0);
    if (vm86_mem == MAP_FAILED) {
        printf("ERROR: could not map vm86 memory");
        return;
    }
    memset(&ctx, 0, sizeof(ctx));

    /* init basic registers */
    r = &ctx.regs;
    r->eip = VM86_CODE_IP;
    r->esp = 0xfffe;
    seg = VM86_CODE_CS;
    r->cs = seg;
    r->ss = seg;
    r->ds = seg;
    r->es = seg;
    r->fs = seg;
    r->gs = seg;
    //r->eflags = VIF_MASK;

    /* move code to proper address. We use the same layout as a .com
       dos program. */
    memcpy(vm86_mem + (VM86_CODE_CS << 4) + VM86_CODE_IP,
           &vm86_code_start, &vm86_code_end - &vm86_code_start);

    /* mark int 0x21 as being emulated */
    set_bit((uint8_t *)&ctx.int_revectored, 0x21);

    for(;;) {
        ret = vm86(VM86_ENTER, &ctx);
        switch(VM86_TYPE(ret)) {
        case VM86_INTx:
            {
                int int_num, ah, v;

                int_num = VM86_ARG(ret);
                if (int_num != 0x21)
                    goto unknown_int;
                ah = (r->eax >> 8) & 0xff;
                switch(ah) {
                case 0x00: /* exit */
                    goto the_end;
                case 0x02: /* write char */
                    {
                        uint8_t c = r->edx;
                        putchar(c);
                    }
                    break;
                case 0x09: /* write string */
                    {
                        uint8_t c, *ptr;
                        ptr = seg_to_linear(r->ds, r->edx);
                        for(;;) {
                            c = *ptr++;
                            if (c == '$')
                                break;
                            putchar(c);
                        }
                        r->eax = (r->eax & ~0xff) | '$';
                    }
                    break;
                case 0xff: /* extension: write eflags number in edx */
                    v = (int)r->edx;
#ifndef LINUX_VM86_IOPL_FIX
                    v &= ~0x3000;
#endif
                    printf("%08x\n", v);
                    break;
                default:
                unknown_int:
                    printf("unsupported int 0x%02x\n", int_num);
                    goto the_end;
                }
            }
            break;
        case VM86_SIGNAL:
            /* a signal came, we just ignore that */
            break;
        case VM86_STI:
            break;
        default:
            printf("ERROR: unhandled vm86 return code (0x%x)\n", ret);
            goto the_end;
        }
    }
 the_end:
    printf("VM86 end\n");
    munmap(vm86_mem, 0x110000);
}
#endif

/* exception tests */
#if defined(__i386__) && !defined(REG_EAX)
#define REG_EAX EAX
#define REG_EBX EBX
#define REG_ECX ECX
#define REG_EDX EDX
#define REG_ESI ESI
#define REG_EDI EDI
#define REG_EBP EBP
#define REG_ESP ESP
#define REG_EIP EIP
#define REG_EFL EFL
#define REG_TRAPNO TRAPNO
#define REG_ERR ERR
#endif

#if defined(__x86_64__)
#define REG_EIP REG_RIP
#endif

jmp_buf jmp_env;
int v1;
int tab[2];

void sig_handler(int sig, siginfo_t *info, void *puc)
{
    ucontext_t *uc = puc;

    printf("si_signo=%d si_errno=%d si_code=%d",
           info->si_signo, info->si_errno, info->si_code);
    printf(" si_addr=0x%08lx",
           (unsigned long)info->si_addr);
    printf("\n");

    printf("trapno=" FMTLX " err=" FMTLX,
           (long)uc->uc_mcontext.gregs[REG_TRAPNO],
           (long)uc->uc_mcontext.gregs[REG_ERR]);
    printf(" EIP=" FMTLX, (long)uc->uc_mcontext.gregs[REG_EIP]);
    printf("\n");
    longjmp(jmp_env, 1);
}

void test_exceptions(void)
{
    struct sigaction act;
    volatile int val;

    act.sa_sigaction = sig_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO | SA_NODEFER;
    sigaction(SIGFPE, &act, NULL);
    sigaction(SIGILL, &act, NULL);
    sigaction(SIGSEGV, &act, NULL);
    sigaction(SIGBUS, &act, NULL);
    sigaction(SIGTRAP, &act, NULL);

    /* test division by zero reporting */
    printf("DIVZ exception:\n");
    if (setjmp(jmp_env) == 0) {
        /* now divide by zero */
        v1 = 0;
        v1 = 2 / v1;
    }

#if 0
#if !defined(__x86_64__)
    printf("BOUND exception:\n");
    if (setjmp(jmp_env) == 0) {
        /* bound exception */
        tab[0] = 1;
        tab[1] = 10;
        asm volatile ("bound %0, %1" : : "r" (11), "m" (tab[0]));
    }
#endif
#endif

#ifdef TEST_SEGS
    printf("segment exceptions:\n");
    if (setjmp(jmp_env) == 0) {
        /* load an invalid segment */
        asm volatile ("movl %0, %%fs" : : "r" ((0x1234 << 3) | 1));
    }
    if (setjmp(jmp_env) == 0) {
        /* null data segment is valid */
        asm volatile ("movl %0, %%fs" : : "r" (3));
        /* null stack segment */
        asm volatile ("movl %0, %%ss" : : "r" (3));
    }

    {
        struct modify_ldt_ldt_s ldt;
        ldt.entry_number = 1;
        ldt.base_addr = (unsigned long)&seg_data1;
        ldt.limit = (sizeof(seg_data1) + 0xfff) >> 12;
        ldt.seg_32bit = 1;
        ldt.contents = MODIFY_LDT_CONTENTS_DATA;
        ldt.read_exec_only = 0;
        ldt.limit_in_pages = 1;
        ldt.seg_not_present = 1;
        ldt.useable = 1;
        modify_ldt(1, &ldt, sizeof(ldt)); /* write ldt entry */

        if (setjmp(jmp_env) == 0) {
            /* segment not present */
            asm volatile ("movl %0, %%fs" : : "r" (MK_SEL(1)));
        }
    }
#endif

    /* test SEGV reporting */
    printf("PF exception:\n");
    if (setjmp(jmp_env) == 0) {
        val = 1;
        /* we add a nop to test a weird PC retrieval case */
        asm volatile ("nop");
        /* now store in an invalid address */
        *(char *)0x1234 = 1;
    }

    /* test SEGV reporting */
    printf("PF exception:\n");
    if (setjmp(jmp_env) == 0) {
        val = 1;
        /* read from an invalid address */
        v1 = *(char *)0x1234;
    }

    /* test illegal instruction reporting */
    printf("UD2 exception:\n");
    if (setjmp(jmp_env) == 0) {
        /* now execute an invalid instruction */
        asm volatile("ud2");
    }
#if 0
    printf("lock nop exception:\n");
    if (setjmp(jmp_env) == 0) {
        /* now execute an invalid instruction */
        asm volatile(".byte 0xf0, 0x90");
    }
#endif

    printf("INT exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("int $0xfd");
    }
    if (setjmp(jmp_env) == 0) {
        asm volatile ("int $0x01");
    }
    if (setjmp(jmp_env) == 0) {
        asm volatile (".byte 0xcd, 0x03");
    }
    if (setjmp(jmp_env) == 0) {
        asm volatile ("int $0x04");
    }
    if (setjmp(jmp_env) == 0) {
        asm volatile ("int $0x05");
    }

    printf("INT3 exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("int3");
    }

    printf("CLI exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("cli");
    }

    printf("STI exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("cli");
    }

#if !defined(__x86_64__)
    printf("INTO exception:\n");
    if (setjmp(jmp_env) == 0) {
        /* overflow exception */
        asm volatile ("addl $1, %0 ; into" : : "r" (0x7fffffff));
    }
#endif

    printf("OUTB exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("outb %%al, %%dx" : : "d" (0x4321), "a" (0));
    }

    printf("INB exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("inb %%dx, %%al" : "=a" (val) : "d" (0x4321));
    }

    printf("REP OUTSB exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("rep outsb" : : "d" (0x4321), "S" (tab), "c" (1));
    }

    printf("REP INSB exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("rep insb" : : "d" (0x4321), "D" (tab), "c" (1));
    }

    printf("HLT exception:\n");
    if (setjmp(jmp_env) == 0) {
        asm volatile ("hlt");
    }

#if 0
    printf("single step exception:\n");
    val = 0;
    if (setjmp(jmp_env) == 0) {
        asm volatile ("pushf\n"
                      "orl $0x00100, (%%esp)\n"
                      "popf\n"
                      "movl $0xabcd, %0\n"
                      "movl $0x0, %0\n" : "=m" (val) : : "cc", "memory");
    }
    printf("val=0x%x\n", val);
#endif
}

#if !defined(__x86_64__)
/* specific precise single step test */
void sig_trap_handler(int sig, siginfo_t *info, void *puc)
{
    ucontext_t *uc = puc;
    printf("EIP=" FMTLX "\n", (long)uc->uc_mcontext.gregs[REG_EIP]);
}

const uint8_t sstep_buf1[4] = { 1, 2, 3, 4};
uint8_t sstep_buf2[4];

void test_single_step(void)
{
    struct sigaction act;
    volatile int val;
    int i;

    val = 0;
    act.sa_sigaction = sig_trap_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGTRAP, &act, NULL);
    asm volatile ("pushf\n"
                  "orl $0x00100, (%%esp)\n"
                  "popf\n"
                  "movl $0xabcd, %0\n"

                  /* jmp test */
                  "movl $3, %%ecx\n"
                  "1:\n"
                  "addl $1, %0\n"
                  "decl %%ecx\n"
                  "jnz 1b\n"

                  /* movsb: the single step should stop at each movsb iteration */
                  "movl $sstep_buf1, %%esi\n"
                  "movl $sstep_buf2, %%edi\n"
                  "movl $0, %%ecx\n"
                  "rep movsb\n"
                  "movl $3, %%ecx\n"
                  "rep movsb\n"
                  "movl $1, %%ecx\n"
                  "rep movsb\n"

                  /* cmpsb: the single step should stop at each cmpsb iteration */
                  "movl $sstep_buf1, %%esi\n"
                  "movl $sstep_buf2, %%edi\n"
                  "movl $0, %%ecx\n"
                  "rep cmpsb\n"
                  "movl $4, %%ecx\n"
                  "rep cmpsb\n"

                  /* getpid() syscall: single step should skip one
                     instruction */
                  "movl $20, %%eax\n"
                  "int $0x80\n"
                  "movl $0, %%eax\n"

                  /* when modifying SS, trace is not done on the next
                     instruction */
                  "movl %%ss, %%ecx\n"
                  "movl %%ecx, %%ss\n"
                  "addl $1, %0\n"
                  "movl $1, %%eax\n"
                  "movl %%ecx, %%ss\n"
                  "jmp 1f\n"
                  "addl $1, %0\n"
                  "1:\n"
                  "movl $1, %%eax\n"
                  "pushl %%ecx\n"
                  "popl %%ss\n"
                  "addl $1, %0\n"
                  "movl $1, %%eax\n"

                  "pushf\n"
                  "andl $~0x00100, (%%esp)\n"
                  "popf\n"
                  : "=m" (val)
                  :
                  : "cc", "memory", "eax", "ecx", "esi", "edi");
    printf("val=%d\n", val);
    for(i = 0; i < 4; i++)
        printf("sstep_buf2[%d] = %d\n", i, sstep_buf2[i]);
}

/* self modifying code test */
uint8_t code[] = {
    0xb8, 0x1, 0x00, 0x00, 0x00, /* movl $1, %eax */
    0xc3, /* ret */
};

asm(".section \".data\"\n"
    "smc_code2:\n"
    "movl 4(%esp), %eax\n"
    "movl %eax, smc_patch_addr2 + 1\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "nop\n"
    "smc_patch_addr2:\n"
    "movl $1, %eax\n"
    "ret\n"
    ".previous\n"
    );

typedef int FuncType(void);
extern int smc_code2(int);
void test_self_modifying_code(void)
{
    int i;
    printf("self modifying code:\n");
    printf("func1 = 0x%x\n", ((FuncType *)code)());
    for(i = 2; i <= 4; i++) {
        code[1] = i;
        printf("func%d = 0x%x\n", i, ((FuncType *)code)());
    }

    /* more difficult test : the modified code is just after the
       modifying instruction. It is forbidden in Intel specs, but it
       is used by old DOS programs */
    for(i = 2; i <= 4; i++) {
        printf("smc_code2(%d) = %d\n", i, smc_code2(i));
    }
}
#endif

long enter_stack[4096];

#if defined(__x86_64__)
#define RSP "%%rsp"
#define RBP "%%rbp"
#else
#define RSP "%%esp"
#define RBP "%%ebp"
#endif

#if !defined(__x86_64__)
/* causes an infinite loop, disable it for now.  */
#define TEST_ENTER(size, stack_type, level)
#else
#define TEST_ENTER(size, stack_type, level)\
{\
    long esp_save, esp_val, ebp_val, ebp_save, i;\
    stack_type *ptr, *stack_end, *stack_ptr;\
    memset(enter_stack, 0, sizeof(enter_stack));\
    stack_end = stack_ptr = (stack_type *)(enter_stack + 4096);\
    ebp_val = (long)stack_ptr;\
    for(i=1;i<=32;i++)\
       *--stack_ptr = i;\
    esp_val = (long)stack_ptr;\
    asm("mov " RSP ", %[esp_save]\n"\
        "mov " RBP ", %[ebp_save]\n"\
        "mov %[esp_val], " RSP "\n"\
        "mov %[ebp_val], " RBP "\n"\
        "enter" size " $8, $" #level "\n"\
        "mov " RSP ", %[esp_val]\n"\
        "mov " RBP ", %[ebp_val]\n"\
        "mov %[esp_save], " RSP "\n"\
        "mov %[ebp_save], " RBP "\n"\
        : [esp_save] "=r" (esp_save),\
        [ebp_save] "=r" (ebp_save),\
        [esp_val] "=r" (esp_val),\
        [ebp_val] "=r" (ebp_val)\
        :  "[esp_val]" (esp_val),\
        "[ebp_val]" (ebp_val));\
    printf("level=%d:\n", level);\
    printf("esp_val=" FMTLX "\n", esp_val - (long)stack_end);\
    printf("ebp_val=" FMTLX "\n", ebp_val - (long)stack_end);\
    for(ptr = (stack_type *)esp_val; ptr < stack_end; ptr++)\
        printf(FMTLX "\n", (long)ptr[0]);\
}
#endif

static void test_enter(void)
{
#if defined(__x86_64__)
    TEST_ENTER("q", uint64_t, 0);
    TEST_ENTER("q", uint64_t, 1);
    TEST_ENTER("q", uint64_t, 2);
    TEST_ENTER("q", uint64_t, 31);
#else
    TEST_ENTER("l", uint32_t, 0);
    TEST_ENTER("l", uint32_t, 1);
    TEST_ENTER("l", uint32_t, 2);
    TEST_ENTER("l", uint32_t, 31);
#endif

    TEST_ENTER("w", uint16_t, 0);
    TEST_ENTER("w", uint16_t, 1);
    TEST_ENTER("w", uint16_t, 2);
    TEST_ENTER("w", uint16_t, 31);
}

#ifdef TEST_SSE

typedef int __m64 __attribute__ ((vector_size(8)));
typedef float __m128 __attribute__ ((vector_size(16)));

typedef union {
    double d[2];
    float s[4];
    uint32_t l[4];
    uint64_t q[2];
    __m128 dq;
} XMMReg;

static uint64_t __attribute__((aligned(16))) test_values[4][2] = {
    { 0x456723c698694873, 0xdc515cff944a58ec },
    { 0x1f297ccd58bad7ab, 0x41f21efba9e3e146 },
    { 0x007c62c2085427f8, 0x231be9e8cde7438d },
    { 0x0f76255a085427f8, 0xc233e9e8c4c9439a },
};

#define SSE_OP(op)\
{\
    asm volatile (#op " %2, %0" : "=x" (r.dq) : "0" (a.dq), "x" (b.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " b=" FMT64X "" FMT64X " r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           b.q[1], b.q[0],\
           r.q[1], r.q[0]);\
}

#define SSE_OP2(op)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    a.q[1] = test_values[2*i][1];\
    b.q[0] = test_values[2*i+1][0];\
    b.q[1] = test_values[2*i+1][1];\
    SSE_OP(op);\
    }\
}

#define MMX_OP2(op)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    b.q[0] = test_values[2*i+1][0];\
    asm volatile (#op " %2, %0" : "=y" (r.q[0]) : "0" (a.q[0]), "y" (b.q[0]));\
    printf("%-9s: a=" FMT64X " b=" FMT64X " r=" FMT64X "\n",\
           #op,\
           a.q[0],\
           b.q[0],\
           r.q[0]);\
    }\
    SSE_OP2(op);\
}


#define SHUF_OP_MMX(op, ib)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    b.q[0] = test_values[2*i+1][0];\
    asm volatile (#op " $" #ib ", %2, %0" : "=y" (r.q[0]) : "0" (a.q[0]), "y" (b.q[0])); \
    printf("%-9s: a=" FMT64X " b=" FMT64X " ib=%02x r=" FMT64X "\n",\
           #op,\
           a.q[0],\
           b.q[0],\
           ib,\
           r.q[0]);\
    }\
}

#define SHUF_OP(op, ib)\
{\
    a.q[0] = test_values[0][0];\
    a.q[1] = test_values[0][1];\
    b.q[0] = test_values[1][0];\
    b.q[1] = test_values[1][1];\
    asm volatile (#op " $" #ib ", %2, %0" : "=x" (r.dq) : "0" (a.dq), "x" (b.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " b=" FMT64X "" FMT64X " ib=%02x r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           b.q[1], b.q[0],\
           ib,\
           r.q[1], r.q[0]);\
}

#define PSHUF_OP(op, ib)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    a.q[1] = test_values[2*i][1];\
    asm volatile (#op " $" #ib ", %1, %0" : "=x" (r.dq) : "x" (a.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " ib=%02x r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           ib,\
           r.q[1], r.q[0]);\
    }\
}

// To use mm0-7 registers instead of xmm registers
#define SHIFT_IM_MMX(op, ib)                        \
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    asm volatile (#op " $" #ib ", %0" : "=y" (r.q[0]) : "0" (a.q[0]));\
    printf("%-9s: a=" FMT64X " ib=%02x r=" FMT64X "\n",\
           #op,\
           a.q[0],\
           ib,\
           r.q[0]);\
    }\
}

#define SHIFT_IM(op, ib)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    a.q[1] = test_values[2*i][1];\
    asm volatile (#op " $" #ib ", %0" : "=x" (r.dq) : "0" (a.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " ib=%02x r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           ib,\
           r.q[1], r.q[0]);\
    }\
}

#define SHIFT_REG_MMX(op, ib)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    b.q[0] = ib;\
    asm volatile (#op " %2, %0" : "=y" (r.q[0]) : "0" (a.q[0]), "y" (b.q[0]));\
    printf("%-9s: a=" FMT64X " b=" FMT64X " ib=%02llx r=" FMT64X "\n",\
           #op,\
           a.q[0],\
           b.q[0],\
           (uint64_t)ib,\
           r.q[0]);\
    }\
}

// To use mm0-7 registers instead of xmm registers
#define SHIFT_OP_MMX(op, ib)\
{\
    SHIFT_IM_MMX(op, ib);\
    SHIFT_REG_MMX(op, ib);\
}

#define SHIFT_REG(op, ib)\
{\
    int i;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    a.q[1] = test_values[2*i][1];\
    b.q[0] = ib;\
    b.q[1] = 0;\
    asm volatile (#op " %2, %0" : "=x" (r.dq) : "0" (a.dq), "x" (b.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " b=" FMT64X "" FMT64X " r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           b.q[1], b.q[0],\
           r.q[1], r.q[0]);\
    }\
}


#define SHIFT_OP(op, ib)\
{\
    SHIFT_OP_MMX(op, ib)\
    SHIFT_IM(op, ib);\
    SHIFT_REG(op, ib);\
}

#define MOVMSK(op)\
{\
    int i, reg;\
    for(i=0;i<sizeof(test_values)/sizeof(uint64_t)/4;i++) {\
    a.q[0] = test_values[2*i][0];\
    a.q[1] = test_values[2*i][1];\
    asm volatile (#op " %1, %0" : "=r" (reg) : "x" (a.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " r=%08x\n",\
           #op,\
           a.q[1], a.q[0],\
           reg);\
    }\
}

#define SSE_OPS(a) \
SSE_OP(a ## ps);\
SSE_OP(a ## ss);

#define SSE_OPD(a) \
SSE_OP(a ## pd);\
SSE_OP(a ## sd);

#define SSE_COMI(op, field)\
{\
    unsigned long eflags;\
    XMMReg a, b;\
    a.field[0] = a1;\
    b.field[0] = b1;\
    asm volatile (#op " %2, %1\n"\
        "pushf\n"\
        "pop %0\n"\
        : "=rm" (eflags)\
        : "x" (a.dq), "x" (b.dq));\
    printf("%-9s: a=%f b=%f cc=%04lx\n",\
           #op, a1, b1,\
           eflags & (CC_C | CC_P | CC_Z | CC_S | CC_O | CC_A));\
}

void test_sse_comi(double a1, double b1)
{
    SSE_COMI(ucomiss, s);
    SSE_COMI(ucomisd, d);
    SSE_COMI(comiss, s);
    SSE_COMI(comisd, d);
}

#define CVT_OP_XMM(op)\
{\
    asm volatile (#op " %1, %0" : "+x" (r.dq) : "x" (a.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           r.q[1], r.q[0]);\
}

/* Force %xmm0 usage to avoid the case where both register index are 0
   to test instruction decoding more extensively */
#define CVT_OP_XMM2MMX(op)\
{\
    asm volatile (#op " %1, %0" : "=y" (r.q[0]) : "x" (a.dq) \
                  : "%xmm0"); \
    asm volatile("emms\n"); \
    printf("%-9s: a=" FMT64X "" FMT64X " r=" FMT64X "\n",\
           #op,\
           a.q[1], a.q[0],\
           r.q[0]);\
}

#define CVT_OP_MMX2XMM(op)\
{\
    asm volatile (#op " %1, %0" : "=x" (r.dq) : "y" (a.q[0]));\
    asm volatile("emms\n"); \
    printf("%-9s: a=" FMT64X " r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.q[0],\
           r.q[1], r.q[0]);\
}

#define CVT_OP_REG2XMM(op)\
{\
    asm volatile (#op " %1, %0" : "+x" (r.dq) : "r" (a.l[0]));\
    printf("%-9s: a=%08x r=" FMT64X "" FMT64X "\n",\
           #op,\
           a.l[0],\
           r.q[1], r.q[0]);\
}

#define CVT_OP_XMM2REG(op)\
{\
    asm volatile (#op " %1, %0" : "=r" (r.l[0]) : "x" (a.dq));\
    printf("%-9s: a=" FMT64X "" FMT64X " r=%08x\n",\
           #op,\
           a.q[1], a.q[0],\
           r.l[0]);\
}

struct fpxstate {
    uint16_t fpuc;
    uint16_t fpus;
    uint16_t fptag;
    uint16_t fop;
    uint32_t fpuip;
    uint16_t cs_sel;
    uint16_t dummy0;
    uint32_t fpudp;
    uint16_t ds_sel;
    uint16_t dummy1;
    uint32_t mxcsr;
    uint32_t mxcsr_mask;
    uint8_t fpregs1[8 * 16];
    uint8_t xmm_regs[8 * 16];
    uint8_t dummy2[224];
};

static struct fpxstate fpx_state __attribute__((aligned(16)));
static struct fpxstate fpx_state2 __attribute__((aligned(16)));

void test_fxsave(void)
{
    struct fpxstate *fp = &fpx_state;
    struct fpxstate *fp2 = &fpx_state2;
    int i, nb_xmm;
    XMMReg a, b;
    a.q[0] = test_values[0][0];
    a.q[1] = test_values[0][1];
    b.q[0] = test_values[1][0];
    b.q[1] = test_values[1][1];

    asm("movdqa %2, %%xmm0\n"
        "movdqa %3, %%xmm7\n"
#if defined(__x86_64__)
        "movdqa %2, %%xmm15\n"
#endif
        " fninit\n"
        " fld1\n"
        " fld1\n"
        " fldz\n"
        " fxsave %0\n"
        " fxrstor %0\n"
        " fxsave %1\n"
        " fninit\n"
        : "=m" (*(uint32_t *)fp2), "=m" (*(uint32_t *)fp)
        : "m" (a), "m" (b));
    printf("fpuc=%04x\n", fp->fpuc);
    printf("fpus=%04x\n", fp->fpus);
    printf("fptag=%04x\n", fp->fptag);
    for(i = 0; i < 3; i++) {
        printf("ST%d: " FMT64X " %04x\n",
               i,
               *(uint64_t *)&fp->fpregs1[i * 16],
               *(uint16_t *)&fp->fpregs1[i * 16 + 8]);
    }
    printf("mxcsr=%08x\n", fp->mxcsr & 0x1f80);
#if defined(__x86_64__)
    nb_xmm = 16;
#else
    nb_xmm = 8;
#endif
    for(i = 0; i < nb_xmm; i++) {
        printf("xmm%d: " FMT64X "" FMT64X "\n",
               i,
               *(uint64_t *)&fp->xmm_regs[i * 16],
               *(uint64_t *)&fp->xmm_regs[i * 16 + 8]);
    }
}

void test_sse(void)
{
    XMMReg r, a, b;
    int i;

    MMX_OP2(punpcklbw);
    MMX_OP2(punpcklwd);
    MMX_OP2(punpckldq);
    MMX_OP2(packsswb);
    MMX_OP2(pcmpgtb);
    MMX_OP2(pcmpgtw);
    MMX_OP2(pcmpgtd);
    MMX_OP2(packuswb);
    MMX_OP2(punpckhbw);
    MMX_OP2(punpckhwd);
    MMX_OP2(punpckhdq);
    MMX_OP2(packssdw);
    MMX_OP2(pcmpeqb);
    MMX_OP2(pcmpeqw);
    MMX_OP2(pcmpeqd);

    MMX_OP2(paddq);
    MMX_OP2(pmullw);
    MMX_OP2(psubusb);
    MMX_OP2(psubusw);
    MMX_OP2(pminub);
    MMX_OP2(pand);
    MMX_OP2(paddusb);
    MMX_OP2(paddusw);
    MMX_OP2(pmaxub);
    MMX_OP2(pandn);

    MMX_OP2(pmulhuw);
    MMX_OP2(pmulhw);

    MMX_OP2(psubsb);
    MMX_OP2(psubsw);
    MMX_OP2(pminsw);
    MMX_OP2(por);
    MMX_OP2(paddsb);
    MMX_OP2(paddsw);
    MMX_OP2(pmaxsw);
    MMX_OP2(pxor);
    MMX_OP2(pmuludq);
    MMX_OP2(pmaddwd);
    MMX_OP2(psadbw);
    MMX_OP2(psubb);
    MMX_OP2(psubw);
    MMX_OP2(psubd);
    MMX_OP2(psubq);
    MMX_OP2(paddb);
    MMX_OP2(paddw);
    MMX_OP2(psrlw);
    MMX_OP2(paddd);

    MMX_OP2(pavgb);
    MMX_OP2(pavgw);

    asm volatile ("pinsrw $1, %1, %0" : "+y" (r.q[0]) : "r" (0x12345678));
    printf("%-9s: r=" FMT64X "\n", "pinsrw", r.q[0]);

    asm volatile ("pinsrw $5, %1, %0" : "+x" (r.dq) : "r" (0x12345678));
    printf("%-9s: r=" FMT64X "" FMT64X "\n", "pinsrw", r.q[1], r.q[0]);

    a.q[0] = test_values[0][0];
    a.q[1] = test_values[0][1];
    asm volatile ("pextrw $1, %1, %0" : "=r" (r.l[0]) : "y" (a.q[0]));
    printf("%-9s: r=%08x\n", "pextrw", r.l[0]);

    asm volatile ("pextrw $5, %1, %0" : "=r" (r.l[0]) : "x" (a.dq));
    printf("%-9s: r=%08x\n", "pextrw", r.l[0]);

    asm volatile ("pmovmskb %1, %0" : "=r" (r.l[0]) : "y" (a.q[0]));
    printf("%-9s: r=%08x\n", "pmovmskb", r.l[0]);

    asm volatile ("pmovmskb %1, %0" : "=r" (r.l[0]) : "x" (a.dq));
    printf("%-9s: r=%08x\n", "pmovmskb", r.l[0]);

    {
        r.q[0] = -1;
        r.q[1] = -1;

        a.q[0] = test_values[0][0];
        a.q[1] = test_values[0][1];
        b.q[0] = test_values[1][0];
        b.q[1] = test_values[1][1];
        asm volatile("maskmovq %1, %0" :
                     : "y" (a.q[0]), "y" (b.q[0]), "D" (&r)
                     : "memory");
        printf("%-9s: r=" FMT64X " a=" FMT64X " b=" FMT64X "\n",
               "maskmov",
               r.q[0],
               a.q[0],
               b.q[0]);
        asm volatile("maskmovdqu %1, %0" :
                     : "x" (a.dq), "x" (b.dq), "D" (&r)
                     : "memory");
        printf("%-9s: r=" FMT64X "" FMT64X " a=" FMT64X "" FMT64X " b=" FMT64X "" FMT64X "\n",
               "maskmov",
               r.q[1], r.q[0],
               a.q[1], a.q[0],
               b.q[1], b.q[0]);
    }

    asm volatile ("emms");

    SSE_OP2(punpcklqdq);
    SSE_OP2(punpckhqdq);
    SSE_OP2(andps);
    SSE_OP2(andpd);
    SSE_OP2(andnps);
    SSE_OP2(andnpd);
    SSE_OP2(orps);
    SSE_OP2(orpd);
    SSE_OP2(xorps);
    SSE_OP2(xorpd);

    SSE_OP2(unpcklps);
    SSE_OP2(unpcklpd);
    SSE_OP2(unpckhps);
    SSE_OP2(unpckhpd);

    SHUF_OP(shufps, 0x78);
    SHUF_OP(shufpd, 0x02);
    SHUF_OP_MMX(pshufw, 0x78);
    SHUF_OP_MMX(pshufw, 0x02);

    PSHUF_OP(pshufd, 0x78);
    PSHUF_OP(pshuflw, 0x78);
    PSHUF_OP(pshufhw, 0x78);

    SHIFT_OP(psrlw, 0);
    SHIFT_OP(psrlw, 7);
    SHIFT_OP(psrlw, 15);
    SHIFT_OP(psrlw, 16);
    SHIFT_REG(psrlw, 0x100000000);
    SHIFT_REG_MMX(psrlw, 0x100000000);

    SHIFT_OP(psraw, 0);
    SHIFT_OP(psraw, 7);
    SHIFT_OP(psraw, 15);
    SHIFT_OP(psraw, 16);
    SHIFT_REG(psraw, 0x100000000);
    SHIFT_REG_MMX(psraw, 0x100000000);

    SHIFT_OP(psllw, 0);
    SHIFT_OP(psllw, 7);
    SHIFT_OP(psllw, 15);
    SHIFT_OP(psllw, 16);
    SHIFT_REG(psllw, 0x100000000);
    SHIFT_REG_MMX(psllw, 0x100000000);

    SHIFT_OP(psrld, 0);
    SHIFT_OP(psrld, 7);
    SHIFT_OP(psrld, 31);
    SHIFT_OP(psrld, 32);
    SHIFT_REG(psrld, 0x100000000);
    SHIFT_REG_MMX(psrld, 0x100000000);

    SHIFT_OP(psrad, 0);
    SHIFT_OP(psrad, 7);
    SHIFT_OP(psrad, 31);
    SHIFT_OP(psrad, 32);
    SHIFT_REG(psrad, 0x100000000);
    SHIFT_REG_MMX(psrad, 0x100000000);

    SHIFT_OP(pslld, 0);
    SHIFT_OP(pslld, 7);
    SHIFT_OP(pslld, 31);
    SHIFT_OP(pslld, 32);
    SHIFT_REG(pslld, 0x100000000);
    SHIFT_REG_MMX(pslld, 0x100000000);

    SHIFT_OP(psrlq, 0);
    SHIFT_OP(psrlq, 7);
    SHIFT_OP(psrlq, 32);
    SHIFT_OP(psrlq, 63);
    SHIFT_OP(psrlq, 64);
    SHIFT_REG(psrlq, 0x100000000);
    SHIFT_REG_MMX(psrlq, 0x100000000);

    SHIFT_OP(psllq, 0);
    SHIFT_OP(psllq, 7);
    SHIFT_OP(psllq, 32);
    SHIFT_OP(psllq, 63);
    SHIFT_OP(psllq, 64);
    SHIFT_REG(psllq, 0x100000000);
    SHIFT_REG_MMX(psllq, 0x100000000);

    // byte-wise shifts
    SHIFT_IM(psrldq, 0);
    SHIFT_IM(psrldq, 1);
    SHIFT_IM(psrldq, 7);
    SHIFT_IM(psrldq, 8);
    SHIFT_IM(psrldq, 11);
    SHIFT_IM(psrldq, 15);
    SHIFT_IM(psrldq, 16);

    SHIFT_IM(pslldq, 0);
    SHIFT_IM(pslldq, 1);
    SHIFT_IM(pslldq, 7);
    SHIFT_IM(pslldq, 8);
    SHIFT_IM(pslldq, 11);
    SHIFT_IM(pslldq, 15);
    SHIFT_IM(pslldq, 16);

    MOVMSK(movmskps);
    MOVMSK(movmskpd);

    /* FPU specific ops */
    {
        uint32_t mxcsr;
        asm volatile("stmxcsr %0" : "=m" (mxcsr));
        printf("mxcsr=%08x\n", mxcsr & 0x1f80);
        asm volatile("ldmxcsr %0" : : "m" (mxcsr));
    }

    asm volatile ("emms");

    test_sse_comi(2, -1);
    test_sse_comi(2, 2);
    test_sse_comi(2, 3);
    test_sse_comi(2, q_nan.d);
    test_sse_comi(q_nan.d, -1);

    for(i = 0; i < 2; i++) {
        a.s[0] = 2.7;
        a.s[1] = 3.4;
        a.s[2] = 4;
        a.s[3] = -6.3;
        b.s[0] = 45.7;
        b.s[1] = 353.4;
        b.s[2] = 4;
        b.s[3] = 56.3;
        if (i == 1) {
            a.s[0] = q_nan.d;
            b.s[3] = q_nan.d;
        }

        SSE_OPS(add);
        SSE_OPS(mul);
        SSE_OPS(sub);
        SSE_OPS(min);
        SSE_OPS(div);
        SSE_OPS(max);
        SSE_OPS(sqrt);
        SSE_OPS(cmpeq);
        SSE_OPS(cmplt);
        SSE_OPS(cmple);
        SSE_OPS(cmpunord);
        SSE_OPS(cmpneq);
        SSE_OPS(cmpnlt);
        SSE_OPS(cmpnle);
        SSE_OPS(cmpord);


        a.d[0] = 2.7;
        a.d[1] = -3.4;
        b.d[0] = 45.7;
        b.d[1] = -53.4;
        if (i == 1) {
            a.d[0] = q_nan.d;
            b.d[1] = q_nan.d;
        }
        SSE_OPD(add);
        SSE_OPD(mul);
        SSE_OPD(sub);
        SSE_OPD(min);
        SSE_OPD(div);
        SSE_OPD(max);
        SSE_OPD(sqrt);
        SSE_OPD(cmpeq);
        SSE_OPD(cmplt);
        SSE_OPD(cmple);
        SSE_OPD(cmpunord);
        SSE_OPD(cmpneq);
        SSE_OPD(cmpnlt);
        SSE_OPD(cmpnle);
        SSE_OPD(cmpord);
    }

    // approximating instructions: Pick some nice round values
    a.s[0] = 1024.0;
    a.s[1] = 1.0 / 256.0;
    b.s[0] = 1024.0;
    b.s[1] = 1.0 / 256.0;
    SSE_OPS(rsqrt);
    SSE_OPS(rcp);

    /* float to float/int */
    a.s[0] = 2.7;
    a.s[1] = 3.4;
    a.s[2] = 4;
    a.s[3] = -6.3;
    CVT_OP_XMM(cvtps2pd);
    CVT_OP_XMM(cvtss2sd);
    CVT_OP_XMM2MMX(cvtps2pi);
    CVT_OP_XMM2MMX(cvttps2pi);
    CVT_OP_XMM2REG(cvtss2si);
    CVT_OP_XMM2REG(cvttss2si);
    CVT_OP_XMM(cvtps2dq);
    CVT_OP_XMM(cvttps2dq);

    a.d[0] = 2.6;
    a.d[1] = -3.4;
    CVT_OP_XMM(cvtpd2ps);
    CVT_OP_XMM(cvtsd2ss);
    CVT_OP_XMM2MMX(cvtpd2pi);
    CVT_OP_XMM2MMX(cvttpd2pi);
    CVT_OP_XMM2REG(cvtsd2si);
    CVT_OP_XMM2REG(cvttsd2si);
    CVT_OP_XMM(cvtpd2dq);
    CVT_OP_XMM(cvttpd2dq);

    /* sse/mmx moves */
    CVT_OP_XMM2MMX(movdq2q);
    CVT_OP_MMX2XMM(movq2dq);

    /* int to float */
    a.l[0] = -6;
    a.l[1] = 2;
    a.l[2] = 100;
    a.l[3] = -60000;
    CVT_OP_MMX2XMM(cvtpi2ps);
    CVT_OP_MMX2XMM(cvtpi2pd);
    CVT_OP_REG2XMM(cvtsi2ss);
    CVT_OP_REG2XMM(cvtsi2sd);
    CVT_OP_XMM(cvtdq2ps);
    CVT_OP_XMM(cvtdq2pd);
    /* XXX: test PNI insns */
#if 0
    SSE_OP2(movshdup);
#endif
    asm volatile ("emms");
}

#endif

#define TEST_CONV_RAX(op)\
{\
    unsigned long a, r;\
    a = i2l(0x8234a6f8);\
    r = a;\
    asm volatile(#op : "=a" (r) : "0" (r));\
    printf("%-10s A=" FMTLX " R=" FMTLX "\n", #op, a, r);\
}

#define TEST_CONV_RAX_RDX(op)\
{\
    unsigned long a, d, r, rh;                   \
    a = i2l(0x8234a6f8);\
    d = i2l(0x8345a1f2);\
    r = a;\
    rh = d;\
    asm volatile(#op : "=a" (r), "=d" (rh) : "0" (r), "1" (rh));   \
    printf("%-10s A=" FMTLX " R=" FMTLX ":" FMTLX "\n", #op, a, r, rh);  \
}

void test_conv(void)
{
    TEST_CONV_RAX(cbw);
    TEST_CONV_RAX(cwde);
#if defined(__x86_64__)
    TEST_CONV_RAX(cdqe);
#endif

    TEST_CONV_RAX_RDX(cwd);
    TEST_CONV_RAX_RDX(cdq);
#if defined(__x86_64__)
    TEST_CONV_RAX_RDX(cqo);
#endif

    {
        unsigned long a, r;
        a = i2l(0x12345678);
        asm volatile("bswapl %k0" : "=r" (r) : "0" (a));
        printf("%-10s: A=" FMTLX " R=" FMTLX "\n", "bswapl", a, r);
    }
#if defined(__x86_64__)
    {
        unsigned long a, r;
        a = i2l(0x12345678);
        asm volatile("bswapq %0" : "=r" (r) : "0" (a));
        printf("%-10s: A=" FMTLX " R=" FMTLX "\n", "bswapq", a, r);
    }
#endif
}


void byte_read(uint8_t* buffer, uint16_t offset, size_t num_bytes)
{
    uint64_t v1 = 0;
    for(size_t i = 0; i < num_bytes && i < 8; i++)
    {
        if(setjmp(jmp_env) == 0)
        {
            v1 |= (uint64_t)buffer[offset + i] << (i * 8);
        }
    }

    uint64_t v2 = 0;
    for(size_t i = 8; i < num_bytes; i++)
    {
        if(setjmp(jmp_env) == 0)
        {
            v2 |= (uint64_t)buffer[offset + i] << ((i - 8) * 8);
        }

    }

    if(num_bytes > 8)
    {
        printf("%-12s: offset=%x value=%08llx%08llx\n", "byte_r", offset, v2, v1);
    }
    else
    {
        printf("%-12s: offset=%x value=%llx\n", "byte_r", offset, v1);
    }
}

uint64_t seq_counter = 0x8070605040302010;
uint64_t get_seq64()
{
    seq_counter += 0x0101010101010101;
    return seq_counter;
}

void byte_write_seq(uint8_t* target, uint16_t offset, size_t num_bytes)
{
    uint64_t v = get_seq64();
    if(num_bytes < 8) v &= (1LL << (num_bytes * 8)) - 1;

    for(size_t i = 0; i < num_bytes; i++)
    {
        if(setjmp(jmp_env) == 0)
        {
            target[offset + i] = (v >> (i * 8 % 64)) & 0xFF;
        }
    }

    if(num_bytes > 8)
    {
        printf("%-12s: offset=%x value=%08llx%08llx\n", "byte_w", offset, v, v);
    }
    else
    {
        printf("%-12s: offset=%x value=%llx\n", "byte_w", offset, v);
    }
}

#define GENERATE_CHUNK_READ(INSTR, BITS, CONSTR)                    \
    void chunk_read ## BITS(uint8_t* addr, uint16_t offset)         \
    {                                                               \
        uint ## BITS ## _t chunk = 0;                               \
        if(setjmp(jmp_env) == 0) {                                  \
            asm volatile(INSTR " %1, %0" :                          \
                         "=" CONSTR (chunk) :                       \
                         "m" (*(addr + offset)), "0" (chunk));      \
        }                                                           \
        printf("%-12s: offset=%x value=%" PRIx ## BITS "\n",        \
               "chunk" #BITS "_r",                                  \
               offset,                                              \
               chunk);                                              \
    }

#define GENERATE_CHUNK_WRITE(INSTR, BITS, CONSTR)                   \
    void chunk_write ## BITS(uint8_t* addr, uint16_t offset)        \
    {                                                               \
        uint ## BITS ## _t chunk = get_seq64();                     \
        if(setjmp(jmp_env) == 0) {                                  \
            asm volatile(INSTR " %0, %1" :                          \
                         "=" CONSTR (chunk) :                       \
                         "m" (*(addr + offset)), "0" (chunk));      \
        }                                                           \
        printf("%-12s: offset=%x value=%" PRIx ## BITS "\n",        \
               "chunk" #BITS "_w",                                  \
               offset,                                              \
               chunk);                                              \
    }

#define GENERATE_CHUNK_FNS(INSTR, BITS, CONSTR)                   \
    GENERATE_CHUNK_READ(INSTR, BITS, CONSTR)                      \
    GENERATE_CHUNK_WRITE(INSTR, BITS, CONSTR)

#define TEST_CHUNK_READ(BITS, ADDR, OFFSET)         \
    byte_write_seq(ADDR, OFFSET, (BITS) >> 3);      \
    chunk_read ## BITS(ADDR, OFFSET);

#define TEST_CHUNK_WRITE(BITS, ADDR, OFFSET)        \
    if(!skip_write_test) {                          \
        byte_write_seq(ADDR, OFFSET, (BITS) >> 3);  \
        mask_pf_address = 1;                        \
        chunk_write ## BITS(ADDR, OFFSET);          \
        mask_pf_address = 0;                        \
        byte_read(ADDR, OFFSET, (BITS) >> 3);       \
    }

#define TEST_CHUNK_READ_WRITE(BITS, ADDR, OFFSET)         \
    if(BITS <= 32) {                                      \
        byte_write_seq(ADDR, OFFSET, (BITS) >> 3);        \
        mask_pf_error = 1;                                \
        mask_pf_address = 1;                              \
        chunk_read_write ## BITS(ADDR, OFFSET);           \
        mask_pf_address = 0;                              \
        mask_pf_error = 0;                                \
        byte_read(ADDR, OFFSET, (BITS) >> 3);             \
    }

// Based on BITS, we calculate the offset where cross-page reads/writes would begin
#define TEST_CROSS_PAGE(BITS, ADDR)                     \
    for(size_t offset = (PAGE_SIZE + 1 - (BITS >> 3));  \
        offset < PAGE_SIZE; offset++)                   \
    {                                                   \
        TEST_CHUNK_READ(BITS, ADDR, offset);            \
        TEST_CHUNK_WRITE(BITS, ADDR, offset);           \
        TEST_CHUNK_READ_WRITE(BITS, ADDR, offset);      \
    }

GENERATE_CHUNK_FNS("movw", 16, "r");
GENERATE_CHUNK_FNS("mov", 32, "r");

#ifdef TEST_SSE
GENERATE_CHUNK_FNS("movq", 64, "y");

void chunk_read_write16(uint8_t* addr, uint16_t offset)
{
    uint16_t chunk = get_seq64();
    if(setjmp(jmp_env) == 0)
    {
        asm volatile("addw %0, %1" :
                     "=r" (chunk) :
                     "m" (*(addr + offset)), "0" (chunk));
    }
    printf("%-12s: offset=%x value=%" PRIx16 "\n",
           "chunk16_rw",
           offset,
           chunk);
}

void chunk_read_write32(uint8_t* addr, uint16_t offset)
{
    uint32_t chunk = get_seq64();
    if(setjmp(jmp_env) == 0)
    {
        asm volatile("add %0, %1" :
                     "=r" (chunk) :
                     "m" (*(addr + offset)), "0" (chunk));
    }
    printf("%-12s: offset=%x value=%" PRIx32 "\n",
           "chunk32_rw",
           offset,
           chunk);
}

// No 64 or 128-bit read-write x86 instructions support a memory address as the destination
void chunk_read_write64(uint8_t* addr, uint16_t offset)
{
    UNUSED(addr);
    UNUSED(offset);
}

void chunk_read_write128(uint8_t* addr, uint16_t offset)
{
    UNUSED(addr);
    UNUSED(offset);
}


void chunk_read128(uint8_t* addr, uint16_t offset)
{
    XMMReg chunk;
    chunk.q[0] = chunk.q[1] = 0.0;
    if(setjmp(jmp_env) == 0)
    {
        asm volatile("movdqu %1, %0" :
                     "=x" (chunk.dq) :
                     "m" (*(addr + offset)), "0" (chunk.dq)
            );
    }
    printf("%-12s: offset=%x value=" FMT64X FMT64X "\n",
           "chunk128_r",
           offset,
           chunk.q[1],
           chunk.q[0]);
}

void chunk_write128(uint8_t* addr, uint16_t offset)
{
    XMMReg chunk;
    chunk.q[0] = get_seq64();
    chunk.q[1] = get_seq64();
    if(setjmp(jmp_env) == 0)
    {
        asm volatile("movdqu %0, %1" :
                     "=x" (chunk.dq) :
                     "m" (*(addr + offset)), "0" (chunk.dq)
            );
    }
    printf("%-12s: offset=%x value=" FMT64X FMT64X "\n",
           "chunk128_w",
           offset,
           chunk.q[1],
           chunk.q[0]);
}
#endif

void* const TEST_ADDRESS = (void *)0x70000000;
uint8_t* first_page = NULL;
uint8_t* second_page = NULL;
uint8_t* throwaway_page = NULL;

void setup_pages(int first_page_type, int second_page_type)
{
    const int prot = PROT_READ | PROT_WRITE;

    if(first_page_type)
    {
        // mmap 2 consecutive pages
        first_page = mmap(TEST_ADDRESS, 2 * PAGE_SIZE, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        assert(first_page == TEST_ADDRESS);
    }
    else
    {
        first_page = NULL;
    }

    // throwaway mmap to reduce likelhood of first_page and second_page mapping to consecutive physical frames
    throwaway_page = mmap(NULL, PAGE_SIZE, prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    assert(throwaway_page != MAP_FAILED && throwaway_page != TEST_ADDRESS && throwaway_page != TEST_ADDRESS + PAGE_SIZE);

    if(second_page_type)
    {
        second_page = mmap(TEST_ADDRESS + PAGE_SIZE, PAGE_SIZE, prot, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
        assert(second_page == TEST_ADDRESS + PAGE_SIZE);
    }
    else
    {
        munmap(TEST_ADDRESS + PAGE_SIZE, PAGE_SIZE);
        second_page = NULL;
    }

    // Trigger page-faults causing virtual pages to be allocated to physical frames
    if(first_page != NULL) memset(first_page, 0x42, PAGE_SIZE);
    memset(throwaway_page, 0x42, PAGE_SIZE);
    if(second_page != NULL) memset(second_page, 0x42, PAGE_SIZE);

    if(first_page_type == PROT_READ)
    {
        mprotect(first_page, PAGE_SIZE, PROT_READ);
    }

    if(second_page_type == PROT_READ)
    {
        mprotect(second_page, PAGE_SIZE, PROT_READ);
    }
}

void free_pages()
{
    munmap(TEST_ADDRESS, PAGE_SIZE);
    munmap(TEST_ADDRESS + PAGE_SIZE, PAGE_SIZE);
    munmap(throwaway_page, PAGE_SIZE);
}

// XXX: Workarounds for qemu bugs: Can be removed when running tests in kvm mode
int mask_pf_error = 0;
int mask_pf_address = 0;
int skip_write_test = 0;

void pagefault_handler(int sig, siginfo_t *info, void *puc)
{
    ucontext_t *uc = puc;

    printf("page fault: addr=0x%08lx err=0x%lx eip=0x%08lx\n",
            (unsigned long)info->si_addr & (mask_pf_address ? ~0xfff : ~0),
            (long)uc->uc_mcontext.gregs[REG_ERR] & (mask_pf_error ? ~2 : ~0),
            (long)uc->uc_mcontext.gregs[REG_EIP]);

    assert(info->si_addr >= TEST_ADDRESS && info->si_addr < TEST_ADDRESS + 2 * PAGE_SIZE);

    longjmp(jmp_env, 1);
}

void test_page_boundaries()
{
    const int prot_rw = PROT_READ | PROT_WRITE;
    const int prot_ronly = PROT_READ;

    setup_pages(prot_rw, prot_rw);

    TEST_CROSS_PAGE(16, TEST_ADDRESS);
    TEST_CROSS_PAGE(32, TEST_ADDRESS);
#ifdef TEST_SSE
    TEST_CROSS_PAGE(64, TEST_ADDRESS);
    TEST_CROSS_PAGE(128, TEST_ADDRESS);
#endif

    struct sigaction act;
    act.sa_sigaction = pagefault_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO | SA_NODEFER;
    sigaction(SIGSEGV, &act, NULL);

    free_pages();
    printf("With non-present page faults in first page:\n");
    setup_pages(0, prot_rw);

    TEST_CROSS_PAGE(16, TEST_ADDRESS);
    TEST_CROSS_PAGE(32, TEST_ADDRESS);
#ifdef TEST_SSE
    TEST_CROSS_PAGE(64, TEST_ADDRESS);
    TEST_CROSS_PAGE(128, TEST_ADDRESS);
#endif

    free_pages();
    printf("With read-only page faults in first page:\n");
    setup_pages(prot_ronly, prot_rw);

    TEST_CROSS_PAGE(16, TEST_ADDRESS);
    TEST_CROSS_PAGE(32, TEST_ADDRESS);
#ifdef TEST_SSE
    TEST_CROSS_PAGE(64, TEST_ADDRESS);
    TEST_CROSS_PAGE(128, TEST_ADDRESS);
#endif

    free_pages();
    printf("With non-present page faults in second page:\n");
    setup_pages(prot_rw, 0);

    TEST_CROSS_PAGE(16, TEST_ADDRESS);
    TEST_CROSS_PAGE(32, TEST_ADDRESS);
#ifdef TEST_SSE
    TEST_CROSS_PAGE(64, TEST_ADDRESS);
    skip_write_test = 1;
    TEST_CROSS_PAGE(128, TEST_ADDRESS);
    skip_write_test = 0;
#endif

    free_pages();
    printf("With read-only page faults in second page:\n");
    setup_pages(prot_rw, prot_ronly);

    TEST_CROSS_PAGE(16, TEST_ADDRESS);
    TEST_CROSS_PAGE(32, TEST_ADDRESS);
#ifdef TEST_SSE
    TEST_CROSS_PAGE(64, TEST_ADDRESS);
    skip_write_test = 1;
    TEST_CROSS_PAGE(128, TEST_ADDRESS);
    skip_write_test = 0;
#endif
}

extern void *__start_initcall;
extern void *__stop_initcall;

int main(int argc, char **argv)
{
    // Uncomment to disable buffering, useful for debugging segfaults
    //setvbuf(stdout, NULL, _IONBF, 0);

    void **ptr;
    void (*func)(void);

    ptr = &__start_initcall;
    while (ptr != &__stop_initcall) {
        func = *ptr++;
        func();
    }
    test_bsx();
    test_popcnt();
    test_mul();
    test_jcc();
    test_loop();
    test_floats();
#if !defined(__x86_64__)
    test_bcd();
#endif
    test_xchg();
    test_string();
    test_misc();
    test_lea();
#ifdef TEST_SEGS
    test_segs();
    test_code16();
#endif
#ifdef TEST_VM86
    test_vm86();
#endif
#if !defined(__x86_64__)
    test_exceptions();
    test_self_modifying_code();
    //test_single_step();
#endif
    test_enter();
    test_conv();
#ifdef TEST_SSE
    test_sse();
    test_fxsave();
#endif
    test_page_boundaries();
    return 0;
}
                                                                                                              source/v64/tests/qemu/test-i386.h                                                                   0000644 0000000 0000000 00000007423 00000000000 013622  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       
#define exec_op glue(exec_, OP)
#define exec_opq glue(glue(exec_, OP), q)
#define exec_opl glue(glue(exec_, OP), l)
#define exec_opw glue(glue(exec_, OP), w)
#define exec_opb glue(glue(exec_, OP), b)

#define EXECOP2(size, rsize, res, s1, flags) \
    asm ("push %4\n\t"\
         "popf\n\t"\
         stringify(OP) size " %" rsize "2, %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=q" (res), "=g" (flags)\
         : "q" (s1), "0" (res), "1" (flags)); \
    printf("%-10s A=" FMTLX " B=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n", \
           stringify(OP) size, s0, s1, res, iflags, flags & CC_MASK);

#define EXECOP1(size, rsize, res, flags) \
    asm ("push %3\n\t"\
         "popf\n\t"\
         stringify(OP) size " %" rsize "0\n\t" \
         "pushf\n\t"\
         "pop %1\n\t"\
         : "=q" (res), "=g" (flags)\
         : "0" (res), "1" (flags)); \
    printf("%-10s A=" FMTLX " R=" FMTLX " CCIN=%04lx CC=%04lx\n", \
           stringify(OP) size, s0, res, iflags, flags & CC_MASK);

#ifdef OP1
#if defined(__x86_64__)
void exec_opq(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP1("q", "", res, flags);
}
#endif

void exec_opl(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP1("l", "k", res, flags);
}

void exec_opw(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP1("w", "w", res, flags);
}

void exec_opb(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP1("b", "b", res, flags);
}
#else
#if defined(__x86_64__)
void exec_opq(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP2("q", "", res, s1, flags);
}
#endif

void exec_opl(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP2("l", "k", res, s1, flags);
}

void exec_opw(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP2("w", "w", res, s1, flags);
}

void exec_opb(long s0, long s1, long iflags)
{
    long res, flags;
    res = s0;
    flags = iflags;
    EXECOP2("b", "b", res, s1, flags);
}
#endif

void exec_op(long s0, long s1)
{
    s0 = i2l(s0);
    s1 = i2l(s1);
#if defined(__x86_64__)
    exec_opq(s0, s1, 0);
#endif
    exec_opl(s0, s1, 0);
    exec_opw(s0, s1, 0);
    exec_opb(s0, s1, 0);
#ifdef OP_CC
#if defined(__x86_64__)
    exec_opq(s0, s1, CC_C);
#endif
    exec_opl(s0, s1, CC_C);
    exec_opw(s0, s1, CC_C);
    exec_opb(s0, s1, CC_C);
#endif
}

void glue(test_, OP)(void)
{
    exec_op(0x12345678, 0x812FADA);
    exec_op(0x12341, 0x12341);
    exec_op(0x12341, -0x12341);
    exec_op(0xffffffff, 0);
    exec_op(0xffffffff, -1);
    exec_op(0xffffffff, 1);
    exec_op(0xffffffff, 2);
    exec_op(0x7fffffff, 0);
    exec_op(0x7fffffff, 1);
    exec_op(0x7fffffff, -1);
    exec_op(0x80000000, -1);
    exec_op(0x80000000, 1);
    exec_op(0x80000000, -2);
    exec_op(0x12347fff, 0);
    exec_op(0x12347fff, 1);
    exec_op(0x12347fff, -1);
    exec_op(0x12348000, -1);
    exec_op(0x12348000, 1);
    exec_op(0x12348000, -2);
    exec_op(0x12347f7f, 0);
    exec_op(0x12347f7f, 1);
    exec_op(0x12347f7f, -1);
    exec_op(0x12348080, -1);
    exec_op(0x12348080, 1);
    exec_op(0x12348080, -2);

    exec_op(0xfffe0080, -1);
    exec_op(0xfffe0080, 1);
    exec_op(0xfffe0080, 0);
    exec_op(0xfffe0080, 0xfffe0080);
    exec_op(0xfffe0080, 0x80);
    exec_op(0xfffe0080, 0x81);
    exec_op(0xfffe0080, 0x10000);
    exec_op(0xfffe0080, 0x20000);
    exec_op(0xfffe0080, 0x1ff7f);
    exec_op(0xfffe0080, 0x1ff80);
    exec_op(0xfffe0080, 0x1ff81);
    exec_op(0xfffe0080, 0x1ffff);


    exec_op(0, 0);
}

void *glue(_test_, OP) __init_call = glue(test_, OP);

#undef OP
#undef OP_CC
                                                                                                                                                                                                                                             source/v64/tests/r1/windows9x.mjs                                                                   0000644 0000000 0000000 00000030057 00000000000 014043  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Windows 98 regressions for the release gate (tools/release_gate.mjs), against
// a baseline build, with the configuration retro-gaming-site uses (256 MiB,
// 16 MiB video memory, no ACPI, NE2K, the v86gl PCI device, C: plus a game
// disk). Every disk is opened read-only (guest writes stay in a RAM overlay).
//
//   BUILD=current  build/libv86.mjs + build/v86.wasm (default)
//   BUILD=site     retro-gaming-site's libv86.js + v86.wasm (the production
//                  build of 2026-09-05/06, before the ACPI/x64/multi-core work)
//   SCENARIO=boot            cold boot to the desktop (taskbar), time it (this C:
//                            image stops at the MS-DOS mode prompt: WIN and Enter
//                            restart it in normal mode)
//   SCENARIO=state:<game>    restore the site's saved state of <game> with its
//                            game disk, run RUN_S (60) seconds: the CPU keeps
//                            retiring instructions, the screen has content, no
//                            emulator error
//
// SITE (../retro-gaming-site), OUT (build/r1-windows9x/<build>-<scenario>),
// TIMEOUT_S (600 for boot). Prints R1_WIN9X_PASS / R1_WIN9X_FAIL and a JSON line.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createRequire as create_require } from "node:module";
import { createHash as create_hash } from "node:crypto";
import { deflateSync as deflate_sync } from "node:zlib";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { ReadOnlyOverlayDisk } from "../smp/disk_fixture.mjs";
import { site_directory } from "../lib/site.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const site = path.resolve(process.env.SITE || site_directory(root)) + "/";
const build = process.env.BUILD || "current";
const scenario = process.env.SCENARIO || "boot";
const out = path.resolve(process.env.OUT || path.join(root, "build/r1-windows9x", `${build}-${scenario.replace(":", "-")}`)) + "/";
fs.mkdirSync(out, { recursive: true });

const V86 = build === "site" ? create_require(import.meta.url)(site + "libv86.js").V86 :
    (await import(root + "build/libv86.mjs")).V86;
const wasm_path = build === "site" ? site + "v86.wasm" : root + "build/v86.wasm";
// The guest's v86gl driver finds its device; no renderer answers (the site's
// older libv86.js has the device built in)
const { createV86GLDevice: create_v86gl_device } = create_require(import.meta.url)(root + "src/browser/glbridge/v86gl_device.js");
const v86gl = build === "site" ? { v86gl_pci: { port: 0xF100, maxBatchBytes: 16 * 1024 * 1024 } } :
    { virtio_devices: [create_v86gl_device({ remote: false, post() {}, listen() {} })] };
const bios_dir = build === "site" ? site + "bios/" : root + "bios/";

const system_disk = site + "windows98/windows98multidisk/windows98hdd_C_512MB.img";
const game = scenario.startsWith("state:") ? scenario.slice(6) : null;
const game_disk = game && site + `game/${game}.img`;
const state_file = game && site + `windows98/states/windows98_audio_vga_2d_multidisk_${game}.bin.zst`;
for(const file of [system_disk, game_disk, state_file].filter(Boolean)) assert.ok(fs.existsSync(file), file);
const image_mtimes = [system_disk, game_disk].filter(Boolean).map(file => fs.statSync(file).mtimeMs);

const disks = { hda: new ReadOnlyOverlayDisk(system_disk), hdb: game_disk ? new ReadOnlyOverlayDisk(game_disk) : undefined };
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    wasm_path, bios: { url: bios_dir + "seabios.bin" }, vga_bios: { url: bios_dir + "vgabios.bin" },
    memory_size: 256 << 20, vram_size: 16 << 20, acpi: false, boot_order: 0x213,
    hda: disks.hda, ...(disks.hdb ? { hdb: disks.hdb } : {}),
    net_device: { type: "ne2k" }, preserve_mac_from_state_image: false, mac_address_translation: true,
    ...v86gl,
    ...(state_file ? { initial_state: { buffer: fs.readFileSync(state_file).buffer } } : {}),
    autostart: false, log_level: 0,
});
const errors = [];
emulator.add_listener("emulator-error", error => errors.push(String(error)));
const t_load = performance.now();
await Promise.race([new Promise(resolve => emulator.add_listener("emulator-loaded", resolve)),
    // (unref'd: this timer must not keep node alive after the run)
    delay(300000, undefined, { ref: false }).then(() => { throw new Error("load timeout"); })]);
const load_s = (performance.now() - t_load) / 1000;
const cpu = emulator.v86.cpu, vga = cpu.devices.vga;

// the screen as RGB rows: VBE (8/15/16/24/32 bpp) or the VGA's pixel buffer
function screen()
{
    if(vga.svga_enabled && vga.svga_width && vga.svga_height)
    {
        const width = vga.svga_width, height = vga.svga_height, bpp = vga.svga_bpp, bytes = bpp === 15 ? 2 : bpp / 8;
        const rgb = Buffer.alloc(width * height * 3), memory = vga.svga_memory;
        for(let i = 0; i < width * height; i++)
        {
            const at = vga.svga_offset * bytes + i * bytes;
            let r, g, b;
            if(bytes === 1) { const c = vga.vga256_palette[memory[at]]; r = c >> 16 & 255; g = c >> 8 & 255; b = c & 255; }
            else if(bytes === 2)
            {
                const v = memory[at] | memory[at + 1] << 8;
                if(bpp === 15) { r = (v >> 10 & 31) << 3; g = (v >> 5 & 31) << 3; b = (v & 31) << 3; }
                else { r = (v >> 11 & 31) << 3; g = (v >> 5 & 63) << 2; b = (v & 31) << 3; }
            }
            else { r = memory[at + 2]; g = memory[at + 1]; b = memory[at]; }
            rgb[i * 3] = r; rgb[i * 3 + 1] = g; rgb[i * 3 + 2] = b;
        }
        return { width, height, rgb, mode: `vbe ${width}x${height}x${bpp}` };
    }
    if(vga.graphical_mode && vga.screen_width && vga.screen_height)
    {
        const width = vga.screen_width, height = vga.screen_height, rgb = Buffer.alloc(width * height * 3);
        const eight_bit = vga.attribute_mode & 0x40;
        for(let y = 0; y < height; y++) for(let x = 0; x < width; x++)
        {
            const index = vga.pixel_buffer[y * vga.virtual_width + x];
            const color = vga.vga256_palette[eight_bit ? index : vga.dac_map[index & vga.color_plane_enable]];
            const at = (y * width + x) * 3;
            rgb[at] = color >> 16 & 255; rgb[at + 1] = color >> 8 & 255; rgb[at + 2] = color & 255;
        }
        return { width, height, rgb, mode: `vga ${width}x${height}` };
    }
    return null;
}
function png(shot)
{
    const { width, height, rgb } = shot, stride = width * 3 + 1, raw = Buffer.alloc(stride * height);
    for(let y = 0; y < height; y++) rgb.copy(raw, y * stride + 1, y * width * 3, (y + 1) * width * 3);
    const crc = data => { let c = ~0; for(const byte of data) { c ^= byte; for(let i = 0; i < 8; i++) c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; } return ~c >>> 0; };
    const chunk = (name, data) => { const body = Buffer.concat([Buffer.from(name), data]), b = Buffer.alloc(data.length + 12);
        b.writeUInt32BE(data.length); body.copy(b, 4); b.writeUInt32BE(crc(body), b.length - 4); return b; };
    const header = Buffer.alloc(13); header.writeUInt32BE(width); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 2;
    return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header),
        chunk("IDAT", deflate_sync(raw)), chunk("IEND", Buffer.alloc(0))]);
}
function text_screen()
{
    if(vga.graphical_mode) return "";
    return Array.from({ length: 25 }, (_, row) => Array.from({ length: 80 }, (_, col) => {
        const c = vga.vga_memory[(row * 80 + col) * 2];
        return c >= 32 && c < 127 ? String.fromCharCode(c) : " ";
    }).join("").trimEnd()).join("\n").trim();
}
const colors = shot => { const set = new Set(); for(let i = 0; i < shot.rgb.length; i += 3 * 37) set.add(shot.rgb.readUIntBE(i, 3)); return set.size; };
// the Windows 9x taskbar: a light gray band (192, 192, 192) along the bottom
function taskbar(shot)
{
    let gray = 0, samples = 0;
    for(let y = shot.height - 22; y < shot.height - 4; y += 3) for(let x = 0; x < shot.width; x += 7)
    {
        const at = (y * shot.width + x) * 3;
        samples++;
        if(Math.abs(shot.rgb[at] - 192) < 12 && Math.abs(shot.rgb[at + 1] - 192) < 12 && Math.abs(shot.rgb[at + 2] - 192) < 12) gray++;
    }
    return gray / samples;
}
const retired = () => Number(cpu.wm.exports["core_statistics_get"]?.(0, 0) ?? 0) || emulator.get_instruction_counter();

const result = { build, scenario, load_s, errors };
const t0 = performance.now();
emulator.run();
let passed = false;
try
{
    if(scenario === "boot")
    {
        const deadline = t0 + (+process.env.TIMEOUT_S || 600) * 1000;
        let last_hash = "", stable_since = 0, shots = 0, last_shot = 0, typed_win = false, confirmed = false;
        for(;;)
        {
            await delay(1000);
            if(errors.length) throw new Error("emulator error: " + errors[0]);
            // this image was last left in MS-DOS mode: start Windows from its prompt
            const text = text_screen();
            if(!typed_win && /C:\\WINDOWS>\s*$/.test(text))
            {
                typed_win = true;
                result.dos_prompt_s = +((performance.now() - t0) / 1000).toFixed(1);
                emulator.keyboard_send_text("win\n");
            }
            // "... return to normal mode, to run Windows applications again [Enter=Y,Esc=N]?"
            if(!confirmed && /return to normal mode/.test(text))
            {
                confirmed = true;
                emulator.keyboard_send_scancodes([0x1C, 0x9C]);
            }
            const shot = screen();
            if(shot)
            {
                const hash = create_hash("sha1").update(shot.rgb).digest("hex");
                if(hash !== last_hash) { last_hash = hash; stable_since = performance.now(); }
                if(performance.now() - last_shot > 30000) { last_shot = performance.now(); fs.writeFileSync(out + `screen-${String(++shots).padStart(2, "0")}.png`, png(shot)); }
                // the desktop: the taskbar, and the screen settled for 5 s
                if(shot.width >= 640 && taskbar(shot) > 0.6 && performance.now() - stable_since > 5000)
                {
                    result.desktop_s = +((stable_since - t0) / 1000).toFixed(1);
                    result.mode = shot.mode;
                    result.colors = colors(shot);
                    fs.writeFileSync(out + "desktop.png", png(shot));
                    passed = true;
                    break;
                }
            }
            if(performance.now() > deadline)
            {
                if(shot) fs.writeFileSync(out + "timeout.png", png(shot));
                else result.text = text_screen();
                throw new Error(`no desktop within ${(deadline - t0) / 1000} s (screen ${shot?.mode || "text"})`);
            }
        }
    }
    else
    {
        const run_s = +process.env.RUN_S || 60;
        const samples = [];
        for(let s = 0; s < run_s; s += 10)
        {
            const before = retired();
            await delay(10000);
            if(errors.length) throw new Error("emulator error: " + errors[0]);
            samples.push(retired() - before);
        }
        const shot = screen();
        if(shot) fs.writeFileSync(out + "final.png", png(shot));
        result.mips = samples.map(n => +(n / 1e7).toFixed(1));
        result.mode = shot?.mode || "text";
        result.colors = shot ? colors(shot) : 0;
        assert.ok(samples.every(n => n > 0), "the CPU retires instructions in every 10 s: " + samples);
        assert.ok(shot && result.colors > 4, "the screen has content: " + result.mode + ", colors " + result.colors);
        passed = true;
    }
}
catch(error)
{
    result.error = String(error.message || error);
}
finally
{
    result.wall_s = +((performance.now() - t0) / 1000).toFixed(1);
    await emulator.destroy();
    [system_disk, game_disk].filter(Boolean).forEach((file, i) => assert.equal(fs.statSync(file).mtimeMs, image_mtimes[i], "image unchanged: " + file));
    fs.writeFileSync(out + "result.json", JSON.stringify(result, null, 1));
    console.log((passed ? "R1_WIN9X_PASS " : "R1_WIN9X_FAIL ") + JSON.stringify(result));
    process.exitCode = passed ? 0 : 1;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/rust/avx.mjs                                                                       0000644 0000000 0000000 00000177054 00000000000 013352  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AVX in the 32-bit engines (docs/simd-xsave-plan.md 8, P5): the VEX forms
// of the shared executor (src/rust/cpu/avx.rs) against a model written here
// from the SDM, and the rules every VEX form shares: VEX.vvvv is the first
// source; a VEX.128 destination register has bits 255:128 zeroed (seen
// through XSAVE, after XRSTOR loaded every upper half), legacy SSE leaves
// them; memory operands have their exact width and need no alignment but
// for VMOVAPS/VMOVAPD/VMOVDQA and the non-temporal moves (#GP(0)); #UD
// without CR4.OSXSAVE, XCR0's SSE and YMM bits or the AVX feature, #NM with
// CR0.TS (after #UD); CR0.EM and CR4.OSFXSR do not matter; #PF has no
// effect. Operands alias in every combination; VEX.W and VEX.L where they
// are ignored, and both VEX prefixes. Every case runs in the interpreter,
// then hot under the page tier (templates for the hot forms, steps for the
// others). (The region tiers, a second compiled arm, were deleted in M11.)
//
// P5 part 1: the data movement and logic forms, VZEROUPPER, VLDMXCSR and
// VSTMXCSR.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { FORMS, big, execute, le, mask, memory_bytes } from "./avx_model.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const hex = bytes => Buffer.from(bytes).toString("hex");
const CODE = 0x100000, SOURCE = 0x200000, DEST = 0x220000, OUT = 0x240000, FAULT = 0x24F000, SKIP = 0x24F100;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000, ABSENT = 0x2F0000;
// a case's XRSTOR and XSAVE areas (standard format, YMM_Hi128 at 576)
const AREAS = 0x300000;
const area_in = n => AREAS + n * 0x800, area_out = n => AREAS + n * 0x800 + 0x400;
// a case's memory at SOURCE and DEST
const SPAN = 48;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

// instructions
const absolute = (r, a) => [0x05 | r << 3, ...u32(a)];
const mov_r32 = (r, v) => [0xB8 | r, ...u32(v)];
const store_r32 = (r, a) => [0x89, 0x05 | r << 3, ...u32(a)];
const xsetbv = value => [...mov_r32(1, 0), ...mov_r32(0, value), ...mov_r32(2, 0), 0x0F, 0x01, 0xD1];
const xrstor = a => [...mov_r32(3, a), ...mov_r32(0, 6), ...mov_r32(2, 0), 0x0F, 0xAE, 0x2B];
const xsave = a => [...mov_r32(3, a), ...mov_r32(0, 6), ...mov_r32(2, 0), 0x0F, 0xAE, 0x23];
// CR4 = CR4 | or & and
const cr4 = (or, and = -1) => [0x0F, 0x20, 0xE0, 0x0D, ...u32(or), 0x25, ...u32(and >>> 0), 0x0F, 0x22, 0xE0];
const OSFXSR = 0x200, OSXMMEXCPT = 0x400, OSXSAVE = 1 << 18;
const CLTS = [0x0F, 0x06];
const SET_CR0 = bits => [0x0F, 0x20, 0xC0, 0x0D, ...u32(bits), 0x0F, 0x22, 0xC0];
const CLEAR_CR0 = bits => [0x0F, 0x20, 0xC0, 0x25, ...u32(~bits >>> 0), 0x0F, 0x22, 0xC0];
/** A VEX instruction: map (1: 0F, 2: 0F38, 3: 0F3A), pp (0, 1: 66, 2: F3,
 * 3: F2), VEX.L, VEX.W and VEX.vvvv; the ModRM byte's reg and r/m register
 * or [address] (neither: no ModRM byte); imm8. The two-byte prefix unless
 * `three`, the map or VEX.W needs the three-byte one. */
function vex({ map = 1, pp = 0, l = 0, w = 0, vvvv = 0, three = false }, op, reg, rm, address, imm8)
{
    const modrm = address !== undefined ? absolute(reg, address) : rm !== undefined ? [0xC0 | reg << 3 | rm] : [];
    const tail = [op, ...modrm, ...(imm8 === undefined ? [] : [imm8])];
    const fields = (~vvvv & 15) << 3 | l << 2 | pp;
    if(map === 1 && !w && !three) return [0xC5, 0x80 | fields, ...tail];
    return [0xC4, 0xE0 | map, w << 7 | fields, ...tail];
}
const GPRS = [1, 5, 6, 7, 0, 2, 3]; // (not ESP)

// Operand data: a case's XMM and YMM_Hi128 registers, MXCSR and memory
const random_bytes = (seed, n) => {
    const a = new Uint8Array(n);
    for(let i = 0; i < n; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; a[i] = seed; }
    return a;
};
const MAX_CASES = 64;
const XMM = random_bytes(0x5EED1234, MAX_CASES * 128), YMMH = random_bytes(0x0BADC0DE, MAX_CASES * 128);
const SOURCES = random_bytes(0x13579BDF, MAX_CASES * SPAN), DESTINATIONS = random_bytes(0x2468ACE1, MAX_CASES * SPAN);
const MXCSRS = random_bytes(0x600DF00D, MAX_CASES * 2);
const GPR_VALUES = random_bytes(0xFEEDFACE, MAX_CASES * 4);
// (exceptions masked: the floating-point forms' cases run without faults, tests/rust/avx_fp.mjs has those)
const mxcsr_of = n => MXCSRS[2 * n] | MXCSRS[2 * n + 1] << 8 | 0x1F80;
const gpr_of = n => new DataView(GPR_VALUES.buffer).getUint32(4 * n, true);
/** The state of case `n` (`c`) before its instruction: XMM0-7 (x), their
 * upper halves (h), MXCSR, the memory at its source (read-only here) and
 * destination, and 16 bytes of results (out); its memory operand at `c.at`
 * of both (avx_model.mjs's execute) */
function initial(n, c)
{
    const s = {
        x: Array.from({ length: 8 }, (_, r) => big(XMM.subarray((n * 8 + r) * 16, (n * 8 + r + 1) * 16))),
        h: Array.from({ length: 8 }, (_, r) => big(YMMH.subarray((n * 8 + r) * 16, (n * 8 + r + 1) * 16))),
        mxcsr: mxcsr_of(n),
        src: c.source || SOURCES.subarray(n * SPAN, (n + 1) * SPAN),
        dest: Uint8Array.from(c.destination || DESTINATIONS.subarray(n * SPAN, (n + 1) * SPAN)),
        out: Uint8Array.from(c.out_before || new Uint8Array(16)),
    };
    const at = c.at ?? 0;
    s.load = size => big(s.src.subarray(at, at + size));
    s.store = (size, v) => s.dest.set(le(v, size), at);
    s.load_at = (offset, size) => big(s.src.subarray(at + offset, at + offset + size));
    s.store_at = (offset, size, v) => s.dest.set(le(v, size), at + offset);
    // (registers the case sets: c.registers)
    for(const [r, value] of Object.entries(c.registers || {})) s.x[r] = value;
    for(const [r, value] of Object.entries(c.uppers || {})) s.h[r] = value;
    s.masked = (value, selected) => le(value).forEach((b, i) => { if(selected[i]) s.dest[at + i] = b; });
    s.gpr = r => BigInt(c.gpr_values?.[r] ?? c.gpr);
    // (ECX of VPCMPESTRI/VPCMPISTRI and the general-purpose destinations: out[0..4])
    s.set_gpr = (r, value) => s.out.set(le(value & mask(32), 4));
    // (the flags: out[4..8], those that set them)
    Object.defineProperty(s, "flags", { set: value => { s.out.set(le(BigInt(value), 4), 4); } });
    return s;
}
/** Case `n`'s XRSTOR area: MXCSR, XMM0-7 (those of `registers` instead)
 * and YMM_Hi128 0-7 in use */
function area(n, registers = {}, uppers = {})
{
    const a = new Uint8Array(832);
    a.set(u32(mxcsr_of(n)), 24);
    a.set(XMM.subarray(n * 128, n * 128 + 128), 160);
    for(const [r, value] of Object.entries(registers)) a.set(le(value), 160 + 16 * r);
    a[512] = 6;
    a.set(YMMH.subarray(n * 128, n * 128 + 128), 576);
    for(const [r, value] of Object.entries(uppers)) a.set(le(value), 576 + 16 * r);
    return a;
}

const machines = [];
/** `until`: what else a warm run of compiled code waits for */
async function run(vm, program, warm, interpreter, label, until = () => true)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    // (the page tier's step counts are the hot run's: x64_page_steps)
    else e["x64_page_steps_freeze"]();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && (compiled_activations(e) === start || !until(vm)))
    {
        assert(performance.now() < deadline, `program/JIT timeout (${label}: ${program.length} bytes, done ${word(vm, 0x600) === 0xCAFE}, ` +
            `compiled ${compiled_activations(e) - start}, ${until(vm) ? "" : "not "}ready, last fault ${word(vm, FAULT)} at ${word(vm, FAULT + 4).toString(16)})`);
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
// the body repeats until byte 0x604 is set, then halts after one more round
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it, the faulting EIP, CR2 and the error code, and skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58, 0xA3, ...u32(FAULT + 12));
    p.push(0xC7, 0x05, ...u32(FAULT), ...u32(vector));
    p.push(0x8B, 0x04, 0x24, 0xA3, ...u32(FAULT + 4));
    p.push(0x0F, 0x20, 0xD0, 0xA3, ...u32(FAULT + 8));
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true], [19, false]];
// SSE and AVX state enabled: CR4.OSFXSR, OSXMMEXCPT and OSXSAVE, XCR0 7
// (without AVX: 3)
const prologue = xcr0 => [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...CLTS, ...CLEAR_CR0(4), ...cr4(OSFXSR | OSXMMEXCPT | OSXSAVE), ...xsetbv(xcr0)];
let PROLOGUE = prologue(7);
/** Runs `program` on each machine of `set`: warm (compiled), then once more
 * cold; returns what `read` reads after each run (the cold run is mostly
 * interpreted: the program was rewritten) */
async function run_all(program, before = () => {}, set = machines, read = () => null, until = undefined)
{
    const results = [];
    for(const [i, vm] of set.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], i) => {
            const h = HANDLER + i * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(new Uint8Array(16), FAULT);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, loop([...PROLOGUE, ...program]), warm, vm === set[0], `machine ${i} ${warm ? "hot" : "one round"}`, until);
            results.push({ label: `machine ${i} ${warm ? "hot" : "one round"}`, data: read(vm) });
        }
    }
    return results;
}
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
const pages = (vm, page, present) => {
    // (the BIOS's page table: 0x13000, identity)
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};
/** The rounds of a check_cases program that the page tier (machine 1) ran since
 * x64_page_steps_reset: it steps each case's XRSTOR and XSAVE (0F AE) */
const page_rounds = () => machines[1].v86.cpu.wm.exports["x64_page_steps"](0xAE0F) / 2;
// The VEX forms of gen/isa_hot_forms.json, which have page tier templates (P5
// part 5): the others here, against every case; the floating-point ones with
// ordinary operands (see PAGE_HOT_FP)
const PAGE_HOT = ["vmovsd", "vmovss", "vmovapd", "vmovaps", "vmovdqu", "vmovdqa", "vmovq", "vmovd", "vxorpd", "vxorps",
    "vandpd", "vandnpd", "vorpd", "vpand", "vpandn", "vpor", "vpxor", "vpcmpeqb", "vpcmpeqd", "vpcmpgtb", "vpaddb",
    "vpmovmskb", "vzeroupper", "vunpcklpd", "vunpckhpd", "vblendvpd", "vpshufb", "vpbroadcastb", "vpbroadcastd"];
// The VEX.256 ones (P6 part 3: the moves and VZEROALL; with the moves of
// the other types): every form of the name templated
const PAGE_HOT_256 = ["vmovdqu", "vmovdqa", "vmovntdq", "vzeroall", "vmovups", "vmovaps", "vmovupd", "vmovapd",
    "vmovntps", "vmovntpd",
    // (AVX2, P7 part 3)
    "vpmovmskb", "vpcmpeqb", "vpcmpeqd", "vpaddb", "vpandn", "vpminub", "vpcmpgtb", "vpand", "vpminud", "vpor", "vpxor",
    "vpbroadcastb", "vpbroadcastd"].map(name => name + " ymm");
// (IR Tier-0, deleted in P7.5, also templated VCVTTSD2SI, VCVTSD2SS,
// VCVTSI2SD, VCVTSS2SD and VCVTPD2PS; the page tier steps them)
const PAGE_HOT_FP = ["vaddsd", "vmulsd", "vsubsd", "vdivsd", "vaddss", "vmulss", "vsubss", "vdivss", "vmulpd", "vcomisd",
    "vucomisd", "vcomiss", "vucomiss", "vcmpsd"];
/** The forms whose cases the page tier ran templates for (fewer steps than cases)
 * or stepped, by name (" ymm": a VEX.256 form's) */
const page_forms = { templated: new Set(), stepped: new Set() };
/** VEX instructions stepped by the page tier (machine 1) since x64_page_steps_reset:
 * keyed by their first two bytes, C4 or C5 and the next, or an address-size
 * or segment prefix and C4 or C5 */
function page_vex_steps()
{
    const steps = machines[1].v86.cpu.wm.exports["x64_page_steps"];
    let count = 0;
    for(let byte = 0; byte < 256; byte++) count += steps(0xC4 | byte << 8) + steps(0xC5 | byte << 8);
    for(const prefix of [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x67]) count += steps(prefix | 0xC400) + steps(prefix | 0xC500);
    return count;
}

let checks = 0;
/** The build has Wasm SIMD (the portable one has no page tier SIMD templates) */
const simd = vm => vm.v86.cpu.wm.exports["jit_wasm_simd_supported"]() !== 0;
/** Runs `cases` in one program: each loads its registers with XRSTOR, runs
 * its `code` between `pre` and `post` and stores its registers with XSAVE;
 * the registers, MXCSR, its destination memory and `out` must be as its
 * `model` says, in each run. Returns the VEX instructions the page tier stepped in
 * its hot run; with the `form` under test, records whether the page tier ran a
 * template for it (page_forms) */
async function check_cases(name, cases, { before = () => {}, form } = {})
{
    const program = [];
    for(const c of cases)
    {
        program.push(...xrstor(area_in(c.n)), ...(c.pre || []), ...c.code, ...(c.post || []), ...xsave(area_out(c.n)));
    }
    const write = vm => {
        for(const c of cases)
        {
            vm.write_memory(area(c.n, c.registers, c.uppers), area_in(c.n));
            vm.write_memory(new Uint8Array(832), area_out(c.n));
            vm.write_memory(c.source || SOURCES.subarray(c.n * SPAN, (c.n + 1) * SPAN), c.source_at ?? SOURCE + c.n * SPAN);
            vm.write_memory(c.destination || DESTINATIONS.subarray(c.n * SPAN, (c.n + 1) * SPAN), c.destination_at ?? DEST + c.n * SPAN);
            vm.write_memory(new Uint8Array(16), OUT + c.n * 16);
        }
        before(vm);
    };
    for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
    const results = await run_all(program, write, machines, vm => ({
        fault: word(vm, FAULT),
        cases: cases.map(c => ({
            area: bytes(vm, area_out(c.n), 832),
            dest: bytes(vm, c.destination_at ?? DEST + c.n * SPAN, SPAN),
            out: bytes(vm, OUT + c.n * 16, 16),
        })),
        page: vm === machines[1] ? page_vex_steps() : 0,
    }), vm => vm !== machines[1] || page_rounds() >= cases.length);
    // (the hot run ran the VEX forms compiled: the page tier a template or
    // steps; steps in a build without Wasm SIMD, which has no page tier SIMD
    // templates. results[2]: machine 1's hot run)
    const steps = results[2].data.page;
    if(form)
    {
        // (a template retries some cases at most: floating-point lanes it refuses)
        if(steps < cases.length / 2 && simd(machines[1])) page_forms.templated.add(form_key(form));
        else
        {
            assert.ok(steps >= cases.length || form.kind === "fp", `${name}: the page tier stepped ${steps} VEX instructions`);
            page_forms.stepped.add(form_key(form));
        }
    }
    for(const { label, data } of results)
    {
        assert.equal(data.fault, 0, `${name} (${label}): no fault`);
        cases.forEach((c, i) => {
            const s = initial(c.n, c);
            c.model(s);
            const got = data.cases[i];
            const what = `${name} case ${c.n} ${hex(c.code)} (${label})`;
            for(let r = 0; r < 8; r++)
            {
                assert.equal(hex(got.area.subarray(160 + 16 * r, 176 + 16 * r)), hex(le(s.x[r])), `${what}: xmm${r}`);
                assert.equal(hex(got.area.subarray(576 + 16 * r, 592 + 16 * r)), hex(le(s.h[r])), `${what}: ymm${r}[255:128]`);
            }
            assert.equal(new DataView(got.area.buffer).getUint32(24, true), s.mxcsr, `${what}: MXCSR`);
            assert.equal(hex(got.dest), hex(s.dest), `${what}: memory`);
            assert.equal(hex(got.out), hex(s.out), `${what}: results`);
        });
    }
    checks += cases.length;
    return steps;
}
/** Registers of case `n`: destination, first source and r/m, which alias in
 * every combination over 32 cases */
const regs = n => {
    const d = n & 7;
    const v = [d, d + 1 & 7, n >> 1 & 7, n * 5 & 7][n >> 3 & 3];
    const m = [d, v, d + 3 & 7, n * 3 + 2 & 7][n & 3];
    return [d, v, m];
};
const CASES = 32;

/** `faulting` raises `vector` at its first byte in every run, after
 * XRSTOR of case 0's registers and `setup`, before `epilogue` and XSAVE:
 * the registers (but YMM_Hi128 with `keep_upper` false), MXCSR and the
 * memory at `memory` are unchanged */
async function expect_fault(setup, faulting, vector, { epilogue = [], before = () => {}, cr2, error_code, label, memory, keep_upper = true, registers = {}, uppers = {} } = {})
{
    const at = CODE + PROLOGUE.length + xrstor(0).length + setup.length;
    for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
    const results = await run_all([...xrstor(area_in(0)), ...setup, ...faulting, ...epilogue, ...xsave(area_out(0))], vm => {
        vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
        vm.write_memory(area(0, registers, uppers), area_in(0));
        before(vm);
    }, machines, vm => ({ fault: [0, 4, 8, 12].map(o => word(vm, FAULT + o)), area: bytes(vm, area_out(0), 832),
        memory: memory && bytes(vm, memory[0], memory[1].length) }),
    // (the page tier steps XRSTOR: the faulting form runs as a template once the
    // page has been compiled again with an entry after it)
    vm => vm !== machines[1] || page_rounds() >= 300);
    const name = label || hex(faulting);
    const initial_area = area(0, registers, uppers);
    for(const { label: run, data } of results)
    {
        assert.deepEqual(data.fault.slice(0, 2), [vector, at], `${name} (${run}): vector, EIP`);
        if(cr2 !== undefined) assert.equal(data.fault[2], cr2, `${name} (${run}): CR2`);
        if(error_code !== undefined) assert.equal(data.fault[3], error_code, `${name} (${run}): error code`);
        assert.equal(hex(data.area.subarray(160, 288)), hex(initial_area.subarray(160, 288)), `${name} (${run}): XMM registers kept`);
        if(keep_upper) assert.equal(hex(data.area.subarray(576, 704)), hex(initial_area.subarray(576, 704)), `${name} (${run}): YMM_Hi128 kept`);
        assert.equal(word_of(data.area, 24), mxcsr_of(0), `${name} (${run}): MXCSR kept`);
        if(memory) assert.equal(hex(data.memory), hex(memory[1]), `${name} (${run}): memory kept`);
    }
    checks++;
}
const word_of = (a, at) => new DataView(a.buffer, a.byteOffset).getUint32(at, true);

// the kinds of forms (avx_model.mjs) whose memory operand is a destination,
// and those with VEX.vvvv
const STORES = ["store", "scalar_st", "store64", "gpr_store", "stmxcsr", "extract", "maskstore", "extract128"];
const VVVV = ["binary", "low", "high", "binary_imm", "insert", "insertps", "blendv", "shift_imm", "maskload", "maskstore", "insert128"];
/** The form has VEX.vvvv (the immediate shifts: the destination) */
const has_vvvv = (f, memory) => VVVV.includes(f.kind) || ["scalar", "scalar_st"].includes(f.kind) && !memory ||
    f.kind === "fp" && ["three", "from_gpr"].includes(f.operands);
// flags before an instruction that sets them: OF, SF, AF (0x7F + 1) and CF (STC)
const FLAGS_BEFORE = [0xB0, 0x7F, 0x04, 0x01, 0xF9];
/** EFLAGS' OSZAPC to `a` (EAX changes) */
const store_flags = a => [0x9C, 0x58, 0x25, ...u32(0x8D5), 0xA3, ...u32(a)];
// explicit lengths of VPCMPESTRx (EAX, EDX): within, beyond, negative, the extremes
const LENGTHS = [0, 1, 3, 7, 8, 9, 15, 16, 17, -1, -5, -16, -17, 0x7FFFFFFF, -0x80000000];
/** Case `n` of gather `f`: VSIB [EBX + index << scale], EBX the source's
 * middle (negative indices too), every element within the source; the
 * destination, mask and index registers distinct; quadword indices beyond
 * 32 bits in odd elements, which 32-bit addressing drops; random masks */
function gather_case(f, n)
{
    const [d, v, index] = [n & 7, n + 3 & 7, n + 5 & 7], scale = n & 3, at = 24;
    const count = (f.l ? 32 : 16) / Math.max(f.data, f.index);
    const low = -(at >> scale), high = SPAN - at - f.data >> scale;
    let indices = 0n;
    for(let k = 0; k < count; k++)
    {
        const value = BigInt(low + (n * 7 + k * 5) % (high - low + 1)) + (f.index === 8 && k & 1 ? 1n << 40n : 0n);
        indices |= BigInt.asUintN(8 * f.index, value) << BigInt(8 * f.index * k);
    }
    const c = { n, at, registers: { [index]: indices & mask(128) }, pre: mov_r32(3, SOURCE + n * SPAN + at), post: [],
        code: [...vex({ map: 2, pp: 1, l: f.l ?? 0, w: f.w, vvvv: v }, f.op), d << 3 | 4, scale << 6 | index << 3 | 3] };
    // (indices beyond the low 128 bits: the others random)
    if(count * f.index > 16) c.uppers = { [index]: indices >> 128n };
    c.model = s => execute(f, s, { d, v, index, scale, long: false });
    return c;
}
/** A form's name, " ymm" added for a VEX.256 one */
const form_key = f => f.name + (f.l ? " ymm" : "");
/** Case `n` of form `f`: registers that alias in every combination, the
 * memory operand from n/2 on (unaligned but for the aligned moves), the
 * general-purpose registers set before and stored after */
function form_case(f, n)
{
    if(f.kind === "gather") return gather_case(f, n);
    const [d, v, m] = regs(n);
    const memory = f.memory || !f.register && n >= CASES / 2;
    const at = f.aligned ? 16 * (n & 1) : n % 17;
    // (the immediate shifts: VEX.vvvv is the destination)
    const vvvv = f.kind === "shift_imm" ? d : has_vvvv(f, memory) ? v : 0;
    // (every imm8 in turn over the forms' cases; VPBLENDVB: the mask register in imm8[7:4], imm8[7] ignored;
    // the shifts by imm8 and VPALIGNR mostly counts below the element's or the
    // operand's size, beyond which the result is 0)
    const imm8 = f.kind === "blendv" ? (n * 5 + 3) % 16 << 4 | n * 7 & 15 : f.kind === "shift_imm" ? (n * 7 + 1) % 20 :
        f.name === "vpalignr" ? (n * 7 + 3) % 36 : n * 37 + 11 & 255;
    const store = STORES.includes(f.kind);
    const address = memory ? (store ? DEST : SOURCE) + n * SPAN + at : undefined;
    const r = GPRS[n % 7];
    const c = { n, at, pre: [], post: [] };
    let [reg, rm] = [d, m];
    const o = { d, v: f.kind === "shift_imm" ? d : v, m: memory ? undefined : m, imm8, long: false };
    switch(f.kind)
    {
        case "to_gpr":
            reg = o.d = r;
            c.pre = mov_r32(r, 0xDEADBEEF);
            c.post = store_r32(r, OUT + n * 16);
            break;
        case "shift_imm": reg = f.group; break;
        case "extract": case "insert":
            rm = r;
            if(memory) break;
            o.m = r;
            c.gpr = gpr_of(n);
            c.pre = mov_r32(r, f.kind === "insert" ? c.gpr : 0xDEADBEEF);
            if(f.kind === "extract") c.post = store_r32(r, OUT + n * 16);
            break;
        case "ptest": case "vtest":
            c.pre = FLAGS_BEFORE;
            c.post = store_flags(OUT + n * 16 + 4);
            break;
        case "fp":
            if(f.operands === "comi")
            {
                c.pre = FLAGS_BEFORE;
                c.post = store_flags(OUT + n * 16 + 4);
            }
            else if(f.operands === "to_gpr")
            {
                reg = o.d = r;
                c.pre = mov_r32(r, 0xDEADBEEF);
                c.post = store_r32(r, OUT + n * 16);
            }
            else if(f.operands === "from_gpr" && !memory)
            {
                rm = o.m = r;
                c.gpr = gpr_of(n);
                c.pre = mov_r32(r, c.gpr);
            }
            break;
        case "pcmpstr":
        {
            // (EAX and EDX: the explicit lengths; ECX ones; the flags set)
            const [la, lb] = [LENGTHS[n % LENGTHS.length], LENGTHS[(n * 7 + 3) % LENGTHS.length]];
            c.gpr_values = { 0: la >>> 0, 2: lb >>> 0 };
            // (VPCMPxSTRM leave ECX)
            c.out_before = Uint8Array.of(255, 255, 255, 255, ...new Array(12).fill(0));
            c.pre = [...FLAGS_BEFORE, ...mov_r32(0, la >>> 0), ...mov_r32(2, lb >>> 0), ...mov_r32(1, -1 >>> 0)];
            c.post = [...store_r32(1, OUT + n * 16), ...store_flags(OUT + n * 16 + 4)];
            break;
        }
        case "gpr_load": case "gpr_store":
            rm = r;
            if(memory) break;
            o.m = r;
            c.gpr = gpr_of(n);
            c.pre = mov_r32(r, f.kind === "gpr_load" ? c.gpr : 0xDEADBEEF);
            if(f.kind === "gpr_store") c.post = store_r32(r, OUT + n * 16);
            break;
        case "ldmxcsr":
        {
            reg = f.group;
            const value = u32(mxcsr_of(n + 32));
            c.source = Uint8Array.from({ length: SPAN }, (_, i) => i >= at && i < at + 4 ? value[i - at] : SOURCES[n * SPAN + i]);
            break;
        }
        case "stmxcsr": reg = f.group; break;
        case "maskmov": c.pre = mov_r32(7, DEST + n * SPAN + at); break;
    }
    // (the shifts by xmm/m128: a count below or beyond the element's width
    // in the low quadword, which alone counts, and random bits above it)
    if(!f.map && f.kind === "binary" && [0xD1, 0xD2, 0xD3, 0xE1, 0xE2, 0xF1, 0xF2, 0xF3].includes(f.op))
    {
        const count = BigInt(n * 5 % 70) | big(SOURCES.subarray(n * SPAN + 8, n * SPAN + 16)) << 64n;
        if(memory)
        {
            c.source = Uint8Array.from(SOURCES.subarray(n * SPAN, (n + 1) * SPAN));
            c.source.set(le(count), at);
        }
        else c.registers = { [m]: count };
    }
    // (the variable shifts: each element's count below or beyond the
    // element's width; as dwords, the qwords' counts and zeros)
    if(f.map === 2 && f.op >= 0x45 && f.op <= 0x47 && f.kind === "binary")
    {
        let counts = 0n;
        for(let k = 0; k < 4; k++) counts |= BigInt((n * 7 + k * 13) % 72) << BigInt(64 * k);
        if(memory)
        {
            c.source = Uint8Array.from(SOURCES.subarray(n * SPAN, (n + 1) * SPAN));
            c.source.set(le(counts, f.l ? 32 : 16), at);
        }
        else
        {
            c.registers = { [m]: counts & mask(128) };
            if(f.l) c.uppers = { [m]: counts >> 128n };
        }
    }
    // (VEX.W where ignored: WIG, WIG32 outside 64-bit mode; VEX.L where ignored, VEX.256 forms' 1)
    const fields = { map: f.map || 1, pp: f.pp, w: f.w === undefined || f.wig32 ? n & 1 : f.w, l: f.l ?? (f.lig ? n >> 2 & 1 : 0), three: !!(n & 2), vvvv };
    const immediate = ["load_imm", "binary_imm", "shift_imm", "extract", "insert", "insertps", "blendv", "pcmpstr", "insert128", "extract128"].includes(f.kind) ||
        f.imm || f.legacy?.imm8 ? imm8 : undefined;
    c.code = f.kind === "zero_upper" || f.kind === "zero_all" ? vex(fields, f.op) : vex(fields, f.op, reg, rm, address, immediate);
    c.model = s => execute(f, s, o);
    return c;
}

try
{
    // Without AVX: CPUID does not report it, and every VEX form is #UD (with
    // CR4.OSXSAVE and XCR0 3)
    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE"], cpu_features_unreleased: true }));
    PROLOGUE = prologue(3);
    {
        const results = await run_all([0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT)], () => {}, machines, vm => word(vm, OUT));
        for(const { label, data } of results) assert.equal(data >>> 28 & 1, 0, `CPUID.1:ECX.AVX (${label})`);
    }
    for(const [label, form] of [["vmovaps xmm1, xmm2", vex({ pp: 0 }, 0x28, 1, 2)], ["vpxor xmm1, xmm2, [mem]", vex({ pp: 1, vvvv: 2 }, 0xEF, 1, undefined, SOURCE)],
        ["vzeroupper", vex({}, 0x77)], ["vmovd xmm1, ecx", vex({ pp: 1 }, 0x6E, 1, 1)]])
    {
        const results = await run_all(form, vm => vm.write_memory(Uint8Array.from(u32(form.length)), SKIP), machines,
            vm => [0, 4].map(o => word(vm, FAULT + o)));
        for(const { label: run, data } of results) assert.deepEqual(data, [6, CODE + PROLOGUE.length], `${label} without AVX (${run}): #UD`);
        checks++;
    }
    PROLOGUE = prologue(7);
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: without AVX, CPUID does not report it and VEX forms are #UD");

    // With AVX but without AVX2: CPUID.7.0:EBX does not report it, and
    // AVX2's forms (VEX.256 of the packed integer instructions) are #UD
    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], cpu_features_unreleased: true }));
    {
        const results = await run_all([0xB8, ...u32(7), 0x31, 0xC9, 0x0F, 0xA2, 0x89, 0x1D, ...u32(OUT)], () => {}, machines, vm => word(vm, OUT));
        for(const { label, data } of results) assert.equal(data >>> 5 & 1, 0, `CPUID.7.0:EBX.AVX2 (${label})`);
    }
    for(const [label, form] of [["vpaddd ymm1, ymm2, ymm3", vex({ pp: 1, l: 1, vvvv: 2 }, 0xFE, 1, 3)],
        ["vpshufb ymm1, ymm2, [mem]", vex({ map: 2, pp: 1, l: 1, vvvv: 2 }, 0x00, 1, undefined, SOURCE)],
        ["vpsrlw ymm1, ymm2, 3", vex({ pp: 1, l: 1, vvvv: 1 }, 0x71, 2, 2, undefined, 3)], ["vpmovmskb ecx, ymm1", vex({ pp: 1, l: 1 }, 0xD7, 1, 1)],
        ["vpbroadcastb xmm1, xmm2", vex({ map: 2, pp: 1 }, 0x78, 1, 2)], ["vpsllvd xmm1, xmm2, xmm3", vex({ map: 2, pp: 1, vvvv: 2 }, 0x47, 1, 3)],
        ["vpermq ymm1, ymm2, 0x1B", vex({ map: 3, pp: 1, l: 1, w: 1 }, 0x00, 1, 2, undefined, 0x1B)],
        ["vbroadcastss xmm1, xmm2", vex({ map: 2, pp: 1 }, 0x18, 1, 2)]])
    {
        const results = await run_all(form, vm => vm.write_memory(Uint8Array.from(u32(form.length)), SKIP), machines,
            vm => [0, 4].map(o => word(vm, FAULT + o)));
        for(const { label: run, data } of results) assert.deepEqual(data, [6, CODE + PROLOGUE.length], `${label} without AVX2 (${run}): #UD`);
        checks++;
    }
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: with AVX but without AVX2, CPUID does not report AVX2 and its forms are #UD");

    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "AVX2"], cpu_features_unreleased: true }));
    {
        const results = await run_all([0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT)], () => {}, machines, vm => word(vm, OUT));
        for(const { label, data } of results) assert.equal(data >>> 27 & 3, 3, `CPUID.1:ECX.OSXSAVE and AVX (${label})`);
    }

    // every form against the model (AVX_ONLY=name,...: those forms only)
    const only = process.env.AVX_ONLY?.split(",");
    for(const f of FORMS.filter(f => !f.long && (!only || only.includes(f.name))))
    {
        await check_cases(`${f.name}${f.l ? " ymm" : ""} (${(f.map || 1) === 1 ? "" : (f.map === 2 ? "0F38 " : "0F3A ")}${f.op.toString(16)}${f.group === undefined ? "" : "/" + f.group})`,
            Array.from({ length: f.kind.startsWith("zero_") || f.memory && f.kind.endsWith("mxcsr") ? 8 : CASES }, (_, n) => form_case(f, n)), { form: f });
    }
    if(simd(machines[1]))
    {
        for(const name of PAGE_HOT.filter(name => !only || only.includes(name))) assert.ok(page_forms.templated.has(name), `${name}: a page tier template`);
        for(const name of PAGE_HOT_256.filter(name => !only || only.includes(name.slice(0, -4))))
        {
            assert.ok(page_forms.templated.has(name) && !page_forms.stepped.has(name), `${name}: the page tier templates`);
        }
    }
    console.log(`PASS: ${FORMS.filter(f => !f.long).length} forms against the model, from registers and memory: bits 255:128 of register destinations zeroed; ` +
        `the page tier templates for ${page_forms.templated.size} of them`);

    // The floating-point hot forms run page tier templates (or their exact path)
    // for ordinary operands: finite, normal and of moderate size
    {
        const values = [1.5, -2.25, 3000, -0.007, 1024, -1, 650, 0.125];
        const vector = (double, k) => {
            const b = new Uint8Array(16), view = new DataView(b.buffer);
            for(let lane = 0; lane < (double ? 2 : 4); lane++)
            {
                const x = values[(k + lane * 3) % values.length];
                if(double) view.setFloat64(8 * lane, x, true);
                else view.setFloat32(4 * lane, x, true);
            }
            return b;
        };
        for(const f of FORMS.filter(f => !f.long && !f.l && PAGE_HOT_FP.includes(f.name) && (!only || only.includes(f.name))))
        {
            const double = f.legacy.double ?? f.legacy.kind === "narrow";
            const cases = Array.from({ length: CASES }, (_, n) => {
                const c = form_case(f, n);
                c.registers = Object.fromEntries(Array.from({ length: 8 }, (_, r) => [r, big(vector(double, n + r))]));
                c.source = new Uint8Array(SPAN);
                c.source.set(vector(double, n + 5).subarray(0, 16), c.at);
                return c;
            });
            const steps = await check_cases(`${f.name} of ordinary operands`, cases);
            if(simd(machines[1])) assert.ok(steps < CASES / 2, `${f.name}: a page tier template (${steps} steps)`);
        }
    }
    // VEX.256 moves among VEX.128 forms in one block (P6 part 3): a VEX.128
    // write zeroes bits 255:128 again after a VEX.256 move wrote them
    // (the page tier zeroes a register's once per block, Emitter::ymm_zeroed), the
    // halves between registers and memory, VZEROALL
    {
        const cases = [];
        for(let n = 0; n < 8; n++)
        {
            // (32-byte aligned: SPAN is 48)
            const at = 16 * (n & 1), source = SOURCE + n * SPAN + at, destination = DEST + n * SPAN + at;
            const load = (pp, op, reg) => vex({ pp, l: 1 }, op, reg, undefined, source);
            cases.push({ n, at, code: n < 4 ? [
                ...load(2, 0x6F, 1), // vmovdqu ymm1, [m256]
                ...vex({ vvvv: 1 }, 0x57, 1, 1), // vxorps xmm1, xmm1, xmm1
                ...load(0, 0x10, 1), // vmovups ymm1, [m256]
                ...vex({ pp: 1, vvvv: 1 }, 0xEF, 1, 1), // vpxor xmm1, xmm1, xmm1
                ...load(0, 0x28, 2), // vmovaps ymm2, [m256]
                ...vex({ l: 1 }, 0x28, 3, 2), // vmovaps ymm3, ymm2
                ...vex({ l: 1 }, 0x11, 2, 4), // vmovups ymm4, ymm2 (11 /r)
                ...vex({ pp: 1, l: 1 }, 0x7F, 3, undefined, destination), // vmovdqa [m256], ymm3
                ...vex({ pp: 1, vvvv: 5 }, 0xEF, 5, 4), // vpxor xmm5, xmm5, xmm4
            ] : [
                ...load(2, 0x6F, 6), // vmovdqu ymm6, [m256]
                ...vex({ l: 1 }, 0x77), // vzeroall
                ...load(1, 0x6F, 7), // vmovdqa ymm7, [m256]
                ...vex({ pp: 2, l: 1 }, 0x7F, 7, 0), // vmovdqu ymm0, ymm7 (7F /r)
                ...vex({ vvvv: 7 }, 0x57, 7, 7), // vxorps xmm7, xmm7, xmm7
                ...vex({ pp: 1, l: 1 }, 0xE7, 0, undefined, destination), // vmovntdq [m256], ymm0
            ], model: s => {
                const [low, high] = [s.load_at(0, 16), s.load_at(16, 16)];
                if(n < 4)
                {
                    [s.x[1], s.h[1]] = [0n, 0n];
                    for(const r of [2, 3, 4]) [s.x[r], s.h[r]] = [low, high];
                    [s.x[5], s.h[5]] = [s.x[5] ^ low, 0n];
                }
                else
                {
                    s.x.fill(0n);
                    s.h.fill(0n);
                    [s.x[0], s.h[0]] = [low, high];
                }
                s.store_at(0, 16, low);
                s.store_at(16, 16, high);
            } });
        }
        const steps = await check_cases("VEX.256 moves and VEX.128 forms in a block", cases);
        if(simd(machines[1])) assert.ok(steps < cases.length / 2, `VEX.256 moves in a block: the page tier templates (${steps} steps)`);
    }
    console.log(`PASS: the page tier templates for ${PAGE_HOT.length + PAGE_HOT_FP.length + PAGE_HOT_256.length} hot forms, VEX.256 moves among VEX.128 forms in a block`);

    // (IR Tier-0 made the instruction after an interpreted VEX one a dispatch
    // entry, so a loop of VEX forms was checked to dispatch as often as one of
    // their legacy forms, P5 part 5; the page tier, which replaced it in
    // P7.5, interprets 32-bit code one instruction at a time, VEX or not)

    // VMASKMOVDQU to [DI] with an address-size prefix (DI's address below
    // 64 KiB; EDI's upper half ignored)
    {
        const f = FORMS.find(f => f.kind === "maskmov");
        const cases = [];
        for(let n = 0; n < 8; n++)
        {
            const c = form_case(f, n), low = 0xC000 + n * SPAN;
            cases.push({ ...c, pre: mov_r32(7, 0x5A5A0000 | low + c.at), code: [0x67, ...c.code], destination_at: low });
        }
        await check_cases("vmaskmovdqu (address size 16)", cases);
    }
    console.log("PASS: VMASKMOVDQU to [DI]");

    // Legacy SSE keeps bits 255:128 of its destination, VEX.128 zeroes them
    {
        const chain = [
            0x0F, 0x28, 0xCA,                       // movaps xmm1, xmm2
            ...vex({ pp: 0 }, 0x28, 3, 4),          // vmovaps xmm3, xmm4
            0x0F, 0x57, 0xEE,                       // xorps xmm5, xmm6
            ...vex({ pp: 0, vvvv: 6 }, 0x57, 6, 6), // vxorps xmm6, xmm6, xmm6
            0xF3, 0x0F, 0x10, 0xF8,                 // movss xmm7, xmm0
            ...vex({ pp: 1, vvvv: 7 }, 0xEB, 0, 1), // vpor xmm0, xmm7, xmm1
        ];
        await check_cases("legacy and VEX moves", [{ n: 0, code: chain, model: s => {
            s.x[1] = s.x[2];
            s.x[3] = s.x[4]; s.h[3] = 0n;
            s.x[5] ^= s.x[6];
            s.x[6] = 0n; s.h[6] = 0n;
            s.x[7] = s.x[7] & ~mask(32) | s.x[0] & mask(32);
            s.x[0] = s.x[7] | s.x[1]; s.h[0] = 0n;
        } }]);
    }
    // CR0.EM and CR4.OSFXSR do not matter to VEX forms
    await check_cases("VEX with CR0.EM or without CR4.OSFXSR", [
        { n: 0, pre: SET_CR0(4), code: vex({ pp: 0 }, 0x28, 1, 2), post: CLEAR_CR0(4), model: s => { s.x[1] = s.x[2]; s.h[1] = 0n; } },
        { n: 1, pre: cr4(0, ~OSFXSR), code: vex({ pp: 1, vvvv: 3 }, 0xEF, 1, 2), post: cr4(OSFXSR), model: s => { s.x[1] = s.x[3] ^ s.x[2]; s.h[1] = 0n; } },
        { n: 2, pre: [...SET_CR0(4), ...cr4(0, ~OSFXSR)], code: vex({ pp: 0 }, 0x77), post: [...CLEAR_CR0(4), ...cr4(OSFXSR)], model: s => s.h.fill(0n) },
    ]);
    // narrow operands at the end of a page: no access beyond them
    const form = (pp, op, kind) => FORMS.find(f => f.pp === pp && f.op === op && f.kind === kind && (f.map || 1) === 1);
    // (the form of a name, not one of the 64-bit mode's; the VEX.256 one)
    const named = (name, kind) => FORMS.find(f => f.name === name && !f.long && (kind === undefined || f.kind === kind));
    const ymm = (name, kind) => FORMS.find(f => f.name === name && f.l === 1 && (kind === undefined || f.kind === kind));
    for(const [label, f, d, v, imm8] of [
        ["vmovss xmm1, [m32]", form(2, 0x10, "scalar"), 1], ["vmovsd xmm2, [m64]", form(3, 0x10, "scalar"), 2],
        ["vmovlps xmm3, xmm4, [m64]", form(0, 0x12, "low"), 3, 4], ["vmovhpd xmm5, xmm6, [m64]", form(1, 0x16, "high"), 5, 6],
        ["vmovddup xmm7, [m64]", form(3, 0x12, "load"), 7], ["vmovq xmm0, [m64]", form(2, 0x7E, "load"), 0],
        ["vmovd xmm1, [m32]", form(1, 0x6E, "gpr_load"), 1], ["vldmxcsr [m32]", form(0, 0xAE, "ldmxcsr"), 2],
        ["vmovss [m32], xmm1", form(2, 0x11, "scalar_st"), 1], ["vmovhps [m64], xmm2", form(0, 0x17, "store64"), 2],
        ["vmovq [m64], xmm3", form(1, 0xD6, "store"), 3], ["vstmxcsr [m32]", form(0, 0xAE, "stmxcsr"), 3],
        ["vmovd [m32], xmm4", form(1, 0x7E, "gpr_store"), 4],
        ["vpmovsxbq xmm1, [m16]", named("vpmovsxbq"), 1], ["vpmovzxdq xmm7, [m64]", named("vpmovzxdq"), 7],
        ["vpinsrb xmm2, xmm3, [m8], 1", named("vpinsrb"), 2, 3, 1], ["vinsertps xmm5, xmm6, [m32], 0x10", named("vinsertps"), 5, 6, 0x10],
        ["vpextrb [m8], xmm4, 2", named("vpextrb"), 4, undefined, 2], ["vpextrw [m16], xmm3, 5", named("vpextrw", "extract"), 3, undefined, 5],
        ["vaddss xmm1, xmm2, [m32]", named("vaddss"), 1, 2], ["vcvtsd2ss xmm3, xmm4, [m64]", named("vcvtsd2ss"), 3, 4],
        ["vcvtps2pd xmm5, [m64]", named("vcvtps2pd"), 5], ["vroundsd xmm6, xmm7, [m64], 1", named("vroundsd"), 6, 7, 1],
        ["vcomiss xmm0, [m32]", named("vcomiss"), 0], ["vbroadcastss xmm2, [m32]", named("vbroadcastss"), 2],
        // (VEX.256: 32 bytes, or those of the element)
        ["vmovups ymm1, [m256]", ymm("vmovups", "load"), 1], ["vmovdqu [m256], ymm2", ymm("vmovdqu", "store"), 2],
        ["vmovddup ymm3, [m256]", ymm("vmovddup"), 3], ["vptest ymm4, [m256]", ymm("vptest"), 4],
        ["vbroadcastsd ymm5, [m64]", ymm("vbroadcastsd"), 5], ["vbroadcastf128 ymm6, [m128]", ymm("vbroadcastf128"), 6],
        ["vinsertf128 ymm7, ymm0, [m128], 1", ymm("vinsertf128"), 7, 0, 1], ["vextractf128 [m128], ymm1, 1", ymm("vextractf128"), 1, undefined, 1],
        // (AVX2: the count of a shift by xmm/m128; the elements of
        // broadcasts and extensions, VBROADCASTI128's m128)
        ["vpsrlw ymm1, ymm2, [m128]", ymm("vpsrlw", "binary"), 1, 2], ["vpslld ymm3, ymm4, [m128]", ymm("vpslld", "binary"), 3, 4],
        ["vpbroadcastb xmm1, [m8]", named("vpbroadcastb"), 1], ["vpbroadcastw ymm2, [m16]", ymm("vpbroadcastw"), 2],
        ["vpbroadcastq ymm3, [m64]", ymm("vpbroadcastq"), 3], ["vbroadcasti128 ymm4, [m128]", ymm("vbroadcasti128"), 4],
        ["vpmovsxbq ymm5, [m32]", ymm("vpmovsxbq"), 5], ["vpmovzxwq ymm6, [m64]", ymm("vpmovzxwq"), 6], ["vpmovzxbw ymm7, [m128]", ymm("vpmovzxbw"), 7],
    ])
    {
        const at = SPAN - memory_bytes(f), store = STORES.includes(f.kind);
        // (VLDMXCSR: a valid value)
        const source = Uint8Array.from(SOURCES.subarray(0, SPAN));
        if(f.kind === "ldmxcsr") source.set(u32(0x7F80), at);
        const c = { n: 0, at, source, code: vex({ map: f.map || 1, pp: f.pp, l: f.l ?? 0, vvvv: v ?? 0 }, f.op, d, undefined, ABSENT - SPAN + at, imm8),
            model: s => execute(f, s, { d, v, imm8, long: false }) };
        // (VCOMISS, VPTEST: the flags)
        if(f.operands === "comi" || f.kind === "ptest") Object.assign(c, { pre: FLAGS_BEFORE, post: store_flags(OUT + 4) });
        await check_cases(label + " at a page end", [{ ...c, [store ? "destination_at" : "source_at"]: ABSENT - SPAN }], { before: vm => pages(vm, ABSENT, false) });
    }
    // VMASKMOVPS/PD across into an absent page: the unselected lanes there
    // are not accessed (no fault), the selected ones before it are
    {
        // (the low quadword's lanes selected: those of VMASKMOVPS 0 and 1, VMASKMOVPD 0)
        const low_lanes = big(Uint8Array.from({ length: 16 }, (_, i) => i < 8 ? 0x80 : 0));
        // (AVX2: VPMASKMOVD and VPMASKMOVQ, VEX.W1, as VMASKMOVPS and VMASKMOVPD)
        for(const [op, w] of [[0x2C, 0], [0x2D, 0], [0x2E, 0], [0x2F, 0], [0x8C, 0], [0x8C, 1], [0x8E, 0], [0x8E, 1]])
        {
            const f = FORMS.find(f => f.map === 2 && f.op === op && f.w === w && !f.l);
            const store = f.kind === "maskstore";
            const c = { n: 0, at: SPAN - 8, registers: { 2: low_lanes }, code: vex({ map: 2, pp: 1, w, vvvv: 2 }, op, 1, undefined, ABSENT - 8),
                model: s => execute(f, s, { d: 1, v: 2, long: false }) };
            await check_cases(`${f.name} across into an absent page (the lanes there not selected)`, [{ ...c, [store ? "destination_at" : "source_at"]: ABSENT - SPAN }],
                { before: vm => pages(vm, ABSENT, false) });
        }
        // (VEX.256: the 32-byte operand's high half on the absent page; the
        // low half's lanes selected, the high half's not)
        const low_half = big(Uint8Array.from({ length: 16 }, (_, i) => i % 4 === 3 ? 0x80 : 0));
        for(const [op, w] of [[0x2C, 0], [0x2D, 0], [0x2E, 0], [0x2F, 0], [0x8C, 0], [0x8C, 1], [0x8E, 0], [0x8E, 1]])
        {
            const f = FORMS.find(f => f.map === 2 && f.op === op && f.w === w && f.l === 1);
            const store = f.kind === "maskstore";
            const c = { n: 0, at: SPAN - 16, registers: { 2: low_half }, uppers: { 2: 0n },
                code: vex({ map: 2, pp: 1, l: 1, w, vvvv: 2 }, op, 1, undefined, ABSENT - 16),
                model: s => execute(f, s, { d: 1, v: 2, long: false }) };
            await check_cases(`${f.name} ymm across into an absent page (the lanes there not selected)`,
                [{ ...c, [store ? "destination_at" : "source_at"]: ABSENT - SPAN }], { before: vm => pages(vm, ABSENT, false) });
        }
    }
    for(const vm of machines) pages(vm, ABSENT, true);
    // VMASKMOVPS/PD set the accessed (and, storing, the dirty) bit of the
    // pages their selected lanes are on; the SDM leaves those of pages with
    // only unselected lanes to the implementation: v86 does not set them
    {
        const low_lanes = big(Uint8Array.from({ length: 16 }, (_, i) => i < 8 ? 0x80 : 0));
        const pte = (vm, page) => word(vm, 0x13000 + (page >>> 12) * 4);
        for(const op of [0x2C, 0x2E])
        {
            const program = [...xrstor(area_in(0)), ...vex({ map: 2, pp: 1, vvvv: 2 }, op, 1, undefined, ABSENT - 8), ...xsave(area_out(0))];
            const results = await run_all(program, vm => {
                vm.write_memory(area(0, { 2: low_lanes }), area_in(0));
                pages(vm, ABSENT - 0x1000, true);
                pages(vm, ABSENT, true);
            }, machines, vm => [pte(vm, ABSENT - 0x1000) & 0x60, pte(vm, ABSENT) & 0x60]);
            for(const { label, data } of results)
            {
                assert.deepEqual(data, [op === 0x2E ? 0x60 : 0x20, 0], `vmaskmovps ${op === 0x2E ? "store" : "load"} (${label}): accessed/dirty bits of the selected lanes' page and the other`);
            }
            checks++;
        }
    }
    // A gather faulting on element k (#PF at the instruction, CR2 the
    // element's address): the elements before it done (loaded if selected,
    // their mask cleared), the rest's mask normalized (all ones or zero by
    // its sign) and the destination's kept, the mask beyond the elements
    // zero (the SDM's operation). The guest then maps the page and runs the
    // gather again, which completes the rest: the result of one uninterrupted
    // gather. (Element 0 not selected; scale 1, base EBX, which XSAVE's
    // address needs too.)
    {
        const PTE = 0x13000 + (ABSENT >>> 12) * 4;
        const pte = value => [0xC7, 0x05, ...u32(PTE), ...u32(value), 0x0F, 0x01, 0x3D, ...u32(ABSENT)];
        const [d, v, index] = [1, 2, 3];
        for(const f of FORMS.filter(f => f.kind === "gather"))
        {
            const count = (f.l ? 32 : 16) / Math.max(f.data, f.index), k = count > 2 ? 2 : 1, bits = BigInt(8 * f.data);
            let indices = 0n, selection = 0n;
            for(let j = 0; j < count; j++)
            {
                indices |= BigInt(j < k ? 8 * j : 64 + 8 * j) << BigInt(8 * f.index * j);
                if(j) selection |= 1n << bits * BigInt(j + 1) - 1n;
            }
            const source = Uint8Array.from(DESTINATIONS.subarray(0, 128));
            const c = { n: 0, at: 0, source, registers: { [index]: indices & mask(128), [v]: selection & mask(128) },
                uppers: { [index]: indices >> 128n, [v]: selection >> 128n } };
            const gather = [...vex({ map: 2, pp: 1, l: f.l ?? 0, w: f.w, vvvv: v }, f.op), d << 3 | 4, index << 3 | 3];
            const prefix = [...xrstor(area_in(0)), ...mov_r32(3, ABSENT - 64)];
            const program = [...prefix, ...gather, ...xsave(area_out(1)), ...pte(ABSENT | 3),
                ...mov_r32(3, ABSENT - 64), ...gather, ...xsave(area_out(0)), ...pte(0)];
            const results = await run_all(program, vm => {
                vm.write_memory(Uint8Array.from(u32(gather.length)), SKIP);
                vm.write_memory(area(0, c.registers, c.uppers), area_in(0));
                vm.write_memory(source, ABSENT - 64);
                pages(vm, ABSENT, false);
            }, machines, vm => ({ fault: [0, 4, 8, 12].map(o => word(vm, FAULT + o)), partial: bytes(vm, area_out(1), 832), done: bytes(vm, area_out(0), 832) }));
            // the expected states
            const whole = initial(0, c);
            execute(f, whole, { d, v, index, scale: 0, long: false });
            const partial = initial(0, c);
            const elements = (value, size) => Array.from({ length: 256 / size }, (_, j) => value >> BigInt(size * j) & mask(size));
            const dest = elements(partial.x[d] | partial.h[d] << 128n, Number(bits));
            const masks = elements(partial.x[v] | partial.h[v] << 128n, Number(bits)).map((x, j) =>
                j >= count ? 0n : x >> bits - 1n ? mask(Number(bits)) : 0n);
            for(let j = 0; j < k; j++)
            {
                if(masks[j]) dest[j] = big(source.subarray(8 * j, 8 * j + f.data));
                masks[j] = 0n;
            }
            const join_all = list => list.reduceRight((value, x) => value << bits | x, 0n);
            const [partial_dest, partial_mask] = [join_all(dest), join_all(masks)];
            const name = `${f.name}${f.l ? " ymm" : ""} faulting on element ${k}`;
            for(const { label, data } of results)
            {
                assert.deepEqual(data.fault.slice(0, 3), [14, CODE + PROLOGUE.length + prefix.length, ABSENT + 8 * k], `${name} (${label}): #PF, EIP, CR2`);
                for(const [r, value, what, area_bytes] of [[d, partial_dest, "destination", data.partial], [v, partial_mask, "mask", data.partial],
                    [d, whole.x[d] | whole.h[d] << 128n, "destination after the restart", data.done], [v, whole.x[v] | whole.h[v] << 128n, "mask after the restart", data.done]])
                {
                    assert.equal(hex(area_bytes.subarray(160 + 16 * r, 176 + 16 * r)), hex(le(value & mask(128))), `${name} (${label}): ${what}, bits 127:0`);
                    assert.equal(hex(area_bytes.subarray(576 + 16 * r, 592 + 16 * r)), hex(le(value >> 128n)), `${name} (${label}): ${what}, bits 255:128`);
                }
            }
            checks++;
        }
        for(const vm of machines) pages(vm, ABSENT, true);
    }
    // A gather's segment: an override's (FS, its base 0x10000) for every
    // element, at the base (EBX) plus the element's scaled index (within 120
    // bytes either side); every third element not selected. A third of the
    // forms, each width and size in turn
    {
        const FS_BASE = 0x10000, [d, v, index] = [4, 5, 6], source = Uint8Array.from(SOURCES.subarray(0, 256));
        const saved = machines.map(vm => ["segment_offsets", "segment_limits", "segment_is_null"].map(name => vm.v86.cpu[name][4]));
        const segment = (vm, values) => ["segment_offsets", "segment_limits", "segment_is_null"].forEach((name, i) => { vm.v86.cpu[name][4] = values[i]; });
        for(const [n, f] of FORMS.filter(f => f.kind === "gather").entries())
        {
            if(n % 3) continue;
            const scale = n & 3, count = (f.l ? 32 : 16) / Math.max(f.data, f.index);
            let indices = 0n, selection = 0n;
            for(let j = 0; j < 32 / f.index; j++)
            {
                const offset = (n * 37 + j * 53) % 241 - 120;
                indices |= BigInt.asUintN(8 * f.index, BigInt(Math.trunc(offset / 2 ** scale))) << BigInt(8 * f.index * j);
            }
            for(let j = 0; j < count; j++) if(j % 3 !== 1) selection |= 1n << BigInt(8 * f.data * (j + 1) - 1);
            const c = { n: 0, at: 128, source, registers: { [index]: indices & mask(128), [v]: selection & mask(128) },
                uppers: { [index]: indices >> 128n, [v]: selection >> 128n } };
            const gather = [0x64, ...vex({ map: 2, pp: 1, l: f.l ?? 0, w: f.w, vvvv: v }, f.op), d << 3 | 4, scale << 6 | index << 3 | 3];
            const program = [...xrstor(area_in(0)), ...mov_r32(3, SOURCE + 128 - FS_BASE), ...gather, ...xsave(area_out(0))];
            const results = await run_all(program, vm => {
                vm.write_memory(area(0, c.registers, c.uppers), area_in(0));
                vm.write_memory(source, SOURCE);
                segment(vm, [FS_BASE, -1, 0]);
            }, machines, vm => bytes(vm, area_out(0), 832));
            const s = initial(0, c);
            execute(f, s, { d, v, index, scale, long: false });
            const name = `${f.name}${f.l ? " ymm" : ""} with FS's base`;
            for(const { label, data } of results)
            {
                for(const r of [d, v])
                {
                    assert.equal(hex(data.subarray(160 + 16 * r, 176 + 16 * r)), hex(le(s.x[r])), `${name} (${label}): XMM${r}`);
                    assert.equal(hex(data.subarray(576 + 16 * r, 592 + 16 * r)), hex(le(s.h[r])), `${name} (${label}): YMM${r}'s upper half`);
                }
            }
            checks++;
        }
        machines.forEach((vm, i) => segment(vm, saved[i]));
    }
    console.log("PASS: legacy SSE keeps the upper halves, VEX zeroes them; CR0.EM and CR4.OSFXSR ignored; narrow operands and VMASKMOV's unselected lanes at a page end (no access, no accessed bit); gathers faulting on an element, then restarted; gathers with FS's base");

    // #UD without CR4.OSXSAVE or with XCR0 3 (before #NM), #NM with CR0.TS
    for(const [label, form] of [
        ["vmovaps xmm1, xmm2", vex({ pp: 0 }, 0x28, 1, 2)], ["vmovups xmm1, [mem]", vex({ pp: 0 }, 0x10, 1, undefined, SOURCE + 3)],
        ["vmovdqu [mem], xmm1", vex({ pp: 2 }, 0x7F, 1, undefined, DEST + 3)], ["vzeroupper", vex({}, 0x77)],
        ["vldmxcsr [mem]", vex({}, 0xAE, 2, undefined, SOURCE)], ["vmaskmovdqu", vex({ pp: 1 }, 0xF7, 1, 2)],
        ["vmovd ecx, xmm1", vex({ pp: 1 }, 0x7E, 1, 1)],
    ])
    {
        const memory = [DEST, DESTINATIONS.subarray(0, 32)];
        const before = vm => { vm.write_memory(DESTINATIONS.subarray(0, 32), DEST); vm.write_memory(Uint8Array.from(u32(0x1F80)), SOURCE); };
        await expect_fault(cr4(0, ~OSXSAVE), form, 6, { epilogue: cr4(OSXSAVE), before, memory, label: label + " without CR4.OSXSAVE" });
        await expect_fault(xsetbv(3), form, 6, { epilogue: xsetbv(7), before, memory, keep_upper: false, label: label + " with XCR0 3" });
        await expect_fault(SET_CR0(8), form, 7, { epilogue: CLTS, before, memory, label: label + " with CR0.TS" });
        await expect_fault([...SET_CR0(8), ...cr4(0, ~OSXSAVE)], form, 6, { epilogue: [...cr4(OSXSAVE), ...CLTS], before, memory, label: label + " with CR0.TS, without CR4.OSXSAVE" });
    }
    console.log("PASS: #UD without CR4.OSXSAVE or with XCR0 3, then #NM with CR0.TS");

    // #GP(0) for a misaligned operand of the aligned moves; #UD for VEX.L1 of
    // VLDMXCSR, VEX.vvvv other than 1111b without that operand; VLDMXCSR's reserved bits
    {
        const memory = [DEST, DESTINATIONS.subarray(0, 48)];
        const before = vm => vm.write_memory(DESTINATIONS.subarray(0, 48), DEST);
        for(const f of FORMS.filter(f => f.aligned))
        {
            const store = f.kind === "store";
            // (first an ordinary access to the same page: the page tier's template
            // finds it in the TLB, where its alignment check decides)
            const warm = store ? [0xA3, ...u32(DEST + 0x100)] : [0xA1, ...u32(SOURCE + 0x100)];
            // (VEX.256: aligned to 16 bytes, not to 32)
            const misaligned = f.l ? 16 : store ? 4 : 8;
            await expect_fault(warm, vex({ map: f.map || 1, pp: f.pp, l: f.l ?? 0 }, f.op, 1, undefined, (store ? DEST : SOURCE) + misaligned), 13,
                { error_code: 0, before, memory, label: `${f.name}${f.l ? " ymm" : ""} misaligned ${store ? "store" : "load"}` });
        }
        await expect_fault([], vex({ l: 1 }, 0xAE, 2, undefined, SOURCE), 6, { label: "vldmxcsr with VEX.L1" });
        await expect_fault([], vex({ pp: 0, vvvv: 3 }, 0x28, 1, 2), 6, { label: "vmovaps with VEX.vvvv 3" });
        await expect_fault([], vex({ three: true, vvvv: 1 }, 0x77), 6, { label: "vzeroupper with VEX.vvvv 1" });
        await expect_fault([], vex({ map: 3, pp: 1, w: 1, vvvv: 2 }, 0x4C, 1, 3, undefined, 0x40), 6, { label: "vpblendvb with VEX.W1" });
        await expect_fault([], vex({ pp: 1, vvvv: 2 }, 0x73, 3, undefined, SOURCE, 3), 6, { label: "vpsrldq with a memory operand" });
        await expect_fault([], vex({ pp: 1 }, 0xC5, 1, undefined, SOURCE, 1), 6, { label: "vpextrw (C5) with a memory operand" });
        await expect_fault([], vex({ pp: 1, vvvv: 3 }, 0x70, 1, 2, undefined, 0x1B), 6, { label: "vpshufd with VEX.vvvv 3" });
        // (gathers: the destination, mask and indices in three registers;
        // 32-bit addressing)
        for(const [label, prefix, vvvv, index] of [["the indices the destination", [], 2, 1], ["the mask the destination", [], 1, 3],
            ["the indices the mask", [], 2, 2], ["16-bit addressing", [0x67], 2, 3]])
        {
            await expect_fault(mov_r32(3, SOURCE), [...prefix, ...vex({ map: 2, pp: 1, vvvv }, 0x90), 1 << 3 | 4, 2 << 6 | index << 3 | 3], 6,
                { label: `vpgatherdd with ${label}` });
        }
        await expect_fault([], vex({}, 0xAE, 2, undefined, SOURCE + 4), 13, { error_code: 0, before: vm => vm.write_memory(Uint8Array.from(u32(0x10000)), SOURCE + 4), label: "vldmxcsr with a reserved bit" });
    }
    // #PF: a load from and a store to an absent page, nothing written; the
    // two VMASKMOVDQU writes: the whole range writable first, as MASKMOVDQU's
    {
        const memory = [ABSENT - 16, DESTINATIONS.subarray(0, 16)];
        const absent = vm => { vm.write_memory(DESTINATIONS.subarray(0, 16), ABSENT - 16); pages(vm, ABSENT, false); };
        await expect_fault([], vex({ pp: 0 }, 0x10, 1, undefined, ABSENT - 8), 14, { before: absent, cr2: ABSENT, error_code: 0, label: "vmovups across into an absent page" });
        await expect_fault([], vex({ pp: 3 }, 0x10, 1, undefined, ABSENT - 4), 14, { before: absent, cr2: ABSENT, error_code: 0, label: "vmovsd across into an absent page" });
        await expect_fault([], vex({ pp: 2 }, 0x7F, 1, undefined, ABSENT - 8), 14, { before: absent, cr2: ABSENT, error_code: 2, memory, label: "vmovdqu store across into an absent page" });
        await expect_fault([], vex({ pp: 1 }, 0xD6, 1, undefined, ABSENT - 4), 14, { before: absent, cr2: ABSENT, error_code: 2, memory, label: "vmovq store across into an absent page" });
        await expect_fault(mov_r32(7, ABSENT - 8), vex({ pp: 1 }, 0xF7, 1, 2), 14, { before: absent, cr2: ABSENT, error_code: 2, memory, label: "vmaskmovdqu across into an absent page" });
        // VMASKMOVPS/PD: a selected lane on the absent page faults, nothing
        // written (the lanes before it selected too: PS 0, 1 and 3, PD 0 and 1)
        const both = big(Uint8Array.from({ length: 16 }, (_, i) => i === 3 || i === 7 || i === 15 ? 0x80 : 0));
        await expect_fault([], vex({ map: 2, pp: 1, vvvv: 2 }, 0x2C, 1, undefined, ABSENT - 8), 14, { before: absent, cr2: ABSENT + 4, error_code: 0,
            registers: { 2: both }, label: "vmaskmovps load, lane 3 on an absent page" });
        await expect_fault([], vex({ map: 2, pp: 1, vvvv: 2 }, 0x2E, 1, undefined, ABSENT - 8), 14, { before: absent, cr2: ABSENT + 4, error_code: 2, memory,
            registers: { 2: both }, label: "vmaskmovps store, lane 3 on an absent page" });
        await expect_fault([], vex({ map: 2, pp: 1, vvvv: 2 }, 0x2F, 1, undefined, ABSENT - 8), 14, { before: absent, cr2: ABSENT, error_code: 2, memory,
            registers: { 2: both }, label: "vmaskmovpd store, lane 1 on an absent page" });
        // VEX.256: the 32 bytes' high half on the absent page; nothing written
        await expect_fault([], vex({ pp: 0, l: 1 }, 0x10, 1, undefined, ABSENT - 16), 14, { before: absent, cr2: ABSENT, error_code: 0, label: "vmovups ymm across into an absent page" });
        await expect_fault([], vex({ pp: 2, l: 1 }, 0x7F, 1, undefined, ABSENT - 16), 14, { before: absent, cr2: ABSENT, error_code: 2, memory, label: "vmovdqu ymm store across into an absent page" });
        await expect_fault([], vex({ map: 3, pp: 1, l: 1 }, 0x19, 1, undefined, ABSENT - 8, 1), 14, { before: absent, cr2: ABSENT, error_code: 2, memory, label: "vextractf128 store across into an absent page" });
        // (VMASKMOVPS: lanes 3 and 5 selected, the 32 bytes at ABSENT - 16: lane 5 on the absent page)
        const lanes_3_5 = [big(Uint8Array.from({ length: 16 }, (_, i) => i === 15 ? 0x80 : 0)), big(Uint8Array.from({ length: 16 }, (_, i) => i === 7 ? 0x80 : 0))];
        await expect_fault([], vex({ map: 2, pp: 1, l: 1, vvvv: 2 }, 0x2C, 1, undefined, ABSENT - 16), 14, { before: absent, cr2: ABSENT + 4, error_code: 0,
            registers: { 2: lanes_3_5[0] }, uppers: { 2: lanes_3_5[1] }, label: "vmaskmovps ymm load, lane 5 on an absent page" });
        await expect_fault([], vex({ map: 2, pp: 1, l: 1, vvvv: 2 }, 0x2E, 1, undefined, ABSENT - 16), 14, { before: absent, cr2: ABSENT + 4, error_code: 2, memory,
            registers: { 2: lanes_3_5[0] }, uppers: { 2: lanes_3_5[1] }, label: "vmaskmovps ymm store, lane 5 on an absent page" });
        for(const vm of machines) pages(vm, ABSENT, true);
    }
    // VEX.256 floating point: all lanes in one exception context (SDM Vol. 1,
    // 11.5.3). VADDPS ymm2, ymm1, ymm0 with only IE unmasked: the low half's
    // sums are inexact (PE, masked), the high half has an SNaN (IE): #XM
    // before any post-computation flag, MXCSR gets IE alone, YMM2 unchanged
    {
        const join32 = l => l.reduceRight((v, x) => v << 32n | x, 0n);
        const one = 0x3F800000n, tiny = 0x30800000n, snan = 0x7F800001n;
        const registers = { 1: join32([one, one, one, one]), 0: join32([tiny, tiny, tiny, tiny]) };
        const uppers = { 1: join32([one, one, one, one]), 0: join32([snan, one, one, one]) };
        const mxcsr = 0x1F80 & ~0x80;
        const initial = area(0, registers, uppers);
        initial.set(u32(mxcsr), 24);
        const at = CODE + PROLOGUE.length + xrstor(0).length;
        const faulting = vex({ pp: 0, l: 1, vvvv: 1 }, 0x58, 2, 0);
        const results = await run_all([...xrstor(area_in(0)), ...faulting, ...xsave(area_out(0))], vm => {
            vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
            vm.write_memory(initial, area_in(0));
        }, machines, vm => ({ fault: [0, 4].map(o => word(vm, FAULT + o)), area: bytes(vm, area_out(0), 832) }),
        vm => vm !== machines[1] || page_rounds() >= 300);
        for(const { label, data } of results)
        {
            assert.deepEqual(data.fault, [19, at], `vaddps ymm, an SNaN in the high half (${label}): #XM`);
            assert.equal(word_of(data.area, 24), mxcsr | 1, `vaddps ymm, an SNaN in the high half (${label}): MXCSR gets IE alone`);
            assert.equal(hex(data.area.subarray(160, 288)), hex(initial.subarray(160, 288)), `vaddps ymm (${label}): XMM registers kept`);
            assert.equal(hex(data.area.subarray(576, 704)), hex(initial.subarray(576, 704)), `vaddps ymm (${label}): YMM_Hi128 kept`);
        }
        checks++;
    }
    console.log("PASS: #GP(0) for misaligned aligned moves and VLDMXCSR's reserved bits, #UD for VEX.L1, VEX.W1, VEX.vvvv, memory operands where invalid and gathers' register overlaps and 16-bit addressing, #PF without effect; one exception context for a VEX.256 floating-point form's lanes");
    console.log(`PASS: ${checks} AVX checks in the interpreter and the page tier`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/rust/avx_fp.mjs                                                                    0000644 0000000 0000000 00000036274 00000000000 014035  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // AVX floating point in the 32-bit engines (docs/simd-xsave-plan.md 8, P5
// part 3): the VEX form of every SSE/SSE2/SSE3/SSE4.1 floating-point form of
// tests/rust/sse_fp_cases.mjs against the same model (exact rational
// arithmetic, independent of SoftFloat and cpu/simd_fp.rs), with VEX's
// operands: the destination XMM2, the first source XMM1, the second XMM0 or
// memory; VCMPPS/PD/SS/SD with all 32 predicates. Each case sets MXCSR (the
// four rounding modes, DAZ, FZ, masked and unmasked exceptions) and checks
// the destination, MXCSR and the fault: #XM, or #UD without
// CR4.OSXMMEXCPT, with the destination unchanged. Every case runs in the
// interpreter, then hot under the page tier. (The region tiers, a second
// compiled arm, were deleted in M11.)
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { FORMS, MXCSRS, bytes128, cases, expect } from "./sse_fp_cases.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x300000, FAULTS = 0x3F0000, CASE = 0x3FF000, SKIP = 0x3FF004;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
// (the destination's value before: unchanged by a faulting instruction)
const BEFORE = 0x5A5A5A5A_A5A5A5A5_12345678_9ABCDEF0n;

const ldmxcsr = a => [0x0F, 0xAE, 0x15, ...u32(a)], stmxcsr = a => [0x0F, 0xAE, 0x1D, ...u32(a)];
const movdqu_load = (r, a) => [0xF3, 0x0F, 0x6F, 0x05 | r << 3, ...u32(a)];
const movdqu_store = (r, a) => [0xF3, 0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
// (VEX.256 VMOVDQU)
const vmovdqu_load = (r, a) => [0xC5, 0xFE, 0x6F, 0x05 | r << 3, ...u32(a)];
const vmovdqu_store = (r, a) => [0xC5, 0xFE, 0x7F, 0x05 | r << 3, ...u32(a)];
const store_eax = a => [0xA3, ...u32(a)];
const OSXSAVE = 1 << 18;
const xsetbv = value => [0xB9, ...u32(0), 0xB8, ...u32(value), 0xBA, ...u32(0), 0x0F, 0x01, 0xD1];

// The VEX forms: those of the legacy ones with XMM operands. `operands`: the
// first source (VEX.vvvv) or none ("two"), a flags result ("comi"), a
// general-purpose destination (ECX) or source (EAX)
const VEX_FORMS = FORMS.filter(form => !["from_mmx", "to_mmx"].includes(form.kind)).map(form => {
    const two = ["from_dwords", "to_dwords"].includes(form.kind) ||
        !form.scalar && (form.op === "sqrt" || ["reciprocal", "widen", "narrow", "round"].includes(form.kind));
    const operands = ["comi", "to_gpr", "from_gpr"].includes(form.kind) ? form.kind : two ? "two" : "three";
    return { ...form, name: "v" + form.name, operands, pp: { "": 0, 102: 1, 243: 2, 242: 3 }[form.prefix.join()], vex_map: form.map === 0x3A ? 3 : 1 };
});
// P6 part 2: the VEX.256 forms, of the packed ones but VDPPD
const VEX256_FORMS = VEX_FORMS.filter(f => !f.scalar && ["two", "three"].includes(f.operands) && f.name !== "vdppd")
    .map(f => ({ ...f, name: f.name + " ymm", l: 1 }));
const BEFORE256 = BEFORE | BEFORE << 128n;
/** A VEX.256 form's cases: two of its VEX.128 form's in one (the second in
 * the high half; VCVTPS2PD's and VCVTDQ2PD's XMM source: the first's), the
 * model over all lanes with one exception context */
function cases256(form)
{
    const list = cases(form);
    const xmm_source = form.kind === "widen" || form.kind === "from_dwords" && form.double;
    return Array.from({ length: list.length >> 1 }, (_, k) => {
        const [c, d] = [list[2 * k], list[2 * k + 1]];
        const a = c.a | d.a << 128n, b = xmm_source ? c.b : c.b | d.b << 128n;
        const imm8 = form.kind === "compare" ? (k * 5 + 3) & 31 : c.imm8;
        return { mxcsr: c.mxcsr, a, b, imm8, ...expect(form, c.mxcsr, a, b, imm8, 256) };
    });
}
/** The instruction: destination XMM2 (ECX; XMM1 for VCOMIS), VEX.vvvv XMM1,
 * r/m XMM0 (EAX) or [source]; both VEX prefixes (`three`) */
function instruction(form, memory, source, imm8, three)
{
    const reg = form.operands === "comi" ? 1 : form.operands === "to_gpr" ? 1 : 2;
    const vvvv = ["three", "from_gpr"].includes(form.operands) ? 1 : 0;
    const modrm = memory ? [0x05 | reg << 3, ...u32(source)] : [0xC0 | reg << 3 | 0];
    const tail = [form.code, ...modrm, ...(form.imm8 ? [imm8] : [])];
    const fields = (~vvvv & 15) << 3 | (form.l ? 4 : 0) | form.pp;
    if(form.vex_map === 1 && !three) return [0xC5, 0x80 | fields, ...tail];
    return [0xC4, 0xE0 | form.vex_map, fields, ...tail];
}
function program(form, memory, list)
{
    const p = [];
    list.forEach((c, n) => {
        const base = DATA + n * 64;
        p.push(0xC7, 0x05, ...u32(CASE), ...u32(n));
        p.push(...ldmxcsr(base + 32));
        // XMM1: the first source; XMM2 (ECX): the destination's value before; XMM0 (EAX): the second source
        p.push(...movdqu_load(1, base), ...movdqu_load(2, base + 48));
        if(form.operands === "to_gpr") p.push(0xB9, ...u32(0x5A5A5A5A));
        if(!memory) p.push(...form.operands === "from_gpr" ? [0xB8, ...u32(Number(c.b & 0xFFFFFFFFn))] : movdqu_load(0, base + 16));
        // (the handler skips the instruction: its length, by its VEX prefix)
        const vex = instruction(form, memory, base + 16, c.imm8, n & 1);
        p.push(0xC7, 0x05, ...u32(SKIP), ...u32(vex.length), ...vex);
        p.push(...stmxcsr(OUT + n * 32 + 16));
        if(form.operands === "comi") p.push(0x9C, 0x58, ...store_eax(OUT + n * 32));
        else if(form.operands === "to_gpr") p.push(0x89, 0x0D, ...u32(OUT + n * 32));
        else p.push(...movdqu_store(2, OUT + n * 32));
    });
    return p;
}

/** A VEX.256 form's program: YMM1 the first source, YMM2 the destination's
 * value before, YMM0 or [source] the second source; 128 bytes of data and 64
 * of results per case */
function program256(form, memory, list)
{
    const p = [];
    list.forEach((c, n) => {
        const base = DATA + n * 128;
        p.push(0xC7, 0x05, ...u32(CASE), ...u32(n));
        p.push(...ldmxcsr(base + 64));
        p.push(...vmovdqu_load(1, base), ...vmovdqu_load(2, base + 96));
        if(!memory) p.push(...vmovdqu_load(0, base + 32));
        const vex = instruction(form, memory, base + 32, c.imm8, n & 1);
        p.push(0xC7, 0x05, ...u32(SKIP), ...u32(vex.length), ...vex);
        p.push(...stmxcsr(OUT + n * 64 + 32));
        p.push(...vmovdqu_store(2, OUT + n * 64));
    });
    return p;
}

const machines = [];
async function run(vm, code, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(code), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 60000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it for the case, skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58);
    p.push(0xA1, ...u32(CASE), 0xC7, 0x04, 0x85, ...u32(FAULTS), ...u32(vector)); // mov [FAULTS + eax*4], vector
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true], [19, false]];
async function create_machines()
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 64 << 20,
            cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], cpu_features_unreleased: true,
            ...arm, disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
let total = 0;
try
{
    machines.push(...await create_machines());
    for(const xmm_exceptions of [true, false])
    {
        // CR4.OSFXSR (the legacy loads and stores), OSXSAVE, OSXMMEXCPT (else
        // unmasked exceptions are #UD); XCR0 7; CR0.TS clear
        const cr4 = [0x0F, 0x20, 0xE0, 0x0D, ...u32(OSXSAVE | (xmm_exceptions ? 0x600 : 0x200)), ...(xmm_exceptions ? [] : [0x25, ...u32(~0x400 >>> 0)]), 0x0F, 0x22, 0xE0];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0x0F, 0x06, ...cr4, ...xsetbv(7)];
        for(const form of xmm_exceptions ? [...VEX_FORMS, ...VEX256_FORMS] : VEX_FORMS.filter(f => f.kind === "binary" && !f.double))
        {
            // (AVX_FP_ONLY=name: one form, for debugging)
            if(process.env.AVX_FP_ONLY && form.name !== process.env.AVX_FP_ONLY) continue;
            // (a VEX.256 form: 128 bytes of data and 64 of results per case)
            const [stride, out_stride] = form.l ? [128, 64] : [64, 32];
            for(const memory of [false, true])
            {
                // (VCMP*: the 32 predicates)
                const list = form.l ? cases256(form) : cases(form).map((c, n) => form.kind !== "compare" ? c :
                    { ...c, imm8: (n * 5 + 3) & 31, ...expect(form, c.mxcsr, c.a, c.b, (n * 5 + 3) & 31) });
                const code = loop([...prologue, ...(form.l ? program256 : program)(form, memory, list)]);
                const data = new Uint8Array(list.length * stride);
                const bytes = (v, n) => Uint8Array.from({ length: n }, (_, i) => Number(v >> BigInt(8 * i) & 0xFFn));
                list.forEach((c, n) => {
                    if(form.l)
                    {
                        data.set(bytes(c.a, 32), n * 128);
                        data.set(bytes(c.b, 32), n * 128 + 32);
                        data.set(u32(c.mxcsr), n * 128 + 64);
                        data.set(bytes(BEFORE256, 32), n * 128 + 96);
                        return;
                    }
                    data.set(bytes128(c.a), n * 64);
                    data.set(bytes128(c.b), n * 64 + 16);
                    data.set(u32(c.mxcsr), n * 64 + 32);
                    data.set(bytes128(BEFORE), n * 64 + 48);
                });
                // (every run: the cold one is mostly interpreted, the program was rewritten)
                const runs = [];
                for(const [m, vm] of machines.entries())
                {
                    vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
                    VECTORS.forEach(([vector, error_code], i) => {
                        const h = HANDLER + i * 0x100;
                        vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
                        vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
                    });
                    for(const warm of [true, false])
                    {
                        vm.write_memory(data, DATA);
                        vm.write_memory(new Uint8Array(list.length * out_stride), OUT);
                        vm.write_memory(new Uint8Array(list.length * 4), FAULTS);
                        vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
                        await run(vm, code, warm, vm === machines[0]);
                        runs.push({ run: `machine ${m} ${warm ? "hot" : "one round"}`, out: Uint8Array.from(vm.read_memory(OUT, list.length * out_stride)),
                            faults: Uint8Array.from(vm.read_memory(FAULTS, list.length * 4)) });
                    }
                }
                for(const { run, out, faults: fault_bytes } of runs)
                {
                    const faults = new DataView(fault_bytes.buffer);
                    const view = new DataView(out.buffer);
                    list.forEach((c, n) => {
                        const label = `${form.name}${memory ? " [mem]" : ""} case ${n} on ${run}: mxcsr ${c.mxcsr.toString(16)} a ${c.a.toString(16)} b ${c.b.toString(16)}${form.imm8 ? " imm8 " + c.imm8 : ""}`;
                        const vector = faults.getUint32(n * 4, true);
                        assert.equal(vector, c.fault ? xmm_exceptions ? 19 : 6 : 0, label + ": fault");
                        if(form.l)
                        {
                            // (all 256 bits; a faulting instruction leaves them alone)
                            assert.equal(view.getUint32(n * 64 + 32, true), c.after, label + ": MXCSR");
                            const actual = [0, 1, 2, 3].reduce((v, q) => v | view.getBigUint64(n * 64 + 8 * q, true) << BigInt(64 * q), 0n);
                            assert.equal(actual.toString(16), (c.fault ? BEFORE256 : c.result).toString(16), label + ": result");
                            return;
                        }
                        assert.equal(view.getUint32(n * 32 + 16, true), c.after, label + ": MXCSR");
                        // a faulting instruction leaves its destination alone
                        let actual, expected;
                        if(form.operands === "comi")
                        {
                            actual = BigInt(view.getUint32(n * 32, true) & 0x8D5);
                            expected = c.fault ? undefined : BigInt(c.result);
                        }
                        else if(form.operands === "to_gpr")
                        {
                            actual = BigInt(view.getUint32(n * 32, true));
                            expected = c.fault ? 0x5A5A5A5An : c.result & 0xFFFFFFFFn;
                        }
                        else
                        {
                            actual = view.getBigUint64(n * 32, true) | view.getBigUint64(n * 32 + 8, true) << 64n;
                            expected = c.fault ? BEFORE : c.result;
                        }
                        if(expected !== undefined) assert.equal(actual.toString(16), expected.toString(16), label + ": result");
                    });
                }
                total += list.length;
            }
        }
        console.log(`PASS: ${xmm_exceptions ? "all forms, unmasked exceptions as #XM" : "unmasked exceptions as #UD without CR4.OSXMMEXCPT"}`);
    }
    console.log(`PASS: ${total} exact AVX floating-point cases (${VEX_FORMS.length} VEX.128 and VEX.LIG forms, ${VEX256_FORMS.length} VEX.256 ones, register and memory sources, ${MXCSRS.length} MXCSR settings) match the model in the interpreter and the page tier`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                                                                                                    source/v64/tests/rust/avx_model.mjs                                                                 0000644 0000000 0000000 00000114120 00000000000 014513  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The AVX forms (VEX.128, VEX.LIG and VEX.256) of tests/rust/avx.mjs and
// tests/x64/avx.mjs and their semantics, written from the SDM's operation
// sections independently of src/rust/cpu/avx.rs. Registers and memory
// operands are BigInts, lane 0 in the low bits. The forms that have legacy
// SSE counterparts use those forms' models (packed_model.mjs,
// shuffle_model.mjs, ssse3_model.mjs, sse4_model.mjs) with VEX's operands.
import assert from "node:assert/strict";
import { packed, packedImmediate as packed_immediate } from "./packed_model.mjs";
import { shuffle } from "./shuffle_model.mjs";
import { model as ssse3 } from "./ssse3_model.mjs";
import { compare_strings, extract, insert, insertps, ptest, sse4_38, sse4_3a } from "./sse4_model.mjs";
import { FORMS as SSE_FP, expect } from "./sse_fp_cases.mjs";
import { Fp } from "./sse_fp_model.mjs";

export const big = b => b.reduceRight((v, x) => v << 8n | BigInt(x), 0n);
export const le = (v, n = 16) => Uint8Array.from({ length: n }, (_, i) => Number(v >> BigInt(8 * i) & 255n));
export const mask = bits => (1n << BigInt(bits)) - 1n;
export const LOW = mask(64);
export const lanes = (v, bits, width = 128) => Array.from({ length: width / bits }, (_, i) => v >> BigInt(i * bits) & mask(bits));
// AVX2: an element (`size` bytes) in each lane of `width` bits; the variable
// shifts (VPSRLVD/Q 45, VPSRAVD 46, VPSLLVD/Q 47) of `bits`-wide elements
const splat = (v, size, width) => join(Array(width / (8 * size)).fill(v & mask(8 * size)), 8 * size);
const variable_shift = (op, bits, a, b, width = 128) => join(lanes(a, bits, width).map((x, n) => {
    const count = lanes(b, bits, width)[n], wide = count >= BigInt(bits);
    if(op === 0x46) return BigInt.asUintN(bits, BigInt.asIntN(bits, x) >> (wide ? BigInt(bits - 1) : count));
    return wide ? 0n : op === 0x45 ? x >> count : x << count & mask(bits);
}), bits);
export const join = (values, bits) => values.reduceRight((v, x) => v << BigInt(bits) | x, 0n);

const unpack = (bits, high) => (a, b) => {
    const [x, y] = [lanes(a, bits), lanes(b, bits)];
    const start = high ? x.length / 2 : 0;
    return join(x.slice(start, start + x.length / 2).flatMap((v, i) => [v, y[start + i]]), bits);
};
const signs = (bits, width = 128) => v => join(lanes(v, bits, width).map(l => l >> BigInt(bits - 1)), 1);
// VEX.256: a 256-bit value's halves, and f (of a VEX.128 form) on each
// (operands BigInts, then imm8, a Number: `high` the high half's imm8)
const low128 = v => v & mask(128), high128 = v => v >> 128n;
const halves = (f, high = imm8 => imm8) => (...operands) => {
    const imm8 = typeof operands.at(-1) === "number" ? [operands.pop()] : [];
    return join([f(...operands.map(low128), ...imm8), f(...operands.map(high128), ...imm8.map(high))], 128);
};
// the other models' operands: 32-bit words, bytes
const words = v => Array.from({ length: 4 }, (_, i) => Number(v >> BigInt(32 * i) & 0xFFFFFFFFn));
const from_words = w => w.reduceRight((v, x) => v << 32n | BigInt(x >>> 0), 0n);
const ZERO = new Uint8Array(16);
// the packed integer operations of 66 0F
const PACKED = {
    0x60: "vpunpcklbw", 0x61: "vpunpcklwd", 0x62: "vpunpckldq", 0x63: "vpacksswb", 0x64: "vpcmpgtb", 0x65: "vpcmpgtw",
    0x66: "vpcmpgtd", 0x67: "vpackuswb", 0x68: "vpunpckhbw", 0x69: "vpunpckhwd", 0x6A: "vpunpckhdq", 0x6B: "vpackssdw",
    0x6C: "vpunpcklqdq", 0x6D: "vpunpckhqdq", 0x74: "vpcmpeqb", 0x75: "vpcmpeqw", 0x76: "vpcmpeqd", 0xD1: "vpsrlw",
    0xD2: "vpsrld", 0xD3: "vpsrlq", 0xD4: "vpaddq", 0xD5: "vpmullw", 0xD8: "vpsubusb", 0xD9: "vpsubusw", 0xDA: "vpminub",
    0xDC: "vpaddusb", 0xDD: "vpaddusw", 0xDE: "vpmaxub", 0xE0: "vpavgb", 0xE1: "vpsraw", 0xE2: "vpsrad", 0xE3: "vpavgw",
    0xE4: "vpmulhuw", 0xE5: "vpmulhw", 0xE8: "vpsubsb", 0xE9: "vpsubsw", 0xEA: "vpminsw", 0xEC: "vpaddsb", 0xED: "vpaddsw",
    0xEE: "vpmaxsw", 0xF1: "vpsllw", 0xF2: "vpslld", 0xF3: "vpsllq", 0xF4: "vpmuludq", 0xF5: "vpmaddwd", 0xF6: "vpsadbw",
    0xF8: "vpsubb", 0xF9: "vpsubw", 0xFA: "vpsubd", 0xFB: "vpsubq", 0xFC: "vpaddb", 0xFD: "vpaddw", 0xFE: "vpaddd",
};
const SSSE3 = { 0x00: "vpshufb", 0x01: "vphaddw", 0x02: "vphaddd", 0x03: "vphaddsw", 0x04: "vpmaddubsw", 0x05: "vphsubw",
    0x06: "vphsubd", 0x07: "vphsubsw", 0x08: "vpsignb", 0x09: "vpsignw", 0x0A: "vpsignd", 0x0B: "vpmulhrsw" };
const SSE4 = { 0x28: "vpmuldq", 0x29: "vpcmpeqq", 0x2B: "vpackusdw", 0x37: "vpcmpgtq", 0x38: "vpminsb", 0x39: "vpminsd",
    0x3A: "vpminuw", 0x3B: "vpminud", 0x3C: "vpmaxsb", 0x3D: "vpmaxsd", 0x3E: "vpmaxuw", 0x3F: "vpmaxud", 0x40: "vpmulld" };
const EXTEND = ["bw", "bd", "bq", "wd", "wq", "dq"];
// The gathers (AVX2, P8): opcode, VEX.W, name, element and index sizes
const GATHERS = [[0x90, 0, "vpgatherdd", 4, 4], [0x90, 1, "vpgatherdq", 8, 4], [0x91, 0, "vpgatherqd", 4, 8],
    [0x91, 1, "vpgatherqq", 8, 8], [0x92, 0, "vgatherdps", 4, 4], [0x92, 1, "vgatherdpd", 8, 4], [0x93, 0, "vgatherqps", 4, 8],
    [0x93, 1, "vgatherqpd", 8, 8]];
// VPBROADCASTB/W/D/Q (AVX2): opcode, element size
const BROADCASTS = [[0x78, 1, "vpbroadcastb"], [0x79, 2, "vpbroadcastw"], [0x58, 4, "vpbroadcastd"], [0x59, 8, "vpbroadcastq"]];

/**
 * The forms: name, map (1: 0F, 2: 0F38, 3: 0F3A; 1 if absent), pp (0, 1:
 * 66, 2: F3, 3: F2), opcode, `group` (ModRM.reg, an opcode extension), and
 * what the instruction does (`kind`, with `f`). `bytes`: the memory
 * operand's size; `aligned`: #GP(0) unless 16-byte aligned; `memory` or
 * `register`: only that form of the r/m operand. `w`: the VEX.W the form
 * requires (WIG, or W0 and W1 ignored outside 64-bit mode, if absent;
 * `wig32`: required in 64-bit mode only); `lig`: VEX.L ignored. Kinds, with d the ModRM.reg register, v VEX.vvvv's
 * and m the r/m operand (a register or memory):
 *   load       d = f(m)
 *   store      m = d (a register destination is a VEX.128 one)
 *   binary     d = f(v, m)
 *   scalar     VMOVSS/VMOVSD 10: d = m from memory, zero-extended; between registers v's upper lanes, m's low one
 *   scalar_st  VMOVSS/VMOVSD 11: m = d to memory; between registers m = v's upper lanes, d's low one
 *   low, high  12/16: one quadword of d from m (a register's high/low one, or m64), the other from v
 *   store64    13/17: m64 = d's low/high quadword
 *   to_gpr     the r/m register d, the general-purpose register the ModRM.reg (f of the XMM register)
 *   gpr_load   VMOVD/VMOVQ xmm, r/m: d = m zero-extended
 *   gpr_store  VMOVD/VMOVQ r/m, xmm: m = d's low dword or quadword
 *   zero_upper VZEROUPPER
 *   ldmxcsr, stmxcsr, maskmov (VMASKMOVDQU: [rDI] = d's bytes the r/m register selects)
 *   load_imm, binary_imm   load and binary with imm8 (f's last argument)
 *   shift_imm  v = f(m register, imm8): VEX.vvvv is the destination
 *   ptest      the flags of d and m
 *   extract    m (a general-purpose register, or memory) = d's element imm8 of `size` bytes
 *   insert     d = v with element imm8 of `size` bytes from m (a general-purpose register's low bytes, or memory)
 *   insertps   d = v with m's dword imm8[7:6] (or the m32) in dword imm8[5:4], dwords imm8[3:0] zeroed
 *   blendv     d = v's or m's bytes, as the sign of the register imm8[7:4]'s bytes selects
 *   pcmpstr    PCMPxSTRx of d and m: ECX (the index) or XMM0 (the mask), and the flags
 *   vtest      ZF and CF of the sign bits of d's and m's lanes of `lane` bytes
 *   maskload   d = m's lanes the sign bits of v's select, the others zero
 *   maskstore  m's lanes the sign bits of v's select = d's
 *   fp         the floating-point form `legacy` of tests/rust/sse_fp_cases.mjs (its
 *              model, MXCSR's flags after) with `operands`: "two" (d = f(m)),
 *              "three" (d = f(v, m)), "comi" (the flags of d and m), "to_gpr" (the
 *              register d = f(m)) or "from_gpr" (d = v with lane 0 from the register
 *              or memory m); `scalar`, `double` as the legacy form's
 */
const FORMS_128 = [
    // full-width loads and stores
    { name: "vmovups", pp: 0, op: 0x10, kind: "load" }, { name: "vmovupd", pp: 1, op: 0x10, kind: "load" },
    { name: "vmovaps", pp: 0, op: 0x28, kind: "load", aligned: true }, { name: "vmovapd", pp: 1, op: 0x28, kind: "load", aligned: true },
    { name: "vmovdqa", pp: 1, op: 0x6F, kind: "load", aligned: true }, { name: "vmovdqu", pp: 2, op: 0x6F, kind: "load" },
    { name: "vlddqu", pp: 3, op: 0xF0, kind: "load", memory: true },
    { name: "vmovntdqa", map: 2, pp: 1, op: 0x2A, kind: "load", aligned: true, memory: true },
    { name: "vmovups", pp: 0, op: 0x11, kind: "store" }, { name: "vmovupd", pp: 1, op: 0x11, kind: "store" },
    { name: "vmovaps", pp: 0, op: 0x29, kind: "store", aligned: true }, { name: "vmovapd", pp: 1, op: 0x29, kind: "store", aligned: true },
    { name: "vmovdqa", pp: 1, op: 0x7F, kind: "store", aligned: true }, { name: "vmovdqu", pp: 2, op: 0x7F, kind: "store" },
    { name: "vmovntps", pp: 0, op: 0x2B, kind: "store", aligned: true, memory: true },
    { name: "vmovntpd", pp: 1, op: 0x2B, kind: "store", aligned: true, memory: true },
    { name: "vmovntdq", pp: 1, op: 0xE7, kind: "store", aligned: true, memory: true },
    // scalar moves (VEX.LIG)
    { name: "vmovss", pp: 2, op: 0x10, kind: "scalar", bytes: 4, lig: true }, { name: "vmovsd", pp: 3, op: 0x10, kind: "scalar", bytes: 8, lig: true },
    { name: "vmovss", pp: 2, op: 0x11, kind: "scalar_st", bytes: 4, lig: true }, { name: "vmovsd", pp: 3, op: 0x11, kind: "scalar_st", bytes: 8, lig: true },
    // quadword moves
    { name: "vmovhlps/vmovlps", pp: 0, op: 0x12, kind: "low" }, { name: "vmovlpd", pp: 1, op: 0x12, kind: "low", memory: true },
    { name: "vmovlhps/vmovhps", pp: 0, op: 0x16, kind: "high" }, { name: "vmovhpd", pp: 1, op: 0x16, kind: "high", memory: true },
    { name: "vmovlps", pp: 0, op: 0x13, kind: "store64", memory: true }, { name: "vmovlpd", pp: 1, op: 0x13, kind: "store64", memory: true },
    { name: "vmovhps", pp: 0, op: 0x17, kind: "store64", memory: true }, { name: "vmovhpd", pp: 1, op: 0x17, kind: "store64", memory: true },
    // duplicates
    { name: "vmovsldup", pp: 2, op: 0x12, kind: "load", f: v => { const l = lanes(v, 32); return join([l[0], l[0], l[2], l[2]], 32); } },
    { name: "vmovshdup", pp: 2, op: 0x16, kind: "load", f: v => { const l = lanes(v, 32); return join([l[1], l[1], l[3], l[3]], 32); } },
    { name: "vmovddup", pp: 3, op: 0x12, kind: "load", bytes: 8, f: v => join([v & LOW, v & LOW], 64) },
    // unpacks and logic
    { name: "vunpcklps", pp: 0, op: 0x14, kind: "binary", f: unpack(32, false) }, { name: "vunpcklpd", pp: 1, op: 0x14, kind: "binary", f: unpack(64, false) },
    { name: "vunpckhps", pp: 0, op: 0x15, kind: "binary", f: unpack(32, true) }, { name: "vunpckhpd", pp: 1, op: 0x15, kind: "binary", f: unpack(64, true) },
    ...[0, 1].flatMap(pp => [
        { name: pp ? "vandpd" : "vandps", pp, op: 0x54, kind: "binary", f: (a, b) => a & b },
        { name: pp ? "vandnpd" : "vandnps", pp, op: 0x55, kind: "binary", f: (a, b) => ~a & b & mask(128) },
        { name: pp ? "vorpd" : "vorps", pp, op: 0x56, kind: "binary", f: (a, b) => a | b },
        { name: pp ? "vxorpd" : "vxorps", pp, op: 0x57, kind: "binary", f: (a, b) => a ^ b },
    ]),
    { name: "vpand", pp: 1, op: 0xDB, kind: "binary", f: (a, b) => a & b }, { name: "vpandn", pp: 1, op: 0xDF, kind: "binary", f: (a, b) => ~a & b & mask(128) },
    { name: "vpor", pp: 1, op: 0xEB, kind: "binary", f: (a, b) => a | b }, { name: "vpxor", pp: 1, op: 0xEF, kind: "binary", f: (a, b) => a ^ b },
    // to general-purpose registers
    { name: "vmovmskps", pp: 0, op: 0x50, kind: "to_gpr", register: true, f: signs(32) },
    { name: "vmovmskpd", pp: 1, op: 0x50, kind: "to_gpr", register: true, f: signs(64) },
    { name: "vpmovmskb", pp: 1, op: 0xD7, kind: "to_gpr", register: true, f: signs(8) },
    // VMOVD and VMOVQ (W1: 64-bit general-purpose operands, 64-bit mode only)
    { name: "vmovd", pp: 1, op: 0x6E, kind: "gpr_load", w: 0, wig32: true }, { name: "vmovq", pp: 1, op: 0x6E, kind: "gpr_load", w: 1, long: true },
    { name: "vmovd", pp: 1, op: 0x7E, kind: "gpr_store", w: 0, wig32: true }, { name: "vmovq", pp: 1, op: 0x7E, kind: "gpr_store", w: 1, long: true },
    { name: "vmovq", pp: 2, op: 0x7E, kind: "load", bytes: 8, f: v => v & LOW },
    { name: "vmovq", pp: 1, op: 0xD6, kind: "store", bytes: 8, f: v => v & LOW },
    // state
    { name: "vzeroupper", pp: 0, op: 0x77, kind: "zero_upper" },
    { name: "vldmxcsr", pp: 0, op: 0xAE, group: 2, kind: "ldmxcsr", memory: true, bytes: 4 },
    { name: "vstmxcsr", pp: 0, op: 0xAE, group: 3, kind: "stmxcsr", memory: true, bytes: 4 },
    { name: "vmaskmovdqu", pp: 1, op: 0xF7, kind: "maskmov", register: true },

    // P5 part 2: the integer forms
    ...Object.entries(PACKED).map(([op, name]) => ({ name, pp: 1, op: +op, kind: "binary",
        f: (a, b) => from_words(packed(0x660F00 | +op, words(a), words(b))) })),
    ...[[0x71, 2, "vpsrlw"], [0x71, 4, "vpsraw"], [0x71, 6, "vpsllw"], [0x72, 2, "vpsrld"], [0x72, 4, "vpsrad"], [0x72, 6, "vpslld"],
        [0x73, 2, "vpsrlq"], [0x73, 3, "vpsrldq"], [0x73, 6, "vpsllq"], [0x73, 7, "vpslldq"]].map(([op, group, name]) =>
        ({ name, pp: 1, op, group, kind: "shift_imm", register: true, f: (v, imm8) => from_words(packed_immediate(0x660F00 | op, group, imm8, words(v))) })),
    ...[[1, 0x660F70, "vpshufd"], [2, 0xF30F70, "vpshufhw"], [3, 0xF20F70, "vpshuflw"]].map(([pp, key, name]) =>
        ({ name, pp, op: 0x70, kind: "load_imm", f: (v, imm8) => from_words(shuffle(key, imm8, [0, 0, 0, 0], words(v))) })),
    ...[[0, 0x0FC6, "vshufps"], [1, 0x660FC6, "vshufpd"]].map(([pp, key, name]) =>
        ({ name, pp, op: 0xC6, kind: "binary_imm", f: (a, b, imm8) => from_words(shuffle(key, imm8, words(a), words(b))) })),
    { name: "vpinsrw", pp: 1, op: 0xC4, kind: "insert", size: 2, w: 0, wig32: true },
    { name: "vpinsrw", pp: 1, op: 0xC4, kind: "insert", size: 2, w: 1, long: true },
    { name: "vpextrw", pp: 1, op: 0xC5, kind: "to_gpr", register: true, w: 0, wig32: true, imm: true },
    { name: "vpextrw", pp: 1, op: 0xC5, kind: "to_gpr", register: true, w: 1, long: true, imm: true },
    ...Object.entries(SSSE3).map(([op, name]) => ({ name, map: 2, pp: 1, op: +op, kind: "binary", f: (a, b) => big(ssse3(+op, le(a), le(b))) })),
    ...[[0x1C, "vpabsb"], [0x1D, "vpabsw"], [0x1E, "vpabsd"]].map(([op, name]) =>
        ({ name, map: 2, pp: 1, op, kind: "load", f: v => big(ssse3(op, ZERO, le(v))) })),
    { name: "vpalignr", map: 3, pp: 1, op: 0x0F, kind: "binary_imm", f: (a, b, imm8) => big(ssse3(0x0F, le(a), le(b), imm8)) },
    { name: "vptest", map: 2, pp: 1, op: 0x17, kind: "ptest" },
    ...EXTEND.flatMap((suffix, i) => [[0x20 + i, "vpmovsx" + suffix], [0x30 + i, "vpmovzx" + suffix]]).map(([op, name]) =>
        ({ name, map: 2, pp: 1, op, kind: "load", bytes: [8, 4, 2, 8, 4, 8][op & 7], f: v => big(sse4_38(op, ZERO, le(v), ZERO)) })),
    ...Object.entries(SSE4).map(([op, name]) => ({ name, map: 2, pp: 1, op: +op, kind: "binary", f: (a, b) => big(sse4_38(+op, le(a), le(b), ZERO)) })),
    { name: "vphminposuw", map: 2, pp: 1, op: 0x41, kind: "load", f: v => big(sse4_38(0x41, ZERO, le(v), ZERO)) },
    ...[[0x0C, "vblendps"], [0x0D, "vblendpd"], [0x0E, "vpblendw"], [0x42, "vmpsadbw"]].map(([op, name]) =>
        ({ name, map: 3, pp: 1, op, kind: "binary_imm", f: (a, b, imm8) => big(sse4_3a(op, le(a), le(b), imm8)) })),
    // (W1: a 64-bit general-purpose register, and VPEXTRQ/VPINSRQ, in 64-bit mode)
    ...[[0x14, 1, "vpextrb"], [0x15, 2, "vpextrw"], [0x16, 4, "vpextrd"], [0x17, 4, "vextractps"]].flatMap(([op, size, name]) => [
        { name, map: 3, pp: 1, op, kind: "extract", size, w: 0, wig32: true },
        { name: op === 0x16 ? "vpextrq" : name, map: 3, pp: 1, op, kind: "extract", size: op === 0x16 ? 8 : size, w: 1, long: true },
    ]),
    ...[[0x20, 1, "vpinsrb"], [0x22, 4, "vpinsrd"]].flatMap(([op, size, name]) => [
        { name, map: 3, pp: 1, op, kind: "insert", size, w: 0, wig32: true },
        { name: op === 0x22 ? "vpinsrq" : name, map: 3, pp: 1, op, kind: "insert", size: op === 0x22 ? 8 : size, w: 1, long: true },
    ]),
    { name: "vinsertps", map: 3, pp: 1, op: 0x21, kind: "insertps" },
    { name: "vpblendvb", map: 3, pp: 1, op: 0x4C, kind: "blendv", w: 0 },
    ...[[0x60, "vpcmpestrm"], [0x61, "vpcmpestri"]].flatMap(([op, name]) => [
        { name, map: 3, pp: 1, op, kind: "pcmpstr", w: 0, wig32: true },
        { name: name + "64", map: 3, pp: 1, op, kind: "pcmpstr", w: 1, long: true },
    ]),
    { name: "vpcmpistrm", map: 3, pp: 1, op: 0x62, kind: "pcmpstr" }, { name: "vpcmpistri", map: 3, pp: 1, op: 0x63, kind: "pcmpstr" },

    // P5 part 3: the floating-point forms
    ...SSE_FP.filter(form => !["from_mmx", "to_mmx"].includes(form.kind)).flatMap(form => {
        const pp = { "": 0, 102: 1, 243: 2, 242: 3 }[form.prefix.join()];
        const scalar = !!form.scalar || ["comi", "to_gpr", "from_gpr"].includes(form.kind);
        const two = ["from_dwords", "to_dwords"].includes(form.kind) ||
            !form.scalar && (form.op === "sqrt" || ["reciprocal", "widen", "narrow", "round"].includes(form.kind));
        const operands = ["comi", "to_gpr", "from_gpr"].includes(form.kind) ? form.kind : two ? "two" : "three";
        const double = form.double ?? form.kind === "narrow";
        // (the memory operand: a scalar's lane, an integer's dword, CVTPS2PD's and CVTDQ2PD's quadword)
        const bytes = form.kind === "from_gpr" ? 4 : scalar ? (double ? 8 : 4) :
            form.kind === "widen" || form.kind === "from_dwords" && double ? 8 : 16;
        // (the scalar forms are VEX.LIG)
        const vex = { name: "v" + form.name, map: form.map === 0x3A ? 3 : 1, pp, op: form.code, kind: "fp", legacy: form, operands, bytes, lig: scalar };
        // (the general-purpose forms: W0 32-bit integers, W1 64-bit ones in 64-bit mode)
        if(operands === "to_gpr" || operands === "from_gpr")
            return [{ ...vex, w: 0, wig32: true }, { ...vex, w: 1, long: true, bytes: operands === "from_gpr" ? 8 : bytes }];
        return [vex];
    }),
    { name: "vblendvps", map: 3, pp: 1, op: 0x4A, kind: "blendv", legacy: 0x14, w: 0 },
    { name: "vblendvpd", map: 3, pp: 1, op: 0x4B, kind: "blendv", legacy: 0x15, w: 0 },

    // P5 part 4: AVX's own 128-bit forms
    { name: "vbroadcastss", map: 2, pp: 1, op: 0x18, kind: "load", memory: true, bytes: 4, w: 0, f: v => join([v, v, v, v], 32) },
    { name: "vpermilps", map: 2, pp: 1, op: 0x0C, kind: "binary", w: 0,
        f: (a, b) => join(lanes(b, 32).map(x => lanes(a, 32)[Number(x & 3n)]), 32) },
    { name: "vpermilpd", map: 2, pp: 1, op: 0x0D, kind: "binary", w: 0,
        f: (a, b) => join(lanes(b, 64).map(x => lanes(a, 64)[Number(x >> 1n & 1n)]), 64) },
    { name: "vpermilps", map: 3, pp: 1, op: 0x04, kind: "load_imm", w: 0,
        f: (v, imm8) => join([0, 1, 2, 3].map(n => lanes(v, 32)[imm8 >> 2 * n & 3]), 32) },
    { name: "vpermilpd", map: 3, pp: 1, op: 0x05, kind: "load_imm", w: 0,
        f: (v, imm8) => join([0, 1].map(n => lanes(v, 64)[imm8 >> n & 1]), 64) },
    { name: "vtestps", map: 2, pp: 1, op: 0x0E, kind: "vtest", lane: 4, w: 0 },
    { name: "vtestpd", map: 2, pp: 1, op: 0x0F, kind: "vtest", lane: 8, w: 0 },
    { name: "vmaskmovps", map: 2, pp: 1, op: 0x2C, kind: "maskload", lane: 4, memory: true, w: 0 },
    { name: "vmaskmovpd", map: 2, pp: 1, op: 0x2D, kind: "maskload", lane: 8, memory: true, w: 0 },
    { name: "vmaskmovps", map: 2, pp: 1, op: 0x2E, kind: "maskstore", lane: 4, memory: true, w: 0 },
    { name: "vmaskmovpd", map: 2, pp: 1, op: 0x2F, kind: "maskstore", lane: 8, memory: true, w: 0 },

    // P7 part 2: AVX2's own VEX.128 forms (`isa`)
    ...BROADCASTS.map(([op, size, name]) => ({ name, map: 2, pp: 1, op, kind: "load", bytes: size, w: 0, isa: "AVX2", f: v => splat(v, size, 128) })),
    { name: "vbroadcastss", map: 2, pp: 1, op: 0x18, kind: "load", register: true, w: 0, isa: "AVX2", f: v => splat(v, 4, 128) },
    { name: "vpblendd", map: 3, pp: 1, op: 0x02, kind: "binary_imm", w: 0, isa: "AVX2",
        f: (a, b, imm8) => join(lanes(a, 32).map((x, n) => imm8 >> n & 1 ? lanes(b, 32)[n] : x), 32) },
    ...[[0x45, 0, "vpsrlvd"], [0x45, 1, "vpsrlvq"], [0x46, 0, "vpsravd"], [0x47, 0, "vpsllvd"], [0x47, 1, "vpsllvq"]].map(([op, w, name]) =>
        ({ name, map: 2, pp: 1, op, kind: "binary", w, isa: "AVX2", f: (a, b) => variable_shift(op, w ? 64 : 32, a, b) })),
    ...[[0x8C, "maskload"], [0x8E, "maskstore"]].flatMap(([op, kind]) => [0, 1].map(w =>
        ({ name: w ? "vpmaskmovq" : "vpmaskmovd", map: 2, pp: 1, op, kind, lane: w ? 8 : 4, memory: true, w, isa: "AVX2" }))),
    // P8: the gathers (`data`, `index`: the element and index sizes)
    ...GATHERS.map(([op, w, name, data, index]) => ({ name, map: 2, pp: 1, op, w, kind: "gather", data, index, memory: true, isa: "AVX2" })),
];

// P6 part 1: the VEX.256 forms (`l`: 1) of data movement, logic, shuffles,
// the cross-lane forms, tests and masks. The lane-wise ones are their VEX.128
// forms on each half (`halves`), with 32-byte memory operands (the aligned
// ones aligned to 32 bytes). Kinds of their own:
//   insert128   d = v with its half imm8[0] from m (xmm or m128)
//   extract128  m (an XMM register, bits 255:128 zeroed, or m128) = d's half imm8[0]
//   zero_all    VZEROALL
const by_name = (name, op) => FORMS_128.find(f => f.name === name && (op === undefined || f.op === op));
// (AVX2's packed integer forms that work on each half: their VEX.128 forms,
// AVX's; the shifts by xmm/m128)
const COUNT_SHIFTS = [0xD1, 0xD2, 0xD3, 0xE1, 0xE2, 0xF1, 0xF2, 0xF3];
const avx2_halves = f => !f.long && f.pp === 1 && ((f.map ?? 1) === 1 && (f.kind === "binary" && !f.map &&
    (f.op in PACKED || [0xDB, 0xDF, 0xEB, 0xEF].includes(f.op)) || f.kind === "shift_imm" || f.kind === "to_gpr" && f.op === 0xD7) ||
    f.map === 2 && (f.kind === "binary" && (f.op <= 0x0B || [0x28, 0x29, 0x2B].includes(f.op) || f.op >= 0x37 && f.op <= 0x40) ||
        f.kind === "load" && f.op >= 0x1C && f.op <= 0x1E || f.name === "vmovntdqa") ||
    f.map === 3 && [0x0E, 0x0F, 0x42, 0x4C].includes(f.op)) || f.op === 0x70 && !f.map;
const wide = (f, extra = {}) => ({ ...f, l: 1, bytes: 32, ...extra });
// VPERM2F128 (AVX), VPERM2I128 (AVX2): each half one of the sources' halves
// (imm8[1:0], imm8[5:4]) or zero (imm8[3], imm8[7])
const vperm2 = (op, name, extra = {}) => ({ name, map: 3, pp: 1, op, kind: "binary_imm", bytes: 32, w: 0, l: 1, ...extra,
    f: (a, b, imm8) => join([imm8, imm8 >> 4].map(c => c & 8 ? 0n : [low128(a), high128(a), low128(b), high128(b)][c & 3]), 128) });
const FORMS_256 = [
    // full-width loads and stores
    ...FORMS_128.filter(f => ["load", "store"].includes(f.kind) && !f.map && f.bytes === undefined && !f.f &&
        [0x10, 0x11, 0x28, 0x29, 0x2B, 0x6F, 0x7F, 0xE7, 0xF0].includes(f.op)).map(f => wide(f)),
    // duplicates, in each half (VMOVDDUP from 32 bytes too)
    ...["vmovsldup", "vmovshdup", "vmovddup"].map(name => wide(by_name(name), { f: halves(by_name(name).f) })),
    // unpacks and logic of PS and PD, in each half
    ...FORMS_128.filter(f => f.kind === "binary" && !f.map && f.pp <= 1 && [0x14, 0x15, 0x54, 0x55, 0x56, 0x57].includes(f.op))
        .map(f => wide(f, { f: halves(f.f) })),
    // VSHUFPS (imm8 for each half), VSHUFPD (imm8[3:2] for the high one)
    ...FORMS_128.filter(f => f.op === 0xC6).map(f => wide(f, { f: halves(f.f, f.pp ? imm8 => imm8 >> 2 : undefined) })),
    // VBLENDPS (imm8[7:4] for the high half), VBLENDPD (imm8[3:2])
    ...FORMS_128.filter(f => f.map === 3 && (f.op === 0x0C || f.op === 0x0D))
        .map(f => wide(f, { f: halves(f.f, imm8 => imm8 >> (f.op === 0x0C ? 4 : 2)) })),
    // VBLENDVPS, VBLENDVPD: the mask register's halves
    ...FORMS_128.filter(f => f.kind === "blendv" && f.legacy).map(f => wide(f)),
    // VPERMILPS, VPERMILPD by a vector (in each half) and by imm8 (VPERMILPD: imm8[3:2] for the high half)
    ...FORMS_128.filter(f => f.name === "vpermilps" || f.name === "vpermilpd")
        .map(f => wide(f, { f: halves(f.f, f.op === 0x05 ? imm8 => imm8 >> 2 : undefined) })),
    // VBROADCASTSS ymm, m32; VBROADCASTSD ymm, m64; VBROADCASTF128 ymm, m128
    { name: "vbroadcastss", map: 2, pp: 1, op: 0x18, kind: "load", memory: true, bytes: 4, w: 0, l: 1, f: v => join(Array(8).fill(v), 32) },
    { name: "vbroadcastsd", map: 2, pp: 1, op: 0x19, kind: "load", memory: true, bytes: 8, w: 0, l: 1, f: v => join(Array(4).fill(v), 64) },
    { name: "vbroadcastf128", map: 2, pp: 1, op: 0x1A, kind: "load", memory: true, bytes: 16, w: 0, l: 1, f: v => join([v, v], 128) },
    { name: "vinsertf128", map: 3, pp: 1, op: 0x18, kind: "insert128", bytes: 16, w: 0, l: 1 },
    { name: "vextractf128", map: 3, pp: 1, op: 0x19, kind: "extract128", bytes: 16, w: 0, l: 1 },
    // VPERM2F128: each half one of the sources' halves (imm8[1:0], imm8[5:4]) or zero (imm8[3], imm8[7])
    vperm2(0x06, "vperm2f128"),
    { name: "vzeroall", pp: 0, op: 0x77, kind: "zero_all", l: 1 },
    // the tests and sign masks over all 256 bits
    wide(by_name("vptest")), wide(by_name("vtestps")), wide(by_name("vtestpd")),
    { ...by_name("vmovmskps"), l: 1, f: signs(32, 256) }, { ...by_name("vmovmskpd"), l: 1, f: signs(64, 256) },
    // VMASKMOVPS, VMASKMOVPD: 8 and 4 lanes
    ...FORMS_128.filter(f => f.kind === "maskload" || f.kind === "maskstore").map(f => ({ ...f, l: 1 })),
    // P6 part 2: the packed floating-point forms but VDPPD, over all lanes
    // with one exception context (sse_fp_cases.mjs's expect at width 256);
    // VCVTPS2PD and VCVTDQ2PD from xmm/m128
    ...FORMS_128.filter(f => f.kind === "fp" && !f.lig && f.name !== "vdppd").map(f => ({ ...f, l: 1,
        bytes: f.legacy.kind === "widen" || f.legacy.kind === "from_dwords" && f.legacy.double ? 16 : 32 })),
    // P7 part 1 (AVX2, `isa`): the packed integer forms on each half. The
    // shifts by xmm/m128 take one count (the low quadword of the 128-bit
    // operand) for both halves; VMPSADBW takes imm8[5:3] for the high half;
    // VPMOVMSKB the sign bits of all 32 bytes; VMOVNTDQA is 32-byte aligned
    ...FORMS_128.filter(avx2_halves).map(f => {
        const isa = { isa: "AVX2" };
        if((f.map ?? 1) === 1 && COUNT_SHIFTS.includes(f.op))
            return wide(f, { ...isa, bytes: 16, f: (a, b) => join([f.f(low128(a), low128(b)), f.f(high128(a), low128(b))], 128) });
        if(f.kind === "to_gpr") return { ...f, ...isa, l: 1, f: signs(8, 256) };
        if(f.kind === "blendv" || f.name === "vmovntdqa") return wide(f, isa);
        return wide(f, { ...isa, f: halves(f.f, f.name === "vmpsadbw" ? imm8 => imm8 >> 3 : undefined) });
    }),
    // P7 part 2 (AVX2): broadcasts (an element from xmm/m, VBROADCASTI128
    // from m128), the extensions from xmm/m128 (m64, m32) over 256 bits,
    // VPERMD/PS (indices in VEX.vvvv), VPERMQ/PD (imm8), VPERM2I128,
    // VINSERTI128, VEXTRACTI128, VPBLENDD (imm8[7:4] for the high half),
    // the variable shifts and VPMASKMOVD/Q
    ...BROADCASTS.map(([op, size, name]) => ({ name, map: 2, pp: 1, op, kind: "load", bytes: size, w: 0, l: 1, isa: "AVX2", f: v => splat(v, size, 256) })),
    { name: "vbroadcastss", map: 2, pp: 1, op: 0x18, kind: "load", register: true, w: 0, l: 1, isa: "AVX2", f: v => splat(v, 4, 256) },
    { name: "vbroadcastsd", map: 2, pp: 1, op: 0x19, kind: "load", register: true, w: 0, l: 1, isa: "AVX2", f: v => splat(v, 8, 256) },
    { name: "vbroadcasti128", map: 2, pp: 1, op: 0x5A, kind: "load", memory: true, bytes: 16, w: 0, l: 1, isa: "AVX2", f: v => join([v, v], 128) },
    ...EXTEND.flatMap((suffix, i) => [[0x20 + i, "vpmovsx" + suffix], [0x30 + i, "vpmovzx" + suffix]]).map(([op, name]) => {
        const half = [8, 4, 2, 8, 4, 8][op & 7], f128 = by_name(name).f;
        return { name, map: 2, pp: 1, op, kind: "load", bytes: 2 * half, w: 0, l: 1, isa: "AVX2",
            f: v => join([f128(v & mask(8 * half)), f128(v >> BigInt(8 * half) & mask(8 * half))], 128) };
    }),
    ...[[0x36, "vpermd"], [0x16, "vpermps"]].map(([op, name]) => ({ name, map: 2, pp: 1, op, kind: "binary", w: 0, l: 1, bytes: 32, isa: "AVX2",
        f: (a, b) => join(lanes(a, 32, 256).map(i => lanes(b, 32, 256)[Number(i & 7n)]), 32) })),
    ...[[0x00, "vpermq"], [0x01, "vpermpd"]].map(([op, name]) => ({ name, map: 3, pp: 1, op, kind: "load_imm", w: 1, l: 1, bytes: 32, isa: "AVX2",
        f: (v, imm8) => join([0, 1, 2, 3].map(n => lanes(v, 64, 256)[imm8 >> 2 * n & 3]), 64) })),
    vperm2(0x46, "vperm2i128", { isa: "AVX2" }),
    { name: "vinserti128", map: 3, pp: 1, op: 0x38, kind: "insert128", bytes: 16, w: 0, l: 1, isa: "AVX2" },
    { name: "vextracti128", map: 3, pp: 1, op: 0x39, kind: "extract128", bytes: 16, w: 0, l: 1, isa: "AVX2" },
    wide(by_name("vpblendd"), { isa: "AVX2", f: halves(by_name("vpblendd").f, imm8 => imm8 >> 4) }),
    ...FORMS_128.filter(f => f.isa === "AVX2" && f.map === 2 && f.op >= 0x45 && f.op <= 0x47)
        .map(f => wide(f, { f: (a, b) => variable_shift(f.op, f.w ? 64 : 32, a, b, 256) })),
    ...FORMS_128.filter(f => f.isa === "AVX2" && (f.kind === "maskload" || f.kind === "maskstore")).map(f => ({ ...f, l: 1 })),
    // P8: the gathers' VEX.256 forms
    ...FORMS_128.filter(f => f.kind === "gather").map(f => ({ ...f, l: 1 })),
];
export const FORMS = [...FORMS_128, ...FORMS_256];

/** The memory operand's size of form `f` */
export const memory_bytes = f => f.bytes ?? f.size ?? (["store64", "low", "high"].includes(f.kind) ? 8 :
    f.kind === "gpr_load" || f.kind === "gpr_store" ? (f.w ? 8 : 4) : f.kind === "insertps" ? 4 :
    ["maskload", "maskstore"].includes(f.kind) && f.l ? 32 : 16);

/**
 * Executes form `f` on `s`: x[r] and h[r], XMM r and bits 255:128 of YMM r
 * (BigInts), mxcsr, flags (OF, SF, ZF, AF, PF, CF, for the forms that set
 * them); s.load(bytes) and s.store(bytes, value) access the memory operand
 * (s.load_at and s.store_at an element at an offset in it),
 * s.masked(value, selected) VMASKMOVDQU's, s.gpr(r) and s.set_gpr(r, value,
 * bits) the general-purpose registers. `o`: d, v (VEX.vvvv), m (the r/m
 * register; undefined for memory), imm8, `long` (64-bit mode).
 */
export function execute(f, s, { d, v, m, imm8, long, index, scale })
{
    const memory = m === undefined;
    // (a VEX.256 form's registers: both halves; its lane-wise memory operand 32 bytes)
    const ymm = f.l === 1, width = ymm ? 256 : 128, full = ymm ? 32 : 16;
    const reg = r => ymm ? s.x[r] | s.h[r] << 128n : s.x[r];
    const source = bytes => memory ? s.load(bytes) : reg(m);
    const write = (r, value) => { s.x[r] = value & mask(128); s.h[r] = ymm ? value >> 128n & mask(128) : 0n; };
    switch(f.kind)
    {
        case "load": write(d, (f.f || (x => x))(source(memory_bytes(f)))); break;
        case "store":
        {
            const value = (f.f || (x => x))(reg(d));
            if(memory) s.store(memory_bytes(f), value);
            else write(m, value);
            break;
        }
        case "binary": write(d, f.f(reg(v), source(f.bytes ?? full))); break;
        case "scalar":
        {
            const low = mask(f.bytes * 8);
            write(d, memory ? s.load(f.bytes) : s.x[v] & ~low | s.x[m] & low);
            break;
        }
        case "scalar_st":
        {
            const low = mask(f.bytes * 8);
            if(memory) s.store(f.bytes, s.x[d]);
            else write(m, s.x[v] & ~low | s.x[d] & low);
            break;
        }
        case "low": write(d, s.x[v] & ~LOW | (memory ? s.load(8) : s.x[m] >> 64n)); break;
        case "high": write(d, s.x[v] & LOW | (memory ? s.load(8) : s.x[m] & LOW) << 64n); break;
        case "store64": s.store(8, f.op === 0x13 ? s.x[d] & LOW : s.x[d] >> 64n); break;
        // (the general-purpose register: ModRM.reg, d here; VPEXTRW: word imm8[2:0])
        case "to_gpr": s.set_gpr(d, f.imm ? extract(le(s.x[m]), 2, imm8) : f.f(reg(m)), long && f.w === 1 ? 64 : 32); break;
        case "gpr_load":
        {
            const bits = long && f.w === 1 ? 64 : 32;
            write(d, memory ? s.load(bits / 8) : s.gpr(m) & mask(bits));
            break;
        }
        case "gpr_store":
        {
            const bits = long && f.w === 1 ? 64 : 32;
            if(memory) s.store(bits / 8, s.x[d] & mask(bits));
            else s.set_gpr(m, s.x[d] & mask(bits), bits);
            break;
        }
        case "zero_upper": s.h.fill(0n, 0, long ? 16 : 8); break;
        case "zero_all": s.x.fill(0n, 0, long ? 16 : 8); s.h.fill(0n, 0, long ? 16 : 8); break;
        case "insert128":
        {
            const value = memory ? s.load(16) : s.x[m], a = reg(v);
            write(d, imm8 & 1 ? low128(a) | value << 128n : value | high128(a) << 128n);
            break;
        }
        case "extract128":
        {
            const value = imm8 & 1 ? high128(reg(d)) : low128(reg(d));
            // (an XMM register: bits 255:128 of its YMM register zeroed)
            if(memory) s.store(16, value);
            else { s.x[m] = value; s.h[m] = 0n; }
            break;
        }
        case "ldmxcsr": s.mxcsr = Number(s.load(4)); break;
        case "stmxcsr": s.store(4, BigInt(s.mxcsr)); break;
        case "maskmov":
        {
            const selected = le(s.x[m]).map(b => b >> 7);
            s.masked(s.x[d], selected);
            break;
        }
        case "load_imm": write(d, f.f(source(full), imm8)); break;
        case "binary_imm": write(d, f.f(reg(v), source(full), imm8)); break;
        case "shift_imm": write(v, f.f(reg(m), imm8)); break;
        case "ptest":
        {
            // (VEX.256: over all 256 bits)
            const a = reg(d), b = source(full);
            const { zf, cf } = ymm ? { zf: (a & b) === 0n, cf: (~a & b & mask(256)) === 0n } : ptest(le(a), le(b));
            s.flags = (zf ? 0x40 : 0) | (cf ? 1 : 0);
            break;
        }
        case "extract":
        {
            const value = extract(le(s.x[d]), f.size, imm8);
            if(memory) s.store(f.size, value);
            else s.set_gpr(m, value, long && f.w === 1 ? 64 : 32);
            break;
        }
        case "insert":
        {
            const value = memory ? s.load(f.size) : s.gpr(m) & mask(8 * f.size);
            write(d, big(insert(le(s.x[v]), f.size, value, imm8)));
            break;
        }
        case "insertps":
        {
            const value = memory ? s.load(4) : s.x[m] >> BigInt(32 * (imm8 >> 6)) & mask(32);
            write(d, big(insertps(le(s.x[v]), value, imm8)));
            break;
        }
        case "blendv":
        {
            const blend = (a, b, selector) => big(sse4_38(f.legacy ?? 0x10, le(a), le(b), le(selector)));
            const selector = reg(imm8 >> 4 & (long ? 15 : 7));
            write(d, ymm ? halves(blend)(reg(v), source(full), selector) : blend(s.x[v], source(16), selector));
            break;
        }
        case "vtest":
        {
            const bits = f.lane * 8;
            const signs = join(lanes(mask(width), bits, width).map(() => 1n << BigInt(bits - 1)), bits);
            const a = reg(d), b = source(full);
            s.flags = ((a & b & signs) === 0n ? 0x40 : 0) | ((~a & b & signs) === 0n ? 1 : 0);
            break;
        }
        // a gather (`index`, the indices' register, and `scale`): the
        // selected elements from the memory operand's address plus each
        // element's sign-extended, scaled index (32-bit addressing outside
        // 64-bit mode wraps), the mask cleared
        case "gather":
        {
            const count = (ymm ? 32 : 16) / Math.max(f.data, f.index), bits = 8 * f.data;
            const selected = lanes(reg(v), bits, 256).slice(0, count).map(x => x >> BigInt(bits - 1) & 1n);
            const values = lanes(reg(d), bits, 256).slice(0, count);
            const indices = lanes(reg(index), 8 * f.index, 256);
            for(let n = 0; n < count; n++)
            {
                if(!selected[n]) continue;
                const offset = BigInt.asIntN(long ? 64 : 32, BigInt.asIntN(8 * f.index, indices[n]) << BigInt(scale));
                values[n] = s.load_at(Number(offset), f.data);
            }
            write(d, join(values, bits));
            write(v, 0n);
            break;
        }
        case "maskload": case "maskstore":
        {
            // (each selected lane on its own: s.load_at, s.store_at)
            const bits = f.lane * 8;
            const selected = lanes(reg(v), bits, width).map(x => x >> BigInt(bits - 1));
            if(f.kind === "maskload") write(d, join(selected.map((on, n) => on ? s.load_at(n * f.lane, f.lane) : 0n), bits));
            else selected.forEach((on, n) => { if(on) s.store_at(n * f.lane, f.lane, lanes(reg(d), bits, width)[n]); });
            break;
        }
        case "fp":
        {
            const form = f.legacy, double = form.double ?? false;
            if(f.operands === "to_gpr" || f.operands === "from_gpr")
            {
                // (32-bit integers, 64-bit with VEX.W1 in 64-bit mode)
                const bits = long && f.w === 1 ? 64 : 32;
                const fp = new Fp(s.mxcsr);
                if(f.operands === "to_gpr")
                {
                    const x = memory ? s.load(f.bytes) : s.x[m] & mask(double ? 64 : 32);
                    s.set_gpr(d, BigInt.asUintN(bits, fp.to_integer(x, double, bits, form.truncate)), bits);
                }
                else
                {
                    const n = BigInt.asIntN(bits, memory ? s.load(bits / 8) : s.gpr(m));
                    const lane = mask(double ? 64 : 32);
                    write(d, s.x[v] & ~lane | fp.from_integer(n, double));
                }
                s.mxcsr = fp.finish().mxcsr;
                break;
            }
            const a = f.operands === "two" ? 0n : f.operands === "comi" ? s.x[d] : reg(v);
            // (VCMP*: the 32 predicates of imm8[4:0]; VEX.256: all lanes)
            const r = expect(form, s.mxcsr, a, source(f.bytes), form.kind === "compare" ? imm8 & 31 : imm8, width);
            assert(!r.fault, `${f.name}: an unmasked exception`);
            s.mxcsr = r.after;
            if(f.operands === "comi") s.flags = Number(r.result);
            else write(d, r.result);
            break;
        }
        case "pcmpstr":
        {
            // (the explicit lengths: EAX and EDX, or RAX and RDX with VEX.W1, signed)
            const bits = long && f.w === 1 ? 64 : 32;
            const length = r => BigInt.asIntN(bits, s.gpr(r));
            const explicit = f.op < 0x62;
            const r = compare_strings(imm8, le(s.x[d]), le(source(16)), explicit ? length(0) : undefined, explicit ? length(2) : undefined);
            if(f.op & 1) s.set_gpr(1, BigInt(r.index), 32);
            else write(0, big(r.mask));
            s.flags = (r.cf ? 1 : 0) | (r.zf ? 0x40 : 0) | (r.sf ? 0x80 : 0) | (r.of ? 0x800 : 0);
            break;
        }
        default: throw new Error(`kind ${f.kind}`);
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/rust/bmi.mjs                                                                       0000644 0000000 0000000 00000072422 00000000000 013314  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // BMI1, BMI2, TZCNT, LZCNT and MOVBE in the 32-bit engines
// (docs/simd-xsave-plan.md 9.2, P10) against tests/rust/bmi_model.mjs:
// every VEX form from registers and memory with edge and random values, the
// destination aliasing the sources, VEX.vvvv and MULX's EDX; the flags the
// SDM defines, v86's values for the undefined ones and, for MULX, PDEP,
// PEXT, RORX and the shifts, flags kept; TZCNT and LZCNT (16 and 32 bits);
// MOVBE loads and stores (16 and 32 bits). Exceptions: #UD for VEX.L1, a
// VEX.vvvv other than 1111b where it is no operand, 66/F2/F3/LOCK before
// VEX, MOVBE from a register; none for CR4.OSXSAVE clear or CR0.TS set (no
// AVX state requirements); #PF without effect, MOVBE's store too. Without
// the features: CPUID reports none, TZCNT and LZCNT are BSF and BSR, the VEX
// forms and MOVBE #UD. Each case runs in the interpreter, then hot under
// the page tier (LZCNT needs the x86-64 profile's machines).
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { ARITHMETIC, VEX_FORMS, execute_vex, ops, v86_flags } from "./bmi_model.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, SOURCE = 0x210000, OUT = 0x230000, FAULT = 0x24F000, SKIP = 0x24F100;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000, ABSENT = 0x2F0000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

const absolute = (r, a) => [0x05 | r << 3, ...u32(a)];
const mov_r32 = (r, v) => [0xB8 | r, ...u32(v)];
const store_r32 = (r, a) => [0x89, 0x05 | r << 3, ...u32(a)];
const PUSHF_STORE = a => [0x9C, 0x58, 0xA3, ...u32(a)];
const CLTS = [0x0F, 0x06];
const SET_TS = [0x0F, 0x20, 0xC0, 0x0D, ...u32(8), 0x0F, 0x22, 0xC0];
const NO_OSXSAVE = [0x0F, 0x20, 0xE0, 0x25, ...u32(~(1 << 18) >>> 0), 0x0F, 0x22, 0xE0];
const GPRS = [0, 1, 2, 3, 5, 6, 7]; // (not ESP)
// flags before (set before the operands: MOV keeps them): OF, SF, AF, CF
// (0x7F + 1, STC) or ZF, PF (XOR EAX, EAX)
const FLAGS_BEFORE = [[[0xB0, 0x7F, 0x04, 0x01, 0xF9], 0x891], [[0x31, 0xC0], 0x44]];

/** A three-byte VEX prefix (no register extensions) and opcode, then ModRM
 * (reg, rm register or [address]) and imm8 */
const vex = ({ map, pp, w = 0, vvvv = 0, l = 0 }, op, reg, rm, address, imm8) => [0xC4, 0xE0 | map, w << 7 | (~vvvv & 15) << 3 | l << 2 | pp, op,
    ...(address === undefined ? [0xC0 | reg << 3 | rm] : absolute(reg, address)), ...(imm8 === undefined ? [] : [imm8])];

// Values: edges of 32 bits and random ones
let seed = 0x5EED5EED;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const EDGES = [0, 1, 2, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0xFFFFFFFE, 0x0000FFFF, 0xFFFF0000, 0x00010000, 0x8000, 0x55555555, 0xAAAAAAAA, 0x00F0F000];
// BEXTR's control and BZHI's index: within, at and beyond the operand, bits above 15
const CONTROLS = [0x0000, 0x0804, 0x1000, 0x2000, 0x1F01, 0x2001, 0x0020, 0x0021, 0x00FF, 0xFF00, 0xFFFF, 0x10101, 0x0510, 0x401E, 0xFFFF0303];
const INDICES = [0, 1, 4, 15, 16, 31, 32, 33, 63, 64, 255, 0x100, 0x101F, 0xFFFFFF05, 7];
const value_of = n => n % 3 === 0 ? EDGES[(n / 3 | 0) % EDGES.length] : random();

const machines = [];
// The forms the page tier (machines[1]) runs as templates (P10 part 2: the hot ones
// of plan 5.1 and their siblings, 32-bit operands); it steps the others
const PAGE_TEMPLATED = ["andn", "blsr", "blsmsk", "blsi", "bzhi", "shlx", "sarx", "shrx", "rorx", "tzcnt 32", "lzcnt 32", "movbe 32"];
const page_forms = { templated: [], stepped: [] };
/** Before a run: the page tier's step counts from 0 */
const reset_steps = vm => vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
/** After a hot run of `count` cases of `name` on the page tier machine: its
 * steps of instructions beginning with the bytes of `key` (two, little
 * endian) say whether it ran a template (a few steps at most: TLB misses) */
function page_check(vm, run, name, key, count)
{
    if(vm !== machines[1] || !run.startsWith("hot")) return;
    const steps = vm.v86.cpu.wm.exports["x64_page_steps"](key), templated = steps < count;
    assert.equal(templated, PAGE_TEMPLATED.includes(name), `${name}: the page tier ${templated ? "ran a template" : "stepped"} (${steps} steps, ${count} cases)`);
    page_forms[templated ? "templated" : "stepped"].push(name);
}
async function run(vm, program, warm, interpreter, label)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, `program/JIT timeout (${label})`);
        await sleep(1);
    }
    // (a hot run goes on a while, then ends at the end of a round)
    if(warm)
    {
        await sleep(20);
        vm.write_memory(Uint8Array.of(1), 0x604);
        while(!cpu.in_hlt[0])
        {
            assert(performance.now() < deadline, `program end timeout (${label})`);
            await sleep(1);
        }
    }
    await vm.stop();
}
// the body repeats until byte 0x604 is set, then halts at the end of the
// round; each round clears the fault record first
const CLEAR_FAULT = [0xC7, 0x05, ...u32(FAULT), 0, 0, 0, 0];
function loop(body)
{
    const p = [...CLEAR_FAULT, ...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it, the faulting EIP, CR2 and the error code, and skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58, 0xA3, ...u32(FAULT + 12));
    p.push(0xC7, 0x05, ...u32(FAULT), ...u32(vector));
    p.push(0x8B, 0x04, 0x24, 0xA3, ...u32(FAULT + 4));
    p.push(0x0F, 0x20, 0xD0, 0xA3, ...u32(FAULT + 8));
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true]];
const PROLOGUE = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...CLTS];
/** Runs `program` on each machine, hot (compiled) then cold; `check` after each run */
async function run_all(program, before = () => {}, set = machines, check = () => {})
{
    for(const [i, vm] of set.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], k) => {
            const h = HANDLER + k * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(new Uint8Array(16), FAULT);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, loop([...PROLOGUE, ...program]), warm, vm === set[0], `machine ${i} ${warm ? "hot" : "cold"}`);
            check(vm, `${warm ? "hot" : "cold"}, machine ${i}`);
        }
    }
}
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/** `faulting` raises `vector` at its first byte after `prologue`, and `check` holds */
async function expect_fault(prologue, faulting, vector, { epilogue = [], before = () => {}, cr2, label, check = () => {} } = {})
{
    const at = CODE + CLEAR_FAULT.length + PROLOGUE.length + prologue.length;
    await run_all([...prologue, ...faulting, ...epilogue], vm => {
        vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
        before(vm);
    }, machines, (vm, run) => {
        assert.deepEqual([word(vm, FAULT), word(vm, FAULT + 4)], [vector, at], `${label} (${run}): vector, EIP`);
        if(cr2 !== undefined) assert.equal(word(vm, FAULT + 8), cr2, `${label} (${run}): CR2`);
        check(vm, run);
    });
}
const no_fault = name => (vm, run) => assert.equal(word(vm, FAULT), 0, `${name} (${run}): fault ${word(vm, FAULT)} at ${word(vm, FAULT + 4).toString(16)}`);
const pages = (vm, page, present) => {
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};
const CPUID = (leaf, out) => [0xB8, ...u32(leaf), 0x31, 0xC9, 0x0F, 0xA2, 0x89, 0x1D, ...u32(out), 0x89, 0x0D, ...u32(out + 4)];

/** TZCNT/LZCNT (F3 0F BC/BD), BSF/BSR without the F3 */
const count_form = (op, bits, reg, rm, address) => [...bits === 16 ? [0x66] : [], 0xF3, 0x0F, op,
    ...(address === undefined ? [0xC0 | reg << 3 | rm] : absolute(reg, address))];
/** MOVBE load (F0) and store (F1) */
const movbe_form = (op, bits, reg, address) => [...bits === 16 ? [0x66] : [], 0x0F, 0x38, op, ...absolute(reg, address)];

let checks = 0;
try
{
    // Without the features: CPUID reports none; TZCNT and LZCNT are BSF and
    // BSR (the F3 prefix ignored); the VEX forms and MOVBE #UD
    machines.push(...await create_machines());
    await run_all([...CPUID(7, OUT), ...CPUID(1, OUT + 8)], undefined, machines, (vm, run) => {
        assert.equal(word(vm, OUT) & (1 << 3 | 1 << 8), 0, `CPUID.7.0:EBX BMI1, BMI2 (${run})`);
        assert.equal(word(vm, OUT + 12) & 1 << 22, 0, `CPUID.1:ECX MOVBE (${run})`);
    });
    {
        const program = [], count = 16;
        for(let n = 0; n < count; n++)
        {
            const op = n & 1 ? 0xBD : 0xBC, value = n < 8 ? 0 : EDGES[n - 7];
            program.push(...mov_r32(2, value), ...mov_r32(1, 0xDEADBEEF), ...count_form(op, 32, 1, 2), ...store_r32(1, OUT + n * 8), ...PUSHF_STORE(OUT + n * 8 + 4));
        }
        await run_all(program, undefined, machines, (vm, run) => {
            no_fault("TZCNT/LZCNT without their features")(vm, run);
            for(let n = 0; n < count; n++)
            {
                const value = n < 8 ? 0 : EDGES[n - 7], name = n & 1 ? "bsr" : "bsf";
                const { result, flags } = ops[name](BigInt(value), 32, 0xDEADBEEFn);
                assert.equal(word(vm, OUT + n * 8), Number(result), `${name} for F3 0F ${n & 1 ? "BD" : "BC"} ${value.toString(16)} (${run})`);
                assert.equal(word(vm, OUT + n * 8 + 4) & flags.defined, flags.value, `${name}'s ZF (${run})`);
            }
        });
    }
    for(const f of VEX_FORMS)
    {
        await expect_fault([], vex(f, f.op, f.group ?? 1, 2, undefined, f.name === "rorx" ? 5 : undefined), 6, { label: `${f.name} without ${f.isa}` });
    }
    await expect_fault([], movbe_form(0xF0, 32, 1, SOURCE), 6, { label: "movbe without its feature" });
    checks += 4 + VEX_FORMS.length;
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: without the features, CPUID reports none, TZCNT and LZCNT are BSF and BSR, the VEX forms and MOVBE #UD");

    // With them (the x86-64 profile, which alone can have LZCNT)
    machines.push(...await create_machines({ cpu_type: "x86_64", cpu_features: ["BMI1", "BMI2", "LZCNT", "MOVBE"], cpu_features_unreleased: true }));
    await run_all([...CPUID(7, OUT), ...CPUID(1, OUT + 8), ...CPUID(0x80000001, OUT + 16)], undefined, machines, (vm, run) => {
        assert.equal(word(vm, OUT) & (1 << 3 | 1 << 8), 1 << 3 | 1 << 8, `CPUID.7.0:EBX BMI1, BMI2 (${run})`);
        assert.equal(word(vm, OUT + 12) & 1 << 22, 1 << 22, `CPUID.1:ECX MOVBE (${run})`);
        assert.equal(word(vm, OUT + 20) & 1 << 5, 1 << 5, `CPUID.80000001H:ECX LZCNT (${run})`);
    });
    checks += 3;

    // Every VEX form against the model
    for(const f of VEX_FORMS)
    {
        const count = 96, cases = [];
        for(let n = 0; n < count; n++)
        {
            const memory = n >= count / 2;
            // (registers: the destinations alias the sources in a third of the cases)
            const reg = GPRS[n % 7], vvvv = f.roles === "reg = rm, imm8" ? 0 : GPRS[(n + (n % 3 === 0 ? 0 : 3)) % 7];
            const rm = memory ? undefined : GPRS[(n + (n % 3 === 1 ? 0 : 5)) % 7];
            const second = ["bextr"].includes(f.name) ? CONTROLS[n % CONTROLS.length] : ["bzhi"].includes(f.name) ? INDICES[n % INDICES.length] : value_of(n + 1);
            cases.push({ memory, reg: f.group === undefined ? reg : f.group, vvvv, rm, source: value_of(n), second,
                rdx: random(), imm8: n * 7 & 255, address: SOURCE + n * 8 + (n & 3), flags: n & 1 });
        }
        const program = [];
        cases.forEach((c, n) => {
            // the flags, then the registers: every GPR but ESP a value;
            // VEX.vvvv's second, the r/m register the source, EDX MULX's
            // multiplier
            program.push(...FLAGS_BEFORE[c.flags][0]);
            for(const r of GPRS) program.push(...mov_r32(r, 0x11111111 * (r + 1)));
            program.push(...mov_r32(2, c.rdx));
            if(f.roles !== "reg = rm, imm8") program.push(...mov_r32(c.vvvv, c.second));
            if(c.memory) program.push(0xC7, 0x05, ...u32(c.address), ...u32(c.source));
            else program.push(...mov_r32(c.rm, c.source));
            program.push(...vex({ map: f.map, pp: f.pp, vvvv: c.vvvv }, f.op, c.reg, c.rm, c.memory ? c.address : undefined, f.name === "rorx" ? c.imm8 : undefined));
            for(const [k, r] of GPRS.entries()) program.push(...store_r32(r, OUT + n * 32 + 4 * k));
            program.push(...PUSHF_STORE(OUT + n * 32 + 28));
        });
        await run_all(program, vm => { vm.write_memory(new Uint8Array(count * 32), OUT); reset_steps(vm); }, machines, (vm, run) => {
            no_fault(f.name)(vm, run);
            page_check(vm, run, f.name, f.map === 3 ? 0xE3C4 : 0xE2C4, count);
            cases.forEach((c, n) => {
                const registers = [];
                for(const r of GPRS) registers[r] = BigInt(0x11111111 * (r + 1) >>> 0);
                registers[2] = BigInt(c.rdx);
                if(f.roles !== "reg = rm, imm8") registers[c.vvvv] = BigInt(c.second >>> 0);
                if(!c.memory) registers[c.rm] = BigInt(c.source);
                const source = c.memory ? BigInt(c.source) : registers[c.rm];
                const { writes, flags } = execute_vex(f, { reg: c.reg, vvvv: c.vvvv, source, imm8: c.imm8, gpr: r => registers[r], bits: 32 });
                for(const [r, v] of writes) registers[r] = v;
                const label = `${f.name} case ${n} (${c.memory ? "memory" : "r" + c.rm}, vvvv r${c.vvvv}, reg r${c.reg}) source ${c.source.toString(16)} second ${(c.second >>> 0).toString(16)} (${run})`;
                for(const [k, r] of GPRS.entries()) assert.equal(word(vm, OUT + n * 32 + 4 * k), Number(registers[r]), `${label}: r${r}`);
                const after = word(vm, OUT + n * 32 + 28) & ARITHMETIC;
                if(flags) assert.equal(after, v86_flags(writes[writes.length - 1][1], 32, flags), `${label}: flags`);
                else assert.equal(after, FLAGS_BEFORE[c.flags][1], `${label}: flags kept`);
            });
        });
        checks += count;
    }
    console.log(`PASS: ${VEX_FORMS.length} VEX forms from registers and memory as the model: the destinations, aliasing, MULX's EDX, the flags (kept where the SDM leaves them)`);

    // TZCNT and LZCNT (16 and 32 bits) from registers and memory, the 16-bit
    // destination's upper half kept
    for(const [op, name] of [[0xBC, "tzcnt"], [0xBD, "lzcnt"]]) for(const bits of [16, 32])
    {
        const count = 48, program = [];
        const operands = Array.from({ length: count }, (_, n) => ({ memory: n >= count / 2, dst: GPRS[n % 7], src: GPRS[(n + 3) % 7], value: value_of(n),
            address: SOURCE + n * 8 + (n & 3) }));
        const operand = n => operands[n];
        for(let n = 0; n < count; n++)
        {
            const { memory, dst, src, value, address } = operand(n);
            program.push(...FLAGS_BEFORE[n & 1][0]);
            if(memory) program.push(0xC7, 0x05, ...u32(address), ...u32(value));
            else program.push(...mov_r32(src, value));
            program.push(...mov_r32(dst, 0xDEADBEEF));
            program.push(...count_form(op, bits, dst, src, memory ? address : undefined), ...store_r32(dst, OUT + n * 8), ...PUSHF_STORE(OUT + n * 8 + 4));
        }
        await run_all(program, reset_steps, machines, (vm, run) => {
            no_fault(name)(vm, run);
            page_check(vm, run, `${name} ${bits}`, bits === 16 ? 0xF366 : 0x0FF3, count);
            for(let n = 0; n < count; n++)
            {
                const { memory, dst, src, value } = operand(n);
                const source = memory || src !== dst ? value : 0xDEADBEEF;
                const { result, flags } = ops[name](BigInt(source), bits);
                const expected = bits === 16 ? (0xDEADBEEF & 0xFFFF0000 | Number(result)) >>> 0 : Number(result);
                const label = `${name} (${bits}) case ${n} ${source.toString(16)} (${run})`;
                assert.equal(word(vm, OUT + n * 8), expected, label);
                assert.equal(word(vm, OUT + n * 8 + 4) & ARITHMETIC, v86_flags(result, bits, flags), `${label}: flags`);
            }
        });
        checks += count;
    }
    console.log("PASS: TZCNT and LZCNT (16 and 32 bits) from registers and memory: the counts, the operand's size for 0 with CF, ZF");

    // MOVBE: loads and stores of 16 and 32 bits, unaligned; flags kept
    for(const bits of [16, 32])
    {
        const count = 32, program = [], values = Array.from({ length: count }, (_, n) => value_of(n));
        for(let n = 0; n < count; n++)
        {
            const value = values[n], r = GPRS[n % 7], address = SOURCE + n * 8 + (n & 3);
            program.push(...FLAGS_BEFORE[n & 1][0], 0xC7, 0x05, ...u32(address), ...u32(value), ...mov_r32(r, 0xA5A5A5A5));
            program.push(...movbe_form(0xF0, bits, r, address), ...store_r32(r, OUT + n * 16));
            program.push(...mov_r32(r, value), ...movbe_form(0xF1, bits, r, OUT + n * 16 + 4 + (n & 3)), ...PUSHF_STORE(OUT + n * 16 + 12));
        }
        await run_all(program, vm => { vm.write_memory(new Uint8Array(count * 16).fill(0xEE), OUT); reset_steps(vm); }, machines, (vm, run) => {
            no_fault("movbe")(vm, run);
            page_check(vm, run, `movbe ${bits}`, bits === 16 ? 0x0F66 : 0x380F, count * 2);
            for(let n = 0; n < count; n++)
            {
                const value = values[n], swapped = Number(ops.movbe(BigInt(value) & (1n << BigInt(bits)) - 1n, bits).result);
                const label = `movbe (${bits}) case ${n} ${value.toString(16)} (${run})`;
                assert.equal(word(vm, OUT + n * 16), bits === 16 ? (0xA5A50000 | swapped) >>> 0 : swapped, `${label}: load`);
                const stored = bytes(vm, OUT + n * 16 + 4 + (n & 3), bits / 8 + 1);
                assert.deepEqual(Array.from(stored.subarray(0, bits / 8)), u32(swapped).slice(0, bits / 8), `${label}: store`);
                assert.equal(stored[bits / 8], 0xEE, `${label}: no byte beyond`);
                assert.equal(word(vm, OUT + n * 16 + 12) & ARITHMETIC, FLAGS_BEFORE[n & 1][1], `${label}: flags kept`);
            }
        });
        checks += count;
    }
    console.log("PASS: MOVBE loads and stores (16 and 32 bits): the bytes reversed, no byte beyond");
    assert.deepEqual([...page_forms.templated].sort(), [...PAGE_TEMPLATED].sort(), "every form the page tier runs as a template was run");
    console.log(`PASS: the page tier ran templates for ${page_forms.templated.join(", ")}; stepped ${page_forms.stepped.join(", ")}`);

    // Exceptions: #UD for VEX.L1, a VEX.vvvv other than 1111b where it is no
    // operand (RORX), 66/F2/F3/LOCK before VEX, MOVBE from a register; none
    // for CR4.OSXSAVE clear or CR0.TS set
    const andn = vex({ map: 2, pp: 0, vvvv: 3 }, 0xF2, 1, 2);
    await expect_fault([], vex({ map: 2, pp: 0, vvvv: 3, l: 1 }, 0xF2, 1, 2), 6, { label: "andn with VEX.L1" });
    await expect_fault([], vex({ map: 3, pp: 3, vvvv: 2 }, 0xF0, 1, 2, undefined, 3), 6, { label: "rorx with VEX.vvvv 2" });
    for(const prefix of [0x66, 0xF2, 0xF3, 0xF0]) await expect_fault([], [prefix, ...andn], 6, { label: `${prefix.toString(16)} andn` });
    await expect_fault([], [0x0F, 0x38, 0xF0, 0xC1], 6, { label: "movbe from a register" });
    await run_all([...NO_OSXSAVE, ...SET_TS, ...mov_r32(2, 0xF0F0), ...mov_r32(3, 0xFF00), ...andn, ...store_r32(1, OUT), ...CLTS], undefined, machines, (vm, run) => {
        no_fault("andn without CR4.OSXSAVE, with CR0.TS")(vm, run);
        assert.equal(word(vm, OUT), 0x00F0, `andn without CR4.OSXSAVE, with CR0.TS (${run})`);
    });
    checks += 8;
    // #PF: the source on an absent page, the destination kept; MOVBE's store
    // across into it writes nothing
    await expect_fault([...mov_r32(1, 0x12345678)], vex({ map: 2, pp: 0, vvvv: 3 }, 0xF2, 1, undefined, ABSENT - 2), 14, {
        cr2: ABSENT, label: "andn across into an absent page",
        before: vm => pages(vm, ABSENT, false),
        check: (vm, run) => assert.equal(vm.v86.cpu.reg32[1] >>> 0, 0x12345678, `andn's destination kept (${run})`),
    });
    await expect_fault([...mov_r32(1, 0x12345678)], movbe_form(0xF1, 32, 1, ABSENT - 2), 14, {
        cr2: ABSENT, label: "movbe store across into an absent page",
        before: vm => { vm.write_memory(new Uint8Array(2).fill(0xEE), ABSENT - 2); pages(vm, ABSENT, false); },
        check: (vm, run) => assert.deepEqual(Array.from(bytes(vm, ABSENT - 2, 2)), [0xEE, 0xEE], `movbe wrote nothing (${run})`),
    });
    for(const vm of machines) pages(vm, ABSENT, true);
    checks += 2;
    console.log("PASS: #UD for VEX.L1, VEX.vvvv where no operand, prefixes before VEX and MOVBE from a register; no AVX state requirements; #PF without effect");

    // Virtual-8086 mode and real mode with a 32-bit code segment, where C4
    // is LES (last: it rewrites the descriptor and page tables): a loop
    // runs until the byte at 604h is set (on the compiled arms in
    // virtual-8086 mode once compiled code ran it: the page tier compiles
    // virtual-8086 code, x64_page_v86, but not real-mode code on a 32-bit
    // stack, which the interpreter runs; the region tiers, which compiled
    // both, were deleted in M11), then falls through to ANDN, which raises
    // #UD, or TZCNT, which runs, and the HLT after it halts (real mode) or
    // raises #GP. The handlers halt: virtual-8086 mode's at ring 0 (a TSS
    // gives the stack), real mode's through the vector table at 0.
    const V86_CODE = 0x8000, GDT = 0x251100, TSS = 0x251200, RING0_STACK = 0x253000, UD_HALT = 0x281000, GP_HALT = 0x281010, REAL_UD = 0x70000;
    const descriptor = (base, limit, access, flags) => [...u32(limit & 0xFFFF | base << 16), ...u32(base & 0xFF000000 | base >>> 16 & 255 | access << 8 | limit & 0xF0000 | flags << 20)];
    // (virtual-8086 mode first: real mode leaves CR0.PE clear)
    for(const real of [false, true])
    {
        for(const [form, name] of [[[0xC4, 0xE2, 0x68, 0xF2, 0xCE], "andn"], [[0xF3, 0x0F, 0xBC, 0xCE], "tzcnt"]])
        {
            for(const [i, vm] of machines.entries())
            {
                const cpu = vm.v86.cpu, e = cpu.wm.exports;
                const label = `${name} in ${real ? "real mode (32-bit code)" : "virtual-8086 mode"} (machine ${i})`;
                // L: INC (E)SI; CMP BYTE [604h], 0; JE L; the form; HLT
                const loop_code = real ? [0x46, 0x80, 0x3D, ...u32(0x604), 0x00, 0x74, 0xF6] : [0x46, 0x80, 0x3E, 0x04, 0x06, 0x00, 0x74, 0xF8];
                cpu.jit_clear_cache();
                vm.write_memory(Uint8Array.from([...loop_code, ...form, 0xF4]), V86_CODE);
                vm.write_memory(new Uint8Array(1), 0x604);
                vm.write_memory(Uint8Array.of(0xF4), UD_HALT);
                vm.write_memory(Uint8Array.of(0xF4), GP_HALT);
                vm.write_memory(Uint8Array.of(0xF4), REAL_UD);
                if(real)
                {
                    // (CR0.PE and PG clear; the vector table at 0: #UD at 7000:0000)
                    cpu.cr[0] &= ~0x80000001; cpu.protected_mode[0] = 0;
                    vm.write_memory(Uint8Array.from([0, 0, 0x00, 0x70]), 6 * 4);
                    cpu.idtr_offset[0] = 0; cpu.idtr_size[0] = 0x3FF;
                    cpu.sreg.fill(0, 0, 6);
                    for(let r = 0; r < 6; r++)
                    {
                        cpu.segment_offsets[r] = 0; cpu.segment_limits[r] = 0xFFFFFFFF; cpu.segment_is_null[r] = 0;
                    }
                    cpu.segment_access_bytes.set([0x93, 0x9B, 0x93, 0x93, 0x93, 0x93]);
                    cpu.cpl[0] = 0; cpu.is_32[0] = 1; cpu.stack_size_32[0] = 1;
                    cpu.flags[0] = 2;
                }
                else
                {
                    // ring-0 code (8) and data (16), the TSS (24) with SS0:ESP0
                    vm.write_memory(Uint8Array.from([...new Array(8).fill(0), ...descriptor(0, 0xFFFFF, 0x9B, 12), ...descriptor(0, 0xFFFFF, 0x93, 12), ...descriptor(TSS, 0x67, 0x89, 0)]), GDT);
                    vm.write_memory(Uint8Array.from([0, 0, 0, 0, ...u32(RING0_STACK), ...u32(16)]), TSS);
                    cpu.gdtr_offset[0] = GDT; cpu.gdtr_size[0] = 31;
                    cpu.segment_offsets[6] = TSS; cpu.segment_limits[6] = 0x67; cpu.tss_size_32[0] = 1;
                    for(const [vector, h] of [[6, UD_HALT], [13, GP_HALT]])
                        vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
                    cpu.idtr_offset[0] = IDT; cpu.idtr_size[0] = 0x7FF;
                    // (user pages: the first 4 MiB)
                    const pde = cpu.cr[3] & ~0xFFF, table = word(vm, pde) & ~0xFFF;
                    vm.write_memory(Uint8Array.from(u32(word(vm, pde) | 4)), pde);
                    for(const page of [0, 8, 9]) vm.write_memory(Uint8Array.from(u32(word(vm, table + page * 4) | 4)), table + page * 4);
                    // CS 0800h (the code at 0), SS 0900h (SP 1000h), ES/DS/FS/GS 0
                    cpu.sreg.set([0, 0x0800, 0x0900, 0, 0, 0]);
                    for(let r = 0; r < 6; r++)
                    {
                        cpu.segment_offsets[r] = cpu.sreg[r] << 4; cpu.segment_limits[r] = 0xFFFF; cpu.segment_is_null[r] = 0;
                    }
                    cpu.segment_access_bytes.set([0xF3, 0xFB, 0xF3, 0xF3, 0xF3, 0xF3]);
                    cpu.cpl[0] = 3; cpu.is_32[0] = 0; cpu.stack_size_32[0] = 0;
                    cpu.flags[0] = 0x20002;
                }
                cpu.flags_changed[0] = 0;
                cpu.reg32.set([0, 0xA5A5A5A5, 0x804, 0x5A5A5A5A, real ? 0xA000 : 0x1000, 0, 0x12345677, 0]);
                cpu.instruction_pointer[0] = V86_CODE; cpu.in_hlt[0] = 0;
                e.update_state_flags(); e.full_clear_tlb();
                const start = compiled_activations(e);
                vm.run();
                const deadline = performance.now() + 20000;
                while(i !== 0 && !real && compiled_activations(e) === start)
                {
                    assert(performance.now() < deadline, `${label}: no compiled code ran`);
                    await sleep(1);
                }
                await sleep(20);
                vm.write_memory(Uint8Array.of(1), 0x604);
                while(!cpu.in_hlt[0])
                {
                    assert(performance.now() < deadline, `${label}: timed out`);
                    await sleep(1);
                }
                await vm.stop();
                const at = loop_code.length, source = real ? cpu.reg32[6] >>> 0 : cpu.reg32[6] & 0xFFFF;
                const halted = name === "andn" ? real ? REAL_UD : UD_HALT : real ? V86_CODE + at + form.length : GP_HALT;
                assert.equal(cpu.instruction_pointer[0] >>> 0, halted + 1, `${label}: halted`);
                if(!real) assert.equal(word(vm, RING0_STACK - 36), name === "andn" ? at : at + form.length, `${label}: the faulting IP`);
                const count = Number(ops.tzcnt(BigInt(source), real ? 32 : 16).result);
                assert.equal(cpu.reg32[1] >>> 0, name === "andn" ? 0xA5A5A5A5 : real ? count : (0xA5A50000 | count) >>> 0, `${label}: ECX`);
            }
            checks++;
        }
    }
    console.log("PASS: virtual-8086 mode and real mode, where C4 is LES: ANDN raises #UD, TZCNT runs, interpreted and compiled");
    console.log(`PASS: ${checks} BMI1/BMI2/TZCNT/LZCNT/MOVBE checks on ${COMPILED_ARMS.length + 1} arms`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                              source/v64/tests/rust/bmi_model.mjs                                                                 0000644 0000000 0000000 00000020754 00000000000 014475  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A model of BMI1, BMI2, TZCNT, LZCNT and MOVBE (docs/simd-xsave-plan.md
// 9.2, P10) from the SDM's operations, written apart from src/rust/cpu/bmi.rs:
// BigInt bit by bit. Each instruction gives its result(s) and its flags as
// { value, defined }: `defined` the flags the SDM specifies, the others
// undefined. v86 gives undefined flags fixed values (`v86_flags`).
export const CF = 1, PF = 4, AF = 0x10, ZF = 0x40, SF = 0x80, OF = 0x800;
export const ARITHMETIC = CF | PF | AF | ZF | SF | OF;

const ones = bits => (1n << BigInt(bits)) - 1n;
const bit = (v, i) => Number(v >> BigInt(i) & 1n);
const sign = (v, bits) => bit(v, bits - 1);
const parity = v => { let n = 0; for(let i = 0; i < 8; i++) n += bit(v, i); return n % 2 === 0; };

/** The flags v86 gives an instruction: its defined ones, and for the
 * undefined ones AF 0, PF the result's parity, SF the result's sign, OF 0 */
export function v86_flags(r, bits, { value, defined })
{
    const fallback = (parity(r) ? PF : 0) | (sign(r, bits) ? SF : 0);
    return value & defined | fallback & ~defined & ARITHMETIC;
}

// each: (operands as BigInt, bits) => { result, flags?: { value, defined } }
export const ops = {
    // ANDN: NOT src1 AND src2; SF, ZF; OF, CF cleared; AF, PF undefined
    andn: (a, b, bits) => {
        const r = ~a & b & ones(bits);
        return { result: r, flags: { value: (r === 0n ? ZF : 0) | (sign(r, bits) ? SF : 0), defined: ZF | SF | OF | CF } };
    },
    // BEXTR: start control[7:0], length control[15:8], bits beyond the
    // operand zero; ZF; CF, OF cleared; AF, SF, PF undefined
    bextr: (src, control, bits) => {
        const start = Number(control & 0xFFn), length = Number(control >> 8n & 0xFFn);
        let r = 0n;
        for(let i = 0; i < length; i++)
        {
            const at = start + i;
            if(at < bits) r |= BigInt(bit(src, at)) << BigInt(i);
        }
        return { result: r & ones(bits), flags: { value: r === 0n ? ZF : 0, defined: ZF | CF | OF } };
    },
    // BLSI: -src AND src; ZF, SF; CF = src != 0; OF cleared
    blsi: (src, bits) => {
        const s = src & ones(bits), r = (-s & s) & ones(bits);
        return { result: r, flags: { value: (r === 0n ? ZF : 0) | (sign(r, bits) ? SF : 0) | (s !== 0n ? CF : 0), defined: ZF | SF | CF | OF } };
    },
    // BLSMSK: (src - 1) XOR src; SF; CF = src == 0; ZF, OF cleared
    blsmsk: (src, bits) => {
        const s = src & ones(bits), r = ((s - 1n) ^ s) & ones(bits);
        return { result: r, flags: { value: (sign(r, bits) ? SF : 0) | (s === 0n ? CF : 0), defined: SF | CF | ZF | OF } };
    },
    // BLSR: (src - 1) AND src; ZF, SF; CF = src == 0; OF cleared
    blsr: (src, bits) => {
        const s = src & ones(bits), r = ((s - 1n) & s) & ones(bits);
        return { result: r, flags: { value: (r === 0n ? ZF : 0) | (sign(r, bits) ? SF : 0) | (s === 0n ? CF : 0), defined: ZF | SF | CF | OF } };
    },
    // BZHI: bits from index[7:0] on cleared; ZF, SF; CF = index > size - 1; OF cleared
    bzhi: (src, index, bits) => {
        const n = Number(index & 0xFFn);
        let r = src & ones(bits);
        if(n < bits) r &= ones(n);
        return { result: r, flags: { value: (r === 0n ? ZF : 0) | (sign(r, bits) ? SF : 0) | (n > bits - 1 ? CF : 0), defined: ZF | SF | CF | OF } };
    },
    // MULX: EDX/RDX times the source, unsigned: high and low halves; no flags
    mulx: (d, src, bits) => {
        const p = (d & ones(bits)) * (src & ones(bits));
        return { result: p >> BigInt(bits), low: p & ones(bits) };
    },
    // PDEP: the source's low bits to the selector's set bits
    pdep: (src, selector, bits) => {
        let r = 0n, k = 0;
        for(let i = 0; i < bits; i++) if(bit(selector, i)) r |= BigInt(bit(src, k++)) << BigInt(i);
        return { result: r };
    },
    // PEXT: the source's bits at the selector's set bits, packed
    pext: (src, selector, bits) => {
        let r = 0n, k = 0;
        for(let i = 0; i < bits; i++) if(bit(selector, i)) r |= BigInt(bit(src, i)) << BigInt(k++);
        return { result: r };
    },
    // RORX: rotate right by imm8 modulo the size
    rorx: (src, imm8, bits) => {
        const n = Number(imm8) % bits, s = src & ones(bits);
        let r = 0n;
        for(let i = 0; i < bits; i++) r |= BigInt(bit(s, (i + n) % bits)) << BigInt(i);
        return { result: r };
    },
    // SARX, SHLX, SHRX: by count modulo the size
    sarx: (src, count, bits) => {
        const n = Number(count) % bits, s = src & ones(bits);
        let r = 0n;
        for(let i = 0; i < bits; i++) r |= BigInt(bit(s, Math.min(i + n, bits - 1))) << BigInt(i);
        return { result: r };
    },
    shlx: (src, count, bits) => ({ result: (src << BigInt(Number(count) % bits)) & ones(bits) }),
    shrx: (src, count, bits) => ({ result: (src & ones(bits)) >> BigInt(Number(count) % bits) }),
    // TZCNT, LZCNT: the operand's size for 0; CF = source zero, ZF = result zero; OF, SF, PF, AF undefined
    tzcnt: (src, bits) => {
        const s = src & ones(bits);
        let r = 0;
        while(r < bits && !bit(s, r)) r++;
        return { result: BigInt(r), flags: { value: (r === 0 ? ZF : 0) | (s === 0n ? CF : 0), defined: ZF | CF } };
    },
    lzcnt: (src, bits) => {
        const s = src & ones(bits);
        let r = 0;
        while(r < bits && !bit(s, bits - 1 - r)) r++;
        return { result: BigInt(r), flags: { value: (r === 0 ? ZF : 0) | (s === 0n ? CF : 0), defined: ZF | CF } };
    },
    // MOVBE: the operand's bytes reversed
    movbe: (v, bits) => {
        let r = 0n;
        for(let i = 0; i < bits / 8; i++) r |= (v >> BigInt(8 * i) & 0xFFn) << BigInt(bits - 8 - 8 * i);
        return { result: r };
    },
    // BSF, BSR (TZCNT and LZCNT without their features): ZF for a zero
    // source, whose destination is kept (v86's); the other flags undefined
    bsf: (src, bits, old) => {
        const s = src & ones(bits);
        if(s === 0n) return { result: old, flags: { value: ZF, defined: ZF } };
        let r = 0;
        while(!bit(s, r)) r++;
        return { result: BigInt(r), flags: { value: 0, defined: ZF } };
    },
    bsr: (src, bits, old) => {
        const s = src & ones(bits);
        if(s === 0n) return { result: old, flags: { value: ZF, defined: ZF } };
        let r = bits - 1;
        while(!bit(s, r)) r--;
        return { result: BigInt(r), flags: { value: 0, defined: ZF } };
    },
};

/** The VEX forms: [name, map, pp, opcode, ModRM.reg group or undefined,
 * operand roles (reg: ModRM.reg, vvvv, rm), imm8] */
export const VEX_FORMS = [
    ["andn", 2, 0, 0xF2, undefined, "reg = vvvv, rm"],
    ["blsr", 2, 0, 0xF3, 1, "vvvv = rm"],
    ["blsmsk", 2, 0, 0xF3, 2, "vvvv = rm"],
    ["blsi", 2, 0, 0xF3, 3, "vvvv = rm"],
    ["bzhi", 2, 0, 0xF5, undefined, "reg = rm, vvvv"],
    ["pext", 2, 2, 0xF5, undefined, "reg = vvvv, rm"],
    ["pdep", 2, 3, 0xF5, undefined, "reg = vvvv, rm"],
    ["mulx", 2, 3, 0xF6, undefined, "reg:vvvv = rdx, rm"],
    ["bextr", 2, 0, 0xF7, undefined, "reg = rm, vvvv"],
    ["shlx", 2, 1, 0xF7, undefined, "reg = rm, vvvv"],
    ["sarx", 2, 2, 0xF7, undefined, "reg = rm, vvvv"],
    ["shrx", 2, 3, 0xF7, undefined, "reg = rm, vvvv"],
    ["rorx", 3, 3, 0xF0, undefined, "reg = rm, imm8"],
].map(([name, map, pp, op, group, roles]) => ({ name, map, pp, op, group, roles, isa: ["andn", "blsr", "blsmsk", "blsi", "bextr"].includes(name) ? "BMI1" : "BMI2" }));

/** A VEX form's results: the registers it writes { register: value } and
 * its flags (or none), from `gpr` (register reads) and its source operand */
export function execute_vex(f, { reg, vvvv, source, imm8, gpr, bits })
{
    const { name } = f;
    switch(name)
    {
        case "andn": case "pext": case "pdep":
        {
            const { result, flags } = ops[name](gpr(vvvv), source, bits);
            return { writes: [[reg, result]], flags };
        }
        case "blsr": case "blsmsk": case "blsi":
        {
            const { result, flags } = ops[name](source, bits);
            return { writes: [[vvvv, result]], flags };
        }
        case "bzhi": case "bextr": case "shlx": case "sarx": case "shrx":
        {
            const { result, flags } = ops[name](source, gpr(vvvv), bits);
            return { writes: [[reg, result]], flags };
        }
        case "mulx":
        {
            const { result, low } = ops.mulx(gpr(2), source, bits);
            // (the low half to VEX.vvvv first: ModRM.reg's high half wins)
            return { writes: [[vvvv, low], [reg, result]] };
        }
        case "rorx": return { writes: [[reg, ops.rorx(source, BigInt(imm8), bits).result]] };
    }
    throw new Error(name);
}
                    source/v64/tests/rust/compiled_arms.mjs                                                             0000644 0000000 0000000 00000002644 00000000000 015362  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Compiled-code arms for tests that compare generated code with the
// interpreter. 32-bit protected-mode code runs in the x64 page tier by
// default since M8 (x64_page_legacy32, docs/jit-unification-plan.md P7.3),
// 16-bit code since M10; the region tiers, a second arm until then, were
// deleted in M11. Tests run their compiled side once per arm (tests check the
// page tier's step counts on the first compiled machine, x64_page_steps).
export const COMPILED_ARMS = [
    { label: "pages", options: { ir_sync_publication: true } },
];

// A hot run of VEX forms waits until no VEX instruction was interpreted
// (ir_interpreted_stat field 6) through a whole round of its program (they
// run in page functions). The run calls it once a round has ended (the
// program sets the word at `marker`); it clears the word until two calls in a
// row found the count unchanged, which spans a round from its start to its
// end.
export function vex_settled(marker)
{
    let last = -1, quiet = 0;
    return vm => {
        const count = vm.v86.cpu.wm.exports["ir_interpreted_stat"](6, 0);
        quiet = count === last ? quiet + 1 : 0;
        last = count;
        if(quiet >= 2) return true;
        vm.write_memory(new Uint8Array(4), marker);
        return false;
    };
}

// Activations of compiled code: the page tier's (x64_page_stat 13)
export function compiled_activations(exports)
{
    return exports["x64_page_stat"](13) >>> 0;
}
                                                                                            source/v64/tests/rust/cpu_optimizations.mjs                                                         0000644 0000000 0000000 00000057754 00000000000 016340  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

// Compiled code against independent oracles, once per compiled arm (the page tier).
const wasm = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
let vm;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const word = address => new DataView(Uint8Array.from(vm.read_memory(address, 4)).buffer).getUint32(0, true);
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const DATA = 0x200000, RESULT = 0x210000;
let cpu, e;
async function run(address) {
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.instruction_pointer[0] = address;
    cpu.in_hlt[0] = 0;
    vm.run();
    const end = performance.now() + 10000;
    while(word(0x600) !== 0xCAFE) { assert(performance.now() < end, "guest timeout"); await sleep(1); }
    await vm.stop();
}
async function compile(address) {
    cpu.instruction_pointer[0] = address;
    cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 10000;
    while(compiled_activations(e) === start) {
        assert(performance.now() < deadline, "natural JIT warmup timeout");
        await sleep(1);
    }
    await vm.stop();
}
const done = [0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE)];
for(const { label, options } of COMPILED_ARMS) {
vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: wasm, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20, ...options,
    disable_keyboard: true, disable_mouse: true, disable_speaker: true,
    net_device: { type: "none" }, autostart: false });
try {
    await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
    vm.run();
    const deadline = performance.now() + 10000;
    while(word(0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
    await vm.stop();
    cpu = vm.v86.cpu; e = cpu.wm.exports;
    // SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
    cpu.cr[4] |= 0x600;
    const patterns = new Uint8Array(512);
    let seed = 0x9132913;
    for(let i = 0; i < patterns.length; i++) {
        seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
        patterns[i] = seed;
    }
    const pattern_view = new DataView(patterns.buffer);
    for(const [i, bits] of [0, 0x80000000, 0x7F800000, 0xFF800000,
        0x7FC12345, 0x7F812345, 1, 0xFFFFFFFF].entries()) {
        pattern_view.setUint32(i * 4, bits, true);
        pattern_view.setUint32(256 + i * 4, ~bits, true);
    }
    vm.write_memory(patterns, DATA);
    const operations = [
        [[], 0x54, "and"], [[0x66], 0x54, "and"], [[0x66], 0xDB, "and"],
        [[], 0x55, "andnot"], [[0x66], 0x55, "andnot"], [[0x66], 0xDF, "andnot"],
        [[], 0x56, "or"], [[0x66], 0x56, "or"], [[0x66], 0xEB, "or"],
        [[], 0x57, "xor"], [[0x66], 0x57, "xor"], [[0x66], 0xEF, "xor"],
    ];
    let cases = 0;
    for(const [index, [prefix, opcode, op]] of operations.entries()) {
        const address = 0x100000 + index * 4096;
        const program = [], expected = new Uint8Array(64 * 20);
        for(let src = 0; src < 8; src++) for(let dst = 0; dst < 8; dst++) {
            const n = src * 8 + dst;
            program.push(0xF3, 0x0F, 0x6F, 0x05 | src << 3, ...u32(DATA + src * 16));
            program.push(0xF3, 0x0F, 0x6F, 0x05 | dst << 3, ...u32(DATA + 256 + dst * 16));
            program.push(0xF9, ...prefix, 0x0F, opcode, 0xC0 | dst << 3 | src);
            program.push(0xF3, 0x0F, 0x7F, 0x05 | dst << 3, ...u32(RESULT + n * 20));
            program.push(0x9C, 0x58, 0xA3, ...u32(RESULT + n * 20 + 16));
            for(let k = 0; k < 16; k++) {
                const b = patterns[256 + dst * 16 + k];
                const a = src === dst ? b : patterns[src * 16 + k];
                expected[n * 20 + k] = op === "and" ? a & b : op === "andnot" ? a & ~b : op === "or" ? a | b : a ^ b;
            }
        }
        program.push(...done);
        program.push(0xE9, ...u32(-program.length - 5));
        assert(program.length < 4096);
        vm.write_memory(Uint8Array.from(program), address);
        await compile(address);
        const before = compiled_activations(e);
        await run(address);
        assert(compiled_activations(e) !== before, "execute compiled IR");
        const result = Uint8Array.from(vm.read_memory(RESULT, expected.length));
        for(let n = 0; n < 64; n++) {
            assert.deepEqual(result.slice(n * 20, n * 20 + 16), expected.slice(n * 20, n * 20 + 16), `${op} ${index} register pair ${n}`);
            assert.equal(result[n * 20 + 16] & 1, 1, "SSE logic preserves carry");
        }
        cases += 64;
    }
    // Same-module and cross-module indirect CALL/RET, followed by live code
    // invalidation. Results must change after replacing the callee.
    for(const target of [0x180100, 0x190100]) {
        const address = 0x180000;
        const program = [0x31, 0xC0, 0xBB, ...u32(target), 0xB9, ...u32(100),
            0xFF, 0xD3, 0x49, 0x75, 0xFB, 0xA3, ...u32(RESULT), ...done];
        program.push(0xE9, ...u32(-program.length - 5));
        vm.write_memory(Uint8Array.from(program), address);
        vm.write_memory(Uint8Array.from([0x83, 0xC0, 7, 0xC3]), target);
        await compile(address);
        await run(address);
        assert.equal(word(RESULT), 700, "indirect call/ret result");
        vm.write_memory(Uint8Array.from([0x83, 0xC0, 11, 0xC3]), target);
        await compile(address);
        await run(address);
        assert.equal(word(RESULT), 1100, "invalidated callee is never reused");
        const state = await vm.save_state();
        await vm.restore_state(state);
        await compile(address);
        await run(address);
        assert.equal(word(RESULT), 1100, "indirect targets after save/restore");
    }
    console.log("PASS: same/cross-module indirect CALL/RET, SMC and save/restore");
    const arith = [[0x01, 0xD8, false, true], [0x03, 0xC3, false, true],
        [0x29, 0xD8, true, true], [0x2B, 0xC3, true, true],
        [0x39, 0xD8, true, false], [0x3B, 0xC3, true, false]];
    const arithmetic = (a, b, sub) => {
        const value = (sub ? a - b : a + b) >>> 0;
        let parity = value & 255;
        parity ^= parity >>> 4; parity ^= parity >>> 2; parity ^= parity >>> 1;
        const carry = sub ? a < b : a + b > 0xFFFFFFFF;
        const overflow = sub ? ((a ^ b) & (a ^ value)) >>> 31 : (~(a ^ b) & (a ^ value)) >>> 31;
        const flags = Number(carry) | ((~parity & 1) << 2) | ((a ^ b ^ value) & 16) |
            (value === 0 ? 64 : 0) | (value >>> 24 & 128) | (overflow << 11);
        return { value, flags };
    };
    let flag_cases = 0;
    for(let first = 0; first < 6; first++) for(let second = 0; second < 6; second++) {
        const program = [], expected = [];
        for(let i = 0; i < 64; i++) {
            const edge = [0, 1, 0xFFFFFFFF, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFF, 0x10000];
            const a = edge[i & 7], b = edge[i >>> 3];
            const f = arith[first], g = arith[second];
            const intermediate = arithmetic(a, b, f[2]);
            const result = arithmetic(f[3] ? intermediate.value : a, b, g[2]);
            expected.push([g[3] ? result.value : f[3] ? intermediate.value : a, result.flags]);
            program.push(0xB8, ...u32(a), 0xBB, ...u32(b), f[0], f[1], 0xB9, ...u32(0x12345678), 0x89, 0xDA, 0x90, g[0], g[1],
                0xA3, ...u32(RESULT + i * 8), 0x9C, 0x58, 0xA3, ...u32(RESULT + i * 8 + 4));
        }
        program.push(...done);
        program.push(0xE9, ...u32(-program.length - 5));
        assert(program.length < 4096);
        const address = 0x300000 + (first * 6 + second) * 4096;
        vm.write_memory(Uint8Array.from(program), address);
        await compile(address); await run(address);
        for(let i = 0; i < expected.length; i++) {
            assert.equal(word(RESULT + i * 8), expected[i][0], "arithmetic result");
            assert.equal(word(RESULT + i * 8 + 4) & 0x8D5, expected[i][1], `flags ${first}/${second}/${i}`);
        }
        flag_cases += expected.length;
    }
    // A flags observer/consumer between arithmetic operations must keep the
    // first operation's carry/overflow, rather than exposing stale metadata.
    for(const [index, barrier] of [[0, [0x9C, 0x5A]], [1, [0x83, 0xD0, 0]],
        [2, [0x40]], [3, [0xD3, 0xE0]]]) {
        const address = 0x340000 + index * 4096;
        const program = [0xB8, ...u32(0xFFFFFFFF), 0xBB, ...u32(1), 0xB9, ...u32(0),
            0x01, 0xD8, ...barrier, 0x89, 0x15, ...u32(RESULT + 8),
            0x9C, 0x5A, 0x89, 0x15, ...u32(RESULT + 4), 0x03, 0xC3, 0xA3, ...u32(RESULT), ...done];
        program.push(0xE9, ...u32(-program.length - 5));
        vm.write_memory(Uint8Array.from(program), address);
        await compile(address); await run(address);
        assert.equal(word(RESULT), index === 1 || index === 2 ? 2 : 1, "flags consumer result");
        if(index !== 1) assert.equal(word(RESULT + 4) & 1, 1, "preserved carry at observer");
        if(index === 0) assert.equal(word(RESULT + 8) & 0x8D5, arithmetic(0xFFFFFFFF, 1, false).flags);
    }
    console.log(`PASS: ${flag_cases} arithmetic flag cases across MOV/NOP and PUSHFD/ADC/INC/zero-shift barriers`);
    // A real #NM must still be raised by the optimized register instruction.
    // Install a guest handler that skips the faulting instruction and clears TS.
    const handler = 0x381000, idt = 0x250000, descriptor = 0x251000;
    const gate = [handler & 255, handler >>> 8 & 255, 8, 0, 0, 0x8E, handler >>> 16 & 255, handler >>> 24];
    vm.write_memory(Uint8Array.from(gate), idt + 7 * 8);
    vm.write_memory(Uint8Array.from([255, 7, ...u32(idt)]), descriptor);
    vm.write_memory(Uint8Array.from([
        0x8B, 0x04, 0x24, 0xA3, ...u32(RESULT),
        0xFF, 0x05, ...u32(RESULT + 4),
        0x83, 0x04, 0x24, 3,
        0x0F, 0x20, 0xC0, 0x83, 0xE0, 0xF7, 0x0F, 0x22, 0xC0, 0xCF,
    ]), handler);
    const fault_program = [0x0F, 0x01, 0x1D, ...u32(descriptor),
        0xF3, 0x0F, 0x6F, 0x05, ...u32(DATA),
        0xF3, 0x0F, 0x6F, 0x0D, ...u32(DATA + 16),
        0x0F, 0x20, 0xC0, 0x83, 0xC8, 8, 0x0F, 0x22, 0xC0];
    const fault_eip = 0x380000 + fault_program.length;
    fault_program.push(0x0F, 0x57, 0xC1, 0xF3, 0x0F, 0x7F, 0x05, ...u32(RESULT + 16), ...done);
    fault_program.push(0xE9, ...u32(-fault_program.length - 5));
    vm.write_memory(Uint8Array.from(fault_program), 0x380000);
    vm.write_memory(new Uint8Array(8), RESULT);
    await compile(0x380000); await run(0x380000);
    assert.equal(word(RESULT), fault_eip, "#NM points to the SSE instruction");
    assert(word(RESULT + 4) > 0, "SSE still raises #NM with TS set");
    assert.deepEqual(Uint8Array.from(vm.read_memory(RESULT + 16, 16)), patterns.slice(0, 16), "faulting XORPS did not change XMM");
    console.log("PASS: optimized SSE retains guest #NM and precise fault EIP");
    // Selectively synchronized division helpers must leave every register
    // intact on #DE; the exception is delivered after locals are materialized.
    const de_handler=0x38C000,de_code=0x38D000;
    vm.write_memory(Uint8Array.from([de_handler&255,de_handler>>>8&255,8,0,0,0x8E,de_handler>>>16&255,de_handler>>>24]),idt);
    for(const instruction of [[0x66,0xF7,0xF3],[0x66,0xF7,0xFB],[0xF7,0xFB]]) {
        const regs=[[0,0x11223344],[1,0xABCDEF01],[2,0x77880000],[3,0],[5,0x10101010],[6,0x12345678],[7,0x99887766]];
        const handler=[];
        for(const [r] of regs) handler.push(0x89,5|r<<3,...u32(RESULT+r*4));
        handler.push(0x8B,0x04,0x24,0xA3,...u32(RESULT+32),0x83,0x04,0x24,instruction.length,0xCF);
        vm.write_memory(Uint8Array.from(handler),de_handler);
        const p=[];
        for(const [r,v] of regs) p.push(0xB8+r,...u32(v));
        const fault=de_code+p.length;
        p.push(...instruction,...done,0xE9,...u32(-p.length-instruction.length-done.length-5));
        vm.write_memory(Uint8Array.from(p),de_code);
        await compile(de_code);await run(de_code);
        for(const [r,v] of regs) assert.equal(word(RESULT+r*4),v,"#DE preserves register "+r);
        assert.equal(word(RESULT+32),fault,"#DE preserves fault EIP");
    }
    console.log("PASS: helper register contracts retain precise division faults");
    // Flags before a faulting memory access must remain observable in the
    // hardware exception frame, even when later arithmetic overwrites them.
    const pf_handler = 0x383000, pf_address = 0x382000;
    vm.write_memory(Uint8Array.from([pf_handler & 255, pf_handler >>> 8 & 255,
        8, 0, 0, 0x8E, pf_handler >>> 16 & 255, pf_handler >>> 24]), idt + 14 * 8);
    vm.write_memory(Uint8Array.from([
        0x8B, 0x44, 0x24, 12, 0xA3, ...u32(RESULT),
        0x8B, 0x44, 0x24, 4, 0xA3, ...u32(RESULT + 4),
        0x83, 0x44, 0x24, 4, 6, 0x83, 0xC4, 4, 0xCF,
    ]), pf_handler);
    const pf_program = [0xB8, ...u32(0xFFFFFFFF), 0xBB, ...u32(1), 0x01, 0xD8,
        // Carry flag provenance through MOV/LEA, overwriting both aliases,
        // before the fault observes the original ADD's architectural flags.
        0xB8, ...u32(7), 0x8D, 0x58, 4,
        0xBE, ...u32(0x801FFC), 0x8B, 0x0E]; // seed a valid relative-read cache
    const pf_eip = pf_address + pf_program.length;
    pf_program.push(0x8B, 0x96, ...u32(4), 0x9C, 0x59, 0x89, 0x0D, ...u32(RESULT + 8),
        0x03, 0xC3, ...done);
    pf_program.push(0xE9, ...u32(-pf_program.length - 5));
    vm.write_memory(Uint8Array.from(pf_program), pf_address);
    await compile(pf_address); await run(pf_address);
    const pf_flags = arithmetic(0xFFFFFFFF, 1, false).flags;
    assert.equal(word(RESULT) & 0x8D5, pf_flags, "flags in page fault frame");
    assert.equal(word(RESULT + 4), pf_eip, "precise memory fault EIP");
    assert.equal(word(RESULT + 8) & 0x8D5, pf_flags, "flags survive fault/IRET");
    console.log("PASS: flags remain precise across guest page fault and IRET");
    // A mapped device read must occur for each access, never reuse paging scratch.
    const old_mmio = cpu.memory_map_read32[0xA0000 >>> 17];
    let device_reads = 0;
    cpu.memory_map_read32[0xA0000 >>> 17] = () => ++device_reads;
    try {
        for(const loads of [
            [0xA1,...u32(0xA0000),0x8B,0x1D,...u32(0xA0004)],
            [0xBE,...u32(0xA0000),0x8B,0x06,0x8B,0x5E,4],
            [0xBE,...u32(0xA0000),0x8B,0x06,0x31,0xC9,0x41,0x8B,0x5E,4],
        ]) {
            const p = [...loads,0x29,0xC3,
                0x89,0x1D,...u32(RESULT),...done];
            p.push(0xE9,...u32(-p.length-5));
            vm.write_memory(Uint8Array.from(p),0x384000);
            await compile(0x384000); await run(0x384000);
            assert(device_reads > 2);
            assert.equal(word(RESULT),1,"each MMIO read observes a fresh device value");
        }
    } finally { cpu.memory_map_read32[0xA0000 >>> 17] = old_mmio; }
    // Every mapped store must reach the device even after a nearby store.
    const write_index = 0xA0000 >>> 17, old_write = cpu.memory_map_write32[write_index];
    const device_writes = [];
    cpu.memory_map_write32[write_index] = (address,value) => device_writes.push([address,value >>> 0]);
    try {
        const p=[0xBE,...u32(0xA0000),0xB8,...u32(0x12345678),
            0x89,0x06,0x89,0x46,4,...done];
        p.push(0xE9,...u32(-p.length-5));
        vm.write_memory(Uint8Array.from(p),0x386000);
        await compile(0x386000); device_writes.length=0; await run(0x386000);
        // The VM may stop between the two stores (compiled code can exit
        // after an MMIO store), so the last pair can be incomplete; the order
        // cannot.
        assert(device_writes.length >= 2);
        for(let i=0;i<device_writes.length;i++) assert.deepEqual(device_writes[i],
            [0xA0000+(i%2)*4,0x12345678]);
    } finally { cpu.memory_map_write32[write_index]=old_write; }
    // RMW cache misses must retain both device reads and writes.
    let rmw_reads=0;
    cpu.memory_map_read32[write_index]=()=>++rmw_reads;
    cpu.memory_map_write32[write_index]=(address,value)=>device_writes.push([address,value>>>0]);
    try {
        const p=[0xBE,...u32(0xA0000),0xB8,...u32(17),0x01,0x06,0x01,0x46,4,...done];
        p.push(0xE9,...u32(-p.length-5));
        vm.write_memory(Uint8Array.from(p),0x386000);
        await compile(0x386000); rmw_reads=0; device_writes.length=0; await run(0x386000);
        assert(rmw_reads>=2 && device_writes.length===rmw_reads);
        for(let i=0;i<rmw_reads;i++) assert.deepEqual(device_writes[i],[0xA0000+(i%2)*4,i+18]);
    } finally { cpu.memory_map_read32[write_index]=old_mmio; cpu.memory_map_write32[write_index]=old_write; }
    // Cached POP crosses upward into a missing page; the exception frame can
    // still use the mapped stack below it. Resume restores the original ESP.
    {
        const base=0x38B000;
        const original_stack=cpu.reg32[4] >>> 0;
        // compile()/run() may stop in a later iteration while ESP still points
        // into the fault-test page. Do not capture that borrowed ESP as the
        // original stack on replay, or later fault frames corrupt copy output.
        const p=[0xBD,...u32(original_stack),0xBC,...u32(0x801FFC),0x58];
        const fault_eip_local=base+p.length; p.push(0x5A);
        const resume=base+p.length; p.push(0x89,0xEC,...done);
        p.push(0xE9,...u32(-p.length-5));
        vm.write_memory(Uint8Array.from([
            0xA3,...u32(RESULT),0x8B,0x44,0x24,4,0xA3,...u32(RESULT+4),
            0xC7,0x44,0x24,4,...u32(resume),0x83,0xC4,4,0xCF,
        ]),pf_handler);
        vm.write_memory(Uint8Array.from(p),base);
        await compile(base);
        vm.write_memory(Uint8Array.from(u32(0x76543210)),0x101FFC);
        // Subsequent fault frames overwrite the popped stack slot, so the
        // precise fault address is the invariant across repeated execution.
        await run(base);
        assert.equal(word(RESULT+4),fault_eip_local,"cached POP retains precise page fault EIP");
        cpu.reg32[4]=original_stack;
    }
    // Warm writers against RAM, then redirect the same compiled code to a
    // previously compiled target. Cached stores/copies must invalidate it.
    const smc_target=0x388000, writer=0x389000, pointer=DATA+768;
    const target_bytes=value => {
        const p=[0xB8,...u32(value),0xA3,...u32(RESULT+32),...done];
        p.push(0xE9,...u32(-p.length-5));
        while(p.length<64) p.push(0x90);
        return p;
    };
    for(const copy of [false,true]) {
        vm.write_memory(Uint8Array.from(target_bytes(1)),smc_target);
        await compile(smc_target); await run(smc_target);
        assert.equal(word(RESULT+32),1);
        vm.write_memory(Uint8Array.from(target_bytes(777)),DATA+1024);
        vm.write_memory(Uint8Array.from(u32(DATA+4096)),pointer);
        const p=[0x8B,0x3D,...u32(pointer)];
        if(copy) p.push(0xBE,...u32(DATA+1024),0xB9,...u32(64),
            0x8A,0x06,0x88,0x07,0x46,0x47,0x49,0x75,0xF7);
        else p.push(0xB8,...u32(777),0x89,0x07,0x89,0x47,64);
        p.push(...done,0xE9,...u32(-p.length-done.length-5));
        vm.write_memory(Uint8Array.from(p),writer);
        await compile(writer);
        vm.write_memory(Uint8Array.from(u32(smc_target+(copy ? 0 : 1))),pointer);
        await run(writer); await run(smc_target);
        assert.equal(word(RESULT+32),777,copy ? "copy into compiled code invalidates JIT" : "cached stores invalidate JIT");
    }
    console.log("PASS: cached stores and ordinary copies preserve code-page invalidation");
    // Capture architectural state at a write fault and leave the failing
    // loop. Tests include a cached store, both batched loops and REP fills.
    for(const kind of ["stores","rmw-stores","byte-loop","dword-loop","stosw","stosd","rmw-add","rmw-xor"]) {
        const base=0x387000;
        const p=[...(kind.startsWith("rmw") ? [0xFC,0xBF,...u32(0x801FD0),0xB9,...u32(12),0x31,0xC0,0xF3,0xAB] : []),
            0xFC,0xBE,...u32(DATA),0xBF,...u32(0x801FD0),
            0xB9,...u32(64),0xB8,...u32(0x12345678),0xF9];
        let fault_eip_local_local, copied, size;
        if(kind === "stores" || kind === "rmw-stores") {
            p.push(0xBF,...u32(0x801FFC));
            if(kind === "rmw-stores") p.push(0xC7,0x07,...u32(0));
            const op=kind === "stores" ? 0x89 : 0x01;
            p.push(op,0x07);
            fault_eip_local_local=base+p.length; p.push(op,0x87,...u32(4)); size=4; copied=1;
        } else if(kind.startsWith("rmw")) {
            size=4;copied=12;fault_eip_local_local=base+p.length;
            p.push(kind === "rmw-add" ? 0x01 : 0x31,0x07,0x83,0xC7,4,0x49,0x75,0xF8);
        } else if(kind.endsWith("loop")) {
            size=kind === "byte-loop" ? 1 : 4; copied=48/size;
            fault_eip_local_local=base+p.length+2;
            p.push(...(size === 1 ? [0x8A,0x06,0x88,0x07,0x46,0x47,0x49,0x75,0xF7] :
                [0x8B,0x06,0x89,0x07,0x83,0xC6,4,0x83,0xC7,4,0x49,0x75,0xF3]));
        } else {
            size=kind === "stosw" ? 2 : 4; copied=48/size;
            fault_eip_local_local=base+p.length; p.push(0xF3,...(size === 2 ? [0x66] : []),0xAB);
        }
        const resume=base+p.length;
        p.push(...done,0xE9,...u32(-p.length-done.length-5));
        // The handler also copies the 48 target bytes (REP MOVSD into
        // RESULT+64): the state at the fault, not wherever the VM stops later
        // (the rmw kinds zero the bytes again at the start of each iteration).
        vm.write_memory(Uint8Array.from([
            0x89,0x0D,...u32(RESULT),0x89,0x35,...u32(RESULT+4),0x89,0x3D,...u32(RESULT+8),
            0xA3,...u32(RESULT+16),0x8B,0x44,0x24,4,0xA3,...u32(RESULT+12),
            0xBE,...u32(0x801FD0),0xBF,...u32(RESULT+64),0xB9,...u32(12),0xF3,0xA5,
            0xC7,0x44,0x24,4,...u32(resume),0x83,0xC4,4,0xCF,
        ]),pf_handler);
        vm.write_memory(Uint8Array.from(p),base);
        await compile(base); await run(base);
        assert.equal(word(RESULT+12),fault_eip_local_local,kind+" precise fault EIP");
        if(kind === "stores" || kind === "rmw-stores") {
            assert.equal(word(RESULT+64+0x2C),0x12345678,"first cached store committed");
        } else {
            assert.equal(word(RESULT),64-copied,kind+" remaining count");
            assert.equal(word(RESULT+8),0x802000,kind+" destination progress");
            assert.equal(word(RESULT+4),DATA+(kind.endsWith("loop") ? 48 : 0),kind+" source progress");
            const expected = kind.endsWith("loop") ? Uint8Array.from(vm.read_memory(DATA,48)) :
                Uint8Array.from({length:48},(_,i)=>(0x12345678 >>> (i%size*8))&255);
            assert.deepEqual(Uint8Array.from(vm.read_memory(RESULT+64,48)),expected,kind+" partial writes");
        }
    }
    console.log("PASS: cached MMIO stores and batched copies/fills retain precise partial write faults");
    // Overlap ends at an unmapped virtual page. The first 47 byte stores must
    // complete, and the fault frame/registers must describe the remaining 17.
    vm.write_memory(Uint8Array.from([
        0x89,0x0D,...u32(RESULT),0x89,0x35,...u32(RESULT+4),0x89,0x3D,...u32(RESULT+8),
        0x8B,0x44,0x24,4,0xA3,...u32(RESULT+12),
        0x83,0x44,0x24,4,2,0x83,0xC4,4,0xCF,
    ]),pf_handler);
    const overlap = [0xFC,0xBE,...u32(0x801FD0),0xBF,...u32(0x801FD1),0xB9,...u32(64)];
    const overlap_eip = 0x385000 + overlap.length;
    overlap.push(0xF3,0xA4,...done);
    overlap.push(0xE9,...u32(-overlap.length-5));
    vm.write_memory(Uint8Array.from({length:48},(_,i)=>i+17),0x101FD0);
    vm.write_memory(Uint8Array.from(overlap),0x385000);
    await compile(0x385000); await run(0x385000);
    assert.equal(word(RESULT),17,"REP remaining ECX after partial page fault");
    assert.equal(word(RESULT+4),0x801FFF,"REP partial ESI");
    assert.equal(word(RESULT+8),0x802000,"REP partial EDI");
    assert.equal(word(RESULT+12),overlap_eip,"fault restarts the REP instruction");
    assert.deepEqual(Uint8Array.from(vm.read_memory(0x101FD0,48)),new Uint8Array(48).fill(17));
    console.log("PASS: MMIO reads are not cached; overlapping REP preserves partial progress at #PF");
    console.log(`PASS: ${cases} real-JIT SSE logical register cases, aliases and carry; ${wasm} ${label}`);
} finally { await vm.destroy(); }
}
                    source/v64/tests/rust/cpu_optimizations_benchmark.mjs                                               0000644 0000000 0000000 00000033463 00000000000 020341  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
// cpu_optimizations_benchmark.mjs [baseline.wasm candidate.wasm]: two cores in
// their default JIT configuration; without paths, the interpreter against the
// default (32-bit code in the x64 page tier) on one core. (The region tiers,
// the reference until then, were deleted in M11.)
const baseline = process.argv[2];
const candidate = process.argv[3] || "build/v86.wasm";
const arms = baseline ? [{ label: baseline, wasm: baseline, options: {} }, { label: candidate, wasm: candidate, options: {} }] :
    [{ label: "interpreter", wasm: candidate, options: { disable_jit: true } }, { label: "pages", wasm: candidate, options: {} }];
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const median = a => a.toSorted((x, y) => x - y)[a.length >> 1];
const machines = [];
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
try {
    for(const { wasm, options } of arms) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: wasm, ...options, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        machines.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const end = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < end); await sleep(1); }
        await vm.stop();
    }
    const address = 0x100000;
    const kinds = ["stack-burst", "rmw-straight", "flags-mixed-read", "flags-linear-region", "sse-scalar-double", "bulk-add-array", "bulk-xor-array", "helper-mul16", "helper-xadd16", "sse-float-nan", "ram-relative-read-lea", "ram-relative-read-alu", "copy-byte-loop", "copy-dword-loop", "ram-relative-writes", "ram-write-pages", "fill-word-pattern", "fill-dword-pattern", "fill-dword-zero", "ram-relative-reads", "ram-relative-pages", "ram-pointer-chase", "flags-mov-setcc", "flags-lea-cmov", "flags-alias-setcc", "flags-mov-jcc", "sse3-duplicate-chain", "sse3-addsub", "sse-register-logic", "integer-flags", "indirect-call-ret", "short-cross-page",
        "x87-add-hit", "x87-add-fallback", "x87-f32-load-store", "x87-f32-rounded-store", "x87-f32-subnormal-store",
        "mmx-movq", "mmx-paddd", "mmx-pmaddwd", "mmx-packed", "sse-packed", "sse-float", "sse-scalar-float", "x87-f64-load-store", "x87-f64-rounded-store", "x87-f64-subnormal-store", "integer-flags-separated", "ram-reads", "rep-overlap", "x87-round", "x87-scale"];
    for(const kind of kinds.filter(kind => !process.env.BENCH_KINDS || process.env.BENCH_KINDS.split(",").includes(kind))) {
        const program = [0xB8, ...u32(1), 0xBB, ...u32(kind === "indirect-call-ret" ? address + 512 : 17)];
        if(kind === "sse-register-logic") {
            for(let r = 0; r < 8; r++) program.push(0x66, 0x0F, 0x6E, 0xC0 | r << 3);
        }
        if(kind === "sse-float" || kind === "sse-float-nan" || kind === "sse-scalar-float" || kind === "sse-scalar-double") {
            for(let r = 0; r < 8; r++) program.push(0x0F,0x10,0x05 | r << 3,...u32(0x220000));
        }
        if(kind.startsWith("x87")) program.push(0xDB, 0xE3);
        if(kind.startsWith("sse3")) {
            for(let r = 0; r < 8; r++) program.push(0xF3,0x0F,0x6F,5 | r << 3,...u32(0x220000));
        }
        if(kind.startsWith("ram-relative") || kind === "ram-write-pages" || kind === "ram-pointer-chase") program.push(0xBE, ...u32(0x220000));
        const loop = program.length;
        if(kind === "stack-burst") {
            for(let i=0;i<32;i++) program.push(0x50);
            for(let i=0;i<32;i++) program.push(0x58);
        } else if(kind === "rmw-straight") {
            program.push(0xBE,...u32(0x220000));
            for(let i=0;i<32;i++) program.push(0x01,0x5E,i*4);
        } else if(kind === "flags-mixed-read" || kind === "flags-linear-region") {
            program.push(0xBE,...u32(0x220000));
            for(let i=0;i<24;i++) {
                program.push(...[[0x39,0xD8],[0x85,0xD8],[0x30,0xD8],[0x66,0x39,0xD8]][i%4]);
                if(kind === "flags-linear-region") program.push(0xEB,0);
                program.push(0x8B,0x56,i*4,0x8D,0x1C,0x13);
            }
        } else if(kind.startsWith("bulk-")) {
            program.push(0xBF,...u32(0x220000),0xB9,...u32(1024),0xB8,...u32(17),
                kind === "bulk-add-array" ? 0x01 : 0x31,0x07,0x83,0xC7,4,0x49,0x75,0xF8);
        } else if(kind.startsWith("helper-")) {
            for(let i=0;i<32;i++) program.push(...(kind === "helper-mul16" ? [0x66,0xF7,0xE3] : [0x66,0x0F,0xC1,0xD8]));
        } else if(kind.startsWith("copy-")) {
            program.push(0xBE,...u32(0x220000),0xBF,...u32(0x230000),0xB9,...u32(1024),
                ...(kind === "copy-byte-loop" ? [0x8A,0x06,0x88,0x07,0x46,0x47,0x49,0x75,0xF7] :
                [0x8B,0x06,0x89,0x07,0x83,0xC6,4,0x83,0xC7,4,0x49,0x75,0xF3]));
        } else if(kind.startsWith("fill-")) {
            program.push(0xFC, 0xBF, ...u32(0x220000), 0xB9, ...u32(1024),
                0xB8, ...u32(kind.endsWith("zero") ? 0 : 0x12345678),
                0xF3, ...(kind === "fill-word-pattern" ? [0x66] : []), 0xAB);
        } else if(kind === "ram-relative-writes" || kind === "ram-write-pages") {
            for(let i=0;i<32;i++) program.push(0x89,0x86 | (i&3)<<3,
                ...u32(kind === "ram-write-pages" ? (i&1)*4096 : i*4));
        } else if(kind.startsWith("flags-")) {
            for(let i = 0; i < 32; i++) {
                // Keep a data dependency through the conditions, rather than
                // timing comparisons whose results can be discarded by Wasm.
                program.push(0x39, 0xD8); // cmp eax, ebx
                if(kind === "flags-lea-cmov") {
                    program.push(0x8D, 0x48, 1, 0x0F, 0x4C, 0xC1); // lea ecx,[eax+1]; cmovl eax,ecx
                } else if(kind === "flags-mov-jcc") {
                    program.push(0xB9, ...u32(1), 0x7D, 3, 0x8D, 0x04, 0x08); // mov ecx,1; jge +3; lea eax,[eax+ecx]
                } else {
                    program.push(0xB9, ...u32(1), 0xBA, ...u32(0));
                    if(kind === "flags-alias-setcc") program.push(0x89, 0xC8); // overwrite cmp destination
                    program.push(0x0F, 0x9C, 0xC2, 0x01, 0xD0); // setl dl; add eax,edx
                }
                program.push(0x01, 0xCB); // add ebx,ecx
            }
        } else if(kind.startsWith("sse3")) {
            for(let i = 0; i < 32; i++) {
                const [prefix,op] = kind === "sse3-addsub" ? [i&1 ? 0xF2 : 0x66,0xD0] :
                    [[0xF2,0x12],[0xF3,0x12],[0xF3,0x16],[0xF2,0x7D]][i&3];
                program.push(prefix,0x0F,op,0xC0 | (i&7)<<3 | ((i+1)&7));
            }
        } else if(kind === "sse-register-logic") {
            for(let i = 0; i < 32; i++) program.push(0x0F, [0x54, 0x55, 0x56, 0x57][i & 3], 0xC0 | (i & 7) << 3 | ((i + 1) & 7));
        } else if(kind === "sse-packed" || kind === "mmx-packed") {
            for(let i = 0; i < 32; i++) program.push(...(kind === "sse-packed" ? [0x66] : []),
                0x0F, [0xEC,0xD5,0xE4,0xF6][i & 3], 0xC0 | (i & 7) << 3 | ((i + 1) & 7));
        } else if(kind === "sse-float" || kind === "sse-float-nan" || kind === "sse-scalar-float" || kind === "sse-scalar-double") {
            for(let i = 0; i < 32; i++) program.push(...(kind === "sse-scalar-float" ? [0xF3] : kind === "sse-scalar-double" ? [0xF2] : []),
                0x0F, [0x5D,0x5F,0x59,0x51][i & 3], 0xC0 | (i & 7) << 3 | ((i + 1) & 7));
        } else if(kind === "x87-f64-load-store") {
            for(let i = 0; i < 16; i++) program.push(0xDD,0x05,...u32(0x220030),0xDD,0x1D,...u32(0x220020));
        } else if(kind === "x87-f64-rounded-store" || kind === "x87-f64-subnormal-store") {
            for(let i = 0; i < 16; i++) program.push(0xDB,0x2D,...u32(0x220000),0xDD,0x1D,...u32(0x220020));
        } else if(kind === "integer-flags-separated") {
            for(let i = 0; i < 16; i++) program.push(0x01, 0xD8, 0x89, 0xDA, 0x90, 0x29, 0xD8);
        } else if(kind === "ram-relative-read-alu" || kind === "ram-relative-read-lea") {
            for(let i=0;i<32;i++) program.push(0x8B,0x86,...u32(i*4),
                ...(kind.endsWith("lea") ? [0x8D,0x1C,0x03] : [0x01,0xC3]));
        } else if(kind.startsWith("ram-relative")) {
            for(let i = 0; i < 32; i++) program.push(0x8B, 0x86 | (i & 3) << 3,
                ...u32(kind === "ram-relative-pages" ? (i & 1) * 4096 : i * 4));
        } else if(kind === "ram-pointer-chase") {
            for(let i = 0; i < 32; i++) program.push(0x8B, 0x36);
        } else if(kind === "ram-reads") {
            for(let i = 0; i < 32; i++) program.push(0x8B, 5 | (i & 3) << 3, ...u32(0x220000 + i * 4));
        } else if(kind === "rep-overlap") {
            program.push(0xFC, 0xBE, ...u32(0x220000), 0xBF, ...u32(0x220001), 0xB9, ...u32(1024), 0xF3, 0xA4);
        } else if(kind === "x87-scale") {
            for(let i = 0; i < 16; i++) program.push(0xD9, 0x05, ...u32(0x220030),
                0xD9, 0x05, ...u32(0x220030), 0xD9, 0xFD, 0xD9, 0x1D, ...u32(0x220020), 0xDD, 0xD8);
        } else if(kind === "x87-round") {
            for(let i = 0; i < 16; i++) program.push(0xD9, 0x05, ...u32(0x220030), 0xD9, 0xFC, 0xD9, 0x1D, ...u32(0x220020));
        } else if(kind === "integer-flags") {
            for(let i = 0; i < 16; i++) program.push(0x01, 0xD8, 0x29, 0xD8);
        } else if(kind === "x87-f32-load-store") {
            for(let i = 0; i < 16; i++) program.push(0xD9, 0x05, ...u32(0x220030), 0xD9, 0x1D, ...u32(0x220020));
        } else if(kind === "x87-f32-rounded-store" || kind === "x87-f32-subnormal-store") {
            for(let i = 0; i < 16; i++) program.push(0xDB, 0x2D, ...u32(0x220000), 0xD9, 0x1D, ...u32(0x220020));
        } else if(kind.startsWith("mmx")) {
            for(let i = 0; i < 32; i++) program.push(0x0F,
                kind === "mmx-movq" ? 0x6F : kind === "mmx-paddd" ? 0xFE : 0xF5,
                0xC0 | (i & 7) << 3 | ((i + 1) & 7));
        } else if(kind === "short-cross-page") {
            // Indirect exits force independently compiled pages through the
            // core dispatcher, unlike a long loop inside one generated module.
        } else if(kind.startsWith("x87")) {
            for(let i = 0; i < 16; i++) program.push(0xDB, 0x2D, ...u32(0x220000),
                0xDB, 0x2D, ...u32(0x220010), 0xDE, 0xC1, 0xDB, 0x3D, ...u32(0x220020));
        } else {
            for(let i = 0; i < 8; i++) program.push(0xFF, 0xD3);
        }
        program.push(0xFF, 0x05, ...u32(0x600));
        if(kind === "short-cross-page") {
            program.push(0xB8, ...u32(address + 4096), 0xFF, 0xE0);
            while(program.length < 4096) program.push(0x90);
            program.push(0xB8, ...u32(address), 0xFF, 0xE0);
        } else program.push(0xE9, ...u32(loop - program.length - 5));
        if(kind === "indirect-call-ret") {
            while(program.length < 512) program.push(0x90);
            program.push(0x83, 0xC0, 1, 0xC3);
        }
        for(const vm of machines) {
            const operands = new Uint8Array(64), view = new DataView(operands.buffer);
            const low = kind === "x87-add-fallback" || kind === "x87-f32-rounded-store" || kind === "x87-f64-rounded-store" ? 0x8000000001n : 0n;
            view.setBigUint64(0, 0x9000000000000000n | low, true); view.setUint16(8, kind === "x87-f32-subnormal-store" ? 0x3F70 : kind === "x87-f64-subnormal-store" ? 0x3BFF : 0x4000, true);
            view.setBigUint64(16, 0x8800000000000000n | low, true); view.setUint16(24, 0x3FFF, true);
            view.setUint32(48, 0x3FC12345, true);
            if(kind === "x87-f64-load-store") view.setFloat64(48, 1.23456789, true);
            if(kind === "sse-float" || kind === "sse-float-nan" || kind === "sse-scalar-float" || kind === "sse-scalar-double" || kind.startsWith("sse3")) {
                for(let j = 0; j < 4; j++) view.setFloat32(j * 4, 1, true);
            }
            if(kind === "sse-scalar-double") for(let j=0;j<2;j++) view.setFloat64(j*8,1,true);
            if(kind === "sse-float-nan") for(let j=0;j<4;j++) view.setUint32(j*4,0x7FC12345,true);
            if(kind === "ram-pointer-chase") view.setUint32(0, 0x220000, true);
            vm.write_memory(operands, 0x220000);
            vm.write_memory(Uint8Array.from(program), address);
            vm.v86.cpu.instruction_pointer[0] = address;
            vm.v86.cpu.in_hlt[0] = 0;
            vm.run(); await sleep(500); await vm.stop();
        }
        if(kind.startsWith("x87-f64")) {
            assert.deepEqual(Uint8Array.from(machines[1].read_memory(0x220020, 8)),
                Uint8Array.from(machines[0].read_memory(0x220020, 8)), "binary64 store bits must match");
        }
        const times = [[], []];
        for(let round = 0; round < 9; round++) for(const index of round & 1 ? [1, 0] : [0, 1]) {
            const vm = machines[index], before = word(vm, 0x600), start = performance.now();
            while(performance.now() - start < 120) vm.v86.cpu.main_loop();
            const elapsed = performance.now() - start;
            const iterations = (word(vm, 0x600) - before) >>> 0;
            assert(iterations > 0);
            if(round >= 2) times[index].push(iterations / elapsed);
        }
        const old_rate = median(times[0]), new_rate = median(times[1]);
        console.log(JSON.stringify({ kind, reference: arms[0].label, candidate: arms[1].label,
            reference_iterations_per_ms: old_rate, candidate_iterations_per_ms: new_rate,
            speedup: new_rate / old_rate, rounds: 7, reference_samples: times[0], candidate_samples: times[1] }));
    }
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                                                                             source/v64/tests/rust/cpu_plan_sequences.mjs                                                        0000644 0000000 0000000 00000053227 00000000000 016423  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

// cpu_plan_sequences.mjs [baseline.wasm] [candidate.wasm]: machine 0 is the
// interpreter (or, with arguments, the baseline core); the candidate core runs
// every sequence once per compiled arm (the page tier) and must match it.
const candidate = process.argv[3] || "build/v86.wasm";
const baseline = process.argv[2] || candidate;
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x210000;
const machines = [], labels = [];
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const data = Uint8Array.from({ length: 8192 }, (_, i) => (i * 37 ^ i >> 3) & 255);
const programs = [];
const oracles = new Map();
for(const mmx of [false, true]) {
    const prefix = mmx ? [] : [0x66];
    for(let seed = 0; seed < 16; seed++) {
        const p = [0xDB, 0xE3];
        for(let r = 0; r < 8; r++) p.push(...(mmx ? [] : [0xF3]), 0x0F, 0x6F, 5 | r << 3, ...u32(DATA + r * 16));
        // Consecutive cached destinations, source aliases, shifts reading a
        // cached count, old custom logic emitters, and MMX custom emitters.
        const ops = [0xFC,0xD5,0xE4,0xF6,0xDB,0xDF,0xEB,0xEF,0xF5,0xFE,0xD1,0xF3];
        for(let i = 0; i < 96; i++) {
            p.push(...prefix, 0x0F, ops[(i + seed) % ops.length], 0xC0 | (i & 7) << 3 | ((i + seed) & 7));
            // Memory, float/helper and group boundaries must flush all values.
            if(i % 19 === 18) p.push(...(mmx ? [] : [0xF3]), 0x0F, 0x6F, 0x05, ...u32(DATA + i));
            if(i % 23 === 22) p.push(...prefix, 0x0F, 0x71, 0xD0, seed);
        }
        for(let r = 0; r < 8; r++) p.push(...(mmx ? [] : [0xF3]), 0x0F, 0x7F, 5 | r << 3, ...u32(OUT + r * 16));
        if(mmx) p.push(0xD9, 0x05, ...u32(DATA), 0xDD, 0x35, ...u32(OUT + 128)); // x87 observer/FNSAVE
        programs.push([`cached ${mmx ? "MMX" : "XMM"} sequence ${seed}`, p]);
    }
}
for(const prefix of [[], [0x66], [0xF2], [0xF3]]) for(let seed = 0; seed < 8; seed++) {
    const p = [];
    for(let r = 0; r < 8; r++) p.push(0xF3, 0x0F, 0x6F, 5 | r << 3, ...u32(DATA + r * 16));
    for(let i = 0; i < 64; i++) {
        p.push(...prefix, 0x0F, [0x58,0x59,0x5C,0x5D,0x5E,0x5F,0x51][i % 7], 0xC0 | (i & 7) << 3 | ((i + seed) & 7));
        if(i % 11 === 10) p.push(0x66, 0x0F, 0xEF, 0xC1);
    }
    for(let r = 0; r < 8; r++) p.push(0xF3, 0x0F, 0x7F, 5 | r << 3, ...u32(OUT + r * 16));
    programs.push([`floating cache prefix=${prefix} aliases=${seed}`, p]);
}
const bits = new DataView(data.buffer);
for(const [i, v] of [0n, 0x8000000000000000n, 0x7FF0000000000000n, 0x7FF123456789ABCDn,
    0x3FF0000000000000n, 0x7FC123457F812345n, 0x3F800000BF800000n, 1n].entries()) bits.setBigUint64(i * 16, v, true);
for(let pc = 0; pc < 3; pc++) for(let rc = 0; rc < 4; rc++) {
    const control = [0,2,3][pc] << 8 | rc << 10 | 0x3F;
    bits.setUint16(7800 + (pc * 4 + rc) * 2,control,true);
    const p = [0xDB,0xE3,0xD9,0x2D,...u32(DATA+7800+(pc*4+rc)*2)];
    for(const [i, exponent] of [-1023,-1022,-1.75,0,1.75,1023,1024].entries()) {
        bits.setFloat64(2000+i*16,1.23456789,true);
        bits.setFloat64(2008+i*16,exponent,true);
        p.push(0xDD,0x05,...u32(DATA+2008+i*16),0xDD,0x05,...u32(DATA+2000+i*16),
            0xD9,0xFD,0xDB,0x3D,...u32(OUT+i*32),0xDB,0x3D,...u32(OUT+i*32+16));
    }
    p.push(0xDF,0xE0,0xA3,...u32(OUT+256));
    programs.push([`FSCALE pc=${pc} rc=${rc}`,p]);
}
// Exercise both FST and FSTP through the JIT, with exact values, rounding,
// signed zero, subnormal, overflow and NaN cases under every x87 control mode.
const doubles = [0n, 0x8000000000000000n, 1n, 0xFFFFFFFFFFFFFn, 0x10000000000000n,
    0x3FF3C0CA4283DE1Bn, 0xBFF3C0CA4283DE1Bn, 0x7FEFFFFFFFFFFFFFn,
    0xFFEFFFFFFFFFFFFFn, 0x7FF0000000000000n, 0x7FF0000000000001n, 0x7FF8123456789ABCn];
const wide_stores = [[0x8000000000000000n,0x3C01], [0xFFFFFFFFFFFFF800n,0x43FE],
    [0x8000000000000400n,0x3FFF], [0x8000000000000C00n,0xBFFF],
    [0xFFFFFFFFFFFFFFFFn,0x43FE], [0x8000000000000001n,0x3C00],
    [0x8000000000000000n,0x7FFF], [0x8000000000000001n,0x7FFF]];
for(const [i,value] of doubles.entries()) bits.setBigUint64(3000+i*16,value,true);
for(const [i,[mantissa,exponent]] of wide_stores.entries()) {
    bits.setBigUint64(3400+i*16,mantissa,true); bits.setUint16(3408+i*16,exponent,true);
}
for(let pc = 0; pc < 3; pc++) for(let rc = 0; rc < 4; rc++) {
    const p = [0xDB,0xE3,0xD9,0x2D,...u32(DATA+7800+(pc*4+rc)*2)];
    // FNINIT marks registers empty without erasing their old payloads. Seed
    // all eight slots so FNSAVE is independent of earlier benchmark programs.
    p.unshift(0xDB,0xE3,...Array.from({ length: 8 }, () => [0xD9,0xEE]).flat());
    for(let i = 0; i < doubles.length + wide_stores.length; i++) {
        p.push(...(i < doubles.length ? [0xDD,0x05,...u32(DATA+3000+i*16)] :
            [0xDB,0x2D,...u32(DATA+3400+(i-doubles.length)*16)]),
        0xDD,0x15,...u32(OUT+i*32), 0xDD,0x3D,...u32(OUT+i*32+8),
        0xDD,0x1D,...u32(OUT+i*32+16), 0xDD,0x3D,...u32(OUT+i*32+24));
    }
    p.push(0xDD,0x35,...u32(OUT+4096));
    programs.push([`binary64 stores pc=${pc} rc=${rc}`,p]);
}
for(const prefix of [0xF3,0xF2,0]) for(let seed=0;seed<8;seed++) {
    const p=[];
    for(let r=0;r<8;r++) p.push(0x0F,0x10,5|r<<3,...u32(DATA+r*16));
    for(let i=0;i<64;i++) {
        p.push(prefix || (i&1 ? 0xF3 : 0xF2),0x0F,[0x58,0x59,0x5C,0x5D,0x5E,0x5F,0x51][i%7],
            0xC0|(i&7)<<3|((i+seed)&7));
        if(i%11 === 10) p.push(0x0F,0x11,5|(i&7)<<3,...u32(OUT+i*16));
        if(i%19 === 18) p.push(0x66,0x0F,0xEF,0xC1);
    }
    for(let r=0;r<8;r++) p.push(0x0F,0x11,5|r<<3,...u32(OUT+2048+r*16));
    programs.push([`scalar lane cache prefix=${prefix} aliases=${seed}`,p]);
}
for(const xor of [false,true]) for(const count of [1,7,8,9,128,129,1024])
for(const start of [0,1,4093]) for(const [dest,counter,value] of [[6,1,0],[3,7,2],[0,2,1]]) {
    const p=[0xFC,0xBE,...u32(DATA),0xBF,...u32(OUT),0xB9,...u32(2048),0xF3,0xA5,
        0xB8+dest,...u32(OUT+start),0xB8+counter,...u32(count),0xB8+value,...u32(0x87654321),
        xor ? 0x31 : 0x01,value<<3|dest,0x83,0xC0|dest,4,0x48|counter,0x75,0xF8];
    for(let reg=0;reg<8;reg++) p.push(0x89,5|reg<<3,...u32(OUT+8120+reg*4));
    p.push(0x9C,0x58,0xA3,...u32(OUT+8152));
    programs.push([`bulk RMW xor=${xor} count=${count} start=${start} regs=${dest},${counter},${value}`,p]);
}
for(const size of [1,4]) for(const count of [17,257]) for(const start of [1,4093])
for(const [source,dest,counter,temp] of [[6,7,3,1],[3,6,7,0],[0,7,6,2]]) {
    const p=[0xB8+source,...u32(DATA+start),0xB8+dest,...u32(OUT+start),0xB8+counter,...u32(count)];
    p.push(size === 1 ? 0x8A : 0x8B,temp<<3|source,size === 1 ? 0x88 : 0x89,temp<<3|dest,
        ...(size === 1 ? [0x40|source,0x40|dest] : [0x83,0xC0|source,4,0x83,0xC0|dest,4]),
        0x48|counter,0x75,size === 1 ? 0xF7 : 0xF3);
    p.push(0x89,5|counter<<3,...u32(OUT+8100),0x89,5|dest<<3,...u32(OUT+8104));
    programs.push([`bulk copy allocation size=${size} count=${count} start=${start} regs=${source},${dest},${counter},${temp}`,p]);
}
for(const kind of ["mul16","imul16","div16","idiv16","idiv32","xadd16","cmpxchg16"])
for(const r of [0,1,2,3,5,6,7]) for(const value of [1,17,1234]) {
    if(r === 2 && kind.includes("div")) continue;
    // MUL/DIV leave some flags undefined/preserved. Seed both VMs identically
    // instead of inheriting flags from whichever previous loop was stopped.
    const p=[0x31,0xFF,0x83,0xC7,0];
    for(const reg of [0,1,2,3,5,6,7]) p.push(0xB8+reg,...u32(
        reg === 2 ? kind === "idiv32" ? 0 : 0xABCD0000 : reg === 0 ? value : 0x12340011));
    if(kind === "idiv32") p.push(0xF7,0xF8|r);
    else if(kind === "xadd16" || kind === "cmpxchg16") p.push(0x66,0x0F,kind === "xadd16" ? 0xC1 : 0xB1,0xC3|r<<3);
    else p.push(0x66,0xF7,0xC0|(["mul16","imul16","div16","idiv16"].indexOf(kind)+4)<<3|r);
    for(let reg=0;reg<8;reg++) p.push(0x89,5|reg<<3,...u32(OUT+reg*4));
    p.push(0x9C,0x58,0xA3,...u32(OUT+32));
    programs.push([`helper effects ${kind} r=${r} value=${value}`,p]);
}
for(const start of [0,1,4080,4093,4095]) for(const gap of [
    [0x01,0xD8], [0x83,0xC3,1], [0x40], [0x49], [0xB9,...u32(123),0x90],
    [0x8D,0x48,4,0x31,0xC9], [0x39,0xC8,0x85,0xC0],
    [0x83,0xC6,4], [0xBE,...u32(DATA+4096)], [0x66,0xBE,0,0],
    [0xC7,0x46,4,...u32(0xABCDEF)], [0x50,0x59], Array(9).fill(0x90)]) {
    const p=[0xBE,...u32(DATA+start),0xBB,...u32(17),0xB9,...u32(9),0x8B,0x06,
        ...gap,0x8B,0x56,4,0x8B,0x5E,8,0x9C,0x59];
    for(const [i,r] of [0,1,2,3,6].entries()) p.push(0x89,5|r<<3,...u32(OUT+i*4));
    programs.push([`RAM read gaps start=${start} gap=${gap}`,p]);
}
for(const size of [1,4]) for(const count of [1,7,8,9,31,128,129,1024])
for(const start of [0,1,3967,4093]) for(const overlap of [null,0,1,-1]) {
    const source = overlap === null ? DATA+start : OUT+1024;
    const dest = overlap === null ? OUT+start : source+overlap;
    const p=[0xFC,0xBE,...u32(DATA),0xBF,...u32(OUT),0xB9,...u32(2048),0xF3,0xA5,
        0xB8,...u32(0x87654321),0xBE,...u32(source),0xBF,...u32(dest),0xB9,...u32(count),0xF9];
    p.push(...(size === 1 ? [0x8A,0x06,0x88,0x07,0x46,0x47,0x49,0x75,0xF7] :
        [0x8B,0x06,0x89,0x07,0x83,0xC6,4,0x83,0xC7,4,0x49,0x75,0xF3]));
    p.push(0x9C,0x5A);
    for(const [i,r] of [0,1,2,6,7].entries()) p.push(0x89,5|r<<3,...u32(OUT+8100+i*4));
    programs.push([`ordinary copy size=${size} count=${count} start=${start} overlap=${overlap}`,p]);
}
for(const size of [1,4]) {
    const p=[0xFC,0xBE,...u32(DATA),0xBF,...u32(0x101100),0xB9,...u32(512),0xF3,0xA4,
        0xBE,...u32(0x101100),0xBF,...u32(0x801101),0xB9,...u32(64)];
    p.push(...(size === 1 ? [0x8A,0x06,0x88,0x07,0x46,0x47,0x49,0x75,0xF7] :
        [0x8B,0x06,0x89,0x07,0x83,0xC6,4,0x83,0xC7,4,0x49,0x75,0xF3]));
    p.push(0xBE,...u32(0x101100),0xBF,...u32(OUT),0xB9,...u32(512),0xF3,0xA4);
    programs.push([`ordinary copy physical alias size=${size}`,p]);
}
for(const start of [0, 1, 3968, 4092, 4093, 4095, 4096]) for(const immediate of [false, true]) {
    const p = [0xBE,...u32(OUT+start),0xB8,...u32(0x12345678)];
    for(let i=0;i<24;i++) {
        const size = [1,2,4][i%3];
        p.push(...(size === 2 ? [0x66] : []), immediate ? size === 1 ? 0xC6 : 0xC7 : size === 1 ? 0x88 : 0x89,
            0x46, i*4, ...(immediate ? size === 1 ? [i] : size === 2 ? [i,0xAB] : u32(0xABCDEF00+i) : []));
    }
    programs.push([`RAM writes start=${start} immediate=${immediate}`,p]);
}
for(const gap of [[0x46], [0x66,0xBE,0xFC,0x0F], [0x8B,0x06], [0xFF,0x06]]) {
    const p=[0xBE,...u32(OUT),0xB8,...u32(0x12345678),0x89,0x06,0x89,0x46,4,...gap,0x89,0x46,8,0x89,0x46,12];
    programs.push([`RAM write barrier ${gap}`,p]);
}
for(const size of [2, 4]) for(const backward of [false, true])
for(const start of [512, 513, 4092, 4093, 4095, 4096])
for(const count of [0, 1, 3, 7, 8, 17, 64]) for(const value of [0, 0xFFFFFFFF, 0x12345678, 0xAAAA5555]) {
    const p = [0xB8, ...u32(value), 0xB9, ...u32(count), 0xBF, ...u32(OUT + start),
        backward ? 0xFD : 0xFC, 0xF9, 0xF3, ...(size === 2 ? [0x66] : []), 0xAB,
        0x89, 0x0D, ...u32(OUT + 8000), 0x89, 0x3D, ...u32(OUT + 8004),
        0x9C, 0x5A, 0x89, 0x15, ...u32(OUT + 8008), 0xFC];
    const name=`memory fill size=${size} backward=${backward} start=${start} count=${count} value=${value}`;
    programs.push([name,p]);
    oracles.set(name,result => {
        const expected=new Uint8Array(8000);
        for(let i=0;i<count;i++) for(let j=0;j<size;j++)
            expected[start+(backward ? -i : i)*size+j]=value >>> (j*8)&255;
        assert.deepEqual(result.slice(0,8000),expected,name+" independent fill bytes");
        const view=new DataView(result.buffer,result.byteOffset,result.byteLength);
        assert.equal(view.getUint32(8000,true),0,name+" final count");
        assert.equal(view.getUint32(8004,true),OUT+start+(backward ? -count : count)*size,name+" final EDI");
        assert.equal(view.getUint32(8008,true)&0x401,(backward ? 0x400 : 0)|1,name+" CF/DF preserved");
    });
}
for(const start of [0, 1, 4080, 4093, 4095]) {
    for(const indexed of [false, true]) {
        const p = [0xBE, ...u32(DATA + start), 0xBF, ...u32(0)];
        for(let r = 0; r < 4; r++) p.push(0x8B,
            (indexed ? 0x84 : 0x86) | r << 3, ...(indexed ? [0xBE] : []), ...u32(r * 4));
        for(let r = 0; r < 4; r++) p.push(0x89, 5 | r << 3, ...u32(OUT + r * 4));
        programs.push([`relative RAM reads offset=${start} indexed=${indexed}`, p]);
    }
    const p = [0xBE, ...u32(DATA + start), 0xB9, ...u32(0xFEDC0000),
        0x0F, 0xBE, 0x06, // movsx eax,byte [esi]
        0x0F, 0xBF, 0x5E, 1, // movsx ebx,word [esi+1]
        0x66, 0x8B, 0x4E, 3, // mov cx,[esi+3]
        0x0F, 0xB7, 0x56, 5, // movzx edx,word [esi+5]
        0x8A, 0x66, 7]; // mov ah,[esi+7]
    for(let r = 0; r < 4; r++) p.push(0x89, 5 | r << 3, ...u32(OUT + r * 4));
    programs.push([`mixed-width RAM reads offset=${start}`, p]);
}
for(const gap of [4, 4096]) {
    const p = [0xBE, ...u32(DATA), 0x8B, 0x06, 0x8B, 0x9E, ...u32(gap),
        0xC7, 0x06, ...u32(0x12345678), // store must end the cache region
        0x8B, 0x0E, 0x8B, 0x56, 4];
    for(let r = 0; r < 4; r++) p.push(0x89, 5 | r << 3, ...u32(OUT + r * 4));
    programs.push([`RAM cache store barrier gap=${gap}`, p]);
}
{
    const p = [0xC7, 0x05, ...u32(DATA), ...u32(DATA + 4096),
        0xBE, ...u32(DATA), 0x8B, 0x36, 0x8B, 0x06, 0x8B, 0x5E, 4,
        0xA3, ...u32(OUT), 0x89, 0x1D, ...u32(OUT + 4)];
    programs.push(["RAM read changes base register/page", p]);
}
{
    const p = [0xB8, ...u32(DATA + 1), 0x8A, 0x00, // mov al,[eax] changes the base
        0x8B, 0x58, 4, 0x8B, 0x48, 8,
        0x89, 0x1D, ...u32(OUT), 0x89, 0x0D, ...u32(OUT + 4)];
    programs.push(["RAM read overwrites partial base register", p]);
}
for(const start of [0, 1, 4080, 4093, 4095]) {
    const p = [];
    for(let r = 0; r < 4; r++) p.push(0x8B, 5 | r << 3, ...u32(DATA + start + r * 4));
    for(let r = 0; r < 4; r++) p.push(0x89, 5 | r << 3, ...u32(OUT + r * 4));
    // A write ends the translation region and must be visible on the next read.
    p.push(0xA1, ...u32(DATA), 0xC7, 0x05, ...u32(DATA + 4), ...u32(0xABCD1234), 0xA1, ...u32(DATA + 4), 0xA3, ...u32(OUT + 16));
    programs.push([`RAM translation, offset ${start}`, p]);
}
for(const first of [[0x05, ...u32(1)], [0x2D, ...u32(1)], [0x3D, ...u32(1)],
    [0x83, 0xC0, 1], [0x83, 0xE8, 1], [0x83, 0xF8, 1], [0x21, 0xD8], [0x09, 0xD8], [0x31, 0xD8], [0x85, 0xD8]]) {
    for(const barrier of [[], [0xB9,...u32(7),0x89,0xDA,0x90], [0x9C,0x59], [0x83,0xD0,0], [0x40], [0xD3,0xE0]]) {
        const p = [0xB8,...u32(0xFFFFFFFF),0xBB,...u32(1),0xB9,...u32(0),0xBA,...u32(0),
            ...first,...barrier,0x29,0xD8,0xA3,...u32(OUT),0x89,0x0D,...u32(OUT+4),0x9C,0x58,0xA3,...u32(OUT+8)];
        programs.push([`flags opcode=${first} barrier=${barrier}`,p]);
    }
}
for(const width of [1, 2, 4]) for(const backward of [false, true]) for(const distance of [1, 2, 3, 16, 127]) {
    const source = 0x220000 + (backward ? 4200 : 4000);
    const dest = source + (backward ? -distance : distance);
    const p = [0xFC, 0xBE, ...u32(DATA), 0xBF, ...u32(0x220000), 0xB9, ...u32(8192), 0xF3, 0xA4,
        backward ? 0xFD : 0xFC, 0xBE, ...u32(source), 0xBF, ...u32(dest), 0xB9, ...u32(64),
        ...(width === 2 ? [0x66] : []), 0xF3, width === 1 ? 0xA4 : 0xA5,
        0x89, 0x0D, ...u32(OUT + 8000), 0x89, 0x35, ...u32(OUT + 8004), 0x89, 0x3D, ...u32(OUT + 8008),
        0xFC, 0xBE, ...u32(0x220000 + 3600), 0xBF, ...u32(OUT), 0xB9, ...u32(1024), 0xF3, 0xA4];
    programs.push([`ordered REP width=${width} backward=${backward} distance=${distance}`, p]);
}
for(const producer of [[0x39,0xD8],[0x85,0xD8],[0x30,0xD8],[0x00,0xF8],[0x28,0xFC],
    [0x66,0x39,0xD8],[0x66,0x85,0xD8],[0x80,0xFC,0x80],[0xF6,0xC4,0x80]])
for(const branch of [false,true]) for(const value of [0,0x80000080,0x7FFFFF7F]) {
    const p=[0xB8,...u32(value),0xBB,...u32(0xFF),0xBE,...u32(DATA)];
    for(let i=0;i<16;i++) {
        p.push(...producer,...(branch?[0xEB,0]:[]),0x8B,0x56,i*4,
            0x9C,0x59,0x89,0x0D,...u32(OUT+i*8),0xA3,...u32(OUT+i*8+4));
    }
    programs.push([`expanded flags ${producer} branch=${branch} value=${value}`,p]);
}
for(const offset of [0,1,2,4000,4093,4095]) for(const count of [2,16,40]) {
    const p=[0x89,0xE7,0xBC,...u32(DATA+4096+offset),0xB8,...u32(0x87654321)];
    for(let i=0;i<count;i++) p.push(0x50,0x8D,0x40,1);
    for(let i=0;i<count;i++) p.push(0x58,0xA3,...u32(OUT+i*4));
    p.push(0x89,0xFC);
    programs.push([`stack cache offset=${offset} count=${count}`,p]);
}
for(const opcode of [0x00,0x01,0x09,0x21,0x29,0x31,0xFE,0xFF])
for(const offset of [0,1,3968,4093,4095]) {
    const p=[0xBE,...u32(DATA+offset),0xB8,...u32(0x87654321)];
    // Initialize in the guest so repetitions remain deterministic.
    for(let i=0;i<32;i++) p.push(0xC7,0x46,i*4,...u32(i*0x1234567));
    for(let i=0;i<32;i++) p.push(opcode,0x46,i*4);
    p.push(0x9C,0x58,0xA3,...u32(OUT+256));
    for(let i=0;i<32;i++) p.push(0x8B,0x46,i*4,0xA3,...u32(OUT+i*4));
    programs.push([`rmw cache opcode=${opcode} offset=${offset}`,p]);
}
for(const padding of [0,3,17]) for(const near of [false,true]) {
    const p=[0xB8,...u32(0x7FFFFFFF),0xBB,...u32(1)];
    for(let i=0;i<8;i++) {
        p.push(0x01,0xD8,...(near?[0xE9,...u32(padding)]:[0xEB,padding]));
        for(let j=0;j<padding;j++) p.push(0xF4); // skipped bytes must never execute
        p.push(0x89,0xC2,0x9C,0x59,0x89,0x0D,...u32(OUT+i*4));
    }
    // CALL next / POP is an instruction-pointer idiom, not a removable JMP.
    p.push(0xE8,0,0,0,0,0x58,0xA3,...u32(OUT+128));
    programs.push([`linear region near=${near} padding=${padding}`,p]);
}
// Two instruction streams can overlap inside a MOV immediate and converge at
// the same indirect JMP. The target cache must own one set of locals per site.
for(const taken of [false, true]) for(const offset of [1, 2, 3, 4]) {
    const p = [0xBA, ...u32(CODE + 19), 0x31, 0xC0,
        0x83, 0xF8, taken ? 1 : 0, 0x75, offset,
        0xB8, 0x90, 0x90, 0x90, 0x90, 0xFF, 0xE2,
        0xA3, ...u32(OUT)];
    const name = `overlapping indirect site taken=${taken} offset=${offset}`;
    programs.push([name, p]);
    oracles.set(name, result => assert.equal(new DataView(result.buffer).getUint32(0, true),
        taken ? 0 : 0x90909090, name));
}
try {
    for(const [label, wasm_path, options] of [
        [process.argv[2] ? baseline : "interpreter", baseline, process.argv[2] ? {} : { disable_jit: true }],
        ...COMPILED_ARMS.map(arm => [arm.label, candidate, arm.options])]) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        machines.push(vm); labels.push(label);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
        // SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
        vm.v86.cpu.cr[4] |= 0x600;
    }
    const selected = programs.filter(([name]) => !process.env.SEQUENCE_FILTER || (process.env.SEQUENCE_FILTER === "nonfloating" ? !name.startsWith("floating") : name.includes(process.env.SEQUENCE_FILTER)));
    for(const [name, body] of selected) {
        // Loop until 0x604 is set, then halt at the end of an iteration: a VM
        // stopped at an arbitrary point (the page tier's exits differ from the
        // loop head) can hold a partially rewritten OUT.
        const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
        p.push(0xE9, ...u32(-p.length - 5), 0xF4);
        const results = [];
        for(const [i, vm] of machines.entries()) {
            const cpu = vm.v86.cpu, e = cpu.wm.exports;
            // Programs reuse CODE: start each from an empty compiler state
            // (compiled code needs more heat to recompile a page after each rewrite).
            cpu.jit_clear_cache();
            vm.write_memory(data, DATA);
            vm.write_memory(new Uint8Array(8192), OUT);
            vm.write_memory(new Uint8Array(8), 0x600);
            vm.write_memory(Uint8Array.from(p), CODE);
            cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
            const start = compiled_activations(e);
            vm.run();
            const deadline = performance.now() + 10000;
            while(word(vm, 0x600) !== 0xCAFE || (i > 0 || process.argv[2]) && compiled_activations(e) === start) {
                assert(performance.now() < deadline, `${labels[i]}: ${name}`); await sleep(1);
            }
            await sleep(20); await vm.stop();
            vm.write_memory(Uint8Array.of(1), 0x604);
            vm.run();
            while(!cpu.in_hlt[0]) { assert(performance.now() < deadline, `${labels[i]}: ${name} halt`); await sleep(1); }
            await vm.stop();
            const result=Uint8Array.from(vm.read_memory(OUT,8192));
            if(oracles.has(name)) oracles.get(name)(result);
            results.push(result);
        }
        for(let i = 1; i < machines.length; i++) assert.deepEqual(results[i], results[0], `${labels[i]}: ${name}`);
    }
    console.log(`PASS: ${selected.length} actual sequences on the page tier, aliases, MMX/x87 transitions and RAM boundaries`);
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/rust/cpu_worker.asm                                                                0000644 0000000 0000000 00000001130 00000000000 014700  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       bits 16
org 0
    cli
    lgdt [cs:gdtr]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:0xF0000 + protected
bits 32
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov fs, ax
    mov gs, ax
    mov esp, 0x8000
    mov dword [0x500], 0xCAFE
.loop:
    inc dword [0x504]
    mov eax, [0x600]
    test eax, eax
    jz .loop
    call eax
    mov dword [0x600], 0
    jmp .loop
align 8
gdt: dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr: dw 23
      dd 0xF0000 + gdt
times 0xFFF0 - ($ - $$) db 0xF4
bits 16
    jmp 0xF000:0
times 0x10000 - ($ - $$) db 0xF4
                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/rust/cvtpi2ps_x87.mjs                                                              0000644 0000000 0000000 00000012711 00000000000 015020  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // CVTPI2PS and CVTPI2PD leave the x87 for MMX (TOP 0, every tag valid) only
// when their source is an MMX register; from memory the x87 stack stays as it
// was. Need for Speed: Most Wanted's mixer runs x87 code right after
// CVTPI2PS xmm, m64: with the transition every load overflowed into the
// indefinite NaN, which reached the reverb's feedback and silenced each race.
// In the interpreter, then hot under the page tier.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x300000;
const read32 = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const FSW_IE = 1, FSW_SF = 1 << 6;

const fninit = [0xDB, 0xE3], fld1 = [0xD9, 0xE8], faddp = [0xDE, 0xC1], emms = [0x0F, 0x77];
const fstp_m32 = a => [0xD9, 0x1D, ...u32(a)];
const fnstsw_to = a => [0xDF, 0xE0, 0xA3, ...u32(a)];
const movdqu_store = (r, a) => [0xF3, 0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
// (SSE: CLTS, CR4.OSFXSR and OSXMMEXCPT)
const PROLOGUE = [0x0F, 0x06, 0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0];
const program = prefix => [
    ...PROLOGUE,
    // from memory: 1 + 1 on the x87 around it, no stack fault
    ...fninit, ...fld1,
    ...prefix, 0x0F, 0x2A, 0x05, ...u32(DATA),
    ...fld1, ...faddp, ...fstp_m32(OUT), ...fnstsw_to(OUT + 4), ...movdqu_store(0, OUT + 16),
    // from MM0: the transition, so that the next load overflows
    ...fninit, 0x0F, 0x6F, 0x05, ...u32(DATA), ...emms, ...fld1,
    ...prefix, 0x0F, 0x2A, 0xC8,
    ...fld1, ...fstp_m32(OUT + 8), ...fnstsw_to(OUT + 12),
    ...fninit, ...emms,
];
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}

async function run(vm, code, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    else e["x64_page_steps_freeze"]();
    vm.write_memory(Uint8Array.from(code), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 60000;
    while(read32(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    if(warm)
    {
        await sleep(20);
        vm.write_memory(Uint8Array.of(1), 0x604);
        while(!cpu.in_hlt[0])
        {
            assert(performance.now() < deadline, "program end timeout");
            await sleep(1);
        }
    }
    await vm.stop();
}

const machines = [];
try
{
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 64 << 20,
            ...arm, disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
        machines.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(read32(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    for(const [name, prefix] of [["cvtpi2ps", []], ["cvtpi2pd", [0x66]]])
    {
        const code = loop(program(prefix));
        for(const [m, vm] of machines.entries())
        {
            for(const warm of [true, false])
            {
                const run_name = `${name}, machine ${m} ${warm ? "hot" : "one round"}`;
                vm.write_memory(Uint8Array.from([...u32(1), ...u32(-2)]), DATA);
                vm.write_memory(new Uint8Array(32), OUT);
                await run(vm, code, warm, m === 0);
                assert.equal(read32(vm, OUT), 0x40000000, run_name + ": from memory, 1 + 1 on the x87 is 2");
                assert.equal(read32(vm, OUT + 4) & (FSW_SF | FSW_IE), 0, run_name + ": from memory, no stack fault");
                const converted = name === "cvtpi2ps" ? [0x3F800000, 0xC0000000] : [0, 0x3FF00000, 0, 0xC0000000];
                converted.forEach((v, i) => assert.equal(read32(vm, OUT + 16 + 4 * i), v, run_name + ": the conversion"));
                // (the indefinite NaN; its sign as FST m32 stores it is the host's, a separate matter)
                const stored = read32(vm, OUT + 8);
                assert.ok((stored & 0x7FC00000) === 0x7FC00000, run_name + ": from MM0, the next load overflows into a NaN: " + stored.toString(16));
                assert.equal(read32(vm, OUT + 12) & (FSW_SF | FSW_IE), FSW_SF | FSW_IE, run_name + ": from MM0, a stack fault");
            }
        }
        console.log(`PASS: ${name} from memory leaves the x87 stack, from MM0 enters MMX`);
    }
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                       source/v64/tests/rust/decode_rules.mjs                                                              0000644 0000000 0000000 00000030415 00000000000 015176  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Decode rules shared by the 32-bit interpreter and the page tier
// (docs/simd-xsave-plan.md 5.2): which row the 66/F2/F3 prefixes select
// (decode_rules::mandatory_variant), the order of repeated F2/F3, #UD for a
// mandatory prefix without a row of its own, the three-byte maps and VEX.
// Each case runs in the interpreter, then hot under the page tier.
// (tests/decode/vex_modes.mjs: C4/C5 by mode.)
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x210000;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000;
const machines = [];
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const load = (r, a) => [0xF3, 0x0F, 0x6F, 5 | r << 3, ...u32(a)];
const store = (r, a) => [0xF3, 0x0F, 0x7F, 5 | r << 3, ...u32(a)];

// (machines[0] of a set is the interpreter: it compiles nothing)
async function run(vm, program, warm = true, interpreter = vm === machines[0])
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
// SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
const ENABLE_SSE = [0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0];
// the body repeats until byte 0x604 is set, then halts after one more round
function loop(body)
{
    const p = [...ENABLE_SSE, ...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** Runs `program` on each machine of `set`, hot, then once more cold (the
 * cold run is mostly interpreted: the program was rewritten);
 * `verify(vm, run)` checks after each run */
async function run_all(program, before = () => {}, set = machines, verify = () => {})
{
    for(const [i, vm] of set.entries())
    {
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, program, warm, vm === set[0]);
            verify(vm, `machine ${i} ${warm ? "hot" : "one round"}`);
        }
    }
}
/** The interpreter, then the page tier, with `options` */
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/** Each form raises #UD at its first byte (the handler skips the form) */
async function expect_undefined(forms, set = machines)
{
    for(const form of forms)
    {
        const h = [0x8B, 0x44, 0x24, 0, 0xA3, ...u32(OUT), 0x83, 0x44, 0x24, 0, form.length, 0xCF];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0xB8, ...u32(DATA)];
        const fault_eip = CODE + ENABLE_SSE.length + prologue.length;
        await run_all(loop([...prologue, ...form]), vm => {
            vm.write_memory(Uint8Array.from([HANDLER & 255, HANDLER >>> 8 & 255, 8, 0, 0, 0x8E, HANDLER >>> 16 & 255, HANDLER >>> 24]), IDT + 6 * 8);
            vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
            vm.write_memory(Uint8Array.from(h), HANDLER);
            vm.write_memory(new Uint8Array(4), OUT);
        }, set, (vm, run) => assert.equal(word(vm, OUT), fault_eip, `${form.map(b => b.toString(16)).join(" ")} (${run}): #UD at the first byte`));
    }
}

try
{
    machines.push(...await create_machines());

    // 66 with F2/F3 is an operand-size prefix; of F2 and F3 the last counts.
    // MOVSS/MOVSD between registers replace the low 32/64 bits only.
    const data = new Uint8Array(64);
    for(let i = 0; i < data.length; i++) data[i] = i * 29 + 7 & 255;
    const moves = [
        [[], 16], [[0x66], 16], [[0x66, 0xF3], 4], [[0xF3, 0x66], 4], [[0x66, 0xF2], 8], [[0xF2, 0x66], 8],
        [[0xF2, 0xF3], 4], [[0xF3, 0xF2], 8], [[0xF2, 0xF3, 0x66], 4], [[0x66, 0xF3, 0xF2], 8],
    ];
    const p = [];
    for(const [n, [prefixes]] of moves.entries())
    {
        p.push(...load(0, DATA), ...load(1, DATA + 16), ...prefixes, 0x0F, 0x10, 0xC1, ...store(0, OUT + n * 16));
    }
    await run_all(loop(p), vm => vm.write_memory(data, DATA), machines, (vm, run) => {
        const bytes = Uint8Array.from(vm.read_memory(OUT, moves.length * 16));
        for(const [n, [prefixes, low]] of moves.entries())
        {
            const expected = data.slice(0, 16);
            expected.set(data.slice(16, 16 + low));
            assert.deepEqual(bytes.slice(n * 16, n * 16 + 16), expected, `0F 10 with ${prefixes.map(b => b.toString(16)).join(" ")} (${run})`);
        }
    });
    console.log(`PASS: ${moves.length} 0F 10 prefix orders select MOVUPS/MOVUPD/MOVSS/MOVSD as iced-x86 does, on ${machines.length} arms`);

    // REPE/REPNE CMPSB: the last of F2/F3 decides
    const strings = new Uint8Array(64);
    strings.set([5, 5, 5, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 0);
    strings.set([5, 5, 5, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], 32);
    const reps = [[[0xF3], 12, 4], [[0xF2], 15, 1], [[0xF2, 0xF3], 12, 4], [[0xF3, 0xF2], 15, 1]];
    const q = [0xFC];
    for(const [n, [prefixes]] of reps.entries())
    {
        q.push(0xBE, ...u32(DATA), 0xBF, ...u32(DATA + 32), 0xB9, ...u32(16), ...prefixes, 0xA6,
            0x89, 0x0D, ...u32(OUT + n * 8), 0x89, 0x35, ...u32(OUT + n * 8 + 4));
    }
    await run_all(loop(q), vm => vm.write_memory(strings, DATA), machines, (vm, run) => {
        for(const [n, [prefixes, ecx, advanced]] of reps.entries())
        {
            assert.equal(word(vm, OUT + n * 8), ecx, `CMPSB with ${prefixes} ECX (${run})`);
            assert.equal(word(vm, OUT + n * 8 + 4), DATA + advanced, `CMPSB with ${prefixes} ESI (${run})`);
        }
    });
    console.log(`PASS: ${reps.length} REPE/REPNE CMPSB prefix orders`);

    // A mandatory prefix without a row of its own is #UD at the first prefix
    // byte; outside the SSE maps F2/F3 are ignored repeat prefixes.
    const undefined_forms = [
        [0xF3, 0x0F, 0x2B, 0x00], [0xF2, 0x0F, 0x2B, 0x00], // MOVNTPS (F3: AMD's MOVNTSS)
        [0x66, 0x0F, 0xC3, 0x00], [0xF3, 0x0F, 0xC3, 0x00], // MOVNTI
        [0xF2, 0x0F, 0x77], [0x66, 0x0F, 0x77],             // EMMS
        [0x66, 0x0F, 0xAE, 0x00], [0xF2, 0x0F, 0xAE, 0x00], // FXSAVE
    ];
    await expect_undefined(undefined_forms);
    // IMUL r32, r/m32 with F3: a repeat prefix, ignored
    await run_all(loop([0xB8, ...u32(7), 0xB9, ...u32(6), 0xF3, 0x0F, 0xAF, 0xC1, 0xA3, ...u32(OUT)]), undefined, machines,
        (vm, run) => assert.equal(word(vm, OUT), 42, `F3 IMUL (${run})`));
    console.log(`PASS: ${undefined_forms.length} undefined mandatory prefixes raise #UD, F3 IMUL ignores the prefix`);

    // The three-byte maps decode in the interpreter and the page tier. SSSE3
    // (P3) and SSE4 (P4b) are #UD without their feature; every other encoding
    // is #UD until its semantics come (docs/simd-xsave-plan.md), whether or
    // not the machine has its CPUID feature; so are F2/F3 at the SSSE3
    // opcodes, F3 at CRC32's and an opcode byte without rows
    const featured_forms = [
        [0x66, 0x0F, 0x38, 0x00, 0xC1], [0x0F, 0x38, 0x00, 0xC1],                  // pshufb
        [0x66, 0x0F, 0x3A, 0x0F, 0xC1, 0x08], [0x0F, 0x3A, 0x0F, 0xC1, 0x08],      // palignr
        [0x66, 0x0F, 0x3A, 0x62, 0x00, 0x04], [0x66, 0x0F, 0x3A, 0x63, 0xC1, 0x0C], // pcmpistrm, pcmpistri
        [0xF2, 0x0F, 0x38, 0xF1, 0xC1], [0x66, 0xF2, 0x0F, 0x38, 0xF1, 0xC1],      // crc32
    ];
    await expect_undefined(featured_forms);
    const three_byte = [
        [0xF3, 0x0F, 0x38, 0x00, 0xC1], [0x66, 0xF2, 0x0F, 0x3A, 0x0F, 0xC1, 0x08], // pshufb, palignr
        [0x0F, 0x38, 0xF0, 0x00], [0xF3, 0x0F, 0x38, 0xF0, 0x00],                  // movbe, F3 at crc32
        [0x0F, 0x38, 0x10, 0xC1], [0x0F, 0x38, 0xFF, 0xC1], [0x0F, 0x3A, 0xFF, 0xC1, 0x00], // no row
    ];
    await expect_undefined(three_byte);

    // VEX (C4/C5 with a register ModRM byte in protected mode): #UD without
    // the features, and with them the AVX forms while the AVX state is off
    // (CR4.OSXSAVE, as here; tests/rust/avx.mjs), but ANDN (BMI1, P10: no AVX
    // state, tests/rust/bmi.mjs); so are 66/F2/F3/LOCK before VEX, VEX.vvvv
    // other than 1111b where it is no operand, the reserved maps and opcodes
    // without rows
    const vex = [
        [0xC5, 0xF8, 0x77], [0xC4, 0xE1, 0x7C, 0x77],                 // vzeroupper, vzeroall
        [0xC4, 0xE2, 0x79, 0x18, 0x00], [0xC4, 0xE2, 0x78, 0xF2, 0xC1], // vbroadcastss xmm0, [eax]; andn
        [0xC4, 0xE3, 0x79, 0x4A, 0xC1, 0x20], [0xC4, 0xE2, 0x61, 0x90, 0x14, 0x88], // vblendvps, vpgatherdd
        [0xC5, 0xF0, 0x77], [0x66, 0xC5, 0xF8, 0x77], [0xF3, 0xC5, 0xF8, 0x77], [0xF0, 0xC5, 0xF8, 0x77],
        [0xC4, 0xE0, 0x78, 0x77], [0xC5, 0xF8, 0x00],
    ];
    await expect_undefined(vex);
    // ... and with a memory ModRM byte, LES and LDS
    const far = [0x8C, 0x1D, ...u32(DATA + 4), 0xC7, 0x05, ...u32(DATA), ...u32(0x12345678),
        0xC4, 0x1D, ...u32(DATA), 0x89, 0x1D, ...u32(OUT), 0x8C, 0x05, ...u32(OUT + 4),
        0xC5, 0x0D, ...u32(DATA), 0x89, 0x0D, ...u32(OUT + 8), 0x1E, 0x07];
    await run_all(loop(far), undefined, machines, (vm, run) => {
        assert.equal(word(vm, OUT), 0x12345678, `LES (${run})`);
        assert.equal(word(vm, OUT + 4) & 0xFFFF, word(vm, DATA + 4) & 0xFFFF, `LES: ES (${run})`);
        assert.equal(word(vm, OUT + 8), 0x12345678, `LDS (${run})`);
    });
    // TZCNT and LZCNT without their features: BSF and BSR
    const bit_scans = loop([0xB9, ...u32(0x810000), 0xF3, 0x0F, 0xBC, 0xC1, 0xA3, ...u32(OUT), 0xF3, 0x0F, 0xBD, 0xC1, 0xA3, ...u32(OUT + 4)]);
    await run_all(bit_scans, undefined, machines,
        (vm, run) => assert.deepEqual([word(vm, OUT), word(vm, OUT + 4)], [16, 23], `F3 BSF, F3 BSR (${run})`));

    // With the features (P10): TZCNT and LZCNT; MOVBE and ANDN run
    // (tests/rust/bmi.mjs), the other forms stay #UD
    const featured = await create_machines({ cpu_type: "x86_64", cpu_features: "x86-64-v3", cpu_features_unreleased: true });
    try
    {
        const runs = [[0x0F, 0x38, 0xF0, 0x00], [0xC4, 0xE2, 0x78, 0xF2, 0xC1]].map(form => form.join());
        await expect_undefined([...three_byte, ...vex].filter(form => !runs.includes(form.join())), featured);
        await run_all(bit_scans, undefined, featured,
            (vm, run) => assert.deepEqual([word(vm, OUT), word(vm, OUT + 4)], [16, 8], `TZCNT, LZCNT (${run})`));
    }
    finally
    {
        for(const vm of featured) await vm.destroy();
    }
    console.log(`PASS: ${featured_forms.length} SSSE3 and SSE4.2 encodings raise #UD without their features; ${three_byte.length} three-byte map and ${vex.length} VEX encodings without their features, all but MOVBE and ANDN also with them; ` +
        "LES/LDS with a memory operand; F3 0F BC/BD are BSF/BSR without BMI1/LZCNT and TZCNT/LZCNT with them");
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                   source/v64/tests/rust/flags_provenance.mjs                                                          0000644 0000000 0000000 00000022137 00000000000 016057  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Compare flag-neutral instruction chains against the interpreter. Each
// consumer gets a fresh producer, so all 16 conditions exercise provenance.
// The page tier runs every program.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const wasm_path = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const CODE = 0x100000, OUT = 0x210000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const producers = [
    ["cmp32", [0x39, 0xD8]], ["cmp32-zero", [0x83, 0xF8, 0]],
    ["cmp32-imm", [0x83, 0xF8, 0xFF]], ["cmp16", [0x66, 0x39, 0xD8]],
    ["cmp8", [0x38, 0xD8]], ["cmp-high8", [0x38, 0xFC]],
    ["add32", [0x01, 0xD8]], ["sub32", [0x29, 0xD8]],
    ["sub8", [0x28, 0xD8]], ["sub-high8", [0x28, 0xFC]],
    ["adc32", [0x11, 0xD8]], ["sbb32", [0x19, 0xD8]],
    ["inc32", [0x40]], ["dec32", [0x48]],
    ["inc16", [0x66, 0x40]], ["dec16", [0x66, 0x48]],
    ["test32", [0x85, 0xD8]], ["test16", [0x66, 0x85, 0xD8]],
    ["test8", [0x84, 0xD8]], ["xor32", [0x31, 0xD8]],
    ["shl32", [0xD1, 0xE0]], ["shr32", [0xD1, 0xE8]],
    ["sar32", [0xD1, 0xF8]], ["add32-alias", [0x01, 0xC0]],
];
const neutral = [
    ["nop", [0x90, 0x90]],
    ["mov-unrelated", [0x89, 0xD1, 0xB9, ...u32(7)]],
    ["mov-dest", [0x89, 0xD0]], ["mov-source", [0x8B, 0xDA]],
    ["mov-both", [0x89, 0xD0, 0x89, 0xD3]],
    ["mov-low8", [0xB0, 0x42]], ["mov-high8", [0xB4, 0x42]],
    ["mov-source-high8", [0xB7, 0x42]],
    ["mov8-reg", [0x88, 0xD4, 0x8A, 0xDA]],
    ["mov16", [0x66, 0x89, 0xD0, 0x66, 0x8B, 0xDA]],
    ["mov16-imm", [0x66, 0xB8, 0x12, 0x34]],
    ["mov-c6-c7", [0xC6, 0xC4, 0x42, 0xC7, 0xC3, ...u32(77)]],
    ["mov16-c7", [0x66, 0xC7, 0xC0, 0x12, 0x34]],
    ["lea-unrelated", [0x8D, 0x4C, 0x42, 7]],
    ["lea-dest", [0x8D, 0x40, 7]],
    ["lea16", [0x66, 0x8D, 0x40, 7]],
    ["lea-address16", [0x67, 0x8D, 0x40, 7]],
    ["movzx8", [0x0F, 0xB6, 0xC4]], ["movsx8", [0x0F, 0xBE, 0xC4]],
    ["movzx16", [0x0F, 0xB7, 0xC3]], ["movsx16", [0x0F, 0xBF, 0xD8]],
    ["movzx8-to16", [0x66, 0x0F, 0xB6, 0xC4]],
    ["movsx8-to16", [0x66, 0x0F, 0xBE, 0xDC]],
    ["movx16-to16", [0x66, 0x0F, 0xB7, 0xC3, 0x66, 0x0F, 0xBF, 0xD8]],
    ["xchg-eax", [0x93]], ["xchg16-eax", [0x66, 0x93]],
    ["xchg-reg", [0x87, 0xD8]], ["xchg16-reg", [0x66, 0x87, 0xD8]],
    ["bswap", [0x0F, 0xC8, 0x0F, 0xCB]],
    // Barriers must discard provenance even though earlier MOVs retain it.
    ["helper-barrier", [0x90, 0xD1, 0xC0]], // ROL changes CF/OF
    ["carry-barrier", [0x90, 0xF8]],
    ["flags-barrier", [0x90, 0x9C, 0x5A, 0x80, 0xF2, 1, 0x52, 0x9D]],
    ["memory-barrier", [0x90, 0xA3, ...u32(0x200000), 0x8B, 0x1D, ...u32(0x200000)]],
];
const inputs = [[0, 0], [0x80000000, 1], [0x7FFFFFFF, 0xFFFFFFFF], [0x80017F80, 0x7FFF80FF]];
const machines = [];
let cases = 0, programs = 0;

// Independent integer reference for CMP conditions, including signed overflow
// and parity. This also checks the interpreter rather than trusting it alone.
function cmp_conditions(producer, a, b) {
    if(!producer.startsWith("cmp")) return null;
    let width = 32;
    if(producer === "cmp32-zero") b = 0;
    if(producer === "cmp32-imm") b = 0xFFFFFFFF;
    if(producer === "cmp16") width = 16;
    if(producer === "cmp8" || producer === "cmp-high8") width = 8;
    if(producer === "cmp-high8") { a >>>= 8; b >>>= 8; }
    const mask = width === 32 ? 0xFFFFFFFF : (1 << width) - 1;
    a = (a & mask) >>> 0;
    b = (b & mask) >>> 0;
    const result = ((a - b) & mask) >>> 0;
    const sign = 2 ** (width - 1);
    const cf = a < b, zf = result === 0, sf = (result & sign) !== 0;
    const of = ((a ^ b) & (a ^ result) & sign) !== 0;
    let parity = 0;
    for(let bit = 0; bit < 8; bit++) parity ^= result >>> bit & 1;
    return [of, !of, cf, !cf, zf, !zf, cf || zf, !cf && !zf,
        sf, !sf, parity === 0, parity !== 0, sf !== of, sf === of,
        zf || sf !== of, !zf && sf === of].map(Number);
}

async function execute(vm, program, label) {
    const interpreted = !label;
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    // Every program reuses CODE. Start each from an empty compiler state:
    // compiled code needs more heat to recompile a page after each rewrite.
    cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4096), OUT);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.instruction_pointer[0] = CODE;
    cpu.in_hlt[0] = 0;
    const warm_start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 10000;
    while(word(vm, 0x600) < 2 || !interpreted && compiled_activations(e) === warm_start) {
        assert(performance.now() < deadline, `${label || "interpreter"}: warmup timeout`);
        await sleep(1);
    }
    await vm.stop();
    if(!interpreted) {
        // Replay from the beginning after warming, not from an arbitrary
        // partially executed loop. All output must be written again.
        vm.write_memory(new Uint8Array(4096), OUT);
        vm.write_memory(new Uint8Array(4), 0x600);
        cpu.instruction_pointer[0] = CODE;
        const replay_start = compiled_activations(e);
        vm.run();
        while(word(vm, 0x600) < 2) {
            assert(performance.now() < deadline, `${label}: replay timeout`);
            await sleep(1);
        }
        await vm.stop();
        assert(compiled_activations(e) !== replay_start, `${label}: replay must execute compiled code`);
    }
    return Uint8Array.from(vm.read_memory(OUT, 4096));
}

try {
    for(const options of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)]) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path, bios: { buffer: bios.slice(0) }, ...options,
            memory_size: 32 << 20, disable_keyboard: true, disable_mouse: true,
            disable_speaker: true, net_device: { type: "none" }, autostart: false });
        machines.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) {
            assert(performance.now() < deadline, "boot timeout");
            await sleep(1);
        }
        await vm.stop();
    }
    for(const [producer, op] of producers) for(const [name, moves] of neutral) {
        if(process.env.FLAGS_FILTER && !`${producer}/${name}`.includes(process.env.FLAGS_FILTER)) continue;
        for(const consumer of ["setcc", "cmov", "jcc"]) {
            const p = [];
            let output = OUT;
            for(const [a, b] of inputs) for(let cc = 0; cc < 16; cc++) {
                p.push(0xB8, ...u32(a), 0xBB, ...u32(b), 0xBA, ...u32(0x12345678),
                    0xB9, ...u32(0), 0xBE, ...u32(1), 0xF9, ...op, ...moves);
                if(consumer === "setcc") p.push(0x0F, 0x90 | cc, 0x05, ...u32(output));
                else {
                    // EDI/ESI are not aliases of any neutral operation above.
                    p.push(0xBF, ...u32(0));
                    if(consumer === "cmov") p.push(0x0F, 0x40 | cc, 0xFE); // cmovcc edi,esi
                    else p.push(0x70 | (cc ^ 1), 5, 0xBF, ...u32(1));
                    p.push(0x89, 0x3D, ...u32(output));
                }
                // PUSHFD checks that preserving metadata never drops visible
                // flags; mask undefined AF for logical/shift operations.
                p.push(0x9C, 0x5A, 0x81, 0xE2, ...u32(0x8C5), 0x89, 0x15, ...u32(output + 4));
                output += 8;
            }
            p.push(0xFF, 0x05, ...u32(0x600));
            p.push(0xE9, ...u32(-p.length - 5));
            assert(p.length < 8192, "test must fit within two pages");
            const reference = await execute(machines[0], p);
            for(const [arm, { label }] of COMPILED_ARMS.entries()) {
                const actual = await execute(machines[1 + arm], p, label);
                const mismatch = actual.findIndex((value, i) => value !== reference[i]);
                assert.equal(mismatch, -1, `${label}: ${producer}/${name}/${consumer} byte=${mismatch}: ` +
                    `JIT=${actual[mismatch]}, interpreter=${reference[mismatch]}`);
                if(!name.endsWith("barrier")) for(const [index, [a, b]] of inputs.entries()) {
                    const expected = cmp_conditions(producer, a, b);
                    if(expected) for(let cc = 0; cc < 16; cc++) {
                        assert.equal(actual[(index * 16 + cc) * 8], expected[cc],
                            `${label}: ${producer}/${name}/${consumer} independent condition ${cc}, input ${index}`);
                    }
                }
            }
            cases += inputs.length * 16;
            programs++;
        }
    }
    console.log(`PASS: ${cases} flag/condition cases in ${programs} programs (interpreter vs warmed page tier)`);
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/rust/fma.mjs                                                                       0000644 0000000 0000000 00000043360 00000000000 013307  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // FMA and F16C in the 32-bit engines (docs/simd-xsave-plan.md 9.3, P11)
// against tests/rust/sse_fp_model.mjs (exact rational arithmetic, independent
// of SoftFloat and cpu/simd_fp.rs). Every FMA form (VFMADD, VFMSUB, VFNMADD,
// VFNMSUB 132/213/231 PS/PD/SS/SD; VFMADDSUB, VFMSUBADD 132/213/231 PS/PD;
// VEX.128 and VEX.256) with the destination XMM2/YMM2, also the first
// source, VEX.vvvv XMM1/YMM1 and the third source XMM0/YMM0 or memory; and
// VCVTPH2PS and VCVTPS2PH with every rounding control. Each case sets MXCSR
// (the rounding modes, DAZ, FZ, masked and unmasked exceptions) and checks
// the destination, MXCSR and the fault: #XM, or #UD without CR4.OSXMMEXCPT,
// with the destination unchanged. The values: special ones; NaNs with
// distinct payloads in two or three operands (the first of the operation's
// x, y, z wins); 0 × ∞ with a QNaN addend (no IE), an SNaN one or a number;
// random ones; and products whose rounding error the addend exposes (one
// rounding gives the error, a rounded product added gives 0). Every case
// runs in the interpreter, then hot under the page tier (the region tiers, a
// second compiled arm, were deleted in M11). Without the features, CPUID
// reports neither and the forms #UD.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { MXCSRS } from "./sse_fp_cases.mjs";
import { FMA_FORMS, F16C_FORMS, fma_cases, f16c_cases, fma_expect } from "./fma_cases.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x300000, FAULTS = 0x3F0000, CASE = 0x3FF000, SKIP = 0x3FF004;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
// (the destination's value before: unchanged by a faulting instruction)
const BEFORE = 0x5A5A5A5A_A5A5A5A5_12345678_9ABCDEF0n;
// (a VEX.128 FMA form's destination's bits 255:128 before: zeroed)
const UPPER = 0x0123456789ABCDEF_FEDCBA9876543210n << 128n;
const BEFORE256 = BEFORE | BEFORE << 128n;
const bytes = (v, n) => Uint8Array.from({ length: n }, (_, i) => Number(v >> BigInt(8 * i) & 0xFFn));

const ldmxcsr = a => [0x0F, 0xAE, 0x15, ...u32(a)], stmxcsr = a => [0x0F, 0xAE, 0x1D, ...u32(a)];
// VMOVDQU xmm/ymm loads and stores (VEX.128 zeroes bits 255:128)
const vmovdqu_load = (r, a, l) => [0xC5, 0xFA | l << 2, 0x6F, 0x05 | r << 3, ...u32(a)];
const vmovdqu_store = (r, a, l) => [0xC5, 0xFA | l << 2, 0x7F, 0x05 | r << 3, ...u32(a)];
const OSXSAVE = 1 << 18;
const xsetbv = value => [0xB9, ...u32(0), 0xB8, ...u32(value), 0xBA, ...u32(0), 0x0F, 0x01, 0xD1];

/** The instruction (three-byte VEX): reg, VEX.vvvv, r/m XMM0/YMM0 or [address] */
function vex(map, w, vvvv, l, op, reg, address, imm8)
{
    const modrm = address === undefined ? [0xC0 | reg << 3] : [0x05 | reg << 3, ...u32(address)];
    return [0xC4, 0xE0 | map, w << 7 | (~vvvv & 15) << 3 | l << 2 | 1, op, ...modrm, ...(imm8 === undefined ? [] : [imm8])];
}
/** A form's program and its data: per case 128 bytes of data (a, b, c or
 * the source, MXCSR) and 64 of results (the destination, MXCSR) */
function program(form, memory, list)
{
    const p = [], data = new Uint8Array(list.length * 128);
    list.forEach((c, n) => {
        const base = DATA + n * 128, out = OUT + n * 64, l = form.l;
        p.push(0xC7, 0x05, ...u32(CASE), ...u32(n));
        p.push(...ldmxcsr(base + 96));
        let instruction;
        if(form.op !== undefined)
        {
            // YMM2/XMM2 the destination (a), YMM1/XMM1 VEX.vvvv (b), YMM0/XMM0 or [base + 64] (c)
            p.push(...vmovdqu_load(2, base, 1), ...vmovdqu_load(1, base + 32, 1));
            if(!memory) p.push(...vmovdqu_load(0, base + 64, 1));
            instruction = vex(2, +form.double, 1, l, form.op, 2, memory ? base + 64 : undefined);
            data.set(bytes(l ? c.a : c.a | UPPER, 32), n * 128);
            data.set(bytes(c.b, 32), n * 128 + 32);
            data.set(bytes(c.c, 32), n * 128 + 64);
        }
        else if(form.kind === "ph2ps")
        {
            // YMM2 the destination (BEFORE), XMM0 or [base + 64] the halves
            p.push(...vmovdqu_load(2, base, 1));
            if(!memory) p.push(...vmovdqu_load(0, base + 64, 1));
            instruction = vex(2, 0, 0, l, 0x13, 2, memory ? base + 64 : undefined);
            data.set(bytes(BEFORE256, 32), n * 128);
            data.set(bytes(c.source, 16), n * 128 + 64);
        }
        else
        {
            // YMM2 the singles, YMM0 or [base + 64] the destination (BEFORE)
            p.push(...vmovdqu_load(2, base, 1), ...vmovdqu_load(0, base + 64, 1));
            instruction = vex(3, 0, 0, l, 0x1D, 2, memory ? base + 64 : undefined, c.imm8);
            data.set(bytes(c.source, 32), n * 128);
            data.set(bytes(BEFORE256, 32), n * 128 + 64);
        }
        data.set(u32(c.mxcsr), n * 128 + 96);
        p.push(0xC7, 0x05, ...u32(SKIP), ...u32(instruction.length), ...instruction);
        p.push(...stmxcsr(out + 32));
        // (the destination: YMM2, YMM0 or the memory at base + 64)
        if(form.kind === "ps2ph") p.push(...memory ? [...vmovdqu_load(3, base + 64, 1), ...vmovdqu_store(3, out, 1)] : vmovdqu_store(0, out, 1));
        else p.push(...vmovdqu_store(2, out, 1));
    });
    return { code: p, data };
}

const machines = [];
async function run(vm, code, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    // (the page tier's step counts are the hot run's: x64_page_steps)
    else e["x64_page_steps_freeze"]();
    vm.write_memory(Uint8Array.from(code), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 60000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    // (a hot run goes on a while, then ends at the end of a round)
    if(warm)
    {
        await sleep(20);
        vm.write_memory(Uint8Array.of(1), 0x604);
        while(!cpu.in_hlt[0])
        {
            assert(performance.now() < deadline, "program end timeout");
            await sleep(1);
        }
    }
    await vm.stop();
}
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it for the case, skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58);
    p.push(0xA1, ...u32(CASE), 0xC7, 0x04, 0x85, ...u32(FAULTS), ...u32(vector)); // mov [FAULTS + eax*4], vector
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true], [19, false]];
/** The build has Wasm SIMD */
const simd = vm => vm.v86.cpu.wm.exports["jit_wasm_simd_supported"]() !== 0;
async function create_machines(cpu_features)
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 64 << 20,
            cpu_features, cpu_features_unreleased: true,
            ...arm, disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/** Runs `code` with `data` hot then once more on every machine: per run the
 * results and the faults of `count` cases. */
async function run_all(code, data, count)
{
    const runs = [];
    for(const [m, vm] of machines.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], i) => {
            const h = HANDLER + i * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            vm.write_memory(data, DATA);
            vm.write_memory(new Uint8Array(count * 64), OUT);
            vm.write_memory(new Uint8Array(count * 4), FAULTS);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, code, warm, vm === machines[0]);
            runs.push({ run: `machine ${m} ${warm ? "hot" : "one round"}`, out: Uint8Array.from(vm.read_memory(OUT, count * 64)),
                faults: new DataView(Uint8Array.from(vm.read_memory(FAULTS, count * 4)).buffer) });
        }
    }
    return runs;
}

let total = 0;
try
{
    // Without the features (AVX only): CPUID reports neither, the forms #UD
    machines.push(...await create_machines(["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"]));
    {
        const cr4 = [0x0F, 0x20, 0xE0, 0x0D, ...u32(OSXSAVE | 0x600), 0x0F, 0x22, 0xE0];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0x0F, 0x06, ...cr4, ...xsetbv(7)];
        const forms = [vex(2, 0, 1, 0, 0x98, 2), vex(2, 1, 1, 1, 0xB8, 2), vex(2, 0, 1, 0, 0xB9, 2), vex(2, 0, 0, 0, 0x13, 2), vex(3, 0, 0, 1, 0x1D, 2, undefined, 4)];
        const p = [0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT + 0x100)];
        forms.forEach((f, n) => p.push(0xC7, 0x05, ...u32(CASE), ...u32(n), 0xC7, 0x05, ...u32(SKIP), ...u32(f.length), ...f));
        const runs = await run_all(loop([...prologue, ...p]), new Uint8Array(0), forms.length);
        for(const { run, out, faults } of runs)
        {
            assert.equal(new DataView(out.buffer).getUint32(0x100, true) & (1 << 12 | 1 << 29), 0, `CPUID.1:ECX FMA, F16C (${run})`);
            forms.forEach((_, n) => assert.equal(faults.getUint32(n * 4, true), 6, `form ${n} without its feature (${run}): #UD`));
        }
        for(const vm of machines) await vm.destroy();
        machines.length = 0;
        console.log("PASS: without FMA and F16C, CPUID reports neither and their forms are #UD");
    }

    machines.push(...await create_machines(["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "FMA", "F16C"]));
    for(const xmm_exceptions of [true, false])
    {
        // CR4.OSXSAVE, OSXMMEXCPT (else unmasked exceptions are #UD); XCR0 7; CR0.TS clear
        const cr4 = [0x0F, 0x20, 0xE0, 0x0D, ...u32(OSXSAVE | (xmm_exceptions ? 0x600 : 0x200)), ...(xmm_exceptions ? [] : [0x25, ...u32(~0x400 >>> 0)]), 0x0F, 0x22, 0xE0];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0x0F, 0x06, ...cr4, ...xsetbv(7)];
        const forms = xmm_exceptions ? [...FMA_FORMS, ...F16C_FORMS] : FMA_FORMS.filter(f => f.name.startsWith("vfmadd231"));
        for(const form of forms)
        {
            // (FMA_ONLY=name[,name...]: those forms, for debugging)
            if(process.env.FMA_ONLY && !process.env.FMA_ONLY.split(",").includes(form.name)) continue;
            for(const memory of [false, true])
            {
                const list = form.op !== undefined ? fma_cases(form) : f16c_cases(form);
                const { code, data } = program(form, memory, list);
                const runs = await run_all(loop([...prologue, ...code]), data, list.length);
                for(const { run, out, faults } of runs)
                {
                    const view = new DataView(out.buffer);
                    list.forEach((c, n) => {
                        const operands = form.op !== undefined ? `a ${c.a.toString(16)} b ${c.b.toString(16)} c ${c.c.toString(16)}` : `source ${c.source.toString(16)} imm8 ${c.imm8}`;
                        const label = `${form.name}${memory ? " [mem]" : ""} case ${n} on ${run}: mxcsr ${c.mxcsr.toString(16)} ${operands}`;
                        assert.equal(faults.getUint32(n * 4, true), c.fault ? xmm_exceptions ? 19 : 6 : 0, label + ": fault");
                        assert.equal(view.getUint32(n * 64 + 32, true), c.after, label + ": MXCSR");
                        const actual = [0, 1, 2, 3].reduce((v, q) => v | view.getBigUint64(n * 64 + 8 * q, true) << BigInt(64 * q), 0n);
                        // (VEX.128: bits 255:128 zeroed; VCVTPS2PH to memory: 8 or 16 bytes, the rest as before)
                        let expected;
                        if(c.fault) expected = form.kind === "ph2ps" || form.kind === "ps2ph" ? BEFORE256 : form.l ? c.a : c.a | UPPER;
                        else if(form.kind === "ps2ph")
                        {
                            const written = form.l ? 128n : 64n;
                            expected = memory ? BEFORE256 & ~((1n << written) - 1n) | c.result : c.result;
                        }
                        else expected = c.result;
                        assert.equal(actual.toString(16), expected.toString(16), label + ": result");
                    });
                }
                total += list.length;
            }
        }
        console.log(`PASS: ${xmm_exceptions ? "all forms, unmasked exceptions as #XM" : "unmasked exceptions as #UD without CR4.OSXMMEXCPT"}`);
    }
    console.log(`PASS: ${total} exact FMA and F16C cases (${FMA_FORMS.length} FMA forms, ${F16C_FORMS.length} F16C forms, register and memory sources, ${MXCSRS.length} MXCSR settings) match the model in the interpreter and the page tier`);

    // The page tier's templates (P11 part 2): the VEX.128 and scalar FMA forms on
    // ordinary operands (no faults: a fault retries) run hot without steps
    // (x64_page_steps of C4 E2); the VEX.256 forms step. With PE set, where the
    // host's relaxed multiply-adds fuse (ir_relaxed_fma), natively
    // (native_fp::fused): no calls of the exact helper x64_fma; with them
    // switched off, through it. The same results either way.
    const page = machines[1].v86.cpu.wm.exports;
    const relaxed = page.ir_relaxed_fma() === 1;
    for(const native of relaxed ? [true, false] : [false])
    {
        page.ir_set_relaxed_fma(+native);
        const cr4 = [0x0F, 0x20, 0xE0, 0x0D, ...u32(OSXSAVE | 0x600), 0x0F, 0x22, 0xE0];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0x0F, 0x06, ...cr4, ...xsetbv(7)];
        const f64 = x => { const b = new DataView(new ArrayBuffer(8)); b.setFloat64(0, x, true); return b.getBigUint64(0, true); };
        const f32 = x => { const b = new DataView(new ArrayBuffer(4)); b.setFloat32(0, x, true); return BigInt(b.getUint32(0, true)); };
        let templated = 0, stepped = 0;
        for(const form of FMA_FORMS)
        {
            const width = form.l ? 256 : 128, lanes = width / (form.double ? 64 : 32);
            const value = n => (form.double ? f64 : f32)(1.25 + n / 7);
            const list = Array.from({ length: 16 }, (_, n) => {
                const of = k => Array.from({ length: lanes }, (_, i) => value(n * 3 + k + i)).reduce((v, x, i) => v | x << BigInt(i * (form.double ? 64 : 32)), 0n);
                const [a, b, c] = [of(0), of(1), of(2)];
                return { mxcsr: 0x1FA0, a, b, c, ...fma_expect(form, 0x1FA0, a, b, c) };
            });
            const { code, data } = program(form, false, list);
            for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
            page.x64_fma_calls_reset();
            const runs = await run_all(loop([...prologue, ...code]), data, list.length);
            const steps = machines[1].v86.cpu.wm.exports["x64_page_steps"](0xE2C4);
            const calls = page.x64_fma_calls();
            for(const { run, out, faults } of runs)
            {
                const view = new DataView(out.buffer);
                list.forEach((c, n) => {
                    assert.equal(faults.getUint32(n * 4, true), 0, `${form.name} ordinary case ${n} (${run}): no fault`);
                    const actual = [0, 1, 2, 3].reduce((v, q) => v | view.getBigUint64(n * 64 + 8 * q, true) << BigInt(64 * q), 0n);
                    assert.equal(actual.toString(16), c.result.toString(16), `${form.name} ordinary case ${n} (${run}): result`);
                });
            }
            // (a template steps the first executions at most; a build without
            // Wasm SIMD has no SIMD templates)
            const is_templated = steps < list.length;
            assert.equal(is_templated, !form.l && simd(machines[1]), `${form.name}: the page tier ${is_templated ? "ran a template" : "stepped"} (${steps} steps, ${list.length} cases)`);
            // (hot rounds of the template: natively, or each through the helper)
            if(is_templated) assert.ok(native ? calls === 0 : calls > list.length, `${form.name}: ${calls} exact helper calls (${native ? "native" : "exact"} FMA)`);
            if(is_templated) templated++;
            else stepped++;
        }
        console.log(simd(machines[1]) ? `PASS: the page tier ran templates for the ${templated} VEX.128 and scalar FMA forms (${native ? "native, relaxed multiply-adds" : "the exact helper"}), stepped the ${stepped} VEX.256 ones` :
            `PASS: the page tier stepped all ${stepped} FMA forms (no Wasm SIMD: no SIMD templates)`);
    }
    page.ir_set_relaxed_fma(+relaxed);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                                                source/v64/tests/rust/fma_cases.mjs                                                                 0000644 0000000 0000000 00000022421 00000000000 014460  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The FMA and F16C forms of docs/simd-xsave-plan.md 9.3 (P11) and their
// cases for tests/rust/fma.mjs and tests/x64/fma.mjs, with the expectations of
// tests/rust/sse_fp_model.mjs (exact rational arithmetic, independent of
// SoftFloat and cpu/simd_fp.rs).
import { SINGLE, DOUBLE, MXCSRS, lanes_of, of_lanes } from "./sse_fp_cases.mjs";
import * as model from "./sse_fp_model.mjs";

// The FMA forms: opcode, the operation (by its low nibble), the order (by its
// high one: 132, 213, 231), PS/PD/SS/SD, VEX.L
export const FMA_FORMS = [];
for(const [code, name, packed] of [[0x96, "fmaddsub", true], [0x97, "fmsubadd", true], [0x98, "fmadd", true], [0x99, "fmadd", false],
    [0x9A, "fmsub", true], [0x9B, "fmsub", false], [0x9C, "fnmadd", true], [0x9D, "fnmadd", false], [0x9E, "fnmsub", true], [0x9F, "fnmsub", false]])
{
    for(const [order, delta] of [["132", 0], ["213", 0x10], ["231", 0x20]])
        for(const double of [false, true])
            for(const l of packed ? [0, 1] : [0])
                FMA_FORMS.push({ name: `v${name}${order}${packed ? "p" : "s"}${double ? "d" : "s"}${l ? " ymm" : ""}`, op: code + delta, double, scalar: !packed, l });
}
/** A lane's x, y, z (x × y + z) of the operands a (DEST), b (SRC2), c (SRC3) */
export const order = (form, a, b, c) => ({ 9: [a, c, b], 10: [b, a, c], 11: [b, c, a] })[form.op >> 4];
/** The operands a, b, c that give x, y, z (`order`'s inverse) */
export const place = (form, x, y, z) => ({ 9: [x, z, y], 10: [y, x, z], 11: [z, x, y] })[form.op >> 4];
/** Lane i's negations: [the product's, the addend's] */
export function negations(form, i)
{
    const kind = form.op & 15, even = i % 2 === 0;
    if(kind === 6) return [false, even];
    if(kind === 7) return [false, !even];
    return [[false, false], [false, false], [false, true], [false, true], [true, false], [true, false], [true, true], [true, true]][kind - 8];
}
/** The model's result of an FMA form: { result, after, fault } */
export function fma_expect(form, mxcsr, a, b, c)
{
    const width = form.l ? 256 : 128;
    const fp = new model.Fp(mxcsr);
    const la = lanes_of(a, form.double, width), lb = lanes_of(b, form.double, width), lc = lanes_of(c, form.double, width);
    for(let i = 0; i < (form.scalar ? 1 : la.length); i++)
    {
        const [x, y, z] = order(form, la[i], lb[i], lc[i]);
        const [np, na] = negations(form, i);
        la[i] = fp.fused(x, y, z, form.double, np, na);
    }
    const { mxcsr: after, fault } = fp.finish();
    return { result: of_lanes(la, form.double), after, fault };
}

let seed = 0x2468ACE1;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const pick = list => list[random() % list.length];
const random_value = double => double ? BigInt(random()) << 32n | BigInt(random()) : BigInt(random());
/** A normal value of moderate size (exponent within ±16 of 0) */
const moderate = double => double ? BigInt(0x3F0 + random() % 32) << 52n | BigInt(random()) << 20n | BigInt(random() & 0xFFFFF) | BigInt(random() & 1) << 63n
    : BigInt(0x6F + random() % 32) << 23n | BigInt(random() & 0x7FFFFF) | BigInt(random() & 1) << 31n;
/** x, y, z in the order of x × y + z: the special triples */
export function triples(double)
{
    const v = double
        ? { q1: 0x7FF8000000000001n, q2: 0xFFF8000000000002n, s3: 0x7FF0000000000003n, q4: 0x7FF8000000000004n, s5: 0xFFF0000000000005n,
            one: 0x3FF0000000000000n, none: 0xBFF0000000000000n, two: 0x4000000000000000n, zero: 0n, nzero: 0x8000000000000000n, inf: 0x7FF0000000000000n, ninf: 0xFFF0000000000000n,
            max: 0x7FEFFFFFFFFFFFFFn, nmax: 0xFFEFFFFFFFFFFFFFn, min: 0x0010000000000000n, half: 0x3FE0000000000000n, denormal: 0x000FFFFFFFFFFFFFn, ndenormal: 0x8000000000000001n }
        : { q1: 0x7FC00001n, q2: 0xFFC00002n, s3: 0x7F800003n, q4: 0x7FC00004n, s5: 0xFF800005n,
            one: 0x3F800000n, none: 0xBF800000n, two: 0x40000000n, zero: 0n, nzero: 0x80000000n, inf: 0x7F800000n, ninf: 0xFF800000n,
            max: 0x7F7FFFFFn, nmax: 0xFF7FFFFFn, min: 0x00800000n, half: 0x3F000000n, denormal: 0x007FFFFFn, ndenormal: 0x80000001n };
    return [
        // NaNs: the first of x, y, z wins (an SNaN: IE)
        [v.q1, v.q2, v.q4], [v.s3, v.q2, v.q4], [v.q1, v.s3, v.q4], [v.q1, v.q2, v.s3], [v.one, v.q2, v.s5], [v.one, v.one, v.s3],
        [v.one, v.one, v.q4], [v.q2, v.one, v.one], [v.one, v.s5, v.denormal],
        // 0 × ∞: with a QNaN addend that NaN and no IE; with an SNaN IE; with a number IE and the default NaN
        [v.zero, v.inf, v.q4], [v.ninf, v.zero, v.q1], [v.inf, v.nzero, v.s3], [v.zero, v.inf, v.one], [v.inf, v.zero, v.inf],
        // ∞ − ∞, ∞ + ∞, ∞ with a number
        [v.inf, v.one, v.ninf], [v.inf, v.one, v.inf], [v.ninf, v.two, v.one], [v.one, v.one, v.ninf],
        // zero sums and their signs
        [v.zero, v.one, v.nzero], [v.nzero, v.one, v.nzero], [v.zero, v.one, v.zero], [v.one, v.one, v.none],
        // overflow, underflow, denormals (DAZ, FZ, DE)
        [v.max, v.max, v.ninf], [v.max, v.two, v.nmax], [v.max, v.two, v.one], [v.min, v.half, v.zero], [v.min, v.half, v.denormal],
        [v.denormal, v.one, v.zero], [v.denormal, v.denormal, v.one], [v.ndenormal, v.two, v.denormal], [v.min, v.min, v.nzero],
    ];
}
/** x, y and the negated rounded product: the fused result is the rounding error */
export function error_triple(double)
{
    const x = moderate(double), y = moderate(double);
    const product = new model.Fp(0x1F80).binary("mul", x, y, double);
    return [x, y, product ^ (double ? 1n << 63n : 1n << 31n)];
}
/** An FMA form's cases: { mxcsr, a, b, c } and the model's expectation */
export function fma_cases(form, mxcsrs = MXCSRS, extra = 4)
{
    const width = form.l ? 256 : 128, lanes = width / (form.double ? 64 : 32), active = form.scalar ? 1 : lanes;
    const special = triples(form.double), values = form.double ? DOUBLE : SINGLE;
    // (each MXCSR: every special triple, then `extra` cases: half with
    // rounding errors exposed, half random)
    const per_mxcsr = Math.ceil(special.length / active) + extra;
    const out = [];
    let k = 0;
    mxcsrs.forEach(mxcsr => {
        for(let n = 0; n < per_mxcsr; n++)
        {
            const a = [], b = [], c = [];
            for(let i = 0; i < lanes; i++)
            {
                let xyz;
                if(i >= active) xyz = [random_value(form.double), random_value(form.double), random_value(form.double)];
                else if(n < per_mxcsr - extra) xyz = special[k++ % special.length];
                else if(n < per_mxcsr - extra / 2) xyz = error_triple(form.double);
                else xyz = [0, 1, 2].map(() => random() & 1 ? pick(values) : random() & 1 ? moderate(form.double) : random_value(form.double));
                const [p, q, r] = place(form, ...xyz);
                a.push(p); b.push(q); c.push(r);
            }
            const ca = of_lanes(a, form.double), cb = of_lanes(b, form.double), cc = of_lanes(c, form.double);
            out.push({ mxcsr, a: ca, b: cb, c: cc, ...fma_expect(form, mxcsr, ca, cb, cc) });
        }
    });
    return out;
}

// F16C: the halves and singles to convert
export const HALVES = [0x0000n, 0x8000n, 0x3C00n, 0xBC00n, 0x0001n, 0x03FFn, 0x8200n, 0x0400n, 0x7BFFn, 0xFBFFn, 0x7C00n, 0xFC00n,
    0x7E00n, 0x7C01n, 0xFD23n, 0x7FFFn, 0x3555n, 0x5640n, 0xC123n, 0x2E66n];
export const SINGLES_TO_HALF = [...SINGLE, 0x477FE000n /* 65504 */, 0x477FEFFFn, 0x477FF000n /* 65520 */, 0x38800000n /* 2^-14 */, 0x33800000n /* 2^-24 */,
    0x33000000n /* 2^-25 */, 0x33000001n, 0x3F801000n /* 1 + 2^-11 */, 0x3F803000n, 0xBF801000n, 0x387FC000n, 0x38000000n, 0xC77FFFFFn, 0x7F801234n, 0xFFC0ABCDn];
export const F16C_FORMS = [
    { name: "vcvtph2ps", kind: "ph2ps", l: 0 }, { name: "vcvtph2ps ymm", kind: "ph2ps", l: 1 },
    { name: "vcvtps2ph", kind: "ps2ph", l: 0 }, { name: "vcvtps2ph ymm", kind: "ps2ph", l: 1 },
];
/** An F16C form's cases: { mxcsr, source, imm8 } and the model's expectation */
export function f16c_cases(form, mxcsrs = MXCSRS, per_mxcsr = 10)
{
    const count = form.l ? 8 : 4, out = [];
    let k = 0;
    mxcsrs.forEach((mxcsr, mi) => {
        for(let n = 0; n < per_mxcsr; n++)
        {
            // (every rounding control: imm8[1:0], or MXCSR.RC with imm8[2]; bits 7:3 ignored)
            const imm8 = (mi + n) & 7 | (n & 1 ? 0xA8 : 0);
            const fp = new model.Fp(mxcsr);
            const rc = imm8 & 4 ? mxcsr >> 13 & 3 : imm8 & 3;
            const lanes = [];
            for(let i = 0; i < count; i++)
            {
                const list = form.kind === "ph2ps" ? HALVES : SINGLES_TO_HALF;
                lanes.push(n < per_mxcsr * 0.7 ? list[k++ % list.length] : form.kind === "ph2ps" ? BigInt(random() & 0xFFFF) : random_value(false));
            }
            let source, result;
            if(form.kind === "ph2ps")
            {
                source = lanes.reduce((v, h, i) => v | h << BigInt(16 * i), 0n);
                result = lanes.reduce((v, h, i) => v | fp.half_to_single(h) << BigInt(32 * i), 0n);
            }
            else
            {
                source = of_lanes(lanes, false);
                result = lanes.reduce((v, x, i) => v | fp.single_to_half(x, rc) << BigInt(16 * i), 0n);
            }
            const { mxcsr: after, fault } = fp.finish();
            out.push({ mxcsr, source, imm8, result, after, fault });
        }
    });
    return out;
}
                                                                                                                                                                                                                                               source/v64/tests/rust/jit_capacity.asm                                                              0000644 0000000 0000000 00000002001 00000000000 015161  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       bits 16
org 0
    cli
    lgdt [cs:gdtr]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:0xF0000 + protected
bits 32
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov fs, ax
    mov gs, ax
    mov esp, 0x8000
    ; Identity-map 8 MiB, plus virtual aliases of the two-page test module.
    cld
    xor eax, eax
    mov edi, 0x12000
    mov ecx, 4096
    rep stosd
    mov dword [0x12000], 0x13003
    mov dword [0x12004], 0x14003
    mov dword [0x12008], 0x15003
    mov edi, 0x13000
    mov eax, 3
    mov ecx, 2048
.pte:
    stosd
    add eax, 4096
    loop .pte
    mov dword [0x15000], 0x100003
    mov dword [0x15004], 0x101003
    mov eax, 0x12000
    mov cr3, eax
    mov eax, cr0
    or eax, 0x80000000
    mov cr0, eax
    mov dword [0x500], 0xCAFE
    hlt
    jmp $
align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr:
    dw 23
    dd 0xF0000 + gdt
times 0xFFF0 - ($ - $$) db 0xF4
bits 16
    jmp 0xF000:start
start equ 0
times 0x10000 - ($ - $$) db 0xF4
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/rust/jit_disabled_promotion.mjs                                                    0000644 0000000 0000000 00000005176 00000000000 017272  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Disabling the JIT at run time (jit_set_enabled) stops the page tier: a hot
// loop runs in the interpreter for 128 CPU frames without a compilation or an
// activation of compiled code; re-enabling compiles and enters it. (Until M11
// of docs/jit-unification-plan.md this tested the region tiers' promotion.)
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
const wasm = process.argv[2] || "build/v86-debug.wasm";
const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: wasm, memory_size: 32 << 20, ir_sync_publication: true,
    bios: { buffer: Uint8Array.from(fs.readFileSync("build/cpu-worker-test.bin")).buffer },
    disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" } });
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const until = async (test, message) => {
    const deadline = performance.now() + 15000;
    while(!test()) { assert(performance.now() < deadline, message); await sleep(1); }
};
try
{
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    vm.run(); await until(() => cpu.mem32s[0x500 >> 2] === 0xCAFE, "boot"); await vm.stop();
    cpu.jit_clear_cache();
    const pc = 0x1200000;
    // (inc eax; jmp short back)
    vm.write_memory(Uint8Array.of(0x40, 0xEB, 0xFD), pc);
    cpu.instruction_pointer[0] = pc; cpu.in_hlt[0] = 0;
    const compiles = () => e.x64_page_stat(0) >>> 0, activations = () => e.x64_page_stat(13) >>> 0;
    assert(e.jit_set_enabled(0));
    const compiled = compiles(), entered = activations(), eax = cpu.reg32[0];
    let frames = 0;
    const main_loop = cpu.main_loop;
    cpu.main_loop = function() { const result = main_loop.call(this); frames++; return result; };
    vm.run(); await until(() => frames >= 128, "128 CPU frames"); await vm.stop();
    const interpreted = (cpu.reg32[0] - eax) >>> 0;
    assert(interpreted > 0, "the loop ran");
    assert.equal(compiles(), compiled, "no compilation with the JIT disabled");
    assert.equal(activations(), entered, "no compiled code entered with the JIT disabled");
    assert(e.jit_set_enabled(1));
    vm.run(); await until(() => activations() > entered, "compiled code after re-enabling"); await vm.stop();
    assert(compiles() > compiled, "the loop compiles after re-enabling");
    console.log(`PASS: ${wasm}: a disabled JIT neither compiles nor enters page functions for 128 CPU frames (${interpreted} interpreted iterations); re-enabled, it compiles the loop`);
}
finally { await vm.destroy(); }
                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/rust/jit_tiers.mjs                                                                 0000644 0000000 0000000 00000007745 00000000000 014547  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Fresh-VM cold/steady comparison of the code generators (the x64 page
// tier's page functions; IR Tier-0's until P7.5, the region tiers' until M11)
// plus SMC and restore checks.
//   node tests/rust/jit_tiers.mjs [baseline.wasm] [candidate.wasm]
// With a baseline core, it runs in its default configuration as an extra arm.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
const baseline=process.argv[2];
const candidate=process.argv[3] || "build/v86.wasm";
const bios=Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const u32=n=>[n&255,n>>>8&255,n>>>16&255,n>>>24&255];
const sleep=ms=>new Promise(r=>setTimeout(r,ms));
const arms=[...baseline ? [{ label: "baseline", wasm: baseline, options: {} }] : [],
    ...COMPILED_ARMS.map(arm=>({ ...arm, wasm: candidate }))];
const results=arms.map(()=>[]);
const word=(vm,a)=>new DataView(Uint8Array.from(vm.read_memory(a,4)).buffer).getUint32(0,true);
for(let round=0;round<5;round++) for(const index of round&1 ? [...arms.keys()].reverse() : arms.keys()) {
    const { label, wasm, options }=arms[index];
    const vm=new V86({graphics_adapter: "bochs_vga", wasm_path:wasm,bios:{buffer:bios.slice(0)},memory_size:32<<20,...options,
        disable_keyboard:true,disable_mouse:true,disable_speaker:true,net_device:{type:"none"},autostart:false});
    try {
        await new Promise(r=>vm.add_listener("emulator-loaded",r));
        vm.run();
        const boot=performance.now();
        while(word(vm,0x500)!==0xCAFE) { assert(performance.now()-boot<10000);await sleep(1); }
        await vm.stop();
        const cpu=vm.v86.cpu,e=cpu.wm.exports;
        for(let page=0;page<6;page++) {
            const address=0x100000+page*4096,p=[0xB8,...u32(page+1),0xBB,...u32(17)];
            for(let i=0;i<32;i++) p.push(0x01,0xD8,0x29,0xD8);
            p.push(0xA3,...u32(0x210000+page*4),0xFF,0x05,...u32(0x600));
            p.push(0xE9,...u32(0x100000+(page+1)%6*4096-address-p.length-5));
            vm.write_memory(Uint8Array.from(p),address);
        }
        cpu.instruction_pointer[0]=0x100000;cpu.in_hlt[0]=0;
        const activations=compiled_activations(e),start=performance.now();vm.run();
        while(compiled_activations(e)===activations) { assert(performance.now()-start<10000,`${label}: first compiled execution`);await sleep(1); }
        const first_compiled_ms=performance.now()-start;
        await sleep(150);await vm.stop();
        for(let page=0;page<6;page++) assert.equal(word(vm,0x210000+page*4),page+1);
        const before=word(vm,0x600),warm=performance.now();
        while(performance.now()-warm<120) cpu.main_loop();
        const pages_per_ms=((word(vm,0x600)-before)>>>0)/(performance.now()-warm);
        const ir=vm.get_jit_info().ir;
        const sample={first_compiled_ms,pages_per_ms,page_functions:ir.page_tier?.functions||0};
        results[index].push(sample);
        if(label==="pages") assert(sample.page_functions>0,"the page tier compiled page functions");
        if(round===0) {
            const saved=await vm.save_state();
            vm.write_memory(Uint8Array.from(u32(9)),0x102001);
            cpu.instruction_pointer[0]=0x100000;cpu.in_hlt[0]=0;vm.run();await sleep(60);await vm.stop();
            assert.equal(word(vm,0x210008),9,`${label}: SMC after compilation uses new bytes`);
            await vm.restore_state(saved);vm.run();await sleep(60);await vm.stop();
            assert.equal(word(vm,0x210008),3,`${label}: restore discards compiled code`);
        }
    } finally { await vm.destroy(); }
}
const median=a=>a.toSorted((a,b)=>a-b)[a.length>>1];
for(const [i,{ label, wasm }] of arms.entries()) {
    const summary={label,wasm,rounds:5};
    for(const key of Object.keys(results[i][0])) summary[key]=median(results[i].map(x=>x[key]));
    console.log(JSON.stringify({...summary,samples:results[i]}));
}
console.log("PASS: page tier compilation, code modification and save/restore");
                           source/v64/tests/rust/mmx_fast_path.mjs                                                             0000644 0000000 0000000 00000030215 00000000000 015371  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
// mmx_fast_path.mjs [baseline.wasm] [candidate.wasm]: machine 0 is the
// interpreter (or, with arguments, the baseline core); the candidate core runs
// every case once per compiled arm (the page tier) and must match it.
const paths = [process.argv[2] || "build/v86.wasm", process.argv[3] || "build/v86.wasm"];
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const DATA = 0x200000, OUT = 0x210000, CODE = 0x100000;
const machines = [], labels = [];
const interpreted_machines = new WeakSet();
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
async function run(vm, address, warm = false) {
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    // Programs reuse CODE: start each warm run from an empty compiler state
    // (compiled code needs more heat to recompile a page after each rewrite).
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.instruction_pointer[0] = address; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const end = performance.now() + 10000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreted_machines.has(vm) && compiled_activations(e) === start) {
        assert(performance.now() < end, "MMX guest/JIT timeout"); await sleep(1);
    }
    await vm.stop();
}
const data = new Uint8Array(8192), dv = new DataView(data.buffer);
for(let i = 0; i < data.length; i += 8) {
    const patterns = [0x8000800080008000n, 0xFFFFFFFF00000001n, 0x7FFF80010000FFFFn, 0x12345678ABCDEF01n];
    dv.setBigUint64(i, patterns[i / 8 % patterns.length], true);
}
function calculate(op, a, b) {
    if(op === 0x6F || (op === 0x7F || op === 0xE7)) return a;
    if(op === 0xFE) return BigInt.asUintN(32, a + b) |
        BigInt.asUintN(32, (a >> 32n) + (b >> 32n)) << 32n;
    const word16 = (v, n) => BigInt.asIntN(16, v >> BigInt(n * 16));
    let value = 0n;
    for(let lane = 0; lane < 2; lane++) value |= BigInt.asUintN(32,
        word16(a, lane * 2) * word16(b, lane * 2) +
        word16(a, lane * 2 + 1) * word16(b, lane * 2 + 1)) << BigInt(lane * 32);
    return value;
}
try {
    const interpreted = !process.argv[2];
    for(const [label, wasm_path, options] of [
        [interpreted ? "interpreter" : paths[0], paths[0], interpreted ? { disable_jit: true } : {}],
        ...COMPILED_ARMS.map(arm => [arm.label, paths[1], arm.options])]) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path, ...options, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        machines.push(vm); labels.push(label);
        if(options.disable_jit) interpreted_machines.add(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const end = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < end); await sleep(1); }
        await vm.stop(); vm.write_memory(data, DATA);
    }
    let count = 0;
    for(const op of [0x6F, 0x7F, 0xFE, 0xF5, 0xE7]) for(const memory of op === 0xE7 ? [true] : [false, true]) {
        const program = [], expected = [];
        for(let src = 0; src < 8; src++) for(let dst = 0; dst < 8; dst++) {
            const n = src * 8 + dst, output = OUT + n * 128;
            // Nonzero TOP before the optimized instruction; all physical MMX
            // registers have known values, including PMADDWD overflow pairs.
            program.push(0xDB, 0xE3);
            for(let r = 0; r < 8; r++) program.push(0x0F, 0x6F, 0x05 | r << 3, ...u32(DATA + r * 8));
            program.push(0xD9, 0xF7, 0xD9, 0xF7, 0xD9, 0xF7, 0xF9);
            const offset = [0, 1, 4092, 4095][src & 3];
            let a = dv.getBigUint64(src * 8, true), b = dv.getBigUint64(dst * 8, true);
            if(memory) {
                if((op === 0x7F || op === 0xE7)) {
                    program.push(0x0F, op, 0x05 | src << 3, ...u32(0x220000 + offset));
                    program.push(0x0F, 0x6F, 0x05 | dst << 3, ...u32(0x220000 + offset));
                } else {
                    a = dv.getBigUint64(offset, true);
                    program.push(0x0F, op, 0x05 | dst << 3, ...u32(DATA + offset));
                }
            } else program.push(0x0F, op, 0xC0 | ((op === 0x7F || op === 0xE7) ? src << 3 | dst : dst << 3 | src));
            program.push(0x9C, 0x58, 0xA3, ...u32(output + 8));
            program.push(0x0F, 0x7F, 0x05 | dst << 3, ...u32(output));
            program.push(0xDD, 0x35, ...u32(output + 16)); // FNSAVE, includes raw 80-bit registers
            expected.push(calculate(op, a, b));
        }
        program.push(0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE));
        program.push(0xE9, ...u32(-program.length - 5));
        const results = [];
        for(const vm of machines) {
            vm.write_memory(Uint8Array.from(program), CODE);
            await run(vm, CODE, true); await run(vm, CODE);
            const bytes = Uint8Array.from(vm.read_memory(OUT, 64 * 128)); results.push(bytes);
            const view = new DataView(bytes.buffer);
            for(let n = 0; n < 64; n++) {
                assert.equal(view.getBigUint64(n * 128, true), expected[n], `MMX ${op.toString(16)} memory=${memory} pair=${n}`);
                assert.equal(view.getUint32(n * 128 + 8, true) & 1, 1, "MMX preserves carry");
                assert.equal(view.getUint16(n * 128 + 20, true) & 0x3800, 0, "MMX resets TOP");
            }
        }
        for(let i = 1; i < machines.length; i++)
            assert.deepEqual(results[i], results[0], `${labels[i]}: MMX results and complete FNSAVE state match ${labels[0]}`);
        count += expected.length;
    }
    // Faulting instructions must preserve the destination, tag state and TOP.
    const idt = 0x250000, descriptor = 0x251000, handler = 0x280000;
    let faults = 0;
    for(const [op, memory] of [[0x6F, false], [0x7F, false], [0xFE, false], [0xF5, false],
        [0x6F, true], [0x7F, true], [0xFE, true], [0xF5, true], [0xE7,true],
        ...[0xEC,0x63,0xD5,0xE4,0xF4,0xF6,0xD1,0x68].flatMap(op => [[op,false],[op,true]])]) {
        for(const vector of memory ? [7, 6, 14] : [7, 6]) {
            const length = memory ? 7 : 3, frame = vector === 14 ? 4 : 0;
            const fault_address = vector === 14 ? 0x801FFC : DATA;
            const program = [0x0F, 0x01, 0x1D, ...u32(descriptor),
                0x0F, 0x20, 0xC0, 0x83, 0xE0, 0xF3, 0x0F, 0x22, 0xC0,
                0xDB, 0xE3, 0xD9, 0xE8];
            if(vector !== 14) program.push(0x0F, 0x20, 0xC0, 0x83, 0xC8, vector === 7 ? 8 : 4, 0x0F, 0x22, 0xC0);
            const fault_eip = CODE + program.length;
            program.push(0x0F, op, memory ? 0x05 : 0xC1, ...(memory ? u32(fault_address) : []));
            program.push(0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE));
            program.push(0x80, 0x3D, ...u32(0x604), 0, 0x75, 5);
            program.push(0xE9, ...u32(-program.length - 5), 0xF4);
            const handler_code = [0x8B, 0x44, 0x24, frame, 0xA3, ...u32(OUT),
                0x83, 0x44, 0x24, frame, length];
            if(vector === 14) handler_code.push(0x83, 0xC4, 4);
            else handler_code.push(0x0F, 0x20, 0xC0, 0x83, 0xE0, 0xF3, 0x0F, 0x22, 0xC0);
            handler_code.push(0xCF);
            const snapshots = [];
            for(const vm of machines) {
                vm.write_memory(Uint8Array.from([handler & 255, handler >>> 8 & 255, 8, 0, 0, 0x8E,
                    handler >>> 16 & 255, handler >>> 24]), idt + vector * 8);
                vm.write_memory(Uint8Array.from([255, 7, ...u32(idt)]), descriptor);
                vm.write_memory(Uint8Array.from(handler_code), handler);
                vm.write_memory(Uint8Array.from(program), CODE);
                vm.write_memory(new Uint8Array(1), 0x604);
                await run(vm, CODE, true);
                vm.write_memory(Uint8Array.of(1), 0x604);
                vm.v86.cpu.fpu_st.fill(0);
                vm.write_memory(Uint8Array.from(u32(0x87654321)), 0x101FFC);
                await run(vm, CODE);
                // Raw F80 registers lag the x87 shadow cache (a dirty f64 is
                // authoritative until a guest observer); synchronize to compare.
                vm.v86.cpu.wm.exports.fpu_sync_all();
                assert.equal(word(vm, OUT), fault_eip, `precise MMX fault #${vector}`);
                assert.equal(vm.v86.cpu.fpu_stack_ptr[0], 7, `fault preserves TOP: ${labels[machines.indexOf(vm)]} op=${op.toString(16)} memory=${memory} #${vector}`);
                assert.equal(vm.v86.cpu.fpu_stack_empty[0], 0x7F, "fault preserves tags");
                snapshots.push(Array.from(vm.v86.cpu.fpu_st));
                if(vector === 14 && (op === 0x7F || op === 0xE7)) assert.equal(word(vm, 0x101FFC), 0x87654321,
                    "cross-page store faults before writing the first page");
            }
            for(let i = 1; i < machines.length; i++) assert.deepEqual(snapshots[i], snapshots[0],
                `${labels[i]}: fault leaves all FPU registers unchanged from ${labels[0]} (op=${op.toString(16)} memory=${memory} #${vector})`);
            faults++;
        }
    }
    // Exercise direct x87 register reads/push/pop with every TOP and with
    // empty/full/partially occupied stacks. Compare complete saved FPU state.
    {
        const program = [];
        let cases = 0;
        for(let top = 0; top < 8; top++) for(const occupied of [0,1,4,8]) for(let source = 0; source < 8; source++) for(const emms of [false, true]) {
            program.push(0xDB,0xE3);
            for(let i = 0; i < occupied; i++) program.push(0xD9,0xE8);
            for(let i = 0; i < top; i++) program.push(0xD9,0xF6);
            program.push(0xD9,0xC0 | source); // FLD ST(i), including underflow/overflow
            program.push(0xD9,0x1D,...u32(0x230000)); // FSTP m32, including direct pop
            if(emms) program.push(0x0F,0x77);
            program.push(0xDD,0x35,...u32(OUT + cases * 128));
            cases++;
        }
        program.push(0xC7,0x05,...u32(0x600),...u32(0xCAFE));
        program.push(0xE9,...u32(-program.length - 5));
        const snapshots = [];
        for(const vm of machines) {
            vm.write_memory(Uint8Array.from(program), CODE);
            await run(vm, CODE, true);
            snapshots.push(Uint8Array.from(vm.read_memory(OUT, cases * 128)));
        }
        for(let i = 1; i < machines.length; i++) assert.deepEqual(snapshots[i], snapshots[0],
            `${labels[i]}: x87 stack tags, status and data across every TOP, underflow and overflow`);
        console.log(`PASS: ${cases} x87 stack boundary states and complete FNSAVE images`);
    }
    // Leave actual MMX state live, rather than the empty state after FNSAVE.
    const live = [0x0F, 0x6F, 0x05, ...u32(DATA), 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE)];
    live.push(0xE9, ...u32(-live.length - 5));
    for(const vm of machines.slice(1)) {
        vm.write_memory(Uint8Array.from(live), CODE);
        await run(vm, CODE, true);
        // Save/restore after executing MMX must retain its shared x87 register state.
        const state = await vm.save_state();
        const before = Array.from(vm.v86.cpu.fpu_st);
        assert.equal(vm.v86.cpu.fpu_stack_empty[0], 0);
        assert.equal(vm.v86.cpu.fpu_stack_ptr[0], 0);
        vm.v86.cpu.fpu_st.fill(0);
        await vm.restore_state(state);
        assert.deepEqual(Array.from(vm.v86.cpu.fpu_st), before);
        assert.equal(vm.v86.cpu.fpu_stack_empty[0], 0);
        assert.equal(vm.v86.cpu.fpu_stack_ptr[0], 0);
    }
    console.log(`PASS: ${faults} real guest #NM/#UD/#PF cases preserve MMX/x87 state and precise EIP`);
    console.log(`PASS: ${count} MMX register/memory cases, aliases, unaligned/page-crossing access, carry, TOP, full FNSAVE and save/restore`);
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/rust/packed_model.mjs                                                              0000644 0000000 0000000 00000013317 00000000000 015152  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Independent lane model: BigInt arithmetic, no Wasm or CPU implementation calls.
import assert from "node:assert/strict";
export function packed(op, destination, source) {
    if([0x0F14,0x0F15,0x660F14,0x660F15].includes(op)) op={0x0F14:0x62,0x0F15:0x6A,0x660F14:0x6C,0x660F15:0x6D}[op];
    // SSE4.1/SSE4.2 (66 0F 38 xx): their byte, kept apart from the 66 0F bytes
    const sse4=op>0xFFFFFF?op&255:undefined;
    op &= 255;
    if(op>=0x54&&op<=0x57)op=[0xDB,0xDF,0xEB,0xEF][op-0x54];
    const bytes = words => {const buffer=new ArrayBuffer(16),v=new DataView(buffer);words.forEach((x,i)=>v.setUint32(i*4,x,true));return new Uint8Array(buffer);};
    const a=bytes(destination),b=bytes(source),out=new Uint8Array(16);
    const read=(v,bits,lane)=>{let n=0n;for(let j=bits/8-1;j>=0;j--)n=n<<8n|BigInt(v[lane*bits/8+j]);return n;};
    const write=(n,bits,lane)=>{n=BigInt.asUintN(bits,n);for(let j=0;j<bits/8;j++){out[lane*bits/8+j]=Number(n&255n);n>>=8n;}};
    const signed=(v,bits,i)=>BigInt.asIntN(bits,read(v,bits,i));
    const result=()=>{const v=new DataView(out.buffer);return Array.from({length:4},(_,i)=>v.getUint32(i*4,true));};
    if(sse4===0x2B){
        // PACKUSDW: signed doublewords to unsigned words
        for(let half=0;half<2;half++) for(let i=0;i<4;i++){const n=signed(half?b:a,32,i);write(n<0n?0n:n>65535n?65535n:n,16,half*4+i);}
        return result();
    }
    const unpack=sse4===undefined&&{0x60:[8,0],0x61:[16,0],0x62:[32,0],0x68:[8,1],0x69:[16,1],0x6A:[32,1],0x6C:[64,0],0x6D:[64,1]}[op];
    if(unpack){
        const [bits,high]=unpack,start=high*64/bits;
        for(let i=0;i<64/bits;i++){write(read(a,bits,start+i),bits,i*2);write(read(b,bits,start+i),bits,i*2+1);}
        return result();
    }
    if(sse4===undefined&&[0x63,0x67,0x6B].includes(op)){
        const bits=op===0x6B?16:8,lo=op===0x67?0n:-(1n<<BigInt(bits-1)),hi=op===0x67?255n:-lo-1n;
        for(let half=0;half<2;half++) for(let i=0;i<64/bits;i++){
            const n=signed(half?b:a,bits*2,i);write(n<lo?lo:n>hi?hi:n,bits,half*64/bits+i);
        }
        return result();
    }
    const shift=sse4===undefined&&{0xD1:[16,"right"],0xD2:[32,"right"],0xD3:[64,"right"],0xE1:[16,"signed"],0xE2:[32,"signed"],0xF1:[16,"left"],0xF2:[32,"left"],0xF3:[64,"left"]}[op];
    if(shift){
        const [bits,kind]=shift,count=read(b,64,0),n=count>=BigInt(bits)?BigInt(bits):count;
        for(let i=0;i<128/bits;i++){
            const x=kind==="signed"?signed(a,bits,i):read(a,bits,i);
            write(kind==="left"?x<<n:x>>n,bits,i);
        }
        return result();
    }
    const spec=sse4!==undefined?{
        0x29:[64,"eq"],0x37:[64,"gt"],0x38:[8,"mins"],0x39:[32,"mins"],0x3A:[16,"minu"],0x3B:[32,"minu"],
        0x3C:[8,"maxs"],0x3D:[32,"maxs"],0x3E:[16,"maxu"],0x3F:[32,"maxu"],0x40:[32,"mull"],
    }[sse4]:{
        0xFC:[8,"add"],0xFD:[16,"add"],0xFE:[32,"add"],0xD4:[64,"add"],
        0xF8:[8,"sub"],0xF9:[16,"sub"],0xFA:[32,"sub"],0xFB:[64,"sub"],
        0xEC:[8,"adds"],0xED:[16,"adds"],0xDC:[8,"addu"],0xDD:[16,"addu"],
        0xE8:[8,"subs"],0xE9:[16,"subs"],0xD8:[8,"subu"],0xD9:[16,"subu"],
        0x64:[8,"gt"],0x65:[16,"gt"],0x66:[32,"gt"],
        0x74:[8,"eq"],0x75:[16,"eq"],0x76:[32,"eq"],
        0xDA:[8,"minu"],0xDE:[8,"maxu"],0xEA:[16,"mins"],0xEE:[16,"maxs"],
        0xE0:[8,"avg"],0xE3:[16,"avg"],0xE4:[16,"mulhu"],0xE5:[16,"mulhs"],
        0xF4:[64,"muld"],0xF6:[64,"sad"],0xD5:[16,"mull"],0xF5:[32,"madd"],
        0xDB:[128,"and"],0xDF:[128,"andnot"],0xEB:[128,"or"],0xEF:[128,"xor"],
    }[op];
    assert(spec,`missing packed model ${(sse4===undefined?op:0x660F3800|sse4).toString(16)}`);
    const [bits,kind]=spec,mask=(1n<<BigInt(bits))-1n,min=-(1n<<BigInt(bits-1)),max=-min-1n;
    const clamp=(n,lo,hi)=>n<lo?lo:n>hi?hi:n;
    for(let i=0;i<128/bits;i++){
        const x=read(a,bits,i),y=read(b,bits,i),sx=BigInt.asIntN(bits,x),sy=BigInt.asIntN(bits,y);
        let n;
        switch(kind){
            case "add": n=x+y;break;
            case "sub": n=x-y;break;
            case "adds": n=clamp(sx+sy,min,max);break;
            case "subs": n=clamp(sx-sy,min,max);break;
            case "addu": n=clamp(x+y,0n,mask);break;
            case "subu": n=clamp(x-y,0n,mask);break;
            case "gt": n=sx>sy?mask:0n;break;
            case "eq": n=x===y?mask:0n;break;
            case "minu": n=x<y?x:y;break;
            case "maxu": n=x>y?x:y;break;
            case "mins": n=sx<sy?sx:sy;break;
            case "maxs": n=sx>sy?sx:sy;break;
            case "avg": n=(x+y+1n)/2n;break;
            case "mulhu": n=x*y>>16n;break;
            case "mulhs": n=sx*sy>>16n;break;
            case "mull": n=x*y;break;
            case "muld": n=read(a,32,2*i)*read(b,32,2*i);break;
            case "madd": n=signed(a,16,2*i)*signed(b,16,2*i)+signed(a,16,2*i+1)*signed(b,16,2*i+1);break;
            case "sad": n=0n;for(let j=0;j<8;j++)n+=BigInt(Math.abs(a[8*i+j]-b[8*i+j]));break;
            case "and": n=x&y;break;
            case "andnot": n=~x&y;break;
            case "or": n=x|y;break;
            case "xor": n=x^y;break;
        }
        write(n,bits,i);
    }
    const v=new DataView(out.buffer);return Array.from({length:4},(_,i)=>v.getUint32(i*4,true));
}

function packed_immediate(op, group, count, destination) {
    if(op===0x660F73&&[3,7].includes(group)){
        let value=destination.reduce((n,x,i)=>n|BigInt(x)<<BigInt(32*i),0n);
        const shift=BigInt(Math.min(count,16)*8);
        value=group===7?value<<shift:value>>shift;
        value=BigInt.asUintN(128,value);
        return Array.from({length:4},(_,i)=>Number(value>>BigInt(32*i)&0xFFFFFFFFn));
    }
    const operation={2:0xD1,4:0xE1,6:0xF1}[group]+(op&255)-0x71;
    return packed(0x660F00|operation,destination,[count,0,0,0]);
}
export { packed_immediate as packedImmediate };
                                                                                                                                                                                                                                                                                                                 source/v64/tests/rust/packed_simd.mjs                                                               0000644 0000000 0000000 00000027406 00000000000 015012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
// packed_simd.mjs [baseline.wasm] [candidate.wasm]: machine 0 is the
// interpreter (or, with arguments, the baseline core); the candidate core runs
// every case once per compiled arm (the page tier) and must match it.
const candidate = process.argv[3] || "build/v86.wasm";
const baseline = process.argv[2] || candidate;
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const machines = [], DATA = 0x200000, OUT = 0x210000, CODE = 0x100000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const labels = [];
// SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
const ENABLE_SSE = [0x0F,0x20,0xE0,0x0D,...u32(0x600),0x0F,0x22,0xE0];
/** An m128 operand, which must be 16-byte aligned (#GP(0)); MMX forms and
 * the narrow SSE operands need no alignment */
function aligned_m128({ mmx, op, prefix }) {
    const p = prefix[0] ?? 0;
    // (MOVLPS/MOVHPS/MOVLPD/MOVHPD and MOVDDUP: an m64; MOVSLDUP, MOVSHDUP: an m128)
    if([0x12, 0x13, 0x16, 0x17].includes(op)) return p === 0xF3;
    if(p === 0x66) return ![0x2A, 0x2E, 0x2F, 0x6E, 0xC4].includes(op); // m64, m64, m32, m16
    if(p === 0xF2) return [0x70, 0x7C, 0x7D, 0xE6].includes(op);
    if(p === 0xF3) return [0x70, 0x5B].includes(op);
    return !mmx && ![0x5A, 0x2A, 0x2C, 0x2D, 0x2E, 0x2F].includes(op); // m64 and m32 sources
}
const ops = [0xE4,0xE5,0xF4,0xF6,0xFC,0xFD,0xFE,0xD4,0xF8,0xF9,0xFA,0xFB,0xEC,0xED,0xDC,0xDD,
    0xE8,0xE9,0xD8,0xD9,0x64,0x65,0x66,0x74,0x75,0x76,0xDA,0xDE,0xEA,0xEE,
    0xE0,0xE3,0xD5,0xF5,0xDB,0xDF,0xEB,0xEF,0x60,0x61,0x62,0x68,0x69,0x6A,
    0x63,0x67,0x6B,0xD1,0xD2,0xD3,0xE1,0xE2,0xF1,0xF2,0xF3];
const instructions = [];
for(const mmx of [true, false]) {
    const prefix = mmx ? [] : [0x66];
    for(const op of mmx ? ops : [...ops, 0x6C, 0x6D]) instructions.push({ mmx, op, prefix });
    for(const op of [0x71, 0x72, 0x73]) for(const group of op === 0x73 ? (mmx ? [2,6] : [2,3,6,7]) : [2,4,6])
        instructions.push({ mmx, op, prefix, group });
}
for(const [prefix, mmx, op] of [[[],true,0x70], [[0x66],false,0x70], [[0xF2],false,0x70],
    [[0xF3],false,0x70], [[],false,0xC6], [[0x66],false,0xC6],
    [[],false,0x14], [[],false,0x15], [[0x66],false,0x14], [[0x66],false,0x15]])
    instructions.push({ mmx, op, prefix, shuffle: op === 0x70 || op === 0xC6 });
for(const prefix of [[], [0x66], [0xF2], [0xF3]]) for(const op of [0x51,0x58,0x59,0x5C,0x5D,0x5E,0x5F,
    ...(!prefix.length || prefix[0] === 0xF3 ? [0x52,0x53] : [])])
    instructions.push({ mmx: false, op, prefix, floating: true });
for(const prefix of [[], [0x66], [0xF2], [0xF3]])
    instructions.push({ mmx: false, op: 0xC2, prefix, shuffle: true, floating: true });
for(const [prefix, op] of [[[],0x5A], [[0x66],0x5A], [[0xF2],0x5A], [[0xF3],0x5A],
    [[],0x5B], [[0x66],0x5B], [[0xF3],0x5B], [[0x66],0xE6], [[0xF2],0xE6], [[0xF3],0xE6]])
    for(let rounding_mode = 0; rounding_mode < 4; rounding_mode++)
        instructions.push({ mmx: false, op, prefix, floating: true, rounding_mode });
for(const prefix of [[], [0x66], [0xF2], [0xF3]]) for(const op of [0x2A,0x2C,0x2D])
    for(let rounding_mode = 0; rounding_mode < 4; rounding_mode++) {
        const scalar = prefix[0] === 0xF2 || prefix[0] === 0xF3;
        instructions.push({ mmx: !scalar && op !== 0x2A, op, prefix, floating: true, rounding_mode,
            source_mmx: !scalar && op === 0x2A, source_gpr: scalar && op === 0x2A,
            target_gpr: scalar && op !== 0x2A });
    }
for(const mmx of [true, false]) {
    const prefix = mmx ? [] : [0x66];
    instructions.push({ mmx, op: 0xF7, prefix, register_only: true, masked_store: true });
    for(const op of [0x6E,0xC4]) instructions.push({ mmx, op, prefix, source_gpr: true, shuffle: op === 0xC4 });
    for(const op of [0xC5,0xD7]) instructions.push({ mmx, op, prefix, source_mmx: mmx, target_gpr: true,
        register_only: true, shuffle: op === 0xC5 });
}
instructions.push({ mmx: true, op: 0x7E, prefix: [], target_gpr: true, register_only: true, reverse: true });
instructions.push({ mmx: true, op: 0x7E, prefix: [], memory_only: true, memory_store: true, output_width: 4 });
for(const prefix of [[], [0x66]]) instructions.push({ mmx: false, op: 0x50, prefix, target_gpr: true, register_only: true });
for(const prefix of [[], [0x66]]) for(const op of [0x2E,0x2F])
    instructions.push({ mmx: false, op, prefix, floating: true, changes_flags: true });
for(const prefix of [[0x66], [0xF2]]) for(const op of [0x7C,0x7D])
    instructions.push({ mmx: false, op, prefix, floating: true });
for(const [prefix, op] of [[[],0x16],[[0xF2],0x12],[[0xF3],0x12],[[0xF3],0x16]])
    instructions.push({ mmx: false, op, prefix });
for(const prefix of [[0xF2], [0xF3]]) instructions.push({ mmx: prefix[0] === 0xF2, op: 0xD6,
    prefix, source_mmx: prefix[0] === 0xF3, register_only: true });
try {
    for(const [label, wasm_path, options] of [
        [process.argv[2] ? baseline : "interpreter", baseline, process.argv[2] ? {} : { disable_jit: true }],
        ...COMPILED_ARMS.map(arm => [arm.label, candidate, arm.options])]) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...options, disable_keyboard: true,
            disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
        machines.push(vm); labels.push(label);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const end = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < end); await sleep(1); }
        await vm.stop();
    }
    let cases = 0;
    for(const { mmx, op, prefix, group, shuffle, floating, rounding_mode = 0, source_mmx, source_gpr, target_gpr, register_only, masked_store, changes_flags, reverse, memory_only, memory_store, output_width } of instructions) {
        const data = new Uint8Array(8192), view = new DataView(data.buffer);
        let seed = 0x713923AB;
        for(let i = 0; i < data.length; i++) { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; data[i] = seed; }
        if(floating) {
            const special = prefix[0] === 0x66 || prefix[0] === 0xF2 ?
                [0n,0x8000000000000000n,0x3FF0000000000000n,0xBFF0000000000000n,1n,
                    0x7FF0000000000000n,0xFFF0000000000000n,0x7FF123456789ABCDn,0x7FFABCDE01234567n] :
                [0n,0x8000000080000000n,0x3F8000003F800000n,0xBF800000BF800000n,0x100000001n,
                    0x7F8000007F800000n,0xFF800000FF800000n,0x7F8123457F812345n,0x7FCABCDE7FCABCDEn];
            const extra = [0.5,-0.5,1.5,-1.5,2.5,-2.5,2147483647,2147483648,-2147483648,-2147483649];
            const scratch = new DataView(new ArrayBuffer(8));
            for(const value of extra) {
                if(prefix[0] === 0x66 || prefix[0] === 0xF2) scratch.setFloat64(0, value, true);
                else { scratch.setFloat32(0, value, true); scratch.setFloat32(4, value, true); }
                special.push(scratch.getBigUint64(0, true));
            }
            for(let i = 0; i < 128; i++) view.setBigUint64(i * 8, special[i % special.length], true);
        }
        const shift = [0xD1,0xD2,0xD3,0xE1,0xE2,0xF1,0xF2,0xF3].includes(op);
        const counts = [0n,1n,15n,16n,31n,32n,63n,64n,255n,0x100000000n,0xFFFFFFFFFFFFFFFFn];
        // Signed saturation and multiply-add overflow alongside random data.
        const patterns = [0x8000800080008000n,0x7FFF7FFF7FFF7FFFn,0xFFFFFFFFFFFFFFFFn,0n];
        for(let i = 0; !floating && i < 16; i++) view.setBigUint64(i * 16,
            shift ? counts[i % counts.length] : patterns[i % 4], true);
        const width = output_width || (target_gpr ? 4 : mmx ? 8 : 16);
        view.setUint32(8000, 0x1F80 | rounding_mode << 13, true);
        const program = [...ENABLE_SSE,0x0F,0xAE,0x15,...u32(DATA + 8000)], total = group || shuffle ? 256 : 96;
        // (misaligned and page-crossing operands where alignment is not required)
        const offsets = aligned_m128({ mmx, op, prefix }) ? [0,16,4064,4080] : [0,1,4092,4095];
        for(let n = 0; n < total; n++) {
            const src = n >> 3 & (source_gpr ? 3 : 7), dst = n & (target_gpr ? 3 : 7), memory = memory_only || !register_only && !group && n >= 64;
            const source = DATA + ((n >> 3) * 16);
            const target = DATA + 512 + dst * 16;
            const load = mmx ? [0x0F,0x6F] : [0xF3,0x0F,0x6F];
            const store = mmx ? [0x0F,0x7F] : [0xF3,0x0F,0x7F];
            program.push(...load, 0x05 | dst << 3, ...u32(target));
            if(source_gpr) program.push(0xB8 | src, ...u32(view.getUint32(source - DATA, true)));
            else program.push(...((source_mmx ?? mmx) ? [0x0F,0x6F] : [0xF3,0x0F,0x6F]), 0x05 | src << 3, ...u32(source));
            if(masked_store) program.push(0xBF,...u32(OUT + n * 32));
            program.push(0xF9, ...prefix, 0x0F, op,
                group ? 0xC0 | group << 3 | dst : reverse ? 0xC0 | src << 3 | dst : memory ? 0x05 | dst << 3 : 0xC0 | dst << 3 | src,
                ...(memory ? u32(memory_store ? OUT + n * 32 : DATA + offsets[n & 3]) : []),
                ...(group || shuffle ? [n] : []));
            if(!masked_store && !memory_store) program.push(...(target_gpr ? [0x89] : store), 0x05 | dst << 3, ...u32(OUT + n * 32));
            program.push(0x9C, 0x58, 0xA3, ...u32(OUT + n * 32 + 16));
        }
        program.push(0xC7,0x05,...u32(0x600),...u32(0xCAFE));
        program.push(0xE9,...u32(-program.length - 5));
        const results = [];
        for(const [i, vm] of machines.entries()) {
            const cpu = vm.v86.cpu, e = cpu.wm.exports;
            // Programs reuse CODE: start each from an empty compiler state
            // (compiled code needs more heat to recompile a page after each rewrite).
            cpu.jit_clear_cache();
            vm.write_memory(data, DATA); vm.write_memory(new Uint8Array(total * 32), OUT);
            vm.write_memory(Uint8Array.from(program), CODE); vm.write_memory(new Uint8Array(4), 0x600);
            cpu.reg32[4] = 0x8000;
            cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
            const start = compiled_activations(e);
            vm.run();
            const end = performance.now() + 10000;
            while(word(vm, 0x600) !== 0xCAFE || (i >= 1 || process.argv[2]) && compiled_activations(e) === start) {
                assert(performance.now() < end, `${labels[i]}: SIMD timeout ${mmx}/${op.toString(16)}`); await sleep(1);
            }
            // Allow every page of the program to reach/publish its compiled code.
            await sleep(20); await vm.stop();
            results.push(Uint8Array.from(vm.read_memory(OUT, total * 32)));
            for(let n = 0; !changes_flags && n < total; n++) assert.equal(results[i][n * 32 + 16] & 1, 1, "preserves CF");
        }
        for(let i = 1; i < machines.length; i++) {
            for(let n = 0; n < total; n++) assert.deepEqual(results[i].slice(n*32,n*32+width), results[0].slice(n*32,n*32+width),
                `${labels[i]}: packed mismatch prefix=${prefix} mmx=${mmx} op=${op.toString(16)} case=${n}`);
            if(changes_flags) for(let n = 0; n < total; n++) assert.deepEqual(
                results[i].slice(n*32+16,n*32+20), results[0].slice(n*32+16,n*32+20), `${labels[i]}: COMI flags`);
        }
        cases += total;
    }
    console.log(`PASS: ${cases} MMX/SSE integer, floating, conversion and transfer cases; aliases, boundaries and memory, on the page tier`);
} finally {
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                          source/v64/tests/rust/shuffle_model.mjs                                                             0000644 0000000 0000000 00000002412 00000000000 015351  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Lane-based reference, independent of the IR byte-shuffle map and Wasm encoding.
export function shuffle(op, immediate, destination, source) {
    if(op===0x660F70) return [0,1,2,3].map(i=>source[immediate>>2*i&3]);
    if(op===0x0FC6) return [destination[immediate&3],destination[immediate>>2&3],source[immediate>>4&3],source[immediate>>6&3]];
    if(op===0x660FC6){const a=(immediate&1)*2,b=(immediate>>1&1)*2;return [...destination.slice(a,a+2),...source.slice(b,b+2)];}
    // BLENDPS, BLENDPD, PBLENDW: imm8 bit i takes element i from the source
    if(op===0x660F3A0C) return [0,1,2,3].map(i=>(immediate>>i&1?source:destination)[i]);
    if(op===0x660F3A0D) return [0,1,2,3].map(i=>(immediate>>(i>>1)&1?source:destination)[i]);
    if(op===0x660F3A0E){
        const half=v=>v.flatMap(x=>[x&65535,x>>>16]),d=half(destination),s=half(source),r=d.map((x,i)=>immediate>>i&1?s[i]:x);
        return [0,1,2,3].map(i=>(r[2*i]|r[2*i+1]<<16)>>>0);
    }
    const words=source.flatMap(x=>[x&65535,x>>>16]),result=words.slice(),start=op===0xF30F70?4:0;
    if(![0xF20F70,0xF30F70].includes(op)) throw new Error(`unknown shuffle ${op.toString(16)}`);
    for(let i=0;i<4;i++)result[start+i]=words[start+(immediate>>2*i&3)];
    return [0,1,2,3].map(i=>(result[2*i]|result[2*i+1]<<16)>>>0);
}
                                                                                                                                                                                                                                                      source/v64/tests/rust/softfloat_fast_path.mjs                                                       0000644 0000000 0000000 00000012312 00000000000 016567  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
const { instance } = await WebAssembly.instantiate(fs.readFileSync("build/softfloat-fast-test.wasm"));
const e = instance.exports;
const hits = [0, 0, 0, 0];
for(const precision of [32, 64, 80]) for(const rounding of [0, 1, 2, 3]) {
    assert.equal(e.verify_scale(precision, rounding, 50000), 0, JSON.stringify({ precision, rounding,
        words: Array.from({ length: 10 }, (_, i) => e.failure_word(i).toString(16)) }));
    assert.equal(e.verify_integral(precision, rounding, 100000), 0, JSON.stringify({ precision, rounding,
        words: Array.from({ length: 10 }, (_, i) => e.failure_word(i).toString(16)) }));
}
console.log("PASS: scale and round/trunc F80 bit patterns and sticky flags, all 12 control modes");
for(const precision of [32, 64, 80]) {
    for(const rounding of [0, 1, 2, 3]) {
        const failure = e.verify(precision, rounding, 100000);
        assert.equal(failure, 0, JSON.stringify({ precision, rounding, failure,
            words: Array.from({ length: 10 }, (_, i) => e.failure_word(i).toString(16)) }));
        for(let op = 0; op < 4; op++) hits[op] += e.hits(op);
    }
}
for(const precision of [32, 64, 80]) for(const rounding of [0, 1, 2, 3]) {
    const failure = e.verify_conversions(precision, rounding, 100000);
    assert.equal(failure, 0, JSON.stringify({ precision, rounding, failure,
        words: Array.from({ length: 10 }, (_, i) => e.failure_word(i).toString(16)) }));
}
for(const precision of [32, 64, 80]) for(const rounding of [0, 1, 2, 3]) {
    const failure = e.verify_wide_conversions(precision, rounding, 100000);
    assert.equal(failure, 0, JSON.stringify({ precision, rounding, failure,
        words: Array.from({ length: 10 }, (_, i) => e.failure_word(i).toString(16)) }));
}
console.log("PASS: binary64/int32/int64 to F80 and binary64 stores, all 12 modes, raw bits and sticky flags");
console.log("PASS: binary32/F80 load and store conversions, all 12 modes, raw bits and sticky flags");
assert(hits.every(n => n > 1000), "all four exact arithmetic paths must be exercised");
console.log("PASS: all 12 precision/rounding combinations; F80 bits and raw sticky exception flags match SoftFloat", { hits });
const median = a => a.sort((x, y) => x - y)[a.length >> 1];
for(let op = 0; op < 5; op++) {
    for(const fallback of [false, true]) {
        const times = [[], []];
        const count = 500000;
        for(let round = 0; round < 9; round++) {
            for(const fast of round & 1 ? [1, 0] : [0, 1]) {
                const start = performance.now();
                const checksum = op === 4 ? e.benchmark_compare(fast, fallback, count) : e.benchmark(op, fast, fallback, count);
                const elapsed = performance.now() - start;
                assert.equal(checksum, op === 4 ? e.benchmark_compare(!fast, fallback, count) : e.benchmark(op, !fast, fallback, count));
                if(round >= 2) times[fast].push(elapsed);
            }
        }
        const reference = median(times[0]), fast = median(times[1]);
        console.log(JSON.stringify({ op: ["add", "sub", "mul", "div", "compare"][op], fallback,
            reference_ms: reference, fast_ms: fast, speedup: reference / fast }));
    }
}

for(let op = 0; op < 4; op++) {
    const times = [[], []];
    for(let round = 0; round < 9; round++) for(const fast of round & 1 ? [1, 0] : [0, 1]) {
        const start = performance.now();
        const checksum = e.benchmark_conversion(op, fast, 1000000);
        const elapsed = performance.now() - start;
        assert.equal(checksum, e.benchmark_conversion(op, !fast, 1000000));
        if(round >= 2) times[fast].push(elapsed);
    }
    console.log(JSON.stringify({ conversion: ["load", "exact-store", "rounded-store", "subnormal-fallback"][op],
        reference_ms: median(times[0]), fast_ms: median(times[1]), speedup: median(times[0]) / median(times[1]) }));
}

for(const kind of ["add", "sub", "mul", "div", "sqrt"]) for(const precision of [32,64,80]) {
    const benchmark = kind === "sqrt" ? e.benchmark_native_sqrt : e.benchmark_native_binary;
    const op = ["add", "sub", "mul", "div"].indexOf(kind);
    const times = [[], []];
    for(let round = 0; round < 9; round++) for(const fast of round & 1 ? [1, 0] : [0, 1]) {
        const start = performance.now();
        const checksum = benchmark(fast, precision, 500000, op);
        const elapsed = performance.now() - start;
        assert.equal(checksum, benchmark(!fast, precision, 500000, op));
        if(round >= 2) times[fast].push(elapsed);
    }
    console.log(JSON.stringify({ kind, native_precision: precision, reference_ms: median(times[0]),
        fast_ms: median(times[1]), speedup: median(times[0]) / median(times[1]) }));
}

{
    const times = [[], []];
    for(let round = 0; round < 9; round++) for(const fast of round & 1 ? [1, 0] : [0, 1]) {
        const start = performance.now(), checksum = e.benchmark_scale(fast, 1000000);
        const elapsed = performance.now() - start;
        assert.equal(checksum, e.benchmark_scale(!fast, 1000000));
        if(round >= 2) times[fast].push(elapsed);
    }
    console.log(JSON.stringify({ kind: "scale", reference_ms: median(times[0]), fast_ms: median(times[1]),
        speedup: median(times[0]) / median(times[1]) }));
}
                                                                                                                                                                                                                                                                                                                      source/v64/tests/rust/softfloat_fast_path.rs                                                        0000644 0000000 0000000 00000057731 00000000000 016440  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #![allow(dead_code)]
#[path = "../../src/rust/profiler.rs"]
mod profiler;
include!("../../src/rust/softfloat.rs");

static mut FAILURE: [u64; 10] = [0; 10];
static mut HITS: [u32; 4] = [0; 4];

#[no_mangle]
pub unsafe fn fast_math_result(op: u32, a: u64, b: u64, precision: u8, rounding: u8) -> u64 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    accelerated(op, F80::of_f64(a), F80::of_f64(b)).to_f64()
}

// Bounded Mandelbrot-style recurrence through the production F80 operators.
// Inputs/results stay in binary64 range; PC=53, nearest-even, so both policies
// must produce identical checksums. This is not the EVEREST benchmark.
#[no_mangle]
pub unsafe fn benchmark_fast_math(fast: bool, points: u32) -> u64 {
    set_x87_fast_math(fast);
    extF80_roundingPrecision = 64;
    softfloat_roundingMode = 0;
    let mut sum = 0u64;
    for i in 0..points {
        let cx = F80::of_f64x(std::hint::black_box(-0.2 + (i % 101) as f64 * 0.0001));
        let cy = F80::of_f64x(0.65);
        let mut x = F80::of_f64x(0.1);
        let mut y = F80::of_f64x(0.1);
        for _ in 0..32 {
            let next_x = x * x - y * y + cx;
            y = (x + x) * y + cy;
            x = next_x;
        }
        sum = sum.wrapping_add(x.mantissa ^ y.mantissa);
    }
    sum
}

#[inline(always)]
unsafe fn reference(op: u32, a: F80, b: F80) -> F80 {
    let mut out = F80::ZERO;
    match op {
        0 => extF80M_add(&a, &b, &mut out),
        1 => extF80M_sub(&a, &b, &mut out),
        2 => extF80M_mul(&a, &b, &mut out),
        _ => extF80M_div(&a, &b, &mut out),
    }
    out
}
#[inline(always)]
fn accelerated(op: u32, a: F80, b: F80) -> F80 {
    match op { 0 => a + b, 1 => a - b, 2 => a * b, _ => a / b }
}
fn candidate(op: u32, a: F80, b: F80) -> Option<F80> {
    match op { 0 => a.exact_add(b), 1 => a.exact_add(-b), 2 => a.exact_mul(b), 3 => a.exact_div(b), _ => None }
}
unsafe fn check(op: u32, a: F80, b: F80, flags: u8) -> bool {
    softfloat_exceptionFlags = flags;
    let expected = reference(op, a, b);
    let expected_flags = softfloat_exceptionFlags;
    softfloat_exceptionFlags = flags;
    let actual = accelerated(op, a, b);
    let actual_flags = softfloat_exceptionFlags;
    if expected.mantissa != actual.mantissa || expected.sign_exponent != actual.sign_exponent ||
        expected_flags != actual_flags {
        FAILURE = [op as u64, a.mantissa, a.sign_exponent as u64, b.mantissa, b.sign_exponent as u64,
            expected.mantissa, expected.sign_exponent as u64, actual.mantissa, actual.sign_exponent as u64,
            (expected_flags as u64) << 8 | actual_flags as u64];
        return false;
    }
    if candidate(op, a, b).is_some() { HITS[op as usize] += 1; }
    true
}
unsafe fn reference_cmp(a: &F80, b: &F80, quiet: bool) -> Option<std::cmp::Ordering> {
    use std::cmp::Ordering;
    if if quiet { extF80M_lt_quiet(a, b) } else { extF80M_lt(a, b) } { Some(Ordering::Less) }
    else if if quiet { extF80M_lt_quiet(b, a) } else { extF80M_lt(b, a) } { Some(Ordering::Greater) }
    else if extF80M_eq(a, b) { Some(Ordering::Equal) }
    else { None }
}
unsafe fn check_cmp(a: F80, b: F80, flags: u8) -> bool {
    for quiet in [false, true] {
        softfloat_exceptionFlags = flags;
        let expected = reference_cmp(&a, &b, quiet);
        let expected_flags = softfloat_exceptionFlags;
        softfloat_exceptionFlags = flags;
        let actual = if quiet { a.partial_cmp_quiet(&b) } else { a.partial_cmp(&b) };
        if expected != actual || expected_flags != softfloat_exceptionFlags {
            FAILURE = [4 + quiet as u64, a.mantissa, a.sign_exponent as u64,
                b.mantissa, b.sign_exponent as u64, expected_flags as u64,
                softfloat_exceptionFlags as u64, 0, 0, 0];
            return false;
        }
    }
    true
}
fn next(seed: &mut u64) -> u64 {
    *seed ^= *seed << 13;
    *seed ^= *seed >> 7;
    *seed ^= *seed << 17;
    *seed
}

#[no_mangle]
pub unsafe fn verify(precision: u8, rounding: u8, count: u32) -> u32 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    HITS = [0; 4];
    let mantissas = [0, 1, 0x7FFFFFFFFFFFFFFF, 0x8000000000000000,
        0x8000000000000001, 0x8000000000000800, 0x8000010000000000,
        0x8000000100000000, 0xC000000000000000, 0xFFFFFFFFFFFFFFFF,
        0xFFFFFFFFFFFFF800, 0xFFFFFF0000000000, 0xFFFFFFFF00000000];
    let exponents = [0, 1, 2, 0x3FFE, 0x3FFF, 0x4000, 0x7FFD, 0x7FFE, 0x7FFF];
    let mut index = 0;
    // Cross boundary encodings, including pseudo-denormals, unnormals and NaNs.
    for &am in &mantissas { for &bm in &mantissas {
        for &ae in &exponents { for &be in &exponents { for signs in 0..4 {
            let a = F80 { mantissa: am, sign_exponent: ae | (signs & 1) << 15 };
            let b = F80 { mantissa: bm, sign_exponent: be | (signs >> 1) << 15 };
            if !check_cmp(a, b, if index & 1 == 0 { 0 } else { 0x1F }) { return index + 1; }
            for op in 0..4 {
                index += 1;
                if !check(op, a, b, if index & 1 == 0 { 0 } else { 0x1F }) { return index; }
            }
        } } }
    } }
    let mut native_seed = 0x2345ABCD12345678;
    for i in 0..100000 {
        let mask = if i & 1 == 0 { !0x7FF } else { !0xFFFFFFFFFF };
        let a = F80 { mantissa: (next(&mut native_seed) | 1 << 63) & mask,
            sign_exponent: 0x3FFF + (i % 100) as u16 | ((i & 1) as u16) << 15 };
        let b = F80 { mantissa: (next(&mut native_seed) | 1 << 63) & mask,
            sign_exponent: 0x3FFF + (i % 7) as u16 | ((i & 2) as u16) << 14 };
        for op in 0..4 { index += 1; if !check(op, a, b, (i & 31) as u8) { return index; } }
    }
    // Native reduced-precision division, including inexact ratios, signs,
    // overflow/underflow boundaries and exponent normalization on either side.
    for exponent in [0x3C01,0x3F81,0x3FFE,0x3FFF,0x4000,0x407E,0x43FE] {
        for a in 1..96u64 { for b in 1..96u64 { for signs in 0..4 {
            let x = F80 { mantissa: 0x8000000000000000 | a << 40,
                sign_exponent: exponent | (signs & 1) << 15 };
            let y = F80 { mantissa: 0x8000000000000000 | b << 40,
                sign_exponent: 0x3FFF | (signs >> 1) << 15 };
            index += 1;
            for op in 0..4 { if !check(op, x, y, (index & 31) as u8) { return index; } }
        } } }
    }
    let mut seed = 0xA0B1C2D312345678;
    for i in 0..count {
        let mask = match i % 4 { 0 => !0, 1 => !0x7FF, 2 => !0xFFFFFFFF, _ => !0xFFFFFFFFFF };
        let ae = next(&mut seed) as u16;
        let be = if i & 1 == 0 { ae.wrapping_add((i % 70) as u16) } else { next(&mut seed) as u16 };
        let a = F80 { mantissa: (next(&mut seed) | 1 << 63) & mask, sign_exponent: ae };
        let b = F80 { mantissa: if i % 7 == 0 { 1 << 63 } else { (next(&mut seed) | 1 << 63) & mask },
            sign_exponent: be };
        if !check_cmp(a, b, if i & 1 == 0 { 0 } else { 0x1F }) { return index + 1; }
        for op in 0..4 {
            index += 1;
            if !check(op, a, b, if i & 1 == 0 { 0 } else { 0x1F }) { return index; }
        }
    }
    0
}
#[no_mangle]
pub unsafe fn failure_word(index: usize) -> u64 { FAILURE[index] }
#[no_mangle]
pub unsafe fn hits(op: usize) -> u32 { HITS[op] }

#[no_mangle]
pub unsafe fn benchmark(op: u32, fast: bool, fallback: bool, count: u32) -> u64 {
    match (op, fast) {
        (0, false) => bench::<0, false>(fallback, count),
        (0, true) => bench::<0, true>(fallback, count),
        (1, false) => bench::<1, false>(fallback, count),
        (1, true) => bench::<1, true>(fallback, count),
        (2, false) => bench::<2, false>(fallback, count),
        (2, true) => bench::<2, true>(fallback, count),
        (3, false) => bench::<3, false>(fallback, count),
        _ => bench::<3, true>(fallback, count),
    }
}
unsafe fn bench<const OP: u32, const FAST: bool>(fallback: bool, count: u32) -> u64 {
    extF80_roundingPrecision = 80;
    softfloat_roundingMode = 0;
    let mut checksum = 0u64;
    for i in 0..count {
        let a = F80 { mantissa: 0x8000000000000000 | (i as u64 & 0x7FFFFF) << 40 |
            if fallback { 1 } else { 0 }, sign_exponent: 0x4000 };
        let b = F80 { mantissa: if OP == 3 && !fallback { 0x8000000000000000 }
            else { 0x9000000000000000 | if fallback { 1 } else { 0 } }, sign_exponent: 0x3FFF };
        softfloat_exceptionFlags = 0;
        let a = std::hint::black_box(a);
        let b = std::hint::black_box(b);
        let result = if FAST { accelerated(OP, a, b) } else { reference(OP, a, b) };
        checksum = checksum.wrapping_add(result.mantissa ^ result.sign_exponent as u64 ^ softfloat_exceptionFlags as u64);
    }
    checksum
}

#[no_mangle]
pub unsafe fn benchmark_compare(fast: bool, fallback: bool, count: u32) -> u64 {
    let mut sum = 0u64;
    for i in 0..count {
        let a = std::hint::black_box(F80 { mantissa: 0x8000000000000000 | i as u64,
            sign_exponent: if fallback { 0x7FFF } else { 0x3FFF } });
        let b = std::hint::black_box(F80 { mantissa: 0x8000000000000000 | (i ^ 1) as u64,
            sign_exponent: if fallback { 0x7FFF } else { 0x3FFF } });
        softfloat_exceptionFlags = 0;
        let result = if fast { a.partial_cmp_quiet(&b) } else { reference_cmp(&a, &b, true) };
        sum = sum.wrapping_add(match result { Some(std::cmp::Ordering::Less) => 1,
            Some(std::cmp::Ordering::Equal) => 2, Some(std::cmp::Ordering::Greater) => 3, None => 4 });
        sum = sum.wrapping_add(softfloat_exceptionFlags as u64);
    }
    sum
}

// Compare the conversion entry points against the linked, unchanged SoftFloat.
unsafe fn check_conversion(bits: u32, raw: F80, flags: u8) -> bool {
    softfloat_exceptionFlags = flags;
    let mut expected = F80::ZERO;
    f32_to_extF80M(bits as i32, &mut expected);
    let expected_flags = softfloat_exceptionFlags;
    softfloat_exceptionFlags = flags;
    let actual = F80::of_f32(bits as i32);
    if actual.mantissa != expected.mantissa || actual.sign_exponent != expected.sign_exponent ||
        softfloat_exceptionFlags != expected_flags {
        FAILURE = [10, bits as u64, expected.mantissa, expected.sign_exponent as u64,
            actual.mantissa, actual.sign_exponent as u64, expected_flags as u64,
            softfloat_exceptionFlags as u64, 0, 0];
        return false;
    }
    for value in [raw, expected] {
        softfloat_exceptionFlags = flags;
        let expected = extF80M_to_f32(&value);
        let expected_flags = softfloat_exceptionFlags;
        softfloat_exceptionFlags = flags;
        let actual = value.to_f32();
        if actual != expected || softfloat_exceptionFlags != expected_flags {
            FAILURE = [11, value.mantissa, value.sign_exponent as u64,
                expected as u32 as u64, actual as u32 as u64,
                expected_flags as u64, softfloat_exceptionFlags as u64, 0, 0, 0];
            return false;
        }
    }
    true
}
#[no_mangle]
pub unsafe fn verify_conversions(precision: u8, rounding: u8, count: u32) -> u32 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    let mut index = 0;
    let exponents = [0, 1, 0x3F68, 0x3F69, 0x3F6A, 0x3F7F, 0x3F80, 0x3F81,
        0x3FFF, 0x407D, 0x407E, 0x407F, 0x7FFE, 0x7FFF];
    // Halfway ties of both parities, rounding carry, noncanonical encodings,
    // binary32 normal/subnormal boundaries, NaN payloads and preexisting flags.
    let mantissas = [0, 1, 0x7FFFFFFFFFFFFFFF, 0x8000000000000000,
        0x8000000000000001, 0x8000007FFFFFFFFF, 0x8000008000000000,
        0x8000008000000001, 0x8000018000000000, 0xC000000000000000,
        0xFFFFFF7FFFFFFFFF, 0xFFFFFF8000000000, 0xFFFFFFFFFFFFFFFF];
    for exp in 0..256u32 { for frac in [0, 1, 0x3FFFFF, 0x400000, 0x7FFFFF] {
        for sign in [0, 0x80000000] { for exponent in exponents { for mantissa in mantissas {
            index += 1;
            if !check_conversion(sign | exp << 23 | frac,
                F80 { mantissa, sign_exponent: exponent | ((sign >> 16) as u16) },
                if index & 1 == 0 { 0 } else { 0x1F }) { return index; }
        } } }
    } }
    let mut seed = 0x0123ABCD87654321;
    for i in 0..count {
        let bits = next(&mut seed) as u32;
        let exponent = if i % 2 == 0 { 0x3F81 + (next(&mut seed) % 254) as u16 }
            else { next(&mut seed) as u16 };
        let mantissa = next(&mut seed) | if i % 2 == 0 { 1 << 63 } else { 0 };
        index += 1;
        if !check_conversion(bits, F80 { mantissa, sign_exponent: exponent }, (i & 31) as u8) {
            return index;
        }
    }
    0
}
#[no_mangle]
pub unsafe fn benchmark_conversion(op: u32, fast: bool, count: u32) -> u64 {
    let mut sum = 0u64;
    softfloat_roundingMode = 0;
    for i in 0..count {
        softfloat_exceptionFlags = 0;
        if op == 0 {
            let bits = std::hint::black_box(0x3F800000 | i & 0x7FFFFF);
            let mut value = F80::ZERO;
            if fast { value = F80::of_f32(bits as i32); }
            else { f32_to_extF80M(bits as i32, &mut value); }
            sum = sum.wrapping_add(value.mantissa ^ value.sign_exponent as u64);
        }
        else {
            let value = std::hint::black_box(F80 {
                mantissa: 0x8000000000000000 | (i as u64 & 0x7FFFFF) << 40 |
                    if op == 2 { 0x8000000001 } else { 0 }, sign_exponent: if op == 3 { 0x3F70 } else { 0x3FFF } });
            let bits = if fast { value.to_f32() } else { extF80M_to_f32(&value) };
            sum = sum.wrapping_add(bits as u32 as u64);
        }
        sum = sum.wrapping_add(softfloat_exceptionFlags as u64);
    }
    sum
}

unsafe fn check_wide_conversion(bits: u64, raw: F80, flags: u8) -> bool {
    for value in [raw, F80::of_f64(bits)] {
        softfloat_exceptionFlags = flags;
        let mut expected = F80::ZERO; extF80M_sqrt(&value, &mut expected);
        let expected_flags = softfloat_exceptionFlags;
        softfloat_exceptionFlags = flags;
        let actual = value.sqrt();
        if actual.mantissa != expected.mantissa || actual.sign_exponent != expected.sign_exponent || softfloat_exceptionFlags != expected_flags {
            FAILURE = [28, value.mantissa, value.sign_exponent as u64, expected.mantissa, actual.mantissa,
                expected.sign_exponent as u64, actual.sign_exponent as u64, expected_flags as u64, softfloat_exceptionFlags as u64, 0];
            return false;
        }
    }

    for truncate in [false, true] {
        let rounding = if truncate { 1 } else { softfloat_roundingMode };
        for wide in [false, true] {
            softfloat_exceptionFlags = flags;
            let expected = if wide { extF80M_to_i64(&raw, rounding, false) }
                else { extF80M_to_i32(&raw, rounding, false) as i64 };
            let expected_flags = softfloat_exceptionFlags;
            softfloat_exceptionFlags = flags;
            let actual = match (wide, truncate) { (true,true) => raw.truncate_to_i64(),
                (true,false) => raw.to_i64(), (false,true) => raw.truncate_to_i32() as i64,
                (false,false) => raw.to_i32() as i64 };
            if actual != expected || softfloat_exceptionFlags != expected_flags {
                FAILURE = [24 + wide as u64 + truncate as u64 * 2, raw.mantissa, raw.sign_exponent as u64,
                    expected as u64, actual as u64, expected_flags as u64, softfloat_exceptionFlags as u64, 0, 0, 0];
                return false;
            }
        }
    }

    for op in 0..3 {
        softfloat_exceptionFlags = flags;
        let mut expected = F80::ZERO;
        match op { 0 => f64_to_extF80M(bits, &mut expected),
            1 => i32_to_extF80M(bits as i32, &mut expected),
            _ => i64_to_extF80M(bits as i64, &mut expected) }
        let expected_flags = softfloat_exceptionFlags;
        softfloat_exceptionFlags = flags;
        let actual = match op { 0 => F80::of_f64(bits), 1 => F80::of_i32(bits as i32), _ => F80::of_i64(bits as i64) };
        if actual.mantissa != expected.mantissa || actual.sign_exponent != expected.sign_exponent || softfloat_exceptionFlags != expected_flags {
            FAILURE = [20 + op, bits, expected.mantissa, expected.sign_exponent as u64,
                actual.mantissa, actual.sign_exponent as u64, expected_flags as u64, softfloat_exceptionFlags as u64, 0, 0];
            return false;
        }
        for value in [raw, expected] {
            softfloat_exceptionFlags = flags;
            let expected = extF80M_to_f64(&value);
            let expected_flags = softfloat_exceptionFlags;
            softfloat_exceptionFlags = flags;
            let actual = value.to_f64();
            if actual != expected || softfloat_exceptionFlags != expected_flags {
                FAILURE = [23, value.mantissa, value.sign_exponent as u64, expected, actual,
                    expected_flags as u64, softfloat_exceptionFlags as u64, 0, 0, 0]; return false;
            }
        }
    }
    true
}
#[no_mangle]
pub unsafe fn verify_wide_conversions(precision: u8, rounding: u8, count: u32) -> u32 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    let mut index = 0;
    for exponent in [0,1,0x3BFE,0x3BFF,0x3C00,0x3C01,0x3FFD,0x3FFE,0x3FFF,0x401D,0x401E,0x401F,0x403D,0x403E,0x403F,0x43FD,0x43FE,0x43FF,0x7FFE,0x7FFF] {
        for mantissa in [0,1,0x7FFFFFFFFFFFFFFF,0x8000000000000000,0x80000000000003FF,
            0x8000000000000400,0x8000000000000401,0x8000000000000C00,0xFFFFFFFFFFFFFFFF] {
            for sign in [0,0x8000] { for exp in 0..2048u64 { for frac in [0,1,0x8000000000000,0xFFFFFFFFFFFFF] {
                index += 1;
                if !check_wide_conversion((sign as u64) << 48 | exp << 52 | frac,
                    F80 { mantissa, sign_exponent: sign | exponent }, (index & 31) as u8) { return index; }
            } } }
        }
    }
    // Exact normal binary64 stores, including both ends of the exponent
    // range and the largest significand. Vary existing sticky flags too.
    for exponent in 1..0x7FFu64 {
        for fraction in [0, 1, 0x8000000000000, 0xFFFFFFFFFFFFF] {
            for sign in [0, 0x8000u16] {
                let bits = ((sign as u64) << 48) | (exponent << 52) | fraction;
                let raw = F80 { mantissa: (fraction | 0x10000000000000) << 11,
                    sign_exponent: sign | (exponent as u16 + 0x3C00) };
                index += 1;
                if !check_wide_conversion(bits, raw, (index & 31) as u8) { return index; }
            }
        }
    }
    let mut seed = 0x13579BDF02468ACE;
    for _ in 0..count {
        let bits = next(&mut seed);
        let raw = F80 { mantissa: next(&mut seed), sign_exponent: next(&mut seed) as u16 };
        index += 1;
        if !check_wide_conversion(bits, raw, (index & 31) as u8) { return index; }
    }
    0
}

#[no_mangle]
pub unsafe fn benchmark_native_binary(fast: bool, precision: u8, count: u32, op: u32) -> u64 {
    extF80_roundingPrecision = precision; softfloat_roundingMode = 0;
    let mut sum = 0u64;
    for i in 0..count {
        let a = std::hint::black_box(F80 { mantissa: 0x8000000000000000 | (i as u64 & 0x7FFFFF) << if precision == 32 { 40 } else { 11 },
            sign_exponent: 0x4000 });
        let b = std::hint::black_box(F80 { mantissa: 0xC000000000000000 | (i as u64 & 0x7FFFFF) << if precision == 32 { 40 } else { 11 },
            sign_exponent: 0x3FFF });
        softfloat_exceptionFlags = 0;
        let result = if fast { accelerated(op, a, b) } else { reference(op, a, b) };
        sum = sum.wrapping_add(result.mantissa ^ result.sign_exponent as u64 ^ softfloat_exceptionFlags as u64);
    }
    sum
}

#[no_mangle]
pub unsafe fn benchmark_native_sqrt(fast: bool, precision: u8, count: u32) -> u64 {
    extF80_roundingPrecision = precision; softfloat_roundingMode = 0;
    let mut sum = 0u64;
    for i in 0..count {
        let a = std::hint::black_box(F80 { mantissa: 0x8000000000000000 | (i as u64 & 0x7FFFFF) << 40,
            sign_exponent: 0x4000 });
        softfloat_exceptionFlags = 0;
        let result = if fast { a.sqrt() } else { let mut out = F80::ZERO; extF80M_sqrt(&a, &mut out); out };
        sum = sum.wrapping_add(result.mantissa ^ result.sign_exponent as u64 ^ softfloat_exceptionFlags as u64);
    }
    sum
}

#[no_mangle]
pub unsafe fn verify_integral(precision: u8, rounding: u8, count: u32) -> u32 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    let mut seed = 0xF21C53123864ABu64;
    for i in 0..count {
        let exponent = if i % 3 == 0 { (next(&mut seed) as u16) & 0x7FFF }
            else { 0x3FBC + (next(&mut seed) % 140) as u16 };
        let mantissa = match i % 8 {
            0 => 0, 1 => 1, 2 => 1 << 63, 3 => u64::MAX, _ => next(&mut seed) | 1 << 63,
        };
        let value = F80 { mantissa, sign_exponent: exponent | ((i & 1) as u16) << 15 };
        for trunc in [false, true] {
            let flags = if i % 2 == 0 { 0 } else { 0x1F };
            softfloat_exceptionFlags = flags;
            let mut expected = F80::ZERO;
            extF80M_roundToInt(&value, if trunc { 1 } else { rounding }, false, &mut expected);
            let expected_flags = softfloat_exceptionFlags;
            softfloat_exceptionFlags = flags;
            let actual = if trunc { value.trunc() } else { value.round() };
            if actual.mantissa != expected.mantissa || actual.sign_exponent != expected.sign_exponent
                || softfloat_exceptionFlags != expected_flags {
                FAILURE = [20, mantissa, value.sign_exponent as u64, rounding as u64, trunc as u64,
                    expected.mantissa, expected.sign_exponent as u64, actual.mantissa,
                    actual.sign_exponent as u64, ((expected_flags as u64) << 8) | softfloat_exceptionFlags as u64];
                return i + 1;
            }
        }
    }
    0
}

#[no_mangle]
pub unsafe fn benchmark_integral(fast: bool, count: u32) -> u64 {
    softfloat_roundingMode = 0;
    extF80_roundingPrecision = 80;
    let mut checksum = 0u64;
    for i in 0..count {
        let value = std::hint::black_box(F80 { mantissa: 0xABCDEF1234567890u64.wrapping_add(i as u64),
            sign_exponent: 0x3FFE + (i & 63) as u16 });
        let result = if fast { value.round() } else {
            let mut result = F80::ZERO;
            extF80M_roundToInt(&value, 0, false, &mut result);
            result
        };
        checksum ^= result.mantissa.wrapping_add(result.sign_exponent as u64);
    }
    checksum
}

#[no_mangle]
pub unsafe fn verify_scale(precision: u8, rounding: u8, count: u32) -> u32 {
    extF80_roundingPrecision = precision;
    softfloat_roundingMode = rounding;
    let mut seed = 0x834256782382A3u64;
    for i in 0..count {
        let a = F80 { mantissa: next(&mut seed), sign_exponent: next(&mut seed) as u16 };
        let b = if i % 8 == 0 {
            F80 { mantissa: next(&mut seed), sign_exponent: next(&mut seed) as u16 }
        } else { F80::of_f64x((i as i32 % 2052 - 1026) as f64 + 0.5) };
        let flags = if i % 2 == 0 { 0 } else { 0x1F };
        softfloat_exceptionFlags = flags;
        let expected = a * b.trunc().two_pow();
        let expected_flags = softfloat_exceptionFlags;
        softfloat_exceptionFlags = flags;
        let actual = a.scale(b);
        if actual.mantissa != expected.mantissa || actual.sign_exponent != expected.sign_exponent
            || softfloat_exceptionFlags != expected_flags {
            FAILURE = [21, a.mantissa, a.sign_exponent as u64, b.mantissa, b.sign_exponent as u64,
                expected.mantissa, expected.sign_exponent as u64, actual.mantissa,
                actual.sign_exponent as u64, ((expected_flags as u64) << 8) | softfloat_exceptionFlags as u64];
            return i + 1;
        }
    }
    0
}
#[no_mangle]
pub unsafe fn benchmark_scale(fast: bool, count: u32) -> u64 {
    softfloat_roundingMode = 0;
    extF80_roundingPrecision = 80;
    let mut checksum = 0u64;
    for i in 0..count {
        let a = std::hint::black_box(F80 { mantissa: 0xABCDEF1234567890u64.wrapping_add(i as u64), sign_exponent: 0x3FFF });
        let b = F80::of_i32((i as i32 & 31) - 16);
        let result = if fast { a.scale(b) } else { a * b.trunc().two_pow() };
        checksum ^= result.mantissa.wrapping_add(result.sign_exponent as u64);
    }
    checksum
}
                                       source/v64/tests/rust/sse3.mjs                                                                      0000644 0000000 0000000 00000035550 00000000000 013423  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x210000;
const machines = [];
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const data = new Uint8Array(8192), dv = new DataView(data.buffer);
const load = (r, a) => [0xF3,0x0F,0x6F,5 | r << 3,...u32(a)];
const store = (r, a) => [0xF3,0x0F,0x7F,5 | r << 3,...u32(a)];
const ops = [["addsubps",0xF2,0xD0,4], ["addsubpd",0x66,0xD0,8],
    ["haddps",0xF2,0x7C,4], ["haddpd",0x66,0x7C,8],
    ["hsubps",0xF2,0x7D,4], ["hsubpd",0x66,0x7D,8],
    ["movddup",0xF2,0x12,8], ["movsldup",0xF3,0x12,4], ["movshdup",0xF3,0x16,4],
    ["lddqu",0xF2,0xF0,1]];
async function run(vm, program, warm = true) {
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    // Programs reuse CODE: start each warm run from an empty compiler state
    // (compiled code needs more heat to recompile a page after each rewrite).
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    // Defined EFLAGS: programs record them, and a previous program's flags
    // depend on where its VM stopped (an exit from compiled code or the loop head).
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 10000;
    while(word(vm, 0x600) !== 0xCAFE || warm && vm !== machines[0] && compiled_activations(e) === start) {
        assert(performance.now() < deadline, "SSE3 program/JIT timeout"); await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
// SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
const ENABLE_SSE = [0x0F,0x20,0xE0,0x0D,...u32(0x600),0x0F,0x22,0xE0];
function loop(body) {
    const p = [...ENABLE_SSE,...body,0xC7,0x05,...u32(0x600),...u32(0xCAFE)];
    p.push(0xE9,...u32(-p.length-5)); return p;
}
function calculate(name, width, source, target) {
    if(name === "lddqu") return source.slice();
    const output = new Uint8Array(16), out = new DataView(output.buffer);
    const a = new DataView(source.buffer, source.byteOffset, 16), b = new DataView(target.buffer, target.byteOffset, 16);
    for(let i = 0; i < 16 / width; i++) {
        if(name.startsWith("mov")) {
            const lane = name === "movddup" ? 0 : (i & ~1) + Number(name === "movshdup");
            output.set(source.slice(lane*width,(lane+1)*width),i*width); continue;
        }
        const get = (v, lane) => width === 8 ? v.getFloat64(lane*8,true) : v.getFloat32(lane*4,true);
        let x, y;
        if(name.startsWith("addsub")) { x = get(b,i); y = get(a,i); }
        else {
            const input = i < 8 / width ? b : a, lane = (i % (8/width))*2;
            x = get(input,lane); y = get(input,lane+1);
        }
        const value = name.startsWith("hsub") || name.startsWith("addsub") && i % 2 === 0 ? x-y : x+y;
        if(width === 8) out.setFloat64(i*8,value,true); else out.setFloat32(i*4,value,true);
    }
    return output;
}
try {
    // Compare the interpreter with the page tier within one build (the region
    // tiers, a second compiled arm, were deleted in M11).
    for(const options of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)]) {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        machines.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded",resolve));
        vm.run();
        const deadline = performance.now()+10000;
        while(word(vm,0x500) !== 0xCAFE) { assert(performance.now()<deadline); await sleep(1); }
        await vm.stop();
    }
    // CPUID feature bits and legacy SAHF/LAHF are separate capabilities.
    const flags_program = [0xB8,...u32(1),0x0F,0xA2,0x89,0x0D,...u32(OUT),0x89,0x15,...u32(OUT+4)];
    for(let ah = 0; ah < 256; ah++) {
        flags_program.push(0xB8,...u32(0x7FFFFFFF),0x83,0xC0,1,0xB4,ah,0x9E,0x9F,
            0x0F,0xB6,0xC4,0xA3,...u32(OUT+16+ah*8),0x9C,0x58,0xA3,...u32(OUT+20+ah*8));
    }
    for(const vm of machines) {
        await run(vm,loop(flags_program));
        assert.equal(word(vm,OUT)&1,1,"CPUID advertises SSE3");
        assert.equal(word(vm,OUT)&8,0,"MONITOR/MWAIT has a separate, disabled CPUID bit");
        assert.equal(word(vm,OUT+4)&(1<<24),1<<24,"CPUID advertises FXSR");
        for(let ah = 0; ah < 256; ah++) {
            assert.equal(word(vm,OUT+16+ah*8),(ah&0xD5)|2,"SAHF/LAHF selected status flags");
            assert.equal(word(vm,OUT+20+ah*8)&0x8D5,(ah&0xD5)|0x800,"SAHF preserves OF");
        }
    }
    console.log("PASS: CPUID SSE3/FXSR, disabled MONITOR, and 256 SAHF/LAHF flag patterns");
    let cases = 0;
    for(const [name,prefix,op,width] of ops) for(const special of [false,true]) {
        for(let i = 0; i < data.length; i++) data[i] = (i*37 ^ i>>3)&255;
        if(width > 1) for(let i = 0; i < data.length/width; i++) {
            if(special) {
                const patterns = width === 8 ? [0n,0x8000000000000000n,1n,0x7FF0000000000000n,0xFFF0000000000000n,0x7FF123456789ABCDn,0x7FFABCDE01234567n] :
                    [0n,0x80000000n,1n,0x7F800000n,0xFF800000n,0x7F812345n,0x7FCABCDEn];
                if(width === 8) dv.setBigUint64(i*8,patterns[i%patterns.length],true);
                else dv.setUint32(i*4,Number(patterns[i%patterns.length]),true);
            } else if(width === 8) dv.setFloat64(i*8,((i*19)%127-63)*0.125,true);
            else dv.setFloat32(i*4,((i*19)%127-63)*0.125,true);
        }
        const p = [], expected = [];
        for(let n = 0; n < 96; n++) {
            const src = n >> 3 & 7, dst = n & 7, memory = name === "lddqu" || n >= 64;
            // (an m128 operand must be 16-byte aligned, but MOVDDUP's m64 and LDDQU's)
            const offset = name === "movddup" || name === "lddqu" ? [0,1,4080,4095][n&3] : [0,16,4080,4096][n&3];
            const source = memory ? offset : src*16, target = 512+dst*16;
            p.push(...load(dst,DATA+target),...load(src,DATA+source));
            p.push(0xF9,prefix,0x0F,op,(memory ? 5 : 0xC0|src)|dst<<3,...(memory ? u32(DATA+source) : []),
                ...store(dst,OUT+n*32),0x9C,0x58,0xA3,...u32(OUT+n*32+16));
            expected.push(calculate(name,width,data.slice(source,source+16),data.slice(src === dst ? source : target,(src === dst ? source : target)+16)));
        }
        const results = [];
        for(const vm of machines) {
            vm.write_memory(data,DATA); vm.write_memory(new Uint8Array(8192),OUT);
            await run(vm,loop(p));
            const bytes = Uint8Array.from(vm.read_memory(OUT,96*32)); results.push(bytes);
            for(let n = 0; n < 96; n++) {
                assert.equal(bytes[n*32+16]&1,1,`${name} preserves carry`);
                // Special-value payloads are compared bitwise between core
                // paths; the independent JS oracle covers exact finite inputs.
                if(!special && (!name.startsWith("h") && !name.startsWith("addsub") || n < 64 || name.startsWith("addsub")))
                    assert.deepEqual(bytes.slice(n*32,n*32+16),expected[n],`${name} oracle ${n}`);
            }
        }
        assert.deepEqual(results[1],results[0],`${name}: interpreter/page tier bits`);
        cases += 96;
    }
    console.log(`PASS: ${cases} SSE3 cases, finite oracle, special bits, aliases and memory boundaries`);

    // The three duplications must see dirty cached inputs and feed cached
    // arithmetic; memory loads and FXSAVE are materialization boundaries.
    for(const special of [false,true]) {
        for(let i = 0; i < 128; i++) dv.setUint32(i*4,special ? [0x7FC12345,0x80000000,1,0x3F800000][i&3] : 0x3F800000,true);
        const p = [0xDB,0xE3];
        for(let r = 0; r < 8; r++) p.push(...load(r,DATA+r*16));
        for(let i = 0; i < 96; i++) {
            const [,prefix,op] = ops[i%9];
            p.push(prefix,0x0F,op,0xC0|(i&7)<<3|((i+1)&7));
            if(i%19 === 18) p.push(...load(i&7,DATA));
        }
        for(let r = 0; r < 8; r++) p.push(...store(r,OUT+r*16));
        p.push(0x0F,0xAE,0x05,...u32(OUT+512));
        const results = [];
        for(const vm of machines) {
            vm.write_memory(data,DATA); vm.write_memory(new Uint8Array(8192),OUT);
            await run(vm,loop(p)); results.push(Uint8Array.from(vm.read_memory(OUT,800)));
        }
        assert.deepEqual(results[1],results[0],"SSE3 mixed sequence, including NaN fallback: interpreter/page tier");
    }
    console.log("PASS: mixed SSE3 cached sequences, alias chains, memory barriers and FXSAVE");

    // FXSAVE/FXRSTOR preserves the live x87 stack and all eight XMMs.
    dv.setUint32(8000,0x1F80,true);
    const fx = [0xDB,0xE3];
    for(let i = 0; i < 8; i++) fx.push(0xD9,0xE8);
    fx.push(0xD9,0xF7,0xD9,0xF7,0xD9,0xF7,0x0F,0xAE,0x15,...u32(DATA+8000));
    for(let r = 0; r < 8; r++) fx.push(...load(r,DATA+r*16));
    fx.push(0x0F,0xAE,0x05,...u32(OUT),0xDB,0xE3);
    for(let r = 0; r < 8; r++) fx.push(0x66,0x0F,0xEF,0xC0|r<<3|r);
    fx.push(0x0F,0xAE,0x0D,...u32(OUT),0x0F,0xAE,0x05,...u32(OUT+512));
    for(const vm of machines) {
        vm.write_memory(data,DATA); vm.write_memory(new Uint8Array(1024),OUT);
        await run(vm,loop(fx));
        assert.deepEqual(Uint8Array.from(vm.read_memory(OUT,512)),Uint8Array.from(vm.read_memory(OUT+512,512)),"FXSAVE/FXRSTOR live state");
    }
    // FISTTP must truncate under every rounding control, then pop ST(0).
    let integer_cases = 0;
    for(const pc of [0,2,3]) for(let rc = 0; rc < 4; rc++) {
        const control = 0x7F|pc<<8|rc<<10;
        dv.setUint16(7900,control,true);
        const p = [], expected = [];
        for(const [size,opcode] of [[2,0xDF],[4,0xDB],[8,0xDD]])
            for(const input of [0,-0,1.75,-1.75,32768,-32769,2147483648,-2147483649,2**63,-(2**63),Infinity,NaN]) {
                const n = expected.length;
                dv.setFloat64(5000+n*8,input,true);
                p.push(0xDB,0xE3,0xD9,0x2D,...u32(DATA+7900),0xDD,0x05,...u32(DATA+5000+n*8),
                    opcode,0x0D,...u32(OUT+n*16),0xDD,0x3D,...u32(OUT+n*16+8),0xD9,0x3D,...u32(OUT+n*16+10));
                const min = -(1n<<BigInt(size*8-1)), max = -min-1n;
                let value = Number.isFinite(input) ? BigInt(Math.trunc(input)) : min;
                if(value < min || value > max) value = min;
                expected.push({ size,value });
            }
        const results = [];
        for(const vm of machines) {
            vm.write_memory(data,DATA); vm.write_memory(new Uint8Array(8192),OUT);
            await run(vm,loop(p));
            const bytes = Uint8Array.from(vm.read_memory(OUT,expected.length*16)), v = new DataView(bytes.buffer);
            results.push(bytes);
            for(const [n,{ size,value }] of expected.entries()) {
                const actual = size === 8 ? v.getBigInt64(n*16,true) : BigInt(size === 4 ? v.getInt32(n*16,true) : v.getInt16(n*16,true));
                assert.equal(actual,value,"FISTTP truncation and integer indefinite");
                assert.equal(v.getUint16(n*16+8,true)&0x3800,0,"FISTTP pops ST(0)");
                assert.equal(v.getUint16(n*16+10,true),control,"FISTTP preserves rounding control");
            }
        }
        assert.deepEqual(results[1],results[0],"FISTTP interpreter/page tier result and status");
        integer_cases += expected.length;
    }
    console.log(`PASS: FXSAVE/FXRSTOR state and ${integer_cases} FISTTP cases across 12 controls`);

    // Real guest exception delivery after the code has reached the JIT.
    const idt = 0x250000, descriptor = 0x251000, handler = 0x280000;
    let faults = 0;
    const fault_cases = [];
    for(const [name,prefix,op] of ops.filter(x => x[2] === 0xD0 || x[0] === "lddqu")) {
        for(const vector of [7,6,14,...(op === 0xD0 ? [13] : [])]) {
            fault_cases.push({ name, vector, instruction: [prefix,0x0F,op,5,
                ...u32(vector === 14 ? op === 0xD0 ? 0x802000 : 0x801FF8 : vector === 13 ? DATA+1 : DATA)] });
        }
    }
    fault_cases.push({ name: "lddqu register invalid", vector: 6, instruction: [0xF2,0x0F,0xF0,0xC1] });
    for(const { name,vector,instruction } of fault_cases) {
        const p = [0x0F,0x01,0x1D,...u32(descriptor),...ENABLE_SSE,
            0x0F,0x20,0xC0,0x83,0xE0,0xF3,0x0F,0x22,0xC0,...load(0,DATA),...load(1,DATA),0xF3,0x0F,0x12,0xC9];
        if(vector === 7 || vector === 6 && !name.includes("invalid"))
            p.push(0x0F,0x20,0xC0,0x83,0xC8,vector === 7 ? 8 : 4,0x0F,0x22,0xC0);
        const fault_eip = CODE+p.length;
        p.push(...instruction,0xC7,0x05,...u32(0x600),...u32(0xCAFE));
        p.push(0x80,0x3D,...u32(0x604),0,0x75,5);
        p.push(0xE9,...u32(-p.length-5),0xF4);
        const frame = vector === 13 || vector === 14 ? 4 : 0;
        const h = [0x8B,0x44,0x24,frame,0xA3,...u32(OUT),0x83,0x44,0x24,frame,instruction.length];
        if(frame) h.push(0x83,0xC4,4);
        else h.push(0x0F,0x20,0xC0,0x83,0xE0,0xF3,0x0F,0x22,0xC0);
        h.push(0xCF);
        for(const vm of machines) {
            vm.write_memory(data,DATA);
            vm.write_memory(Uint8Array.from([handler&255,handler>>>8&255,8,0,0,0x8E,handler>>>16&255,handler>>>24]),idt+vector*8);
            vm.write_memory(Uint8Array.from([255,7,...u32(idt)]),descriptor);
            vm.write_memory(Uint8Array.from(h),handler); vm.write_memory(new Uint8Array(1),0x604);
            await run(vm,p);
            // (the hot run stops anywhere in its loop: its fault record, not its registers)
            assert.equal(word(vm,OUT),fault_eip,`${name} precise #${vector} (hot)`);
            vm.write_memory(new Uint8Array(4),OUT);
            vm.write_memory(Uint8Array.of(1),0x604); await run(vm,p,false);
            assert.equal(word(vm,OUT),fault_eip,`${name} precise #${vector}`);
            assert.deepEqual(new Uint8Array(vm.v86.cpu.reg_xmm32s.buffer,vm.v86.cpu.reg_xmm32s.byteOffset,16),data.slice(0,16),`${name} fault preserves XMM0`);
            assert.deepEqual(new Uint8Array(vm.v86.cpu.reg_xmm32s.buffer,vm.v86.cpu.reg_xmm32s.byteOffset+16,16),
                calculate("movsldup",4,data.slice(0,16),data.slice(0,16)),"fault materializes earlier cached duplication");
        }
        faults++;
    }
    console.log(`PASS: ${faults} guest #NM/#UD/#GP/#PF cases preserve XMM destination and EIP`);
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                        source/v64/tests/rust/sse4.mjs                                                                      0000644 0000000 0000000 00000130317 00000000000 013421  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SSE4.1 and SSE4.2 integer forms in the 32-bit engines (docs/simd-xsave-plan.md
// 7.2, 7.3, P4b) against a model of the SDM's pseudocode written here
// (tests/rust/sse4_model.mjs, independent of src/rust/cpu/simd_int.rs):
// register and memory sources, the destination as the source and as XMM0
// (BLENDV's mask), every imm8 of the blends, INSERTPS and MPSADBW, the
// element selection of PEXTR*/PINSR* to and from registers and memory, the
// flags of PTEST and the exceptions: #UD without the feature, with CR0.EM,
// without CR4.OSFXSR, with LOCK or an F2/F3 prefix and for MOVNTDQA from a
// register, #NM with CR0.TS, #GP(0) for a misaligned m128 (none for the
// narrow operands) and #PF, each without effect. SSE4.2: PCMPESTRI/M and
// PCMPISTRI/M for every imm8 (ECX or XMM0 and the flags; explicit lengths
// zero, negative, the most negative, beyond the register; an unaligned m128;
// the whole m128 read though a string ends early), CRC32 from 8-, 16- and
// 32-bit registers (AH-BH too) and memory (flags kept, no XMM state checks),
// and POPCNT, which has its own CPUID bit. Every case runs in the
// interpreter, then hot under the page tier.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { Fp, compare_strings, crc32, extract, get, insert, insertps, ptest, round_lane, set, sse4_38, sse4_3a } from "./sse4_model.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const hex = bytes => Buffer.from(bytes).toString("hex");
const CODE = 0x100000, DEST = 0x200000, SOURCE = 0x210000, MASK = 0x220000, OUT = 0x230000, FAULT = 0x24F000, SKIP = 0x24F100;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000, ABSENT = 0x2F0000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

// Operand data: random bytes, and lanes of edge values (8 kinds)
const make_data = seed => {
    const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
    const a = new Uint8Array(512 * 16), v = new DataView(a.buffer);
    const edges = {
        1: [0x00, 0x01, 0x7F, 0x80, 0x81, 0xFE, 0xFF, 0x40],
        2: [0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0x4000, 0xC000],
        4: [0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0x0000FFFF, 0xFFFF0000],
    };
    for(let n = 0; n < 512; n++)
    {
        const kind = n % 8;
        for(let i = 0; i < 16; i++)
        {
            if(kind < 3) a[n * 16 + i] = random();
            else if(kind === 3) a[n * 16 + i] = edges[1][random() & 7];
            else if(kind === 4 && i % 2 === 0) v.setUint16(n * 16 + i, edges[2][random() & 7], true);
            else if(kind === 5 && i % 4 === 0) v.setUint32(n * 16 + i, edges[4][random() & 7], true);
            // (equal halves: PCMPEQQ, PHMINPOSUW ties)
            else if(kind === 6) a[n * 16 + i] = i < 8 ? random() & 3 : a[n * 16 + i - 8];
            else if(kind === 7) a[n * 16 + i] = (random() & 1) * 0xFF;
        }
    }
    return a;
};
const destinations = make_data(0x5EED1234), sources = make_data(0x0BADC0DE), masks = make_data(0x13579BDF);
// Strings for PCMPxSTRx: a small alphabet (so that elements match and fall in
// ranges), bytes of either sign and words; a zero element ends an implicit
// string (none in a fifth of them)
const make_strings = seed => {
    const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
    const a = new Uint8Array(512 * 16);
    const alphabets = [[0x61, 0x62, 0x63, 0x64], [0x41, 0x61, 0x7F, 0x80, 0xFF, 0x01], [0x61, 0x62]];
    for(let n = 0; n < 512; n++)
    {
        const alphabet = alphabets[n % 3], end = random() % 20;
        for(let i = 0; i < 16; i++) a[n * 16 + i] = alphabet[random() % alphabet.length];
        // (as words: the end in either byte of an element, or both)
        if(end < 16) a[n * 16 + end] = 0;
        if(end < 16 && n % 4 === 0) a[n * 16 + (end ^ 1)] = 0;
    }
    return a;
};
const needles = make_strings(0x600DF00D), haystacks = make_strings(0xFEEDFACE);
// explicit lengths (EAX, EDX): within, at and beyond the elements, negative, the extremes
const LENGTHS = [0, 1, 2, 3, 7, 8, 9, 15, 16, 17, 100, -1, -2, -7, -8, -9, -16, -17, 0x7FFFFFFF, -0x80000000, -0x7FFFFFFF];

const LOAD = [0xF3, 0x0F, 0x6F], STORE = [0xF3, 0x0F, 0x7F];
const absolute = (r, a) => [0x05 | r << 3, ...u32(a)];
const mov_r32 = (r, v) => [0xB8 | r, ...u32(v)];
const store_r32 = (r, a) => [0x89, 0x05 | r << 3, ...u32(a)];
const PUSHF_STORE = a => [0x9C, 0x58, 0xA3, ...u32(a)];
/** 66 0F map op ModRM(reg, rm or [address]) imm8 */
const encode = (map, op, reg, rm, address, imm8, prefixes = []) => [...prefixes, 0x66, 0x0F, map, op,
    ...(address === undefined ? [0xC0 | reg << 3 | rm] : absolute(reg, address)), ...(imm8 === undefined ? [] : [imm8])];
const OSFXSR = [0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0]; // CR4 |= OSFXSR | OSXMMEXCPT
const NO_OSFXSR = [0x0F, 0x20, 0xE0, 0x25, ...u32(~0x200 >>> 0), 0x0F, 0x22, 0xE0];
const CLTS = [0x0F, 0x06];
const SET_CR0 = bits => [0x0F, 0x20, 0xC0, 0x0D, ...u32(bits), 0x0F, 0x22, 0xC0];
const CLEAR_CR0 = bits => [0x0F, 0x20, 0xC0, 0x25, ...u32(~bits >>> 0), 0x0F, 0x22, 0xC0];

// The forms of 66 0F 38 with simd_int::sse4 semantics: [op, name, memory bytes]
const BINARY = [[0x10, "pblendvb"], [0x14, "blendvps"], [0x15, "blendvpd"], [0x20, "pmovsxbw", 8], [0x21, "pmovsxbd", 4],
    [0x22, "pmovsxbq", 2], [0x23, "pmovsxwd", 8], [0x24, "pmovsxwq", 4], [0x25, "pmovsxdq", 8], [0x28, "pmuldq"], [0x29, "pcmpeqq"],
    [0x2B, "packusdw"], [0x30, "pmovzxbw", 8], [0x31, "pmovzxbd", 4], [0x32, "pmovzxbq", 2], [0x33, "pmovzxwd", 8],
    [0x34, "pmovzxwq", 4], [0x35, "pmovzxdq", 8], [0x37, "pcmpgtq"], [0x38, "pminsb"], [0x39, "pminsd"], [0x3A, "pminuw"],
    [0x3B, "pminud"], [0x3C, "pmaxsb"], [0x3D, "pmaxsd"], [0x3E, "pmaxuw"], [0x3F, "pmaxud"], [0x40, "pmulld"],
    [0x41, "phminposuw"]].map(([op, name, bytes = 16]) => ({ op, name, bytes }));
// 66 0F 3A with imm8 between XMM operands
const IMMEDIATE = [[0x0C, "blendps"], [0x0D, "blendpd"], [0x0E, "pblendw"], [0x21, "insertps"], [0x42, "mpsadbw"]];
const EXTRACT = [[0x14, "pextrb", 1], [0x15, "pextrw", 2], [0x16, "pextrd", 4], [0x17, "extractps", 4]];
const INSERT = [[0x20, "pinsrb", 1], [0x22, "pinsrd", 4]];
const GPRS = [0, 1, 2, 3, 5, 6, 7]; // (not ESP)
// The forms with page tier templates (P4b part 4): one Wasm SIMD operation (66 0F
// 38) and the blends with imm8 (66 0F 3A); PBLENDVB, BLENDVPS and BLENDVPD
// (P5 part 5; IR Tier-0, deleted in P7.5, also had PMULDQ's)
const TEMPLATED_38 = [0x10, 0x14, 0x15, 0x29, 0x2B, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40];
const TEMPLATED_3A = [0x0C, 0x0D, 0x0E];
// PCMPESTRM, PCMPESTRI, PCMPISTRM, PCMPISTRI
const STRINGS = [[0x60, "pcmpestrm"], [0x61, "pcmpestri"], [0x62, "pcmpistrm"], [0x63, "pcmpistri"]];
/** CRC32 r32, r/m8 (F2 0F 38 F0), r/m16 (66 F2 0F 38 F1), r/m32 (F2 0F 38 F1) */
const crc32_form = (bytes, reg, rm, address) => [...bytes === 2 ? [0x66] : [], 0xF2, 0x0F, 0x38, bytes === 1 ? 0xF0 : 0xF1,
    ...(address === undefined ? [0xC0 | reg << 3 | rm] : absolute(reg, address))];
/** POPCNT r16/r32, r/m16/r/m32 */
const popcnt_form = (bytes, reg, rm, address) => [...bytes === 2 ? [0x66] : [], 0xF3, 0x0F, 0xB8,
    ...(address === undefined ? [0xC0 | reg << 3 | rm] : absolute(reg, address))];
// flags before: OF, SF, AF, CF (0x7F + 1, STC) or ZF, PF (XOR EAX, EAX)
const FLAGS_BEFORE = [[[0xB0, 0x7F, 0x04, 0x01, 0xF9], 0x891], [[0x31, 0xC0], 0x44]];

const machines = [];
async function run(vm, program, warm, interpreter, label)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    // (the page tier's step counts are the hot run's: x64_page_steps)
    else e["x64_page_steps_freeze"]();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, `program/JIT timeout (${label}: ${program.length} bytes, done ${word(vm, 0x600) === 0xCAFE}, compiled ${compiled_activations(e) - start})`);
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
// the body repeats until byte 0x604 is set, then halts after one more round
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it, the faulting EIP, CR2 and the error code, and skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58, 0xA3, ...u32(FAULT + 12));
    p.push(0xC7, 0x05, ...u32(FAULT), ...u32(vector));
    p.push(0x8B, 0x04, 0x24, 0xA3, ...u32(FAULT + 4));
    p.push(0x0F, 0x20, 0xD0, 0xA3, ...u32(FAULT + 8));
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true]];
const PROLOGUE = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...CLTS, ...CLEAR_CR0(4), ...OSFXSR];
/** Runs `program` on each machine of `set`: warm (compiled), then once more
 * cold; returns what `read` reads after each run (the cold run is mostly
 * interpreted: the program was rewritten) */
async function run_all(program, before = () => {}, set = machines, read = () => null)
{
    const results = [];
    for(const [i, vm] of set.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], i) => {
            const h = HANDLER + i * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(new Uint8Array(16), FAULT);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, loop([...PROLOGUE, ...program]), warm, vm === set[0], `machine ${i} ${warm ? "hot" : "one round"}`);
            results.push({ label: `machine ${i} ${warm ? "hot" : "one round"}`, data: read(vm) });
        }
    }
    return results;
}
/** Runs `program` on every machine; the results of OUT (`length` bytes) of
 * each run must agree; returns the interpreter's */
async function run_out(program, before, length, label)
{
    const results = await run_all(program, before, machines, vm => bytes(vm, OUT, length));
    for(const { label: run, data } of results)
    {
        for(let at = 0; at < length; at += 16)
        {
            if(!data.subarray(at, at + 16).every((b, k) => b === results[0].data[at + k]))
            {
                assert.fail(`${label} at ${at / 16}: ${run} ${hex(data.subarray(at, at + 16))}, interpreter ${hex(results[0].data.subarray(at, at + 16))}`);
            }
        }
    }
    return results[0].data;
}
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/** The build has Wasm SIMD (the fallback build has no SIMD templates) */
const simd = vm => vm.v86.cpu.wm.exports["jit_wasm_simd_supported"]() !== 0;
/** The page tier (machine 1) ran a template for the form under test, whose
 * interpreter steps are keyed by its first two bytes, 66 0F; or stepped it
 * each round. A build without Wasm SIMD has no SIMD templates. Reset the
 * counts before the run (x64_page_steps_reset). */
function page_ran(name, templated, count)
{
    const page_steps = machines[1].v86.cpu.wm.exports["x64_page_steps"];
    const steps = page_steps(0x0F66);
    if(templated && simd(machines[1])) assert.ok(steps < count / 2, `${name}: the page tier template (${steps} steps)`);
    else assert.ok(steps >= count, `${name}: the page tier steps (${steps})`);
}
/** `faulting` raises `vector` at its first byte after `prologue` (the
 * handler skips it) in every run, and OUT holds `out` afterwards */
async function expect_fault(prologue, faulting, vector, { epilogue = [], before = () => {}, cr2, error_code, label, out, memory } = {})
{
    const at = CODE + PROLOGUE.length + prologue.length;
    const results = await run_all([...prologue, ...faulting, ...epilogue], vm => {
        vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
        before(vm);
    }, machines, vm => ({ fault: [0, 4, 8, 12].map(o => word(vm, FAULT + o)), out: bytes(vm, OUT, 16),
        memory: memory && bytes(vm, memory[0], memory[1].length) }));
    const name = label || hex(faulting);
    for(const { label: run, data } of results)
    {
        assert.deepEqual(data.fault.slice(0, 2), [vector, at], `${name} (${run}): vector, EIP`);
        if(cr2 !== undefined) assert.equal(data.fault[2], cr2, `${name} (${run}): CR2`);
        if(error_code !== undefined) assert.equal(data.fault[3], error_code, `${name} (${run}): error code`);
        if(out) assert.equal(hex(data.out), hex(out), `${name} (${run}): destination kept`);
        if(memory) assert.equal(hex(data.memory), hex(memory[1]), `${name} (${run}): memory kept`);
    }
}
const pages = (vm, page, present) => {
    // (the BIOS's page table: 0x13000, identity)
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};
const write_data = vm => {
    vm.write_memory(destinations, DEST);
    vm.write_memory(sources, SOURCE);
    vm.write_memory(masks, MASK);
};
let checks = 0;
try
{
    // Without SSE4.1 and SSE4.2: CPUID reports neither, every form is #UD
    const CPUID = [0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT)];
    machines.push(...await create_machines({ cpu_features: ["SSSE3"] }));
    await run_all(CPUID);
    for(const vm of machines) assert.equal(word(vm, OUT) >>> 19 & 3, 0, "CPUID.1:ECX.SSE4_1/SSE4_2");
    for(const { op, name } of [...BINARY, { op: 0x17, name: "ptest" }, { op: 0x2A, name: "movntdqa" }])
    {
        await expect_fault([], encode(0x38, op, 1, undefined, SOURCE, undefined), 6, { label: `${name} without SSE4` });
    }
    for(const [op, name] of [...IMMEDIATE, ...EXTRACT, ...INSERT, [0x08, "roundps"], [0x0B, "roundsd"], [0x40, "dpps"], [0x41, "dppd"], ...STRINGS])
    {
        await expect_fault([], encode(0x3A, op, 1, 2, undefined, 0), 6, { label: `${name} without SSE4` });
    }
    for(const bytes of [1, 2, 4]) await expect_fault([], crc32_form(bytes, 1, 2), 6, { label: `crc32 (${bytes}) without SSE4.2` });
    // POPCNT has a CPUID bit of its own (always set), not SSE4.2's
    {
        const program = [...CPUID, 0xB8, ...u32(0xF0F00001), ...popcnt_form(4, 1, 0), 0x89, 0x0D, ...u32(OUT + 4)];
        const results = await run_all(program, () => {}, machines, vm => [word(vm, OUT), word(vm, OUT + 4), word(vm, FAULT)]);
        for(const { label, data: [ecx, count, fault] } of results)
        {
            assert.deepEqual([ecx >>> 23 & 1, count, fault], [1, 9, 0], `CPUID.1:ECX.POPCNT and POPCNT without SSE4.2 (${label})`);
        }
    }
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: without SSE4.1/SSE4.2, CPUID reports neither and every form is #UD; POPCNT is there");

    // With SSE4.1 but not SSE4.2: PCMPGTQ, PCMPxSTRx and CRC32 are #UD, the SSE4.1 forms are not
    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1"] }));
    await run_all(CPUID);
    for(const vm of machines) assert.equal(word(vm, OUT) >>> 19 & 3, 1, "CPUID.1:ECX.SSE4_1/SSE4_2");
    await expect_fault([], encode(0x38, 0x37, 1, 2), 6, { label: "pcmpgtq without SSE4.2" });
    for(const [op, name] of STRINGS) await expect_fault([], encode(0x3A, op, 1, 2, undefined, 0x0C), 6, { label: `${name} without SSE4.2` });
    for(const bytes of [1, 2, 4]) await expect_fault([], crc32_form(bytes, 1, 2), 6, { label: `crc32 (${bytes}) without SSE4.2` });
    {
        const results = await run_all([...encode(0x38, 0x3B, 1, 2), ...encode(0x3A, 0x0E, 1, 2, undefined, 3)], () => {}, machines, vm => word(vm, FAULT));
        for(const { label, data } of results) assert.equal(data, 0, `PMINUD and PBLENDW with SSE4.1 only (${label})`);
    }
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: with SSE4.1 only, CPUID reports it; PCMPGTQ, PCMPxSTRx and CRC32 are #UD, the SSE4.1 forms run");

    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2"] }));
    await run_all(CPUID);
    for(const vm of machines) assert.equal(word(vm, OUT) >>> 19 & 3, 3, "CPUID.1:ECX.SSE4_1/SSE4_2");

    // 66 0F 38 against the model. XMM0 (BLENDV's mask) is loaded first, then
    // the destination, then a register source: the operands may alias.
    const CASES = 64;
    let cases = 0;
    for(const { op, name, bytes: width } of BINARY)
    {
        const program = [];
        for(let n = 0; n < CASES; n++)
        {
            const dst = n & 7, src = n >> 3 & 7, memory = n >= CASES / 2;
            // a narrow memory operand needs no alignment
            const address = SOURCE + n * 16 + (width < 16 ? n & 7 : 0);
            program.push(...LOAD, ...absolute(0, MASK + n * 16), ...LOAD, ...absolute(dst, DEST + n * 16));
            if(!memory) program.push(...LOAD, ...absolute(src, SOURCE + n * 16));
            program.push(...encode(0x38, op, dst, src, memory ? address : undefined));
            program.push(...STORE, ...absolute(dst, OUT + n * 16));
        }
        for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(CASES * 16), OUT); }, CASES * 16, name);
        page_ran(name, TEMPLATED_38.includes(op), CASES);
        for(let n = 0; n < CASES; n++)
        {
            const dst = n & 7, src = n >> 3 & 7, memory = n >= CASES / 2;
            const registers = [masks.slice(n * 16, n * 16 + 16)];
            registers[dst] = destinations.slice(n * 16, n * 16 + 16);
            if(!memory) registers[src] = sources.slice(n * 16, n * 16 + 16);
            const offset = n * 16 + (width < 16 ? n & 7 : 0);
            const source = memory ? Uint8Array.from({ length: 16 }, (_, i) => i < width ? sources[offset + i] : 0) : registers[src];
            const expected = sse4_38(op, registers[dst], source, registers[0]);
            assert.equal(hex(result.subarray(n * 16, n * 16 + 16)), hex(expected),
                `${name} xmm${dst}, ${memory ? "[mem]" : "xmm" + src} (xmm0 ${hex(registers[0])}): d=${hex(registers[dst])} s=${hex(source)}`);
        }
        cases += CASES;
    }
    console.log(`PASS: ${cases} cases of ${BINARY.length} forms of 66 0F 38 (PMOVSX/PMOVZX, BLENDV, PMULDQ/PMULLD, PCMPEQQ/PCMPGTQ, PACKUSDW, PMIN/PMAX, PHMINPOSUW) match the model in the interpreter and the page tier; the page tier templates for ${TEMPLATED_38.length}`);
    checks += cases;

    // PTEST: ZF and CF from the model, AF, OF, PF and SF cleared (set before)
    {
        const program = [];
        for(let n = 0; n < CASES; n++)
        {
            const memory = n >= CASES / 2;
            program.push(...LOAD, ...absolute(3, DEST + n * 16));
            if(!memory) program.push(...LOAD, ...absolute(5, SOURCE + n * 16));
            // (OF, SF, AF set by 0x7F + 1, CF by STC)
            program.push(0xB0, 0x7F, 0x04, 0x01, 0xF9);
            program.push(...encode(0x38, 0x17, 3, 5, memory ? SOURCE + n * 16 : undefined));
            program.push(...PUSHF_STORE(OUT + n * 16));
        }
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(CASES * 16), OUT); }, CASES * 16, "ptest");
        for(let n = 0; n < CASES; n++)
        {
            const { zf, cf } = ptest(destinations.slice(n * 16, n * 16 + 16), sources.slice(n * 16, n * 16 + 16));
            const flags = new DataView(result.buffer).getUint32(n * 16, true);
            assert.equal(flags & 0x8D5, (zf ? 0x40 : 0) | (cf ? 1 : 0), `ptest ${n}: flags ${flags.toString(16)}`);
        }
        cases += CASES;
        checks += CASES;
    }
    console.log("PASS: PTEST sets ZF and CF as the model, clears AF, OF, PF and SF");

    // 66 0F 3A with imm8: every imm8, register and memory sources
    for(const [op, name] of IMMEDIATE)
    {
        const program = [];
        const count = 512;
        for(let n = 0; n < count; n++)
        {
            const imm8 = n & 255, dst = n % 7 + 1, src = n % 5, memory = n >= 256;
            const address = SOURCE + n * 16;
            program.push(...LOAD, ...absolute(dst, DEST + n * 16));
            if(!memory) program.push(...LOAD, ...absolute(src, SOURCE + n * 16));
            program.push(...encode(0x3A, op, dst, src, memory ? address : undefined, imm8));
            program.push(...STORE, ...absolute(dst, OUT + n * 16));
        }
        for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(count * 16), OUT); }, count * 16, name);
        page_ran(name, TEMPLATED_3A.includes(op), count);
        for(let n = 0; n < count; n++)
        {
            const imm8 = n & 255, dst = n % 7 + 1, src = n % 5, memory = n >= 256;
            const s = sources.slice(n * 16, n * 16 + 16);
            // (a destination that is also the source holds the source)
            const d = !memory && dst === src ? s : destinations.slice(n * 16, n * 16 + 16);
            // (INSERTPS from memory: the m32, imm8[7:6] ignored)
            const expected = op === 0x21 && memory ? insertps(d, get(s, 4, 0), imm8) : sse4_3a(op, d, s, imm8);
            assert.equal(hex(result.subarray(n * 16, n * 16 + 16)), hex(expected), `${name} imm8=${imm8.toString(16)} ${memory ? "[mem]" : "xmm"}`);
        }
        cases += count;
        checks += count;
    }
    console.log(`PASS: BLENDPS/BLENDPD/PBLENDW/INSERTPS/MPSADBW, every imm8 from registers and memory`);

    // PEXTR*/EXTRACTPS to a register (zero-extended) and to memory (the
    // bytes after unchanged), PINSRB/PINSRD from a register (its low bytes) and memory
    for(const [op, name, size] of EXTRACT)
    {
        const program = [], count = 64;
        for(let n = 0; n < count; n++)
        {
            const xmm = n % 8, gpr = GPRS[n % 7], imm8 = n * 37 & 255, memory = n >= count / 2;
            program.push(...LOAD, ...absolute(xmm, SOURCE + n * 16), ...mov_r32(gpr, 0xDEADBEEF));
            if(memory) program.push(...encode(0x3A, op, xmm, 0, OUT + n * 16 + (n & 7), imm8));
            else program.push(...encode(0x3A, op, xmm, gpr, undefined, imm8), ...store_r32(gpr, OUT + n * 16));
        }
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(count * 16).fill(0xEE), OUT); }, count * 16, name);
        for(let n = 0; n < count; n++)
        {
            const imm8 = n * 37 & 255, memory = n >= count / 2;
            const value = extract(sources.slice(n * 16, n * 16 + 16), size, imm8);
            const expected = new Uint8Array(16).fill(0xEE);
            if(memory) set(expected.subarray(n & 7), size, 0, value);
            else set(expected, 4, 0, value);
            assert.equal(hex(result.subarray(n * 16, n * 16 + 16)), hex(expected), `${name} imm8=${imm8} ${memory ? "[mem]" : "r32"}`);
        }
        cases += count;
        checks += count;
    }
    for(const [op, name, size] of INSERT)
    {
        const program = [], count = 64;
        for(let n = 0; n < count; n++)
        {
            const xmm = n % 8, gpr = GPRS[n % 7], imm8 = n * 37 & 255, memory = n >= count / 2;
            program.push(...LOAD, ...absolute(xmm, DEST + n * 16), ...mov_r32(gpr, Number(get(sources.subarray(n * 16), 4, 0))));
            program.push(...encode(0x3A, op, xmm, gpr, memory ? SOURCE + n * 16 + (n & 7) : undefined, imm8));
            program.push(...STORE, ...absolute(xmm, OUT + n * 16));
        }
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(count * 16), OUT); }, count * 16, name);
        for(let n = 0; n < count; n++)
        {
            const imm8 = n * 37 & 255, memory = n >= count / 2;
            const value = get(sources.subarray(n * 16 + (memory ? n & 7 : 0)), size, 0);
            const expected = insert(destinations.slice(n * 16, n * 16 + 16), size, value, imm8);
            assert.equal(hex(result.subarray(n * 16, n * 16 + 16)), hex(expected), `${name} imm8=${imm8} ${memory ? "[mem]" : "r32"}`);
        }
        cases += count;
        checks += count;
    }
    console.log(`PASS: PEXTRB/PEXTRW/PEXTRD/EXTRACTPS and PINSRB/PINSRD with registers and memory, ${cases} cases in all`);

    // ROUND: the page tier (machine 1) rounds finite lanes natively from the
    // default MXCSR (PE clear: set natively when reported), without the
    // exact helper (x64_sse_fp_calls) or steps; a NaN lane leaves the
    // template (the page tier retries the instruction in the interpreter; IR
    // Tier-0, before P7.5, called the helper). Every imm8 mode (bits 4-7 are
    // ignored), registers and memory.
    {
        const FINITE = [0.5, 1.5, 2.5, -0.5, -1.5, -2.5, 3.7, -2.3, 1e-40, -1e-40, 0, -0, 1e10, -7, 123.456, 0.25];
        const NAN_LANES = [NaN, 1.5, -0.5, NaN];
        const values = (double, list, n) => {
            const v = new DataView(new ArrayBuffer(16));
            for(let i = 0; i < (double ? 2 : 4); i++)
            {
                const x = list[(n * 3 + i * 5) % list.length];
                if(double) v.setFloat64(i * 8, x === 1e-40 ? 1e-310 : x, true);
                else v.setFloat32(i * 4, x, true);
            }
            return new Uint8Array(v.buffer);
        };
        const MXCSR_DEFAULT = MASK + 0x1000;
        for(const [op, name, double, scalar] of [[0x0A, "roundss", false, true], [0x0B, "roundsd", true, true],
            [0x08, "roundps", false, false], [0x09, "roundpd", true, false]])
            for(const nan of [false, true])
        {
            const count = 64, program = [0x0F, 0xAE, 0x15, ...u32(MXCSR_DEFAULT)];
            const imm8 = n => [0, 1, 2, 3, 4, 8, 9, 10, 11, 12][n % 10] | n * 16 & 0xF0;
            const sources = new Uint8Array(count * 16);
            for(let n = 0; n < count; n++) sources.set(values(double, nan && n % 2 ? NAN_LANES : FINITE, n), n * 16);
            for(let n = 0; n < count; n++)
            {
                const dst = n % 8, src = (n + 3) % 8, memory = n >= count / 2;
                program.push(...LOAD, ...absolute(dst, DEST + n * 16));
                if(!memory) program.push(...LOAD, ...absolute(src, SOURCE + n * 16));
                program.push(...encode(0x3A, op, dst, src, memory ? SOURCE + n * 16 : undefined, imm8(n)), ...STORE, ...absolute(dst, OUT + n * 16));
            }
            program.push(0x0F, 0xAE, 0x1D, ...u32(OUT + count * 16));
            for(const vm of machines)
            {
                vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
                vm.v86.cpu.wm.exports["x64_sse_fp_calls_reset"]();
            }
            const label = `${name}${nan ? " with NaN lanes" : ""}`;
            const result = await run_out(program, vm => {
                write_data(vm);
                vm.write_memory(sources, SOURCE);
                vm.write_memory(Uint8Array.from(u32(0x1F80)), MXCSR_DEFAULT);
                vm.write_memory(new Uint8Array(count * 16 + 16), OUT);
            }, count * 16 + 16, label);
            const fp = new Fp(0x1F80), size = double ? 8 : 4;
            for(let n = 0; n < count; n++)
            {
                const expected = destinations.slice(n * 16, n * 16 + 16), source = sources.subarray(n * 16, n * 16 + 16);
                for(let i = 0; i < (scalar ? 1 : 16 / size); i++) set(expected, size, i, round_lane(fp, get(source, size, i), double, imm8(n)));
                assert.equal(hex(result.subarray(n * 16, n * 16 + 16)), hex(expected), `${label} ${n}, imm8 ${imm8(n).toString(16)}`);
            }
            assert.equal(new DataView(result.buffer, result.byteOffset).getUint32(count * 16, true), fp.finish().mxcsr, `${label}: MXCSR`);
            const page = machines[1].v86.cpu.wm.exports;
            const steps = page["x64_page_steps"](0x0F66), calls = page["x64_sse_fp_calls"](0x660F3A00 | op);
            if(!simd(machines[1])) assert.ok(steps >= count, `${label}: the page tier steps without Wasm SIMD (${steps})`);
            else if(nan) assert.ok(calls + steps >= count / 4, `${label}: NaN lanes leave the template (${calls} calls, ${steps} steps and retries)`);
            else assert.ok(calls === 0 && steps < count / 2, `${label}: the page tier rounds natively (${calls} calls, ${steps} steps)`);
            checks += count;
        }
        console.log("PASS: ROUNDSS/ROUNDSD/ROUNDPS/ROUNDPD in the page tier natively for finite lanes (PE set there), retried for NaN lanes, every mode");
    }

    // MOVNTDQA loads an aligned m128
    {
        const program = [];
        for(let n = 0; n < 8; n++) program.push(...encode(0x38, 0x2A, n, 0, SOURCE + n * 16), ...STORE, ...absolute(n, OUT + n * 16));
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(128), OUT); }, 128, "movntdqa");
        assert.equal(hex(result), hex(sources.slice(0, 128)), "movntdqa");
        checks++;
    }

    // PCMPxSTRx against the model, every imm8 (bit 7 is reserved) from
    // registers and from an unaligned m128. XMM0 holds a pattern, then the
    // needle and the haystack are loaded (they may be XMM0 or the same
    // register). Out: XMM0, ECX (DEADBEEF before) and the flags.
    const PATTERN = OUT + 0x8000, pattern = Uint8Array.from({ length: 16 }, (_, i) => 0xC0 + i);
    // (the data must reach no match, all elements matching, and both strings ending early)
    const reached = { none: 0, all: 0, short: 0 };
    for(const [op, name] of STRINGS)
    {
        const count = 512, program = [];
        const operands = n => ({ imm8: n & 255, dst: n % 8, src: (n * 3 + 1) % 8, memory: n >= 256,
            la: LENGTHS[n % LENGTHS.length], lb: LENGTHS[(n * 7 + 3) % LENGTHS.length], address: MASK + n * 32 + (n & 15) });
        for(let n = 0; n < count; n++)
        {
            const { imm8, dst, src, memory, la, lb, address } = operands(n);
            program.push(...LOAD, ...absolute(0, PATTERN), ...LOAD, ...absolute(dst, DEST + n * 16));
            if(!memory) program.push(...LOAD, ...absolute(src, SOURCE + n * 16));
            program.push(...FLAGS_BEFORE[n & 1][0], ...mov_r32(0, la), ...mov_r32(2, lb), ...mov_r32(1, 0xDEADBEEF));
            program.push(...encode(0x3A, op, dst, src, memory ? address : undefined, imm8));
            program.push(...store_r32(1, OUT + n * 32 + 16), ...STORE, ...absolute(0, OUT + n * 32), ...PUSHF_STORE(OUT + n * 32 + 20));
        }
        for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
        const result = await run_out(program, vm => {
            vm.write_memory(needles, DEST);
            vm.write_memory(haystacks, SOURCE);
            for(let n = 256; n < count; n++) vm.write_memory(haystacks.subarray(n * 16, n * 16 + 16), operands(n).address);
            vm.write_memory(pattern, PATTERN);
            vm.write_memory(new Uint8Array(count * 32), OUT);
        }, count * 32, name);
        page_ran(name, true, count);
        const view = new DataView(result.buffer, result.byteOffset);
        for(let n = 0; n < count; n++)
        {
            const { imm8, dst, src, memory, la, lb } = operands(n);
            const registers = [pattern];
            registers[dst] = needles.slice(n * 16, n * 16 + 16);
            if(!memory) registers[src] = haystacks.slice(n * 16, n * 16 + 16);
            const explicit = op < 0x62;
            const r = compare_strings(imm8, registers[dst], memory ? haystacks.slice(n * 16, n * 16 + 16) : registers[src],
                explicit ? BigInt(la) : undefined, explicit ? BigInt(lb) : undefined);
            const index = op & 1;
            const label = `${name} xmm${dst}, ${memory ? "[mem]" : "xmm" + src}, ${imm8.toString(16)} (eax ${la}, edx ${lb})`;
            assert.equal(hex(result.subarray(n * 32, n * 32 + 16)), hex(index ? registers[0] : r.mask), `${label}: XMM0`);
            assert.equal(view.getUint32(n * 32 + 16, true), index ? r.index : 0xDEADBEEF, `${label}: ECX`);
            const flags = (r.cf ? 1 : 0) | (r.zf ? 0x40 : 0) | (r.sf ? 0x80 : 0) | (r.of ? 0x800 : 0);
            assert.equal(view.getUint32(n * 32 + 20, true) & 0x8D5, flags, `${label}: flags`);
            reached.none += r.intres2 === 0;
            reached.all += r.intres2 === (imm8 & 1 ? 0xFF : 0xFFFF);
            reached.short += r.zf && r.sf;
        }
        cases += count;
        checks += count;
    }
    assert(reached.none > 50 && reached.all > 50 && reached.short > 50, `PCMPxSTRx data: ${JSON.stringify(reached)}`);
    console.log("PASS: PCMPESTRM/PCMPESTRI/PCMPISTRM/PCMPISTRI, every imm8 from registers and unaligned memory: XMM0, ECX and the flags as the model; the page tier templates");

    // CRC32 against the model: r/m8 (AH-BH too), r/m16 and r/m32 from
    // registers (the destination's too) and unaligned memory; the flags kept
    for(const bytes of [1, 2, 4])
    {
        const count = 128, program = [];
        const operands = n => {
            const memory = n >= count / 2, rm = n % 8;
            return { memory, dst: GPRS[n % 7], rm: bytes > 1 && rm === 4 ? 5 : rm,
                crc: [0, 0xFFFFFFFF, 0x12345678, 0x80000001][n % 4] ^ Number(get(destinations.subarray(n * 16), 4, 0)) * (n % 5 === 0 ? 0 : 1),
                value: Number(get(sources.subarray(n * 16), 4, 0)), address: SOURCE + n * 16 + (n & 7) };
        };
        for(let n = 0; n < count; n++)
        {
            const { memory, dst, rm, crc, value, address } = operands(n);
            program.push(...FLAGS_BEFORE[n & 1][0]);
            // (the source's register, then the destination: the destination wins if they are one)
            if(!memory) program.push(...mov_r32(bytes === 1 ? rm & 3 : rm, value));
            program.push(...mov_r32(dst, crc), ...crc32_form(bytes, dst, rm, memory ? address : undefined));
            program.push(...store_r32(dst, OUT + n * 16), ...PUSHF_STORE(OUT + n * 16 + 4));
        }
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(count * 16), OUT); }, count * 16, `crc32 (${bytes})`);
        const view = new DataView(result.buffer, result.byteOffset);
        for(let n = 0; n < count; n++)
        {
            const { memory, dst, rm, crc, value } = operands(n);
            const registers = [];
            if(!memory) registers[bytes === 1 ? rm & 3 : rm] = value >>> 0;
            registers[dst] = crc >>> 0;
            let source;
            if(memory) source = Number(get(sources.subarray(n * 16 + (n & 7)), bytes, 0));
            else if(bytes === 1) source = registers[rm & 3] >>> (rm & 4 ? 8 : 0) & 0xFF;
            else source = registers[rm] & (bytes === 2 ? 0xFFFF : -1);
            const expected = Number(crc32(BigInt(registers[dst]), BigInt(source >>> 0), bytes));
            const label = `crc32 r${dst}, ${memory ? "[mem]" : "r" + rm} (${bytes}) crc ${registers[dst].toString(16)} value ${(source >>> 0).toString(16)}`;
            assert.equal(view.getUint32(n * 16, true), expected, label);
            assert.equal(view.getUint32(n * 16 + 4, true) & 0x8D5, FLAGS_BEFORE[n & 1][1], `${label}: flags kept`);
        }
        cases += count;
        checks += count;
    }
    console.log("PASS: CRC32 r32, r/m8 (AH-BH too), r/m16 and r/m32 from registers and memory as the CRC-32C model, the flags kept");

    // POPCNT r16/r32 from registers and memory: OF, SF, AF, CF and PF cleared,
    // ZF for a zero source; r16 keeps the upper half
    for(const bytes of [2, 4])
    {
        const count = 64, program = [];
        const VALUES = [0, 1, 0xFFFFFFFF, 0x80000000, 0x00010000, 0x8000, 0xFFFF0000, 0x5555AAAA];
        const operands = n => ({ memory: n >= count / 2, dst: GPRS[n % 7], src: GPRS[(n + 3) % 7], address: SOURCE + n * 16 + (n & 7),
            value: n % 16 < 8 ? VALUES[n % 8] : Number(get(sources.subarray(n * 16), 4, 0)) });
        for(let n = 0; n < count; n++)
        {
            const { memory, dst, src, address, value } = operands(n);
            program.push(...FLAGS_BEFORE[n & 1][0]);
            if(memory) program.push(0xC7, 0x05, ...u32(address), ...u32(value));
            else program.push(...mov_r32(src, value));
            program.push(...mov_r32(dst, 0xDEADBEEF), ...popcnt_form(bytes, dst, src, memory ? address : undefined));
            program.push(...store_r32(dst, OUT + n * 16), ...PUSHF_STORE(OUT + n * 16 + 4));
        }
        const result = await run_out(program, vm => { write_data(vm); vm.write_memory(new Uint8Array(count * 16), OUT); }, count * 16, `popcnt (${bytes})`);
        const view = new DataView(result.buffer, result.byteOffset);
        for(let n = 0; n < count; n++)
        {
            const { value } = operands(n);
            const source = bytes === 2 ? value & 0xFFFF : value >>> 0;
            const ones = source.toString(2).split("1").length - 1;
            const label = `popcnt (${bytes}) of ${source.toString(16)}`;
            assert.equal(view.getUint32(n * 16, true), bytes === 2 ? (0xDEAD0000 | ones) >>> 0 : ones, label);
            assert.equal(view.getUint32(n * 16 + 4, true) & 0x8D5, source === 0 ? 0x40 : 0, `${label}: flags`);
        }
        cases += count;
        checks += count;
    }
    console.log("PASS: POPCNT r16/r32 from registers and memory, its flags");

    // Faults: the destination keeps its value
    const keep = r => [...LOAD, ...absolute(r, DEST)];
    const kept = r => [...STORE, ...absolute(r, OUT)];
    const out = destinations.slice(0, 16);
    const before = vm => { write_data(vm); vm.write_memory(new Uint8Array(16), OUT); };
    const samples = [
        ["pminud", encode(0x38, 0x3B, 6, undefined, SOURCE + 8), true],
        ["pblendvb", encode(0x38, 0x10, 6, undefined, SOURCE + 4), true],
        ["ptest", encode(0x38, 0x17, 6, undefined, SOURCE + 1), true],
        ["movntdqa", encode(0x38, 0x2A, 6, undefined, SOURCE + 8), true],
        ["blendps", encode(0x3A, 0x0C, 6, undefined, SOURCE + 8, 5), true],
        ["mpsadbw", encode(0x3A, 0x42, 6, undefined, SOURCE + 12, 5), true],
        ["pmovzxbw", encode(0x38, 0x30, 6, undefined, SOURCE + 8), false],
        ["pinsrd", encode(0x3A, 0x22, 6, undefined, SOURCE + 1, 1), false],
        ["insertps", encode(0x3A, 0x21, 6, undefined, SOURCE + 3, 0x10), false],
        // (PCMPxSTRx: an m128 without alignment, SDM exception type 4 note)
        ["pcmpistri", encode(0x3A, 0x63, 6, undefined, SOURCE + 3, 0x0C), false],
        ["pcmpestrm", encode(0x3A, 0x60, 6, undefined, SOURCE + 9, 0x40), false],
    ];
    for(const [name, form, aligned] of samples)
    {
        const label = name + " [misaligned]";
        if(aligned)
        {
            await expect_fault(keep(6), form, 13, { epilogue: kept(6), before, error_code: 0, label, out });
        }
        else
        {
            const results = await run_all([...keep(6), ...form, ...kept(6)], before, machines, vm => word(vm, FAULT));
            for(const { label: run, data } of results) assert.equal(data, 0, `${label} (${run}): no fault`);
        }
        // CR0.TS: #NM; CR0.EM and no CR4.OSFXSR: #UD
        await expect_fault([...keep(6), ...SET_CR0(8)], form, 7, { epilogue: [...CLTS, ...kept(6)], before, label: name + " with CR0.TS", out });
        await expect_fault([...keep(6), ...SET_CR0(4)], form, 6, { epilogue: [...CLEAR_CR0(4), ...kept(6)], before, label: name + " with CR0.EM", out });
        await expect_fault([...keep(6), ...NO_OSFXSR], form, 6, { epilogue: [...OSFXSR, ...kept(6)], before, label: name + " without OSFXSR", out });
        checks += 4;
    }
    // LOCK, F2 and F3 are #UD; so is MOVNTDQA from a register
    for(const prefix of [0xF0, 0xF2, 0xF3])
    {
        for(const form of [encode(0x38, 0x3B, 6, 1), encode(0x3A, 0x0E, 6, 1, undefined, 3), encode(0x3A, 0x16, 1, 2, undefined, 1),
            encode(0x3A, 0x63, 6, 1, undefined, 0x0C)])
        {
            await expect_fault(keep(6), [prefix, ...form], 6, { epilogue: kept(6), before, label: `${prefix.toString(16)} ${hex(form)}`, out });
            checks++;
        }
    }
    await expect_fault(keep(6), encode(0x38, 0x2A, 6, 1), 6, { epilogue: kept(6), before, label: "movntdqa xmm6, xmm1", out });
    // CRC32 and POPCNT have no XMM state: CR0.TS, CR0.EM and CR4.OSFXSR do
    // not matter. LOCK is #UD, so is F3 at CRC32's opcodes.
    for(const [name, form] of [["crc32 ecx, byte [mem]", crc32_form(1, 1, 0, SOURCE + 1)], ["crc32 ecx, edx", crc32_form(4, 1, 2)],
        ["crc32 ecx, word [mem]", crc32_form(2, 1, 0, SOURCE + 3)], ["popcnt ecx, word [mem]", popcnt_form(2, 1, 0, SOURCE + 3)],
        ["popcnt ecx, edx", popcnt_form(4, 1, 2)]])
    {
        for(const [setup, undo, what] of [[SET_CR0(8), CLTS, "CR0.TS"], [SET_CR0(4), CLEAR_CR0(4), "CR0.EM"], [NO_OSFXSR, OSFXSR, "no CR4.OSFXSR"]])
        {
            const results = await run_all([...setup, ...form, ...undo], before, machines, vm => word(vm, FAULT));
            for(const { label, data } of results) assert.equal(data, 0, `${name} with ${what} (${label}): no fault`);
            checks++;
        }
        await expect_fault([], [0xF0, ...form], 6, { before, label: `lock ${name}` });
        checks++;
    }
    for(const op of [0xF0, 0xF1])
    {
        await expect_fault([], [0xF3, 0x0F, 0x38, op, 0xC1], 6, { before, label: `F3 0F 38 ${op.toString(16)} (not CRC32)` });
        checks++;
    }
    // #PF: a load from and a store to an absent page, nothing written
    const absent = vm => { before(vm); vm.write_memory(new Uint8Array(16).fill(0xEE), ABSENT - 16); pages(vm, ABSENT, false); };
    await expect_fault(keep(6), encode(0x38, 0x32, 6, undefined, ABSENT - 1), 14, { epilogue: kept(6), before: absent, cr2: ABSENT, error_code: 0, label: "pmovzxbq across into an absent page", out });
    await expect_fault(keep(6), encode(0x3A, 0x16, 6, undefined, ABSENT - 2, 3), 14, { epilogue: kept(6), before: absent, cr2: ABSENT, error_code: 2,
        label: "pextrd across into an absent page", memory: [ABSENT - 16, new Uint8Array(16).fill(0xEE)] });
    // PCMPISTRI reads all of its m128 though the string ends at its first
    // byte; a CRC32 operand across into the page. ECX keeps its value.
    const ecx = [...u32(0x12345678), ...new Array(12).fill(0)];
    await expect_fault(mov_r32(1, 0x12345678), encode(0x3A, 0x63, 6, undefined, ABSENT - 4, 0x0C), 14, { epilogue: store_r32(1, OUT),
        before: vm => { absent(vm); vm.write_memory(new Uint8Array(4), ABSENT - 4); }, cr2: ABSENT, error_code: 0,
        label: "pcmpistri across into an absent page", out: ecx });
    await expect_fault(mov_r32(1, 0x12345678), crc32_form(4, 1, 0, ABSENT - 2), 14, { epilogue: store_r32(1, OUT), before: absent, cr2: ABSENT,
        error_code: 0, label: "crc32 across into an absent page", out: ecx });
    for(const vm of machines) pages(vm, ABSENT, true);
    checks += 5;
    console.log("PASS: #GP(0) for misaligned m128 operands (none for narrow ones or PCMPxSTRx), #NM, #UD (EM, OSFXSR, LOCK, F2/F3, MOVNTDQA register) and #PF, without effect; CRC32 and POPCNT without XMM checks");
    console.log(`PASS: ${checks} SSE4 checks in the interpreter and the page tier`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                                                                                 source/v64/tests/rust/sse4_model.mjs                                                                0000644 0000000 0000000 00000030730 00000000000 014577  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A model of SSE4.1 and SSE4.2 (docs/simd-xsave-plan.md 7.2, 7.3) written
// from the SDM's pseudocode, independent of src/rust/cpu: byte vectors in and
// out (16 bytes, little-endian lanes, read as BigInts); floating point with
// tests/rust/sse_fp_model.mjs (exact arithmetic under MXCSR); PCMPxSTRx after
// SDM Vol. 2, 4.1; CRC32 as the SDM's polynomial division (CRC-32C).
import { Fp, IE, PE, format, is_inf, is_nan, is_snan, is_zero } from "./sse_fp_model.mjs";

export { Fp };

/** Lane `i` of `size` bytes, unsigned or sign-extended */
export function get(v, size, i, signed = false)
{
    let x = 0n;
    for(let k = size - 1; k >= 0; k--) x = x << 8n | BigInt(v[i * size + k]);
    return signed && x >> BigInt(size * 8 - 1) ? x - (1n << BigInt(size * 8)) : x;
}
/** Lane `i` of `size` bytes := x (truncated) */
export function set(v, size, i, x)
{
    x = BigInt.asUintN(size * 8, x);
    for(let k = 0; k < size; k++) { v[i * size + k] = Number(x & 0xFFn); x >>= 8n; }
}
const lanes = (size, f) => {
    const r = new Uint8Array(16);
    for(let i = 0; i < 16 / size; i++) set(r, size, i, f(i));
    return r;
};
const min = (a, b) => a < b ? a : b, max = (a, b) => a > b ? a : b;

/** The 66 0F 38 forms but PTEST: the destination after the operation (BLENDV: the mask is XMM0) */
export function sse4_38(op, d, s, xmm0)
{
    switch(op)
    {
        case 0x10: return lanes(1, i => get(xmm0, 1, i) & 0x80n ? get(s, 1, i) : get(d, 1, i)); // pblendvb
        case 0x14: return lanes(4, i => get(xmm0, 4, i) >> 31n ? get(s, 4, i) : get(d, 4, i)); // blendvps
        case 0x15: return lanes(8, i => get(xmm0, 8, i) >> 63n ? get(s, 8, i) : get(d, 8, i)); // blendvpd
        // pmovsx/pmovzx: the low elements of the source, extended
        case 0x20: case 0x30: return lanes(2, i => get(s, 1, i, op === 0x20)); // bw
        case 0x21: case 0x31: return lanes(4, i => get(s, 1, i, op === 0x21)); // bd
        case 0x22: case 0x32: return lanes(8, i => get(s, 1, i, op === 0x22)); // bq
        case 0x23: case 0x33: return lanes(4, i => get(s, 2, i, op === 0x23)); // wd
        case 0x24: case 0x34: return lanes(8, i => get(s, 2, i, op === 0x24)); // wq
        case 0x25: case 0x35: return lanes(8, i => get(s, 4, i, op === 0x25)); // dq
        case 0x28: return lanes(8, i => get(d, 4, 2 * i, true) * get(s, 4, 2 * i, true)); // pmuldq
        case 0x29: return lanes(8, i => get(d, 8, i) === get(s, 8, i) ? -1n : 0n); // pcmpeqq
        case 0x2B: return lanes(2, i => { // packusdw
            const x = i < 4 ? get(d, 4, i, true) : get(s, 4, i - 4, true);
            return x < 0n ? 0n : x > 0xFFFFn ? 0xFFFFn : x;
        });
        case 0x37: return lanes(8, i => get(d, 8, i, true) > get(s, 8, i, true) ? -1n : 0n); // pcmpgtq (SSE4.2)
        case 0x38: return lanes(1, i => min(get(d, 1, i, true), get(s, 1, i, true))); // pminsb
        case 0x39: return lanes(4, i => min(get(d, 4, i, true), get(s, 4, i, true))); // pminsd
        case 0x3A: return lanes(2, i => min(get(d, 2, i), get(s, 2, i))); // pminuw
        case 0x3B: return lanes(4, i => min(get(d, 4, i), get(s, 4, i))); // pminud
        case 0x3C: return lanes(1, i => max(get(d, 1, i, true), get(s, 1, i, true))); // pmaxsb
        case 0x3D: return lanes(4, i => max(get(d, 4, i, true), get(s, 4, i, true))); // pmaxsd
        case 0x3E: return lanes(2, i => max(get(d, 2, i), get(s, 2, i))); // pmaxuw
        case 0x3F: return lanes(4, i => max(get(d, 4, i), get(s, 4, i))); // pmaxud
        case 0x40: return lanes(4, i => get(d, 4, i, true) * get(s, 4, i, true)); // pmulld: the low half
        case 0x41: { // phminposuw: the smallest word of the source and its (first) index
            let index = 0;
            for(let i = 1; i < 8; i++) if(get(s, 2, i) < get(s, 2, index)) index = i;
            return lanes(2, i => i === 0 ? get(s, 2, index) : i === 1 ? BigInt(index) : 0n);
        }
    }
    throw new Error("sse4_38 " + op.toString(16));
}

/** PTEST: ZF if source AND destination is zero, CF if source AND NOT destination is; the others clear */
export function ptest(d, s)
{
    let and = 0n, andn = 0n;
    for(let i = 0; i < 2; i++)
    {
        and |= get(d, 8, i) & get(s, 8, i);
        andn |= get(s, 8, i) & ~get(d, 8, i);
    }
    return { zf: and === 0n, cf: BigInt.asUintN(64, andn) === 0n };
}

/** The 66 0F 3A integer and bitwise forms with imm8 (INSERTPS: `s` a register; see insertps) */
export function sse4_3a(op, d, s, imm8)
{
    switch(op)
    {
        case 0x0C: return lanes(4, i => imm8 >> i & 1 ? get(s, 4, i) : get(d, 4, i)); // blendps
        case 0x0D: return lanes(8, i => imm8 >> i & 1 ? get(s, 8, i) : get(d, 8, i)); // blendpd
        case 0x0E: return lanes(2, i => imm8 >> i & 1 ? get(s, 2, i) : get(d, 2, i)); // pblendw
        case 0x21: return insertps(d, get(s, 4, imm8 >> 6 & 3), imm8);
        case 0x42: { // mpsadbw: eight sums of absolute differences against a 4-byte block of the source
            const source = (imm8 & 3) * 4, destination = (imm8 >> 2 & 1) * 4;
            return lanes(2, i => {
                let sum = 0n;
                for(let j = 0; j < 4; j++)
                {
                    const x = get(d, 1, destination + i + j) - get(s, 1, source + j);
                    sum += x < 0n ? -x : x;
                }
                return sum;
            });
        }
    }
    throw new Error("sse4_3a " + op.toString(16));
}
/** INSERTPS with the 32-bit `value` (from memory, or the dword of the source register imm8[7:6] selects) */
export function insertps(d, value, imm8)
{
    const r = lanes(4, i => i === (imm8 >> 4 & 3) ? value : get(d, 4, i));
    return lanes(4, i => imm8 >> i & 1 ? 0n : get(r, 4, i));
}
/** PEXTRB/PEXTRW/PEXTRD/PEXTRQ/EXTRACTPS: the element imm8 selects */
export const extract = (v, size, imm8) => get(v, size, imm8 & (16 / size - 1));
/** PINSRB/PINSRD/PINSRQ: the element imm8 selects := value */
export function insert(d, size, value, imm8)
{
    const r = Uint8Array.from(d);
    set(r, size, imm8 & (16 / size - 1), value);
    return r;
}

/**
 * ROUNDPS/PD/SS/SD of one lane: to an integral value by imm8[1:0], or by
 * MXCSR.RC if imm8[2]; imm8[3] suppresses PE. IE for an SNaN, never DE;
 * DAZ applies. Zeros keep their sign.
 */
export function round_lane(fp, x0, double, imm8)
{
    const f = format(double);
    const { x } = fp.input(x0, double);
    if(is_nan(x, double))
    {
        if(is_snan(x, double)) fp.flags |= IE;
        return x | 1n << BigInt(f.p - 2);
    }
    if(is_inf(x, double) || is_zero(x, double)) return x;
    const rc = imm8 & 4 ? fp.rc : imm8 & 3;
    const sign = x >> BigInt(f.bits - 1) & 1n;
    const field = Number(x >> BigInt(f.p - 1) & (1n << BigInt(f.ebits)) - 1n);
    const bias = (1 << f.ebits - 1) - 1;
    const m = x & (1n << BigInt(f.p - 1)) - 1n | (field ? 1n << BigInt(f.p - 1) : 0n);
    const e = (field || 1) - bias - (f.p - 1); // |x| = m * 2^e
    if(e >= 0) return x;
    const q = m >> BigInt(-e), rem = m & (1n << BigInt(-e)) - 1n, half = 1n << BigInt(-e - 1);
    let up;
    switch(rc)
    {
        case 0: up = rem > half || rem === half && (q & 1n) === 1n; break;
        case 1: up = sign === 1n && rem !== 0n; break;
        case 2: up = sign === 0n && rem !== 0n; break;
        default: up = false;
    }
    if(rem !== 0n && !(imm8 & 8)) fp.flags |= PE;
    const n = up ? q + 1n : q;
    if(n === 0n) return sign << BigInt(f.bits - 1);
    // an integer of at most p bits: exact
    const length = n.toString(2).length;
    return sign << BigInt(f.bits - 1) | BigInt(length - 1 + bias) << BigInt(f.p - 1) | n << BigInt(f.p - length) & (1n << BigInt(f.p - 1)) - 1n;
}

/**
 * DPPS/DPPD: the products imm8[7:4] selects (else +0.0), summed pairwise in
 * the SDM's order, each operation rounded, to the lanes imm8[3:0] selects
 * (else +0.0). Returns the lanes, MXCSR and whether an unmasked exception
 * faults. Each multiplication and addition has its own exceptions (as a
 * single operation, SDM Vol. 1, 11.5.3) and sets its flags; the SDM's
 * pseudo-code looks for an unmasked one after DPPD's two multiplications
 * and after each addition (DPPS: only after the additions, so the first
 * addition runs even when a multiplication had one).
 */
export function dot_product(mxcsr, d, s, imm8, double)
{
    const size = double ? 8 : 4, n = 16 / size;
    let flags = 0, fault = false;
    const step = (op, a, b) => {
        const one = new Fp(mxcsr);
        const r = one.binary(op, a, b, double);
        const done = one.finish();
        flags |= done.mxcsr & 0x3F;
        fault ||= done.fault;
        return r;
    };
    const done = sum => ({ result: lanes(size, i => imm8 >> i & 1 ? sum : 0n), mxcsr: mxcsr | flags, fault });
    const products = Array.from({ length: n }, (_, i) => imm8 >> 4 + i & 1 ? step("mul", get(d, size, i), get(s, size, i)) : 0n);
    if(double)
    {
        if(fault) return done(0n);
        return done(step("add", products[0], products[1]));
    }
    const low = step("add", products[0], products[1]);
    if(fault) return done(0n);
    const high = step("add", products[2], products[3]);
    if(fault) return done(0n);
    return done(step("add", low, high));
}

/**
 * PCMPESTRI/PCMPESTRM/PCMPISTRI/PCMPISTRM (SDM Vol. 2, 4.1): `a` the first
 * operand (xmm1), `b` the second (xmm2/m128), `la` and `lb` the explicit
 * lengths (EAX/EDX or RAX/RDX as signed BigInts; undefined: implicit, up to
 * the first zero element). Returns IntRes2 (a bit per element of b), the
 * xSTRI index, the xSTRM mask and CF, ZF, SF, OF (AF and PF are cleared).
 */
export function compare_strings(imm8, a, b, la, lb)
{
    const words = imm8 & 1, signed = (imm8 & 2) !== 0, n = words ? 8 : 16, size = words ? 2 : 1;
    const ea = Array.from({ length: n }, (_, i) => get(a, size, i, signed));
    const eb = Array.from({ length: n }, (_, i) => get(b, size, i, signed));
    const length = (e, explicit) => {
        if(explicit === undefined)
        {
            const zero = e.indexOf(0n);
            return zero < 0 ? n : zero;
        }
        const magnitude = explicit < 0n ? -explicit : explicit;
        return magnitude > BigInt(n) ? n : Number(magnitude);
    };
    const va = length(ea, la), vb = length(eb, lb);
    const aggregation = imm8 >> 2 & 3;
    // BoolRes for element j of b and element i of a, invalid elements forced (SDM table 4-7)
    const bool = (j, i) => {
        const a_valid = i < va, b_valid = j < vb;
        if(!a_valid || !b_valid)
        {
            if(aggregation === 2) return !a_valid && !b_valid; // equal each
            if(aggregation === 3) return !a_valid; // equal ordered
            return false;
        }
        if(aggregation === 1) return i % 2 === 0 ? eb[j] >= ea[i] : eb[j] <= ea[i]; // ranges
        return ea[i] === eb[j];
    };
    let intres1 = 0;
    for(let j = 0; j < n; j++)
    {
        let r = false;
        switch(aggregation)
        {
            case 0: for(let i = 0; i < n; i++) r ||= bool(j, i); break; // equal any
            case 1: for(let i = 0; i < n; i += 2) r ||= bool(j, i) && bool(j, i + 1); break; // ranges
            case 2: r = bool(j, j); break; // equal each
            case 3: r = true; for(let k = 0; k < n - j; k++) r &&= bool(j + k, k); break; // equal ordered
        }
        if(r) intres1 |= 1 << j;
    }
    const all = (1 << n) - 1;
    let intres2;
    switch(imm8 >> 4 & 3)
    {
        case 1: intres2 = ~intres1 & all; break; // negative
        case 3: intres2 = intres1 ^ (1 << vb) - 1; break; // masked negative: the valid elements of b
        default: intres2 = intres1;
    }
    let index = n;
    if(intres2) index = imm8 & 0x40 ? 31 - Math.clz32(intres2) : 31 - Math.clz32(intres2 & -intres2);
    const mask = imm8 & 0x40 ? lanes(size, i => intres2 >> i & 1 ? -1n : 0n) : lanes(2, i => i === 0 ? BigInt(intres2) : 0n);
    return { intres2, index, mask, cf: intres2 !== 0, zf: vb < n, sf: va < n, of: (intres2 & 1) !== 0 };
}

const reflect = (x, bits) => {
    let r = 0n;
    for(let i = 0n; i < BigInt(bits); i++) r |= (x >> i & 1n) << BigInt(bits) - 1n - i;
    return r;
};
/** Polynomial remainder over GF(2) */
const mod2 = (x, p) => {
    const degree = p.toString(2).length - 1;
    for(let bit = x.toString(2).length - 1; bit >= degree; bit--)
    {
        if(x >> BigInt(bit) & 1n) x ^= p << BigInt(bit - degree);
    }
    return x;
};
/** CRC32 with a source of `bytes` bytes: the SDM's BIT_REFLECT and MOD2 by 11EDC6F41H */
export function crc32(crc, value, bytes)
{
    const bits = bytes * 8;
    const t3 = reflect(BigInt.asUintN(bits, value), bits) << 32n;
    const t4 = reflect(BigInt.asUintN(32, crc), 32) << BigInt(bits);
    return reflect(mod2(t3 ^ t4, 0x11EDC6F41n), 32);
}
                                        source/v64/tests/rust/sse_faults.mjs                                                                0000644 0000000 0000000 00000072160 00000000000 014714  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Legacy SSE exception conditions in the 32-bit engines (docs/simd-xsave-plan.md
// 3.3, P4a). Without CR4.OSFXSR every form that names an XMM register or
// MXCSR is #UD: also with CR0.TS (#UD before #NM), and before any check of
// its memory operand. MMX forms run, including the SSE, SSE2 and SSSE3 ones
// on MMX registers, and so do EMMS and FXSAVE. A misaligned 16-byte memory
// operand is #GP(0) without effect and before #PF, except for MOVUPS,
// MOVUPD, MOVDQU and LDDQU; UNPCKLPS/UNPCKLPD read 8 bytes of an aligned
// m128; narrower operands, MMX forms and the masked stores need no
// alignment. Each program runs in the interpreter, then hot under the page
// tier; the fault log, registers and memory must agree after the hot run and
// after one more round.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const hex = n => (n >>> 0).toString(16);
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

// The program runs at CODE; the length of each faulting instruction is at
// CODE + LENGTHS (its handler skips it). Every form has a slot of 0x40 bytes
// in each region: sources at DATA_A (aligned) and DATA_M (at skew(k)), store
// targets at STORE_A and STORE_M, its results at OUT. The handlers log
// vector, EIP, error code (-1 without) and CR2 (#PF, else 0) per fault.
const CODE = 0x100000, LENGTHS = 0x10000, PATTERN = 0x120000, MM_PATTERN = 0x120080, MXCSR = 0x1200C0;
const DATA_A = 0x130000, DATA_M = 0x140000, STORE_A = 0x150000, STORE_M = 0x160000, OUT = 0x170000;
const LOG = 0x180000, LOG_INDEX = 0x18FFF0, FXAREA = 0x190000;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000, ABSENT = 0x2F0000;
const SLOT = 0x40, REGION = 0x10000;
const skew = k => [8, 4, 1, 12, 15, 2, 9, 6][k % 8];
const EDX_INIT = 0x13572468, EBX_INIT = 0x2468ACE0, MXCSR_INIT = 0x1F80;
const OSFXSR = 0x200, OSXMMEXCPT = 0x400, EM = 4, TS = 8;

let seed = 0x5EED1234;
const random_bytes = n => Uint8Array.from({ length: n }, () => {
    seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
    return seed & 255;
});
const XMM_INIT = random_bytes(128), MM_INIT = random_bytes(64);

// [name, opcode, operands, imm8]. Operands "<ModRM.reg>,<r/m>/<memory>": x
// XMM, m MMX, g GPR (EDX as ModRM.reg, EBX as r/m), a digit the ModRM.reg of
// a group, "=" r/m is ModRM.reg, "-" no register form. Memory: "A" an m128
// that must be 16-byte aligned, a byte count, "-" none, "*" the masked store
// to [EDI]; "!" the memory operand is written.
const XMM_FORMS = [
    ["addps", [0x0F, 0x58], "x,x/A"],
    ["addss", [0xF3, 0x0F, 0x58], "x,x/4"],
    ["mulpd", [0x66, 0x0F, 0x59], "x,x/A"],
    ["divsd", [0xF2, 0x0F, 0x5E], "x,x/8"],
    ["sqrtps", [0x0F, 0x51], "x,x/A"],
    ["minpd", [0x66, 0x0F, 0x5D], "x,x/A"],
    ["maxss", [0xF3, 0x0F, 0x5F], "x,x/4"],
    ["cmpps", [0x0F, 0xC2], "x,x/A", 1],
    ["cmpsd", [0xF2, 0x0F, 0xC2], "x,x/8", 2],
    ["ucomiss", [0x0F, 0x2E], "x,x/4"],
    ["comisd", [0x66, 0x0F, 0x2F], "x,x/8"],
    ["rcpps", [0x0F, 0x53], "x,x/A"],
    ["rsqrtss", [0xF3, 0x0F, 0x52], "x,x/4"],
    ["haddps", [0xF2, 0x0F, 0x7C], "x,x/A"],
    ["hsubpd", [0x66, 0x0F, 0x7D], "x,x/A"],
    ["addsubps", [0xF2, 0x0F, 0xD0], "x,x/A"],
    ["addsubpd", [0x66, 0x0F, 0xD0], "x,x/A"],
    ["cvtps2pd", [0x0F, 0x5A], "x,x/8"],
    ["cvtpd2ps", [0x66, 0x0F, 0x5A], "x,x/A"],
    ["cvtss2sd", [0xF3, 0x0F, 0x5A], "x,x/4"],
    ["cvtsd2ss", [0xF2, 0x0F, 0x5A], "x,x/8"],
    ["cvtdq2ps", [0x0F, 0x5B], "x,x/A"],
    ["cvtps2dq", [0x66, 0x0F, 0x5B], "x,x/A"],
    ["cvttps2dq", [0xF3, 0x0F, 0x5B], "x,x/A"],
    ["cvtdq2pd", [0xF3, 0x0F, 0xE6], "x,x/8"],
    ["cvtpd2dq", [0xF2, 0x0F, 0xE6], "x,x/A"],
    ["cvttpd2dq", [0x66, 0x0F, 0xE6], "x,x/A"],
    ["cvtsi2ss", [0xF3, 0x0F, 0x2A], "x,g/4"],
    ["cvtsi2sd", [0xF2, 0x0F, 0x2A], "x,g/4"],
    ["cvttss2si", [0xF3, 0x0F, 0x2C], "g,x/4"],
    ["cvtsd2si", [0xF2, 0x0F, 0x2D], "g,x/8"],
    // (the conversions between MMX and XMM registers are XMM forms)
    ["cvtpi2ps", [0x0F, 0x2A], "x,m/8"],
    ["cvtpi2pd", [0x66, 0x0F, 0x2A], "x,m/8"],
    ["cvtps2pi", [0x0F, 0x2D], "m,x/8"],
    ["cvttps2pi", [0x0F, 0x2C], "m,x/8"],
    ["cvttpd2pi", [0x66, 0x0F, 0x2C], "m,x/A"],
    ["cvtpd2pi", [0x66, 0x0F, 0x2D], "m,x/A"],
    ["andps", [0x0F, 0x54], "x,x/A"],
    ["andnpd", [0x66, 0x0F, 0x55], "x,x/A"],
    ["orps", [0x0F, 0x56], "x,x/A"],
    ["xorps", [0x0F, 0x57], "x,x/A"],
    ["xorps zeroing", [0x0F, 0x57], "x,=/-"],
    ["unpcklps", [0x0F, 0x14], "x,x/A"],
    ["unpcklpd", [0x66, 0x0F, 0x14], "x,x/A"],
    ["unpckhps", [0x0F, 0x15], "x,x/A"],
    ["unpckhpd", [0x66, 0x0F, 0x15], "x,x/A"],
    ["shufps", [0x0F, 0xC6], "x,x/A", 0x1B],
    ["shufpd", [0x66, 0x0F, 0xC6], "x,x/A", 1],
    ["movmskps", [0x0F, 0x50], "g,x/-"],
    ["movmskpd", [0x66, 0x0F, 0x50], "g,x/-"],
    ["movups", [0x0F, 0x10], "x,x/16"],
    ["movups store", [0x0F, 0x11], "x,x/16!"],
    ["movupd", [0x66, 0x0F, 0x10], "x,x/16"],
    ["movupd store", [0x66, 0x0F, 0x11], "x,x/16!"],
    ["movss", [0xF3, 0x0F, 0x10], "x,x/4"],
    ["movss store", [0xF3, 0x0F, 0x11], "x,x/4!"],
    ["movsd", [0xF2, 0x0F, 0x10], "x,x/8"],
    ["movsd store", [0xF2, 0x0F, 0x11], "x,x/8!"],
    ["movaps", [0x0F, 0x28], "x,x/A"],
    ["movaps store", [0x0F, 0x29], "x,x/A!"],
    ["movapd", [0x66, 0x0F, 0x28], "x,x/A"],
    ["movapd store", [0x66, 0x0F, 0x29], "x,x/A!"],
    ["movntps", [0x0F, 0x2B], "x,-/A!"],
    ["movntpd", [0x66, 0x0F, 0x2B], "x,-/A!"],
    ["movlps", [0x0F, 0x12], "x,x/8"], // (register form: MOVHLPS)
    ["movlps store", [0x0F, 0x13], "x,-/8!"],
    ["movhps", [0x0F, 0x16], "x,x/8"], // (register form: MOVLHPS)
    ["movhps store", [0x0F, 0x17], "x,-/8!"],
    ["movlpd", [0x66, 0x0F, 0x12], "x,-/8"],
    ["movhpd store", [0x66, 0x0F, 0x17], "x,-/8!"],
    ["movsldup", [0xF3, 0x0F, 0x12], "x,x/A"],
    ["movshdup", [0xF3, 0x0F, 0x16], "x,x/A"],
    ["movddup", [0xF2, 0x0F, 0x12], "x,x/8"],
    ["lddqu", [0xF2, 0x0F, 0xF0], "x,-/16"],
    ["movdqa", [0x66, 0x0F, 0x6F], "x,x/A"],
    ["movdqa store", [0x66, 0x0F, 0x7F], "x,x/A!"],
    ["movdqu", [0xF3, 0x0F, 0x6F], "x,x/16"],
    ["movdqu store", [0xF3, 0x0F, 0x7F], "x,x/16!"],
    ["movntdq", [0x66, 0x0F, 0xE7], "x,-/A!"],
    ["maskmovdqu", [0x66, 0x0F, 0xF7], "x,x/*"],
    ["movd xmm, r/m32", [0x66, 0x0F, 0x6E], "x,g/4"],
    ["movd r/m32, xmm", [0x66, 0x0F, 0x7E], "x,g/4!"],
    ["movq xmm, xmm/m64", [0xF3, 0x0F, 0x7E], "x,x/8"],
    ["movq xmm/m64, xmm", [0x66, 0x0F, 0xD6], "x,x/8!"],
    ["movq2dq", [0xF3, 0x0F, 0xD6], "x,m/-"],
    ["movdq2q", [0xF2, 0x0F, 0xD6], "m,x/-"],
    ["paddd", [0x66, 0x0F, 0xFE], "x,x/A"],
    ["psubb", [0x66, 0x0F, 0xF8], "x,x/A"],
    ["pxor", [0x66, 0x0F, 0xEF], "x,x/A"],
    ["pxor zeroing", [0x66, 0x0F, 0xEF], "x,=/-"],
    ["pand", [0x66, 0x0F, 0xDB], "x,x/A"],
    ["pcmpeqb", [0x66, 0x0F, 0x74], "x,x/A"],
    ["pcmpeqd all ones", [0x66, 0x0F, 0x76], "x,=/-"],
    ["pcmpgtd", [0x66, 0x0F, 0x66], "x,x/A"],
    ["punpcklbw", [0x66, 0x0F, 0x60], "x,x/A"],
    ["punpcklqdq", [0x66, 0x0F, 0x6C], "x,x/A"],
    ["punpckhdq", [0x66, 0x0F, 0x6A], "x,x/A"],
    ["packsswb", [0x66, 0x0F, 0x63], "x,x/A"],
    ["packuswb", [0x66, 0x0F, 0x67], "x,x/A"],
    ["pmullw", [0x66, 0x0F, 0xD5], "x,x/A"],
    ["pmulhuw", [0x66, 0x0F, 0xE4], "x,x/A"],
    ["pmuludq", [0x66, 0x0F, 0xF4], "x,x/A"],
    ["pmaddwd", [0x66, 0x0F, 0xF5], "x,x/A"],
    ["psadbw", [0x66, 0x0F, 0xF6], "x,x/A"],
    ["pavgb", [0x66, 0x0F, 0xE0], "x,x/A"],
    ["pminub", [0x66, 0x0F, 0xDA], "x,x/A"],
    ["pmaxsw", [0x66, 0x0F, 0xEE], "x,x/A"],
    ["paddq", [0x66, 0x0F, 0xD4], "x,x/A"],
    ["paddusb", [0x66, 0x0F, 0xDC], "x,x/A"],
    ["psllw", [0x66, 0x0F, 0xF1], "x,x/A"],
    ["psrad", [0x66, 0x0F, 0xE2], "x,x/A"],
    ["psrlq", [0x66, 0x0F, 0xD3], "x,x/A"],
    ["psllw imm8", [0x66, 0x0F, 0x71], "6,x/-", 3],
    ["psrad imm8", [0x66, 0x0F, 0x72], "4,x/-", 5],
    ["psrldq", [0x66, 0x0F, 0x73], "3,x/-", 4],
    ["pslldq", [0x66, 0x0F, 0x73], "7,x/-", 9],
    ["pshufd", [0x66, 0x0F, 0x70], "x,x/A", 0x1B],
    ["pshufhw", [0xF3, 0x0F, 0x70], "x,x/A", 0x39],
    ["pshuflw", [0xF2, 0x0F, 0x70], "x,x/A", 0x93],
    ["pextrw", [0x66, 0x0F, 0xC5], "g,x/-", 5],
    ["pinsrw", [0x66, 0x0F, 0xC4], "x,g/2", 3],
    ["pmovmskb", [0x66, 0x0F, 0xD7], "g,x/-"],
    ["pshufb", [0x66, 0x0F, 0x38, 0x00], "x,x/A"],
    ["palignr", [0x66, 0x0F, 0x3A, 0x0F], "x,x/A", 5],
    ["pmaddubsw", [0x66, 0x0F, 0x38, 0x04], "x,x/A"],
    ["phaddw", [0x66, 0x0F, 0x38, 0x01], "x,x/A"],
    ["psignb", [0x66, 0x0F, 0x38, 0x08], "x,x/A"],
    ["pabsd", [0x66, 0x0F, 0x38, 0x1E], "x,x/A"],
    ["pmulhrsw", [0x66, 0x0F, 0x38, 0x0B], "x,x/A"],
    // (in this order: STMXCSR reads the MXCSR that LDMXCSR set)
    ["ldmxcsr", [0x0F, 0xAE], "2,-/4"],
    ["stmxcsr", [0x0F, 0xAE], "3,-/4!"],
];
const MMX_FORMS = [
    ["paddd mm", [0x0F, 0xFE], "m,m/8"],
    ["pxor mm", [0x0F, 0xEF], "m,m/8"],
    ["pshufw", [0x0F, 0x70], "m,m/8", 0x1B],
    ["pshufb mm", [0x0F, 0x38, 0x00], "m,m/8"],
    ["palignr mm", [0x0F, 0x3A, 0x0F], "m,m/8", 3],
    ["pmaddubsw mm", [0x0F, 0x38, 0x04], "m,m/8"],
    ["pabsb mm", [0x0F, 0x38, 0x1C], "m,m/8"],
    ["movq mm", [0x0F, 0x6F], "m,m/8"],
    ["movq mm store", [0x0F, 0x7F], "m,m/8!"],
    ["movd mm, r/m32", [0x0F, 0x6E], "m,g/4"],
    ["movd r/m32, mm", [0x0F, 0x7E], "m,g/4!"],
    ["pinsrw mm", [0x0F, 0xC4], "m,g/2", 2],
    ["pextrw mm", [0x0F, 0xC5], "g,m/-", 1],
    ["pmovmskb mm", [0x0F, 0xD7], "g,m/-"],
    ["movntq", [0x0F, 0xE7], "m,-/8!"],
    ["maskmovq", [0x0F, 0xF7], "m,m/*"],
    ["pavgb mm", [0x0F, 0xE0], "m,m/8"],
    ["psadbw mm", [0x0F, 0xF6], "m,m/8"],
    ["pmuludq mm", [0x0F, 0xF4], "m,m/8"],
    ["paddq mm", [0x0F, 0xD4], "m,m/8"],
    ["psubq mm", [0x0F, 0xFB], "m,m/8"],
    ["pminub mm", [0x0F, 0xDA], "m,m/8"],
    ["psllw mm, imm8", [0x0F, 0x71], "6,m/-", 3],
    ["punpcklbw mm", [0x0F, 0x60], "m,m/4"],
    ["packsswb mm", [0x0F, 0x63], "m,m/8"],
];
const ALL = [...XMM_FORMS.map(f => [f, true]), ...MMX_FORMS.map(f => [f, false])].map(([[name, op, operands, imm], xmm], k) => {
    const [, reg, rm, memory, store] = /^([xmg0-7]),([xmg=-])\/(A|\d+|-|\*)(!?)$/.exec(operands);
    return { name, op, reg, rm, imm, xmm, k, aligned: memory === "A", memory: !"-*".includes(memory), masked: memory === "*", store: store === "!" };
});
const XMM = ALL.filter(f => f.xmm), MMX = ALL.filter(f => !f.xmm);
const form = name => ALL.find(f => f.name === name);

const reg_of = f => /\d/.test(f.reg) ? +f.reg : f.reg === "g" ? 2 : f.k % 8;
const rm_of = f => f.rm === "=" ? reg_of(f) : f.rm === "g" ? 3 : (f.k + 3) % 8;
/** The instruction, with a register or [address] operand */
const encode = (f, address) => [...f.op,
    ...(address === undefined ? [0xC0 | reg_of(f) << 3 | rm_of(f)] : [0x05 | reg_of(f) << 3, ...u32(address)]),
    ...(f.imm === undefined ? [] : [f.imm])];
/** The memory operand of slot k (for masked stores [EDI]) */
const slot = (f, misaligned) => (f.store || f.masked ? (misaligned ? STORE_M : STORE_A) : (misaligned ? DATA_M : DATA_A)) +
    f.k * SLOT + (misaligned ? skew(f.k) : 0);

// Sources: random bytes, the same at both addresses of a slot; LDMXCSR's is
// the initial MXCSR
const DATA = random_bytes(REGION);
DATA.set(u32(MXCSR_INIT), form("ldmxcsr").k * SLOT);
const DATA_SKEWED = random_bytes(REGION);
for(const f of ALL) DATA_SKEWED.set(DATA.subarray(f.k * SLOT, (f.k + 1) * SLOT - skew(f.k)), f.k * SLOT + skew(f.k));

const movdqu_load = (r, a) => [0xF3, 0x0F, 0x6F, 0x05 | r << 3, ...u32(a)];
const movdqu_store = (r, a) => [0xF3, 0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
const movq_load = (r, a) => [0x0F, 0x6F, 0x05 | r << 3, ...u32(a)];
const movq_store = (r, a) => [0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
const mov_edx = v => [0xBA, ...u32(v)], mov_ebx = v => [0xBB, ...u32(v)], mov_edi = v => [0xBF, ...u32(v)];
const store_edx = a => [0x89, 0x15, ...u32(a)], store_ebx = a => [0x89, 0x1D, ...u32(a)];
const ldmxcsr = a => [0x0F, 0xAE, 0x15, ...u32(a)], stmxcsr = a => [0x0F, 0xAE, 0x1D, ...u32(a)];
const fxsave = a => [0x0F, 0xAE, 0x05, ...u32(a)], fxrstor = a => [0x0F, 0xAE, 0x0D, ...u32(a)];
const EMMS = [0x0F, 0x77], CLTS = [0x0F, 0x06];
const SET_CR0 = bits => [0x0F, 0x20, 0xC0, 0x0D, ...u32(bits), 0x0F, 0x22, 0xC0];
const CLEAR_CR0 = bits => [0x0F, 0x20, 0xC0, 0x25, ...u32(~bits >>> 0), 0x0F, 0x22, 0xC0];
const SET_CR4 = bits => [0x0F, 0x20, 0xE0, 0x0D, ...u32(bits), 0x0F, 0x22, 0xE0];
const CLEAR_CR4 = bits => [0x0F, 0x20, 0xE0, 0x25, ...u32(~bits >>> 0), 0x0F, 0x22, 0xE0];
// (every round: the IDT, CR0.TS and CR0.EM clear, OSFXSR, MXCSR, the log)
const PROLOGUE = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...CLTS, ...CLEAR_CR0(EM), ...SET_CR4(OSFXSR | OSXMMEXCPT),
    ...ldmxcsr(MXCSR), 0xC7, 0x05, ...u32(LOG_INDEX), ...u32(0)];

class Program
{
    constructor() { this.code = [...PROLOGUE]; this.expected = []; }
    emit(...code) { this.code.push(...code); return this; }
    /** `code`, which raises `fault` ([vector, error code, CR2]) if given */
    insn(code, fault, name = "") {
        if(fault)
        {
            const [vector, error_code = -1, cr2 = 0] = fault;
            this.expected.push({ vector, eip: CODE + this.code.length, error_code: error_code >>> 0, cr2, length: code.length, name });
        }
        return this.emit(...code);
    }
    /** The rounds: the body repeats until byte 0x604 is set, then halts after one more */
    build()
    {
        const code = [...this.code, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
        code.push(0xE9, ...u32(-code.length - 5), 0xF4);
        const lengths = new Uint8Array(code.length);
        for(const { eip, length } of this.expected) lengths[eip - CODE] = length;
        return { code: Uint8Array.from(code), lengths, expected: this.expected };
    }
}

/** A handler for `vector`: logs the fault and skips the faulting instruction (halts if it is not in the table) */
const handler = (vector, error_code) => [
    0x8B, 0x0D, ...u32(LOG_INDEX), // mov ecx, [LOG_INDEX]
    0xC1, 0xE1, 0x04, // shl ecx, 4
    ...(error_code ? [0x58] : [0xB8, ...u32(-1)]), // pop eax / mov eax, -1
    0x89, 0x81, ...u32(LOG + 8), // mov [ecx + LOG + 8], eax
    0xC7, 0x81, ...u32(LOG), ...u32(vector), // mov dword [ecx + LOG], vector
    ...(vector === 14 ? [0x0F, 0x20, 0xD0] : [0x31, 0xC0]), // mov eax, cr2 / xor eax, eax
    0x89, 0x81, ...u32(LOG + 12), // mov [ecx + LOG + 12], eax
    0x8B, 0x04, 0x24, // mov eax, [esp]
    0x89, 0x81, ...u32(LOG + 4), // mov [ecx + LOG + 4], eax
    0xFF, 0x05, ...u32(LOG_INDEX), // inc dword [LOG_INDEX]
    0x0F, 0xB6, 0x80, ...u32(LENGTHS), // movzx eax, byte [eax + LENGTHS]
    0x85, 0xC0, 0x75, 0x03, 0xF4, 0xEB, 0xFD, // test eax, eax; jnz +3; hlt; jmp hlt
    0x01, 0x04, 0x24, // add [esp], eax
    0xCF, // iret
];
const VECTORS = [[6, false], [7, false], [13, true], [14, true], [19, false]];

const pages = (vm, page, present) => {
    // (the BIOS's page table: 0x13000, identity)
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};

const machines = [];
const labels = ["interpreter", ...COMPILED_ARMS.map(arm => arm.label)];
async function run(vm, code, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(code, CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && (compiled_activations(e) - start >>> 0) < 3)
    {
        if(performance.now() > deadline)
        {
            await vm.stop();
            const n = word(vm, LOG_INDEX), last = n ? [0, 4, 8, 12].map(o => hex(word(vm, LOG + (n - 1) * 16 + o))) : [];
            assert.fail(`program timeout at EIP ${hex(cpu.instruction_pointer[0])}, ${n} faults logged, the last ${last.join(" ")}`);
        }
        await sleep(1);
    }
    if(warm) await sleep(50);
    await vm.stop();
}

/** Runs the program on every machine, hot then one round cold; checks the
 * fault log of each run and that the runs agree. Returns the interpreter's. */
async function execute(program, setup = () => {})
{
    const { code, lengths, expected } = program.build();
    const results = [];
    for(const [i, vm] of machines.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], n) => {
            const h = HANDLER + n * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            vm.write_memory(lengths, CODE + LENGTHS);
            vm.write_memory(XMM_INIT, PATTERN);
            vm.write_memory(MM_INIT, MM_PATTERN);
            vm.write_memory(Uint8Array.from(u32(MXCSR_INIT)), MXCSR);
            vm.write_memory(DATA, DATA_A);
            vm.write_memory(DATA_SKEWED, DATA_M);
            vm.write_memory(new Uint8Array(REGION).fill(0xEE), STORE_A);
            vm.write_memory(new Uint8Array(REGION).fill(0xEE), STORE_M);
            vm.write_memory(new Uint8Array(REGION), OUT);
            vm.write_memory(new Uint8Array(REGION), LOG);
            vm.write_memory(new Uint8Array(0x1000).fill(0xEE), FXAREA);
            setup(vm);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, code, warm, i === 0);
            results.push({
                label: `${labels[i]} (${warm ? "hot" : "one round"})`,
                log: bytes(vm, LOG, (expected.length + 1) * 16),
                out: bytes(vm, OUT, REGION), store_a: bytes(vm, STORE_A, REGION), store_m: bytes(vm, STORE_M, REGION),
                fxarea: bytes(vm, FXAREA + 0x400, 0x400), below_absent: bytes(vm, ABSENT - 0x40, 0x40),
            });
        }
    }
    for(const result of results)
    {
        const view = new DataView(result.log.buffer);
        for(let n = 0; n <= expected.length; n++)
        {
            const [vector, eip, error_code, cr2] = [0, 4, 8, 12].map(o => view.getUint32(n * 16 + o, true));
            if(n === expected.length)
            {
                assert.equal(vector, 0, `${result.label}: an unexpected fault #${vector} at ${hex(eip)}`);
                break;
            }
            const e = expected[n];
            if(vector !== e.vector || eip !== e.eip || error_code !== e.error_code || cr2 !== e.cr2)
            {
                assert.fail(`${result.label}: fault ${n} (${e.name}): #${vector} at ${hex(eip)}, error code ${hex(error_code)}, CR2 ${hex(cr2)}; ` +
                    `expected #${e.vector} at ${hex(e.eip)}, error code ${hex(e.error_code)}, CR2 ${hex(e.cr2)}`);
            }
        }
        for(const key of ["out", "store_a", "store_m", "fxarea", "below_absent"])
        {
            same(result[key], results[0][key], `${result.label}: ${key} as in the interpreter`);
        }
    }
    return results[0];
}
/** Byte equality, reporting the first difference (the slot's form, for slotted regions) */
function same(actual, expected, what, base = 0)
{
    for(let i = 0; i < Math.max(actual.length, expected.length); i++)
    {
        if(actual[i] !== expected[i])
        {
            const f = ALL[(base + i) / SLOT | 0];
            assert.fail(`${what}: byte ${hex(base + i)}${f ? " (slot of " + f.name + ")" : ""} is ${actual[i]?.toString(16)}, expected ${expected[i]?.toString(16)}`);
        }
    }
}

const load_registers = p => {
    for(let r = 0; r < 8; r++) p.emit(...movdqu_load(r, PATTERN + 16 * r));
    for(let r = 0; r < 8; r++) p.emit(...movq_load(r, MM_PATTERN + 8 * r));
    p.emit(...mov_edx(EDX_INIT), ...mov_ebx(EBX_INIT));
};
// XMM registers at OUT, MMX registers at OUT + 0x80, EDX, EBX and MXCSR at OUT + 0xC0
const save_registers = p => {
    for(let r = 0; r < 8; r++) p.emit(...movdqu_store(r, OUT + 16 * r));
    for(let r = 0; r < 8; r++) p.emit(...movq_store(r, OUT + 0x80 + 8 * r));
    p.emit(...EMMS, ...store_edx(OUT + 0xC0), ...store_ebx(OUT + 0xC4), ...stmxcsr(OUT + 0xC8));
};
const registers_kept = (result, what) => {
    same(result.out.subarray(0, 0x80), XMM_INIT, `${what}: XMM registers kept`);
    assert.equal(new DataView(result.out.buffer).getUint32(0xC8, true), MXCSR_INIT, `${what}: MXCSR kept`);
};
const ABSENT_FORMS = ["addps", "movaps", "movdqa store", "pshufb", "ldmxcsr", "stmxcsr"];

let checks = 0;
try
{
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            cpu_features: ["SSSE3"], ...arm, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        machines.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }

    // CR4.OSFXSR and CR0.TS. The forms in register and memory variants (the
    // memory operand misaligned or absent), alternating XMM and MMX forms (a
    // block checks the MMX conditions, then those of an XMM form)
    const task = ({ osfxsr, ts, xmm = true }) => {
        const p = new Program();
        load_registers(p);
        if(!osfxsr) p.emit(...CLEAR_CR4(OSFXSR));
        if(ts) p.emit(...SET_CR0(TS));
        const xmm_fault = osfxsr ? [7] : [6], mmx_fault = ts ? [7] : undefined;
        const variants = f => f.masked ? [[mov_edi(slot(f, true)), encode(f)]] :
            [...(f.rm === "-" ? [] : [[[], encode(f)]]), ...(f.memory ? [[[], encode(f, slot(f, true))]] : [])];
        for(let i = 0; i < XMM.length; i++)
        {
            if(xmm) for(const [before, code] of variants(XMM[i])) p.emit(...before).insn(code, xmm_fault, XMM[i].name);
            if(i < MMX.length) for(const [before, code] of variants(MMX[i])) p.emit(...before).insn(code, mmx_fault, MMX[i].name);
        }
        if(xmm) for(const name of ABSENT_FORMS) p.insn(encode(form(name), ABSENT + (form(name).aligned ? 0 : 8)), xmm_fault, name + " [absent]");
        p.insn(EMMS, mmx_fault, "emms").insn(fxsave(FXAREA), mmx_fault, "fxsave");
        if(ts) p.emit(...CLTS);
        if(!osfxsr) p.emit(...SET_CR4(OSFXSR));
        save_registers(p);
        return p;
    };
    const absent = vm => pages(vm, ABSENT, false);
    const reference = await execute(task({ osfxsr: true, ts: false, xmm: false }));
    const without = await execute(task({ osfxsr: false, ts: false }), absent);
    registers_kept(without, "without OSFXSR");
    same(without.out.subarray(0x80, 0xC8), reference.out.subarray(0x80, 0xC8), "without OSFXSR: MMX registers, EDX, EBX as with it");
    same(without.store_m, reference.store_m, "without OSFXSR: memory as with it (the MMX stores)");
    const ud = task({ osfxsr: false, ts: false }).expected.length;
    for(const [osfxsr, what] of [[false, "without OSFXSR, CR0.TS: #UD, MMX forms #NM"], [true, "with CR0.TS: #NM"]])
    {
        const result = await execute(task({ osfxsr, ts: true }), absent);
        registers_kept(result, what);
        same(result.out.subarray(0x80, 0xC0), MM_INIT, `${what}: MMX registers kept`);
        assert.deepEqual([...result.out.subarray(0xC0, 0xC8)], [...u32(EDX_INIT), ...u32(EBX_INIT)], `${what}: EDX, EBX kept`);
        same(result.store_m, new Uint8Array(REGION).fill(0xEE), `${what}: memory kept`);
    }
    for(const vm of machines) pages(vm, ABSENT, true);
    checks += 4;
    console.log(`PASS: without CR4.OSFXSR ${ud} XMM form variants are #UD (also with CR0.TS, misaligned or absent operands) and ${MMX.length} MMX forms, EMMS and FXSAVE run; with CR0.TS all are #NM`);

    // Alignment: every memory form at an aligned, then a misaligned address
    const alignment = misaligned => {
        const p = new Program();
        for(const f of ALL.filter(f => f.memory || f.masked))
        {
            const r = reg_of(f);
            // the register the form writes (or stores), reloaded; the mask too
            if(f.reg === "x") p.emit(...movdqu_load(r, PATTERN + 16 * r));
            if(f.reg === "m") p.emit(...movq_load(r, MM_PATTERN + 8 * r));
            if(f.reg === "g") p.emit(...mov_edx(EDX_INIT));
            if(f.masked && f.rm === "x") p.emit(...movdqu_load(rm_of(f), PATTERN + 16 * rm_of(f)));
            if(f.masked && f.rm === "m") p.emit(...movq_load(rm_of(f), MM_PATTERN + 8 * rm_of(f)));
            if(f.masked) p.emit(...mov_edi(slot(f, misaligned))).insn(encode(f));
            else p.insn(encode(f, slot(f, misaligned)), misaligned && f.aligned ? [13, 0] : undefined, f.name);
            const out = OUT + f.k * SLOT;
            p.emit(...f.reg === "x" ? movdqu_store(r, out) : f.reg === "m" ? movq_store(r, out) : f.reg === "g" ? store_edx(out) : stmxcsr(out));
        }
        const area = FXAREA + (misaligned ? 0x408 : 0);
        p.insn(fxsave(area), misaligned ? [13, 0] : undefined, "fxsave").insn(fxrstor(area), misaligned ? [13, 0] : undefined, "fxrstor");
        p.emit(...EMMS);
        return p;
    };
    const aligned = await execute(alignment(false)), skewed = await execute(alignment(true));
    let faulting = 0, passing = 0;
    for(const f of ALL.filter(f => f.memory || f.masked))
    {
        const at = f.k * SLOT, r = reg_of(f), what = `${f.name} [misaligned by ${skew(f.k)}]`;
        if(f.aligned)
        {
            // #GP(0): the register and memory are kept
            const kept = f.reg === "x" ? XMM_INIT.subarray(16 * r, 16 * r + 16) : f.reg === "m" ? MM_INIT.subarray(8 * r, 8 * r + 8) : Uint8Array.from(u32(EDX_INIT));
            same(skewed.out.subarray(at, at + kept.length), kept, `${what}: register kept`);
            same(skewed.store_m.subarray(at, at + SLOT), new Uint8Array(SLOT).fill(0xEE), `${what}: memory kept`, at);
            faulting++;
        }
        else
        {
            same(skewed.out.subarray(at, at + 16), aligned.out.subarray(at, at + 16), `${what}: result as aligned`, at);
            const s = skew(f.k);
            same(skewed.store_m.subarray(at + s, at + SLOT), aligned.store_a.subarray(at, at + SLOT - s), `${what}: stored as aligned`, at);
            same(skewed.store_m.subarray(at, at + s), new Uint8Array(s).fill(0xEE), `${what}: nothing stored below`, at);
            passing++;
        }
    }
    same(skewed.fxarea.subarray(0, 0x210), new Uint8Array(0x210).fill(0xEE), "fxsave [misaligned]: memory kept");
    checks += 2;
    console.log(`PASS: misaligned, ${faulting} memory forms are #GP(0) without effect (also FXSAVE, FXRSTOR) and ${passing} run as aligned`);

    // #GP(0) for alignment comes before #PF; #NM (CR0.TS) before both
    const order = new Program();
    load_registers(order);
    const cases = [
        ["movaps", ABSENT + 8, [13, 0]],
        ["movaps", ABSENT, [14, 0, ABSENT]],
        ["movaps store", ABSENT + 4, [13, 0]],
        ["movaps store", ABSENT, [14, 2, ABSENT]],
        ["unpcklps", ABSENT + 8, [13, 0]],
        ["unpcklpd", ABSENT, [14, 0, ABSENT]],
        ["pshufd", ABSENT + 1, [13, 0]],
        ["addps", ABSENT + 12, [13, 0]],
        ["pshufb", ABSENT + 2, [13, 0]],
        ["movntdq", ABSENT + 8, [13, 0]],
        ["cvttpd2pi", ABSENT + 8, [13, 0]],
        ["movups", ABSENT + 8, [14, 0, ABSENT + 8]],
        ["movups", ABSENT - 8, [14, 0, ABSENT]],
        ["lddqu", ABSENT - 4, [14, 0, ABSENT]],
        ["movdqu store", ABSENT - 8, [14, 2, ABSENT]],
        ["addss", ABSENT + 8, [14, 0, ABSENT + 8]],
        ["paddd mm", ABSENT + 8, [14, 0, ABSENT + 8]],
    ];
    for(const [name, address, fault] of cases) order.insn(encode(form(name), address), fault, `${name} [${hex(address)}]`);
    order.emit(...SET_CR0(TS));
    for(const [name, address] of [["addps", ABSENT + 8], ["movaps store", ABSENT + 4], ["paddd mm", ABSENT + 8], ["movdqa", DATA_M + 1]])
    {
        order.insn(encode(form(name), address), [7], `${name} [${hex(address)}] with CR0.TS`);
    }
    order.emit(...CLTS);
    save_registers(order);
    const ordered = await execute(order, vm => {
        vm.write_memory(new Uint8Array(0x40).fill(0xEE), ABSENT - 0x40);
        pages(vm, ABSENT, false);
    });
    for(const vm of machines) pages(vm, ABSENT, true);
    registers_kept(ordered, "page faults");
    same(ordered.out.subarray(0x80, 0xC0), MM_INIT, "page faults: MMX registers kept");
    same(ordered.below_absent, new Uint8Array(0x40).fill(0xEE), "a store across into an absent page: nothing written");
    checks++;
    console.log(`PASS: #GP(0) for misalignment before #PF (${cases.length} cases), #NM before both`);
    console.log(`PASS: ${checks} legacy SSE fault checks on ${machines.length} arms`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/rust/sse_fp.mjs                                                                    0000644 0000000 0000000 00000040665 00000000000 014030  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Exact SSE floating point in the 32-bit engines (docs/simd-xsave-plan.md
// 7.4, P4a, P4b): every SSE/SSE2/SSE3/SSE4.1 floating-point form (ROUND and
// DPPS/DPPD with tests/rust/sse4_model.mjs's use of the model), with register and
// memory sources, against the model of tests/rust/sse_fp_model.mjs (exact
// rational arithmetic, independent of SoftFloat and cpu/simd_fp.rs). Each
// case sets MXCSR (the four rounding modes, DAZ, FZ, masked and unmasked
// exceptions, PE set or not) and checks the destination, MXCSR and the fault:
// #XM, or #UD without CR4.OSXMMEXCPT, with the destination unchanged. Values
// include zeros, denormals, the normal extremes, infinities, QNaNs and SNaNs
// and results that overflow, underflow or are inexact. Every case runs in the
// interpreter, then hot under the page tier, whose native paths
// (x86tpl::native_fp) must be refused exactly where they would differ.
// Then the same cases run as 64-bit code in long mode under the x64 page
// tier (docs/jit-unification-plan.md P4.18: its templates with JIT_SWITCHES
// x64_sse_fast_check=1, else the forms it takes before P4.18).
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { FORMS, MXCSRS, bytes128, cases } from "./sse_fp_cases.mjs";
import { assemble, actual as run_guest } from "../x64/guest_runner.mjs";
import { long_mode_guest } from "../x64/guest_builder.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x300000, FAULTS = 0x3F0000, CASE = 0x3FF000, SKIP = 0x3FF004;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);

// the code of a case: MXCSR, the operands, the instruction, its results
const ldmxcsr = a => [0x0F, 0xAE, 0x15, ...u32(a)], stmxcsr = a => [0x0F, 0xAE, 0x1D, ...u32(a)];
const movdqu_load = (r, a) => [0xF3, 0x0F, 0x6F, 0x05 | r << 3, ...u32(a)];
const movdqu_store = (r, a) => [0xF3, 0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
const movq_load = (r, a) => [0x0F, 0x6F, 0x05 | r << 3, ...u32(a)], movq_store = (r, a) => [0x0F, 0x7F, 0x05 | r << 3, ...u32(a)];
const mov_eax = a => [0xA1, ...u32(a)], store_eax = a => [0xA3, ...u32(a)];
const EMMS = [0x0F, 0x77];
/** The instruction: register 1 (XMM, MMX or EAX) and register 0 or [source] */
function instruction(form, memory, source, imm8)
{
    const rm = memory ? [0x05 | 1 << 3, ...u32(source)] : [0xC0 | 1 << 3 | 0];
    return [...form.prefix, 0x0F, ...(form.map ? [form.map] : []), form.code, ...rm, ...(form.imm8 ? [imm8] : [])];
}
function program(form, memory, list)
{
    const p = [];
    list.forEach((c, n) => {
        const base = DATA + n * 64;
        p.push(0xC7, 0x05, ...u32(CASE), ...u32(n));
        p.push(...ldmxcsr(base + 32));
        // register 1: the destination; register 0: the source (unless memory)
        if(form.kind === "to_gpr") p.push(0xB9, ...u32(0x5A5A5A5A)); // ecx (register 1)
        else if(form.kind === "to_mmx") p.push(...movq_load(1, base));
        else p.push(...movdqu_load(1, base));
        if(!memory)
        {
            if(form.kind === "from_gpr") p.push(0xB8, ...u32(Number(c.b & 0xFFFFFFFFn)));
            else if(form.kind === "from_mmx") p.push(...movq_load(0, base + 16));
            else p.push(...movdqu_load(0, base + 16));
        }
        p.push(...instruction(form, memory, base + 16, c.imm8));
        p.push(...stmxcsr(OUT + n * 32 + 16));
        if(form.kind === "comi") p.push(0x9C, 0x58, ...store_eax(OUT + n * 32));
        else if(form.kind === "to_gpr") p.push(0x89, 0x0D, ...u32(OUT + n * 32));
        else if(form.kind === "to_mmx") p.push(...movq_store(1, OUT + n * 32), ...EMMS);
        else p.push(...movdqu_store(1, OUT + n * 32));
        if(form.kind === "from_mmx") p.push(...EMMS);
    });
    return p;
}

const machines = [];
async function run(vm, code, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(code), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 60000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it for the case, skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58);
    p.push(0xA1, ...u32(CASE), 0xC7, 0x04, 0x85, ...u32(FAULTS), ...u32(vector)); // mov [FAULTS + eax*4], vector
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true], [19, false]];
async function create_machines()
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 64 << 20,
            // (the SSE4.1 forms: ROUND, DPPS/DPPD)
            cpu_features: ["SSSE3", "SSE4.1"],
            ...arm, disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}

// The long-mode column: a form's cases as 64-bit code, LONG_ROUNDS times
// over (the page tier compiles each page during the first rounds), with an
// IDT whose handlers record a fault for the case and skip the instruction
// as above. A fault resumes at a jump's target, a block start of the page
// function, so the rest of the page runs compiled.
const L_DATA = 0x400000, L_OUT = 0x800000, L_FAULTS = 0xA00000, L_CASE = 0xA10000, L_SKIP = 0xA10004, L_IDT = 0xA20000;
const LONG_ROUNDS = 24;
/** The instruction in 64-bit code ([source] through a SIB byte: ModRM 0x05 is RIP-relative there) */
function instruction64(form, memory, source, imm8)
{
    const rm = memory ? [0x04 | 1 << 3, 0x25, ...u32(source)] : [0xC0 | 1 << 3 | 0];
    return [...form.prefix, 0x0F, ...(form.map ? [form.map] : []), form.code, ...rm, ...(form.imm8 ? [imm8] : [])];
}
function long_program(form, memory, list, xmm_exceptions)
{
    const lines = [];
    for(const [vector] of VECTORS)
    {
        const gate = L_IDT + vector * 16;
        lines.push(`lea rax, [rel fault${vector}]`, `mov [${gate}], ax`, `mov word [${gate + 2}], 24`, `mov word [${gate + 4}], 0x8E00`,
            "shr rax, 16", `mov [${gate + 6}], ax`, "shr rax, 16", `mov [${gate + 8}], eax`, `mov dword [${gate + 12}], 0`);
    }
    lines.push("lidt [rel idtr]", "mov rax, cr4", `or eax, ${xmm_exceptions ? 0x600 : 0x200}`, ...(xmm_exceptions ? [] : ["and eax, ~0x400"]),
        "mov cr4, rax", `mov r15d, ${LONG_ROUNDS}`, "cases:");
    list.forEach((c, n) => {
        const base = L_DATA + n * 64, out = L_OUT + n * 32;
        lines.push(`mov dword [${L_CASE}], ${n}`, `ldmxcsr [${base + 32}]`);
        if(form.kind === "to_gpr") lines.push("mov ecx, 0x5A5A5A5A");
        else if(form.kind === "to_mmx") lines.push(`movq mm1, [${base}]`);
        else lines.push(`movdqu xmm1, [${base}]`);
        if(!memory)
        {
            if(form.kind === "from_gpr") lines.push(`mov eax, ${Number(c.b & 0xFFFFFFFFn)}`);
            else if(form.kind === "from_mmx") lines.push(`movq mm0, [${base + 16}]`);
            else lines.push(`movdqu xmm0, [${base + 16}]`);
        }
        // (a fault skips the instruction and the 2-byte jump: L_SKIP)
        lines.push(`db ${instruction64(form, memory, base + 16, c.imm8).join(",")}`, `jmp short resume${n}`, `resume${n}:`,
            `stmxcsr [${out + 16}]`);
        if(form.kind === "comi") lines.push("pushfq", "pop rax", `mov [${out}], eax`);
        else if(form.kind === "to_gpr") lines.push(`mov [${out}], ecx`);
        else if(form.kind === "to_mmx") lines.push(`movq [${out}], mm1`, "emms");
        else lines.push(`movdqu [${out}], xmm1`);
        if(form.kind === "from_mmx") lines.push("emms");
    });
    lines.push("dec r15d", "jnz cases");
    const handlers = VECTORS.map(([vector, error_code]) => [`fault${vector}:`, "push rax", `mov eax, [${L_CASE}]`,
        `mov dword [${L_FAULTS} + rax * 4], ${vector}`, `mov eax, [${L_SKIP}]`, `add [rsp + ${error_code ? 16 : 8}], rax`, "pop rax",
        ...(error_code ? ["add rsp, 8"] : []), "iretq"].join("\n"));
    return long_mode_guest(lines.join("\n"), [...handlers, "align 8", `idtr: dw 4095`, `dq ${L_IDT}`].join("\n"));
}
/** Run the cases of `form` in long mode under the page tier: its outputs and fault vectors */
async function run_long(form, memory, list, xmm_exceptions, data)
{
    const directory = assemble(`sse-fp-model-${form.name}${memory ? "-mem" : ""}`, long_program(form, memory, list, xmm_exceptions));
    let out, faults, native;
    await run_guest(directory, {
        length: 8, timeout: 120000,
        options: { wasm_path: candidate, disable_jit: false, ir_sync_publication: true, cpu_features: ["SSSE3", "SSE4.1"] },
        setup: emulator => {
            const cpu = emulator.v86.cpu;
            cpu.mem8.set(data, L_DATA);
            cpu.mem8.fill(0, L_OUT, L_OUT + list.length * 32);
            cpu.mem8.fill(0, L_FAULTS, L_FAULTS + list.length * 4);
            cpu.mem8.set(u32(instruction64(form, memory, 0, 0).length + 2), L_SKIP);
        },
        inspect: emulator => {
            const cpu = emulator.v86.cpu;
            out = cpu.mem8.slice(L_OUT, L_OUT + list.length * 32);
            faults = cpu.mem8.slice(L_FAULTS, L_FAULTS + list.length * 4);
            native = cpu.wm.exports.x64_page_stat(1);
        },
    });
    return { out, faults, native };
}

/** Compare a run's outputs (and fault vectors) for `list` with the model */
function check(form, memory, list, run, out, fault_bytes, xmm_exceptions)
{
    const faults = new DataView(fault_bytes.buffer);
    const view = new DataView(out.buffer);
    list.forEach((c, n) => {
        const label = `${form.name}${memory ? " [mem]" : ""} case ${n} on ${run}: mxcsr ${c.mxcsr.toString(16)} a ${c.a.toString(16)} b ${c.b.toString(16)}${form.imm8 ? " imm8 " + c.imm8 : ""}`;
        const vector = faults.getUint32(n * 4, true);
        assert.equal(vector, c.fault ? xmm_exceptions ? 19 : 6 : 0, label + ": fault");
        assert.equal(view.getUint32(n * 32 + 16, true), c.after, label + ": MXCSR");
        // a faulting instruction leaves its destination alone
        const destination = form.kind === "to_gpr" ? 0x5A5A5A5An : form.kind === "comi" ? undefined : c.a;
        let actual, expected;
        if(form.kind === "comi")
        {
            actual = BigInt(view.getUint32(n * 32, true) & 0x8D5);
            expected = c.fault ? undefined : BigInt(c.result);
        }
        else if(form.kind === "to_gpr")
        {
            actual = BigInt(view.getUint32(n * 32, true));
            expected = c.fault ? destination : c.result & 0xFFFFFFFFn;
        }
        else if(form.kind === "to_mmx")
        {
            actual = view.getBigUint64(n * 32, true);
            expected = c.fault ? c.a & 0xFFFFFFFFFFFFFFFFn : c.result;
        }
        else
        {
            actual = view.getBigUint64(n * 32, true) | view.getBigUint64(n * 32 + 8, true) << 64n;
            expected = c.fault ? destination : c.result;
        }
        if(expected !== undefined) assert.equal(actual.toString(16), expected.toString(16), label + ": result");
    });
}

let total = 0, long_total = 0;
try
{
    machines.push(...await create_machines());
    for(const xmm_exceptions of [true, false])
    {
        // CR4.OSFXSR and OSXMMEXCPT (else unmasked exceptions are #UD), CR0.TS clear
        const cr4 = [0x0F, 0x20, 0xE0, 0x0D, ...u32(xmm_exceptions ? 0x600 : 0x200), ...(xmm_exceptions ? [] : [0x25, ...u32(~0x400 >>> 0)]), 0x0F, 0x22, 0xE0];
        const prologue = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), 0x0F, 0x06, ...cr4];
        for(const form of xmm_exceptions ? FORMS : FORMS.filter(f => f.kind === "binary" && !f.double))
        {
            // (SSE_FP_ONLY=name: one form, for debugging)
            if(process.env.SSE_FP_ONLY && form.name !== process.env.SSE_FP_ONLY) continue;
            for(const memory of [false, true])
            {
                const list = cases(form);
                const length = instruction(form, memory, 0, 0).length;
                const code = loop([...prologue, ...program(form, memory, list)]);
                const data = new Uint8Array(list.length * 64);
                list.forEach((c, n) => {
                    data.set(bytes128(c.a), n * 64);
                    data.set(bytes128(c.b), n * 64 + 16);
                    data.set(u32(c.mxcsr), n * 64 + 32);
                });
                // (every run: the cold one is mostly interpreted, the program was rewritten)
                const runs = [];
                for(const [m, vm] of machines.entries())
                {
                    vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
                    VECTORS.forEach(([vector, error_code], i) => {
                        const h = HANDLER + i * 0x100;
                        vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
                        vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
                    });
                    vm.write_memory(Uint8Array.from(u32(length)), SKIP);
                    for(const warm of [true, false])
                    {
                        vm.write_memory(data, DATA);
                        vm.write_memory(new Uint8Array(list.length * 32), OUT);
                        vm.write_memory(new Uint8Array(list.length * 4), FAULTS);
                        vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
                        await run(vm, code, warm, vm === machines[0]);
                        runs.push({ run: `machine ${m} ${warm ? "hot" : "one round"}`, out: Uint8Array.from(vm.read_memory(OUT, list.length * 32)),
                            faults: Uint8Array.from(vm.read_memory(FAULTS, list.length * 4)) });
                    }
                }
                for(const { run, out, faults } of runs) check(form, memory, list, run, out, faults, xmm_exceptions);
                // (the long-mode column: SSE_FP_LONG=0 leaves it out)
                if(process.env.SSE_FP_LONG !== "0")
                {
                    const { out, faults, native } = await run_long(form, memory, list, xmm_exceptions, data);
                    // (each case runs some 10 instructions, which the page tier
                    // compiles from the third round on; a form it steps leaves
                    // a page function at each case)
                    assert.ok(native > list.length * 2 * LONG_ROUNDS, `${form.name}: the page tier ran the cases (${native} native instructions)`);
                    check(form, memory, list, "the x64 page tier", out, faults, xmm_exceptions);
                    long_total += list.length;
                }
                total += list.length;
            }
        }
        console.log(`PASS: ${xmm_exceptions ? "all forms, unmasked exceptions as #XM" : "unmasked exceptions as #UD without CR4.OSXMMEXCPT"}`);
    }
    console.log(`PASS: ${total} exact SSE floating-point cases (${FORMS.length} forms, register and memory sources, ${MXCSRS.length} MXCSR settings) match the model in the interpreter and the page tier`);
    if(long_total) console.log(`PASS: ${long_total} of them as 64-bit code under the x64 page tier`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                           source/v64/tests/rust/sse_fp_cases.mjs                                                              0000644 0000000 0000000 00000035740 00000000000 015204  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The SSE floating-point forms of tests/rust/sse_fp.mjs and their VEX forms
// (tests/rust/avx_fp.mjs): their cases, special values for each lane, MXCSR
// settings, and the model's result for each (tests/rust/sse_fp_model.mjs,
// exact rational arithmetic, independent of SoftFloat and cpu/simd_fp.rs).
import * as model from "./sse_fp_model.mjs";
import { dot_product, round_lane } from "./sse4_model.mjs";

// the values: special ones, and a few to overflow, underflow and round
export const SINGLE = [0n, 0x80000000n, 0x3F800000n, 0xBF800000n, 0x3FC00000n, 1n, 0x807FFFFFn, 0x00800000n, 0x80800000n,
    0x7F7FFFFFn, 0xFF7FFFFFn, 0x7F800000n, 0xFF800000n, 0x7FC00001n, 0xFF812345n, 0x7F800003n,
    0x40400000n, 0x3DCCCCCDn, 0x7149F2CAn, 0x0DA24260n, 0x00C00000n, 0x4B800001n, 0xCF000000n, 0x4F000000n,
    // a product that rounds to the smallest normal but is tiny after rounding (UE)
    0x3EFFFFFFn, 0x01000000n];
export const DOUBLE = [0n, 0x8000000000000000n, 0x3FF0000000000000n, 0xBFF0000000000000n, 0x3FF8000000000000n, 1n,
    0x800FFFFFFFFFFFFFn, 0x0010000000000000n, 0x8010000000000000n, 0x7FEFFFFFFFFFFFFFn, 0xFFEFFFFFFFFFFFFFn,
    0x7FF0000000000000n, 0xFFF0000000000000n, 0x7FF8000000000001n, 0xFFF0123456789ABCn, 0x7FF0000000000003n,
    0x4008000000000000n, 0x3FB999999999999An, 0x7E37E43C8800759Cn, 0x01A56E1FC2F8F359n, 0x0018000000000000n,
    0x4340000000000001n, 0xC1E0000000000000n, 0x41E0000000000000n, 0x36A0000000000000n, 0x3810000000000000n,
    0x3FDFFFFFFFFFFFFFn, 0x0020000000000000n];
// MXCSR: defaults; PE set (the native paths); each rounding mode; DAZ, FZ;
// everything unmasked; only the post-computation exceptions unmasked
export const MXCSRS = [0x1F80, 0x1FA0, 0x3FA0, 0x5FA0, 0x7FA0, 0x1FE0, 0x9FA0, 0x9FE0, 0x0000, 0x0180, 0x0700 | 0x20];

let seed = 0x13572468;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const pick = list => list[random() % list.length];
const random_value = double => double ? BigInt(random()) << 32n | BigInt(random()) : BigInt(random());

export const lanes_of = (v, double, width = 128) => {
    const n = width / (double ? 64 : 32), bits = double ? 64n : 32n, mask = (1n << bits) - 1n;
    return Array.from({ length: n }, (_, i) => v >> BigInt(i) * bits & mask);
};
export const of_lanes = (lanes, double) => lanes.reduce((v, x, i) => v | x << BigInt(i) * (double ? 64n : 32n), 0n);
export const bytes128 = v => Uint8Array.from({ length: 16 }, (_, i) => Number(v >> BigInt(8 * i) & 0xFFn));

// The forms: prefix and opcode byte, the operation, the operand shape
export const FORMS = [];
for(const [prefix, double, scalar] of [[[], false, false], [[0x66], true, false], [[0xF3], false, true], [[0xF2], true, true]])
{
    for(const [code, op] of [[0x51, "sqrt"], [0x58, "add"], [0x59, "mul"], [0x5C, "sub"], [0x5D, "min"], [0x5E, "div"], [0x5F, "max"]])
        FORMS.push({ name: op + (scalar ? "s" : "p") + (double ? "d" : "s"), prefix, code, kind: "binary", op, double, scalar });
    FORMS.push({ name: "cmp" + (scalar ? "s" : "p") + (double ? "d" : "s"), prefix, code: 0xC2, kind: "compare", double, scalar, imm8: true });
}
for(const [prefix, double] of [[[0x66], true], [[0xF2], false]])
{
    FORMS.push({ name: "hadd" + (double ? "pd" : "ps"), prefix, code: 0x7C, kind: "horizontal", op: "add", double });
    FORMS.push({ name: "hsub" + (double ? "pd" : "ps"), prefix, code: 0x7D, kind: "horizontal", op: "sub", double });
    FORMS.push({ name: "addsub" + (double ? "pd" : "ps"), prefix, code: 0xD0, kind: "addsub", double });
}
for(const [prefix, double] of [[[], false], [[0x66], true]])
{
    FORMS.push({ name: (double ? "ucomisd" : "ucomiss"), prefix, code: 0x2E, kind: "comi", double, predicate: 0 });
    FORMS.push({ name: (double ? "comisd" : "comiss"), prefix, code: 0x2F, kind: "comi", double, predicate: 1 });
}
for(const [prefix, scalar] of [[[], false], [[0xF3], true]])
{
    FORMS.push({ name: scalar ? "rsqrtss" : "rsqrtps", prefix, code: 0x52, kind: "reciprocal", square_root: true, scalar });
    FORMS.push({ name: scalar ? "rcpss" : "rcpps", prefix, code: 0x53, kind: "reciprocal", square_root: false, scalar });
}
// conversions: from (float width, integer, mmx/gpr) to ...
FORMS.push(
    { name: "cvtps2pd", prefix: [], code: 0x5A, kind: "widen", scalar: false },
    { name: "cvtss2sd", prefix: [0xF3], code: 0x5A, kind: "widen", scalar: true },
    { name: "cvtpd2ps", prefix: [0x66], code: 0x5A, kind: "narrow", scalar: false },
    { name: "cvtsd2ss", prefix: [0xF2], code: 0x5A, kind: "narrow", scalar: true },
    { name: "cvtdq2ps", prefix: [], code: 0x5B, kind: "from_dwords", double: false },
    { name: "cvtdq2pd", prefix: [0xF3], code: 0xE6, kind: "from_dwords", double: true },
    { name: "cvtps2dq", prefix: [0x66], code: 0x5B, kind: "to_dwords", double: false, truncate: false },
    { name: "cvttps2dq", prefix: [0xF3], code: 0x5B, kind: "to_dwords", double: false, truncate: true },
    { name: "cvtpd2dq", prefix: [0xF2], code: 0xE6, kind: "to_dwords", double: true, truncate: false },
    { name: "cvttpd2dq", prefix: [0x66], code: 0xE6, kind: "to_dwords", double: true, truncate: true },
    { name: "cvtsi2ss", prefix: [0xF3], code: 0x2A, kind: "from_gpr", double: false },
    { name: "cvtsi2sd", prefix: [0xF2], code: 0x2A, kind: "from_gpr", double: true },
    { name: "cvtss2si", prefix: [0xF3], code: 0x2D, kind: "to_gpr", double: false, truncate: false },
    { name: "cvttss2si", prefix: [0xF3], code: 0x2C, kind: "to_gpr", double: false, truncate: true },
    { name: "cvtsd2si", prefix: [0xF2], code: 0x2D, kind: "to_gpr", double: true, truncate: false },
    { name: "cvttsd2si", prefix: [0xF2], code: 0x2C, kind: "to_gpr", double: true, truncate: true },
    { name: "cvtpi2ps", prefix: [], code: 0x2A, kind: "from_mmx", double: false },
    { name: "cvtpi2pd", prefix: [0x66], code: 0x2A, kind: "from_mmx", double: true },
    { name: "cvtps2pi", prefix: [], code: 0x2D, kind: "to_mmx", double: false, truncate: false },
    { name: "cvttps2pi", prefix: [], code: 0x2C, kind: "to_mmx", double: false, truncate: true },
    { name: "cvtpd2pi", prefix: [0x66], code: 0x2D, kind: "to_mmx", double: true, truncate: false },
    { name: "cvttpd2pi", prefix: [0x66], code: 0x2C, kind: "to_mmx", double: true, truncate: true },
);

// SSE4.1 (66 0F 3A): every rounding control with and without PE suppressed,
// and the dot products' lane masks (all products often)
for(const [code, name, double, scalar] of [[0x08, "roundps", false, false], [0x09, "roundpd", true, false],
    [0x0A, "roundss", false, true], [0x0B, "roundsd", true, true]])
{
    FORMS.push({ name, prefix: [0x66], map: 0x3A, code, kind: "round", double, scalar, imm8: (mi, n) => (mi * 5 + n) & 15 });
}
for(const [code, name, double] of [[0x40, "dpps", false], [0x41, "dppd", true]])
{
    FORMS.push({ name, prefix: [0x66], map: 0x3A, code, kind: "dot", double, imm8: (mi, n) => n % 3 === 0 ? 0xFF : (mi * 37 + n * 101) & 255 });
}

// integer sources: the edges of the conversions
const INTEGERS = [0n, 1n, 0xFFFFFFFFn, 0x7FFFFFFFn, 0x80000000n, 0x01000001n, 0xFEFFFFFFn, 0x075BCD15n, 0x80000001n, 0x00FFFFFFn];

/**
 * The cases of a form: { mxcsr, a (the destination), b (the source), imm8 }
 * with the model's expectation { result, after (MXCSR), fault }. The active
 * lanes go through every pair of special values, then random ones.
 */
export function cases(form)
{
    const double = form.double ?? form.kind === "narrow";
    const integer = ["from_dwords", "from_gpr", "from_mmx"].includes(form.kind);
    const values = integer ? INTEGERS : double ? DOUBLE : SINGLE;
    const lane_double = integer ? false : double;
    const lanes = lane_double ? 2 : 4;
    const active = form.scalar || form.kind === "comi" || form.kind === "from_gpr" || form.kind === "to_gpr" ? 1 : lanes;
    const out = [];
    // (every pair of special values in the active lanes)
    const count = Math.max(64, Math.ceil(values.length * values.length / MXCSRS.length / active));
    MXCSRS.forEach((mxcsr, mi) => {
        for(let n = 0; n < count; n++)
        {
            const a = [], b = [];
            for(let i = 0; i < lanes; i++)
            {
                const k = (mi * count + n) * active + i;
                if(i < active && k < values.length * values.length)
                {
                    a.push(values[k % values.length]);
                    b.push(values[Math.floor(k / values.length) % values.length]);
                }
                else
                {
                    a.push(random() & 3 ? pick(values) : random_value(lane_double));
                    b.push(random() & 3 ? pick(values) : random_value(lane_double));
                }
            }
            const ca = of_lanes(a, lane_double), cb = of_lanes(b, lane_double);
            // (CMP: the predicate in imm8[2:0], the other bits set too, which legacy SSE ignores)
            const imm8 = typeof form.imm8 === "function" ? form.imm8(mi, n) : form.imm8 ? (mi + n) & 7 | (n * 3 + mi) % 32 << 3 : 0;
            out.push({ mxcsr, a: ca, b: cb, imm8, ...expect(form, mxcsr, ca, cb, form.kind === "compare" ? imm8 & 7 : imm8) });
        }
    });
    return out;
}
export function expect(form, mxcsr, a, b, imm8, width = 128)
{
    // (`width` 256: a VEX.256 form, its lanes with one exception context)
    const wide = width === 256, half = (v, h) => v >> BigInt(128 * h) & ((1n << 128n) - 1n);
    const fp = new model.Fp(mxcsr);
    let result;
    switch(form.kind)
    {
        case "binary": case "compare":
        {
            const la = lanes_of(a, form.double, width), lb = lanes_of(b, form.double, width);
            const n = form.scalar ? 1 : la.length;
            const all = form.double ? 0xFFFFFFFFFFFFFFFFn : 0xFFFFFFFFn;
            for(let i = 0; i < n; i++)
                la[i] = form.kind === "compare" ? (fp.compare(la[i], lb[i], form.double, imm8) ? all : 0n) :
                    fp.binary(form.op, la[i], lb[i], form.double);
            result = of_lanes(la, form.double);
            break;
        }
        case "horizontal": case "addsub":
        {
            // (HADD/HSUB: their pairs within each half)
            const r = [];
            for(let h = 0; h < width / 128; h++)
            {
                const la = lanes_of(half(a, h), form.double), lb = lanes_of(half(b, h), form.double), n = la.length;
                for(let i = 0; i < n; i++)
                {
                    if(form.kind === "addsub") r.push(fp.binary(i % 2 ? "add" : "sub", la[i], lb[i], form.double));
                    else
                    {
                        const v = i < n / 2 ? la : lb, base = i % (n / 2) * 2;
                        r.push(fp.binary(form.op, v[base], v[base + 1], form.double));
                    }
                }
            }
            result = of_lanes(r, form.double);
            break;
        }
        case "round":
        {
            const la = lanes_of(a, form.double, width), lb = lanes_of(b, form.double, width);
            for(let i = 0; i < (form.scalar ? 1 : la.length); i++) la[i] = round_lane(fp, lb[i], form.double, imm8);
            result = of_lanes(la, form.double);
            break;
        }
        case "dot":
        {
            // (each operation with its own exceptions, see the model; VEX.256:
            // each half's in turn, an unmasked exception before the high one)
            const value = r => r.result.reduceRight((v, x) => v << 8n | BigInt(x), 0n);
            const low = dot_product(mxcsr, bytes128(half(a, 0)), bytes128(half(b, 0)), imm8, form.double);
            if(!wide || low.fault) return { result: value(low), after: low.mxcsr, fault: low.fault };
            const high = dot_product(low.mxcsr, bytes128(half(a, 1)), bytes128(half(b, 1)), imm8, form.double);
            return { result: value(low) | value(high) << 128n, after: high.mxcsr, fault: high.fault };
        }
        case "comi":
        {
            const x = lanes_of(a, form.double)[0], y = lanes_of(b, form.double)[0];
            // the flags of the comparison (COMI: a QNaN is invalid; UCOMI: only an SNaN)
            fp.compare(x, y, form.double, form.predicate);
            const dx = fp.input(x, form.double).x, dy = fp.input(y, form.double).x;
            if(model.is_nan(dx, form.double) || model.is_nan(dy, form.double)) result = 0x45;
            else
            {
                const c = model.compare(dx, dy, form.double);
                result = c < 0 ? 0x01 : c === 0 ? 0x40 : 0;
            }
            break;
        }
        case "reciprocal":
        {
            const la = lanes_of(a, false, width), lb = lanes_of(b, false, width);
            if(!form.scalar) la.fill(0n);
            for(let i = 0; i < (form.scalar ? 1 : la.length); i++) la[i] = model.reciprocal(lb[i], form.square_root);
            result = of_lanes(la, false);
            break;
        }
        case "widen": case "narrow":
        {
            const from_double = form.kind === "narrow";
            // (VEX.256: four lanes, of an XMM source or into an XMM result)
            const lb = lanes_of(b, from_double, wide && from_double ? 256 : 128);
            const n = form.scalar ? 1 : wide ? 4 : 2;
            const converted = Array.from({ length: n }, (_, i) => fp.convert(lb[i], from_double));
            if(form.scalar)
            {
                const la = lanes_of(a, !from_double);
                la[0] = converted[0];
                result = of_lanes(la, !from_double);
            }
            else result = of_lanes(converted, !from_double);
            break;
        }
        case "from_dwords":
        {
            const n = (form.double ? 2 : 4) * (wide ? 2 : 1);
            const ints = lanes_of(b, false, wide && !form.double ? 256 : 128).map(x => BigInt.asIntN(32, x)).slice(0, n);
            result = of_lanes(ints.map(x => fp.from_integer(x, form.double)), form.double);
            break;
        }
        case "to_dwords":
        {
            const lb = lanes_of(b, form.double, width);
            const ints = lb.slice(0, (form.double ? 2 : 4) * (wide ? 2 : 1)).map(x => BigInt.asUintN(32, fp.to_integer(x, form.double, 32, form.truncate)));
            result = of_lanes(ints, false);
            break;
        }
        case "from_gpr": case "from_mmx":
        {
            const n = form.kind === "from_gpr" ? 1 : 2;
            const ints = lanes_of(b, false).slice(0, n).map(x => BigInt.asIntN(32, x));
            const converted = ints.map(x => fp.from_integer(x, form.double));
            if(form.kind === "from_mmx" && form.double) result = of_lanes(converted, true);
            else
            {
                const la = lanes_of(a, form.double);
                converted.forEach((x, i) => la[i] = x);
                result = of_lanes(la, form.double);
            }
            break;
        }
        case "to_gpr": case "to_mmx":
        {
            const lb = lanes_of(b, form.double);
            const n = form.kind === "to_gpr" ? 1 : 2;
            result = of_lanes(lb.slice(0, n).map(x => BigInt.asUintN(32, fp.to_integer(x, form.double, 32, form.truncate))), false);
            break;
        }
    }
    const { mxcsr: after, fault } = fp.finish();
    return { result, after, fault };
}
                                source/v64/tests/rust/sse_fp_model.mjs                                                              0000644 0000000 0000000 00000045743 00000000000 015212  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A model of SSE floating point (docs/simd-xsave-plan.md 7.4) written from
// IEEE 754 and the SDM, independent of src/rust/cpu/simd_fp.rs and SoftFloat:
// exact rational arithmetic on BigInts, rounded by MXCSR.RC, with DAZ and FZ,
// x86's NaN rules (SDM Vol. 1, 4.8.3.5), tininess detected after rounding
// (SDM Vol. 1, 4.9.1.5), the exception precedence of SDM Vol. 1, 4.9.2 and
// the order of SDM Vol. 1, 11.5.3 (`finish`).
//
// Values are BigInt bit patterns; `double` selects binary64 over binary32.

export const IE = 1, DE = 2, ZE = 4, OE = 8, UE = 16, PE = 32;

export function format(double)
{
    return double ? { bits: 64, p: 53, ebits: 11 } : { bits: 32, p: 24, ebits: 8 };
}
/** binary16 (F16C's half precision) */
export const HALF = { bits: 16, p: 11, ebits: 5 };
const mask = n => (1n << BigInt(n)) - 1n;
const bias = f => (1 << (f.ebits - 1)) - 1;
const max_exponent = f => (1 << f.ebits) - 1;
const sign_bit = f => 1n << BigInt(f.bits - 1);
const bit_length = m => m === 0n ? 0 : m.toString(2).length;

function parts(x, f)
{
    return {
        sign: Number(x >> BigInt(f.bits - 1) & 1n),
        exponent: Number(x >> BigInt(f.p - 1) & mask(f.ebits)),
        fraction: x & mask(f.p - 1),
    };
}
export function is_nan(x, double) { const f = format(double), q = parts(x, f); return q.exponent === max_exponent(f) && q.fraction !== 0n; }
export function is_snan(x, double) { const f = format(double); return is_nan(x, double) && (x >> BigInt(f.p - 2) & 1n) === 0n; }
export function is_inf(x, double) { const f = format(double), q = parts(x, f); return q.exponent === max_exponent(f) && q.fraction === 0n; }
export function is_zero(x, double) { return (x & mask(format(double).bits - 1)) === 0n; }
export function is_denormal(x, double) { const f = format(double), q = parts(x, f); return q.exponent === 0 && q.fraction !== 0n; }
const quiet = (x, f) => x | 1n << BigInt(f.p - 2);
export const indefinite = double => double ? 0xFFF8000000000000n : 0xFFC00000n;
const infinity = (sign, f) => (sign ? sign_bit(f) : 0n) | mask(f.ebits) << BigInt(f.p - 1);
const zero = (sign, f) => sign ? sign_bit(f) : 0n;

/** A finite value: |x| = m * 2^e */
function value(x, f)
{
    const q = parts(x, f);
    if(q.exponent === 0) return { sign: q.sign, m: q.fraction, e: 1 - bias(f) - (f.p - 1) };
    return { sign: q.sign, m: q.fraction | 1n << BigInt(f.p - 1), e: q.exponent - bias(f) - (f.p - 1) };
}

/**
 * Round (-1)^sign * (m * 2^e + something below 2^e if `sticky`), m > 0 or
 * sticky, to the format by RC (0 nearest even, 1 down, 2 up, 3 toward zero):
 * { bits, flags (OE, UE, PE as with every exception masked), tiny }
 */
export function round(sign, m, e, sticky, f, rc)
{
    const emin = 1 - bias(f);
    const s = sign ? sign_bit(f) : 0n;
    // m * 2^-drop, rounded
    const shift = (m, drop) => {
        let q, rem = 0n, half = 0n;
        if(drop > 0) { q = m >> BigInt(drop); rem = m & mask(drop); half = 1n << BigInt(drop - 1); }
        else q = m << BigInt(-drop);
        const inexact = rem !== 0n || sticky;
        let up;
        switch(rc)
        {
            case 0: up = drop > 0 && (rem > half || rem === half && (sticky || (q & 1n) === 1n)); break;
            case 1: up = sign === 1 && inexact; break;
            case 2: up = sign === 0 && inexact; break;
            default: up = false;
        }
        return { q: up ? q + 1n : q, inexact };
    };
    // with an unbounded exponent: p significant bits
    let drop = bit_length(m) - f.p;
    const u = shift(m, drop);
    if(bit_length(u.q) > f.p) { u.q >>= 1n; drop += 1; }
    const exponent = e + drop + f.p - 1; // of the leading bit
    if(exponent > bias(f))
    {
        const to_infinity = rc === 0 || rc === 1 && sign === 1 || rc === 2 && sign === 0;
        const largest = BigInt(max_exponent(f) - 1) << BigInt(f.p - 1) | mask(f.p - 1);
        return { bits: s | (to_infinity ? infinity(0, f) : largest), flags: OE | PE, tiny: false };
    }
    const tiny = exponent < emin;
    if(!tiny)
    {
        const bits = BigInt(exponent + bias(f)) << BigInt(f.p - 1) | u.q & mask(f.p - 1);
        return { bits: s | bits, flags: u.inexact ? PE : 0, tiny };
    }
    // on the denormal grid (rounding up may reach the smallest normal: the same bits)
    const d = shift(m, emin - (f.p - 1) - e);
    return { bits: s | d.q, flags: d.inexact ? PE | UE : 0, tiny };
}

/** One SSE instruction's MXCSR: its controls, and the flags of its lanes */
/**
 * The comparison predicates of CMPPS/CMPPD/CMPSS/CMPSD (0-7, imm8[2:0]) and
 * VCMPPS/VCMPPD/VCMPSS/VCMPSD (0-31, imm8[4:0]), SDM vol. 2A, CMPPD, Table
 * 3-1: [name, the result when (less, equal, greater, unordered), whether a
 * QNaN operand signals an invalid operation]
 */
export const PREDICATES = [
    ["EQ_OQ", [0, 1, 0, 0], 0], ["LT_OS", [1, 0, 0, 0], 1], ["LE_OS", [1, 1, 0, 0], 1], ["UNORD_Q", [0, 0, 0, 1], 0],
    ["NEQ_UQ", [1, 0, 1, 1], 0], ["NLT_US", [0, 1, 1, 1], 1], ["NLE_US", [0, 0, 1, 1], 1], ["ORD_Q", [1, 1, 1, 0], 0],
    ["EQ_UQ", [0, 1, 0, 1], 0], ["NGE_US", [1, 0, 0, 1], 1], ["NGT_US", [1, 1, 0, 1], 1], ["FALSE_OQ", [0, 0, 0, 0], 0],
    ["NEQ_OQ", [1, 0, 1, 0], 0], ["GE_OS", [0, 1, 1, 0], 1], ["GT_OS", [0, 0, 1, 0], 1], ["TRUE_UQ", [1, 1, 1, 1], 0],
    ["EQ_OS", [0, 1, 0, 0], 1], ["LT_OQ", [1, 0, 0, 0], 0], ["LE_OQ", [1, 1, 0, 0], 0], ["UNORD_S", [0, 0, 0, 1], 1],
    ["NEQ_US", [1, 0, 1, 1], 1], ["NLT_UQ", [0, 1, 1, 1], 0], ["NLE_UQ", [0, 0, 1, 1], 0], ["ORD_S", [1, 1, 1, 0], 1],
    ["EQ_US", [0, 1, 0, 1], 1], ["NGE_UQ", [1, 0, 0, 1], 0], ["NGT_UQ", [1, 1, 0, 1], 0], ["FALSE_OS", [0, 0, 0, 0], 1],
    ["NEQ_OS", [1, 0, 1, 0], 1], ["GE_OQ", [0, 1, 1, 0], 0], ["GT_OQ", [0, 0, 1, 0], 0], ["TRUE_US", [1, 1, 1, 1], 1],
];

export class Fp
{
    constructor(mxcsr)
    {
        this.mxcsr = mxcsr;
        this.flags = 0;
        this.rc = mxcsr >> 13 & 3;
        this.daz = (mxcsr & 0x40) !== 0;
        this.fz = (mxcsr & 0x8000) !== 0;
        this.um_masked = (mxcsr & 0x800) !== 0;
    }
    /** A floating-point source: zero for a denormal with DAZ; its DE, if any */
    input(x, double)
    {
        if(!is_denormal(x, double)) return { x, de: 0 };
        if(this.daz) return { x: x & sign_bit(format(double)), de: 0 };
        return { x, de: DE };
    }
    /** A rounded result: FZ and unmasked underflow (any tiny result) */
    deliver(r, double)
    {
        if(r.tiny)
        {
            if(!this.um_masked) r.flags |= UE;
            else if(this.fz)
            {
                r.flags |= UE | PE;
                r.bits &= sign_bit(format(double));
            }
        }
        this.flags |= r.flags;
        return r.bits;
    }
    /** One lane of "add", "sub", "mul", "div", "sqrt" (of b), "min", "max" */
    binary(op, a0, b0, double)
    {
        const f = format(double);
        const ia = op === "sqrt" ? { x: 0n, de: 0 } : this.input(a0, double), ib = this.input(b0, double);
        const a = ia.x, b = ib.x, de = ia.de | ib.de;
        if(op === "min" || op === "max")
        {
            // any NaN: the second operand, as it is, and IE
            if(is_nan(a, double) || is_nan(b, double)) { this.flags |= IE; return b; }
            this.flags |= de;
            const c = compare(a, b, double);
            return (op === "min" ? c < 0 : c > 0) ? a : b;
        }
        // NaN operands: the first one's, quieted (IE for an SNaN; DE is not reported)
        const nans = op === "sqrt" ? [b] : [a, b];
        if(nans.some(x => is_snan(x, double))) this.flags |= IE;
        const nan = nans.find(x => is_nan(x, double));
        if(nan !== undefined) return quiet(nan, f);
        const invalid = () => { this.flags |= IE; return indefinite(double); };
        const sa = parts(a, f).sign, sb = parts(b, f).sign;
        const [ia_, ib_, za, zb] = [is_inf(a, double), is_inf(b, double), is_zero(a, double), is_zero(b, double)];
        switch(op)
        {
            case "add": case "sub":
            {
                const sb2 = op === "sub" ? sb ^ 1 : sb;
                if(ia_ && ib_) return sa === sb2 ? infinity(sa, f) : invalid();
                this.flags |= de;
                if(ia_) return infinity(sa, f);
                if(ib_) return infinity(sb2, f);
                const x = value(a, f), y = value(b, f);
                const e = Math.min(x.e, y.e);
                const sum = (x.sign ? -1n : 1n) * (x.m << BigInt(x.e - e)) + (sb2 ? -1n : 1n) * (y.m << BigInt(y.e - e));
                if(sum === 0n)
                {
                    // exact zeros: -0 for two negative ones, else -0 only when rounding down
                    return zero(za && zb && sa === 1 && sb2 === 1 || !(za && zb && sa === sb2) && this.rc === 1 ? 1 : 0, f);
                }
                return this.deliver(round(sum < 0n ? 1 : 0, sum < 0n ? -sum : sum, e, false, f, this.rc), double);
            }
            case "mul":
            {
                const sign = sa ^ sb;
                if((ia_ || ib_) && (za || zb)) return invalid();
                this.flags |= de;
                if(ia_ || ib_) return infinity(sign, f);
                if(za || zb) return zero(sign, f);
                const x = value(a, f), y = value(b, f);
                return this.deliver(round(sign, x.m * y.m, x.e + y.e, false, f, this.rc), double);
            }
            case "div":
            {
                const sign = sa ^ sb;
                if(ia_ && ib_ || za && zb) return invalid();
                // an infinite dividend: infinite, even divided by zero (no ZE)
                if(ia_) { this.flags |= de; return infinity(sign, f); }
                if(zb) { this.flags |= ZE; return infinity(sign, f); }
                this.flags |= de;
                if(ib_ || za) return zero(sign, f);
                const x = value(a, f), y = value(b, f);
                const k = 2 * f.p + 8;
                const scaled = x.m << BigInt(k);
                return this.deliver(round(sign, scaled / y.m, x.e - y.e - k, scaled % y.m !== 0n, f, this.rc), double);
            }
            case "sqrt":
            {
                if(zb) return b;
                if(sb) return invalid();
                this.flags |= de;
                if(ib_) return b;
                const y = value(b, f);
                let m = y.m, e = y.e;
                if(e & 1) { m <<= 1n; e -= 1; }
                const k = 2 * (2 * f.p + 8);
                m <<= BigInt(k);
                e -= k;
                const root = isqrt(m);
                return this.deliver(round(0, root, e / 2, root * root !== m, f, this.rc), double);
            }
        }
        throw new Error(op);
    }
    /**
     * One lane of FMA (SDM Vol. 1, 14.5.2, Table 14-17): x * y (negated if
     * `negate_product`) + z (negated if `negate_addend`), the exact sum
     * rounded once. NaN operands: the first of x, y, z, quieted and not
     * negated; IE for an SNaN, and for 0 * inf only without a NaN addend.
     */
    fused(x0, y0, z0, double, negate_product, negate_addend)
    {
        const f = format(double);
        const ix = this.input(x0, double), iy = this.input(y0, double), iz = this.input(z0, double);
        const de = ix.de | iy.de | iz.de;
        const operands = [ix.x, iy.x, iz.x];
        if(operands.some(v => is_snan(v, double))) this.flags |= IE;
        const nan = operands.find(v => is_nan(v, double));
        if(nan !== undefined) return quiet(nan, f);
        const [x, y, z] = operands;
        const invalid = () => { this.flags |= IE; return indefinite(double); };
        const sp = parts(x, f).sign ^ parts(y, f).sign ^ (negate_product ? 1 : 0);
        const sz = parts(z, f).sign ^ (negate_addend ? 1 : 0);
        const infinite_product = is_inf(x, double) || is_inf(y, double);
        const zero_product = is_zero(x, double) || is_zero(y, double);
        if(infinite_product && zero_product) return invalid();
        if(infinite_product)
        {
            if(is_inf(z, double) && sz !== sp) return invalid();
            this.flags |= de;
            return infinity(sp, f);
        }
        this.flags |= de;
        if(is_inf(z, double)) return infinity(sz, f);
        // the exact sum: the product's m * 2^e and the addend's on a common exponent
        const product = zero_product ? { m: 0n, e: 0 } : (() => { const a = value(x, f), b = value(y, f); return { m: a.m * b.m, e: a.e + b.e }; })();
        const addend = is_zero(z, double) ? { m: 0n, e: 0 } : value(z, f);
        const e = Math.min(product.e, addend.e);
        const sum = (sp ? -1n : 1n) * (product.m << BigInt(product.e - e)) + (sz ? -1n : 1n) * (addend.m << BigInt(addend.e - e));
        if(sum === 0n)
        {
            // an exact zero: the zeros' sign when both are zeros of one sign, else -0 only when rounding down
            const both_zero = zero_product && is_zero(z, double);
            return zero(both_zero && sp === sz ? sp : this.rc === 1 ? 1 : 0, f);
        }
        return this.deliver(round(sum < 0n ? 1 : 0, sum < 0n ? -sum : sum, e, false, f, this.rc), double);
    }
    /** VCVTPH2PS: a half (BigInt bits) to single precision, exactly: no DAZ, no DE; IE for an SNaN */
    half_to_single(h)
    {
        const to = format(false);
        const q = parts(h, HALF);
        if(q.exponent === max_exponent(HALF) && q.fraction !== 0n)
        {
            if((h >> BigInt(HALF.p - 2) & 1n) === 0n) this.flags |= IE;
            return quiet(zero(q.sign, to) | mask(to.ebits) << BigInt(to.p - 1) | q.fraction << BigInt(to.p - HALF.p), to);
        }
        if(q.exponent === max_exponent(HALF)) return infinity(q.sign, to);
        if(q.exponent === 0 && q.fraction === 0n) return zero(q.sign, to);
        const v = value(h, HALF);
        return round(q.sign, v.m, v.e, false, to, 0).bits;
    }
    /** VCVTPS2PH: a single to a half by `rc`: DAZ and DE; FZ does not apply,
     * an unmasked underflow is any tiny result */
    single_to_half(x0, rc)
    {
        const from = format(false);
        const { x, de } = this.input(x0, false);
        const q = parts(x, from);
        if(is_nan(x, false))
        {
            if(is_snan(x, false)) this.flags |= IE;
            return quiet(zero(q.sign, HALF) | mask(HALF.ebits) << BigInt(HALF.p - 1) | q.fraction >> BigInt(from.p - HALF.p), HALF);
        }
        this.flags |= de;
        if(is_inf(x, false)) return infinity(q.sign, HALF);
        if(is_zero(x, false)) return zero(q.sign, HALF);
        const v = value(x, from);
        const r = round(q.sign, v.m, v.e, false, HALF, rc);
        if(r.tiny && !this.um_masked) r.flags |= UE;
        this.flags |= r.flags;
        return r.bits;
    }
    /** CMPPS/CMPPD/CMPSS/CMPSD predicate 0-7 of a and b, VCMP*'s 0-31 (PREDICATES; COMI: 1; UCOMI: 0) */
    compare(a0, b0, double, predicate)
    {
        const ia = this.input(a0, double), ib = this.input(b0, double);
        const a = ia.x, b = ib.x;
        const unordered = is_nan(a, double) || is_nan(b, double);
        const [, truth, signaling] = PREDICATES[predicate];
        if(is_snan(a, double) || is_snan(b, double) || unordered && signaling) this.flags |= IE;
        if(!unordered) this.flags |= ia.de | ib.de;
        const c = unordered ? undefined : compare(a, b, double);
        return truth[unordered ? 3 : c < 0 ? 0 : c === 0 ? 1 : 2] === 1;
    }
    /** A signed integer (BigInt) to the format */
    from_integer(n, double)
    {
        if(n === 0n) return 0n;
        return this.deliver(round(n < 0n ? 1 : 0, n < 0n ? -n : n, 0, false, format(double), this.rc), double);
    }
    /** Between the formats: from `from_double` to the other one */
    convert(x0, from_double)
    {
        const from = format(from_double), to = format(!from_double);
        const { x, de } = this.input(x0, from_double);
        if(is_nan(x, from_double))
        {
            if(is_snan(x, from_double)) this.flags |= IE;
            const q = parts(x, from), shift = BigInt(Math.abs(from.p - to.p));
            const fraction = from_double ? q.fraction >> shift : q.fraction << shift;
            return quiet(zero(q.sign, to) | mask(to.ebits) << BigInt(to.p - 1) | fraction, to);
        }
        this.flags |= de;
        const sign = parts(x, from).sign;
        if(is_inf(x, from_double)) return infinity(sign, to);
        if(is_zero(x, from_double)) return zero(sign, to);
        const v = value(x, from);
        return this.deliver(round(sign, v.m, v.e, false, to, this.rc), !from_double);
    }
    /** To a 32- or 64-bit signed integer (BigInt), by RC or truncating; no DE */
    to_integer(x0, double, bits, truncate)
    {
        const f = format(double), { x } = this.input(x0, double);
        const indefinite = -(1n << BigInt(bits - 1));
        if(is_nan(x, double) || is_inf(x, double)) { this.flags |= IE; return indefinite; }
        if(is_zero(x, double)) return 0n;
        const v = value(x, f);
        // |x| = m * 2^e: the integer part and whether anything is below it
        let q, rem;
        if(v.e >= 0) { q = v.m << BigInt(v.e); rem = 0n; }
        else { q = v.m >> BigInt(-v.e); rem = v.m & mask(-v.e); }
        const half = v.e < 0 ? 1n << BigInt(-v.e - 1) : 0n;
        const rc = truncate ? 3 : this.rc;
        let up;
        switch(rc)
        {
            case 0: up = rem > half || rem === half && rem !== 0n && (q & 1n) === 1n; break;
            case 1: up = v.sign === 1 && rem !== 0n; break;
            case 2: up = v.sign === 0 && rem !== 0n; break;
            default: up = false;
        }
        if(up) q += 1n;
        const n = v.sign ? -q : q;
        if(n < indefinite || n > -indefinite - 1n) { this.flags |= IE; return indefinite; }
        if(rem !== 0n) this.flags |= PE;
        return n;
    }
    /** MXCSR afterwards and whether the instruction faults (SDM Vol. 1, 11.5.3) */
    finish()
    {
        const unmasked = ~(this.mxcsr >> 7) & 0x3F;
        const pre = this.flags & (IE | DE | ZE);
        if(pre & unmasked) return { mxcsr: this.mxcsr | pre, fault: true };
        return { mxcsr: this.mxcsr | this.flags, fault: (this.flags & unmasked) !== 0 };
    }
}

/** The order of two non-NaN values: -1, 0, 1 (zeros of either sign equal) */
export function compare(a, b, double)
{
    const f = format(double);
    if(is_zero(a, double) && is_zero(b, double)) return 0;
    const key = x => x & sign_bit(f) ? -(x & mask(f.bits - 1)) : x & mask(f.bits - 1);
    const ka = key(a), kb = key(b);
    return ka < kb ? -1 : ka > kb ? 1 : 0;
}
function isqrt(n)
{
    if(n < 2n) return n;
    let x = 1n << BigInt(Math.ceil(bit_length(n) / 2));
    while(true)
    {
        const y = (x + n / x) >> 1n;
        if(y >= x) return x;
        x = y;
    }
}

/** RCPSS/RSQRTSS of one lane, as v86 computes it within the architectural error */
export function reciprocal(x, square_root)
{
    const sign = x & 0x80000000n;
    if(is_nan(x, false)) return quiet(x, format(false));
    if((x & 0x7F800000n) === 0n) return sign | 0x7F800000n;
    if(square_root && sign) return indefinite(false);
    if(is_inf(x, false)) return sign;
    const v = new DataView(new ArrayBuffer(4));
    v.setUint32(0, Number(x));
    const a = v.getFloat32(0);
    const r = square_root ? Math.fround(1 / Math.fround(Math.sqrt(a))) : Math.fround(1 / a);
    v.setFloat32(0, r);
    const bits = BigInt(v.getUint32(0));
    return is_denormal(bits, false) ? bits & 0x80000000n : bits;
}
                             source/v64/tests/rust/ssse3.mjs                                                                     0000644 0000000 0000000 00000043522 00000000000 013604  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SSSE3 in the 32-bit engines (docs/simd-xsave-plan.md P3): every MMX and XMM
// form against a model of the SDM's pseudocode written here (independent of
// src/rust/cpu/simd_int.rs), with register and memory sources, a destination
// that is also the source, every PALIGNR shift, saturation and sign edges;
// the x87 aliasing and tag transition of the MMX forms; and the exception
// rules: #UD without SSSE3, with CR0.EM, LOCK or an F2/F3 prefix, #NM with
// CR0.TS, #GP for a misaligned XMM memory operand (none for MMX) and #PF,
// each without effect. Every case runs in the interpreter, then hot under
// the page tier.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
import { OPS, PALIGNR, model } from "./ssse3_model.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DEST = 0x200000, SOURCE = 0x201000, OUT = 0x210000, FAULT = 0x21F000, SKIP = 0x21F100;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000, ABSENT = 0x206000;
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

// Operand data: random bytes, and lanes of edge values
const CASES = 64;
const make_data = seed => {
    const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
    const a = new Uint8Array(256 * 16), v = new DataView(a.buffer);
    const bytes = [0x00, 0x01, 0x7F, 0x80, 0x81, 0xFE, 0xFF, 0x40];
    const words = [0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0x4000, 0xC000];
    const dwords = [0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0x40000000, 0xC0000000];
    for(let n = 0; n < 256; n++)
    {
        for(let i = 0; i < 16; i++)
        {
            const kind = n % 4;
            if(kind === 0) a[n * 16 + i] = random();
            else if(kind === 1) a[n * 16 + i] = bytes[random() & 7];
            else if(kind === 2 && i % 2 === 0) v.setUint16(n * 16 + i, words[random() & 7], true);
            else if(kind === 3 && i % 4 === 0) v.setUint32(n * 16 + i, dwords[random() & 7], true);
        }
    }
    return a;
};
const destinations = make_data(0x5EED1234), sources = make_data(0x0BADC0DE);

const LOAD_MM = [0x0F, 0x6F], STORE_MM = [0x0F, 0x7F], LOAD_XMM = [0xF3, 0x0F, 0x6F], STORE_XMM = [0xF3, 0x0F, 0x7F];
const absolute = (r, a) => [0x05 | r << 3, ...u32(a)];
/** The instruction: dst, src register, or dst, [address] */
function encode(op, xmm, dst, src, address, imm8, prefixes = [])
{
    const map = op === PALIGNR ? 0x3A : 0x38;
    return [...prefixes, ...(xmm ? [0x66] : []), 0x0F, map, op,
        ...(address === undefined ? [0xC0 | dst << 3 | src] : absolute(dst, address)),
        ...(op === PALIGNR ? [imm8] : [])];
}
// The registers, source address and PALIGNR shift of case n; a destination
// that is also the source holds the source
const operands = (n, xmm, count) => {
    const memory = n >= count / 2;
    // an MMX memory operand needs no alignment
    const address = memory ? SOURCE + n * 16 + (xmm ? 0 : n & 7) : undefined;
    // (every PALIGNR shift once, small and large ones in both halves)
    return { dst: n & 7, src: n >> 3 & 7, memory, address, imm8: n * 37 & 255 };
};
const OSFXSR = [0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0]; // CR4 |= OSFXSR | OSXMMEXCPT
const CLTS = [0x0F, 0x06], EMMS = [0x0F, 0x77];
const SET_CR0 = bits => [0x0F, 0x20, 0xC0, 0x0D, ...u32(bits), 0x0F, 0x22, 0xC0];
const CLEAR_CR0 = bits => [0x0F, 0x20, 0xC0, 0x25, ...u32(~bits >>> 0), 0x0F, 0x22, 0xC0];

const machines = [];
async function run(vm, program, warm, interpreter)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    // (the page tier's step counts are the hot run's: x64_page_steps)
    else e["x64_page_steps_freeze"]();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    if(warm) await sleep(20);
    await vm.stop();
}
// the body repeats until byte 0x604 is set, then halts after one more round
function loop(body)
{
    const p = [...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it, the faulting EIP, CR2 and the error code, and skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58, 0xA3, ...u32(FAULT + 12));
    p.push(0xC7, 0x05, ...u32(FAULT), ...u32(vector));
    p.push(0x8B, 0x04, 0x24, 0xA3, ...u32(FAULT + 4));
    p.push(0x0F, 0x20, 0xD0, 0xA3, ...u32(FAULT + 8));
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true]];
const PROLOGUE = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...CLTS, ...CLEAR_CR0(4), ...OSFXSR];
/** Runs `program` on each machine of `set`: warm (compiled), then once more
 * cold; returns what `read` reads after each run (the cold run is mostly
 * interpreted: the program was rewritten) */
async function run_all(program, before = () => {}, set = machines, read = () => null)
{
    const results = [];
    for(const [i, vm] of set.entries())
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], i) => {
            const h = HANDLER + i * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(new Uint8Array(16), FAULT);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, loop([...PROLOGUE, ...program]), warm, vm === set[0]);
            results.push({ run: `machine ${i} ${warm ? "hot" : "one round"}`, data: read(vm) });
        }
    }
    return results;
}
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/** `faulting` raises `vector` at its first byte after `prologue` (the
 * handler skips it) in every run; `check(out, run)` sees OUT after each */
async function expect_fault(set, prologue, faulting, vector, { epilogue = [], before = () => {}, cr2, error_code, label, check } = {})
{
    const at = CODE + PROLOGUE.length + prologue.length;
    const results = await run_all([...prologue, ...faulting, ...epilogue], vm => {
        vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
        before(vm);
    }, set, vm => ({ fault: [0, 4, 8, 12].map(o => word(vm, FAULT + o)), out: bytes(vm, OUT, 28) }));
    const name = label || faulting.map(b => b.toString(16)).join(" ");
    for(const { run, data } of results)
    {
        assert.deepEqual(data.fault.slice(0, 2), [vector, at], `${name} (${run}): vector, EIP`);
        if(cr2 !== undefined) assert.equal(data.fault[2], cr2, `${name} (${run}): CR2`);
        if(error_code !== undefined) assert.equal(data.fault[3], error_code, `${name} (${run}): error code`);
        check?.(data.out, `${name} (${run})`);
    }
}
const pages = (vm, page, present) => {
    // (the BIOS's page table: 0x13000, identity)
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};

let checks = 0;
try
{
    // Without SSSE3: every form is #UD, also with CR0.TS (#UD comes first)
    machines.push(...await create_machines());
    for(const [op, name] of OPS)
    {
        for(const xmm of [false, true])
        {
            await expect_fault(machines, [], encode(op, xmm, 1, 2, undefined, 0), 6, { label: `${name} without SSSE3` });
            await expect_fault(machines, SET_CR0(8), encode(op, xmm, 1, undefined, SOURCE, 0), 6,
                { epilogue: CLTS, label: `${name} [mem] without SSSE3, CR0.TS` });
            checks += 2;
        }
    }
    await run_all([0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT)]);
    for(const vm of machines) assert.equal(word(vm, OUT) >>> 9 & 1, 0, "CPUID.1:ECX.SSSE3");
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log(`PASS: without SSSE3, CPUID reports none and ${OPS.length * 2} forms are #UD (before #NM)`);

    machines.push(...await create_machines({ cpu_features: ["SSSE3"] }));
    await run_all([0xB8, ...u32(1), 0x0F, 0xA2, 0x89, 0x0D, ...u32(OUT)]);
    for(const vm of machines) assert.equal(word(vm, OUT) >>> 9 & 1, 1, "CPUID.1:ECX.SSSE3");

    // Every form against the model
    let cases = 0;
    for(const [op, name] of OPS)
    {
        for(const xmm of [false, true])
        {
            const size = xmm ? 16 : 8, count = op === PALIGNR ? 256 : CASES;
            const [load, store] = xmm ? [LOAD_XMM, STORE_XMM] : [LOAD_MM, STORE_MM];
            const program = [];
            for(let n = 0; n < count; n++)
            {
                const { dst, src, memory, address, imm8 } = operands(n, xmm, count);
                program.push(...load, ...absolute(dst, DEST + n * 16));
                if(!memory) program.push(...load, ...absolute(src, SOURCE + n * 16));
                program.push(...encode(op, xmm, dst, src, address, imm8));
                program.push(...store, ...absolute(dst, OUT + n * 16));
            }
            if(!xmm) program.push(...EMMS);
            for(const vm of machines) vm.v86.cpu.wm.exports["x64_page_steps_reset"]();
            const runs = await run_all(program, vm => {
                vm.write_memory(destinations, DEST);
                vm.write_memory(sources, SOURCE);
                vm.write_memory(new Uint8Array(count * 16), OUT);
            }, machines, vm => bytes(vm, OUT, count * 16));
            // The page tier (machine 1) has templates for PSHUFB and PALIGNR on
            // XMM registers (IR Tier-0, deleted in P7.5, also had the MMX
            // ones); it steps the others through the interpreter (keyed by
            // their first two bytes: 66 0F, 0F 38 or 0F 3A), each round. A
            // build without Wasm SIMD has no SIMD templates (it still moves
            // XMM registers natively).
            const page_steps = machines[1].v86.cpu.wm.exports["x64_page_steps"];
            const steps = page_steps(xmm ? 0x0F66 : op === PALIGNR ? 0x3A0F : 0x380F);
            const templates = machines[1].v86.cpu.wm.exports["jit_wasm_simd_supported"]() !== 0;
            if(templates && xmm && (op === 0x00 || op === PALIGNR)) assert.ok(steps < count / 2, `${name}: the page tier template (${steps} steps)`);
            else assert.ok(steps >= count, `${name}: the page tier steps (${steps})`);
            const results = runs.map(({ data }) => data);
            for(let n = 0; n < count; n++)
            {
                const { dst, src, memory, address, imm8 } = operands(n, xmm, count);
                const source = memory ? sources.slice(address - SOURCE, address - SOURCE + size) : sources.slice(n * 16, n * 16 + size);
                // (a destination that is also the source register holds the source)
                const destination = !memory && dst === src ? source : destinations.slice(n * 16, n * 16 + size);
                const expected = model(op, destination, source, imm8);
                for(const [i, result] of results.entries())
                {
                    assert.deepEqual(result.slice(n * 16, n * 16 + size), expected,
                        `${name} ${xmm ? "xmm" : "mm"}${dst}, ${memory ? "[mem]" : (xmm ? "xmm" : "mm") + src}` +
                        `${op === PALIGNR ? ", " + imm8 : ""} on ${runs[i].run}: d=${Buffer.from(destination).toString("hex")} s=${Buffer.from(source).toString("hex")}`);
                }
            }
            cases += count;
        }
    }
    checks += cases;
    console.log(`PASS: ${cases} SSSE3 cases (${OPS.length} MMX and XMM forms, register and memory sources, all PALIGNR shifts) match the SDM model in the interpreter and the page tier; the page tier templates XMM PSHUFB and PALIGNR`);

    // The MMX forms alias the x87 registers: the destination's exponent is all
    // ones, TOP is 0 and all tags are valid. A fault changes nothing.
    const FNINIT = [0xDB, 0xE3], FLD1 = [0xD9, 0xE8], fnstenv = a => [0xD9, 0x35, ...u32(a)], fxsave = a => [0x0F, 0xAE, 0x05, ...u32(a)];
    for(const [op, name] of OPS)
    {
        const runs = await run_all([...FNINIT, ...FLD1, ...LOAD_MM, ...absolute(3, DEST), ...FNINIT, ...FLD1,
            ...encode(op, false, 3, 5, undefined, 4), ...fnstenv(OUT), ...fxsave(OUT + 0x40), ...EMMS], vm => {
            vm.write_memory(destinations, DEST);
        }, machines, vm => ({ env: bytes(vm, OUT, 28), area: bytes(vm, OUT + 0x40, 512) }));
        for(const { run, data: { env, area } } of runs)
        {
            assert.equal(env[5] >> 3 & 7, 0, `${name} (${run}): TOP`);
            assert.equal(env[8] | env[9] << 8, 0, `${name} (${run}): tag word, all valid`);
            assert.deepEqual([area[32 + 3 * 16 + 8], area[32 + 3 * 16 + 9]], [0xFF, 0xFF], `${name} (${run}): MM3's exponent`);
        }
        checks++;
        // #PF on the source: no transition
        await expect_fault(machines, [...FNINIT, ...FLD1], encode(op, false, 3, undefined, ABSENT + 8, 0x11), 14, {
            epilogue: [...fnstenv(OUT), ...FNINIT], cr2: ABSENT + 8, label: `${name} mm3, [absent page]`,
            before: vm => pages(vm, ABSENT, false),
            check: (env, run) => assert.deepEqual([env[5] >> 3 & 7, env[8] | env[9] << 8], [7, 0x3FFF], `${run}: x87 state after #PF`),
        });
        for(const vm of machines) pages(vm, ABSENT, true);
        checks++;
    }
    console.log(`PASS: ${OPS.length} MMX forms set TOP 0, all tags valid and the exponent of their destination; none after #PF`);

    // Faults: CR0.TS (#NM), CR0.EM, LOCK, F2/F3 (#UD), a misaligned XMM memory
    // operand (#GP(0), MMX: none), #PF; the destination keeps its value
    const keep = (xmm, r) => [...(xmm ? LOAD_XMM : LOAD_MM), ...absolute(r, DEST)];
    const kept = (xmm, r) => [...(xmm ? STORE_XMM : STORE_MM), ...absolute(r, OUT)];
    for(const [op, name] of OPS)
    {
        for(const xmm of [false, true])
        {
            const label = `${name} ${xmm ? "xmm" : "mm"}`;
            const check = (out, run) => assert.deepEqual(out.slice(0, xmm ? 16 : 8), destinations.slice(0, xmm ? 16 : 8), `${run}: destination kept`);
            const before = vm => vm.write_memory(destinations, DEST);
            await expect_fault(machines, [...keep(xmm, 6), ...SET_CR0(8)], encode(op, xmm, 6, 1, undefined, 1), 7,
                { epilogue: [...CLTS, ...kept(xmm, 6)], before, label: label + " with CR0.TS", check });
            await expect_fault(machines, [...keep(xmm, 6), ...SET_CR0(4)], encode(op, xmm, 6, undefined, SOURCE, 1), 6,
                { epilogue: [...CLEAR_CR0(4), ...kept(xmm, 6)], before, label: label + " with CR0.EM", check });
            for(const prefix of [0xF0, 0xF2, 0xF3])
            {
                await expect_fault(machines, keep(xmm, 6), encode(op, xmm, 6, 1, undefined, 1, [prefix]), 6,
                    { epilogue: kept(xmm, 6), before, label: `${prefix.toString(16)} ${label}`, check });
            }
            // (the absolute address is linear: the flat segments have base 0)
            const misaligned = encode(op, xmm, 6, undefined, SOURCE + 8, 1);
            if(xmm)
            {
                await expect_fault(machines, keep(xmm, 6), misaligned, 13, { epilogue: kept(xmm, 6), before, error_code: 0, label: label + ", [misaligned]", check });
            }
            else
            {
                const runs = await run_all([...keep(xmm, 6), ...misaligned, ...kept(xmm, 6), ...EMMS], before, machines, vm => word(vm, FAULT));
                for(const { run, data } of runs) assert.equal(data, 0, `${label}, [misaligned] (${run}): no fault`);
            }
            await expect_fault(machines, keep(xmm, 6), encode(op, xmm, 6, undefined, ABSENT + 16, 1), 14, {
                epilogue: kept(xmm, 6), cr2: ABSENT + 16, label: label + ", [absent page]",
                before: vm => { before(vm); pages(vm, ABSENT, false); }, check,
            });
            for(const vm of machines) pages(vm, ABSENT, true);
            checks += 7;
        }
    }
    console.log(`PASS: #NM with CR0.TS; #UD with CR0.EM, LOCK, F2 and F3; #GP(0) for misaligned XMM operands only; #PF; destinations kept (${OPS.length * 2} forms)`);
    console.log(`PASS: ${checks} SSSE3 checks in the interpreter and the page tier`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                              source/v64/tests/rust/ssse3_model.mjs                                                               0000644 0000000 0000000 00000007172 00000000000 014765  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A model of the SSSE3 instructions written from the SDM's pseudocode,
// independent of src/rust/cpu/simd_int.rs (tests/rust/ssse3.mjs, tests/x64/ssse3.mjs)
import assert from "node:assert/strict";

// The opcode bytes (0F 38 xx, and PALIGNR: 0F 3A 0F) and names
export const OPS = [[0x00, "pshufb"], [0x01, "phaddw"], [0x02, "phaddd"], [0x03, "phaddsw"], [0x04, "pmaddubsw"],
    [0x05, "phsubw"], [0x06, "phsubd"], [0x07, "phsubsw"], [0x08, "psignb"], [0x09, "psignw"], [0x0A, "psignd"],
    [0x0B, "pmulhrsw"], [0x1C, "pabsb"], [0x1D, "pabsw"], [0x1E, "pabsd"], [0x0F, "palignr"]];
export const PALIGNR = 0x0F;

/** The SDM's pseudocode for `op` with N-byte operands (8: MMX, 16: XMM) */
export function model(op, destination, source, imm8)
{
    // (copies: typed array views need aligned offsets)
    destination = Uint8Array.from(destination);
    source = Uint8Array.from(source);
    const n = destination.length, result = new Uint8Array(n);
    const view = (a, T) => new T(a.buffer, a.byteOffset, a.length / T.BYTES_PER_ELEMENT);
    const clamp = x => Math.max(-0x8000, Math.min(0x7FFF, x));
    if(op === PALIGNR)
    {
        // temp = DEST:SRC >> imm8 * 8
        const temp = new Uint8Array(2 * n);
        temp.set(source, 0);
        temp.set(destination, n);
        for(let i = 0; i < n; i++) result[i] = i + imm8 < 2 * n ? temp[i + imm8] : 0;
        return result;
    }
    switch(op)
    {
        case 0x00:
            for(let i = 0; i < n; i++) result[i] = source[i] & 0x80 ? 0 : destination[source[i] & (n === 8 ? 7 : 15)];
            break;
        case 0x01: case 0x03: case 0x05: case 0x07: case 0x02: case 0x06:
        {
            const T = op === 0x02 || op === 0x06 ? Int32Array : Int16Array;
            const d = view(destination, T), s = view(source, T), r = view(result, T), half = d.length / 2;
            for(let i = 0; i < half; i++)
            {
                for(const [v, k] of [[d, i], [s, half + i]])
                {
                    // PHADD: the sum of the pair; PHSUB: the low element minus the high one
                    let x = op <= 0x03 ? v[2 * i] + v[2 * i + 1] : v[2 * i] - v[2 * i + 1];
                    if(op === 0x03 || op === 0x07) x = clamp(x);
                    r[k] = x;
                }
            }
            break;
        }
        case 0x04:
        {
            // unsigned destination bytes times signed source bytes, pairs saturated
            const s = view(source, Int8Array), r = view(result, Int16Array);
            for(let i = 0; i < n / 2; i++) r[i] = clamp(destination[2 * i] * s[2 * i] + destination[2 * i + 1] * s[2 * i + 1]);
            break;
        }
        case 0x08: case 0x09: case 0x0A:
        {
            const T = [Int8Array, Int16Array, Int32Array][op - 0x08];
            const d = view(destination, T), s = view(source, T), r = view(result, T);
            for(let i = 0; i < d.length; i++) r[i] = s[i] < 0 ? -d[i] : s[i] === 0 ? 0 : d[i];
            break;
        }
        case 0x0B:
        {
            const d = view(destination, Int16Array), s = view(source, Int16Array), r = view(result, Int16Array);
            // temp = ((DEST * SRC) >> 14) + 1; DEST = temp[16:1]
            for(let i = 0; i < d.length; i++) r[i] = ((d[i] * s[i] >> 14) + 1) >> 1;
            break;
        }
        case 0x1C: case 0x1D: case 0x1E:
        {
            const [S, U] = [[Int8Array, Uint8Array], [Int16Array, Uint16Array], [Int32Array, Uint32Array]][op - 0x1C];
            const s = view(source, S), r = view(result, U);
            for(let i = 0; i < s.length; i++) r[i] = Math.abs(s[i]);
            break;
        }
        default: assert.fail(op);
    }
    return result;
}
                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/rust/verify-wasmgen-dummy-output.js                                                0000755 0000000 0000000 00000002022 00000000000 020012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import assert from "node:assert/strict";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

process.on("unhandledRejection", exn => { throw exn; });

const DUMMY_MODULE_PATH = path.resolve(__dirname, "../../build/dummy_output.wasm");
const dummy_module = fs.readFileSync(DUMMY_MODULE_PATH);

const wm = new WebAssembly.Module(dummy_module);
const mem = new WebAssembly.Memory({ initial: 256 });

// These tests have to be kept in sync with src/rust/wasmgen/module_init.rs' tests
// XXX: make the test more complex, involving locals, conditionals and stuff

let baz_recd_arg;
function baz(arg) {
    baz_recd_arg = arg;
    return 456;
}

let foo_recd_arg;
function foo(arg) {
    foo_recd_arg = arg;
}

const i = new WebAssembly.Instance(wm, { "e": { m: mem, baz, foo } });
i.exports.f();

assert(baz_recd_arg === 2, `baz returned: "${baz_recd_arg}"`);
assert(foo_recd_arg === 456, `foo returned: "${foo_recd_arg}"`);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              source/v64/tests/rust/x87_fast_math.mjs                                                             0000644 0000000 0000000 00000004377 00000000000 015225  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
const { instance } = await WebAssembly.instantiate(fs.readFileSync("build/softfloat-fast-test.wasm"));
const e = instance.exports;
const view = new DataView(new ArrayBuffer(8));
const bits = x => { view.setFloat64(0, x, true); return view.getBigUint64(0, true); };
const number = x => { view.setBigUint64(0, x, true); return view.getFloat64(0, true); };
const ops = [(a,b) => a+b, (a,b) => a-b, (a,b) => a*b, (a,b) => a/b];
const inputs = [0, -0, 1, -1, 1.5, 2 ** -53, 1 + 2 ** -52, Number.MIN_VALUE,
    2 ** -1022, Number.MAX_VALUE, Infinity, -Infinity, NaN];
e.set_x87_fast_math(1);
for(const precision of [32, 64, 80]) for(let rounding = 0; rounding < 4; rounding++) {
    for(let op = 0; op < 4; op++) {
        for(const a of inputs) for(const b of inputs) {
            const expected = ops[op](a, b);
            const actual = BigInt.asUintN(64, e.fast_math_result(op, bits(a), bits(b), precision, rounding));
            if(Number.isNaN(expected)) assert(Number.isNaN(number(actual)));
            else assert.equal(actual, bits(expected), `op=${op}, p=${precision}, r=${rounding}, a=${a}, b=${b}`);
        }
    }
}
e.set_x87_fast_math(0);
assert.notEqual(e.fast_math_result(0, bits(1), bits(2 ** -53), 64, 3), bits(1),
    "compatible mode still honors upward arithmetic rounding");
e.set_x87_fast_math(1);
assert.equal(e.fast_math_result(0, bits(1), bits(2 ** -53), 64, 3), bits(1));
console.log("PASS: native f64 results for all four operators/all 12 modes, specials and mode switching");
const times = [[], []], checksums = [null, null];
for(let round = 0; round < 7; round++) for(const fast of round & 1 ? [1, 0] : [0, 1]) {
    const start = performance.now();
    checksums[fast] = e.benchmark_fast_math(fast, 8192);
    const ms = performance.now() - start;
    if(round >= 2) times[fast].push(ms);
}
assert.equal(checksums[0], checksums[1], "bounded recurrence has identical final values");
const median = a => a.sort((a,b) => a-b)[a.length >> 1];
const compatible = median(times[0]), fast = median(times[1]);
console.log(JSON.stringify({ benchmark: "bounded F80 Mandelbrot-style recurrence",
    points: 8192, iterations_per_point: 32, compatible_ms: compatible, fast_f64_ms: fast, speedup: compatible / fast }));
                                                                                                                                                                                                                                                                 source/v64/tests/rust/x87_fast_path.asm                                                             0000644 0000000 0000000 00000005761 00000000000 015215  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       bits 16
org 0
start:
    cli
    mov ax, 0xF000
    mov ds, ax
    xor ax, ax
    mov es, ax
    mov ss, ax
    mov sp, 0x8000
again:
    mov bp, controls
    mov cx, 12
    mov di, 0x500
.control:
    mov si, operands
    mov bx, (operands_end - operands) / 20
.pair:
%macro calculate 1
    fninit
    fldcw [ds:bp]
    fld tword [si]
    fld tword [si + 10]
    %1 st1, st0
    fnstsw [es:di + 10]
    fstp tword [es:di]
    add di, 12
%endmacro
    calculate faddp
    calculate fsubp
    calculate fmulp
    calculate fdivp
%macro compare 1
    fninit
    fldcw [ds:bp]
    fld tword [si]
    fld tword [si + 10]
    %1 st1
    fnstsw [es:di + 10]
    fstp tword [es:di]
    add di, 12
%endmacro
    compare fcom
    compare fucom
    add si, 20
    dec bx
    jnz .pair
    mov si, single_inputs
    mov bx, (single_inputs_end - single_inputs) / 4
.single_load:
    fninit
    fldcw [ds:bp]
    fld dword [si]
    fnstsw [es:di + 10]
    fst dword [es:di + 12]
    fnstsw [es:di + 16]
    fstp tword [es:di]
    add di, 18
    add si, 4
    dec bx
    jnz .single_load
    mov si, single_store_inputs
    mov bx, (single_store_inputs_end - single_store_inputs) / 10
.single_store:
    fninit
    fldcw [ds:bp]
    fld tword [si]
    fstp dword [es:di]
    fnstsw [es:di + 4]
    add di, 6
    add si, 10
    dec bx
    jnz .single_store
    add bp, 2
    dec cx
    jnz .control
    inc word [es:0x400]
    jmp again
controls:
    dw 0x007F, 0x047F, 0x087F, 0x0C7F
    dw 0x027F, 0x067F, 0x0A7F, 0x0E7F
    dw 0x037F, 0x077F, 0x0B7F, 0x0F7F
operands:
%macro pair 4
    dq %1
    dw %2
    dq %3
    dw %4
%endmacro
    pair 0xC000000000000000, 0x4000, 0x8000000000000000, 0x4000
    pair 0x8000010000000000, 0x3FFF, 0xFFFFFF0000000000, 0xBFFF
    pair 0x8000000000000001, 0x3FFF, 0x8000000000000001, 0xBFFF
    pair 0xFFFFFFFFFFFFFFFF, 0x7FFE, 0x8000000000000000, 0x4000
    pair 0x8000000000000000, 0x0001, 0x8000000000000000, 0x4000
    pair 1, 0, 0x8000000000000000, 0x3FFF
    pair 0, 0x8000, 0, 0
    pair 0x8000000000000000, 0x7FFF, 0x8000000000000000, 0xFFFF
    pair 0x8000000000000001, 0x7FFF, 0xC000000000000001, 0x7FFF
operands_end:
single_inputs:
    dd 0, 0x80000000, 1, 0x80000001, 0x007FFFFF, 0x00800000
    dd 0x3F800000, 0xBF800000, 0x3FC12345, 0x7F7FFFFF, 0xFF7FFFFF
    dd 0x7F800000, 0xFF800000, 0x7FC12345, 0x7F812345, 0xFFC12345
single_inputs_end:
single_store_inputs:
%macro store_input 2
    dq %1
    dw %2
%endmacro
    store_input 0x8000000000000000, 0x3FFF
    store_input 0x8000008000000000, 0x3FFF
    store_input 0x8000018000000000, 0x3FFF
    store_input 0x8000008000000001, 0xBFFF
    store_input 0xFFFFFF8000000000, 0x407E
    store_input 0x8000000000000001, 0x3F80
    store_input 0x8000000000000001, 0x3F69
    store_input 0, 0x8000
    store_input 0x8000000000000000, 0x7FFF
    store_input 0x8000000000000001, 0x7FFF
    store_input 0xC000000000000001, 0xFFFF
    store_input 0x7FFFFFFFFFFFFFFF, 0x3FFF
single_store_inputs_end:
times 0xFFF0 - ($ - $$) db 0xF4
    jmp 0xF000:start
times 0x10000 - ($ - $$) db 0xF4
               source/v64/tests/rust/x87_fast_path.mjs                                                             0000644 0000000 0000000 00000012140 00000000000 015213  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
// node tests/rust/x87_fast_path.mjs [baseline.wasm] [candidate.wasm]
// With a core built with the profiler feature (build/v86-profiler.wasm), the
// paths the F80 operations took are checked too, from the profiler's
// statistics; X87_PATHS=1 requires such a core.
const bios = Uint8Array.from(fs.readFileSync("build/x87-fast-test.bin")).buffer;
// (the stat enum's names in order: src/rust/profiler.rs)
const stats = fs.readFileSync(new URL("../../src/rust/profiler.rs", import.meta.url), "utf8")
    .match(/pub enum stat \{([^}]*)\}/)[1].replace(/\/\/.*$/gm, "").split(",").map(s => s.trim()).filter(Boolean);
const stat = name => { const index = stats.indexOf(name); assert(index >= 0, name); return index; };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run(wasm, interpreted, fast_math = false) {
    const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: wasm, bios: { buffer: bios }, memory_size: 32 << 20,
        disable_jit: interpreted, disable_keyboard: true, disable_mouse: true,
        x87_fast_math: fast_math,
        disable_speaker: true, net_device: { type: "none" }, autostart: false });
    try {
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        const e = vm.v86.cpu.wm.exports;
        if(process.env.X87_PATHS === "1") assert(e.profiler_is_enabled(), "X87_PATHS=1: " + wasm + " needs the profiler feature");
        const cycles = () => { const bytes = vm.read_memory(0x400, 2); return bytes[0] | bytes[1] << 8; };
        const until = async predicate => {
            const deadline = performance.now() + 10000;
            while(!predicate()) {
                assert(performance.now() < deadline, "x87 guest timed out");
                await sleep(10);
            }
        };
        vm.run();
        await until(() => cycles() >= 20 && (interpreted || vm.get_jit_info().ir.page_tier.native_instructions > 0));
        await vm.stop();
        if(e.profiler_is_enabled()) {
            const [exact, softfloat, native] = ["X87_EXACT", "X87_SOFTFLOAT", "X87_NATIVE_F64"].map(name => e.profiler_stat_get(stat(name)));
            const paths = JSON.stringify({ exact, softfloat, native });
            if(fast_math) assert(native > 0 && exact === 0 && softfloat === 0, "fast math: native f64 only " + paths);
            else assert(exact > 0 && softfloat > 0 && native === 0, "compatible: the exact path and SoftFloat both " + paths);
            checked_paths++;
        }
        const result = Uint8Array.from(vm.read_memory(0x500, 12 * (9 * 6 * 12 + 16 * 18 + 12 * 6)));
        const state = await vm.save_state();
        const before = cycles();
        vm.run();
        await until(() => cycles() > before + 5);
        await vm.stop();
        await vm.restore_state(state);
        assert.equal(e.get_x87_fast_math(), +fast_math, "guest state restore preserves selected host arithmetic policy");
        assert.equal(cycles(), before, "save/restore preserves the guest timeline");
        vm.run();
        await until(() => cycles() > before + 5);
        await vm.stop();
        assert.deepEqual(Uint8Array.from(vm.read_memory(0x500, result.length)), result,
            "x87 arithmetic after state restore preserves results and status words");
        return result;
    } finally { await vm.destroy(); }
}
let checked_paths = 0;
const candidate = process.argv[3] || "build/v86.wasm";
const interpreted = await run(candidate, true);
const jit = await run(candidate, false);
assert.deepEqual(jit, interpreted, "interpreter and actual JIT must match arithmetic/comparison and binary32 conversion results/status");
if(process.argv[2]) {
    assert.deepEqual(jit, await run(process.argv[2], false), "before/after Wasm results must match");
}
const fast_interpreted = await run(candidate, true, true);
const fast_jit = await run(candidate, false, true);
assert.deepEqual(fast_jit, fast_interpreted, "fast f64 interpreter/JIT results and state restore agree");
assert.notDeepEqual(fast_jit, jit, "extended precision/rounding cases expose the intentional semantic difference");
// Per control: nine pairs with four arithmetic results then two comparisons,
// followed by load/store conversion tests. These remain byte-for-byte intact.
const stride = 9 * 6 * 12 + 16 * 18 + 12 * 6;
for(let mode = 0; mode < 12; mode++) {
    for(let pair = 0; pair < 9; pair++) {
        const offset = mode * stride + pair * 72 + 48;
        assert.deepEqual(fast_jit.slice(offset, offset + 24), jit.slice(offset, offset + 24),
            "comparison semantics are unchanged");
    }
    assert.deepEqual(fast_jit.slice(mode * stride + 648, (mode + 1) * stride),
        jit.slice(mode * stride + 648, (mode + 1) * stride), "load/store conversion semantics are unchanged");
}
console.log("PASS: compatible and fast-f64 x87, all 12 controls, interpreter/JIT and save/restore; comparisons and conversions unchanged" +
    (process.argv[2] ? "; compatible mode matches previous Wasm" : "") +
    (checked_paths ? "; the paths taken (profiler statistics, " + checked_paths + " runs)" : ""));
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/rust/x87_jit_cache.mjs                                                             0000644 0000000 0000000 00000051335 00000000000 015164  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";
// x87 in the page tier against the interpreter: native f64 arithmetic over
// the shadow cache (x87_fast_math with x87_jit_cache), its entry guards and
// observers, and the runtime policies. (The region tiers, a second compiled
// arm, were deleted in M11.)
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const CODE = 0x100000, DATA = 0x200000, OUT = 0x210000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24];
const sleep = ms => new Promise(r => setTimeout(r, ms));
const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const machines = [];
async function boot(options, wasm = process.argv[2] || "build/v86.wasm") {
    const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: wasm, bios: { buffer: bios.slice(0) },
        memory_size: 32 << 20, x87_fast_math: true, ...options,
        disable_keyboard: true, disable_mouse: true, disable_speaker: true, net_device: { type: "none" }, autostart: false });
    machines.push(vm);
    await new Promise(r => vm.add_listener("emulator-loaded", r));
    vm.run();
    const end = performance.now() + 10000;
    while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < end); await sleep(1); }
    await vm.stop();
    // SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
    vm.v86.cpu.cr[4] |= 0x600;
    return vm;
}
async function run(vm, body, data, interpreted = false) {
    const p = [...body, 0xFF, 0x05, ...u32(0x600)];
    p.push(0xE9, ...u32(-p.length - 5));
    // Every program reuses CODE: start each from an empty compiler state
    // (compiled code needs more heat to recompile a page after each rewrite).
    vm.v86.cpu.jit_clear_cache();
    vm.write_memory(data, DATA);
    vm.write_memory(new Uint8Array(1024), OUT);
    vm.write_memory(new Uint8Array(4), 0x600);
    vm.write_memory(Uint8Array.from(p), CODE);
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    // A preceding #NM case may stop with TS set between guest instructions.
    // Reset that fixture state; the #NM test sets TS itself inside its body.
    cpu.cr[0] &= ~12;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const end = performance.now() + 10000;
    while(word(vm, 0x600) < 4 || !interpreted && compiled_activations(e) === start) {
        assert(performance.now() < end, "guest/JIT timeout"); await sleep(1);
    }
    await vm.stop();
    return { bytes: Uint8Array.from(vm.read_memory(OUT, 512)), program: p };
}
let reference, helper;
const arms = [];
// Interpreter reference, then every compiled arm (the page tier); all must produce identical bytes.
async function compare(body, message) {
    const a = await run(reference, body, data, true), results = [];
    for(const { label, vm } of arms) {
        const b = await run(vm, body, data);
        assert.deepEqual(b.bytes, a.bytes, `${label}: ${message}`);
        results.push(b);
    }
    return { a, results };
}
const region = [0xD9,0xC0, 0xD8,0xC8, 0xD9,0xC9, 0xD8,0xC9, 0xDE,0xC1,
    0xD8,0xE1, 0xDC,0xE9, 0xD8,0xF2, 0xD8,0xCA];
const snapshot = [0xDB,0xF1, 0x9C,0x58,0xA3,...u32(OUT+128), // FCOMI then flags
    0xDD,0x35,...u32(OUT)]; // FNSAVE observes every stack slot, tags, TOP and status
const data = new Uint8Array(4096), d = new DataView(data.buffer);
for(const [i,n] of [1.234567890123,0.7321987654321,2].entries()) d.setFloat64(i*8,n,true);
const prefix = (control, rotation = 0, wide = false, count = 3) => {
    d.setUint16(64,control,true);
    return [0xDB,0xE3,...Array.from({length:8},()=>[0xD9,0xEE]).flat(),0xDB,0xE3,
        ...Array.from({length:rotation},()=>[0xD9,0xF7]).flat(),0xD9,0x2D,...u32(DATA+64),
        ...Array.from({length:count},(_,i)=>[...(wide && i === 2 ? [0xDB,0x2D,...u32(DATA+80)] : [0xDD,0x05,...u32(DATA+i%3*8)])]).flat()];
};
try {
    reference = await boot({ disable_jit: true, x87_jit_cache: false });
    // The page tier without the x87 cache: every x87 operation uses helpers.
    helper = await boot({ x87_jit_cache: false });
    for(const { label, options } of COMPILED_ARMS) arms.push({ label, vm: await boot({ ...options, x87_jit_cache: true }) });
    for(const pc of [0,2,3]) for(let rc=0;rc<4;rc++) for(let rotation=0;rotation<8;rotation++) {
        const control=0x7F|pc<<8|rc<<10;
        const body=[...prefix(control,rotation),...region,
            0xDD,0x15,...u32(OUT+256), // memory observer separates regions
            ...region,...snapshot];
        const { a } = await compare(body, `pc=${pc},rc=${rc},top=${rotation}`);
        assert.deepEqual((await run(helper,body,data)).bytes,a.bytes,`helper pc=${pc},rc=${rc},top=${rotation}`);
    }
    console.log("PASS: 96 control/TOP combinations, native regions, stack copies/exchanges/pops, compare/memory observers");
    // Exercise every decoded arithmetic form, including reverse operands,
    // ST(0) aliases, distant stack slots and popping into ST(0).
    for(const opcode of [0xD8,0xDC,0xDE]) for(const group of [0,1,4,5,6,7]) for(const r of [0,1,7]) {
        const body=[...prefix(0x27F,0,false,8),0xD8,0xC1,0xD8,0xC9,
            opcode,0xC0|group<<3|r,...snapshot];
        await compare(body, `arithmetic opcode=${opcode},group=${group},r=${r}`);
    }
    console.log("PASS: all 18 arithmetic forms, aliases, distant slots and pop destinations");
    // Ordered compares must preserve all non-arithmetic EFLAGS, distinguish
    // status-word vs integer flags, pop correctly, and keep values cached.
    const observe=snapshot.slice(2); // do not overwrite the comparison under test
    const compare_forms=[[0xD8,0xD1],[0xD8,0xD9],[0xDC,0xD1],[0xDC,0xD9],
        [0xDE,0xD9],[0xDB,0xF1],[0xDF,0xF1]];
    for(const cmp of compare_forms) for(const value of [0.0625,0.125,0.25,-0.125]) for(const rc of [0,1,2,3]) {
        d.setFloat64(0,1,true);d.setFloat64(8,value,true);d.setFloat64(16,2,true);
        const body=[...prefix(0x27F|rc<<10,7,false,8),0xD9,0xE5, // FXAM seeds C bits
            0xB8,...u32(0x7FFFFFFF),0x83,0xC0,1,0xF9, // deferred OF/SF/AF and CF
            0xD8,0xC0,0xD8,0xC0,0xD8,0xC0,...cmp,...observe];
        await compare(body, `compare ${cmp}, value=${value},rc=${rc}`);
    }
    // Normal entry -> overflow -> NaN exercises signaling ordered comparisons,
    // including a later ADD clearing SoftFloat flags but retaining x87 invalid.
    d.setFloat64(0,Number.MAX_VALUE,true);d.setFloat64(8,2,true);d.setFloat64(16,3,true);
    for(const cmp of compare_forms) for(const tail of [[],[0xD8,0xC1],[0xD8,0xC9],[0xD8,0xE1],[0xD8,0xF1]]) {
        const body=[...prefix(0x27F,0,false,4),0xB8,...u32(0x7FFFFFFF),0x83,0xC0,1,0xF9,0xD8,0xC0,0xD8,0xE0,0xD8,0xC0,...cmp,...tail,...observe];
        const { results } = await compare(body, `cached NaN compare ${cmp} and subsequent arithmetic ${tail}`);
        for(const b of results) assert(new DataView(b.bytes.buffer).getUint16(4,true)&1,"ordered NaN sets x87 invalid");
    }
    for(const [i,n] of [1.234567890123,0.7321987654321,2].entries()) d.setFloat64(i*8,n,true);
    // Compare then more arithmetic/stack moves stays in a single region.
    const joined=[...prefix(0x27F),...region,0xDF,0xF1,0xD9,0xC0,
        0xD8,0xC1,0xD8,0xC9,0xD8,0xE1,0xD8,0xD1,...observe];
    await compare(joined, "comparison connects subsequent cached operations");
    console.log("PASS: ordered compare forms/rounding, EFLAGS/status, pops, NaNs and cache continuity");
    // Conditional branches consume the EFLAGS produced by FCOMIP at a block
    // boundary. Cover ordered less/equal/greater and unordered parity branches.
    for(const value of [0.0625,0.125,0.25,Number.MAX_VALUE]) for(const jump of [0x72,0x74,0x7A]) {
        d.setFloat64(16,value,true);d.setFloat64(8,1,true);
        const arithmetic=value===Number.MAX_VALUE ? [0xD8,0xC0,0xD8,0xE0,0xD8,0xC0] : [0xD8,0xC0,0xD8,0xC0,0xD8,0xC0];
        const body=[...prefix(0x27F),...arithmetic,0xDF,0xF1,
            jump,7,0xB8,...u32(111),0xEB,5,0xB8,...u32(222),0xA3,...u32(OUT+300),...observe];
        await compare(body, "Jcc sees cached FCOMIP flags");
        const take=jump===0x72 ? value===0.0625 || value===Number.MAX_VALUE :
            jump===0x74 ? value===0.125 || value===Number.MAX_VALUE : value===Number.MAX_VALUE;
        for(const { vm } of arms) assert.equal(word(vm,OUT+300),take?222:111);
    }
    for(const [i,n] of [1.234567890123,0.7321987654321,2].entries()) d.setFloat64(i*8,n,true);
    // Entry guards preserve wide/special/subnormal values and stack faults.
    for(const [mantissa,exponent,count] of [[0x8000000000000001n,0x3FFF,3],
        [0x8000000000000000n,0x7FFF,3],[0xC000000000000000n,0x7FFF,3],
        [0xA000000000000000n,0x7FFF,3],[1n,0,3],[0x8000000000000000n,0x3FFF,1],
        [0x8000000000000000n,0x3FFF,8]]) {
        d.setBigUint64(80,mantissa,true);d.setUint16(88,exponent,true);
        const body=[...prefix(0x27F,0,true,count),...region,...snapshot];
        await compare(body, "guarded fallback preserves original helper semantics");
    }
    for(const value of [Number.MAX_VALUE, 2 ** -1022, Number.MIN_VALUE, -0]) {
        d.setFloat64(0,value,true);
        for(let rc=0;rc<4;rc++) {
            const body=[...prefix(0x27F|rc<<10),...region,...snapshot];
            await compare(body,"overflow/subnormal/NaN intermediates preserve helper results");
        }
    }
    d.setFloat64(0,1.234567890123,true);
    // Newly native stack/control operations, quiet compares and math helpers
    // must preserve the complete F80 image, including freed physical slots.
    const extra_ops = [
        [0xD9,0xFC], [0xD9,0xD0], [0xD9,0xE0], [0xD9,0xE1], [0xD9,0xE8], [0xD9,0xEE],
        [0xD9,0xF6,0xD9,0xF7], [0xDD,0xC2], [0xDD,0xD2], [0xDD,0xDA],
        [0xDD,0xE1], [0xDD,0xE9], [0xDA,0xE9], [0xDB,0xE9], [0xDF,0xE9],
        [0xD9,0xFE], [0xD9,0xFF], [0xD9,0xFB], [0xD9,0xF2], [0xD9,0xF3],
    ];
    for(const ops of extra_ops) for(const rotation of [0,3,7]) for(const rc of [0,1,2,3]) {
        const body=[...prefix(0x27F|rc<<10,rotation),0xD8,0xC1,0x31,0xC0,...ops,...observe];
        await compare(body,`extended operations ${ops},top=${rotation},rc=${rc}`);
    }
    for(const value of [-2.5,-1.5,-0.5,-0,0,0.5,1.5,2.5,2**53,Infinity]) for(const rc of [0,1,2,3]) {
        d.setFloat64(16,value,true);
        const body=[...prefix(0x27F|rc<<10),0xD9,0xFC,...snapshot];
        await compare(body,`FRNDINT value=${value},rc=${rc}`);
    }
    d.setFloat64(16,2,true);
    // Generate a quiet NaN inside the cache, then use every unordered compare.
    for(const cmp of [[0xDD,0xE1],[0xDD,0xE9],[0xDA,0xE9],[0xDB,0xE9],[0xDF,0xE9]]) {
        const body=[...prefix(0x27F),0xD8,0xE0,0xD8,0xF0,0x31,0xC0,...cmp,...observe];
        await compare(body,`quiet NaN compare ${cmp}`);
    }
    console.log("PASS: native stack/control/quiet comparisons and cached transcendental helpers");
    // MMX accesses observe the physical F80 storage; direct MMX writes then
    // invalidate cached values before later x87 accesses, including EMMS.
    for(const ops of [
        [0x0F,0x7F,0x05,...u32(OUT+256)], // MOVQ [out],mm0
        [0x0F,0x6F,0x05,...u32(DATA),0x0F,0x77], // MOVQ mm0,[data]; EMMS
        [0x0F,0xEF,0xC0,0x0F,0x77], // PXOR mm0,mm0; EMMS
        [0x66,0x0F,0x2A,0xC0], // CVTPI2PD xmm0,mm0 also has a mandatory prefix
        [0xF3,0x0F,0xD6,0xC0,0xF2,0x0F,0xD6,0xC8,0x0F,0x77], // MMX/XMM transfers
        [0x66,0x0F,0xEF,0xC0], // ordinary XMM PXOR must not alias the x87 stack

        [0x0F,0xAE,0x05,...u32(OUT+512), // FXSAVE/FXRSTOR, overwrite between
         0xD9,0xE0,0x0F,0xAE,0x0D,...u32(OUT+512)],
        [0xD9,0x35,...u32(OUT+256),0xD9,0x25,...u32(OUT+256)], // environment
        [0xDD,0x35,...u32(OUT+256),0xDD,0x25,...u32(OUT+256)], // full state
    ]) {
        const body=[...prefix(0x27F),...region,0x31,0xC0,...ops,...observe];
        await compare(body,`MMX/state observer ${ops}`);
    }
    for(const is32 of [false,true]) for(const rc of [0,1,2,3]) {
        for(const bits of is32 ? [0,0x80000000,1,0x7F800000,0x7FC12345,0x7F812345] :
            [0n,0x8000000000000000n,1n,0x7FF0000000000000n,0x7FF8123456789ABCn,0x7FF0123456789ABCn]) {
            if(is32) d.setUint32(96,bits,true); else d.setBigUint64(96,bits,true);
            const body=[...prefix(0x27F|rc<<10),is32?0xD9:0xDD,0x05,...u32(DATA+96),
                0xDD,0x1D,...u32(OUT+256),...snapshot];
            await compare(body,`memory load/store width=${is32?32:64},bits=${bits},rc=${rc}`);
        }
    }
    console.log("PASS: cached m32/m64 loads and m64 stores, signed zero, subnormals, infinities and NaN payloads");
    // Consecutive regions separated by real branches reuse the shadow cache.
    // No F80 observer is needed until the final FNSAVE.
    const split=[...prefix(0x27F),0x31,0xC0,...Array.from({length:30},()=>[0xD8,0xC9,0xEB,0]).flat(),...observe];
    await compare(split, "persistent branch boundaries");
    console.log("PASS: persistent branch caching, MMX aliases and environment/full-state observers");
    // Observe the committed FPU state inside #PF and resume after the memory
    // instruction. #NM must instead trap before any cached operation executes.
    const IDT=0x220000,DESC=0x221000,HANDLER=0x222000;
    for(const fault_kind of ["read","store","load","nm"]) {
        const nm=fault_kind==="nm", fault_length=fault_kind==="read"?5:6;
        const handler=nm ? [0x8B,0x04,0x24,0xA3,...u32(OUT+400),0x0F,0x06,0xCF] :
            [0xDD,0x35,...u32(OUT),0xDD,0x25,...u32(OUT),
                0x8B,0x44,0x24,4,0xA3,...u32(OUT+400),
                0x83,0x44,0x24,4,fault_length,0x83,0xC4,4,0xCF];
        for(const vm of machines) {
            vm.write_memory(Uint8Array.from([HANDLER&255,HANDLER>>>8&255,8,0,0,0x8E,HANDLER>>>16&255,HANDLER>>>24]),IDT+(nm?7:14)*8);
            vm.write_memory(Uint8Array.from([0xFF,7,...u32(IDT)]),DESC);
            vm.write_memory(Uint8Array.from(handler),HANDLER);
        }
        const body=[...prefix(0x27F),0x0F,0x01,0x1D,...u32(DESC)];
        if(nm) body.push(0x0F,0x20,0xC0,0x83,0xC8,8,0x0F,0x22,0xC0);
        const fault_ops=[...region,0xDF,0xF1];
        const fault=CODE+body.length+(nm?0:fault_ops.length);
        body.push(...fault_ops);
        if(nm) body.push(...snapshot);
        else body.push(...(fault_kind==="store"?[0xDD,0x1D]:fault_kind==="load"?[0xDD,0x05]:[0xA1]),...u32(0xA00000));
        await compare(body,nm?"#NM preserves first-instruction EIP and state":`#PF ${fault_kind} sees precise cache and stack state`);
        for(const { vm } of arms) assert.equal(word(vm,OUT+400),fault,"precise fault EIP");
    }
    console.log("PASS: overflow/subnormal intermediates and precise #NM/#PF state");
    // A long x87 run (20 copies of the sequence; the region tiers split it at
    // their bound until M11); warm code checks the runtime policy anew at
    // every instruction (x87_native_policy).
    const body=[...prefix(0x27F),...Array.from({length:20},()=>region).flat(),...snapshot];
    const a=await run(helper,body,data);
    helper.v86.cpu.wm.exports.set_x87_fast_math(false);
    const compatible=await run(helper,body,data);
    helper.v86.cpu.wm.exports.set_x87_fast_math(true);
    const output=vm=>Uint8Array.from(vm.read_memory(OUT,512));
    for(const { label, vm: cached } of arms) {
        const e=cached.v86.cpu.wm.exports, b=await run(cached,body,data);
        assert.deepEqual(b.bytes,a.bytes,`${label}: a long x87 run preserves all stack state`);
        e.set_x87_fast_math(false);cached.run();await sleep(25);await cached.stop();
        assert.deepEqual(output(cached),compatible.bytes,`${label}: warm code honors compatible arithmetic`);
        e.set_x87_fast_math(true);cached.run();await sleep(25);await cached.stop();
        const saved=await cached.save_state();
        e.set_x87_jit_cache(false);cached.run();await sleep(25);await cached.stop();
        assert.deepEqual(output(cached),a.bytes,`${label}: warm code honors cache disable`);
        await cached.restore_state(saved);
        assert.equal(e.get_x87_jit_cache(),0,"restore retains selected host policy");
        e.set_x87_jit_cache(true);cached.run();await sleep(25);await cached.stop();
        assert.deepEqual(output(cached),b.bytes,`${label}: restore regenerates valid cached code`);
    }
    console.log("PASS: guard fallback, long x87 runs, runtime switch, SMC between cases and save/restore");
    // Save while f64 is authoritative and no guest F80 observer has run.
    d.setFloat64(8,1,true);d.setFloat64(16,2,true);
    const seed_only=[...prefix(0x27F),0xD8,0xC1,0xFF,0x05,...u32(0x600),0xE9,...u32(-11)];
    for(const { label, vm: cached } of arms) {
        await run(cached,seed_only,data);
        const dirty_saved=await cached.save_state();
        assert.equal(cached.v86.cpu.fpu_st[5*4+1]>>>0,0xC0000000,`${label}: save materializes 3.0 significand`);
        assert.equal(cached.v86.cpu.fpu_st[5*4+2]&65535,0x4000,`${label}: save materializes 3.0 exponent`);
        await run(cached,[...prefix(0x27F),0xD8,0xE0,...snapshot],data);
        await cached.restore_state(dirty_saved);
        assert.equal(BigInt.asUintN(64,cached.v86.cpu.wm.exports.fpu_store_m64_bits()),0x4008000000000000n,
            `${label}: restore discards newer shadow values and reads saved 3.0`);
    }
    console.log("PASS: host save materializes dirty f64 state and restore discards stale shadow values");
    // Warm-loop throughput in the page tier, same generated code and input; switch
    // only runtime cache policy. The body reloads its seeds each iteration.
    const cached=arms[0].vm;
    await run(cached,[...prefix(0x27F),...Array.from({length:3},()=>region).flat(),...snapshot],data);
    const times=[[],[]];
    for(let round=0;round<7;round++) for(const mode of round&1?[1,0]:[0,1]) {
        cached.v86.cpu.wm.exports.set_x87_jit_cache(!!mode);
        const start=performance.now(),before=word(cached,0x600);
        while(performance.now()-start<80) cached.v86.cpu.main_loop();
        if(round>=2) times[mode].push(((word(cached,0x600)-before)>>>0)/(performance.now()-start));
    }
    const median=a=>a.sort((a,b)=>a-b)[a.length>>1];
    console.log(JSON.stringify({benchmark:"actual x87 guest loop",helper_loops_per_ms:median(times[0]),
        cached_loops_per_ms:median(times[1]),speedup:median(times[1])/median(times[0])}));
    if(process.env.X87_COMPARE_BASELINE) {
        const baseline=await boot({ x87_jit_cache: true },process.env.X87_COMPARE_BASELINE);
        cached.v86.cpu.wm.exports.set_x87_jit_cache(true);
        const body=[...prefix(0x27F),...region,0xD8,0xD1,...region,0xD8,0xD1,...region,0xDF,0xF1,...observe];
        const before=await run(baseline,body,data),after=await run(cached,body,data);
        assert.deepEqual(after.bytes,before.bytes,"previous cached build and cached comparisons agree");
        const rates=[[],[]], vms=[baseline,cached];
        for(let round=0;round<7;round++) for(const mode of round&1?[1,0]:[0,1]) {
            const vm=vms[mode],start=performance.now(),count=word(vm,0x600);
            while(performance.now()-start<80) vm.v86.cpu.main_loop();
            if(round>=2) rates[mode].push(((word(vm,0x600)-count)>>>0)/(performance.now()-start));
        }
        console.log(JSON.stringify({benchmark:"previous build vs persistent cache guest loop",
            before_loops_per_ms:median(rates[0]),after_loops_per_ms:median(rates[1]),speedup:median(rates[1])/median(rates[0])}));
        // Seed once, then retain the stack across loop backedges, matching the
        // persistence mechanism independently of per-iteration FSAVE/reloads.
        d.setFloat64(0,0.25,true);d.setFloat64(8,1,true);d.setFloat64(16,2,true);
        const seeded=prefix(0x27F), loop=[...Array.from({length:4},()=>
            [0xD8,0xC1,0xD8,0xE1,0xD8,0xC9]).flat(),0xD8,0xD1,
            0xDD,0x15,...u32(OUT+256),0xFF,0x05,...u32(0x600)];
        loop.push(0xE9,...u32(-loop.length-5));
        const persistent_body=[...seeded,...loop];
        const old_persistent=await run(baseline,persistent_body,data),new_persistent=await run(cached,persistent_body,data);
        assert.deepEqual(new_persistent.bytes,old_persistent.bytes,"persistent loop output agrees");
        const persistent_rates=[[],[]];
        for(let round=0;round<7;round++) for(const mode of round&1?[1,0]:[0,1]) {
            const vm=vms[mode],start=performance.now(),count=word(vm,0x600);
            while(performance.now()-start<80) vm.v86.cpu.main_loop();
            if(round>=2) persistent_rates[mode].push(((word(vm,0x600)-count)>>>0)/(performance.now()-start));
        }
        console.log(JSON.stringify({benchmark:"persistent x87 backedge guest loop",
            before_loops_per_ms:median(persistent_rates[0]),after_loops_per_ms:median(persistent_rates[1]),
            speedup:median(persistent_rates[1])/median(persistent_rates[0])}));

    }
} finally { for(const vm of machines) await vm.destroy(); }
                                                                                                                                                                                                                                                                                                   source/v64/tests/rust/xsave.mjs                                                                     0000644 0000000 0000000 00000122537 00000000000 013676  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The XSAVE feature set in the 32-bit engines (docs/simd-xsave-plan.md P2):
// CPUID leaves 1 and 0xD, CR4.OSXSAVE, XGETBV/XSETBV, XSAVE/XRSTOR in the
// standard format (round trips, partial saves, init on restore, the header
// and MXCSR checks, the fault order and page faults without partial effects)
// and FXSAVE/FXRSTOR, which share the state encoding (cpu/xstate.rs). Each
// case runs in the interpreter, then hot under the page tier; its checks
// follow the hot run (compiled code) and the cold one. P9:
// XSAVEOPT, XGETBV(1), XSAVEC and XRSTOR's compacted form, XSAVES, XRSTORS and
// IA32_XSS.
import assert from "node:assert/strict";
import fs from "node:fs";
import { V86 } from "../../build/libv86.mjs";
import { COMPILED_ARMS, compiled_activations } from "./compiled_arms.mjs";

const candidate = process.argv[2] || "build/v86.wasm";
const bios = Uint8Array.from(fs.readFileSync("build/jit-capacity.bin")).buffer;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const CODE = 0x100000, DATA = 0x200000, OUT = 0x210000, FAULT = 0x211000, SKIP = 0x211100;
const IDT = 0x250000, DESCRIPTOR = 0x251000, HANDLER = 0x280000;
// XSAVE areas (64-byte aligned); CROSSING's YMM_Hi128 starts on the next page
const AREA = 0x202000, AREA2 = 0x203000, AREA3 = 0x204000, CROSSING = 0x205DC0, ABSENT = 0x206000;

const word = (vm, a) => new DataView(Uint8Array.from(vm.read_memory(a, 4)).buffer).getUint32(0, true);
const bytes = (vm, a, n) => Uint8Array.from(vm.read_memory(a, n));

// instructions
const mov_eax = n => [0xB8, ...u32(n)], mov_ecx = n => [0xB9, ...u32(n)], mov_edx = n => [0xBA, ...u32(n)], mov_ebx = n => [0xBB, ...u32(n)];
const store_eax = a => [0xA3, ...u32(a)], store_ebx = a => [0x89, 0x1D, ...u32(a)];
const store_ecx = a => [0x89, 0x0D, ...u32(a)], store_edx = a => [0x89, 0x15, ...u32(a)];
const cpuid = (leaf, subleaf, out) => [...mov_eax(leaf), ...mov_ecx(subleaf), 0x0F, 0xA2,
    ...store_eax(out), ...store_ebx(out + 4), ...store_ecx(out + 8), ...store_edx(out + 12)];
const OSXSAVE = [0x0F, 0x20, 0xE0, 0x0D, ...u32(1 << 18), 0x0F, 0x22, 0xE0];          // CR4 |= OSXSAVE
const NO_OSXSAVE = [0x0F, 0x20, 0xE0, 0x25, ...u32(~(1 << 18) >>> 0), 0x0F, 0x22, 0xE0];
// SSE enabled (CR4.OSFXSR, OSXMMEXCPT: the BIOS leaves them clear)
const ENABLE_SSE = [0x0F, 0x20, 0xE0, 0x0D, ...u32(0x600), 0x0F, 0x22, 0xE0];
const SET_TS = [0x0F, 0x20, 0xC0, 0x0D, ...u32(8), 0x0F, 0x22, 0xC0], CLTS = [0x0F, 0x06];
const XGETBV = [0x0F, 0x01, 0xD0], XSETBV = [0x0F, 0x01, 0xD1];
const xsetbv = value => [...mov_ecx(0), ...mov_eax(value), ...mov_edx(0), ...XSETBV];
const XSAVE = [0x0F, 0xAE, 0x23], XRSTOR = [0x0F, 0xAE, 0x2B], XSAVEOPT = [0x0F, 0xAE, 0x33]; // [ebx]
const XSAVEC = [0x0F, 0xC7, 0x23], XSAVES = [0x0F, 0xC7, 0x2B], XRSTORS = [0x0F, 0xC7, 0x1B];
const FXSAVE = [0x0F, 0xAE, 0x03], FXRSTOR = [0x0F, 0xAE, 0x0B];
const ALL = [...mov_eax(-1), ...mov_edx(-1)];
const fld = a => [0xDD, 0x05, ...u32(a)], fstp = a => [0xDD, 0x1D, ...u32(a)], FNINIT = [0xDB, 0xE3];
const fnstcw = a => [0xD9, 0x3D, ...u32(a)];
const movups_load = (r, a) => [0x0F, 0x10, 5 | r << 3, ...u32(a)], movups_store = (r, a) => [0x0F, 0x11, 5 | r << 3, ...u32(a)];
const ldmxcsr = a => [0x0F, 0xAE, 0x15, ...u32(a)], stmxcsr = a => [0x0F, 0xAE, 0x1D, ...u32(a)];
const XORPS_0_7 = [0x0F, 0x57, 0xC0, 0x0F, 0x57, 0xFF];
const VZEROALL = [0xC5, 0xFC, 0x77];
// VINSERTF128 ymm6, ymm6, [a], 1: YMM6's upper half from memory
const vinsertf128_6 = a => [0xC4, 0xE3, 0x4D, 0x18, 0x35, ...u32(a), 1];
const xgetbv = (ecx, out) => [...mov_ecx(ecx), ...XGETBV, ...store_eax(out), ...store_edx(out + 4)];

const machines = [];
// The start of every program: a known CR0.TS, CR4.OSXSAVE and XCR0 (a warm
// run stops anywhere in its loop)
let preamble = [];
async function run(vm, program, warm = true, interpreter = false)
{
    const cpu = vm.v86.cpu, e = cpu.wm.exports;
    if(warm) cpu.jit_clear_cache();
    vm.write_memory(Uint8Array.from(program), CODE);
    vm.write_memory(new Uint8Array(4), 0x600);
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2; cpu.flags_changed[0] = 0;
    cpu.instruction_pointer[0] = CODE; cpu.in_hlt[0] = 0;
    const start = compiled_activations(e);
    vm.run();
    const deadline = performance.now() + 20000;
    while(word(vm, 0x600) !== 0xCAFE || warm && !interpreter && compiled_activations(e) === start)
    {
        assert(performance.now() < deadline, "program/JIT timeout");
        await sleep(1);
    }
    // (a hot run goes on a while, then ends at the end of a round)
    if(warm)
    {
        await sleep(20);
        vm.write_memory(Uint8Array.of(1), 0x604);
        while(!cpu.in_hlt[0])
        {
            assert(performance.now() < deadline, "program end timeout");
            await sleep(1);
        }
    }
    await vm.stop();
}
// the body repeats until byte 0x604 is set, then halts at the end of the
// round; each round clears the fault record first
const CLEAR_FAULT = [0xC7, 0x05, ...u32(FAULT), 0, 0, 0, 0];
function loop(body)
{
    const p = [...CLEAR_FAULT, ...body, 0xC7, 0x05, ...u32(0x600), ...u32(0xCAFE), 0x80, 0x3D, ...u32(0x604), 0, 0x75, 5];
    p.push(0xE9, ...u32(-p.length - 5), 0xF4);
    return p;
}
/** A handler for `vector`: records it, the faulting EIP, CR2 and the error code, and skips [SKIP] bytes */
function handler(vector, error_code)
{
    const p = [];
    if(error_code) p.push(0x58, ...store_eax(FAULT + 12));            // pop eax: the error code
    p.push(0xC7, 0x05, ...u32(FAULT), ...u32(vector));
    p.push(0x8B, 0x04, 0x24, ...store_eax(FAULT + 4));                // [esp]: EIP
    p.push(0x0F, 0x20, 0xD0, ...store_eax(FAULT + 8));                // CR2
    p.push(0xA1, ...u32(SKIP), 0x01, 0x04, 0x24, 0xCF);               // add [esp], [SKIP]; iret
    return p;
}
const VECTORS = [[6, false], [7, false], [13, true], [14, true]];
/** Runs `program` on each machine of `set`, hot (compiled), then once more
 * cold (mostly interpreted: the program was rewritten), and checks each run
 * with `check` (the hot run stops anywhere in its loop: what the loop's
 * rounds write alike) */
async function run_all(program, before = () => {}, set = machines, check = () => {})
{
    for(const vm of set)
    {
        vm.write_memory(Uint8Array.from([255, 7, ...u32(IDT)]), DESCRIPTOR);
        VECTORS.forEach(([vector, error_code], i) => {
            const h = HANDLER + i * 0x100;
            vm.write_memory(Uint8Array.from([h & 255, h >>> 8 & 255, 8, 0, 0, 0x8E, h >>> 16 & 255, h >>> 24]), IDT + vector * 8);
            vm.write_memory(Uint8Array.from(handler(vector, error_code)), h);
        });
        // (the program first loads the IDT)
        const p = [0x0F, 0x01, 0x1D, ...u32(DESCRIPTOR), ...ENABLE_SSE, ...preamble, ...program];
        for(const warm of [true, false])
        {
            before(vm);
            vm.write_memory(new Uint8Array(16), FAULT);
            vm.write_memory(Uint8Array.of(warm ? 0 : 1), 0x604);
            await run(vm, loop(p), warm, vm === set[0]);
            check(vm, `${warm ? "hot" : "cold"}, machine ${set.indexOf(vm)}`);
        }
    }
}
/** The interpreter, then the page tier, with `options` */
async function create_machines(options = {})
{
    const set = [];
    for(const arm of [{ disable_jit: true }, ...COMPILED_ARMS.map(arm => arm.options)])
    {
        const vm = new V86({ graphics_adapter: "bochs_vga", wasm_path: candidate, bios: { buffer: bios.slice(0) }, memory_size: 32 << 20,
            ...arm, ...options, disable_keyboard: true, disable_mouse: true, disable_speaker: true,
            net_device: { type: "none" }, autostart: false });
        set.push(vm);
        await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
        vm.run();
        const deadline = performance.now() + 10000;
        while(word(vm, 0x500) !== 0xCAFE) { assert(performance.now() < deadline); await sleep(1); }
        await vm.stop();
    }
    return set;
}
/**
 * `faulting` raises `vector` at its first byte after `prologue` (the
 * handler skips it, `epilogue` follows), with CR2 `cr2` for a page fault
 */
async function expect_fault(set, prologue, faulting, vector, { epilogue = [], before = () => {}, cr2, label, check = () => {} } = {})
{
    // (the fault record's clearing, the IDT load, SSE and the preamble come first)
    const at = CODE + CLEAR_FAULT.length + 7 + ENABLE_SSE.length + preamble.length + prologue.length;
    const name = label || faulting.map(b => b.toString(16)).join(" ");
    await run_all([...prologue, ...faulting, ...epilogue], vm => {
        vm.write_memory(Uint8Array.from(u32(faulting.length)), SKIP);
        before(vm);
    }, set, (vm, run) => {
        assert.deepEqual([word(vm, FAULT), word(vm, FAULT + 4)], [vector, at], `${name} (${run}): vector, EIP`);
        if(cr2 !== undefined) assert.equal(word(vm, FAULT + 8), cr2, `${name} (${run}): CR2`);
        check(vm, run);
    });
}
/** A check: no fault */
const no_fault = name => (vm, run) =>
    assert.equal(word(vm, FAULT), 0, `${name} (${run}): fault ${word(vm, FAULT)} at ${word(vm, FAULT + 4).toString(16)}`);
const fill = (vm, a, n, byte) => vm.write_memory(new Uint8Array(n).fill(byte), a);
/** A pattern-filled area whose header (bytes 512-575) is 0 but XSTATE_BV */
function prepare(vm, a, xstate_bv = 0)
{
    fill(vm, a, 832, 0xCC);
    vm.write_memory(new Uint8Array(64), a + 512);
    vm.write_memory(Uint8Array.from(u32(xstate_bv)), a + 512);
}
const pages = (vm, page, present) => {
    // (the BIOS's page table: 0x13000, identity)
    vm.write_memory(Uint8Array.from(u32(present ? page | 3 : 0)), 0x13000 + (page >>> 12) * 4);
    vm.v86.cpu.wm.exports["full_clear_tlb"]();
};

let count = 0;
try
{
    // Without XSAVE: no CPUID bits, CR4.OSXSAVE is reserved, the instructions #UD
    machines.push(...await create_machines());
    preamble = CLTS;
    await run_all(cpuid(1, 0, OUT), undefined, machines, (vm, run) => assert.equal(word(vm, OUT + 8) & 3 << 26, 0, `CPUID.1:ECX XSAVE, OSXSAVE (${run})`));
    await expect_fault(machines, OSXSAVE.slice(0, -3), OSXSAVE.slice(-3), 13, { label: "MOV CR4 with OSXSAVE" });
    for(const [instruction, label] of [[XGETBV, "XGETBV"], [XSETBV, "XSETBV"], [[...mov_ebx(AREA), ...XSAVE], "XSAVE"], [[...mov_ebx(AREA), ...XSAVEOPT], "XSAVEOPT"],
        [[...mov_ebx(AREA), ...XSAVEC], "XSAVEC"], [[...mov_ebx(AREA), ...XSAVES], "XSAVES"], [[...mov_ebx(AREA), ...XRSTORS], "XRSTORS"]])
    {
        const prologue = instruction.length > 3 ? instruction.slice(0, -3) : [];
        await expect_fault(machines, prologue, instruction.slice(-3), 6, { label: label + " without XSAVE" });
    }
    count += 9;
    for(const vm of machines) await vm.destroy();
    machines.length = 0;
    console.log("PASS: without XSAVE, CPUID reports none, CR4.OSXSAVE is reserved, XGETBV/XSETBV/XSAVE/XSAVEOPT/XSAVEC/XSAVES/XRSTORS #UD");

    // XSAVE without AVX: XCR0 can have x87 and SSE state
    machines.push(...await create_machines({ cpu_features: ["XSAVE"], cpu_features_unreleased: true }));
    preamble = [...CLTS, ...OSXSAVE, ...xsetbv(1), ...NO_OSXSAVE];
    await run_all([...cpuid(1, 0, OUT), ...OSXSAVE, ...cpuid(1, 0, OUT + 16), ...cpuid(0xD, 0, OUT + 32),
        ...cpuid(0xD, 1, OUT + 48), ...cpuid(0xD, 2, OUT + 64), ...mov_ecx(0), ...XGETBV, ...store_eax(OUT + 80), ...store_edx(OUT + 84),
        ...xsetbv(3), ...mov_ecx(0), ...XGETBV, ...store_eax(OUT + 88), ...cpuid(0xD, 0, OUT + 96), ...xsetbv(1), ...NO_OSXSAVE], undefined, machines, (vm, run) => {
        assert.equal(word(vm, OUT + 8) >>> 26 & 3, 1, `CPUID.1:ECX: XSAVE, without OSXSAVE (${run})`);
        assert.equal(word(vm, OUT + 24) >>> 26 & 3, 3, `CPUID.1:ECX: XSAVE, OSXSAVE (${run})`);
        assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + 32 + i)), [3, 576, 576, 0], `CPUID.0xD.0 (${run})`);
        assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + 48 + i)), [0, 0, 0, 0], `CPUID.0xD.1 (${run})`);
        assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + 64 + i)), [0, 0, 0, 0], `CPUID.0xD.2 (${run})`);
        assert.deepEqual([word(vm, OUT + 80), word(vm, OUT + 84), word(vm, OUT + 88)], [1, 0, 3], `XGETBV: XCR0 1 at reset, 3 after XSETBV (${run})`);
        assert.equal(word(vm, OUT + 100), 576, `CPUID.0xD.0:EBX with XCR0 3 (${run})`);
    });
    // without the XSAVEOPT and XSAVEC features, 0F AE /6 and 0F C7 /4 on memory are #UD
    await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA), ...ALL], XSAVEOPT, 6, { epilogue: NO_OSXSAVE, label: "XSAVEOPT without its feature" });
    await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA), ...ALL], XSAVEC, 6, { epilogue: NO_OSXSAVE, label: "XSAVEC without its feature" });
    // without XSAVES: XSAVES and XRSTORS #UD (IA32_XSS: an absent MSR, which
    // outside long mode reads 0 and ignores writes as all of them here;
    // tests/x64/xsave.mjs has its #GP in long mode)
    await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA), ...ALL], XSAVES, 6, { epilogue: NO_OSXSAVE, label: "XSAVES without its feature" });
    await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA), ...ALL], XRSTORS, 6, { epilogue: NO_OSXSAVE, label: "XRSTORS without its feature" });
    count += 13;
    // XSETBV's checks: XCR0 only, x87 always, supported bits only; XGETBV
    // of XCR 1 needs XGETBV1; no mandatory prefix; LOCK
    for(const [ecx, value] of [[0, 0], [0, 2], [0, 7], [0, 5], [1, 3], [0, 0x100003]])
    {
        await expect_fault(machines, [...OSXSAVE, ...mov_ecx(ecx), ...mov_eax(value), ...mov_edx(0)], XSETBV, 13,
            { epilogue: NO_OSXSAVE, label: `XSETBV ${ecx}, ${value.toString(16)}` });
    }
    await expect_fault(machines, [...OSXSAVE, ...mov_ecx(1)], XGETBV, 13, { epilogue: NO_OSXSAVE, label: "XGETBV 1" });
    for(const prefix of [0x66, 0xF2, 0xF3, 0xF0])
    {
        await expect_fault(machines, [...OSXSAVE, ...mov_ecx(0)], [prefix, ...XGETBV], 6, { epilogue: NO_OSXSAVE, label: `${prefix.toString(16)} XGETBV` });
        await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA)], [prefix, ...XSAVE], 6, { epilogue: NO_OSXSAVE, label: `${prefix.toString(16)} XSAVE` });
    }
    count += 15;
    console.log("PASS: CPUID 1 and 0xD, XGETBV/XSETBV and their #GP/#UD cases with XSAVE (XCR0 x87|SSE)");

    // XSAVE and XRSTOR: a round trip of x87, MMX/XMM and MXCSR state; a
    // partial save; init on restore; FXSAVE's layout matches XSAVE's
    const constants = new Float64Array([1.5, -2.25]);
    const xmm = Uint8Array.from({ length: 32 }, (_, i) => i * 7 + 3);
    const setup = vm => {
        vm.write_memory(new Uint8Array(constants.buffer), DATA);
        vm.write_memory(xmm, DATA + 16);
        vm.write_memory(Uint8Array.from(u32(0x1FA0)), DATA + 48);
        vm.write_memory(Uint8Array.from(u32(0x1F80)), DATA + 52);
        prepare(vm, AREA);
        prepare(vm, AREA2, 1);
        prepare(vm, AREA3);
        vm.write_memory(Uint8Array.from(u32(0x1F80)), AREA3 + 24);
        fill(vm, AREA3 + 160, 16, 0x55);
        prepare(vm, AREA + 0x800);
    };
    const state = [...FNINIT, ...fld(DATA), ...fld(DATA + 8), ...movups_load(0, DATA + 16), ...movups_load(7, DATA + 32), ...ldmxcsr(DATA + 48)];
    await run_all([...OSXSAVE, ...xsetbv(3), ...state,
        ...mov_ebx(AREA), ...ALL, ...XSAVE,
        ...mov_ebx(AREA + 0x800), ...FXSAVE,
        ...mov_ebx(AREA2), ...mov_eax(2), ...mov_edx(0), ...XSAVE,
        ...FNINIT, ...XORPS_0_7, ...ldmxcsr(DATA + 52),
        ...mov_ebx(AREA), ...ALL, ...XRSTOR,
        ...fstp(OUT), ...fstp(OUT + 8), ...movups_store(0, OUT + 16), ...movups_store(7, OUT + 32), ...stmxcsr(OUT + 48),
        // init: XSTATE_BV 0, MXCSR from memory (RFBM[1])
        ...mov_ebx(AREA3), ...mov_eax(3), ...mov_edx(0), ...XRSTOR,
        ...fnstcw(OUT + 64), ...movups_store(0, OUT + 80), ...stmxcsr(OUT + 96),
        ...xsetbv(1), ...NO_OSXSAVE], setup, machines, (vm, run) => {
        no_fault("XSAVE/XRSTOR round trip")(vm, run);
        assert.deepEqual(new Float64Array(bytes(vm, OUT, 16).buffer), Float64Array.of(-2.25, 1.5), "x87 after XRSTOR");
        assert.deepEqual(bytes(vm, OUT + 16, 32), xmm, "XMM0, XMM7 after XRSTOR");
        assert.equal(word(vm, OUT + 48), 0x1FA0, "MXCSR after XRSTOR");
        const area = bytes(vm, AREA, 832);
        const view = new DataView(area.buffer);
        assert.deepEqual([view.getUint16(0, true), view.getUint32(24, true), view.getUint32(28, true)], [0x37F, 0x1FA0, 0xFFFF], "FCW, MXCSR, MXCSR_MASK");
        assert.equal(area[4], 0xC0, "abridged FTW: two registers in use");
        assert.deepEqual(area.subarray(160, 176), xmm.subarray(0, 16), "XMM0 at 160");
        assert.deepEqual(area.subarray(272, 288), xmm.subarray(16, 32), "XMM7 at 272");
        assert.ok(area.subarray(288, 512).every(b => b === 0xCC), "bytes 288-511 untouched outside 64-bit mode");
        assert.deepEqual([view.getUint32(512, true), view.getUint32(516, true)], [3, 0], "XSTATE_BV: x87 and SSE in use");
        assert.ok(area.subarray(520, 576).every(b => b === 0) && area.subarray(576).every(b => b === 0xCC), "only XSTATE_BV of the header, no YMM");
        assert.ok([5, 14, 15, 22, 23, 42, 43, 47].every(i => area[i] === 0xCC), "reserved bytes are not stored");
        // FXSAVE: the same legacy region
        const fx = bytes(vm, AREA + 0x800, 512);
        for(const [from, to] of [[0, 5], [6, 14], [16, 22], [24, 32], [32, 42], [160, 288]])
        {
            assert.deepEqual(fx.subarray(from, to), area.subarray(from, to), `FXSAVE bytes ${from}-${to}`);
        }
        assert.ok(fx.subarray(288, 512).every(b => b === 0xCC), "FXSAVE leaves 288-511 alone outside 64-bit mode");
        // the partial save: SSE only (MXCSR with it), XSTATE_BV bit 0 kept
        const partial = bytes(vm, AREA2, 576);
        assert.ok(partial.subarray(0, 24).every(b => b === 0xCC) && partial.subarray(32, 160).every(b => b === 0xCC), "x87 not stored");
        assert.equal(new DataView(partial.buffer).getUint32(24, true), 0x1FA0, "MXCSR stored with SSE");
        assert.deepEqual(partial.subarray(160, 176), xmm.subarray(0, 16));
        assert.equal(new DataView(partial.buffer).getUint32(512, true), 3, "XSTATE_BV: old bit 0, bit 1 in use");
        // init: FNINIT's x87 state, XMM zero, MXCSR loaded
        assert.equal(word(vm, OUT + 64) & 0xFFFF, 0x37F, "x87 init: FCW");
        assert.deepEqual(bytes(vm, OUT + 80, 16), new Uint8Array(16), "SSE init: XMM0 0");
        assert.equal(word(vm, OUT + 96), 0x1F80, "MXCSR loaded although SSE is initialized");
    });
    count += 20;
    console.log("PASS: XSAVE/XRSTOR round trip, partial save, init on restore, FXSAVE layout (XCR0 3)");

    // Faults: #UD without CR4.OSXSAVE before #NM; #NM with CR0.TS; #GP for
    // misalignment, the header and MXCSR; page faults before any byte moves
    await expect_fault(machines, [...SET_TS, ...mov_ebx(AREA)], XSAVE, 6, { epilogue: CLTS, label: "XSAVE without OSXSAVE, TS set" });
    await expect_fault(machines, [...OSXSAVE, ...SET_TS, ...mov_ebx(AREA), ...ALL], XSAVE, 7, { epilogue: [...CLTS, ...NO_OSXSAVE], label: "XSAVE with TS" });
    await expect_fault(machines, [...OSXSAVE, ...SET_TS, ...mov_ebx(AREA), ...ALL], XRSTOR, 7, { epilogue: [...CLTS, ...NO_OSXSAVE], label: "XRSTOR with TS" });
    for(const [offset, instruction, label] of [[32, XSAVE, "XSAVE"], [16, XRSTOR, "XRSTOR"], [8, FXSAVE, "FXSAVE"], [4, FXRSTOR, "FXRSTOR"]])
    {
        await expect_fault(machines, [...OSXSAVE, ...mov_ebx(AREA + offset), ...ALL], instruction, 13,
            { epilogue: NO_OSXSAVE, label: label + " misaligned", before: vm => prepare(vm, AREA) });
    }
    for(const [patch, label] of [[[520 + 7, 0x80], "XCOMP_BV[63] without XSAVEC"], [[512, 4 | 3], "XSTATE_BV bit outside XCR0"],
        [[530, 1], "header bytes 23:8"], [[26, 1], "MXCSR reserved bits"]])
    {
        await expect_fault(machines, [...OSXSAVE, ...xsetbv(3), ...mov_ebx(AREA), ...ALL], XRSTOR, 13, {
            epilogue: NO_OSXSAVE, label,
            before: vm => {
                prepare(vm, AREA, 3);
                vm.write_memory(Uint8Array.from(u32(0x1F80)), AREA + 24);
                vm.write_memory(Uint8Array.of(patch[1]), AREA + patch[0]);
            },
        });
    }
    await expect_fault(machines, [...mov_ebx(CROSSING - 0x1000 + 0x40)], FXRSTOR, 13, {
        label: "FXRSTOR with MXCSR reserved bits",
        before: vm => vm.write_memory(Uint8Array.from(u32(0x10000)), CROSSING - 0x1000 + 0x40 + 24),
    });
    // the header on an absent page: nothing stored; XRSTOR reads it first
    for(const [instruction, label] of [[XSAVE, "XSAVE"], [XRSTOR, "XRSTOR"]])
    {
        const base = ABSENT - 512;
        await expect_fault(machines, [...OSXSAVE, ...xsetbv(3), ...mov_ebx(base), ...ALL], instruction, 14, {
            epilogue: NO_OSXSAVE, cr2: ABSENT, label: label + " header on an absent page",
            before: vm => { fill(vm, base, 512, 0xCC); pages(vm, ABSENT, false); },
            check: (vm, run) => assert.ok(bytes(vm, base, 512).every(b => b === 0xCC), `${label}: no byte stored before the page fault (${run})`),
        });
        for(const vm of machines) pages(vm, ABSENT, true);
    }
    // components not asked for are not touched: YMM's place on an absent page
    await run_all([...OSXSAVE, ...xsetbv(3), ...mov_ebx(CROSSING), ...ALL, ...XSAVE, ...XRSTOR, ...xsetbv(1), ...NO_OSXSAVE], vm => {
        prepare(vm, CROSSING, 3);
        vm.write_memory(Uint8Array.from(u32(0x1F80)), CROSSING + 24);
        pages(vm, CROSSING + 576, false);
    }, machines, no_fault("XSAVE/XRSTOR without AVX state next to an absent page"));
    for(const vm of machines) pages(vm, CROSSING + 576, true);
    count += 14;
    console.log("PASS: #UD before #NM, #NM with CR0.TS, #GP for alignment, the header and MXCSR, #PF before any byte moves, no access beyond the components");
    for(const vm of machines) await vm.destroy();
    machines.length = 0;

    // With AVX: XCR0 can enable YMM state, which XRSTOR loads and XSAVE stores
    // (no AVX instruction has semantics yet); CPUID's sizes follow XCR0
    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"], cpu_features_unreleased: true }));
    const ymm = Uint8Array.from({ length: 128 }, (_, i) => i * 13 + 1);
    await run_all([...OSXSAVE, ...cpuid(0xD, 0, OUT), ...cpuid(0xD, 2, OUT + 16), ...xsetbv(7), ...cpuid(0xD, 0, OUT + 32),
        ...mov_ebx(AREA), ...ALL, ...XRSTOR, ...mov_ebx(AREA2), ...ALL, ...XSAVE,
        ...mov_ebx(CROSSING), ...ALL, ...XSAVE,
        ...xsetbv(1), ...NO_OSXSAVE], vm => {
        prepare(vm, AREA, 4);
        vm.write_memory(Uint8Array.from(u32(0x1F80)), AREA + 24);
        vm.write_memory(ymm, AREA + 576);
        prepare(vm, AREA2);
        prepare(vm, CROSSING);
    }, machines, (vm, run) => {
        no_fault("YMM round trip")(vm, run);
        assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + i)), [7, 576, 832, 0], "CPUID.0xD.0 with AVX, XCR0 1");
        assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + 16 + i)), [256, 576, 0, 0], "CPUID.0xD.2");
        assert.equal(word(vm, OUT + 36), 832, "CPUID.0xD.0:EBX with XCR0 7");
        const area = bytes(vm, AREA2, 832);
        assert.deepEqual(area.subarray(576, 704), ymm, "YMM0_H-YMM7_H stored");
        assert.ok(area.subarray(704).every(b => b === 0xCC), "YMM8_H-YMM15_H only in 64-bit mode");
        assert.equal(new DataView(area.buffer).getUint32(512, true), 4, "XSTATE_BV: x87 and SSE initial (XRSTOR initialized them), AVX in use");
    });
    await expect_fault(machines, [...OSXSAVE, ...mov_ecx(0), ...mov_eax(5), ...mov_edx(0)], XSETBV, 13, { epilogue: NO_OSXSAVE, label: "XSETBV YMM without SSE" });
    // the YMM component on an absent page: nothing stored on the first page
    await expect_fault(machines, [...OSXSAVE, ...xsetbv(7), ...mov_ebx(CROSSING), ...ALL], XSAVE, 14, {
        epilogue: [...xsetbv(1), ...NO_OSXSAVE], cr2: CROSSING + 576, label: "XSAVE with YMM on an absent page",
        before: vm => { prepare(vm, CROSSING); pages(vm, CROSSING + 576, false); },
        check: (vm, run) => assert.ok(bytes(vm, CROSSING, 512).every(b => b === 0xCC), `no legacy-region byte stored before the page fault (${run})`),
    });
    for(const vm of machines) pages(vm, CROSSING + 576, true);
    count += 8;
    console.log("PASS: with AVX, XCR0 enables YMM state; CPUID 0xD sizes follow XCR0; XSAVE stores YMM_Hi128 or faults first");
    for(const vm of machines) await vm.destroy();
    machines.length = 0;

    // P9: XSAVEOPT, XGETBV(1), XSAVEC, XSAVES and XRSTORS. The rounds of
    // these programs keep XCR0 7 and CR4.OSXSAVE (the preamble sets them
    // alike each round): compiled code depends on them, and a program
    // changing them every round would run interpreted on the compiled arms.
    machines.push(...await create_machines({ cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "XSAVEOPT", "XGETBV1", "XSAVEC", "XSAVES"], cpu_features_unreleased: true }));
    preamble = [...CLTS, ...OSXSAVE, ...xsetbv(7)];
    {
        // (every component in its initial configuration: XRSTOR of an area whose
        // XSTATE_BV is 0, MXCSR 1F80H; FNINIT would keep ST0-ST7's contents)
        const upper = Uint8Array.from({ length: 16 }, (_, i) => 0x90 + i), INIT = AREA2 + 0x800;
        const initial = [...mov_ebx(INIT), ...ALL, ...XRSTOR];
        const state = [...fld(DATA), ...fld(DATA + 8), ...movups_load(0, DATA + 16), ...movups_load(7, DATA + 32), ...ldmxcsr(DATA + 48), ...vinsertf128_6(DATA + 64)];
        // the state's x87 registers, XMM0, XMM7, MXCSR and YMM6_H at `out`
        const store_state = out => [...fstp(out), ...fstp(out + 8), ...movups_store(0, out + 16), ...movups_store(7, out + 32), ...stmxcsr(out + 48),
            0xC4, 0xE3, 0x7D, 0x19, 0x35, ...u32(out + 52), 1];                // vextractf128 [out + 52], ymm6, 1
        const check_state = (vm, out, what) => {
            assert.deepEqual(new Float64Array(bytes(vm, out, 16).buffer), Float64Array.of(-2.25, 1.5), `${what}: x87`);
            assert.deepEqual([bytes(vm, out + 16, 32), word(vm, out + 48)], [xmm, 0x1FA0], `${what}: XMM0, XMM7, MXCSR`);
            assert.deepEqual(bytes(vm, out + 52, 16), upper, `${what}: YMM6_H`);
        };
        const data = vm => {
            vm.write_memory(new Uint8Array(new Float64Array([1.5, -2.25]).buffer), DATA);
            vm.write_memory(xmm, DATA + 16);
            vm.write_memory(Uint8Array.from(u32(0x1FA0)), DATA + 48);
            vm.write_memory(Uint8Array.from(u32(0x1F80)), DATA + 52);
            vm.write_memory(upper, DATA + 64);
            prepare(vm, INIT);
            vm.write_memory(Uint8Array.from(u32(0x1F80)), INIT + 24);
        };
        const header = (vm, a) => [word(vm, a + 512), word(vm, a + 516), word(vm, a + 520), word(vm, a + 524)];
        // compacted areas to restore (XSTATE_BV, XCOMP_BV), their legacy region
        // and YMM_Hi128 0CCH
        const compacted = (vm, a, xstate_bv, xcomp_bv) => {
            fill(vm, a, 832, 0xCC);
            vm.write_memory(new Uint8Array(64), a + 512);
            vm.write_memory(Uint8Array.from([...u32(xstate_bv), 0, 0, 0, 0, ...u32(xcomp_bv), 0, 0, 0, 0x80]), a + 512);
        };

        // CPUID.0xD.1 and XGETBV(1), XCR0 AND XINUSE: here exactly the
        // components not in their initial configuration (the SDM lets XINUSE
        // be 1 for one that is; MXCSR is not part of it)
        await run_all([...cpuid(0xD, 1, OUT), ...initial, ...xgetbv(1, OUT + 16),
            ...ldmxcsr(DATA + 48), ...xgetbv(1, OUT + 24), ...fld(DATA), ...xgetbv(1, OUT + 32), ...movups_load(7, DATA + 16), ...xgetbv(1, OUT + 40),
            ...vinsertf128_6(DATA + 64), ...xgetbv(1, OUT + 48), ...xsetbv(3), ...xgetbv(1, OUT + 56), ...cpuid(0xD, 1, OUT + 64), ...xsetbv(7)], data, machines, (vm, run) => {
            no_fault("XGETBV(1), CPUID.0xD.1")(vm, run);
            assert.deepEqual([0, 4, 8, 12].map(i => word(vm, OUT + i)), [15, 832, 0, 0],
                `CPUID.0xD.1 with XCR0 7: XSAVEOPT, XSAVEC, XGETBV1, XSAVES; the compacted size; IA32_XSS bits (${run})`);
            assert.equal(word(vm, OUT + 68), 576, `CPUID.0xD.1:EBX with XCR0 3 (${run})`);
            assert.deepEqual([16, 24, 32, 40, 48, 56].map(o => [word(vm, OUT + o), word(vm, OUT + o + 4)]), [[0, 0], [0, 0], [1, 0], [3, 0], [7, 0], [3, 0]],
                `XGETBV(1): initial, MXCSR alone, x87, XMM7, YMM6_H, XCR0 3 (${run})`);
        });
        count += 4;

        // XSAVEOPT stores what XSAVE does but for the components in their
        // initial configuration (the init optimization; there is no modified
        // one), and MXCSR with RFBM[1] or RFBM[2] whatever XINUSE says
        await run_all([...initial, ...state,
            ...mov_ebx(AREA), ...ALL, ...XSAVE, ...mov_ebx(AREA2), ...ALL, ...XSAVEOPT,
            // all initial but MXCSR: only MXCSR (with MXCSR_MASK), XSTATE_BV 0
            ...initial, ...ldmxcsr(DATA + 48), ...mov_ebx(AREA3), ...ALL, ...XSAVEOPT,
            // x87 in use, RFBM SSE: MXCSR only, XSTATE_BV's other bits kept
            ...fld(DATA), ...mov_ebx(AREA + 0x800), ...mov_eax(2), ...mov_edx(0), ...XSAVEOPT,
            // XRSTOR of the all-initial area: everything initialized, MXCSR loaded
            ...movups_load(7, DATA + 16), ...vinsertf128_6(DATA + 64), ...mov_ebx(AREA3), ...ALL, ...XRSTOR,
            ...movups_store(7, OUT + 64), ...stmxcsr(OUT + 80), ...xgetbv(1, OUT + 88)], vm => {
            data(vm);
            prepare(vm, AREA);
            prepare(vm, AREA2);
            prepare(vm, AREA3, 7);
            prepare(vm, AREA + 0x800, 5);
        }, machines, (vm, run) => {
            no_fault("XSAVEOPT")(vm, run);
            assert.deepEqual(bytes(vm, AREA2, 832), bytes(vm, AREA, 832), `XSAVEOPT with every component in use: XSAVE's area (${run})`);
            const init = bytes(vm, AREA3, 832), view = new DataView(init.buffer);
            assert.ok(init.subarray(0, 24).every(b => b === 0xCC) && init.subarray(32, 288).every(b => b === 0xCC) && init.subarray(576).every(b => b === 0xCC),
                `XSAVEOPT stores no component in its initial configuration (${run})`);
            assert.deepEqual([view.getUint32(24, true), view.getUint32(28, true), view.getUint32(512, true), view.getUint32(516, true)], [0x1FA0, 0xFFFF, 0, 0],
                `XSAVEOPT: MXCSR, MXCSR_MASK, XSTATE_BV 0 (${run})`);
            const partial = bytes(vm, AREA + 0x800, 832), partial_view = new DataView(partial.buffer);
            assert.ok(partial.subarray(0, 24).every(b => b === 0xCC) && partial.subarray(32, 288).every(b => b === 0xCC),
                `XSAVEOPT of SSE alone: neither x87 (not requested) nor XMM (initial) (${run})`);
            assert.deepEqual([partial_view.getUint32(24, true), partial_view.getUint32(512, true)], [0x1FA0, 5], `XSAVEOPT of SSE alone: MXCSR, XSTATE_BV bits 0 and 2 kept (${run})`);
            assert.deepEqual([bytes(vm, OUT + 64, 16), word(vm, OUT + 80), word(vm, OUT + 88)], [new Uint8Array(16), 0x1FA0, 0],
                `XRSTOR of XSAVEOPT's all-initial area (${run})`);
        });
        count += 6;

        // XSAVEC, the compacted form (XCOMP_BV: RFBM with bit 63; YMM_Hi128 at
        // 576 as the only extended component), and XRSTOR of it. XSAVEC stores
        // the components in use, SSE state also when MXCSR is not 1F80H, MXCSR
        // only with SSE state, and no header byte but XSTATE_BV and XCOMP_BV.
        // The compacted XRSTOR loads MXCSR with SSE state only and initializes
        // it to 1F80H with it.
        const C_ALL = AREA, S_ALL = AREA2, C_MXCSR = AREA3, C_NONE = AREA + 0x800, C_YMM = AREA3 + 0x800;
        // (all initial with MXCSR 1FA0H in memory: SSE initialized, MXCSR
        // 1F80H; YMM alone with MXCSR 1FA0H: RFBM 4 keeps MXCSR)
        const R_INIT = 0x207000, R_YMM = 0x207400;
        const header_junk = (vm, a) => vm.write_memory(new Uint8Array(48).fill(0xEE), a + 528);
        await run_all([...initial, ...state,
            ...mov_ebx(C_ALL), ...ALL, ...XSAVEC, ...mov_ebx(S_ALL), ...ALL, ...XSAVE,
            ...mov_ebx(C_YMM), ...mov_eax(4), ...mov_edx(0), ...XSAVEC,
            ...initial, ...ldmxcsr(DATA + 48), ...mov_ebx(C_MXCSR), ...ALL, ...XSAVEC,
            ...initial, ...mov_ebx(C_NONE), ...ALL, ...XSAVEC,
            // the round trip: XRSTOR of XSAVEC's area
            ...initial, ...mov_ebx(C_ALL), ...ALL, ...XRSTOR, ...store_state(OUT + 32),
            // all initial from the compacted form: MXCSR 1F80H, not memory's
            ...state, ...mov_ebx(R_INIT), ...ALL, ...XRSTOR, ...stmxcsr(OUT + 112), ...movups_store(0, OUT + 116),
            // YMM alone (RFBM 4): MXCSR kept
            ...ldmxcsr(DATA + 52), ...mov_ebx(R_YMM), ...mov_eax(4), ...mov_edx(0), ...XRSTOR, ...stmxcsr(OUT + 132)], vm => {
            data(vm);
            for(const a of [C_ALL, S_ALL, C_MXCSR, C_NONE, C_YMM]) prepare(vm, a);
            for(const a of [C_MXCSR, C_NONE, C_YMM]) header_junk(vm, a);
            compacted(vm, R_INIT, 0, 7);
            vm.write_memory(Uint8Array.from(u32(0x1FA0)), R_INIT + 24);
            compacted(vm, R_YMM, 6, 7);
            vm.write_memory(Uint8Array.from(u32(0x1FA0)), R_YMM + 24);
        }, machines, (vm, run) => {
            no_fault("XSAVEC, compacted XRSTOR")(vm, run);
            const all = bytes(vm, C_ALL, 832), standard = bytes(vm, S_ALL, 832);
            assert.deepEqual([all.subarray(0, 512), all.subarray(576)], [standard.subarray(0, 512), standard.subarray(576)],
                `XSAVEC with every component in use: XSAVE's legacy region and YMM_Hi128 (${run})`);
            assert.deepEqual(header(vm, C_ALL), [7, 0, 7, 0x80000000], `XSAVEC: XSTATE_BV, XCOMP_BV (${run})`);
            const ymm_only = bytes(vm, C_YMM, 832);
            assert.ok(ymm_only.subarray(0, 512).every(b => b === 0xCC), `XSAVEC of YMM alone: no legacy-region byte, not MXCSR (${run})`);
            assert.deepEqual(ymm_only.subarray(576 + 96, 576 + 112), standard.subarray(576 + 96, 576 + 112), `XSAVEC of YMM alone: YMM6_H (${run})`);
            assert.deepEqual(header(vm, C_YMM), [4, 0, 4, 0x80000000], `XSAVEC of YMM alone: XSTATE_BV, XCOMP_BV (${run})`);
            assert.ok(ymm_only.subarray(528, 576).every(b => b === 0xEE), `XSAVEC writes no header byte but XSTATE_BV and XCOMP_BV (${run})`);
            const mxcsr_only = bytes(vm, C_MXCSR, 832), mxcsr_view = new DataView(mxcsr_only.buffer);
            assert.ok(mxcsr_only.subarray(0, 24).every(b => b === 0xCC) && mxcsr_only.subarray(32, 160).every(b => b === 0xCC), `XSAVEC: x87 initial, not stored (${run})`);
            assert.deepEqual([mxcsr_view.getUint32(24, true), mxcsr_view.getUint32(28, true)], [0x1FA0, 0xFFFF], `XSAVEC: SSE state for MXCSR 1FA0H (${run})`);
            assert.ok(mxcsr_only.subarray(160, 288).every(b => b === 0), `XSAVEC: SSE state stored, XMM0-7 zero (${run})`);
            assert.ok(mxcsr_only.subarray(288, 512).every(b => b === 0xCC) && mxcsr_only.subarray(576).every(b => b === 0xCC), `XSAVEC: YMM initial, not stored (${run})`);
            assert.deepEqual(header(vm, C_MXCSR), [2, 0, 7, 0x80000000], `XSAVEC: XSTATE_BV SSE (${run})`);
            const none = bytes(vm, C_NONE, 832);
            assert.ok(none.subarray(0, 512).every(b => b === 0xCC) && none.subarray(576).every(b => b === 0xCC), `XSAVEC with every component initial and MXCSR 1F80H: nothing stored (${run})`);
            assert.deepEqual(header(vm, C_NONE), [0, 0, 7, 0x80000000], `XSAVEC with nothing in use: XSTATE_BV 0 (${run})`);
            check_state(vm, OUT + 32, `compacted XRSTOR (${run})`);
            assert.deepEqual([word(vm, OUT + 112), bytes(vm, OUT + 116, 16)], [0x1F80, new Uint8Array(16)], `compacted XRSTOR initializing SSE state: MXCSR 1F80H, XMM0 0 (${run})`);
            assert.equal(word(vm, OUT + 132), 0x1F80, `compacted XRSTOR without RFBM[1]: MXCSR kept (${run})`);
        });
        count += 15;
        // MXCSR's reserved bits: #GP(0) only when SSE state is loaded
        await run_all([...mov_ebx(R_INIT), ...ALL, ...XRSTOR, ...stmxcsr(OUT)], vm => {
            compacted(vm, R_INIT, 0, 7);
            vm.write_memory(Uint8Array.from(u32(0x10000)), R_INIT + 24);
        }, machines, (vm, run) => {
            no_fault("compacted XRSTOR, MXCSR reserved bits without SSE state")(vm, run);
            assert.equal(word(vm, OUT), 0x1F80, `compacted XRSTOR initializes MXCSR, ignoring memory's (${run})`);
        });
        count += 2;

        // XSAVES: XSAVEC's stores and header with RFBM (XCR0 OR IA32_XSS) AND
        // EDX:EAX at CPL 0; XRSTORS of its area; XRSTOR of it (compacted,
        // within XCR0); IA32_XSS (no supervisor state component) reads 0 and
        // takes 0
        const S_XSAVES = 0x207800, RDMSR = [0x0F, 0x32], WRMSR = [0x0F, 0x30];
        await run_all([...initial, ...state,
            ...mov_ebx(C_ALL), ...ALL, ...XSAVEC, ...mov_ebx(S_XSAVES), ...ALL, ...XSAVES,
            ...initial, ...mov_ebx(S_XSAVES), ...ALL, ...XRSTORS, ...store_state(OUT + 32),
            ...initial, ...mov_ebx(S_XSAVES), ...ALL, ...XRSTOR, ...store_state(OUT + 112),
            ...mov_ecx(0xDA0), ...RDMSR, ...store_eax(OUT), ...store_edx(OUT + 4),
            ...mov_ecx(0xDA0), ...mov_eax(0), ...mov_edx(0), ...WRMSR], vm => {
            data(vm);
            prepare(vm, C_ALL);
            prepare(vm, S_XSAVES);
            vm.write_memory(new Uint8Array(8).fill(0xEE), OUT);
        }, machines, (vm, run) => {
            no_fault("XSAVES, XRSTORS, IA32_XSS")(vm, run);
            assert.deepEqual(bytes(vm, S_XSAVES, 832), bytes(vm, C_ALL, 832), `XSAVES: XSAVEC's area (${run})`);
            check_state(vm, OUT + 32, `XRSTORS of XSAVES's area (${run})`);
            check_state(vm, OUT + 112, `XRSTOR of XSAVES's area (${run})`);
            assert.deepEqual([word(vm, OUT), word(vm, OUT + 4)], [0, 0], `RDMSR IA32_XSS (${run})`);
        });
        count += 5;

        // the faults: #UD without CR4.OSXSAVE (before #NM), #NM with CR0.TS,
        // #GP(0) misaligned, 66, F2 and F3 #UD, a register operand #UD
        // (XSAVEC, XSAVES, XRSTORS), the header on an absent page #PF before
        // any byte moves
        const FORMS = [[XSAVEOPT, "XSAVEOPT"], [XSAVEC, "XSAVEC"], [XSAVES, "XSAVES"], [XRSTORS, "XRSTORS"]];
        for(const [instruction, label] of FORMS)
        {
            await expect_fault(machines, [...NO_OSXSAVE, ...SET_TS, ...mov_ebx(AREA)], instruction, 6, { epilogue: CLTS, label: label + " without OSXSAVE, TS set" });
            await expect_fault(machines, [...SET_TS, ...mov_ebx(AREA), ...ALL], instruction, 7, { epilogue: CLTS, label: label + " with TS" });
            await expect_fault(machines, [...mov_ebx(AREA + 16), ...ALL], instruction, 13, { label: label + " misaligned" });
            for(const prefix of [0x66, 0xF2, 0xF3])
            {
                await expect_fault(machines, [...mov_ebx(AREA), ...ALL], [prefix, ...instruction], 6, { label: `${prefix.toString(16)} ${label}` });
            }
            if(instruction[1] === 0xC7)
            {
                await expect_fault(machines, ALL, [0x0F, 0xC7, 0xC3 | instruction[2] & 0x38], 6, { label: label + " with a register operand" });
            }
            const base = ABSENT - 512, restore = instruction === XRSTORS;
            await expect_fault(machines, [...fld(DATA), ...mov_ebx(base), ...ALL], instruction, 14, {
                epilogue: FNINIT, cr2: ABSENT, label: label + " header on an absent page",
                before: vm => {
                    fill(vm, base, 512, 0xCC);
                    pages(vm, ABSENT, false);
                    vm.write_memory(new Uint8Array(new Float64Array([1.5]).buffer), DATA);
                },
                check: (vm, run) => assert.ok(restore || bytes(vm, base, 512).every(b => b === 0xCC), `${label}: no byte stored before the page fault (${run})`),
            });
            for(const vm of machines) pages(vm, ABSENT, true);
        }
        count += 4 * 8 - 1;
        // the header's #GP(0) cases: the compacted XRSTOR (XCR0 3 or 7), and
        // XRSTORS (the standard form, XCOMP_BV beyond XCR0 | IA32_XSS)
        for(const [instruction, xcr0, xstate_bv, xcomp_bv, patch, mxcsr, label] of [
            [XRSTOR, 3, 1, 7, null, 0x1F80, "compacted XRSTOR: XCOMP_BV beyond XCR0"], [XRSTOR, 7, 4, 3, null, 0x1F80, "compacted XRSTOR: XSTATE_BV beyond XCOMP_BV"],
            [XRSTOR, 7, 1, 7, 528, 0x1F80, "compacted XRSTOR: header byte 16"], [XRSTOR, 7, 1, 7, 575, 0x1F80, "compacted XRSTOR: header byte 63"],
            [XRSTOR, 7, 2, 7, null, 0x10000, "compacted XRSTOR: MXCSR reserved bits with SSE state"],
            [XRSTORS, 7, 1, null, null, 0x1F80, "XRSTORS of the standard form"], [XRSTORS, 7, 1, 0xF, null, 0x1F80, "XRSTORS: XCOMP_BV beyond XCR0 | IA32_XSS"],
            [XRSTORS, 7, 4, 3, null, 0x1F80, "XRSTORS: XSTATE_BV beyond XCOMP_BV"], [XRSTORS, 7, 1, 7, 560, 0x1F80, "XRSTORS: header byte 48"]])
        {
            await expect_fault(machines, [...xsetbv(xcr0), ...mov_ebx(R_INIT), ...ALL], instruction, 13, {
                epilogue: xsetbv(7), label,
                before: vm => {
                    if(xcomp_bv === null) prepare(vm, R_INIT, xstate_bv);
                    else compacted(vm, R_INIT, xstate_bv, xcomp_bv);
                    vm.write_memory(Uint8Array.from(u32(mxcsr)), R_INIT + 24);
                    if(patch !== null) vm.write_memory(Uint8Array.of(1), R_INIT + patch);
                },
            });
        }
        count += 9;
        // IA32_XSS takes no supported bit: #GP(0)
        for(const [eax, edx] of [[1, 0], [0x100, 0], [0, 1]])
        {
            await expect_fault(machines, [...mov_ecx(0xDA0), ...mov_eax(eax), ...mov_edx(edx)], WRMSR, 13, { label: `WRMSR IA32_XSS ${edx}:${eax.toString(16)}` });
        }
        count += 3;
    }
    console.log("PASS: XSAVEOPT, XGETBV(1), XSAVEC and the compacted XRSTOR, XSAVES and XRSTORS with IA32_XSS (CPUID.0xD.1, stores, headers, MXCSR, faults)");
    console.log(`PASS: ${count} XSAVE feature set checks on ${COMPILED_ARMS.length + 1} arms`);
}
finally
{
    for(const vm of machines) await vm.destroy();
}
                                                                                                                                                                 source/v64/tests/smp/affinity_probe.asm                                                             0000644 0000000 0000000 00000004172 00000000000 015333  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; ELF32 Linux process: bind to argv[1] (CPU 0..7), verify getcpu before and
; after real arithmetic progress, then report one bounded completion record.
; No libc, compiler, scheduler affinity utility or guest build tools needed.
; nasm -f bin tests/smp/affinity_probe.asm -o build/smp/affinity_probe
bits 32
org 0x08048000

elf_header:
    db 0x7F, "ELF", 1, 1, 1, 0
    times 8 db 0
    dw 2, 3
    dd 1, start, program_header - $$, 0, 0
    dw 52, 32, 1, 0, 0, 0
program_header:
    dd 1, 0, $$, $$, file_end - $$, file_end - $$, 7, 0x1000

start:
    cmp dword [esp], 2
    jne failure
    mov eax, [esp + 8]
    cmp byte [eax + 1], 0
    jne failure
    movzx ecx, byte [eax]
    sub ecx, '0'
    cmp ecx, 7
    ja failure
    mov [requested_cpu], ecx
    mov eax, 1
    shl eax, cl
    mov [cpu_mask], eax
    add cl, '0'
    mov [id_digit], cl
    mov [cpu_digit], cl

    mov eax, 241                    ; sched_setaffinity(0, 4, &mask)
    xor ebx, ebx
    mov ecx, 4
    mov edx, cpu_mask
    int 0x80
    test eax, eax
    js failure
    call check_cpu

    xor eax, eax
    mov ecx, 100000
.progress:
    add eax, ecx
    dec ecx
    jnz .progress
    cmp eax, (100000 * 100001 / 2) & 0xFFFFFFFF
    jne failure
    call check_cpu

    mov ecx, message
    mov edx, message_end - message
    call write_stdout
    xor ebx, ebx
    jmp exit

check_cpu:
    mov eax, 318                    ; getcpu(&actual_cpu, NULL, NULL)
    mov ebx, actual_cpu
    xor ecx, ecx
    xor edx, edx
    int 0x80
    test eax, eax
    js failure
    mov eax, [actual_cpu]
    cmp eax, [requested_cpu]
    jne failure
    ret

failure:
    mov ecx, error_message
    mov edx, error_end - error_message
    call write_stdout
    mov ebx, 1
exit:
    mov eax, 1                      ; exit(status)
    int 0x80
    ud2
write_stdout:
    mov eax, 4                      ; write(1, message, length)
    mov ebx, 1
    int 0x80
    ret

align 4
requested_cpu: dd 0
actual_cpu: dd 0
cpu_mask: dd 0
message: db "C2_PROGRESS id="
id_digit: db "0"
    db " cpu="
cpu_digit: db "0"
    db " iterations=100000", 10
message_end:
error_message: db "C2_AFFINITY_FAIL", 10
error_end:
file_end:
                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/smp/ap_startup.asm                                                                 0000644 0000000 0000000 00000014372 00000000000 014520  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Guest-only AP startup and IPI fixture for ap_startup.mjs. The host writes
; commands to a mailbox; only this BSP sends INIT/SIPI and changes AP state.
; All APs enter the copied real-mode trampoline at CS:IP = vector*256:0.

bits 32
org 0x100000

MB_MAGIC equ 0x1BADB002
MB_FLAGS equ 0x10000
CONTROL equ 0x380000
RECORDS equ CONTROL + 0x100
LAPIC equ 0xFEE00000
IDT equ 0x200000
STACKS equ 0x300000

; Mailbox: cores, command, target, request, completed, vector, guest_error,
; stage, acknowledgement bitmap. Records: 64 bytes per APIC ID.
header:
    dd MB_MAGIC, MB_FLAGS, -(MB_MAGIC + MB_FLAGS)
    dd header, header, end, end, start

start:
    cli
    cld
    lgdt [gdtr]
    jmp 8:.protected
.protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, STACKS + 0x10000
    ; Mask the legacy PIC: every interrupt in this fixture must be an IPI.
    mov al, 0xFF
    out 0x21, al
    out 0xA1, al

    mov esi, trampoline
    mov edi, 0x8000
    mov ecx, trampoline_end - trampoline
    rep movsb
    mov esi, trampoline
    mov edi, 0x9000
    mov ecx, trampoline_end - trampoline
    rep movsb

    mov edi, IDT
    mov ecx, 256
    mov eax, unexpected_interrupt
    mov ebx, eax
    and eax, 0xFFFF
    or eax, 8 << 16
    and ebx, 0xFFFF0000
    or ebx, 0x8E00
.fill_idt:
    stosd
    xchg eax, ebx
    stosd
    xchg eax, ebx
    loop .fill_idt
    mov eax, fixed_ipi
    mov edi, IDT + 0x41 * 8
    call install_gate
%assign n 1
%rep 7
    mov eax, ack_%+n
    mov edi, IDT + (0x50 + n) * 8
    call install_gate
%assign n n+1
%endrep
    mov eax, spurious_interrupt
    mov edi, IDT + 0xFF * 8
    call install_gate
    lidt [idtr]
    mov dword [LAPIC + 0xF0], 0x1FF
    mov dword [CONTROL + 28], 1
    sti

.command_loop:
    mov eax, [CONTROL + 12]
    cmp eax, [CONTROL + 16]
    jne .command
    pause
    jmp .command_loop
.command:
    mov eax, [CONTROL + 4]
    cmp eax, 1
    je .start_all
    cmp eax, 2
    je .directed
    cmp eax, 3
    je .all
    cmp eax, 4
    je .excluding
    cmp eax, 5
    je .physical_broadcast
    cmp eax, 6
    je .restart
    cmp eax, 7
    je .sipi_only
    cmp eax, 8
    je .restart_two_sipis
    mov dword [CONTROL + 24], 1
    jmp .complete
.start_all:
    mov ebx, 1
.next_ap:
    mov ecx, ebx
    shl ecx, 24
    mov [LAPIC + 0x310], ecx
    mov dword [LAPIC + 0x300], 0xC500 ; INIT level assert
    mov dword [LAPIC + 0x300], 0x8500 ; INIT level deassert
    mov dword [LAPIC + 0x300], 0x608  ; SIPI vector 8
    inc ebx
    cmp ebx, [CONTROL]
    jb .next_ap
    jmp .complete
.directed:
    mov eax, [CONTROL + 8]
    shl eax, 24
    mov [LAPIC + 0x310], eax
    mov dword [LAPIC + 0x300], 0x41
    jmp .complete
.all:
    mov dword [LAPIC + 0x300], 0x80041
    jmp .complete
.excluding:
    mov dword [LAPIC + 0x300], 0xC0041
    jmp .complete
.physical_broadcast:
    mov dword [LAPIC + 0x310], 0xFF000000
    mov dword [LAPIC + 0x300], 0x41
    jmp .complete
.restart:
.restart_two_sipis:
    mov eax, [CONTROL + 8]
    shl eax, 24
    mov [LAPIC + 0x310], eax
    mov dword [LAPIC + 0x300], 0xC500
    mov dword [LAPIC + 0x300], 0x8500
    mov eax, [CONTROL + 20]
    or eax, 0x600
    mov [LAPIC + 0x300], eax
    cmp dword [CONTROL + 4], 8
    jne .complete
    ; Two SIPIs before a scheduler boundary: the first vector must win.
    xor eax, 1
    mov [LAPIC + 0x300], eax
    jmp .complete
.sipi_only:
    mov eax, [CONTROL + 8]
    shl eax, 24
    mov [LAPIC + 0x310], eax
    mov eax, [CONTROL + 20]
    or eax, 0x600
    mov [LAPIC + 0x300], eax
.complete:
    mov eax, [CONTROL + 12]
    mov [CONTROL + 16], eax
    jmp .command_loop

install_gate:
    mov [edi], ax
    mov word [edi + 2], 8
    mov word [edi + 4], 0x8E00
    shr eax, 16
    mov [edi + 6], ax
    ret

; Position-independent 16-bit code, copied to both 0x8000 and 0x9000.
bits 16
trampoline:
    cli
    mov eax, cr0
    mov edx, eax                    ; prove the AP arrived in real mode
    mov ax, cs
    movzx esi, ax                   ; original startup CS, preserved into PM
    lgdt [cs:trampoline_gdtr - trampoline]
    mov eax, cr0
    or eax, 1
    mov cr0, eax
    jmp dword 8:ap_start
trampoline_gdtr:
    dw gdt_end - gdt - 1
    dd gdt
trampoline_end:

bits 32
ap_start:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov ebx, [LAPIC + 0x20]
    shr ebx, 24
    lea esp, [ebx + 1]
    shl esp, 16
    add esp, STACKS
    mov edi, ebx
    shl edi, 6
    add edi, RECORDS
    inc dword [edi]                 ; boot count survives re-INIT
    mov [edi + 12], edx
    mov [edi + 16], esi
    shr esi, 8
    mov [edi + 8], esi
    mov [edi + 24], esp
    mov eax, 1
    push ebx
    cpuid
    shr ebx, 24
    mov [edi + 44], ebx
    pop ebx
    mov eax, cr0
    mov [edi + 48], eax
    xor eax, eax
    mov ax, cs
    mov [edi + 56], eax
    lidt [idtr]
    mov dword [LAPIC + 0xF0], 0x1FF
    mov dword [LAPIC + 0x80], 0
    lea ebp, [ebx + 0xC0010000]
    lea esi, [ebx + 0x51A70000]
    push ebp                       ; private stack canary, retained over HLT
    lea eax, [ebx + 0xA9000000]
    mov [edi + 4], eax
.wait:
    mov dword [edi + 40], 1
    sti
    hlt
    cli
    mov dword [edi + 40], 0
    inc dword [edi + 36]
    lea eax, [ebx + 0xC0010000]
    cmp ebp, eax
    jne .bad_register
    cmp [esp], eax
    jne .bad_register
    lea eax, [ebx + 0x51A70000]
    cmp esi, eax
    jne .bad_register
    lea eax, [ebx + 1]
    shl eax, 16
    add eax, STACKS - 4
    cmp esp, eax
    jne .bad_register
    jmp .wait
.bad_register:
    inc dword [edi + 28]
    jmp .wait

fixed_ipi:
    pushad
    mov ebx, [LAPIC + 0x20]
    shr ebx, 24
    mov edi, ebx
    shl edi, 6
    inc dword [RECORDS + edi + 32]
    mov dword [LAPIC + 0xB0], 0
    test ebx, ebx
    jz .return
    ; A different vector for each AP avoids merging broadcast replies in IRR.
    mov dword [LAPIC + 0x310], 0
    lea eax, [ebx + 0x50]
    mov [LAPIC + 0x300], eax
.return:
    popad
    iretd

%assign n 1
%rep 7
ack_%+n:
    lock bts dword [CONTROL + 32], n
    mov dword [LAPIC + 0xB0], 0
    iretd
%assign n n+1
%endrep

spurious_interrupt:
    iretd
unexpected_interrupt:
    mov dword [CONTROL + 24], 2
    cli
.halt:
    hlt
    jmp .halt

align 8
gdt:
    dq 0
    dq 0x00CF9A000000FFFF
    dq 0x00CF92000000FFFF
gdt_end:
gdtr:
    dw gdt_end - gdt - 1
    dd gdt
idtr:
    dw 256 * 8 - 1
    dd IDT
end:
                                                                                                                                                                                                                                                                      source/v64/tests/smp/ap_startup.mjs                                                                 0000644 0000000 0000000 00000021550 00000000000 014525  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// AP startup: real guest INIT/SIPI through the low-memory trampoline,
// independent AP registers/stacks, physical/shorthand IPIs and HLT wakeup.
// The host supplies only mailbox commands; it never loads an AP context or
// changes an AP's CS, IP, registers, interrupt state or runnable state.
// Build: nasm -f bin tests/smp/ap_startup.asm -o build/smp/ap_startup.bin

import assert from "node:assert/strict";
import url from "node:url";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { CORE_STATE_RANGES, STATE_OFFSETS } = await import("../../src/state_layout.js");
const KERNEL = url.fileURLToPath(new URL("../../build/smp/ap_startup.bin", import.meta.url));
const CONTROL = 0x380000;
const RECORDS = CONTROL + 0x100;
const STRIDE = 64;
const SLICE_LIMIT = 1000;
const TIME_LIMIT_MS = 15000;
const fields = ["boots", "signature", "vector", "real_cr0", "real_cs", "reserved", "stack", "errors",
    "irqs", "resumes", "ready", "cpuid_id", "protected_cr0", "reserved2", "protected_cs", "reserved3"];

async function test(count)
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: KERNEL },
        memory_size: 32 * 1024 * 1024,
        cpu_cores: count,
        acpi: true,
        autostart: false,
        disable_jit: true,
        log_level: 0,
    });
    let load_timeout;
    try
    {
        await new Promise((resolve, reject) => {
            load_timeout = setTimeout(() => reject(new Error(`${count} cores: loading timed out`)), TIME_LIMIT_MS);
            emulator.add_listener("emulator-loaded", resolve);
        });
    }
    catch(error)
    {
        await emulator.destroy();
        throw error;
    }
    finally
    {
        clearTimeout(load_timeout);
    }
    const cpu = emulator.v86.cpu;
    const memory = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const read = address => memory.getUint32(address, true);
    const write = (address, value) => memory.setUint32(address, value, true);
    const record = id => Object.fromEntries(fields.map((name, index) => [name, read(RECORDS + id * STRIDE + index * 4)]));
    const records = () => Array.from({ length: count }, (_, id) => record(id));
    let slices = 0;
    let request = 0;
    let phase = "load";

    // Inspect saved state without switching cores or touching guest state.
    function core_field(id, offset, size = 4)
    {
        if(id === cpu.active_core)
        {
            const view = new DataView(cpu.wasm_memory.buffer);
            return size === 1 ? view.getUint8(cpu.state_base + offset) : view.getUint32(cpu.state_base + offset, true);
        }
        const index = CORE_STATE_RANGES.findIndex(([start, end]) => start <= offset && offset + size <= end);
        assert.notEqual(index, -1, `core field ${offset} is saved`);
        const bytes = cpu.cores[id].saved[index];
        const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
        const local = offset - CORE_STATE_RANGES[index][0];
        return size === 1 ? view.getUint8(local) : view.getUint32(local, true);
    }

    function run_until(label, predicate)
    {
        phase = label;
        const deadline = performance.now() + TIME_LIMIT_MS;
        for(let i = 0; i < SLICE_LIMIT; i++)
        {
            cpu.run_cores();
            slices++;
            assert.equal(read(CONTROL + 24), 0, `${label}: guest error`);
            assert.ok(records().every(r => r.errors === 0), `${label}: AP register/stack corruption`);
            if(predicate()) return;
            assert.ok(performance.now() < deadline, `${label}: wall-clock timeout`);
        }
        assert.fail(`${label}: timed out after ${SLICE_LIMIT} scheduler rounds`);
    }

    function command(kind, target = 0, vector = 8)
    {
        write(CONTROL + 4, kind);
        write(CONTROL + 8, target);
        write(CONTROL + 20, vector);
        write(CONTROL + 12, ++request);
        run_until(`command ${kind}, target ${target}, vector ${vector}`, () => read(CONTROL + 16) === request);
    }

    function verify_ap(id, boots, vector)
    {
        const r = record(id);
        assert.equal(r.boots, boots, `AP ${id}: boot count`);
        assert.equal(r.signature, 0xA9000000 + id, `AP ${id}: signature`);
        assert.equal(r.vector, vector, `AP ${id}: first accepted SIPI vector`);
        assert.equal(r.real_cr0 & 1, 0, `AP ${id}: trampoline entered in real mode`);
        assert.equal(r.real_cs, vector << 8, `AP ${id}: real-mode CS`);
        assert.equal(r.protected_cr0 & 1, 1, `AP ${id}: switched to protected mode`);
        assert.equal(r.protected_cs, 8, `AP ${id}: protected-mode code selector`);
        assert.equal(r.stack, 0x300000 + (id + 1) * 0x10000, `AP ${id}: private stack`);
        assert.equal(r.cpuid_id, id, `AP ${id}: CPUID ID agrees with LAPIC ID`);
        assert.equal(r.errors, 0, `AP ${id}: guest checked its preserved registers and stack`);
        assert.equal(r.ready, 1, `AP ${id}: reached HLT`);
        assert.equal(core_field(id, STATE_OFFSETS.in_hlt, 1), 1, `AP ${id}: actually halted`);
        const reg = index => core_field(id, STATE_OFFSETS.reg32 + index * 4);
        assert.equal(reg(3), id, `AP ${id}: EBX`);
        assert.equal(reg(5), 0xC0010000 + id, `AP ${id}: EBP`);
        assert.equal(reg(6), 0x51A70000 + id, `AP ${id}: ESI`);
        assert.equal(reg(7), RECORDS + id * STRIDE, `AP ${id}: EDI`);
        assert.equal(reg(4), r.stack - 4, `AP ${id}: ESP`);
        assert.equal(read(r.stack - 4), 0xC0010000 + id, `AP ${id}: stack canary`);
    }

    function ipi(kind, targets, target = 0)
    {
        const before = records();
        const target_set = new Set(targets);
        const mask = targets.filter(id => id !== 0).reduce((bits, id) => bits | 1 << id, 0);
        write(CONTROL + 32, 0);
        command(kind, target);
        run_until(`IPI ${kind}: targets ${targets.join(",")}`, () => targets.every(id =>
            record(id).irqs === before[id].irqs + 1 &&
            (id === 0 || record(id).resumes === before[id].resumes + 1)) && read(CONTROL + 32) === mask);
        for(let id = 0; id < count; id++)
        {
            assert.equal(record(id).irqs, before[id].irqs + Number(target_set.has(id)), `IPI ${kind}: core ${id} delivery`);
            if(id !== 0) verify_ap(id, before[id].boots, before[id].vector);
        }
    }

    try
    {
        write(CONTROL, count);
        assert.equal(cpu.cores.length, count);
        assert.ok(cpu.cores.slice(1).every(core => !core.running), "APs initially wait for SIPI");
        run_until("BSP mailbox ready", () => read(CONTROL + 28) === 1);
        assert.ok(cpu.cores.slice(1).every(core => !core.running), "APs cannot execute before guest startup IPIs");
        command(1);
        run_until("all APs reached HLT", () => records().slice(1).every(r => r.boots === 1 && r.ready === 1));
        for(let id = 1; id < count; id++) verify_ap(id, 1, 8);

        // Each targeted AP must leave HLT, service the IPI, acknowledge the
        // BSP with its own vector, restore its registers and halt again.
        for(let id = 1; id < count; id++) ipi(2, [id], id);
        const all = Array.from({ length: count }, (_, id) => id);
        ipi(3, all);                 // ICR all including self
        ipi(4, all.slice(1));        // ICR all excluding self
        ipi(5, all);                 // physical destination 0xFF

        // A SIPI to an already running (even currently halted) AP is ignored.
        command(7, 1, 9);
        ipi(2, [1], 1);
        verify_ap(1, 1, 8);

        command(6, 1, 9);
        run_until("AP re-INIT and restart", () => record(1).boots === 2 && record(1).ready === 1);
        verify_ap(1, 2, 9);
        for(let id = 2; id < count; id++) verify_ap(id, 1, 8);
        ipi(2, [1], 1);
        console.log(`${count} cores: real-mode startup, independent state, directed/broadcast IPI, HLT and re-INIT passed`);

        command(8, 1, 8);
        run_until("two queued SIPIs", () => record(1).boots === 3 && record(1).ready === 1);
        verify_ap(1, 3, 8);
        ipi(2, [1], 1);
        command(8, 1, 9);
        run_until("two queued SIPIs in reverse order", () => record(1).boots === 4 && record(1).ready === 1);
        verify_ap(1, 4, 9);
        ipi(2, [1], 1);
        console.log(`${count} cores: first SIPI wins in both vector orders, ${slices} scheduler rounds`);
    }
    catch(error)
    {
        console.error(JSON.stringify({ count, phase, slices, mailbox: Array.from({ length: 9 }, (_, i) => read(CONTROL + i * 4)), records: records(), diagnostics: cpu.get_diagnostics() }, null, 2));
        throw error;
    }
    finally
    {
        await emulator.destroy();
    }
}

const failures = [];
for(const count of [2, 4, 8])
{
    try { await test(count); }
    catch(error) { failures.push(error); console.error(`${count} cores: ${error.stack}`); }
}
assert.equal(failures.length, 0, `${failures.length} AP startup configurations failed`);
                                                                                                                                                        source/v64/tests/smp/apic_routing.mjs                                                               0000644 0000000 0000000 00000040147 00000000000 015031  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Exercise the real Wasm interrupt controllers through their guest MMIO
// registers. No guest loop, firmware timing, or generated code is involved.

import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { STATE_OFFSETS } from "../../src/state_layout.js";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const root = fileURLToPath(new URL("../../", import.meta.url));
const LAPIC = 0xFEE00000;
const IOAPIC = 0xFEC00000;
const INIT = 1;
const SIPI = 2;

for(const count of [2, 4, 8])
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: root + "bios/seabios.bin" },
        vga_bios: { url: root + "bios/vgabios.bin" },
        acpi: true,
        cpu_cores: count,
        autostart: false,
        memory_size: 32 * 1024 * 1024,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const cpu = emulator.v86.cpu;
    const write = (reg, value) => cpu.write32(LAPIC + reg, value);
    const read = reg => cpu.read32s(LAPIC + reg) >>> 0;
    const send = (destination, command) => {
        write(0x310, destination << 24);
        write(0x300, command);
    };
    const reset = () => {
        cpu.reset_cores();
        cpu.reset_cpu();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            write(0xF0, 0x1FF);
            write(0xD0, (1 << core) << 24);
        }
        cpu.switch_core(0);
    };
    const irr = (core, vector) => {
        cpu.switch_core(core);
        return !!(read(0x200 + (vector >> 5) * 16) & 1 << (vector & 31));
    };
    const targets = vector => Array.from({ length: count }, (_, core) => irr(core, vector));
    const io_write = (reg, value) => {
        cpu.write32(IOAPIC, reg);
        cpu.write32(IOAPIC + 0x10, value);
    };
    const io_read = reg => {
        cpu.write32(IOAPIC, reg);
        return cpu.read32s(IOAPIC + 0x10) >>> 0;
    };

    try
    {
        // Physical destination and all three destination shorthands.
        reset();
        send(count - 1, 0x41);
        assert.deepEqual(targets(0x41), Array.from({ length: count }, (_, i) => i === count - 1));
        reset();
        send(0, 1 << 18 | 0x42);
        assert.deepEqual(targets(0x42), Array.from({ length: count }, (_, i) => i === 0));
        reset();
        send(0, 2 << 18 | 0x43);
        assert.deepEqual(targets(0x43), Array(count).fill(true));
        reset();
        send(0, 3 << 18 | 0x44);
        assert.deepEqual(targets(0x44), Array.from({ length: count }, (_, i) => i !== 0));

        // Logical destinations use each recipient's own DFR and LDR.
        reset();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            write(0xE0, 0xFFFFFFFF);
            write(0xD0, (1 << core) << 24);
        }
        cpu.switch_core(0);
        send((1 << (count - 1)) | 1, 1 << 11 | 0x45);
        assert.deepEqual(targets(0x45), Array.from({ length: count }, (_, i) => i === 0 || i === count - 1));
        reset();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            write(0xE0, 0x0FFFFFFF);
            write(0xD0, (core % 2 ? 0x22 : 0x12) << 24);
        }
        cpu.switch_core(0);
        send(0x22, 1 << 11 | 0x46);
        assert.deepEqual(targets(0x46), Array.from({ length: count }, (_, i) => i % 2 === 1));

        // NMIs ignore vector and IF, and never enter the fixed IRQ IRR.
        // Use physical destinations: self shorthand with NMI is reserved
        // (Intel SDM volume 3A, Tables 12-3 and 12-4).
        reset();
        send(1, 4 << 8);
        assert.equal(cpu.apic_core_nmi_pending(1), 1);
        assert.equal(read(0x200), 0);
        send(1, 5 << 8 | 1 << 14);
        assert.equal(cpu.apic_core_nmi_pending(1), 0, "INIT clears an older NMI");
        assert.equal(cpu.apic_take_core_events(1), INIT);
        send(0, 4 << 8);
        assert.equal(new Uint8Array(cpu.wasm_memory.buffer)[cpu.state_base + STATE_OFFSETS.nmi_blocked], 1,
            "physical self NMI is delivered immediately despite IF being clear");

        // First SIPI wins; a later INIT supersedes a pending startup.
        reset();
        send(1, 5 << 8 | 1 << 14);
        send(1, 6 << 8 | 0x08);
        send(1, 6 << 8 | 0x09);
        assert.equal(cpu.wm.exports.apic_peek_core_events(1), INIT | SIPI | 0x0800);
        cpu.take_core_events(1);
        assert.equal(cpu.instruction_pointer[0], 0x8000);
        assert.equal(cpu.cores[1].running, true);
        cpu.switch_core(0);
        send(1, 6 << 8 | 0x0A);
        cpu.take_core_events(1);
        cpu.switch_core(1);
        assert.equal(cpu.instruction_pointer[0], 0x8000, "running AP ignores another SIPI");
        cpu.switch_core(0);
        send(1, 6 << 8 | 0x0B);
        send(1, 5 << 8 | 1 << 14);
        assert.equal(cpu.wm.exports.apic_peek_core_events(1), INIT);
        cpu.take_core_events(1);
        assert.equal(cpu.cores[1].running, false, "INIT cancels the pending SIPI");
        send(1, 6 << 8 | 0x0C);
        send(1, 5 << 8 | 1 << 15); // INIT level deassert is not another INIT
        assert.equal(cpu.apic_take_core_events(1), SIPI | 0x0C00);
        send(1, 5 << 8 | 1 << 14);
        send(1, 4 << 8);
        cpu.take_core_events(1);
        assert.equal(cpu.apic_core_nmi_pending(1), 1, "NMI after INIT survives deferred reset");

        // Restore pending events without consuming them (single-core
        // snapshots use these same controller exports).
        cpu.wm.exports.apic_restore_core_events(1, SIPI | 0x0D00, false);
        assert.equal(cpu.wm.exports.apic_peek_core_events(1), SIPI | 0x0D00);
        assert.equal(cpu.apic_core_nmi_pending(1), 0);

        // Lowest priority considers ISR as well as TPR: core 0 is serving
        // B1, while core 1 (TPR 20) can accept vector 50 immediately.
        reset();
        cpu.sreg[2] = 0;
        cpu.segment_offsets[2] = 0;
        cpu.reg32[4] = 0x8000;
        send(0, 0xB1);
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        assert.equal(read(0xA0), 0xB0, "PPR reflects the in-service class");
        for(let core = 1; core < count; core++)
        {
            cpu.switch_core(core);
            write(0x80, core === 1 ? 0x20 : 0xE0);
        }
        cpu.switch_core(0);
        cpu.device_lower_irq(11);
        io_write(0x10 + 11 * 2 + 1, ((1 << count) - 1) << 24);
        io_write(0x10 + 11 * 2, 1 << 11 | 1 << 8 | 0x50);
        cpu.device_raise_irq(11);
        assert.deepEqual(targets(0x50), Array.from({ length: count }, (_, i) => i === 1));
        cpu.device_lower_irq(11);
        cpu.switch_core(0);
        send(0, 0xB2);
        assert.equal(cpu.apic_core_interrupt_pending(0), 0, "same priority class cannot nest");
        write(0xB0, 0);
        assert.equal(cpu.apic_core_interrupt_pending(0), 1, "EOI releases the pending class");

        // Device interrupts use the same routing, including NMI delivery.
        reset();
        cpu.device_lower_irq(9);
        io_write(0x10 + 9 * 2 + 1, (count - 1) << 24);
        io_write(0x10 + 9 * 2, 0x51);
        cpu.device_raise_irq(9);
        assert.deepEqual(targets(0x51), Array.from({ length: count }, (_, i) => i === count - 1));
        cpu.switch_core(0);
        cpu.device_lower_irq(9);
        io_write(0x10 + 9 * 2, 4 << 8);
        cpu.device_raise_irq(9);
        assert.equal(cpu.apic_core_nmi_pending(count - 1), 1);

        // A level-triggered device on an AP is redelivered after EOI while
        // asserted, and stops once lowered. EOI may route back to its sender.
        reset();
        cpu.device_lower_irq(9);
        cpu.device_lower_irq(10);
        io_write(0x10 + 10 * 2 + 1, 1 << 24);
        io_write(0x10 + 10 * 2, 1 << 15 | 0x52);
        cpu.device_raise_irq(10);
        assert.equal(irr(1, 0x52), true);
        cpu.sreg[2] = 0;
        cpu.segment_offsets[2] = 0;
        cpu.reg32[4] = 0x8000;
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        assert.equal(irr(1, 0x52), false);
        assert.ok(io_read(0x10 + 10 * 2) & 1 << 14, "level interrupt has remote IRR");
        write(0xB0, 0);
        assert.equal(irr(1, 0x52), true, "EOI redelivers an asserted level");
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        cpu.device_lower_irq(10);
        write(0xB0, 0);
        assert.equal(irr(1, 0x52), false);
        assert.equal(io_read(0x10 + 10 * 2) & 1 << 14, 0, "EOI clears remote IRR after lowering");
        assert.ok(read(0x180 + (0x52 >> 5) * 16) & 1 << (0x52 & 31),
            "EOI retains the last accepted TMR mode until the next interrupt");
        // Software disable retains already pending state, masks all LVT
        // sources, and rejects new fixed interrupts. Special IPIs still work.
        reset();
        send(1, 0x61);
        cpu.switch_core(1);
        write(0xF0, 0xFF);
        write(0x350, 7 << 8);
        assert.ok(read(0x350) & 1 << 16, "disabled LAPIC forces LVT masks");
        assert.equal(cpu.apic_core_interrupt_pending(1), 0);
        assert.equal(irr(1, 0x61), true, "software disable preserves IRR");
        cpu.switch_core(0);
        send(1, 0x62);
        assert.equal(irr(1, 0x62), false);
        write(0xF0, 0x1FF);
        assert.equal(cpu.apic_core_interrupt_pending(1), 1);
        write(0xF0, 0xFF);
        cpu.switch_core(0);
        send(1, 4 << 8);
        assert.equal(cpu.apic_core_nmi_pending(1), 1);
        send(1, 5 << 8 | 1 << 14);
        assert.equal(cpu.apic_take_core_events(1), INIT);
        send(0, 6 << 8 | 8);
        assert.equal(cpu.apic_take_core_events(0), 0, "BSP ignores SIPI");

        // Execute guest WRMSR/OUT instructions to cover CPU/controller wiring.
        const execute = bytes => {
            cpu.sreg[1] = cpu.sreg[2] = 0;
            cpu.segment_offsets[1] = cpu.segment_offsets[2] = 0;
            cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
            cpu.reg32[4] = 0x8000;
            cpu.flags[0] = 2;
            cpu.in_hlt[0] = 0;
            cpu.mem8.set([...bytes, 0xF4], 0x1000);
            cpu.full_clear_tlb();
            cpu.run_cpu_slice(bytes.length + 2);
            assert.equal(cpu.in_hlt[0], 1, "register fixture reaches HLT");
        };
        const msr_enable = enabled => {
            cpu.reg32[1] = 0x1B;
            cpu.reg32[0] = (LAPIC | (enabled ? 0x800 : 0)) | 0;
            cpu.reg32[2] = 0;
            execute([0x0F, 0x30]);
        };
        const out = (port, value) => execute([0xB0, value, 0xE6, port]);

        reset();
        cpu.switch_core(1);
        msr_enable(false);
        assert.equal(cpu.wm.exports.apic_core_hardware_enabled(1), 0);
        assert.equal(read(0x20), 0xFFFFFFFF, "hardware-disabled MMIO is unmapped");
        write(0xF0, 0x1FF);
        cpu.switch_core(0);
        send(1, 0x63);
        send(1, 4 << 8);
        send(1, 5 << 8 | 1 << 14);
        assert.equal(cpu.apic_core_nmi_pending(1), 0);
        assert.equal(cpu.apic_take_core_events(1), 0);
        assert.equal(cpu.wm.exports.apic_core_hardware_enabled(0), 1);
        cpu.switch_core(1);
        msr_enable(true);
        assert.equal(read(0x20), 1 << 24);
        assert.equal(read(0xF0) & 0x100, 0, "hardware re-enable starts software disabled");
        assert.equal(irr(1, 0x63), false);

        // Lowest-priority routing excludes disabled recipients; reserved ICR
        // encodings and illegal vectors do not become fixed interrupts.
        reset();
        write(0xF0, 0xFF);
        send(0, 2 << 18 | 1 << 8 | 0x64);
        assert.deepEqual(targets(0x64), Array.from({ length: count }, (_, i) => i === 1));
        reset();
        for(const mode of [3, 7])
        {
            cpu.switch_core(0);
            send(1, mode << 8 | 0x65);
            assert.equal(irr(1, 0x65), false);
        }
        // nor does an SMI (delivery mode 2): it is latched for the core
        // (src/rust/cpu/smm.rs), its vector ignored
        cpu.switch_core(0);
        send(1, 2 << 8 | 0x65);
        assert.equal(irr(1, 0x65), false);
        assert.equal(cpu.apic_core_smi_pending(1), 1, "SMI latched");
        cpu.apic_restore_smi(1, false);
        cpu.switch_core(0);
        send(1, 0x0F);
        write(0x280, 0);
        assert.ok(read(0x280) & 1 << 5, "illegal send vector latches ESR");
        send(1, 0xFF);
        assert.equal(irr(1, 0xFF), true, "0xFF is a valid fixed vector");
        cpu.switch_core(0);
        assert.equal(cpu.wm.exports.apic_core_ipi_sent(0), 2, "the SMI and the fixed IPI");
        assert.equal(cpu.wm.exports.apic_core_ipi_received(1), 2);

        // Cluster broadcast retains the member mask; reserved DFR values do
        // not silently act as the cluster model.
        reset();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            write(0xE0, 0);
            assert.equal(read(0xE0), 0x0FFFFFFF, "DFR reserved low 28 bits read as ones");
            write(0xD0, ((core % 2 ? 0x20 : 0x10) | (core % 2 ? 2 : 1)) << 24);
        }
        cpu.switch_core(0);
        send(0xF2, 1 << 11 | 0x66);
        assert.deepEqual(targets(0x66), Array.from({ length: count }, (_, i) => i % 2 === 1));
        cpu.switch_core(1);
        write(0xE0, 0x7FFFFFFF);
        cpu.switch_core(0);
        send(0x22, 1 << 11 | 0x67);
        assert.equal(irr(1, 0x67), false);

        // An edge IPI queued behind a level IRQ must not suppress that IRQ's
        // EOI broadcast. The pending edge itself never gets a remote EOI.
        reset();
        cpu.device_lower_irq(10);
        io_write(0x10 + 10 * 2 + 1, 1 << 24);
        io_write(0x10 + 10 * 2, 1 << 15 | 0x68);
        cpu.device_raise_irq(10);
        cpu.switch_core(1);
        cpu.sreg[2] = cpu.segment_offsets[2] = 0;
        cpu.reg32[4] = 0x8000;
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        cpu.switch_core(0);
        send(1, 1 << 15 | 0x68); // integrated xAPIC IPI is still edge-triggered
        cpu.device_lower_irq(10);
        cpu.switch_core(1);
        assert.ok(read(0x180 + (0x68 >> 5) * 16) & 1 << (0x68 & 31));
        write(0xB0, 0);
        assert.equal(io_read(0x10 + 10 * 2) & 1 << 14, 0);
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        assert.equal(read(0x180 + (0x68 >> 5) * 16) & 1 << (0x68 & 31), 0);
        write(0xB0, 0);

        // Route the PIC through masked/unmasked BSP LINT0, then IOAPIC ExtINT
        // to an AP. ExtINT obtains its vector from the PIC, ignores LAPIC TPR,
        // and does not enter LAPIC ISR or require a LAPIC EOI.
        reset();
        for(let irq = 0; irq < 16; irq++) cpu.device_lower_irq(irq);
        for(let irq = 0; irq < 24; irq++) io_write(0x10 + irq * 2, 1 << 16);
        for(const [port, value] of [[0x20, 0x11], [0x21, 0x20], [0x21, 4], [0x21, 1],
            [0xA0, 0x11], [0xA1, 0x28], [0xA1, 2], [0xA1, 1], [0x21, 0xFE], [0xA1, 0xFF]]) out(port, value);
        cpu.device_raise_irq(0);
        assert.equal(cpu.wm.exports.routed_pic_pending(0), 1, "reset virtual wire reaches BSP");
        assert.equal(cpu.wm.exports.routed_pic_pending(1), 0);
        write(0x350, 1 << 16 | 7 << 8);
        assert.equal(cpu.wm.exports.routed_pic_pending(0), 0, "masking LINT0 blocks PIC");
        io_write(0x11, 1 << 24);
        io_write(0x10, 7 << 8);
        assert.equal(cpu.wm.exports.routed_pic_pending(0), 0);
        assert.equal(cpu.wm.exports.routed_pic_pending(1), 1, "ExtINT selects AP destination");
        cpu.switch_core(1);
        write(0x80, 0xF0);
        cpu.write16(0x20 * 4, 0x2000);
        cpu.write16(0x20 * 4 + 2, 0);
        cpu.sreg[2] = cpu.segment_offsets[2] = 0;
        cpu.reg32[4] = 0x8000;
        cpu.flags[0] = 0x202;
        cpu.handle_irqs();
        assert.equal(cpu.instruction_pointer[0], 0x2000, "ExtINT vector comes from PIC");
        assert.equal(read(0x100 + (0x20 >> 5) * 16), 0, "ExtINT does not enter ISR");
        assert.equal(cpu.wm.exports.routed_pic_pending(1), 0, "one PIC acknowledge retires request");
        assert.equal(io_read(0x10) & 1 << 14, 0, "ExtINT does not hold remote IRR");

        console.log(`${count} cores: APIC enable, destinations, INIT/SIPI, NMI, ExtINT, PPR, ESR, EOI and IOAPIC routing passed`);
    }
    finally
    {
        await emulator.destroy();
    }
}
                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/tests/smp/atomic_boundaries.asm                                                          0000644 0000000 0000000 00000011400 00000000000 016012  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; LOCK/XCHG/CMPXCHG8B exception/MMIO gate. The guest performs all page-table
; updates, accesses and #PF recovery. Test PIO only brackets observations.
bits 32
org 0x100000
%define CONTROL 0x380000
%define DESCRIPTORS 0x381000
%define RESULT 0x382000
%define PD 0x200000
%define PT 0x201000
%define IDT 0x280000
%define VIRTUAL 0x40000000
%define RECOVERY CONTROL + 12
header:
    dd 0x1BADB002, 0x10000, -(0x1BADB002 + 0x10000)
    dd header, header, end, end, start
start:
    cli
    cld
    lgdt [gdtr]
    jmp 8:protected
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov esp, 0x310000
    mov edi, IDT
    mov ecx, 256
    mov eax, unexpected
    mov ebx, eax
    and eax, 0xFFFF
    or eax, 8 << 16
    and ebx, 0xFFFF0000
    or ebx, 0x8E00
.idt:
    stosd
    xchg eax, ebx
    stosd
    xchg eax, ebx
    loop .idt
    mov eax, page_fault
    mov word [IDT + 14 * 8], ax
    shr eax, 16
    mov word [IDT + 14 * 8 + 6], ax
    mov eax, invalid_opcode
    mov word [IDT + 6 * 8], ax
    shr eax, 16
    mov word [IDT + 6 * 8 + 6], ax
    lidt [idtr]
    mov dword [PD], 0x83
    mov dword [PD + 1024], PT | 3
    mov eax, PD
    mov cr3, eax
    mov eax, cr4
    or eax, 1 << 4
    mov cr4, eax
    mov eax, cr0
    or eax, (1 << 31) | (1 << 16) ; CR0.PG + WP: supervisor RO writes fault
    mov cr0, eax
    mov esi, DESCRIPTORS
    xor ebp, ebp
.next:
    mov eax, [esi]
    mov [PT], eax
    mov eax, [esi + 4]
    mov [PT + 4], eax
    invlpg [VIRTUAL]
    invlpg [VIRTUAL + 4096]
    mov dword [RESULT + 40], 0
    mov dword [RESULT + 48], 0
    mov dword [RESULT + 28], 0
    mov dword [RESULT + 32], 0
    mov dword [RESULT + 36], 0
    mov eax, [esi + 12]           ; operation table index
    shl eax, 3
    mov ebx, [operations + eax + 4]
    mov [RECOVERY], ebx
    mov ebx, [operations + eax]
    mov [CONTROL + 16], ebx
    mov eax, [esi + 20]
    mov [CONTROL + 20], eax      ; warm-up iterations or one observed access
    mov eax, ebp
    mov dx, 0x504
    out dx, eax
.repeat:
    mov edi, [esi + 8]
    mov eax, [esi + 16]
    mov edx, 0x88776655
    mov ebx, 0x10203040
    mov ecx, 0x50607080
    push dword 0x8D7             ; CF/PF/AF/ZF/SF/OF, IF clear
    popfd
    call [CONTROL + 16]
    mov [RESULT], eax
    mov [RESULT + 4], edx
    mov [RESULT + 8], ebx
    mov [RESULT + 12], ecx
    pushfd
    pop dword [RESULT + 16]
    dec dword [CONTROL + 20]
    jnz .repeat
    mov eax, ebp
    mov dx, 0x508
    out dx, eax
    inc ebp
    add esi, 24
    cmp ebp, [CONTROL]
    jb .next
    mov dword [CONTROL + 4], 0xD0D0
.halt:
    hlt
    jmp .halt
page_fault:
    mov dword [RESULT + 48], 14
    push eax
    mov eax, [esp + 8]
    mov [RESULT + 28], eax
    mov eax, cr2
    mov [RESULT + 32], eax
    mov eax, [esp + 4]
    mov [RESULT + 36], eax
    inc dword [RESULT + 40]
    mov eax, [esp + 16]
    mov [RESULT + 44], eax
    mov eax, [RECOVERY]
    mov [esp + 8], eax
    pop eax
    add esp, 4
    iretd
invalid_opcode:
    mov dword [RESULT + 48], 6
    push eax
    mov eax, [esp + 4]
    mov [RESULT + 28], eax
    inc dword [RESULT + 40]
    mov eax, [esp + 12]
    mov [RESULT + 44], eax
    mov eax, [RECOVERY]
    mov [esp + 4], eax
    pop eax
    iretd
unexpected:
    mov dword [CONTROL + 8], 1
    cli
    hlt
    jmp unexpected
align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr:
    dw $ - gdt - 1
    dd gdt
idtr:
    dw 256 * 8 - 1
    dd IDT
operations:
    dd op0, after0, op1, after1, op2, after2, op3, after3
    dd op4, after4, op5, after5, op6, after6, op7, after7
    dd op8, after8, op9, after9, op10, after10, op11, after11
    dd op12, after12, op13, after13, op14, after14, op15, after15
    dd op16, after16
align 4096
op0: lock inc word [edi]
after0: ret
align 4096
op1: lock inc dword [edi]
after1: ret
align 4096
op2: xchg ax, [edi]
after2: ret
align 4096
op3: xchg eax, [edi]
after3: ret
align 4096
op4: lock xadd [edi], eax
after4: ret
align 4096
op5: lock cmpxchg [edi], ebx
after5: ret
align 4096
op6: lock cmpxchg [edi], ebx
after6: ret
align 4096
op7: lock cmpxchg8b [edi]
after7: ret
align 4096
op8: lock cmpxchg8b [edi]
after8: ret
align 4096
op9: db 0xF0, 0x01, 0xD8             ; LOCK ADD EAX, EBX (register destination)
after9: ret
align 4096
op10: db 0xF0, 0x89, 0x07            ; LOCK MOV [EDI], EAX
 after10: ret
align 4096
op11: db 0xF0, 0xFF, 0xC0            ; LOCK INC EAX
 after11: ret
align 4096
op12: db 0xF0, 0x0F, 0xC7, 0xC8      ; LOCK CMPXCHG8B register encoding
 after12: ret
align 4096
op13: db 0xF0, 0x83, 0x3F, 1         ; LOCK CMP [EDI], 1
 after13: ret
align 4096
op14: db 0xF0, 0x0F, 0xBA, 0x27, 1   ; LOCK BT [EDI], 1
 after14: ret
align 4096
op15: db 0xF0, 0x03, 0x07            ; LOCK ADD EAX, [EDI] (read-only memory)
 after15: ret
align 4096
op16: db 0xF0, 0x90                  ; LOCK NOP
 after16: ret
end:
                                                                                                                                                                                                                                                                source/v64/tests/smp/atomic_boundaries.mjs                                                          0000644 0000000 0000000 00000025155 00000000000 016037  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { setImmediate as set_immediate } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { smp_modes, with_smp_mode, compiled_hits, published } from "../lib/smp_modes.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
fs.mkdirSync(root + "build/smp", { recursive: true });
const kernel = root + "build/smp/atomic_boundaries.bin";
const assembled = spawnSync("nasm", ["-f", "bin", "-o", kernel, root + "tests/smp/atomic_boundaries.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);
const modes = smp_modes();
const CONTROL = 0x380000;
const RESULT = 0x382000;
const RAM = 0x3A0000;
const MMIO = 0x10000000;
const VIRTUAL = 0x40000000;
const INITIAL = Uint8Array.of(0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88);
const names = ["LOCK INC16", "LOCK INC32", "XCHG16", "XCHG32", "LOCK XADD32", "LOCK CMPXCHG32 success", "LOCK CMPXCHG32 failure", "LOCK CMPXCHG8B success", "LOCK CMPXCHG8B failure"];
const cases = [];
for(let op = 0; op < names.length; op++)
{
    const width = [2, 4, 2, 4, 4, 4, 4, 8, 8][op];
    cases.push({ op, width, permission: 3, first: RAM, second: RAM + 4096, offset: 256, warm: true, label: names[op] + " warm" });
    if(op >= 7)
    {
        cases.push({ op, width, permission: 3, first: MMIO, second: MMIO + 4096,
            offset: 256, high_bit: true, label: names[op] + " aligned MMIO low-dword bit31" });
    }
    for(const space of ["ram", "mmio", "mixed"])
    {
        for(const permission of [3, 0, 1])
        {
            cases.push({ op, width, permission, first: space === "ram" ? RAM : MMIO,
                second: space === "mmio" ? MMIO + 4096 : RAM + 4096,
                offset: 4096 - (width === 2 ? 1 : 3),
                label: `${names[op]} ${space} second-page=${permission === 3 ? "writable" : permission === 0 ? "absent" : "read-only"}` });
        }
    }
}

for(let op = 9; op <= 16; op++)
{
    for(const permission of [3, 0, 1])
    {
        cases.push({ op, width: 8, permission, first: MMIO, second: MMIO + 4096,
            offset: 4093, invalid: true, label: `illegal LOCK form ${op - 9}, second PTE=${permission}` });
    }
}

function initial_bytes(test)
{
    const bytes = INITIAL.slice(0, test.width);
    if(test.high_bit) bytes[3] |= 0x80;
    return bytes;
}

function initial_eax(test)
{
    if(test.op === 2 || test.op === 3) return 0xA1B2C3D4;
    if(test.op === 4) return 1;
    if(test.op === 6 || test.op === 8) return 0;
    return test.high_bit ? 0xC4332211 : 0x44332211;
}

function expected(test)
{
    const bytes = initial_bytes(test);
    const view = new DataView(bytes.buffer);
    const registers = [initial_eax(test), 0x88776655, 0x10203040, 0x50607080];
    if(test.permission !== 3 || test.invalid) return { bytes, registers };
    switch(test.op)
    {
        case 0: view.setUint16(0, 0x2212, true); break;
        case 1: view.setUint32(0, 0x44332212, true); break;
        case 2: view.setUint16(0, 0xC3D4, true); registers[0] = 0xA1B22211; break;
        case 3: view.setUint32(0, 0xA1B2C3D4, true); registers[0] = 0x44332211; break;
        case 4: view.setUint32(0, 0x44332212, true); registers[0] = 0x44332211; break;
        case 5: view.setUint32(0, 0x10203040, true); break;
        case 6: registers[0] = 0x44332211; break;
        case 7:
            view.setUint32(0, 0x10203040, true);
            view.setUint32(4, 0x50607080, true);
            break;
        case 8: registers[0] = test.high_bit ? 0xC4332211 : 0x44332211; break;
    }
    return { bytes, registers };
}

for(const mode of modes)
{
    const emulator = new V86(with_smp_mode({ graphics_adapter: "bochs_vga", multiboot: { url: kernel }, memory_size: 16 << 20,
        acpi: true, cpu_cores: 2, cpu_quantum: 257, cpu_schedule_seed: 7,
        disable_jit: mode === "interpreter", experimental_smp_jit: true, ir_sync_publication: true,
        autostart: false, log_level: 0 }, mode));
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const cpu = emulator.v86.cpu;
        const e = cpu.wm.exports;
        const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        const word = address => view().getUint32(address, true);
        const set = (address, value) => view().setUint32(address, value, true);
        set(CONTROL, cases.length);
        cases.forEach((test, i) => {
            const address = 0x381000 + i * 24;
            set(address, test.first | 3);
            set(address + 4, test.second | test.permission);
            set(address + 8, VIRTUAL + test.offset);
            set(address + 12, test.op);
            set(address + 16, initial_eax(test));
            set(address + 20, test.warm ? 2048 : 1);
        });
        const device = new Uint8Array(0x20000);
        const device_view = new DataView(device.buffer);
        let active = null;
        let trace = [];
        let checked = 0;
        const record = (kind, address, bytes) => {
            assert.ok(active, "MMIO only inside a guest operation");
            for(let i = 0; i < bytes.length; i++) trace.push([kind, address + i, bytes[i]]);
        };
        cpu.io.mmap_register(MMIO, device.length,
            address => { const value = device[address - MMIO]; record("read", address, [value]); return value; },
            (address, value) => { record("write", address, [value]); device[address - MMIO] = value; },
            address => { const value = device_view.getInt32(address - MMIO, true); record("read", address, device.slice(address - MMIO, address - MMIO + 4)); return value; },
            (address, value) => { device_view.setInt32(address - MMIO, value, true); record("write", address, device.slice(address - MMIO, address - MMIO + 4)); });
        const physical = (test, i) => test.offset + i < 4096 ? test.first + test.offset + i : test.second + test.offset + i - 4096;
        cpu.io.register_write(0x504, device, undefined, undefined, index => {
            active = cases[index];
            trace = [];
            for(let i = 0; i < active.width; i++)
            {
                const address = physical(active, i);
                if(address >= MMIO) device[address - MMIO] = initial_bytes(active)[i];
                else cpu.mem8[address] = initial_bytes(active)[i];
            }
        });
        cpu.io.register_write(0x508, device, undefined, undefined, index => {
            const test = cases[index];
            const label = `${mode}: ${test.label}`;
            assert.equal(test, active);
            if(test.warm)
            {
                if(mode !== "interpreter") assert.ok(published(e, 0x101000 + test.op * 4096), `${label}: operation published after warm-up`);
                active = null;
                return;
            }
            const want = expected(test);
            const fault = test.permission !== 3 || test.invalid;
            assert.equal(word(RESULT + 40), fault ? 1 : 0, `${label}: exactly the expected exception`);
            if(fault)
            {
                assert.equal(word(RESULT + 48), test.invalid ? 6 : 14, `${label}: exception vector`);
                assert.equal(word(RESULT + 28), 0x101000 + test.op * 4096, `${label}: restart EIP names full instruction including LOCK`);
                if(!test.invalid)
                {
                    assert.equal(word(RESULT + 32), VIRTUAL + 4096, `${label}: CR2 names second page`);
                    assert.equal(word(RESULT + 36), test.permission === 0 ? 2 : 3, `${label}: #PF write/protection bits`);
                }
                assert.equal(word(RESULT + 16) & 0x8D5, 0x8D5, `${label}: arithmetic flags unchanged by fault`);
                assert.deepEqual(trace, [], `${label}: no MMIO read or write before all permissions pass`);
            }
            else
            {
                const arithmetic = [0x5, 0x5, 0x8D5, 0x8D5, 0x4, 0x44, 0x91, 0x8D5, 0x895][test.op];
                assert.equal(word(RESULT + 16) & 0x8D5, arithmetic, `${label}: only committed arithmetic flags change`);
            }
            if(!fault && test.op >= 5)
            {
                assert.equal((word(RESULT + 16) >> 6) & 1, test.op === 6 || test.op === 8 ? 0 : 1, `${label}: comparison ZF`);
            }
            assert.deepEqual([0, 4, 8, 12].map(offset => word(RESULT + offset)), want.registers, `${label}: registers commit together`);
            const actual = Uint8Array.from({ length: test.width }, (_, i) => {
                const address = physical(test, i);
                return address >= MMIO ? device[address - MMIO] : cpu.mem8[address];
            });
            assert.deepEqual(actual, want.bytes, `${label}: operand commits wholly or remains unchanged`);
            if(!fault)
            {
                const mmio = Array.from({ length: test.width }, (_, i) => [physical(test, i), i]).filter(([address]) => address >= MMIO);
                const reads = trace.filter(([kind]) => kind === "read").sort((a, b) => a[1] - b[1]);
                const writes = trace.filter(([kind]) => kind === "write").sort((a, b) => a[1] - b[1]);
                assert.deepEqual(reads, mmio.map(([address, i]) => ["read", address, initial_bytes(test)[i]]), `${label}: each MMIO byte read exactly once`);
                assert.deepEqual(writes, mmio.map(([address, i]) => ["write", address, want.bytes[i]]), `${label}: MMIO writeback occurs even on failed CMPXCHG`);
                const first_write = trace.findIndex(([kind]) => kind === "write");
                if(first_write >= 0) assert.ok(trace.slice(first_write).every(([kind]) => kind === "write"), `${label}: reads precede writes`);
            }
            active = null;
            checked++;
        });
        const deadline = performance.now() + 30000;
        let rounds = 0;
        while(word(CONTROL + 4) !== 0xD0D0)
        {
            assert.equal(word(CONTROL + 8), 0, `${mode}: unexpected guest exception`);
            if(performance.now() >= deadline) throw new Error(`${mode}: guest stalled ${JSON.stringify(cpu.get_diagnostics())}`);
            cpu.run_cores();
            if((++rounds & 1023) === 0) await set_immediate();
        }
        assert.equal(checked, cases.filter(test => !test.warm).length);
        const hits = compiled_hits(e);
        if(mode !== "interpreter") assert.ok(hits > 0, `${mode}: compiled code actually executed`);
        console.log(`${mode}: ${checked} atomic #UD/page-fault/write-protection/MMIO cases passed; compiled activations=${hits}`);
    }
    finally { await emulator.destroy(); }
}
                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/smp/clock.mjs                                                                      0000644 0000000 0000000 00000025016 00000000000 013437  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// No Wasm required: exercise the real device models against one injectable
// clock, including the exact deadlines used when all processors are halted.
import assert from "node:assert/strict";
import { MachineClock } from "../../src/machine_clock.js";
import { PIT } from "../../src/pit.js";
import { RTC } from "../../src/rtc.js";
import { ACPI } from "../../src/acpi.js";
import { create_platform } from "../../src/platform.js";
import { set_log_level } from "../../src/log.js";

set_log_level(0);
let passed = 0;
function test(name, run)
{
    run();
    passed++;
    console.log("PASS " + name);
}

function machine(options)
{
    const clock = new MachineClock({ mode: "deterministic", instructions_per_ms: 1000, ...options });
    const interrupts = [];
    const lines = new Map();
    const cpu = {
        clock,
        // (an i440FX machine with ACPI: the PM block's layout)
        platform: create_platform({ acpi: true }, 64 << 20),
        io: { register_read() {}, register_write() {}, unregister_range() {}, ports: [] },
        devices: { pci: { register_device: device => new Int32Array(new Uint8Array(device.pci_space).buffer) } },
        shared_irq_sources: Array.from({ length: 24 }, () => new Set()),
        device_raise_irq: irq => {
            if(!lines.get(irq)) interrupts.push([clock.now(), irq, 1]);
            lines.set(irq, true);
        },
        device_lower_irq: irq => {
            if(lines.get(irq)) interrupts.push([clock.now(), irq, 0]);
            lines.set(irq, false);
        },
        set_shared_irq_level: (irq, source, level) => {
            if(level) cpu.device_raise_irq(irq);
            else cpu.device_lower_irq(irq);
        },
    };
    const bus = { send() {} };
    const pit = new PIT(cpu, bus);
    const rtc = new RTC(cpu);
    const acpi = new ACPI(cpu, bus);
    return { clock, pit, rtc, acpi, interrupts };
}

function write_rtc(rtc, index, value)
{
    rtc.cmos_index = index;
    rtc.cmos_port_write(value);
}

function read_rtc(rtc, index)
{
    rtc.cmos_index = index;
    return rtc.cmos_port_read();
}

function program(m)
{
    m.pit.port43_write(0x34); // counter 0, rate generator, low/high
    m.pit.counter_write(0, 0xA9);
    m.pit.counter_write(0, 4); // 1193 ticks, approximately 1 ms
    write_rtc(m.rtc, 0xB, 0x42); // periodic, 24-hour BCD
    m.acpi.smi_cmd_write(0xF1);
    m.acpi.pm_write(2, 2, 1); // enable timer SCI
}

test("normal clock is monotonic, does not advance on equal reads and bounds host gaps", () => {
    let host = 100;
    const clock = new MachineClock({ now: () => host, wall_epoch_ms: 10000, max_host_delta_ms: 1000 });
    assert.equal(clock.now(), 0);
    assert.equal(clock.now(), 0);
    host += 25;
    assert.equal(clock.now(), 25);
    host -= 5;
    assert.equal(clock.now(), 25);
    host += 15;
    assert.equal(clock.now(), 35);
    host += 5000;
    assert.equal(clock.now(), 1035);
    assert.equal(clock.now(), 1035);
    assert.deepEqual(clock.get_diagnostics(), {
        host_pause_count: 1, discarded_host_ms: 4000, host_backwards_count: 1,
        committed_instructions: 0, idle_ms: 0,
    });
});

test("pause freezes monotonic time and RTC epoch, resume excludes paused host time", () => {
    let host = 0;
    const clock = new MachineClock({ now: () => host, wall_epoch_ms: 10000 });
    host = 20;
    clock.pause();
    host = 100000;
    assert.equal(clock.now(), 20);
    assert.equal(clock.wall_time(), 10020);
    clock.resume();
    host += 8;
    assert.equal(clock.now(), 28);
    assert.equal(clock.get_diagnostics().host_pause_count, 0);
});

test("deterministic clock consumes committed progress once; reads and vCPU count add no time", () => {
    let pending = 0;
    const clock = new MachineClock({ mode: "deterministic", instructions_per_ms: 1000 });
    clock.set_instruction_source(() => { const n = pending; pending = 0; return n; });
    pending = 1234;
    assert.equal(clock.now(), 1.234);
    for(let i = 0; i < 100; i++) assert.equal(clock.now(), 1.234);
    pending = 766;
    assert.equal(clock.wall_time(), 946684800002);
    assert.equal(clock.get_diagnostics().committed_instructions, 2000);

    const other = new MachineClock({ mode: "deterministic", instructions_per_ms: 1000 });
    for(let i = 0; i < 2000; i++) other.advance_instructions(1);
    assert.equal(other.now(), clock.now());
    clock.advance_to(10);
    clock.advance_to(9);
    clock.advance_instructions(500);
    assert.equal(clock.now(), 10.5);
});

test("snapshot restores virtual time and RTC wall epoch independently of host", () => {
    let host = 0;
    const clock = new MachineClock({ now: () => host, wall_epoch_ms: 10000 });
    host = 50;
    const saved = clock.get_state();
    host = 100000;
    const restored = new MachineClock({ now: () => host, wall_epoch_ms: 999999 });
    restored.pause();
    restored.set_state(saved);
    host += 999999;
    assert.equal(restored.now(), 50);
    assert.equal(restored.wall_time(), 10050);
    restored.resume();
    host += 2;
    assert.equal(restored.wall_time(), 10052);
});

test("identical inputs produce identical PIT/RTC/PM interrupt sequences and PM readings", () => {
    const run = () => {
        const m = machine();
        program(m);
        const reads = [];
        // Include PM bit-23 rollover, exercising a slow deadline alongside IRQ0/8.
        for(const count of [0, 250, 727, 23, 9000, 1000000, 1333346, 2343346])
        {
            m.clock.advance_instructions(count);
            m.pit.timer(m.clock.now(), false);
            m.rtc.timer(m.clock.now(), false);
            m.acpi.timer(m.clock.now());
            reads.push([m.acpi.pm_read(8, 4), read_rtc(m.rtc, 0), read_rtc(m.rtc, 0xC)]);
            const before = m.clock.now();
            assert.equal(m.acpi.pm_read(8, 4), m.acpi.pm_read(8, 4));
            assert.equal(m.clock.now(), before);
        }
        assert.ok(m.interrupts.some(e => e[1] === 0));
        assert.ok(m.interrupts.some(e => e[1] === 8));
        assert.ok(m.interrupts.some(e => e[1] === 9));
        return [m.interrupts, reads];
    };
    assert.deepEqual(run(), run());
});

test("halt deadline jumps wake PIT and RTC at exact deadlines and leave future deadlines", () => {
    const m = machine();
    program(m);
    const rtc_deadline = m.rtc.timer(m.clock.now(), false);
    m.clock.advance_to(rtc_deadline);
    assert.ok(m.rtc.timer(m.clock.now(), false) > 0);
    assert.ok(m.interrupts.some(e => e[1] === 8));

    const pit_deadline = m.pit.timer(m.clock.now(), false);
    m.clock.advance_to(m.clock.now() + pit_deadline);
    assert.ok(m.pit.timer(m.clock.now(), false) > 0);
    assert.ok(m.interrupts.some(e => e[1] === 0));
});

test("device snapshots preserve PIT/RTC/PM phase and calendar with the machine clock", () => {
    const m = machine();
    program(m);
    m.clock.advance_instructions(1234567);
    m.pit.timer(m.clock.now(), false);
    m.rtc.timer(m.clock.now(), false);
    m.acpi.timer(m.clock.now());
    const clock_state = m.clock.get_state();
    const pit_state = m.pit.get_state().map(x => ArrayBuffer.isView(x) ? x.slice() : x);
    const rtc_state = m.rtc.get_state().map(x => ArrayBuffer.isView(x) ? x.slice() : x);
    const acpi_state = m.acpi.get_state().map(x => ArrayBuffer.isView(x) ? x.slice() : x);
    const restored = machine({ wall_epoch_ms: 1893456000000 });
    restored.clock.set_state(clock_state);
    restored.pit.set_state(pit_state);
    restored.rtc.set_state(rtc_state);
    restored.acpi.set_state(acpi_state);
    const sample = x => [x.pit.get_counter_value(0, x.clock.now()),
        x.rtc.timer(x.clock.now(), false), x.acpi.pm_read(8, 4),
        read_rtc(x.rtc, 0), read_rtc(x.rtc, 9), x.clock.wall_time()];
    assert.deepEqual(sample(m), sample(restored));
    m.clock.advance_instructions(12345);
    restored.clock.advance_instructions(12345);
    assert.deepEqual(sample(m), sample(restored));
});

test("PIT exact deadline delivery remains stable over 40000 halts and fractional ticks", () => {
    for(const reload of [1, 17, 1193, 65535])
    {
        const m = machine();
        m.pit.port43_write(0x34);
        m.pit.counter_write(0, reload & 255);
        m.pit.counter_write(0, reload >> 8);
        for(let i = 0; i < 10000; i++)
        {
            const delta = m.pit.timer(m.clock.now(), false);
            assert.ok(delta > 0);
            m.clock.advance_to(m.clock.now() + delta);
            const before = m.interrupts.length;
            assert.ok(m.pit.timer(m.clock.now(), false) > 0);
            assert.ok(m.interrupts.length > before);
            assert.deepEqual(m.interrupts.at(-1), [m.clock.now(), 0, 1]);
        }
    }
});

test("RTC periodic events do not starve simultaneous update or alarm events", () => {
    const m = machine();
    write_rtc(m.rtc, 1, 1); // alarm second 1
    write_rtc(m.rtc, 3, 0);
    write_rtc(m.rtc, 5, 0);
    write_rtc(m.rtc, 0xB, 0x72);
    m.clock.advance_to(1000);
    m.rtc.timer(m.clock.now(), false);
    assert.equal(read_rtc(m.rtc, 0xC) & 0xF0, 0xF0);
});

test("legacy RTC snapshots rebase host UTC deadlines without changing saved calendar", () => {
    const m = machine();
    write_rtc(m.rtc, 0xB, 0x42);
    const state = m.rtc.get_state();
    state.length = 15;
    state[3] = 1600000000000;
    state[4] = state[3] + 50;
    m.clock.advance_to(123);
    m.rtc.set_state(state);
    assert.equal(m.rtc.last_update, 123);
    assert.equal(m.rtc.timer(m.clock.now(), false), 50);
    assert.equal(m.rtc.rtc_time, state[2]);
});

test("invalid clock rates, committed counts and deadlines are rejected", () => {
    assert.throws(() => new MachineClock({ instructions_per_ms: 0 }));
    assert.throws(() => new MachineClock({ mode: "unknown" }));
    const clock = new MachineClock({ mode: "deterministic" });
    assert.throws(() => clock.advance_instructions(-1));
    assert.throws(() => clock.advance_instructions(0.5));
    assert.throws(() => clock.advance_to(Infinity));
});

test("a normal clock's rate: the machine's time at a fraction of the host's, waits scaled back", () => {
    let host = 0;
    const clock = new MachineClock({ now: () => host, rate: 0.25 });
    host = 400;
    assert.equal(clock.now(), 100);
    assert.equal(clock.to_host_ms(100), 400);
    // (a long host gap: capped first, then scaled)
    host = 5400;
    assert.equal(clock.now(), 350);
    assert.equal(new MachineClock({ now: () => host }).to_host_ms(100), 100);
    assert.equal(new MachineClock({ mode: "deterministic" }).to_host_ms(100), 100);
    for(const rate of [0, -1, 1.5, NaN]) assert.throws(() => new MachineClock({ now: () => 0, rate }));
});

console.log(JSON.stringify({ suite: "machine-clock-devices", passed }));
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/smp/clock_boot_bench.mjs                                                           0000644 0000000 0000000 00000025123 00000000000 015620  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Compare independently built releases. Every sample starts a fresh Node/VM.
// Only run() -> Linux serial shell is timed; builds and image loading are not.
// Example:
// node tests/smp/clock_boot_bench.mjs --baseline /tmp/v86-before \
//   --current /tmp/v86-current --samples 5 --output /tmp/c0-boot.json
import assert from "node:assert/strict";
import { execFile, execFileSync } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { fileURLToPath, pathToFileURL as path_to_file_url } from "node:url";

const script = fileURLToPath(import.meta.url);
const repository = path.resolve(path.dirname(script), "../..");
assert.equal((process.argv.length - 2) % 2, 0, "every --option requires a value");
const options = Object.fromEntries(Array.from({ length: (process.argv.length - 2) / 2 }, (_, i) =>
    [process.argv[2 + i * 2].replace(/^--/, ""), process.argv[3 + i * 2]]));
const assets = path.resolve(options.assets || repository);
const hash = file => create_hash("sha256").update(fs.readFileSync(file)).digest("hex");
const workload_bytes = 16 * 1024 * 1024;
const workload_hash = create_hash("md5").update(Buffer.alloc(workload_bytes)).digest("hex");
const timeout_ms = +(options.timeout || 120000);
const marker = "C0_BENCH_RESULT ";

function command(executable, args, cwd)
{
    try { return execFileSync(executable, args, { cwd, encoding: "utf8" }).trim(); }
    catch{ return null; }
}

async function sample(root)
{
    const { V86 } = await import(path_to_file_url(path.join(root, "build/libv86.mjs")));
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        wasm_path: path.join(root, "build/v86.wasm"),
        bios: { url: path.join(assets, "bios/seabios.bin") },
        vga_bios: { url: path.join(assets, "bios/vgabios.bin") },
        cdrom: { url: path.join(assets, "images/linux4.iso") },
        memory_size: 128 << 20,
        cpu_cores: 1,
        acpi: true,
        autostart: false,
        log_level: 0,
    });
    let serial = "";
    let boot_started;
    let boot_finished;
    let workload_started;
    let workload_finished;
    let boot_resolve;
    let workload_resolve;
    let phase = "load";
    let timeout;
    const booted = new Promise(resolve => { boot_resolve = resolve; });
    const worked = new Promise(resolve => { workload_resolve = resolve; });
    emulator.add_listener("serial0-output-byte", byte => {
        serial += String.fromCharCode(byte);
        if(phase === "boot" && serial.endsWith("~% "))
        {
            boot_finished = performance.now();
            phase = "shell";
            boot_resolve();
        }
        if(phase === "workload" && serial.endsWith("~% "))
        {
            workload_finished = performance.now();
            phase = "done";
            workload_resolve();
        }
    });
    const failed = new Promise((_, reject) => {
        timeout = setTimeout(() => reject(new Error(`${phase} timed out after ${timeout_ms} ms`)), timeout_ms);
        emulator.add_listener("emulator-error", reject);
    });
    try
    {
        await Promise.race([new Promise(resolve => emulator.add_listener("emulator-loaded", resolve)), failed]);
        phase = "boot";
        boot_started = performance.now();
        emulator.run();
        await Promise.race([booted, failed]);
        assert.ok(!serial.includes("Kernel panic"), "Linux boot must reach shell without panic");
        const boot_serial_length = serial.length;
        phase = "workload";
        workload_started = performance.now();
        emulator.serial0_send("dd if=/dev/zero bs=1024 count=16384 2>/dev/null | md5sum\n");
        await Promise.race([worked, failed]);
        assert.match(serial.slice(boot_serial_length), new RegExp(`(?:\\r?\\n)${workload_hash}  -\\r?\\n`),
            "fixed 16 MiB stream must complete with the expected digest");
        await emulator.stop();
        return {
            boot_wall_ms: boot_finished - boot_started,
            workload_wall_ms: workload_finished - workload_started,
            instruction_counter: emulator.v86.cpu.instruction_counter[0] >>> 0,
            serial_sha256: create_hash("sha256").update(serial).digest("hex"),
            serial,
        };
    }
    catch(error)
    {
        if(options.transcript) fs.writeFileSync(options.transcript, serial);
        throw error;
    }
    finally
    {
        clearTimeout(timeout);
        await emulator.destroy();
    }
}

if(options.sample)
{
    const result = await sample(path.resolve(options.sample));
    if(options.transcript) fs.writeFileSync(options.transcript, result.serial);
    delete result.serial;
    console.log(marker + JSON.stringify(result));
}
else
{
    assert.ok(options.baseline && options.current, "--baseline and --current release build roots are required");
    const sample_count = +(options.samples || 5);
    const max_ratio = +(options.ratio || 1.10);
    assert.ok(Number.isInteger(sample_count) && sample_count >= 3, "at least three measured samples per revision");
    assert.ok(Number.isFinite(max_ratio) && max_ratio >= 1, "--ratio is the maximum current/baseline median boot ratio");
    const output = path.resolve(options.output || "build/c0-boot-bench.json");
    const logs = output.replace(/\.json$/, "") + "-serial";
    fs.mkdirSync(path.dirname(output), { recursive: true });
    fs.mkdirSync(logs, { recursive: true });
    const roots = { baseline: path.resolve(options.baseline), current: path.resolve(options.current) };
    const report = {
        schema: 1,
        started_utc: new Date().toISOString(),
        host: {
            platform: os.platform(), release: os.release(), architecture: os.arch(),
            model: os.cpus()[0].model, logical_cpus: os.cpus().length, memory_bytes: os.totalmem(),
            node: process.version, v8: process.versions.v8,
            load_average_start: os.loadavg(),
            os_version: command("sw_vers", []),
            rustc: command("rustc", ["--version"]),
            clang: command("clang", ["--version"]),
            java: command("java", ["--version"]),
        },
        method: {
            build_command: "make build/v86.wasm build/libv86.mjs (independent worktrees/target directories, WASM_OPT=false)",
            clock: "normal (default)", cpu_cores: 1, acpi: true, memory_bytes: 128 << 20,
            jit: "default", sample_count, warmups_per_revision: 1,
            order: "alternating AB/BA pairs, fresh Node process and VM each sample",
            start: "performance.now immediately before emulator.run after emulator-loaded",
            end: "serial0-output-byte callback completing Linux shell prompt '~% '",
            boot_source: "linux4.iso default bootloader/kernel command line, through SeaBIOS POST",
            excludes: "build, module import, WebAssembly instantiation and initial BIOS/image loading before emulator-loaded; guest disk I/O during boot remains included",
            workload: { bytes: workload_bytes, md5: workload_hash, command: "dd if=/dev/zero bs=1024 count=16384 2>/dev/null | md5sum" },
            boot_median_max_ratio: max_ratio,
        },
        artifacts: Object.fromEntries(Object.entries(roots).map(([label, root]) => [label, {
            root, commit: command("git", ["rev-parse", "HEAD"], root),
            working_tree: command("git", ["status", "--short", "--untracked-files=no"], root),
            wasm_sha256: hash(path.join(root, "build/v86.wasm")),
            js_sha256: hash(path.join(root, "build/libv86.mjs")),
            softfloat_sha256: hash(path.join(root, "build/softfloat.o")),
            zstd_sha256: hash(path.join(root, "build/zstddeclib.o")),
            closure_compiler_sha256: hash(path.join(root, "closure-compiler/compiler.jar")),
        }])),
        inputs: Object.fromEntries(["bios/seabios.bin", "bios/vgabios.bin", "images/linux4.iso"].map(file =>
            [file, { bytes: fs.statSync(path.join(assets, file)).size, sha256: hash(path.join(assets, file)) }])),
        runner_sha256: hash(script), warmups: [], samples: [],
    };
    const save = () => fs.writeFileSync(output, JSON.stringify(report, null, 2) + "\n");
    const run = async (label, index, warmup) => {
        const transcript = path.join(logs, `${warmup ? "warmup" : "sample"}-${index}-${label}.log`);
        let stdout;
        try
        {
            ({ stdout } = await promisify(execFile)(process.execPath, [script,
                "--sample", roots[label], "--assets", assets,
                "--timeout", String(timeout_ms), "--transcript", transcript,
            ], { timeout: timeout_ms + 15000, maxBuffer: 1024 * 1024 }));
        }
        catch(error)
        {
            report.failure = { label, index, warmup, message: String(error), transcript: path.relative(path.dirname(output), transcript) };
            save();
            throw error;
        }
        const line = stdout.split("\n").find(text => text.startsWith(marker));
        assert.ok(line, "child returned a measured result");
        const result = { label, index, transcript: path.relative(path.dirname(output), transcript), ...JSON.parse(line.slice(marker.length)) };
        report[warmup ? "warmups" : "samples"].push(result);
        save();
        console.log(`${warmup ? "warmup" : "sample"} ${index} ${label}: boot ${result.boot_wall_ms.toFixed(1)} ms, workload ${result.workload_wall_ms.toFixed(1)} ms`);
    };
    save();
    await run("baseline", 0, true);
    await run("current", 0, true);
    for(let index = 1; index <= sample_count; index++)
    {
        for(const label of index % 2 ? ["baseline", "current"] : ["current", "baseline"])
        {
            await run(label, index, false);
        }
    }
    const median = values => {
        values.sort((a, b) => a - b);
        return (values[Math.floor((values.length - 1) / 2)] + values[Math.floor(values.length / 2)]) / 2;
    };
    report.summary = Object.fromEntries(["boot_wall_ms", "workload_wall_ms"].map(metric => {
        const baseline = median(report.samples.filter(sample => sample.label === "baseline").map(sample => sample[metric]));
        const current = median(report.samples.filter(sample => sample.label === "current").map(sample => sample[metric]));
        return [metric, { baseline_median: baseline, current_median: current, ratio: current / baseline }];
    }));
    report.passed = report.summary.boot_wall_ms.ratio <= max_ratio;
    report.finished_utc = new Date().toISOString();
    report.host.load_average_end = os.loadavg();
    save();
    console.log(JSON.stringify({ passed: report.passed, ...report.summary, output }, null, 2));
    if(!report.passed) process.exitCode = 1;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/smp/clock_execution.mjs                                                            0000644 0000000 0000000 00000041140 00000000000 015516  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Machine clock integration tests: real interpreter/Wasm dispatch and real device ports.
import assert from "node:assert/strict";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
let passed = 0;
async function test(name, run)
{
    await run();
    passed++;
    console.log("PASS " + name);
}

async function machine(cores = 1, extra = {})
{
    const emulator = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: cores, memory_size: 16 << 20,
        autostart: false, log_level: 0, cpu_quantum: 17, cpu_schedule_seed: 0x12345678,
        cpu_clock: { mode: "deterministic", instructions_per_ms: 1000 }, ...extra });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume();
    return emulator;
}

function entry(cpu, bytes, ip = 0x1000)
{
    cpu.sreg[1] = 0;
    cpu.segment_offsets[1] = 0;
    cpu.instruction_pointer[0] = cpu.previous_ip[0] = ip;
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2;
    cpu.in_hlt[0] = 0;
    cpu.mem8.set(bytes, ip);
    cpu.full_clear_tlb();
}

function work(cpu)
{
    cpu.clock.now();
    return cpu.clock.get_diagnostics().committed_instructions;
}

function interrupt(cpu, vector, target = 0x1200)
{
    cpu.mem8.set([target & 255, target >> 8, 0, 0], vector * 4);
    cpu.mem8[target] = 0xF4; // handler: hlt
}

await test("ordinary and prefixed instructions retire once; faulting dispatch does not", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0x90, 0x66, 0x90, 0xF4]);
        const before = work(cpu);
        cpu.run_cpu_slice(100);
        assert.equal(work(cpu) - before, 3);
        assert.equal(cpu.clock.now(), 0.003);

        interrupt(cpu, 6);
        entry(cpu, [0x0F, 0x0B]); // UD2 -> #UD
        const fault_before = work(cpu);
        cpu.run_cpu_slice(1);
        assert.equal(cpu.instruction_pointer[0], 0x1200);
        assert.equal(work(cpu), fault_before, "#UD dispatch must not retire");
        cpu.run_cpu_slice(1);
        assert.equal(work(cpu) - fault_before, 1, "handler HLT retires normally");
    }
    finally { await emulator.destroy(); }
});

await test("REP counts completed elements across bounded slices, including empty REP", async () => {
    const emulator = await machine(2);
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0xF3, 0xAA, 0xF4]);
        cpu.reg32[0] = 0x5A;
        cpu.reg32[1] = 1000;
        cpu.reg32[7] = 0x4000;
        const before = work(cpu);
        cpu.run_cpu_slice(1000);
        assert.equal(cpu.reg32[1], 744);
        assert.equal(work(cpu) - before, 256);
        assert.equal(cpu.instruction_pointer[0], 0x1000);
        cpu.run_cpu_slice(1000);
        cpu.run_cpu_slice(1000);
        cpu.run_cpu_slice(1000);
        assert.equal(cpu.reg32[1], 0);
        assert.equal(work(cpu) - before, 1001); // elements plus final HLT
        assert.ok(cpu.mem8.slice(0x4000, 0x4000 + 1000).every(x => x === 0x5A));

        entry(cpu, [0xF3, 0xAA, 0xF4]);
        cpu.reg32[1] = 0;
        const empty_before = work(cpu);
        cpu.run_cpu_slice(100);
        assert.equal(work(cpu) - empty_before, 2);
    }
    finally { await emulator.destroy(); }
});

await test("STI shadow permits its successor before pending IPI, without duplicate retirement", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        interrupt(cpu, 0x50);
        entry(cpu, [0xFB, 0x40, 0xF4]); // sti; inc ax; hlt
        cpu.reg32[0] = 0;
        cpu.write32(0xFEE000F0, 0x1FF);
        cpu.write32(0xFEE00300, 0x40050); // fixed self IPI, initially IF=0
        const before = work(cpu);
        cpu.run_cpu_slice(1);
        assert.equal(work(cpu) - before, 1);
        assert.equal(cpu.instruction_pointer[0], 0x1001);
        assert.equal(cpu.reg32[0], 0);
        cpu.run_cpu_slice(1);
        assert.equal(cpu.reg32[0], 1);
        assert.equal(cpu.instruction_pointer[0], 0x1200);
        assert.equal(work(cpu) - before, 2, "IPI delivery is not an instruction");
        cpu.run_cpu_slice(1);
        assert.equal(work(cpu) - before, 3);
    }
    finally { await emulator.destroy(); }
});

await test("REP preserves completed elements before a same-dispatch page fault", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0x67, 0xF3, 0xAA, 0xF4]); // address16 REP STOSB uses the element path
        const memory = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        const set32 = (address, value) => memory.setUint32(address, value >>> 0, true);
        set32(0x3008, 0xFFFF);
        set32(0x300C, 0xCF9B00); // flat ring-0 32-bit code
        set32(0x3010, 0xFFFF);
        set32(0x3014, 0xCF9300); // flat ring-0 32-bit data
        cpu.gdtr_offset[0] = 0x3000;
        cpu.gdtr_size[0] = 23;
        cpu.idtr_offset[0] = 0x2000;
        cpu.idtr_size[0] = 0x7FF;
        set32(0x2000 + 14 * 8, 0x81200);
        set32(0x2004 + 14 * 8, 0x8E00); // #PF -> 08:1200
        cpu.mem8[0x1200] = 0xF4;
        set32(0x10000, 0x11003);
        for(let page = 0; page < 256; page++) set32(0x11000 + page * 4, page << 12 | 3);
        set32(0x11000 + 5 * 4, 0); // 0x5000 absent, five elements beyond 0x4FFB
        cpu.cr[0] = 0x80010011 | 0;
        cpu.cr[3] = 0x10000;
        cpu.protected_mode[0] = cpu.is_32[0] = cpu.stack_size_32[0] = 1;
        cpu.segment_offsets.fill(0, 0, 6);
        cpu.segment_limits.fill(-1, 0, 6);
        cpu.segment_is_null.fill(0, 0, 6);
        cpu.sreg.set([16, 8, 16, 16, 16, 16]);
        cpu.segment_access_bytes.set([0x93, 0x9B, 0x93, 0x93, 0x93, 0x93]);
        cpu.reg32[0] = 0x5A;
        cpu.reg32[1] = 10;
        cpu.reg32[7] = 0x4FFB;
        cpu.update_state_flags();
        cpu.full_clear_tlb();
        const before = work(cpu);
        cpu.run_cpu_slice(1);
        assert.equal(cpu.cr[2], 0x5000);
        assert.equal(cpu.instruction_pointer[0], 0x1200);
        assert.equal(cpu.reg32[1], 5);
        assert.equal(cpu.reg32[7], 0x5000);
        assert.equal(work(cpu) - before, 5);
        assert.deepEqual(Array.from(cpu.mem8.slice(0x4FFB, 0x5001)), [0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0]);
    }
    finally { await emulator.destroy(); }
});

await test("PIO PM polling observes prior commits inside a single Wasm slice", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        const acpi = cpu.devices.acpi;
        acpi.pci_config[0x40 >> 2] = 0x601;
        acpi.pci_config[0x80 >> 2] |= 1;
        acpi.update_pm_decode();
        entry(cpu, [0xBA, 0x08, 0x06, 0xBF, 0x00, 0x40, 0xB9, 8, 0,
            0x66, 0xED, 0x66, 0xAB, 0xE2, 0xFA, 0xF4]);
        const before = work(cpu);
        cpu.run_cpu_slice(1000);
        assert.equal(work(cpu) - before, 28);
        const samples = Array.from(new Uint32Array(cpu.mem8.buffer, cpu.mem8.byteOffset + 0x4000, 8));
        assert.ok(samples[0] > 0);
        for(let i = 1; i < samples.length; i++) assert.ok(samples[i] > samples[i - 1]);
        assert.equal(acpi.pm_read(8, 4), acpi.pm_read(8, 4), "host reads do not create guest work");
    }
    finally { await emulator.destroy(); }
});

await test("paused snapshot restores virtual time, pending progress and RTC calendar", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0x90, 0x90, 0xF4]);
        cpu.run_cpu_slice(100);
        cpu.clock.pause();
        const saved_time = cpu.clock.now();
        const saved_wall = cpu.clock.wall_time();
        const saved_work = work(cpu);
        const saved = await emulator.save_state();
        cpu.clock.resume();
        entry(cpu, [0x90, 0xF4]);
        cpu.run_cpu_slice(100);
        assert.ok(cpu.clock.now() > saved_time);
        cpu.clock.pause();
        await emulator.restore_state(saved);
        assert.equal(cpu.clock.now(), saved_time);
        assert.equal(cpu.clock.wall_time(), saved_wall);
        assert.equal(work(cpu), saved_work);
        assert.equal(cpu.clock.paused, true);
        cpu.clock.advance_to(1000);
        assert.equal(cpu.clock.now(), saved_time);
        cpu.clock.resume();
        entry(cpu, [0x90, 0xF4]);
        cpu.run_cpu_slice(100);
        assert.equal(work(cpu), saved_work + 2);
    }
    finally { await emulator.destroy(); }
});

await test("repeated per-core TSC writes use machine ticks, including nonzero initial offsets", async () => {
    const emulator = await machine(2);
    try
    {
        const cpu = emulator.v86.cpu;
        cpu.clock.advance_instructions(1000);
        for(let core = 0; core < 2; core++)
        {
            cpu.switch_core(core);
            cpu.set_tsc(100 + core, 0);
            cpu.store_current_tsc();
            assert.equal(cpu.current_tsc[0], 100 + core);
            cpu.set_tsc(200 + core, 0);
            cpu.store_current_tsc();
            assert.equal(cpu.current_tsc[0], 200 + core);
        }
        cpu.clock.advance_instructions(1000);
        cpu.switch_core(0);
        cpu.set_tsc(400, 0);
        cpu.store_current_tsc();
        assert.equal(cpu.current_tsc[0], 400);
    }
    finally { await emulator.destroy(); }

    let host = 0;
    const normal = await machine(1, { cpu_clock: { mode: "normal", now: () => host } });
    try
    {
        const cpu = normal.v86.cpu;
        host = 100;
        cpu.reboot_internal(); // reset stores a nonzero machine-time offset
        cpu.set_tsc(321, 0);
        cpu.store_current_tsc();
        assert.equal(cpu.current_tsc[0], 321);
    }
    finally { await normal.destroy(); }
});

await test("guest CF9 reset yields the active instruction before resetting commit state", async () => {
    const emulator = await machine(2);
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0xBA, 0xF9, 0x0C, 0xB0, 6, 0xEE, 0x40, 0xF4]);
        const before = work(cpu);
        cpu.run_cpu_slice(100);
        assert.equal(cpu.active_core, 0);
        assert.equal(cpu.instruction_pointer[0], 0xFFFF0, "reset occurs at the safe return boundary");
        assert.equal(work(cpu) - before, 3, "the resetting OUT retires once, successor does not execute");
        assert.deepEqual(cpu.cores.map(core => core.running), [true, false]);
        assert.equal(cpu.clock.paused, false);
    }
    finally { await emulator.destroy(); }
});

await test("guest programs PIT then halts without jumping to an obsolete 100ms deadline", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        entry(cpu, [0xB0, 0x34, 0xE6, 0x43, // counter0 periodic, low/high
            0xB0, 17, 0xE6, 0x40, 0xB0, 0, 0xE6, 0x40, 0xF4]);
        cpu.run_cores();
        assert.equal(cpu.in_hlt[0], 1);
        assert.equal(work(cpu), 7);
        assert.equal(cpu.clock.now(), 0.007, "executing then halting does not use the earlier deadline");
        cpu.run_cores();
        assert.ok(cpu.clock.now() > 0.007 && cpu.clock.now() < 0.1, "idle round uses the newly programmed PIT");
    }
    finally { await emulator.destroy(); }
});

await test("normal-mode save and restore freeze one timestamp across all devices", async () => {
    let host = 0;
    const epoch = 946684800000;
    const emulator = await machine(1, { cpu_clock: { mode: "normal", now: () => host, wall_epoch_ms: epoch } });
    try
    {
        const cpu = emulator.v86.cpu;
        // Advancing this source on each sample exposes any unfrozen time reads
        // during serialization. It models host time spent collecting devices.
        cpu.clock.host_now = () => ++host;
        const saved = await emulator.save_state();
        const header = new Int32Array(saved, 0, 4);
        const state = JSON.parse(new TextDecoder().decode(new Uint8Array(saved, 16, header[3]))).state;
        const saved_time = state[95][2];
        assert.equal(state[47][2], epoch + saved_time, "RTC matches the saved machine timestamp");
        assert.equal(state[50][5], Math.floor(saved_time * 3579.545), "PM matches that same timestamp");
        assert.equal(cpu.clock.paused, false, "saving keeps the prior run/pause lifecycle");
        await emulator.restore_state(saved);
        assert.equal(cpu.clock.time_ms, saved_time, "restore excludes its host-side processing time");
        assert.equal(cpu.devices.rtc.rtc_time, epoch + saved_time);
        assert.equal(cpu.devices.acpi.timer_last, state[50][5]);
        assert.equal(cpu.clock.paused, false);
    }
    finally { await emulator.destroy(); }
});

await test("legacy UTC RTC and host-monotonic timer snapshots rebase without host-age delay", async () => {
    const emulator = await machine();
    try
    {
        const cpu = emulator.v86.cpu;
        cpu.clock.advance_instructions(25000);
        cpu.devices.rtc.cmos_index = 0xB;
        cpu.devices.rtc.cmos_port_write(0x42);
        cpu.devices.pit.port43_write(0x34);
        cpu.devices.pit.counter_write(0, 0xA9);
        cpu.devices.pit.counter_write(0, 4);
        cpu.clock.pause();
        const rtc_time = cpu.devices.rtc.rtc_time;
        const interval = cpu.devices.rtc.next_interrupt - cpu.clock.now();
        const saved = await emulator.save_state();
        cpu.clock.resume();
        cpu.clock.advance_instructions(5000000);
        cpu.clock.pause();
        const destination_time = cpu.clock.now();
        const set_state = cpu.set_state.bind(cpu);
        cpu.set_state = state => {
            // Emulate the positional format from before the machine clock, not merely a modern state
            // with optional slots removed: RTC deadlines were host UTC and
            // PIT/LAPIC anchors were unrelated host performance.now values.
            const epoch = state[47][2] - state[47][3];
            state[47][3] += epoch;
            state[47][4] += epoch;
            state[47].length = 15;
            state[58][7].fill(1000000000);
            const lapic = new DataView(state[46].buffer, state[46].byteOffset);
            lapic.setUint32(8, 0, true); // divider shift
            lapic.setUint32(12, 1000000, true);
            lapic.setUint32(16, 1000000, true);
            lapic.setFloat64(24, 1000000000, true);
            lapic.setUint32(32, 0x50, true);
            lapic.setUint32(160, 0x1FF, true);
            state.length = 95;
            set_state(state);
        };
        await emulator.restore_state(saved);
        assert.equal(cpu.clock.now(), destination_time);
        assert.equal(cpu.clock.wall_time(), rtc_time);
        assert.equal(cpu.devices.rtc.rtc_time, rtc_time);
        assert.equal(cpu.devices.rtc.next_interrupt - cpu.clock.now(), interval);
        assert.ok(cpu.devices.pit.counter_start_time.every(time => time === destination_time));
        assert.equal(cpu.read32s(0xFEE00390), 1000000, "restored LAPIC count is immediately meaningful");
        cpu.clock.resume();
        cpu.clock.advance_to(destination_time + 1);
        cpu.run_hardware_timers(true, cpu.clock.now());
        assert.equal(cpu.read32s(0xFEE00390), 0, "old host age does not postpone the restored timer");
    }
    finally { await emulator.destroy(); }
});

await test("fixed image, inputs and seed repeat IRQ sequence, PM samples and serial output", async () => {
    const run = async () => {
        const emulator = await machine(2);
        try
        {
            const cpu = emulator.v86.cpu;
            const irqs = [];
            let serial = "";
            emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
            const raise = cpu.device_raise_irq;
            cpu.device_raise_irq = irq => { irqs.push([cpu.clock.now(), irq]); raise(irq); };
            const acpi = cpu.devices.acpi;
            acpi.pci_config[0x40 >> 2] = 0x601;
            acpi.pci_config[0x80 >> 2] |= 1;
            acpi.update_pm_decode();
            cpu.devices.pit.port43_write(0x34);
            cpu.devices.pit.counter_write(0, 17);
            cpu.devices.pit.counter_write(0, 0);
            entry(cpu, [0xBA, 0x08, 0x06, 0xBF, 0x00, 0x40, 0xB9, 64, 0,
                0x66, 0xED, 0x66, 0xAB, 0xE2, 0xFA,
                0xBA, 0xF8, 0x03, 0xB0, 0x4B, 0xEE, 0xB0, 0x0A, 0xEE, 0xF4]);
            for(let round = 0; round < 20; round++) cpu.run_cores();
            const samples = Array.from(new Uint32Array(cpu.mem8.buffer, cpu.mem8.byteOffset + 0x4000, 64));
            assert.ok(irqs.some(e => e[1] === 0));
            assert.equal(serial, "K\n");
            assert.equal(cpu.in_hlt[0], 1);
            return { irqs, samples, serial, work: work(cpu), time: cpu.clock.now() };
        }
        finally { await emulator.destroy(); }
    };
    assert.deepEqual(await run(), await run());
});

console.log(JSON.stringify({ suite: "machine-clock-execution", passed }));
                                                                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/smp/coherence.asm                                                                  0000644 0000000 0000000 00000012175 00000000000 014270  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Cooperative SMP coherence gate. The harness starts independent protected-
; mode contexts; INIT/SIPI itself is covered by ap_startup.asm. All sharing,
; atomics, code modification, page-table changes and shootdown IPIs below are
; guest instructions. EDI = core ID, CONTROL = {cores, iterations}.
bits 32
org 0x100000
%define CONTROL 0x380000
%define TOTAL CONTROL + 8
%define GUARDED CONTROL + 12
%define LOCKWORD CONTROL + 16
%define FINISHED CONTROL + 20
%define PHASE CONTROL + 24
%define SHOOT CONTROL + 28
%define OLD_SEEN CONTROL + 32
%define NEW_SEEN CONTROL + 36
%define SMC_SEEN CONTROL + 40
%define ERROR CONTROL + 44
%define RECORDS CONTROL + 0x100
%define UNALIGNED 0x390FFF
%define CMP64 0x391FFD
%define IDT 0x280000
%define PD 0x200000
%define VIRTUAL 0x40000000
%define ALIAS 0x50000000
%define LAPIC 0xFEE00000

header:
    dd 0x1BADB002, 0x10000, -(0x1BADB002 + 0x10000)
    dd header, header, end, end, start

start:
    cli
    cld
    mov esi, edi
    lgdt [gdtr]
    jmp 8:protected
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    lea esp, [esi + 1]
    shl esp, 16
    add esp, 0x300000
    mov al, 0xFF
    out 0x21, al
    out 0xA1, al

    mov ebp, esi
    shl ebp, 12
    add ebp, PD
    mov edi, ebp
    mov ecx, 1024
    xor eax, eax
    rep stosd
    mov dword [ebp], 0x83
    mov dword [ebp + (VIRTUAL >> 22) * 4], 0x400083
    mov dword [ebp + (LAPIC >> 22) * 4], 0xFEC00083
    cmp esi, 1
    jne .no_alias
    mov eax, hot_function
    or eax, 3
    mov [0x220000], eax
    mov dword [ebp + (ALIAS >> 22) * 4], 0x220003
.no_alias:
    mov cr3, ebp
    mov eax, cr4
    or eax, 1 << 4
    mov cr4, eax
    mov eax, cr0
    or eax, 1 << 31
    mov cr0, eax
    mov dword [LAPIC + 0xF0], 0x1FF
    mov dword [LAPIC + 0x350], 0x10000
    cmp esi, 1
    jne .alias_warmed
    mov eax, [ALIAS]                ; cache alias before core 0 compiles it
.alias_warmed:

    mov ebp, esi
    shl ebp, 6
    add ebp, RECORDS
    mov edi, [CONTROL + 4]
.atomic:
    mov eax, 1
    lock xadd [TOTAL], eax
    add [ebp + 4], eax              ; sum all returned tickets in host
    lock inc dword [UNALIGNED]      ; crosses a 4 KiB page boundary
.acquire:
    mov eax, 1
    xchg eax, [LOCKWORD]            ; implicit LOCK
    test eax, eax
    jnz .acquire
    inc dword [GUARDED]
    mov dword [LOCKWORD], 0
.retry64:
    mov eax, [CMP64]
    mov edx, [CMP64 + 4]
    mov ebx, eax
    mov ecx, edx
    add ebx, 1
    adc ecx, 0
    lock cmpxchg8b [CMP64]           ; unaligned and spans two pages
    jnz .retry64
    dec edi
    jnz .atomic
    lock inc dword [FINISHED]
.barrier:
    mov eax, [FINISHED]
    cmp eax, [CONTROL]
    jne .barrier                   ; shared load must observe another core
    cmp esi, 0
    je primary
    cmp esi, 1
    je modifier
.other:
    cmp dword [PHASE], 6
    jne .other
    jmp done

primary:
    mov edi, IDT
    mov ecx, 256
    mov eax, unexpected
    mov ebx, eax
    and eax, 0xFFFF
    or eax, 8 << 16
    and ebx, 0xFFFF0000
    or ebx, 0x8E00
.idt:
    stosd
    xchg eax, ebx
    stosd
    xchg eax, ebx
    loop .idt
    mov eax, shootdown
    mov word [IDT + 0x70 * 8], ax
    shr eax, 16
    mov word [IDT + 0x70 * 8 + 6], ax
    lidt [idtr]
    mov ecx, 8192
.warm:
    call hot_function
    dec ecx
    jnz .warm
.wait_compiled:
    call hot_function
    cmp dword [CONTROL + 52], 0
    je .wait_compiled
    mov dword [PHASE], 1
.wait_smc:
    cmp dword [PHASE], 2
    jne .wait_smc
    xor eax, eax
    cpuid                          ; architecturally serialize modified code
    call hot_function
    mov [SMC_SEEN], eax
    mov eax, [VIRTUAL]             ; populate this core's translation
    mov dword [PHASE], 3
.wait_remap:
    cmp dword [PHASE], 4
    jne .wait_remap
    mov eax, [VIRTUAL]             ; must still use OLD translation
    mov [OLD_SEEN], eax
    mov dword [PHASE], 5
    sti
.wait_shoot:
    cmp dword [SHOOT], 0
    je .wait_shoot
    cli
    mov eax, [VIRTUAL]             ; now INVLPG made the new PDE visible
    mov [NEW_SEEN], eax
    mov dword [PHASE], 6
    jmp done

modifier:
.wait_hot:
    cmp dword [PHASE], 1
    jne .wait_hot
    cmp dword [CONTROL + 48], 0
    jne .dma_wrote
    mov dword [ALIAS + 1], 0x22222222
.dma_wrote:
    mov dword [PHASE], 2
.wait_tlb:
    cmp dword [PHASE], 3
    jne .wait_tlb
    mov dword [PD + (VIRTUAL >> 22) * 4], 0x800083
    mov dword [PHASE], 4
.wait_stale:
    cmp dword [PHASE], 5
    jne .wait_stale
    mov dword [LAPIC + 0x310], 0
    mov dword [LAPIC + 0x300], 0x70
.wait_done:
    cmp dword [PHASE], 6
    jne .wait_done

done:
    lea eax, [esi + 0xD0D0]
    mov [ebp], eax
.halt:
    hlt
    jmp .halt

shootdown:
%ifndef SKIP_SHOOTDOWN
    invlpg [VIRTUAL]
%endif
    inc dword [SHOOT]
    mov dword [LAPIC + 0xB0], 0
    iretd
unexpected:
    mov dword [ERROR], 1
    cli
    hlt
    jmp unexpected

align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr:
    dw $ - gdt - 1
    dd gdt
idtr:
    dw 256 * 8 - 1
    dd IDT

; Use a distinct executable physical page to detect stale code after a write
; by a core whose local TLB has never executed or marked that page as code.
align 4096
hot_function:
    mov eax, 0x11111111
    ret
end:
                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/smp/coherence.mjs                                                                  0000644 0000000 0000000 00000020413 00000000000 014273  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { setImmediate as set_immediate } from "node:timers";
import { fileURLToPath } from "node:url";
import { smp_modes, with_smp_mode, compiled_hits, published } from "../lib/smp_modes.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const mutation = process.env.SMP_MUTATION || "";
assert.ok(["", "flush-on-switch", "no-shootdown"].includes(mutation));
const kernel = root + `build/smp/coherence${mutation ? "-" + mutation : ""}.bin`;
fs.mkdirSync(root + "build/smp", { recursive: true });
const assembled = spawnSync("nasm", [...(mutation === "no-shootdown" ? ["-DSKIP_SHOOTDOWN"] : []), "-f", "bin", "-o", kernel, root + "tests/smp/coherence.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);
const CONTROL = 0x380000;
const RECORDS = CONTROL + 0x100;
const OLD = 0xA5A51111;
const NEW = 0x5A5A2222;
const seeds = process.env.SMP_SEEDS ? process.env.SMP_SEEDS.split(",").map(Number) : Array.from({ length: 10 }, (_, i) => i + 1);
const modes = smp_modes();
const quantums = process.env.SMP_QUANTUMS?.split(",").map(Number) || [17, 257, 4096];

async function run(cores, seed, quantum, mode, writer = "guest", asynchronous = false)
{
    const iterations = 128 + seed * 7;
    const emulator = new V86(with_smp_mode({
        graphics_adapter: "bochs_vga",
        multiboot: { url: kernel },
        memory_size: 16 << 20,
        acpi: true,
        cpu_cores: cores,
        cpu_quantum: quantum,
        cpu_schedule_seed: seed,
        disable_jit: mode === "interpreter",
        experimental_smp_jit: true,
        ir_sync_publication: !asynchronous,
        autostart: false,
        log_level: 0,
    }, mode));
    const label = `${mode} cores=${cores} seed=${seed} quantum=${quantum} writer=${writer} async=${asynchronous}`;
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const cpu = emulator.v86.cpu;
        const e = cpu.wm.exports;
        const memory = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        const word = address => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(address, true);
        memory.setUint32(CONTROL, cores, true);
        memory.setUint32(CONTROL + 4, iterations, true);
        memory.setUint32(CONTROL + 52, mode === "interpreter" ? 1 : 0, true);
        memory.setUint32(0x400000, OLD, true);
        memory.setUint32(0x800000, NEW, true);
        memory.setUint32(0x391FFD, 0xFFFFFF00, true);
        memory.setUint32(0x392001, 0x12345678, true);
        // Only establish independent entry contexts. The guest performs all
        // coherence operations; the harness never flushes a runtime TLB.
        const switch_core = cpu.switch_core.bind(cpu);
        let dma_wrote = false;
        cpu.switch_core = id => {
            switch_core(id);
            if(mutation === "flush-on-switch") cpu.full_clear_tlb();
            if(writer === "dma" && id === 1 && word(CONTROL + 24) === 1 && !dma_wrote)
            {
                // Use the same physical RAM write barrier as DMA/IDE/virtio.
                // The guest sees completion and skips its own SMC store.
                cpu.write_blob(Uint8Array.of(0x33, 0x33, 0x33, 0x33), 0x101001);
                new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).setUint32(CONTROL + 48, 1, true);
                dma_wrote = true;
            }
        };
        const entry = cpu.save_core_state();
        for(let id = 0; id < cores; id++)
        {
            cpu.switch_core(id);
            cpu.load_core_state(entry);
            cpu.reg32[7] = id;
            cpu.cores[id].running = true;
        }
        cpu.switch_core(0);
        const deadline = performance.now() + 30000;
        let rounds = 0;
        let hot_hits = 0;
        let max_slice = 0;
        while(Array.from({ length: cores }, (_, id) => word(RECORDS + id * 64)).some((value, id) => value !== 0xD0D0 + id))
        {
            assert.equal(word(CONTROL + 44), 0, `${label}: unexpected guest exception`);
            if(performance.now() >= deadline) throw new Error(`${label}: timeout phase=${word(CONTROL + 24)} diagnostics=${JSON.stringify(cpu.get_diagnostics())}`);
            const before_steps = cpu.cores.map(core => core.steps);
            cpu.run_cores();
            for(let id = 0; id < cores; id++)
            {
                const slice = cpu.cores[id].steps - before_steps[id];
                max_slice = Math.max(max_slice, slice);
                // JIT polls occur at block/activation boundaries. For this
                // fixture allow one 256-step activation beyond the request;
                // the interpreter only permits STI's one shadow instruction.
                assert.ok(slice <= quantum + (mode === "interpreter" ? 1 : 256), `${label}: bounded core ${id} slice (${slice})`);
            }
            // (the page tier counts no calls per function: its native
            // instructions, once the page has one)
            if(published(e, 0x101000)) hot_hits = Math.max(hot_hits, e.x64_page_stat(1) >>> 0);
            if(hot_hits > 0) new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).setUint32(CONTROL + 52, 1, true);
            rounds++;
            if((rounds & (asynchronous ? 7 : 127)) === 0) await new Promise(resolve => set_immediate(resolve));
        }
        const total = cores * iterations;
        assert.equal(word(CONTROL + 8), total, `${label}: LOCK XADD counter`);
        assert.equal(word(CONTROL + 12), total, `${label}: implicit XCHG spinlock`);
        assert.equal(word(0x390FFF), total, `${label}: cross-page LOCK INC`);
        assert.equal(word(0x391FFD), (0xFFFFFF00 + total) >>> 0, `${label}: unaligned cross-page CMPXCHG8B`);
        assert.equal(word(0x392001), 0x12345678 + Math.floor((0xFFFFFF00 + total) / 0x100000000), `${label}: CMPXCHG8B high-word carry`);
        const tickets = Array.from({ length: cores }, (_, id) => word(RECORDS + id * 64 + 4)).reduce((a, b) => a + b, 0);
        assert.equal(tickets, total * (total - 1) / 2, `${label}: unique XADD tickets`);
        assert.equal(word(CONTROL + 32), OLD, `${label}: remote PTE write does not flush another core's TLB`);
        assert.equal(word(CONTROL + 36), NEW, `${label}: IPI + INVLPG publishes new mapping`);
        assert.equal(word(CONTROL + 40), writer === "dma" ? 0x33333333 : 0x22222222, `${label}: cross-core SMC invalidates compiled code`);
        if(writer === "dma") assert.equal(dma_wrote, true, `${label}: DMA writer ran`);
        assert.equal(word(CONTROL + 28), 1, `${label}: exactly one shootdown IPI`);
        const hits = compiled_hits(e);
        if(mode !== "interpreter")
        {
            assert.ok(hits > 0, `${label}: compiled code must actually execute: ${JSON.stringify(cpu.get_jit_info().ir)}`);
            assert.ok(hot_hits > 0, `${label}: the modified function must execute from compiled code before SMC`);
        }
        else assert.equal(hits, 0, `${label}: interpreter reference has no JIT hits`);
        return { rounds, hits, max_slice };
    }
    finally
    {
        await emulator.destroy();
    }
}

let cases = 0;
for(const mode of modes)
{
    let hits = 0;
    let max_slice = 0;
    for(const quantum of quantums)
    {
        for(const seed of seeds)
        {
            const result = await run(2, seed, quantum, mode);
            hits += result.hits;
            max_slice = Math.max(max_slice, result.max_slice);
            cases++;
        }
        console.log(`${mode}: ${seeds.length} seeds × 2 cores × quantum ${quantum}: LOCK/XCHG/CMPXCHG8B, cross-core SMC, stale TLB and IPI shootdown passed`);
    }
    for(const cores of [4, 8])
    {
        const result = await run(cores, 1, 257, mode);
        hits += result.hits;
        cases++;
    }
    hits += (await run(2, 1, 257, mode, "dma")).hits;
    cases++;
    if(mode !== "interpreter")
    {
        hits += (await run(2, 1, 257, mode, "guest", true)).hits;
        cases++;
    }
    console.log(`${mode}: 4/8-core coherence, DMA physical writer and publication variants passed; compiled activations=${hits}, maximum observed slice=${max_slice}`);
}
console.log(`SMP coherence: ${cases} cases passed`);
                                                                                                                                                                                                                                                     source/v64/tests/smp/core_statistics.mjs                                                            0000644 0000000 0000000 00000027323 00000000000 015551  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Architectural counters across interpreter and page-tier execution.
// Initial protected-mode contexts are injected only to isolate accounting.
// All increments, REP progress, faults and halts come from guest instructions.
import assert from "node:assert/strict";
import { setImmediate as set_immediate } from "node:timers";
import { smp_modes, with_smp_mode, mode_hits } from "../lib/smp_modes.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const modes = smp_modes();
// SMP_CORES=1: CPU 0's program alone (IR Tier-0's REP template ran on one core
// only, until P7.5: its elements must count the same)
const fields = ["retired_instructions", "rep_elements", "faults", "halt_count", "runtime_ms"];
const specifications = [
    { loops: 2048, elements: 1000, destination: 0x40000, fault: "ud" },
    { loops: 2085, elements: 0, destination: 0x44000, fault: "none" },
    { loops: 2122, elements: 10, destination: 0x4FFB, fault: "pf" },
];
specifications.length = Number(process.env.SMP_CORES || specifications.length);
// (alone, CPU 0 loops long enough for the page tier to compile its page)
if(specifications.length === 1) specifications[0].loops = 1 << 18;
const u32 = value => [value & 255, value >>> 8 & 255, value >>> 16 & 255, value >>> 24];
const COMPARED = 24;

function guest(core)
{
    const { loops, elements, destination, fault } = specifications[core];
    return Uint8Array.from([
        0x90, 0x66, 0x90,                   // nop; prefixed nop: two instructions
        0xBF, ...u32(0x48000 + core),       // mov edi, ordinary STOSB destination
        0xB0, 0x5A, 0xAA,                  // mov al, 5A; stosb (not a REP element)
        0xB9, ...u32(loops), 0x31, 0xC0,   // mov ecx, loops; xor eax,eax
        0x40, 0x49, 0x75, 0xFC,            // inc eax; dec ecx; jnz: exactly 3N
        0xBE, ...u32(0x52000),              // mov esi, zeros
        0xBF, ...u32(0x53000),              // mov edi, zeros
        0xB9, ...u32(COMPARED),             // mov ecx, COMPARED
        0xF3, 0xA6,                        // repe cmpsb: COMPARED elements, all equal
        0xB9, ...u32(elements),             // mov ecx, REP count
        0xBF, ...u32(destination),          // mov edi, REP destination
        0xB0, 0x5A,                        // mov al, 5A
        ...(fault === "pf" ? [0x67] : []),// force address16 element path for #PF
        0xF3, 0xAA,                        // rep stosb: one retirement on completion
        ...(fault === "ud" ? [0x0F, 0x0B] : []),
        0xF4,                              // normal or exception-handler HLT
    ]);
}

function initialize(cpu)
{
    const memory = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const write = (address, value) => memory.setUint32(address, value >>> 0, true);
    write(0x28008, 0xFFFF); write(0x2800C, 0xCF9B00);
    write(0x28010, 0xFFFF); write(0x28014, 0xCF9300);
    for(const vector of [6, 14])
    {
        write(0x29000 + vector * 8, 0x80000);
        write(0x29004 + vector * 8, 0x38E00); // interrupt gate -> 08:00030000
    }
    cpu.mem8[0x30000] = 0xF4; // fault handler: hlt
    cpu.mem8.set([0x90, 0x90, 0xF4], 0x32000); // later snapshot mutation
    write(0x90000, 0x91003);
    for(let page = 0; page < 1024; page++) write(0x91000 + page * 4, page << 12 | 3);
    write(0x91000 + 5 * 4, 0); // REP on CPU 2 commits five bytes then faults
    for(let core = 0; core < specifications.length; core++)
    {
        cpu.switch_core(core);
        const ip = 0x10000 + core * 0x1000;
        cpu.mem8.set(guest(core), ip);
        cpu.reg32.fill(0);
        cpu.reg32[4] = 0x80000 - core * 0x1000;
        cpu.instruction_pointer[0] = cpu.previous_ip[0] = ip;
        cpu.flags[0] = 2;
        cpu.in_hlt[0] = 0;
        cpu.gdtr_offset[0] = 0x28000;
        cpu.gdtr_size[0] = 23;
        cpu.idtr_offset[0] = 0x29000;
        cpu.idtr_size[0] = 0x7FF;
        cpu.cr[0] = 0x80010011 | 0;
        cpu.cr[3] = 0x90000;
        cpu.cr[4] = 0;
        cpu.protected_mode[0] = cpu.is_32[0] = cpu.stack_size_32[0] = 1;
        cpu.segment_offsets.fill(0, 0, 6);
        cpu.segment_limits.fill(-1, 0, 6);
        cpu.segment_is_null.fill(0, 0, 6);
        cpu.sreg.set([16, 8, 16, 16, 16, 16]);
        cpu.segment_access_bytes.set([0x93, 0x9B, 0x93, 0x93, 0x93, 0x93]);
        cpu.update_state_flags();
        cpu.full_clear_tlb();
        cpu.cores[core].running = true;
    }
    cpu.switch_core(0);
}

function statistics(cpu)
{
    const diagnostics = cpu.get_diagnostics().cores;
    return diagnostics.map((core, id) => Object.fromEntries(fields.map((field, index) => {
        const value = cpu.wm.exports.core_statistics_get(id, index);
        assert.equal(core[field], value, `CPU ${id}: ${field} diagnostic agrees with counter`);
        return [field, value];
    })));
}

async function halted(cpu, label)
{
    const deadline = performance.now() + 15000;
    let rounds = 0;
    while(cpu.get_diagnostics().cores.some(core => core.state !== "halted"))
    {
        assert.ok(performance.now() < deadline, `${label}: guest timed out ${JSON.stringify(cpu.get_diagnostics())}`);
        cpu.run_cores();
        if(++rounds % 16 === 0) await new Promise(resolve => set_immediate(resolve));
    }
    return rounds;
}

for(const mode of modes)
{
    const emulator = new V86(with_smp_mode({
        graphics_adapter: "bochs_vga",
        wasm_path: process.env.WASM_PATH,
        memory_size: 16 << 20, acpi: true, cpu_cores: specifications.length,
        cpu_quantum: 17, cpu_schedule_seed: 42,
        disable_jit: mode === "interpreter", experimental_smp_jit: true, ir_sync_publication: true,
        autostart: false, log_level: 0,
    }, mode));
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const cpu = emulator.v86.cpu;
        const ex = cpu.wm.exports;
        assert.equal(typeof ex.core_statistics_get, "function", "rebuild Wasm with architectural statistics exports");
        initialize(cpu);
        const hits = () => mode_hits(ex, mode);
        const per_core_hits = specifications.map(() => 0);
        const run_cpu_slice = cpu.run_cpu_slice.bind(cpu);
        cpu.run_cpu_slice = budget => {
            const core = cpu.active_core;
            const before = hits();
            const result = run_cpu_slice(budget);
            per_core_hits[core] += (hits() - before) >>> 0;
            return result;
        };
        const hits_before = hits();
        cpu.clock.resume();
        const rounds = await halted(cpu, mode);
        cpu.clock.pause();
        // (one core does not run through run_cpu_slice: all hits are its)
        if(specifications.length === 1) per_core_hits[0] = (hits() - hits_before) >>> 0;
        const original = statistics(cpu);
        for(let core = 0; core < specifications.length; core++)
        {
            const specification = specifications[core];
            const expected = {
                retired_instructions: specification.loops * 3 + (specification.fault === "pf" ? 15 : 16),
                rep_elements: COMPARED + (specification.fault === "pf" ? 5 : specification.elements),
                faults: specification.fault === "none" ? 0 : 1,
                halt_count: 1,
            };
            for(const field of Object.keys(expected))
            {
                assert.equal(original[core][field], expected[field], `${mode} CPU ${core}: exact ${field}`);
            }
            assert.ok(original[core].runtime_ms > 0, `${mode} CPU ${core}: measured execution time`);
            assert.equal(cpu.mem8[0x48000 + core], 0x5A, "ordinary STOSB executed but is not a REP element");
            cpu.switch_core(core);
            assert.equal(cpu.reg32[0], (specification.loops & ~255) | 0x5A, "arithmetic loop reached its exact terminal value");
            assert.equal(cpu.reg32[1], specification.fault === "pf" ? 5 : 0, "REP remaining count");
            if(specification.fault === "pf") assert.equal(cpu.cr[2], 0x5000, "fault occurs after five successful REP elements");
            if(mode !== "interpreter") assert.ok(per_core_hits[core] > 0, `${mode} CPU ${core}: compiled code really executed`);
        }
        assert.ok(cpu.mem8.slice(0x40000, 0x40000 + 1000).every(byte => byte === 0x5A), "completed REP committed all 1000 stores");
        if(specifications.length > 2) assert.deepEqual(Array.from(cpu.mem8.slice(0x4FFB, 0x5001)), [0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0]);
        if(mode === "interpreter")
        {
            assert.equal(ex.x64_page_stat(1), 0);
            assert.ok(cpu.cores[0].steps > original[0].retired_instructions,
                "REP continuation and fault dispatches must not inflate architectural retirement");
        }
        if(specifications.length === 1)
        {
            // (the snapshot checks below are about separate cores)
            console.log(`${mode}, one core: exact statistics passed ${JSON.stringify({ per_core_hits, counters: original })}`);
            continue;
        }

        const saved = await emulator.save_state();
        cpu.switch_core(1);
        cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x32000;
        cpu.in_hlt[0] = 0;
        cpu.clock.resume();
        await halted(cpu, `${mode} snapshot mutation`);
        cpu.clock.pause();
        const changed = statistics(cpu);
        assert.deepEqual(changed[0], original[0], "executing CPU 1 does not charge CPU 0");
        assert.deepEqual(changed[2], original[2], "executing CPU 1 does not charge CPU 2");
        assert.equal(changed[1].retired_instructions, original[1].retired_instructions + 3);
        assert.equal(changed[1].halt_count, original[1].halt_count + 1);
        assert.ok(changed[1].runtime_ms > original[1].runtime_ms);
        await emulator.restore_state(saved);
        assert.deepEqual(statistics(cpu), original, "whole-machine snapshot restores every core's exact counters and runtime");
        cpu.reboot_internal();
        assert.deepEqual(statistics(cpu), specifications.map(() => Object.fromEntries(fields.map(field => [field, 0]))),
            "machine reset clears all counters including APs and accumulated runtime");
        console.log(`${mode}: exact per-core statistics, successful/empty/faulting REP, ordinary STOSB, #UD/#PF, HLT, snapshot/reset passed ${JSON.stringify({ rounds, per_core_hits, counters: original })}`);
    }
    finally { await emulator.destroy(); }
}

// Snapshots predating the per-core extension have no statistics to restore.
// They must start at zero rather than inheriting the destination VM's history.
const legacy_vm = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: 1, memory_size: 16 << 20,
    wasm_path: process.env.WASM_PATH, disable_jit: true, autostart: false, log_level: 0 });
try
{
    await new Promise(resolve => legacy_vm.add_listener("emulator-loaded", resolve));
    const cpu = legacy_vm.v86.cpu;
    const run = () => {
        cpu.sreg[1] = cpu.segment_offsets[1] = 0;
        cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
        cpu.mem8.set([0x90, 0xF4], 0x1000);
        cpu.flags[0] = 2;
        cpu.in_hlt[0] = 0;
        cpu.full_clear_tlb();
        cpu.run_cpu_slice(4);
    };
    run();
    const saved = await legacy_vm.save_state();
    run();
    assert.equal(statistics(cpu)[0].retired_instructions, 4);
    const set_state = cpu.set_state.bind(cpu);
    cpu.set_state = state => {
        state.length = 96; // keep the clock, omit the optional per-core extension
        set_state(state);
    };
    await legacy_vm.restore_state(saved);
    assert.deepEqual(statistics(cpu)[0], Object.fromEntries(fields.map(field => [field, 0])),
        "legacy snapshot without counters cannot inherit destination execution history");
    console.log("legacy snapshot: missing per-core statistics restore as zero");
}
finally { await legacy_vm.destroy(); }
                                                                                                                                                                                                                                                                                                             source/v64/tests/smp/core_swap.asm                                                                  0000644 0000000 0000000 00000005523 00000000000 014316  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Fixture for tests/smp/core_swap.mjs: a multiboot kernel that two CPU
; contexts run on one machine while the harness switches between them at
; main-loop boundaries (CPU.save_core_state/load_core_state).
;
; The harness sets EDI to the context id (0 or 1) before the first slice.
; Each context maps virtual 0x40000000 to its own 4 MiB page, physical
; 0x400000 * (id + 1), so a TLB entry left over from the other context sends
; writes to the wrong physical page. The loop mixes integer, x87 and SSE work
; so that registers, lazy flags, the x87 stack (and its shadow cache) and XMM
; registers all have to travel with the context.

bits 32
org 0x100000

MB_MAGIC    equ 0x1BADB002
MB_FLAGS    equ 0x10000             ; the address fields below are valid
ITERATIONS  equ 1500000
VIRTUAL     equ 0x40000000
RESULTS     equ 0x380000            ; 64 bytes per context

header:
    dd MB_MAGIC, MB_FLAGS, -(MB_MAGIC + MB_FLAGS)
    dd header, header, end, end, start

start:
    cli
    mov ebx, edi                    ; context id

    ; stack below 0x300000 + (id + 1) * 0x10000
    lea esp, [ebx + 1]
    shl esp, 16
    add esp, 0x300000

    ; page directory at 0x200000 + id * 0x1000: 4 MiB pages
    mov ebp, ebx
    shl ebp, 12
    add ebp, 0x200000
    mov edi, ebp
    mov ecx, 1024
    xor eax, eax
    rep stosd
    mov dword [ebp], 0x83           ; 0..4 MiB identity (present, writable, 4 MiB)
    lea eax, [ebx + 1]
    shl eax, 22
    or eax, 0x83
    mov [ebp + (VIRTUAL >> 22) * 4], eax

    mov cr3, ebp
    mov eax, cr4
    or eax, (1 << 4) | (1 << 9) | (1 << 10)     ; PSE, OSFXSR, OSXMMEXCPT
    mov cr4, eax
    mov eax, cr0
    and eax, ~(1 << 2)                          ; no x87 emulation
    or eax, (1 << 31) | (1 << 1)                ; paging, MP
    mov cr0, eax

    fninit
    fldcw [control]                 ; double precision, as Windows uses: the x87
                                    ; shadow cache (fast math) is live across slices
    fld1
    xorps xmm0, xmm0
    lea eax, [ebx + 1]
    cvtsi2ss xmm1, eax
    shufps xmm1, xmm1, 0            ; xmm1 = id + 1 in every lane

    mov esi, VIRTUAL
    mov ecx, ITERATIONS
    xor eax, eax
.loop:
    imul eax, eax, 33
    add eax, ecx
    add eax, ebx
    mov edx, ecx
    and edx, 1023
    xor eax, [esi + edx * 4]
    mov [esi + edx * 4], eax
    fmul qword [factor]             ; st0 = 1.0000001 ** n: every lost update shows
    addps xmm0, xmm1
    dec ecx
    jnz .loop

    mov edi, ebx
    shl edi, 6
    add edi, RESULTS
    mov [edi], eax
    fstp qword [edi + 8]
    movups [edi + 16], xmm0
    xor eax, eax
    xor ecx, ecx
.sum:
    add eax, [esi + ecx * 4]
    inc ecx
    cmp ecx, 1024
    jne .sum
    mov [edi + 32], eax
    lea eax, [ebx + 0xD0D0]
    mov [edi + 36], eax             ; done marker
.halt:
    hlt
    jmp .halt

align 8
control:    dw 0x027F
align 8
factor:     dq 1.0000001
end:
                                                                                                                                                                             source/v64/tests/smp/core_swap.mjs                                                                  0000755 0000000 0000000 00000014523 00000000000 014332  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Two CPU contexts on one machine, switched at main-loop boundaries with
// CPU.save_core_state/load_core_state: the mechanism cooperative
// multicore is built on. Each context must end exactly as when it runs alone,
// with the JIT (default) and the interpreter (DISABLE_JIT=1).
//
// The fixture (core_swap.asm) maps the same virtual page to a different
// physical page per context; a control run that keeps the TLB across switches
// must produce a difference, so the test is known to see cross-talk.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const { CORE_STATE_RANGES, STATE_OFFSETS } = await import("../../src/state_layout.js");

const KERNEL = __dirname + "/../../build/smp/core_swap.bin";
const RESULTS = 0x380000;
const PAGES = [0x400000, 0x800000];
const REG_EDI = 7;

async function machine()
{
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        multiboot: { url: KERNEL },
        memory_size: 32 * 1024 * 1024,
        autostart: false,
        disable_jit: +process.env.DISABLE_JIT,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    emulator.v86.cpu.clock.resume(); // explicit main_loop driver
    return emulator;
}

/** The entry state twice, with EDI = context id */
function initial_contexts(cpu)
{
    const entry = cpu.save_core_state();
    return [0, 1].map(id => {
        cpu.load_core_state(entry);
        cpu.reg32[REG_EDI] = id;
        return cpu.save_core_state();
    });
}

const u32 = (cpu, address) => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(address, true);
const done = (cpu, id) => u32(cpu, RESULTS + 64 * id + 36) === 0xD0D0 + id;

/** Run the contexts in `order` (lists of ids), one main-loop slice at a time */
function run(cpu, contexts, order)
{
    const slices = [0, 0];
    const sequence = [];
    for(const ids of order)
    {
        for(let guard = 0; ids.some(id => !done(cpu, id)); guard++)
        {
            assert.ok(guard < 100000, "contexts did not finish");
            for(const id of ids)
            {
                if(done(cpu, id)) continue;
                cpu.load_core_state(contexts[id]);
                cpu.main_loop();
                contexts[id] = cpu.save_core_state();
                slices[id]++;
                sequence.push(id);
            }
        }
    }
    return { slices, sequence };
}

/** Core state read directly (x87 shadow written back first), independent of save_core_state */
function core_state(cpu)
{
    cpu.wm.exports["fpu_cache_barrier"]();
    const memory = new Uint8Array(cpu.wasm_memory.buffer);
    return CORE_STATE_RANGES.map(([start, end]) => Buffer.from(memory.slice(cpu.state_base + start, cpu.state_base + end)).toString("hex")).join("");
}

function outcome_of(cpu, id, state)
{
    return {
        results: Buffer.from(cpu.mem8.slice(RESULTS + 64 * id, RESULTS + 64 * id + 64)).toString("hex"),
        page: Buffer.from(cpu.mem8.slice(PAGES[id], PAGES[id] + 4096)).toString("hex"),
        state,
    };
}

const saved_state = saved => saved.map(bytes => Buffer.from(bytes).toString("hex")).join("");

const mode = +process.env.DISABLE_JIT ? "interpreter" : "JIT";

// Cached state flags (not core state) must follow the loaded core: an AP
// starts in real mode while the BSP runs in protected mode
{
    const m = await machine();
    const c = m.v86.cpu;
    const [a] = initial_contexts(c);
    c.load_core_state(a);
    c.is_32[0] = 0;
    c.stack_size_32[0] = 0;
    c.update_state_flags();
    const b = c.save_core_state();
    const state_flags = () => new Uint8Array(c.wasm_memory.buffer)[c.state_base + STATE_OFFSETS.state_flags];
    c.load_core_state(a);
    const flags_a = state_flags();
    c.load_core_state(b);
    const flags_b = state_flags();
    c.update_state_flags();
    assert.notEqual(flags_a, flags_b);
    assert.equal(flags_b, state_flags(), "state flags recomputed for the loaded core");
    await m.destroy();
}

// Reference: each context alone on its own machine, without any switching
const expected = [];
for(const id of [0, 1])
{
    const m = await machine();
    const c = m.v86.cpu;
    c.reg32[REG_EDI] = id;
    for(let guard = 0; !done(c, id); guard++)
    {
        assert.ok(guard < 100000, "reference run did not finish");
        c.main_loop();
    }
    expected.push(outcome_of(c, id, core_state(c)));
    await m.destroy();
}

// Interleaved: both contexts on one machine, switching after every slice
const interleaved = await machine();
const cpu = interleaved.v86.cpu;
const contexts = initial_contexts(cpu);
const { slices, sequence } = run(cpu, contexts, [[0, 1]]);
const actual = [0, 1].map(id => outcome_of(cpu, id, saved_state(contexts[id])));
await interleaved.destroy();

const switches = sequence.slice(1).filter((id, i) => id !== sequence[i]).length;
console.log(`${mode}: ${slices[0]} + ${slices[1]} slices, ${switches} switches between the contexts`);
assert.ok(slices[0] >= 3 && slices[1] >= 3 && switches >= 4, "the contexts must actually interleave");
for(const id of [0, 1])
{
    assert.equal(actual[id].results, expected[id].results, `context ${id}: results`);
    assert.equal(actual[id].page, expected[id].page, `context ${id}: physical page`);
    assert.equal(actual[id].state, expected[id].state, `context ${id}: final per-core state`);
}

// Control: without the TLB flush on a switch, the second context's accesses to
// the shared virtual page hit the first context's translation
const control = await machine();
const control_cpu = control.v86.cpu;
const control_contexts = initial_contexts(control_cpu);
const full_clear_tlb = control_cpu.full_clear_tlb;
control_cpu.full_clear_tlb = () => {};
run(control_cpu, control_contexts, [[0, 1]]);
control_cpu.full_clear_tlb = full_clear_tlb;
const broken = [0, 1].map(id => outcome_of(control_cpu, id, saved_state(control_contexts[id])).page);
await control.destroy();
assert.notDeepEqual(broken, expected.map(e => e.page), "control run without TLB flush must show cross-talk");

console.log(`${mode}: interleaved contexts match the reference; the control run without TLB flush differs`);
                                                                                                                                                                             source/v64/tests/smp/disk_fixture.mjs                                                               0000644 0000000 0000000 00000022510 00000000000 015040  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Test-only disks. Host image descriptors are opened read-only; guest writes
// exist only in sector overlays and never call a host-file write operation.
import fs from "node:fs";
import assert from "node:assert/strict";

export class ReadOnlyOverlayDisk
{
    constructor(filename)
    {
        this.fd = fs.openSync(filename, "r");
        this.byteLength = fs.fstatSync(this.fd).size;
        this.overlay = new Map();
    }
    load() { this.onload?.({}); }
    get(start, length, done)
    {
        assert.ok(start >= 0 && start + length <= this.byteLength);
        const data = new Uint8Array(length);
        assert.equal(fs.readSync(this.fd, data, 0, length, start), length);
        for(let sector = Math.floor(start / 512); sector * 512 < start + length; sector++)
        {
            const changed = this.overlay.get(sector);
            if(!changed) continue;
            const from = Math.max(start, sector * 512), to = Math.min(start + length, (sector + 1) * 512);
            data.set(changed.subarray(from - sector * 512, to - sector * 512), from - start);
        }
        done(data);
    }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache() { return undefined; }
    set(start, data, done)
    {
        assert.ok(start >= 0 && start + data.length <= this.byteLength);
        for(let at = 0; at < data.length;)
        {
            const sector = Math.floor((start + at) / 512), within = (start + at) % 512;
            let changed = this.overlay.get(sector);
            if(!changed)
            {
                this.get(sector * 512, 512, bytes => { changed = bytes; });
                this.overlay.set(sector, changed);
            }
            const count = Math.min(512 - within, data.length - at);
            changed.set(data.subarray(at, at + count), within);
            at += count;
        }
        done?.();
    }
    get_buffer(done) { done(undefined); }
    get_state()
    {
        const sectors = [...this.overlay.keys()].sort((a, b) => a - b);
        const bytes = new Uint8Array(sectors.length * 512);
        sectors.forEach((sector, i) => bytes.set(this.overlay.get(sector), i * 512));
        return [1, this.byteLength, Uint32Array.from(sectors), bytes];
    }
    // Also takes the written blocks of the browser's lazily loaded disks
    // (AsyncXHRBuffer and friends in src/buffer.js: [null, block numbers, their
    // 256 bytes each in chunks], or [[[block, 256 bytes], ...]] before), so
    // snapshots saved by a website restore here. Checked by hand: a failing
    // node:assert comparison renders the whole value into a line diff whose cost
    // is quadratic, and node is SIGKILLed with no output long before it throws.
    set_state(state)
    {
        const fail = what => { throw new Error(`Snapshot state of disk (${this.byteLength} bytes) ${what}`); };
        if(!Array.isArray(state)) fail("is not an array");
        if(state[0] === 1)
        {
            if(state[1] !== this.byteLength) fail(`is for a disk of ${state[1]} bytes`);
            if(!(state[2] instanceof Uint32Array) || !(state[3] instanceof Uint8Array) ||
                state[2].length * 512 !== state[3].length) fail("has an invalid sector overlay");
            this.overlay.clear();
            state[2].forEach((sector, i) => this.overlay.set(sector, state[3].slice(i * 512, (i + 1) * 512)));
        }
        else if(state[0] === null && state[1] instanceof Float64Array && Array.isArray(state[2]))
        {
            const [, blocks, chunks] = state;
            if(chunks.some(chunk => !(chunk instanceof Uint8Array) || chunk.length % 256) ||
                chunks.reduce((sum, chunk) => sum + chunk.length / 256, 0) !== blocks.length ||
                blocks.some(block => !Number.isSafeInteger(block) || block < 0 || (block + 1) * 256 > this.byteLength))
                fail("has invalid written blocks");
            this.overlay.clear();
            let i = 0;
            for(const chunk of chunks)
                for(let at = 0; at < chunk.length; at += 256) this.set(blocks[i++] * 256, chunk.subarray(at, at + 256));
        }
        else if(state.length === 1 && Array.isArray(state[0]))
        {
            for(const entry of state[0])
            {
                if(!Array.isArray(entry) || !Number.isSafeInteger(entry[0]) || entry[0] < 0 ||
                    (entry[0] + 1) * 256 > this.byteLength ||
                    !(entry[1] instanceof Uint8Array) || entry[1].length !== 256) fail("has an invalid block cache entry");
            }
            this.overlay.clear();
            for(const [block, bytes] of state[0]) this.set(block * 256, bytes);
        }
        else fail("has an unknown format (only an overlay or a browser block cache restore here)");
    }
    close() { fs.closeSync(this.fd); }
}

export class MemoryDisk
{
    constructor(bytes) { this.bytes = bytes; this.byteLength = bytes.length; }
    load() { this.onload?.({}); }
    get(start, length, done) { assert.ok(start + length <= this.byteLength); done(this.bytes.subarray(start, start + length)); }
    get_and_cache(start, length, done) { this.get(start, length, done); }
    get_from_cache(start, length) { return this.bytes.subarray(start, start + length); }
    set(start, bytes, done) { this.bytes.set(bytes, start); done?.(); }
    get_buffer(done) { done(this.bytes.slice().buffer); }
    get_state() { return [this.byteLength, this.bytes]; }
    set_state(state)
    {
        // (not assert.equal: see ReadOnlyOverlayDisk.set_state)
        if(state[0] !== this.byteLength || !(state[1] instanceof Uint8Array) || state[1].length !== this.byteLength)
            throw new Error(`Snapshot state does not fit this ${this.byteLength}-byte memory disk`);
        this.bytes = state[1].slice();
    }
}

// One MBR FAT16 partition, 16 MiB disk, 2 KiB clusters, 8.3 root files.
export function make_fat16(files)
{
    const bytes = new Uint8Array(16 << 20), view = new DataView(bytes.buffer);
    const partition = 63, total = bytes.length / 512 - partition, boot = partition * 512;
    const fat_sectors = 32, root_sectors = 32, cluster_sectors = 4;
    const fat = boot + 512, root = fat + 2 * fat_sectors * 512, data = root + root_sectors * 512;
    const ascii = (at, text) => bytes.set(Buffer.from(text, "ascii"), at);
    const word = (at, value) => view.setUint16(at, value, true);
    const dword = (at, value) => view.setUint32(at, value, true);
    bytes.set([0xFA,0xEB,0xFD]);
    dword(440, 0xC3002026);
    bytes[446] = 0x80; bytes.set([1,1,0], 447);
    bytes[450] = 0x0E; bytes.set([0xFE,0xFF,0xFF], 451);
    dword(454, partition); dword(458, total); word(510, 0xAA55);
    bytes.set([0xEB,0x3C,0x90], boot); ascii(boot + 3, "C3TOOLS ");
    word(boot + 11, 512); bytes[boot + 13] = cluster_sectors; word(boot + 14, 1); bytes[boot + 16] = 2;
    word(boot + 17, 512); word(boot + 19, total); bytes[boot + 21] = 0xF8;
    word(boot + 22, fat_sectors); word(boot + 24, 63); word(boot + 26, 16); dword(boot + 28, partition);
    bytes[boot + 36] = 0x80; bytes[boot + 38] = 0x29; dword(boot + 39, 0xC3202026);
    ascii(boot + 43, "C3TOOLS    "); ascii(boot + 54, "FAT16   "); word(boot + 510, 0xAA55);
    word(fat, 0xFFF8); word(fat + 2, 0xFFFF);
    let next = 2, entry = root;
    for(const [filename, contents] of Object.entries(files))
    {
        const [name, extension = ""] = filename.toUpperCase().split(".");
        assert.ok(name.length <= 8 && extension.length <= 3);
        ascii(entry, name.padEnd(8) + extension.padEnd(3)); bytes[entry + 11] = 0x20;
        const clusters = Math.ceil(contents.length / (cluster_sectors * 512));
        word(entry + 26, clusters ? next : 0); dword(entry + 28, contents.length);
        word(entry + 24, (46 << 9) | (9 << 5) | 27);
        for(let i = 0; i < clusters; i++) word(fat + (next + i) * 2, i + 1 === clusters ? 0xFFFF : next + i + 1);
        bytes.set(contents, data + (next - 2) * cluster_sectors * 512);
        next += clusters; entry += 32;
    }
    assert.ok(next * 2 <= fat_sectors * 512 && entry < root + root_sectors * 512);
    bytes.set(bytes.subarray(fat, fat + fat_sectors * 512), fat + fat_sectors * 512);
    return bytes;
}

export function read_fat16(bytes, filename)
{
    const view = new DataView(bytes.buffer, bytes.byteOffset), word = at => view.getUint16(at, true), dword = at => view.getUint32(at, true);
    const boot = dword(454) * 512, cluster_bytes = bytes[boot + 13] * 512;
    const fat = boot + word(boot + 14) * 512, root = fat + bytes[boot + 16] * word(boot + 22) * 512;
    const data = root + Math.ceil(word(boot + 17) * 32 / 512) * 512;
    const [name, extension = ""] = filename.toUpperCase().split(".");
    const wanted = name.padEnd(8) + extension.padEnd(3);
    for(let at = root; at < data && bytes[at]; at += 32)
    {
        if(Buffer.from(bytes.subarray(at, at + 11)).toString("ascii") !== wanted) continue;
        const size = dword(at + 28), result = new Uint8Array(size), visited = new Set();
        let cluster = word(at + 26), offset = 0;
        while(offset < size && cluster >= 2 && cluster < 0xFFF8 && !visited.has(cluster))
        {
            visited.add(cluster);
            const length = Math.min(cluster_bytes, size - offset), start = data + (cluster - 2) * cluster_bytes;
            result.set(bytes.subarray(start, start + length), offset); offset += length; cluster = word(fat + cluster * 2);
        }
        return offset === size ? result : undefined;
    }
    return undefined;
}
                                                                                                                                                                                        source/v64/tests/smp/exception_lifecycle.mjs                                                        0000644 0000000 0000000 00000014532 00000000000 016362  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Guest delivery failures must escalate in the CPU, never unwind the host.
import assert from "node:assert/strict";
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const vm = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: 2, memory_size: 16 << 20,
    disable_jit: true, autostart: false, log_level: 0 });
await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
const cpu = vm.v86.cpu;
const ex = cpu.wm.exports;
const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
const word = addr => view().getUint32(addr, true);
function gate(vector, present = true, base = 0x4000, selector = 8)
{
    const target = 0x2000 + vector * 16;
    view().setBigUint64(base + vector * 8, BigInt(target) | BigInt(selector) << 16n |
        BigInt(present ? 0x8E : 0x0E) << 40n, true);
    cpu.mem8[target] = 0xF4;
}
function setup(bytes, core = 1, idt = 0x4000)
{
    cpu.switch_core(core);
    cpu.load_core_state(cpu.core_reset_state);
    ex.exception_restore(core, 0);
    cpu.cores[core].running = true;
    cpu.sreg[1] = 8;
    cpu.sreg[2] = cpu.sreg[3] = cpu.sreg[0] = 16;
    cpu.segment_offsets.fill(0);
    cpu.segment_limits.fill(-1);
    cpu.protected_mode[0] = cpu.is_32[0] = cpu.stack_size_32[0] = 1;
    cpu.cr[0] = 0x11;
    cpu.reg32[4] = 0x9000;
    cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
    cpu.flags[0] = 2;
    cpu.in_hlt[0] = 0;
    cpu.gdtr_offset[0] = 0x6000;
    cpu.gdtr_size[0] = 23;
    view().setBigUint64(0x6008, 0x00CF9A000000FFFFn, true);
    view().setBigUint64(0x6010, 0x00CF92000000FFFFn, true);
    cpu.idtr_offset[0] = idt;
    cpu.idtr_size[0] = 255 * 8 + 7;
    for(let vector = 0; vector < 256; vector++) gate(vector, true, idt);
    cpu.mem8.set(bytes, 0x1000);
    cpu.update_state_flags();
    cpu.full_clear_tlb();
}
function delivered(vector, error)
{
    cpu.run_cpu_slice(1);
    assert.equal(cpu.instruction_pointer[0], 0x2000 + vector * 16, `delivered vector ${vector}`);
    if(error !== undefined) assert.equal(word(cpu.reg32[4] >>> 0), error);
}
function paging(missing)
{
    cpu.mem8.fill(0, 0xA000, 0xC000);
    view().setUint32(0xA000, 0xB003, true);
    for(let page = 0; page < 1024; page++) view().setUint32(0xB000 + page * 4, page === missing ? 0 : page * 4096 | 3, true);
    cpu.cr[3] = 0xA000;
    cpu.cr[0] = 0x80000011 | 0;
    cpu.full_clear_tlb();
}
try
{
    setup([0xF7, 0xF1]); // DIV ECX=0: contributory -> #NP => #DF
    gate(0, false);
    delivered(8, 0);
    setup([0x0F, 0x0B]); // #UD is benign: #NP is delivered, not #DF
    gate(6, false);
    delivered(11, 6 * 8 | 2);
    setup([0xCD, 13]); // Software INT 13 is not a contributory exception
    gate(13, false);
    delivered(11, 13 * 8 | 2);
    setup([0xF7, 0xF1], 1, 0x3FC0); // #DE gate on absent page, #PF gate present
    paging(3);
    delivered(14, 0);
    assert.equal(cpu.cr[2], 0x3FC0);
    setup([0xA1, 0, 0, 0x40, 0]); // #PF then non-present #PF gate => #DF
    gate(14, false);
    paging(-1);
    delivered(8, 0);
    assert.equal(cpu.cr[2], 0x400000);
    setup([0xCF]); // IRET null CS: guest #GP, stack unchanged before delivery
    view().setUint32(0x9000, 0x1234, true);
    view().setUint32(0x9004, 0, true);
    view().setUint32(0x9008, 2, true);
    delivered(13, 0);
    assert.equal(word(cpu.reg32[4] + 4), 0x1000);
    for(const [descriptor, target, vector, code] of [
        [0x00000B0000000000n, 0xFFFFFFFF, 13, 24], // system TSS never a CS, even P=0
        [0x0000120000000000n, 0xFFFFFFFF, 13, 24], // data segment before presence/limit
        [0x00001A0000000000n, 0xFFFFFFFF, 11, 24], // absent code before limit
        [0x00009A0000000000n, 0xFFFFFFFF, 13, 0],  // valid code, EIP beyond limit
    ])
    {
        setup([0xCF]);
        cpu.gdtr_size[0] = 31;
        view().setBigUint64(0x6018, descriptor, true);
        view().setUint32(0x9000, target, true);
        view().setUint32(0x9004, 24, true);
        view().setUint32(0x9008, 2, true);
        delivered(vector, code);
    }
    setup([0x90]);
    gate(2, false);
    cpu.apic_restore_core_events(1, 0, true);
    cpu.handle_irqs();
    assert.equal(cpu.instruction_pointer[0], 0x20B0);
    assert.equal(word(cpu.reg32[4]), 2 * 8 | 3, "NMI delivery fault carries EXT=1");
    setup([0xF7, 0xF1]);
    cpu.gdtr_size[0] = 10; // CS descriptor starts in table but extends beyond its limit
    cpu.run_cpu_slice(100);
    assert.equal(ex.exception_shutdown(1), 1);
    setup([0xF7, 0xF1]);
    cpu.segment_limits[2] = 4; // exception frames exceed stack; no host assertion
    cpu.run_cpu_slice(100);
    assert.equal(ex.exception_shutdown(1), 1);
    setup([0xF7, 0xF1]);
    gate(0, false); gate(8, false);
    const epoch = cpu.execution_epoch;
    cpu.run_cpu_slice(100);
    assert.equal(ex.exception_shutdown(1), 1);
    assert.equal(cpu.core_runnable(1), false);
    assert.equal(cpu.execution_epoch, epoch, "AP shutdown does not reset machine");
    const saved = await vm.save_state();
    ex.exception_restore(1, 0);
    await vm.restore_state(saved);
    assert.equal(ex.exception_shutdown(1), 1, "AP shutdown survives whole-machine restore");
    cpu.apic_restore_core_events(1, 1, false);
    cpu.take_core_events(1);
    assert.equal(ex.exception_shutdown(1), 0);
    assert.equal(cpu.cores[1].running, false, "INIT leaves AP waiting for SIPI");
    setup([0xF7, 0xF1]);
    gate(0, false); gate(8, false);
    cpu.run_cpu_slice(100);
    gate(2);
    cpu.apic_restore_core_events(1, 0, true);
    assert.equal(cpu.core_runnable(1), true);
    cpu.run_cpu_slice(1);
    assert.equal(ex.exception_shutdown(1), 0, "NMI wakes AP shutdown");
    assert.equal(cpu.instruction_pointer[0], 0x2021); // NMI handler HLT
    setup([0xF7, 0xF1], 0);
    cpu.idtr_size[0] = 0; // #GP -> #DF -> board reset, not recursive host panic
    const reset_epoch = cpu.execution_epoch;
    cpu.run_cores();
    assert.equal(cpu.execution_epoch, reset_epoch + 1);
    assert.ok(cpu.cores.every(core => core.steps === 0 && core.slices === 0), "old round cannot credit work after board reset");
    assert.equal(cpu.active_core, 0);
    assert.equal(cpu.cores[1].running, false);
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xFFFF0);
    console.log("PASS exception delivery: benign/contributory/PF matrix, #DF frame, invalid IRET, AP shutdown/snapshot/INIT/NMI, BSP safe-point reset");
}
finally { await vm.destroy(); }
                                                                                                                                                                      source/v64/tests/smp/firmware_boot.asm                                                              0000644 0000000 0000000 00000001332 00000000000 015165  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; A boot sector reached only after SeaBIOS completes POST, including its
; expected-CPU-count rendezvous. The harness supplies this on a floppy.
bits 16
org 0x7C00

start:
    cli
    xor ax, ax
    mov ds, ax
    mov ss, ax
    mov sp, 0x7C00
    ; Expose the fw_cfg count seen by firmware, without changing it.
    mov dx, 0x510
    mov ax, 5                      ; FW_CFG_NB_CPUS
    out dx, ax
    inc dx
    in al, dx
    mov [0x500], al
    in al, dx
    mov [0x501], al
    mov eax, 1
    cpuid
    shr ebx, 24
    mov [0x504], ebx                ; boot must reach this on the BSP
    mov eax, 0x534D5042              ; "SMPB" pass marker
    out 0xF4, eax
.halt:
    hlt
    jmp .halt

times 510 - ($ - $$) db 0
dw 0xAA55
                                                                                                                                                                                                                                                                                                      source/v64/tests/smp/firmware_boot.mjs                                                              0000644 0000000 0000000 00000014434 00000000000 015205  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Real SeaBIOS POST, including its INIT/SIPI rendezvous, then floppy boot.
// No multiboot, AP state injection or firmware CPU-count overrides.
// Build: nasm -f bin tests/smp/firmware_boot.asm -o build/smp/firmware_boot.bin
import assert from "node:assert/strict";
import { setImmediate as set_immediate } from "node:timers";
import fs from "node:fs";
import url from "node:url";
import { locate_acpi_tables } from "../../src/acpi_tables.js";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const local = path => url.fileURLToPath(new URL(path, import.meta.url));
const sector = fs.readFileSync(local("../../build/smp/firmware_boot.bin"));
assert.equal(sector.length, 512, "fixture is one boot sector");
assert.equal(sector.readUInt16LE(510), 0xAA55, "boot signature");
const TIME_LIMIT_MS = 30000;
const ROUND_LIMIT = 1000000;
const MARKER = 0x534D5042;

function check_madt(cpu, count)
{
    const tables = locate_acpi_tables(cpu.mem8);
    assert.ok(tables, "SeaBIOS installed an RSDP");
    assert.ok(tables.tables.every(table => table.checksum_ok), "ACPI table checksums");
    const madt = tables.tables.find(table => table.signature === "APIC");
    assert.ok(madt, "SeaBIOS installed a MADT");
    const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const ids = [];
    const processors = [];
    const end = madt.address + madt.length;
    for(let p = madt.address + 44; p < end;)
    {
        assert.ok(p + 2 <= end, "complete MADT entry header");
        const type = cpu.mem8[p];
        const length = cpu.mem8[p + 1];
        assert.ok(length >= 2 && p + length <= end, "bounded MADT entry");
        if(type === 0)
        {
            assert.equal(length, 8, "processor local APIC entry length");
            if(view.getUint32(p + 4, true) & 1)
            {
                processors.push(cpu.mem8[p + 2]);
                ids.push(cpu.mem8[p + 3]);
            }
        }
        p += length;
    }
    const expected = Array.from({ length: count }, (_, id) => id);
    assert.deepEqual(ids.sort((a, b) => a - b), expected, "enabled MADT APIC IDs");
    assert.deepEqual(processors.sort((a, b) => a - b), expected, "enabled MADT processor IDs");
    return tables.oem_id.trim();
}

async function test(count)
{
    const disk = new Uint8Array(1440 * 1024);
    disk.set(sector);
    const emulator = new V86({
        graphics_adapter: "bochs_vga",
        bios: { url: local("../../bios/seabios.bin") },
        vga_bios: { url: local("../../bios/vgabios.bin") },
        fda: { buffer: disk.buffer },
        memory_size: 32 * 1024 * 1024,
        cpu_cores: count,
        acpi: true,
        disable_jit: true,
        autostart: false,
        log_level: 0,
    });
    let load_timeout;
    let cpu;
    let firmware_log = "";
    let marker = null;
    let marker_core = -1;
    let rounds = 0;
    const started = new Set();
    const startup_events = Array.from({ length: count }, () => []);
    try
    {
        await new Promise((resolve, reject) => {
            load_timeout = setTimeout(() => reject(new Error("emulator load timed out")), TIME_LIMIT_MS);
            emulator.add_listener("emulator-loaded", resolve);
        });
        clearTimeout(load_timeout);
        cpu = emulator.v86.cpu;
        cpu.clock.resume(); // this fixture explicitly drives scheduling rounds
        assert.equal(cpu.cores.length, count);
        assert.ok(cpu.cores.slice(1).every(core => !core.running), "APs initially wait for guest startup");
        // Observe event consumption without changing the returned bits or
        // invoking a core-state operation. All senders remain BIOS code.
        const take_events = cpu.apic_take_core_events;
        cpu.apic_take_core_events = core => {
            const events = take_events(core);
            if(events) startup_events[core].push(events);
            return events;
        };
        cpu.io.register_write(0x402, {}, value => {
            firmware_log = (firmware_log + String.fromCharCode(value)).slice(-16000);
        });
        const finish = value => { marker = value >>> 0; marker_core = cpu.active_core; };
        cpu.io.register_write(0xF4, {}, finish, finish, finish);
        const deadline = performance.now() + TIME_LIMIT_MS;
        while(marker === null)
        {
            assert.ok(++rounds <= ROUND_LIMIT, "SeaBIOS round limit exceeded");
            assert.ok(performance.now() < deadline, "SeaBIOS POST/floppy boot timed out");
            cpu.run_cores();
            for(let id = 1; id < count; id++)
            {
                if(cpu.cores[id].running && cpu.cores[id].steps > 0) started.add(id);
            }
            // Floppy reads can complete on the host event loop.
            if(rounds % 256 === 0) await new Promise(resolve => set_immediate(resolve));
        }
        assert.equal(marker, MARKER, "boot sector pass marker");
        assert.equal(marker_core, 0, "BSP executed the boot sector");
        assert.equal(started.size, count - 1, "every AP ran during real SeaBIOS POST");
        for(let id = 1; id < count; id++)
        {
            assert.ok(startup_events[id].some(events => events & 1), `AP ${id}: BIOS sent INIT`);
            assert.ok(startup_events[id].some(events => events & 2), `AP ${id}: BIOS sent SIPI`);
        }
        const memory = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        assert.equal(memory.getUint16(0x500, true), count, "firmware expected CPU count was not reduced");
        assert.equal(memory.getUint32(0x504, true), 0, "boot sector sees BSP CPUID ID");
        const oem = check_madt(cpu, count);
        console.log(`${count} cores: SeaBIOS POST, ${started.size} real APs, ${oem} MADT IDs and floppy boot passed (${rounds} rounds)`);
    }
    catch(error)
    {
        console.error(JSON.stringify({ count, rounds, marker, started: [...started], startup_events, firmware_log,
            diagnostics: cpu?.get_diagnostics() }, null, 2));
        throw error;
    }
    finally
    {
        clearTimeout(load_timeout);
        await emulator.destroy();
    }
}

const failures = [];
for(const count of [2, 3, 4, 8])
{
    try { await test(count); }
    catch(error) { failures.push(error); console.error(`${count} cores: ${error.stack}`); }
}
assert.equal(failures.length, 0, `${failures.length} SeaBIOS configurations failed`);
                                                                                                                                                                                                                                    source/v64/tests/smp/legacy_low_hole.mjs                                                            0000644 0000000 0000000 00000011072 00000000000 015475  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Warm both cores' legacy translations/JIT code, relocate RAM, then prove the
// low physical hole cannot alias its backing and removing the window restores
// ordinary RAM. Core 1 executes code above the hole to test the fast-limit gap.
import assert from "node:assert/strict";
import { setImmediate as set_immediate } from "node:timers";
import { smp_modes, with_smp_mode, mode_hits } from "../lib/smp_modes.mjs";
const { V86 } = await import(process.env.V86_LIB_PATH || (+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js"));
const u32 = value => [value & 255, value >>> 8 & 255, value >>> 16 & 255, value >>> 24];
const modes = smp_modes();
const target = 0x200000, high = 2 ** 32, value = 0x12345678, relocated = 0x87654321;
const ips = [0x10000, 0x300000];
const code = new Uint8Array([
    0x31, 0xC9,                           // xor ecx, ecx
    0xC7, 0x05, ...u32(target), ...u32(value), // mov [target], value
    0xA1, ...u32(target),                  // mov eax, [target]
    0x41,                                 // inc ecx
    0x81, 0xF9, ...u32(4096),             // cmp ecx, 4096
    0x75, 0xE8,                           // jne loop (-24)
    0xF4,
]);
for(const mode of modes)
{
    const emulator = new V86(with_smp_mode({ graphics_adapter: "bochs_vga", wasm_path: process.env.WASM_PATH, memory_size: 16 << 20,
        acpi: true, cpu_cores: 2, disable_jit: mode === "interpreter", experimental_smp_jit: true, ir_sync_publication: true,
        autostart: false, log_level: 0, net_device: { type: "none" } }, mode));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    try
    {
        const cpu = emulator.v86.cpu, e = cpu.wm.exports;
        for(let core = 0; core < 2; core++)
        {
            cpu.switch_core(core);
            cpu.write_blob(code, ips[core]);
            cpu.reg32.fill(0);
            cpu.reg32[4] = 0x400000 + core * 4096;
            cpu.flags[0] = 2;
            cpu.cr[0] = 0x11;
            cpu.cr[3] = cpu.cr[4] = 0;
            cpu.protected_mode[0] = cpu.is_32[0] = cpu.stack_size_32[0] = 1;
            cpu.segment_offsets.fill(0, 0, 6);
            cpu.segment_limits.fill(-1, 0, 6);
            cpu.segment_is_null.fill(0, 0, 6);
            cpu.sreg.set([16, 8, 16, 16, 16, 16]);
            cpu.segment_access_bytes.set([0x93, 0x9B, 0x93, 0x93, 0x93, 0x93]);
            cpu.update_state_flags();
            cpu.full_clear_tlb();
            cpu.cores[core].running = true;
        }
        const hits = () => mode_hits(e, mode);
        const run = async (phase, expected) => {
            const counts = [];
            for(let core = 0; core < 2; core++)
            {
                cpu.switch_core(core);
                cpu.instruction_pointer[0] = cpu.previous_ip[0] = ips[core];
                cpu.in_hlt[0] = 0;
                const before = hits(), deadline = performance.now() + 10000;
                let rounds = 0;
                while(!cpu.in_hlt[0])
                {
                    assert.ok(performance.now() < deadline, `${mode}/${phase}/${core}: timeout`);
                    cpu.run_cpu_slice(257);
                    if(++rounds % 16 === 0) await new Promise(resolve => set_immediate(resolve));
                }
                counts.push((hits() - before) >>> 0);
                assert.equal(cpu.reg32[0] >>> 0, expected, `${mode}/${phase}/${core}: guest load result`);
                assert.equal(cpu.reg32[1], 4096, "guest completed all loop iterations");
                if(mode !== "interpreter") assert.ok(counts[core] > 0, `${mode}/${phase}/${core}: actual compiled execution`);
            }
            return counts;
        };
        cpu.clock.resume();
        const before = await run("before", value);
        assert.equal(e.x64_phys_set_window(0, 0, 1, target, 4096, 1), 1);
        assert.equal(!!cpu.in_mapped_range(target), true);
        assert.equal(!!cpu.in_mapped_range(ips[1]), false, "RAM beyond hole stays executable");
        cpu.write32_physical(high, relocated);
        const mapped = await run("mapped", 0xFFFFFFFF);
        assert.equal(cpu.read32_physical(high), relocated, "neither core's legacy store changed high RAM");
        assert.equal(e.x64_phys_set_window(0, 0, 0, 0, 0, 0), 1);
        assert.equal(!!cpu.in_mapped_range(target), false);
        const removed = await run("removed", value);
        assert.equal(cpu.read32_physical(target), value);
        cpu.clock.pause();
        console.log(`PASS legacy low hole ${mode}: before=${before} mapped=${mapped} removed=${removed}`);
    }
    finally { await emulator.destroy(); }
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/smp/lifecycle.mjs                                                                  0000644 0000000 0000000 00000016406 00000000000 014306  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Machine snapshots must preserve every core, including stopped APs and
// cached translations. Topology mismatches are rejected before any mutation.
import assert from "node:assert/strict";
import { STATE_OFFSETS } from "../../src/state_layout.js";
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
async function machine(count)
{
    const vm = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: count, memory_size: 16 << 20,
        disable_jit: true, autostart: false, log_level: 0,
        cpu_clock: { mode: "deterministic", instructions_per_ms: 100 }, cpu_schedule_seed: 42 });
    await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
    return vm;
}
for(const count of [1, 2, 3, 4, 8])
{
    const vm = await machine(count);
    const cpu = vm.v86.cpu;
    try
    {
        cpu.clock.resume();
        cpu.clock.advance_instructions(250);
        const bytes = new Uint8Array(cpu.wasm_memory.buffer);
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            cpu.reg32[0] = 0x12340000 + core;
            cpu.cr[2] = 0xABCD000 + core;
            cpu.cores[core].running = core % 2 === 0;
            cpu.in_hlt[0] = core % 3 === 0 ? 1 : 0;
            bytes[cpu.state_base + STATE_OFFSETS.nmi_blocked] = core % 2;
            bytes[cpu.state_base + STATE_OFFSETS.interrupt_shadow] = core % 2;
            cpu.set_tsc(5555 + core, 0);
            cpu.set_tsc(1000 + core, 0);
            cpu.apic_restore_core_events(core, core % 2 ? 1 : 0, core % 3 === 0);
            cpu.wm.exports["apic_restore_extint"](core, core % 2 !== 0);
            cpu.cores[core].steps = 100 + core;
            cpu.cores[core].slices = 10 + core;
        }
        cpu.clock.pause();
        const before = cpu.get_machine_core_state();
        const clock = cpu.clock.get_state();
        const saved = await vm.save_state();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            cpu.reg32.fill(0);
            cpu.apic_init_core(core);
            cpu.apic_restore_core_events(core, 0, false);
        }
        cpu.mem8.fill(0xFF, 0x1000, 0x2000);
        await vm.restore_state(saved);
        assert.deepEqual(cpu.get_machine_core_state(), before, "all per-core state round trips");
        assert.deepEqual(cpu.clock.get_state(), clock, "clock epoch and progress round trip while stopped");
        assert.equal(cpu.clock.paused, true);
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            cpu.store_current_tsc();
            assert.equal(cpu.current_tsc[0], 1000 + core, "per-core TSC offset survives switches and restore");
        }
        const other = await machine(count === 1 ? 2 : 1);
        try
        {
            const target = other.v86.cpu;
            const state = target.get_machine_core_state();
            const memory = target.mem8.slice();
            const time = target.clock.get_state();
            await assert.rejects(other.restore_state(saved), /topology mismatch/);
            assert.deepEqual(target.get_machine_core_state(), state);
            assert.equal(Buffer.compare(target.mem8.slice(), memory), 0);
            assert.deepEqual(target.clock.get_state(), time);
        }
        finally { await other.destroy(); }
        cpu.write32(0xFEC00000, 0x10);
        cpu.write32(0xFEC00010, 0x30); // previous Linux's unmasked timer route
        if(count > 1)
        {
            cpu.apic_restore_core_events(1, 1, false);
            cpu.take_core_events(1);
            assert.equal(cpu.read32s(0xFEC00010), 0x30, "AP INIT preserves machine routing");
        }
        cpu.reboot_internal();
        assert.equal(cpu.active_core, 0);
        cpu.write32(0xFEC00000, 0x10);
        assert.equal(cpu.read32s(0xFEC00010), 1 << 16, "board reset masks stale timer routing before firmware reprograms it");
        assert.equal(cpu.get_state_pic()[2], 0, "board reset clears PIC ISR");
        assert.deepEqual(cpu.cores.map(core => core.running), Array.from({ length: count }, (_, i) => i === 0));
        for(let core = 0; core < count; core++)
        {
            assert.equal(cpu.apic_peek_core_events(core), 0);
            assert.equal(cpu.apic_core_nmi_pending(core), 0);
        }
        console.log(`${count} cores: whole-machine state, NMI/ExtINT, TSC offsets, topology rejection and reset passed`);
    }
    finally { await vm.destroy(); }
}

// A snapshot in the middle of REP preserves partial writes, remaining count,
// continuation EIP, scheduling seed and the machine's committed-work clock.
const rep_vm = await machine(2);
try
{
    const cpu = rep_vm.v86.cpu;
    cpu.clock.resume();
    for(let core = 0; core < 2; core++)
    {
        cpu.switch_core(core);
        cpu.cores[core].running = true;
        cpu.sreg[1] = cpu.segment_offsets[1] = 0;
        cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
        cpu.mem8.set([0xF3, 0xAA, 0xF4], 0x1000);
        cpu.flags[0] = 2;
        cpu.in_hlt[0] = 0;
        cpu.reg32[0] = 0xA0 + core;
        cpu.reg32[1] = 1000;
        cpu.reg32[7] = 0x4000 + core * 0x1000;
    }
    cpu.run_cores();
    for(let core = 0; core < 2; core++)
    {
        cpu.switch_core(core);
        assert.equal(cpu.reg32[1], 744);
    }
    const saved = await rep_vm.save_state();
    const finish = () => {
        for(let i = 0; i < 10 && cpu.cores.some((_, id) => cpu.core_runnable(id)); i++) cpu.run_cores();
        assert.ok(cpu.cores.every((_, id) => !cpu.core_runnable(id)));
        return { memory: cpu.mem8.slice(0x4000, 0x6000), clock: cpu.clock.get_state(),
            cores: cpu.get_machine_core_state().map((part, index) => index !== 6 ? part :
                part.map(core => core.map((field, slot) => slot === 10 ? field.slice(0, 32) : field))) };
    };
    const first = finish();
    await rep_vm.restore_state(saved);
    const second = finish();
    assert.deepEqual(second, first);
    console.log("SMP lifecycle: pending REP/HLT replay preserves RAM, every core, scheduler seed and committed clock exactly");
}
finally { await rep_vm.destroy(); }

// Public save invoked by a synchronous device listener must wait until the
// current OUT and the machine round finish, never copy a live Wasm frame.
const reentrant_vm = await machine(2);
try
{
    const cpu = reentrant_vm.v86.cpu;
    cpu.clock.resume();
    cpu.sreg[1] = cpu.segment_offsets[1] = 0;
    cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
    cpu.mem8.set([0xE6, 0x80, 0xF4], 0x1000); // out 80h, al; hlt
    cpu.flags[0] = 2;
    let pending;
    let captured = false;
    const get_state = cpu.get_state.bind(cpu);
    cpu.get_state = () => {
        assert.equal(cpu.in_cpu, false, "snapshot is outside the active Wasm frame");
        captured = true;
        return get_state();
    };
    cpu.io.register_write(0x80, {}, () => {
        pending = reentrant_vm.save_state();
        assert.equal(captured, false, "save is deferred inside the device callback");
    });
    cpu.run_cores();
    await pending;
    assert.equal(captured, true);
    assert.equal(cpu.instruction_pointer[0], 0x1003);
    console.log("SMP lifecycle: snapshot requested inside a device callback waits for a machine safe point");
}
finally { await reentrant_vm.destroy(); }
                                                                                                                                                                                                                                                          source/v64/tests/smp/linux_topology.mjs                                                             0000644 0000000 0000000 00000025461 00000000000 015443  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Topology OS acceptance: unmodified 32-bit Linux 4.16 SMP from images/linux4.iso.
// Firmware starts APs, Linux brings them online, sysfs reports one package,
// and concurrent ELF32 processes bind to every CPU and complete real work.
// No host writes to CPU contexts or firmware counts occur in this test.
import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";
import { with_smp_mode } from "../lib/smp_modes.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const local = path => url.fileURLToPath(new URL(path, import.meta.url));
const affinity_probe = fs.readFileSync(local("../../build/smp/affinity_probe"));
const TIMEOUT_MS = 120000;
// (tests/lib/smp_modes.mjs)
const jit_mode = process.env.SMP_JIT_MODE || "interpreter";
assert.ok(["interpreter", "pages"].includes(jit_mode), "SMP_JIT_MODE must be interpreter or pages");
const counts = process.env.CPU_COUNTS ? process.env.CPU_COUNTS.split(",").map(Number) : [1, 2, 3, 4, 8];
assert.ok(counts.every(count => Number.isInteger(count) && count >= 1 && count <= 8));
const transcript_directory = process.env.C2_LOG_DIR;
if(transcript_directory) fs.mkdirSync(transcript_directory, { recursive: true });

// The bundled SeaBIOS config disables SMBIOS. If a replacement BIOS emits
// Type 4, it must still describe one socket with N cores and N threads.
function check_smbios(cpu, count)
{
    const memory = cpu.mem8;
    const view = new DataView(memory.buffer, memory.byteOffset);
    const text = (address, length) => String.fromCharCode(...memory.subarray(address, address + length));
    for(let address = 0xF0000; address < 0x100000; address += 16)
    {
        if(text(address, 4) !== "_SM_") continue;
        const entry_length = memory[address + 5];
        assert.equal(memory.subarray(address, address + entry_length).reduce((sum, byte) => sum + byte, 0) & 255, 0, "SMBIOS entry checksum");
        const start = view.getUint32(address + 0x18, true);
        const end = start + view.getUint16(address + 0x16, true);
        assert.ok(end <= memory.length, "SMBIOS table in RAM");
        let packages = 0;
        for(let position = start; position < end;)
        {
            const type = memory[position];
            const length = memory[position + 1];
            assert.ok(length >= 4 && position + length <= end, "bounded SMBIOS structure");
            if(type === 4)
            {
                packages++;
                assert.ok(length >= 0x28, "SMBIOS Type 4 includes core/thread counts");
                assert.equal(memory[position + 0x23], count, "SMBIOS core count");
                assert.equal(memory[position + 0x24], count, "SMBIOS enabled core count");
                assert.equal(memory[position + 0x25], count, "SMBIOS thread count");
            }
            position += length;
            while(position + 1 < end && (memory[position] !== 0 || memory[position + 1] !== 0)) position++;
            position += 2;
            if(type === 127) break;
        }
        assert.equal(packages, 1, "SMBIOS describes one processor package");
        return "one package";
    }
    return "not emitted";
}

async function test(count)
{
    const emulator = new V86(with_smp_mode({
        graphics_adapter: "bochs_vga",
        wasm_path: process.env.WASM_PATH,
        bios: { url: local("../../bios/seabios.bin") },
        vga_bios: { url: local("../../bios/vgabios.bin") },
        cdrom: { url: local("../../images/linux4.iso") },
        memory_size: 128 << 20,
        cpu_cores: count,
        acpi: true,
        disable_jit: jit_mode === "interpreter",
        experimental_smp_jit: jit_mode !== "interpreter",
        ir_sync_publication: true,
        autostart: false,
        filesystem: {},
        log_level: 0,
    }, jit_mode, false));
    let serial = "";
    let cpu;
    let timeout;
    let phase = "load";
    let rounds = 0;
    let summary;
    const per_core_jit = Array.from({ length: count }, () => ({ pages: 0 }));
    const jit_counts = () => ({
        // (instructions the page tier ran natively)
        pages: cpu.wm.exports.x64_page_stat(1) >>> 0,
    });
    emulator.add_listener("serial0-output-byte", byte => {
        const character = String.fromCharCode(byte);
        serial += character;
        if(+process.env.SHOW_LOGS) process.stdout.write(character);
    });

    async function run_until(label, predicate)
    {
        phase = label;
        const deadline = performance.now() + TIMEOUT_MS;
        while(!predicate())
        {
            assert.ok(performance.now() < deadline, `${count} CPUs: ${label} timed out`);
            assert.ok(!serial.includes("Kernel panic"), "Linux kernel panic");
            await new Promise(resolve => setTimeout(resolve, 10));
        }
    }

    try
    {
        await new Promise((resolve, reject) => {
            timeout = setTimeout(() => reject(new Error("emulator load timed out")), 15000);
            emulator.add_listener("emulator-loaded", resolve);
            emulator.add_listener("emulator-error", reject);
        });
        clearTimeout(timeout);
        cpu = emulator.v86.cpu;
        const run_cores = cpu.run_cores.bind(cpu);
        cpu.run_cores = () => { rounds++; return run_cores(); };
        if(jit_mode !== "interpreter")
        {
            // Counter deltas are attributed at scheduler boundaries, without
            // changing dispatch, memory or CPU state. Single-core normal mode
            // uses main_loop; multicore uses run_cpu_slice.
            const method = count === 1 ? "main_loop" : "run_cpu_slice";
            const execute = cpu[method].bind(cpu);
            cpu[method] = (...args) => {
                const core = cpu.active_core;
                const before = jit_counts();
                const result = execute(...args);
                const after = jit_counts();
                per_core_jit[core].pages += (after.pages - before.pages) >>> 0;
                return result;
            };
        }
        await emulator.create_file("c2-affinity", affinity_probe);
        const script = `
set -eu
printf 'C2_KERNEL '; uname -a
printf 'C2_ONLINE '; cat /sys/devices/system/cpu/online
for d in /sys/devices/system/cpu/cpu[0-9]*; do
    id=\${d##*cpu}
    printf 'C2_TOPOLOGY id=%s package=%s core=%s threads=%s package_cpus=%s\\n' "$id" "$(cat "$d/topology/physical_package_id")" "$(cat "$d/topology/core_id")" "$(cat "$d/topology/thread_siblings_list")" "$(cat "$d/topology/core_siblings_list")"
done
cp /mnt/c2-affinity /tmp/c2-affinity
chmod 755 /tmp/c2-affinity
for id in ${Array.from({ length: count }, (_, id) => id).join(" ")}; do
    /tmp/c2-affinity "$id" &
done
wait
echo C2_DONE
`;
        await emulator.create_file("c2-topology.sh", Buffer.from(script));
        const boot_started = performance.now();
        emulator.run();
        await run_until("boot to shell", () => /~% $/.test(serial));
        const boot_wall_ms = Math.round(performance.now() - boot_started);
        const boot_jit = per_core_jit.map(counters => ({ ...counters }));
        emulator.serial0_send("sh /mnt/c2-topology.sh\n");
        await run_until("topology and affinity progress", () => serial.includes("C2_DONE\r\n") || serial.includes("C2_DONE\n"));
        await emulator.stop();
        assert.ok(!serial.includes("C2_AFFINITY_FAIL"), "affinity/getcpu/progress fixture failed");
        assert.match(serial, /C2_KERNEL Linux [^\r\n]*SMP/, "kernel was built with SMP");
        const expected_list = count === 1 ? "0" : `0-${count - 1}`;
        assert.equal(serial.match(/C2_ONLINE ([^\r\n]+)/)?.[1], expected_list, "every configured CPU is online");
        const topology = [...serial.matchAll(/C2_TOPOLOGY id=(\d+) package=(-?\d+) core=(-?\d+) threads=([^ ]+) package_cpus=([^\r\n]+)/g)];
        assert.equal(topology.length, count, "one topology record per configured CPU");
        const seen = new Set();
        for(const [, id_text, package_id, core_id, threads, package_cpus] of topology)
        {
            const id = +id_text;
            assert.ok(id < count && !seen.has(id), "unique valid CPU ID");
            seen.add(id);
            assert.equal(+package_id, 0, `CPU ${id}: one physical package`);
            assert.equal(+core_id, id, `CPU ${id}: distinct physical core`);
            assert.equal(threads, id_text, `CPU ${id}: one thread per core`);
            assert.equal(package_cpus, expected_list, `CPU ${id}: package membership`);
        }
        const progress = [...serial.matchAll(/C2_PROGRESS id=(\d+) cpu=(\d+) iterations=(\d+)/g)];
        assert.equal(progress.length, count, "each bound process completed work");
        assert.deepEqual(progress.map(match => +match[1]).sort((a, b) => a - b), [...seen].sort((a, b) => a - b));
        for(const [, id, actual_cpu, iterations] of progress)
        {
            assert.equal(actual_cpu, id, "getcpu agrees with sched_setaffinity before/after progress");
            assert.equal(+iterations, 100000, "bound arithmetic work completed and checksum matched");
        }
        const smbios = check_smbios(cpu, count);
        const hits = jit_counts();
        const workload_jit = per_core_jit.map((counters, id) => ({
            pages: counters.pages - boot_jit[id].pages,
        }));
        if(jit_mode === "interpreter") assert.deepEqual(hits, { pages: 0 }, "interpreter reference executed no compiled code");
        else
        {
            assert.ok(hits.pages > 0, "pages compiled code actually executed");
            for(let id = 0; id < count; id++)
            {
                assert.ok(per_core_jit[id].pages > 0, `CPU ${id}: pages activations`);
                assert.ok(workload_jit[id].pages > 0, `CPU ${id}: pages ran after boot during the affinity workload`);
            }
        }
        summary = { count, jit_mode, rounds, boot_wall_ms, total_wall_ms: Math.round(performance.now() - boot_started),
            smbios, hits, per_core_jit, workload_jit };
        console.log(`${jit_mode} ${count} CPUs: Linux topology and bound progress passed ${JSON.stringify(summary)}`);
    }
    catch(error)
    {
        const vga_text = cpu && Array.from({ length: 25 }, (_, row) =>
            Array.from({ length: 80 }, (_, column) => String.fromCharCode(cpu.mem8[0xB8000 + (row * 80 + column) * 2] || 32)).join("").trimEnd()).join("\n");
        console.error(JSON.stringify({ count, jit_mode, phase, rounds, per_core_jit, serial_tail: serial.slice(-20000), vga_text, diagnostics: cpu?.get_diagnostics() }, null, 2));
        throw error;
    }
    finally
    {
        if(transcript_directory)
        {
            fs.writeFileSync(`${transcript_directory}/linux4-${count}cpu.log`, serial);
            if(summary) fs.writeFileSync(`${transcript_directory}/linux4-${count}cpu.json`, JSON.stringify(summary, null, 2) + "\n");
        }
        clearTimeout(timeout);
        await emulator.destroy();
    }
}

for(const count of counts) await test(count);
                                                                                                                                                                                                               source/v64/tests/smp/memory_order.asm                                                               0000644 0000000 0000000 00000004437 00000000000 015042  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       ; Single-producer/single-consumer ring queues. Queue slots carry a sequence and
; its complement, published with an ordinary store to HEAD. This deliberately
; uses no LOCK instructions, fences or PAUSE on the normal data path: x86
; store/store and load/load order and fresh loads across slices are sufficient.
bits 32
org 0x100000
%define CONTROL 0x380000
%define QUEUES 0x390000
%define RECORDS 0x381000
header:
    dd 0x1BADB002, 0x10000, -(0x1BADB002 + 0x10000)
    dd header, header, end, end, start
start:
    cli
    cld
    mov esi, edi
    lgdt [gdtr]
    jmp 8:protected
protected:
    mov ax, 16
    mov ds, ax
    mov es, ax
    mov ss, ax
    lea esp, [esi + 1]
    shl esp, 16
    add esp, 0x300000
    mov ebp, esi
    shr ebp, 1
    shl ebp, 12
    add ebp, QUEUES
    mov edi, 1
    xor ebx, ebx
    test esi, 1
    jz consumer
producer:
    mov eax, [ebp]                 ; producer-owned HEAD
    mov ecx, eax
    sub ecx, [ebp + 64]            ; acquire latest consumer TAIL
    cmp ecx, 16
    je producer
    mov edx, eax
    and edx, 15
    shl edx, 3
%ifdef PUBLISH_EARLY
    inc eax
    mov [ebp], eax
    pause                         ; force observer between bad publish/payload
%endif
    mov [ebp + edx + 128], edi
    mov ecx, edi
    not ecx
    mov [ebp + edx + 132], ecx
%ifndef PUBLISH_EARLY
    inc eax
    mov [ebp], eax                 ; release payload with ordinary x86 store
%endif
    inc edi
    cmp edi, [CONTROL]
    jbe producer
    jmp done
consumer:
    mov eax, [ebp + 64]
    cmp eax, [ebp]                 ; acquire published HEAD, no cached load
    je consumer
    mov edx, eax
    and edx, 15
    shl edx, 3
    cmp [ebp + edx + 128], edi
    jne failed
    mov ecx, edi
    not ecx
    cmp [ebp + edx + 132], ecx
    jne failed
    add ebx, edi
    inc eax
    mov [ebp + 64], eax            ; release slot only after both payload reads
    inc edi
    cmp edi, [CONTROL]
    jbe consumer
done:
    mov edx, esi
    shl edx, 6
    mov [RECORDS + edx + 4], ebx
    mov [RECORDS + edx + 8], edi
    lea eax, [esi + 0xD0D0]
    mov [RECORDS + edx], eax
.halt:
    hlt
    jmp .halt
failed:
    mov [CONTROL + 4], edi
    lea eax, [esi + 1]
    mov [CONTROL + 8], eax
    jmp done
align 8
gdt:
    dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF
gdtr:
    dw $ - gdt - 1
    dd gdt
end:
                                                                                                                                                                                                                                 source/v64/tests/smp/memory_order.mjs                                                               0000644 0000000 0000000 00000010347 00000000000 015050  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
import assert from "node:assert/strict";
import fs from "node:fs";
import { spawnSync } from "node:child_process";
import { setImmediate as set_immediate } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { smp_modes, with_smp_mode, compiled_hits } from "../lib/smp_modes.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const mutation = process.env.SMP_MUTATION || "";
assert.ok(["", "publish-early"].includes(mutation));
fs.mkdirSync(root + "build/smp", { recursive: true });
const kernel = root + `build/smp/memory_order${mutation ? "-" + mutation : ""}.bin`;
const assembled = spawnSync("nasm", [...(mutation ? ["-DPUBLISH_EARLY"] : []), "-f", "bin", "-o", kernel, root + "tests/smp/memory_order.asm"], { encoding: "utf8" });
assert.equal(assembled.status, 0, assembled.stderr);
const seeds = process.env.SMP_SEEDS?.split(",").map(Number) || Array.from({ length: 10 }, (_, i) => i + 1);
const modes = smp_modes();
const quantums = process.env.SMP_QUANTUMS?.split(",").map(Number) || [17, 257, 4096];
const CONTROL = 0x380000;
const RECORDS = 0x381000;

async function run(cores, seed, quantum, mode)
{
    const count = 4096 + seed * 17;
    const emulator = new V86(with_smp_mode({ graphics_adapter: "bochs_vga", multiboot: { url: kernel }, memory_size: 16 << 20,
        acpi: true, cpu_cores: cores, cpu_quantum: quantum, cpu_schedule_seed: seed,
        disable_jit: mode === "interpreter", experimental_smp_jit: true, ir_sync_publication: true,
        autostart: false, log_level: 0 }, mode));
    const label = `${mode} cores=${cores} seed=${seed} quantum=${quantum}`;
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const cpu = emulator.v86.cpu;
        const e = cpu.wm.exports;
        const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        const word = address => view().getUint32(address, true);
        view().setUint32(CONTROL, count, true);
        const entry = cpu.save_core_state();
        for(let id = 0; id < cores; id++)
        {
            cpu.switch_core(id);
            cpu.load_core_state(entry);
            cpu.reg32[7] = id;
            cpu.cores[id].running = true;
        }
        cpu.switch_core(0);
        let rounds = 0;
        const deadline = performance.now() + 30000;
        while(Array.from({ length: cores }, (_, id) => word(RECORDS + id * 64)).some((value, id) => value !== 0xD0D0 + id))
        {
            assert.equal(word(CONTROL + 8), 0, `${label}: payload observed before publication or slot reused before read, sequence=${word(CONTROL + 4)}`);
            if(performance.now() >= deadline) throw new Error(`${label}: queue stalled ${JSON.stringify(cpu.get_diagnostics())}`);
            cpu.run_cores();
            if((++rounds & 1023) === 0) await set_immediate();
        }
        assert.equal(word(CONTROL + 8), 0, `${label}: queue payload mismatch`);
        for(let id = 0; id < cores; id++)
        {
            assert.equal(word(RECORDS + id * 64 + 8), count + 1, `${label}: core ${id} completed every item`);
            assert.equal(word(RECORDS + id * 64 + 4), id & 1 ? 0 : count * (count + 1) / 2, `${label}: consumer ${id} checksum`);
            assert.equal(word(0x390000 + (id >> 1) * 4096 + (id & 1 ? 0 : 64)), count, `${label}: queue fully drained`);
        }
        const hits = compiled_hits(e);
        if(mode !== "interpreter") assert.ok(hits > 0, `${label}: compiled queue actually executed`);
        else assert.equal(hits, 0);
        return hits;
    }
    finally { await emulator.destroy(); }
}

let cases = 0;
for(const mode of modes)
{
    let hits = 0;
    for(const quantum of quantums)
    {
        for(const seed of seeds)
        {
            hits += await run(2, seed, quantum, mode);
            cases++;
        }
    }
    for(const cores of [4, 8])
    {
        hits += await run(cores, 1, 257, mode);
        cases++;
    }
    console.log(`${mode}: lock-free publication/queue passed ${seeds.length} seeds × ${quantums.length} quantums, 2/4/8 cores; compiled activations=${hits}`);
}
console.log(`SMP memory ordering: ${cases} cases passed`);
                                                                                                                                                                                                                                                                                         source/v64/tests/smp/os_stress.mjs                                                                  0000644 0000000 0000000 00000036603 00000000000 014374  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Real Linux cross-core stress: fork/shared publication, signal delivery, migration,
// IDE sectors and NE2K frames while the whole machine is stopped and restored.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createHash as create_hash } from "node:crypto";
import { setImmediate as set_immediate } from "node:timers";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { smp_modes, with_smp_mode, mode_hits } from "../lib/smp_modes.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const module_url = new URL(process.env.V86_MODULE || (+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js"), import.meta.url);
const { V86 } = await import(module_url.href);
const mutation = process.env.SMP_OS_MUTATION || "";
assert.ok(["", "network-corruption"].includes(mutation));
const modes = smp_modes();
const seeds = process.env.SMP_SEEDS?.split(",").map(Number) || Array.from({ length: 10 }, (_, i) => i + 1);
const quantums = process.env.SMP_QUANTUMS?.split(",").map(Number) || [257, 4096];
const cores = +(process.env.CPU_CORES || 4);
const parallel = +process.env.PARALLEL;
const rounds = +(process.env.SMP_ROUNDS || 256);
const timeout_ms = +(process.env.SMP_TIMEOUT_MS || 180000);
const log_dir = process.env.C3_LOG_DIR;
const boot_cache = process.env.C3_BOOT_CACHE;
if(boot_cache) fs.mkdirSync(boot_cache, { recursive: true });
if(log_dir) fs.mkdirSync(log_dir, { recursive: true });
assert.ok(Number.isInteger(cores) && cores >= 2 && cores <= 8);
assert.ok(Number.isInteger(rounds) && rounds >= 16 && rounds <= 4096 && rounds % 8 === 0);
assert.ok(seeds.length && seeds.every(seed => Number.isInteger(seed) && seed >= 1 && seed <= 0xFFFFFFFF));
assert.ok(quantums.length && quantums.every(quantum => Number.isInteger(quantum) && quantum >= 1 && quantum <= 100000));
fs.mkdirSync(path.join(root, "build/smp"), { recursive: true });
function command(program, args)
{
    const result = spawnSync(program, args, { encoding: "utf8" });
    assert.equal(result.status, 0, `${program}: ${result.stderr || result.error}`);
    return result.stdout.trim();
}
const target = command("rustc", ["-vV"]).match(/host: (.+)/)[1];
const linker = process.env.LD_LLD || path.join(command("rustc", ["--print", "sysroot"]), "lib/rustlib", target, "bin/rust-lld");
command(process.env.CLANG || "clang", ["--target=i386-unknown-linux-gnu", "-m32", "-O2", "-ffreestanding", "-fno-stack-protector", "-fno-pic", "-fno-builtin", "-mno-sse", "-mno-mmx", "-c", path.join(root, "tests/smp/os_stress_guest.c"), "-o", path.join(root, "build/smp/os_stress_guest.o")]);
command(linker, ["-flavor", "gnu", "-m", "elf_i386", "-static", "-e", "_start", "-o", path.join(root, "build/smp/os_stress_guest"), path.join(root, "build/smp/os_stress_guest.o")]);
const guest = fs.readFileSync(path.join(root, "build/smp/os_stress_guest"));
const digest = data => create_hash("sha256").update(data).digest("hex");
const wasm_bytes = fs.readFileSync(process.env.WASM_PATH || path.join(root, +process.env.TEST_RELEASE_BUILD ? "build/v86.wasm" : "build/v86-debug.wasm"));
const wasm_module = await WebAssembly.compile(wasm_bytes);
const media = { javascript_entry: digest(fs.readFileSync(module_url)), wasm: digest(wasm_bytes), linux4: digest(fs.readFileSync(path.join(root, "images/linux4.iso"))), guest: digest(guest), disk_sha256: digest(new Uint8Array(4 << 20)), disk: "4 MiB zero-filled disposable IDE disk; writes at 1 MiB + (seed & 31) * 8192" };

for(const mode of modes)
{
    const disk = new Uint8Array(4 << 20);
    // PARALLEL=1: the application processors run in vCPU workers
    const emulator = new V86(with_smp_mode({ graphics_adapter: "bochs_vga", ...(parallel ? { wasm_path: path.join(root, "build/v86-parallel.wasm"), parallel: true } :
        { wasm_fn: async imports => (await WebAssembly.instantiate(wasm_module, imports)).exports }),
        bios: { url: path.join(root, "bios/seabios.bin") }, vga_bios: { url: path.join(root, "bios/vgabios.bin") },
        cdrom: { url: path.join(root, "images/linux4.iso") }, hda: { buffer: disk.buffer },
        memory_size: 128 << 20, cpu_cores: cores, acpi: true, cpu_schedule_seed: seeds[0],
        disable_jit: mode === "interpreter", experimental_smp_jit: mode !== "interpreter",
        ir_sync_publication: true, filesystem: {}, net_device: { type: "ne2k" }, autostart: false, log_level: 0 }, mode, false));
    let serial = "", phase = "load", cpu, packets = 0, received = 0, poweroffs = 0, disk_reads = 0, disk_writes = 0;
    const started_ms = performance.now();
    const results = [];
    const frame_lengths = new Set();
    const per_core_jit = Array.from({ length: cores }, () => 0);
    emulator.add_listener("serial0-output-byte", byte => { const ch = String.fromCharCode(byte); serial += ch; if(+process.env.SHOW_LOGS) process.stdout.write(ch); });
    emulator.add_listener("acpi-power-off", () => poweroffs++);
    emulator.add_listener("ide-read-end", event => { if(event[0] === 0) disk_reads += event[1]; });
    emulator.add_listener("ide-write-end", event => { if(event[0] === 0) disk_writes += event[1]; });
    emulator.bus.register("net0-send", packet => {
        if(packet.length < 14 || packet[12] !== 0x88 || packet[13] !== 0xB5) return;
        packets++;
        frame_lengths.add(packet.length);
        if(+process.env.SHOW_LOGS) console.log(`C3_HOST_PACKET length=${packet.length} bytes=${Buffer.from(packet.subarray(0, 32)).toString("hex")}`);
        const reply = Uint8Array.from(packet);
        reply.fill(255, 0, 6); reply.set([2,0,0,0,0,2], 6);
        if(mutation === "network-corruption") reply[18] ^= 1;
        set_immediate(() => { received++; emulator.bus.send("net0-receive", reply); });
    });
    async function until(label, predicate)
    {
        phase = label;
        const deadline = performance.now() + timeout_ms;
        while(!predicate())
        {
            assert.ok(performance.now() < deadline, `${mode}: ${label} timed out`);
            assert.ok(!serial.includes("Kernel panic"), "kernel panic");
            assert.ok(!serial.includes("C3_FAIL"), serial.slice(-1000));
            await new Promise(resolve => setTimeout(resolve, 5));
        }
    }
    function summary(text, seed)
    {
        const record = text.match(new RegExp(`C3_DONE seed=${seed} rounds=(\\d+) cores=(\\d+) signals=(\\d+) io=(\\d+) cpu_checks=([\\d,]+)`));
        assert.ok(record, "guest completion record");
        assert.equal(+record[1], rounds); assert.equal(+record[2], cores); assert.ok(+record[3] > 0); assert.equal(+record[4], rounds / 8);
        const cpu_checks = record[5].split(",").map(Number);
        assert.equal(cpu_checks.length, cores); assert.ok(cpu_checks.every(value => value === rounds), "every core receives exactly one affinity/getcpu check per round");
        return { rounds: +record[1], cores: +record[2], io: +record[4], cpu_checks };
    }
    async function run_round(seed, quantum, snapshot)
    {
        const round_started_ms = performance.now();
        cpu.scheduler_seed = seed;
        cpu.scheduler_quantum = quantum;
        if(parallel) for(let core = 1; core < cores; core++) per_core_jit[core] = cpu.parallel.core_counters(core).jit;
        const begin = serial.length, net_before = packets, reads_before = disk_reads, writes_before = disk_writes, jit_before = per_core_jit.slice();
        emulator.serial0_send(`/tmp/c3-stress ${cores} ${seed} ${rounds}\n`);
        await until(`seed=${seed} quantum=${quantum} active`, () => serial.slice(begin).includes(`C3_ACTIVE seed=${seed}\r\n`));
        let saved;
        if(snapshot)
        {
            await emulator.stop();
            const stopped = cpu.get_machine_core_state();
            const clock = cpu.clock.get_state();
            saved = await emulator.save_state();
            await new Promise(resolve => setTimeout(resolve, 25));
            assert.deepEqual(cpu.get_machine_core_state(), stopped, "stop freezes every core");
            assert.deepEqual(cpu.clock.get_state(), clock, "stop freezes machine time");
            emulator.run();
        }
        await until(`seed=${seed} quantum=${quantum} completion`, () => serial.slice(begin).includes(`C3_DONE seed=${seed} `));
        await until("shell after workload", () => /~% $/.test(serial));
        await emulator.stop();
        const first = summary(serial.slice(begin), seed);
        assert.ok(packets - net_before >= rounds / 8, "guest uses emulated NE2K transmit");
        assert.equal(received, packets, "every frame echoed through NE2K receive");
        assert.ok(disk_reads - reads_before >= rounds / 8 * 4096, "O_DIRECT reads reach IDE");
        assert.ok(disk_writes - writes_before >= rounds / 8 * 4096, "O_DIRECT writes reach IDE");
        if(saved)
        {
            await emulator.restore_state(saved);
            const replay_begin = serial.length;
            emulator.run();
            await until("snapshot replay", () => serial.slice(replay_begin).includes(`C3_DONE seed=${seed} `));
            await until("shell after replay", () => /~% $/.test(serial));
            await emulator.stop();
            assert.deepEqual(summary(serial.slice(replay_begin), seed), first, "restored OS processes preserve publication/migration/disk/network work");
        }
        if(parallel) for(let core = 1; core < cores; core++) per_core_jit[core] = cpu.parallel.core_counters(core).jit;
        const jit = per_core_jit.map((value, i) => value - jit_before[i]);
        if(mode === "interpreter") assert.ok(jit.every(value => value === 0));
        else assert.ok(jit.every(value => value > 0), "each core executes compiled code during workload");
        const record = { seed, quantum, wall_ms: Math.round(performance.now() - round_started_ms), snapshot: !!saved, ...first, packets: packets - net_before, disk_read_bytes: disk_reads - reads_before, disk_write_bytes: disk_writes - writes_before, jit };
        results.push(record);
        console.log(`${mode}: OS stress passed ${JSON.stringify(record)}`);
        emulator.run();
    }
    try
    {
        await new Promise((resolve, reject) => {
            const timer = setTimeout(() => reject(new Error("load timeout")), 15000);
            emulator.add_listener("emulator-loaded", () => { clearTimeout(timer); resolve(); });
            emulator.add_listener("emulator-error", reject);
        });
        cpu = emulator.v86.cpu;
        const e = cpu.wm.exports;
        const run_slice = cpu.run_cpu_slice.bind(cpu);
        const jit_count = () => mode_hits(e, mode);
        cpu.run_cpu_slice = budget => { const id = cpu.active_core, before = jit_count(); const r = run_slice(budget); per_core_jit[id] += (jit_count() - before) >>> 0; return r; };
        // (with vCPU workers the machine's own core runs through main_loop)
        const main_loop = cpu.main_loop.bind(cpu);
        cpu.main_loop = () => { const before = jit_count(); const r = main_loop(); per_core_jit[0] += (jit_count() - before) >>> 0; return r; };
        const cached = boot_cache && path.join(boot_cache, `linux4-${mode}-${cores}.bin`);
        if(cached && fs.existsSync(cached)) await emulator.restore_state(Uint8Array.from(fs.readFileSync(cached)).buffer);
        else
        {
            emulator.run();
            await until("boot", () => /~% $/.test(serial));
            await emulator.stop();
            if(cached) fs.writeFileSync(cached, new Uint8Array(await emulator.save_state()));
        }
        await emulator.create_file("c3-stress", guest);
        emulator.run();
        emulator.serial0_send("cp /mnt/c3-stress /tmp/c3-stress; chmod 755 /tmp/c3-stress; ifconfig eth0 up; echo C3_READY\n");
        await until("guest setup", () => serial.includes("C3_READY\r\n") && /~% $/.test(serial));
        for(const quantum of quantums) for(const seed of seeds) await run_round(seed, quantum, seed === seeds[0]);
        const reset_begin = serial.length;
        await emulator.restart();
        await until("whole machine reboot", () => serial.slice(reset_begin).includes("Files send via emulator") && /~% $/.test(serial));
        emulator.serial0_send("printf 'C3_REBOOT_ONLINE '; cat /sys/devices/system/cpu/online; poweroff -f\n");
        await until("guest ACPI S5", () => poweroffs > 0 && !emulator.is_running());
        assert.match(serial.slice(reset_begin), new RegExp(`C3_REBOOT_ONLINE 0-${cores - 1}`));
        assert.equal(cpu.clock.paused, true, "S5 pauses the machine clock");
        const powered_off = cpu.get_machine_core_state();
        await new Promise(resolve => setTimeout(resolve, 25));
        assert.deepEqual(cpu.get_machine_core_state(), powered_off, "S5 leaves every core stopped");
        console.log(`${mode}: reboot re-onlines ${cores} cores and guest ACPI S5 stops the machine`);
    }
    catch(error)
    {
        const vga_text = cpu && Array.from({ length: 25 }, (_, row) => Array.from({ length: 80 }, (_, column) =>
            String.fromCharCode(cpu.mem8[0xB8000 + (row * 80 + column) * 2] || 32)).join("").trimEnd()).join("\n");
        console.error(JSON.stringify({ mode, phase, packets, received, serial_tail: serial.slice(-15000), vga_text, diagnostics: cpu?.get_diagnostics() }, null, 2));
        if(log_dir && cpu)
        {
            await emulator.stop();
            const failure_state = await emulator.save_state();
            fs.writeFileSync(path.join(log_dir, `os-stress-${mode}-failure.bin`), new Uint8Array(failure_state));
            cpu.switch_core(0);
            const ip = cpu.instruction_pointer[0] >>> 0;
            const physical = cpu.translate_address_system_read(ip);
            const instruction = { ip, physical, registers: [...cpu.reg32].map(value => value >>> 0),
                bytes: Buffer.from(cpu.mem8.subarray(physical, physical + 64)).toString("hex") };
            fs.writeFileSync(path.join(log_dir, `os-stress-${mode}-instruction.json`), JSON.stringify(instruction, null, 2) + "\n");
            if(+process.env.SMP_RECOVER_INTERPRETER)
            {
                await emulator.restore_state(failure_state);
                // (no compilation: the page tier neither compiles nor enters
                // its functions with the JIT disabled)
                assert.equal(cpu.wm.exports.jit_set_enabled(0), 1);
                const recovery_begin = serial.length;
                emulator.run();
                const recovery_deadline = performance.now() + 30000;
                while(performance.now() < recovery_deadline && !/Files send via emulator[\s\S]*~% $/.test(serial.slice(recovery_begin)))
                    await new Promise(resolve => setTimeout(resolve, 20));
                await emulator.stop();
                const recovery = { reached_shell: /~% $/.test(serial.slice(recovery_begin)), serial: serial.slice(recovery_begin), diagnostics: cpu.get_diagnostics() };
                fs.writeFileSync(path.join(log_dir, `os-stress-${mode}-recovery.json`), JSON.stringify(recovery, null, 2) + "\n");
                console.log("interpreter recovery " + JSON.stringify(recovery));
            }
        }
        throw error;
    }
    finally
    {
        if(log_dir)
        {
            fs.writeFileSync(path.join(log_dir, `os-stress-${mode}.log`), serial);
            fs.writeFileSync(path.join(log_dir, `os-stress-${mode}.json`), JSON.stringify({ media, mode, cores, mutation, wall_ms: Math.round(performance.now() - started_ms), results, packets, received, frame_lengths: [...frame_lengths], poweroffs, disk_reads, disk_writes, per_core_jit }, null, 2) + "\n");
        }
        await emulator.destroy();
    }
}
                                                                                                                             source/v64/tests/smp/os_stress_guest.c                                                              0000644 0000000 0000000 00000017424 00000000000 015234  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Freestanding i386 Linux cross-core stress workload. Build with os_stress.mjs.
 * MAP_SHARED publication is deliberately ordinary x86 loads/stores; only the
 * shared progress increment is LOCKed. Nothing edits the emulator's CPU state. */
typedef unsigned int u32;
typedef unsigned char u8;
static int sc(int n, int a, int b, int c, int d, int e)
{
    int r;
    __asm__ volatile("int $0x80" : "=a"(r) : "a"(n), "b"(a), "c"(b), "d"(c), "S"(d), "D"(e) : "memory", "cc");
    return r;
}
#define S(n,a,b,c) sc(n,(int)(a),(int)(b),(int)(c),0,0)
static int length(const char *s) { int n = 0; while(s[n]) n++; return n; }
static void out(const char *s) { S(4,1,s,length(s)); }
static void number(u32 n) { char b[12]; int i = 11; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); out(b + i); }
static void die(const char *s) { out("C3_FAIL "); out(s); out("\n"); S(1,1,0,0); for(;;); }
static int check(int n, const char *s) { if(n < 0) die(s); return n; }
static void yield(void) { S(158,0,0,0); }
struct slot { volatile u32 sequence, ack, payload, inverse; };
struct shared { struct slot slots[8]; volatile u32 progress[8], cpu_checks[8], signals, fail; };
static struct shared *shared;
static u32 cores, seed, rounds;
static int parent_pid;
static void signal_handler(int n) { (void)n; __asm__ volatile("lock incl %0" : "+m"(shared->signals) :: "memory", "cc"); }
__asm__(".text\n.global signal_return\nsignal_return:\nmov $173,%eax\nint $0x80\nud2\n");
extern void signal_return(void);
static void bind_cpu(u32 id)
{
    u32 mask = 1u << id, actual = 0xFFFFFFFF;
    check(S(241,0,4,&mask), "affinity");
    check(S(318,&actual,0,0), "getcpu");
    if(actual != id) die("migration");
    __asm__ volatile("lock incl %0" : "+m"(shared->cpu_checks[id]) :: "memory", "cc");
}
static u32 value(u32 iteration, u32 id) { return (seed * 1664525u + iteration * 1013904223u) ^ (id * 0x9E3779B9u); }
static void child(u32 id)
{
    for(u32 i = 1; i <= rounds; i++)
    {
        bind_cpu((id + i / 8) % cores);
        struct slot *s = &shared->slots[id];
        while(s->sequence != i) yield();
        if(s->payload != value(i,id) || s->inverse != ~s->payload) die("publication");
        __asm__ volatile("lock incl %0" : "+m"(shared->progress[id]) :: "memory", "cc");
        s->ack = i;
        if((i & 7) == 0) check(S(37,parent_pid,10,0), "kill");
    }
    S(1,0,0,0);
    for(;;);
}
static int socket_call(int op, int *args) { return S(102,op,args,0); }
struct sockaddr_ll { unsigned short family, protocol; int ifindex; unsigned short hatype; u8 pkttype, halen, addr[8]; };
static int net_open(struct sockaddr_ll *address)
{
    int args[6] = {17,3,0xB588,0,0,0};
    int fd = check(socket_call(1,args), "socket");
    int socket_type = 0, type_length = 4;
    args[0] = fd; args[1] = 1; args[2] = 3; args[3] = (int)&socket_type; args[4] = (int)&type_length;
    check(socket_call(15,args), "socket type");
    if(socket_type != 3) { out("C3_SOCKET_TYPE "); number(socket_type); out("\n"); die("socket type mismatch"); }
    char request[40] = {'e','t','h','0',0};
    check(S(54,fd,0x8933,request), "ifindex");
    address->family = 17; address->protocol = 0xB588;
    address->ifindex = *(int *)(request + 16); address->halen = 6;
    for(u32 i = 0; i < 6; i++) address->addr[i] = 255;
    args[0] = fd; args[1] = (int)address; args[2] = sizeof(*address);
    check(socket_call(2,args), "bind packet socket");
    int timeout[2] = {5,0};
    args[0] = fd; args[1] = 1; args[2] = 20; args[3] = (int)timeout; args[4] = sizeof(timeout);
    check(socket_call(14,args), "socket timeout");
    return fd;
}
static void net_round(int fd, struct sockaddr_ll *address, u32 iteration)
{
    u8 frame[64] = {0}, received[128];
    for(int i = 0; i < 6; i++) frame[i] = 255;
    frame[6] = 2; frame[11] = 1; frame[12] = 0x88; frame[13] = 0xB5;
    for(u32 i = 14; i < sizeof(frame); i++) frame[i] = (u8)(value(iteration,i) >> (i & 7));
    /* EtherType payload declares its length; link-layer padding is ignored. */
    frame[14] = sizeof(frame) - 14; frame[15] = frame[16] = frame[17] = 0;
    int args[6] = {fd,(int)frame,sizeof(frame),0,(int)address,sizeof(*address)};
    if(check(socket_call(11,args), "send packet") != sizeof(frame)) die("short network send");
    for(;;)
    {
        args[0] = fd; args[1] = (int)received; args[2] = sizeof(received); args[3] = args[4] = args[5] = 0;
        int n = socket_call(12,args);
        if(n == -4) continue;
        if(check(n,"receive packet") < (int)sizeof(frame)) die("short network payload");
        for(u32 i = 14; i < sizeof(frame); i++) if(frame[i] != received[i]) die("network payload");
        break;
    }
}
static u8 disk_write[4096] __attribute__((aligned(4096)));
static u8 disk_read[4096] __attribute__((aligned(4096)));
static void disk_round(int fd, u32 iteration)
{
    int offset = (1 << 20) + (seed & 31) * 8192;
    for(u32 i = 0; i < sizeof(disk_write); i++) disk_write[i] = (u8)(value(iteration,i) >> (i & 7));
    check(S(19,fd,offset,0),"disk seek write");
    if(check(S(4,fd,disk_write,sizeof(disk_write)),"disk write") != sizeof(disk_write)) die("disk short write");
    check(S(118,fd,0,0),"disk fsync");
    check(S(19,fd,offset,0),"disk seek read");
    if(check(S(3,fd,disk_read,sizeof(disk_read)),"disk read") != sizeof(disk_read)) die("disk short read");
    for(u32 i = 0; i < sizeof(disk_write); i++) if(disk_read[i] != disk_write[i]) die("disk payload");
}
static u32 parse(char *s) { u32 n = 0; while(*s >= '0' && *s <= '9') n = n * 10 + *s++ - '0'; return n; }
void entry(int *stack)
{
    if(stack[0] != 4) die("usage: cores seed rounds");
    char **argv = (char **)(stack + 1);
    cores = parse(argv[1]); seed = parse(argv[2]); rounds = parse(argv[3]);
    if(cores < 2 || cores > 8 || rounds < 16 || rounds > 4096) die("arguments");
    u32 mapping[6] = {0,4096,3,0x21,0xFFFFFFFF,0};
    shared = (struct shared *)S(90,mapping,0,0);
    if((u32)shared >= 0xFFFFF001u) die("mmap shared");
    /* mmap may return a valid address with its high bit set. */
    parent_pid = check(S(20,0,0,0),"getpid");
    struct { void (*handler)(int); u32 flags; void (*restorer)(void); u32 mask[2]; } action = {signal_handler,0x04000004,signal_return,{0,0}};
    check(sc(174,10,(int)&action,0,8,0), "sigaction");
    int disk = S(5,"/dev/sda",2 | 0x4000,0);
    if(disk < 0) disk = S(5,"/dev/hda",2 | 0x4000,0);
    check(disk,"open emulated disk");
    struct sockaddr_ll address = {0};
    int net = net_open(&address);
    for(u32 id = 1; id < cores; id++) if(check(S(2,0,0,0),"fork") == 0) child(id);
    out("C3_ACTIVE seed="); number(seed); out("\n");
    for(u32 i = 1; i <= rounds; i++)
    {
        bind_cpu((i / 8) % cores);
        for(u32 id = 1; id < cores; id++)
        {
            struct slot *s = &shared->slots[id];
            s->payload = value(i,id); s->inverse = ~s->payload;
            __asm__ volatile("" ::: "memory");
            s->sequence = i;
        }
        for(u32 id = 1; id < cores; id++) while(shared->slots[id].ack != i) yield();
        shared->progress[0]++;
        if((i & 7) == 0) { disk_round(disk,i); net_round(net,&address,i); }
    }
    for(u32 id = 1; id < cores; id++) { int status, result; do { result = S(7,-1,&status,0); } while(result == -4); check(result,"waitpid"); if(status) die("child exit"); }
    if(!shared->signals) die("no signal delivery");
    for(u32 id = 0; id < cores; id++) if(shared->progress[id] != rounds || shared->cpu_checks[id] != rounds) die("core progress");
    out("C3_DONE seed="); number(seed); out(" rounds="); number(rounds); out(" cores="); number(cores);
    out(" signals="); number(shared->signals); out(" io="); number(rounds / 8); out(" cpu_checks=");
    for(u32 id = 0; id < cores; id++) { if(id) out(","); number(shared->cpu_checks[id]); }
    out("\n");
    S(1,0,0,0);
    for(;;);
}
__asm__(".text\n.global _start\n_start:\nmov %esp,%eax\npush %eax\ncall entry\nud2\n");
                                                                                                                                                                                                                                            source/v64/tests/smp/physical_bus.mjs                                                               0000644 0000000 0000000 00000036517 00000000000 015041  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Real Wasm memory/MMIO and VirtIO transport through the 36-bit bus.
import assert from "node:assert/strict";
import { VirtIO } from "../../src/virtio.js";
const { V86 } = await import(process.env.V86_LIB_PATH || (+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js"));
const emulator = new V86({ graphics_adapter: "bochs_vga", wasm_path: process.env.WASM_PATH, memory_size: 16 << 20,
    disable_jit: true, autostart: false, log_level: 0, net_device: { type: "none" },
    hda: { buffer: new ArrayBuffer(8192) }, virtio_balloon: true });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
try
{
    const cpu = emulator.v86.cpu, e = cpu.wm.exports;
    const HIGH = 2 ** 32, LIMIT = 2 ** 36;
    const generation = () => (e.x64_phys_generation(false) >>> 0) + (e.x64_phys_generation(true) >>> 0) * HIGH;
    const map = (slot, address, backing, length, kind = 1) =>
        e.x64_phys_set_window(slot, address >>> 0, Math.floor(address / HIGH), backing, length, kind);
    const before = generation();
    assert.equal(map(0, HIGH, 0x200000, 0x10000), 1);
    assert.ok(generation() > before);
    const first = generation();
    assert.equal(map(0, HIGH, 0x200000, 0x10000), 1);
    assert.equal(generation(), first, "no-op mapping does not invalidate again");
    assert.deepEqual(Array.from({ length: 5 }, (_, field) => e.x64_phys_get_window(0, field)), [0, 1, 0x200000, 0x10000, 1]);
    assert.equal(map(1, HIGH + 0x1000, 0x220000, 0x1000), 0, "overlap rejected");
    assert.equal(generation(), first, "failed mapping changes nothing");
    assert.throws(() => cpu.read8_physical(0x200000), RangeError, "relocated low physical RAM is a hole");
    cpu.write32_physical(0x1000, 0xAABBCCDD);
    cpu.write32_physical(HIGH + 0x1000, 0x12345678);
    assert.equal(cpu.read32_physical(HIGH + 0x1000), 0x12345678);
    assert.equal(cpu.read32_physical(0x1000), 0xAABBCCDD, "high physical access never aliases its low DWORD");
    assert.equal(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x201000, true), 0x12345678);
    assert.equal(!!cpu.in_mapped_range(0x201000), true);
    assert.equal(!!cpu.in_mapped_range(0x210000), false, "RAM above the first hole still has an ordinary fast mapping");
    assert.equal(cpu.read32s(0x201000) >>> 0, 0xFFFFFFFF, "legacy physical read sees a hole");
    cpu.write32(0x201000, 0xBAD);
    assert.equal(cpu.read32_physical(HIGH + 0x1000), 0x12345678, "legacy physical write cannot reach relocated backing");
    const first_high_bytes = cpu.read_blob_physical(HIGH, 2);
    cpu.write32(0x1FFFFE, 0x11223344);
    assert.deepEqual(cpu.mem8.slice(0x1FFFFE, 0x200000), new Uint8Array([0x44, 0x33]));
    assert.deepEqual(cpu.read_blob_physical(HIGH, 2), first_high_bytes, "straddling legacy physical write ignores hole bytes");
    assert.equal(cpu.read32s(0x1FFFFE) >>> 0, 0xFFFF3344);

    assert.equal(map(1, HIGH + 0x10000, 0x220000, 0x1000), 1);
    const split = new Uint8Array([1, 2, 3, 4]);
    cpu.write_blob_physical(split, HIGH + 0xFFFE);
    assert.deepEqual(cpu.read_blob_physical(HIGH + 0xFFFE, 4), split);
    assert.equal(cpu.read32_physical(HIGH + 0xFFFE), 0x04030201);
    assert.deepEqual(cpu.mem8.slice(0x20FFFE, 0x210000), split.slice(0, 2));
    assert.deepEqual(cpu.mem8.slice(0x220000, 0x220002), split.slice(2));
    const unchanged = cpu.mem8.slice(0x220FFC, 0x221000);
    assert.throws(() => cpu.write_blob_physical(new Uint8Array(8).fill(0xFF), HIGH + 0x10FFC), RangeError);
    assert.deepEqual(cpu.mem8.slice(0x220FFC, 0x221000), unchanged, "whole blob validated before first write");
    assert.throws(() => cpu.read8_physical(LIMIT), RangeError);
    assert.throws(() => cpu.write32_physical(LIMIT - 2, 1), RangeError);
    console.log("PASS physical Wasm RAM relocation, split windows, all-or-nothing invalid range");

    const device = new Uint8Array(0x20000), view = new DataView(device.buffer), trace = [];
    const MMIO = 0x10000000, HIGH_MMIO = 2 * HIGH;
    cpu.io.mmap_register(MMIO, device.length,
        address => { trace.push(["r8", address]); return device[(address >>> 0) - MMIO]; },
        (address, value) => { trace.push(["w8", address]); device[(address >>> 0) - MMIO] = value; },
        address => { trace.push(["r32", address]); return view.getInt32((address >>> 0) - MMIO, true); },
        (address, value) => { trace.push(["w32", address]); view.setInt32((address >>> 0) - MMIO, value, true); });
    assert.equal(map(2, HIGH_MMIO, MMIO, 0x1000, 2), 1);
    cpu.write32_physical(HIGH_MMIO + 4, 0x87654321);
    assert.equal(cpu.read32_physical(HIGH_MMIO + 4), 0x87654321);
    assert.deepEqual(trace.map(([kind]) => kind), ["w32", "r32"]);
    assert.equal(cpu.read32_physical(MMIO + 4), 0x87654321, "MMIO window explicitly aliases existing device decode");
    trace.length = 0;
    assert.throws(() => cpu.write32_physical(HIGH_MMIO + 0xFFE, 0xAAAAAAAA), RangeError);
    assert.equal(trace.length, 0, "invalid second half cannot trigger first-half MMIO");
    const last_device = new Uint8Array(0x20000);
    cpu.io.mmap_register(0xFFFE0000, last_device.length,
        address => last_device[(address >>> 0) - 0xFFFE0000],
        (address, value) => { last_device[(address >>> 0) - 0xFFFE0000] = value; });
    cpu.write32_physical(HIGH - 2, 0x44332211);
    assert.deepEqual(last_device.slice(-2), new Uint8Array([0x11, 0x22]));
    assert.deepEqual(cpu.mem8.slice(0x200000, 0x200002), new Uint8Array([0x33, 0x44]));
    assert.equal(cpu.read32_physical(HIGH - 2), 0x44332211);
    console.log("PASS physical Wasm high MMIO, no premature MMIO effects, cross-4GiB scalar");

    const options = {
        name: "high-dma-wasm", pci_id: 0x78, device_id: 0x1041, subsystem_device_id: 1,
        common: { initial_port: 0xAF00, features: [28, 29, 32], queues: [{ size_supported: 8, notify_offset: 0 }], on_driver_ok() {} },
        notification: { initial_port: 0xAF40, single_handler: true, handlers: [() => {}] },
        isr_status: { initial_port: 0xAF60 },
    };
    const virtio = new VirtIO(cpu, options), queue = virtio.queues[0];
    const table = HIGH + 0x1000, avail = HIGH + 0x2000, used = HIGH + 0x3000;
    for(const [offset, address] of [[32, table], [40, avail], [48, used]])
    {
        cpu.io.port_write32(0xAF00 + offset + 4, 1);
        cpu.io.port_write32(0xAF00 + offset, address >>> 0);
        assert.equal(cpu.io.port_read32(0xAF00 + offset + 4), 1);
    }
    cpu.write_blob_physical(new Uint8Array(0x3000), table);
    const descriptor = (address, data, length, flags, next = 0) => {
        cpu.write32_physical(address, data >>> 0);
        cpu.write32_physical(address + 4, Math.floor(data / HIGH));
        cpu.write32_physical(address + 8, length);
        cpu.write16_physical(address + 12, flags);
        cpu.write16_physical(address + 14, next);
    };
    const indirect = HIGH + 0x6000, payload = HIGH + 0x7000, reply = HIGH + 0x8000;
    const message = new Uint8Array([9, 8, 7, 6, 5]);
    descriptor(table, indirect, 32, 4);
    descriptor(indirect, payload, message.length, 1, 1);
    descriptor(indirect + 16, reply, message.length, 2);
    cpu.write_blob_physical(message, payload);
    cpu.write_blob_physical(new Uint8Array(message.length).fill(0xAA), 0x8000);
    cpu.write16_physical(avail + 2, 1);
    cpu.write16_physical(avail + 4, 0);
    cpu.io.port_write16(0xAF00 + 28, 1);
    assert.equal(queue.enabled, true);
    const chain = queue.pop_request();
    assert.equal(chain.valid, true);
    const actual = new Uint8Array(message.length);
    assert.equal(chain.get_next_blob(actual), actual.length);
    assert.deepEqual(actual, message);
    assert.equal(chain.set_next_blob(actual), actual.length);
    queue.push_reply(chain);
    queue.flush_replies();
    assert.deepEqual(cpu.read_blob_physical(reply, actual.length), message);
    assert.deepEqual(cpu.read_blob_physical(0x8000, actual.length), new Uint8Array(actual.length).fill(0xAA));
    assert.equal(cpu.read16_physical(used + 2), 1);
    assert.equal(cpu.read32_physical(used + 8), message.length);
    console.log("PASS real PCI-register VirtIO high rings, indirect table, DMA blob and completion");

    const dma = cpu.devices.dma;
    const dma_address = address => {
        dma.channel_addr[0] = address & 0xFFFF;
        dma.channel_page[0] = address >>> 16 & 255;
        dma.channel_pagehi[0] = address >>> 24;
        dma.channel_count[0] = 3;
    };
    let called = false, dma_error;
    dma_address(0x200000);
    dma.do_read({ byteLength: 4, get() { called = true; } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(dma_error, true);
    assert.equal(called, false, "8237 rejects low hole before requesting disk data");
    dma_error = undefined;
    dma.do_write({ byteLength: 4, set() { called = true; } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(dma_error, true);
    assert.equal(called, false, "8237 rejects low hole before writing disk data");
    dma_address(0x9000);
    dma.do_read({ byteLength: 4, get(start, length, done) { done(split); } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(dma_error, false);
    assert.deepEqual(cpu.read_blob_physical(0x9000, 4), split);
    dma_address(0x9000);
    dma.do_write({ byteLength: 4, set(start, data, done) { assert.deepEqual(data, split); done(); } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(dma_error, false);
    dma_address(0xFFFFFFFF);
    assert.equal(dma.address_get_8bit(0), 0xFFFFFFFF);
    dma.do_read({ byteLength: 4, get() { assert.fail("32-bit DMA must not extend into high RAM"); } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(dma_error, true);
    let delayed;
    dma_address(0x230000);
    dma.do_read({ byteLength: 4, get(start, length, done) { delayed = done; } }, 0, 4, 0, error => { dma_error = error; });
    assert.equal(map(3, HIGH + 0x20000, 0x230000, 4096), 1);
    const before_delayed = cpu.mem8.slice(0x230000, 0x230004);
    delayed(split);
    assert.equal(dma_error, true);
    assert.deepEqual(cpu.mem8.slice(0x230000, 0x230004), before_delayed, "async DMA rechecks relocation after data arrives");
    assert.equal(map(3, 0, 0, 0, 0), 1);
    console.log("PASS real 8237 DMA low holes, normal transfer, 32-bit limit, async remap rejection");

    const ide = cpu.devices.ide.primary.master, channel = cpu.devices.ide.primary;
    const prdt = 0xB000;
    const prd = (slot, address, count, end) => {
        cpu.write32_physical(prdt + slot * 8, address);
        cpu.write16_physical(prdt + slot * 8 + 4, count);
        cpu.write16_physical(prdt + slot * 8 + 6, end ? 0x8000 : 0);
    };
    const atapi_transfer = () => {
        channel.prdt_addr = prdt;
        channel.dma_status = 1;
        ide.current_command = 0xA0;
        ide.status_reg = 8;
        ide.data = new Uint8Array([5, 6, 7, 8]);
        ide.data_length = 4;
        ide.do_atapi_dma();
    };
    prd(0, 0x9000, 2, false);
    prd(1, 0x200000, 2, true);
    const before_ide = cpu.read_blob_physical(0x9000, 4);
    atapi_transfer();
    assert.equal(channel.dma_status & 3, 2);
    assert.equal(ide.error_reg, 4);
    assert.deepEqual(cpu.read_blob_physical(0x9000, 4), before_ide, "IDE prevalidates later PRD before writing the first");
    prd(1, 0x9002, 2, true);
    atapi_transfer();
    assert.equal(channel.dma_status & 3, 0);
    assert.deepEqual(cpu.read_blob_physical(0x9000, 4), new Uint8Array([5, 6, 7, 8]));
    channel.prdt_addr = 0x200000;
    assert.throws(() => ide.dma_segments(4), RangeError);
    channel.prdt_addr = prdt;
    prd(0, 0xFFFFFFFE, 4, true);
    assert.throws(() => ide.dma_segments(4), RangeError, "IDE buffer remains 32-bit even when high RAM exists");
    channel.prdt_addr = 0xFFFFFFFC;
    assert.throws(() => ide.dma_segments(4), RangeError, "IDE PRDT cannot cross 4GiB");
    const ata_setup = command => {
        channel.prdt_addr = prdt;
        channel.dma_status = 1;
        ide.current_command = command;
        ide.sector_count_reg = 1;
        ide.is_lba = 1;
        ide.head = ide.lba_low_reg = ide.lba_mid_reg = ide.lba_high_reg = 0;
    };
    const sector = Uint8Array.from({ length: 512 }, (_, i) => i * 17 & 255);
    cpu.write_blob_physical(sector, 0x9000);
    prd(0, 0x9000, 512, true);
    ata_setup(0xCA);
    ide.do_ata_write_sectors_dma();
    assert.equal(channel.dma_status & 3, 0);
    assert.equal(ide.current_command, -1);
    cpu.write_blob_physical(new Uint8Array(512), 0x9000);
    ata_setup(0xC8);
    ide.do_ata_read_sectors_dma();
    assert.equal(channel.dma_status & 3, 0);
    assert.deepEqual(cpu.read_blob_physical(0x9000, 512), sector);
    prd(0, 0x200000, 512, true);
    for(const command of [0xCA, 0xC8])
    {
        ata_setup(command);
        if(command === 0xCA) ide.do_ata_write_sectors_dma();
        else ide.do_ata_read_sectors_dma();
        assert.equal(channel.dma_status & 3, 2);
        assert.equal(ide.current_command, -1);
    }
    console.log("PASS real IDE PRDT low holes, full-transfer preflight, device abort, 32-bit limits");

    const balloon = cpu.devices.virtio_balloon;
    const balloon_table = HIGH + 0x9000, balloon_avail = HIGH + 0xA000, balloon_used = HIGH + 0xB000;
    cpu.write_blob_physical(new Uint8Array(0x3000), balloon_table);
    cpu.io.port_write16(0xD800 + 22, 3);
    for(const [offset, address] of [[32, balloon_table], [40, balloon_avail], [48, balloon_used]])
    {
        cpu.io.port_write32(0xD800 + offset, address >>> 0);
        cpu.io.port_write32(0xD800 + offset + 4, 1);
    }
    descriptor(balloon_table, HIGH + 0xC000, 16, 2);
    cpu.write_blob_physical(new Uint8Array(16).fill(0xCC), HIGH + 0xC000);
    cpu.write_blob_physical(new Uint8Array(16).fill(0xDD), 0xC000);
    cpu.write16_physical(balloon_avail + 2, 1);
    cpu.io.port_write16(0xD800 + 28, 1);
    cpu.io.port_write16(0xD900 + 4, 3);
    assert.deepEqual(cpu.read_blob_physical(HIGH + 0xC000, 16), new Uint8Array(16));
    assert.deepEqual(cpu.read_blob_physical(0xC000, 16), new Uint8Array(16).fill(0xDD));
    assert.equal(balloon.zeroed, 16);
    assert.equal(cpu.read16_physical(balloon_used + 2), 1);
    console.log("PASS real VirtIO balloon high free-page hint zeros correct backing only");

    if(e.x64_phys_restore_windows)
    {
        const saved = new Uint32Array(80);
        for(let slot = 0; slot < 16; slot++)
            for(let field = 0; field < 5; field++) saved[slot * 5 + field] = e.x64_phys_get_window(slot, field);
        const pointer = e.v86_malloc(saved.byteLength);
        try
        {
            const transfer = new Uint32Array(cpu.wasm_memory.buffer, pointer, saved.length);
            transfer.set(saved);
            transfer[16] = 16; // slot 3 physical high DWORD: outside 36 bits
            transfer[18] = 4096;
            transfer[19] = 1;
            const unchanged_generation = generation();
            assert.equal(e.x64_phys_restore_windows(pointer, saved.length), 0);
            assert.equal(generation(), unchanged_generation);
            assert.equal(cpu.read32_physical(HIGH + 0x7000), 0x06070809);
            transfer.set(saved);
            assert.equal(e.x64_phys_restore_windows(pointer, saved.length), 1);
            assert.ok(generation() > unchanged_generation);
            assert.equal(cpu.read32_physical(HIGH + 0x7000), 0x06070809);
            console.log("PASS physical window restore transaction rejects bad set and refreshes generation");
        }
        finally { e.v86_free(pointer); }
    }
    else assert.fail("physical transactional restore export missing: rebuild required");
}
finally { await emulator.destroy(); }
                                                                                                                                                                                 source/v64/tests/smp/scheduler.mjs                                                                  0000644 0000000 0000000 00000013507 00000000000 014324  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Cooperative scheduling boundaries and the single-core snapshot compatibility path.
// Architectural AP startup is covered separately by ap_startup.asm.
import assert from "node:assert/strict";
import { STATE_OFFSETS } from "../../src/state_layout.js";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

async function machine(cores)
{
    const emulator = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: cores, memory_size: 16 << 20,
        disable_jit: true, autostart: false, log_level: 0 });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    return emulator;
}

function entry(cpu, ip)
{
    cpu.sreg[1] = 0;
    cpu.segment_offsets[1] = 0;
    cpu.instruction_pointer[0] = ip;
    cpu.previous_ip[0] = ip;
    cpu.reg32[4] = 0x8000;
    cpu.flags[0] = 2;
    cpu.in_hlt[0] = 0;
    cpu.full_clear_tlb();
}

const emulator = await machine(2);
try
{
    const cpu = emulator.v86.cpu;
    entry(cpu, 0x1000);
    cpu.mem8.set([0xEB, 0xFE], 0x1000); // busy loop without PAUSE
    assert.equal(cpu.run_cpu_slice(17), 17, "a same-page busy loop obeys the exact dispatch budget");
    assert.equal(cpu.instruction_pointer[0], 0x1000);
    assert.equal(cpu.run_cpu_slice(0), 0);

    // STI's interrupt shadow may consume one extra instruction at the slice
    // boundary, but a chain of STI (IF already set) must not recurse forever.
    entry(cpu, 0x1000);
    cpu.mem8.fill(0xFB, 0x1000, 0x1064);
    cpu.mem8[0x1064] = 0xF4;
    assert.equal(cpu.run_cpu_slice(1), 2);
    assert.equal(cpu.instruction_pointer[0], 0x1002);
    assert.equal(cpu.in_hlt[0], 0);
    assert.equal(cpu.run_cpu_slice(1), 1);
    entry(cpu, 0x1000);
    cpu.mem8.set(Array.from({ length: 300 }, (_, i) => [0xFA, 0xFB, 0x90][i % 3]), 0x1000);
    assert.equal(cpu.run_cpu_slice(17), 18, "STI shadow steps count toward the dispatch budget");
    assert.equal(cpu.instruction_pointer[0], 0x1012);

    // A long REP yields with architectural progress retained, even though the
    // entire transfer fits in RAM and does not access a device.
    entry(cpu, 0x1000);
    cpu.mem8.set([0xF3, 0xAA, 0xF4], 0x1000); // rep stosb; hlt
    cpu.reg32[0] = 0x5A;
    cpu.reg32[1] = 1000;
    cpu.reg32[7] = 0x4000;
    assert.equal(cpu.run_cpu_slice(4096), 1);
    assert.equal(cpu.reg32[1], 744);
    assert.equal(cpu.instruction_pointer[0], 0x1000);
    assert.ok(cpu.mem8.slice(0x4000, 0x4100).every(x => x === 0x5A));
    assert.equal(cpu.mem8[0x4100], 0);

    entry(cpu, 0x1000);
    cpu.mem8.set([0xF4, 0xEB, 0xFD], 0x1000); // BSP: CLI+HLT
    cpu.run_cpu_slice(10);
    cpu.switch_core(1);
    cpu.cores[1].running = true;
    entry(cpu, 0x1100);
    cpu.flags[0] = 0x202;
    cpu.mem8.set([0xF4, 0xEB, 0xFD], 0x1100); // AP: STI+HLT
    cpu.mem8.set([0xFF, 0x06, 0x00, 0x50, 0xCF], 0x1200); // inc word [0x5000]; iret
    cpu.mem8.set([0x00, 0x12, 0x00, 0x00], 0x50 * 4); // real-mode timer vector
    cpu.run_cpu_slice(10);
    cpu.switch_core(0);
    const lapic = new Uint32Array(cpu.wasm_memory.buffer, cpu.apic_addr(1), 46);
    lapic[40] = 0x1FF; // software enable
    lapic[8] = 0x50; // unmasked one-shot timer
    lapic[3] = lapic[4] = 1;
    new Float64Array(cpu.wasm_memory.buffer, cpu.apic_addr(1) + 24, 1)[0] = 0;

    let timer_calls = 0;
    const timers = cpu.run_hardware_timers.bind(cpu);
    cpu.run_hardware_timers = (...args) => { timer_calls++; return timers(...args); };
    cpu.run_cores();
    assert.equal(timer_calls, 1, "one machine timer service per round, even with a CLI+HLT BSP");
    assert.equal(cpu.mem8[0x5000], 1, "a halted AP wakes for its LAPIC timer");
    assert.equal(cpu.in_hlt[0], 1, "the AP returned from its interrupt and halted again");
    cpu.run_cores();
    assert.equal(timer_calls, 2);
    assert.equal(cpu.mem8[0x5000], 1, "one-shot timer must not fire twice");

    cpu.flags[0] = 2;
    cpu.write32(0xFEE00300, 0x40060); // a maskable self IPI while IF=0
    assert.ok(cpu.run_cores() > 0, "a halted IF=0 core with a masked IPI must not busy-spin the host");

    const memory = cpu.mem8.slice(0, 0x6000);
    await assert.rejects(emulator.restore_state(new ArrayBuffer(0)), /Invalid snapshot length/);
    assert.deepEqual(cpu.mem8.slice(0, 0x6000), memory, "rejected restore leaves RAM untouched");
    const saved = await emulator.save_state();
    await emulator.restore_state(saved);
    assert.deepEqual(cpu.mem8.slice(0, 0x6000), memory);
}
finally
{
    await emulator.destroy();
}

const single = await machine(1);
try
{
    const cpu = single.v86.cpu;
    const bytes = new Uint8Array(cpu.wasm_memory.buffer);
    cpu.apic_enabled[0] = 0;
    bytes[cpu.state_base + STATE_OFFSETS.nmi_blocked] = 1;
    cpu.apic_restore_core_events(0, 1, true);
    const saved = await single.save_state();
    cpu.apic_enabled[0] = 1;
    bytes[cpu.state_base + STATE_OFFSETS.nmi_blocked] = 0;
    cpu.apic_restore_core_events(0, 0, false);
    await single.restore_state(saved);
    assert.equal(cpu.apic_enabled[0], 0);
    assert.equal(bytes[cpu.state_base + STATE_OFFSETS.nmi_blocked], 1);
    assert.equal(cpu.apic_core_nmi_pending(0), 1);
    assert.equal(cpu.apic_peek_core_events(0), 1);

    // The existing version-6 format accepts old positional arrays. Absent
    // new fields must reset the state, not retain NMI state from this machine.
    const set_state = cpu.set_state.bind(cpu);
    cpu.set_state = state => { state.length = 94; set_state(state); };
    await single.restore_state(saved);
    assert.equal(cpu.apic_enabled[0], 1);
    assert.equal(bytes[cpu.state_base + STATE_OFFSETS.nmi_blocked], 0);
    assert.equal(cpu.apic_core_nmi_pending(0), 0);
    assert.equal(cpu.apic_peek_core_events(0), 0);
}
finally
{
    await single.destroy();
}
console.log("SMP scheduler: exact busy-loop budget, bounded REP, halted-AP timer, snapshot restore and NMI state passed");
                                                                                                                                                                                         source/v64/tests/smp/state_stream.mjs                                                               0000644 0000000 0000000 00000020414 00000000000 015034  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// V7 writes to a real file; no test-side whole snapshot buffer hides allocation.
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { setImmediate as set_immediate } from "node:timers";
import { createHash as create_hash } from "node:crypto";
import { crc32 } from "node:zlib";
import { MessageChannel } from "node:worker_threads";
import { begin_state_io } from "../../src/state_io.js";
import { state_stream_client, state_stream_server } from "../../src/browser/state_stream_transport.js";
const { V86 } = await import(process.env.V86_LIB_PATH || (+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js"));
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "v86-state-stream-"));
const file = await fs.open(path.join(directory, "state.v7"), "w+");
const emulator = new V86({ graphics_adapter: "bochs_vga", wasm_path: process.env.WASM_PATH, memory_size: 16 << 20,
    cpu_cores: 2, acpi: true, disable_jit: true, autostart: false, log_level: 0,
    net_device: { type: "none" } });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
try
{
    const cpu = emulator.v86.cpu, e = cpu.wm.exports, HIGH = 2 ** 32;
    cpu.mem8.fill(0);
    for(let page = 0; page < cpu.mem8.length / 4096; page += 2)
        cpu.mem8.fill(page & 255 || 0xA5, page * 4096, (page + 1) * 4096);
    assert.equal(e.x64_phys_set_window(0, 0, 1, 0x200000, 0x10000, 1), 1);
    cpu.write32_physical(HIGH + 0x5000, 0x1234ABCD);
    const windows = cpu.get_physical_windows();
    cpu.reg32[0] = 0xABCD;
    cpu.switch_core(1); cpu.reg32[0] = 0x9876; cpu.switch_core(0);
    const original_pack = cpu.pack_memory;
    cpu.pack_memory = () => { throw new Error("V7 must never pack whole RAM"); };
    let position = 0, maximum = 0, active = 0, peak = 0, writes = 0, input_received = 0;
    cpu.bus.register("stream-test-input", () => { input_received++; }, null);
    const complete_io = begin_state_io(cpu);
    setTimeout(() => { cpu.mem8[0x1010] = 0x77; complete_io(); }, 5);
    await emulator.save_state_stream(async bytes => {
        active++; peak = Math.max(peak, active);
        assert.ok(bytes instanceof Uint8Array && bytes.length <= 1024 * 1024);
        maximum = Math.max(maximum, bytes.length);
        if(!writes++)
        {
            assert.equal(cpu.mem8[0x1010], 0x77, "all DMA completed before bitmap capture");
            emulator.bus.send("stream-test-input", 1);
            assert.equal(input_received, 0, "external input held until the transaction completes");
        }
        await new Promise(resolve => set_immediate(resolve));
        const result = await file.write(bytes, 0, bytes.length, position);
        assert.equal(result.bytesWritten, bytes.length);
        position += bytes.length;
        active--;
    });
    cpu.pack_memory = original_pack;
    assert.equal(peak, 1, "writer backpressure permits one outstanding chunk");
    assert.equal(input_received, 1);
    assert.ok(position > 8 << 20);
    const header = new Uint8Array(32); await file.read(header, 0, 32, 0);
    assert.equal(new DataView(header.buffer).getUint32(4, true), 7);
    // the checksums are CRC-32 as zlib's (files saved before must still load)
    const manifest = new Uint8Array(new DataView(header.buffer).getUint32(12, true));
    await file.read(manifest, 0, manifest.length, 32);
    assert.equal(new DataView(header.buffer).getUint32(28, true), crc32(manifest), "manifest checksum");
    const record_header = new Uint8Array(16); await file.read(record_header, 0, 16, 32 + manifest.length);
    const record = new Uint8Array(16 + new DataView(record_header.buffer).getUint32(12, true) + 4);
    await file.read(record, 0, record.length, 32 + manifest.length);
    assert.equal(new DataView(record.buffer).getUint32(record.length - 4, true), crc32(record.subarray(0, record.length - 4)), "record checksum");
    let reads = 0;
    const source = { size: position, async read(offset, length) {
        assert.ok(length <= 1024 * 1024); reads++;
        const bytes = new Uint8Array(length);
        assert.equal((await file.read(bytes, 0, length, offset)).bytesRead, length);
        return bytes;
    } };
    assert.equal(e.x64_phys_set_window(0, 0, 0, 0, 0, 0), 1);
    cpu.mem8.fill(0xEE); cpu.reg32[0] = 0;
    await emulator.restore_state_stream(source);
    assert.deepEqual(cpu.get_physical_windows(), windows);
    assert.equal(cpu.read32_physical(HIGH + 0x5000), 0x1234ABCD);
    assert.equal(cpu.mem8[0x1010], 0x77);
    assert.equal(cpu.mem8[0x1000], 0);
    assert.equal(cpu.mem8[0x2000], 2);
    assert.equal(cpu.reg32[0], 0xABCD);
    cpu.switch_core(1); assert.equal(cpu.reg32[0], 0x9876); cpu.switch_core(0);
    console.log(`PASS V7 file roundtrip: ${position} bytes, ${writes} writes/${reads} reads, max chunk ${maximum}, two cores/high RAM/DMA drain/backpressure`);

    const hash_ram = () => create_hash("sha256").update(cpu.mem8.subarray(0)).digest("hex");
    const epoch = cpu.execution_epoch, untouched = hash_ram();
    const last = new Uint8Array(1); await file.read(last, 0, 1, position - 5);
    await file.write(Uint8Array.of(last[0] ^ 1), 0, 1, position - 5);
    await assert.rejects(emulator.restore_state_stream(source), /record\/checksum/);
    assert.equal(cpu.execution_epoch, epoch);
    assert.equal(hash_ram(), untouched, "late corrupt data is rejected before the first RAM write");
    await file.write(last, 0, 1, position - 5);
    await assert.rejects(emulator.restore_state_stream({ ...source, size: position - 1 }), /total length/);
    assert.equal(hash_ram(), untouched);
    console.log("PASS V7 damaged final record and truncated source rejected before architectural/RAM mutation");

    let ram_start = null, ram_reads = 0;
    const failing = { size: position, async read(offset, length) {
        const bytes = await source.read(offset, length);
        if(length > 20 && new DataView(bytes.buffer).getUint32(0, true) === 2)
        {
            if(ram_start === null) ram_start = offset;
            if(offset === ram_start && ++ram_reads === 2) throw new Error("second-pass I/O failure");
        }
        return bytes;
    } };
    await assert.rejects(emulator.restore_state_stream(failing), /second-pass I\/O failure/);
    assert.equal(emulator.is_running(), false);
    assert.equal(cpu.clock.paused, true);
    await emulator.restore_state_stream(source);
    console.log("PASS V7 second-pass I/O failure keeps CPU/clock stopped; a fresh restore recovers");

    const save_channel = new MessageChannel();
    let transport_position = 0, transport_max = 0;
    const save_server = state_stream_server(save_channel.port1, "save", async bytes => {
        transport_max = Math.max(transport_max, bytes.length);
        transport_position += bytes.length;
        await new Promise(resolve => set_immediate(resolve));
    });
    const save_client = state_stream_client(save_channel.port2);
    try { await emulator.save_state_stream(save_client.write); }
    finally { save_client.close(); save_server.close(); }
    assert.equal(transport_position, position);
    assert.ok(transport_max <= 1024 * 1024);
    const restore_channel = new MessageChannel();
    const restore_server = state_stream_server(restore_channel.port1, "restore", source);
    const restore_client = state_stream_client(restore_channel.port2);
    try { await emulator.restore_state_stream({ size: restore_server.size, read: restore_client.read }); }
    finally { restore_client.close(); restore_server.close(); }
    assert.equal(cpu.read32_physical(HIGH + 0x5000), 0x1234ABCD);
    console.log("PASS real MessagePort stream transport preserves bounded chunks and request/reply backpressure");

    const v6 = await emulator.save_state();
    assert.equal(new DataView(v6).getUint32(4, true), 6);
    cpu.write32_physical(HIGH + 0x5000, 0);
    await emulator.restore_state(v6);
    assert.equal(cpu.read32_physical(HIGH + 0x5000), 0x1234ABCD);
    await assert.rejects(emulator.save_state_stream(async () => { throw new Error("sink cancelled"); }), /sink cancelled/);
    assert.equal(emulator.v86.state_busy, null);
    console.log("PASS legacy V6 save/import retained and cancelled writer releases snapshot transaction");
}
finally
{
    await emulator.destroy();
    await file.close();
    await fs.rm(directory, { recursive: true, force: true });
}
                                                                                                                                                                                                                                                    source/v64/tests/smp/topology.mjs                                                                   0000644 0000000 0000000 00000017106 00000000000 014221  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Topology: CPUID and firmware-input contract. These are instruction-level checks;
// architectural AP startup and real firmware boot have separate guest gates.
import assert from "node:assert/strict";
import { build_acpi_tables } from "../../src/acpi_tables.js";
import { create_platform } from "../../src/platform.js";
import { CMOS_BIOS_SMP_COUNT } from "../../src/rtc.js";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const LEAVES = [[0, 0], [1, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 7],
    [0xB, 0], [0xB, 1], [0xB, 2], [0xB, 7], [0x1F, 0], [0x1F, 1], [0x1F, 2], [0x1F, 7]];

function cpuid(cpu, core, leaf, subleaf)
{
    cpu.switch_core(core);
    cpu.sreg[1] = 0;
    cpu.segment_offsets[1] = 0;
    cpu.instruction_pointer[0] = cpu.previous_ip[0] = 0x1000;
    cpu.flags[0] = 2;
    cpu.in_hlt[0] = 0;
    cpu.reg32[0] = leaf;
    cpu.reg32[1] = subleaf;
    cpu.mem8.set([0x0F, 0xA2, 0xF4], 0x1000); // CPUID; HLT
    cpu.full_clear_tlb();
    cpu.run_cpu_slice(4);
    assert.equal(cpu.in_hlt[0], 1, "CPUID fixture reached HLT");
    return [0, 3, 1, 2].map(index => cpu.reg32[index] >>> 0);
}

function firmware_inputs(cpu, cores)
{
    for(const selector of [5, 15]) // FW_CFG_NB_CPUS / MAX_CPUS
    {
        cpu.io.port_write16(0x510, selector);
        assert.equal(cpu.io.port_read8(0x511) | cpu.io.port_read8(0x511) << 8, cores, `fw_cfg ${selector}`);
    }
    assert.equal(cpu.devices.rtc.cmos_read(CMOS_BIOS_SMP_COUNT), cores - 1, "CMOS additional CPUs");
    const { tables, layout } = build_acpi_tables(cpu.platform, 0x600);
    const madt = tables.subarray(layout.APIC.offset, layout.APIC.offset + layout.APIC.length);
    const ids = [];
    for(let p = 44; p < madt.length; p += madt[p + 1])
    {
        assert.ok(madt[p + 1] >= 2, "bounded MADT entry");
        if(madt[p] === 0)
        {
            assert.equal(madt[p + 2], madt[p + 3], "ACPI processor ID equals APIC ID");
            assert.equal(madt[p + 4] & 1, 1, "processor enabled");
            ids.push(madt[p + 3]);
        }
    }
    assert.deepEqual(ids, Array.from({ length: cores }, (_, id) => id));
    // The bundled DSDT uses fixed-size, empty Processor objects: extended
    // opcode 5B83, one-byte package length, NameSeg, ProcID, no P_BLK.
    const dsdt = Buffer.from(tables.subarray(layout.DSDT.offset, layout.DSDT.offset + layout.DSDT.length));
    const processors = [];
    for(let p = 36; p + 13 <= dsdt.length; p++)
    {
        if(dsdt[p] !== 0x5B || dsdt[p + 1] !== 0x83) continue;
        assert.equal(dsdt[p + 2], 11, "AML Processor package length");
        processors.push([dsdt.toString("ascii", p + 3, p + 7), dsdt[p + 7]]);
    }
    assert.deepEqual(processors, ids.map(id => ["CP" + id.toString(16).toUpperCase().padStart(2, "0"), id]), "AML Processor IDs agree with MADT and CPUID");
}

for(const cores of [1, 2, 3, 4, 5, 6, 7, 8])
{
    const emulator = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: cores, memory_size: 16 << 20,
        disable_jit: true, autostart: false, log_level: 0 });
    let timeout;
    try
    {
        await new Promise((resolve, reject) => {
            timeout = setTimeout(() => reject(new Error("machine load timed out")), 15000);
            emulator.add_listener("emulator-loaded", resolve);
            emulator.add_listener("emulator-error", reject);
        });
        clearTimeout(timeout);
        const cpu = emulator.v86.cpu;
        assert.deepEqual(cpu.platform.topology, {
            sockets: 1, cores_per_socket: cores, threads_per_core: 1,
            logical_processors: cores, package_shift: Math.ceil(Math.log2(cores)),
        });
        assert.equal(cpu.platform.cpuid_profile, cores === 1 ? "legacy" : "smp32");
        const results = [];
        for(let id = 0; id < cores; id++)
        {
            const query = (leaf, subleaf = 0) => cpuid(cpu, id, leaf, subleaf);
            const values = LEAVES.map(([leaf, subleaf]) => query(leaf, subleaf));
            results.push(values);
            assert.equal(query(0)[0], cores === 1 ? 0x16 : 0x1F, "profile maximum basic leaf");
            const [, ebx, , edx] = query(1);
            assert.equal(ebx >>> 24, id, "initial APIC ID");
            assert.equal(ebx >>> 16 & 0xFF, cores, "logical processors per package");
            assert.equal(edx >>> 28 & 1, Number(cores > 1), "HTT qualifies package logical count");
            for(let subleaf = 0; subleaf < 3; subleaf++)
            {
                const geometry = [[0x121, 0x01C0003F, 0x3F, 1], [0x122, 0x01C0003F, 0x3F, 1], [0x143, 0x05C0003F, 0xFFF, 1]][subleaf];
                const sharing = subleaf === 2 ? cores : 1;
                geometry[0] = (geometry[0] | (cores - 1) << 26 | (sharing - 1) << 14) >>> 0;
                assert.deepEqual(query(4, subleaf), geometry, `cache subleaf ${subleaf}`);
            }
            assert.deepEqual(query(4, 3), [0, 0, 0, 0], "cache enumeration terminates");
            for(const leaf of [0xB, 0x1F])
            {
                for(const subleaf of [0, 1, 2, 7])
                {
                    const expected = cores === 1 ? [0, 0, 0, 0] : subleaf === 0 ? [0, 1, 0x100, id] :
                        subleaf === 1 ? [Math.ceil(Math.log2(cores)), cores, 0x201, id] : [0, 0, subleaf, id];
                    assert.deepEqual(query(leaf, subleaf), expected, `leaf ${leaf}, subleaf ${subleaf}`);
                }
                if(cores > 1) assert.equal(id >>> query(leaf, 1)[0], 0, "every core belongs to package zero");
            }
        }
        // Every field other than the documented per-core APIC ID is identical.
        for(let id = 1; id < cores; id++)
        {
            LEAVES.forEach(([leaf], index) => {
                const actual = [...results[id][index]];
                if(leaf === 1) actual[1] &= 0xFFFFFF;
                if(leaf === 0xB || leaf === 0x1F) actual[3] = 0;
                assert.deepEqual(actual, results[0][index], `core ${id}, leaf ${leaf}: package consistency`);
            });
        }
        firmware_inputs(cpu, cores);
        console.log(`${cores} cores: CPUID profile, package/core shifts, cache domains, MADT/fw_cfg/CMOS agree`);
    }
    finally
    {
        clearTimeout(timeout);
        await emulator.destroy();
    }
}

// Invalid counts fail before firmware or execution can use them.
for(const count of [0, -1, 1.5, 9])
{
    assert.throws(() => create_platform({ acpi: true, cpu_cores: count }, 16 << 20), /cpu_cores/);
}

// The legacy Windows-NT CPUID cap remains available for one core, while a
// multicore profile cannot hide the topology leaves it requires.
for(const [cores, level, rejected] of [[1, 2, false], [2, 2, true], [2, 0x1F, false]])
{
    const emulator = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: cores, cpuid_level: level,
        memory_size: 16 << 20, disable_jit: true, autostart: false, log_level: 0 });
    let timeout;
    try
    {
        const loaded = new Promise((resolve, reject) => {
            timeout = setTimeout(() => reject(new Error("profile load timed out")), 15000);
            emulator.add_listener("emulator-loaded", resolve);
            emulator.add_listener("emulator-error", reject);
        });
        if(rejected) await assert.rejects(loaded, /cpuid_level >= 0x1F/);
        else
        {
            await loaded;
            assert.equal(cpuid(emulator.v86.cpu, 0, 0, 0)[0], level, "explicit compatible CPUID maximum");
        }
    }
    finally
    {
        clearTimeout(timeout);
        await emulator.destroy();
    }
}
console.log("CPUID maximum override: legacy single-core cap preserved; incompatible SMP cap rejected");
                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/smp/virtio_high_dma.mjs                                                            0000644 0000000 0000000 00000020772 00000000000 015504  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Exercise the actual VirtIO transport against a sparse 36-bit physical bus.
// This isolates address decoding from RAM allocation: high and low aliases
// deliberately contain different bytes, and legacy 32-bit helpers are absent.
import assert from "node:assert/strict";
import { VirtIO } from "../../src/virtio.js";

globalThis.DEBUG = false;
const LIMIT = 2 ** 36;
const HIGH = 2 ** 32;
const ranges = [[0, 0x10000], [HIGH, HIGH + 0x10000], [LIMIT - 0x1000, LIMIT]];
const bytes = new Map();
const accesses = [];
const cpu = {
    io: { register_read() {}, register_write() {} },
    // (absent: src/pci.js's functions off the bus, by pci_id; this one never is)
    devices: { pci: { absent: [], register_device() {}, raise_irq() {}, lower_irq() {} } },
    validate_physical_range(address, length)
    {
        if(!Number.isSafeInteger(address) || !Number.isSafeInteger(length) ||
            address < 0 || length < 0 || address >= LIMIT || length > LIMIT - address ||
            !ranges.some(([start, end]) => address >= start && address + length <= end))
        {
            throw new RangeError("Invalid physical range");
        }
    },
    read_blob_physical(address, length)
    {
        this.validate_physical_range(address, length);
        accesses.push(["read", address, length]);
        return Uint8Array.from({ length }, (_, i) => bytes.get(address + i) || 0);
    },
    write_blob_physical(blob, address)
    {
        this.validate_physical_range(address, blob.length);
        accesses.push(["write", address, blob.length]);
        blob.forEach((byte, i) => bytes.set(address + i, byte));
    },
    read16_physical(address)
    {
        return new DataView(this.read_blob_physical(address, 2).buffer).getUint16(0, true);
    },
    read32_physical(address)
    {
        return new DataView(this.read_blob_physical(address, 4).buffer).getUint32(0, true);
    },
    write16_physical(address, value)
    {
        const blob = new Uint8Array(2);
        new DataView(blob.buffer).setUint16(0, value, true);
        this.write_blob_physical(blob, address);
    },
    write32_physical(address, value)
    {
        const blob = new Uint8Array(4);
        new DataView(blob.buffer).setUint32(0, value, true);
        this.write_blob_physical(blob, address);
    },
};

const options = {
    name: "high-dma-test", pci_id: 0x38, device_id: 0x1041, subsystem_device_id: 1,
    common: { initial_port: 0xD000, features: [28, 29, 32], queues: [{ size_supported: 8, notify_offset: 0 }], on_driver_ok() {} },
    notification: { initial_port: 0xD100, single_handler: true, handlers: [() => {}] },
    isr_status: { initial_port: 0xD200 },
};
const virtio = new VirtIO(cpu, options);
const queue = virtio.queues[0];
const fields = new Map(virtio.create_common_capability(options.common).struct.map(field => [field.name, field]));
function write_address(name, address, high_first = false)
{
    const low = fields.get("queue_" + name + " (low dword)");
    const high = fields.get("queue_" + name + " (high dword)");
    if(high_first) high.write(Math.floor(address / HIGH));
    low.write(address >>> 0);
    if(!high_first) high.write(Math.floor(address / HIGH));
    assert.equal(low.read() >>> 0, address >>> 0);
    assert.equal(high.read() >>> 0, Math.floor(address / HIGH));
}
const table = HIGH + 0x1000, avail = HIGH + 0x2000, used = HIGH + 0x3000;
function configure()
{
    virtio.reset();
    bytes.clear();
    write_address("desc", table, true);
    write_address("avail", avail);
    write_address("used", used, true);
    fields.get("queue_enable").write(1);
    assert.equal(queue.enabled, true);
}
function descriptor(at, address, length, flags, next = 0)
{
    cpu.write32_physical(at, address >>> 0);
    cpu.write32_physical(at + 4, Math.floor(address / HIGH));
    cpu.write32_physical(at + 8, length);
    cpu.write16_physical(at + 12, flags);
    cpu.write16_physical(at + 14, next);
}
function post()
{
    cpu.write16_physical(avail + 2, 1);
    cpu.write16_physical(avail + 4, 0);
    assert.equal(queue.has_request(), true);
    return queue.pop_request();
}
function complete(chain, expected)
{
    assert.equal(chain.valid, true);
    const actual = new Uint8Array(expected.length);
    const first = Math.min(2, actual.length);
    assert.equal(chain.get_next_blob(actual.subarray(0, first)), first);
    assert.equal(chain.get_next_blob(actual.subarray(first)), actual.length - first);
    assert.deepEqual(actual, expected);
    assert.equal(chain.set_next_blob(actual.subarray(0, first)), first);
    assert.equal(chain.set_next_blob(actual.subarray(first)), actual.length - first);
    queue.push_reply(chain);
    queue.flush_replies();
    assert.equal(cpu.read16_physical(used + 2), 1);
    assert.equal(cpu.read32_physical(used + 8), expected.length);
    assert.equal(queue.has_request(), false);
}

configure();
fields.get("queue_desc (low dword)").write(0x8000);
fields.get("queue_desc (high dword)").write(0);
assert.equal(queue.desc_addr, table, "active queue address stays stable until reset");
assert.equal(fields.get("queue_desc (low dword)").read(), 0x1000);
assert.equal(fields.get("queue_desc (high dword)").read(), 1);
const payload = HIGH + 0x4000, reply = HIGH + 0x5000;
const message = new Uint8Array([0x10, 0x20, 0x30, 0x40, 0x50]);
cpu.write_blob_physical(message, payload);
cpu.write_blob_physical(new Uint8Array([0xAA, 0xBB, 0xCC, 0xDD, 0xEE]), 0x5000);
descriptor(table, payload, message.length, 1, 1);
descriptor(table + 16, reply, message.length, 2);
complete(post(), message);
assert.deepEqual(cpu.read_blob_physical(reply, message.length), message);
assert.deepEqual(cpu.read_blob_physical(0x5000, 5), new Uint8Array([0xAA, 0xBB, 0xCC, 0xDD, 0xEE]));
assert.ok(accesses.some(([kind, address]) => kind === "read" && address === table));
console.log("PASS VirtIO high direct rings, partial blobs, used ring, no low32 alias");

configure();
const indirect = HIGH + 0x6000, top_reply = LIMIT - message.length;
cpu.write_blob_physical(message, 0x4000);
descriptor(table, indirect, 32, 4);
descriptor(indirect, 0x4000, message.length, 1, 1);
descriptor(indirect + 16, top_reply, message.length, 2);
complete(post(), message);
assert.deepEqual(cpu.read_blob_physical(top_reply, message.length), message);
console.log("PASS VirtIO high indirect table, mixed low/high payload, final 36-bit byte");

const saved = globalThis.structuredClone(queue.get_state());
queue.reset();
assert.deepEqual([...queue.address_words], [0, 0, 0, 0, 0, 0]);
queue.set_state(saved);
assert.equal(queue.desc_addr, table);
assert.equal(queue.avail_addr, avail);
assert.equal(queue.used_addr, used);
assert.equal(fields.get("queue_desc (high dword)").read(), 1);
const legacy = saved.slice(0, 10);
legacy[4] = -2147479552;
legacy[5] = -2147475456;
legacy[7] = -2147471360;
queue.set_state(legacy);
assert.equal(queue.desc_addr, 0x80001000);
assert.equal(queue.avail_addr, 0x80002000);
assert.equal(queue.used_addr, 0x80003000);
assert.deepEqual([...queue.address_words], [0x80001000, 0, 0x80002000, 0, 0x80003000, 0]);
console.log("PASS VirtIO high snapshot/reset and legacy signed32 snapshot");

for(const high of [16, 0x200000, 0xFFFFFFFF])
{
    configure();
    queue.enabled = false;
    fields.get("queue_desc (high dword)").write(high);
    fields.get("queue_desc (low dword)").write(0x12345000);
    assert.equal(fields.get("queue_desc (high dword)").read(), high);
    assert.equal(fields.get("queue_desc (low dword)").read(), 0x12345000);
    const raw_saved = globalThis.structuredClone(queue.get_state());
    queue.reset();
    queue.set_state(raw_saved);
    assert.equal(fields.get("queue_desc (high dword)").read(), high);
    fields.get("queue_enable").write(1);
    assert.equal(queue.enabled, false);
    assert.ok(virtio.device_status & 64);
}
console.log("PASS VirtIO unsupported 64-bit register values preserved and rejected");

for(const [address, length, flags] of [[LIMIT, 4, 0], [HIGH + 0xFFFE, 4, 2], [LIMIT - 2, 4, 2]])
{
    configure();
    descriptor(table, address, length, flags);
    const chain = post();
    assert.equal(chain.valid, false);
    assert.equal(chain.length_readable, 0);
    assert.equal(chain.length_writable, 0);
    assert.ok(virtio.device_status & 64);
    assert.equal(queue.has_request(), false);
    queue.push_reply(chain);
    queue.flush_replies();
    assert.equal(cpu.read16_physical(used + 2), 0);
}
configure();
descriptor(table, indirect, 16, 4);
descriptor(indirect, indirect, 16, 4);
assert.equal(post().valid, false);
assert.ok(virtio.device_status & 64);
console.log("PASS VirtIO out-of-range DMA and nested indirect descriptor fail without completion");
      source/v64/tests/smp/windows_probe.c                                                                0000644 0000000 0000000 00000005642 00000000000 014661  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* XP-compatible, no CRT. A Win32 SMP qualification probe, not a CPU-info test.
 * Results go beside the executable on the disposable FAT16 test disk. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static HANDLE result;
static volatile LONG shared_total;
static DWORD system_cpus, failed, checks[8];
static HANDLE threads[8];
static void text(const char *s) { DWORD n = 0, wrote; while(s[n]) n++; WriteFile(result,s,n,&wrote,0); }
static void number(DWORD n) { char b[12]; int i = 11; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); text(b + i); }
static DWORD apic_id(void) { DWORD a = 1, b, c, d; __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "=c"(c), "=d"(d)); return b >> 24; }
static DWORD WINAPI worker(void *argument)
{
    DWORD id = (DWORD)argument;
    for(DWORD round = 0; round < 128; round++)
    {
        DWORD target = (id + round) % system_cpus;
        if(!SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR)1 << target) || apic_id() != target) InterlockedIncrement((LONG *)&failed);
        DWORD sum = 0;
        for(DWORD i = 1; i <= 1000; i++) sum += i ^ round;
        DWORD expected = 0;
        for(DWORD i = 1000; i; i--) expected += i ^ round;
        if(sum != expected || apic_id() != target) InterlockedIncrement((LONG *)&failed);
        InterlockedIncrement(&shared_total);
        checks[id]++;
        Sleep(0);
    }
    return 0;
}
void __attribute__((stdcall)) entry(void)
{
    char path[MAX_PATH];
    GetModuleFileNameA(0,path,sizeof(path));
    DWORD at = 0, last = 0;
    while(path[at]) { if(path[at] == '\\') last = at + 1; at++; }
    const char name[] = "RESULT.TXT";
    for(at = 0; at < sizeof(name); at++) path[last + at] = name[at];
    result = CreateFileA(path,GENERIC_WRITE,FILE_SHARE_READ,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
    if(result == INVALID_HANDLE_VALUE) ExitProcess(10);
    SYSTEM_INFO info;
    GetSystemInfo(&info);
    DWORD_PTR process_mask = 0, machine_mask = 0;
    if(!GetProcessAffinityMask(GetCurrentProcess(), &process_mask, &machine_mask)) ExitProcess(11);
    system_cpus = info.dwNumberOfProcessors;
    text("C3_XP_BEGIN processors="); number(system_cpus); text(" process_mask="); number((DWORD)process_mask); text(" machine_mask="); number((DWORD)machine_mask); text("\r\n");
    FlushFileBuffers(result);
    if(system_cpus < 1 || system_cpus > 8) ExitProcess(12);
    for(DWORD id = 0; id < system_cpus; id++)
    {
        threads[id] = CreateThread(0,0,worker,(void *)id,0,0);
        if(!threads[id]) ExitProcess(13);
    }
    if(WaitForMultipleObjects(system_cpus,threads,TRUE,120000) != WAIT_OBJECT_0) ExitProcess(14);
    text("C3_XP_DONE processors="); number(system_cpus); text(" progress="); number((DWORD)shared_total); text(" failures="); number(failed); text(" checks=");
    for(DWORD id = 0; id < system_cpus; id++) { if(id) text(","); number(checks[id]); }
    text("\r\n"); FlushFileBuffers(result); CloseHandle(result);
    ExitProcess(failed ? 1 : 0);
}
                                                                                              source/v64/tests/smp/windows_qualification.mjs                                                      0000644 0000000 0000000 00000033510 00000000000 016744  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Optional Windows XP qualification using a user-supplied disk. The source
// image is opened O_RDONLY; all installation/boot/probe writes remain in RAM.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { createHash as create_hash } from "node:crypto";
import { deflateSync as deflate_sync } from "node:zlib";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { MemoryDisk, ReadOnlyOverlayDisk, make_fat16, read_fat16 } from "./disk_fixture.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const filename = process.argv[2];
assert.ok(filename, "usage: windows_qualification.mjs original-xp-disk.img");
const image_path = path.resolve(filename), source_stat = fs.statSync(image_path);
const output_dir = path.resolve(process.env.XP_LOG_DIR || path.join(root, "build/c3-windows-xp"));
fs.mkdirSync(output_dir, { recursive: true });
const module_url = new URL(process.env.V86_MODULE || "../../build/libv86.mjs", import.meta.url);
const { V86 } = await import(module_url.href);
const hash = bytes => create_hash("sha256").update(bytes).digest("hex");
function command(name, args)
{
    const result = spawnSync(name, args, { maxBuffer: 128 << 20 });
    assert.equal(result.status, 0, `${name}: ${result.stderr?.toString() || result.error}`);
    return result.stdout;
}
const seven_zip = process.env.SEVEN_ZIP || "7zz";
const cab = command(seven_zip, ["x", "-so", image_path, "WINDOWS/Driver Cache/i386/sp3.cab"]);
const cab_path = path.join(output_dir, "sp3.cab");
fs.writeFileSync(cab_path, cab);
const hal = command(seven_zip, ["x", "-so", cab_path, "halmacpi.dll"]);
const kernel = command(seven_zip, ["x", "-so", cab_path, "ntkrnlmp.exe"]);
const original_hal = command(seven_zip, ["x", "-so", image_path, "WINDOWS/system32/hal.dll"]);
const original_kernel = command(seven_zip, ["x", "-so", image_path, "WINDOWS/system32/ntoskrnl.exe"]);
function version_strings(bytes)
{
    const latin = bytes.toString("latin1");
    return [...latin.matchAll(/(?:[ -~]\x00){6,}/g)].map(match => Buffer.from(match[0], "latin1").toString("utf16le"))
        .filter(value => /5\.1\.2600| HAL|ntkrnlmp|ntoskrnl|halmacpi|^hal\.dll$/i.test(value));
}
for(const bytes of [hal, kernel, original_hal, original_kernel]) assert.ok(version_strings(bytes).some(value => value.includes("5.1.2600.5512")), "matching XP SP3 binaries");
const probe_path = path.join(output_dir, "C3PROBE.EXE");
command(process.env.MINGW_CC || "i686-w64-mingw32-gcc", ["-Os", "-nostdlib", "-fno-builtin", "-fno-stack-protector", "-Wl,--entry,_entry@0", "-Wl,--subsystem,console", "-o", probe_path, path.join(root, "tests/smp/windows_probe.c"), "-lkernel32"]);
const boot = "[boot loader]\r\ntimeout=0\r\ndefault=multi(0)disk(0)rdisk(0)partition(1)\\WINDOWS\r\n[operating systems]\r\nmulti(0)disk(0)rdisk(0)partition(1)\\WINDOWS=\"XP ACPI SMP RAM overlay\" /HAL=HALSMP.DLL /KERNEL=NTSMP.EXE /noexecute=AlwaysOff /fastdetect /sos /bootlog\r\n";
const setup = `@echo off\r
copy /y "%~dp0HALMP.DLL" "%SystemRoot%\\System32\\HALSMP.DLL"\r
if errorlevel 1 goto fail\r
copy /y "%~dp0NTMP.EXE" "%SystemRoot%\\System32\\NTSMP.EXE"\r
if errorlevel 1 goto fail\r
attrib -s -h -r "%SystemDrive%\\boot.ini"\r
copy /y "%~dp0BOOT.INI" "%SystemDrive%\\boot.ini"\r
if errorlevel 1 goto fail\r
echo C3_SETUP_DONE>"%~dp0SETUP.TXT"\r
del /q "%~dp0RESULT.TXT"\r
shutdown -r -t 0\r
goto end\r
:fail\r
echo C3_SETUP_FAIL>"%~dp0SETUP.TXT"\r
:end\r
`;
const auxiliary = new MemoryDisk(make_fat16({ "C3PROBE.EXE": fs.readFileSync(probe_path), "HALMP.DLL": hal,
    "NTMP.EXE": kernel, "BOOT.INI": Buffer.from(boot), "SETUPMP.BAT": Buffer.from(setup) }));
fs.writeFileSync(path.join(output_dir, "tools.img"), auxiliary.bytes);
const source = new ReadOnlyOverlayDisk(image_path);
const cores = +(process.env.CPU_CORES || 4);
assert.ok(Number.isInteger(cores) && cores >= 2 && cores <= 8);
const wasm_bytes = fs.readFileSync(process.env.WASM_PATH || path.join(root, "build/v86.wasm"));
const wasm = await WebAssembly.compile(wasm_bytes);
const image_hash = create_hash("sha256");
for await (const chunk of fs.createReadStream(image_path)) image_hash.update(chunk);
const report = { image: { path: image_path, size: source_stat.size, original_mtime_ms: source_stat.mtimeMs, sha256: image_hash.digest("hex") },
    javascript: hash(fs.readFileSync(module_url)), wasm: hash(wasm_bytes), cores,
    binaries: Object.fromEntries(Object.entries({ original_hal, original_kernel, hal, kernel }).map(([name, bytes]) => [name, { sha256: hash(bytes), strings: version_strings(bytes) }])),
    initial: null, smp: null, qualification: "not yet run", modes: [], interventions: [] };
const vm = new V86({ graphics_adapter: "bochs_vga", wasm_fn: async imports => (await WebAssembly.instantiate(wasm, imports)).exports,
    bios: { url: path.join(root, "bios/seabios.bin") }, vga_bios: { url: path.join(root, "bios/vgabios.bin") },
    hda: source, hdb: auxiliary, memory_size: 512 << 20, vram_size: 16 << 20,
    acpi: true, cpu_cores: cores, experimental_smp_jit: true, ir_tier0: true,
    ir_sync_publication: true, net_device: { type: "ne2k" }, autostart: false, log_level: 0 });
let phase = "load", serial = "", last_mode_ms = 0, graphics_seen = false, cpu, heartbeat;
const started = performance.now();
vm.add_listener("screen-set-size", size => {
    report.modes.push({ ms: Math.round(performance.now() - started), size });
    if(size[0] >= 640 && size[1] >= 480 && size[2] >= 16) { graphics_seen = true; last_mode_ms = performance.now(); }
});
vm.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
const ascii_scans = Object.fromEntries(Object.entries({ "1234567890": [2,3,4,5,6,7,8,9,10,11],
    "qwertyuiop": [16,17,18,19,20,21,22,23,24,25], "asdfghjkl": [30,31,32,33,34,35,36,37,38],
    "zxcvbnm": [44,45,46,47,48,49,50] }).flatMap(([letters, values]) => [...letters].map((letter, i) => [letter, values[i]])));
Object.assign(ascii_scans, { " ": 57, ".": 52, "/": 53, "\\": 43, "-": 12, ";": 39 });
const shifted = { ":": 39, "%": 6, "(": 10, ")": 11, "@": 3 };
async function run_command(command_line)
{
    console.log("guest command: " + command_line);
    // Win+R, then scan codes. No browser keyboard adapter is needed.
    await vm.keyboard_send_scancodes([0xE0,0x5B,0x13,0x93,0xE0,0xDB], 30);
    await new Promise(resolve => setTimeout(resolve, 500));
    for(const ch of command_line.toLowerCase())
    {
        const shift = shifted[ch], code = shift || ascii_scans[ch]; assert.ok(code, `scan code ${ch}`);
        await vm.keyboard_send_scancodes(shift ? [42,code,code | 128,170] : [code,code | 128], +(process.env.XP_KEY_DELAY || 25));
    }
    await vm.keyboard_send_scancodes([28,156], 30);
}
const file_text = name => { const bytes = read_fat16(auxiliary.bytes, name); return bytes ? Buffer.from(bytes).toString("ascii") : ""; };
async function run_probe(label)
{
    phase = label;
    const deadline = performance.now() + +(process.env.XP_PHASE_MS || 240000);
    let next_command = 0, boot_menu_accepted = false;
    while(performance.now() < deadline)
    {
        const command_file = path.join(output_dir, "command.txt");
        if(fs.existsSync(command_file))
        {
            const input = fs.readFileSync(command_file, "utf8").trim(); fs.unlinkSync(command_file);
            await run_command(input); next_command = performance.now() + 60000;
        }
        if(!graphics_seen && !boot_menu_accepted)
        {
            const vga = cpu.devices.vga;
            const text = Array.from({length:80 * 25}, (_,i) => String.fromCharCode(vga.vga_memory[i * 2])).join("");
            if(text.includes("Seconds until Windows starts:") && text.includes("Start Windows Normally"))
            {
                report.interventions ||= [];
                report.interventions.push({phase,ms:Math.round(performance.now() - started),kind:"accept Start Windows Normally boot menu"});
                await vm.keyboard_send_scancodes([28,156],30);
                boot_menu_accepted = true;
            }
        }
        const text = file_text("RESULT.TXT");
        const match = text.match(/C3_XP_DONE processors=(\d+) progress=(\d+) failures=(\d+) checks=([\d,]+)\r?\n/);
        if(match)
        {
            const result = { processors: +match[1], progress: +match[2], failures: +match[3], checks: match[4].split(",").map(Number), text };
            assert.equal(result.failures, 0); assert.equal(result.progress, result.processors * 128);
            assert.deepEqual(result.checks, Array(result.processors).fill(128));
            console.log(label + " " + JSON.stringify(result));
            return result;
        }
        if(graphics_seen && performance.now() - last_mode_ms > 10000 && performance.now() > next_command)
        {
            await run_command("cmd /c for %d in (d e f g h) do @if exist %d:\\c3probe.exe %d:\\c3probe.exe");
            next_command = performance.now() + 30000;
        }
        await new Promise(resolve => setTimeout(resolve, 100));
    }
    throw new Error(`${label}: Windows probe did not complete`);
}
function screenshot()
{
    const vga = cpu.devices.vga, width = vga.svga_width, height = vga.svga_height;
    if(!vga.svga_enabled || vga.svga_bpp !== 32 || !width || !height) return;
    const raw = Buffer.alloc((width * 3 + 1) * height), memory = vga.svga_memory;
    for(let y = 0; y < height; y++) for(let x = 0; x < width; x++)
    {
        const from = (vga.svga_offset + y * width + x) * 4, to = y * (width * 3 + 1) + 1 + x * 3;
        raw[to] = memory[from + 2]; raw[to + 1] = memory[from + 1]; raw[to + 2] = memory[from];
    }
    const crc = bytes => { let c = 0xFFFFFFFF; for(const byte of bytes) { c ^= byte; for(let i = 0; i < 8; i++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; } return (c ^ 0xFFFFFFFF) >>> 0; };
    const chunk = (name, bytes) => { const n = Buffer.from(name), data = Buffer.concat([n, bytes]), out = Buffer.alloc(bytes.length + 12); out.writeUInt32BE(bytes.length); data.copy(out, 4); out.writeUInt32BE(crc(data), out.length - 4); return out; };
    const header = Buffer.alloc(13); header.writeUInt32BE(width); header.writeUInt32BE(height,4); header[8] = 8; header[9] = 2;
    fs.writeFileSync(path.join(output_dir, "screen.png"), Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk("IHDR",header),chunk("IDAT",deflate_sync(raw)),chunk("IEND",Buffer.alloc(0))]));
}
try
{
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    cpu = vm.v86.cpu;
    heartbeat = setInterval(() => {
        screenshot();
        console.log(JSON.stringify({ phase, ms: Math.round(performance.now() - started), graphics_seen,
            display: [cpu.devices.vga.svga_width, cpu.devices.vga.svga_height, cpu.devices.vga.svga_bpp],
            core_steps: cpu.cores.map(core => core.steps), overlay_sectors: source.overlay.size,
            result: file_text("RESULT.TXT").slice(0, 160) }));
    }, 30000);
    if(process.env.XP_RESTORE) await vm.restore_state(fs.readFileSync(process.env.XP_RESTORE));
    vm.run();
    if(!process.env.XP_RESUME_MP)
    {
        report.initial = await run_probe("original installed HAL");
        assert.equal(report.initial.processors, 1, "the supplied Standard PC installation is UP");
        phase = "install matching ACPI MP boot in RAM overlay";
        await run_command("cmd /c for %d in (d e f g h) do @if exist %d:\\setupmp.bat %d:\\setupmp.bat");
        const setup_deadline = performance.now() + 30000;
        while(!file_text("SETUP.TXT").includes("C3_SETUP_DONE"))
        {
            assert.ok(performance.now() < setup_deadline && !file_text("SETUP.TXT").includes("C3_SETUP_FAIL"), "guest installs matching MP files into RAM overlay");
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        while(file_text("RESULT.TXT"))
        {
            assert.ok(performance.now() < setup_deadline, "setup removes the previous probe result before reboot");
            await new Promise(resolve => setTimeout(resolve, 100));
        }
        graphics_seen = false;
    }
    report.smp = await run_probe("ACPI MP HAL from matching SP3 cabinet");
    assert.equal(report.smp.processors, cores, "Windows actually schedules every configured core");
    report.qualification = "passed: real Win32 threads migrate and complete work on every configured APIC ID";
}
catch(error)
{
    report.qualification = "blocked or failed: " + error.message;
    console.error(report.qualification);
    process.exitCode = 1;
}
finally
{
    clearInterval(heartbeat);
    await vm.stop();
    if(process.exitCode) fs.writeFileSync(path.join(output_dir, "failure-state.bin"), new Uint8Array(await vm.save_state()));
    if(cpu) { report.diagnostics = cpu.get_diagnostics(); screenshot(); }
    if(process.env.XP_CONVERTED_DISK)
    {
        const converted = path.resolve(process.env.XP_CONVERTED_DISK);
        assert.notEqual(converted, image_path);
        fs.copyFileSync(image_path, converted, fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE);
        const output = fs.openSync(converted, "r+");
        try { for(const [sector, bytes] of source.overlay) fs.writeSync(output, bytes, 0, bytes.length, sector * 512); }
        finally { fs.closeSync(output); }
        report.converted_disk = converted;
    }
    report.phase = phase; report.wall_ms = Math.round(performance.now() - started); report.overlay_sectors = source.overlay.size;
    const final_stat = fs.statSync(image_path);
    assert.equal(final_stat.size, source_stat.size); assert.equal(final_stat.mtimeMs, source_stat.mtimeMs, "original image never written");
    report.image.original_unchanged = true;
    fs.writeFileSync(path.join(output_dir, "qualification.json"), JSON.stringify(report, null, 2) + "\n");
    fs.writeFileSync(path.join(output_dir, "serial.log"), serial);
    fs.writeFileSync(path.join(output_dir, "tools-final.img"), auxiliary.bytes);
    await vm.destroy(); source.close();
}
                                                                                                                                                                                        source/v64/tests/smp/windows_reference.mjs                                                          0000644 0000000 0000000 00000011537 00000000000 016057  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Independent XP reference. The supplied converted disk is opened by QEMU's
// temporary snapshot layer. Only a new disposable FAT tool disk is writable.
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import {spawn, spawnSync} from "node:child_process";
import {setTimeout as delay} from "node:timers/promises";
import {read_fat16} from "./disk_fixture.mjs";
const [disk, tools] = process.argv.slice(2);
assert.ok(disk && tools, "usage: windows_reference.mjs converted-xp.img tools.img");
const directory = path.resolve(process.env.XP_QEMU_DIR || "build/c3-xp-qemu");
fs.mkdirSync(directory, {recursive:true});
const auxiliary = path.join(directory,"tools.img");
fs.copyFileSync(tools,auxiliary,fs.constants.COPYFILE_EXCL);
const stat = fs.statSync(disk);
const args = ["-machine","pc,accel=tcg","-cpu","pentium3","-smp","4","-m","512",
    "-drive",`file=${path.resolve(disk)},format=raw,if=ide,index=0,snapshot=on`,
    "-drive",`file=${auxiliary},format=raw,if=ide,index=1`,
    "-device","ne2k_pci","-vga","std","-display","none","-serial","none","-monitor","none","-qmp","stdio","-no-reboot"];
const child=spawn("qemu-system-i386",args,{stdio:["pipe","pipe","pipe"]});
let buffer="",stderr="",id=0;
const pending=new Map();
child.stderr.on("data",data=>stderr+=data);
child.stdout.on("data",data=>{
    buffer+=data;
    while(buffer.includes("\n"))
    {
        const end=buffer.indexOf("\n"),line=buffer.slice(0,end);buffer=buffer.slice(end+1);
        let value;try {value=JSON.parse(line);} catch{continue;}
        if(value.id!==undefined){pending.get(value.id)?.(value);pending.delete(value.id);}
    }
});
const request=(execute,args={})=>new Promise((resolve,reject)=>{
    const n=id++;pending.set(n,value=>value.error?reject(new Error(JSON.stringify(value.error))):resolve(value.return));
    child.stdin.write(JSON.stringify({execute,arguments:args,id:n})+"\n");
});
const monitor=(command,cpu_index=0)=>request("human-monitor-command",{"command-line":command,"cpu-index":cpu_index});
const qcode={" ":"spc", ".":"dot", "/":"slash", "\\":"backslash", "-":"minus", ":":"shift-semicolon", "%":"shift-5", "(":"shift-9", ")":"shift-0", "@":"shift-2"};
async function keys(names)
{
    const event = (key,down)=>({type:"key",data:{down,key:{type:"qcode",data:key}}});
    await request("input-send-event",{events:names.map(key=>event(key,true))});
    await delay(50);
    await request("input-send-event",{events:names.toReversed().map(key=>event(key,false))});
    await delay(50);
}
async function command(text)
{
    console.log("QEMU guest command: "+text);
    await keys(["meta_l","r"]);await delay(1000);
    for(const ch of text.toLowerCase()) await keys((qcode[ch] || ch).split("-"));
    await keys(["ret"]);
}
const report={disk:path.resolve(disk),args,version:spawnSync("qemu-system-i386",["--version"],{encoding:"utf8"}).stdout,observations:[],result:null};
try
{
    await request("qmp_capabilities");
    const started=performance.now(),limit=+(process.env.XP_QEMU_MS || 180000);
    let next_command=135000,next_sample=0;
    while(performance.now()-started<limit)
    {
        const ms=Math.round(performance.now()-started);
        const bytes=read_fat16(fs.readFileSync(auxiliary),"RESULT.TXT");
        if(bytes)
        {
            const value=Buffer.from(bytes).toString("ascii");
            report.probe=value;
            if(value.includes("C3_XP_DONE processors=4")){report.result=value;console.log(value);break;}
        }
        if(ms>=next_sample)
        {
            const registers=[];
            for(let n=0;n<4;n++)registers.push(await monitor("info registers",n));
            report.observations.push({ms,registers});
            await request("screendump",{filename:path.join(directory,`screen-${ms}.ppm`)});
            fs.writeFileSync(path.join(directory,"qualification.json"),JSON.stringify(report,null,2)+"\n");
            console.log(`QEMU progress ${ms} ms: ${registers.map(v=>v.match(/EIP=([\da-f]+)/i)?.[1]).join(",")}`);
            next_sample+=30000;
        }
        if(ms>=next_command){await command("cmd /c for %d in (d e f g h) do @if exist %d:\\c3probe.exe %d:\\c3probe.exe");next_command+=45000;}
        await delay(1000);
    }
    await request("screendump",{filename:path.join(directory,"screen-final.ppm")});
    await request("stop");
    await monitor(`pmemsave 0x562EC0 20 "${path.join(directory,"bugcheck.bin")}"`);
    if(!report.result || !/C3_XP_DONE processors=4 progress=512 failures=0 checks=128,128,128,128/.test(report.result))process.exitCode=1;
}
finally
{
    report.stderr=stderr;
    fs.writeFileSync(path.join(directory,"qualification.json"),JSON.stringify(report,null,2)+"\n");
    await request("quit").catch(()=>{});child.kill();
    const after=fs.statSync(disk);assert.equal(after.size,stat.size);assert.equal(after.mtimeMs,stat.mtimeMs,"reference input disk remained unchanged");
}
                                                                                                                                                                 source/v64/tests/smp/x64_snapshot.mjs                                                               0000644 0000000 0000000 00000013676 00000000000 014715  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Full-machine persistence for high physical windows and per-core wide TLBs.
// Cache contents are injected to isolate snapshot semantics; paging.rs tests
// independently prove stale translations survive until architectural INVLPG.
import assert from "node:assert/strict";
const { V86 } = await import(process.env.V86_LIB_PATH || (+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js"));
const emulator = new V86({ graphics_adapter: "bochs_vga", wasm_path: process.env.WASM_PATH, memory_size: 16 << 20,
    acpi: true, cpu_cores: 2, disable_jit: true, autostart: false, log_level: 0,
    net_device: { type: "none" } });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
try
{
    const cpu = emulator.v86.cpu, e = cpu.wm.exports;
    const HIGH = 2 ** 32;
    const generation = () => (e.x64_phys_generation(false) >>> 0) + (e.x64_phys_generation(true) >>> 0) * HIGH;
    const with_buffer = (words, operation) => {
        const pointer = e.v86_malloc(Math.max(4, words.byteLength));
        try
        {
            new Uint32Array(cpu.wasm_memory.buffer, pointer, words.length).set(words);
            return operation(pointer, words.length);
        }
        finally { e.v86_free(pointer); }
    };
    const restore_tlb = (core, words) => with_buffer(words,
        (pointer, count) => e.x64_tlb_snapshot_restore(core, pointer, count));
    assert.equal(e.x64_phys_set_window(0, 0, 1, 0x200000, 0x10000, 1), 1);
    const windows = cpu.get_physical_windows();
    const initial_generation = generation();
    assert.equal(with_buffer(windows, (pointer, count) => e.x64_phys_validate_windows(pointer, count)), 1);
    assert.equal(generation(), initial_generation, "validating windows cannot invalidate caches");
    const invalid_windows = windows.slice();
    invalid_windows[1] = 16;
    assert.equal(with_buffer(invalid_windows, (pointer, count) => e.x64_phys_validate_windows(pointer, count)), 0);
    assert.equal(generation(), initial_generation);
    assert.deepEqual(cpu.get_physical_windows(), windows);
    const records = [0, 1].map(core => {
        const linear_page = (0xFFFF800000100000n + BigInt(core) * 4096n) >> 12n;
        return new Uint32Array([
            Number(linear_page & 0xFFFFFFFFn), Number(linear_page >> 32n),
            0x1000 + core * 0x1000, 1, 24,
            0x5000 + core * 0x1000, 1, 12, 7 | core * 8, 4,
            0x1008, 1, 0x2008, 1, 0x3008, 1, 0x4008, 1,
        ]);
    });
    for(let core = 0; core < 2; core++)
    {
        cpu.switch_core(core);
        cpu.reg32[0] = 0xAB00 + core;
        assert.equal(with_buffer(records[core], (pointer, count) => e.x64_tlb_snapshot_validate(pointer, count)), 1);
        assert.equal(restore_tlb(core, records[core]), 1);
        assert.deepEqual(cpu.get_wide_tlb(core), records[core]);
    }
    cpu.switch_core(0);
    const payload = Uint8Array.from({ length: 32 }, (_, index) => index * 7 & 255);
    cpu.write_blob_physical(payload, HIGH + 0x5000);
    const snapshot = await emulator.save_state();
    assert.deepEqual(cpu.get_wide_tlb(0), records[0], "save does not flush an active core cache");
    assert.deepEqual(cpu.get_wide_tlb(1), records[1], "save does not flush an inactive core cache");
    assert.equal(e.x64_phys_set_window(0, 0, 0, 0, 0, 0), 1);
    cpu.write_blob_physical(new Uint8Array(payload.length).fill(0xEE), 0x205000);
    assert.equal(restore_tlb(0, new Uint32Array(0)), 1);
    assert.equal(restore_tlb(1, new Uint32Array(0)), 1);
    cpu.reg32[0] = 0xBAD;
    await emulator.restore_state(snapshot);
    assert.deepEqual(cpu.get_physical_windows(), windows);
    assert.deepEqual(cpu.read_blob_physical(HIGH + 0x5000, payload.length), payload);
    assert.throws(() => cpu.read8_physical(0x205000), RangeError);
    for(let core = 0; core < 2; core++)
    {
        assert.deepEqual(cpu.get_wide_tlb(core), records[core], "physical restore precedes per-core TLB restore");
        cpu.switch_core(core);
        assert.equal(cpu.reg32[0], 0xAB00 + core);
    }
    cpu.switch_core(0);
    console.log("PASS full-machine snapshot preserves high RAM/window and two independent wide TLB records");

    const original_set_state = cpu.set_state.bind(cpu);
    for(const kind of ["physical", "tlb"])
    {
        const old_generation = generation(), old_epoch = cpu.execution_epoch;
        cpu.set_state = state => {
            if(kind === "physical") state[97][1][1] = 16;
            else state[96][6][1][12][6] = 16;
            original_set_state(state);
        };
        try { await assert.rejects(emulator.restore_state(snapshot), /Invalid/); }
        finally { cpu.set_state = original_set_state; }
        assert.equal(generation(), old_generation);
        assert.equal(cpu.execution_epoch, old_epoch, "invalid snapshot rejected before architectural mutation");
        assert.deepEqual(cpu.get_physical_windows(), windows);
        for(let core = 0; core < 2; core++) assert.deepEqual(cpu.get_wide_tlb(core), records[core]);
        assert.deepEqual(cpu.read_blob_physical(HIGH + 0x5000, payload.length), payload);
    }
    console.log("PASS invalid physical/wide-TLB snapshot rejected before any live architectural state changes");

    cpu.set_state = state => {
        state.length = 97; // prior state images have no physical map extension
        for(const core of state[96][6]) core.length = 12; // no portable x64 TLB extension
        original_set_state(state);
    };
    try { await emulator.restore_state(snapshot); }
    finally { cpu.set_state = original_set_state; }
    assert.deepEqual(cpu.get_physical_windows(), new Uint32Array(80));
    assert.throws(() => cpu.read8_physical(HIGH + 0x5000), RangeError);
    assert.deepEqual(cpu.read_blob_physical(0x205000, payload.length), payload);
    for(let core = 0; core < 2; core++) assert.equal(cpu.get_wide_tlb(core).length, 0);
    console.log("PASS legacy missing physical/wide-TLB extensions clear destination mappings and cached translations");
}
finally { await emulator.destroy(); }
                                                                  source/v64/tests/smp/xstate_lifecycle.mjs                                                           0000644 0000000 0000000 00000015710 00000000000 015673  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// XSAVE-managed state across the machine's lifecycle (docs/simd-xsave-plan.md
// 6.4): per-core XCR0, YMM0_H-YMM15_H, XMM and x87 state round trip through
// snapshots; INIT keeps them (and the rest resets), RESET sets XCR0 to 1;
// snapshots from before the XSAVE range restore XCR0 1 and zero YMM halves,
// also the single-core snapshots from before machine core state; and a
// snapshot restores only into a machine with its CPU features.
import assert from "node:assert/strict";
import { CORE_STATE_RANGES, STATE_OFFSETS } from "../../src/state_layout.js";
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const FEATURES = ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX"];
async function machine(count, cpu_features)
{
    const vm = new V86({ graphics_adapter: "bochs_vga", acpi: true, cpu_cores: count, memory_size: 16 << 20,
        disable_jit: true, autostart: false, log_level: 0, cpu_features, cpu_features_unreleased: true,
        cpu_clock: { mode: "deterministic", instructions_per_ms: 100 }, cpu_schedule_seed: 42 });
    await new Promise(resolve => vm.add_listener("emulator-loaded", resolve));
    return vm;
}
/** A field of the active core */
const field = (cpu, offset, size) => new Uint8Array(cpu.wasm_memory.buffer, cpu.state_base + offset, size);
const u32 = (cpu, offset) => new DataView(cpu.wasm_memory.buffer, cpu.state_base + offset, 4).getUint32(0, true);
/** Distinct XSAVE state on each core */
function fingerprint(cpu, core)
{
    cpu.switch_core(core);
    new DataView(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.xcr0, 8).setUint32(0, 7, true);
    field(cpu, STATE_OFFSETS.ymm_hi, 256).set(Uint8Array.from({ length: 256 }, (_, i) => i + core * 37));
    field(cpu, STATE_OFFSETS.reg_xmm, 128).set(Uint8Array.from({ length: 128 }, (_, i) => i * 3 + core));
    cpu.mxcsr[0] = 0x1F80 | core << 5;
    new DataView(cpu.wasm_memory.buffer, cpu.state_base + STATE_OFFSETS.fpu_control_word, 2).setUint16(0, 0x27F + core, true);
    cpu.reg32[0] = 0x12340000 + core;
}
function check_fingerprint(cpu, core, label)
{
    cpu.switch_core(core);
    assert.equal(u32(cpu, STATE_OFFSETS.xcr0), 7, `${label}: core ${core} XCR0`);
    assert.deepEqual(field(cpu, STATE_OFFSETS.ymm_hi, 256), Uint8Array.from({ length: 256 }, (_, i) => i + core * 37), `${label}: core ${core} YMM_H`);
    assert.deepEqual(field(cpu, STATE_OFFSETS.reg_xmm, 128), Uint8Array.from({ length: 128 }, (_, i) => i * 3 + core), `${label}: core ${core} XMM`);
    assert.equal(cpu.mxcsr[0], 0x1F80 | core << 5, `${label}: core ${core} MXCSR`);
    assert.equal(u32(cpu, STATE_OFFSETS.fpu_control_word) & 0xFFFF, 0x27F + core, `${label}: core ${core} FCW`);
}
function check_reset_xstate(cpu, core, label)
{
    cpu.switch_core(core);
    assert.equal(u32(cpu, STATE_OFFSETS.xcr0), 1, `${label}: core ${core} XCR0 1`);
    assert.ok(field(cpu, STATE_OFFSETS.ymm_hi, 256).every(b => b === 0), `${label}: core ${core} YMM_H 0`);
}
/** A snapshot with its state (the JSON part) edited */
function rewrite(snapshot, edit)
{
    const header = new Int32Array(snapshot, 0, 4);
    const info = JSON.parse(new TextDecoder().decode(new Uint8Array(snapshot, 16, header[3])));
    edit(info.state);
    const json = new TextEncoder().encode(JSON.stringify(info));
    const old_start = 16 + header[3] + 3 & ~3, start = 16 + json.length + 3 & ~3;
    const result = new Uint8Array(start + snapshot.byteLength - old_start);
    result.set(new Uint8Array(snapshot, 0, 16));
    result.set(json, 16);
    result.set(new Uint8Array(snapshot, old_start), start);
    const out = new Int32Array(result.buffer, 0, 4);
    out[2] = result.length;
    out[3] = json.length;
    return result.buffer;
}
const XSTATE_RANGE = CORE_STATE_RANGES.findIndex(([start]) => start === STATE_OFFSETS.xcr0);
assert.ok(XSTATE_RANGE !== -1 && CORE_STATE_RANGES[XSTATE_RANGE][1] === STATE_OFFSETS.ymm_hi + 256);

for(const count of [1, 2])
{
    const vm = await machine(count, FEATURES);
    const cpu = vm.v86.cpu;
    try
    {
        for(let core = 0; core < count; core++) check_reset_xstate(cpu, core, "after creation");
        for(let core = 0; core < count; core++) fingerprint(cpu, core);
        const saved = await vm.save_state();
        for(let core = 0; core < count; core++)
        {
            cpu.switch_core(core);
            field(cpu, STATE_OFFSETS.xcr0, 272).fill(0x55);
            cpu.mxcsr[0] = 0x1F80;
        }
        await vm.restore_state(saved);
        for(let core = 0; core < count; core++) check_fingerprint(cpu, core, "snapshot");

        // a snapshot from before the XSAVE range: XCR0 1, YMM_H 0, the rest restored
        await vm.restore_state(rewrite(saved, state => {
            state[96][7].splice(XSTATE_RANGE, 1);
            for(const core of state[96][6]) core[1].splice(XSTATE_RANGE, 1);
        }));
        for(let core = 0; core < count; core++)
        {
            check_reset_xstate(cpu, core, "snapshot without the XSAVE range");
            assert.equal(cpu.reg32[0], 0x12340000 + core, "the other state is restored");
            assert.equal(cpu.mxcsr[0], 0x1F80 | core << 5);
        }
        if(count === 1)
        {
            // ... and from before machine core state (one core)
            await vm.restore_state(saved);
            await vm.restore_state(rewrite(saved, state => { state[96] = null; }));
            check_reset_xstate(cpu, 0, "snapshot without machine core state");
        }
        else
        {
            // INIT keeps x87, SSE and XSAVE state; the rest resets
            await vm.restore_state(saved);
            cpu.apic_restore_core_events(1, 1, false);
            cpu.take_core_events(1);
            check_fingerprint(cpu, 1, "INIT");
            cpu.switch_core(1);
            assert.equal(cpu.reg32[0], 0, "INIT resets the general registers");
        }
        // RESET: XCR0 1, YMM_H 0, MXCSR 1F80
        await vm.restore_state(saved);
        cpu.reboot_internal();
        for(let core = 0; core < count; core++)
        {
            check_reset_xstate(cpu, core, "reset");
            assert.equal(cpu.mxcsr[0], 0x1F80, "reset: MXCSR");
        }

        // the CPU features: a machine without them refuses the snapshot, and
        // this one a snapshot from before features were recorded
        const plain = await machine(count);
        try
        {
            const target = plain.v86.cpu, before = target.get_machine_core_state();
            await assert.rejects(plain.restore_state(saved), /CPU features SSSE3 SSE4.1 SSE4.2 XSAVE AVX .*this one has none/);
            assert.deepEqual(target.get_machine_core_state(), before, "nothing restored");
        }
        finally { await plain.destroy(); }
        await assert.rejects(vm.restore_state(rewrite(saved, state => { delete state[106]; })), /CPU features none/);
        console.log(`${count} core${count > 1 ? "s" : ""}: XSAVE state through snapshots, ${count > 1 ? "INIT, " : ""}reset, older snapshots and the feature check`);
    }
    finally { await vm.destroy(); }
}
                                                        source/v64/tests/tpm/linux_tpm.mjs                                                                  0000755 0000000 0000000 00000016541 00000000000 014372  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The TPM 2.0 with a real driver (docs/tpm.md; the plan's T1, "Linux 的
// tpm_crb 验证命令通路"): Alpine 3.24 x86_64 (the pinned standard ISO, its LTS
// kernel: the virt kernel has no TPM drivers; tests/lib/alpine_image.mjs)
// with tpm: { version: "2.0" } under SeaBIOS.
// SeaBIOS finds the TPM, starts it and measures the boot into the log area
// the TPM2 table gives (etc/tpm/log); Linux binds tpm_crb to the DSDT's
// MSFT0101 through the TPM2 table, registers /dev/tpm0 (TPM 2.0) and reads
// SeaBIOS's event log, which replayed gives the PCRs the TPM has; its hwrng
// draws from it. A command through /dev/tpm0 (GetRandom); PCR_Extend there
// and the PCR as Linux's sysfs reads it (pcr-sha256/16): SHA-256 of the
// old value and the data; a snapshot keeps it.
//
// MACHINE=q35, CPU_CORES=2, SHOW_LOGS=1, TEST_RELEASE_BUILD=1.

import assert from "node:assert/strict";
import crypto from "node:crypto";
import url from "node:url";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";
import { replay } from "../lib/tpm_event_log.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "i440fx";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const prepared = await prepare_alpine("x86_64-lts");
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: ROOT + "bios/seabios.bin" },
    vga_bios: { url: ROOT + "bios/vgabios.bin" },
    bzimage: { url: prepared.kernel },
    initrd: { url: prepared.initrd },
    cdrom: { url: prepared.iso },
    cmdline: "console=ttyS0,115200 loglevel=4 nokaslr modules=loop,squashfs,sd-mod",
    memory_size: 512 * 1024 * 1024,
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    acpi: true,
    net_device: { type: "none" },
    tpm: { version: "2.0" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial);
    process.exit(1);
}, 900 * 1000);

let serial = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});

const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}
/** A command's output: between markers its echo does not have */
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send("echo BE''GIN; " + cmd + "; echo EN''D\n");
    const output = await wait_serial(/^END\r?\n[^]*:~# (\x1b\[6n)?$/m, JSON.stringify(cmd), timeout_ms);
    return output.replace(/\r/g, "").match(/^BEGIN\n([^]*?)^END$/m)[1];
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

/** A TPM command through /dev/tpm0 (one file descriptor, written then read): the response's hex */
async function tpm(hex)
{
    const bytes = Buffer.from(hex.replace(/ /g, ""), "hex");
    bytes.writeUInt32BE(bytes.length, 2);
    const escaped = Array.from(bytes, b => "\\" + b.toString(8).padStart(3, "0")).join("");
    const output = await command("exec 3<>/dev/tpm0; printf '" + escaped + "' >&3; dd bs=4096 count=1 <&3 2>/dev/null | od -An -v -tx1 | tr -d ' \\n'; echo; exec 3>&-");
    return output.trim();
}

console.log("Booting Alpine x86_64 with a TPM 2.0 (" + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");
await wait_serial(/login: $/, "the login prompt", 600000);
serial = "";
emulator.serial0_send("root\n");
await wait_serial(PROMPT, "the shell", 120000);

await step("tpm_crb on MSFT0101: /dev/tpm0, a TPM 2.0, the hwrng", async () => {
    const output = await command("for i in $(seq 20); do [ -e /dev/tpm0 ] && break; modprobe tpm_crb 2>/dev/null; sleep 1; done; " +
        "basename $(readlink /sys/class/tpm/tpm0/device/driver); cat /sys/class/tpm/tpm0/tpm_version_major; " +
        "cat /sys/class/tpm/tpm0/device/hid 2>/dev/null; cat /sys/class/misc/hw_random/rng_available");
    assert.match(output, /^tpm_crb$/m);
    assert.match(output, /^2$/m);
    assert.match(output, /^MSFT0101$/m);
    assert.match(output, /tpm-rng-0/);
});

await step("SeaBIOS started the TPM and measured the boot: the TPM2 table's log replayed", async () => {
    const encoded = await command("base64 -w0 /sys/kernel/security/tpm0/binary_bios_measurements; echo", 300000);
    const { pcrs, events } = replay(Buffer.from(encoded.trim(), "base64"));
    // (its separators end PCRs 0 to 7 before the boot)
    for(const pcr of [0, 1, 2, 3, 4, 5, 6, 7]) assert.ok(pcrs.has(pcr), "PCR " + pcr + " in the log");
    const reads = await command("for p in " + [...pcrs.keys()].join(" ") + "; do echo $p $(cat /sys/class/tpm/tpm0/pcr-sha256/$p); done");
    for(const line of reads.trim().split("\n"))
    {
        const [pcr, value] = line.split(" ");
        assert.equal(value.toLowerCase(), pcrs.get(+pcr).toString("hex"), "PCR " + pcr);
    }
    console.log("    " + events + " events, PCRs " + [...pcrs.keys()].sort((a, b) => a - b).join(", "));
});

await step("a command through /dev/tpm0: GetRandom", async () => {
    const response = await tpm("8001 00000000 0000017b 0010");
    assert.match(response, /^80010000001c00000000(0010)[0-9a-f]{32}$/);
});

let expected;
await step("PCR_Extend through /dev/tpm0; Linux's sysfs reads the PCR: SHA-256 of the old value and the data", async () => {
    const before = (await command("cat /sys/class/tpm/tpm0/pcr-sha256/16")).trim().toLowerCase();
    const data = crypto.randomBytes(32);
    const response = await tpm("8002 00000000 00000182 00000010 00000009 40000009 0000 00 0000 00000001 000b " + data.toString("hex"));
    assert.match(response, /^80020000001300000000/);
    expected = crypto.createHash("sha256").update(Buffer.concat([Buffer.from(before, "hex"), data])).digest("hex");
    assert.equal((await command("cat /sys/class/tpm/tpm0/pcr-sha256/16")).trim().toLowerCase(), expected);
});

await step("a snapshot: the PCR after restoring", async () => {
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    serial = "";
    emulator.serial0_send("\n");
    await wait_serial(PROMPT, "the shell after restoring", 30000);
    assert.equal((await command("cat /sys/class/tpm/tpm0/pcr-sha256/16")).trim().toLowerCase(), expected);
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                               source/v64/tests/tpm/tpm.mjs                                                                        0000755 0000000 0000000 00000024651 00000000000 013154  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The TPM 2.0 device (docs/tpm.md) without a guest: a machine with tpm, the
// CRB driven through the machine's memory map as a driver drives it
// (locality, command ready, the command in the data buffer, start, the
// response). The interface identifier; TPM2_Startup, GetRandom (bytes that
// differ), the PCR banks (SHA-256 only, as made), PCR_Extend and PCR_Read
// (the digest SHA-256 of the old value and the data); the ACPI tables
// (TPM2: CRB, the control area, the log area; the DSDT's MSFT0101). The state kept
// (tpm.state written back): an NV index defined and written in one machine
// is read in the next; a damaged store is refused, a store of zeros is a new
// TPM. Snapshots: the PCRs (volatile) come back, a snapshot of a store
// written since does not restore. A machine reset is the TPM's (Startup
// needed again).
//
// TEST_RELEASE_BUILD=1, MACHINE=q35.

import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const MACHINE = process.env.MACHINE || "i440fx";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const directory = ROOT + "build/tpm-test/";
fs.mkdirSync(directory, { recursive: true });
const STORE = directory + "tpm-state.img";
fs.writeFileSync(STORE, Buffer.alloc(512 * 1024));

const BASE = 0xFED40000;

/** A machine with a TPM, not running: { emulator, cpu } */
async function machine(state)
{
    const emulator = new V86({
        bios: { url: ROOT + "bios/seabios.bin" },
        vga_bios: { url: ROOT + "bios/vgabios.bin" },
        memory_size: 64 * 1024 * 1024,
        graphics_adapter: "bochs_vga",
        machine_type: MACHINE,
        acpi: true,
        net_device: { type: "none" },
        tpm: { version: "2.0", state },
        autostart: false,
        log_level: 0,
    });
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-ready", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    return { emulator, cpu: emulator.v86.cpu };
}

/** The CRB through the memory map, as a driver: { read, write, command } */
function crb(cpu)
{
    const block = address => address >>> 17;
    const read = offset => cpu.memory_map_read32[block(BASE + offset)](BASE + offset | 0) >>> 0;
    const write = (offset, value) => cpu.memory_map_write32[block(BASE + offset)](BASE + offset | 0, value | 0);
    const command = (hex, locality = 0) =>
    {
        const window = locality * 0x1000;
        const bytes = Buffer.from(hex.replace(/ /g, ""), "hex");
        bytes.writeUInt32BE(bytes.length, 2);
        write(window + 0x08, 1);                        // LOC_CTRL: request access
        assert.equal(read(window + 0x0C) & 1, 1, "the locality granted");
        assert.equal(read(window + 0x00) >> 2 & 7, locality, "the active locality");
        write(window + 0x40, 1);                        // CTRL_REQ: command ready
        assert.equal(read(window + 0x44) & 2, 0, "not idle");
        const buffer = read(window + 0x5C);             // CMD_LADDR
        assert.equal(buffer, BASE + 0x80);
        const padded = Buffer.concat([bytes, Buffer.alloc(-bytes.length & 3)]);
        for(let i = 0; i < padded.length; i += 4) write(buffer - BASE + i, padded.readInt32LE(i));
        write(window + 0x4C, 1);                        // CTRL_START
        assert.equal(read(window + 0x4C), 0, "the command done");
        const header = Buffer.alloc(8);
        header.writeUInt32LE(read(0x80), 0);
        header.writeUInt32LE(read(0x84), 4);
        const length = header.readUInt32BE(2);
        const response = Buffer.alloc(length + 3 & ~3);
        for(let i = 0; i < response.length; i += 4) response.writeUInt32LE(read(0x80 + i), i);
        write(window + 0x40, 2);                        // go idle
        write(window + 0x08, 2);                        // relinquish
        return response.subarray(0, length);
    };
    return { read, write, command };
}

const code = response => response.readUInt32BE(6);
const STARTUP = "8001 00000000 00000144 0000";
// a password session with an empty password
const PW = "00000009 40000009 0000 00 0000";
const NV_INDEX = "01500016";

let passed = 0;
async function step(name, f)
{
    await f();
    passed++;
    console.log("ok - " + name);
}

let first = await machine({ url: STORE, disk_option: "read_write" });
let tpm = crb(first.cpu);

await step("the interface identifier: CRB, version 1, five localities; QEMU's vendor and device", async () => {
    const low = tpm.read(0x30), high = tpm.read(0x34);
    assert.equal(low & 0xF, 1, "interface type CRB");
    assert.equal(low >> 4 & 0xF, 1, "CRB version 1");
    assert.equal(low >> 8 & 1, 1, "five localities");
    assert.equal(high, 0x00011014);
    assert.equal(tpm.read(0x00) & 0x80, 0x80, "the registers valid");
    assert.equal(tpm.read(0x58), 0xF80, "the buffer's size");
});

await step("Startup, GetRandom (bytes from the host's randomness)", async () => {
    assert.equal(code(tpm.command(STARTUP)), 0);
    const a = tpm.command("8001 00000000 0000017b 0020"), b = tpm.command("8001 00000000 0000017b 0020");
    assert.equal(code(a), 0);
    assert.equal(a.readUInt16BE(10), 32);
    assert.notDeepEqual(a.subarray(12), b.subarray(12));
});

let pcr16;
await step("the PCR banks: SHA-256 only; PCR_Extend and PCR_Read agree with SHA-256", async () => {
    const banks = tpm.command("8001 00000000 0000017a 00000005 00000000 00000001");
    assert.equal(code(banks), 0);
    // (count 4: SHA-1, SHA-256, SHA-384, SHA-512; selected PCRs only in SHA-256's)
    assert.equal(banks.subarray(19).toString("hex"), "000403000000000b03ffffff000c03000000000d03000000");
    const data = crypto.randomBytes(32);
    assert.equal(code(tpm.command("8002 00000000 00000182 00000010 " + PW + " 00000001 000b " + data.toString("hex"))), 0);
    const read = tpm.command("8001 00000000 0000017e 00000001 000b 03 000001");
    assert.equal(code(read), 0);
    pcr16 = crypto.createHash("sha256").update(Buffer.concat([Buffer.alloc(32), data])).digest();
    assert.deepEqual(read.subarray(read.length - 32), pcr16);
});

await step("the ACPI tables: TPM2 (CRB, its control area, the log area) and the DSDT's MSFT0101", async () => {
    const fw = first.cpu.option_roms.find(file => file.name === "etc/acpi/tables");
    const bytes = Buffer.from(fw.get_data ? fw.get_data() : fw.data);
    const at = bytes.indexOf("TPM2");
    assert.ok(at >= 0, "a TPM2 table");
    assert.equal(bytes.readUInt32LE(at + 4), 76);
    assert.equal(bytes[at + 8], 4, "revision 4");
    assert.equal(Number(bytes.readBigUInt64LE(at + 40)), BASE + 0x40, "the control area");
    assert.equal(bytes.readUInt32LE(at + 48), 7, "start method CRB");
    assert.equal(bytes.readUInt32LE(at + 64), 0x10000, "a log area of 64 KiB");
    const log = first.cpu.option_roms.find(file => file.name === "etc/tpm/log");
    assert.equal(log && log.data.length, 0x10000, "etc/tpm/log, which the table loader allocates");
    assert.ok(bytes.indexOf("MSFT0101") > 0, "the DSDT's MSFT0101");
});

await step("the state kept: an NV index written in one machine, read in the next", async () => {
    // NV_DefineSpace(owner): AUTHWRITE | AUTHREAD | NO_DA, 8 bytes; NV_Write
    assert.equal(code(tpm.command("8002 00000000 0000012a 40000001 " + PW + " 0000 000e " + NV_INDEX + " 000b 02040004 0000 0008")), 0);
    assert.equal(code(tpm.command("8002 00000000 00000137 " + NV_INDEX + " " + NV_INDEX + " " + PW + " 0008 7638362074706d21 0000")), 0);
    await first.emulator.destroy();
    const second = await machine({ url: STORE, disk_option: "read_write" });
    tpm = crb(second.cpu);
    assert.equal(code(tpm.command(STARTUP)), 0);
    const read = tpm.command("8002 00000000 0000014e " + NV_INDEX + " " + NV_INDEX + " " + PW + " 0008 0000");
    assert.equal(code(read), 0);
    assert.equal(read.subarray(read.length - 13, read.length - 5).toString(), "v86 tpm!");
    first = second;
});

await step("a snapshot: the PCRs come back; a reset is the TPM's", async () => {
    const data = crypto.randomBytes(32);
    assert.equal(code(tpm.command("8002 00000000 00000182 00000010 " + PW + " 00000001 000b " + data.toString("hex"))), 0);
    const state = await first.emulator.save_state();
    // (the platform reset: the TPM wants Startup again)
    first.emulator.restart();
    assert.equal(code(tpm.command("8001 00000000 0000017e 00000001 000b 03 000001")), 0x100, "TPM_RC_INITIALIZE");
    await first.emulator.restore_state(state);
    const read = tpm.command("8001 00000000 0000017e 00000001 000b 03 000001");
    assert.equal(code(read), 0);
    assert.deepEqual(read.subarray(read.length - 32), crypto.createHash("sha256").update(Buffer.concat([Buffer.alloc(32), data])).digest());
    // (a change to the store since: the snapshot no longer fits it)
    assert.equal(code(tpm.command("8002 00000000 00000137 " + NV_INDEX + " " + NV_INDEX + " " + PW + " 0008 6368616e67656421 0000")), 0);
    await assert.rejects(first.emulator.restore_state(state), /tpm_state/);
    await first.emulator.destroy();
});

await step("a damaged store is refused; a store of zeros is a new TPM", async () => {
    const damaged = Buffer.alloc(512 * 1024);
    damaged.write("garbage", 100);
    fs.writeFileSync(directory + "damaged.img", damaged);
    const emulator = new V86({
        bios: { url: ROOT + "bios/seabios.bin" },
        vga_bios: { url: ROOT + "bios/vgabios.bin" },
        memory_size: 64 * 1024 * 1024, graphics_adapter: "bochs_vga", machine_type: MACHINE, acpi: true, net_device: { type: "none" },
        tpm: { version: "2.0", state: { url: directory + "damaged.img", disk_option: "read_write" } },
        autostart: false, log_level: 0,
    });
    const error = await new Promise(resolve => {
        emulator.add_listener("emulator-error", resolve);
        emulator.add_listener("emulator-ready", () => resolve(null));
    });
    assert.match(String(error && error.message), /damaged/);
    // (in memory: a new TPM, without the NV index)
    const fresh = await machine(undefined);
    tpm = crb(fresh.cpu);
    assert.equal(code(tpm.command(STARTUP)), 0);
    assert.notEqual(code(tpm.command("8002 00000000 0000014e " + NV_INDEX + " " + NV_INDEX + " " + PW + " 0008 0000")), 0);
    await fresh.emulator.destroy();
});

console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                       source/v64/tests/tpm/uefi_tpm.mjs                                                                   0000755 0000000 0000000 00000013506 00000000000 014161  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The TPM with the UEFI firmware (docs/tpm.md; the plan's T2): OVMF finds the
// TPM 2.0 behind the CRB, starts it and measures the boot into its SHA-256
// PCRs (the firmware volumes, its configuration, the boot loader, GRUB and
// Linux's own measurements through the TCG2 protocol); Linux (Alpine 3.24's
// LTS kernel from a GPT disk's ESP, tests/lib/uefi_disk.mjs) finds the event
// log through the EFI configuration table. The log replayed (each event's
// SHA-256 digest extended into its PCR) gives what the TPM reads for every
// PCR it names: the measurements are the TPM's, the log describes them.
//
// MACHINE=i440fx, CPU_CORES=2, SHOW_LOGS=1, TEST_RELEASE_BUILD=1. macOS (hdiutil).

import assert from "node:assert/strict";
import url from "node:url";
import { replay } from "../lib/tpm_event_log.mjs";
import { prepare_esp_disk } from "../lib/uefi_disk.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "q35";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const disk = await prepare_esp_disk("lts");
const emulator = new V86({
    firmware: {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-code.fd" },
        vars: { url: ROOT + "bios/ovmf-vars.fd" },
        debug_console: true,
    },
    hda: { url: disk },
    memory_size: 768 * 1024 * 1024,
    graphics_adapter: "bochs_vga",
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    qemu_compatible: MACHINE === "i440fx",
    acpi: true,
    net_device: { type: "none" },
    tpm: { version: "2.0" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial.slice(-3000));
    process.exit(1);
}, 900 * 1000);

let serial = "";
let debug_log = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(serial))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(serial);
    }
});
emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });

const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + serial.slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(serial))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(serial);
        }
    });
}
/** A command's output: between markers its echo does not have */
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send("echo BE''GIN; " + cmd + "; echo EN''D\n");
    const output = await wait_serial(/^END\r?\n[^]*:~# (\x1b\[6n)?$/m, JSON.stringify(cmd), timeout_ms);
    return output.replace(/\r/g, "").match(/^BEGIN\n([^]*?)^END$/m)[1];
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

console.log("Booting the LTS ESP disk under UEFI with a TPM (" + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");

await step("OVMF: the TPM 2.0 found, started, its SHA-256 bank active; Linux's login", async () => {
    await wait_serial(/login: $/, "the login prompt", 600000);
    assert.match(debug_log, /Tcg2ConfigPeimEntryPoint: TPM2 detected/);
    assert.match(debug_log, /TPM2Startup: TPM_RC_SUCCESS/);
    assert.match(debug_log, /Tpm2GetCapabilitySupportedAndActivePcrs - TpmActivePcrBanks 0x00000002/);
    assert.doesNotMatch(debug_log, /ASSERT /);
    serial = "";
    emulator.serial0_send("root\n");
    await wait_serial(PROMPT, "the shell", 120000);
});

await step("Linux: tpm_crb, the event log from the EFI configuration table", async () => {
    const output = await command("for i in $(seq 20); do [ -e /dev/tpm0 ] && break; sleep 1; done; " +
        "basename $(readlink /sys/class/tpm/tpm0/device/driver); dmesg | grep -o 'TPMFinalLog=0x[0-9a-f]*\\|TPMEventLog=0x[0-9a-f]*' | sort -u; " +
        "ls -l /sys/kernel/security/tpm0/binary_bios_measurements");
    assert.match(output, /^tpm_crb$/m);
    assert.match(output, /TPMEventLog=0x/);
    assert.match(output, /binary_bios_measurements/);
});

await step("the event log replayed: each PCR it names reads as the TPM has it", async () => {
    const encoded = await command("base64 -w0 /sys/kernel/security/tpm0/binary_bios_measurements; echo", 300000);
    const { pcrs, events } = replay(Buffer.from(encoded.trim(), "base64"));
    assert.ok(events > 20, events + " events");
    for(const pcr of [0, 1, 2, 3, 4, 5, 6, 7]) assert.ok(pcrs.has(pcr), "PCR " + pcr + " in the log");
    const reads = await command("for p in " + [...pcrs.keys()].join(" ") + "; do echo $p $(cat /sys/class/tpm/tpm0/pcr-sha256/$p); done");
    for(const line of reads.trim().split("\n"))
    {
        const [pcr, value] = line.split(" ");
        assert.equal(value.toLowerCase(), pcrs.get(+pcr).toString("hex"), "PCR " + pcr);
    }
    console.log("    " + events + " events, PCRs " + [...pcrs.keys()].sort((a, b) => a - b).join(", "));
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                          source/v64/tests/uefi/efi_min.h                                                                     0000644 0000000 0000000 00000006051 00000000000 013537  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The few UEFI tables, protocols and GUIDs the test applications use
 * (tests/uefi/sb_app.c, vars_app.c): x86_64-w64-mingw32-gcc, no EFI headers.
 * Only the members they call are named. */
typedef unsigned long long u64;
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef u64 status_t;
typedef void *handle_t;
typedef struct { u32 a; u16 b, c; u8 d[8]; } guid_t;
#define API __attribute__((ms_abi))

typedef struct { u64 signature; u32 revision, size, crc, reserved; } table_header;
typedef struct text_out
{
    void *reset;
    API status_t (*output)(struct text_out *, const u16 *);
} text_out;
typedef struct
{
    table_header hdr;
    void *get_time, *set_time, *get_wakeup, *set_wakeup, *set_virtual, *convert;
    API status_t (*get_variable)(const u16 *, const guid_t *, u32 *, u64 *, void *);
    void *next_name;
    API status_t (*set_variable)(const u16 *, const guid_t *, u32, u64, const void *);
    void *next_count;
    API void (*reset)(u32, status_t, u64, void *);
} runtime_services;
typedef struct
{
    table_header hdr;
    void *raise, *restore, *allocate_pages, *free_pages, *memory_map;
    API status_t (*allocate_pool)(u32, u64, void **);
    API status_t (*free_pool)(void *);
    void *create_event, *set_timer, *wait, *signal, *close_event, *check_event;
    void *install, *reinstall, *uninstall;
    API status_t (*handle_protocol)(handle_t, const guid_t *, void **);
    void *reserved, *notify, *locate_handle, *locate_path, *install_table;
    API status_t (*load_image)(u8, handle_t, void *, void *, u64, handle_t *);
    API status_t (*start_image)(handle_t, u64 *, u16 **);
    void *exit;
    API status_t (*unload_image)(handle_t);
    void *exit_boot_services, *next_monotonic, *stall;
    API status_t (*set_watchdog)(u64, u64, u64, u16 *);
} boot_services;
typedef struct
{
    table_header hdr;
    u16 *vendor;
    u32 revision;
    handle_t in_handle;
    void *in;
    handle_t out_handle;
    text_out *out;
    handle_t err_handle;
    void *err;
    runtime_services *rt;
    boot_services *bs;
} system_table;
typedef struct
{
    u32 revision;
    handle_t parent;
    system_table *system;
    handle_t device;
    void *path;
    void *reserved;
    u32 options_size;
    void *options;
} loaded_image;
typedef struct file
{
    u64 revision;
    API status_t (*open)(struct file *, struct file **, const u16 *, u64, u64);
    API status_t (*close)(struct file *);
    void *remove;
    API status_t (*read)(struct file *, u64 *, void *);
    void *write;
    API status_t (*get_position)(struct file *, u64 *);
    API status_t (*set_position)(struct file *, u64);
} file;
typedef struct
{
    u64 revision;
    API status_t (*open_volume)(void *, file **);
} file_system;

static const guid_t LOADED_IMAGE = {0x5B1B31A1, 0x9562, 0x11d2, {0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B}};
static const guid_t FILE_SYSTEM = {0x964E5B22, 0x6459, 0x11d2, {0x8E, 0x39, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B}};
static const guid_t DEVICE_PATH = {0x09576E91, 0x6D3F, 0x11d2, {0x8E, 0x39, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B}};
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/uefi/esp_boot.mjs                                                                  0000755 0000000 0000000 00000016752 00000000000 014321  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// A cold boot from a fixed disk under UEFI (docs/uefi.md, the plan's F1):
// OVMF's boot manager finds no boot entries, starts the removable-media
// loader of the GPT disk's EFI System Partition (tests/lib/uefi_disk.mjs:
// GRUB, then Alpine 3.24 x86_64 from the ESP alone), on Q35's AHCI or
// i440FX's IDE. In Linux: booted through UEFI (64-bit firmware, EFI runtime
// variables with OVMF's Boot####), the ESP mounted as the boot media, v86's
// SMBIOS, the ACPI tables with Q35's ECAM where OVMF put it and every BAR in
// the root bridge's windows, S0 and S5 only. A snapshot; "reboot" through
// the firmware back to the login; "poweroff" through ACPI S5.
//
// MACHINE=i440fx, CPU_CORES=2, SHOW_LOGS=1, TEST_RELEASE_BUILD=1. macOS (hdiutil).

import assert from "node:assert/strict";
import url from "node:url";
import { prepare_esp_disk } from "../lib/uefi_disk.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "q35";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const disk = await prepare_esp_disk();
const emulator = new V86({
    firmware: {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-code.fd" },
        vars: { url: ROOT + "bios/ovmf-vars.fd" },
        debug_console: true,
    },
    hda: { url: disk },
    memory_size: 512 * 1024 * 1024,
    graphics_adapter: "bochs_vga",
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    qemu_compatible: MACHINE === "i440fx",
    acpi: true,
    net_device: { type: "none" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + plain(serial).slice(-3000));
    process.exit(1);
}, 900 * 1000);

let serial = "";
let debug_log = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(plain(serial)))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(plain(serial));
    }
});
emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });

/** Serial output without the terminal's escape sequences and carriage returns */
function plain(text)
{
    return text.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");
}

const PROMPT = /:~# (\x1b\[6n)?$/;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + plain(serial).slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(plain(serial)))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(plain(serial));
        }
    });
}
/** A shell command's output: between markers that its echo (which a long command wraps) does not have */
async function command(cmd, timeout_ms = 120000)
{
    serial = "";
    emulator.serial0_send("echo BE''GIN; " + cmd + "; echo EN''D\n");
    const output = await wait_serial(/^END\n[^]*:~# (\x1b\[6n)?$/m, JSON.stringify(cmd), timeout_ms);
    return output.match(/^BEGIN\n([^]*?)^END$/m)[1];
}
async function login()
{
    await wait_serial(/login: $/, "the login prompt", 600000);
    serial = "";
    emulator.serial0_send("root\n");
    await wait_serial(PROMPT, "the shell", 120000);
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

console.log("Booting the ESP disk under UEFI (" + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");

await step("the boot manager starts the disk's removable-media loader: GRUB, Linux, Alpine's login", async () => {
    await wait_serial(/BdsDxe: starting Boot\d+ "[^"]*" from \S+\n/, "the boot manager", 180000);
    const boot = plain(serial).match(/BdsDxe: starting Boot\d+ "([^"]*)" from (\S+)/);
    assert.ok(boot, plain(serial).slice(-1000));
    assert.match(boot[2], MACHINE === "q35" ? /^PciRoot\(0x0\)\/Pci\(0x1F,0x2\)\/Sata\(0x0,0xFFFF,0x0\)$/ : /^PciRoot\(0x0\)\/Pci\(0x1,0x1\)\/Ata\(/,
        "the disk: " + boot[2]);
    await wait_serial(/Booting `Alpine virt \(UEFI, from the ESP\)'/, "GRUB's entry", 120000);
    await login();
});

await step("Linux: booted through 64-bit UEFI, EDK II's runtime variables with the boot entries", async () => {
    assert.match(await command("cat /sys/firmware/efi/fw_platform_size"), /^64$/m);
    assert.match(await command("dmesg | grep 'efi: EFI v'"), /EFI v2\.7\d? by EDK II/);
    const variables = await command("ls /sys/firmware/efi/efivars");
    assert.match(variables, /BootOrder-8be4df61-93ca-11d2-aa0d-00e098032b8c/);
    assert.match(variables, /Boot0001-8be4df61-93ca-11d2-aa0d-00e098032b8c/);
});

await step("the ESP: the GPT partition's name, mounted as the boot media", async () => {
    assert.match(await command("cat /sys/block/sda/sda1/uevent"), /PARTNAME=ESP/);
    assert.match(await command("grep sda1 /proc/mounts"), /^\/dev\/sda1 \/media\/sda1 vfat /m);
});

await step("SMBIOS, the ACPI tables, the PCI windows, the sleep states", async () => {
    assert.match(await command("cat /sys/class/dmi/id/sys_vendor /sys/class/dmi/id/product_name"),
        MACHINE === "q35" ? /^v86\nv86 PC \(Q35 \+ ICH9\)$/m : /^v86\nv86 PC \(i440FX \+ PIIX\)$/m);
    const tables = await command("ls /sys/firmware/acpi/tables");
    for(const table of ["DSDT", "FACP", "APIC", ...(MACHINE === "q35" ? ["MCFG"] : [])])
    {
        assert.match(tables, new RegExp("\\b" + table + "\\b"), table);
    }
    if(MACHINE === "q35")
    {
        assert.match(await command("dmesg | grep -i ecam"), /\[mem 0xe0000000-0xefffffff\]/);
    }
    assert.doesNotMatch(await command("dmesg | grep -iE \"can't claim|no compatible bridge window|failed to assign\""), /\S/,
        "every BAR where the root bridge's windows have it");
    assert.match(await command("dmesg | grep 'ACPI: PM: (supports'"), /\(supports S0 S5\)/);
});

await step("a snapshot: Linux goes on after restoring", async () => {
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    assert.match(await command("echo RE''STORED"), /^RESTORED$/m);
});

await step("reboot: through the firmware and the ESP to the login again", async () => {
    debug_log = "";
    serial = "";
    emulator.serial0_send("reboot\n");
    await wait_serial(/BdsDxe: starting Boot\d+ /, "the boot manager after rebooting", 300000);
    assert.match(debug_log, /SecCoreStartupWithStack/);
    await login();
});

await step("poweroff: ACPI S5 turns the machine off", async () => {
    emulator.serial0_send("poweroff\n");
    const start = Date.now();
    while(!emulator.v86.cpu.powered_off())
    {
        assert.ok(Date.now() - start < 120000, "powered off within 2 minutes");
        await new Promise(resolve => setTimeout(resolve, 500));
    }
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                      source/v64/tests/uefi/sb_app.c                                                                      0000644 0000000 0000000 00000017526 00000000000 013401  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* What tests/uefi/secure_boot.mjs runs as \EFI\BOOT\BOOTX64.EFI (signed with
 * its test db key): Secure Boot seen from inside, line by line on the console
 * ("V86SB ..."). x86_64-w64-mingw32-gcc with the tables of efi_min.h.
 *
 * First boot (its counter variable V86SbBoot absent): LoadImage of each probe
 * in \PROBE (signed by a db key, unsigned, changed after signing, signed by a
 * key not enrolled, revoked by its hash in dbx, signed by a second key that
 * is not in db yet); SetVariable with each update in \UPDATE (the file name
 * is the variable, its data an EFI_VARIABLE_AUTHENTICATION_2 update, or raw
 * for UNSIGNED); a direct write to the variable store's flash; then the
 * second key's probe again; then a cold reset.
 * Second boot: the probes again; then Linux (\LINUX\VMLINUZ.EFI, signed, with
 * the command line of \LINUX\CMDLINE.TXT). With -DPROBE=n: a probe that only
 * returns. */
#include "efi_min.h"

#ifdef PROBE
API status_t efi_main(handle_t image, void *system)
{
    (void)image;
    (void)system;
    /* (a different constant per probe: a different image, a different hash) */
    static volatile u32 variant = PROBE;
    return variant ? 0 : 1;
}
#else

static const guid_t GLOBAL = {0x8BE4DF61, 0x93CA, 0x11d2, {0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C}};
static const guid_t SECURITY_DATABASE = {0xD719B2CB, 0x3D3A, 0x4596, {0xA3, 0xBC, 0xDA, 0xD0, 0x0E, 0x67, 0x65, 0x6F}};
static const guid_t TEST = {0x86B00F5E, 0x5B57, 0x4C1A, {0x9E, 0x2D, 0x76, 0x38, 0x36, 0x53, 0x42, 0x01}};
#define NV 1
#define BS 2
#define RT 4
#define TIME_AUTH 0x20
#define APPEND 0x40
/* the variable store: 4 GiB - the code (3.5 MiB) - the store (528 KiB), its first variable */
#define STORE_FLASH ((volatile u8 *)0xFFC00064ULL)

static system_table *st;
static handle_t self;
static file *root;
static u16 line[400];
static int at;

static void put(const char *s) { while(*s && at < 398) line[at++] = (u8)*s++; }
static void put_hex(u64 n)
{
    for(int i = 60; i >= 0; i -= 4)
    {
        if(i > 0 && !(n >> i)) continue;
        line[at++] = "0123456789abcdef"[n >> i & 15];
    }
}
static void flush(void)
{
    line[at++] = '\r';
    line[at++] = '\n';
    line[at] = 0;
    st->out->output(st->out, line);
    at = 0;
}
static void ascii_to_wide(const char *s, u16 *out) { while((*out++ = (u8)*s++)); }

static u64 variable_byte(const u16 *name, const guid_t *vendor)
{
    u8 value = 0xFF;
    u64 size = 1;
    u32 attributes;
    return st->rt->get_variable(name, vendor, &attributes, &size, &value) ? 0xFF : value;
}

/* a file of the volume, in pool memory */
static status_t read_file(const char *name, u8 **data, u64 *size)
{
    u16 wide[80];
    file *f;
    ascii_to_wide(name, wide);
    status_t s = root->open(root, &f, wide, 1, 0);
    if(s) return s;
    f->set_position(f, ~0ULL);
    f->get_position(f, size);
    f->set_position(f, 0);
    s = st->bs->allocate_pool(2, *size + 2, (void **)data);
    if(!s) s = f->read(f, size, *data);
    f->close(f);
    return s;
}

/* the file's device path: this volume's, then the file's node */
static void *file_path(const char *name)
{
    u8 *device;
    loaded_image *image;
    st->bs->handle_protocol(self, &LOADED_IMAGE, (void **)&image);
    if(st->bs->handle_protocol(image->device, &DEVICE_PATH, (void **)&device)) return 0;
    u64 length = 0;
    while(!(device[length] == 0x7F && device[length + 1] == 0xFF)) length += device[length + 2] | device[length + 3] << 8;
    u64 name_length = 0;
    while(name[name_length]) name_length++;
    u64 node = 4 + (name_length + 1) * 2;
    u8 *path;
    if(st->bs->allocate_pool(2, length + node + 4, (void **)&path)) return 0;
    for(u64 i = 0; i < length; i++) path[i] = device[i];
    u8 *n = path + length;
    n[0] = 4;
    n[1] = 4;
    n[2] = node & 0xFF;
    n[3] = node >> 8;
    ascii_to_wide(name, (u16 *)(n + 4));
    n += node;
    n[0] = 0x7F;
    n[1] = 0xFF;
    n[2] = 4;
    n[3] = 0;
    return path;
}

/* LoadImage from the file (the firmware verifies it), unloaded again */
static status_t probe(const char *name)
{
    handle_t h;
    status_t s = st->bs->load_image(0, self, file_path(name), 0, 0, &h);
    if(!s) st->bs->unload_image(h);
    put("V86SB load ");
    put(name);
    put(" ");
    put_hex(s);
    flush();
    return s;
}

static void probes(void)
{
    probe("\\PROBE\\DB.EFI");
    probe("\\PROBE\\UNSIGNED.EFI");
    probe("\\PROBE\\CHANGED.EFI");
    probe("\\PROBE\\OTHER.EFI");
    probe("\\PROBE\\REVOKED.EFI");
    probe("\\PROBE\\DB2.EFI");
}

/* SetVariable with an update file: name, its GUID, attributes */
static void update(const char *file_name, const char *label, const u16 *variable, const guid_t *vendor, u32 attributes)
{
    u8 *data;
    u64 size;
    status_t s = read_file(file_name, &data, &size);
    if(!s) s = st->rt->set_variable(variable, vendor, attributes, size, data);
    put("V86SB set ");
    put(label);
    put(" ");
    put_hex(s);
    flush();
}

static void flash_write(void)
{
    u8 before = STORE_FLASH[0];
    /* CFI: program (0x40), its byte; then read array */
    STORE_FLASH[0] = 0x40;
    STORE_FLASH[0] = 0x00;
    STORE_FLASH[0] = 0xFF;
    u8 after = STORE_FLASH[0];
    put("V86SB flash ");
    put_hex(before);
    put(" ");
    put_hex(after);
    flush();
}

static void boot_linux(void)
{
    u8 *cmdline;
    u64 size;
    handle_t h;
    loaded_image *image;
    if(read_file("\\LINUX\\CMDLINE.TXT", &cmdline, &size)) return;
    u16 *options;
    st->bs->allocate_pool(2, (size + 1) * 2, (void **)&options);
    for(u64 i = 0; i < size; i++) options[i] = cmdline[i] == '\n' ? 0 : cmdline[i];
    options[size] = 0;
    status_t s = st->bs->load_image(0, self, file_path("\\LINUX\\VMLINUZ.EFI"), 0, 0, &h);
    put("V86SB linux ");
    put_hex(s);
    flush();
    if(s) return;
    st->bs->handle_protocol(h, &LOADED_IMAGE, (void **)&image);
    image->options = options;
    image->options_size = (u32)(size + 1) * 2;
    st->bs->start_image(h, 0, 0);
}

API status_t efi_main(handle_t image, system_table *system)
{
    st = system;
    self = image;
    /* (the boot manager's five minutes are not enough for a slow machine) */
    st->bs->set_watchdog(0, 0, 0, 0);
    loaded_image *loaded;
    file_system *volume;
    st->bs->handle_protocol(image, &LOADED_IMAGE, (void **)&loaded);
    st->bs->handle_protocol(loaded->device, &FILE_SYSTEM, (void **)&volume);
    volume->open_volume(volume, &root);

    u8 boot = 0;
    u64 size = 1;
    u32 attributes;
    if(st->rt->get_variable(u"V86SbBoot", &TEST, &attributes, &size, &boot)) boot = 0;
    u8 next = boot + 1;
    st->rt->set_variable(u"V86SbBoot", &TEST, NV | BS | RT, 1, &next);
    put("V86SB boot ");
    put_hex(boot);
    put(" SecureBoot ");
    put_hex(variable_byte(u"SecureBoot", &GLOBAL));
    put(" SetupMode ");
    put_hex(variable_byte(u"SetupMode", &GLOBAL));
    flush();

    if(boot == 0)
    {
        probes();
        update("\\UPDATE\\UNSIGNED.BIN", "db-unsigned", u"db", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH | APPEND);
        update("\\UPDATE\\PKBYKEK.BIN", "PK-signed-by-KEK", u"PK", &GLOBAL, NV | BS | RT | TIME_AUTH);
        update("\\UPDATE\\DBXOTHER.BIN", "dbx-signed-by-other", u"dbx", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH | APPEND);
        flash_write();
        update("\\UPDATE\\DBADD.BIN", "db-append-db2", u"db", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH | APPEND);
        probe("\\PROBE\\DB2.EFI");
        update("\\UPDATE\\DBSET2.BIN", "db-set-t2", u"db", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH);
        update("\\UPDATE\\DBSET2.BIN", "db-set-t2-replayed", u"db", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH);
        update("\\UPDATE\\DBSET1.BIN", "db-set-t1-older", u"db", &SECURITY_DATABASE, NV | BS | RT | TIME_AUTH);
        put("V86SB reset");
        flush();
        st->rt->reset(0, 0, 0, 0);
    }
    probes();
    put("V86SB linux next");
    flush();
    boot_linux();
    put("V86SB end");
    flush();
    return 0;
}
#endif
                                                                                                                                                                          source/v64/tests/uefi/secure_boot.mjs                                                               0000755 0000000 0000000 00000032355 00000000000 015015  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Secure Boot (docs/uefi.md, the plan's F2): the Secure Boot firmware
// (bios/ovmf-secure-code.fd: its variable services in SMM, its store written
// only in SMM) on Q35 with a variable store of test keys (tools/uefi_vars.mjs:
// PK, KEK, db with key DB, dbx with one image's hash), the keys made for the
// test (tests/lib/authenticode.mjs; build/secure-boot-test/keys, never part
// of the repository). An ESP (tests/lib/fat.mjs) holds tests/uefi/sb_app.c
// signed with DB as \EFI\BOOT\BOOTX64.EFI, the probes, the updates and
// Alpine's virt kernel signed with DB. What has to hold:
// - Secure Boot on (User Mode); the app itself verified and run
// - LoadImage: signed with DB passes; unsigned, changed after signing, signed
//   with a key not enrolled, revoked by its hash in dbx, and signed with a
//   key not in db yet are refused (the firmware's log says why)
// - SetVariable: db without a signature, PK signed by KEK (it needs PK), dbx
//   signed by a key not in KEK are refused; db appended with DB2 (signed by
//   KEK) is taken, and DB2's probe then passes; db replaced (time T2), the
//   same update again and an older one (T1) are refused: no replay
// - a direct write to the store's flash outside SMM does nothing
// - after a cold reset: the store as left (DB2 in db, in the flash's bytes
//   too), the probes as before; Linux (signed) boots and sees Secure Boot on
//
// CPU_CORES=2, SHOW_LOGS=1, TEST_RELEASE_BUILD=1. Needs x86_64-w64-mingw32-gcc
// and openssl.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import crypto from "node:crypto";
import { spawnSync } from "node:child_process";
import { make_esp } from "../lib/fat.mjs";
import { test_key, sign_pe, pe_hash, signed_update } from "../lib/authenticode.mjs";
import { prepare as prepare_alpine } from "../lib/alpine_image.mjs";
import {
    write_variables, read_variables, secure_boot_variables, x509_list, signature_list,
    CERT_SHA256, GLOBAL_VARIABLE, IMAGE_SECURITY_DATABASE, SECURE_BOOT_ATTRIBUTES, APPEND,
} from "../../tools/uefi_vars.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const OUT = ROOT + "build/secure-boot-test/";
fs.mkdirSync(OUT, { recursive: true });
const OWNER = "86b00f5e-5b57-4c1a-9e2d-763836534201";

// --- the keys, the images, the updates
const keys = Object.fromEntries(["PK", "KEK", "DB", "DB2", "OTHER"].map(name => [name, test_key(OUT + "keys", name)]));

function compile(output, defines = [])
{
    const result = spawnSync("x86_64-w64-mingw32-gcc", ["-std=gnu11", "-O2", "-ffreestanding", "-fno-builtin", "-fno-tree-loop-distribute-patterns",
        "-fno-stack-protector", "-mno-stack-arg-probe", "-mno-red-zone", "-Wall", "-Werror", "-nostdlib", "-shared", "-Wl,-dll",
        "-Wl,--subsystem,10", "-Wl,--entry,efi_main", "-Wl,--dynamicbase", ...defines, "-o", output, path.join(__dirname, "sb_app.c")], { encoding: "utf8" });
    assert.equal(result.status, 0, result.stderr);
    return new Uint8Array(fs.readFileSync(output));
}
const app = compile(OUT + "app.efi");
const probe = n => compile(OUT + "probe" + n + ".efi", ["-DPROBE=" + n]);
const signed_db = sign_pe(probe(1), keys.DB);
// (changed after signing: a byte of its code, far from the headers)
const changed = signed_db.slice();
changed[0x400 + 0x10] ^= 0xFF;
const revoked = sign_pe(probe(2), keys.DB);

const T1 = new Date(Date.UTC(2026, 0, 1)), T2 = new Date(Date.UTC(2026, 6, 1));
const db_lists = [x509_list(keys.DB.certificate, OWNER), x509_list(keys.DB2.certificate, OWNER)];
const db_both = new Uint8Array(Buffer.concat(db_lists));
const update = (name, guid, attributes, time, data, signer) => signed_update({ name, guid, attributes, time, data, signer });

const prepared = await prepare_alpine("x86_64-virt");
const esp = make_esp({
    "EFI/BOOT/BOOTX64.EFI": sign_pe(app, keys.DB),
    "PROBE/DB.EFI": signed_db,
    "PROBE/UNSIGNED.EFI": probe(1),
    "PROBE/CHANGED.EFI": changed,
    "PROBE/OTHER.EFI": sign_pe(probe(1), keys.OTHER),
    "PROBE/REVOKED.EFI": revoked,
    "PROBE/DB2.EFI": sign_pe(probe(3), keys.DB2),
    "UPDATE/UNSIGNED.BIN": db_lists[1],
    "UPDATE/PKBYKEK.BIN": update("PK", GLOBAL_VARIABLE, SECURE_BOOT_ATTRIBUTES, T1, x509_list(keys.OTHER.certificate, OWNER), keys.KEK),
    "UPDATE/DBXOTHER.BIN": update("dbx", IMAGE_SECURITY_DATABASE, SECURE_BOOT_ATTRIBUTES | APPEND, T1,
        signature_list(CERT_SHA256, [crypto.randomBytes(32)], OWNER), keys.OTHER),
    "UPDATE/DBADD.BIN": update("db", IMAGE_SECURITY_DATABASE, SECURE_BOOT_ATTRIBUTES | APPEND, T1, db_lists[1], keys.KEK),
    "UPDATE/DBSET2.BIN": update("db", IMAGE_SECURITY_DATABASE, SECURE_BOOT_ATTRIBUTES, T2, db_both, keys.KEK),
    "UPDATE/DBSET1.BIN": update("db", IMAGE_SECURITY_DATABASE, SECURE_BOOT_ATTRIBUTES, T1, db_both, keys.KEK),
    "LINUX/VMLINUZ.EFI": sign_pe(new Uint8Array(fs.readFileSync(prepared.kernel)), keys.DB),
    "LINUX/INITRD.IMG": new Uint8Array(fs.readFileSync(prepared.initrd)),
    "LINUX/CMDLINE.TXT": Buffer.from("initrd=\\LINUX\\INITRD.IMG console=ttyS0,115200 loglevel=4 modules=loop,squashfs,sd-mod\n"),
});

// the store: test keys, REVOKED's hash in dbx
const vars = write_variables(new Uint8Array(fs.readFileSync(ROOT + "bios/ovmf-vars.fd")), secure_boot_variables({
    pk: x509_list(keys.PK.certificate, OWNER),
    kek: x509_list(keys.KEK.certificate, OWNER),
    db: db_lists[0],
    dbx: signature_list(CERT_SHA256, [pe_hash(revoked)], OWNER),
}));

const emulator = new V86({
    firmware: {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-secure-code.fd" },
        vars: { buffer: vars.buffer },
        secure_boot: true,
        debug_console: true,
    },
    hda: { buffer: esp.buffer },
    cdrom: { url: prepared.iso },
    memory_size: 768 * 1024 * 1024,
    graphics_adapter: "bochs_vga",
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: "q35",
    acpi: true,
    net_device: { type: "none" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output:\n" + serial.slice(-3000));
    process.exit(1);
}, 900 * 1000);

let serial = "", debug_log = "";
emulator.add_listener("serial0-output-byte", byte => {
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
});
emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });
// (the firmware's log and the serial console, for a failure)
process.on("exit", () => {
    fs.writeFileSync(OUT + "firmware.log", debug_log);
    fs.writeFileSync(OUT + "serial.log", serial);
});
const plain = () => serial.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");
async function until(pattern, what, timeout_ms)
{
    const deadline = Date.now() + timeout_ms;
    while(!pattern.test(plain()))
    {
        assert.ok(Date.now() < deadline, "timed out waiting for " + what + ":\n" + plain().slice(-2500));
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}
/** The app's report: "V86SB key ..." lines from the given point */
const reports = from => plain().slice(from).split("\n").filter(line => line.startsWith("V86SB ")).map(line => line.slice(6).trim());
const status_of = (lines, prefix) =>
{
    const line = lines.find(l => l.startsWith(prefix + " "));
    assert.ok(line, "no report of " + prefix + " in:\n" + lines.join("\n"));
    return BigInt("0x" + line.slice(prefix.length + 1).split(" ")[0]);
};
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}
const SECURITY_VIOLATION = 0x800000000000001An;
const refused = s => s === SECURITY_VIOLATION || s === 0x800000000000000Fn || s === 0x8000000000000002n;
const PROBES = ["DB", "UNSIGNED", "CHANGED", "OTHER", "REVOKED", "DB2"].map(name => "load \\PROBE\\" + name + ".EFI");

console.log("Booting the Secure Boot firmware with test keys (Q35, " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");
let first;
await step("Secure Boot on, User Mode; the signed app runs", async () => {
    await until(/V86SB reset/, "the app's first run", 300000);
    first = reports(0);
    assert.match(first[0], /^boot 0 SecureBoot 1 SetupMode 0$/);
    assert.match(debug_log, /Variable SetupMode is 0\r?\nVariable SecureBoot is 1/);
});

await step("LoadImage: signed with DB passes; unsigned, changed, other key, revoked by dbx, DB2 not yet in db refused", async () => {
    const [db, unsigned, changed, other, revoked, db2] = PROBES.map(p => status_of(first, p));
    assert.equal(db, 0n, "DB");
    for(const [name, status] of Object.entries({ unsigned, changed, other, revoked, db2 })) assert.ok(refused(status), name + ": " + status.toString(16));
    assert.match(debug_log, /DxeImageVerificationLib: Image is not signed and SHA\d+ hash of image is not found in DB\/DBX/);
    assert.match(debug_log, /DxeImageVerificationLib: Image is signed but signature is not allowed by DB and SHA256 hash of image is not found in DB\/DBX/);
    assert.match(debug_log, /DxeImageVerificationLib: Image is signed but SHA256 hash of image is found in DBX/);
});

await step("SetVariable: unsigned db, PK signed by KEK, dbx signed by an unknown key refused", async () => {
    for(const label of ["db-unsigned", "PK-signed-by-KEK", "dbx-signed-by-other"])
    {
        assert.ok(refused(status_of(first, "set " + label)), label);
    }
});

await step("the store's flash outside SMM: a program command does nothing", async () => {
    const [before, after] = first.find(l => l.startsWith("flash ")).split(" ").slice(1);
    assert.equal(after, before);
    assert.equal(before, "aa", "the first variable's header");
    assert.ok(emulator.v86.cpu.firmware.pflash.refused_writes >= 2, "writes refused");
});

await step("db appended with DB2 (signed by KEK): taken, DB2's probe passes; replaced at T2, then that again and T1: refused", async () => {
    assert.equal(status_of(first, "set db-append-db2"), 0n);
    const loads = first.filter(l => l.startsWith("load \\PROBE\\DB2.EFI "));
    assert.equal(loads.length, 2);
    assert.equal(BigInt("0x" + loads[1].split(" ")[2]), 0n, "DB2 after the update");
    assert.equal(status_of(first, "set db-set-t2"), 0n);
    assert.ok(refused(status_of(first, "set db-set-t2-replayed")), "replayed");
    assert.ok(refused(status_of(first, "set db-set-t1-older")), "older");
});

await step("after a cold reset: the store as left (DB2 in db, also in the flash), the probes as before", async () => {
    const from = plain().lastIndexOf("V86SB reset");
    await until(/V86SB linux next/, "the app's second run", 300000);
    const second = reports(from).filter(l => l !== "reset");
    assert.match(second[0], /^boot 1 SecureBoot 1 SetupMode 0$/);
    const [db, unsigned, changed, other, revoked, db2] = PROBES.map(p => status_of(second, p));
    assert.equal(db, 0n);
    assert.equal(db2, 0n, "DB2: in db since the update");
    for(const [name, status] of Object.entries({ unsigned, changed, other, revoked })) assert.ok(refused(status), name);
    // (the bytes of the flash: what the machine writes back)
    const store = new Uint8Array(await new Promise(resolve => emulator.v86.cpu.firmware.pflash.buffer.get(0, vars.length, resolve)));
    const variables = read_variables(store);
    const db_variable = variables.find(v => v.name === "db");
    assert.ok(Buffer.from(db_variable.data).includes(Buffer.from(keys.DB2.certificate)), "DB2's certificate in db");
    assert.deepEqual(variables.filter(v => v.name === "PK").map(v => Buffer.from(v.data).includes(Buffer.from(keys.PK.certificate))), [true], "PK unchanged");
});

await step("Linux, signed with DB, boots and sees Secure Boot on", async () => {
    await until(/V86SB linux 0/, "the kernel loaded", 60000);
    await until(/login: $/, "Linux's login prompt", 600000);
    emulator.serial0_send("root\n");
    await until(/:~# (\x1b\[6n)?$/, "the shell", 60000);
    // (the variable through efivarfs: its attributes, then its byte; the
    // firmware's GetVariable in SMM under Linux)
    serial = "";
    emulator.serial0_send("F=/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c; " +
        "for i in $(seq 20); do [ -e $F ] && break; sleep 1; done; echo BE''GIN; od -An -tu1 $F; echo rc=$?; dmesg | grep -i 'secure boot'; echo EN''D\n");
    await until(/^END$/m, "the command", 60000);
    const output = plain().match(/^BEGIN\n([^]*?)^END$/m)[1];
    if(!/^\s*(\d+\s+){4}1\s*$/m.test(output))
    {
        serial = "";
        emulator.serial0_send("echo BE''GIN; ls -l /sys/firmware/efi/efivars | head; mount | grep efivar; dmesg | grep -i efi; echo EN''D\n");
        await until(/^END$/m, "the diagnostics", 60000);
        assert.fail("the SecureBoot variable: 1\n" + output + "\n" + plain());
    }
    assert.match(output, /Secure boot enabled/i);
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                                                                                                                   source/v64/tests/uefi/shell.mjs                                                                     0000755 0000000 0000000 00000021135 00000000000 013605  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The UEFI firmware (docs/uefi.md, docs/modern-pc-devices-plan.md F1): the
// pinned OVMF (bios/ovmf-code.fd, bios/ovmf-vars.fd) as flash at the top of
// 4 GiB boots to its Shell on the serial port. Its debug log (QEMU's debug
// console at 0x402) shows the fw_cfg contract met: revision 1 without DMA,
// etc/e820, the SMBIOS tables, no ASSERT; its graphics driver (QemuVideoDxe)
// sets a mode on the Bochs VGA (GOP); the variable store is writable CFI
// flash (src/pflash.js). Shell commands see the PCI devices, v86's SMBIOS
// and the memory map, and set a non-volatile variable; "reset" goes through
// the reset vector again, to the Shell, the variable kept; a snapshot taken
// at the Shell goes on after restoring.
//
// MACHINE=i440fx (with qemu_compatible: OVMF's layout), CPU_CORES=2,
// MEMORY_MB=5120 (RAM above 4 GiB: extended RAM, in etc/e820 and SMBIOS),
// SHOW_LOGS=1 (the serial port), TEST_RELEASE_BUILD=1.

import assert from "node:assert/strict";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SHOW_LOGS = +process.env.SHOW_LOGS;
const CPU_CORES = +process.env.CPU_CORES || 1;
const MACHINE = process.env.MACHINE || "q35";
const MEMORY_MB = +process.env.MEMORY_MB || 512;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const emulator = new V86({
    firmware: {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-code.fd" },
        vars: { url: ROOT + "bios/ovmf-vars.fd" },
        debug_console: true,
    },
    // (beyond the 2 GiB heap: extended RAM above 4 GiB, as the VM manager makes it)
    memory_size: Math.min(MEMORY_MB, 2048) * 1024 * 1024,
    extended_memory_size: Math.max(MEMORY_MB - 2048, 0) * 1024 * 1024 || undefined,
    graphics_adapter: "bochs_vga",
    cpu_type: "x86_64",
    cpu_cores: CPU_CORES,
    experimental_smp_jit: CPU_CORES > 1,
    machine_type: MACHINE,
    qemu_compatible: MACHINE === "i440fx",
    acpi: true,
    net_device: { type: "none" },
    autostart: true,
    log_level: 0,
});

const overall_timeout = setTimeout(() => {
    console.log("\nTimeout. Serial output since the last command:\n" + serial + "\nDebug log tail:\n" + debug_log.slice(-3000));
    process.exit(1);
}, 300 * 1000);

let serial = "";
let debug_log = "";
let waiter = null;
emulator.add_listener("serial0-output-byte", byte =>
{
    const chr = String.fromCharCode(byte);
    if(SHOW_LOGS) process.stdout.write(chr);
    serial += chr;
    if(waiter && waiter.pattern.test(plain(serial)))
    {
        const { resolve } = waiter;
        waiter = null;
        resolve(plain(serial));
    }
});
emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });
const sizes = [];
emulator.add_listener("screen-set-size", size => { sizes.push(size); });

/** Serial output without the terminal's escape sequences and carriage returns */
function plain(text)
{
    return text.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");
}

const PROMPT = /Shell> $/;
// a non-volatile variable of a GUID of our own: L"v86"
const VARIABLE = "V86Test -guid 2c94c1ab-37b4-4d11-9a3f-5fd77b0d5e8a";
const SET_VARIABLE = "setvar " + VARIABLE + " -nv -bs -rt =L\"v86\"";
const GET_VARIABLE = "setvar " + VARIABLE;
function wait_serial(pattern, what, timeout_ms)
{
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + plain(serial).slice(-3000))), timeout_ms);
        waiter = { pattern, resolve: text => { clearTimeout(timer); resolve(text); } };
        if(pattern.test(plain(serial)))
        {
            waiter = null;
            clearTimeout(timer);
            resolve(plain(serial));
        }
    });
}
/** Type a Shell command and wait for the next prompt: its output */
async function command(cmd, timeout_ms = 60000)
{
    serial = "";
    // (the terminal reads keys one at a time: give it each)
    for(const chr of cmd + "\r")
    {
        emulator.serial0_send(chr);
        await new Promise(resolve => setTimeout(resolve, 20));
    }
    const output = await wait_serial(PROMPT, JSON.stringify(cmd), timeout_ms);
    return output.slice(output.indexOf(cmd) + cmd.length).replace(PROMPT, "");
}
let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

console.log("Booting OVMF (" + MACHINE + ", " + CPU_CORES + " core" + (CPU_CORES > 1 ? "s" : "") + ")");

await step("the reset vector, SEC, PEI and DXE in place: the Shell on the serial port", async () => {
    await wait_serial(PROMPT, "the Shell", 180000);
    assert.match(plain(serial), /UEFI Interactive Shell v2\.2/);
    assert.match(plain(serial), /UEFI v2\.70 \(EDK II, 0x00010000\)/);
});

await step("the debug log: fw_cfg revision 1 over I/O ports, etc/e820, SMBIOS 2.8, no ASSERT", async () => {
    assert.match(debug_log, /^SecCoreStartupWithStack\(0xFFFCC000, 0x820000\)/);
    assert.match(debug_log, /QemuFwCfgProbe: Supported 1, DMA 0/);
    assert.match(debug_log, /FW CFG Revision: 0x1/);
    assert.match(debug_log, MEMORY_MB === 512 ? /PlatformGetLowMemoryCB: LowMemory=0x20000000/ : /PlatformGetLowMemoryCB: LowMemory=0x/);
    assert.match(debug_log, /DetectSmbiosVersion: SMBIOS version from QEMU: 0x0208/);
    for(const type of [1, 3, 4, 16, 17, 19, 32, 0])
    {
        assert.match(debug_log, new RegExp("SmbiosAdd: Smbios type " + type + " with size"), "SMBIOS type " + type);
    }
    assert.match(debug_log, /S3SaveStateDxe: Skip S3BootScript because ACPI S3 disabled/);
    assert.doesNotMatch(debug_log, /ASSERT /);
});

await step("the variable store: CFI flash, writable; the fault tolerant write on it", async () => {
    assert.match(debug_log, /QemuFlashDetected => FD behaves as FLASH, writable/);
    assert.match(debug_log, /Disabling EMU Variable FVB since flash variables appear to be supported/);
    assert.match(debug_log, /Ftw: FtwWorkSpaceLba - 0x41, WorkBlockSize {2}- 0x1000/);
});

await step("GOP: QemuVideoDxe drives the Bochs VGA and sets a graphics mode", async () => {
    assert.match(debug_log, /QemuVideo: QEMU Standard VGA detected/);
    assert.match(debug_log, /Adding Bochs Internal Mode \d+: 1024x768, 32-bit/);
    assert.doesNotMatch(debug_log, /BochsID mismatch/);
    const graphical = sizes.filter(([width, height, bpp]) => bpp === 32 && width >= 640 && height >= 480);
    assert.ok(graphical.length, "a 32-bit graphics mode among " + JSON.stringify(sizes));
});

await step("Shell commands: pci, smbiosview, memmap; setvar of a non-volatile variable", async () => {
    const pci = await command("pci");
    assert.match(pci, MACHINE === "q35" ? /Vendor 8086 Device 29C0/ : /Vendor 8086 Device 1237/, "the host bridge");
    assert.match(pci, /Vendor 1234 Device 1111/, "the Bochs VGA");
    const system = await command("smbiosview -t 1");
    assert.match(system, /Manufacturer: v86/);
    assert.match(system, MACHINE === "q35" ? /ProductName: v86 PC \(Q35 \+ ICH9\)/ : /ProductName: v86 PC \(i440FX \+ PIIX\)/);
    const processor = await command("smbiosview -t 4");
    assert.match(processor, /GenuineIntel/);
    const memmap = await command("memmap");
    const total = memmap.match(/Total Memory: +([\d,]+) MB/);
    const mb = total && +total[1].replace(/,/g, "");
    assert.ok(mb >= MEMORY_MB - 12 && mb <= MEMORY_MB, "total memory: " + memmap.slice(-400));
    await command(SET_VARIABLE);
    assert.match(await command(GET_VARIABLE), /76 00 38 00 36 00/);
});

await step("reset: through the reset vector to the Shell again, the variable kept", async () => {
    debug_log = "";
    serial = "";
    for(const chr of "reset\r")
    {
        emulator.serial0_send(chr);
        await new Promise(resolve => setTimeout(resolve, 20));
    }
    await wait_serial(/UEFI Interactive Shell v2\.2[^]*Shell> $/, "the Shell after reset", 180000);
    assert.match(debug_log, /SecCoreStartupWithStack/);
    assert.doesNotMatch(debug_log, /ASSERT /);
    assert.match(await command(GET_VARIABLE), /76 00 38 00 36 00/, "the non-volatile variable");
});

await step("a snapshot at the Shell goes on after restoring", async () => {
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    const output = await command("ver");
    assert.match(output, /UEFI Interactive Shell v2\.2/);
});

clearTimeout(overall_timeout);
await emulator.destroy();
console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/uefi/vars.mjs                                                                      0000755 0000000 0000000 00000012577 00000000000 013463  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The UEFI firmware's variable store kept (docs/uefi.md): firmware.vars with
// disk_option "read_write" is written back as a disk is (src/pflash.js, a
// local file here: src/disk_writeback.js). A copy of bios/ovmf-vars.fd: a
// machine sets a non-volatile variable in the Shell and is destroyed; the
// file has the variable and OVMF's boot entries; a second machine of the
// same file reads the variable. Snapshots hold a reference to the store: one
// of the second machine restores, one of the first does not (the store
// has been written since). The same file read only: the changes stay in
// memory, the file as it was.
//
// TEST_RELEASE_BUILD=1, MACHINE=i440fx.

import assert from "node:assert/strict";
import fs from "node:fs";
import url from "node:url";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const MACHINE = process.env.MACHINE || "q35";
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const directory = ROOT + "build/uefi/";
fs.mkdirSync(directory, { recursive: true });
const store = directory + "vars-test.fd";
fs.copyFileSync(ROOT + "bios/ovmf-vars.fd", store);
const template = fs.readFileSync(ROOT + "bios/ovmf-vars.fd");

const VARIABLE = "V86Test -guid 2c94c1ab-37b4-4d11-9a3f-5fd77b0d5e8a";
const PROMPT = /Shell> $/;
const plain = text => text.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");

/** A machine of the store, at its Shell: { emulator, command } */
async function machine(disk_option)
{
    const emulator = new V86({
        firmware: {
            type: "uefi",
            code: { url: ROOT + "bios/ovmf-code.fd" },
            vars: { url: store, disk_option },
        },
        memory_size: 512 * 1024 * 1024,
        graphics_adapter: "bochs_vga",
        cpu_type: "x86_64",
        machine_type: MACHINE,
        qemu_compatible: MACHINE === "i440fx",
        acpi: true,
        net_device: { type: "none" },
        autostart: true,
        log_level: 0,
    });
    let serial = "", waiter = null;
    emulator.add_listener("serial0-output-byte", byte => {
        serial += String.fromCharCode(byte);
        if(waiter && PROMPT.test(plain(serial))) { const resolve = waiter; waiter = null; resolve(plain(serial)); }
    });
    const prompt = (what, timeout_ms) => new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error("timed out waiting for " + what + ":\n" + plain(serial).slice(-2000))), timeout_ms);
        waiter = text => { clearTimeout(timer); resolve(text); };
        if(PROMPT.test(plain(serial))) { waiter = null; clearTimeout(timer); resolve(plain(serial)); }
    });
    await prompt("the Shell", 180000);
    const command = async cmd => {
        serial = "";
        for(const chr of cmd + "\r")
        {
            emulator.serial0_send(chr);
            await new Promise(resolve => setTimeout(resolve, 20));
        }
        const output = await prompt(JSON.stringify(cmd), 60000);
        return output.slice(output.indexOf(cmd) + cmd.length).replace(PROMPT, "");
    };
    return { emulator, command };
}

let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}

/** Whether the store has a UCS-2 name */
const has_name = (bytes, name) => Buffer.from(bytes).includes(Buffer.from(name, "utf16le"));

let first_state;
await step("a machine writes the store: a variable set in the Shell, then destroyed", async () => {
    const { emulator, command } = await machine("read_write");
    await command("setvar " + VARIABLE + " -nv -bs -rt =L\"v86\"");
    assert.match(await command("setvar " + VARIABLE), /76 00 38 00 36 00/);
    first_state = await emulator.save_state();
    await emulator.destroy();
    const bytes = fs.readFileSync(store);
    assert.equal(bytes.length, template.length);
    assert.ok(!bytes.equals(template), "the file written");
    assert.ok(has_name(bytes, "V86Test"), "the variable in the file");
    assert.ok(has_name(bytes, "BootOrder"), "OVMF's boot entries in the file");
});

await step("a second machine of the file: the variable there; its own snapshot restores, the first machine's not", async () => {
    const { emulator, command } = await machine("read_write");
    assert.match(await command("setvar " + VARIABLE), /76 00 38 00 36 00/);
    await command("setvar " + VARIABLE + " =L\"v64\"");
    const state = await emulator.save_state();
    await emulator.restore_state(state);
    assert.match(await command("setvar " + VARIABLE), /76 00 36 00 34 00/);
    await assert.rejects(emulator.restore_state(first_state), /firmware_vars/);
    await emulator.destroy();
});

await step("read only: the changes in memory, the file as it was", async () => {
    const before = fs.readFileSync(store);
    const { emulator, command } = await machine("read_only");
    assert.match(await command("setvar " + VARIABLE), /76 00 36 00 34 00/);
    await command("setvar " + VARIABLE + " =L\"x86\"");
    assert.match(await command("setvar " + VARIABLE), /78 00 38 00 36 00/);
    await emulator.destroy();
    assert.ok(fs.readFileSync(store).equals(before), "the file unchanged");
});

console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                                 source/v64/tests/uefi/vars_app.c                                                                    0000644 0000000 0000000 00000012565 00000000000 013746  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* What tests/uefi/vars_resilience.mjs runs as \EFI\BOOT\BOOTX64.EFI: the
 * variable store under writes, line by line on the console ("V86VARS ...").
 * \MODE.TXT says what to do:
 *   setup G    eight marks (V86Mark0..7, 64 bytes each) and V86Big (4 KiB,
 *              generation G's pattern)
 *   write G    V86Big with generation G's pattern
 *   fill       V86Fxxxx variables of 1 KiB until the store is full
 *   delete     every other V86Fxxxx variable (the even ones)
 *   check      V86Big: which generation it holds (or "bad"); the marks
 *              intact; the V86Fxxxx variables present
 * then "V86VARS done". x86_64-w64-mingw32-gcc with the tables of efi_min.h. */
#include "efi_min.h"

static const guid_t TEST = {0x86B00F5E, 0x5B57, 0x4C1A, {0x9E, 0x2D, 0x76, 0x38, 0x36, 0x53, 0x42, 0x02}};
#define ATTRIBUTES 7 /* non-volatile, boot services, runtime */
#define BIG 4096
#define MARK 64
#define FILL 1024
#define MAX_FILL 512

static system_table *st;
static u16 line[200];
static int at;
static u8 buffer[BIG];

static void put(const char *s) { while(*s && at < 198) line[at++] = (u8)*s++; }
static void put_hex(u64 n)
{
    for(int i = 60; i >= 0; i -= 4)
    {
        if(i > 0 && !(n >> i)) continue;
        line[at++] = "0123456789abcdef"[n >> i & 15];
    }
}
static void flush(void)
{
    line[at++] = '\r';
    line[at++] = '\n';
    line[at] = 0;
    st->out->output(st->out, line);
    at = 0;
}

static u8 pattern(u32 seed, u32 i) { return (u8)(i * 7 + seed * 31); }
static void fill_pattern(u8 *data, u32 size, u32 seed) { for(u32 i = 0; i < size; i++) data[i] = pattern(seed, i); }
static int matches(const u8 *data, u32 size, u32 seed)
{
    for(u32 i = 0; i < size; i++) if(data[i] != pattern(seed, i)) return 0;
    return 1;
}

/* "V86Mark3", "V86F002a" */
static void name(u16 *out, const char *prefix, u32 n, int digits)
{
    while(*prefix) *out++ = (u8)*prefix++;
    for(int i = digits - 1; i >= 0; i--) *out++ = "0123456789abcdef"[n >> (4 * i) & 15];
    *out = 0;
}

static status_t set(const u16 *variable, u32 size, const u8 *data) { return st->rt->set_variable(variable, &TEST, ATTRIBUTES, size, data); }
static status_t get(const u16 *variable, u64 *size)
{
    u32 attributes;
    *size = BIG;
    return st->rt->get_variable(variable, &TEST, &attributes, size, buffer);
}

static void write_big(u32 generation, const char *label)
{
    fill_pattern(buffer, BIG, 1000 + generation);
    put("V86VARS ");
    put(label);
    put(" ");
    put_hex(set(u"V86Big", BIG, buffer));
    flush();
}

static void check(void)
{
    u64 size;
    status_t s = get(u"V86Big", &size);
    put("V86VARS big ");
    put_hex(s);
    put(" ");
    put_hex(size);
    put(" ");
    u32 generation = 0;
    for(u32 g = 1; g < 16 && !s && size == BIG; g++) if(matches(buffer, BIG, 1000 + g)) generation = g;
    if(generation) put_hex(generation);
    else put("bad");
    flush();
    int marks = 0;
    for(u32 i = 0; i < 8; i++)
    {
        u16 n[16];
        name(n, "V86Mark", i, 1);
        marks += !get(n, &size) && size == MARK && matches(buffer, MARK, i);
    }
    put("V86VARS marks ");
    put_hex(marks);
    flush();
    u32 present = 0, bad = 0;
    for(u32 i = 0; i < MAX_FILL; i++)
    {
        u16 n[16];
        name(n, "V86F", i, 4);
        if(get(n, &size)) continue;
        present++;
        bad += size != FILL || !matches(buffer, FILL, 2000 + i);
    }
    put("V86VARS fills ");
    put_hex(present);
    put(" bad ");
    put_hex(bad);
    flush();
}

static u32 read_number(const char *s)
{
    u32 n = 0;
    while(*s == ' ') s++;
    while(*s >= '0' && *s <= '9') n = n * 10 + (u32)(*s++ - '0');
    return n;
}

API status_t efi_main(handle_t image, system_table *system)
{
    st = system;
    st->bs->set_watchdog(0, 0, 0, 0);
    loaded_image *loaded;
    file_system *volume;
    file *root, *f;
    st->bs->handle_protocol(image, &LOADED_IMAGE, (void **)&loaded);
    st->bs->handle_protocol(loaded->device, &FILE_SYSTEM, (void **)&volume);
    volume->open_volume(volume, &root);
    char mode[32] = {0};
    u64 size = sizeof(mode) - 1;
    if(root->open(root, &f, u"\\MODE.TXT", 1, 0) || f->read(f, &size, mode))
    {
        put("V86VARS no mode");
        flush();
        return 0;
    }
    f->close(f);

    if(mode[0] == 's')
    {
        for(u32 i = 0; i < 8; i++)
        {
            u16 n[16];
            u8 data[MARK];
            name(n, "V86Mark", i, 1);
            fill_pattern(data, MARK, i);
            set(n, MARK, data);
        }
        write_big(read_number(mode + 5), "setup");
    }
    else if(mode[0] == 'w')
    {
        write_big(read_number(mode + 5), "write");
    }
    else if(mode[0] == 'f')
    {
        u32 count = 0;
        status_t s = 0;
        for(; count < MAX_FILL; count++)
        {
            u16 n[16];
            name(n, "V86F", count, 4);
            fill_pattern(buffer, FILL, 2000 + count);
            if((s = set(n, FILL, buffer))) break;
        }
        put("V86VARS fill ");
        put_hex(count);
        put(" ");
        put_hex(s);
        flush();
    }
    else if(mode[0] == 'd')
    {
        u32 deleted = 0;
        for(u32 i = 0; i < MAX_FILL; i += 2)
        {
            u16 n[16];
            name(n, "V86F", i, 4);
            if(!get(n, &size)) deleted += !set(n, 0, 0);
        }
        put("V86VARS deleted ");
        put_hex(deleted);
        flush();
    }
    check();
    put("V86VARS done");
    flush();
    return 0;
}
                                                                                                                                           source/v64/tests/uefi/vars_resilience.mjs                                                           0000755 0000000 0000000 00000024602 00000000000 015655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// The UEFI variable store under failure (docs/uefi.md, the plan's F2: store
// exhaustion and consistency across power loss). The firmware's variable
// driver and its fault tolerant writes (edk2's FTW) keep the store
// consistent on real flash; what v86 has to give them is flash that behaves
// as flash (src/pflash.js). tests/uefi/vars_app.c, the ESP's boot loader,
// writes and checks variables (\MODE.TXT says what); between machines the
// store is the flash's bytes.
// - A 4 KiB variable rewritten (generation 1 to 2), the power cut at points
//   through the write (the store as the flash holds it after that many
//   programs and erases): the next boot finds generation 1 or 2, never a
//   mix, the other variables intact.
// - The store filled with 1 KiB variables until the firmware says it is full
//   (EFI_OUT_OF_RESOURCES); half of them deleted; the rewrite then needs the
//   space of the deleted ones (the firmware reclaims it), and the power cut
//   at points through that too.
//
// SECURE_BOOT=1: the Secure Boot firmware (its variable driver and FTW in
// SMM, the store written only in SMM) with a store of test keys, the app
// signed. TEST_RELEASE_BUILD=1. Needs x86_64-w64-mingw32-gcc (and openssl
// with SECURE_BOOT).

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import { spawnSync } from "node:child_process";
import { make_esp } from "../lib/fat.mjs";
import { test_key, sign_pe } from "../lib/authenticode.mjs";
import { write_variables, secure_boot_variables, x509_list, signature_list, CERT_SHA256 } from "../../tools/uefi_vars.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
const SECURE_BOOT = +process.env.SECURE_BOOT;
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");

const OUT = ROOT + "build/vars-resilience-test/";
fs.mkdirSync(OUT, { recursive: true });
const OWNER = "86b00f5e-5b57-4c1a-9e2d-763836534201";

const build = spawnSync("x86_64-w64-mingw32-gcc", ["-std=gnu11", "-O2", "-ffreestanding", "-fno-builtin", "-fno-tree-loop-distribute-patterns",
    "-fno-stack-protector", "-mno-stack-arg-probe", "-mno-red-zone", "-Wall", "-Werror", "-nostdlib", "-shared", "-Wl,-dll",
    "-Wl,--subsystem,10", "-Wl,--entry,efi_main", "-Wl,--dynamicbase", "-o", OUT + "vars.efi", path.join(__dirname, "vars_app.c")], { encoding: "utf8" });
assert.equal(build.status, 0, build.stderr);
let app = new Uint8Array(fs.readFileSync(OUT + "vars.efi"));
let template = new Uint8Array(fs.readFileSync(ROOT + "bios/ovmf-vars.fd"));
if(SECURE_BOOT)
{
    const keys = Object.fromEntries(["PK", "KEK", "DB"].map(name => [name, test_key(ROOT + "build/secure-boot-test/keys", name)]));
    app = sign_pe(app, keys.DB);
    template = write_variables(template, secure_boot_variables({
        pk: x509_list(keys.PK.certificate, OWNER),
        kek: x509_list(keys.KEK.certificate, OWNER),
        db: x509_list(keys.DB.certificate, OWNER),
        dbx: signature_list(CERT_SHA256, [new Uint8Array(32)], OWNER),
    }));
}

/**
 * A machine of the store, the app in a mode, until it is done: its report,
 * the store after, and the store after each of the given numbers of
 * programs and erases (cuts)
 * @param {!Uint8Array} store
 * @param {string} mode
 * @param {!Array<number>=} cuts
 */
async function run(store, mode, cuts = [])
{
    const emulator = new V86({
        firmware: {
            type: "uefi",
            code: { url: ROOT + (SECURE_BOOT ? "bios/ovmf-secure-code.fd" : "bios/ovmf-code.fd") },
            vars: { buffer: store.slice().buffer },
            secure_boot: !!SECURE_BOOT,
            debug_console: true,
        },
        hda: { buffer: make_esp({ "EFI/BOOT/BOOTX64.EFI": app, "MODE.TXT": Buffer.from(mode + "\n") }, 16).buffer },
        memory_size: 512 * 1024 * 1024,
        graphics_adapter: "bochs_vga",
        cpu_type: "x86_64",
        machine_type: "q35",
        acpi: true,
        net_device: { type: "none" },
        autostart: false,
        log_level: 0,
    });
    await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
    let serial = "", debug_log = "";
    emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
    emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });
    // (each program and erase: the store's bytes then, at the cuts)
    const pflash = emulator.v86.cpu.firmware.pflash;
    const bytes = () => read(pflash);
    const store_op = pflash.store.bind(pflash);
    const captured = new Map();
    let operations = 0;
    pflash.store = (offset, data) => {
        store_op(offset, data);
        operations++;
        if(cuts.includes(operations)) captured.set(operations, bytes());
    };
    emulator.run();
    const deadline = Date.now() + 300000;
    while(!/V86VARS done/.test(serial))
    {
        assert.ok(Date.now() < deadline, "the app did not finish (" + mode + "):\n" + serial.slice(-1500));
        await new Promise(resolve => setTimeout(resolve, 50));
    }
    assert.doesNotMatch(debug_log, /ASSERT /, "an assertion in the firmware");
    const report = serial.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "").split("\n")
        .filter(l => l.startsWith("V86VARS ")).map(l => l.slice(8).trim());
    const after = bytes();
    await emulator.destroy();
    return { report, store: after, operations, captured, debug_log };
}
/** @param {!Object} pflash */
function read(pflash)
{
    let result;
    pflash.buffer.get(0, pflash.size, data => { result = data.slice(); });
    return result;
}
/** A report line's words after its key */
const field = (report, key) =>
{
    const line = report.find(l => l.startsWith(key + " "));
    assert.ok(line, "no " + key + " in:\n" + report.join("\n"));
    return line.slice(key.length + 1).split(" ");
};

let passed = 0;
async function step(name, f)
{
    const start = Date.now();
    await f();
    passed++;
    console.log("ok - " + name + " (" + ((Date.now() - start) / 1000).toFixed(1) + " s)");
}
/** Cut points through a write of n operations: the first few, then spread */
const cut_points = n => [...new Set([1, 2, 3, 8, Math.floor(n / 4), Math.floor(n / 2), Math.floor(n * 3 / 4), n - 2, n - 1])].filter(k => k > 0 && k < n);

/**
 * Stores cut short: each boots, V86Big one of the generations whole, the
 * marks and fills as they were; how often each generation was seen
 * @param {!Map<number, !Uint8Array>} captured
 * @param {!Array<string>} generations
 * @param {number} fills
 */
async function check_cuts(captured, generations, fills)
{
    const seen = {};
    for(const [k, store] of captured)
    {
        const { report } = await run(store, "check");
        const [status, , generation] = field(report, "big");
        assert.equal(status, "0", "V86Big after a cut at " + k);
        assert.ok(generations.includes(generation), "V86Big a whole generation after a cut at " + k + ": " + generation);
        assert.deepEqual(field(report, "marks"), ["8"], "the marks after a cut at " + k);
        assert.deepEqual(field(report, "fills"), [fills.toString(16), "bad", "0"], "the fills after a cut at " + k);
        seen[generation] = (seen[generation] || 0) + 1;
    }
    return seen;
}

console.log("The variable store under failure (" + (SECURE_BOOT ? "the Secure Boot firmware, SMM" : "OVMF") + ", Q35)");
let initial, rewrite;
await step("the variables written: eight marks and a 4 KiB variable (generation 1)", async () => {
    initial = await run(template, "setup 1");
    assert.deepEqual(field(initial.report, "setup"), ["0"]);
    assert.deepEqual(field(initial.report, "big"), ["0", "1000", "1"]);
    assert.deepEqual(field(initial.report, "marks"), ["8"]);
});

await step("the power cut through a rewrite (generation 2): each store boots with generation 1 or 2 whole, the marks intact", async () => {
    // (how many programs and erases the rewrite makes, then the cuts through it)
    rewrite = await run(initial.store, "write 2");
    assert.deepEqual(field(rewrite.report, "write"), ["0"]);
    assert.deepEqual(field(rewrite.report, "big"), ["0", "1000", "2"]);
    const cuts = cut_points(rewrite.operations);
    const { captured } = await run(initial.store, "write 2", cuts);
    assert.equal(captured.size, cuts.length);
    const seen = await check_cuts(captured, ["1", "2"], 0);
    console.log("    " + rewrite.operations + " operations; cut at " + cuts.join(", ") + ": generation " + JSON.stringify(seen));
    assert.ok(seen["1"] && seen["2"], "both generations among the cuts");
});

let full, holes;
await step("the store filled until the firmware says it is full; half the fills deleted", async () => {
    full = await run(rewrite.store, "fill");
    const [count, status] = field(full.report, "fill");
    assert.equal(status, "8000000000000009", "EFI_OUT_OF_RESOURCES");
    assert.ok(parseInt(count, 16) > 100, count + " variables of 1 KiB");
    assert.deepEqual(field(full.report, "fills"), [count, "bad", "0"]);
    holes = await run(full.store, "delete");
    const deleted = parseInt(field(holes.report, "deleted")[0], 16);
    assert.equal(deleted, Math.ceil(parseInt(count, 16) / 2));
    assert.deepEqual(field(holes.report, "fills"), [(parseInt(count, 16) - deleted).toString(16), "bad", "0"]);
    assert.deepEqual(field(holes.report, "marks"), ["8"]);
    console.log("    " + parseInt(count, 16) + " fills, " + deleted + " deleted");
});

await step("a rewrite into the reclaimed space, the power cut through it: each store consistent", async () => {
    const remaining = parseInt(field(holes.report, "fills")[0], 16);
    const whole = await run(holes.store, "write 3");
    assert.deepEqual(field(whole.report, "write"), ["0"], "the rewrite after the reclaim");
    assert.deepEqual(field(whole.report, "big"), ["0", "1000", "3"]);
    assert.ok(whole.operations > rewrite.operations * 4, "a reclaim on the way: " + whole.operations + " operations");
    const cuts = cut_points(whole.operations);
    const { captured } = await run(holes.store, "write 3", cuts);
    const seen = await check_cuts(captured, ["2", "3"], remaining);
    console.log("    " + whole.operations + " operations; cut at " + cuts.join(", ") + ": generation " + JSON.stringify(seen));
});

console.log("PASS: " + passed + " steps");
process.exit(0);
                                                                                                                              source/v64/tests/uefi/windows_setup.mjs                                                             0000755 0000000 0000000 00000016253 00000000000 015415  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node

// Windows booted through UEFI (docs/uefi.md, the plan's F1 "Windows UEFI
// 引导"): a Windows 8.1 x64 installer ISO (WIN_ISO, read only: its writes
// stay in memory) on Q35's SATA CD drive. OVMF's boot manager starts the
// CD's \EFI\BOOT\BOOTX64.EFI (from its El Torito EFI image), whose "Press
// any key to boot from CD or DVD" gets Enter; Windows Boot Manager, winload
// and Windows PE start; Setup's first page is on the screen, drawn through
// GOP's frame buffer at 1280x800 (the Bochs VGA): its background colour on
// most of the screen, the dialog's title bar and its Next button. A local
// test: the ISO is not part of the repository (about 90 s to Setup).
//
// SECURE_BOOT=1: the Secure Boot firmware with Microsoft's keys
// (bios/ovmf-secure-code.fd, bios/ovmf-vars-ms.fd: docs/uefi.md): the boot
// manager and winload are verified against db (Windows Production PCA 2011)
// and dbx before they run.
//
// MEMORY_MB=4096: RAM above 4 GiB too (extended RAM; Windows 11's 4 GB).
// WIN_ISO=<path> (default retro-gaming-site/windows8/windows81_full.iso
// beside the checkout), SHOW_SCREEN=<file.png>, TEST_RELEASE_BUILD=1.

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import url from "node:url";
import zlib from "node:zlib";
import { ReadOnlyOverlayDisk } from "../smp/disk_fixture.mjs";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));
const ROOT = __dirname + "../../";
process.on("unhandledRejection", exn => { throw exn; });

const TEST_RELEASE_BUILD = +process.env.TEST_RELEASE_BUILD;
// (beside the main checkout, or beside the checkout of build/<worktree>)
const ISO = path.resolve(process.env.WIN_ISO || ["../", "../../../"].map(up => path.join(ROOT, up, "retro-gaming-site/windows8/windows81_full.iso"))
    .find(candidate => fs.existsSync(candidate)) || "retro-gaming-site/windows8/windows81_full.iso");
if(!fs.existsSync(ISO))
{
    console.log("Skipped: no Windows installer ISO at " + ISO + " (WIN_ISO)");
    process.exit(0);
}
const { V86 } = await import(TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const SECURE_BOOT = +process.env.SECURE_BOOT;
const MEMORY_MB = +process.env.MEMORY_MB || 2048;

const emulator = new V86({
    firmware: SECURE_BOOT ? {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-secure-code.fd" },
        vars: { url: ROOT + "bios/ovmf-vars-ms.fd" },
        secure_boot: true,
        debug_console: true,
    } : {
        type: "uefi",
        code: { url: ROOT + "bios/ovmf-code.fd" },
        vars: { url: ROOT + "bios/ovmf-vars.fd" },
    },
    cdrom: new ReadOnlyOverlayDisk(ISO),
    memory_size: Math.min(MEMORY_MB, 2048) * 1024 * 1024,
    extended_memory_size: Math.max(MEMORY_MB - 2048, 0) * 1024 * 1024 || undefined,
    graphics_adapter: "bochs_vga",
    cpu_type: "x86_64",
    machine_type: "q35",
    acpi: true,
    net_device: { type: "none" },
    autostart: true,
    log_level: 0,
});
await new Promise(resolve => emulator.add_listener("emulator-ready", resolve));
const cpu = emulator.v86.cpu;

let serial = "", debug_log = "";
emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); });
emulator.add_listener("debug-console-output-byte", byte => { debug_log += String.fromCharCode(byte); });
const plain = text => text.replace(/\x1b\[[0-9;=?]*[A-Za-z]/g, "").replace(/\r/g, "");

/** The screen as RGB rows, or null in text mode */
function screen()
{
    const vga = cpu.devices.vga;
    if(!vga || !vga.svga_enabled || vga.svga_bpp !== 32) return null;
    const width = vga.svga_width, height = vga.svga_height;
    const memory = new Uint8Array(cpu.wasm_memory.buffer, cpu.mmio_ram_backing(vga.lfb_region) >>> 0, vga.vga_memory_size);
    const offset = vga.svga_offset * 4;
    const pixel = (x, y) => { const at = offset + (y * width + x) * 4; return [memory[at + 2], memory[at + 1], memory[at]]; };
    return { width, height, pixel };
}

/** Setup's first page: its background on most of the screen, the dialog's title bar, the Next button */
function setup_page(s)
{
    if(!s || s.width !== 1280 || s.height !== 800) return false;
    let background = 0, samples = 0;
    for(let y = 0; y < s.height; y += 8) for(let x = 0; x < s.width; x += 8)
    {
        const [r, g, b] = s.pixel(x, y);
        samples++;
        if(r === 24 && g === 0 && b === 82) background++;
    }
    const [tr, tg, tb] = s.pixel(500, 185);
    const [nr, ng, nb] = s.pixel(899, 602);
    return background / samples > 0.85 && tb > 200 && tr > 140 && tr < tb && nr > 200 && ng > 200 && nb > 200;
}

function save_png(s, file)
{
    const stride = s.width * 3 + 1, raw = Buffer.alloc(stride * s.height);
    for(let y = 0; y < s.height; y++) for(let x = 0; x < s.width; x++) raw.set(s.pixel(x, y), y * stride + 1 + x * 3);
    const crc = data => { let c = 0xFFFFFFFF; for(const byte of data) { c ^= byte; for(let i = 0; i < 8; i++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; } return (c ^ 0xFFFFFFFF) >>> 0; };
    const chunk = (name, data) => { const body = Buffer.concat([Buffer.from(name), data]), b = Buffer.alloc(data.length + 12); b.writeUInt32BE(data.length); body.copy(b, 4); b.writeUInt32BE(crc(body), b.length - 4); return b; };
    const header = Buffer.alloc(13); header.writeUInt32BE(s.width); header.writeUInt32BE(s.height, 4); header[8] = 8; header[9] = 2;
    fs.writeFileSync(file, Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", zlib.deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]));
}

const start = Date.now();
const elapsed = () => ((Date.now() - start) / 1000).toFixed(0) + " s";
const until = async (condition, what, timeout_ms, poll = 1000) =>
{
    while(!condition())
    {
        assert.ok(Date.now() - start < timeout_ms, "timed out waiting for " + what + "; serial:\n" + plain(serial).slice(-1500));
        await new Promise(resolve => setTimeout(resolve, poll));
    }
};

console.log("Booting " + path.basename(ISO) + " through OVMF (Q35, " + MEMORY_MB + " MB" + (SECURE_BOOT ? ", Secure Boot" : "") + ")");
await until(() => /BdsDxe: starting Boot\d+ "UEFI v86 ATAPI CD-ROM"/.test(plain(serial)), "the boot manager starting the CD", 180000, 200);
console.log("ok - the boot manager starts the CD's loader (" + elapsed() + ")");
// "Press any key to boot from CD or DVD": on the graphics console only
for(let i = 0; i < 8; i++)
{
    emulator.keyboard_send_scancodes([0x1C, 0x9C]);
    await new Promise(resolve => setTimeout(resolve, 700));
}
await until(() => setup_page(screen()), "Windows Setup's first page", 900000, 2000);
console.log("ok - Windows Setup's first page at 1280x800 through GOP (" + elapsed() + ")");
assert.doesNotMatch(plain(serial), /failed to start Boot\d+ "UEFI v86 ATAPI CD-ROM"/);
if(SECURE_BOOT)
{
    // (User Mode, Secure Boot on; nothing refused on the way)
    assert.match(debug_log, /Variable SetupMode is 0\r?\nVariable SecureBoot is 1/);
    assert.doesNotMatch(debug_log, /DxeImageVerificationLib: Image is (not signed|signed but)/);
    console.log("ok - with Secure Boot on: Windows' loaders verified against db and dbx");
}
if(process.env.SHOW_SCREEN) save_png(screen(), process.env.SHOW_SCREEN);

await emulator.destroy();
console.log("PASS");
process.exit(0);
                                                                                                                                                                                                                                                                                                                                                     source/v64/tests/wasmgen/builder.rs                                                                 0000644 0000000 0000000 00000015451 00000000000 014471  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use super::{Signature, WasmBuilder, WasmType};
use std::fs;

fn save(builder: &mut WasmBuilder, name: &str) {
    builder.finish();
    fs::create_dir_all("build/ir-wasm").unwrap();
    fs::write(format!("build/ir-wasm/{name}.wasm"), &builder.output).unwrap();
}

#[test]
fn capacity_modules() {
    for n in [127, 128, 255, 256, 1023, 1024] {
        let mut w = WasmBuilder::new();
        let mut ints = Vec::new();
        for i in 0..n {
            w.const_i32(i);
            ints.push(w.set_new_local());
        }
        // Keep all locals live, then read and tee indices across every LEB boundary.
        for (i, local) in ints.iter().enumerate() {
            w.const_i32(i as i32 * 4);
            w.get_local(local);
            w.tee_local(local);
            w.store_aligned_i32(0);
        }
        for local in ints {
            w.free_local(local);
        }
        save(&mut w, &format!("locals-{n}"));
        let mut w = WasmBuilder::new();
        let mut i32s = Vec::new();
        let mut i64s = Vec::new();
        let mut f32s = Vec::new();
        let mut f64s = Vec::new();
        let mut vectors = Vec::new();
        for i in 0..n {
            w.const_i32(i);
            i32s.push(w.set_new_local());
            w.const_i64(i as i64);
            i64s.push(w.set_new_local_i64());
            w.const_i32(0);
            w.instruction_body.extend_from_slice(&[0x2A, 2, 0]);
            f32s.push(w.set_new_local_f32());
            w.const_i32(0);
            w.load_aligned_f64(0);
            f64s.push(w.set_new_local_f64());
            w.simd_zero();
            vectors.push(w.set_new_local_v128());
        }
        for i in 0..n as usize {
            w.const_i32((i * 4) as i32);
            w.get_local(&i32s[i]);
            w.store_aligned_i32(0);
            w.get_local_i64(&i64s[i]);
            w.drop_();
            w.get_local_f32(&f32s[i]);
            w.drop_();
            w.get_local_f64(&f64s[i]);
            w.drop_();
            w.get_local_v128(&vectors[i]);
            w.drop_();
        }
        for local in i32s {
            w.free_local(local);
        }
        for local in i64s {
            w.free_local_i64(local);
        }
        for local in f32s {
            w.free_local_f32(local);
        }
        for local in f64s {
            w.free_local_f64(local);
        }
        for local in vectors {
            w.free_local_v128(local);
        }
        // Reuse by type, without allocating another local.
        let count = w.local_types.len();
        w.const_i64(12);
        let local = w.set_new_local_i64();
        w.free_local_i64(local);
        assert_eq!(count, w.local_types.len());
        save(&mut w, &format!("groups-{n}"));
        let mut w = WasmBuilder::new();
        for i in 0..n {
            let mut k = i;
            let types = [
                WasmType::I32,
                WasmType::I64,
                WasmType::F32,
                WasmType::F64,
                WasmType::V128,
            ];
            let params: Vec<_> = (0..5)
                .map(|_| {
                    let t = types[k as usize % 5];
                    k /= 5;
                    t
                })
                .collect();
            let signature = Signature::new(&params, &[]);
            assert_eq!(w.intern_signature(signature.clone()), i as u32);
            assert_eq!(w.intern_signature(signature), i as u32);
        }
        for i in 0..n {
            w.call_signature(
                &format!("{}-{i}", "h".repeat(130)),
                Signature::new(&[], &[]),
            );
        }
        save(&mut w, &format!("imports-{n}"));
        let mut w = WasmBuilder::new();
        let outer = w.block_void();
        for _ in 0..n {
            w.block_void();
        }
        w.br(outer);
        w.unreachable();
        for _ in 0..=n {
            w.block_end();
        }
        save(&mut w, &format!("depth-{n}"));
    }
}

#[test]
fn fresh_zeroed_locals_do_not_reuse_runtime_values() {
    let mut w = WasmBuilder::new();
    w.const_i32(0x12345678);
    let old = w.set_new_local();
    let old_index = old.0;
    w.free_local(old);
    w.const_i64(-1);
    let old = w.set_new_local_i64();
    let old_i64_index = old.0;
    w.free_local_i64(old);
    w.const_i32(0);
    w.simd_memory(0, 4);
    let old = w.set_new_local_v128();
    let old_v128_index = old.0;
    w.free_local_v128(old);

    let length = w.body_len();
    let ints: Vec<_> = (0..256).map(|_| w.declare_zeroed_local()).collect();
    let wide = w.declare_zeroed_local_i64();
    let vector = w.declare_zeroed_local_v128();
    assert_eq!(length, w.body_len(), "declarations emit no initialization");
    assert!(ints.iter().all(|local| local.0 != old_index));
    assert_ne!(wide.0, old_i64_index);
    assert_ne!(vector.0, old_v128_index);
    assert_eq!(w.declared_local_count(), 261);
    for (index, local) in ints.iter().enumerate() {
        w.const_i32(32 + index as i32 * 4);
        w.get_local(local);
        w.store_aligned_i32(0);
    }
    w.const_i32(1056);
    w.get_local_i64(&wide);
    w.store_aligned_i64(0);
    w.const_i32(1072);
    w.get_local_v128(&vector);
    w.simd_memory(0x0B, 4);
    for local in ints {
        w.free_local(local);
    }
    w.free_local_i64(wide);
    w.free_local_v128(vector);
    save(&mut w, "fresh-zeroed-locals");
}

#[test]
#[should_panic(expected = "signature mismatch")]
fn incompatible_import_is_rejected() {
    let mut w = WasmBuilder::new();
    w.call_signature("helper", Signature::new(&[], &[]));
    w.call_signature("helper", Signature::new(&[WasmType::I32], &[]));
}

#[test]
#[should_panic(expected = "freed twice")]
fn double_free_is_rejected_in_release_too() {
    let mut w = WasmBuilder::new();
    w.const_i32(1);
    let local = w.set_new_local();
    let duplicate = local.unsafe_clone();
    w.free_local(local);
    w.free_local(duplicate);
}

#[test]
#[should_panic(expected = "all locals must be freed")]
fn unfreed_local_is_rejected() {
    let mut w = WasmBuilder::new();
    w.const_i32(1);
    let _local = w.set_new_local();
    w.finish();
}

#[test]
fn vector_wasm_helper_and_multivalue_signature() {
    let mut w = WasmBuilder::new();
    w.const_i32(0);
    w.simd_memory(0, 4);
    w.call_signature(
        "vector_identity",
        Signature::new(&[WasmType::V128], &[WasmType::V128]),
    );
    let vector = w.set_new_local_v128();
    w.const_i32(16);
    w.get_local_v128(&vector);
    w.simd_memory(0x0B, 4);
    w.free_local_v128(vector);
    w.call_signature("pair", Signature::new(&[], &[WasmType::I32, WasmType::I64]));
    let wide = w.set_new_local_i64();
    let narrow = w.set_new_local();
    w.const_i32(32);
    w.get_local(&narrow);
    w.store_aligned_i32(0);
    w.const_i32(40);
    w.get_local_i64(&wide);
    w.store_aligned_i64(0);
    w.free_local(narrow);
    w.free_local_i64(wide);
    save(&mut w, "typed-helpers");
}
                                                                                                                                                                                                                       source/v64/tests/x64/accounting.mjs                                                                 0000644 0000000 0000000 00000005261 00000000000 014320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Instruction accounting under the x64 page tier's P4 switches
// (docs/jit-unification-plan.md P4 acceptance): system_bench.mjs's guests
// (steps, retries, exits, cold code, SYSCALL at CPL 3, lazy FPU faults)
// retire the same instructions, and the mode ledger accounts for all of
// them, with the page tier off (the reference), on, and on with each
// switch of `ARMS`. The x64 page tier counts exactly with x64_block_count=0
// (docs/profiling.md), so these runs set it.
//
//   node tests/x64/accounting.mjs
import assert from "node:assert/strict";
import {run} from "./system_bench.mjs";
import {mode_ledger, mode_ledger_total} from "../../tools/bench/jit_stats.mjs";

const N = 3000;
const GUESTS = ["base", "cpuid", "retry", "iretq", "syscall", "port_in", "fxsave", "cr0_ts", "nm", "popfq_ac", "cold", "sti"];
const ARMS = {
    interpreter: {x64_page: 0},
    page_tier: {},
    heat_batch: {x64_heat_batch: 1},
    miss_run: {x64_miss_run: 1},
    both: {x64_heat_batch: 1, x64_miss_run: 1},
    sti_shadow: {x64_sti_shadow: 1},
    // (the short guests reach a lower count than the default)
    hot_inline: {x64_hot_inline: 1, x64_hot_count: 4096},
    loops: {x64_loops: 1},
    all: {x64_hot_inline: 1, x64_hot_count: 4096, x64_loops: 1, x64_jac_entries: 2048},
};
const results = {};
// (x64_hot_inline: pages recompiled with inline lookups, P4.14)
let hot_recompiles = 0;
for(const guest of GUESTS)
{
    for(const [arm, switches] of Object.entries(ARMS))
    {
        let retired = 0, ledger = null;
        await run(guest, N, {switches: {x64_block_count: 0, mode_ledger: 1, ...switches}, inspect: emulator => {
            const e = emulator.v86.cpu.wm.exports;
            retired = e.core_statistics_get(0, 0);
            ledger = mode_ledger(e);
            hot_recompiles += arm === "hot_inline" ? e.x64_page_stat(33) : 0;
        }});
        assert.equal(mode_ledger_total(ledger), retired, `${guest}/${arm}: the ledger ${JSON.stringify(ledger)} accounts for ${retired}`);
        (results[guest] ??= {})[arm] = retired;
    }
    const reference = results[guest].interpreter;
    for(const [arm, retired] of Object.entries(results[guest]))
        assert.equal(retired, reference, `${guest}: ${arm} retired ${retired}, the interpreter ${reference}`);
}
assert.ok(hot_recompiles >= GUESTS.length / 2, `x64_hot_inline recompiled ${hot_recompiles} hot pages`);
console.log(`PASS: ${GUESTS.length} guests retire as many instructions as the interpreter with the page tier and its ` +
    `P4 switches (${Object.keys(ARMS).slice(1).join(", ")}), the mode ledger accounting for each: ` +
    GUESTS.map(g => `${g} ${results[g].interpreter}`).join(", ") + `; ${hot_recompiles} hot recompiles`);
                                                                                                                                                                                                                                                                                                                                               source/v64/tests/x64/avx.mjs                                                                        0000644 0000000 0000000 00000141436 00000000000 012771  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// AVX in the x64 engine (docs/simd-xsave-plan.md 8, P5): the VEX forms in
// 64-bit mode (XMM8-15 through VEX.R, VEX.B and VEX.vvvv, memory operands
// through VEX.X and VEX.B, RIP-relative ones, the VEX.W1 forms with 64-bit
// general-purpose operands) and in compatibility mode (the 32-bit
// interpreter: XMM0-7 only, VZEROUPPER leaving YMM8-15's upper halves),
// against QEMU and the model of tests/rust/avx_model.mjs. Registers are
// loaded with XRSTOR and stored with XSAVE, which shows the upper halves of
// the YMM registers. Faults: #UD without CR4.OSXSAVE or with XCR0 3, #NM
// with CR0.TS, #GP(0) for a misaligned operand of an aligned move and a
// non-canonical address; CR0.EM does not matter. Interpreted, with the x64
// page tier, and with compatibility-mode code compiled. Both blocks loop so
// that they become hot.
//
// P5 part 1: the data movement and logic forms, VZEROUPPER, VLDMXCSR and
// VSTMXCSR. P8: the gathers (VSIB: index registers 8-15 through VEX.X).
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {fileURLToPath} from "node:url";
import {FORMS, big, execute, le, mask, memory_bytes} from "../rust/avx_model.mjs";

const OUT = 0x300000, CASE = OUT + 0x80, SKIP = OUT + 0x84, COUNTER = OUT + 0x88, MATCH = OUT + 0xC0, FAULTS = OUT + 0x100;
// a case's general-purpose result, its memory destination (48 bytes) and its
// XSAVE area (up to 5120 cases; RESULTS beyond the IDT, the stack and
// 0x3FFEA0, which held a heap allocator's header at power-on with the JIT
// enabled: tests/x64/initial_ram.mjs)
const GPR_OUT = OUT + 0x1000, STORES = OUT + 0x29000, RESULTS = OUT + 0x110000;
// a case's fault record ([vector, RIP] as the fault cases'): none expected
const CASE_FAULTS = OUT + 0x15000;
const SPAN = 48, AREA = 832;
// (compatibility-mode code is compiled only after a while)
const IDT = 0x380000, ROUNDS = 400, COMPAT_ROUNDS = 4000;
const u32 = n => [n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255];
const hex = b => Buffer.from(b).toString("hex");

// 8 register files (XMM0-15, YMM0-15's upper halves, MXCSR) and 1 KiB of memory operands
let seed = 0x13572468;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const AREAS = Array.from({length: 8}, () => {
    const a = new Uint8Array(AREA);
    // (MXCSR: exceptions masked, the floating-point forms run without faults)
    a.set(u32(random() & 0xFFFF | 0x1F80), 24);
    for(let i = 160; i < 416; i++) a[i] = random();
    a[512] = 6;
    for(let i = 576; i < 832; i++) a[i] = random();
    return a;
});
const samples = Uint8Array.from({length: 1024}, () => random());
// (VLDMXCSR's operands: valid values at the last 64 bytes)
for(let i = 960; i < 1024; i += 4) samples.set(u32(random() & 0xFFFF), i);
// (the counts of the shifts by xmm/m128, at COUNTS: below and beyond the
// elements' widths in the low quadword, which alone counts, random bits above
// it; a register count is loaded from there first)
const COUNTS = 512;
[1, 7, 15, 16, 31, 32, 63, 65].forEach((count, k) => samples.set(le(BigInt(count), 8), COUNTS + 16 * k));
const count_shift = f => !f.map && f.kind === "binary" && [0xD1, 0xD2, 0xD3, 0xE1, 0xE2, 0xF1, 0xF2, 0xF3].includes(f.op);
// (the variable shifts' counts, at VCOUNTS: 32 bytes each, quadwords below
// and beyond 64, as dwords those and zeros)
const VCOUNTS = 640;
for(let k = 0; k < 8; k++) for(let e = 0; e < 4; e++) samples.set(le(BigInt((k * 7 + e * 13) % 72), 8), VCOUNTS + 32 * k + 8 * e);
const variable_shift = f => f.map === 2 && f.op >= 0x45 && f.op <= 0x47 && f.kind === "binary";

/** A VEX instruction: fields map, pp, L, W, vvvv (4 bits) and the
 * three-byte prefix; ModRM's reg and r/m register `rm` or memory operand
 * `mem` {base, index, scale, disp}: [base + index << scale + disp32]; imm8.
 * VEX.R, X and B extend registers 8-15. */
function encode({map = 1, pp = 0, l = 0, w = 0, vvvv = 0, three = false}, op, reg, rm, mem, imm8)
{
    let modrm = [], x = 0, b = 0;
    if(mem)
    {
        const {base, index, scale = 0, disp = 0} = mem;
        b = base >> 3;
        if(index !== undefined)
        {
            x = index >> 3;
            modrm = [0x80 | (reg & 7) << 3 | 4, scale << 6 | (index & 7) << 3 | base & 7, ...u32(disp)];
        }
        else if((base & 7) === 4) modrm = [0x80 | (reg & 7) << 3 | 4, 0x24, ...u32(disp)];
        else modrm = [0x80 | (reg & 7) << 3 | base & 7, ...u32(disp)];
    }
    else if(rm !== undefined)
    {
        b = rm >> 3;
        modrm = [0xC0 | (reg & 7) << 3 | rm & 7];
    }
    const r = reg >> 3;
    const tail = [op, ...modrm, ...(imm8 === undefined ? [] : [imm8])];
    const fields = (~vvvv & 15) << 3 | l << 2 | pp;
    if(map === 1 && !w && !three && !x && !b) return [0xC5, (r ? 0 : 0x80) | fields, ...tail];
    return [0xC4, (r ? 0 : 0x80) | (x ? 0 : 0x40) | (b ? 0 : 0x20) | map, w << 7 | fields, ...tail];
}
const GPR64 = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"];
const GPR32 = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"];
// general-purpose operands and address registers (not RAX, RDX: XRSTOR/XSAVE's; not RSP)
const OPERANDS = [[1, 9, 14, 6, 11], [1, 3, 6, 7, 5]];
const STORE_KINDS = ["store", "scalar_st", "store64", "gpr_store", "stmxcsr", "extract", "maskstore", "extract128"];
// the kinds with VEX.vvvv (the immediate shifts: the destination) and with imm8
const VVVV = ["binary", "low", "high", "binary_imm", "insert", "insertps", "blendv", "maskload", "maskstore", "insert128", "gather"];
const has_vvvv = c => VVVV.includes(c.f.kind) || ["scalar", "scalar_st"].includes(c.f.kind) && !c.memory ||
    c.f.kind === "fp" && ["three", "from_gpr"].includes(c.f.operands);
const IMMEDIATE = ["load_imm", "binary_imm", "shift_imm", "extract", "insert", "insertps", "blendv", "pcmpstr", "insert128", "extract128"];
// explicit lengths of VPCMPESTRx: within, beyond, negative, beyond 32 bits (with VEX.W1)
const LENGTHS = [0n, 3n, 8n, 9n, 16n, 17n, -1n, -7n, -16n, 0x7FFFFFFFn, -0x80000000n, 0x100000005n, -0x100000002n, 0x8000000000000000n];

// the cases: {long, f, k (register file), d, v, m, memory {base, index, scale, at}, gpr}
const cases = [];
for(const long of [true, false])
{
    const regs = long ? 16 : 8;
    for(const f of FORMS.filter(f => long || !f.long))
    {
        const count = f.kind.startsWith("zero_") ? 2 : 4;
        for(let i = 0; i < count; i++)
        {
            const n = cases.length;
            const memory = f.memory || !f.register && i >= count / 2;
            // (the registers alias in one case of two)
            const d = (n * 5 + (long ? 3 : 0)) % regs, v = i & 1 ? d : (d + 7) % regs, m = i & 1 ? (v + 1) % regs : d;
            const gprs = OPERANDS[long ? 0 : 1];
            const c = {long, f, k: n % 8, d, v, m: memory ? undefined : m, gpr: gprs[n % 3], n};
            if(count_shift(f) && !memory) c.count_from = COUNTS + 16 * (n % 8);
            if(variable_shift(f) && !memory) c.count_from = VCOUNTS + 32 * (n % 8);
            // (every imm8 over the forms' cases; VPBLENDVB: the mask register in imm8[7:4], imm8[7] ignored in compatibility mode;
            // the shifts by imm8 and VPALIGNR mostly counts below the
            // element's or the operand's size, beyond which the result is 0)
            c.imm8 = f.kind === "blendv" ? (n * 5 + 3) % 16 << 4 | n * 7 & 15 : f.kind === "shift_imm" ? (n * 7 + 1) % 20 :
                f.name === "vpalignr" ? (n * 7 + 3) % 36 : n * 37 + 11 & 255;
            if(f.kind === "gather")
            {
                // (destination, mask and indices distinct, #UD otherwise;
                // each index within 256 bytes either side of `at`, a
                // quadword's high half outside 64-bit mode random: address
                // size 32 ignores it; beyond the elements, random)
                [c.v, c.vsib] = [(d + 3) % regs, (d + 5) % regs];
                const scale = n % 4, elements = (f.l ? 32 : 16) / Math.max(f.data, f.index);
                const low = Math.ceil(-256 / 2 ** scale), high = Math.floor((255 - f.data) / 2 ** scale);
                c.indices = 0n;
                for(let e = 0; e < 32 / f.index; e++)
                {
                    const value = e >= elements ? BigInt(random()) :
                        BigInt(low + random() % (high - low + 1)) + (f.index === 8 && !long && e & 1 ? BigInt(random()) << 32n : 0n);
                    c.indices |= BigInt.asUintN(8 * f.index, value) << BigInt(8 * f.index * e);
                }
                c.memory = {base: gprs[3 + n % 2], scale, at: 256 + n % 8, disp: -0x40 + n};
            }
            else if(memory)
            {
                // [base + index << scale + disp]: the operand at `at` of the samples (or of the case's destination)
                // (a VEX.256 store within its 48 bytes: at 16 at most; the
                // aligned ones' operands 32-byte aligned: a destination at
                // n * 48 + 16 * (n & 1), a sample at 32 * (n & 1))
                const store = STORE_KINDS.includes(f.kind);
                const at = count_shift(f) ? COUNTS + 16 * (n % 8) : variable_shift(f) ? VCOUNTS + 32 * (n % 8) :
                    f.aligned ? (f.l && !store ? 32 : 16) * (n & 1) : f.kind === "ldmxcsr" ? 960 + 4 * (n % 16) :
                    f.l && store ? (n * 7) % 17 : (n * 7) % 33;
                // (VPCMPxSTRx: not RCX, which holds ones before)
                const index = f.kind === "pcmpstr" ? gprs[1] : gprs[(n + 1) % 3];
                c.memory = {base: gprs[3 + n % 2], index: i === count - 1 ? index : undefined, scale: n % 4, at, disp: -0x40 + n};
            }
            cases.push(c);
        }
    }
}
const store_kind = c => STORE_KINDS.includes(c.f.kind);
const code = (c, n) => {
    const lines = [], f = c.f;
    const R = c.long ? GPR64 : GPR32;
    lines.push("mov eax,6", "xor edx,edx", `xrstor [areas + ${c.k * AREA}]`);
    let reg = c.d, rm = c.m, mem;
    if(c.memory)
    {
        const {base, index, scale, at, disp} = c.memory;
        const target = store_kind(c) ? `${STORES + n * SPAN + at}` : `samples + ${at}`;
        // (the index register holds 3)
        lines.push(`lea ${R[base]},[${target} - ${disp} - ${index === undefined ? 0 : 3 << scale}]`);
        if(index !== undefined) lines.push(`mov ${R[index]},3`);
        mem = {base, index, scale, disp};
    }
    switch(f.kind)
    {
        case "to_gpr":
            reg = c.gpr;
            lines.push(`mov ${R[c.gpr]},-1`);
            break;
        case "gpr_load": case "gpr_store":
            if(c.memory) break;
            rm = c.gpr;
            c.value = BigInt(random()) << 32n | BigInt(random());
            lines.push(`mov ${R[c.gpr]},${f.kind === "gpr_load" ? "0x" + (c.long ? c.value : c.value & 0xFFFFFFFFn).toString(16) : -1}`);
            break;
        case "ldmxcsr": case "stmxcsr": reg = f.group; break;
        case "maskmov":
            lines.push(`mov ${c.long ? "rdi" : "edi"},${STORES + n * SPAN + 5}`);
            break;
        case "shift_imm": reg = f.group; break;
        case "extract": case "insert":
            if(c.memory) break;
            rm = c.gpr;
            c.value = BigInt(random()) << 32n | BigInt(random());
            lines.push(`mov ${R[c.gpr]},${f.kind === "insert" ? "0x" + (c.long ? c.value : c.value & 0xFFFFFFFFn).toString(16) : -1}`);
            break;
        case "ptest": case "vtest":
            // (OF, SF, AF set by 0x7F + 1, CF by STC)
            lines.push("mov al,0x7F", "add al,1", "stc");
            break;
        case "fp":
            if(f.operands === "comi") lines.push("mov al,0x7F", "add al,1", "stc");
            else if(f.operands === "to_gpr")
            {
                reg = c.gpr;
                lines.push(`mov ${R[c.gpr]},-1`);
            }
            else if(f.operands === "from_gpr" && !c.memory)
            {
                rm = c.gpr;
                c.value = BigInt(random()) << 32n | BigInt(random());
                lines.push(`mov ${R[c.gpr]},0x${(c.long ? c.value : c.value & 0xFFFFFFFFn).toString(16)}`);
            }
            break;
        case "gather":
            // (the indices: 32 bytes jumped over; ..@ labels keep the
            // block's local labels in scope)
            lines.push(`jmp ..@gather_${n}_load`, `..@gather_${n}: dq ${[0, 1, 2, 3].map(k => "0x" + (c.indices >> BigInt(64 * k) & mask(64)).toString(16)).join(",")}`,
                `..@gather_${n}_load:`, `vmovdqu ymm${c.vsib},[..@gather_${n}]`);
            mem.index = c.vsib;
            break;
        case "pcmpstr":
        {
            const value = x => "0x" + BigInt.asUintN(c.long ? 64 : 32, x).toString(16);
            c.lengths = [LENGTHS[n % LENGTHS.length], LENGTHS[(n * 5 + 2) % LENGTHS.length]];
            lines.push("mov al,0x7F", "add al,1", "stc", `mov ${R[0]},${value(c.lengths[0])}`, `mov ${R[2]},${value(c.lengths[1])}`, `mov ${R[1]},-1`);
            break;
        }
    }
    if(f.kind === "to_gpr" && f.imm) lines.push(`mov ${R[c.gpr]},-1`);
    if(c.count_from !== undefined) lines.push(`vmovdqu ${f.l ? "ymm" : "xmm"}${c.m},[samples + ${c.count_from}]`);
    const vvvv = f.kind === "shift_imm" ? c.d : has_vvvv(c) ? c.v : 0;
    const imm8 = IMMEDIATE.includes(f.kind) || f.imm || f.legacy?.imm8 ? c.imm8 : undefined;
    // (VEX.W where ignored: WIG, WIG32 outside 64-bit mode; VEX.L where
    // ignored, but for the floating-point forms: QEMU 10.2 raises #UD for
    // VSQRTSS with VEX.L1 and stops on VROUNDSS's, an assertion of
    // gen_VROUNDSS; tests/rust/avx.mjs has their VEX.L1 cases)
    const fields = {map: f.map || 1, pp: f.pp, w: f.w === undefined || f.wig32 && !c.long ? n & 1 : f.w,
        l: f.l ?? (f.lig && f.kind !== "fp" ? n >> 1 & 1 : 0), three: !!(n & 2), vvvv};
    // (a fault, unexpected, is recorded and the instruction skipped)
    const instruction = f.kind.startsWith("zero_") ? encode(fields, f.op) : encode(fields, f.op, reg, rm, mem, imm8);
    lines.push(`mov dword [${CASE}],${(CASE_FAULTS - FAULTS) / 16 + n}`, `mov dword [${SKIP}],${instruction.length}`);
    lines.push(`db ${instruction.join(",")}`);
    if(["to_gpr"].includes(f.kind) || ["gpr_store", "extract"].includes(f.kind) && !c.memory || f.operands === "to_gpr")
    {
        lines.push(`mov [${GPR_OUT + n * 16}],${R[c.gpr]}`);
    }
    if(f.kind === "pcmpstr") lines.push(`mov [${GPR_OUT + n * 16}],${R[1]}`);
    // (the flags: OF, SF, ZF, AF, PF, CF)
    if(["ptest", "vtest", "pcmpstr"].includes(f.kind) || f.operands === "comi") lines.push(c.long ? "pushfq\npop rax" : "pushfd\npop eax", "and eax,0x8D5", `mov [${GPR_OUT + n * 16 + 8}],eax`);
    lines.push("mov eax,6", "xor edx,edx", `xsave [${RESULTS + n * AREA}]`);
    return lines.join("\n");
};
const block = long => cases.map((c, n) => c.long === long ? code(c, n) : "").filter(Boolean).join("\n");

// VMOVSS and VMOVSD with VEX.L1 (VEX.LIG): the SDM zeroes bits 255:128 of
// the destination register as with VEX.L0 (the operation is VEX.128's).
// QEMU 10.2 runs them as 256-bit operations: between registers those bits
// come from the first source (VEX.vvvv), VMOVSD from memory keeps them
// (VMOVSS from memory zeroes them). Against QEMU, any of these.
const qemu_lig = (c, n) => c.f.lig && c.f.kind !== "fp" && (n >> 1 & 1) === 1;
// VPCMPESTRx with VEX.W1: QEMU 10.2 takes the lengths from EAX and EDX, as
// for REX.W (tests/x64/sse4.mjs), not from RAX and RDX
const qemu_w1 = c => c.f.kind === "pcmpstr" && c.f.w === 1;
// VRCPPS, VRSQRTPS, VRCPSS, VRSQRTSS: approximations within 1.5 * 2^-12 of
// the exact result (SDM): QEMU's and the model's lanes within 2^-10 of each
// other, the special values (NaN, infinite, zero, denormal) exact. QEMU 10.2
// computes a denormal source's (exact) reciprocal or reciprocal square root,
// 2^63 or more; the SDM takes the source as 0.0 and returns ±∞ (the model's)
const approximate = c => c.f.legacy?.kind === "reciprocal";
const close = (q, m) => {
    for(let i = 0; i < 16; i += 4)
    {
        const [x, y] = [q.readUInt32LE(i), m.readUInt32LE(i)];
        const normal = v => (v >>> 23 & 255) !== 0 && (v >>> 23 & 255) !== 255;
        if(x === y) continue;
        if((y & 0x7FFFFFFF) === 0x7F800000 && !((x ^ y) >>> 31) && normal(x) && (x >>> 23 & 255) >= 127 + 63) continue;
        if(!normal(x) || !normal(y) || (x ^ y) >>> 31) return false;
        const [fx, fy] = [q.readFloatLE(i), m.readFloatLE(i)];
        if(Math.abs(fx - fy) > Math.abs(fy) * 2 ** -10) return false;
    }
    return true;
};
// VPBLENDVB outside 64-bit mode: the mask register is imm8[6:4] (SDM vol. 2A,
// 2.3, the /is4 operand); QEMU 10.2 takes imm8[7:4]
const qemu_is4 = c => c.f.kind === "blendv" && !c.long && c.imm8 & 0x80;
// A gather with quadword indices outside 64-bit mode: address size 32 wraps
// each element's address at 4 GiB, a quadword index's high half ignored;
// QEMU 10.2 adds the indices at 64 bits (and faults)
const qemu_vsib32 = c => c.f.kind === "gather" && !c.long && c.f.index === 8;
// The model: each case's XSAVE area (the registers it can reach), its
// general-purpose result and its memory destination (`qemu`: QEMU's
// deviations for qemu_lig, "kept" or "first source")
const expected_case = (c, n, qemu = undefined) => {
    const area = AREAS[c.k], regs = c.long ? 16 : 8;
    const s = {
        x: Array.from({length: 16}, (_, r) => big(area.subarray(160 + 16 * r, 176 + 16 * r))),
        h: Array.from({length: 16}, (_, r) => big(area.subarray(576 + 16 * r, 592 + 16 * r))),
        mxcsr: area[24] | area[25] << 8,
        // (VPCMPxSTRM leave RCX: ones)
        gpr_out: c.f.kind === "pcmpstr" ? Uint8Array.from({length: 16}, (_, i) => i < (c.long ? 8 : 4) ? 255 : 0) : new Uint8Array(16),
        dest: new Uint8Array(SPAN),
    };
    Object.defineProperty(s, "flags", {set: value => { s.gpr_out.set(u32(value), 8); }});
    const at = c.memory?.at ?? 0;
    s.load = bytes => big(samples.subarray(at, at + bytes));
    s.store = (bytes, v) => s.dest.set(le(v, bytes), at);
    s.load_at = (offset, bytes) => big(samples.subarray(at + offset, at + offset + bytes));
    s.store_at = (offset, bytes, v) => s.dest.set(le(v, bytes), at + offset);
    s.masked = (value, selected) => le(value).forEach((b, i) => { if(selected[i]) s.dest[5 + i] = b; });
    s.gpr = r => {
        const value = c.f.kind === "pcmpstr" ? c.lengths[r === 0 ? 0 : 1] : c.value;
        return BigInt.asUintN(c.long ? 64 : 32, value);
    };
    // (32-bit results zero-extended in 64-bit mode; in compatibility mode a 32-bit store)
    s.set_gpr = (r, value) => s.gpr_out.set(le(value, c.long ? 8 : 4));
    const o = {d: c.d, v: c.f.kind === "shift_imm" ? c.d : c.v, m: c.m, imm8: c.imm8, long: c.long, index: c.vsib, scale: c.memory?.scale};
    if(c.f.kind === "to_gpr" || c.f.operands === "to_gpr") Object.assign(o, {d: c.gpr});
    if(["gpr_load", "gpr_store", "extract", "insert"].includes(c.f.kind) && !c.memory || c.f.operands === "from_gpr" && !c.memory) o.m = c.gpr;
    // (a register count: loaded by VMOVDQU, bits 255:128 zeroed but by a
    // VEX.256 form's)
    if(c.count_from !== undefined) [s.x[c.m], s.h[c.m]] = [big(samples.subarray(c.count_from, c.count_from + 16)),
        c.f.l ? big(samples.subarray(c.count_from + 16, c.count_from + 32)) : 0n];
    // (a gather's indices: loaded by VMOVDQU)
    if(c.vsib !== undefined) [s.x[c.vsib], s.h[c.vsib]] = [c.indices & mask(128), c.indices >> 128n];
    const upper = [...s.h];
    execute(qemu === "W0" ? {...c.f, w: 0} : c.f, s, o);
    if(qemu === "kept") s.h = upper;
    if(qemu === "first source" && !c.memory) s.h[c.f.op === 0x10 ? c.d : c.m] = upper[c.v];
    const out = new Uint8Array(AREA);
    out.set(u32(s.mxcsr), 24);
    out.set(u32(0xFFFF), 28);
    for(let r = 0; r < regs; r++)
    {
        out.set(le(s.x[r]), 160 + 16 * r);
        out.set(le(s.h[r]), 576 + 16 * r);
    }
    return {area: out, gpr: s.gpr_out, dest: s.dest};
};
// (the bytes an XSAVE stores: MXCSR and MXCSR_MASK, the XMM and YMM_Hi128 registers of the mode)
const xsave_bytes = (area, long) => Buffer.concat([area.subarray(24, 32), area.subarray(160, long ? 416 : 288), area.subarray(576, long ? 832 : 704)]);

// the faults: [vector, what, long, setup, instruction, the vector QEMU raises instead]
const VMOVAPS = encode({pp: 0}, 0x28, 1, 2), VZEROUPPER = encode({}, 0x77), VLDMXCSR = "vldmxcsr [samples + 960]";
const FAULT_CASES = [];
for(const long of [true, false])
{
    for(const [what, instruction] of [["vmovaps xmm1,xmm2", `db ${VMOVAPS.join(",")}`], ["vzeroupper", `db ${VZEROUPPER.join(",")}`], ["vldmxcsr", VLDMXCSR],
        ...long ? [["vpxor xmm12,xmm13,xmm9", "vpxor xmm12,xmm13,xmm9"], ["vmovq r10,xmm11", "vmovq r10,xmm11"]] : [["vmovd ecx,xmm3", "vmovd ecx,xmm3"]]])
    {
        FAULT_CASES.push([6, `${what} without CR4.OSXSAVE`, long, "no_osxsave", instruction]);
        FAULT_CASES.push([6, `${what} with XCR0 3`, long, "xcr0_3", instruction]);
        FAULT_CASES.push([7, `${what} with CR0.TS`, long, "ts", instruction]);
        FAULT_CASES.push([6, `${what} with CR0.TS, without CR4.OSXSAVE`, long, "ts no_osxsave", instruction]);
    }
    // (0: no fault. VEX forms ignore CR0.EM, SDM exception type tables; QEMU
    // 10.2 raises #UD, as for legacy SSE)
    FAULT_CASES.push([0, "vmovaps xmm1,xmm2 with CR0.EM", long, "em", `db ${VMOVAPS.join(",")}`, 6]);
    FAULT_CASES.push([13, "vmovaps xmm1,[misaligned]", long, "", "vmovaps xmm1,[samples + 8]"]);
    FAULT_CASES.push([13, "vmovntdq [misaligned],xmm2", long, "", `vmovntdq [${STORES + 4}],xmm2`]);
    FAULT_CASES.push([13, "vmovntdqa xmm3,[misaligned]", long, "", "vmovntdqa xmm3,[samples + 4]"]);
    FAULT_CASES.push([0, "vmovups xmm1,[misaligned]", long, "", "vmovups xmm1,[samples + 8]"]);
    // (VEX.256: the aligned moves need 32-byte alignment; samples and
    // STORES are 32-byte aligned)
    FAULT_CASES.push([13, "vmovaps ymm1,[16-byte aligned]", long, "", "vmovaps ymm1,[samples + 16]"]);
    FAULT_CASES.push([13, "vmovntdq [16-byte aligned],ymm2", long, "", `vmovntdq [${STORES + 16}],ymm2`]);
    FAULT_CASES.push([13, "vmovdqa [16-byte aligned],ymm3", long, "", `vmovdqa [${STORES + 48}],ymm3`]);
    FAULT_CASES.push([0, "vmovdqu ymm1,[misaligned]", long, "", "vmovdqu ymm1,[samples + 8]"]);
    // (QEMU 10.2 does not check MXCSR's reserved bits: no fault, and MXCSR
    // takes the value until the next LDMXCSR)
    FAULT_CASES.push([13, "vldmxcsr with a reserved bit", long, "mxcsr", "vldmxcsr [reserved_mxcsr]", 0]);
    if(long)
    {
        FAULT_CASES.push([13, "vmovups xmm1,[non-canonical]", long, "", "mov rbx,0x0000800000000000\nvmovups xmm1,[rbx]"]);
        // (QEMU 10.2 raises #GP(0) for a non-canonical stack address too: tests/x64/system_oracle.mjs)
        FAULT_CASES.push([12, "vmovdqu [rbp non-canonical],xmm1", long, "", "mov rbp,0x0000800000000000\nvmovdqu [rbp],xmm1", 13]);
        // (a gather: the selected element's address, its first)
        FAULT_CASES.push([13, "vpgatherdd xmm1,[non-canonical]", long, "",
            "mov rbx,0x0000800000000000\nvpcmpeqd xmm3,xmm3,xmm3\nvpxor xmm2,xmm2,xmm2\nvpgatherdd xmm1,[rbx+xmm2*4],xmm3"]);
        FAULT_CASES.push([12, "vpgatherqq ymm1,[rbp non-canonical]", long, "",
            "mov rbp,0x0000800000000000\nvpcmpeqd ymm3,ymm3,ymm3\nvpxor xmm2,xmm2,xmm2\nvpgatherqq ymm1,[rbp+ymm2*8],ymm3", 13]);
    }
}
const SET_CR0 = (bits, long) => long ? `mov rax,cr0\nor eax,${bits}\nmov cr0,rax` : `mov eax,cr0\nor eax,${bits}\nmov cr0,eax`;
const CLEAR_CR0 = long => long ? "mov rax,cr0\nand eax,~12\nmov cr0,rax" : "mov eax,cr0\nand eax,~12\nmov cr0,eax";
const CR4 = (long, or, and = -1) => long ? `mov rax,cr4\nor eax,${or}\nand eax,${and}\nmov cr4,rax` : `mov eax,cr4\nor eax,${or}\nand eax,${and}\nmov cr4,eax`;
const XSETBV = value => `xor ecx,ecx\nmov eax,${value}\nxor edx,edx\nxsetbv`;
const faults = long => FAULT_CASES.map(([, what, in_long, setup, instruction], n) => {
    if(in_long !== long) return "";
    const before = [], after = [];
    if(setup.includes("no_osxsave")) { before.push(CR4(long, 0, ~(1 << 18))); after.push(CR4(long, 1 << 18)); }
    if(setup.includes("xcr0_3")) { before.push(XSETBV(3)); after.push(XSETBV(7)); }
    if(setup.includes("ts")) before.push(SET_CR0(8, long));
    if(setup.includes("em")) before.push(SET_CR0(4, long));
    if(setup.includes("mxcsr")) after.push("ldmxcsr [default_mxcsr]");
    // (setup instructions before the faulting one: its address)
    const lines = instruction.split("\n"), last = lines.pop(), prefix = lines.join("\n");
    return `
${before.join("\n")}
${prefix}
mov dword [${CASE}],${n}
mov dword [${SKIP}],fault_end${n} - fault${n}
fault${n}: ${last}
fault_end${n}:
${CLEAR_CR0(long)}
${after.join("\n")}
mov eax,fault${n}
cmp eax,[${FAULTS + n * 16 + 8}]
sete byte [${MATCH + n}]`;
}).join("\n");

const directory = assemble("avx", long_mode_guest(`
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,7
mov rax,HIGH+nm
call set_gate
mov ebx,12
mov rax,HIGH+stack_fault
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
mov ebx,14
mov rax,HIGH+page_fault
call set_gate
lidt [rel idtr]
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
${XSETBV(7)}
; 64-bit mode
mov dword [${COUNTER}],${ROUNDS}
.rounds:
${block(true)}
dec dword [${COUNTER}]
jnz .rounds
${faults(true)}
; YMM8-15's upper halves through compatibility mode, where VZEROUPPER leaves them
mov eax,6
xor edx,edx
xrstor [areas]
; compatibility mode
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
db ${VZEROUPPER.join(",")}
mov eax,6
xor edx,edx
xsave [${RESULTS - AREA}]
mov dword [${COUNTER}],${COMPAT_ROUNDS}
.rounds:
${block(false)}
dec dword [${COUNTER}]
jnz .rounds
${faults(false)}
jmp 0x18:back
bits 64
back:
mov eax,6
xor edx,edx
xsave [${RESULTS - 2 * AREA}]
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
nm:
mov ecx,7
jmp record
stack_fault:
add rsp,8
mov ecx,12
jmp record
gp:
add rsp,8
mov ecx,13
jmp record
page_fault:
add rsp,8
mov ecx,14
record:
mov edx,[${CASE}]
shl edx,4
mov [${FAULTS} + rdx],ecx
mov rax,[rsp]
mov [${FAULTS} + rdx + 8],rax
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
reserved_mxcsr: dd 0x10000
default_mxcsr: dd 0x1F80
align 64
areas: db ${AREAS.flatMap(a => Array.from(a)).join(",")}
align 32
samples: db ${Array.from(samples).join(",")}
`));

const length = RESULTS - OUT + cases.length * AREA;
assert.ok(cases.length <= 5120 && STORES + cases.length * SPAN <= IDT && GPR_OUT + cases.length * 16 <= CASE_FAULTS && CASE_FAULTS + cases.length * 16 <= STORES);
const check = (result, label) => {
    // the model first: QEMU is a reference, not the specification
    cases.forEach((c, n) => {
        const e = expected_case(c, n, label === "QEMU" && qemu_w1(c) ? "W0" : undefined);
        const what = `${label}: ${c.long ? "64-bit" : "compatibility"} ${c.f.name} (${c.f.op.toString(16)}) case ${n}`;
        if(label === "QEMU" && (qemu_is4(c) || qemu_vsib32(c))) return;
        const area = result.subarray(RESULTS - OUT + n * AREA, RESULTS - OUT + (n + 1) * AREA);
        assert.equal(result.readUInt32LE(CASE_FAULTS - OUT + n * 16), 0, `${what}: no fault`);
        const deviation = label === "QEMU" && qemu_lig(c, n) &&
            ["kept", "first source"].some(qemu => xsave_bytes(area, c.long).equals(xsave_bytes(expected_case(c, n, qemu).area, c.long)));
        if(label === "QEMU" && approximate(c))
        {
            // (the destination within the error, the rest exactly; VEX.256:
            // its upper half in the YMM_Hi128 component too)
            const [q, m] = [Buffer.from(area), Buffer.from(e.area)];
            for(const at of c.f.l ? [160 + 16 * c.d, 576 + 16 * c.d] : [160 + 16 * c.d])
            {
                assert.ok(close(q.subarray(at, at + 16), m.subarray(at, at + 16)), `${what}: an approximation within the error`);
                q.fill(0, at, at + 16);
                m.fill(0, at, at + 16);
            }
            assert.equal(hex(xsave_bytes(q, c.long)), hex(xsave_bytes(m, c.long)), `${what}: registers`);
        }
        else if(!deviation) assert.equal(hex(xsave_bytes(area, c.long)), hex(xsave_bytes(e.area, c.long)), `${what}: registers`);
        assert.equal(hex(result.subarray(GPR_OUT - OUT + n * 16, GPR_OUT - OUT + n * 16 + 16)), hex(e.gpr), `${what}: general-purpose result`);
        assert.equal(hex(result.subarray(STORES - OUT + n * SPAN, STORES - OUT + (n + 1) * SPAN)), hex(e.dest), `${what}: memory`);
    });
    // VZEROUPPER in compatibility mode zeroes YMM0-7's upper halves, and
    // YMM8-15's are kept through the compatibility-mode block (QEMU 10.2
    // zeroes all 16 in every mode: CPU_NB_REGS in gen_VZEROUPPER); VZEROALL
    // there zeroes YMM0-7 and keeps XMM8-15 too (QEMU zeroes all 16)
    const kept = result.subarray(RESULTS - OUT - 2 * AREA, RESULTS - OUT - AREA);
    const zeroed = result.subarray(RESULTS - OUT - AREA, RESULTS - OUT);
    assert.ok(zeroed.subarray(576, 704).every(b => b === 0), `${label}: VZEROUPPER in compatibility mode: YMM0-7 upper halves`);
    assert.equal(hex(kept.subarray(704, 832)), hex(label === "QEMU" ? new Uint8Array(128) : AREAS[0].subarray(704, 832)),
        `${label}: YMM8-15 upper halves kept through compatibility mode`);
    assert.equal(hex(kept.subarray(288, 416)), hex(label === "QEMU" ? new Uint8Array(128) : AREAS[0].subarray(288, 416)),
        `${label}: XMM8-15 kept through compatibility mode (VZEROALL)`);
    FAULT_CASES.forEach(([vector, what, , , , qemu], n) => {
        const deviation = label === "QEMU" && qemu !== undefined;
        assert.equal(result.readUInt32LE(FAULTS - OUT + n * 16), deviation ? qemu : vector, `${label}: ${what}: vector`);
        assert.equal(result[MATCH - OUT + n], (deviation ? qemu : vector) === 0 ? 0 : 1, `${label}: ${what}: RIP`);
    });
};
// v86 against QEMU, but for the fault records, VMOVSS/VMOVSD's upper halves
// and YMM8-15's after compatibility mode, where QEMU deviates
const comparable = buffer => {
    const copy = Buffer.from(buffer);
    cases.forEach((c, n) => {
        // (compatibility mode: XSAVE writes neither XMM8-15 nor YMM8-15's
        // upper halves, which hold what memory held: with the JIT enabled,
        // the power-on heap header at 0x5FFEA8, tests/x64/initial_ram.mjs)
        if(!c.long)
        {
            copy.fill(0, RESULTS - OUT + n * AREA + 288, RESULTS - OUT + n * AREA + 416);
            copy.fill(0, RESULTS - OUT + n * AREA + 704, RESULTS - OUT + (n + 1) * AREA);
        }
        if(qemu_lig(c, n)) copy.fill(0, RESULTS - OUT + n * AREA + 576, RESULTS - OUT + (n + 1) * AREA);
        if(approximate(c))
        {
            copy.fill(0, RESULTS - OUT + n * AREA + 160 + 16 * c.d, RESULTS - OUT + n * AREA + 176 + 16 * c.d);
            if(c.f.l) copy.fill(0, RESULTS - OUT + n * AREA + 576 + 16 * c.d, RESULTS - OUT + n * AREA + 592 + 16 * c.d);
        }
        if(qemu_w1(c) || qemu_is4(c) || qemu_vsib32(c))
        {
            copy.fill(0, RESULTS - OUT + n * AREA, RESULTS - OUT + (n + 1) * AREA);
            copy.fill(0, GPR_OUT - OUT + n * 16, GPR_OUT - OUT + n * 16 + 16);
        }
        // (QEMU's fault there)
        if(qemu_vsib32(c)) copy.fill(0, CASE_FAULTS - OUT + n * 16, CASE_FAULTS - OUT + n * 16 + 16);
    });
    copy.fill(0, RESULTS - OUT - 2 * AREA + 704, RESULTS - OUT - AREA);
    copy.fill(0, RESULTS - OUT - 2 * AREA + 288, RESULTS - OUT - 2 * AREA + 416);
    // (and XMM0-7 and YMM0-7's upper halves there: the last
    // compatibility-mode case's, a gather where QEMU deviates, qemu_vsib32)
    copy.fill(0, RESULTS - OUT - 2 * AREA + 160, RESULTS - OUT - 2 * AREA + 288);
    copy.fill(0, RESULTS - OUT - 2 * AREA + 576, RESULTS - OUT - 2 * AREA + 704);
    // (between the stores and the XSAVE areas: the IDT and the stack, with fault frames)
    copy.fill(0, STORES - OUT + cases.length * SPAN, RESULTS - OUT - 2 * AREA);
    // (XSTATE_BV: XINUSE may be 1 for a component in its initial
    // configuration, SDM vol. 1, 13.6, and QEMU does not track it: after
    // VZEROUPPER, the YMM state is initial for v86)
    for(let n = -2; n < cases.length; n++) copy.fill(0, RESULTS - OUT + n * AREA + 512, RESULTS - OUT + n * AREA + 520);
    FAULT_CASES.forEach(([, , , , , qemu], n) => {
        if(qemu === undefined) return;
        copy.fill(0, FAULTS - OUT + n * 16, FAULTS - OUT + n * 16 + 16);
        copy[MATCH - OUT + n] = 0;
    });
    return copy;
};
const expected = await reference(directory, {length});
// (X64_AVX_LIST=1: list QEMU's differences from the model, for debugging)
if(process.env.X64_AVX_LIST)
{
    cases.forEach((c, n) => {
        const e = expected_case(c, n);
        const area = expected.subarray(RESULTS - OUT + n * AREA, RESULTS - OUT + (n + 1) * AREA);
        const [got, want] = [xsave_bytes(area, c.long), xsave_bytes(e.area, c.long)];
        const registers = [];
        for(let i = 0; i < got.length; i++) if(got[i] !== want[i]) registers.push(i < 8 ? "mxcsr" : i < 8 + (c.long ? 256 : 128) ? "xmm" + (i - 8 >> 4) : "ymmh" + (i - 8 - (c.long ? 256 : 128) >> 4));
        const gpr = !expected.subarray(GPR_OUT - OUT + n * 16, GPR_OUT - OUT + n * 16 + 16).equals(Buffer.from(e.gpr));
        const fault = expected.readUInt32LE(CASE_FAULTS - OUT + n * 16);
        if(fault) registers.push("fault " + fault);
        const memory = !expected.subarray(STORES - OUT + n * SPAN, STORES - OUT + (n + 1) * SPAN).equals(Buffer.from(e.dest));
        if(registers.length || gpr || memory)
        {
            console.log(n, c.long ? "64-bit" : "compat", c.f.name, c.f.kind, c.f.op.toString(16), `d${c.d} v${c.v} m${c.m}`, c.memory ? "memory" : "register",
                `l${c.f.lig ? n >> 1 & 1 : 0} w${c.f.w ?? n & 1}`, [...new Set(registers)].join(" "), gpr ? "gpr" : "", memory ? "memory" : "");
        }
    });
    FAULT_CASES.forEach(([vector, what], n) => {
        const got = expected.readUInt32LE(FAULTS - OUT + n * 16);
        if(got !== vector) console.log("fault", what, "QEMU", got, "SDM", vector);
    });
    process.exit(0);
}
check(expected, "QEMU");
const FEATURES = {cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "AVX2"], cpu_features_unreleased: true};
for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}],
    // (compatibility-mode code in the page tier, docs/jit-unification-plan.md P7.2)
    ["x64 page tier, compat32", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        jit_switches: {x64_page_compat32: 1}}]])
{
    let page = 0, page32 = 0;
    const result = await actual(directory, {length, timeout: 180000, options: {...FEATURES, ...options},
        inspect: emulator => {
            page = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            page32 = emulator.v86.cpu.wm.exports.x64_page_stat(36);
        }});
    check(result, label);
    {
        const [mine, theirs] = [comparable(result), comparable(expected)];
        const at = mine.findIndex((b, i) => b !== theirs[i]);
        assert.ok(at < 0, `${label}: equal to QEMU (but for its documented deviations): first difference at ${(OUT + at).toString(16)}`);
    }
    if(options.disable_jit === false) assert.ok(page > 1000, `${label}: compiled 64-bit code ran (${page})`);
    if(options.jit_switches?.x64_page_compat32) assert.ok(page32 > 0, `${label}: the page tier compiled compatibility-mode code (${page32})`);
    console.log(`PASS (${label}): ${cases.length} AVX cases in 64-bit and compatibility mode, ${FAULT_CASES.length} faults, as QEMU and the model`);
}

// The page tier's templates for the hot VEX forms (P5 part 5; the VEX.256
// moves and VZEROALL, P6 part 3; AVX2's, P7 part 3): a hot loop of
// them over ordinary values (finite, normal, of moderate size: no retries)
// runs with almost no steps (x64_page_stat(4)), as QEMU. (Its stores are off
// the code's page, which they would invalidate.) The results' bits
// of every round are summed (R14, R13): an execution the page tier got wrong
// shows even when the last round ran in the interpreter.
{
    const ITERATIONS = 20000;
    const f64 = x => { const b = Buffer.alloc(8); b.writeDoubleLE(x); return [...b]; };
    const hot_samples = [...f64(1.5), ...f64(-2.25), ...f64(3000), ...f64(0.125), ...f64(-7.75), ...f64(1024),
        ...samples.subarray(0, 64)];
    const hot = assemble("avx-hot", long_mode_guest(`
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
${XSETBV(7)}
mov r15d,${ITERATIONS}
xor r14d,r14d
xor r13d,r13d
.loop:
vmovdqu ymm8,[hot_ymm + 8]
vmovdqa ymm9,[hot_ymm + 32]
vmovups ymm10,ymm8
vmovaps ymm11,ymm9
vmovupd [${OUT + 0x488}],ymm10
vmovapd [${OUT + 0x4C0}],ymm11
vmovntdq [${OUT + 0x4E0}],ymm8
vmovntps [${OUT + 0x500}],ymm9
vmovdqu ymm12,[${OUT + 0x488}]
vmovntpd [${OUT + 0x560}],ymm12
vxorps xmm12,xmm12,xmm9
vmovdqu [${OUT + 0x520}],ymm12
vzeroall
vmovdqu [${OUT + 0x540}],ymm11
add r14,[${OUT + 0x498}]
add r14,[${OUT + 0x4D8}]
add r14,[${OUT + 0x4F0}]
add r14,[${OUT + 0x518}]
add r14,[${OUT + 0x578}]
add r13,[${OUT + 0x520}]
add r13,[${OUT + 0x530}]
add r13,[${OUT + 0x548}]
add r13,[${OUT + 0x558}]
vpbroadcastb ymm8,[hot_ymm + 3]
vpbroadcastd ymm9,[hot_ymm + 12]
vpcmpeqb ymm10,ymm8,[hot_ymm + 32]
vpcmpeqd ymm11,ymm9,ymm10
vpaddb ymm12,ymm10,[hot_ymm]
vpandn ymm12,ymm12,ymm8
vpminub ymm12,ymm12,ymm9
vpcmpgtb ymm13,ymm12,ymm8
vpand ymm13,ymm13,ymm11
vpminud ymm13,ymm13,[hot_ymm + 40]
vpor ymm14,ymm13,ymm10
vpxor ymm14,ymm14,ymm9
vpmovmskb eax,ymm14
add r13,rax
vpmovmskb eax,ymm12
add r13,rax
vpbroadcastd xmm15,[hot_ymm + 8]
vpbroadcastb xmm7,xmm14
vpaddb xmm15,xmm15,xmm7
vmovq rax,xmm15
add r14,rax
vmovsd xmm1,[hot_samples]
vmovsd xmm2,[hot_samples + 8]
vaddsd xmm3,xmm1,xmm2
vmulsd xmm4,xmm3,[hot_samples + 16]
vsubsd xmm5,xmm4,xmm1
vdivsd xmm6,xmm5,xmm2
vmovq rax,xmm6
add r14,rax
vcomisd xmm6,xmm1
setb al
movzx eax,al
add r13,rax
vucomisd xmm1,[hot_samples + 24]
seta al
movzx eax,al
add r13,rax
vcmpsd xmm7,xmm1,xmm6,2
vmovq rax,xmm7
add r14,rax
vcmpltpd xmm7,xmm3,[hot_samples + 32]
vmovq rax,xmm7
add r14,rax
vcvttsd2si eax,xmm6
add r13,rax
vcvttsd2si rax,xmm4
add r13,rax
vcvtsi2sd xmm8,xmm1,r15
vcvtsi2sd xmm9,xmm2,r15d
vcvtsd2ss xmm10,xmm2,xmm6
vcvtss2sd xmm11,xmm3,xmm10
vmovq rax,xmm11
add r14,rax
vmulpd xmm12,xmm1,[hot_samples + 8]
vaddss xmm12,xmm12,[hot_samples + 4]
vmovq rax,xmm12
add r14,rax
vxorpd xmm12,xmm1,xmm2
vandnpd xmm12,xmm12,xmm3
vorpd xmm12,xmm12,[hot_samples + 40]
vandpd xmm12,xmm12,xmm8
vxorps xmm12,xmm12,xmm9
vmovdqu xmm13,[hot_samples + 48]
vpcmpeqb xmm14,xmm13,[hot_samples + 64]
vpcmpgtb xmm15,xmm13,xmm14
vpaddb xmm15,xmm15,xmm13
vpcmpeqd xmm0,xmm15,xmm13
vpxor xmm0,xmm0,xmm15
vpand xmm0,xmm0,xmm12
vpor xmm0,xmm0,xmm9
vpandn xmm0,xmm0,xmm11
vpmovmskb eax,xmm0
add r13,rax
vblendvpd xmm1,xmm12,xmm0,xmm15
vunpcklpd xmm2,xmm1,xmm6
vmovapd [${OUT + 0x400}],xmm2
vmovdqa xmm3,[${OUT + 0x400}]
vmovd eax,xmm3
add r13,rax
vmovq rax,xmm1
add r14,rax
vmovd xmm4,r13d
vmovq xmm5,r14
vpaddb xmm0,xmm0,xmm4
vpaddb xmm0,xmm0,xmm5
vzeroupper
dec r15d
jnz .loop
mov [${OUT + 16}],r14
mov [${OUT + 24}],r13
stmxcsr [${OUT + 32}]
${Array.from({length: 16}, (_, r) => `vmovdqu [${OUT + 48 + 16 * r}],xmm${r}`).join("\n")}
`, `
align 16
hot_samples: db ${hot_samples.join(",")}
align 32
hot_ymm: db ${Array.from(samples.subarray(64, 160)).join(",")}
`));
    // (the guest runner's completion word is at OUT)
    const length = 48 + 256;
    const expected = await reference(hot, {length});
    let steps, retired;
    const result = await actual(hot, {length, timeout: 60000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => {
            steps = emulator.v86.cpu.wm.exports.x64_page_stat(4);
            retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
        }});
    assert.equal(hex(result), hex(expected), "hot loop: the sums, MXCSR and XMM0-15 as QEMU");
    assert.ok(retired > ITERATIONS * 50 && steps < ITERATIONS / 10, `page tier templates: ${retired} retired, ${steps} steps`);
    console.log(`PASS (x64 page tier): the hot VEX forms' templates, as QEMU (${retired} instructions retired natively, ${steps} steps)`);
}

// The parallel build (cores in workers) reaches guest memory through aligned
// atomics: an unaligned read is served from a copy (x64::pages::BOUNCE), made
// by the access cache's inline code or by x64_page_access, of the read's 16
// or 32 bytes. A hot loop of unaligned 128- and 256-bit loads from a page
// without code, which an aligned read puts in the access cache (unaligned
// reads alone leave it out), compiled by the page tier of
// build/v86-parallel.wasm on the bootstrap processor (two cores: the other
// one waits for its SIPI in a vCPU worker), as QEMU (P12: the inline copy
// took 8 bytes of a 32-byte read, and glibc's AVX2 memcpy garbled printf with
// cores in workers).
{
    const ITERATIONS = 20000;
    const data = Array.from({length: 96}, (_, i) => (i * 37 + 11) & 255);
    const unaligned = assemble("avx-parallel-unaligned", long_mode_guest(`
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
${XSETBV(7)}
mov r15d,${ITERATIONS}
xor r14d,r14d
vpxor xmm0,xmm0,xmm0
vpxor xmm2,xmm2,xmm2
.loop:
add r14,[unaligned_data + 64]
vmovdqu ymm1,[unaligned_data + 1]
vpaddb ymm0,ymm0,ymm1
vpaddb ymm0,ymm0,[unaligned_data + 35]
vpcmpeqb ymm3,ymm1,[unaligned_data + 13]
vpsubb ymm0,ymm0,ymm3
vmovdqu xmm4,[unaligned_data + 5]
vpaddb xmm2,xmm2,xmm4
dec r15d
jnz .loop
vmovdqu [${OUT + 16}],ymm0
vmovdqu [${OUT + 48}],xmm2
mov [${OUT + 64}],r14
`, `
align 4096
unaligned_data: db ${data.join(",")}
`));
    const length = 72;
    const expected = await reference(unaligned, {length});
    let retired;
    const result = await actual(unaligned, {length, timeout: 120000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
            cpu_cores: 2, parallel: true, wasm_path: fileURLToPath(new URL("../../build/v86-parallel.wasm", import.meta.url))},
        inspect: emulator => { retired = emulator.v86.cpu.wm.exports.x64_page_stat(1); }});
    assert.equal(hex(result.subarray(16)), hex(expected.subarray(16)), "parallel build: unaligned 128- and 256-bit loads as QEMU");
    assert.ok(retired > ITERATIONS * 5, `parallel build: compiled code ran (${retired} retired)`);
    console.log(`PASS (x64 page tier, parallel build): unaligned VEX.128 and VEX.256 loads in compiled code, as QEMU (${retired} retired natively)`);
}

// The page tier's VEX.256 moves (P6 part 3) check the whole access in
// compiled code: a hot loop's aligned moves and 32-byte stores run without
// faults but in three rounds, a thousand apart: one stores across into an
// absent page (#PF, nothing written), one takes a 16-byte aligned address
// for VMOVAPS ymm, one for VMOVDQA ymm (#GP(0) each). The handlers count the
// faults and skip the 4-byte instruction. (After a retry the runtime
// interprets for a while: single faulting instructions, such as FAULT_CASES,
// and the instructions after one in a round do not run as page-tier code.
// The stores are off the code's page, which they would invalidate.) As QEMU,
// but for the crossing store's low half, which QEMU 10.2 writes (11.1)
{
    const FAULT_ROUNDS = 20000, PATTERN = "0x1122334455667788";
    const fault_loop = assemble("avx-fault-loop", long_mode_guest(`
mov ebx,13
mov rax,HIGH+gp
call set_gate
mov ebx,14
mov rax,HIGH+pf
call set_gate
lidt [rel idtr]
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
${XSETBV(7)}
; (the 2 MiB page at 0x600000 absent)
mov qword [0x202000 + 3 * 8],0
mov rax,cr3
mov cr3,rax
mov rax,${PATTERN}
mov [0x5FFFF0],rax
mov [0x5FFFF8],rax
vmovdqu ymm2,[aligned]
mov r15d,${FAULT_ROUNDS}
xor r14d,r14d
xor r13d,r13d
xor r12d,r12d
.loop:
lea rbx,[aligned]
mov edx,${OUT + 0x800}
mov esi,0x5FFF00
cmp r15d,3001
jne .misaligned_load
mov esi,0x5FFFF0
.misaligned_load:
cmp r15d,2001
jne .misaligned_store
lea rbx,[aligned + 16]
.misaligned_store:
cmp r15d,1001
jne .go
mov edx,${OUT + 0x810}
.go:
vmovaps ymm1,[rbx]
vmovdqa [rdx],ymm2
vmovdqu [rsi],ymm2
add r13,[${OUT + 0x808}]
dec r15d
jnz .loop
mov [${OUT + 16}],r14
mov [${OUT + 24}],r13
mov [${OUT + 32}],r12
mov rax,[0x5FFFF0]
mov [${OUT + 40}],rax
mov rax,[0x5FFFF8]
mov [${OUT + 48}],rax
vmovdqu [${OUT + 64}],ymm1
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
gp:
add rsp,8
inc r14
add qword [rsp],4
iretq
pf:
add rsp,8
inc r12
mov rax,cr2
mov [${OUT + 56}],rax
add qword [rsp],4
iretq
align 8
idtr: dw 511
dq ${IDT}
align 32
aligned: db ${Array.from(samples.subarray(160, 256)).join(",")}
`));
    const length = 96;
    const expected = await reference(fault_loop, {length});
    let retired;
    const result = await actual(fault_loop, {length, timeout: 60000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => { retired = emulator.v86.cpu.wm.exports.x64_page_stat(1); }});
    const pattern = BigInt(PATTERN);
    assert.deepEqual([16, 32, 56].map(at => result.readBigUInt64LE(at)), [2n, 1n, 0x600000n], "#GP twice, #PF once at 0x600000");
    assert.deepEqual([40, 48].map(at => result.readBigUInt64LE(at)), [pattern, pattern], "the crossing store wrote nothing");
    // (QEMU: its low half written)
    for(const b of [result, expected]) b.fill(0, 40, 56);
    assert.equal(hex(result), hex(expected), "the fault counts, CR2, the sums and YMM1 as QEMU");
    assert.ok(retired > FAULT_ROUNDS * 8, `the loop ran as page-tier code (${retired} instructions retired natively)`);
    console.log(`PASS (x64 page tier): VEX.256 alignment and cross-page faults in compiled code, as QEMU (${retired} retired natively)`);
}

// The page tier's conversion and compare templates at the edges of what
// they admit, legacy and VEX forms, as QEMU, in compiled loops whose results'
// bits are summed every round (R14): one of admitted operands only (exact
// results, so no flags: a 53-bit integer, the ends of the integer ranges,
// equal operands of CMP's NLT and NLE), run natively with almost no steps;
// then one loop each for an inexact conversion (PE, set natively) and for
// operands the templates refuse (retried in the interpreter: IE), MXCSR
// reset before each.
{
    const ITERATIONS = 20000;
    const f64 = x => { const b = Buffer.alloc(8); b.writeDoubleLE(x); return [...b]; };
    const edge_samples = [...f64(2147483647), ...f64(-2147483648), ...f64(-(2 ** 63)), ...f64(1.5), ...f64(2 ** -125),
        ...f64(2147483648), ...f64(-2147483649)];
    const loop = (n, body) => `mov r15d,${ITERATIONS}
xor r14d,r14d
ldmxcsr [edge_mxcsr]
.loop${n}:
${body}
dec r15d
jnz .loop${n}
mov [${OUT + 16 + 16 * n}],r14
stmxcsr [${OUT + 24 + 16 * n}]`;
    const sum = (move, register) => `${move} rax,${register}\nadd r14,rax`;
    const loops = [
        // admitted: exact
        [`mov rax,0x10000000000001
vcvtsi2sd xmm1,xmm1,rax
${sum("vmovq", "xmm1")}
mov rax,0x20000000000000
cvtsi2sd xmm2,rax
${sum("movq", "xmm2")}
mov eax,0xFFFFFF
vcvtsi2ss xmm3,xmm3,eax
vmovd eax,xmm3
add r14,rax
${[0, 8].map(at => `vmovsd xmm4,[edge_samples + ${at}]
vcvttsd2si eax,xmm4
add r14,rax
cvtsd2si ebx,xmm4
add r14,rbx`).join("\n")}
vmovsd xmm4,[edge_samples + 16]
vcvttsd2si rax,xmm4
add r14,rax
vmovsd xmm5,[edge_samples + 32]
vcvtsd2ss xmm6,xmm6,xmm5
vmovd eax,xmm6
add r14,rax
vmovsd xmm7,[edge_samples + 24]
vcmpsd xmm8,xmm7,xmm7,5
${sum("vmovq", "xmm8")}
vcmpsd xmm8,xmm7,xmm7,6
${sum("vmovq", "xmm8")}
vcmpps xmm9,xmm7,xmm7,13
${sum("vmovq", "xmm9")}
movapd xmm10,xmm7
cmpsd xmm10,xmm7,5
${sum("movq", "xmm10")}
movapd xmm11,xmm7
cmppd xmm11,xmm7,6
${sum("movq", "xmm11")}`, true],
        // inexact: a 54-bit integer (PE)
        [`mov rax,0x20000000000001
vcvtsi2sd xmm1,xmm1,rax
${sum("vmovq", "xmm1")}`, true],
        // refused: beyond the 32-bit range (IE, the integer indefinite)
        [`vmovsd xmm4,[edge_samples + 40]
vcvttsd2si eax,xmm4
add r14,rax`, false],
        [`vmovsd xmm4,[edge_samples + 48]
cvttsd2si eax,xmm4
add r14,rax`, false],
    ];
    const edges = assemble("avx-edges", long_mode_guest(`
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
${XSETBV(7)}
${loops.map(([body], n) => loop(n, body)).join("\n")}
`, `
align 16
edge_samples: db ${edge_samples.join(",")}
edge_mxcsr: dd 0x1F80
`));
    // (the guest runner's completion word is at OUT)
    const length = 16 + 16 * loops.length;
    const expected = await reference(edges, {length});
    let steps;
    const result = await actual(edges, {length, timeout: 60000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => { steps = emulator.v86.cpu.wm.exports.x64_page_stat(4); }});
    loops.forEach((_, n) => assert.equal(hex(result.subarray(16 + 16 * n, 32 + 16 * n)), hex(expected.subarray(16 + 16 * n, 32 + 16 * n)),
        `edge loop ${n}: the sum and MXCSR as QEMU`));
    // (the refused loops retry: those of the others are few)
    assert.ok(steps < ITERATIONS * 2 + ITERATIONS / 10, `edge loops: ${steps} steps`);
    console.log(`PASS (x64 page tier): conversion and compare templates at the edges, as QEMU (${steps} steps)`);
}
                                                                                                                                                                                                                                  source/v64/tests/x64/bmi.mjs                                                                        0000644 0000000 0000000 00000047004 00000000000 012736  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// BMI1, BMI2, TZCNT, LZCNT and MOVBE in the x64 engine (docs/simd-xsave-plan.md
// 9.2, P10): in 64-bit mode (VEX.W1: 64-bit operands; R8-R15 through VEX.R,
// VEX.B and VEX.vvvv; 32-bit results zero-extended; memory sources) and in
// compatibility mode (32-bit operands, VEX.W ignored), against
// tests/rust/bmi_model.mjs (v86's values for the flags the SDM leaves
// undefined) and QEMU (those flags masked). The flags are set before each
// case; MULX, PDEP, PEXT, RORX and the shifts keep them. Faults: #UD for
// VEX.L1, a prefix before VEX and MOVBE from a register; no AVX state
// requirements. Both blocks loop: interpreted, then with the x64 page tier,
// then also with the page tier in compatibility mode.
// (Compatibility mode's cases include VEX.W1, which is ignored there.)
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {ARITHMETIC, VEX_FORMS, ops, v86_flags} from "../rust/bmi_model.mjs";

const OUT = 0x300000, CASE = OUT + 0x80, SKIP = OUT + 0x84, MATCH = OUT + 0xC0, FAULTS = OUT + 0x100, RESULTS = OUT + 0x1000;
const IDT = 0x380000, ROUNDS = 200, COMPAT_ROUNDS = 2000;
const SLOT = 32;

let seed = 0x13579BDF;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const random64 = () => BigInt(random()) << 32n | BigInt(random());
const EDGES = [0n, 1n, 2n, 0x7FFFFFFFn, 0x80000000n, 0xFFFFFFFFn, 0x100000000n, 0x8000000000000000n, 0xFFFFFFFFFFFFFFFFn,
    0x7FFFFFFFFFFFFFFFn, 0xFFFF0000FFFF0000n, 0x5555555555555555n, 0x0000F0F000000000n, 0xFFFFFFFF00000000n, 0x8000000000000001n];
const value = n => n % 3 === 0 ? EDGES[(n / 3 | 0) % EDGES.length] : random64();
// BEXTR's control and BZHI's index
// (start 64 or 32 with a length: beyond a 64-bit or 32-bit operand)
const CONTROLS = [0x0000n, 0x0804n, 0x2000n, 0x4000n, 0x1F01n, 0x2001n, 0x3F01n, 0x0040n, 0x00FFn, 0xFF00n, 0xFFFFn, 0x10101n, 0x0510n, 0x203Cn, 0xFFFF0303n,
    0x0840n, 0xFF40n, 0x0820n, 0x2020n];
const INDICES = [0n, 1n, 4n, 31n, 32n, 33n, 63n, 64n, 65n, 255n, 0x100n, 0x101Fn, 0xFFFFFF05n, 7n, 0xFFFFFFFFFFFFFF20n];

const R64 = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"];
const R32 = ["eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d"];
const R16 = ["ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w"];
const name_of = (r, bits) => (bits === 64 ? R64 : bits === 32 ? R32 : R16)[r];
// registers for operands: not RSP; R8-R15 in 64-bit mode
const USABLE = long => long ? [0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] : [0, 1, 2, 3, 5, 6, 7];

// The cases: { long, name, bits, roles..., before: register values, flags (0/1), expected }
const VEX = ["andn", "bextr", "blsi", "blsmsk", "blsr", "bzhi", "mulx", "pdep", "pext", "rorx", "sarx", "shlx", "shrx"];
const cases = [];
for(const long of [true, false])
{
    const regs = USABLE(long);
    for(const name of VEX) for(const bits of long ? [32, 64] : [32])
    {
        // (BEXTR and BZHI: each control and index in each size)
        const count = name === "bextr" ? CONTROLS.length : name === "bzhi" ? INDICES.length : 12;
        for(let k = 0; k < count; k++)
        {
            const n = cases.length;
            const memory = k >= count - 4;
            // (destination, vvvv and r/m: distinct, but aliasing in some cases)
            const d = regs[n % regs.length], v = regs[(n + (k % 4 === 0 ? 0 : 5)) % regs.length], m = regs[(n + (k % 4 === 1 ? 0 : 9)) % regs.length];
            const second = name === "bextr" ? CONTROLS[k] : name === "bzhi" ? INDICES[k] :
                ["sarx", "shlx", "shrx"].includes(name) ? BigInt(n * 13 % 140) : value(n + 1);
            // (compatibility mode: some register forms with VEX.W1)
            const w1 = !long && !memory && k % 3 === 2;
            cases.push({long, kind: "vex", name, bits, d, v, m, memory, source: value(n), second, rdx: random64(), imm8: n * 37 % 256, flags: n & 1, w1});
        }
    }
    for(const name of ["tzcnt", "lzcnt"]) for(const bits of long ? [16, 32, 64] : [16, 32])
        for(let k = 0; k < 8; k++)
        {
            const n = cases.length;
            cases.push({long, kind: "count", name, bits, d: regs[n % regs.length], m: regs[(n + 4) % regs.length], memory: k >= 5,
                source: k < 2 ? 0n : value(n), before: random64(), flags: n & 1});
        }
    for(const bits of long ? [16, 32, 64] : [16, 32])
        for(let k = 0; k < 4; k++)
        {
            const n = cases.length;
            cases.push({long, kind: "movbe", name: "movbe", bits, d: regs[n % regs.length], source: value(n), before: random64(), flags: n & 1});
        }
}
const mask = bits => (1n << BigInt(bits)) - 1n;
const hex64 = v => "0x" + BigInt.asUintN(64, v).toString(16);

/** A case's code: the flags first (MOV keeps them), the registers, the
 * instruction; then the slot: two destinations, the flags, memory */
const code = (c, n) => {
    const out = RESULTS + n * SLOT, data = out + 24, reg = r => name_of(r, c.long ? 64 : 32);
    const lines = [c.flags ? "xor eax,eax" : "mov al,0x7F\nadd al,1\nstc"];
    const set = (r, v) => lines.push(`mov ${reg(r)},${hex64(c.long ? v : v & 0xFFFFFFFFn)}`);
    // (a memory source first, through RAX/EAX, which the registers' values follow)
    if(c.memory || c.kind === "movbe") lines.push(`mov ${reg(0)},${hex64(c.long ? c.source : c.source & 0xFFFFFFFFn)}`, `mov [${data}],${reg(0)}`);
    if(c.kind === "vex")
    {
        // every operand register a known value: RDX (MULX), VEX.vvvv, r/m
        for(const r of USABLE(c.long)) set(r, 0x1111111111111111n * BigInt(r + 1));
        set(2, c.rdx);
        if(c.name !== "rorx" && !["blsi", "blsmsk", "blsr"].includes(c.name)) set(c.v, c.second);
        if(!c.memory) set(c.m, c.source);
        const w = c.bits, o = r => name_of(r, w), src = c.memory ? `${w === 64 ? "qword" : "dword"} [${data}]` : o(c.m);
        const text = {
            andn: `andn ${o(c.d)},${o(c.v)},${src}`, bextr: `bextr ${o(c.d)},${src},${o(c.v)}`, bzhi: `bzhi ${o(c.d)},${src},${o(c.v)}`,
            blsi: `blsi ${o(c.v)},${src}`, blsmsk: `blsmsk ${o(c.v)},${src}`, blsr: `blsr ${o(c.v)},${src}`,
            mulx: `mulx ${o(c.d)},${o(c.v)},${src}`, pdep: `pdep ${o(c.d)},${o(c.v)},${src}`, pext: `pext ${o(c.d)},${o(c.v)},${src}`,
            rorx: `rorx ${o(c.d)},${src},${c.imm8}`, sarx: `sarx ${o(c.d)},${src},${o(c.v)}`, shlx: `shlx ${o(c.d)},${src},${o(c.v)}`,
            shrx: `shrx ${o(c.d)},${src},${o(c.v)}`,
        }[c.name];
        if(c.w1)
        {
            // (NASM has no VEX.W1 form of 32-bit registers: the bytes)
            const f = VEX_FORMS.find(f => f.name === c.name), vvvv = c.name === "rorx" ? 0 : c.v;
            const bytes = [0xC4, 0xE0 | f.map, 0x80 | (~vvvv & 15) << 3 | f.pp, f.op, 0xC0 | (f.group ?? c.d) << 3 | c.m, ...c.name === "rorx" ? [c.imm8] : []];
            lines.push(`db ${bytes.join(",")}`);
        }
        else lines.push(text);
        const first = ["blsi", "blsmsk", "blsr"].includes(c.name) ? c.v : c.d;
        lines.push(`mov [${out}],${reg(first)}`);
        if(c.name === "mulx") lines.push(`mov [${out + 8}],${reg(c.v)}`);
    }
    else if(c.kind === "count")
    {
        set(c.d, c.before);
        if(!c.memory && c.m !== c.d) set(c.m, c.source);
        const width = ["", "", "word", "", "dword", "", "", "", "qword"][c.bits / 8];
        lines.push(`${c.name} ${name_of(c.d, c.bits)},${c.memory ? `${width} [${data}]` : name_of(c.m, c.bits)}`, `mov [${out}],${reg(c.d)}`);
    }
    else
    {
        // MOVBE: load into the register, store from it
        set(c.d, c.before);
        const width = ["", "", "word", "", "dword", "", "", "", "qword"][c.bits / 8];
        lines.push(`movbe ${name_of(c.d, c.bits)},${width} [${data}]`, `mov [${out}],${reg(c.d)}`);
        lines.push(`mov qword [${out + 8}],0`.replace("qword", c.long ? "qword" : "dword"), `movbe ${width} [${out + 8}],${name_of(c.d, c.bits)}`);
    }
    lines.push(c.long ? "pushfq\npop rax" : "pushfd\npop eax", "and eax,0x8D5", `mov [${out + 16}],eax`);
    return lines.join("\n");
};
/** The model's slot of a case (v86's undefined flags; `qemu`: those masked) */
const expected = c => {
    const slot = new Uint8Array(SLOT), view = new DataView(slot.buffer);
    const width = c.long ? 64 : 32, full = mask(width);
    const write = (at, v) => { if(c.long) view.setBigUint64(at, BigInt.asUintN(64, v), true); else view.setUint32(at, Number(v & 0xFFFFFFFFn), true); };
    // the register file before the instruction
    const regs = [];
    let flags_before = c.flags ? 0x44 : 0x891, defined = ARITHMETIC, flags;
    if(c.kind === "vex")
    {
        for(const r of USABLE(c.long)) regs[r] = (0x1111111111111111n * BigInt(r + 1)) & full;
        regs[2] = c.rdx & full;
        if(c.name !== "rorx" && !["blsi", "blsmsk", "blsr"].includes(c.name)) regs[c.v] = c.second & full;
        if(!c.memory) regs[c.m] = c.source & full;
        const bits = c.bits, source = (c.memory ? c.source : regs[c.m]) & mask(bits);
        // (32-bit results zero-extended: the low `bits` of the register)
        const set = (r, v) => { regs[r] = v & mask(bits); };
        let r;
        switch(c.name)
        {
            case "andn": case "pdep": case "pext": r = ops[c.name](regs[c.v], source, bits); set(c.d, r.result); break;
            case "bextr": case "bzhi": case "sarx": case "shlx": case "shrx": r = ops[c.name](source, regs[c.v], bits); set(c.d, r.result); break;
            case "blsi": case "blsmsk": case "blsr": r = ops[c.name](source, bits); set(c.v, r.result); break;
            case "mulx": r = ops.mulx(regs[2], source, bits); set(c.v, r.low); set(c.d, r.result); break;
            case "rorx": r = ops.rorx(source, BigInt(c.imm8), bits); set(c.d, r.result); break;
        }
        const first = ["blsi", "blsmsk", "blsr"].includes(c.name) ? c.v : c.d;
        write(0, regs[first]);
        if(c.name === "mulx") write(8, regs[c.v]);
        if(r.flags) { flags = v86_flags(regs[first], bits, r.flags); defined = r.flags.defined; }
        else flags = flags_before;
    }
    else if(c.kind === "count")
    {
        regs[c.d] = c.before & full;
        if(!c.memory && c.m !== c.d) regs[c.m] = c.source & full;
        const source = c.memory ? c.source : regs[c.m];
        const r = ops[c.name](source, c.bits);
        // (16 bits: the rest kept; 32: zero-extended)
        const result = c.bits === 16 ? regs[c.d] & ~0xFFFFn | r.result : r.result;
        write(0, result);
        flags = v86_flags(r.result, c.bits, r.flags);
        defined = r.flags.defined;
    }
    else
    {
        const loaded = ops.movbe(c.source & mask(c.bits), c.bits).result;
        const before = c.before & full;
        const result = c.bits === 16 ? before & ~0xFFFFn | loaded : loaded;
        write(0, result);
        // (the store: the register's bytes reversed again, the source's)
        view.setBigUint64(8, c.source & mask(c.bits), true);
        if(!c.long) view.setUint32(12, 0, true);
        flags = flags_before;
    }
    view.setUint32(16, flags, true);
    return {slot, defined};
};

const block = long => cases.map((c, n) => c.long === long ? code(c, n) : "").filter(Boolean).join("\n");
// faults: [vector, what, long, code, QEMU's vector where it deviates]
const FAULT_CASES = [];
for(const long of [true, false])
{
    FAULT_CASES.push([6, "andn with VEX.L1", long, "db 0xC4, 0xE2, 0x64, 0xF2, 0xCA"]);
    FAULT_CASES.push([6, "66 andn", long, "db 0x66, 0xC4, 0xE2, 0x60, 0xF2, 0xCA"]);
    FAULT_CASES.push([6, "movbe from a register", long, "db 0x0F, 0x38, 0xF0, 0xC1"]);
    // (VEX.vvvv must be 1111b where no operand, SDM vol. 2A 2.3.6; QEMU 10.2
    // does not check)
    FAULT_CASES.push([6, "rorx with VEX.vvvv 2", long, "db 0xC4, 0xE3, 0x6B, 0xF0, 0xCA, 0x03", 0]);
    // (no AVX state requirements: CR4.OSXSAVE is clear here, and CR0.TS set)
    FAULT_CASES.push([0, "andn without CR4.OSXSAVE, with CR0.TS", long, long ? "mov rax,cr0\nbts rax,3\nmov cr0,rax\nandn ecx,ebx,edx" : "mov eax,cr0\nbts eax,3\nmov cr0,eax\nandn ecx,ebx,edx"]);
}
const faults = long => FAULT_CASES.map(([, , in_long, instruction], n) => {
    if(in_long !== long) return "";
    const lines = instruction.split("\n"), last = lines.pop();
    return `
${lines.join("\n")}
mov dword [${CASE}],${n}
mov dword [${SKIP}],fault_end${n} - fault${n}
fault${n}: ${last}
fault_end${n}:
clts
mov eax,fault${n}
cmp eax,[${FAULTS + n * 16 + 8}]
sete byte [${MATCH + n}]`;
}).join("\n");

const directory = assemble("bmi", long_mode_guest(`
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
lidt [rel idtr]
mov dword [${OUT + 0x88}],${ROUNDS}
.rounds:
${block(true)}
dec dword [${OUT + 0x88}]
jnz .rounds
${faults(true)}
; compatibility mode
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov dword [${OUT + 0x88}],${COMPAT_ROUNDS}
.rounds:
${block(false)}
dec dword [${OUT + 0x88}]
jnz .rounds
${faults(false)}
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
gp:
add rsp,8
mov ecx,13
record:
mov edx,[${CASE}]
shl edx,4
mov [${FAULTS} + rdx],ecx
mov rax,[rsp]
mov [${FAULTS} + rdx + 8],rax
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
`));

const length = RESULTS - OUT + cases.length * SLOT;
const check = (result, label) => {
    cases.forEach((c, n) => {
        const {slot, defined} = expected(c);
        const got = result.subarray(RESULTS - OUT + n * SLOT, RESULTS - OUT + (n + 1) * SLOT);
        const what = `${label}: ${c.long ? "64-bit" : "compatibility"} ${c.name} (${c.bits}) case ${n}${c.memory ? " memory" : ""}`;
        assert.equal(Buffer.from(got.subarray(0, 16)).toString("hex"), Buffer.from(slot.subarray(0, 16)).toString("hex"), `${what}: destinations`);
        const flags = new DataView(got.buffer, got.byteOffset).getUint32(16, true), want = new DataView(slot.buffer).getUint32(16, true);
        // (QEMU: the flags the SDM defines; v86: those and its values for the rest)
        const compared = label === "QEMU" ? defined : ARITHMETIC;
        assert.equal(flags & compared, want & compared, `${what}: flags ${flags.toString(16)}, expected ${want.toString(16)} (compared ${compared.toString(16)})`);
    });
    FAULT_CASES.forEach(([vector, what, , , qemu], n) => {
        const want = label === "QEMU" && qemu !== undefined ? qemu : vector;
        assert.equal(result.readUInt32LE(FAULTS - OUT + n * 16), want, `${label}: ${what}: vector`);
        assert.equal(result[MATCH - OUT + n], want === 0 ? 0 : 1, `${label}: ${what}: RIP`);
    });
};
const expected_qemu = await reference(directory, {length});
check(expected_qemu, "QEMU");
const FEATURES = {cpu_type: "x86_64", cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "BMI1", "BMI2", "LZCNT", "MOVBE"], cpu_features_unreleased: true};
for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}],
    // (compatibility-mode code in the page tier, docs/jit-unification-plan.md P7.2)
    ["x64 page tier, compat32", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        jit_switches: {x64_page_compat32: 1}}]])
{
    let page = 0, page32 = 0;
    const result = await actual(directory, {length, timeout: 180000, options: {...FEATURES, ...options},
        inspect: emulator => {
            page = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            page32 = emulator.v86.cpu.wm.exports.x64_page_stat(36);
        }});
    check(result, label);
    if(options.disable_jit === false) assert.ok(page > 1000, `${label}: compiled 64-bit code ran (${page})`);
    if(options.jit_switches?.x64_page_compat32) assert.ok(page32 > 0, `${label}: the page tier compiled compatibility-mode code (${page32})`);
    console.log(`PASS (${label}): ${cases.length} BMI1/BMI2/TZCNT/LZCNT/MOVBE cases in 64-bit and compatibility mode, ${FAULT_CASES.length} faults, as the model and QEMU`);
}

// The page tier's templates for the hot BMI forms (P10 part 2, plan 5.1):
// a hot loop of TZCNT and LZCNT, SHRX/SARX/SHLX, BLSMSK, BLSR, BLSI, BZHI
// and ANDN on 32- and 64-bit operands and MOVBE loads and stores runs with
// almost no steps (x64_page_stat(4)), as QEMU. Every round adds the results
// to R14 and, right after each instruction, the flags the SDM defines for
// it to R13 (the shifts keep STC's CF): an execution the page tier got
// wrong shows even when the last round ran in the interpreter. Three calls
// end in a BMI instruction, so their flags stay in the lazy record until
// the caller reads them. (The stores are off the code's page.) CRC32 from
// memory (F2 0F 38 F0/F1, SSE4.2) sits beside MOVBE's rows.
{
    const ITERATIONS = 20000;
    const fold = mask => `pushfq\npop rdx\nand edx,${mask}\nadd r13,rdx`;
    // (CF ZF; CF ZF SF OF; CF)
    const COUNT = 0x41, LOGIC = 0x8C1, CARRY = 0x1;
    const hot = assemble("bmi-hot", long_mode_guest(`
jmp .start
.tz:
tzcnt eax,esi
ret
.bi:
blsi rax,rbx
ret
.bz:
bzhi eax,edi,ecx
ret
.start:
mov r15d,${ITERATIONS}
xor r14d,r14d
xor r13d,r13d
.loop:
imul rdi,r15,0x9E3779B1
mov rbx,rdi
shl rbx,13
xor rbx,rdi
mov ecx,r15d
and ecx,0x3F
mov esi,r15d
and esi,0xFF
mov [${OUT + 0x400}],rdi
mov [${OUT + 0x408}],rbx
tzcnt eax,edi
${fold(COUNT)}
add r14,rax
tzcnt rax,rbx
${fold(COUNT)}
add r14,rax
lzcnt eax,ecx
${fold(COUNT)}
add r14,rax
lzcnt rax,rdi
${fold(COUNT)}
add r14,rax
tzcnt eax,esi
${fold(COUNT)}
add r14,rax
lzcnt rax,rsi
${fold(COUNT)}
add r14,rax
stc
shrx eax,edi,ecx
${fold(CARRY)}
add r14,rax
sarx rax,rdi,rcx
add r14,rax
shlx eax,ebx,ecx
add r14,rax
shlx rax,[${OUT + 0x408}],rcx
add r14,rax
blsmsk eax,edi
${fold(LOGIC)}
add r14,rax
blsmsk rax,rsi
${fold(LOGIC)}
add r14,rax
blsr rax,rdi
${fold(LOGIC)}
add r14,rax
blsr eax,esi
${fold(LOGIC)}
add r14,rax
blsi rax,rbx
${fold(LOGIC)}
add r14,rax
bzhi eax,edi,ecx
${fold(LOGIC)}
add r14,rax
bzhi rax,rbx,rcx
${fold(LOGIC)}
add r14,rax
andn eax,edi,ebx
${fold(LOGIC)}
add r14,rax
andn rax,rbx,[${OUT + 0x400}]
${fold(LOGIC)}
add r14,rax
call .tz
${fold(COUNT)}
add r14,rax
call .bi
${fold(LOGIC)}
add r14,rax
call .bz
${fold(LOGIC)}
add r14,rax
movbe eax,[${OUT + 0x400}]
add r14,rax
movbe rax,[${OUT + 0x408}]
add r14,rax
movbe [${OUT + 0x410}],edi
movbe [${OUT + 0x418}],rbx
add r14,[${OUT + 0x410}]
add r14,[${OUT + 0x418}]
crc32 eax,byte [${OUT + 0x401}]
crc32 eax,dword [${OUT + 0x404}]
crc32 rax,qword [${OUT + 0x408}]
add r14,rax
dec r15d
jnz .loop
mov [${OUT + 16}],r14
mov [${OUT + 24}],r13
`));
    const length = 32;
    const expected = await reference(hot, {length});
    let steps, retired;
    const result = await actual(hot, {length, timeout: 60000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => {
            steps = emulator.v86.cpu.wm.exports.x64_page_stat(4);
            retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
        }});
    assert.equal(Buffer.from(result.subarray(16, 32)).toString("hex"), Buffer.from(expected.subarray(16, 32)).toString("hex"), "hot loop: the sums as QEMU");
    // (CRC32 has no page-tier template: three steps a round)
    assert.ok(retired > ITERATIONS * 50 && steps < ITERATIONS * 3 + ITERATIONS / 10, `page tier templates: ${retired} retired, ${steps} steps`);
    console.log(`PASS (x64 page tier): the hot BMI forms' templates, as QEMU (${retired} instructions retired natively, ${steps} steps)`);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/x64/cache_oracle.mjs                                                               0000644 0000000 0000000 00000003156 00000000000 014557  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
const source = long_mode_guest(`
mov ecx,200000
xor r8d,r8d
xor r9d,r9d
call hot_loop
mov [0x300008],r8
mov [0x300010],r9
; Patch the immediate through the LOW alias of the currently cached high code.
mov byte [hot_loop+3],7
mov ecx,200000
xor r8d,r8d
xor r9d,r9d
call hot_loop
mov [0x300018],r8
mov [0x300020],r9
`, `
hot_loop:
add r8,byte 3
xor r9,r8
sub ecx,1
jnz hot_loop
ret
`);
const dir = assemble("cache", source);
const config = {length: 40};
const oracle = await reference(dir, config);
// (the second arm interprets the 32-bit setup code: ir_tier0 off; it ran it
// in the region tiers until M11 of docs/jit-unification-plan.md)
for(const [backend, ir_tier0] of [["pages", true], ["pages, 32-bit code interpreted", false]])
{
    let retired = 0, rejected = 0;
    const result = await actual(dir, {...config, options: {disable_jit: false, experimental_smp_jit: true,
        ir_tier0, ir_sync_publication: true}, inspect: emulator => {
        const ex = emulator.v86.cpu.wm.exports;
        retired = ex.x64_page_stat(1); rejected = ex.x64_page_stat(5);
        assert.ok(retired > 1000, "runtime executed actual native instructions");
        assert.ok(rejected > 0, "a write through the low alias retired the page function of the high RIP");
    }});
    assert.deepEqual(result, oracle, backend + " native result agrees with QEMU after SMC");
    console.log(`PASS ${backend}: ${retired} native retirements, ${rejected} page functions invalidated`);
}
                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/x64/compat_fuzz.mjs                                                                0000644 0000000 0000000 00000066664 00000000000 014545  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Random 32-bit programs in IA-32e compatibility mode (WOW64's), each looped
// until its code pages are compiled by the x64 page tier with
// x64_page_compat32 (docs/jit-unification-plan.md P7.2), then compared with
// the same guest run by the interpreters alone: the eight GPRs, EFLAGS and
// the data pages must be identical. As tests/x64/page_fuzz.mjs for 64-bit
// code: templated forms of every width, memory operands (base, index,
// absolute; LOCK RMW), the 32-bit stack, calls, forward branches, string
// instructions, interpreter steps and page-crossing accesses.
//
// COMPAT_FUZZ_SEED, COMPAT_FUZZ_CASES (per guest), COMPAT_FUZZ_GUESTS,
// COMPAT_FUZZ_ITERATIONS; COMPAT_FUZZ_VERBOSE=1 prints a differing case's
// program; COMPAT_FUZZ_SAVE=<file> with COMPAT_FUZZ_SAVE_GUEST and
// COMPAT_FUZZ_SAVE_CASE saves one ({init, lines}), COMPAT_FUZZ_BODY=<file>
// runs a saved one in every case (or with COMPAT_FUZZ_BODY_GUEST and
// COMPAT_FUZZ_BODY_CASE in that one)
import assert from "node:assert/strict";
import fs from "node:fs";
import {assemble} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {with_jit_switches} from "../lib/jit_switches.mjs";
import {setImmediate as yield_event} from "node:timers/promises";

let seed = Number(process.env.COMPAT_FUZZ_SEED || 1) >>> 0 || 1;
const random = () => {
    seed ^= seed << 13; seed >>>= 0;
    seed ^= seed >>> 17;
    seed ^= seed << 5; seed >>>= 0;
    return seed / 0x100000000;
};
const pick = list => list[Math.floor(random() * list.length)];
const int = (lo, hi) => lo + Math.floor(random() * (hi - lo + 1));

// ebp: data base (two pages at 0x500000); esp: the stack; the loop counter
// is in memory.
const GPR32 = ["eax", "ecx", "edx", "ebx", "esi", "edi"];
const NAMES = {eax: ["eax", "ax", "al"], ecx: ["ecx", "cx", "cl"], edx: ["edx", "dx", "dl"], ebx: ["ebx", "bx", "bl"],
    esi: ["esi", "si", null], edi: ["edi", "di", null]};
const WIDTHS = [32, 16, 8];
const SIZE = {32: "dword", 16: "word", 8: "byte"};
const BYTE = ["al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"];
const reg = w => w === 8 ? pick(BYTE) : NAMES[pick(GPR32)][WIDTHS.indexOf(w)];
const DATA = 0x500000, COUNTER = 0x4FF000, RESULT = 0x300000, RECORD = 0x2200, MAGIC = 0xC064C064;
const mem = w => {
    const bytes = w / 8;
    const cross = random() < 0.04;
    const disp = cross ? 4096 - int(1, Math.max(1, bytes - 1)) : int(0, 8190 - bytes) & ~(random() < 0.7 ? bytes - 1 : 0);
    switch(int(0, 2))
    {
        case 0: return `${SIZE[w]} [ebp+${disp}]`;
        case 1: return `${SIZE[w]} [${DATA + disp}]`;
        default: return `${SIZE[w]} [ebp+${disp - 64}+64]`;
    }
};
const imm = w => {
    const v = [0, 1, -1, 0x7F, 0x80, 0x7FFF, 0x8000, 0x7FFFFFFF, -0x80000000, int(-1000, 1000), int(0, 0xFFFFFFFF) | 0][int(0, 10)];
    if(w === 8) return v & 0xFF;
    if(w === 16) return v & 0xFFFF;
    return v | 0;
};
const XMM = Array.from({length: 8}, (_, i) => `xmm${i}`);
// SSE memory operands: aligned forms get 16-byte aligned addresses;
// unaligned ones sometimes cross into the second page
const vmem = (bytes, aligned) => {
    let disp = int(0, 8190 - bytes);
    if(aligned) disp &= ~15;
    else if(random() < 0.1) disp = 4096 - int(1, bytes - 1);
    return random() < 0.5 ? `[ebp+${disp}]` : `[${DATA + disp}]`;
};
function sse_instruction()
{
    const a = pick(XMM), b = pick(XMM);
    return pick([
        `movdqu ${a}, ${vmem(16, false)}`, `movdqu ${vmem(16, false)}, ${a}`, `movups ${a}, ${vmem(16, false)}`, `movups ${vmem(16, false)}, ${a}`,
        `movupd ${a}, ${b}`, `movdqu ${a}, ${b}`, `movdqa ${a}, ${vmem(16, true)}`, `movdqa ${vmem(16, true)}, ${a}`,
        `movaps ${a}, ${b}`, `movaps ${a}, ${vmem(16, true)}`, `movapd ${vmem(16, true)}, ${a}`,
        `movss ${a}, ${b}`, `movss ${a}, ${vmem(4, false)}`, `movss ${vmem(4, false)}, ${a}`,
        `movsd ${a}, ${b}`, `movsd ${a}, ${vmem(8, false)}`, `movsd ${vmem(8, false)}, ${a}`,
        `movq ${a}, ${b}`, `movq ${a}, ${vmem(8, false)}`, `movq ${vmem(8, false)}, ${a}`,
        `movd ${a}, ${reg(32)}`, `movd ${reg(32)}, ${a}`, `movd ${a}, ${vmem(4, false)}`, `movd ${vmem(4, false)}, ${a}`,
        `${pick(["pxor", "por", "pand", "pandn", "xorps", "orps", "andps", "andnps", "xorpd", "andpd"])} ${a}, ${random() < 0.5 ? b : vmem(16, true)}`,
        `${pick(["paddd", "psubd", "paddw", "psubusb", "pcmpeqd", "pcmpgtw", "pmullw", "pmaxsw", "pminub", "pavgb", "punpcklbw", "punpckhdq", "packsswb", "pmaddwd", "psadbw"])} ${a}, ${random() < 0.5 ? b : vmem(16, true)}`,
        `${pick(["addps", "subps", "mulps", "divps", "minps", "maxps", "addsd", "mulsd", "subss", "divss", "sqrtps", "sqrtsd"])} ${a}, ${random() < 0.5 ? b : vmem(16, true)}`,
        `${pick(["psllw", "psrld", "psraw", "psrlq", "pslldq", "psrldq"])} ${a}, ${int(0, 20)}`,
        `pshufd ${a}, ${b}, ${int(0, 255)}`, `shufps ${a}, ${b}, ${int(0, 255)}`,
        `cvtsi2ss ${a}, ${reg(32)}`, `cvttss2si ${reg(32)}, ${a}`, `cvtdq2ps ${a}, ${b}`, `cvttps2dq ${a}, ${b}`, `cvtss2sd ${a}, ${b}`,
        `${pick(["comiss", "ucomiss", "comisd"])} ${a}, ${b}\nset${pick(CC)} al`,
        `pmovmskb ${reg(32)}, ${a}`, `movmskps ${reg(32)}, ${a}`, `pextrw ${reg(32)}, ${a}, ${int(0, 7)}`, `pinsrw ${a}, ${reg(32)}, ${int(0, 7)}`,
        `cmpps ${a}, ${b}, ${int(0, 7)}`,
    ]);
}
// scalar SSE on two registers that the page tier holds in v128 locals
// (named twice or more in a stretch, P4.17): scalar moves, loads and
// results merge into them by shuffles, MOVQ and loads zero the rest; their
// whole values stored right after
function sse_chain()
{
    const [a, b] = [pick(XMM), pick(XMM)];
    const double = random() < 0.5;
    const [mov, size] = double ? ["movsd", 8] : ["movss", 4];
    const arith = () => pick(double ? ["addsd", "subsd", "mulsd"] : ["addss", "subss", "mulss"]);
    const steps = [];
    for(let n = int(2, 6); n--;)
    {
        steps.push(pick([
            `${mov} ${a}, ${vmem(size, false)}`, `${mov} ${a}, ${b}`, `${mov} ${b}, ${a}`,
            `movq ${a}, ${b}`, `movq ${b}, ${vmem(8, false)}`,
            `${arith()} ${a}, ${b}`, `${arith()} ${a}, ${vmem(size, false)}`, `${arith()} ${b}, ${a}`,
            `${mov} ${vmem(size, false)}, ${a}`,
        ]));
    }
    return [`movups ${a}, ${vmem(16, false)}`, `movups ${b}, ${vmem(16, false)}`, ...steps,
        `movups ${vmem(16, false)}, ${a}`, `movups ${vmem(16, false)}, ${b}`].join("\n");
}
// MMX (the MM registers are the x87 mantissas): each result stored to the
// data, most snippets ending with EMMS (an empty stack for the x87 ones)
const MM = Array.from({length: 8}, (_, i) => `mm${i}`);
const PACKED_MMX = ["paddb", "paddw", "paddd", "paddq", "psubb", "psubw", "psubd", "psubq", "paddsb", "paddsw", "paddusb", "paddusw",
    "psubsb", "psubsw", "psubusb", "psubusw", "pmullw", "pmulhw", "pmulhuw", "pmaddwd", "pmuludq", "pand", "pandn", "por", "pxor",
    "pcmpeqb", "pcmpeqw", "pcmpeqd", "pcmpgtb", "pcmpgtw", "pcmpgtd", "packsswb", "packssdw", "packuswb", "punpcklbw", "punpcklwd",
    "punpckldq", "punpckhbw", "punpckhwd", "punpckhdq", "psrlw", "psrld", "psrlq", "psllw", "pslld", "psllq", "psraw", "psrad",
    "pavgb", "pavgw", "pminub", "pmaxub", "pminsw", "pmaxsw", "psadbw"];
function mmx_instruction()
{
    const a = pick(MM), b = pick(MM);
    const op = pick([
        `movq ${a}, ${random() < 0.5 ? b : `qword ${vmem(8, false)}`}`,
        `movq qword ${vmem(8, false)}, ${a}`,
        `movd ${a}, ${random() < 0.5 ? reg(32) : `dword ${vmem(4, false)}`}`,
        `movd ${random() < 0.5 ? reg(32) : `dword ${vmem(4, false)}`}, ${a}`,
        `${pick(PACKED_MMX)} ${a}, ${random() < 0.5 ? b : vmem(8, false)}`,
        `${pick(PACKED_MMX)} ${a}, ${b}`,
        `${pick(["psrlw", "psraw", "psllw", "psrld", "psrad", "pslld", "psrlq", "psllq"])} ${a}, ${pick([0, 1, int(0, 70)])}`,
        `pshufw ${a}, ${random() < 0.5 ? b : vmem(8, false)}, ${int(0, 255)}`,
    ]);
    return `${op}\nmovq qword ${vmem(8, false)}, ${a}` + (random() < 0.7 ? "\nemms" : "");
}
// x87 snippets that leave the stack as they found it (stores capture the
// results; the operands are whatever the data holds)
function x87_instruction()
{
    const m = w => `${SIZE[w] || (w === 64 ? "qword" : "")} ${vmem(w / 8, false)}`;
    return pick([
        `fld dword ${vmem(4, false)}\nf${pick(["add", "sub", "mul", "div", "subr", "divr"])} qword ${vmem(8, false)}\nfstp qword ${vmem(8, false)}`,
        `fld qword ${vmem(8, false)}\nf${pick(["add", "sub", "mul", "div"])} dword ${vmem(4, false)}\nfstp dword ${vmem(4, false)}`,
        `fild dword ${vmem(4, false)}\nfi${pick(["add", "mul", "sub"])} word ${vmem(2, false)}\nfistp dword ${vmem(4, false)}`,
        `fild word ${vmem(2, false)}\nfistp word ${vmem(2, false)}`,
        `fild qword ${vmem(8, false)}\nfistp qword ${vmem(8, false)}`,
        `fld1\nfldz\nfaddp st1, st0\nfld dword ${vmem(4, false)}\nfmulp st1, st0\nfstp dword ${vmem(4, false)}`,
        `fld qword ${vmem(8, false)}\nfld st0\nfmul st0, st1\nfxch st1\nfchs\nfabs\nfaddp st1, st0\nfstp qword ${vmem(8, false)}`,
        `fld dword ${vmem(4, false)}\nfcomp dword ${vmem(4, false)}\nfnstsw ax\nsahf\nset${pick(["b", "e", "be", "p"])} cl`,
        `fld qword ${vmem(8, false)}\nfld qword ${vmem(8, false)}\nf${pick(["comi", "ucomi"])}p st0, st1\nfstp st0\nset${pick(["b", "e", "a", "p"])} dl`,
        `fld dword ${vmem(4, false)}\nfld dword ${vmem(4, false)}\nfcmov${pick(["b", "e", "be", "u", "nb", "ne", "nbe", "nu"])} st0, st1\nfstp dword ${vmem(4, false)}\nfstp st0`,
        `fnstcw word ${vmem(2, false)}\nfld dword ${vmem(4, false)}\nfstp qword ${vmem(8, false)}`,
        // register-only runs (x86tpl::x87run; integer operands: magnitudes
        // where every operation shows): reversed forms, FST/FXCH, FFREE, and
        // a run whose guard fails (ST(5) empty: masked underflow)
        `fild word ${vmem(2, false)}\nfld1\nfld st1\nfdivr st0, st1\nfsubp st2, st0\nfxch st1\nfstp qword ${vmem(8, false)}\nfstp qword ${vmem(8, false)}`,
        `fild dword ${vmem(4, false)}\nfld st0\nfst st1\nfmul st0, st1\nfsub st0, st1\nfdiv st0, st1\nfstp qword ${vmem(8, false)}\nfstp qword ${vmem(8, false)}`,
        `fild word ${vmem(2, false)}\nfld st0\nfmul st0, st1\nfxch st1\nfchs\nfabs\nfsubrp st1, st0\nfstp qword ${vmem(8, false)}`,
        `fld1\nfldz\nfxch st1\nffree st1\nfstp qword ${vmem(8, false)}`,
        `fld st5\nfld st0\nfmulp st1, st0\nfstp qword ${vmem(8, false)}`,
        // stepped forms (FNSTENV, 80-bit stores) right after compiled ones:
        // they read the x87 state the open cache holds (closed at the step)
        `fild word ${vmem(2, false)}\nfld st0\nfmul st0, st1\nfnstenv ${vmem(28, false)}\nfstp qword ${vmem(8, false)}\nfstp qword ${vmem(8, false)}`,
        `fild dword ${vmem(4, false)}\nfld1\nfaddp st1, st0\nfld st0\nfstp tword ${vmem(10, false)}\nfstp qword ${vmem(8, false)}`,
    ]);
}
const CC = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"];
const ALU = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"];
const rm = w => random() < 0.5 ? reg(w) : mem(w);

// (COMPAT_FUZZ_SKIP=15,16: generate none of those cases)
const SKIP = new Set((process.env.COMPAT_FUZZ_SKIP || "").split(",").filter(Boolean).map(Number));
function instruction(state)
{
    const w = pick(WIDTHS);
    const alu = pick(ALU);
    const w16 = pick([16, 32]);
    let which = int(0, 58);
    while(SKIP.has(which)) which = int(0, 58);
    switch(which)
    {
        case 0: case 1: return `${alu} ${reg(w)}, ${reg(w)}`;
        case 2: return `${alu} ${reg(w)}, ${imm(w)}`;
        case 3: return `${alu} ${reg(w)}, ${mem(w)}`;
        case 4: return `${random() < 0.3 && alu !== "cmp" ? "lock " : ""}${alu} ${mem(w)}, ${reg(w)}`;
        case 5: return `${alu} ${mem(w)}, ${imm(w)}`;
        case 6: return `test ${reg(w)}, ${random() < 0.5 ? imm(w) : reg(w)}`;
        case 7: return `mov ${reg(w)}, ${imm(w)}`;
        case 8: return `mov ${reg(w)}, ${mem(w)}`;
        case 9: return `mov ${mem(w)}, ${random() < 0.5 ? reg(w) : imm(w)}`;
        case 10: return pick([`movzx ${reg(32)}, ${pick([reg(8), mem(8), reg(16), mem(16)])}`,
            `movsx ${reg(pick([16, 32]))}, ${pick([reg(8), mem(8)])}`, `movsx ${reg(32)}, ${pick([reg(16), mem(16)])}`]);
        case 11: return `lea ${reg(pick([32, 16]))}, [${reg(32)}+${reg(32)}*${pick([1, 2, 4, 8])}+${int(-2000, 2000)}]`;
        case 12: { const op = pick(["inc", "dec", "neg", "not"]); return random() < 0.5 ? `${op} ${reg(w)}` : `${random() < 0.3 ? "lock " : ""}${op} ${mem(w)}`; }
        case 13: return `${pick(["shl", "shr", "sar", "rol", "ror"])} ${random() < 0.7 ? reg(w) : mem(w)}, ${pick([1, int(0, 40), int(0, 7)])}`;
        case 14: return `${pick(["shl", "shr", "sar", "rol", "ror", "rcl", "rcr"])} ${random() < 0.8 ? reg(w) : mem(w)}, cl`;
        case 15: return `imul ${reg(w16)}, ${rm(w16)}${random() < 0.5 ? ", " + imm(16) : ""}`;
        case 16: return `${pick(["mul", "imul"])} ${rm(32)}`;
        case 17: return pick([`mov ebx, ${int(3, 0x7FFFFFF0) | 3}\nxor edx, edx\ndiv ebx`, `mov ebx, ${int(3, 0x7FFFFFF0) | 3}\ncdq\nidiv ebx`,
            (at => `or dword [ebp+${at}], 3\nxor edx, edx\ndiv dword [ebp+${at}]`)(int(0, 8000) & ~3)]);
        case 18: { const r = reg(32); return `push ${pick([r, reg(32), mem(32), String(imm(32))])}\npop ${r}`; }
        case 19: return `cmov${pick(CC)} ${reg(w16)}, ${rm(w16)}`;
        case 20: return `set${pick(CC)} ${random() < 0.6 ? reg(8) : mem(8)}`;
        case 21: { const n = state.labels++; return `j${pick(CC)} .s${n}\n${simple()}\n${simple()}\n.s${n}:`; }
        case 22: return `xchg ${reg(w)}, ${rm(w)}`;
        case 23: return `${random() < 0.5 ? "lock " : ""}xadd ${mem(w)}, ${reg(w)}`;
        case 24: return random() < 0.5 ? `cmpxchg ${reg(w)}, ${reg(w)}` : `lock cmpxchg ${mem(w)}, ${reg(w)}`;
        case 25: return pick(["cbw", "cwde", "cwd", "cdq"]);
        case 26: return `${pick(["bt", "bts", "btr", "btc"])} ${reg(w16)}, ${random() < 0.5 ? int(0, 255) : reg(w16)}`;
        case 27: return `${pick(["bsf", "bsr"])} ${reg(w16)}, ${rm(w16)}`;
        case 28: return `bswap ${reg(32)}`;
        case 29: return pick(["clc", "stc", "cmc", "lahf", "sahf", "cld", "std", "nop", "pushfd\npop eax", "xchg eax, eax"]);
        case 30: return `call ${pick(["leaf_near", "leaf_far"])}`;
        case 31: return pick(["cpuid", "mov eax, ds", `mov word [ebp+${int(0, 8000)}], ss`, "pause"]);
        case 32: { const op = pick(["movsb", "movsw", "movsd", "stosb", "stosw", "stosd", "cmpsb", "cmpsw", "cmpsd", "scasb", "scasw", "scasd"]);
            const src = int(0, 7000), dst = random() < 0.3 ? src + int(-16, 16) : int(0, 7000), count = pick([0, 1, int(2, 16), int(17, 300)]);
            const prefix = random() < 0.8 ? (/^(cmps|scas)/.test(op) ? pick(["repe ", "repne "]) : "rep ") : "";
            return `lea esi, [ebp+${src}]\nlea edi, [ebp+${Math.max(0, dst)}]\nmov ecx, ${count}\n${random() < 0.2 ? "std\n" : ""}${prefix}${op}\ncld`; }
        case 33: return `test ${mem(w)}, ${random() < 0.5 ? imm(w) : reg(w)}`;
        case 34: return `cmp ${reg(w)}, ${mem(w)}\nj${pick(CC)} .c${state.labels}\ninc edi\n.c${state.labels++}:`;
        case 35: return `sub ${reg(w)}, ${imm(8)}\nset${pick(CC)} al`;
        case 36: { const r = reg(32); return `xor ${r}, ${r}`; }
        case 37: return `and ebx, 255\n${alu} ${reg(32)}, [ebp+ebx*${pick([1, 2, 4])}+${int(0, 7000)}]`;
        case 38: return `and ecx, 255\nmov ${pick(["eax", "edx", "esi"])}, [ebp+ecx*4+${int(0, 7000)}]`;
        // a shift's SF, ZF and PF read only after leaving the page (leaf_far
        // keeps them): pending in the lazy record at the exit
        case 39: return `${pick(["shl", "shr", "sar"])} ${reg(32)}, ${pick([int(1, 31), "cl"])}\ncall leaf_far\n${pick([`set${pick(["z", "nz", "s", "ns", "p", "np", "b", "o", "le", "g"])} ${reg(8)}`, "pushfd\npop eax", "lahf"])}`;
        case 40: case 41: case 42: case 43: case 44: return sse_instruction();
        case 45: case 46: case 47: return x87_instruction();
        case 55: case 56: case 57: return mmx_instruction();
        case 58: return sse_chain();
        // indirect transfers inside the loop to its own code: a CALL and RET
        // in the page, a jump table (dispatched by the loop's head, P7.2)
        case 48: { const n = state.labels++; return `call .f${n}\njmp .e${n}\n.f${n}:\n${simple()}\nret\n.e${n}:`; }
        // bit scans, counts, SHLD/SHRD and BMI (the 32-bit interpreter's
        // flags: BSF/BSR and SHLD/SHRD leave lazy ones), sources often small
        // or 0, then a condition on what they set
        case 50: case 52: case 53: {
            const t = pick(GPR32.filter(r => r !== "ecx"));
            // (added up in the data the test compares: registers are often
            // overwritten, and XOR or a byte store keeps only some rounds)
            const set = cc => (random() < 0.5 ? `\nset${pick(cc)} al\nmovzx eax, al` : `\npushfd\npop eax`) +
                `\nadd dword [ebp+${int(0, 8188) & ~3}], eax`;
            return pick([
                `and ${t}, ${int(0, 3)}\n${pick(["bsf", "bsr"])} ${reg(32)}, ${t}${set(["z", "nz", "p", "np", "s", "o", "b"])}`,
                `${pick(["bsf", "bsr"])} ${reg(w16)}, ${rm(w16)}${set(["z", "nz", "p", "o"])}`,
                `and ${t}, ${int(0, 3)}\npopcnt ${reg(32)}, ${t}${set(["z", "nz", "b", "p", "o"])}`,
                `and ${t}, ${pick([0, 0xFF, 0xFFFF0000])}\n${pick(["tzcnt", "lzcnt"])} ${reg(32)}, ${t}${set(["z", "nz", "b", "ae", "s"])}`,
                `${pick(["shld", "shrd"])} ${rm(32)}, ${reg(32)}, ${pick([1, 2, int(0, 31), 31])}${set(["o", "no", "b", "ae", "z", "s", "p"])}`,
                // (operands loaded first: the program's values are often small)
                (([d, r]) => `mov ${d}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\nmov ${r}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\n` +
                    `${pick(["shld", "shrd"])} ${d}, ${r}, ${int(1, 31)}${set(["o", "no", "b", "ae", "z", "s", "p"])}`)(pick([["ebx", "esi"], ["edi", "edx"], ["esi", "ebx"]])),
                `${pick(["shld", "shrd"])} ${rm(w16)}, ${reg(w16)}, cl`,
                (([d, r]) => `mov ${d}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\nmov ${r}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\n` +
                    `mov cl, ${pick([2, 3, 5, 9, 30, 34])}\n${pick(["shld", "shrd"])} ${d}, ${r}, cl${set(["o", "no"])}`)(pick([["ebx", "esi"], ["edi", "edx"], ["esi", "ebx"]])),
                (([d, r]) => `mov ${d}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\nmov ${r}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}\n` +
                    `mov cl, ${pick([0, 1, 2, int(0, 255), 31, 32, 33])}\n${pick(["shld", "shrd"])} ${d}, ${r}, cl${set(["o", "no", "b", "ae", "z", "s", "p"])}`)(pick([["ebx", "esi"], ["edi", "edx"], ["esi", "ebx"]])),
            ]);
        }
        case 51: case 54: {
            const t = pick(GPR32);
            // (added up in the data the test compares: registers are often
            // overwritten, and XOR or a byte store keeps only some rounds)
            const set = cc => (random() < 0.5 ? `\nset${pick(cc)} al\nmovzx eax, al` : `\npushfd\npop eax`) +
                `\nadd dword [ebp+${int(0, 8188) & ~3}], eax`;
            return pick([`and ${t}, ${int(0, 3)}\nandn ${reg(32)}, ${reg(32)}, ${t}`, `and ${t}, ${int(0, 3)}\n${pick(["blsr", "blsmsk", "blsi"])} ${reg(32)}, ${t}`,
                `bzhi ${reg(32)}, ${rm(32)}, ${reg(32)}`, `${pick(["shlx", "sarx", "shrx"])} ${reg(32)}, ${rm(32)}, ${reg(32)}`,
                `rorx ${reg(32)}, ${rm(32)}, ${int(0, 31)}`]) + set(["z", "nz", "b", "ae", "s", "o"]);
        }
        case 49: {
            const n = state.labels++, r = pick(["ebx", "edx", "esi"]);
            return `mov ${r}, ${reg(32)}\nand ${r}, 3\njmp [.t${n}+${r}*4]\n.t${n}: dd .a${n}, .b${n}, .c${n}, .d${n}\n` +
                ["a", "b", "c", "d"].map(l => `.${l}${n}:\n${simple()}\njmp .e${n}`).join("\n") + `\n.e${n}:`;
        }
        default: return `${pick(["add", "sub", "and", "or", "xor", "adc", "sbb"])} ${mem(w)}, ${imm(w)}`;
    }
}
function simple()
{
    return pick([`add ${reg(32)}, ${int(0, 99)}`, `xor ${reg(32)}, ${reg(32)}`, `inc ${mem(32)}`, `mov ${reg(16)}, ${mem(16)}`]);
}

const cases = Number(process.env.COMPAT_FUZZ_CASES || 12);
const guests = Number(process.env.COMPAT_FUZZ_GUESTS || 4);
const ITERATIONS = Number(process.env.COMPAT_FUZZ_ITERATIONS || 300);
let failures = 0, native_total = 0, compat_compiles = 0;
for(let guest = 0; guest < guests; guest++)
{
    const first_seed = seed;
    // 64-bit code: each case in compatibility mode, back by a far jump
    let body = "mov rax, cr4\nor eax, 0x600\nmov cr4, rax\n";
    let functions = "";
    const programs = [];
    for(let c = 0; c < cases; c++)
    {
        const state = {labels: 0};
        let lines = Array.from({length: int(20, 70)}, () => instruction(state));
        let init = GPR32.map(r => `mov ${r}, 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}`).join("\n");
        // (COMPAT_FUZZ_BODY_GUEST and COMPAT_FUZZ_BODY_CASE: only there; the
        // others stay as the seed makes them)
        const target = (name, n) => process.env[name] === undefined || +process.env[name] === n;
        if(process.env.COMPAT_FUZZ_BODY && target("COMPAT_FUZZ_BODY_GUEST", guest) && target("COMPAT_FUZZ_BODY_CASE", c))
            ({init, lines} = JSON.parse(fs.readFileSync(process.env.COMPAT_FUZZ_BODY, "utf8")));
        if(process.env.COMPAT_FUZZ_SAVE && +process.env.COMPAT_FUZZ_SAVE_GUEST === guest && +process.env.COMPAT_FUZZ_SAVE_CASE === c)
            fs.writeFileSync(process.env.COMPAT_FUZZ_SAVE, JSON.stringify({init, lines}, null, 1));
        programs.push(init + "\n.loop:\n" + lines.join("\n"));
        body += `mov rax, HIGH+after_${c}\nmov [0x2FF000], rax\npush 8\nmov eax, case_${c}\npush rax\no64 retf\nafter_${c}:\n`;
        functions += `
align 4096
case_${c}:
fninit
${init}
${XMM.map((x, i) => `movdqu ${x}, [xmm_init_${c}+${i * 16}]`).join("\n")}
mov ebp, ${DATA}
mov dword [${COUNTER}], ${ITERATIONS}
push 0x${(int(0, 0xFFF) & 0xCD5).toString(16)}
popfd
.loop:
${lines.join("\n")}
dec dword [${COUNTER}]
jnz .loop
${["eax", "ecx", "edx", "ebx", "esi", "edi", "ebp", "esp"].map((r, i) => `mov [${RESULT + 8 + c * RECORD + i * 4}], ${r}`).join("\n")}
pushfd
pop eax
mov [${RESULT + 8 + c * RECORD + 32}], eax
cld
mov esi, ${DATA}
mov edi, ${RESULT + 8 + c * RECORD + 256}
mov ecx, 8192
rep movsb
${XMM.map((x, i) => `movdqu [${RESULT + 8 + c * RECORD + 8448 + i * 16}], ${x}`).join("\n")}
mov edi, ${DATA}
mov ecx, 8192
mov al, 0x5A
rep stosb
jmp 0x18:back_to_64
align 16
xmm_init_${c}:
${Array.from({length: 32}, () => `dd 0x${(int(0, 0xFFFFFFFF) >>> 0).toString(16)}`).join("\n")}
`;
    }
    const source = long_mode_guest(body, `
bits 32
${functions}
align 4096
leaf_near:
add esi, 7
xor edi, esi
ret
align 4096
leaf_far:
lea esi, [esi+edi*2+3]
ror edi, 5
ret
bits 64
back_to_64:
jmp [0x2FF000]
`);
    const dir = assemble(`compat-fuzz-${guest}`, source.replace("high_mode:\n", `high_mode:\nmov rdi, ${DATA}\nmov ecx, 8192\nmov al, 0x5A\nrep stosb\n`));
    const length = 8 + cases * RECORD;
    const run = async jit => {
        const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
        // (JIT_SWITCHES adds switches, e.g. x64_loops=1 for loops in cold compiles)
        const emulator = new V86(with_jit_switches({graphics_adapter: "bochs_vga", multiboot: {url: dir + "guest.bin"}, memory_size: 32 << 20, acpi: true,
            disable_jit: !jit, experimental_smp_jit: true, ir_sync_publication: true, autostart: false, log_level: 0,
            cpu_type: "x86_64", cpu_features: ["BMI1", "BMI2", "LZCNT", "MOVBE"], cpu_features_unreleased: true,
            // (compatibility mode's first compile waits for x64_legacy_heat, as
            // legacy mode's: the loops here are shorter, as tier0_fuzz's)
            jit_switches: {x64_page_compat32: 1, x64_legacy_heat: 2000}}));
        try
        {
            await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
            const cpu = emulator.v86.cpu;
            // (COMPAT_FUZZ_RECORD=<dir>: the compiled run's page functions,
            // with TEST_RELEASE_BUILD=1 and a build/v86.wasm with ir-test-hooks)
            const record = jit && process.env.COMPAT_FUZZ_RECORD && cpu.wm.exports.x64_page_record_start;
            if(record) cpu.wm.exports.x64_page_record_start();
            const deadline = performance.now() + 120000;
            let rounds = 0;
            while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(RESULT, true) !== MAGIC)
            {
                if(performance.now() > deadline) throw new Error("guest timed out: " + JSON.stringify(cpu.get_diagnostics()));
                cpu.run_cores();
                if((++rounds & 63) === 0) await yield_event();
            }
            const x = cpu.wm.exports;
            if(record)
            {
                fs.mkdirSync(process.env.COMPAT_FUZZ_RECORD, {recursive: true});
                for(let i = 0, n = x.x64_page_record_count(); i < n; i++)
                {
                    const bytes = new Uint8Array(x.memory.buffer, x.x64_page_record_address(i), x.x64_page_record_length(i)).slice();
                    new Uint8Array(x.memory.buffer, x.x64_page_replay_input(bytes.length), bytes.length).set(bytes);
                    const length = x.x64_page_replay();
                    fs.writeFileSync(`${process.env.COMPAT_FUZZ_RECORD}/g${guest}_${i}.wasm`, new Uint8Array(x.memory.buffer, x.x64_page_replay_output(), length));
                }
            }
            return {result: Buffer.from(cpu.mem8.slice(RESULT, RESULT + length)), native: jit ? x.x64_page_stat(1) : 0,
                compat_compiles: jit ? x.x64_page_stat(36) : 0, stats: jit ? Array.from({length: 13}, (_, i) => x.x64_page_stat(i)) : []};
        }
        finally { await emulator.destroy(); }
    };
    const reference = await run(false);
    const compiled = await run(true);
    native_total += compiled.native;
    compat_compiles += compiled.compat_compiles;
    for(let c = 0; c < cases; c++)
    {
        const at = 8 + c * RECORD;
        const a = reference.result.subarray(at, at + RECORD), b = compiled.result.subarray(at, at + RECORD);
        if(!a.equals(b))
        {
            failures++;
            const names = ["eax", "ecx", "edx", "ebx", "esi", "edi", "ebp", "esp", "eflags"];
            const diffs = [];
            for(let i = 0; i < 9; i++) if(a.readUInt32LE(i * 4) !== b.readUInt32LE(i * 4)) diffs.push(`${names[i]}: interpreter ${a.readUInt32LE(i * 4).toString(16)} page ${b.readUInt32LE(i * 4).toString(16)}`);
            for(let i = 256; i < 256 + 8192; i++) if(a[i] !== b[i]) { diffs.push(`data+${i - 256}: ${a[i].toString(16)} vs ${b[i].toString(16)}`); if(diffs.length > 24) break; }
            for(let i = 0; i < 8; i++) if(!a.subarray(8448 + i * 16, 8464 + i * 16).equals(b.subarray(8448 + i * 16, 8464 + i * 16)))
                diffs.push(`xmm${i}: interpreter ${a.subarray(8448 + i * 16, 8464 + i * 16).toString("hex")} page ${b.subarray(8448 + i * 16, 8464 + i * 16).toString("hex")}`);
            console.log(`FAIL guest ${guest} (seed ${first_seed}) case ${c}:\n  ` + diffs.join("\n  "));
            if(process.env.COMPAT_FUZZ_VERBOSE) console.log(programs[c]);
        }
    }
    console.log(`guest ${guest} (seed ${first_seed}): ${cases} cases, native retired ${compiled.native}, compat compiles ${compiled.compat_compiles}, stats ${JSON.stringify(compiled.stats)}`);
    assert.ok(compiled.compat_compiles > 0 && compiled.native > cases * ITERATIONS * 5, "the page tier executed the 32-bit loops");
}
assert.equal(failures, 0, `${failures} cases differ`);
console.log(`PASS compat fuzz: ${guests * cases} 32-bit programs identical to the interpreter (${native_total} native instructions, ${compat_compiles} compatibility-mode compiles)`);
                                                                            source/v64/tests/x64/compat_jit.mjs                                                                 0000644 0000000 0000000 00000013317 00000000000 014320  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Compiled 32-bit code in IA-32e compatibility mode (x64_page_compat32):
// the same hot compatibility-mode routine runs twice under 4-level paging
// with NX. Between the runs, 64-bit code remaps a data page (PTE write +
// INVLPG), which the already compiled code must observe (the 32-bit TLB it
// reads inline is filled from x64 translations). The loop mixes loads,
// stores, PUSH/CALL/RET and patches a CALLed routine after compilation.
// One page (dual) runs as 64-bit and as 32-bit code (bytes that decode
// alike: each mode's function of the same physical page), called in loops
// from both modes; between the runs, 64-bit code patches it (a write to a
// page with a compatibility-mode function). A loop reads a routine's
// immediate and writes it back incremented through one base register and
// displacement page, then calls it: the write must not take the
// translation the reads keep (x64_fast_lookup's kept translations, one
// per kind), as the code page refuses writes to the inline lookups.
// Results must equal the interpreter's, and with x64_page_compat32 the x64
// page tier's compiled code must have run (docs/jit-unification-plan.md
// P7.2, M6's acceptance; the region tiers' arm went with them in M11).
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const ITERATIONS = 200000, PATCHED = 60000, DUAL = 40000, SMC = 3000;
const body = `
; 4 KiB page table at 0x210000 for linear 0x600000..0x7FFFFF (identity), NX
mov rdi,0x210000
mov eax,0x600003
mov ecx,512
.pt:
mov [rdi],rax
add eax,0x1000
add rdi,8
loop .pt
mov rax,0x210003
bts rax,63
mov [0x202018],rax
mov rax,cr3
mov cr3,rax
mov dword [0x700000],0x5EED0001
mov dword [0x600000],0x10101010
call dual64
mov rax,HIGH+second
mov [0x301000],rax
jmp run_compat
second:
; phase 2: linear 0x600000 now maps physical 0x700000
mov qword [0x210000],0x700003
invlpg [0x600000]
; dual's XOR EBX, EAX becomes SUB EBX, EAX (both modes' functions go)
mov byte [dual+2],0x29
call dual64
mov rax,HIGH+done
mov [0x301000],rax
jmp run_compat
run_compat:
push 8
mov eax,compat_entry
push rax
o64 retf
done:
mov rsi,0x601000
mov rdi,0x300010
mov ecx,9
rep movsq
jmp body_end
; the dual page from 64-bit code: EAX at 0x601030 + phase * 4
dual64:
mov ecx,${DUAL}
mov eax,1
mov ebx,7
.loop:
mov edx,dual
call rdx
dec ecx
jnz .loop
mov edx,[0x301008]
mov [0x601030+rdx*4],eax
ret
body_end:
`;
const data = `
bits 32
compat_entry:
mov ecx,${ITERATIONS}
xor eax,eax
xor edx,edx
xor edi,edi
mov dword [helper+2],0x11111111
.loop:
mov ebx,ecx
and ebx,1023
add eax,[0x600000+ebx*4]
mov [0x600000+ebx*4],eax
lea edi,[edi+eax*2+1]
xor edx,eax
rol edx,3
push eax
call helper
pop esi
add edi,esi
dec ecx
jnz .loop
mov ebx,[0x301008]
mov [0x601000+ebx*8],eax
mov [0x601004+ebx*8],edx
mov [0x601010+ebx*8],edi
mov eax,[0x600000]
mov [0x601020+ebx*4],eax
; patch the CALLed routine and run it again
mov dword [helper+2],0x22222222
mov ecx,${PATCHED}
.loop2:
call helper
dec ecx
jnz .loop2
mov [0x601028+ebx*4],edx
; the dual page from 32-bit code: EAX at 0x601038 + phase * 4
mov ecx,${DUAL}
mov eax,1
mov ebx,7
.dual:
call dual
dec ecx
jnz .dual
mov ebx,[0x301008]
mov [0x601038+ebx*4],eax
; the routine's immediate read and written through EBX: EDX at 0x601040
; + phase * 4
mov ecx,${SMC}
mov ebx,smc
xor edx,edx
.smc:
mov eax,[ebx+2]
inc eax
mov [ebx+2],eax
call ebx
dec ecx
jnz .smc
mov ebx,[0x301008]
mov [0x601040+ebx*4],edx
inc dword [0x301008]
jmp 0x18:back_to_64
; its own page: patching it leaves the loop's compiled code in place
align 4096
helper:
add edx,0x11111111
ret
; ADD EDX, imm32 (the immediate at +2), patched by the loop above
align 4096
smc:
add edx,0x01010101
ret
; ADD EAX, EBX; XOR EBX, EAX; RET in either mode
align 4096
dual:
add eax,ebx
xor ebx,eax
ret
bits 64
back_to_64:
jmp [0x301000]
`;
const directory = assemble("compat-jit", long_mode_guest(body, data));
const results = {};
for(const [name, jit, page32] of [["interpreter", false, false], ["page tier, compat interpreted", true, false],
    ["page tier, compat32", true, true]])
{
    let page;
    const result = await actual(directory, {length: 88, timeout: 120000,
        options: jit ? {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
            jit_switches: {x64_page_compat32: page32 ? 1 : 0}} : {},
        inspect: emulator => {
            const x = emulator.v86.cpu.wm.exports;
            page = {compat_compiles: x.x64_page_stat(36), native: x.x64_page_stat(1)};
        }});
    results[name] = result;
    console.log(`${name}: ${result.subarray(16, 80).toString("hex")} page tier ${JSON.stringify(page)}`);
    if(page32) assert.ok(page.compat_compiles > 0 && page.native > ITERATIONS * 10, "the page tier ran the compatibility-mode code");
}
const view = results.interpreter;
// per phase: EAX/EDX at +0/+4 (+8), EDI at +16 (+8), first data dword at +32 (+4)
assert.notEqual(view.readUInt32LE(16 + 4), view.readUInt32LE(16 + 12), "phase 2 ran on the remapped page");
// the dual page: 64-bit results at +48 (+4), 32-bit ones at +56 (+4)
assert.notEqual(view.readUInt32LE(16 + 48), view.readUInt32LE(16 + 52), "phase 2 ran the patched dual page in 64-bit mode");
assert.notEqual(view.readUInt32LE(16 + 56), view.readUInt32LE(16 + 60), "phase 2 ran the patched dual page in compatibility mode");
// the patched routine: the sum of its immediates
assert.notEqual(view.readUInt32LE(16 + 64), 0, "the patched routine ran");
for(const name of Object.keys(results)) assert.deepEqual(results[name], view, `${name} agrees with the interpreter`);
console.log("PASS compatibility-mode JIT: loads/stores, CALL/RET, patched code (also through a register its reads use), a remapped page and a page run in both modes agree with the interpreter");
                                                                                                                                                                                                                                                                                                                 source/v64/tests/x64/cpu_features.mjs                                                               0000644 0000000 0000000 00000016161 00000000000 014654  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The CPU features of docs/simd-xsave-plan.md (src/cpu_features.js, setting
// cpu_features): CPUID reports exactly the requested features (not given:
// every released one for x86_64, the owner's decision of 2026-10-17, none for
// x86; [] none), a preset names a set, cpuid_level leaves out what it cannot report together with what
// requires it, and an unknown feature, one the profile cannot have or one
// without its requirements fails. Every milestone is released (M1
// x86-64-v2, M2 XSAVE, M3 AVX, M4 x86-64-v3, M5 the XSAVE family): no feature
// is listed as unreleased (that would warn unless cpu_features_unreleased).
import assert from "node:assert/strict";
import url from "node:url";
import {assemble, actual} from "./guest_runner.mjs";

const root = url.fileURLToPath(new URL("../../", import.meta.url));
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const {unreleased_cpu_features} = await import("../../src/cpu.js");

const directory = assemble("cpu-features", `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
xor eax,eax
cpuid
mov [0x300004],eax
mov eax,1
cpuid
mov [0x300008],ecx
mov eax,7
xor ecx,ecx
cpuid
mov [0x30000C],ebx
mov eax,0x80000001
cpuid
mov [0x300010],ecx
mov eax,0xD
mov ecx,1
cpuid
mov [0x300014],eax
mov dword [0x300000],0xC064C064
hlt
jmp $
image_end:
`);

// CPUID bits of the plan's features: leaf 1 ECX, leaf 7 EBX, 80000001h ECX,
// leaf 0Dh subleaf 1 EAX
const LEAF1 = {SSSE3: 9, FMA: 12, "SSE4.1": 19, "SSE4.2": 20, MOVBE: 22, XSAVE: 26, AVX: 28, F16C: 29};
const LEAF7 = {BMI1: 3, AVX2: 5, BMI2: 8};
const EXT1 = {LZCNT: 5};
const LEAFD1 = {XSAVEOPT: 0, XSAVEC: 1, XGETBV1: 2, XSAVES: 3};
const mask = (table, names) => names.filter(n => n in table).reduce((m, n) => m | 1 << table[n], 0);
const all = table => mask(table, Object.keys(table));
const V2 = ["SSSE3", "SSE4.1", "SSE4.2"];
const V3 = [...V2, "XSAVE", "AVX", "AVX2", "FMA", "F16C", "BMI1", "BMI2", "LZCNT", "MOVBE"];
// (the 32-bit profile: x86-64-v3's features but LZCNT, plan Q7)
const LEGACY_V3 = V3.filter(name => name !== "LZCNT");
const XSAVE_FAMILY = ["XSAVE", "XSAVEOPT", "XSAVEC", "XGETBV1", "XSAVES"];

for(const [options, expected, level] of [
    [{}, []],
    [{cpu_type: "x86_64"}, [...V3, ...XSAVE_FAMILY.slice(1)]],
    [{cpu_type: "x86_64", cpu_features: []}, []],
    [{cpu_features: [...V2, "BMI1", "BMI2", "MOVBE"], cpu_features_unreleased: true}, [...V2, "BMI1", "BMI2", "MOVBE"]],
    [{cpu_features: "x86-64-v2"}, V2],
    [{cpu_features: ["XSAVE"]}, ["XSAVE"]],
    [{cpu_type: "x86_64", cpu_features: [...V2, "XSAVE", "AVX"]}, [...V2, "XSAVE", "AVX"]],
    [{cpu_type: "x86_64", cpu_features: "x86-64-v3"}, V3],
    [{cpu_type: "x86_64", cpu_features: "x86-64-v3", cpu_features_unreleased: true}, V3],
    [{cpu_features: LEGACY_V3}, LEGACY_V3],
    [{cpu_features: XSAVE_FAMILY}, XSAVE_FAMILY],
    [{cpu_type: "x86_64", cpu_features: [...V3, ...XSAVE_FAMILY.slice(1)]}, [...V3, ...XSAVE_FAMILY.slice(1)]],
    // leaf 0xD is out of reach: XSAVE goes, and AVX, AVX2, FMA, F16C and the
    // XSAVE family with it
    [{cpu_type: "x86_64", cpu_features: [...V3, ...XSAVE_FAMILY.slice(1)], cpuid_level: 7}, [...V2, "BMI1", "BMI2", "LZCNT", "MOVBE"], 7],
    // the Windows NT setting: neither leaf 7 nor leaf 0xD
    [{cpu_features: [...V2, "BMI1", "MOVBE"], cpu_features_unreleased: true, cpuid_level: 2}, [...V2, "MOVBE"], 2],
])
{
    const result = await actual(directory, {length: 24, options});
    const name = JSON.stringify(options);
    const [leaf0, leaf1, leaf7, ext1, leafd1] = [4, 8, 12, 16, 20].map(at => result.readUInt32LE(at));
    assert.equal(leaf1 & all(LEAF1), mask(LEAF1, expected), `${name}: CPUID.1:ECX ${leaf1.toString(16)}`);
    assert.equal(leaf7 & all(LEAF7), mask(LEAF7, expected), `${name}: CPUID.7.0:EBX ${leaf7.toString(16)}`);
    assert.equal(ext1 & all(EXT1), mask(EXT1, expected), `${name}: CPUID.80000001h:ECX ${ext1.toString(16)}`);
    // (leaf 0xD's subleaf 1 only where leaf 0xD is reported)
    if(expected.includes("XSAVE")) assert.equal(leafd1 & all(LEAFD1), mask(LEAFD1, expected), `${name}: CPUID.0Dh.1:EAX ${leafd1.toString(16)}`);
    if(level !== undefined) assert.equal(leaf0, level, `${name}: maximum basic leaf`);
    console.log(`PASS ${name} -> ${expected.join(" ") || "no plan features"}`);
}

for(const [options, message] of [
    [{cpu_features: ["LZCNT"]}, /LZCNT needs cpu_type: "x86_64"/],
    [{cpu_features: "x86-64-v3"}, /LZCNT needs cpu_type: "x86_64"/],
    [{cpu_features: ["SSE4.1"]}, /SSE4\.1 requires SSSE3/],
    [{cpu_type: "x86_64", cpu_features: ["AVX", "SSSE3", "SSE4.1", "SSE4.2"]}, /AVX requires XSAVE/],
    [{cpu_features: ["AVX512F"]}, /unknown feature "AVX512F"/],
    [{cpu_features: "x86-64-v4"}, /unknown preset "x86-64-v4"/],
])
{
    const emulator = new V86({graphics_adapter: "bochs_vga", bios: {url: root + "bios/seabios.bin"}, vga_bios: {url: root + "bios/vgabios.bin"},
        autostart: false, log_level: 0, ...options});
    const error = await new Promise(resolve => {
        emulator.add_listener("emulator-loaded", () => resolve(null));
        emulator.add_listener("emulator-error", resolve);
    });
    assert.match(String(error), message, JSON.stringify(options));
    await emulator.destroy();
    console.log(`PASS ${JSON.stringify(options)} is refused`);
}

// a snapshot keeps the CPU its guest saw: a machine whose features were not
// chosen takes the snapshot's, one given cpu_features refuses other ones
{
    const machine = async options => {
        const emulator = new V86({graphics_adapter: "bochs_vga", bios: {url: root + "bios/seabios.bin"}, vga_bios: {url: root + "bios/vgabios.bin"},
            autostart: false, log_level: 0, cpu_type: "x86_64", ...options});
        await new Promise((resolve, reject) => {
            emulator.add_listener("emulator-loaded", resolve);
            emulator.add_listener("emulator-error", reject);
        });
        return emulator;
    };
    const baseline = await machine({cpu_features: []});
    const state = await baseline.save_state();
    await baseline.destroy();
    const defaulted = await machine({});
    assert.notEqual(defaulted.v86.cpu.cpu_features, 0, "x86_64's default features");
    await defaulted.restore_state(state);
    assert.equal(defaulted.v86.cpu.cpu_features, 0, "the restored machine has the snapshot's features");
    assert.equal(defaulted.v86.cpu.wm.exports["get_cpu_features"](), 0, "and so has the core");
    await defaulted.destroy();
    const chosen = await machine({cpu_features: "x86-64-v3"});
    await assert.rejects(chosen.restore_state(state), /The snapshot is from a machine with the CPU features none/);
    await chosen.destroy();
    console.log("PASS a snapshot's CPU features: taken by a machine with the default, refused by one with cpu_features");
}

for(const requested of [undefined, "x86-64-v2", "x86-64-v3", ["SSSE3", "XSAVE"], LEGACY_V3, [...V3, ...XSAVE_FAMILY]])
{
    assert.deepEqual(unreleased_cpu_features(requested), [], JSON.stringify(requested));
}
console.log("PASS every feature of M1-M5 (x86-64-v2, XSAVE, AVX, x86-64-v3, the XSAVE family) is released");
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/x64/direct_loader.mjs                                                              0000644 0000000 0000000 00000010104 00000000000 014756  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Direct boot (multiboot/bzimage) stays 32-bit: x86-64 kernels boot from a
// BIOS disk or ISO, or through a 32-bit multiboot entry that enables long
// mode itself (all tests/x64 guests). Inputs the loaders cannot handle are
// rejected with an emulator-error before anything runs, instead of being
// parsed with 32-bit structures. A 32-bit i386 multiboot ELF still boots.
import assert from "node:assert/strict";

const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const MAGIC = 0x1BADB002;

function elf({elf_class = 1, machine = 3, code = []} = {})
{
    const image = new Uint8Array(0x200);
    const view = new DataView(image.buffer);
    view.setUint32(0, 0x464C457F, true);
    image.set([elf_class, 1, 1], 4);
    view.setUint16(16, 2, true);          // ET_EXEC
    view.setUint16(18, machine, true);
    view.setUint32(20, 1, true);
    view.setUint32(24, 0x10010C, true);   // entry
    view.setUint32(28, 52, true);         // program headers
    view.setUint16(40, 52, true);
    view.setUint16(42, 32, true);
    view.setUint16(44, 1, true);
    view.setUint16(46, 40, true);
    // PT_LOAD of the whole file at 1 MiB
    [1, 0, 0x100000, 0x100000, 0x200, 0x200, 5, 0x1000].forEach((v, i) => view.setUint32(52 + i * 4, v, true));
    // multiboot header without the address fields (the ELF headers are used)
    [MAGIC, 0, -MAGIC >>> 0].forEach((v, i) => view.setUint32(0x100 + i * 4, v, true));
    image.set(code, 0x10C);
    return image.buffer;
}
function headerless()
{
    const image = new Uint8Array(0x200);
    [MAGIC, 0, -MAGIC >>> 0].forEach((v, i) => new DataView(image.buffer).setUint32(0x40 + i * 4, v, true));
    return image.buffer;
}
function bzimage(protocol)
{
    const image = new Uint8Array(0x1000);
    const view = new DataView(image.buffer);
    view.setUint16(0x1FE, 0xAA55, true);
    view.setUint32(0x202, 0x53726448, true); // "HdrS"
    view.setUint16(0x206, protocol, true);
    image[0x211] = 1;                          // LOADED_HIGH
    return image.buffer;
}

async function boot(options)
{
    const emulator = new V86({graphics_adapter: "bochs_vga", memory_size: 32 << 20, autostart: false, disable_jit: true, log_level: 0, ...options});
    try
    {
        return await new Promise(resolve => {
            emulator.add_listener("emulator-loaded", () => resolve({emulator}));
            emulator.add_listener("emulator-error", error => resolve({error}));
        });
    }
    catch(error) { return {error}; }
}

for(const [name, options, pattern] of [
    ["64-bit multiboot ELF", {multiboot: {buffer: elf({elf_class: 2})}}, /64-bit ELF/],
    ["x86-64 machine ELF32", {multiboot: {buffer: elf({machine: 62})}}, /not an i386 image \(machine 62\)/],
    ["multiboot without address header or ELF", {multiboot: {buffer: headerless()}}, /neither an address header nor an ELF header/],
    ["bzimage boot protocol 2.01", {bzimage: {buffer: bzimage(0x201)}, bios: {buffer: new Uint8Array(65536).fill(0xF4).buffer}}, /older than 2\.02/],
    ["bzimage without a boot header", {bzimage: {buffer: new ArrayBuffer(0x1000)}, bios: {buffer: new Uint8Array(65536).fill(0xF4).buffer}}, /no Linux boot sector signature/],
])
{
    const {emulator, error} = await boot(options);
    if(emulator) { await emulator.destroy(); assert.fail(name + ": loaded"); }
    assert.match(String(error?.message || error), pattern, name);
    console.log(`PASS rejected: ${name}`);
}

// mov dword [0x300000], 0xC064C064; hlt
const {emulator, error} = await boot({multiboot: {buffer: elf({code: [0xC7, 0x05, 0, 0, 0x30, 0, 0x64, 0xC0, 0x64, 0xC0, 0xF4, 0xEB, 0xFE]})}});
assert.ok(emulator, "i386 multiboot ELF loads: " + error);
try
{
    const cpu = emulator.v86.cpu;
    for(let round = 0; round < 2000 && new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x300000, true) !== 0xC064C064; round++) cpu.run_cores();
    assert.equal(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x300000, true), 0xC064C064, "i386 multiboot ELF ran");
}
finally { await emulator.destroy(); }
console.log("PASS i386 multiboot ELF still boots");
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/x64/extended_memory.mjs                                                            0000644 0000000 0000000 00000031511 00000000000 015353  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Extended RAM (docs/x86-64.md): guest RAM beyond the wasm32
// backing store. 64 MiB of RAM, 16 MiB of it relocated to 4 GiB, and
// EXTENDED_GIB (default 6) GiB of extended RAM after it, cached in a pool of
// only 4 MiB of frames, so that nearly every access pages. A long-mode guest
// writes and checks samples across all of it and dense patterns in part of
// it, copies with string instructions, runs code there, runs with its page
// tables there (their accessed/dirty bits too), runs 32-bit compatibility-
// mode code there (the 32-bit bus aperture) and reads a block the host wrote
// by DMA. A hot loop there is compiled by the page tier, then rewritten
// from low code, after its frame was evicted (REP MOVSB), and by itself;
// each run must see the new bytes. The host checks the bytes, then a snapshot stream restores them
// into a second machine. Interpreter and page tier must agree; the page
// tier's access caches must release their frames (X64_CORES=2 runs the
// machine through the multi-core slice loop, whose safe points do that too).
import assert from "node:assert/strict";
import { assemble, actual } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const MiB = 1 << 20, GiB = 2 ** 30;
const memory_size = 64 * MiB, high = 16 * MiB;
const EXTENDED = (+process.env.EXTENDED_GIB || 6) * GiB;
const EXT = 4 * GiB + high;                  // first extended byte
const KEY = 0x5A5A5A5A12345678n;
const DENSE = EXT + GiB, DENSE_BYTES = 32 * MiB;
const DMA = EXT + 2 * GiB + MiB + 0x4000;   // (between the 64 KiB samples)
const HOT = EXT + 3 * GiB + 0x200000;       // the hot loop's page
const EVICT = EXT + 3 * GiB + 16 * MiB;     // 16 MiB touched to evict every frame
const HOT_ITERATIONS = 3000;
assert.ok(EXTENDED >= 6 * GiB, "the fixture's addresses need at least 6 GiB");

const hex = n => "0x" + n.toString(16);
// Identity map [4 GiB, 12 GiB) with 2 MiB pages: PDs at 0x210000.., PDPT[4..11];
// linear 1 GiB (PDPT[1], PD at 0x218000) -> EXT + 2 GiB for compatibility mode.
const body = `
mov rdi, 0x210000
mov rax, 0x100000083
mov ecx, 8 * 512
.map:
mov [rdi], rax
add rax, 0x200000
add rdi, 8
dec ecx
jnz .map
mov rdi, 0x201020
mov rax, 0x210003
mov ecx, 8
.pdpt:
mov [rdi], rax
add rax, 0x1000
add rdi, 8
loop .pdpt
mov rax, ${hex(EXT + 2 * GiB)} | 0x83
mov [0x218000], rax
mov qword [0x201008], 0x218003
mov rax, cr3
mov cr3, rax

; 1. a qword every 64 KiB of extended RAM, then check them all
mov rbx, ${hex(EXT)}
mov r8, ${hex(EXTENDED)}
mov r9, ${hex(KEY)}
xor rcx, rcx
.sample_write:
lea rdi, [rbx + rcx]
mov rax, rdi
xor rax, r9
mov [rdi], rax
add rcx, 0x10000
cmp rcx, r8
jb .sample_write
xor rcx, rcx
xor r10, r10
.sample_check:
lea rdi, [rbx + rcx]
mov rax, rdi
xor rax, r9
cmp [rdi], rax
je .sample_ok
inc r10
.sample_ok:
add rcx, 0x10000
cmp rcx, r8
jb .sample_check
mov [0x300008], r10

; 2. dense: 32 MiB of qwords i * K, checked; then 1 MiB copied inside
;    extended RAM and 8 KiB out of it with REP MOVSQ
mov rdi, ${hex(DENSE)}
mov ecx, ${DENSE_BYTES / 8}
xor rdx, rdx
mov r11, 0x9E3779B97F4A7C15
.dense_write:
mov [rdi], rdx
add rdx, r11
add rdi, 8
dec ecx
jnz .dense_write
mov rdi, ${hex(DENSE)}
mov ecx, ${DENSE_BYTES / 8}
xor rdx, rdx
xor r10, r10
.dense_check:
cmp [rdi], rdx
je .dense_ok
inc r10
.dense_ok:
add rdx, r11
add rdi, 8
dec ecx
jnz .dense_check
mov [0x300010], r10
mov rsi, ${hex(DENSE)}
mov rdi, ${hex(DENSE + DENSE_BYTES)}
mov ecx, ${MiB / 8}
rep movsq
mov rsi, ${hex(DENSE + 8 * MiB)}
mov rdi, 0x380000
mov ecx, 8192 / 8
rep movsq

; 3. code in extended RAM
lea rsi, [rel ext_code]
mov rdi, ${hex(EXT + 3 * GiB + 0x123000)}
mov ecx, ext_code_end - ext_code
rep movsb
mov rax, ${hex(EXT + 3 * GiB + 0x123000)}
call rax
mov [0x300018], rax

; 4. page tables in extended RAM: copy PML4, PDPT, the low PD and the 8
;    PDs, point them at each other there, and touch a fresh page through them
mov rbp, ${hex(EXT + 4 * GiB)}
mov rsi, 0x200000
mov rdi, rbp
mov ecx, 0x3000 / 8
rep movsq
mov rsi, 0x210000
lea rdi, [rbp + 0x10000]
mov ecx, 0x9000 / 8
rep movsq
lea rax, [rbp + 0x1003]
mov [rbp], rax
mov [rbp + 0x800], rax
lea rax, [rbp + 0x2003]
mov [rbp + 0x1000], rax
lea rax, [rbp + 0x18003]
mov [rbp + 0x1008], rax
lea rax, [rbp + 0x10003]
lea rdi, [rbp + 0x1020]
mov ecx, 8
.remap:
mov [rdi], rax
add rax, 0x1000
add rdi, 8
loop .remap
mov cr3, rbp
; linear EXT + 5 GiB through the copies; then its PD entry there
mov rdi, ${hex(EXT + 5 * GiB)}
mov rax, 0x0123456789ABCDEF
mov [rdi], rax
mov rax, [rdi]
mov [0x300020], rax
mov rax, [rbp + 0x10000 + ${((EXT + 5 * GiB - 4 * GiB) / (2 * MiB)) * 8}]
mov [0x300028], rax
mov rax, cr3
mov [0x300030], rax
mov rax, 0x200000
mov cr3, rax

; 5. compatibility mode: 32-bit code at linear 1 GiB, which is extended RAM
lea rsi, [rel compat_code]
mov rdi, 0x40000000
mov ecx, compat_code_end - compat_code
rep movsb
sub rsp, 8
mov dword [rsp], compat_return
mov dword [rsp + 4], 24
push 8
push 0x40000000
retfq
compat_return:
mov rax, HIGH + compat_back
jmp rax
compat_back:

; 6. the block the host wrote by DMA: sum of its qwords
mov rsi, ${hex(DMA)}
mov ecx, 4096 / 8
xor rax, rax
.dma_sum:
add rax, [rsi]
add rsi, 8
loop .dma_sum
mov [0x300048], rax
; and a block for the host to read
mov rdi, ${hex(DMA + 4096)}
mov ecx, 4096 / 8
mov rax, 0x1111111111111111
.dma_fill:
mov [rdi], rax
mov rdx, 0x0101010101010101
add rax, rdx
add rdi, 8
loop .dma_fill

; 7. a hot loop in extended RAM (compiled by the page tier), rewritten
lea rsi, [rel hot_code]
mov rdi, ${hex(HOT)}
mov ecx, hot_code_end - hot_code
rep movsb
mov rbx, ${hex(HOT)}
xor edi, edi
call rbx
mov [0x300050], rax
; its immediate, from low code
mov dword [rbx + hot_imm - 4 - hot_code], 0x01020304
xor edi, edi
call rbx
mov [0x300058], rax
; every frame evicted: the compiled loop stays valid
mov rdi, ${hex(EVICT + 0x800)}
mov ecx, 16 * 256
.evict:
mov [rdi], rcx
add rdi, 4096
loop .evict
xor edi, edi
call rbx
mov [0x300060], rax
; with REP MOVSB into the page (not resident), then the loop rewrites
; itself: the ADD after its store must see the new immediate
lea rsi, [rel hot_patch]
lea rdi, [rbx + hot_imm - 4 - hot_code]
mov ecx, 4
rep movsb
mov edi, 0x55
call rbx
mov [0x300068], rax
mov edi, 0x66
call rbx
mov [0x300070], rax
`;
const data = `
ext_code:
lea rax, [rel ext_code]
add rax, 7
ret
ext_code_end:
hot_code:
xor eax, eax
mov ecx, ${HOT_ITERATIONS}
hot_loop:
add rax, strict dword 0x11111111
hot_imm:
dec ecx
jnz hot_loop
test edi, edi
jz hot_done
mov [rel hot_site + 2], edi
hot_site:
add rax, strict dword 0
hot_done:
ret
hot_code_end:
hot_patch:
dd 0x0A0B0C0D
bits 32
compat_code:
mov dword [0x40180000], 0x11111111
add dword [0x40180000], 0x22222222
mov dword [0x40180004], 0
lock add dword [0x40180004], 5
mov esi, 0x40180000
mov edi, 0x40180100
mov ecx, 16
rep movsd
mov eax, [0x40180100]
mov [0x300040], eax
mov eax, [0x40180004]
mov [0x300044], eax
retf
compat_code_end:
bits 64
`;
const source = long_mode_guest(body, data);
const directory = assemble("extended-memory", source);

const dma_block = new Uint8Array(4096);
for(let i = 0; i < dma_block.length; i++) dma_block[i] = i * 7 + 3;
const dma_sum = (() => {
    let sum = 0n;
    const view = new DataView(dma_block.buffer);
    for(let i = 0; i < 4096; i += 8) sum += view.getBigUint64(i, true);
    return sum & (1n << 64n) - 1n;
})();
const options = { memory_size, high_memory_size: high, extended_memory_size: EXTENDED, extended_memory_cache: 4 * MiB };
const u64_at = (bytes, offset) => new DataView(bytes.buffer, bytes.byteOffset).getBigUint64(offset, true);
const dense_expected = i => BigInt.asUintN(64, BigInt(i) * 0x9E3779B97F4A7C15n);

function check_host_view(cpu, label)
{
    for(const offset of [0, 0x10000, 1.5 * GiB, 5 * GiB - 0x10000, EXTENDED - 0x10000])
    {
        const address = EXT + offset;
        assert.equal(u64_at(cpu.read_blob_physical(address, 8), 0), BigInt(address) ^ KEY, `${label}: sample at ${hex(address)}`);
    }
    const dense = cpu.read_blob_physical(DENSE + 3 * MiB, 64 * 1024);
    for(let i = 0; i < dense.length; i += 8)
    {
        assert.equal(u64_at(dense, i), dense_expected((3 * MiB + i) / 8), `${label}: dense qword ${i}`);
    }
    const copied = cpu.read_blob_physical(DENSE + DENSE_BYTES, 4096);
    assert.deepEqual(copied, cpu.read_blob_physical(DENSE, 4096), `${label}: REP MOVSQ inside extended RAM`);
    const filled = cpu.read_blob_physical(DMA + 4096, 4096);
    assert.equal(u64_at(filled, 8), 0x1212121212121212n, `${label}: guest block read by the host`);
}

const results = [];
let snapshot = null;
for(const jit of [false, true])
{
    let stats;
    const result = await actual(directory, {
        length: 0x78, timeout: 600000,
        options: { ...options, disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: true },
        setup: emulator => { emulator.v86.cpu.write_blob_physical(dma_block, DMA); },
        inspect: async emulator => {
            const cpu = emulator.v86.cpu;
            check_host_view(cpu, jit ? "page tier" : "interpreter");
            const low = cpu.mem8.subarray(0x380000, 0x380000 + 8192);
            for(let i = 0; i < 8192; i += 8) assert.equal(u64_at(low, i), dense_expected((8 * MiB + i) / 8), "REP MOVSQ out of extended RAM");
            stats = Array.from({ length: 16 }, (_, i) => cpu.wm.exports.x64_ext_stat(i));
            if(jit)
            {
                const chunks = [];
                await emulator.save_state_stream(chunk => { chunks.push(chunk.slice()); });
                const total = chunks.reduce((n, chunk) => n + chunk.length, 0);
                snapshot = new Uint8Array(total);
                let at = 0;
                for(const chunk of chunks) { snapshot.set(chunk, at); at += chunk.length; }
            }
        },
    });
    const u64 = offset => result.readBigUInt64LE(offset);
    assert.equal(u64(0) & 0xFFFFFFFFn, 0xC064C064n, "guest completed");
    assert.equal(u64(8), 0n, "samples across extended RAM");
    assert.equal(u64(16), 0n, "dense patterns under eviction");
    assert.equal(u64(24), BigInt(EXT + 3 * GiB + 0x123000 + 7), "code fetched and executed in extended RAM");
    assert.equal(u64(32), 0x0123456789ABCDEFn, "access through page tables in extended RAM");
    assert.equal(u64(40) & 0x60n, 0x60n, "accessed and dirty set in the extended PD entry");
    assert.equal(u64(48), BigInt(EXT + 4 * GiB), "CR3 in extended RAM");
    assert.equal(result.readUInt32LE(0x40), 0x33333333, "compatibility-mode code in extended RAM");
    assert.equal(result.readUInt32LE(0x44), 5, "LOCK ADD in compatibility mode");
    assert.equal(u64(0x48), dma_sum, "the host's DMA block");
    const hot = (imm, site) => BigInt.asUintN(64, BigInt(HOT_ITERATIONS) * imm + site);
    assert.equal(u64(0x50), hot(0x11111111n, 0n), "hot loop in extended RAM");
    assert.equal(u64(0x58), hot(0x01020304n, 0n), "hot loop rewritten from low code");
    assert.equal(u64(0x60), hot(0x01020304n, 0n), "hot loop after its frame was evicted");
    assert.equal(u64(0x68), hot(0x0A0B0C0Dn, 0x55n), "hot loop rewritten by REP MOVSB and by itself");
    assert.equal(u64(0x70), hot(0x0A0B0C0Dn, 0x66n), "hot loop rewriting itself again");
    // (each rewrite found the page compiled: the loop runs 9000 instructions)
    if(jit) assert.ok(stats[15] >= 4, "page-tier code in extended RAM retired by writes: " + stats);
    else assert.equal(stats[15], 0, "no page-tier code without the JIT");
    assert.ok(stats[3] > 10000, "the frame pool was reused: " + stats);
    // (frames held by access caches are released at safe points, so that
    // eviction goes on and almost no access needs the bounce frame)
    if(jit) assert.ok(stats[8] > 0, "cached frames released: " + stats);
    assert.ok(stats[9] < stats[1] / 10, "bounce accesses are rare: " + stats);
    results.push(result);
    console.log(`${jit ? "page tier" : "interpreter"}: extended RAM ${EXTENDED / GiB} GiB, frames ${stats[7]}; ` +
        `hits ${stats[0]}, loads ${stats[1]}, write-backs ${stats[2]}, evictions ${stats[3]}, aperture ${stats[4]}, ` +
        `releases ${stats[8]}, bounces ${stats[9]}, code retired by writes ${stats[15]}`);
}
assert.deepEqual(results[1], results[0], "page tier and interpreter agree");

// the snapshot stream carries extended RAM into another machine
{
    const emulator = new V86({ graphics_adapter: "bochs_vga", multiboot: { url: directory + "guest.bin" }, acpi: true, autostart: false, log_level: 0,
        cpu_cores: Number(process.env.X64_CORES || 1), ...options });
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    await emulator.restore_state_stream({ size: snapshot.length, read: async (offset, length) => snapshot.subarray(offset, offset + length) });
    check_host_view(emulator.v86.cpu, "restored");
    await emulator.destroy();
    console.log(`snapshot stream: ${(snapshot.length / MiB).toFixed(1)} MiB restored into another machine`);
}
console.log("X64_EXTENDED_MEMORY_PASS");
                                                                                                                                                                                       source/v64/tests/x64/fma.mjs                                                                        0000644 0000000 0000000 00000040310 00000000000 012723  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// FMA and F16C in the x64 engine (docs/simd-xsave-plan.md 9.3, P11): every
// form in 64-bit mode with XMM0-15 (VEX.R, VEX.B and VEX.vvvv's top bit),
// aliased operands and memory operands, and in compatibility mode, against
// QEMU and tests/rust/sse_fp_model.mjs (through tests/rust/fma_cases.mjs).
// Eight forms (each order, each negation, ADDSUB/SUBADD, both widths) go
// through every special triple of fma_cases (NaN payloads in two or three
// operands: the first of x, y, z wins; 0 × ∞ with a QNaN, an SNaN or a
// number added; signed zeros, overflow, underflow, denormals) under three
// MXCSR settings; the others through random and special values. MXCSR's
// exceptions are masked there; the faults (#XM, destination unchanged) come
// with every exception unmasked. The cases run in rounds: interpreted, then
// with the x64 page tier, then also with the page tier in compatibility mode.
// QEMU 10.2 deviates from the SDM for F16C's denormals: VCVTPH2PS of a
// denormal half reports DE and, with DAZ, gives zero (the SDM: DAZ is
// ignored, and no denormal exception is reported); VCVTPS2PH flushes a tiny
// result to zero with FZ (the SDM: FZ is ignored, a tiny result is a half
// denormal). Those cases compare QEMU's MXCSR without DE; VCVTPH2PS's with
// DAZ or with DE unmasked (QEMU raises #XM) and VCVTPS2PH's with FZ are
// judged by the SDM alone. Nor does QEMU raise #XM for unmasked exceptions:
// the fault cases are judged by the model alone.
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {FMA_FORMS, F16C_FORMS, fma_cases, fma_expect, f16c_cases} from "../rust/fma_cases.mjs";

const OUT = 0x300000, CASE = OUT + 0x80, SKIP = OUT + 0x84, COUNTER = OUT + 0x88, FAULTS = OUT + 0x100, RESULTS = OUT + 0x2000, IDT = 0x380000;
// (the cases run in rounds, so that the last ones run compiled: the page tier
// compiles a page after 2000 visits)
const ROUNDS = 400, COMPAT_ROUNDS = 4000;
const SLOT = 48;
// (MXCSR: exceptions masked; nearest, nearest with PE set (where native FMA
// is admitted: x86tpl::native_fp::fused), down and DAZ|FZ, up)
const MASKED = [0x1F80, 0x1FA0, 0x3FA0, 0x9FE0 | 0x4000];
const FULL = ["vfmadd132sd", "vfmadd213ss", "vfmadd231pd", "vfnmsub132ss", "vfmsub213sd", "vfnmadd231ps ymm", "vfmaddsub132ps", "vfmsubadd231pd ymm"];

let seed = 0x0BADF00D;
const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
const pick = list => list[random() % list.length];
const hex = (v, bytes) => Array.from({length: bytes}, (_, i) => "0x" + Number(v >> BigInt(8 * i) & 0xFFn).toString(16)).join(",");

// The cases: {form, long, a, b, c (or source, imm8), mxcsr, registers A, B, C, memory, expected {result, after, fault}}
const cases = [];
for(const form of FMA_FORMS)
{
    const full = FULL.includes(form.name);
    const list = fma_cases(form, full ? MASKED : [pick(MASKED)], full ? 2 : 2);
    const chosen = full ? list : [list[0], list[list.length - 1], list[list.length - 2], list[random() % list.length]];
    for(const [k, c] of chosen.entries())
    {
        for(const long of full ? [true] : [true, false])
        {
            if(!long && k > 1) continue;
            const regs = long ? 16 : 8, memory = k % 2 === 1;
            // (registers: distinct, but in some cases the third source is VEX.vvvv's or the destination)
            let A = random() % regs, B = random() % regs, C = random() % regs;
            if(k % 5 === 4) C = B;
            else if(k % 7 === 6) C = A;
            else { while(B === A) B = random() % regs; while(C === A || C === B) C = random() % regs; }
            // (the operands as loaded in order A, B, C: an alias holds the last value)
            const value = r => r === C && !memory ? c.c : r === B ? c.b : c.a;
            const [a, b, cc] = [value(A), value(B), memory ? c.c : value(C)];
            cases.push({form, long, A, B, C, memory, a: c.a, b: c.b, c: c.c, mxcsr: c.mxcsr, expected: fma_expect(form, c.mxcsr, a, b, cc)});
        }
    }
}
for(const form of F16C_FORMS)
{
    const list = f16c_cases(form, MASKED, 6);
    for(const [k, c] of list.entries())
    {
        for(const long of k < 12 ? [true, false] : [true])
        {
            const regs = long ? 16 : 8;
            const A = random() % regs;
            let C = random() % regs;
            while(C === A) C = random() % regs;
            cases.push({form, long, A, C, memory: k % 2 === 1, source: c.source, imm8: c.imm8, mxcsr: c.mxcsr, expected: c});
        }
    }
}
// Faults: every exception unmasked (and the defaults, no fault), on special operands
const UNMASKED = 0;
for(const name of ["vfmadd132sd", "vfnmsub231ps", "vfmaddsub213pd ymm", "vfmsub132ss"])
{
    const form = FMA_FORMS.find(f => f.name === name);
    for(const c of fma_cases(form, [UNMASKED], 0).filter((_, n) => n % 3 === 0))
        cases.push({form, long: true, A: 1, B: 9, C: 14, memory: false, a: c.a, b: c.b, c: c.c, mxcsr: UNMASKED, expected: fma_expect(form, UNMASKED, c.a, c.b, c.c)});
}
for(const form of F16C_FORMS)
    for(const c of f16c_cases(form, [UNMASKED], 6))
        cases.push({form, long: true, A: 3, C: 12, memory: false, source: c.source, imm8: c.imm8, mxcsr: UNMASKED, expected: c});

const xmm = (r, l) => (l ? "ymm" : "xmm") + r;
/** A case's code: MXCSR, the operands, the instruction (the handler skips it
 * on #XM), the destination's 256 bits and MXCSR to its slot */
const code = (c, n) => {
    const out = RESULTS + n * SLOT, data = `case_${n}`, l = c.form.l;
    const lines = [`mov dword [${CASE}],${n}`, `ldmxcsr [${data} + 96]`];
    let instruction, destination;
    if(c.form.op !== undefined)
    {
        lines.push(`vmovdqu ${xmm(c.A, 1)},[${data}]`, `vmovdqu ${xmm(c.B, 1)},[${data} + 32]`);
        if(!c.memory) lines.push(`vmovdqu ${xmm(c.C, 1)},[${data} + 64]`);
        const size = c.form.scalar ? (c.form.double ? "qword" : "dword") : l ? "yword" : "oword";
        const third = c.memory ? `${size} [${data} + 64]` : xmm(c.C, l && !c.form.scalar);
        const mnemonic = c.form.name.split(" ")[0];
        instruction = `${mnemonic} ${xmm(c.A, l)},${xmm(c.B, l)},${third}`;
        destination = xmm(c.A, 1);
    }
    else if(c.form.kind === "ph2ps")
    {
        lines.push(`vmovdqu ${xmm(c.A, 1)},[${data}]`);
        if(!c.memory) lines.push(`vmovdqu ${xmm(c.C, 1)},[${data} + 64]`);
        instruction = `vcvtph2ps ${xmm(c.A, l)},${c.memory ? `${l ? "oword" : "qword"} [${data} + 64]` : xmm(c.C, 0)}`;
        destination = xmm(c.A, 1);
    }
    else
    {
        lines.push(`vmovdqu ${xmm(c.A, 1)},[${data}]`, `vmovdqu ${xmm(c.C, 1)},[${data} + 64]`);
        instruction = `vcvtps2ph ${c.memory ? `${l ? "oword" : "qword"} [${data} + 64]` : xmm(c.C, 0)},${xmm(c.A, l)},${c.imm8}`;
        destination = c.memory ? null : xmm(c.C, 1);
    }
    lines.push(`mov dword [${SKIP}],skip_end${n} - skip${n}`, `skip${n}: ${instruction}`, `skip_end${n}:`);
    if(destination) lines.push(`vmovdqu [${out}],${destination}`);
    else lines.push(`vmovdqu ymm15,[${data} + 64]`.replace("ymm15", c.long ? "ymm15" : "ymm7"), `vmovdqu [${out}],${c.long ? "ymm15" : "ymm7"}`);
    lines.push(`stmxcsr [${out} + 32]`);
    return lines.join("\n");
};
/** A case's data: 128 bytes (A's, B's, C's 256 bits, MXCSR) */
const BEFORE256 = 0x5A5A5A5A_A5A5A5A5_12345678_9ABCDEF0n * (1n + (1n << 128n));
// (the operands' bits 255:128 for VEX.128 forms: a destination's are zeroed)
const UPPER = 0x0123456789ABCDEF_FEDCBA9876543210n << 128n;
const data = (c, n) => {
    let a, b, third;
    if(c.form.op !== undefined) [a, b, third] = c.form.l ? [c.a, c.b, c.c] : [c.a | UPPER, c.b | UPPER, c.c | UPPER];
    else if(c.form.kind === "ph2ps") [a, b, third] = [BEFORE256, 0n, c.source];
    else [a, b, third] = [c.source, 0n, BEFORE256];
    return `align 32\ncase_${n}: db ${hex(a, 32)}\ndb ${hex(b, 32)}\ndb ${hex(third, 32)}\ndd ${c.mxcsr}\ntimes 28 db 0`;
};
/** The slot the model expects: the destination's 256 bits, MXCSR */
const expected_slot = c => {
    const e = c.expected, l = c.form.l;
    let result;
    if(c.form.op !== undefined) result = e.fault ? c.a : e.result;
    else if(c.form.kind === "ph2ps") result = e.fault ? BEFORE256 : e.result;
    else
    {
        // (to memory: 8 or 16 bytes, the rest as before; to a register the rest zeroed)
        const written = l ? 128n : 64n;
        result = e.fault ? BEFORE256 : c.memory ? BEFORE256 & ~((1n << written) - 1n) | e.result : e.result;
    }
    // (a faulting FMA form's destination: as loaded, A's value unless aliased)
    if(c.form.op !== undefined && e.fault)
    {
        const loaded = c.A === c.C && !c.memory ? c.c : c.A === c.B ? c.b : c.a;
        result = c.form.l ? loaded : loaded | UPPER;
    }
    return {result, after: e.after, fault: e.fault};
};

const block = long => cases.map((c, n) => c.long === long ? code(c, n) : "").filter(Boolean).join("\n");
const directory = assemble("fma", long_mode_guest(`
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
xor ecx,ecx
mov eax,7
xor edx,edx
xsetbv
mov ebx,19
mov rax,HIGH+xm
call set_gate
mov ebx,6
mov rax,HIGH+ud
call set_gate
lidt [rel idtr]
mov dword [${COUNTER}],${ROUNDS}
rounds64:
${block(true)}
dec dword [${COUNTER}]
jnz rounds64
; compatibility mode
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov dword [${COUNTER}],${COMPAT_ROUNDS}
rounds32:
${block(false)}
dec dword [${COUNTER}]
jnz rounds32
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
xm:
mov ecx,19
record:
mov edx,[${CASE}]
mov [${FAULTS} + rdx * 4],ecx
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
${cases.map(data).join("\n")}
`));

assert.ok(cases.length * 4 <= RESULTS - FAULTS, "the faults' table fits");
const length = RESULTS - OUT + cases.length * SLOT;
/** VCVTPH2PS of a denormal half (see above: QEMU reports DE) */
const denormal_half = c => c.form.kind === "ph2ps" && [0, 1, 2, 3, 4, 5, 6, 7].some(i => {
    const h = c.source >> BigInt(16 * i) & 0xFFFFn;
    return (h & 0x7C00n) === 0n && (h & 0x3FFn) !== 0n;
});
const check = (result, label) => {
    cases.forEach((c, n) => {
        const qemu_de = label === "QEMU" && denormal_half(c);
        if(qemu_de && ((c.mxcsr & 0x100) === 0 || (c.mxcsr & 0x40) !== 0)) return;
        if(label === "QEMU" && c.form.kind === "ps2ph" && (c.mxcsr & 0x8000) !== 0) return;
        if(label === "QEMU" && c.mxcsr === UNMASKED) return;
        const {result: want, after, fault} = expected_slot(c);
        const got = result.subarray(RESULTS - OUT + n * SLOT, RESULTS - OUT + n * SLOT + 32);
        const operands = c.form.op !== undefined ? `a ${c.a.toString(16)} b ${c.b.toString(16)} c ${c.c.toString(16)} (registers ${c.A} ${c.B} ${c.C})` : `source ${c.source.toString(16)} imm8 ${c.imm8}`;
        const what = `${label}: ${c.long ? "64-bit" : "compatibility"} ${c.form.name}${c.memory ? " [mem]" : ""} case ${n}, mxcsr ${c.mxcsr.toString(16)}, ${operands}`;
        assert.equal(result.readUInt32LE(FAULTS - OUT + n * 4), fault ? 19 : 0, `${what}: fault`);
        const value = Array.from(got).reduceRight((v, x) => v << 8n | BigInt(x), 0n);
        assert.equal(value.toString(16), want.toString(16), `${what}: result`);
        const mxcsr = result.readUInt32LE(RESULTS - OUT + n * SLOT + 32);
        assert.equal(qemu_de ? mxcsr & ~2 : mxcsr, after, `${what}: MXCSR`);
    });
};
const expected_qemu = await reference(directory, {length});
check(expected_qemu, "QEMU");
const FEATURES = {cpu_type: "x86_64", cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "FMA", "F16C"], cpu_features_unreleased: true};
for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}],
    // (compatibility-mode code in the page tier, docs/jit-unification-plan.md P7.2)
    ["x64 page tier, compat32", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        jit_switches: {x64_page_compat32: 1}}]])
{
    let page = 0, page32 = 0;
    const result = await actual(directory, {length, timeout: 180000, options: {...FEATURES, ...options},
        inspect: emulator => {
            page = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            page32 = emulator.v86.cpu.wm.exports.x64_page_stat(36);
        }});
    check(result, label);
    if(options.disable_jit === false) assert.ok(page > 1000, `${label}: compiled 64-bit code ran (${page})`);
    if(options.jit_switches?.x64_page_compat32) assert.ok(page32 > 0, `${label}: the page tier compiled compatibility-mode code (${page32})`);
    console.log(`PASS (${label}): ${cases.length} FMA and F16C cases in 64-bit and compatibility mode (XMM0-15, aliased and memory operands, faults), as the model and QEMU`);
}

// The page tier's templates for FMA (P11 part 2): a hot loop of the hot forms
// (VFMADD213SD, VFMADD132SD, VFMADD231SD, VFMSUB132SD, VFMSUB231SD,
// VFMADD132PD, VFMADD213PD, VFMADD213SS) and siblings, register and memory
// operands, on ordinary values (no exceptions), runs with almost no steps
// (x64_page_stat(4)), the sums of every round as QEMU's. PE is set after the
// first rounding: where the host's relaxed multiply-adds fuse
// (ir_relaxed_fma), natively (x86tpl::native_fp::fused: the exact helper
// x64_fma only before), and again with them switched off (every FMA
// through the helper).
for(const native of [true, false])
{
    const ITERATIONS = 20000;
    const hot = assemble("fma-hot", long_mode_guest(`
mov rax,cr4
or eax,3 << 9 | 1 << 18 ; OSFXSR, OSXMMEXCPT, OSXSAVE
mov cr4,rax
xor ecx,ecx
mov eax,7
xor edx,edx
xsetbv
mov r15d,${ITERATIONS}
vxorpd xmm13,xmm13,xmm13
vxorpd xmm14,xmm14,xmm14
vxorpd xmm15,xmm15,xmm15
.loop:
vcvtsi2sd xmm0,xmm0,r15d
vmulsd xmm0,xmm0,[rel scale]
vmovsd xmm1,[rel c4]
vfmadd213sd xmm1,xmm0,[rel c3]
vfmadd213sd xmm1,xmm0,[rel c2]
vmovsd xmm2,[rel c1]
vfmadd231sd xmm2,xmm1,xmm0
vmovapd xmm3,xmm0
vfmadd132sd xmm3,xmm2,[rel c0]
vfmsub132sd xmm3,xmm1,xmm0
vfmsub231sd xmm3,xmm2,[rel c1]
vfnmadd213sd xmm3,xmm0,xmm2
vaddsd xmm15,xmm15,xmm3
vmovapd xmm4,xmm0
vmovupd xmm5,[rel pd]
vfmadd132pd xmm5,xmm4,[rel pd2]
vfmadd213pd xmm5,xmm4,xmm4
vfnmsub231pd xmm5,xmm4,[rel pd]
vaddpd xmm14,xmm14,xmm5
vcvtsd2ss xmm6,xmm6,xmm0
vmovss xmm7,[rel s1]
vfmadd213ss xmm7,xmm6,[rel s2]
vfmsub231ss xmm7,xmm6,xmm6
vfmaddsub213ps xmm7,xmm6,xmm7
vaddss xmm13,xmm13,xmm7
dec r15d
jnz .loop
vmovupd [${OUT + 16}],xmm15
vmovupd [${OUT + 32}],xmm14
vmovupd [${OUT + 48}],xmm13
`, `
align 16
scale: dq 0.0001
c0: dq 1.0
c1: dq 0.5
c2: dq 0.16666666666666666
c3: dq 0.041666666666666664
c4: dq 0.008333333333333333
pd: dq 0.75, -1.25
pd2: dq 3.0, 0.125
s1: dd 1.5
s2: dd -0.375
`));
    const length = 64;
    const expected = await reference(hot, {length});
    let steps, retired, calls, relaxed;
    const result = await actual(hot, {length, timeout: 60000,
        options: {...FEATURES, disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        setup: emulator => {
            const e = emulator.v86.cpu.wm.exports;
            relaxed = e.ir_relaxed_fma() === 1 && native;
            e.ir_set_relaxed_fma(+relaxed);
            e.x64_fma_calls_reset();
        },
        inspect: emulator => {
            steps = emulator.v86.cpu.wm.exports.x64_page_stat(4);
            retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            calls = emulator.v86.cpu.wm.exports.x64_fma_calls();
        }});
    if(native && !relaxed) continue;
    assert.equal(Buffer.from(result.subarray(16, 64)).toString("hex"), Buffer.from(expected.subarray(16, 64)).toString("hex"), "hot loop: the sums as QEMU");
    assert.ok(retired > ITERATIONS * 20 && steps < ITERATIONS / 10, `page tier templates: ${retired} retired, ${steps} steps`);
    // (13 FMA instructions per iteration)
    assert.ok(relaxed ? calls < ITERATIONS / 10 : calls > ITERATIONS * 10, `${calls} exact helper calls (${relaxed ? "native" : "exact"} FMA)`);
    console.log(`PASS (x64 page tier): the hot FMA forms' templates (${relaxed ? "native, relaxed multiply-adds" : "the exact helper"}), as QEMU (${retired} instructions retired natively, ${steps} steps, ${calls} helper calls)`);
}
                                                                                                                                                                                                                                                                                                                        source/v64/tests/x64/frame_buffer.mjs                                                               0000644 0000000 0000000 00000013412 00000000000 014606  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The x64 page tier writes device memory (the VGA frame buffer,
// src/rust/cpu/mmio_ram.rs) directly once a write translation of it is
// cached: the page is marked written when the translation is filled, and the
// translation is retired when the screen takes the written pages, so the next
// write marks the page again. When the guest moves the BAR, cached
// translations of the old place must go: writes there reach nothing.
//
// A long-mode guest runs one hot store loop (compiled into a page function)
// four times; the host draws the screen and moves BAR0 in between.
import assert from "node:assert/strict";
import {assemble} from "./guest_runner.mjs";

const STATUS = 0x300000;    // guest: the phase it finished; host: the phase it may start
const NEW_BASE = 0x300008;  // host: where BAR0 went
const source = `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr32]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x3F0000
; identity map: 0-1 GiB, and the 2 MiB pages of the frame buffer in 3-4 GiB
mov dword [0x200000],0x201007
mov dword [0x201000],0x202007
mov dword [0x201000+3*8],0x203003
mov edi,0x202000
mov eax,0x83
mov ecx,512
.low:
mov [edi],eax
add eax,0x200000
add edi,8
loop .low
; BAR0 of the VGA (PCI 00:12.0)
mov dx,0xCF8
mov eax,0x80000000 | 0x12 << 11 | 0x10
out dx,eax
mov dx,0xCFC
in eax,dx
and eax,~0xF
mov [lfb],eax
call map_lfb
; 64x48, 32 bpp, linear frame buffer (Bochs VBE)
mov dx,0x1CE
mov ax,4
out dx,ax
mov dx,0x1CF
mov ax,0
out dx,ax
mov dx,0x1CE
mov ax,1
out dx,ax
mov dx,0x1CF
mov ax,64
out dx,ax
mov dx,0x1CE
mov ax,2
out dx,ax
mov dx,0x1CF
mov ax,48
out dx,ax
mov dx,0x1CE
mov ax,3
out dx,ax
mov dx,0x1CF
mov ax,32
out dx,ax
mov dx,0x1CE
mov ax,4
out dx,ax
mov dx,0x1CF
mov ax,0x41
out dx,ax
mov eax,cr4
or eax,0x20
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x100
xor edx,edx
wrmsr
mov eax,cr0
or eax,0x80000001
mov cr0,eax
jmp 24:long_mode

; the four 2 MiB pages of the 8 MiB frame buffer at [lfb]
map_lfb:
mov eax,[lfb]
mov edi,eax
sub edi,0xC0000000
shr edi,21
lea edi,[0x203000+edi*8]
or eax,0x83
mov ecx,4
.map:
mov [edi],eax
add eax,0x200000
add edi,8
loop .map
ret

bits 64
long_mode:
mov esi,[lfb]
mov eax,0x00112233
call fill
mov edi,1
call phase
mov eax,0x00AABBCC
call fill
mov edi,2
call phase
; BAR0 moved: the old place first, then the new one
mov eax,0x00445566
call fill
mov edi,3
call phase
; (the host has mapped the new place)
mov rax,cr3
mov cr3,rax
mov esi,[NEW_BASE]
mov eax,0x00778899
call fill
mov edi,4
call phase
.halt:
hlt
jmp .halt

; the hot loop: 1024 pixels at rsi, many times over
fill:
mov ecx,300000
.loop:
mov edx,ecx
and edx,1023
mov [rsi+rdx*4],eax
dec ecx
jnz .loop
ret

; report phase edi done, wait until the host lets phase edi + 1 start
phase:
mov [${STATUS}],edi
.wait:
pause
cmp dword [${STATUS}+4],edi
jne .wait
ret

align 8
lfb: dd 0
gdt:
dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
gdtr32: dw 31
dd gdt
image_end:
`.replace("[NEW_BASE]", `[${NEW_BASE}]`);

const directory = assemble("frame-buffer", source);
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const emulator = new V86({graphics_adapter: "bochs_vga", multiboot: {url: directory + "guest.bin"}, memory_size: 32 << 20, acpi: true,
    disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true, autostart: false, log_level: 0});
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu, io = cpu.io, vga = cpu.devices.vga;
const word = address => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(address, true);
const set_word = (address, value) => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).setUint32(address, value, true);
const run_until = phase => {
    const deadline = performance.now() + 60000;
    while(word(STATUS) !== phase)
    {
        assert.ok(performance.now() < deadline, "the guest did not finish phase " + phase);
        cpu.run_cores();
    }
};
const pixel = (x, y) => {
    cpu.devices.display.request_frame();
    const p = (y * vga.pixels.width + x) * 4;
    return [...vga.pixels.data.subarray(p, p + 3)].map(v => v.toString(16).padStart(2, "0")).join("");
};
const lfb_fills = () => cpu.wm.exports["x64_page_stat"](17);

run_until(1);
assert.ok(lfb_fills() > 0, "the page tier translated frame buffer pages for direct access");
assert.equal(pixel(5, 0), "112233", "direct writes marked their page: drawn");
console.log(`PASS: page functions write the frame buffer directly (${lfb_fills()} translations)`);

set_word(STATUS + 4, 1);
run_until(2);
// No screen update since phase 2's writes: the loop's write translation is
// still cached (and its page marked) when the BAR moves
const old_base = vga.lfb_address;
const new_base = old_base + (16 << 20) >>> 0;
io.port_write32(0xcf8, 0x80000000 | 0x12 << 11 | 0x10);
io.port_write32(0xcfc, new_base);
assert.equal(vga.lfb_address, new_base);
set_word(NEW_BASE, new_base);
// map the new place for the guest: 2 MiB pages in its 3-4 GiB directory
for(let k = 0; k < 4; k++) set_word(0x203000 + ((new_base - 0xC0000000 >>> 21) + k) * 8, new_base + k * (2 << 20) | 0x83);
set_word(STATUS + 4, 2);
run_until(3);
assert.equal(pixel(5, 0), "aabbcc",
    "phase 2 marked its page again after the screen took it, and phase 3's writes to the old place reached nothing");
console.log("PASS: pages are marked again after the screen took them; a moved BAR drops cached translations");

set_word(STATUS + 4, 3);
run_until(4);
assert.equal(pixel(5, 0), "778899", "writes to the new place are drawn");
console.log(`PASS: the frame buffer is drawn from its new place (${old_base.toString(16)} -> ${new_base.toString(16)})`);
await emulator.destroy();
                                                                                                                                                                                                                                                      source/v64/tests/x64/gltest.c                                                                       0000644 0000000 0000000 00000214025 00000000000 013121  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GLES 3.0 conformance-ish tests for the x86_64 Linux guest's GPU drivers
// (tests/x64/linux_gpu.mjs): each test draws into a 64 x 64 framebuffer
// object (or captures numbers) on EGL's surfaceless platform, then
//
//     LIBGL_ALWAYS_SOFTWARE=1 gltest ref     the images of llvmpipe, into /tmp/gltest-ref/
//     gltest cmp                             the driver's, compared with them
//
// prints "GLTEST <name> ok|FAIL max=<largest channel difference> bad=<pixels
// off by more than the tolerance>" and, for failures, both images as PPM in
// base64 ("GLIMG <name> <which> <chunk>") for the harness to save.
//
// Built without the C library's headers (the host has none for musl): the
// declarations it needs are here, it links against musl's libc and Mesa's
// libEGL from the guest's Alpine packages, and every GL function comes from
// eglGetProcAddress.

typedef unsigned int GLenum, GLuint, GLbitfield;
typedef int GLint, GLsizei;
typedef unsigned char GLubyte, GLboolean;
typedef float GLfloat;
typedef long GLintptr, GLsizeiptr;
typedef char GLchar;
typedef unsigned long GLuint64;
typedef struct GLsync_ *GLsync;
typedef unsigned long size_t;
typedef void *EGLDisplay, *EGLContext, *EGLConfig, *EGLSurface;
typedef int EGLint;
typedef unsigned int EGLBoolean, EGLenum;
typedef long EGLAttrib;

// the C library
int printf(const char *, ...);
int snprintf(char *, size_t, const char *, ...);
void *malloc(size_t);
void *calloc(size_t, size_t);
void free(void *);
void *memset(void *, int, size_t);
void *memcpy(void *, const void *, size_t);
int strcmp(const char *, const char *);
size_t strlen(const char *);
int open(const char *, int, ...);
long read(int, void *, size_t);
long write(int, const void *, size_t);
int close(int);
int mkdir(const char *, int);
void exit(int);
int fflush(void *);
#define O_RDONLY 0
#define O_WRONLY 1
#define O_CREAT 0100
#define O_TRUNC 01000

// EGL
EGLDisplay eglGetPlatformDisplay(EGLenum, void *, const EGLAttrib *);
EGLBoolean eglInitialize(EGLDisplay, EGLint *, EGLint *);
EGLBoolean eglBindAPI(EGLenum);
EGLContext eglCreateContext(EGLDisplay, EGLConfig, EGLContext, const EGLint *);
EGLBoolean eglMakeCurrent(EGLDisplay, EGLSurface, EGLSurface, EGLContext);
void *eglGetProcAddress(const char *);
EGLint eglGetError(void);
#define EGL_PLATFORM_SURFACELESS_MESA 0x31DD
#define EGL_OPENGL_ES_API 0x30A0
#define EGL_CONTEXT_MAJOR_VERSION 0x3098
#define EGL_CONTEXT_MINOR_VERSION 0x30FB
#define EGL_NONE 0x3038

// the start: what musl's crt1 does
int __libc_start_main(int (*)(int, char **, char **), int, char **, void (*)(void), void (*)(void), void (*)(void));
int main(int, char **, char **);
#if defined(__aarch64__)
// (the arm64 guest's, tests/a64/linux_gpu.mjs: the stack is 16-byte aligned at entry)
__asm__(".text\n.global _start\n_start:\n mov x29, #0\n mov x30, #0\n mov x0, sp\n bl start_c\n brk #0\n");
#else
__asm__(".text\n.global _start\n_start:\n xor %rbp, %rbp\n mov %rsp, %rdi\n andq $-16, %rsp\n call start_c\n hlt\n");
#endif
__attribute__((used)) void start_c(long *p)
{
    __libc_start_main(main, (int)p[0], (char **)(p + 1), 0, 0, 0);
}

// ---------------------------------------------------------------------------
// GL: functions from eglGetProcAddress, the constants used

#define GL_FUNCTIONS(F) \
    F(void, glClear, (GLbitfield)) F(void, glClearColor, (GLfloat, GLfloat, GLfloat, GLfloat)) \
    F(void, glClearDepthf, (GLfloat)) F(void, glClearStencil, (GLint)) F(void, glEnable, (GLenum)) F(void, glDisable, (GLenum)) \
    F(void, glScissor, (GLint, GLint, GLsizei, GLsizei)) F(void, glViewport, (GLint, GLint, GLsizei, GLsizei)) \
    F(GLenum, glGetError, (void)) F(const GLubyte *, glGetString, (GLenum)) F(void, glFinish, (void)) \
    F(void, glGenBuffers, (GLsizei, GLuint *)) F(void, glBindBuffer, (GLenum, GLuint)) \
    F(void, glBufferData, (GLenum, GLsizeiptr, const void *, GLenum)) F(void, glBufferSubData, (GLenum, GLintptr, GLsizeiptr, const void *)) \
    F(void, glDeleteBuffers, (GLsizei, const GLuint *)) F(void, glBindBufferBase, (GLenum, GLuint, GLuint)) \
    F(void *, glMapBufferRange, (GLenum, GLintptr, GLsizeiptr, GLbitfield)) F(GLboolean, glUnmapBuffer, (GLenum)) \
    F(GLuint, glCreateShader, (GLenum)) F(void, glShaderSource, (GLuint, GLsizei, const GLchar *const *, const GLint *)) \
    F(void, glCompileShader, (GLuint)) F(void, glGetShaderiv, (GLuint, GLenum, GLint *)) \
    F(void, glGetShaderInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) F(GLuint, glCreateProgram, (void)) \
    F(void, glAttachShader, (GLuint, GLuint)) F(void, glLinkProgram, (GLuint)) F(void, glGetProgramiv, (GLuint, GLenum, GLint *)) \
    F(void, glGetProgramInfoLog, (GLuint, GLsizei, GLsizei *, GLchar *)) F(void, glUseProgram, (GLuint)) \
    F(void, glDeleteProgram, (GLuint)) F(void, glDeleteShader, (GLuint)) \
    F(GLint, glGetUniformLocation, (GLuint, const GLchar *)) F(void, glUniform1i, (GLint, GLint)) \
    F(void, glUniform1f, (GLint, GLfloat)) F(void, glUniform4f, (GLint, GLfloat, GLfloat, GLfloat, GLfloat)) \
    F(GLuint, glGetUniformBlockIndex, (GLuint, const GLchar *)) F(void, glUniformBlockBinding, (GLuint, GLuint, GLuint)) \
    F(void, glTransformFeedbackVaryings, (GLuint, GLsizei, const GLchar *const *, GLenum)) \
    F(void, glBeginTransformFeedback, (GLenum)) F(void, glEndTransformFeedback, (void)) \
    F(void, glGenVertexArrays, (GLsizei, GLuint *)) F(void, glBindVertexArray, (GLuint)) \
    F(void, glDeleteVertexArrays, (GLsizei, const GLuint *)) \
    F(void, glVertexAttribPointer, (GLuint, GLint, GLenum, GLboolean, GLsizei, const void *)) \
    F(void, glVertexAttribIPointer, (GLuint, GLint, GLenum, GLsizei, const void *)) \
    F(void, glEnableVertexAttribArray, (GLuint)) F(void, glVertexAttribDivisor, (GLuint, GLuint)) \
    F(void, glDrawArrays, (GLenum, GLint, GLsizei)) F(void, glDrawElements, (GLenum, GLsizei, GLenum, const void *)) \
    F(void, glDrawArraysInstanced, (GLenum, GLint, GLsizei, GLsizei)) \
    F(void, glDrawElementsInstanced, (GLenum, GLsizei, GLenum, const void *, GLsizei)) \
    F(void, glGenTextures, (GLsizei, GLuint *)) F(void, glBindTexture, (GLenum, GLuint)) F(void, glActiveTexture, (GLenum)) \
    F(void, glDeleteTextures, (GLsizei, const GLuint *)) F(void, glTexParameteri, (GLenum, GLenum, GLint)) \
    F(void, glTexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) \
    F(void, glTexSubImage2D, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void *)) \
    F(void, glTexImage3D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const void *)) \
    F(void, glTexStorage2D, (GLenum, GLsizei, GLenum, GLsizei, GLsizei)) F(void, glGenerateMipmap, (GLenum)) \
    F(void, glPixelStorei, (GLenum, GLint)) \
    F(void, glGenFramebuffers, (GLsizei, GLuint *)) F(void, glBindFramebuffer, (GLenum, GLuint)) \
    F(void, glDeleteFramebuffers, (GLsizei, const GLuint *)) \
    F(void, glFramebufferTexture2D, (GLenum, GLenum, GLenum, GLuint, GLint)) \
    F(void, glFramebufferRenderbuffer, (GLenum, GLenum, GLenum, GLuint)) F(GLenum, glCheckFramebufferStatus, (GLenum)) \
    F(void, glGenRenderbuffers, (GLsizei, GLuint *)) F(void, glBindRenderbuffer, (GLenum, GLuint)) \
    F(void, glDeleteRenderbuffers, (GLsizei, const GLuint *)) \
    F(void, glRenderbufferStorage, (GLenum, GLenum, GLsizei, GLsizei)) \
    F(void, glRenderbufferStorageMultisample, (GLenum, GLsizei, GLenum, GLsizei, GLsizei)) \
    F(void, glDrawBuffers, (GLsizei, const GLenum *)) F(void, glReadBuffer, (GLenum)) \
    F(void, glReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void *)) \
    F(void, glBlitFramebuffer, (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum)) \
    F(void, glCopyTexSubImage2D, (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei)) \
    F(void, glBlendFunc, (GLenum, GLenum)) F(void, glBlendEquation, (GLenum)) \
    F(void, glBlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum)) F(void, glBlendColor, (GLfloat, GLfloat, GLfloat, GLfloat)) \
    F(void, glColorMask, (GLboolean, GLboolean, GLboolean, GLboolean)) F(void, glDepthFunc, (GLenum)) \
    F(void, glDepthMask, (GLboolean)) F(void, glStencilFunc, (GLenum, GLint, GLuint)) \
    F(void, glStencilOp, (GLenum, GLenum, GLenum)) F(void, glCullFace, (GLenum)) F(void, glFrontFace, (GLenum)) \
    F(void, glPolygonOffset, (GLfloat, GLfloat)) \
    F(void, glGenQueries, (GLsizei, GLuint *)) F(void, glBeginQuery, (GLenum, GLuint)) F(void, glEndQuery, (GLenum)) \
    F(void, glGetQueryObjectuiv, (GLuint, GLenum, GLuint *)) F(void, glDeleteQueries, (GLsizei, const GLuint *)) \
    F(void, glClearBufferfv, (GLenum, GLint, const GLfloat *)) F(void, glClearBufferuiv, (GLenum, GLint, const GLuint *)) \
    F(void, glTexBuffer, (GLenum, GLenum, GLuint)) \
    F(void, glDispatchCompute, (GLuint, GLuint, GLuint)) F(void, glMemoryBarrier, (GLbitfield)) \
    F(void, glBindImageTexture, (GLuint, GLuint, GLint, GLboolean, GLint, GLenum, GLenum)) \
    F(void, glPatchParameteri, (GLenum, GLint)) F(void, glUniform1ui, (GLint, GLuint)) \
    F(void, glUniform1d, (GLint, double)) \
    F(void, glDrawArraysIndirect, (GLenum, const void *)) F(void, glDrawElementsIndirect, (GLenum, GLenum, const void *)) \
    F(GLuint, glCreateShaderProgramv, (GLenum, GLsizei, const GLchar *const *)) \
    F(void, glTexImage2DMultisample, (GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean)) \
    F(void, glGetIntegerv, (GLenum, GLint *)) F(const GLubyte *, glGetStringi, (GLenum, GLuint)) \
    F(void, glBufferStorage, (GLenum, GLsizeiptr, const void *, GLbitfield)) \
    F(GLsync, glFenceSync, (GLenum, GLbitfield)) F(GLenum, glClientWaitSync, (GLsync, GLbitfield, GLuint64)) \
    F(void, glDeleteSync, (GLsync))

#define DECLARE(ret, name, args) static ret (*name) args;
GL_FUNCTIONS(DECLARE)

#define GL_COLOR_BUFFER_BIT 0x4000
#define GL_DEPTH_BUFFER_BIT 0x0100
#define GL_STENCIL_BUFFER_BIT 0x0400
#define GL_POINTS 0x0000
#define GL_LINES 0x0001
#define GL_LINE_STRIP 0x0003
#define GL_TRIANGLES 0x0004
#define GL_TRIANGLE_STRIP 0x0005
#define GL_TRIANGLE_FAN 0x0006
#define GL_BYTE 0x1400
#define GL_UNSIGNED_BYTE 0x1401
#define GL_SHORT 0x1402
#define GL_UNSIGNED_SHORT 0x1403
#define GL_INT 0x1404
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_HALF_FLOAT 0x140B
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_UNIFORM_BUFFER 0x8A11
#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E
#define GL_STATIC_DRAW 0x88E4
#define GL_STREAM_READ 0x88E1
#define GL_VERTEX_SHADER 0x8B31
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_TEXTURE_2D 0x0DE1
#define GL_TEXTURE_3D 0x806F
#define GL_TEXTURE_2D_ARRAY 0x8C1A
#define GL_TEXTURE_CUBE_MAP 0x8513
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
#define GL_TEXTURE_WRAP_R 0x8072
#define GL_TEXTURE_SWIZZLE_R 0x8E42
#define GL_TEXTURE_SWIZZLE_G 0x8E43
#define GL_TEXTURE_SWIZZLE_B 0x8E44
#define GL_TEXTURE_SWIZZLE_A 0x8E45
#define GL_TEXTURE_COMPARE_MODE 0x884C
#define GL_TEXTURE_COMPARE_FUNC 0x884D
#define GL_COMPARE_REF_TO_TEXTURE 0x884E
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
#define GL_LINEAR_MIPMAP_NEAREST 0x2701
#define GL_NEAREST_MIPMAP_NEAREST 0x2700
#define GL_REPEAT 0x2901
#define GL_CLAMP_TO_EDGE 0x812F
#define GL_MIRRORED_REPEAT 0x8370
#define GL_ALPHA 0x1906
#define GL_RGB 0x1907
#define GL_RGBA 0x1908
#define GL_LUMINANCE 0x1909
#define GL_LUMINANCE_ALPHA 0x190A
#define GL_RED 0x1903
#define GL_BLUE 0x1905
#define GL_RG 0x8227
#define GL_R8 0x8229
#define GL_RG8 0x822B
#define GL_R32F 0x822E
#define GL_RGBA8 0x8058
#define GL_RGBA16F 0x881A
#define GL_RGBA32F 0x8814
#define GL_RGBA8UI 0x8D7C
#define GL_R32UI 0x8236
#define GL_RGBA_INTEGER 0x8D99
#define GL_RED_INTEGER 0x8D94
#define GL_SRGB8_ALPHA8 0x8C43
#define GL_DEPTH_COMPONENT 0x1902
#define GL_DEPTH_COMPONENT16 0x81A5
#define GL_DEPTH_COMPONENT24 0x81A6
#define GL_DEPTH24_STENCIL8 0x88F0
#define GL_FRAMEBUFFER 0x8D40
#define GL_READ_FRAMEBUFFER 0x8CA8
#define GL_DRAW_FRAMEBUFFER 0x8CA9
#define GL_RENDERBUFFER 0x8D41
#define GL_COLOR_ATTACHMENT0 0x8CE0
#define GL_COLOR_ATTACHMENT1 0x8CE1
#define GL_DEPTH_ATTACHMENT 0x8D00
#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A
#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
#define GL_DEPTH_TEST 0x0B71
#define GL_STENCIL_TEST 0x0B90
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_TEST 0x0C11
#define GL_CULL_FACE 0x0B44
#define GL_RASTERIZER_DISCARD 0x8C89
#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69
#define GL_POLYGON_OFFSET_FILL 0x8037
#define GL_NEVER 0x0200
#define GL_LESS 0x0201
#define GL_EQUAL 0x0202
#define GL_LEQUAL 0x0203
#define GL_GREATER 0x0204
#define GL_NOTEQUAL 0x0205
#define GL_GEQUAL 0x0206
#define GL_ALWAYS 0x0207
#define GL_KEEP 0x1E00
#define GL_REPLACE 0x1E01
#define GL_INCR 0x1E02
#define GL_ZERO 0
#define GL_ONE 1
#define GL_SRC_COLOR 0x0300
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_DST_COLOR 0x0306
#define GL_CONSTANT_COLOR 0x8001
#define GL_FUNC_ADD 0x8006
#define GL_MIN 0x8007
#define GL_MAX 0x8008
#define GL_FUNC_REVERSE_SUBTRACT 0x800B
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_CW 0x0900
#define GL_CCW 0x0901
#define GL_INTERLEAVED_ATTRIBS 0x8C8C
#define GL_SEPARATE_ATTRIBS 0x8C8D
#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88
#define GL_ANY_SAMPLES_PASSED 0x8C2F
#define GL_QUERY_RESULT 0x8866
#define GL_MAP_READ_BIT 0x0001
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_VERSION 0x1F02
#define GL_RENDERER 0x1F01
#define GL_COLOR 0x1800
#define GL_TEXTURE_RECTANGLE 0x84F5
#define GL_TEXTURE_BUFFER 0x8C2A
#define GL_TEXTURE_2D_MULTISAMPLE 0x9100
#define GL_CLIP_DISTANCE0 0x3000
#define GL_GEOMETRY_SHADER 0x8DD9
#define GL_DEPTH_COMPONENT32F 0x8CAC
#define GL_RGBA32UI 0x8D70
#define GL_RGBA8I 0x8D8E
#define GL_R32I 0x8235
#define GL_UNSIGNED_INT_IMM 0
#define EGL_OPENGL_API 0x30A2
#define GL_COMPUTE_SHADER 0x91B9
#define GL_TESS_CONTROL_SHADER 0x8E88
#define GL_TESS_EVALUATION_SHADER 0x8E87
#define GL_PATCHES 0x000E
#define GL_PATCH_VERTICES 0x8E72
#define GL_SHADER_STORAGE_BUFFER 0x90D2
#define GL_DRAW_INDIRECT_BUFFER 0x8F3F
#define GL_ALL_BARRIER_BITS 0xFFFFFFFF
#define GL_WRITE_ONLY 0x88B9
#define GL_READ_ONLY 0x88B8
#define GL_READ_WRITE 0x88BA
#define GL_R32UI_IMAGE 0x8236
#define GL_MAP_WRITE_BIT 0x0002
#define GL_MAP_PERSISTENT_BIT 0x0040
#define GL_MAP_COHERENT_BIT 0x0080
#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x4000
#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117
#define GL_SYNC_FLUSH_COMMANDS_BIT 0x0001
#define GL_NUM_EXTENSIONS 0x821D
#define GL_EXTENSIONS 0x1F03
#define EGL_CONTEXT_OPENGL_PROFILE_MASK 0x30FD
#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT 0x1

// ---------------------------------------------------------------------------

#define W 64
#define H 64
static int mode_ref;
static int failures;
static unsigned char pixels[W * H * 4];
static const char *dir = "/tmp/gltest-ref";

static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/** An image as PPM in base64, in lines of the harness's */
static void print_image(const char *name, const char *which, const unsigned char *rgba)
{
    static unsigned char ppm[32 + W * H * 3];
    int n = snprintf((char *)ppm, 32, "P6\n%d %d\n255\n", W, H);
    for(int i = 0; i < W * H; i++)
    {
        // (bottom row first in GL: top first in the picture)
        int row = H - 1 - i / W, column = i % W;
        const unsigned char *p = rgba + (row * W + column) * 4;
        ppm[n++] = p[0]; ppm[n++] = p[1]; ppm[n++] = p[2];
    }
    static char line[4100];
    int at = 0, chunk = 0;
    for(int i = 0; i < n; i += 3)
    {
        unsigned v = ppm[i] << 16 | (i + 1 < n ? ppm[i + 1] << 8 : 0) | (i + 2 < n ? ppm[i + 2] : 0);
        line[at++] = base64[v >> 18 & 63];
        line[at++] = base64[v >> 12 & 63];
        line[at++] = i + 1 < n ? base64[v >> 6 & 63] : '=';
        line[at++] = i + 2 < n ? base64[v & 63] : '=';
        if(at >= 4000 || i + 3 >= n)
        {
            line[at] = 0;
            printf("GLIMG %s %s %d %s\n", name, which, chunk++, line);
            at = 0;
        }
    }
    printf("GLIMG %s %s end\n", name, which);
}

/** The result of a test: bytes (an image if `image`), to keep or to compare */
static void result(const char *name, const unsigned char *bytes, int length, int image, int tolerance)
{
    char path[256];
    snprintf(path, sizeof(path), "%s/%s.raw", dir, name);
    GLenum error = glGetError();
    if(mode_ref)
    {
        int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
        write(fd, bytes, length);
        close(fd);
        if(error) printf("GLTEST %s ref (GL error %x)\n", name, error);
        else printf("GLTEST %s ref\n", name);
        return;
    }
    static unsigned char ref[W * H * 4];
    int fd = open(path, O_RDONLY);
    long got = fd >= 0 ? read(fd, ref, length) : -1;
    if(fd >= 0) close(fd);
    if(got != length)
    {
        printf("GLTEST %s FAIL no reference\n", name);
        failures++;
        return;
    }
    int max = 0, bad = 0;
    for(int i = 0; i < length; i++)
    {
        int d = bytes[i] > ref[i] ? bytes[i] - ref[i] : ref[i] - bytes[i];
        if(d > max) max = d;
    }
    if(image)
    {
        for(int i = 0; i < W * H; i++)
        {
            for(int c = 0; c < 4; c++)
            {
                int d = bytes[4 * i + c] > ref[4 * i + c] ? bytes[4 * i + c] - ref[4 * i + c] : ref[4 * i + c] - bytes[4 * i + c];
                if(d > tolerance) { bad++; break; }
            }
        }
    }
    else
    {
        bad = max > tolerance;
        // (numbers: the first word that differs, for the log)
        for(int i = 0; i + 4 <= length && bad; i += 4)
        {
            const unsigned int *g = (const unsigned int *)(bytes + i), *r = (const unsigned int *)(ref + i);
            if(*g != *r)
            {
                printf("GLTEST %s first difference at byte %d: got %u (0x%x), expected %u (0x%x)\n", name, i, *g, *g, *r, *r);
                break;
            }
        }
    }
    // (a few pixels on edges may differ: GPUs need not rasterize alike)
    int ok = !error && bad <= (image ? 8 : 0);
    printf("GLTEST %s %s max=%d bad=%d", name, ok ? "ok" : "FAIL", max, bad);
    if(error) printf(" glerror=%x", error);
    printf("\n");
    if(!ok)
    {
        failures++;
        if(image)
        {
            print_image(name, "got", bytes);
            print_image(name, "ref", ref);
        }
        else
        {
            printf("GLDATA %s got", name);
            for(int i = 0; i < length && i < 64; i++) printf(" %02x", bytes[i]);
            printf("\nGLDATA %s ref", name);
            for(int i = 0; i < length && i < 64; i++) printf(" %02x", ref[i]);
            printf("\n");
        }
    }
    fflush(0);
}

static GLuint shader(GLenum type, const char *source)
{
    GLuint s = glCreateShader(type);
    glShaderSource(s, 1, &source, 0);
    glCompileShader(s);
    GLint ok = 0;
    glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
    if(!ok)
    {
        char log[1024];
        glGetShaderInfoLog(s, sizeof(log), 0, log);
        printf("shader: %s\n", log);
    }
    return s;
}

/** A program; `varyings` for transform feedback */
static GLuint program2(const char *vs, const char *fs, int count, const char *const *varyings, GLenum mode)
{
    GLuint p = glCreateProgram();
    GLuint v = shader(GL_VERTEX_SHADER, vs), f = shader(GL_FRAGMENT_SHADER, fs);
    glAttachShader(p, v);
    glAttachShader(p, f);
    if(count) glTransformFeedbackVaryings(p, count, varyings, mode);
    glLinkProgram(p);
    GLint ok = 0;
    glGetProgramiv(p, GL_LINK_STATUS, &ok);
    if(!ok)
    {
        char log[1024];
        glGetProgramInfoLog(p, sizeof(log), 0, log);
        printf("link: %s\n", log);
    }
    glDeleteShader(v);
    glDeleteShader(f);
    glUseProgram(p);
    return p;
}

static GLuint program(const char *vs, const char *fs)
{
    return program2(vs, fs, 0, 0, 0);
}

static GLuint program_gs(const char *vs, const char *gs, const char *fs)
{
    GLuint p = glCreateProgram();
    GLuint v = shader(GL_VERTEX_SHADER, vs), g = shader(GL_GEOMETRY_SHADER, gs), f = shader(GL_FRAGMENT_SHADER, fs);
    glAttachShader(p, v);
    glAttachShader(p, g);
    glAttachShader(p, f);
    glLinkProgram(p);
    GLint ok = 0;
    glGetProgramiv(p, GL_LINK_STATUS, &ok);
    if(!ok)
    {
        char log[1024];
        glGetProgramInfoLog(p, sizeof(log), 0, log);
        printf("link: %s\n", log);
    }
    glUseProgram(p);
    return p;
}

/** A framebuffer of a 64 x 64 RGBA8 texture, maybe with depth and stencil */
static GLuint fbo, fbo_color, fbo_depth;
static void target(int depth_stencil)
{
    glGenFramebuffers(1, &fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    glGenTextures(1, &fbo_color);
    glBindTexture(GL_TEXTURE_2D, fbo_color);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, W, H, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fbo_color, 0);
    fbo_depth = 0;
    if(depth_stencil)
    {
        glGenRenderbuffers(1, &fbo_depth);
        glBindRenderbuffer(GL_RENDERBUFFER, fbo_depth);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, W, H);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fbo_depth);
    }
    if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) printf("framebuffer incomplete\n");
    glViewport(0, 0, W, H);
    glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
    glClearDepthf(1.0f);
    glClearStencil(0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

/** The target's pixels compared (without a name: not), then everything made for the test deleted */
static void finish(const char *name, int tolerance)
{
    if(name)
    {
        glPixelStorei(GL_PACK_ALIGNMENT, 1);
        glReadPixels(0, 0, W, H, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
        result(name, pixels, W * H * 4, 1, tolerance);
    }
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDeleteFramebuffers(1, &fbo);
    glDeleteTextures(1, &fbo_color);
    if(fbo_depth) glDeleteRenderbuffers(1, &fbo_depth);
    glUseProgram(0);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_STENCIL_TEST);
    glDisable(GL_BLEND);
    glDisable(GL_SCISSOR_TEST);
    glDisable(GL_CULL_FACE);
    glDisable(GL_POLYGON_OFFSET_FILL);
    glDisable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
    glColorMask(1, 1, 1, 1);
    glDepthMask(1);
}

/** A vertex buffer of floats bound to attribute `index` */
static GLuint vbo(GLuint index, int components, const float *data, int bytes)
{
    GLuint b;
    glGenBuffers(1, &b);
    glBindBuffer(GL_ARRAY_BUFFER, b);
    glBufferData(GL_ARRAY_BUFFER, bytes, data, GL_STATIC_DRAW);
    glVertexAttribPointer(index, components, GL_FLOAT, 0, 0, 0);
    glEnableVertexAttribArray(index);
    return b;
}

static GLuint vao;
static void fresh_vao(void)
{
    if(vao) glDeleteVertexArrays(1, &vao);
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
}

#define VS_HEADER "#version 300 es\n"
#define FS_HEADER "#version 300 es\nprecision highp float;\nprecision highp int;\n"

static const float quad[] = { -1, -1, 1, -1, -1, 1, 1, 1 };

// ---------------------------------------------------------------------------
// The tests

static void test_clear(void)
{
    target(0);
    glEnable(GL_SCISSOR_TEST);
    glScissor(8, 16, 24, 20);
    glClearColor(1, 0.5f, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);
    finish("clear-scissor", 1);
}

static void test_triangle(void)
{
    target(0);
    fresh_vao();
    program(VS_HEADER "in vec2 p; in vec3 c; out vec3 v; void main() { v = c; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "in vec3 v; out vec4 o; void main() { o = vec4(v, 1.0); }");
    const float p[] = { -0.9f, -0.9f, 0.9f, -0.7f, 0.0f, 0.9f };
    const float c[] = { 1, 0, 0, 0, 1, 0, 0, 0, 1 };
    vbo(0, 2, p, sizeof(p));
    vbo(1, 3, c, sizeof(c));
    glDrawArrays(GL_TRIANGLES, 0, 3);
    finish("triangle", 2);
}

/** Front faces, culling, and the window's way up */
static void test_cull(void)
{
    target(0);
    fresh_vao();
    program(VS_HEADER "in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "out vec4 o; void main() { o = gl_FrontFacing ? vec4(0, 1, 0, 1) : vec4(1, 0, 0, 1); }");
    // a counter-clockwise triangle on the left, a clockwise one on the right
    const float p[] = { -0.9f, -0.5f, -0.1f, -0.5f, -0.5f, 0.5f, 0.1f, -0.5f, 0.5f, 0.5f, 0.9f, -0.5f };
    vbo(0, 2, p, sizeof(p));
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CW);
    glEnable(GL_SCISSOR_TEST);
    glScissor(0, 0, W, 16);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    finish("cull-front-face", 2);
}

static void test_depth_stencil(void)
{
    target(1);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; uniform float z; void main() { gl_Position = vec4(p, z, 1.0); }",
        FS_HEADER "uniform vec4 color; out vec4 o; void main() { o = color; }");
    GLint z = glGetUniformLocation(p, "z"), color = glGetUniformLocation(p, "color");
    vbo(0, 2, quad, sizeof(quad));
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_STENCIL_TEST);
    // a stencil mask in the middle
    glStencilFunc(GL_ALWAYS, 1, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    glColorMask(0, 0, 0, 0);
    glDepthMask(0);
    glEnable(GL_SCISSOR_TEST);
    glScissor(16, 16, 32, 32);
    glUniform1f(z, 0.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDisable(GL_SCISSOR_TEST);
    glColorMask(1, 1, 1, 1);
    glDepthMask(1);
    // red at z 0.5 everywhere, then green at 0.0 only where the stencil is 1,
    // then blue at 0.25 (behind green, in front of red)
    glStencilFunc(GL_ALWAYS, 0, 0xFF);
    glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
    glUniform1f(z, 0.5f);
    glUniform4f(color, 1, 0, 0, 1);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glStencilFunc(GL_EQUAL, 1, 0xFF);
    glUniform1f(z, 0.0f);
    glUniform4f(color, 0, 1, 0, 1);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDisable(GL_STENCIL_TEST);
    glEnable(GL_SCISSOR_TEST);
    glScissor(0, 0, 40, 40);
    glUniform1f(z, 0.25f);
    glUniform4f(color, 0, 0, 1, 1);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("depth-stencil", 0);
}

static void test_blend(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform vec4 color; out vec4 o; void main() { o = color; }");
    GLint color = glGetUniformLocation(p, "color");
    vbo(0, 2, quad, sizeof(quad));
    glEnable(GL_BLEND);
    glEnable(GL_SCISSOR_TEST);
    glScissor(0, 0, 32, 64);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glUniform4f(color, 1, 0, 0, 0.5f);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glScissor(32, 0, 32, 32);
    glBlendFunc(GL_ONE, GL_ONE);
    glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
    glUniform4f(color, 0.05f, 0.1f, 0.1f, 0);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glScissor(32, 32, 32, 32);
    glBlendEquation(GL_FUNC_ADD);
    glBlendColor(0.5f, 0.25f, 1, 1);
    glBlendFuncSeparate(GL_CONSTANT_COLOR, GL_ZERO, GL_ONE, GL_ZERO);
    glUniform4f(color, 1, 1, 1, 0.75f);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("blend", 2);
}

/** A texture: a checkerboard of colors, its mipmaps, nearest and linear */
static void test_texture(void)
{
    target(0);
    fresh_vao();
    // left: wrapping, nearest; right: level 0 with the sub-image (nearest); then level 2 (linear)
    GLuint p = program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p * 0.75 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform sampler2D s; uniform sampler2D m; uniform float lod; in vec2 t; out vec4 o;\n"
        "void main() { o = t.x < 0.5 ? texture(s, t * 2.0) : textureLod(m, t, lod); }");
    static unsigned char texels[16 * 16 * 4];
    for(int y = 0; y < 16; y++)
        for(int x = 0; x < 16; x++)
        {
            unsigned char *t = texels + 4 * (y * 16 + x);
            t[0] = x * 16; t[1] = y * 16; t[2] = (x ^ y) & 1 ? 255 : 0; t[3] = 255;
        }
    GLuint tex[2];
    glGenTextures(2, tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glActiveTexture(GL_TEXTURE0 + 1);
    glBindTexture(GL_TEXTURE_2D, tex[1]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    // (a sub-image: a white block)
    static unsigned char white[4 * 4 * 4];
    memset(white, 255, sizeof(white));
    glTexSubImage2D(GL_TEXTURE_2D, 0, 4, 4, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, white);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(glGetUniformLocation(p, "s"), 0);
    glUniform1i(glGetUniformLocation(p, "m"), 1);
    glUniform1f(glGetUniformLocation(p, "lod"), 0.0f);
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("texture-subimage", 0);
    target(0);
    glUseProgram(p);
    glGenerateMipmap(GL_TEXTURE_2D);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glUniform1f(glGetUniformLocation(p, "lod"), 2.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("texture-mipmap", 3);
    glDeleteTextures(2, tex);
}

/** The legacy formats (swizzled) and texture swizzles */
static void test_swizzle(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform sampler2D a, l, la, s; in vec2 t; out vec4 o;\n"
        "void main() { vec2 u = fract(t * 2.0); o = t.y < 0.5 ? (t.x < 0.5 ? texture(a, u) : texture(l, u)) : (t.x < 0.5 ? texture(la, u) : texture(s, u)); }");
    static unsigned char texels[4 * 4 * 4];
    for(int i = 0; i < 64; i++) texels[i] = i * 4;
    GLuint tex[4];
    glGenTextures(4, tex);
    const GLenum formats[] = { GL_ALPHA, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_RGBA };
    const char *names[] = { "a", "l", "la", "s" };
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    for(int i = 0; i < 4; i++)
    {
        glActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(GL_TEXTURE_2D, tex[i]);
        glTexImage2D(GL_TEXTURE_2D, 0, formats[i], 4, 4, 0, formats[i], GL_UNSIGNED_BYTE, texels);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glUniform1i(glGetUniformLocation(p, names[i]), i);
    }
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ONE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ZERO);
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("legacy-formats-swizzle", 1);
    glDeleteTextures(4, tex);
}

/** Two render targets, flat integer varyings, gl_FragCoord */
static void test_mrt(void)
{
    target(0);
    GLuint second;
    glGenTextures(1, &second);
    glBindTexture(GL_TEXTURE_2D, second);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, W, H, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, second, 0);
    const GLenum buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
    glDrawBuffers(2, buffers);
    const float black[] = { 0, 0, 0, 1 };
    glClearBufferfv(GL_COLOR, 1, black);
    fresh_vao();
    program(VS_HEADER "in vec2 p; flat out int k; void main() { k = gl_VertexID; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "flat in int k; layout(location = 0) out vec4 a; layout(location = 1) out vec4 b;\n"
        "void main() { a = vec4(float(k) / 4.0, 0.5, 0.0, 1.0); b = vec4(gl_FragCoord.xy / 64.0, gl_FragCoord.z, 1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glReadBuffer(GL_COLOR_ATTACHMENT1);
    glPixelStorei(GL_PACK_ALIGNMENT, 1);
    glReadPixels(0, 0, W, H, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    result("mrt-fragcoord", pixels, W * H * 4, 1, 2);
    glReadBuffer(GL_COLOR_ATTACHMENT0);
    finish("mrt-flat", 2);
    glDeleteTextures(1, &second);
}

/** Instancing, 8-bit indices, primitive restart, a uniform buffer */
static void test_instancing(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; in vec2 offset; in uvec4 tint;\n"
        "layout(std140) uniform U { vec4 scale; vec4 colors[4]; };\n"
        "out vec4 c; void main() { c = colors[gl_InstanceID & 3] * vec4(tint) / 255.0; gl_Position = vec4(p * scale.xy + offset, 0.0, 1.0); }",
        FS_HEADER "in vec4 c; out vec4 o; void main() { o = c; }");
    const float corners[] = { -1, -1, 1, -1, -1, 1, 1, 1, 0, 1.5f };
    vbo(0, 2, corners, sizeof(corners));
    const float offsets[] = { -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f };
    vbo(1, 2, offsets, sizeof(offsets));
    glVertexAttribDivisor(1, 1);
    const unsigned char tints[] = { 255, 255, 255, 255, 128, 255, 255, 255, 255, 128, 255, 255, 255, 255, 128, 255 };
    GLuint tb;
    glGenBuffers(1, &tb);
    glBindBuffer(GL_ARRAY_BUFFER, tb);
    glBufferData(GL_ARRAY_BUFFER, sizeof(tints), tints, GL_STATIC_DRAW);
    glVertexAttribIPointer(2, 4, GL_UNSIGNED_BYTE, 4, 0);
    glEnableVertexAttribArray(2);
    glVertexAttribDivisor(2, 1);
    const float u[] = { 0.3f, 0.3f, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1 };
    GLuint ub;
    glGenBuffers(1, &ub);
    glBindBuffer(GL_UNIFORM_BUFFER, ub);
    glBufferData(GL_UNIFORM_BUFFER, sizeof(u), u, GL_STATIC_DRAW);
    glUniformBlockBinding(p, glGetUniformBlockIndex(p, "U"), 2);
    glBindBufferBase(GL_UNIFORM_BUFFER, 2, ub);
    // a strip, a restart, a triangle (to the fifth corner)
    const unsigned char indices[] = { 0, 1, 2, 3, 255, 2, 3, 4 };
    GLuint ib;
    glGenBuffers(1, &ib);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
    glDrawElementsInstanced(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_BYTE, 0, 4);
    finish("instancing-ubo-restart", 2);
}

/** Transform feedback: what the vertex shader wrote, and how many primitives */
static void test_transform_feedback(void)
{
    target(0);
    fresh_vao();
    static const char *varyings[] = { "a", "b" };
    program2(VS_HEADER "in vec4 p; out vec4 a; out float b; void main() { a = p * 2.0 + vec4(1.0); b = float(gl_VertexID) * 0.5; gl_Position = p; }",
        FS_HEADER "out vec4 o; void main() { o = vec4(1.0); }", 2, varyings, GL_INTERLEAVED_ATTRIBS);
    const float p[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
    vbo(0, 4, p, sizeof(p));
    GLuint out;
    glGenBuffers(1, &out);
    glBindBuffer(GL_TRANSFORM_FEEDBACK_BUFFER, out);
    glBufferData(GL_TRANSFORM_FEEDBACK_BUFFER, 6 * 5 * 4, 0, GL_STREAM_READ);
    glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, out);
    GLuint q;
    glGenQueries(1, &q);
    glEnable(GL_RASTERIZER_DISCARD);
    glBeginQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN, q);
    glBeginTransformFeedback(GL_TRIANGLES);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glEndTransformFeedback();
    glEndQuery(GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN);
    glDisable(GL_RASTERIZER_DISCARD);
    GLuint written = 0;
    glGetQueryObjectuiv(q, GL_QUERY_RESULT, &written);
    static unsigned char data[6 * 5 * 4 + 4];
    void *mapped = glMapBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 6 * 5 * 4, GL_MAP_READ_BIT);
    if(mapped) memcpy(data, mapped, 6 * 5 * 4);
    glUnmapBuffer(GL_TRANSFORM_FEEDBACK_BUFFER);
    memcpy(data + 6 * 5 * 4, &written, 4);
    result("transform-feedback", data, sizeof(data), 0, 0);
    glDeleteBuffers(1, &out);
    glDeleteQueries(1, &q);
    finish(0, 0);
}

/** An occlusion query: how many samples passed (any) */
static void test_occlusion(void)
{
    target(1);
    fresh_vao();
    program(VS_HEADER "in vec2 p; void main() { gl_Position = vec4(p, 0.5, 1.0); }",
        FS_HEADER "out vec4 o; void main() { o = vec4(1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glEnable(GL_DEPTH_TEST);
    GLuint q[2];
    glGenQueries(2, q);
    glBeginQuery(GL_ANY_SAMPLES_PASSED, q[0]);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glEndQuery(GL_ANY_SAMPLES_PASSED);
    // behind: nothing passes
    glDepthFunc(GL_GREATER);
    glBeginQuery(GL_ANY_SAMPLES_PASSED, q[1]);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glEndQuery(GL_ANY_SAMPLES_PASSED);
    GLuint results[2] = { 7, 7 };
    glGetQueryObjectuiv(q[0], GL_QUERY_RESULT, &results[0]);
    glGetQueryObjectuiv(q[1], GL_QUERY_RESULT, &results[1]);
    result("occlusion-query", (unsigned char *)results, sizeof(results), 0, 0);
    glDeleteQueries(2, q);
    finish("occlusion-image", 0);
}

/** Copies: a blit (scaled, flipped), a copy into a texture */
static void test_blit(void)
{
    // a picture to copy from
    target(0);
    fresh_vao();
    program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "in vec2 t; out vec4 o; void main() { o = vec4(t, step(0.5, fract(t.x * 4.0)), 1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    GLuint source = fbo, source_color = fbo_color;
    target(0);
    glBindFramebuffer(GL_READ_FRAMEBUFFER, source);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo);
    glBlitFramebuffer(0, 0, 64, 64, 0, 0, 32, 32, GL_COLOR_BUFFER_BIT, GL_NEAREST);
    glBlitFramebuffer(0, 0, 64, 64, 32, 64, 64, 32, GL_COLOR_BUFFER_BIT, GL_NEAREST);
    glBlitFramebuffer(16, 16, 48, 48, 0, 32, 32, 64, GL_COLOR_BUFFER_BIT, GL_NEAREST);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
    finish("blit", 1);
    glDeleteFramebuffers(1, &source);
    glDeleteTextures(1, &source_color);
}

/** Polygon offset, lines and points, a fan */
static void test_primitives(void)
{
    target(1);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; void main() { gl_PointSize = 1.0; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform vec4 color; out vec4 o; void main() { o = color; }");
    GLint color = glGetUniformLocation(p, "color");
    const float shape[] = { 0, 0, 0.8f, 0, 0.5f, 0.6f, -0.2f, 0.8f, -0.7f, 0.3f, -0.6f, -0.5f, 0.1f, -0.8f };
    vbo(0, 2, shape, sizeof(shape));
    glUniform4f(color, 0.2f, 0.6f, 1, 1);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 7);
    glUniform4f(color, 1, 1, 0, 1);
    glDrawArrays(GL_LINE_STRIP, 1, 6);
    glUniform4f(color, 1, 0, 1, 1);
    glDrawArrays(GL_POINTS, 0, 7);
    finish("fan-lines-points", 2);
}

/** Flat shading by the last vertex with indices: a strip with a restart, a fan */
static void test_flat_indexed(void)
{
    const char *vs = VS_HEADER "in vec2 p; flat out int k; void main() { k = gl_VertexID; gl_Position = vec4(p, 0.0, 1.0); }";
    const char *fs = FS_HEADER "flat in int k; out vec4 o; void main() { o = vec4(float(k % 3) / 2.0, float(k / 3) / 2.0, 0.5, 1.0); }";
    // a 3 x 3 grid of vertices, row by row
    float grid[18];
    for(int i = 0; i < 9; i++) { grid[2 * i] = (i % 3 - 1) * 0.9f; grid[2 * i + 1] = (i / 3 - 1) * 0.9f; }
    target(0);
    fresh_vao();
    program(vs, fs);
    vbo(0, 2, grid, sizeof(grid));
    const unsigned short strip[] = { 0, 3, 1, 4, 2, 5, 0xFFFF, 3, 6, 4, 7, 5, 8 };
    GLuint ib;
    glGenBuffers(1, &ib);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(strip), strip, GL_STATIC_DRAW);
    glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
    glDrawElements(GL_TRIANGLE_STRIP, 13, GL_UNSIGNED_SHORT, 0);
    finish("flat-indexed-strip", 1);
    target(0);
    fresh_vao();
    program(vs, fs);
    vbo(0, 2, grid, sizeof(grid));
    // around the middle
    const unsigned short fan[] = { 4, 0, 1, 2, 5, 8, 7, 6, 3, 0 };
    glGenBuffers(1, &ib);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(fan), fan, GL_STATIC_DRAW);
    glDrawElements(GL_TRIANGLE_FAN, 10, GL_UNSIGNED_SHORT, 0);
    finish("flat-indexed-fan", 1);
}


/** A depth texture drawn into, then sampled with a comparison */
static void test_shadow(void)
{
    // the depth: a gradient from left (0) to right (1)
    GLuint depth;
    glGenTextures(1, &depth);
    glBindTexture(GL_TEXTURE_2D, depth);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, W, H, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    GLuint f;
    glGenFramebuffers(1, &f);
    glBindFramebuffer(GL_FRAMEBUFFER, f);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
    glViewport(0, 0, W, H);
    glClearDepthf(1.0f);
    glClear(GL_DEPTH_BUFFER_BIT);
    fresh_vao();
    program(VS_HEADER "in vec2 p; void main() { gl_Position = vec4(p, p.x, 1.0); }", FS_HEADER "out vec4 o; void main() { o = vec4(1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_ALWAYS);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glDisable(GL_DEPTH_TEST);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDeleteFramebuffers(1, &f);
    // compared with a reference that rises from bottom to top
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform highp sampler2DShadow s; in vec2 t; out vec4 o; void main() { float r = texture(s, vec3(t, t.y)); o = vec4(r, t.x, 0.0, 1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glBindTexture(GL_TEXTURE_2D, depth);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
    glUniform1i(glGetUniformLocation(p, "s"), 0);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    // (along the diagonal the depth and the reference meet: rounding decides)
    finish("shadow-sampler", 2);
    glDeleteTextures(1, &depth);
}

/** A cube map, a 3D texture and an array, sampled */
static void test_texture_kinds(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform samplerCube c; uniform highp sampler3D v; uniform highp sampler2DArray a; in vec2 t; out vec4 o;\n"
        "void main() { vec2 u = t * 0.5 + 0.5;\n"
        "  if(t.y > 0.0) o = texture(c, vec3(t.x * 2.0, 1.0, t.y * 3.0 - 1.5));\n"
        "  else if(t.x < 0.0) o = texture(v, vec3(u.x * 2.0, u.y * 2.0, fract(u.x * 4.0)));\n"
        "  else o = texture(a, vec3(fract(u * 4.0), floor(u.x * 6.0) - 3.0)); }");
    vbo(0, 2, quad, sizeof(quad));
    GLuint tex[3];
    glGenTextures(3, tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, tex[0]);
    for(int face = 0; face < 6; face++)
    {
        unsigned char texels[2 * 2 * 4];
        for(int i = 0; i < 4; i++)
        {
            texels[4 * i] = face & 1 ? 255 : 40 * i; texels[4 * i + 1] = face & 2 ? 255 : 60; texels[4 * i + 2] = face & 4 ? 255 : 30 * face; texels[4 * i + 3] = 255;
        }
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glActiveTexture(GL_TEXTURE0 + 1);
    glBindTexture(GL_TEXTURE_3D, tex[1]);
    static unsigned char volume[4 * 4 * 4 * 4];
    for(int i = 0; i < 64; i++) { volume[4 * i] = (i & 3) * 80; volume[4 * i + 1] = (i >> 2 & 3) * 80; volume[4 * i + 2] = (i >> 4) * 80; volume[4 * i + 3] = 255; }
    glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA8, 4, 4, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, volume);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glActiveTexture(GL_TEXTURE0 + 2);
    glBindTexture(GL_TEXTURE_2D_ARRAY, tex[2]);
    static unsigned char layers[2 * 2 * 3 * 4];
    for(int i = 0; i < 12; i++) { layers[4 * i] = i / 4 == 0 ? 255 : 0; layers[4 * i + 1] = i / 4 == 1 ? 255 : 0; layers[4 * i + 2] = i / 4 == 2 ? 255 : (i & 3) * 60; layers[4 * i + 3] = 255; }
    glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, 2, 2, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, layers);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(glGetUniformLocation(p, "c"), 0);
    glUniform1i(glGetUniformLocation(p, "v"), 1);
    glUniform1i(glGetUniformLocation(p, "a"), 2);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("cube-3d-array", 0);
    glActiveTexture(GL_TEXTURE0);
    glDeleteTextures(3, tex);
}

/** Each cube face in a stripe of its own (2 x 2 texels: its orientation), then each layer of an array */
static void test_cube_faces(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS_HEADER "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        FS_HEADER "uniform samplerCube c; uniform highp sampler2DArray a; in vec2 t; out vec4 o;\n"
        "void main() { float k = floor(t.x * 6.0); vec2 u = vec2(fract(t.x * 6.0), t.y * 2.0) * 1.6 - 0.8;\n"
        "  if(t.y < 0.5) { o = texture(a, vec3(fract(t.x * 4.0), t.y * 2.0, floor(t.x * 4.0))); return; }\n"
        "  u = vec2(fract(t.x * 6.0), t.y * 2.0 - 1.0) * 1.6 - 0.8;\n"
        "  vec3 d = k == 0.0 ? vec3(1.0, u.y, u.x) : k == 1.0 ? vec3(-1.0, u.y, u.x) : k == 2.0 ? vec3(u.x, 1.0, u.y) :\n"
        "    k == 3.0 ? vec3(u.x, -1.0, u.y) : k == 4.0 ? vec3(u.x, u.y, 1.0) : vec3(u.x, u.y, -1.0);\n"
        "  o = texture(c, d); }");
    vbo(0, 2, quad, sizeof(quad));
    GLuint tex[2];
    glGenTextures(2, tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, tex[0]);
    for(int face = 0; face < 6; face++)
    {
        unsigned char texels[2 * 2 * 4];
        for(int i = 0; i < 4; i++)
        {
            texels[4 * i] = face * 40 + 35; texels[4 * i + 1] = i & 1 ? 230 : 20; texels[4 * i + 2] = i & 2 ? 230 : 20; texels[4 * i + 3] = 255;
        }
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, GL_RGBA8, 2, 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glActiveTexture(GL_TEXTURE0 + 1);
    glBindTexture(GL_TEXTURE_2D_ARRAY, tex[1]);
    static unsigned char layers[2 * 2 * 4 * 4];
    for(int i = 0; i < 16; i++) { layers[4 * i] = (i / 4) * 70 + 20; layers[4 * i + 1] = i & 1 ? 230 : 20; layers[4 * i + 2] = i & 2 ? 230 : 20; layers[4 * i + 3] = 255; }
    glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA8, 2, 2, 4, 0, GL_RGBA, GL_UNSIGNED_BYTE, layers);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(glGetUniformLocation(p, "c"), 0);
    glUniform1i(glGetUniformLocation(p, "a"), 1);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("cube-faces-array-layers", 0);
    glActiveTexture(GL_TEXTURE0);
    glDeleteTextures(2, tex);
}

/** An integer render target, read back as integers */
static void test_integer_target(void)
{
    target(0);
    GLuint t;
    glGenTextures(1, &t);
    glBindTexture(GL_TEXTURE_2D, t);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI, 32, 32, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t, 0);
    const GLuint clear[] = { 7, 70000, 0xFFFFFFF0u, 3 };
    glClearBufferuiv(GL_COLOR, 0, clear);
    glViewport(0, 0, 32, 32);
    fresh_vao();
    program(VS_HEADER "in vec2 p; flat out uint k; void main() { k = uint(gl_VertexID) * 1000u + 5u; gl_Position = vec4(p * 0.5, 0.0, 1.0); }",
        FS_HEADER "flat in uint k; out uvec4 o; void main() { o = uvec4(k, uint(gl_FragCoord.x) << 20, 0x80000000u | uint(gl_FragCoord.y), 9u); }");
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glPixelStorei(GL_PACK_ALIGNMENT, 4);
    glReadPixels(0, 0, 32, 32, GL_RGBA_INTEGER, GL_UNSIGNED_INT, pixels);
    result("integer-target", pixels, 32 * 32 * 16, 0, 0);
    glViewport(0, 0, W, H);
    finish(0, 0);
    glDeleteTextures(1, &t);
}

// ---------------------------------------------------------------------------
// OpenGL 3.3 core

#define VS33 "#version 330 core\n"

/** A geometry shader: points into quads, with a varying of its own */
static void test_geometry_shader(void)
{
    target(0);
    fresh_vao();
    program_gs(VS33 "in vec2 p; out vec3 c; void main() { c = vec3(p * 0.5 + 0.5, 0.25); gl_Position = vec4(p, 0.0, 1.0); }",
        VS33 "layout(points) in; layout(triangle_strip, max_vertices = 4) out; in vec3 c[]; out vec3 color; out vec2 corner;\n"
        "void main() { for(int i = 0; i < 4; i++) { vec2 d = vec2(i & 1, i >> 1) * 2.0 - 1.0; corner = d; color = c[0];\n"
        "  gl_Position = gl_in[0].gl_Position + vec4(d * 0.15, 0.0, 0.0); EmitVertex(); } EndPrimitive(); }",
        VS33 "in vec3 color; in vec2 corner; out vec4 o; void main() { o = vec4(color, 1.0) * (1.0 - 0.5 * length(corner) / 1.5); }");
    const float points[] = { -0.6f, -0.6f, 0.6f, -0.5f, 0.0f, 0.0f, -0.5f, 0.6f, 0.6f, 0.6f };
    vbo(0, 2, points, sizeof(points));
    glDrawArrays(GL_POINTS, 0, 5);
    finish("geometry-shader", 2);
}

/** gl_ClipDistance: the triangle cut along a line */
static void test_clip_distance(void)
{
    target(0);
    fresh_vao();
    program(VS33 "in vec2 p; out vec3 c; void main() { c = vec3(1.0, p * 0.5 + 0.5); gl_ClipDistance[0] = p.x + p.y * 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        VS33 "in vec3 c; out vec4 o; void main() { o = vec4(c, 1.0); }");
    glEnable(GL_CLIP_DISTANCE0);
    const float p[] = { -0.9f, -0.9f, 0.9f, -0.9f, 0.0f, 0.9f };
    vbo(0, 2, p, sizeof(p));
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisable(GL_CLIP_DISTANCE0);
    finish("clip-distance", 2);
}

/** Rectangle textures, buffer textures, texture() on an integer texture */
static void test_texture_33(void)
{
    target(0);
    fresh_vao();
    GLuint p = program(VS33 "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        VS33 "uniform sampler2DRect r; uniform samplerBuffer b; uniform isampler2D i; in vec2 t; out vec4 o;\n"
        "void main() { if(t.y < 0.5) o = texture(r, t * vec2(5.0, 6.0));\n"
        "  else if(t.x < 0.5) o = texelFetch(b, int(t.x * 16.0));\n"
        "  else o = vec4(texture(i, t)) / 255.0; }");
    vbo(0, 2, quad, sizeof(quad));
    GLuint tex[3], buffer;
    glGenTextures(3, tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_RECTANGLE, tex[0]);
    unsigned char rect[5 * 3 * 4];
    for(int k = 0; k < 15; k++) { rect[4 * k] = k * 17; rect[4 * k + 1] = 255 - k * 17; rect[4 * k + 2] = k & 1 ? 200 : 50; rect[4 * k + 3] = 255; }
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_RECTANGLE, 0, GL_RGBA8, 5, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glActiveTexture(GL_TEXTURE0 + 1);
    float values[16 * 4];
    for(int k = 0; k < 64; k++) values[k] = (k * 7 % 16) / 15.0f;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_TEXTURE_BUFFER, buffer);
    glBufferData(GL_TEXTURE_BUFFER, sizeof(values), values, GL_STATIC_DRAW);
    glBindTexture(GL_TEXTURE_BUFFER, tex[1]);
    glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, buffer);
    glActiveTexture(GL_TEXTURE0 + 2);
    glBindTexture(GL_TEXTURE_2D, tex[2]);
    signed char ints[4 * 4 * 4];
    for(int k = 0; k < 64; k++) ints[k] = (k * 13) & 127;
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8I, 4, 4, 0, GL_RGBA_INTEGER, GL_BYTE, ints);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(glGetUniformLocation(p, "r"), 0);
    glUniform1i(glGetUniformLocation(p, "b"), 1);
    glUniform1i(glGetUniformLocation(p, "i"), 2);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("rect-buffer-integer-textures", 1);
    glActiveTexture(GL_TEXTURE0);
    glDeleteTextures(3, tex);
    glDeleteBuffers(1, &buffer);
}

/** A multisampled texture drawn into, then read sample by sample */
static void test_multisample_texture(void)
{
    GLuint ms, f;
    glGenTextures(1, &ms);
    glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, ms);
    glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, 4, GL_RGBA8, W, H, 1);
    glGenFramebuffers(1, &f);
    glBindFramebuffer(GL_FRAMEBUFFER, f);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, ms, 0);
    glViewport(0, 0, W, H);
    glClearColor(0.25f, 0.5f, 0.75f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    fresh_vao();
    program(VS33 "in vec2 p; void main() { gl_Position = vec4(p * 0.5, 0.0, 1.0); }", VS33 "out vec4 o; void main() { o = vec4(1.0, 0.0, 0.5, 1.0); }");
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glDeleteFramebuffers(1, &f);
    target(0);
    fresh_vao();
    program(VS33 "in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }",
        VS33 "uniform sampler2DMS s; out vec4 o; void main() { ivec2 at = ivec2(gl_FragCoord.xy); o = vec4(0.0);\n"
        "  for(int i = 0; i < 4; i++) o += texelFetch(s, at, i) * 0.25; }");
    vbo(0, 2, quad, sizeof(quad));
    glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, ms);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    // (the quad's edges: sample positions differ between GPUs)
    finish("multisample-texture", 2);
    glDeleteTextures(1, &ms);
}

static void run_gl33(EGLDisplay display)
{
    eglBindAPI(EGL_OPENGL_API);
    const EGLint attributes[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3,
        EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE };
    EGLContext context = eglCreateContext(display, 0, 0, attributes);
    if(!context || !eglMakeCurrent(display, 0, 0, context))
    {
        printf("GLTEST gl33 FAIL no context (%x)\n", eglGetError());
        failures++;
        return;
    }
    vao = 0;
    printf("GLTEST renderer %s, %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
    test_geometry_shader();
    test_clip_distance();
    test_texture_33();
    test_multisample_texture();
}


// ---------------------------------------------------------------------------
// OpenGL 4.3 core

#define VS43 "#version 430 core\n"

static GLuint program_stages(const GLenum *types, const char *const *sources, int count)
{
    GLuint p = glCreateProgram();
    for(int i = 0; i < count; i++)
    {
        GLuint s = shader(types[i], sources[i]);
        glAttachShader(p, s);
        glDeleteShader(s);
    }
    glLinkProgram(p);
    GLint ok = 0;
    glGetProgramiv(p, GL_LINK_STATUS, &ok);
    if(!ok)
    {
        char log[1024];
        glGetProgramInfoLog(p, sizeof(log), 0, log);
        printf("link: %s\n", log);
    }
    glUseProgram(p);
    return p;
}

/** A compute shader: shared memory, a barrier, a storage buffer with an atomic, an image */
static void test_compute(void)
{
    const char *cs = VS43 "layout(local_size_x = 8, local_size_y = 8) in;\n"
        "layout(std430, binding = 0) buffer Out { uint count; uint data[]; };\n"
        "layout(rgba8, binding = 0) writeonly uniform image2D img;\n"
        "shared uint tile[64];\n"
        "uniform uint scale;\n"
        "void main() { uvec2 g = gl_GlobalInvocationID.xy; uint i = gl_LocalInvocationIndex;\n"
        "  tile[i] = g.x * scale + g.y; barrier();\n"
        "  uint v = tile[63u - i];\n"
        "  atomicAdd(count, 1u);\n"
        "  data[g.y * 64u + g.x] = v + gl_WorkGroupID.x * 1000u + gl_NumWorkGroups.x * 100000u;\n"
        "  imageStore(img, ivec2(g), vec4(vec2(g) / 64.0, float(i) / 64.0, 1.0)); }";
    GLenum type = GL_COMPUTE_SHADER;
    GLuint p = program_stages(&type, &cs, 1);
    glUniform1ui(glGetUniformLocation(p, "scale"), 3);
    target(0);
    glBindImageTexture(0, fbo_color, 0, 0, 0, GL_WRITE_ONLY, GL_RGBA8);
    GLuint b;
    glGenBuffers(1, &b);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, b);
    static unsigned int zeros[1 + 64 * 64];
    glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(zeros), zeros, GL_STREAM_READ);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, b);
    glUseProgram(p);
    glDispatchCompute(8, 8, 1);
    glMemoryBarrier(GL_ALL_BARRIER_BITS);
    static unsigned char data[16384];
    const void *mapped = glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, 16384, GL_MAP_READ_BIT);
    if(mapped) memcpy(data, mapped, 16384);
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    result("compute-buffer", data, 16384, 0, 0);
    glDeleteBuffers(1, &b);
    finish("compute-image", 0);
}

/** A fragment shader with a storage buffer (atomics) and an image it reads */
static void test_fragment_storage(void)
{
    // an image to read: a gradient
    GLuint img;
    glGenTextures(1, &img);
    glBindTexture(GL_TEXTURE_2D, img);
    glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32UI, 16, 16);
    static unsigned int texels[256];
    for(int i = 0; i < 256; i++) texels[i] = i * 977u;
    glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 16, 16, GL_RED_INTEGER, GL_UNSIGNED_INT, texels);
    target(0);
    fresh_vao();
    GLenum types[2] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };
    const char *sources[2] = {
        VS43 "in vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }",
        VS43 "layout(std430, binding = 1) buffer Counts { uint total; uint rows[64]; };\n"
        "layout(r32ui, binding = 1) readonly uniform uimage2D src; out vec4 o;\n"
        "void main() { ivec2 at = ivec2(gl_FragCoord.xy); uint v = imageLoad(src, at / 4).x;\n"
        "  atomicAdd(total, 1u); atomicMax(rows[at.y], uint(at.x));\n"
        "  o = vec4(float(v & 255u) / 255.0, float((v >> 8) & 255u) / 255.0, 0.25, 1.0); }" };
    program_stages(types, sources, 2);
    vbo(0, 2, quad, sizeof(quad));
    glBindImageTexture(1, img, 0, 0, 0, GL_READ_ONLY, GL_R32UI);
    GLuint b;
    glGenBuffers(1, &b);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, b);
    static unsigned int zeros[65];
    glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(zeros), zeros, GL_STREAM_READ);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, b);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glMemoryBarrier(GL_ALL_BARRIER_BITS);
    static unsigned char data[65 * 4];
    const void *mapped = glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, sizeof(data), GL_MAP_READ_BIT);
    if(mapped) memcpy(data, mapped, sizeof(data));
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    result("fragment-storage-buffer", data, sizeof(data), 0, 0);
    glDeleteBuffers(1, &b);
    finish("fragment-image-load", 1);
    glDeleteTextures(1, &img);
}

/** Tessellation: a quad patch into a grid, colored by where its vertices are */
static void test_tessellation(void)
{
    target(0);
    fresh_vao();
    GLenum types[4] = { GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER };
    const char *sources[4] = {
        VS43 "in vec2 p; out vec2 v; void main() { v = p; }",
        VS43 "layout(vertices = 4) out; in vec2 v[]; out vec2 c[]; patch out float shade;\n"
        "void main() { c[gl_InvocationID] = v[gl_InvocationID] * 0.9;\n"
        "  if(gl_InvocationID == 0) { gl_TessLevelOuter[0] = 2.0; gl_TessLevelOuter[1] = 3.0; gl_TessLevelOuter[2] = 4.0;\n"
        "    gl_TessLevelOuter[3] = 5.0; gl_TessLevelInner[0] = 4.0; gl_TessLevelInner[1] = 3.0; shade = 0.75; } }",
        VS43 "layout(quads, equal_spacing, ccw) in; in vec2 c[]; patch in float shade; out vec3 color;\n"
        "void main() { vec2 a = mix(c[0], c[1], gl_TessCoord.x), b = mix(c[3], c[2], gl_TessCoord.x);\n"
        "  color = vec3(gl_TessCoord.xy, shade); gl_Position = vec4(mix(a, b, gl_TessCoord.y), 0.0, 1.0); }",
        VS43 "in vec3 color; out vec4 o; void main() { o = vec4(color, 1.0); }" };
    program_stages(types, sources, 4);
    const float corners[] = { -1, -1, 1, -1, 1, 1, -1, 1 };
    vbo(0, 2, corners, sizeof(corners));
    glPatchParameteri(GL_PATCH_VERTICES, 4);
    glDrawArrays(GL_PATCHES, 0, 4);
    finish("tessellation", 2);
}

/** Doubles (GX computes them as floats: values floats hold exactly) */
static void test_doubles(void)
{
    target(0);
    fresh_vao();
    GLenum types[2] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };
    const char *sources[2] = {
        VS43 "in vec2 p; out vec2 t; void main() { t = p * 0.5 + 0.5; gl_Position = vec4(p, 0.0, 1.0); }",
        VS43 "uniform double k; in vec2 t; out vec4 o;\n"
        "void main() { dvec2 d = dvec2(t) * k + dvec2(0.25, 0.5); double m = max(d.x, d.y) - floor(d.y);\n"
        "  o = vec4(vec2(fract(d)), float(m * 0.5), 1.0); }" };
    GLuint p = program_stages(types, sources, 2);
    glUniform1d(glGetUniformLocation(p, "k"), 2.0);
    vbo(0, 2, quad, sizeof(quad));
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    finish("doubles", 2);
}

/** Indirect draws, with and without indices; texture gathers with offsets */
static void test_indirect_gather(void)
{
    target(0);
    fresh_vao();
    GLenum types[2] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };
    const char *sources[2] = {
        VS43 "in vec2 p; out vec2 t; flat out int instance; void main() { t = p * 0.5 + 0.5; instance = gl_InstanceID;\n"
        "  gl_Position = vec4(p * 0.45 + vec2(gl_InstanceID % 2, gl_InstanceID / 2) - 0.5, 0.0, 1.0); }",
        VS43 "uniform sampler2D s; in vec2 t; flat in int instance; out vec4 o;\n"
        "void main() { vec4 g = textureGatherOffset(s, t, ivec2(instance - 1, 1), 1);\n"
        "  o = vec4(g.xy, g.z * 0.5 + g.w * 0.5, 1.0); }" };
    GLuint p = program_stages(types, sources, 2);
    vbo(0, 2, quad, sizeof(quad));
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    static unsigned char texels[8 * 8 * 4];
    for(int i = 0; i < 64; i++) { texels[4 * i] = i * 4; texels[4 * i + 1] = 255 - i * 4; texels[4 * i + 2] = (i * 37) & 255; texels[4 * i + 3] = 255; }
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, texels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glUniform1i(glGetUniformLocation(p, "s"), 0);
    // two instances without indices (from the second), two with
    const unsigned int arrays[4] = { 4, 2, 0, 0 };
    const unsigned int elements[5] = { 4, 2, 0, 0, 2 };
    const unsigned short indices[4] = { 0, 1, 2, 3 };
    GLuint ib, args[2];
    glGenBuffers(1, &ib);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
    glGenBuffers(2, args);
    glBindBuffer(GL_DRAW_INDIRECT_BUFFER, args[0]);
    glBufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(arrays), arrays, GL_STATIC_DRAW);
    glDrawArraysIndirect(GL_TRIANGLE_STRIP, 0);
    glBindBuffer(GL_DRAW_INDIRECT_BUFFER, args[1]);
    glBufferData(GL_DRAW_INDIRECT_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
    glDrawElementsIndirect(GL_TRIANGLE_STRIP, GL_UNSIGNED_SHORT, 0);
    finish("indirect-gather", 1);
    glDeleteTextures(1, &tex);
}

static int has_extension(const char *name)
{
    GLint count = 0;
    glGetIntegerv(GL_NUM_EXTENSIONS, &count);
    for(int i = 0; i < count; i++)
    {
        const GLubyte *e = glGetStringi(GL_EXTENSIONS, i);
        if(e && !strcmp((const char *)e, name)) return 1;
    }
    return 0;
}

/** Wait until the GPU has done everything so far (a fence, as persistent mappings need) */
static void wait_gpu(void)
{
    GLsync sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
    glClientWaitSync(sync, GL_SYNC_FLUSH_COMMANDS_BIT, 5000000000ul);
    glDeleteSync(sync);
}

/**
 * ARB_buffer_storage: persistent, coherent mappings (virtio-gpu's host
 * visible memory). Vertices written through a mapping while it stays mapped,
 * in pages far apart and again after the GPU used them; a compute shader that
 * reads its input through one and writes its output that the CPU reads from it.
 */
static void test_buffer_storage(void)
{
    if(!has_extension("GL_ARB_buffer_storage"))
    {
        printf("GLTEST buffer-storage skipped (no GL_ARB_buffer_storage)\n");
        return;
    }
    target(0);
    fresh_vao();
    GLenum types[2] = { GL_VERTEX_SHADER, GL_FRAGMENT_SHADER };
    const char *sources[2] = {
        VS43 "layout(location = 0) in vec2 p; layout(location = 1) in vec3 c; out vec3 v;\n"
        "void main() { v = c; gl_Position = vec4(p, 0.0, 1.0); }",
        VS43 "in vec3 v; out vec4 o; void main() { o = vec4(v, 1.0); }" };
    program_stages(types, sources, 2);
    const int size = 65536;
    const GLbitfield flags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
    GLuint b;
    glGenBuffers(1, &b);
    glBindBuffer(GL_ARRAY_BUFFER, b);
    glBufferStorage(GL_ARRAY_BUFFER, size, 0, flags);
    float *mapped = glMapBufferRange(GL_ARRAY_BUFFER, 0, size, flags);
    if(!mapped)
    {
        printf("GLTEST buffer-storage FAIL no mapping (%x)\n", glGetError());
        failures++;
        return;
    }
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    // a triangle: x, y, r, g, b each vertex
    const float tri[3][15] = {
        { -0.9f, -0.9f, 1, 0, 0, -0.1f, -0.9f, 1, 0, 0, -0.5f, -0.1f, 1, 1, 0 },
        { 0.1f, -0.9f, 0, 1, 0, 0.9f, -0.9f, 0, 1, 0, 0.5f, -0.1f, 0, 1, 1 },
        { -0.4f, 0.1f, 0, 0, 1, 0.4f, 0.1f, 0, 0, 1, 0.0f, 0.9f, 1, 0, 1 },
    };
    // the first at the start, the second 32 KiB in
    memcpy(mapped, tri[0], sizeof(tri[0]));
    memcpy((char *)mapped + 32768, tri[1], sizeof(tri[1]));
    for(int k = 0; k < 2; k++)
    {
        const long at = k ? 32768 : 0;
        glVertexAttribPointer(0, 2, GL_FLOAT, 0, 20, (const void *)at);
        glVertexAttribPointer(1, 3, GL_FLOAT, 0, 20, (const void *)(at + 8));
        glDrawArrays(GL_TRIANGLES, 0, 3);
    }
    // the first one's bytes again, once the GPU has drawn it
    wait_gpu();
    memcpy(mapped, tri[2], sizeof(tri[2]));
    glVertexAttribPointer(0, 2, GL_FLOAT, 0, 20, (const void *)0);
    glVertexAttribPointer(1, 3, GL_FLOAT, 0, 20, (const void *)8);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    finish("buffer-storage-vertices", 2);
    glDeleteBuffers(1, &b);

    // compute: in[i] written by the CPU, out[i] = in[i] * 3 + i read by it
    const char *cs = VS43 "layout(local_size_x = 64) in;\n"
        "layout(std430, binding = 2) buffer Data { uint in_[1024]; uint pad[1024]; uint out_[1024]; };\n"
        "void main() { uint i = gl_GlobalInvocationID.x; out_[i] = in_[i] * 3u + i; }";
    GLenum type = GL_COMPUTE_SHADER;
    program_stages(&type, &cs, 1);
    const GLbitfield rw = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
    glGenBuffers(1, &b);
    glBindBuffer(GL_SHADER_STORAGE_BUFFER, b);
    glBufferStorage(GL_SHADER_STORAGE_BUFFER, 3 * 4096, 0, rw);
    unsigned int *words = glMapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, 3 * 4096, rw);
    if(!words)
    {
        printf("GLTEST buffer-storage FAIL no storage mapping (%x)\n", glGetError());
        failures++;
        return;
    }
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, b);
    static unsigned char data[2 * 4096];
    for(int round = 0; round < 2; round++)
    {
        for(int i = 0; i < 1024; i++) words[i] = i * 7u + round * 100000u;
        glDispatchCompute(16, 1, 1);
        glMemoryBarrier(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT);
        wait_gpu();
        memcpy(data + round * 4096, words + 2048, 4096);
    }
    glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
    result("buffer-storage-compute", data, sizeof(data), 0, 0);
    glDeleteBuffers(1, &b);
}

static void run_gl43(EGLDisplay display)
{
    const EGLint attributes[] = { EGL_CONTEXT_MAJOR_VERSION, 4, EGL_CONTEXT_MINOR_VERSION, 3,
        EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE };
    EGLContext context = eglCreateContext(display, 0, 0, attributes);
    if(!context || !eglMakeCurrent(display, 0, 0, context))
    {
        // (a driver without OpenGL 4.3: these are not its tests)
        printf("GLTEST gl43 skipped (%x)\n", eglGetError());
        return;
    }
    vao = 0;
    printf("GLTEST renderer %s, %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
    test_compute();
    test_fragment_storage();
    test_doubles();
    test_indirect_gather();
    test_tessellation();
    test_buffer_storage();
}

int main(int argc, char **argv, char **envp)
{
    mode_ref = argc > 1 && !strcmp(argv[1], "ref");
    mkdir(dir, 0755);
    EGLDisplay display = eglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA, 0, 0);
    EGLint major, minor;
    if(!display || !eglInitialize(display, &major, &minor))
    {
        printf("GLTEST egl FAIL no display (%x)\n", eglGetError());
        return 1;
    }
    eglBindAPI(EGL_OPENGL_ES_API);
    const EGLint attributes[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 0, EGL_NONE };
    EGLContext context = eglCreateContext(display, 0, 0, attributes);
    if(!context || !eglMakeCurrent(display, 0, 0, context))
    {
        printf("GLTEST egl FAIL no context (%x)\n", eglGetError());
        return 1;
    }
#define LOAD(ret, name, args) name = (ret (*) args)eglGetProcAddress(#name);
    GL_FUNCTIONS(LOAD)
    printf("GLTEST renderer %s, %s\n", glGetString(GL_RENDERER), glGetString(GL_VERSION));
    test_clear();
    test_triangle();
    test_cull();
    test_depth_stencil();
    test_blend();
    test_texture();
    test_swizzle();
    test_mrt();
    test_instancing();
    test_transform_feedback();
    test_occlusion();
    test_blit();
    test_primitives();
    test_flat_indexed();
    test_shadow();
    test_texture_kinds();
    test_cube_faces();
    test_integer_target();
    run_gl33(display);
    run_gl43(display);
    printf("GLTEST done %d failures\n", failures);
    fflush(0);
    return 0;
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/x64/gpu_remote_renderer.mjs                                                        0000644 0000000 0000000 00000023713 00000000000 016224  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // A real GPU for a guest running in node: the display adapter's 3D renderer
// (src/browser/glbridge/svga_renderer.js) in a headless Chrome with WebGPU,
// connected to the device by a WebSocket. The node harnesses keep their
// automation (screenshots of the device's own picture, keys, overlays) and
// the guest's 3D is drawn by the same code a page runs.
//
//   const remote = await create_remote_renderer();
//   new V86({ ..., graphics_adapter_test: { level: "vgpu9", renderer: remote.renderer } });
//
// GL_CHROME selects the browser. Frames on the socket: a type byte, then
//   1 submit: seq (u32), the batch      2 reset      7 submit of a GX batch
//   3 write: offset (u32), the bytes    4 done: seq (u32)
//   5 lost: the reason (UTF-8)          6 ready (the renderer is up)
//   8 log: a line of the renderer's     9 submit of a VX batch (Venus)

import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import { createHash as create_hash } from "node:crypto";
import { fileURLToPath } from "node:url";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
const TYPES = { submit: 1, reset: 2, write: 3, done: 4, lost: 5, ready: 6, submit_gx: 7, log: 8, submit_vx: 9 };

/** One binary WebSocket frame, server to client (not masked) */
function frame(payload)
{
    const length = payload.length;
    const header = length < 126 ? Buffer.from([0x82, length]) :
        length < 65536 ? Buffer.from([0x82, 126, length >> 8, length & 0xFF]) :
        Buffer.concat([Buffer.from([0x82, 127]), (() => { const b = Buffer.alloc(8); b.writeBigUInt64BE(BigInt(length)); return b; })()]);
    return Buffer.concat([header, payload]);
}

/**
 * The messages in what the client sent so far (masked frames, maybe
 * fragmented); keeps what is incomplete
 */
function frame_reader(on_message)
{
    let pending = Buffer.alloc(0), fragments = [];
    return chunk => {
        pending = Buffer.concat([pending, chunk]);
        for(;;)
        {
            if(pending.length < 2) return;
            const fin = pending[0] & 0x80, opcode = pending[0] & 0xF, masked = pending[1] & 0x80;
            let length = pending[1] & 0x7F, at = 2;
            if(length === 126) { if(pending.length < 4) return; length = pending.readUInt16BE(2); at = 4; }
            else if(length === 127) { if(pending.length < 10) return; length = Number(pending.readBigUInt64BE(2)); at = 10; }
            const mask = masked ? pending.subarray(at, at + 4) : null;
            if(masked) at += 4;
            if(pending.length < at + length) return;
            const payload = Buffer.from(pending.subarray(at, at + length));
            if(mask) for(let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
            pending = pending.subarray(at + length);
            if(opcode === 8) { on_message(null); return; }
            if(opcode === 0 || opcode === 1 || opcode === 2)
            {
                fragments.push(payload);
                if(fin) { on_message(Buffer.concat(fragments)); fragments = []; }
            }
        }
    };
}

/**
 * @param {{timeout: (number|undefined), shader_dir: (string|undefined)}=} options
 * @return {!Promise<{renderer: !Object, close: function(), stats: !Object}>}
 */
export async function create_remote_renderer(options = {})
{
    let socket = null, to_device = null, ready_resolve, ready_reject;
    const ready = new Promise((resolve, reject) => { ready_resolve = resolve; ready_reject = reject; });
    const stats = { batches: 0, bytes: 0, writes: 0 };

    const server = http.createServer((req, res) => {
        const file = path.resolve(root, "." + new URL(req.url, "http://localhost").pathname);
        if(!file.startsWith(root + path.sep)) { res.writeHead(403).end(); return; }
        fs.readFile(file, (error, data) => {
            if(error) { res.writeHead(404).end(); return; }
            res.setHeader("Content-Type", /\.(js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".wasm") ? "application/wasm" : "text/html");
            res.end(data);
        });
    });
    server.on("upgrade", (req, connection) => {
        const accept = create_hash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
        connection.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n");
        connection.setNoDelay(true);
        socket = connection;
        connection.on("data", frame_reader(message => {
            if(!message) return;
            const type = message[0];
            if(type === TYPES.ready) { ready_resolve(); return; }
            if(type === TYPES.log) { console.log("renderer: " + message.subarray(1).toString()); return; }
            if(!to_device) return;
            if(type === TYPES.write)
            {
                stats.writes++;
                to_device({ "type": "write", "offset": message.readUInt32LE(1), "bytes": new Uint8Array(message.subarray(5)) });
            }
            else if(type === TYPES.done) to_device({ "type": "done", "seq": message.readUInt32LE(1) });
            else if(type === TYPES.lost) to_device({ "type": "lost", "reason": message.subarray(1).toString() });
        }));
        connection.on("error", () => {});
    });
    await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
    const port = server.address().port;
    const profile = fs.mkdtempSync(path.join(os.tmpdir(), "v86-gpu-renderer-"));
    const browser = spawn(process.env.GL_CHROME || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", [
        "--headless=new", "--enable-unsafe-webgpu", "--no-first-run", "--no-default-browser-check",
        "--disable-background-networking", "--disable-renderer-backgrounding", "--disable-background-timer-throttling",
        `--user-data-dir=${profile}`,
        `http://127.0.0.1:${port}/tests/glbridge/svga_remote_renderer.html?ws=ws://127.0.0.1:${port}/renderer`,
    ], { stdio: ["ignore", "ignore", "pipe"] });
    // A harness stopped by a signal skips close(); Chrome would outlive it
    const kill_browser = () => browser.kill("SIGKILL");
    process.on("exit", kill_browser);
    for(const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]])
    {
        if(!process.listenerCount(signal)) process.once(signal, () => process.exit(code));
    }
    let stderr = "";
    browser.stderr.on("data", data => { stderr = (stderr + data).slice(-4000); });
    let closing = false;
    browser.on("exit", code => {
        ready_reject(new Error("Chrome exited (" + code + "): " + stderr));
        // after that, the device must not wait for it
        if(!closing && to_device) to_device({ "type": "lost", "reason": "Chrome exited (" + code + ")" });
    });
    const timer = setTimeout(() => ready_reject(new Error("the renderer page did not come up\n" + stderr)), options.timeout || 30000);
    try
    {
        await ready;
    }
    finally
    {
        clearTimeout(timer);
    }

    // options.shader_dir: Venus's shaders (VX SHADER_CREATE: SPIR-V, by
    // content) and pipelines (PIPELINE_CREATE, with their shaders' files)
    // written there, a corpus for VX's translation (vx/naga)
    const shader_files = new Map();
    const dump_vx = bytes => {
        const words = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
        if(words[0] !== 0x30315856) return;
        for(let at = 4, end = Math.min(words[2], words.length); at + 2 <= end;)
        {
            const op = words[at], n = words[at + 1], body = words.subarray(at + 2, at + 2 + n);
            at += 2 + n;
            if(op === 18)
            {
                const spirv = Buffer.from(body.buffer, body.byteOffset + 8, body[1]);
                const name = create_hash("sha1").update(spirv).digest("hex").slice(0, 16) + ".spv";
                shader_files.set(body[0], name);
                if(!fs.existsSync(options.shader_dir + "/" + name)) fs.writeFileSync(options.shader_dir + "/" + name, spirv);
            }
            else if(op === 19)
            {
                let text = Buffer.from(body.buffer, body.byteOffset + 4, (n - 1) * 4).toString("utf8").replace(/\0+$/, "");
                try
                {
                    const desc = JSON.parse(text);
                    for(const stage of desc["stages"] || []) stage["file"] = shader_files.get(stage["shader"]);
                    fs.appendFileSync(options.shader_dir + "/pipelines.jsonl", JSON.stringify(desc) + "\n");
                }
                catch(e) {}
            }
        }
    };
    if(options.shader_dir) fs.mkdirSync(options.shader_dir, { recursive: true });
    const renderer = {
        "post": message => {
            if(!socket) return;
            if(message["type"] === "submit")
            {
                const bytes = message["bytes"], head = Buffer.alloc(5);
                if(options.shader_dir && message["stream"] === "vx") dump_vx(bytes);
                head[0] = message["stream"] === "gx" ? TYPES.submit_gx : message["stream"] === "vx" ? TYPES.submit_vx : TYPES.submit;
                head.writeUInt32LE(message["seq"], 1);
                stats.batches++;
                stats.bytes += bytes.length;
                socket.write(frame(Buffer.concat([head, Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)])));
            }
            else if(message["type"] === "reset")
            {
                socket.write(frame(Buffer.from([TYPES.reset])));
            }
        },
        "listen": handler => { to_device = handler; },
    };
    return {
        renderer,
        stats,
        close: () => {
            closing = true;
            socket && socket.destroy();
            browser.kill();
            process.off("exit", kill_browser);
            server.close();
            // (Chrome may still be writing its profile as it goes)
            setTimeout(() => fs.rm(profile, { recursive: true, force: true, maxRetries: 5 }, () => {}), 1000).unref();
        },
    };
}
                                                     source/v64/tests/x64/gpu_trace.mjs                                                                  0000644 0000000 0000000 00000010434 00000000000 014135  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // GPU traces (docs/gpu-devices.md, "Tests"): what a display adapter's device
// sends its 3D renderer, recorded so the renderer can be run on it again
// without the guest (tests/glbridge/svga_trace_replay_browser_test.html). A
// batch is self-contained, so a trace is the batches in order.
//
// File: "V86GTRC1", then records of (u32 type, u32 length, bytes):
//   type 1: a D9WG batch, as the device submitted it
//   type 2: a JSON note (what made the trace)

import fs from "node:fs";
import { setImmediate as set_immediate } from "node:timers";

const MAGIC = "V86GTRC1";
export const TRACE_BATCH = 1;
export const TRACE_NOTE = 2;

/**
 * A renderer for the device's channel that renders nothing: it records each
 * batch and answers at once, readbacks with zeros and queries with 0. The
 * guest then runs as if its frames were black.
 * @param {string} file where the trace goes, or null to keep none
 * @param {Object} note written first
 */
export function create_trace_renderer(file, note)
{
    const fd = file ? fs.openSync(file, "w") : -1;
    const write = (type, bytes) => {
        if(fd < 0) return;
        const header = Buffer.alloc(8);
        header.writeUInt32LE(type, 0);
        header.writeUInt32LE(bytes.length, 4);
        fs.writeSync(fd, header);
        fs.writeSync(fd, bytes);
    };
    if(fd >= 0)
    {
        fs.writeSync(fd, Buffer.from(MAGIC));
        write(TRACE_NOTE, Buffer.from(JSON.stringify(note || {})));
    }
    let to_device = null;
    const stats = { batches: 0, bytes: 0, readbacks: 0, queries: 0 };
    const renderer = {
        "post": message => {
            if(message["type"] !== "submit") return;
            const bytes = message["bytes"];
            stats.batches++;
            stats.bytes += bytes.length;
            write(TRACE_BATCH, bytes);
            const answers = [];
            const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            for(let at = 32; at < 32 + view.getUint32(20, true);)
            {
                const opcode = view.getUint16(at, true), size = view.getUint32(at + 4, true), p = at + 16;
                if(opcode === 12)
                {
                    // READBACK_SURFACE: zeros, as many as asked for
                    const count = view.getUint32(p + 36, true);
                    const answer = new Uint8Array(16 + count);
                    const a = new DataView(answer.buffer);
                    a.setUint32(0, view.getUint32(p + 44, true), true);
                    a.setUint32(4, count, true);
                    a.setUint32(12, 1, true);
                    answers.push({ "type": "write", "offset": view.getUint32(p + 40, true), "bytes": answer });
                    stats.readbacks++;
                }
                else if(opcode === 0x401)
                {
                    // END_QUERY: no samples
                    const answer = new Uint32Array([view.getUint32(p + 12, true), 0, 0, 1]);
                    answers.push({ "type": "write", "offset": view.getUint32(p + 8, true), "bytes": new Uint8Array(answer.buffer) });
                    stats.queries++;
                }
                at += size;
            }
            const seq = message["seq"];
            // later, as a renderer would answer
            set_immediate(() => {
                for(const answer of answers) to_device(answer);
                to_device({ "type": "done", "seq": seq });
            });
        },
        "listen": handler => { to_device = handler; },
    };
    return { renderer, stats, close: () => fd >= 0 && fs.closeSync(fd) };
}

/**
 * @param {!Uint8Array} bytes a trace file
 * @return {{note: Object, batches: !Array<!Uint8Array>}}
 */
export function read_trace(bytes)
{
    if(Buffer.from(bytes.subarray(0, 8)).toString() !== MAGIC) throw new Error("not a GPU trace");
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    let note = null;
    const batches = [];
    for(let at = 8; at + 8 <= bytes.length;)
    {
        const type = view.getUint32(at, true), length = view.getUint32(at + 4, true);
        const body = bytes.subarray(at + 8, at + 8 + length);
        if(type === TRACE_NOTE) note = JSON.parse(Buffer.from(body).toString());
        else if(type === TRACE_BATCH) batches.push(body);
        at += 8 + length;
    }
    return { note, batches };
}
                                                                                                                                                                                                                                    source/v64/tests/x64/guest_builder.mjs                                                              0000644 0000000 0000000 00000001746 00000000000 015027  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // NASM multiboot entry. The guest itself enters long mode and its high alias.
export function long_mode_guest(body, data = "")
{
    return `bits 32
org 0x100000
%define HIGH 0xFFFF800000000000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x3F0000
mov dword [0x200000],0x201003
mov dword [0x200800],0x201003
mov dword [0x201000],0x202003
mov edi,0x202000
mov eax,0x83
mov ecx,512
.pages:
mov [edi],eax
add eax,0x200000
add edi,8
loop .pages
mov eax,cr4
or eax,0x20
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x900
xor edx,edx
wrmsr
mov eax,cr0
or eax,0x80010001
mov cr0,eax
jmp 24:long_mode
bits 64
long_mode:
mov rax,HIGH+high_mode
jmp rax
high_mode:
${body}
mov dword [0x300000],0xC064C064
hlt
jmp $
${data}
align 8
gdt: dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
gdtr: dw 31
dd gdt
image_end:
`;
}
                          source/v64/tests/x64/guest_runner.mjs                                                               0000644 0000000 0000000 00000015300 00000000000 014701  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Shared independent reference runner: both machines execute the same guest bytes.
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawn, spawnSync} from "node:child_process";
import {setImmediate as yield_event, setTimeout as delay} from "node:timers/promises";
import {fileURLToPath} from "node:url";
import { with_jit_switches } from "../lib/jit_switches.mjs";
export const root = fileURLToPath(new URL("../../", import.meta.url));
export function assemble(name, source)
{
    const directory = `${root}build/x64-${name}/`;
    fs.mkdirSync(directory, {recursive: true});
    fs.writeFileSync(directory + "guest.asm", source);
    const result = spawnSync("nasm", ["-f", "bin", "-o", directory + "guest.bin", directory + "guest.asm"], {encoding: "utf8"});
    assert.equal(result.status, 0, result.stderr);
    assert.ok(fs.statSync(directory + "guest.bin").size < 0xF0000, "guest overlaps page tables");
    return directory;
}
// A test interrupted by a signal skips `finally`; QEMU would outlive it.
const references = new Set();
process.on("exit", () => { for(const child of references) child.kill("SIGKILL"); });
for(const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]])
{
    process.once(signal, () => process.exit(code));
}
export async function reference(directory, {address = 0x300000, magic = 0xC064C064, length, timeout = 20000})
{
    const child = spawn("qemu-system-x86_64", ["-machine", "pc,accel=tcg", "-cpu", "max,vendor=GenuineIntel,phys-bits=36,-la57,-pdpe1gb", "-m", "32M", "-display", "none", "-serial", "none", "-monitor", "none", "-qmp", "stdio", "-no-reboot", "-no-shutdown", "-kernel", directory + "guest.bin", ...(process.env.X64_QEMU_TRACE ? ["-d", "int", "-D", directory + "qemu.log"] : [])], {stdio: ["pipe", "pipe", "pipe"]});
    references.add(child);
    child.on("exit", () => references.delete(child));
    let input = "", error = "", id = 0;
    const pending = new Map();
    child.stderr.on("data", data => error += data);
    const fail_pending = reason => {
        for(const callback of pending.values()) callback({error: {desc: String(reason)}});
        pending.clear();
    };
    child.on("error", fail_pending);
    child.on("exit", (code, signal) => fail_pending(`QEMU exited (${code}, ${signal}): ${error}`));
    child.stdin.on("error", fail_pending);
    child.stdout.on("data", data => {
        input += data;
        while(input.includes("\n"))
        {
            const end = input.indexOf("\n"), line = input.slice(0, end);
            input = input.slice(end + 1);
            let message;
            try { message = JSON.parse(line); } catch{ continue; }
            if(message.id !== undefined)
            {
                const callback = pending.get(message.id);
                pending.delete(message.id);
                callback?.(message);
            }
        }
    });
    const request = (execute, args = {}) => new Promise((resolve, reject) => {
        const n = id++;
        const timer = setTimeout(() => {
            pending.delete(n);
            reject(new Error(`QEMU monitor timeout for ${execute}: ${error}`));
        }, timeout);
        pending.set(n, message => {
            clearTimeout(timer);
            if(message.error) reject(new Error(JSON.stringify(message.error)));
            else resolve(message.return);
        });
        child.stdin.write(JSON.stringify({execute, arguments: args, id: n}) + "\n");
    });
    try
    {
        await request("qmp_capabilities");
        const deadline = performance.now() + timeout;
        let seen = false;
        while(performance.now() < deadline)
        {
            const value = await request("human-monitor-command", {"command-line": `xp /1wx ${address}`});
            if(value.includes(magic.toString(16))) { seen = true; break; }
            await delay(50);
        }
        if(!seen)
        {
            const registers = await request("human-monitor-command", {"command-line": "info registers"});
            const marker = await request("human-monitor-command", {"command-line": `xp /32gx ${address}`});
            throw new Error("QEMU guest timed out: " + error + "\n" + registers + "\n" + marker);
        }
        await request("stop");
        await request("human-monitor-command", {"command-line": `pmemsave ${address} ${length} "${directory}qemu.bin"`});
        await request("quit");
    }
    // (SIGTERM is only a shutdown request, which -no-shutdown turns into a pause)
    finally { child.kill("SIGKILL"); }
    return fs.readFileSync(directory + "qemu.bin");
}
export async function actual(directory, {address = 0x300000, magic = 0xC064C064, length, timeout = 30000, setup, inspect, options = {}})
{
    const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
    // X64_JIT=1 runs every oracle guest with the JIT (the x64 page tier for
    // long-mode code), X64_IR_TIER0=0 additionally with ir_tier0: false.
    const jit = process.env.X64_JIT ? {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        ...(process.env.X64_IR_TIER0 === "0" ? {ir_tier0: false} : {})} : {};
    // (JIT_SWITCHES too: tests/lib/jit_switches.mjs)
    const emulator = new V86(with_jit_switches({graphics_adapter: "bochs_vga", multiboot: {url: directory + "guest.bin"}, memory_size: 32 << 20, acpi: true,
        cpu_cores: Number(process.env.X64_CORES || 1), disable_jit: true, autostart: false, log_level: 0, ...jit, ...options}));
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        const cpu = emulator.v86.cpu;
        if(setup) await setup(emulator);
        const deadline = performance.now() + timeout;
        let rounds = 0;
        while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(address, true) !== magic)
        {
            try
            {
                if(performance.now() > deadline) throw new Error("Guest timed out");
                cpu.run_cores();
            }
            catch(error)
            {
                fs.writeFileSync(directory + "v86-failure.bin", cpu.mem8.slice(address, address + length));
                console.error("Guest failure", JSON.stringify(cpu.get_diagnostics()));
                console.error("Wide RIP", cpu.wm.exports["memory"].buffer ? Array.from(new Uint32Array(cpu.wasm_memory.buffer, 1584, 2)) : "");
                throw error;
            }
            if((++rounds & (options.disable_jit === false ? 0 : 255)) === 0) await yield_event();
        }
        const result = Buffer.from(cpu.mem8.slice(address, address + length));
        fs.writeFileSync(directory + "v86.bin", result);
        if(inspect) await inspect(emulator);
        return result;
    }
    finally { await emulator.destroy(); }
}
                                                                                                                                                                                                                                                                                                                                source/v64/tests/x64/high_memory.mjs                                                                0000644 0000000 0000000 00000012130 00000000000 014466  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// high_memory_size: the top of RAM appears at guest physical 4 GiB. A long-mode
// guest maps it with its own page tables, writes and executes there, and the
// host checks the relocated backing bytes and the multiboot memory map.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const MiB = 1 << 20;
const memory_size = 64 * MiB, high = 16 * MiB, low = memory_size - high;
// PDPT[4] -> PD at 0x203000 mapping [4 GiB, 4 GiB + 16 MiB) with 2 MiB pages,
// at linear 0x100000000 (identity) through the low PML4 entry.
const body = `
mov qword [0x201020], 0x203003
mov rdi, 0x203000
mov rax, 0x100000083
mov ecx, 8
.map:
mov [rdi], rax
add rax, 0x200000
add rdi, 8
loop .map
mov rax, cr3
mov cr3, rax
mov rbx, 0x100000000
mov rax, 0x1122334455667788
mov [rbx], rax
mov [rbx + 0xFFFFF8], rax
not rax
mov [rbx + 0x800000], rax
; copy a tiny function to 4 GiB + 1 MiB and call it there
lea rsi, [rel high_code]
lea rdi, [rbx + 0x100000]
mov ecx, high_code_end - high_code
rep movsb
lea rax, [rbx + 0x100000]
call rax
mov [0x300008], rax
mov rax, [rbx]
mov [0x300010], rax
mov rax, [rbx + 0xFFFFF8]
mov [0x300018], rax
; page tables above 4 GiB: copy PML4/PDPT/PD/PD(4 GiB) to 4 GiB + 2 MiB
mov rsi, 0x200000
mov rdi, 0x100200000
mov ecx, 0x4000 / 8
rep movsq
mov rdi, 0x100200000
mov rax, 0x100201003
mov [rdi], rax
mov [rdi + 0x800], rax
mov rax, 0x100202003
mov [rdi + 0x1000], rax
mov rax, 0x100203003
mov [rdi + 0x1020], rax
mov rax, 0x100200000
mov cr3, rax
; a hot function at 4 GiB + 1 MiB (compiled by a JIT), then patched there
lea rsi, [rel hot_code]
lea rdi, [rbx + 0x100000]
mov ecx, hot_code_end - hot_code
rep movsb
mov r12d, 4000
xor r13, r13
.hot:
mov ecx, 10
lea rax, [rbx + 0x100000]
call rax
add r13, rax
dec r12d
jnz .hot
mov [0x300020], r13
mov dword [rbx + 0x100000 + hot_add - hot_code + 2], 0x22
mov ecx, 10
lea rax, [rbx + 0x100000]
call rax
mov [0x300028], rax
mov rax, cr3
mov [0x300030], rax
mov rax, 0x200000
mov cr3, rax
`;
const data = `
high_code:
lea rax, [rel high_code]
ret
high_code_end:
hot_code:
xor eax, eax
hot_add:
add rax, strict dword 0x11
dec rcx
jnz hot_add
ret
hot_code_end:
`;
// Also request the multiboot memory map (header flag bit 1).
const source = long_mode_guest(body, data).replace("dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)", "dd 0x1BADB002,0x10002,-(0x1BADB002+0x10002)");
assert.ok(source.includes("0x10002"));
const directory = assemble("high-memory", source);
let multiboot_map;
const results = [];
for(const jit of [false, true])
{
let stats;
const result = await actual(directory, {length: 56, options: {memory_size, high_memory_size: high, disable_jit: !jit, ir_sync_publication: true},
    inspect: emulator => {
        const cpu = emulator.v86.cpu;
        const view = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
        const info = 0x7C00, count = view.getUint32(info + 44, true), at = view.getUint32(info + 48, true);
        multiboot_map = [];
        for(let offset = 0; offset < count; offset += 24)
        {
            const entry = at + offset;
            multiboot_map.push([view.getBigUint64(entry + 4, true), view.getBigUint64(entry + 12, true), view.getUint32(entry + 20, true)]);
        }
        // The relocated range is the top of the host backing, not low RAM.
        assert.equal(view.getBigUint64(low, true), 0x1122334455667788n, "4 GiB decodes to the top of the backing store");
        assert.equal(view.getBigUint64(low + 0x800000, true), ~0x1122334455667788n & (1n << 64n) - 1n, "high RAM middle");
        assert.equal(view.getBigUint64(memory_size - 8, true), 0x1122334455667788n, "last relocated qword");
        assert.equal(cpu.low_memory_size, low);
        stats = Array.from({length: 13}, (_, i) => cpu.wm.exports.x64_page_stat(i));
    }});
const u64 = offset => result.readBigUInt64LE(offset);
assert.equal(u64(0) & 0xFFFFFFFFn, 0xC064C064n, "guest completed");
assert.equal(u64(8), 0x100100000n, "code fetched and executed at 4 GiB + 1 MiB");
assert.equal(u64(16), 0x1122334455667788n);
assert.equal(u64(24), 0x1122334455667788n);
assert.equal(u64(32), 4000n * 10n * 0x11n, "hot high-RAM code under page tables above 4 GiB");
assert.equal(u64(40), 10n * 0x22n, "the patched high-RAM code runs");
assert.equal(u64(48), 0x100200000n, "CR3 above 4 GiB");
if(jit)
{
    assert.ok(stats[1] > 30000, `page functions ran the high-RAM code: ${stats}`);
    assert.ok(stats[5] >= 1, `the store through 4 GiB retired the compiled page: ${stats}`);
}
results.push(result);
console.log(`${jit ? "page tier" : "interpreter"}: native ${stats[1]}, compiled ${stats[0]}, invalidated ${stats[5]}`);
}
assert.deepEqual(results[1], results[0], "page tier and interpreter agree");
const available = multiboot_map.filter(entry => entry[2] === 1);
assert.ok(available.every(([base, length]) => base + length <= BigInt(low) || base >= 1n << 32n), "no low RAM entry covers the relocated range");
assert.deepEqual(available.at(-1), [1n << 32n, BigInt(high), 1], "multiboot map reports RAM at 4 GiB");
console.log("X64_HIGH_MEMORY_PASS", JSON.stringify(multiboot_map.map(entry => entry.map(String))));
                                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/x64/include/stddef.h                                                               0000644 0000000 0000000 00000000524 00000000000 014515  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The little of <stddef.h> that third_party/vulkan's headers need, for
 * tests/x64/vktest.c (x86_64 Linux, musl; the host has no musl headers) */
#ifndef V86_STDDEF_H
#define V86_STDDEF_H
typedef unsigned long size_t;
typedef long ptrdiff_t;
#define NULL ((void *)0)
#define offsetof(type, member) __builtin_offsetof(type, member)
#endif
                                                                                                                                                                            source/v64/tests/x64/include/stdint.h                                                               0000644 0000000 0000000 00000001003 00000000000 014542  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The little of <stdint.h> that third_party/vulkan's headers need, for
 * tests/x64/vktest.c (x86_64 Linux, LP64) */
#ifndef V86_STDINT_H
#define V86_STDINT_H
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long int64_t;
typedef unsigned long uint64_t;
typedef long intptr_t;
typedef unsigned long uintptr_t;
#define UINT32_MAX 0xFFFFFFFFu
#define UINT64_MAX 0xFFFFFFFFFFFFFFFFul
#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/x64/initial_ram.mjs                                                                0000755 0000000 0000000 00000006564 00000000000 014470  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Guest RAM reads as zero until something writes it, whatever the wasm heap
// it is allocated from held before (cpu/memory.rs allocate_memory). With
// ir_tier0 on, jit::reserve_compiler_heap (the region scheduler's until M11
// of docs/jit-unification-plan.md) frees 16 chunks of
// 2 MiB just before RAM is allocated in their place, and their allocator
// headers used to show up in guest RAM: 0x0020000A00400010 at 0x3FFEA0
// (reported as an x64 page tier write: no guest touched it), a header every
// 2 MiB and the heap's former end marker every 2 MiB + 64 KiB; in every
// configuration, the initial heap's end marker (0x28 at 0x9FDC). Checked in
// each configuration: before the first instruction, all of RAM is zero but
// the multiboot image; after a long-mode guest ran a loop (compiled by the
// page tier), RAM from 0x300000 to its end is zero but the guest's marker.
// With ir_tier0 on, 32 MiB of RAM lies within the memory the heap had used, and
// 64 MiB extends past it.
import assert from "node:assert/strict";
import fs from "node:fs";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const IMAGE = 0x100000, OUT = 0x300000, MARKER = 0xC064C064;
const directory = assemble("initial-ram", long_mode_guest(`
mov ecx,2000000
.loop:
add eax,ecx
dec ecx
jnz .loop
`));
const image = fs.readFileSync(directory + "guest.bin");
const hex = n => "0x" + n.toString(16).toUpperCase();
/** The first qwords that differ (a short message: assert's diff of 32 MiB
 * buffers would take forever), `base` being the guest address of byte 0 */
function differences(bytes, expected, base)
{
    if(bytes.equals(expected)) return "";
    const found = [];
    for(let i = 0; i < bytes.length && found.length < 8; i += 8)
    {
        const value = bytes.readBigUInt64LE(i), want = expected.readBigUInt64LE(i);
        if(value !== want) found.push(`${hex(base + i)}: ${hex(value)} (expected ${hex(want)})`);
    }
    return found.join(", ");
}

const page_tier = {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true};
for(const [label, options] of [
    ["interpreted", {}],
    ["x64 page tier", page_tier],
    ["x64 page tier, 64 MiB", {...page_tier, memory_size: 64 << 20}],
    ["x64 page tier without ir_tier0", {...page_tier, ir_tier0: false}],
])
{
    const size = options.memory_size || 32 << 20;
    const loaded = Buffer.alloc(size);
    image.copy(loaded, IMAGE);
    const finished = Buffer.alloc(size - OUT);
    finished.writeUInt32LE(MARKER, 0);
    let before, native = 0;
    const result = await actual(directory, {length: size - OUT, timeout: 120000, options,
        setup: emulator => {
            const cpu = emulator.v86.cpu;
            assert.equal(cpu.mem8.length, size);
            before = differences(Buffer.from(cpu.mem8.buffer, cpu.mem8.byteOffset, size), loaded, 0);
        },
        inspect: emulator => { native = emulator.v86.cpu.wm.exports.x64_page_stat(1); }});
    assert.equal(before, "", `${label}: before the first instruction, RAM is zero but the multiboot image`);
    assert.equal(differences(result, finished, OUT), "", `${label}: RAM from 0x300000 is zero but the marker`);
    if(options.disable_jit === false) assert.ok(native > 1000000, `${label}: compiled code ran (${native} instructions)`);
    console.log(`PASS (${label}): ${size >> 20} MiB of RAM read as zero until written`);
}
                                                                                                                                            source/v64/tests/x64/integer_oracle.mjs                                                             0000644 0000000 0000000 00000031261 00000000000 015147  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// One genuine 32->64 guest, independently executed by QEMU TCG and v86.
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawn, spawnSync} from "node:child_process";
import {setImmediate as yield_event, setTimeout as delay} from "node:timers/promises";
import {fileURLToPath} from "node:url";
const root=fileURLToPath(new URL("../../",import.meta.url));
const dir=root+"build/x64-integer/";fs.mkdirSync(dir,{recursive:true});
const tests=[];
const registers={8:["r8b","r9b"],16:["r8w","r9w"],32:["r8d","r9d"],64:["r8","r9"]};
const vals=[0n,1n,0x7Fn,0x80n,0x7FFFn,0x8000n,0x7FFFFFFFn,0x80000000n,0x1234567887654321n,0x7FFFFFFFFFFFFFFFn,0x8000000000000000n,0xFFFFFFFFFFFFFFFFn];
function add(code,mask=0x8D5,a=0x87654321FEDCBA98n,b=0x1234567889ABCDEFn,flags=0x8D7){tests.push({code,mask,a,b,flags});}
for(const w of [8,16,32,64]) for(const [op,mask] of [["add",0x8D5],["adc",0x8D5],["sub",0x8D5],["sbb",0x8D5],["and",0x8C5],["or",0x8C5],["xor",0x8C5],["cmp",0x8D5],["test",0x8C5]])
{
    const [a,b]=registers[w];for(let i=0;i<vals.length;i++) for(const carry of [0,1])add(`${op} ${a}, ${b}`,mask,vals[i],vals[(i*5+1)%vals.length],0x802|carry);
}
for(const w of [8,16,32,64]) for(const op of ["rol","ror","rcl","rcr","shl","shr","sar"])
{
    const [a]=registers[w];for(const count of [0,1,2,7,8,15,16,31,32,63,64,255])
    {
        const c=count&(w===64?63:31);const rotate=["rol","ror","rcl","rcr"].includes(op);
        let mask=c===0?0x8D5:rotate?1:0xC4|(c<=w?1:0);if(c===1)mask|=0x800;
        add(`${op} ${a}, ${count}`,mask);
    }
}
for(const w of [8,16,32,64])
{
    const [a,b]=registers[w];for(const op of ["xchg","xadd","cmpxchg"])add(`${op} ${a}, ${b}`,op==="xchg"?0x8D5:0x8D5);
    add(`xadd ${a}, ${a}`);add(`inc ${a}`);add(`dec ${a}`);add(`neg ${a}`);add(`not ${a}`);
}
for(const w of [16,32,64])
{
    const [a,b]=registers[w];for(const op of ["imul","bsf","bsr","popcnt"])
        add(`${op} ${a}, ${b}`,op==="imul"?0x801:op==="popcnt"?0x8D5:0x40);
    for(const op of ["shld","shrd"]) for(const count of [0,1,2,7,15])add(`${op} ${a}, ${b}, ${count}`,count===0?0x8D5:count===1?0x8C5:0xC5);
    for(const op of ["bt","bts","btr","btc"]) for(const index of [0,3,15,31,63])add(`${op} ${a}, ${index}`,1);
    if(w!==32)add(`push ${a}\npop ${b}`);add(`mov ${a}, ${b}`);add(`cmovz ${a}, ${b}`);add(`cmovnz ${a}, ${b}`);
}
for(const op of ["mul","imul","div","idiv"]) for(const w of [16,32,64])
{
    const [a]=registers[w];add(`xor edx, edx\nmov eax, 123\n${op} ${a}`,op==="mul"||op==="imul"?0x801:0,7n);
}
for(const w of [16,32,64])
{
    const [operand,other]=registers[w];
    for(const a of [3n,0xFFFFFFFFFFFFFFFFn,0x8000000000000000n])
    {
        add(`mov rax, -1\nmul ${operand}`,0x801,a);
        add(`mov rax, -17\nimul ${operand}`,0x801,a);
        add(`imul ${operand}, ${other}`,0x801,a,0xFFFFFFFFFFFFFFFFn);
    }
    add(`mov rax, -123\nmov rdx, -1\nidiv ${operand}`,0,7n);
    add(`mov rax, 1\nmov edx, 1\ndiv ${operand}`,0,7n);
}
add("mov r8, 0x1122334455667788\nmov r8d, 0xFFEEDDCC");
add("mov r8, 0x1122334455667788\nmov r8w, 0xAA55");
add("mov r8, 0x1122334455667788\nmov r8b, 0xAA");
add("mov rax, 0x1122334455667788\nmov ah, 0xAB");
add("mov rax, 0x1122334455667788\nmov al, 0xAB");
add("bswap r8");add("bswap r8d");
add("xadd ah, al");add("xadd ah, ah");add("xchg ah, al");add("cmpxchg ah, bl");
add("mov r8, 0x1111222233334444\nmov r9, 0xAABBCCDD00400000\nmov r8, [r9d]");
add("mov r8, 0x400000\nlea r9, [r8+r8*4-37]");
add("lea r8, [rel high_mode]");
add("mov r8, 0xFFFFFFFA00000080\nmovsx r9, r8b");
add("mov r8, 0xFFFFFFFA00008000\nmovsx r9, r8w");
add("mov r8, 0xFFFFFFFA80000000\nmovsxd r9, r8d");
add("enter 32, 0\nleave");
add("call .return_test\njmp .return_done\n.return_test: mov r8, 0x1234567890ABCDEF\nret\n.return_done:");
add("mov rax, 0x8899AABBCCDDEEFF\nmov rdx, 0x1020304050607080\nlock cmpxchg16b [rsi]",0x40);
add("xor eax, eax\nxor edx, edx\nlock cmpxchg16b [rsi]",0x40);
add("mov eax, 0xCCDDEEFF\nmov edx, 0x8899AABB\nlock cmpxchg8b [rsi]",0x40);
add("xor eax, eax\nxor edx, edx\nlock cmpxchg8b [rsi]",0x40);
add("mov r8, -1\nlock xadd [rsi], r8");
add("xchg [rsi], r8");
add("mov rax, 0x8899AABBCCDDEEFF\nlock cmpxchg [rsi], r8");
add("xor eax, eax\nlock cmpxchg [rsi], r8");
add("mov r9, -1\nbts qword [rsi+8], r9",1);
add("mov rcx, 2\nmov rsi, 0x400000\nmov rdi, 0x400010\nrep movsq\nmov rsi, 0x400010\nmov r8, [rsi]\nmov r9, [rsi+8]");
add("mov rcx, 2\nmov rsi, 0x400008\nmov rdi, 0x400018\nstd\nrep movsq\nmov r8, [0x400010]\nmov r9, [0x400018]",0xCD5);
add("mov rcx, 0x1234567800000002\nmov rsi, 0x9999999900400000\nmov rdi, 0xAAAAAAAA00400010\na32 rep movsq\nmov r8, [0x400010]\nmov r9, [0x400018]");
add("mov rcx, 0\nmov rsi, 0xDEADBEEF00000000\nmov rdi, rsi\nrep movsq");
add("mov rcx, 2\nmov rdi, 0x400000\nrep stosq");
add("mov rcx, 2\nmov rsi, 0x400000\nrep lodsq");
add("mov rax, 0x8899AABBCCDDEEFF\nmov rcx, 2\nmov rdi, 0x400000\nrepe scasq");
add("mov rax, 0\nmov rcx, 2\nmov rdi, 0x400000\nrepne scasq");
add("mov rcx, 2\nmov rsi, 0x400000\nmov rdi, 0x400008\nrepe cmpsq");
for(const [name,index] of [["fs",0xC0000100],["gs",0xC0000101]])
{
    add(`mov ecx, ${index}\nmov eax, 0x400000\nmov edx, 0xFFFF8000\nwrmsr\nmov r8, [${name}:0]\nmov r9, [${name}:8]\nxor eax, eax\nxor edx, edx\nwrmsr`);
}
for(const [n,cc] of ["o","no","b","ae","e","ne","be","a","s","ns","p","np","l","ge","le","g"].entries())
{
    for(const flags of [2,0x8D7])
    {
        const label=`cc_${n}_${flags}`;
        add(`mov r8, 0\nj${cc} ${label}\nmov r8, 1\n${label}:`,0x8D5,1n,2n,flags);
        add(`cmov${cc} r8, r9`,0x8D5,1n,2n,flags);
        add(`set${cc} r8b`,0x8D5,0xFFFFFFFFFFFFFFFFn,2n,flags);
    }
}
for(const opcode of ["loop","loope","loopne","jrcxz"])
{
    for(const count of [0,1,2])
    {
        const label=`loop_${opcode}_${count}`;
        add(`mov ecx, ${count}\nmov r8, 0\n${opcode} ${label}\nmov r8, 1\n${label}:`);
    }
}
add("db 0x48,0x66,0x89,0xC8");
add("db 0x66,0x48,0x89,0xC8");
add("db 0x48,0x40,0x89,0xC8");
// Cache hints must consume the full encoding without touching mapped or
// noncanonical operands; MOVNTI retains ordinary stores' architectural value.
add("movnti [rsi], r8d");
add("movnti [rsi], r8");
for(const hint of ["prefetcht0", "prefetcht1", "prefetcht2", "prefetchnta", "prefetchw"])
    add(`mov rax, 0x1234567800000000\n${hint} [rax+0x12345678]`);
for(const width of ["r8w", "r8d", "r8"])
    add(`rdrand ${width}\nmov r8, 0`);
add("db 0xF3,0x0F,0x1E,0xFA"); // ENDBR64 is NOP when CET is absent.
add("db 0xF3,0x0F,0x1E,0xFB"); // ENDBR32 is also NOP in this profile.
const RESULT=0x300000,RECORD=72,MAGIC=0xC064C064;
// With a JIT, every case runs again after its pages are hot, so the last
// passes execute compiled code (cases are idempotent).
const REPEAT=Number(process.env.X64_REPEAT||10);
let body="";
for(let n=0;n<tests.length;n++)
{
    const t=tests[n];body+=`\nmov dword [${RESULT+4}], ${n}\n; case ${n}: ${t.code.replaceAll("\n"," / ")}\nmov rsi, 0x400000\nmov rax, 0x8899AABBCCDDEEFF\nmov [rsi], rax\nmov rax, 0x1020304050607080\nmov [rsi+8], rax\nmov rax, 0x1234567890ABCDEF\nmov rdx, 0x234567890ABCDEF1\nmov rbx, 0x34567890ABCDEF12\nmov rcx, 0x4567890ABCDEF123\nmov r8, 0x${t.a.toString(16)}\nmov r9, 0x${t.b.toString(16)}\npush ${t.flags}\npopfq\n${t.code}\npushfq\npop r10\nmov rdi, ${RESULT+8+n*RECORD}\nmov [rdi], r8\nmov [rdi+8], r9\nmov [rdi+16], rax\nmov [rdi+24], rdx\nmov [rdi+32], rbx\nmov [rdi+40], rcx\nmov [rdi+48], r10\nmov rsi, 0x400000\nmov r10, [rsi]\nmov [rdi+56], r10\nmov r10, [rsi+8]\nmov [rdi+64], r10\n`;
}
const source=`bits 32
org 0x100000
header:
dd 0x1BADB002, 0x10000, -(0x1BADB002+0x10000)
dd header, header, image_end, image_end, start
start:
cli
cld
lgdt [gdtr]
jmp 8:protected
protected:
mov ax, 16
mov ds, ax
mov es, ax
mov ss, ax
mov esp, 0x3F0000
mov dword [0x200000], 0x201003
mov dword [0x200800], 0x201003
mov dword [0x201000], 0x202003
mov edi, 0x202000
mov eax, 0x83
mov ecx, 512
.pages:
mov [edi], eax
add eax, 0x200000
add edi, 8
loop .pages
mov eax, cr4
or eax, 0x20
mov cr4, eax
mov eax, 0x200000
mov cr3, eax
mov ecx, 0xC0000080
rdmsr
or eax, 0x100
wrmsr
mov eax, cr0
or eax, 0x80010001
mov cr0, eax
jmp 24:long_mode
bits 64
long_mode:
mov rax, 0xFFFF800000000000+high_mode
jmp rax
high_mode:
${process.env.X64_JIT ? `mov r12, 1000000\n.warm: add r8, r9\ndec r12\njnz .warm\nmov dword [0x2FFFF0], ${REPEAT}\ncase_repeat:\n` : ""}
${body}
${process.env.X64_JIT ? "dec dword [0x2FFFF0]\njnz case_repeat\n" : ""}
mov dword [${RESULT}], ${MAGIC}
hlt
jmp $
align 8
gdt:
dq 0, 0x00CF9A000000FFFF, 0x00CF92000000FFFF, 0x00AF9A000000FFFF
gdtr: dw 31
dd gdt
image_end:
`;
fs.writeFileSync(dir+"guest.asm",source);fs.writeFileSync(dir+"cases.json",JSON.stringify(tests,(_key,v)=>typeof v==="bigint"?v.toString():v,null,2));
const assembled=spawnSync("nasm",["-f","bin","-o",dir+"guest.bin",dir+"guest.asm"],{encoding:"utf8"});assert.equal(assembled.status,0,assembled.stderr);
assert.ok(fs.statSync(dir+"guest.bin").size<0xF0000,"fixture does not overlap page tables");
async function qemu_oracle()
{
    const q=spawn("qemu-system-x86_64",["-machine","pc,accel=tcg","-cpu","max","-m","32M","-display","none","-serial","none","-monitor","none","-qmp","stdio","-no-reboot","-no-shutdown","-kernel",dir+"guest.bin"],{stdio:["pipe","pipe","pipe"]});
    let input="",error="",id=0;const pending=new Map();q.stderr.on("data",d=>error+=d);
    q.stdout.on("data",d=>{input+=d;while(input.includes("\n")){const end=input.indexOf("\n");const line=input.slice(0,end);input=input.slice(end+1);let msg;try {msg=JSON.parse(line);} catch{continue;} if(msg.id!==undefined){const fn=pending.get(msg.id);pending.delete(msg.id);fn?.(msg);}}});
    const request=(execute,args={})=>new Promise((resolve,reject)=>{const n=id++;pending.set(n,msg=>msg.error?reject(new Error(JSON.stringify(msg.error))):resolve(msg.return));q.stdin.write(JSON.stringify({execute,arguments:args,id:n})+"\n");});
    try
    {
        await request("qmp_capabilities");const deadline=performance.now()+20000;let seen=false;
        while(performance.now()<deadline){const value=await request("human-monitor-command",{"command-line":`xp /1wx ${RESULT}`});if(value.includes(MAGIC.toString(16))){seen=true;break;} await delay(50);}
        assert.ok(seen,"QEMU guest timed out: "+error);
        await request("stop");await request("human-monitor-command",{"command-line":`pmemsave ${RESULT+8} ${tests.length*RECORD} "${dir}qemu.bin"`});await request("quit");
    }
    finally {q.kill();}
    return fs.readFileSync(dir+"qemu.bin");
}
const oracle=await qemu_oracle();assert.equal(oracle.length,tests.length*RECORD);
console.log(`QEMU TCG: ${tests.length} integer/flags/aliases/atomic64/CX16 cases, high RIP reached`);
if(process.env.X64_ORACLE_ONLY)process.exit(0);
const {V86}=await import(+process.env.TEST_RELEASE_BUILD?"../../build/libv86.mjs":"../../src/main.js");
const emulator=new V86({graphics_adapter: "bochs_vga", multiboot:{url:dir+"guest.bin"},memory_size:32<<20,acpi:true,cpu_cores:Number(process.env.X64_CORES||1),disable_jit:!process.env.X64_JIT,experimental_smp_jit:true,ir_sync_publication:true,autostart:false,log_level:0});
try
{
    await new Promise(resolve=>emulator.add_listener("emulator-loaded",resolve));const cpu=emulator.v86.cpu;
    const view=()=>new DataView(cpu.mem8.buffer,cpu.mem8.byteOffset);const deadline=performance.now()+30000;let rounds=0;
    while(view().getUint32(RESULT,true)!==MAGIC){if(performance.now()>deadline) throw new Error("v86 guest stalled at case "+view().getUint32(RESULT+4,true)+": "+JSON.stringify(cpu.get_diagnostics()));try {cpu.run_cores();} catch(error) {console.error("guest failure",JSON.stringify(cpu.get_diagnostics()),"case",view().getUint32(RESULT+4,true));throw error;} if(process.env.X64_JIT || (++rounds&255)===0) await yield_event();}
    fs.writeFileSync(dir+"v86.bin",cpu.mem8.slice(RESULT+8,RESULT+8+tests.length*RECORD));const expected=new DataView(oracle.buffer,oracle.byteOffset);
    for(let n=0;n<tests.length;n++) for(let field=0;field<9;field++)
    {
        const at=n*RECORD+field*8;const mask=field===6?BigInt(tests[n].mask):0xFFFFFFFFFFFFFFFFn;
        assert.equal(view().getBigUint64(RESULT+8+at,true)&mask,expected.getBigUint64(at,true)&mask,`case ${n} field ${["r8","r9","rax","rdx","rbx","rcx","flags","mem0","mem8"][field]}: ${tests[n].code}`);
    }
    if(process.env.X64_JIT)
    {
        const stat=n=>cpu.wm.exports.x64_page_stat(n);
        const count=stat(1);
        assert.ok(count>tests.length*4,`page functions actually retired instructions; compiled=${stat(0)}, retries=${stat(2)}, steps=${stat(4)}`);
        console.log(`page tier: retired=${count} compiled=${stat(0)} retries=${stat(2)} unknown=${stat(3)} steps=${stat(4)} templated=${stat(10)}/${stat(9)}`);
    }
    console.log(`PASS: v86 agrees with independent QEMU on ${tests.length} integer guest cases`);
}
finally {await emulator.destroy();}
                                                                                                                                                                                                                                                                                                                                               source/v64/tests/x64/irq_boundary.mjs                                                               0000644 0000000 0000000 00000005733 00000000000 014670  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// External interrupts raised by a device callback inside a long-mode
// instruction are delivered at the next instruction boundary: the handler
// runs once, sees the following RIP, and IRETQ restores the original stack.
// Expected values follow the SDM interrupt-delivery rules (Vol.3A §6.6).
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawnSync} from "node:child_process";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const body = `
lidt [rel idtr]
lea rax, [rel irq1]
mov word [rel idt+0x21*16], ax
mov word [rel idt+0x21*16+2], 0x18
mov word [rel idt+0x21*16+4], 0x8E00
shr rax, 16
mov word [rel idt+0x21*16+6], ax
shr rax, 16
mov dword [rel idt+0x21*16+8], eax
; ICW1-4: master PIC at vector 0x20, slave at 0x28, 8086 mode.
mov al, 0x11
out 0x20, al
out 0xA0, al
mov al, 0x20
out 0x21, al
mov al, 0x28
out 0xA1, al
mov al, 4
out 0x21, al
mov al, 2
out 0xA1, al
mov al, 1
out 0x21, al
out 0xA1, al
mov al, 0xFF
out 0xA1, al
mov al, 0xFD
out 0x21, al
mov rbp, rsp
sti
; Case 1: the 8042 raises IRQ1 while executing this OUT.
mov al, 0x20
out 0x64, al
after_device_out:
nop
nop
mov [0x300008], rbp
mov [0x300010], rsp
pushfq
pop qword [0x300018]
; Case 2: IRQ1 becomes pending while masked; unmasking it in OUT delivers it.
cli
mov al, 0xFF
out 0x21, al
mov al, 0x20
out 0x64, al
sti
mov al, 0xFD
out 0x21, al
after_unmask_out:
nop
mov [0x300020], rsp
cli
`;
const data = `
irq1:
mov rax, [rsp]
mov rcx, [rel count]
mov [0x300040+rcx*8], rax
inc qword [rel count]
in al, 0x60
mov al, 0x20
out 0x20, al
iretq
align 8
count: dq 0
idtr: dw 0x22*16-1
dq HIGH+idt
align 16
idt: times 0x22*16 db 0
`;
const source = long_mode_guest(body, data);
const directory = assemble("irq-boundary", source);
const result = await actual(directory, {length: 0x60, timeout: 20000});
const u64 = offset => result.readBigUInt64LE(offset);
function label_address(name)
{
    // Assemble a copy that appends the label's link address.
    const probe = source.replace("image_end:\n", `image_end:\ndq ${name}\n`);
    fs.writeFileSync(directory + "probe.asm", probe);
    const out = spawnSync("nasm", ["-f", "bin", "-o", directory + "probe.bin", directory + "probe.asm"], {encoding: "utf8"});
    assert.equal(out.status, 0, out.stderr);
    const bytes = fs.readFileSync(directory + "probe.bin");
    return 0xFFFF800000000000n + bytes.readBigUInt64LE(bytes.length - 8);
}
assert.equal(u64(0), 0xC064C064n, "guest completed");
assert.equal(u64(0x08), u64(0x10), "IRETQ restored RSP after device-raised IRQ");
assert.notEqual(u64(0x18) & 0x200n, 0n, "IF restored");
assert.equal(u64(0x20), u64(0x08), "IRETQ restored RSP after unmask-delivered IRQ");
assert.equal(u64(0x40), label_address("after_device_out"), "return RIP follows the device OUT");
assert.equal(u64(0x48), label_address("after_unmask_out"), "return RIP follows the unmasking OUT");
assert.equal(u64(0x50), 0n, "exactly two deliveries");
console.log("X64_IRQ_BOUNDARY_PASS");
                                     source/v64/tests/x64/kept_translations.mjs                                                          0000644 0000000 0000000 00000005470 00000000000 015734  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The translations an x64 page function keeps per base register while it runs
// (docs/jit-unification-plan.md P4.21, x64_fast_lookup with inline lookups)
// must not serve an access that only ends in their page: a hot loop reads and
// writes through RBX in a page and across the boundary with the page before
// it, the two mapped to physical pages that are not adjacent (4 KiB pages in
// reverse order), so a translation of the second page applied to the crossing
// access would reach the wrong memory. Results equal the interpreter's.
import assert from "node:assert/strict";
import { assemble, actual } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";

// linear 0x800000-0x9FFFFF: a page table at 0x700000 maps page i to physical
// 0xA00000 + (511 - i) * 4096 (PD entry 4 points to it)
const TABLE = 0x700000, LINEAR = 0x800000, PHYSICAL = 0xA00000, ROUNDS = 30000;
const body = `
mov rdi, ${TABLE}
xor ecx, ecx
map:
mov eax, 511
sub eax, ecx
shl rax, 12
add rax, ${PHYSICAL} | 3
mov [rdi + rcx * 8], rax
inc ecx
cmp ecx, 512
jne map
mov qword [0x202020], ${TABLE} | 3
mov rax, cr3
mov cr3, rax
; the pattern: each byte of the 2 MiB its linear offset's low byte
mov rdi, ${LINEAR}
xor ecx, ecx
fill:
mov [rdi + rcx], cl
inc ecx
cmp ecx, 0x200000
jne fill
mov rbx, ${LINEAR + 0x5000}
xor r8, r8
xor r9, r9
mov ecx, ${ROUNDS}
hot:
mov rax, [rbx + 8]
add r8, rax
mov rdx, [rbx - 4]
add r9, rdx
mov [rbx - 2], ax
mov eax, [rbx + 16]
xor r8, rax
mov [rbx - 3], edx
add r9, [rbx - 6]
mov rdx, rcx
and edx, 7
shl edx, 12
mov rbx, ${LINEAR + 0x5000}
add rbx, rdx
dec ecx
jnz hot
mov [0x300008], r8
mov [0x300010], r9
`;
const directory = assemble("kept-translations", long_mode_guest(body));
const runs = [];
for(const [label, options] of [
    ["interpreter", { disable_jit: true }],
    ["page tier", { disable_jit: false, ir_sync_publication: true,
        jit_switches: { x64_fast_lookup: 1, x64_hot_inline: 1, x64_outline: 0 } }],
])
{
    let memory, native;
    await actual(directory, {
        length: 24, timeout: 120000, options: { memory_size: 64 << 20, ...options },
        inspect: emulator => {
            const cpu = emulator.v86.cpu;
            memory = Buffer.from(cpu.mem8.slice(0x300008, 0x300018)).toString("hex") +
                Buffer.from(cpu.mem8.slice(PHYSICAL, PHYSICAL + 0x200000)).toString("base64");
            native = cpu.wm.exports.x64_page_stat(1);
        },
    });
    runs.push({ label, memory, native });
}
assert.ok(runs[1].native > ROUNDS * 10, `the page tier ran the loop (${runs[1].native} native instructions)`);
assert.ok(runs[1].memory === runs[0].memory, "the page tier's results and memory equal the interpreter's");
console.log(`PASS kept_translations: page-crossing accesses through a register with a kept translation (${runs[1].native} native instructions)`);
                                                                                                                                                                                                        source/v64/tests/x64/linux_boot.mjs                                                                 0000644 0000000 0000000 00000101340 00000000000 014343  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Unmodified Alpine x86_64 kernel: real Linux boot protocol, firmware and initrd.
// The private CPUID switch is used only for qualification; no public CPU option.
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawn, spawnSync} from "node:child_process";
import {createHash as create_hash} from "node:crypto";
import {setTimeout as delay} from "node:timers/promises";
import {setImmediate as set_immediate} from "node:timers";
import {fileURLToPath} from "node:url";
import {prepare_glibc, check_glibc, qemu_cpu, GLIBC_COMMAND} from "./linux_glibc.mjs";
import {prepare as prepare_alpine} from "../lib/alpine_image.mjs";
const root = fileURLToPath(new URL("../../", import.meta.url));
const directory = root + "build/x64-linux/";
// X64_LINUX_FLAVOR: "virt" (default, the virt kernel) or "lts" (the standard
// ISO's lts kernel, which also has hibernation, for the S4 cycles)
const flavor = process.env.X64_LINUX_FLAVOR || "virt";
assert.ok(["virt", "lts"].includes(flavor), "X64_LINUX_FLAVOR is virt or lts");
// (the pinned ISO, downloaded, checked and unpacked: tests/lib/alpine_image.mjs)
const prepared = await prepare_alpine("x86_64-" + flavor);
const {name, sha256: digest} = prepared.image;
const kernel_file = `boot/vmlinuz-${flavor}`, initrd_file = `boot/initramfs-${flavor}`;
const source = prepared.source;
const hash = bytes => create_hash("sha256").update(bytes).digest("hex");
// 64-bit and compatibility-mode probes from one freestanding source. They are
// delivered as a ustar image on the IDE disk and unpacked by the guest shell.
// Concurrent configurations get separate probe builds and result files.
const cores = Number(process.env.X64_CORES || 1);
// X64_CPU_FEATURES: CPU features of docs/simd-xsave-plan.md, comma-separated
// (e.g. XSAVE); X64_LINUX_GLIBC=1: also the glibc acceptance of plan 11.3
// (tests/x64/linux_glibc.mjs), against a QEMU run with the same features
const features = process.env.X64_CPU_FEATURES ? process.env.X64_CPU_FEATURES.split(",") : [];
const glibc_test = !!+process.env.X64_LINUX_GLIBC;
const tag_for = backend => `${backend}-${cores}c${process.env.X64_HIGH_MEMORY ? "-high" : ""}${flavor === "virt" ? "" : "-" + flavor}` +
    (features.length ? "-" + create_hash("sha256").update(features.join(",")).digest("hex").slice(0, 8) : "") + (glibc_test ? "-glibc" : "") +
    (/\bnoxsave\b/.test(process.env.X64_LINUX_CMDLINE || "") ? "-noxsave" : "");
const tag = tag_for(+process.env.X64_LINUX_QEMU ? "qemu" : +process.env.X64_JIT ? "native" : "interpreter");
const probe_directory = directory + `probe-${tag}/`;
fs.mkdirSync(probe_directory, {recursive: true});
function run(program, args)
{
    const result = spawnSync(program, args, {encoding: "utf8"});
    assert.equal(result.status, 0, `${program}: ${result.stderr || result.error}`);
    return result.stdout.trim();
}
const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
const probe_source = root + "tests/x64/linux_probe.c";
for(const [bits, target, flags, emulation] of [
    [64, "x86_64-unknown-linux-gnu", ["-mno-red-zone"], "elf_x86_64"],
    [32, "i386-unknown-linux-gnu", ["-m32", "-mno-sse", "-mno-mmx"], "elf_i386"],
])
{
    run(process.env.CLANG || "clang", [`--target=${target}`, ...flags, "-O2", "-ffreestanding", "-fno-stack-protector",
        "-fno-pic", "-fno-builtin", "-c", probe_source, "-o", probe_directory + `probe${bits}.o`]);
    run(lld, ["-flavor", "gnu", "-m", emulation, "-static", "-e", "_start", "-o", probe_directory + `linux_probe${bits}`, probe_directory + `probe${bits}.o`]);
}
const glibc = glibc_test ? await prepare_glibc(root, directory, probe_directory + "glibc/", lld) : null;
run("bsdtar", ["--format", "ustar", "--no-xattrs", "--no-mac-metadata", "--uid", "0", "--gid", "0",
    "-cf", probe_directory + "probe.tar", "-C", probe_directory, "linux_probe64", "linux_probe32", ...(glibc ? ["-C", glibc.stage, "glibc"] : [])]);
const probe_disk = fs.readFileSync(probe_directory + "probe.tar");
// v86 runs also bring up virtio-net (Alpine virt has no NE2K driver) and echo
// raw frames on the host (X64_PROBE_NET); the QEMU reference skips that round.
// Extended RAM: X64_EXTENDED_MEMORY=<bytes> of extended RAM after the relocated RAM;
// X64_LINUX_MEMTEST=<MiB>: the probe maps, writes and checks that much and
// counts its pages in extended RAM (they must be there); X64_EXTENDED_CACHE=<bytes>
// of frames that hold it (default 512 MiB)
const extended_memory = Number(process.env.X64_EXTENDED_MEMORY || 0);
// X64_MEMORY=<MiB> of RAM in the WebAssembly heap (default 512; index.html
// puts 2048 there before it adds extended RAM)
const memory_mib = Number(process.env.X64_MEMORY || 512);
const extended_cache = Number(process.env.X64_EXTENDED_CACHE || 0);
const memtest_mib = Number(process.env.X64_LINUX_MEMTEST || 0);
const guest_command = net => (net ? "modprobe virtio_net 2>/dev/null; ifconfig eth0 up && " : "") +
    `tar -xf /dev/sda -C /tmp && /tmp/linux_probe64 ${net ? "net" : ""} && /tmp/linux_probe32 ${net ? "net" : ""}; ` +
    (glibc_test ? GLIBC_COMMAND : "") +
    (memtest_mib ? `grep MemTotal /proc/meminfo; /tmp/linux_probe64 memtest ${memtest_mib} ${extended_first_pfn()}; ` : "") +
    "uname -m; cat /sys/devices/system/cpu/online; grep 'System RAM' /proc/iomem; echo X64_LINUX_BOOT_OK\n";
function extended_first_pfn() { return (2 ** 32 + Number(process.env.X64_HIGH_MEMORY || 0)) / 4096; }
// High memory: relocate this many bytes of RAM to guest physical 4 GiB (v86) or give
// QEMU the same split, so the kernel and probes must use RAM above 4 GiB.
const high_memory = Number(process.env.X64_HIGH_MEMORY || 0);
// Sleep states: X64_LINUX_SLEEP=<cycles> suspends to RAM and hibernates to /dev/sdb
// (a blank disk) that many times each; Alpine's initramfs restores through resume=.
const sleep_cycles = Number(process.env.X64_LINUX_SLEEP || 0);
const cmdline = process.env.X64_LINUX_CMDLINE || "console=ttyS0,115200 earlyprintk=serial,ttyS0,115200 loglevel=7 nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage" +
    // (Alpine's live initramfs handles resume= before it loads disk drivers
    // for the root file system: load the IDE driver first, or /dev/sdb is missing)
    (sleep_cycles ? ",ata_piix resume=/dev/sdb" : "");
// (with noxsave on the command line the kernel leaves CR4.OSXSAVE clear:
// what needs XSAVE is not usable, and AVX instructions are #UD)
const XSAVE_DEPENDENT = ["XSAVE", "AVX", "AVX2", "FMA", "F16C", "XSAVEOPT", "XSAVEC", "XGETBV1", "XSAVES"];
const usable = /\bnoxsave\b/.test(cmdline) ? features.filter(name => !XSAVE_DEPENDENT.includes(name)) : features;
const manifest = {source, iso_sha256: digest, kernel_sha256: hash(fs.readFileSync(directory + kernel_file)),
    initrd_sha256: hash(fs.readFileSync(directory + initrd_file)), cmdline,
    probe_tar_sha256: hash(probe_disk), probe64_sha256: hash(fs.readFileSync(probe_directory + "linux_probe64")),
    probe32_sha256: hash(fs.readFileSync(probe_directory + "linux_probe32"))};
fs.writeFileSync(directory + `image-${tag}.json`, JSON.stringify(manifest, null, 2) + "\n");
if(+process.env.X64_LINUX_PREPARE_ONLY) process.exit(0);
function check_probes(text, net)
{
    for(const bits of [64, 32])
    {
        const line = text.match(new RegExp(`X64_PROBE_OK arch=${bits} cpus=(\\d+) threads=\\d+ counter=(\\d+) cpu_checks=([\\d,]+)`));
        assert.ok(line, `${bits}-bit probe result: ${text.match(new RegExp(`X64_PROBE_FAIL arch=${bits}[^\\r\\n]*`))?.[0] || "missing"}`);
        assert.equal(+line[1], cores, `${bits}-bit probe sees every online CPU`);
        assert.equal(+line[2], cores * 20000, `${bits}-bit LOCKed counter`);
        assert.deepEqual(line[3].split(",").map(Number), Array.from({length: cores}, (_, i) => i), `${bits}-bit threads ran on each CPU`);
        assert.match(text, new RegExp(`X64_PROBE_OK arch=${bits} [^\\r\\n]* tlb_stale=0 entry=${bits === 32 ? "vdso" : "syscall"}`), `${bits}-bit remote TLB shootdown and system call entry`);
        const matrix = text.match(new RegExp(`X64_PROBE_XC arch=${bits} packages=1 cores=(\\d+) threads_per_core=1 migrations=(\\d+) signals=(\\d+) smc_rounds=64 direct_io=1`));
        assert.ok(matrix, `${bits}-bit multicore matrix: ${text.match(new RegExp(`X64_PROBE_FAIL arch=${bits}[^\\r\\n]*`))?.[0] || "missing"}`);
        assert.deepEqual(matrix.slice(1).map(Number), [cores, cores * 24, cores * 16], `${bits}-bit topology, migrations and signals`);
        const placed = +text.match(new RegExp(`X64_PROBE_OK arch=${bits} [^\\r\\n]* high_pages=(\\d+)`))[1];
        if(high_memory || extended_memory) assert.ok(placed > 0, `${bits}-bit process received frames above 4 GiB`);
        else assert.equal(placed, 0, `${bits}-bit process: no RAM above 4 GiB exists`);
        if(net) assert.match(text, new RegExp(`X64_PROBE_NET arch=${bits} frames=16`), `${bits}-bit raw frames through eth0 (virtio-net) and back`);
        // YMM fingerprints across context switches: twice as many threads as
        // CPUs, 8 rounds of 5 steps (one of them a signal) each
        const ymm = text.match(new RegExp(`X64_PROBE_YMM arch=${bits} avx=(\\d)(?: registers=(\\d+) threads=(\\d+) steps=(\\d+) signals=(\\d+) bad=(\\d+))?`));
        assert.ok(ymm, `${bits}-bit YMM probe: ${text.match(new RegExp(`X64_PROBE_FAIL arch=${bits}[^\\r\\n]*`))?.[0] || "missing"}`);
        if(usable.includes("AVX")) assert.deepEqual(ymm.slice(1).map(Number), [1, bits === 64 ? 16 : 8, 2 * cores, 80 * cores, 16 * cores, 0], `${bits}-bit YMM state across context switches`);
        else assert.equal(ymm[1], "0", `${bits}-bit probe: no AVX without the feature`);
    }
}
if(+process.env.X64_LINUX_QEMU)
{
    // (with features: QEMU's CPU gets them, v86's vendor and model)
    const qemu_model = features.length || glibc_test ? qemu_cpu(features) : "qemu64,phys-bits=36,-pdpe1gb";
    const child = spawn("qemu-system-x86_64", ["-machine", `pc,accel=tcg${high_memory ? `,max-ram-below-4g=${(512 << 20) - high_memory}` : ""}`, "-cpu", qemu_model, "-m", "512M",
        "-display", "none", "-monitor", "none", "-serial", "stdio", "-no-reboot", "-no-shutdown",
        "-kernel", directory + kernel_file, "-initrd", directory + initrd_file, "-cdrom", directory + name, "-append", cmdline,
        "-drive", `file=${probe_directory}probe.tar,format=raw,if=ide,index=0,snapshot=on`,
        "-smp", `${Number(process.env.X64_CORES || 1)},sockets=1,cores=${Number(process.env.X64_CORES || 1)},threads=1`,
        ...(process.env.X64_QEMU_TRACE ? ["-d", "in_asm", "-D", directory + "qemu-instructions.log"] : [])],
    {stdio: ["pipe", "pipe", "pipe"]});
    let transcript = "", logged_in = false, command = false;
    let timer;
    try
    {
        await new Promise((resolve, reject) => {
            timer = setTimeout(() => reject(new Error("QEMU Linux boot deadline")), Number(process.env.X64_LINUX_TIMEOUT || 60000));
            child.on("error", reject);
            child.on("exit", code => reject(new Error(`QEMU exited ${code}`)));
            const output = bytes => {
                transcript += bytes;
                if(+process.env.SHOW_LOGS) process.stdout.write(bytes);
                if(transcript.includes("localhost login:") && !logged_in) { child.stdin.write("root\n"); logged_in = true; }
                if(transcript.includes("localhost:~#") && !command) { child.stdin.write(guest_command(false)); command = true; }
                if(/\r?\nX64_LINUX_BOOT_OK\r?\n/.test(transcript)) resolve();
                if(transcript.includes("Kernel panic")) reject(new Error("QEMU kernel panic"));
            };
            child.stdout.on("data", output);
            child.stderr.on("data", output);
        });
        assert.match(transcript, /\r?\nx86_64\r?\n/);
        check_probes(transcript, false);
        if(high_memory) assert.match(transcript, /\n\s*100000000-[0-9a-f]+ : System RAM/, "kernel owns RAM above 4 GiB");
        if(glibc) console.log("X64_LINUX_GLIBC " + JSON.stringify(check_glibc(transcript, usable, glibc.libraries, null)));
        console.log("X64_LINUX_QEMU_PASS");
    }
    finally
    {
        clearTimeout(timer);
        child.kill();
        fs.writeFileSync(directory + `${tag}.serial`, transcript);
    }
    process.exit(0);
}
// The glibc acceptance compares with QEMU under the same features: that run first
let glibc_reference = null;
// (X64_LINUX_GLIBC_TIMES=1: only the times, without the QEMU reference)
if(glibc && !+process.env.X64_LINUX_GLIBC_TIMES)
{
    const reference = spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {env: {...process.env, X64_LINUX_QEMU: "1"}, stdio: "inherit"});
    assert.equal(reference.status, 0, "the QEMU reference run");
    glibc_reference = fs.readFileSync(directory + tag_for("qemu") + ".serial", "utf8");
}
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const jit = !!+process.env.X64_JIT;
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    wasm_path: process.env.WASM_PATH,
    bios: {url: root + "bios/seabios.bin"}, vga_bios: {url: root + "bios/vgabios.bin"},
    bzimage: {url: directory + kernel_file}, initrd: {url: directory + initrd_file},
    cdrom: {url: directory + name}, hda: {buffer: probe_disk.buffer.slice(probe_disk.byteOffset, probe_disk.byteOffset + probe_disk.length)},
    ...(sleep_cycles ? {hdb: {buffer: new ArrayBuffer(256 << 20)}} : {}),
    cmdline, memory_size: memory_mib * (1 << 20), high_memory_size: high_memory, cpu_cores: cores, acpi: true, autostart: false,
    ...(extended_memory ? {extended_memory_size: extended_memory} : {}),
    ...(extended_cache ? {extended_memory_cache: extended_cache} : {}),
    disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: true, log_level: 0, net_device: {type: "virtio"},
    // (the x64 profile, as set_x64_test_capabilities below; LZCNT needs it)
    cpu_type: "x86_64",
    // (exactly X64_CPU_FEATURES, none without it: x86_64's default has every feature, the reference's qemu64 none)
    cpu_features: features, ...(features.length ? {cpu_features_unreleased: true} : {}),
    ...(process.env.X64_IR_TIER0 === "0" ? {ir_tier0: false} : {}),
    // X64_PARALLEL=1: the application processors run in vCPU workers
    ...(+process.env.X64_PARALLEL ? {parallel: true, wasm_path: root + "build/v86-parallel.wasm"} : {}),
});
let serial = "";
// Raw frames of EtherType 88B5 come back with source 02:00:00:00:00:02
let echoed = 0;
emulator.bus.register("net0-send", packet => {
    if(packet.length < 14 || packet[12] !== 0x88 || packet[13] !== 0xB5 || packet[11] !== 1) return;
    const reply = Uint8Array.from(packet);
    reply.set([2, 0, 0, 0, 0, 2], 6);
    echoed++;
    set_immediate(() => emulator.bus.send("net0-receive", reply));
});
let cpu;
let snapshot;
let rounds = 0;
let booted = false;
let execution_error;
let command_sent = false;
const snapshot_markers = ["X64_PROBE_START arch=64", "X64_PROBE_OK arch=64", "X64_PROBE_START arch=32"];
const snapshots_taken = [], snapshot_bytes = [];
const transcript = directory + `v86-${tag}.serial`;
emulator.add_listener("serial0-output-byte", byte => {
    const c = String.fromCharCode(byte);
    serial += c;
    if(+process.env.SHOW_LOGS) process.stdout.write(c);
});
function inspect()
{
    const view = new DataView(cpu.wasm_memory.buffer);
    const u64 = offset => view.getBigUint64(offset, true).toString(16);
    const wide_ip = BigInt(view.getUint32(1584, true)) << 32n | BigInt(cpu.instruction_pointer[0] >>> 0);
    // Read-only diagnostic walk for this 512 MiB fixture: never alters A/D,
    // devices, TLB contents or architectural state.
    const physical = address => {
        if(!(cpu.cr[0] & 0x80000000)) return Number(address);
        if(!(view.getBigUint64(1696, true) & 0x400n)) return null;
        const ram = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset, cpu.mem8.length);
        let table = BigInt(cpu.cr[3] >>> 0) | BigInt(view.getUint32(1612, true)) << 32n;
        for(const shift of [39n, 30n, 21n, 12n])
        {
            const at = Number(table & 0xFFFFFF000n) + Number(address >> shift & 511n) * 8;
            if(at + 8 > ram.byteLength) return null;
            const entry = ram.getBigUint64(at, true);
            if(!(entry & 1n)) return null;
            if(shift === 12n || shift < 39n && entry & 128n)
            {
                const mask = (1n << shift) - 1n;
                return Number(entry & 0xFFFFFF000n & ~mask | address & mask);
            }
            table = entry;
        }
        return null;
    };
    const at = physical(wide_ip);
    return {rounds, rip: (BigInt(view.getUint32(1584, true)) << 32n | BigInt(cpu.instruction_pointer[0] >>> 0)).toString(16),
        previous_rip: (BigInt(view.getUint32(1588, true)) << 32n | BigInt(cpu.previous_ip[0] >>> 0)).toString(16),
        physical_ip: at, instruction_bytes: at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + 16)).toString("hex"),
        gpr: Array.from({length: 16}, (_, i) => ((BigInt(view.getUint32(1360 + i * 4, true)) << 32n) | BigInt(view.getUint32(i < 8 ? 64 + i * 4 : 1424 + (i - 8) * 4, true))).toString(16)),
        efer: u64(1696), cs_long: view.getUint8(1744), serial_bytes: serial.length,
        extended: cpu.extended_pages ? Array.from({length: 14}, (_, i) => cpu.wm.exports.x64_ext_stat(i)) : undefined,
        page_tier: cpu.wm.exports.x64_page_stat ? Object.fromEntries(["compiled", "native", "retries", "unknown", "steps", "invalidated", "entries", "failed", "recompiled", "instructions", "templated", "evicted", "live"].map((name, i) => [name, cpu.wm.exports.x64_page_stat(i)])) : null,
        diagnostics: cpu.get_diagnostics()};
}
try
{
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    cpu = emulator.v86.cpu;
    assert.equal(typeof cpu.wm.exports.set_x64_test_capabilities, "function", "rebuild Wasm with private qualification switch");
    cpu.wm.exports.set_x64_test_capabilities(1);
    // X64_ARCH_CAPABILITIES=0: no IA32_ARCH_CAPABILITIES, so the guest also
    // runs its speculation mitigations (PTI, VERW, ITS thunks).
    if(process.env.X64_ARCH_CAPABILITIES === "0") cpu.wm.exports.set_x64_arch_capabilities(0);
    if(process.env.X64_STEP_PROFILE) cpu.wm.exports.x64_page_profile(1);
    // compiled 32-bit code in compatibility mode (the probe's i386 process)
    // X64_RELAXED_FMA=0: FMA through the exact helper, not relaxed SIMD's
    // fused multiply-adds (an A/B switch for the timings)
    if(process.env.X64_RELAXED_FMA === "0") cpu.wm.exports.ir_set_relaxed_fma(0);
    const run_cores = cpu.run_cores.bind(cpu);
    cpu.run_cores = () => {
        rounds++;
        try { return run_cores(); }
        catch(error) { execution_error = error; emulator.stop(); return 100; }
    };
    emulator.run();
    const started = performance.now();
    const deadline = performance.now() + Number(process.env.X64_LINUX_TIMEOUT || 300000);
    let next_report = performance.now() + 10000;
    while(performance.now() < deadline)
    {
        await delay(10);
        if(execution_error) throw execution_error;
        if(serial.includes("Kernel panic") || serial.includes("not implemented")) throw new Error("Guest kernel reported a failure");
        if(/localhost login:/.test(serial) && !command_sent)
        {
            // (the boot's wall time, for the boot budget of docs/simd-xsave-plan.md 12.2)
            console.log("X64_LINUX_LOGIN_MS " + Math.round(performance.now() - started));
            emulator.serial0_send("root\n");
            command_sent = true;
        }
        if(/localhost:~#/.test(serial) && !booted)
        {
            emulator.serial0_send(guest_command(true));
            booted = true;
        }
        // X64_LINUX_SNAPSHOT=1: save and restore the whole machine while the
        // probes run (threads on every CPU, pending IPIs, page functions).
        // Rounds alternate between the chunked V7 stream, written to and read
        // back from a file (no whole-snapshot buffer on either side), and the
        // single-buffer V6 format.
        for(const marker of snapshot_markers)
        {
            if(+process.env.X64_LINUX_SNAPSHOT && booted && !snapshots_taken.includes(marker) && serial.includes(marker))
            {
                snapshots_taken.push(marker);
                emulator.stop();
                if(snapshots_taken.length % 2)
                {
                    const file = await fs.promises.open(directory + `snapshot-${tag}.v7`, "w+");
                    let bytes = 0, largest = 0, chunks = 0;
                    try
                    {
                        await emulator.save_state_stream(async chunk => {
                            await file.write(chunk, 0, chunk.length, bytes);
                            bytes += chunk.length; chunks++; largest = Math.max(largest, chunk.length);
                        });
                        await emulator.restore_state_stream({size: bytes, read: async (offset, length) => {
                            const data = new Uint8Array(length);
                            const read = (await file.read(data, 0, length, offset))["bytesRead"];
                            return read === length ? data : data.subarray(0, read);
                        }});
                    }
                    finally { await file.close(); fs.rmSync(directory + `snapshot-${tag}.v7`, {force: true}); }
                    assert.ok(largest <= 1 << 20, "V7 chunks are at most 1 MiB");
                    snapshot_bytes.push({format: "V7 stream", bytes, chunks, largest_chunk: largest});
                }
                else
                {
                    const state = await emulator.save_state();
                    await emulator.restore_state(state);
                    snapshot_bytes.push({format: "V6 buffer", bytes: state.byteLength});
                }
                emulator.run();
            }
        }
        if(booted && /\r?\nX64_LINUX_BOOT_OK\r?\n/.test(serial)) break;
        if(performance.now() >= next_report)
        {
            snapshot = inspect();
            console.log("X64_LINUX_PROGRESS " + JSON.stringify(snapshot));
            fs.writeFileSync(transcript, serial);
            next_report = performance.now() + 10000;
        }
    }
    snapshot = inspect();
    assert.ok(booted && /\r?\nX64_LINUX_BOOT_OK\r?\n/.test(serial), "real x64 Linux login shell and command deadline");
    // (to login and through the probes: docs/x86-64.md's boot time, the
    // arm64 plan's E level compares its own with it)
    console.log("X64_LINUX_PROBES_MS " + Math.round(performance.now() - started));
    assert.match(serial, /\r?\nx86_64\r?\n/, "uname confirms actual x86_64 userspace");
    check_probes(serial, true);
    assert.equal(echoed, 32, "the host echoed every probe frame");
    if(glibc) console.log("X64_LINUX_GLIBC " + JSON.stringify(check_glibc(serial, usable, glibc.libraries, glibc_reference)));
    if(high_memory || extended_memory)
    {
        assert.match(serial, new RegExp(`\\n\\s*100000000-${(0x100000000 + high_memory + extended_memory - 1).toString(16)} : System RAM`),
            "kernel owns the relocated and extended RAM above 4 GiB");
    }
    if(memtest_mib)
    {
        const line = serial.match(/X64_MEMTEST mib=(\d+) pages=(\d+) errors=(\d+) extended_pages=(\d+)/);
        assert.ok(line, "memtest result: " + (serial.match(/X64_PROBE_FAIL[^\r\n]*/)?.[0] || "missing"));
        assert.equal(+line[3], 0, "memtest contents");
        if(extended_memory) assert.ok(+line[4] > +line[2] / 4, `memtest pages in extended RAM: ${line[0]}`);
        console.log("X64_LINUX_MEMTEST " + line[0] + " " + (serial.match(/MemTotal:\s*\d+ kB/)?.[0] || ""));
    }
    if(+process.env.X64_LINUX_SNAPSHOT)
    {
        assert.deepEqual(snapshots_taken, snapshot_markers, "snapshots taken during every probe phase");
        console.log("X64_LINUX_SNAPSHOT_PASS " + JSON.stringify(snapshot_bytes));
    }
    if(sleep_cycles)
    {
        const next = (name, limit_ms = 120000) => new Promise((resolve, reject) => {
            const timer = setTimeout(() => reject(new Error(`sleep: no ${name} event; acpi ` +
                JSON.stringify(cpu.get_diagnostics().acpi) + "\n" + serial.slice(-3000))), limit_ms);
            emulator.add_listener(name, function listener(value) {
                clearTimeout(timer);
                emulator.remove_listener(name, listener);
                resolve(value);
            });
        });
        const wait_serial = async (pattern, from, what, limit_ms = 300000) => {
            const limit = performance.now() + limit_ms;
            while(!pattern.test(serial.slice(from)))
            {
                if(execution_error) throw execution_error;
                if(performance.now() > limit) throw new Error("sleep: " + what + "\n" + serial.slice(-2000));
                await delay(10);
            }
            return serial.slice(from);
        };
        const run = async (command, marker) => {
            const from = serial.length;
            emulator.serial0_send(command + "; echo " + marker + "_$((6*7))\n");
            return wait_serial(new RegExp(marker + "_42\\r?\\n"), from, command);
        };
        const value = (text, key) => +(text.match(new RegExp(key + "=(\\d+)")) || [])[1];
        const states = await run("echo STATE=$(cat /sys/power/state)", "STATES");
        // (the serial console echoes the command line too: take the output line)
        const state_line = [...states.matchAll(/STATE=([^$\r\n][^\r\n]*)/g)].at(-1)[1];
        console.log("X64_LINUX_SLEEP_STATES " + state_line);
        assert.match(state_line, /\bmem\b/, "the kernel can suspend to RAM");
        // Alpine's virt kernel has no CONFIG_HIBERNATION; the lts kernel does
        const can_hibernate = /\bdisk\b/.test(state_line);
        assert.ok(can_hibernate || flavor === "virt", "the lts kernel can hibernate");
        await run("dd if=/dev/urandom of=/tmp/s3.bin bs=1024 count=4096 2>/dev/null; md5sum /tmp/s3.bin > /tmp/s3.md5", "PATTERN");
        const online = cores === 1 ? "0" : "0-" + (cores - 1);
        for(let cycle = 1; cycle <= sleep_cycles; cycle++)
        {
            const by_rtc = cycle % 2 === 1;
            const slept = next("acpi-sleep"), woke = next("acpi-wake");
            const from = serial.length;
            // (the kernel log is cleared each cycle: over many cycles its ring buffer wraps)
            emulator.serial0_send("dmesg -c >/dev/null; " + (by_rtc ? "echo 0 > /sys/class/rtc/rtc0/wakealarm; echo +3 > /sys/class/rtc/rtc0/wakealarm; " : "") +
                "echo mem > /sys/power/state; echo RESUMED_$((" + cycle + "*7))\n");
            assert.equal(await slept, "S3");
            if(!by_rtc) { await delay(500); await emulator.power_button(); }
            assert.equal(await woke, by_rtc ? "rtc" : "power-button");
            await wait_serial(new RegExp("RESUMED_" + cycle * 7 + "\\r?\\n"), from, "resume " + cycle);
            const check = await run("md5sum -c /tmp/s3.md5 >/dev/null && echo INTACT=1; echo WAKES=$(dmesg | grep -c 'Waking up from system sleep state S3'); echo ONLINE=$(cat /sys/devices/system/cpu/online)", "CHECK");
            assert.equal(value(check, "INTACT"), 1, "RAM survives S3");
            assert.equal(value(check, "WAKES"), 1, "woke from S3");
            assert.match(check, new RegExp("ONLINE=" + online + "\\r?\\n"), "every CPU is back online");
            console.log(`X64_LINUX_S3 cycle ${cycle}: ${by_rtc ? "RTC alarm" : "power button"}, RAM intact, CPUs ${online}`);
        }
        if(can_hibernate)
        {
            const swap = await run("mkswap /dev/sdb >/dev/null && swapon /dev/sdb && echo platform > /sys/power/disk && echo 1 > /sys/power/pm_debug_messages && echo SWAP_OK=1", "SWAP");
            assert.equal(value(swap, "SWAP_OK"), 1, "swap and platform hibernation");
        }
        else console.log("X64_LINUX_S4 skipped: this kernel has no hibernation (" + state_line + ")");
        for(let cycle = 1; can_hibernate && cycle <= sleep_cycles; cycle++)
        {
            const marker = 5000 + cycle;
            await run(`echo ${marker} > /tmp/s4-marker; dmesg -c >/dev/null`, "MARK");
            const off = next("acpi-power-off");
            const from = serial.length;
            emulator.serial0_send("echo disk > /sys/power/state; echo THAWED=$(cat /tmp/s4-marker)\n");
            assert.equal(await off, "S4");
            await delay(200);
            await emulator.power_button();
            const thawed = await wait_serial(/THAWED=\d+\r?\n/, from, "restore " + cycle, 600000);
            assert.equal(value(thawed, "THAWED"), marker, "the shell continues in the restored kernel");
            // (Linux 6 logs the restore itself only with pm_debug_messages during
            // suspend to RAM; the S4 wake-up of the restored kernel is always logged)
            const check = await run("echo RESTORED=$(dmesg | grep -c 'Waking up from system sleep state S4'); echo ONLINE=$(cat /sys/devices/system/cpu/online); md5sum -c /tmp/s3.md5 >/dev/null && echo INTACT=1", "CHECK");
            assert.equal(value(check, "RESTORED"), 1, "restored from the swap image");
            assert.equal(value(check, "INTACT"), 1, "tmpfs contents came back from disk");
            assert.match(check, new RegExp("ONLINE=" + online + "\\r?\\n"), "every CPU is back online");
            console.log(`X64_LINUX_S4 cycle ${cycle}: hibernated, powered on, restored (marker ${marker}), CPUs ${online}`);
        }
        console.log("X64_LINUX_SLEEP_PASS");
    }
    if(+process.env.X64_LINUX_LIFECYCLE)
    {
        // Guest reboot (reset through the FADT/keyboard controller path the
        // kernel picks), a second boot to a shell, then poweroff into S5.
        const wait_for = async (pattern, from, what) => {
            const limit = performance.now() + Number(process.env.X64_LINUX_TIMEOUT || 300000);
            while(!pattern.test(serial.slice(from)))
            {
                if(execution_error) throw execution_error;
                if(performance.now() > limit) throw new Error("lifecycle: " + what);
                await delay(10);
            }
        };
        let mark = serial.length;
        emulator.serial0_send("reboot\n");
        await wait_for(/Linux version[\s\S]*localhost login:/, mark, "second boot to login");
        mark = serial.length;
        emulator.serial0_send("root\n");
        await wait_for(/localhost:~#/, mark, "second shell");
        mark = serial.length;
        emulator.serial0_send("uname -m; cat /sys/devices/system/cpu/online; echo X64_REBOOT_OK\n");
        await wait_for(/\r?\nX64_REBOOT_OK\r?\n/, mark, "command after reboot");
        assert.match(serial.slice(mark), /\r?\nx86_64\r?\n/, "x86_64 after reboot");
        assert.match(serial.slice(mark), new RegExp(`\\r?\\n${cores === 1 ? "0" : "0-" + (cores - 1)}\\r?\\n`), "every CPU online after reboot");
        const off = new Promise(resolve => emulator.add_listener("acpi-power-off", resolve));
        emulator.serial0_send("poweroff\n");
        const state = await Promise.race([off, delay(120000).then(() => null)]);
        if(state !== "S5")
        {
            const diagnostics = cpu.get_diagnostics();
            fs.writeFileSync(directory + `poweroff-${tag}.json`, JSON.stringify(diagnostics, null, 1));
            throw new Error("no ACPI S5 after poweroff: " + JSON.stringify(diagnostics.cores.map(core => [core.state, core.linear_ip, core.halted, core.interrupts_enabled])));
        }
        await delay(100);
        assert.ok(!emulator.is_running(), "the machine stopped in S5");
        console.log("X64_LINUX_LIFECYCLE_PASS");
    }
    fs.writeFileSync(directory + `result-${tag}.json`, JSON.stringify({...manifest, passed: true, snapshot}, null, 2) + "\n");
    console.log("X64_LINUX_PASS " + JSON.stringify(snapshot));
    if(process.env.X64_STEP_PROFILE)
    {
        const get = cpu.wm.exports.x64_page_profile_get;
        const name = key => (key & 0x10000 ? "rep " : "") + (key & 0x4000 ?
            `VEX.${key & 0x1000 ? 256 : 128}.${["", "66.", "F3.", "F2."][(key >> 10) & 3]}` : "") +
            ["", "0F ", "0F38 ", "0F3A "][(key >> 8) & 3] + (key & 0xFF).toString(16).padStart(2, "0");
        for(const [label, base] of [["X64_STEP_PROFILE", 0], ["X64_RETRY_PROFILE", 0x20000]])
        {
            const rows = [];
            for(let key = 0; key < 0x20000; key++) { const n = get(base + key); if(n) rows.push([n, key]); }
            rows.sort((a, b) => b[0] - a[0]);
            console.log(label + " " + rows.slice(0, 60).map(([n, key]) => `${name(key)}:${n}`).join(" "));
        }
        console.log("X64_REFUSED crossing=" + get(0x40000) + " fault=" + get(0x40001) + " device=" + get(0x40002) + " code=" + get(0x40003));
    }
}
catch(error)
{
    if(cpu) snapshot = inspect();
    fs.writeFileSync(directory + `result-${tag}.json`, JSON.stringify({...manifest, passed: false, error: String(error), snapshot}, null, 2) + "\n");
    console.error("X64_LINUX_FAILURE " + JSON.stringify(snapshot));
    throw error;
}
finally
{
    fs.writeFileSync(transcript, serial);
    await emulator.destroy();
}
                                                                                                                                                                                                                                                                                                source/v64/tests/x64/linux_glibc.mjs                                                                0000644 0000000 0000000 00000023103 00000000000 014460  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // The glibc part of the x64 Linux acceptance (docs/simd-xsave-plan.md 11.3,
// P12), for tests/x64/linux_boot.mjs with X64_LINUX_GLIBC=1: Ubuntu 24.04's
// glibc 2.39 (the package whose libraries gave plan 5.1's hot forms),
// tests/x64/linux_glibc_probe.c linked against it, and libhwprobe.so
// (tests/x64/linux_hwprobe.c) in a baseline build and, under
// glibc-hwcaps/x86-64-v3, a -march=x86-64-v3 one. Alpine itself uses musl:
// the probe runs through glibc's ld.so with --library-path.
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawnSync} from "node:child_process";
import {createHash as create_hash} from "node:crypto";

const PACKAGE = {
    name: "libc6_2.39-0ubuntu8.9_amd64.deb",
    sha256: "ff5557d99b51f761c4b7c92368b9cc45565eda17df9bf9eb4b134d09825008be",
    url: "https://launchpad.net/ubuntu/+archive/primary/+files/libc6_2.39-0ubuntu8.9_amd64.deb",
};
const LIBRARIES = ["ld-linux-x86-64.so.2", "libc.so.6", "libm.so.6"];
// glibc's x86-64 levels (sysdeps/x86/get-isa-level.h) beyond what the x64
// profile always has (CMPXCHG16B, LAHF/SAHF, POPCNT, SSE3)
const V2 = ["SSSE3", "SSE4.1", "SSE4.2"];
const V3 = [...V2, "XSAVE", "AVX", "AVX2", "BMI1", "BMI2", "F16C", "FMA", "LZCNT", "MOVBE"];
// The implementations glibc picks with AVX2, BMI1, BMI2 and LZCNT
// (ifunc-avx2.h) use YMM registers; with FMA and AVX2 libm's use FMA
// (ifunc-fma.h). Without AVX2 no IFUNC picks a YMM or FMA implementation.
// (not wmemset: glibc 2.39 keeps its SSE2 version on this CPU model)
const AVX2_STRINGS = ["memchr", "memcmp", "memcpy", "memmove", "memrchr", "memset", "rawmemchr", "stpcpy", "strcat",
    "strchr", "strchrnul", "strcmp", "strcpy", "strlen", "strncmp", "strnlen", "strrchr", "wcschr", "wcslen", "wmemchr",
    "__memcmpeq"];
const FMA_MATH = ["sin", "cos", "tan", "atan", "sincos", "expf", "logf", "log2f", "exp2f", "powf", "sinf", "cosf",
    "sincosf", "fma", "fmaf", "__exp_finite", "__log_finite", "__pow_finite"];

export const GLIBC_COMMAND = "/tmp/glibc/lib/ld-linux-x86-64.so.2 --help | grep x86-64-v; " +
    "/tmp/glibc/lib/ld-linux-x86-64.so.2 --library-path /tmp/glibc/lib /tmp/glibc/glibc_probe; ";

const hash = bytes => create_hash("sha256").update(bytes).digest("hex");
function run(program, args)
{
    const result = spawnSync(program, args, {encoding: "utf8", maxBuffer: 1 << 28});
    assert.equal(result.status, 0, `${program} ${args.join(" ")}: ${result.stderr || result.error}`);
    return result.stdout;
}

/** The pinned package's ld.so, libc and libm in `directory`glibc-2.39/ */
async function libraries(directory, local)
{
    const out = directory + "glibc-2.39/";
    if(LIBRARIES.every(name => fs.existsSync(out + name))) return out;
    const deb = directory + PACKAGE.name;
    if(!fs.existsSync(deb))
    {
        if(fs.existsSync(local)) fs.copyFileSync(local, deb);
        else
        {
            const response = await fetch(PACKAGE.url);
            assert.ok(response.ok, `glibc package HTTP ${response.status}`);
            fs.writeFileSync(deb, Buffer.from(await response.arrayBuffer()));
        }
    }
    assert.equal(hash(fs.readFileSync(deb)), PACKAGE.sha256, "pinned glibc package SHA-256");
    const unpack = out + "unpack/";
    fs.mkdirSync(unpack, {recursive: true});
    run("bsdtar", ["-xf", deb, "-C", unpack, "data.tar.zst"]);
    run("bsdtar", ["-xf", unpack + "data.tar.zst", "-C", unpack, ...LIBRARIES.map(name => "./usr/lib/x86_64-linux-gnu/" + name)]);
    for(const name of LIBRARIES) fs.copyFileSync(unpack + "usr/lib/x86_64-linux-gnu/" + name, out + name);
    fs.rmSync(unpack, {recursive: true, force: true});
    return out;
}

/** Builds the probe and both libhwprobe.so in `work` (the package is kept in
 * `directory`): returns the directory that holds glibc/ as the guest finds
 * it in /tmp, and the libraries there */
export async function prepare_glibc(root, directory, work, lld)
{
    const glibc = await libraries(directory, root + "build/simd-xsave/p0-baseline/glibc/" + PACKAGE.name);
    const lib = work + "stage/glibc/lib/";
    fs.rmSync(work, {recursive: true, force: true});
    fs.mkdirSync(lib + "glibc-hwcaps/x86-64-v3", {recursive: true});
    const clang = args => run(process.env.CLANG || "clang", ["--target=x86_64-unknown-linux-gnu", "-O2", "-ffreestanding", "-fno-stack-protector", ...args]);
    const v3 = lib + "glibc-hwcaps/x86-64-v3/libhwprobe.so";
    clang(["-fPIC", "-c", root + "tests/x64/linux_hwprobe.c", "-o", work + "hwprobe.o"]);
    clang(["-fPIC", "-march=x86-64-v3", "-ffp-contract=fast", "-DHWPROBE_V3", "-c", root + "tests/x64/linux_hwprobe.c", "-o", work + "hwprobe-v3.o"]);
    run(lld, ["-flavor", "gnu", "-m", "elf_x86_64", "-shared", "-soname", "libhwprobe.so", "-o", lib + "libhwprobe.so", work + "hwprobe.o"]);
    run(lld, ["-flavor", "gnu", "-m", "elf_x86_64", "-shared", "-soname", "libhwprobe.so", "-o", v3, work + "hwprobe-v3.o"]);
    // (plan 11.3: a build for a level holds that level's instructions)
    const code = run("objdump", ["-d", v3]), baseline = run("objdump", ["-d", lib + "libhwprobe.so"]);
    assert.match(code, /vfmadd\d+sd/, "the x86-64-v3 libhwprobe.so has FMA");
    assert.match(code, /%ymm/, "the x86-64-v3 libhwprobe.so has AVX2");
    assert.doesNotMatch(baseline, /%ymm|vfmadd/, "the baseline libhwprobe.so has neither");
    for(const name of LIBRARIES) fs.copyFileSync(glibc + name, lib + name);
    clang(["-fPIE", "-fno-builtin", "-c", root + "tests/x64/linux_glibc_probe.c", "-o", work + "probe.o"]);
    run(lld, ["-flavor", "gnu", "-m", "elf_x86_64", "-pie", "--dynamic-linker", "/lib64/ld-linux-x86-64.so.2",
        "-o", work + "stage/glibc/glibc_probe", work + "probe.o", lib + "libc.so.6", lib + "libm.so.6", lib + "libhwprobe.so"]);
    return {stage: work + "stage/", libraries: lib};
}

/** What each GLIBC_IFUNC line chose: "avx2" (YMM registers), "fma" or
 * "other", from the disassembly of the function (its .eh_frame range) */
function ifunc_kinds(text, libraries)
{
    const ranges = {}, kinds = {};
    const frames = library => ranges[library] ??= [...run("objdump", ["--dwarf=frames", libraries + library])
        .matchAll(/FDE cie=\w+ pc=([0-9a-f]+)\.\.\.?([0-9a-f]+)/g)].map(m => [parseInt(m[1], 16), parseInt(m[2], 16)]);
    for(const [, name, library, offset] of text.matchAll(/GLIBC_IFUNC (\S+) (\S+) ([0-9a-f]+)\r?\n/g))
    {
        const at = parseInt(offset, 16);
        const range = frames(library).find(([start, end]) => start <= at && at < end);
        assert.ok(range, `${name}: no .eh_frame range at ${offset} in ${library}`);
        const code = run("objdump", ["-d", "--start-address=0x" + range[0].toString(16), "--stop-address=0x" + range[1].toString(16), libraries + library]);
        kinds[name] = /vfn?m(add|sub)/.test(code) ? "fma" : /%ymm/.test(code) ? "avx2" : "other";
    }
    return kinds;
}

/** Checks the glibc probe's report in `text` for `features`; `reference`:
 * a transcript of the same probe under QEMU with the same features, whose
 * IFUNC choices and results must be the same */
export function check_glibc(text, features, libraries, reference)
{
    const has = list => list.every(name => features.includes(name));
    const levels = {};
    for(const [, level, supported] of text.matchAll(/^\s*x86-64-v(\d)( \(supported, searched\))?\r?$/gm)) levels[level] = !!supported;
    assert.deepEqual(levels, {2: has(V2), 3: has(V3), 4: false}, "ld.so --help: the glibc-hwcaps levels the CPU supports");
    assert.match(text, /\nGLIBC_PROBE_OK\r?\n/, "the glibc probe ran to its end");
    const hwcaps = text.match(/GLIBC_HWCAPS (\S+) [0-9a-f]+/);
    assert.equal(hwcaps?.[1], has(V3) ? "x86-64-v3" : "baseline", "ld.so loaded the libhwprobe.so of the CPU's level");
    const kinds = ifunc_kinds(text, libraries);
    assert.equal(Object.keys(kinds).length, 64, "every IFUNC reported");
    for(const [name, kind] of Object.entries(kinds))
    {
        if(!has(["AVX2"])) assert.equal(kind, "other", `glibc's IFUNC choice for ${name} without AVX2`);
        else if(FMA_MATH.includes(name)) assert.equal(kind, has(["FMA"]) ? "fma" : "other", `glibc's IFUNC choice for ${name}`);
        else if(AVX2_STRINGS.includes(name) && has(["BMI1", "BMI2", "LZCNT"])) assert.equal(kind, "avx2", `glibc's IFUNC choice for ${name}`);
    }
    const results = s => s.match(/^GLIBC_(STRING|MATH|HWCAPS) [^\r\n]+/gm);
    if(reference)
    {
        assert.deepEqual(kinds, ifunc_kinds(reference, libraries), "the same IFUNC choices as QEMU");
        assert.deepEqual(results(text), results(reference), "the same string, libm and libhwprobe.so results as QEMU");
    }
    return {kinds, times: Object.fromEntries([...text.matchAll(/GLIBC_TIME (\S+) (\d+)/g)].map(([, name, ns]) => [name, +ns]))};
}

/** QEMU's -cpu for the x64 profile with `features` (v86's CPUID vendor and
 * model, so that glibc tunes its choices the same way); QEMU 10.2's TCG has
 * no XSAVEC or XSAVES, and with this model and XSAVE but not XSAVEOPT its
 * guest kernel hangs setting up XSAVE: QEMU gets XSAVEOPT with XSAVE (the
 * kernel's context switch format does not change what the probes see) */
export function qemu_cpu(features)
{
    if(features.includes("XSAVE") && !features.includes("XSAVEOPT")) features = [...features, "XSAVEOPT"];
    const flags = {"SSSE3": "ssse3", "SSE4.1": "sse4.1", "SSE4.2": "sse4.2", "XSAVE": "xsave", "AVX": "avx", "AVX2": "avx2",
        "FMA": "fma", "F16C": "f16c", "BMI1": "bmi1", "BMI2": "bmi2", "LZCNT": "abm", "MOVBE": "movbe", "XSAVEOPT": "xsaveopt",
        "XGETBV1": "xgetbv1"};
    return ["qemu64,phys-bits=36,-pdpe1gb,vendor=GenuineIntel,family=6,model=7,stepping=3,+popcnt,+cx16,+lahf-lm",
        ...features.filter(name => flags[name]).map(name => "+" + flags[name])].join(",");
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/tests/x64/linux_glibc_probe.c                                                            0000644 0000000 0000000 00000043357 00000000000 015315  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* The real-guest acceptance probe of docs/simd-xsave-plan.md 11.3 (P12):
 * linked against Ubuntu 24.04's glibc 2.39 (libc.so.6, libm.so.6 and
 * libhwprobe.so, see below) and run through glibc's ld.so in Alpine x86_64
 * (musl) by tests/x64/linux_boot.mjs (X64_LINUX_GLIBC=1). It prints:
 *   GLIBC_IFUNC <name> <library> <offset>: the implementation glibc's IFUNC
 *     resolver chose for <name> (dlsym or dlvsym, then dladdr: the offset in
 *     its library); the harness disassembles that function (its range from
 *     .eh_frame) to tell the AVX2, FMA, SSE4 and SSE2 variants
 *   GLIBC_STRING <name> <hash>: string functions over lengths 0-300 at every
 *     alignment within 64 bytes, strings that end right before an unmapped
 *     page, overlapping copies
 *   GLIBC_MATH <name> <hash>: libm functions on 4096 fixed inputs and the
 *     special values
 *   GLIBC_HWCAPS <level> <hash>: libhwprobe.so's level, from the copy that
 *     ld.so loaded (glibc-hwcaps/x86-64-v3 holds a -march=x86-64-v3 build),
 *     and its results (FMA dot products, an AVX2 integer loop in that build)
 *   GLIBC_TIME <name> <ns>: the time of a fixed amount of work (not compared)
 * The harness compares everything but the times with QEMU's run under the
 * same CPU features. Built freestanding: no glibc headers on the host. */
typedef unsigned long size_t;
typedef unsigned long u64;
typedef unsigned int u32;
typedef struct { const char *dli_fname; void *dli_fbase; const char *dli_sname; void *dli_saddr; } Dl_info;
struct timespec { long tv_sec; long tv_nsec; };
#define RTLD_DEFAULT ((void *)0)

extern int printf(const char *, ...);
extern void *dlsym(void *, const char *);
extern void *dlvsym(void *, const char *, const char *);
extern int dladdr(const void *, Dl_info *);
extern void *mmap(void *, size_t, int, int, int, long);
extern int clock_gettime(int, struct timespec *);
extern size_t strlen(const char *);
extern size_t strnlen(const char *, size_t);
extern char *strchr(const char *, int);
extern char *strchrnul(const char *, int);
extern char *strrchr(const char *, int);
extern void *memchr(const void *, int, size_t);
extern void *memrchr(const void *, int, size_t);
extern void *rawmemchr(const void *, int);
extern int strcmp(const char *, const char *);
extern int strncmp(const char *, const char *, size_t);
extern int memcmp(const void *, const void *, size_t);
extern int strcasecmp(const char *, const char *);
extern char *strcpy(char *, const char *);
extern char *stpcpy(char *, const char *);
extern char *strncpy(char *, const char *, size_t);
extern char *strcat(char *, const char *);
extern void *memcpy(void *, const void *, size_t);
extern void *memmove(void *, const void *, size_t);
extern void *mempcpy(void *, const void *, size_t);
extern void *memset(void *, int, size_t);
extern size_t strspn(const char *, const char *);
extern size_t strcspn(const char *, const char *);
extern char *strpbrk(const char *, const char *);
extern char *strstr(const char *, const char *);
extern size_t wcslen(const int *);
extern int *wmemset(int *, int, size_t);
extern int *wcschr(const int *, int);
extern int wcscmp(const int *, const int *);
extern double exp(double), exp2(double), log(double), log2(double), log10(double), pow(double, double);
extern double sin(double), cos(double), tan(double), atan(double), atan2(double, double), asin(double), acos(double);
extern double sinh(double), cosh(double), tanh(double), expm1(double), log1p(double), fma(double, double, double);
extern float expf(float), exp2f(float), logf(float), log2f(float), powf(float, float), sinf(float), cosf(float), fmaf(float, float, float);
extern void sincos(double, double *, double *);
extern void sincosf(float, float *, float *);
/* libhwprobe.so (tests/x64/linux_hwprobe.c) */
extern const char *hwprobe_level(void);
extern double hwprobe_dot(const double *, const double *, int);
extern unsigned hwprobe_mix(const unsigned *, int);

/* FNV-1a, 64 bits */
static u64 mix(u64 h, u64 v)
{
    for(int i = 0; i < 8; i++)
    {
        h ^= (v >> (8 * i)) & 0xFF;
        h *= 0x100000001B3ul;
    }
    return h;
}
static u64 bits(double x) { u64 b; __builtin_memcpy(&b, &x, 8); return b; }
static u32 bits32(float x) { u32 b; __builtin_memcpy(&b, &x, 4); return b; }
static long now(void)
{
    struct timespec t;
    clock_gettime(1, &t);
    return t.tv_sec * 1000000000l + t.tv_nsec;
}

static const char *const LIBC_IFUNCS[] = {
    "memchr", "memcmp", "memcpy", "memmove", "mempcpy", "memrchr", "memset", "rawmemchr", "stpcpy", "stpncpy",
    "strcasecmp", "strcat", "strchr", "strchrnul", "strcmp", "strcpy", "strcspn", "strlen", "strncasecmp", "strncat",
    "strncmp", "strncpy", "strnlen", "strpbrk", "strrchr", "strspn", "strstr", "wcschr", "wcscmp", "wcslen", "wcsnlen",
    "wmemchr", "wmemcmp", "wmemset", "__memcmpeq",
};
/* (libm's exp, log, pow, atan2, asin and acos dispatch internally; their
 * deprecated __*_finite aliases, GLIBC_2.15, are IFUNCs over the same
 * implementations) */
static const char *const LIBM_IFUNCS[] = {
    "sin", "cos", "tan", "atan", "sincos", "expm1", "log2", "exp2f", "expf", "log2f", "logf", "powf", "sinf", "cosf",
    "sincosf", "fma", "fmaf", "floor", "ceil", "rint", "nearbyint", "trunc", "roundeven",
};
static const char *const LIBM_FINITE[] = {
    "__exp_finite", "__log_finite", "__pow_finite", "__atan2_finite", "__asin_finite", "__acos_finite",
};

static void ifuncs(const char *const *names, int count, const char *version)
{
    for(int i = 0; i < count; i++)
    {
        void *f = version ? dlvsym(RTLD_DEFAULT, names[i], version) : dlsym(RTLD_DEFAULT, names[i]);
        Dl_info info;
        if(!f || !dladdr(f, &info)) { printf("GLIBC_IFUNC %s missing\n", names[i]); continue; }
        const char *library = info.dli_fname, *slash = library;
        for(const char *c = library; *c; c++) if(*c == '/') slash = c + 1;
        printf("GLIBC_IFUNC %s %s %lx\n", names[i], slash, (u64)((char *)f - (char *)info.dli_fbase));
    }
}

/* Two pages, the second unmapped: a string that ends at the end of the first
 * page must not fault however wide the implementation reads */
static char *edge_page(void)
{
    char *p = mmap(0, 3 * 4096, 0, 0x22, -1, 0);
    char *q = mmap(p, 2 * 4096, 3, 0x32, -1, 0); /* MAP_FIXED: the first two pages readable */
    (void)q;
    return p + 4096;
}

static void strings(void)
{
    char *edge = edge_page(), *end = edge + 4096;
    static char a[1024] __attribute__((aligned(64))), b[1024] __attribute__((aligned(64)));
    static char copy[2048] __attribute__((aligned(64)));
    u64 h[16];
    for(int i = 0; i < 16; i++) h[i] = 0xCBF29CE484222325ul;
    enum { LEN, NLEN, CHR, RCHR, MCHR, CMP, NCMP, MCMP, CASE, CPY, MOVE, SET, SPN, STR, WIDE, CAT };
    for(int length = 0; length <= 300; length += length < 80 ? 1 : 7)
    {
        for(int align = 0; align < 64; align++)
        {
            /* a string at the end of the readable page (only for the
             * alignment that ends it there), else inside a */
            for(int at_edge = 0; at_edge < 2; at_edge++)
            {
                char *s = at_edge ? end - length - 1 : a + align;
                if(at_edge && align) break;
                if(!at_edge && align + length + 1 > (int)sizeof a) continue;
                for(int i = 0; i < length; i++) s[i] = 'a' + (i * 7 + align) % 23;
                s[length] = 0;
                h[LEN] = mix(h[LEN], strlen(s));
                h[NLEN] = mix(h[NLEN], strnlen(s, length / 2 + 3));
                for(int c = 'a'; c < 'a' + 26; c += 5)
                {
                    char *r = strchr(s, c);
                    h[CHR] = mix(h[CHR], r ? (u64)(r - s) : ~0ul);
                    r = strchrnul(s, c);
                    h[CHR] = mix(h[CHR], (u64)(r - s));
                    r = strrchr(s, c);
                    h[RCHR] = mix(h[RCHR], r ? (u64)(r - s) : ~0ul);
                    void *m = memchr(s, c, length);
                    h[MCHR] = mix(h[MCHR], m ? (u64)((char *)m - s) : ~0ul);
                    m = memrchr(s, c, length);
                    h[MCHR] = mix(h[MCHR], m ? (u64)((char *)m - s) : ~0ul);
                }
                h[MCHR] = mix(h[MCHR], (u64)((char *)rawmemchr(s, 0) - s));
                /* comparisons against a copy that differs at one position (or nowhere) */
                char *t = b + (align * 5) % 64;
                for(int diff = -1; diff < length; diff += length / 5 + 1)
                {
                    for(int i = 0; i <= length; i++) t[i] = s[i];
                    if(diff >= 0) t[diff] = (char)(t[diff] + (diff & 1 ? 1 : -1) * (1 + (diff & 64)));
                    int r = strcmp(s, t);
                    h[CMP] = mix(h[CMP], r < 0 ? 1 : r > 0 ? 2 : 3);
                    r = strncmp(s, t, length - length / 3);
                    h[NCMP] = mix(h[NCMP], r < 0 ? 1 : r > 0 ? 2 : 3);
                    r = memcmp(s, t, length);
                    h[MCMP] = mix(h[MCMP], r < 0 ? 1 : r > 0 ? 2 : 3);
                    if(diff >= 0) t[diff] ^= 0x20;
                    r = strcasecmp(s, t);
                    h[CASE] = mix(h[CASE], r < 0 ? 1 : r > 0 ? 2 : 3);
                }
                /* copies to every alignment */
                char *d = copy + (align * 3) % 64;
                __builtin_memset(copy, 0x5A, sizeof copy);
                h[CPY] = mix(h[CPY], (u64)(stpcpy(d, s) - d));
                strcpy(d + length + 9, s);
                strncpy(d + 2 * length + 20, s, length / 2 + 5);
                strcat(d, "xyz");
                for(int i = 0; i < (int)sizeof copy; i += 8) h[CPY] = mix(h[CPY], *(u64 *)(copy + i));
                /* overlapping moves both ways, memcpy and mempcpy, memset */
                __builtin_memset(copy, 0, sizeof copy);
                for(int i = 0; i < 700; i++) copy[i] = (char)(i * 13 + align);
                memmove(copy + align, copy + 64 + (length & 31), length * 2);
                memmove(copy + 300 + (length & 15), copy + 290 + align, length);
                memcpy(copy + 1200 + align, copy + (length & 63), length);
                h[MOVE] = mix(h[MOVE], (u64)((char *)mempcpy(copy + 1600, s, length) - copy));
                for(int i = 0; i < 2048; i += 8) h[MOVE] = mix(h[MOVE], *(u64 *)(copy + i));
                memset(copy + align, length, length * 3);
                for(int i = 0; i < 2048; i += 8) h[SET] = mix(h[SET], *(u64 *)(copy + i));
                h[SPN] = mix(h[SPN], strspn(s, "abcdefghij"));
                h[SPN] = mix(h[SPN], strcspn(s, "uvw"));
                char *p = strpbrk(s, "qrs");
                h[SPN] = mix(h[SPN], p ? (u64)(p - s) : ~0ul);
                if(length > 6)
                {
                    char needle[8];
                    for(int i = 0; i < 5; i++) needle[i] = s[length - 6 + i];
                    needle[5] = 0;
                    p = strstr(s, needle);
                    h[STR] = mix(h[STR], p ? (u64)(p - s) : ~0ul);
                    needle[2] = 'z';
                    p = strstr(s, needle);
                    h[STR] = mix(h[STR], p ? (u64)(p - s) : ~0ul);
                }
            }
        }
        /* wide strings */
        static int w[400] __attribute__((aligned(64))), w2[400] __attribute__((aligned(64)));
        if(length < 380)
        {
            wmemset(w, 'k', length);
            w[length] = 0;
            for(int i = 0; i <= length; i++) w2[i] = w[i];
            if(length) w2[length / 2] = 'm';
            h[WIDE] = mix(h[WIDE], wcslen(w));
            int *r = wcschr(w, 'k');
            h[WIDE] = mix(h[WIDE], r ? (u64)(r - w) : ~0ul);
            int c = wcscmp(w, w2);
            h[WIDE] = mix(h[WIDE], c < 0 ? 1 : c > 0 ? 2 : 3);
        }
    }
    static const char *const NAMES[] = { "strlen", "strnlen", "strchr", "strrchr", "memchr", "strcmp", "strncmp",
        "memcmp", "strcasecmp", "strcpy", "memmove", "memset", "strspn", "strstr", "wide" };
    for(int i = 0; i < 15; i++) printf("GLIBC_STRING %s %016lx\n", NAMES[i], h[i]);
}

/* 4096 inputs: a sweep of each function's interesting range, the special values */
static double input(int i, double low, double high)
{
    static const u64 SPECIAL[] = { 0, 0x8000000000000000ul, 0x7FF0000000000000ul, 0xFFF0000000000000ul,
        0x7FF8000000000000ul, 1, 0x000FFFFFFFFFFFFFul, 0x0010000000000000ul, 0x3FF0000000000000ul,
        0xBFF0000000000000ul, 0x7FEFFFFFFFFFFFFFul, 0x3FE0000000000000ul, 0x400921FB54442D18ul };
    if(i < 13) { double x; __builtin_memcpy(&x, &SPECIAL[i], 8); return x; }
    /* (a sweep with irregular steps: every last bit pattern) */
    return low + (high - low) * ((i - 13) * 0.000244140625 + (i * 2654435761u % 1000) * 1e-9);
}

static void math(void)
{
    enum { N = 4096 };
    struct { const char *name; double (*f)(double); double low, high; } unary[] = {
        { "exp", exp, -745, 710 }, { "exp2", exp2, -1075, 1024 }, { "log", log, 0, 1e6 }, { "log2", log2, 0, 4 },
        { "log10", log10, 0, 1e3 }, { "sin", sin, -100, 100 }, { "cos", cos, -100, 100 }, { "tan", tan, -10, 10 },
        { "atan", atan, -50, 50 }, { "asin", asin, -1, 1 }, { "acos", acos, -1, 1 }, { "sinh", sinh, -20, 20 },
        { "cosh", cosh, -20, 20 }, { "tanh", tanh, -10, 10 }, { "expm1", expm1, -40, 40 }, { "log1p", log1p, -1, 100 },
    };
    for(int k = 0; k < (int)(sizeof unary / sizeof unary[0]); k++)
    {
        u64 h = 0xCBF29CE484222325ul;
        for(int i = 0; i < N; i++) h = mix(h, bits(unary[k].f(input(i, unary[k].low, unary[k].high))));
        printf("GLIBC_MATH %s %016lx\n", unary[k].name, h);
    }
    u64 h = 0xCBF29CE484222325ul, hs = h, hf = h, hfs = h, hfma = h, hfmaf = h, hatan2 = h;
    for(int i = 0; i < N; i++)
    {
        double x = input(i, 0, 30), y = input(N - 1 - i, -12, 12);
        h = mix(h, bits(pow(x, y)));
        double s, c;
        sincos(input(i, -1e4, 1e4), &s, &c);
        hs = mix(mix(hs, bits(s)), bits(c));
        hatan2 = mix(hatan2, bits(atan2(y, input(i, -5, 5))));
        float fx = (float)input(i, -90, 90), fy = (float)input(N - 1 - i, -3, 3);
        hf = mix(hf, bits32(expf(fx)) | (u64)bits32(exp2f(fx / 2)) << 32);
        hf = mix(hf, bits32(logf(fx + 91)) | (u64)bits32(log2f(fx + 91)) << 32);
        hf = mix(hf, bits32(powf(fx + 91, fy)) | (u64)bits32(sinf(fx)) << 32);
        float sf, cf;
        sincosf(fx * 100, &sf, &cf);
        hfs = mix(hfs, bits32(sf) | (u64)bits32(cf) << 32);
        hfs = mix(hfs, bits32(cosf(fx)));
        hfma = mix(hfma, bits(fma(x, y, input(i, -1e3, 1e3))));
        hfmaf = mix(hfmaf, bits32(fmaf(fx, fy, (float)input(i, -1, 1))));
    }
    printf("GLIBC_MATH pow %016lx\nGLIBC_MATH sincos %016lx\nGLIBC_MATH atan2 %016lx\nGLIBC_MATH float %016lx\n"
        "GLIBC_MATH sincosf %016lx\nGLIBC_MATH fma %016lx\nGLIBC_MATH fmaf %016lx\n", h, hs, hatan2, hf, hfs, hfma, hfmaf);
}

static void hwcaps(void)
{
    static double a[1000], b[1000];
    static unsigned v[1000];
    /* (ordinary values: no specials) */
    for(int i = 0; i < 1000; i++) { a[i] = input(i + 100, -3, 3); b[i] = input(1999 - i, -7, 7); v[i] = (unsigned)i * 2246822519u; }
    u64 h = 0xCBF29CE484222325ul;
    for(int n = 0; n <= 1000; n += 37)
    {
        h = mix(h, bits(hwprobe_dot(a + n % 5, b, 1000 - n - n % 5)));
        h = mix(h, hwprobe_mix(v + n % 7, 1000 - n - n % 7));
    }
    printf("GLIBC_HWCAPS %s %016lx\n", hwprobe_level(), h);
}

/* The times (best of ten) of libm's functions and of string functions on
 * fixed work: the performance budget of plan 12.2 compares them between CPU
 * profiles (the FMA and AVX2 versions against the SSE2 ones). The copies and
 * the memset are misaligned and cross pages; from 2 KiB (SSE2) or 4 KiB
 * (AVX2) glibc's ERMS versions use REP MOVSB and REP STOSB */
#define PAGE_ALIGNED __attribute__((aligned(4096)))
static void timing(void)
{
    static const char *const NAMES[] = { "exp", "log", "sin", "pow", "strlen", "memchr", "memcpy", "memcpy16k", "memset" };
    static char s[8192] PAGE_ALIGNED, d[8192] PAGE_ALIGNED, big_s[16384 + 4096] PAGE_ALIGNED, big_d[16384 + 4096] PAGE_ALIGNED;
    for(int i = 0; i < 4095; i++) s[i] = 'a' + i % 26;
    for(int f = 0; f < 9; f++)
    {
        long best = -1;
        for(int round = 0; round < 10; round++)
        {
            volatile double sink = 0;
            size_t n = 0;
            long t = now();
            for(int i = 0; i < 20000; i++)
            {
                double x = i * 1e-3;
                switch(f)
                {
                case 0: sink += exp(x); break;
                case 1: sink += log(x + 1.5); break;
                case 2: sink += sin(x * 37); break;
                case 3: sink += pow(1.0001, x * 100); break;
                case 4: if(i < 2000) n += strlen(s + (i & 63)); break;
                case 5: if(i < 2000) n += (size_t)((char *)memchr(s, 'z' - (i & 3), 4000) - s); break;
                case 6: if(i < 2000) memcpy(d + 2048 + (i & 31), s + 2048 + (i & 63), 4000 - 64); break;
                case 7: if(i < 500) memcpy(big_d + 2048 + (i & 31), big_s + 2048 + (i & 63), 16384 - 64); break;
                default: if(i < 2000) memset(d + 2048 + (i & 31), i, 4000 - 64); break;
                }
            }
            long elapsed = now() - t;
            if(best < 0 || elapsed < best) best = elapsed;
            (void)n;
        }
        printf("GLIBC_TIME %s %ld\n", NAMES[f], best);
    }
}

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    ifuncs(LIBC_IFUNCS, sizeof LIBC_IFUNCS / sizeof LIBC_IFUNCS[0], 0);
    ifuncs(LIBM_IFUNCS, sizeof LIBM_IFUNCS / sizeof LIBM_IFUNCS[0], 0);
    ifuncs(LIBM_FINITE, sizeof LIBM_FINITE / sizeof LIBM_FINITE[0], "GLIBC_2.15");
    strings();
    math();
    hwcaps();
    timing();
    printf("GLIBC_PROBE_OK\n");
    return 0;
}

/* crt1's job: glibc's start (init arrays, stdio, exit through atexit) */
__asm__(".text\n.globl _start\n_start:\nxor %ebp,%ebp\nmov %rdx,%r9\npop %rsi\nmov %rsp,%rdx\nand $-16,%rsp\n"
    "push %rax\npush %rsp\nxor %r8d,%r8d\nxor %ecx,%ecx\nlea main(%rip),%rdi\ncall *__libc_start_main@GOTPCREL(%rip)\nhlt\n");
                                                                                                                                                                                                                                                                                 source/v64/tests/x64/linux_gpu.mjs                                                                  0000644 0000000 0000000 00000154302 00000000000 014201  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// x86_64 Linux (Alpine 3.24, the official virt ISO) on a display adapter:
// installs Mesa and the GPU test programs from build/x64-linux/gpu-repo.tar
// (tools/alpine_repo.mjs), loads the adapter's DRM driver and runs the
// steps of a scenario on the serial console, saving screenshots.
//
//     GPU_ADAPTER=bochs_vga node tests/x64/linux_gpu.mjs
//
// GPU_ARCH=aarch64 (tests/a64/linux_gpu.mjs; docs/arm64-virt-android16-plan.md
// P7.2): the same scenarios on the arm64 virt machine with virtio_gpu (no
// VGA), from build/a64-linux/ (gpu-repo.tar from `tools/alpine_repo.mjs
// --arch aarch64`); the ISO, the repository and the test programs on
// virtio-blk disks, found by their serials; the GPU on the PCIe host
// (GPU_TRANSPORT=mmio: on virtio-mmio, without host visible memory); the
// page tier (GPU_NO_JIT=1: the interpreter)
//
// GPU_ADAPTER: bochs_vga (default), vmware_svga, virtio_gpu
// GPU_SCENARIO: the steps below: drm (default), gl, sm41, sm5, gltest, virgl, venus, resize, kms, input (the virt machine);
// custom: the steps in the JSON file GPU_STEPS
// GPU_LEVEL: pins the adapter's level (graphics_adapter_test), e.g. 2d or 2d-full;
// vgpu9 records the 3D batches into <out>/trace.bin (tests/x64/gpu_trace.mjs),
// or with GPU_RENDERER=chrome draws them on the GPU of a headless Chrome
// GPU_OUT: the output directory (default build/x64-linux/gpu-<adapter>[-<level>]/)
// SHOW_LOGS=1: echo the serial console; LINUX_GPU_TIMEOUT: ms (default 900000);
// GPU_SCREENSHOT_AFTER: ms from a step's command to its screenshot, for every step
// LINUX_GPU_MEMORY: MiB (default 1024; 1536 for the virgl and vkcube scenarios and on arm64)

import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { create_trace_renderer } from "./gpu_trace.mjs";
import { create_remote_renderer } from "./gpu_remote_renderer.mjs";
import { IMAGES, directory_of } from "../lib/alpine_image.mjs";
import { PictureSink, save_png } from "../lib/picture_sink.mjs";

const root = fileURLToPath(new URL("../../", import.meta.url));
const arch = process.env.GPU_ARCH || "x86_64";
assert.ok(arch === "x86_64" || arch === "aarch64", "GPU_ARCH is x86_64 or aarch64");
const arm = arch === "aarch64";
// (the pinned ISO and its unpacked files: tests/lib/alpine_image.mjs)
const directory = directory_of(arch);
const adapter = process.env.GPU_ADAPTER || (arm ? "virtio_gpu" : "bochs_vga");
assert.ok(!arm || adapter === "virtio_gpu", "the virt machine has virtio_gpu only");
const scenario = process.env.GPU_SCENARIO || "drm";
const out = process.env.GPU_OUT || path.join(directory, "gpu-" + adapter + (process.env.GPU_LEVEL ? "-" + process.env.GPU_LEVEL : ""));
fs.mkdirSync(out, { recursive: true });

const iso = directory + IMAGES[arch + "-virt"].name;
const repo = directory + "gpu-repo.tar";
for(const file of [iso, directory + "boot/vmlinuz-virt", directory + "boot/initramfs-virt"])
{
    assert.ok(fs.existsSync(file), file + " is missing: run tests/x64/linux_boot.mjs once (X64_LINUX_PREPARE_ONLY=1)");
}
assert.ok(fs.existsSync(repo), repo + " is missing: run tools/alpine_repo.mjs");

const DRIVER = { bochs_vga: "bochs", vmware_svga: "vmwgfx", virtio_gpu: "virtio_gpu" }[adapter];
// the levels with 3D (vmware_svga's vgpu9 and up)
const LEVEL_3D = ["vgpu9", "gb9", "dx10", "dx10.1", "dx11", "dx11-full", "virgl", "virgl43", "virgl43-blob", "virgl43-hostmem",
    "venus"].includes(process.env.GPU_LEVEL);
assert.ok(DRIVER, "GPU_ADAPTER is bochs_vga, vmware_svga or virtio_gpu");

const APK = "apk add --no-network --repository /mnt/repo/main --repository /mnt/repo/community";
// Alpine 3.23's Mesa (25.2), which has the virgl driver 3.24's (26.1)
// lacks: from a pinned (tagged) repository, so that nothing else comes from it
const APK_VIRGL = "printf '@v323 /mnt/repo/v3.23/main\\n@v323 /mnt/repo/v3.23/community\\n' >> /etc/apk/repositories; " + APK +
    " mesa@v323 mesa-dri-gallium@v323 mesa-gbm@v323 mesa-egl@v323 mesa-gl@v323 mesa-gles@v323 llvm21-libs@v323";
const SCENARIOS = {
    // KMS through the adapter's DRM driver: modes, a test pattern, kmscube
    drm: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " kmscube libdrm-tests mesa-dri-gallium mesa-utils >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; tail -15 /tmp/apk.log", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        [`dmesg | grep -i -E '${DRIVER}|drm' | tail -40; echo STEP_DMESG_DONE`, /STEP_DMESG_DONE/],
        ["modetest -c 2>&1 | head -30; echo STEP_MODES_DONE", /STEP_MODES_DONE/],
        ["SCREENSHOT console", null],
        // (a screenshot 20 s into the command, while it draws)
        // (with 3D the 400 frames take seconds, not a minute)
        ["kmscube -c 400 2>&1 | grep -E 'Rendered|renderer'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube", after: LEVEL_3D ? 2500 : 20000 }],
    ],
    // OpenGL beyond kmscube: the version Mesa reports on GBM, a textured
    // kmscube, and weston on DRM with its EGL and shm clients
    gl: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " kmscube mesa-dri-gallium mesa-utils mesa-demos weston weston-backend-drm weston-shell-desktop " +
            "weston-clients seatd >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; grep -i error /tmp/apk.log | head -5; " +
            "command -v eglinfo kmscube weston weston-simple-egl seatd >/dev/null && echo STEP_APK_PROGRAMS", /STEP_APK_PROGRAMS/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["eglinfo -B -p gbm 2>&1 | grep -E 'OpenGL|renderer|version' | head -12; echo STEP_EGLINFO_DONE",
            LEVEL_3D ? /OpenGL core profile version: (3\.[3-9]|4\.)/ : /STEP_EGLINFO_DONE/],
        ["kmscube -M rgba -c 200 2>&1 | grep -E 'Rendered|renderer'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-rgba", after: LEVEL_3D ? 2500 : 20000 }],
        ["seatd -g video >/tmp/seatd.log 2>&1 & sleep 1; export XDG_RUNTIME_DIR=/tmp/xdg; mkdir -p -m 700 $XDG_RUNTIME_DIR; " +
            "(weston --backend=drm --shell=desktop --idle-time=0 --continue-without-input >/tmp/weston.log 2>&1 &); sleep 15; export WAYLAND_DISPLAY=$(ls $XDG_RUNTIME_DIR | grep -m1 '^wayland-[0-9]*$'); echo $WAYLAND_DISPLAY; " +
            "[ -n \"$WAYLAND_DISPLAY\" ] || { tail -25 /tmp/weston.log /tmp/seatd.log; ps; dmesg | tail -15; }; echo STEP_WESTON_UP",
            /wayland-\d[\s\S]*STEP_WESTON_UP/],
        ["timeout 20 weston-simple-egl -f 2>&1 | tail -3; echo STEP_EGL_DONE", /STEP_EGL_DONE/,
            { screenshot: "weston-simple-egl", after: 12000 }],
        ["timeout 10 weston-simple-shm 2>&1 | tail -3; echo STEP_SHM_DONE", /STEP_SHM_DONE/,
            { screenshot: "weston-simple-shm", after: 6000 }],
        ["grep -i -E 'error|renderer|GL version|EGL' /tmp/weston.log | head -20; echo STEP_WESTON_LOG", /STEP_WESTON_LOG/],
        // the page's size changes (virtio_gpu tells the guest; the others ignore it)
        ["HOST set_display_size 1280 800", null],
        ["sleep 10; tail -6 /tmp/weston.log; echo STEP_WESTON_RESIZE", /STEP_WESTON_RESIZE/, { screenshot: "weston-host-resize", after: 9000 }],
    ],
    // shader model 4.1 (vmware_svga's dx10.1): vmwgfx makes SM4_1 contexts,
    // Mesa offers what that adds to GL 3.3 (Mesa's svga needs SM5 for GL 4),
    // and multisamples: kmscube with 4x MSAA
    sm41: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " kmscube mesa-dri-gallium mesa-utils >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; tail -5 /tmp/apk.log", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["dmesg | grep -i -E 'shader model|dx2|capabilities' | tail -8; echo STEP_DMESG_DONE", /shader model: SM4_1[\s\S]*STEP_DMESG_DONE/],
        ["eglinfo -B -p gbm 2>&1 | grep -E 'OpenGL core profile (version|shading)' | head -4; echo STEP_EGLINFO_DONE",
            /OpenGL core profile version: 3\.3/],
        ["eglinfo -p gbm 2>&1 | grep -o -E 'GL_ARB_(texture_cube_map_array|texture_gather|draw_buffers_blend|sample_shading|texture_query_lod)' | sort -u; echo STEP_EXTENSIONS_DONE",
            /GL_ARB_draw_buffers_blend[\s\S]*GL_ARB_sample_shading[\s\S]*GL_ARB_texture_cube_map_array[\s\S]*GL_ARB_texture_gather[\s\S]*GL_ARB_texture_query_lod/],
        // (it starts slower than without MSAA)
        ["kmscube -s 4 -c 400 2>&1 | grep -E 'Rendered|renderer|samples|failed'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-msaa", after: 5000 }],
        ["kmscube -M rgba -c 200 2>&1 | grep -E 'Rendered|renderer'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-rgba", after: 2500 }],
    ],
    // shader model 5 (vmware_svga's dx11): vmwgfx makes SM5 contexts with
    // GL 4.3's extras, Mesa reports GL 4.3 with compute, tessellation,
    // SSBOs and images; kmscube with 8x MSAA
    sm5: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " kmscube mesa-dri-gallium mesa-utils >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; tail -5 /tmp/apk.log", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["dmesg | grep -i -E 'shader model|dx3' | tail -8; echo STEP_DMESG_DONE", /shader model: SM_5_1X[\s\S]*STEP_DMESG_DONE/],
        ["eglinfo -B -p gbm 2>&1 | grep -E 'OpenGL core profile (version|shading)' | head -4; echo STEP_EGLINFO_DONE",
            /OpenGL core profile version: 4\.3/],
        ["eglinfo -p gbm 2>&1 | grep -o -E 'GL_ARB_(compute_shader|tessellation_shader|shader_storage_buffer_object|shader_image_load_store|gpu_shader5)' | sort -u; echo STEP_EXTENSIONS_DONE",
            /GL_ARB_compute_shader[\s\S]*GL_ARB_gpu_shader5[\s\S]*GL_ARB_shader_image_load_store[\s\S]*GL_ARB_shader_storage_buffer_object[\s\S]*GL_ARB_tessellation_shader/],
        ["kmscube -s 8 -c 400 2>&1 | grep -E 'Rendered|renderer|samples|failed'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-msaa8", after: 5000 }],
        ["kmscube -M rgba -c 200 2>&1 | grep -E 'Rendered|renderer'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-rgba", after: 2500 }],
    ],
    // tests/x64/gltest.c on the adapter's 3D driver (virgl, svga): each
    // test's picture compared with llvmpipe's
    gltest: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK_VIRGL + " >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; grep -i -A3 error /tmp/apk.log | head", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        // (virtio_gpu: its features, and the host visible memory at level virgl43-hostmem)
        ["dmesg | grep -i -E 'features:|host memory window|shader model' | tail -4; echo STEP_DMESG_DONE", /STEP_DMESG_DONE/],
        ["tar -xf /dev/sdb -C /tmp && LIBGL_ALWAYS_SOFTWARE=1 /tmp/gltest ref 2>&1 | grep -E '^GLTEST (renderer|done|egl)|GL error|^shader|^link'; echo STEP_REF_DONE",
            /llvmpipe[\s\S]*STEP_REF_DONE/],
        ["/tmp/gltest cmp >/tmp/gltest.log 2>&1; grep -v '^GLIMG' /tmp/gltest.log; grep -q FAIL /tmp/gltest.log && grep '^GLIMG' /tmp/gltest.log; " +
            "dmesg | grep -i -A2 segfault | tail -4; echo STEP_GLTEST_DONE", /GLTEST done 0 failures[\s\S]*STEP_GLTEST_DONE/],
    ],
    // virtio_gpu's 3D (GPU_LEVEL=virgl): Mesa's virgl driver on the capsets,
    // what it reports, and kmscube
    // (Alpine 3.24's Mesa has no virgl driver: 3.23's, from v3.23/ of the repository)
    virgl: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        ["free -m | head -2; df -m / | tail -1; echo STEP_MEMORY_DONE", /STEP_MEMORY_DONE/],
        [APK_VIRGL + " kmscube mesa-utils mesa-demos weston weston-backend-drm weston-shell-desktop weston-clients seatd " +
            ">/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; grep -i -A3 error /tmp/apk.log | head -20", /STEP_APK_RC=[02]/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["dmesg | grep -i -E 'features:|capset|virgl' | tail -8; echo STEP_DMESG_DONE", /\+virgl[\s\S]*STEP_DMESG_DONE/],
        // which of GL 3.0's and GLES 3.0's prerequisites Mesa does not offer
        ["eglinfo -p gbm 2>&1 | sed -n '/compatibility profile extensions/,/OpenGL ES profile/p' | tr ',' '\\n' | sed 's/^ *//' | sort -u > /tmp/ext.txt; " +
            "for e in GL_ARB_color_buffer_float GL_ARB_depth_buffer_float GL_ARB_half_float_vertex GL_ARB_map_buffer_range " +
            "GL_ARB_shader_texture_lod GL_ARB_texture_float GL_ARB_texture_rg GL_ARB_texture_compression_rgtc GL_EXT_draw_buffers2 " +
            "GL_ARB_framebuffer_object GL_EXT_framebuffer_sRGB GL_EXT_packed_float GL_EXT_texture_array GL_EXT_texture_shared_exponent " +
            "GL_EXT_transform_feedback GL_NV_conditional_render GL_EXT_texture_sRGB GL_EXT_pixel_buffer_object GL_ARB_draw_instanced " +
            "GL_ARB_texture_buffer_object GL_ARB_uniform_buffer_object GL_ARB_texture_rectangle GL_NV_primitive_restart " +
            "GL_ARB_copy_buffer GL_EXT_texture_integer GL_ARB_texture_multisample GL_ARB_depth_clamp GL_ARB_ES3_compatibility " +
            "GL_ARB_draw_elements_base_vertex GL_EXT_provoking_vertex GL_EXT_vertex_array_bgra GL_EXT_texture_snorm " +
            "GL_ARB_seamless_cube_map GL_ARB_sync GL_ARB_fragment_coord_conventions GL_ARB_provoking_vertex " +
            "GL_ARB_blend_func_extended GL_ARB_explicit_attrib_location GL_ARB_occlusion_query2 GL_ARB_sampler_objects " +
            "GL_ARB_shader_bit_encoding GL_ARB_texture_rgb10_a2ui GL_ARB_texture_swizzle GL_ARB_timer_query " +
            "GL_ARB_instanced_arrays GL_ARB_vertex_type_2_10_10_10_rev; do grep -q \"^$e$\" /tmp/ext.txt || echo MISSING $e; done; " +
            "wc -l < /tmp/ext.txt; echo STEP_MISSING_DONE", /STEP_MISSING_DONE/],
        ["HOST stats", null],
        ["eglinfo -B -p gbm 2>&1 | grep -E 'OpenGL.*(renderer|version)' | head -12; echo STEP_EGLINFO_DONE", /virgl[\s\S]*STEP_EGLINFO_DONE/],
        // tests/x64/gltest.c: llvmpipe's pictures, then virgl's compared with them
        ["tar -xf /dev/sdb -C /tmp && LIBGL_ALWAYS_SOFTWARE=1 /tmp/gltest ref 2>&1 | grep -E '^GLTEST (renderer|done|egl)|GL error|^shader|^link'; echo STEP_REF_DONE",
            /llvmpipe[\s\S]*STEP_REF_DONE/],
        ["/tmp/gltest cmp >/tmp/gltest.log 2>&1; grep -v '^GLIMG' /tmp/gltest.log; grep -q FAIL /tmp/gltest.log && grep '^GLIMG' /tmp/gltest.log; echo STEP_GLTEST_DONE",
            /STEP_GLTEST_DONE/],
        ["kmscube -c 300 2>&1 | grep -E 'Rendered|renderer|failed|error' | head -5", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube", after: 4000 }],
        ["kmscube -M rgba -c 300 2>&1 | grep -E 'Rendered|failed|error' | head -5", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube-rgba", after: 4000 }],
        // a snapshot while kmscube draws (the 3D resources and the context
        // go into it and come back), then the tests again
        // (stdin a pipe nothing comes through: kmscube stops at the first input)
        ["sleep 1000 | kmscube -M rgba -c 100000 > /tmp/kmscube.log 2>&1 & sleep 6; echo STEP_BACKGROUND", /STEP_BACKGROUND/],
        ["HOST snapshot", null],
        ["sleep 3; echo STEP_AFTER_SNAPSHOT", /STEP_AFTER_SNAPSHOT/, { screenshot: "kmscube-after-snapshot", after: 2000 }],
        // (it went on drawing: SUBMIT_3D, 519, went on)
        ["HOST stats", null],
        ["pkill kmscube; sleep 1; grep -c Rendered /tmp/kmscube.log; tail -2 /tmp/kmscube.log; echo STEP_KILLED", /STEP_KILLED/],
        ["/tmp/gltest cmp 2>&1 | grep -E 'FAIL|done'; echo STEP_GLTEST_AGAIN", /GLTEST done 0 failures[\s\S]*STEP_GLTEST_AGAIN/],
        ["seatd -g video >/tmp/seatd.log 2>&1 & sleep 1; export XDG_RUNTIME_DIR=/tmp/xdg; mkdir -p -m 700 $XDG_RUNTIME_DIR; " +
            "(weston --backend=drm --shell=desktop --idle-time=0 --continue-without-input >/tmp/weston.log 2>&1 &); sleep 15; export WAYLAND_DISPLAY=$(ls $XDG_RUNTIME_DIR | grep -m1 '^wayland-[0-9]*$'); echo $WAYLAND_DISPLAY; " +
            "[ -n \"$WAYLAND_DISPLAY\" ] || { tail -25 /tmp/weston.log /tmp/seatd.log; ps; dmesg | tail -15; }; echo STEP_WESTON_UP",
            /wayland-\d[\s\S]*STEP_WESTON_UP/],
        ["timeout 20 weston-simple-egl -f 2>&1 | tail -3; echo STEP_EGL_DONE", /STEP_EGL_DONE/,
            { screenshot: "weston-simple-egl", after: 12000 }],
        ["timeout 15 es2gears_wayland 2>&1 | tail -3; echo STEP_GEARS_DONE", /STEP_GEARS_DONE/,
            { screenshot: "es2gears", after: 10000 }],
        ["grep -i -E 'error|renderer|GL version|EGL' /tmp/weston.log | head -20; echo STEP_WESTON_LOG", /STEP_WESTON_LOG/],
    ],
    // virtio_gpu's Vulkan (GPU_LEVEL=venus): Mesa's venus driver on the
    // device's Venus contexts (src/graphics_adapters/virtio_gpu/venus.js),
    // what vulkaninfo reports, next to lavapipe's
    venus: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " mesa-vulkan-virtio mesa-vulkan-swrast vulkan-loader vulkan-tools >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; " +
            "grep -i -A3 error /tmp/apk.log | head; ls /usr/share/vulkan/icd.d/", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["dmesg | grep -i -E 'features:|capset|host memory window' | tail -6; echo STEP_DMESG_DONE", /\+context_init[\s\S]*STEP_DMESG_DONE/],
        ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json vulkaninfo --summary > /tmp/lvp.txt 2>&1; echo rc=$?; " +
            "grep -E 'apiVersion|deviceName|driverName' /tmp/lvp.txt || head -30 /tmp/lvp.txt; echo STEP_LAVAPIPE_DONE", /STEP_LAVAPIPE_DONE/],
        ["VN_DEBUG=init VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json vulkaninfo --summary 2>&1 | tail -40; echo STEP_SUMMARY_DONE",
            /Venus[\s\S]*STEP_SUMMARY_DONE/],
        ["HOST stats", null],
        ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json vulkaninfo > /tmp/vulkaninfo.txt 2>&1; echo STEP_VULKANINFO_RC=$?; " +
            "wc -l < /tmp/vulkaninfo.txt; grep -i -E 'error|abort|fail' /tmp/vulkaninfo.txt | head -10", /STEP_VULKANINFO_RC=0/],
        // tests/x64/vktest.c: lavapipe's results, then Venus's (a real GPU:
        // GPU_RENDERER=chrome). On arm64, Alpine 3.24's lavapipe crashes in the
        // tests whose meta operations compile shaders (blit, resolve, ...; on
        // QEMU too): there it runs a test a process and Venus must pass them
        // all (vktest checks each result itself, its expectations lavapipe's on x86_64)
        ...(arm ? [
            ["tar -xf /dev/sdb -C /tmp && for t in $(/tmp/vktest list); do VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json " +
                "/tmp/vktest $t > /tmp/lvp-$t.log 2>&1; echo \"VKTEST-LVP $t rc=$? $(grep -E 'VKTEST '$t' (ok|FAIL)' /tmp/lvp-$t.log)\"; done; echo STEP_LVP_DONE",
                /STEP_LVP_DONE/],
            ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json /tmp/vktest " + (process.env.VKTEST_ONLY || "") +
                " 2>&1 | grep -E 'VKTEST|rror|abort'; echo STEP_VKTEST_DONE",
                /VKTEST done 0 failures[\s\S]*STEP_VKTEST_DONE/],
        ] : [
            ["tar -xf /dev/sdb -C /tmp && for t in " + (process.env.VKTEST_ONLY || "\"\"") + "; do VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json /tmp/vktest $t" +
                " 2>&1 | grep VKTEST; done; echo STEP_LVP_DONE",
                /VKTEST done[\s\S]*STEP_LVP_DONE/],
            ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json /tmp/vktest " + (process.env.VKTEST_ONLY || "") +
                " 2>&1 | grep -E 'VKTEST|rror|abort'; echo STEP_VKTEST_DONE",
                /STEP_VKTEST_DONE/],
        ]),
        ["HOST stats", null],
    ],
    // Venus's WSI (GPU_LEVEL=venus): vkcube on weston, through the driver's
    // software WSI (no dma-buf: each frame copied into a host visible buffer,
    // then into weston's wl_shm buffer); weston draws with pixman (Alpine
    // 3.24's Mesa has no GL driver for virtio-gpu)
    vkcube: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        // (the repository lacks two install_if packages: seatd-openrc, gstreamer-ptp-helper)
        [APK + " mesa-vulkan-virtio mesa-vulkan-swrast vulkan-loader vulkan-tools weston weston-backend-drm weston-shell-desktop seatd >/tmp/apk.log 2>&1; " +
            "echo STEP_APK_RC=$?; grep -i error /tmp/apk.log | head -5; command -v weston vkcube seatd >/dev/null && echo STEP_APK_PROGRAMS", /STEP_APK_PROGRAMS/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json vulkaninfo 2>/dev/null | grep -E '(VK_KHR_swapchain|VK_KHR_external_semaphore_fd|VK_KHR_external_fence_fd) ' | sort -u; " +
            "echo STEP_EXTENSIONS_DONE", /VK_KHR_swapchain[\s\S]*STEP_EXTENSIONS_DONE/],
        ["seatd -g video >/tmp/seatd.log 2>&1 & sleep 1; export XDG_RUNTIME_DIR=/tmp/xdg; mkdir -p -m 700 $XDG_RUNTIME_DIR; " +
            "(weston --backend=drm --renderer=pixman --shell=desktop --idle-time=0 --continue-without-input >/tmp/weston.log 2>&1 &); sleep 15; " +
            "export WAYLAND_DISPLAY=$(ls $XDG_RUNTIME_DIR | grep -m1 '^wayland-[0-9]*$'); echo $WAYLAND_DISPLAY; " +
            "[ -n \"$WAYLAND_DISPLAY\" ] || { tail -25 /tmp/weston.log /tmp/seatd.log; ps; dmesg | tail -15; }; echo STEP_WESTON_UP",
            /wayland-\d[\s\S]*STEP_WESTON_UP/],
        // what the Wayland surface offers (formats, present modes, extents)
        ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json vulkaninfo 2>&1 | sed -n '/Presentable Surfaces/,/Device Properties and Extensions/p' | " +
            "grep -v -E '^\\s*$' | head -60; echo STEP_SURFACE_DONE", /STEP_SURFACE_DONE/],
        // (lavapipe's first: vkcube itself on this weston)
        ["VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json timeout 60 vkcube --wsi wayland --c 20 > /tmp/vkcube-lvp.log 2>&1; " +
            "echo STEP_LVP_RC=$?; tail -5 /tmp/vkcube-lvp.log; dmesg | grep -i segfault | tail -3", /STEP_LVP_RC=/],
        // (frames per second: the frames over the seconds they took)
        ["S=$(date +%s); MESA_LOG_LEVEL=debug VN_DEBUG=result VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json timeout 120 vkcube --wsi wayland --c " +
            (process.env.VKCUBE_FRAMES || 1000) + " > /tmp/vkcube.log 2>&1; echo STEP_VKCUBE_RC=$? seconds=$(($(date +%s) - S)); tail -15 /tmp/vkcube.log; " +
            "dmesg | grep -i segfault | tail -2", /STEP_VKCUBE_RC=0/,
            { screenshot: "vkcube", after: 12000 }],
        ["HOST stats", null],
        // a snapshot while vkcube draws: the Venus context, its objects
        // and the GPU's contents go into it and come back; vkcube goes on
        ["(VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/virtio_icd.x86_64.json vkcube --wsi wayland --c 1000000 > /tmp/vkcube-bg.log 2>&1 &); " +
            "sleep 8; echo STEP_BACKGROUND", /STEP_BACKGROUND/, { screenshot: "vkcube-before-snapshot", after: 7000 }],
        ["HOST snapshot", null],
        ["sleep 6; echo STEP_AFTER_SNAPSHOT", /STEP_AFTER_SNAPSHOT/, { screenshot: "vkcube-after-snapshot", after: 5000 }],
        ["HOST stats", null],
        ["pidof vkcube && echo STEP_VKCUBE_ALIVE; pkill vkcube; sleep 1; tail -5 /tmp/vkcube-bg.log; echo STEP_KILLED", /STEP_VKCUBE_ALIVE[\s\S]*STEP_KILLED/],
        ["grep -i -E 'error|warn' /tmp/weston.log | head -10; echo STEP_WESTON_LOG", /STEP_WESTON_LOG/],
    ],
    // what Android's graphics needs of the kernel's KMS (docs/arm64-virt-android16-plan.md
    // P7.3; GPU_LEVEL=virgl43-hostmem, for the fences): the planes (a primary
    // and a cursor), an atomic mode set, the cursor, dma-buf PRIME from GBM
    // to weston (linux-dmabuf) and explicit synchronization with sync files
    // (EGL_ANDROID_native_fence_sync, weston's linux-explicit-synchronization)
    kms: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK_VIRGL + " libdrm-tests mesa-utils weston weston-backend-drm weston-shell-desktop weston-clients seatd " +
            ">/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; command -v modetest weston weston-simple-dmabuf-egl eglinfo >/dev/null && echo STEP_APK_PROGRAMS",
            /STEP_APK_PROGRAMS/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["modetest -M virtio_gpu -p 2>&1 | grep -E -A2 '^[0-9]+\\s+[0-9]+\\s+[0-9]+' | head -12; " +
            "modetest -M virtio_gpu -p | awk '/^Planes:/ {p=1} p && /^[0-9]/ {n++} END {print \"STEP_PLANES \" n}'",
            /STEP_PLANES [2-9]/],
        // (the connector, the CRTC and the primary plane: an atomic commit of
        // the mode and the plane with modetest's test pattern)
        ["C=$(modetest -M virtio_gpu -c | awk '$3==\"connected\" {print $1; exit}'); " +
            "R=$(modetest -M virtio_gpu -p | awk '/^CRTCs:/ {c=1; next} c && /^[0-9]/ {print $1; exit}'); " +
            "P=$(modetest -M virtio_gpu -p | awk '/^Planes:/ {p=1; next} p && /^[0-9]/ {print $1; exit}'); echo $C $R $P; " +
            "sleep 10 | modetest -M virtio_gpu -a -s $C@$R:1024x768 -P $P@$R:1024x768 > /tmp/atomic.log 2>&1; head -6 /tmp/atomic.log; " +
            "echo ATOMIC_FAILURES $(grep -c -i -E 'fail|invalid' /tmp/atomic.log); echo STEP_ATOMIC", /ATOMIC_FAILURES 0\r?\nSTEP_ATOMIC/,
            { screenshot: "atomic-modeset", after: 6000 }],
        ["sleep 12 | modetest -M virtio_gpu -s $C:1024x768 -C 2>&1 | head -4; echo STEP_CURSOR", /STEP_CURSOR/,
            { screenshot: "cursor", after: 8000 }],
        ["HOST stats", null],
        ["eglinfo -p gbm 2>&1 | grep -o -E 'EGL_ANDROID_native_fence_sync|EGL_EXT_image_dma_buf_import|EGL_MESA_image_dma_buf_export' | sort -u; echo STEP_EGL_EXTENSIONS",
            /EGL_ANDROID_native_fence_sync[\s\S]*EGL_EXT_image_dma_buf_import[\s\S]*STEP_EGL_EXTENSIONS/],
        ["seatd -g video >/tmp/seatd.log 2>&1 & sleep 1; export XDG_RUNTIME_DIR=/tmp/xdg; mkdir -p -m 700 $XDG_RUNTIME_DIR; " +
            "(weston --backend=drm --shell=desktop --idle-time=0 --continue-without-input >/tmp/weston.log 2>&1 &); sleep 15; export WAYLAND_DISPLAY=$(ls $XDG_RUNTIME_DIR | grep -m1 '^wayland-[0-9]*$'); echo $WAYLAND_DISPLAY; " +
            "[ -n \"$WAYLAND_DISPLAY\" ] || { tail -25 /tmp/weston.log /tmp/seatd.log; ps; dmesg | tail -15; }; echo STEP_WESTON_UP",
            /wayland-\d[\s\S]*STEP_WESTON_UP/],
        ["weston-simple-dmabuf-egl --help 2>&1 | head -30; echo STEP_HELP", /STEP_HELP/],
        // (dma-buf from GBM through linux-dmabuf; then with explicit
        // synchronization: acquire and release fences as sync files)
        ["timeout 20 weston-simple-dmabuf-egl 2>&1 | tail -4; echo STEP_DMABUF rc=$?", /STEP_DMABUF/,
            { screenshot: "dmabuf", after: 15000 }],
        ["timeout 20 weston-simple-dmabuf-egl -e 1 2>&1 | tail -4; echo STEP_EXPLICIT", /STEP_EXPLICIT/,
            { screenshot: "dmabuf-explicit-sync", after: 15000 }],
        ["grep -i -E 'dmabuf|explicit|sync|error' /tmp/weston.log | head -12; echo STEP_WESTON_LOG", /explicit sync: yes[\s\S]*STEP_WESTON_LOG/],
        ["HOST stats", null],
    ],
    // input on the desktop (the virt machine's virtio-input, P7.4): weston
    // with its input devices (no --continue-without-input), text typed into
    // weston-terminal (which runs it), the pointer moved and clicked, and
    // two touches on the multi-touch screen read from its evdev node
    input: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " mesa-dri-gallium weston weston-backend-drm weston-shell-desktop weston-terminal weston-clients seatd " +
            ">/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; grep -i error /tmp/apk.log | head -5; " +
            "command -v weston weston-terminal seatd >/dev/null && echo STEP_APK_PROGRAMS", /STEP_APK_PROGRAMS/],
        [`modprobe ${DRIVER}; modprobe evdev; modprobe virtio_input; sleep 2; ls /dev/dri /dev/input; echo STEP_DRM_OK`, /event\d[\s\S]*STEP_DRM_OK/],
        // (the live system has eudev's libudev but no udevd: libinput takes
        // only devices whose udev properties say they are input devices, so
        // the database entries udevd's input_id would write are written here)
        ["mkdir -p /run/udev/data; for e in /sys/class/input/event*; do t=; case \"$(cat $e/device/name)\" in " +
            "*Keyboard) t='ID_INPUT_KEY=1 ID_INPUT_KEYBOARD=1';; *Tablet) t='ID_INPUT_MOUSE=1';; *MultiTouch) t='ID_INPUT_TOUCHSCREEN=1';; esac; " +
            "{ echo I:1; echo E:ID_INPUT=1; for p in $t; do echo E:$p; done; echo G:seat; echo Q:seat; echo V:1; } > /run/udev/data/c$(cat $e/dev); done; " +
            "grep -c ID_INPUT=1 /run/udev/data/c13:*; echo STEP_UDEV_DATA", /STEP_UDEV_DATA/],
        ["seatd -g video >/tmp/seatd.log 2>&1 & sleep 1; export XDG_RUNTIME_DIR=/tmp/xdg; mkdir -p -m 700 $XDG_RUNTIME_DIR; " +
            "(weston --backend=drm --shell=desktop --idle-time=0 >/tmp/weston.log 2>&1 &); sleep 20; export WAYLAND_DISPLAY=$(ls $XDG_RUNTIME_DIR | grep -m1 '^wayland-[0-9]*$'); echo $WAYLAND_DISPLAY; " +
            "[ -n \"$WAYLAND_DISPLAY\" ] || { tail -25 /tmp/weston.log /tmp/seatd.log; ps; dmesg | tail -15; }; echo STEP_WESTON_UP",
            /wayland-\d[\s\S]*STEP_WESTON_UP/],
        ["grep -i -E 'input device|keyboard|pointer|touch' /tmp/weston.log | head -12; echo STEP_INPUT_DEVICES",
            /Virtio Keyboard[\s\S]*Virtio Tablet[\s\S]*STEP_INPUT_DEVICES/],
        ["(weston-terminal --shell=/bin/sh >/tmp/terminal.log 2>&1 &); sleep 20; echo STEP_TERMINAL", /STEP_TERMINAL/],
        ["HOST pointer 0.5 0.5", null],
        ["HOST click", null],
        ["HOST type touch /tmp/typed\n", null],
        ["sleep 8; [ -e /tmp/typed ] && echo TYPED_FILE_EXISTS; grep -c SYN_DROPPED /tmp/weston.log; echo STEP_TYPED", /\nTYPED_FILE_EXISTS[\s\S]*STEP_TYPED/,
            { screenshot: "weston-typed", after: 6000 }],
        // (the multi-touch screen's events as the guest's evdev reads them,
        // for 15 s: two touches, tracking IDs 0 and 1, the first at x 0.25
        // (0x2000), BTN_TOUCH down; then both lifted, BTN_TOUCH up)
        ["for e in /sys/class/input/event*; do grep -q MultiTouch $e/device/name && M=/dev/input/${e##*/}; done; " +
            "(timeout 15 dd if=$M bs=24 2>/dev/null | hexdump -v -e '24/1 \"%02x\" \"\\n\"' | sed 's/^/GPU_EVT /' > /tmp/touch.txt &); sleep 2; echo STEP_TOUCH_READY",
            /STEP_TOUCH_READY/],
        ["HOST touch 0.25 0.25 0.75 0.5", null],
        ["HOST touch", null],
        ["sleep 16; cut -c 41- /tmp/touch.txt | tr '\\n' ' '; echo; echo STEP_TOUCHED",
            /0300390000000000 0300350000200000[\s\S]*0300390001000000[\s\S]*01004a0101000000[\s\S]*03003900ffffffff[\s\S]*01004a0100000000[\s\S]*STEP_TOUCHED/],
    ],
    // the page's size reaching the guest (virtio_gpu): a display event, the
    // new preferred mode, which a KMS client then sets
    resize: [
        ["mkdir -p /mnt/repo && tar -xf /dev/sda -C /mnt/repo && echo STEP_REPO_OK", /STEP_REPO_OK/],
        [APK + " kmscube libdrm-tests mesa-dri-gallium >/tmp/apk.log 2>&1; echo STEP_APK_RC=$?; tail -5 /tmp/apk.log", /STEP_APK_RC=0/],
        [`modprobe ${DRIVER} && sleep 2 && ls /dev/dri && echo STEP_DRM_OK`, /STEP_DRM_OK/],
        ["dmesg | grep -i -E 'virtio_gpu|virtio-pci|fb0|features:|scanouts' | tail -12; echo STEP_DMESG_DONE", /\+edid[\s\S]*STEP_DMESG_DONE/],
        ["cat /sys/class/drm/card*-Virtual-1/modes | head -3; echo STEP_MODES_DONE", /^1024x768\r?$/m],
        ["SCREENSHOT console", null],
        ["HOST set_display_size 1280 800", null],
        // (sysfs lists what fbdev's probe kept, which is no larger than its
        // frame buffer; a KMS client's probe sees every mode)
        ["sleep 3; modetest -M virtio_gpu -c | grep -m3 -E '#[0-9]+ '; echo STEP_MODES_DONE", /#0 1280x800 [\s\S]*preferred[\s\S]*STEP_MODES_DONE/],
        ["C=$(modetest -M virtio_gpu -c | awk '$3==\"connected\" {print $1; exit}'); sleep 10 | modetest -M virtio_gpu -s $C:1280x800 2>&1 | head -4",
            /setting mode 1280x800/, { screenshot: "modetest-1280x800", after: 7000 }],
        // a snapshot taken and restored with the mode set: the guest carries on
        ["HOST snapshot", null],
        ["SCREENSHOT restored", null],
        ["cat /sys/class/drm/card*-Virtual-1/status; echo STEP_RESTORED", /connected[\s\S]*STEP_RESTORED/],
        ["kmscube -c 100 2>&1 | grep -E 'Rendered|renderer'", /Rendered [1-9]\d* frames/,
            { screenshot: "kmscube", after: 20000 }],
        // (the commands the guest sent: blob ones at the levels with blobs)
        ["HOST stats", null],
    ],
};
// (GPU_SCENARIO=custom: the steps in the JSON file GPU_STEPS, [command, pattern source, options], for debugging)
if(scenario === "custom")
{
    SCENARIOS.custom = JSON.parse(fs.readFileSync(process.env.GPU_STEPS, "utf8")).map(([command, pattern, options]) =>
        [command, pattern === null ? null : new RegExp(pattern), ...(options ? [options] : [])]);
}
assert.ok(SCENARIOS[scenario], "unknown GPU_SCENARIO " + scenario);
// (the repository's and the test programs' disks: $REPO and $TESTS, set
// after the login; the Vulkan ICDs are the architecture's)
// (the arm64 guest's programs start about three times slower: its sleeps
// and timeouts are three times as long)
const steps = SCENARIOS[scenario].map(([command, ...rest]) => [command.replaceAll("/dev/sda", "$REPO").replaceAll("/dev/sdb", "$TESTS")
    .replaceAll(".x86_64.json", "." + arch + ".json")
    .replace(/\b(sleep|timeout) (\d+)([; ])/g, (match, verb, seconds, after) => arm ? `${verb} ${seconds * 3}${after}` : match), ...rest]);
const DISKS = arm ? "REPO=; TESTS=; for d in /sys/block/vd*; do case \"$(cat $d/serial 2>/dev/null)\" in " +
    "a64gpurepo) REPO=/dev/${d##*/};; a64gputests) TESTS=/dev/${d##*/};; esac; done; echo STEP_DISKS $REPO $TESTS" :
    "REPO=/dev/sda; TESTS=/dev/sdb; echo STEP_DISKS $REPO $TESTS";


const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const sink = new PictureSink();
// A 3D level needs a renderer: the real one in a headless Chrome
// (GPU_RENDERER=chrome, tests/x64/gpu_remote_renderer.mjs), or one that
// records the batches into a trace (tests/x64/gpu_trace.mjs) and renders nothing
// tests/x64/gltest.c for the scenarios that run it (/dev/sdb): built here
// with clang and rust-lld against musl's libc and Mesa's libEGL, taken from
// the repository's Alpine 3.23 packages
function build_gltest()
{
    const dir = directory + "gltest/", sysroot = dir + "sysroot/";
    const run = (program, args) => {
        const result = spawnSync(program, args, { encoding: "utf8" });
        assert.equal(result.status, 0, `${program}: ${result.stderr || result.error}`);
        return result.stdout.trim();
    };
    fs.mkdirSync(sysroot, { recursive: true });
    const packages = directory + "gpu-repo/v3.23/main/" + arch + "/";
    for(const name of fs.readdirSync(packages).filter(f => /^(musl|mesa-egl)-\d.*\.apk$/.test(f)))
    {
        spawnSync("bsdtar", ["-xf", packages + name, "-C", sysroot]);
    }
    const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
    const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
    run(process.env.CLANG || "clang", ["--target=" + arch + "-unknown-linux-musl", "-fPIC", "-O1", "-c", root + "tests/x64/gltest.c", "-o", dir + "gltest.o"]);
    run(lld, ["-flavor", "gnu", "-m", LINKER_EMULATION, "-pie", "--dynamic-linker", "/lib/ld-musl-" + arch + ".so.1", "--allow-shlib-undefined",
        "-o", dir + "gltest", dir + "gltest.o", sysroot + "lib/ld-musl-" + arch + ".so.1", sysroot + "usr/lib/libEGL.so.1"]);
    run("bsdtar", ["--format", "ustar", "--no-xattrs", "--no-mac-metadata", "--uid", "0", "--gid", "0", "-cf", dir + "gltest.tar", "-C", dir, "gltest"]);
    return dir + "gltest.tar";
}
// tests/x64/vktest.c, for the venus scenario (/dev/sdb): the same way,
// against the Vulkan loader, with third_party/vulkan's headers
function build_vktest()
{
    const dir = directory + "vktest/", sysroot = dir + "sysroot/";
    const run = (program, args) => {
        const result = spawnSync(program, args, { encoding: "utf8" });
        assert.equal(result.status, 0, `${program}: ${result.stderr || result.error}`);
        return result.stdout.trim();
    };
    fs.mkdirSync(sysroot, { recursive: true });
    const packages = directory + "gpu-repo/main/" + arch + "/";
    for(const name of fs.readdirSync(packages).filter(f => /^(musl|vulkan-loader)-\d.*\.apk$/.test(f)))
    {
        spawnSync("bsdtar", ["-xf", packages + name, "-C", sysroot]);
    }
    const host = run("rustc", ["-vV"]).match(/host: (.+)/)[1];
    const lld = process.env.LD_LLD || `${run("rustc", ["--print", "sysroot"])}/lib/rustlib/${host}/bin/rust-lld`;
    // the shaders, as C arrays: tests/x64/vktest_shaders/ by naga (Vulkan GLSL)
    const shaders = [];
    for(const name of fs.readdirSync(root + "tests/x64/vktest_shaders").sort())
    {
        const stage = { vert: "vert", frag: "frag", comp: "compute" }[name.split(".").pop()];
        const spv = dir + name + ".spv";
        run(process.env.NAGA || "naga", ["--input-kind", "glsl", "--shader-stage", stage, "--keep-coordinate-space",
            root + "tests/x64/vktest_shaders/" + name, spv]);
        const file = fs.readFileSync(spv);
        const words = new Uint32Array(file.buffer.slice(file.byteOffset, file.byteOffset + file.length));
        shaders.push(`static const uint32_t SPV_${name.replace(".", "_")}[] = { ${Array.from(words, w => "0x" + w.toString(16)).join(", ")} };`);
    }
    // vkcube's (glslang's: combined image samplers), out of the guest's vulkan-tools
    const tools = fs.readdirSync(packages).find(f => /^vulkan-tools-\d.*\.apk$/.test(f));
    spawnSync("bsdtar", ["-xf", packages + tools, "-C", dir, "usr/bin/vkcube"]);
    const binary = fs.readFileSync(dir + "usr/bin/vkcube");
    for(let align = 0; align < 4; align++)
    {
        const w = new Uint32Array(binary.buffer.slice(binary.byteOffset + align, binary.byteOffset + align + (binary.length - align & ~3)));
        for(let i = 0; i < w.length; i++)
        {
            if(w[i] !== 0x07230203) continue;
            // the module: instructions while they parse, to its last OpFunctionEnd
            let at = i + 5, end = 0, model = -1;
            while(at < w.length)
            {
                const count = w[at] >>> 16, op = w[at] & 0xFFFF;
                if(!count || op > 400 && op < 4400) break;
                if(op === 15 && model < 0) model = w[at + 1];
                at += count;
                if(op === 56) end = at;
            }
            const stage = { 0: "vert", 4: "frag" }[model];
            if(!end || !stage) continue;
            shaders.push(`static const uint32_t SPV_cube_${stage}[] = { ${Array.from(w.subarray(i, end), x => "0x" + x.toString(16)).join(", ")} };`);
        }
    }
    fs.writeFileSync(dir + "vktest_shaders.h", "// generated by tests/x64/linux_gpu.mjs\n" + shaders.join("\n") + "\n");
    run(process.env.CLANG || "clang", ["--target=" + arch + "-unknown-linux-musl", "-fPIC", "-O1", "-I", dir, "-I", root + "tests/x64/include", "-I", root + "third_party/vulkan",
        "-c", root + "tests/x64/vktest.c", "-o", dir + "vktest.o"]);
    run(lld, ["-flavor", "gnu", "-m", LINKER_EMULATION, "-pie", "--dynamic-linker", "/lib/ld-musl-" + arch + ".so.1", "--allow-shlib-undefined",
        "-o", dir + "vktest", dir + "vktest.o", sysroot + "lib/ld-musl-" + arch + ".so.1", sysroot + "usr/lib/libvulkan.so.1"]);
    run("bsdtar", ["--format", "ustar", "--no-xattrs", "--no-mac-metadata", "--uid", "0", "--gid", "0", "-cf", dir + "vktest.tar", "-C", dir, "vktest"]);
    return dir + "vktest.tar";
}
const LINKER_EMULATION = arm ? "aarch64linux" : "elf_x86_64";
const gltest = steps.some(step => step[0].includes("$TESTS")) ? (scenario === "venus" ? build_vktest() : build_gltest()) : null;

const remote = LEVEL_3D && process.env.GPU_RENDERER === "chrome" ? await create_remote_renderer() : null;
const trace = LEVEL_3D && !remote ?
    create_trace_renderer(path.join(out, "trace.bin"), { adapter, level: process.env.GPU_LEVEL, scenario }) : null;
// VENUS_TRACE=1: the Venus commands the device runs, as decoded (venus.js's on_command)
const venus_trace = name => +process.env.VENUS_TRACE > 1 || !/^vk(Cmd|SetReply|Get(PhysicalDevice|Device|Image|Buffer)\w*(Properties|Requirements))/.test(name);
// (the root file system is half the RAM: the arm64 packages need more than 512 MiB of it)
const memory_size = Number(process.env.LINUX_GPU_MEMORY || (arm || ["virgl", "vkcube"].includes(scenario) ? 1536 : 1024)) * 1048576;
const array_buffer = file => { const b = fs.readFileSync(file); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };
const test_options = process.env.GPU_LEVEL ? { graphics_adapter_test: { level: process.env.GPU_LEVEL, renderer: remote ? remote.renderer : trace && trace.renderer } } : {};
// (the virt machine: the ISO, the repository and the test programs on
// virtio-blk, the GPU on the PCIe host or virtio-mmio; less than 2 GiB of
// RAM with the GPU's device memory)
const emulator = arm ? new V86({
    cpu_type: "arm64", graphics_adapter: "virtio_gpu", wasm_path: process.env.A64_WASM || root + "build/v86-arm64.wasm",
    kernel: { url: directory + "boot/vmlinuz-virt" }, initrd: { url: directory + "boot/initramfs-virt" },
    cmdline: "console=ttyAMA0 loglevel=4 nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage",
    virtio_disks: [{ buffer: array_buffer(iso), readonly: true }, { buffer: array_buffer(repo), id: "a64gpurepo", readonly: true },
        ...(gltest ? [{ buffer: array_buffer(gltest), id: "a64gputests", readonly: true }] : [])],
    virtio_transport: process.env.GPU_TRANSPORT || "pci", virtio_input: ["keyboard", "tablet", "multitouch"],
    memory_size, cpu_cores: Number(process.env.GPU_CORES || 1), autostart: false, log_level: 0, net_device: { type: "none" },
    screen_adapter: sink, ...(+process.env.GPU_NO_JIT ? {} : { jit_switches: { a64_page: 1 } }), ...test_options,
}) : new V86({
    graphics_adapter: adapter,
    wasm_path: process.env.WASM_PATH,
    bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
    bzimage: { url: directory + "boot/vmlinuz-virt" }, initrd: { url: directory + "boot/initramfs-virt" },
    cdrom: { url: iso }, hda: { url: repo }, ...(gltest ? { hdb: { url: gltest } } : {}),
    cmdline: "console=ttyS0,115200 loglevel=4 nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage",
    // (the root file system is half the RAM: the virgl and vkcube scenarios' packages need more than 1 GiB's)
    memory_size, acpi: true, autostart: false,
    disable_jit: !!+process.env.LINUX_GPU_NO_JIT, experimental_smp_jit: !+process.env.LINUX_GPU_NO_JIT,
    log_level: 0, net_device: { type: "none" }, screen_adapter: sink,
    ...(process.env.VRAM_SIZE ? { vram_size: Number(process.env.VRAM_SIZE) } : {}),
    ...test_options,
});

let serial = "";
// the guest drivers' logs through the VMware backdoor (vmwgfx's host log)
emulator.add_listener("vmware-log", text => console.log("guest-log: " + String(text).trim()));
emulator.add_listener("serial0-output-byte", byte => {
    const c = String.fromCharCode(byte);
    serial += c;
    if(+process.env.SHOW_LOGS) process.stdout.write(c);
});

const started = performance.now();
const elapsed = () => ((performance.now() - started) / 1000).toFixed(0) + "s";
const deadline = started + Number(process.env.LINUX_GPU_TIMEOUT || (arm ? 2700000 : 900000));

async function wait_for(pattern, from)
{
    while(performance.now() < deadline)
    {
        const tail = serial.slice(from);
        if(pattern.test(tail)) return tail;
        if(/Kernel panic/.test(serial)) throw new Error("Kernel panic");
        await delay(20);
    }
    throw new Error("timed out waiting for " + pattern);
}

/** A step's third element: { screenshot, after } */
const arguments_of = step => step[2] || {};

let failed = false;
try
{
    await new Promise((resolve, reject) => {
        emulator.add_listener("emulator-loaded", resolve);
        emulator.add_listener("emulator-error", reject);
    });
    const cpu = emulator.v86.cpu;
    if(!arm) cpu.wm.exports.set_x64_test_capabilities(1);
    const venus = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["virtio_gpu"]?.venus;
    if(venus && +process.env.VENUS_TRACE)
    {
        venus.on_command = (name, a) => {
            if(!venus_trace(name)) return;
            const brief = JSON.stringify(a, (k, v) => ArrayBuffer.isView(v) ? "[" + v.length + " bytes]" : v);
            console.log("venus: " + name + " " + brief.slice(0, 300));
        };
        if(+process.env.VENUS_TRACE > 1) venus.vk.debug = text => console.log("venus-device: " + text);
    }
    emulator.run();
    // GPU_DEBUG_BLITS=n: the first n BLIT_SURFACE_TO_SCREEN commands and what came of them
    const svga3d_debug = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"]?.svga3d;
    if(svga3d_debug && +process.env.GPU_DEBUG_BLITS)
    {
        let left = +process.env.GPU_DEBUG_BLITS;
        const blit = svga3d_debug.blit_surface_to_screen.bind(svga3d_debug), to_desktop = svga3d_debug.to_desktop.bind(svga3d_debug);
        svga3d_debug.blit_surface_to_screen = p => { if(left > 0) console.log("BLIT_SURFACE_TO_SCREEN " + Array.from(p).join(" ")); blit(p); };
        svga3d_debug.to_desktop = (...args) => {
            if(left-- > 0)
            {
                const [surface] = args;
                console.log("to_desktop format=" + surface.format + " sizes=" + JSON.stringify(surface.sizes) + " " + args.slice(1).map(a => JSON.stringify(a)).join(" ") +
                    " screens=" + JSON.stringify([...svga3d_debug.device.screens.screens.values()].map(s => [s.id, s.x, s.y, s.width, s.height])));
            }
            to_desktop(...args);
        };
    }

    // virgl's shaders as they come (TGSI text): GPU_OUT/tgsi/, each once
    const virgl = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["virtio_gpu"]?.virgl;
    if(virgl)
    {
        const dir = path.join(out, "tgsi");
        fs.mkdirSync(dir, { recursive: true });
        if(+process.env.GPU_DEBUG_VIRGL) virgl.debug_log = text => console.log("virgl-debug " + text);
        const seen = new Set();
        virgl.shader_log = (type, text) => {
            if(seen.has(text)) return;
            seen.add(text);
            const stage = ["vs", "fs", "gs", "tcs", "tes", "cs"][type] || "s" + type;
            fs.writeFileSync(path.join(dir, String(seen.size).padStart(3, "0") + "-" + stage + ".txt"), text);
        };
    }

    // vmware_svga's DX shaders as they come (VGPU10 tokens): GPU_OUT/dxbc/, each once
    if(svga3d_debug)
    {
        const dir = path.join(out, "dxbc");
        fs.mkdirSync(dir, { recursive: true });
        const seen = new Set();
        svga3d_debug.shader_log = (shid, type, bytes) => {
            const key = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
            if(seen.has(key)) return;
            seen.add(key);
            fs.writeFileSync(path.join(dir, String(seen.size).padStart(3, "0") + "-" + type + ".bin"), bytes);
        };
    }

    await wait_for(/localhost login:/, 0);
    emulator.serial0_send("root\n");
    await wait_for(/localhost:~# /, 0);
    console.log(`[${elapsed()}] logged in`);
    {
        const from = serial.length;
        emulator.serial0_send(DISKS + "\n");
        const tail = await wait_for(/\nSTEP_DISKS \/dev\/\w+ ?(\/dev\/\w+)?\r?\n[\s\S]*localhost:~# /, from);
        console.log(`[${elapsed()}] disks: ${tail.match(/\nSTEP_DISKS ([^\r\n]*)/)[1]}`);
    }

    for(const step of steps)
    {
        const [command, expect] = step;
        if(command.startsWith("HOST "))
        {
            // the page's side: HOST set_display_size <width> <height> [display],
            // HOST snapshot (saved, then restored in place)
            const [verb, ...values] = command.slice(5).split(" ");
            if(verb === "set_display_size") emulator.set_display_size(...values.map(Number));
            // HOST pointer <x> <y> (fractions of the screen), HOST click, HOST type <text>,
            // HOST touch [<x> <y> ...] (the touches now, fractions of the screen; none: all lifted)
            else if(verb === "pointer") emulator.bus.send("mouse-absolute", [Number(values[0]) * 1000, Number(values[1]) * 1000, 1000, 1000]);
            else if(verb === "click")
            {
                emulator.bus.send("mouse-click", [true, false, false]);
                await delay(100);
                emulator.bus.send("mouse-click", [false, false, false]);
            }
            // (slowly: a guest compositor under emulation that renders in
            // software for a while lets evdev's 64 events overflow, SYN_DROPPED,
            // and libinput drops the keys)
            else if(verb === "type") await emulator.keyboard_send_text(values.join(" ").replace(/\\n/g, "\n"), 400);
            else if(verb === "touch")
            {
                const touches = [];
                for(let i = 0; i + 1 < values.length; i += 2) touches.push([i / 2, Number(values[i]) * 1000, Number(values[i + 1]) * 1000]);
                emulator.bus.send("touch", { "touches": touches, "width": 1000, "height": 1000 });
            }
            else if(verb === "stats")
            {
                // what the adapter's device has done (virtio_gpu: commands, virgl's)
                const device = emulator.v86.cpu.devices.graphics_adapter.device;
                const gpu = device["virtio_gpu"];
                if(gpu) console.log("virtio-gpu " + JSON.stringify({ stats: gpu.stats, active: gpu.active,
                    scanouts: gpu.scanouts.map(s => [s.enabled, s.resource_id, s.width, s.height, !!s.rgba]), pending: gpu.pending && gpu.pending.length,
                    virgl: gpu.virgl && { counts: gpu.virgl.counts, warnings: gpu.virgl.warnings, submitted: gpu.virgl.submitted, completed: gpu.virgl.completed,
                        requests: gpu.virgl.requests.size, completions: gpu.virgl.completions.length },
                    venus: gpu.venus && { stats: gpu.venus.stats, vk: gpu.venus.vk.stats, warnings: gpu.venus.vk.warnings,
                        contexts: [...gpu.venus.contexts.values()].map(c => ({ rings: c.rings.size, objects: c.objects.size })) } }));
            }
            else if(verb === "snapshot")
            {
                await emulator.stop();
                const state = await emulator.save_state();
                await emulator.restore_state(state);
                await emulator.run();
                console.log(`[${elapsed()}] snapshot: ${(state.byteLength / 1048576).toFixed(1)} MiB, restored`);
            }
            else throw new Error("unknown HOST step " + verb);
            console.log(`[${elapsed()}] ${command}`);
            continue;
        }
        if(command.startsWith("SCREENSHOT "))
        {
            // nothing presents in node: ask for a whole frame first
            cpu.devices.display.request_frame(true);
            const file = save_png(sink, out, command.slice(11));
            console.log(`[${elapsed()}] screenshot ${file || "(text mode)"}`);
            continue;
        }
        const from = serial.length;
        emulator.serial0_send(command + "\n");
        const options = arguments_of(step);
        if(options.screenshot)
        {
            // (GPU_SCREENSHOT_AFTER: ms, for every screenshot step instead of its
            // own; the arm64 guest's llvmpipe takes three times as long to start)
            await delay(Number(process.env.GPU_SCREENSHOT_AFTER || options.after * (arm && !LEVEL_3D ? 3 : 1)));
            cpu.devices.display.request_frame(true);
            console.log(`[${elapsed()}] screenshot ${save_png(sink, out, options.screenshot)}`);
        }
        // the command is done when the prompt comes back after its output
        const tail = await wait_for(/\n[^\n]*localhost:~# /, from + command.length);
        console.log(`[${elapsed()}] $ ${command}\n` + tail.replace(/\r/g, "").split("\n").slice(1, -1).join("\n"));
        if(!expect.test(tail)) throw new Error("step failed: " + command);
    }
    console.log("LINUX_GPU_DONE " + adapter + " " + scenario);
}
catch(error)
{
    failed = true;
    console.error("LINUX_GPU_FAIL " + adapter + ": " + error.message + "\n" + error.stack);
    emulator.v86 && emulator.v86.cpu.devices.display && emulator.v86.cpu.devices.display.request_frame(true);
    save_png(sink, out, "failure");
}
finally
{
    fs.writeFileSync(path.join(out, "serial.log"), serial);
    // gltest's failures: its pictures (PPM in base64) as PNG
    const pictures = new Map();
    for(const m of serial.replace(/\r/g, "").matchAll(/^GLIMG (\S+) (\S+) (\d+) (\S+)$/gm))
    {
        const key = m[1] + "-" + m[2];
        pictures.set(key, (pictures.get(key) || "") + m[4]);
    }
    for(const [key, text] of pictures)
    {
        const ppm = Buffer.from(text, "base64");
        const header = /^P6\n(\d+) (\d+)\n255\n/.exec(ppm.subarray(0, 32).toString("latin1"));
        if(!header) continue;
        const width = +header[1], height = +header[2], rgb = ppm.subarray(header[0].length);
        const rgba = new Uint8Array(width * height * 4);
        for(let i = 0; i < width * height; i++) rgba.set([rgb[3 * i], rgb[3 * i + 1], rgb[3 * i + 2], 255], 4 * i);
        console.log("gltest picture " + save_png({ width, height, rgba }, out, "gltest-" + key));
    }
    const svga3d = emulator.v86 && emulator.v86.cpu.devices.graphics_adapter && emulator.v86.cpu.devices.graphics_adapter.device["svga"]?.svga3d;
    if(svga3d) console.log("svga3d commands: " + JSON.stringify(svga3d.counts) + " warnings: " + JSON.stringify(svga3d.warnings));
    const virgl_end = emulator.v86 && emulator.v86.cpu.devices.graphics_adapter && emulator.v86.cpu.devices.graphics_adapter.device["virtio_gpu"]?.virgl;
    if(virgl_end) console.log("virgl: " + JSON.stringify({ counts: virgl_end.counts, warnings: virgl_end.warnings }));
    if(remote)
    {
        remote.close();
        console.log("renderer: " + JSON.stringify(remote.stats));
    }
    if(trace)
    {
        trace.close();
        console.log("trace: " + JSON.stringify(trace.stats) + " in " + path.join(out, "trace.bin"));
    }
    emulator.destroy();
}
process.exit(failed ? 1 : 0);
                                                                                                                                                                                                                                                                                                                              source/v64/tests/x64/linux_hwprobe.c                                                                0000644 0000000 0000000 00000001733 00000000000 014504  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* libhwprobe.so, for the glibc-hwcaps check of tests/x64/linux_glibc_probe.c
 * (docs/simd-xsave-plan.md 11.3): built for baseline x86-64 into the library
 * directory and with -march=x86-64-v3 into its glibc-hwcaps/x86-64-v3
 * subdirectory, where ld.so takes it from when the CPU supports x86-64-v3.
 * The v3 build's loops become FMA, AVX2 and BMI2 code (the harness checks
 * the disassembly). */
#ifdef HWPROBE_V3
const char *hwprobe_level(void) { return "x86-64-v3"; }
#else
const char *hwprobe_level(void) { return "baseline"; }
#endif
/* (a chain of multiply-adds: VFMADD231SD in the v3 build) */
double hwprobe_dot(const double *a, const double *b, int n)
{
    double s = 0;
    for(int i = 0; i < n; i++) s += a[i] * b[i];
    return s;
}
/* (vectorized: VPMULLD, VPSRLVD, VPXOR, VPADDD ymm in the v3 build) */
unsigned hwprobe_mix(const unsigned *v, int n)
{
    unsigned s = 0;
    for(int i = 0; i < n; i++) s += (v[i] * 2654435761u) ^ (v[i] >> (i & 15));
    return s;
}
                                     source/v64/tests/x64/linux_probe.c                                                                  0000644 0000000 0000000 00000074044 00000000000 014152  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Freestanding Linux user probe, built once for x86_64 and once for i386 so
 * the same checks run as a native 64-bit process and as a compatibility-mode
 * process under an x86_64 kernel: raw system calls, uname, mmap/mprotect with
 * a SIGSEGV round trip, fork/pipe/wait4, CLONE_THREAD threads bound to every
 * online CPU with LOCKed counters, a cross-CPU TLB shootdown after MAP_FIXED,
 * tmpfs file I/O, and the physical placement of 16 MiB of touched pages
 * (how many frames lie above 4 GiB, from /proc/self/pagemap). A second line
 * (X64_PROBE_XC) covers the multicore matrix: /sys topology, thread
 * migration, signals to threads on other CPUs, cross-modifying code
 * executed on another CPU, and an O_DIRECT read of the disk. A third line
 * (X64_PROBE_YMM) checks the YMM registers across context switches when the
 * kernel enabled AVX. With the argument "net", raw Ethernet frames (EtherType
 * 88B5) go out through eth0 (virtio-net) and must come back unchanged from
 * the host's echo (X64_PROBE_NET). No libc. */
#if defined(__x86_64__)
typedef long word;
enum { SYS_read = 0, SYS_write = 1, SYS_open = 2, SYS_close = 3, SYS_lseek = 8, SYS_mmap = 9,
    SYS_mprotect = 10, SYS_rt_sigaction = 13, SYS_pipe = 22, SYS_sched_yield = 24, SYS_getpid = 39,
    SYS_clone = 56, SYS_fork = 57, SYS_exit = 60, SYS_wait4 = 61, SYS_uname = 63, SYS_unlink = 87,
    SYS_sched_setaffinity = 203, SYS_sched_getaffinity = 204, SYS_exit_group = 231, SYS_getcpu = 309,
    SYS_gettid = 186, SYS_tgkill = 234, SYS_ioctl = 16, SYS_socket = 41, SYS_sendto = 44, SYS_recvfrom = 45,
    SYS_bind = 49, SYS_setsockopt = 54 };
#define ARCH "64"
#define SIGINFO_ADDR 16
static word sc(word n, word a, word b, word c, word d, word e, word f)
{
    word r;
    register word r10 __asm__("r10") = d;
    register word r8 __asm__("r8") = e;
    register word r9 __asm__("r9") = f;
    __asm__ volatile("syscall" : "=a"(r) : "a"(n), "D"(a), "S"(b), "d"(c), "r"(r10), "r"(r8), "r"(r9) : "rcx", "r11", "memory", "cc");
    return r;
}
__asm__(".text\n.global signal_return\nsignal_return:\nmov $15,%eax\nsyscall\nud2\n"
    /* spawn(fn, arg, stack_top, flags): the child pops fn/arg off its stack. */
    ".global spawn\nspawn:\nsub $16,%rdx\nmov %rdi,(%rdx)\nmov %rsi,8(%rdx)\nmov %rdx,%rsi\nmov %rcx,%rdi\n"
    "xor %edx,%edx\nxor %r10d,%r10d\nxor %r8d,%r8d\nmov $56,%eax\nsyscall\ntest %rax,%rax\njnz 1f\n"
    "pop %rax\npop %rdi\ncall *%rax\nxor %edi,%edi\nmov $60,%eax\nsyscall\nud2\n1:\nret\n"
    ".global _start\n_start:\nmov %rsp,%rdi\nand $-16,%rsp\ncall entry\nud2\n");
static word *mapping(word length, int prot)
{
    return (word *)sc(SYS_mmap, 0, length, prot, 0x22, -1, 0);
}
/* MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED over an existing page */
static word remap(word address)
{
    return sc(SYS_mmap, address, 4096, 3, 0x32, -1, 0);
}
#else
typedef int word;
enum { SYS_exit = 1, SYS_fork = 2, SYS_read = 3, SYS_write = 4, SYS_open = 5, SYS_close = 6,
    SYS_unlink = 10, SYS_lseek = 19, SYS_getpid = 20, SYS_pipe = 42, SYS_old_mmap = 90, SYS_wait4 = 114,
    SYS_clone = 120, SYS_uname = 122, SYS_mprotect = 125, SYS_sched_yield = 158, SYS_rt_sigaction = 174,
    SYS_sched_setaffinity = 241, SYS_sched_getaffinity = 242, SYS_exit_group = 252, SYS_getcpu = 318,
    SYS_gettid = 224, SYS_tgkill = 270, SYS_ioctl = 54, SYS_socket = 359, SYS_bind = 361, SYS_setsockopt = 366,
    SYS_sendto = 369, SYS_recvfrom = 371 };
#define ARCH "32"
#define SIGINFO_ADDR 12
static word sc(word n, word a, word b, word c, word d, word e, word f)
{
    word r;
    (void)f;
    __asm__ volatile("int $0x80" : "=a"(r) : "a"(n), "b"(a), "c"(b), "d"(c), "S"(d), "D"(e) : "memory", "cc");
    return r;
}
__asm__(".text\n.global signal_return\nsignal_return:\nmov $173,%eax\nint $0x80\nud2\n"
    ".global spawn\nspawn:\npush %ebx\npush %esi\npush %edi\nmov 24(%esp),%ecx\nsub $8,%ecx\n"
    "mov 16(%esp),%eax\nmov %eax,(%ecx)\nmov 20(%esp),%eax\nmov %eax,4(%ecx)\nmov 28(%esp),%ebx\n"
    "xor %edx,%edx\nxor %esi,%esi\nxor %edi,%edi\nmov $120,%eax\nint $0x80\ntest %eax,%eax\njnz 1f\n"
    "pop %eax\npop %edx\npush %edx\ncall *%eax\nxor %ebx,%ebx\nmov $1,%eax\nint $0x80\nud2\n"
    "1:\npop %edi\npop %esi\npop %ebx\nret\n"
    ".global _start\n_start:\nmov %esp,%eax\nand $-16,%esp\nsub $12,%esp\npush %eax\ncall entry\nud2\n");
/* old_mmap takes its six arguments from memory. */
static word *mapping(word length, int prot)
{
    word args[6] = {0, length, prot, 0x22, -1, 0};
    return (word *)sc(SYS_old_mmap, (word)args, 0, 0, 0, 0, 0);
}
static word remap(word address)
{
    word args[6] = {address, 4096, 3, 0x32, -1, 0};
    return sc(SYS_old_mmap, (word)args, 0, 0, 0, 0, 0);
}
#endif
#define S(n, a, b, c) sc(n, (word)(a), (word)(b), (word)(c), 0, 0, 0)

void *memset(void *d, int v, unsigned long n) { unsigned char *p = d; while(n--) *p++ = (unsigned char)v; return d; }
void *memcpy(void *d, const void *s, unsigned long n) { unsigned char *p = d; const unsigned char *q = s; while(n--) *p++ = *q++; return d; }
extern void signal_return(void);
extern word spawn(void (*fn)(word), word arg, void *stack_top, word flags);

static int length(const char *s) { int n = 0; while(s[n]) n++; return n; }
static void out(const char *s) { S(SYS_write, 1, s, length(s)); }
static void number(unsigned long n) { char b[24]; int i = 23; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); out(b + i); }
static void die(const char *s) { out("X64_PROBE_FAIL arch=" ARCH " "); out(s); out("\n"); S(SYS_exit_group, 1, 0, 0); for(;;); }
static word check(word n, const char *s) { if(n < 0 && n > -4096) die(s); return n; }
static int same(const char *a, const char *b) { while(*a && *a == *b) { a++; b++; } return *a == *b; }

static volatile word fault_address;
static volatile word *protected_page;
static void segv(int sig, void *info, void *context)
{
    (void)sig; (void)context;
    fault_address = *(word *)((char *)info + SIGINFO_ADDR);
    check(S(SYS_mprotect, protected_page, 4096, 3), "mprotect restore");
}

#define THREADS 8
#define ITERATIONS 20000
static unsigned cpus;
static volatile unsigned counter, finished, bound[THREADS];
/* TLB shootdown: every worker keeps a translation of `watched` live on its
 * CPU; the main thread then replaces the page with MAP_FIXED. Once mmap has
 * returned, no CPU may still read the old frame. */
static volatile word *watched;
static volatile unsigned readers, remapped, stale;
static char stacks[THREADS][16384] __attribute__((aligned(16)));
static void worker(word id)
{
    unsigned long mask = 1ul << (id % cpus);
    unsigned cpu = ~0u;
    check(S(SYS_sched_setaffinity, 0, sizeof(mask), &mask), "thread affinity");
    check(S(SYS_getcpu, &cpu, 0, 0), "getcpu");
    if(cpu != id % cpus) die("thread migration");
    bound[id] = cpu + 1;
    for(int i = 0; i < ITERATIONS; i++)
    {
        __asm__ volatile("lock addl $1,%0" : "+m"(counter) :: "memory", "cc");
        if((i & 1023) == 0) S(SYS_sched_yield, 0, 0, 0);
    }
    word seen = 0;
    __asm__ volatile("lock addl $1,%0" : "+m"(readers) :: "memory", "cc");
    while(!remapped) seen += *watched;
    if(*watched != 2) __asm__ volatile("lock addl $1,%0" : "+m"(stale) :: "memory", "cc");
    (void)seen;
    __asm__ volatile("lock addl $1,%0" : "+m"(finished) :: "memory", "cc");
}

/* Multicore matrix (X64_PROBE_XC). */
#define MIGRATIONS 24
#define SIGNALS 16
#define SMC_ROUNDS 64
static volatile word tids[THREADS];
static volatile unsigned signalled[THREADS], moved[THREADS], xc_done, xc_ready;
static volatile unsigned smc_sequence, smc_ack, smc_bad;
/* not the first phase's stacks: an exiting thread still returns through its own */
static char xc_stacks[THREADS][16384] __attribute__((aligned(16)));
static unsigned char *smc_code;
static void rt_signal(int sig, void *info, void *context)
{
    (void)sig; (void)info; (void)context;
    word tid = S(SYS_gettid, 0, 0, 0);
    for(unsigned id = 0; id < THREADS; id++)
        if(tids[id] == tid) __asm__ volatile("lock addl $1,%0" : "+m"(signalled[id]) :: "memory", "cc");
}
static void set_cpu(unsigned cpu)
{
    unsigned long mask = 1ul << cpu;
    check(S(SYS_sched_setaffinity, 0, sizeof(mask), &mask), "affinity");
}
static void xc_worker(word id)
{
    tids[id] = S(SYS_gettid, 0, 0, 0);
    /* migration: every step lands on the requested CPU */
    for(unsigned k = 0; k < MIGRATIONS; k++)
    {
        unsigned target = (id + k) % cpus, cpu = ~0u;
        set_cpu(target);
        check(S(SYS_getcpu, &cpu, 0, 0), "getcpu");
        if(cpu != target) die("migration");
        __asm__ volatile("lock addl $1,%0" : "+m"(moved[id]) :: "memory", "cc");
    }
    set_cpu(id % cpus);
    __asm__ volatile("lock addl $1,%0" : "+m"(xc_ready) :: "memory", "cc");
    /* signals from the main thread on another CPU */
    while(signalled[id] < SIGNALS) S(SYS_sched_yield, 0, 0, 0);
    /* the last worker executes code that the main thread rewrites */
    if(id == cpus - 1)
    {
        for(unsigned round = 1; round <= SMC_ROUNDS; round++)
        {
            while(smc_sequence != round) S(SYS_sched_yield, 0, 0, 0);
            /* serializing instruction before executing the modified code */
            unsigned a = 0, b, c = 0, d;
            __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d) :: "memory");
            unsigned value = ((unsigned (*)(void))smc_code)();
            if(value != round * 3 + 1) __asm__ volatile("lock addl $1,%0" : "+m"(smc_bad) :: "memory", "cc");
            smc_ack = round;
        }
    }
    __asm__ volatile("lock addl $1,%0" : "+m"(xc_done) :: "memory", "cc");
}
static word read_file(const char *path, char *buffer, word size)
{
    word fd = check(S(SYS_open, path, 0, 0), path);
    word n = check(S(SYS_read, fd, buffer, size - 1), path);
    S(SYS_close, fd, 0, 0);
    buffer[n] = 0;
    return n;
}
static unsigned parse(const char *s) { unsigned n = 0; while(*s >= '0' && *s <= '9') n = n * 10 + (unsigned)(*s++ - '0'); return n; }
static void matrix(void)
{
    /* topology: one package, a distinct core per CPU, no sibling threads */
    char path[64], text[64];
    unsigned cores_seen = 0;
    for(unsigned cpu = 0; cpu < cpus; cpu++)
    {
        const char *parts[3] = {"physical_package_id", "core_id", "thread_siblings_list"};
        unsigned values[3];
        for(int k = 0; k < 3; k++)
        {
            const char *prefix = "/sys/devices/system/cpu/cpu";
            int n = 0;
            for(const char *q = prefix; *q; q++) path[n++] = *q;
            char digits[8]; int d = 0; unsigned v = cpu; do { digits[d++] = '0' + v % 10; v /= 10; } while(v);
            while(d) path[n++] = digits[--d];
            for(const char *q = "/topology/"; *q; q++) path[n++] = *q;
            for(const char *q = parts[k]; *q; q++) path[n++] = *q;
            path[n] = 0;
            read_file(path, text, sizeof(text));
            values[k] = parse(text);
        }
        if(values[0] != 0) die("package id");
        if(values[2] != cpu) die("thread siblings");
        if(cores_seen >> values[1] & 1) die("core id");
        cores_seen |= 1u << values[1];
    }
    /* O_DIRECT from the IDE disk (the probe tarball: ustar magic) */
    static char direct[8192] __attribute__((aligned(4096)));
    word disk = check(S(SYS_open, "/dev/sda", 040000, 0), "open O_DIRECT");
    if(check(S(SYS_read, disk, direct, 4096), "direct read") != 4096) die("direct read length");
    S(SYS_close, disk, 0, 0);
    if(!(direct[257] == 'u' && direct[258] == 's' && direct[259] == 't' && direct[260] == 'a' && direct[261] == 'r')) die("direct read contents");

    /* mov eax, imm32; mov ecx, 100; 1: dec ecx; jnz 1b; ret (hot enough for a JIT) */
    smc_code = (unsigned char *)mapping(4096, 7);
    if((unsigned long)smc_code >= (unsigned long)-4096) die("mmap exec");
    static const unsigned char body[] = {0xB8, 0, 0, 0, 0, 0xB9, 100, 0, 0, 0, 0xFF, 0xC9, 0x75, 0xFC, 0xC3};
    memcpy(smc_code, body, sizeof(body));
    struct { void *handler; unsigned long flags; void *restorer; unsigned long mask[2]; } action =
        {(void *)rt_signal, 0x04000004, (void *)signal_return, {0, 0}};
    /* a real-time signal: repeated sends queue instead of coalescing */
    check(sc(SYS_rt_sigaction, 40, (word)&action, 0, 8, 0, 0), "sigaction rt");
    set_cpu(0);
    for(unsigned id = 0; id < cpus; id++)
        check(spawn(xc_worker, id, xc_stacks[id] + sizeof(xc_stacks[id]), 0x00050F00), "clone xc");
    while(xc_ready != cpus) S(SYS_sched_yield, 0, 0, 0);
    word tgid = S(SYS_getpid, 0, 0, 0);
    for(unsigned n = 0; n < SIGNALS; n++)
        for(unsigned id = 0; id < cpus; id++)
            check(sc(SYS_tgkill, tgid, tids[id], 40, 0, 0, 0), "tgkill");
    for(unsigned round = 1; round <= SMC_ROUNDS; round++)
    {
        unsigned value = round * 3 + 1;
        memcpy(smc_code + 1, &value, 4);
        __asm__ volatile("" ::: "memory");
        smc_sequence = round;
        while(smc_ack != round) S(SYS_sched_yield, 0, 0, 0);
    }
    while(xc_done != cpus) S(SYS_sched_yield, 0, 0, 0);
    unsigned migrated = 0, signals = 0;
    for(unsigned id = 0; id < cpus; id++) { migrated += moved[id]; signals += signalled[id]; }
    if(migrated != cpus * MIGRATIONS) die("migration count");
    if(signals != cpus * SIGNALS) die("signal count");
    if(smc_bad) die("cross-modified code");
    out("X64_PROBE_XC arch=" ARCH " packages=1 cores="); number(cpus); out(" threads_per_core=1 migrations="); number(migrated);
    out(" signals="); number(signals); out(" smc_rounds="); number(SMC_ROUNDS); out(" direct_io=1\n");
}

/* YMM state across the kernel's context switches (X64_PROBE_YMM,
 * docs/simd-xsave-plan.md 11.3): when the kernel enabled AVX
 * (CPUID.1:ECX.OSXSAVE and AVX, XCR0 bits 1 and 2), twice as many threads as
 * CPUs each hold a fingerprint in every YMM register (16 in 64-bit mode, 8 in
 * compatibility mode) across a system call, sched_yield, a migration to
 * another CPU, a signal whose handler overwrites them all, and a spin during
 * which the other threads preempt it. Every step loads the registers, makes
 * the call and spins in one asm statement, then stores them for the check. */
#if defined(__x86_64__)
#define YMM_REGS 16
#define YMM_ASM(load, store) \
    load(0) load(1) load(2) load(3) load(4) load(5) load(6) load(7) load(8) load(9) load(10) load(11) load(12) load(13) load(14) load(15) \
    "syscall\n" "1: dec %[spin]\n" "jnz 1b\n" \
    store(0) store(1) store(2) store(3) store(4) store(5) store(6) store(7) store(8) store(9) store(10) store(11) store(12) store(13) store(14) store(15)
#define YMM_LOAD(n) "vmovdqu " #n "*32(%[in]),%%ymm" #n "\n"
#define YMM_STORE(n) "vmovdqu %%ymm" #n "," #n "*32(%[out])\n"
static word ymm_step(const void *in, void *out, word n, word a, word b, word c, word spin)
{
    word r;
    __asm__ volatile(YMM_ASM(YMM_LOAD, YMM_STORE)
        : "=a"(r), [spin] "+r"(spin) : "a"(n), "D"(a), "S"(b), "d"(c), [in] "r"(in), [out] "r"(out)
        : "rcx", "r11", "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
          "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15");
    return r;
}
/* (AVX, not AVX2: VCMPPS with the always-true predicate, VXORPS) */
#define YMM_CLOBBER "vcmpps $15,%%ymm0,%%ymm0,%%ymm0\nvcmpps $15,%%ymm8,%%ymm8,%%ymm8\nvcmpps $15,%%ymm15,%%ymm15,%%ymm15\n" \
    "vxorps %%ymm3,%%ymm3,%%ymm3\nvxorps %%ymm12,%%ymm12,%%ymm12\n"
#else
#define YMM_REGS 8
#define YMM_ASM(load, store) \
    load(0) load(1) load(2) load(3) load(4) load(5) load(6) load(7) \
    "int $0x80\n" "1: decl %[spin]\n" "jnz 1b\n" \
    store(0) store(1) store(2) store(3) store(4) store(5) store(6) store(7)
#define YMM_LOAD(n) "vmovdqu " #n "*32(%[in]),%%ymm" #n "\n"
#define YMM_STORE(n) "vmovdqu %%ymm" #n "," #n "*32(%[out])\n"
static word ymm_step(const void *in, void *out, word n, word a, word b, word c, word spin)
{
    word r;
    __asm__ volatile(YMM_ASM(YMM_LOAD, YMM_STORE)
        : "=a"(r), [spin] "+m"(spin) : "a"(n), "b"(a), "c"(b), "d"(c), [in] "S"(in), [out] "D"(out)
        : "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7");
    return r;
}
#define YMM_CLOBBER "vcmpps $15,%%ymm0,%%ymm0,%%ymm0\nvcmpps $15,%%ymm5,%%ymm5,%%ymm5\nvxorps %%ymm3,%%ymm3,%%ymm3\n"
#endif
#define YMM_THREADS (2 * THREADS)
#define YMM_ROUNDS 8
#define YMM_SPIN 100000
static unsigned char ymm_in[YMM_THREADS][YMM_REGS * 32] __attribute__((aligned(32)));
static unsigned char ymm_out[YMM_THREADS][YMM_REGS * 32] __attribute__((aligned(32)));
static volatile unsigned ymm_bad, ymm_steps, ymm_done, ymm_handled;
static volatile word ymm_tids[YMM_THREADS];
static char ymm_stacks[YMM_THREADS][16384] __attribute__((aligned(16)));
static unsigned ymm_threads;
static int avx_enabled(void)
{
    unsigned a = 1, b, c = 0, d;
    __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d));
    if(!(c >> 27 & 1) || !(c >> 28 & 1)) return 0;
    unsigned lo, hi;
    __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
    return (lo & 6) == 6;
}
static void ymm_signal(int sig, void *info, void *context)
{
    (void)sig; (void)info; (void)context;
    __asm__ volatile(YMM_CLOBBER ::: "memory");
    __asm__ volatile("lock addl $1,%0" : "+m"(ymm_handled) :: "memory", "cc");
}
static void ymm_worker(word id)
{
    ymm_tids[id] = S(SYS_gettid, 0, 0, 0);
    word tgid = S(SYS_getpid, 0, 0, 0);
    for(unsigned round = 0; round < YMM_ROUNDS; round++)
    {
        for(unsigned kind = 0; kind < 5; kind++)
        {
            unsigned char *in = ymm_in[id], *out = ymm_out[id];
            for(int i = 0; i < YMM_REGS * 32; i++) { in[i] = (unsigned char)(id * 37 + round * 11 + kind * 5 + i * 3 + (i >> 5)); out[i] = 0; }
            unsigned long mask = 1ul << ((id + round + kind) % cpus);
            switch(kind)
            {
            case 0: ymm_step(in, out, SYS_getpid, 0, 0, 0, 1); break;
            case 1: ymm_step(in, out, SYS_sched_yield, 0, 0, 0, 1); break;
            case 2: check(ymm_step(in, out, SYS_sched_setaffinity, 0, sizeof(mask), (word)&mask, 1), "ymm migration"); break;
            case 3: check(ymm_step(in, out, SYS_tgkill, tgid, ymm_tids[id], 41, 1), "ymm tgkill"); break;
            default: ymm_step(in, out, SYS_getpid, 0, 0, 0, YMM_SPIN); break;
            }
            for(int i = 0; i < YMM_REGS * 32; i++)
                if(out[i] != in[i]) { __asm__ volatile("lock addl $1,%0" : "+m"(ymm_bad) :: "memory", "cc"); break; }
            __asm__ volatile("lock addl $1,%0" : "+m"(ymm_steps) :: "memory", "cc");
        }
    }
    __asm__ volatile("lock addl $1,%0" : "+m"(ymm_done) :: "memory", "cc");
}
static void ymm_matrix(void)
{
    if(!avx_enabled()) { out("X64_PROBE_YMM arch=" ARCH " avx=0\n"); return; }
    struct { void *handler; unsigned long flags; void *restorer; unsigned long mask[2]; } action =
        {(void *)ymm_signal, 0x04000004, (void *)signal_return, {0, 0}};
    check(sc(SYS_rt_sigaction, 41, (word)&action, 0, 8, 0, 0), "sigaction ymm");
    ymm_threads = 2 * cpus;
    for(unsigned id = 0; id < ymm_threads; id++)
        check(spawn(ymm_worker, id, ymm_stacks[id] + sizeof(ymm_stacks[id]), 0x00050F00), "clone ymm");
    while(ymm_done != ymm_threads) S(SYS_sched_yield, 0, 0, 0);
    if(ymm_handled != ymm_threads * YMM_ROUNDS) die("ymm signals");
    out("X64_PROBE_YMM arch=" ARCH " avx=1 registers="); number(YMM_REGS); out(" threads="); number(ymm_threads);
    out(" steps="); number(ymm_steps); out(" signals="); number(ymm_handled); out(" bad="); number(ymm_bad); out("\n");
    if(ymm_bad) die("ymm fingerprint");
}

/* AF_PACKET socket on eth0: send frames, receive the host's echoes */
#define NET_FRAMES 16
static void network(void)
{
    struct { unsigned short family, protocol; int ifindex; unsigned short hatype; unsigned char pkttype, halen, addr[8]; } address = {0};
    word fd = check(sc(SYS_socket, 17 /* AF_PACKET */, 3 /* SOCK_RAW */, 0xB588 /* htons(0x88B5) */, 0, 0, 0), "packet socket");
    char request[40] = {'e', 't', 'h', '0', 0};
    check(S(SYS_ioctl, fd, 0x8933 /* SIOCGIFINDEX */, request), "eth0 index");
    address.family = 17; address.protocol = 0xB588; address.ifindex = *(int *)(request + 16); address.halen = 6;
    for(int i = 0; i < 6; i++) address.addr[i] = 255;
    check(sc(SYS_bind, fd, (word)&address, sizeof(address), 0, 0, 0), "bind packet socket");
    struct { long seconds, microseconds; } timeout = {10, 0};
    check(sc(SYS_setsockopt, fd, 1 /* SOL_SOCKET */, 20 /* SO_RCVTIMEO */, (word)&timeout, sizeof(timeout), 0), "receive timeout");
    for(unsigned round = 0; round < NET_FRAMES; round++)
    {
        unsigned char frame[96] = {0}, received[160];
        for(int i = 0; i < 6; i++) frame[i] = 255;
        frame[6] = 2; frame[11] = 1; frame[12] = 0x88; frame[13] = 0xB5;
        for(unsigned i = 14; i < sizeof(frame); i++) frame[i] = (unsigned char)(i * 7 + round * 13 + ARCH[0]);
        /* bound socket: no destination (the i386 wrapper passes five arguments) */
        if(check(sc(SYS_sendto, fd, (word)frame, sizeof(frame), 0, 0, 0), "send frame") != sizeof(frame)) die("short frame");
        for(;;)
        {
            word n = sc(SYS_recvfrom, fd, (word)received, sizeof(received), 0, 0, 0);
            if(n == -4) continue; /* EINTR */
            if(check(n, "receive frame") < (word)sizeof(frame)) die("short echo");
            if(received[11] != 2) continue; /* our own transmitted frame */
            for(unsigned i = 14; i < sizeof(frame); i++) if(received[i] != frame[i]) die("echo payload");
            break;
        }
    }
    S(SYS_close, fd, 0, 0);
    out("X64_PROBE_NET arch=" ARCH " frames="); number(NET_FRAMES); out("\n");
}

/* The auxiliary vector follows argv and envp on the initial stack. */
static word auxv(word *stack, word type)
{
    word *p = stack + 1 + stack[0] + 1;
    while(*p) p++;
    for(p++; p[0]; p += 2) if(p[0] == type) return p[1];
    return 0;
}

#if defined(__x86_64__)
/* "memtest <MiB> <first extended PFN>" (extended RAM): map that much anonymous memory
 * in 64 MiB pieces, write two words into every page (one of them derived
 * from its address), check them all, and count through /proc/self/pagemap
 * the pages the kernel placed at or above the given frame (extended RAM). */
static void memtest(const char *size, const char *first)
{
    unsigned long mib = 0, extended = 0;
    for(const char *c = size; *c; c++) mib = mib * 10 + (unsigned long)(*c - '0');
    for(const char *c = first; *c; c++) extended = extended * 10 + (unsigned long)(*c - '0');
    enum { PIECE = 64 << 20 };
    static unsigned char *pieces[4096];
    unsigned long count = mib / 64, errors = 0, above = 0, pages = 0;
    if(count > 4096) die("memtest size");
    for(unsigned long p = 0; p < count; p++)
    {
        pieces[p] = (unsigned char *)mapping(PIECE, 3);
        if((unsigned long)pieces[p] >= (unsigned long)-4096) die("memtest mmap");
        for(unsigned long offset = 0; offset < PIECE; offset += 4096)
        {
            word *w = (word *)(pieces[p] + offset);
            w[0] = (word)(pieces[p] + offset) ^ 0x5A5A5A5A5A5A5A5A;
            w[511] = (word)(p * PIECE + offset);
        }
    }
    static unsigned long long frames[512];
    word map = check(S(SYS_open, "/proc/self/pagemap", 0, 0), "open pagemap");
    for(unsigned long p = 0; p < count; p++)
    {
        for(unsigned long offset = 0; offset < PIECE; offset += 4096)
        {
            word *w = (word *)(pieces[p] + offset);
            if(w[0] != ((word)(pieces[p] + offset) ^ 0x5A5A5A5A5A5A5A5A) || w[511] != (word)(p * PIECE + offset)) errors++;
        }
        for(unsigned long first_page = 0; first_page < PIECE / 4096; first_page += 512)
        {
            check(S(SYS_lseek, map, ((unsigned long)pieces[p] / 4096 + first_page) * 8, 0), "pagemap seek");
            for(word done = 0, n; done < (word)sizeof(frames); done += n)
                if((n = check(S(SYS_read, map, (char *)frames + done, sizeof(frames) - done), "pagemap read")) == 0) die("pagemap eof");
            for(int i = 0; i < 512; i++)
            {
                if(!(frames[i] >> 63)) die("memtest page not present");
                if((frames[i] & ((1ull << 55) - 1)) >= extended) above++;
                pages++;
            }
        }
    }
    S(SYS_close, map, 0, 0);
    out("X64_MEMTEST mib="); number(mib); out(" pages="); number(pages); out(" errors="); number(errors);
    out(" extended_pages="); number(above); out("\n");
    if(errors) die("memtest contents");
    S(SYS_exit_group, 0, 0, 0);
}
#endif

void entry(word *stack)
{
#if defined(__x86_64__)
    if(stack[0] >= 4 && same((const char *)stack[2], "memtest")) memtest((const char *)stack[3], (const char *)stack[4]);
#endif
    out("X64_PROBE_START arch=" ARCH "\n");
    const char *entry_path = "syscall";
#if !defined(__x86_64__)
    /* Compatibility processes normally enter through the vDSO's
     * __kernel_vsyscall (SYSENTER on Intel), then return via SYSRETL/IRET. */
    word vsyscall = auxv(stack, 32 /* AT_SYSINFO */);
    if(!vsyscall) die("AT_SYSINFO");
    word via_vdso, via_int80 = S(SYS_getpid, 0, 0, 0);
    __asm__ volatile("call *%1" : "=a"(via_vdso) : "r"(vsyscall), "a"(SYS_getpid) : "memory", "cc", "ecx", "edx");
    if(via_vdso != via_int80) die("vDSO getpid");
    entry_path = "vdso";
#else
    if(!auxv(stack, 33 /* AT_SYSINFO_EHDR */)) die("AT_SYSINFO_EHDR");
#endif
    struct { char sysname[65], nodename[65], release[65], version[65], machine[65], domain[65]; } names;
    check(S(SYS_uname, &names, 0, 0), "uname");
    if(!same(names.machine, "x86_64")) die("uname machine");
    if(sizeof(void *) * 8 != (ARCH[0] == '6' ? 64 : 32)) die("pointer width");

    unsigned long affinity[16] = {0};
    word bytes = check(S(SYS_sched_getaffinity, 0, sizeof(affinity), affinity), "getaffinity");
    for(word i = 0; i < bytes / (word)sizeof(affinity[0]); i++)
        for(unsigned long m = affinity[i]; m; m &= m - 1) cpus++;
    if(cpus == 0 || cpus > THREADS) die("cpu count");

    /* mmap, then write to a read-only page: the handler sees the exact page
     * address, restores write access, and the faulting store is retried. */
    word *pages = mapping(8192, 3);
    if((unsigned long)pages >= (unsigned long)-4096) die("mmap");
    for(int i = 0; i < 4096 / (int)sizeof(word); i++) pages[i] = (word)i * 0x01010101;
    protected_page = (word *)((char *)pages + 4096);
    struct { void *handler; unsigned long flags; void *restorer; unsigned long mask[2]; } action =
        {(void *)segv, 0x04000004, (void *)signal_return, {0, 0}};
    check(sc(SYS_rt_sigaction, 11, (word)&action, 0, 8, 0, 0), "sigaction");
    check(S(SYS_mprotect, protected_page, 4096, 1), "mprotect");
    protected_page[3] = 0x5A5A;
    if(fault_address != (word)protected_page + 3 * (word)sizeof(word) || protected_page[3] != 0x5A5A) die("SIGSEGV round trip");
    if(pages[5] != 5 * 0x01010101) die("mapping contents");

    int fds[2];
    check(S(SYS_pipe, fds, 0, 0), "pipe");
    word child = check(S(SYS_fork, 0, 0, 0), "fork");
    if(child == 0)
    {
        word pid = S(SYS_getpid, 0, 0, 0);
        S(SYS_write, fds[1], &pid, sizeof(pid));
        S(SYS_exit, 7, 0, 0);
    }
    word reported = 0;
    if(check(S(SYS_read, fds[0], &reported, sizeof(reported)), "pipe read") != sizeof(reported) || reported != child) die("pipe pid");
    int status = 0;
    if(check(sc(SYS_wait4, child, (word)&status, 0, 0, 0, 0), "wait4") != child || status != 7 << 8) die("child status");

    watched = mapping(4096, 3);
    if((unsigned long)watched >= (unsigned long)-4096) die("mmap watched");
    *watched = 1;
    /* CLONE_VM|FS|FILES|SIGHAND|THREAD|SYSVSEM */
    for(unsigned id = 0; id < cpus; id++)
        check(spawn(worker, id, stacks[id] + sizeof(stacks[id]), 0x00050F00), "clone");
    while(readers != cpus) S(SYS_sched_yield, 0, 0, 0);
    if(remap((word)watched) != (word)watched) die("mmap fixed");
    *watched = 2;
    remapped = 1;
    while(finished != cpus) S(SYS_sched_yield, 0, 0, 0);
    if(stale) die("stale TLB entry after remap");
    if(counter != cpus * ITERATIONS) die("locked counter");
    for(unsigned id = 0; id < cpus; id++) if(bound[id] != id + 1) die("thread binding");

    static char data[4096], back[4096];
    for(int i = 0; i < 4096; i++) data[i] = (char)(i * 7 + 3);
    word fd = check(S(SYS_open, "/tmp/x64-probe", 0102, 0644), "open");
    if(check(S(SYS_write, fd, data, sizeof(data)), "file write") != sizeof(data)) die("short write");
    check(S(SYS_lseek, fd, 0, 0), "lseek");
    if(check(S(SYS_read, fd, back, sizeof(back)), "file read") != sizeof(back)) die("short read");
    for(int i = 0; i < 4096; i++) if(back[i] != data[i]) die("file contents");
    S(SYS_close, fd, 0, 0);
    check(S(SYS_unlink, "/tmp/x64-probe", 0, 0), "unlink");

    /* Physical placement: count touched pages whose frame is at or above
     * 4 GiB (PFN 0x100000), with contents verified through the mapping. */
    static unsigned long long frames[4096];
    unsigned char *block = (unsigned char *)mapping(16 << 20, 3);
    if((unsigned long)block >= (unsigned long)-4096) die("mmap block");
    for(int i = 0; i < 4096; i++) block[i * 4096 + (i & 4095)] = (unsigned char)(i * 13 + 1);
    word map = check(S(SYS_open, "/proc/self/pagemap", 0, 0), "open pagemap");
#if defined(__x86_64__)
    check(S(SYS_lseek, map, (unsigned long)block / 4096 * 8, 0), "pagemap seek");
#else
    /* _llseek: the 32-bit offset of a user page index always fits */
    long long position = 0;
    check(sc(140, map, 0, (word)((unsigned long)block / 4096 * 8), (word)&position, 0, 0), "pagemap seek");
#endif
    for(word done = 0, n; done < (word)sizeof(frames); done += n)
        if((n = check(S(SYS_read, map, (char *)frames + done, sizeof(frames) - done), "pagemap read")) == 0) die("pagemap eof");
    S(SYS_close, map, 0, 0);
    unsigned high_pages = 0;
    for(int i = 0; i < 4096; i++)
    {
        if(!(frames[i] >> 63)) die("page not present");
        if((frames[i] & ((1ull << 55) - 1)) >= 0x100000) high_pages++;
        if(block[i * 4096 + (i & 4095)] != (unsigned char)(i * 13 + 1)) die("block contents");
    }

    out("X64_PROBE_OK arch=" ARCH " cpus="); number(cpus);
    out(" threads="); number(cpus); out(" counter="); number(counter);
    out(" cpu_checks="); for(unsigned id = 0; id < cpus; id++) { if(id) out(","); number(bound[id] - 1); }
    out(" fault=page child=7 tlb_stale="); number(stale); out(" entry="); out(entry_path); out(" high_pages="); number(high_pages); out("\n");
    matrix();
    ymm_matrix();
    if(stack[0] >= 2 && same((const char *)stack[2], "net")) network();
    S(SYS_exit_group, 0, 0, 0);
    for(;;);
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/x64/mode_ledger.mjs                                                                0000755 0000000 0000000 00000003431 00000000000 014434  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The mode ledger (docs/jit-unification-plan.md P0.6) with the x64 page tier:
// on from the machine's construction, its sum is the retired count
// (cross-phase rule 3), and a multiboot guest's way into long mode lands in
// the rows of its modes: the 32-bit setup interpreted, the far jump that
// leaves compatibility mode, then a 64-bit loop that the page tier runs
// natively and in which it steps CPUID.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {mode_ledger, mode_ledger_total} from "../../tools/bench/jit_stats.mjs";

const ITERATIONS = 20000;
const directory = assemble("mode-ledger", long_mode_guest(`
mov r8d,${ITERATIONS}
.loop:
xor eax,eax
cpuid
add r9,rax
dec r8d
jnz .loop
`));
let ledger, retired;
await actual(directory, {length: 4, timeout: 60000,
    options: {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true, jit_switches: {mode_ledger: 1}},
    inspect: emulator => {
        const e = emulator.v86.cpu.wm.exports;
        ledger = mode_ledger(e);
        retired = e.core_statistics_get(0, 0);
    }});
const row = name => ledger[name] || {};
assert.equal(mode_ledger_total(ledger), retired, `the ledger accounts for every retired instruction: ${JSON.stringify(ledger)}`);
assert.ok(row("prot32.flat").interpreted > 0, `the 32-bit setup: ${JSON.stringify(ledger)}`);
assert.ok(row("compat32.flat").interpreted > 0, `the far jump from compatibility mode: ${JSON.stringify(ledger)}`);
assert.ok(row("long64").page_native > ITERATIONS && row("long64").page_step >= ITERATIONS / 2, `the 64-bit loop: ${JSON.stringify(ledger)}`);
console.log(`PASS: the mode ledger accounts for ${retired} retired instructions: ${JSON.stringify(ledger)}`);
                                                                                                                                                                                                                                       source/v64/tests/x64/multicore.asm                                                                  0000644 0000000 0000000 00000014522 00000000000 014160  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       bits 32
org 0x100000
%define CONTROL 0x380000
%define RECORDS 0x390000
%define LAPIC 0xFEE00000
%define HIGH 0xFFFF800000000000
%define VIRTUAL HIGH+0x40055000
%define ITERATIONS 512
%define IDT 0x370000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,end,end,start
start:
cli
cld
lgdt [gdtr]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x310000
mov al,255
out 0x21,al
out 0xA1,al
mov esi,trampoline
mov edi,0x8000
mov ecx,trampoline_end-trampoline
rep movsb
mov dword [CONTROL+8],-1
mov dword [CONTROL+12],-1
%ifdef REFERENCE
mov dword [CONTROL+28],1
%endif
xor ebx,ebx
.prepare:
mov ebp,ebx
shl ebp,16
add ebp,0x200000
lea eax,[ebp+0x1003]
mov [ebp],eax
mov [ebp+256*8],eax
mov [ebp+ebx*8+256*8],eax
lea eax,[ebp+0x2003]
mov [ebp+0x1000],eax
lea eax,[ebp+0x3003]
mov [ebp+0x1008],eax
lea edi,[ebp+0x2000]
mov eax,0x83
mov ecx,512
.pages:
stosd
mov dword [edi],0
add edi,4
add eax,0x200000
loop .pages
mov eax,ebx
shl eax,21
add eax,0x800083
mov [ebp+0x3000],eax
and eax,~4095
add eax,0x55000
lea edx,[ebx+0xA100]
mov [eax],edx
add eax,0x800000
lea edx,[ebx+0xB200]
mov [eax],edx
mov eax,ebx
shl eax,12
lea edx,[ebx+0xF500]
mov [eax+0x400000],edx
lea edx,[ebx+0x6500]
mov [eax+0x440000],edx
lea edx,[ebx+0x7500]
mov [eax+0x480000],edx
; PDPT[3] -> uncached 2 MiB page for the local APIC at its identity address
lea eax,[ebp+0x4003]
mov [ebp+0x1018],eax
mov dword [ebp+0x4000+0x1F7*8],0xFEE0009B
inc ebx
cmp ebx,4
jb .prepare
mov dword [LAPIC+0xF0],0x1FF
mov ebx,1
.start_ap:
mov eax,ebx
shl eax,24
mov [LAPIC+0x310],eax
mov dword [LAPIC+0x300],0xC500
mov dword [LAPIC+0x300],0x8500
mov dword [LAPIC+0x300],0x608
inc ebx
cmp ebx,4
jb .start_ap
xor ebx,ebx
jmp enter_long
bits 16
trampoline:
cli
mov edx,cr0
mov ax,cs
movzx esi,ax
lgdt [cs:trampoline_gdtr-trampoline]
mov eax,cr0
or eax,1
mov cr0,eax
jmp dword 8:ap_entry
trampoline_gdtr:
dw 31
dd gdt
trampoline_end:
bits 32
ap_entry:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov ebx,[LAPIC+0x20]
shr ebx,24
mov edi,ebx
shl edi,10
mov [RECORDS+edi],edx
mov [RECORDS+edi+4],esi
enter_long:
lea esp,[ebx+1]
shl esp,16
add esp,0x300000
mov eax,ebx
shl eax,16
add eax,0x200000
mov cr3,eax
mov eax,cr4
or eax,0x620
mov cr4,eax
mov ecx,0xC0000080
rdmsr
or eax,0x100
wrmsr
mov eax,cr0
and eax,~12
or eax,0x80010001
mov cr0,eax
jmp 24:long_entry
bits 64
long_entry:
mov r15d,ebx
mov rax,r15
shl rax,39
mov r14,HIGH
or r14,rax
mov rax,high_entry
add rax,r14
jmp rax
high_entry:
mov rbp,r15
shl rbp,10
add rbp,RECORDS
mov rdi,HIGH+CONTROL
mov rax,r15
shl rax,12
add eax,0x400000
mov edx,0xFFFF8000
mov ecx,0xC0000100
wrmsr
add eax,0x40000
inc ecx
wrmsr
add eax,0x40000
inc ecx
wrmsr
mov eax,r15d
or eax,0xAA000000
xor edx,edx
mov ecx,0xC0000103
wrmsr
mov r8,0xAABBCCDD00000000
add r8,r15
%assign n 8
%rep 8
mov rax,0xDADABABA00000000+n
add rax,r15
mov [rbp+64+(n-8)*16],rax
not rax
mov [rbp+72+(n-8)*16],rax
movdqu xmm%+n,[rbp+64+(n-8)*16]
%assign n n+1
%endrep
mov r9,VIRTUAL
mov eax,[r9]
mov [rbp+16],eax
mov rbx,r15
shl rbx,16
add rbx,0x203000
mov eax,r15d
shl eax,21
add eax,0x1000083
mov [rbx],eax ; leave this core's old TLB translation cached across snapshot
xor r12d,r12d
xor r13d,r13d
mov ecx,10000
.hot:
add r12,7
xor r13,r12
dec ecx
jnz .hot
mov r10d,ITERATIONS
call contend
mov [rbp+8],r14
mov [rbp+24],r8
lock inc dword [rdi+16]
.barrier:
cmp dword [rdi+28],0
je .host_release
cmp dword [rdi+16],4
jne .barrier
mov dword [rdi+20],1
.host_release:
cmp dword [rdi+20],0
je .barrier
; State below must have survived many switches and optional snapshot restore.
mov rax,0xAABBCCDD00000000
add rax,r15
cmp r8,rax
jne fail_gpr
cmp r12,70000
jne fail_gpr
mov eax,[r9]
mov [rbp+32],eax
cmp eax,[rbp+16]
jne fail_tlb
invlpg [r9]
mov eax,[r9]
mov [rbp+36],eax
lea edx,[r15d+0xB200]
cmp eax,edx
jne fail_tlb
mov eax,[fs:0]
lea edx,[r15d+0xF500]
cmp eax,edx
jne fail_msr
mov eax,[gs:0]
lea edx,[r15d+0x6500]
cmp eax,edx
jne fail_msr
swapgs
mov eax,[gs:0]
lea edx,[r15d+0x7500]
cmp eax,edx
jne fail_msr
swapgs
rdtscp
mov eax,r15d
or eax,0xAA000000
cmp eax,ecx
jne fail_msr
mov [rbp+40],ecx
%assign n 8
%rep 8
movdqu [rbp+256+(n-8)*16],xmm%+n
mov rax,[rbp+256+(n-8)*16]
cmp rax,[rbp+64+(n-8)*16]
jne fail_xmm
mov rax,[rbp+264+(n-8)*16]
cmp rax,[rbp+72+(n-8)*16]
jne fail_xmm
%assign n n+1
%endrep
mov r10d,ITERATIONS
call contend
mov dword [rbp+48],0xD064
lock inc dword [rdi+24]
; Long-mode IPI phase: directed fixed IPIs, NMIs and an all-excluding-self
; broadcast reach APs halted with IF=1 through a 64-bit IDT.
mov esi,LAPIC
test r15d,r15d
jnz .ap_ipi
.wait_done:
cmp dword [rdi+24],4
jne .wait_done
mov rax,ipi_handler
mov rbx,IDT+0x41*16
call set_gate
mov rax,nmi_handler
mov rbx,IDT+2*16
call set_gate
mov dword [rdi+40],1
lidt [idtr]
.wait_ready:
cmp dword [rdi+44],3
jne .wait_ready
mov ebx,1
.directed:
mov eax,ebx
shl eax,24
mov [rsi+0x310],eax
mov dword [rsi+0x300],0x4041
mov eax,ebx
shl eax,10
.wait_fixed:
cmp dword [RECORDS+rax+56],1
jne .wait_fixed
mov eax,ebx
shl eax,24
mov [rsi+0x310],eax
mov dword [rsi+0x300],0x4400
mov eax,ebx
shl eax,10
.wait_nmi:
cmp dword [RECORDS+rax+60],1
jne .wait_nmi
inc ebx
cmp ebx,4
jb .directed
mov dword [rsi+0x300],0xC4041
mov ebx,1
.wait_broadcast:
mov eax,ebx
shl eax,10
cmp dword [RECORDS+rax+56],2
jne .wait_broadcast
inc ebx
cmp ebx,4
jb .wait_broadcast
mov dword [rdi+36],1
jmp .done
.ap_ipi:
cmp dword [rdi+40],1
jne .ap_ipi
lidt [idtr]
mov dword [rsi+0xF0],0x1FF
lock inc dword [rdi+44]
sti
.idle:
hlt
jmp .idle
.done:
hlt
jmp .done
set_gate:
mov [rbx],ax
mov word [rbx+2],0x18
mov word [rbx+4],0x8E00
shr rax,16
mov [rbx+6],ax
shr rax,16
mov [rbx+8],eax
mov dword [rbx+12],0
ret
ipi_handler:
push rax
push rsi
mov esi,LAPIC
mov eax,[rsi+0x20]
shr eax,24
shl eax,10
lock inc dword [RECORDS+rax+56]
mov dword [rsi+0xB0],0
pop rsi
pop rax
iretq
nmi_handler:
push rax
push rsi
mov esi,LAPIC
mov eax,[rsi+0x20]
shr eax,24
shl eax,10
lock inc dword [RECORDS+rax+60]
; the interrupted RIP must be inside the AP idle loop
mov rsi,[rsp+16]
mov [RECORDS+rax+64+128+128+64],rsi
pop rsi
pop rax
iretq
contend:
.retry:
mov rax,[rdi]
mov rdx,[rdi+8]
lea rbx,[rax+1]
mov rcx,rbx
not rcx
lock cmpxchg16b [rdi]
jnz .retry
dec r10d
jnz .retry
ret
fail_gpr: mov eax,1
jmp failed
fail_tlb: mov eax,2
jmp failed
fail_msr: mov eax,3
jmp failed
fail_xmm: mov eax,4
failed:
mov [rbp+52],eax
mov [rdi+32],eax
jmp high_entry.done
align 8
gdt:
dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
gdtr: dw 31
dd gdt
idtr: dw 0x42*16-1
dq IDT
end:
                                                                                                                                                                              source/v64/tests/x64/multicore.mjs                                                                  0000644 0000000 0000000 00000020515 00000000000 014170  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Real INIT/SIPI APs: no host writes to registers, runnable flags or page tables.
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawnSync} from "node:child_process";
import {setImmediate as yield_event} from "node:timers/promises";
import {fileURLToPath} from "node:url";
const root = fileURLToPath(new URL("../../", import.meta.url));
const directory = root + "build/x64-multicore/";
fs.mkdirSync(directory, {recursive: true});
const kernel = directory + "guest.bin";
const nasm = spawnSync("nasm", ["-f", "bin", "-o", kernel, root + "tests/x64/multicore.asm"], {encoding: "utf8"});
assert.equal(nasm.status, 0, nasm.stderr);
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const {CORE_STATE_RANGES, STATE_OFFSETS} = await import("../../src/state_layout.js");
const modes = process.env.X64_MODES?.split(",") || ["interpreter", "pages"];
const seeds = process.env.X64_SEEDS?.split(",").map(Number) || [1, 7];
const quantums = process.env.X64_QUANTUMS?.split(",").map(Number) || [17, 257];
const CONTROL = 0x380000, RECORDS = 0x390000, ITERATIONS = 512;
async function run(mode, seed, quantum)
{
    const label = `${mode} seed=${seed} quantum=${quantum}`;
    const emulator = new V86({graphics_adapter: "bochs_vga", multiboot: {url: kernel}, memory_size: 32 << 20, cpu_cores: 4,
        cpu_quantum: quantum, cpu_schedule_seed: seed, acpi: true, autostart: false,
        disable_jit: mode === "interpreter", experimental_smp_jit: true,
        ir_sync_publication: true, log_level: 0});
    let cpu, rounds = 0;
    const native = [0, 0, 0, 0];
    try
    {
        await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
        cpu = emulator.v86.cpu;
        const ex = cpu.wm.exports;
        const slice = cpu.run_cpu_slice.bind(cpu);
        cpu.run_cpu_slice = (...args) => {
            const core = cpu.active_core;
            const before = ex.x64_page_stat(1);
            const result = slice(...args);
            native[core] += ex.x64_page_stat(1) - before;
            return result;
        };
        const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset, cpu.mem8.length);
        const word = offset => view().getUint32(offset, true);
        const quad = offset => view().getBigUint64(offset, true);
        function core_field(id, offset, size = 4)
        {
            if(cpu.active_core === id)
            {
                const data = new DataView(cpu.wasm_memory.buffer);
                return size === 1 ? data.getUint8(cpu.state_base + offset) : data.getUint32(cpu.state_base + offset, true);
            }
            const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
            assert.ok(index >= 0);
            const bytes = cpu.cores[id].saved[index];
            const data = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
            const local = offset - CORE_STATE_RANGES[index][0];
            return size === 1 ? data.getUint8(local) : data.getUint32(local, true);
        }
        async function until(phase, predicate)
        {
            const deadline = performance.now() + 60000;
            while(!predicate())
            {
                cpu.run_cores();
                rounds++;
                assert.equal(word(CONTROL + 32), 0, `${label} ${phase}: guest canary/TLB/MSR/vector failure`);
                if(performance.now() > deadline) throw new Error(`${label} ${phase}: timeout ${JSON.stringify(cpu.get_diagnostics())}`);
                await yield_event();
            }
        }
        await until("all four genuine long-mode APs at checkpoint", () => word(CONTROL + 16) === 4);
        assert.equal(quad(CONTROL), 4n * BigInt(ITERATIONS));
        assert.equal(quad(CONTROL + 8), BigInt.asUintN(64, ~quad(CONTROL)));
        for(let id = 0; id < 4; id++)
        {
            const at = RECORDS + id * 1024;
            if(id)
            {
                assert.equal(word(at) & 1, 0, `AP ${id}: reset real mode`);
                assert.equal(word(at + 4), 0x800, `AP ${id}: guest SIPI vector 8`);
            }
            assert.equal(quad(at + 8), 0xFFFF800000000000n + (BigInt(id) << 39n), `core ${id}: distinct full RIP alias`);
            assert.equal(quad(at + 24), 0xAABBCCDD00000000n + BigInt(id));
            assert.equal(word(at + 16), 0xA100 + id, `core ${id}: private mapping at common linear address`);
            assert.equal(core_field(id, STATE_OFFSETS.x64_cs_long, 1), 1);
            assert.equal(core_field(id, STATE_OFFSETS.x64_gpr_hi + 8 * 4), 0xAABBCCDD);
            assert.equal(core_field(id, STATE_OFFSETS.x64_gpr_ext_lo), id);
            const rip = BigInt(core_field(id, STATE_OFFSETS.instruction_pointer)) |
                BigInt(core_field(id, STATE_OFFSETS.x64_rip_hi)) << 32n;
            assert.equal(rip >> 39n, (0xFFFF800000000000n + (BigInt(id) << 39n)) >> 39n);
        }
        const snapshot = await emulator.save_state();
        async function finish()
        {
            view().setUint32(CONTROL + 20, 1, true); // documented guest release mailbox only
            await until("atomic contention completed", () => word(CONTROL + 24) === 4);
            await until("long-mode fixed, NMI and broadcast IPIs", () => word(CONTROL + 36) === 1);
            // Each core runs at its own alias HIGH + (id << 39).
            const alias = id => 0xFFFF800000000000n + (BigInt(id) << 39n);
            const idle = quad(RECORDS + 1024 + 384) - alias(1);
            assert.ok(idle > 0x100000n && idle < 0x110000n, "NMI return RIP is in the guest image");
            for(let id = 0; id < 4; id++)
            {
                const at = RECORDS + id * 1024;
                assert.equal(word(at + 56), id ? 2 : 0, `core ${id}: directed + all-excluding-self fixed IPI`);
                assert.equal(word(at + 60), id ? 1 : 0, `core ${id}: NMI IPI`);
                if(id) assert.equal(quad(at + 384), alias(id) + idle, `core ${id}: NMI interrupted the halted idle loop`);
            }
            assert.equal(quad(CONTROL), 8n * BigInt(ITERATIONS));
            assert.equal(quad(CONTROL + 8), BigInt.asUintN(64, ~quad(CONTROL)));
            for(let id = 0; id < 4; id++)
            {
                const at = RECORDS + id * 1024;
                assert.equal(word(at + 32), 0xA100 + id, `core ${id}: stale TLB survives core switch / snapshot`);
                assert.equal(word(at + 36), 0xB200 + id, `core ${id}: INVLPG sees private replacement`);
                assert.equal(word(at + 40), 0xAA000000 + id, `core ${id}: RDTSCP TSC_AUX`);
                assert.equal(word(at + 48), 0xD064, `core ${id}: finished`);
                assert.equal(word(at + 52), 0);
                assert.deepEqual(Buffer.from(cpu.mem8.slice(at + 256, at + 384)), Buffer.from(cpu.mem8.slice(at + 64, at + 192)), `core ${id}: all XMM8..15`);
            }
            return Buffer.from(cpu.mem8.slice(RECORDS, RECORDS + 4096));
        }
        const original = await finish();
        await emulator.restore_state(snapshot);
        assert.equal(word(CONTROL + 16), 4, "all checkpoint arrivals restored");
        assert.equal(word(CONTROL + 20), 0, "release flag restored");
        const restored = await finish();
        assert.deepEqual(restored, original, "snapshot replay has identical complete per-core results");
        if(mode === "interpreter") assert.deepEqual(native, [0, 0, 0, 0]);
        else assert.ok(native.every(count => count > 1000), `${label}: every core actually executed native i64 code: ${native}`);
        const result = {mode, seed, quantum, rounds, native, snapshot_bytes: snapshot.byteLength};
        console.log("PASS x64 four-core INIT/SIPI, state/TLB isolation, CX16, fixed/NMI/broadcast IPIs, snapshot " + JSON.stringify(result));
        return result;
    }
    catch(error)
    {
        if(cpu)
        {
            fs.writeFileSync(directory + "failure.json", JSON.stringify(cpu.get_diagnostics(), null, 2));
            fs.writeFileSync(directory + "failure-records.bin", Buffer.from(cpu.mem8.slice(RECORDS, RECORDS + 4096)));
        }
        throw error;
    }
    finally { await emulator.destroy(); }
}
const results = [];
for(const mode of modes) for(const seed of seeds) for(const quantum of quantums) results.push(await run(mode, seed, quantum));
fs.writeFileSync(directory + "results.json", JSON.stringify(results, null, 2) + "\n");
                                                                                                                                                                                   source/v64/tests/x64/opcode_matrix.mjs                                                              0000644 0000000 0000000 00000024220 00000000000 015017  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Execution-level long-mode opcode matrix. Every row of the opcode-map
// corpus (x64::decode::tests::opcode_map_corpus, expectations written by
// tests/x64/oracle from iced-x86 gated by the advertised CPUID profile) runs
// once at CPL3 in a sandbox: code slots are user read-only pages, data and
// stack are user no-execute pages, the harness and everything else is
// supervisor-only or not present, the FPU/MXCSR state is reset per case, and
// every exception vector, SYSCALL and SYSENTER lands in the harness, which
// records the outcome. Each slot is the instruction followed by INT3, so a
// completed instruction reports its executed length.
//
// Checks: an encoding is #UD in v86 exactly when iced-x86 + the profile say
// it is invalid, and a completed instruction consumed iced-x86's length.
// OPCODE_MATRIX_LIMIT=n runs the first n rows; X64_JIT=1 runs with the page
// tier (each case executes once, so this mostly exercises the interpreter).
import assert from "node:assert/strict";
import fs from "node:fs";
import {spawnSync} from "node:child_process";
import {setImmediate as yield_event} from "node:timers/promises";
import {fileURLToPath} from "node:url";

const root = fileURLToPath(new URL("../../", import.meta.url));
const directory = root + "build/x64-opcode-matrix/";
fs.mkdirSync(directory, {recursive: true});
const expected_path = root + "build/x64-decode/expected.json";
assert.ok(fs.existsSync(expected_path), "run `make x64-decode-tests` first (writes build/x64-decode/expected.json)");
let rows = JSON.parse(fs.readFileSync(expected_path, "utf8"));
if(process.env.OPCODE_MATRIX_LIMIT) rows = rows.slice(0, +process.env.OPCODE_MATRIX_LIMIT);

const SLOTS = 0x800000, SLOT = 32, RESULTS = 0x2000000, RECORD = 16, DATA = 0x600000, USER_STACK = 0x7F0000;
const MAGIC = 0xC064C064, STATUS = 0x480000;
assert.ok(rows.length * SLOT <= 0x1800000 - SLOTS && rows.length * RECORD <= 0x1000000);
const error_code = new Set([8, 10, 11, 12, 13, 14, 17, 21, 29, 30]);
const stubs = Array.from({length: 32}, (_, v) => `stub_${v}:\n${error_code.has(v) ? "" : "push 0\n"}push ${v}\njmp record_fault`).join("\n");
const gates = Array.from({length: 32}, (_, v) => `lea rax,[rel stub_${v}]\nmov edi,${v}\ncall set_gate`).join("\n");
const source = `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr32]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x5F0000
; 2 MiB pages: 0-8 MiB supervisor (harness, tables, stacks), data/stack
; user RW NX, code slots user RO, results supervisor, the rest absent
mov dword [0x200000],0x201007
mov dword [0x201000],0x202007
mov dword [0x202000+0*8],0x000083
mov dword [0x202000+1*8],0x200083
mov dword [0x202000+2*8],0x400083
mov dword [0x202000+3*8],0x600087
mov dword [0x202000+3*8+4],0x80000000
mov edi,0x202000+4*8
mov eax,0x800085
mov ecx,8
.code:
mov [edi],eax
add eax,0x200000
add edi,8
loop .code
mov edi,0x202000+16*8
mov eax,0x2000083
mov ecx,8
.results:
mov [edi],eax
mov dword [edi+4],0x80000000
add eax,0x200000
add edi,8
loop .results
mov eax,cr4
or eax,0x620
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x901
xor edx,edx
wrmsr
mov eax,cr0
or eax,0x80010033
and eax,~0x0C
mov cr0,eax
jmp 24:long_mode
bits 64
long_mode:
lgdt [rel gdtr64]
lidt [rel idtr64]
lea rax,[rel tss]
mov word [rel gdt+58],ax
shr rax,16
mov byte [rel gdt+60],al
mov byte [rel gdt+63],ah
shr rax,16
mov dword [rel gdt+64],eax
mov qword [rel tss+4],0x5F0000
; I/O map base beyond the TSS limit: CPL3 port I/O faults
mov word [rel tss+102],104
mov ax,0x38
ltr ax
mov al,0xFF
out 0x21,al
out 0xA1,al
${gates}
; INT3 closes every slot and must be usable from CPL3
mov byte [rel idt+3*16+5],0xEE
mov ecx,0xC0000081
xor eax,eax
mov edx,0x00230018
wrmsr
mov ecx,0xC0000082
lea rax,[rel syscall_landing]
mov rdx,rax
shr rdx,32
wrmsr
mov ecx,0xC0000084
mov eax,0x4700
xor edx,edx
wrmsr
mov ecx,0x174
mov eax,0x18
xor edx,edx
wrmsr
mov ecx,0x175
mov eax,0x5E0000
wrmsr
mov ecx,0x176
lea rax,[rel sysenter_landing]
mov rdx,rax
shr rdx,32
wrmsr
mov rdi,${DATA}
mov rax,0x5A5A5A5A5A5A5A5A
mov ecx,0x40000
rep stosq
run_case:
mov rsp,0x5F0000
mov eax,[rel case_index]
cmp eax,[rel case_count]
jae done
mov dword [${STATUS}],eax
fninit
ldmxcsr [rel mxcsr_default]
mov rax,0x1000
mov ecx,8
mov edx,0x10
mov rbx,${DATA + 0x800}
mov rsi,${DATA + 0x100}
mov rdi,${DATA + 0x200}
mov rbp,${DATA + 0x400}
mov r8,${DATA + 0x480}
mov r9,${DATA + 0x500}
mov r10,${DATA + 0x580}
mov r11,${DATA + 0x600}
mov r12,${DATA + 0x680}
mov r13,${DATA + 0x700}
mov r14,${DATA + 0x780}
mov r15,${DATA + 0x880}
push 0x23
push ${USER_STACK}
push 2
push 0x33
mov r15d,[rel case_index]
shl r15,5
add r15,${SLOTS}
push r15
mov r15,${DATA + 0x880}
iretq
; [rsp] vector, [rsp+8] error, [rsp+16] RIP
record_fault:
mov eax,[rel case_index]
shl rax,4
add rax,${RESULTS}
mov rdx,[rsp]
mov [rax],edx
mov rdx,[rsp+8]
mov [rax+4],edx
mov rdx,[rsp+16]
mov [rax+8],rdx
inc dword [rel case_index]
jmp run_case
syscall_landing:
mov eax,[rel case_index]
shl rax,4
add rax,${RESULTS}
mov dword [rax],0x100
mov [rax+8],rcx
inc dword [rel case_index]
jmp run_case
sysenter_landing:
mov eax,[rel case_index]
shl rax,4
add rax,${RESULTS}
mov dword [rax],0x101
inc dword [rel case_index]
jmp run_case
done:
mov dword [${STATUS + 4}],${MAGIC}
hlt
jmp done
set_gate:
shl rdi,4
lea rdx,[rel idt]
add rdi,rdx
mov word [rdi],ax
mov word [rdi+2],0x18
mov word [rdi+4],0x8E00
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
mov dword [rdi+12],0
ret
${stubs}
align 16
mxcsr_default: dd 0x1F80
case_index: dd 0
case_count: dd ${rows.length}
align 16
gdt:
dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
dq 0x00CFF2000000FFFF,0x00CFFA000000FFFF,0x00AFFA000000FFFF
dq 0x0000890000000067,0
dq 0,0
gdtr32: dw 87
dd gdt
gdtr64: dw 87
dq gdt
idtr64: dw 511
dq idt
align 16
tss: times 104 db 0
align 16
idt: times 512 db 0
image_end:
`;
fs.writeFileSync(directory + "guest.asm", source);
const nasm = spawnSync("nasm", ["-f", "bin", "-o", directory + "guest.bin", directory + "guest.asm"], {encoding: "utf8"});
assert.equal(nasm.status, 0, nasm.stderr);

const slots = new Uint8Array(rows.length * SLOT).fill(0xCC);
const lengths = [];
for(const [n, [hex, , length]] of rows.entries())
{
    const bytes = Buffer.from(hex, "hex");
    const used = Math.min(length || 15, 15, bytes.length);
    slots.set(bytes.subarray(0, used), n * SLOT);
    lengths.push(used);
}
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const emulator = new V86({graphics_adapter: "bochs_vga", multiboot: {url: directory + "guest.bin"}, memory_size: 64 << 20, acpi: true,
    disable_jit: !process.env.X64_JIT, ir_sync_publication: true, autostart: false, log_level: 0});
const outcomes = [];
try
{
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const cpu = emulator.v86.cpu;
    cpu.mem8.set(slots, SLOTS);
    const view = () => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset);
    const deadline = performance.now() + Number(process.env.OPCODE_MATRIX_TIMEOUT || 1800000);
    let rounds = 0;
    while(view().getUint32(STATUS + 4, true) !== MAGIC)
    {
        if(performance.now() > deadline) throw new Error("matrix timed out at case " + view().getUint32(STATUS, true));
        cpu.run_cores();
        if((++rounds & 63) === 0) await yield_event();
    }
    for(let n = 0; n < rows.length; n++)
    {
        const at = RESULTS + n * RECORD;
        outcomes.push({vector: view().getUint32(at, true), error: view().getUint32(at + 4, true), rip: view().getBigUint64(at + 8, true)});
    }
}
finally { await emulator.destroy(); }

// Encodings that are architecturally #UD although iced-x86 decodes them as
// instructions (UD0/UD1/UD2).
const always_ud = new Set(["Ud0_r16_rm16", "Ud0_r32_rm32", "Ud0_r64_rm64", "Ud1_r16_rm16", "Ud1_r32_rm32", "Ud1_r64_rm64", "Ud2", "Ud0"]);
// Encodings iced-x86 attributes to an extension this profile lacks, but which
// a processor without that extension executes in an older form (SDM): TZCNT
// and LZCNT run as REP BSF/BSR, WBNOINVD as WBINVD, and the prefetch/hint
// spaces 0F0D, 0F18 and 0F19-0F1F (PREFETCHW, PREFETCHIT*, CLDEMOTE, CET
// RDSSP) are NOPs.
const older_form = /^(Tzcnt|Lzcnt)_|^Wbnoinvd$|^Prefetch(w|wt1|reserved\d|it0|it1)?_m8$|^Cldemote_m8$|^Rdssp[dq]_r(32|64)$/;
const problems = new Map();
const details = [];
let completed = 0, ud = 0;
for(const [n, [hex, expect_valid, , code]] of rows.entries())
{
    const {vector, rip} = outcomes[n];
    const slot = BigInt(SLOTS + n * SLOT);
    const is_ud = vector === 6 && rip === slot;
    ud += is_ud;
    const valid = (expect_valid || older_form.test(code)) && !always_ud.has(code);
    let problem = null;
    if(valid && is_ud) problem = "v86 #UD, expected valid";
    else if(!valid && !is_ud) problem = `v86 ${vector === 3 ? "completed" : "vector " + vector}, expected #UD`;
    else if(valid && vector === 3 && rip === slot + BigInt(lengths[n] + 1)) completed++;
    // (relative branches may land on an INT3 inside their own slot; INT3
    // itself reports the address after it)
    else if(valid && vector === 3 && rip > slot && rip <= slot + 16n && rip !== slot + 1n
        && !/^(J[a-z]*|Loop[a-z]*|Jrcxz|Jecxz|Call)_rel|^Int3/.test(code)) problem = `executed ${rip - slot - 1n} bytes, expected ${lengths[n]}`;
    if(problem)
    {
        details.push([hex.slice(0, 30), code, problem]);
        const key = `${code}: ${problem}`;
        const entry = problems.get(key) || {count: 0, example: hex.slice(0, 30)};
        entry.count++;
        problems.set(key, entry);
    }
}
for(const [key, {count, example}] of [...problems].sort((a, b) => b[1].count - a[1].count))
    console.log(`MISMATCH ${key} x${count} (e.g. ${example})`);
console.log(`opcode matrix: ${rows.length} encodings run at CPL3, ${ud} #UD, ${completed} completed with the expected length, ${problems.size} mismatching forms`);
fs.writeFileSync(directory + "mismatches.json", JSON.stringify([...problems], null, 1));
fs.writeFileSync(directory + "mismatch-rows.json", JSON.stringify(details));
assert.equal(problems.size, 0, "long-mode execution disagrees with iced-x86 + the CPUID profile");
console.log("PASS opcode matrix");
                                                                                                                                                                                                                                                                                                                                                                                source/v64/tests/x64/oracle/Cargo.toml                                                              0000644 0000000 0000000 00000000346 00000000000 014647  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       [package]
name = "v86-x64-decode-oracle"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
iced-x86 = { version = "=1.21.0", default-features = false, features = ["std", "decoder", "instr_info"] }
serde_json = "1"
                                                                                                                                                                                                                                                                                          source/v64/tests/x64/oracle/src/main.rs                                                             0000644 0000000 0000000 00000024171 00000000000 015002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       use iced_x86::{CpuidFeature, Decoder, DecoderOptions, OpKind, Register};
use std::collections::BTreeMap;
fn reg(r: Register) -> i64 {
    match r {
        Register::None => -1,
        Register::RIP | Register::EIP => -2,
        _ => r.number() as i64,
    }
}
/// CPUID features of the x64 qualification profile (instructions_0f.rs
/// cpuid + apply_x64_test_capabilities). ENDBR is a hint NOP without CET.
fn advertised(feature: CpuidFeature) -> bool {
    use CpuidFeature::*;
    matches!(feature, INTEL8086 | INTEL186 | INTEL286 | INTEL386 | INTEL486 | X64 | CMOV | CMPXCHG16B | CPUID | CX8
        | FPU | FPU287 | FPU387 | FXSR | MMX | MSR | MULTIBYTENOP | PAUSE | POPCNT | RDRAND | SEP | SSE | SSE2 | SSE3
        | SYSCALL | TSC | CET_IBT | RDTSCP | CLFSH)
}
/// Long-mode opcode map: validity (after CPUID gating) and length of every
/// row of build/x64-decode/opcodes.json (x64::decode::tests::opcode_map_corpus).
fn opcode_map(path: &str) {
    let Ok(text) = std::fs::read(path) else { return; };
    let rows: Vec<Vec<serde_json::Value>> = serde_json::from_slice(&text).unwrap();
    let mut differences: BTreeMap<String, (usize, String)> = BTreeMap::new();
    let mut valid = 0;
    // Per-row expectations for tests/x64/opcode_matrix.mjs (execution).
    let mut expected_rows = Vec::with_capacity(rows.len());
    for row in &rows {
        let bytes: Vec<u8> = row[0].as_array().unwrap().iter().map(|v| v.as_u64().unwrap() as u8).collect();
        let ok = row[1].as_u64().unwrap() == 1;
        let length = row[2].as_u64().unwrap() as usize;
        let i = Decoder::with_ip(64, &bytes, 0xFFFF_8000_0000_1000, DecoderOptions::NONE).decode();
        let expected = !i.is_invalid() && i.cpuid_features().iter().all(|&f| advertised(f));
        valid += expected as usize;
        expected_rows.push(format!("[\"{}\",{},{},\"{:?}\"]", bytes.iter().map(|b| format!("{b:02x}")).collect::<String>(),
            expected as u8, if i.is_invalid() { length } else { i.len() }, i.code()));
        let problem = if ok != expected {
            Some(format!("v86 {} iced {} ({:?} {:?})", if ok { "valid" } else { "#UD" }, if expected { "valid" } else { "#UD" }, i.code(), i.cpuid_features()))
        } else if ok && length != i.len() {
            Some(format!("length v86 {} iced {} ({:?})", length, i.len(), i.code()))
        } else {
            None
        };
        if let Some(problem) = problem {
            // key: prefixes and opcode bytes, without ModRM/SIB/immediates
            let mut key = String::new();
            let mut at = 0;
            while matches!(bytes[at], 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3 | 0x40..=0x4F) { key += &format!("{:02X} ", bytes[at]); at += 1; }
            let opcode_len = if bytes[at] != 0x0F { 1 } else if matches!(bytes[at + 1], 0x38 | 0x3A) { 3 } else { 2 };
            for b in &bytes[at..at + opcode_len] { key += &format!("{:02X}", b); }
            key += &format!(" /{}{}", bytes[at + opcode_len] >> 3 & 7, if bytes[at + opcode_len] >= 0xC0 { "r" } else { "m" });
            let entry = differences.entry(key).or_insert((0, problem));
            entry.0 += 1;
        }
    }
    // The shared decoder gives undefined and unadvertised opcodes a length and
    // leaves #UD to the executors (tests/x64/opcode_matrix.mjs checks that at
    // run time); anything else is a failure.
    let mut decoded_undefined = 0;
    let mut failures = 0;
    for (key, (count, problem)) in &differences {
        if problem.starts_with("v86 valid iced #UD") {
            decoded_undefined += count;
            if std::env::var("OPCODE_MAP_VERBOSE").is_ok() { println!("UNDEFINED {key}: {problem} x{count}"); }
        } else {
            failures += 1;
            println!("DIFF {key}: {problem} x{count}");
        }
    }
    std::fs::write("build/x64-decode/expected.json", format!("[{}]", expected_rows.join(","))).unwrap();
    println!("opcode map: {} rows, {} valid per iced-x86 and the CPUID profile; {} rows of undefined/unadvertised opcodes decoded for executor #UD", rows.len(), valid, decoded_undefined);
    assert_eq!(failures, 0, "long-mode opcode map validity/length differs from iced-x86");
}
/// The features of the plan (docs/simd-xsave-plan.md) and the baseline's:
/// iced-x86 forms that need others are #UD
fn plan_feature(feature: CpuidFeature) -> bool {
    use CpuidFeature::*;
    advertised(feature)
        || matches!(feature, SSSE3 | SSE4_1 | SSE4_2 | AVX | AVX2 | FMA | F16C | BMI1 | BMI2 | LZCNT | MOVBE)
}
/// The bytes after each entry of the SIMD corpus (tests/decode/simd_corpus.rs FILLER)
const FILLER: [u8; 8] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x08];
/// The SIMD decode corpus (tests/decode/simd_corpus.rs): VEX and legacy SIMD
/// encodings in 16-, 32- and 64-bit mode, decoded by the x64 decoder with
/// every feature as if all rows had semantics. Validity, length and VEX form
/// must match iced-x86, except where the SDM and iced-x86 differ (counted).
fn simd_corpus(path: &str) {
    let Ok(data) = std::fs::read(path) else { return; };
    let names: Vec<String> =
        serde_json::from_slice(&std::fs::read("build/x64-decode/simd-forms.json").unwrap()).unwrap();
    let (mut at, mut rows, mut valid, mut vvvv_top) = (0, 0, 0, 0);
    let mut differences: BTreeMap<String, (usize, String)> = BTreeMap::new();
    while at < data.len() {
        let (bits, n) = (data[at] as u32, data[at + 1] as usize);
        let bytes = &data[at + 2..at + 2 + n];
        let ok = data[at + 2 + n] == 1;
        let length = data[at + 3 + n] as usize;
        let form = u16::from_le_bytes([data[at + 4 + n], data[at + 5 + n]]);
        at += 6 + n;
        rows += 1;
        let mut full = bytes.to_vec();
        full.extend(FILLER);
        let decode = |b: &[u8]| Decoder::with_ip(bits, b, 0x1000, DecoderOptions::NONE).decode();
        let i = decode(&full);
        let expected = !i.is_invalid() && i.cpuid_features().iter().all(|&f| plan_feature(f));
        let name = |form: u16| if form == 0xFFFF { "-".to_string() } else { names[form as usize].clone() };
        // the opcode, after the legacy prefixes and REX
        let start = bytes
            .iter()
            .position(|&b| !(matches!(b, 0x26 | 0x2E | 0x36 | 0x3E | 0x64..=0x67 | 0xF0 | 0xF2 | 0xF3) || bits == 64 && b & 0xF0 == 0x40))
            .unwrap();
        let problem = if ok == expected {
            if ok && (length != i.len() || form != 0xFFFF && name(form) != format!("{:?}", i.code())) {
                Some(format!("v86 {} length {length}, iced {:?} length {}", name(form), i.code(), i.len()))
            } else {
                None
            }
        } else if ok && bits != 64 && bytes[start] == 0xC4 && bytes[start + 2] & 0x40 == 0 && {
            // SDM 2.3.5.6: outside 64-bit mode the three-byte prefix's top
            // VEX.vvvv bit is ignored; iced-x86 requires it to be 1
            let mut set = full.clone();
            set[start + 2] |= 0x40;
            let j = decode(&set);
            !j.is_invalid() && j.len() == length && format!("{:?}", j.code()) == name(form)
        } {
            vvvv_top += 1;
            None
        } else {
            Some(format!("v86 {} ({}), iced {} ({:?} {:?})", if ok { "valid" } else { "#UD" }, name(form),
                if expected { "valid" } else { "#UD" }, i.code(), i.cpuid_features()))
        };
        valid += ok as usize;
        if let Some(problem) = problem {
            let key = format!("{bits}-bit {:02X?}", &bytes[..(start + 4).min(bytes.len())]);
            differences.entry(key).or_insert((0, problem)).0 += 1;
        }
    }
    for (key, (count, problem)) in differences.iter().take(40) {
        println!("DIFF {key}: {problem} x{count}");
    }
    println!(
        "SIMD corpus: {rows} VEX and legacy SIMD encodings in 16/32/64-bit mode, {valid} valid; \
         {vvvv_top} differ from iced-x86 by SDM 2.3.5.6 (the top VEX.vvvv bit outside 64-bit mode)"
    );
    assert!(differences.is_empty(), "{} groups of SIMD encodings differ from iced-x86", differences.len());
    println!("PASS: the SIMD decode corpus agrees with iced-x86 1.21.0 in validity, length and VEX form");
}
fn main() {
    opcode_map("build/x64-decode/opcodes.json");
    simd_corpus("build/x64-decode/simd.bin");
    let path = std::env::args()
        .nth(1)
        .unwrap_or("build/x64-decode/corpus.json".into());
    let rows: Vec<Vec<serde_json::Value>> =
        serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
    for (n, row) in rows.iter().enumerate() {
        let bytes: Vec<u8> = row[0]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_u64().unwrap() as u8)
            .collect();
        let bitness = row[1].as_u64().unwrap() as u32;
        let i =
            Decoder::with_ip(bitness, &bytes, 0xFFFF_8000_0000_1000, DecoderOptions::NONE).decode();
        let expected: Vec<u64> = row[2..]
            .iter()
            .map(|v| v.as_u64().unwrap_or_else(|| v.as_i64().unwrap() as u64))
            .collect();
        assert!(!i.is_invalid(), "invalid oracle row {n}: {bytes:02X?}");
        let memory = i.op1_kind() == OpKind::Memory;
        let segment =
            if memory { (i.memory_segment() as u32 - Register::ES as u32) as u64 } else { 0 };
        let mut displacement = if memory { i.memory_displacement64() } else { 0 };
        let address_size = expected[2];
        if address_size == 16 {
            displacement = displacement as u16 as u64;
        } else if address_size == 32 {
            displacement = displacement as u32 as u64;
        }
        let actual = vec![
            i.len() as u64,
            (i.op0_register().size() * 8) as u64,
            address_size,
            reg(i.op0_register()) as u64,
            if memory { u64::MAX } else { reg(i.op1_register()) as u64 },
            if memory { reg(i.memory_base()) as u64 } else { u64::MAX },
            if memory { reg(i.memory_index()) as u64 } else { u64::MAX },
            if memory { i.memory_index_scale().ilog2() as u64 } else { 0 },
            segment,
            displacement,
        ];
        assert_eq!(actual, expected, "oracle row {n}: {bytes:02X?}, {i:?}");
    }
    println!(
        "PASS: {} mode/prefix/REX/ModRM/SIB rows agree with iced-x86 1.21.0",
        rows.len()
    );
}
                                                                                                                                                                                                                                                                                                                                                                                                       source/v64/tests/x64/page_fuzz.mjs                                                                  0000644 0000000 0000000 00000044306 00000000000 014163  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Random long-mode programs, each looped until its code pages are compiled by
// the x64 page tier (src/rust/x64/pagegen.rs), then compared with the same
// guest run by the wide interpreter alone: every GPR, RFLAGS and the data
// pages must be identical. The programs mix templated forms (all widths,
// memory operands with SIB/RIP/FS bases, LOCK RMW, stack, calls, forward
// branches) with interpreter steps and page-crossing accesses (retries).
//
// PAGE_FUZZ_SEED, PAGE_FUZZ_CASES (per guest), PAGE_FUZZ_GUESTS;
// PAGE_FUZZ_STRADDLE=1: each case starts near the end of a page, so that its
// loop runs across the page boundary (instructions that straddle it).
import assert from "node:assert/strict";
import fs from "node:fs";
import {assemble} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {setImmediate as yield_event} from "node:timers/promises";

let seed = Number(process.env.PAGE_FUZZ_SEED || 1) >>> 0 || 1;
const random = () => {
    seed ^= seed << 13; seed >>>= 0;
    seed ^= seed >>> 17;
    seed ^= seed << 5; seed >>>= 0;
    return seed / 0x100000000;
};
const pick = list => list[Math.floor(random() * list.length)];
const int = (lo, hi) => lo + Math.floor(random() * (hi - lo + 1));
const hex = n => "0x" + n.toString(16);

// r13: small index; r14: data base; r15: loop counter; rsp: stack.
const GPR64 = ["rax", "rcx", "rdx", "rbx", "rsi", "rdi", "rbp", "r8", "r9", "r10", "r11", "r12"];
const NAMES = {
    rax: ["rax", "eax", "ax", "al"], rcx: ["rcx", "ecx", "cx", "cl"], rdx: ["rdx", "edx", "dx", "dl"],
    rbx: ["rbx", "ebx", "bx", "bl"], rsi: ["rsi", "esi", "si", "sil"], rdi: ["rdi", "edi", "di", "dil"],
    rbp: ["rbp", "ebp", "bp", "bpl"], r8: ["r8", "r8d", "r8w", "r8b"], r9: ["r9", "r9d", "r9w", "r9b"],
    r10: ["r10", "r10d", "r10w", "r10b"], r11: ["r11", "r11d", "r11w", "r11b"], r12: ["r12", "r12d", "r12w", "r12b"],
};
const WIDTHS = [64, 32, 16, 8];
const SIZE = {64: "qword", 32: "dword", 16: "word", 8: "byte"};
const LEGACY8 = ["al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"];
const REX8 = ["al", "cl", "dl", "bl", "sil", "dil", "bpl", "r8b", "r9b", "r10b", "r11b", "r12b"];
// Registers usable together in one instruction (no AH-BH with REX).
const regs = (w, n) => {
    const set = w === 8 ? (random() < 0.4 ? LEGACY8 : REX8) : GPR64.map(r => NAMES[r][WIDTHS.indexOf(w)]);
    return Array.from({length: n}, () => pick(set));
};
const reg = w => regs(w, 1)[0];
// Combinable with a memory operand (which may use REX.B for r14).
const low_reg = w => NAMES[pick(["rax", "rcx", "rdx", "rbx", "rsi", "rdi", "r8", "r9", "r10"])][WIDTHS.indexOf(w)];
// Data: two pages at r14 = FS base = 0x500000, and a RIP-relative buffer.
const mem = w => {
    const bytes = w / 8;
    const cross = random() < 0.04;
    const disp = cross ? 4096 - int(1, Math.max(1, bytes - 1)) : int(0, 8190 - bytes) & ~(random() < 0.7 ? bytes - 1 : 0);
    switch(int(0, 4))
    {
        case 0: return `${SIZE[w]} [r14+${disp}]`;
        case 1: return `${SIZE[w]} [r14+r13*${pick([1, 2, 4, 8])}+${Math.min(disp, 8190 - 255 * 8 - bytes)}]`;
        case 2: return `${SIZE[w]} [fs:${disp}]`;
        case 3: return `${SIZE[w]} [rel data+${disp}]`;
        default: return `${SIZE[w]} [r14+${disp - 64}+64]`;
    }
};
const XMM = Array.from({length: 16}, (_, i) => `xmm${i}`);
// SSE memory operand: aligned forms get 16-byte aligned addresses (no r13
// index); unaligned ones sometimes cross into the second page.
const vmem = (bytes, aligned) => {
    let disp = int(0, 8190 - bytes);
    if(aligned) disp &= ~15;
    else if(random() < 0.1) disp = 4096 - int(1, bytes - 1);
    switch(int(0, aligned ? 2 : 3))
    {
        case 0: return `[r14+${disp}]`;
        case 1: return `[fs:${disp}]`;
        case 2: return `[rel data+${disp}]`;
        default: return `[r14+r13*${pick([1, 2, 4, 8])}+${Math.min(disp, 8190 - 255 * 8 - bytes)}]`;
    }
};
function sse_instruction()
{
    const a = pick(XMM), b = pick(XMM);
    return pick([
        `movdqu ${a}, ${vmem(16, false)}`, `movdqu ${vmem(16, false)}, ${a}`, `movups ${a}, ${vmem(16, false)}`, `movups ${vmem(16, false)}, ${a}`,
        `movupd ${a}, ${b}`, `movdqu ${a}, ${b}`, `movdqa ${a}, ${vmem(16, true)}`, `movdqa ${vmem(16, true)}, ${a}`,
        `movaps ${a}, ${b}`, `movaps ${a}, ${vmem(16, true)}`, `movapd ${vmem(16, true)}, ${a}`, `movntdq ${vmem(16, true)}, ${a}`,
        `movntps ${vmem(16, true)}, ${a}`, `movntpd ${vmem(16, true)}, ${a}`,
        `movss ${a}, ${b}`, `movss ${a}, ${vmem(4, false)}`, `movss ${vmem(4, false)}, ${a}`,
        `movsd ${a}, ${b}`, `movsd ${a}, ${vmem(8, false)}`, `movsd ${vmem(8, false)}, ${a}`,
        `movq ${a}, ${b}`, `movq ${a}, ${vmem(8, false)}`, `movq ${vmem(8, false)}, ${a}`,
        `movd ${a}, ${low_reg(32)}`, `movq ${a}, ${low_reg(64)}`, `movd ${low_reg(32)}, ${a}`, `movq ${low_reg(64)}, ${a}`,
        `movd ${a}, ${vmem(4, false)}`, `movd ${vmem(4, false)}, ${a}`,
        `${pick(["pxor", "por", "pand", "pandn", "xorps", "orps", "andps", "andnps", "xorpd", "orpd", "andpd", "andnpd"])} ${a}, ${random() < 0.5 ? b : vmem(16, true)}`,
        (width => `movnti ${mem(width)}, ${low_reg(width)}`)(pick([32, 64])),
        pick(["sfence", "lfence", "mfence"]),
        `mov ${low_reg(64)}, cr8`, `mov r11, ${low_reg(64)}\nand r11d, 15\nmov cr8, r11`,
        "rdtscp\nxor eax, eax\nxor edx, edx",
    ]);
}
const imm = w => {
    const v = [0, 1, -1, 0x7F, 0x80, 0x7FFF, 0x8000, 0x7FFFFFFF, -0x80000000, int(-1000, 1000), int(0, 0xFFFFFFFF) | 0][int(0, 10)];
    if(w === 8) return v & 0xFF;
    if(w === 16) return v & 0xFFFF;
    return v | 0;
};
const CC = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"];
const ALU = ["add", "or", "adc", "sbb", "and", "sub", "xor", "cmp"];
const rm = w => random() < 0.5 ? low_reg(w) : mem(w);

function instruction(state)
{
    const w = pick(WIDTHS);
    const alu = pick(ALU);
    const w16 = pick([16, 32, 64]);
    switch(int(0, 57))
    {
        case 56: case 57: {
            // MOV AL/AX/EAX/RAX with a 64-bit absolute address (moffs)
            const acc = pick(["al", "ax", "eax", "rax"]), disp = int(0, 8190 - 8) & ~(random() < 0.7 ? 7 : 0);
            const where = random() < 0.5 ? `[abs qword ${0x500000 + disp}]` : `[fs:abs qword ${disp}]`;
            return random() < 0.5 ? `mov ${acc}, ${where}` : `mov ${where}, ${acc}`;
        }
        case 52: case 53: case 54: case 55: return sse_instruction();
        case 40: { const wide = random() < 0.5; const d = wide ? "r11" : "r11d";
            return `mov r11d, ${int(3, 0x7FFFFFF0) | 3}\n${pick([`xor edx, edx\ndiv ${d}`, `${wide ? "cqo" : "cdq"}\nidiv ${d}`, `mov edx, 1\ndiv ${d}`, (at => `or ${SIZE[wide ? 64 : 32]} [r14+${at}], 3\nxor edx, edx\ndiv ${SIZE[wide ? 64 : 32]} [r14+${at}]`)(int(0, 8000) & ~7)])}`; }
        case 50: case 51: case 41: { const op = pick(["movsb", "movsw", "movsd", "movsq", "stosb", "stosw", "stosd", "stosq",
            "cmpsb", "cmpsw", "cmpsd", "cmpsq", "scasb", "scasw", "scasd", "scasq"]);
            const src = int(0, 8000), dst = random() < 0.3 ? src + int(-16, 16) : int(0, 8000), count = pick([0, 1, int(2, 16), int(17, 600)]);
            const prefix = random() < 0.8 ? (/^(cmps|scas)/.test(op) ? pick(["repe ", "repne "]) : "rep ") : "";
            return `lea rsi, [r14+${src}]\nlea rdi, [r14+${Math.max(0, dst)}]\nxor [rsi], r15d\nmov eax, r15d\nmov ecx, ${count}\n${random() < 0.2 ? "std\n" : ""}${prefix}${op}\ncld`; }
        case 42: return "swapgs\nadd r12, [gs:8]\nswapgs";
        case 43: return pick(["cli", "mov eax, ds", "mov r9w, ss", `mov word [r14+${int(0, 8000)}], cs`, "mov rdx, fs"]);
        case 44: { const sw = pick([32, 64]); return `${pick(["shld", "shrd"])} ${rm(sw)}, ${low_reg(sw)}, ${int(0, 70)}`; }
        case 45: return `${random() < 0.5 ? "lock " : ""}cmpxchg16b [r14+${int(0, 8000) & ~15}]`;
        case 46: return `${random() < 0.5 ? "lock " : ""}cmpxchg8b [r14+${int(0, 8000)}]`;
        case 48: return pick(["mov r11, cr3\nmov cr3, r11", `invlpg [r14+${int(0, 8000)}]`]);
        case 49: return pick([`add ${low_reg(64)}, r15`, `xor ${mem(32)}, r15d`, `imul ${low_reg(32)}, r15d, ${int(1, 99)}`]);
        case 47: { const d = int(2, 9); return `mov edx, ${int(0, d - 1)}\nmov r11, ${d}\ndiv r11`; }
        case 0: case 1: case 38: { const [a, b] = regs(w, 2); return `${alu} ${a}, ${b}`; }
        case 2: return `${alu} ${reg(w)}, ${imm(w)}`;
        case 3: return `${alu} ${low_reg(w)}, ${mem(w)}`;
        case 4: return `${random() < 0.3 && alu !== "cmp" ? "lock " : ""}${alu} ${mem(w)}, ${low_reg(w)}`;
        case 5: return `${alu} ${mem(w)}, ${imm(w)}`;
        case 6: { const [a, b] = regs(w, 2); return `test ${a}, ${random() < 0.5 ? imm(w) : b}`; }
        case 7: return `mov ${reg(w)}, ${imm(w === 64 && random() < 0.3 ? 32 : w)}`;
        case 8: return w === 64 && random() < 0.3 ? `mov ${reg(64)}, ${hex(int(0, 0xFFFFFFFF) * 0x100000000 + int(0, 0xFFFFFFFF))}` : `mov ${low_reg(w)}, ${mem(w)}`;
        case 9: return `mov ${mem(w)}, ${random() < 0.5 ? low_reg(w) : imm(w === 64 ? 32 : w)}`;
        case 10: return pick([`movzx ${pick(["eax", "ecx", "edx", "ebx", "esi", "edi", "ebp"])}, ${pick(LEGACY8)}`,
            `movsx ${low_reg(pick([32, 64]))}, ${pick([low_reg(8), mem(8), low_reg(16), mem(16)])}`,
            `movzx ${low_reg(pick([16, 32, 64]))}, ${pick([low_reg(8), mem(8)])}`]);
        case 11: return pick([`movsxd ${low_reg(64)}, ${low_reg(32)}`, `movsxd ${low_reg(64)}, ${mem(32)}`, `movzx ${low_reg(64)}, ${mem(16)}`]);
        case 12: return `lea ${low_reg(pick([64, 32, 16]))}, [${low_reg(64)}+${low_reg(64)}*${pick([1, 2, 4, 8])}+${int(-2000, 2000)}]`;
        case 13: { const op = pick(["inc", "dec", "neg", "not"]); return random() < 0.5 ? `${op} ${reg(w)}` : `${random() < 0.3 ? "lock " : ""}${op} ${mem(w)}`; }
        case 14: return `${pick(["shl", "shr", "sar", "rol", "ror"])} ${random() < 0.7 ? reg(w) : mem(w)}, ${pick([1, int(0, 70) & 0xFF, int(0, 7)])}`;
        case 15: return `${pick(["shl", "shr", "sar", "rol", "ror", "rcl", "rcr"])} ${random() < 0.8 ? reg(w) : mem(w)}, cl`;
        case 16: return `imul ${low_reg(w16)}, ${rm(w16)}${random() < 0.5 ? ", " + imm(16) : ""}`;
        case 17: { const mw = pick([32, 64]); return `${pick(["mul", "imul"])} ${rm(mw)}`; }
        case 18: { const r = low_reg(64); return `push ${pick([r, low_reg(64), mem(64), String(imm(32))])}\npop ${r}`; }
        case 19: return `cmov${pick(CC)} ${low_reg(w16)}, ${rm(w16)}`;
        case 20: return `set${pick(CC)} ${random() < 0.6 ? reg(8) : mem(8)}`;
        case 21: { const n = state.labels++; return `j${pick(CC)} .s${n}\n${instruction_simple()}\n${instruction_simple()}\n.s${n}:`; }
        case 22: return `xchg ${low_reg(w)}, ${rm(w)}`;
        case 23: return `${random() < 0.5 ? "lock " : ""}xadd ${mem(w)}, ${low_reg(w)}`;
        case 24: return random() < 0.5 ? `cmpxchg ${low_reg(w)}, ${low_reg(w)}` : `lock cmpxchg ${mem(w)}, ${low_reg(w)}`;
        case 25: return pick(["cbw", "cwde", "cdqe", "cwd", "cdq", "cqo"]);
        case 26: return `${pick(["bt", "bts", "btr", "btc"])} ${rm(w16)}, ${random() < 0.5 ? int(0, 255) : ["r13", "r13d", "r13w"][[64, 32, 16].indexOf(w16)]}`;
        case 27: return `${pick(["bsf", "bsr", "popcnt"])} ${low_reg(w16)}, ${rm(w16)}`;
        case 28: return `bswap ${low_reg(pick([32, 64]))}`;
        case 29: return pick(["clc", "stc", "cmc", "lahf", "sahf", "cld", "std", "nop", "pushfq\npopfq", "pushfq\npop rax", "xchg eax, eax", "nop dword [rax+rax+0x10]"]);
        case 30: return `call ${pick(["leaf_near", "leaf_far"])}`;
        case 31: return pick(["cpuid", "xorps xmm0, xmm1", "movq rax, xmm2", "movq xmm2, rbx", "pause", "paddd xmm3, xmm2"]);
        case 32: return `mov r13d, ${int(0, 255)}`;
        case 33: return `test ${mem(w)}, ${random() < 0.5 ? imm(w) : low_reg(w)}`;
        case 34: return `cmp ${low_reg(w)}, ${mem(w)}\nj${pick(CC)} .c${state.labels}\ninc r12\n.c${state.labels++}:`;
        case 35: return `sub ${low_reg(w)}, ${imm(8)}\nset${pick(CC)} al`;
        case 36: { const r = reg(32); return `xor ${r}, ${r}`; }
        case 37: return `dec r12\nj${pick(["ne", "e", "s", "g", "le"])} .d${state.labels}\nnot r11\n.d${state.labels++}:`;
        default: return `${pick(["add", "sub", "and", "or", "xor", "adc", "sbb"])} ${mem(w)}, ${imm(w)}`;
    }
}
function instruction_simple()
{
    return pick([`add ${low_reg(64)}, ${int(0, 99)}`, `xor ${low_reg(32)}, ${low_reg(32)}`, `inc ${mem(32)}`, `mov ${low_reg(16)}, ${mem(16)}`]);
}

const cases = Number(process.env.PAGE_FUZZ_CASES || 12);
const guests = Number(process.env.PAGE_FUZZ_GUESTS || 4);
const ITERATIONS = Number(process.env.PAGE_FUZZ_ITERATIONS || 300);
// GPRs and RFLAGS, the two data pages, XMM0..15
const RESULT = 0x300000, RECORD = 0x2200, MAGIC = 0xC064C064;
let failures = 0, native_total = 0;
for(let guest = 0; guest < guests; guest++)
{
    const first_seed = seed;
    let body = `
mov rax, cr4
or eax, 0x600
mov cr4, rax
mov ecx, 0xC0000100
mov eax, 0x500000
xor edx, edx
wrmsr
mov ecx, 0xC0000102
mov eax, 0x500100
xor edx, edx
wrmsr
`;
    let functions = "";
    for(let c = 0; c < cases; c++)
    {
        const state = {labels: 0};
        let lines = [];
        const count = int(20, 70);
        for(let i = 0; i < count; i++) lines.push(instruction(state));
        // Cold access caches each iteration: generated slow paths run too.
        if(random() < 0.5) lines.splice(int(0, lines.length), 0, "mov r11, cr3\nmov cr3, r11");
        let init = GPR64.map(r => `mov ${r}, ${hex(int(0, 0xFFFFFFFF) * 0x100000000 + int(0, 0xFFFFFFFF))}`).join("\n") + "\n" +
            XMM.map((x, i) => `movq ${x}, ${GPR64[i % 12]}\nmovq xmm15, ${GPR64[(i * 5 + 3) % 12]}\npunpcklqdq ${x}, xmm15`).join("\n");
        if(process.env.PAGE_FUZZ_BODY)
        {
            // {init: string, lines: [string]} (see PAGE_FUZZ_SAVE)
            const saved = JSON.parse(fs.readFileSync(process.env.PAGE_FUZZ_BODY, "utf8"));
            init = saved.init;
            lines = saved.lines;
        }
        if(process.env.PAGE_FUZZ_SAVE && +process.env.PAGE_FUZZ_SAVE_GUEST === guest && c === +process.env.PAGE_FUZZ_SAVE_CASE)
            fs.writeFileSync(process.env.PAGE_FUZZ_SAVE, JSON.stringify({init, lines}, null, 1));
        const straddle = process.env.PAGE_FUZZ_STRADDLE ? `jmp near .body\ntimes ${4096 - int(360, 1400)} db 0xCC\n.body:\n` : "";
        functions += `
align 4096
case_${c}:
${straddle}${init}
mov r13d, ${int(0, 255)}
mov r14, 0x500000
mov r15d, ${ITERATIONS}
push 0x${(int(0, 0xFFF) & 0xCD5).toString(16)}
popfq
.loop:
${lines.join("\n")}
dec r15d
jnz .loop
mov r15, ${RESULT + 8 + c * RECORD}
${[...GPR64, "r13", "r14"].map((r, i) => `mov [r15+${i * 8}], ${r}`).join("\n")}
pushfq
pop rax
mov [r15+${15 * 8}], rax
cld
mov rsi, 0x500000
lea rdi, [r15+256]
mov ecx, 8192
rep movsb
${XMM.map((x, i) => `movdqu [r15+${8448 + i * 16}], ${x}`).join("\n")}
; reset the data pages for the next case
mov rdi, 0x500000
mov ecx, 8192
mov al, 0x5A
rep stosb
ret
`;
        body += `call case_${c}\n`;
    }
    const source = long_mode_guest(body + `mov rsp, 0x3F0000\n`, `
${functions}
align 4096
leaf_near:
add r12, 7
xor r11, r12
ret
align 4096
leaf_far:
lea r12, [r12+r11*2+3]
ror r11, 5
ret
align 16
data: times 8192 db 0
`);
    const dir = assemble(`page-fuzz-${guest}`, source.replace("high_mode:\n", "high_mode:\nmov rdi, 0x500000\nmov ecx, 8192\nmov al, 0x5A\nrep stosb\n"));
    const length = 8 + cases * RECORD;
    const run = async jit => {
        const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
        const emulator = new V86({graphics_adapter: "bochs_vga", multiboot: {url: dir + "guest.bin"}, memory_size: 32 << 20, acpi: true,
            disable_jit: !jit, experimental_smp_jit: true, ir_sync_publication: true, autostart: false, log_level: 0});
        try
        {
            await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
            const cpu = emulator.v86.cpu;
            const deadline = performance.now() + 120000;
            let rounds = 0;
            while(new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(RESULT, true) !== MAGIC)
            {
                if(performance.now() > deadline) throw new Error("guest timed out: " + JSON.stringify(cpu.get_diagnostics()));
                cpu.run_cores();
                if((++rounds & 63) === 0) await yield_event();
            }
            const native = jit ? cpu.wm.exports.x64_page_stat(1) : 0;
            return {result: Buffer.from(cpu.mem8.slice(RESULT, RESULT + length)), native,
                stats: jit ? Array.from({length: 13}, (_, i) => cpu.wm.exports.x64_page_stat(i)) : []};
        }
        finally { await emulator.destroy(); }
    };
    const reference = await run(false);
    const compiled = await run(true);
    native_total += compiled.native;
    for(let c = 0; c < cases; c++)
    {
        const at = 8 + c * RECORD;
        const a = reference.result.subarray(at, at + RECORD), b = compiled.result.subarray(at, at + RECORD);
        if(!a.equals(b))
        {
            failures++;
            const names = [...GPR64, "r13", "r14", "r15", "flags"];
            const diffs = [];
            for(let i = 0; i < 16; i++) if(a.readBigUInt64LE(i * 8) !== b.readBigUInt64LE(i * 8)) diffs.push(`${names[i]}: interpreter ${a.readBigUInt64LE(i * 8).toString(16)} page ${b.readBigUInt64LE(i * 8).toString(16)}`);
            for(let i = 256; i < 8448; i++) if(a[i] !== b[i]) { diffs.push(`data+${i - 256}: ${a[i].toString(16)} vs ${b[i].toString(16)}`); if(diffs.length > 24) break; }
            for(let i = 0; i < 16; i++) if(!a.subarray(8448 + i * 16, 8464 + i * 16).equals(b.subarray(8448 + i * 16, 8464 + i * 16)))
                diffs.push(`xmm${i}: interpreter ${a.subarray(8448 + i * 16, 8464 + i * 16).toString("hex")} page ${b.subarray(8448 + i * 16, 8464 + i * 16).toString("hex")}`);
            console.log(`FAIL guest ${guest} (seed ${first_seed}) case ${c}:\n  ` + diffs.join("\n  "));
        }
    }
    console.log(`guest ${guest} (seed ${first_seed}): ${cases} cases, native retired ${compiled.native}, stats ${JSON.stringify(compiled.stats)}`);
    assert.ok(compiled.native > cases * ITERATIONS * 5, "the page tier executed the loops");
}
assert.equal(failures, 0, `${failures} cases differ`);
console.log(`PASS page fuzz: ${guests * cases} programs identical to the interpreter (${native_total} native instructions)`);
                                                                                                                                                                                                                                                                                                                          source/v64/tests/x64/page_system.mjs                                                                0000644 0000000 0000000 00000032055 00000000000 014507  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// System behavior of the x64 page tier (src/rust/x64/pagegen.rs, pages.rs)
// in hot loops, against QEMU TCG and the wide interpreter:
// - CPL3 loops (the access cache's user tables) and a user access to a
//   supervisor page from compiled code;
// - #PF on a not-present page, CR0.WP write faults on a read-only page after
//   reads of it were cached, and NX instruction fetches, each resuming the
//   loop through the fault handler (the page function retries the access in
//   the interpreter, which delivers the fault);
// - one backing page run through two linear aliases (position-independent
//   functions);
// - LOCKed read-modify-writes crossing into a not-present page after they
//   were compiled: #PF at the second page with no partial commit;
// - self-modifying code: a loop patching an immediate of a function in
//   another compiled page, and an instruction later in its own page.
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";

const RESULT = 0x300000;
const scenarios = [];
// `expected`: fields asserted from the SDM where QEMU TCG differs
const add = (name, code, expected = {}) => scenarios.push({name, code, expected});

add("user loop and supervisor fault", `
mov ecx, 0xC0000081
xor eax, eax
mov edx, 0x00200018
wrmsr
mov ecx, 0xC0000082
lea rax, [rel .back]
mov rdx, rax
shr rdx, 32
wrmsr
mov ecx, 0xC0000084
xor eax, eax
xor edx, edx
wrmsr
push 0x23
push 0x3D0000
push 2
push 0x33
lea rax, [rel .user]
push rax
iretq
.user:
mov rsi, 0x600000
mov ecx, 40000
xor eax, eax
xor r9, r9
.uloop:
mov edx, ecx
and edx, 511
add rax, [rsi+rdx*8]
mov [rsi+rdx*8], rax
xor rax, rdx
test ecx, 1023
jnz .unext
lea rbx, [rel .uafter]
mov [0x500010], rbx
mov rbx, [0xA00008]
.uafter:
inc r9
.unext:
dec ecx
jnz .uloop
mov qword [0x500010], 0
mov r8, rax
syscall
.back:
mov rsp, 0x3F0000
mov edx, 0x10
mov ss, edx
mov r10, rcx
mov r11, [0x600100]`);

add("not-present page faults", `
lea rax, [rel .kafter]
mov [0x500010], rax
mov ecx, 30000
xor r8, r8
xor r9, r9
.kloop:
mov rbx, 0x700000
test ecx, 7
jnz .mapped
mov rbx, 0x40001008
.mapped:
mov rax, [rbx]
add r8, rax
add qword [rbx+8], rcx
jmp .knext
.kafter:
inc r9
.knext:
dec ecx
jnz .kloop
mov qword [0x500010], 0
mov r10, [0x700008]`);

add("write-protect faults after cached reads", `
lea rax, [rel .wafter]
mov [0x500010], rax
mov rsi, 0x800000
mov ecx, 30000
xor r8, r8
xor r9, r9
.wloop:
mov edx, ecx
and edx, 511
add r8, [rsi+rdx*8]
test ecx, 15
jnz .wnext
mov [rsi+rdx*8], r8
.wafter:
inc r9
.wnext:
dec ecx
jnz .wloop
mov qword [0x500010], 0`);

add("NX fetch faults", `
lea rax, [rel .nafter]
mov [0x500010], rax
mov ecx, 5000
xor r9, r9
mov r10, 0xC00000
.nloop:
call r10
.nafter:
inc r9
dec ecx
jnz .nloop
mov qword [0x500010], 0
mov r8, rsp`);

// Cross-core atomicity in compiled code: LOCKed read-modify-writes (and implicitly
// locked XCHG) warmed on a page-crossing operand, then aimed across into a
// not-present page: #PF at the second page, nothing written to the first.
add("LOCK operations crossing into a not-present page", `
mov rdi, 0x204000
mov eax, 0xE00007
mov ecx, 512
.ptl:
mov [rdi], rax
add eax, 0x1000
add rdi, 8
loop .ptl
mov qword [0x204008], 0
mov qword [0x202000+7*8], 0x204007
mov rax, cr3
mov cr3, rax
mov word [0xE00FFE], 0x3344
lea rax, [rel .lafter]
mov [0x500010], rax
mov ecx, 20000
xor r8, r8
xor r9, r9
xor edx, edx
.lloop:
mov rsi, 0xE02FFE
test ecx, 7
jnz .lmapped
mov rsi, 0xE00FFE
.lmapped:
mov eax, ecx
lock xadd [rsi], eax
add r8, rax
lock add dword [rsi], ecx
xchg [rsi], edx
lock or dword [rsi], 0x100
lock btc dword [rsi], 3
mov eax, [rsi]
lea ebx, [rax+rcx]
lock cmpxchg [rsi], ebx
add r8, rax
jmp .lnext
.lafter:
inc r9
.lnext:
dec ecx
jnz .lloop
mov qword [0x500010], 0
movzx r10d, word [0xE00FFE]
mov r11d, [0xE02FFE]
mov qword [0x202000+7*8], 0xE00087
mov rax, cr3
mov cr3, rax`,
// A read-modify-write checks its operand for writing (W=1 in the #PF error
// code, as on Intel); QEMU 10.2 falls back to a plain load for a
// page-crossing atomic and reports a read (0).
{5: 2n});

add("patching a compiled function in another page", `
mov ecx, 30000
xor r10, r10
.sloop:
call smc_target
test ecx, 511
jnz .snext
inc byte [rel smc_target+3]
.snext:
dec ecx
jnz .sloop
mov r8, r10
movzx r9, byte [rel smc_target+3]`);

add("patching the running page", `
mov ecx, 30000
xor r11, r11
.ploop:
mov eax, ecx
shr eax, 6
mov byte [rel .patched+1], al
.patched:
mov bl, 0
movzx rbx, bl
add r11, rbx
dec ecx
jnz .ploop
mov r8, r11`);

add("one page function at two linear aliases", `
mov ecx, 20000
xor r10, r10
xor r11, r11
.aloop:
lea rax, [rel alias_target]
call rax
mov eax, alias_target
call rax
dec ecx
jnz .aloop
mov r8, [rel alias_data]
mov r9, [alias_data]`);

// INVLPG after switching a 4 KiB PTE between two backing pages: data reads
// must come from the new page, and code that remaps its own page must fetch
// the instruction after INVLPG from the new page (targeted invalidation of
// the access cache and of the cached code translation)
add("INVLPG remaps a code and data page", `
mov rdi, 0x340000
mov eax, 0xE00003
mov ecx, 512
.ptfill:
mov [rdi], rax
add rax, 0x1000
add rdi, 8
dec ecx
jnz .ptfill
mov qword [0x202000+7*8], 0x340003
mov rax, cr3
mov cr3, rax
; both pages: mov [0x340000], rdx / invlpg [0xE00000] / mov eax, <1 or 2> / ret
mov rax, 0x0034000025148948
mov [0xE01000], rax
mov [0xE02000], rax
mov rax, 0x00E00000253C010F
mov [0xE01008], rax
mov [0xE02008], rax
mov rax, 0x0000C300000001B8
mov [0xE01010], rax
mov rax, 0x0000C300000002B8
mov [0xE02010], rax
mov qword [0xE01800], 11
mov qword [0xE02800], 22
mov ecx, 20000
xor r10, r10
xor r11, r11
.rloop:
mov eax, ecx
and eax, 1
shl eax, 12
add eax, 0xE01003
mov [0x340000], rax
invlpg [0xE00000]
lea r11, [r11 + r11*2]
add r11, [0xE00800]
xor eax, 0x3000
mov rdx, rax
mov rax, 0xE00000
call rax
lea r10, [r10 + r10*2]
add r10, rax
dec ecx
jnz .rloop
mov r8, r10
mov r9, r11`);

// MOV CR3 with CR4.PGE: a non-global PTE switched between two backing
// pages must take effect after the CR3 reload, for data and for code; a
// global page (unchanged) stays usable. Uses the page table of the INVLPG
// scenario (0xE00000..0xFFFFFF in 4 KiB pages).
add("CR3 reload keeps global pages, drops the others", `
mov rax, cr4
or rax, 0x80
mov cr4, rax
mov rax, 0x0000C300000003B8
mov [0xE03000], rax
mov rax, 0x0000C300000004B8
mov [0xE04000], rax
mov qword [0xE03800], 33
mov qword [0xE04800], 44
mov qword [0xE05800], 55
mov qword [0x340000 + 0x10*8], 0xE05103
mov ecx, 20000
xor r10, r10
xor r11, r11
.cr3loop:
mov eax, ecx
and eax, 1
shl eax, 12
add eax, 0xE03003
mov [0x340000], rax
mov rax, cr3
mov cr3, rax
lea r11, [r11 + r11*2]
add r11, [0xE00800]
add r11, [0xE10800]
mov rax, 0xE00000
call rax
lea r10, [r10 + r10*2]
add r10, rax
dec ecx
jnz .cr3loop
mov rax, cr4
and rax, ~0x80
mov cr4, rax
mov r8, r10
mov r9, r11`);

// A loop whose body straddles a page boundary: MOV r64, imm64 is split
// across the two pages (stepped in place), and the loop branch returns to
// the first page
add("instruction across a page boundary in a loop", `
mov ecx, 30000
xor r10, r10
jmp .straddle
align 4096
times 4096 - 8 db 0xCC
.straddle:
add r10, rcx
mov rax, 0x1122334455667788
xor r10, rax
rol r10, 7
dec ecx
jnz .straddle
mov r8, r10`);

// EFLAGS produced lazily on one page and read on the next (the record is
// passed along when page functions chain): CMP, then ADD + INC (INC keeps
// CF), consumed by SETcc, ADC and a conditional branch
add("lazy flags across a page transition", `
mov ecx, 20000
xor r10, r10
xor r11, r11
.flagloop:
mov eax, ecx
imul eax, eax, 0x9E3779B1
cmp eax, 0x80000000
jmp .flagpage1
.flagback:
dec ecx
jnz .flagloop
mov r8, r10
mov r9, r11
jmp .flagdone
align 4096
.flagpage1:
setb dl
seto bl
movzx edx, dl
movzx ebx, bl
lea r10, [r10 + rdx*2]
add r10, rbx
mov rax, rcx
shl rax, 40
add rax, r11
inc r11
jmp .flagpage2
align 4096
.flagpage2:
adc r10, 3
sets dl
movzx edx, dl
add r11, rdx
jo .flagover
jmp .flagback
.flagover:
add r10, 1000
jmp .flagback
.flagdone:`);

add("control register reads in a loop", `
mov ecx, 20000
xor r10, r10
xor r11, r11
.crloop:
mov rax, cr0
and eax, 0x80010001
add r10, rax
mov rbx, cr3
add r10, rbx
mov rdx, cr4
and edx, 0x20
add r11, rdx
mov r8, cr2
xor r11, r8
dec ecx
jnz .crloop
mov r8, r10
mov r9, r11`);

add("STI shadow before a pending self-IPI", `
mov al, 0xFF
out 0x21, al
out 0xA1, al
mov rbx, 0xFEE00000
mov dword [rbx+0xF0], 0x1FF
lea rax, [rel handler_64]
lea rdi, [rel idt+64*16]
mov word [rdi], ax
mov rdx, rax
shr rdx, 16
mov word [rdi+6], dx
shr rdx, 16
mov dword [rdi+8], edx
xor eax, eax
xor edx, edx
xor r9, r9
xor r10, r10
xor r11, r11
mov ecx, 3000
.iloop:
mov dword [rbx+0x300], 0x40040
sti
inc rax
inc rdx
cli
dec ecx
jnz .iloop
mov r8, rax`);

// Each scenario has its own code page (SMC scenarios exhaust their page's
// recompilations).
const body = scenarios.map((s, n) => `
align 4096
; ${s.name} (the fault record starts clear)
mov qword [0x500020], 0
mov qword [0x500028], 0
mov qword [0x500030], 0
${s.code}
mov rdi, ${RESULT + 8 + n * 64}
mov [rdi], r8
mov [rdi+8], r9
mov [rdi+16], r10
mov [rdi+24], r11
mov rax, [0x500020]
mov [rdi+32], rax
mov rax, [0x500028]
mov [rdi+40], rax
mov rax, [0x500030]
mov [rdi+48], rax
`).join("\n");

const source = `bits 32
org 0x100000
%define HIGH 0xFFFF800000000000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr32]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x3F0000
mov dword [0x200000],0x201007
mov dword [0x200800],0x201007
mov dword [0x201000],0x202007
mov edi,0x202000
mov eax,0x87
mov ecx,512
.pages:
mov [edi],eax
add eax,0x200000
add edi,8
loop .pages
; 0x800000: user read-only, 0xA00000: supervisor, 0xC00000: no-execute,
; 0xFEE00000: local APIC (uncached)
mov dword [0x201000+3*8],0x203003
mov dword [0x203000+0x1F7*8],0xFEE0009B
mov dword [0x202000+4*8],0x800085
mov dword [0x202000+5*8],0xA00083
mov dword [0x202000+6*8+4],0x80000000
mov eax,cr4
or eax,0x20
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x901
xor edx,edx
wrmsr
mov eax,cr0
or eax,0x80010001
mov cr0,eax
jmp 24:long_mode
bits 64
long_mode:
mov rax,HIGH+high_mode
jmp rax
high_mode:
lgdt [rel gdtr64]
lidt [rel idtr64]
lea rax,[rel tss]
mov word [rel gdt+58],ax
shr rax,16
mov byte [rel gdt+60],al
mov byte [rel gdt+63],ah
shr rax,16
mov dword [rel gdt+64],eax
mov rax,HIGH+0x3E0000
mov [rel tss+4],rax
mov ax,0x38
ltr ax
lea rdi,[rel idt]
mov ecx,256
lea rax,[rel unexpected]
.init_idt:
mov word [rdi],ax
mov word [rdi+2],0x18
mov word [rdi+4],0x8E00
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
mov dword [rdi+12],0
add rdi,16
loop .init_idt
lea rax,[rel handler_14]
lea rdi,[rel idt+14*16]
mov word [rdi],ax
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
mov qword [0x500010],0
mov byte [0xC00000],0xC3
${body}
mov dword [${RESULT}],0xC064C064
hlt
jmp $
handler_14:
push rax
mov rax,[rsp+8]
mov [0x500028],rax
mov qword [0x500020],14
mov rax,cr2
mov [0x500030],rax
mov rax,[0x500010]
test rax,rax
jz .return
mov [rsp+16],rax
.return:
pop rax
add rsp,8
iretq
handler_64:
add r10, rax
add r11, rdx
inc r9
mov dword [rbx+0xB0], 0
iretq
unexpected:
cli
hlt
jmp $
align 4096
smc_target:
add r10, byte 5
ret
align 4096
alias_target:
lea rdx, [rel alias_data]
add r10, [rdx]
inc qword [rdx]
add r11, rdx
call smc_target
lea rax, [rel .back]
add r11, rax
.back:
ret
align 4096
alias_data: dq 0
align 16
gdt:
dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
dq 0x00CFF2000000FFFF,0x00CFFA000000FFFF,0x00AFFA000000FFFF
dq 0x0000890000000067,0
dq 0,0
gdtr32: dw 87
dd gdt
gdtr64: dw 87
dq HIGH+gdt
idtr64: dw 4095
dq HIGH+idt
align 16
tss: times 104 db 0
align 16
idt: times 4096 db 0
image_end:
`;
const dir = assemble("page-system", source);
const config = {length: 8 + scenarios.length * 64, timeout: 120000};
const oracle = await reference(dir, config);
console.log(`QEMU: ${scenarios.length} page tier system scenarios`);
const compare = (result, label) => {
    for(const [n, s] of scenarios.entries()) for(let field = 0; field < 7; field++)
    {
        const at = 8 + n * 64 + field * 8;
        const expected = s.expected[field] ?? oracle.readBigUInt64LE(at);
        assert.equal(result.readBigUInt64LE(at).toString(16), expected.toString(16),
            `${label}: ${s.name}, ${["r8", "r9", "r10", "r11", "vector", "error", "cr2"][field]}`);
    }
};
compare(await actual(dir, config), "interpreter");
let stats;
compare(await actual(dir, {...config, options: {disable_jit: false, ir_sync_publication: true}, inspect: emulator => {
    stats = Array.from({length: 13}, (_, i) => emulator.v86.cpu.wm.exports.x64_page_stat(i));
}}), "page tier");
const [compiled, retired, retries, , , invalidated] = stats;
console.log(`page tier: compiled ${compiled}, native ${retired}, retries ${retries}, invalidated ${invalidated}, stats ${JSON.stringify(stats)}`);
assert.ok(retired > 400000, "the loops ran in page functions");
assert.ok(retries > 1000, "faulting accesses left compiled code to be interpreted");
assert.ok(invalidated >= 10, "code writes retired compiled pages");
console.log("PASS page tier system scenarios agree with QEMU and the interpreter");
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/tests/x64/poweroff_loop.mjs                                                              0000644 0000000 0000000 00000020426 00000000000 015046  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Repeated boot -> poweroff -> S5 -> power-on of x86_64 Linux (Alpine virt,
// as tests/x64/linux_boot.mjs prepares it) on several cores, to catch the
// intermittent poweroff that once ended with every core idle and no ACPI S5
// (docs/x86-64.md, known limits). A cycle without S5
// within 120 s of "poweroff" writes build/x64-linux/poweroff-loop-<cycle>-late.json
// (diagnostics, serial tail) and waits POWEROFF_LATE_S (900) more seconds: a
// late S5 is counted as slow, none at all fails with the scheduler's view of
// every core and the serial console's interrupt state in poweroff-loop-<cycle>.json.
//
// POWEROFF_CYCLES (20), X64_CORES (4), X64_JIT (1), POWEROFF_PARALLEL=1.
import assert from "node:assert/strict";
import fs from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import { ROOT as root, IMAGES, directory_of } from "../lib/alpine_image.mjs";

// (the pinned ISO and its unpacked files: tests/lib/alpine_image.mjs)
const directory = directory_of("x86_64");
const kernel = directory + "boot/vmlinuz-virt", initrd = directory + "boot/initramfs-virt";
const iso = directory + IMAGES["x86_64-virt"].name;
for(const file of [kernel, initrd, iso]) assert.ok(fs.existsSync(file), file + " (run tests/x64/linux_boot.mjs once)");
const cycles = +(process.env.POWEROFF_CYCLES || 20), cores = +(process.env.X64_CORES || 4);
const jit = process.env.X64_JIT !== "0";
const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const emulator = new V86({
    graphics_adapter: "bochs_vga",
    bios: { url: root + "bios/seabios.bin" }, vga_bios: { url: root + "bios/vgabios.bin" },
    bzimage: { url: kernel }, initrd: { url: initrd }, cdrom: { url: iso },
    cmdline: "console=ttyS0,115200 loglevel=7 nokaslr panic=-1 modules=loop,squashfs,sd-mod,usb-storage",
    memory_size: 512 << 20, cpu_cores: cores, acpi: true, autostart: false, cpu_type: "x86_64",
    disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: true, log_level: 0,
    ...(+process.env.POWEROFF_PARALLEL ? { parallel: true, wasm_path: root + "build/v86-parallel.wasm" } : {}),
});
let serial = "";
emulator.add_listener("serial0-output-byte", byte => { serial += String.fromCharCode(byte); if(serial.length > 1 << 20) serial = serial.slice(-(1 << 19)); });
await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
const cpu = emulator.v86.cpu;
// every byte of the serial console, for a failure report (a panic reboots: panic=-1)
let serial_log = "";
emulator.add_listener("serial0-output-byte", byte => { serial_log += String.fromCharCode(byte); });
let cycle_now = 0;
const wait_for = async (pattern, from, what, ms) => {
    const limit = performance.now() + ms;
    while(!pattern.test(serial.slice(from)))
    {
        if(performance.now() > limit)
        {
            fs.writeFileSync(directory + `poweroff-loop-${cycle_now}-error.json`, JSON.stringify({ what,
                diagnostics: cpu.get_diagnostics(), last_reset: cpu.last_reset || null }, null, 1));
            fs.writeFileSync(directory + `poweroff-loop-${cycle_now}-error.serial`, serial_log);
            throw new Error(`${what}: timed out (serial in poweroff-loop-${cycle_now}-error.serial); tail ${JSON.stringify(serial.slice(-2000))}`);
        }
        await delay(20);
    }
};
const started = performance.now();
const late = [];
for(let cycle = 1; cycle <= cycles; cycle++)
{
    cycle_now = cycle;
    let mark = serial.length;
    const t0 = performance.now();
    emulator.run();
    await wait_for(/localhost login:/, mark, `cycle ${cycle}: login prompt`, 900000);
    mark = serial.length;
    emulator.serial0_send("root\n");
    await wait_for(/localhost:~#/, mark, `cycle ${cycle}: shell`, 120000);
    mark = serial.length;
    emulator.serial0_send(`cat /sys/devices/system/cpu/online; echo READY_${cycle}\n`);
    await wait_for(new RegExp(`\\nREADY_${cycle}\\r?\\n`), mark, `cycle ${cycle}: command`, 120000);
    assert.match(serial.slice(mark), new RegExp(`\\n0-${cores - 1}\\r?\\n`), "every CPU online");
    const off = new Promise(resolve => emulator.add_listener("acpi-power-off", resolve));
    const poweroff_at = serial.length;
    const poweroff_time = performance.now();
    emulator.serial0_send("poweroff\n");
    let state = await Promise.race([off, delay(120000).then(() => null)]);
    if(state !== "S5")
    {
        // slow or stuck: the machine state now, then up to POWEROFF_LATE_S
        // more seconds for a late S5 (a loaded host may need them)
        const late_limit = +(process.env.POWEROFF_LATE_S || 900) * 1000;
        const late_report = { cycle, diagnostics: cpu.get_diagnostics(), serial: serial.slice(poweroff_at) };
        state = await Promise.race([off, delay(late_limit).then(() => null)]);
        if(state === "S5")
        {
            late.push({ cycle, seconds: Math.round((performance.now() - poweroff_time) / 1000) });
            fs.writeFileSync(directory + `poweroff-loop-${cycle}-late.json`, JSON.stringify(late_report, null, 1));
            console.log(`cycle ${cycle}: S5 only after ${late.at(-1).seconds} s`);
        }
    }
    if(state !== "S5")
    {
        // why a core does not run: the scheduler's view of every core, before
        // and after a few more rounds
        const { STATE_OFFSETS, CORE_STATE_RANGES } = await import("../../src/state_layout.js");
        const field = (core, offset, size) => {
            if(core === cpu.active_core)
            {
                const view = new DataView(cpu.wasm_memory.buffer, cpu.state_base + offset, size);
                return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
            }
            const index = CORE_STATE_RANGES.findIndex(([start, end]) => offset >= start && offset + size <= end);
            const bytes = cpu.cores[core].saved[index];
            const view = new DataView(bytes.buffer, bytes.byteOffset + offset - CORE_STATE_RANGES[index][0], size);
            return size === 1 ? view.getUint8(0) : view.getInt32(0, true);
        };
        const scheduler = () => cpu.cores.map((state, core) => ({ core, running: state.running,
            runnable: cpu.core_runnable(core), in_hlt: field(core, STATE_OFFSETS.in_hlt, 1),
            interrupt_shadow: field(core, STATE_OFFSETS.interrupt_shadow, 1), flags: field(core, STATE_OFFSETS.flags, 4) >>> 0,
            interrupt_pending: !!cpu.apic_core_interrupt_pending(core), nmi_pending: !!cpu.apic_core_nmi_pending(core),
            events: cpu.apic_peek_core_events(core), shutdown: cpu.wm.exports.exception_shutdown(core),
            retired: cpu.wm.exports.core_statistics_get(core, 0) }));
        const before = scheduler();
        // the serial console's interrupt: the UART's pending conditions and the
        // IOAPIC input 4 (redirection entry, IRR and line level)
        const uart = cpu.devices.uart0;
        const ioapic = new Uint32Array(cpu.wasm_memory.buffer, cpu.get_ioapic_addr(), 52);
        const irq_state = () => ({ uart: { ier: uart.ier, iir: uart.iir, ints: uart.ints, lsr: uart.lsr, lcr: uart.line_control,
            mcr: uart.modem_control, input: uart.input.length },
            ioapic4: { config: ioapic[4] >>> 0, destination: ioapic[24 + 4] >>> 0, irr: ioapic[50] >>> 0 & 16, line: ioapic[51] >>> 0 & 16 } });
        const irq_before = irq_state();
        await delay(2000);
        const report = { cycle, diagnostics: cpu.get_diagnostics(), last_reset: cpu.last_reset || null,
            scheduler: { before, after_2s: scheduler() }, irq: { before: irq_before, after_2s: irq_state() },
            serial: serial.slice(poweroff_at) };
        fs.writeFileSync(directory + `poweroff-loop-${cycle}.json`, JSON.stringify(report, null, 1));
        throw new Error(`cycle ${cycle}: no ACPI S5 within 120 s of poweroff: ` +
            JSON.stringify(report.diagnostics.cores.map(core => [core.state, core.linear_ip, core.halted, core.interrupts_enabled])));
    }
    await delay(100);
    assert.ok(!emulator.is_running(), "stopped in S5");
    console.log(`cycle ${cycle}: boot and poweroff in ${((performance.now() - t0) / 1000).toFixed(0)} s, S5`);
}
await emulator.destroy();
console.log(`X64_POWEROFF_LOOP_PASS ${cycles} cycles on ${cores} cores in ${((performance.now() - started) / 60000).toFixed(1)} min` +
    (late.length ? `; S5 later than 120 s in ${late.length}: ${JSON.stringify(late)}` : ""));
                                                                                                                                                                                                                                          source/v64/tests/x64/profile_options.mjs                                                            0000644 0000000 0000000 00000006246 00000000000 015405  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Embedder options for 64-bit guests:
// - memory_size above the wasm32 limit is reduced to 2 GiB - 128 KiB instead
//   of wrapping (8 GiB used to become 0 bytes, then the BIOS load failed);
// - cpu_type: "x86_64" presents the x86-64 CPU profile: CPUID.80000001h:EDX
//   long mode (bit 29), NX (20) and SYSCALL (11) only when it is set; an
//   unknown cpu_type, or the removed experimental_x64, fails in the
//   constructor (and so does arm64 with a PC display).
import assert from "node:assert/strict";
import url from "node:url";
import {assemble, actual} from "./guest_runner.mjs";

const root = url.fileURLToPath(new URL("../../", import.meta.url));
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const MAX = 2 ** 31 - 128 * 1024;

for(const gib of [4, 6, 8])
{
    const emulator = new V86({graphics_adapter: "bochs_vga", bios: {url: root + "bios/seabios.bin"}, vga_bios: {url: root + "bios/vgabios.bin"},
        memory_size: gib * 2 ** 30, autostart: false, log_level: 0});
    const error = await new Promise(resolve => {
        emulator.add_listener("emulator-loaded", () => resolve(null));
        emulator.add_listener("emulator-error", resolve);
    });
    assert.equal(error, null, `${gib} GiB: ${error}`);
    assert.equal(emulator.v86.cpu.memory_size[0] >>> 0, MAX, `${gib} GiB is reduced to the maximum`);
    await emulator.destroy();
    console.log(`PASS memory_size ${gib} GiB loads with ${MAX / 2 ** 20} MiB`);
}

const directory = assemble("profile-options", `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
mov eax,0x80000001
cpuid
mov [0x300004],edx
mov dword [0x300000],0xC064C064
hlt
jmp $
image_end:
`);
const X64_EDX = 1 << 29 | 1 << 20 | 1 << 11;
for(const [options, expected] of [
    [{}, 0],
    [{cpu_type: "x86"}, 0],
    [{cpu_type: "x86_64"}, X64_EDX],
])
{
    const result = await actual(directory, {length: 8, options});
    const edx = result.readUInt32LE(4);
    const name = JSON.stringify(options);
    assert.equal(edx & X64_EDX, expected >>> 0, `${name}, EDX ${edx.toString(16)}`);
    console.log(`PASS ${name} -> CPUID.80000001h:EDX ${edx.toString(16)}`);
}

for(const cpu_type of ["aarch64", "x86-64", ""])
{
    assert.throws(() => new V86({graphics_adapter: "bochs_vga", cpu_type, autostart: false}),
        /Unknown cpu_type .*supported: "x86", "x86_64", "arm64"/, `cpu_type ${JSON.stringify(cpu_type)} is refused`);
    console.log(`PASS cpu_type ${JSON.stringify(cpu_type)} is refused`);
}
// (arm64 runs on machine_type "virt", which has no VGA: tests/api/arm64-options.js)
assert.throws(() => new V86({graphics_adapter: "bochs_vga", cpu_type: "arm64", autostart: false}), /is not on machine_type "virt"/);
console.log("PASS cpu_type \"arm64\" with a PC display is refused");
for(const experimental_x64 of [true, false])
{
    assert.throws(() => new V86({graphics_adapter: "bochs_vga", experimental_x64, autostart: false}),
        /experimental_x64 was replaced by cpu_type: "x86_64"/, `experimental_x64: ${experimental_x64} is refused`);
    console.log(`PASS experimental_x64: ${experimental_x64} is refused`);
}
                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/x64/protected_mode_msrs.mjs                                                        0000644 0000000 0000000 00000011540 00000000000 016224  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The x86-64 CPU profile has its IA-32e MSRs outside long mode too: a 32-bit
// kernel on cpu_type: "x86_64" sees CPUID.(EAX=7,ECX=0):EDX[29] and reads
// IA32_ARCH_CAPABILITIES (0x10A) with EFER.LME clear. That used to reach the
// 32-bit MSR table, which lacks it, and the debug build aborted on the unknown
// MSR (Linux 4 stopped at "Booting the kernel."). In 32-bit protected mode,
// RDMSR reads the value a 64-bit OS reads (tests/platform/cpu-contract.json),
// WRMSR to it raises #GP (read-only), and KERNEL_GS_BASE and TSC_AUX keep what
// is written and fault on what long mode refuses. Interpreted, then compiled:
// the probe repeats until the x64 page tier compiles its page.
import assert from "node:assert/strict";
import fs from "node:fs";
import {assemble, actual, root} from "./guest_runner.mjs";

// (the #GP flag lives with the results: a store to the code page would keep
// the JIT from compiling the probe)
const OUT = 0x300000, FAULTED = OUT + 12, RECORDS = OUT + 16, ROUNDS = 100000;
const contract = JSON.parse(fs.readFileSync(root + "tests/platform/cpu-contract.json", "utf8"));
const [arch_high, arch_low] = contract.profiles["x64-1"].msrs["0x0000010a"].split(":").map(x => parseInt(x, 16));
// [RDMSR or WRMSR, ECX, EDX, EAX written]
const STEPS = [
    ["read", 0xC0000080],
    ["read", 0x10A],
    ["write", 0x10A, 0, 0],
    ["write", 0xC0000102, 0xFFFF8000, 0x12345678],
    ["read", 0xC0000102],
    ["write", 0xC0000102, 0x00008000, 0],           // non-canonical
    ["write", 0xC0000103, 0, 0x2A],
    ["read", 0xC0000103],
    ["write", 0xC0000103, 1, 0x2A],                 // TSC_AUX is 32 bits
];
// per step: whether it raised #GP, then EAX and EDX after it
const EXPECTED = [
    [0, 0, 0],                                      // EFER: LME clear
    [0, arch_low, arch_high],
    [1, 0, 0],
    [0, 0x12345678, 0xFFFF8000],
    [0, 0x12345678, 0xFFFF8000],
    [1, 0, 0x00008000],
    [0, 0x2A, 0],
    [0, 0x2A, 0],
    [1, 0x2A, 1],
];

const directory = assemble("protected-mode-msrs", `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
; a GDT of its own (exceptions reload CS from it), then an IDT whose #GP
; handler skips the faulting RDMSR/WRMSR (2 bytes) and flags it
lgdt [gdtr]
jmp 8:.flat
.flat:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x200000
mov edi,idt
mov ecx,32
.gate:
mov eax,other
mov [edi],ax
mov word [edi + 2],8
mov word [edi + 4],0x8E00
shr eax,16
mov [edi + 6],ax
add edi,8
loop .gate
mov eax,gp_handler
mov [idt + 13 * 8],ax
shr eax,16
mov [idt + 13 * 8 + 6],ax
lidt [idtr]
mov eax,7
xor ecx,ecx
cpuid
mov [${OUT + 8}],edx
mov ebp,${ROUNDS}
.round:
call probe
dec ebp
jnz .round
mov dword [${OUT}],0xC064C064
.halt:
hlt
jmp .halt
probe:
mov edi,${RECORDS}
${STEPS.map(([op, msr, edx = 0, eax = 0]) => op === "read" ?
    `mov ecx,${msr}\ncall read` :
    `mov ecx,${msr}\nmov edx,${edx}\nmov eax,${eax}\ncall write`).join("\n")}
ret
read:
xor eax,eax
xor edx,edx
mov dword [${FAULTED}],0
rdmsr
jmp record
write:
mov dword [${FAULTED}],0
wrmsr
record:
mov ebx,[${FAULTED}]
mov [edi],ebx
mov [edi + 4],eax
mov [edi + 8],edx
add edi,12
ret
gp_handler:
mov dword [${FAULTED}],1
add esp,4                       ; the error code
add dword [esp],2               ; past RDMSR/WRMSR
iret
other:
mov dword [${OUT + 4}],0xBAD
.stop:
hlt
jmp .stop
align 8
gdt: dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF
gdtr: dw 3 * 8 - 1
dd gdt
idtr: dw 32 * 8 - 1
dd idt
idt: times 32 dq 0
image_end:
`);

const hex = x => "0x" + (x >>> 0).toString(16);
for(const [name, jit] of [["interpreter", false], ["JIT", true]])
{
    let ir;
    const result = await actual(directory, {length: 16 + 12 * STEPS.length, timeout: 120000,
        options: {cpu_type: "x86_64", ...(jit ? {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true} : {})},
        inspect: emulator => { ir = emulator.v86.cpu.get_jit_info().ir; }});
    assert.equal(result.readUInt32LE(4), 0, `${name}: no exception other than #GP`);
    assert.ok(result.readUInt32LE(8) & 1 << 29, `${name}: CPUID.(EAX=7,ECX=0):EDX[29] advertises IA32_ARCH_CAPABILITIES`);
    STEPS.forEach(([op, msr], i) => {
        const at = 16 + 12 * i;
        const observed = [0, 4, 8].map(offset => result.readUInt32LE(at + offset));
        assert.deepEqual(observed, EXPECTED[i].map(x => x >>> 0),
            `${name}: ${op === "read" ? "RDMSR" : "WRMSR"} ${hex(msr)}: #GP, EAX, EDX ${observed.map(hex)}, expected ${EXPECTED[i].map(hex)}`);
    });
    // (32-bit protected-mode code in the x64 page tier)
    if(jit) assert.ok(ir.page_tier.activations > 0 && ir.page_tier.native_instructions > 0,
        `compiled code ran: ${JSON.stringify(ir.page_tier)}`);
    console.log(`PASS 32-bit protected mode on the x86-64 profile (${name}): IA32_ARCH_CAPABILITIES = ${hex(arch_high)}:${hex(arch_low)}, read-only; KERNEL_GS_BASE and TSC_AUX`);
}
                                                                                                                                                                source/v64/tests/x64/protected_mode_rdtscp.mjs                                                      0000644 0000000 0000000 00000021624 00000000000 016543  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The x86-64 CPU profile advertises RDTSCP (CPUID.80000001h:EDX[27]) in every
// mode, and a 32-bit Linux kernel on cpu_type: "x86_64" uses it with EFER.LMA
// clear (rdtsc_ordered). RDTSCP used to be implemented only by the long-mode
// engine; 32-bit code took #UD. In 32-bit protected mode it returns the TSC in
// EDX:EAX and IA32_TSC_AUX in ECX (all 32 bits, with an operand-size prefix
// too), and with CR4.TSD it raises #GP at CPL 3 but not at CPL 0. The legacy
// profile does not advertise it and keeps #UD. Interpreted, then compiled:
// the probe repeats until the IR compiles its page, and a new TSC_AUX each
// round shows every RDTSCP reads the current one.
// Compiled compatibility-mode code (EFER.LMA set) steps through the same
// 32-bit instruction, which must agree with the long-mode engine: RDTSCP in
// either profile there.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

// (the flags live with the results: a store to the code page would keep the
// JIT from compiling the probe)
const OUT = 0x300000, BAD = OUT + 4, FEATURES = OUT + 8, FAULTED = OUT + 12, MISMATCHES = OUT + 16,
    FAULTS = OUT + 20, RECORDS = OUT + 32, ROUNDS = 100000;
const TSS = 0x2F0000, KERNEL_STACK = 0x200000, INTERRUPT_STACK = 0x1F0000, USER_STACK = 0x1E0000;
// TSC_AUX in each round (the round counter counts down to 1)
const AUX = 0x12340000;
const SENTINELS = [0xEEEEEEEE, 0xDDDDDDDD, 0xCCCCCCCC];
const STEPS = ["CPL 0", "CPL 0, o16, CR4.TSD", "CPL 3, CR4.TSD", "CPL 3"];
// the vector each step raises, or 0
const EXPECTED = {x64: [0, 0, 13, 0], legacy: [6, 6, 6, 6]};

const directory = assemble("protected-mode-rdtscp", `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
%macro probe 0-1
mov dword [${FAULTED}],0
mov eax,${SENTINELS[0]}
mov edx,${SENTINELS[1]}
mov ecx,${SENTINELS[2]}
%1 rdtscp
call record
%endmacro
start:
cli
; a GDT with ring 3 segments and a TSS, then an IDT whose #UD and #GP
; handlers skip the faulting RDTSCP and flag it; INT 30h (clear CR4.TSD) and
; INT 31h (back to ring 0) are open to ring 3
lgdt [gdtr]
jmp 8:.flat
.flat:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,${KERNEL_STACK}
mov dword [${TSS + 4}],${INTERRUPT_STACK}
mov dword [${TSS + 8}],16
mov word [${TSS + 102}],104
mov ax,0x28
ltr ax
mov ebx,0
.gate:
mov eax,other
mov dx,0x8E00
call set_gate
inc ebx
cmp ebx,0x32
jb .gate
mov ebx,6
mov eax,ud_handler
call set_gate
mov ebx,13
mov eax,gp_handler
call set_gate
mov ebx,0x30
mov eax,clear_tsd
mov dx,0xEE00
call set_gate
mov ebx,0x31
mov eax,to_kernel
call set_gate
lidt [idtr]
mov eax,0x80000001
cpuid
mov [${FEATURES}],edx
mov ebp,${ROUNDS}
round:
mov edi,${RECORDS}
lea esi,[ebp + ${AUX}]
mov eax,cr4
and eax,~4
mov cr4,eax
; only a CPU with RDTSCP has TSC_AUX
test dword [${FEATURES}],1 << 27
jz .no_aux
mov ecx,0xC0000103
mov eax,esi
xor edx,edx
wrmsr
.no_aux:
rdtsc
mov [edi],eax
mov [edi + 4],edx
add edi,8
probe
mov eax,cr4
or eax,4
mov cr4,eax
probe o16
push 0x23
push ${USER_STACK}
push 2
push 0x1B
push .user
iret
.user:
mov ax,0x23
mov ds,ax
mov es,ax
probe
int 0x30
probe
int 0x31
round_end:
rdtsc
mov [edi],eax
mov [edi + 4],edx
dec ebp
jnz round
mov dword [${OUT}],0xC064C064
.halt:
hlt
jmp .halt
; [FAULTED], EAX, EDX, ECX; ECX must be this round's TSC_AUX unless it faulted
record:
mov ebx,[${FAULTED}]
mov [edi],ebx
mov [edi + 4],eax
mov [edi + 8],edx
mov [edi + 12],ecx
add edi,16
test ebx,ebx
jnz .faulted
cmp ecx,esi
je .done
inc dword [${MISMATCHES}]
jmp .done
.faulted:
inc dword [${FAULTS}]
.done:
ret
; eax: handler, ebx: vector, dx: type
set_gate:
mov [idt + ebx * 8],ax
mov word [idt + ebx * 8 + 2],8
mov [idt + ebx * 8 + 4],dx
shr eax,16
mov [idt + ebx * 8 + 6],ax
ret
gp_handler:
mov dword [${FAULTED}],13
add esp,4                       ; the error code
jmp skip
ud_handler:
mov dword [${FAULTED}],6
skip:                           ; past RDTSCP (3 bytes) or o16 RDTSCP (4)
push eax
mov eax,[esp + 4]
cmp byte [eax],0x66
pop eax
jne .short
inc dword [esp]
.short:
add dword [esp],3
iret
clear_tsd:
push eax
mov eax,cr4
and eax,~4
mov cr4,eax
pop eax
iret
to_kernel:
mov esp,${KERNEL_STACK}
mov ax,16
mov ds,ax
mov es,ax
jmp round_end
other:
mov dword [${BAD}],0xBAD
.stop:
hlt
jmp .stop
align 8
; (accessed bits set: segment loads leave the code page alone)
gdt: dq 0,0x00CF9B000000FFFF,0x00CF93000000FFFF,0x00CFFB000000FFFF,0x00CFF3000000FFFF
dd ${(TSS & 0xFFFF) << 16 | 0x67},${TSS & 0xFF000000 | 0x8900 | TSS >>> 16 & 0xFF}
gdtr: dw 6 * 8 - 1
dd gdt
idtr: dw 0x32 * 8 - 1
dd idt
idt: times 0x32 dq 0
image_end:
`);

const hex = x => "0x" + (x >>> 0).toString(16);
for(const [profile, cpu_type] of [["x64", "x86_64"], ["legacy", undefined]])
{
    const expected = EXPECTED[profile];
    for(const [name, jit] of [["interpreter", false], ["JIT", true]])
    {
        const run = `${profile} profile, ${name}`;
        let ir;
        const result = await actual(directory, {length: RECORDS + 8 + 16 * STEPS.length + 8 - OUT, timeout: 120000,
            options: {...(cpu_type ? {cpu_type} : {}), ...(jit ? {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true} : {})},
            inspect: emulator => { ir = emulator.v86.cpu.get_jit_info().ir; }});
        const word = at => result.readUInt32LE(at - OUT);
        const tsc = at => BigInt(word(at + 4)) << 32n | BigInt(word(at));
        assert.equal(word(BAD), 0, `${run}: no exception other than #UD and #GP`);
        assert.equal(!!(word(FEATURES) & 1 << 27), profile === "x64", `${run}: CPUID.80000001h:EDX[27] (RDTSCP)`);
        // the last round's records: its first RDTSC, the steps, its last RDTSC
        const times = [tsc(RECORDS)];
        STEPS.forEach((step, i) => {
            const at = RECORDS + 8 + 16 * i;
            const [vector, eax, edx, ecx] = [0, 4, 8, 12].map(offset => word(at + offset));
            assert.equal(vector, expected[i], `${run}: ${step}: raised ${vector}, expected ${expected[i]}`);
            if(vector)
            {
                assert.deepEqual([eax, edx, ecx].map(hex), SENTINELS.map(hex), `${run}: ${step}: the faulting RDTSCP left EAX, EDX, ECX alone`);
            }
            else
            {
                assert.equal(hex(ecx), hex(AUX + 1), `${run}: ${step}: ECX = TSC_AUX`);
                times.push(tsc(at + 4));
            }
        });
        times.push(tsc(RECORDS + 8 + 16 * STEPS.length));
        times.slice(1).forEach((time, i) => assert.ok(time >= times[i], `${run}: TSC goes backwards: ${times.map(time => "0x" + time.toString(16))}`));
        assert.equal(word(MISMATCHES), 0, `${run}: rounds where ECX was not that round's TSC_AUX`);
        assert.equal(word(FAULTS), ROUNDS * expected.filter(Boolean).length, `${run}: faults over all rounds`);
        // (32-bit protected-mode code in the x64 page tier)
        if(jit) assert.ok(ir.page_tier.activations > 0 && ir.page_tier.native_instructions > 0,
            `${run}: compiled code ran: ${JSON.stringify(ir.page_tier)}`);
        console.log(`PASS 32-bit RDTSCP (${run}): ${profile === "x64" ? "EDX:EAX = TSC, ECX = TSC_AUX, #GP at CPL 3 with CR4.TSD" : "#UD"}`);
    }
}

const COMPAT_AUX = 0x5A5A0001, ITERATIONS = 5000000;
const compat = assemble("compat-rdtscp", long_mode_guest(`
mov ecx,0xC0000103
mov eax,${COMPAT_AUX}
xor edx,edx
wrmsr
push 8
mov eax,compat_entry
push rax
o64 retf
back:
`, `
bits 32
; RDTSC, the last of the RDTSCPs, RDTSC; how many RDTSCPs missed TSC_AUX
compat_entry:
rdtsc
mov [${OUT + 16}],eax
mov [${OUT + 20}],edx
mov ebp,${ITERATIONS}
xor edi,edi
.loop:
mov ecx,${SENTINELS[2]}
rdtscp
cmp ecx,${COMPAT_AUX}
je .same
inc edi
.same:
dec ebp
jnz .loop
mov [${OUT + 24}],eax
mov [${OUT + 28}],edx
rdtsc
mov [${OUT + 32}],eax
mov [${OUT + 36}],edx
mov [${OUT + 12}],edi
jmp 0x18:back_to_64
bits 64
back_to_64:
mov rax,HIGH+back
jmp rax
`));
for(const [profile, cpu_type] of [["x64", "x86_64"], ["legacy", undefined]])
{
    for(const [name, jit] of [["interpreter", false], ["compat JIT", true]])
    {
        const run = `compatibility mode, ${profile} profile, ${name}`;
        let ir;
        const result = await actual(compat, {length: 40, timeout: 60000,
            options: {...(cpu_type ? {cpu_type} : {}), ...(jit ? {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true} : {})},
            inspect: emulator => { ir = emulator.v86.cpu.get_jit_info().ir; }});
        const tsc = at => BigInt(result.readUInt32LE(at + 4)) << 32n | BigInt(result.readUInt32LE(at));
        assert.equal(result.readUInt32LE(12), 0, `${run}: RDTSCPs whose ECX was not TSC_AUX`);
        assert.ok(tsc(16) <= tsc(24) && tsc(24) <= tsc(32), `${run}: RDTSCP's EDX:EAX between the RDTSCs`);
        // (32-bit protected-mode code in the x64 page tier)
        if(jit) assert.ok(ir.page_tier.activations > 0 && ir.page_tier.native_instructions > 0,
            `${run}: compiled code ran: ${JSON.stringify(ir.page_tier)}`);
        console.log(`PASS RDTSCP (${run})`);
    }
}
                                                                                                            source/v64/tests/x64/rep_strings.mjs                                                                0000644 0000000 0000000 00000012161 00000000000 014522  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// REP MOVS and REP STOS in 64-bit mode against QEMU, interpreted and with
// the x64 page tier: element sizes 1, 2, 4 and 8, both directions, one
// element up to more than a page (several interpreter steps), and source to
// destination distances around the elements' span, where an element reads
// what an earlier one wrote (LZ backreferences) or does not. The interpreter
// copies a chunk at once in the second case (x64::execute::bulk_string, as
// cpu::string), element by element in the first. The operands lie in 4 KiB
// pages mapped to scattered frames, as a process's memory is (the page
// tier's single-page template, the interpreter's chunks at page ends).
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const OUT = 0x300000, RESULTS = OUT + 0x100;
// 8 pages at 1 GiB, mapped in this order of the frames at FRAMES
const AREA = 0x40000000, PAGES = 8, FRAMES = 0x600000, ORDER = [3, 6, 1, 7, 0, 5, 2, 4];
const cases = [];
for(const size of [1, 2, 4, 8])
{
    for(const down of [false, true])
    {
        for(const bytes of [size, 7 * size, 1000, 5000])
        {
            const count = Math.max(1, Math.floor(bytes / size));
            const span = count * size;
            // the first element's address: 3 bytes past a page boundary in
            // the middle of the area (a backward string runs down from it)
            const src = AREA + 0x4003 + size;
            for(const distance of new Set([-(span + 3), -span, -span + 1, -size - 1, -size, -1, 0, 1, size - 1, size, size + 1, span - 1, span, span + 3]))
            {
                cases.push({movs: true, size, down, count, src, dst: src + distance});
            }
            for(const offset of [0x2FFD, 0x5001 + size])
            {
                cases.push({movs: false, size, down, count, src: 0, dst: AREA + offset});
            }
        }
    }
}
const KIND = c => (c.movs ? 0 : 4) + Math.log2(c.size);
const table = cases.map((c, n) => `dq ${KIND(c)},${+c.down},${c.count},${c.src},${c.dst},0x${(0x0123456789ABCDEFn + BigInt(n) * 0x1111n).toString(16)}`).join("\n");

const ROUNDS = 3;
const source = long_mode_guest(`
; the area's 4 KiB pages: PML4[0] -> PDPT 0x201000, entry 1 -> PD 0x203000 -> PT 0x204000
mov edi,0x203000
mov ecx,1024
xor eax,eax
.zero:
mov [rdi],rax
add rdi,8
dec ecx
jnz .zero
mov qword [0x201008],0x203003
mov qword [0x203000],0x204003
${ORDER.map((frame, page) => `mov qword [${0x204000 + 8 * page}],${FRAMES + frame * 4096 + 3}`).join("\n")}
mov rax,cr3
mov cr3,rax
mov r15d,${ROUNDS}
round_loop:
lea r12,[rel cases]
mov r13d,${cases.length}
mov r14d,${RESULTS}
case_loop:
call fill
mov rbx,[r12]
mov rcx,[r12+16]
mov rsi,[r12+24]
mov rdi,[r12+32]
mov rax,[r12+40]
cmp qword [r12+8],0
je forward
std
forward:
lea rdx,[rel kinds]
jmp [rdx+rbx*8]
k_movsb: rep movsb
jmp done
k_movsw: rep movsw
jmp done
k_movsd: rep movsd
jmp done
k_movsq: rep movsq
jmp done
k_stosb: rep stosb
jmp done
k_stosw: rep stosw
jmp done
k_stosd: rep stosd
jmp done
k_stosq: rep stosq
done:
cld
mov [r14+8],rsi
mov [r14+16],rdi
mov [r14+24],rcx
call hash
mov [r14],rax
add r14,32
add r12,48
dec r13d
jnz case_loop
dec r15d
jnz round_loop
jmp finish
align 8
kinds: dq k_movsb,k_movsw,k_movsd,k_movsq,k_stosb,k_stosw,k_stosd,k_stosq
; the area: a Weyl sequence of quadwords
fill:
mov rdi,${AREA}
mov ecx,${PAGES * 512}
mov rax,0x0F1E2D3C4B5A6978
mov rdx,0x9E3779B97F4A7C15
.fill:
mov [rdi],rax
add rax,rdx
add rdi,8
dec ecx
jnz .fill
ret
hash:
mov rdi,${AREA}
mov ecx,${PAGES * 512}
xor eax,eax
mov rdx,0x100000001B3
.hash:
xor rax,[rdi]
imul rax,rdx
rol rax,5
add rdi,8
dec ecx
jnz .hash
ret
finish:
`, `
align 8
cases:
${table}
`);
const directory = assemble("rep-strings", source);
const length = RESULTS - OUT + cases.length * 32;
const expected = await reference(directory, {length, timeout: 120000});
const check = (result, label) => {
    for(let n = 0; n < cases.length; n++)
    {
        const at = RESULTS - OUT + n * 32;
        const got = result.subarray(at, at + 32), want = expected.subarray(at, at + 32);
        if(Buffer.compare(got, want) !== 0)
        {
            const c = cases[n], q = (b, i) => b.readBigUInt64LE(i * 8).toString(16);
            assert.fail(`${label}: case ${n} ${c.movs ? "MOVS" : "STOS"}${c.size * 8} ${c.down ? "down" : "up"} count ${c.count} ` +
                `src ${c.src.toString(16)} dst ${c.dst.toString(16)}: hash/RSI/RDI/RCX ${[0, 1, 2, 3].map(i => q(got, i))}, QEMU ${[0, 1, 2, 3].map(i => q(want, i))}`);
        }
    }
};
check(await actual(directory, {length, timeout: 120000}), "interpreted");
console.log(`PASS (interpreted): ${cases.length} REP MOVS/STOS cases as QEMU`);
let retired;
check(await actual(directory, {length, timeout: 120000, options: {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
    inspect: emulator => { retired = emulator.v86.cpu.wm.exports.x64_page_stat(1); }}), "x64 page tier");
assert.ok(retired > 1000000, `the page tier ran the cases (${retired} retired natively)`);
console.log(`PASS (x64 page tier): ${cases.length} REP MOVS/STOS cases as QEMU (${retired} retired natively)`);
                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/tests/x64/smm_entry_state.mjs                                                            0000755 0000000 0000000 00000010725 00000000000 015407  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// What an SMI handler that enters long mode itself finds (as OVMF's SMI entry
// does: src/rust/cpu/smm.rs, docs/uefi.md): the guest leaves upper halves in
// GDTR's and IDTR's bases, RSP and RAX, and its PML4 in extended RAM above
// 4 GiB (CR3's upper half), then sends itself an SMI from 64-bit code. Its
// handler at SMBASE + 0x8000 loads GDTR, IDTR and CR3 in 16-bit code (32-bit
// values), enables long mode, sets ESP in compatibility mode and reads them in
// 64-bit mode: the bases and CR3 zero-extended (LGDT, LIDT and MOV to CR3
// outside 64-bit mode), RSP and RAX without the old upper halves (the general
// registers' are cleared on SMM entry). RSM restores the guest's whole values.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const body = `
; the local APIC: PDPT[3] -> a page directory with its 2 MiB page (uncached)
mov qword [0x201018], 0x203003
mov eax, 0xFEE0009B
mov [0x203000+0x1F7*8], rax
mov rax, cr3
mov cr3, rax
; the SMI handler at SMBASE + 0x8000
lea rsi, [rel smi_handler]
mov edi, 0x38000
mov ecx, smi_handler_end - smi_handler
rep movsb
; GDTR and IDTR with an upper half in their bases (nothing reads either
; until they are restored: no segment loads, interrupts off)
sgdt [0x300100]
sidt [0x300110]
mov rbx, 0xFFFFFE3D00000000
mov rax, [0x300102]
or rax, rbx
mov [0x300122], rax
mov ax, [0x300100]
mov [0x300120], ax
lgdt [0x300120]
mov rax, [0x300112]
or rax, rbx
mov [0x300132], rax
mov ax, [0x300110]
mov [0x300130], ax
lidt [0x300130]
; the PML4 above 4 GiB: a page directory mapping linear 2 GiB to the
; extended RAM at 4 GiB (PDPT[2]), the PML4 copied there, CR3 pointing to it
mov qword [0x201010], 0x204003
mov rax, 0x100000083
mov [0x204000], rax
mov rax, cr3
mov cr3, rax
mov esi, 0x200000
mov edi, 0x80000000
mov ecx, 512
rep movsq
mov rax, 0x100000000
mov cr3, rax
; RSP and RAX with upper halves
mov rbp, rsp
mov rcx, 0x0000777700000000
or rsp, rcx
mov rax, 0x1111222233334444
; an SMI to this core: ICR delivery mode SMI, shorthand self
mov edi, 0xFEE00000
mov dword [rdi+0x310], 0
mov dword [rdi+0x300], 0x40200
mov [0x300008], rax
mov [0x300010], rsp
mov rsp, rbp
mov rax, cr3
mov [0x300018], rax
mov eax, 0x200000
mov cr3, rax
sgdt [0x300140]
sidt [0x300150]
lgdt [0x300100]
lidt [0x300110]
; what the handler saw
mov esi, 0x500300
mov edi, 0x300200
mov ecx, 0x38
rep movsb
`;
// (run at 0x3000:0x8000, its addresses linear through SMM's 4 GiB segments;
// the guest's GDT: 8 32-bit code, 16 data, 24 64-bit code)
const data = `
bits 16
smi_handler:
o32 lgdt [dword gdtr]
o32 lidt [dword smm_idtr]
mov eax, 0x200000
mov cr3, eax
mov eax, cr4
or eax, 0x20
mov cr4, eax
mov ecx, 0xC0000080
mov eax, 0x900
xor edx, edx
wrmsr
mov eax, cr0
or eax, 0x80000001
mov cr0, eax
jmp dword 8:(0x38000 + .compatibility - smi_handler)
bits 32
.compatibility:
mov ax, 16
mov ds, ax
mov ss, ax
mov esp, 0x3F000
jmp 24:(0x38000 + .long - smi_handler)
bits 64
.long:
sgdt [0x500300]
sidt [0x500310]
mov [0x500320], rsp
mov [0x500328], rax
mov rax, cr3
mov [0x500330], rax
rsm
smi_handler_end:
smm_idtr: dw 0x1FF
dd 0x12345000
`;
const directory = assemble("smm-entry-state", long_mode_guest(body, data));
const result = await actual(directory, {length: 0x300, timeout: 30000, options: {cpu_type: "x86_64", extended_memory_size: 2 << 20}});
const u64 = offset => result.readBigUInt64LE(offset);
const u16 = offset => result.readUInt16LE(offset);

assert.equal(u64(0), 0xC064C064n, "guest completed");
assert.equal(u64(0x202) >> 32n, 0n, "the handler's GDTR: a 32-bit base from 16-bit code, zero-extended");
assert.equal(u64(0x202), u64(0x102), "the handler's GDTR: the guest's table");
assert.equal(u16(0x200), u16(0x100), "the handler's GDTR limit");
assert.equal(u64(0x212), 0x12345000n, "the handler's IDTR: zero-extended");
assert.equal(u64(0x220), 0x3F000n, "RSP: ESP set in compatibility mode, no old upper half");
assert.equal(u64(0x228) >> 32n, 0n, "RAX: the upper half cleared on entry");
assert.equal(u64(0x230), 0x200000n, "CR3: set in 16-bit code, zero-extended");
assert.equal(u64(0x18), 0x100000000n, "CR3 after RSM: the PML4 above 4 GiB");
assert.equal(u64(0x08), 0x1111222233334444n, "RAX after RSM");
assert.equal(u64(0x10) >> 32n, 0x7777n, "RSP after RSM: its upper half");
assert.equal(u64(0x142), u64(0x122), "GDTR after RSM: the base with its upper half");
assert.equal(u64(0x152), u64(0x132), "IDTR after RSM: the base with its upper half");
console.log("X64_SMM_ENTRY_STATE_PASS");
                                           source/v64/tests/x64/smm_long_mode.mjs                                                              0000644 0000000 0000000 00000012170 00000000000 015002  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// An SMI in long mode (src/rust/cpu/smm.rs): the guest sends itself an SMI
// through the local APIC (ICR delivery mode SMI) from 64-bit code. Its
// handler at SMBASE + 0x8000 (the default SMBASE, 0x30000: no firmware runs)
// sends itself another one on its first run, which waits in SMM until RSM;
// it copies QEMU's 64-bit save area (revision 0x20064) out and edits the
// saved RAX and R8 before RSM. Long mode resumes after the APIC write with
// the state the save area held: RAX incremented twice, R8's high half
// replaced, the rest as it was.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const body = `
; the local APIC: PDPT[3] -> a page directory with its 2 MiB page (uncached)
mov qword [0x201018], 0x203003
mov eax, 0xFEE0009B
mov [0x203000+0x1F7*8], rax
mov rax, cr3
mov cr3, rax
; the SMI handler at SMBASE + 0x8000
lea rsi, [rel smi_handler]
mov edi, 0x38000
mov ecx, smi_handler_end - smi_handler
rep movsb
mov dword [0x500100], 0
mov rax, 0x1111222233334444
mov rbx, 0x0123456789ABCDEF
mov r8, 0x5555666677778888
mov r15, 0x9999AAAABBBBCCCC
mov rbp, rsp
pushfq
pop qword [0x300030]
; an SMI to this core: ICR delivery mode SMI, shorthand self (the APIC
; through a register: a disp32 address is sign extended)
mov edi, 0xFEE00000
mov dword [rdi+0x310], 0
mov dword [rdi+0x300], 0x40200
after_smi:
mov [0x300008], rax
mov [0x300010], rbx
mov [0x300018], r8
mov [0x300020], r15
mov eax, [0x500100]
mov [0x300028], rax
mov [0x300038], rsp
mov [0x300040], rbp
pushfq
pop qword [0x300048]
mov rax, cr0
mov [0x300050], rax
mov rax, cr3
mov [0x300058], rax
mov rax, cr4
mov [0x300060], rax
mov ecx, 0xC0000080
rdmsr
mov [0x300068], eax
mov [0x30006C], edx
lea rax, [rel after_smi]
mov [0x300070], rax
lea rax, [rel gdt]
mov [0x300078], rax
; the save area of the second SMI, as its handler copied it
mov esi, 0x500200
mov edi, 0x300100
mov ecx, 0x200
rep movsb
`;
// (16-bit code, run at 0x3000:0x8000: relative jumps, absolute addresses
// through the 4 GiB segments of SMM)
const data = `
bits 16
smi_handler:
inc dword [dword 0x500100]
cmp dword [dword 0x500100], 1
jne .copy
mov dword [dword 0xFEE00310], 0
mov dword [dword 0xFEE00300], 0x40200
.copy:
mov esi, 0x3FE00
mov edi, 0x500200
mov ecx, 0x80
cld
a32 rep movsd
add dword [dword 0x3FFF8], 1
mov dword [dword 0x3FFBC], 0x11223344
rsm
smi_handler_end:
bits 64
`;
const directory = assemble("smm-long-mode", long_mode_guest(body, data));
let core_state;
const result = await actual(directory, {length: 0x300, timeout: 30000, options: {cpu_type: "x86_64"},
    inspect: emulator => {
        const cpu = emulator.v86.cpu;
        core_state = {smm: !!cpu.smm_active(), pending: !!cpu.apic_core_smi_pending(0)};
    }});
const u64 = offset => result.readBigUInt64LE(offset);
const u32 = offset => result.readUInt32LE(offset);
const u16 = offset => result.readUInt16LE(offset);
// an offset of the save area (from SMBASE + 0x8000) in the copy
const area = offset => 0x100 + offset - 0x7E00;

assert.equal(u64(0), 0xC064C064n, "guest completed");
assert.equal(u64(0x28), 2n, "two SMIs: the second one waited for RSM");
assert.deepEqual(core_state, {smm: false, pending: false});
assert.equal(u64(0x08), 0x1111222233334446n, "RAX: incremented by each handler");
assert.equal(u64(0x10), 0x0123456789ABCDEFn, "RBX");
assert.equal(u64(0x18), 0x1122334477778888n, "R8: the high half the handler wrote");
assert.equal(u64(0x20), 0x9999AAAABBBBCCCCn, "R15");
assert.equal(u64(0x38), u64(0x40), "RSP");
assert.equal(u64(0x48), u64(0x30), "RFLAGS");

assert.equal(u32(area(0x7EFC)), 0x00020064, "revision: SMBASE relocation, 64-bit layout");
assert.equal(u32(area(0x7F00)), 0x30000, "SMBASE");
assert.equal(u64(area(0x7F78)), u64(0x70), "RIP: after the APIC write");
assert.equal(u64(area(0x7FF8)), 0x1111222233334445n, "RAX (the first handler's edit)");
assert.equal(u64(area(0x7FE0)), 0x0123456789ABCDEFn, "RBX");
assert.equal(u64(area(0x7FD8)), u64(0x40), "RSP");
assert.equal(u64(area(0x7FF8 - 8 * 8)), 0x1122334477778888n, "R8");
assert.equal(u64(area(0x7FF8 - 15 * 8)), 0x9999AAAABBBBCCCCn, "R15");
assert.equal(u32(area(0x7F70)), Number(u64(0x30)), "RFLAGS");
assert.equal(u64(area(0x7ED0)), u64(0x68) & 0xFFFFFFFFn, "EFER: LME, LMA, NXE");
assert.equal(u64(area(0x7ED0)), 0xD00n);
assert.equal(u32(area(0x7F58)), Number(u64(0x50) & 0xFFFFFFFFn), "CR0");
assert.equal(u64(area(0x7F50)), 0x200000n, "CR3");
assert.equal(u32(area(0x7F48)), 0x20, "CR4: PAE");
assert.equal(u64(area(0x7F50)), u64(0x58));
assert.equal(u16(area(0x7E10)), 0x18, "CS selector");
assert.equal(u16(area(0x7E12)) & ~1, 0xA09A, "CS attributes: code, L, G");
assert.equal(u32(area(0x7E14)), 0xFFFFFFFF, "CS limit");
assert.equal(u64(area(0x7E18)), 0n, "CS base");
assert.equal(u16(area(0x7E20)), 0x10, "SS selector");
assert.equal(u16(area(0x7E22)) & ~1, 0xC092, "SS attributes: data, B, G");
assert.equal(u16(area(0x7E30)), 0x10, "DS selector");
assert.equal(u32(area(0x7E64)), 31, "GDTR limit");
assert.equal(u64(area(0x7E68)), u64(0x78) & 0xFFFFFFFFn, "GDTR base");
assert.equal(u16(area(0x7E92)) & 0x8F, 0x8B, "TR: a busy 64-bit TSS");
console.log("X64_SMM_LONG_MODE_PASS");
                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/x64/sse4.mjs                                                                       0000644 0000000 0000000 00000111531 00000000000 013042  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// SSE4.1 and SSE4.2 integer forms in the x64 engine (docs/simd-xsave-plan.md
// P4b): in 64-bit mode (XMM8-15 through REX, PEXTRQ/PINSRQ through REX.W,
// register destinations zero-extended to 64 bits) and in compatibility mode,
// with register and memory sources, against QEMU and the SDM model of
// tests/rust/sse4_model.mjs; PTEST's flags; #GP(0) for a misaligned m128
// (none for narrow operands), #NM with CR0.TS, #UD with CR0.EM, F3 or
// MOVNTDQA from a register. SSE4.2: PCMPxSTRx (lengths in EAX/EDX, or RAX/RDX
// with REX.W; the index to ECX, zero-extended; an unaligned m128), CRC32 (REX.W,
// AH and SIL, the destination zero-extended, the flags kept) and POPCNT, all
// without XMM state checks but PCMPxSTRx's. Interpreted, with the x64 page
// tier, and with compatibility-mode code compiled. Both blocks loop so that
// they become hot.
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {Fp, compare_strings, crc32, dot_product, extract, get, insert, insertps, ptest, round_lane, set, sse4_38, sse4_3a} from "../rust/sse4_model.mjs";

const OUT = 0x300000, CASE = OUT + 0x80, SKIP = OUT + 0x84, MATCH = OUT + 0xC0, FAULTS = OUT + 0x100, RESULTS = OUT + 0x1000;
// the MXCSR settings of the ROUND and DPP cases (default, RC down, up, toward zero; DAZ)
const MXCSR_VALUES = [0x1F80, 0x3F80, 0x5F80, 0x7F80, 0x1FC0];
// (compatibility-mode code is compiled only after a while)
const IDT = 0x380000, ROUNDS = 400, COMPAT_ROUNDS = 20000;

// 16 sample vectors: random bytes and lanes of edge values; then fractional,
// halfway, tiny and special floating-point values (16-18 single, 19-20 double)
const samples = new Uint8Array(26 * 16);
{
    const view = new DataView(samples.buffer);
    let seed = 0x2468ACE1;
    const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
    const edges = [[1, [0x00, 0x01, 0x7F, 0x80, 0x81, 0xFF, 0x40, 0xC0]],
        [2, [0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0x4000, 0xC000]],
        [4, [0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0x40000000, 0xC0000000]]];
    for(let n = 0; n < 16; n++)
    {
        const [size, values] = edges[n % 4] || [1, null];
        for(let i = 0; i < 16; i += size)
        {
            const value = values ? values[random() & 7] : random() & 255;
            if(size === 1) samples[n * 16 + i] = value;
            else if(size === 2) view.setUint16(n * 16 + i, value, true);
            else view.setUint32(n * 16 + i, value, true);
        }
    }
}
{
    const view = new DataView(samples.buffer);
    [[0.5, -1.5, 2.5, -0.25], [3.7, -2.3, 1e-40, -1e30], [NaN, -0, Infinity, 1e-45]].forEach((values, n) =>
        values.forEach((v, i) => view.setFloat32((16 + n) * 16 + i * 4, v, true)));
    [[2.5, -0.5], [1e-310, -1234.5678]].forEach((values, n) => values.forEach((v, i) => view.setFloat64((19 + n) * 16 + i * 8, v, true)));
    // (an SNaN in the last single lane)
    view.setUint32(18 * 16 + 12, 0x7F800001, true);
    // strings (21-24): a haystack, a needle, ranges, words of either sign (a
    // zero element in each but the haystack); 25 pads the unaligned reads
    samples.set([0x61, 0x62, 0x63, 0x61, 0x62, 0x63, 0x64, 0x62, 0x63, 0x7A, 0x41, 0x80, 0xFF, 0x62, 0x63, 0x61], 21 * 16);
    samples.set([0x62, 0x63, 0x00, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D], 22 * 16);
    samples.set([0x61, 0x63, 0x7A, 0x7A, 0x80, 0x81, 0x41, 0x5A, 0x00, 0x00, 0x30, 0x39, 0x01, 0x02, 0x03, 0x04], 23 * 16);
    [0x0061, 0x8000, 0x0062, 0xFFFF, 0x7FFF, 0x0000, 0x0061, 0x0063].forEach((v, i) => view.setUint16(24 * 16 + i * 2, v, true));
}
const sample = i => samples.subarray(i * 16, i * 16 + 16);
const hex = b => Buffer.from(b).toString("hex");

// [name, 66 0F 38 opcode byte, memory bytes]
const BINARY = [["pblendvb", 0x10], ["blendvps", 0x14], ["blendvpd", 0x15], ["pmovsxbw", 0x20, 8], ["pmovsxbd", 0x21, 4],
    ["pmovsxbq", 0x22, 2], ["pmovsxwd", 0x23, 8], ["pmovsxwq", 0x24, 4], ["pmovsxdq", 0x25, 8], ["pmuldq", 0x28], ["pcmpeqq", 0x29],
    ["packusdw", 0x2B], ["pmovzxbw", 0x30, 8], ["pmovzxbd", 0x31, 4], ["pmovzxbq", 0x32, 2], ["pmovzxwd", 0x33, 8],
    ["pmovzxwq", 0x34, 4], ["pmovzxdq", 0x35, 8], ["pcmpgtq", 0x37], ["pminsb", 0x38], ["pminsd", 0x39], ["pminuw", 0x3A],
    ["pminud", 0x3B], ["pmaxsb", 0x3C], ["pmaxsd", 0x3D], ["pmaxuw", 0x3E], ["pmaxud", 0x3F], ["pmulld", 0x40], ["phminposuw", 0x41]];
const IMMEDIATE = [["blendps", 0x0C], ["blendpd", 0x0D], ["pblendw", 0x0E], ["insertps", 0x21], ["mpsadbw", 0x42]];

// the cases: {long, kind, name, op, memory, dst, src, a, b, mask, imm8, offset}; the result is at RESULTS + 16 n
const cases = [];
const regs = long => long ? 16 : 8;
for(const long of [true, false])
{
    const base = long ? 8 : 0;
    for(const [name, op, bytes = 16] of BINARY) for(const memory of [false, true])
    {
        for(const [a, b, mask] of memory ? [[3, 6, 9]] : [[0, 1, 2], [2, 5, 11], [7, 7, 4]])
        {
            const n = cases.length;
            const dst = base + n % 8;
            const src = memory ? undefined : a === b ? dst : (dst + 1 + n * 5 % (regs(long) - 1)) % regs(long);
            cases.push({long, kind: "binary", name, op, memory, dst, src, a, b, mask, imm8: 0, offset: memory && bytes < 16 ? n & 7 : 0});
        }
    }
    for(const [name, op] of IMMEDIATE) for(const memory of [false, true]) for(const imm8 of memory ? [0x1B, 0xE4] : [0x00, 0x5A, 0xA5, 0xFF, 0x93])
    {
        const n = cases.length;
        const dst = base + n % 8, src = memory ? undefined : (dst + 3) % regs(long);
        cases.push({long, kind: "immediate", name, op, memory, dst, src, a: n % 16, b: (n + 5) % 16, imm8, offset: 0});
    }
    for(const memory of [false, true]) for(const [a, b] of [[1, 2], [5, 5], [10, 12]])
    {
        const n = cases.length;
        cases.push({long, kind: "ptest", name: "ptest", op: 0x17, memory, dst: base + n % 8, src: memory ? undefined : base + (n + 1) % 8, a, b, imm8: 0, offset: 0});
    }
    // extracts to a GPR (preloaded with ones: zero-extended) and to memory, inserts from a GPR and memory
    for(const [name, op, size] of [["pextrb", 0x14, 1], ["pextrw", 0x15, 2], ["pextrd", 0x16, 4], ["extractps", 0x17, 4],
        ...long ? [["pextrq", 0x16, 8]] : []]) for(const memory of [false, true]) for(const imm8 of [0, 3, 6, 13])
    {
        const n = cases.length;
        cases.push({long, kind: "extract", name, op, size, memory, dst: base + n % 8, a: n % 16, imm8, offset: memory ? n & 7 : 0});
    }
    for(const [name, op, size] of [["pinsrb", 0x20, 1], ["pinsrd", 0x22, 4], ...long ? [["pinsrq", 0x22, 8]] : []])
        for(const memory of [false, true]) for(const imm8 of [0, 1, 7, 14])
    {
        const n = cases.length;
        cases.push({long, kind: "insert", name, op, size, memory, dst: base + n % 8, a: n % 16, b: (n + 9) % 16, imm8, offset: memory ? n & 7 : 0});
    }
    {
        const n = cases.length;
        cases.push({long, kind: "movntdqa", name: "movntdqa", op: 0x2A, memory: true, dst: base + n % 8, a: n % 16, b: (n + 4) % 16, imm8: 0, offset: 0});
    }
    // ROUND and DPPS/DPPD from the default MXCSR; its flags afterwards in the next slot
    for(const [name, op, double, scalar] of [["roundps", 0x08, false, false], ["roundpd", 0x09, true, false],
        ["roundss", 0x0A, false, true], ["roundsd", 0x0B, true, true]])
        for(const memory of [false, true]) for(const imm8 of [0, 1, 2, 3, 4, 8, 9, 10, 11, 12])
    {
        const n = cases.length;
        cases.push({long, kind: "round", name, op, double, scalar, memory, dst: base + n % 8, src: memory ? undefined : base + (n + 3) % 8,
            a: n % 16, b: double ? 19 + (n & 1) : 16 + n % 3, imm8, offset: 0});
        cases.push({long, kind: "mxcsr", name: name + " MXCSR"});
    }
    // ROUND from other MXCSR settings, which the page tier retries in the
    // interpreter: MXCSR.RC for imm8[2], DAZ with denormal lanes
    for(const [name, op, double, scalar] of [["roundss", 0x0A, false, true], ["roundpd", 0x09, true, false]])
        for(const [mxcsr, imm8s, b] of [[0x3F80, [4, 12, 1], double ? 19 : 16], [0x5F80, [4], double ? 19 : 17],
            [0x7F80, [12], double ? 20 : 16], [0x1FC0, [1, 2, 10], double ? 20 : 17]])
            for(const imm8 of imm8s)
    {
        const n = cases.length;
        cases.push({long, kind: "round", name, op, double, scalar, memory: n % 2 === 0, dst: base + n % 8, src: n % 2 === 0 ? undefined : base + (n + 3) % 8,
            a: n % 16, b, imm8, offset: 0, mxcsr});
        cases.push({long, kind: "mxcsr", name: name + " MXCSR"});
    }
    // (QEMU 10.2 propagates SSE NaNs as the x87 does, the larger significand
    // of two QNaNs: against it, at most one NaN product meets in an addition.
    // tests/rust/sse_fp.mjs checks every combination against the model.)
    const operands = [[16, 17, [0xFF, 0xF1, 0x3C, 0x81, 0x33, 0x12]], [17, 16, [0xFF, 0x5A]],
        [17, 18, [0x81, 0x3C, 0x12, 0x33]], [18, 16, [0x81, 0x3C, 0x12, 0x33]]];
    for(const [name, op, double] of [["dpps", 0x40, false], ["dppd", 0x41, true]])
        for(const memory of [false, true]) for(const [a, b, imms] of double ? [[19, 20, [0xFF, 0x31, 0x12, 0x23]], [20, 19, [0x33, 0x11]]] : operands) for(const imm8 of imms)
    {
        const n = cases.length;
        cases.push({long, kind: "dot", name, op, double, memory, dst: base + n % 8, src: memory ? undefined : base + (n + 3) % 8, a, b, imm8, offset: 0});
        cases.push({long, kind: "mxcsr", name: name + " MXCSR"});
    }
    // PCMPxSTRx: XMM0 (preset) in its slot, RCX/ECX (ones before) and the
    // flags in the next; explicit lengths in RAX/RDX with REX.W (o64), else
    // EAX/EDX (the low halves: other lengths)
    const lengths = [[5n, 3n], [-4n, 17n], [0x100000003n, -0x100000002n], [0xFFFFFFFFn, 0x80000000n], [-0x8000000000000000n, 7n]];
    for(const [name, op] of [["pcmpestrm", 0x60], ["pcmpestri", 0x61], ["pcmpistrm", 0x62], ["pcmpistri", 0x63]])
        for(const memory of [false, true])
            for(const [imm8, a, b] of [[0x00, 22, 21], [0x0C, 22, 21], [0x04, 23, 21], [0x48, 21, 22], [0x3B, 24, 24], [0x75, 24, 23], [0x18, 21, 21]])
                for(const w of long && op < 0x62 ? [false, true] : [false])
    {
        const n = cases.length;
        const [la, lb] = lengths[n % lengths.length];
        cases.push({long, kind: "pcmpstr", name, op, memory, w, dst: base + n % 8, src: memory ? undefined : base + (n + 3) % 8, a, b, imm8, la, lb,
            offset: memory ? n % 16 : 0});
        cases.push({long, kind: "registers", name: name + " RCX, flags"});
    }
    // CRC32 and POPCNT: [instruction, destination, its value before, the
    // source's register and its value (or a memory operand), the operation's
    // width]; the destination and the flags (set before) in the slot
    const ONES = 0xFFFFFFFF00000000n;
    const scalar = long ? [
        ["crc32 eax,byte [samples + 3]", "rax", ONES | 0x12345678n, undefined, 0n, 8],
        ["crc32 rax,byte [samples + 17]", "rax", ONES, undefined, 0n, 8],
        ["crc32 eax,word [samples + 33]", "rax", ONES | 0xFFFFFFFFn, undefined, 0n, 16],
        ["crc32 eax,dword [samples + 50]", "rax", ONES | 0x80000001n, undefined, 0n, 32],
        ["crc32 rax,qword [samples + 67]", "rax", ONES | 0x1n, undefined, 0n, 64],
        ["crc32 eax,ah", "rax", ONES | 0x0000C300n, undefined, 0n, 8],
        ["crc32 eax,sil", "rax", ONES | 0x5A5A5A5An, "rsi", 0x1234567890ABCDEFn, 8],
        ["crc32 r9d,r10w", "r9", ONES | 0xDEADBEEFn, "r10", 0xFEDCBA9876543210n, 16],
        ["crc32 r9,r10", "r9", ONES | 0xDEADBEEFn, "r10", 0xFEDCBA9876543210n, 64],
        ["crc32 r11d,ecx", "r11", ONES, "rcx", 0xFFFFFFFF00000000n, 32],
        ["popcnt ax,cx", "rax", ONES | 0x12345678n, "rcx", 0xFFFF0000FFFFFFFFn, 16],
        ["popcnt eax,ecx", "rax", ONES, "rcx", 0xFFFFFFFF00000000n, 32],
        ["popcnt rax,rcx", "rax", 0n, "rcx", 0x8000000000000001n, 64],
        ["popcnt r10,qword [samples + 160]", "r10", ONES, undefined, 0n, 64],
        ["popcnt r10w,word [samples + 177]", "r10", ONES, undefined, 0n, 16],
    ] : [
        ["crc32 eax,byte [samples + 5]", "eax", 0x12345678n, undefined, 0n, 8],
        ["crc32 eax,word [samples + 37]", "eax", 0xFFFFFFFFn, undefined, 0n, 16],
        ["crc32 eax,dword [samples + 71]", "eax", 0n, undefined, 0n, 32],
        ["crc32 eax,dh", "eax", 0x87654321n, "edx", 0x0000A500n, 8],
        ["crc32 eax,cx", "eax", 0x87654321n, "ecx", 0x12345678n, 16],
        ["crc32 ebx,ebx", "ebx", 0x55AA55AAn, undefined, 0n, 32],
        ["popcnt ax,word [samples + 177]", "eax", 0xFFFFFFFFn, undefined, 0n, 16],
        ["popcnt ecx,eax", "ecx", 0n, "eax", 0n, 32],
    ];
    for(const [instruction, dst, before, src, value, width] of scalar)
    {
        cases.push({long, kind: "scalar", name: instruction, instruction, dst, before, src, value, width});
    }
}
// (X64_SSE4_FILTER=text: only the cases whose name has it, for debugging)
if(process.env.X64_SSE4_FILTER)
{
    const kept = cases.filter((c, n) => c.name.includes(process.env.X64_SSE4_FILTER) || c.kind === "mxcsr" && cases[n - 1].name.includes(process.env.X64_SSE4_FILTER));
    cases.length = 0;
    cases.push(...kept);
}
const at = (i, offset = 0) => `[samples + ${i * 16 + offset}]`;
const code = (c, n) => {
    const x = r => "xmm" + r, out = RESULTS + n * 16;
    const lines = [];
    switch(c.kind)
    {
        case "binary":
            lines.push(`movdqu xmm0,${at(c.mask)}`, `movdqu ${x(c.dst)},${at(c.a)}`);
            if(!c.memory) lines.push(`movdqu ${x(c.src)},${at(c.b)}`);
            lines.push(`${c.name} ${x(c.dst)},${c.memory ? at(c.b, c.offset) : x(c.src)}`, `movdqu [${out}],${x(c.dst)}`);
            break;
        case "immediate":
            lines.push(`movdqu ${x(c.dst)},${at(c.a)}`);
            if(!c.memory) lines.push(`movdqu ${x(c.src)},${at(c.b)}`);
            lines.push(`${c.name} ${x(c.dst)},${c.memory ? at(c.b) : x(c.src)},${c.imm8}`, `movdqu [${out}],${x(c.dst)}`);
            break;
        case "ptest":
            lines.push(`movdqu ${x(c.dst)},${at(c.a)}`);
            if(!c.memory) lines.push(`movdqu ${x(c.src)},${at(c.b)}`);
            // (OF, SF, AF set by 0x7F + 1, CF by STC)
            lines.push("mov al,0x7F", "add al,1", "stc", `ptest ${x(c.dst)},${c.memory ? at(c.b) : x(c.src)}`);
            lines.push(c.long ? "pushfq\npop rax" : "pushfd\npop eax", "and eax,0x8D5", `mov [${out}],eax`);
            break;
        case "extract":
        {
            lines.push(`movdqu ${x(c.dst)},${at(c.a)}`);
            if(c.memory)
            {
                lines.push(`mov dword [${out}],0xEEEEEEEE`, `mov dword [${out + 4}],0xEEEEEEEE`, `mov dword [${out + 8}],0xEEEEEEEE`, `mov dword [${out + 12}],0xEEEEEEEE`);
                const width = ["", "byte", "word", "", "dword", "", "", "", "qword"][c.size];
                lines.push(`${c.name} ${width} [${out + c.offset}],${x(c.dst)},${c.imm8}`);
            }
            else
            {
                // (the register written, zero-extended: ones before)
                lines.push(c.long ? "mov rdx,-1" : "mov edx,-1");
                // (PEXTRW to a register: the SSE4.1 encoding, 66 0F 3A 15)
                if(c.op === 0x15)
                {
                    const rex = c.dst >= 8 ? [0x44] : [];
                    lines.push(`db 0x66, ${[...rex, 0x0F, 0x3A, 0x15, 0xC0 | (c.dst & 7) << 3 | 2, c.imm8].join(", ")}`);
                }
                else lines.push(`${c.name} ${c.size === 8 ? "rdx" : "edx"},${x(c.dst)},${c.imm8}`);
                lines.push(c.long ? `mov [${out}],rdx` : `mov [${out}],edx\nmov dword [${out + 4}],0`);
            }
            break;
        }
        case "insert":
            lines.push(`movdqu ${x(c.dst)},${at(c.a)}`);
            if(c.memory) lines.push(`${c.name} ${x(c.dst)},${["", "byte", "", "", "dword", "", "", "", "qword"][c.size]} ${at(c.b, c.offset)},${c.imm8}`);
            else lines.push(c.size === 8 ? `mov rdx,${at(c.b)}` : `mov edx,${at(c.b)}`, `${c.name} ${x(c.dst)},${c.size === 8 ? "rdx" : "edx"},${c.imm8}`);
            lines.push(`movdqu [${out}],${x(c.dst)}`);
            break;
        case "movntdqa":
            lines.push(`movntdqa ${x(c.dst)},${at(c.b)}`, `movdqu [${out}],${x(c.dst)}`);
            break;
        case "round": case "dot":
        {
            // (a scalar ROUND's memory operand: its lane)
            const width = c.scalar ? c.double ? "qword " : "dword " : "";
            lines.push(`ldmxcsr [mxcsr_values + ${4 * MXCSR_VALUES.indexOf(c.mxcsr ?? 0x1F80)}]`, `movdqu ${x(c.dst)},${at(c.a)}`);
            if(!c.memory) lines.push(`movdqu ${x(c.src)},${at(c.b)}`);
            lines.push(`${c.name} ${x(c.dst)},${c.memory ? width + at(c.b) : x(c.src)},${c.imm8}`, `movdqu [${out}],${x(c.dst)}`);
            lines.push(`stmxcsr [${out + 16}]`, `mov dword [${out + 20}],0`, `mov dword [${out + 24}],0`, `mov dword [${out + 28}],0`);
            break;
        }
        case "pcmpstr":
        {
            const [ax, dx, cx] = c.long ? ["rax", "rdx", "rcx"] : ["eax", "edx", "ecx"];
            const value = v => "0x" + BigInt.asUintN(c.long ? 64 : 32, v).toString(16);
            // (ECX counts the rounds)
            lines.push(`push ${cx}`, `movdqu xmm0,${at(5)}`, `movdqu ${x(c.dst)},${at(c.a)}`);
            if(!c.memory) lines.push(`movdqu ${x(c.src)},${at(c.b)}`);
            // (OF, SF, AF set by 0x7F + 1, CF by STC)
            lines.push("mov al,0x7F", "add al,1", "stc", `mov ${ax},${value(c.la)}`, `mov ${dx},${value(c.lb)}`, `mov ${cx},-1`);
            lines.push(`${c.w ? "o64 " : ""}${c.name} ${x(c.dst)},${c.memory ? at(c.b, c.offset) : x(c.src)},${c.imm8}`);
            lines.push(`mov [${out + 16}],${cx}`, ...c.long ? [] : [`mov dword [${out + 20}],0`]);
            lines.push(c.long ? "pushfq\npop rax" : "pushfd\npop eax", "and eax,0x8D5", `mov [${out + 24}],eax`, `mov dword [${out + 28}],0`);
            lines.push(`movdqu [${out}],xmm0`, `pop ${cx}`);
            break;
        }
        case "scalar":
            lines.push(c.long ? "push rcx" : "push ecx", "mov al,0x7F", "add al,1", "stc");
            if(c.src) lines.push(`mov ${c.src},0x${c.value.toString(16)}`);
            lines.push(`mov ${c.dst},0x${c.before.toString(16)}`, c.instruction, `mov [${out}],${c.dst}`, ...c.long ? [] : [`mov dword [${out + 4}],0`]);
            lines.push(c.long ? "pushfq\npop rax" : "pushfd\npop eax", "and eax,0x8D5", `mov [${out + 8}],eax`, `mov dword [${out + 12}],0`);
            lines.push(c.long ? "pop rcx" : "pop ecx");
            break;
        // (written by the case before)
        case "mxcsr": case "registers":
            break;
    }
    return lines.join("\n");
};
const block = long => cases.map((c, n) => c.long === long ? code(c, n) : "").filter(Boolean).join("\n");

// the faults: [vector, what, long, instruction, the vector QEMU raises instead]
const FAULT_CASES = [
    [13, "pminud xmm8,[misaligned]", true, "pminud xmm8,[samples + 8]"],
    // PTEST's m128 is of exception type 4 (SDM): legacy SSE raises #GP(0)
    // unless it is 16-byte aligned. QEMU 10.2 does not check (none).
    [13, "ptest xmm1,[misaligned]", false, "ptest xmm1,[samples + 4]", 0],
    [13, "movntdqa xmm9,[misaligned]", true, "movntdqa xmm9,[samples + 8]"],
    [13, "mpsadbw xmm2,[misaligned]", false, "mpsadbw xmm2,[samples + 12],5"],
    [7, "pmaxsd xmm10,xmm11 with CR0.TS", true, "pmaxsd xmm10,xmm11"],
    [7, "pextrd eax,xmm1 with CR0.TS", false, "pextrd eax,xmm1,1"],
    [6, "pblendw xmm1,xmm2 with CR0.EM", true, "pblendw xmm1,xmm2,3"],
    [6, "insertps xmm1,xmm2 with CR0.EM", false, "insertps xmm1,xmm2,0x10"],
    [6, "F3 pminud xmm1,xmm2", true, "db 0xF3, 0x66, 0x0F, 0x38, 0x3B, 0xCA"],
    [6, "F2 pextrb eax,xmm1", false, "db 0xF2, 0x66, 0x0F, 0x3A, 0x14, 0xC8, 1"],
    [6, "movntdqa xmm1,xmm2", true, "db 0x66, 0x0F, 0x38, 0x2A, 0xCA"],
    [6, "movntdqa xmm3,xmm4", false, "db 0x66, 0x0F, 0x38, 0x2A, 0xDC"],
    // (0: no fault. PCMPxSTRx: an m128 without alignment, SDM exception type
    // 4 note; CRC32 and POPCNT have no XMM state checks)
    [0, "pcmpistri xmm8,[misaligned]", true, "pcmpistri xmm8,[samples + 3],0x0C"],
    [0, "pcmpestrm xmm1,[misaligned]", false, "pcmpestrm xmm1,[samples + 9],0x40"],
    [7, "pcmpestri xmm1,xmm2 with CR0.TS", false, "pcmpestri xmm1,xmm2,0"],
    [6, "pcmpistrm xmm9,xmm10 with CR0.EM", true, "pcmpistrm xmm9,xmm10,0x40"],
    [0, "crc32 eax,ecx with CR0.TS", true, "crc32 eax,ecx"],
    [0, "crc32 rax,byte [x] with CR0.EM", true, "crc32 rax,byte [samples]"],
    [0, "crc32 eax,byte [x] with CR0.EM", false, "crc32 eax,byte [samples]"],
    [0, "popcnt eax,ecx with CR0.TS", false, "popcnt eax,ecx"],
    [6, "lock crc32 eax,ecx", true, "db 0xF0, 0xF2, 0x0F, 0x38, 0xF1, 0xC1"],
    [6, "F3 0F 38 F0", false, "db 0xF3, 0x0F, 0x38, 0xF0, 0xC1"],
];
const SET_CR0 = (bits, long) => long ? `mov rax,cr0\nor eax,${bits}\nmov cr0,rax` : `mov eax,cr0\nor eax,${bits}\nmov cr0,eax`;
const CLEAR_CR0 = long => long ? "mov rax,cr0\nand eax,~12\nmov cr0,rax" : "mov eax,cr0\nand eax,~12\nmov cr0,eax";
const faults = long => FAULT_CASES.map(([vector, what, in_long, instruction], n) => in_long !== long ? "" : `
${what.includes("CR0.TS") ? SET_CR0(8, long) : what.includes("CR0.EM") ? SET_CR0(4, long) : ""}
mov dword [${CASE}],${n}
mov dword [${SKIP}],fault_end${n} - fault${n}
fault${n}: ${instruction}
fault_end${n}:
${CLEAR_CR0(long)}
mov eax,fault${n}
cmp eax,[${FAULTS + n * 16 + 8}]
sete byte [${MATCH + n}]`).join("\n");

const directory = assemble("sse4", long_mode_guest(`
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,7
mov rax,HIGH+nm
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
lidt [rel idtr]
mov rax,cr4
or eax,3 << 9 ; OSFXSR, OSXMMEXCPT
mov cr4,rax
; 64-bit mode
mov ecx,${ROUNDS}
.rounds:
${block(true)}
dec ecx
jnz .rounds
${faults(true)}
; compatibility mode
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov ecx,${COMPAT_ROUNDS}
.rounds:
${block(false)}
dec ecx
jnz .rounds
${faults(false)}
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
nm:
mov ecx,7
jmp record
gp:
add rsp,8
mov ecx,13
record:
mov edx,[${CASE}]
shl edx,4
mov [${FAULTS} + rdx],ecx
mov rax,[rsp]
mov [${FAULTS} + rdx + 8],rax
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
mxcsr_values: dd ${MXCSR_VALUES.join(",")}
align 16
samples: db ${Array.from(samples).join(",")}
`));

const length = RESULTS - OUT + cases.length * 16;
// PCMPxSTRx by the model: XMM0 preset, then the destination and a register
// source. REX.W: the lengths in RAX and RDX (SDM); QEMU 10.2 does not pass
// REX.W to its helpers (target/i386/tcg/emit.c.inc, gen_PCMPESTRx) and takes
// EAX and EDX, a deviation (`qemu`)
const strings = (c, qemu = false) => {
    const registers = [];
    registers[0] = sample(5);
    registers[c.dst] = sample(c.a);
    if(!c.memory) registers[c.src] = sample(c.b);
    const b = c.memory ? samples.subarray(c.b * 16 + c.offset, c.b * 16 + c.offset + 16) : registers[c.src];
    const explicit = c.op < 0x62, width = c.w && !qemu ? 64 : 32;
    const r = compare_strings(c.imm8, registers[c.dst], b, explicit ? BigInt.asIntN(width, c.la) : undefined, explicit ? BigInt.asIntN(width, c.lb) : undefined);
    return {...r, xmm0: c.op & 1 ? registers[0] : r.mask};
};
// a register operand's name: its register, the bits' position and number
const register = name => {
    let m;
    if((m = /^r(\d+)([dwb]?)$/.exec(name))) return {key: "r" + m[1], shift: 0n, bits: {"": 64, d: 32, w: 16, b: 8}[m[2]]};
    if((m = /^([abcd])([hl])$/.exec(name))) return {key: m[1], shift: m[2] === "h" ? 8n : 0n, bits: 8};
    if((m = /^(si|di|bp|sp)l$/.exec(name))) return {key: m[1], shift: 0n, bits: 8};
    if((m = /^([re]?)([abcd])x$/.exec(name))) return {key: m[2], shift: 0n, bits: {r: 64, e: 32, "": 16}[m[1]]};
    if((m = /^([re]?)(si|di|bp|sp)$/.exec(name))) return {key: m[2], shift: 0n, bits: {r: 64, e: 32, "": 16}[m[1]]};
    throw new Error(`register ${name}`);
};
// CRC32 and POPCNT by the model: the destination register afterwards, the flags
const scalar_result = c => {
    const [, mnemonic, d, s] = /^(\S+) ([^,]+),(.+)$/.exec(c.instruction);
    const registers = {};
    if(c.src) registers[register(c.src).key] = c.value;
    registers[register(c.dst).key] = c.before;
    const memory = /\[samples \+ (\d+)\]/.exec(s);
    let source;
    if(memory) source = get(samples.subarray(+memory[1]), c.width / 8, 0);
    else
    {
        const r = register(s);
        source = registers[r.key] >> r.shift & (1n << BigInt(r.bits)) - 1n;
    }
    const old = registers[register(d).key];
    if(mnemonic === "crc32") return {value: crc32(old & 0xFFFFFFFFn, source, c.width / 8), flags: 0x891};
    const ones = BigInt(source.toString(2).split("1").length - 1);
    // (a 16-bit destination keeps the rest; a 32-bit one is zero-extended in 64-bit mode)
    const value = register(d).bits === 16 ? old & ~0xFFFFn | ones : ones;
    return {value: c.long ? value : value & 0xFFFFFFFFn, flags: source === 0n ? 0x40 : 0};
};
const floating = (c) => {
    if(c.kind === "dot") return dot_product(0x1F80, sample(c.a), sample(c.b), c.imm8, c.double);
    const fp = new Fp(c.mxcsr ?? 0x1F80), result = Uint8Array.from(sample(c.a)), size = c.double ? 8 : 4;
    for(let i = 0; i < (c.scalar ? 1 : 16 / size); i++) set(result, size, i, round_lane(fp, get(sample(c.b), size, i), c.double, c.imm8));
    return {result, mxcsr: fp.finish().mxcsr};
};
const expected_result = (c, n, qemu) => {
    const result = new Uint8Array(16);
    switch(c.kind)
    {
        case "round": case "dot":
            return floating(c).result;
        case "pcmpstr":
            return strings(c, qemu).xmm0;
        case "registers":
        {
            const c0 = cases[n - 1], r = strings(c0, qemu);
            set(result, 8, 0, c0.op & 1 ? BigInt(r.index) : c0.long ? 0xFFFFFFFFFFFFFFFFn : 0xFFFFFFFFn);
            set(result, 4, 2, BigInt((r.cf ? 1 : 0) | (r.zf ? 0x40 : 0) | (r.sf ? 0x80 : 0) | (r.of ? 0x800 : 0)));
            return result;
        }
        case "scalar":
        {
            const {value, flags} = scalar_result(c);
            set(result, 8, 0, value);
            set(result, 4, 2, BigInt(flags));
            return result;
        }
        case "mxcsr":
            set(result, 4, 0, BigInt(floating(cases[n - 1]).mxcsr));
            return result;
        case "binary":
        {
            // XMM0 loaded first, then the destination, then a register source
            const registers = [];
            registers[0] = sample(c.mask);
            registers[c.dst] = sample(c.a);
            if(!c.memory) registers[c.src] = sample(c.b);
            const bytes = BINARY.find(([name]) => name === c.name)[2] || 16;
            const source = c.memory ? Uint8Array.from({length: 16}, (_, i) => i < bytes ? samples[c.b * 16 + c.offset + i] : 0) : registers[c.src];
            return sse4_38(c.op, registers[c.dst], source, registers[0]);
        }
        case "immediate":
        {
            const s = sample(c.b), d = !c.memory && c.src === c.dst ? s : sample(c.a);
            return c.op === 0x21 && c.memory ? insertps(d, get(s, 4, 0), c.imm8) : sse4_3a(c.op, d, s, c.imm8);
        }
        case "ptest":
        {
            const s = sample(c.b), d = !c.memory && c.src === c.dst ? s : sample(c.a);
            const {zf, cf} = ptest(d, s);
            set(result, 4, 0, BigInt((zf ? 0x40 : 0) | (cf ? 1 : 0)));
            return result;
        }
        case "extract":
        {
            const value = extract(sample(c.a), c.size, c.imm8);
            if(c.memory)
            {
                result.fill(0xEE);
                set(result.subarray(c.offset), c.size, 0, value);
            }
            else set(result, 8, 0, value);
            return result;
        }
        case "insert":
        {
            const value = c.memory ? get(samples.subarray(c.b * 16 + c.offset), c.size, 0) : get(sample(c.b), c.size, 0);
            return insert(sample(c.a), c.size, value, c.imm8);
        }
        case "movntdqa":
            return sample(c.b);
    }
};
const check = (result, label) => {
    // the model first: QEMU is a reference, not the specification
    cases.forEach((c, n) => {
        const value = Uint8Array.from(result.subarray(RESULTS - OUT + n * 16, RESULTS - OUT + n * 16 + 16));
        assert.equal(hex(value), hex(expected_result(c, n, label === "QEMU")),
            `${label}: ${c.long ? "64-bit" : "compatibility"} ${["scalar", "registers", "mxcsr"].includes(c.kind) ? c.name : `${c.name} xmm${c.dst}, ${c.memory ? "[mem]" : c.src === undefined ? "r" : "xmm" + c.src} imm8=${c.imm8}`}`);
    });
    FAULT_CASES.forEach(([vector, what, , , qemu], n) => {
        const deviation = label === "QEMU" && qemu !== undefined;
        assert.equal(result.readUInt32LE(FAULTS - OUT + n * 16), deviation ? qemu : vector, `${label}: ${what}: vector`);
        assert.equal(result[MATCH - OUT + n], deviation && qemu === 0 || vector === 0 ? 0 : 1, `${label}: ${what}: RIP`);
    });
};
// v86 against QEMU, but for the fault records and the REX.W PCMPESTRx results where QEMU deviates
const comparable = buffer => {
    const copy = Buffer.from(buffer);
    cases.forEach((c, n) => {
        if(c.kind === "pcmpstr" && c.w) copy.fill(0, RESULTS - OUT + n * 16, RESULTS - OUT + n * 16 + 32);
    });
    FAULT_CASES.forEach(([, , , , qemu], n) => {
        if(qemu === undefined) return;
        copy.fill(0, FAULTS - OUT + n * 16, FAULTS - OUT + n * 16 + 16);
        copy[MATCH - OUT + n] = 0;
    });
    return copy;
};
const expected = await reference(directory, {length});
check(expected, "QEMU");
for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}],
    // (compatibility-mode code in the page tier, docs/jit-unification-plan.md P7.2)
    ["x64 page tier, compat32", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        jit_switches: {x64_page_compat32: 1}}]])
{
    let page = 0, page32 = 0;
    const result = await actual(directory, {length, timeout: 180000, options: {cpu_features: ["SSSE3", "SSE4.1", "SSE4.2"], ...options},
        inspect: emulator => {
            page = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            page32 = emulator.v86.cpu.wm.exports.x64_page_stat(36);
        }});
    check(result, label);
    assert.ok(comparable(result).equals(comparable(expected)), `${label}: equal to QEMU (but for its documented deviations)`);
    if(options.disable_jit === false) assert.ok(page > 1000, `${label}: compiled 64-bit code ran (${page})`);
    if(options.jit_switches?.x64_page_compat32) assert.ok(page32 > 0, `${label}: the page tier compiled compatibility-mode code (${page32})`);
    console.log(`PASS (${label}): ${cases.length} SSE4 cases in 64-bit and compatibility mode, ${FAULT_CASES.length} faults, as QEMU and the SDM model`);
}

// The page tier has templates for the SSE4.1 forms of one Wasm SIMD operation,
// the blends with imm8 (register and aligned memory sources), ROUND and
// PCMPxSTRx: a hot loop of them runs without steps (x64_page_stat(4)),
// ROUNDPS setting PE. (R15 counts: PCMPISTRI writes ECX.)
const ITERATIONS = 100000;
const hot = assemble("sse4-hot", long_mode_guest(`
mov rax,cr4
or eax,3 << 9
mov cr4,rax
movdqu xmm9,[hot_samples]
mov r15d,${ITERATIONS}
.loop:
movdqu xmm8,[hot_samples + 16]
pminud xmm8,xmm9
pmaxsd xmm8,[hot_samples + 32]
movdqu xmm10,[hot_samples + 48]
pcmpgtq xmm10,xmm8
movdqu xmm11,[hot_samples + 64]
pmulld xmm11,xmm8
pblendw xmm11,[hot_samples + 80],0xA5
movdqu xmm12,[hot_samples + 96]
blendps xmm12,xmm10,5
packusdw xmm12,xmm11
movdqu xmm13,[hot_samples + 112]
roundsd xmm13,xmm13,9
movdqu xmm14,[hot_samples + 128]
roundss xmm14,[hot_samples + 132],10
roundps xmm15,[hot_samples + 128],0
movdqu xmm1,[hot_samples + 160]
pcmpistri xmm1,[hot_samples + 147],0x0C
movdqu xmm2,[hot_samples + 144]
mov eax,3
mov edx,-17
pcmpestrm xmm2,xmm1,0x40
dec r15d
jnz .loop
movdqu [${OUT + 16}],xmm8
movdqu [${OUT + 32}],xmm10
movdqu [${OUT + 48}],xmm11
movdqu [${OUT + 64}],xmm12
movdqu [${OUT + 80}],xmm13
movdqu [${OUT + 96}],xmm14
movdqu [${OUT + 112}],xmm15
stmxcsr [${OUT + 128}]
mov [${OUT + 132}],ecx
movdqu [${OUT + 144}],xmm0
`, `
align 16
hot_samples: db ${[...samples.subarray(0, 112), ...sample(19), ...sample(16), ...sample(21), ...sample(22), ...new Uint8Array(16)].join(",")}
`));
{
    let steps, retired;
    const result = await actual(hot, {length: 160, timeout: 60000,
        options: {cpu_features: ["SSSE3", "SSE4.1", "SSE4.2"], disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => {
            steps = emulator.v86.cpu.wm.exports.x64_page_stat(4);
            retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
        }});
    const xmm8 = sse4_38(0x3D, sse4_38(0x3B, sample(1), sample(0)), sample(2));
    const xmm10 = sse4_38(0x37, sample(3), xmm8);
    const xmm11 = sse4_3a(0x0E, sse4_38(0x40, sample(4), xmm8), sample(5), 0xA5);
    const xmm12 = sse4_38(0x2B, sse4_3a(0x0C, sample(6), xmm10, 5), xmm11);
    const fp = new Fp(0x1F80);
    const rounded = (destination, source, double, lanes, imm8) => {
        const result = Uint8Array.from(destination), size = double ? 8 : 4;
        for(let i = 0; i < lanes; i++) set(result, size, i, round_lane(fp, get(source, size, i), double, imm8));
        return result;
    };
    const xmm13 = rounded(sample(19), sample(19), true, 1, 9);
    const xmm14 = rounded(sample(16), sample(16).subarray(4), false, 1, 10);
    const xmm15 = rounded(new Uint8Array(16), sample(16), false, 4, 0);
    for(const [register, value, at] of [[8, xmm8, 16], [10, xmm10, 32], [11, xmm11, 48], [12, xmm12, 64], [13, xmm13, 80], [14, xmm14, 96], [15, xmm15, 112]])
    {
        assert.equal(hex(result.subarray(at, at + 16)), hex(value), `hot loop: XMM${register}`);
    }
    assert.equal(result.readUInt32LE(128), fp.finish().mxcsr, "hot loop: MXCSR (PE from ROUNDPS)");
    // (the haystack at hot_samples + 147: sample 21 from byte 3, then sample 22)
    const haystack = Uint8Array.from([...sample(21).subarray(3), ...sample(22).subarray(0, 3)]);
    assert.equal(result.readUInt32LE(132), compare_strings(0x0C, sample(22), haystack).index, "hot loop: PCMPISTRI's ECX");
    assert.equal(hex(result.subarray(144, 160)), hex(compare_strings(0x40, sample(21), sample(22), 3n, -17n).mask), "hot loop: PCMPESTRM's XMM0");
    assert.ok(retired > ITERATIONS * 20 && steps < ITERATIONS / 10, `page tier templates: ${retired} retired, ${steps} steps`);
    console.log(`PASS (x64 page tier): SSE4.1 and SSE4.2 templates, ROUND and PCMPxSTRx included (${retired} instructions retired natively, ${steps} steps)`);
}

// The page tier's ROUND refuses MXCSR.DAZ and, for imm8[2], MXCSR.RC other
// than nearest (a retry: the runtime interprets it and runs on to an offset
// the function serves, here the loop's head, so a round retries once at
// least, x64::pages::unserved_run): in a compiled loop,
// a denormal lane rounds up to 0 with DAZ (1 without) and imm8 4 rounds down.
// The results of every round are summed: an execution the page tier got wrong
// shows even when the last round ran in the interpreter.
{
    const DAZ_ITERATIONS = 2000;
    const refusals = assemble("sse4-refusals", long_mode_guest(`
mov rax,cr4
or eax,3 << 9
mov cr4,rax
xorpd xmm4,xmm4
xorpd xmm5,xmm5
mov r15d,${DAZ_ITERATIONS}
.loop:
ldmxcsr [mxcsr_daz]
movdqu xmm1,[values]
roundpd xmm2,xmm1,2
addpd xmm4,xmm2
ldmxcsr [mxcsr_down]
roundpd xmm3,xmm1,4
addpd xmm5,xmm3
dec r15d
jnz .loop
ldmxcsr [mxcsr_default]
movdqu [${OUT + 16}],xmm4
movdqu [${OUT + 32}],xmm5
`, `
align 16
values: dq 1e-310, -2.5
mxcsr_daz: dd 0x1FC0
mxcsr_down: dd 0x3F80
mxcsr_default: dd 0x1F80
`));
    let retries;
    const result = await actual(refusals, {length: 48, timeout: 60000,
        options: {cpu_features: ["SSSE3", "SSE4.1", "SSE4.2"], disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
        inspect: emulator => { retries = emulator.v86.cpu.wm.exports.x64_page_stat(2); }});
    const view = new DataView(new ArrayBuffer(16));
    view.setFloat64(0, 1e-310, true);
    view.setFloat64(8, -2.5, true);
    const values = new Uint8Array(view.buffer);
    // (the sums of small integers: exact)
    const summed = (mxcsr, imm8) => {
        const fp = new Fp(mxcsr), out = new DataView(new ArrayBuffer(16));
        for(let i = 0; i < 2; i++)
        {
            const lane = new DataView(new ArrayBuffer(8));
            lane.setBigUint64(0, round_lane(fp, get(values, 8, i), true, imm8), true);
            out.setFloat64(i * 8, lane.getFloat64(0, true) * DAZ_ITERATIONS, true);
        }
        return new Uint8Array(out.buffer);
    };
    assert.equal(hex(result.subarray(16, 32)), hex(summed(0x1FC0, 2)), "ROUNDPD with DAZ, summed");
    assert.equal(hex(result.subarray(32, 48)), hex(summed(0x3F80, 4)), "ROUNDPD with MXCSR.RC down, summed");
    assert.ok(retries > DAZ_ITERATIONS / 2, `page tier: the refused ROUNDs are retried (${retries} retries)`);
    console.log(`PASS (x64 page tier): ROUND refuses DAZ and MXCSR.RC (${retries} retries)`);
}
                                                                                                                                                                       source/v64/tests/x64/sse_fp_template.mjs                                                            0000644 0000000 0000000 00000017530 00000000000 015342  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The x64 page tier's SSE ADD/SUB/MUL/DIV template (x64::pagegen, vfp): it
// runs natively only when that cannot change MXCSR and otherwise retries
// the instruction in the interpreter. Each of the 16 instructions (PS PD SS
// SD), with a register and with a memory source, is applied to the same
// vectors of special and random operands under MXCSR values that allow and
// that refuse the native path, in a loop until the page tier has compiled
// the code; every result and MXCSR must equal the interpreter's.
// With x64_sse_fast_check (JIT_SWITCHES; docs/jit-unification-plan.md
// P4.18) the instructions go through x86tpl::ops::float, which also takes
// SQRT, MIN and MAX (PS PD SS SD) and RCP and RSQRT (PS SS), tested too,
// and runs refused ones exactly in place, but those whose register facts
// hold only for admitted operands, which retry (as IR Tier-0's did).
//
// SSE_FP_SEED, SSE_FP_VECTORS (per form, default 256), SSE_FP_ROUNDS (8),
// SSE_FP_FORMS (a regular expression of the mnemonics to test);
// SSE_FP_ORDINARY=1: only ordinary operands under MXCSR 0x1FA0, where the
// native path must take (nearly) every instruction.
import assert from "node:assert/strict";
import { assemble, actual } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";

let seed = Number(process.env.SSE_FP_SEED || 1) >>> 0 || 1;
const random = () => {
    seed ^= seed << 13; seed >>>= 0;
    seed ^= seed >>> 17;
    seed ^= seed << 5; seed >>>= 0;
    return seed / 0x100000000;
};
const int = n => Math.floor(random() * n);
const COUNT = +(process.env.SSE_FP_VECTORS || 256);
const ROUNDS = +(process.env.SSE_FP_ROUNDS || 8);
const VECTORS = 0x400000, OUT = 0x600000, STRIDE = 48, OUT_STRIDE = 32;
const ORDINARY = +process.env.SSE_FP_ORDINARY;
const FORMS = new RegExp(process.env.SSE_FP_FORMS || ".");

// operands: bit patterns of every class the guards distinguish
// (ordinary operands are positive: SQRT and RSQRT refuse negative ones)
function single()
{
    const sign = ORDINARY ? 0 : int(2) << 31;
    switch(ORDINARY ? 11 : int(12))
    {
        case 0: return sign;                                              // zero
        case 1: return sign | 1 + int(0x7FFFFF);                         // denormal
        case 2: return sign | 0x7F800000;                                 // infinity
        case 3: return 0x7FC00000 | int(0x3FFFFF);                        // QNaN
        case 4: return 0x7F800001 + int(0x3FFFFF);                        // SNaN
        case 5: return sign | 0x00800000 + int(4);                        // smallest normals
        case 6: return sign | 0x7F7FFFFF - int(4);                        // largest
        case 7: return sign | (1 + int(12)) << 23 | int(0x7FFFFF);       // tiny normals (products underflow)
        case 8: return sign | (240 + int(14)) << 23 | int(0x7FFFFF);     // huge (products overflow)
        default: return sign | (100 + int(56)) << 23 | int(0x7FFFFF);   // ordinary
    }
}
function double()
{
    const sign = BigInt(ORDINARY ? 0 : int(2)) << 63n;
    const mantissa = () => BigInt(int(0x100000)) << 32n | BigInt(int(0x100000000));
    switch(ORDINARY ? 11 : int(12))
    {
        case 0: return sign;
        case 1: return sign | 1n + mantissa();
        case 2: return sign | 0x7FF0000000000000n;
        case 3: return 0x7FF8000000000000n | mantissa();
        case 4: return 0x7FF0000000000001n + mantissa() % 0x7FFFFFFFFFFFFn;
        case 5: return sign | 0x0010000000000000n + BigInt(int(4));
        case 6: return sign | 0x7FEFFFFFFFFFFFFFn - BigInt(int(4));
        case 7: return sign | BigInt(1 + int(40)) << 52n | mantissa();
        case 8: return sign | BigInt(2000 + int(46)) << 52n | mantissa();
        default: return sign | BigInt(900 + int(250)) << 52n | mantissa();
    }
}
// MXCSR: 0x1FA0 and 0x1FBF allow the native path; the others refuse it
const MXCSR = [0x1F80, 0x1FA0, 0x1FA0, 0x1FA0, 0x1FBF, 0x3FA0, 0x5FA0, 0x7FA0, 0x1FE0, 0x9FA0];

const vectors = new DataView(new ArrayBuffer(COUNT * STRIDE));
for(let v = 0; v < COUNT; v++)
{
    const at = v * STRIDE;
    vectors.setUint32(at, ORDINARY ? 0x1FA0 : MXCSR[int(MXCSR.length)], true);
    if(v % 2)
    {
        for(let lane = 0; lane < 2; lane++)
        {
            const a = double();
            // sometimes b = -a (exact cancellation) or a copy (x - x)
            const b = ORDINARY ? double() : [double(), a ^ 1n << 63n, a][int(6) < 4 ? 0 : 1 + int(2)];
            vectors.setBigUint64(at + 16 + lane * 8, a, true);
            vectors.setBigUint64(at + 32 + lane * 8, b, true);
        }
    }
    else
    {
        for(let lane = 0; lane < 4; lane++)
        {
            const a = single();
            const b = ORDINARY ? single() : [single(), (a ^ 0x80000000) >>> 0, a][int(6) < 4 ? 0 : 1 + int(2)];
            vectors.setUint32(at + 16 + lane * 4, a >>> 0, true);
            vectors.setUint32(at + 32 + lane * 4, b >>> 0, true);
        }
    }
}

const forms = [];
for(const op of ["add", "sub", "mul", "div", "sqrt", "min", "max", "rcp", "rsqrt"])
    for(const suffix of ["ps", "pd", "ss", "sd"])
        for(const memory of [false, true])
            if((!op.startsWith("r") || !suffix.endsWith("d")) && FORMS.test(op + suffix)) forms.push({ op: op + suffix, memory });
let body = `
mov rax, cr4
or rax, 0x600                 ; OSFXSR, OSXMMEXCPT
mov cr4, rax
mov r15d, ${ROUNDS}
.round:
`;
forms.forEach(({ op, memory }, index) => {
    body += `
mov rsi, ${VECTORS}
mov rdi, ${OUT + index * COUNT * OUT_STRIDE}
mov ecx, ${COUNT}
.form${index}:
ldmxcsr [rsi]
movups xmm0, [rsi + 16]
movups xmm1, [rsi + 32]
${op} xmm0, ${memory ? "[rsi + 32]" : "xmm1"}
stmxcsr [rdi]
movups [rdi + 16], xmm0
add rsi, ${STRIDE}
add rdi, ${OUT_STRIDE}
dec ecx
jnz .form${index}
`;
});
body += `
dec r15d
jnz .round
mov eax, 0x1F80
mov [0x300010], eax
ldmxcsr [0x300010]
`;
const directory = assemble("sse-fp-template", long_mode_guest(body));
const length = forms.length * COUNT * OUT_STRIDE;
const results = [];
for(const jit of [false, true])
{
    let output, stats;
    await actual(directory, {
        length: 8, timeout: 600000,
        options: { memory_size: 16 << 20, disable_jit: !jit, ir_sync_publication: true },
        setup: emulator => { emulator.v86.cpu.mem8.set(new Uint8Array(vectors.buffer), VECTORS); },
        inspect: emulator => {
            const cpu = emulator.v86.cpu;
            output = cpu.mem8.slice(OUT, OUT + length);
            stats = Array.from({ length: 13 }, (_, i) => cpu.wm.exports.x64_page_stat(i));
        },
    });
    results.push(output);
    console.log(`${jit ? "page tier" : "interpreter"}: native ${stats[1]}, compiled ${stats[0]}, steps ${stats[4]}, retries ${stats[2]}, templated ${stats[10]}`);
    if(jit) assert.ok(stats[1] > forms.length * COUNT, "the page tier ran the forms: " + stats);
    // (ordinary operands: a refusal of the template is a retry; LDMXCSR and
    // STMXCSR are steps either way)
    if(jit && ORDINARY) assert.ok(stats[2] < forms.length * COUNT * ROUNDS / 10, "the native path ran: " + stats);
}
for(let form = 0; form < forms.length; form++)
{
    for(let v = 0; v < COUNT; v++)
    {
        const at = (form * COUNT + v) * OUT_STRIDE;
        const differs = results[0].subarray(at, at + OUT_STRIDE).some((byte, i) => byte !== results[1][at + i]);
        if(differs)
        {
            const hex = bytes => Buffer.from(bytes).toString("hex");
            assert.fail(`${forms[form].op}${forms[form].memory ? " mem" : ""} vector ${v} (mxcsr ${vectors.getUint32(v * STRIDE, true).toString(16)}, ` +
                `a ${hex(new Uint8Array(vectors.buffer, v * STRIDE + 16, 16))}, b ${hex(new Uint8Array(vectors.buffer, v * STRIDE + 32, 16))}): ` +
                `interpreter ${hex(results[0].subarray(at, at + OUT_STRIDE))} page tier ${hex(results[1].subarray(at, at + OUT_STRIDE))}`);
        }
    }
}
console.log(`X64_SSE_FP_TEMPLATE_PASS ${forms.length} forms x ${COUNT} vectors x ${ROUNDS} rounds`);
                                                                                                                                                                        source/v64/tests/x64/sse_int_template.mjs                                                           0000644 0000000 0000000 00000022517 00000000000 015530  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The x64 page tier's SSE2 packed integer, shuffle, shift and compare
// templates (x64::pagegen: Vpacked, VshiftImm, Vcompare, Mxcsr). Every form,
// with a register and (where it exists) an aligned memory source, runs over
// the same vectors in a loop until the page tier has compiled it; each
// result (XMM, EFLAGS after COMISS/UCOMISS/COMISD/UCOMISD, MXCSR) must equal
// the interpreter's. Compare operands include NaNs, denormals, infinities
// and zeros, under MXCSR values with and without DAZ/FTZ.
//
// SSE_INT_SEED, SSE_INT_VECTORS (per form, default 64), SSE_INT_ROUNDS (6)
import assert from "node:assert/strict";
import { assemble, actual } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";

let seed = Number(process.env.SSE_INT_SEED || 1) >>> 0 || 1;
const random = () => {
    seed ^= seed << 13; seed >>>= 0;
    seed ^= seed >>> 17;
    seed ^= seed << 5; seed >>>= 0;
    return seed / 0x100000000;
};
const int = n => Math.floor(random() * n);
const COUNT = +(process.env.SSE_INT_VECTORS || 64);
const ROUNDS = +(process.env.SSE_INT_ROUNDS || 6);
const VECTORS = 0x400000, OUT = 0x600000, STRIDE = 48, OUT_STRIDE = 32;

function single()
{
    const sign = int(2) << 31;
    switch(int(9))
    {
        case 0: return sign;                                    // zero
        case 1: return sign | 1 + int(0x7FFFFF);               // denormal
        case 2: return sign | 0x7F800000;                       // infinity
        case 3: return 0x7FC00000 | int(0x3FFFFF);              // QNaN
        case 4: return 0x7F800001 + int(0x3FFFFF);              // SNaN
        default: return sign | (100 + int(56)) << 23 | int(0x7FFFFF);
    }
}
function double()
{
    const sign = BigInt(int(2)) << 63n;
    const mantissa = () => BigInt(int(0x100000)) << 32n | BigInt(int(0x100000000));
    switch(int(9))
    {
        case 0: return sign;
        case 1: return sign | 1n + mantissa();
        case 2: return sign | 0x7FF0000000000000n;
        case 3: return 0x7FF8000000000000n | mantissa();
        case 4: return 0x7FF0000000000001n + mantissa() % 0x7FFFFFFFFFFFFn;
        default: return sign | BigInt(900 + int(250)) << 52n | mantissa();
    }
}
// all exceptions masked; with and without DAZ (0x40), FTZ (0x8000), PE, RC
const MXCSR = [0x1F80, 0x1FA0, 0x1FC0, 0x9F80, 0x9FC0, 0x3F80, 0x1FBF];

// vector v: [0] MXCSR, [4] flags seed, [16] a, [32] b. Even vectors hold
// float lanes (a/b alike for compares), odd ones random bytes with a small
// shift count in b's low quadword now and then.
const vectors = new DataView(new ArrayBuffer(COUNT * STRIDE));
for(let v = 0; v < COUNT; v++)
{
    const at = v * STRIDE;
    vectors.setUint32(at, MXCSR[int(MXCSR.length)], true);
    vectors.setUint32(at + 4, int(0x100000000), true);
    if(v % 4 === 0)
    {
        for(let lane = 0; lane < 4; lane++)
        {
            const a = single();
            const b = [single(), a, (a ^ 0x80000000) >>> 0][int(3)];
            vectors.setUint32(at + 16 + lane * 4, a >>> 0, true);
            vectors.setUint32(at + 32 + lane * 4, b >>> 0, true);
        }
    }
    else if(v % 4 === 2)
    {
        for(let lane = 0; lane < 2; lane++)
        {
            const a = double();
            const b = [double(), a, a ^ 1n << 63n][int(3)];
            vectors.setBigUint64(at + 16 + lane * 8, a, true);
            vectors.setBigUint64(at + 32 + lane * 8, b, true);
        }
    }
    else
    {
        for(let i = 16; i < 48; i++) vectors.setUint8(at + i, int(256));
        if(int(2)) vectors.setBigUint64(at + 32, BigInt(int(70)), true);
    }
}

const binary = ["paddb", "paddw", "paddd", "paddq", "psubb", "psubw", "psubd", "psubq", "paddsb", "paddsw", "paddusb", "paddusw",
    "psubsb", "psubsw", "psubusb", "psubusw", "pcmpgtb", "pcmpgtw", "pcmpgtd", "pcmpeqb", "pcmpeqw", "pcmpeqd",
    "pminub", "pmaxub", "pminsw", "pmaxsw", "pavgb", "pavgw", "pmulhuw", "pmulhw", "pmuludq", "psadbw", "pmullw", "pmaddwd",
    "punpcklbw", "punpcklwd", "punpckldq", "punpckhbw", "punpckhwd", "punpckhdq", "punpcklqdq", "punpckhqdq",
    "unpcklps", "unpckhps", "unpcklpd", "unpckhpd",
    "packsswb", "packuswb", "packssdw", "psrlw", "psrld", "psrlq", "psraw", "psrad", "psllw", "pslld", "psllq"];
const forms = [];
for(const op of binary)
{
    forms.push({ text: `${op} xmm0, xmm1` });
    forms.push({ text: `${op} xmm0, [rsi + 32]` });
}
// high registers (REX.R/REX.B)
forms.push({ text: "paddw xmm9, xmm12", high: true });
forms.push({ text: "punpcklbw xmm9, [rsi + 32]", high: true });
forms.push({ text: "unpcklps xmm9, xmm12", high: true });
forms.push({ text: "pshufd xmm9, xmm12, 0x1B", high: true });
forms.push({ text: "psrlw xmm12, 3", high: true, shifted: 12 });
for(const imm of [0x00, 0x1B, 0x4E, 0xB1, 0xE4, 0xFF, int(256)])
{
    for(const op of ["pshufd", "pshuflw", "pshufhw", "shufps", "shufpd"])
    {
        forms.push({ text: `${op} xmm0, xmm1, 0x${imm.toString(16)}` });
        forms.push({ text: `${op} xmm0, [rsi + 32], 0x${imm.toString(16)}` });
    }
}
for(const count of [0, 1, 3, 7, 8, 15, 16, 31, 32, 63, 64, 200])
    for(const op of ["psrlw", "psrld", "psrlq", "psraw", "psrad", "psllw", "pslld", "psllq", "psrldq", "pslldq"])
        forms.push({ text: `${op} xmm0, ${count}` });
for(const op of ["comiss", "ucomiss", "comisd", "ucomisd"])
{
    forms.push({ text: `${op} xmm0, xmm1`, flags: true });
    forms.push({ text: `${op} xmm0, [rsi + 32]`, flags: true });
    forms.push({ text: `${op} xmm11, xmm1`, flags: true, high: true });
}
// conditions fused with the compare (Known::Float), whose EFLAGS are then
// written again unread: each condition by SETcc (eight a form, packed into
// [rdi + 8]) and by a Jcc after a compare of its own
const CONDITIONS = ["o", "no", "b", "ae", "e", "ne", "be", "a", "s", "ns", "p", "np", "l", "ge", "le", "g"];
const SET_REGISTERS = ["al", "ah", "bl", "bh", "dl", "dh", "r8b", "r9b"];
let jumps = 0;
for(const op of ["comiss", "ucomiss", "comisd", "ucomisd"])
{
    for(const half of [0, 1])
    {
        forms.push({ text: `
xor eax, eax
xor ebx, ebx
xor edx, edx
xor r8d, r8d
xor r9d, r9d
${op} xmm0, xmm1
${CONDITIONS.slice(8 * half, 8 * half + 8).map((cc, k) => `set${cc} ${SET_REGISTERS[k]}`).join("\n")}
add r10d, r10d
shl ebx, 16
or eax, ebx
shl r9d, 8
or r8d, r9d
shl rdx, 32
or rax, rdx
shl r8, 48
or rax, r8
mov [rdi + 8], rax` });
    }
    forms.push({ text: `
xor eax, eax
${CONDITIONS.map((cc, k) => `${op} xmm0, xmm1
j${cc} .jump${jumps}_${k}
bts eax, ${k}
.jump${jumps}_${k}:`).join("\n")}
mov [rdi + 8], rax` });
    jumps++;
}

let body = `
mov rax, cr4
or rax, 0x600                 ; OSFXSR, OSXMMEXCPT
mov cr4, rax
mov r15d, ${ROUNDS}
.round:
`;
forms.forEach(({ text, flags, high, shifted }, index) => {
    const dst = high ? (shifted === 12 ? "xmm12" : text.includes("xmm11") ? "xmm11" : "xmm9") : "xmm0";
    body += `
mov rsi, ${VECTORS}
mov rdi, ${OUT + index * COUNT * OUT_STRIDE}
mov ecx, ${COUNT}
.form${index}:
ldmxcsr [rsi]
movups xmm0, [rsi + 16]
movups xmm1, [rsi + 32]
movups xmm9, [rsi + 16]
movups xmm11, [rsi + 16]
movups xmm12, [rsi + ${shifted === 12 ? 16 : 32}]
mov eax, [rsi + 4]
add eax, eax                  ; some flags state
${text}
${flags ? "pushfq\npop rax\nmov [rdi + 8], rax" : ""}
stmxcsr [rdi]
movups [rdi + 16], ${dst}
add rsi, ${STRIDE}
add rdi, ${OUT_STRIDE}
dec ecx
jnz .form${index}
`;
});
body += `
dec r15d
jnz .round
mov eax, 0x1F80
mov [0x300010], eax
ldmxcsr [0x300010]
`;
const directory = assemble("sse-int-template", long_mode_guest(body));
const length = forms.length * COUNT * OUT_STRIDE;
const results = [];
for(const jit of [false, true])
{
    let output, stats;
    await actual(directory, {
        length: 8, timeout: 600000,
        options: { memory_size: 16 << 20, disable_jit: !jit, ir_sync_publication: true },
        setup: emulator => { emulator.v86.cpu.mem8.set(new Uint8Array(vectors.buffer), VECTORS); },
        inspect: emulator => {
            const cpu = emulator.v86.cpu;
            output = cpu.mem8.slice(OUT, OUT + length);
            stats = Array.from({ length: 13 }, (_, i) => cpu.wm.exports.x64_page_stat(i));
        },
    });
    results.push(output);
    console.log(`${jit ? "page tier" : "interpreter"}: native ${stats[1]}, compiled ${stats[0]}, retries ${stats[2]}, steps ${stats[4]}, templated ${stats[10]}`);
    if(jit)
    {
        assert.ok(stats[1] > forms.length * COUNT * 8, "the page tier ran the forms: " + stats);
        // the loop bodies are templated: few steps per iteration
        assert.ok(stats[4] < forms.length * COUNT * ROUNDS / 4, "SSE forms were templated: " + stats);
    }
}
for(let form = 0; form < forms.length; form++)
{
    for(let v = 0; v < COUNT; v++)
    {
        const at = (form * COUNT + v) * OUT_STRIDE;
        const differs = results[0].subarray(at, at + OUT_STRIDE).some((byte, i) => byte !== results[1][at + i]);
        if(differs)
        {
            const hex = bytes => Buffer.from(bytes).toString("hex");
            assert.fail(`${forms[form].text} vector ${v} (mxcsr ${vectors.getUint32(v * STRIDE, true).toString(16)}, ` +
                `a ${hex(new Uint8Array(vectors.buffer, v * STRIDE + 16, 16))}, b ${hex(new Uint8Array(vectors.buffer, v * STRIDE + 32, 16))}): ` +
                `interpreter ${hex(results[0].subarray(at, at + OUT_STRIDE))} page tier ${hex(results[1].subarray(at, at + OUT_STRIDE))}`);
        }
    }
}
console.log(`X64_SSE_INT_TEMPLATE_PASS ${forms.length} forms x ${COUNT} vectors x ${ROUNDS} rounds`);
                                                                                                                                                                                 source/v64/tests/x64/ssse3.mjs                                                                      0000644 0000000 0000000 00000024104 00000000000 013223  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// SSSE3 in the x64 engine (docs/simd-xsave-plan.md P3): the MMX and XMM forms
// in 64-bit mode (XMM8-15 through REX, which MMX registers ignore) and in
// compatibility mode, with register and memory sources, against QEMU and the
// SDM model of tests/rust/ssse3_model.mjs; #GP(0) for a misaligned XMM memory
// operand (none for MMX), #NM with CR0.TS, #UD with CR0.EM or F3, in both
// modes. Interpreted and with the x64 page tier, with and without its
// compatibility-mode code (x64_page_compat32). Both blocks loop so that they
// become hot.
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {OPS, PALIGNR, model} from "../rust/ssse3_model.mjs";

const OUT = 0x300000, CASE = OUT + 0x80, SKIP = OUT + 0x84, MATCH = OUT + 0xC0, FAULTS = OUT + 0x100, RESULTS = OUT + 0x1000;
// (compatibility-mode code is compiled only after a while)
const IDT = 0x380000, ROUNDS = 400, COMPAT_ROUNDS = 20000;

// 16 sample vectors: random bytes and lanes of edge values
const samples = new Uint8Array(16 * 16);
{
    const view = new DataView(samples.buffer);
    let seed = 0x13579BDF;
    const random = () => { seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5; return seed >>> 0; };
    const edges = [[1, [0x00, 0x01, 0x7F, 0x80, 0x81, 0xFF, 0x40, 0xC0]],
        [2, [0x0000, 0x0001, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0x4000, 0xC000]],
        [4, [0, 1, 0x7FFFFFFF, 0x80000000, 0x80000001, 0xFFFFFFFF, 0x40000000, 0xC0000000]]];
    for(let n = 0; n < 16; n++)
    {
        const [size, values] = edges[n % 4] || [1, null];
        for(let i = 0; i < 16; i += size)
        {
            const value = values ? values[random() & 7] : random() & 255;
            if(size === 1) samples[n * 16 + i] = value;
            else if(size === 2) view.setUint16(n * 16 + i, value, true);
            else view.setUint32(n * 16 + i, value, true);
        }
    }
}
const sample = i => samples.subarray(i * 16, i * 16 + 16);

// the cases: [long, xmm, op, memory, dst, src, a, b, imm8]
const cases = [];
for(const [op, name] of OPS)
{
    for(const long of [true, false]) for(const xmm of [true, false]) for(const memory of [false, true])
    {
        const imms = op === PALIGNR ? (long && !memory ? [0, 1, 4, 7, 8, 9, 15, 16, 17, 24, 31, 32, 200] : [3, 12, 20]) : [0];
        const pairs = memory ? [[3, 6]] : [[0, 1], [2, 5], [7, 7]];
        for(const imm8 of imms) for(const [a, b] of op === PALIGNR ? [[9, 10]] : pairs)
        {
            const n = cases.length;
            const count = long && xmm ? 16 : 8, base = long && xmm ? 8 : 0;
            const dst = base + n % 8;
            // (a destination that is also the source: sample pair [7, 7] and every 11th case)
            const src = memory ? undefined : a === b || n % 11 === 0 ? dst : (dst + 1 + n * 5 % (count - 1)) % count;
            cases.push({long, xmm, op, name, memory, dst, src, a, b, imm8,
                // (MMX memory operands need no alignment)
                offset: memory && !xmm ? n & 7 : 0});
        }
    }
}
const code = (c, n) => {
    const reg = r => (c.xmm ? "xmm" : "mm") + r, load = c.xmm ? "movdqu" : "movq";
    const at = i => `[samples + ${i * 16}]`;
    const lines = [`${load} ${reg(c.dst)},${at(c.a)}`];
    if(!c.memory) lines.push(`${load} ${reg(c.src)},${at(c.b)}`);
    lines.push(c.raw || `${c.name} ${reg(c.dst)},${c.memory ? `[samples + ${c.b * 16 + c.offset}]` : reg(c.src)}${c.op === PALIGNR ? "," + c.imm8 : ""}`);
    lines.push(`${load} [${RESULTS + n * 16}],${reg(c.dst)}`);
    return lines.join("\n");
};
const block = long => cases.map((c, n) => c.long === long ? code(c, n) : "").filter(Boolean).join("\n");

// 64-bit mode ignores REX for MMX registers: REX.WRB PSHUFB mm2,mm3
cases.push({long: true, xmm: false, op: 0x00, name: "pshufb", memory: false, dst: 2, src: 3, a: 4, b: 11, imm8: 0, offset: 0,
    raw: "db 0x4D, 0x0F, 0x38, 0x00, 0xD3"});

// the faults: [vector, what, long, instruction]
const FAULT_CASES = [
    [13, "pshufb xmm8,[misaligned]", true, "pshufb xmm8,[samples + 8]"],
    [13, "palignr xmm1,[misaligned]", false, "palignr xmm1,[samples + 4],3"],
    [7, "pabsd xmm9,xmm10 with CR0.TS", true, "pabsd xmm9,xmm10"],
    [7, "phaddw mm1,mm2 with CR0.TS", false, "phaddw mm1,mm2"],
    [6, "pmulhrsw xmm1,xmm2 with CR0.EM", true, "pmulhrsw xmm1,xmm2"],
    [6, "psignb mm1,mm2 with CR0.EM", false, "psignb mm1,mm2"],
    [6, "F3 pshufb xmm1,xmm2", true, "db 0xF3, 0x66, 0x0F, 0x38, 0x00, 0xCA"],
    [6, "F3 pshufb mm1,mm2", false, "db 0xF3, 0x0F, 0x38, 0x00, 0xCA"],
];
const SET_CR0 = (bits, long) => long ? `mov rax,cr0\nor eax,${bits}\nmov cr0,rax` : `mov eax,cr0\nor eax,${bits}\nmov cr0,eax`;
const CLEAR_CR0 = long => long ? "mov rax,cr0\nand eax,~12\nmov cr0,rax" : "mov eax,cr0\nand eax,~12\nmov cr0,eax";
const faults = long => FAULT_CASES.map(([vector, what, in_long, instruction], n) => in_long !== long ? "" : `
${vector === 7 ? SET_CR0(8, long) : vector === 6 && what.includes("CR0.EM") ? SET_CR0(4, long) : ""}
mov dword [${CASE}],${n}
mov dword [${SKIP}],fault_end${n} - fault${n}
fault${n}: ${instruction}
fault_end${n}:
${CLEAR_CR0(long)}
mov eax,fault${n}
cmp eax,[${FAULTS + n * 16 + 8}]
sete byte [${MATCH + n}]`).join("\n");

const directory = assemble("ssse3", long_mode_guest(`
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,7
mov rax,HIGH+nm
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
lidt [rel idtr]
mov rax,cr4
or eax,3 << 9 ; OSFXSR, OSXMMEXCPT
mov cr4,rax
; 64-bit mode
mov ecx,${ROUNDS}
.rounds:
${block(true)}
dec ecx
jnz .rounds
emms
${faults(true)}
; compatibility mode
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov ecx,${COMPAT_ROUNDS}
.rounds:
${block(false)}
dec ecx
jnz .rounds
emms
${faults(false)}
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
`, `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
nm:
mov ecx,7
jmp record
gp:
add rsp,8
mov ecx,13
record:
mov edx,[${CASE}]
shl edx,4
mov [${FAULTS} + rdx],ecx
mov rax,[rsp]
mov [${FAULTS} + rdx + 8],rax
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
align 16
samples: db ${Array.from(samples).join(",")}
`));

const length = RESULTS - OUT + cases.length * 16;
const expected = await reference(directory, {length});
const check = (result, label) => {
    // the model first: QEMU is a reference, not the specification
    cases.forEach((c, n) => {
        const size = c.xmm ? 16 : 8;
        const source = c.memory ? samples.subarray(c.b * 16 + c.offset, c.b * 16 + c.offset + size) : sample(c.b).subarray(0, size);
        const destination = !c.memory && c.src === c.dst ? source : sample(c.a).subarray(0, size);
        const value = result.subarray(RESULTS - OUT + n * 16, RESULTS - OUT + n * 16 + size);
        assert.deepEqual(Uint8Array.from(value), model(c.op, destination, source, c.imm8),
            `${label}: ${c.long ? "64-bit" : "compatibility"} ${c.name} ${c.xmm ? "xmm" : "mm"}${c.dst}, ${c.memory ? "[mem]" : (c.xmm ? "xmm" : "mm") + c.src} ${c.imm8}`);
    });
    FAULT_CASES.forEach(([vector, what], n) => {
        assert.equal(result.readUInt32LE(FAULTS - OUT + n * 16), vector, `${label}: ${what}: vector`);
        assert.equal(result[MATCH - OUT + n], 1, `${label}: ${what}: RIP`);
    });
};
check(expected, "QEMU");
for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}],
    // (compatibility-mode code in the page tier, docs/jit-unification-plan.md P7.2)
    ["x64 page tier, compat32", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true,
        jit_switches: {x64_page_compat32: 1}}]])
{
    let page = 0, page32 = 0;
    const result = await actual(directory, {length, timeout: 120000, options: {cpu_features: ["SSSE3"], ...options},
        inspect: emulator => {
            page = emulator.v86.cpu.wm.exports.x64_page_stat(1);
            page32 = emulator.v86.cpu.wm.exports.x64_page_stat(36);
        }});
    check(result, label);
    assert.ok(result.equals(expected), `${label}: equal to QEMU`);
    if(options.disable_jit === false) assert.ok(page > 1000, `${label}: compiled 64-bit code ran (${page})`);
    if(options.jit_switches?.x64_page_compat32) assert.ok(page32 > 0, `${label}: the page tier compiled compatibility-mode code (${page32})`);
    console.log(`PASS (${label}): ${cases.length} SSSE3 cases in 64-bit and compatibility mode, ${FAULT_CASES.length} faults, as QEMU and the SDM model`);
}

// The page tier has templates for PSHUFB and PALIGNR (register and aligned
// memory sources): a hot loop of them runs without steps (x64_page_stat(4))
const ITERATIONS = 100000;
const hot = assemble("ssse3-hot", long_mode_guest(`
mov rax,cr4
or eax,3 << 9
mov cr4,rax
movdqu xmm9,[samples]
mov ecx,${ITERATIONS}
.loop:
movdqu xmm8,[samples + 16]
pshufb xmm8,xmm9
palignr xmm8,[samples + 32],5
pshufb xmm10,[samples + 48]
palignr xmm11,xmm8,20
dec ecx
jnz .loop
movdqu [${OUT + 16}],xmm8
movdqu [${OUT + 32}],xmm10
movdqu [${OUT + 48}],xmm11
`, `
align 16
samples: db ${Array.from(samples.subarray(0, 64)).join(",")}
`));
let steps, retired;
const result = await actual(hot, {length: 64, timeout: 60000,
    options: {cpu_features: ["SSSE3"], disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
    inspect: emulator => {
        steps = emulator.v86.cpu.wm.exports.x64_page_stat(4);
        retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
    }});
const xmm8 = model(PALIGNR, model(0x00, sample(1), sample(0)), sample(2), 5);
assert.deepEqual(Uint8Array.from(result.subarray(16, 32)), xmm8, "hot loop: XMM8");
assert.deepEqual(Uint8Array.from(result.subarray(48, 64)), model(PALIGNR, new Uint8Array(16), xmm8, 20), "hot loop: XMM11");
assert.ok(retired > ITERATIONS * 4 && steps < ITERATIONS / 10, `page tier templates: ${retired} retired, ${steps} steps`);
console.log(`PASS (x64 page tier): PSHUFB and PALIGNR templates (${retired} instructions retired natively, ${steps} steps)`);
                                                                                                                                                                                                                                                                                                                                                                                                                                                            source/v64/tests/x64/step_events.mjs                                                                0000644 0000000 0000000 00000007371 00000000000 014531  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The step profile's events (docs/jit-unification-plan.md P4.0), counted on
// system_bench.mjs's guests: FXSAVE/FXRSTOR, CLTS, MOV CR0 changing TS and
// #NM as often as the guest executes them, whichever tier runs it; HPET and
// ACPI PM timer reads; why the x64 page tier's functions return (a retry, a
// step that ended the activation, why it did: CR0 changes are barriers,
// SYSCALL/SYSRETQ and MOV CR3 only change what P4.3's STEP_CHAIN may
// continue after); misses before the first compile; CPU frames. A step that
// continues (CPUID, IN) is no exit.
import assert from "node:assert/strict";
import {run, iterations, WARM} from "./system_bench.mjs";

const N = 4000;
const profile = {};
for(const name of ["base", "cpuid", "port_in", "retry", "hpet", "syscall", "mov_cr3", "fxsave", "cr0_ts", "nm"])
{
    const {records} = await run(name, N, {profile: true, inspect: name === "base" ? emulator => {
        // (a PM timer read: the guest has no PM base, read the device)
        for(let i = 0; i < 7; i++) emulator.v86.cpu.devices.acpi.pm_read(8, 4);
    } : undefined});
    profile[name] = records;
}
const count = (name, key) => profile[name].find(r => r.name === "long64 " + key)?.count ?? 0;
// (all iterations: the warm pass and the timed one; the timed pass runs compiled)
const all = name => WARM + iterations(name, N), timed = name => iterations(name, N);
const exactly = (name, key, expected) =>
    assert.equal(count(name, key), expected, `${name}: ${key}: ${JSON.stringify(profile[name].slice(0, 12))}`);
const at_least = (name, key, expected) =>
    assert.ok(count(name, key) >= expected, `${name}: ${key} ${count(name, key)} < ${expected}: ${JSON.stringify(profile[name].slice(0, 12))}`);
const below = (name, key, limit) =>
    assert.ok(count(name, key) < limit, `${name}: ${key} ${count(name, key)} >= ${limit}`);

// executed in every tier: exact
exactly("fxsave", "event fxstate FXSAVE", all("fxsave"));
exactly("fxsave", "event fxstate FXRSTOR", all("fxsave"));
exactly("cr0_ts", "event CLTS", all("cr0_ts"));
exactly("cr0_ts", "event CR0.TS", all("cr0_ts"));
exactly("nm", "event #NM", all("nm"));
exactly("nm", "event CLTS", all("nm"));
exactly("nm", "event CR0.TS", all("nm"));
exactly("hpet", "event hpet-read", all("hpet"));
exactly("base", "event pm-timer-read", 7);
// the x64 page tier's exits
at_least("retry", "event exit retry", timed("retry"));
at_least("hpet", "event exit retry", timed("hpet"));
at_least("cr0_ts", "event exit step", 2 * timed("cr0_ts"));
at_least("cr0_ts", "event step-exit barrier", 2 * timed("cr0_ts"));
at_least("cr0_ts", "event step-context cr0", 2 * timed("cr0_ts"));
at_least("syscall", "event step-exit chainable", 2 * timed("syscall"));
at_least("syscall", "event step-context cpl", 2 * timed("syscall"));
at_least("syscall", "event step-context cs", 2 * timed("syscall"));
at_least("mov_cr3", "event step-exit chainable", timed("mov_cr3"));
below("syscall", "event step-exit barrier", timed("syscall") / 10);
for(const name of ["cpuid", "port_in"]) below(name, "event exit step", timed(name) / 10);
at_least("cpuid", "x64page 0F A2", timed("cpuid"));
at_least("port_in", "x64page E4", timed("port_in"));
// misses before the compile, and HLT
at_least("base", "event miss cold", 1);
at_least("base", "event miss compile", 1);
// (no frame events since M11: the region scheduler's begin_cpu_frame noted them)
exactly("base", "event step-exit halt", 1);
console.log(`PASS: the step profile's events: FXSAVE/FXRSTOR, CLTS, CR0.TS, #NM, HPET and PM timer reads counted exactly; ` +
    `retries ${count("retry", "event exit retry")}, SYSCALL/SYSRETQ chainable step exits ${count("syscall", "event step-exit chainable")}, ` +
    `CR0 barriers ${count("cr0_ts", "event step-exit barrier")}, cold misses ${count("base", "event miss cold")}`);
                                                                                                                                                                                                                                                                       source/v64/tests/x64/step_profile.mjs                                                               0000755 0000000 0000000 00000003731 00000000000 014664  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The step profile of the x64 page tier (docs/jit-unification-plan.md P0.5):
// a long-mode loop whose page function steps CPUID and a REX.W CPUID. With
// the JIT switch step_profile on, the steps land under their StepKeys
// (64-bit mode, the x64 page tier; REX.W kept apart), and
// x64_page_profile_get still reads them by the tier's earlier key, which
// sums the two.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {set_jit_switches} from "../../src/jit_switches.js";
import {step_key, step_profile} from "../../tools/step_profile.mjs";

const ITERATIONS = 20000;
const directory = assemble("step-profile", long_mode_guest(`
mov r8d,${ITERATIONS}
.loop:
xor eax,eax
cpuid
xor eax,eax
db 0x48
cpuid
dec r8d
jnz .loop
`));
let profile, legacy, steps;
await actual(directory, {length: 4, timeout: 60000,
    options: {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true},
    setup: emulator => {
        const cpu = emulator.v86.cpu;
        set_jit_switches(cpu.wm.exports, cpu.wasm_memory, {step_profile: 1}, "x64 step_profile");
    },
    inspect: emulator => {
        const e = emulator.v86.cpu.wm.exports;
        profile = step_profile(e);
        legacy = e.x64_page_profile_get(0x1A2);
        steps = e.x64_page_stat(4);
    }});
const count = fields => profile.find(r => r.key === step_key({opcode: 0xA2, map: 1, mode: "long64", stepper: "x64page", ...fields}))?.count ?? 0;
const plain = count({}), wide = count({rex_w: true});
assert.ok(plain >= ITERATIONS / 2 && wide >= ITERATIONS / 2,
    `the x64 page tier stepped CPUID ${plain} and REX.W CPUID ${wide} times (${steps} steps): ${JSON.stringify(profile.slice(0, 4))}`);
assert.equal(legacy, plain + wide, "x64_page_profile_get sums CPUID's StepKeys");
console.log(`PASS: the x64 page tier stepped CPUID ${plain} and REX.W CPUID ${wide} times, under their StepKeys and its earlier key`);
                                       source/v64/tests/x64/system_bench.mjs                                                               0000644 0000000 0000000 00000023056 00000000000 014653  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The host time of single events in 64-bit code under the x64 page tier
// (docs/jit-unification-plan.md P4.0): a loop repeating one event N times,
// timed by the guest's own RDTSC (v86's TSC counts host nanoseconds), against
// the same loop with a NOP. The events are what compiled code leaves to the
// interpreter or leaves altogether: steps that continue (CPUID, POPFQ),
// a retry (a load the access cache refuses: past the end of RAM; a page-
// crossing one is served now, x64::pages::crossing_host), IRETQ,
// SYSCALL with SYSRETQ, port I/O (IN from port 80h), an HPET register read
// (MMIO), FXSAVE with FXRSTOR, MOV CR3, a TS write to CR0 with CLTS (both end
// the activation: CR0 changed), lazy FPU switching (TS set, #NM, CLTS,
// IRETQ), RDTSC (a helper call), an interrupt window (STI, an instruction in
// its shadow, CLI); and per instruction, code outside compiled code:
// interpreted, and cold (misses). P4.1 ranks the exits with these costs.
//
//   node tests/x64/system_bench.mjs [iterations=400000] [rounds=3] [event...]
//   node tests/x64/system_bench.mjs --events [iterations=20000] [event...]
// Each guest runs its loop twice, timing the second pass (the first compiles
// it). --events runs each guest once with the step profile on and prints its
// StepKeys and events per iteration of both passes instead
// (tests/x64/step_events.mjs checks them). Needs build/libv86.mjs with
// TEST_RELEASE_BUILD=1 (else src/main.js). JIT_SWITCHES applies.
import {fileURLToPath} from "node:url";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";
import {set_jit_switches} from "../../src/jit_switches.js";
import {step_profile} from "../../tools/step_profile.mjs";

// The guest's 1 GiB identity map also accessible to CPL 3 (SYSRETQ's user code)
const USER_PAGES = `or dword [0x200000],4
or dword [0x200800],4
or dword [0x201000],4
mov rdi,0x202000
mov ecx,512
.user_pages:
or dword [rdi],4
add rdi,8
loop .user_pages
mov rax,cr3
mov cr3,rax`;
// IDT vector 7 (#NM) to nm_handler, the IDT at 5 MiB
const NM_IDT = `mov rdi,0x500000+7*16
lea rax,[rel nm_handler]
mov [rdi],ax
mov word [rdi+2],0x18
mov word [rdi+4],0x8E00
shr rax,16
mov [rdi+6],ax
shr rax,16
mov [rdi+8],eax
mov dword [rdi+12],0
mov word [0x501000],0xFFF
mov rax,0x500000
mov [0x501002],rax
lidt [0x501000]`;

// Each event: its loop body; setup before the loop; handlers (code after
// the guest's end); `scale` of the iterations; emulator options. In the loop
// rbx points at data (4 MiB), r8 counts, r13 the pass, r14 the start time.
export const EVENTS = {
    base: {loop: "nop"},
    cpuid: {loop: "xor eax,eax\ncpuid"},
    popfq: {loop: "pushfq\npopfq"},
    // (POPFQ toggling AC: a step that ends the activation, chainable; less
    // popfq, what ending it adds to a step)
    popfq_ac: {loop: "pushfq\nxor dword [rsp],0x40000\npopfq"},
    // (192 MiB past the data: no RAM there, no device either)
    retry: {loop: "mov rax,[rbx+0xC000000]"},
    iretq: {loop: "mov rax,rsp\npush 16\npush rax\npushfq\npush 24\nlea rax,[rel .next]\npush rax\niretq\n.next:"},
    // (the loop at CPL 3: SYSRETQ enters it, a SYSCALL with r9 set leaves)
    syscall: {
        setup: `${USER_PAGES}
mov ecx,0xC0000080
rdmsr
or eax,1
wrmsr
mov ecx,0xC0000081
xor eax,eax
mov edx,0x00080018
wrmsr
mov ecx,0xC0000082
lea rax,[rel syscall_entry]
mov rdx,rax
shr rdx,32
wrmsr
mov ecx,0xC0000084
xor eax,eax
xor edx,edx
wrmsr
xor r9d,r9d
lea rcx,[rel .user]
pushfq
pop r11
o64 sysret
.user:`,
        loop: "syscall",
        leave: "mov r9d,1\nsyscall",
        handlers: `syscall_entry:
test r9d,r9d
jnz bench_done
o64 sysret`,
    },
    port_in: {loop: "in al,0x80"},
    // (Q35's HPET: its 2 MiB at 0xFEC00000 uncached, read the main counter)
    hpet: {
        setup: `mov qword [0x201018],0x203003
mov rax,0xFEC0009B
mov [0x203000+0x1F6*8],rax
mov rax,cr3
mov cr3,rax
mov rsi,0xFED000F0`,
        loop: "mov eax,[rsi]",
        options: {machine_type: "q35", hpet: true},
    },
    fxsave: {setup: "mov rax,cr4\nor eax,0x600\nmov cr4,rax", loop: "fxsave [rbx]\nfxrstor [rbx]", scale: 0.1},
    mov_cr3: {loop: "mov rax,cr3\nmov cr3,rax"},
    cr0_ts: {loop: "mov rax,cr0\nor eax,8\nmov cr0,rax\nclts"},
    // (#NM at FNOP, the handler clears TS and returns to it)
    nm: {setup: NM_IDT, loop: "mov rax,cr0\nor eax,8\nmov cr0,rax\nfnop", handlers: "nm_handler:\nclts\niretq", scale: 0.5},
    rdtsc: {loop: "rdtsc"},
    // (an interrupt window: STI, NOP in its shadow, CLI; the PICs masked,
    // the guest has no IDT)
    sti: {setup: "mov al,0xFF\nout 0x21,al\nout 0xA1,al", loop: "sti\nnop\ncli"},
    // Instructions outside compiled code, ns per instruction: interpreted
    // with the x64 page tier off (its run() returns at once), and code that
    // stays cold: COLD_PAGES pages run once, each a loop of 1801
    // instructions, under the tier's compile threshold (2000), so every
    // instruction is a cold miss (P4.5c)
    interp: {loop: "nop", options: {jit_switches: {x64_page: 0}}, per_instruction: 3},
    cold: {cold: true},
};

const COLD_PAGES = 180, COLD_INSTRUCTIONS = 1 + 600 * 3 + 1;
// (cold: one pass of one iteration)
export const iterations = (name, n) => EVENTS[name].cold ? 1 : Math.max(1, Math.round(n * (EVENTS[name].scale ?? 1)));
/** The iterations of the untimed first pass, which compiles the loop's page */
export const WARM = 5000;
/** Instructions per iteration of the events timed per instruction */
export const per_instruction = name => EVENTS[name].cold ? COLD_PAGES * COLD_INSTRUCTIONS : EVENTS[name].per_instruction;

/** The guest of event `name`: WARM iterations, then `n` (scaled) timed into 0x300008 */
export function guest(name, n)
{
    const event = EVENTS[name];
    // (each page: its loop, then a jump over the padding to the next page)
    if(event.cold) return long_mode_guest(`rdtsc
shl rdx,32
or rax,rdx
mov r14,rax
jmp cold_pages
%macro COLD_PAGE 0
mov ecx,600
%%loop:
nop
dec ecx
jnz %%loop
jmp %%next
align 4096,db 0xCC
%%next:
%endmacro
align 4096,db 0xCC
cold_pages:
%rep ${COLD_PAGES}
COLD_PAGE
%endrep
rdtsc
shl rdx,32
or rax,rdx
sub rax,r14
mov [0x300008],rax
bench_done:`);
    return long_mode_guest(`mov rbx,0x400000
${event.setup || ""}
xor r13d,r13d
.pass:
mov r8d,${WARM}
test r13d,r13d
jz .start
mov r8d,${iterations(name, n)}
.start:
rdtsc
shl rdx,32
or rax,rdx
mov r14,rax
.loop:
${event.loop}
dec r8d
jnz .loop
rdtsc
shl rdx,32
or rax,rdx
sub rax,r14
mov [0x300008],rax
inc r13d
cmp r13d,2
jb .pass
${event.leave || ""}
bench_done:`, event.handlers || "");
}

const JIT = {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true};

/** Run event `name`'s guest: the loop's nanoseconds; with `profile`, also
 * the step profile (after `inspect`, which gets the emulator); `switches`:
 * JIT switches for this run */
export async function run(name, n, {profile = false, inspect, switches = {}} = {})
{
    const directory = assemble(`system-bench-${name}`, guest(name, n));
    let records;
    const options = {...JIT, ...EVENTS[name].options};
    options.jit_switches = {...options.jit_switches, ...switches};
    const result = await actual(directory, {length: 16, timeout: 300000, options,
        setup: emulator => {
            const cpu = emulator.v86.cpu;
            // (the runner steps the cores itself: the machine clock, and with
            // it the TSC, would stand still)
            cpu.clock.resume();
            if(profile) set_jit_switches(cpu.wm.exports, cpu.wasm_memory, {step_profile: 1}, "system_bench");
        },
        inspect: emulator => {
            inspect?.(emulator);
            if(profile) records = step_profile(emulator.v86.cpu.wm.exports);
        }});
    return {ns: Number(result.readBigUint64LE(8)), records};
}

async function main()
{
    const args = process.argv.slice(2);
    const events = args[0] === "--events";
    if(events) args.shift();
    const numbers = args.filter(a => /^\d+$/.test(a)).map(Number);
    const names = args.filter(a => !/^\d+$/.test(a));
    for(const name of names) if(!EVENTS[name]) throw new Error(`no event ${name}: ${Object.keys(EVENTS).join(" ")}`);
    if(events)
    {
        const n = numbers[0] || 20000;
        for(const name of names.length ? names : Object.keys(EVENTS))
        {
            const {records} = await run(name, n, {profile: true});
            const count = EVENTS[name].cold ? COLD_PAGES * 600 : WARM + iterations(name, n);
            const rows = records.filter(r => r.count >= count / 4).slice(0, 12)
                .map(r => `${r.name} ${+(r.count / count).toFixed(2)}`);
            console.log(`${name} (${count} iterations): ${rows.join(", ")}`);
        }
        return;
    }
    const N = numbers[0] || 400000, ROUNDS = numbers[1] || 3;
    const chosen = ["base", ...(names.length ? names : Object.keys(EVENTS)).filter(name => name !== "base")];
    const times = {};
    for(let round = 0; round < ROUNDS; round++)
    {
        for(const name of chosen)
        {
            (times[name] ??= []).push((await run(name, N)).ns / iterations(name, N));
        }
    }
    const median = values => [...values].sort((a, b) => a - b)[values.length >> 1];
    const base = median(times.base);
    const result = {iterations: N, rounds: ROUNDS, base_ns: +base.toFixed(2), ns_per_event: {}, ns_per_instruction: {}};
    for(const name of chosen.slice(1))
    {
        if(per_instruction(name)) result.ns_per_instruction[name] = +(median(times[name]) / per_instruction(name)).toFixed(1);
        else result.ns_per_event[name] = +(median(times[name]) - base).toFixed(1);
    }
    console.log(JSON.stringify(result));
}

if(process.argv[1] === fileURLToPath(import.meta.url)) await main();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  source/v64/tests/x64/system_oracle.mjs                                                              0000644 0000000 0000000 00000064631 00000000000 015045  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";
const cases = [];
const add = (name, code) => cases.push({name, code});
const fault = (name, code, vector, error = 0) => add(name, `lea rax, [rel .resume]\nmov [0x500010], rax\n${code}\n.resume:\nmov rax, ${vector}\nmov rbx, ${error}`);
add("wide descriptor registers", "sgdt [0x501000]\nsidt [0x501010]\nmov rax, [0x501002]\nmov rbx, [0x501012]\nstr cx\nsldt dx");
add("FS and kernel GS MSRs", "mov ecx, 0xC0000100\nmov eax, 0x55667788\nmov edx, 0xFFFF8888\nwrmsr\nrdmsr\nmov ebx, edx");
add("SWAPGS full bases", "mov ecx, 0xC0000101\nmov eax, 0x12345678\nmov edx, 0xFFFF9000\nwrmsr\nmov ecx, 0xC0000102\nmov eax, 0x87654321\nmov edx, 0xFFFFA000\nwrmsr\nswapgs\nmov ecx, 0xC0000101\nrdmsr\nmov ebx, edx\nswapgs");
add("RDTSCP TSC_AUX", "mov ecx, 0xC0000103\nmov eax, 0xFEDCBA98\nxor edx, edx\nwrmsr\nrdtscp\nxor eax, eax\nxor edx, edx");
add("PAT read and write", "mov ecx, 0x277\nmov eax, 0x00070406\nmov edx, eax\nwrmsr\nrdmsr");
fault("noncanonical LSTAR", "mov ecx, 0xC0000082\nxor eax, eax\nmov edx, 0x8000\nwrmsr", 13);
fault("reserved CR3 physical bits", "mov rax, 0x1000000000\nmov cr3, rax", 13);
fault("LMA cannot clear PAE", "mov rax, cr4\nand eax, ~0x20\nmov cr4, rax", 13);
fault("LME is immutable while paging", "mov ecx, 0xC0000080\nrdmsr\nand eax, ~0x100\nwrmsr", 13);
fault("long CS cannot clear paging", "mov rax, cr0\nbtr rax, 31\nmov cr0, rax", 13);
fault("noncanonical load", "mov rax, 0x800000000000\nmov rbx, [rax]", 13);
fault("noncanonical stack operand", "mov rbp, 0x800000000000\nmov rbx, [rbp]", 12);
fault("unmapped canonical page", "mov rax, 0x40000000\nmov rbx, [rax]", 14);
fault("illegal instruction", "ud2", 6);
fault("division error", "xor edx, edx\nxor ecx, ecx\ndiv rcx", 0);
fault("invalid TSS selector", "mov eax, 0x10\nltr ax", 13, 16);
fault("busy TSS reload", "mov eax, 0x38\nltr ax", 13, 56);
add("same privilege interrupt full frame", "int 0x40");
add("IST stack and IRETQ", "int 0x41");
add("SYSCALL kernel entry preserves high RCX and R11", "mov ecx, 0xC0000081\nmov eax, 0\nmov edx, 0x00180018\nwrmsr\nmov ecx, 0xC0000082\nlea rax, [rel .entry]\nmov rdx, rax\nshr rdx, 32\nwrmsr\nmov ecx, 0xC0000084\nmov eax, 0x600\nxor edx, edx\nwrmsr\nsyscall\njmp .done\n.entry:\nmov rax, rcx\nmov rbx, r11\njmp rcx\n.done:");
add("user IRETQ SYSCALL SYSRETQ round trip", "mov ecx, 0xC0000081\nxor eax, eax\nmov edx, 0x00200018\nwrmsr\nmov ecx, 0xC0000082\nlea rax, [rel .service]\nmov rdx, rax\nshr rdx, 32\nwrmsr\nmov qword [0x500018], 0\npush 0x23\npush 0x3D0000\npush 2\npush 0x33\nlea rax, [rel .user]\npush rax\niretq\n.user:\nmov rax, 0x1122334455667788\nsyscall\nmov rbx, 0x8877665544332211\nsyscall\n.service:\ninc qword [0x500018]\ncmp qword [0x500018], 1\njne .done\no64 sysret\n.done:\nmov rsp, 0x3F0000\nmov rcx, [0x500018]\nmov rdx, 0");
add("RETFQ compatibility code and 32-bit far RET return", "push 8\nmov eax, .compat\npush rax\no64 retf\nbits 32\n.compat:\nmov eax, 0x76543210\nmov ebx, 0xFEDCBA98\npush dword 0x18\npush dword .back64\nretf\nbits 64\n.back64:\nmov rdx, HIGH+.high\njmp rdx\n.high:\nxor edx, edx");
add("compatibility SYSENTER to full high kernel RIP", "mov ecx, 0x174\nmov eax, 0x18\nxor edx, edx\nwrmsr\nmov ecx, 0x175\nmov eax, 0x3F0000\nwrmsr\nmov ecx, 0x176\nlea rax, [rel .entry64]\nmov rdx, rax\nshr rdx, 32\nwrmsr\npush 0x23\npush 0x3D0000\npush 2\npush 0x2B\nmov eax, .compat\npush rax\niretq\nbits 32\n.compat:\nmov ebx, 0xAABBCCDD\nsysenter\nbits 64\n.entry64:\nmov rax, rsp\nmov ecx, 0x11223344\nxor edx, edx\nmov esi,0x10\nmov ss,si");
add("full-width debug address registers", "mov rax, 0xFFFF812345678900\nmov dr0, rax\nmov rbx, dr0\nxor eax,eax\nmov dr0,rax\nmov dr7,rax\nmov rcx,dr7");
fault("DR6 rejects high reserved bits", "mov rax,0x100000000\nmov dr6,rax",13);
add("DR0 retains full noncanonical bit pattern", "mov rax,0x800000000000\nmov dr0,rax\nmov rbx,dr0\nxor eax,eax\nmov dr0,rax");
fault("DR4 with CR4.DE", "mov rdx,cr4\nbts rdx,3\nmov cr4,rdx\nmov rax,dr4",6);
add("debug general-detect fault", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov eax,0x2000\nmov dr7,rax\nmov rbx,0x1234\nmov rbx,dr0\n.resume:\nmov rax,dr7\nmov rcx,dr6\nxor edx,edx\nmov dr6,rdx");
add("trap flag retires one instruction before DB", "xor eax,eax\nmov dr6,rax\npush qword 0x102\npopfq\ninc eax\nmov rbx,dr6");
add("FS GS stack selectors", "mov eax,0x10\nmov fs,ax\nmov gs,ax\npush fs\npop rax\npush gs\npop rbx\npush qword 0x10\npop fs\npush qword 0x10\npop gs\nmov cx,fs\nmov dx,gs");
for(const [name, instruction] of [["LAR code", "lar rax,ecx"], ["LSL data", "lsl rax,ecx"], ["VERR code", "verr cx"], ["VERW data", "verw cx"]])
{
    add(name, `mov ecx,0x10\nmov rax,0x123456789ABCDEF0\n${instruction}\npushfq\npop rbx\nand ebx,0x40`);
}
add("LAR invalid selector preserves destination", "mov ecx,0xFFF0\nmov rax,0x123456789ABCDEF0\nlar rax,ecx\npushfq\npop rbx\nand ebx,0x40");
fault("NX instruction fetch preserves full fault address", "mov qword [0x202040],0x1000087\nbts qword [0x202040],63\nmov rax,0x1000000\ninvlpg [rax]\njmp rax",14,17);
fault("CR0.WP write protection", "mov qword [0x202040],0x1000085\nmov rax,0x1000000\ninvlpg [rax]\nmov qword [rax],0x1234",14,3);
fault("reserved physical address bit in large leaf", "mov rax,0x1001000087\nmov [0x202040],rax\nmov rax,0x1000000\ninvlpg [rax]\nmov rbx,[rax]",14,9);
add("cross-page write fault has no RAM partial commit", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov qword [0x202060],0x208007\nmov qword [0x208000],0x1800007\nmov qword [0x208008],0x1801005\nmov eax,0x1800000\ninvlpg [rax]\nadd eax,0x1000\ninvlpg [rax]\nmov dword [0x1800FFC],0xAABBCCDD\nmov rax,0x1122334455667788\nmov [0x1800FFC],rax\n.resume:\nmov eax,[0x1800FFC]\nmov ebx,3");
add("wide TLB retains translation until INVLPG", "mov qword [0x202060],0x208007\nmov qword [0x208000],0x1800007\nmov dword [0x1A00000],0x76543210\nmov eax,0x1800000\ninvlpg [rax]\nmov dword [rax],0x12345678\nmov ebx,[rax]\nmov qword [0x208000],0x1A00007\nmov ebx,[rax]\ninvlpg [rax]\nmov ecx,[rax]\nxor eax,eax");
add("execution breakpoint faults before register commit", "lea rax,[rel .resume]\nmov [0x500010],rax\nxor eax,eax\nmov dr6,rax\nlea rax,[rel .watched]\nmov dr0,rax\nmov eax,1\nmov dr7,rax\nxor eax,eax\n.watched:\ninc eax\n.resume:\nxor edx,edx\nmov dr7,rdx\nmov rbx,dr6");
add("high data write breakpoint traps after committed store", "xor eax,eax\nmov dr6,rax\nmov rdi,HIGH+0x500800\nmov dr0,rdi\nmov eax,0x90001\nmov dr7,rax\nmov r9,0x1122334455667788\nmov [rdi],r9\nxor eax,eax\nmov dr7,rax\nmov rax,[rdi]\nmov rbx,dr6");
add("high data read breakpoint traps after register commit", "xor eax,eax\nmov dr6,rax\nmov rdi,HIGH+0x500800\nmov dr0,rdi\nmov eax,0xB0001\nmov dr7,rax\nmov rax,[rdi]\nxor edx,edx\nmov dr7,rdx\nmov rbx,dr6");
// Far transfers in 64-bit mode (SDM Vol.2A JMP/CALL; Vol.3A §5.8.3.1).
// The case fills the 64-bit call gate at GDT 0x48 (DPL 3) with its target.
const gate = (target, selector = "0x18") => `lea rax,[rel ${target}]\nmov word [rel gdt+0x48],ax\nmov word [rel gdt+0x4A],${selector}\nmov word [rel gdt+0x4C],0xEC00\nshr rax,16\nmov word [rel gdt+0x4E],ax\nshr rax,16\nmov dword [rel gdt+0x50],eax\nmov dword [rel gdt+0x54],0`;
add("far JMP m16:32 to compatibility code and RETF back", "jmp far dword [rel .ptr]\n.ptr: dd .compat\ndw 0x08\nbits 32\n.compat:\nmov eax,0x13572468\nmov ebx,cs\npush dword 0x18\npush dword .back64\nretf\nbits 64\n.back64:\nmov rdx,HIGH+.high\njmp rdx\n.high:\nxor edx,edx");
add("far CALL m16:64 to 64-bit code and RETFQ", "call far qword [rel .ptr]\nmov rdx,rsp\njmp .done\n.target:\nmov rax,[rsp]\nmov rbx,[rsp+8]\nmov rcx,cs\no64 retf\n.ptr: dq .target\ndw 0x18\n.done:\nsub rdx,0x3F0000");
add("far CALL m16:32 pushes 32-bit CS:EIP", "call far dword [rel .ptr]\n.ret32:\nmov rdx,HIGH+.high\njmp rdx\n.target:\nmov eax,[rsp]\nmov ebx,[rsp+4]\nlea rcx,[rsp+8]\nsub rcx,0x3F0000\nretf\n.ptr: dd .target\ndw 0x18\n.high:\nxor edx,edx");
add("64-bit call gate from CPL3 to CPL0 switches to TSS RSP0", gate(".entry") + "\npush 0x23\npush 0x3D0000\npush 2\npush 0x33\nlea rax,[rel .user]\npush rax\niretq\n.user:\ncall far dword [rel .ptr]\n.ptr: dd 0\ndw 0x4B\n.entry:\nmov rax,[rsp+8]\nmov rbx,[rsp+24]\nmov rcx,[rsp+16]\nmov rdx,rsp\nmov rsi,ss\nshl rsi,32\nor rdx,rsi\nmov rsi,cs\nshl rsi,48\nor rdx,rsi\nmov rsp,0x3F0000\nmov esi,0x10\nmov ss,si");
add("64-bit call gate at same privilege keeps the stack", gate(".entry") + "\ncall far dword [rel .ptr]\n.ptr: dd 0\ndw 0x48\n.entry:\nmov rax,[rsp+8]\nlea rbx,[rsp+16]\nsub rbx,0x3F0000\nmov rcx,cs\nmov rsp,0x3F0000");
fault("far JMP to a TSS selector", "jmp far dword [rel .ptr]\n.ptr: dd 0\ndw 0x38", 13, 0x38);
fault("far JMP to a data segment", "jmp far dword [rel .ptr]\n.ptr: dd 0\ndw 0x10", 13, 0x10);
fault("far JMP null selector", "jmp far dword [rel .ptr]\n.ptr: dd 0\ndw 0", 13, 0);
fault("far JMP register form", "db 0xFF,0xE8", 6);
fault("far CALL noncanonical 64-bit offset", "call far qword [rel .ptr]\n.ptr: dq 0x800000000000\ndw 0x18", 13, 0);
fault("far JMP to DPL3 code from CPL0", "jmp far dword [rel .ptr]\n.ptr: dd 0\ndw 0x30", 13, 0x30);
fault("call gate to 32-bit code", gate(".entry", "0x08") + "\ncall far dword [rel .ptr]\n.ptr: dd 0\ndw 0x48\n.entry:\nnop", 13, 8);
fault("call gate above the GDT limit", "call far dword [rel .ptr]\n.ptr: dd 0\ndw 0x58", 13, 0x58);

// Leaving long mode (SDM Vol.3A §10.8.5): compatibility code, paging off
// (LMA clears), LME off, legacy protected mode, and back.
add("leave long mode through compatibility code and re-enter", "push 8\nmov eax,.compat\npush rax\no64 retf\nbits 32\n.compat:\nmov eax,cr0\nand eax,0x7FFFFFFF\nmov cr0,eax\nmov ecx,0xC0000080\nrdmsr\nand eax,~0x100\nwrmsr\nrdmsr\nmov esi,eax\nmov edi,0x13579BDF\nor eax,0x100\nwrmsr\nmov eax,cr0\nor eax,0x80000000\nmov cr0,eax\njmp 0x18:.long_again\nbits 64\n.long_again:\nmov rax,HIGH+.high\njmp rax\n.high:\nmov ecx,0xC0000080\nrdmsr\nmov rbx,rsi\nmov rcx,rdi\nmov edx,eax\nxor eax,eax");
// Priority among simultaneous exceptions (SDM Vol.3A §6.9, instruction tables).
add("MOVAPS alignment #GP precedes the page fault", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov rdx,cr4\nbts rdx,9\nmov cr4,rdx\nmov rax,0x40000008\nmovaps xmm0,[rax]\n.resume:\nmov rdx,cr4\nbtr rdx,9\nmov cr4,rdx\nxor edx,edx");
add("SSE without OSFXSR is #UD even with CR0.TS", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov rdx,cr0\nbts rdx,3\nmov cr0,rdx\nmovaps xmm0,xmm1\n.resume:\nmov rdx,cr0\nbtr rdx,3\nmov cr0,rdx\nxor edx,edx");
add("SSE with OSFXSR and CR0.TS is #NM", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov rdx,cr4\nbts rdx,9\nmov cr4,rdx\nmov rdx,cr0\nbts rdx,3\nmov cr0,rdx\nmovaps xmm0,xmm1\n.resume:\nmov rdx,cr0\nbtr rdx,3\nmov cr0,rdx\nmov rdx,cr4\nbtr rdx,9\nmov cr4,rdx\nxor edx,edx");
add("x87 with CR0.TS is #NM; WAIT only with CR0.MP", "lea rax,[rel .first]\nmov [0x500010],rax\nmov rdx,cr0\nbts rdx,3\nmov cr0,rdx\nfwait\ninc ecx\nfld1\n.first:\nmov rbx,[0x500020]\nlea rax,[rel .second]\nmov [0x500010],rax\nmov rdx,cr0\nbts rdx,1\nmov cr0,rdx\nfwait\ninc ecx\n.second:\nmov rdx,cr0\nand edx,~0xA\nmov cr0,rdx\nfninit\nxor edx,edx");
add("cross-page read faults at the second page", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov rax,0x3FFFFFFC\nmov rbx,[rax]\n.resume:\nxor eax,eax");
const small_pages = "mov qword [0x202060],0x208007\nmov qword [0x208000],0x1800007\nmov qword [0x208008],0\nmov eax,0x1800000\ninvlpg [rax]\nadd eax,0x1000\ninvlpg [rax]\n";
add("PUSH crossing into a not-present page leaves RSP", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov byte [rel idt+14*16+4],1\n" + small_pages + "mov rcx,rsp\nmov rsp,0x1801004\nmov rax,0x1122334455667788\npush rax\n.resume:\nmov rdx,rsp\nmov rsp,rcx\nmov byte [rel idt+14*16+4],0\nxor eax,eax\nxor ecx,ecx");
add("instruction fetch crossing into a not-present page", "lea rax,[rel .resume]\nmov [0x500010],rax\n" + small_pages + "mov dword [0x1800FFE],0x223344B8\nmov eax,0x55\nmov rcx,0x1800FFE\njmp rcx\n.resume:\nxor ecx,ecx");
add("code breakpoint precedes the fetch page fault", "lea rax,[rel .resume]\nmov [0x500010],rax\nxor eax,eax\nmov dr6,rax\nmov rax,0x40000000\nmov dr0,rax\nmov eax,1\nmov dr7,rax\nmov rax,0x40000000\njmp rax\n.resume:\nxor edx,edx\nmov dr7,rdx\nmov rbx,dr6\nmov dr6,rdx\nxor eax,eax");
add("single step and a data breakpoint report in one #DB", "lea rax,[rel .resume]\nmov [0x500010],rax\nxor eax,eax\nmov dr6,rax\nmov eax,0x500800\nmov dr0,rax\nmov eax,0x10001\nmov dr7,rax\npush qword 0x102\npopfq\nmov byte [0x500800],1\ninc ecx\n.resume:\nxor edx,edx\nmov dr7,rdx\nmov rbx,dr6\nmov dr6,rdx\nxor eax,eax");
add("MOV SS delays the single-step trap by one instruction", "lea rax,[rel .resume]\nmov [0x500010],rax\nxor eax,eax\nmov dr6,rax\nmov eax,0x10\npush qword 0x102\npopfq\nmov ss,ax\ninc ecx\ninc edx\n.resume:\nmov rbx,dr6\nxor eax,eax\nmov dr6,rax");
add("single step does not trap a faulting instruction", "lea rax,[rel .resume]\nmov [0x500010],rax\nxor eax,eax\nmov dr6,rax\npush qword 0x102\npopfq\nmov rbx,[0x40000000]\n.resume:\nmov rbx,dr6\nxor eax,eax\nmov dr6,rax");
// A #PF while pushing the frame of a #PF escalates to #DF (SDM Vol.3A
// §6.15, Table 6-5), delivered on IST1; the saved RIP/RSP of #DF are
// undefined, so only vector, error code and CR2 are compared.
// SYSRET without REX.W (SDM Vol.2B SYSRET): CS = STAR[63:48]|3 as 32-bit
// code, SS = +8, EIP = ECX (high RCX ignored), RFLAGS from R11. In
// compatibility mode 0x40 is INC EAX (in 64-bit mode a REX prefix); SYSENTER
// returns to the kernel.
add("SYSRET to compatibility mode and SYSENTER back", "mov ecx,0xC0000081\nxor eax,eax\nmov edx,0x00200018\nwrmsr\nmov ecx,0x174\nmov eax,0x18\nxor edx,edx\nwrmsr\nmov ecx,0x175\nmov eax,0x3F0000\nwrmsr\nmov ecx,0x176\nlea rax,[rel .entry64]\nmov rdx,rax\nshr rdx,32\nwrmsr\nmov r11,0x43\nmov eax,.compat\nmov rcx,0x5A5A5A5A00000000\nor rcx,rax\nsysret\nbits 32\n.compat:\nlahf\nmov ecx,eax\nmov ebx,cs\nmov edx,ss\nmov eax,0x13572467\ninc eax\nsysenter\nbits 64\n.entry64:\nmov esi,0x10\nmov ss,si\nmovzx ecx,ch");
// Intel SYSRET checks RCX before leaving ring 0 (SDM Vol.2B SYSRET): #GP(0)
// with CPL, CS and RSP unchanged.
fault("SYSRETQ to a noncanonical RIP", "mov ecx,0xC0000081\nxor eax,eax\nmov edx,0x00200018\nwrmsr\nmov r11,2\nmov rcx,0x0000800000000000\no64 sysret", 13);
// Hot 32-bit code in compatibility mode (compiled by v86's IR): loads,
// stores, CALL/RET, a code patch after compilation, then a call into a page
// that the loop only used as data and that is NX: #PF (P|I/D) at its address.
add("compatibility-mode hot loop, code patch and NX", "mov rax,[0x202018]\nbts rax,63\nmov [0x202018],rax\nmov rax,cr3\nmov cr3,rax\nmov eax,.fault_resume\nmov [0x500010],rax\npush 8\nmov eax,.compat\npush rax\no64 retf\nbits 32\n.compat:\nmov ecx,40000\nxor eax,eax\nxor edx,edx\n.loop:\nmov ebx,ecx\nand ebx,1023\nadd eax,[0x600000+ebx*4]\nmov [0x600000+ebx*4],eax\nxor edx,eax\nrol edx,3\ncall .helper\ndec ecx\njnz .loop\nmov [0x601000],eax\nmov [0x601004],edx\nmov dword [.helper+2],0x22222222\nmov ecx,20000\n.loop2:\ncall .helper\ndec ecx\njnz .loop2\nmov [0x601008],edx\nmov byte [0x600800],0xC3\ncall 0x600800\njmp .fault_resume\n.helper:\nadd edx,0x11111111\nret\n.fault_resume:\nadd esp,4\njmp 0x18:.long\nbits 64\n.long:\nmov rax,HIGH+.high\njmp rax\n.high:\nmov rax,[0x202018]\nbtr rax,63\nmov [0x202018],rax\nmov rax,cr3\nmov cr3,rax\nmov eax,[0x601000]\nmov ebx,[0x601004]\nmov ecx,[0x601008]\nxor edx,edx");
// The APIC page: PDPT[3] -> PD at 0x209000, 2 MiB UC page at 0xFEE00000
// (a register source: a qword store sign-extends imm32).
const map_apic = "mov qword [0x201018],0x209003\nmov eax,0xFEE0009B\nmov [0x209000+503*8],rax\nmov rax,cr3\nmov cr3,rax\nmov esi,0xFEE00000\n";
const unmap_apic = "mov qword [0x201018],0\nmov rax,cr3\nmov cr3,rax\n";
// NMI blocking (SDM Vol.3A §6.7.1): a self-NMI through the ICR enters
// handler_2, which sends a second one; it stays pending until IRETQ.
add("second NMI is held until IRETQ", map_apic + "mov dword [rsi+0x310],0\nmov dword [rsi+0x300],0x4400\nmov r8d,1000000\n.wait:\ncmp ebx,2\nje .done\ndec r8d\njnz .wait\n.done:\nxor edx,edx\ntest r8d,r8d\nsetnz dl\n" + unmap_apic + "xor eax,eax");
// CR8 is TPR[7:4] of the local APIC (SDM Vol.3A §10.8.6.1).
add("CR8 aliases the local APIC TPR", map_apic + "add esi,0x80\nmov eax,5\nmov cr8,rax\nmov ebx,[rsi]\nmov dword [rsi],0x3F\nmov rcx,cr8\nxor eax,eax\nmov cr8,rax\nmov edx,[rsi]\n" + unmap_apic + "xor eax,eax");
fault("CR8 reserved bits", "mov eax,16\nmov cr8,rax", 13);
// SYSCALL outside 64-bit mode is #UD on Intel (SDM Vol.2B SYSCALL: CS.L = 0).
// The #UD handler returns to .back, still in compatibility mode.
add("SYSCALL in compatibility mode is #UD", "mov eax,.back\nmov [0x500010],rax\npush 8\nmov eax,.compat\npush rax\no64 retf\nbits 32\n.compat:\nsyscall\n.back:\njmp 0x18:.long\nbits 64\n.long:\nmov rax,HIGH+.high\njmp rax\n.high:\nmov eax,6\nxor ebx,ebx");
add("page fault while delivering a page fault is a double fault on IST", "lea rax,[rel .resume]\nmov [0x500010],rax\nmov rcx,rsp\nmov rsp,0x40001000\nmov rbx,[0x40000100]\n.resume:\nmov rsp,rcx\nxor eax,eax\nxor ecx,ecx\nxor edx,edx\nmov qword [0x500038],0");
// QEMU 10.2 does not implement these control-write faults (misc_helper.c).
// Check them against explicit SDM outcomes in a separate v86 guest.
const specification_cases = cases.splice(5, 5);
// QEMU 10.2's lcall helper lowers RSP by the pushed CS:RIP before raising
// #GP for a noncanonical target; SDM Vol.3A §6.5 restores it for a fault.
// QEMU 10.2 helper_write_crN passes any CR8 value to the TPR (SDM: #GP).
// QEMU 10.2 TCG accepts SYSCALL whenever EFER.LMA is set, compatibility mode included.
// QEMU 10.2 SYSRETQ to a noncanonical RIP faults at CPL3 like AMD, not #GP(0) in ring 0.
for(const name of ["noncanonical stack operand", "reserved physical address bit in large leaf", "far CALL noncanonical 64-bit offset", "CR8 reserved bits", "SYSCALL in compatibility mode is #UD", "SYSRETQ to a noncanonical RIP"])
    specification_cases.push(...cases.splice(cases.findIndex(test => test.name === name), 1));
// QEMU 10.2 TCG never reaches the result marker once a DR0 data watchpoint
// hits a high linear address, so these use SDM Vol.3B §18.2.4/§18.3.1.2
// outcomes: the access completes, then #DB traps with DR6.B0 set.
const expectation_cases = [];
for(const [name, rax, rbx] of [
    ["high data write breakpoint traps after committed store", 0x1122334455667788n, 0xFFFF0FF1n],
    ["high data read breakpoint traps after register commit", 0x1122334455667788n, 0xFFFF0FF1n],
    // SDM Vol.3B §18.2.3: one #DB after the store reports both BS and B0.
    ["single step and a data breakpoint report in one #DB", 0n, 0xFFFF4FF1n],
])
{
    const index = cases.findIndex(test => test.name === name);
    assert.notEqual(index, -1, name);
    expectation_cases.push({...cases.splice(index, 1)[0], rax, rbx});
}
// Compatibility-mode descriptor loads use the full 64-bit GDTR base. Windows
// keeps its GDT above 4 GiB; here a copy at physical 0x800000 is aliased at
// 0xFFFF808000000000 (PML4[257]), whose low 32 bits reach linear 0 instead.
// MOV DS, LAR, LSL and a far JMP back to 64-bit mode all read it (LAR bits
// 19:16 are undefined; QEMU clears them).
add("compatibility-mode descriptor loads from a GDT above 4 GiB", "mov qword [0x200808],0x20A003\nmov qword [0x20A000],0x20B003\nmov qword [0x20B000],0x800083\nmov rax,cr3\nmov cr3,rax\nlea rsi,[rel gdt]\nmov edi,0x800000\nmov ecx,11\nrep movsq\nmov word [0x501100],87\nmov rax,0xFFFF808000000000\nmov [0x501102],rax\nlgdt [0x501100]\npush 8\nmov eax,.compat\npush rax\no64 retf\nbits 32\n.compat:\nmov eax,0x10\nmov ds,ax\nmov ecx,0x18\nlar ebx,eax\nand ebx,0xF0FF00\nlsl edx,eax\njmp 0x18:.long\nbits 64\n.long:\nmov rsi,HIGH+.high\njmp rsi\n.high:\nlgdt [rel gdtr64]\nmov qword [0x200808],0\nmov rsi,cr3\nmov cr3,rsi\nmov esi,ds\nshl rsi,32\nor rax,rsi");
// SYSEXIT (SDM Vol.2B): the 32-bit form enters compatibility mode with
// CS = SYSENTER_CS+16, SS = +24; REX.W enters 64-bit mode with CS = +32,
// SS = +40 (RPL 3, no descriptor reads), RIP = RDX, RSP = RCX. Each returns
// with SYSENTER, after which a far return restores a real kernel CS.
add("SYSEXIT to compatibility and 64-bit mode", "mov ecx,0x174\nmov eax,0x10\nxor edx,edx\nwrmsr\nmov ecx,0x175\nmov eax,0x3F0000\nwrmsr\nmov ecx,0x176\nlea rax,[rel .entry1]\nmov rdx,rax\nshr rdx,32\nwrmsr\nxor ebp,ebp\nmov edx,.compat\nmov ecx,0x3D0000\nsysexit\nbits 32\n.compat:\nmov ebx,ss\nshl ebx,16\nmov bx,cs\nmov ebp,esp\nsysenter\nbits 64\n.entry1:\npush 0x18\nlea rax,[rel .k1]\npush rax\no64 retf\n.k1:\nmov esi,0x10\nmov ss,si\nmov ecx,0x176\nlea rax,[rel .entry2]\nmov rdx,rax\nshr rdx,32\nwrmsr\nlea rdx,[rel .user64]\nmov rcx,0x3D0000\no64 sysexit\n.user64:\nmov r8d,ss\nshl r8d,16\nmov r8w,cs\nmov r10,rsp\nsysenter\n.entry2:\npush 0x18\nlea rax,[rel .k2]\npush rax\no64 retf\n.k2:\nmov esi,0x10\nmov ss,si\nmov eax,ebx\nmov rbx,r8\nmov rcx,r10\nmov rdx,rbp");
// IA32_APIC_BASE in long mode (SDM Vol.3A §10.4.4): BSP|EN|base, written
// back unchanged, cleared EN hides CPUID.1:EDX.APIC, set again restores it;
// bit 40 is above MAXPHYADDR (36).
add("IA32_APIC_BASE disable and re-enable", "mov ecx,0x1B\nrdmsr\nmov r8d,eax\nmov r9d,edx\nwrmsr\nbtr eax,11\nwrmsr\nmov eax,1\ncpuid\nmov r10d,edx\nmov ecx,0x1B\nmov eax,r8d\nmov edx,r9d\nwrmsr\nrdmsr\nmov r11d,eax\nmov eax,1\ncpuid\nmov eax,r8d\nmov ebx,r11d\nmov ecx,r10d\nshr ecx,9\nand ecx,1\nshr edx,9\nand edx,1");
fault("IA32_APIC_BASE reserved bit", "mov ecx,0x1B\nrdmsr\nbts edx,8\nwrmsr", 13);
function source_for(cases)
{
let body = "";
for(const [n, test] of cases.entries())
{
    body += `\ncase_${n}:\nmov dword [0x300004], ${n}\nmov qword [0x500010], 0\nmov qword [0x500020], 0\nmov qword [0x500028], 0\nmov qword [0x500030], 0\nmov qword [0x500038], 0\nxor eax, eax\nmov cr2, rax\nmov ebx, 0\nmov ecx, 0\nmov edx, 0\n${test.code}\nmov rdi, ${0x300008 + n * 64}\nmov [rdi], rax\nmov [rdi+8], rbx\nmov [rdi+16], rcx\nmov [rdi+24], rdx\nmov rax, [0x500020]\nmov [rdi+32], rax\nmov rax, [0x500028]\nmov [rdi+40], rax\nmov rax, [0x500030]\nmov [rdi+48], rax\nmov rax, [0x500038]\nmov [rdi+56], rax\n`;
}
return `bits 32
org 0x100000
%define HIGH 0xFFFF800000000000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr32]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x3F0000
mov dword [0x200000],0x201007
mov dword [0x200800],0x201007
mov dword [0x201000],0x202007
mov edi,0x202000
mov eax,0x87
mov ecx,512
.pages:
mov [edi],eax
add eax,0x200000
add edi,8
loop .pages
mov eax,cr4
or eax,0x20
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x901
xor edx,edx
wrmsr
mov eax,cr0
or eax,0x80010001
mov cr0,eax
jmp 24:long_mode
bits 64
long_mode:
mov rax,HIGH+high_mode
jmp rax
high_mode:
lgdt [rel gdtr64]
lidt [rel idtr64]
lea rax,[rel tss]
mov word [rel gdt+58],ax
shr rax,16
mov byte [rel gdt+60],al
mov byte [rel gdt+63],ah
shr rax,16
mov dword [rel gdt+64],eax
mov rax,HIGH+0x3E0000
mov [rel tss+4],rax
mov rax,HIGH+0x3C0000
mov [rel tss+36],rax
mov ax,0x38
ltr ax
lea rdi,[rel idt]
mov ecx,256
lea rax,[rel unexpected]
.init_idt:
mov word [rdi],ax
mov word [rdi+2],0x18
mov word [rdi+4],0x8E00
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
mov dword [rdi+12],0
add rdi,16
loop .init_idt
%macro GATE 2
lea rax,[rel handler_%1]
lea rdi,[rel idt+%1*16]
mov word [rdi],ax
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
mov byte [rdi+4],%2
%endmacro
GATE 0,0
GATE 1,0
GATE 2,0
GATE 6,0
GATE 7,0
GATE 8,1
GATE 12,0
GATE 13,0
GATE 14,0
GATE 64,0
GATE 65,1
${body}
mov dword [0x300000],0xC064C064
hlt
jmp $
%macro HANDLER 2
handler_%1:
%if %2 == 0
push 0
%endif
push %1
jmp common_handler
%endmacro
HANDLER 0,0
HANDLER 1,0
HANDLER 6,0
HANDLER 7,0
HANDLER 8,1
HANDLER 12,1
HANDLER 13,1
HANDLER 14,1
HANDLER 64,0
HANDLER 65,0
handler_2:
inc ebx
cmp ebx,1
jne .out
mov dword [rsi+0x300],0x4400
mov r9d,20000
.hold:
dec r9d
jnz .hold
mov ecx,ebx
.out:
iretq
common_handler:
push rax
mov rax,[rsp+8]
mov [0x500020],rax
mov rax,[rsp+16]
mov [0x500028],rax
mov rax,cr2
mov [0x500030],rax
lea rax,[rsp+24]
mov [0x500038],rax
mov rax,[0x500010]
test rax,rax
jz .return
mov [rsp+24],rax
.return:
and qword [rsp+40],~0x100
pop rax
add rsp,16
iretq
unexpected:
cli
hlt
jmp $
align 16
gdt:
dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
dq 0x00CFF2000000FFFF,0x00CFFA000000FFFF,0x00AFFA000000FFFF
dq 0x0000890000000067,0
dq 0,0
gdtr32: dw 87
dd gdt
gdtr64: dw 87
dq HIGH+gdt
idtr64: dw 4095
dq HIGH+idt
align 16
tss: times 104 db 0
align 16
idt: times 4096 db 0
image_end:
`;
}
const dir = assemble("system", source_for(cases));
const config = {length: 8 + cases.length * 64};
const oracle = await reference(dir, config);
console.log(`QEMU: ${cases.length} long-mode system cases`);
if(!process.env.X64_ORACLE_ONLY)
{
    const value = await actual(dir, config);
    for(const [n, test] of cases.entries()) for(let field = 0; field < 8; field++)
    {
        const at = 8 + n * 64 + field * 8;
        assert.equal(value.readBigUInt64LE(at), oracle.readBigUInt64LE(at), `case ${n} ${test.name}, field ${field}`);
    }
    console.log(`PASS: ${cases.length} independent system/exception/IST/syscall cases`);
}

if(!process.env.X64_ORACLE_ONLY)
{
    const directory = assemble("system-control-faults", source_for(specification_cases));
    const result = await actual(directory, {length: 8 + specification_cases.length * 64});
    for(const [n, test] of specification_cases.entries())
    {
        const at = 8 + n * 64;
        assert.equal(result.readBigUInt64LE(at + 32), result.readBigUInt64LE(at), test.name + " vector");
        assert.equal(result.readBigUInt64LE(at + 40), result.readBigUInt64LE(at + 8), test.name + " error code");
        // The #GP frame sits directly below the untouched 0x3F0000 stack.
        if(test.name === "far CALL noncanonical 64-bit offset")
            assert.equal(result.readBigUInt64LE(at + 56), 0x3F0000n - 40n, test.name + " restores RSP");
    }
    console.log(`PASS: ${specification_cases.length} SDM fault cases (QEMU reference differs or is unavailable)`);

    const watch = assemble("system-data-breakpoints", source_for(expectation_cases));
    const observed = await actual(watch, {length: 8 + expectation_cases.length * 64});
    for(const [n, test] of expectation_cases.entries())
    {
        const at = 8 + n * 64;
        assert.equal(observed.readBigUInt64LE(at), test.rax, test.name + " committed value");
        assert.equal(observed.readBigUInt64LE(at + 8), test.rbx, test.name + " DR6");
        assert.equal(observed.readBigUInt64LE(at + 32), 1n, test.name + " #DB vector");
    }
    console.log(`PASS: ${expectation_cases.length} SDM data-breakpoint cases (QEMU reference hangs)`);
}
                                                                                                       source/v64/tests/x64/task_faults.mjs                                                                0000644 0000000 0000000 00000011671 00000000000 014510  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// 32-bit protected mode: LLDT, LTR and task switch faults (SDM Vol.3A §7.3,
// Vol.2A LLDT/LTR/JMP), compared with QEMU. These used to panic the host
// (unimplemented paths); the guest must see the architectural fault instead:
// LLDT of a non-LDT, a not-present LDT or an LDT-relative selector, LTR of
// a busy TSS, JMP to a not-present or busy TSS, a working task switch there
// and back, and a task switch whose new TSS names an invalid LDT (#TS in the
// new task, after the switch).
import assert from "node:assert/strict";
import {assemble, reference, actual} from "./guest_runner.mjs";

const source = `bits 32
org 0x100000
header:
dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
lgdt [gdtr]
jmp 8:pm
pm:
mov ax,0x10
mov ds,ax
mov es,ax
mov ss,ax
mov fs,ax
mov gs,ax
mov esp,0x3F0000
mov dword [0x300004],0
; interrupt gates for #TS, #NP, #GP
mov edi,idt
mov eax,handler_10
call gate
mov edi,idt+11*8-10*8
mov eax,handler_11
call gate
mov edi,idt+13*8-10*8
mov eax,handler_13
call gate
lidt [idtr]
; TSS bases into their descriptors
mov eax,tss1
mov edi,gdt+0x20
call set_base
mov eax,tss2
mov edi,gdt+0x28
call set_base
mov eax,tss2
mov edi,gdt+0x30
call set_base
mov eax,tss4
mov edi,gdt+0x48
call set_base
mov eax,ldt_table
mov edi,gdt+0x18
call set_base
mov eax,ldt_table
mov edi,gdt+0x40
call set_base
; 1. LLDT of a data segment: #GP(0x38)
mov dword [resume],.n1
mov ax,0x38
lldt ax
.n1:
; 2. LLDT of a not-present LDT: #NP(0x40)
mov dword [resume],.n2
mov ax,0x40
lldt ax
.n2:
; 3. LLDT of an LDT-relative selector: #GP(0x1C)
mov dword [resume],.n3
mov ax,0x1C
lldt ax
.n3:
; a valid LDT
mov ax,0x18
lldt ax
sldt ax
mov [0x300100],eax
; 4. LTR, then LTR of the same (now busy) TSS: #GP(0x20)
mov ax,0x20
ltr ax
mov dword [resume],.n4
ltr ax
.n4:
; 5. JMP to a not-present TSS: #NP(0x30)
mov dword [resume],.n5
jmp 0x30:0
.n5:
; 6. JMP to the busy current TSS: #GP(0x20)
mov dword [resume],.n6
jmp 0x20:0
.n6:
; 7. a task switch to task 2 and back
jmp 0x28:0
mov [0x300108],eax
str ax
mov [0x30010C],eax
; 8. a new TSS with an invalid LDT: #TS(0x38) in the new task (last:
; segment state after a fault past the commit point is undefined)
jmp 0x48:0
hlt

task2:
mov eax,0x7A5C2
mov [0x300104],eax
jmp 0x20:0

task4:
hlt

gate:
mov [edi],ax
mov word [edi+2],8
mov word [edi+4],0x8E00
shr eax,16
mov [edi+6],ax
ret
set_base:
mov [edi+2],ax
shr eax,16
mov [edi+4],al
mov [edi+7],ah
ret

handler_10:
; the new task's data segments may be unusable: reload before recording
mov eax,[esp]
mov bx,0x10
mov ds,bx
mov es,bx
mov ss,bx
mov esp,0x3C0000
mov [0x300118],eax
mov eax,[0x300004]
mov dword [0x300008+eax*8],10
mov dword [0x30000C+eax*8],0
inc dword [0x300004]
str ax
mov [0x300110],eax
mov dword [0x300000],0xC064C064
hlt
jmp $
handler_11:
push 11
jmp common_handler
handler_13:
push 13
common_handler:
push eax
push ebx
mov eax,[0x300004]
mov ebx,[esp+8]
mov [0x300008+eax*8],ebx
mov ebx,[esp+12]
mov [0x30000C+eax*8],ebx
inc dword [0x300004]
mov ebx,[resume]
mov [esp+16],ebx
pop ebx
pop eax
add esp,8
iret

align 8
resume: dd 0
gdt:
dq 0
dq 0x00CF9A000000FFFF   ; 0x08 code
dq 0x00CF92000000FFFF   ; 0x10 data
dq 0x0000820000000017   ; 0x18 LDT
dq 0x0000890000000067   ; 0x20 TSS 1 (available)
dq 0x0000890000000067   ; 0x28 TSS 2 (available)
dq 0x0000090000000067   ; 0x30 TSS (not present)
dq 0x00CF92000000FFFF   ; 0x38 data (not an LDT)
dq 0x0000020000000017   ; 0x40 LDT (not present)
dq 0x0000890000000067   ; 0x48 TSS 4 (its LDT field is invalid)
gdt_end:
gdtr: dw gdt_end-gdt-1
dd gdt
idtr: dw 14*8-1
dd idt-10*8
idt: times 4*8 db 0
ldt_table: times 24 db 0
align 16
tss1: times 104 db 0
tss2:
dd 0, 0x3E0000, 0x10, 0, 0, 0, 0, 0
dd task2, 2, 0, 0, 0, 0, 0x3E0000, 0, 0, 0
dd 0x10, 8, 0x10, 0x10, 0x10, 0x10, 0, 0
align 16
tss4:
dd 0, 0x3D0000, 0x10, 0, 0, 0, 0, 0
dd task4, 2, 0, 0, 0, 0, 0x3D0000, 0, 0, 0
dd 0x10, 8, 0x10, 0x10, 0x10, 0x10, 0x38, 0
image_end:
`;
const directory = assemble("task-faults", source);
const config = {length: 0x120};
const qemu = await reference(directory, config);
const v86 = await actual(directory, config);
const faults = buffer => Array.from({length: buffer.readUInt32LE(4)}, (_, i) =>
    [buffer.readUInt32LE(8 + i * 8), buffer.readUInt32LE(12 + i * 8)]);
console.log("QEMU faults", JSON.stringify(faults(qemu)));
assert.deepEqual(faults(qemu), [[13, 0x38], [11, 0x40], [13, 0x1C], [13, 0x20], [11, 0x30], [13, 0x20], [10, 0]], "reference");
assert.deepEqual(faults(v86), faults(qemu), "vectors and error codes");
for(const [offset, what] of [[0x100, "SLDT"], [0x104, "task 2 ran"], [0x10C, "TR after returning"], [0x110, "TR after the #TS"]])
{
    assert.equal(v86.readUInt32LE(offset) >>> 0, qemu.readUInt32LE(offset) >>> 0, what);
}
// (SDM: the error code is the LDT selector; QEMU pushes it through the new
// task's SS, whose state is undefined here, so only v86's is checked)
assert.equal(v86.readUInt32LE(0x118), 0x38, "#TS error code");
console.log("PASS task switch/LLDT/LTR faults agree with QEMU");
                                                                       source/v64/tests/x64/triple_fault.mjs                                                               0000644 0000000 0000000 00000005150 00000000000 014655  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// A triple fault in 64-bit mode (SDM Vol.3A §6.15, interrupt 8: a fault while
// delivering #DF enters shutdown). On the BSP the board resets the machine at
// the next safe point: the core restarts at the reset vector in real mode and
// no long-mode state survives (EFER.LME/LMA, CR0/CR4, the high RIP and the
// high halves of the GPRs are architecturally reset). QEMU is not usable as a
// reference: with -no-reboot it exits.
import assert from "node:assert/strict";
import {assemble} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

// #UD with an empty IDT: #GP(IDT limit) -> #DF -> #GP again -> shutdown
const body = `
mov rax,0x1122334455667788
mov r9,rax
mov dword [0x300000],0x7F7F7F7F
lidt [rel null_idt]
ud2
`;
const data = `
null_idt: dw 0
dq 0
`;
const directory = assemble("triple-fault", long_mode_guest(body, data));
const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
for(const jit of [false, true])
{
    const emulator = new V86({graphics_adapter: "bochs_vga", multiboot: {url: directory + "guest.bin"}, memory_size: 32 << 20, acpi: true, autostart: false,
        log_level: 0, disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: true});
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    const cpu = emulator.v86.cpu;
    const view = () => new DataView(cpu.wasm_memory.buffer);
    const epoch = cpu.execution_epoch;
    let marked = false, rounds = 0;
    while(cpu.execution_epoch === epoch)
    {
        assert.ok(++rounds < 100000, "the triple fault resets the board");
        cpu.run_cores();
        marked ||= new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(0x300000, true) === 0x7F7F7F7F;
    }
    assert.ok(marked, "the guest reached 64-bit mode before faulting");
    assert.equal(cpu.execution_epoch, epoch + 1);
    const d = cpu.get_diagnostics();
    assert.equal(d.cpu.mode, "real");
    assert.equal(cpu.instruction_pointer[0] >>> 0, 0xFFFF0, "restart at the reset vector");
    assert.equal(view().getUint32(1584, true), 0, "RIP high half cleared");
    assert.equal(view().getBigUint64(1696, true), 0n, "EFER (LME/LMA/NXE/SCE) reset");
    assert.equal(cpu.cr[0] & 0x80000001, 0, "CR0.PG/PE clear");
    assert.equal(cpu.cr[4], 0, "CR4 clear");
    assert.equal(view().getUint32(1360 + 9 * 4, true), 0, "R9 high half cleared");
    assert.equal(cpu.wm.exports.exception_shutdown(0), 0, "the reset left shutdown");
    console.log(`PASS 64-bit triple fault resets the board (${jit ? "page tier" : "interpreter"})`);
    emulator.destroy();
}
                                                                                                                                                                                                                                                                                                                                                                                                                        source/v64/tests/x64/unaligned_parallel.mjs                                                         0000644 0000000 0000000 00000005553 00000000000 016014  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Hot pages compiled with inline access cache lookups (x64_hot_inline,
// docs/jit-unification-plan.md P4.14) in the parallel build, whose guest
// memory accesses are atomics that need natural alignment: a hot loop of
// unaligned loads and stores must give the interpreter's results, and no
// more retries than with outlined lookups (an inline lookup's unaligned
// access calls the module's lookup function, which bounces reads and passes
// unaligned write hosts to the code that handles them, not the runtime's
// x64_page_access, which would refuse them).
import assert from "node:assert/strict";
import { assemble, actual } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";

const BUFFER = 0x400000, ROUNDS = 20000;
const directory = assemble("unaligned-parallel", long_mode_guest(`
mov rdi, ${BUFFER}
mov ecx, ${ROUNDS}
xor eax, eax
hot:
mov [rdi + 1], eax
mov [rdi + 6], ax
mov [rdi + 11], rax
add eax, [rdi + 3]
add rax, [rdi + 9]
movzx edx, word [rdi + 13]
add eax, edx
mov rdx, rcx
and edx, 255
lea rdi, [${BUFFER} + rdx * 8 + 5]
dec ecx
jnz hot
mov [0x300008], rax
`));
const parallel = new URL("../../build/v86-parallel.wasm", import.meta.url).pathname;
const runs = [];
for(const [label, options] of [
    ["interpreter", { disable_jit: true }],
    ["outlined", { wasm_path: parallel, disable_jit: false, ir_sync_publication: true, jit_switches: { x64_hot_inline: 0 } }],
    ["hot inline", { wasm_path: parallel, disable_jit: false, ir_sync_publication: true, jit_switches: { x64_hot_inline: 1, x64_hot_count: 4096 } }],
])
{
    let memory, retries, native, hot;
    await actual(directory, {
        length: 8, timeout: 120000, options,
        inspect: emulator => {
            const cpu = emulator.v86.cpu;
            memory = Buffer.from(cpu.mem8.slice(BUFFER, BUFFER + 4096)).toString("hex") + Buffer.from(cpu.mem8.slice(0x300008, 0x300010)).toString("hex");
            const stat = i => cpu.wm.exports.x64_page_stat ? cpu.wm.exports.x64_page_stat(i) : 0;
            [retries, native, hot] = [stat(2), stat(1), stat(33)];
        },
    });
    runs.push({ label, memory, retries, native, hot });
    console.log(`${label}: retries ${retries}, native ${native}, hot recompiles ${hot}`);
}
const [reference, outlined, inline] = runs;
assert.equal(outlined.memory, reference.memory, "outlined lookups give the interpreter's results");
assert.equal(inline.memory, reference.memory, "inline lookups give the interpreter's results");
assert.ok(outlined.native > ROUNDS * 5 && inline.native > ROUNDS * 5, "the page tier ran the loop");
assert.ok(inline.hot >= 1, "the hot page was recompiled with inline lookups");
assert.ok(inline.retries <= outlined.retries, `no more retries inline (${inline.retries}) than outlined (${outlined.retries})`);
console.log("PASS unaligned_parallel: unaligned loads and stores of a hot page in the parallel build");
                                                                                                                                                     source/v64/tests/x64/vector_oracle.mjs                                                              0000644 0000000 0000000 00000074217 00000000000 015024  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Identical real long-mode guest bytes run on independent QEMU TCG and v86.
import assert from "node:assert/strict";
import fs from "node:fs";
import {assemble, reference, actual} from "./guest_runner.mjs";
import {step_profile} from "../../tools/step_profile.mjs";
const cases = [];
function add(name, code, a = [0x3F800000,0x40000000,0x40400000,0x40800000], b = [0x40000000,0x40800000,0x40C00000,0x41000000], mxcsr = 0x1F80)
{
    cases.push({name,code,a,b,mxcsr});
}
const floats = [[0x3F800000,0x33800000,0x00800000,0x80000001], [0x7FC12345,0x7F812345,0x7F800000,0xFF800000], [0x00000001,0x80000000,0x7F7FFFFF,0xBF800000]];
const doubles = [[0x00000000,0x3FF00000,0x00000000,0x40000000], [0x00000001,0x7FF80000,0x00000001,0x7FF00000], [1,0,0xFFFFFFFF,0x7FEFFFFF]];
for(const instruction of ["addps","subps","mulps","divps","minps","maxps","sqrtps","addss","subss","mulss","divss","minss","maxss","sqrtss"])
    for(const [n,values] of floats.entries()) for(const rounding of [0,1,2,3])
        add(`${instruction} sample ${n} rounding ${rounding}`, `${instruction} xmm8,xmm9`, values, floats[(n+1)%floats.length],0x1F80|(rounding<<13));
for(const instruction of ["addpd","subpd","mulpd","divpd","minpd","maxpd","sqrtpd","addsd","subsd","mulsd","divsd","minsd","maxsd","sqrtsd"])
    for(const [n,values] of doubles.entries()) for(const rounding of [0,1,2,3])
        add(`${instruction} sample ${n} rounding ${rounding}`, `${instruction} xmm8,xmm9`, values,doubles[(n+1)%doubles.length],0x1F80|(rounding<<13));
for(const instruction of ["addps","mulps","divps","sqrtps","addpd","mulpd","divpd","sqrtpd"])
    for(const mode of [0x1FC0,0x9F80,0x9FC0]) add(`${instruction} DAZ/FZ ${mode.toString(16)}`,`${instruction} xmm8,xmm9`,[1,0x80000001,0x00800000,0x80000000],[0x3F000000,0x40000000,0x7F7FFFFF,0],mode);
for(const ins of ["paddb","paddw","paddd","paddq","psubb","psubw","psubd","psubq","paddsb","paddsw","paddusb","paddusw","psubsb","psubsw","psubusb","psubusw","pand","pandn","por","pxor","pcmpeqb","pcmpeqw","pcmpeqd","pcmpgtb","pcmpgtw","pcmpgtd","packsswb","packssdw","packuswb","punpcklbw","punpcklwd","punpckldq","punpcklqdq","punpckhbw","punpckhwd","punpckhdq","punpckhqdq","pmullw","pmulhw","pmulhuw","pmuludq","pmaddwd","psadbw","pminub","pmaxub","pminsw","pmaxsw","pavgb","pavgw","psrlw","psrld","psrlq","psraw","psrad","psllw","pslld","psllq"])
    add(ins,`${ins} xmm8,xmm9`,[0x807F0180,0x80007FFF,0xFFFF0001,0x80000000],[0xFFFF0101,0x80008000,0x7FFF0001,0xFFFFFFFF]);
for(const ins of ["psrlw","psrld","psrlq","psraw","psrad","psllw","pslld","psllq","psrldq","pslldq"])
    for(const n of [0,1,15,16,31,32,63,64,255]) add(`${ins} ${n}`,`${ins} xmm15,${n}`);
for(const ins of ["pshufd","pshuflw","pshufhw","shufps","shufpd"])
    for(const n of [0,27,255]) add(`${ins} ${n}`,`${ins} xmm8,xmm9,${n}`);
for(const ins of ["cmpps","cmppd","cmpss","cmpsd"]) for(let predicate=0;predicate<8;predicate++)
    for(const values of [[0x3F800000,0,0xBF800000,0x7F800000],[0x7FC12345,0x7F812345,0x7FC00000,0xFFC00000]]) add(`${ins} ${predicate} ${values[0].toString(16)}`,`${ins} xmm8,xmm9,${predicate}`,values,values.toReversed());
for(const ins of ["ucomiss","comiss","ucomisd","comisd"]) for(const values of floats) add(ins+values[0],`${ins} xmm8,xmm9`,values,values.toReversed());
for(const ins of ["haddps","haddpd","hsubps","hsubpd","addsubps","addsubpd"]) add(ins,`${ins} xmm8,xmm9`);
for(const ins of ["cvtps2pd","cvtpd2ps","cvtss2sd","cvtsd2ss","cvtdq2ps","cvtps2dq","cvttps2dq","cvtdq2pd","cvtpd2dq","cvttpd2dq"]) for(const values of floats) for(const rounding of [0,1,2,3])
    add(`${ins} ${values[0]} round ${rounding}`,`${ins} xmm8,xmm9`,undefined,values,0x1F80|rounding<<13);
// (MXCSR.PE set: where the page tier's conversion templates admit them, they
// run natively; P2.5, switch x64_cvt)
for(const ins of ["cvtps2pd","cvtpd2ps","cvtdq2ps","cvtps2dq","cvttps2dq","cvtdq2pd","cvtpd2dq","cvttpd2dq"])
    for(const [n,values] of [...floats,...doubles,[0x3FC00000,0xBFC00000,0x4B800001,0xCF000000],[1,2,0x7FFFFFFF,0x80000000]].entries())
        for(const operand of ["xmm9","[rel .b]"]) add(`${ins} PE ${n} ${operand}`,`${ins} xmm8,${operand}`,undefined,values,0x1FA0);
for(const ins of ["cvtsi2ss","cvtsi2sd"]) for(const n of ["0x7FFFFFFFFFFFFFFF","0x8000000000000000","0x20000000000001"]) for(const rounding of [0,1,2,3]) add(`${ins} ${n} ${rounding}`,`mov r10,${n}\n${ins} xmm8,r10`,undefined,undefined,0x1F80|rounding<<13);
for(const ins of ["cvtss2si","cvttss2si","cvtsd2si","cvttsd2si"]) for(const values of floats) for(const rounding of [0,1,2,3]) add(`${ins} ${values[0]} ${rounding}`,`${ins} rax,xmm9`,undefined,values,0x1F80|rounding<<13);
for(const code of ["movq xmm15,xmm8","movd xmm8,r10d","movq xmm8,r10","movq rax,xmm9","movd eax,xmm9","movhlps xmm8,xmm9","movlhps xmm8,xmm9","movss xmm8,xmm9","movsd xmm8,xmm9","movddup xmm8,xmm9","movsldup xmm8,xmm9","movshdup xmm8,xmm9","movmskps eax,xmm9","movmskpd eax,xmm9","pmovmskb eax,xmm9","pinsrw xmm8,r10d,7","pextrw eax,xmm9,7"])
    add(code,`mov r10,0xFFEEDDCCBBAA9988\n${code}`);
add("FXSAVE64/FXRSTOR64 all sixteen registers", "fxsave64 [0x510000]\npxor xmm8,xmm8\npxor xmm9,xmm9\npxor xmm15,xmm15\nfxrstor64 [0x510000]");
add("x87 arithmetic and m80 full pointer", "fld qword [rel .a]\nfld qword [rel .b]\nfaddp st1,st0\nfstp tword [0x510300]\nfld tword [0x510300]\nfstp qword [0x510310]\nmovq xmm8,[0x510310]",doubles[0],doubles[0]);
add("x87 save/restore environment", "fld1\nfldpi\nfnsave [0x510400]\nfrstor [0x510400]\nfaddp st1,st0\nfstp qword [0x510310]\nmovq xmm8,[0x510310]");
for(let r=0;r<16;r++) add(`FXRSTOR preserves XMM${r}`,`movdqa xmm${r},xmm9\nfxsave64 [0x510000]\npxor xmm${r},xmm${r}\nfxrstor64 [0x510000]\nmovdqa xmm8,xmm${r}`);
add("FXSAVE64 high FIP and FDP", "lea rax,[rel .fld]\n.fld:\nfld qword [rel .a]\nfxsave64 [0x510000]\nmov rdx,[0x510008]\nsub rdx,rax\nmovq xmm8,rdx\nlea rax,[rel .a]\nmov rdx,[0x510010]\nsub rdx,rax\nmovq xmm9,rdx\nfstp st0\nmov eax,0", doubles[0],doubles[0]);
for(const ins of ["faddp","fmulp","fsubp","fsubrp","fdivp","fdivrp"]) add("x87 "+ins,`fld qword [rel .a]\nfld qword [rel .b]\n${ins} st1,st0\nfstp qword [0x510310]\nmovq xmm8,[0x510310]`,doubles[0],[0,0x40080000,0,0]);
for(const ins of ["cvtsd2si","cvttsd2si"]) for(const values of [[0,0x43E00000,0,0],[0,0xC3E00000,0,0],[0xFFFFFFFF,0x43DFFFFF,0,0]]) for(const rounding of [0,1,2,3]) add(`${ins} int64 boundary ${values[1]} ${rounding}`,`${ins} rax,xmm9`,undefined,values,0x1F80|rounding<<13);
for(const ins of ["paddb","paddw","paddd","paddq","psubb","psubw","psubd","psubq","paddsb","paddsw","paddusb","paddusw","psubsb","psubsw","psubusb","psubusw","pand","pandn","por","pxor","pcmpeqb","pcmpeqw","pcmpeqd","pcmpgtb","pcmpgtw","pcmpgtd","packsswb","packssdw","packuswb","punpcklbw","punpcklwd","punpckldq","punpckhbw","punpckhwd","punpckhdq","pmullw","pmulhw","pmulhuw","pmuludq","pmaddwd","psadbw","pminub","pmaxub","pminsw","pmaxsw","pavgb","pavgw"]) add("MMX "+ins,`movq mm7,[rel .a]\nmovq mm6,[rel .b]\n${ins} mm7,mm6\nmovq [0x510310],mm7\nmovq xmm8,[0x510310]\nemms`,[0x807F0180,0x80007FFF,0,0],[0xFFFF0101,0x80008000,0,0]);
for(const ins of ["cvtpi2ps","cvtpi2pd"]) add(ins,`movq mm7,[rel .b]\n${ins} xmm8,mm7\nemms`,undefined,[0x80000000,0x7FFFFFFF,0,0]);
for(const ins of ["cvtps2pi","cvtpd2pi","cvttps2pi","cvttpd2pi"]) add(ins,`${ins} mm7,xmm9\nmovq [0x510310],mm7\nmovq xmm8,[0x510310]\nemms`,undefined,[0x3FC00000,0xBFC00000,0,0]);
for(const ins of ["rcpps","rcpss","rsqrtps","rsqrtss"]) add(ins,`${ins} xmm8,xmm9`,undefined,[0x3F800000,0x40800000,0x7F800000,0x80000000]);
add("SSE full base and address32 override", "mov r10,HIGH+0x510000\nmovdqu [r10],xmm9\nmovdqu xmm8,[r10]\na32 movdqu xmm15,[r10d]");
add("SSE full FS base", "mov ecx,0xC0000100\nmov eax,0x510000\nmov edx,0xFFFF8000\nwrmsr\nmovdqu [fs:0],xmm9\nmovdqu xmm8,[fs:0]\nxor eax,eax\nxor edx,edx\nwrmsr");
add("CLFLUSH coherent cache line", "clflush [0x510000]");
for(const rounding of [0,1,2,3]) for(const value of [[0,0x3FF80000,0,0],[0,0xBFF80000,0,0],[0xFFFFFFFF,0x43DFFFFF,0,0]]) add(`x87 integer rounding ${rounding} ${value[1]}`,`mov word [0x510820],${0x37F | rounding << 10}\nfldcw [0x510820]\nfld qword [rel .a]\nfistp qword [0x510310]\nmovq xmm8,[0x510310]\nfnstsw ax`,value);
add("x87 FNCLEX preserves condition flags", "fld1\nfldz\nfcom st1\nfnclex\nfnstsw ax");
for(const [kind,cw,load] of [["divide zero",0x37B,"fldz\nfld1"],["invalid",0x37E,"fldz\nfldz"]]) add("x87 deferred #MF "+kind,`lea rax,[rel .resume]\nmov [0x500010],rax\nmov word [0x510820],${cw}\nfldcw [0x510820]\n${load}\nfdiv st0,st1\nfwait\n.resume:\nmov eax,0\nfnstsw ax\nfnclex`);

const fault = (name,code,mxcsr=0x1F80,a,b) => add(name,`lea rax,[rel .resume]\nmov [0x500010],rax\n${code}\n.resume:\nclts\nmov rax,cr4\nor eax,0x600\nmov cr4,rax\nmov eax,0`,a,b,mxcsr);
fault("unmasked SIMD invalid destination suppression","divps xmm8,xmm9",0x1F00,[0,0,0,0],[0,0,0,0]);
fault("unmasked SIMD divzero destination suppression","divpd xmm8,xmm9",0x1D80,doubles[0],[0,0,0,0]);
fault("SIMD disabled OSFXSR","mov rax,cr4\nbtr rax,9\nmov cr4,rax\npxor xmm8,xmm9");
fault("SIMD TS lazy switch","mov rax,cr0\nbts rax,3\nmov cr0,rax\nmovaps xmm8,xmm9");
fault("unaligned packed #GP","movaps xmm8,[0x600FF8]");
fault("unaligned MOVSLDUP #GP","movsldup xmm8,[0x600FF8]");
fault("unaligned MOVSHDUP #GP","movshdup xmm8,[0x600FF8]");
fault("cross-page vector load #PF","movdqu xmm8,[0x600FF8]");
fault("cross-page vector store no partial write","movdqu [0x600FF8],xmm8");
fault("cross-page FXSAVE no partial write","fxsave64 [0x600F00]");
fault("cross-page FXRSTOR no partial state","fxrstor64 [0x600F00]");
// VMASKMOVPS/PD across into the absent page: lanes there that the mask
// (XMM9's sign bits) does not select are not accessed; a selected one faults
// before any lane is stored (docs/simd-xsave-plan.md 8)
const AVX = "mov rax,cr4\nbts rax,18\nmov cr4,rax\nxor ecx,ecx\nmov eax,7\nxor edx,edx\nxsetbv";
for(const [suffix, size, selections] of [["ps", 4, [[0, 1], [0, 2], [3]]], ["pd", 8, [[0], [0, 1]]]])
    for(const lanes of selections)
    {
        // (the dwords of XMM9 with the sign bit of a selected lane)
        const mask = [0, 1, 2, 3].map(i => lanes.includes(i / (size / 4) | 0) && (size === 4 || i & 1) ? 0x80000000 : 0);
        const what = `lanes ${lanes.join(",")} across into an absent page`;
        fault(`vmaskmov${suffix} load ${what}`, `${AVX}\nvmaskmov${suffix} xmm8,xmm9,[0x600FF8]`, undefined, undefined, mask);
        fault(`vmaskmov${suffix} store ${what}`, `${AVX}\nvmaskmov${suffix} [0x600FF8],xmm9,xmm8`, undefined, undefined, mask);
    }
// VEX.256 (P6): 32 bytes across into the absent page, the load a #PF and the
// store one without a partial write; the aligned moves need 32-byte alignment
fault("cross-page VEX.256 load #PF", `${AVX}\nvmovdqu ymm8,[0x600FF0]`);
fault("cross-page VEX.256 store no partial write", `${AVX}\nvmovdqu [0x600FF0],ymm8`);
fault("VEX.256 aligned load at 16 bytes #GP", `${AVX}\nvmovaps ymm8,[0x600FD0]`);
fault("VEX.256 aligned store at 16 bytes #GP", `${AVX}\nvmovntdq [0x600FD0],ymm8`);
// AVX2 gathers (P8). The destination YMM8 is filled with D0 to D7 and the
// mask YMM9 has junk beside its sign bits and beyond the elements; base,
// index register, scale and address size vary. After it, the high halves of
// both go to XMM15 and XMM0. A gather loads each selected element in turn,
// clearing its mask; it zeroes the mask beyond the elements first and the
// destination beyond them last (docs/simd-xsave-plan.md 9)
const HALVES = "vextracti128 xmm15,ymm8,1\nvextracti128 xmm0,ymm9,1";
// (the fill's dwords, D0 to D7, and mask elements)
const [D1, D2, D3, D4, D5, D6, D7] = [1, 2, 3, 4, 5, 6, 7].map(n => 0xD0D0D0D0 + n * 0x01010101), ALL = 0xFFFFFFFF, SIGN = 0x80000000;
function gather(name, instruction, mask, index, setup, index_register = 10)
{
    const dwords = v => v.map(x => typeof x === "string" ? x : "0x" + (x >>> 0).toString(16)).join(",");
    const code = `jmp .gskip\nalign 32\n.gmask: dd ${dwords(mask)}\n.gindex: dd ${dwords(index)}\n.gskip:\n${AVX}\nvmovdqu ymm8,[rel gfill]\nvmovdqu ymm9,[rel .gmask]\nvmovdqu ymm${index_register},[rel .gindex]\n${setup}\n${instruction}`;
    // (each may fault: an unexpected one in QEMU, too, a difference)
    add(name, `lea rax,[rel .resume]\nmov [0x500010],rax\n${code}\n.resume:\n${HALVES}\nmov eax,0`);
}
{
    let seed = 0x2468ACE;
    const random = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 1;
    const junk = () => (random() << 1 ^ random()) >>> 0;
    // (base and displacement around the term of the index; `table`+256 each)
    const ADDRESSES = [
        ["rbx", "lea rbx,[rel table+256]", x => `[rbx+${x}]`],
        ["r13 disp8", "lea r13,[rel table+256+64]", x => `[r13+${x}-64]`],
        ["r12 disp32", "lea r12,[rel table+256-0x1000]", x => `[r12+${x}+0x1000]`],
        ["no base", "", x => `[${x}+table+256]`],
        ["address32", "lea ebx,[rel table+256]", x => `[ebx+${x}]`],
    ];
    let k = 0;
    for(const [mnemonic, size, index_size] of [["vpgatherdd", 4, 4], ["vpgatherdq", 8, 4], ["vpgatherqd", 4, 8], ["vpgatherqq", 8, 8],
        ["vgatherdps", 4, 4], ["vgatherdpd", 8, 4], ["vgatherqps", 4, 8], ["vgatherqpd", 8, 8]])
        for(const wide of [false, true])
            for(let variant = 0; variant < 3; variant++, k++)
            {
                const count = (wide ? 32 : 16) / Math.max(size, index_size);
                const scale = [1, 2, 4, 8][k % 4];
                const [where, setup, address] = ADDRESSES[k % ADDRESSES.length];
                const r = [10, 2, 14][k % 3];
                const vector = wide && !(size === 4 && index_size === 8) ? "ymm" : "xmm";
                const index_vector = wide && !(size === 8 && index_size === 4) ? "ymm" : "xmm";
                const mask = Array.from({length: 8}, junk), index = Array.from({length: 8}, junk);
                for(let n = 0; n < count; n++)
                {
                    const selected = variant === 0 || random() & 1;
                    mask[(n + 1) * size / 4 - 1] = (selected ? 0x80000000 : 0) | random() & 0x7FFFFFFF;
                    const low = Math.ceil(-256 / scale), high = Math.floor((256 - size) / scale);
                    const value = low + random() % (high - low + 1);
                    if(index_size === 4) index[n] = value;
                    else [index[2 * n], index[2 * n + 1]] = [value, value < 0 ? -1 : 0];
                }
                gather(`${mnemonic} ${vector} ${index_vector} indices ${where} scale ${scale} #${variant}`,
                    `${mnemonic} ${vector}8,${address(`${index_vector}${r}*${scale}`)},${vector}9`, mask, index, setup, r);
            }
    // nothing selected: nothing loaded, the destination still zeroed beyond
    // the elements (the high dwords of the mask beyond them have sign bits)
    gather("vpgatherqd ymm indices none selected", "vpgatherqd xmm8,[rbx+ymm10*4],xmm9",
        [0x7FFFFFFF, 1, 0x12345678, 0, SIGN, SIGN, SIGN, SIGN], [0, 0, 1, 0, 2, 0, 3, 0], "lea rbx,[rel table+256]");
    gather("vpgatherdd xmm none selected", "vpgatherdd xmm8,[rbx+xmm10*4],xmm9",
        [0, 0x7FFFFFFF, 0, 1, SIGN, ALL, SIGN, ALL], [0, 1, 2, 3, 0, 0, 0, 0], "lea rbx,[rel table+256]");
    // address size 32: the element's address wraps at 4 GiB (base 0xFFFFFFF0)
    gather("vpgatherdd address32 wraps at 4 GiB", "vpgatherdd xmm8,[ebx+xmm10*1],xmm9",
        [ALL, 0, ALL, ALL, 0, 0, 0, 0], ["table+256+0x10", "table+256+0x18", "table+256+0x14", "table+256+0x23", 0, 0, 0, 0], "mov ebx,0xFFFFFFF0");
    // an unselected element is not accessed, so not in an absent page either
    gather("vpgatherqq ymm unselected elements in an absent page", "vpgatherqq ymm8,[rbx+ymm10*8],ymm9",
        [0, SIGN, 0, 0x7FFFFFFF, 0, SIGN, 0, 0], [0, 0, 2, 0, 1, 0, 0x100, 0], "mov ebx,0x600FF0");
    // a fault: the elements before the faulting one loaded and their masks
    // clear, the rest as before (the mask normalized, zero beyond the
    // elements), the destination not yet zeroed beyond the elements
    gather("vpgatherdd xmm element 2 in an absent page", "vpgatherdd xmm8,[rbx+xmm10*4],xmm9",
        [ALL, ALL, ALL, ALL, SIGN, SIGN, ALL, ALL], [0, 1, 4, 2, 0, 0, 0, 0], "mov ebx,0x600FF0");
    gather("vpgatherdd ymm element 5 in an absent page", "vpgatherdd ymm8,[rbx+ymm10*1],ymm9",
        [ALL, ALL, 0, ALL, ALL, ALL, ALL, ALL], [0, 4, 8, 12, 0, 16, 0, 4], "mov ebx,0x600FF0");
    gather("vpgatherdq xmm element 1 across into an absent page", "vpgatherdq xmm8,[rbx+xmm10*4],xmm9",
        [ALL, ALL, ALL, ALL, ALL, ALL, ALL, ALL], [0, 3, 0, 0, 0, 0, 0, 0], "mov ebx,0x600FF0");
    gather("vpgatherqd ymm element 3 in an absent page", "vpgatherqd xmm8,[rbx+ymm10*1],xmm9",
        [ALL, 0, ALL, ALL, SIGN, SIGN, SIGN, SIGN], [0, 0, 4, 0, 8, 0, 16, 0], "mov ebx,0x600FF0");
    gather("vpgatherdd xmm fault with unnormalized mask elements", "vpgatherdd xmm8,[rbx+xmm10*4],xmm9",
        [SIGN | 1, SIGN | 2, SIGN | 3, 0xC0000000, 0, 0, 0, 0], [0, 1, 4, 2, 0, 0, 0, 0], "mov ebx,0x600FF0");
    // quadword indices beyond 32 bits: 4 GiB below the table, the base
    gather("vpgatherqq ymm indices beyond 32 bits", "vpgatherqq ymm8,[rbx+ymm10*1],ymm9",
        [0, SIGN, 0, SIGN, 0, SIGN, 0, SIGN], [0, 1, 8, 1, -8, 0, 16, 1], "mov rbx,HIGH+table+256-0x100000000");
    // a qword index is not truncated: 2^31 above the base, not below it
    gather("vpgatherqq xmm index 2^31 not truncated", "vpgatherqq xmm8,[rbx+xmm10*1],xmm9",
        [0, SIGN, 0, SIGN, 0, 0, 0, 0], [0, 0, SIGN, 0, 0, 0, 0, 0], "mov ebx,0x600FF0");
    // an override's segment, FS or GS, for every element (the base from its
    // MSR, 4 KiB; zero again after)
    for(const [segment, msr] of [["fs", 0xC0000100], ["gs", 0xC0000101]])
        gather(`vpgatherdd ymm ${segment} base`, `vpgatherdd ymm8,[${segment}:rbx+ymm10*4],ymm9\nmov ecx,${msr}\nxor eax,eax\nxor edx,edx\nwrmsr`,
            [ALL, 0, ALL, SIGN, ALL, ALL, 0x7FFFFFFF, ALL], [0, -3, 5, 7, -8, 2, 1, 63], `mov ecx,${msr}\nmov eax,0x1000\nxor edx,edx\nwrmsr\nlea rbx,[rel table+256-0x1000]`);
    // a non-canonical element: #GP(0), or #SS(0) with RBP the base
    gather("vpgatherdd non-canonical element #GP", "vpgatherdd xmm8,[rbx+xmm10*1],xmm9",
        [ALL, ALL, ALL, ALL, 0, 0, 0, 0], [0, "-0x601000", 4, 8, 0, 0, 0, 0], "mov rbx,HIGH+0x600FF0");
    gather("vpgatherdd non-canonical element from RBP #SS", "vpgatherdd xmm8,[rbp+xmm10*1],xmm9",
        [ALL, ALL, ALL, ALL, 0, 0, 0, 0], [0, "-0x601000", 4, 8, 0, 0, 0, 0], "mov rbp,HIGH+0x600FF0");
}
// #UD: two of destination, mask and index the same register; no SIB byte;
// a register operand
for(const [name, code] of [["destination is index", "vpgatherdd xmm8,[rbx+xmm8*4],xmm9"], ["destination is mask", "vpgatherdd xmm8,[rbx+xmm10*4],xmm8"],
    ["mask is index", "vpgatherdd xmm8,[rbx+xmm9*4],xmm9"], ["no SIB byte", "db 0xC4,0x62,0x31,0x90,0x03"], ["register operand", "db 0xC4,0x62,0x31,0x90,0xC4"]])
    fault("invalid gather form " + name, `${AVX}\n${code}`);
fault("invalid MXCSR high bits","mov dword [0x510800],0xFFFFFFFF\nldmxcsr [0x510800]");
for(const [name,encoding] of [["MOVDQ2Q memory","0xF2,0x0F,0xD6,0x00"],["MOVQ2DQ memory","0xF3,0x0F,0xD6,0x00"],["MOVNTPS register","0x0F,0x2B,0xC0"],["MOVLPD register","0x66,0x0F,0x12,0xC0"],["MOVLPS store register","0x0F,0x13,0xC0"],["MOVMSKPS memory","0x0F,0x50,0x00"],["PEXTRW memory","0x66,0x0F,0xC5,0x00,0"],["MASKMOVDQU memory","0x66,0x0F,0xF7,0x00"],["LDDQU register","0xF2,0x0F,0xF0,0xC0"]]) fault("invalid SIMD form "+name,"db "+encoding);

// QEMU 10.2 TCG does not raise unmasked SSE exceptions or reject high
// LDMXCSR bits. Its source also documents x87-style SSE NaN propagation.
// Keep those reference results visible and check explicit architectural
// postconditions separately; do not change execution to match oracle gaps.
add("first SSE NaN payload wins", "addps xmm8,xmm9", [0x7FC12345,0x7F812345,0x7FC12345,0x7F812345], [0x7FC54321,0x7FC54321,0x7F854321,0x7F854321]);
const specification = new Map([
    ["unmasked SIMD invalid destination suppression", {vector:19,mxcsr:0x1F01,unchanged:true}],
    ["unmasked SIMD divzero destination suppression", {vector:19,mxcsr:0x1D84,unchanged:true}],
    ["invalid MXCSR high bits", {vector:13,mxcsr:0x1F80,unchanged:true}],
    ["FXSAVE64 high FIP and FDP", {vector:0,mxcsr:0x1F80,result:[0,0,0,0],zero_xmm9:true}],
    ["first SSE NaN payload wins", {vector:0,mxcsr:0x1F81,result:[0x7FC12345,0x7FC12345,0x7FC12345,0x7FC12345]}],
    // SDM opcode map Table A-3 gives 66 0F 12 only an Mq source (memory);
    // QEMU 10.2 executes the undefined register form as a low-qword move.
    ["invalid SIMD form MOVLPD register", {vector:6,mxcsr:0x1F80,unchanged:true}],
    // MOVSLDUP/MOVSHDUP take an m128 of exception type 4 (SDM): legacy SSE
    // raises #GP(0) unless it is 16-byte aligned (only LDDQU and PCMPxSTRx
    // are exempt). QEMU 10.2 does not check, and page-faults on the crossing.
    ["unaligned MOVSLDUP #GP", {vector:13,mxcsr:0x1F80,unchanged:true}],
    ["unaligned MOVSHDUP #GP", {vector:13,mxcsr:0x1F80,unchanged:true}],
    // VMASKMOVPS/PD access only the selected lanes (SDM: no fault for a lane
    // whose mask bit is 0) and, faulting, store none (a fault restores the
    // state before the instruction, SDM vol. 3 6.5). QEMU 10.2 loads the
    // whole operand (a fault for unselected lanes, CR2 at the page boundary)
    // and stores lane by lane (those before the faulting one written).
    ["vmaskmovps load lanes 0,1 across into an absent page", {vector:0,mxcsr:0x1F80,result:[0x44332211,0x88776655,0,0]}],
    ["vmaskmovpd load lanes 0 across into an absent page", {vector:0,mxcsr:0x1F80,result:[0x44332211,0x88776655,0,0]}],
    ["vmaskmovps load lanes 3 across into an absent page", {vector:14,mxcsr:0x1F80,unchanged:true,error_code:0,cr2:0x601004}],
    ["vmaskmovps store lanes 0,2 across into an absent page", {vector:14,mxcsr:0x1F80,unchanged:true,error_code:2,cr2:0x601000,memory:true}],
    ["vmaskmovpd store lanes 0,1 across into an absent page", {vector:14,mxcsr:0x1F80,unchanged:true,error_code:2,cr2:0x601000,memory:true}],
    // A VEX.256 store faulting on its high half writes nothing (SDM vol. 3
    // 6.5); QEMU 10.2 stores the low half first
    ["cross-page VEX.256 store no partial write", {vector:14,mxcsr:0x1F80,unchanged:true,error_code:2,cr2:0x601000,memory:true}],
    // A gather sets each element's mask to all ones or zero by its sign and
    // zeroes the mask beyond the elements before loading any (SDM VPGATHERDD
    // operation; the zeroing allowed even with a fault), so a fault leaves
    // them so. QEMU 10.2 leaves the mask as it was from the faulting element.
    ...[["vpgatherdd xmm element 2 in an absent page", [0x55667788,0x11223344,D2,D3, 0,0,ALL,ALL, D4,D5,D6,D7, 0,0,0,0], 0x601000],
        ["vpgatherdq xmm element 1 across into an absent page", [0x55667788,0x11223344,D2,D3, 0,0,ALL,ALL, D4,D5,D6,D7, 0,0,0,0], 0x601000],
        ["vpgatherqd ymm element 3 in an absent page", [0x55667788,D1,0x44332211,D3, 0,0,0,ALL, D4,D5,D6,D7, 0,0,0,0], 0x601000],
        ["vpgatherdd xmm fault with unnormalized mask elements", [0x55667788,0x11223344,D2,D3, 0,0,ALL,ALL, D4,D5,D6,D7, 0,0,0,0], 0x601000],
        ["vpgatherqq xmm index 2^31 not truncated", [0x55667788,0x11223344,D2,D3, 0,0,ALL,ALL, D4,D5,D6,D7, 0,0,0,0], 0x80600FF0]]
        .map(([name, registers, cr2]) => [name, {vector:14,mxcsr:0x1F80,registers,error_code:0,cr2}]),
    // a non-canonical address relative to SS is #SS(0) (exception type 12);
    // QEMU 10.2 raises #GP(0)
    ["vpgatherdd non-canonical element from RBP #SS", {vector:12,mxcsr:0x1F80,registers:[0x55667788,D1,D2,D3, 0,ALL,ALL,ALL, D4,D5,D6,D7, 0,0,0,0],error_code:0,cr2:0}],
    // address size 32 computes each element's address modulo 2^32 (as
    // Bochs); QEMU 10.2 adds the index at 64 bits and faults above 4 GiB
    ["vpgatherdd address32 wraps at 4 GiB", {vector:0,mxcsr:0x1F80,registers:[0xA54080C0,D1,0xA54182C3,0x458ACFA5, 0,0,0,0, 0,0,0,0, 0,0,0,0]}],
]);
const selected = process.env.X64_VECTOR_FILTER ? cases.filter(x=>x.name.includes(process.env.X64_VECTOR_FILTER)) : cases;
assert.ok(selected.length);
let body="";
for(const [n,test] of selected.entries())
{
    body+=`\ncase_${n}:\nmov dword [0x300004],${n}\nmov qword [0x500010],0\nmov qword [0x500020],0\nmov qword [0x500028],0\nmov qword [0x500030],0\nfninit\nmov dword [0x510800],${test.mxcsr}\nldmxcsr [0x510800]\nmovdqu xmm8,[rel .a]\nmovdqu xmm9,[rel .b]\nmovdqu xmm15,[rel .a]\nmovdqu xmm0,[rel sentinel]\nmovdqu [0x600FF0],xmm0\nmovdqu [0x600F00],xmm0\nmov eax,0\nmov cr2,rax\npush 2\npopfq\n${test.code}\nmov rdi,${0x300008+n*128}\nmovdqu [rdi],xmm8\nmovdqu [rdi+16],xmm9\nmovdqu [rdi+32],xmm15\nmovdqu [rdi+48],xmm0\nstmxcsr [rdi+64]\nmov [rdi+72],rax\npushfq\npop rax\nand eax,0x8D5\nmov [rdi+80],rax\nmov eax,[0x500020]\nmov [rdi+68],eax\nmov rax,[0x500028]\nmov [rdi+88],rax\nmov rax,[0x500030]\nmov [rdi+96],rax\nmovdqu xmm0,[0x600FF0]\nmovdqu [rdi+104],xmm0\nmov rax,[0x600F00]\nmov [rdi+120],rax\njmp .done\nalign 16\n.a: dd ${test.a.join(",")}\n.b: dd ${test.b.join(",")}\n.done:\n`;
}
const source=`bits 32
org 0x100000
%define HIGH 0xFFFF800000000000
header: dd 0x1BADB002,0x10000,-(0x1BADB002+0x10000)
dd header,header,image_end,image_end,start
start:
cli
cld
lgdt [gdtr]
jmp 8:protected
protected:
mov ax,16
mov ds,ax
mov es,ax
mov ss,ax
mov esp,0x3F0000
mov dword [0x200000],0x201003
mov dword [0x200800],0x201003
mov dword [0x201000],0x202003
mov edi,0x202000
mov eax,0x83
mov ecx,512
.pages:
mov [edi],eax
add eax,0x200000
add edi,8
loop .pages
mov dword [0x202018],0x203003
mov dword [0x203000],0x600003
mov eax,cr4
or eax,0x620
mov cr4,eax
mov eax,0x200000
mov cr3,eax
mov ecx,0xC0000080
mov eax,0x900
xor edx,edx
wrmsr
mov eax,cr0
and eax,~12
or eax,0x80010021
mov cr0,eax
jmp 24:long_mode
bits 64
long_mode:
mov rax,HIGH+high_mode
jmp rax
high_mode:
lidt [rel idtr]
lea rdi,[rel idt]
mov ecx,256
lea rax,[rel unexpected]
.idt:
mov word [rdi],ax
mov word [rdi+2],0x18
mov word [rdi+4],0x8E00
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
add rdi,16
loop .idt
%macro GATE 1
lea rax,[rel handler_%1]
lea rdi,[rel idt+%1*16]
mov word [rdi],ax
mov rdx,rax
shr rdx,16
mov word [rdi+6],dx
shr rdx,16
mov dword [rdi+8],edx
%endmacro
GATE 6
GATE 7
GATE 12
GATE 13
GATE 14
GATE 16
GATE 19
${process.env.X64_JIT ? "mov ecx,1000000\n.warm: add r10,3\nxor r11,r10\npxor xmm8,xmm9\nsub ecx,1\njnz .warm\n" : ""}
${body}
mov dword [0x300000],0xC064C064
hlt
jmp $
%macro HANDLER 2
handler_%1:
%if %2 == 0
push 0
%endif
push %1
jmp handler
%endmacro
HANDLER 6,0
HANDLER 7,0
HANDLER 12,1
HANDLER 13,1
HANDLER 14,1
HANDLER 16,0
HANDLER 19,0
handler:
push rax
mov rax,[rsp+8]
mov [0x500020],rax
mov rax,[rsp+16]
mov [0x500028],rax
mov rax,cr2
mov [0x500030],rax
mov rax,[0x500010]
test rax,rax
jz unexpected
mov [rsp+24],rax
pop rax
add rsp,16
iretq
unexpected:
cli
hlt
jmp $
align 16
sentinel: dq 0x1122334455667788,0x8877665544332211
align 32
gfill: dd 0xD0D0D0D0,0xD1D1D1D1,0xD2D2D2D2,0xD3D3D3D3,0xD4D4D4D4,0xD5D5D5D5,0xD6D6D6D6,0xD7D7D7D7
table:
%assign i 0
%rep 128
dd 0xA5000000+i*0x10203
%assign i i+1
%endrep
gdt: dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF
gdtr: dw 31
dd gdt
idtr: dw 4095
dq HIGH+idt
align 16
idt: times 4096 db 0
image_end:
`;
const directory=assemble("vector",source),length=8+selected.length*128;
fs.writeFileSync(directory+"cases.json",JSON.stringify(selected.map(x=>x.name),null,2)+"\n");
const expected=await reference(directory,{length});
console.log(`QEMU vector reference: ${selected.length} real long-mode cases`);
if(!process.env.X64_ORACLE_ONLY)
{
    const received=await actual(directory,{length,timeout:60000,
        options: {disable_jit:!process.env.X64_JIT,experimental_smp_jit:true,
            ir_tier0:process.env.X64_JIT === "pages",ir_sync_publication:true,
            // (the VMASKMOV and gather cases)
            cpu_features:["SSSE3","SSE4.1","SSE4.2","XSAVE","AVX","AVX2"],cpu_features_unreleased:true},
        inspect: emulator => {
            if(process.env.X64_JIT)
            {
                const retired = emulator.v86.cpu.wm.exports.x64_page_stat(1);
                assert.ok(retired > 1000,`mixed vector/native loop executed compiled instructions: retired=${retired}, compiled=${emulator.v86.cpu.wm.exports.x64_page_stat(0)}`);
                console.log(`native retirement=${retired} backend=${process.env.X64_JIT}`);
                // (X64_STEP_PROFILE=1 with JIT_SWITCHES=step_profile=1: what the page tier stepped)
                if(process.env.X64_STEP_PROFILE) for(const {name,count} of step_profile(emulator.v86.cpu.wm.exports,Number(process.env.X64_STEP_PROFILE)||12)) console.log(`step ${name}: ${count}`);
            }
        }});
    const failures=[];
    for(let n=0;n<selected.length;n++)
    {
        const from=8+n*128,e=expected.subarray(from,from+128),a=received.subarray(from,from+128);
        const spec = specification.get(selected[n].name);
        if(spec)
        {
            assert.equal(a.readUInt32LE(68),spec.vector,selected[n].name+" exception vector");
            assert.equal(a.readUInt32LE(64),spec.mxcsr,selected[n].name+" MXCSR");
            // (`registers`: XMM8, XMM9, XMM15 and XMM0, the gathers' halves)
            const value = Buffer.alloc(spec.registers ? 64 : 16);
            (spec.registers || spec.result || selected[n].a).forEach((v,i)=>value.writeUInt32LE(v,i*4));
            assert.deepEqual(a.subarray(0,value.length),value,selected[n].name+(spec.registers ? " registers" : " destination commit"));
            if(spec.zero_xmm9) assert.deepEqual(a.subarray(16,32),Buffer.alloc(16),selected[n].name+" data pointer");
            if(spec.error_code !== undefined) assert.equal(a.readUInt32LE(88),spec.error_code,selected[n].name+" error code");
            if(spec.cr2 !== undefined) assert.equal(a.readBigUInt64LE(96),BigInt(spec.cr2),selected[n].name+" CR2");
            // (nothing stored: the sentinel at 0x600FF0)
            if(spec.memory) assert.equal(a.subarray(104,120).toString("hex"),"88776655443322111122334455667788",selected[n].name+" memory");
            continue;
        }
        if(!e.equals(a)) failures.push({case:n,name:selected[n].name,expected:e.toString("hex"),actual:a.toString("hex"),offsets:Array.from({length:128},(_,i)=>i).filter(i=>e[i]!==a[i])});
    }
    fs.writeFileSync(directory+"differences.json",JSON.stringify(failures,null,2)+"\n");
    assert.equal(failures.length,0,JSON.stringify(failures.slice(0,10),null,2));
    console.log(`v86 vector/x87: ${selected.length} cases pass (${selected.filter(x=>specification.has(x.name)).length} explicit SDM cases for documented QEMU gaps)`);
}
                                                                                                                                                                                                                                                                                                                                                                                 source/v64/tests/x64/vktest.c                                                                       0000644 0000000 0000000 00000260407 00000000000 013144  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // Vulkan tests for the x86_64 Linux guest's Vulkan drivers (tests/x64/
// linux_gpu.mjs, scenario venus): virtio-gpu's Venus and, as the reference,
// lavapipe. Each test checks its results against what they must be:
//
//     VK_ICD_FILENAMES=<icd> vktest [test...]
//
// prints "VKTEST <name> ok" or "VKTEST <name> FAIL <what>", then
// "VKTEST done <n> failures".
//
// Built without the C library's headers (the host has none for musl; the
// two the Vulkan headers include are in tests/x64/include), with
// third_party/vulkan's; it links against musl's libc and the Vulkan loader
// from the guest's Alpine packages.

#include "vulkan_core.h"
// the shaders: tests/x64/vktest_shaders/ compiled by naga, and vkcube's
// (glslang's SPIR-V, from the guest's vulkan-tools), by tests/x64/linux_gpu.mjs
#include "vktest_shaders.h"

int printf(const char *, ...);
void *malloc(size_t);
void *calloc(size_t, size_t);
void free(void *);
void *memset(void *, int, size_t);
void *memcpy(void *, const void *, size_t);
int memcmp(const void *, const void *, size_t);
int strcmp(const char *, const char *);
int fflush(void *);

// the start: what musl's crt1 does
int __libc_start_main(int (*)(int, char **, char **), int, char **, void (*)(void), void (*)(void), void (*)(void));
int main(int, char **, char **);
#if defined(__aarch64__)
// (the arm64 guest's, tests/a64/linux_gpu.mjs: the stack is 16-byte aligned at entry)
__asm__(".text\n.global _start\n_start:\n mov x29, #0\n mov x30, #0\n mov x0, sp\n bl start_c\n brk #0\n");
#else
__asm__(".text\n.global _start\n_start:\n xor %rbp, %rbp\n mov %rsp, %rdi\n andq $-16, %rsp\n call start_c\n hlt\n");
#endif
__attribute__((used)) void start_c(long *p)
{
    __libc_start_main(main, (int)p[0], (char **)(p + 1), 0, 0, 0);
}

// ---------------------------------------------------------------------------
// The device

static VkInstance instance;
static VkPhysicalDevice physical;
static VkDevice device;
static VkQueue queue;
static VkCommandPool pool;
static int dynamic_rendering;
/** flat_pipeline's for dynamic rendering: VkPipelineRenderingCreateInfo, no render pass */
static const void *flat_next;
static VkPhysicalDeviceMemoryProperties memory_properties;
static int failures;
static int timeline_semaphores;
static char failure[256];

#define CHECK(x) do { VkResult r_ = (x); if(r_ != VK_SUCCESS) { printf("VKTEST error %s: %d\n", #x, r_); return 1; } } while(0)
#define EXPECT(cond, ...) do { if(!(cond)) { if(!failure[0]) { char *f_ = failure; (void)f_; sprintf_like(failure, __VA_ARGS__); } } } while(0)

static void sprintf_like(char *out, const char *text, ...)
{
    // (a fixed message: enough to say which check)
    int i = 0;
    for(; text[i] && i < 255; i++) out[i] = text[i];
    out[i] = 0;
}

static int setup(void)
{
    VkApplicationInfo app = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "vktest", .apiVersion = VK_API_VERSION_1_1 };
    VkInstanceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app };
    CHECK(vkCreateInstance(&info, 0, &instance));
    uint32_t count = 1;
    VkResult r = vkEnumeratePhysicalDevices(instance, &count, &physical);
    if((r != VK_SUCCESS && r != VK_INCOMPLETE) || !count) { printf("VKTEST error: no physical device\n"); return 1; }
    VkPhysicalDeviceProperties props;
    vkGetPhysicalDeviceProperties(physical, &props);
    printf("VKTEST device %s, Vulkan %u.%u.%u\n", props.deviceName, props.apiVersion >> 22, props.apiVersion >> 12 & 1023, props.apiVersion & 4095);
    vkGetPhysicalDeviceMemoryProperties(physical, &memory_properties);
    float priority = 1;
    VkDeviceQueueCreateInfo queue_info = { .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, .queueFamilyIndex = 0,
        .queueCount = 1, .pQueuePriorities = &priority };
    // VK_KHR_timeline_semaphore, when there is
    uint32_t extension_count = 0;
    vkEnumerateDeviceExtensionProperties(physical, 0, &extension_count, 0);
    VkExtensionProperties *extensions = calloc(extension_count + 1, sizeof *extensions);
    vkEnumerateDeviceExtensionProperties(physical, 0, &extension_count, extensions);
    for(uint32_t i = 0; i < extension_count; i++)
    {
        if(!strcmp(extensions[i].extensionName, "VK_KHR_timeline_semaphore")) timeline_semaphores = 1;
        if(!strcmp(extensions[i].extensionName, "VK_KHR_dynamic_rendering")) dynamic_rendering = 1;
    }
    free(extensions);
    // and VK_KHR_dynamic_rendering (with what it needs)
    const char *enabled[4];
    uint32_t enabled_count = 0;
    void *chain = 0;
    VkPhysicalDeviceDynamicRenderingFeatures dynamic_features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES,
        .dynamicRendering = VK_TRUE };
    VkPhysicalDeviceTimelineSemaphoreFeatures timeline_features = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES,
        .timelineSemaphore = VK_TRUE };
    if(dynamic_rendering)
    {
        enabled[enabled_count++] = "VK_KHR_dynamic_rendering";
        enabled[enabled_count++] = "VK_KHR_depth_stencil_resolve";
        enabled[enabled_count++] = "VK_KHR_create_renderpass2";
        dynamic_features.pNext = chain;
        chain = &dynamic_features;
    }
    if(timeline_semaphores)
    {
        enabled[enabled_count++] = "VK_KHR_timeline_semaphore";
        timeline_features.pNext = chain;
        chain = &timeline_features;
    }
    VkDeviceCreateInfo device_info = { .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, .queueCreateInfoCount = 1, .pQueueCreateInfos = &queue_info,
        .pNext = chain, .enabledExtensionCount = enabled_count, .ppEnabledExtensionNames = enabled };
    CHECK(vkCreateDevice(physical, &device_info, 0, &device));
    vkGetDeviceQueue(device, 0, 0, &queue);
    VkCommandPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
        .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT };
    CHECK(vkCreateCommandPool(device, &pool_info, 0, &pool));
    return 0;
}

static uint32_t memory_type(uint32_t bits, VkMemoryPropertyFlags want)
{
    for(uint32_t i = 0; i < memory_properties.memoryTypeCount; i++)
    {
        if(bits & 1u << i && (memory_properties.memoryTypes[i].propertyFlags & want) == want) return i;
    }
    return ~0u;
}

typedef struct { VkBuffer buffer; VkDeviceMemory memory; uint8_t *map; VkDeviceSize size; } Buffer;

static Buffer buffer(VkDeviceSize size, int host)
{
    Buffer b = { .size = size };
    VkBufferCreateInfo info = { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size,
        .usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
            VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT };
    vkCreateBuffer(device, &info, 0, &b.buffer);
    VkMemoryRequirements req;
    vkGetBufferMemoryRequirements(device, b.buffer, &req);
    VkMemoryAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size,
        .memoryTypeIndex = memory_type(req.memoryTypeBits, host ? VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT :
            VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) };
    vkAllocateMemory(device, &alloc, 0, &b.memory);
    vkBindBufferMemory(device, b.buffer, b.memory, 0);
    if(host) vkMapMemory(device, b.memory, 0, VK_WHOLE_SIZE, 0, (void **)&b.map);
    return b;
}

static void buffer_free(Buffer *b)
{
    if(b->map) vkUnmapMemory(device, b->memory);
    vkDestroyBuffer(device, b->buffer, 0);
    vkFreeMemory(device, b->memory, 0);
}

typedef struct { VkImage image; VkDeviceMemory memory; VkFormat format; uint32_t width, height; } Image;

static Image image(VkFormat format, uint32_t width, uint32_t height, uint32_t mips, VkSampleCountFlagBits samples, VkImageUsageFlags usage)
{
    Image i = { .format = format, .width = width, .height = height };
    VkImageCreateInfo info = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D, .format = format,
        .extent = { width, height, 1 }, .mipLevels = mips, .arrayLayers = 1, .samples = samples, .tiling = VK_IMAGE_TILING_OPTIMAL,
        .usage = usage, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED };
    vkCreateImage(device, &info, 0, &i.image);
    VkMemoryRequirements req;
    vkGetImageMemoryRequirements(device, i.image, &req);
    VkMemoryAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = req.size,
        .memoryTypeIndex = memory_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) };
    vkAllocateMemory(device, &alloc, 0, &i.memory);
    vkBindImageMemory(device, i.image, i.memory, 0);
    return i;
}

static void image_free(Image *i)
{
    vkDestroyImage(device, i->image, 0);
    vkFreeMemory(device, i->memory, 0);
}

static VkCommandBuffer begin(void)
{
    VkCommandBuffer cb;
    VkCommandBufferAllocateInfo info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = pool,
        .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, .commandBufferCount = 1 };
    vkAllocateCommandBuffers(device, &info, &cb);
    VkCommandBufferBeginInfo begin_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
        .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT };
    vkBeginCommandBuffer(cb, &begin_info);
    return cb;
}

/** end, submit, wait for the fence */
static VkResult run(VkCommandBuffer cb)
{
    vkEndCommandBuffer(cb);
    VkFence fence;
    VkFenceCreateInfo fence_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
    vkCreateFence(device, &fence_info, 0, &fence);
    VkSubmitInfo submit = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cb };
    VkResult r = vkQueueSubmit(queue, 1, &submit, fence);
    if(r == VK_SUCCESS) r = vkWaitForFences(device, 1, &fence, VK_TRUE, 30ull * 1000 * 1000 * 1000);
    vkDestroyFence(device, fence, 0);
    vkFreeCommandBuffers(device, pool, 1, &cb);
    return r;
}

static void barrier(VkCommandBuffer cb)
{
    VkMemoryBarrier b = { .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT };
    vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &b, 0, 0, 0, 0);
}

static void layout(VkCommandBuffer cb, VkImage image, VkImageAspectFlags aspect, VkImageLayout from, VkImageLayout to)
{
    VkImageMemoryBarrier b = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .srcAccessMask = VK_ACCESS_MEMORY_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT, .oldLayout = from, .newLayout = to,
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = image,
        .subresourceRange = { aspect, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS } };
    vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, 0, 0, 0, 1, &b);
}

static int near(int a, int b, int tolerance)
{
    return a - b <= tolerance && b - a <= tolerance;
}

// ---------------------------------------------------------------------------
// The tests: each returns nonzero on an error of the API, and puts what it
// found wrong into `failure`

/** copies host -> device local -> host; the guest's writes reach the GPU, the GPU's come back */
static int test_buffer_copy(void)
{
    Buffer src = buffer(4096, 1), mid = buffer(4096, 0), dst = buffer(4096, 1);
    for(int i = 0; i < 4096; i++) src.map[i] = (uint8_t)(i * 7 + 3);
    memset(dst.map, 0x5A, 4096);
    VkCommandBuffer cb = begin();
    VkBufferCopy whole = { 0, 0, 4096 }, part = { 1024, 8, 512 };
    vkCmdCopyBuffer(cb, src.buffer, mid.buffer, 1, &whole);
    barrier(cb);
    vkCmdCopyBuffer(cb, mid.buffer, dst.buffer, 1, &part);
    CHECK(run(cb));
    int bad = 0;
    for(int i = 0; i < 4096; i++)
    {
        uint8_t want = i >= 8 && i < 520 ? (uint8_t)((i - 8 + 1024) * 7 + 3) : 0x5A;
        if(dst.map[i] != want) bad++;
    }
    EXPECT(!bad, "bytes differ after the copies");
    buffer_free(&src); buffer_free(&mid); buffer_free(&dst);
    return 0;
}

static int test_fill_update(void)
{
    Buffer b = buffer(2048, 1);
    memset(b.map, 0x5A, 2048);
    uint32_t words[16];
    for(int i = 0; i < 16; i++) words[i] = 0x01020304u * (i + 1);
    VkCommandBuffer cb = begin();
    vkCmdFillBuffer(cb, b.buffer, 256, 256, 0x11223344);
    vkCmdUpdateBuffer(cb, b.buffer, 1024, sizeof words, words);
    vkCmdFillBuffer(cb, b.buffer, 1536, VK_WHOLE_SIZE, 0);
    CHECK(run(cb));
    uint32_t *w = (uint32_t *)b.map;
    int bad = 0;
    for(int i = 64; i < 128; i++) bad += w[i] != 0x11223344;
    EXPECT(!bad, "vkCmdFillBuffer");
    EXPECT(!memcmp(b.map + 1024, words, sizeof words), "vkCmdUpdateBuffer");
    EXPECT(b.map[255] == 0x5A && b.map[512] == 0x5A && b.map[1023] == 0x5A, "bytes around them changed");
    bad = 0;
    for(int i = 1536; i < 2048; i++) bad += b.map[i] != 0;
    EXPECT(!bad, "vkCmdFillBuffer to VK_WHOLE_SIZE");
    buffer_free(&b);
    return 0;
}

/** buffer -> image -> buffer, the second with a row length and offset of its own */
static int test_image_roundtrip(void)
{
    const uint32_t W = 64, H = 48;
    Buffer src = buffer(W * H * 4, 1), dst = buffer(256 + 70 * H * 4, 1);
    for(uint32_t i = 0; i < W * H * 4; i++) src.map[i] = (uint8_t)(i * 13 + i / 256);
    memset(dst.map, 0, dst.size);
    Image img = image(VK_FORMAT_R8G8B8A8_UNORM, W, H, 1, VK_SAMPLE_COUNT_1_BIT,
        VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, img.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { W, H, 1 } };
    vkCmdCopyBufferToImage(cb, src.buffer, img.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &in);
    layout(cb, img.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
    VkBufferImageCopy out = { .bufferOffset = 256, .bufferRowLength = 70, .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
        .imageExtent = { W, H, 1 } };
    vkCmdCopyImageToBuffer(cb, img.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dst.buffer, 1, &out);
    CHECK(run(cb));
    int bad = 0;
    for(uint32_t y = 0; y < H; y++) bad += memcmp(dst.map + 256 + y * 70 * 4, src.map + y * W * 4, W * 4) != 0;
    EXPECT(!bad, "rows differ");
    image_free(&img); buffer_free(&src); buffer_free(&dst);
    return 0;
}

/** a region of mip 1 */
static int test_image_mip_region(void)
{
    Buffer src = buffer(16 * 16 * 4, 1), dst = buffer(16 * 16 * 4, 1);
    for(int i = 0; i < 16 * 16 * 4; i++) src.map[i] = (uint8_t)(255 - i);
    memset(dst.map, 0, dst.size);
    Image img = image(VK_FORMAT_R8G8B8A8_UINT, 32, 32, 3, VK_SAMPLE_COUNT_1_BIT,
        VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, img.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 1, 0, 1 }, .imageOffset = { 4, 2, 0 }, .imageExtent = { 8, 6, 1 } };
    vkCmdCopyBufferToImage(cb, src.buffer, img.image, VK_IMAGE_LAYOUT_GENERAL, 1, &in);
    barrier(cb);
    VkBufferImageCopy out = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 1, 0, 1 }, .imageOffset = { 4, 2, 0 }, .imageExtent = { 8, 6, 1 } };
    vkCmdCopyImageToBuffer(cb, img.image, VK_IMAGE_LAYOUT_GENERAL, dst.buffer, 1, &out);
    CHECK(run(cb));
    EXPECT(!memcmp(dst.map, src.map, 8 * 6 * 4), "the region of mip 1 differs");
    image_free(&img); buffer_free(&src); buffer_free(&dst);
    return 0;
}

static int read_color(Image *img, uint32_t mip, Buffer *out)
{
    VkCommandBuffer cb = begin();
    layout(cb, img->image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, 1 },
        .imageExtent = { img->width >> mip, img->height >> mip, 1 } };
    vkCmdCopyImageToBuffer(cb, img->image, VK_IMAGE_LAYOUT_GENERAL, out->buffer, 1, &copy);
    return run(cb);
}

static int test_clear_color(void)
{
    Buffer out = buffer(16 * 16 * 16, 1);
    VkImageSubresourceRange all = { VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, 1 };
    // UNORM: (0.25, 0.5, 0.75, 1)
    Image unorm = image(VK_FORMAT_R8G8B8A8_UNORM, 16, 16, 2, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, unorm.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkClearColorValue c1 = { .float32 = { 0.25f, 0.5f, 0.75f, 1.0f } };
    vkCmdClearColorImage(cb, unorm.image, VK_IMAGE_LAYOUT_GENERAL, &c1, 1, &all);
    CHECK(run(cb));
    CHECK(read_color(&unorm, 1, &out));
    EXPECT(near(out.map[0], 64, 1) && near(out.map[1], 128, 1) && near(out.map[2], 191, 1) && out.map[3] == 255 &&
        !memcmp(out.map, out.map + 4 * 63, 4), "R8G8B8A8_UNORM's mip 1");
    // UINT, exact
    Image uint = image(VK_FORMAT_R32G32B32A32_UINT, 8, 8, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    cb = begin();
    layout(cb, uint.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkClearColorValue c2 = { .uint32 = { 1, 2, 0x80000000u, 0xFFFFFFFFu } };
    vkCmdClearColorImage(cb, uint.image, VK_IMAGE_LAYOUT_GENERAL, &c2, 1, &all);
    CHECK(run(cb));
    CHECK(read_color(&uint, 0, &out));
    uint32_t *u = (uint32_t *)out.map;
    EXPECT(u[0] == 1 && u[1] == 2 && u[2] == 0x80000000u && u[3] == 0xFFFFFFFFu && u[255] == 0xFFFFFFFFu, "R32G32B32A32_UINT");
    // half floats
    Image half = image(VK_FORMAT_R16G16B16A16_SFLOAT, 8, 8, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    cb = begin();
    layout(cb, half.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkClearColorValue c3 = { .float32 = { 0.5f, -2.0f, 0.0f, 1.0f } };
    vkCmdClearColorImage(cb, half.image, VK_IMAGE_LAYOUT_GENERAL, &c3, 1, &all);
    CHECK(run(cb));
    CHECK(read_color(&half, 0, &out));
    uint16_t *h = (uint16_t *)out.map;
    EXPECT(h[0] == 0x3800 && h[1] == 0xC000 && h[2] == 0 && h[3] == 0x3C00, "R16G16B16A16_SFLOAT");
    image_free(&unorm); image_free(&uint); image_free(&half); buffer_free(&out);
    return 0;
}

static int test_clear_depth(void)
{
    Buffer out = buffer(16 * 16 * 4, 1);
    Image d32 = image(VK_FORMAT_D32_SFLOAT, 16, 16, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    Image d16 = image(VK_FORMAT_D16_UNORM, 16, 16, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkImageSubresourceRange depth = { VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1 };
    VkClearDepthStencilValue v = { 0.375f, 0 };
    VkCommandBuffer cb = begin();
    layout(cb, d32.image, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    layout(cb, d16.image, VK_IMAGE_ASPECT_DEPTH_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    vkCmdClearDepthStencilImage(cb, d32.image, VK_IMAGE_LAYOUT_GENERAL, &v, 1, &depth);
    v.depth = 0.5f;
    vkCmdClearDepthStencilImage(cb, d16.image, VK_IMAGE_LAYOUT_GENERAL, &v, 1, &depth);
    barrier(cb);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0, 1 }, .imageExtent = { 16, 16, 1 } };
    vkCmdCopyImageToBuffer(cb, d32.image, VK_IMAGE_LAYOUT_GENERAL, out.buffer, 1, &copy);
    CHECK(run(cb));
    float *f = (float *)out.map;
    EXPECT(f[0] == 0.375f && f[255] == 0.375f, "D32_SFLOAT");
    cb = begin();
    vkCmdCopyImageToBuffer(cb, d16.image, VK_IMAGE_LAYOUT_GENERAL, out.buffer, 1, &copy);
    CHECK(run(cb));
    uint16_t *s = (uint16_t *)out.map;
    EXPECT(near(s[0], 32768, 1), "D16_UNORM");
    image_free(&d32); image_free(&d16); buffer_free(&out);
    return 0;
}

static int test_copy_image(void)
{
    Buffer src = buffer(32 * 32 * 4, 1), out = buffer(32 * 32 * 4, 1);
    for(int i = 0; i < 32 * 32 * 4; i++) src.map[i] = (uint8_t)(i ^ i >> 8);
    Image a = image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    Image b = image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, a.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    layout(cb, b.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 32, 32, 1 } };
    vkCmdCopyBufferToImage(cb, src.buffer, a.image, VK_IMAGE_LAYOUT_GENERAL, 1, &in);
    VkClearColorValue zero = { 0 };
    VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
    vkCmdClearColorImage(cb, b.image, VK_IMAGE_LAYOUT_GENERAL, &zero, 1, &range);
    barrier(cb);
    VkImageCopy region = { .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .srcOffset = { 8, 4, 0 },
        .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .dstOffset = { 1, 2, 0 }, .extent = { 16, 8, 1 } };
    vkCmdCopyImage(cb, a.image, VK_IMAGE_LAYOUT_GENERAL, b.image, VK_IMAGE_LAYOUT_GENERAL, 1, &region);
    CHECK(run(cb));
    CHECK(read_color(&b, 0, &out));
    int bad = 0;
    for(int y = 0; y < 32; y++) for(int x = 0; x < 32; x++)
    {
        const uint8_t *got = out.map + (y * 32 + x) * 4;
        int inside = x >= 1 && x < 17 && y >= 2 && y < 10;
        const uint8_t *want = src.map + ((y - 2 + 4) * 32 + x - 1 + 8) * 4;
        bad += inside ? memcmp(got, want, 4) != 0 : got[0] | got[1] | got[2] | got[3];
    }
    EXPECT(!bad, "the copied region (or what is around it) differs");
    image_free(&a); image_free(&b); buffer_free(&src); buffer_free(&out);
    return 0;
}

/** 4x4 -> 2x2, linear: each texel the average of 4 */
static int test_blit(void)
{
    Buffer src = buffer(4 * 4 * 4, 1), out = buffer(2 * 2 * 4, 1);
    for(int i = 0; i < 16; i++) { src.map[i * 4] = (uint8_t)(i * 16); src.map[i * 4 + 1] = 100; src.map[i * 4 + 2] = (uint8_t)(i & 1 ? 200 : 0); src.map[i * 4 + 3] = 255; }
    Image a = image(VK_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    Image b = image(VK_FORMAT_R8G8B8A8_UNORM, 2, 2, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, a.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    layout(cb, b.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkBufferImageCopy in = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 4, 4, 1 } };
    vkCmdCopyBufferToImage(cb, src.buffer, a.image, VK_IMAGE_LAYOUT_GENERAL, 1, &in);
    barrier(cb);
    VkImageBlit blit = { .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .srcOffsets = { { 0, 0, 0 }, { 4, 4, 1 } },
        .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .dstOffsets = { { 0, 0, 0 }, { 2, 2, 1 } } };
    vkCmdBlitImage(cb, a.image, VK_IMAGE_LAYOUT_GENERAL, b.image, VK_IMAGE_LAYOUT_GENERAL, 1, &blit, VK_FILTER_LINEAR);
    CHECK(run(cb));
    CHECK(read_color(&b, 0, &out));
    // texel (0, 0) averages source texels 0, 1, 4, 5: red (0 + 16 + 64 + 80) / 4 = 40, blue (0 + 200 + 0 + 200) / 4 = 100
    EXPECT(near(out.map[0], 40, 2) && out.map[1] == 100 && near(out.map[2], 100, 2) && out.map[3] == 255, "the linear blit's average");
    image_free(&a); image_free(&b); buffer_free(&src); buffer_free(&out);
    return 0;
}

static int test_resolve(void)
{
    Buffer out = buffer(8 * 8 * 4, 1);
    Image ms = image(VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, VK_SAMPLE_COUNT_4_BIT, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);
    Image one = image(VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkCommandBuffer cb = begin();
    layout(cb, ms.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    layout(cb, one.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    VkClearColorValue c = { .float32 = { 0, 1, 0.5f, 1 } };
    VkImageSubresourceRange range = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
    vkCmdClearColorImage(cb, ms.image, VK_IMAGE_LAYOUT_GENERAL, &c, 1, &range);
    barrier(cb);
    VkImageResolve resolve = { .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 },
        .extent = { 8, 8, 1 } };
    vkCmdResolveImage(cb, ms.image, VK_IMAGE_LAYOUT_GENERAL, one.image, VK_IMAGE_LAYOUT_GENERAL, 1, &resolve);
    CHECK(run(cb));
    CHECK(read_color(&one, 0, &out));
    EXPECT(out.map[0] == 0 && out.map[1] == 255 && near(out.map[2], 128, 1) && out.map[3] == 255, "the resolved color");
    image_free(&ms); image_free(&one); buffer_free(&out);
    return 0;
}

static int test_fence(void)
{
    VkFence fence;
    VkFenceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .flags = VK_FENCE_CREATE_SIGNALED_BIT };
    CHECK(vkCreateFence(device, &info, 0, &fence));
    EXPECT(vkGetFenceStatus(device, fence) == VK_SUCCESS, "created signaled");
    vkResetFences(device, 1, &fence);
    EXPECT(vkGetFenceStatus(device, fence) == VK_NOT_READY, "reset: not ready");
    EXPECT(vkWaitForFences(device, 1, &fence, VK_TRUE, 0) == VK_TIMEOUT, "a wait of 0 on an unsignaled fence times out");
    EXPECT(vkWaitForFences(device, 1, &fence, VK_TRUE, 1000 * 1000) == VK_TIMEOUT, "a wait of 1 ms times out");
    Buffer b = buffer(256, 1);
    VkCommandBuffer cb = begin();
    vkCmdFillBuffer(cb, b.buffer, 0, 256, 0xCAFEF00D);
    vkEndCommandBuffer(cb);
    VkSubmitInfo submit = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cb };
    CHECK(vkQueueSubmit(queue, 1, &submit, fence));
    CHECK(vkWaitForFences(device, 1, &fence, VK_TRUE, 30ull * 1000 * 1000 * 1000));
    EXPECT(vkGetFenceStatus(device, fence) == VK_SUCCESS, "signaled by the submission");
    EXPECT(((uint32_t *)b.map)[63] == 0xCAFEF00D, "the submission's work is done when its fence is");
    vkFreeCommandBuffers(device, pool, 1, &cb);
    vkDestroyFence(device, fence, 0);
    buffer_free(&b);
    return 0;
}

/** a submission waits for a timeline value the host signals, and signals the next */
static int test_timeline(void)
{
    if(!timeline_semaphores) { EXPECT(0, "VK_KHR_timeline_semaphore is not there"); return 0; }
    VkSemaphoreTypeCreateInfo type = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO, .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE,
        .initialValue = 0 };
    VkSemaphoreCreateInfo info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = &type };
    VkSemaphore timeline;
    CHECK(vkCreateSemaphore(device, &info, 0, &timeline));
    Buffer b = buffer(256, 1);
    memset(b.map, 0, 256);
    VkCommandBuffer cb = begin();
    vkCmdFillBuffer(cb, b.buffer, 0, 256, 0x12345678);
    vkEndCommandBuffer(cb);
    uint64_t wait = 1, signal = 2;
    VkTimelineSemaphoreSubmitInfo values = { .sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO,
        .waitSemaphoreValueCount = 1, .pWaitSemaphoreValues = &wait, .signalSemaphoreValueCount = 1, .pSignalSemaphoreValues = &signal };
    VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
    VkSubmitInfo submit = { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .pNext = &values, .waitSemaphoreCount = 1, .pWaitSemaphores = &timeline,
        .pWaitDstStageMask = &stage, .commandBufferCount = 1, .pCommandBuffers = &cb, .signalSemaphoreCount = 1, .pSignalSemaphores = &timeline };
    PFN_vkGetSemaphoreCounterValue get = (PFN_vkGetSemaphoreCounterValue)vkGetDeviceProcAddr(device, "vkGetSemaphoreCounterValueKHR");
    PFN_vkSignalSemaphore host_signal = (PFN_vkSignalSemaphore)vkGetDeviceProcAddr(device, "vkSignalSemaphoreKHR");
    PFN_vkWaitSemaphores host_wait = (PFN_vkWaitSemaphores)vkGetDeviceProcAddr(device, "vkWaitSemaphoresKHR");
    if(!get || !host_signal || !host_wait) { EXPECT(0, "no timeline semaphore functions"); return 0; }
    CHECK(vkQueueSubmit(queue, 1, &submit, VK_NULL_HANDLE));
    uint64_t value = 99;
    get(device, timeline, &value);
    EXPECT(value == 0, "nothing signaled yet");
    VkSemaphoreWaitInfo wait_info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO, .semaphoreCount = 1, .pSemaphores = &timeline, .pValues = &signal };
    EXPECT(host_wait(device, &wait_info, 1000 * 1000) == VK_TIMEOUT, "the submission waits for the host");
    EXPECT(((uint32_t *)b.map)[0] == 0, "and its work is not done");
    VkSemaphoreSignalInfo signal_info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO, .semaphore = timeline, .value = 1 };
    CHECK(host_signal(device, &signal_info));
    CHECK(host_wait(device, &wait_info, 30ull * 1000 * 1000 * 1000));
    get(device, timeline, &value);
    EXPECT(value == 2, "the submission signaled 2");
    EXPECT(((uint32_t *)b.map)[63] == 0x12345678, "after the host's signal, the work is done");
    vkFreeCommandBuffers(device, pool, 1, &cb);
    vkDestroySemaphore(device, timeline, 0);
    buffer_free(&b);
    return 0;
}

/** two submissions in order through a binary semaphore; vkQueueWaitIdle */
static int test_semaphores(void)
{
    VkSemaphoreCreateInfo info = { .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
    VkSemaphore semaphore;
    CHECK(vkCreateSemaphore(device, &info, 0, &semaphore));
    Buffer a = buffer(256, 1), b = buffer(256, 1);
    memset(b.map, 0, 256);
    VkCommandBuffer first = begin();
    vkCmdFillBuffer(first, a.buffer, 0, 256, 0x0BADBEEF);
    vkEndCommandBuffer(first);
    VkCommandBuffer second = begin();
    VkBufferCopy copy = { 0, 0, 256 };
    vkCmdCopyBuffer(second, a.buffer, b.buffer, 1, &copy);
    vkEndCommandBuffer(second);
    VkPipelineStageFlags stage = VK_PIPELINE_STAGE_TRANSFER_BIT;
    VkSubmitInfo submits[2] = {
        { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &first, .signalSemaphoreCount = 1, .pSignalSemaphores = &semaphore },
        { .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .waitSemaphoreCount = 1, .pWaitSemaphores = &semaphore, .pWaitDstStageMask = &stage,
          .commandBufferCount = 1, .pCommandBuffers = &second },
    };
    CHECK(vkQueueSubmit(queue, 1, &submits[0], VK_NULL_HANDLE));
    CHECK(vkQueueSubmit(queue, 1, &submits[1], VK_NULL_HANDLE));
    CHECK(vkQueueWaitIdle(queue));
    EXPECT(((uint32_t *)b.map)[0] == 0x0BADBEEF && ((uint32_t *)b.map)[63] == 0x0BADBEEF, "the second saw the first's work");
    VkCommandBuffer cbs[2] = { first, second };
    vkFreeCommandBuffers(device, pool, 2, cbs);
    vkDestroySemaphore(device, semaphore, 0);
    buffer_free(&a); buffer_free(&b);
    return 0;
}

static int test_events(void)
{
    VkEventCreateInfo info = { .sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO };
    VkEvent event;
    CHECK(vkCreateEvent(device, &info, 0, &event));
    EXPECT(vkGetEventStatus(device, event) == VK_EVENT_RESET, "created reset");
    vkSetEvent(device, event);
    EXPECT(vkGetEventStatus(device, event) == VK_EVENT_SET, "set by the host");
    vkResetEvent(device, event);
    VkCommandBuffer cb = begin();
    vkCmdSetEvent(cb, event, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
    CHECK(run(cb));
    EXPECT(vkGetEventStatus(device, event) == VK_EVENT_SET, "set by a command buffer");
    vkDestroyEvent(device, event, 0);
    return 0;
}

/** memory the GPU writes, mapped again later: the GPU's bytes */
static int test_remap(void)
{
    Buffer b = buffer(8192, 1);
    vkUnmapMemory(device, b.memory);
    b.map = 0;
    VkCommandBuffer cb = begin();
    vkCmdFillBuffer(cb, b.buffer, 4096, 4096, 0x55AA55AA);
    CHECK(run(cb));
    uint32_t *w;
    CHECK(vkMapMemory(device, b.memory, 0, VK_WHOLE_SIZE, 0, (void **)&w));
    EXPECT(w[1024] == 0x55AA55AA && w[2047] == 0x55AA55AA, "the GPU's writes, in a later mapping");
    w[0] = 0x600DF00D;
    vkUnmapMemory(device, b.memory);
    Buffer out = buffer(256, 1);
    cb = begin();
    VkBufferCopy copy = { 0, 0, 4 };
    vkCmdCopyBuffer(cb, b.buffer, out.buffer, 1, &copy);
    CHECK(run(cb));
    EXPECT(((uint32_t *)out.map)[0] == 0x600DF00D, "the guest's write before an unmap reaches the GPU");
    vkDestroyBuffer(device, b.buffer, 0);
    vkFreeMemory(device, b.memory, 0);
    buffer_free(&out);
    return 0;
}


// ---------------------------------------------------------------------------
// Drawing: 64x64 targets, read back as RGBA8

#define SIZE 64

static VkShaderModule shader(const uint32_t *code, size_t size)
{
    VkShaderModuleCreateInfo info = { .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code };
    VkShaderModule module = VK_NULL_HANDLE;
    vkCreateShaderModule(device, &info, 0, &module);
    return module;
}

typedef struct {
    VkRenderPass pass;
    VkFramebuffer framebuffer;
    Image color, resolve, depth;
    VkImageView views[3];
    int has_depth, samples;
} Target;

static VkImageView view_of(Image *img, VkImageAspectFlags aspect)
{
    VkImageViewCreateInfo info = { .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img->image, .viewType = VK_IMAGE_VIEW_TYPE_2D,
        .format = img->format, .subresourceRange = { aspect, 0, 1, 0, 1 } };
    VkImageView view = VK_NULL_HANDLE;
    vkCreateImageView(device, &info, 0, &view);
    return view;
}

/** a render pass of a color attachment (cleared), maybe a depth one (cleared to 1), maybe 4x with a resolve */
static Target target(int depth, int samples, VkClearColorValue unused)
{
    Target t = { .has_depth = depth, .samples = samples };
    VkSampleCountFlagBits count = samples > 1 ? VK_SAMPLE_COUNT_4_BIT : VK_SAMPLE_COUNT_1_BIT;
    t.color = image(VK_FORMAT_R8G8B8A8_UNORM, SIZE, SIZE, 1, count, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
    VkAttachmentDescription attachments[3] = {
        { .format = VK_FORMAT_R8G8B8A8_UNORM, .samples = count, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
          .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
          .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, .finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL },
    };
    uint32_t n = 1;
    VkAttachmentReference color_ref = { 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }, resolve_ref = { 0, 0 }, depth_ref = { 0, 0 };
    t.views[0] = view_of(&t.color, VK_IMAGE_ASPECT_COLOR_BIT);
    if(samples > 1)
    {
        t.resolve = image(VK_FORMAT_R8G8B8A8_UNORM, SIZE, SIZE, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
        attachments[n] = attachments[0];
        attachments[n].samples = VK_SAMPLE_COUNT_1_BIT;
        attachments[n].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
        resolve_ref = (VkAttachmentReference){ n, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL };
        t.views[n++] = view_of(&t.resolve, VK_IMAGE_ASPECT_COLOR_BIT);
    }
    if(depth)
    {
        t.depth = image(VK_FORMAT_D32_SFLOAT, SIZE, SIZE, 1, count, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
        attachments[n] = (VkAttachmentDescription){ .format = VK_FORMAT_D32_SFLOAT, .samples = count, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
            .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
            .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
            .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
        depth_ref = (VkAttachmentReference){ n, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL };
        t.views[n++] = view_of(&t.depth, VK_IMAGE_ASPECT_DEPTH_BIT);
    }
    VkSubpassDescription subpass = { .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1,
        .pColorAttachments = &color_ref, .pResolveAttachments = samples > 1 ? &resolve_ref : 0, .pDepthStencilAttachment = depth ? &depth_ref : 0 };
    VkRenderPassCreateInfo info = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = n, .pAttachments = attachments,
        .subpassCount = 1, .pSubpasses = &subpass };
    vkCreateRenderPass(device, &info, 0, &t.pass);
    VkFramebufferCreateInfo fb = { .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = t.pass, .attachmentCount = n,
        .pAttachments = t.views, .width = SIZE, .height = SIZE, .layers = 1 };
    vkCreateFramebuffer(device, &fb, 0, &t.framebuffer);
    return t;
}

static void target_free(Target *t)
{
    vkDestroyFramebuffer(device, t->framebuffer, 0);
    vkDestroyRenderPass(device, t->pass, 0);
    int n = 1 + (t->samples > 1) + t->has_depth;
    for(int i = 0; i < n; i++) vkDestroyImageView(device, t->views[i], 0);
    image_free(&t->color);
    if(t->samples > 1) image_free(&t->resolve);
    if(t->has_depth) image_free(&t->depth);
}

static void begin_pass(VkCommandBuffer cb, Target *t, float r, float g, float b)
{
    VkClearValue clears[3] = { { .color = { .float32 = { r, g, b, 1 } } } };
    int n = 1;
    if(t->samples > 1) clears[n++].color = clears[0].color;
    if(t->has_depth) clears[n++].depthStencil = (VkClearDepthStencilValue){ 1, 0 };
    VkRenderPassBeginInfo info = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = t->pass, .framebuffer = t->framebuffer,
        .renderArea = { { 0, 0 }, { SIZE, SIZE } }, .clearValueCount = n, .pClearValues = clears };
    vkCmdBeginRenderPass(cb, &info, VK_SUBPASS_CONTENTS_INLINE);
    VkViewport viewport = { 0, 0, SIZE, SIZE, 0, 1 };
    VkRect2D scissor = { { 0, 0 }, { SIZE, SIZE } };
    vkCmdSetViewport(cb, 0, 1, &viewport);
    vkCmdSetScissor(cb, 0, 1, &scissor);
}

/** the target's picture (the resolved one when there is one) into `out` */
static int read_target(Target *t, Buffer *out)
{
    VkCommandBuffer cb = begin();
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { SIZE, SIZE, 1 } };
    vkCmdCopyImageToBuffer(cb, t->samples > 1 ? t->resolve.image : t->color.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, out->buffer, 1, &copy);
    return run(cb);
}

static const uint8_t *pixel(Buffer *b, int x, int y)
{
    return b->map + (y * SIZE + x) * 4;
}

static int pixel_is(Buffer *b, int x, int y, int r, int g, int bl, int tolerance)
{
    const uint8_t *p = pixel(b, x, y);
    return near(p[0], r, tolerance) && near(p[1], g, tolerance) && near(p[2], bl, tolerance);
}

typedef struct {
    VkPipeline pipeline;
    VkPipelineLayout layout;
    VkDescriptorSetLayout set_layout;
} Pipeline;

/**
 * flat.vert/flat.frag: vertex buffer 0 (position vec3, color vec4: 28
 * bytes), push constants, the uniform buffer at set 0 binding 0
 */
static Pipeline flat_pipeline(Target *t, VkPrimitiveTopology topology, int depth_test, int blend)
{
    Pipeline p = { 0 };
    VkDescriptorSetLayoutBinding binding = { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, 0 };
    VkDescriptorSetLayoutCreateInfo set_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 1, .pBindings = &binding };
    vkCreateDescriptorSetLayout(device, &set_info, 0, &p.set_layout);
    VkPushConstantRange push = { VK_SHADER_STAGE_VERTEX_BIT, 0, 16 };
    VkPipelineLayoutCreateInfo layout_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &p.set_layout,
        .pushConstantRangeCount = 1, .pPushConstantRanges = &push };
    vkCreatePipelineLayout(device, &layout_info, 0, &p.layout);
    VkShaderModule vs = shader(SPV_flat_vert, sizeof SPV_flat_vert), fs = shader(SPV_flat_frag, sizeof SPV_flat_frag);
    VkPipelineShaderStageCreateInfo stages[2] = {
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vs, .pName = "main" },
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fs, .pName = "main" },
    };
    VkVertexInputBindingDescription vb = { 0, 28, VK_VERTEX_INPUT_RATE_VERTEX };
    VkVertexInputAttributeDescription attributes[2] = { { 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0 }, { 1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, 12 } };
    VkPipelineVertexInputStateCreateInfo vertex = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
        .vertexBindingDescriptionCount = 1, .pVertexBindingDescriptions = &vb, .vertexAttributeDescriptionCount = 2, .pVertexAttributeDescriptions = attributes };
    VkPipelineInputAssemblyStateCreateInfo assembly = { .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, .topology = topology };
    VkPipelineViewportStateCreateInfo viewport = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1 };
    VkPipelineRasterizationStateCreateInfo raster = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
        .polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE, .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1 };
    VkPipelineMultisampleStateCreateInfo ms = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
        .rasterizationSamples = t->samples > 1 ? VK_SAMPLE_COUNT_4_BIT : VK_SAMPLE_COUNT_1_BIT };
    VkPipelineDepthStencilStateCreateInfo ds = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
        .depthTestEnable = depth_test, .depthWriteEnable = depth_test, .depthCompareOp = VK_COMPARE_OP_LESS, .maxDepthBounds = 1 };
    VkPipelineColorBlendAttachmentState attachment = { .blendEnable = blend, .srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA,
        .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD, .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE,
        .dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO, .alphaBlendOp = VK_BLEND_OP_ADD, .colorWriteMask = 0xF };
    VkPipelineColorBlendStateCreateInfo blend_state = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
        .attachmentCount = 1, .pAttachments = &attachment };
    VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
    VkPipelineDynamicStateCreateInfo dynamic = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, .dynamicStateCount = 2,
        .pDynamicStates = dynamic_states };
    VkGraphicsPipelineCreateInfo info = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2, .pStages = stages,
        .pVertexInputState = &vertex, .pInputAssemblyState = &assembly, .pViewportState = &viewport, .pRasterizationState = &raster,
        .pMultisampleState = &ms, .pDepthStencilState = t->has_depth ? &ds : 0, .pColorBlendState = &blend_state, .pDynamicState = &dynamic,
        .layout = p.layout, .renderPass = flat_next ? VK_NULL_HANDLE : t->pass, .pNext = flat_next };
    vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, 0, &p.pipeline);
    vkDestroyShaderModule(device, vs, 0);
    vkDestroyShaderModule(device, fs, 0);
    return p;
}

static void pipeline_free(Pipeline *p)
{
    vkDestroyPipeline(device, p->pipeline, 0);
    vkDestroyPipelineLayout(device, p->layout, 0);
    vkDestroyDescriptorSetLayout(device, p->set_layout, 0);
}

/** a descriptor set of one uniform buffer for flat.vert */
static VkDescriptorSet uniform_set(Pipeline *p, VkDescriptorPool *pool_out, Buffer *ubo)
{
    VkDescriptorPoolSize size = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 };
    VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .maxSets = 1, .poolSizeCount = 1, .pPoolSizes = &size };
    vkCreateDescriptorPool(device, &pool_info, 0, pool_out);
    VkDescriptorSetAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = *pool_out,
        .descriptorSetCount = 1, .pSetLayouts = &p->set_layout };
    VkDescriptorSet set;
    vkAllocateDescriptorSets(device, &alloc, &set);
    VkDescriptorBufferInfo info = { ubo->buffer, 0, 16 };
    VkWriteDescriptorSet write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .dstBinding = 0, .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &info };
    vkUpdateDescriptorSets(device, 1, &write, 0, 0);
    return set;
}

/** a rectangle of two triangles, at a depth, of a color: 6 vertices of flat.vert's */
static void rectangle(float *v, float x0, float y0, float x1, float y1, float z, float r, float g, float b, float a)
{
    const float corners[6][2] = { { x0, y0 }, { x1, y0 }, { x0, y1 }, { x1, y0 }, { x1, y1 }, { x0, y1 } };
    for(int i = 0; i < 6; i++)
    {
        float *o = v + i * 7;
        o[0] = corners[i][0]; o[1] = corners[i][1]; o[2] = z;
        o[3] = r; o[4] = g; o[5] = b; o[6] = a;
    }
}

/** a rectangle, moved by push constants, tinted by a uniform buffer; Y down as Vulkan's */
static int test_draw(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 0);
    Buffer vb = buffer(6 * 28, 1), ubo = buffer(256, 1), out = buffer(SIZE * SIZE * 4, 1);
    rectangle((float *)vb.map, -0.5f, -0.75f, 0.5f, 0.25f, 0.5f, 1, 0.5f, 0.25f, 1);
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkCommandBuffer cb = begin();
    begin_pass(cb, &t, 0, 0, 0);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.layout, 0, 1, &set, 0, 0);
    VkDeviceSize offset = 0;
    vkCmdBindVertexBuffers(cb, 0, 1, &vb.buffer, &offset);
    float push[4] = { 0.25f, 0, 1, 0 };
    vkCmdPushConstants(cb, p.layout, VK_SHADER_STAGE_VERTEX_BIT, 0, 16, push);
    vkCmdDraw(cb, 6, 1, 0, 0);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    // x: -0.25 .. 0.75 -> pixels 24 .. 56; y: -0.75 .. 0.25 -> rows 8 .. 40 (Vulkan: -1 is the top)
    EXPECT(pixel_is(&out, 40, 12, 255, 128, 64, 2), "inside the rectangle (moved by the push constants)");
    EXPECT(pixel_is(&out, 40, 44, 0, 0, 0, 0), "below it: Y down");
    EXPECT(pixel_is(&out, 10, 20, 0, 0, 0, 0), "left of it");
    EXPECT(pixel_is(&out, 60, 20, 0, 0, 0, 0), "right of it");
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    target_free(&t);
    buffer_free(&vb); buffer_free(&ubo); buffer_free(&out);
    return 0;
}

/** indexed draws with a depth test: the nearer rectangle wins whatever the order */
static int test_depth(void)
{
    Target t = target(1, 1, (VkClearColorValue){ 0 });
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 1, 0);
    Buffer vb = buffer(3 * 6 * 28, 1), ib = buffer(64, 1), ubo = buffer(256, 1), out = buffer(SIZE * SIZE * 4, 1);
    float *v = (float *)vb.map;
    rectangle(v, -1, -1, 1, 1, 0.5f, 1, 0, 0, 1);              // red, everywhere, at 0.5
    rectangle(v + 42, -0.5f, -0.5f, 0.5f, 0.5f, 0.25f, 0, 1, 0, 1); // green, the middle, nearer
    rectangle(v + 84, -1, -1, 1, 1, 0.75f, 0, 0, 1, 1);      // blue, everywhere, behind
    uint16_t *indices = (uint16_t *)ib.map;
    for(int i = 0; i < 18; i++) indices[i] = (uint16_t)i;
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkCommandBuffer cb = begin();
    begin_pass(cb, &t, 0, 0, 0);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.layout, 0, 1, &set, 0, 0);
    VkDeviceSize offset = 0;
    vkCmdBindVertexBuffers(cb, 0, 1, &vb.buffer, &offset);
    vkCmdBindIndexBuffer(cb, ib.buffer, 0, VK_INDEX_TYPE_UINT16);
    float push[4] = { 0, 0, 1, 0 };
    vkCmdPushConstants(cb, p.layout, VK_SHADER_STAGE_VERTEX_BIT, 0, 16, push);
    vkCmdDrawIndexed(cb, 6, 1, 0, 0, 0);
    vkCmdDrawIndexed(cb, 6, 1, 6, 0, 0);
    vkCmdDrawIndexed(cb, 6, 1, 0, 12, 0);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    EXPECT(pixel_is(&out, 32, 32, 0, 255, 0, 0), "the middle: the nearest (green)");
    EXPECT(pixel_is(&out, 4, 4, 255, 0, 0, 0), "a corner: red, in front of blue");
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    target_free(&t);
    buffer_free(&vb); buffer_free(&ib); buffer_free(&ubo); buffer_free(&out);
    return 0;
}

/** blending: half transparent red over blue; and 4x MSAA, resolved */
static int test_blend_msaa(void)
{
    for(int msaa = 0; msaa < 2; msaa++)
    {
        Target t = target(0, msaa ? 4 : 1, (VkClearColorValue){ 0 });
        Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 1);
        Buffer vb = buffer(6 * 28, 1), ubo = buffer(256, 1), out = buffer(SIZE * SIZE * 4, 1);
        rectangle((float *)vb.map, -1, -1, 1, 1, 0, 1, 0, 0, 0.5f);
        float tint[4] = { 1, 1, 1, 1 };
        memcpy(ubo.map, tint, sizeof tint);
        VkDescriptorPool dpool;
        VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
        VkCommandBuffer cb = begin();
        begin_pass(cb, &t, 0, 0, 1);
        vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.pipeline);
        vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p.layout, 0, 1, &set, 0, 0);
        VkDeviceSize offset = 0;
        vkCmdBindVertexBuffers(cb, 0, 1, &vb.buffer, &offset);
        float push[4] = { 0, 0, 1, 0 };
        vkCmdPushConstants(cb, p.layout, VK_SHADER_STAGE_VERTEX_BIT, 0, 16, push);
        vkCmdDraw(cb, 6, 1, 0, 0);
        vkCmdEndRenderPass(cb);
        CHECK(run(cb));
        CHECK(read_target(&t, &out));
        EXPECT(pixel_is(&out, 32, 32, 128, 0, 128, 2), msaa ? "4x MSAA, resolved: half red over blue" : "half red over blue");
        vkDestroyDescriptorPool(device, dpool, 0);
        pipeline_free(&p);
        target_free(&t);
        buffer_free(&vb); buffer_free(&ubo); buffer_free(&out);
    }
    return 0;
}

/** a 2x2 texture, nearest, through a separate sampler: its texels in the quadrants */
static int test_texture(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Buffer texels = buffer(16, 1), out = buffer(SIZE * SIZE * 4, 1);
    const uint8_t rgba[16] = { 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255 };
    memcpy(texels.map, rgba, 16);
    Image tex = image(VK_FORMAT_R8G8B8A8_UNORM, 2, 2, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkImageView view = view_of(&tex, VK_IMAGE_ASPECT_COLOR_BIT);
    VkSamplerCreateInfo sampler_info = { .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_NEAREST, .minFilter = VK_FILTER_NEAREST,
        .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
        .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .maxLod = 1 };
    VkSampler sampler;
    vkCreateSampler(device, &sampler_info, 0, &sampler);
    VkDescriptorSetLayoutBinding bindings[2] = {
        { 0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT, 0 },
        { 1, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, 0 },
    };
    VkDescriptorSetLayoutCreateInfo set_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 2, .pBindings = bindings };
    VkDescriptorSetLayout set_layout;
    vkCreateDescriptorSetLayout(device, &set_info, 0, &set_layout);
    VkPipelineLayoutCreateInfo layout_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &set_layout };
    VkPipelineLayout pipeline_layout;
    vkCreatePipelineLayout(device, &layout_info, 0, &pipeline_layout);
    VkShaderModule vs = shader(SPV_textured_vert, sizeof SPV_textured_vert), fs = shader(SPV_textured_frag, sizeof SPV_textured_frag);
    VkPipelineShaderStageCreateInfo stages[2] = {
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vs, .pName = "main" },
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fs, .pName = "main" },
    };
    VkPipelineVertexInputStateCreateInfo vertex = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
    VkPipelineInputAssemblyStateCreateInfo assembly = { .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
        .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP };
    VkViewport vp = { 0, 0, SIZE, SIZE, 0, 1 };
    VkRect2D sc = { { 0, 0 }, { SIZE, SIZE } };
    VkPipelineViewportStateCreateInfo viewport = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .pViewports = &vp,
        .scissorCount = 1, .pScissors = &sc };
    VkPipelineRasterizationStateCreateInfo raster = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .lineWidth = 1 };
    VkPipelineMultisampleStateCreateInfo ms = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT };
    VkPipelineColorBlendAttachmentState attachment = { .colorWriteMask = 0xF };
    VkPipelineColorBlendStateCreateInfo blend = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .attachmentCount = 1, .pAttachments = &attachment };
    VkGraphicsPipelineCreateInfo info = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2, .pStages = stages,
        .pVertexInputState = &vertex, .pInputAssemblyState = &assembly, .pViewportState = &viewport, .pRasterizationState = &raster,
        .pMultisampleState = &ms, .pColorBlendState = &blend, .layout = pipeline_layout, .renderPass = t.pass };
    VkPipeline pipeline;
    vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, 0, &pipeline);
    VkDescriptorPoolSize sizes[2] = { { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1 }, { VK_DESCRIPTOR_TYPE_SAMPLER, 1 } };
    VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .maxSets = 1, .poolSizeCount = 2, .pPoolSizes = sizes };
    VkDescriptorPool dpool;
    vkCreateDescriptorPool(device, &pool_info, 0, &dpool);
    VkDescriptorSetAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = dpool, .descriptorSetCount = 1, .pSetLayouts = &set_layout };
    VkDescriptorSet set;
    vkAllocateDescriptorSets(device, &alloc, &set);
    VkDescriptorImageInfo image_info = { .imageView = view, .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
    VkDescriptorImageInfo sampler_desc = { .sampler = sampler };
    VkWriteDescriptorSet writes[2] = {
        { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, .pImageInfo = &image_info },
        { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .dstBinding = 1, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER, .pImageInfo = &sampler_desc },
    };
    vkUpdateDescriptorSets(device, 2, writes, 0, 0);
    VkCommandBuffer cb = begin();
    layout(cb, tex.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 2, 2, 1 } };
    vkCmdCopyBufferToImage(cb, texels.buffer, tex.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
    layout(cb, tex.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
    begin_pass(cb, &t, 0, 0, 0);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &set, 0, 0);
    vkCmdDraw(cb, 4, 1, 0, 0);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    EXPECT(pixel_is(&out, 16, 16, 255, 0, 0, 0), "top left: texel (0, 0)");
    EXPECT(pixel_is(&out, 48, 16, 0, 255, 0, 0), "top right: texel (1, 0)");
    EXPECT(pixel_is(&out, 16, 48, 0, 0, 255, 0), "bottom left: texel (0, 1)");
    EXPECT(pixel_is(&out, 48, 48, 255, 255, 255, 0), "bottom right: texel (1, 1)");
    vkDestroyPipeline(device, pipeline, 0);
    vkDestroyDescriptorPool(device, dpool, 0);
    vkDestroyPipelineLayout(device, pipeline_layout, 0);
    vkDestroyDescriptorSetLayout(device, set_layout, 0);
    vkDestroyShaderModule(device, vs, 0);
    vkDestroyShaderModule(device, fs, 0);
    vkDestroySampler(device, sampler, 0);
    vkDestroyImageView(device, view, 0);
    image_free(&tex);
    target_free(&t);
    buffer_free(&texels); buffer_free(&out);
    return 0;
}

/** a compute shader into a storage buffer the guest maps */
static int test_compute(void)
{
    Buffer b = buffer(256 * 4, 1);
    memset(b.map, 0, 256 * 4);
    VkDescriptorSetLayoutBinding binding = { 0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, 0 };
    VkDescriptorSetLayoutCreateInfo set_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 1, .pBindings = &binding };
    VkDescriptorSetLayout set_layout;
    vkCreateDescriptorSetLayout(device, &set_info, 0, &set_layout);
    VkPushConstantRange push = { VK_SHADER_STAGE_COMPUTE_BIT, 0, 4 };
    VkPipelineLayoutCreateInfo layout_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &set_layout,
        .pushConstantRangeCount = 1, .pPushConstantRanges = &push };
    VkPipelineLayout pipeline_layout;
    vkCreatePipelineLayout(device, &layout_info, 0, &pipeline_layout);
    VkShaderModule cs = shader(SPV_fill_comp, sizeof SPV_fill_comp);
    VkComputePipelineCreateInfo info = { .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
        .stage = { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = cs, .pName = "main" },
        .layout = pipeline_layout };
    VkPipeline pipeline;
    vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &info, 0, &pipeline);
    VkDescriptorPoolSize size = { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1 };
    VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .maxSets = 1, .poolSizeCount = 1, .pPoolSizes = &size };
    VkDescriptorPool dpool;
    vkCreateDescriptorPool(device, &pool_info, 0, &dpool);
    VkDescriptorSetAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = dpool, .descriptorSetCount = 1, .pSetLayouts = &set_layout };
    VkDescriptorSet set;
    vkAllocateDescriptorSets(device, &alloc, &set);
    VkDescriptorBufferInfo buffer_info = { b.buffer, 0, VK_WHOLE_SIZE };
    VkWriteDescriptorSet write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, .pBufferInfo = &buffer_info };
    vkUpdateDescriptorSets(device, 1, &write, 0, 0);
    VkCommandBuffer cb = begin();
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &set, 0, 0);
    uint32_t base = 7;
    vkCmdPushConstants(cb, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, 4, &base);
    vkCmdDispatch(cb, 4, 1, 1);
    CHECK(run(cb));
    const uint32_t *values = (const uint32_t *)b.map;
    int bad = 0;
    for(uint32_t i = 0; i < 256; i++) bad += values[i] != i * 2 + 7;
    EXPECT(!bad, "the storage buffer's values");
    vkDestroyPipeline(device, pipeline, 0);
    vkDestroyDescriptorPool(device, dpool, 0);
    vkDestroyPipelineLayout(device, pipeline_layout, 0);
    vkDestroyDescriptorSetLayout(device, set_layout, 0);
    vkDestroyShaderModule(device, cs, 0);
    buffer_free(&b);
    return 0;
}


/** vkCmdClearAttachments: a rectangle of the color, in the render pass */
static int test_clear_attachments(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Buffer out = buffer(SIZE * SIZE * 4, 1);
    VkCommandBuffer cb = begin();
    begin_pass(cb, &t, 1, 0, 0);
    VkClearAttachment clear = { .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, .colorAttachment = 0,
        .clearValue = { .color = { .float32 = { 0, 1, 0, 1 } } } };
    VkClearRect rect = { { { 16, 8 }, { 32, 16 } }, 0, 1 };
    vkCmdClearAttachments(cb, 1, &clear, 1, &rect);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    EXPECT(pixel_is(&out, 32, 16, 0, 255, 0, 0), "inside the rectangle: its color");
    EXPECT(pixel_is(&out, 32, 30, 255, 0, 0, 0), "below it: the pass's clear");
    EXPECT(pixel_is(&out, 8, 16, 255, 0, 0, 0), "left of it");
    target_free(&t);
    buffer_free(&out);
    return 0;
}

/**
 * vkcube's shaders (glslang's SPIR-V: a combined image sampler, arrays in a
 * uniform buffer, derivatives): a triangle over the target, white texture;
 * the light is dot(lightDir, normal) = 0.707 for a flat triangle facing
 * the viewer: 180 in alpha, and vkcube's gamma makes the color 219 (as
 * lavapipe draws it)
 */
static int test_vkcube_shaders(void)
{
    if(sizeof SPV_cube_vert < 20 || sizeof SPV_cube_frag < 20) { EXPECT(0, "no vkcube shaders in the build"); return 0; }
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Buffer ubo = buffer(64 + 36 * 16 * 2, 1), texel = buffer(4, 1), out = buffer(SIZE * SIZE * 4, 1);
    float *u = (float *)ubo.map;
    memset(u, 0, ubo.size);
    for(int i = 0; i < 4; i++) u[i * 5] = 1;
    const float corners[3][4] = { { -1, -1, 0.5f, 1 }, { 3, -1, 0.5f, 1 }, { -1, 3, 0.5f, 1 } };
    memcpy(u + 16, corners, sizeof corners);
    memset(texel.map, 255, 4);
    Image tex = image(VK_FORMAT_R8G8B8A8_UNORM, 1, 1, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    VkImageView view = view_of(&tex, VK_IMAGE_ASPECT_COLOR_BIT);
    VkSamplerCreateInfo sampler_info = { .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR, .minFilter = VK_FILTER_LINEAR,
        .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
        .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, .maxLod = 1 };
    VkSampler sampler;
    vkCreateSampler(device, &sampler_info, 0, &sampler);
    VkDescriptorSetLayoutBinding bindings[2] = {
        { 0, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_VERTEX_BIT, 0 },
        { 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, 0 },
    };
    VkDescriptorSetLayoutCreateInfo set_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 2, .pBindings = bindings };
    VkDescriptorSetLayout set_layout;
    vkCreateDescriptorSetLayout(device, &set_info, 0, &set_layout);
    VkPipelineLayoutCreateInfo layout_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &set_layout };
    VkPipelineLayout pipeline_layout;
    vkCreatePipelineLayout(device, &layout_info, 0, &pipeline_layout);
    VkShaderModule vs = shader(SPV_cube_vert, sizeof SPV_cube_vert), fs = shader(SPV_cube_frag, sizeof SPV_cube_frag);
    VkPipelineShaderStageCreateInfo stages[2] = {
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vs, .pName = "main" },
        { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = fs, .pName = "main" },
    };
    VkPipelineVertexInputStateCreateInfo vertex = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
    VkPipelineInputAssemblyStateCreateInfo assembly = { .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
        .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST };
    VkPipelineViewportStateCreateInfo viewport = { .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, .viewportCount = 1, .scissorCount = 1 };
    VkPipelineRasterizationStateCreateInfo raster = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, .lineWidth = 1 };
    VkPipelineMultisampleStateCreateInfo ms = { .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT };
    VkPipelineColorBlendAttachmentState attachment = { .colorWriteMask = 0xF };
    VkPipelineColorBlendStateCreateInfo blend = { .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, .attachmentCount = 1, .pAttachments = &attachment };
    VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
    VkPipelineDynamicStateCreateInfo dynamic = { .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, .dynamicStateCount = 2, .pDynamicStates = dynamic_states };
    VkGraphicsPipelineCreateInfo info = { .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2, .pStages = stages,
        .pVertexInputState = &vertex, .pInputAssemblyState = &assembly, .pViewportState = &viewport, .pRasterizationState = &raster,
        .pMultisampleState = &ms, .pColorBlendState = &blend, .pDynamicState = &dynamic, .layout = pipeline_layout, .renderPass = t.pass };
    VkPipeline pipeline;
    vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &info, 0, &pipeline);
    VkDescriptorPoolSize sizes[2] = { { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 }, { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 } };
    VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .maxSets = 1, .poolSizeCount = 2, .pPoolSizes = sizes };
    VkDescriptorPool dpool;
    vkCreateDescriptorPool(device, &pool_info, 0, &dpool);
    VkDescriptorSetAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = dpool, .descriptorSetCount = 1, .pSetLayouts = &set_layout };
    VkDescriptorSet set;
    vkAllocateDescriptorSets(device, &alloc, &set);
    VkDescriptorBufferInfo buffer_info = { ubo.buffer, 0, VK_WHOLE_SIZE };
    VkDescriptorImageInfo image_info = { .sampler = sampler, .imageView = view, .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
    VkWriteDescriptorSet writes[2] = {
        { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .dstBinding = 0, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, .pBufferInfo = &buffer_info },
        { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .dstBinding = 1, .descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, .pImageInfo = &image_info },
    };
    vkUpdateDescriptorSets(device, 2, writes, 0, 0);
    VkCommandBuffer cb = begin();
    layout(cb, tex.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 1, 1, 1 } };
    vkCmdCopyBufferToImage(cb, texel.buffer, tex.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
    layout(cb, tex.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
    begin_pass(cb, &t, 0, 0, 0);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, 1, &set, 0, 0);
    vkCmdDraw(cb, 3, 1, 0, 0);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    const uint8_t *c = pixel(&out, 32, 32);
    printf("VKTEST vkcube-shaders: center %d,%d,%d,%d\n", c[0], c[1], c[2], c[3]);
    EXPECT(pixel_is(&out, 32, 32, 219, 219, 219, 3) && near(c[3], 180, 3), "lit white: dot(lightDir, normal)");
    vkDestroyPipeline(device, pipeline, 0);
    vkDestroyDescriptorPool(device, dpool, 0);
    vkDestroyPipelineLayout(device, pipeline_layout, 0);
    vkDestroyDescriptorSetLayout(device, set_layout, 0);
    vkDestroyShaderModule(device, vs, 0);
    vkDestroyShaderModule(device, fs, 0);
    vkDestroySampler(device, sampler, 0);
    vkDestroyImageView(device, view, 0);
    image_free(&tex);
    target_free(&t);
    buffer_free(&ubo); buffer_free(&texel); buffer_free(&out);
    return 0;
}


/** draws flat.vert's rectangles with `p` into `t`, the pass begun with these contents */
static void begin_flat(VkCommandBuffer cb, Target *t, Pipeline *p, VkDescriptorSet set, Buffer *vb)
{
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p->pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, p->layout, 0, 1, &set, 0, 0);
    VkDeviceSize offset = 0;
    vkCmdBindVertexBuffers(cb, 0, 1, &vb->buffer, &offset);
    float push[4] = { 0, 0, 1, 0 };
    vkCmdPushConstants(cb, p->layout, VK_SHADER_STAGE_VERTEX_BIT, 0, 16, push);
    VkViewport viewport = { 0, 0, SIZE, SIZE, 0, 1 };
    VkRect2D scissor = { { 0, 0 }, { SIZE, SIZE } };
    vkCmdSetViewport(cb, 0, 1, &viewport);
    vkCmdSetScissor(cb, 0, 1, &scissor);
}

/**
 * Occlusion queries (the samples a draw covers: precise), timestamps, and
 * vkCmdCopyQueryPoolResults with availability
 */
static int test_queries(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 0);
    Buffer vb = buffer(12 * 28, 1), ubo = buffer(256, 1), copied = buffer(64, 1);
    // 32 x 32 pixels; then one off the target
    rectangle((float *)vb.map, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 1, 1, 1, 1);
    rectangle((float *)vb.map + 42, 2, 2, 3, 3, 0.5f, 1, 1, 1, 1);
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    memset(copied.map, 0xEE, 64);
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkQueryPoolCreateInfo occlusion_info = { .sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, .queryType = VK_QUERY_TYPE_OCCLUSION, .queryCount = 2 };
    VkQueryPoolCreateInfo time_info = { .sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO, .queryType = VK_QUERY_TYPE_TIMESTAMP, .queryCount = 2 };
    VkQueryPool occlusion, times;
    CHECK(vkCreateQueryPool(device, &occlusion_info, 0, &occlusion));
    CHECK(vkCreateQueryPool(device, &time_info, 0, &times));
    VkCommandBuffer cb = begin();
    vkCmdResetQueryPool(cb, occlusion, 0, 2);
    vkCmdResetQueryPool(cb, times, 0, 2);
    vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, times, 0);
    begin_pass(cb, &t, 0, 0, 0);
    begin_flat(cb, &t, &p, set, &vb);
    vkCmdBeginQuery(cb, occlusion, 0, VK_QUERY_CONTROL_PRECISE_BIT);
    vkCmdDraw(cb, 6, 1, 0, 0);
    vkCmdEndQuery(cb, occlusion, 0);
    vkCmdBeginQuery(cb, occlusion, 1, VK_QUERY_CONTROL_PRECISE_BIT);
    vkCmdDraw(cb, 6, 1, 6, 0);
    vkCmdEndQuery(cb, occlusion, 1);
    vkCmdEndRenderPass(cb);
    vkCmdWriteTimestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, times, 1);
    vkCmdCopyQueryPoolResults(cb, occlusion, 0, 2, copied.buffer, 0, 16, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT);
    vkCmdCopyQueryPoolResults(cb, occlusion, 0, 1, copied.buffer, 32, 8, VK_QUERY_RESULT_WAIT_BIT);
    CHECK(run(cb));
    uint64_t samples[2] = { 0 }, stamps[2] = { 0 };
    CHECK(vkGetQueryPoolResults(device, occlusion, 0, 2, sizeof samples, samples, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT));
    CHECK(vkGetQueryPoolResults(device, times, 0, 2, sizeof stamps, stamps, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT));
    printf("VKTEST queries: samples %llu %llu, timestamps %llu %llu\n", (unsigned long long)samples[0], (unsigned long long)samples[1],
        (unsigned long long)stamps[0], (unsigned long long)stamps[1]);
    // (without occlusionQueryPrecise, any number but 0 says samples passed)
    VkPhysicalDeviceFeatures features;
    vkGetPhysicalDeviceFeatures(physical, &features);
    EXPECT(features.occlusionQueryPrecise ? samples[0] == 32 * 32 : samples[0] > 0, "the rectangle's samples");
    EXPECT(samples[1] == 0, "none off the target");
    EXPECT(stamps[1] >= stamps[0] && stamps[0], "timestamps in order");
    const uint64_t *c = (const uint64_t *)copied.map;
    const uint32_t *c32 = (const uint32_t *)copied.map;
    EXPECT(c[0] == samples[0] && c[1] == 1 && c[2] == 0 && c[3] == 1, "copied: results and availability");
    EXPECT(c32[8] == samples[0] && c32[9] == 0xEEEEEEEE, "copied: 32 bits, nothing after");
    vkDestroyQueryPool(device, occlusion, 0);
    vkDestroyQueryPool(device, times, 0);
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    target_free(&t);
    buffer_free(&vb); buffer_free(&ubo); buffer_free(&copied);
    return 0;
}

/** a render pass whose draw is in a secondary command buffer */
static int test_secondary(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 0);
    Buffer vb = buffer(6 * 28, 1), ubo = buffer(256, 1), out = buffer(SIZE * SIZE * 4, 1);
    rectangle((float *)vb.map, 0, 0, 1, 1, 0.5f, 0, 1, 1, 1);
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkCommandBuffer secondary;
    VkCommandBufferAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, .commandPool = pool,
        .level = VK_COMMAND_BUFFER_LEVEL_SECONDARY, .commandBufferCount = 1 };
    CHECK(vkAllocateCommandBuffers(device, &alloc, &secondary));
    VkCommandBufferInheritanceInfo inheritance = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, .renderPass = t.pass,
        .subpass = 0, .framebuffer = t.framebuffer };
    VkCommandBufferBeginInfo begin_info = { .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
        .flags = VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT, .pInheritanceInfo = &inheritance };
    CHECK(vkBeginCommandBuffer(secondary, &begin_info));
    begin_flat(secondary, &t, &p, set, &vb);
    vkCmdDraw(secondary, 6, 1, 0, 0);
    CHECK(vkEndCommandBuffer(secondary));
    VkCommandBuffer cb = begin();
    VkClearValue clear = { .color = { .float32 = { 1, 0, 0, 1 } } };
    VkRenderPassBeginInfo info = { .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = t.pass, .framebuffer = t.framebuffer,
        .renderArea = { { 0, 0 }, { SIZE, SIZE } }, .clearValueCount = 1, .pClearValues = &clear };
    vkCmdBeginRenderPass(cb, &info, VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS);
    vkCmdExecuteCommands(cb, 1, &secondary);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    EXPECT(pixel_is(&out, 48, 48, 0, 255, 255, 0), "the secondary's rectangle");
    EXPECT(pixel_is(&out, 16, 16, 255, 0, 0, 0), "the pass's clear around it");
    vkFreeCommandBuffers(device, pool, 1, &secondary);
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    target_free(&t);
    buffer_free(&vb); buffer_free(&ubo); buffer_free(&out);
    return 0;
}

/** vkCmdDrawIndirect (two draws from one buffer) and vkCmdDrawIndexedIndirect */
static int test_indirect(void)
{
    Target t = target(0, 1, (VkClearColorValue){ 0 });
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 0);
    Buffer vb = buffer(18 * 28, 1), ubo = buffer(256, 1), ib = buffer(6 * 2, 1), args = buffer(64, 1), out = buffer(SIZE * SIZE * 4, 1);
    rectangle((float *)vb.map, -1, -1, 0, 0, 0.5f, 1, 0, 0, 1);
    rectangle((float *)vb.map + 42, 0, -1, 1, 0, 0.5f, 0, 1, 0, 1);
    rectangle((float *)vb.map + 84, -1, 0, 0, 1, 0.5f, 0, 0, 1, 1);
    const uint16_t indices[6] = { 0, 1, 2, 3, 4, 5 };
    memcpy(ib.map, indices, sizeof indices);
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    // two VkDrawIndirectCommand (stride 16), then a VkDrawIndexedIndirectCommand at 32 (vertex offset 12)
    uint32_t *a = (uint32_t *)args.map;
    const uint32_t draws[8] = { 6, 1, 0, 0, 6, 1, 6, 0 };
    memcpy(a, draws, sizeof draws);
    a[8] = 6; a[9] = 1; a[10] = 0; a[11] = 12; a[12] = 0;
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkCommandBuffer cb = begin();
    begin_pass(cb, &t, 0, 0, 0);
    begin_flat(cb, &t, &p, set, &vb);
    vkCmdDrawIndirect(cb, args.buffer, 0, 2, 16);
    vkCmdBindIndexBuffer(cb, ib.buffer, 0, VK_INDEX_TYPE_UINT16);
    vkCmdDrawIndexedIndirect(cb, args.buffer, 32, 1, 20);
    vkCmdEndRenderPass(cb);
    CHECK(run(cb));
    CHECK(read_target(&t, &out));
    EXPECT(pixel_is(&out, 16, 16, 255, 0, 0, 0), "the first indirect draw");
    EXPECT(pixel_is(&out, 48, 16, 0, 255, 0, 0), "the second one");
    EXPECT(pixel_is(&out, 16, 48, 0, 0, 255, 0), "the indexed one");
    EXPECT(pixel_is(&out, 48, 48, 0, 0, 0, 0), "nothing else");
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    target_free(&t);
    buffer_free(&vb); buffer_free(&ubo); buffer_free(&ib); buffer_free(&args); buffer_free(&out);
    return 0;
}

static void mip_layout(VkCommandBuffer cb, VkImage image, uint32_t mip, VkImageLayout from, VkImageLayout to)
{
    VkImageMemoryBarrier b = { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
        .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT, .oldLayout = from, .newLayout = to,
        .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = image,
        .subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, mip, 1, 0, 1 } };
    vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, 0, 0, 0, 1, &b);
}

/** a mip chain made by linear blits, mip by mip (as vkcube and most engines make theirs) */
static int test_mipmaps(void)
{
    Image img = image(VK_FORMAT_R8G8B8A8_UNORM, 8, 8, 4, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
    Buffer texels = buffer(8 * 8 * 4, 1), out = buffer(4 * 4 * 4, 1);
    // left half red, right half blue
    for(int y = 0; y < 8; y++)
        for(int x = 0; x < 8; x++)
        {
            uint8_t *t = texels.map + (y * 8 + x) * 4;
            t[0] = x < 4 ? 255 : 0; t[1] = 0; t[2] = x < 4 ? 0 : 255; t[3] = 255;
        }
    VkCommandBuffer cb = begin();
    layout(cb, img.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 8, 8, 1 } };
    vkCmdCopyBufferToImage(cb, texels.buffer, img.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy);
    for(uint32_t mip = 1; mip < 4; mip++)
    {
        mip_layout(cb, img.image, mip - 1, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
        int32_t from = 8 >> (mip - 1), to = 8 >> mip;
        VkImageBlit blit = { .srcSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, mip - 1, 0, 1 }, .srcOffsets = { { 0, 0, 0 }, { from, from, 1 } },
            .dstSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, mip, 0, 1 }, .dstOffsets = { { 0, 0, 0 }, { to, to, 1 } } };
        vkCmdBlitImage(cb, img.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, img.image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
    }
    mip_layout(cb, img.image, 3, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
    VkBufferImageCopy back[2] = {
        { .bufferOffset = 0, .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 1, 0, 1 }, .imageExtent = { 4, 4, 1 } },
        { .bufferOffset = 0, .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 3, 0, 1 }, .imageExtent = { 1, 1, 1 } },
    };
    vkCmdCopyImageToBuffer(cb, img.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, out.buffer, 1, &back[0]);
    CHECK(run(cb));
    const uint8_t *m1 = out.map;
    EXPECT(near(m1[0], 255, 1) && near(m1[2], 0, 1) && near(m1[12 + 2], 255, 1), "mip 1: still red and blue halves");
    cb = begin();
    vkCmdCopyImageToBuffer(cb, img.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, out.buffer, 1, &back[1]);
    CHECK(run(cb));
    printf("VKTEST mipmaps: mip 3 %d,%d,%d,%d\n", out.map[0], out.map[1], out.map[2], out.map[3]);
    EXPECT(near(out.map[0], 128, 2) && near(out.map[2], 128, 2) && out.map[3] == 255, "mip 3 (1x1): the average, purple");
    image_free(&img);
    buffer_free(&texels); buffer_free(&out);
    return 0;
}

/** a compute shader's imageStore into a storage image */
static int test_storage_image(void)
{
    Image img = image(VK_FORMAT_R8G8B8A8_UNORM, 16, 16, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
    VkImageView view = view_of(&img, VK_IMAGE_ASPECT_COLOR_BIT);
    Buffer out = buffer(16 * 16 * 4, 1);
    VkDescriptorSetLayoutBinding binding = { 0, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, 0 };
    VkDescriptorSetLayoutCreateInfo set_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, .bindingCount = 1, .pBindings = &binding };
    VkDescriptorSetLayout set_layout;
    vkCreateDescriptorSetLayout(device, &set_info, 0, &set_layout);
    VkPipelineLayoutCreateInfo layout_info = { .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1, .pSetLayouts = &set_layout };
    VkPipelineLayout pipeline_layout;
    vkCreatePipelineLayout(device, &layout_info, 0, &pipeline_layout);
    VkShaderModule cs = shader(SPV_store_comp, sizeof SPV_store_comp);
    VkComputePipelineCreateInfo info = { .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
        .stage = { .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = cs, .pName = "main" },
        .layout = pipeline_layout };
    VkPipeline pipeline;
    CHECK(vkCreateComputePipelines(device, VK_NULL_HANDLE, 1, &info, 0, &pipeline));
    VkDescriptorPoolSize size = { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 };
    VkDescriptorPoolCreateInfo pool_info = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, .maxSets = 1, .poolSizeCount = 1, .pPoolSizes = &size };
    VkDescriptorPool dpool;
    vkCreateDescriptorPool(device, &pool_info, 0, &dpool);
    VkDescriptorSetAllocateInfo alloc = { .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, .descriptorPool = dpool, .descriptorSetCount = 1, .pSetLayouts = &set_layout };
    VkDescriptorSet set;
    vkAllocateDescriptorSets(device, &alloc, &set);
    VkDescriptorImageInfo image_info = { .imageView = view, .imageLayout = VK_IMAGE_LAYOUT_GENERAL };
    VkWriteDescriptorSet write = { .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = set, .descriptorCount = 1,
        .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, .pImageInfo = &image_info };
    vkUpdateDescriptorSets(device, 1, &write, 0, 0);
    VkCommandBuffer cb = begin();
    layout(cb, img.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL);
    vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
    vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline_layout, 0, 1, &set, 0, 0);
    vkCmdDispatch(cb, 2, 2, 1);
    barrier(cb);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { 16, 16, 1 } };
    vkCmdCopyImageToBuffer(cb, img.image, VK_IMAGE_LAYOUT_GENERAL, out.buffer, 1, &copy);
    CHECK(run(cb));
    const uint8_t *px = out.map + (5 * 16 + 10) * 4;
    printf("VKTEST storage-image: (10, 5) %d,%d,%d,%d\n", px[0], px[1], px[2], px[3]);
    EXPECT(near(px[0], 170, 1) && near(px[1], 85, 1) && near(px[2], 128, 1) && px[3] == 255, "the stored color of (10, 5)");
    vkDestroyPipeline(device, pipeline, 0);
    vkDestroyDescriptorPool(device, dpool, 0);
    vkDestroyPipelineLayout(device, pipeline_layout, 0);
    vkDestroyDescriptorSetLayout(device, set_layout, 0);
    vkDestroyShaderModule(device, cs, 0);
    vkDestroyImageView(device, view, 0);
    image_free(&img);
    buffer_free(&out);
    return 0;
}


/** VK_KHR_dynamic_rendering: a clear and a draw into an image view, no render pass object */
static int test_dynamic_rendering(void)
{
    if(!dynamic_rendering) { EXPECT(0, "VK_KHR_dynamic_rendering is not offered"); return 0; }
    PFN_vkCmdBeginRenderingKHR begin_rendering = (PFN_vkCmdBeginRenderingKHR)vkGetDeviceProcAddr(device, "vkCmdBeginRenderingKHR");
    PFN_vkCmdEndRenderingKHR end_rendering = (PFN_vkCmdEndRenderingKHR)vkGetDeviceProcAddr(device, "vkCmdEndRenderingKHR");
    if(!begin_rendering || !end_rendering) { EXPECT(0, "no vkCmdBeginRenderingKHR"); return 0; }
    Image color = image(VK_FORMAT_R8G8B8A8_UNORM, SIZE, SIZE, 1, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
    VkImageView view = view_of(&color, VK_IMAGE_ASPECT_COLOR_BIT);
    Target t = { .samples = 1 };
    VkFormat format = VK_FORMAT_R8G8B8A8_UNORM;
    VkPipelineRenderingCreateInfo rendering = { .sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO, .colorAttachmentCount = 1,
        .pColorAttachmentFormats = &format };
    flat_next = &rendering;
    Pipeline p = flat_pipeline(&t, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, 0, 0);
    flat_next = 0;
    Buffer vb = buffer(6 * 28, 1), ubo = buffer(256, 1), out = buffer(SIZE * SIZE * 4, 1);
    rectangle((float *)vb.map, -1, -1, 0, 0, 0.5f, 1, 1, 0, 1);
    float tint[4] = { 1, 1, 1, 1 };
    memcpy(ubo.map, tint, sizeof tint);
    VkDescriptorPool dpool;
    VkDescriptorSet set = uniform_set(&p, &dpool, &ubo);
    VkCommandBuffer cb = begin();
    layout(cb, color.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
    VkRenderingAttachmentInfo attachment = { .sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO, .imageView = view,
        .imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
        .clearValue = { .color = { .float32 = { 0, 0, 1, 1 } } } };
    VkRenderingInfo info = { .sType = VK_STRUCTURE_TYPE_RENDERING_INFO, .renderArea = { { 0, 0 }, { SIZE, SIZE } }, .layerCount = 1,
        .colorAttachmentCount = 1, .pColorAttachments = &attachment };
    begin_rendering(cb, &info);
    begin_flat(cb, &t, &p, set, &vb);
    vkCmdDraw(cb, 6, 1, 0, 0);
    end_rendering(cb);
    layout(cb, color.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
    VkBufferImageCopy copy = { .imageSubresource = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, .imageExtent = { SIZE, SIZE, 1 } };
    vkCmdCopyImageToBuffer(cb, color.image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, out.buffer, 1, &copy);
    CHECK(run(cb));
    EXPECT(pixel_is(&out, 16, 16, 255, 255, 0, 0), "the rectangle");
    EXPECT(pixel_is(&out, 48, 48, 0, 0, 255, 0), "the clear");
    vkDestroyDescriptorPool(device, dpool, 0);
    pipeline_free(&p);
    vkDestroyImageView(device, view, 0);
    image_free(&color);
    buffer_free(&vb); buffer_free(&ubo); buffer_free(&out);
    return 0;
}

static const struct { const char *name; int (*run)(void); } TESTS[] = {
    { "buffer-copy", test_buffer_copy },
    { "fill-update", test_fill_update },
    { "image-roundtrip", test_image_roundtrip },
    { "image-mip-region", test_image_mip_region },
    { "clear-color", test_clear_color },
    { "clear-depth", test_clear_depth },
    { "copy-image", test_copy_image },
    { "blit", test_blit },
    { "resolve", test_resolve },
    { "fence", test_fence },
    { "timeline", test_timeline },
    { "semaphores", test_semaphores },
    { "events", test_events },
    { "remap", test_remap },
    { "draw", test_draw },
    { "depth", test_depth },
    { "blend-msaa", test_blend_msaa },
    { "texture", test_texture },
    { "compute", test_compute },
    { "clear-attachments", test_clear_attachments },
    { "vkcube-shaders", test_vkcube_shaders },
    { "queries", test_queries },
    { "secondary", test_secondary },
    { "indirect", test_indirect },
    { "mipmaps", test_mipmaps },
    { "storage-image", test_storage_image },
    { "dynamic-rendering", test_dynamic_rendering },
};

int main(int argc, char **argv, char **envp)
{
    // ("list": the tests' names, one a line, without a device)
    if(argc == 2 && !strcmp(argv[1], "list"))
    {
        for(unsigned i = 0; i < sizeof TESTS / sizeof TESTS[0]; i++) printf("%s\n", TESTS[i].name);
        return 0;
    }
    if(setup()) return 1;
    for(unsigned i = 0; i < sizeof TESTS / sizeof TESTS[0]; i++)
    {
        int wanted = argc < 2;
        for(int j = 1; j < argc; j++) wanted |= !strcmp(argv[j], TESTS[i].name);
        if(!wanted) continue;
        failure[0] = 0;
        printf("VKTEST start %s\n", TESTS[i].name);
        fflush(0);
        int error = TESTS[i].run();
        if(error || failure[0])
        {
            failures++;
            printf("VKTEST %s FAIL %s\n", TESTS[i].name, error ? "(an API call failed)" : failure);
        }
        else printf("VKTEST %s ok\n", TESTS[i].name);
        fflush(0);
    }
    printf("VKTEST done %d failures\n", failures);
    vkDestroyCommandPool(device, pool, 0);
    vkDestroyDevice(device, 0);
    vkDestroyInstance(instance, 0);
    return failures != 0;
}
                                                                                                                                                                                                                                                         source/v64/tests/x64/vktest_shaders/fill.comp                                                       0000644 0000000 0000000 00000000516 00000000000 016310  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
// each invocation writes index * 2 + base into the storage buffer
layout(local_size_x = 64) in;
layout(set = 0, binding = 0) buffer Out { uint values[]; } out_buffer;
layout(push_constant) uniform Push { uint base; } pc;
void main() {
    uint i = gl_GlobalInvocationID.x;
    out_buffer.values[i] = i * 2u + pc.base;
}
                                                                                                                                                                                  source/v64/tests/x64/vktest_shaders/flat.frag                                                       0000644 0000000 0000000 00000000205 00000000000 016264  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
layout(location = 0) in vec4 v_color;
layout(location = 0) out vec4 out_color;
void main() {
    out_color = v_color;
}
                                                                                                                                                                                                                                                                                                                                                                                           source/v64/tests/x64/vktest_shaders/flat.vert                                                       0000644 0000000 0000000 00000000775 00000000000 016341  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
// position (x, y, z) and color from vertex buffers; push constants move
// and scale; a uniform buffer tints
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 0) out vec4 v_color;
layout(push_constant) uniform Push { vec2 offset; float scale; float pad; } pc;
layout(set = 0, binding = 0) uniform Frame { vec4 tint; } frame;
void main() {
    v_color = color * frame.tint;
    gl_Position = vec4(position.xy * pc.scale + pc.offset, position.z, 1.0);
}
   source/v64/tests/x64/vktest_shaders/store.comp                                                      0000644 0000000 0000000 00000000533 00000000000 016515  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
// each invocation stores its position as a color into the storage image
layout(local_size_x = 8, local_size_y = 8) in;
layout(set = 0, binding = 0, rgba8) uniform writeonly image2D target;
void main() {
    ivec2 p = ivec2(gl_GlobalInvocationID.xy);
    imageStore(target, p, vec4(float(p.x) / 15.0, float(p.y) / 15.0, 0.5, 1.0));
}
                                                                                                                                                                     source/v64/tests/x64/vktest_shaders/textured.frag                                                   0000644 0000000 0000000 00000000613 00000000000 017205  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
// the texture, a separate sampler; a specialization constant scales
layout(location = 0) in vec2 v_uv;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 0) uniform texture2D tex;
layout(set = 0, binding = 1) uniform sampler smp;
layout(constant_id = 7) const float brightness = 1.0;
void main() {
    out_color = texture(sampler2D(tex, smp), v_uv) * brightness;
}
                                                                                                                     source/v64/tests/x64/vktest_shaders/textured.vert                                                   0000644 0000000 0000000 00000000436 00000000000 017251  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #version 450
// a full-target quad from the vertex index: its texture coordinates
layout(location = 0) out vec2 v_uv;
void main() {
    vec2 corner = vec2(float(gl_VertexIndex & 1), float(gl_VertexIndex >> 1));
    v_uv = corner;
    gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
}
                                                                                                                                                                                                                                  source/v64/tests/x64/windows_boot.mjs                                                               0000644 0000000 0000000 00000276012 00000000000 014707  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// Windows x64 qualification on a user-supplied disk (64-bit and WOW64 probes, topology).
// The image is opened read-only; every guest write stays in a RAM overlay.
// A FAT16 tools disk carries PROBE64.EXE (native) and PROBE32.EXE (WOW64,
// compatibility mode); after sign-in they run through Win+R and write their
// results next to themselves.
//
// Env: WIN_IMAGE, WIN_CORES (1), WIN_MEMORY_MB (2048), X64_JIT (1),
// X64_IR_TIER0, WIN_PARALLEL, WIN_USER_PASSWORD (the image's test account password),
// WIN_TIMEOUT_MS, WIN_OUT (output directory), WIN_STOP_AT_DESKTOP=1 (stop once
// the desktop shows after sign-in; for boot timing), WIN_CPU_PROFILE=<seconds>
// (host CPU profiles, one <out>/prof-<end>s.cpuprofile per window),
// WIN_OVERLAY_SAVE=<file> (after the desktop: a full shutdown, then the disk
// overlay, i.e. every sector the guest wrote, is saved), WIN_OVERLAY_LOAD=<file>
// (boot with such an overlay: the state after Windows installed the drivers
// for this machine; the image itself is never written), WIN_IDLE=1 (after the
// desktop: host and in-guest CPU load of the idle desktop, see host_window),
// WIN_CPULOAD32=<rounds> (after the desktop: the timed WOW64 workload
// tests/x64/windows_cpuload32.c as LOAD32.EXE, an X64_WIN_CPULOAD32 line with
// each round's time; docs/jit-unification-plan.md P0.12). While it runs, a line written to
// <out>/command.txt is executed: "key <scancodes hex>", "type <text>",
// "run <command line>", "enter", "space", "password", "shot", "rips",
// "diag" (each core's registers and last faults), "mem <core> <linear
// address, hex> <bytes>" (guest memory through that core's CR3),
// "trace on|off" (WIN_USER_TRACE=1 enables it from the start), "jitstats
// <phase>" (a JIT_STATS record, tools/bench/jit_stats.mjs, named <phase>;
// with JIT_STATS=1 the harness also writes one at the desktop and one at
// the end, phases "desktop" and "end"), "runadmin
// <cmd /c line>" (elevated through PowerShell, Alt+Y for UAC), "wait <s>",
// "launch <command line>" (run by the launcher with cmd /c, see WIN_LAUNCHER),
// "display <width> <height> [index]" (V86.set_display_size), "mouse <dx> <dy>",
// "nudge <dx> <dy> <n>" (n PS/2 movements; Windows' pointer ballistics
// depend on each packet's size, so a fixed recipe lands at the same place:
// "corner", the pointer into the top left corner, then nudges), "click
// [right]", "pointer <x> <y> <screen width> <screen height>",
// "snapshot" (saved
// and restored in place),
// "svgalog on|off" (the SVGA3D commands other than DX and the frequent GB
// ones, with their first words, as "svga3d-command" events; "svgalog
// 1101,1267" logs only those command ids), "svgashaders"
// (the GB shaders' bytecode, as "svga3d-shader" events).
// WIN_GRAPHICS_ADAPTER: the display adapter (bochs_vga; virtio_gpu; vmware_svga, whose
// level WIN_SVGA_LEVEL pins; WIN_GPU_RENDERER=chrome gives it a 3D renderer, in
// a headless Chrome, and the device its highest level, dx11);
// WIN_CDROM=<iso>: a CD-ROM, e.g. with drivers to install; WIN_HDB=<image>: a
// second disk in place of the tools disk, read-only like the first.
// WIN_LAUNCHER=<guest path of LAUNCH.EXE>: started from the Run dialog once
// the desktop shows; then "launch" runs programs as the user without typing
// (WIN_LAUNCHER_ADMIN=1: elevated, through UAC once, so they are too).
// WIN_NO_PROBE=1: no qualification probe (its Run dialog takes the focus from
// full-screen programs), and no signing in again unless a password box shows.
// WIN_CPU_FEATURES=<features>: cpu_features (cpu_type x86_64; "default": its
// default, every feature; "none": none), e.g. the
// x86-64-v3 set; the probes then check the YMM state (X64_WIN_AVX, see
// windows_probe.c); WIN_PROBE_SNAPSHOT=1: the machine saved and restored in
// place once each probe's AVX part has started.
// "savestate <file>": the machine saved to <file>.state, with what the guest
// wrote to its disks (<file>.hda.ovl, <file>.hdb.ovl) and the harness's own
// (<file>.json); WIN_STATE_LOAD=<file> starts from there instead of booting
// (same WIN_* machine settings; the session is signed in, the launcher runs).
// WIN_RATES=<s>: every <s> seconds, the SVGA3D commands per second
// ("svga3d-rates": presents among them, for frame rates).
// WIN_MACHINE=q35: the Q35 machine (AHCI; a Windows installed on IDE may need
// its storahci driver enabled first, see docs/ahci.md), with WIN_HPET=1 the
// HPET, WIN_ROOT_PORTS=<n> PCI Express root ports, WIN_SMBUS=1 the SMBus.
// WIN_PCIE_DEVICE=<port>: a virtio device (Windows 8.1 has no driver for it)
// behind that root port, its hot plug slot empty at boot; "pcieattach <port>"
// plugs it in, "pciedetach <port> [surprise]" takes it out (by the attention
// button: "pcie-detached" once the guest switched the slot and its power
// indicator off), "pcieslot <port>" reports the slot's registers;
// WIN_PCIE_TRACE=1: every slot control write of the guest and every slot
// event, as "pcie-sltctl" and "pcie-event". WIN_PCIE_AHCI=<port>: instead, a
// second AHCI controller (Windows has its driver) with a 16 MiB FAT16 disk,
// in that root port's slot from boot; WIN_AHCI_TRACE=1: its global and port
// control writes and its configuration writes, as "ahci-write", "ahci-config".
// WIN_NIC=<net_device.type>: the network card (ne2k; e1000, which Windows 8.1
// drives with nete1g3e.inf). WIN_NET=1: connected to the fetch backend's
// network (DHCP, DNS; its HTTP requests answered with 404 here, nothing leaves
// the machine) with tests/devices/tcp_endpoint.mjs at 192.168.86.1:5000
// serving 16 MiB of a pattern; the tools disk then has NIC.CMD, which writes
// the card's device and driver, the DHCP address and an HTTP download's MD5
// to NIC.TXT ("file NIC.TXT" prints it, X64_WIN_NIC_MD5 is the pattern's).
// "file <name>": a file of the tools disk, as an X64_WIN_FILE line.
// WIN_AUDIO=<audio_device>: the sound card (sb16; hd_audio, which Windows
// drives with hdaudbus.inf and hdaudio.inf); with hd_audio the tools disk has
// SND.CMD, which writes the controller's and codec's devices, the audio
// endpoints and the time of playing Windows' longest Media WAV to SND.TXT,
// and "audio" prints what the controller played (X64_WIN_AUDIO: bytes,
// formats, how many samples were not silent).
// WIN_USB=1: USB (a UHCI controller with the HID tablet; WIN_USB=ehci: EHCI
// with its UHCI companions; xhci: xHCI); the tools disk has
// USB.CMD, which writes the controller's, its root hub's, the tablet's and
// its HID mouse's devices to USB.TXT and then the cursor's position every
// 300 ms (tests/x64/windows_usb.c); "pointergrid" walks the page's pointer
// through the corners, the centre and a 5x5 grid of the 1024x768 screen,
// 2.5 s at each (X64_WIN_POINTER lines), then to (3, 5), where the logging
// stops. WIN_USB_DISK=1: a USB disk too (a FAT16 image in memory with
// USBDISK.TXT); USBCHECK.EXE reads that file and writes FROMWIN.TXT, which
// "usbdiskfile <name>" prints from the image (X64_WIN_USB_DISK_FILE).
// WIN_USB_TRACE=1: each report the tablet gives the guest (X64_WIN_TABLET_REPORT).
// WIN_TPM=1: a TPM 2.0 (docs/tpm.md); USB.CMD lists its device (ACPI\MSFT0101) too.
// WIN_TPM_TRACE=1: each command the guest sends the TPM, its response code and
// how long it took (X64_WIN_TPM).
// "waitfile <name> <text> [seconds]": until a file of the tools disk has the
// text (USB.CMD writes READY once it logs the cursor, END when done).
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import {createHash as create_hash} from "node:crypto";
import {deflateSync as deflate_sync} from "node:zlib";
import {spawnSync} from "node:child_process";
import {setTimeout as delay} from "node:timers/promises";
import {fileURLToPath} from "node:url";
import {MemoryDisk, ReadOnlyOverlayDisk, make_fat16, read_fat16} from "../smp/disk_fixture.mjs";
import {jit_switches_from_env} from "../lib/jit_switches.mjs";
import {jit_stats_enabled, print_jit_stats} from "../../tools/bench/jit_stats.mjs";
import {CPU_FEATURES, CPU_FEATURE_PRESETS} from "../../src/cpu_features.js";
import {site_directory} from "../lib/site.mjs";
import {tcp_endpoint} from "../devices/tcp_endpoint.mjs";
import {STATE_OFFSETS} from "../../src/state_layout.js";
// WIN_CPU_FEATURES: feature names, comma separated, or a preset ("x86-64-v3")
// (default: cpu_type x86_64 without cpu_features, every released feature;
// none: x86_64 with none)
const win_cpu_features_default = process.env.WIN_CPU_FEATURES === "default";
const win_cpu_features = win_cpu_features_default ?
    Object.keys(CPU_FEATURES).filter(name => CPU_FEATURES[name]["released"] && CPU_FEATURES[name]["profiles"].includes("x86_64")) :
    process.env.WIN_CPU_FEATURES === "none" ? [] : process.env.WIN_CPU_FEATURES ?
        CPU_FEATURE_PRESETS[process.env.WIN_CPU_FEATURES] || process.env.WIN_CPU_FEATURES.split(",") : null;

const root = fileURLToPath(new URL("../../", import.meta.url));
// (the default: retro-gaming-site next to the main checkout, also from a worktree)
const image_path = path.resolve(process.env.WIN_IMAGE || path.join(site_directory(root), "windows8/windows8.img"));
const out = path.resolve(process.env.WIN_OUT || path.join(root, "build/x64-windows"));
fs.mkdirSync(out, {recursive: true});
const cores = +(process.env.WIN_CORES || 1), jit = process.env.X64_JIT !== "0";
const password = process.env.WIN_USER_PASSWORD || "admin1";
// (not `<< 20`: 2048 << 20 overflows int32; v86 caps RAM just below 2 GiB)
const memory_mb = +(process.env.WIN_MEMORY_MB || 2048);
const source_stat = fs.statSync(image_path);

function build(compiler, entry, output, source = "tests/x64/windows_probe.c", libraries = [])
{
    const result = spawnSync(compiler, ["-Os", "-nostdlib", "-fno-builtin", "-fno-stack-protector", "-mno-stack-arg-probe",
        `-Wl,--entry,${entry}`, "-Wl,--subsystem,console", "-o", output, path.join(root, source), "-lkernel32", ...libraries], {encoding: "utf8"});
    assert.equal(result.status, 0, result.stderr);
    return fs.readFileSync(output);
}
const probe64 = build("x86_64-w64-mingw32-gcc", "entry", path.join(out, "PROBE64.EXE"));
const probe32 = build("i686-w64-mingw32-gcc", "_entry@0", path.join(out, "PROBE32.EXE"));
const cpuload = build("x86_64-w64-mingw32-gcc", "entry", path.join(out, "CPULOAD.EXE"), "tests/x64/windows_cpuload.c");
const cpuload32 = build("i686-w64-mingw32-gcc", "_entry@0", path.join(out, "LOAD32.EXE"), "tests/x64/windows_cpuload32.c");
// WIN_NET: what NIC.CMD checks, and the download it makes
const nic_pattern = new Uint8Array(16 << 20);
for(let i = 0; i < nic_pattern.length; i++) nic_pattern[i] = (i * 2654435761 >>> 24) ^ i >>> 12;
const nic_script = [
    "$ErrorActionPreference = 'Continue'",
    "Get-WmiObject Win32_PnPEntity | Where-Object { $_.DeviceID -like 'PCI\\VEN_8086&DEV_100E*' } | ForEach-Object {",
    "    'DEVICE ' + $_.DeviceID + ' | ' + $_.Name + ' | error=' + $_.ConfigManagerErrorCode + ' | service=' + $_.Service }",
    "Get-WmiObject Win32_PnPSignedDriver | Where-Object { $_.DeviceID -like 'PCI\\VEN_8086&DEV_100E*' } | ForEach-Object {",
    "    'DRIVER inf=' + $_.InfName + ' version=' + $_.DriverVersion + ' provider=' + $_.DriverProviderName }",
    "for($i = 0; $i -lt 90; $i++) {",
    "    $a = @(Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -and ($_.IPAddress -like '192.168.86.*') })",
    "    if($a.Count) { break }; Start-Sleep 2 }",
    "$a | ForEach-Object { 'IP ' + ($_.IPAddress -join ',') + ' dhcp=' + $_.DHCPEnabled + ' server=' + $_.DHCPServer +",
    "    ' gateway=' + ($_.DefaultIPGateway -join ',') + ' mac=' + $_.MACAddress }",
    "$file = Join-Path $env:TEMP 'pattern.bin'",
    "try {",
    "    $t = Get-Date",
    "    (New-Object Net.WebClient).DownloadFile('http://192.168.86.1:5000/pattern', $file)",
    "    $s = ((Get-Date) - $t).TotalSeconds",
    "    'HTTP md5=' + (Get-FileHash -Algorithm MD5 $file).Hash.ToLower() + ' bytes=' + (Get-Item $file).Length + ' seconds=' + $s",
    "} catch { 'HTTP error ' + $_ }",
].join("\r\n") + "\r\n";
// WIN_AUDIO=hd_audio: what SND.CMD checks
const snd_script = [
    "$ErrorActionPreference = 'Continue'",
    "Get-WmiObject Win32_PnPEntity | Where-Object { $_.DeviceID -like 'PCI\\VEN_8086&DEV_2668*' -or $_.DeviceID -like 'PCI\\VEN_8086&DEV_293E*' -or",
    "    $_.DeviceID -like 'HDAUDIO\\*' } | ForEach-Object {",
    "    'DEVICE ' + $_.DeviceID + ' | ' + $_.Name + ' | error=' + $_.ConfigManagerErrorCode + ' | service=' + $_.Service }",
    "Get-WmiObject Win32_PnPEntity | Where-Object { $_.DeviceID -like 'SWD\\MMDEVAPI\\*' } | ForEach-Object {",
    "    'ENDPOINT ' + $_.Name + ' | error=' + $_.ConfigManagerErrorCode }",
    "Get-Service Audiosrv | ForEach-Object { 'SERVICE ' + $_.Name + ' ' + $_.Status }",
    "Get-WmiObject Win32_PnPSignedDriver | Where-Object { $_.DeviceID -like 'HDAUDIO\\*' -or $_.DeviceID -like 'PCI\\VEN_8086&DEV_2668*' -or",
    "    $_.DeviceID -like 'PCI\\VEN_8086&DEV_293E*' } | ForEach-Object { 'DRIVER inf=' + $_.InfName + ' version=' + $_.DriverVersion + ' device=' + $_.DeviceName }",
    "$wav = Get-ChildItem (Join-Path $env:windir 'Media') -Filter *.wav | Sort-Object Length -Descending | Select-Object -First 1",
    "try {",
    "    $t = Get-Date",
    "    (New-Object Media.SoundPlayer $wav.FullName).PlaySync()",
    "    'PLAYED ' + $wav.Name + ' bytes=' + $wav.Length + ' seconds=' + ((Get-Date) - $t).TotalSeconds",
    "} catch { 'PLAY error ' + $_ }",
].join("\r\n") + "\r\n";
const snd_cmd = "@echo off\r\nset OUT=%~d0\\SND.TXT\r\necho BEGIN> %OUT%\r\n" +
    "powershell -NoProfile -ExecutionPolicy Bypass -File %~d0\\SND.PS1 >> %OUT% 2>&1\r\necho END>> %OUT%\r\n";
// WIN_USB: what USB.CMD checks (tests/x64/windows_usb.c)
const usb_check = process.env.WIN_USB && build("i686-w64-mingw32-gcc", "_entry@0", path.join(out, "USBCHECK.EXE"), "tests/x64/windows_usb.c",
    ["-luser32", "-lsetupapi", "-lcfgmgr32"]);
const usb_cmd = "@echo off\r\nstart %~d0\\USBCHECK.EXE\r\n";
// WIN_USB_DISK: the USB disk's image (another disk signature and volume
// serial than the tools disk's)
const usb_disk = process.env.WIN_USB_DISK ? make_fat16({"USBDISK.TXT": Buffer.from("v86 USB disk check\r\n")}) : null;
if(usb_disk)
{
    new DataView(usb_disk.buffer).setUint32(440, 0x5B2026C3, true);
    new DataView(usb_disk.buffer).setUint32(63 * 512 + 39, 0x5B2026C3, true);
}
const nic_cmd = "@echo off\r\nset OUT=%~d0\\NIC.TXT\r\necho BEGIN> %OUT%\r\n" +
    "powershell -NoProfile -ExecutionPolicy Bypass -File %~d0\\NIC.PS1 >> %OUT% 2>&1\r\necho END>> %OUT%\r\n";
const tools = new MemoryDisk(make_fat16({"PROBE64.EXE": probe64, "PROBE32.EXE": probe32, "CPULOAD.EXE": cpuload, "LOAD32.EXE": cpuload32,
    ...(process.env.WIN_NET ? {"NIC.CMD": Buffer.from(nic_cmd), "NIC.PS1": Buffer.from(nic_script)} : {}),
    ...(process.env.WIN_AUDIO === "hd_audio" ? {"SND.CMD": Buffer.from(snd_cmd), "SND.PS1": Buffer.from(snd_script)} : {}),
    ...(process.env.WIN_USB ? {"USB.CMD": Buffer.from(usb_cmd), "USBCHECK.EXE": usb_check} : {})}));
const source = new ReadOnlyOverlayDisk(image_path);
// WIN_HDB=<image>: that disk (e.g. retro-gaming-site/game/3dmark06.img) in
// place of the tools disk, never written either (its writes stay in memory)
const hdb_path = process.env.WIN_HDB && path.resolve(process.env.WIN_HDB);
const hdb_stat = hdb_path && fs.statSync(hdb_path);
const hdb = hdb_path ? new ReadOnlyOverlayDisk(hdb_path) : tools;
// Overlay file: "V86OVL1\0", image size (u64), sector count (u32), the
// sector numbers (u32 each), then their contents
function load_overlay(disk, filename)
{
    const file = fs.readFileSync(filename);
    assert.equal(file.toString("latin1", 0, 8), "V86OVL1\0", "overlay file");
    assert.equal(Number(file.readBigUInt64LE(8)), disk.byteLength, "overlay of this image");
    const count = file.readUInt32LE(16);
    const sectors = new Uint32Array(file.buffer.slice(file.byteOffset + 20, file.byteOffset + 20 + count * 4));
    const bytes = new Uint8Array(file.buffer, file.byteOffset + 20 + count * 4, count * 512);
    disk.set_state([1, disk.byteLength, sectors, bytes]);
}
const state_load = process.env.WIN_STATE_LOAD && path.resolve(process.env.WIN_STATE_LOAD);
if(state_load) load_overlay(source, state_load + ".hda.ovl");
else if(process.env.WIN_OVERLAY_LOAD) load_overlay(source, process.env.WIN_OVERLAY_LOAD);
if(state_load && hdb_path && fs.existsSync(state_load + ".hdb.ovl")) load_overlay(hdb, state_load + ".hdb.ovl");
function save_overlay(filename, disk = source)
{
    const [, size, sectors, bytes] = disk.get_state();
    const header = Buffer.alloc(20);
    header.write("V86OVL1\0", 0, "latin1");
    header.writeBigUInt64LE(BigInt(size), 8);
    header.writeUInt32LE(sectors.length, 16);
    fs.writeFileSync(filename, Buffer.concat([header, Buffer.from(sectors.buffer, sectors.byteOffset, sectors.byteLength), Buffer.from(bytes)]));
}

const {V86} = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
// WIN_PCIE_AHCI's disk: FAT16 like the tools disk, with a disk signature of
// its own (Windows takes a disk whose signature collides with another offline)
function hot_plug_disk()
{
    const bytes = make_fat16({"HOTPLUG.TXT": Buffer.from("v86 PCI Express hot plug\r\n")});
    new DataView(bytes.buffer).setUint32(440, 0x76386870, true);
    return bytes;
}
// WIN_GPU_RENDERER=chrome: vmware_svga's 3D drawn by a headless Chrome (the default level, dx11-full)
const remote_renderer = process.env.WIN_GPU_RENDERER === "chrome" ?
    await (await import("./gpu_remote_renderer.mjs")).create_remote_renderer() : null;
const vm = new V86({
    graphics_adapter: process.env.WIN_GRAPHICS_ADAPTER || "bochs_vga",
    // WIN_SVGA_LEVEL: pin what vmware_svga declares (2d, 2d-full, ...)
    ...(process.env.WIN_SVGA_LEVEL || remote_renderer ? {graphics_adapter_test: {level: process.env.WIN_SVGA_LEVEL || undefined,
        renderer: remote_renderer && remote_renderer.renderer}} : {}),
    wasm_path: process.env.WASM_PATH,
    ...(process.env.WIN_CDROM ? {cdrom: {url: path.resolve(process.env.WIN_CDROM)}} : {}),
    bios: {url: root + "bios/seabios.bin"}, vga_bios: {url: root + "bios/vgabios.bin"},
    hda: source, hdb, memory_size: memory_mb * 1048576, vram_size: 16 << 20,
    acpi: true, cpu_cores: cores, autostart: false, log_level: 0,
    net_device: {type: process.env.WIN_NIC || "ne2k", ...(process.env.WIN_NET ? {relay_url: "fetch"} : {})},
    ...(process.env.WIN_AUDIO ? {audio_device: process.env.WIN_AUDIO} : {}),
    // (WIN_USB=ehci: EHCI with its companions; xhci)
    ...(process.env.WIN_USB ? {usb: {controller: ["ehci", "xhci"].includes(process.env.WIN_USB) ? process.env.WIN_USB : "uhci", tablet: true,
        ...(usb_disk ? {mass_storage: [{id: "stick", image: {buffer: usb_disk.buffer}}]} : {})}} : {}),
    ...(process.env.WIN_TPM ? {tpm: {version: "2.0"}} : {}),
    // WIN_QEMU_COMPATIBLE=1: devices where QEMU, which the image was installed with, had them
    qemu_compatible: !!+process.env.WIN_QEMU_COMPATIBLE,
    // JIT_SWITCHES (tests/lib/jit_switches.mjs)
    ...(Object.keys(jit_switches_from_env()).length ? {jit_switches: jit_switches_from_env()} : {}),
    ...(process.env.WIN_MACHINE ? {machine_type: process.env.WIN_MACHINE, hpet: !!+process.env.WIN_HPET,
        pcie_root_ports: +process.env.WIN_ROOT_PORTS || 0, smbus: !!+process.env.WIN_SMBUS} : {}),
    ...(process.env.WIN_PCIE_DEVICE ? {virtio_devices: [{"name": "hotplug", "device_id": 0x1044, "subsystem_device_id": 4,
        "queues": [{"size": 8}], "pcie_root_port": +process.env.WIN_PCIE_DEVICE, "pcie_plugged": false, "notify": () => {}}]} : {}),
    // (behind root port n is the bus that pci_ids number n + 1)
    ...(process.env.WIN_PCIE_AHCI ? {ahci_test_drives: [{buffer: new MemoryDisk(hot_plug_disk())}], ahci_test_pci_id: +process.env.WIN_PCIE_AHCI + 1 << 8} : {}),
    // WIN_QUANTUM: instructions per core slice when cores take turns
    ...(process.env.WIN_QUANTUM ? {cpu_quantum: +process.env.WIN_QUANTUM} : {}),
    // WIN_ASYNC_PUBLICATION=1: compile generated modules asynchronously, as
    // the browser does by default
    disable_jit: !jit, experimental_smp_jit: jit, ir_sync_publication: !+process.env.WIN_ASYNC_PUBLICATION,
    ...(process.env.X64_IR_TIER0 === "0" ? {ir_tier0: false} : {}),
    ...(win_cpu_features ? {cpu_type: "x86_64", ...(win_cpu_features_default ? {} : {cpu_features: win_cpu_features})} : {}),
    // WIN_PARALLEL=1: the application processors run in vCPU workers
    // (WIN_PARALLEL_WASM: another build of it)
    ...(+process.env.WIN_PARALLEL ? {parallel: true, wasm_path: process.env.WIN_PARALLEL_WASM || root + "build/v86-parallel.wasm"} : {}),
});

// Rolling host profiles of this process (node:inspector), so that each boot
// phase can be read separately
let profiler = null;
if(+process.env.WIN_CPU_PROFILE)
{
    const inspector = await import("node:inspector/promises");
    profiler = new inspector.Session();
    profiler.connect();
    await profiler.post("Profiler.enable");
    await profiler.post("Profiler.setSamplingInterval", {interval: 2000});
    await profiler.post("Profiler.start");
}
async function profile_window()
{
    const {profile} = await profiler.post("Profiler.stop");
    fs.writeFileSync(path.join(out, `prof-${String(elapsed()).padStart(4, "0")}s.cpuprofile`), JSON.stringify(profile));
    await profiler.post("Profiler.start");
    // page functions are named x64_page_<linear page>: name the guest module
    // of each (<out>/modules.json, for offline profiles by guest module)
    // (compatibility-mode code too since M9; t0_<linear page> was IR
    // Tier-0's, before P7.5)
    if(!cpu) return;
    const self = new Map(), by_id = new Map(profile.nodes.map(node => [node.id, node]));
    let total = 0;
    profile.samples.forEach((id, i) => {
        const d = profile.timeDeltas[i] || 0, name = by_id.get(id).callFrame.functionName;
        total += d;
        const match = name.match(/^(?:x64_page_|t0_)([0-9a-f]+)$/);
        if(match) self.set(match[1], (self.get(match[1]) || 0) + d);
    });
    const limit = performance.now() + 2000;
    for(const [page] of [...self].sort((a, b) => b[1] - a[1]))
    {
        if(page_modules[page] === undefined && performance.now() < limit) page_modules[page] = guest_module(BigInt("0x" + page));
    }
    fs.writeFileSync(path.join(out, "modules.json"), JSON.stringify(page_modules, null, 1));
    // the generated code's time by guest module (% of the window)
    const modules = new Map();
    for(const [page, t] of self)
    {
        const m = page_modules[page], name = m ? m.replace(/\+0x[0-9a-f]+$/, "") : BigInt("0x" + page) >= 0xFFFF800000000000n ? "kernel ?" : "user ?";
        modules.set(name, (modules.get(name) || 0) + t);
    }
    console.log("X64_WIN_PROFILE_MODULES " + JSON.stringify([...modules].sort((a, b) => b[1] - a[1]).slice(0, 20)
        .map(([name, t]) => [name, +(100 * t / total).toFixed(2)])));
}
// (the most recent address spaces first)
const page_modules = {}, seen_cr3 = new Set(), module_headers = new Map();
// The PE image containing a linear address, as "name+0xoffset": scan down to
// its MZ header, name it by the PDB of its CodeView debug entry (or its
// export name); user addresses under each address space seen so far
function guest_module(address)
{
    const spaces = [current_cr3(), ...[...seen_cr3].reverse().slice(0, 16)];
    for(const cr3 of address >= 0xFFFF800000000000n ? spaces.slice(0, 1) : spaces)
    {
        const u8 = va => { const at = physical(cr3, va); return at === null ? null : cpu.mem8[at]; };
        // (a cached header scan: the image base of the page, or none)
        const cached = module_headers.get(cr3 + ":" + address.toString(16));
        if(cached === null) continue;
        const u16 = va => { const a = u8(va), b = u8(va + 1n); return a === null || b === null ? null : a | b << 8; };
        const u32 = va => { const a = u16(va), b = u16(va + 2n); return a === null || b === null ? null : (a | b << 16) >>> 0; };
        const string = va => { let text = ""; for(let c; text.length < 64 && (c = u8(va)) && c >= 32 && c < 127; va++) text += String.fromCharCode(c); return text; };
        for(let page = address & ~0xFFFn, n = 0; n < 4096; n++, page -= 0x1000n)
        {
            if(u16(page) !== 0x5A4D) continue;
            const pe = page + BigInt(u32(page + 0x3Cn) ?? 0);
            if(u32(pe) !== 0x4550) continue;
            const optional = pe + 24n, wide = u16(optional) === 0x20B;
            if(address - page >= BigInt(u32(optional + 56n) ?? 0)) break;
            const directories = optional + (wide ? 112n : 96n);
            let name = "";
            const debug = u32(directories + 6n * 8n), debug_size = u32(directories + 6n * 8n + 4n);
            for(let i = 0; debug && i < debug_size / 28 && !name; i++)
            {
                const entry = page + BigInt(debug) + BigInt(i * 28);
                const data = u32(entry + 20n);
                if(u32(entry + 12n) === 2 && data && u32(page + BigInt(data)) === 0x53445352)
                    name = string(page + BigInt(data) + 24n).split("\\").pop().replace(/\.pdb$/i, "");
            }
            const exports = u32(directories);
            if(!name && exports) name = string(page + BigInt(u32(page + BigInt(exports) + 12n) ?? 0));
            return (name || "0x" + page.toString(16)) + "+0x" + (address - page).toString(16);
        }
        module_headers.set(cr3 + ":" + address.toString(16), null);
    }
    return null;
}
function current_cr3()
{
    return BigInt(cpu.cr[3] >>> 0) & ~0xFFFn | BigInt(new Uint32Array(cpu.wasm_memory.buffer, 1612, 1)[0]) << 32n;
}
const started = performance.now();
const elapsed = () => Math.round((performance.now() - started) / 1000);
let powered_off = null;
vm.add_listener("acpi-power-off", state => { powered_off = state; });
// the guest drivers' logs through the VMware backdoor (vm3d's release log)
vm.add_listener("vmware-log", text => event("guest-log", {text: String(text).slice(0, 400)}));
vm.add_listener("vmware-rpci", text => {
    // (the launcher asks once a second)
    if(String(text) !== "info-get guestinfo.v86.run") event("rpci", {text: String(text).slice(0, 200)});
});
// the launcher (tools/windows/launch.c) in the user's session, once it said so
let launcher_ready = false, launch_serial = 0;
vm.add_listener("vmware-log", text => { if(String(text) === "launch: ready") launcher_ready = true; });
const backdoor_seen = new Set();
vm.add_listener("vmware-backdoor-unknown", command => { if(!backdoor_seen.has(command)) { backdoor_seen.add(command); event("backdoor-unknown", {command}); } });
const report = {image: {path: image_path, size: source_stat.size, mtime_ms: source_stat.mtimeMs}, cores, jit,
    parallel: !!+process.env.WIN_PARALLEL, memory_mb, modes: [], events: [], results: {}};
const event = (kind, detail = {}) => { const e = {s: elapsed(), kind, ...detail}; report.events.push(e); console.log("X64_WIN_EVENT " + JSON.stringify(e)); };
let cpu, graphics_since = 0, last_mode = null, execution_error;
vm.add_listener("screen-set-size", size => {
    report.modes.push({s: elapsed(), size});
    last_mode = size; graphics_since = performance.now();
    event("mode", {size});
});

// Set 1 scan codes
const scans = {};
for(const [letters, codes] of [["1234567890", [2,3,4,5,6,7,8,9,10,11]], ["qwertyuiop", [16,17,18,19,20,21,22,23,24,25]],
    ["asdfghjkl", [30,31,32,33,34,35,36,37,38]], ["zxcvbnm", [44,45,46,47,48,49,50]]])
    [...letters].forEach((letter, i) => { scans[letter] = codes[i]; });
Object.assign(scans, {" ": 57, ".": 52, "/": 53, "\\": 43, "-": 12, ";": 39, "=": 13, ",": 51, "'": 40});
const shifted = {":": 39, "%": 6, "(": 10, ")": 11, "@": 3, "&": 8, "\"": 40, ">": 52, "<": 51, "_": 12, "|": 43};
async function type(text)
{
    for(const ch of text)
    {
        const upper = ch >= "A" && ch <= "Z";
        const code = shifted[ch] || scans[ch.toLowerCase()];
        assert.ok(code, `scan code for ${JSON.stringify(ch)}`);
        const shift = upper || shifted[ch];
        await vm.keyboard_send_scancodes(shift ? [42, code, code | 128, 170] : [code, code | 128], 30);
        await delay(40);
    }
}
const press = async codes => { await vm.keyboard_send_scancodes(codes, 30); await delay(100); };
const enter = () => press([28, 156]);
// The sign-in screen of this image at 1024x768: the password box is a white
// field right of the user tile. Keys pressed before it appears are lost
// (the lock screen fades out slowly on an emulated core).
// vga.svga_memory is a lib.js view (a Proxy that builds a typed array on
// every element access): read the frame buffer through one plain array
const svga_bytes = () => new Uint8Array(cpu.wasm_memory.buffer, cpu.devices.vga.svga_memory.byteOffset, cpu.devices.vga.vga_memory_size);
// The picture on screen: vmware_svga's first screen object (RGBA), its
// register mode, virtio_gpu's first display (RGBA), or the VGA core's VBE
// mode (BGR in the frame buffer); null in text and planar modes
function frame_buffer()
{
    const gpu = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["virtio_gpu"];
    const scanout = gpu && gpu.active && gpu.scanouts[0];
    if(scanout && scanout.rgba) return {width: scanout.width, height: scanout.height, bpp: 32, pitch: scanout.width * 4, offset: 0, rgba: scanout.rgba};
    const svga = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
    const screen = svga && svga.svga_active() && svga.screens.screens.get(0);
    if(screen) return {width: screen.width, height: screen.height, bpp: 32, pitch: screen.width * 4, offset: 0, rgba: screen.rgba};
    if(svga && svga.svga_active()) return {width: svga.width, height: svga.height, bpp: svga.bpp, pitch: svga.pitch(), offset: 0};
    const vga = cpu.devices.vga;
    if(!vga.svga_enabled) return null;
    const bytes = vga.svga_bpp / 8;
    return {width: vga.svga_width, height: vga.svga_height, bpp: vga.svga_bpp, pitch: vga.svga_width * bytes, offset: vga.svga_offset * bytes};
}
// 1024x768 at 16/24/32 bpp, as the pixel heuristics below expect
function desktop_mode()
{
    const fb = frame_buffer();
    return fb && fb.width === 1024 && fb.height === 768 && [32, 24, 16].includes(fb.bpp) ? fb : null;
}
let pixel_memory = null, pixel_memory_at = -1;
function pixel(x, y)
{
    const fb = frame_buffer(), bytes_per = fb.bpp / 8;
    // (one array per polling round: the wasm memory may grow in between)
    if(pixel_memory_at !== Math.floor(performance.now() / 50) || pixel_memory.buffer !== cpu.wasm_memory.buffer)
    {
        pixel_memory = svga_bytes();
        pixel_memory_at = Math.floor(performance.now() / 50);
    }
    const at = fb.offset + y * fb.pitch + x * bytes_per, m = fb.rgba || pixel_memory;
    if(fb.rgba) return [m[at], m[at + 1], m[at + 2]];
    return bytes_per === 2 ? [(m[at + 1] >> 3) << 3, (m[at] >> 5 | (m[at + 1] & 7) << 3) << 2, (m[at] & 31) << 3] : [m[at + 2], m[at + 1], m[at]];
}
function password_box_visible()
{
    if(!desktop_mode()) return false;
    const background = pixel(100, 100), tile = pixel(260, 190);
    return [[620, 248], [680, 248], [720, 256], [735, 240]].every(([x, y]) => pixel(x, y).every(c => c > 230)) &&
        // a plain background, not white, around the gray user tile
        !background.every(c => c > 230) && [[900, 100], [100, 600], [900, 600]].every(([x, y]) => pixel(x, y).every((c, i) => c === background[i])) &&
        tile.every(c => c >= 40 && c <= 110 && Math.abs(c - tile[0]) < 8);
}
// The desktop: the white Start logo at the left end of the taskbar (four
// panes split by a vertical gap)
function desktop_visible()
{
    if(!desktop_mode()) return false;
    const white = (x, y) => pixel(x, y).every(c => c > 220);
    return [[16, 744], [30, 744], [16, 752], [30, 752]].every(([x, y]) => white(x, y)) && !white(23, 746) && !white(10, 745) && !white(40, 745);
}
let last_sign_in = -Infinity;
// A key wakes the display or dismisses the lock screen; repeat until the
// password box shows, clear anything typed into it, then sign in.
async function sign_in()
{
    event("sign-in");
    last_sign_in = performance.now();
    for(let i = 0; i < 12 && !password_box_visible() && !desktop_visible(); i++)
    {
        await press([57, 185]);
        for(const limit = performance.now() + 10000; performance.now() < limit && !password_box_visible() && !desktop_visible();) await delay(250);
    }
    // never type the password blind (it could reach the desktop); the caller
    // retries while the session is not up
    if(!password_box_visible()) { event("sign-in-no-password-box"); return; }
    event("password-box");
    for(let i = 0; i < 4; i++) await press([14, 142]);
    await type(password);
    await enter();
}
// The Run dialog of this image at 1024x768 (bottom left), open with the
// input focused: white body, the grey button strip and the edit box's blue
// focus border
function run_dialog_ready()
{
    if(!desktop_mode()) return false;
    const white = (x, y) => pixel(x, y).every(c => c > 245);
    const [r, , b] = pixel(398, 622);
    return white(300, 555) && white(300, 600) && white(100, 650) && pixel(60, 700).every(c => Math.abs(c - 240) <= 6) && b > 200 && r < 120;
}
// Keys typed before the dialog has focus are lost (it takes seconds to tens
// of seconds to appear on a loaded host); returns whether the line was typed
async function run_command(line)
{
    event("run", {line});
    const asked = performance.now();
    await press([0xE0, 0x5B, 0x13, 0x93, 0xE0, 0xDB]); // Win+R
    for(const limit = performance.now() + 60000; performance.now() < limit && !run_dialog_ready();) await delay(100);
    if(!run_dialog_ready()) { event("run-dialog-missing"); return false; }
    // responsiveness: Win+R until the dialog is up with its input focused
    event("run-dialog", {ms: Math.round(performance.now() - asked)});
    await delay(1000);
    // the previous command is preselected; typing replaces it
    await type(line);
    await enter();
    return true;
}

// A command line for cmd /c, elevated: PowerShell's Start-Process -Verb
// RunAs from the Run dialog, then Alt+Y on the UAC prompt (the line must not
// contain quotes)
async function run_admin(line)
{
    event("runadmin", {line});
    if(!await run_command(`powershell -c "start-process cmd -verb runas -argumentlist '/c ${line}'"`)) return false;
    // The UAC prompt dims the desktop (its Start logo is gone): wait for it,
    // answer Yes, and wait for the desktop to come back
    for(const limit = performance.now() + 600000; performance.now() < limit && desktop_visible();)
    {
        await delay(1000);
        screenshot(false);
    }
    if(desktop_visible()) { event("uac-missing"); return false; }
    await delay(5000);
    screenshot(true);
    event("uac");
    for(let i = 0; i < 5 && !desktop_visible(); i++)
    {
        await press([0x38, 0x15, 0x95, 0xB8]); // Alt+Y
        for(const limit = performance.now() + 30000; performance.now() < limit && !desktop_visible();) await delay(500);
    }
    event(desktop_visible() ? "uac-accepted" : "uac-stuck");
    return desktop_visible();
}

function text_screen()
{
    const vga = cpu.devices.vga;
    if(vga.graphical_mode) return "";
    return Array.from({length: 25}, (_, row) => Array.from({length: 80}, (_, col) => {
        const c = vga.vga_memory[(row * 80 + col) * 2];
        return c >= 32 && c < 127 ? String.fromCharCode(c) : " ";
    }).join("").trimEnd()).join("\n").trim();
}
let last_hash = "", shots = 0, last_saved = 0, last_change = 0, dark_fraction = 1, colors = 0;
let svga_seen = "";
// The SVGA II registers as the guest's driver sets them, logged on change
function observe_svga()
{
    // virtio_gpu: whether its displays are on screen, what they show, what the driver sent
    const gpu = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["virtio_gpu"];
    if(gpu)
    {
        // (the transport: v86's VirtIO object, from the source tree)
        const t = cpu.devices.graphics_adapter.pci_device;
        const state = {active: gpu.active, scanouts: gpu.scanouts.map(sc => [sc.enabled, sc.host_width, sc.host_height, sc.resource_id, sc.width, sc.height]),
            resources: gpu.resources.size, errors: gpu.stats.errors, last_error: gpu.stats.last_error.toString(16), commands: gpu.stats.commands,
            cursor: [gpu.stats.cursor_updates, gpu.stats.cursor_moves, gpu.cursor.width, gpu.cursor.height, gpu.cursor.visible],
            status: t && t.device_status, features: t && Array.from(t.driver_feature || [], f => (f >>> 0).toString(16)),
            queues: t && t.queues && t.queues.map(q => [q.size, q.enabled, (q.desc_addr || 0).toString(16), q.avail_last_idx]),
            isr: t && t.isr_status, irq_line: cpu.devices.pci.device_spaces[cpu.devices.graphics_adapter.pci_id][15] & 0xFF};
        const key = JSON.stringify(state);
        if(key !== svga_seen && performance.now() >= svga3d_next) { svga_seen = key; svga3d_next = performance.now() + 5000; event("virtio-gpu", state); }
        return;
    }
    const svga = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
    if(!svga) return;
    const state = {level: svga.level, enable: svga.enable, mode: `${svga.width}x${svga.height}x${svga.bpp}`, pitch: svga.pitch(),
        guest_id: svga.guest_id, config_done: svga.config_done, irq_mask: svga.irq_mask, id: svga.id.toString(16),
        screens: [...svga.screens.screens.values()].map(sc => [sc.id, sc.x, sc.y, sc.width, sc.height, sc.backing ? sc.backing.gmr : -1]),
        unknown: svga.stats ? svga.stats.last_unknown : 0, errors: svga.stats ? svga.stats.errors : 0};
    const key = JSON.stringify(state);
    if(key !== svga_seen) { svga_seen = key; event("svga", state); }
    // the 3D commands so far, every 30 s while they change
    if(svga.svga3d && performance.now() >= svga3d_next)
    {
        svga3d_next = performance.now() + 30000;
        const counts = JSON.stringify(svga.svga3d.counts);
        const activity = counts + JSON.stringify(svga.stats);
        if(activity !== svga3d_seen) { svga3d_seen = activity; event("svga3d", {counts: svga.svga3d.counts, bytes: svga.svga3d.bytes, surfaces: svga.svga3d.surfaces.size, contexts: svga.svga3d.contexts.size, device: svga.stats, warnings: svga.svga3d.warnings}); }
    }
}
let svga3d_next = 0, svga3d_seen = "";
function screenshot(force)
{
    const fb = frame_buffer();
    if(!fb || !fb.width || !fb.height || ![32, 24, 16].includes(fb.bpp)) return null;
    const width = fb.width, height = fb.height;
    const bytes_per = fb.bpp / 8, stride = width * 3 + 1, raw = Buffer.alloc(stride * height), memory = fb.rgba || svga_bytes();
    for(let y = 0; y < height; y++) for(let x = 0; x < width; x++)
    {
        const from = fb.offset + y * fb.pitch + x * bytes_per, to = y * stride + 1 + x * 3;
        if(fb.rgba) { raw[to] = memory[from]; raw[to + 1] = memory[from + 1]; raw[to + 2] = memory[from + 2]; }
        else if(bytes_per === 2)
        {
            const v = memory[from] | memory[from + 1] << 8;
            raw[to] = (v >> 11 & 31) << 3; raw[to + 1] = (v >> 5 & 63) << 2; raw[to + 2] = (v & 31) << 3;
        }
        else { raw[to] = memory[from + 2]; raw[to + 1] = memory[from + 1]; raw[to + 2] = memory[from]; }
    }
    const hash = create_hash("sha1").update(raw).digest("hex").slice(0, 12);
    if(hash === last_hash && !force) return hash;
    last_hash = hash;
    last_change = performance.now();
    let dark = 0, samples = 0;
    const palette = new Set();
    for(let at = 1; at < raw.length; at += 3 * 97)
    {
        samples++;
        if(raw[at] + raw[at + 1] + raw[at + 2] < 48) dark++;
        palette.add(raw[at] >> 5 | raw[at + 1] >> 5 << 3 | raw[at + 2] >> 5 << 6);
    }
    dark_fraction = dark / samples;
    colors = palette.size;
    const crc = data => { let c = 0xFFFFFFFF; for(const byte of data) { c ^= byte; for(let i = 0; i < 8; i++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; } return (c ^ 0xFFFFFFFF) >>> 0; };
    const chunk = (name, data) => { const tag = Buffer.from(name), body = Buffer.concat([tag, data]), b = Buffer.alloc(data.length + 12); b.writeUInt32BE(data.length); body.copy(b, 4); b.writeUInt32BE(crc(body), b.length - 4); return b; };
    const header = Buffer.alloc(13); header.writeUInt32BE(width); header.writeUInt32BE(height, 4); header[8] = 8; header[9] = 2;
    const png = Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", header), chunk("IDAT", deflate_sync(raw)), chunk("IEND", Buffer.alloc(0))]);
    fs.writeFileSync(path.join(out, "screen.png"), png);
    // numbered history: at most one per 20 s (a console cursor blinks)
    if(force || performance.now() - last_saved > 20000)
    {
        last_saved = performance.now();
        fs.writeFileSync(path.join(out, `screen-${String(++shots).padStart(3, "0")}-${elapsed()}s.png`), png);
    }
    return hash;
}
function stats()
{
    const ex = cpu.wm.exports;
    const tier = ex.x64_page_stat ? Object.fromEntries([["compiled", 0], ["native", 1], ["retries", 2], ["unknown", 3], ["steps", 4], ["invalidated", 5],
        ["failed", 7], ["recompiled", 8], ["evicted", 11], ["live", 12], ["activations", 13], ["invlpg", 14], ["cr_writes", 15], ["access_misses", 16], ["lfb_fills", 17], ["cr3_keep_global", 18], ["jac_large_flush", 19], ["unaligned_reads", 25], ["distinct", 21], ["ms_in_calls", 20], ["ms_in_execute", 22], ["ms_first_calls", 23], ["bytes_compiled", 24], ["cr0_writes", 26], ["cr3_writes", 27], ["cr4_writes", 28], ["full_flushes", 29], ["walks", 30], ["compat_fills", 31], ["compat_refills", 32], ["hot_recompiles", 33], ["jac_fills", 34], ["jac_conflicts", 35]]
        .map(([name, i]) => [name, ex.x64_page_stat(i)])) : null;
    const d = cpu.get_diagnostics();
    return {page_tier: tier, cores: d.cores.map(core => ({state: core.state, ip: core.linear_ip, cs: core.cs, retired: core.retired_instructions, halted: core.halted})),
        mode: d.cpu.mode, overlay_sectors: source.overlay.size, execution: d.execution,
        workers: d.parallel ? d.parallel.cores.map(core => ({steps: core.steps, slices: core.slices, waits: core.waits, io: core.io, refused: core.refused})) : undefined,
        kicks: cpu.wm.exports.parallel_kick_count ? cpu.wm.exports.parallel_kick_count() : undefined};
}
// Read-only 4-level walk (no A/D updates), for diagnostics only.
function physical(cr3, address)
{
    const ram = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset, cpu.mem8.length);
    let table = cr3;
    for(const shift of [39n, 30n, 21n, 12n])
    {
        const at = Number(table & 0xFFFFFF000n) + Number(address >> shift & 511n) * 8;
        if(at + 8 > ram.byteLength) return null;
        const entry = ram.getBigUint64(at, true);
        if(!(entry & 1n)) return null;
        if(shift === 12n || shift < 39n && entry & 128n)
        {
            const mask = (1n << shift) - 1n;
            return Number(entry & 0xFFFFFF000n & ~mask | address & mask);
        }
        table = entry;
    }
    return null;
}
// "diag": each core's registers, its last faults (core 0's from this
// instance, a vCPU worker's from its instance's copy in the shared memory),
// the paging entries of the last fault address and the code at its RIP
// (cores taking turns: the running one only, whose fault log they share)
function diagnose()
{
    const memory = cpu.wasm_memory.buffer, e = cpu.wm.exports, O = STATE_OFFSETS;
    const hex = v => "0x" + BigInt.asUintN(64, BigInt(v)).toString(16);
    const result = [];
    for(let core = 0; core < (cpu.parallel ? cores : 1); core++)
    {
        const base = core === 0 ? cpu.state_base : cpu.parallel.state_base(core);
        const view = new DataView(memory, base);
        const u32 = offset => view.getUint32(offset, true);
        const pair = (low, high) => BigInt(u32(high)) << 32n | BigInt(u32(low));
        const gpr = i => pair(i < 8 ? O.reg32 + 4 * i : O.x64_gpr_ext_lo + 4 * (i - 8), O.x64_gpr_hi + 4 * i);
        const names = ["rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"];
        const regs = Object.fromEntries(names.map((name, i) => [name, hex(gpr(i))]));
        const cr = i => pair(O.cr + 4 * i, O.x64_cr_hi + 4 * i);
        const cr3 = cr(3) & ~0xFFFn, rip = pair(O.instruction_pointer, O.x64_rip_hi);
        Object.assign(regs, {rip: hex(rip), flags: hex(u32(O.flags)), cpl: view.getUint8(O.cpl), cs: hex(view.getUint16(O.sreg + 2, true)),
            cr0: hex(cr(0)), cr2: hex(cr(2)), cr3: hex(cr3), cr4: hex(cr(4)), cr8: hex(view.getBigUint64(O.x64_cr8, true)),
            gs_base: hex(pair(O.segment_offsets + 20, O.x64_segment_base_hi + 20)),
            kernel_gs_base: hex(view.getBigUint64(O.x64_kernel_gs_base, true)), in_hlt: view.getUint8(O.in_hlt)});
        // the fault log: [vector, error, rip, address, rsp, cs] x 16, most recent at next - 1
        const instance = cpu.parallel ? cpu.parallel.instance_bases[core] : 0;
        const log_at = instance + e.x64_fault_log_location(0), next = new Uint32Array(memory, instance + e.x64_fault_log_location(1), 1)[0];
        const faults = [];
        for(let i = 0; i < Math.min(16, next); i++)
        {
            const entry = new BigUint64Array(memory, log_at + ((next - 1 - i) % 16) * 48, 6);
            faults.push({vector: Number(entry[0]), error: hex(entry[1]), rip: hex(entry[2]), address: hex(entry[3]), rsp: hex(entry[4]), cs: hex(entry[5])});
        }
        const walk = address => {
            const ram = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset, cpu.mem8.length);
            const entries = [];
            let table = cr3;
            for(const shift of [39n, 30n, 21n, 12n])
            {
                const at = Number(table & 0xFFFFFF000n) + Number(address >> shift & 511n) * 8;
                if(at + 8 > ram.byteLength) { entries.push("beyond RAM " + hex(at)); break; }
                const entry = ram.getBigUint64(at, true);
                entries.push(hex(at) + ":" + hex(entry));
                if(!(entry & 1n) || shift === 12n || shift < 39n && entry & 128n) break;
                table = entry;
            }
            return entries;
        };
        const code = address => {
            const at = physical(cr3, address);
            return at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + 24)).toString("hex");
        };
        const last = faults[0];
        result.push({core, regs, faults_taken: next, faults: faults.slice(0, 8),
            last_walk: last && last.address !== hex(-1) ? walk(BigInt(last.address)) : null,
            last_code: last ? code(BigInt(last.rip)) : null, rip_code: code(rip),
            kernel_offset: kernel_base !== null ? hex(rip - kernel_base) : null});
    }
    return result;
}
// RIP sampling between slices: which kernel code is hot (offline
// symbolization against ntoskrnl.exe; the base is found from LSTAR, which
// points into ntoskrnl)
const rip_samples = new Map();
let kernel_base = null;
function sample_rip()
{
    const view = new DataView(cpu.wasm_memory.buffer);
    const rip = BigInt(view.getUint32(1584, true)) << 32n | BigInt(cpu.instruction_pointer[0] >>> 0);
    if(kernel_base === null && view.getBigUint64(1720, true) !== 0n)
    {
        const lstar = view.getBigUint64(1720, true);
        const cr3 = BigInt(cpu.cr[3] >>> 0) | BigInt(view.getUint32(1612, true)) << 32n;
        for(let page = lstar & ~0xFFFn, n = 0; n < 8192; n++, page -= 0x1000n)
        {
            const at = physical(cr3, page);
            if(at !== null && cpu.mem8[at] === 0x4D && cpu.mem8[at + 1] === 0x5A) { kernel_base = page; event("kernel-base", {base: "0x" + page.toString(16)}); break; }
        }
    }
    const compat = view.getUint8(1744) === 0 && (view.getBigUint64(1696, true) & 0x400n) !== 0n;
    const key = compat ? "compat:0x" + rip.toString(16) :
        kernel_base !== null && rip >= kernel_base && rip < kernel_base + 0x1000000n ? "nt+0x" + (rip - kernel_base).toString(16) : "0x" + rip.toString(16);
    rip_samples.set(key, (rip_samples.get(key) || 0) + 1);
    if(!rip_raw.has(key)) rip_raw.set(key, rip);
}
// (a sampled key's RIP, for its code bytes in the report)
const rip_raw = new Map();
function rip_bytes(key)
{
    const rip = rip_raw.get(key);
    if(rip === undefined) return null;
    const at = physical(current_cr3(), rip - 16n);
    return at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + 32)).toString("hex");
}
// WIN_USER_TRACE=1: exceptions taken from user mode (compatibility mode: all;
// 64-bit: all but #PF), with the code at the faulting RIP, read while the
// process is (most likely) still current
let trace_seen = 0;
function poll_user_trace()
{
    const ex = cpu.wm.exports, count = ex.x64_user_trace_count();
    if(count === trace_seen) return;
    const first = Math.max(0, count - 1024);
    const u64 = (i, f) => BigInt(ex.x64_user_trace(i - first, f, 1) >>> 0) << 32n | BigInt(ex.x64_user_trace(i - first, f, 0) >>> 0);
    for(let i = Math.max(trace_seen, first); i < count; i++)
    {
        const [vector, error, rip, address, rsp, cs, cr3] = [0, 1, 2, 3, 4, 5, 6].map(f => u64(i, f));
        const at = physical(cr3, rip);
        const none = 0xFFFFFFFFFFFFFFFFn, hex = v => "0x" + v.toString(16);
        console.log("X64_WIN_TRACE " + JSON.stringify({n: i, vector: Number(vector), error: error === none ? null : hex(error), rip: hex(rip),
            cr2: address === none ? null : hex(address), rsp: hex(rsp), cs: hex(cs), cr3: hex(cr3),
            code: at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + 16)).toString("hex")}));
    }
    trace_seen = count;
}
// WIN_IDLE=1: after the desktop, how busy the idle guest is. Host windows
// of 10 s (per core: share of the wall clock spent executing, MIPS, HLTs),
// and CPULOAD.EXE (tests/x64/windows_cpuload.c): Windows' own accounting,
// the numbers Task Manager shows, over WIN_IDLE_ROUNDS windows of 10 s,
// started WIN_IDLE_SETTLE_S (20) seconds after the desktop appeared.
let host_last = null;
function host_window()
{
    const ex = cpu.wm.exports, now = performance.now(), usage = process.cpuUsage();
    const sample = {at: now, usage, cores: Array.from({length: cores}, (_, core) => [0, 3, 4].map(f => ex.core_statistics_get(core, f)))};
    if(host_last)
    {
        const wall = now - host_last.at;
        event("host-window", {wall_ms: Math.round(wall),
            host_cpu: +((usage.user + usage.system - host_last.usage.user - host_last.usage.system) / 1000 / wall).toFixed(2),
            cores: sample.cores.map(([retired, halts, runtime], core) => {
                const [retired0, halts0, runtime0] = host_last.cores[core];
                return {busy: +((runtime - runtime0) / wall).toFixed(3), mips: Math.round((retired - retired0) / wall / 1000), halts: halts - halts0};
            })});
    }
    host_last = sample;
}
const port_counts = new Map();
const snapshots_taken = [];
const result_text = name => { const bytes = read_fat16(tools.bytes, name); return bytes ? Buffer.from(bytes).toString("ascii") : ""; };

try
{
    await new Promise((resolve, reject) => { vm.add_listener("emulator-loaded", resolve); vm.add_listener("emulator-error", reject); });
    cpu = vm.v86.cpu;
    // the screen when the guest resets the machine (a bugcheck's blue
    // screen, gone once the firmware runs), and the reset at once (the
    // main loop may be busy signing in)
    {
        const note_reset = cpu.note_reset.bind(cpu);
        cpu.note_reset = reason => {
            note_reset(reason);
            event("reset-now", {reason, count: cpu.last_reset && cpu.last_reset.count});
            screenshot(true);
        };
    }
    // WIN_USB_TRACE=1: each report the tablet gives the guest
    // (X64_WIN_TABLET_REPORT buttons x y, the tablet's 0..32767, at s)
    if(process.env.WIN_USB_TRACE && cpu.devices.usb)
    {
        const tablet = cpu.devices.usb.device["tablet"];
        const data_in = tablet.data_in.bind(tablet);
        tablet.data_in = (endpoint, max_length) =>
        {
            const r = data_in(endpoint, max_length);
            if(r instanceof Uint8Array) console.log("X64_WIN_TABLET_REPORT " + r[0] + " " + (r[1] | r[2] << 8) + " " + (r[3] | r[4] << 8) + " at " +
                (performance.now() / 1000).toFixed(2));
            return r;
        };
    }
    // WIN_TPM_TRACE=1: each TPM command (X64_WIN_TPM code response-code
    // milliseconds at s, a failed one's bytes)
    if(process.env.WIN_TPM_TRACE && cpu.devices.tpm)
    {
        const u32 = (b, at) => (b[at] << 24 | b[at + 1] << 16 | b[at + 2] << 8 | b[at + 3]) >>> 0;
        cpu.devices.tpm.device["on_command"] = (command, response, ms) =>
            console.log("X64_WIN_TPM " + u32(command, 6).toString(16) + " " + u32(response, 6).toString(16) + " " + ms.toFixed(1) +
                " at " + elapsed() + (u32(response, 6) ? " " + Buffer.from(command.subarray(0, 96)).toString("hex") : ""));
    }
    // WIN_AUDIO=hd_audio: what the controller played
    const audio = {bytes: 0, formats: {}, loud: 0};
    vm.add_listener("hd-audio-pcm", pcm => {
        for(const chunk of pcm["chunks"])
        {
            audio.bytes += chunk.length;
            audio.formats[pcm["format"].toString(16)] = (audio.formats[pcm["format"].toString(16)] || 0) + chunk.length;
            const samples = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.length >> 1);
            for(const sample of samples) if(Math.abs(sample) > 64) audio.loud++;
        }
    });
    report.audio = audio;
    if(process.env.WIN_NET)
    {
        // (Windows' own HTTP: NCSI, updates; nothing reaches the internet)
        vm.network_adapter.fetch = () => Promise.resolve(new Response("", {status: 404}));
        tcp_endpoint(vm, {5000: {serve: () => Buffer.concat([Buffer.from("HTTP/1.0 200 OK\r\nContent-Type: application/octet-stream\r\n" +
            "Content-Length: " + nic_pattern.length + "\r\n\r\n"), nic_pattern])}});
        console.log("X64_WIN_NIC_MD5 " + create_hash("md5").update(nic_pattern).digest("hex"));
    }
    if(+process.env.WIN_AHCI_TRACE && cpu.devices.ahci_test)
    {
        // GHC, and each port's PxIE, PxCMD, PxSCTL; and its configuration
        // space writes (command, power management, MSI)
        const ahci = cpu.devices.ahci_test, write32 = ahci.write32.bind(ahci);
        ahci.write32 = (offset, value, mask) => {
            if(offset === 4 || offset >= 0x100 && [0x14, 0x18, 0x2C].includes(offset & 0x7F))
                event("ahci-write", {offset: offset.toString(16), value: (value >>> 0).toString(16)});
            write32(offset, value, mask);
        };
        const pci = cpu.devices.pci, function_write = pci.function_write.bind(pci);
        pci.function_write = (pci_id, offset, size, value) => {
            if(pci_id === ahci.pci_id && offset >= 4) event("ahci-config", {offset: offset.toString(16), size, value: (value >>> 0).toString(16)});
            function_write(pci_id, offset, size, value);
        };
    }
    if(+process.env.WIN_PCIE_TRACE)
    {
        for(const port of cpu.devices.pcie_root_ports || [])
        {
            const written = port.slot_control_written.bind(port), raised = port.event.bind(port);
            port.slot_control_written = value => { event("pcie-sltctl", {port: port.number, value: value.toString(16)}); written(value); };
            port.event = events => { if(events !== 0x10) event("pcie-event", {port: port.number, events: events.toString(16)}); raised(events); };
        }
    }
    // virtio_gpu: every device status the driver writes, every control
    // command and every reset of the transport, as they happen
    const virtio = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["virtio_gpu"] &&
        cpu.devices.graphics_adapter.pci_device;
    if(virtio)
    {
        const status_field = virtio.mmio_fields.find(field => field.offset === 20);
        const write_status = status_field.write;
        status_field.write = value => { event("virtio-status", {value, before: virtio.device_status}); write_status(value); };
        const gpu = cpu.devices.graphics_adapter.device["virtio_gpu"];
        const control = gpu.control.bind(gpu);
        let logged = 0;
        gpu.control = bytes => {
            const response = control(bytes);
            const type = bytes[0] | bytes[1] << 8, result = response[0] | response[1] << 8;
            if(logged++ < 200 || result >= 0x1200) event("virtio-command", {type: type.toString(16), result: result.toString(16), length: bytes.length});
            return response;
        };
        const needs_reset = virtio.needs_reset.bind(virtio);
        virtio.needs_reset = () => { event("virtio-needs-reset"); needs_reset(); };
    }
    // WIN_GUESTINFO=key=value;...: what the VMware backdoor answers for
    // guestinfo.<key> (VMware's drivers read their settings so, e.g.
    // loglevel.vm3d.all=10 or svga.wddm.miniportLogging=TRUE)
    for(const entry of (process.env.WIN_GUESTINFO || "").split(";").filter(Boolean))
    {
        const at = entry.indexOf("=");
        cpu.devices.vmware.guestinfo.set(entry.slice(0, at), entry.slice(at + 1));
    }
    if(process.env.WIN_X64_PROFILE !== "0") cpu.wm.exports.set_x64_test_capabilities(1);
    if(process.env.WIN_PAGE_TIER === "0") cpu.wm.exports.x64_page_set_enabled(0);
    if(process.env.WIN_STEP_PROFILE) cpu.wm.exports.x64_page_profile(1);
    if(process.env.WIN_RECOMPILE_MISSES) cpu.wm.exports.x64_page_set_recompile_misses(+process.env.WIN_RECOMPILE_MISSES);
    // WIN_OUTLINE=0: inline the access cache lookup at every access
    if(process.env.WIN_OUTLINE === "0") cpu.wm.exports.x64_page_set_outline(0);
    // WIN_SIZE_STATS=1: Wasm bytes per template kind, printed at the end
    if(process.env.WIN_SIZE_STATS) cpu.wm.exports.x64_pagegen_size_stats(1);
    // WIN_PAGE_TIMING=1: time spent inside page function calls (stats)
    if(process.env.WIN_PAGE_TIMING) cpu.wm.exports.x64_page_timing(1);
    // WIN_DUMP_MODULES=<n>: save every 64th published page function module
    // (up to n) to <out>/modules/ for offline size analysis
    if(+process.env.WIN_DUMP_MODULES)
    {
        fs.mkdirSync(path.join(out, "modules"), {recursive: true});
        const publish = cpu.jit_publish.bind(cpu);
        let published = 0, dumped = 0;
        cpu.jit_publish = (client, id, slot, pointer, length) => {
            if(published++ % 64 === 0 && dumped < +process.env.WIN_DUMP_MODULES)
                fs.writeFileSync(path.join(out, "modules", `m${String(dumped++).padStart(4, "0")}.wasm`),
                    new Uint8Array(cpu.wasm_memory.buffer, pointer >>> 0, length >>> 0));
            return publish(client, id, slot, pointer, length);
        };
    }
    // WIN_RECORD=<file>: the inputs of the page tier's compilations, saved at
    // the end as tools/replay_record.mjs saves them (a test core's replay
    // hooks: WASM_PATH=build/v86-ir-test-release.wasm), e.g. to replay a
    // boot's pages under other JIT switches
    if(process.env.WIN_RECORD)
    {
        if(!cpu.wm.exports.x64_page_record_start) throw new Error("WIN_RECORD: the core has no replay hooks (WASM_PATH=build/v86-ir-test-release.wasm)");
        cpu.wm.exports.x64_page_record_start();
    }
    // WIN_LPT_STATUS=<hex>: the status register of the unconnected LPT1
    if(process.env.WIN_LPT_STATUS) cpu.devices.parallel0.status = parseInt(process.env.WIN_LPT_STATUS, 16);
    // WIN_PORT_STATS=1: port accesses by port and size, printed each minute
    if(process.env.WIN_PORT_STATS)
    {
        for(const [name, kind] of [["port_read8", "in8"], ["port_read16", "in16"], ["port_read32", "in32"],
            ["port_write8", "out8"], ["port_write16", "out16"], ["port_write32", "out32"]])
        {
            const f = cpu.io[name].bind(cpu.io);
            cpu.io[name] = (port, ...rest) => {
                const key = kind + ":" + port.toString(16);
                port_counts.set(key, (port_counts.get(key) || 0) + 1);
                return f(port, ...rest);
            };
        }
    }
    if(process.env.WIN_USER_TRACE) cpu.wm.exports.x64_user_trace_enable(1);
    // The reset is noted before any state is replaced: record the code at
    // each faulting RIP and the descriptor tables while they are intact.
    const note_reset = cpu.note_reset.bind(cpu);
    cpu.note_reset = reason => {
        note_reset(reason);
        const info = cpu.last_reset, cr3 = BigInt(cpu.cr[3] >>> 0) | BigInt(new Uint32Array(cpu.wasm_memory.buffer, 1612, 1)[0]) << 32n;
        const bytes = (address, length) => {
            const at = physical(cr3, BigInt(address));
            return at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + length)).toString("hex");
        };
        for(const fault of info.x64_faults || [])
        {
            fault.bytes = bytes(fault.rip, 24);
            // (a kernel fault: the code before it too, to disassemble what led there)
            if(fault.cs === "0x10") fault.before = bytes(BigInt(fault.rip) - 512n, 512);
        }
        // The image containing the first faulting RIP (scan down for its MZ
        // header), plus the stack, for offline symbolization
        const first = info.x64_faults?.[info.x64_faults.length - 1];
        if(first)
        {
            for(let page = BigInt(first.rip) & ~0xFFFn, n = 0; n < 4096; n++, page -= 0x1000n)
            {
                const header = bytes(page, 2);
                if(header === "4d5a") { info.image_base = "0x" + page.toString(16); break; }
            }
            info.stack = "";
            for(let at = BigInt(first.rsp), end = at + 0x40000n; at < end;)
            {
                const length = 0x1000 - Number(at & 0xFFFn), part = bytes(at, length);
                if(part === null) break;
                info.stack += part;
                at += BigInt(length);
            }
            for(const rva of (process.env.WIN_DUMP_RVAS || "").split(",").filter(Boolean))
                (info.dumps ||= {})[rva] = info.image_base && bytes(BigInt(info.image_base) + BigInt(rva), 64);
        }
        info.gdt = bytes(info.gdtr[0], Math.min(info.gdtr[1] + 1, 0x80));
        info.idt_3_8_13 = [3, 8, 13].map(v => bytes(BigInt(info.idtr[0]) + BigInt(v * 16), 16));
    };
    const run_cores = cpu.run_cores.bind(cpu);
    cpu.run_cores = () => { try { return run_cores(); } catch(error) { execution_error = error; vm.stop(); return 100; } };
    let resumed = null;
    if(state_load)
    {
        const fd = fs.openSync(state_load + ".state", "r"), size = fs.fstatSync(fd).size;
        await vm.restore_state_stream({size, read: async (offset, length) => {
            const bytes = new Uint8Array(length);
            for(let done = 0; done < length;) done += fs.readSync(fd, bytes, done, length - done, offset + done);
            return bytes;
        }});
        fs.closeSync(fd);
        resumed = JSON.parse(fs.readFileSync(state_load + ".json", "utf8"));
        launch_serial = resumed.launch_serial;
        launcher_ready = resumed.launcher_ready;
        event("state-loaded", {file: state_load, bytes: size});
    }
    vm.run();
    const deadline = performance.now() + +(process.env.WIN_TIMEOUT_MS || 3600000);
    let next_profile = performance.now() + 1000 * +(process.env.WIN_CPU_PROFILE || 0);
    let next_report = 0, next_samples = performance.now() + 60000, next_shot = 0, resets = 0, signed_in = false, probe_sent = 0, text_seen = "";
    let shutdown_at = 0, shutdown_sent = false, shutdown_deadline = 0;
    // (a loaded state is signed in, past the desktop)
    if(resumed) { signed_in = true; probe_sent = Infinity; report.desktop_s = elapsed(); }
    let next_rates = performance.now() + 1000 * +(process.env.WIN_RATES || 0), rates_counts = null, rates_at = performance.now(), rates_retired = 0;
    let rate_samples = {n: 0, halted: 0, backlog: 0, waiting: 0};
    // a line of command.txt (see the top of this file), or of WIN_SETUP
    // (a bad line is reported, not fatal: the guest's state is worth more)
    const command = line => run_one(line).catch(error => {
        if(error === execution_error) throw error;
        event("command-failed", {line, error: String(error && error.message || error)});
    });
    const run_one = async line => {
        const [verb, ...rest] = line.split(" "), argument = rest.join(" ");
        event("command", {line});
        if(verb === "key") await press(argument.split(/\s+/).map(v => parseInt(v, 16)));
        else if(verb === "type") await type(argument);
        else if(verb === "run") await run_command(argument);
        else if(verb === "runadmin") await run_admin(argument);
        else if(verb === "enter") await enter();
        else if(verb === "space") await press([57, 185]);
        else if(verb === "password") { await type(password); await enter(); }
        else if(verb === "shot") screenshot(true);
        else if(verb === "file") console.log("X64_WIN_FILE " + argument + "\n" + result_text(argument));
        // "usbdevices": each USB device's controller and speed (X64_WIN_USB_DEVICES)
        else if(verb === "usbdevices") console.log("X64_WIN_USB_DEVICES " + JSON.stringify(await vm.usb_devices()));
        else if(verb === "usbdiskfile")
        {
            const bytes = usb_disk && read_fat16(usb_disk, argument);
            console.log("X64_WIN_USB_DISK_FILE " + argument + "\n" + (bytes ? Buffer.from(bytes).toString("ascii") : "(none)"));
        }
        else if(verb === "audio") console.log("X64_WIN_AUDIO " + JSON.stringify(report.audio));
        else if(verb === "waitfile")
        {
            const [name, text, seconds] = argument.split(" ");
            for(const limit = performance.now() + 1000 * (+seconds || 600); performance.now() < limit && !result_text(name).includes(text);)
            {
                await delay(2000);
                if(execution_error) throw execution_error;
                screenshot(false);
            }
            event(result_text(name).includes(text) ? "waitfile-found" : "waitfile-timeout", {name, text});
        }
        else if(verb === "pointergrid")
        {
            const points = [[0, 0], [1023, 0], [0, 767], [1023, 767], [512, 384]];
            for(let i = 0; i < 5; i++) for(let j = 0; j < 5; j++) points.push([Math.round(i * 1023 / 4), Math.round(j * 767 / 4)]);
            for(const [x, y] of points)
            {
                vm.bus.send("mouse-absolute", [x, y, 1024, 768]);
                console.log("X64_WIN_POINTER " + x + " " + y + " at " + elapsed() + (process.env.WIN_USB_TRACE ? " (" + (performance.now() / 1000).toFixed(2) + ")" : ""));
                await delay(2500);
            }
            // (USBCHECK.EXE stops logging there)
            vm.bus.send("mouse-absolute", [3, 5, 1024, 768]);
        }
        // the page's size for a display (V86.set_display_size; virtio_gpu tells the guest)
        else if(verb === "display") vm.set_display_size(...argument.split(/\s+/).map(Number));
        // a relative mouse movement (PS/2), in pixels, y up
        else if(verb === "mouse") vm.bus.send("mouse-delta", argument.split(/\s+/).map(Number));
        // "nudge <dx> <dy> <n>": n relative movements of (dx, dy), one PS/2
        // packet each (y up; Windows' pointer ballistics see each packet's size)
        else if(verb === "nudge")
        {
            const [dx, dy, n] = argument.split(/\s+/).map(Number);
            for(let i = 0; i < n; i++) { vm.bus.send("mouse-delta", [dx, dy]); await delay(20); }
        }
        // "corner": the pointer into the top left corner of the screen
        else if(verb === "corner")
        {
            for(let i = 0; i < 40; i++) { vm.bus.send("mouse-delta", [-120, 120]); await delay(20); }
        }
        // "click [right]": a click of the left (right) button where the pointer is
        else if(verb === "click")
        {
            const right = argument === "right";
            vm.bus.send("mouse-click", [!right, false, right]);
            await delay(300);
            vm.bus.send("mouse-click", [false, false, false]);
        }
        // an absolute position on a screen of the given size (the VMware
        // backdoor's mouse, which takes over from PS/2 once its driver runs)
        else if(verb === "pointer") vm.bus.send("mouse-absolute", argument.split(/\s+/).map(Number));
        // the machine into files, to start from later (WIN_STATE_LOAD)
        // (streamed: with the GPU's contents a state passes 4 GiB)
        else if(verb === "savestate")
        {
            const file = path.resolve(argument);
            await vm.stop();
            let bytes = 0;
            try
            {
                const fd = fs.openSync(file + ".state", "w");
                try { await vm.save_state_stream(chunk => { fs.writeSync(fd, chunk); bytes += chunk.length; }); }
                finally { fs.closeSync(fd); }
                save_overlay(file + ".hda.ovl");
                if(hdb_path) save_overlay(file + ".hdb.ovl", hdb);
                fs.writeFileSync(file + ".json", JSON.stringify({launch_serial, launcher_ready, signed_in: true}));
            }
            finally { vm.run(); }
            event("savestate", {file, bytes});
        }
        // a snapshot saved and restored in place (the disks are not in it, and unchanged)
        else if(verb === "snapshot")
        {
            await vm.stop();
            const state = await vm.save_state();
            await vm.restore_state(state);
            vm.run();
            event("snapshot", {bytes: state.byteLength});
        }
        else if(verb === "rips") next_samples = 0;
        // each core's registers, last faults and the paging entries of the last fault address
        else if(verb === "diag") console.log("X64_WIN_DIAG " + JSON.stringify(diagnose()));
        // "mem <core> <linear address, hex> <bytes>": guest memory through that core's CR3
        else if(verb === "mem")
        {
            const [core, address, length] = argument.split(/\s+/);
            const cr3 = BigInt(diagnose()[+core].regs.cr3), start = BigInt("0x" + address.replace(/^0x/, ""));
            let text = "";
            for(let at = start; at < start + BigInt(+length); at += 8n)
            {
                const where = physical(cr3, at);
                text += where === null ? "????????????????" : new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset + where, 8).getBigUint64(0, true).toString(16).padStart(16, "0");
                text += (at - start) % 32n === 24n ? "\n" : " ";
            }
            console.log(`X64_WIN_MEM ${core} 0x${start.toString(16)}\n${text}`);
        }
        else if(verb === "jitstats") print_jit_stats(vm, {script: "windows_boot", phase: argument || "command", s: elapsed(), wasm: process.env.WASM_PATH || null, cores});
        // PCI Express hot plug (WIN_PCIE_DEVICE)
        else if(verb === "pcieattach") await vm.attach_pcie_device(+argument);
        else if(verb === "pciedetach")
        {
            const [port, how] = argument.split(/\s+/);
            const asked = performance.now();
            vm.detach_pcie_device(+port, {surprise: how === "surprise"}).then(
                () => event("pcie-detached", {port: +port, after_s: Math.round((performance.now() - asked) / 100) / 10}),
                error => event("pcie-detach-failed", {port: +port, error: String(error && error.message || error)}));
        }
        else if(verb === "pcieslot")
        {
            const port = cpu.devices.pcie_root_ports[+argument];
            const read = (offset, size) => cpu.devices.pci.function_read(port.pci_id, offset, size).toString(16);
            event("pcie-slot", {port: +argument, card: port.card, slot_control: read(0x58, 2), slot_status: read(0x5A, 2),
                link_status: read(0x52, 2), msi_control: read(0x82, 2), command: read(0x04, 2)});
        }
        else if(verb === "trace") { cpu.wm.exports.x64_user_trace_enable(argument !== "off"); trace_seen = 0; }
        else if(verb === "launch")
        {
            if(!launcher_ready) event("launcher-missing");
            cpu.devices.vmware.guestinfo.set("v86.run", ++launch_serial + " " + argument);
        }
        else if(verb === "svgashaders")
        {
            // the legacy (GB) shaders' bytecode, as "svga3d-shader" events
            const svga = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
            for(const [shid, sh] of svga && svga.svga3d ? svga.svga3d.gb_shaders : [])
            {
                const code = sh.code ? new Uint32Array(sh.code.buffer, sh.code.byteOffset, sh.code.byteLength >> 2) : [];
                event("svga3d-shader", {shid, type: sh.type, code: Array.from(code, v => (v >>> 0).toString(16)).join(" ")});
            }
        }
        else if(verb === "dxshaders")
        {
            // the DX shaders' tokens as they are bound, as "dx-shader" events
            const svga = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
            if(svga && svga.svga3d) svga.svga3d.shader_log = argument === "off" ? null : (shid, type, bytes) => {
                const code = new Uint32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength >> 2);
                event("dx-shader", {shid, type, code: Array.from(code, v => (v >>> 0).toString(16)).join(" ")});
            };
        }
        else if(verb === "svgalog")
        {
            const svga = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
            const quiet = new Set([1094, 1098, 1119, 1126, 1127, 1135]);
            // "svgalog 1101,1267": only those commands (any range)
            const only = /^\d+(,\d+)*$/.test(argument) ? new Set(argument.split(",").map(Number)) : null;
            if(svga && svga.svga3d) svga.svga3d.command_log = argument === "off" ? null : (id, p) => {
                if(only ? !only.has(id) : id >= 1143 && id < 1300 || quiet.has(id)) return;
                event("svga3d-command", {id, n: p.length, body: Array.from(p.subarray(0, 24), v => (v >>> 0).toString(16)).join(" ")});
            };
        }
        else if(verb === "wait")
        {
            // (the main loop is not running: keep watching the screen, and
            // take commands from command.txt)
            for(const limit = performance.now() + 1000 * +argument; performance.now() < limit;)
            {
                await delay(2000);
                if(execution_error) throw execution_error;
                screenshot(false);
                observe_svga();
                const file = path.join(out, "command.txt");
                if(fs.existsSync(file))
                {
                    const lines = fs.readFileSync(file, "utf8").split("\n").map(line => line.trim()).filter(Boolean);
                    fs.unlinkSync(file);
                    for(const next of lines) await command(next);
                }
            }
        }
    };
    let idle_at = 0, idle_sent = false, next_host_window = 0;
    let load32_at = 0, load32_sent = false;
    while(performance.now() < deadline)
    {
        await delay(200);
        if(execution_error) throw execution_error;
        const command_file = path.join(out, "command.txt");
        if(fs.existsSync(command_file))
        {
            const lines = fs.readFileSync(command_file, "utf8").split("\n").map(line => line.trim()).filter(Boolean);
            fs.unlinkSync(command_file);
            for(const line of lines) await command(line);
        }
        poll_user_trace();
        observe_svga();
        // WIN_RATES: the SVGA3D commands per second since the last time;
        // the guest's MIPS, how often its core was halted (sampled each
        // loop) and the renderer's backlog (batches sent, not yet done)
        const svga_rates = cpu.devices.graphics_adapter && cpu.devices.graphics_adapter.device["svga"];
        if(+process.env.WIN_RATES && svga_rates && svga_rates.svga3d)
        {
            const s3 = svga_rates.svga3d, cores_now = cpu.get_diagnostics().cores, core = cores_now[0];
            rate_samples.n++;
            if(core.halted) rate_samples.halted++;
            rate_samples.backlog += s3.submitted - s3.completed;
            if(s3.completions.length) rate_samples.waiting++;
            if(performance.now() >= next_rates)
            {
                const now = performance.now(), counts = {...s3.counts}, seconds = (now - rates_at) / 1000;
                const retired = cores_now.reduce((sum, c) => sum + Number(c.retired_instructions), 0);
                if(rates_counts)
                {
                    const rates = Object.entries(counts).map(([id, n]) => [id, (n - (rates_counts[id] || 0)) / seconds]).filter(r => r[1] > 0)
                        .sort((a, b) => b[1] - a[1]).slice(0, 16).map(([id, r]) => [+id, +r.toFixed(2)]);
                    const frames = ((counts[1127] || 0) - (rates_counts[1127] || 0)) / seconds;
                    event("svga3d-rates", {s: +seconds.toFixed(1), frames: +frames.toFixed(2), mips: +((retired - rates_retired) / seconds / 1e6).toFixed(1),
                        halted: +(rate_samples.halted / rate_samples.n).toFixed(2), completions_pending: +(rate_samples.waiting / rate_samples.n).toFixed(2),
                        backlog: +(rate_samples.backlog / rate_samples.n).toFixed(1), rates});
                }
                rates_counts = counts;
                rates_retired = retired;
                rates_at = now;
                rate_samples = {n: 0, halted: 0, backlog: 0, waiting: 0};
                next_rates = now + 1000 * +process.env.WIN_RATES;
            }
        }
        if(profiler && performance.now() >= next_profile)
        {
            next_profile = performance.now() + 1000 * +process.env.WIN_CPU_PROFILE;
            await profile_window();
        }
        const text = text_screen();
        if(text && text !== text_seen) { text_seen = text; event("text", {text}); }
        // (WIN_SHOT_MS: how often; a screenshot of 1280x1024 costs the host a few per cent at 2 s)
        if(performance.now() >= next_shot)
        {
            next_shot = performance.now() + +(process.env.WIN_SHOT_MS || 2000);
            screenshot(false);
        }
        if(cpu.last_reset && cpu.last_reset.count !== resets)
        {
            resets = cpu.last_reset.count;
            event("reset", cpu.last_reset);
        }
        sample_rip();
        if(cpu.cr[4] & 1 << 5) { const cr3 = current_cr3(); seen_cr3.delete(cr3); seen_cr3.add(cr3); }
        if(performance.now() >= next_samples)
        {
            next_samples = performance.now() + 60000;
            const top = [...rip_samples].sort((a, b) => b[1] - a[1]).slice(0, 12);
            console.log("X64_WIN_RIPS " + JSON.stringify(top));
            // the code around the three most sampled RIPs (16 bytes before, 16 from)
            console.log("X64_WIN_RIP_BYTES " + JSON.stringify(top.slice(0, 3).map(([key]) => [key, rip_bytes(key)])));
            // the samples by guest module (image name and the offset of the hottest RIP in it)
            const modules = new Map();
            for(const [key, n] of rip_samples)
            {
                const rip = rip_raw.get(key);
                let name = "?";
                try { const m = rip === undefined ? null : guest_module(rip); name = m ? m.replace(/\+0x[0-9a-f]+$/, "") : key.startsWith("nt+") ? "nt" : "?"; } catch(e) {}
                modules.set(name, (modules.get(name) || 0) + n);
            }
            console.log("X64_WIN_RIP_MODULES " + JSON.stringify([...modules].sort((a, b) => b[1] - a[1]).slice(0, 16)));
            rip_raw.clear();
            if(port_counts.size)
            {
                console.log("X64_WIN_PORTS " + JSON.stringify([...port_counts].sort((a, b) => b[1] - a[1]).slice(0, 16)));
                port_counts.clear();
            }
            rip_samples.clear();
            if(process.env.WIN_STEP_PROFILE)
            {
                // interpreter steps inside page functions, by opcode (see pages.rs)
                const get = cpu.wm.exports.x64_page_profile_get;
                const name = key => (key & 0x10000 ? "rep " : "") + ["", "0F ", "0F38 ", "0F3A "][key >> 8 & 3] + (key & 0xFF).toString(16).padStart(2, "0");
                const rows = [];
                for(let key = 0; key < 0x20000; key++) { const n = get(key); if(n) rows.push([n, key]); }
                rows.sort((a, b) => b[0] - a[0]);
                console.log("X64_WIN_STEPS " + rows.slice(0, 40).map(([n, key]) => `${name(key)}:${n}`).join(" "));
                // retried instructions by opcode, and why accesses were refused
                const retries = [];
                for(let key = 0; key < 0x20000; key++) { const n = get(0x20000 + key); if(n) retries.push([n, key]); }
                retries.sort((a, b) => b[0] - a[0]);
                // the most stepped instructions: where, and their bytes
                const step_rip = cpu.wm.exports.x64_page_step_rip, hot = [];
                for(let n = 0; n < 24; n++)
                {
                    const low = step_rip(n, false, false);
                    if(low < 0) break;
                    const rip = BigInt(step_rip(n, true, false)) << 32n | BigInt(low);
                    const at = physical(current_cr3(), rip);
                    hot.push({rip: "0x" + rip.toString(16), n: step_rip(n, false, true), at: guest_module(rip),
                        bytes: at === null ? null : Buffer.from(cpu.mem8.subarray(at, at + 12)).toString("hex")});
                }
                console.log("X64_WIN_STEP_RIPS " + JSON.stringify(hot));
                console.log("X64_WIN_RETRIES " + retries.slice(0, 30).map(([n, key]) => `${name(key)}:${n}`).join(" ") +
                    " refused(cross,fault,device,code)=" + [0, 1, 2, 3].map(i => get(0x40000 + i)).join(",") + " unserved_steps=" + get(0x40004) + " retries_pe_clear=" + get(0x40005) + " late_entries(call,aligned,other)=" + [6, 7, 8].map(i => get(0x40000 + i)).join(","));
            }
        }
        if(performance.now() >= next_report)
        {
            next_report = performance.now() + 15000;
            console.log("X64_WIN_PROGRESS " + JSON.stringify({s: elapsed(), screen: last_hash, dark: +dark_fraction.toFixed(2), colors, mode: last_mode, ...stats()}));
        }
        // Sign in once the graphical session has settled. Boot screens are
        // almost entirely black; the lock screen is a full-screen picture,
        // shown first as a plain colour while it loads (keys pressed then
        // are lost). Sign in once a many-coloured screen has been stable.
        if(!signed_in && last_mode && last_mode[0] >= 800 && dark_fraction < 0.6 && colors >= 12 && performance.now() - last_change > 3000 && !process.env.WIN_MANUAL)
        {
            await sign_in();
            signed_in = true;
            probe_sent = performance.now() + 60000;
        }
        if(signed_in && performance.now() > probe_sent && !process.env.WIN_MANUAL)
        {
            if(!desktop_visible())
            {
                // lock screen (sign-in lost, or locked after idling with the
                // display off), password box, or still signing in
                // (WIN_NO_PROBE: a full-screen program hides the desktop for
                // long; only a password box means the session is locked)
                if(password_box_visible() || !process.env.WIN_NO_PROBE && performance.now() - last_sign_in > 180000) await sign_in();
                probe_sent = performance.now() + 20000;
            }
            else if(!process.env.WIN_OVERLAY_SAVE && !process.env.WIN_STOP_AT_DESKTOP && !process.env.WIN_IDLE && !process.env.WIN_CPULOAD32 && !process.env.WIN_NO_PROBE)
            {
                const arch = report.results[64] ? 32 : 64;
                const started = await run_command(`cmd /c for %d in (d e f g h) do @if exist %d:\\probe${arch}.exe %d:\\probe${arch}.exe`);
                // WOW64 start-up is slow; one attempt at a time
                probe_sent = performance.now() + (started ? 600000 : 20000);
            }
        }
        for(const arch of [64, 32])
        {
            const text = result_text(`RESULT${arch}.TXT`);
            // WIN_PROBE_SNAPSHOT: once the AVX part runs (threads with their
            // YMM fingerprints), save and restore the machine in place
            if(+process.env.WIN_PROBE_SNAPSHOT && text.includes(`X64_WIN_AVX_START arch=${arch}`) && !snapshots_taken.includes(arch))
            {
                snapshots_taken.push(arch);
                await vm.stop();
                const state = await vm.save_state();
                await vm.restore_state(state);
                vm.run();
                event("probe-snapshot", {arch, bytes: state.byteLength});
            }
            const match = text.match(/X64_WIN_DONE arch=(\d+) processors=(\d+) packages=(\d+) cores=(\d+) smt_cores=(\d+) progress=(\d+) failures=(\d+) apic_ids=(\w+) high_block=(\w+) checks=([\d,]+)\r?\n/);
            if(match && !report.results[arch])
            {
                const avx = text.match(/X64_WIN_AVX arch=\d+ avx=(\d)(?: avx2=(\d) fma=(\d) threads=(\d+) steps=(\d+) faults=(\d+) xstate=(\d+) compute_bad=(\d+) bad=(\d+))?/);
                // (QueryPerformanceFrequency: the HPET's 14318180 Hz, the ACPI
                // PM timer's 3579545 Hz, else the TSC; docs/jit-unification-plan.md
                // open question 4)
                const qpf = text.match(/X64_WIN_BEGIN arch=\d+ processors=\d+ architecture=\d+ qpf=(\w+)/);
                report.results[arch] = {qpf: qpf ? parseInt(qpf[1], 16) : null,
                    qpc_source: qpf ? {14318180: "hpet", 3579545: "acpi-pm-timer"}[parseInt(qpf[1], 16)] ?? "tsc" : null,
                    processors: +match[2], packages: +match[3], cores: +match[4], smt_cores: +match[5],
                    progress: +match[6], failures: +match[7], apic_ids: match[8], high_block: match[9],
                    avx: avx && (avx[2] === undefined ? {avx: 0} : {avx: 1, avx2: +avx[2], fma: +avx[3], threads: +avx[4], steps: +avx[5],
                        faults: +avx[6], xstate: +avx[7], compute_bad: +avx[8], bad: +avx[9]}), text};
                event("probe", {arch, result: report.results[arch]});
                probe_sent = performance.now() + 2000;
            }
        }
        if(report.results[64] && report.results[32]) break;
        if(signed_in && !report.desktop_s && desktop_visible())
        {
            report.desktop_s = elapsed();
            event("desktop");
            // (tools/bench/jit_stats.mjs, docs/jit-unification-plan.md P0.7)
            if(jit_stats_enabled()) print_jit_stats(vm, {script: "windows_boot", phase: "desktop", wasm: process.env.WASM_PATH || null, desktop_s: report.desktop_s, cores});
            for(let attempt = 0; process.env.WIN_LAUNCHER && !launcher_ready && attempt < 4; attempt++)
            {
                if(process.env.WIN_LAUNCHER_ADMIN) await run_admin(process.env.WIN_LAUNCHER);
                else await run_command(process.env.WIN_LAUNCHER);
                for(const limit = performance.now() + 60000; performance.now() < limit && !launcher_ready;) await delay(500);
                event(launcher_ready ? "launcher" : "launcher-retry");
            }
            // WIN_SETUP: commands separated by ";;" once the desktop shows
            // (e.g. "runadmin E:\\INSTVM3D.CMD;;wait 300;;shot"), before
            // WIN_OVERLAY_SAVE shuts down and keeps what they did
            for(const line of (process.env.WIN_SETUP || "").split(";;").map(line => line.trim()).filter(Boolean))
            {
                await command(line);
            }
            if(process.env.WIN_SETUP && !process.env.WIN_OVERLAY_SAVE) break;
            if(process.env.WIN_OVERLAY_SAVE) shutdown_at = performance.now() + 30000;
            else if(process.env.WIN_IDLE) idle_at = performance.now() + 1000 * +(process.env.WIN_IDLE_SETTLE_S || 20);
            else if(process.env.WIN_CPULOAD32) load32_at = performance.now() + 1000 * +(process.env.WIN_IDLE_SETTLE_S || 20);
            else if(process.env.WIN_DESKTOP_TEST)
            {
                // desktop responsiveness: open programs one after another
                // (Win+R latency each time), screenshots after each
                await delay(15000);
                for(const program of ["notepad", "calc", "control", "explorer", "notepad"])
                {
                    await run_command(program);
                    await delay(12000);
                    screenshot(true);
                }
                break;
            }
            else if(process.env.WIN_STOP_AT_DESKTOP) break;
        }
        if(idle_at && performance.now() >= idle_at && !idle_sent)
        {
            host_window();
            next_host_window = performance.now() + 10000;
            idle_sent = await run_command(`cmd /c for %d in (d e f g h) do @if exist %d:\\cpuload.exe %d:\\cpuload.exe ${+process.env.WIN_IDLE_ROUNDS || 6}`);
            if(!idle_sent) idle_at = performance.now() + 20000;
        }
        if(load32_at && performance.now() >= load32_at && !load32_sent)
        {
            load32_sent = await run_command(`cmd /c for %d in (d e f g h) do @if exist %d:\\load32.exe %d:\\load32.exe ${+process.env.WIN_CPULOAD32 || 5}`);
            if(!load32_sent) load32_at = performance.now() + 20000;
        }
        if(load32_sent)
        {
            const load = result_text("LOAD32.TXT");
            if(load.includes("CPULOAD32_DONE"))
            {
                const rounds = [...load.matchAll(/round (\d+) ms=(\d+) checksum=([0-9a-f]+)/g)].map(m => ({ms: +m[2], checksum: m[3]}));
                // (the median and the fastest leave out the first round, which
                // also compiles; the fastest is what the gate compares: a
                // fresh desktop's background work slows other rounds)
                const warm = rounds.slice(1).map(r => r.ms).sort((a, b) => a - b);
                report.cpuload32 = {wow64: /wow64=1/.test(load), rounds, median_ms: warm[warm.length >> 1] ?? rounds[0]?.ms, min_ms: warm[0] ?? rounds[0]?.ms};
                console.log("X64_WIN_CPULOAD32 " + JSON.stringify(report.cpuload32));
                break;
            }
        }
        if(idle_sent && performance.now() >= next_host_window)
        {
            host_window();
            next_host_window += 10000;
        }
        if(idle_sent)
        {
            const load = result_text("CPULOAD.TXT");
            if(load.includes("CPULOAD_DONE"))
            {
                report.cpuload = load;
                console.log(load);
                break;
            }
        }
        // WIN_OVERLAY_SAVE: after the desktop has settled, a full (not
        // hybrid) shutdown; the overlay is saved once the guest is off
        if(shutdown_at && performance.now() >= shutdown_at && !shutdown_sent)
        {
            shutdown_sent = await run_command(process.env.WIN_SHUTDOWN_COMMAND || "shutdown /s /t 0");
            if(!shutdown_sent) shutdown_at = performance.now() + 20000;
            else shutdown_deadline = performance.now() + 900000;
        }
        if(shutdown_sent && powered_off)
        {
            event("power-off", {state: powered_off});
            save_overlay(process.env.WIN_OVERLAY_SAVE);
            event("overlay-saved", {sectors: source.overlay.size});
            break;
        }
        assert.ok(!shutdown_deadline || performance.now() < shutdown_deadline, "the guest powered off");
    }
    // (the probes run in plain qualification runs, not in setup sessions)
    for(const arch of process.env.WIN_STOP_AT_DESKTOP || process.env.WIN_IDLE || process.env.WIN_CPULOAD32 || process.env.WIN_SETUP || process.env.WIN_HDB ? [] : [64, 32])
    {
        const r = report.results[arch];
        assert.ok(r, `probe ${arch} completed`);
        assert.equal(r.failures, 0, `probe ${arch} failures`);
        assert.equal(r.processors, cores);
        assert.equal(r.packages, 1); assert.equal(r.cores, cores); assert.equal(r.smt_cores, 0);
        assert.equal(r.progress, cores * 64);
        if(arch === 64) assert.ok(BigInt("0x" + r.high_block) >> 32n > 0n, "x64 top-down allocation above 4 GiB");
        // the YMM state (docs/simd-xsave-plan.md 11.3): 8 rounds of 3 steps
        // (one migrates, one faults) on 2N threads; x64 GetThreadContext
        const features = win_cpu_features || [];
        assert.ok(r.avx, `probe ${arch}: AVX line`);
        if(features.includes("AVX"))
        {
            assert.deepEqual(r.avx, {avx: 1, avx2: +features.includes("AVX2"), fma: +features.includes("FMA"), threads: 2 * cores,
                steps: 48 * cores, faults: 16 * cores, xstate: arch === 64 ? 1 : 0, compute_bad: 0, bad: 0}, `probe ${arch}: YMM state`);
            if(+process.env.WIN_PROBE_SNAPSHOT) assert.ok(snapshots_taken.includes(arch), `probe ${arch}: snapshot during the AVX part`);
        }
        else assert.equal(r.avx.avx, 0, `probe ${arch}: no AVX without the feature`);
    }
    if(process.env.WIN_STOP_AT_DESKTOP) assert.ok(report.desktop_s, "desktop reached");
    if(process.env.WIN_IDLE) assert.ok(report.cpuload, "CPULOAD.EXE completed");
    if(process.env.WIN_CPULOAD32) assert.ok(report.cpuload32?.wow64 && report.cpuload32.rounds.length, "LOAD32.EXE (CPULOAD32) completed under WOW64");
    report.passed = true;
    console.log("X64_WIN_PASS " + JSON.stringify(report.results));
}
catch(error)
{
    report.passed = false;
    report.error = String(error?.stack || error);
    console.error("X64_WIN_FAILURE " + report.error);
    process.exitCode = 1;
}
finally
{
    if(remote_renderer)
    {
        console.log("X64_WIN_RENDERER " + JSON.stringify(remote_renderer.stats));
        remote_renderer.close();
    }
    if(profiler) await profile_window();
    if(cpu && jit_stats_enabled()) print_jit_stats(vm, {script: "windows_boot", phase: "end", s: elapsed(), wasm: process.env.WASM_PATH || null, desktop_s: report.desktop_s ?? null, cores});
    if(cpu && process.env.WIN_SIZE_STATS) cpu.wm.exports.x64_pagegen_size_dump();
    if(cpu && process.env.WIN_RECORD)
    {
        const e = cpu.wm.exports, chunks = [];
        for(let i = 0, n = e.x64_page_record_count(); i < n; i++)
        {
            const length = Buffer.alloc(4);
            length.writeUInt32LE(e.x64_page_record_length(i));
            chunks.push(length, Buffer.from(new Uint8Array(cpu.wasm_memory.buffer, e.x64_page_record_address(i) >>> 0, e.x64_page_record_length(i))));
        }
        fs.writeFileSync(process.env.WIN_RECORD, Buffer.concat(chunks));
        console.log(`X64_WIN_RECORD ${chunks.length / 2} records`);
    }
    // WIN_DUMP_OVERLAY=<file>: the sectors written so far (no shutdown: what
    // the guest had flushed), e.g. to read setupapi.dev.log
    if(process.env.WIN_DUMP_OVERLAY) save_overlay(process.env.WIN_DUMP_OVERLAY);
    // WIN_DUMP_IMAGES=ci,ntkrnlmp: those guest modules (named as in
    // modules.json) as mapped in memory, to <out>/<name>@<base>.bin
    for(const name of cpu ? (process.env.WIN_DUMP_IMAGES || "").split(",").filter(Boolean) : [])
    {
        const entry = Object.entries(page_modules).find(([, where]) => where && where.split("+")[0] === name);
        if(!entry) continue;
        const base = BigInt("0x" + entry[0]) - BigInt(entry[1].split("+")[1]);
        const cr3 = current_cr3(), at = physical(cr3, base);
        if(at === null) continue;
        const pe = base + BigInt(cpu.mem8[at + 0x3C] | cpu.mem8[at + 0x3D] << 8);
        const size_at = physical(cr3, pe + 24n + 56n);
        const size = new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset + size_at, 4).getUint32(0, true);
        const image = Buffer.alloc(size);
        for(let offset = 0; offset < size; offset += 4096)
        {
            const page = physical(cr3, base + BigInt(offset));
            if(page !== null) image.set(cpu.mem8.subarray(page, page + Math.min(4096, size - offset)), offset);
        }
        fs.writeFileSync(path.join(out, `${name}@${base.toString(16)}.bin`), image);
    }
    if(cpu) { report.final = stats(); screenshot(true); report.text_screen = text_screen(); }
    await vm.stop();
    const final_stat = fs.statSync(image_path);
    assert.equal(final_stat.mtimeMs, source_stat.mtimeMs, "the source image was never written");
    if(hdb_path) assert.equal(fs.statSync(hdb_path).mtimeMs, hdb_stat.mtimeMs, "the second disk's image was never written");
    report.wall_s = elapsed();
    fs.writeFileSync(path.join(out, `result-${jit ? "page" : "interpreter"}-${cores}c${report.parallel ? "-parallel" : ""}.json`),
        JSON.stringify(report, null, 1));
    fs.writeFileSync(path.join(out, "tools-final.img"), tools.bytes);
    await vm.destroy();
    source.close();
    if(hdb_path) hdb.close();
}
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      source/v64/tests/x64/windows_cpuload.c                                                              0000644 0000000 0000000 00000024166 00000000000 015025  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Desktop CPU load, as Windows itself accounts it (the numbers Task
 * Manager shows): per-processor idle/kernel/user/DPC/interrupt time and the
 * processes and threads that used the processor, over windows of WINDOW_MS
 * (6, or the number given on the command line). No CRT; x64 only. Results
 * go beside the executable (CPULOAD.TXT), one flushed block per window, then
 * CPULOAD_DONE. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define WINDOW_MS 10000
#define MAX_CPUS 8
#define TRACKED 1024
typedef LONG (WINAPI *query_fn)(ULONG, void *, ULONG, ULONG *);
typedef LONG (WINAPI *resolution_fn)(ULONG *, ULONG *, ULONG *);
static HANDLE result;
static query_fn query;
static void text(const char *s) { DWORD n = 0, wrote; while(s[n]) n++; WriteFile(result, s, n, &wrote, 0); }
static void number(unsigned long long n) { char b[24]; int i = 23; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); text(b + i); }
static void hex(unsigned long long n) { char b[20]; int i = 19; b[i] = 0; do { b[--i] = "0123456789abcdef"[n & 15]; n >>= 4; } while(n); text(b + i); }
/* tenths of a percent of a total */
static void permille(unsigned long long part, unsigned long long total)
{
    unsigned long long p = total ? part * 1000 / total : 0;
    number(p / 10); text("."); number(p % 10); text("%");
}
static void wide(const WCHAR *s, USHORT bytes)
{
    char b[64]; DWORD n = 0;
    for(; n < bytes / 2 && n < 63; n++) b[n] = s[n] < 128 ? (char)s[n] : '?';
    b[n] = 0;
    text(n ? b : "Idle");
}
/* SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION (class 8) */
typedef struct { LARGE_INTEGER idle, kernel, user, dpc, interrupt; ULONG interrupts; ULONG pad; } processor_times;
/* SYSTEM_INTERRUPT_INFORMATION (class 23) */
typedef struct { ULONG context_switches, dpc_count, dpc_rate, time_increment, dpc_bypass, apc_bypass; } interrupt_info;
static processor_times cpu_before[MAX_CPUS], cpu_after[MAX_CPUS];
static interrupt_info irq_before[MAX_CPUS], irq_after[MAX_CPUS];
/* per process and per thread: (id, 100 ns units) from the previous window */
typedef struct { unsigned long long id, time, cycles; } sample;
static sample processes[TRACKED], threads[TRACKED];
static DWORD process_count, thread_count;
static unsigned char buffer[1 << 20];
static unsigned long long previous(sample *table, DWORD count, unsigned long long id, unsigned long long *cycles)
{
    for(DWORD i = 0; i < count; i++) if(table[i].id == id) { if(cycles) *cycles = table[i].cycles; return table[i].time; }
    if(cycles) *cycles = 0;
    return 0;
}
typedef struct { unsigned long long delta, cycles, id, start; const WCHAR *name; USHORT name_bytes; } row;
static row top_processes[16], top_threads[16];
static void keep(row *top, row entry)
{
    for(int i = 0; i < 16; i++)
    {
        if(entry.delta > top[i].delta)
        {
            for(int j = 15; j > i; j--) top[j] = top[j - 1];
            top[i] = entry;
            return;
        }
    }
}
/* offsets in SYSTEM_PROCESS_INFORMATION / SYSTEM_THREAD_INFORMATION (x64) */
#define P_NEXT 0
#define P_THREADS 4
#define P_CYCLES 24
#define P_USER 40
#define P_KERNEL 48
#define P_NAME_LENGTH 56
#define P_NAME_BUFFER 64
#define P_PID 80
#define P_SIZE 0x100
#define T_KERNEL 0
#define T_USER 8
#define T_START 32
#define T_TID 48
#define T_SIZE 0x50
static int snapshot(int report, unsigned long long window)
{
    ULONG length = 0;
    if(query(5, buffer, sizeof(buffer), &length) < 0) return 0;
    static sample next_processes[TRACKED], next_threads[TRACKED];
    DWORD next_process_count = 0, next_thread_count = 0;
    for(int i = 0; i < 16; i++) { top_processes[i].delta = 0; top_threads[i].delta = 0; }
    for(unsigned char *p = buffer;; p += *(ULONG *)(p + P_NEXT))
    {
        unsigned long long pid = *(unsigned long long *)(p + P_PID);
        unsigned long long time = *(unsigned long long *)(p + P_USER) + *(unsigned long long *)(p + P_KERNEL);
        unsigned long long cycles = *(unsigned long long *)(p + P_CYCLES), cycles_before;
        const WCHAR *name = *(const WCHAR **)(p + P_NAME_BUFFER);
        USHORT name_bytes = *(USHORT *)(p + P_NAME_LENGTH);
        unsigned long long before = previous(processes, process_count, pid, &cycles_before);
        if(report) keep(top_processes, (row){time - before, cycles - cycles_before, pid, 0, name, name_bytes});
        if(next_process_count < TRACKED) next_processes[next_process_count++] = (sample){pid, time, cycles};
        ULONG count = *(ULONG *)(p + P_THREADS);
        for(ULONG t = 0; t < count; t++)
        {
            unsigned char *thread = p + P_SIZE + t * T_SIZE;
            unsigned long long tid = *(unsigned long long *)(thread + T_TID);
            unsigned long long ttime = *(unsigned long long *)(thread + T_USER) + *(unsigned long long *)(thread + T_KERNEL);
            unsigned long long tbefore = previous(threads, thread_count, tid, 0);
            /* (the idle threads all have id 0: report them per processor above) */
            if(report && pid) keep(top_threads, (row){ttime - tbefore, 0, pid << 32 | tid, *(unsigned long long *)(thread + T_START), name, name_bytes});
            if(next_thread_count < TRACKED) next_threads[next_thread_count++] = (sample){tid, ttime, 0};
        }
        if(!*(ULONG *)(p + P_NEXT)) break;
    }
    for(DWORD i = 0; i < next_process_count; i++) processes[i] = next_processes[i];
    for(DWORD i = 0; i < next_thread_count; i++) threads[i] = next_threads[i];
    process_count = next_process_count;
    thread_count = next_thread_count;
    if(!report) return 1;
    text(" processes (share of all processors' time; kernel+user; cycles):\r\n");
    for(int i = 0; i < 16 && top_processes[i].delta; i++)
    {
        text("  "); permille(top_processes[i].delta, window); text(" "); wide(top_processes[i].name, top_processes[i].name_bytes);
        text(" pid="); number(top_processes[i].id); text(" cycles="); number(top_processes[i].cycles); text("\r\n");
    }
    text(" threads:\r\n");
    for(int i = 0; i < 16 && top_threads[i].delta; i++)
    {
        text("  "); permille(top_threads[i].delta, window); text(" "); wide(top_threads[i].name, top_threads[i].name_bytes);
        text(" pid="); number(top_threads[i].id >> 32); text(" tid="); number(top_threads[i].id & 0xFFFFFFFF);
        text(" start=0x"); hex(top_threads[i].start); text("\r\n");
    }
    return 1;
}
static void finish(DWORD code) { FlushFileBuffers(result); CloseHandle(result); ExitProcess(code); }
void entry(void)
{
    char path[MAX_PATH];
    GetModuleFileNameA(0, path, sizeof(path));
    DWORD at = 0, last = 0;
    while(path[at]) { if(path[at] == '\\') last = at + 1; at++; }
    const char name[] = "CPULOAD.TXT";
    for(at = 0; at < sizeof(name); at++) path[last + at] = name[at];
    result = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    if(result == INVALID_HANDLE_VALUE) ExitProcess(10);
    HMODULE ntdll = GetModuleHandleA("ntdll.dll");
    query = (query_fn)GetProcAddress(ntdll, "NtQuerySystemInformation");
    resolution_fn resolution = (resolution_fn)GetProcAddress(ntdll, "NtQueryTimerResolution");
    if(!query) finish(11);
    int rounds = 0;
    for(const char *c = GetCommandLineA(); *c; c++) rounds = *c >= '0' && *c <= '9' ? rounds * 10 + (*c - '0') : 0;
    if(rounds <= 0) rounds = 6;
    SYSTEM_INFO info;
    GetNativeSystemInfo(&info);
    DWORD cpus = info.dwNumberOfProcessors > MAX_CPUS ? MAX_CPUS : info.dwNumberOfProcessors;
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    ULONG coarsest = 0, finest = 0, current = 0;
    if(resolution) resolution(&coarsest, &finest, &current);
    text("CPULOAD_BEGIN processors="); number(cpus); text(" qpc_hz="); number(frequency.QuadPart);
    text(" timer_100ns(coarsest,finest,current)="); number(coarsest); text(","); number(finest); text(","); number(current);
    text(" uptime_ms="); number(GetTickCount64()); text("\r\n");
    FlushFileBuffers(result);
    ULONG length;
    query(8, cpu_before, sizeof(processor_times) * cpus, &length);
    query(23, irq_before, sizeof(interrupt_info) * cpus, &length);
    snapshot(0, 0);
    for(int round = 0; round < rounds; round++)
    {
        LARGE_INTEGER q0, q1;
        QueryPerformanceCounter(&q0);
        Sleep(WINDOW_MS);
        QueryPerformanceCounter(&q1);
        query(8, cpu_after, sizeof(processor_times) * cpus, &length);
        query(23, irq_after, sizeof(interrupt_info) * cpus, &length);
        unsigned long long all = 0, idle_all = 0;
        text("CPULOAD_WINDOW round="); number(round); text(" qpc_ms="); number((q1.QuadPart - q0.QuadPart) * 1000 / frequency.QuadPart);
        text(" uptime_ms="); number(GetTickCount64()); text("\r\n");
        for(DWORD c = 0; c < cpus; c++)
        {
            /* kernel time includes idle time */
            unsigned long long idle = cpu_after[c].idle.QuadPart - cpu_before[c].idle.QuadPart;
            unsigned long long kernel = cpu_after[c].kernel.QuadPart - cpu_before[c].kernel.QuadPart;
            unsigned long long user = cpu_after[c].user.QuadPart - cpu_before[c].user.QuadPart;
            unsigned long long dpc = cpu_after[c].dpc.QuadPart - cpu_before[c].dpc.QuadPart;
            unsigned long long interrupt = cpu_after[c].interrupt.QuadPart - cpu_before[c].interrupt.QuadPart;
            unsigned long long total = kernel + user;
            all += total; idle_all += idle;
            text(" cpu"); number(c); text(" busy="); permille(total - idle, total);
            text(" user="); permille(user, total); text(" kernel="); permille(kernel - idle, total);
            text(" dpc="); permille(dpc, total); text(" interrupt="); permille(interrupt, total);
            text(" interrupts="); number(cpu_after[c].interrupts - cpu_before[c].interrupts);
            text(" dpcs="); number(irq_after[c].dpc_count - irq_before[c].dpc_count);
            text(" switches="); number(irq_after[c].context_switches - irq_before[c].context_switches);
            text(" total_ms="); number(total / 10000); text("\r\n");
            cpu_before[c] = cpu_after[c];
            irq_before[c] = irq_after[c];
        }
        text(" all busy="); permille(all - idle_all, all); text("\r\n");
        snapshot(1, all);
        FlushFileBuffers(result);
    }
    text("CPULOAD_DONE\r\n");
    finish(0);
}
                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/tests/x64/windows_cpuload32.c                                                            0000644 0000000 0000000 00000013445 00000000000 015170  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* CPULOAD32 (docs/jit-unification-plan.md P0.12): a timed 32-bit workload
 * for WOW64. Fixed work per round (about 250M instructions, 1.5-2 s at the
 * emulator's speed in 2026-10; the first round also compiles): integer mixing, a pointer chase over
 * 1 MiB, sorting through a comparison function, indirect calls, string
 * copies, and system calls (NtQueryPerformanceCounter through WOW64's
 * thunks, about one per 1000 instructions of the round). Each round's time
 * (QueryPerformanceCounter, ms) and the checksum go beside the executable
 * (LOAD32.TXT: the tools disk is FAT16 with 8.3 names, as is the program's,
 * LOAD32.EXE), one flushed line per round, then CPULOAD32_DONE; the
 * guest's clock runs with the emulator, so a round's time measures how fast
 * the emulator runs WOW64 code. No CRT; i686 (i686-w64-mingw32-gcc). Rounds:
 * 5, or the number given on the command line. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
typedef unsigned int u32;
static HANDLE result;
static void text(const char *s) { DWORD n = 0, wrote; while(s[n]) n++; WriteFile(result, s, n, &wrote, 0); }
/* (32-bit arithmetic only: no libgcc for 64-bit division) */
static void number(u32 n) { char b[12]; int i = 11; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); text(b + i); }
static void hex(u32 n) { char b[12]; int i = 11; b[i] = 0; do { b[--i] = "0123456789abcdef"[n & 15]; n >>= 4; } while(n); text(b + i); }
static void finish(DWORD code) { FlushFileBuffers(result); CloseHandle(result); ExitProcess(code); }
static u32 seed = 1;
static u32 lcg(void) { return seed = seed * 1664525u + 1013904223u; }
static u32 mix(u32 h, u32 v) { return (h ^ v) * 0x01000193u; }

#define CHASE (1 << 18)
static u32 next[CHASE];
static u32 values[4096];
static char text_a[4096], text_b[4096];
static int compare(const void *a, const void *b) { u32 x = *(const u32 *)a, y = *(const u32 *)b; return x < y ? -1 : x > y; }
/* (an insertion sort below 16, quicksort above: calls through the pointer) */
static void sort(u32 *v, int n, int (*less)(const void *, const void *))
{
    while(n > 16)
    {
        u32 pivot = v[n / 2];
        int i = 0, j = n - 1;
        for(;;)
        {
            while(less(&v[i], &pivot) < 0) i++;
            while(less(&pivot, &v[j]) < 0) j--;
            if(i >= j) break;
            u32 t = v[i]; v[i] = v[j]; v[j] = t;
            i++; j--;
        }
        sort(v, j + 1, less);
        v += j + 1; n -= j + 1;
    }
    for(int i = 1; i < n; i++)
    {
        u32 x = v[i]; int j = i;
        for(; j > 0 && less(&x, &v[j - 1]) < 0; j--) v[j] = v[j - 1];
        v[j] = x;
    }
}
static u32 op_add(u32 a, u32 b) { return a + b * 3; }
static u32 op_xor(u32 a, u32 b) { return (a ^ b) >> 1 | a << 31; }
static u32 op_mul(u32 a, u32 b) { return a * (b | 1); }
static u32 op_sub(u32 a, u32 b) { return a - (b >> 3); }
static u32 (*const ops[4])(u32, u32) = { op_add, op_xor, op_mul, op_sub };

static u32 round_work(u32 h)
{
    LARGE_INTEGER t;
    for(int pass = 0; pass < 128; pass++)
    {
        /* integer mixing */
        for(u32 i = 0; i < 200000; i++) h = mix(h, i * 2654435761u + (h >> 7));
        /* a pointer chase over a random cycle */
        u32 p = h & (CHASE - 1);
        for(u32 i = 0; i < 200000; i++) { p = next[p]; h += p; }
        /* sorting through a comparison function */
        for(int i = 0; i < 4096; i++) values[i] = lcg();
        sort(values, 4096, compare);
        h = mix(h, values[h & 4095]);
        /* indirect calls */
        for(u32 i = 0; i < 100000; i++) h = ops[(h ^ i) & 3](h, i);
        /* string copies (REP MOVS) */
        for(int i = 0; i < 64; i++)
        {
            u32 n = 1024 + (lcg() & 2047), d = lcg() & 1023, s = lcg() & 1023, count = n;
            char *to = text_b + d;
            const char *from = text_a + s;
            __asm__ volatile("rep movsb" : "+D"(to), "+S"(from), "+c"(count) : : "memory");
            h = mix(h, (u32)text_b[(d + n / 2) & 4095]);
        }
        /* system calls through WOW64 (the checksum does not see the time) */
        for(int i = 0; i < 400; i++) { QueryPerformanceCounter(&t); h += t.QuadPart != 0; }
    }
    return h;
}

void __attribute__((stdcall)) entry(void)
{
    char path[MAX_PATH];
    GetModuleFileNameA(0, path, sizeof(path));
    DWORD at = 0, last = 0;
    while(path[at]) { if(path[at] == '\\') last = at + 1; at++; }
    const char name[] = "LOAD32.TXT";
    for(at = 0; at < sizeof(name); at++) path[last + at] = name[at];
    result = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    if(result == INVALID_HANDLE_VALUE) ExitProcess(10);
    int rounds = 0;
    for(const char *c = GetCommandLineA(); *c; c++) rounds = *c >= '0' && *c <= '9' ? rounds * 10 + (*c - '0') : 0;
    if(rounds <= 0) rounds = 5;
    /* a random cycle through CHASE slots */
    for(u32 i = 0; i < CHASE; i++) next[i] = i;
    for(u32 i = CHASE - 1; i > 0; i--) { u32 j = lcg() % i, t = next[i]; next[i] = next[j]; next[j] = t; }
    for(int i = 0; i < 4096; i++) text_a[i] = (char)lcg();
    BOOL wow64 = FALSE;
    IsWow64Process(GetCurrentProcess(), &wow64);
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    text("CPULOAD32 wow64="); number(wow64); text(" frequency="); number(frequency.LowPart); text("\r\n");
    /* (QPC frequencies are below 2^32 and a round lasts less than 2^32 ticks) */
    u32 per_ms = frequency.LowPart / 1000;
    u32 h = 0;
    for(int r = 0; r < rounds; r++)
    {
        LARGE_INTEGER start, end;
        seed = 1;
        QueryPerformanceCounter(&start);
        h = round_work(h);
        QueryPerformanceCounter(&end);
        text("round "); number(r); text(" ms="); number((u32)(end.QuadPart - start.QuadPart) / per_ms);
        text(" checksum="); hex(h); text("\r\n");
        FlushFileBuffers(result);
    }
    text("CPULOAD32_DONE\r\n");
    finish(0);
}
                                                                                                                                                                                                                           source/v64/tests/x64/windows_probe.c                                                                0000644 0000000 0000000 00000034660 00000000000 014505  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* Windows x64 qualification probe, built twice: x86_64 (native) and i686
 * (runs under WOW64, i.e. compatibility-mode code). No CRT. Results go
 * beside the executable on the disposable FAT16 test disk.
 *
 * Checks: the processor count and topology reported by the Windows
 * topology API (one package, N cores, one thread per core), threads pinned
 * to every processor run there (APIC ID from CPUID), interlocked work adds
 * up exactly, and (x64) memory placed above 4 GiB of virtual address space
 * is usable.
 *
 * AVX (docs/simd-xsave-plan.md 11.3, P12), when CPUID reports OSXSAVE and AVX
 * and XGETBV(0) has the SSE and AVX state: twice as many threads as
 * processors each hold a fingerprint in every YMM register (16 in the x64
 * probe, 8 under WOW64) while they spin, migrate to every processor in turn,
 * and fault on UD2, which a vectored exception handler skips; the registers
 * must be unchanged after each step. The x64 probe also suspends a thread
 * spinning with its fingerprint and reads its YMM state with GetThreadContext
 * (CONTEXT_XSTATE). With AVX2 and FMA, arithmetic on ymm registers is
 * compared with the same done in scalar code. One more line: X64_WIN_AVX. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef _WIN64
#define ARCH "64"
#else
#define ARCH "32"
#endif
#define ROUNDS 64
static HANDLE result;
static volatile LONG shared_total, failed;
static DWORD system_cpus, checks[8], apic_seen[8];
static HANDLE threads[8];
static void text(const char *s) { DWORD n = 0, wrote; while(s[n]) n++; WriteFile(result, s, n, &wrote, 0); }
static void number(DWORD n) { char b[12]; int i = 11; b[i] = 0; do { b[--i] = '0' + n % 10; n /= 10; } while(n); text(b + i); }
static void hex(unsigned long long n) { char b[20]; int i = 19; b[i] = 0; do { b[--i] = "0123456789abcdef"[n & 15]; n >>= 4; } while(n); text(b + i); }
static DWORD apic_id(void) { DWORD a = 1, b, c = 0, d; __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d)); return b >> 24; }
static DWORD WINAPI worker(void *argument)
{
    DWORD id = (DWORD)(DWORD_PTR)argument;
    for(DWORD round = 0; round < ROUNDS; round++)
    {
        DWORD target = (id + round) % system_cpus;
        if(!SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR)1 << target)) InterlockedIncrement(&failed);
        Sleep(0);
        DWORD seen = apic_id();
        if(seen >= 8) InterlockedIncrement(&failed);
        else InterlockedOr((LONG *)&apic_seen[target], 1 << seen);
        DWORD sum = 0, expected = 0;
        for(DWORD i = 1; i <= 1000; i++) sum += i ^ round;
        for(DWORD i = 1000; i; i--) expected += i ^ round;
        if(sum != expected || apic_id() != seen) InterlockedIncrement(&failed);
        InterlockedIncrement(&shared_total);
        checks[id]++;
    }
    return 0;
}
static void finish(DWORD code) { FlushFileBuffers(result); CloseHandle(result); ExitProcess(code); }

/* AVX: the steps load every YMM register from `in`, fault on UD2 when
 * `fault` (the handler skips it), spin, and store them to `out` */
#ifdef _WIN64
#define YMM_REGS 16
#define LOADS(n) "vmovdqu " #n "*32(%[in]),%%ymm" #n "\n"
#define STORES(n) "vmovdqu %%ymm" #n "," #n "*32(%[out])\n"
#define ALL(f) f(0) f(1) f(2) f(3) f(4) f(5) f(6) f(7) f(8) f(9) f(10) f(11) f(12) f(13) f(14) f(15)
#define YMM_CLOBBERS "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"
#else
#define YMM_REGS 8
#define LOADS(n) "vmovdqu " #n "*32(%[in]),%%ymm" #n "\n"
#define STORES(n) "vmovdqu %%ymm" #n "," #n "*32(%[out])\n"
#define ALL(f) f(0) f(1) f(2) f(3) f(4) f(5) f(6) f(7)
/* (the i686 build has no SSE: the compiler keeps nothing in XMM registers) */
#define YMM_CLOBBERS "memory"
#endif
#ifdef _WIN64
#define XMM0_3 , "xmm0", "xmm1", "xmm2", "xmm3"
#else
#define XMM0_3
#endif
static void ymm_step(const unsigned char *in, unsigned char *out, DWORD fault, DWORD spin)
{
    __asm__ volatile(ALL(LOADS)
        "test %[fault],%[fault]\n" "jz 1f\n" "ud2\n" "1:\n"
        "2: dec %[spin]\n" "jnz 2b\n"
        ALL(STORES)
        : [spin] "+r"(spin) : [in] "r"(in), [out] "r"(out), [fault] "r"(fault) : "memory", "cc", YMM_CLOBBERS);
}
#define AVX_ROUNDS 8
#define AVX_SPIN 2000000
static volatile LONG avx_steps, avx_faults, avx_bad;
static DWORD avx_threads;
static unsigned char ymm_in[16][YMM_REGS * 32] __attribute__((aligned(32))), ymm_out[16][YMM_REGS * 32] __attribute__((aligned(32)));
static LONG CALLBACK on_fault(EXCEPTION_POINTERS *e)
{
    if(e->ExceptionRecord->ExceptionCode != EXCEPTION_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH;
#ifdef _WIN64
    e->ContextRecord->Rip += 2;
#else
    e->ContextRecord->Eip += 2;
#endif
    InterlockedIncrement(&avx_faults);
    return EXCEPTION_CONTINUE_EXECUTION;
}
static DWORD WINAPI ymm_worker(void *argument)
{
    DWORD id = (DWORD)(DWORD_PTR)argument;
    for(DWORD round = 0; round < AVX_ROUNDS; round++)
    {
        for(DWORD kind = 0; kind < 3; kind++)
        {
            unsigned char *in = ymm_in[id], *out = ymm_out[id];
            for(DWORD i = 0; i < YMM_REGS * 32; i++) { in[i] = (unsigned char)(id * 37 + round * 11 + kind * 5 + i * 3 + (i >> 5)); out[i] = 0; }
            /* (a migration first, then a step that the scheduler preempts) */
            if(kind == 1 && !SetThreadAffinityMask(GetCurrentThread(), (DWORD_PTR)1 << ((id + round) % system_cpus))) InterlockedIncrement(&avx_bad);
            ymm_step(in, out, kind == 2, kind == 0 ? 1 : AVX_SPIN);
            for(DWORD i = 0; i < YMM_REGS * 32; i++) if(out[i] != in[i]) { InterlockedIncrement(&avx_bad); break; }
            InterlockedIncrement(&avx_steps);
        }
    }
    return 0;
}
#ifdef _WIN64
/* a thread suspended while it spins with its fingerprint: GetThreadContext
 * with CONTEXT_XSTATE gives its XMM registers and YMM upper halves */
static volatile LONG victim_ready, victim_stop;
static DWORD WINAPI victim(void *argument)
{
    (void)argument;
    const unsigned char *in = ymm_in[15];
    __asm__ volatile(ALL(LOADS) "movl $1,(%[ready])\n" "1: pause\n" "cmpl $0,(%[stop])\n" "je 1b\n"
        :: [in] "r"(in), [ready] "r"(&victim_ready), [stop] "r"(&victim_stop) : "memory", "cc", YMM_CLOBBERS);
    return 0;
}
typedef BOOL (WINAPI *initialize_context_fn)(void *, DWORD, CONTEXT **, DWORD *);
typedef BOOL (WINAPI *set_mask_fn)(CONTEXT *, DWORD64);
typedef void *(WINAPI *locate_fn)(CONTEXT *, DWORD, DWORD *);
static DWORD xstate_check(void)
{
    HMODULE k = GetModuleHandleA("kernel32.dll");
    initialize_context_fn initialize = (initialize_context_fn)GetProcAddress(k, "InitializeContext");
    set_mask_fn set_mask = (set_mask_fn)GetProcAddress(k, "SetXStateFeaturesMask");
    locate_fn locate = (locate_fn)GetProcAddress(k, "LocateXStateFeature");
    if(!initialize || !set_mask || !locate) return 2;
    for(DWORD i = 0; i < 16 * 32; i++) ymm_in[15][i] = (unsigned char)(i * 13 + 7);
    HANDLE thread = CreateThread(0, 0, victim, 0, 0, 0);
    if(!thread) return 3;
    while(!victim_ready) Sleep(1);
    DWORD verdict = 0;
    if(SuspendThread(thread) == (DWORD)-1) verdict = 4;
    static unsigned char buffer[8192] __attribute__((aligned(64)));
    CONTEXT *context = 0;
    DWORD length = sizeof(buffer);
    if(!verdict && !initialize(buffer, CONTEXT_ALL | CONTEXT_XSTATE, &context, &length)) verdict = 5;
    if(!verdict && !set_mask(context, XSTATE_MASK_AVX)) verdict = 6;
    if(!verdict && !GetThreadContext(thread, context)) verdict = 7;
    if(!verdict)
    {
        DWORD size = 0;
        unsigned char *upper = locate(context, XSTATE_AVX, &size);
        const unsigned char *low = (const unsigned char *)&context->Xmm0;
        if(!upper || size < 256) verdict = 8;
        for(DWORD r = 0; !verdict && r < 16; r++)
            for(DWORD b = 0; b < 16; b++)
                if(low[r * 16 + b] != ymm_in[15][r * 32 + b] || upper[r * 16 + b] != ymm_in[15][r * 32 + 16 + b]) { verdict = 9; break; }
    }
    victim_stop = 1;
    ResumeThread(thread);
    WaitForSingleObject(thread, 60000);
    CloseHandle(thread);
    return verdict ? verdict : 1;
}
#endif
/* AVX2 and FMA on ymm registers against scalar code (exact operands) */
static DWORD compute_check(DWORD avx2, DWORD fma)
{
    static int a[8] __attribute__((aligned(32))) = {1, -2, 3, -4, 5, 6, -7, 8}, b[8] __attribute__((aligned(32))) = {9, 10, -11, 12, 13, -14, 15, 16};
    static int sum[8] __attribute__((aligned(32))), product[8] __attribute__((aligned(32)));
    static double x[4] __attribute__((aligned(32))) = {1.5, -2.25, 3.0, 0.5}, y[4] __attribute__((aligned(32))) = {4.0, 0.5, -1.25, 6.0};
    static double z[4] __attribute__((aligned(32))) = {0.25, 1.0, -2.0, 3.5}, fused[4] __attribute__((aligned(32)));
    DWORD bad = 0;
    if(avx2)
    {
        __asm__ volatile("vmovdqa (%[a]),%%ymm0\n" "vmovdqa (%[b]),%%ymm1\n" "vpaddd %%ymm1,%%ymm0,%%ymm2\n" "vpmulld %%ymm1,%%ymm0,%%ymm3\n"
            "vmovdqa %%ymm2,(%[sum])\n" "vmovdqa %%ymm3,(%[product])\n" "vzeroupper\n"
            :: [a] "r"(a), [b] "r"(b), [sum] "r"(sum), [product] "r"(product) : "memory" XMM0_3);
        for(int i = 0; i < 8; i++) if(sum[i] != a[i] + b[i] || product[i] != a[i] * b[i]) bad++;
    }
    if(fma)
    {
        __asm__ volatile("vmovapd (%[x]),%%ymm0\n" "vmovapd (%[y]),%%ymm1\n" "vmovapd (%[z]),%%ymm2\n" "vfmadd231pd %%ymm1,%%ymm0,%%ymm2\n"
            "vmovapd %%ymm2,(%[out])\n" "vzeroupper\n"
            :: [x] "r"(x), [y] "r"(y), [z] "r"(z), [out] "r"(fused) : "memory" XMM0_3);
        /* (exact: the operands have few bits) */
        for(int i = 0; i < 4; i++) if(fused[i] != x[i] * y[i] + z[i]) bad++;
    }
    return bad;
}
static void avx(void)
{
    DWORD a = 1, b, c = 0, d;
    __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d));
    DWORD has_fma = c >> 12 & 1, usable = c >> 27 & 1 && c >> 28 & 1;
    if(usable)
    {
        DWORD lo, hi;
        __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
        usable = (lo & 6) == 6;
    }
    if(!usable) { text("X64_WIN_AVX arch=" ARCH " avx=0\r\n"); return; }
    a = 7; c = 0;
    __asm__ volatile("cpuid" : "+a"(a), "=b"(b), "+c"(c), "=d"(d));
    DWORD has_avx2 = b >> 5 & 1;
    text("X64_WIN_AVX_START arch=" ARCH "\r\n");
    FlushFileBuffers(result);
    AddVectoredExceptionHandler(1, on_fault);
    avx_threads = 2 * system_cpus;
    HANDLE workers[16];
    for(DWORD id = 0; id < avx_threads; id++)
    {
        workers[id] = CreateThread(0, 0, ymm_worker, (void *)(DWORD_PTR)id, 0, 0);
        if(!workers[id]) finish(17);
    }
    if(WaitForMultipleObjects(avx_threads, workers, TRUE, 1800000) != WAIT_OBJECT_0) finish(18);
    DWORD xstate = 0;
#ifdef _WIN64
    xstate = xstate_check();
#endif
    DWORD compute = compute_check(has_avx2, has_fma);
    text("X64_WIN_AVX arch=" ARCH " avx=1 avx2="); number(has_avx2); text(" fma="); number(has_fma);
    text(" threads="); number(avx_threads); text(" steps="); number((DWORD)avx_steps); text(" faults="); number((DWORD)avx_faults);
    text(" xstate="); number(xstate); text(" compute_bad="); number(compute); text(" bad="); number((DWORD)avx_bad); text("\r\n");
    if(avx_bad || compute || (xstate && xstate != 1)) InterlockedIncrement(&failed);
}
#ifdef _WIN64
void entry(void)
#else
void __attribute__((stdcall)) entry(void)
#endif
{
    char path[MAX_PATH];
    GetModuleFileNameA(0, path, sizeof(path));
    DWORD at = 0, last = 0;
    while(path[at]) { if(path[at] == '\\') last = at + 1; at++; }
    const char name[] = "RESULT" ARCH ".TXT";
    for(at = 0; at < sizeof(name); at++) path[last + at] = name[at];
    result = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
    if(result == INVALID_HANDLE_VALUE) ExitProcess(10);
    SYSTEM_INFO info;
    GetNativeSystemInfo(&info);
    system_cpus = info.dwNumberOfProcessors;
    text("X64_WIN_BEGIN arch=" ARCH " processors="); number(system_cpus);
    text(" architecture="); number(info.wProcessorArchitecture);
    /* QueryPerformanceCounter's source (docs/jit-unification-plan.md open
       question 4): 14318180 Hz the HPET, 3579545 Hz the ACPI PM timer, other
       values the TSC */
    LARGE_INTEGER qpf;
    text(" qpf="); hex(QueryPerformanceFrequency(&qpf) ? (unsigned long long)qpf.QuadPart : 0);
    text("\r\n");
    FlushFileBuffers(result);
    if(system_cpus < 1 || system_cpus > 8) finish(12);
    /* topology API */
    SYSTEM_LOGICAL_PROCESSOR_INFORMATION topology[64];
    DWORD bytes = sizeof(topology), packages = 0, cores = 0, smt = 0;
    if(!GetLogicalProcessorInformation(topology, &bytes)) finish(13);
    for(DWORD i = 0; i < bytes / sizeof(topology[0]); i++)
    {
        if(topology[i].Relationship == RelationProcessorPackage) packages++;
        if(topology[i].Relationship == RelationProcessorCore)
        {
            cores++;
            if(topology[i].ProcessorCore.Flags) smt++;
            DWORD_PTR mask = topology[i].ProcessorMask;
            if(mask == 0 || (mask & (mask - 1))) InterlockedIncrement(&failed); /* one logical processor per core */
        }
    }
    /* memory: x64 allocates top-down, far above 4 GiB */
    unsigned long long high = 0;
#ifdef _WIN64
    volatile unsigned long long *block = VirtualAlloc(0, 1 << 20, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE);
    if(!block) finish(15);
    high = (unsigned long long)block;
    for(DWORD i = 0; i < (1 << 20) / 8; i += 512) block[i] = high ^ i;
    for(DWORD i = 0; i < (1 << 20) / 8; i += 512) if(block[i] != (high ^ i)) InterlockedIncrement(&failed);
    if(high >> 32 == 0) InterlockedIncrement(&failed);
    VirtualFree((void *)block, 0, MEM_RELEASE);
#endif
    for(DWORD id = 0; id < system_cpus; id++)
    {
        threads[id] = CreateThread(0, 0, worker, (void *)(DWORD_PTR)id, 0, 0);
        if(!threads[id]) finish(14);
    }
    if(WaitForMultipleObjects(system_cpus, threads, TRUE, 600000) != WAIT_OBJECT_0) finish(16);
    avx();
    /* each processor ran on exactly one APIC ID, all distinct */
    DWORD all = 0;
    for(DWORD cpu = 0; cpu < system_cpus; cpu++)
    {
        DWORD mask = apic_seen[cpu];
        if(mask == 0 || (mask & (mask - 1)) || (all & mask)) InterlockedIncrement(&failed);
        all |= mask;
    }
    text("X64_WIN_DONE arch=" ARCH " processors="); number(system_cpus);
    text(" packages="); number(packages); text(" cores="); number(cores); text(" smt_cores="); number(smt);
    text(" progress="); number((DWORD)shared_total); text(" failures="); number((DWORD)failed);
    text(" apic_ids="); hex(all); text(" high_block="); hex(high); text(" checks=");
    for(DWORD id = 0; id < system_cpus; id++) { if(id) text(","); number(checks[id]); }
    text("\r\n");
    finish(failed ? 1 : 0);
}
                                                                                source/v64/tests/x64/windows_usb.c                                                                  0000644 0000000 0000000 00000022551 00000000000 014163  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* What WIN_USB checks (tests/x64/windows_boot.mjs, tests/devices/
 * usb_windows_xp.mjs, docs/usb.md), 32-bit (XP, and WOW64 on 64-bit
 * Windows), no CRT. USB.TXT beside the program gets the present devices of
 * the UHCI controller (PIIX3's 8086:7020, ICH9's 8086:2934) or the EHCI
 * (ICH9's 8086:293A) and its companions (2934 to 2936) or the xHCI (QEMU's
 * 1B36:000D), the root hubs, and
 * the tablet (0627:0001: the USB device and its HID mouse), "DEVICE id |
 * name | error=n | service=s | started" (n is the device's Device Manager
 * problem code, 0 when it has none), then "SCREEN w h", "READY", the
 * cursor's position every 300 ms ("POS x y ms", ms the guest's tick count)
 * until the cursor stays at (3, 5) (where the harness puts it when it is
 * done) or for 15 minutes, and "END". Each line is appended and flushed to
 * the disk, so that the tools disk has it at once (Windows' cache held it
 * for minutes; PowerShell's WMI took minutes too). With a USB disk (U2):
 * its devices (USB\VID_46F4&PID_0001, USBSTOR\...) too, and the file
 * USBDISK.TXT read from the removable drive, FROMWIN.TXT written to it.
 * With WIN_TPM (docs/tpm.md): the TPM's device (ACPI\MSFT0101) too, and
 * commands through Windows' TPM Base Services (tbs.dll, Windows 8 and later):
 * "TPM version=v interface=i", "TPM GetRandom rc=r bytes=n", "TPM
 * manufacturer m" (or "TPM none rc=r" without a TPM). */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <setupapi.h>
#include <cfgmgr32.h>
static char path[MAX_PATH];
static char line[600];
static int at;
static void put(const char *s) { while(*s && at < (int)sizeof(line) - 3) line[at++] = *s++; }
static void put_number(long n)
{
    char b[12];
    int i = 11;
    b[i] = 0;
    if(n < 0) { put("-"); n = -n; }
    do { b[--i] = '0' + n % 10; n /= 10; } while(n);
    put(b + i);
}
static void flush(void)
{
    line[at++] = '\r';
    line[at++] = '\n';
    HANDLE file = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_ALWAYS, 0, 0);
    if(file != INVALID_HANDLE_VALUE)
    {
        DWORD wrote;
        SetFilePointer(file, 0, 0, FILE_END);
        WriteFile(file, line, at, &wrote, 0);
        FlushFileBuffers(file);
        CloseHandle(file);
    }
    at = 0;
}
static int starts(const char *s, const char *prefix)
{
    for(; *prefix; s++, prefix++)
    {
        char c = *s >= 'a' && *s <= 'z' ? *s - 32 : *s;
        if(c != *prefix) return 0;
    }
    return 1;
}
static void devices(void)
{
    static const char *const wanted[] = {"PCI\\VEN_8086&DEV_7020", "PCI\\VEN_8086&DEV_2934", "PCI\\VEN_8086&DEV_2935", "PCI\\VEN_8086&DEV_2936",
        "PCI\\VEN_8086&DEV_293A", "PCI\\VEN_1B36&DEV_000D", "USB\\ROOT_HUB", "USB\\VID_0627&PID_0001", "HID\\VID_0627&PID_0001", "USB\\VID_46F4&PID_0001", "USBSTOR\\",
        "ACPI\\MSFT0101"};
    HDEVINFO set = SetupDiGetClassDevsA(0, 0, 0, DIGCF_ALLCLASSES | DIGCF_PRESENT);
    if(set == INVALID_HANDLE_VALUE) { put("DEVICES error"); flush(); return; }
    SP_DEVINFO_DATA device;
    device.cbSize = sizeof(device);
    for(DWORD i = 0; SetupDiEnumDeviceInfo(set, i, &device); i++)
    {
        char id[200], name[200] = "", service[64] = "";
        if(!SetupDiGetDeviceInstanceIdA(set, &device, id, sizeof(id), 0)) continue;
        int match = 0;
        for(int j = 0; j < (int)(sizeof(wanted) / sizeof(wanted[0])); j++) match |= starts(id, wanted[j]);
        if(!match) continue;
        if(!SetupDiGetDeviceRegistryPropertyA(set, &device, SPDRP_FRIENDLYNAME, 0, (BYTE *)name, sizeof(name), 0))
            SetupDiGetDeviceRegistryPropertyA(set, &device, SPDRP_DEVICEDESC, 0, (BYTE *)name, sizeof(name), 0);
        SetupDiGetDeviceRegistryPropertyA(set, &device, SPDRP_SERVICE, 0, (BYTE *)service, sizeof(service), 0);
        ULONG status = 0, problem = 0;
        CONFIGRET result = CM_Get_DevNode_Status(&status, &problem, device.DevInst, 0);
        put("DEVICE ");
        put(id);
        put(" | ");
        put(name);
        put(" | error=");
        put_number(result != CR_SUCCESS ? -1 : status & DN_HAS_PROBLEM ? (long)problem : 0);
        put(" | service=");
        put(service);
        put(status & DN_STARTED ? " | started" : " | not started");
        flush();
    }
    SetupDiDestroyDeviceInfoList(set);
}
static void put_hex(unsigned long n)
{
    char b[9];
    for(int i = 7; i >= 0; i--, n >>= 4) b[i] = "0123456789abcdef"[n & 15];
    b[8] = 0;
    put(b);
}
static unsigned long be32(const BYTE *b) { return (unsigned long)b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]; }
/* The TPM through TBS: its device information, then GetRandom and the
 * manufacturer property (GetCapability) as raw TPM 2.0 commands */
static void tpm(void)
{
    HMODULE tbs = LoadLibraryA("tbs.dll");
    if(!tbs) return;
    typedef UINT32 (WINAPI *create_t)(const void *, void **);
    typedef UINT32 (WINAPI *submit_t)(void *, UINT32, UINT32, const BYTE *, UINT32, BYTE *, UINT32 *);
    typedef UINT32 (WINAPI *close_t)(void *);
    typedef UINT32 (WINAPI *info_t)(UINT32, void *);
    create_t create = (create_t)GetProcAddress(tbs, "Tbsi_Context_Create");
    submit_t submit = (submit_t)GetProcAddress(tbs, "Tbsip_Submit_Command");
    close_t close = (close_t)GetProcAddress(tbs, "Tbsip_Context_Close");
    info_t info = (info_t)GetProcAddress(tbs, "Tbsi_GetDeviceInfo");
    if(!create || !submit || !close) return;
    /* TBS_CONTEXT_PARAMS2: version 2, includeTpm20 */
    UINT32 params[2] = {2, 4};
    void *context = 0;
    UINT32 rc = create(params, &context);
    if(rc) { put("TPM none rc=0x"); put_hex(rc); flush(); return; }
    if(info)
    {
        /* TBS_DEVICE_INFO: structVersion, tpmVersion, tpmInterfaceType, tpmImpRevision */
        UINT32 device[4] = {0};
        rc = info(sizeof(device), device);
        put("TPM version=");
        put_number(rc ? -1 : (long)device[1]);
        put(" interface=");
        put_number(rc ? -1 : (long)device[2]);
        flush();
    }
    static const BYTE get_random[] = {0x80, 0x01, 0, 0, 0, 12, 0, 0, 0x01, 0x7B, 0, 16};
    BYTE response[256];
    UINT32 length = sizeof(response);
    rc = submit(context, 0, 200, get_random, sizeof(get_random), response, &length);
    put("TPM GetRandom rc=0x");
    put_hex(rc ? rc : length >= 10 ? be32(response + 6) : 0xFFFFFFFF);
    put(" bytes=");
    put_number(!rc && length >= 12 ? (long)(response[10] << 8 | response[11]) : -1);
    flush();
    /* GetCapability(TPM_CAP_TPM_PROPERTIES, TPM_PT_MANUFACTURER, 1) */
    static const BYTE get_manufacturer[] = {0x80, 0x01, 0, 0, 0, 22, 0, 0, 0x01, 0x7A, 0, 0, 0, 6, 0, 0, 0x01, 0x05, 0, 0, 0, 1};
    length = sizeof(response);
    rc = submit(context, 0, 200, get_manufacturer, sizeof(get_manufacturer), response, &length);
    put("TPM manufacturer ");
    if(!rc && length >= 27 && !be32(response + 6))
    {
        /* tag, size, rc, moreData, capability, count, property, value */
        char name[5] = {0};
        for(int i = 0; i < 4; i++) name[i] = response[23 + i] >= 0x20 && response[23 + i] < 0x7F ? response[23 + i] : '.';
        put(name);
    }
    else { put("rc=0x"); put_hex(rc ? rc : length >= 10 ? be32(response + 6) : 0xFFFFFFFF); }
    flush();
    close(context);
}
/* A USB disk (WIN_USB_DISK): the removable drive with USBDISK.TXT on it,
 * "DISK X: <its first line>", then FROMWIN.TXT written there and flushed,
 * "DISK WRITTEN" */
static void usb_disk(void)
{
    char root[] = "C:\\", file[] = "C:\\USBDISK.TXT";
    for(char letter = 'C'; letter <= 'Z'; letter++)
    {
        root[0] = file[0] = letter;
        if(GetDriveTypeA(root) != DRIVE_REMOVABLE) continue;
        HANDLE in = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
        if(in == INVALID_HANDLE_VALUE) continue;
        char text[80];
        DWORD length = 0;
        ReadFile(in, text, sizeof(text) - 1, &length, 0);
        CloseHandle(in);
        while(length && (text[length - 1] == '\r' || text[length - 1] == '\n')) length--;
        text[length] = 0;
        put("DISK ");
        put(root);
        put(" ");
        put(text);
        flush();
        char out_name[] = "C:\\FROMWIN.TXT";
        out_name[0] = letter;
        HANDLE out = CreateFileA(out_name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
        if(out == INVALID_HANDLE_VALUE) { put("DISK WRITE error"); flush(); return; }
        static const char message[] = "written by Windows through the USB disk\r\n";
        DWORD wrote;
        BOOL ok = WriteFile(out, message, sizeof(message) - 1, &wrote, 0) && FlushFileBuffers(out);
        CloseHandle(out);
        put(ok ? "DISK WRITTEN" : "DISK WRITE error");
        flush();
        return;
    }
}
void WINAPI entry(void)
{
    DWORD n = GetModuleFileNameA(0, path, MAX_PATH - 16);
    while(n && path[n - 1] != '\\') n--;
    const char *name = "USB.TXT";
    for(int i = 0; name[i]; i++) path[n++] = name[i];
    path[n] = 0;
    devices();
    tpm();
    usb_disk();
    put("SCREEN ");
    put_number(GetSystemMetrics(SM_CXSCREEN));
    put(" ");
    put_number(GetSystemMetrics(SM_CYSCREEN));
    flush();
    put("READY");
    flush();
    for(int i = 0, sentinel = 0; i < 3000 && sentinel < 2; i++)
    {
        POINT p;
        if(GetCursorPos(&p))
        {
            sentinel = p.x == 3 && p.y == 5 ? sentinel + 1 : 0;
            put("POS ");
            put_number(p.x);
            put(" ");
            put_number(p.y);
            put(" ");
            put_number(GetTickCount());
            flush();
        }
        Sleep(300);
    }
    put("END");
    flush();
    ExitProcess(0);
}
                                                                                                                                                       source/v64/tests/x64/xmm_state.mjs                                                                  0000644 0000000 0000000 00000014154 00000000000 014170  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The XMM registers the x64 page tier keeps in v128 locals within a block
// (docs/jit-unification-plan.md P4.17, x64_xmm_locals) are what the guest
// sees wherever it leaves compiled code: a hot SSE loop, whose block holds
// XMM registers it wrote, loads from a 2 MiB page that is not present until
// the #PF handler maps it (the fault leaves mid-block and the load retries);
// then SSE instructions run single-stepped (TF, a #DB each); a snapshot is
// saved in the middle of the hot loop and restored in another emulator,
// which finishes the run. Every XMM register, the stored results and the
// fault and step counts must equal the interpreter's.
//
// JIT_SWITCHES as usual; the compiled runs set x64_xmm_locals=1 (and the
// other code-quality switches of M5) unless it says otherwise.
import assert from "node:assert/strict";
import { assemble } from "./guest_runner.mjs";
import { long_mode_guest } from "./guest_builder.mjs";
import { with_jit_switches } from "../lib/jit_switches.mjs";

const { V86 } = await import(+process.env.TEST_RELEASE_BUILD ? "../../build/libv86.mjs" : "../../src/main.js");
const RESULTS = 0x300200, PROGRESS = 0x300100, FAULTS = 0x300320, STEPS = 0x300310, IDT = 0x380000;
const SOURCE = 0x5F0000, TARGET = 0x480000, ITERATIONS = 0x2000, PASSES = 64;
const M5 = "x64_xmm_locals=1,x64_hot_inline=1,x64_hot_count=4096,x64_loops=1,x64_sse_fast_check=1,x64_i32_ops=1,x64_fast_lookup=1";

const gate = (vector, label) => `
lea rax, [rel ${label}]
mov [${IDT + vector * 16}], ax
mov word [${IDT + vector * 16 + 2}], 24
mov word [${IDT + vector * 16 + 4}], 0x8E00
shr rax, 16
mov [${IDT + vector * 16 + 6}], ax
shr rax, 16
mov [${IDT + vector * 16 + 8}], eax
mov dword [${IDT + vector * 16 + 12}], 0`;
const body = `
${gate(1, "debug")}
${gate(14, "page_fault")}
lidt [rel idtr]
mov rax, cr4
or eax, 0x600
mov cr4, rax
; the 2 MiB page at 0x600000 (PD entry 3) not present until the #PF handler
and qword [0x202018], ~1
mov rax, cr3
mov cr3, rax
mov eax, 0x01234567
movd xmm1, eax
pshufd xmm1, xmm1, 0
mov eax, 0x00FF00FF
movd xmm2, eax
pshufd xmm2, xmm2, 0x44
pcmpeqd xmm5, xmm5
pxor xmm6, xmm6
pxor xmm7, xmm7
mov r8d, ${PASSES}
pass:
mov rsi, ${SOURCE}
mov rdi, ${TARGET}
mov ecx, ${ITERATIONS}
hot:
movdqa xmm0, [rsi]
paddd xmm0, xmm1
pxor xmm2, xmm0
movdqa xmm3, xmm2
pshufd xmm4, xmm3, 0x1B
paddq xmm5, xmm4
psubw xmm6, xmm0
pand xmm7, xmm6
por xmm7, xmm3
movdqa [rdi], xmm5
add rsi, 16
add rdi, 16
dec ecx
jnz hot
mov [${PROGRESS}], r8d
dec r8d
jnz pass
; single-stepped SSE: a #DB after each instruction
pushfq
or qword [rsp], 0x100
popfq
paddd xmm1, xmm2
pxor xmm3, xmm1
movdqa xmm7, xmm3
pshufd xmm6, xmm7, 0x4E
pushfq
and qword [rsp], ~0x100
popfq
${[0, 1, 2, 3, 4, 5, 6, 7].map(r => `movdqu [${RESULTS + r * 16}], xmm${r}`).join("\n")}
`;
const data = `
debug:
inc dword [${STEPS}]
iretq
page_fault:
inc dword [${FAULTS}]
or qword [0x202018], 1
push rax
mov rax, cr3
mov cr3, rax
pop rax
add rsp, 8
iretq
align 8
idtr: dw 4095
dq ${IDT}
`;
const directory = assemble("xmm-state", long_mode_guest(body, data));

const pattern = Uint8Array.from({ length: ITERATIONS * 16 }, (_, i) => (i * 37 + (i >> 9) * 11) & 255);
const MAGIC = 0x300000;
const done = cpu => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(MAGIC, true) === 0xC064C064;
const outcome = cpu => ({
    xmm: Buffer.from(cpu.mem8.slice(RESULTS, RESULTS + 128)).toString("hex"),
    stores: Buffer.from(cpu.mem8.slice(TARGET, TARGET + ITERATIONS * 16)).toString("base64"),
    faults: new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(FAULTS, true),
    steps: new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(STEPS, true),
});
async function machine(jit)
{
    const options = { graphics_adapter: "bochs_vga", multiboot: { url: directory + "guest.bin" }, memory_size: 32 << 20, acpi: true,
        disable_jit: !jit, autostart: false, log_level: 0, net_device: { type: "none" },
        ...(jit ? { ir_sync_publication: true, jit_switches: Object.fromEntries((process.env.JIT_SWITCHES || M5).split(",").filter(Boolean).map(kv => { const [k, v] = kv.split("="); return [k, +v]; })) } : {}) };
    const emulator = new V86(jit ? options : with_jit_switches(options));
    await new Promise(resolve => emulator.add_listener("emulator-loaded", resolve));
    return emulator;
}
/** Run until `until` (or the end), within `timeout` ms */
function run(emulator, until, timeout = 120000)
{
    const cpu = emulator.v86.cpu, deadline = performance.now() + timeout;
    while(!done(cpu) && !until(cpu))
    {
        assert.ok(performance.now() < deadline, "guest timed out");
        cpu.run_cores();
    }
}

const reference = await machine(false);
reference.v86.cpu.mem8.set(pattern, SOURCE);
run(reference, () => false);
const expected = outcome(reference.v86.cpu);
await reference.destroy();
assert.equal(expected.faults, 1, "the interpreter took the one #PF");
assert.ok(expected.steps >= 4, "the interpreter single-stepped the SSE instructions: " + expected.steps);

// compiled: a snapshot in the middle of the passes, after the fault
const compiled = await machine(true);
const cpu = compiled.v86.cpu;
cpu.mem8.set(pattern, SOURCE);
const progress = cpu => new DataView(cpu.mem8.buffer, cpu.mem8.byteOffset).getUint32(PROGRESS, true);
run(compiled, cpu => progress(cpu) !== 0 && progress(cpu) < PASSES / 2);
assert.ok(!done(cpu), "the snapshot is taken before the end");
const native = cpu.wm.exports.x64_page_stat(1);
assert.ok(native > ITERATIONS * 10 * PASSES / 4, `the page tier ran the hot loop (${native} native instructions)`);
const snapshot = await compiled.save_state();
run(compiled, () => false);
const finished = outcome(cpu);
await compiled.destroy();
assert.deepEqual(finished, expected, "the page tier's run equals the interpreter's");

const restored = await machine(true);
await restored.restore_state(snapshot);
run(restored, () => false);
const resumed = outcome(restored.v86.cpu);
await restored.destroy();
assert.deepEqual(resumed, expected, "the run from the snapshot equals the interpreter's");
console.log(`PASS xmm_state: XMM registers across a #PF mid-block, ${expected.steps} single steps and a snapshot restore (${native} native instructions before it)`);
                                                                                                                                                                                                                                                                                                                                                                                                                    source/v64/tests/x64/xsave.mjs                                                                      0000644 0000000 0000000 00000042362 00000000000 013317  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       #!/usr/bin/env node
// The XSAVE feature set in the x64 engine and in compatibility mode
// (docs/simd-xsave-plan.md P2), with cpu_type "x86_64" and the x86-64-v3
// features: XSAVE64 and XSAVE store x87 state in their 64- and 32-bit formats,
// XMM0-XMM15 and YMM0_H-YMM15_H; FXSAVE64 leaves bytes 416-511 alone;
// compatibility-mode XSAVE and XRSTOR store and load registers 0-7 only, and
// XRSTOR there leaves XMM8-15 and YMM8_H-15_H alone; XGETBV; and the faults
// of the x64 engine (#UD without CR4.OSXSAVE or with a mandatory prefix, #NM
// with CR0.TS, #GP for misalignment, the header, MXCSR and XSETBV/XGETBV).
// P9 part 1: XSAVEOPT and XGETBV(1), whose XINUSE counts XMM8-15 in 64-bit
// mode only; part 2: XSAVEC and XRSTOR of its compacted form; part 3:
// XSAVES, XRSTORS and IA32_XSS. Interpreted, then with the x64 page tier.
import assert from "node:assert/strict";
import {assemble, actual} from "./guest_runner.mjs";
import {long_mode_guest} from "./guest_builder.mjs";

const OUT = 0x300000, XGETBV = OUT + 0x10, SKIP = OUT + 0x80, CASE = OUT + 0x84, MATCH = OUT + 0xC0, FAULTS = OUT + 0x100;
const DATA = OUT + 0x400, IDT = OUT + 0x9000;
const AREA_Y = OUT + 0x1000, AREA1 = OUT + 0x2000, AREA2 = OUT + 0x3000, AREA3 = OUT + 0x4000;
const AREA4 = OUT + 0x5000, AREA5 = OUT + 0x6000, AREA6 = OUT + 0x7000, BAD_HEADER = OUT + 0x8000, BAD_MXCSR = OUT + 0x8400;
const LENGTH = 0xA000;
// the faulting cases: [vector, what]
const CASES = [[6, "XSAVE without CR4.OSXSAVE"], [13, "XSAVE64 misaligned"], [7, "XSAVE64 with CR0.TS"],
    [13, "XRSTOR64, XCOMP_BV[63]"], [13, "XRSTOR64, MXCSR reserved bits"], [13, "XSETBV 0"], [13, "XGETBV 1"],
    [6, "66 XGETBV"], [6, "F3 XSAVE64"], [6, "XSAVEOPT64 without its feature"], [6, "XSAVES64 without its feature"],
    [13, "RDMSR IA32_XSS without XSAVES"], [13, "WRMSR IA32_XSS without XSAVES"]];

/** set CASE and SKIP, then the faulting instruction at label f<n>, then check its RIP */
const fault = (n, length, instruction) => `
mov dword [${CASE}],${n}
mov dword [${SKIP}],${length}
f${n}: ${instruction}
lea rax,[rel f${n}]
cmp rax,[${FAULTS} + ${n} * 16 + 8]
sete byte [${MATCH} + ${n}]`;

// the handlers: #UD, #NM and #GP record CASE's vector and RIP, then skip SKIP bytes
const HANDLERS = `
set_gate:
mov rdi,rbx
shl rdi,4
add rdi,${IDT}
mov [rdi],ax
mov word [rdi + 2],0x18
mov word [rdi + 4],0x8E00
shr rax,16
mov [rdi + 6],ax
shr rax,16
mov [rdi + 8],eax
mov dword [rdi + 12],0
ret
ud:
mov ecx,6
jmp record
nm:
mov ecx,7
jmp record
gp:
add rsp,8
mov ecx,13
record:
mov edx,[${CASE}]
shl edx,4
mov [${FAULTS} + rdx],ecx
mov rax,[rsp]
mov [${FAULTS} + rdx + 8],rax
mov eax,[${SKIP}]
add [rsp],rax
iretq
align 8
idtr: dw 511
dq ${IDT}
`;

const directory = assemble("xsave", long_mode_guest(`
; an IDT: #UD, #NM and #GP record CASE's vector and RIP, then skip SKIP bytes
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,7
mov rax,HIGH+nm
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
lidt [rel idtr]
; SSE (OSFXSR, OSXMMEXCPT) and XSAVE enabled, XCR0 x87, SSE, AVX
mov rax,cr4
or eax,1 << 18 | 3 << 9
mov cr4,rax
xor ecx,ecx
mov eax,7
xor edx,edx
xsetbv
xor ecx,ecx
xgetbv
mov [${XGETBV}],eax
mov [${XGETBV + 4}],edx
; XMM0-15, two x87 registers, then YMM0_H-15_H and MXCSR from AREA_Y
mov rsi,${DATA}
%assign i 0
%rep 16
movdqu xmm%[i],[rsi + i * 16]
%assign i i + 1
%endrep
fninit
fld qword [rsi + 256]
fld qword [rsi + 264]
mov eax,4
xor edx,edx
mov rbx,${AREA_Y}
xrstor64 [rbx]
mov eax,-1
mov edx,-1
mov rbx,${AREA1}
xsave64 [rbx]
mov rbx,${AREA2}
xsave [rbx]
mov rbx,${AREA3}
fxsave64 [rbx]
; compatibility mode: XSAVE into AREA4, XRSTOR from AREA5
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov ebx,${AREA4}
mov eax,-1
mov edx,-1
xsave [ebx]
mov ebx,${AREA5}
xrstor [ebx]
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
mov eax,-1
mov edx,-1
mov rbx,${AREA6}
xsave64 [rbx]
; the faults
mov rax,cr4
and eax,~(1 << 18)
mov cr4,rax
mov rbx,${AREA1}
${fault(0, 3, "xsave [rbx]")}
mov rax,cr4
or eax,1 << 18
mov cr4,rax
mov rbx,${AREA1 + 32}
${fault(1, 4, "xsave64 [rbx]")}
mov rax,cr0
or eax,8
mov cr0,rax
mov rbx,${AREA1}
${fault(2, 4, "xsave64 [rbx]")}
clts
mov rbx,${BAD_HEADER}
${fault(3, 4, "xrstor64 [rbx]")}
mov rbx,${BAD_MXCSR}
${fault(4, 4, "xrstor64 [rbx]")}
xor ecx,ecx
xor eax,eax
xor edx,edx
${fault(5, 3, "xsetbv")}
mov ecx,1
${fault(6, 3, "xgetbv")}
xor ecx,ecx
${fault(7, 4, "db 0x66, 0x0F, 0x01, 0xD0")}
mov rbx,${AREA1}
${fault(8, 5, "db 0xF3, 0x48, 0x0F, 0xAE, 0x23")}
${fault(9, 4, "xsaveopt64 [rbx]")}
${fault(10, 4, "xsaves64 [rbx]")}
mov ecx,0xDA0
${fault(11, 2, "rdmsr")}
mov ecx,0xDA0
xor eax,eax
xor edx,edx
${fault(12, 2, "wrmsr")}
`, HANDLERS));

const xmm = Uint8Array.from({length: 256}, (_, i) => i * 7 + 1);
const ymm = Uint8Array.from({length: 256}, (_, i) => i * 11 + 5);
const setup = emulator => {
    const write = (bytes, address) => emulator.write_memory(bytes, address);
    const u32 = n => Uint8Array.from([n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255]);
    write(new Uint8Array(LENGTH), OUT);
    write(xmm, DATA);
    write(new Uint8Array(Float64Array.of(1.5, -2.25).buffer), DATA + 256);
    // AREA_Y: YMM_Hi128 with MXCSR 0x1FA0; XSTATE_BV: AVX
    write(u32(0x1FA0), AREA_Y + 24);
    write(ymm, AREA_Y + 576);
    write(u32(4), AREA_Y + 512);
    for(const area of [AREA3, AREA4]) write(new Uint8Array(832).fill(0xCC), area);
    write(new Uint8Array(64), AREA4 + 512);
    // AREA5: x87 in its initial configuration, XMM 5A, YMM_H A5
    write(u32(0x37F), AREA5);
    write(u32(0x1F80), AREA5 + 24);
    write(new Uint8Array(256).fill(0x5A), AREA5 + 160);
    write(new Uint8Array(256).fill(0xA5), AREA5 + 576);
    write(u32(7), AREA5 + 512);
    write(u32(0x80000000), BAD_HEADER + 520 + 4);
    write(u32(0x10000), BAD_MXCSR + 24);
};

for(const [label, options] of [["interpreted", {}],
    ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}]])
{
    const result = new Uint8Array(await actual(directory, {length: LENGTH, setup, options: {cpu_type: "x86_64", cpu_features: "x86-64-v3", cpu_features_unreleased: true, ...options}}));
    const view = new DataView(result.buffer, result.byteOffset, result.length);
    const at = address => address - OUT;
    const area = address => result.subarray(at(address), at(address) + 832);
    const u32 = (address, offset) => view.getUint32(at(address) + offset, true);
    assert.deepEqual([u32(XGETBV, 0), u32(XGETBV, 4)], [7, 0], `${label}: XGETBV 0`);
    // XSAVE64: the 64-bit FIP (the high alias), all 16 XMM and YMM_H
    const full = area(AREA1);
    assert.equal(u32(AREA1, 12), 0xFFFF8000, `${label}: XSAVE64: FIP[63:32]`);
    assert.deepEqual([u32(AREA1, 0) & 0xFFFF, full[4], u32(AREA1, 24), u32(AREA1, 28)], [0x37F, 0xC0, 0x1FA0, 0xFFFF], `${label}: XSAVE64: FCW, FTW, MXCSR`);
    assert.deepEqual(full.subarray(160, 416), xmm, `${label}: XSAVE64: XMM0-15`);
    assert.deepEqual(full.subarray(576, 832), ymm, `${label}: XSAVE64: YMM0_H-15_H`);
    assert.deepEqual([u32(AREA1, 512), u32(AREA1, 516)], [7, 0], `${label}: XSAVE64: XSTATE_BV`);
    // XSAVE: FIP[31:0] with FCS (which x87 instructions in 64-bit mode set to 0), not FIP[63:32]
    assert.deepEqual([u32(AREA2, 8), u32(AREA2, 12)], [u32(AREA1, 8), 0], `${label}: XSAVE: FIP[31:0], FCS`);
    assert.deepEqual(area(AREA2).subarray(160, 416), xmm, `${label}: XSAVE: XMM0-15 in 64-bit mode`);
    // FXSAVE64: XMM0-15, but not bytes 416-511
    const fx = area(AREA3);
    assert.deepEqual(fx.subarray(160, 416), xmm, `${label}: FXSAVE64: XMM0-15`);
    assert.ok(fx.subarray(416, 512).every(b => b === 0xCC), `${label}: FXSAVE64 leaves 416-511 alone`);
    // compatibility mode: registers 0-7 only
    const compat = area(AREA4);
    assert.deepEqual(compat.subarray(160, 288), xmm.subarray(0, 128), `${label}: compatibility XSAVE: XMM0-7`);
    assert.ok(compat.subarray(288, 512).every(b => b === 0xCC), `${label}: compatibility XSAVE leaves XMM8-15 alone`);
    assert.deepEqual(compat.subarray(576, 704), ymm.subarray(0, 128), `${label}: compatibility XSAVE: YMM0_H-7_H`);
    assert.ok(compat.subarray(704).every(b => b === 0xCC), `${label}: compatibility XSAVE leaves YMM8_H-15_H alone`);
    assert.equal(u32(AREA4, 512), 7, `${label}: compatibility XSAVE: XSTATE_BV`);
    // ... and XRSTOR loads XMM0-7 and YMM0_H-7_H
    const after = area(AREA6);
    assert.ok(after.subarray(160, 288).every(b => b === 0x5A), `${label}: XMM0-7 from compatibility XRSTOR`);
    assert.deepEqual(after.subarray(288, 416), xmm.subarray(128), `${label}: XMM8-15 kept`);
    assert.ok(after.subarray(576, 704).every(b => b === 0xA5), `${label}: YMM0_H-7_H from compatibility XRSTOR`);
    assert.deepEqual(after.subarray(704, 832), ymm.subarray(128), `${label}: YMM8_H-15_H kept`);
    assert.deepEqual([u32(AREA6, 0) & 0xFFFF, after[4], u32(AREA6, 512)], [0x37F, 0, 6], `${label}: x87 initial, XSTATE_BV SSE and AVX`);
    // the faults, at their instructions
    CASES.forEach(([vector, what], n) => {
        assert.equal(u32(FAULTS + n * 16, 0), vector, `${label}: ${what}: vector`);
        assert.equal(result[at(MATCH) + n], 1, `${label}: ${what}: RIP`);
    });
    console.log(`PASS (${label}): XSAVE64/XSAVE/FXSAVE64 layouts, compatibility-mode XSAVE/XRSTOR, XGETBV and ${CASES.length} faults`);
}

// P9 part 1: XSAVEOPT and XGETBV(1). Every component initial (XRSTOR64 of an
// area whose XSTATE_BV is 0), then XMM8 alone in use
{
    const INIT = OUT + 0x1000, OPT64 = OUT + 0x2000, OPT32 = OUT + 0x3000, C64 = OUT + 0x4000, C32 = OUT + 0x5000, S64 = OUT + 0x6000, S32 = OUT + 0x7000;
    const VALUES = OUT + 0x20;
    const EXT_CASES = [[6, "66 XSAVEOPT64"], [6, "F3 XSAVEOPT64"], [13, "XSAVEOPT64 misaligned"], [6, "66 XSAVEC64"], [13, "XSAVEC64 misaligned"],
        [13, "WRMSR IA32_XSS 1"], [13, "XRSTORS64 of the standard form"], [6, "66 XSAVES64"], [13, "XSAVES64 at CPL 3"], [13, "XRSTORS64 at CPL 3"]];
    // ring 3: a GDT with user data (28H) and 64-bit code (30H) and a TSS (40H)
    // whose RSP0 is the stack; INT 1FH's gate (DPL 3) returns to ring 0
    const RING3 = `
align 8
gdt3: dq 0,0x00CF9A000000FFFF,0x00CF92000000FFFF,0x00AF9A000000FFFF,0,0x00CFF2000000FFFF,0x00AFFA000000FFFF,0,0,0
gdt3r: dw 79
dq HIGH+gdt3
align 16
tss3: dd 0
dq 0x3F0000
times 92 db 0
`;
    const ext = assemble("xsave-ext", long_mode_guest(`
mov ebx,6
mov rax,HIGH+ud
call set_gate
mov ebx,13
mov rax,HIGH+gp
call set_gate
lidt [rel idtr]
mov rax,cr4
or eax,1 << 18 | 3 << 9
mov cr4,rax
xor ecx,ecx
mov eax,7
xor edx,edx
xsetbv
mov eax,-1
mov edx,-1
mov rbx,${INIT}
xrstor64 [rbx]
mov ecx,1
xgetbv
mov [${VALUES}],eax
mov [${VALUES + 4}],edx
mov rax,0x123456789ABCDEF0
movq xmm8,rax
mov ecx,1
xgetbv
mov [${VALUES + 8}],eax
mov eax,-1
mov edx,-1
mov rbx,${OPT64}
xsaveopt64 [rbx]
mov rbx,${C64}
xsavec64 [rbx]
mov rbx,${S64}
xsaves64 [rbx]
mov eax,0xD
mov ecx,1
cpuid
mov [${VALUES + 24}],eax
mov [${VALUES + 28}],ebx
push 8
mov rax,compat
push rax
o64 retf
bits 32
compat:
mov ecx,1
xgetbv
mov [${VALUES + 12}],eax
mov eax,-1
mov edx,-1
mov ebx,${OPT32}
xsaveopt [ebx]
mov ebx,${C32}
xsavec [ebx]
mov ebx,${S32}
xsaves [ebx]
jmp 0x18:back
bits 64
back:
mov rax,HIGH+in_long_mode
jmp rax
in_long_mode:
pxor xmm8,xmm8
mov eax,-1
mov edx,-1
mov rbx,${C64}
xrstor64 [rbx]
movq [${VALUES + 16}],xmm8
pxor xmm8,xmm8
mov eax,-1
mov edx,-1
mov rbx,${S64}
xrstors64 [rbx]
movq [${VALUES + 32}],xmm8
mov ecx,0xDA0
rdmsr
mov [${VALUES + 40}],eax
mov [${VALUES + 44}],edx
mov rbx,${OPT64}
${fault(0, 5, "db 0x66, 0x48, 0x0F, 0xAE, 0x33")}
${fault(1, 5, "db 0xF3, 0x48, 0x0F, 0xAE, 0x33")}
mov rbx,${OPT64 + 32}
${fault(2, 4, "xsaveopt64 [rbx]")}
mov rbx,${C64}
${fault(3, 5, "db 0x66, 0x48, 0x0F, 0xC7, 0x23")}
mov rbx,${C64 + 16}
${fault(4, 4, "xsavec64 [rbx]")}
mov ecx,0xDA0
mov eax,1
xor edx,edx
${fault(5, 2, "wrmsr")}
mov eax,-1
mov edx,-1
mov rbx,${OPT64}
${fault(6, 4, "xrstors64 [rbx]")}
mov rbx,${S64}
${fault(7, 5, "db 0x66, 0x48, 0x0F, 0xC7, 0x2B")}
; the TSS descriptor (its base the high alias), the GDT, TR
lea rax,[rel tss3]
lea rdi,[rel gdt3 + 0x40]
mov word [rdi],0x67
mov [rdi + 2],ax
shr rax,16
mov [rdi + 4],al
mov byte [rdi + 5],0x89
mov byte [rdi + 6],0
shr rax,8
mov [rdi + 7],al
shr rax,8
mov [rdi + 8],eax
mov dword [rdi + 12],0
lgdt [rel gdt3r]
mov ax,0x40
ltr ax
; the first 4 MiB user-accessible, in both aliases
or qword [0x200000],4
or qword [0x200800],4
or qword [0x201000],4
or qword [0x202000],4
or qword [0x202008],4
mov rax,cr3
mov cr3,rax
mov ebx,0x1F
mov rax,HIGH+back_to_ring0
call set_gate
mov word [${IDT} + 0x1F * 16 + 4],0xEE00
push 0x2B
push 0x3D0000
push 2
push 0x33
mov rax,HIGH+ring3
push rax
iretq
ring3:
mov eax,-1
mov edx,-1
mov rbx,${S64}
${fault(8, 4, "xsaves64 [rbx]")}
${fault(9, 4, "xrstors64 [rbx]")}
int 0x1F
back_to_ring0:
mov rsp,0x3F0000
`, HANDLERS + RING3));
    const setup = emulator => {
        const write = (bytes, address) => emulator.write_memory(bytes, address);
        const u32 = n => Uint8Array.from([n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255]);
        write(new Uint8Array(LENGTH), OUT);
        write(u32(0x37F), INIT);
        write(u32(0x1F80), INIT + 24);
        for(const area of [OPT64, OPT32, C64, C32, S64, S32])
        {
            write(new Uint8Array(832).fill(0xCC), area);
            write(new Uint8Array(64), area + 512);
            write(u32(7), area + 512);
        }
    };
    for(const [label, options] of [["interpreted", {}],
        ["x64 page tier", {disable_jit: false, experimental_smp_jit: true, ir_sync_publication: true}]])
    {
        const result = new Uint8Array(await actual(ext, {length: LENGTH, setup,
            options: {cpu_type: "x86_64", cpu_features: ["SSSE3", "SSE4.1", "SSE4.2", "XSAVE", "AVX", "XSAVEOPT", "XGETBV1", "XSAVEC", "XSAVES"],
                cpu_features_unreleased: true, ...options}}));
        const view = new DataView(result.buffer, result.byteOffset, result.length);
        const at = address => address - OUT;
        const u32 = address => view.getUint32(at(address), true);
        const area = address => result.subarray(at(address), at(address) + 832);
        assert.deepEqual([u32(VALUES), u32(VALUES + 4), u32(VALUES + 8), u32(VALUES + 12)], [0, 0, 2, 0],
            `${label}: XGETBV(1): initial, XMM8 in 64-bit mode, XMM8 in compatibility mode`);
        const opt64 = area(OPT64), opt32 = area(OPT32);
        const xmm8 = Uint8Array.from([0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, 0, 0]);
        assert.ok(opt64.subarray(0, 24).every(b => b === 0xCC) && opt64.subarray(32, 160).every(b => b === 0xCC), `${label}: XSAVEOPT64: x87 (initial) not stored`);
        assert.deepEqual([u32(OPT64 + 24), u32(OPT64 + 28)], [0x1F80, 0xFFFF], `${label}: XSAVEOPT64: MXCSR, MXCSR_MASK`);
        assert.deepEqual(opt64.subarray(160, 416), Uint8Array.from({length: 256}, (_, i) => i >= 128 && i < 144 ? xmm8[i - 128] : 0), `${label}: XSAVEOPT64: XMM0-15`);
        assert.ok(opt64.subarray(416, 512).every(b => b === 0xCC) && opt64.subarray(576).every(b => b === 0xCC), `${label}: XSAVEOPT64: YMM (initial) not stored`);
        assert.deepEqual([u32(OPT64 + 512), u32(OPT64 + 516)], [2, 0], `${label}: XSAVEOPT64: XSTATE_BV`);
        assert.ok(opt32.subarray(0, 24).every(b => b === 0xCC) && opt32.subarray(32, 512).every(b => b === 0xCC) && opt32.subarray(576).every(b => b === 0xCC),
            `${label}: compatibility-mode XSAVEOPT: no component in use`);
        assert.deepEqual([u32(OPT32 + 24), u32(OPT32 + 512)], [0x1F80, 0], `${label}: compatibility-mode XSAVEOPT: MXCSR, XSTATE_BV`);
        // XSAVEC64: SSE state (XMM0-15, MXCSR) alone; the compacted header
        const c64 = area(C64), c32 = area(C32);
        assert.deepEqual([c64.subarray(0, 512), c64.subarray(576)], [opt64.subarray(0, 512), opt64.subarray(576)], `${label}: XSAVEC64 stores what XSAVEOPT64 did`);
        assert.deepEqual([512, 516, 520, 524].map(o => u32(C64 + o)), [2, 0, 7, 0x80000000], `${label}: XSAVEC64: XSTATE_BV, XCOMP_BV`);
        assert.ok(c32.subarray(0, 512).every(b => b === 0xCC) && c32.subarray(576).every(b => b === 0xCC), `${label}: compatibility-mode XSAVEC: nothing stored`);
        assert.deepEqual([512, 516, 520, 524].map(o => u32(C32 + o)), [0, 0, 7, 0x80000000], `${label}: compatibility-mode XSAVEC: XSTATE_BV, XCOMP_BV`);
        assert.deepEqual([u32(VALUES + 16), u32(VALUES + 20)], [0x9ABCDEF0, 0x12345678], `${label}: XRSTOR64 of XSAVEC64's area: XMM8`);
        assert.deepEqual([u32(VALUES + 24), u32(VALUES + 28)], [15, 832], `${label}: CPUID.0xD.1: XSAVEOPT, XSAVEC, XGETBV1, XSAVES; the compacted size`);
        // XSAVES64 and XSAVES: XSAVEC64's and XSAVEC's areas; XRSTORS64 of XSAVES64's
        assert.deepEqual(area(S64), c64, `${label}: XSAVES64 stores what XSAVEC64 did`);
        assert.deepEqual(area(S32), c32, `${label}: compatibility-mode XSAVES stores what XSAVEC did`);
        assert.deepEqual([u32(VALUES + 32), u32(VALUES + 36)], [0x9ABCDEF0, 0x12345678], `${label}: XRSTORS64 of XSAVES64's area: XMM8`);
        assert.deepEqual([u32(VALUES + 40), u32(VALUES + 44)], [0, 0], `${label}: RDMSR IA32_XSS`);
        EXT_CASES.forEach(([vector, what], n) => {
            assert.equal(view.getUint32(at(FAULTS + n * 16), true), vector, `${label}: ${what}: vector`);
            assert.equal(result[at(MATCH) + n], 1, `${label}: ${what}: RIP`);
        });
        console.log(`PASS (${label}): XSAVEOPT64/XSAVEOPT's init optimization, XGETBV(1) by mode, XSAVEC64/XSAVEC and XRSTOR64 of the compacted form, XSAVES64/XSAVES/XRSTORS64 and IA32_XSS, ${EXT_CASES.length} faults`);
    }
}
                                                                                                                                                                                                                                                                              source/v64/tests/x86tpl/pagegen_leaf_digests.rs                                                     0000644 0000000 0000000 00000012147 00000000000 016665  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       //! Golden digests of the page tier's leaf emission (x64/pagegen.rs; until
//! P7.5 deleted IR Tier-0, tests/x86tpl/leaf_digests.rs pinned the leaves as
//! Tier-0's classifiers used them, the method of P2.1): its own
//! immediate shift, and x86tpl's packed operations as pagegen classifies
//! them, keyed by encoding. That digest is the one of pagegen's own Packed
//! table and emitter before P2.3 replaced them, so the change kept every
//! encoding's bytes, for every imm8.
use super::*;
use crate::wasmgen::wasm_builder::WasmLocalV128;
use std::collections::BTreeMap;

/// FNV-1a, 64-bit
struct Fnv(u64);
impl Fnv {
    fn new() -> Self { Fnv(0xCBF2_9CE4_8422_2325) }
    fn bytes(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.0 ^= byte as u64;
            self.0 = self.0.wrapping_mul(0x0000_0100_0000_01B3);
        }
    }
}

/// A leaf's outputs by their parameters
#[derive(Default)]
struct Grid(BTreeMap<String, Vec<u8>>);
impl Grid {
    /// Emit `f` into a fresh builder that has two v128 locals (zeros), and
    /// record the finished module under `key`
    fn emit(&mut self, key: String, f: impl FnOnce(&mut WasmBuilder, [&WasmLocalV128; 2])) {
        let mut w = WasmBuilder::new();
        let locals = [(); 2].map(|_| {
            w.simd_zero();
            w.set_new_local_v128()
        });
        f(&mut w, [&locals[0], &locals[1]]);
        for local in locals {
            w.free_local_v128(local);
        }
        w.finish();
        let output = w.output().to_vec();
        if let Some(previous) = self.0.insert(key.clone(), output.clone()) {
            assert!(previous == output, "{key}: two outputs");
        }
    }
    fn digest(&self) -> (usize, u64) {
        let mut hash = Fnv::new();
        for (key, output) in &self.0 {
            hash.bytes(key.as_bytes());
            hash.bytes(&(output.len() as u32).to_le_bytes());
            hash.bytes(output);
        }
        (self.0.len(), hash.0)
    }
}

/// The packed operations pagegen's classifiers give each encoding (key):
/// the 66 0F codes of packed_op, VPAND/VPANDN/VPOR/VPXOR (VEX.256), the
/// shuffles, PALIGNR and the SSE4 forms with every imm8, PSHUFB and the
/// VEX unpacks. Keyed by encoding rather than by value, so that the digest
/// survives P2.3's change of type (x86tpl's Packed) when the bytes do.
fn packed_by_encoding() -> Vec<(String, Packed)> {
    // (66 0F DB DF EB EF: Op::Vlogic in sse(), "logic" below for VEX.256)
    let mut forms: Vec<(String, Packed)> = (0..=255u8)
        .filter(|code| !matches!(code, 0xDB | 0xDF | 0xEB | 0xEF))
        .filter_map(|code| vec::packed_op(code, false).map(|op| (format!("66 0F {code:02X}"), op)))
        .collect();
    forms.extend([
        ("logic DB".to_string(), Packed::Binary(0x4E)),
        ("logic DF".to_string(), Packed::AndNot),
        ("logic EB".to_string(), Packed::Binary(0x50)),
        ("logic EF".to_string(), Packed::Binary(0x51)),
        ("pshufb".to_string(), Packed::Swizzle(0x8F)),
    ]);
    for (double, high) in [(false, false), (false, true), (true, false), (true, true)] {
        forms.push((
            format!("unpack {double} {high}"),
            Packed::Unpack(if double { 8 } else { 4 }, high),
        ));
    }
    for op in [0x660F70, 0xF20F70, 0xF30F70, 0x0FC6, 0x660FC6] {
        for imm in 0..256 {
            forms.push((format!("shuffle {op:X} {imm}"), vec::shuffle(op, imm)));
        }
    }
    for imm in 0..256 {
        forms.push((format!("palignr {imm}"), palignr(imm)));
    }
    for op in 0x660F3800..=0x660F38FF {
        forms.extend(sse4_packed(op, None).map(|p| (format!("sse4 {op:X}"), p)));
    }
    for op in 0x660F3A00..=0x660F3AFF {
        for imm in 0..256 {
            forms.extend(sse4_packed(op, Some(imm)).map(|p| (format!("sse4 {op:X} {imm}"), p)));
        }
    }
    forms
}

#[test]
fn pagegen_packed_by_encoding() {
    let mut grid = Grid::default();
    for (key, op) in packed_by_encoding() {
        grid.emit(key, |w, [a, b]| vec::packed(w, op, a, b, 16));
    }
    let (points, digest) = grid.digest();
    println!("    packed by encoding: {points}, 0x{digest:016X}");
    assert_eq!((points, digest), (2378, 0x8E4D380DE01AA2A4));
}

/// (name, grid points, digest)
const GOLDEN: [(&str, usize, u64); 1] = [("shift_immediate", 8192, 0x43F6712CA35E8767)];

#[test]
fn pagegen_leaf_digests() {
    let mut shift = Grid::default();
    for bits in [16u8, 32, 64, 128] {
        for kind in 0..8u8 {
            for count in 0..=255u8 {
                shift.emit(format!("{bits} {kind} {count}"), |w, [a, _]| {
                    w.get_local_v128(a);
                    shift_immediate(w, bits, kind, count)
                });
            }
        }
    }
    let actual: Vec<(&str, usize, u64)> = [("shift_immediate", shift)]
        .iter()
        .map(|(name, grid)| {
            let (points, digest) = grid.digest();
            (*name, points, digest)
        })
        .collect();
    for (name, points, digest) in &actual {
        println!("    (\"{name}\", {points}, 0x{digest:016X}),");
    }
    assert_eq!(
        actual, GOLDEN,
        "pagegen leaf digests changed (expected: GOLDEN; printed above)"
    );
}
                                                                                                                                                                                                                                                                                                                                                                                                                         source/v64/third_party/README.md                                                                    0000644 0000000 0000000 00000002113 00000000000 013471  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       # Third-party headers

Device interface definitions, used only to generate constant tables
(`tools/gen_svga_constants.js`) and to build guest test programs
(`tests/x64/vktest.c`); none of this is compiled into v86.

| Directory | Source | License |
| --- | --- | --- |
| `vmware-svga/` | Mesa, `src/gallium/drivers/svga/include/` (VMware SVGA II and SVGA3D, including `VGPU10ShaderTokens.h` and `svga3d_shaderdefs.h`), fetched 2026-10-01 from gitlab.freedesktop.org/mesa/mesa `main` | `GPL-2.0 OR MIT`; used under MIT |
| `virgl/` | virglrenderer, `src/virgl_protocol.h` and `src/virgl_hw.h`, fetched 2026-10-01 from gitlab.freedesktop.org/virgl/virglrenderer `main` | MIT |
| `virtio/` | Linux, `include/uapi/linux/virtio_gpu.h`, fetched 2026-10-01 from torvalds/linux `master` | BSD-3-Clause |
| `vulkan/` | Khronos Vulkan-Headers 1.4.354 (`vulkan.h`, `vulkan_core.h`, `vk_platform.h`, `vk_video/`), as Mesa 26.1.6 ships them in `include/vulkan/`, fetched 2026-10-02 | Apache-2.0 |

Each file keeps its own copyright and license header. Update a directory as a
whole and regenerate the constants.
                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/third_party/virgl/virgl_hw.h                                                             0000644 0000000 0000000 00000107106 00000000000 015337  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright 2014, 2015 Red Hat.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * on the rights to use, copy, modify, merge, publish, distribute, sub
 * license, and/or sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#ifndef VIRGL_HW_H
#define VIRGL_HW_H

#include <stdint.h>

struct virgl_box {
	uint32_t x, y, z;
	uint32_t w, h, d;
};

/* formats known by the HW device - based on gallium subset */
enum virgl_formats {
   VIRGL_FORMAT_NONE                    = 0,
   VIRGL_FORMAT_B8G8R8A8_UNORM          = 1,
   VIRGL_FORMAT_B8G8R8X8_UNORM          = 2,
   VIRGL_FORMAT_A8R8G8B8_UNORM          = 3,
   VIRGL_FORMAT_X8R8G8B8_UNORM          = 4,
   VIRGL_FORMAT_B5G5R5A1_UNORM          = 5,
   VIRGL_FORMAT_B4G4R4A4_UNORM          = 6,
   VIRGL_FORMAT_B5G6R5_UNORM            = 7,
   VIRGL_FORMAT_R10G10B10A2_UNORM       = 8,
   VIRGL_FORMAT_L8_UNORM                = 9,    /**< ubyte luminance */
   VIRGL_FORMAT_A8_UNORM                = 10,   /**< ubyte alpha */
   VIRGL_FORMAT_I8_UNORM                = 11,
   VIRGL_FORMAT_L8A8_UNORM              = 12,   /**< ubyte alpha, luminance */
   VIRGL_FORMAT_L16_UNORM               = 13,   /**< ushort luminance */
   VIRGL_FORMAT_U8Y8V8Y8_422_UNORM      = 14,
   VIRGL_FORMAT_Y8U8Y8V8_422_UNORM      = 15,
   VIRGL_FORMAT_Z16_UNORM               = 16,
   VIRGL_FORMAT_Z32_UNORM               = 17,
   VIRGL_FORMAT_Z32_FLOAT               = 18,
   VIRGL_FORMAT_Z24_UNORM_S8_UINT       = 19,
   VIRGL_FORMAT_S8_UINT_Z24_UNORM       = 20,
   VIRGL_FORMAT_Z24X8_UNORM             = 21,
   VIRGL_FORMAT_X8Z24_UNORM             = 22,
   VIRGL_FORMAT_S8_UINT                 = 23,   /**< ubyte stencil */
   VIRGL_FORMAT_R64_FLOAT               = 24,
   VIRGL_FORMAT_R64G64_FLOAT            = 25,
   VIRGL_FORMAT_R64G64B64_FLOAT         = 26,
   VIRGL_FORMAT_R64G64B64A64_FLOAT      = 27,
   VIRGL_FORMAT_R32_FLOAT               = 28,
   VIRGL_FORMAT_R32G32_FLOAT            = 29,
   VIRGL_FORMAT_R32G32B32_FLOAT         = 30,
   VIRGL_FORMAT_R32G32B32A32_FLOAT      = 31,

   VIRGL_FORMAT_R32_UNORM               = 32,
   VIRGL_FORMAT_R32G32_UNORM            = 33,
   VIRGL_FORMAT_R32G32B32_UNORM         = 34,
   VIRGL_FORMAT_R32G32B32A32_UNORM      = 35,
   VIRGL_FORMAT_R32_USCALED             = 36,
   VIRGL_FORMAT_R32G32_USCALED          = 37,
   VIRGL_FORMAT_R32G32B32_USCALED       = 38,
   VIRGL_FORMAT_R32G32B32A32_USCALED    = 39,
   VIRGL_FORMAT_R32_SNORM               = 40,
   VIRGL_FORMAT_R32G32_SNORM            = 41,
   VIRGL_FORMAT_R32G32B32_SNORM         = 42,
   VIRGL_FORMAT_R32G32B32A32_SNORM      = 43,
   VIRGL_FORMAT_R32_SSCALED             = 44,
   VIRGL_FORMAT_R32G32_SSCALED          = 45,
   VIRGL_FORMAT_R32G32B32_SSCALED       = 46,
   VIRGL_FORMAT_R32G32B32A32_SSCALED    = 47,

   VIRGL_FORMAT_R16_UNORM               = 48,
   VIRGL_FORMAT_R16G16_UNORM            = 49,
   VIRGL_FORMAT_R16G16B16_UNORM         = 50,
   VIRGL_FORMAT_R16G16B16A16_UNORM      = 51,

   VIRGL_FORMAT_R16_USCALED             = 52,
   VIRGL_FORMAT_R16G16_USCALED          = 53,
   VIRGL_FORMAT_R16G16B16_USCALED       = 54,
   VIRGL_FORMAT_R16G16B16A16_USCALED    = 55,

   VIRGL_FORMAT_R16_SNORM               = 56,
   VIRGL_FORMAT_R16G16_SNORM            = 57,
   VIRGL_FORMAT_R16G16B16_SNORM         = 58,
   VIRGL_FORMAT_R16G16B16A16_SNORM      = 59,

   VIRGL_FORMAT_R16_SSCALED             = 60,
   VIRGL_FORMAT_R16G16_SSCALED          = 61,
   VIRGL_FORMAT_R16G16B16_SSCALED       = 62,
   VIRGL_FORMAT_R16G16B16A16_SSCALED    = 63,

   VIRGL_FORMAT_R8_UNORM                = 64,
   VIRGL_FORMAT_R8G8_UNORM              = 65,
   VIRGL_FORMAT_R8G8B8_UNORM            = 66,
   VIRGL_FORMAT_R8G8B8A8_UNORM          = 67,
   VIRGL_FORMAT_X8B8G8R8_UNORM          = 68,

   VIRGL_FORMAT_R8_USCALED              = 69,
   VIRGL_FORMAT_R8G8_USCALED            = 70,
   VIRGL_FORMAT_R8G8B8_USCALED          = 71,
   VIRGL_FORMAT_R8G8B8A8_USCALED        = 72,

   VIRGL_FORMAT_R8_SNORM                = 74,
   VIRGL_FORMAT_R8G8_SNORM              = 75,
   VIRGL_FORMAT_R8G8B8_SNORM            = 76,
   VIRGL_FORMAT_R8G8B8A8_SNORM          = 77,

   VIRGL_FORMAT_R8_SSCALED              = 82,
   VIRGL_FORMAT_R8G8_SSCALED            = 83,
   VIRGL_FORMAT_R8G8B8_SSCALED          = 84,
   VIRGL_FORMAT_R8G8B8A8_SSCALED        = 85,

   VIRGL_FORMAT_R32_FIXED               = 87,
   VIRGL_FORMAT_R32G32_FIXED            = 88,
   VIRGL_FORMAT_R32G32B32_FIXED         = 89,
   VIRGL_FORMAT_R32G32B32A32_FIXED      = 90,

   VIRGL_FORMAT_R16_FLOAT               = 91,
   VIRGL_FORMAT_R16G16_FLOAT            = 92,
   VIRGL_FORMAT_R16G16B16_FLOAT         = 93,
   VIRGL_FORMAT_R16G16B16A16_FLOAT      = 94,

   VIRGL_FORMAT_L8_SRGB                 = 95,
   VIRGL_FORMAT_L8A8_SRGB               = 96,
   VIRGL_FORMAT_R8G8B8_SRGB             = 97,
   VIRGL_FORMAT_A8B8G8R8_SRGB           = 98,
   VIRGL_FORMAT_X8B8G8R8_SRGB           = 99,
   VIRGL_FORMAT_B8G8R8A8_SRGB           = 100,
   VIRGL_FORMAT_B8G8R8X8_SRGB           = 101,
   VIRGL_FORMAT_A8R8G8B8_SRGB           = 102,
   VIRGL_FORMAT_X8R8G8B8_SRGB           = 103,
   VIRGL_FORMAT_R8G8B8A8_SRGB           = 104,

   /* compressed formats */
   VIRGL_FORMAT_DXT1_RGB                = 105,
   VIRGL_FORMAT_DXT1_RGBA               = 106,
   VIRGL_FORMAT_DXT3_RGBA               = 107,
   VIRGL_FORMAT_DXT5_RGBA               = 108,

   /* sRGB, compressed */
   VIRGL_FORMAT_DXT1_SRGB               = 109,
   VIRGL_FORMAT_DXT1_SRGBA              = 110,
   VIRGL_FORMAT_DXT3_SRGBA              = 111,
   VIRGL_FORMAT_DXT5_SRGBA              = 112,

   /* rgtc compressed */
   VIRGL_FORMAT_RGTC1_UNORM             = 113,
   VIRGL_FORMAT_RGTC1_SNORM             = 114,
   VIRGL_FORMAT_RGTC2_UNORM             = 115,
   VIRGL_FORMAT_RGTC2_SNORM             = 116,

   VIRGL_FORMAT_R8G8_B8G8_422_UNORM     = 117,
   VIRGL_FORMAT_G8R8_G8B8_422_UNORM     = 118,

   VIRGL_FORMAT_R8SG8SB8UX8U_NORM       = 119,
   VIRGL_FORMAT_R5SG5SB6U_NORM          = 120,

   VIRGL_FORMAT_A8B8G8R8_UNORM          = 121,
   VIRGL_FORMAT_B5G5R5X1_UNORM          = 122,
   VIRGL_FORMAT_R10G10B10A2_USCALED     = 123,
   VIRGL_FORMAT_R11G11B10_FLOAT         = 124,
   VIRGL_FORMAT_R9G9B9E5_FLOAT          = 125,
   VIRGL_FORMAT_Z32_FLOAT_S8X24_UINT    = 126,
   VIRGL_FORMAT_R1_UNORM                = 127,
   VIRGL_FORMAT_R10G10B10X2_USCALED     = 128,
   VIRGL_FORMAT_R10G10B10X2_SNORM       = 129,

   VIRGL_FORMAT_L4A4_UNORM              = 130,
   VIRGL_FORMAT_B10G10R10A2_UNORM       = 131,
   VIRGL_FORMAT_R10SG10SB10SA2U_NORM    = 132,
   VIRGL_FORMAT_R8G8Bx_SNORM            = 133,
   VIRGL_FORMAT_R8G8B8X8_UNORM          = 134,
   VIRGL_FORMAT_B4G4R4X4_UNORM          = 135,
   VIRGL_FORMAT_X24S8_UINT              = 136,
   VIRGL_FORMAT_S8X24_UINT              = 137,
   VIRGL_FORMAT_X32_S8X24_UINT          = 138,
   VIRGL_FORMAT_B2G3R3_UNORM            = 139,

   VIRGL_FORMAT_L16A16_UNORM            = 140,
   VIRGL_FORMAT_A16_UNORM               = 141,
   VIRGL_FORMAT_I16_UNORM               = 142,

   VIRGL_FORMAT_LATC1_UNORM             = 143,
   VIRGL_FORMAT_LATC1_SNORM             = 144,
   VIRGL_FORMAT_LATC2_UNORM             = 145,
   VIRGL_FORMAT_LATC2_SNORM             = 146,

   VIRGL_FORMAT_A8_SNORM                = 147,
   VIRGL_FORMAT_L8_SNORM                = 148,
   VIRGL_FORMAT_L8A8_SNORM              = 149,
   VIRGL_FORMAT_I8_SNORM                = 150,
   VIRGL_FORMAT_A16_SNORM               = 151,
   VIRGL_FORMAT_L16_SNORM               = 152,
   VIRGL_FORMAT_L16A16_SNORM            = 153,
   VIRGL_FORMAT_I16_SNORM               = 154,

   VIRGL_FORMAT_A16_FLOAT               = 155,
   VIRGL_FORMAT_L16_FLOAT               = 156,
   VIRGL_FORMAT_L16A16_FLOAT            = 157,
   VIRGL_FORMAT_I16_FLOAT               = 158,
   VIRGL_FORMAT_A32_FLOAT               = 159,
   VIRGL_FORMAT_L32_FLOAT               = 160,
   VIRGL_FORMAT_L32A32_FLOAT            = 161,
   VIRGL_FORMAT_I32_FLOAT               = 162,

   VIRGL_FORMAT_Y8_V8_U8_420_UNORM      = 163,
   VIRGL_FORMAT_Y8_V8_U8_422_UNORM      = 164,
   VIRGL_FORMAT_Y8_U8_V8_420_UNORM      = 165,  /**< aka I420 */
   VIRGL_FORMAT_Y8_U8V8_420_UNORM       = 166,
   VIRGL_FORMAT_Y8_V8U8_420_UNORM       = 167,

   VIRGL_FORMAT_A4R4_UNORM              = 168,
   VIRGL_FORMAT_R4A4_UNORM              = 169,
   VIRGL_FORMAT_R8A8_UNORM              = 170,
   VIRGL_FORMAT_A8R8_UNORM              = 171,

   VIRGL_FORMAT_R10G10B10A2_SSCALED     = 172,
   VIRGL_FORMAT_R10G10B10A2_SNORM       = 173,
   VIRGL_FORMAT_B10G10R10A2_USCALED     = 174,
   VIRGL_FORMAT_B10G10R10A2_SSCALED     = 175,
   VIRGL_FORMAT_B10G10R10A2_SNORM       = 176,

   VIRGL_FORMAT_R8_UINT                 = 177,
   VIRGL_FORMAT_R8G8_UINT               = 178,
   VIRGL_FORMAT_R8G8B8_UINT             = 179,
   VIRGL_FORMAT_R8G8B8A8_UINT           = 180,

   VIRGL_FORMAT_R8_SINT                 = 181,
   VIRGL_FORMAT_R8G8_SINT               = 182,
   VIRGL_FORMAT_R8G8B8_SINT             = 183,
   VIRGL_FORMAT_R8G8B8A8_SINT           = 184,

   VIRGL_FORMAT_R16_UINT                = 185,
   VIRGL_FORMAT_R16G16_UINT             = 186,
   VIRGL_FORMAT_R16G16B16_UINT          = 187,
   VIRGL_FORMAT_R16G16B16A16_UINT       = 188,

   VIRGL_FORMAT_R16_SINT                = 189,
   VIRGL_FORMAT_R16G16_SINT             = 190,
   VIRGL_FORMAT_R16G16B16_SINT          = 191,
   VIRGL_FORMAT_R16G16B16A16_SINT       = 192,
   VIRGL_FORMAT_R32_UINT                = 193,
   VIRGL_FORMAT_R32G32_UINT             = 194,
   VIRGL_FORMAT_R32G32B32_UINT          = 195,
   VIRGL_FORMAT_R32G32B32A32_UINT       = 196,

   VIRGL_FORMAT_R32_SINT                = 197,
   VIRGL_FORMAT_R32G32_SINT             = 198,
   VIRGL_FORMAT_R32G32B32_SINT          = 199,
   VIRGL_FORMAT_R32G32B32A32_SINT       = 200,

   VIRGL_FORMAT_A8_UINT                 = 201,
   VIRGL_FORMAT_I8_UINT                 = 202,
   VIRGL_FORMAT_L8_UINT                 = 203,
   VIRGL_FORMAT_L8A8_UINT               = 204,

   VIRGL_FORMAT_A8_SINT                 = 205,
   VIRGL_FORMAT_I8_SINT                 = 206,
   VIRGL_FORMAT_L8_SINT                 = 207,
   VIRGL_FORMAT_L8A8_SINT               = 208,

   VIRGL_FORMAT_A16_UINT                = 209,
   VIRGL_FORMAT_I16_UINT                = 210,
   VIRGL_FORMAT_L16_UINT                = 211,
   VIRGL_FORMAT_L16A16_UINT             = 212,

   VIRGL_FORMAT_A16_SINT                = 213,
   VIRGL_FORMAT_I16_SINT                = 214,
   VIRGL_FORMAT_L16_SINT                = 215,
   VIRGL_FORMAT_L16A16_SINT             = 216,

   VIRGL_FORMAT_A32_UINT                = 217,
   VIRGL_FORMAT_I32_UINT                = 218,
   VIRGL_FORMAT_L32_UINT                = 219,
   VIRGL_FORMAT_L32A32_UINT             = 220,

   VIRGL_FORMAT_A32_SINT                = 221,
   VIRGL_FORMAT_I32_SINT                = 222,
   VIRGL_FORMAT_L32_SINT                = 223,
   VIRGL_FORMAT_L32A32_SINT             = 224,

   VIRGL_FORMAT_B10G10R10A2_UINT        = 225,
   VIRGL_FORMAT_ETC1_RGB8               = 226,
   VIRGL_FORMAT_R8G8_R8B8_422_UNORM     = 227,
   VIRGL_FORMAT_G8R8_B8R8_422_UNORM     = 228,
   VIRGL_FORMAT_R8G8B8X8_SNORM          = 229,

   VIRGL_FORMAT_R8G8B8X8_SRGB           = 230,

   VIRGL_FORMAT_R8G8B8X8_UINT           = 231,
   VIRGL_FORMAT_R8G8B8X8_SINT           = 232,
   VIRGL_FORMAT_B10G10R10X2_UNORM       = 233,
   VIRGL_FORMAT_R16G16B16X16_UNORM      = 234,
   VIRGL_FORMAT_R16G16B16X16_SNORM      = 235,
   VIRGL_FORMAT_R16G16B16X16_FLOAT      = 236,
   VIRGL_FORMAT_R16G16B16X16_UINT       = 237,
   VIRGL_FORMAT_R16G16B16X16_SINT       = 238,
   VIRGL_FORMAT_R32G32B32X32_FLOAT      = 239,
   VIRGL_FORMAT_R32G32B32X32_UINT       = 240,
   VIRGL_FORMAT_R32G32B32X32_SINT       = 241,
   VIRGL_FORMAT_R8A8_SNORM              = 242,
   VIRGL_FORMAT_R16A16_UNORM            = 243,
   VIRGL_FORMAT_R16A16_SNORM            = 244,
   VIRGL_FORMAT_R16A16_FLOAT            = 245,
   VIRGL_FORMAT_R32A32_FLOAT            = 246,
   VIRGL_FORMAT_R8A8_UINT               = 247,
   VIRGL_FORMAT_R8A8_SINT               = 248,
   VIRGL_FORMAT_R16A16_UINT             = 249,
   VIRGL_FORMAT_R16A16_SINT             = 250,
   VIRGL_FORMAT_R32A32_UINT             = 251,
   VIRGL_FORMAT_R32A32_SINT             = 252,

   VIRGL_FORMAT_R10G10B10A2_UINT        = 253,
   VIRGL_FORMAT_B5G6R5_SRGB             = 254,

   VIRGL_FORMAT_BPTC_RGBA_UNORM         = 255,
   VIRGL_FORMAT_BPTC_SRGBA              = 256,
   VIRGL_FORMAT_BPTC_RGB_FLOAT          = 257,
   VIRGL_FORMAT_BPTC_RGB_UFLOAT         = 258,

   /*VIRGL_FORMAT_A8L8_UNORM              = 259, Removed and no user */
   /*VIRGL_FORMAT_A8L8_SNORM              = 260, Removed and no user */
   /*VIRGL_FORMAT_A8L8_SRGB               = 261, Removed and no user */
   /*VIRGL_FORMAT_A16L16_UNORM            = 262, Removed and no user */

   VIRGL_FORMAT_G8R8_UNORM              = 263,
   VIRGL_FORMAT_G8R8_SNORM              = 264,
   VIRGL_FORMAT_G16R16_UNORM            = 265,
   VIRGL_FORMAT_G16R16_SNORM            = 266,
   VIRGL_FORMAT_A8B8G8R8_SNORM          = 267,

   VIRGL_FORMAT_X8B8G8R8_SNORM          = 268,

   /* etc2 compressed */
   VIRGL_FORMAT_ETC2_RGB8               = 269,
   VIRGL_FORMAT_ETC2_SRGB8              = 270,
   VIRGL_FORMAT_ETC2_RGB8A1             = 271,
   VIRGL_FORMAT_ETC2_SRGB8A1            = 272,
   VIRGL_FORMAT_ETC2_RGBA8              = 273,
   VIRGL_FORMAT_ETC2_SRGBA8             = 274,
   VIRGL_FORMAT_ETC2_R11_UNORM          = 275,
   VIRGL_FORMAT_ETC2_R11_SNORM          = 276,
   VIRGL_FORMAT_ETC2_RG11_UNORM         = 277,
   VIRGL_FORMAT_ETC2_RG11_SNORM         = 278,

    /* astc compressed */
   VIRGL_FORMAT_ASTC_4x4                = 279,
   VIRGL_FORMAT_ASTC_5x4                = 280,
   VIRGL_FORMAT_ASTC_5x5                = 281,
   VIRGL_FORMAT_ASTC_6x5                = 282,
   VIRGL_FORMAT_ASTC_6x6                = 283,
   VIRGL_FORMAT_ASTC_8x5                = 284,
   VIRGL_FORMAT_ASTC_8x6                = 285,
   VIRGL_FORMAT_ASTC_8x8                = 286,
   VIRGL_FORMAT_ASTC_10x5               = 287,
   VIRGL_FORMAT_ASTC_10x6               = 288,
   VIRGL_FORMAT_ASTC_10x8               = 289,
   VIRGL_FORMAT_ASTC_10x10              = 290,
   VIRGL_FORMAT_ASTC_12x10              = 291,
   VIRGL_FORMAT_ASTC_12x12              = 292,
   VIRGL_FORMAT_ASTC_4x4_SRGB           = 293,
   VIRGL_FORMAT_ASTC_5x4_SRGB           = 294,
   VIRGL_FORMAT_ASTC_5x5_SRGB           = 295,
   VIRGL_FORMAT_ASTC_6x5_SRGB           = 296,
   VIRGL_FORMAT_ASTC_6x6_SRGB           = 297,
   VIRGL_FORMAT_ASTC_8x5_SRGB           = 298,
   VIRGL_FORMAT_ASTC_8x6_SRGB           = 299,
   VIRGL_FORMAT_ASTC_8x8_SRGB           = 300,
   VIRGL_FORMAT_ASTC_10x5_SRGB          = 301,
   VIRGL_FORMAT_ASTC_10x6_SRGB          = 302,
   VIRGL_FORMAT_ASTC_10x8_SRGB          = 303,
   VIRGL_FORMAT_ASTC_10x10_SRGB         = 304,
   VIRGL_FORMAT_ASTC_12x10_SRGB         = 305,
   VIRGL_FORMAT_ASTC_12x12_SRGB         = 306,

   VIRGL_FORMAT_R10G10B10X2_UNORM       = 308,
   VIRGL_FORMAT_A4B4G4R4_UNORM          = 311,

   VIRGL_FORMAT_R8_SRGB                 = 312,
   VIRGL_FORMAT_R8G8_SRGB               = 313,

   VIRGL_FORMAT_X6Y10_X6U10X6V10_420_UNORM = 314,
   VIRGL_FORMAT_X4Y12_X4U12X4V12_420_UNORM = 315,
   VIRGL_FORMAT_Y16_U16V16_420_UNORM       = 316,

   VIRGL_FORMAT_B8G8R8_UNORM            = 317,
   VIRGL_FORMAT_R3G3B2_UNORM            = 318,
   VIRGL_FORMAT_R4G4B4A4_UNORM          = 319,
   VIRGL_FORMAT_R5G5B5A1_UNORM          = 320,
   VIRGL_FORMAT_R5G6B5_UNORM            = 321,

   VIRGL_FORMAT_Y8_400_UNORM            = 322,
   VIRGL_FORMAT_Y8_U8_V8_444_UNORM      = 323,
   VIRGL_FORMAT_Y8_U8_V8_422_UNORM      = 324,
   VIRGL_FORMAT_Y8_U8V8_422_UNORM       = 325, /* aka Y8_U8V8_422_UNORM */
   VIRGL_FORMAT_Y8_UNORM                = 326,
   VIRGL_FORMAT_Y8V8Y8U8_422_UNORM      = 327,
   VIRGL_FORMAT_Z16_UNORM_S8_UINT       = 328,
   VIRGL_FORMAT_Z24_UNORM_S8_UINT_AS_R8G8B8A8 = 329,
   VIRGL_FORMAT_A1B5G5R5_UINT           = 330,
   VIRGL_FORMAT_A1B5G5R5_UNORM          = 331,
   VIRGL_FORMAT_A1R5G5B5_UINT           = 332,
   VIRGL_FORMAT_A1R5G5B5_UNORM          = 333,
   VIRGL_FORMAT_A2B10G10R10_UINT        = 334,
   VIRGL_FORMAT_A2B10G10R10_UNORM       = 335,
   VIRGL_FORMAT_A2R10G10B10_UINT        = 336,
   VIRGL_FORMAT_A2R10G10B10_UNORM       = 337,
   VIRGL_FORMAT_A4B4G4R4_UINT           = 338,
   VIRGL_FORMAT_A4R4G4B4_UINT           = 339,
   VIRGL_FORMAT_A4R4G4B4_UNORM          = 340,
   VIRGL_FORMAT_A8B8G8R8_SINT           = 341,
   VIRGL_FORMAT_A8B8G8R8_SSCALED        = 342,
   VIRGL_FORMAT_A8B8G8R8_UINT           = 343,
   VIRGL_FORMAT_A8B8G8R8_USCALED        = 344,
   VIRGL_FORMAT_A8R8G8B8_SINT           = 345,
   VIRGL_FORMAT_A8R8G8B8_SNORM          = 346,
   VIRGL_FORMAT_A8R8G8B8_UINT           = 347,
   VIRGL_FORMAT_ASTC_3x3x3              = 348,
   VIRGL_FORMAT_ASTC_3x3x3_SRGB         = 349,
   VIRGL_FORMAT_ASTC_4x3x3              = 350,
   VIRGL_FORMAT_ASTC_4x3x3_SRGB         = 351,
   VIRGL_FORMAT_ASTC_4x4x3              = 352,
   VIRGL_FORMAT_ASTC_4x4x3_SRGB         = 353,
   VIRGL_FORMAT_ASTC_4x4x4              = 354,
   VIRGL_FORMAT_ASTC_4x4x4_SRGB         = 355,
   VIRGL_FORMAT_ASTC_5x4x4              = 356,
   VIRGL_FORMAT_ASTC_5x4x4_SRGB         = 357,
   VIRGL_FORMAT_ASTC_5x5x4              = 358,
   VIRGL_FORMAT_ASTC_5x5x4_SRGB         = 359,
   VIRGL_FORMAT_ASTC_5x5x5              = 360,
   VIRGL_FORMAT_ASTC_5x5x5_SRGB         = 361,
   VIRGL_FORMAT_ASTC_6x5x5              = 362,
   VIRGL_FORMAT_ASTC_6x5x5_SRGB         = 363,
   VIRGL_FORMAT_ASTC_6x6x5              = 364,
   VIRGL_FORMAT_ASTC_6x6x5_SRGB         = 365,
   VIRGL_FORMAT_ASTC_6x6x6              = 366,
   VIRGL_FORMAT_ASTC_6x6x6_SRGB         = 367,
   VIRGL_FORMAT_ATC_RGB                 = 368,
   VIRGL_FORMAT_ATC_RGBA_EXPLICIT       = 369,
   VIRGL_FORMAT_ATC_RGBA_INTERPOLATED   = 370,
   VIRGL_FORMAT_A8Y8U8V8_444_UNORM      = 371,
   VIRGL_FORMAT_B10G10R10A2_SINT        = 372,
   VIRGL_FORMAT_B10G10R10X2_SINT        = 373,
   VIRGL_FORMAT_B10G10R10X2_SNORM       = 374,
   VIRGL_FORMAT_B2G3R3_UINT             = 375,
   VIRGL_FORMAT_B4G4R4A4_UINT           = 376,
   VIRGL_FORMAT_B5G5R5A1_UINT           = 377,
   VIRGL_FORMAT_B5G6R5_UINT             = 378,
   VIRGL_FORMAT_B8G8R8A8_SINT           = 379,
   VIRGL_FORMAT_B8G8R8A8_SNORM          = 380,
   VIRGL_FORMAT_B8G8R8A8_SSCALED        = 381,
   VIRGL_FORMAT_B8G8R8A8_UINT           = 382,
   VIRGL_FORMAT_B8G8R8A8_USCALED        = 383,
   VIRGL_FORMAT_B8G8_R8G8_422_UNORM     = 384,
   VIRGL_FORMAT_B8G8R8_SINT             = 385,
   VIRGL_FORMAT_B8G8R8_SNORM            = 386,
   VIRGL_FORMAT_B8G8R8_SRGB             = 387,
   VIRGL_FORMAT_B8G8R8_SSCALED          = 388,
   VIRGL_FORMAT_B8G8R8_UINT             = 389,
   VIRGL_FORMAT_B8G8R8_USCALED          = 390,
   VIRGL_FORMAT_B8G8R8X8_SINT           = 391,
   VIRGL_FORMAT_B8G8R8X8_SNORM          = 392,
   VIRGL_FORMAT_B8G8R8X8_UINT           = 393,
   VIRGL_FORMAT_B8R8_G8R8_422_UNORM     = 394,
   VIRGL_FORMAT_FXT1_RGB                = 395,
   VIRGL_FORMAT_FXT1_RGBA               = 396,
   VIRGL_FORMAT_G16R16_SINT             = 397,
   VIRGL_FORMAT_G8B8_G8R8_422_UNORM     = 398,
   VIRGL_FORMAT_G8_B8_R8_420_UNORM      = 399,
   VIRGL_FORMAT_G8_B8R8_420_UNORM       = 400,
   VIRGL_FORMAT_G8R8_SINT               = 401,
   VIRGL_FORMAT_Y10Y10Y10X2_U10V10U10X2V10U10V10X2_420_UNORM = 402,
   VIRGL_FORMAT_R10G10B10A2_SINT        = 403,
   VIRGL_FORMAT_R10G10B10X2_SINT        = 404,
   VIRGL_FORMAT_R3G3B2_UINT             = 405,
   VIRGL_FORMAT_R4G4B4A4_UINT           = 406,
   VIRGL_FORMAT_R4G4B4X4_UNORM          = 407,
   VIRGL_FORMAT_R5G5B5A1_UINT           = 408,
   VIRGL_FORMAT_R5G5B5X1_UNORM          = 409,
   VIRGL_FORMAT_R5G6B5_SRGB             = 410,
   VIRGL_FORMAT_R5G6B5_UINT             = 411,
   VIRGL_FORMAT_R64G64B64A64_SINT       = 412,
   VIRGL_FORMAT_R64G64B64A64_UINT       = 413,
   VIRGL_FORMAT_R64G64B64_SINT          = 414,
   VIRGL_FORMAT_R64G64B64_UINT          = 415,
   VIRGL_FORMAT_R64G64_SINT             = 416,
   VIRGL_FORMAT_R64G64_UINT             = 417,
   VIRGL_FORMAT_R64_SINT                = 418,
   VIRGL_FORMAT_R64_UINT                = 419, /**< raw doubles (ARB_vertex_attrib_64bit) */
   VIRGL_FORMAT_R8_B8_G8_420_UNORM      = 420,
   VIRGL_FORMAT_R8_B8G8_420_UNORM       = 421,
   VIRGL_FORMAT_R8B8_R8G8_422_UNORM     = 422,
   VIRGL_FORMAT_R8_G8_B8_420_UNORM      = 423,
   VIRGL_FORMAT_R8_G8B8_420_UNORM       = 424,
   VIRGL_FORMAT_R8_G8_B8_444_UNORM      = 425,
   VIRGL_FORMAT_V8Y8U8Y8_422_UNORM      = 426,
   VIRGL_FORMAT_X1B5G5R5_UNORM          = 427,
   VIRGL_FORMAT_X1R5G5B5_UNORM          = 428,
   VIRGL_FORMAT_X8Y8U8V8_444_UNORM      = 429,
   VIRGL_FORMAT_X8B8G8R8_SINT           = 430,
   VIRGL_FORMAT_X8R8G8B8_SINT           = 431,
   VIRGL_FORMAT_X8R8G8B8_SNORM          = 432,
   VIRGL_FORMAT_Y16_U16_V16_420_UNORM   = 433,
   VIRGL_FORMAT_Y16_U16_V16_422_UNORM   = 434,
   VIRGL_FORMAT_Y16_U16V16_422_UNORM    = 435,
   VIRGL_FORMAT_Y16_U16_V16_444_UNORM   = 436,
   VIRGL_FORMAT_X6Y10X6U10X6Y10X6V10_422_UNORM = 437,
   VIRGL_FORMAT_X4Y12X4U12X4Y12X4V12_422_UNORM = 438,
   VIRGL_FORMAT_Y16U16Y16V16_422_UNORM  = 439,
   VIRGL_FORMAT_U10Y10V10A2_444_UNORM   = 440,
   VIRGL_FORMAT_X4U12X4Y12X4V12X4A12_444_UNORM = 441,
   VIRGL_FORMAT_U16Y16V16A16_444_UNORM  = 442,
   VIRGL_FORMAT_Y10_U10V10_420_UNORM    = 443,
   VIRGL_FORMAT_Y10_U10V10_422_UNORM    = 444,
   VIRGL_FORMAT_Y8_U8_V8_440_UNORM      = 445,
   VIRGL_FORMAT_R10_G10B10_420_UNORM    = 446,
   VIRGL_FORMAT_R10_G10B10_422_UNORM    = 447,
   VIRGL_FORMAT_X6G10_X6B10X6R10_420_UNORM = 448,
   VIRGL_FORMAT_X4G12_X4B12X4R12_420_UNORM = 449,
   VIRGL_FORMAT_X6R10_UNORM             = 450,
   VIRGL_FORMAT_X6R10X6G10_UNORM        = 451,
   VIRGL_FORMAT_X4R12_UNORM             = 452,
   VIRGL_FORMAT_X4R12X4G12_UNORM        = 453,
   VIRGL_FORMAT_R8_G8B8_422_UNORM       = 454,
   VIRGL_FORMAT_R8_B8G8_422_UNORM       = 455,
   VIRGL_FORMAT_G8_B8R8_422_UNORM       = 456,
   VIRGL_FORMAT_ASTC_4x4_FLOAT          = 457,
   VIRGL_FORMAT_ASTC_5x4_FLOAT          = 458,
   VIRGL_FORMAT_ASTC_5x5_FLOAT          = 459,
   VIRGL_FORMAT_ASTC_6x5_FLOAT          = 460,
   VIRGL_FORMAT_ASTC_6x6_FLOAT          = 461,
   VIRGL_FORMAT_ASTC_8x5_FLOAT          = 462,
   VIRGL_FORMAT_ASTC_8x6_FLOAT          = 463,
   VIRGL_FORMAT_ASTC_8x8_FLOAT          = 464,
   VIRGL_FORMAT_ASTC_10x5_FLOAT         = 465,
   VIRGL_FORMAT_ASTC_10x6_FLOAT         = 466,
   VIRGL_FORMAT_ASTC_10x8_FLOAT         = 467,
   VIRGL_FORMAT_ASTC_10x10_FLOAT        = 468,
   VIRGL_FORMAT_ASTC_12x10_FLOAT        = 469,
   VIRGL_FORMAT_ASTC_12x12_FLOAT        = 470,
   VIRGL_FORMAT_Y8U8V8_420_UNORM_PACKED = 471,
   VIRGL_FORMAT_Y10U10V10_420_UNORM_PACKED = 472,
   VIRGL_FORMAT_R8G8B8_420_UNORM_PACKED = 473,
   VIRGL_FORMAT_R10G10B10_420_UNORM_PACKED = 474,
   VIRGL_FORMAT_Y10X6_U10X6_V10X6_420_UNORM = 475,
   VIRGL_FORMAT_Y10X6_U10X6_V10X6_422_UNORM = 476,
   VIRGL_FORMAT_Y10X6_U10X6_V10X6_444_UNORM = 477,
   VIRGL_FORMAT_Y12X4_U12X4_V12X4_420_UNORM = 478,
   VIRGL_FORMAT_Y12X4_U12X4_V12X4_422_UNORM = 479,
   VIRGL_FORMAT_Y12X4_U12X4_V12X4_444_UNORM = 480,
   VIRGL_FORMAT_X6Y10_X6U10X6V10_422_UNORM = 481,

   VIRGL_FORMAT_MAX /* = PIPE_FORMAT_COUNT */,

   /* Below formats must not be used in the guest. */
   VIRGL_FORMAT_B8G8R8X8_UNORM_EMULATED,
   VIRGL_FORMAT_B8G8R8A8_UNORM_EMULATED,
   VIRGL_FORMAT_MAX_EXTENDED
};

/* These are used by the capability_bits field in virgl_caps_v2. */
#define VIRGL_CAP_NONE 0u
#define VIRGL_CAP_TGSI_INVARIANT       (1u << 0)
#define VIRGL_CAP_TEXTURE_VIEW         (1u << 1)
#define VIRGL_CAP_SET_MIN_SAMPLES      (1u << 2)
#define VIRGL_CAP_COPY_IMAGE           (1u << 3)
#define VIRGL_CAP_TGSI_PRECISE         (1u << 4)
#define VIRGL_CAP_TXQS                 (1u << 5)
#define VIRGL_CAP_MEMORY_BARRIER       (1u << 6)
#define VIRGL_CAP_COMPUTE_SHADER       (1u << 7)
#define VIRGL_CAP_FB_NO_ATTACH         (1u << 8)
#define VIRGL_CAP_ROBUST_BUFFER_ACCESS (1u << 9)
#define VIRGL_CAP_TGSI_FBFETCH         (1u << 10)
#define VIRGL_CAP_SHADER_CLOCK         (1u << 11)
#define VIRGL_CAP_TEXTURE_BARRIER      (1u << 12)
#define VIRGL_CAP_TGSI_COMPONENTS      (1u << 13)
#define VIRGL_CAP_GUEST_MAY_INIT_LOG   (1u << 14)
#define VIRGL_CAP_SRGB_WRITE_CONTROL   (1u << 15)
#define VIRGL_CAP_QBO                  (1u << 16)
#define VIRGL_CAP_TRANSFER             (1u << 17)
#define VIRGL_CAP_FBO_MIXED_COLOR_FORMATS  (1u << 18)
#define VIRGL_CAP_HOST_IS_GLES         (1u << 19)
#define VIRGL_CAP_BIND_COMMAND_ARGS    (1u << 20)
#define VIRGL_CAP_MULTI_DRAW_INDIRECT  (1u << 21)
#define VIRGL_CAP_INDIRECT_PARAMS      (1u << 22)
#define VIRGL_CAP_TRANSFORM_FEEDBACK3  (1u << 23)
#define VIRGL_CAP_3D_ASTC              (1u << 24)
#define VIRGL_CAP_INDIRECT_INPUT_ADDR  (1u << 25)
#define VIRGL_CAP_COPY_TRANSFER        (1u << 26)
#define VIRGL_CAP_CLIP_HALFZ           (1u << 27)
#define VIRGL_CAP_APP_TWEAK_SUPPORT    (1u << 28)
#define VIRGL_CAP_BGRA_SRGB_IS_EMULATED (1u << 29)
#define VIRGL_CAP_CLEAR_TEXTURE        (1u << 30)
#define VIRGL_CAP_ARB_BUFFER_STORAGE   (1u << 31)

// Legacy alias
#define VIRGL_CAP_FAKE_FP64            VIRGL_CAP_HOST_IS_GLES

/* These are used by the capability_bits_v2 field in virgl_caps_v2. */
#define VIRGL_CAP_V2_BLEND_EQUATION       (1u << 0)
#define VIRGL_CAP_V2_UNTYPED_RESOURCE     (1u << 1)
#define VIRGL_CAP_V2_VIDEO_MEMORY         (1u << 2)
#define VIRGL_CAP_V2_MEMINFO              (1u << 3)
#define VIRGL_CAP_V2_STRING_MARKER        (1u << 4)
#define VIRGL_CAP_V2_DIFFERENT_GPU        (1u << 5)
#define VIRGL_CAP_V2_IMPLICIT_MSAA        (1u << 6)
#define VIRGL_CAP_V2_COPY_TRANSFER_BOTH_DIRECTIONS (1u << 7)
#define VIRGL_CAP_V2_SCANOUT_USES_GBM     (1u << 8)
#define VIRGL_CAP_V2_SSO                  (1u << 9)
#define VIRGL_CAP_V2_TEXTURE_SHADOW_LOD   (1u << 10)
#define VIRGL_CAP_V2_VS_VERTEX_LAYER      (1u << 11)
#define VIRGL_CAP_V2_VS_VIEWPORT_INDEX    (1u << 12)
#define VIRGL_CAP_V2_PIPELINE_STATISTICS_QUERY (1u << 13)
#define VIRGL_CAP_V2_DRAW_PARAMETERS      (1u << 14)
#define VIRGL_CAP_V2_GROUP_VOTE           (1u << 15)
#define VIRGL_CAP_V2_MIRROR_CLAMP_TO_EDGE (1u << 16)
#define VIRGL_CAP_V2_MIRROR_CLAMP         (1u << 17)
#define VIRGL_CAP_V2_RESOURCE_LAYOUT      (1u << 18)
#define VIRGL_CAP_V2_QUERY_FORMAT_MODIFIER (1u << 19)

/* virgl bind flags - these are compatible with mesa 10.5 gallium.
 * but are fixed, no other should be passed to virgl either.
 */
#define VIRGL_BIND_DEPTH_STENCIL (1u << 0)
#define VIRGL_BIND_RENDER_TARGET (1u << 1)
#define VIRGL_BIND_SAMPLER_VIEW  (1u << 3)
#define VIRGL_BIND_VERTEX_BUFFER (1u << 4)
#define VIRGL_BIND_INDEX_BUFFER  (1u << 5)
#define VIRGL_BIND_CONSTANT_BUFFER (1u << 6)
#define VIRGL_BIND_DISPLAY_TARGET (1u << 7)
#define VIRGL_BIND_COMMAND_ARGS  (1u << 8)
#define VIRGL_BIND_STREAM_OUTPUT (1u << 11)
#define VIRGL_BIND_SHADER_BUFFER (1u << 14)
#define VIRGL_BIND_QUERY_BUFFER  (1u << 15)
#define VIRGL_BIND_CURSOR        (1u << 16)
#define VIRGL_BIND_CUSTOM        (1u << 17)
#define VIRGL_BIND_SCANOUT       (1u << 18)
/* Used for buffers that are backed by guest storage and
 * are only read by the host.
 */
#define VIRGL_BIND_STAGING       (1u << 19)
#define VIRGL_BIND_SHARED        (1u << 20)

#define VIRGL_BIND_PREFER_EMULATED_BGRA  (1u << 21) /* non-functional */

#define VIRGL_BIND_LINEAR (1u << 22)

#define VIRGL_BIND_SHARED_SUBFLAGS (0xffu << 24)

#define VIRGL_BIND_MINIGBM_CAMERA_WRITE (1u << 24)
#define VIRGL_BIND_MINIGBM_CAMERA_READ (1u << 25)
#define VIRGL_BIND_MINIGBM_HW_VIDEO_DECODER (1u << 26)
#define VIRGL_BIND_MINIGBM_HW_VIDEO_ENCODER (1u << 27)
#define VIRGL_BIND_MINIGBM_SW_READ_OFTEN (1u << 28)
#define VIRGL_BIND_MINIGBM_SW_READ_RARELY (1u << 29)
#define VIRGL_BIND_MINIGBM_SW_WRITE_OFTEN (1u << 30)
#define VIRGL_BIND_MINIGBM_SW_WRITE_RARELY (1u << 31)
#define VIRGL_BIND_MINIGBM_PROTECTED (0xfu << 28) // Mutually exclusive with SW_ flags

struct virgl_caps_bool_set1 {
        unsigned indep_blend_enable:1;
        unsigned indep_blend_func:1;
        unsigned cube_map_array:1;
        unsigned shader_stencil_export:1;
        unsigned conditional_render:1;
        unsigned start_instance:1;
        unsigned primitive_restart:1;
        unsigned blend_eq_sep:1;
        unsigned instanceid:1;
        unsigned vertex_element_instance_divisor:1;
        unsigned seamless_cube_map:1;
        unsigned occlusion_query:1;
        unsigned timer_query:1;
        unsigned streamout_pause_resume:1;
        unsigned texture_multisample:1;
        unsigned fragment_coord_conventions:1;
        unsigned depth_clip_disable:1;
        unsigned seamless_cube_map_per_texture:1;
        unsigned ubo:1;
        unsigned color_clamping:1; /* not in GL 3.1 core profile */
        unsigned poly_stipple:1; /* not in GL 3.1 core profile */
        unsigned mirror_clamp:1;
        unsigned texture_query_lod:1;
        unsigned has_fp64:1;
        unsigned has_tessellation_shaders:1;
        unsigned has_indirect_draw:1;
        unsigned has_sample_shading:1;
        unsigned has_cull:1;
        unsigned conditional_render_inverted:1;
        unsigned derivative_control:1;
        unsigned polygon_offset_clamp:1;
        unsigned transform_feedback_overflow_query:1;
        /* DO NOT ADD ANYMORE MEMBERS - need to add another 32-bit to v2 caps */
};

/* endless expansion capabilites - current gallium has 252 formats */
struct virgl_supported_format_mask {
        uint32_t bitmask[16];
};
/* capabilities set 2 - version 1 - 32-bit and float values */
struct virgl_caps_v1 {
        uint32_t max_version;
        struct virgl_supported_format_mask sampler;
        struct virgl_supported_format_mask render;
        struct virgl_supported_format_mask depthstencil;
        struct virgl_supported_format_mask vertexbuffer;
        struct virgl_caps_bool_set1 bset;
        uint32_t glsl_level;
        uint32_t max_texture_array_layers;
        uint32_t max_streamout_buffers;
        uint32_t max_dual_source_render_targets;
        uint32_t max_render_targets;
        uint32_t max_samples;
        uint32_t prim_mask;
        uint32_t max_tbo_size;
        uint32_t max_uniform_blocks;
        uint32_t max_viewports;
        uint32_t max_texture_gather_components;
};

struct virgl_video_caps {
        uint32_t profile:8;
        uint32_t entrypoint:8;
        uint32_t max_level:8;
        uint32_t stacked_frames:8;

        uint32_t max_width:16;
        uint32_t max_height:16;

        uint32_t prefered_format:16;
        uint32_t max_macroblocks:16;

        uint32_t npot_texture:1;
        uint32_t supports_progressive:1;
        uint32_t supports_interlaced:1;
        uint32_t prefers_interlaced:1;
        uint32_t max_temporal_layers:8;
        uint32_t reserved:20;
};

/*
 * This struct should be growable when used in capset 2,
 * so we shouldn't have to add a v3 ever.
 */
struct virgl_caps_v2 {
        struct virgl_caps_v1 v1;
        float min_aliased_point_size;
        float max_aliased_point_size;
        float min_smooth_point_size;
        float max_smooth_point_size;
        float min_aliased_line_width;
        float max_aliased_line_width;
        float min_smooth_line_width;
        float max_smooth_line_width;
        float max_texture_lod_bias;
        uint32_t max_geom_output_vertices;
        uint32_t max_geom_total_output_components;
        uint32_t max_vertex_outputs;
        uint32_t max_vertex_attribs;
        uint32_t max_shader_patch_varyings;
        int32_t min_texel_offset;
        int32_t max_texel_offset;
        int32_t min_texture_gather_offset;
        int32_t max_texture_gather_offset;
        uint32_t texture_buffer_offset_alignment;
        uint32_t uniform_buffer_offset_alignment;
        uint32_t shader_buffer_offset_alignment;
        uint32_t capability_bits;
        uint32_t sample_locations[8];
        uint32_t max_vertex_attrib_stride;
        uint32_t max_shader_buffer_frag_compute;
        uint32_t max_shader_buffer_other_stages;
        uint32_t max_shader_image_frag_compute;
        uint32_t max_shader_image_other_stages;
        uint32_t max_image_samples;
        uint32_t max_compute_work_group_invocations;
        uint32_t max_compute_shared_memory_size;
        uint32_t max_compute_grid_size[3];
        uint32_t max_compute_block_size[3];
        uint32_t max_texture_2d_size;
        uint32_t max_texture_3d_size;
        uint32_t max_texture_cube_size;
        uint32_t max_combined_shader_buffers;
        uint32_t max_atomic_counters[6];
        uint32_t max_atomic_counter_buffers[6];
        uint32_t max_combined_atomic_counters;
        uint32_t max_combined_atomic_counter_buffers;
        uint32_t host_feature_check_version;
        struct virgl_supported_format_mask supported_readback_formats;
        struct virgl_supported_format_mask scanout;
        uint32_t capability_bits_v2;
        uint32_t max_video_memory;
        char renderer[64];
        float max_anisotropy;
        // NOTE: this informs guest-side PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS,
        // **NOT** GL_MAX_TEXTURE_IMAGE_UNITS!!!
        // Guest-side driver has always used it as such.
        uint32_t max_texture_samplers;
        struct virgl_supported_format_mask supported_multisample_formats;
        uint32_t max_const_buffer_size[6]; // PIPE_SHADER_TYPES
        uint32_t num_video_caps;
        struct virgl_video_caps video_caps[32];
        uint32_t max_uniform_block_size;
        uint32_t max_tcs_outputs;
        uint32_t max_tes_outputs;
        uint32_t max_shader_storage_blocks[6]; // PIPE_SHADER_TYPES
};

union virgl_caps {
        uint32_t max_version;
        struct virgl_caps_v1 v1;
        struct virgl_caps_v2 v2;
};

enum virgl_errors {
        VIRGL_ERROR_NONE,
        VIRGL_ERROR_UNKNOWN,
        VIRGL_ERROR_UNKNOWN_RESOURCE_FORMAT,
};

enum virgl_ctx_errors {
        VIRGL_ERROR_CTX_NONE,
        VIRGL_ERROR_CTX_UNKNOWN,
        VIRGL_ERROR_CTX_ILLEGAL_SHADER,
        VIRGL_ERROR_CTX_ILLEGAL_HANDLE,
        VIRGL_ERROR_CTX_ILLEGAL_RESOURCE,
        VIRGL_ERROR_CTX_ILLEGAL_SURFACE,
        VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT,
        VIRGL_ERROR_CTX_ILLEGAL_CMD_BUFFER,
        VIRGL_ERROR_CTX_GLES_HAVE_TES_BUT_MISS_TCS,
        VIRGL_ERROR_GL_ANY_SAMPLES_PASSED,
        VIRGL_ERROR_CTX_ILLEGAL_FORMAT,
        VIRGL_ERROR_CTX_ILLEGAL_SAMPLER_VIEW_TARGET,
        VIRGL_ERROR_CTX_TRANSFER_IOV_BOUNDS,
        VIRGL_ERROR_CTX_ILLEGAL_DUAL_SRC_BLEND,
        VIRGL_ERROR_CTX_UNSUPPORTED_FUNCTION,
        VIRGL_ERROR_CTX_ILLEGAL_PROGRAM_PIPELINE,
        VIRGL_ERROR_CTX_TOO_MANY_VERTEX_ATTRIBUTES,
        VIRGL_ERROR_CTX_UNSUPPORTED_TEX_WRAP,
        VIRGL_ERROR_CTX_CUBE_MAP_FACE_OUT_OF_RANGE,
        VIRGL_ERROR_CTX_BLIT_AREA_OUT_OF_RANGE,
        VIRGL_ERROR_CTX_SSBO_BINDING_RANGE,
        VIRGL_ERROR_CTX_RESOURCE_OUT_OF_RANGE,
};

enum virgl_statistics_query_index {
   VIRGL_STAT_QUERY_IA_VERTICES = 0,
   VIRGL_STAT_QUERY_IA_PRIMITIVES = 1,
   VIRGL_STAT_QUERY_VS_INVOCATIONS = 2,
   VIRGL_STAT_QUERY_GS_INVOCATIONS = 3,
   VIRGL_STAT_QUERY_GS_PRIMITIVES = 4,
   VIRGL_STAT_QUERY_C_INVOCATIONS = 5,
   VIRGL_STAT_QUERY_C_PRIMITIVES = 6,
   VIRGL_STAT_QUERY_PS_INVOCATIONS = 7,
   VIRGL_STAT_QUERY_HS_INVOCATIONS = 8,
   VIRGL_STAT_QUERY_DS_INVOCATIONS = 9,
   VIRGL_STAT_QUERY_CS_INVOCATIONS = 10,
};

/**
 * Flags for the driver about resource behaviour:
 */
#define VIRGL_RESOURCE_Y_0_TOP (1 << 0)
#define VIRGL_RESOURCE_FLAG_MAP_PERSISTENT (1 << 1)
#define VIRGL_RESOURCE_FLAG_MAP_COHERENT   (1 << 2)

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                          source/v64/third_party/virgl/virgl_protocol.h                                                       0000644 0000000 0000000 00000074035 00000000000 016566  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Copyright 2014, 2015 Red Hat.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * on the rights to use, copy, modify, merge, publish, distribute, sub
 * license, and/or sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#ifndef VIRGL_PROTOCOL_H
#define VIRGL_PROTOCOL_H

#include <stdint.h>

#define VIRGL_QUERY_STATE_NEW 0
#define VIRGL_QUERY_STATE_DONE 1
#define VIRGL_QUERY_STATE_WAIT_HOST 2

struct virgl_host_query_state {
   uint32_t query_state;
   uint32_t result_size;
   uint64_t result;
};

struct virgl_memory_info
{
   uint32_t total_device_memory; /**< size of device memory, e.g. VRAM */
   uint32_t avail_device_memory; /**< free device memory at the moment */
   uint32_t total_staging_memory; /**< size of staging memory, e.g. GART */
   uint32_t avail_staging_memory; /**< free staging memory at the moment */
   uint32_t device_memory_evicted; /**< size of memory evicted (monotonic counter) */
   uint32_t nr_device_memory_evictions; /**< # of evictions (monotonic counter) */
};

#define VIRGL_RESOURCE_MAX_PLANES	4
struct virgl_resource_layout
{
    uint64_t modifier;
    uint32_t num_planes;
    uint32_t reserved1;
    struct {
        uint64_t offset;
        uint32_t stride;
        uint32_t size;
    } planes[VIRGL_RESOURCE_MAX_PLANES];
};

#define VIRGL_MAX_FORMATS_MODIFIERS	128
struct virgl_gbm_format_modifier
{
    uint64_t num;
    struct {
        uint64_t modifier;
        uint64_t virgl_format;
    } formats[VIRGL_MAX_FORMATS_MODIFIERS];
};

enum virgl_object_type {
   VIRGL_OBJECT_NULL,
   VIRGL_OBJECT_BLEND,
   VIRGL_OBJECT_RASTERIZER,
   VIRGL_OBJECT_DSA,
   VIRGL_OBJECT_SHADER,
   VIRGL_OBJECT_VERTEX_ELEMENTS,
   VIRGL_OBJECT_SAMPLER_VIEW,
   VIRGL_OBJECT_SAMPLER_STATE,
   VIRGL_OBJECT_SURFACE,
   VIRGL_OBJECT_QUERY,
   VIRGL_OBJECT_STREAMOUT_TARGET,
   VIRGL_OBJECT_MSAA_SURFACE,
   VIRGL_MAX_OBJECTS,
};

/* context cmds to be encoded in the command stream */
enum virgl_context_cmd {
   VIRGL_CCMD_NOP = 0,
   VIRGL_CCMD_CREATE_OBJECT = 1,
   VIRGL_CCMD_BIND_OBJECT,
   VIRGL_CCMD_DESTROY_OBJECT,
   VIRGL_CCMD_SET_VIEWPORT_STATE,
   VIRGL_CCMD_SET_FRAMEBUFFER_STATE,
   VIRGL_CCMD_SET_VERTEX_BUFFERS,
   VIRGL_CCMD_CLEAR,
   VIRGL_CCMD_DRAW_VBO,
   VIRGL_CCMD_RESOURCE_INLINE_WRITE,
   VIRGL_CCMD_SET_SAMPLER_VIEWS,
   VIRGL_CCMD_SET_INDEX_BUFFER,
   VIRGL_CCMD_SET_CONSTANT_BUFFER,
   VIRGL_CCMD_SET_STENCIL_REF,
   VIRGL_CCMD_SET_BLEND_COLOR,
   VIRGL_CCMD_SET_SCISSOR_STATE,
   VIRGL_CCMD_BLIT,
   VIRGL_CCMD_RESOURCE_COPY_REGION,
   VIRGL_CCMD_BIND_SAMPLER_STATES,
   VIRGL_CCMD_BEGIN_QUERY,
   VIRGL_CCMD_END_QUERY,
   VIRGL_CCMD_GET_QUERY_RESULT,
   VIRGL_CCMD_SET_POLYGON_STIPPLE,
   VIRGL_CCMD_SET_CLIP_STATE,
   VIRGL_CCMD_SET_SAMPLE_MASK,
   VIRGL_CCMD_SET_STREAMOUT_TARGETS,
   VIRGL_CCMD_SET_RENDER_CONDITION,
   VIRGL_CCMD_SET_UNIFORM_BUFFER,

   VIRGL_CCMD_SET_SUB_CTX,
   VIRGL_CCMD_CREATE_SUB_CTX,
   VIRGL_CCMD_DESTROY_SUB_CTX,
   VIRGL_CCMD_BIND_SHADER,
   VIRGL_CCMD_SET_TESS_STATE,
   VIRGL_CCMD_SET_MIN_SAMPLES,
   VIRGL_CCMD_SET_SHADER_BUFFERS,
   VIRGL_CCMD_SET_SHADER_IMAGES,
   VIRGL_CCMD_MEMORY_BARRIER,
   VIRGL_CCMD_LAUNCH_GRID,
   VIRGL_CCMD_SET_FRAMEBUFFER_STATE_NO_ATTACH,
   VIRGL_CCMD_TEXTURE_BARRIER,
   VIRGL_CCMD_SET_ATOMIC_BUFFERS,
   VIRGL_CCMD_SET_DEBUG_FLAGS,
   VIRGL_CCMD_GET_QUERY_RESULT_QBO,
   VIRGL_CCMD_TRANSFER3D,
   VIRGL_CCMD_END_TRANSFERS,
   VIRGL_CCMD_COPY_TRANSFER3D,
   VIRGL_CCMD_SET_TWEAKS,
   VIRGL_CCMD_CLEAR_TEXTURE,
   VIRGL_CCMD_PIPE_RESOURCE_CREATE,
   VIRGL_CCMD_PIPE_RESOURCE_SET_TYPE,
   VIRGL_CCMD_GET_MEMORY_INFO,
   VIRGL_CCMD_SEND_STRING_MARKER,
   VIRGL_CCMD_LINK_SHADER,

   /* video codec */
   VIRGL_CCMD_CREATE_VIDEO_CODEC,
   VIRGL_CCMD_DESTROY_VIDEO_CODEC,
   VIRGL_CCMD_CREATE_VIDEO_BUFFER,
   VIRGL_CCMD_DESTROY_VIDEO_BUFFER,
   VIRGL_CCMD_BEGIN_FRAME,
   VIRGL_CCMD_DECODE_MACROBLOCK,
   VIRGL_CCMD_DECODE_BITSTREAM,
   VIRGL_CCMD_ENCODE_BITSTREAM,
   VIRGL_CCMD_END_FRAME,

   VIRGL_CCMD_CLEAR_SURFACE,
   VIRGL_CCMD_GET_PIPE_RESOURCE_LAYOUT,
   VIRGL_CCMD_QUERY_GBM_FORMAT_MODIFIER,

   VIRGL_MAX_COMMANDS
};

/*
 8-bit cmd headers
 8-bit object type
 16-bit length
*/

#define VIRGL_CMD0(cmd, obj, len) ((cmd) | ((obj) << 8) | ((len) << 16))
#define VIRGL_CMD0_MAX_DWORDS (((1ULL << 16) - 1) / 4) * 4

/* hw specification */
#define VIRGL_MAX_COLOR_BUFS 8
#define VIRGL_MAX_CLIP_PLANES 8

#define VIRGL_OBJ_CREATE_HEADER 0
#define VIRGL_OBJ_CREATE_HANDLE 1

#define VIRGL_OBJ_BIND_HEADER 0
#define VIRGL_OBJ_BIND_HANDLE 1

#define VIRGL_OBJ_DESTROY_HANDLE 1

/* some of these defines are a specification - not used in the code */
/* bit offsets for blend state object */
#define VIRGL_OBJ_BLEND_SIZE (VIRGL_MAX_COLOR_BUFS + 3)
#define VIRGL_OBJ_BLEND_HANDLE 1
#define VIRGL_OBJ_BLEND_S0 2
#define VIRGL_OBJ_BLEND_S0_INDEPENDENT_BLEND_ENABLE(x) ((x) & 0x1 << 0)
#define VIRGL_OBJ_BLEND_S0_LOGICOP_ENABLE(x) (((x) & 0x1) << 1)
#define VIRGL_OBJ_BLEND_S0_DITHER(x) (((x) & 0x1) << 2)
#define VIRGL_OBJ_BLEND_S0_ALPHA_TO_COVERAGE(x) (((x) & 0x1) << 3)
#define VIRGL_OBJ_BLEND_S0_ALPHA_TO_ONE(x) (((x) & 0x1) << 4)
#define VIRGL_OBJ_BLEND_S1 3
#define VIRGL_OBJ_BLEND_S1_LOGICOP_FUNC(x) (((x) & 0xf) << 0)
/* repeated once per number of cbufs */

#define VIRGL_OBJ_BLEND_S2(cbuf) (4 + (cbuf))
#define VIRGL_OBJ_BLEND_S2_RT_BLEND_ENABLE(x) (((x) & 0x1) << 0)
#define VIRGL_OBJ_BLEND_S2_RT_RGB_FUNC(x) (((x) & 0x7) << 1)
#define VIRGL_OBJ_BLEND_S2_RT_RGB_SRC_FACTOR(x) (((x) & 0x1f) << 4)
#define VIRGL_OBJ_BLEND_S2_RT_RGB_DST_FACTOR(x) (((x) & 0x1f) << 9)
#define VIRGL_OBJ_BLEND_S2_RT_ALPHA_FUNC(x) (((x) & 0x7) << 14)
#define VIRGL_OBJ_BLEND_S2_RT_ALPHA_SRC_FACTOR(x) (((x) & 0x1f) << 17)
#define VIRGL_OBJ_BLEND_S2_RT_ALPHA_DST_FACTOR(x) (((x) & 0x1f) << 22)
#define VIRGL_OBJ_BLEND_S2_RT_COLORMASK(x) (((x) & 0xf) << 27)

/* bit offsets for DSA state */
#define VIRGL_OBJ_DSA_SIZE 5
#define VIRGL_OBJ_DSA_HANDLE 1
#define VIRGL_OBJ_DSA_S0 2
#define VIRGL_OBJ_DSA_S0_DEPTH_ENABLE(x) (((x) & 0x1) << 0)
#define VIRGL_OBJ_DSA_S0_DEPTH_WRITEMASK(x) (((x) & 0x1) << 1)
#define VIRGL_OBJ_DSA_S0_DEPTH_FUNC(x) (((x) & 0x7) << 2)
#define VIRGL_OBJ_DSA_S0_ALPHA_ENABLED(x) (((x) & 0x1) << 8)
#define VIRGL_OBJ_DSA_S0_ALPHA_FUNC(x) (((x) & 0x7) << 9)
#define VIRGL_OBJ_DSA_S1 3
#define VIRGL_OBJ_DSA_S2 4
#define VIRGL_OBJ_DSA_S1_STENCIL_ENABLED(x) (((x) & 0x1) << 0)
#define VIRGL_OBJ_DSA_S1_STENCIL_FUNC(x) (((x) & 0x7) << 1)
#define VIRGL_OBJ_DSA_S1_STENCIL_FAIL_OP(x) (((x) & 0x7) << 4)
#define VIRGL_OBJ_DSA_S1_STENCIL_ZPASS_OP(x) (((x) & 0x7) << 7)
#define VIRGL_OBJ_DSA_S1_STENCIL_ZFAIL_OP(x) (((x) & 0x7) << 10)
#define VIRGL_OBJ_DSA_S1_STENCIL_VALUEMASK(x) (((x) & 0xff) << 13)
#define VIRGL_OBJ_DSA_S1_STENCIL_WRITEMASK(x) (((x) & 0xff) << 21)
#define VIRGL_OBJ_DSA_ALPHA_REF 5

/* offsets for rasterizer state */
#define VIRGL_OBJ_RS_SIZE 9
#define VIRGL_OBJ_RS_HANDLE 1
#define VIRGL_OBJ_RS_S0 2
#define VIRGL_OBJ_RS_S0_FLATSHADE(x) (((x) & 0x1) << 0)
#define VIRGL_OBJ_RS_S0_DEPTH_CLIP(x) (((x) & 0x1) << 1)
#define VIRGL_OBJ_RS_S0_CLIP_HALFZ(x) (((x) & 0x1) << 2)
#define VIRGL_OBJ_RS_S0_RASTERIZER_DISCARD(x) (((x) & 0x1) << 3)
#define VIRGL_OBJ_RS_S0_FLATSHADE_FIRST(x) (((x) & 0x1) << 4)
#define VIRGL_OBJ_RS_S0_LIGHT_TWOSIZE(x) (((x) & 0x1) << 5)
#define VIRGL_OBJ_RS_S0_SPRITE_COORD_MODE(x) (((x) & 0x1) << 6)
#define VIRGL_OBJ_RS_S0_POINT_QUAD_RASTERIZATION(x) (((x) & 0x1) << 7)
#define VIRGL_OBJ_RS_S0_CULL_FACE(x) (((x) & 0x3) << 8)
#define VIRGL_OBJ_RS_S0_FILL_FRONT(x) (((x) & 0x3) << 10)
#define VIRGL_OBJ_RS_S0_FILL_BACK(x) (((x) & 0x3) << 12)
#define VIRGL_OBJ_RS_S0_SCISSOR(x) (((x) & 0x1) << 14)
#define VIRGL_OBJ_RS_S0_FRONT_CCW(x) (((x) & 0x1) << 15)
#define VIRGL_OBJ_RS_S0_CLAMP_VERTEX_COLOR(x) (((x) & 0x1) << 16)
#define VIRGL_OBJ_RS_S0_CLAMP_FRAGMENT_COLOR(x) (((x) & 0x1) << 17)
#define VIRGL_OBJ_RS_S0_OFFSET_LINE(x) (((x) & 0x1) << 18)
#define VIRGL_OBJ_RS_S0_OFFSET_POINT(x) (((x) & 0x1) << 19)
#define VIRGL_OBJ_RS_S0_OFFSET_TRI(x) (((x) & 0x1) << 20)
#define VIRGL_OBJ_RS_S0_POLY_SMOOTH(x) (((x) & 0x1) << 21)
#define VIRGL_OBJ_RS_S0_POLY_STIPPLE_ENABLE(x) (((x) & 0x1) << 22)
#define VIRGL_OBJ_RS_S0_POINT_SMOOTH(x) (((x) & 0x1) << 23)
#define VIRGL_OBJ_RS_S0_POINT_SIZE_PER_VERTEX(x) (((x) & 0x1) << 24)
#define VIRGL_OBJ_RS_S0_MULTISAMPLE(x) (((x) & 0x1) << 25)
#define VIRGL_OBJ_RS_S0_LINE_SMOOTH(x) (((x) & 0x1) << 26)
#define VIRGL_OBJ_RS_S0_LINE_STIPPLE_ENABLE(x) (((x) & 0x1) << 27)
#define VIRGL_OBJ_RS_S0_LINE_LAST_PIXEL(x) (((x) & 0x1) << 28)
#define VIRGL_OBJ_RS_S0_HALF_PIXEL_CENTER(x) (((x) & 0x1) << 29)
#define VIRGL_OBJ_RS_S0_BOTTOM_EDGE_RULE(x) (((x) & 0x1) << 30)
#define VIRGL_OBJ_RS_S0_FORCE_PERSAMPLE_INTERP(x) (((x) & 0x1) << 31)

#define VIRGL_OBJ_RS_POINT_SIZE 3
#define VIRGL_OBJ_RS_SPRITE_COORD_ENABLE 4
#define VIRGL_OBJ_RS_S3 5

#define VIRGL_OBJ_RS_S3_LINE_STIPPLE_PATTERN(x) (((x) & 0xffff) << 0)
#define VIRGL_OBJ_RS_S3_LINE_STIPPLE_FACTOR(x) (((x) & 0xff) << 16)
#define VIRGL_OBJ_RS_S3_CLIP_PLANE_ENABLE(x) (((x) & 0xff) << 24)
#define VIRGL_OBJ_RS_LINE_WIDTH 6
#define VIRGL_OBJ_RS_OFFSET_UNITS 7
#define VIRGL_OBJ_RS_OFFSET_SCALE 8
#define VIRGL_OBJ_RS_OFFSET_CLAMP 9

#define VIRGL_OBJ_CLEAR_SIZE 8
#define VIRGL_OBJ_CLEAR_BUFFERS 1
#define VIRGL_OBJ_CLEAR_COLOR_0 2 /* color is 4 * u32/f32/i32 */
#define VIRGL_OBJ_CLEAR_COLOR_1 3
#define VIRGL_OBJ_CLEAR_COLOR_2 4
#define VIRGL_OBJ_CLEAR_COLOR_3 5
#define VIRGL_OBJ_CLEAR_DEPTH_0 6 /* depth is a double precision float */
#define VIRGL_OBJ_CLEAR_DEPTH_1 7
#define VIRGL_OBJ_CLEAR_STENCIL 8

/* shader object */
#define VIRGL_OBJ_SHADER_HDR_SIZE(nso) (5 + ((nso) ? (2 * nso) + 4 : 0))
#define VIRGL_OBJ_SHADER_HANDLE 1
#define VIRGL_OBJ_SHADER_TYPE 2
#define VIRGL_OBJ_SHADER_OFFSET 3
#define VIRGL_OBJ_SHADER_OFFSET_VAL(x) (((x) & 0x7fffffff) << 0)
/* start contains full length in VAL - also implies continuations */
/* continuation contains offset in VAL */
#define VIRGL_OBJ_SHADER_OFFSET_CONT (0x1u << 31)
#define VIRGL_OBJ_SHADER_NUM_TOKENS 4
#define VIRGL_OBJ_SHADER_SO_NUM_OUTPUTS 5
#define VIRGL_OBJ_SHADER_SO_STRIDE(x) (6 + (x))
#define VIRGL_OBJ_SHADER_SO_OUTPUT0(x) (10 + (x * 2))
#define VIRGL_OBJ_SHADER_SO_OUTPUT_REGISTER_INDEX(x) (((x) & 0xff) << 0)
#define VIRGL_OBJ_SHADER_SO_OUTPUT_START_COMPONENT(x) (((x) & 0x3) << 8)
#define VIRGL_OBJ_SHADER_SO_OUTPUT_NUM_COMPONENTS(x) (((x) & 0x7) << 10)
#define VIRGL_OBJ_SHADER_SO_OUTPUT_BUFFER(x) (((x) & 0x7) << 13)
#define VIRGL_OBJ_SHADER_SO_OUTPUT_DST_OFFSET(x) (((x) & 0xffff) << 16)
#define VIRGL_OBJ_SHADER_SO_OUTPUT0_SO(x) (11 + (x * 2))
#define VIRGL_OBJ_SHADER_SO_OUTPUT_STREAM(x) (((x) & 0x03) << 0)

/* viewport state */
#define VIRGL_SET_VIEWPORT_STATE_SIZE(num_viewports) ((6 * (num_viewports)) + 1)
#define VIRGL_SET_VIEWPORT_START_SLOT 1
#define VIRGL_SET_VIEWPORT_STATE_SCALE_0(x) (2 + (x * 6))
#define VIRGL_SET_VIEWPORT_STATE_SCALE_1(x) (3 + (x * 6))
#define VIRGL_SET_VIEWPORT_STATE_SCALE_2(x) (4 + (x * 6))
#define VIRGL_SET_VIEWPORT_STATE_TRANSLATE_0(x) (5 + (x * 6))
#define VIRGL_SET_VIEWPORT_STATE_TRANSLATE_1(x) (6 + (x * 6))
#define VIRGL_SET_VIEWPORT_STATE_TRANSLATE_2(x) (7 + (x * 6))

/* framebuffer state */
#define VIRGL_SET_FRAMEBUFFER_STATE_SIZE(nr_cbufs) ((nr_cbufs) + 2)
#define VIRGL_SET_FRAMEBUFFER_STATE_NR_CBUFS 1
#define VIRGL_SET_FRAMEBUFFER_STATE_NR_ZSURF_HANDLE 2
#define VIRGL_SET_FRAMEBUFFER_STATE_CBUF_HANDLE(x) ((x) + 3)

/* vertex elements object */
#define VIRGL_OBJ_VERTEX_ELEMENTS_SIZE(num_elements) (((num_elements) * 4) + 1)
#define VIRGL_OBJ_VERTEX_ELEMENTS_HANDLE 1
#define VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(x) (((x) * 4) + 2) /* repeated per VE */
#define VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(x) (((x) * 4) + 3)
#define VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(x) (((x) * 4) + 4)
#define VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(x) (((x) * 4) + 5)

/* vertex buffers */
#define VIRGL_SET_VERTEX_BUFFERS_SIZE(num_buffers) ((num_buffers) * 3)
#define VIRGL_SET_VERTEX_BUFFER_STRIDE(x) (((x) * 3) + 1)
#define VIRGL_SET_VERTEX_BUFFER_OFFSET(x) (((x) * 3) + 2)
#define VIRGL_SET_VERTEX_BUFFER_HANDLE(x) (((x) * 3) + 3)

/* index buffer */
#define VIRGL_SET_INDEX_BUFFER_SIZE(ib) (((ib) ? 2 : 0) + 1)
#define VIRGL_SET_INDEX_BUFFER_HANDLE 1
#define VIRGL_SET_INDEX_BUFFER_INDEX_SIZE 2 /* only if sending an IB handle */
#define VIRGL_SET_INDEX_BUFFER_OFFSET 3     /* only if sending an IB handle */

/* constant buffer */
#define VIRGL_SET_CONSTANT_BUFFER_SHADER_TYPE 1
#define VIRGL_SET_CONSTANT_BUFFER_INDEX 2
#define VIRGL_SET_CONSTANT_BUFFER_DATA_START 3

#define VIRGL_SET_UNIFORM_BUFFER_SIZE 5
#define VIRGL_SET_UNIFORM_BUFFER_SHADER_TYPE 1
#define VIRGL_SET_UNIFORM_BUFFER_INDEX 2
#define VIRGL_SET_UNIFORM_BUFFER_OFFSET 3
#define VIRGL_SET_UNIFORM_BUFFER_LENGTH 4
#define VIRGL_SET_UNIFORM_BUFFER_RES_HANDLE 5

/* draw VBO */
#define VIRGL_DRAW_VBO_SIZE 12
#define VIRGL_DRAW_VBO_SIZE_TESS 14
#define VIRGL_DRAW_VBO_SIZE_INDIRECT 20
#define VIRGL_DRAW_VBO_START 1
#define VIRGL_DRAW_VBO_COUNT 2
#define VIRGL_DRAW_VBO_MODE 3
#define VIRGL_DRAW_VBO_INDEXED 4
#define VIRGL_DRAW_VBO_INSTANCE_COUNT 5
#define VIRGL_DRAW_VBO_INDEX_BIAS 6
#define VIRGL_DRAW_VBO_START_INSTANCE 7
#define VIRGL_DRAW_VBO_PRIMITIVE_RESTART 8
#define VIRGL_DRAW_VBO_RESTART_INDEX 9
#define VIRGL_DRAW_VBO_MIN_INDEX 10
#define VIRGL_DRAW_VBO_MAX_INDEX 11
#define VIRGL_DRAW_VBO_COUNT_FROM_SO 12
/* tess packet */
#define VIRGL_DRAW_VBO_VERTICES_PER_PATCH 13
#define VIRGL_DRAW_VBO_DRAWID 14
/* indirect packet */
#define VIRGL_DRAW_VBO_INDIRECT_HANDLE 15
#define VIRGL_DRAW_VBO_INDIRECT_OFFSET 16
#define VIRGL_DRAW_VBO_INDIRECT_STRIDE 17
#define VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT 18
#define VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_OFFSET 19
#define VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_HANDLE 20

/* create surface */
#define VIRGL_OBJ_SURFACE_SIZE 5
#define VIRGL_OBJ_SURFACE_HANDLE 1
#define VIRGL_OBJ_SURFACE_RES_HANDLE 2
#define VIRGL_OBJ_SURFACE_FORMAT 3
#define VIRGL_OBJ_SURFACE_BUFFER_FIRST_ELEMENT 4
#define VIRGL_OBJ_SURFACE_BUFFER_LAST_ELEMENT 5
#define VIRGL_OBJ_SURFACE_TEXTURE_LEVEL 4
#define VIRGL_OBJ_SURFACE_TEXTURE_LAYERS 5

/* create surface with implicit MSAA support (for EXT_multisample_render_to_texture) */
#define VIRGL_OBJ_MSAA_SURFACE_SIZE (VIRGL_OBJ_SURFACE_SIZE + 1)
#define VIRGL_OBJ_SURFACE_SAMPLE_COUNT 6

/* create streamout target */
#define VIRGL_OBJ_STREAMOUT_SIZE 4
#define VIRGL_OBJ_STREAMOUT_HANDLE 1
#define VIRGL_OBJ_STREAMOUT_RES_HANDLE 2
#define VIRGL_OBJ_STREAMOUT_BUFFER_OFFSET 3
#define VIRGL_OBJ_STREAMOUT_BUFFER_SIZE 4

/* sampler state */
#define VIRGL_OBJ_SAMPLER_STATE_SIZE 9
#define VIRGL_OBJ_SAMPLER_STATE_HANDLE 1
#define VIRGL_OBJ_SAMPLER_STATE_S0 2
#define VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_S(x) (((x) & 0x7) << 0)
#define VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_T(x) (((x) & 0x7) << 3)
#define VIRGL_OBJ_SAMPLE_STATE_S0_WRAP_R(x) (((x) & 0x7) << 6)
#define VIRGL_OBJ_SAMPLE_STATE_S0_MIN_IMG_FILTER(x) (((x) & 0x1) << 9) /* Used to be 2 bits wide */
#define VIRGL_OBJ_SAMPLE_STATE_S0_MIN_MIP_FILTER(x) (((x) & 0x3) << 11)
#define VIRGL_OBJ_SAMPLE_STATE_S0_MAG_IMG_FILTER(x) (((x) & 0x1) << 13) /* Used to be 2 bits wide */
#define VIRGL_OBJ_SAMPLE_STATE_S0_COMPARE_MODE(x) (((x) & 0x1) << 15)
#define VIRGL_OBJ_SAMPLE_STATE_S0_COMPARE_FUNC(x) (((x) & 0x7) << 16)
#define VIRGL_OBJ_SAMPLE_STATE_S0_SEAMLESS_CUBE_MAP(x) (((x) & 0x1) << 19)
#define VIRGL_OBJ_SAMPLE_STATE_S0_MAX_ANISOTROPY(x) (((x & 0x1f)) << 20) /* Used to be 6 bits wide */

#define VIRGL_OBJ_SAMPLER_STATE_LOD_BIAS 3
#define VIRGL_OBJ_SAMPLER_STATE_MIN_LOD 4
#define VIRGL_OBJ_SAMPLER_STATE_MAX_LOD 5
#define VIRGL_OBJ_SAMPLER_STATE_BORDER_COLOR(x) ((x) + 6) /* 6 - 9 */


/* sampler view */
#define VIRGL_OBJ_SAMPLER_VIEW_SIZE 6
#define VIRGL_OBJ_SAMPLER_VIEW_HANDLE 1
#define VIRGL_OBJ_SAMPLER_VIEW_RES_HANDLE 2
#define VIRGL_OBJ_SAMPLER_VIEW_FORMAT 3
#define VIRGL_OBJ_SAMPLER_VIEW_BUFFER_FIRST_ELEMENT 4
#define VIRGL_OBJ_SAMPLER_VIEW_BUFFER_LAST_ELEMENT 5
#define VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LAYER 4
#define VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LEVEL 5
#define VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE 6
#define VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_R(x) (((x) & 0x7) << 0)
#define VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_G(x) (((x) & 0x7) << 3)
#define VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_B(x) (((x) & 0x7) << 6)
#define VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE_A(x) (((x) & 0x7) << 9)

/* set sampler views */
#define VIRGL_SET_SAMPLER_VIEWS_SIZE(num_views) ((num_views) + 2)
#define VIRGL_SET_SAMPLER_VIEWS_SHADER_TYPE 1
#define VIRGL_SET_SAMPLER_VIEWS_START_SLOT 2
#define VIRGL_SET_SAMPLER_VIEWS_V0_HANDLE 3

/* bind sampler states */
#define VIRGL_BIND_SAMPLER_STATES(num_states) ((num_states) + 2)
#define VIRGL_BIND_SAMPLER_STATES_SHADER_TYPE 1
#define VIRGL_BIND_SAMPLER_STATES_START_SLOT 2
#define VIRGL_BIND_SAMPLER_STATES_S0_HANDLE 3

/* set stencil reference */
#define VIRGL_SET_STENCIL_REF_SIZE 1
#define VIRGL_SET_STENCIL_REF 1
#define VIRGL_STENCIL_REF_VAL(f, s) ((f & 0xff) | (((s & 0xff) << 8)))

/* set blend color */
#define VIRGL_SET_BLEND_COLOR_SIZE 4
#define VIRGL_SET_BLEND_COLOR(x) ((x) + 1)

/* set scissor state */
#define VIRGL_SET_SCISSOR_STATE_SIZE(x) (1 + 2 * x)
#define VIRGL_SET_SCISSOR_START_SLOT 1
#define VIRGL_SET_SCISSOR_MINX_MINY(x) (2 + (x * 2))
#define VIRGL_SET_SCISSOR_MAXX_MAXY(x) (3 + (x * 2))

/* resource copy region */
#define VIRGL_CMD_RESOURCE_COPY_REGION_SIZE 13
#define VIRGL_CMD_RCR_DST_RES_HANDLE 1
#define VIRGL_CMD_RCR_DST_LEVEL 2
#define VIRGL_CMD_RCR_DST_X 3
#define VIRGL_CMD_RCR_DST_Y 4
#define VIRGL_CMD_RCR_DST_Z 5
#define VIRGL_CMD_RCR_SRC_RES_HANDLE 6
#define VIRGL_CMD_RCR_SRC_LEVEL 7
#define VIRGL_CMD_RCR_SRC_X 8
#define VIRGL_CMD_RCR_SRC_Y 9
#define VIRGL_CMD_RCR_SRC_Z 10
#define VIRGL_CMD_RCR_SRC_W 11
#define VIRGL_CMD_RCR_SRC_H 12
#define VIRGL_CMD_RCR_SRC_D 13

/* blit */
#define VIRGL_CMD_BLIT_SIZE 21
#define VIRGL_CMD_BLIT_S0 1
#define VIRGL_CMD_BLIT_S0_MASK(x) (((x) & 0xff) << 0)
#define VIRGL_CMD_BLIT_S0_FILTER(x) (((x) & 0x3) << 8)
#define VIRGL_CMD_BLIT_S0_SCISSOR_ENABLE(x) (((x) & 0x1) << 10)
#define VIRGL_CMD_BLIT_S0_RENDER_CONDITION_ENABLE(x) (((x) & 0x1) << 11)
#define VIRGL_CMD_BLIT_S0_ALPHA_BLEND(x) (((x) & 0x1) << 12)
#define VIRGL_CMD_BLIT_SCISSOR_MINX_MINY 2
#define VIRGL_CMD_BLIT_SCISSOR_MAXX_MAXY 3
#define VIRGL_CMD_BLIT_DST_RES_HANDLE 4
#define VIRGL_CMD_BLIT_DST_LEVEL 5
#define VIRGL_CMD_BLIT_DST_FORMAT 6
#define VIRGL_CMD_BLIT_DST_X 7
#define VIRGL_CMD_BLIT_DST_Y 8
#define VIRGL_CMD_BLIT_DST_Z 9
#define VIRGL_CMD_BLIT_DST_W 10
#define VIRGL_CMD_BLIT_DST_H 11
#define VIRGL_CMD_BLIT_DST_D 12
#define VIRGL_CMD_BLIT_SRC_RES_HANDLE 13
#define VIRGL_CMD_BLIT_SRC_LEVEL 14
#define VIRGL_CMD_BLIT_SRC_FORMAT 15
#define VIRGL_CMD_BLIT_SRC_X 16
#define VIRGL_CMD_BLIT_SRC_Y 17
#define VIRGL_CMD_BLIT_SRC_Z 18
#define VIRGL_CMD_BLIT_SRC_W 19
#define VIRGL_CMD_BLIT_SRC_H 20
#define VIRGL_CMD_BLIT_SRC_D 21

/* query object */
#define VIRGL_OBJ_QUERY_SIZE 4
#define VIRGL_OBJ_QUERY_HANDLE 1
#define VIRGL_OBJ_QUERY_TYPE_INDEX 2
#define VIRGL_OBJ_QUERY_TYPE(x) (x & 0xffff)
#define VIRGL_OBJ_QUERY_INDEX(x) ((x & 0xffff) << 16)
#define VIRGL_OBJ_QUERY_OFFSET 3
#define VIRGL_OBJ_QUERY_RES_HANDLE 4

#define VIRGL_QUERY_BEGIN_HANDLE 1

#define VIRGL_QUERY_END_HANDLE 1

#define VIRGL_QUERY_RESULT_SIZE 2
#define VIRGL_QUERY_RESULT_HANDLE 1
#define VIRGL_QUERY_RESULT_WAIT 2

/* render condition */
#define VIRGL_RENDER_CONDITION_SIZE 3
#define VIRGL_RENDER_CONDITION_HANDLE 1
#define VIRGL_RENDER_CONDITION_CONDITION 2
#define VIRGL_RENDER_CONDITION_MODE 3

/* resource inline write */
#define VIRGL_RESOURCE_IW_RES_HANDLE 1
#define VIRGL_RESOURCE_IW_LEVEL 2
#define VIRGL_RESOURCE_IW_USAGE 3
#define VIRGL_RESOURCE_IW_STRIDE 4
#define VIRGL_RESOURCE_IW_LAYER_STRIDE 5
#define VIRGL_RESOURCE_IW_X 6
#define VIRGL_RESOURCE_IW_Y 7
#define VIRGL_RESOURCE_IW_Z 8
#define VIRGL_RESOURCE_IW_W 9
#define VIRGL_RESOURCE_IW_H 10
#define VIRGL_RESOURCE_IW_D 11
#define VIRGL_RESOURCE_IW_DATA_START 12

/* set streamout targets */
#define VIRGL_SET_STREAMOUT_TARGETS_APPEND_BITMASK 1
#define VIRGL_SET_STREAMOUT_TARGETS_H0 2

/* set sample mask */
#define VIRGL_SET_SAMPLE_MASK_SIZE 1
#define VIRGL_SET_SAMPLE_MASK_MASK 1

/* set clip state */
#define VIRGL_SET_CLIP_STATE_SIZE 32
#define VIRGL_SET_CLIP_STATE_C0 1

/* polygon stipple */
#define VIRGL_POLYGON_STIPPLE_SIZE 32
#define VIRGL_POLYGON_STIPPLE_P0 1

#define VIRGL_BIND_SHADER_SIZE 2
#define VIRGL_BIND_SHADER_HANDLE 1
#define VIRGL_BIND_SHADER_TYPE 2

/* tess state */
#define VIRGL_TESS_STATE_SIZE 6

/* set min samples */
#define VIRGL_SET_MIN_SAMPLES_SIZE 1
#define VIRGL_SET_MIN_SAMPLES_MASK 1

/* set shader buffers */
#define VIRGL_SET_SHADER_BUFFER_ELEMENT_SIZE 3
#define VIRGL_SET_SHADER_BUFFER_SIZE(x) (VIRGL_SET_SHADER_BUFFER_ELEMENT_SIZE * (x)) + 2
#define VIRGL_SET_SHADER_BUFFER_SHADER_TYPE 1
#define VIRGL_SET_SHADER_BUFFER_START_SLOT 2
#define VIRGL_SET_SHADER_BUFFER_OFFSET(x) ((x) * VIRGL_SET_SHADER_BUFFER_ELEMENT_SIZE + 3)
#define VIRGL_SET_SHADER_BUFFER_LENGTH(x) ((x) * VIRGL_SET_SHADER_BUFFER_ELEMENT_SIZE + 4)
#define VIRGL_SET_SHADER_BUFFER_RES_HANDLE(x) ((x) * VIRGL_SET_SHADER_BUFFER_ELEMENT_SIZE + 5)

/* set shader images */
#define VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE 5
#define VIRGL_SET_SHADER_IMAGE_SIZE(x) (VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE * (x)) + 2
#define VIRGL_SET_SHADER_IMAGE_SHADER_TYPE 1
#define VIRGL_SET_SHADER_IMAGE_START_SLOT 2
#define VIRGL_SET_SHADER_IMAGE_FORMAT(x) ((x) * VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE + 3)
#define VIRGL_SET_SHADER_IMAGE_ACCESS(x) ((x) * VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE + 4)
#define VIRGL_SET_SHADER_IMAGE_LAYER_OFFSET(x) ((x) * VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE + 5)
#define VIRGL_SET_SHADER_IMAGE_LEVEL_SIZE(x) ((x) * VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE + 6)
#define VIRGL_SET_SHADER_IMAGE_RES_HANDLE(x) ((x) * VIRGL_SET_SHADER_IMAGE_ELEMENT_SIZE + 7)

/* memory barrier */
#define VIRGL_MEMORY_BARRIER_SIZE 1
#define VIRGL_MEMORY_BARRIER_FLAGS 1

/* launch grid */
#define VIRGL_LAUNCH_GRID_SIZE 8
#define VIRGL_LAUNCH_BLOCK_X 1
#define VIRGL_LAUNCH_BLOCK_Y 2
#define VIRGL_LAUNCH_BLOCK_Z 3
#define VIRGL_LAUNCH_GRID_X 4
#define VIRGL_LAUNCH_GRID_Y 5
#define VIRGL_LAUNCH_GRID_Z 6
#define VIRGL_LAUNCH_INDIRECT_HANDLE 7
#define VIRGL_LAUNCH_INDIRECT_OFFSET 8

/* framebuffer state no attachment */
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_SIZE 2
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_WIDTH_HEIGHT 1
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_WIDTH(x) (x & 0xffff)
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_HEIGHT(x) ((x >> 16) & 0xffff)
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_LAYERS_SAMPLES 2
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_LAYERS(x) (x & 0xffff)
#define VIRGL_SET_FRAMEBUFFER_STATE_NO_ATTACH_SAMPLES(x) ((x >> 16) & 0xff)

/* texture barrier */
#define VIRGL_TEXTURE_BARRIER_SIZE 1
#define VIRGL_TEXTURE_BARRIER_FLAGS 1

/* hw atomics */
#define VIRGL_SET_ATOMIC_BUFFER_ELEMENT_SIZE 3
#define VIRGL_SET_ATOMIC_BUFFER_SIZE(x) (VIRGL_SET_ATOMIC_BUFFER_ELEMENT_SIZE * (x)) + 1
#define VIRGL_SET_ATOMIC_BUFFER_START_SLOT 1
#define VIRGL_SET_ATOMIC_BUFFER_OFFSET(x) ((x) * VIRGL_SET_ATOMIC_BUFFER_ELEMENT_SIZE + 2)
#define VIRGL_SET_ATOMIC_BUFFER_LENGTH(x) ((x) * VIRGL_SET_ATOMIC_BUFFER_ELEMENT_SIZE + 3)
#define VIRGL_SET_ATOMIC_BUFFER_RES_HANDLE(x) ((x) * VIRGL_SET_ATOMIC_BUFFER_ELEMENT_SIZE + 4)

/* set debug flags */
#define VIRGL_SET_DEBUG_FLAGS_MIN_SIZE 2
#define VIRGL_SET_DEBUG_FLAGSTRING_OFFSET 1

/* query buffer object */
#define VIRGL_QUERY_RESULT_QBO_SIZE 6
#define VIRGL_QUERY_RESULT_QBO_HANDLE 1
#define VIRGL_QUERY_RESULT_QBO_QBO_HANDLE 2
#define VIRGL_QUERY_RESULT_QBO_WAIT 3
#define VIRGL_QUERY_RESULT_QBO_RESULT_TYPE 4
#define VIRGL_QUERY_RESULT_QBO_OFFSET 5
#define VIRGL_QUERY_RESULT_QBO_INDEX 6

#define VIRGL_TRANSFER_TO_HOST   1
#define VIRGL_TRANSFER_FROM_HOST 2

/* Transfer */
#define VIRGL_TRANSFER3D_SIZE 13
/* The first 11 dwords are the same as VIRGL_RESOURCE_IW_*  */
#define VIRGL_TRANSFER3D_DATA_OFFSET 12
#define VIRGL_TRANSFER3D_DIRECTION 13

/* Copy transfer to host and from host*/
#define VIRGL_COPY_TRANSFER3D_SIZE 14
/* The first 11 dwords are the same as VIRGL_RESOURCE_IW_*  */
#define VIRGL_COPY_TRANSFER3D_SRC_RES_HANDLE 12
#define VIRGL_COPY_TRANSFER3D_SRC_RES_OFFSET 13
#define VIRGL_COPY_TRANSFER3D_FLAGS 14
#define VIRGL_COPY_TRANSFER3D_FLAGS_SYNCHRONIZED (1 << 0)
/* 1 << 1 means transfer from host.
   0 << 1 means transfer to host.*/
#define VIRGL_COPY_TRANSFER3D_FLAGS_READ_FROM_HOST (1 << 1)

/* set tweak flags */
#define VIRGL_SET_TWEAKS_SIZE 2
#define VIRGL_SET_TWEAKS_ID 1
#define VIRGL_SET_TWEAKS_VALUE 2

enum vrend_tweak_type {
   virgl_tweak_gles_brga_emulate,
   virgl_tweak_gles_brga_apply_dest_swizzle,
   virgl_tweak_gles_tf3_samples_passes_multiplier,
   virgl_tweak_undefined
};

/* Clear texture */
#define VIRGL_CLEAR_TEXTURE_SIZE 12
#define VIRGL_TEXTURE_HANDLE 1
#define VIRGL_TEXTURE_LEVEL 2
#define VIRGL_TEXTURE_SRC_X 3
#define VIRGL_TEXTURE_SRC_Y 4
#define VIRGL_TEXTURE_SRC_Z 5
#define VIRGL_TEXTURE_SRC_W 6
#define VIRGL_TEXTURE_SRC_H 7
#define VIRGL_TEXTURE_SRC_D 8
#define VIRGL_TEXTURE_ARRAY_A 9
#define VIRGL_TEXTURE_ARRAY_B 10
#define VIRGL_TEXTURE_ARRAY_C 11
#define VIRGL_TEXTURE_ARRAY_D 12

/* virgl create */
#define VIRGL_PIPE_RES_CREATE_SIZE 11
#define VIRGL_PIPE_RES_CREATE_TARGET 1
#define VIRGL_PIPE_RES_CREATE_FORMAT 2
#define VIRGL_PIPE_RES_CREATE_BIND 3
#define VIRGL_PIPE_RES_CREATE_WIDTH 4
#define VIRGL_PIPE_RES_CREATE_HEIGHT 5
#define VIRGL_PIPE_RES_CREATE_DEPTH 6
#define VIRGL_PIPE_RES_CREATE_ARRAY_SIZE 7
#define VIRGL_PIPE_RES_CREATE_LAST_LEVEL 8
#define VIRGL_PIPE_RES_CREATE_NR_SAMPLES 9
#define VIRGL_PIPE_RES_CREATE_FLAGS 10
#define VIRGL_PIPE_RES_CREATE_BLOB_ID 11

/* VIRGL_CCMD_PIPE_RESOURCE_SET_TYPE */
#define VIRGL_PIPE_RES_SET_TYPE_SIZE(nplanes) (8 + (nplanes) * 2)
#define VIRGL_PIPE_RES_SET_TYPE_RES_HANDLE 1
#define VIRGL_PIPE_RES_SET_TYPE_FORMAT 2
#define VIRGL_PIPE_RES_SET_TYPE_BIND 3
#define VIRGL_PIPE_RES_SET_TYPE_WIDTH 4
#define VIRGL_PIPE_RES_SET_TYPE_HEIGHT 5
#define VIRGL_PIPE_RES_SET_TYPE_USAGE 6
#define VIRGL_PIPE_RES_SET_TYPE_MODIFIER_LO 7
#define VIRGL_PIPE_RES_SET_TYPE_MODIFIER_HI 8
#define VIRGL_PIPE_RES_SET_TYPE_PLANE_STRIDE(plane) (9 + (plane) * 2)
#define VIRGL_PIPE_RES_SET_TYPE_PLANE_OFFSET(plane) (10 + (plane) * 2)

/* send string marker */
#define VIRGL_SEND_STRING_MARKER_MIN_SIZE 2
#define VIRGL_SEND_STRING_MARKER_STRING_SIZE 1
#define VIRGL_SEND_STRING_MARKER_OFFSET 2

/* link shader program */
#define VIRGL_LINK_SHADER_SIZE 6
#define VIRGL_LINK_SHADER_VERTEX_HANDLE 1
#define VIRGL_LINK_SHADER_FRAGMENT_HANDLE 2
#define VIRGL_LINK_SHADER_GEOMETRY_HANDLE 3
#define VIRGL_LINK_SHADER_TESS_CTRL_HANDLE 4
#define VIRGL_LINK_SHADER_TESS_EVAL_HANDLE 5
#define VIRGL_LINK_SHADER_COMPUTE_HANDLE 6

/* VIRGL_CCMD_CREATE_VIDEO_CODEC */
#define VIRGL_CREATE_VIDEO_CODEC_MIN_SIZE   7
#define VIRGL_CREATE_VIDEO_CODEC_HANDLE     1
#define VIRGL_CREATE_VIDEO_CODEC_PROFILE    2
#define VIRGL_CREATE_VIDEO_CODEC_ENTRYPOINT 3
#define VIRGL_CREATE_VIDEO_CODEC_CHROMA_FMT 4
#define VIRGL_CREATE_VIDEO_CODEC_LEVEL      5
#define VIRGL_CREATE_VIDEO_CODEC_WIDTH      6
#define VIRGL_CREATE_VIDEO_CODEC_HEIGHT     7
#define VIRGL_CREATE_VIDEO_CODEC_MAX_REF    8

/* VIRGL_CCMD_DESTROY_VIDEO_CODEC */
#define VIRGL_DESTROY_VIDEO_CODEC_MIN_SIZE  1
#define VIRGL_DESTROY_VIDEO_CODEC_HANDLE    1

/* VIRGL_CCMD_CREATE_VIDEO_BUFFER */
#define VIRGL_CREATE_VIDEO_BUFFER_MIN_SIZE  5
#define VIRGL_CREATE_VIDEO_BUFFER_HANDLE    1
#define VIRGL_CREATE_VIDEO_BUFFER_FORMAT    2
#define VIRGL_CREATE_VIDEO_BUFFER_WIDTH     3
#define VIRGL_CREATE_VIDEO_BUFFER_HEIGHT    4
#define VIRGL_CREATE_VIDEO_BUFFER_RES_BASE  5

/* VIRGL_CCMD_DESTROY_VIDEO_BUFFER */
#define VIRGL_DESTROY_VIDEO_BUFFER_MIN_SIZE 1
#define VIRGL_DESTROY_VIDEO_BUFFER_HANDLE   1

/* VIRGL_CCMD_BEGIN_FRAME */
#define VIRGL_BEGIN_FRAME_MIN_SIZE          2
#define VIRGL_BEGIN_FRAME_CDC_HANDLE        1
#define VIRGL_BEGIN_FRAME_TGT_HANDLE        2

/* VIRGL_CCMD_DECODE_MACROBLOCK */

/* VIRGL_CCMD_DECODE_BITSTREAM */
#define VIRGL_DECODE_BS_MIN_SIZE            5
#define VIRGL_DECODE_BS_CDC_HANDLE          1
#define VIRGL_DECODE_BS_TGT_HANDLE          2
#define VIRGL_DECODE_BS_DSC_HANDLE          3
#define VIRGL_DECODE_BS_BUF_HANDLE          4
#define VIRGL_DECODE_BS_BUF_SIZE            5

/* VIRGL_CCMD_ENCODE_BITSTREAM */
#define VIRGL_ENCODE_BS_MIN_SIZE            5
#define VIRGL_ENCODE_BS_CDC_HANDLE          1
#define VIRGL_ENCODE_BS_SRC_HANDLE          2
#define VIRGL_ENCODE_BS_DEST_HANDLE         3
#define VIRGL_ENCODE_BS_DESC_HANDLE         4
#define VIRGL_ENCODE_BS_FEED_HANDLE         5

/* VIRGL_CCMD_END_FRAME */
#define VIRGL_END_FRAME_MIN_SIZE            2
#define VIRGL_END_FRAME_CDC_HANDLE          1
#define VIRGL_END_FRAME_TGT_HANDLE          2

/* VIRGL_CCMD_CLEAR_SURFACE */
#define VIRGL_CLEAR_SURFACE_SIZE                   10
#define VIRGL_CLEAR_SURFACE_S0                     1
#define VIRGL_CLEAR_SURFACE_S0_RENDER_CONDITION(x) (((x)&0x1) << 0)
#define VIRGL_CLEAR_SURFACE_S0_BUFFERS(x)          (((x)&0x7) << 1)
#define VIRGL_CLEAR_SURFACE_HANDLE                 2
#define VIRGL_CLEAR_SURFACE_COLOR_0                3 /* color is 4 * u32/f32/i32 or (depth/f64+stencil/u32) */
#define VIRGL_CLEAR_SURFACE_COLOR_1                4
#define VIRGL_CLEAR_SURFACE_COLOR_2                5
#define VIRGL_CLEAR_SURFACE_COLOR_3                6
#define VIRGL_CLEAR_SURFACE_DST_X                  7
#define VIRGL_CLEAR_SURFACE_DST_Y                  8
#define VIRGL_CLEAR_SURFACE_WIDTH                  9
#define VIRGL_CLEAR_SURFACE_HEIGHT                 10

/* VIRGL_CCMD_GET_PIPE_RESOURCE_LAYOUT */
#define VIRGL_RESOURCE_LAYOUT_SIZE           2
#define VIRGL_RESOURCE_LAYOUT_HANDLE_OUT     1
#define VIRGL_RESOURCE_LAYOUT_HANDLE_TARGET  2

/* VIRGL_CCMD_QUERY_GBM_FORMAT_MODIFIER */
#define VIRGL_QUERY_FORMAT_MODIFIER_SIZE     1
#define VIRGL_QUERY_FORMAT_MODIFIER_HANDLE   1

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   source/v64/third_party/virtio/virtio_gpu.h                                                          0000644 0000000 0000000 00000027157 00000000000 016105  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /*
 * Virtio GPU Device
 *
 * Copyright Red Hat, Inc. 2013-2014
 *
 * Authors:
 *     Dave Airlie <airlied@redhat.com>
 *     Gerd Hoffmann <kraxel@redhat.com>
 *
 * This header is BSD licensed so anyone can use the definitions
 * to implement compatible drivers/servers:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of IBM nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL IBM OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#ifndef VIRTIO_GPU_HW_H
#define VIRTIO_GPU_HW_H

#include <linux/types.h>

/*
 * VIRTIO_GPU_CMD_CTX_*
 * VIRTIO_GPU_CMD_*_3D
 */
#define VIRTIO_GPU_F_VIRGL               0

/*
 * VIRTIO_GPU_CMD_GET_EDID
 */
#define VIRTIO_GPU_F_EDID                1
/*
 * VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID
 */
#define VIRTIO_GPU_F_RESOURCE_UUID       2

/*
 * VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB
 */
#define VIRTIO_GPU_F_RESOURCE_BLOB       3
/*
 * VIRTIO_GPU_CMD_CREATE_CONTEXT with
 * context_init and multiple timelines
 */
#define VIRTIO_GPU_F_CONTEXT_INIT        4
/*
 * The device provides a valid blob_alignment
 * field in its configuration and both
 * VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB and
 * VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB requests
 * must be aligned to that value.
 */
#define VIRTIO_GPU_F_BLOB_ALIGNMENT      5

enum virtio_gpu_ctrl_type {
	VIRTIO_GPU_UNDEFINED = 0,

	/* 2d commands */
	VIRTIO_GPU_CMD_GET_DISPLAY_INFO = 0x0100,
	VIRTIO_GPU_CMD_RESOURCE_CREATE_2D,
	VIRTIO_GPU_CMD_RESOURCE_UNREF,
	VIRTIO_GPU_CMD_SET_SCANOUT,
	VIRTIO_GPU_CMD_RESOURCE_FLUSH,
	VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D,
	VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING,
	VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING,
	VIRTIO_GPU_CMD_GET_CAPSET_INFO,
	VIRTIO_GPU_CMD_GET_CAPSET,
	VIRTIO_GPU_CMD_GET_EDID,
	VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID,
	VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB,
	VIRTIO_GPU_CMD_SET_SCANOUT_BLOB,

	/* 3d commands */
	VIRTIO_GPU_CMD_CTX_CREATE = 0x0200,
	VIRTIO_GPU_CMD_CTX_DESTROY,
	VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE,
	VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE,
	VIRTIO_GPU_CMD_RESOURCE_CREATE_3D,
	VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D,
	VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D,
	VIRTIO_GPU_CMD_SUBMIT_3D,
	VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB,
	VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB,

	/* cursor commands */
	VIRTIO_GPU_CMD_UPDATE_CURSOR = 0x0300,
	VIRTIO_GPU_CMD_MOVE_CURSOR,

	/* success responses */
	VIRTIO_GPU_RESP_OK_NODATA = 0x1100,
	VIRTIO_GPU_RESP_OK_DISPLAY_INFO,
	VIRTIO_GPU_RESP_OK_CAPSET_INFO,
	VIRTIO_GPU_RESP_OK_CAPSET,
	VIRTIO_GPU_RESP_OK_EDID,
	VIRTIO_GPU_RESP_OK_RESOURCE_UUID,
	VIRTIO_GPU_RESP_OK_MAP_INFO,

	/* error responses */
	VIRTIO_GPU_RESP_ERR_UNSPEC = 0x1200,
	VIRTIO_GPU_RESP_ERR_OUT_OF_MEMORY,
	VIRTIO_GPU_RESP_ERR_INVALID_SCANOUT_ID,
	VIRTIO_GPU_RESP_ERR_INVALID_RESOURCE_ID,
	VIRTIO_GPU_RESP_ERR_INVALID_CONTEXT_ID,
	VIRTIO_GPU_RESP_ERR_INVALID_PARAMETER,
};

enum virtio_gpu_shm_id {
	VIRTIO_GPU_SHM_ID_UNDEFINED = 0,
	/*
	 * VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB
	 * VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB
	 */
	VIRTIO_GPU_SHM_ID_HOST_VISIBLE = 1
};

#define VIRTIO_GPU_FLAG_FENCE         (1 << 0)
/*
 * If the following flag is set, then ring_idx contains the index
 * of the command ring that needs to used when creating the fence
 */
#define VIRTIO_GPU_FLAG_INFO_RING_IDX (1 << 1)

struct virtio_gpu_ctrl_hdr {
	__le32 type;
	__le32 flags;
	__le64 fence_id;
	__le32 ctx_id;
	__u8 ring_idx;
	__u8 padding[3];
};

/* data passed in the cursor vq */

struct virtio_gpu_cursor_pos {
	__le32 scanout_id;
	__le32 x;
	__le32 y;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_UPDATE_CURSOR, VIRTIO_GPU_CMD_MOVE_CURSOR */
struct virtio_gpu_update_cursor {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_cursor_pos pos;  /* update & move */
	__le32 resource_id;           /* update only */
	__le32 hot_x;                 /* update only */
	__le32 hot_y;                 /* update only */
	__le32 padding;
};

/* data passed in the control vq, 2d related */

struct virtio_gpu_rect {
	__le32 x;
	__le32 y;
	__le32 width;
	__le32 height;
};

/* VIRTIO_GPU_CMD_RESOURCE_UNREF */
struct virtio_gpu_resource_unref {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_RESOURCE_CREATE_2D: create a 2d resource with a format */
struct virtio_gpu_resource_create_2d {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 format;
	__le32 width;
	__le32 height;
};

/* VIRTIO_GPU_CMD_SET_SCANOUT */
struct virtio_gpu_set_scanout {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_rect r;
	__le32 scanout_id;
	__le32 resource_id;
};

/* VIRTIO_GPU_CMD_RESOURCE_FLUSH */
struct virtio_gpu_resource_flush {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_rect r;
	__le32 resource_id;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D: simple transfer to_host */
struct virtio_gpu_transfer_to_host_2d {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_rect r;
	__le64 offset;
	__le32 resource_id;
	__le32 padding;
};

struct virtio_gpu_mem_entry {
	__le64 addr;
	__le32 length;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING */
struct virtio_gpu_resource_attach_backing {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 nr_entries;
};

/* VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING */
struct virtio_gpu_resource_detach_backing {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
};

/* VIRTIO_GPU_RESP_OK_DISPLAY_INFO */
#define VIRTIO_GPU_MAX_SCANOUTS 16
struct virtio_gpu_resp_display_info {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_display_one {
		struct virtio_gpu_rect r;
		__le32 enabled;
		__le32 flags;
	} pmodes[VIRTIO_GPU_MAX_SCANOUTS];
};

/* data passed in the control vq, 3d related */

struct virtio_gpu_box {
	__le32 x, y, z;
	__le32 w, h, d;
};

/* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D, VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D */
struct virtio_gpu_transfer_host_3d {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_box box;
	__le64 offset;
	__le32 resource_id;
	__le32 level;
	__le32 stride;
	__le32 layer_stride;
};

/* VIRTIO_GPU_CMD_RESOURCE_CREATE_3D */
#define VIRTIO_GPU_RESOURCE_FLAG_Y_0_TOP (1 << 0)
struct virtio_gpu_resource_create_3d {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 target;
	__le32 format;
	__le32 bind;
	__le32 width;
	__le32 height;
	__le32 depth;
	__le32 array_size;
	__le32 last_level;
	__le32 nr_samples;
	__le32 flags;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_CTX_CREATE */
#define VIRTIO_GPU_CONTEXT_INIT_CAPSET_ID_MASK 0x000000ff
struct virtio_gpu_ctx_create {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 nlen;
	__le32 context_init;
	char debug_name[64];
};

/* VIRTIO_GPU_CMD_CTX_DESTROY */
struct virtio_gpu_ctx_destroy {
	struct virtio_gpu_ctrl_hdr hdr;
};

/* VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE, VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE */
struct virtio_gpu_ctx_resource {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_SUBMIT_3D */
struct virtio_gpu_cmd_submit {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 size;
	__le32 padding;
};

#define VIRTIO_GPU_CAPSET_VIRGL 1
#define VIRTIO_GPU_CAPSET_VIRGL2 2
#define VIRTIO_GPU_CAPSET_GFXSTREAM_VULKAN 3
#define VIRTIO_GPU_CAPSET_VENUS 4
#define VIRTIO_GPU_CAPSET_CROSS_DOMAIN 5
#define VIRTIO_GPU_CAPSET_DRM 6

/* VIRTIO_GPU_CMD_GET_CAPSET_INFO */
struct virtio_gpu_get_capset_info {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 capset_index;
	__le32 padding;
};

/* VIRTIO_GPU_RESP_OK_CAPSET_INFO */
struct virtio_gpu_resp_capset_info {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 capset_id;
	__le32 capset_max_version;
	__le32 capset_max_size;
	__le32 padding;
};

/* VIRTIO_GPU_CMD_GET_CAPSET */
struct virtio_gpu_get_capset {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 capset_id;
	__le32 capset_version;
};

/* VIRTIO_GPU_RESP_OK_CAPSET */
struct virtio_gpu_resp_capset {
	struct virtio_gpu_ctrl_hdr hdr;
	__u8 capset_data[];
};

/* VIRTIO_GPU_CMD_GET_EDID */
struct virtio_gpu_cmd_get_edid {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 scanout;
	__le32 padding;
};

/* VIRTIO_GPU_RESP_OK_EDID */
struct virtio_gpu_resp_edid {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 size;
	__le32 padding;
	__u8 edid[1024];
};

#define VIRTIO_GPU_EVENT_DISPLAY (1 << 0)

struct virtio_gpu_config {
	__le32 events_read;
	__le32 events_clear;
	__le32 num_scanouts;
	__le32 num_capsets;
	__le32 blob_alignment;
};

/* simple formats for fbcon/X use */
enum virtio_gpu_formats {
	VIRTIO_GPU_FORMAT_B8G8R8A8_UNORM  = 1,
	VIRTIO_GPU_FORMAT_B8G8R8X8_UNORM  = 2,
	VIRTIO_GPU_FORMAT_A8R8G8B8_UNORM  = 3,
	VIRTIO_GPU_FORMAT_X8R8G8B8_UNORM  = 4,

	VIRTIO_GPU_FORMAT_R8G8B8A8_UNORM  = 67,
	VIRTIO_GPU_FORMAT_X8B8G8R8_UNORM  = 68,

	VIRTIO_GPU_FORMAT_A8B8G8R8_UNORM  = 121,
	VIRTIO_GPU_FORMAT_R8G8B8X8_UNORM  = 134,
};

/* VIRTIO_GPU_CMD_RESOURCE_ASSIGN_UUID */
struct virtio_gpu_resource_assign_uuid {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
};

/* VIRTIO_GPU_RESP_OK_RESOURCE_UUID */
struct virtio_gpu_resp_resource_uuid {
	struct virtio_gpu_ctrl_hdr hdr;
	__u8 uuid[16];
};

/* VIRTIO_GPU_CMD_RESOURCE_CREATE_BLOB */
struct virtio_gpu_resource_create_blob {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
#define VIRTIO_GPU_BLOB_MEM_GUEST             0x0001
#define VIRTIO_GPU_BLOB_MEM_HOST3D            0x0002
#define VIRTIO_GPU_BLOB_MEM_HOST3D_GUEST      0x0003

#define VIRTIO_GPU_BLOB_FLAG_USE_MAPPABLE     0x0001
#define VIRTIO_GPU_BLOB_FLAG_USE_SHAREABLE    0x0002
#define VIRTIO_GPU_BLOB_FLAG_USE_CROSS_DEVICE 0x0004
	/* zero is invalid blob mem */
	__le32 blob_mem;
	__le32 blob_flags;
	__le32 nr_entries;
	__le64 blob_id;
	__le64 size;
	/*
	 * sizeof(nr_entries * virtio_gpu_mem_entry) bytes follow
	 */
};

/* VIRTIO_GPU_CMD_SET_SCANOUT_BLOB */
struct virtio_gpu_set_scanout_blob {
	struct virtio_gpu_ctrl_hdr hdr;
	struct virtio_gpu_rect r;
	__le32 scanout_id;
	__le32 resource_id;
	__le32 width;
	__le32 height;
	__le32 format;
	__le32 padding;
	__le32 strides[4];
	__le32 offsets[4];
};

/* VIRTIO_GPU_CMD_RESOURCE_MAP_BLOB */
struct virtio_gpu_resource_map_blob {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
	__le64 offset;
};

/* VIRTIO_GPU_RESP_OK_MAP_INFO */
#define VIRTIO_GPU_MAP_CACHE_MASK     0x0f
#define VIRTIO_GPU_MAP_CACHE_NONE     0x00
#define VIRTIO_GPU_MAP_CACHE_CACHED   0x01
#define VIRTIO_GPU_MAP_CACHE_UNCACHED 0x02
#define VIRTIO_GPU_MAP_CACHE_WC       0x03
struct virtio_gpu_resp_map_info {
	struct virtio_gpu_ctrl_hdr hdr;
	__u32 map_info;
	__u32 padding;
};

/* VIRTIO_GPU_CMD_RESOURCE_UNMAP_BLOB */
struct virtio_gpu_resource_unmap_blob {
	struct virtio_gpu_ctrl_hdr hdr;
	__le32 resource_id;
	__le32 padding;
};

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                 source/v64/third_party/vmware-svga/README                                                           0000644 0000000 0000000 00000000431 00000000000 015332  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       Files in this directory are auto-generated from description files and any changes made to them will be discarded on the next update.

Only vmw_surf_defs.h and vm_basic_types.h are written from scratch and provide the glue necessary for the auto-generated files (the rest of them).
                                                                                                                                                                                                                                       source/v64/third_party/vmware-svga/VGPU10ShaderTokens.h                                             0000644 0000000 0000000 00000067302 00000000000 020072  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 2012-2023 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * VGPU10ShaderTokens.h --
 *
 *    VGPU10 shader token definitions.
 */

#ifndef VGPU10SHADERTOKENS_H
#define VGPU10SHADERTOKENS_H

#ifdef __cplusplus
extern "C" {
#endif

#include "vm_basic_types.h"

#define VGPU10_MAX_VS_INPUTS                               16
#define VGPU10_MAX_VS_OUTPUTS                              16
#define VGPU10_MAX_GS_INPUTS                               16
#define VGPU10_MAX_GS_OUTPUTS                              32
#define VGPU10_MAX_PS_INPUTS                               32
#define VGPU10_MAX_PS_OUTPUTS                              8
#define VGPU10_MAX_TEMPS                                   4096
#define VGPU10_MAX_CONSTANT_BUFFERS                        (14 + 1)
#define VGPU10_MAX_CONSTANT_BUFFER_ELEMENT_COUNT           4096
#define VGPU10_MAX_IMMEDIATE_CONSTANT_BUFFER_ELEMENT_COUNT 4096
#define VGPU10_MAX_SAMPLERS                                16
#define VGPU10_MAX_RESOURCES                               128
#define VGPU10_MIN_TEXEL_FETCH_OFFSET                      -8
#define VGPU10_MAX_TEXEL_FETCH_OFFSET                      7

#define VGPU10_1_MAX_VS_INPUTS  32
#define VGPU10_1_MAX_VS_OUTPUTS 32
#define VGPU10_1_MAX_GS_INPUTS  32

#define VGPU11_MAX_HS_INPUT_CONTROL_POINTS     32
#define VGPU11_MAX_HS_INPUT_PATCH_CONSTANTS    32
#define VGPU11_MAX_HS_OUTPUT_CP_PHASE_ELEMENTS 32
#define VGPU11_MAX_HS_OUTPUT_CONTROL_POINTS    32
#define VGPU11_MAX_HS_OUTPUTS                  32
#define VGPU11_MAX_DS_INPUT_CONTROL_POINTS     32
#define VGPU11_MAX_DS_INPUT_PATCH_CONSTANTS    32
#define VGPU11_MAX_DS_OUTPUTS                  32
#define VGPU11_MAX_GS_STREAMS                  4
#define VGPU11_MAX_FUNCTION_BODIES             256
#define VGPU11_MAX_FUNCTION_TABLES             256
#define VGPU11_MAX_INTERFACES                  253

#define VGPU10_MAX_INPUTS                32
#define VGPU10_MAX_OUTPUTS               32
#define VGPU10_MAX_INPUT_PATCH_CONSTANTS 32

typedef enum {
   VGPU10_PIXEL_SHADER = 0,
   VGPU10_VERTEX_SHADER = 1,
   VGPU10_GEOMETRY_SHADER = 2,

   VGPU10_HULL_SHADER = 3,
   VGPU10_DOMAIN_SHADER = 4,
   VGPU10_COMPUTE_SHADER = 5
} VGPU10_PROGRAM_TYPE;

typedef union {
   struct {
      unsigned int minorVersion : 4;
      unsigned int majorVersion : 4;
      unsigned int              : 8;
      unsigned int programType  : 16;
   };
   uint32 value;
} VGPU10ProgramToken;

typedef enum {
   VGPU10_OPCODE_ADD = 0,
   VGPU10_OPCODE_AND = 1,
   VGPU10_OPCODE_BREAK = 2,
   VGPU10_OPCODE_BREAKC = 3,
   VGPU10_OPCODE_CALL = 4,
   VGPU10_OPCODE_CALLC = 5,
   VGPU10_OPCODE_CASE = 6,
   VGPU10_OPCODE_CONTINUE = 7,
   VGPU10_OPCODE_CONTINUEC = 8,
   VGPU10_OPCODE_CUT = 9,
   VGPU10_OPCODE_DEFAULT = 10,
   VGPU10_OPCODE_DERIV_RTX = 11,
   VGPU10_OPCODE_DERIV_RTY = 12,
   VGPU10_OPCODE_DISCARD = 13,
   VGPU10_OPCODE_DIV = 14,
   VGPU10_OPCODE_DP2 = 15,
   VGPU10_OPCODE_DP3 = 16,
   VGPU10_OPCODE_DP4 = 17,
   VGPU10_OPCODE_ELSE = 18,
   VGPU10_OPCODE_EMIT = 19,
   VGPU10_OPCODE_EMITTHENCUT = 20,
   VGPU10_OPCODE_ENDIF = 21,
   VGPU10_OPCODE_ENDLOOP = 22,
   VGPU10_OPCODE_ENDSWITCH = 23,
   VGPU10_OPCODE_EQ = 24,
   VGPU10_OPCODE_EXP = 25,
   VGPU10_OPCODE_FRC = 26,
   VGPU10_OPCODE_FTOI = 27,
   VGPU10_OPCODE_FTOU = 28,
   VGPU10_OPCODE_GE = 29,
   VGPU10_OPCODE_IADD = 30,
   VGPU10_OPCODE_IF = 31,
   VGPU10_OPCODE_IEQ = 32,
   VGPU10_OPCODE_IGE = 33,
   VGPU10_OPCODE_ILT = 34,
   VGPU10_OPCODE_IMAD = 35,
   VGPU10_OPCODE_IMAX = 36,
   VGPU10_OPCODE_IMIN = 37,
   VGPU10_OPCODE_IMUL = 38,
   VGPU10_OPCODE_INE = 39,
   VGPU10_OPCODE_INEG = 40,
   VGPU10_OPCODE_ISHL = 41,
   VGPU10_OPCODE_ISHR = 42,
   VGPU10_OPCODE_ITOF = 43,
   VGPU10_OPCODE_LABEL = 44,
   VGPU10_OPCODE_LD = 45,
   VGPU10_OPCODE_LD_MS = 46,
   VGPU10_OPCODE_LOG = 47,
   VGPU10_OPCODE_LOOP = 48,
   VGPU10_OPCODE_LT = 49,
   VGPU10_OPCODE_MAD = 50,
   VGPU10_OPCODE_MIN = 51,
   VGPU10_OPCODE_MAX = 52,
   VGPU10_OPCODE_CUSTOMDATA = 53,
   VGPU10_OPCODE_MOV = 54,
   VGPU10_OPCODE_MOVC = 55,
   VGPU10_OPCODE_MUL = 56,
   VGPU10_OPCODE_NE = 57,
   VGPU10_OPCODE_NOP = 58,
   VGPU10_OPCODE_NOT = 59,
   VGPU10_OPCODE_OR = 60,
   VGPU10_OPCODE_RESINFO = 61,
   VGPU10_OPCODE_RET = 62,
   VGPU10_OPCODE_RETC = 63,
   VGPU10_OPCODE_ROUND_NE = 64,
   VGPU10_OPCODE_ROUND_NI = 65,
   VGPU10_OPCODE_ROUND_PI = 66,
   VGPU10_OPCODE_ROUND_Z = 67,
   VGPU10_OPCODE_RSQ = 68,
   VGPU10_OPCODE_SAMPLE = 69,
   VGPU10_OPCODE_SAMPLE_C = 70,
   VGPU10_OPCODE_SAMPLE_C_LZ = 71,
   VGPU10_OPCODE_SAMPLE_L = 72,
   VGPU10_OPCODE_SAMPLE_D = 73,
   VGPU10_OPCODE_SAMPLE_B = 74,
   VGPU10_OPCODE_SQRT = 75,
   VGPU10_OPCODE_SWITCH = 76,
   VGPU10_OPCODE_SINCOS = 77,
   VGPU10_OPCODE_UDIV = 78,
   VGPU10_OPCODE_ULT = 79,
   VGPU10_OPCODE_UGE = 80,
   VGPU10_OPCODE_UMUL = 81,
   VGPU10_OPCODE_UMAD = 82,
   VGPU10_OPCODE_UMAX = 83,
   VGPU10_OPCODE_UMIN = 84,
   VGPU10_OPCODE_USHR = 85,
   VGPU10_OPCODE_UTOF = 86,
   VGPU10_OPCODE_XOR = 87,
   VGPU10_OPCODE_DCL_RESOURCE = 88,
   VGPU10_OPCODE_DCL_CONSTANT_BUFFER = 89,
   VGPU10_OPCODE_DCL_SAMPLER = 90,
   VGPU10_OPCODE_DCL_INDEX_RANGE = 91,
   VGPU10_OPCODE_DCL_GS_OUTPUT_PRIMITIVE_TOPOLOGY = 92,
   VGPU10_OPCODE_DCL_GS_INPUT_PRIMITIVE = 93,
   VGPU10_OPCODE_DCL_MAX_OUTPUT_VERTEX_COUNT = 94,
   VGPU10_OPCODE_DCL_INPUT = 95,
   VGPU10_OPCODE_DCL_INPUT_SGV = 96,
   VGPU10_OPCODE_DCL_INPUT_SIV = 97,
   VGPU10_OPCODE_DCL_INPUT_PS = 98,
   VGPU10_OPCODE_DCL_INPUT_PS_SGV = 99,
   VGPU10_OPCODE_DCL_INPUT_PS_SIV = 100,
   VGPU10_OPCODE_DCL_OUTPUT = 101,
   VGPU10_OPCODE_DCL_OUTPUT_SGV = 102,
   VGPU10_OPCODE_DCL_OUTPUT_SIV = 103,
   VGPU10_OPCODE_DCL_TEMPS = 104,
   VGPU10_OPCODE_DCL_INDEXABLE_TEMP = 105,
   VGPU10_OPCODE_DCL_GLOBAL_FLAGS = 106,

   VGPU10_OPCODE_VMWARE = 107,

   VGPU10_OPCODE_LOD = 108,
   VGPU10_OPCODE_GATHER4 = 109,
   VGPU10_OPCODE_SAMPLE_POS = 110,
   VGPU10_OPCODE_SAMPLE_INFO = 111,

   VGPU10_OPCODE_RESERVED1 = 112,
   VGPU10_OPCODE_HS_DECLS = 113,
   VGPU10_OPCODE_HS_CONTROL_POINT_PHASE = 114,
   VGPU10_OPCODE_HS_FORK_PHASE = 115,
   VGPU10_OPCODE_HS_JOIN_PHASE = 116,
   VGPU10_OPCODE_EMIT_STREAM = 117,
   VGPU10_OPCODE_CUT_STREAM = 118,
   VGPU10_OPCODE_EMITTHENCUT_STREAM = 119,
   VGPU10_OPCODE_INTERFACE_CALL = 120,
   VGPU10_OPCODE_BUFINFO = 121,
   VGPU10_OPCODE_DERIV_RTX_COARSE = 122,
   VGPU10_OPCODE_DERIV_RTX_FINE = 123,
   VGPU10_OPCODE_DERIV_RTY_COARSE = 124,
   VGPU10_OPCODE_DERIV_RTY_FINE = 125,
   VGPU10_OPCODE_GATHER4_C = 126,
   VGPU10_OPCODE_GATHER4_PO = 127,
   VGPU10_OPCODE_GATHER4_PO_C = 128,
   VGPU10_OPCODE_RCP = 129,
   VGPU10_OPCODE_F32TOF16 = 130,
   VGPU10_OPCODE_F16TOF32 = 131,
   VGPU10_OPCODE_UADDC = 132,
   VGPU10_OPCODE_USUBB = 133,
   VGPU10_OPCODE_COUNTBITS = 134,
   VGPU10_OPCODE_FIRSTBIT_HI = 135,
   VGPU10_OPCODE_FIRSTBIT_LO = 136,
   VGPU10_OPCODE_FIRSTBIT_SHI = 137,
   VGPU10_OPCODE_UBFE = 138,
   VGPU10_OPCODE_IBFE = 139,
   VGPU10_OPCODE_BFI = 140,
   VGPU10_OPCODE_BFREV = 141,
   VGPU10_OPCODE_SWAPC = 142,
   VGPU10_OPCODE_DCL_STREAM = 143,
   VGPU10_OPCODE_DCL_FUNCTION_BODY = 144,
   VGPU10_OPCODE_DCL_FUNCTION_TABLE = 145,
   VGPU10_OPCODE_DCL_INTERFACE = 146,
   VGPU10_OPCODE_DCL_INPUT_CONTROL_POINT_COUNT = 147,
   VGPU10_OPCODE_DCL_OUTPUT_CONTROL_POINT_COUNT = 148,
   VGPU10_OPCODE_DCL_TESS_DOMAIN = 149,
   VGPU10_OPCODE_DCL_TESS_PARTITIONING = 150,
   VGPU10_OPCODE_DCL_TESS_OUTPUT_PRIMITIVE = 151,
   VGPU10_OPCODE_DCL_HS_MAX_TESSFACTOR = 152,
   VGPU10_OPCODE_DCL_HS_FORK_PHASE_INSTANCE_COUNT = 153,
   VGPU10_OPCODE_DCL_HS_JOIN_PHASE_INSTANCE_COUNT = 154,
   VGPU10_OPCODE_DCL_THREAD_GROUP = 155,
   VGPU10_OPCODE_DCL_UAV_TYPED = 156,
   VGPU10_OPCODE_DCL_UAV_RAW = 157,
   VGPU10_OPCODE_DCL_UAV_STRUCTURED = 158,
   VGPU10_OPCODE_DCL_TGSM_RAW = 159,
   VGPU10_OPCODE_DCL_TGSM_STRUCTURED = 160,
   VGPU10_OPCODE_DCL_RESOURCE_RAW = 161,
   VGPU10_OPCODE_DCL_RESOURCE_STRUCTURED = 162,
   VGPU10_OPCODE_LD_UAV_TYPED = 163,
   VGPU10_OPCODE_STORE_UAV_TYPED = 164,
   VGPU10_OPCODE_LD_RAW = 165,
   VGPU10_OPCODE_STORE_RAW = 166,
   VGPU10_OPCODE_LD_STRUCTURED = 167,
   VGPU10_OPCODE_STORE_STRUCTURED = 168,
   VGPU10_OPCODE_ATOMIC_AND = 169,
   VGPU10_OPCODE_ATOMIC_OR = 170,
   VGPU10_OPCODE_ATOMIC_XOR = 171,
   VGPU10_OPCODE_ATOMIC_CMP_STORE = 172,
   VGPU10_OPCODE_ATOMIC_IADD = 173,
   VGPU10_OPCODE_ATOMIC_IMAX = 174,
   VGPU10_OPCODE_ATOMIC_IMIN = 175,
   VGPU10_OPCODE_ATOMIC_UMAX = 176,
   VGPU10_OPCODE_ATOMIC_UMIN = 177,
   VGPU10_OPCODE_IMM_ATOMIC_ALLOC = 178,
   VGPU10_OPCODE_IMM_ATOMIC_CONSUME = 179,
   VGPU10_OPCODE_IMM_ATOMIC_IADD = 180,
   VGPU10_OPCODE_IMM_ATOMIC_AND = 181,
   VGPU10_OPCODE_IMM_ATOMIC_OR = 182,
   VGPU10_OPCODE_IMM_ATOMIC_XOR = 183,
   VGPU10_OPCODE_IMM_ATOMIC_EXCH = 184,
   VGPU10_OPCODE_IMM_ATOMIC_CMP_EXCH = 185,
   VGPU10_OPCODE_IMM_ATOMIC_IMAX = 186,
   VGPU10_OPCODE_IMM_ATOMIC_IMIN = 187,
   VGPU10_OPCODE_IMM_ATOMIC_UMAX = 188,
   VGPU10_OPCODE_IMM_ATOMIC_UMIN = 189,
   VGPU10_OPCODE_SYNC = 190,
   VGPU10_OPCODE_DADD = 191,
   VGPU10_OPCODE_DMAX = 192,
   VGPU10_OPCODE_DMIN = 193,
   VGPU10_OPCODE_DMUL = 194,
   VGPU10_OPCODE_DEQ = 195,
   VGPU10_OPCODE_DGE = 196,
   VGPU10_OPCODE_DLT = 197,
   VGPU10_OPCODE_DNE = 198,
   VGPU10_OPCODE_DMOV = 199,
   VGPU10_OPCODE_DMOVC = 200,
   VGPU10_OPCODE_DTOF = 201,
   VGPU10_OPCODE_FTOD = 202,
   VGPU10_OPCODE_EVAL_SNAPPED = 203,
   VGPU10_OPCODE_EVAL_SAMPLE_INDEX = 204,
   VGPU10_OPCODE_EVAL_CENTROID = 205,
   VGPU10_OPCODE_DCL_GS_INSTANCE_COUNT = 206,
   VGPU10_OPCODE_ABORT = 207,
   VGPU10_OPCODE_DEBUG_BREAK = 208,

   VGPU10_OPCODE_RESERVED0 = 209,
   VGPU10_OPCODE_DDIV = 210,
   VGPU10_OPCODE_DFMA = 211,
   VGPU10_OPCODE_DRCP = 212,
   VGPU10_OPCODE_MSAD = 213,
   VGPU10_OPCODE_DTOI = 214,
   VGPU10_OPCODE_DTOU = 215,
   VGPU10_OPCODE_ITOD = 216,
   VGPU10_OPCODE_UTOD = 217,

   VGPU10_NUM_OPCODES
} VGPU10_OPCODE_TYPE;

typedef enum {
   VGPU10_VMWARE_OPCODE_IDIV = 0,
   VGPU10_VMWARE_OPCODE_DFRC = 1,
   VGPU10_VMWARE_OPCODE_DRSQ = 2,
   VGPU10_VMWARE_NUM_OPCODES
} VGPU10_VMWARE_OPCODE_TYPE;

typedef enum {
   VGPU10_INTERPOLATION_UNDEFINED = 0,
   VGPU10_INTERPOLATION_CONSTANT = 1,
   VGPU10_INTERPOLATION_LINEAR = 2,
   VGPU10_INTERPOLATION_LINEAR_CENTROID = 3,
   VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE = 4,
   VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE_CENTROID = 5,
   VGPU10_INTERPOLATION_LINEAR_SAMPLE = 6,
   VGPU10_INTERPOLATION_LINEAR_NOPERSPECTIVE_SAMPLE = 7
} VGPU10_INTERPOLATION_MODE;

typedef enum {
   VGPU10_RESOURCE_DIMENSION_UNKNOWN = 0,
   VGPU10_RESOURCE_DIMENSION_BUFFER = 1,
   VGPU10_RESOURCE_DIMENSION_TEXTURE1D = 2,
   VGPU10_RESOURCE_DIMENSION_TEXTURE2D = 3,
   VGPU10_RESOURCE_DIMENSION_TEXTURE2DMS = 4,
   VGPU10_RESOURCE_DIMENSION_TEXTURE3D = 5,
   VGPU10_RESOURCE_DIMENSION_TEXTURECUBE = 6,
   VGPU10_RESOURCE_DIMENSION_TEXTURE1DARRAY = 7,
   VGPU10_RESOURCE_DIMENSION_TEXTURE2DARRAY = 8,
   VGPU10_RESOURCE_DIMENSION_TEXTURE2DMSARRAY = 9,
   VGPU10_RESOURCE_DIMENSION_TEXTURECUBEARRAY = 10,

   VGPU10_RESOURCE_DIMENSION_RAW_BUFFER = 11,
   VGPU10_RESOURCE_DIMENSION_STRUCTURED_BUFFER = 12,
   VGPU10_RESOURCE_DIMENSION_MAX = 12
} VGPU10_RESOURCE_DIMENSION;

typedef enum {
   VGPU10_SAMPLER_MODE_DEFAULT = 0,
   VGPU10_SAMPLER_MODE_COMPARISON = 1,
   VGPU10_SAMPLER_MODE_MONO = 2
} VGPU10_SAMPLER_MODE;

typedef enum {
   VGPU10_INSTRUCTION_TEST_ZERO = 0,
   VGPU10_INSTRUCTION_TEST_NONZERO = 1
} VGPU10_INSTRUCTION_TEST_BOOLEAN;

typedef enum {
   VGPU10_CB_IMMEDIATE_INDEXED = 0,
   VGPU10_CB_DYNAMIC_INDEXED = 1
} VGPU10_CB_ACCESS_PATTERN;

typedef enum {
   VGPU10_PRIMITIVE_UNDEFINED = 0,
   VGPU10_PRIMITIVE_POINT = 1,
   VGPU10_PRIMITIVE_LINE = 2,
   VGPU10_PRIMITIVE_TRIANGLE = 3,
   VGPU10_PRIMITIVE_LINE_ADJ = 6,
   VGPU10_PRIMITIVE_TRIANGLE_ADJ = 7,
   VGPU10_PRIMITIVE_SM40_MAX = 7,

   VGPU10_PRIMITIVE_1_CONTROL_POINT_PATCH = 8,
   VGPU10_PRIMITIVE_2_CONTROL_POINT_PATCH = 9,
   VGPU10_PRIMITIVE_3_CONTROL_POINT_PATCH = 10,
   VGPU10_PRIMITIVE_4_CONTROL_POINT_PATCH = 11,
   VGPU10_PRIMITIVE_5_CONTROL_POINT_PATCH = 12,
   VGPU10_PRIMITIVE_6_CONTROL_POINT_PATCH = 13,
   VGPU10_PRIMITIVE_7_CONTROL_POINT_PATCH = 14,
   VGPU10_PRIMITIVE_8_CONTROL_POINT_PATCH = 15,
   VGPU10_PRIMITIVE_9_CONTROL_POINT_PATCH = 16,
   VGPU10_PRIMITIVE_10_CONTROL_POINT_PATCH = 17,
   VGPU10_PRIMITIVE_11_CONTROL_POINT_PATCH = 18,
   VGPU10_PRIMITIVE_12_CONTROL_POINT_PATCH = 19,
   VGPU10_PRIMITIVE_13_CONTROL_POINT_PATCH = 20,
   VGPU10_PRIMITIVE_14_CONTROL_POINT_PATCH = 21,
   VGPU10_PRIMITIVE_15_CONTROL_POINT_PATCH = 22,
   VGPU10_PRIMITIVE_16_CONTROL_POINT_PATCH = 23,
   VGPU10_PRIMITIVE_17_CONTROL_POINT_PATCH = 24,
   VGPU10_PRIMITIVE_18_CONTROL_POINT_PATCH = 25,
   VGPU10_PRIMITIVE_19_CONTROL_POINT_PATCH = 26,
   VGPU10_PRIMITIVE_20_CONTROL_POINT_PATCH = 27,
   VGPU10_PRIMITIVE_21_CONTROL_POINT_PATCH = 28,
   VGPU10_PRIMITIVE_22_CONTROL_POINT_PATCH = 29,
   VGPU10_PRIMITIVE_23_CONTROL_POINT_PATCH = 30,
   VGPU10_PRIMITIVE_24_CONTROL_POINT_PATCH = 31,
   VGPU10_PRIMITIVE_25_CONTROL_POINT_PATCH = 32,
   VGPU10_PRIMITIVE_26_CONTROL_POINT_PATCH = 33,
   VGPU10_PRIMITIVE_27_CONTROL_POINT_PATCH = 34,
   VGPU10_PRIMITIVE_28_CONTROL_POINT_PATCH = 35,
   VGPU10_PRIMITIVE_29_CONTROL_POINT_PATCH = 36,
   VGPU10_PRIMITIVE_30_CONTROL_POINT_PATCH = 37,
   VGPU10_PRIMITIVE_31_CONTROL_POINT_PATCH = 38,
   VGPU10_PRIMITIVE_32_CONTROL_POINT_PATCH = 39,
   VGPU10_PRIMITIVE_MAX = 39
} VGPU10_PRIMITIVE;

typedef enum {
   VGPU10_PRIMITIVE_TOPOLOGY_UNDEFINED = 0,
   VGPU10_PRIMITIVE_TOPOLOGY_POINTLIST = 1,
   VGPU10_PRIMITIVE_TOPOLOGY_LINELIST = 2,
   VGPU10_PRIMITIVE_TOPOLOGY_LINESTRIP = 3,
   VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4,
   VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5,
   VGPU10_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10,
   VGPU10_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11,
   VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12,
   VGPU10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13
} VGPU10_PRIMITIVE_TOPOLOGY;

typedef enum {
   VGPU10_CUSTOMDATA_COMMENT = 0,
   VGPU10_CUSTOMDATA_DEBUGINFO = 1,
   VGPU10_CUSTOMDATA_OPAQUE = 2,
   VGPU10_CUSTOMDATA_DCL_IMMEDIATE_CONSTANT_BUFFER = 3
} VGPU10_CUSTOMDATA_CLASS;

typedef enum {
   VGPU10_RESINFO_RETURN_FLOAT = 0,
   VGPU10_RESINFO_RETURN_RCPFLOAT = 1,
   VGPU10_RESINFO_RETURN_UINT = 2
} VGPU10_RESINFO_RETURN_TYPE;

typedef enum {
   VGPU10_INSTRUCTION_RETURN_FLOAT = 0,
   VGPU10_INSTRUCTION_RETURN_UINT = 1
} VGPU10_INSTRUCTION_RETURN_TYPE;

typedef enum {
   VGPU10_TESSELLATOR_DOMAIN_UNDEFINED = 0,
   VGPU10_TESSELLATOR_DOMAIN_ISOLINE = 1,
   VGPU10_TESSELLATOR_DOMAIN_TRI = 2,
   VGPU10_TESSELLATOR_DOMAIN_QUAD = 3,
   VGPU10_TESSELLATOR_DOMAIN_MAX = 3
} VGPU10_TESSELLATOR_DOMAIN;

typedef enum {
   VGPU10_TESSELLATOR_PARTITIONING_UNDEFINED = 0,
   VGPU10_TESSELLATOR_PARTITIONING_INTEGER = 1,
   VGPU10_TESSELLATOR_PARTITIONING_POW2 = 2,
   VGPU10_TESSELLATOR_PARTITIONING_FRACTIONAL_ODD = 3,
   VGPU10_TESSELLATOR_PARTITIONING_FRACTIONAL_EVEN = 4,
   VGPU10_TESSELLATOR_PARTITIONING_MAX = 4
} VGPU10_TESSELLATOR_PARTITIONING;

typedef enum {
   VGPU10_TESSELLATOR_OUTPUT_UNDEFINED = 0,
   VGPU10_TESSELLATOR_OUTPUT_POINT = 1,
   VGPU10_TESSELLATOR_OUTPUT_LINE = 2,
   VGPU10_TESSELLATOR_OUTPUT_TRIANGLE_CW = 3,
   VGPU10_TESSELLATOR_OUTPUT_TRIANGLE_CCW = 4,
   VGPU10_TESSELLATOR_OUTPUT_MAX = 4
} VGPU10_TESSELLATOR_OUTPUT_PRIMITIVE;

typedef union {
   struct {
      unsigned int opcodeType        : 11;
      unsigned int interpolationMode : 4;
      unsigned int                   : 3;
      unsigned int testBoolean       : 1;
      unsigned int preciseValues     : 4;
      unsigned int                   : 1;
      unsigned int instructionLength : 7;
      unsigned int extended          : 1;
   };

   struct {
      unsigned int                  : 11;
      unsigned int vmwareOpcodeType : 4;
   };
   struct {
      unsigned int                   : 11;
      unsigned int resourceDimension : 5;
      unsigned int sampleCount       : 7;
   };
   struct {
      unsigned int             : 11;
      unsigned int samplerMode : 4;
   };
   struct {
      unsigned int               : 11;
      unsigned int accessPattern : 1;
   };
   struct {
      unsigned int           : 11;
      unsigned int primitive : 6;
   };
   struct {
      unsigned int                   : 11;
      unsigned int primitiveTopology : 7;
   };
   struct {
      unsigned int                 : 11;
      unsigned int customDataClass : 21;
   };
   struct {
      unsigned int                   : 11;
      unsigned int resinfoReturnType : 2;
      unsigned int saturate          : 1;
   };
   struct {
      unsigned int                    : 11;
      unsigned int refactoringAllowed : 1;

      unsigned int enableDoublePrecisionFloatOps : 1;
      unsigned int forceEarlyDepthStencil        : 1;
      unsigned int enableRawAndStructuredBuffers : 1;
   };
   struct {
      unsigned int                : 11;
      unsigned int instReturnType : 2;
   };

   struct {
      unsigned int                       : 11;
      unsigned int syncThreadsInGroup    : 1;
      unsigned int syncThreadGroupShared : 1;
      unsigned int syncUAVMemoryGroup    : 1;
      unsigned int syncUAVMemoryGlobal   : 1;
   };
   struct {
      unsigned int                   : 11;
      unsigned int controlPointCount : 6;
   };
   struct {
      unsigned int            : 11;
      unsigned int tessDomain : 2;
   };
   struct {
      unsigned int                  : 11;
      unsigned int tessPartitioning : 3;
   };
   struct {
      unsigned int                     : 11;
      unsigned int tessOutputPrimitive : 3;
   };
   struct {
      unsigned int                             : 11;
      unsigned int interfaceIndexedDynamically : 1;
   };
   struct {
      unsigned int                      : 11;
      unsigned int uavResourceDimension : 5;
      unsigned int globallyCoherent     : 1;
      unsigned int                      : 6;
      unsigned int uavHasCounter        : 1;
   };
   uint32 value;
} VGPU10OpcodeToken0;

typedef enum {
   VGPU10_EXTENDED_OPCODE_EMPTY = 0,
   VGPU10_EXTENDED_OPCODE_SAMPLE_CONTROLS = 1,

   VGPU10_EXTENDED_OPCODE_RESOURCE_DIM = 2,
   VGPU10_EXTENDED_OPCODE_RESOURCE_RETURN_TYPE = 3
} VGPU10_EXTENDED_OPCODE_TYPE;

typedef union {
   struct {
      unsigned int opcodeType : 6;
      unsigned int            : 3;
      unsigned int offsetU    : 4;
      unsigned int offsetV    : 4;
      unsigned int offsetW    : 4;
      unsigned int            : 10;
      unsigned int extended   : 1;
   };

   struct {
      unsigned int                   : 6;
      unsigned int resourceDimension : 5;
   };
   struct {
      unsigned int                     : 6;
      unsigned int resourceReturnTypeX : 4;
      unsigned int resourceReturnTypeY : 4;
      unsigned int resourceReturnTypeZ : 4;
      unsigned int resourceReturnTypeW : 4;
   };
   uint32 value;
} VGPU10OpcodeToken1;

typedef enum {
   VGPU10_OPERAND_0_COMPONENT = 0,
   VGPU10_OPERAND_1_COMPONENT = 1,
   VGPU10_OPERAND_4_COMPONENT = 2,
   VGPU10_OPERAND_N_COMPONENT = 3
} VGPU10_OPERAND_NUM_COMPONENTS;

typedef enum {
   VGPU10_OPERAND_4_COMPONENT_MASK_MODE = 0,
   VGPU10_OPERAND_4_COMPONENT_SWIZZLE_MODE = 1,
   VGPU10_OPERAND_4_COMPONENT_SELECT_1_MODE = 2
} VGPU10_OPERAND_4_COMPONENT_SELECTION_MODE;

#define VGPU10_OPERAND_4_COMPONENT_MASK_X 0x1
#define VGPU10_OPERAND_4_COMPONENT_MASK_Y 0x2
#define VGPU10_OPERAND_4_COMPONENT_MASK_Z 0x4
#define VGPU10_OPERAND_4_COMPONENT_MASK_W 0x8

#define VGPU10_OPERAND_4_COMPONENT_MASK_XY                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_X | VGPU10_OPERAND_4_COMPONENT_MASK_Y)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XZ                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_X | VGPU10_OPERAND_4_COMPONENT_MASK_Z)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XW                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_X | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_YZ                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_Y | VGPU10_OPERAND_4_COMPONENT_MASK_Z)
#define VGPU10_OPERAND_4_COMPONENT_MASK_YW                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_Y | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_ZW                                     \
   (VGPU10_OPERAND_4_COMPONENT_MASK_Z | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XYZ                                    \
   (VGPU10_OPERAND_4_COMPONENT_MASK_XY | VGPU10_OPERAND_4_COMPONENT_MASK_Z)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XYW                                    \
   (VGPU10_OPERAND_4_COMPONENT_MASK_XY | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XZW                                    \
   (VGPU10_OPERAND_4_COMPONENT_MASK_XZ | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_YZW                                    \
   (VGPU10_OPERAND_4_COMPONENT_MASK_YZ | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_XYZW                                   \
   (VGPU10_OPERAND_4_COMPONENT_MASK_XYZ | VGPU10_OPERAND_4_COMPONENT_MASK_W)
#define VGPU10_OPERAND_4_COMPONENT_MASK_ALL VGPU10_OPERAND_4_COMPONENT_MASK_XYZW

#define VGPU10_REGISTER_INDEX_FROM_SEMANTIC 0xffffffff

typedef enum {
   VGPU10_COMPONENT_X = 0,
   VGPU10_COMPONENT_Y = 1,
   VGPU10_COMPONENT_Z = 2,
   VGPU10_COMPONENT_W = 3
} VGPU10_COMPONENT_NAME;

typedef enum {
   VGPU10_OPERAND_TYPE_TEMP = 0,
   VGPU10_OPERAND_TYPE_INPUT = 1,
   VGPU10_OPERAND_TYPE_OUTPUT = 2,
   VGPU10_OPERAND_TYPE_INDEXABLE_TEMP = 3,
   VGPU10_OPERAND_TYPE_IMMEDIATE32 = 4,
   VGPU10_OPERAND_TYPE_IMMEDIATE64 = 5,
   VGPU10_OPERAND_TYPE_SAMPLER = 6,
   VGPU10_OPERAND_TYPE_RESOURCE = 7,
   VGPU10_OPERAND_TYPE_CONSTANT_BUFFER = 8,
   VGPU10_OPERAND_TYPE_IMMEDIATE_CONSTANT_BUFFER = 9,
   VGPU10_OPERAND_TYPE_LABEL = 10,
   VGPU10_OPERAND_TYPE_INPUT_PRIMITIVEID = 11,
   VGPU10_OPERAND_TYPE_OUTPUT_DEPTH = 12,
   VGPU10_OPERAND_TYPE_NULL = 13,
   VGPU10_OPERAND_TYPE_SM40_MAX = 13,

   VGPU10_OPERAND_TYPE_RASTERIZER = 14,
   VGPU10_OPERAND_TYPE_OUTPUT_COVERAGE_MASK = 15,
   VGPU10_OPERAND_TYPE_SM41_MAX = 15,

   VGPU10_OPERAND_TYPE_STREAM = 16,
   VGPU10_OPERAND_TYPE_FUNCTION_BODY = 17,
   VGPU10_OPERAND_TYPE_FUNCTION_TABLE = 18,
   VGPU10_OPERAND_TYPE_INTERFACE = 19,
   VGPU10_OPERAND_TYPE_FUNCTION_INPUT = 20,
   VGPU10_OPERAND_TYPE_FUNCTION_OUTPUT = 21,
   VGPU10_OPERAND_TYPE_OUTPUT_CONTROL_POINT_ID = 22,
   VGPU10_OPERAND_TYPE_INPUT_FORK_INSTANCE_ID = 23,
   VGPU10_OPERAND_TYPE_INPUT_JOIN_INSTANCE_ID = 24,
   VGPU10_OPERAND_TYPE_INPUT_CONTROL_POINT = 25,
   VGPU10_OPERAND_TYPE_OUTPUT_CONTROL_POINT = 26,
   VGPU10_OPERAND_TYPE_INPUT_PATCH_CONSTANT = 27,
   VGPU10_OPERAND_TYPE_INPUT_DOMAIN_POINT = 28,
   VGPU10_OPERAND_TYPE_THIS_POINTER = 29,
   VGPU10_OPERAND_TYPE_UAV = 30,
   VGPU10_OPERAND_TYPE_THREAD_GROUP_SHARED_MEMORY = 31,
   VGPU10_OPERAND_TYPE_INPUT_THREAD_ID = 32,
   VGPU10_OPERAND_TYPE_INPUT_THREAD_GROUP_ID = 33,
   VGPU10_OPERAND_TYPE_INPUT_THREAD_ID_IN_GROUP = 34,
   VGPU10_OPERAND_TYPE_INPUT_COVERAGE_MASK = 35,
   VGPU10_OPERAND_TYPE_INPUT_THREAD_ID_IN_GROUP_FLATTENED = 36,
   VGPU10_OPERAND_TYPE_INPUT_GS_INSTANCE_ID = 37,
   VGPU10_OPERAND_TYPE_OUTPUT_DEPTH_GREATER_EQUAL = 38,
   VGPU10_OPERAND_TYPE_OUTPUT_DEPTH_LESS_EQUAL = 39,
   VGPU10_OPERAND_TYPE_CYCLE_COUNTER = 40,
   VGPU10_OPERAND_TYPE_SM50_MAX = 40,

   VGPU10_NUM_OPERANDS
} VGPU10_OPERAND_TYPE;

typedef enum {
   VGPU10_OPERAND_INDEX_0D = 0,
   VGPU10_OPERAND_INDEX_1D = 1,
   VGPU10_OPERAND_INDEX_2D = 2,
   VGPU10_OPERAND_INDEX_3D = 3
} VGPU10_OPERAND_INDEX_DIMENSION;

typedef enum {
   VGPU10_OPERAND_INDEX_IMMEDIATE32 = 0,
   VGPU10_OPERAND_INDEX_IMMEDIATE64 = 1,
   VGPU10_OPERAND_INDEX_RELATIVE = 2,
   VGPU10_OPERAND_INDEX_IMMEDIATE32_PLUS_RELATIVE = 3,
   VGPU10_OPERAND_INDEX_IMMEDIATE64_PLUS_RELATIVE = 4
} VGPU10_OPERAND_INDEX_REPRESENTATION;

typedef union {
   struct {
      unsigned int numComponents        : 2;
      unsigned int selectionMode        : 2;
      unsigned int mask                 : 4;
      unsigned int                      : 4;
      unsigned int operandType          : 8;
      unsigned int indexDimension       : 2;
      unsigned int index0Representation : 3;
      unsigned int index1Representation : 3;
      unsigned int                      : 3;
      unsigned int extended             : 1;
   };
   struct {
      unsigned int          : 4;
      unsigned int swizzleX : 2;
      unsigned int swizzleY : 2;
      unsigned int swizzleZ : 2;
      unsigned int swizzleW : 2;
   };
   struct {
      unsigned int            : 4;
      unsigned int selectMask : 2;
   };
   uint32 value;
} VGPU10OperandToken0;

typedef enum {
   VGPU10_EXTENDED_OPERAND_EMPTY = 0,
   VGPU10_EXTENDED_OPERAND_MODIFIER = 1
} VGPU10_EXTENDED_OPERAND_TYPE;

typedef enum {
   VGPU10_OPERAND_MODIFIER_NONE = 0,
   VGPU10_OPERAND_MODIFIER_NEG = 1,
   VGPU10_OPERAND_MODIFIER_ABS = 2,
   VGPU10_OPERAND_MODIFIER_ABSNEG = 3
} VGPU10_OPERAND_MODIFIER;

typedef union {
   struct {
      unsigned int extendedOperandType : 6;
      unsigned int operandModifier     : 8;
      unsigned int                     : 17;
      unsigned int extended            : 1;
   };
   uint32 value;
} VGPU10OperandToken1;

typedef enum {
   VGPU10_RETURN_TYPE_MIN = 1,

   VGPU10_RETURN_TYPE_UNORM = 1,
   VGPU10_RETURN_TYPE_SNORM = 2,
   VGPU10_RETURN_TYPE_SINT = 3,
   VGPU10_RETURN_TYPE_UINT = 4,
   VGPU10_RETURN_TYPE_FLOAT = 5,
   VGPU10_RETURN_TYPE_MIXED = 6,
   VGPU10_RETURN_TYPE_SM40_MAX = 6,

   VGPU10_RETURN_TYPE_DOUBLE = 7,
   VGPU10_RETURN_TYPE_CONTINUED = 8,
   VGPU10_RETURN_TYPE_UNUSED = 9,

   VGPU10_RETURN_TYPE_MAX = 9
} VGPU10_RESOURCE_RETURN_TYPE;

typedef union {
   struct {
      unsigned int component0 : 4;
      unsigned int component1 : 4;
      unsigned int component2 : 4;
      unsigned int component3 : 4;
   };
   uint32 value;
} VGPU10ResourceReturnTypeToken;

typedef enum {
   VGPU10_NAME_MIN = 0,

   VGPU10_NAME_UNDEFINED = 0,
   VGPU10_NAME_POSITION = 1,
   VGPU10_NAME_CLIP_DISTANCE = 2,
   VGPU10_NAME_CULL_DISTANCE = 3,
   VGPU10_NAME_RENDER_TARGET_ARRAY_INDEX = 4,
   VGPU10_NAME_VIEWPORT_ARRAY_INDEX = 5,
   VGPU10_NAME_VERTEX_ID = 6,
   VGPU10_NAME_PRIMITIVE_ID = 7,
   VGPU10_NAME_INSTANCE_ID = 8,
   VGPU10_NAME_IS_FRONT_FACE = 9,
   VGPU10_NAME_SAMPLE_INDEX = 10,
   VGPU10_NAME_SM40_MAX = 10,

   VGPU10_NAME_FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR = 11,
   VGPU10_NAME_FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR = 12,
   VGPU10_NAME_FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR = 13,
   VGPU10_NAME_FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR = 14,
   VGPU10_NAME_FINAL_QUAD_U_INSIDE_TESSFACTOR = 15,
   VGPU10_NAME_FINAL_QUAD_V_INSIDE_TESSFACTOR = 16,
   VGPU10_NAME_FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR = 17,
   VGPU10_NAME_FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR = 18,
   VGPU10_NAME_FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR = 19,
   VGPU10_NAME_FINAL_TRI_INSIDE_TESSFACTOR = 20,
   VGPU10_NAME_FINAL_LINE_DETAIL_TESSFACTOR = 21,
   VGPU10_NAME_FINAL_LINE_DENSITY_TESSFACTOR = 22,

   VGPU10_NAME_MAX = 22
} VGPU10_SYSTEM_NAME;

typedef union {
   struct {
      unsigned int name : 16;
   };
   uint32 value;
} VGPU10NameToken;

#ifdef __cplusplus
}
#endif

#endif
                                                                                                                                                                                                                                                                                                                              source/v64/third_party/vmware-svga/svga3d_cmd.h                                                     0000644 0000000 0000000 00000106041 00000000000 016641  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 2012-2022 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_cmd.h --
 *
 *    SVGA 3d hardware cmd definitions
 */

#ifndef _SVGA3D_CMD_H_
#define _SVGA3D_CMD_H_

#include "svga3d_limits.h"
#include "svga3d_types.h"
#include "svga_reg.h"

typedef enum SVGAFifo3dCmdId {
   SVGA_3D_CMD_LEGACY_BASE = 1000,
   SVGA_3D_CMD_BASE = 1040,

   SVGA_3D_CMD_SURFACE_DEFINE = 1040,
   SVGA_3D_CMD_SURFACE_DESTROY = 1041,
   SVGA_3D_CMD_SURFACE_COPY = 1042,
   SVGA_3D_CMD_SURFACE_STRETCHBLT = 1043,
   SVGA_3D_CMD_SURFACE_DMA = 1044,
   SVGA_3D_CMD_CONTEXT_DEFINE = 1045,
   SVGA_3D_CMD_CONTEXT_DESTROY = 1046,
   SVGA_3D_CMD_SETTRANSFORM = 1047,
   SVGA_3D_CMD_SETZRANGE = 1048,
   SVGA_3D_CMD_SETRENDERSTATE = 1049,
   SVGA_3D_CMD_SETRENDERTARGET = 1050,
   SVGA_3D_CMD_SETTEXTURESTATE = 1051,
   SVGA_3D_CMD_SETMATERIAL = 1052,
   SVGA_3D_CMD_SETLIGHTDATA = 1053,
   SVGA_3D_CMD_SETLIGHTENABLED = 1054,
   SVGA_3D_CMD_SETVIEWPORT = 1055,
   SVGA_3D_CMD_SETCLIPPLANE = 1056,
   SVGA_3D_CMD_CLEAR = 1057,
   SVGA_3D_CMD_PRESENT = 1058,
   SVGA_3D_CMD_SHADER_DEFINE = 1059,
   SVGA_3D_CMD_SHADER_DESTROY = 1060,
   SVGA_3D_CMD_SET_SHADER = 1061,
   SVGA_3D_CMD_SET_SHADER_CONST = 1062,
   SVGA_3D_CMD_DRAW_PRIMITIVES = 1063,
   SVGA_3D_CMD_SETSCISSORRECT = 1064,
   SVGA_3D_CMD_BEGIN_QUERY = 1065,
   SVGA_3D_CMD_END_QUERY = 1066,
   SVGA_3D_CMD_WAIT_FOR_QUERY = 1067,
   SVGA_3D_CMD_PRESENT_READBACK = 1068,
   SVGA_3D_CMD_BLIT_SURFACE_TO_SCREEN = 1069,
   SVGA_3D_CMD_SURFACE_DEFINE_V2 = 1070,
   SVGA_3D_CMD_GENERATE_MIPMAPS = 1071,
   SVGA_3D_CMD_DEAD4 = 1072,
   SVGA_3D_CMD_DEAD5 = 1073,
   SVGA_3D_CMD_DEAD6 = 1074,
   SVGA_3D_CMD_DEAD7 = 1075,
   SVGA_3D_CMD_DEAD8 = 1076,
   SVGA_3D_CMD_DEAD9 = 1077,
   SVGA_3D_CMD_DEAD10 = 1078,
   SVGA_3D_CMD_DEAD11 = 1079,
   SVGA_3D_CMD_ACTIVATE_SURFACE = 1080,
   SVGA_3D_CMD_DEACTIVATE_SURFACE = 1081,
   SVGA_3D_CMD_SCREEN_DMA = 1082,
   SVGA_3D_CMD_DEAD1 = 1083,
   SVGA_3D_CMD_DEAD2 = 1084,

   SVGA_3D_CMD_DEAD12 = 1085,
   SVGA_3D_CMD_DEAD13 = 1086,
   SVGA_3D_CMD_DEAD14 = 1087,
   SVGA_3D_CMD_DEAD15 = 1088,
   SVGA_3D_CMD_DEAD16 = 1089,
   SVGA_3D_CMD_DEAD17 = 1090,

   SVGA_3D_CMD_SET_OTABLE_BASE = 1091,
   SVGA_3D_CMD_READBACK_OTABLE = 1092,

   SVGA_3D_CMD_DEFINE_GB_MOB = 1093,
   SVGA_3D_CMD_DESTROY_GB_MOB = 1094,
   SVGA_3D_CMD_DEAD3 = 1095,
   SVGA_3D_CMD_UPDATE_GB_MOB_MAPPING = 1096,

   SVGA_3D_CMD_DEFINE_GB_SURFACE = 1097,
   SVGA_3D_CMD_DESTROY_GB_SURFACE = 1098,
   SVGA_3D_CMD_BIND_GB_SURFACE = 1099,
   SVGA_3D_CMD_COND_BIND_GB_SURFACE = 1100,
   SVGA_3D_CMD_UPDATE_GB_IMAGE = 1101,
   SVGA_3D_CMD_UPDATE_GB_SURFACE = 1102,
   SVGA_3D_CMD_READBACK_GB_IMAGE = 1103,
   SVGA_3D_CMD_READBACK_GB_SURFACE = 1104,
   SVGA_3D_CMD_INVALIDATE_GB_IMAGE = 1105,
   SVGA_3D_CMD_INVALIDATE_GB_SURFACE = 1106,

   SVGA_3D_CMD_DEFINE_GB_CONTEXT = 1107,
   SVGA_3D_CMD_DESTROY_GB_CONTEXT = 1108,
   SVGA_3D_CMD_BIND_GB_CONTEXT = 1109,
   SVGA_3D_CMD_READBACK_GB_CONTEXT = 1110,
   SVGA_3D_CMD_INVALIDATE_GB_CONTEXT = 1111,

   SVGA_3D_CMD_DEFINE_GB_SHADER = 1112,
   SVGA_3D_CMD_DESTROY_GB_SHADER = 1113,
   SVGA_3D_CMD_BIND_GB_SHADER = 1114,

   SVGA_3D_CMD_SET_OTABLE_BASE64 = 1115,

   SVGA_3D_CMD_BEGIN_GB_QUERY = 1116,
   SVGA_3D_CMD_END_GB_QUERY = 1117,
   SVGA_3D_CMD_WAIT_FOR_GB_QUERY = 1118,

   SVGA_3D_CMD_NOP = 1119,

   SVGA_3D_CMD_ENABLE_GART = 1120,
   SVGA_3D_CMD_DISABLE_GART = 1121,
   SVGA_3D_CMD_MAP_MOB_INTO_GART = 1122,
   SVGA_3D_CMD_UNMAP_GART_RANGE = 1123,

   SVGA_3D_CMD_DEFINE_GB_SCREENTARGET = 1124,
   SVGA_3D_CMD_DESTROY_GB_SCREENTARGET = 1125,
   SVGA_3D_CMD_BIND_GB_SCREENTARGET = 1126,
   SVGA_3D_CMD_UPDATE_GB_SCREENTARGET = 1127,

   SVGA_3D_CMD_READBACK_GB_IMAGE_PARTIAL = 1128,
   SVGA_3D_CMD_INVALIDATE_GB_IMAGE_PARTIAL = 1129,

   SVGA_3D_CMD_SET_GB_SHADERCONSTS_INLINE = 1130,

   SVGA_3D_CMD_GB_SCREEN_DMA = 1131,
   SVGA_3D_CMD_BIND_GB_SURFACE_WITH_PITCH = 1132,
   SVGA_3D_CMD_GB_MOB_FENCE = 1133,
   SVGA_3D_CMD_DEFINE_GB_SURFACE_V2 = 1134,
   SVGA_3D_CMD_DEFINE_GB_MOB64 = 1135,
   SVGA_3D_CMD_REDEFINE_GB_MOB64 = 1136,
   SVGA_3D_CMD_NOP_ERROR = 1137,

   SVGA_3D_CMD_SET_VERTEX_STREAMS = 1138,
   SVGA_3D_CMD_SET_VERTEX_DECLS = 1139,
   SVGA_3D_CMD_SET_VERTEX_DIVISORS = 1140,
   SVGA_3D_CMD_DRAW = 1141,
   SVGA_3D_CMD_DRAW_INDEXED = 1142,

   SVGA_3D_CMD_DX_MIN = 1143,
   SVGA_3D_CMD_DX_DEFINE_CONTEXT = 1143,
   SVGA_3D_CMD_DX_DESTROY_CONTEXT = 1144,
   SVGA_3D_CMD_DX_BIND_CONTEXT = 1145,
   SVGA_3D_CMD_DX_READBACK_CONTEXT = 1146,
   SVGA_3D_CMD_DX_INVALIDATE_CONTEXT = 1147,
   SVGA_3D_CMD_DX_SET_SINGLE_CONSTANT_BUFFER = 1148,
   SVGA_3D_CMD_DX_SET_SHADER_RESOURCES = 1149,
   SVGA_3D_CMD_DX_SET_SHADER = 1150,
   SVGA_3D_CMD_DX_SET_SAMPLERS = 1151,
   SVGA_3D_CMD_DX_DRAW = 1152,
   SVGA_3D_CMD_DX_DRAW_INDEXED = 1153,
   SVGA_3D_CMD_DX_DRAW_INSTANCED = 1154,
   SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED = 1155,
   SVGA_3D_CMD_DX_DRAW_AUTO = 1156,
   SVGA_3D_CMD_DX_SET_INPUT_LAYOUT = 1157,
   SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS = 1158,
   SVGA_3D_CMD_DX_SET_INDEX_BUFFER = 1159,
   SVGA_3D_CMD_DX_SET_TOPOLOGY = 1160,
   SVGA_3D_CMD_DX_SET_RENDERTARGETS = 1161,
   SVGA_3D_CMD_DX_SET_BLEND_STATE = 1162,
   SVGA_3D_CMD_DX_SET_DEPTHSTENCIL_STATE = 1163,
   SVGA_3D_CMD_DX_SET_RASTERIZER_STATE = 1164,
   SVGA_3D_CMD_DX_DEFINE_QUERY = 1165,
   SVGA_3D_CMD_DX_DESTROY_QUERY = 1166,
   SVGA_3D_CMD_DX_BIND_QUERY = 1167,
   SVGA_3D_CMD_DX_SET_QUERY_OFFSET = 1168,
   SVGA_3D_CMD_DX_BEGIN_QUERY = 1169,
   SVGA_3D_CMD_DX_END_QUERY = 1170,
   SVGA_3D_CMD_DX_READBACK_QUERY = 1171,
   SVGA_3D_CMD_DX_SET_PREDICATION = 1172,
   SVGA_3D_CMD_DX_SET_SOTARGETS = 1173,
   SVGA_3D_CMD_DX_SET_VIEWPORTS = 1174,
   SVGA_3D_CMD_DX_SET_SCISSORRECTS = 1175,
   SVGA_3D_CMD_DX_CLEAR_RENDERTARGET_VIEW = 1176,
   SVGA_3D_CMD_DX_CLEAR_DEPTHSTENCIL_VIEW = 1177,
   SVGA_3D_CMD_DX_PRED_COPY_REGION = 1178,
   SVGA_3D_CMD_DX_PRED_COPY = 1179,
   SVGA_3D_CMD_DX_PRESENTBLT = 1180,
   SVGA_3D_CMD_DX_GENMIPS = 1181,
   SVGA_3D_CMD_DX_UPDATE_SUBRESOURCE = 1182,
   SVGA_3D_CMD_DX_READBACK_SUBRESOURCE = 1183,
   SVGA_3D_CMD_DX_INVALIDATE_SUBRESOURCE = 1184,
   SVGA_3D_CMD_DX_DEFINE_SHADERRESOURCE_VIEW = 1185,
   SVGA_3D_CMD_DX_DESTROY_SHADERRESOURCE_VIEW = 1186,
   SVGA_3D_CMD_DX_DEFINE_RENDERTARGET_VIEW = 1187,
   SVGA_3D_CMD_DX_DESTROY_RENDERTARGET_VIEW = 1188,
   SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW = 1189,
   SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_VIEW = 1190,
   SVGA_3D_CMD_DX_DEFINE_ELEMENTLAYOUT = 1191,
   SVGA_3D_CMD_DX_DESTROY_ELEMENTLAYOUT = 1192,
   SVGA_3D_CMD_DX_DEFINE_BLEND_STATE = 1193,
   SVGA_3D_CMD_DX_DESTROY_BLEND_STATE = 1194,
   SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_STATE = 1195,
   SVGA_3D_CMD_DX_DESTROY_DEPTHSTENCIL_STATE = 1196,
   SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE = 1197,
   SVGA_3D_CMD_DX_DESTROY_RASTERIZER_STATE = 1198,
   SVGA_3D_CMD_DX_DEFINE_SAMPLER_STATE = 1199,
   SVGA_3D_CMD_DX_DESTROY_SAMPLER_STATE = 1200,
   SVGA_3D_CMD_DX_DEFINE_SHADER = 1201,
   SVGA_3D_CMD_DX_DESTROY_SHADER = 1202,
   SVGA_3D_CMD_DX_BIND_SHADER = 1203,
   SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT = 1204,
   SVGA_3D_CMD_DX_DESTROY_STREAMOUTPUT = 1205,
   SVGA_3D_CMD_DX_SET_STREAMOUTPUT = 1206,
   SVGA_3D_CMD_DX_SET_COTABLE = 1207,
   SVGA_3D_CMD_DX_READBACK_COTABLE = 1208,
   SVGA_3D_CMD_DX_BUFFER_COPY = 1209,
   SVGA_3D_CMD_DX_TRANSFER_FROM_BUFFER = 1210,
   SVGA_3D_CMD_DX_SURFACE_COPY_AND_READBACK = 1211,
   SVGA_3D_CMD_DX_MOVE_QUERY = 1212,
   SVGA_3D_CMD_DX_BIND_ALL_QUERY = 1213,
   SVGA_3D_CMD_DX_READBACK_ALL_QUERY = 1214,
   SVGA_3D_CMD_DX_PRED_TRANSFER_FROM_BUFFER = 1215,
   SVGA_3D_CMD_DX_MOB_FENCE_64 = 1216,
   SVGA_3D_CMD_DX_BIND_ALL_SHADER = 1217,
   SVGA_3D_CMD_DX_HINT = 1218,
   SVGA_3D_CMD_DX_BUFFER_UPDATE = 1219,
   SVGA_3D_CMD_DX_SET_VS_CONSTANT_BUFFER_OFFSET = 1220,
   SVGA_3D_CMD_DX_SET_PS_CONSTANT_BUFFER_OFFSET = 1221,
   SVGA_3D_CMD_DX_SET_GS_CONSTANT_BUFFER_OFFSET = 1222,
   SVGA_3D_CMD_DX_SET_HS_CONSTANT_BUFFER_OFFSET = 1223,
   SVGA_3D_CMD_DX_SET_DS_CONSTANT_BUFFER_OFFSET = 1224,
   SVGA_3D_CMD_DX_SET_CS_CONSTANT_BUFFER_OFFSET = 1225,

   SVGA_3D_CMD_DX_COND_BIND_ALL_SHADER = 1226,
   SVGA_3D_CMD_DX_MAX = 1227,

   SVGA_3D_CMD_SCREEN_COPY = 1227,

   SVGA_3D_CMD_RESERVED1 = 1228,
   SVGA_3D_CMD_RESERVED2 = 1229,
   SVGA_3D_CMD_RESERVED3 = 1230,
   SVGA_3D_CMD_RESERVED4 = 1231,
   SVGA_3D_CMD_RESERVED5 = 1232,
   SVGA_3D_CMD_RESERVED6 = 1233,
   SVGA_3D_CMD_RESERVED7 = 1234,
   SVGA_3D_CMD_RESERVED8 = 1235,

   SVGA_3D_CMD_GROW_OTABLE = 1236,
   SVGA_3D_CMD_DX_GROW_COTABLE = 1237,
   SVGA_3D_CMD_INTRA_SURFACE_COPY = 1238,

   SVGA_3D_CMD_DEFINE_GB_SURFACE_V3 = 1239,

   SVGA_3D_CMD_DX_RESOLVE_COPY = 1240,
   SVGA_3D_CMD_DX_PRED_RESOLVE_COPY = 1241,
   SVGA_3D_CMD_DX_PRED_CONVERT_REGION = 1242,
   SVGA_3D_CMD_DX_PRED_CONVERT = 1243,
   SVGA_3D_CMD_WHOLE_SURFACE_COPY = 1244,

   SVGA_3D_CMD_DX_DEFINE_UA_VIEW = 1245,
   SVGA_3D_CMD_DX_DESTROY_UA_VIEW = 1246,
   SVGA_3D_CMD_DX_CLEAR_UA_VIEW_UINT = 1247,
   SVGA_3D_CMD_DX_CLEAR_UA_VIEW_FLOAT = 1248,
   SVGA_3D_CMD_DX_COPY_STRUCTURE_COUNT = 1249,
   SVGA_3D_CMD_DX_SET_UA_VIEWS = 1250,

   SVGA_3D_CMD_DX_DRAW_INDEXED_INSTANCED_INDIRECT = 1251,
   SVGA_3D_CMD_DX_DRAW_INSTANCED_INDIRECT = 1252,
   SVGA_3D_CMD_DX_DISPATCH = 1253,
   SVGA_3D_CMD_DX_DISPATCH_INDIRECT = 1254,

   SVGA_3D_CMD_WRITE_ZERO_SURFACE = 1255,
   SVGA_3D_CMD_UPDATE_ZERO_SURFACE = 1256,
   SVGA_3D_CMD_DX_TRANSFER_TO_BUFFER = 1257,
   SVGA_3D_CMD_DX_SET_STRUCTURE_COUNT = 1258,

   SVGA_3D_CMD_LOGICOPS_BITBLT = 1259,
   SVGA_3D_CMD_LOGICOPS_TRANSBLT = 1260,
   SVGA_3D_CMD_LOGICOPS_STRETCHBLT = 1261,
   SVGA_3D_CMD_LOGICOPS_COLORFILL = 1262,
   SVGA_3D_CMD_LOGICOPS_ALPHABLEND = 1263,
   SVGA_3D_CMD_LOGICOPS_CLEARTYPEBLEND = 1264,

   SVGA_3D_CMD_DX_COPY_COTABLE_INTO_MOB = 1265,

   SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_V2 = 1266,

   SVGA_3D_CMD_DEFINE_GB_SURFACE_V4 = 1267,
   SVGA_3D_CMD_DX_SET_CS_UA_VIEWS = 1268,
   SVGA_3D_CMD_DX_SET_MIN_LOD = 1269,

   SVGA_3D_CMD_DX_DEFINE_DEPTHSTENCIL_VIEW_V2 = 1272,
   SVGA_3D_CMD_DX_DEFINE_STREAMOUTPUT_WITH_MOB = 1273,
   SVGA_3D_CMD_DX_SET_SHADER_IFACE = 1274,
   SVGA_3D_CMD_DX_BIND_STREAMOUTPUT = 1275,
   SVGA_3D_CMD_SURFACE_STRETCHBLT_NON_MS_TO_MS = 1276,
   SVGA_3D_CMD_DX_BIND_SHADER_IFACE = 1277,

   SVGA_3D_CMD_UPDATE_GB_SCREENTARGET_MOVE = 1278,

   SVGA_3D_CMD_DX_PRED_STAGING_COPY = 1281,
   SVGA_3D_CMD_DX_STAGING_COPY = 1282,
   SVGA_3D_CMD_DX_PRED_STAGING_COPY_REGION = 1283,
   SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_V2 = 1284,
   SVGA_3D_CMD_DX_SET_INDEX_BUFFER_V2 = 1285,
   SVGA_3D_CMD_DX_SET_VERTEX_BUFFERS_OFFSET_AND_SIZE = 1286,
   SVGA_3D_CMD_DX_SET_INDEX_BUFFER_OFFSET_AND_SIZE = 1287,
   SVGA_3D_CMD_DX_DEFINE_RASTERIZER_STATE_V2 = 1288,
   SVGA_3D_CMD_DX_PRED_STAGING_CONVERT_REGION = 1289,
   SVGA_3D_CMD_DX_PRED_STAGING_CONVERT = 1290,
   SVGA_3D_CMD_DX_STAGING_BUFFER_COPY = 1291,

   SVGA_3D_CMD_MAX = 1304,
   SVGA_3D_CMD_FUTURE_MAX = 3000
} SVGAFifo3dCmdId;

#define SVGA_NUM_3D_CMD (SVGA_3D_CMD_MAX - SVGA_3D_CMD_BASE)

#pragma pack(push, 1)
typedef struct {
   uint32 id;
   uint32 size;
} SVGA3dCmdHeader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 numMipLevels;
} SVGA3dSurfaceFace;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
   SVGA3dSurface1Flags surfaceFlags;
   SVGA3dSurfaceFormat format;

   SVGA3dSurfaceFace face[SVGA3D_MAX_SURFACE_FACES];

} SVGA3dCmdDefineSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
   SVGA3dSurface1Flags surfaceFlags;
   SVGA3dSurfaceFormat format;

   SVGA3dSurfaceFace face[SVGA3D_MAX_SURFACE_FACES];
   uint32 multisampleCount;
   SVGA3dTextureFilter autogenFilter;

} SVGA3dCmdDefineSurface_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
} SVGA3dCmdDestroySurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
} SVGA3dCmdDefineContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
} SVGA3dCmdDestroyContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dClearFlag clearFlag;
   uint32 color;
   float depth;
   uint32 stencil;

} SVGA3dCmdClear;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dLightType type;
   SVGA3dBool inWorldSpace;
   float diffuse[4];
   float specular[4];
   float ambient[4];
   float position[4];
   float direction[4];
   float range;
   float falloff;
   float attenuation0;
   float attenuation1;
   float attenuation2;
   float theta;
   float phi;
} SVGA3dLightData;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;

} SVGA3dCmdPresent;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dRenderStateName state;
   union {
      uint32 uintValue;
      float floatValue;
   };
} SVGA3dRenderState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

} SVGA3dCmdSetRenderState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dRenderTargetType type;
   SVGA3dSurfaceImageId target;
} SVGA3dCmdSetRenderTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dest;

} SVGA3dCmdSurfaceCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId surface;
   SVGA3dCopyBox box;
} SVGA3dCmdIntraSurfaceCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 srcSid;
   uint32 destSid;
} SVGA3dCmdWholeSurfaceCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dest;
   SVGA3dBox boxSrc;
   SVGA3dBox boxDest;
} SVGA3dCmdSurfaceStretchBltNonMSToMS;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dest;
   SVGA3dBox boxSrc;
   SVGA3dBox boxDest;
   SVGA3dStretchBltMode mode;
} SVGA3dCmdSurfaceStretchBlt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {

   uint32 discard : 1;

   uint32 unsynchronized : 1;

   uint32 reserved : 30;
} SVGA3dSurfaceDMAFlags;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAGuestImage guest;
   SVGA3dSurfaceImageId host;
   SVGA3dTransferType transfer;

} SVGA3dCmdSurfaceDMA;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 suffixSize;

   uint32 maximumOffset;

   SVGA3dSurfaceDMAFlags flags;
} SVGA3dCmdSurfaceDMASuffix;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {

   uint32 first;
   uint32 last;
} SVGA3dArrayRangeHint;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {

   uint32 surfaceId;
   uint32 offset;
   uint32 stride;
} SVGA3dArray;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {

   SVGA3dDeclType type;
   SVGA3dDeclMethod method;
   SVGA3dDeclUsage usage;
   uint32 usageIndex;
} SVGA3dVertexArrayIdentity;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dVertexDecl {
   SVGA3dVertexArrayIdentity identity;
   SVGA3dArray array;
   SVGA3dArrayRangeHint rangeHint;
} SVGA3dVertexDecl;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dPrimitiveRange {

   SVGA3dPrimitiveType primType;
   uint32 primitiveCount;

   SVGA3dArray indexArray;
   uint32 indexWidth;

   int32 indexBias;
} SVGA3dPrimitiveRange;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 numVertexDecls;
   uint32 numRanges;

} SVGA3dCmdDrawPrimitives;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

   uint32 primitiveCount;
   uint32 startVertexLocation;

   uint8 primitiveType;
   uint8 padding[3];
} SVGA3dCmdDraw;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

   uint8 primitiveType;

   uint32 indexBufferSid;
   uint32 indexBufferOffset;

   uint8 indexBufferStride;

   int32 baseVertexLocation;

   uint32 primitiveCount;
   uint32 pad0;
   uint16 pad1;
} SVGA3dCmdDrawIndexed;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {

   uint16 streamOffset;
   uint8 stream;
   uint8 type;
   uint8 method;
   uint8 usage;
   uint8 usageIndex;
   uint8 padding;

} SVGA3dVertexElement;
#pragma pack(pop)

#define SVGA3D_VERTEX_ELEMENT_RESPECT_STREAM (1 << 7)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

   uint32 numElements;

} SVGA3dCmdSetVertexDecls;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
   uint32 stride;
   uint32 offset;
} SVGA3dVertexStream;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

   uint32 numStreams;

} SVGA3dCmdSetVertexStreams;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 numDivisors;
} SVGA3dCmdSetVertexDivisors;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stage;
   SVGA3dTextureStateName name;
   union {
      uint32 value;
      float floatValue;
   };
} SVGA3dTextureState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;

} SVGA3dCmdSetTextureState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dTransformType type;
   float matrix[16];
} SVGA3dCmdSetTransform;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   float min;
   float max;
} SVGA3dZRange;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dZRange zRange;
} SVGA3dCmdSetZRange;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   float diffuse[4];
   float ambient[4];
   float specular[4];
   float emissive[4];
   float shininess;
} SVGA3dMaterial;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dFace face;
   SVGA3dMaterial material;
} SVGA3dCmdSetMaterial;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 index;
   SVGA3dLightData data;
} SVGA3dCmdSetLightData;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 index;
   uint32 enabled;
} SVGA3dCmdSetLightEnabled;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dRect rect;
} SVGA3dCmdSetViewport;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dRect rect;
} SVGA3dCmdSetScissorRect;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 index;
   float plane[4];
} SVGA3dCmdSetClipPlane;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 shid;
   SVGA3dShaderType type;

} SVGA3dCmdDefineShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 shid;
   SVGA3dShaderType type;
} SVGA3dCmdDestroyShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 reg;
   SVGA3dShaderType type;
   SVGA3dShaderConstType ctype;
   uint32 values[4];

} SVGA3dCmdSetShaderConst;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dShaderType type;
   uint32 shid;
} SVGA3dCmdSetShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
} SVGA3dCmdBeginQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
   SVGAGuestPtr guestResult;
} SVGA3dCmdEndQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
   SVGAGuestPtr guestResult;
} SVGA3dCmdWaitForQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 totalSize;
   SVGA3dQueryState state;
   union {
      uint32 result32;
      uint32 queryCookie;
   };
} SVGA3dQueryResult;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId srcImage;
   SVGASignedRect srcRect;
   uint32 destScreenId;
   SVGASignedRect destRect;

} SVGA3dCmdBlitSurfaceToScreen;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
   SVGA3dTextureFilter filter;
} SVGA3dCmdGenerateMipmaps;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
} SVGA3dCmdActivateSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
} SVGA3dCmdDeactivateSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdScreenDMA {
   uint32 screenId;
   SVGAGuestImage refBuffer;
   SVGAGuestImage destBuffer;
   SVGAGuestImage changeMap;
} SVGA3dCmdScreenDMA;
#pragma pack(pop)

#define SVGA3D_LOTRANSBLT_HONORALPHA    (0x01)
#define SVGA3D_LOSTRETCHBLT_MIRRORX     (0x01)
#define SVGA3D_LOSTRETCHBLT_MIRRORY     (0x02)
#define SVGA3D_LOALPHABLEND_SRCHASALPHA (0x01)

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsBitBlt {

   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dst;
   SVGA3dLogicOp logicOp;
   SVGA3dLogicOpRop3 logicOpRop3;

} SVGA3dCmdLogicOpsBitBlt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsTransBlt {

   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dst;
   uint32 color;
   uint32 flags;
   SVGA3dBox srcBox;
   SVGA3dSignedBox dstBox;
   SVGA3dBox clipBox;
} SVGA3dCmdLogicOpsTransBlt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsStretchBlt {

   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dst;
   uint16 mode;
   uint16 flags;
   SVGA3dBox srcBox;
   SVGA3dSignedBox dstBox;
   SVGA3dBox clipBox;
} SVGA3dCmdLogicOpsStretchBlt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsColorFill {

   SVGA3dSurfaceImageId dst;
   uint32 color;
   SVGA3dLogicOp logicOp;
   SVGA3dLogicOpRop3 logicOpRop3;

} SVGA3dCmdLogicOpsColorFill;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsAlphaBlend {

   SVGA3dSurfaceImageId src;
   SVGA3dSurfaceImageId dst;
   uint32 alphaVal;
   uint32 flags;
   SVGA3dBox srcBox;
   SVGA3dSignedBox dstBox;
   SVGA3dBox clipBox;
} SVGA3dCmdLogicOpsAlphaBlend;
#pragma pack(pop)

#define SVGA3D_CLEARTYPE_INVALID_GAMMA_INDEX 0xFFFFFFFF

#define SVGA3D_CLEARTYPE_GAMMA_WIDTH  512
#define SVGA3D_CLEARTYPE_GAMMA_HEIGHT 16

#pragma pack(push, 1)
typedef struct SVGA3dCmdLogicOpsClearTypeBlend {

   SVGA3dSurfaceImageId tmp;
   SVGA3dSurfaceImageId dst;
   SVGA3dSurfaceImageId gammaSurf;
   SVGA3dSurfaceImageId alphaSurf;
   uint32 gamma;
   uint32 color;
   uint32 color2;
   int32 alphaOffsetX;
   int32 alphaOffsetY;

} SVGA3dCmdLogicOpsClearTypeBlend;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAMobFormat ptDepth;
   uint32 sizeInBytes;
   PPN64 base;
} SVGAOTableMobEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceFormat format;
   SVGA3dSurface1Flags surface1Flags;
   uint32 numMipLevels;
   uint32 multisampleCount;
   SVGA3dTextureFilter autogenFilter;
   SVGA3dSize size;
   SVGAMobId mobid;
   uint32 arraySize;
   uint32 mobPitch;
   SVGA3dSurface2Flags surface2Flags;
   uint8 multisamplePattern;
   uint8 qualityLevel;
   uint16 bufferByteStride;
   float minLOD;
   uint32 pad0[2];
} SVGAOTableSurfaceEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGAMobId mobid;
} SVGAOTableContextEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dShaderType type;
   uint32 sizeInBytes;
   uint32 offsetInBytes;
   SVGAMobId mobid;
} SVGAOTableShaderEntry;
#pragma pack(pop)

#define SVGA_STFLAG_PRIMARY  (1 << 0)
#define SVGA_STFLAG_RESERVED (1 << 1)
typedef uint32 SVGAScreenTargetFlags;

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceImageId image;
   uint32 width;
   uint32 height;
   int32 xRoot;
   int32 yRoot;
   SVGAScreenTargetFlags flags;
   uint32 dpi;
   uint32 pad[7];
} SVGAOTableScreenTargetEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   float value[4];
} SVGA3dShaderConstFloat;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   int32 value[4];
} SVGA3dShaderConstInt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 value;
} SVGA3dShaderConstBool;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint16 streamOffset;
   uint8 stream;
   uint8 type;
   uint8 methodUsage;
   uint8 usageIndex;
} SVGAGBVertexElement;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
   uint16 stride;
   uint32 offset;
} SVGAGBVertexStream;
#pragma pack(pop)
#pragma pack(push, 1)
typedef struct {
   SVGA3dRect viewport;
   SVGA3dRect scissorRect;
   SVGA3dZRange zRange;

   SVGA3dSurfaceImageId renderTargets[SVGA3D_RT_MAX];
   SVGAGBVertexElement decl1[4];

   uint32 renderStates[SVGA3D_RS_MAX];
   SVGAGBVertexElement decl2[18];
   uint32 pad0[2];

   struct {
      SVGA3dFace face;
      SVGA3dMaterial material;
   } material;

   float clipPlanes[SVGA3D_MAX_CLIP_PLANES][4];
   float matrices[SVGA3D_TRANSFORM_MAX][16];

   SVGA3dBool lightEnabled[SVGA3D_NUM_LIGHTS];
   SVGA3dLightData lightData[SVGA3D_NUM_LIGHTS];

   uint32 shaders[SVGA3D_NUM_SHADERTYPE_PREDX];
   SVGAGBVertexElement decl3[10];
   uint32 pad1[3];

   uint32 occQueryActive;
   uint32 occQueryValue;

   SVGA3dShaderConstInt pShaderIValues[SVGA3D_CONSTINTREG_MAX];
   SVGA3dShaderConstInt vShaderIValues[SVGA3D_CONSTINTREG_MAX];
   uint16 pShaderBValues;
   uint16 vShaderBValues;

   SVGAGBVertexStream streams[SVGA3D_MAX_VERTEX_ARRAYS];
   SVGA3dVertexDivisor divisors[SVGA3D_MAX_VERTEX_ARRAYS];
   uint32 numVertexDecls;
   uint32 numVertexStreams;
   uint32 numVertexDivisors;
   uint32 pad2[30];

   uint32 tsColorKey[SVGA3D_NUM_TEXTURE_UNITS];
   uint32 textureStages[SVGA3D_NUM_TEXTURE_UNITS][SVGA3D_TS_CONSTANT + 1];
   uint32 tsColorKeyEnable[SVGA3D_NUM_TEXTURE_UNITS];

   SVGA3dShaderConstFloat pShaderFValues[SVGA3D_CONSTREG_MAX];
   SVGA3dShaderConstFloat vShaderFValues[SVGA3D_CONSTREG_MAX];
} SVGAGBContextData;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAOTableType type;
   PPN32 baseAddress;
   uint32 sizeInBytes;
   uint32 validSizeInBytes;
   SVGAMobFormat ptDepth;
} SVGA3dCmdSetOTableBase;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAOTableType type;
   PPN64 baseAddress;
   uint32 sizeInBytes;
   uint32 validSizeInBytes;
   SVGAMobFormat ptDepth;
} SVGA3dCmdSetOTableBase64;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAOTableType type;
   PPN64 baseAddress;
   uint32 sizeInBytes;
   uint32 validSizeInBytes;
   SVGAMobFormat ptDepth;
} SVGA3dCmdGrowOTable;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAOTableType type;
} SVGA3dCmdReadbackOTable;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBMob {
   SVGAMobId mobid;
   SVGAMobFormat ptDepth;
   PPN32 base;
   uint32 sizeInBytes;
} SVGA3dCmdDefineGBMob;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDestroyGBMob {
   SVGAMobId mobid;
} SVGA3dCmdDestroyGBMob;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBMob64 {
   SVGAMobId mobid;
   SVGAMobFormat ptDepth;
   PPN64 base;
   uint32 sizeInBytes;
} SVGA3dCmdDefineGBMob64;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdRedefineGBMob64 {
   SVGAMobId mobid;
   SVGAMobFormat ptDepth;
   PPN64 base;
   uint32 sizeInBytes;
} SVGA3dCmdRedefineGBMob64;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdUpdateGBMobMapping {
   SVGAMobId mobid;
} SVGA3dCmdUpdateGBMobMapping;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBSurface {
   uint32 sid;
   SVGA3dSurface1Flags surfaceFlags;
   SVGA3dSurfaceFormat format;
   uint32 numMipLevels;
   uint32 multisampleCount;
   SVGA3dTextureFilter autogenFilter;
   SVGA3dSize size;
} SVGA3dCmdDefineGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBSurface_v2 {
   uint32 sid;
   SVGA3dSurface1Flags surfaceFlags;
   SVGA3dSurfaceFormat format;
   uint32 numMipLevels;
   uint32 multisampleCount;
   SVGA3dTextureFilter autogenFilter;
   SVGA3dSize size;
   uint32 arraySize;
   uint32 pad;
} SVGA3dCmdDefineGBSurface_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBSurface_v3 {
   uint32 sid;
   SVGA3dSurfaceAllFlags surfaceFlags;
   SVGA3dSurfaceFormat format;
   uint32 numMipLevels;
   uint32 multisampleCount;
   SVGA3dMSPattern multisamplePattern;
   SVGA3dMSQualityLevel qualityLevel;
   SVGA3dTextureFilter autogenFilter;
   SVGA3dSize size;
   uint32 arraySize;
} SVGA3dCmdDefineGBSurface_v3;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBSurface_v4 {
   uint32 sid;
   SVGA3dSurfaceAllFlags surfaceFlags;
   SVGA3dSurfaceFormat format;
   uint32 numMipLevels;
   uint32 multisampleCount;
   SVGA3dMSPattern multisamplePattern;
   SVGA3dMSQualityLevel qualityLevel;
   SVGA3dTextureFilter autogenFilter;
   SVGA3dSize size;
   uint32 arraySize;
   uint32 bufferByteStride;
} SVGA3dCmdDefineGBSurface_v4;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDestroyGBSurface {
   uint32 sid;
} SVGA3dCmdDestroyGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdBindGBSurface {
   uint32 sid;
   SVGAMobId mobid;
} SVGA3dCmdBindGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdBindGBSurfaceWithPitch {
   uint32 sid;
   SVGAMobId mobid;
   uint32 baseLevelPitch;
} SVGA3dCmdBindGBSurfaceWithPitch;
#pragma pack(pop)

#define SVGA3D_COND_BIND_GB_SURFACE_FLAG_READBACK (1 << 0)
#define SVGA3D_COND_BIND_GB_SURFACE_FLAG_UPDATE   (1 << 1)

#pragma pack(push, 1)
typedef struct SVGA3dCmdCondBindGBSurface {
   uint32 sid;
   SVGAMobId testMobid;
   SVGAMobId mobid;
   uint32 flags;
} SVGA3dCmdCondBindGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdUpdateGBImage {
   SVGA3dSurfaceImageId image;
   SVGA3dBox box;
} SVGA3dCmdUpdateGBImage;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdUpdateGBSurface {
   uint32 sid;
} SVGA3dCmdUpdateGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdReadbackGBImage {
   SVGA3dSurfaceImageId image;
} SVGA3dCmdReadbackGBImage;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdReadbackGBSurface {
   uint32 sid;
} SVGA3dCmdReadbackGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdReadbackGBImagePartial {
   SVGA3dSurfaceImageId image;
   SVGA3dBox box;
   uint32 invertBox;
} SVGA3dCmdReadbackGBImagePartial;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdInvalidateGBImage {
   SVGA3dSurfaceImageId image;
} SVGA3dCmdInvalidateGBImage;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdInvalidateGBSurface {
   uint32 sid;
} SVGA3dCmdInvalidateGBSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdInvalidateGBImagePartial {
   SVGA3dSurfaceImageId image;
   SVGA3dBox box;
   uint32 invertBox;
} SVGA3dCmdInvalidateGBImagePartial;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBContext {
   uint32 cid;
} SVGA3dCmdDefineGBContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDestroyGBContext {
   uint32 cid;
} SVGA3dCmdDestroyGBContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdBindGBContext {
   uint32 cid;
   SVGAMobId mobid;
   uint32 validContents;
} SVGA3dCmdBindGBContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdReadbackGBContext {
   uint32 cid;
} SVGA3dCmdReadbackGBContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdInvalidateGBContext {
   uint32 cid;
} SVGA3dCmdInvalidateGBContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDefineGBShader {
   uint32 shid;
   SVGA3dShaderType type;
   uint32 sizeInBytes;
} SVGA3dCmdDefineGBShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdBindGBShader {
   uint32 shid;
   SVGAMobId mobid;
   uint32 offsetInBytes;
} SVGA3dCmdBindGBShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDestroyGBShader {
   uint32 shid;
} SVGA3dCmdDestroyGBShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   uint32 regStart;
   SVGA3dShaderType shaderType;
   SVGA3dShaderConstType constType;

} SVGA3dCmdSetGBShaderConstInline;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
} SVGA3dCmdBeginGBQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
   SVGAMobId mobid;
   uint32 offset;
} SVGA3dCmdEndGBQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGA3dQueryType type;
   SVGAMobId mobid;
   uint32 offset;
} SVGA3dCmdWaitForGBQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAMobId mobid;
   uint32 mustBeZero;
   uint32 initialized;
} SVGA3dCmdEnableGart;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGAMobId mobid;
   uint32 gartOffset;
} SVGA3dCmdMapMobIntoGart;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 gartOffset;
   uint32 numPages;
} SVGA3dCmdUnmapGartRange;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   uint32 width;
   uint32 height;
   int32 xRoot;
   int32 yRoot;
   SVGAScreenTargetFlags flags;

   uint32 dpi;
} SVGA3dCmdDefineGBScreenTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
} SVGA3dCmdDestroyGBScreenTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   SVGA3dSurfaceImageId image;
} SVGA3dCmdBindGBScreenTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   SVGA3dRect rect;
} SVGA3dCmdUpdateGBScreenTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   SVGA3dRect rect;
   SVGA3dFrameUpdateType type;
} SVGA3dCmdUpdateGBScreenTarget_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   SVGA3dRect rect;
   SVGA3dFrameUpdateType type;
   SVGAUnsignedPoint srcPoint;
} SVGA3dCmdUpdateGBScreenTargetMove;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdGBScreenDMA {
   uint32 screenId;
   uint32 dead;
   SVGAMobId destMobID;
   uint32 destPitch;
   SVGAMobId changeMapMobID;
} SVGA3dCmdGBScreenDMA;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 value;
   uint32 mobId;
   uint32 mobOffset;
} SVGA3dCmdGBMobFence;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 stid;
   SVGA3dSurfaceImageId dest;

   uint32 statusMobId;
   uint32 statusMobOffset;

   uint32 mustBeInvalidId;
   uint32 mustBeZero;
} SVGA3dCmdScreenCopy;
#pragma pack(pop)

#define SVGA_SCREEN_COPY_STATUS_FAILURE 0x00
#define SVGA_SCREEN_COPY_STATUS_SUCCESS 0x01
#define SVGA_SCREEN_COPY_STATUS_INVALID 0xFFFFFFFF

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
} SVGA3dCmdWriteZeroSurface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 sid;
} SVGA3dCmdUpdateZeroSurface;
#pragma pack(pop)

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               source/v64/third_party/vmware-svga/svga3d_devcaps.h                                                 0000644 0000000 0000000 00000041564 00000000000 017533  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 1998-2021 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_devcaps.h --
 *
 *    SVGA 3d caps definitions
 */

#ifndef _SVGA3D_DEVCAPS_H_
#define _SVGA3D_DEVCAPS_H_

#include "svga3d_types.h"

#define SVGA3D_MAKE_HWVERSION(major, minor) (((major) << 16) | ((minor) & 0xFF))
#define SVGA3D_MAJOR_HWVERSION(version)     ((version) >> 16)
#define SVGA3D_MINOR_HWVERSION(version)     ((version) & 0xFF)

typedef enum {
   SVGA3D_HWVERSION_WS5_RC1 = SVGA3D_MAKE_HWVERSION(0, 1),
   SVGA3D_HWVERSION_WS5_RC2 = SVGA3D_MAKE_HWVERSION(0, 2),
   SVGA3D_HWVERSION_WS51_RC1 = SVGA3D_MAKE_HWVERSION(0, 3),
   SVGA3D_HWVERSION_WS6_B1 = SVGA3D_MAKE_HWVERSION(1, 1),
   SVGA3D_HWVERSION_FUSION_11 = SVGA3D_MAKE_HWVERSION(1, 4),
   SVGA3D_HWVERSION_WS65_B1 = SVGA3D_MAKE_HWVERSION(2, 0),
   SVGA3D_HWVERSION_WS8_B1 = SVGA3D_MAKE_HWVERSION(2, 1),
   SVGA3D_HWVERSION_CURRENT = SVGA3D_HWVERSION_WS8_B1,
} SVGA3dHardwareVersion;

typedef uint32 SVGA3dDevCapIndex;

#define SVGA3D_DEVCAP_INVALID    ((uint32) - 1)
#define SVGA3D_DEVCAP_3D         0
#define SVGA3D_DEVCAP_MAX_LIGHTS 1

#define SVGA3D_DEVCAP_MAX_TEXTURES                     2
#define SVGA3D_DEVCAP_MAX_CLIP_PLANES                  3
#define SVGA3D_DEVCAP_VERTEX_SHADER_VERSION            4
#define SVGA3D_DEVCAP_VERTEX_SHADER                    5
#define SVGA3D_DEVCAP_FRAGMENT_SHADER_VERSION          6
#define SVGA3D_DEVCAP_FRAGMENT_SHADER                  7
#define SVGA3D_DEVCAP_MAX_RENDER_TARGETS               8
#define SVGA3D_DEVCAP_S23E8_TEXTURES                   9
#define SVGA3D_DEVCAP_S10E5_TEXTURES                   10
#define SVGA3D_DEVCAP_MAX_FIXED_VERTEXBLEND            11
#define SVGA3D_DEVCAP_D16_BUFFER_FORMAT                12
#define SVGA3D_DEVCAP_D24S8_BUFFER_FORMAT              13
#define SVGA3D_DEVCAP_D24X8_BUFFER_FORMAT              14
#define SVGA3D_DEVCAP_QUERY_TYPES                      15
#define SVGA3D_DEVCAP_TEXTURE_GRADIENT_SAMPLING        16
#define SVGA3D_DEVCAP_MAX_POINT_SIZE                   17
#define SVGA3D_DEVCAP_MAX_SHADER_TEXTURES              18
#define SVGA3D_DEVCAP_MAX_TEXTURE_WIDTH                19
#define SVGA3D_DEVCAP_MAX_TEXTURE_HEIGHT               20
#define SVGA3D_DEVCAP_MAX_VOLUME_EXTENT                21
#define SVGA3D_DEVCAP_MAX_TEXTURE_REPEAT               22
#define SVGA3D_DEVCAP_MAX_TEXTURE_ASPECT_RATIO         23
#define SVGA3D_DEVCAP_MAX_TEXTURE_ANISOTROPY           24
#define SVGA3D_DEVCAP_MAX_PRIMITIVE_COUNT              25
#define SVGA3D_DEVCAP_MAX_VERTEX_INDEX                 26
#define SVGA3D_DEVCAP_MAX_VERTEX_SHADER_INSTRUCTIONS   27
#define SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_INSTRUCTIONS 28
#define SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEMPS          29
#define SVGA3D_DEVCAP_MAX_FRAGMENT_SHADER_TEMPS        30
#define SVGA3D_DEVCAP_TEXTURE_OPS                      31
#define SVGA3D_DEVCAP_SURFACEFMT_X8R8G8B8              32
#define SVGA3D_DEVCAP_SURFACEFMT_A8R8G8B8              33
#define SVGA3D_DEVCAP_SURFACEFMT_A2R10G10B10           34
#define SVGA3D_DEVCAP_SURFACEFMT_X1R5G5B5              35
#define SVGA3D_DEVCAP_SURFACEFMT_A1R5G5B5              36
#define SVGA3D_DEVCAP_SURFACEFMT_A4R4G4B4              37
#define SVGA3D_DEVCAP_SURFACEFMT_R5G6B5                38
#define SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE16           39
#define SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8_ALPHA8     40
#define SVGA3D_DEVCAP_SURFACEFMT_ALPHA8                41
#define SVGA3D_DEVCAP_SURFACEFMT_LUMINANCE8            42
#define SVGA3D_DEVCAP_SURFACEFMT_Z_D16                 43
#define SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8               44
#define SVGA3D_DEVCAP_SURFACEFMT_Z_D24X8               45
#define SVGA3D_DEVCAP_SURFACEFMT_DXT1                  46
#define SVGA3D_DEVCAP_SURFACEFMT_DXT2                  47
#define SVGA3D_DEVCAP_SURFACEFMT_DXT3                  48
#define SVGA3D_DEVCAP_SURFACEFMT_DXT4                  49
#define SVGA3D_DEVCAP_SURFACEFMT_DXT5                  50
#define SVGA3D_DEVCAP_SURFACEFMT_BUMPX8L8V8U8          51
#define SVGA3D_DEVCAP_SURFACEFMT_A2W10V10U10           52
#define SVGA3D_DEVCAP_SURFACEFMT_BUMPU8V8              53
#define SVGA3D_DEVCAP_SURFACEFMT_Q8W8V8U8              54
#define SVGA3D_DEVCAP_SURFACEFMT_CxV8U8                55
#define SVGA3D_DEVCAP_SURFACEFMT_R_S10E5               56
#define SVGA3D_DEVCAP_SURFACEFMT_R_S23E8               57
#define SVGA3D_DEVCAP_SURFACEFMT_RG_S10E5              58
#define SVGA3D_DEVCAP_SURFACEFMT_RG_S23E8              59
#define SVGA3D_DEVCAP_SURFACEFMT_ARGB_S10E5            60
#define SVGA3D_DEVCAP_SURFACEFMT_ARGB_S23E8            61

#define SVGA3D_DEVCAP_MISSING62 62

#define SVGA3D_DEVCAP_MAX_VERTEX_SHADER_TEXTURES 63

#define SVGA3D_DEVCAP_MAX_SIMULTANEOUS_RENDER_TARGETS 64

#define SVGA3D_DEVCAP_SURFACEFMT_V16U16       65
#define SVGA3D_DEVCAP_SURFACEFMT_G16R16       66
#define SVGA3D_DEVCAP_SURFACEFMT_A16B16G16R16 67
#define SVGA3D_DEVCAP_SURFACEFMT_UYVY         68
#define SVGA3D_DEVCAP_SURFACEFMT_YUY2         69

#define SVGA3D_DEVCAP_DEAD4 70
#define SVGA3D_DEVCAP_DEAD5 71
#define SVGA3D_DEVCAP_DEAD7 72
#define SVGA3D_DEVCAP_DEAD6 73

#define SVGA3D_DEVCAP_AUTOGENMIPMAPS  74
#define SVGA3D_DEVCAP_SURFACEFMT_NV12 75
#define SVGA3D_DEVCAP_DEAD10          76

#define SVGA3D_DEVCAP_MAX_CONTEXT_IDS 77

#define SVGA3D_DEVCAP_MAX_SURFACE_IDS 78

#define SVGA3D_DEVCAP_SURFACEFMT_Z_DF16      79
#define SVGA3D_DEVCAP_SURFACEFMT_Z_DF24      80
#define SVGA3D_DEVCAP_SURFACEFMT_Z_D24S8_INT 81

#define SVGA3D_DEVCAP_SURFACEFMT_ATI1 82
#define SVGA3D_DEVCAP_SURFACEFMT_ATI2 83

#define SVGA3D_DEVCAP_DEAD1 84
#define SVGA3D_DEVCAP_DEAD8 85
#define SVGA3D_DEVCAP_DEAD9 86

#define SVGA3D_DEVCAP_LINE_AA           87
#define SVGA3D_DEVCAP_LINE_STIPPLE      88
#define SVGA3D_DEVCAP_MAX_LINE_WIDTH    89
#define SVGA3D_DEVCAP_MAX_AA_LINE_WIDTH 90

#define SVGA3D_DEVCAP_SURFACEFMT_YV12 91

#define SVGA3D_DEVCAP_DEAD3 92

#define SVGA3D_DEVCAP_TS_COLOR_KEY 93

#define SVGA3D_DEVCAP_DEAD2 94

#define SVGA3D_DEVCAP_DXCONTEXT 95

#define SVGA3D_DEVCAP_DEAD11 96

#define SVGA3D_DEVCAP_DX_MAX_VERTEXBUFFERS 97

#define SVGA3D_DEVCAP_DX_MAX_CONSTANT_BUFFERS 98

#define SVGA3D_DEVCAP_DX_PROVOKING_VERTEX 99

#define SVGA3D_DEVCAP_DXFMT_X8R8G8B8                   100
#define SVGA3D_DEVCAP_DXFMT_A8R8G8B8                   101
#define SVGA3D_DEVCAP_DXFMT_R5G6B5                     102
#define SVGA3D_DEVCAP_DXFMT_X1R5G5B5                   103
#define SVGA3D_DEVCAP_DXFMT_A1R5G5B5                   104
#define SVGA3D_DEVCAP_DXFMT_A4R4G4B4                   105
#define SVGA3D_DEVCAP_DXFMT_Z_D32                      106
#define SVGA3D_DEVCAP_DXFMT_Z_D16                      107
#define SVGA3D_DEVCAP_DXFMT_Z_D24S8                    108
#define SVGA3D_DEVCAP_DXFMT_Z_D15S1                    109
#define SVGA3D_DEVCAP_DXFMT_LUMINANCE8                 110
#define SVGA3D_DEVCAP_DXFMT_LUMINANCE4_ALPHA4          111
#define SVGA3D_DEVCAP_DXFMT_LUMINANCE16                112
#define SVGA3D_DEVCAP_DXFMT_LUMINANCE8_ALPHA8          113
#define SVGA3D_DEVCAP_DXFMT_DXT1                       114
#define SVGA3D_DEVCAP_DXFMT_DXT2                       115
#define SVGA3D_DEVCAP_DXFMT_DXT3                       116
#define SVGA3D_DEVCAP_DXFMT_DXT4                       117
#define SVGA3D_DEVCAP_DXFMT_DXT5                       118
#define SVGA3D_DEVCAP_DXFMT_BUMPU8V8                   119
#define SVGA3D_DEVCAP_DXFMT_BUMPL6V5U5                 120
#define SVGA3D_DEVCAP_DXFMT_BUMPX8L8V8U8               121
#define SVGA3D_DEVCAP_DXFMT_FORMAT_DEAD1               122
#define SVGA3D_DEVCAP_DXFMT_ARGB_S10E5                 123
#define SVGA3D_DEVCAP_DXFMT_ARGB_S23E8                 124
#define SVGA3D_DEVCAP_DXFMT_A2R10G10B10                125
#define SVGA3D_DEVCAP_DXFMT_V8U8                       126
#define SVGA3D_DEVCAP_DXFMT_Q8W8V8U8                   127
#define SVGA3D_DEVCAP_DXFMT_CxV8U8                     128
#define SVGA3D_DEVCAP_DXFMT_X8L8V8U8                   129
#define SVGA3D_DEVCAP_DXFMT_A2W10V10U10                130
#define SVGA3D_DEVCAP_DXFMT_ALPHA8                     131
#define SVGA3D_DEVCAP_DXFMT_R_S10E5                    132
#define SVGA3D_DEVCAP_DXFMT_R_S23E8                    133
#define SVGA3D_DEVCAP_DXFMT_RG_S10E5                   134
#define SVGA3D_DEVCAP_DXFMT_RG_S23E8                   135
#define SVGA3D_DEVCAP_DXFMT_BUFFER                     136
#define SVGA3D_DEVCAP_DXFMT_Z_D24X8                    137
#define SVGA3D_DEVCAP_DXFMT_V16U16                     138
#define SVGA3D_DEVCAP_DXFMT_G16R16                     139
#define SVGA3D_DEVCAP_DXFMT_A16B16G16R16               140
#define SVGA3D_DEVCAP_DXFMT_UYVY                       141
#define SVGA3D_DEVCAP_DXFMT_YUY2                       142
#define SVGA3D_DEVCAP_DXFMT_NV12                       143
#define SVGA3D_DEVCAP_DXFMT_FORMAT_DEAD2               144
#define SVGA3D_DEVCAP_DXFMT_R32G32B32A32_TYPELESS      145
#define SVGA3D_DEVCAP_DXFMT_R32G32B32A32_UINT          146
#define SVGA3D_DEVCAP_DXFMT_R32G32B32A32_SINT          147
#define SVGA3D_DEVCAP_DXFMT_R32G32B32_TYPELESS         148
#define SVGA3D_DEVCAP_DXFMT_R32G32B32_FLOAT            149
#define SVGA3D_DEVCAP_DXFMT_R32G32B32_UINT             150
#define SVGA3D_DEVCAP_DXFMT_R32G32B32_SINT             151
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_TYPELESS      152
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_UINT          153
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_SNORM         154
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_SINT          155
#define SVGA3D_DEVCAP_DXFMT_R32G32_TYPELESS            156
#define SVGA3D_DEVCAP_DXFMT_R32G32_UINT                157
#define SVGA3D_DEVCAP_DXFMT_R32G32_SINT                158
#define SVGA3D_DEVCAP_DXFMT_R32G8X24_TYPELESS          159
#define SVGA3D_DEVCAP_DXFMT_D32_FLOAT_S8X24_UINT       160
#define SVGA3D_DEVCAP_DXFMT_R32_FLOAT_X8X24            161
#define SVGA3D_DEVCAP_DXFMT_X32_G8X24_UINT             162
#define SVGA3D_DEVCAP_DXFMT_R10G10B10A2_TYPELESS       163
#define SVGA3D_DEVCAP_DXFMT_R10G10B10A2_UINT           164
#define SVGA3D_DEVCAP_DXFMT_R11G11B10_FLOAT            165
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_TYPELESS          166
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UNORM             167
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UNORM_SRGB        168
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_UINT              169
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_SINT              170
#define SVGA3D_DEVCAP_DXFMT_R16G16_TYPELESS            171
#define SVGA3D_DEVCAP_DXFMT_R16G16_UINT                172
#define SVGA3D_DEVCAP_DXFMT_R16G16_SINT                173
#define SVGA3D_DEVCAP_DXFMT_R32_TYPELESS               174
#define SVGA3D_DEVCAP_DXFMT_D32_FLOAT                  175
#define SVGA3D_DEVCAP_DXFMT_R32_UINT                   176
#define SVGA3D_DEVCAP_DXFMT_R32_SINT                   177
#define SVGA3D_DEVCAP_DXFMT_R24G8_TYPELESS             178
#define SVGA3D_DEVCAP_DXFMT_D24_UNORM_S8_UINT          179
#define SVGA3D_DEVCAP_DXFMT_R24_UNORM_X8               180
#define SVGA3D_DEVCAP_DXFMT_X24_G8_UINT                181
#define SVGA3D_DEVCAP_DXFMT_R8G8_TYPELESS              182
#define SVGA3D_DEVCAP_DXFMT_R8G8_UNORM                 183
#define SVGA3D_DEVCAP_DXFMT_R8G8_UINT                  184
#define SVGA3D_DEVCAP_DXFMT_R8G8_SINT                  185
#define SVGA3D_DEVCAP_DXFMT_R16_TYPELESS               186
#define SVGA3D_DEVCAP_DXFMT_R16_UNORM                  187
#define SVGA3D_DEVCAP_DXFMT_R16_UINT                   188
#define SVGA3D_DEVCAP_DXFMT_R16_SNORM                  189
#define SVGA3D_DEVCAP_DXFMT_R16_SINT                   190
#define SVGA3D_DEVCAP_DXFMT_R8_TYPELESS                191
#define SVGA3D_DEVCAP_DXFMT_R8_UNORM                   192
#define SVGA3D_DEVCAP_DXFMT_R8_UINT                    193
#define SVGA3D_DEVCAP_DXFMT_R8_SNORM                   194
#define SVGA3D_DEVCAP_DXFMT_R8_SINT                    195
#define SVGA3D_DEVCAP_DXFMT_P8                         196
#define SVGA3D_DEVCAP_DXFMT_R9G9B9E5_SHAREDEXP         197
#define SVGA3D_DEVCAP_DXFMT_R8G8_B8G8_UNORM            198
#define SVGA3D_DEVCAP_DXFMT_G8R8_G8B8_UNORM            199
#define SVGA3D_DEVCAP_DXFMT_BC1_TYPELESS               200
#define SVGA3D_DEVCAP_DXFMT_BC1_UNORM_SRGB             201
#define SVGA3D_DEVCAP_DXFMT_BC2_TYPELESS               202
#define SVGA3D_DEVCAP_DXFMT_BC2_UNORM_SRGB             203
#define SVGA3D_DEVCAP_DXFMT_BC3_TYPELESS               204
#define SVGA3D_DEVCAP_DXFMT_BC3_UNORM_SRGB             205
#define SVGA3D_DEVCAP_DXFMT_BC4_TYPELESS               206
#define SVGA3D_DEVCAP_DXFMT_ATI1                       207
#define SVGA3D_DEVCAP_DXFMT_BC4_SNORM                  208
#define SVGA3D_DEVCAP_DXFMT_BC5_TYPELESS               209
#define SVGA3D_DEVCAP_DXFMT_ATI2                       210
#define SVGA3D_DEVCAP_DXFMT_BC5_SNORM                  211
#define SVGA3D_DEVCAP_DXFMT_R10G10B10_XR_BIAS_A2_UNORM 212
#define SVGA3D_DEVCAP_DXFMT_B8G8R8A8_TYPELESS          213
#define SVGA3D_DEVCAP_DXFMT_B8G8R8A8_UNORM_SRGB        214
#define SVGA3D_DEVCAP_DXFMT_B8G8R8X8_TYPELESS          215
#define SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM_SRGB        216
#define SVGA3D_DEVCAP_DXFMT_Z_DF16                     217
#define SVGA3D_DEVCAP_DXFMT_Z_DF24                     218
#define SVGA3D_DEVCAP_DXFMT_Z_D24S8_INT                219
#define SVGA3D_DEVCAP_DXFMT_YV12                       220
#define SVGA3D_DEVCAP_DXFMT_R32G32B32A32_FLOAT         221
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_FLOAT         222
#define SVGA3D_DEVCAP_DXFMT_R16G16B16A16_UNORM         223
#define SVGA3D_DEVCAP_DXFMT_R32G32_FLOAT               224
#define SVGA3D_DEVCAP_DXFMT_R10G10B10A2_UNORM          225
#define SVGA3D_DEVCAP_DXFMT_R8G8B8A8_SNORM             226
#define SVGA3D_DEVCAP_DXFMT_R16G16_FLOAT               227
#define SVGA3D_DEVCAP_DXFMT_R16G16_UNORM               228
#define SVGA3D_DEVCAP_DXFMT_R16G16_SNORM               229
#define SVGA3D_DEVCAP_DXFMT_R32_FLOAT                  230
#define SVGA3D_DEVCAP_DXFMT_R8G8_SNORM                 231
#define SVGA3D_DEVCAP_DXFMT_R16_FLOAT                  232
#define SVGA3D_DEVCAP_DXFMT_D16_UNORM                  233
#define SVGA3D_DEVCAP_DXFMT_A8_UNORM                   234
#define SVGA3D_DEVCAP_DXFMT_BC1_UNORM                  235
#define SVGA3D_DEVCAP_DXFMT_BC2_UNORM                  236
#define SVGA3D_DEVCAP_DXFMT_BC3_UNORM                  237
#define SVGA3D_DEVCAP_DXFMT_B5G6R5_UNORM               238
#define SVGA3D_DEVCAP_DXFMT_B5G5R5A1_UNORM             239
#define SVGA3D_DEVCAP_DXFMT_B8G8R8A8_UNORM             240
#define SVGA3D_DEVCAP_DXFMT_B8G8R8X8_UNORM             241
#define SVGA3D_DEVCAP_DXFMT_BC4_UNORM                  242
#define SVGA3D_DEVCAP_DXFMT_BC5_UNORM                  243

#define SVGA3D_DEVCAP_SM41           244
#define SVGA3D_DEVCAP_MULTISAMPLE_2X 245
#define SVGA3D_DEVCAP_MULTISAMPLE_4X 246

#define SVGA3D_DEVCAP_MS_FULL_QUALITY 247

#define SVGA3D_DEVCAP_LOGICOPS 248

#define SVGA3D_DEVCAP_LOGIC_BLENDOPS 249

#define SVGA3D_DEVCAP_DEAD12 250

#define SVGA3D_DEVCAP_DXFMT_BC6H_TYPELESS  251
#define SVGA3D_DEVCAP_DXFMT_BC6H_UF16      252
#define SVGA3D_DEVCAP_DXFMT_BC6H_SF16      253
#define SVGA3D_DEVCAP_DXFMT_BC7_TYPELESS   254
#define SVGA3D_DEVCAP_DXFMT_BC7_UNORM      255
#define SVGA3D_DEVCAP_DXFMT_BC7_UNORM_SRGB 256

#define SVGA3D_DEVCAP_DEAD13 257

#define SVGA3D_DEVCAP_SM5            258
#define SVGA3D_DEVCAP_MULTISAMPLE_8X 259

#define SVGA3D_DEVCAP_MAX_FORCED_SAMPLE_COUNT 260

#define SVGA3D_DEVCAP_GL43 261

#define SVGA3D_DEVCAP_MAX 262

#define SVGA3D_DXFMT_SUPPORTED          (1 << 0)
#define SVGA3D_DXFMT_SHADER_SAMPLE      (1 << 1)
#define SVGA3D_DXFMT_COLOR_RENDERTARGET (1 << 2)
#define SVGA3D_DXFMT_DEPTH_RENDERTARGET (1 << 3)
#define SVGA3D_DXFMT_BLENDABLE          (1 << 4)
#define SVGA3D_DXFMT_MIPS               (1 << 5)
#define SVGA3D_DXFMT_ARRAY              (1 << 6)
#define SVGA3D_DXFMT_VOLUME             (1 << 7)
#define SVGA3D_DXFMT_DX_VERTEX_BUFFER   (1 << 8)
#define SVGA3D_DXFMT_MULTISAMPLE        (1 << 9)
#define SVGA3D_DXFMT_MAX                (1 << 10)

typedef union {
   SVGA3dBool b;
   uint32 u;
   int32 i;
   float f;
} SVGA3dDevCapResult;

#endif
                                                                                                                                            source/v64/third_party/vmware-svga/svga3d_dx.h                                                      0000644 0000000 0000000 00000127053 00000000000 016517  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 2012-2023 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_dx.h --
 *
 *    SVGA 3d hardware definitions for DX10 support.
 */

#ifndef _SVGA3D_DX_H_
#define _SVGA3D_DX_H_

#include "svga3d_limits.h"
#include "svga3d_types.h"
#include "svga_reg.h"

#define SVGA3D_INPUT_MIN               0
#define SVGA3D_INPUT_PER_VERTEX_DATA   0
#define SVGA3D_INPUT_PER_INSTANCE_DATA 1
#define SVGA3D_INPUT_MAX               2
typedef uint32 SVGA3dInputClassification;

#define SVGA3D_COLOR_WRITE_ENABLE_RED   (1 << 0)
#define SVGA3D_COLOR_WRITE_ENABLE_GREEN (1 << 1)
#define SVGA3D_COLOR_WRITE_ENABLE_BLUE  (1 << 2)
#define SVGA3D_COLOR_WRITE_ENABLE_ALPHA (1 << 3)
#define SVGA3D_COLOR_WRITE_ENABLE_ALL                                          \
   (SVGA3D_COLOR_WRITE_ENABLE_RED | SVGA3D_COLOR_WRITE_ENABLE_GREEN |          \
    SVGA3D_COLOR_WRITE_ENABLE_BLUE | SVGA3D_COLOR_WRITE_ENABLE_ALPHA)
typedef uint8 SVGA3dColorWriteEnable;

#define SVGA3D_DEPTH_WRITE_MASK_ZERO 0
#define SVGA3D_DEPTH_WRITE_MASK_ALL  1
typedef uint8 SVGA3dDepthWriteMask;

#define SVGA3D_FILTER_MIP_LINEAR  (1 << 0)
#define SVGA3D_FILTER_MAG_LINEAR  (1 << 2)
#define SVGA3D_FILTER_MIN_LINEAR  (1 << 4)
#define SVGA3D_FILTER_ANISOTROPIC (1 << 6)
#define SVGA3D_FILTER_COMPARE     (1 << 7)
typedef uint32 SVGA3dFilter;

#define SVGA3D_CULL_INVALID 0
#define SVGA3D_CULL_MIN     1
#define SVGA3D_CULL_NONE    1
#define SVGA3D_CULL_FRONT   2
#define SVGA3D_CULL_BACK    3
#define SVGA3D_CULL_MAX     4
typedef uint8 SVGA3dCullMode;

#define SVGA3D_COMPARISON_INVALID       0
#define SVGA3D_COMPARISON_MIN           1
#define SVGA3D_COMPARISON_NEVER         1
#define SVGA3D_COMPARISON_LESS          2
#define SVGA3D_COMPARISON_EQUAL         3
#define SVGA3D_COMPARISON_LESS_EQUAL    4
#define SVGA3D_COMPARISON_GREATER       5
#define SVGA3D_COMPARISON_NOT_EQUAL     6
#define SVGA3D_COMPARISON_GREATER_EQUAL 7
#define SVGA3D_COMPARISON_ALWAYS        8
#define SVGA3D_COMPARISON_MAX           9
typedef uint8 SVGA3dComparisonFunc;

#define SVGA3D_MULTISAMPLE_RAST_DISABLE      0
#define SVGA3D_MULTISAMPLE_RAST_ENABLE       1
#define SVGA3D_MULTISAMPLE_RAST_DX_MAX       1
#define SVGA3D_MULTISAMPLE_RAST_DISABLE_LINE 2
#define SVGA3D_MULTISAMPLE_RAST_MAX          2
typedef uint8 SVGA3dMultisampleRastEnable;

#define SVGA3D_DX_MAX_VERTEXBUFFERS             32
#define SVGA3D_DX_MAX_VERTEXINPUTREGISTERS      16
#define SVGA3D_DX_SM41_MAX_VERTEXINPUTREGISTERS 32
#define SVGA3D_DX_MAX_SOTARGETS                 4
#define SVGA3D_DX_MAX_SRVIEWS                   128
#define SVGA3D_DX_MAX_CONSTBUFFERS              16
#define SVGA3D_DX_MAX_SAMPLERS                  16
#define SVGA3D_DX_MAX_CLASS_INSTANCES           253

#define SVGA3D_DX_MAX_CONSTBUF_BINDING_SIZE (4096 * 4 * (uint32)sizeof(uint32))

typedef uint32 SVGA3dShaderResourceViewId;
typedef uint32 SVGA3dRenderTargetViewId;
typedef uint32 SVGA3dDepthStencilViewId;
typedef uint32 SVGA3dUAViewId;

typedef uint32 SVGA3dShaderId;
typedef uint32 SVGA3dElementLayoutId;
typedef uint32 SVGA3dSamplerId;
typedef uint32 SVGA3dBlendStateId;
typedef uint32 SVGA3dDepthStencilStateId;
typedef uint32 SVGA3dRasterizerStateId;
typedef uint32 SVGA3dQueryId;
typedef uint32 SVGA3dStreamOutputId;

typedef union {
   struct {
      uint32 r;
      uint32 g;
      uint32 b;
      uint32 a;
   };

   uint32 value[4];
} SVGA3dRGBAUint32;

#pragma pack(push, 1)
typedef struct {
   uint32 cid;
   SVGAMobId mobid;
} SVGAOTableDXContextEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineContext {
   uint32 cid;
} SVGA3dCmdDXDefineContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyContext {
   uint32 cid;
} SVGA3dCmdDXDestroyContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindContext {
   uint32 cid;
   SVGAMobId mobid;
   uint32 validContents;
} SVGA3dCmdDXBindContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXReadbackContext {
   uint32 cid;
} SVGA3dCmdDXReadbackContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXInvalidateContext {
   uint32 cid;
} SVGA3dCmdDXInvalidateContext;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetSingleConstantBuffer {
   uint32 slot;
   SVGA3dShaderType type;
   SVGA3dSurfaceId sid;
   uint32 offsetInBytes;
   uint32 sizeInBytes;
} SVGA3dCmdDXSetSingleConstantBuffer;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetShaderResources {
   uint32 startView;
   SVGA3dShaderType type;

} SVGA3dCmdDXSetShaderResources;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetShader {
   SVGA3dShaderId shaderId;
   SVGA3dShaderType type;
} SVGA3dCmdDXSetShader;
#pragma pack(pop)

typedef union {
   struct {
      uint32 cbOffset : 12;
      uint32 cbId     : 4;
      uint32 baseSamp : 4;
      uint32 baseTex  : 7;
      uint32 reserved : 5;
   };
   uint32 value;
} SVGA3dIfaceData;

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetShaderIface {
   SVGA3dShaderType type;
   uint32 numClassInstances;
   uint32 index;
   uint32 iface;
   SVGA3dIfaceData data;
} SVGA3dCmdDXSetShaderIface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindShaderIface {
   uint32 cid;
   SVGAMobId mobid;
   uint32 offsetInBytes;
} SVGA3dCmdDXBindShaderIface;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetSamplers {
   uint32 startSampler;
   SVGA3dShaderType type;

} SVGA3dCmdDXSetSamplers;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDraw {
   uint32 vertexCount;
   uint32 startVertexLocation;
} SVGA3dCmdDXDraw;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawIndexed {
   uint32 indexCount;
   uint32 startIndexLocation;
   int32 baseVertexLocation;
} SVGA3dCmdDXDrawIndexed;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawInstanced {
   uint32 vertexCountPerInstance;
   uint32 instanceCount;
   uint32 startVertexLocation;
   uint32 startInstanceLocation;
} SVGA3dCmdDXDrawInstanced;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawIndexedInstanced {
   uint32 indexCountPerInstance;
   uint32 instanceCount;
   uint32 startIndexLocation;
   int32 baseVertexLocation;
   uint32 startInstanceLocation;
} SVGA3dCmdDXDrawIndexedInstanced;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawIndexedInstancedIndirect {
   SVGA3dSurfaceId argsBufferSid;
   uint32 byteOffsetForArgs;
} SVGA3dCmdDXDrawIndexedInstancedIndirect;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawInstancedIndirect {
   SVGA3dSurfaceId argsBufferSid;
   uint32 byteOffsetForArgs;
} SVGA3dCmdDXDrawInstancedIndirect;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDrawAuto {
   uint32 pad0;
} SVGA3dCmdDXDrawAuto;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDispatch {
   uint32 threadGroupCountX;
   uint32 threadGroupCountY;
   uint32 threadGroupCountZ;
} SVGA3dCmdDXDispatch;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDispatchIndirect {
   SVGA3dSurfaceId argsBufferSid;
   uint32 byteOffsetForArgs;
} SVGA3dCmdDXDispatchIndirect;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetInputLayout {
   SVGA3dElementLayoutId elementLayoutId;
} SVGA3dCmdDXSetInputLayout;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dVertexBuffer {
   SVGA3dSurfaceId sid;
   uint32 stride;
   uint32 offset;
} SVGA3dVertexBuffer;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetVertexBuffers {
   uint32 startBuffer;

} SVGA3dCmdDXSetVertexBuffers;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dVertexBuffer_v2 {
   SVGA3dSurfaceId sid;
   uint32 stride;
   uint32 offset;
   uint32 sizeInBytes;
} SVGA3dVertexBuffer_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetVertexBuffers_v2 {
   uint32 startBuffer;

} SVGA3dCmdDXSetVertexBuffers_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dVertexBufferOffsetAndSize {
   uint32 stride;
   uint32 offset;
   uint32 sizeInBytes;
} SVGA3dVertexBufferOffsetAndSize;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetVertexBuffersOffsetAndSize {
   uint32 startBuffer;

} SVGA3dCmdDXSetVertexBuffersOffsetAndSize;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetIndexBuffer {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   uint32 offset;
} SVGA3dCmdDXSetIndexBuffer;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetIndexBuffer_v2 {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   uint32 offset;
   uint32 sizeInBytes;
} SVGA3dCmdDXSetIndexBuffer_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetIndexBufferOffsetAndSize {
   SVGA3dSurfaceFormat format;
   uint32 offset;
   uint32 sizeInBytes;
} SVGA3dCmdDXSetIndexBufferOffsetAndSize;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetTopology {
   SVGA3dPrimitiveType topology;
} SVGA3dCmdDXSetTopology;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetRenderTargets {
   SVGA3dDepthStencilViewId depthStencilViewId;

} SVGA3dCmdDXSetRenderTargets;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetBlendState {
   SVGA3dBlendStateId blendId;
   float blendFactor[4];
   uint32 sampleMask;
} SVGA3dCmdDXSetBlendState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetDepthStencilState {
   SVGA3dDepthStencilStateId depthStencilId;
   uint32 stencilRef;
} SVGA3dCmdDXSetDepthStencilState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetRasterizerState {
   SVGA3dRasterizerStateId rasterizerId;
} SVGA3dCmdDXSetRasterizerState;
#pragma pack(pop)

#define SVGA3D_DXQUERY_FLAG_PREDICATEHINT (1 << 0)
typedef uint32 SVGA3dDXQueryFlags;

#define SVGADX_QDSTATE_INVALID  ((uint8) - 1)
#define SVGADX_QDSTATE_MIN      0
#define SVGADX_QDSTATE_IDLE     0
#define SVGADX_QDSTATE_ACTIVE   1
#define SVGADX_QDSTATE_PENDING  2
#define SVGADX_QDSTATE_FINISHED 3
#define SVGADX_QDSTATE_MAX      4
typedef uint8 SVGADXQueryDeviceState;

#pragma pack(push, 1)
typedef struct {
   SVGA3dQueryTypeUint8 type;
   uint16 pad0;
   SVGADXQueryDeviceState state;
   SVGA3dDXQueryFlags flags;
   SVGAMobId mobid;
   uint32 offset;
} SVGACOTableDXQueryEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineQuery {
   SVGA3dQueryId queryId;
   SVGA3dQueryType type;
   SVGA3dDXQueryFlags flags;
} SVGA3dCmdDXDefineQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyQuery {
   SVGA3dQueryId queryId;
} SVGA3dCmdDXDestroyQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindQuery {
   SVGA3dQueryId queryId;
   SVGAMobId mobid;
} SVGA3dCmdDXBindQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetQueryOffset {
   SVGA3dQueryId queryId;
   uint32 mobOffset;
} SVGA3dCmdDXSetQueryOffset;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBeginQuery {
   SVGA3dQueryId queryId;
} SVGA3dCmdDXBeginQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXEndQuery {
   SVGA3dQueryId queryId;
} SVGA3dCmdDXEndQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXReadbackQuery {
   SVGA3dQueryId queryId;
} SVGA3dCmdDXReadbackQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXMoveQuery {
   SVGA3dQueryId queryId;
   SVGAMobId mobid;
   uint32 mobOffset;
} SVGA3dCmdDXMoveQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindAllQuery {
   uint32 cid;
   SVGAMobId mobid;
} SVGA3dCmdDXBindAllQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXReadbackAllQuery {
   uint32 cid;
} SVGA3dCmdDXReadbackAllQuery;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetPredication {
   SVGA3dQueryId queryId;
   uint32 predicateValue;
} SVGA3dCmdDXSetPredication;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dDXSOState {
   uint32 offset;
   uint32 intOffset;
   uint32 dead1;
   uint32 dead2;
} SVGA3dDXSOState;
#pragma pack(pop)

#define SVGA3D_DX_SO_OFFSET_APPEND ((uint32)~0u)

#pragma pack(push, 1)
typedef struct SVGA3dSoTarget {
   SVGA3dSurfaceId sid;
   uint32 offset;
   uint32 sizeInBytes;
} SVGA3dSoTarget;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetSOTargets {
   uint32 pad0;

} SVGA3dCmdDXSetSOTargets;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dViewport {
   float x;
   float y;
   float width;
   float height;
   float minDepth;
   float maxDepth;
} SVGA3dViewport;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetViewports {
   uint32 pad0;

} SVGA3dCmdDXSetViewports;
#pragma pack(pop)

#define SVGA3D_DX_MAX_VIEWPORTS 16

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetScissorRects {
   uint32 pad0;

} SVGA3dCmdDXSetScissorRects;
#pragma pack(pop)

#define SVGA3D_DX_MAX_SCISSORRECTS 16

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXClearRenderTargetView {
   SVGA3dRenderTargetViewId renderTargetViewId;
   SVGA3dRGBAFloat rgba;
} SVGA3dCmdDXClearRenderTargetView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXClearDepthStencilView {
   uint16 flags;
   uint16 stencil;
   SVGA3dDepthStencilViewId depthStencilViewId;
   float depth;
} SVGA3dCmdDXClearDepthStencilView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredCopyRegion {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dCopyBox box;
} SVGA3dCmdDXPredCopyRegion;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredStagingCopyRegion {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dCopyBox box;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];
} SVGA3dCmdDXPredStagingCopyRegion;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredCopy {
   SVGA3dSurfaceId dstSid;
   SVGA3dSurfaceId srcSid;
} SVGA3dCmdDXPredCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredConvertRegion {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dBox destBox;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dBox srcBox;
} SVGA3dCmdDXPredConvertRegion;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredStagingConvertRegion {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dBox destBox;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dBox srcBox;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];
} SVGA3dCmdDXPredStagingConvertRegion;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredConvert {
   SVGA3dSurfaceId dstSid;
   SVGA3dSurfaceId srcSid;
} SVGA3dCmdDXPredConvert;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredStagingConvert {
   SVGA3dSurfaceId dstSid;
   SVGA3dSurfaceId srcSid;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];
} SVGA3dCmdDXPredStagingConvert;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBufferCopy {
   SVGA3dSurfaceId dest;
   SVGA3dSurfaceId src;
   uint32 destX;
   uint32 srcX;
   uint32 width;
} SVGA3dCmdDXBufferCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXStagingBufferCopy {
   SVGA3dSurfaceId dest;
   SVGA3dSurfaceId src;
   uint32 destX;
   uint32 srcX;
   uint32 width;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];
} SVGA3dCmdDXStagingBufferCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dSurfaceFormat copyFormat;
} SVGA3dCmdDXResolveCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId dstSid;
   uint32 dstSubResource;
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dSurfaceFormat copyFormat;
} SVGA3dCmdDXPredResolveCopy;
#pragma pack(pop)

typedef uint32 SVGA3dDXPresentBltMode;
#define SVGADX_PRESENTBLT_LINEAR           (1 << 0)
#define SVGADX_PRESENTBLT_FORCE_SRC_SRGB   (1 << 1)
#define SVGADX_PRESENTBLT_FORCE_SRC_XRBIAS (1 << 2)
#define SVGADX_PRESENTBLT_MODE_MAX         (1 << 3)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPresentBlt {
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dSurfaceId dstSid;
   uint32 destSubResource;
   SVGA3dBox boxSrc;
   SVGA3dBox boxDest;
   SVGA3dDXPresentBltMode mode;
} SVGA3dCmdDXPresentBlt;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXGenMips {
   SVGA3dShaderResourceViewId shaderResourceViewId;
} SVGA3dCmdDXGenMips;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXUpdateSubResource {
   SVGA3dSurfaceId sid;
   uint32 subResource;
   SVGA3dBox box;
} SVGA3dCmdDXUpdateSubResource;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXReadbackSubResource {
   SVGA3dSurfaceId sid;
   uint32 subResource;
} SVGA3dCmdDXReadbackSubResource;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXInvalidateSubResource {
   SVGA3dSurfaceId sid;
   uint32 subResource;
} SVGA3dCmdDXInvalidateSubResource;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXTransferFromBuffer {
   SVGA3dSurfaceId srcSid;
   uint32 srcOffset;
   uint32 srcPitch;
   uint32 srcSlicePitch;
   SVGA3dSurfaceId destSid;
   uint32 destSubResource;
   SVGA3dBox destBox;
} SVGA3dCmdDXTransferFromBuffer;
#pragma pack(pop)

#define SVGA3D_TRANSFER_TO_BUFFER_READBACK   (1 << 0)
#define SVGA3D_TRANSFER_TO_BUFFER_FLAGS_MASK (1 << 0)
typedef uint32 SVGA3dTransferToBufferFlags;

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXTransferToBuffer {
   SVGA3dSurfaceId srcSid;
   uint32 srcSubResource;
   SVGA3dBox srcBox;
   SVGA3dSurfaceId destSid;
   uint32 destOffset;
   uint32 destPitch;
   uint32 destSlicePitch;
   SVGA3dTransferToBufferFlags flags;
} SVGA3dCmdDXTransferToBuffer;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredTransferFromBuffer {
   SVGA3dSurfaceId srcSid;
   uint32 srcOffset;
   uint32 srcPitch;
   uint32 srcSlicePitch;
   SVGA3dSurfaceId destSid;
   uint32 destSubResource;
   SVGA3dBox destBox;
} SVGA3dCmdDXPredTransferFromBuffer;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSurfaceCopyAndReadback {
   SVGA3dSurfaceId srcSid;
   SVGA3dSurfaceId destSid;
   SVGA3dCopyBox box;
} SVGA3dCmdDXSurfaceCopyAndReadback;
#pragma pack(pop)

typedef uint32 SVGADXHintId;
#define SVGA_DX_HINT_NONE             0
#define SVGA_DX_HINT_PREFETCH_OBJECT  1
#define SVGA_DX_HINT_PREEVICT_OBJECT  2
#define SVGA_DX_HINT_PREFETCH_COBJECT 3
#define SVGA_DX_HINT_PREEVICT_COBJECT 4
#define SVGA_DX_HINT_MAX              5

#pragma pack(push, 1)
typedef struct SVGAObjectRef {
   SVGAOTableType type;
   uint32 id;
} SVGAObjectRef;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGACObjectRef {
   SVGACOTableType type;
   uint32 cid;
   uint32 id;
} SVGACObjectRef;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXHint {
   SVGADXHintId hintId;

} SVGA3dCmdDXHint;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBufferUpdate {
   SVGA3dSurfaceId sid;
   uint32 x;
   uint32 width;
} SVGA3dCmdDXBufferUpdate;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetConstantBufferOffset {
   uint32 slot;
   uint32 offsetInBytes;
} SVGA3dCmdDXSetConstantBufferOffset;
#pragma pack(pop)

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetVSConstantBufferOffset;

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetPSConstantBufferOffset;

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetGSConstantBufferOffset;

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetHSConstantBufferOffset;

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetDSConstantBufferOffset;

typedef SVGA3dCmdDXSetConstantBufferOffset SVGA3dCmdDXSetCSConstantBufferOffset;

#define SVGA3D_BUFFEREX_SRV_RAW        (1 << 0)
#define SVGA3D_BUFFEREX_SRV_FLAGS_MAX  (1 << 1)
#define SVGA3D_BUFFEREX_SRV_FLAGS_MASK (SVGA3D_BUFFEREX_SRV_FLAGS_MAX - 1)
typedef uint32 SVGA3dBufferExFlags;

#pragma pack(push, 1)
typedef struct {
   union {
      struct {
         uint32 firstElement;
         uint32 numElements;
         uint32 pad0;
         uint32 pad1;
      } buffer;
      struct {
         uint32 mostDetailedMip;
         uint32 firstArraySlice;
         uint32 mipLevels;
         uint32 arraySize;
      } tex;
      struct {
         uint32 firstElement;
         uint32 numElements;
         SVGA3dBufferExFlags flags;
         uint32 pad0;
      } bufferex;
   };
} SVGA3dShaderResourceViewDesc;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   SVGA3dShaderResourceViewDesc desc;
   uint32 pad;
} SVGACOTableDXSRViewEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineShaderResourceView {
   SVGA3dShaderResourceViewId shaderResourceViewId;

   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;

   SVGA3dShaderResourceViewDesc desc;
} SVGA3dCmdDXDefineShaderResourceView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyShaderResourceView {
   SVGA3dShaderResourceViewId shaderResourceViewId;
} SVGA3dCmdDXDestroyShaderResourceView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dRenderTargetViewDesc {
   union {
      struct {
         uint32 firstElement;
         uint32 numElements;
         uint32 padding0;
      } buffer;
      struct {
         uint32 mipSlice;
         uint32 firstArraySlice;
         uint32 arraySize;
      } tex;
      struct {
         uint32 mipSlice;
         uint32 firstW;
         uint32 wSize;
      } tex3D;
   };
} SVGA3dRenderTargetViewDesc;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   SVGA3dRenderTargetViewDesc desc;
   uint32 pad[2];
} SVGACOTableDXRTViewEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineRenderTargetView {
   SVGA3dRenderTargetViewId renderTargetViewId;

   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;

   SVGA3dRenderTargetViewDesc desc;
} SVGA3dCmdDXDefineRenderTargetView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyRenderTargetView {
   SVGA3dRenderTargetViewId renderTargetViewId;
} SVGA3dCmdDXDestroyRenderTargetView;
#pragma pack(pop)

#define SVGA3D_DXDSVIEW_CREATE_READ_ONLY_DEPTH   0x01
#define SVGA3D_DXDSVIEW_CREATE_READ_ONLY_STENCIL 0x02
#define SVGA3D_DXDSVIEW_CREATE_FLAG_MASK         0x03
typedef uint8 SVGA3DCreateDSViewFlags;

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   uint32 mipSlice;
   uint32 firstArraySlice;
   uint32 arraySize;
   SVGA3DCreateDSViewFlags flags;
   uint8 pad0;
   uint16 pad1;
   uint32 pad2;
} SVGACOTableDXDSViewEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineDepthStencilView {
   SVGA3dDepthStencilViewId depthStencilViewId;

   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   uint32 mipSlice;
   uint32 firstArraySlice;
   uint32 arraySize;
   SVGA3DCreateDSViewFlags flags;
   uint8 pad0;
   uint16 pad1;
} SVGA3dCmdDXDefineDepthStencilView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineDepthStencilView_v2 {
   SVGA3dDepthStencilViewId depthStencilViewId;

   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   uint32 mipSlice;
   uint32 firstArraySlice;
   uint32 arraySize;
   SVGA3DCreateDSViewFlags flags;
   uint8 pad0;
   uint16 pad1;
} SVGA3dCmdDXDefineDepthStencilView_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyDepthStencilView {
   SVGA3dDepthStencilViewId depthStencilViewId;
} SVGA3dCmdDXDestroyDepthStencilView;
#pragma pack(pop)

#define SVGA3D_UABUFFER_RAW     (1 << 0)
#define SVGA3D_UABUFFER_APPEND  (1 << 1)
#define SVGA3D_UABUFFER_COUNTER (1 << 2)
typedef uint32 SVGA3dUABufferFlags;

#pragma pack(push, 1)
typedef struct {
   union {
      struct {
         uint32 firstElement;
         uint32 numElements;
         SVGA3dUABufferFlags flags;
         uint32 padding0;
         uint32 padding1;
      } buffer;
      struct {
         uint32 mipSlice;
         uint32 firstArraySlice;
         uint32 arraySize;
         uint32 padding0;
         uint32 padding1;
      } tex;
      struct {
         uint32 mipSlice;
         uint32 firstW;
         uint32 wSize;
         uint32 padding0;
         uint32 padding1;
      } tex3D;
   };
} SVGA3dUAViewDesc;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;
   SVGA3dUAViewDesc desc;
   uint32 structureCount;
   uint32 pad[7];
} SVGACOTableDXUAViewEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineUAView {
   SVGA3dUAViewId uaViewId;

   SVGA3dSurfaceId sid;
   SVGA3dSurfaceFormat format;
   SVGA3dResourceType resourceDimension;

   SVGA3dUAViewDesc desc;
} SVGA3dCmdDXDefineUAView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyUAView {
   SVGA3dUAViewId uaViewId;
} SVGA3dCmdDXDestroyUAView;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXClearUAViewUint {
   SVGA3dUAViewId uaViewId;
   SVGA3dRGBAUint32 value;
} SVGA3dCmdDXClearUAViewUint;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXClearUAViewFloat {
   SVGA3dUAViewId uaViewId;
   SVGA3dRGBAFloat value;
} SVGA3dCmdDXClearUAViewFloat;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXCopyStructureCount {
   SVGA3dUAViewId srcUAViewId;
   SVGA3dSurfaceId destSid;
   uint32 destByteOffset;
} SVGA3dCmdDXCopyStructureCount;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetStructureCount {
   SVGA3dUAViewId uaViewId;
   uint32 structureCount;
} SVGA3dCmdDXSetStructureCount;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetUAViews {
   uint32 uavSpliceIndex;

} SVGA3dCmdDXSetUAViews;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetCSUAViews {
   uint32 startIndex;

} SVGA3dCmdDXSetCSUAViews;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dInputElementDesc {
   uint32 inputSlot;
   uint32 alignedByteOffset;
   SVGA3dSurfaceFormat format;
   SVGA3dInputClassification inputSlotClass;
   uint32 instanceDataStepRate;
   uint32 inputRegister;
} SVGA3dInputElementDesc;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint32 elid;
   uint32 numDescs;
   SVGA3dInputElementDesc descs[32];
   uint32 pad[62];
} SVGACOTableDXElementLayoutEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineElementLayout {
   SVGA3dElementLayoutId elementLayoutId;

} SVGA3dCmdDXDefineElementLayout;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyElementLayout {
   SVGA3dElementLayoutId elementLayoutId;
} SVGA3dCmdDXDestroyElementLayout;
#pragma pack(pop)

#define SVGA3D_DX_MAX_RENDER_TARGETS 8

#pragma pack(push, 1)
typedef struct SVGA3dDXBlendStatePerRT {
   uint8 blendEnable;
   uint8 srcBlend;
   uint8 destBlend;
   uint8 blendOp;
   uint8 srcBlendAlpha;
   uint8 destBlendAlpha;
   uint8 blendOpAlpha;
   SVGA3dColorWriteEnable renderTargetWriteMask;
   uint8 logicOpEnable;
   uint8 logicOp;
   uint16 pad0;
} SVGA3dDXBlendStatePerRT;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint8 alphaToCoverageEnable;
   uint8 independentBlendEnable;
   uint16 pad0;
   SVGA3dDXBlendStatePerRT perRT[SVGA3D_DX_MAX_RENDER_TARGETS];
   uint32 pad1[7];
} SVGACOTableDXBlendStateEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineBlendState {
   SVGA3dBlendStateId blendId;
   uint8 alphaToCoverageEnable;
   uint8 independentBlendEnable;
   uint16 pad0;
   SVGA3dDXBlendStatePerRT perRT[SVGA3D_DX_MAX_RENDER_TARGETS];
} SVGA3dCmdDXDefineBlendState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyBlendState {
   SVGA3dBlendStateId blendId;
} SVGA3dCmdDXDestroyBlendState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint8 depthEnable;
   SVGA3dDepthWriteMask depthWriteMask;
   SVGA3dComparisonFunc depthFunc;
   uint8 stencilEnable;
   uint8 frontEnable;
   uint8 backEnable;
   uint8 stencilReadMask;
   uint8 stencilWriteMask;

   uint8 frontStencilFailOp;
   uint8 frontStencilDepthFailOp;
   uint8 frontStencilPassOp;
   SVGA3dComparisonFunc frontStencilFunc;

   uint8 backStencilFailOp;
   uint8 backStencilDepthFailOp;
   uint8 backStencilPassOp;
   SVGA3dComparisonFunc backStencilFunc;
} SVGACOTableDXDepthStencilEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineDepthStencilState {
   SVGA3dDepthStencilStateId depthStencilId;

   uint8 depthEnable;
   SVGA3dDepthWriteMask depthWriteMask;
   SVGA3dComparisonFunc depthFunc;
   uint8 stencilEnable;
   uint8 frontEnable;
   uint8 backEnable;
   uint8 stencilReadMask;
   uint8 stencilWriteMask;

   uint8 frontStencilFailOp;
   uint8 frontStencilDepthFailOp;
   uint8 frontStencilPassOp;
   SVGA3dComparisonFunc frontStencilFunc;

   uint8 backStencilFailOp;
   uint8 backStencilDepthFailOp;
   uint8 backStencilPassOp;
   SVGA3dComparisonFunc backStencilFunc;
} SVGA3dCmdDXDefineDepthStencilState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyDepthStencilState {
   SVGA3dDepthStencilStateId depthStencilId;
} SVGA3dCmdDXDestroyDepthStencilState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint8 fillMode;
   SVGA3dCullMode cullMode;
   uint8 frontCounterClockwise;
   uint8 provokingVertexLast;
   int32 depthBias;
   float depthBiasClamp;
   float slopeScaledDepthBias;
   uint8 depthClipEnable;
   uint8 scissorEnable;
   SVGA3dMultisampleRastEnable multisampleEnable;
   uint8 antialiasedLineEnable;
   float lineWidth;
   uint8 lineStippleEnable;
   uint8 lineStippleFactor;
   uint16 lineStipplePattern;
   uint8 forcedSampleCount;
   uint8 mustBeZero[3];
} SVGACOTableDXRasterizerStateEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineRasterizerState {
   SVGA3dRasterizerStateId rasterizerId;

   uint8 fillMode;
   SVGA3dCullMode cullMode;
   uint8 frontCounterClockwise;
   uint8 provokingVertexLast;
   int32 depthBias;
   float depthBiasClamp;
   float slopeScaledDepthBias;
   uint8 depthClipEnable;
   uint8 scissorEnable;
   SVGA3dMultisampleRastEnable multisampleEnable;
   uint8 antialiasedLineEnable;
   float lineWidth;
   uint8 lineStippleEnable;
   uint8 lineStippleFactor;
   uint16 lineStipplePattern;
} SVGA3dCmdDXDefineRasterizerState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineRasterizerState_v2 {
   SVGA3dRasterizerStateId rasterizerId;

   uint8 fillMode;
   SVGA3dCullMode cullMode;
   uint8 frontCounterClockwise;
   uint8 provokingVertexLast;
   int32 depthBias;
   float depthBiasClamp;
   float slopeScaledDepthBias;
   uint8 depthClipEnable;
   uint8 scissorEnable;
   SVGA3dMultisampleRastEnable multisampleEnable;
   uint8 antialiasedLineEnable;
   float lineWidth;
   uint8 lineStippleEnable;
   uint8 lineStippleFactor;
   uint16 lineStipplePattern;
   uint32 forcedSampleCount;
} SVGA3dCmdDXDefineRasterizerState_v2;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyRasterizerState {
   SVGA3dRasterizerStateId rasterizerId;
} SVGA3dCmdDXDestroyRasterizerState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   SVGA3dFilter filter;
   uint8 addressU;
   uint8 addressV;
   uint8 addressW;
   uint8 pad0;
   float mipLODBias;
   uint8 maxAnisotropy;
   SVGA3dComparisonFunc comparisonFunc;
   uint16 pad1;
   SVGA3dRGBAFloat borderColor;
   float minLOD;
   float maxLOD;
   uint32 pad2[6];
} SVGACOTableDXSamplerEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineSamplerState {
   SVGA3dSamplerId samplerId;
   SVGA3dFilter filter;
   uint8 addressU;
   uint8 addressV;
   uint8 addressW;
   uint8 pad0;
   float mipLODBias;
   uint8 maxAnisotropy;
   SVGA3dComparisonFunc comparisonFunc;
   uint16 pad1;
   SVGA3dRGBAFloat borderColor;
   float minLOD;
   float maxLOD;
} SVGA3dCmdDXDefineSamplerState;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroySamplerState {
   SVGA3dSamplerId samplerId;
} SVGA3dCmdDXDestroySamplerState;
#pragma pack(pop)

#define SVGADX_SIGNATURE_SEMANTIC_NAME_UNDEFINED                         0
#define SVGADX_SIGNATURE_SEMANTIC_NAME_POSITION                          1
#define SVGADX_SIGNATURE_SEMANTIC_NAME_CLIP_DISTANCE                     2
#define SVGADX_SIGNATURE_SEMANTIC_NAME_CULL_DISTANCE                     3
#define SVGADX_SIGNATURE_SEMANTIC_NAME_RENDER_TARGET_ARRAY_INDEX         4
#define SVGADX_SIGNATURE_SEMANTIC_NAME_VIEWPORT_ARRAY_INDEX              5
#define SVGADX_SIGNATURE_SEMANTIC_NAME_VERTEX_ID                         6
#define SVGADX_SIGNATURE_SEMANTIC_NAME_PRIMITIVE_ID                      7
#define SVGADX_SIGNATURE_SEMANTIC_NAME_INSTANCE_ID                       8
#define SVGADX_SIGNATURE_SEMANTIC_NAME_IS_FRONT_FACE                     9
#define SVGADX_SIGNATURE_SEMANTIC_NAME_SAMPLE_INDEX                      10
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_EQ_0_EDGE_TESSFACTOR 11
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_EQ_0_EDGE_TESSFACTOR 12
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_EQ_1_EDGE_TESSFACTOR 13
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_EQ_1_EDGE_TESSFACTOR 14
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_U_INSIDE_TESSFACTOR    15
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_QUAD_V_INSIDE_TESSFACTOR    16
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_U_EQ_0_EDGE_TESSFACTOR  17
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_V_EQ_0_EDGE_TESSFACTOR  18
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_W_EQ_0_EDGE_TESSFACTOR  19
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_TRI_INSIDE_TESSFACTOR       20
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_LINE_DETAIL_TESSFACTOR      21
#define SVGADX_SIGNATURE_SEMANTIC_NAME_FINAL_LINE_DENSITY_TESSFACTOR     22
#define SVGADX_SIGNATURE_SEMANTIC_NAME_MAX                               23
typedef uint32 SVGA3dDXSignatureSemanticName;

#define SVGADX_SIGNATURE_REGISTER_COMPONENT_UNKNOWN 0
#define SVGADX_SIGNATURE_REGISTER_COMPONENT_UINT32  1
#define SVGADX_SIGNATURE_REGISTER_COMPONENT_INT32   2
#define SVGADX_SIGNATURE_REGISTER_COMPONENT_FLOAT   3
typedef uint32 SVGA3dDXSignatureRegisterComponentType;

#define SVGADX_SIGNATURE_MIN_PRECISION_DEFAULT 0
typedef uint32 SVGA3dDXSignatureMinPrecision;

#pragma pack(push, 1)
typedef struct SVGA3dDXSignatureEntry {
   uint32 registerIndex;
   SVGA3dDXSignatureSemanticName semanticName;
   uint32 mask;
   SVGA3dDXSignatureRegisterComponentType componentType;
   SVGA3dDXSignatureMinPrecision minPrecision;
} SVGA3dDXShaderSignatureEntry;
#pragma pack(pop)

#define SVGADX_SIGNATURE_HEADER_VERSION_0 0x08a92d12

#pragma pack(push, 1)
typedef struct SVGA3dDXSignatureHeader {
   uint32 headerVersion;
   uint32 numInputSignatures;
   uint32 numOutputSignatures;
   uint32 numPatchConstantSignatures;
} SVGA3dDXShaderSignatureHeader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineShader {
   SVGA3dShaderId shaderId;
   SVGA3dShaderType type;
   uint32 sizeInBytes;
} SVGA3dCmdDXDefineShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGACOTableDXShaderEntry {
   SVGA3dShaderType type;
   uint32 sizeInBytes;
   uint32 offsetInBytes;
   SVGAMobId mobid;
   uint32 pad[4];
} SVGACOTableDXShaderEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyShader {
   SVGA3dShaderId shaderId;
} SVGA3dCmdDXDestroyShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindShader {
   uint32 cid;
   uint32 shid;
   SVGAMobId mobid;
   uint32 offsetInBytes;
} SVGA3dCmdDXBindShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindAllShader {
   uint32 cid;
   SVGAMobId mobid;
} SVGA3dCmdDXBindAllShader;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXCondBindAllShader {
   uint32 cid;
   SVGAMobId testMobid;
   SVGAMobId mobid;
} SVGA3dCmdDXCondBindAllShader;
#pragma pack(pop)

#define SVGA3D_MAX_DX10_STREAMOUT_DECLS 64
#define SVGA3D_MAX_STREAMOUT_DECLS      512

#pragma pack(push, 1)
typedef struct SVGA3dStreamOutputDeclarationEntry {
   uint32 outputSlot;
   uint32 registerIndex;
   uint8 registerMask;
   uint8 pad0;
   uint16 pad1;
   uint32 stream;
} SVGA3dStreamOutputDeclarationEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGAOTableStreamOutputEntry {
   uint32 numOutputStreamEntries;
   SVGA3dStreamOutputDeclarationEntry decl[SVGA3D_MAX_DX10_STREAMOUT_DECLS];
   uint32 streamOutputStrideInBytes[SVGA3D_DX_MAX_SOTARGETS];
   uint32 rasterizedStream;
   uint32 numOutputStreamStrides;
   uint32 mobid;
   uint32 offsetInBytes;
   uint8 usesMob;
   uint8 pad0;
   uint16 pad1;
   uint32 pad2[246];
} SVGACOTableDXStreamOutputEntry;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineStreamOutput {
   SVGA3dStreamOutputId soid;
   uint32 numOutputStreamEntries;
   SVGA3dStreamOutputDeclarationEntry decl[SVGA3D_MAX_DX10_STREAMOUT_DECLS];
   uint32 streamOutputStrideInBytes[SVGA3D_DX_MAX_SOTARGETS];
   uint32 rasterizedStream;
} SVGA3dCmdDXDefineStreamOutput;
#pragma pack(pop)

#define SVGA3D_DX_SO_NO_RASTERIZED_STREAM 0xFFFFFFFF

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDefineStreamOutputWithMob {
   SVGA3dStreamOutputId soid;
   uint32 numOutputStreamEntries;
   uint32 numOutputStreamStrides;
   uint32 streamOutputStrideInBytes[SVGA3D_DX_MAX_SOTARGETS];
   uint32 rasterizedStream;
} SVGA3dCmdDXDefineStreamOutputWithMob;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXBindStreamOutput {
   SVGA3dStreamOutputId soid;
   uint32 mobid;
   uint32 offsetInBytes;
   uint32 sizeInBytes;
} SVGA3dCmdDXBindStreamOutput;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXDestroyStreamOutput {
   SVGA3dStreamOutputId soid;
} SVGA3dCmdDXDestroyStreamOutput;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetStreamOutput {
   SVGA3dStreamOutputId soid;
} SVGA3dCmdDXSetStreamOutput;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetMinLOD {
   SVGA3dSurfaceId sid;
   float minLOD;
} SVGA3dCmdDXSetMinLOD;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct {
   uint64 value;
   uint32 mobId;
   uint32 mobOffset;
} SVGA3dCmdDXMobFence64;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXSetCOTable {
   uint32 cid;
   uint32 mobid;
   SVGACOTableType type;
   uint32 validSizeInBytes;
} SVGA3dCmdDXSetCOTable;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXGrowCOTable {
   uint32 cid;
   uint32 mobid;
   SVGACOTableType type;
   uint32 validSizeInBytes;
} SVGA3dCmdDXGrowCOTable;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXReadbackCOTable {
   uint32 cid;
   SVGACOTableType type;
} SVGA3dCmdDXReadbackCOTable;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXCopyCOTableIntoMob {
   uint32 cid;
   SVGACOTableType type;
   uint32 mobid;
} SVGA3dCmdDXCopyCOTableIntoMob;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXPredStagingCopy {
   SVGA3dSurfaceId dstSid;
   SVGA3dSurfaceId srcSid;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];

} SVGA3dCmdDXPredStagingCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCmdDXStagingCopy {
   SVGA3dSurfaceId dstSid;
   SVGA3dSurfaceId srcSid;
   uint8 readback;
   uint8 unsynchronized;
   uint8 mustBeZero[2];

} SVGA3dCmdDXStagingCopy;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dCOTableData {
   uint32 mobid;
} SVGA3dCOTableData;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dBufferBinding {
   uint32 bufferId;
   uint32 stride;
   uint32 offset;
} SVGA3dBufferBinding;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGA3dConstantBufferBinding {
   uint32 sid;
   uint32 offsetInBytes;
   uint32 sizeInBytes;
} SVGA3dConstantBufferBinding;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGADXInputAssemblyMobFormat {
   uint32 layoutId;
   SVGA3dBufferBinding vertexBuffers[SVGA3D_DX_MAX_VERTEXBUFFERS];
   uint32 indexBufferSid;
   uint32 pad;
   uint32 indexBufferOffset;
   uint32 indexBufferFormat;
   uint32 topology;
} SVGADXInputAssemblyMobFormat;
#pragma pack(pop)

#pragma pack(push, 1)
typedef struct SVGADXContextMobFormat {
   SVGADXInputAssemblyMobFormat inputAssembly;

   struct {
      uint32 blendStateId;
      uint32 blendFactor[4];
      uint32 sampleMask;
      uint32 depthStencilStateId;
      uint32 stencilRef;
      uint32 rasterizerStateId;
      uint32 depthStencilViewId;
      uint32 renderTargetViewIds[SVGA3D_DX_MAX_RENDER_TARGETS];
   } renderState;

   uint32 pad0[8];

   struct {
      uint32 targets[SVGA3D_DX_MAX_SOTARGETS];
      uint32 soid;
   } streamOut;

   uint32 pad1[10];

   uint32 uavSpliceIndex;

   uint8 numViewports;
   uint8 numScissorRects;
   uint16 pad2[1];

   uint32 pad3[3];

   SVGA3dViewport viewports[SVGA3D_DX_MAX_VIEWPORTS];
   uint32 pad4[32];

   SVGASignedRect scissorRects[SVGA3D_DX_MAX_SCISSORRECTS];
   uint32 pad5[64];

   struct {
      uint32 queryID;
      uint32 value;
   } predication;

   SVGAMobId shaderIfaceMobid;
   uint32 shaderIfaceOffset;
   struct {
      uint32 shaderId;
      SVGA3dConstantBufferBinding constantBuffers[SVGA3D_DX_MAX_CONSTBUFFERS];
      uint32 shaderResources[SVGA3D_DX_MAX_SRVIEWS];
      uint32 samplers[SVGA3D_DX_MAX_SAMPLERS];
   } shaderState[SVGA3D_NUM_SHADERTYPE];
   uint32 pad6[26];

   SVGA3dQueryId queryID[SVGA3D_MAX_QUERY];

   SVGA3dCOTableData cotables[SVGA_COTABLE_MAX];

   uint32 pad7[64];

   uint32 uaViewIds[SVGA3D_DX11_1_MAX_UAVIEWS];
   uint32 csuaViewIds[SVGA3D_DX11_1_MAX_UAVIEWS];

   uint32 pad8[188];
} SVGADXContextMobFormat;
#pragma pack(pop)

#define SVGA3D_DX_MAX_CLASS_INSTANCES_PADDED 256

#pragma pack(push, 1)
typedef struct SVGADXShaderIfaceMobFormat {
   struct {
      uint32 numClassInstances;
      uint32 iface[SVGA3D_DX_MAX_CLASS_INSTANCES_PADDED];
      SVGA3dIfaceData data[SVGA3D_DX_MAX_CLASS_INSTANCES_PADDED];
   } shaderIfaceState[SVGA3D_NUM_SHADERTYPE];

   uint32 pad0[1018];
} SVGADXShaderIfaceMobFormat;
#pragma pack(pop)

#define SVGA_MOB_FENCE_FLAG_IRQ (1 << 0)
#define SVGA_MOB_FENCE_MASK     (SVGA_MOB_FENCE_FLAG_IRQ)
typedef uint32 SVGAMobFenceFlags;

#pragma pack(push, 1)
typedef struct {
   uint64 value;
   uint32 mobId;
   uint32 mobOffset;
   uint32 flags;
} SVGA3dCmdDXMobFenceWithFlags;
#pragma pack(pop)

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     source/v64/third_party/vmware-svga/svga3d_limits.h                                                  0000644 0000000 0000000 00000005336 00000000000 017404  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 2012-2021 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_limits.h --
 *
 *    SVGA 3d hardware limits
 */

#ifndef _SVGA3D_LIMITS_H_
#define _SVGA3D_LIMITS_H_

#define SVGA3D_HB_MAX_CONTEXT_IDS 256
#define SVGA3D_HB_MAX_SURFACE_IDS (32 * 1024)

#define SVGA3D_DX_MAX_RENDER_TARGETS         8
#define SVGA3D_DX11_MAX_UAVIEWS              8
#define SVGA3D_DX11_1_MAX_UAVIEWS            64
#define SVGA3D_MAX_UAVIEWS                   (SVGA3D_DX11_1_MAX_UAVIEWS)
#define SVGA3D_DX11_MAX_SIMULTANEOUS_RTUAV   (SVGA3D_DX11_MAX_UAVIEWS)
#define SVGA3D_DX11_1_MAX_SIMULTANEOUS_RTUAV (SVGA3D_DX11_1_MAX_UAVIEWS)
#define SVGA3D_MAX_SIMULTANEOUS_RTUAV        (SVGA3D_MAX_UAVIEWS)

#define SVGA3D_HB_MAX_SURFACE_SIZE MBYTES_2_BYTES(128)

#define SVGA3D_MAX_SHADERIDS 5000

#define SVGA3D_MAX_SIMULTANEOUS_SHADERS 20000

#define SVGA3D_NUM_TEXTURE_UNITS 32
#define SVGA3D_NUM_LIGHTS        8

#define SVGA3D_MAX_VIDEOPROCESSOR_SAMPLERS 32

#define SVGA3D_MAX_SHADER_MEMORY_BYTES (8 * 1024 * 1024)
#define SVGA3D_MAX_SHADER_MEMORY                                               \
   (SVGA3D_MAX_SHADER_MEMORY_BYTES / sizeof(uint32))

#define SVGA3D_MAX_SHADER_THREAD_GROUPS 65535

#define SVGA3D_MAX_CLIP_PLANES 6

#define SVGA3D_MAX_TEXTURE_COORDS 8

#define SVGA3D_MAX_SURFACE_FACES 6

#define SVGA3D_SM4_MAX_SURFACE_ARRAYSIZE 512
#define SVGA3D_SM5_MAX_SURFACE_ARRAYSIZE 2048
#define SVGA3D_MAX_SURFACE_ARRAYSIZE     SVGA3D_SM5_MAX_SURFACE_ARRAYSIZE

#define SVGA3D_MAX_VERTEX_ARRAYS 32

#define SVGA3D_MAX_DRAW_PRIMITIVE_RANGES 32

#define SVGA3D_MAX_SAMPLES 8
#endif
                                                                                                                                                                                                                                                                                                  source/v64/third_party/vmware-svga/svga3d_reg.h                                                     0000644 0000000 0000000 00000003003 00000000000 016645  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 1998-2015 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_reg.h --
 *
 *    SVGA 3d hardware definitions
 */

#ifndef _SVGA3D_REG_H_
#define _SVGA3D_REG_H_

#include "svga_reg.h"

#include "svga3d_cmd.h"
#include "svga3d_devcaps.h"
#include "svga3d_dx.h"
#include "svga3d_limits.h"
#include "svga3d_types.h"

#endif
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             source/v64/third_party/vmware-svga/svga3d_shaderdefs.h                                              0000644 0000000 0000000 00000026510 00000000000 020210  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       /* SPDX-License-Identifier: GPL-2.0 OR MIT */
/*
 * Copyright (c) 2007-2020 Broadcom. All Rights Reserved. The term
 * "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

/*
 * svga3d_shaderdefs.h --
 *
 *    SVGA3D byte code format and limit definitions.
 */

#ifndef __SVGA3D_SHADER_DEFS__
#define __SVGA3D_SHADER_DEFS__

#include "svga3d_types.h"

#if defined __cplusplus
extern "C" {
#endif

#define SVGA3D_INPUTREG_MAX          16
#define SVGA3D_OUTPUTREG_MAX         12
#define SVGA3D_VERTEX_SAMPLERREG_MAX 4
#define SVGA3D_PIXEL_SAMPLERREG_MAX  16
#define SVGA3D_SAMPLERREG_MAX                                                  \
   (SVGA3D_PIXEL_SAMPLERREG_MAX + SVGA3D_VERTEX_SAMPLERREG_MAX)
#define SVGA3D_TEMPREG_MAX 32
#define SVGA3D_ADDRREG_MAX 1
#define SVGA3D_PREDREG_MAX 1

#define SVGA3D_MAX_SRC_REGS      4
#define SVGA3D_MAX_NESTING_LEVEL 32

#define SVGA3D_VS_TYPE 0xFFFE
#define SVGA3D_PS_TYPE 0xFFFF

typedef struct {
   union {
      struct {
         uint32 minor : 8;
         uint32 major : 8;
         uint32 type  : 16;
      };

      uint32 value;
   };
} SVGA3dShaderVersion;

#define SVGA3D_VS_10 ((uint32)((SVGA3D_VS_TYPE << 16) | 1 << 8))
#define SVGA3D_VS_11 ((uint32)(SVGA3D_VS_10 | 1))
#define SVGA3D_VS_20 ((uint32)((SVGA3D_VS_TYPE << 16) | 2 << 8))
#define SVGA3D_VS_21 ((uint32)(SVGA3D_VS_20 | 1))
#define SVGA3D_VS_30 ((uint32)((SVGA3D_VS_TYPE << 16) | 3 << 8))

#define SVGA3D_PS_10 ((uint32)((SVGA3D_PS_TYPE << 16) | 1 << 8))
#define SVGA3D_PS_11 ((uint32)(SVGA3D_PS_10 | 1))
#define SVGA3D_PS_12 ((uint32)(SVGA3D_PS_10 | 2))
#define SVGA3D_PS_13 ((uint32)(SVGA3D_PS_10 | 3))
#define SVGA3D_PS_14 ((uint32)(SVGA3D_PS_10 | 4))
#define SVGA3D_PS_20 ((uint32)((SVGA3D_PS_TYPE << 16) | 2 << 8))
#define SVGA3D_PS_21 ((uint32)(SVGA3D_PS_20 | 1))
#define SVGA3D_PS_30 ((uint32)((SVGA3D_PS_TYPE << 16) | 3 << 8))

typedef enum {
   SVGA3DPSVERSION_NONE = 0,
   SVGA3DPSVERSION_ENABLED = 1,
   SVGA3DPSVERSION_11 = 3,
   SVGA3DPSVERSION_12 = 5,
   SVGA3DPSVERSION_13 = 7,
   SVGA3DPSVERSION_14 = 9,
   SVGA3DPSVERSION_20 = 11,
   SVGA3DPSVERSION_30 = 13,
   SVGA3DPSVERSION_40 = 15,
   SVGA3DPSVERSION_MAX
} SVGA3dPixelShaderVersion;

typedef enum {
   SVGA3DVSVERSION_NONE = 0,
   SVGA3DVSVERSION_ENABLED = 1,
   SVGA3DVSVERSION_11 = 3,
   SVGA3DVSVERSION_20 = 5,
   SVGA3DVSVERSION_30 = 7,
   SVGA3DVSVERSION_40 = 9,
   SVGA3DVSVERSION_MAX
} SVGA3dVertexShaderVersion;

typedef enum {
   SVGA3DOP_NOP = 0,
   SVGA3DOP_MOV = 1,
   SVGA3DOP_ADD = 2,
   SVGA3DOP_SUB = 3,
   SVGA3DOP_MAD = 4,
   SVGA3DOP_MUL = 5,
   SVGA3DOP_RCP = 6,
   SVGA3DOP_RSQ = 7,
   SVGA3DOP_DP3 = 8,
   SVGA3DOP_DP4 = 9,
   SVGA3DOP_MIN = 10,
   SVGA3DOP_MAX = 11,
   SVGA3DOP_SLT = 12,
   SVGA3DOP_SGE = 13,
   SVGA3DOP_EXP = 14,
   SVGA3DOP_LOG = 15,
   SVGA3DOP_LIT = 16,
   SVGA3DOP_DST = 17,
   SVGA3DOP_LRP = 18,
   SVGA3DOP_FRC = 19,
   SVGA3DOP_M4x4 = 20,
   SVGA3DOP_M4x3 = 21,
   SVGA3DOP_M3x4 = 22,
   SVGA3DOP_M3x3 = 23,
   SVGA3DOP_M3x2 = 24,
   SVGA3DOP_CALL = 25,
   SVGA3DOP_CALLNZ = 26,
   SVGA3DOP_LOOP = 27,
   SVGA3DOP_RET = 28,
   SVGA3DOP_ENDLOOP = 29,
   SVGA3DOP_LABEL = 30,
   SVGA3DOP_DCL = 31,
   SVGA3DOP_POW = 32,
   SVGA3DOP_CRS = 33,
   SVGA3DOP_SGN = 34,
   SVGA3DOP_ABS = 35,
   SVGA3DOP_NRM = 36,
   SVGA3DOP_SINCOS = 37,
   SVGA3DOP_REP = 38,
   SVGA3DOP_ENDREP = 39,
   SVGA3DOP_IF = 40,
   SVGA3DOP_IFC = 41,
   SVGA3DOP_ELSE = 42,
   SVGA3DOP_ENDIF = 43,
   SVGA3DOP_BREAK = 44,
   SVGA3DOP_BREAKC = 45,
   SVGA3DOP_MOVA = 46,
   SVGA3DOP_DEFB = 47,
   SVGA3DOP_DEFI = 48,

   SVGA3DOP_TEXCOORD = 64,
   SVGA3DOP_TEXKILL = 65,
   SVGA3DOP_TEX = 66,
   SVGA3DOP_TEXBEM = 67,
   SVGA3DOP_TEXBEML = 68,
   SVGA3DOP_TEXREG2AR = 69,
   SVGA3DOP_TEXREG2GB = 70,
   SVGA3DOP_TEXM3x2PAD = 71,
   SVGA3DOP_TEXM3x2TEX = 72,
   SVGA3DOP_TEXM3x3PAD = 73,
   SVGA3DOP_TEXM3x3TEX = 74,
   SVGA3DOP_RESERVED0 = 75,
   SVGA3DOP_TEXM3x3SPEC = 76,
   SVGA3DOP_TEXM3x3VSPEC = 77,
   SVGA3DOP_EXPP = 78,
   SVGA3DOP_LOGP = 79,
   SVGA3DOP_CND = 80,
   SVGA3DOP_DEF = 81,
   SVGA3DOP_TEXREG2RGB = 82,
   SVGA3DOP_TEXDP3TEX = 83,
   SVGA3DOP_TEXM3x2DEPTH = 84,
   SVGA3DOP_TEXDP3 = 85,
   SVGA3DOP_TEXM3x3 = 86,
   SVGA3DOP_TEXDEPTH = 87,
   SVGA3DOP_CMP = 88,
   SVGA3DOP_BEM = 89,
   SVGA3DOP_DP2ADD = 90,
   SVGA3DOP_DSX = 91,
   SVGA3DOP_DSY = 92,
   SVGA3DOP_TEXLDD = 93,
   SVGA3DOP_SETP = 94,
   SVGA3DOP_TEXLDL = 95,
   SVGA3DOP_BREAKP = 96,
   SVGA3DOP_LAST_INST,
   SVGA3DOP_PHASE = 0xFFFD,
   SVGA3DOP_COMMENT = 0xFFFE,
   SVGA3DOP_END = 0xFFFF,
} SVGA3dShaderOpCodeType;

typedef enum {
   SVGA3DOPCONT_NONE,
   SVGA3DOPCONT_PROJECT,
   SVGA3DOPCONT_BIAS,
} SVGA3dShaderOpCodeControlFnType;

typedef enum {
   SVGA3DOPCOMP_RESERVED0 = 0,
   SVGA3DOPCOMP_GT,
   SVGA3DOPCOMP_EQ,
   SVGA3DOPCOMP_GE,
   SVGA3DOPCOMP_LT,
   SVGA3DOPCOMP_NE,
   SVGA3DOPCOMP_LE,
   SVGA3DOPCOMP_RESERVED1
} SVGA3dShaderOpCodeCompFnType;

typedef enum {
   SVGA3DREG_TEMP = 0,
   SVGA3DREG_INPUT,
   SVGA3DREG_CONST,
   SVGA3DREG_ADDR,
   SVGA3DREG_TEXTURE = 3,
   SVGA3DREG_RASTOUT,
   SVGA3DREG_ATTROUT,
   SVGA3DREG_TEXCRDOUT,
   SVGA3DREG_OUTPUT = 6,
   SVGA3DREG_CONSTINT,
   SVGA3DREG_COLOROUT,
   SVGA3DREG_DEPTHOUT,
   SVGA3DREG_SAMPLER,
   SVGA3DREG_CONST2,
   SVGA3DREG_CONST3,
   SVGA3DREG_CONST4,
   SVGA3DREG_CONSTBOOL,
   SVGA3DREG_LOOP,
   SVGA3DREG_TEMPFLOAT16,
   SVGA3DREG_MISCTYPE,
   SVGA3DREG_LABEL,
   SVGA3DREG_PREDICATE,
} SVGA3dShaderRegType;

typedef enum {
   SVGA3DRASTOUT_POSITION = 0,
   SVGA3DRASTOUT_FOG,
   SVGA3DRASTOUT_PSIZE
} SVGA3dShaderRastOutRegType;

typedef enum {
   SVGA3DMISCREG_POSITION = 0,
   SVGA3DMISCREG_FACE
} SVGA3DShaderMiscRegType;

typedef enum {
   SVGA3DSAMP_UNKNOWN = 0,
   SVGA3DSAMP_2D = 2,
   SVGA3DSAMP_CUBE,
   SVGA3DSAMP_VOLUME,
   SVGA3DSAMP_2D_SHADOW,
   SVGA3DSAMP_MAX,
} SVGA3dShaderSamplerType;

#define SVGA3DWRITEMASK_0   1
#define SVGA3DWRITEMASK_1   2
#define SVGA3DWRITEMASK_2   4
#define SVGA3DWRITEMASK_3   8
#define SVGA3DWRITEMASK_ALL 15

#define SVGA3DDSTMOD_NONE             0
#define SVGA3DDSTMOD_SATURATE         1
#define SVGA3DDSTMOD_PARTIALPRECISION 2

#define SVGA3DDSTMOD_MSAMPCENTROID 4

typedef enum {
   SVGA3DDSTSHFSCALE_X1 = 0,
   SVGA3DDSTSHFSCALE_X2 = 1,
   SVGA3DDSTSHFSCALE_X4 = 2,
   SVGA3DDSTSHFSCALE_X8 = 3,
   SVGA3DDSTSHFSCALE_D8 = 13,
   SVGA3DDSTSHFSCALE_D4 = 14,
   SVGA3DDSTSHFSCALE_D2 = 15
} SVGA3dShaderDstShfScaleType;

#define SVGA3DSWIZZLE_REPLICATEX 0x00
#define SVGA3DSWIZZLE_REPLICATEY 0x55
#define SVGA3DSWIZZLE_REPLICATEZ 0xAA
#define SVGA3DSWIZZLE_REPLICATEW 0xFF
#define SVGA3DSWIZZLE_NONE       0xE4
#define SVGA3DSWIZZLE_YZXW       0xC9
#define SVGA3DSWIZZLE_ZXYW       0xD2
#define SVGA3DSWIZZLE_WXYZ       0x1B

typedef enum {
   SVGA3DSRCMOD_NONE = 0,
   SVGA3DSRCMOD_NEG,
   SVGA3DSRCMOD_BIAS,
   SVGA3DSRCMOD_BIASNEG,
   SVGA3DSRCMOD_SIGN,
   SVGA3DSRCMOD_SIGNNEG,
   SVGA3DSRCMOD_COMP,
   SVGA3DSRCMOD_X2,
   SVGA3DSRCMOD_X2NEG,
   SVGA3DSRCMOD_DZ,
   SVGA3DSRCMOD_DW,
   SVGA3DSRCMOD_ABS,
   SVGA3DSRCMOD_ABSNEG,
   SVGA3DSRCMOD_NOT,
} SVGA3dShaderSrcModType;

typedef struct {
   union {
      struct {
         uint32 comment_op   : 16;
         uint32 comment_size : 16;
      };

      struct {
         uint32 op         : 16;
         uint32 control    : 3;
         uint32 reserved2  : 5;
         uint32 size       : 4;
         uint32 predicated : 1;
         uint32 reserved1  : 1;
         uint32 coissue    : 1;
         uint32 reserved0  : 1;
      };

      uint32 value;
   };
} SVGA3dShaderInstToken;

typedef struct {
   union {
      struct {
         uint32 num        : 11;
         uint32 type_upper : 2;
         uint32 relAddr    : 1;
         uint32 reserved1  : 2;
         uint32 mask       : 4;
         uint32 dstMod     : 4;
         uint32 shfScale   : 4;
         uint32 type_lower : 3;
         uint32 reserved0  : 1;
      };

      uint32 value;
   };
} SVGA3dShaderDestToken;

typedef struct {
   union {
      struct {
         uint32 num        : 11;
         uint32 type_upper : 2;
         uint32 relAddr    : 1;
         uint32 reserved1  : 2;
         uint32 swizzle    : 8;
         uint32 srcMod     : 4;
         uint32 type_lower : 3;
         uint32 reserved0  : 1;
      };

      uint32 value;
   };
} SVGA3dShaderSrcToken;

typedef struct {
   union {
      struct {
         union {
            struct {
               uint32 usage     : 5;
               uint32 reserved1 : 11;
               uint32 index     : 4;
               uint32 reserved0 : 12;
            };

            struct {
               uint32 reserved3 : 27;
               uint32 type      : 4;
               uint32 reserved2 : 1;
            };
         };

         SVGA3dShaderDestToken dst;
      };

      uint32 values[2];
   };
} SVGA3DOpDclArgs;

typedef struct {
   union {
      struct {
         SVGA3dShaderDestToken dst;

         union {
            float constValues[4];
            int constIValues[4];
            Bool constBValue;
         };
      };

      uint32 values[5];
   };
} SVGA3DOpDefArgs;

typedef union {
   uint32 value;
   SVGA3dShaderInstToken inst;
   SVGA3dShaderDestToken dest;
   SVGA3dShaderSrcToken src;
} SVGA3dShaderToken;

typedef struct {
   SVGA3dShaderVersion version;

} SVGA3dShaderProgram;

static const uint32 SVGA3D_INPUT_REG_POSITION_VS11 = 0;
static const uint32 SVGA3D_INPUT_REG_PSIZE_VS11 = 1;
static const uint32 SVGA3D_INPUT_REG_FOG_VS11 = 3;
static const uint32 SVGA3D_INPUT_REG_FOG_MASK_VS11 = SVGA3DWRITEMASK_3;
static const uint32 SVGA3D_INPUT_REG_COLOR_BASE_VS11 = 2;
static const uint32 SVGA3D_INPUT_REG_TEXCOORD_BASE_VS11 = 4;

static const uint32 SVGA3D_INPUT_REG_COLOR_BASE_PS11 = 0;
static const uint32 SVGA3D_INPUT_REG_TEXCOORD_BASE_PS11 = 2;
static const uint32 SVGA3D_OUTPUT_REG_DEPTH_PS11 = 0;
static const uint32 SVGA3D_OUTPUT_REG_COLOR_PS11 = 1;

static const uint32 SVGA3D_INPUT_REG_COLOR_BASE_PS20 = 0;
static const uint32 SVGA3D_INPUT_REG_COLOR_NUM_PS20 = 2;
static const uint32 SVGA3D_INPUT_REG_TEXCOORD_BASE_PS20 = 2;
static const uint32 SVGA3D_INPUT_REG_TEXCOORD_NUM_PS20 = 8;
static const uint32 SVGA3D_OUTPUT_REG_COLOR_BASE_PS20 = 1;
static const uint32 SVGA3D_OUTPUT_REG_COLOR_NUM_PS20 = 4;
static const uint32 SVGA3D_OUTPUT_REG_DEPTH_BASE_PS20 = 0;
static const uint32 SVGA3D_OUTPUT_REG_DEPTH_NUM_PS20 = 1;

static INLINE SVGA3dShaderRegType
SVGA3dShaderGetRegType(uint32 token)
{
   SVGA3dShaderSrcToken src;
   src.value = token;
   return (SVGA3dShaderRegType)(src.type_upper << 3 | src.type_lower);
}

#if defined __cplusplus
}
#endif

#endif
                                                                                                                                                                                        source/v64/third_party/vmware-svga/svga3d_surfacedefs.h                                             0000644 0000000 0000000 00000077717 00000000000 020411  0                                                                                                    ustar 00                                                                                                                                                                                                                                                       // SPDX-License-Identifier: GPL-2.0 OR MIT
/**************************************************************************
 *
 * Copyright (c) 2009-2024 Broadcom. All Rights Reserved. The term
 * “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
 *
 **************************************************************************/

#ifndef _SVGA3D_SURFACEDEFS_H_
#define _SVGA3D_SURFACEDEFS_H_

#include <stdint.h>
#include "svga3d_types.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef enum SVGA3dBlockDesc {
   SVGA3DBLOCKDESC_NONE = 0,
   SVGA3DBLOCKDESC_BLUE = 1 << 0,
   SVGA3DBLOCKDESC_W = 1 << 0,
   SVGA3DBLOCKDESC_BUMP_L = 1 << 0,
   SVGA3DBLOCKDESC_GREEN = 1 << 1,
   SVGA3DBLOCKDESC_V = 1 << 1,
   SVGA3DBLOCKDESC_RED = 1 << 2,
   SVGA3DBLOCKDESC_U = 1 << 2,
   SVGA3DBLOCKDESC_LUMINANCE = 1 << 2,
   SVGA3DBLOCKDESC_ALPHA = 1 << 3,
   SVGA3DBLOCKDESC_Q = 1 << 3,
   SVGA3DBLOCKDESC_BUFFER = 1 << 4,
   SVGA3DBLOCKDESC_COMPRESSED = 1 << 5,
   SVGA3DBLOCKDESC_FP = 1 << 6,
   SVGA3DBLOCKDESC_PLANAR_YUV = 1 << 7,
   SVGA3DBLOCKDESC_2PLANAR_YUV = 1 << 8,
   SVGA3DBLOCKDESC_3PLANAR_YUV = 1 << 9,
   SVGA3DBLOCKDESC_STENCIL = 1 << 11,
   SVGA3DBLOCKDESC_TYPELESS = 1 << 12,
   SVGA3DBLOCKDESC_SINT = 1 << 13,
   SVGA3DBLOCKDESC_UINT = 1 << 14,
   SVGA3DBLOCKDESC_NORM = 1 << 15,
   SVGA3DBLOCKDESC_SRGB = 1 << 16,
   SVGA3DBLOCKDESC_EXP = 1 << 17,
   SVGA3DBLOCKDESC_COLOR = 1 << 18,
   SVGA3DBLOCKDESC_DEPTH = 1 << 19,
   SVGA3DBLOCKDESC_BUMP = 1 << 20,
   SVGA3DBLOCKDESC_YUV_VIDEO = 1 << 21,
   SVGA3DBLOCKDESC_MIXED = 1 << 22,
   SVGA3DBLOCKDESC_CX = 1 << 23,
   SVGA3DBLOCKDESC_BC1 = 1 << 24,
   SVGA3DBLOCKDESC_BC2 = 1 << 25,
   SVGA3DBLOCKDESC_BC3 = 1 << 26,
   SVGA3DBLOCKDESC_BC4 = 1 << 27,
   SVGA3DBLOCKDESC_BC5 = 1 << 28,
   SVGA3DBLOCKDESC_BC6H = 1 << 29,
   SVGA3DBLOCKDESC_BC7 = 1 << 30,
   SVGA3DBLOCKDESC_COMPRESSED_MASK = SVGA3DBLOCKDESC_BC1 | SVGA3DBLOCKDESC_BC2 |
                                     SVGA3DBLOCKDESC_BC3 | SVGA3DBLOCKDESC_BC4 |
                                     SVGA3DBLOCKDESC_BC5 |
                                     SVGA3DBLOCKDESC_BC6H | SVGA3DBLOCKDESC_BC7,
   SVGA3DBLOCKDESC_A_UINT =
      SVGA3DBLOCKDESC_ALPHA | SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_A_UNORM = SVGA3DBLOCKDESC_A_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_R_UINT =
      SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_R_UNORM = SVGA3DBLOCKDESC_R_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_R_SINT =
      SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_R_SNORM = SVGA3DBLOCKDESC_R_SINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_G_UINT =
      SVGA3DBLOCKDESC_GREEN | SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RG_UINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                             SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RG_UNORM = SVGA3DBLOCKDESC_RG_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_RG_SINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                             SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RG_SNORM = SVGA3DBLOCKDESC_RG_SINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_RGB_UINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                              SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_UINT |
                              SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGB_SINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                              SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_SINT |
                              SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGB_UNORM = SVGA3DBLOCKDESC_RGB_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_RGB_UNORM_SRGB =
      SVGA3DBLOCKDESC_RGB_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_RGBA_UINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                               SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_ALPHA |
                               SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGBA_UNORM =
      SVGA3DBLOCKDESC_RGBA_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_RGBA_UNORM_SRGB =
      SVGA3DBLOCKDESC_RGBA_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_RGBA_SINT = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                               SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_ALPHA |
                               SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGBA_SNORM =
      SVGA3DBLOCKDESC_RGBA_SINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_RGBA_FP = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                             SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_ALPHA |
                             SVGA3DBLOCKDESC_FP | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_UV =
      SVGA3DBLOCKDESC_U | SVGA3DBLOCKDESC_V | SVGA3DBLOCKDESC_BUMP,
   SVGA3DBLOCKDESC_UVL = SVGA3DBLOCKDESC_UV | SVGA3DBLOCKDESC_BUMP_L |
                         SVGA3DBLOCKDESC_MIXED | SVGA3DBLOCKDESC_BUMP,
   SVGA3DBLOCKDESC_UVW =
      SVGA3DBLOCKDESC_UV | SVGA3DBLOCKDESC_W | SVGA3DBLOCKDESC_BUMP,
   SVGA3DBLOCKDESC_UVWA = SVGA3DBLOCKDESC_UVW | SVGA3DBLOCKDESC_ALPHA |
                          SVGA3DBLOCKDESC_MIXED | SVGA3DBLOCKDESC_BUMP,
   SVGA3DBLOCKDESC_UVWQ = SVGA3DBLOCKDESC_U | SVGA3DBLOCKDESC_V |
                          SVGA3DBLOCKDESC_W | SVGA3DBLOCKDESC_Q |
                          SVGA3DBLOCKDESC_BUMP,
   SVGA3DBLOCKDESC_L_UNORM = SVGA3DBLOCKDESC_LUMINANCE | SVGA3DBLOCKDESC_UINT |
                             SVGA3DBLOCKDESC_NORM | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_LA_UNORM = SVGA3DBLOCKDESC_LUMINANCE |
                              SVGA3DBLOCKDESC_ALPHA | SVGA3DBLOCKDESC_UINT |
                              SVGA3DBLOCKDESC_NORM | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_R_FP =
      SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_FP | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RG_FP =
      SVGA3DBLOCKDESC_R_FP | SVGA3DBLOCKDESC_GREEN | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGB_FP =
      SVGA3DBLOCKDESC_RG_FP | SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_YUV = SVGA3DBLOCKDESC_YUV_VIDEO | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_AYUV =
      SVGA3DBLOCKDESC_ALPHA | SVGA3DBLOCKDESC_YUV_VIDEO | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_RGB_EXP = SVGA3DBLOCKDESC_RED | SVGA3DBLOCKDESC_GREEN |
                             SVGA3DBLOCKDESC_BLUE | SVGA3DBLOCKDESC_EXP |
                             SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_COMP_TYPELESS =
      SVGA3DBLOCKDESC_COMPRESSED | SVGA3DBLOCKDESC_TYPELESS,
   SVGA3DBLOCKDESC_COMP_UNORM = SVGA3DBLOCKDESC_COMPRESSED |
                                SVGA3DBLOCKDESC_UINT | SVGA3DBLOCKDESC_NORM |
                                SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_COMP_SNORM = SVGA3DBLOCKDESC_COMPRESSED |
                                SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_NORM |
                                SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_COMP_UNORM_SRGB =
      SVGA3DBLOCKDESC_COMP_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_BC1_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC1 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC1_COMP_UNORM =
      SVGA3DBLOCKDESC_BC1 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC1_COMP_UNORM_SRGB =
      SVGA3DBLOCKDESC_BC1_COMP_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_BC2_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC2 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC2_COMP_UNORM =
      SVGA3DBLOCKDESC_BC2 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC2_COMP_UNORM_SRGB =
      SVGA3DBLOCKDESC_BC2_COMP_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_BC3_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC3 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC3_COMP_UNORM =
      SVGA3DBLOCKDESC_BC3 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC3_COMP_UNORM_SRGB =
      SVGA3DBLOCKDESC_BC3_COMP_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_BC4_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC4 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC4_COMP_UNORM =
      SVGA3DBLOCKDESC_BC4 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC4_COMP_SNORM =
      SVGA3DBLOCKDESC_BC4 | SVGA3DBLOCKDESC_COMP_SNORM,
   SVGA3DBLOCKDESC_BC5_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC5 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC5_COMP_UNORM =
      SVGA3DBLOCKDESC_BC5 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC5_COMP_SNORM =
      SVGA3DBLOCKDESC_BC5 | SVGA3DBLOCKDESC_COMP_SNORM,
   SVGA3DBLOCKDESC_BC6H_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC6H | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC6H_COMP_UF16 =
      SVGA3DBLOCKDESC_BC6H | SVGA3DBLOCKDESC_COMPRESSED,
   SVGA3DBLOCKDESC_BC6H_COMP_SF16 =
      SVGA3DBLOCKDESC_BC6H | SVGA3DBLOCKDESC_COMPRESSED,
   SVGA3DBLOCKDESC_BC7_COMP_TYPELESS =
      SVGA3DBLOCKDESC_BC7 | SVGA3DBLOCKDESC_COMP_TYPELESS,
   SVGA3DBLOCKDESC_BC7_COMP_UNORM =
      SVGA3DBLOCKDESC_BC7 | SVGA3DBLOCKDESC_COMP_UNORM,
   SVGA3DBLOCKDESC_BC7_COMP_UNORM_SRGB =
      SVGA3DBLOCKDESC_BC7_COMP_UNORM | SVGA3DBLOCKDESC_SRGB,
   SVGA3DBLOCKDESC_NV12 = SVGA3DBLOCKDESC_YUV_VIDEO |
                          SVGA3DBLOCKDESC_PLANAR_YUV |
                          SVGA3DBLOCKDESC_2PLANAR_YUV | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_YV12 = SVGA3DBLOCKDESC_YUV_VIDEO |
                          SVGA3DBLOCKDESC_PLANAR_YUV |
                          SVGA3DBLOCKDESC_3PLANAR_YUV | SVGA3DBLOCKDESC_COLOR,
   SVGA3DBLOCKDESC_DEPTH_UINT = SVGA3DBLOCKDESC_DEPTH | SVGA3DBLOCKDESC_UINT,
   SVGA3DBLOCKDESC_DEPTH_UNORM =
      SVGA3DBLOCKDESC_DEPTH_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_DS = SVGA3DBLOCKDESC_DEPTH | SVGA3DBLOCKDESC_STENCIL,
   SVGA3DBLOCKDESC_DS_UINT =
      SVGA3DBLOCKDESC_DEPTH | SVGA3DBLOCKDESC_STENCIL | SVGA3DBLOCKDESC_UINT,
   SVGA3DBLOCKDESC_DS_UNORM = SVGA3DBLOCKDESC_DS_UINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_DEPTH_FP = SVGA3DBLOCKDESC_DEPTH | SVGA3DBLOCKDESC_FP,
   SVGA3DBLOCKDESC_UV_UINT = SVGA3DBLOCKDESC_UV | SVGA3DBLOCKDESC_UINT,
   SVGA3DBLOCKDESC_UV_SNORM =
      SVGA3DBLOCKDESC_UV | SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_NORM,
   SVGA3DBLOCKDESC_UVCX_SNORM = SVGA3DBLOCKDESC_UV_SNORM | SVGA3DBLOCKDESC_CX,
   SVGA3DBLOCKDESC_UVWQ_SNORM =
      SVGA3DBLOCKDESC_UVWQ | SVGA3DBLOCKDESC_SINT | SVGA3DBLOCKDESC_NORM,
} SVGA3dBlockDesc;

typedef struct SVGA3dChannelDef {
   union {
      uint8_t blue;
      uint8_t w_bump;
      uint8_t l_bump;
      uint8_t uv_video;
      uint8_t u_video;
   };
   union {
      uint8_t green;
      uint8_t stencil;
      uint8_t v_bump;
      uint8_t v_video;
   };
   union {
      uint8_t red;
      uint8_t u_bump;
      uint8_t luminance;
      uint8_t y_video;
      uint8_t depth;
      uint8_t data;
   };
   union {
      uint8_t alpha;
      uint8_t q_bump;
      uint8_t exp;
   };
} SVGA3dChannelDef;

typedef struct SVGA3dSurfaceDesc {
   SVGA3dSurfaceFormat format;
   SVGA3dBlockDesc blockDesc;
   SVGA3dSize blockSize;
   uint32_t bytesPerBlock;
   uint32_t pitchBytesPerBlock;
   SVGA3dChannelDef bitDepth;
   SVGA3dChannelDef bitOffset;
} SVGA3dSurfaceDesc;

static const SVGA3dSurfaceDesc g_SVGA3dSurfaceDescs[SVGA3D_FORMAT_MAX] = {
   {SVGA3D_FORMAT_INVALID,
    SVGA3DBLOCKDESC_NONE,
    {1, 1, 1},
    0,
    0,
    {{0}, {0}, {0}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_X8R8G8B8,
    SVGA3DBLOCKDESC_RGB_UNORM,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {0}},
    {{0}, {8}, {16}, {24}}},
   {SVGA3D_A8R8G8B8,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{0}, {8}, {16}, {24}}},
   {SVGA3D_R5G6B5,
    SVGA3DBLOCKDESC_RGB_UNORM,
    {1, 1, 1},
    2,
    2,
    {{5}, {6}, {5}, {0}},
    {{0}, {5}, {11}, {0}}},
   {SVGA3D_X1R5G5B5,
    SVGA3DBLOCKDESC_RGB_UNORM,
    {1, 1, 1},
    2,
    2,
    {{5}, {5}, {5}, {0}},
    {{0}, {5}, {10}, {0}}},
   {SVGA3D_A1R5G5B5,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    2,
    2,
    {{5}, {5}, {5}, {1}},
    {{0}, {5}, {10}, {15}}},
   {SVGA3D_A4R4G4B4,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    2,
    2,
    {{4}, {4}, {4}, {4}},
    {{0}, {4}, {8}, {12}}},
   {SVGA3D_Z_D32,
    SVGA3DBLOCKDESC_DEPTH_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_Z_D16,
    SVGA3DBLOCKDESC_DEPTH_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {16}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_Z_D24S8,
    SVGA3DBLOCKDESC_DS_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {8}, {24}, {0}},
    {{0}, {0}, {8}, {0}}},
   {SVGA3D_Z_D15S1,
    SVGA3DBLOCKDESC_DS_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {1}, {15}, {0}},
    {{0}, {0}, {1}, {0}}},
   {SVGA3D_LUMINANCE8,
    SVGA3DBLOCKDESC_L_UNORM,
    {1, 1, 1},
    1,
    1,
    {{0}, {0}, {8}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_LUMINANCE4_ALPHA4,
    SVGA3DBLOCKDESC_LA_UNORM,
    {1, 1, 1},
    1,
    1,
    {{0}, {0}, {4}, {4}},
    {{0}, {0}, {0}, {4}}},
   {SVGA3D_LUMINANCE16,
    SVGA3DBLOCKDESC_L_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {16}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_LUMINANCE8_ALPHA8,
    SVGA3DBLOCKDESC_LA_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {8}, {8}},
    {{0}, {0}, {0}, {8}}},
   {SVGA3D_DXT1,
    SVGA3DBLOCKDESC_BC1_COMP_UNORM,
    {4, 4, 1},
    8,
    8,
    {{0}, {0}, {64}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_DXT2,
    SVGA3DBLOCKDESC_BC2_COMP_UNORM,
    {4, 4, 1},
    16,
    16,
    {{0}, {0}, {128}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_DXT3,
    SVGA3DBLOCKDESC_BC2_COMP_UNORM,
    {4, 4, 1},
    16,
    16,
    {{0}, {0}, {128}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_DXT4,
    SVGA3DBLOCKDESC_BC3_COMP_UNORM,
    {4, 4, 1},
    16,
    16,
    {{0}, {0}, {128}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_DXT5,
    SVGA3DBLOCKDESC_BC3_COMP_UNORM,
    {4, 4, 1},
    16,
    16,
    {{0}, {0}, {128}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_BUMPU8V8,
    SVGA3DBLOCKDESC_UV_SNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_BUMPL6V5U5,
    SVGA3DBLOCKDESC_UVL,
    {1, 1, 1},
    2,
    2,
    {{6}, {5}, {5}, {0}},
    {{10}, {5}, {0}, {0}}},
   {SVGA3D_BUMPX8L8V8U8,
    SVGA3DBLOCKDESC_UVL,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {0}},
    {{16}, {8}, {0}, {0}}},
   {SVGA3D_FORMAT_DEAD1,
    SVGA3DBLOCKDESC_NONE,
    {1, 1, 1},
    3,
    3,
    {{8}, {8}, {8}, {0}},
    {{16}, {8}, {0}, {0}}},
   {SVGA3D_ARGB_S10E5,
    SVGA3DBLOCKDESC_RGBA_FP,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_ARGB_S23E8,
    SVGA3DBLOCKDESC_RGBA_FP,
    {1, 1, 1},
    16,
    16,
    {{32}, {32}, {32}, {32}},
    {{64}, {32}, {0}, {96}}},
   {SVGA3D_A2R10G10B10,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    4,
    4,
    {{10}, {10}, {10}, {2}},
    {{0}, {10}, {20}, {30}}},
   {SVGA3D_V8U8,
    SVGA3DBLOCKDESC_UV_SNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_Q8W8V8U8,
    SVGA3DBLOCKDESC_UVWQ_SNORM,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_CxV8U8,
    SVGA3DBLOCKDESC_UVCX_SNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_X8L8V8U8,
    SVGA3DBLOCKDESC_UVL,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {0}},
    {{16}, {8}, {0}, {0}}},
   {SVGA3D_A2W10V10U10,
    SVGA3DBLOCKDESC_UVWA,
    {1, 1, 1},
    4,
    4,
    {{10}, {10}, {10}, {2}},
    {{20}, {10}, {0}, {30}}},
   {SVGA3D_ALPHA8,
    SVGA3DBLOCKDESC_A_UNORM,
    {1, 1, 1},
    1,
    1,
    {{0}, {0}, {0}, {8}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R_S10E5,
    SVGA3DBLOCKDESC_R_FP,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {16}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R_S23E8,
    SVGA3DBLOCKDESC_R_FP,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_RG_S10E5,
    SVGA3DBLOCKDESC_RG_FP,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_RG_S23E8,
    SVGA3DBLOCKDESC_RG_FP,
    {1, 1, 1},
    8,
    8,
    {{0}, {32}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_BUFFER,
    SVGA3DBLOCKDESC_BUFFER,
    {1, 1, 1},
    1,
    1,
    {{0}, {0}, {8}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_Z_D24X8,
    SVGA3DBLOCKDESC_DEPTH_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {24}, {0}},
    {{0}, {0}, {8}, {0}}},
   {SVGA3D_V16U16,
    SVGA3DBLOCKDESC_UV_SNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_G16R16,
    SVGA3DBLOCKDESC_RG_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_A16B16G16R16,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_UYVY,
    SVGA3DBLOCKDESC_YUV,
    {2, 1, 1},
    4,
    4,
    {{8}, {0}, {8}, {0}},
    {{0}, {0}, {8}, {0}}},
   {SVGA3D_YUY2,
    SVGA3DBLOCKDESC_YUV,
    {2, 1, 1},
    4,
    4,
    {{8}, {0}, {8}, {0}},
    {{8}, {0}, {0}, {0}}},
   {SVGA3D_NV12,
    SVGA3DBLOCKDESC_NV12,
    {2, 2, 1},
    6,
    2,
    {{0}, {0}, {48}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_FORMAT_DEAD2,
    SVGA3DBLOCKDESC_NONE,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{0}, {8}, {16}, {24}}},
   {SVGA3D_R32G32B32A32_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    16,
    16,
    {{32}, {32}, {32}, {32}},
    {{64}, {32}, {0}, {96}}},
   {SVGA3D_R32G32B32A32_UINT,
    SVGA3DBLOCKDESC_RGBA_UINT,
    {1, 1, 1},
    16,
    16,
    {{32}, {32}, {32}, {32}},
    {{64}, {32}, {0}, {96}}},
   {SVGA3D_R32G32B32A32_SINT,
    SVGA3DBLOCKDESC_RGBA_SINT,
    {1, 1, 1},
    16,
    16,
    {{32}, {32}, {32}, {32}},
    {{64}, {32}, {0}, {96}}},
   {SVGA3D_R32G32B32_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    12,
    12,
    {{32}, {32}, {32}, {0}},
    {{64}, {32}, {0}, {0}}},
   {SVGA3D_R32G32B32_FLOAT,
    SVGA3DBLOCKDESC_RGB_FP,
    {1, 1, 1},
    12,
    12,
    {{32}, {32}, {32}, {0}},
    {{64}, {32}, {0}, {0}}},
   {SVGA3D_R32G32B32_UINT,
    SVGA3DBLOCKDESC_RGB_UINT,
    {1, 1, 1},
    12,
    12,
    {{32}, {32}, {32}, {0}},
    {{64}, {32}, {0}, {0}}},
   {SVGA3D_R32G32B32_SINT,
    SVGA3DBLOCKDESC_RGB_SINT,
    {1, 1, 1},
    12,
    12,
    {{32}, {32}, {32}, {0}},
    {{64}, {32}, {0}, {0}}},
   {SVGA3D_R16G16B16A16_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_R16G16B16A16_UINT,
    SVGA3DBLOCKDESC_RGBA_UINT,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_R16G16B16A16_SNORM,
    SVGA3DBLOCKDESC_RGBA_SNORM,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_R16G16B16A16_SINT,
    SVGA3DBLOCKDESC_RGBA_SINT,
    {1, 1, 1},
    8,
    8,
    {{16}, {16}, {16}, {16}},
    {{32}, {16}, {0}, {48}}},
   {SVGA3D_R32G32_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    8,
    8,
    {{0}, {32}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_R32G32_UINT,
    SVGA3DBLOCKDESC_RG_UINT,
    {1, 1, 1},
    8,
    8,
    {{0}, {32}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_R32G32_SINT,
    SVGA3DBLOCKDESC_RG_SINT,
    {1, 1, 1},
    8,
    8,
    {{0}, {32}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_R32G8X24_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    8,
    8,
    {{0}, {8}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_D32_FLOAT_S8X24_UINT,
    SVGA3DBLOCKDESC_DS,
    {1, 1, 1},
    8,
    8,
    {{0}, {8}, {32}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_R32_FLOAT_X8X24,
    SVGA3DBLOCKDESC_R_FP,
    {1, 1, 1},
    8,
    8,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_X32_G8X24_UINT,
    SVGA3DBLOCKDESC_G_UINT,
    {1, 1, 1},
    8,
    8,
    {{0}, {8}, {0}, {0}},
    {{0}, {32}, {0}, {0}}},
   {SVGA3D_R10G10B10A2_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    4,
    4,
    {{10}, {10}, {10}, {2}},
    {{20}, {10}, {0}, {30}}},
   {SVGA3D_R10G10B10A2_UINT,
    SVGA3DBLOCKDESC_RGBA_UINT,
    {1, 1, 1},
    4,
    4,
    {{10}, {10}, {10}, {2}},
    {{20}, {10}, {0}, {30}}},
   {SVGA3D_R11G11B10_FLOAT,
    SVGA3DBLOCKDESC_RGB_FP,
    {1, 1, 1},
    4,
    4,
    {{10}, {11}, {11}, {0}},
    {{22}, {11}, {0}, {0}}},
   {SVGA3D_R8G8B8A8_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_R8G8B8A8_UNORM,
    SVGA3DBLOCKDESC_RGBA_UNORM,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_R8G8B8A8_UNORM_SRGB,
    SVGA3DBLOCKDESC_RGBA_UNORM_SRGB,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_R8G8B8A8_UINT,
    SVGA3DBLOCKDESC_RGBA_UINT,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_R8G8B8A8_SINT,
    SVGA3DBLOCKDESC_RGBA_SINT,
    {1, 1, 1},
    4,
    4,
    {{8}, {8}, {8}, {8}},
    {{16}, {8}, {0}, {24}}},
   {SVGA3D_R16G16_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_R16G16_UINT,
    SVGA3DBLOCKDESC_RG_UINT,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_R16G16_SINT,
    SVGA3DBLOCKDESC_RG_SINT,
    {1, 1, 1},
    4,
    4,
    {{0}, {16}, {16}, {0}},
    {{0}, {16}, {0}, {0}}},
   {SVGA3D_R32_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_D32_FLOAT,
    SVGA3DBLOCKDESC_DEPTH_FP,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R32_UINT,
    SVGA3DBLOCKDESC_R_UINT,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R32_SINT,
    SVGA3DBLOCKDESC_R_SINT,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {32}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R24G8_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    4,
    4,
    {{0}, {8}, {24}, {0}},
    {{0}, {24}, {0}, {0}}},
   {SVGA3D_D24_UNORM_S8_UINT,
    SVGA3DBLOCKDESC_DS_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {8}, {24}, {0}},
    {{0}, {24}, {0}, {0}}},
   {SVGA3D_R24_UNORM_X8,
    SVGA3DBLOCKDESC_R_UNORM,
    {1, 1, 1},
    4,
    4,
    {{0}, {0}, {24}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_X24_G8_UINT,
    SVGA3DBLOCKDESC_G_UINT,
    {1, 1, 1},
    4,
    4,
    {{0}, {8}, {0}, {0}},
    {{0}, {24}, {0}, {0}}},
   {SVGA3D_R8G8_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_R8G8_UNORM,
    SVGA3DBLOCKDESC_RG_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_R8G8_UINT,
    SVGA3DBLOCKDESC_RG_UINT,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_R8G8_SINT,
    SVGA3DBLOCKDESC_RG_SINT,
    {1, 1, 1},
    2,
    2,
    {{0}, {8}, {8}, {0}},
    {{0}, {8}, {0}, {0}}},
   {SVGA3D_R16_TYPELESS,
    SVGA3DBLOCKDESC_TYPELESS,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {16}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R16_UNORM,
    SVGA3DBLOCKDESC_R_UNORM,
    {1, 1, 1},
    2,
    2,
    {{0}, {0}, {16}, {0}},
    {{0}, {0}, {0}, {0}}},
   {SVGA3D_R16_UINT,
    SVGA3DBLOCKDESC_R_UINT,
    {1, 1, 1},
    2,